diff --git a/.actrc b/.actrc new file mode 100644 index 00000000000..e89c18787cd --- /dev/null +++ b/.actrc @@ -0,0 +1,2 @@ +# Needed for testing our workflows +-P ubuntu-latest=nektos/act-environments-ubuntu:18.04 diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md deleted file mode 100644 index e8548f92086..00000000000 --- a/.github/CONTRIBUTING.md +++ /dev/null @@ -1,1222 +0,0 @@ -# Contributing to Terraform - AWS Provider - -**First:** if you're unsure or afraid of _anything_, ask for help! You can -submit a work in progress (WIP) pull request, or file an issue with the parts -you know. We'll do our best to guide you in the right direction, and let you -know if there are guidelines we will need to follow. We want people to be able -to participate without fear of doing the wrong thing. - -Below are our expectations for contributors. Following these guidelines gives us -the best opportunity to work with you, by making sure we have the things we need -in order to make it happen. Doing your best to follow it will speed up our -ability to merge PRs and respond to issues. - - - -- [Issues](#issues) - - [Issue Reporting Checklists](#issue-reporting-checklists) - - [Bug Reports](#bug-reports) - - [Feature Requests](#feature-requests) - - [Questions](#questions) - - [Issue Lifecycle](#issue-lifecycle) -- [Pull Requests](#pull-requests) - - [Pull Request Lifecycle](#pull-request-lifecycle) - - [Checklists for Contribution](#checklists-for-contribution) - - [Documentation Update](#documentation-update) - - [Enhancement/Bugfix to a Resource](#enhancementbugfix-to-a-resource) - - [Adding Resource Import Support](#adding-resource-import-support) - - [Adding Resource Name Generation Support](#adding-resource-name-generation-support) - - [Adding Resource Tagging Support](#adding-resource-tagging-support) - - [New Resource](#new-resource) - - [New Service](#new-service) - - [New Region](#new-region) - - [Common Review Items](#common-review-items) - - [Go Coding Style](#go-coding-style) - - [Resource Contribution Guidelines](#resource-contribution-guidelines) - - [Acceptance Testing Guidelines](#acceptance-testing-guidelines) - - [Writing Acceptance Tests](#writing-acceptance-tests) - - [Acceptance Tests Often Cost Money to Run](#acceptance-tests-often-cost-money-to-run) - - [Running an Acceptance Test](#running-an-acceptance-test) - - [Writing an Acceptance Test](#writing-an-acceptance-test) - - [Writing and running Cross-Account Acceptance Tests](#writing-and-running-cross-account-acceptance-tests) - - [Writing and running Cross-Region Acceptance Tests](#writing-and-running-cross-region-acceptance-tests) - - - -## Issues - -### Issue Reporting Checklists - -We welcome issues of all kinds including feature requests, bug reports, and -general questions. Below you'll find checklists with guidelines for well-formed -issues of each type. - -#### [Bug Reports](https://github.com/terraform-providers/terraform-provider-aws/issues/new?template=Bug_Report.md) - - - [ ] __Test against latest release__: Make sure you test against the latest - released version. It is possible we already fixed the bug you're experiencing. - - - [ ] __Search for possible duplicate reports__: It's helpful to keep bug - reports consolidated to one thread, so do a quick search on existing bug - reports to check if anybody else has reported the same thing. You can [scope - searches by the label "bug"](https://github.com/terraform-providers/terraform-provider-aws/issues?q=is%3Aopen+is%3Aissue+label%3Abug) to help narrow things down. - - - [ ] __Include steps to reproduce__: Provide steps to reproduce the issue, - along with your `.tf` files, with secrets removed, so we can try to - reproduce it. Without this, it makes it much harder to fix the issue. - - - [ ] __For panics, include `crash.log`__: If you experienced a panic, please - create a [gist](https://gist.github.com) of the *entire* generated crash log - for us to look at. Double check no sensitive items were in the log. - -#### [Feature Requests](https://github.com/terraform-providers/terraform-provider-aws/issues/new?labels=enhancement&template=Feature_Request.md) - - - [ ] __Search for possible duplicate requests__: It's helpful to keep requests - consolidated to one thread, so do a quick search on existing requests to - check if anybody else has reported the same thing. You can [scope searches by - the label "enhancement"](https://github.com/terraform-providers/terraform-provider-aws/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement) to help narrow things down. - - - [ ] __Include a use case description__: In addition to describing the - behavior of the feature you'd like to see added, it's helpful to also lay - out the reason why the feature would be important and how it would benefit - Terraform users. - -#### [Questions](https://github.com/terraform-providers/terraform-provider-aws/issues/new?labels=question&template=Question.md) - - - [ ] __Search for answers in Terraform documentation__: We're happy to answer - questions in GitHub Issues, but it helps reduce issue churn and maintainer - workload if you work to [find answers to common questions in the - documentation](https://www.terraform.io/docs/providers/aws/index.html). Oftentimes Question issues result in documentation updates - to help future users, so if you don't find an answer, you can give us - pointers for where you'd expect to see it in the docs. - -### Issue Lifecycle - -1. The issue is reported. - -2. The issue is verified and categorized by a Terraform collaborator. - Categorization is done via GitHub labels. We generally use a two-label - system of (1) issue/PR type, and (2) section of the codebase. Type is - one of "bug", "enhancement", "documentation", or "question", and section - is usually the AWS service name. - -3. An initial triage process determines whether the issue is critical and must - be addressed immediately, or can be left open for community discussion. - -4. The issue is addressed in a pull request or commit. The issue number will be - referenced in the commit message so that the code that fixes it is clearly - linked. - -5. The issue is closed. Sometimes, valid issues will be closed because they are - tracked elsewhere or non-actionable. The issue is still indexed and - available for future viewers, or can be re-opened if necessary. - -## Pull Requests - -We appreciate direct contributions to the provider codebase. Here's what to -expect: - - * For pull requests that follow the guidelines, we will proceed to reviewing - and merging, following the provider team's review schedule. There may be some - internal or community discussion needed before we can complete this. - * Pull requests that don't follow the guidelines will be commented with what - they're missing. The person who submits the pull request or another community - member will need to address those requests before they move forward. - -### Pull Request Lifecycle - -1. [Fork the GitHub repository](https://help.github.com/en/articles/fork-a-repo), - modify the code, and [create a pull request](https://help.github.com/en/articles/creating-a-pull-request-from-a-fork). - You are welcome to submit your pull request for commentary or review before - it is fully completed by creating a [draft pull request](https://help.github.com/en/articles/about-pull-requests#draft-pull-requests) - or adding `[WIP]` to the beginning of the pull request title. - Please include specific questions or items you'd like feedback on. - -1. Once you believe your pull request is ready to be reviewed, ensure the - pull request is not a draft pull request by [marking it ready for review](https://help.github.com/en/articles/changing-the-stage-of-a-pull-request) - or removing `[WIP]` from the pull request title if necessary, and a - maintainer will review it. Follow [the checklists below](#checklists-for-contribution) - to help ensure that your contribution can be easily reviewed and potentially - merged. - -1. One of Terraform's provider team members will look over your contribution and - either approve it or provide comments letting you know if there is anything - left to do. We do our best to keep up with the volume of PRs waiting for - review, but it may take some time depending on the complexity of the work. - -1. Once all outstanding comments and checklist items have been addressed, your - contribution will be merged! Merged PRs will be included in the next - Terraform release. The provider team takes care of updating the CHANGELOG as - they merge. - -1. In some cases, we might decide that a PR should be closed without merging. - We'll make sure to provide clear reasoning when this happens. - -### Checklists for Contribution - -There are several different kinds of contribution, each of which has its own -standards for a speedy review. The following sections describe guidelines for -each type of contribution. - -#### Documentation Update - -The [Terraform AWS Provider's website source][website] is in this repository -along with the code and tests. Below are some common items that will get -flagged during documentation reviews: - -- [ ] __Reasoning for Change__: Documentation updates should include an explanation for why the update is needed. -- [ ] __Prefer AWS Documentation__: Documentation about AWS service features and valid argument values that are likely to update over time should link to AWS service user guides and API references where possible. -- [ ] __Large Example Configurations__: Example Terraform configuration that includes multiple resource definitions should be added to the repository `examples` directory instead of an individual resource documentation page. Each directory under `examples` should be self-contained to call `terraform apply` without special configuration. -- [ ] __Terraform Configuration Language Features__: Individual resource documentation pages and examples should refrain from highlighting particular Terraform configuration language syntax workarounds or features such as `variable`, `local`, `count`, and built-in functions. - -#### Enhancement/Bugfix to a Resource - -Working on existing resources is a great way to get started as a Terraform -contributor because you can work within existing code and tests to get a feel -for what to do. - -In addition to the below checklist, please see the [Common Review -Items](#common-review-items) sections for more specific coding and testing -guidelines. - - - [ ] __Acceptance test coverage of new behavior__: Existing resources each - have a set of [acceptance tests][acctests] covering their functionality. - These tests should exercise all the behavior of the resource. Whether you are - adding something or fixing a bug, the idea is to have an acceptance test that - fails if your code were to be removed. Sometimes it is sufficient to - "enhance" an existing test by adding an assertion or tweaking the config - that is used, but it's often better to add a new test. You can copy/paste an - existing test and follow the conventions you see there, modifying the test - to exercise the behavior of your code. - - [ ] __Documentation updates__: If your code makes any changes that need to - be documented, you should include those doc updates in the same PR. This - includes things like new resource attributes or changes in default values. - The [Terraform website][website] source is in this repo and includes - instructions for getting a local copy of the site up and running if you'd - like to preview your changes. - - [ ] __Well-formed Code__: Do your best to follow existing conventions you - see in the codebase, and ensure your code is formatted with `go fmt`. (The - Travis CI build will fail if `go fmt` has not been run on incoming code.) - The PR reviewers can help out on this front, and may provide comments with - suggestions on how to improve the code. - - [ ] __Vendor additions__: Create a separate PR if you are updating the vendor - folder. This is to avoid conflicts as the vendor versions tend to be fast- - moving targets. We will plan to merge the PR with this change first. - -#### Adding Resource Import Support - -Adding import support for Terraform resources will allow existing infrastructure to be managed within Terraform. This type of enhancement generally requires a small to moderate amount of code changes. - -Comprehensive code examples and information about resource import support can be found in the [Extending Terraform documentation](https://www.terraform.io/docs/extend/resources/import.html). - -In addition to the below checklist and the items noted in the Extending Terraform documentation, please see the [Common Review Items](#common-review-items) sections for more specific coding and testing guidelines. - -- [ ] _Resource Code Implementation_: In the resource code (e.g. `aws/resource_aws_service_thing.go`), implementation of `Importer` `State` function -- [ ] _Resource Acceptance Testing Implementation_: In the resource acceptance testing (e.g. `aws/resource_aws_service_thing_test.go`), implementation of `TestStep`s with `ImportState: true` -- [ ] _Resource Documentation Implementation_: In the resource documentation (e.g. `website/docs/r/service_thing.html.markdown`), addition of `Import` documentation section at the bottom of the page - -#### Adding Resource Name Generation Support - -Terraform AWS Provider resources can use shared logic to support and test name generation, where the operator can choose between an expected naming value, a generated naming value with a prefix, or a fully generated name. - -Implementing name generation support for Terraform AWS Provider resources requires the following, each with its own section below: - -- [ ] _Resource Name Generation Code Implementation_: In the resource code (e.g. `aws/resource_aws_service_thing.go`), implementation of `name_prefix` attribute, along with handling in `Create` function. -- [ ] _Resource Name Generation Testing Implementation_: In the resource acceptance testing (e.g. `aws/resource_aws_service_thing_test.go`), implementation of new acceptance test functions and configurations to exercise new naming logic. -- [ ] _Resource Name Generation Documentation Implementation_: In the resource documentation (e.g. `website/docs/r/service_thing.html.markdown`), addition of `name_prefix` argument and update of `name` argument description. - -##### Resource Name Generation Code Implementation - -- In the resource Go file (e.g. `aws/resource_aws_service_thing.go`), add the following Go import: `"github.com/terraform-providers/terraform-provider-aws/aws/internal/naming"` -- In the resource schema, add the new `name_prefix` attribute and adjust the `name` attribute to be `Optional`, `Computed`, and `ConflictsWith` the `name_prefix` attribute. Ensure to keep any existing schema fields on `name` such as `ValidateFunc`. e.g. - -```go -"name": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ForceNew: true, - ConflictsWith: []string{"name_prefix"}, -}, -"name_prefix": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ConflictsWith: []string{"name"}, -}, -``` - -- In the resource `Create` function, switch any calls from `d.Get("name").(string)` to instead use the `naming.Generate()` function, e.g. - -```go -name := naming.Generate(d.Get("name").(string), d.Get("name_prefix").(string)) - -// ... in AWS Go SDK Input types, etc. use aws.String(name) -``` - -##### Resource Name Generation Testing Implementation - -- In the resource testing (e.g. `aws/resource_aws_service_thing_test.go`), add the following Go import: `"github.com/terraform-providers/terraform-provider-aws/aws/internal/naming"` -- In the resource testing, implement two new tests named `_Name_Generated` and `_NamePrefix` with associated configurations, that verifies creating the resource without `name` and `name_prefix` arguments (for the former) and with only the `name_prefix` argument (for the latter). e.g. - -```go -func TestAccAWSServiceThing_Name_Generated(t *testing.T) { - var thing service.ServiceThing - resourceName := "aws_service_thing.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSServiceThingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSServiceThingConfigNameGenerated(), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSServiceThingExists(resourceName, &thing), - naming.TestCheckResourceAttrNameGenerated(resourceName, "name"), - ), - }, - // If the resource supports import: - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func TestAccAWSServiceThing_NamePrefix(t *testing.T) { - var thing service.ServiceThing - resourceName := "aws_service_thing.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSServiceThingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSServiceThingConfigNamePrefix("tf-acc-test-prefix-"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSServiceThingExists(resourceName, &thing), - naming.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), - ), - }, - // If the resource supports import: - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func testAccAWSServiceThingConfigNameGenerated() string { - return fmt.Sprintf(` -resource "aws_service_thing" "test" { - # ... other configuration ... -} -`) -} - -func testAccAWSServiceThingConfigNamePrefix(namePrefix string) string { - return fmt.Sprintf(` -resource "aws_service_thing" "test" { - # ... other configuration ... - - name_prefix = %[1]q -} -`, namePrefix) -} -``` - -##### Resource Code Generation Documentation Implementation - -- In the resource documentation (e.g. `website/docs/r/service_thing.html.markdown`), add the following to the arguments reference: - -```markdown -* `name_prefix` - (Optional) Creates a unique name beginning with the specified prefix. Conflicts with `name`. -``` - -- Adjust the existing `name` argument reference to ensure its denoted as `Optional`, includes a mention that it can be generated, and that it conflicts with `name_prefix`: - -```markdown -* `name` - (Optional) Name of the thing. If omitted, Terraform will assign a random, unique name. Conflicts with `name_prefix`. -``` - -#### Adding Resource Tagging Support - -AWS provides key-value metadata across many services and resources, which can be used for a variety of use cases including billing, ownership, and more. See the [AWS Tagging Strategy page](https://aws.amazon.com/answers/account-management/aws-tagging-strategies/) for more information about tagging at a high level. - -Implementing tagging support for Terraform AWS Provider resources requires the following, each with its own section below: - -- [ ] _Generated Service Tagging Code_: In the internal code generators (e.g. `aws/internal/keyvaluetags`), implementation and customization of how a service handles tagging, which is standardized for the resources. -- [ ] _Resource Tagging Code Implementation_: In the resource code (e.g. `aws/resource_aws_service_thing.go`), implementation of `tags` schema attribute, along with handling in `Create`, `Read`, and `Update` functions. -- [ ] _Resource Tagging Acceptance Testing Implementation_: In the resource acceptance testing (e.g. `aws/resource_aws_service_thing_test.go`), implementation of new acceptance test function and configurations to exercise new tagging logic. -- [ ] _Resource Tagging Documentation Implementation_: In the resource documentation (e.g. `website/docs/r/service_thing.html.markdown`), addition of `tags` argument - -See also a [full example pull request for implementing EKS tagging](https://github.com/terraform-providers/terraform-provider-aws/pull/10307). - -##### Adding Service to Tag Generating Code - -This step is only necessary for the first implementation and may have been previously completed. If so, move on to the next section. - -More details about this code generation, including fixes for potential error messages in this process, can be found in the [keyvaluetags documentation](../aws/internal/keyvaluetags/README.md). - -- Open the AWS Go SDK documentation for the service, e.g. for [`service/eks`](https://docs.aws.amazon.com/sdk-for-go/api/service/eks/). Note: there can be a delay between the AWS announcement and the updated AWS Go SDK documentation. -- Determine the "type" of tagging implementation. Some services will use a simple map style (`map[string]*string` in Go) while others will have a separate structure shape (`[]service.Tag` struct with `Key` and `Value` fields). - - - If the type is a map, add the AWS Go SDK service name (e.g. `eks`) to `mapServiceNames` in `aws/internal/keyvaluetags/generators/servicetags/main.go` - - Otherwise, if the type is a struct, add the AWS Go SDK service name (e.g. `eks`) to `sliceServiceNames` in `aws/internal/keyvaluetags/generators/servicetags/main.go`. If the struct name is not exactly `Tag`, it can be customized via the `ServiceTagType` function. If the struct key field is not exactly `Key`, it can be customized via the `ServiceTagTypeKeyField` function. If the struct value field is not exactly `Value`, it can be customized via the `ServiceTagTypeValueField` function. - -- Determine if the service API includes functionality for listing tags (usually a `ListTags` or `ListTagsForResource` API call) or updating tags (usually `TagResource` and `UntagResource` API calls). If so, add the AWS Go SDK service client information to `ServiceClientType` (along with the new required import) in `aws/internal/keyvaluetags/service_generation_customizations.go`, e.g. for EKS: - - ```go - case "eks": - funcType = reflect.TypeOf(eks.New) - ``` - - - If the service API includes functionality for listing tags, add the AWS Go SDK service name (e.g. `eks`) to `serviceNames` in `aws/internal/keyvaluetags/generators/listtags/main.go`. - - If the service API includes functionality for updating tags, add the AWS Go SDK service name (e.g. `eks`) to `serviceNames` in `aws/internal/keyvaluetags/generators/updatetags/main.go`. - -- Run `make gen` (`go generate ./...`) and ensure there are no errors via `make test` (`go test ./...`) - -##### Resource Tagging Code Implementation - -- In the resource Go file (e.g. `aws/resource_aws_eks_cluster.go`), add the following Go import: `"github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags"` -- In the resource schema, add `"tags": tagsSchema(),` -- If the API supports tagging on creation (the `Input` struct accepts a `Tags` field), in the resource `Create` function, implement the logic to convert the configuration tags into the service tags, e.g. with EKS Clusters: - - ```go - input := &eks.CreateClusterInput{ - /* ... other configuration ... */ - Tags: keyvaluetags.New(d.Get("tags").(map[string]interface{})).IgnoreAws().EksTags(), - } - ``` - - If the service API does not allow passing an empty list, the logic can be adjusted similar to: - - ```go - input := &eks.CreateClusterInput{ - /* ... other configuration ... */ - } - - if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { - input.Tags = keyvaluetags.New(v).IgnoreAws().EksTags() - } - ``` - -- Otherwise if the API does not support tagging on creation (the `Input` struct does not accept a `Tags` field), in the resource `Create` function, implement the logic to convert the configuration tags into the service API call to tag a resource, e.g. with ElasticSearch Domain: - - ```go - if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { - if err := keyvaluetags.ElasticsearchserviceUpdateTags(conn, d.Id(), nil, v); err != nil { - return fmt.Errorf("error adding Elasticsearch Cluster (%s) tags: %s", d.Id(), err) - } - } - ``` - -- Some EC2 resources (for example [`aws_ec2_fleet`](https://www.terraform.io/docs/providers/aws/r/ec2_fleet.html)) have a `TagsSpecification` field in the `InputStruct` instead of a `Tags` field. In these cases the `ec2TagSpecificationsFromMap()` helper function should be used, e.g.: - - ```go - input := &ec2.CreateFleetInput{ - /* ... other configuration ... */ - TagSpecifications: ec2TagSpecificationsFromMap(d.Get("tags").(map[string]interface{}), ec2.ResourceTypeFleet), - } - ``` - -- In the resource `Read` function, implement the logic to convert the service tags to save them into the Terraform state for drift detection, e.g. with EKS Clusters (which had the tags available in the DescribeCluster API call): - - ```go - // Typically declared near conn := /* ... */ - ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig - - if err := d.Set("tags", keyvaluetags.EksKeyValueTags(cluster.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %s", err) - } - ``` - - If the service API does not return the tags directly from reading the resource and requires a separate API call, its possible to use the `keyvaluetags` functionality like the following, e.g. with Athena Workgroups: - - ```go - // Typically declared near conn := /* ... */ - ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig - - tags, err := keyvaluetags.AthenaListTags(conn, arn.String()) - - if err != nil { - return fmt.Errorf("error listing tags for resource (%s): %s", arn, err) - } - - if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %s", err) - } - ``` - -- In the resource `Update` function (this may be the first functionality requiring the creation of the `Update` function), implement the logic to handle tagging updates, e.g. with EKS Clusters: - - ```go - if d.HasChange("tags") { - o, n := d.GetChange("tags") - if err := keyvaluetags.EksUpdateTags(conn, d.Get("arn").(string), o, n); err != nil { - return fmt.Errorf("error updating tags: %s", err) - } - } - ``` - -##### Resource Tagging Acceptance Testing Implementation - -- In the resource testing (e.g. `aws/resource_aws_eks_cluster_test.go`), verify that existing resources without tagging are unaffected and do not have tags saved into their Terraform state. This should be done in the `_basic` acceptance test by adding a line similar to `resource.TestCheckResourceAttr(resourceName, "tags.%s", "0"),` -- In the resource testing, implement a new test named `_Tags` with associated configurations, that verifies creating the resource with tags and updating tags. e.g. EKS Clusters: - - ```go - func TestAccAWSEksCluster_Tags(t *testing.T) { - var cluster1, cluster2, cluster3 eks.Cluster - rName := acctest.RandomWithPrefix("tf-acc-test") - resourceName := "aws_eks_cluster.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEks(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEksClusterDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSEksClusterConfigTags1(rName, "key1", "value1"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEksClusterExists(resourceName, &cluster1), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - { - Config: testAccAWSEksClusterConfigTags2(rName, "key1", "value1updated", "key2", "value2"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEksClusterExists(resourceName, &cluster2), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), - ), - }, - { - Config: testAccAWSEksClusterConfigTags1(rName, "key2", "value2"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEksClusterExists(resourceName, &cluster3), - resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), - ), - }, - }, - }) - } - - func testAccAWSEksClusterConfigTags1(rName, tagKey1, tagValue1 string) string { - return testAccAWSEksClusterConfig_Base(rName) + fmt.Sprintf(` - resource "aws_eks_cluster" "test" { - name = %[1]q - role_arn = "${aws_iam_role.test.arn}" - - tags = { - %[2]q = %[3]q - } - - vpc_config { - subnet_ids = ["${aws_subnet.test.*.id[0]}", "${aws_subnet.test.*.id[1]}"] - } - - depends_on = ["aws_iam_role_policy_attachment.test-AmazonEKSClusterPolicy", "aws_iam_role_policy_attachment.test-AmazonEKSServicePolicy"] - } - `, rName, tagKey1, tagValue1) - } - - func testAccAWSEksClusterConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return testAccAWSEksClusterConfig_Base(rName) + fmt.Sprintf(` - resource "aws_eks_cluster" "test" { - name = %[1]q - role_arn = "${aws_iam_role.test.arn}" - - tags = { - %[2]q = %[3]q - %[4]q = %[5]q - } - - vpc_config { - subnet_ids = ["${aws_subnet.test.*.id[0]}", "${aws_subnet.test.*.id[1]}"] - } - - depends_on = ["aws_iam_role_policy_attachment.test-AmazonEKSClusterPolicy", "aws_iam_role_policy_attachment.test-AmazonEKSServicePolicy"] - } - `, rName, tagKey1, tagValue1, tagKey2, tagValue2) - } - ``` - -- Verify all acceptance testing passes for the resource (e.g. `make testacc TESTARGS='-run=TestAccAWSEksCluster_'`) - -#### Resource Tagging Documentation Implementation - -- In the resource documentation (e.g. `website/docs/r/eks_cluster.html.markdown`), add the following to the arguments reference: - - ```markdown - * `tags` - (Optional) Key-value mapping of resource tags - ``` - -#### New Resource - -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. - -In addition to the below checklist, please see the [Common Review -Items](#common-review-items) sections for more specific coding and testing -guidelines. - - - [ ] __Minimal LOC__: It's difficult for both the reviewer and author to go - through long feedback cycles on a big PR with many resources. We ask 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 - approach these. - - [ ] __Resource Naming__: Resources should be named `aws__`, - using underscores (`_`) as the separator. Resources are namespaced with the - service name to allow easier searching of related resources, to align - the resource naming with the service for [Customizing Endpoints](https://www.terraform.io/docs/providers/aws/guides/custom-service-endpoints.html#available-endpoint-customizations), - and to prevent future conflicts with new AWS services/resources. - For reference: - - - `service` is the AWS short service name that matches the entry in - `endpointServiceNames` (created via the [New Service](#new-service) - section) - - `name` represents the conceptual infrastructure represented by the - create, read, update, and delete methods of the service API. It should - be a singular noun. For example, in an API that has methods such as - `CreateThing`, `DeleteThing`, `DescribeThing`, and `ModifyThing` the name - of the resource would end in `_thing`. - - - [ ] __Arguments_and_Attributes__: The HCL for arguments and attributes should - mimic the types and structs presented by the AWS API. API arguments should be - converted from `CamelCase` to `camel_case`. - - [ ] __Documentation__: Each resource gets a page in the Terraform - documentation. The [Terraform website][website] source is in this - repo and includes instructions for getting a local copy of the site up and - running if you'd like to preview your changes. For a resource, you'll want - to add a new file in the appropriate place and add a link to the sidebar for - that page. - - [ ] __Well-formed Code__: Do your best to follow existing conventions you - see in the codebase, and ensure your code is formatted with `go fmt`. (The - Travis CI build will fail if `go fmt` has not been run on incoming code.) - The PR reviewers can help out on this front, and may provide comments with - suggestions on how to improve the code. - - [ ] __Vendor updates__: Create a separate PR if you are adding to the vendor - folder. This is to avoid conflicts as the vendor versions tend to be fast- - moving targets. We will plan to merge the PR with this change first. - -#### New Service - -Implementing a new AWS service gives Terraform the ability to manage resources in -a whole new API. It's a larger undertaking, but brings major new functionality -into Terraform. - -- [ ] __Service Client__: Before new resources are submitted, we request - a separate pull request containing just the new AWS Go SDK service client. - Doing so will pull the AWS Go SDK service code into the project at the - current version. Since the AWS Go SDK is updated frequently, these pull - requests can easily have merge conflicts or be out of date. The maintainers - prioritize reviewing and merging these quickly to prevent those situations. - - To add the AWS Go SDK service client: - - - In `aws/provider.go` Add a new service entry to `endpointServiceNames`. - This service name should match the AWS Go SDK or AWS CLI service name. - - In `aws/config.go`: Add a new import for the AWS Go SDK code. e.g. - `github.com/aws/aws-sdk-go/service/quicksight` - - In `aws/config.go`: Add a new `{SERVICE}conn` field to the `AWSClient` - struct for the service client. The service name should match the name - in `endpointServiceNames`. e.g. `quicksightconn *quicksight.QuickSight` - - In `aws/config.go`: Create the new service client in the `{SERVICE}conn` - field in the `AWSClient` instantiation within `Client()`. e.g. - `quicksightconn: quicksight.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["quicksight"])})),` - - In `website/allowed-subcategories.txt`: Add a name acceptable for the documentation navigation. - - In `website/docs/guides/custom-service-endpoints.html.md`: Add the service - name in the list of customizable endpoints. - - In `infrastructure/repository/labels-service.tf`: Add the new service to create a repository label. - - In `.hashibot.hcl`: Add the new service to automated issue and pull request labeling. e.g. with the `quicksight` service - - ```hcl - behavior "regexp_issue_labeler_v2" "service_labels" { - # ... other configuration ... - - label_map = { - # ... other services ... - "service/quicksight" = [ - "aws_quicksight_", - ], - # ... other services ... - } - } - - behavior "pull_request_path_labeler" "service_labels" - # ... other configuration ... - - label_map = { - # ... other services ... - "service/quicksight" = [ - "**/*_quicksight_*", - "**/quicksight_*", - ], - # ... other services ... - } - } - ``` - - - Run the following then submit the pull request: - - ```sh - go test ./aws - go mod tidy - go mod vendor - ``` - -- [ ] __Initial Resource__: Some services can be big and it can be - difficult for both reviewer & author to go through long feedback cycles - on a big PR with many resources. Often feedback items in one resource - will also need to be applied in other resources. We prefer you to submit - the necessary minimum in a single PR, ideally **just the first resource** - of the service. - -The initial resource and changes afterwards should follow the other sections -of this guide as appropriate. - -#### New Region - -While region validation is automatically added with SDK updates, new regions -are generally limited in which services they support. Below are some -manually sourced values from documentation. - - - [ ] Check [Elastic Load Balancing endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/elb.html#elb_region) and add Route53 Hosted Zone ID if available to `aws/data_source_aws_elb_hosted_zone_id.go` - - [ ] Check [Amazon Simple Storage Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/s3.html#s3_region) and add Route53 Hosted Zone ID if available to `aws/hosted_zones.go` - - [ ] Check [CloudTrail Supported Regions docs](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-supported-regions.html#cloudtrail-supported-regions) and add AWS Account ID if available to `aws/data_source_aws_cloudtrail_service_account.go` - - [ ] Check [Elastic Load Balancing Access Logs docs](https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-access-logs.html#attach-bucket-policy) and add Elastic Load Balancing Account ID if available to `aws/data_source_aws_elb_service_account.go` - - [ ] Check [Redshift Database Audit Logging docs](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html#db-auditing-bucket-permissions) and add AWS Account ID if available to `aws/data_source_aws_redshift_service_account.go` - - [ ] Check [AWS Elastic Beanstalk endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/elasticbeanstalk.html#elasticbeanstalk_region) and add Route53 Hosted Zone ID if available to `aws/data_source_aws_elastic_beanstalk_hosted_zone.go` - -### Common Review Items - -The Terraform AWS Provider follows common practices to ensure consistent and -reliable implementations across all resources in the project. While there may be -older resource and testing code that predates these guidelines, new submissions -are generally expected to adhere to these items to maintain Terraform Provider -quality. For any guidelines listed, contributors are encouraged to ask any -questions and community reviewers are encouraged to provide review suggestions -based on these guidelines to speed up the review and merge process. - -#### Go Coding Style - -The following Go language resources provide common coding preferences that may be referenced during review, if not automatically handled by the project's linting tools. - -- [Effective Go](https://golang.org/doc/effective_go.html) -- [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments) - -#### Resource Contribution Guidelines - -The following resource checks need to be addressed before your contribution can be merged. The exclusion of any applicable check may result in a delayed time to merge. - -- [ ] __Passes Testing__: All code and documentation changes must pass unit testing, code linting, and website link testing. Resource code changes must pass all acceptance testing for the resource. -- [ ] __Avoids API Calls Across Account, Region, and Service Boundaries__: Resources should not implement cross-account, cross-region, or cross-service API calls. -- [ ] __Avoids Optional and Required for Non-Configurable Attributes__: Resource schema definitions for read-only attributes should not include `Optional: true` or `Required: true`. -- [ ] __Avoids resource.Retry() without resource.RetryableError()__: Resource logic should only implement [`resource.Retry()`](https://godoc.org/github.com/hashicorp/terraform/helper/resource#Retry) if there is a retryable condition (e.g. `return resource.RetryableError(err)`). -- [ ] __Avoids Resource Read Function in Data Source Read Function__: Data sources should fully implement their own resource `Read` functionality including duplicating `d.Set()` calls. -- [ ] __Avoids Reading Schema Structure in Resource Code__: The resource `Schema` should not be read in resource `Create`/`Read`/`Update`/`Delete` functions to perform looping or otherwise complex attribute logic. Use [`d.Get()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.Get) and [`d.Set()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.Set) directly with individual attributes instead. -- [ ] __Avoids ResourceData.GetOkExists()__: Resource logic should avoid using [`ResourceData.GetOkExists()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.GetOkExists) as its expected functionality is not guaranteed in all scenarios. -- [ ] __Implements Read After Create and Update__: Except where API eventual consistency prohibits immediate reading of resources or updated attributes, resource `Create` and `Update` functions should return the resource `Read` function. -- [ ] __Implements Immediate Resource ID Set During Create__: Immediately after calling the API creation function, the resource ID should be set with [`d.SetId()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.SetId) before other API operations or returning the `Read` function. -- [ ] __Implements Attribute Refreshes During Read__: All attributes available in the API should have [`d.Set()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.Set) called their values in the Terraform state during the `Read` function. -- [ ] __Implements Error Checks with Non-Primative Attribute Refreshes__: When using [`d.Set()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.Set) with non-primative types (`schema.TypeList`, `schema.TypeSet`, or `schema.TypeMap`), perform error checking to [prevent issues where the code is not properly able to refresh the Terraform state](https://www.terraform.io/docs/extend/best-practices/detecting-drift.html#error-checking-aggregate-types). -- [ ] __Implements Import Acceptance Testing and Documentation__: Support for resource import (`Importer` in resource schema) must include `ImportState` acceptance testing (see also the [Acceptance Testing Guidelines](#acceptance-testing-guidelines) below) and `## Import` section in resource documentation. -- [ ] __Implements Customizable Timeouts Documentation__: Support for customizable timeouts (`Timeouts` in resource schema) must include `## Timeouts` section in resource documentation. -- [ ] __Implements State Migration When Adding New Virtual Attribute__: For new "virtual" attributes (those only in Terraform and not in the API), the schema should implement [State Migration](https://www.terraform.io/docs/extend/resources.html#state-migrations) to prevent differences for existing configurations that upgrade. -- [ ] __Uses AWS Go SDK Constants__: Many AWS services provide string constants for value enumerations, error codes, and status types. See also the "Constants" sections under each of the service packages in the [AWS Go SDK documentation](https://docs.aws.amazon.com/sdk-for-go/api/). -- [ ] __Uses AWS Go SDK Pointer Conversion Functions__: Many APIs return pointer types and these functions return the zero value for the type if the pointer is `nil`. This prevents potential panics from unchecked `*` pointer dereferences and can eliminate boilerplate `nil` checking in many cases. See also the [`aws` package in the AWS Go SDK documentation](https://docs.aws.amazon.com/sdk-for-go/api/aws/). -- [ ] __Uses AWS Go SDK Types__: Use available SDK structs instead of implementing custom types with indirection. -- [ ] __Uses TypeList and MaxItems: 1__: Configuration block attributes (e.g. `Type: schema.TypeList` or `Type: schema.TypeSet` with `Elem: &schema.Resource{...}`) that can only have one block should use `Type: schema.TypeList` and `MaxItems: 1` in the schema definition. -- [ ] __Uses Existing Validation Functions__: Schema definitions including `ValidateFunc` for attribute validation should use available [Terraform `helper/validation` package](https://godoc.org/github.com/hashicorp/terraform/helper/validation) functions. `All()`/`Any()` can be used for combining multiple validation function behaviors. -- [ ] __Uses isResourceTimeoutError() with resource.Retry()__: Resource logic implementing [`resource.Retry()`](https://godoc.org/github.com/hashicorp/terraform/helper/resource#Retry) should error check with `isResourceTimeoutError(err error)` and potentially unset the error before returning the error. For example: - - ```go - var output *kms.CreateKeyOutput - err := resource.Retry(1*time.Minute, func() *resource.RetryError { - var err error - - output, err = conn.CreateKey(input) - - /* ... */ - - return nil - }) - - if isResourceTimeoutError(err) { - output, err = conn.CreateKey(input) - } - - if err != nil { - return fmt.Errorf("error creating KMS External Key: %s", err) - } - ``` - -- [ ] __Uses resource.NotFoundError__: Custom errors for missing resources should use [`resource.NotFoundError`](https://godoc.org/github.com/hashicorp/terraform/helper/resource#NotFoundError). -- [ ] __Uses resource.UniqueId()__: API fields for concurrency protection such as `CallerReference` and `IdempotencyToken` should use [`resource.UniqueId()`](https://godoc.org/github.com/hashicorp/terraform/helper/resource#UniqueId). The implementation includes a monotonic counter which is safer for concurrent operations than solutions such as `time.Now()`. -- [ ] __Skips Exists Function__: Implementing a resource `Exists` function is extraneous as it often duplicates resource `Read` functionality. Ensure `d.SetId("")` is used to appropriately trigger resource recreation in the resource `Read` function. -- [ ] __Skips id Attribute__: The `id` attribute is implicit for all Terraform resources and does not need to be defined in the schema. - -The below are style-based items that _may_ be noted during review and are recommended for simplicity, consistency, and quality assurance: - -- [ ] __Avoids CustomizeDiff__: Usage of `CustomizeDiff` is generally discouraged. -- [ ] __Implements Error Message Context__: Returning errors from resource `Create`, `Read`, `Update`, and `Delete` functions should include additional messaging about the location or cause of the error for operators and code maintainers by wrapping with [`fmt.Errorf()`](https://godoc.org/golang.org/x/exp/errors/fmt#Errorf). - - An example `Delete` API error: `return fmt.Errorf("error deleting {SERVICE} {THING} (%s): %s", d.Id(), err)` - - An example `d.Set()` error: `return fmt.Errorf("error setting {ATTRIBUTE}: %s", err)` -- [ ] __Implements arn Attribute__: APIs that return an Amazon Resource Name (ARN), should implement `arn` as an attribute. -- [ ] __Implements Warning Logging With Resource State Removal__: If a resource is removed outside of Terraform (e.g. via different tool, API, or web UI), `d.SetId("")` and `return nil` can be used in the resource `Read` function to trigger resource recreation. When this occurs, a warning log message should be printed beforehand: `log.Printf("[WARN] {SERVICE} {THING} (%s) not found, removing from state", d.Id())` -- [ ] __Uses isAWSErr() with AWS Go SDK Error Objects__: Use the available `isAWSErr(err error, code string, message string)` helper function instead of the `awserr` package to compare error code and message contents. -- [ ] __Uses %s fmt Verb with AWS Go SDK Objects__: AWS Go SDK objects implement `String()` so using the `%v`, `%#v`, or `%+v` fmt verbs with the object are extraneous or provide unhelpful detail. -- [ ] __Uses Elem with TypeMap__: While provider schema validation does not error when the `Elem` configuration is not present with `Type: schema.TypeMap` attributes, including the explicit `Elem: &schema.Schema{Type: schema.TypeString}` is recommended. -- [ ] __Uses American English for Attribute Naming__: For any ambiguity with attribute naming, prefer American English over British English. e.g. `color` instead of `colour`. -- [ ] __Skips Timestamp Attributes__: Generally, creation and modification dates from the API should be omitted from the schema. -- [ ] __Skips Error() Call with AWS Go SDK Error Objects__: Error objects do not need to have `Error()` called. - -#### Acceptance Testing Guidelines - -The below are required items that will be noted during submission review and prevent immediate merging: - -- [ ] __Implements CheckDestroy__: Resource testing should include a `CheckDestroy` function (typically named `testAccCheckAws{SERVICE}{RESOURCE}Destroy`) that calls the API to verify that the Terraform resource has been deleted or disassociated as appropriate. More information about `CheckDestroy` functions can be found in the [Extending Terraform TestCase documentation](https://www.terraform.io/docs/extend/testing/acceptance-tests/testcase.html#checkdestroy). -- [ ] __Implements Exists Check Function__: Resource testing should include a `TestCheckFunc` function (typically named `testAccCheckAws{SERVICE}{RESOURCE}Exists`) that calls the API to verify that the Terraform resource has been created or associated as appropriate. Preferably, this function will also accept a pointer to an API object representing the Terraform resource from the API response that can be set for potential usage in later `TestCheckFunc`. More information about these functions can be found in the [Extending Terraform Custom Check Functions documentation](https://www.terraform.io/docs/extend/testing/acceptance-tests/testcase.html#checkdestroy). -- [ ] __Excludes Provider Declarations__: Test configurations should not include `provider "aws" {...}` declarations. If necessary, only the provider declarations in `provider_test.go` should be used for multiple account/region or otherwise specialized testing. -- [ ] __Passes in us-west-2 Region__: Tests default to running in `us-west-2` and at a minimum should pass in that region or include necessary `PreCheck` functions to skip the test when ran outside an expected environment. -- [ ] __Uses resource.ParallelTest__: Tests should utilize [`resource.ParallelTest()`](https://godoc.org/github.com/hashicorp/terraform/helper/resource#ParallelTest) instead of [`resource.Test()`](https://godoc.org/github.com/hashicorp/terraform/helper/resource#Test) except where serialized testing is absolutely required. -- [ ] __Uses fmt.Sprintf()__: Test configurations preferably should to be separated into their own functions (typically named `testAccAws{SERVICE}{RESOURCE}Config{PURPOSE}`) that call [`fmt.Sprintf()`](https://golang.org/pkg/fmt/#Sprintf) for variable injection or a string `const` for completely static configurations. Test configurations should avoid `var` or other variable injection functionality such as [`text/template`](https://golang.org/pkg/text/template/). -- [ ] __Uses Randomized Infrastructure Naming__: Test configurations that utilize resources where a unique name is required should generate a random name. Typically this is created via `rName := acctest.RandomWithPrefix("tf-acc-test")` in the acceptance test function before generating the configuration. - -For resources that support import, the additional item below is required that will be noted during submission review and prevent immediate merging: - -- [ ] __Implements ImportState Testing__: Tests should include an additional `TestStep` configuration that verifies resource import via `ImportState: true` and `ImportStateVerify: true`. This `TestStep` should be added to all possible tests for the resource to ensure that all infrastructure configurations are properly imported into Terraform. - -The below are style-based items that _may_ be noted during review and are recommended for simplicity, consistency, and quality assurance: - -- [ ] __Uses Builtin Check Functions__: Tests should utilize already available check functions, e.g. `resource.TestCheckResourceAttr()`, to verify values in the Terraform state over creating custom `TestCheckFunc`. More information about these functions can be found in the [Extending Terraform Builtin Check Functions documentation](https://www.terraform.io/docs/extend/testing/acceptance-tests/teststep.html#builtin-check-functions). -- [ ] __Uses TestCheckResoureAttrPair() for Data Sources__: Tests should utilize [`resource.TestCheckResourceAttrPair()`](https://godoc.org/github.com/hashicorp/terraform/helper/resource#TestCheckResourceAttrPair) to verify values in the Terraform state for data sources attributes to compare them with their expected resource attributes. -- [ ] __Excludes Timeouts Configurations__: Test configurations should not include `timeouts {...}` configuration blocks except for explicit testing of customizable timeouts (typically very short timeouts with `ExpectError`). -- [ ] __Implements Default and Zero Value Validation__: The basic test for a resource (typically named `TestAccAws{SERVICE}{RESOURCE}_basic`) should utilize available check functions, e.g. `resource.TestCheckResourceAttr()`, to verify default and zero values in the Terraform state for all attributes. Empty/missing configuration blocks can be verified with `resource.TestCheckResourceAttr(resourceName, "{ATTRIBUTE}.#", "0")` and empty maps with `resource.TestCheckResourceAttr(resourceName, "{ATTRIBUTE}.%", "0")` - -The below are location-based items that _may_ be noted during review and are recommended for consistency with testing flexibility. Resource testing is expected to pass across multiple AWS environments supported by the Terraform AWS Provider (e.g. AWS Standard and AWS GovCloud (US)). Contributors are not expected or required to perform testing outside of AWS Standard, e.g. running only in the `us-west-2` region is perfectly acceptable, however these are provided for reference: - -- [ ] __Uses aws_ami Data Source__: Any hardcoded AMI ID configuration, e.g. `ami-12345678`, should be replaced with the [`aws_ami` data source](https://www.terraform.io/docs/providers/aws/d/ami.html) pointing to an Amazon Linux image. A common pattern is a configuration like the below, which will likely be moved into a common configuration function in the future: - - ```hcl - data "aws_ami" "amzn-ami-minimal-hvm-ebs" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-minimal-hvm-*"] - } - filter { - name = "root-device-type" - values = ["ebs"] - } - } - ``` - -- [ ] __Uses aws_availability_zones Data Source__: Any hardcoded AWS Availability Zone configuration, e.g. `us-west-2a`, should be replaced with the [`aws_availability_zones` data source](https://www.terraform.io/docs/providers/aws/d/availability_zones.html). A common pattern is declaring `data "aws_availability_zones" "available" {...}` and referencing it via `data.aws_availability_zones.available.names[0]` or `data.aws_availability_zones.available.names[count.index]` in resources utilizing `count`. - - ```hcl - data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } - } - ``` - -- [ ] __Uses aws_region Data Source__: Any hardcoded AWS Region configuration, e.g. `us-west-2`, should be replaced with the [`aws_region` data source](https://www.terraform.io/docs/providers/aws/d/region.html). A common pattern is declaring `data "aws_region" "current" {}` and referencing it via `data.aws_region.current.name` -- [ ] __Uses aws_partition Data Source__: Any hardcoded AWS Partition configuration, e.g. the `aws` in a `arn:aws:SERVICE:REGION:ACCOUNT:RESOURCE` ARN, should be replaced with the [`aws_partition` data source](https://www.terraform.io/docs/providers/aws/d/partition.html). A common pattern is declaring `data "aws_partition" "current" {}` and referencing it via `data.aws_partition.current.partition` -- [ ] __Uses Builtin ARN Check Functions__: Tests should utilize available ARN check functions, e.g. `testAccMatchResourceAttrRegionalARN()`, to validate ARN attribute values in the Terraform state over `resource.TestCheckResourceAttrSet()` and `resource.TestMatchResourceAttr()` -- [ ] __Uses testAccCheckResourceAttrAccountID()__: Tests should utilize the available AWS Account ID check function, `testAccCheckResourceAttrAccountID()` to validate account ID attribute values in the Terraform state over `resource.TestCheckResourceAttrSet()` and `resource.TestMatchResourceAttr()` - -### Writing Acceptance Tests - -Terraform includes an acceptance test harness that does most of the repetitive -work involved in testing a resource. For additional information about testing -Terraform Providers, see the [Extending Terraform documentation](https://www.terraform.io/docs/extend/testing/index.html). - -#### Acceptance Tests Often Cost Money to Run - -Because acceptance tests create real resources, they often cost money to run. -Because the resources only exist for a short period of time, the total amount -of money required is usually a relatively small. Nevertheless, we don't want -financial limitations to be a barrier to contribution, so if you are unable to -pay to run acceptance tests for your contribution, mention this in your -pull request. We will happily accept "best effort" implementations of -acceptance tests and run them for you on our side. This might mean that your PR -takes a bit longer to merge, but it most definitely is not a blocker for -contributions. - -#### Running an Acceptance Test - -Acceptance tests can be run using the `testacc` target in the Terraform -`Makefile`. The individual tests to run can be controlled using a regular -expression. Prior to running the tests provider configuration details such as -access keys must be made available as environment variables. - -For example, to run an acceptance test against the Amazon Web Services -provider, the following environment variables must be set: - -```sh -# Using a profile -export AWS_PROFILE=... -# Otherwise -export AWS_ACCESS_KEY_ID=... -export AWS_SECRET_ACCESS_KEY=... -export AWS_DEFAULT_REGION=... -``` - -Please note that the default region for the testing is `us-west-2` and must be -overriden via the `AWS_DEFAULT_REGION` environment variable, if necessary. This -is especially important for testing AWS GovCloud (US), which requires: - -```sh -export AWS_DEFAULT_REGION=us-gov-west-1 -``` - -Tests can then be run by specifying the target provider and a regular -expression defining the tests to run: - -```sh -$ make testacc TEST=./aws TESTARGS='-run=TestAccAWSCloudWatchDashboard_update' -==> Checking that code complies with gofmt requirements... -TF_ACC=1 go test ./aws -v -run=TestAccAWSCloudWatchDashboard_update -timeout 120m -=== RUN TestAccAWSCloudWatchDashboard_update ---- PASS: TestAccAWSCloudWatchDashboard_update (26.56s) -PASS -ok github.com/terraform-providers/terraform-provider-aws/aws 26.607s -``` - -Entire resource test suites can be targeted by using the naming convention to -write the regular expression. For example, to run all tests of the -`aws_cloudwatch_dashboard` resource rather than just the update test, you can start -testing like this: - -```sh -$ make testacc TEST=./aws TESTARGS='-run=TestAccAWSCloudWatchDashboard' -==> Checking that code complies with gofmt requirements... -TF_ACC=1 go test ./aws -v -run=TestAccAWSCloudWatchDashboard -timeout 120m -=== RUN TestAccAWSCloudWatchDashboard_importBasic ---- PASS: TestAccAWSCloudWatchDashboard_importBasic (15.06s) -=== RUN TestAccAWSCloudWatchDashboard_basic ---- PASS: TestAccAWSCloudWatchDashboard_basic (12.70s) -=== RUN TestAccAWSCloudWatchDashboard_update ---- PASS: TestAccAWSCloudWatchDashboard_update (27.81s) -PASS -ok github.com/terraform-providers/terraform-provider-aws/aws 55.619s -``` - -Please Note: On macOS 10.14 and later (and some Linux distributions), the default user open file limit is 256. This may cause unexpected issues when running the acceptance testing since this can prevent various operations from occurring such as opening network connections to AWS. To view this limit, the `ulimit -n` command can be run. To update this limit, run `ulimit -n 1024` (or higher). - -#### Writing an Acceptance Test - -Terraform has a framework for writing acceptance tests which minimises the -amount of boilerplate code necessary to use common testing patterns. The entry -point to the framework is the `resource.ParallelTest()` function. - -Tests are divided into `TestStep`s. Each `TestStep` proceeds by applying some -Terraform configuration using the provider under test, and then verifying that -results are as expected by making assertions using the provider API. It is -common for a single test function to exercise both the creation of and updates -to a single resource. Most tests follow a similar structure. - -1. Pre-flight checks are made to ensure that sufficient provider configuration - is available to be able to proceed - for example in an acceptance test - targeting AWS, `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` must be set prior - to running acceptance tests. This is common to all tests exercising a single - provider. - -Each `TestStep` is defined in the call to `resource.ParallelTest()`. Most assertion -functions are defined out of band with the tests. This keeps the tests -readable, and allows reuse of assertion functions across different tests of the -same type of resource. The definition of a complete test looks like this: - -```go -func TestAccAWSCloudWatchDashboard_basic(t *testing.T) { - var dashboard cloudwatch.GetDashboardOutput - rInt := acctest.RandInt() - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCloudWatchDashboardDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSCloudWatchDashboardConfig(rInt), - Check: resource.ComposeTestCheckFunc( - testAccCheckCloudWatchDashboardExists("aws_cloudwatch_dashboard.foobar", &dashboard), - resource.TestCheckResourceAttr("aws_cloudwatch_dashboard.foobar", "dashboard_name", testAccAWSCloudWatchDashboardName(rInt)), - ), - }, - }, - }) -} -``` - -When executing the test, the following steps are taken for each `TestStep`: - -1. The Terraform configuration required for the test is applied. This is - responsible for configuring the resource under test, and any dependencies it - may have. For example, to test the `aws_cloudwatch_dashboard` resource, a valid configuration with the requisite fields is required. This results in configuration which looks like this: - - ```hcl - resource "aws_cloudwatch_dashboard" "foobar" { - dashboard_name = "terraform-test-dashboard-%d" - dashboard_body = < -### Terraform Version +### Terraform CLI and Terraform AWS Provider Version diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 36230fdbc0b..44dda1d6918 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,8 @@ blank_issues_enabled: false contact_links: + - name: Terraform AWS Provider Roadmap + url: https://github.com/terraform-providers/terraform-provider-aws/blob/master/ROADMAP.md + about: View the Roadmap for the upcoming work planned on the AWS provider. - name: Terraform AWS Provider Questions url: https://discuss.hashicorp.com/c/terraform-providers/tf-aws about: GitHub issues in this repository are only intended for bug reports and feature requests. Other issues will be closed. Please ask and answer questions through the Terraform AWS Provider Community Forum. diff --git a/.github/MAINTAINING.md b/.github/MAINTAINING.md deleted file mode 100644 index be32dee870d..00000000000 --- a/.github/MAINTAINING.md +++ /dev/null @@ -1,310 +0,0 @@ -# Maintaining the Terraform AWS Provider - - - -- [Pull Requests](#pull-requests) - - [Pull Request Review Process](#pull-request-review-process) - - [Dependency Updates](#dependency-updates) - - [AWS Go SDK Updates](#aws-go-sdk-updates) - - [golangci-lint Updates](#golangci-lint-updates) - - [Terraform Plugin SDK Updates](#terraform-plugin-sdk-updates) - - [tfproviderdocs Updates](#tfproviderdocs-updates) - - [tfproviderlint Updates](#tfproviderlint-updates) - - [yaml.v2 Updates](#yaml-v2-updates) - - [Pull Request Merge Process](#pull-request-merge-process) - - [Pull Request Types to CHANGELOG](#pull-request-types-to-changelog) -- [Release Process](#release-process) - - - -## Pull Requests - -### Pull Request Review Process - -Notes for each type of pull request are (or will be) available in subsections below. - -- If you plan to be responsible for the pull request through the merge/closure process, assign it to yourself -- Add `bug`, `enhancement`, `new-data-source`, `new-resource`, or `technical-debt` labels to match expectations from change -- Perform a quick scan of open issues and ensure they are referenced in the pull request description (e.g. `Closes #1234`, `Relates #5678`). Edit the description yourself and mention this to the author: - -```markdown -This pull request appears to be related to/solve #1234, so I have edited the pull request description to denote the issue reference. -``` - -- Review the contents of the pull request and ensure the change follows the relevant section of the [Contributing Guide](https://github.com/terraform-providers/terraform-provider-aws/blob/master/.github/CONTRIBUTING.md#checklists-for-contribution) -- If the change is not acceptable, leave a long form comment about the reasoning and close the pull request -- If the change is acceptable with modifications, leave a pull request review marked using the `Request Changes` option (for maintainer pull requests with minor modification requests, giving feedback with the `Approve` option is recommended so they do not need to wait for another round of review) -- If the author is unresponsive for changes (by default we give two weeks), determine importance and level of effort to finish the pull request yourself including their commits or close the pull request -- Run relevant acceptance testing ([locally](https://github.com/terraform-providers/terraform-provider-aws/blob/master/.github/CONTRIBUTING.md#running-an-acceptance-test) or in TeamCity) against AWS Commercial and AWS GovCloud (US) to ensure no new failures are being introduced -- Approve the pull request with a comment outlining what steps you took that ensure the change is acceptable, e.g. acceptance testing output - -``````markdown -Looks good, thanks @username! :rocket: - -Output from acceptance testing in AWS Commercial: - -``` ---- PASS: TestAcc... ---- PASS: TestAcc... -``` - -Output from acceptance testing in AWS GovCloud (US): - -``` ---- PASS: TestAcc... ---- PASS: TestAcc... -``` -`````` - -#### Dependency Updates - -##### AWS Go SDK Updates - -Almost exclusively, `github.com/aws/aws-sdk-go` updates are additive in nature. It is generally safe to only scan through them before approving and merging. If you have any concerns about any of the service client updates such as suspicious code removals in the update, or deprecations introduced, run the acceptance testing for potentially affected resources before merging. - -Authentication changes: - -Occassionally, there will be changes listed in the authentication pieces of the AWS Go SDK codebase, e.g. changes to `aws/session`. The AWS Go SDK `CHANGELOG` should include a relevant description of these changes under a heading such as `SDK Enhancements` or `SDK Bug Fixes`. If they seem worthy of a callout in the Terraform AWS Provider `CHANGELOG`, then upon merging we should include a similar message prefixed with the `provider` subsystem, e.g. `* provider: ...`. - -Additionally, if a `CHANGELOG` addition seemed appropriate, this dependency and version should also be updated in the Terraform S3 Backend, which currently lives in Terraform Core. An example of this can be found with https://github.com/terraform-providers/terraform-provider-aws/pull/9305 and https://github.com/hashicorp/terraform/pull/22055. - -CloudFront changes: - -CloudFront service client updates have previously caused an issue when a new field introduced in the SDK was not included with Terraform and caused all requests to error (https://github.com/terraform-providers/terraform-provider-aws/issues/4091). As a precaution, if you see CloudFront updates, run all the CloudFront resource acceptance testing before merging (`TestAccAWSCloudFront`). - -New Regions: - -These are added to the AWS Go SDK `aws/endpoints/defaults.go` file and generally noted in the AWS Go SDK `CHANGELOG` as `aws/endpoints: Updated Regions`. Since April 2019, new regions added to AWS now require being explicitly enabled before they can be used. Examples of this can be found when `me-south-1` was announced: - -- [Terraform AWS Provider issue](https://github.com/terraform-providers/terraform-provider-aws/issues/9545) -- [Terraform AWS Provider AWS Go SDK update pull request](https://github.com/terraform-providers/terraform-provider-aws/pull/9538) -- [Terraform AWS Provider data source update pull request](https://github.com/terraform-providers/terraform-provider-aws/pull/9547) -- [Terraform S3 Backend issue](https://github.com/hashicorp/terraform/issues/22254) -- [Terraform S3 Backend pull request](https://github.com/hashicorp/terraform/pull/22253) - -Typically our process for new regions is as follows: - -- Create new (if not existing) Terraform AWS Provider issue: Support Automatic Region Validation for `XX-XXXXX-#` (Location) -- Create new (if not existing) Terraform S3 Backend issue: backend/s3: Support Automatic Region Validation for `XX-XXXXX-#` (Location) -- [Enable the new region in an AWS testing account](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable) and verify AWS Go SDK update works with the new region with `export AWS_DEFAULT_REGION=XX-XXXXX-#` with the new region and run the `TestAccDataSourceAwsRegion_` acceptance testing or by building the provider and testing a configuration like the following: - -```hcl -provider "aws" { - region = "me-south-1" -} - -data "aws_region" "current" {} - -output "region" { - value = data.aws_region.current.name -} -``` - -- Merge AWS Go SDK update in Terraform AWS Provider and close issue with the following information: - -``````markdown -Support for automatic validation of this new region has been merged and will release with version of the Terraform AWS Provider, later this week. - ---- - -Please note that this new region requires [a manual process to enable](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable). Once enabled in the console, it takes a few minutes for everything to work properly. - -If the region is not enabled properly, or the enablement process is still in progress, you can receive errors like these: - -```console -$ terraform apply - -Error: error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid. - status code: 403, request id: 142f947b-b2c3-11e9-9959-c11ab17bcc63 - - on main.tf line 1, in provider "aws": - 1: provider "aws" { -``` - ---- - -To use this new region before support has been added to Terraform AWS Provider version in use, you must disable the provider's automatic region validation via: - -```hcl -provider "aws" { - # ... potentially other configuration ... - - region = "me-south-1" - skip_region_validation = true -} -``` -`````` - -- Update the Terraform AWS Provider `CHANGELOG` with the following: - -```markdown -NOTES: - -* provider: Region validation now automatically supports the new `XX-XXXXX-#` (Location) region. For AWS operations to work in the new region, the region must be explicitly enabled as outlined in the [AWS Documentation](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable). When the region is not enabled, the Terraform AWS Provider will return errors during credential validation (e.g. `error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid`) or AWS operations will throw their own errors (e.g. `data.aws_availability_zones.current: Error fetching Availability Zones: AuthFailure: AWS was not able to validate the provided access credentials`). [GH-####] - -ENHANCEMENTS: - -* provider: Support automatic region validation for `XX-XXXXX-#` [GH-####] -``` - -- Follow the [Contributing Guide](https://github.com/terraform-providers/terraform-provider-aws/blob/master/.github/CONTRIBUTING.md#new-region) to submit updates for various data sources to support the new region -- Submit the dependency update to the Terraform S3 Backend by running the following: - -```shell -go get github.com/aws/aws-sdk-go@v#.#.# -go mod tidy -go mod vendor -``` - -- Create a S3 Bucket in the new region and verify AWS Go SDK update works with new region by building the Terraform S3 Backend and testing a configuration like the following: - -```hcl -terraform { - backend "s3" { - bucket = "XXX" - key = "test" - region = "me-south-1" - } -} - -output "test" { - value = timestamp() -} -``` - -- After approval, merge AWS Go SDK update in Terraform S3 Backend and close issue with the following information: - -``````markdown -Support for automatic validation of this new region has been merged and will release with the next version of the Terraform. - -This was verified on a build of Terraform with the update: - -```hcl -terraform { - backend "s3" { - bucket = "XXX" - key = "test" - region = "me-south-1" - } -} - -output "test" { - value = timestamp() -} -``` - -Outputs: - -```console -$ terraform init -... -Terraform has been successfully initialized! -``` - ---- - -Please note that this new region requires [a manual process to enable](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable). Once enabled in the console, it takes a few minutes for everything to work properly. - -If the region is not enabled properly, or the enablement process is still in progress, you can receive errors like these: - -```console -$ terraform init - -Initializing the backend... - -Error: error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid. -``` - ---- - -To use this new region before this update is released, you must disable the Terraform S3 Backend's automatic region validation via: - -```hcl -terraform { - # ... potentially other configuration ... - - backend "s3" { - # ... other configuration ... - - region = "me-south-1" - skip_region_validation = true - } -} -``` -`````` - -- Update the Terraform S3 Backend `CHANGELOG` with the following: - -```markdown -NOTES: - -* backend/s3: Region validation now automatically supports the new `XX-XXXXX-#` (Location) region. For AWS operations to work in the new region, the region must be explicitly enabled as outlined in the [AWS Documentation](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable). When the region is not enabled, the Terraform S3 Backend will return errors during credential validation (e.g. `error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid`). [GH-####] - -ENHANCEMENTS: - -* backend/s3: Support automatic region validation for `XX-XXXXX-#` [GH-####] -``` - -##### golangci-lint Updates - -Merge if CI passes. - -##### Terraform Plugin SDK Updates - -Except for trivial changes, run the full acceptance testing suite against the pull request and verify there are no new or unexpected failures. - -##### tfproviderdocs Updates - -Merge if CI passes. - -##### tfproviderlint Updates - -Merge if CI passes. - -##### yaml.v2 Updates - -Run the acceptance testing pattern, `TestAccAWSCloudFormationStack(_dataSource)?_yaml`, and merge if passing. - -### Pull Request Merge Process - -- Add this pull request to the upcoming release milestone -- Add any linked issues that will be closed by the pull request to the same upcoming release milestone -- Merge the pull request -- Delete the branch (if the branch is on this repository) -- Determine if the pull request should have a CHANGELOG entry by reviewing the [Pull Request Types to CHANGELOG section](#pull-request-types-to-changelog). If so, update the repository `CHANGELOG.md` by directly committing to the `master` branch (e.g. editing the file in the GitHub web interface). See also the [Extending Terraform documentation](https://www.terraform.io/docs/extend/best-practices/versioning.html) for more information about the expected CHANGELOG format. -- Leave a comment on any issues closed by the pull request noting that it has been merged and when to expect the release containing it, e.g. - -```markdown -The fix for this has been merged and will release with version X.Y.Z of the Terraform AWS Provider, expected in the XXX timeframe. -``` - -### Pull Request Types to CHANGELOG - -The CHANGELOG is intended to show operator-impacting changes to the codebase for a particular version. If every change or commit to the code resulted in an entry, the CHANGELOG would become less useful for operators. The lists below are general guidelines on when a decision needs to be made to decide whether a change should have an entry. - -Changes that should have a CHANGELOG entry: - -- New Resources and Data Sources -- New full-length documentation guides (e.g. EKS Getting Started Guide, IAM Policy Documents with Terraform) -- Resource and provider bug fixes -- Resource and provider enhancements -- Deprecations -- Removals - -Changes that may have a CHANGELOG entry: - -- Dependency updates: If the update contains relevant bug fixes or enhancements that affect operators, those should be called out. - -Changes that should _not_ have a CHANGELOG entry: - -- Resource and provider documentation updates -- Testing updates - -## Release Process - -- Create a milestone for the next release after this release (generally, the next milestone will be a minor version increase unless previously decided for a major or patch version) -- Check the existing release milestone for open items and either work through them or move them to the next milestone -- Run the HashiCorp (non-OSS) TeamCity release job with the `DEPLOYMENT_TARGET_VERSION` matching the expected release milestone and `DEPLOYMENT_NEXT_VERSION` matching the next release milestone -- Wait for the TeamCity release job and CircleCI website deployment jobs to complete either by watching the build logs or Slack notifications -- Close the release milestone -- Create a new GitHub release with the release title exactly matching the tag and milestone (e.g. `v2.22.0`) and copy the notes from the CHANGELOG to the release notes. This will trigger [HashiBot](https://github.com/apps/hashibot) release comments. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 2ad1f40c11c..2d7f686e259 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,4 +1,4 @@ - + diff --git a/.github/workflows/README.md b/.github/workflows/README.md new file mode 100644 index 00000000000..248d11bb1bf --- /dev/null +++ b/.github/workflows/README.md @@ -0,0 +1,20 @@ +# GitHub Workflows + +## Using the `setup-terraform` action + +By default, the [`setup-terraform` action](https://github.com/hashicorp/setup-terraform) adds a wrapper for the `terraform` command that allows passing results to subsequent steps. This will prevent using the output of a `terraform` command as the input to another command in the same step. + +The wrapper can be turned off by using + +```yaml +steps: +- uses: hashicorp/setup-terraform@v1 + with: + terraform_wrapper: false +``` + +## Testing workflows locally + +The tool [`act`](https://github.com/nektos/act) can be used to test GitHub workflows locally. The default container [intentionally does not have feature parity](https://github.com/nektos/act#default-runners-are-intentionally-incomplete) with the containers used in GitHub due to the size of a full container. + +The file `./actrc` configures `act` to use a fully-featured container. diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml new file mode 100644 index 00000000000..26c4588caaf --- /dev/null +++ b/.github/workflows/changelog.yml @@ -0,0 +1,48 @@ +name: CHANGELOG Checks +on: + push: + branches: + - master + - 'release/**' + pull_request: + paths: + - CHANGELOG.md + +env: + GO_VERSION: "1.14" + GO111MODULE: on + +jobs: + comment: + if: github.event_name == 'pull_request' && !contains(fromJSON('["bflad", "breathingdust", "ewbankkit", "gdavison", "maryelizbeth"]'), github.actor) + name: Comment + runs-on: ubuntu-latest + steps: + - name: PR Comment + uses: unsplash/comment-on-pr@v1.2.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + msg: |- + Thank you for your contribution! :rocket: + + Please note that the `CHANGELOG.md` file contents are handled by the maintainers during merge. This is to prevent pull request merge conflicts, especially for contributions which may not be merged immediately. Please see the [Contributing Guide](https://github.com/terraform-providers/terraform-provider-aws/blob/master/.github/CONTRIBUTING.md) for additional pull request review items. + + Remove any changes to the `CHANGELOG.md` file and commit them in this pull request to prevent delays with reviewing and potentially merging this pull request. + - name: Fail the check + run: exit 1 + misspell: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - run: go install github.com/client9/misspell/cmd/misspell + - run: misspell -error -source text CHANGELOG.md diff --git a/.github/workflows/changelog_checks.yml b/.github/workflows/changelog_checks.yml deleted file mode 100644 index d8dcdac3a82..00000000000 --- a/.github/workflows/changelog_checks.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: CHANGELOG Checks -on: - pull_request: - paths: - - CHANGELOG.md - -jobs: - PRCheck: - name: PR Check - runs-on: ubuntu-latest - steps: - - name: PR Comment - uses: unsplash/comment-on-pr@v1.2.0 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - msg: |- - Thank you for your contribution! :rocket: - - Please note that the `CHANGELOG.md` file contents are handled by the maintainers during merge. This is to prevent pull request merge conflicts, especially for contributions which may not be merged immediately. Please see the [Contributing Guide](https://github.com/terraform-providers/terraform-provider-aws/blob/master/.github/CONTRIBUTING.md) for additional pull request review items. - - Remove any changes to the `CHANGELOG.md` file and commit them in this pull request to prevent delays with reviewing and potentially merging this pull request. - - name: Fail the check - run: exit 1 diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml new file mode 100644 index 00000000000..61553ab3c29 --- /dev/null +++ b/.github/workflows/dependencies.yml @@ -0,0 +1,59 @@ +name: Dependency Checks + +on: + push: + branches: + - master + - 'release/**' + pull_request: + paths: + - awsproviderlint/** # go/analysis/analysistest requires vendoring + - go.mod + - go.sum + - vendor/** + +env: + GO_VERSION: "1.14" + +jobs: + comment: + if: github.event_name == 'pull_request' && !contains(fromJSON('["anGie44", "bflad", "breathingdust", "DrFaust92", "ewbankkit", "gdavison", "maryelizbeth", "YakDriver", "renovate[bot]"]'), github.actor) + name: Comment + runs-on: ubuntu-latest + steps: + - name: PR Comment + uses: unsplash/comment-on-pr@v1.2.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + check_duplicate_msg: true + msg: |- + Thank you for your contribution! :rocket: + + Please note that typically Go dependency changes are handled in this repository by Renovate Bot or the maintainers. This is to prevent pull request merge conflicts and further delay reviews of contributions. Remove any changes to the `go.mod`, `go.sum`, and `vendor/` files and commit them into this pull request. + + Additional details: + + * Check [open pull requests with the `dependencies` label](https://github.com/terraform-providers/terraform-provider-aws/pulls?q=is%3Aopen+is%3Apr+label%3Adependencies) to view other dependency updates. + * If this pull request includes an update the AWS Go SDK (or any other dependency) version, only updates submitted via Renovate Bot will be merged. This pull request will need to remove these changes and will need to be rebased after the existing dependency update via Renovate Bot has been merged for this pull request to be reviewed. + * If this pull request is for supporting a new AWS service: + * Ensure the new AWS service changes are following the [Contributing Guide section on new services](https://github.com/terraform-providers/terraform-provider-aws/blob/master/docs/contributing/contribution-checklists.md#new-service), in particular that the dependency addition and initial provider support are in a separate pull request from other changes (e.g. new resources). Contributions not following this item will not be reviewed until the changes are split. + * If this pull request is already a separate pull request from the above item, you can ignore this message. + go_mod: + name: go mod + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - name: go mod + run: | + echo "==> Checking source code with go mod tidy..." + go mod tidy + git diff --exit-code -- go.mod go.sum || \ + (echo; echo "Unexpected difference in go.mod/go.sum files. Run 'go mod tidy' command or revert any go.mod/go.sum changes and commit."; exit 1) + echo "==> Checking source code with go mod vendor..." + go mod vendor + git diff --compact-summary --exit-code -- vendor || \ + (echo; echo "Unexpected difference in vendor/ directory. Run 'go mod vendor' command or revert any go.mod/go.sum/vendor changes and commit."; exit 1) diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml new file mode 100644 index 00000000000..38198662591 --- /dev/null +++ b/.github/workflows/documentation.yml @@ -0,0 +1,50 @@ +name: Documentation Checks +on: + push: + branches: + - master + pull_request: + paths: + - .markdownlinkcheck.json + - .markdownlint.yml + - .github/workflows/documentation.yml + - docs/** + +env: + GO_VERSION: "1.14" + GO111MODULE: on + +jobs: + markdown-link-check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: gaurav-nelson/github-action-markdown-link-check@v1 + with: + use-quiet-mode: 'yes' + use-verbose-mode: 'yes' + config-file: '.markdownlinkcheck.json' + folder-path: 'docs' + file-extension: '.md' + markdown-lint: + runs-on: ubuntu-latest + steps: + - uses: avto-dev/markdown-lint@v1.3.0 + with: + config: '.markdownlint.yml' + args: 'docs' + misspell: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - run: go install github.com/client9/misspell/cmd/misspell + - run: misspell -error -source text docs/ diff --git a/.github/workflows/examples.yml b/.github/workflows/examples.yml index 19b9bbe379c..6830ad9f6f4 100644 --- a/.github/workflows/examples.yml +++ b/.github/workflows/examples.yml @@ -18,20 +18,16 @@ jobs: fail-fast: false matrix: go_version: ["1.14"] - terraform_version: ["0.11.14", "0.12.24"] + terraform_version: ["0.12.29"] steps: - uses: actions/checkout@v2 with: fetch-depth: 0 - - name: git fetch tags - run: git fetch --depth=1 origin +refs/tags/*:refs/tags/* - - uses: actions/cache@v1 + - uses: actions/cache@v2 with: path: ~/go/pkg/mod - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - uses: actions/setup-go@v1 + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - uses: actions/setup-go@v2 with: go-version: ${{ matrix.go_version }} - name: go build @@ -44,31 +40,33 @@ jobs: - uses: hashicorp/setup-terraform@v1 with: terraform_version: ${{ matrix.terraform_version }} + # Needed to use the output of `terraform validate -json` + terraform_wrapper: false + - name: install tflint + env: + TFLINT_VERSION: "v0.18.0" + run: | + curl -s https://raw.githubusercontent.com/terraform-linters/tflint/master/install_linux.sh | sh - name: terraform run: | for DIR in $(find ./examples -type f -name '*.tf' -exec dirname {} \; | sort -u); do - if [ ${{ matrix.terraform_version }} = 0.11.14 ]; then - if [ $DIR = ./examples/eks-getting-started ]; then - # Skip example already converted to Terraform 0.12 and later syntax - continue - elif [ $DIR = ./examples/two-tier ]; then - # 0.11 validation requires file path to exist - mkdir -p ~/.ssh - touch ~/.ssh/terraform-provider-aws-example.pub - fi - fi - pushd $DIR + pushd "$DIR" if [ -f terraform.template.tfvars ]; then cp terraform.template.tfvars terraform.tfvars fi echo; echo -e "\e[1;35m===> Initializing Example: $DIR <===\e[0m"; echo terraform init - # Prefer Terraform 0.12 and later format checking to prevent conflicts - if [ ${{ matrix.terraform_version }} != 0.11.14 ]; then - echo; echo -e "\e[1;35m===> Format Checking Example: $DIR <===\e[0m"; echo - terraform fmt -check - fi + echo; echo -e "\e[1;35m===> Format Checking Example: $DIR <===\e[0m"; echo + terraform fmt -check echo; echo -e "\e[1;35m===> Validating Example: $DIR <===\e[0m"; echo + # Catch errors terraform validate + # Terraform syntax checks + tflint \ + --enable-rule=terraform_deprecated_interpolation \ + --enable-rule=terraform_deprecated_index \ + --enable-rule=terraform_unused_declarations \ + --enable-rule=terraform_comment_syntax \ + --enable-rule=terraform_required_version popd done diff --git a/.github/workflows/issues.yml b/.github/workflows/issues.yml index 4253aebf217..d684ce928ca 100644 --- a/.github/workflows/issues.yml +++ b/.github/workflows/issues.yml @@ -7,7 +7,7 @@ jobs: - uses: actions/checkout@v1.0.0 - name: Apply Issue Triage Label uses: actions/github@v1.0.0 - if: github.event.action == 'opened' && !contains(fromJSON('["bflad", "breathingdust", "ewbankkit", "gdavison", "maryelizbeth"]'), github.actor) + if: github.event.action == 'opened' && !contains(fromJSON('["anGie44", "bflad", "breathingdust", "DrFaust92", "ewbankkit", "gdavison", "maryelizbeth", "YakDriver"]'), github.actor) env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml new file mode 100644 index 00000000000..638ca772dd9 --- /dev/null +++ b/.github/workflows/snapshot.yml @@ -0,0 +1,46 @@ +name: Snapshot + +on: + schedule: + - cron: '15 5 * * *' + workflow_dispatch: + +env: + GO_VERSION: "1.14" + GO111MODULE: on + +jobs: + goreleaser: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - name: goreleaser release + uses: goreleaser/goreleaser-action@v2 + with: + args: release --rm-dist --skip-sign --snapshot --timeout 2h + - name: artifact naming + id: naming + run: | + case $GITHUB_REF in + refs/heads/*) + ARTIFACT="${GITHUB_REF#refs/heads/}";; + refs/pull/*) + ARTIFACT="pr-${GITHUB_REF#refs/pull/}" + ARTIFACT="${ARTIFACT%/merge}";; + *) + ARTIFACT="${GITHUB_REF}";; + esac + echo "::set-output name=artifact::$ARTIFACT-$(date -u +'%Y-%m-%dT%H-%M')" + - uses: actions/upload-artifact@v2 + with: + name: ${{steps.naming.outputs.artifact}} + path: dist/*.zip diff --git a/.github/workflows/team_slack_bot.yml b/.github/workflows/team_slack_bot.yml new file mode 100644 index 00000000000..14937271a82 --- /dev/null +++ b/.github/workflows/team_slack_bot.yml @@ -0,0 +1,20 @@ +name: team-slack-bot + +on: + schedule: + - cron: '0 15 * * 1-5' + +jobs: + open-pr-stats: + runs-on: ubuntu-latest + name: open-pr-stats + steps: + - name: open-pr-stats + uses: breathingdust/github-team-slackbot@v17 + with: + github_token: ${{ secrets.GITHUB_ACTIONS_TOKEN}} + org: terraform-providers + repo: terraform-provider-aws + team_slug: aws-provider + slack_token: ${{ secrets.SLACK_BOT_TOKEN }} + slack_channel: ${{ secrets.SLACK_CHANNEL }} diff --git a/.github/workflows/terraform_provider.yml b/.github/workflows/terraform_provider.yml new file mode 100644 index 00000000000..45c28cee32e --- /dev/null +++ b/.github/workflows/terraform_provider.yml @@ -0,0 +1,284 @@ +name: Terraform Provider Checks + +on: + push: + branches: + - master + - 'release/**' + pull_request: + paths: + - .github/workflows/terraform_provider.yml + - .golangci.yml + - .goreleaser.yml + - aws/** + - awsproviderlint/** + - docs/index.md + - docs/data-sources/** + - docs/guides/** + - docs/resources/** + - go.sum + - GNUmakefile + - main.go + - staticcheck.conf + - website/** + +env: + AWS_DEFAULT_REGION: us-west-2 + GO_VERSION: "1.14" + GO111MODULE: on + TERRAFORM_VERSION: "0.12.25" + +jobs: + go_mod_download: + name: go mod download + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/cache@v2 + continue-on-error: true + id: cache-go-pkg-mod + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - if: steps.cache-go-pkg-mod.outputs.cache-hit != 'true' || steps.cache-go-pkg-mod.outcome == 'failure' + run: go mod download + + go_build: + name: go build + needs: [go_mod_download] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/cache@v2 + continue-on-error: true + id: cache-terraform-plugin-dir + timeout-minutes: 2 + with: + path: terraform-plugin-dir + key: ${{ runner.os }}-terraform-plugin-dir-${{ hashFiles('go.sum') }}-${{ hashFiles('aws/**') }} + - if: steps.cache-terraform-plugin-dir.outputs.cache-hit != 'true' || steps.cache-terraform-plugin-dir.outcome == 'failure' + uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - if: steps.cache-terraform-plugin-dir.outputs.cache-hit != 'true' || steps.cache-terraform-plugin-dir.outcome == 'failure' + name: go env + run: | + echo "::set-env name=GOCACHE::$(go env GOCACHE)" + - if: steps.cache-terraform-plugin-dir.outputs.cache-hit != 'true' || steps.cache-terraform-plugin-dir.outcome == 'failure' + uses: actions/cache@v2 + with: + path: ${{ env.GOCACHE }} + key: ${{ runner.os }}-GOCACHE-${{ hashFiles('go.sum') }}-${{ hashFiles('aws/**') }} + - if: steps.cache-terraform-plugin-dir.outputs.cache-hit != 'true' || steps.cache-terraform-plugin-dir.outcome == 'failure' + uses: actions/cache@v2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - if: steps.cache-terraform-plugin-dir.outputs.cache-hit != 'true' || steps.cache-terraform-plugin-dir.outcome == 'failure' + name: go build + run: go build -o terraform-plugin-dir/terraform-provider-aws_v99.99.99_x4 . + + terraform_providers_schema: + name: terraform providers schema + needs: [go_build] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/cache@v2 + continue-on-error: true + id: cache-terraform-providers-schema + timeout-minutes: 2 + with: + path: terraform-providers-schema + key: ${{ runner.os }}-terraform-providers-schema-${{ hashFiles('go.sum') }}-${{ hashFiles('aws/**') }} + - if: steps.cache-terraform-providers-schema.outputs.cache-hit != 'true' || steps.cache-terraform-providers-schema.outcome == 'failure' + uses: actions/cache@v2 + timeout-minutes: 2 + with: + path: terraform-plugin-dir + key: ${{ runner.os }}-terraform-plugin-dir-${{ hashFiles('go.sum') }}-${{ hashFiles('aws/**') }} + - if: steps.cache-terraform-providers-schema.outputs.cache-hit != 'true' || steps.cache-terraform-providers-schema.outcome == 'failure' + uses: hashicorp/setup-terraform@v1 + with: + terraform_version: ${{ env.TERRAFORM_VERSION }} + terraform_wrapper: false + - if: steps.cache-terraform-providers-schema.outputs.cache-hit != 'true' || steps.cache-terraform-providers-schema.outcome == 'failure' + name: terraform init + run: | + # We need a file to initialize the provider + echo 'data "aws_partition" "example" {}' > example.tf + terraform init -plugin-dir terraform-plugin-dir + - if: steps.cache-terraform-providers-schema.outputs.cache-hit != 'true' || steps.cache-terraform-providers-schema.outcome == 'failure' + name: terraform providers schema + run: | + mkdir terraform-providers-schema + terraform providers schema -json > terraform-providers-schema/schema.json + + awsproviderlint: + needs: [go_build] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - name: go env + run: | + echo "::set-env name=GOCACHE::$(go env GOCACHE)" + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ${{ env.GOCACHE }} + key: ${{ runner.os }}-GOCACHE-${{ hashFiles('go.sum') }}-${{ hashFiles('aws/**') }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - run: go install ./awsproviderlint + - name: awsproviderlint + run: make awsproviderlint + + go_generate: + name: go generate + needs: [go_build] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - name: go env + run: | + echo "::set-env name=GOCACHE::$(go env GOCACHE)" + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ${{ env.GOCACHE }} + key: ${{ runner.os }}-GOCACHE-${{ hashFiles('go.sum') }}-${{ hashFiles('aws/**') }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - run: go generate ./... + - name: Check for Git Differences + run: | + git diff --compact-summary --exit-code || \ + (echo; echo "Unexpected difference in directories after code generation. Run 'make gen' command and commit."; exit 1) + + go_test: + name: go test + needs: [go_build] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - name: go env + run: | + echo "::set-env name=GOCACHE::$(go env GOCACHE)" + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ${{ env.GOCACHE }} + key: ${{ runner.os }}-GOCACHE-${{ hashFiles('go.sum') }}-${{ hashFiles('aws/**') }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - run: go test ./... -timeout=120s + + golangci-lint: + needs: [go_build] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - name: go env + run: | + echo "::set-env name=GOCACHE::$(go env GOCACHE)" + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ${{ env.GOCACHE }} + key: ${{ runner.os }}-GOCACHE-${{ hashFiles('go.sum') }}-${{ hashFiles('aws/**') }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - run: go install github.com/golangci/golangci-lint/cmd/golangci-lint + - run: golangci-lint run ./aws/... + - run: golangci-lint run ./awsproviderlint/... + + goreleaser: + needs: [go_mod_download] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - name: goreleaser check + continue-on-error: true + uses: goreleaser/goreleaser-action@v2 + with: + args: check + - name: goreleaser build + uses: goreleaser/goreleaser-action@v2 + with: + args: build --snapshot --timeout 1h + + tfproviderdocs: + needs: [terraform_providers_schema] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - run: go install github.com/bflad/tfproviderdocs + - uses: actions/cache@v2 + timeout-minutes: 2 + with: + path: terraform-providers-schema + key: ${{ runner.os }}-terraform-providers-schema-${{ hashFiles('go.sum') }}-${{ hashFiles('aws/**') }} + - name: tfproviderdocs check + run: | + tfproviderdocs check \ + -allowed-resource-subcategories-file website/allowed-subcategories.txt \ + -ignore-file-missing-data-sources aws_alb,aws_alb_listener,aws_alb_target_group \ + -ignore-file-missing-resources aws_alb,aws_alb_listener,aws_alb_listener_certificate,aws_alb_listener_rule,aws_alb_target_group,aws_alb_target_group_attachment \ + -ignore-side-navigation-data-sources aws_alb,aws_alb_listener,aws_alb_target_group,aws_kms_secret \ + -provider-name aws \ + -providers-schema-json terraform-providers-schema/schema.json \ + -require-resource-subcategory diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml index e975771e984..e96f114c853 100644 --- a/.github/workflows/website.yml +++ b/.github/workflows/website.yml @@ -1,21 +1,144 @@ +## These checks will be superseded by documentation.yml +## when the provider documentation layout is moved to +## the Terraform Registry layout. name: Website Checks on: push: branches: - master + - 'release/**' pull_request: paths: + - .github/workflows/website.yml + - .markdownlinkcheck.json + - .markdownlint.yml - website/docs/** +env: + GO_VERSION: "1.14" + GO111MODULE: on + TFLINT_VERSION: "v0.18.0" + jobs: markdown-link-check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: gaurav-nelson/github-action-markdown-link-check@v1 - with: - use-quiet-mode: 'yes' - use-verbose-mode: 'yes' - config-file: '.markdownlinkcheck.json' - folder-path: 'website/docs' - file-extension: '.markdown' + - uses: actions/checkout@v2 + - uses: gaurav-nelson/github-action-markdown-link-check@v1 + name: markdown-link-check website/docs/**/*.markdown + with: + use-quiet-mode: 'yes' + use-verbose-mode: 'yes' + config-file: '.markdownlinkcheck.json' + folder-path: 'website/docs' + file-extension: '.markdown' + - uses: gaurav-nelson/github-action-markdown-link-check@v1 + name: markdown-link-check website/docs/**/*.md + with: + use-quiet-mode: 'yes' + use-verbose-mode: 'yes' + config-file: '.markdownlinkcheck.json' + folder-path: 'website/docs' + file-extension: '.md' + markdown-lint: + runs-on: ubuntu-latest + steps: + - uses: avto-dev/markdown-lint@v1.3.0 + with: + config: '.markdownlint.yml' + args: 'website/docs' + misspell: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - run: go install github.com/client9/misspell/cmd/misspell + - run: misspell -error -source text website/ + terrafmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - run: go install github.com/katbyte/terrafmt + - run: terrafmt diff ./website --check --pattern '*.markdown' --quiet + validate-terraform: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-go@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/cache@v2 + continue-on-error: true + timeout-minutes: 2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-pkg-mod-${{ hashFiles('go.sum') }} + - run: | + # go get github.com/katbyte/terrafmt + git clone --branch json-output --single-branch https://github.com/gdavison/terrafmt terrafmt + cd terrafmt + go install + - run: curl -s https://raw.githubusercontent.com/terraform-linters/tflint/master/install_linux.sh | sh + - run: | + exit_code=0 + + # Configure the rules for tflint. + # The *_invalid_* rules disabled here prevent evaluation of expressions. + # Do not disable *_invalid_name rules, since these are good checks for e.g. "%s" formatting verbs + # being carried over from test cases. + shared_rules=( + "--enable-rule=terraform_comment_syntax" + "--disable-rule=aws_cloudwatch_event_target_invalid_arn" + "--disable-rule=aws_cognito_user_pool_domain_invalid_domain" + "--disable-rule=aws_db_instance_default_parameter_group" + "--disable-rule=aws_elasticache_cluster_default_parameter_group" + "--disable-rule=aws_iam_saml_provider_invalid_saml_metadata_document" + "--disable-rule=aws_iam_server_certificate_invalid_certificate_body" + "--disable-rule=aws_iam_server_certificate_invalid_private_key" + "--disable-rule=aws_transfer_ssh_key_invalid_body" + "--disable-rule=aws_worklink_website_certificate_authority_association_invalid_certificate" + ) + find ./website/docs -type f \( -name '*.md' -o -name '*.markdown' \) \ + | sort -u \ + | while read -r filename ; do + rules=("${shared_rules[@]}") + if [[ "$filename" == "./website/docs/guides/version-2-upgrade.html.md" ]]; then + # ./website/docs/guides/version-2-upgrade.html.md should still include pre-0.12 syntax, + # since v1.0 does not support Terraform 0.12. + rules+=( + "--disable-rule=terraform_deprecated_interpolation" + "--disable-rule=terraform_deprecated_index" + ) + else + rules+=( + "--enable-rule=terraform_deprecated_interpolation" + "--enable-rule=terraform_deprecated_index" + ) + fi + # echo "Let's go with $filename..." + # We need to capture the output and error code here. We don't want to exit on the first error + set +e + ./scripts/validate-terraform-file.sh "$filename" "${rules[@]}" + lint_exitcode=$? + set -e + if [ $lint_exitcode -ne 0 ]; then exit_code=1; fi + done + + exit $exit_code diff --git a/.gitignore b/.gitignore index 519507f6f27..f3bf485d7cf 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ example.tf terraform.tfplan terraform.tfstate bin/ +dist/ modules-dev/ /pkg/ website/.vagrant diff --git a/.go-version b/.go-version index b0f139ead18..24a57f28a41 100644 --- a/.go-version +++ b/.go-version @@ -1 +1 @@ -1.13.7 +1.14.5 diff --git a/.golangci.yml b/.golangci.yml index cb031979943..7b207c74554 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,9 +1,18 @@ issues: exclude-rules: + - linters: + - gosimple + text: "S1039:" + # Exclude issues bypassing staticcheck.conf - linters: - staticcheck text: "SA1019:" + + - linters: + - unparam + text: "always receives" + max-per-linter: 0 max-same-issues: 0 @@ -20,12 +29,13 @@ linters: - structcheck - unconvert - unused + - unparam - varcheck - vet linters-settings: errcheck: - ignore: github.com/hashicorp/terraform-plugin-sdk/helper/schema:ForceNew|Set,fmt:.*,io:Close + ignore: github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema:ForceNew|Set,fmt:.*,io:Close run: modules-download-mode: vendor diff --git a/.goreleaser.yml b/.goreleaser.yml new file mode 100644 index 00000000000..8d1a78155dd --- /dev/null +++ b/.goreleaser.yml @@ -0,0 +1,47 @@ +archives: + - files: + - none* + format: zip + name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}' +before: + hooks: + - go mod download +builds: + - binary: '{{ .ProjectName }}_{{ .Version }}' + flags: + - -trimpath + goarch: + - '386' + - amd64 + - arm + - arm64 + goos: + - darwin + - freebsd + - linux + - windows + ignore: + - goarch: '386' + goos: darwin + ldflags: + - -s -w -X aws/version.ProviderVersion={{.Version}} + mod_timestamp: '{{ .CommitTimestamp }}' +changelog: + skip: true +checksum: + name_template: '{{ .ProjectName }}_{{ .Version }}_SHA256SUMS' + algorithm: sha256 +env: + - CGO_ENABLED=0 +release: + disable: true +signs: + - artifacts: checksum + args: + - "--batch" + - "--local-user" + - "{{ .Env.GPG_FINGERPRINT }}" # set this environment variable for your signing key + - "--output" + - "${signature}" + - "--detach-sign" + - "${artifact}" diff --git a/.hashibot.hcl b/.hashibot.hcl index 86dbb9baf67..9ee6d8cc204 100644 --- a/.hashibot.hcl +++ b/.hashibot.hcl @@ -35,6 +35,41 @@ behavior "deprecated_import_commenter" "hashicorp_terraform" { EOF } +behavior "deprecated_import_commenter" "sdkv1" { + import_regexp = "github.com/hashicorp/terraform-plugin-sdk/(helper/(acctest|customdiff|logging|resource|schema|structure|validation)|terraform)" + marker_label = "terraform-plugin-sdk-v1" + + message = <<-EOF + Hello, and thank you for your contribution! + + This project recently upgraded to [V2 of the Terraform Plugin SDK](https://www.terraform.io/docs/extend/guides/v2-upgrade-guide.html) + + This pull request appears to include at least one V1 import path of the SDK (`${var.import_path}`). Please import the V2 path `github.com/hashicorp/terraform-plugin-sdk/v2/helper/PACKAGE` + + To resolve this situation without losing any existing work, you may be able to Git rebase your branch against the current master branch (example below); replacing any remaining old import paths with the newer ones. + + ```console + $ git fetch --all + $ git rebase origin/master + ``` + + Another option is to create a new branch from the current master with the same code changes (replacing the import paths), submit a new pull request, and close this existing pull request. + + We apologize for this inconvenience and appreciate your effort. Thank you for contributing and helping make the Terraform AWS Provider better for everyone. + EOF +} + +behavior "deprecated_import_commenter" "sdkv1_deprecated" { + import_regexp = "github.com/hashicorp/terraform-plugin-sdk/helper/(hashcode|mutexkv|encryption)" + marker_label = "terraform-plugin-sdk-v1" + + message = <<-EOF + Hello, and thank you for your contribution! + This pull request appears to include the Go import path `${var.import_path}`, which was deprecated after upgrading to [V2 of the Terraform Plugin SDK](https://www.terraform.io/docs/extend/guides/v2-upgrade-guide.html). + You may use a now internalized version of the package found in `github.com/terraform-providers/terraform-provider-aws/aws/internal/PACKAGE`. + EOF +} + behavior "opened_pull_request_labeler" "triage" { labels = ["needs-triage"] skip_collaborators = true @@ -154,6 +189,9 @@ behavior "regexp_issue_labeler_v2" "service_labels" { "service/cloudwatchlogs" = [ "aws_cloudwatch_log_", ], + "service/codeartifact" = [ + "aws_codeartifact_", + ], "service/codebuild" = [ "aws_codebuild_", ], @@ -232,6 +270,7 @@ behavior "regexp_issue_labeler_v2" "service_labels" { "aws_spot", "aws_route(\"|`|$)", "aws_vpn_", + "aws_volume_attachment", ], "service/ecr" = [ "aws_ecr_", @@ -246,7 +285,7 @@ behavior "regexp_issue_labeler_v2" "service_labels" { "aws_eks_", ], "service/elastic-transcoder" = [ - "aws_elastic_transcoder_", + "aws_elastictranscoder_", ], "service/elasticache" = [ "aws_elasticache_", @@ -385,12 +424,18 @@ behavior "regexp_issue_labeler_v2" "service_labels" { "service/neptune" = [ "aws_neptune_", ], + "service/networkmanager" = [ + "aws_networkmanager_", + ], "service/opsworks" = [ "aws_opsworks_", ], "service/organizations" = [ "aws_organizations_", ], + "service/outposts" = [ + "aws_outposts_", + ], "service/personalize" = [ "aws_personalize_", ], @@ -422,6 +467,9 @@ behavior "regexp_issue_labeler_v2" "service_labels" { "service/resourcegroups" = [ "aws_resourcegroups_", ], + "service/resourcegroupstaggingapi" = [ + "aws_resourcegroupstaggingapi_", + ], "service/robomaker" = [ "aws_robomaker_", ], @@ -493,6 +541,9 @@ behavior "regexp_issue_labeler_v2" "service_labels" { "service/swf" = [ "aws_swf_", ], + "service/synthetics" = [ + "aws_synthetics_", + ], "service/transfer" = [ "aws_transfer_", ], @@ -525,6 +576,7 @@ behavior "pull_request_path_labeler" "service_labels" { label_map = { # label provider related changes "provider" = [ + "*.md", ".github/**/*", ".gitignore", ".go-version", @@ -541,6 +593,8 @@ behavior "pull_request_path_labeler" "service_labels" { "aws/internal/naming/*", "aws/provider.go", "aws/utils.go", + "docs/*.md", + "docs/contributing/**/*", "GNUmakefile", "infrastructure/**/*", "main.go", @@ -551,7 +605,13 @@ behavior "pull_request_path_labeler" "service_labels" { "website/**/partition*", "website/**/region*" ] - # label test related changes + "documentation" = [ + "docs/**/*", + "*.md", + ] + "examples" = [ + "examples/**/*", + ] "tests" = [ "**/*_test.go", "**/testdata/**/*", @@ -560,7 +620,6 @@ behavior "pull_request_path_labeler" "service_labels" { ".gometalinter.json", ".markdownlinkcheck.json", ".markdownlint.yml", - ".travis.yml", "staticcheck.conf" ] # label services @@ -688,6 +747,10 @@ behavior "pull_request_path_labeler" "service_labels" { "**/*_cloudwatch_log_*", "**/cloudwatch_log_*" ] + "service/codeartifact" = [ + "**/*_codeartifact_*", + "**/codeartifact_*" + ] "service/codebuild" = [ "**/*_codebuild_*", "**/codebuild_*" @@ -806,6 +869,7 @@ behavior "pull_request_path_labeler" "service_labels" { "aws/*_aws_subnet*", "aws/*_aws_vpc*", "aws/*_aws_vpn*", + "aws/*_aws_volume_attachment*", "website/**/availability_zone*", "website/**/customer_gateway*", "website/**/default_network_acl*", @@ -834,7 +898,8 @@ behavior "pull_request_path_labeler" "service_labels" { "website/**/spot_*", "website/**/subnet*", "website/**/vpc*", - "website/**/vpn*" + "website/**/vpn*", + "website/**/volume_attachment*" ] "service/ecr" = [ "**/*_ecr_*", @@ -1041,6 +1106,10 @@ behavior "pull_request_path_labeler" "service_labels" { "**/*_neptune_*", "**/neptune_*" ] + "service/networkmanager" = [ + "**/*_networkmanager_*", + "**/networkmanager_*" + ] "service/opsworks" = [ "**/*_opsworks_*", "**/opsworks_*" @@ -1049,6 +1118,10 @@ behavior "pull_request_path_labeler" "service_labels" { "**/*_organizations_*", "**/organizations_*" ] + "service/outposts" = [ + "**/*_outposts_*", + "**/outposts_*" + ] "service/pinpoint" = [ "**/*_pinpoint_*", "**/pinpoint_*" @@ -1087,6 +1160,10 @@ behavior "pull_request_path_labeler" "service_labels" { "**/*_resourcegroups_*", "**/resourcegroups_*" ] + "service/resourcegroupstaggingapi" = [ + "**/*_resourcegroupstaggingapi_*", + "**/resourcegroupstaggingapi_*" + ] "service/robomaker" = [ "**/*_robomaker_*", "**/robomaker_*", @@ -1189,6 +1266,10 @@ behavior "pull_request_path_labeler" "service_labels" { "**/*_swf_*", "**/swf_*" ] + "service/synthetics" = [ + "**/*_synthetics_*", + "**/synthetics_*" + ] "service/transfer" = [ "**/*_transfer_*", "**/transfer_*" diff --git a/.markdownlinkcheck.json b/.markdownlinkcheck.json index 03d4284040a..e1be6a99409 100644 --- a/.markdownlinkcheck.json +++ b/.markdownlinkcheck.json @@ -2,6 +2,9 @@ "ignorePatterns": [ { "pattern": "^http(s)?://(?!(docs\\.aws\\.amazon\\.com|github.com|(www\\.)?terraform\\.io))" + }, + { + "pattern": "^https://github.com/[^/]+/[^/]+/(issues|labels|pull)" } ], "replacementPatterns": [ @@ -17,6 +20,10 @@ "pattern": "^/docs/providers/aws/", "replacement": "file:///github/workspace/website/docs/" }, + { + "pattern": "^(custom-service-endpoints|resource-tagging|version-2-upgrade|version-3-upgrade).html.markdown(#.*)?$", + "replacement": "file:///github/workspace/website/docs/guides/$1.html.md$2" + }, { "pattern": "^file:///github/workspace/website/docs/guides/(.*)\\.markdown(#.*)?$", "replacement": "file:///github/workspace/website/docs/guides/$1.md$2" diff --git a/.markdownlint.yml b/.markdownlint.yml index f9782ba5a20..0ae15e39d04 100644 --- a/.markdownlint.yml +++ b/.markdownlint.yml @@ -2,6 +2,8 @@ # https://github.com/DavidAnson/markdownlint#configuration default: true +MD007: + indent: 4 # Disabled Rules # https://github.com/DavidAnson/markdownlint/blob/master/doc/Rules.md @@ -9,7 +11,6 @@ default: true MD001: false MD004: false MD006: false -MD007: false MD009: false MD010: false MD012: false diff --git a/.tfproto5 b/.tfproto5 new file mode 100644 index 00000000000..e69de29bb2d diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index e0eed8c0941..00000000000 --- a/.travis.yml +++ /dev/null @@ -1,38 +0,0 @@ -dist: xenial -sudo: required -services: - - docker -language: go - -env: - global: GOFLAGS=-mod=vendor - -matrix: - fast_finish: true - allow_failures: - - go: tip - include: - - go: "1.13.x" - name: "Code Lint" - script: make lint - - go: "1.13.x" - name: "Code UnitTest" - script: - - make test - - make gencheck - - go: "1.13.x" - name: "Dependencies" - script: make depscheck - - go: "1.13.x" - name: "Website" - script: - - make docscheck - - make website-test - - make website-lint - -install: - - make tools - -branches: - only: - - master diff --git a/CHANGELOG.md b/CHANGELOG.md index 689ded43ef6..7f74646245b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4422 +1,185 @@ -## 2.62.0 (Unreleased) -## 2.61.0 (May 08, 2020) +## 3.3.0 (Unreleased) -FEATURES: - -* **New Data Source:** `aws_ec2_coip_pool` ([#12852](https://github.com/terraform-providers/terraform-provider-aws/issues/12852)) -* **New Data Source:** `aws_ec2_coip_pools` ([#12852](https://github.com/terraform-providers/terraform-provider-aws/issues/12852)) -* **New Data Source:** `aws_ec2_local_gateway` ([#12764](https://github.com/terraform-providers/terraform-provider-aws/issues/12764)) -* **New Data Source:** `aws_ec2_local_gateways` ([#12764](https://github.com/terraform-providers/terraform-provider-aws/issues/12764)) -* **New Data Source:** `aws_ec2_local_gateway_route_table` ([#13002](https://github.com/terraform-providers/terraform-provider-aws/issues/13002)) -* **New Data Source:** `aws_ec2_local_gateway_route_tables` ([#13002](https://github.com/terraform-providers/terraform-provider-aws/issues/13002)) -* **New Resource:** `aws_ec2_transit_gateway_peering_attachment_accepter` ([#11185](https://github.com/terraform-providers/terraform-provider-aws/issues/11185)) - -ENHANCEMENTS: - -* data-source/aws_ebs_volume: Add `multi_attach_enabled` attribute ([#13108](https://github.com/terraform-providers/terraform-provider-aws/issues/13108)) -* data-source/aws_efs_file_system: Add `size_in_bytes` attribute ([#13125](https://github.com/terraform-providers/terraform-provider-aws/issues/13125)) -* data-source/aws_eip: Add `customer_owned_ip` and `customer_owned_ipv4_pool` attributes ([#12862](https://github.com/terraform-providers/terraform-provider-aws/issues/12862)) -* data-source/aws_launch_template: add `partition_number` attribute ([#11655](https://github.com/terraform-providers/terraform-provider-aws/issues/11655)) -* resource/aws_api_gateway_deployment: Add `triggers` argument ([#13054](https://github.com/terraform-providers/terraform-provider-aws/issues/13054)) -* resource/aws_apigatewayv2_deployment: Add `triggers` argument ([#13055](https://github.com/terraform-providers/terraform-provider-aws/issues/13055)) -* resource/aws_ebs_volume: Add `multi_attach_enabled` attribute ([#13108](https://github.com/terraform-providers/terraform-provider-aws/issues/13108)) -* resource/aws_eip: Add `customer_owned_ip` attribute and `customer_owned_ipv4_pool` argument ([#12862](https://github.com/terraform-providers/terraform-provider-aws/issues/12862)) -* resource/aws_glue_connection: Support `KAFKA` for `connection_type` argument ([#13141](https://github.com/terraform-providers/terraform-provider-aws/issues/13141)) -* resource/aws_launch_template: add `partition_number` attribute ([#11655](https://github.com/terraform-providers/terraform-provider-aws/issues/11655)) -* resource/aws_launch_template: add `plan time validation to `volume_type`, `spot_instance_type`, `ipv6_addresses`, `ipv4_addresses`, `private_ip_address` ([#11655](https://github.com/terraform-providers/terraform-provider-aws/issues/11655)) -* resource/aws_workspaces_directory: Add output attributes for `workspace_security_group_id`, `iam_role_id`, `registration_code`, `directory_name`, `directory_type`, `customer_user_name`, `alias`, `ip_group_ids` and `dns_ip_addresses` ([#13089](https://github.com/terraform-providers/terraform-provider-aws/issues/13089)) - -BUG FIXES: - -* resource/aws_workspaces_directory: Fixes error when removing tags ([#13089](https://github.com/terraform-providers/terraform-provider-aws/issues/13089)) - -## 2.60.0 (May 01, 2020) - -NOTES: - -* provider: Region validation now automatically supports the new `eu-south-1` (Europe (Milan)) region. For AWS operations to work in the new region, the region must be explicitly enabled as outlined in the [AWS Documentation](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable). When the region is not enabled, the Terraform AWS Provider will return errors during credential validation (e.g. `error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid`) or AWS operations will throw their own errors (e.g. `data.aws_availability_zones.current: Error fetching Availability Zones: AuthFailure: AWS was not able to validate the provided access credentials`). ([#12970](https://github.com/terraform-providers/terraform-provider-aws/issues/12970)) -* provider: Ignore tags functionality across all data sources and resources (except `aws_autoscaling_group`) via the provider-level `ignore_tags` configuration block has been enabled and this functionality is no longer considered in preview. ([#13039](https://github.com/terraform-providers/terraform-provider-aws/issues/13039)) - -FEATURES: - -* **New Data Source:** `aws_backup_plan` ([#13035](https://github.com/terraform-providers/terraform-provider-aws/issues/13035)) -* **New Data Source:** `aws_backup_selection` ([#13035](https://github.com/terraform-providers/terraform-provider-aws/issues/13035)) -* **New Data Source:** `aws_backup_vault` ([#13035](https://github.com/terraform-providers/terraform-provider-aws/issues/13035)) -* **New Data Source:** `aws_ec2_transit_gateway_peering_attachment` ([#11162](https://github.com/terraform-providers/terraform-provider-aws/issues/11162)) -* **New Resource:** `aws_ec2_transit_gateway_peering_attachment` ([#11162](https://github.com/terraform-providers/terraform-provider-aws/issues/11162)) -* **New Resource:** `aws_guardduty_organization_admin_account` ([#13034](https://github.com/terraform-providers/terraform-provider-aws/issues/13034)) -* **New Resource:** `aws_guardduty_organization_configuration` ([#13034](https://github.com/terraform-providers/terraform-provider-aws/issues/13034)) - -ENHANCEMENTS: - -* data-source/aws_cloudtrail_service_account: Support `eu-south-1` region ([#13061](https://github.com/terraform-providers/terraform-provider-aws/issues/13061)) -* data-source/aws_ebs_volume: Add `outpost_arn` attribute ([#12439](https://github.com/terraform-providers/terraform-provider-aws/issues/12439)) -* data-source/aws_elastic_beanstalk_hosted_zone: Support `eu-south-1` region ([#13061](https://github.com/terraform-providers/terraform-provider-aws/issues/13061)) -* data-source/aws_elb_hosted_zone_id: Add `us-gov-east-1` and `us-gov-west-1` region values ([#12976](https://github.com/terraform-providers/terraform-provider-aws/issues/12976)) -* data-source/aws_elb_hosted_zone_id: Support `eu-south-1` region ([#13061](https://github.com/terraform-providers/terraform-provider-aws/issues/13061)) -* data-source/aws_elb_service_account: Support `eu-south-1` region ([#13061](https://github.com/terraform-providers/terraform-provider-aws/issues/13061)) -* data-source/aws_instance: Add `outpost_arn` attribute ([#12330](https://github.com/terraform-providers/terraform-provider-aws/issues/12330)) -* data-source/aws_network_interface: Add `outpost_arn` attribute ([#12440](https://github.com/terraform-providers/terraform-provider-aws/issues/12440)) -* data-source/aws_s3_bucket: Support `eu-south-1` region for `hosted_zone_id` attribute ([#13061](https://github.com/terraform-providers/terraform-provider-aws/issues/13061)) -* data-source/aws_subnet: Add `outposts_arn` attribute ([#12097](https://github.com/terraform-providers/terraform-provider-aws/issues/12097)) -* provider: Support automatic region validation for `eu-south-1` ([#12970](https://github.com/terraform-providers/terraform-provider-aws/issues/12970)) -* provider: Implement ignore tags functionality across all data sources and resources (except `aws_autoscaling_group`) ([#13039](https://github.com/terraform-providers/terraform-provider-aws/issues/13039)) -* resource/aws_api_gateway_stage: Ignore `NotFoundException` error on destroy ([#12826](https://github.com/terraform-providers/terraform-provider-aws/issues/12826)) -* resource/aws_db_snapshot: Support import ([#12978](https://github.com/terraform-providers/terraform-provider-aws/issues/12978)) -* resource/aws_default_route_table: Add plan-time validation to `cidr_block` and `ipv6_cidr_block` arguments ([#12858](https://github.com/terraform-providers/terraform-provider-aws/issues/12858)) -* resource/aws_default_route_table: Support import ([#13030](https://github.com/terraform-providers/terraform-provider-aws/issues/13030)) -* resource/aws_dms_endpoint: Add `kafka_settings` configuration block and `kafka` to `engine_name` argument validation ([#12835](https://github.com/terraform-providers/terraform-provider-aws/issues/12835)) -* resource/aws_ebs_volume: Add `outpost_arn` argument ([#12439](https://github.com/terraform-providers/terraform-provider-aws/issues/12439)) -* resource/aws_elasticsearch_domain: Support customizable update timeout ([#12916](https://github.com/terraform-providers/terraform-provider-aws/issues/12916)) -* resource/aws_glue_connection: Support `MONGODB` for `connection_type` argument ([#13011](https://github.com/terraform-providers/terraform-provider-aws/issues/13011)) -* resource/aws_key_pair: Support tag-on-create ([#12962](https://github.com/terraform-providers/terraform-provider-aws/issues/12962)) -* resource/aws_instance: Add `outpost_arn` attribute ([#12330](https://github.com/terraform-providers/terraform-provider-aws/issues/12330)) -* resource/aws_mq_broker: Support import ([#11841](https://github.com/terraform-providers/terraform-provider-aws/issues/11841)) -* resource/aws_network_interface: Add `outpost_arn` attribute ([#12440](https://github.com/terraform-providers/terraform-provider-aws/issues/12440)) -* resource/aws_placement_group: Support tag-on-create ([#12963](https://github.com/terraform-providers/terraform-provider-aws/issues/12963)) -* resource/aws_route_table: Add plan-time validation to `cidr_block` and `ipv6_cidr_block` arguments ([#12858](https://github.com/terraform-providers/terraform-provider-aws/issues/12858)) -* resource/aws_route53_health_check: Support plan-time validation for `reference_name` argument ([#12873](https://github.com/terraform-providers/terraform-provider-aws/issues/12873)) -* resource/aws_s3_bucket: Support `eu-south-1` region for `hosted_zone_id` attribute ([#13061](https://github.com/terraform-providers/terraform-provider-aws/issues/13061)) -* resource/aws_spot_fleet_request: Add `launch_template_config` configuration block (Support EC2 Launch Templates) ([#12732](https://github.com/terraform-providers/terraform-provider-aws/issues/12732)) -* resource/aws_spot_fleet_request: Support import ([#12767](https://github.com/terraform-providers/terraform-provider-aws/issues/12767)) -* resource/aws_storagegateway_gateway: Add `gateway_vpc_endpoint` argument ([#9966](https://github.com/terraform-providers/terraform-provider-aws/issues/9966)) -* resource/aws_storagegateway_smb_file_share: Add `path` attribute ([#12623](https://github.com/terraform-providers/terraform-provider-aws/issues/12623)) -* resource/aws_subnet: Add `outposts_arn` argument ([#12097](https://github.com/terraform-providers/terraform-provider-aws/issues/12097)) -* resource/aws_wafregional_xss_match_set: Add plan-time validation for `xss_match_tuple` configuration block arguments ([#13024](https://github.com/terraform-providers/terraform-provider-aws/issues/13024)) - -BUG FIXES: - -* data-source/aws_api_gateway_rest_api: Prevent error with VPC Endpoint configured APIs ([#12825](https://github.com/terraform-providers/terraform-provider-aws/issues/12825)) -* resource/aws_appautoscaling_scheduled_action: Prevent error on refresh with multiple resources using the same scheduled action name ([#12699](https://github.com/terraform-providers/terraform-provider-aws/issues/12699)) -* resource/aws_batch_job_queue: Prevent panic when `ComputeEnvironmentOrder` is updated outside Terraform ([#12632](https://github.com/terraform-providers/terraform-provider-aws/issues/12632)) -* resource/aws_default_route_table: Proper tag on resource creation ([#12858](https://github.com/terraform-providers/terraform-provider-aws/issues/12858)) -* resource/aws_efs_file_system: Prevent panic with empty `lifecycle_policy` configuration block ([#12640](https://github.com/terraform-providers/terraform-provider-aws/issues/12640)) -* resource/aws_fsx_windows_file_system: Prevent panic when update includes `self_managed_active_directory` settings ([#12630](https://github.com/terraform-providers/terraform-provider-aws/issues/12630)) -* resource/aws_glue_catalog_table: Prevent various panics with empty configuration blocks ([#12611](https://github.com/terraform-providers/terraform-provider-aws/issues/12611)) -* resource/aws_kinesis_firehose_delivery_stream: Prevent panic with empty `processing_configuration` configuration block ([#12613](https://github.com/terraform-providers/terraform-provider-aws/issues/12613)) -* resource/aws_kms_external_key: Prevent `MalformedPolicyDocumentException` errors on creation by retrying for up to 2 minutes to wait for IAM change propagation ([#12863](https://github.com/terraform-providers/terraform-provider-aws/issues/12863)) -* resource/aws_kms_key: Prevent `MalformedPolicyDocumentException` errors on creation by retrying for up to 2 minutes to wait for IAM change propagation ([#12863](https://github.com/terraform-providers/terraform-provider-aws/issues/12863)) -* resource/aws_lb_listener: Prevent panics on creation and refresh when API throttled ([#12617](https://github.com/terraform-providers/terraform-provider-aws/issues/12617)) -* resource/aws_route53_zone: Prevent panic with APIs missing `ChangeInfo` during creation (best effort fix for LocalStack) ([#12634](https://github.com/terraform-providers/terraform-provider-aws/issues/12634)) -* resource/aws_storagegateway_gateway: Perform multiple connectivity checks after activation to wait if the underlying server (e.g. EC2 Instance) is automatically rebooted ([#12772](https://github.com/terraform-providers/terraform-provider-aws/issues/12772)) -* resource/aws_storagegateway_gateway: Retry 504 status code on activation ([#12773](https://github.com/terraform-providers/terraform-provider-aws/issues/12773)) -* resource/aws_wafregional_xss_match_set: Prevent crash with `xss_match_tuple` configuration block since version 2.59.0 ([#13024](https://github.com/terraform-providers/terraform-provider-aws/issues/13024)) - -## 2.59.0 (April 23, 2020) - -NOTES: - -* provider: Region validation now automatically supports the new `af-south-1` (Africa (Cape Town)) region. For AWS operations to work in the new region, the region must be explicitly enabled as outlined in the [AWS Documentation](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable). When the region is not enabled, the Terraform AWS Provider will return errors during credential validation (e.g. `error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid`) or AWS operations will throw their own errors (e.g. `data.aws_availability_zones.current: Error fetching Availability Zones: AuthFailure: AWS was not able to validate the provided access credentials`). ([#12715](https://github.com/terraform-providers/terraform-provider-aws/issues/12715)) -* resource/aws_iam_user: The additional `force_destroy` behavior for handling signing certificates requires two additional IAM permissions (`iam:ListSigningCertificates` and `iam:DeleteSigningCertificate`). Restrictive IAM permissions for Terraform runs may require updates. ([#10542](https://github.com/terraform-providers/terraform-provider-aws/issues/10542)) -* resource/aws_rds_cluster: Due to recent API support for Aurora MySQL 5.7 and PostgreSQL Global Clusters which implemented the engine mode as `provisioned` instead of the previous `global` for Aurora MySQL 5.6, the resource now requires the `DescribeGlobalClusters` API call. Restrictive IAM permissions may require updates. ([#12867](https://github.com/terraform-providers/terraform-provider-aws/issues/12867)) - -FEATURES: - -* **New Resource:** `aws_apigatewayv2_api_mapping` ([#9461](https://github.com/terraform-providers/terraform-provider-aws/issues/9461)) -* **New Resource:** `aws_apigatewayv2_vpc_link` ([#12577](https://github.com/terraform-providers/terraform-provider-aws/issues/12577)) - -ENHANCEMENTS: - -* data_source/aws_acm_certificate: Add `tags` output ([#11659](https://github.com/terraform-providers/terraform-provider-aws/issues/11659)) -* data-source/aws_cloudtrail_service_account: Support `af-south-1` region ([#12967](https://github.com/terraform-providers/terraform-provider-aws/issues/12967)) -* data-source/aws_elastic_beanstalk_hosted_zone: Support `af-south-1` region ([#12967](https://github.com/terraform-providers/terraform-provider-aws/issues/12967)) -* data-source/aws_elb_hosted_zone_id: Support `af-south-1` region ([#12967](https://github.com/terraform-providers/terraform-provider-aws/issues/12967)) -* data-source/aws_elb_service_account: Support `af-south-1` region ([#12967](https://github.com/terraform-providers/terraform-provider-aws/issues/12967)) -* data-source/aws_s3_bucket: Support `af-south-1` region for `hosted_zone_id` attribute ([#12967](https://github.com/terraform-providers/terraform-provider-aws/issues/12967)) -* provider: Support automatic region validation for `af-south-1` ([#12715](https://github.com/terraform-providers/terraform-provider-aws/issues/12715)) -* resource/aws_apigatewayv2_api: Add `cors_configuration`, `credentials_arn`, `route_key` and `target` attributes ([#12452](https://github.com/terraform-providers/terraform-provider-aws/issues/12452)) -* resource/aws_appsync_graphql_api: Add `log_config` configuration block `exclude_verbose_content` argument ([#12884](https://github.com/terraform-providers/terraform-provider-aws/issues/12884)) -* resource/aws_config_configuration_recorder: Prevent error during deletion operation when resource is missing ([#12734](https://github.com/terraform-providers/terraform-provider-aws/issues/12734)) -* resource/aws_default_network_acl: Support import ([#12924](https://github.com/terraform-providers/terraform-provider-aws/issues/12924)) -* resource/aws_lambda_alias: Suppress differences for equivalent `function_name` argument values of name versus ARN ([#12902](https://github.com/terraform-providers/terraform-provider-aws/issues/12902)) -* resource/aws_network_acl_rule: Support import ([#12921](https://github.com/terraform-providers/terraform-provider-aws/issues/12921)) -* resource/aws_route: Add plan-time validation for `destination_cidr_block` and `destination_ipv6_cidr_block` arguments ([#12890](https://github.com/terraform-providers/terraform-provider-aws/issues/12890)) -* resource/aws_s3_bucket: Support `af-south-1` region for `hosted_zone_id` attribute ([#12967](https://github.com/terraform-providers/terraform-provider-aws/issues/12967)) -* resource/aws_service_discovery_private_dns_namespace: Support import ([#12929](https://github.com/terraform-providers/terraform-provider-aws/issues/12929)) -* resource/aws_ssm_activation: Support import ([#12933](https://github.com/terraform-providers/terraform-provider-aws/issues/12933)) -* resource/aws_ssm_maintenance_window_target: Add plan-time validation to `resource_type` argument ([#11783](https://github.com/terraform-providers/terraform-provider-aws/issues/11783)) -* resource/aws_ssm_maintenance_window_target: Support import ([#12935](https://github.com/terraform-providers/terraform-provider-aws/issues/12935)) -* resource/aws_volume_attachment: Support import ([#12948](https://github.com/terraform-providers/terraform-provider-aws/issues/12948)) -* resource/aws_waf_ipset: Add plan-time validation for `ip_set_descriptors` configuration block arguments ([#12775](https://github.com/terraform-providers/terraform-provider-aws/issues/12775)) -* resource/aws_waf_sql_injection_match_set: Support import ([#11657](https://github.com/terraform-providers/terraform-provider-aws/issues/11657)) -* resource/aws_waf_xss_match_set: Add plan-time validation for `xss_match_tuples` configuration block arguments ([#12777](https://github.com/terraform-providers/terraform-provider-aws/issues/12777)) -* resource/aws_wafregional_web_acl: Add plan-time validation to various arguments ([#12793](https://github.com/terraform-providers/terraform-provider-aws/issues/12793)) - -BUG FIXES: - -* data-source/aws_launch_template: Prevent type error with `network_interfaces` `associate_public_ip_address` attribute ([#12936](https://github.com/terraform-providers/terraform-provider-aws/issues/12936)) -* resource/aws_glue_security_configuration: Prevent empty string KMS Key ARN in S3 Encryption settings ([#12898](https://github.com/terraform-providers/terraform-provider-aws/issues/12898)) -* resource/aws_iam_user: Ensure `force_destroy` argument removes signing certificates when enabled ([#10542](https://github.com/terraform-providers/terraform-provider-aws/issues/10542)) -* resource/aws_rds_cluster: Prevent unexpected `global_cluster_identifier` differences and deletion error with `aurora-mysql` and `aurora-postgresql` Global Cluster members ([#12867](https://github.com/terraform-providers/terraform-provider-aws/issues/12867)) -* resource/aws_route: Prevent not found after creation error with `destination_ipv6_cidr_block` set to `::0/0` ([#12890](https://github.com/terraform-providers/terraform-provider-aws/issues/12890)) - -## 2.58.0 (April 16, 2020) - -FEATURES: - -* **New Data Source:** `aws_regions` ([#12269](https://github.com/terraform-providers/terraform-provider-aws/issues/12269)) -* **New Resource:** `aws_apigatewayv2_deployment` ([#9245](https://github.com/terraform-providers/terraform-provider-aws/issues/9245)) -* **New Resource:** `aws_apigatewayv2_domain_name` ([#9391](https://github.com/terraform-providers/terraform-provider-aws/issues/9391)) -* **New Resource:** `aws_apigatewayv2_integration_response` ([#9365](https://github.com/terraform-providers/terraform-provider-aws/issues/9365)) -* **New Resource:** `aws_apigatewayv2_route` ([#8881](https://github.com/terraform-providers/terraform-provider-aws/issues/8881)) -* **New Resource:** `aws_apigatewayv2_route_response` ([#9373](https://github.com/terraform-providers/terraform-provider-aws/issues/9373)) -* **New Resource:** `aws_apigatewayv2_stage` ([#9232](https://github.com/terraform-providers/terraform-provider-aws/issues/9232)) -* **New Resource:** `aws_dms_event_subscription` ([#7170](https://github.com/terraform-providers/terraform-provider-aws/issues/7170)) - -ENHANCEMENTS: - -* data-source/aws_dynamodb_table: Add `replica` attribute (initial support for Global Tables V2 (version 2019.11.21)) ([#12342](https://github.com/terraform-providers/terraform-provider-aws/issues/12342)) -* data-source/aws_instance: Exports `volume_name` for `root_block_device` ([#12620](https://github.com/terraform-providers/terraform-provider-aws/issues/12620)) -* resource/aws_backup_plan: Add `rule` configuration block `copy_action` configuration block (support cross region copy) ([#11923](https://github.com/terraform-providers/terraform-provider-aws/issues/11923)) -* resource/aws_cognito_identity_provider: Support plan-time validation for `idp_identifiers`, `provider_name`, and `provider_type` arguments ([#10705](https://github.com/terraform-providers/terraform-provider-aws/issues/10705)) -* resource/aws_dms_endpoint: Add `elasticsearch_settings` configuration block and `elasticsearch` to `engine_name` validation (support Elasticsearch endpoints) ([#11792](https://github.com/terraform-providers/terraform-provider-aws/issues/11792)) -* resource/aws_dms_endpoint: Add `kinesis_settings` configuration block and `kinesis` to `engine_name` validation (support Kinesis endpoints) ([#8633](https://github.com/terraform-providers/terraform-provider-aws/issues/8633)) -* resource/aws_dynamodb_table: Add `replica` configuration block (initial support for Global Tables V2 (version 2019.11.21)) ([#12342](https://github.com/terraform-providers/terraform-provider-aws/issues/12342)) -* resource/aws_ec2_client_vpn_endpoint: Allow two `authentication_options` configuration blocks ([#12819](https://github.com/terraform-providers/terraform-provider-aws/issues/12819)) -* resource/aws_instance: Allow changing root volume size without re-creating resource ([#12620](https://github.com/terraform-providers/terraform-provider-aws/issues/12620)) -* resource/aws_instance: Exports `volume_name` for `root_block_device` ([#12620](https://github.com/terraform-providers/terraform-provider-aws/issues/12620)) - -BUG FIXES: - -* resource/aws_dlm_lifecycle_policy: Ensure plan-time validation for `times` argument only allows 24 hour format ([#12800](https://github.com/terraform-providers/terraform-provider-aws/issues/12800)) - -## 2.57.0 (April 09, 2020) - -BREAKING CHANGES: - -* provider: The configuration for the preview ignore tags functionality has been updated to include a wrapping configuration block. For example: - -```hcl -provider "aws" { - ignore_tags { - keys = ["TagKey1"] - } -} -``` - -FEATURES: - -* **New Data Source:** `aws_cloudfront_distribution` ([#6468](https://github.com/terraform-providers/terraform-provider-aws/issues/6468)) -* **New Resource:** `aws_apigatewayv2_authorizer` ([#9228](https://github.com/terraform-providers/terraform-provider-aws/issues/9228)) -* **New Resource:** `aws_apigatewayv2_integration` ([#8949](https://github.com/terraform-providers/terraform-provider-aws/issues/8949)) -* **New Resource:** `aws_apigatewayv2_model` ([#8912](https://github.com/terraform-providers/terraform-provider-aws/issues/8912)) - -ENHANCEMENTS: - -* data-source/aws_lambda_layer_version: Support plan-time validation for `compatible_runtime` argument `dotnetcore3.1` value (support .NET Core 3.1) ([#12712](https://github.com/terraform-providers/terraform-provider-aws/issues/12712)) -* resource/aws_cloudhsm_v2_cluster: Support tag-on-create ([#11683](https://github.com/terraform-providers/terraform-provider-aws/issues/11683)) -* resource/aws_docdb_cluster: Add `deletion_protection` argument ([#12650](https://github.com/terraform-providers/terraform-provider-aws/issues/12650)) -* resource/aws_egress_only_internet_gateway: Add `tags` argument ([#11568](https://github.com/terraform-providers/terraform-provider-aws/issues/11568)) -* resource/aws_lambda_function: Support plan-time validation for `runtime` argument `dotnetcore3.1` value (support .NET Core 3.1) ([#12712](https://github.com/terraform-providers/terraform-provider-aws/issues/12712)) -* resource/aws_lambda_layer_version: Support plan-time validation for `compatible_runtimes` argument `dotnetcore3.1` value (support .NET Core 3.1) ([#12712](https://github.com/terraform-providers/terraform-provider-aws/issues/12712)) -* resource/aws_rds_global_cluster: Add `aurora-postgresql` to `engine` argument plan-time validation ([#12401](https://github.com/terraform-providers/terraform-provider-aws/issues/12401)) -* resource/aws_redshift_snapshot_copy_grant: Support resource import ([#10350](https://github.com/terraform-providers/terraform-provider-aws/issues/10350)) -* resource/aws_spot_fleet_request: Add `tags` argument (support tagging of Spot Fleet Request itself) ([#12295](https://github.com/terraform-providers/terraform-provider-aws/issues/12295)) -* resource/aws_spot_fleet_request: Support plan-time validation for `launch_specification` configuration block `ebs_block_device` `volume_type`, `iam_instance_profile_arn`, `placement_tenancy`, and `root_block_device` `volume_type` arguments ([#12295](https://github.com/terraform-providers/terraform-provider-aws/issues/12295)) -* resource/aws_spot_fleet_request: Support plan-time validation for `allocation_strategy`, `instance_interruption_behaviour`, and `target_group_arns` arguments ([#12295](https://github.com/terraform-providers/terraform-provider-aws/issues/12295)) -* service/ec2: Prevent eventual consistency errors tagging resources on creation ([#12735](https://github.com/terraform-providers/terraform-provider-aws/issues/12735)) - -BUG FIXES: - -* resource/aws_appautoscaling_policy: Fix error when importing DynamoDB Table Index policy ([#11232](https://github.com/terraform-providers/terraform-provider-aws/issues/11232)) -* resource/aws_db_instance: Allow creating read replica into RAM shared Subnet with VPC Security Group ([#12700](https://github.com/terraform-providers/terraform-provider-aws/issues/12700)) -* resource/aws_kms_key: Prevent eventual consistency related errors on creation ([#12738](https://github.com/terraform-providers/terraform-provider-aws/issues/12738)) -* resource/aws_lb_target_group: Automatically propose resource recreation for TCP `protocol` Target Groups when `health_check` configuration block `interval`, `protocol`, or `timeout` argument values are updated ([#4568](https://github.com/terraform-providers/terraform-provider-aws/issues/4568)) - -## 2.56.0 (April 03, 2020) - -NOTES: - -* resource/aws_emr_cluster: The bug fix in this release will potentially re-create EMR Clusters with multiple bootstrap actions, since bootstrap actions cannot be modified in place. To avoid re-creation, temporarily add the [`ignore_changes` lifecycle configuration argument](https://www.terraform.io/docs/configuration/resources.html#ignore_changes) and/or update the order in your Terraform configuration. - -ENHANCEMENTS: - -* data-source/aws_launch_template: Add `hibernation_options` attribute ([#12492](https://github.com/terraform-providers/terraform-provider-aws/issues/12492)) -* resource/aws_codepipeline: Adds cross-region action support ([#12549](https://github.com/terraform-providers/terraform-provider-aws/issues/12549)) -* resource/aws_dx_connection: Support `2Gbps` and `5Gbps` values in plan-time validation for `bandwidth` argument ([#12559](https://github.com/terraform-providers/terraform-provider-aws/issues/12559)) -* resource/aws_dx_lag: Support `2Gbps` and `5Gbps` values in plan-time validation for `bandwidth` argument ([#12559](https://github.com/terraform-providers/terraform-provider-aws/issues/12559)) -* resource/aws_elastic_transcoder_preset: Support plan-time validation for `role` argument ([#12575](https://github.com/terraform-providers/terraform-provider-aws/issues/12575)) -* resource/aws_kms_grant: Support resource import ([#11991](https://github.com/terraform-providers/terraform-provider-aws/issues/11991)) -* resource/aws_launch_template: Add `hibernation_options` configuration block ([#12492](https://github.com/terraform-providers/terraform-provider-aws/issues/12492)) - -BUG FIXES: - -* resource/aws_codedeploy_deployment_group: Fix `blue_green_deployment_config` updates for ECS ([#11885](https://github.com/terraform-providers/terraform-provider-aws/issues/11885)) -* resource/aws_emr_cluster: Now properly sets the order when multiple bootstrap actions are defined -* resource/aws_kms_grant: Remove resource from Terraform state instead of error if removed outside Terraform ([#12560](https://github.com/terraform-providers/terraform-provider-aws/issues/12560)) -* resource/aws_s3_bucket: Prevent various panics with empty configuration blocks ([#12614](https://github.com/terraform-providers/terraform-provider-aws/issues/12614)) -* resource/aws_volume_attachment: Ensure any error is shown while waiting for volume to detach ([#12596](https://github.com/terraform-providers/terraform-provider-aws/issues/12596)) - -## 2.55.0 (March 27, 2020) - -FEATURES: - -* **New Resource:** `aws_ec2_availability_zone_group` ([#12400](https://github.com/terraform-providers/terraform-provider-aws/issues/12400)) - -ENHANCEMENTS: - -* data-source/aws_availability_zone: Add `all_availability_zones` and `filter` arguments ([#12400](https://github.com/terraform-providers/terraform-provider-aws/issues/12400)) -* data-source/aws_availability_zone: Add `group_name`, `network_border_group`, and `opt_in_status` attributes ([#12400](https://github.com/terraform-providers/terraform-provider-aws/issues/12400)) -* data-source/aws_availability_zones: Add `all_availability_zones` and `filter` arguments ([#12400](https://github.com/terraform-providers/terraform-provider-aws/issues/12400)) -* data-source/aws_availability_zones: Add `group_names` attribute ([#12400](https://github.com/terraform-providers/terraform-provider-aws/issues/12400)) -* data-source/aws_ec2_transit_gateway_dx_gateway_attachement: Add `filter` and `tags` arguments ([#12516](https://github.com/terraform-providers/terraform-provider-aws/issues/12516)) -* data-source/aws_ec2_transit_gateway_vpn_attachment: Add `filter` and `tags` arguments ([#12415](https://github.com/terraform-providers/terraform-provider-aws/issues/12415)) -* data-source/aws_instance: Add `metadata_options` attribute ([#12491](https://github.com/terraform-providers/terraform-provider-aws/issues/12491)) -* data-source/aws_launch_template: Add `filter` and `tags` arguments ([#12403](https://github.com/terraform-providers/terraform-provider-aws/issues/12403)) -* data-source/aws_launch_template: Add `metadata_options` attribute ([#12491](https://github.com/terraform-providers/terraform-provider-aws/issues/12491)) -* data-source/aws_prefix_list: Add `filter` argument ([#12416](https://github.com/terraform-providers/terraform-provider-aws/issues/12416)) -* data-source/aws_vpc_endpoint_service: Add `filter` and `tags` arguments ([#12404](https://github.com/terraform-providers/terraform-provider-aws/issues/12404)) -* resource/aws_athena_workgroup: Add `force_destroy` argument ([#12254](https://github.com/terraform-providers/terraform-provider-aws/issues/12254)) -* resource/aws_cloudwatch_log_metric_filter: Support resource import ([#11992](https://github.com/terraform-providers/terraform-provider-aws/issues/11992)) -* resource/aws_flow_log: Add `max_aggregation_interval` argument ([#12483](https://github.com/terraform-providers/terraform-provider-aws/issues/12483)) -* resource/aws_instance: Add `metadata_options` configuration block (support IMDSv2) ([#12491](https://github.com/terraform-providers/terraform-provider-aws/issues/12491)) -* resource/aws_launch_template: Add `metadata_options` configuration block (support IMDSv2) ([#12491](https://github.com/terraform-providers/terraform-provider-aws/issues/12491)) -* resource/aws_msk_cluster: Add `logging_info` configuration block (support CloudWatch, Firehose, and S3 logging) ([#12215](https://github.com/terraform-providers/terraform-provider-aws/issues/12215)) -* resource/aws_mq_configuration: Support plan-time validation for `engine_type` argument ([#11843](https://github.com/terraform-providers/terraform-provider-aws/issues/11843)) -* resource/aws_route53_health_check: A dd plan-time validation to `insufficient_data_health_status` ([#12305](https://github.com/terraform-providers/terraform-provider-aws/issues/12305)) -* resource/aws_storagegateway_nfs_file_share: Add `path` attribute ([#12530](https://github.com/terraform-providers/terraform-provider-aws/issues/12530)) - -BUG FIXES: - -* resource/aws_db_instance: Allow restoring from snapshot into RAM shared Subnet with VPC Security Group ([#12447](https://github.com/terraform-providers/terraform-provider-aws/issues/12447)) -* resource/aws_mq_configuration: Remove extraneous `ListTags` API call during refresh ([#11843](https://github.com/terraform-providers/terraform-provider-aws/issues/11843)) -* resource/aws_neptune_cluster_instance: Add missing `configuring-log-exports` as allowed pending state ([#12079](https://github.com/terraform-providers/terraform-provider-aws/issues/12079)) -* resource/aws_route53_health_check: Do not recreate health check when using compressed ipv6 address ([#12305](https://github.com/terraform-providers/terraform-provider-aws/issues/12305)) - -## 2.54.0 (March 19, 2020) - -FEATURES: - -* **New Resource:** `aws_kinesis_video_stream` ([#8291](https://github.com/terraform-providers/terraform-provider-aws/issues/8291)) -* **New Resource:** `aws_securityhub_member` ([#6975](https://github.com/terraform-providers/terraform-provider-aws/issues/6975)) - -ENHANCEMENTS: - -* data-source/aws_iam_role: Add `tags` attribute ([#12349](https://github.com/terraform-providers/terraform-provider-aws/issues/12349)) -* data-source/aws_lb: Add `drop_invalid_header_fields` attribute ([#11257](https://github.com/terraform-providers/terraform-provider-aws/issues/11257)) -* provider: Support AWS shared configuration file `duration_seconds` setting for assume role ([#12359](https://github.com/terraform-providers/terraform-provider-aws/issues/12359)) -* resource/aws_backup_plan: Support resource import ([#12381](https://github.com/terraform-providers/terraform-provider-aws/issues/12381)) -* resource/aws_cognito_user_pool: Add `email_configuration` configuration block `from_email_address` argument ([#11607](https://github.com/terraform-providers/terraform-provider-aws/issues/11607)) -* resource/aws_cognito_user_pool: Add `username_configuration` configuration block (Support case insensitive usernames) ([#12317](https://github.com/terraform-providers/terraform-provider-aws/issues/12317)) -* resource/aws_cognito_user_pool_client: Add `analytics_configuration` configuration block (Support Pinpoint analytics) ([#11762](https://github.com/terraform-providers/terraform-provider-aws/issues/11762)) -* resource/aws_cognito_user_pool_client: Add `prevent_user_existence_errors` argument ([#11604](https://github.com/terraform-providers/terraform-provider-aws/issues/11604)) -* resource/aws_dlm_lifecycle_policy: Support plan-time validation for 1 hour schedules in `policy_details` `schedule` `create_rule` `interval` argument ([#12327](https://github.com/terraform-providers/terraform-provider-aws/issues/12327)) -* resource/aws_inspector_assessment_template: Add `tags` argument ([#12375](https://github.com/terraform-providers/terraform-provider-aws/issues/12375)) -* resource/aws_inspector_assessment_template: Support resource import ([#12375](https://github.com/terraform-providers/terraform-provider-aws/issues/12375)) -* resource/aws_lambda_function: Support plan-time validation for `handler` argument ([#12411](https://github.com/terraform-providers/terraform-provider-aws/issues/12411)) -* resource/aws_lb: Add `drop_invalid_header_fields` argument ([#11257](https://github.com/terraform-providers/terraform-provider-aws/issues/11257)) -* resource/aws_nat_gateway: Support tag-on-create ([#12347](https://github.com/terraform-providers/terraform-provider-aws/issues/12347)) -* resource/aws_opsworks_application: Support resource import ([#12383](https://github.com/terraform-providers/terraform-provider-aws/issues/12383)) -* resource/aws_opsworks_application: Add plan-time validation to `data_source_arn` and `data_source_type` arguments and `app_source` configuration block `type` argument ([#12383](https://github.com/terraform-providers/terraform-provider-aws/issues/12383)) -* resource/aws_opsworks_custom_layer: Add `tags` argument, `arn` attribute, and plan-time validation to `custom_instance_profile_arn` argument ([#11667](https://github.com/terraform-providers/terraform-provider-aws/issues/11667)) -* resource/aws_opsworks_ganglia_layer: Add `tags` argument, `arn` attribute, and plan-time validation to `custom_instance_profile_arn` argument ([#11667](https://github.com/terraform-providers/terraform-provider-aws/issues/11667)) -* resource/aws_opsworks_haproxy_layer: Add `tags` argument, `arn` attribute, and plan-time validation to `custom_instance_profile_arn` argument ([#11667](https://github.com/terraform-providers/terraform-provider-aws/issues/11667)) -* resource/aws_opsworks_java_app_layer: Add `tags` argument, `arn` attribute, and plan-time validation to `custom_instance_profile_arn` argument ([#11667](https://github.com/terraform-providers/terraform-provider-aws/issues/11667)) -* resource/aws_opsworks_memcached_layer: Add `tags` argument, `arn` attribute, and plan-time validation to `custom_instance_profile_arn` argument ([#11667](https://github.com/terraform-providers/terraform-provider-aws/issues/11667)) -* resource/aws_opsworks_mysql_layer: Add `tags` argument, `arn` attribute, and plan-time validation to `custom_instance_profile_arn` argument ([#11667](https://github.com/terraform-providers/terraform-provider-aws/issues/11667)) -* resource/aws_opsworks_nodejs_app_layer: Add `tags` argument, `arn` attribute, and plan-time validation to `custom_instance_profile_arn` argument ([#11667](https://github.com/terraform-providers/terraform-provider-aws/issues/11667)) -* resource/aws_opsworks_php_app_layer: Add `tags` argument, `arn` attribute, and plan-time validation to `custom_instance_profile_arn` argument ([#11667](https://github.com/terraform-providers/terraform-provider-aws/issues/11667)) -* resource/aws_opsworks_rails_app_layer: Add `tags` argument, `arn` attribute, and plan-time validation to `custom_instance_profile_arn` argument ([#11667](https://github.com/terraform-providers/terraform-provider-aws/issues/11667)) -* resource/aws_opsworks_static_web_layer: Add `tags` argument, `arn` attribute, and plan-time validation to `custom_instance_profile_arn` argument ([#11667](https://github.com/terraform-providers/terraform-provider-aws/issues/11667)) -* resource/aws_vpc_dhcp_options_association: Support resource import ([#7252](https://github.com/terraform-providers/terraform-provider-aws/issues/7252)) - -BUG FIXES: - -* resource/aws_api_gateway_rest_api: Ignore ordering differences for `endpoint_configuration` configuration block `vpc_endpoint_ids` argument ([#12350](https://github.com/terraform-providers/terraform-provider-aws/issues/12350)) -* resource/aws_backup_selection: Automatically retry on additional IAM Role eventual consistency error ([#10687](https://github.com/terraform-providers/terraform-provider-aws/issues/10687)) -* resource/aws_backup_vault: Remove resource from Terraform state when deleted outside Terraform ([#11845](https://github.com/terraform-providers/terraform-provider-aws/issues/11845)) -* resource/aws_cognito_user_pool_client: Ignore ordering differences for `callback_urls`, `logout_urls`, and `supported_identity_providers` arguments ([#12388](https://github.com/terraform-providers/terraform-provider-aws/issues/12388)) -* resource/aws_ebs_snapshot_copy: Return API errors instead of panic if unable to read snapshot ([#12283](https://github.com/terraform-providers/terraform-provider-aws/issues/12283)) -* resource/aws_kinesis_stream: Ensure `kms_key_id` argument in-place updates complete successfully ([#12008](https://github.com/terraform-providers/terraform-provider-aws/issues/12008)) -* resource/aws_lambda_alias: Propose resource recreation for `function_name` argument updates ([#11170](https://github.com/terraform-providers/terraform-provider-aws/issues/11170)) -* resource/aws_opsworks_application: Mark `app_source` configuration block `ssh_key` argument as sensitive ([#11984](https://github.com/terraform-providers/terraform-provider-aws/issues/11984)) -* resource/aws_opsworks_stack: Mark `custom_cookbooks_source` configuration block `ssh_key` argument as sensitive ([#11984](https://github.com/terraform-providers/terraform-provider-aws/issues/11984)) -* resource/aws_s3_bucket: Retry `NoSuchBucket` error when setting tags during resource creation ([#12418](https://github.com/terraform-providers/terraform-provider-aws/issues/12418)) - -## 2.53.0 (March 12, 2020) - -NOTES: - -* resource/aws_cognito_user_pool: The addition of Software Token MFA support required the use of new `GetUserPoolMfaConfig` and `SetUserPoolMfaConfig` API calls. Restrictive IAM permissions for Terraform may require updates. ([#12358](https://github.com/terraform-providers/terraform-provider-aws/issues/12358)) - -FEATURES: - -* **New Resource:** `aws_apigatewayv2_api` ([#8842](https://github.com/terraform-providers/terraform-provider-aws/issues/8842)) - - -ENHANCEMENTS: - -* resource/aws_appsync_graphql_api: Add `xray_enabled` argument ([#11972](https://github.com/terraform-providers/terraform-provider-aws/issues/11972)) -* resource/aws_cloud9_environment_ec2: Add `tags` argument ([#12132](https://github.com/terraform-providers/terraform-provider-aws/issues/12132)) -* resource/aws_cognito_user_pool: Add `software_token_mfa_configuration` configuration block (Support Time-based One-Time Password (TOTP) Multi-Factor Authentication) ([#12358](https://github.com/terraform-providers/terraform-provider-aws/issues/12358)) -* resource/aws_ec2_traffic_mirror_filter: Add `tags` argument ([#12133](https://github.com/terraform-providers/terraform-provider-aws/issues/12133)) -* resource/aws_ec2_traffic_mirror_session: Add `tags` argument ([#12134](https://github.com/terraform-providers/terraform-provider-aws/issues/12134)) -* resource/aws_ec2_traffic_mirror_target: Add `tags` argument and `network_load_balancer_arn` plan-time validation ([#12135](https://github.com/terraform-providers/terraform-provider-aws/issues/12135)) -* resource/aws_flow_log: Add `tags` argument ([#12273](https://github.com/terraform-providers/terraform-provider-aws/issues/12273)) -* resource/aws_flow_log: Add `iam_role_arn` and `log_destination` plan-time validation ([#12273](https://github.com/terraform-providers/terraform-provider-aws/issues/12273)) -* resource/aws_globalaccelerator_accelerator: Add `tags` argument ([#12309](https://github.com/terraform-providers/terraform-provider-aws/issues/12309)) -* resource/aws_vpc_endpoint: Support tag-on-create ([#12288](https://github.com/terraform-providers/terraform-provider-aws/issues/12288)) -* resource/aws_vpc_endpoint_service: Support tag-on-create and add `network_load_balancer_arns` plan-time validation ([#12290](https://github.com/terraform-providers/terraform-provider-aws/issues/12290)) - -BUG FIXES: - -* resource/aws_vpn_gateway: Automatically retry on `DetachVpnGateway` calls receiving `InvalidParameterValue: This call cannot be completed because there are pending VPNs or Virtual Interfaces` ([#11720](https://github.com/terraform-providers/terraform-provider-aws/issues/11720)) -* resource/aws_vpn_gateway_attachment: Automatically retry on `DetachVpnGateway` calls receiving `InvalidParameterValue: This call cannot be completed because there are pending VPNs or Virtual Interfaces` ([#11720](https://github.com/terraform-providers/terraform-provider-aws/issues/11720)) - -## 2.52.0 (March 06, 2020) - -FEATURES: - -* **New Data Source:** `aws_ec2_instance_type_offering` ([#12139](https://github.com/terraform-providers/terraform-provider-aws/issues/12139)) -* **New Data Source:** `aws_ec2_instance_type_offerings` ([#12139](https://github.com/terraform-providers/terraform-provider-aws/issues/12139)) - -ENHANCEMENTS: - -* resource/aws_eks_cluster: Add `encryption_config` configuration block ([#12280](https://github.com/terraform-providers/terraform-provider-aws/issues/12280)) -* resource/aws_globalaccelerator_accelerator: Add `dns_name` and `hosted_zone_id` attributes ([#11670](https://github.com/terraform-providers/terraform-provider-aws/issues/11670)) -* resource/aws_lb_target_group: Add `load_balancing_algorithm_type` argument (support Least Outstanding Requests algorithm for Application Load Balancers) ([#11141](https://github.com/terraform-providers/terraform-provider-aws/issues/11141)) -* resource/aws_s3_bucket: Add `grant` to implement ACL policy grants ([#3728](https://github.com/terraform-providers/terraform-provider-aws/issues/3728)) - -BUG FIXES: - -* resource/aws_iam_service_linked_role: Allow `aws_service_name` argument validation to accept values in AWS partitions outside AWS Commercial and AWS GovCloud (US) ([#11919](https://github.com/terraform-providers/terraform-provider-aws/issues/11919)) -* resource/aws_lambda_function_event_invoke_config: Retry on additional IAM eventual consistency error with SNS Topic destinations ([#12171](https://github.com/terraform-providers/terraform-provider-aws/issues/12171)) -* resource/aws_media_store_container: Prevent `ValidationException` error on creation when no tags are configured ([#12170](https://github.com/terraform-providers/terraform-provider-aws/issues/12170)) - -## 2.51.0 (February 28, 2020) - -FEATURES: - -* **New Data Source:** `aws_sfn_activity` ([#11080](https://github.com/terraform-providers/terraform-provider-aws/issues/11080)) -* **New Data Source:** `aws_sfn_state_machine` ([#10932](https://github.com/terraform-providers/terraform-provider-aws/issues/10932)) -* **New Resource:** `aws_ec2_traffic_mirror_filter` ([#9372](https://github.com/terraform-providers/terraform-provider-aws/issues/9372)) -* **New Resource:** `aws_ec2_traffic_mirror_filter_rule` ([#9372](https://github.com/terraform-providers/terraform-provider-aws/issues/9372)) -* **New Resource:** `aws_ec2_traffic_mirror_session` ([#9372](https://github.com/terraform-providers/terraform-provider-aws/issues/9372)) -* **New Resource:** `aws_ec2_traffic_mirror_target` ([#9372](https://github.com/terraform-providers/terraform-provider-aws/issues/9372)) -* **New Resource:** `aws_s3_access_point` ([#11276](https://github.com/terraform-providers/terraform-provider-aws/issues/11276)) - -ENHANCEMENTS: - -* data-source/aws_lambda_layer_version: Support plan-time validation for `compatible_runtime` argument `ruby2.7` value ([#12116](https://github.com/terraform-providers/terraform-provider-aws/issues/12116)) -* resource/aws_dx_hosted_private_virtual_interface: Add `amazon_side_asn` attribute ([#11415](https://github.com/terraform-providers/terraform-provider-aws/issues/11415)) -* resource/aws_dx_hosted_public_virtual_interface: Add `amazon_side_asn` attribute ([#11415](https://github.com/terraform-providers/terraform-provider-aws/issues/11415)) -* resource/aws_dx_hosted_transit_virtual_interface: Add `amazon_side_asn` attribute ([#11415](https://github.com/terraform-providers/terraform-provider-aws/issues/11415)) -* resource/aws_dx_private_virtual_interface: Add `amazon_side_asn` attribute ([#11415](https://github.com/terraform-providers/terraform-provider-aws/issues/11415)) -* resource/aws_dx_public_virtual_interface: Add `amazon_side_asn` attribute ([#11415](https://github.com/terraform-providers/terraform-provider-aws/issues/11415)) -* resource/aws_dx_transit_virtual_interface: Add `amazon_side_asn` attribute ([#11415](https://github.com/terraform-providers/terraform-provider-aws/issues/11415)) -* resource/aws_glue_job: Add `notification_property` configuration block ([#12115](https://github.com/terraform-providers/terraform-provider-aws/issues/12115)) -* resource/aws_lambda_event_source_mapping: Add `bisect_batch_on_function_error`, `maximum_record_age_in_seconds`, `maximum_retry_attempts`, and `parallelization_factor` arguments ([#11100](https://github.com/terraform-providers/terraform-provider-aws/issues/11100)) -* resource/aws_lambda_event_source_mapping: Add `destination_config` configuration block ([#11100](https://github.com/terraform-providers/terraform-provider-aws/issues/11100)) -* resource/aws_lambda_function: Support plan-time validation for `runtime` argument `ruby2.7` value ([#12116](https://github.com/terraform-providers/terraform-provider-aws/issues/12116)) -* resource/aws_lambda_layer_version: Support plan-time validation for `compatible_runtimes` argument `ruby2.7` value ([#12116](https://github.com/terraform-providers/terraform-provider-aws/issues/12116)) -* resource/aws_msk_cluster: Support in-place updates to `enhanced_monitoring` and `number_of_broker_nodes` arguments ([#11451](https://github.com/terraform-providers/terraform-provider-aws/issues/11451)) -* resource/aws_msk_cluster: Add `open_monitoring` configuration block (support Prometheus monitoring configuration) ([#11451](https://github.com/terraform-providers/terraform-provider-aws/issues/11451)) - -BUG FIXES: - -* resource/aws_workspaces_directory: Prevent panic and remove resource from Terraform state if removed outside Terraform ([#11837](https://github.com/terraform-providers/terraform-provider-aws/issues/11837)) - -## 2.50.0 (February 20, 2020) - -NOTES: - -* resource/aws_lambda_function: The `publish` argument now will also publish versions for configuration updates. This is accomplished via a separate `PublishVersion` API call, where before the publishing only occurred via the `Publish` parameter of the `UpdateFunctionCode` API call. Restrictive IAM permissions for Terraform may require updates. ([#11211](https://github.com/terraform-providers/terraform-provider-aws/issues/11211)) -* resource/aws_ram_resource_share_accepter: The `status` attribute now reflects the status of the RAM Resource Share and not the RAM Resource Share Invitation (which expires after 7 days). ([#11562](https://github.com/terraform-providers/terraform-provider-aws/issues/11562)) - -FEATURES: - -* **New Data Source:** `aws_lambda_alias` ([#9490](https://github.com/terraform-providers/terraform-provider-aws/issues/9490)) - -ENHANCEMENTS: - -* resource/aws_appmesh_route: Add `priority` and `header` attributes to support route priorities and HTTP header-based routing ([#10402](https://github.com/terraform-providers/terraform-provider-aws/issues/10402)) -* resource/aws_iam_access_key: Add `ses_smtp_password_v4` attribute (add per-region SigV4 support) ([#11144](https://github.com/terraform-providers/terraform-provider-aws/issues/11144)) -* resource/aws_security_group: Support import of `name_prefix` argument ([#12052](https://github.com/terraform-providers/terraform-provider-aws/issues/12052)) -* resource/aws_transfer_server: Add `host_key` argument and `host_key_fingerprint` attribute ([#8913](https://github.com/terraform-providers/terraform-provider-aws/issues/8913)) - -BUG FIXES: - -* resource/aws_lambda_function: If `publish` argument is enabled, also publish new versions on function configuration-only updates in addition to function code updates ([#11211](https://github.com/terraform-providers/terraform-provider-aws/issues/11211)) -* resource/aws_lambda_permission: Fix error when Lambda permission is deleted out-of-band ([#11924](https://github.com/terraform-providers/terraform-provider-aws/issues/11924)) -* resource/aws_ram_resource_share_accepter: Fix read operations after the RAM Resource Share Invitation is no longer present after 7 days ([#11562](https://github.com/terraform-providers/terraform-provider-aws/issues/11562)) - -## 2.49.0 (February 14, 2020) - -FEATURES: - -* **New Resource:** `aws_codestarnotifications_notification_rule` ([#10991](https://github.com/terraform-providers/terraform-provider-aws/issues/10991)) -* **New Resource:** `aws_s3_bucket_analytics_configuration` ([#11874](https://github.com/terraform-providers/terraform-provider-aws/issues/11874)) - -ENHANCEMENTS: - -* data-source/aws_api_gateway_rest_api: Add `api_key_source`, `arn`, `binary_media_types`, `description`, `endpoint_configuration`, `execution_arn`, `minimum_compression_size`, `policy`, and `tags` attributes ([#10971](https://github.com/terraform-providers/terraform-provider-aws/issues/10971)) -* resource/aws_db_instance: Support `agent` value in `enable_cloudwatch_logs_exports` argument plan-time validation (Support MSSQL agent log) ([#11472](https://github.com/terraform-providers/terraform-provider-aws/issues/11472)) -* resource/aws_db_instance: Add `delete_automated_backups` argument ([#8461](https://github.com/terraform-providers/terraform-provider-aws/issues/8461)) -* resource/aws_gamelift_fleet: Add `tags` argument ([#11559](https://github.com/terraform-providers/terraform-provider-aws/issues/11559)) -* resource/aws_instance: Add `hibernation` argument ([#6961](https://github.com/terraform-providers/terraform-provider-aws/issues/6961)) -* resource/aws_launch_template: Add `cpu_options` configuration block (support disabling multithreading) ([#6552](https://github.com/terraform-providers/terraform-provider-aws/issues/6552)) -* resource/aws_neptune_cluster: Add `enable_cloudwatch_logs_exports` argument (support audit logging) ([#11949](https://github.com/terraform-providers/terraform-provider-aws/issues/11949)) -* resource/aws_neptune_cluster: Add `deletion_protection` argument ([#11731](https://github.com/terraform-providers/terraform-provider-aws/issues/11731)) -* resource/aws_rds_global_database: Support `aurora-mysql` value in `engine` argument plan-time validation (Support Aurora MySQL 5.7) ([#11790](https://github.com/terraform-providers/terraform-provider-aws/issues/11790)) - -BUG FIXES: - -* data-source/aws_route53_zone: Fixes regression from version 2.48.0 when filtering using `tags` ([#11953](https://github.com/terraform-providers/terraform-provider-aws/issues/11953)) -* resource/aws_batch_job_definition: Prevent extraneous differences with `container_properties` argument missing `environment`, `mountPoints`, `ulimits`, and `volumes` configuration ([#12000](https://github.com/terraform-providers/terraform-provider-aws/issues/12000)) -* resource/aws_cognito_user_pool: Allow `admin_create_user_config` configuration block `unused_account_validity_days` argument to be omitted ([#12001](https://github.com/terraform-providers/terraform-provider-aws/issues/12001)) -* resource/aws_launch_configuration: Fixes regression from version 2.23.0 with instance store AMIs returning an unexpected error ([#9810](https://github.com/terraform-providers/terraform-provider-aws/issues/9810)) -* resource/aws_launch_configuration: Fixes regression from version 2.23.0 to allow missing EC2 Image during root block device lookup ([#12009](https://github.com/terraform-providers/terraform-provider-aws/issues/12009)) -* resource/aws_route53_record: The artificial, hardcoded five minute timeouts for creation and deletions have been removed in preference of the default AWS Go SDK retrying logic ([#11895](https://github.com/terraform-providers/terraform-provider-aws/issues/11895)) - -## 2.48.0 (February 07, 2020) - -NOTES: - -* resource/aws_organizations_policy_attachment: The underlying API calls have switched from `ListPoliciesForTarget` to `ListTargetsForPolicy`. Restrictive IAM Policies for Terraform execution may require updates. ([#11612](https://github.com/terraform-providers/terraform-provider-aws/issues/11612)) - -FEATURES: - -* **New Data Source:** `aws_ssm_patch_baseline` ([#9486](https://github.com/terraform-providers/terraform-provider-aws/issues/9486)) -* **New Resource:** `aws_datasync_location_smb` ([#10381](https://github.com/terraform-providers/terraform-provider-aws/issues/10381)) - -ENHANCEMENTS: - -* resource/aws_batch_job_definition: Support resource import ([#11407](https://github.com/terraform-providers/terraform-provider-aws/issues/11407)) -* resource/aws_codebuild_project: Add `source` and `secondary_source` configuration block `git_submodules_config` configuration block ([#10952](https://github.com/terraform-providers/terraform-provider-aws/issues/10952)) -* resource/aws_codebuild_project: Add `source_version` argument ([#9877](https://github.com/terraform-providers/terraform-provider-aws/issues/9877)) -* resource/aws_elasticache_cluster: Add `computed` flag for `port` property and set to true ([#10017](https://github.com/terraform-providers/terraform-provider-aws/issues/10017)) -* resource/aws_fsx_lustre_file_system: Lower minimum `storage_capacity` argument validation to 1200 to match API updates ([#11847](https://github.com/terraform-providers/terraform-provider-aws/issues/11847)) -* resource/aws_organizations_policy: Support `type` argument `TAG_POLICY` value in plan-time validation ([#11612](https://github.com/terraform-providers/terraform-provider-aws/issues/11612)) -* resource/aws_organizations_policy_attachment: Support tag policies ([#11612](https://github.com/terraform-providers/terraform-provider-aws/issues/11612)) - -BUG FIXES: - -* resource/aws_appautoscaling_target: Prevent state removal of resource immediately after creation due to eventual consistency ([#11819](https://github.com/terraform-providers/terraform-provider-aws/issues/11819)) -* resource/aws_appautoscaling_target: Automatically retry creation on `ValidationException: ECS service doesn't exist` for ECS eventual consistency ([#11693](https://github.com/terraform-providers/terraform-provider-aws/issues/11693)) -* resource/aws_batch_job_definition: Properly set `container_properties` and `name` into Terraform state and perform drift detection ([#11488](https://github.com/terraform-providers/terraform-provider-aws/issues/11488)) -* resource/aws_cloudformation_stack_set: Wait for update operation completion (default timeout of 30 minutes) and report any errors ([#11726](https://github.com/terraform-providers/terraform-provider-aws/issues/11726)) -* resource/aws_cloudwatch_log_stream: Prevent state removal of resource immediately after creation due to eventual consistency ([#11617](https://github.com/terraform-providers/terraform-provider-aws/issues/11617)) -* resource/aws_codedeploy_deployment_group: Fixes unexpected behaviour when removing block attributes ([#11648](https://github.com/terraform-providers/terraform-provider-aws/issues/11648)) -* resource/aws_default_security_group: Ensure `description` attribute is written into Terraform state ([#11650](https://github.com/terraform-providers/terraform-provider-aws/issues/11650)) -* resource/aws_dynamodb_table: Skip `ResourceNotFoundException` error during deletion ([#11692](https://github.com/terraform-providers/terraform-provider-aws/issues/11692)) -* resource/aws_ec2_client_vpn_endpoint: Ensure `dns_servers` attribute is refreshed in Terraform state ([#11889](https://github.com/terraform-providers/terraform-provider-aws/issues/11889)) -* resource/aws_ecs_cluster: Delay check of ECS Cluster status during creation for ECS eventual consistency ([#11701](https://github.com/terraform-providers/terraform-provider-aws/issues/11701)) -* resource/aws_kinesis_firehose_delivery_stream: Allow processors to be cleared from extended S3 configuration ([#11649](https://github.com/terraform-providers/terraform-provider-aws/issues/11649)) -* resource/aws_network_acl_rule: Trigger resource recreation instead of error when same number rule (but opposite ingress/egress) is removed ([#11544](https://github.com/terraform-providers/terraform-provider-aws/issues/11544)) -* resource/aws_placement_group: Additional handling for creation and deletion eventual consistency ([#11671](https://github.com/terraform-providers/terraform-provider-aws/issues/11671)) -* resource/aws_s3_bucket: Retry read after creation for 404 status code and prevent 2 minute delay for triggering recreation on existing resources deleted outside Terraform ([#11894](https://github.com/terraform-providers/terraform-provider-aws/issues/11894)) - -## 2.47.0 (January 30, 2020) - -NOTES: - -* resource/aws_efs_file_system: Tagging API calls have been refactored to the AWS standardized `TagResource` and `UntagResource` API calls (from `CreateTags` and `DeleteTags` respectively). Restrictive IAM Policies for Terraform execution may require updates. ([#11654](https://github.com/terraform-providers/terraform-provider-aws/issues/11654)) - -ENHANCEMENTS: - -* data-source/aws_api_gateway_vpc_link: Add `description`, `status`, `status_message`, `tags`, and `target_arns` attributes ([#10822](https://github.com/terraform-providers/terraform-provider-aws/issues/10822)) -* data-source/aws_dynamodb_table: Add `server_side_encryption` `kms_key_arn` attribute ([#11081](https://github.com/terraform-providers/terraform-provider-aws/issues/11081)) -* data-source/aws_efs_file_system: Add `lifecycle_policy`, `provisioned_throughput_in_mibps`, and `throughput_mode` attributes ([#11647](https://github.com/terraform-providers/terraform-provider-aws/issues/11647)) -* data-source/aws_kms_key: Add `customer_master_key_spec` attribute ([#11062](https://github.com/terraform-providers/terraform-provider-aws/issues/11062)) -* resource/aws_dynamodb_table: Add `server_side_encryption` configuration block `kms_key_arn` argument (support customer managed CMKs for server-side encryption) ([#11081](https://github.com/terraform-providers/terraform-provider-aws/issues/11081)) -* resource/aws_dynamodb_table: Support in-place updates for `server_side_encryption` configurations ([#11081](https://github.com/terraform-providers/terraform-provider-aws/issues/11081)) -* resource/aws_elasticsearch_domain: Add `domain_endpoint_options` configuration block (support enforcing HTTPS) ([#10430](https://github.com/terraform-providers/terraform-provider-aws/issues/10430)) -* resource/aws_gamelift_fleet: Add `fleet_type` argument (support Spot Fleets) ([#8234](https://github.com/terraform-providers/terraform-provider-aws/issues/8234)) -* resource/aws_kms_key: Add `customer_master_key_spec` argument and plan-time validation support for `key_usage` value `SIGN_VERIFY` (support asymmetric keys) ([#11062](https://github.com/terraform-providers/terraform-provider-aws/issues/11062)) -* resource/aws_sagemaker_notebook_instance: Add `direct_internet_access` argument ([#8618](https://github.com/terraform-providers/terraform-provider-aws/issues/8618)) -* resource/aws_ssm_activation: Add `automation_target_parameter_name` argument ([#11755](https://github.com/terraform-providers/terraform-provider-aws/issues/11755)) -* resource/aws_ssm_document: Add `target_type` argument ([#11479](https://github.com/terraform-providers/terraform-provider-aws/issues/11479)) -* resource/aws_ssm_maintenance_window: Add `description` argument ([#11478](https://github.com/terraform-providers/terraform-provider-aws/issues/11478)) -* resource/aws_storagegateway_gateway: Add `cloudwatch_log_group_arn` argument ([#10939](https://github.com/terraform-providers/terraform-provider-aws/issues/10939)) - -BUG FIXES: - -* data-source/aws_api_gateway_rest_api: Fixes `root_resource_id` not being set on correctly when REST API contains more than 25 resources ([#11705](https://github.com/terraform-providers/terraform-provider-aws/issues/11705)) -* resource/aws_cloudwatch_log_subscription_filter: Perform eventual consistency retries on update ([#11739](https://github.com/terraform-providers/terraform-provider-aws/issues/11739)) -* resource/aws_cognito_user_pool: Deprecate `unused_account_validity_days` argument and add support for `temporary_password_validity_days` argument ([#10890](https://github.com/terraform-providers/terraform-provider-aws/issues/10890)) -* resource/aws_elasticsearch_domain: Automatically retry resource creation on additional error messages relating to eventual consistency ([#11663](https://github.com/terraform-providers/terraform-provider-aws/issues/11663)) -* resource/aws_elasticsearch_domain: Ensure in-place version upgrade is fully successful before returning ([#11793](https://github.com/terraform-providers/terraform-provider-aws/issues/11793)) -* resource/aws_emr_instance_group: Wait for `RUNNING` status on creation ([#11688](https://github.com/terraform-providers/terraform-provider-aws/issues/11688)) -* resource/aws_ssm_activation: Properly trigger resource recreation when deleted outside Terraform ([#11658](https://github.com/terraform-providers/terraform-provider-aws/issues/11658)) -* resource/aws_ssm_parameter: Prevent `KeyId` error when switching `type` value from `SecureString` to `String` ([#10819](https://github.com/terraform-providers/terraform-provider-aws/issues/10819)) -* service/efs: Generate proper `dns_name` attribute hostname suffix in AWS China, AWS C2S, and AWS SC2S partitions ([#11746](https://github.com/terraform-providers/terraform-provider-aws/issues/11746)) - -## 2.46.0 (January 23, 2020) - -NOTES: - -* provider: Terraform AWS Provider version 2.45.0 included AWS Go SDK version 1.28.0, which contained a regression in error handling behavior across many services that either prevented or incorrectly modified error messages from being surfaced by the API. Other than confusing errors in certain cases, this also affected automatic retry logic in a few resources. This release contains an AWS Go SDK update which should resolve these issues. - -ENHANCEMENTS: - -* data-source/aws_api_gateway_api_key: Add `created_date`, `description`, `enabled`, `last_updated_date`, and `tags` attributes ([#10821](https://github.com/terraform-providers/terraform-provider-aws/issues/10821)) -* data-source/aws_cloudwatch_log_group: Add `kms_key_id`, `retention_in_days`, and `tags` attributes ([#10755](https://github.com/terraform-providers/terraform-provider-aws/issues/10755)) -* data-source/aws_db_instance: Add `multi_az` attribute ([#10795](https://github.com/terraform-providers/terraform-provider-aws/issues/10795)) -* data-source/aws_sqs_queue: Add `tags` attribute ([#10820](https://github.com/terraform-providers/terraform-provider-aws/issues/10820)) -* resource/aws_acm_certificate: Support tag-on-create ([#11073](https://github.com/terraform-providers/terraform-provider-aws/issues/11073)) -* resource/aws_api_gateway_rest_api: Add `endpoint_configuration` configuration block `vpc_endpoint_ids` argument ([#10627](https://github.com/terraform-providers/terraform-provider-aws/issues/10627)) -* resource/aws_cloudfront_distribution: Validate `origin_group` configuration block `member` argument contains max 2 items ([#10357](https://github.com/terraform-providers/terraform-provider-aws/issues/10357)) -* resource/aws_cognito_user_pool_client: Support plan-time validation values of `ALLOW_*` variations for `explicit_auth_flows` argument ([#10976](https://github.com/terraform-providers/terraform-provider-aws/issues/10976)) -* resource/aws_ecs_task_definition: Add `volume` configuration block `efs_volume_configuration` configuration block (support preview EFS volume configuration) ([#11707](https://github.com/terraform-providers/terraform-provider-aws/issues/11707)) -* resource/aws_ecs_task_definition: Add plan-time validation for `execution_role_arn` argument, `placement_constraints` configuration block `type` argument, and `task_role_arn` argument ([#11707](https://github.com/terraform-providers/terraform-provider-aws/issues/11707)) -* resource/aws_egress_only_internet_gateway: Support resource import ([#11071](https://github.com/terraform-providers/terraform-provider-aws/issues/11071)) -* resource/aws_key_pair: Add `tags` argument and `key_pair_id` attribute ([#11481](https://github.com/terraform-providers/terraform-provider-aws/issues/11481)) -* resource/aws_network_interface: Add `mac_address` attribute ([#10633](https://github.com/terraform-providers/terraform-provider-aws/issues/10633)) -* resource/aws_organization_organization: Support plan-time validation value of `TAG_POLICY` in `enabled_policy_types` argument ([#11535](https://github.com/terraform-providers/terraform-provider-aws/issues/11535)) -* resource/aws_placement_group: Add `tags` argument and `placement_group_id` attribute ([#11482](https://github.com/terraform-providers/terraform-provider-aws/issues/11482)) -* resource/aws_rds_cluster_endpoint: Add `tags` argument ([#11074](https://github.com/terraform-providers/terraform-provider-aws/issues/11074)) - -BUG FIXES: - -* data-source/aws_acmpca_certificate_authority: Properly set `not_after` and `not_before` values into the Terraform state ([#11491](https://github.com/terraform-providers/terraform-provider-aws/issues/11491)) -* provider: Upgrade AWS Go SDK dependency to fix missing/incorrect API error messages and missing retries regression introduced in Terraform AWS Provider version 2.45.0 ([#11727](https://github.com/terraform-providers/terraform-provider-aws/issues/11727)) -* resource/aws_acmpca_certificate_authority: Properly set `not_after` and `not_before` values into the Terraform state ([#11491](https://github.com/terraform-providers/terraform-provider-aws/issues/11491)) -* resource/aws_api_gateway_account: Update retryable error message handling for recent API update ([#11735](https://github.com/terraform-providers/terraform-provider-aws/issues/11735)) -* resource_aws_cognito_resource_server: Increase `scope` max limit to match API ([#10505](https://github.com/terraform-providers/terraform-provider-aws/issues/10505)) -* resource_aws_cognito_user_pool_client: Increase `allowed_oauth_scopes` max limit to match API ([#10505](https://github.com/terraform-providers/terraform-provider-aws/issues/10505)) -* resource/aws_dms_certificate: Properly set `certificate_wallet` value into Terraform state ([#11496](https://github.com/terraform-providers/terraform-provider-aws/issues/11496)) -* resource/aws_ec2_client_vpn_endpoint: Properly set `status` value into Terraform state ([#11497](https://github.com/terraform-providers/terraform-provider-aws/issues/11497)) -* resource/aws_ecs_task_definition: Properly refresh `ipc_mode` and `pid_mode` attributes in Terraform state for drift detection ([#11707](https://github.com/terraform-providers/terraform-provider-aws/issues/11707)) -* resource/aws_emr_security_configuration: Properly set `creation_date` value into the Terraform state ([#11491](https://github.com/terraform-providers/terraform-provider-aws/issues/11491)) -* resource/aws_iam_service_linked_role: Properly set `create_date` value into the Terraform state ([#11491](https://github.com/terraform-providers/terraform-provider-aws/issues/11491)) -* resource/aws_iot_topic_rule: Trigger resource recreation on `name` argument updates ([#10366](https://github.com/terraform-providers/terraform-provider-aws/issues/10366)) -* resource/aws_lambda_event_source_mapping: Properly set `last_modified` value into the Terraform state ([#11491](https://github.com/terraform-providers/terraform-provider-aws/issues/11491)) -* resource/aws_organizations_account: Properly set `joined_timestamp` value into the Terraform state ([#11491](https://github.com/terraform-providers/terraform-provider-aws/issues/11491)) -* resource/aws_redshift_cluster: Handle `available, prep-for-resize` pending status during creation and update ([#10530](https://github.com/terraform-providers/terraform-provider-aws/issues/10530)) -* resource/aws_ssm_activation: Properly set `expiration_date` value into the Terraform state and perform drift detection when configured ([#11491](https://github.com/terraform-providers/terraform-provider-aws/issues/11491)) -* resource/aws_ssm_document: Properly set `created_date` value into the Terraform state ([#11491](https://github.com/terraform-providers/terraform-provider-aws/issues/11491)) -* resource/aws_waf_sql_injection_match_set: Properly set `sql_injection_match_tuples` value into Terraform state ([#11498](https://github.com/terraform-providers/terraform-provider-aws/issues/11498)) - -## 2.45.0 (January 17, 2020) - -ENHANCEMENTS: - -* resource/aws_codepipeline_webhook: Support in-place `tags` updates ([#11387](https://github.com/terraform-providers/terraform-provider-aws/issues/11387)) -* resource/aws_db_parameter_group: Support resetting parameter group values ([#11540](https://github.com/terraform-providers/terraform-provider-aws/issues/11540)) -* resource/aws_docdb_cluster: Support `profiler` CloudWatch export type ([#11051](https://github.com/terraform-providers/terraform-provider-aws/issues/11051)) -* resource/aws_gamelift_alias: Add `tags` argument ([#11486](https://github.com/terraform-providers/terraform-provider-aws/issues/11486)) -* resource/aws_gamelift_build: Add `tags` argument and `arn` attribute ([#11486](https://github.com/terraform-providers/terraform-provider-aws/issues/11486)) -* resource/aws_gamelift_fleet - Add support for instance_role_arn ([#11553](https://github.com/terraform-providers/terraform-provider-aws/issues/11553)) -* resource/aws_gamelift_game_session_queue: Add `tags` argument ([#11486](https://github.com/terraform-providers/terraform-provider-aws/issues/11486)) -* resource/aws_neptune_parameter_group: Support tag-on-create ([#11245](https://github.com/terraform-providers/terraform-provider-aws/issues/11245)) -* resource/aws_pinpoint_app: Add plan-time validation for `limit` configuration block `daily`, `maximum_duration`, `messages_per_second` and `total` arguments ([#11368](https://github.com/terraform-providers/terraform-provider-aws/issues/11368)) -* resource/aws_rds_cluster: Allow enabling Aurora Serverless HTTP endpoint (Data API) with `enable_http_endpoint` ([#11048](https://github.com/terraform-providers/terraform-provider-aws/issues/11048)) -* resource/aws_rds_cluster_parameter_group: Support resetting parameter group values ([#11540](https://github.com/terraform-providers/terraform-provider-aws/issues/11540)) -* resource/aws_ssm_document: Add support for "Package" document type ([#11492](https://github.com/terraform-providers/terraform-provider-aws/issues/11492)) -* resource/aws_vpc_peering_connection_accepter: Support resource import ([#4486](https://github.com/terraform-providers/terraform-provider-aws/issues/4486)) - -BUG FIXES: - -* resource/aws_autoscaling_group: Prevent indefinite wait for desired capacity to be available when instance_weight specified and >=1 ([#11357](https://github.com/terraform-providers/terraform-provider-aws/issues/11357)) -* resource/aws_cloudwatch_event_rule: Retry deletion on CloudWatch Events Target deletion eventual consistency ([#11475](https://github.com/terraform-providers/terraform-provider-aws/issues/11475)) -* resource/aws_cloudwatch_event_target: Return failed entry error code and message if provided in `RemoveTargets` response ([#11475](https://github.com/terraform-providers/terraform-provider-aws/issues/11475)) -* resource/aws_codepipeline_webhook: Properly trigger resource recreation when `authentication_configuration` configuration block `allowed_ip_range` and `secret_token` arguments change ([#11387](https://github.com/terraform-providers/terraform-provider-aws/issues/11387)) -* resource/aws_emr_cluster: Prevent perpetual difference with `ec2_attributes` configuration block `emr_managed_master_security_group`, `emr_managed_slave_security_group`, and `service_access_security_groups` arguments when omitted (support EMR Managed Security Groups) ([#5493](https://github.com/terraform-providers/terraform-provider-aws/issues/5493)) -* resource/aws_opsworks_permission: Prevent `Unable to change own permission level` error during self updates ([#11379](https://github.com/terraform-providers/terraform-provider-aws/issues/11379)) - -## 2.44.0 (January 09, 2020) - -FEATURES: - -* **New Data Source:** `aws_directory_service_directory` ([#11282](https://github.com/terraform-providers/terraform-provider-aws/issues/11282)) -* **New Resource:** `aws_workspaces_directory` ([#11023](https://github.com/terraform-providers/terraform-provider-aws/issues/11023)) - -ENHANCEMENTS: - -* data-source/aws_launch_configuration: Add `arn` attribute ([#11416](https://github.com/terraform-providers/terraform-provider-aws/issues/11416)) -* data-source/aws_eks_cluster: Add `vpc_config` list `public_access_cidrs` attribute ([#11442](https://github.com/terraform-providers/terraform-provider-aws/issues/11442)) -* resource/aws_ami_launch_permission: Support resource import ([#11437](https://github.com/terraform-providers/terraform-provider-aws/issues/11437)) -* resource/aws_api_gateway_authorizer: Support resource import ([#11436](https://github.com/terraform-providers/terraform-provider-aws/issues/11436)) -* resource/aws_api_gateway_authorizer: Add plan time validation for `provider_arns` argument ([#11436](https://github.com/terraform-providers/terraform-provider-aws/issues/11436)) -* resource/aws_api_gateway_usage_plan_key: Support resource import ([#11439](https://github.com/terraform-providers/terraform-provider-aws/issues/11439)) -* resource/aws_batch_compute_environment: Add `compute_environment_name_prefix` argument and make `compute_environment_name` argument optional (support full name generation) ([#10682](https://github.com/terraform-providers/terraform-provider-aws/issues/10682)) -* resource/aws_batch_compute_environment: Add `compute_resources` configuration block `allocation_strategy` argument ([#10894](https://github.com/terraform-providers/terraform-provider-aws/issues/10894)) -* resource/aws_batch_job_queue: Support resource import ([#11406](https://github.com/terraform-providers/terraform-provider-aws/issues/11406)) -* resource/aws_cloudformation_stack: Prevent difference with `Transform` templates showing processed template (support SAM templates) ([#9006](https://github.com/terraform-providers/terraform-provider-aws/issues/9006)) -* resource/aws_cloudwatch_event_rule: Support tag-on-create ([#11346](https://github.com/terraform-providers/terraform-provider-aws/issues/11346)) -* resource/aws_db_instance: Remove `identifier_prefix` 16 character truncation for `sqlserver` engine ([#9040](https://github.com/terraform-providers/terraform-provider-aws/issues/9040)) -* resource/aws_ecs_service: Add plan time validation for `launch_type`, `load_balancer` configuration block `target_group_arn` and `container_port`, and `placement_constraints` configuration block `type` arguments ([#11423](https://github.com/terraform-providers/terraform-provider-aws/issues/11423)) -* resource/aws_eks_cluster: Add `vpc_config` configuration block `public_access_cidrs` argument ([#11442](https://github.com/terraform-providers/terraform-provider-aws/issues/11442)) -* resource/aws_elasticache_cluster: Add `arn` attribute ([#11243](https://github.com/terraform-providers/terraform-provider-aws/issues/11243)) -* resource/aws_launch_configuration: Add `arn` attribute ([#11416](https://github.com/terraform-providers/terraform-provider-aws/issues/11416)) -* resource/aws_lb: Add plan-time validation for `ip_address_type` and `load_balancer_type` arguments ([#11419](https://github.com/terraform-providers/terraform-provider-aws/issues/11419)) -* resource/aws_rds_cluster_instance: Allow updating `ca_cert_identifier` for `aws_rds_cluster_instance` ([#10954](https://github.com/terraform-providers/terraform-provider-aws/issues/10954)) -* resource/aws_wafregional_xss_match_set: Support resource import ([#11432](https://github.com/terraform-providers/terraform-provider-aws/issues/11432)) - -BUG FIXES: - -* provider: Allow `aws` account ID in ARN validation (support ARNs such as AWS Managed IAM Policies) ([#11450](https://github.com/terraform-providers/terraform-provider-aws/issues/11450)) -* provider: Support AWS C2S/SC2S Regional ARNs in ARN validation ([#11471](https://github.com/terraform-providers/terraform-provider-aws/issues/11471)) -* resource/aws_api_gateway_usage_plan_key: Ensure Terraform performs drift detection of `key_type` argument ([#11439](https://github.com/terraform-providers/terraform-provider-aws/issues/11439)) -* resource/aws_appautoscaling_policy: Prevent potential state removal of resource immediately after creation due to eventual consistency ([#11222](https://github.com/terraform-providers/terraform-provider-aws/issues/11222)) -* resource/aws_cloudwatch_dashboard: Trigger resource recreation on `dashboard_name` updates (prevent dangling resource) ([#9784](https://github.com/terraform-providers/terraform-provider-aws/issues/9784)) -* resource/aws_cloudwatch_event_rule: Improved handling of `is_enabled` argument ([#11346](https://github.com/terraform-providers/terraform-provider-aws/issues/11346)) -* resource/aws_ecs_service: Automatically retry IAM Service Linked Role assume role error on creation due to asynchronous creation of role on first usage and IAM eventual consistency ([#11423](https://github.com/terraform-providers/terraform-provider-aws/issues/11423)) -* resource/aws_iam_instance: Allows for instance profiles to be changed when instances are in stopped state ([#11104](https://github.com/terraform-providers/terraform-provider-aws/issues/11104)) -* resource/aws_opsworks_stack: Ensure `tags` are refreshed in Terraform state during read for drift detection ([#11373](https://github.com/terraform-providers/terraform-provider-aws/issues/11373)) -* resource/aws_rds_cluster_instance: Prevent `is already being deleted` error on deletion and wait for deletion completion ([#11468](https://github.com/terraform-providers/terraform-provider-aws/issues/11468)) - -## 2.43.0 (December 19, 2019) - -NOTES: - -* This will be the last planned release until early January. Enjoy the rest of your year! - -FEATURES: - -* **New Data Source:** `aws_organizations_organizational_units` ([#10395](https://github.com/terraform-providers/terraform-provider-aws/issues/10395)) -* **New Resource:** `aws_accessanalyzer_analyzer` ([#11169](https://github.com/terraform-providers/terraform-provider-aws/issues/11169)) -* **New Resource:** `aws_lambda_function_event_invoke_config` ([#11165](https://github.com/terraform-providers/terraform-provider-aws/issues/11165)) - -ENHANCEMENTS: - -* data-source/aws_elb: Add `arn` attribute ([#11345](https://github.com/terraform-providers/terraform-provider-aws/issues/11345)) -* resource/aws_batch_compute_environment: Support resource import ([#11299](https://github.com/terraform-providers/terraform-provider-aws/issues/11299)) -* resource/aws_codebuild_project: Add `queued_timeout` argument ([#11261](https://github.com/terraform-providers/terraform-provider-aws/issues/11261)) -* resource/aws_fsx_windows_file_system: Support `storage_capacity` minimum value of `32` in validation to match recent updates to the API ([#11272](https://github.com/terraform-providers/terraform-provider-aws/issues/11272)) -* resource/aws_opsworks_custom_layer: Add `encrypted` `ebs_volume` configuration ([#7110](https://github.com/terraform-providers/terraform-provider-aws/issues/7110)) - -BUG FIXES: - -* resource/aws_datasync_agent: Trigger resource recreation on updated `InvalidRequestException` error for agents deleted outside Terraform ([#11005](https://github.com/terraform-providers/terraform-provider-aws/issues/11005)) -* resource/aws_ecs_cluster: Fixes intermittent failures on update when cluster dependencies are updating ([#11310](https://github.com/terraform-providers/terraform-provider-aws/issues/11310)) -* resource/aws_ecs_cluster: Fixes bug where ECS cluster capacity providers are updated but default provider strategy is not changed ([#11316](https://github.com/terraform-providers/terraform-provider-aws/issues/11316)) -* resource/aws_globalaccelerator_endpoint_group: Allow `traffic_dial_percentage` to be set to `0` ([#11253](https://github.com/terraform-providers/terraform-provider-aws/issues/11253)) -* resource/aws_lb_listener_rule: Fixes regression from version 2.42.0 when updating a rule without modifying condition ([#11364](https://github.com/terraform-providers/terraform-provider-aws/issues/11364)) -* resource/aws_ssm_activation: Ensure `tags` are refreshed into Terraform state during read for drift detection ([#11290](https://github.com/terraform-providers/terraform-provider-aws/issues/11290)) - -## 2.42.0 (December 13, 2019) - -FEATURES: - -* **New Resource:** `aws_ecs_capacity_provider` ([#11151](https://github.com/terraform-providers/terraform-provider-aws/issues/11151)) -* **New Resource:** `aws_media_convert_queue` ([#10041](https://github.com/terraform-providers/terraform-provider-aws/issues/10041)) -* **New Resource:** `aws_workspaces_ip_group` ([#10904](https://github.com/terraform-providers/terraform-provider-aws/issues/10904)) - -ENHANCEMENTS: - -* resource/aws_apigateway_usage_plan: Add `tags` argument and `arn` attribute ([#10566](https://github.com/terraform-providers/terraform-provider-aws/issues/10566)) -* resource/aws_codebuild_project: Add `ARM_CONTAINER` as valid `environment` configuration block `compute_type` argument value ([#11206](https://github.com/terraform-providers/terraform-provider-aws/issues/11206)) -* resource/aws_ecs_cluster: Add `capacity_providers` argument and `default_capacity_provider_strategy` configuration block (support ECS Capacity Providers) ([#11151](https://github.com/terraform-providers/terraform-provider-aws/issues/11151)) -* resource/aws_ecs_service: Add `capacity_provider_strategy` configuration block (support ECS Capacity Providers) ([#11151](https://github.com/terraform-providers/terraform-provider-aws/issues/11151)) -* resource/aws_emr_cluster: Add `step_concurrency_level` argument ([#11196](https://github.com/terraform-providers/terraform-provider-aws/issues/11196)) -* resource/aws_lb_listener_rule: Support ALB advanced routing rules ([#8268](https://github.com/terraform-providers/terraform-provider-aws/issues/8268)) - -BUG FIXES: - -* provider: Prevent crash in planning IAM Policy equivalency checking with invalid `Resource` declarations (e.g. a list of list of strings) ([#11107](https://github.com/terraform-providers/terraform-provider-aws/issues/11107)) -* resource/aws_eks_cluster: Handle additional `InvalidParameterException: Error in role params` error during creation for IAM eventual consistency ([#11127](https://github.com/terraform-providers/terraform-provider-aws/issues/11127)) -* resource/aws_iam_role: Ignore additional `NoSuchEntity` errors on deletion ([#11125](https://github.com/terraform-providers/terraform-provider-aws/issues/11125)) -* resource/aws_network_interface: Prevent extraneous `ModifyNetworkInterfaceAttribute` API call during update ([#11277](https://github.com/terraform-providers/terraform-provider-aws/issues/11277)) -* resource/aws_security_group: Support ampersand (`&`) in `ingress` and `egress` configuration block `description` argument value validation ([#9528](https://github.com/terraform-providers/terraform-provider-aws/issues/9528)) -* resource/aws_security_group_rule: Support ampersand (`&`) in `description` argument value validation ([#9528](https://github.com/terraform-providers/terraform-provider-aws/issues/9528)) - -## 2.41.0 (December 04, 2019) - -FEATURES: - -* **New Resource:** `aws_eks_fargate_profile` ([#11111](https://github.com/terraform-providers/terraform-provider-aws/issues/11111)) -* **New Resource:** `aws_lambda_provisioned_concurrency_config` ([#11129](https://github.com/terraform-providers/terraform-provider-aws/issues/11129)) - -ENHANCEMENTS: - -* data-source/aws_route_table: adds attributes `gateway_id` and `associations.gateway_id` ([#11122](https://github.com/terraform-providers/terraform-provider-aws/issues/11122)) -* resource/aws_autoscaling_group: Add `max_instance_lifetime` argument ([#10951](https://github.com/terraform-providers/terraform-provider-aws/issues/10951)) -* resource/aws_autoscaling_group: Add `mixed_instances_policy` `launch_template` `override` configuration block `weighted_capacity` argument ([#11004](https://github.com/terraform-providers/terraform-provider-aws/issues/11004)) -* resource/aws_codebuild_project: Add Linux GPU worker ([#11035](https://github.com/terraform-providers/terraform-provider-aws/issues/11035)) -* resource/aws_docdb_cluster_instance: Add support for `ca_cert_identifier` parameter ([#11041](https://github.com/terraform-providers/terraform-provider-aws/issues/11041)) -* resource/aws_emr_cluster: Outputs EMR cluster ARN ([#11078](https://github.com/terraform-providers/terraform-provider-aws/issues/11078)) -* resource/aws_iam_access_key: Remove deprecation from `secret` and mark `secret` and `ses_smtp_password` to sensitive ([#10908](https://github.com/terraform-providers/terraform-provider-aws/issues/10908)) -* resource/aws_iam_user: Delete a user's virtual MFA devices when `force_destroy` is enabled ([#11040](https://github.com/terraform-providers/terraform-provider-aws/issues/11040)) -* resource/aws_route_table_association: adds attribute `gateway_id` ([#11122](https://github.com/terraform-providers/terraform-provider-aws/issues/11122)) - -BUG FIXES: - -* resource/aws_batch_compute_environment: Forces new resource when `launch_template` contents are changed ([#11057](https://github.com/terraform-providers/terraform-provider-aws/issues/11057)) -* resource/aws_datasync_location_s3: Automatically retry creation for IAM errors due to eventual consistency ([#10984](https://github.com/terraform-providers/terraform-provider-aws/issues/10984)) -* resource/aws_launch_template: Only set associate_public_ip_address on network interfaces if it's explicitly set to avoid problems with multiple network interfaces ([#10157](https://github.com/terraform-providers/terraform-provider-aws/issues/10157)) - -## 2.40.0 (November 26, 2019) - -NOTES: - -* resource/aws_datasync_task: The DataSync API and SDK have removed `BEST_EFFORT` as a valid value for the `options` configuration block `posix_permissions` argument. The value has been removed from the validation in this resource to match those changes. ([#10985](https://github.com/terraform-providers/terraform-provider-aws/issues/10985)) - -FEATURES: - -* **New Resource:** `aws_dx_hosted_transit_virtual_interface` ([#8523](https://github.com/terraform-providers/terraform-provider-aws/issues/8523)) -* **New Resource:** `aws_dx_hosted_transit_virtual_interface_accepter` ([#8523](https://github.com/terraform-providers/terraform-provider-aws/issues/8523)) - -ENHANCEMENTS: - -* data-source/aws_eks_cluster: Add `vpc_config` nested block `cluster_security_group_id` attribute ([#11002](https://github.com/terraform-providers/terraform-provider-aws/issues/11002)) -* resource/aws_cloudwatch_metric_alarm: Add `threshold_metric_id` argument (support Anomaly Detection metrics) ([#9828](https://github.com/terraform-providers/terraform-provider-aws/issues/9828)) -* resource/aws_codebuild_project: Add support for BUILD_GENERAL1_2XLARGE CodeBuild compute type [GH11015] -* resource/aws_dx_private_virtual_interface: Support tagging-on-create ([#9572](https://github.com/terraform-providers/terraform-provider-aws/issues/9572)) -* resource/aws_dx_private_virtual_interface: Validate Virtual Interface type on import ([#9572](https://github.com/terraform-providers/terraform-provider-aws/issues/9572)) -* resource/aws_dx_public_virtual_interface: Validate Virtual Interface type on import ([#9572](https://github.com/terraform-providers/terraform-provider-aws/issues/9572)) -* resource/aws_ebs_snapshot: Support tagging-on-create and in-place `tags` updates ([#10935](https://github.com/terraform-providers/terraform-provider-aws/issues/10935)) -* resource/aws_ebs_snapshot_copy: Support tagging-on-create and in-place `tags` updates ([#10936](https://github.com/terraform-providers/terraform-provider-aws/issues/10936)) -* resource/aws_eks_cluster: Add `vpc_config` configuration block `cluster_security_group_id` attribute ([#11002](https://github.com/terraform-providers/terraform-provider-aws/issues/11002)) -* resource/aws_lambda_function: Support waiting for function creation and configuration updates ([#11016](https://github.com/terraform-providers/terraform-provider-aws/issues/11016)) - -BUG FIXES: - -* data-source/aws_iam_group: Ensure `users` attribute populates fully when group contains more than 100 users ([#10993](https://github.com/terraform-providers/terraform-provider-aws/issues/10993)) -* resource/aws_default_route_table: Return helpful not found error on resource creation instead of generic `Provider produced inconsistent result after apply` error when given invalid `default_route_table_id` argument value ([#10981](https://github.com/terraform-providers/terraform-provider-aws/issues/10981)) -* resource/aws_default_route_table: Propose resource recreation for missing Default Route Table on refresh instead of returning an error ([#10981](https://github.com/terraform-providers/terraform-provider-aws/issues/10981)) - -## 2.39.0 (November 21, 2019) - -FEATURES: - -* **New Data Source:** `aws_guardduty_detector` ([#10463](https://github.com/terraform-providers/terraform-provider-aws/issues/10463)) -* **New Resource:** `aws_glue_workflow` ([#10891](https://github.com/terraform-providers/terraform-provider-aws/issues/10891)) - -ENHANCEMENTS: - -* provider: Support for EC2 Metadata secure tokens ([#10940](https://github.com/terraform-providers/terraform-provider-aws/issues/10940)) -* resource/aws_glue_job: Add `number_of_workers` and `worker_type` arguments ([#9115](https://github.com/terraform-providers/terraform-provider-aws/issues/9115)) -* resource/aws_glue_job: Add `tags` argument and `arn` attribute ([#10968](https://github.com/terraform-providers/terraform-provider-aws/issues/10968)) -* resource/aws_glue_trigger: Add `workflow_name` argument ([#9762](https://github.com/terraform-providers/terraform-provider-aws/issues/9762)) -* resource/aws_glue_trigger: Add `actions` configuration block `crawler_name` argument ([#10190](https://github.com/terraform-providers/terraform-provider-aws/issues/10190)) -* resource/aws_glue_trigger: Add `predicate` `conditions` configuration block `crawler_name` and `crawl_state` arguments ([#10190](https://github.com/terraform-providers/terraform-provider-aws/issues/10190)) -* resource/aws_glue_trigger: Add `tags` argument and `arn` attribute ([#10967](https://github.com/terraform-providers/terraform-provider-aws/issues/10967)) -* resource/aws_iam_group_policy: Add IAM Policy JSON difference suppression and validation to `policy` argument ([#9660](https://github.com/terraform-providers/terraform-provider-aws/issues/9660)) -* resource/aws_lambda_event_source_mapping: Add `maximum_batching_window_in_seconds` argument ([#10051](https://github.com/terraform-providers/terraform-provider-aws/issues/10051)) -* resource/aws_lambda_function: Support `java11`, `nodejs12.x`, and `python3.8` as valid `runtime` argument values in validation ([#10938](https://github.com/terraform-providers/terraform-provider-aws/issues/10938)) -* resource/aws_lambda_layer_version: Support `java11`, `nodejs12.x`, and `python3.8` as valid `compatible_runtimes` argument values in validation ([#10938](https://github.com/terraform-providers/terraform-provider-aws/issues/10938)) -* resource/aws_resourcegroups_group: Add `tags` argument ([#10640](https://github.com/terraform-providers/terraform-provider-aws/issues/10640)) - -BUG FIXES: - -* data_source/aws_instance: Fixes a bug where multiple EBS volumes would get collapsed and only one would return ([#10045](https://github.com/terraform-providers/terraform-provider-aws/issues/10045)) -* resource/aws_appmesh_virtual_node: Allow FQDN values in `service_discovery` `aws_cloud_map` configuration block `namespace_name` and `service_name` argument validations ([#9788](https://github.com/terraform-providers/terraform-provider-aws/issues/9788)) -* resource/aws_batch_compute_environment: Propose resource recreation when updating `compute_resources` configuration block `tags` argument ([#10937](https://github.com/terraform-providers/terraform-provider-aws/issues/10937)) -* resource/aws_iam_instance_profile: Remove requirement to specify a role, as it is not required by the API ([#10525](https://github.com/terraform-providers/terraform-provider-aws/issues/10525)) -* resource/aws_opsworks_application: Fixes issue where `terraform apply` continuously suggests applying changes to `ssh_key` or `password` in `app_source` property ([#10175](https://github.com/terraform-providers/terraform-provider-aws/issues/10175)) -* resource/aws_opsworks_stack: Fixes issue where `terraform apply` continuously suggests applying changes to `ssh_key` or `password` in `custom_cookbooks_source` property ([#10175](https://github.com/terraform-providers/terraform-provider-aws/issues/10175)) - -## 2.38.0 (November 18, 2019) - -FEATURES: - -* **New Resource:** `aws_eks_node_group` ([#10916](https://github.com/terraform-providers/terraform-provider-aws/issues/10916)) - -## 2.37.0 (November 18, 2019) - -ENHANCEMENTS: - -* resource/aws_api_gateway_rest_api: Add `tags` argument and `arn` attribute ([#10581](https://github.com/terraform-providers/terraform-provider-aws/issues/10581)) -* resource/aws_db_instance: Add `ca_cert_identifier` argument ([#10490](https://github.com/terraform-providers/terraform-provider-aws/issues/10490)) -* resource/aws_dlm_lifecycle_policy: Add `tags` argument and `arn` attribute ([#10864](https://github.com/terraform-providers/terraform-provider-aws/issues/10864)) -* resource/aws_efs_file_system: Add `AFTER_7_DAYS` as a valid `lifecycle_policy` configuration block `transition_to_ia` argument value ([#10825](https://github.com/terraform-providers/terraform-provider-aws/issues/10825)) -* resource/aws_glue_crawler: Add `tags` argument ([#10805](https://github.com/terraform-providers/terraform-provider-aws/issues/10805)) -* resource/aws_s3_bucket_inventory: Add `IntelligentTieringAccessTier` as valid value for `optional_fields` argument ([#10746](https://github.com/terraform-providers/terraform-provider-aws/issues/10746)) -* resource/aws_waf_geo_match_set: Support resource import and add `arn` attribute ([#10480](https://github.com/terraform-providers/terraform-provider-aws/issues/10480)) -* resource/aws_waf_regex_match_set: Support resource import and add `arn` attribute ([#10481](https://github.com/terraform-providers/terraform-provider-aws/issues/10481)) -* resource/aws_waf_regex_pattern_set: Support resource import and add `arn` attribute ([#10482](https://github.com/terraform-providers/terraform-provider-aws/issues/10482)) -* resource/aws_waf_size_constraint_set: Support resource import and add `arn` attribute ([#10484](https://github.com/terraform-providers/terraform-provider-aws/issues/10484)) -* resource/aws_waf_xss_match_set: Support resource import and add `arn` attribute ([#10485](https://github.com/terraform-providers/terraform-provider-aws/issues/10485)) -* resource/aws_wafregional_rate_based_rule: Add `tags` argument and `arn` attribute ([#10897](https://github.com/terraform-providers/terraform-provider-aws/issues/10897)) -* resource/aws_wafregional_rule_group: Add `tags` argument and `arn` attribute ([#10896](https://github.com/terraform-providers/terraform-provider-aws/issues/10896)) -* resource/aws_wafregional_rule: Add `tags` argument and `arn` attribute ([#10895](https://github.com/terraform-providers/terraform-provider-aws/issues/10895)) -* resource/aws_wafregional_web_acl: Add `tags` argument ([#10889](https://github.com/terraform-providers/terraform-provider-aws/issues/10889)) -* resource/aws_wafregional_web_acl_association: Support resource import ([#10538](https://github.com/terraform-providers/terraform-provider-aws/issues/10538)) -* resource/aws_cloudtrail: support Tag on create ([#10818](https://github.com/terraform-providers/terraform-provider-aws/issues/10818)) - -BUG FIXES: - -* data-source/aws_iam_policy_document: Prevent panic when combining single principal identifier with multiple principal identifiers ([#10780](https://github.com/terraform-providers/terraform-provider-aws/issues/10780)) -* data-source/aws_iam_policy_document: Prevent losing identifier elements when combining single and multiple principals identifiers ([#10844](https://github.com/terraform-providers/terraform-provider-aws/issues/10844)) -* resource/aws_servicequotas_service_quota: Remove resource from Terraform state on `NoSuchResourceException` error ([#10735](https://github.com/terraform-providers/terraform-provider-aws/issues/10735)) - -## 2.36.0 (November 14, 2019) - -ENHANCEMENTS: - -* data-source/aws_iam_group: Add `users` attribute ([#7132](https://github.com/terraform-providers/terraform-provider-aws/issues/7132)) -* resource/aws_apigateway_stage: Add `arn` attribute ([#10570](https://github.com/terraform-providers/terraform-provider-aws/issues/10570)) -* resource/aws_s3_bucket: Retry reading tags on `NoSuchBucket` errors due to eventual inconsistency ([#10863](https://github.com/terraform-providers/terraform-provider-aws/issues/10863)) -* resource/aws_waf_rule: Add `arn` attribute ([#10798](https://github.com/terraform-providers/terraform-provider-aws/issues/10798)) -* resource/aws_waf_rule_group: Add `arn` attribute ([#10799](https://github.com/terraform-providers/terraform-provider-aws/issues/10799)) - -## 2.35.0 (November 07, 2019) - -NOTES: - -* provider: New `ignore_tag_prefixes` and `ignore_tags` arguments are being tested as a public preview for ignoring tags across all resources under a provider. Support for the functionality must be added to individual resources in the codebase and is only implemented for the `aws_subnet` and `aws_vpc` resources at this time. Until a general availability announcement, no compatibility promises are made with these provider arguments and their functionality. ([#10418](https://github.com/terraform-providers/terraform-provider-aws/issues/10418)) - -FEATURES: - -* **New Data Source:** `aws_qldb_ledger` ([#10394](https://github.com/terraform-providers/terraform-provider-aws/issues/10394)) -* **New Resource:** `aws_qldb_ledger` ([#10394](https://github.com/terraform-providers/terraform-provider-aws/issues/10394)) - -ENHANCEMENTS: - -* data-source/aws_db_cluster_snapshot: Add `tags` attribute ([#10488](https://github.com/terraform-providers/terraform-provider-aws/issues/10488)) -* data-source/aws_db_instance: Add `tags` attribute ([#10550](https://github.com/terraform-providers/terraform-provider-aws/issues/10550)) -* data-source/aws_vpc_endpoint: Add `filter` and `tags` arguments ([#10503](https://github.com/terraform-providers/terraform-provider-aws/issues/10503)) -* provider: Add `ignore_tag_prefixes` and `ignore_tags` arguments (in public preview, see note above) ([#10418](https://github.com/terraform-providers/terraform-provider-aws/issues/10418)) -* resource/aws_acmpca_certificate_authority: Support tagging on creation ([#10736](https://github.com/terraform-providers/terraform-provider-aws/issues/10736)) -* resource/aws_api_gateway_api_key: Add `tags` argument and `arn` attribute ([#10568](https://github.com/terraform-providers/terraform-provider-aws/issues/10568)) -* resource/aws_api_gateway_client_certificate: Add `tags` argument and `arn` attribute ([#10569](https://github.com/terraform-providers/terraform-provider-aws/issues/10569)) -* resource/aws_api_gateway_domain_name: Add `tags` argument and `arn` attribute ([#10567](https://github.com/terraform-providers/terraform-provider-aws/issues/10567)) -* resource/aws_api_gateway_vpc_link: Add `tags` argument and `arn` attribute ([#10561](https://github.com/terraform-providers/terraform-provider-aws/issues/10561)) -* resource/aws_cloudwatch_log_group: Support tagging on creation ([#10753](https://github.com/terraform-providers/terraform-provider-aws/issues/10753)) -* resource/aws_db_cluster_snapshot: Add `tags` argument ([#10488](https://github.com/terraform-providers/terraform-provider-aws/issues/10488)) -* resource/aws_ec2_fleet: Support in-place `tags` updates ([#10761](https://github.com/terraform-providers/terraform-provider-aws/issues/10761)) -* resource/aws_launch_template: Support tagging on creation ([#10759](https://github.com/terraform-providers/terraform-provider-aws/issues/10759)) -* resource/aws_mq_broker: Support in-place `security_groups` updates ([#10442](https://github.com/terraform-providers/terraform-provider-aws/issues/10442)) -* resource/aws_storagegateway_cached_iscsi_volume: Add `tags` argument ([#10613](https://github.com/terraform-providers/terraform-provider-aws/issues/10613)) -* resource/aws_storagegateway_gateway: Add `tags` argument ([#10588](https://github.com/terraform-providers/terraform-provider-aws/issues/10588)) -* resource/aws_storagegateway_nfs_file_share: Add `tags` argument ([#10722](https://github.com/terraform-providers/terraform-provider-aws/issues/10722)) -* resource/aws_subnet: Support provider-wide ignore tags (in public preview, see note above) ([#10418](https://github.com/terraform-providers/terraform-provider-aws/issues/10418)) -* resource/aws_swf_domain: Add `tags` argument and `arn` attribute ([#10763](https://github.com/terraform-providers/terraform-provider-aws/issues/10763)) -* resource/aws_vpc: Support provider-wide ignore tags (in public preview, see note above) ([#10418](https://github.com/terraform-providers/terraform-provider-aws/issues/10418)) -* resource/aws_waf_rate_based_rule: Add `tags` argument and `arn` attribute ([#10479](https://github.com/terraform-providers/terraform-provider-aws/issues/10479)) - -BUG FIXES: - -* data-source/aws_route53_resolver_rule: Do not retrieve tags for rules shared with the AWS account that owns the data source ([#10348](https://github.com/terraform-providers/terraform-provider-aws/issues/10348)) -* resource/aws_api_gateway_authorizer: Set `authorizer_result_ttl_in_seconds` argument default to 300 to match API default which properly allows setting to 0 for disabling caching ([#9605](https://github.com/terraform-providers/terraform-provider-aws/issues/9605)) -* resource/aws_autoscaling_group: Batch ELB attachments and detachments by 10 to prevent API and rate limiting errors ([#10445](https://github.com/terraform-providers/terraform-provider-aws/issues/10445)) -* resource/aws_s3_bucket_public_access_block: Remove from Terraform state when S3 Bucket is already destroyed ([#10534](https://github.com/terraform-providers/terraform-provider-aws/issues/10534)) -* resource/aws_ssm_maintenance_window_task: Prevent crashes with empty configuration blocks ([#10713](https://github.com/terraform-providers/terraform-provider-aws/issues/10713)) - -## 2.34.0 (October 31, 2019) - -ENHANCEMENTS: - -* resource/aws_ecr_repository: Add `image_scanning_configuration` configuration block (support image scanning on push) ([#10671](https://github.com/terraform-providers/terraform-provider-aws/issues/10671)) -* resource/aws_elasticache_replication_group: Add `kms_key_id` argument (support KMS encryption) ([#10380](https://github.com/terraform-providers/terraform-provider-aws/issues/10380)) -* resource/aws_flow_log: Add `log_format` argument ([#10374](https://github.com/terraform-providers/terraform-provider-aws/issues/10374)) -* resource/aws_glue_job: Add `glue_version` argument ([#10237](https://github.com/terraform-providers/terraform-provider-aws/issues/10237)) -* resource/aws_storagegateway_smb_file_share: Add `tags` argument ([#10620](https://github.com/terraform-providers/terraform-provider-aws/issues/10620)) - -BUG FIXES: - -* resource/aws_backup_plan: Correctly handle changes to `recovery_point_tags` arguments ([#10641](https://github.com/terraform-providers/terraform-provider-aws/issues/10641)) -* resource/aws_backup_plan: Prevent `diffs didn't match` errors with `rule` configuration blocks ([#10641](https://github.com/terraform-providers/terraform-provider-aws/issues/10641)) -* resource/aws_cloudhsm_v2_cluster: Ensure multiple tag configurations are applied correctly ([#10309](https://github.com/terraform-providers/terraform-provider-aws/issues/10309)) -* resource/aws_cloudhsm_v2_cluster: Perform drift detection with tags ([#10309](https://github.com/terraform-providers/terraform-provider-aws/issues/10309)) -* resource/aws_dx_gateway_association: Fix backwards compatibility issue with missing `dx_gateway_association_id` attribute ([#8776](https://github.com/terraform-providers/terraform-provider-aws/issues/8776)) -* resource/aws_s3_bucket: Bypass `MethodNotAllowed` errors for Object Lock Configuration on read (support AWS C2S) ([#10657](https://github.com/terraform-providers/terraform-provider-aws/issues/10657)) - -## 2.33.0 (October 17, 2019) - -FEATURES: - -* **New Data Source:** `aws_waf_rate_based_rule` ([#10124](https://github.com/terraform-providers/terraform-provider-aws/issues/10124)) -* **New Data Source:** `aws_wafregional_rate_based_rule` ([#10125](https://github.com/terraform-providers/terraform-provider-aws/issues/10125)) -* **New Resource:** `aws_quicksight_user` ([#10401](https://github.com/terraform-providers/terraform-provider-aws/issues/10401)) - -ENHANCEMENTS: - -* resource/aws_glue_classifier: Add `csv_classifier` configuration block (support CSV classifiers) ([#9824](https://github.com/terraform-providers/terraform-provider-aws/issues/9824)) -* resource/aws_waf_byte_match_set: Support resource import ([#10477](https://github.com/terraform-providers/terraform-provider-aws/issues/10477)) -* resource/aws_waf_rate_based_rule: Support resource import ([#10475](https://github.com/terraform-providers/terraform-provider-aws/issues/10475)) -* resource/aws_waf_rule: Add `tags` argument ([#10408](https://github.com/terraform-providers/terraform-provider-aws/issues/10408)) -* resource/aws_waf_rule_group: Add `tags` argument ([#10408](https://github.com/terraform-providers/terraform-provider-aws/issues/10408)) -* resource/aws_waf_web_acl: Add `tags` argument ([#10408](https://github.com/terraform-providers/terraform-provider-aws/issues/10408)) - -BUG FIXES: - -* resource/aws_gamelift_fleet: Increase default deletion timeout to 20 minutes to match service timing ([#10443](https://github.com/terraform-providers/terraform-provider-aws/issues/10443)) - -## 2.32.0 (October 10, 2019) - -NOTES: - -* provider: The underlying Terraform codebase dependency for the provider SDK and acceptance testing framework has been migrated from `github.com/hashicorp/terraform` to `github.com/hashicorp/terraform-plugin-sdk`. They are functionality equivalent and this should only impact codebase development to switch imports. For more information see the [Terraform Plugin SDK page in the Extending Terraform documentation](https://www.terraform.io/docs/extend/plugin-sdk.html). ([#10367](https://github.com/terraform-providers/terraform-provider-aws/issues/10367)) - -ENHANCEMENTS: - -* resource/aws_emr_instance_group: Add `configurations_json` argument ([#10426](https://github.com/terraform-providers/terraform-provider-aws/issues/10426)) - -BUG FIXES: - -* provider: Fix session handling to correctly validate and use assume_role credentials ([#10379](https://github.com/terraform-providers/terraform-provider-aws/issues/10379)) -* resource/aws_autoscaling_group: Batch ALB/NLB attachments and detachments by 10 to prevent API and rate limiting errors ([#10435](https://github.com/terraform-providers/terraform-provider-aws/issues/10435)) -* resource/aws_emr_instance_group: Remove terminated instance groups from the Terraform state ([#10425](https://github.com/terraform-providers/terraform-provider-aws/issues/10425)) -* resource/aws_s3_bucket: Prevent infinite deletion recursion with `force_destroy` argument and object keys with empty "directory" prefixes present since version 2.29.0 ([#10388](https://github.com/terraform-providers/terraform-provider-aws/issues/10388)) -* resource/aws_vpc_endpoint_route_table_association: Fix resource import support ([#10454](https://github.com/terraform-providers/terraform-provider-aws/issues/10454)) - -## 2.31.0 (October 03, 2019) - -NOTES: - -* resource/aws_lambda_function: Environments using Lambda functions with VPC configurations should upgrade their Terraform AWS Provider to this version or later to appropriately handle the networking changes introduced by the [improved VPC networking for AWS Lambda functions](https://aws.amazon.com/blogs/compute/announcing-improved-vpc-networking-for-aws-lambda-functions/) deployment. These changes prevent proper deletion of EC2 Subnets and Security Groups for accounts and regions updated to the new Lambda networking infrastructure in older versions of the Terraform AWS Provider. Additional information and configuration workarounds for prior versions can be found in [this GitHub issue](https://github.com/terraform-providers/terraform-provider-aws/issues/10329). - -ENHANCEMENTS: - -* data-source/aws_eks_cluster: Add `tags` attribute ([#10307](https://github.com/terraform-providers/terraform-provider-aws/issues/10307)) -* resource/aws_efs_filesystem: Support tag-on-create ([#10254](https://github.com/terraform-providers/terraform-provider-aws/issues/10254)) -* resource/aws_eks_cluster: Add `tags` argument ([#10307](https://github.com/terraform-providers/terraform-provider-aws/issues/10307)) -* resource/aws_mq_broker: Add `encryption_options` configuration block (support AWS and customer managed KMS CMKs) ([#10276](https://github.com/terraform-providers/terraform-provider-aws/issues/10276)) - -BUG FIXES: - -* provider: Upstream AWS Go SDK fix for parsing AWS shared credentials files missing right-hand values ([#10310](https://github.com/terraform-providers/terraform-provider-aws/issues/10310)) -* resource/aws_lb_listener_certificate: Retry `CertificateNotFound` errors on creation for eventual consistency ([#10294](https://github.com/terraform-providers/terraform-provider-aws/issues/10294)) -* resource/aws_s3_bucket_object: Fix object deletion for non-versioned objects ([#10352](https://github.com/terraform-providers/terraform-provider-aws/issues/10352)) -* resource/aws_security_group: Handle updated ENI description and longer deletion timeframe for new Lambda Hyperplane ENIs ([#10114](https://github.com/terraform-providers/terraform-provider-aws/issues/10114)] / [[#10347](https://github.com/terraform-providers/terraform-provider-aws/issues/10347)) -* resource/aws_subnet: Handle updated ENI description and longer deletion timeframe for new Lambda Hyperplane ENIs ([#10114](https://github.com/terraform-providers/terraform-provider-aws/issues/10114)] / [[#10347](https://github.com/terraform-providers/terraform-provider-aws/issues/10347)) -* resource/aws_vpc_peering_connection: Ensure `allow_remote_vpc_dns_resolution` usage works with inter-region peering ([#7627](https://github.com/terraform-providers/terraform-provider-aws/issues/7627)) -* resource/aws_vpc_peering_connection_accepter: Ensure `allow_remote_vpc_dns_resolution` usage works with inter-region peering ([#7627](https://github.com/terraform-providers/terraform-provider-aws/issues/7627)) -* resource/aws_vpc_peering_connection_options: Ensure `allow_remote_vpc_dns_resolution` usage works with inter-region peering ([#7627](https://github.com/terraform-providers/terraform-provider-aws/issues/7627)) -* resource/aws_waf_rate_based_rule: Upstream AWS Go SDK fix to allow `rate_limit` arguments between 100 and 1999 ([#10310](https://github.com/terraform-providers/terraform-provider-aws/issues/10310)) -* resource/aws_wafregional_rate_based_rule: Upstream AWS Go SDK fix to allow `rate_limit` arguments between 100 and 1999 ([#10310](https://github.com/terraform-providers/terraform-provider-aws/issues/10310)) -* resource/aws_wafregional_web_acl_association: Ensure missing resource triggers state removal ([#10216](https://github.com/terraform-providers/terraform-provider-aws/issues/10216)) -* service/waf: Prevent incorrect `Error getting WAF change token` errors for API calls that should be retried or specially handled ([#10242](https://github.com/terraform-providers/terraform-provider-aws/issues/10242)) -* service/wafregional: Prevent incorrect `Error getting WAF regional change token` errors for API calls that should be retried or specially handled ([#10242](https://github.com/terraform-providers/terraform-provider-aws/issues/10242)) - -## 2.30.0 (September 26, 2019) - -NOTES: - -* provider: The default development, testing, and building of the Terraform AWS Provider binary is now done with Go 1.13. This version of Go now requires macOS 10.11 El Capitan or later and FreeBSD 11.2 or later. Support for previous versions of those operating systems has been discontinued. ([#10206](https://github.com/terraform-providers/terraform-provider-aws/issues/10206)) -* provider: The actual Terraform version running the provider will now be included the AWS Go SDK `User-Agent` headers for Terraform 0.12 and later. Terraform 0.11 and earlier will use `Terraform/0.11+compatible` as this information was not accessible in those versions. Previously, the Terraform version in the `User-Agent` header was based on the github.com/hashicorp/terraform dependency in the provider codebase. ([#9570](https://github.com/terraform-providers/terraform-provider-aws/issues/9570)) - -ENHANCEMENTS: - -* data-source/aws_cloudtrail_service_account: Support `cn-north-1` region ([#10134](https://github.com/terraform-providers/terraform-provider-aws/issues/10134)) -* data-source/aws_elastic_beanstalk_hosted_zone: Support `ap-east-1`, `ap-northeast-3`, `us-gov-east-1` and `us-gov-west-1` regions ([#10134](https://github.com/terraform-providers/terraform-provider-aws/issues/10134)) -* data-source/aws_elb_hosted_zone_id: Support `cn-northwest-1` region ([#10134](https://github.com/terraform-providers/terraform-provider-aws/issues/10134)) -* data-source/aws_redshift_service_account: Support `ap-northeast-3`, `cn-north-1`, `eu-north-1` and `me-south-1` regions ([#10134](https://github.com/terraform-providers/terraform-provider-aws/issues/10134)) -* provider: Use real Terraform version in User-Agent header ([#9570](https://github.com/terraform-providers/terraform-provider-aws/issues/9570)) -* resource/aws_appsync_graphql_api: Add `additional_authentication_providers` configuration blocks ([#8587](https://github.com/terraform-providers/terraform-provider-aws/issues/8587)) -* resource/aws_elastic_beanstalk_environment: Add `endpoint_url` attribute ([#10015](https://github.com/terraform-providers/terraform-provider-aws/issues/10015)) -* resource/aws_lightsail_static_ip_attachment: Add `ip_address` attribute ([#10109](https://github.com/terraform-providers/terraform-provider-aws/issues/10109)) -* resource/aws_opsworks_stack: Switch legacy Opsworks client User-Agent to real Terraform version ([#10246](https://github.com/terraform-providers/terraform-provider-aws/issues/10246)) -* resource/aws_sns_topic_policy: Support resource import ([#10163](https://github.com/terraform-providers/terraform-provider-aws/issues/10163)) -* resource/aws_sqs_queue: Support tag-on-create in AWS Commercial regions ([#10156](https://github.com/terraform-providers/terraform-provider-aws/issues/10156)) - -BUG FIXES: - -* data-source/aws_elb_hosted_zone_id: Correct value for `cn-north-1` region ([#10134](https://github.com/terraform-providers/terraform-provider-aws/issues/10134)) -* resource/aws_ec2_client_vpn_endpoint: Ensure missing resource triggers state removal ([#10187](https://github.com/terraform-providers/terraform-provider-aws/issues/10187)) -* resource/aws_instance: Prevent panic when updating `credit_specification` to empty configuration block ([#10212](https://github.com/terraform-providers/terraform-provider-aws/issues/10212)) -* resource/aws_security_group: Ensure deletion errors are properly raised ([#10165](https://github.com/terraform-providers/terraform-provider-aws/issues/10165)) -* resource/aws_spot_fleet_request: Ensure `launch_specification` configuration block `placement_group` argument is passed through to the API when it is specified ([#10103](https://github.com/terraform-providers/terraform-provider-aws/issues/10103)) - -## 2.29.0 (September 20, 2019) - -ENHANCEMENTS: -* data-source/aws_s3_bucket_object: Add `object_lock_legal_hold_status`, `object_lock_mode` and `object_lock_retain_until_date` attributes ([#9942](https://github.com/terraform-providers/terraform-provider-aws/issues/9942)) -* resource/aws_glue_job: Add ability to specify python version for pythonshell in glue jobs ([#9409](https://github.com/terraform-providers/terraform-provider-aws/issues/9409)) -* resource/aws_s3_bucket_object: Add `force_destroy`, `object_lock_legal_hold_status`, `object_lock_mode` and `object_lock_retain_until_date` attributes ([#9942](https://github.com/terraform-providers/terraform-provider-aws/issues/9942)) -* resource/aws_ssm_association: Add import support ([#10055](https://github.com/terraform-providers/terraform-provider-aws/issues/10055)) -* resource/aws_waf_rate_based_rule: Update rate based rule limit for WAF ([#9946](https://github.com/terraform-providers/terraform-provider-aws/pull/9946)) -* resource/aws_wafregional_rate_based_rule: Update rate based rule limit for WAF ([#9946](https://github.com/terraform-providers/terraform-provider-aws/pull/9946)) - -BUG FIXES: - -* resource/aws_ecs_task_definition: Fix a crash if `containers_definition` argument JSON defines `environment` without `name` value ([#10074](https://github.com/terraform-providers/terraform-provider-aws/issues/10074)) - -## 2.28.1 (September 12, 2019) - -BUG FIXES: - -* Revert "resource/aws_cloudfront_distribution: Fix `active_trusted_signers` attribute for Terraform 0.12" ([#10093](https://github.com/terraform-providers/terraform-provider-aws/issues/10093)) - -## 2.28.0 (September 12, 2019) - -NOTES: - -* resource/aws_cloudfront_distribution: This attribute implemented a legacy Terraform library (flatmap), which does not work with Terraform 0.12's data types and whose only usage was on this single attribute across all Terraform Providers. The attribute now implements (in the closest approximation to the previous implementation) the nested object data into the Terraform state in all Terraform versions. Any references to nested attributes such as `active_trusted_signers.enabled` will need to be updated to `active_trusted_signers.0.enabled`. ([#10013](https://github.com/terraform-providers/terraform-provider-aws/issues/10013)) - -FEATURES: - -* **New Data Source:** `aws_route53_resolver_rule` ([#9805](https://github.com/terraform-providers/terraform-provider-aws/issues/9805)) -* **New Data Source:** `aws_route53_resolver_rules` ([#9805](https://github.com/terraform-providers/terraform-provider-aws/issues/9805)) - -ENHANCEMENTS: - -* data-source/aws_eks_cluster: Add `identity` attribute (support getting OIDC issuer URL) ([#10006](https://github.com/terraform-providers/terraform-provider-aws/issues/10006)) -* resource/aws_eks_cluster: Add `identity` attribute (support getting OIDC issuer URL) ([#10006](https://github.com/terraform-providers/terraform-provider-aws/issues/10006)) -* resource/aws_elasticache_cluster: Support `cluster_id` validation up to 50 characters ([#9941](https://github.com/terraform-providers/terraform-provider-aws/issues/9941)) -* resource/aws_elasticache_replication_group: Support `replication_group_id` validation up to 40 characters ([#9941](https://github.com/terraform-providers/terraform-provider-aws/issues/9941)) - -BUG FIXES: - -* resource/aws_instance: Final retries after timeouts creating and updating instance and getting instance password data -* resource/aws_cloudfront_distribution: Support accessing `active_trusted_signers` attribute `items` in Terraform 0.12 ([#10013](https://github.com/terraform-providers/terraform-provider-aws/issues/10013)) -* resource/aws_cognito_user_pool: Fix perpetual diffs on `sms_verification_message` ([#9758](https://github.com/terraform-providers/terraform-provider-aws/issues/9758)) -* resource/aws_elasticsearch_domain: Final retries after timeouts creating, updating, and deleting domains ([#9892](https://github.com/terraform-providers/terraform-provider-aws/issues/9892)) -* resource/aws_elasticsearch_domain_policy: Final retries after timeouts upserting and deleting domain policies ([#9892](https://github.com/terraform-providers/terraform-provider-aws/issues/9892)) -* resource/aws_iam_policy_attachment: Revert a change causing errors with policies not being found during attachment ([#10063](https://github.com/terraform-providers/terraform-provider-aws/issues/10063)) -* resource/aws_lightsail_instance: Fixes an issue where 2-character lightsail instance names didn't get validated properly ([#10046](https://github.com/terraform-providers/terraform-provider-aws/issues/10046)) - - -## 2.27.0 (September 05, 2019) - -ENHANCEMENTS: - -* data-source/aws_ecs_cluster: Add `setting` attribute ([#9720](https://github.com/terraform-providers/terraform-provider-aws/issues/9720)) -* provider: Support AWS C2S and SC2S endpoints ([#9998](https://github.com/terraform-providers/terraform-provider-aws/issues/9998)) -* resource/aws_ecs_cluster: Add `setting` configuration blocks (support enabling Container Insights) ([#9720](https://github.com/terraform-providers/terraform-provider-aws/issues/9720)) -* resource/aws_kinesis_firehose_delivery_stream: Add `server_side_encryption` configuration block (support Server Side Encryption) ([#6523](https://github.com/terraform-providers/terraform-provider-aws/issues/6523)) - -BUG FIXES: - -* resource/aws_s3_bucket: Include any system tags that Terraform ignores when setting S3 bucket tags ([#7342](https://github.com/terraform-providers/terraform-provider-aws/issues/7342)) - -## 2.26.0 (August 29, 2019) - -FEATURES: - -* **New Data Source:** `aws_elasticsearch_domain` ([#1867](https://github.com/terraform-providers/terraform-provider-aws/issues/1867)) - -BUG FIXES: - -* resource/aws_ec2_capacity_reservation: Fixes error handling when an EC2 Capacity Reservation is deleted manually but is still in state ([#9862](https://github.com/terraform-providers/terraform-provider-aws/issues/9862)) -* resource/aws_s3_bucket: Final retries after timeouts creating, updating and updating replication configuration for s3 buckets ([#9861](https://github.com/terraform-providers/terraform-provider-aws/issues/9861)) -* resource/aws_s3_bucket_inventory: Final retries after timeout reading and putting bucket inventories ([#9861](https://github.com/terraform-providers/terraform-provider-aws/issues/9861)) -* resource/aws_s3_bucket_metric: Final retry after timeout putting bucket metric ([#9861](https://github.com/terraform-providers/terraform-provider-aws/issues/9861)) -* resource/aws_s3_bucket_notification: Final retry after timeout putting notification ([#9861](https://github.com/terraform-providers/terraform-provider-aws/issues/9861)) -* resource/aws_s3_bucket_policy: Final retry after timeout putting policy ([#9861](https://github.com/terraform-providers/terraform-provider-aws/issues/9861)) -* resource/aws_s3_bucket_public_access_block: Final retries after timeouts creating and reading blocks ([#9861](https://github.com/terraform-providers/terraform-provider-aws/issues/9861)) - -## 2.25.0 (August 23, 2019) - -ENHANCEMENTS: - -* resource/aws_rds_cluster: Support `postgresql` in plan time validation for `enabled_cloudwatch_logs_exports` argument ([#9740](https://github.com/terraform-providers/terraform-provider-aws/issues/9740)) - -BUG FIXES: - -* resource/aws_cloudwatch_event_target: Add default setting for ecs_target task_count ([#9773](https://github.com/terraform-providers/terraform-provider-aws/issues/9773)) -* resource/aws_cloudwatch_log_subscription_filter: Prevent difference when omitting default `distribution` argument value of `ByLogStream` ([#9265](https://github.com/terraform-providers/terraform-provider-aws/issues/9265)) -* resource/aws_db_instance: Fix enabling Enhanced Monitoring on update to handle IAM eventual consistency ([#9747](https://github.com/terraform-providers/terraform-provider-aws/issues/9747)) -* resource/aws_elb: Final retries after timeouts creating and updating ELBs ([#9765](https://github.com/terraform-providers/terraform-provider-aws/issues/9765)) -* resource/aws_elb_attachment: Final retry after timout creating ELB attachment ([#9765](https://github.com/terraform-providers/terraform-provider-aws/issues/9765)) -* resource/aws_iam_instance_profile: Final retry after timeout adding role to profile ([#9766](https://github.com/terraform-providers/terraform-provider-aws/issues/9766)) -* resource/aws_iam_policy: Final retry after timeout reading policy ([#9766](https://github.com/terraform-providers/terraform-provider-aws/issues/9766)) -* resource/aws_iam_role: Final retries after timeouts creating and deleting IAM roles ([#9766](https://github.com/terraform-providers/terraform-provider-aws/issues/9766)) -* resource/aws_iam_user: Final retry after timeout deleting user login profile ([#9766](https://github.com/terraform-providers/terraform-provider-aws/issues/9766)) -* resource/aws_inspector_assessment_target: Final retry after timeout deleting target ([#9767](https://github.com/terraform-providers/terraform-provider-aws/issues/9767)) -* resource/aws_internet_gateway: Final retries after timeouts creating, attaching, and deleting gateways ([#9779](https://github.com/terraform-providers/terraform-provider-aws/issues/9779)) -* resource/aws_iot_thing_type: Final retry after timeout deleting IOT thing type ([#9780](https://github.com/terraform-providers/terraform-provider-aws/issues/9780)) -* resource/aws_kinesis_firehose_delivery_stream: Prevent differences with disabled `data_format_conversion_configuration` and `processing_configuration` after changes outside Terraform ([#9103](https://github.com/terraform-providers/terraform-provider-aws/issues/9103)) -* resource/aws_launch_configuration: Final retry after timeout creating launch configuration ([#9781](https://github.com/terraform-providers/terraform-provider-aws/issues/9781)) -* resource/aws_lb: Final retry after timeout waiting for network interfaces to detach ([#9787](https://github.com/terraform-providers/terraform-provider-aws/issues/9787)) -* resource/aws_lb_listener_certificate: Final retry after timeout reading listener certificate ([#9787](https://github.com/terraform-providers/terraform-provider-aws/issues/9787)) -* resource/aws_lb_listener_rule: Final retries after timeout reading and creating listener rules ([#9787](https://github.com/terraform-providers/terraform-provider-aws/issues/9787)) -* resource/aws_msk_cluster: Final retries after timeouts creating and deleting clusters ([#9793](https://github.com/terraform-providers/terraform-provider-aws/issues/9793)) -* resource/aws_network_acl: Final retry after timeout deleting ACLs ([#9830](https://github.com/terraform-providers/terraform-provider-aws/issues/9830)) -* resource/aws_network_acl_rule: Final retry after timeout creating ACL rules ([#9830](https://github.com/terraform-providers/terraform-provider-aws/issues/9830)) -* resource/aws_network_acl_rule: Remove resource from Terraform state on `InvalidNetworkAclID.NotFound` errors ([#9710](https://github.com/terraform-providers/terraform-provider-aws/issues/9710)) -* resource/aws_opsworks_stack: Final retry after timeout creating stack ([#9818](https://github.com/terraform-providers/terraform-provider-aws/issues/9818)) -* resource/aws_rds_cluster_instance: Ensure `monitoring_interval` and `monitoring_role_arn` attributes are always written to the Terraform state ([#9748](https://github.com/terraform-providers/terraform-provider-aws/issues/9748)) -* resource/aws_redshift_cluster: Final retry after timeout deleting cluster ([#9796](https://github.com/terraform-providers/terraform-provider-aws/issues/9796)) -* resource/aws_redshift_snapshot_copy_grant: Final retries after timeouts finding and deleting grants ([#9796](https://github.com/terraform-providers/terraform-provider-aws/issues/9796)) -* resource/aws_route: Final retry after timeout creating route ([#9797](https://github.com/terraform-providers/terraform-provider-aws/issues/9797)) -* resource/aws_route_table: Final retry after timeout updating route table ([#9797](https://github.com/terraform-providers/terraform-provider-aws/issues/9797)) -* resource/aws_route_table_association: Final retry after timeout creating route table association ([#9797](https://github.com/terraform-providers/terraform-provider-aws/issues/9797)) -* resource/aws_s3_bucket_object: Allow using SSE-S3 encryption with `etag` argument ([#9442](https://github.com/terraform-providers/terraform-provider-aws/issues/9442)) -* resource/aws_sagemaker_model: Final retry after timeout deleting model ([#9799](https://github.com/terraform-providers/terraform-provider-aws/issues/9799)) -* resource/aws_sagemaker_notebook_instance: Final retry after timeout updating instance ([#9799](https://github.com/terraform-providers/terraform-provider-aws/issues/9799)) -* resource/aws_security_group: Final retry after timeout deleting security group ([#9812](https://github.com/terraform-providers/terraform-provider-aws/issues/9812)) -* resource/aws_security_group_rule: Final retry after timeout creating security group rule ([#9812](https://github.com/terraform-providers/terraform-provider-aws/issues/9812)) -* resource/aws_sqs_queue: Final retry after timeout creating queue ([#9813](https://github.com/terraform-providers/terraform-provider-aws/issues/9813)) -* resource/aws_sqs_queue_policy: Final retry after timeout updating queue policy ([#9813](https://github.com/terraform-providers/terraform-provider-aws/issues/9813)) -* resource/aws_transfer_server: Final retry after timeout waiting for transfer server deletion ([#9815](https://github.com/terraform-providers/terraform-provider-aws/issues/9815)) -* resource/aws_wafregional_web_acl_association: Final retry after timeout creating association ([#9820](https://github.com/terraform-providers/terraform-provider-aws/issues/9820)) -* service/dynamodb: Final retries after timeouts setting dynamodb tags ([#9821](https://github.com/terraform-providers/terraform-provider-aws/issues/9821)) -* service/sagemaker: Final retries after timeouts setting sagemaker tags ([#9821](https://github.com/terraform-providers/terraform-provider-aws/issues/9821)) -* service/waf: Final retry after timeout getting change token ([#9826](https://github.com/terraform-providers/terraform-provider-aws/issues/9826)) -* service/wafregional: Final retry after timeout getting change token ([#9826](https://github.com/terraform-providers/terraform-provider-aws/issues/9826)) - -## 2.24.0 (August 15, 2019) - -FEATURES: - -* **New Resource:** `aws_config_organization_custom_rule` ([#9716](https://github.com/terraform-providers/terraform-provider-aws/issues/9716)) -* **New Resource:** `aws_config_organization_managed_rule` ([#9716](https://github.com/terraform-providers/terraform-provider-aws/issues/9716)) -* **New Resource:** `aws_fsx_lustre_file_system` ([#7074](https://github.com/terraform-providers/terraform-provider-aws/issues/7074)] / [[#9761](https://github.com/terraform-providers/terraform-provider-aws/issues/9761)) -* **New Resource:** `aws_fsx_windows_file_system` ([#7074](https://github.com/terraform-providers/terraform-provider-aws/issues/7074)] / [[#9761](https://github.com/terraform-providers/terraform-provider-aws/issues/9761)) -* **New Resource:** `aws_ram_resource_share_accepter` ([#8259](https://github.com/terraform-providers/terraform-provider-aws/issues/8259)) - -ENHANCEMENTS: - -* resource/aws_codebuild_project: Add `artifacts` configuration block `artifact_identifier` argument ([#9652](https://github.com/terraform-providers/terraform-provider-aws/issues/9652)) -* resource/aws_codebuild_project: Add plan time validation for `artifacts` and `secondary_artifacts` configuration blocks `packaging` argument ([#9652](https://github.com/terraform-providers/terraform-provider-aws/issues/9652)) -* resource/aws_rds_cluster: Add `multimaster` to `engine_mode` argument validation (support Aurora Multi-Master Clusters) ([#9691](https://github.com/terraform-providers/terraform-provider-aws/issues/9691)) -* resource/aws_rds_cluster_instance: Allow `aurora-mysql` (MySQL 5.7) engine to enable Performance Insights ([#9635](https://github.com/terraform-providers/terraform-provider-aws/issues/9635)) -* resource/aws_wafregional_regex_match_set: Support resource import ([#9699](https://github.com/terraform-providers/terraform-provider-aws/issues/9699)) -* resource/aws_wafregional_regex_pattern_set: Support resource import ([#9712](https://github.com/terraform-providers/terraform-provider-aws/issues/9712)) -* resource/aws_wafregional_size_constraint_set: Support resource import ([#9713](https://github.com/terraform-providers/terraform-provider-aws/issues/9713)) -* resource/aws_wafregional_sql_injection_match_set: Support resource import ([#9717](https://github.com/terraform-providers/terraform-provider-aws/issues/9717)) - -BUG FIXES: - -* resource/aws_acm_certificate_validation: Final retries after timeouts creating and checking validation for ACM certificates ([#9661](https://github.com/terraform-providers/terraform-provider-aws/issues/9661)) -* resource/aws_ami: Final retry after timeout reading AMI ([#9674](https://github.com/terraform-providers/terraform-provider-aws/issues/9674)) -* resource/aws_cloudhsm_v2_cluster: Final retries after timeouts creating, updating, and deleting CloudHSM clusters ([#9675](https://github.com/terraform-providers/terraform-provider-aws/issues/9675)) -* resource/aws_cloudhsm_v2_hsm: Final retries after timeouts creating and deleting CloudHSM modules ([#9675](https://github.com/terraform-providers/terraform-provider-aws/issues/9675)) -* resource/aws_cloudtrail: Final retries after timeouts creating and updating cloudtrails ([#9678](https://github.com/terraform-providers/terraform-provider-aws/issues/9678)) -* resource/aws_codebuild_project: Final retries after timeouts creating and updating codebuild projects ([#9682](https://github.com/terraform-providers/terraform-provider-aws/issues/9682)) -* resource/aws_codebuild_project: Properly perform drift detection and updates for `secondary_artifacts` configuration block arguments (except `name` which will require a separate fix) ([#9652](https://github.com/terraform-providers/terraform-provider-aws/issues/9652)) -* resource/aws_codedeploy_deployment_group: Final retries after timeouts creating and updating deployment groups ([#9682](https://github.com/terraform-providers/terraform-provider-aws/issues/9682)) -* resource/aws_codepipeline: Final retry after timeout creating codepipeline ([#9682](https://github.com/terraform-providers/terraform-provider-aws/issues/9682)) -* resource/aws_cognito_user_pool: Final retries after timeouts creating and updating Cognito user pools ([#9684](https://github.com/terraform-providers/terraform-provider-aws/issues/9684)) -* resource/aws_db_instance: Fix enabling Performance Insights on update without Performance Insights KMS Key ID ([#9745](https://github.com/terraform-providers/terraform-provider-aws/issues/9745)) -* resource/aws_dms_endpoint: Final retry after timeout creating DMS endpoint ([#9695](https://github.com/terraform-providers/terraform-provider-aws/issues/9695)) -* resource/aws_docdb_cluster_instance: Final retries after timeouts creating and updating DocDB cluster instances ([#9696](https://github.com/terraform-providers/terraform-provider-aws/issues/9696)) -* resource/aws_docdb_cluster_parameter_group: Final retry after timeout deleting DocDB cluster parameter groups ([#9696](https://github.com/terraform-providers/terraform-provider-aws/issues/9696)) -* resource/aws_docdb_subnet_group: Final retry after timeout deleting DocDB subnet groups ([#9696](https://github.com/terraform-providers/terraform-provider-aws/issues/9696)) -* resource/aws_dynamodb_table: Final retries after timeouts creating, updating, and deleting DynamoDB tables ([#9697](https://github.com/terraform-providers/terraform-provider-aws/issues/9697)) -* resource/aws_ebs_snapshot: Final retries after timeouts creating, deleting or waiting for available EBS snapshots ([#9698](https://github.com/terraform-providers/terraform-provider-aws/issues/9698)) -* resource/aws_ebs_snapshot_copy: Final retry after timeout deleting EBS snapshot copies ([#9698](https://github.com/terraform-providers/terraform-provider-aws/issues/9698)) -* resource/aws_ecs_cluster: Final retries after timeouts reading and deleting ECS cluster ([#9704](https://github.com/terraform-providers/terraform-provider-aws/issues/9704)) -* resource/aws_ecs_service: Final retries after timeouts creating, updating, and deleting ECS service ([#9704](https://github.com/terraform-providers/terraform-provider-aws/issues/9704)) -* resource/aws_eip: Final retries after timeouts reading, updating, and deleting EIPs ([#9728](https://github.com/terraform-providers/terraform-provider-aws/issues/9728)) -* resource/aws_eip_association: Final retry after timeout creating EIP association ([#9728](https://github.com/terraform-providers/terraform-provider-aws/issues/9728)) -* resource/aws_eks_cluster: Final retry after timeout creating EKS cluster ([#9729](https://github.com/terraform-providers/terraform-provider-aws/issues/9729)) -* resource/aws_elastic_beanstalk_application: Final retries after timeouts reading and deleting beanstalk applications ([#9731](https://github.com/terraform-providers/terraform-provider-aws/issues/9731)) -* resource/aws_gamelift_build: Final retry after timeout creating gamelift build ([#9752](https://github.com/terraform-providers/terraform-provider-aws/issues/9752)) -* resource/aws_gamelift fleet: Final retry after timeout deleting gamelift fleet ([#9752](https://github.com/terraform-providers/terraform-provider-aws/issues/9752)) -* resource/aws_glue_crawler: Final retry after timeout creating glue crawler ([#9753](https://github.com/terraform-providers/terraform-provider-aws/issues/9753)) -* resource/aws_guardduty_member: Final retry after timeout waiting for email invitation ([#9757](https://github.com/terraform-providers/terraform-provider-aws/issues/9757)) -* resource/aws_lb_target_group_attachment: Perform drift detection on attachments using target health description (trigger resource recreation for manually deregistered attachments) ([#9610](https://github.com/terraform-providers/terraform-provider-aws/issues/9610)) -* resource/aws_vpn_gateway: Retry after timeouts attaching and deleting VPN gateways, and retrying attachment after pending VPN errors ([#9641](https://github.com/terraform-providers/terraform-provider-aws/issues/9641)) - -## 2.23.0 (August 07, 2019) - -FEATURES: - -* **New Data Source:** `aws_s3_bucket_objects` ([#6968](https://github.com/terraform-providers/terraform-provider-aws/issues/6968)) -* **New Resource:** `aws_dx_transit_virtual_interface` ([#8522](https://github.com/terraform-providers/terraform-provider-aws/issues/8522)) -* **New Resource:** `aws_redshift_snapshot_schedule` ([#8064](https://github.com/terraform-providers/terraform-provider-aws/issues/8064)) -* **New Resource:** `aws_redshift_snapshot_schedule_association` ([#8064](https://github.com/terraform-providers/terraform-provider-aws/issues/8064)) - -ENHANCEMENTS: - -* data-source/aws_eks_cluster: Add `status` attribute ([#9582](https://github.com/terraform-providers/terraform-provider-aws/issues/9582)) -* data-source/aws_instance: Add `ebs_block_device` and `root_block_device` configuration block `encryption` and `kms_key_id` attributes ([#4861](https://github.com/terraform-providers/terraform-provider-aws/issues/4861)] / [[#7757](https://github.com/terraform-providers/terraform-provider-aws/issues/7757)) -* data-source/aws_partition: Add `dns_suffix` attribute (e.g. `amazonaws.com` in AWS Commercial, `amazonaws.com.cn` in AWS China) ([#5602](https://github.com/terraform-providers/terraform-provider-aws/issues/5602)) -* resource/aws_acm_certificate: Support `options` configuration block `certificate_transparency_logging_preference` argument ([#9413](https://github.com/terraform-providers/terraform-provider-aws/issues/9413)) -* resource/aws_acm_certificate: Add `certificate_authority_arn` argument (support issuance of ACM private certificates) ([#6666](https://github.com/terraform-providers/terraform-provider-aws/issues/6666)) -* resource/aws_cognito_identity_pool: Add `tags` argument ([#9639](https://github.com/terraform-providers/terraform-provider-aws/issues/9639)) -* resource/aws_ecr_repository: Add `image_tag_mutability` argument (support immutable image tags) ([#9557](https://github.com/terraform-providers/terraform-provider-aws/issues/9557)) -* resource/aws_efs_file_system: Add `lifecycle_policy` configuration block (support transition to IA storage after 14, 30, 60, or 90 days) ([#9636](https://github.com/terraform-providers/terraform-provider-aws/issues/9636)) -* resource/aws_eks_cluster: Add `status` attribute ([#9582](https://github.com/terraform-providers/terraform-provider-aws/issues/9582)) -* resource/aws_glue_crawler: Add `catalog_target` configuration block ([#9430](https://github.com/terraform-providers/terraform-provider-aws/issues/9430)) -* resource/aws_instance: Add `ebs_block_device` and `root_block_device` configuration block `encryption` and `kms_key_id` arguments (support encryption on launch) ([#4861](https://github.com/terraform-providers/terraform-provider-aws/issues/4861)] / [[#7757](https://github.com/terraform-providers/terraform-provider-aws/issues/7757)) -* resource/aws_iot_certificate: Mark `csr` argument as optional and add `certificate_pem`, `public_key`, and `private_key` attributes (support creating key and certificate) ([#9283](https://github.com/terraform-providers/terraform-provider-aws/issues/9283)) -* resource/aws_lambda_permission: Support resource import ([#9369](https://github.com/terraform-providers/terraform-provider-aws/issues/9369)) -* resource/aws_launch_configuration: Add `root_block_device` configuration block `encrypted` argument (support encryption on launch) ([#7759](https://github.com/terraform-providers/terraform-provider-aws/issues/7759)) -* resource/aws_s3_bucket_object: Added plan time validation for `bucket` and `key` arguments ([#9591](https://github.com/terraform-providers/terraform-provider-aws/issues/9591)) -* resource/aws_spot_fleet_request: Add `ebs_block_device` and `root_block_device` configuration block `kms_key_id` argument (support encryption on launch) ([#9599](https://github.com/terraform-providers/terraform-provider-aws/issues/9599)) -* resource/aws_wafregional_geo_match_set: Support resource import ([#9620](https://github.com/terraform-providers/terraform-provider-aws/issues/9620)) -* resource/aws_wafregional_rate_based_rule: Support resource import ([#9621](https://github.com/terraform-providers/terraform-provider-aws/issues/9621)) - -BUG FIXES: - -* provider: Environment credentials have precedence over shared config credentials even if the `AWS_PROFILE` environment credentials are present. Explicitly configure the provider `profile` to override this behavior. The AWS Go SDK change that was released in version 2.21.0 of the Terraform AWS Provider has been mostly reverted. ([#9555](https://github.com/terraform-providers/terraform-provider-aws/issues/9555)) -* resource/aws_acm_certificate: Wait for presence of `DomainValidationOptions` when requesting ACM certificates (previously the API would always immediately return this information during creation) ([#9598](https://github.com/terraform-providers/terraform-provider-aws/issues/9598)) -* resource/aws_autoscaling_group: Final retries after timeouts creating, draining, and deleting ASGs and autoscaling helpers ([#9649](https://github.com/terraform-providers/terraform-provider-aws/issues/9649)) -* resource/aws_cloud9_environment_ec2: Final retries after timeouts creating and deleting Cloud9 environments ([#9629](https://github.com/terraform-providers/terraform-provider-aws/issues/9629)) -* resource/aws_cloudfront_distribution: Ensure deployment timeout matches documentation at 90 minutes ([#9642](https://github.com/terraform-providers/terraform-provider-aws/issues/9642)) -* resource/aws_datasync_agent: Final retries after timeouts creating datasync agent ([#9608](https://github.com/terraform-providers/terraform-provider-aws/issues/9608)) -* resource/aws_datasync_task: Final retry after timeout error creating datasync task ([#9608](https://github.com/terraform-providers/terraform-provider-aws/issues/9608)) -* resource/aws_dax_cluster: Final retries after timeouts when creating and deleting Dax clusters ([#9630](https://github.com/terraform-providers/terraform-provider-aws/issues/9630)) -* resource/aws_egress_only_internet_gateway: Final retry after timeout when reading gateway ([#9638](https://github.com/terraform-providers/terraform-provider-aws/issues/9638)) -* resource/aws_lambda_event_source_mapping: Final retries after timeout when creating, updating, and deleting event source mappings ([#9553](https://github.com/terraform-providers/terraform-provider-aws/issues/9553)) -* resource/aws_lambda_function: Final retry when creating lambda function ([#9553](https://github.com/terraform-providers/terraform-provider-aws/issues/9553)) -* resource/aws_lambda_permission: Final retries when creating, reading, and deleting lambda permissions ([#9553](https://github.com/terraform-providers/terraform-provider-aws/issues/9553)) -* resource/aws_media_package_channel: Final retries after timeouts deleting media package channels ([#9633](https://github.com/terraform-providers/terraform-provider-aws/issues/9633)) -* resource/aws_media_store_container: Final retries after timeouts deleting media store containers ([#9633](https://github.com/terraform-providers/terraform-provider-aws/issues/9633)) -* resource/aws_organizations_organizational_unit: Final retry after timeout when creating organizational unit ([#9631](https://github.com/terraform-providers/terraform-provider-aws/issues/9631)) -* resource/aws_organizations_policy: Final retry after timeout creating policy ([#9631](https://github.com/terraform-providers/terraform-provider-aws/issues/9631)) -* resource/aws_organizations_policy_attachment: Final retry after timeout creating policy attachment ([#9631](https://github.com/terraform-providers/terraform-provider-aws/issues/9631)) -* resource/aws_secretsmanager_secret: Final retries after timeouts creating and updating secrets ([#9632](https://github.com/terraform-providers/terraform-provider-aws/issues/9632)) -* resource/aws_sns_platform_application: Final retry after timeout error updating SNS platform application ([#9607](https://github.com/terraform-providers/terraform-provider-aws/issues/9607)) -* resource/aws_vpc: Final retry after timeout deleting VPC ([#9644](https://github.com/terraform-providers/terraform-provider-aws/issues/9644)) - -## 2.22.0 (August 01, 2019) - -NOTES: - -* provider: Region validation now automatically supports the new `me-south-1` Middle East (Bahrain) region. For AWS operations to work in the new region, the region must be explicitly enabled as outlined in the [previous new region announcement blog post](https://aws.amazon.com/blogs/aws/now-open-aws-asia-pacific-hong-kong-region/). When the region is not enabled, the Terraform AWS Provider will return errors during credential validation (e.g. `error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid`) or AWS operations will throw their own errors (e.g. `data.aws_availability_zones.current: Error fetching Availability Zones: AuthFailure: AWS was not able to validate the provided access credentials`). ([#9538](https://github.com/terraform-providers/terraform-provider-aws/issues/9538)) - -FEATURES: - -* **New Resource:** `aws_codebuild_source_credential` ([#7631](https://github.com/terraform-providers/terraform-provider-aws/issues/7631)) -* **New Resource:** `aws_fms_admin_account` ([#4310](https://github.com/terraform-providers/terraform-provider-aws/issues/4310)) - -ENHANCEMENTS: - -* data-source/aws_cloudtrail_service_account: Support `me-south-1` region ([#9547](https://github.com/terraform-providers/terraform-provider-aws/issues/9547)) -* data-source/aws_elastic_beanstalk_hosted_zone: Support `me-south-1` region ([#9547](https://github.com/terraform-providers/terraform-provider-aws/issues/9547)) -* data-source/aws_elb_hosted_zone_id: Support `me-south-1` region ([#9547](https://github.com/terraform-providers/terraform-provider-aws/issues/9547)) -* data-source/aws_elb_service_account: Support `me-south-1` region ([#9547](https://github.com/terraform-providers/terraform-provider-aws/issues/9547)) -* data-source/aws_s3_bucket: Support `me-south-1` region for `hosted_zone_id` attribute ([#9547](https://github.com/terraform-providers/terraform-provider-aws/issues/9547)) -* provider: Support automatic region validation for `me-south-1` ([#9538](https://github.com/terraform-providers/terraform-provider-aws/issues/9538)) -* resource/aws_codebuild_project: Add `override_artifact_name` argument to `artifacts` and `secondary_artifacts` configuration blocks ([#7824](https://github.com/terraform-providers/terraform-provider-aws/issues/7824)) -* resource/aws_config_aggregate_authorization: Add `tags` argument ([#9561](https://github.com/terraform-providers/terraform-provider-aws/issues/9561)) -* resource/aws_config_config_rule: Add `tags` argument ([#9561](https://github.com/terraform-providers/terraform-provider-aws/issues/9561)) -* resource/aws_config_configuration_aggregator: Add `tags` argument ([#9561](https://github.com/terraform-providers/terraform-provider-aws/issues/9561)) -* resource/aws_ec2_client_vpn_endpoint: Add `split_tunnel` argument ([#9566](https://github.com/terraform-providers/terraform-provider-aws/issues/9566)) -* resource/aws_ecs_service: Allow multiple `load_balancer` configuration blocks (support for multiple target groups) ([#9411](https://github.com/terraform-providers/terraform-provider-aws/issues/9411)) -* resource/aws_pinpoint_app: Add `tags` argument ([#9460](https://github.com/terraform-providers/terraform-provider-aws/issues/9460)) -* resource/aws_route_table_association: Support resource import ([#6999](https://github.com/terraform-providers/terraform-provider-aws/issues/6999)) -* resource/aws_route_table_association: Allow in-place updates of `subnet_id` argument ([#6999](https://github.com/terraform-providers/terraform-provider-aws/issues/6999)) -* resource/aws_s3_bucket: Support `me-south-1` region for `hosted_zone_id` attribute ([#9547](https://github.com/terraform-providers/terraform-provider-aws/issues/9547)) - -BUG FIXES: - -* resource/aws_codebuild_project: Properly perform drift detection and updates for `artifacts` configuration block arguments ([#9559](https://github.com/terraform-providers/terraform-provider-aws/issues/9559)) -* resource/aws_ec2_client_vpn_endpoint: Remove hardcoded one minute timeout during resource creation ([#9558](https://github.com/terraform-providers/terraform-provider-aws/issues/9558)) -* resource/aws_route53_record: Prevent error when removing `weighted_routing_policy` ([#9565](https://github.com/terraform-providers/terraform-provider-aws/issues/9565)) -* resource/aws_storagegateway_cached_iscsi_volume: Retry after timeout deleting volume ([#9536](https://github.com/terraform-providers/terraform-provider-aws/issues/9536)) -* resource/aws_storagegateway_cached_iscsi_volume: Fix errors deleting volumes when volumes don't exist ([#9543](https://github.com/terraform-providers/terraform-provider-aws/issues/9543)) -* resource/aws_storagegateway_gateway: Retry after timeouts creating gateway ([#9536](https://github.com/terraform-providers/terraform-provider-aws/issues/9536)) - -## 2.21.1 (July 26, 2019) - -BUG FIXES: - -* resource/aws_autoscaling_group: Revert change from version 2.21.0 to `load_balancers` and `target_group_arns` arguments that removes attachments when using the `aws_autoscaling_attachment` resource (https://github.com/terraform-providers/terraform-provider-aws/issues/9513) ([#9518](https://github.com/terraform-providers/terraform-provider-aws/issues/9518)) - -## 2.21.0 (July 25, 2019) - -NOTES: - -* provider: After this update, the AWS Go SDK will prefer credentials found via the `AWS_PROFILE` environment variable when both the `AWS_PROFILE` environment variable and the `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` environment variables are statically defined. Previously the SDK would ignore the `AWS_PROFILE` environment variable, if static environment credentials were also specified. This is listed as a bug fix in the AWS Go SDK release notes. ([#9428](https://github.com/terraform-providers/terraform-provider-aws/issues/9428)) - -FEATURES: -* **New Data Source**: `aws_organizations_organization` ([#9419](https://github.com/terraform-providers/terraform-provider-aws/issues/9419)) -* **New Data Source**: `aws_waf_ipset` ([#9481](https://github.com/terraform-providers/terraform-provider-aws/issues/9481)) -* **New Data Source**: `aws_wafregional_ipset` ([#9484](https://github.com/terraform-providers/terraform-provider-aws/issues/9484)) - -ENHANCEMENTS: - -* provider: Add support for assuming role via web identity token via the `AWS_WEB_IDENTITY_TOKEN_FILE` and `AWS_ROLE_ARN` environment variables ([#9428](https://github.com/terraform-providers/terraform-provider-aws/issues/9428)) -* resource/aws_cloudwatch_event_target: Support resource import ([#9431](https://github.com/terraform-providers/terraform-provider-aws/issues/9431)) -* resource/aws_s3_bucket_object: Add `metadata` argument ([#1945](https://github.com/terraform-providers/terraform-provider-aws/issues/1945)) -* resource/aws_wafregional_ipset: Support resource import ([#9424](https://github.com/terraform-providers/terraform-provider-aws/issues/9424)) - -BUG FIXES: - -* provider: Load credentials via the `AWS_PROFILE` environment variable (if available) when `AWS_PROFILE` is defined along with `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` ([#9428](https://github.com/terraform-providers/terraform-provider-aws/issues/9428)) -* resource/aws_autoscaling_group: Always perform drift detection with `load_balancers` and `target_group_arns` arguments ([#9478](https://github.com/terraform-providers/terraform-provider-aws/issues/9478)) -* resource/aws_cloudfront_distribution: Prevent `DistributionAlreadyExists` errors during concurrent distribution creation ([#9470](https://github.com/terraform-providers/terraform-provider-aws/issues/9470)) -* resource/aws_cognito_user_pool_client: Properly update name value ([#9437](https://github.com/terraform-providers/terraform-provider-aws/issues/9437)) -* resource/aws_config_config_rule: Retries after timeouts when creating and deleting config rules ([#9438](https://github.com/terraform-providers/terraform-provider-aws/issues/9438)) -* resource/aws_config_delivery_channel: Retries after timeouts when creating and deleting config delivery channels ([#9438](https://github.com/terraform-providers/terraform-provider-aws/issues/9438)) -* resource/aws_customer_gateway: Final retry after timeout deleting customer gateway ([#9421](https://github.com/terraform-providers/terraform-provider-aws/issues/9421)) -* resource/aws_db_instance: Redact `MasterUserPassword` from user interface when displaying `InvalidParameterValue` error during resource creation ([#9446](https://github.com/terraform-providers/terraform-provider-aws/issues/9446)) -* resource/aws_db_instance: Retries after timeouts creating DB instances ([#9477](https://github.com/terraform-providers/terraform-provider-aws/issues/9477)) -* resource/aws_db_option_group: Retry after timeout deleting DB option group ([#9477](https://github.com/terraform-providers/terraform-provider-aws/issues/9477)) -* resource/aws_db_parameter_group: Retry after timeout deleting DB parameter group ([#9477](https://github.com/terraform-providers/terraform-provider-aws/issues/9477)) -* resource/aws_kms_grant: Final retries after timeouts when creating, finding, and revoking grants ([#9415](https://github.com/terraform-providers/terraform-provider-aws/issues/9415)) -* resource/aws_kms_key: Final retries after timeouts when creating keys and updating key rotation status ([#9415](https://github.com/terraform-providers/terraform-provider-aws/issues/9415)) -* resource/aws_rds_cluster: Properly update `master_password` during snapshot restore ([#9505](https://github.com/terraform-providers/terraform-provider-aws/issues/9505)) -* resource/aws_s3_bucket: Ensure `website_endpoint` and `website_domain` attributes have correct DNS suffix in AWS China ([#9444](https://github.com/terraform-providers/terraform-provider-aws/issues/9444)) -* resource/aws_ses_domain_identity_verification: Retry after timeout when creating SES domain identity verification ([#9417](https://github.com/terraform-providers/terraform-provider-aws/issues/9417)) -* resource/aws_sfn_activity: Retry after timeout deleting SFN activity ([#9498](https://github.com/terraform-providers/terraform-provider-aws/issues/9498)) -* resource/aws_sfn_state_machine: Retry after timeouts deleting and creating SFN state machines ([#9498](https://github.com/terraform-providers/terraform-provider-aws/issues/9498)) - -## 2.20.0 (July 19, 2019) - -NOTES: - -* resource/aws_ssm_maintenance_window_task: The `logging_info` and `task_parameters` configuration blocks have been deprecated in favor of a new `task_invocation_parameters` configuration block to match the API ([#7823](https://github.com/terraform-providers/terraform-provider-aws/issues/7823)) - -FEATURES: -* **New Data Source** `aws_waf_rule` ([#9318](https://github.com/terraform-providers/terraform-provider-aws/issues/9318)) -* **New Data Source:** `aws_waf_web_acl` ([#9320](https://github.com/terraform-providers/terraform-provider-aws/issues/9320)) -* **New Data Source** `aws_wafregional_rule` ([#9319](https://github.com/terraform-providers/terraform-provider-aws/issues/9319)) -* **New Data Source:** `aws_wafregional_web_acl` ([#9321](https://github.com/terraform-providers/terraform-provider-aws/issues/9321)) -* **New Resource:** `aws_quicksight_group` ([#8233](https://github.com/terraform-providers/terraform-provider-aws/issues/8233)) -* **New Resource:** `aws_servicequotas_service_quota` ([#9192](https://github.com/terraform-providers/terraform-provider-aws/issues/9192)) - -ENHANCEMENTS: - -* data-source/aws_route53_zone: Add `linked_service_principal` and `linked_service_description` attributes ([#9390](https://github.com/terraform-providers/terraform-provider-aws/issues/9390)) -* provider: Support for assuming role using credential process from the shared AWS configuration file ([#9305](https://github.com/terraform-providers/terraform-provider-aws/issues/9305)) -* resource/aws_api_gateway_domain_name: Add `security_policy` argument ([#9128](https://github.com/terraform-providers/terraform-provider-aws/issues/9128)) -* resource/aws_athena_named_query: Add `workgroup` argument ([#9383](https://github.com/terraform-providers/terraform-provider-aws/issues/9383)) -* resource/aws_autoscaling_lifecycle_hook: Support resource import ([#9336](https://github.com/terraform-providers/terraform-provider-aws/issues/9336)) -* resource/aws_elasticsearch_domain: Add `cluster_config` configuration block `zone_awareness_config` configuration block (support three Availability Zone awareness) ([#9398](https://github.com/terraform-providers/terraform-provider-aws/issues/9398)) -* resource/aws_emr_cluster: Add `master_instance_group` configuration block `instance_count` argument (support multiple master nodes) ([#9235](https://github.com/terraform-providers/terraform-provider-aws/issues/9235)) -* resource/aws_media_store_container: Add `tags` argument ([#9379](https://github.com/terraform-providers/terraform-provider-aws/issues/9379)) -* resource/aws_rds_cluster: Support `scaling_configuration` configuration block `timeout_action` argument ([#9374](https://github.com/terraform-providers/terraform-provider-aws/issues/9374)) -* resource/aws_s3_bucket_object: Allow empty object ([#7544](https://github.com/terraform-providers/terraform-provider-aws/issues/7544)) -* resource/aws_ssm_maintenance_window_task: Support resource import and in-place updates ([#7823](https://github.com/terraform-providers/terraform-provider-aws/issues/7823)) -* resource/aws_ssm_maintenance_window_task: Add `task_invocation_parameters` configuration block and deprecate `logging_info` and `task_parameters` configuration blocks to match API ([#7823](https://github.com/terraform-providers/terraform-provider-aws/issues/7823)) - -BUG FIXES: - -* resource/aws_appautoscaling_policy: Properly support importing of dynamodb policies ([#8397](https://github.com/terraform-providers/terraform-provider-aws/issues/8397)) -* resource/aws_cloudwatch_event_permissions: Clean up error handling when reading event permissions ([#9065](https://github.com/terraform-providers/terraform-provider-aws/issues/9065)) -* resource/aws_cloudwatch_event_rule: Retry error handling when creating and updating event rules ([#9065](https://github.com/terraform-providers/terraform-provider-aws/issues/9065)) -* resource/aws_cloudwatch_log_destination: Clean up error handling when putting log destination ([#9065](https://github.com/terraform-providers/terraform-provider-aws/issues/9065)) -* resource/aws_cloudwatch_log_subscription_filter: Clean up error handling when creating log subscription filter ([#9065](https://github.com/terraform-providers/terraform-provider-aws/issues/9065)) -* resource/aws_cognito_identity_provider: Properly pass all attributes during update ([#9396](https://github.com/terraform-providers/terraform-provider-aws/issues/9396)) -* resource/aws_db_event_subscription: Handle `SubscriptionNotFound` errors during refresh and deletion ([#9371](https://github.com/terraform-providers/terraform-provider-aws/issues/9371)) -* resource/aws_s3_account_public_access_block: Retry after timeout when reading s3 account public access block ([#9387](https://github.com/terraform-providers/terraform-provider-aws/issues/9387)) -* resource/aws_ssm_maintenance_window_task: Bypass `DoesNotExistException` error on deletion ([#7823](https://github.com/terraform-providers/terraform-provider-aws/issues/7823)) -* resource/aws_ssm_maintenance_window_task: Prevent `task_parameters` ordering differences ([#9364](https://github.com/terraform-providers/terraform-provider-aws/issues/9364)) - -## 2.19.0 (July 11, 2019) - -FEATURES: - -* **New Data Source:** `aws_msk_configuration` ([#9088](https://github.com/terraform-providers/terraform-provider-aws/issues/9088)) -* **New Resource:** `aws_athena_workgroup` ([#9290](https://github.com/terraform-providers/terraform-provider-aws/issues/9290)) -* **New Resource:** `aws_datapipeline_pipeline` ([#9267](https://github.com/terraform-providers/terraform-provider-aws/issues/9267)) -* **New Resource:** `aws_directory_service_log_subscription` ([#9261](https://github.com/terraform-providers/terraform-provider-aws/issues/9261)) - -ENHANCEMENTS: - -* resource/aws_acmpca_certificate_authority: Support validation for `ROOT` certificate authority type ([#9292](https://github.com/terraform-providers/terraform-provider-aws/issues/9292)) -* resource/aws_appmesh_virtual_node: Add `aws_cloud_map` configuration block under `spec` and `service_discovery` ([#9271](https://github.com/terraform-providers/terraform-provider-aws/issues/9271)) -* resource/aws_appmesh_virtual_router: Add `tags` argument ([#9249](https://github.com/terraform-providers/terraform-provider-aws/issues/9249)) -* resource/aws_appmesh_virtual_service: Add `tags` argument ([#9252](https://github.com/terraform-providers/terraform-provider-aws/issues/9252)) -* resource/aws_codebuild_project: Add `environment` configuration block `registry_credential` configuration block (support Secrets Manager registry credentials) ([#9168](https://github.com/terraform-providers/terraform-provider-aws/issues/9168)) -* resource/aws_codebuild_project: Add `logs_config` configuration block (support CloudWatch and S3 logging configuration) ([#7534](https://github.com/terraform-providers/terraform-provider-aws/issues/7534)) -* resource/aws_ebs_snapshot: Support customizable create/delete timeouts and increase defaults to 10 minutes ([#9157](https://github.com/terraform-providers/terraform-provider-aws/issues/9157)) -* resource/aws_lightsail_instance: Add validation for `name` argument ([#8667](https://github.com/terraform-providers/terraform-provider-aws/issues/8667)) -* resource/aws_lightsail_instance: Add `tags` argument ([#9273](https://github.com/terraform-providers/terraform-provider-aws/issues/9273)) -* resource/aws_organizations_account: Add `tags` argument ([#9202](https://github.com/terraform-providers/terraform-provider-aws/issues/9202)) -* resource/aws_service_discovery_service: Add `namespace_id` argument (Support HTTP namespaces) ([#7341](https://github.com/terraform-providers/terraform-provider-aws/issues/7341)) -* resource/aws_ssm_document: Support resource import ([#9313](https://github.com/terraform-providers/terraform-provider-aws/issues/9313)) -* resource/aws_waf_rule_group: Support resource import ([#9254](https://github.com/terraform-providers/terraform-provider-aws/issues/9254)) -* resource/aws_wafregional_byte_match_set: Support resource import ([#9258](https://github.com/terraform-providers/terraform-provider-aws/issues/9258)) -* resource/aws_wafregional_rule: Support resource import ([#9239](https://github.com/terraform-providers/terraform-provider-aws/issues/9239)) -* resource/aws_wafregional_rule_group: Support resource import ([#9240](https://github.com/terraform-providers/terraform-provider-aws/issues/9240)) -* resource/aws_wafregional_web_acl: Support resource import ([#9248](https://github.com/terraform-providers/terraform-provider-aws/issues/9248)) - -BUG FIXES: - -* resource/aws_backup_selection: Retry creation for IAM eventual consistency error ([#9298](https://github.com/terraform-providers/terraform-provider-aws/issues/9298)) -* resource/aws_db_event_subscription: Prevent `Unable to find RDS Event Subscription` error during deletion and refresh ([#9274](https://github.com/terraform-providers/terraform-provider-aws/issues/9274)) -* resource/aws_iam_policy_attachment: Bypass `NoSuchEntity` error when detaching groups, roles, and users (support group, role (when `force_detach_policies` is enabled), and user renames (when `force_destroy` is enabled)) ([#9278](https://github.com/terraform-providers/terraform-provider-aws/issues/9278)) -* resource/aws_s3_bucket: Properly handle the creation of tags defined in `lifecycle_rule` when no prefix argument is specified ([#7162](https://github.com/terraform-providers/terraform-provider-aws/issues/7162)) -* resource/aws_ssm_document: Ensure `content` attribute is always refreshed ([#9313](https://github.com/terraform-providers/terraform-provider-aws/issues/9313)) -* resource/aws_transfer_user: Final retry after timeout waiting for deletion of transfer user ([#9241](https://github.com/terraform-providers/terraform-provider-aws/issues/9241)) -* service/organizations: Automatically retry API calls on `ConcurrentModificationException` error ([#9195](https://github.com/terraform-providers/terraform-provider-aws/issues/9195)) - -## 2.18.0 (July 05, 2019) - -FEATURES: - -* **New Data Source:** `aws_servicequotas_service` ([#9177](https://github.com/terraform-providers/terraform-provider-aws/issues/9177)) -* **New Data Source:** `aws_servicequotas_service_quota` ([#9177](https://github.com/terraform-providers/terraform-provider-aws/issues/9177)) - -ENHANCEMENTS: - -* resource/aws_appmesh_route: Add `tags` argument ([#9206](https://github.com/terraform-providers/terraform-provider-aws/issues/9206)) -* resource/aws_appmesh_virtual_node: Add `tags` argument ([#9207](https://github.com/terraform-providers/terraform-provider-aws/issues/9207)) -* resource/aws_codecommit_repository: Add `tags` argument ([#9215](https://github.com/terraform-providers/terraform-provider-aws/issues/9215)) -* resource/aws_ec2_transit_gateway_route: Add `blackhole` argument ([#9224](https://github.com/terraform-providers/terraform-provider-aws/issues/9224)) -* resource/aws_iam_group_policy: Support resource import ([#9217](https://github.com/terraform-providers/terraform-provider-aws/issues/9217)) - -BUG FIXES: - -* resource/aws_db_instance: Properly include `allow_major_version_upgrade` value when creating an RDS instance from a replica or snapshot to allow RDS to perform a major version upgrade if necessary ([#9178](https://github.com/terraform-providers/terraform-provider-aws/issues/9178)) -* resource/aws_db_instance: Prevent `InvalidParameterCombination: No modifications were requested` error when updating only `allow_major_version_upgrade` argument ([#9193](https://github.com/terraform-providers/terraform-provider-aws/issues/9193)) -* resource/aws_emr_cluster: Skip refreshing the `kerberos_attributes` configuration block `ad_domain_join_user` argument from the API as it does not contain the real configuration value ([#8559](https://github.com/terraform-providers/terraform-provider-aws/issues/8559)) - -## 2.17.0 (June 28, 2019) - -FEATURES: - -* **New Data Source:** `aws_ebs_default_kms_key` ([#8884](https://github.com/terraform-providers/terraform-provider-aws/issues/8884)) -* **New Data Source:** `aws_ebs_encryption_by_default` ([#8884](https://github.com/terraform-providers/terraform-provider-aws/issues/8884)) -* **New Resource:** `aws_appsync_function` ([#8502](https://github.com/terraform-providers/terraform-provider-aws/issues/8502)) - -ENHANCEMENTS: - -* data-source/aws_acm_certificate: Add `key_types` argument (support searching for non-default key algorithm certificates such as RSA 4096 bit) ([#8553](https://github.com/terraform-providers/terraform-provider-aws/issues/8553)) -* data-source/aws_ssm_parameter: Add `version` attribute ([#9127](https://github.com/terraform-providers/terraform-provider-aws/issues/9127)) -* resource/aws_appmesh_mesh: Add `tags` argument ([#8111](https://github.com/terraform-providers/terraform-provider-aws/issues/8111)) -* resource/aws_appsync_resolver: Add `kind` argument and `pipeline_config` configuration block ([#8502](https://github.com/terraform-providers/terraform-provider-aws/issues/8502)) -* resource/aws_db_instance: Add `max_allocated_storage` argument (support Storage Autoscaling) ([#9087](https://github.com/terraform-providers/terraform-provider-aws/issues/9087)) -* resource/aws_directory_service_directory: Tag on create (support tag limiting IAM policies) ([#7937](https://github.com/terraform-providers/terraform-provider-aws/issues/7937)) -* resource/aws_dms_endpoint: Support `db2` in `engine_name` validation ([#9097](https://github.com/terraform-providers/terraform-provider-aws/issues/9097)) -* resource/aws_kinesis_firehose_delivery_stream: Tag on create (support tag limiting IAM policies) ([#7981](https://github.com/terraform-providers/terraform-provider-aws/issues/7981)) -* resource/aws_lb_listener: Support `TCP_UDP` and `UDP` in `protocol` validation ([#9111](https://github.com/terraform-providers/terraform-provider-aws/issues/9111)) -* resource/aws_lb_target_group: Support `TCP_UDP` and `UDP` in `protocol` validation ([#9111](https://github.com/terraform-providers/terraform-provider-aws/issues/9111)) -* resource/aws_route53_healthcheck: Add validation for `request_interval` argument ([#9158](https://github.com/terraform-providers/terraform-provider-aws/issues/9158)) -* resource/aws_ssm_parameter: Add `version` attribute ([#9127](https://github.com/terraform-providers/terraform-provider-aws/issues/9127)) - -BUG FIXES: -* resource/aws_api_gateway_account: Fix error handling during update ([#9068](https://github.com/terraform-providers/terraform-provider-aws/issues/9068)) -* resource/aws_api_gateway_base_path_mapping: Fix error handling during create ([#9068](https://github.com/terraform-providers/terraform-provider-aws/issues/9068)) -* resource/aws_api_gateway_domain_name: Remove unnecessary retry during delete ([#9068](https://github.com/terraform-providers/terraform-provider-aws/issues/9068)) -* resource/aws_api_gateway_gateway_response: Remove unnecessary retry during delete ([#9068](https://github.com/terraform-providers/terraform-provider-aws/issues/9068)) -* resource/aws_api_gateway_model: Remove unnecessary retry during delete ([#9068](https://github.com/terraform-providers/terraform-provider-aws/issues/9068)) -* resource/aws_api_gateway_usage_plan: Remove unnecessary retry during delete ([#9068](https://github.com/terraform-providers/terraform-provider-aws/issues/9068)) -* resource/aws_api_gateway_usage_plan_key: Remove unnecessary retry during delete ([#9068](https://github.com/terraform-providers/terraform-provider-aws/issues/9068)) -* resource/aws_db_snapshot: Prevent not found error when deleted outside Terraform ([#9099](https://github.com/terraform-providers/terraform-provider-aws/issues/9099)) -* resource/aws_ebs_snapshot_copy: Prevent error when resource is deleted outside Terraform ([#9106](https://github.com/terraform-providers/terraform-provider-aws/issues/9106)) -* resource/aws_ecr_repository: Final retries when reading and deleting ECR repositories ([#9079](https://github.com/terraform-providers/terraform-provider-aws/issues/9079)) -* resource/aws_ecr_repository_policy: Final retries when creating and updating ECR repository policies ([#9079](https://github.com/terraform-providers/terraform-provider-aws/issues/9079)) -* resource/aws_lb_target_group: Properly validate up to `120` seconds for `health_check` configuration block `timeout` argument ([#9152](https://github.com/terraform-providers/terraform-provider-aws/issues/9152)) -* resource/aws_spot_fleet_request: Add final retry when creating spot fleet request ([#9078](https://github.com/terraform-providers/terraform-provider-aws/issues/9078)) -* resource/aws_spot_instance_request: Add final retry when creating spot instance request ([#9078](https://github.com/terraform-providers/terraform-provider-aws/issues/9078)) -* resource/aws_ssm_maintenance_window_target: Prevent `InvalidParameter` error on resource creation when optional `name` or `description` were missing ([#9165](https://github.com/terraform-providers/terraform-provider-aws/issues/9165)) - -## 2.16.0 (June 20, 2019) - -FEATURES: - -* **New Resource:** `aws_globalaccelerator_endpoint_group` ([#8328](https://github.com/terraform-providers/terraform-provider-aws/issues/8328)) -* **New Resource:** `aws_ebs_default_kms_key` ([#8771](https://github.com/terraform-providers/terraform-provider-aws/issues/8771)) -* **New Resource:** `aws_ebs_encryption_by_default` ([#8771](https://github.com/terraform-providers/terraform-provider-aws/issues/8771)) -* **New Resource:** `aws_ses_identity_policy` ([#5128](https://github.com/terraform-providers/terraform-provider-aws/issues/5128)) - -ENHANCEMENTS: - -* data-source/aws_vpc_endpoint: Add `owner_id` and `tags` attributes ([#8674](https://github.com/terraform-providers/terraform-provider-aws/issues/8674)) -* data-source/aws_vpc_endpoint: Add `requester_managed` attribute ([#8396](https://github.com/terraform-providers/terraform-provider-aws/issues/8396)) -* data-source/aws_vpc_endpoint_service: Add `manages_vpc_endpoints` attribute ([#8396](https://github.com/terraform-providers/terraform-provider-aws/issues/8396)) -* data-source/aws_vpc_endpoint_service: Add `service_id` and `tags` attributes ([#8674](https://github.com/terraform-providers/terraform-provider-aws/issues/8674)) -* provider: Support for chaining assume IAM role from AWS shared configuration files ([#8987](https://github.com/terraform-providers/terraform-provider-aws/issues/8987)) -* resource/aws_backup_vault: Support resource import ([#9041](https://github.com/terraform-providers/terraform-provider-aws/issues/9041)) -* resource/aws_codepipeline: Add `tags` argument ([#8993](https://github.com/terraform-providers/terraform-provider-aws/issues/8993)) -* resource/aws_codepipeline_webhook: Add `tags` argument ([#8993](https://github.com/terraform-providers/terraform-provider-aws/issues/8993)) -* resource/aws_ecs_task_definition: Add `proxy_configuration` configuration block (support AppMesh proxying) ([#8780](https://github.com/terraform-providers/terraform-provider-aws/issues/8780)) -* resource/aws_instance: Prevent panic when `credit_specification` configuration block is missing arguments ([#9003](https://github.com/terraform-providers/terraform-provider-aws/issues/9003)) -* resource/aws_organizations_organization: Add `non_master_accounts` attribute ([#8926](https://github.com/terraform-providers/terraform-provider-aws/issues/8926)) -* resource/aws_secretsmanager_secret: Tag on create (support tag limiting IAM policies) ([#9023](https://github.com/terraform-providers/terraform-provider-aws/issues/9023)) -* resource/aws_vpc_endpoint: Add `owner_id` attribute ([#8674](https://github.com/terraform-providers/terraform-provider-aws/issues/8674)) -* resource/aws_vpc_endpoint: Add `requester_managed` attribute ([#8396](https://github.com/terraform-providers/terraform-provider-aws/issues/8396)) -* resource/aws_vpc_endpoint: Add `tags` argument ([#8674](https://github.com/terraform-providers/terraform-provider-aws/issues/8674)) -* resource/aws_vpc_endpoint_service: Add `manages_vpc_endpoints` attribute ([#8396](https://github.com/terraform-providers/terraform-provider-aws/issues/8396)) -* resource/aws_vpc_endpoint_service: Add `tags` argument ([#8674](https://github.com/terraform-providers/terraform-provider-aws/issues/8674)) - -BUG FIXES: - -* provider: Fix AWS shared configuration file credential source not assuming a role with environment and ECS credentials ([#8987](https://github.com/terraform-providers/terraform-provider-aws/issues/8987)) -* provider: Properly configure Route 53 service client in AWS GovCloud (US) ([#9010](https://github.com/terraform-providers/terraform-provider-aws/issues/9010)) -* provider: Properly configure Route 53 service client in AWS China ([#9060](https://github.com/terraform-providers/terraform-provider-aws/issues/9060)) -* resource/aws_api_gateway_resource: Removes an extraneous retry when deleting API gateway resource ([#9054](https://github.com/terraform-providers/terraform-provider-aws/issues/9054)) -* resource/aws_appautoscaling_policy: Retries after timeouts in creating and reading policies ([#9039](https://github.com/terraform-providers/terraform-provider-aws/issues/9039)) -* resource/aws_appautoscaling_scheduled_action: Retry after timeout putting scheduled actions ([#9039](https://github.com/terraform-providers/terraform-provider-aws/issues/9039)) -* resource/aws_cloudwatch_event_permission: Prevent not found error when deleted outside Terraform ([#9044](https://github.com/terraform-providers/terraform-provider-aws/issues/9044)) -* resource/aws_dx_gateway: Fix resource import with associations ([#8970](https://github.com/terraform-providers/terraform-provider-aws/issues/8970)) -* resource/aws_elasticache_parameter_group: Final retry deleting parameter group ([#9013](https://github.com/terraform-providers/terraform-provider-aws/issues/9013)) -* resource/aws_elasticache_replication_group: Final retry deleting replication group ([#9013](https://github.com/terraform-providers/terraform-provider-aws/issues/9013)) -* resource/aws_elasticache_subnet_group: Final retry deleting subnet group ([#9013](https://github.com/terraform-providers/terraform-provider-aws/issues/9013)) -* resource/aws_emr_cluster: Final retry after timeout error when deleting EMR cluster ([#9053](https://github.com/terraform-providers/terraform-provider-aws/issues/9053)) -* resource/aws_kinesis_firehose_delivery_stream: Add final retries when creating and updating firehose delivery streams ([#9017](https://github.com/terraform-providers/terraform-provider-aws/issues/9017)) -* resource/aws_neptune_cluster: Final retries when creating, updating, and deleting Neptune clusters ([#9036](https://github.com/terraform-providers/terraform-provider-aws/issues/9036)) -* resource/aws_neptune_cluster_instance: Final retries creating and updating cluster instances ([#9036](https://github.com/terraform-providers/terraform-provider-aws/issues/9036)) -* resource/aws_neptune_parameter_group: Final retries updating and deleting parameter groups ([#9036](https://github.com/terraform-providers/terraform-provider-aws/issues/9036)) -* resource/aws_opsworks_permission: Improves error handing when setting opsworks permissions ([#9055](https://github.com/terraform-providers/terraform-provider-aws/issues/9055)) -* resource/aws_rds_cluster: Final retries after timeout creating and updating cluster ([#8994](https://github.com/terraform-providers/terraform-provider-aws/issues/8994)) -* resource/aws_rds_cluster_instance: Final retry after timeout creating cluster instance ([#8994](https://github.com/terraform-providers/terraform-provider-aws/issues/8994)) -* resource/aws_rds_global_cluster: Final retry after timeout deleting global cluster ([#8994](https://github.com/terraform-providers/terraform-provider-aws/issues/8994)) -* resource/aws_ses_receipt_rule_set: Prevent missing Terraform state for newly created resources ([#9045](https://github.com/terraform-providers/terraform-provider-aws/issues/9045)) -* resource/aws_ssm_document: Final retries when creating and deleting SSM documents ([#8992](https://github.com/terraform-providers/terraform-provider-aws/issues/8992)) -* resource/aws_ssm_resource_data_sync: Final retry when creating SSM resource data sync ([#8992](https://github.com/terraform-providers/terraform-provider-aws/issues/8992)) - - -## 2.15.0 (June 13, 2019) - -FEATURES: - -* **New Data Source:** `aws_customer_gateway` ([#8977](https://github.com/terraform-providers/terraform-provider-aws/issues/8977)) - -ENHANCEMENTS: - -* resource/aws_cognito_user_pool: Add `email_sending_account` attribute to the email configuration block ([#8626](https://github.com/terraform-providers/terraform-provider-aws/issues/8626)) -* resource/aws_redshift_cluster: Add `arn` attribute ([#8894](https://github.com/terraform-providers/terraform-provider-aws/issues/8894)) -* resource/aws_redshift_event_subscription: Add `arn` attribute and support `tags` updates ([#8894](https://github.com/terraform-providers/terraform-provider-aws/issues/8894)) -* resource/aws_redshift_parameter_group: Add `arn` attribute and `tags` argument ([#8894](https://github.com/terraform-providers/terraform-provider-aws/issues/8894)) -* resource/aws_redshift_snapshot_copy_grant: Add `arn` attribute and support `tags` updates ([#8894](https://github.com/terraform-providers/terraform-provider-aws/issues/8894)) -* resource/aws_redshift_subnet_group: Add `arn` attribute ([#8894](https://github.com/terraform-providers/terraform-provider-aws/issues/8894)) -* resource/aws_ses_identity_notification_topic: Add `include_original_headers` argument ([#7293](https://github.com/terraform-providers/terraform-provider-aws/issues/7293)) - -BUG FIXES: - -* resource/aws_api_gateway_resource: Final retry for deleting api gateway resource ([#8893](https://github.com/terraform-providers/terraform-provider-aws/issues/8893)) -* resource/aws_appautoscaling_target: Final retry for registering autoscaling target ([#8893](https://github.com/terraform-providers/terraform-provider-aws/issues/8893)) -* resource/aws_default_vpc_dhcp_options: Add pagination to get the default DHCP options correctly ([#8907](https://github.com/terraform-providers/terraform-provider-aws/issues/8907)) -* resource/aws_docdb_cluster: Retries after timeout errors for docdb cluster operations ([#8986](https://github.com/terraform-providers/terraform-provider-aws/issues/8986)) -* resource/aws_dx_connection_association: Final retry for deleting dx connection association ([#8893](https://github.com/terraform-providers/terraform-provider-aws/issues/8893)) -* resource/aws_dynamodb_table_item: add a nil check when building the table item ID ([#8900](https://github.com/terraform-providers/terraform-provider-aws/issues/8900)) -* resource/aws_eks_cluster: Increase default creation timeout to 30 minutes ([#8909](https://github.com/terraform-providers/terraform-provider-aws/issues/8909)) -* resource/aws_elasticache_cluster: Final retry when deleting elasticache cluster ([#8893](https://github.com/terraform-providers/terraform-provider-aws/issues/8893)) -* resource/aws_elasticache_replication_group: Implement passthrough state migration for upstream `missing MigrateState function` error in Terraform 0.12 ([#8887](https://github.com/terraform-providers/terraform-provider-aws/issues/8887)) -* resource/aws_elasticache_security_group: Final retry for deleting elasticache security group ([#8981](https://github.com/terraform-providers/terraform-provider-aws/issues/8981)) -* resource/aws_iam_server_certificate: Final retry for deleting IAM server cert ([#8893](https://github.com/terraform-providers/terraform-provider-aws/issues/8893)) -* resource/aws_iam_service_linked_role: Automatically suppress Application Autoscaling `custom_suffix` differences ([#8931](https://github.com/terraform-providers/terraform-provider-aws/issues/8931)) -* resource/aws_kinesis_analytics_application: Final retries for kinesis applications ([#8984](https://github.com/terraform-providers/terraform-provider-aws/issues/8984)) -* resource/aws_sns_topic_subscription: Final retry for SNS topic subscription ([#8893](https://github.com/terraform-providers/terraform-provider-aws/issues/8893)) -* resource/aws_ssm_activation: Final retry for creating SSM activation ([#8893](https://github.com/terraform-providers/terraform-provider-aws/issues/8893)) -* resource/aws_vpc_dhcp_options: Add final retry to deleting DHCP options ([#8907](https://github.com/terraform-providers/terraform-provider-aws/issues/8907)) - -## 2.14.0 (June 06, 2019) - -FEATURES: - -* **New Data Source:** `aws_ec2_transit_gateway_dx_gateway_attachment` ([#8678](https://github.com/terraform-providers/terraform-provider-aws/issues/8678)) - -ENHANCEMENTS: - -* data-source/aws_msk_cluster: Add `bootstrap_brokers_tls` attribute ([#8850](https://github.com/terraform-providers/terraform-provider-aws/issues/8850)) -* resource/aws_codebuild_webhook: Add `filter_groups` configuration blocks ([#8110](https://github.com/terraform-providers/terraform-provider-aws/issues/8110)) -* resource/aws_msk_cluster: Add `client_authentication`, `configuration_info`, and `encryption_in_transit` configuration blocks ([#8850](https://github.com/terraform-providers/terraform-provider-aws/issues/8850)) -* resource/aws_msk_cluster: Add `bootstrap_brokers_tls` and `current_version` attributes ([#8850](https://github.com/terraform-providers/terraform-provider-aws/issues/8850)) -* resource/aws_msk_cluster: Support `broker_node_group_into` configuration block `ebs_volume_size` argument updates ([#8850](https://github.com/terraform-providers/terraform-provider-aws/issues/8850)) -* resource/aws_msk_cluster: Support tagging on creation ([#8850](https://github.com/terraform-providers/terraform-provider-aws/issues/8850)) -* resource/aws_subnet: Use customizable timeouts for pending creation and waiting for `DependencyViolation` errors on deletion ([#6322](https://github.com/terraform-providers/terraform-provider-aws/issues/6322)) - -BUG FIXES: - -* resource/aws_acmpca_certificate_authority: Add retry after timeout when creating CA ([#8856](https://github.com/terraform-providers/terraform-provider-aws/issues/8856)) -* resource/aws_launch_template: Add a nil check for `spot_options` to avoiding panicking if options are empty ([#8844](https://github.com/terraform-providers/terraform-provider-aws/issues/8844)) -* resource/aws_s3_bucket_metric: Add a nil check for `filter` to avoid panicking if empty ([#8852](https://github.com/terraform-providers/terraform-provider-aws/issues/8852)) -* resource/aws_subnet: Bump default timeout for deletion from 10 to 20 minutes to better handle ELBv2 ENI deletions ([#6322](https://github.com/terraform-providers/terraform-provider-aws/issues/6322)) - -## 2.13.0 (May 31, 2019) - -FEATURES: - -* **New Resource:** `aws_ec2_transit_gateway_vpc_attachment_accepter` ([#8679](https://github.com/terraform-providers/terraform-provider-aws/issues/8679)) - -ENHANCEMENTS: - -* resource/aws_iot_role_alias: Add `arn` attribute ([#8812](https://github.com/terraform-providers/terraform-provider-aws/issues/8812)) - -BUG FIXES: - -* data-source/aws_rds_cluster: Add missing `hosted_zone_id` attribute ([#8799](https://github.com/terraform-providers/terraform-provider-aws/issues/8799)) -* resource/aws_dms_endpoint: Fix casing for `mongodb_settings` configuration block `auth_type`, `auth_mechanism`, and `nesting_level` argument defaults ([#8008](https://github.com/terraform-providers/terraform-provider-aws/issues/8008)] / [[#8795](https://github.com/terraform-providers/terraform-provider-aws/issues/8795)) - -## 2.12.0 (May 24, 2019) - -NOTES: - -* resource/aws_dx_gateway_association: The `vpn_gateway_id` attribute is being deprecated in favor of the new `associated_gateway_id` attribute to support transit gateway associations ([#8528](https://github.com/terraform-providers/terraform-provider-aws/issues/8528)) -* resource/aws_dx_gateway_association_proposal: The `vpn_gateway_id` attribute is being deprecated in favor of the new `associated_gateway_id` attribute to support transit gateway associations ([#8528](https://github.com/terraform-providers/terraform-provider-aws/issues/8528)) - -FEATURES: - -* **New Data Source:** `aws_msk_cluster` ([#8743](https://github.com/terraform-providers/terraform-provider-aws/issues/8743)) -* **New Resource:** `aws_msk_cluster` ([#8635](https://github.com/terraform-providers/terraform-provider-aws/issues/8635)) -* **New Resource:** `aws_msk_configuration` ([#8740](https://github.com/terraform-providers/terraform-provider-aws/issues/8740)) - -ENHANCEMENTS: - -* resource/aws_codebuild_project: Add `cache` configuration block `modes` argument and add `type` argument validation of `local` (support local cache) ([#8215](https://github.com/terraform-providers/terraform-provider-aws/issues/8215)) -* resource/aws_db_instance: Add `performance_insights_enabled`, `performance_insights_kms_key_id`, and `performance_insights_retention_period` arguments ([#6453](https://github.com/terraform-providers/terraform-provider-aws/issues/6453)) -* resource/aws_dx_gateway_association: New attributes `associated_gateway_owner_account_id` and `proposal_id` added to support the acceptance of a Direct Connect gateway association proposal and create a cross-account Direct Connect gateway association. New exported attributes `associated_gateway_type` and `dx_gateway_owner_account_id` ([#8528](https://github.com/terraform-providers/terraform-provider-aws/issues/8528)) -* resource/aws_dx_gateway_association_proposal: New attribute `associated_gateway_id` replaces deprecated `vpn_gateway_id` attribute to support transit gateway associations. New exported attributes `associated_gateway_owner_account_id` and `associated_gateway_type` ([#8528](https://github.com/terraform-providers/terraform-provider-aws/issues/8528)) -* resource/aws_ec2_transit_gateway: Handle deletion of transit gateways with DirectConnect Attachments ([#8752](https://github.com/terraform-providers/terraform-provider-aws/issues/8752)) -* resource/aws_ec2_transit_gateway_route: Add retry to read method after timeout ([#8726](https://github.com/terraform-providers/terraform-provider-aws/issues/8726)) -* resource/aws_kinesis_stream: Add `enforce_consumer_deletion` argument ([#8682](https://github.com/terraform-providers/terraform-provider-aws/issues/8682)) -* resource/aws_ssm_maintenance_window_target: Add support for name and description for maintenance window targets ([#8671](https://github.com/terraform-providers/terraform-provider-aws/issues/8671)) - -BUG FIXES: - -* resource/aws_iam_group: Prevent state removal during name attribute update ([#8707](https://github.com/terraform-providers/terraform-provider-aws/issues/8707)) - -## 2.11.0 (May 17, 2019) - -NOTES: - -* resource/aws_emr_cluster: The `instance_group` configuration block, `master_instance_type` argument, `core_instance_count` argument, and `core_instance_type` argument have been deprecated in favor of new `master_instance_group` and `core_instance_group` configuration blocks. The older, conflicting configurations were problematic in update scenarios. Task instance groups can be managed with the `aws_emr_instance_group` resource. Upgrade instructions can be found in the new Version 3 Upgrade Guide. ([#8459](https://github.com/terraform-providers/terraform-provider-aws/issues/8459)) -* resource/aws_emr_instance_group: The addition of `autoscaling_policy` and `bid_price` arguments allow for the migration of task instance groups from the deprecated `instance_group` configuration block in the `aws_emr_cluster` resource. Import instructions for `aws_emr_instance_group` can be found in the resource documentation. ([#8078](https://github.com/terraform-providers/terraform-provider-aws/issues/8078)) - -FEATURES: - -* **New Data Source:** `aws_ecr_image` ([#8403](https://github.com/terraform-providers/terraform-provider-aws/issues/8403)) -* **New Data Source:** `aws_ram_resource_share` ([#8491](https://github.com/terraform-providers/terraform-provider-aws/issues/8491)) -* **New Guide:** Version 3 Upgrade Guide ([#8459](https://github.com/terraform-providers/terraform-provider-aws/issues/8459)) -* **New Resource:** `aws_ses_email_identity` ([#6575](https://github.com/terraform-providers/terraform-provider-aws/issues/6575)) -* **New Resource:** `aws_shield_protection` ([#7721](https://github.com/terraform-providers/terraform-provider-aws/issues/7721)) - -ENHANCEMENTS: - -* resource/aws_autoscaling_schedule: Support resource import ([#8300](https://github.com/terraform-providers/terraform-provider-aws/issues/8300)) -* resource/aws_backup_selection: Support resource import ([#8546](https://github.com/terraform-providers/terraform-provider-aws/issues/8546)) -* resource/aws_dynamodb_table: Support tagging on creation (where available) ([#8469](https://github.com/terraform-providers/terraform-provider-aws/issues/8469)) -* resource/aws_elastic_beanstalk_application: Add `tags` argument and `arn` attribute ([#8614](https://github.com/terraform-providers/terraform-provider-aws/issues/8614)) -* resource/aws_elastic_beanstalk_application_version: Add `tags` argument and `arn` attribute ([#8614](https://github.com/terraform-providers/terraform-provider-aws/issues/8614)) -* resource/aws_emr_cluster: Add `master_instance_group` and `core_instance_group` configuration blocks (deprecates other instance group configuration methods) ([#8459](https://github.com/terraform-providers/terraform-provider-aws/issues/8459)) -* resource/aws_emr_instance_group: Add support for `autoscaling_policy`, `bid_price`, and resource import ([#8078](https://github.com/terraform-providers/terraform-provider-aws/issues/8078)) -* resource/aws_kinesis_analytics_application: Add `tags` argument ([#8643](https://github.com/terraform-providers/terraform-provider-aws/issues/8643)) -* resource/aws_lambda_function: Support `nodejs10.x` in `runtime` validation ([#8622](https://github.com/terraform-providers/terraform-provider-aws/issues/8622)) -* resource/aws_organizations_account: Add parent_id argument (support moving accounts) ([#8583](https://github.com/terraform-providers/terraform-provider-aws/issues/8583)) -* resource/aws_sfn_activity: Support tagging on creation ([#8395](https://github.com/terraform-providers/terraform-provider-aws/issues/8395)) -* resource/aws_sfn_state_machine: Support tagging on creation ([#8395](https://github.com/terraform-providers/terraform-provider-aws/issues/8395)) -* resource/aws_sns_topic: Add `tags` argument ([#8468](https://github.com/terraform-providers/terraform-provider-aws/issues/8468)) - -BUG FIXES: - -* resource/aws_backup_selection: Properly trigger resource recreation with `selection_tag` updates ([#8546](https://github.com/terraform-providers/terraform-provider-aws/issues/8546)) -* resource/aws_cloudwatch_event_rule: Ignore `UnknownOperationException` error on reading tags (fixes ap-east-1 support) ([#8659](https://github.com/terraform-providers/terraform-provider-aws/issues/8659)) -* resource/aws_ssm_parameter: Remove `Tier` from `PutParameter` if unsupported (fixes AWS China support) ([#8664](https://github.com/terraform-providers/terraform-provider-aws/issues/8664)) -* resource/aws_vpn_gateway: Handle `attaching` and `detaching` attachment status ([#8576](https://github.com/terraform-providers/terraform-provider-aws/issues/8576)) -* resource/aws_vpn_gateway_attachment: Handle `attaching` and `detaching` attachment status ([#8576](https://github.com/terraform-providers/terraform-provider-aws/issues/8576)) - -## 2.10.0 (May 10, 2019) - -FEATURES: - -* **New Data Source:** `aws_lambda_layer_version` ([#8577](https://github.com/terraform-providers/terraform-provider-aws/issues/8577)) -* **New Resource:** `aws_organizations_organizational_unit` ([#4207](https://github.com/terraform-providers/terraform-provider-aws/issues/4207)) -* **New Resource:** `aws_xray_sampling_rule` ([#8535](https://github.com/terraform-providers/terraform-provider-aws/issues/8535)) - -ENHANCEMENTS: - -* data-source/aws_rds_cluster: Add `resource_id` attribute ([#8317](https://github.com/terraform-providers/terraform-provider-aws/issues/8317)) -* resource/aws_appsync_graphql_api: Add `tags` argument ([#8567](https://github.com/terraform-providers/terraform-provider-aws/issues/8567)) -* resource/aws_cloudfront_distribution: Validate `*_cache_behavior` `forwarded_values` `cookies` configuration block `forward` argument ([#8563](https://github.com/terraform-providers/terraform-provider-aws/issues/8563)) -* resource/aws_glue_job: Add `pythonshell` job support by adding the `max_capacity` argument and deprecating the `allocated_capacity` argument ([#7340](https://github.com/terraform-providers/terraform-provider-aws/issues/7340)) -* resource/aws_lambda_alias: Support resource import ([#8513](https://github.com/terraform-providers/terraform-provider-aws/issues/8513)) -* resource/aws_organizations_organization: Add `roots` attribute ([#8399](https://github.com/terraform-providers/terraform-provider-aws/issues/8399)) -* resource/aws_organizations_organization: Add `accounts` attribute ([#8581](https://github.com/terraform-providers/terraform-provider-aws/issues/8581)) -* resource/aws_organizations_organization: Add `enabled_policy_types` argument ([#8588](https://github.com/terraform-providers/terraform-provider-aws/issues/8588)) -* resource/aws_rds_cluster: Add `copy_tags_to_snapshot` argument ([#8544](https://github.com/terraform-providers/terraform-provider-aws/issues/8544)) -* resource/aws_ssm_parameter: Add `tier` argument (support `Advanced` parameters) ([#8525](https://github.com/terraform-providers/terraform-provider-aws/issues/8525)) - -## 2.9.0 (May 06, 2019) - -FEATURES: - -* **New Resource:** aws_db_instance_role_association ([#8466](https://github.com/terraform-providers/terraform-provider-aws/issues/8466)) - -ENHANCEMENTS: - -* data-source/aws_availability_zones: Add blacklisted_names and blacklisted_zone_ids arguments ([#8463](https://github.com/terraform-providers/terraform-provider-aws/issues/8463)) -* resource/aws_elb_attachment: Retry ELB attachment on `InvalidTarget` error ([#8483](https://github.com/terraform-providers/terraform-provider-aws/issues/8483)) -* resource/aws_sfn_state_machine: Bypass `UnknownOperationException` error for `ListTagsForResource` API call (additional LocalStack support) ([#8467](https://github.com/terraform-providers/terraform-provider-aws/issues/8467)) -* resource/aws_ssm_activation: Add `tags` argument ([#8426](https://github.com/terraform-providers/terraform-provider-aws/issues/8426)) -* resource/aws_ssm_document: Add `tags` argument ([#8426](https://github.com/terraform-providers/terraform-provider-aws/issues/8426)) -* resource/aws_ssm_maintenance_window: Add `tags` argument ([#8426](https://github.com/terraform-providers/terraform-provider-aws/issues/8426)) -* resource/aws_ssm_patch_baseline: Add `tags` argument ([#8426](https://github.com/terraform-providers/terraform-provider-aws/issues/8426)) - -## 2.8.0 (April 26, 2019) - -NOTES: - -* provider: Region validation now automatically supports the new `ap-east-1` Asia Pacific (Hong Kong) region. For AWS operations to work in the new region, the region must be explicitly enabled as outlined in the [announcement blog post](https://aws.amazon.com/blogs/aws/now-open-aws-asia-pacific-hong-kong-region/). When the region is not enabled, the Terraform AWS Provider will return errors during credential validation (e.g. `provider.aws: error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid`) or AWS operations will throw their own errors (e.g. `data.aws_availability_zones.current: Error fetching Availability Zones: AuthFailure: AWS was not able to validate the provided access credentials`). - -FEATURES: - -* **New Resource:** `aws_dx_gateway_association_proposal` ([#8320](https://github.com/terraform-providers/terraform-provider-aws/issues/8320)) - -ENHANCEMENTS: - -* data-source/aws_cloudtrail_service_account: Support new `ap-east-1` region ([#8437](https://github.com/terraform-providers/terraform-provider-aws/issues/8437)) -* data-source/aws_dx_gateway: Add `owner_account_id` attribute ([#8320](https://github.com/terraform-providers/terraform-provider-aws/issues/8320)) -* data-source/aws_eks_cluster: Add `enabled_cluster_log_types` attribute ([#8402](https://github.com/terraform-providers/terraform-provider-aws/issues/8402)) -* data-source/aws_elb_hosted_zone_id: Support new `ap-east-1` region ([#8437](https://github.com/terraform-providers/terraform-provider-aws/issues/8437)) -* data-source/aws_elb_service_account: Support new `ap-east-1` region ([#8437](https://github.com/terraform-providers/terraform-provider-aws/issues/8437)) -* data-source/aws_redshift_service_account: Support new `ap-east-1` region ([#8437](https://github.com/terraform-providers/terraform-provider-aws/issues/8437)) -* data-source/aws_s3_bucket: Support new `ap-east-1` region in `hosted_zone_id` attribute ([#8437](https://github.com/terraform-providers/terraform-provider-aws/issues/8437)) -* provider: Support automatic region validation for `ap-east-1` ([#8440](https://github.com/terraform-providers/terraform-provider-aws/issues/8440)) -* resource/aws_dx_gateway: Add `owner_account_id` attribute ([#8320](https://github.com/terraform-providers/terraform-provider-aws/issues/8320)) -* resource/aws_dx_gateway_association: Support resource import ([#8222](https://github.com/terraform-providers/terraform-provider-aws/issues/8222)) -* resource/aws_dx_gateway_association: Add `allowed_prefixes` argument ([#8222](https://github.com/terraform-providers/terraform-provider-aws/issues/8222)) -* resource/aws_lb: Support Network Load Balancer (NLB) access logs ([#8282](https://github.com/terraform-providers/terraform-provider-aws/issues/8282)) -* resource/aws_s3_bucket: Support new `ap-east-1` region in `hosted_zone_id` attribute ([#8437](https://github.com/terraform-providers/terraform-provider-aws/issues/8437)) -* resource/aws_transfer_user: Support `user_name` containing uppercase letters, hyphens, and underscores ([#8304](https://github.com/terraform-providers/terraform-provider-aws/issues/8304)) - -BUG FIXES: - -* resource/aws_eks_cluster: Ignore ordering and properly handle removals with `enabled_cluster_log_types` argument ([#8402](https://github.com/terraform-providers/terraform-provider-aws/issues/8402)) -* resource/aws_emr_cluster: Increase deletion timeout from 10 to 20 minutes to match AWS documentation ([#8428](https://github.com/terraform-providers/terraform-provider-aws/issues/8428)) -* resource/aws_lb: Prevent difference when `subnet_mapping` configuration block `allocation_id` argument was omitted ([#8282](https://github.com/terraform-providers/terraform-provider-aws/issues/8282)) -* resource/aws_lb: Properly disable access logs with `access_logs` configuration block `enabled` argument set to `false` ([#8282](https://github.com/terraform-providers/terraform-provider-aws/issues/8282)) -* resource/aws_network_interface: Refresh private_ips_count into Terraform state and allow for updates from 0 to greater than 0 ([#8353](https://github.com/terraform-providers/terraform-provider-aws/issues/8353)) -* resource/aws_vpc: Set ipv6_association_id and ipv6_cidr_block attributes as updated for assign_generated_ipv6_cidr_block updates ([#6721](https://github.com/terraform-providers/terraform-provider-aws/issues/6721)) - -## 2.7.0 (April 18, 2019) - -NOTES: - -* provider: This release includes only a Terraform SDK upgrade with compatibility for Terraform v0.12. The provider remains backwards compatible with Terraform v0.11 and this update should have no significant changes in behavior for the provider. Please report any unexpected behavior in new GitHub issues (Terraform core: https://github.com/hashicorp/terraform/issues or Terraform AWS Provider: https://github.com/terraform-providers/terraform-provider-aws/issues) ([#8366](https://github.com/terraform-providers/terraform-provider-aws/issues/8366)) - -## 2.6.0 (April 10, 2019) - -NOTES: - -* resource/aws_route53_record: Remove deprecation from `allow_overwrite` argument as there are some use cases where it is helpful. We discourage its usage in most environments (in preference of using `terraform import`) as it can easily cause conflicting management of the same Route53 Record. ([#8274](https://github.com/terraform-providers/terraform-provider-aws/issues/8274)) - -FEATURES: - -* **New Resource:** `aws_worklink_website_certificate_authority_association` ([#7459](https://github.com/terraform-providers/terraform-provider-aws/issues/7459)) - -ENHANCEMENTS: - -* resource/aws_appmesh_mesh: Add `spec` configuration block (support egress filter rules) ([#8119](https://github.com/terraform-providers/terraform-provider-aws/issues/8119)) -* resource/aws_appmesh_route: Add `spec` configuration block `tcp_route` configuration block (support TCP routing) ([#8119](https://github.com/terraform-providers/terraform-provider-aws/issues/8119)) -* resource/aws_appmesh_virtual_node: Add `spec` configuration block `logging` configuration block (support access logging) ([#8119](https://github.com/terraform-providers/terraform-provider-aws/issues/8119)) -* resource/aws_eks_cluster: Add `enabled_cluster_log_types` argument (support EKS control plane logging) ([#8216](https://github.com/terraform-providers/terraform-provider-aws/issues/8216)) -* resource/aws_iam_user_group_membership: Support resource import ([#6976](https://github.com/terraform-providers/terraform-provider-aws/issues/6976)) -* resource/aws_launch_template: Add `elastic_inference_accelerator` configuration block ([#8247](https://github.com/terraform-providers/terraform-provider-aws/issues/8247)) -* resource/aws_redshift_cluster: Add configurable timeouts ([#8241](https://github.com/terraform-providers/terraform-provider-aws/issues/8241)) -* resource/aws_transfer_server: Add `endpoint_details` configuration block and `endpoint_type` argument (support Private Link) ([#8121](https://github.com/terraform-providers/terraform-provider-aws/issues/8121)) -* resource/aws_wafregional_web_acl_association: Support additional `resource_arn` types (e.g. API Gateway) ([#7205](https://github.com/terraform-providers/terraform-provider-aws/issues/7205)) - -BUG FIXES: - -* data-source/aws_lb_target_group: Add missing schema attributes ([#8213](https://github.com/terraform-providers/terraform-provider-aws/issues/8213)) -* resource/aws_appautoscaling_policy: Retry creation on `ObjectNotFound` errors for eventual consistency ([#8273](https://github.com/terraform-providers/terraform-provider-aws/issues/8273)) -* resource/aws_backup_plan: Prevent the sending of empty lifecycle attributes ([#8236](https://github.com/terraform-providers/terraform-provider-aws/issues/8236)) -* resource/aws_glue_catalog_table: Properly trigger resource recreation when deleted outside Terraform ([#8174](https://github.com/terraform-providers/terraform-provider-aws/issues/8174)) -* resource/aws_secretsmanager_secret: Handle additional scheduled for deletion error message on immediate secret recreation ([#8219](https://github.com/terraform-providers/terraform-provider-aws/issues/8219)) -* provider: Prevent panic when setting `endpoints` configuration ([#8226](https://github.com/terraform-providers/terraform-provider-aws/issues/8226)) - -## 2.5.0 (April 05, 2019) - -FEATURES: - -* **New Guide:** [`Custom Service Endpoints`](https://www.terraform.io/docs/providers/aws/guides/custom-service-endpoints.html) ([#8092](https://github.com/terraform-providers/terraform-provider-aws/issues/8092)) -* **New Resource:** `aws_backup_selection` ([#7382](https://github.com/terraform-providers/terraform-provider-aws/issues/7382)) -* **New Resource:** `aws_sagemaker_endpoint` ([#2479](https://github.com/terraform-providers/terraform-provider-aws/issues/2479)) -* **New Resource:** `aws_sagemaker_notebook_instance_lifecycle_configuration` ([#7585](https://github.com/terraform-providers/terraform-provider-aws/issues/7585)) - -ENHANCEMENTS: - -* provider: Support customization of all service endpoints ([#8096](https://github.com/terraform-providers/terraform-provider-aws/issues/8096)) -* resource/aws_acmpca_certificate_authority: Add `permanent_deletion_time_in_days` argument ([#7366](https://github.com/terraform-providers/terraform-provider-aws/issues/7366)) -* resource/aws_budgets_budget: Add `notification` configuration block (support notifications) ([#4523](https://github.com/terraform-providers/terraform-provider-aws/issues/4523)) -* resource/aws_cloudfront_distribution: Add `wait_for_deployment` argument ([#8116](https://github.com/terraform-providers/terraform-provider-aws/issues/8116)) -* resource/aws_cloudwatch_log_subscription_filter: Support resource import ([#8147](https://github.com/terraform-providers/terraform-provider-aws/issues/8147)) -* resource/aws_cloudwatch_metric_alarm: Add `tags` argument ([#8168](https://github.com/terraform-providers/terraform-provider-aws/issues/8168)) -* resource/aws_ecr_repository: Tag on creation (support tag limiting IAM policies) ([#8198](https://github.com/terraform-providers/terraform-provider-aws/issues/8198)) -* resource/aws_lb_target_group: Add `enabled` argument to target group health checks ([#7570](https://github.com/terraform-providers/terraform-provider-aws/issues/7570)) -* resource/aws_sagemaker_notebook_instance: Add `lifecycle_config_name` argument ([#7586](https://github.com/terraform-providers/terraform-provider-aws/issues/7586)) -* service/ec2: Automatically retry `CreateVpnConnection` and `CreateVpnGateway` requests for concurrency errors ([#8161](https://github.com/terraform-providers/terraform-provider-aws/issues/8161)) - -BUG FIXES: - -* resource/aws_cloudfront_distribution: Ignore attribute ordering of cache behavior forwarded values `headers` and cookies `whitelisted_names` arguments ([#8150](https://github.com/terraform-providers/terraform-provider-aws/issues/8150)) - -## 2.4.0 (March 29, 2019) - -NOTES: - -* service/ec2: Due to an upcoming update to the EC2 service, both the `aws_instance` data source and resource will no longer make the EC2 API call `DescribeInstanceCreditSpecifications` unless they are in the T2 or T3 instance families. Previously, the EC2 service would allow this API call for instance families that did not support credit specifications, however the upcoming update will return an error and prevent Terraform runs from completing. - -FEATURES: - -* **New Data Source:** `aws_ec2_transit_gateway_vpn_attachment` ([#8071](https://github.com/terraform-providers/terraform-provider-aws/issues/8071)) -* **New Resource:** `aws_appsync_resolver` ([#6451](https://github.com/terraform-providers/terraform-provider-aws/issues/6451)) -* **New Resource:** `aws_kms_ciphertext` ([#6993](https://github.com/terraform-providers/terraform-provider-aws/issues/6993)) -* **New Resource:** `aws_kms_external_key` ([#8066](https://github.com/terraform-providers/terraform-provider-aws/issues/8066)) -* **New Resource:** `aws_sagemaker_endpoint_configuration` ([#2477](https://github.com/terraform-providers/terraform-provider-aws/issues/2477)) - -ENHANCEMENTS: - -* data-source/aws_instance: Only call `DescribeInstanceCreditSpecifications` for T2 and T3 Instance Families ([#8107](https://github.com/terraform-providers/terraform-provider-aws/issues/8107)) -* data-source/aws_kms_ciphertext: Hide `plaintext` in logs and user interface ([#6100](https://github.com/terraform-providers/terraform-provider-aws/issues/6100)) -* resource/aws_appsync_graphql_api: Add `schema` argument ([#4840](https://github.com/terraform-providers/terraform-provider-aws/issues/4840)) -* resource/aws_batch_compute_environment: Add `compute_resources` configuration block `launch_template` configuration block (support EC2 Launch Templates) ([#8026](https://github.com/terraform-providers/terraform-provider-aws/issues/8026)) -* resource/aws_cloudwatch_event_rule: Add `tags` argument ([#8076](https://github.com/terraform-providers/terraform-provider-aws/issues/8076)) -* resource/aws_instance: Only call `DescribeInstanceCreditSpecifications` for T2 and T3 Instance Families ([#8107](https://github.com/terraform-providers/terraform-provider-aws/issues/8107)) -* resource/aws_ram_principal_association: Validate `principal` as AWS Account ID or ARN ([#8048](https://github.com/terraform-providers/terraform-provider-aws/issues/8048)) -* resource/aws_s3_bucket: Support `DEEP_ARCHIVE` in storage class validations ([#8109](https://github.com/terraform-providers/terraform-provider-aws/issues/8109)) -* resource/aws_s3_bucket_object: Support `DEEP_ARCHIVE` in `storage_class` validation ([#8109](https://github.com/terraform-providers/terraform-provider-aws/issues/8109)) -* resource/aws_vpn_connection: Add `transit_gateway_attachment_id` attribute ([#8070](https://github.com/terraform-providers/terraform-provider-aws/issues/8070)) - -BUG FIXES: - -* resource/aws_cloudwatch_metric_alarm: Prevent `ValidationError` when updating `metric_query` alarms ([#8085](https://github.com/terraform-providers/terraform-provider-aws/issues/8085)) - -## 2.3.0 (March 21, 2019) - -BREAKING CHANGES: - -* service/appmesh: Changes to support AppMesh General Availability (GA) release. The AppMesh resources were added while the API was under Public Preview and the GA release earlier this month introduced breaking changes which prevented further AWS Go SDK updates. This is a very atypical situation for the Terraform AWS Provider as most AWS API and SDK changes are additive. To prevent this situation in the future we may introduce separate Terraform AWS Provider(s) specifically for Public Preview or Beta APIs. If or when this occurs, it will be separately announced. The maintainers will continue following Terraform Provider compatibility promises outlined on the [HashiCorp Blog](https://www.hashicorp.com/blog/hashicorp-terraform-provider-versioning) and [Extending Terraform documentation](https://www.terraform.io/docs/extend/best-practices/versioning.html) as best as possible except other existing Public Preview resources. ([#7659](https://github.com/terraform-providers/terraform-provider-aws/issues/7659)) -* resource/aws_appmesh_virtual_node: Replace `backends` configuration block(s) with `backend` configuration blocks ([#7858](https://github.com/terraform-providers/terraform-provider-aws/issues/7858)) -* resource/aws_appmesh_virtual_node: Replace `service_discovery` configuration block `service_name` argument with `service_discovery` configuration block `dns` configuration block ([#7858](https://github.com/terraform-providers/terraform-provider-aws/issues/7858)) -* resource/aws_appmesh_virtual_router: Remove `spec` configuration block `service_names` argument ([#7858](https://github.com/terraform-providers/terraform-provider-aws/issues/7858)) - -FEATURES: - -* **New Data Source:** `aws_transfer_server` ([#7977](https://github.com/terraform-providers/terraform-provider-aws/issues/7977)) -* **New Resource:** `aws_appmesh_virtual_service` ([#7858](https://github.com/terraform-providers/terraform-provider-aws/issues/7858)) -* **New Resource:** `aws_backup_plan` ([#7350](https://github.com/terraform-providers/terraform-provider-aws/issues/7350)) -* **New Resource:** `aws_cloudformation_stack_set` ([#8020](https://github.com/terraform-providers/terraform-provider-aws/issues/8020)) -* **New Resource:** `aws_cloudformation_stack_set_instance` ([#8020](https://github.com/terraform-providers/terraform-provider-aws/issues/8020)) - -ENHANCEMENTS: - -* data-source/aws_eks_cluster: Add `vpc_config` configuration block `endpoint_private_access` and `endpoint_public_access` attributes ([#8024](https://github.com/terraform-providers/terraform-provider-aws/issues/8024)) -* data-source/aws_instance: Add `get_user_data` argument and `user_data_base64` attribute ([#8001](https://github.com/terraform-providers/terraform-provider-aws/issues/8001)) -* provider: Support custom endpoint for `ses` ([#7986](https://github.com/terraform-providers/terraform-provider-aws/issues/7986)) -* provider: Support custom endpoints for `firehose` and `redshift` ([#8007](https://github.com/terraform-providers/terraform-provider-aws/issues/8007)) -* resource/aws_api_gateway_deployment: Allow `stage_name` argument to be optional ([#6459](https://github.com/terraform-providers/terraform-provider-aws/issues/6459)) -* resource/aws_appautoscaling_policy: Support resource import ([#8032](https://github.com/terraform-providers/terraform-provider-aws/issues/8032)) -* resource/aws_appautoscaling_target: Support resource import ([#8032](https://github.com/terraform-providers/terraform-provider-aws/issues/8032)) -* resource/aws_appmesh_route: Support resource import ([#7858](https://github.com/terraform-providers/terraform-provider-aws/issues/7858)) -* resource/aws_appmesh_virtual_node: Support resource import ([#7858](https://github.com/terraform-providers/terraform-provider-aws/issues/7858)) -* resource/aws_appmesh_virtual_router: Support resource import ([#7858](https://github.com/terraform-providers/terraform-provider-aws/issues/7858)) -* resource/aws_appmesh_virtual_router: Add `spec` configuration block `listener` configuration block ([#7858](https://github.com/terraform-providers/terraform-provider-aws/issues/7858)) -* resource/aws_cloudfront_distribution: Add `origin_group` configuration block (support Origin Groups and failover) ([#7202](https://github.com/terraform-providers/terraform-provider-aws/issues/7202)) -* resource/aws_codebuild_project: Add `project_environment` configuration block `image_pull_credentials_type` argument (support cross-account images) ([#7458](https://github.com/terraform-providers/terraform-provider-aws/issues/7458)) -* resource/aws_ecr_repository_policy: Support resource import ([#7974](https://github.com/terraform-providers/terraform-provider-aws/issues/7974)) -* resource/aws_eks_cluster: Add `vpc_config` configuration block `endpoint_private_access` and `endpoint_public_access` arguments (support disabling public access) ([#8024](https://github.com/terraform-providers/terraform-provider-aws/issues/8024)) -* resource/aws_iam_access_key: Support `status` updates (support disabling/enabling access keys) ([#7961](https://github.com/terraform-providers/terraform-provider-aws/issues/7961)) -* resource/aws_kinesis_analytics_application: Support resource import ([#8027](https://github.com/terraform-providers/terraform-provider-aws/issues/8027)) -* resource/aws_media_package_channel: Add `tags` argument ([#7984](https://github.com/terraform-providers/terraform-provider-aws/issues/7984)) -* resource/aws_route53_zone_association: Support resource import ([#7966](https://github.com/terraform-providers/terraform-provider-aws/issues/7966)) -* resource/aws_s3_bucket_inventory: Support plan-time validation of `optional_fields` values `ObjectLockRetainUntilDate`, `ObjectLockMode` and `ObjectLockLegalHoldStatus` ([#7952](https://github.com/terraform-providers/terraform-provider-aws/issues/7952)) -* resource/aws_ssm_association: Add `compliance_severity` argument ([#7852](https://github.com/terraform-providers/terraform-provider-aws/issues/7852)) -* resource/aws_ssm_association: Add `max_concurrency` and `max_errors` arguments ([#7970](https://github.com/terraform-providers/terraform-provider-aws/issues/7970)) - -BUG FIXES: - -* resource/aws_appautoscaling_policy: Recreate resource for `resource_id` updates ([#7982](https://github.com/terraform-providers/terraform-provider-aws/issues/7982)) -* resource/aws_appautoscaling_policy: Ignore `ObjectNotFoundException` on deletion ([#7982](https://github.com/terraform-providers/terraform-provider-aws/issues/7982)) -* resource/aws_route53_zone_association: Properly trigger resource recreation on all updates ([#7966](https://github.com/terraform-providers/terraform-provider-aws/issues/7966)) - -## 2.2.0 (March 15, 2019) - -FEATURES: - -* **New Resource:** `aws_globalaccelerator_listener` ([#7003](https://github.com/terraform-providers/terraform-provider-aws/issues/7003)) -* **New Resource:** `aws_guardduty_invite_accepter` ([#4610](https://github.com/terraform-providers/terraform-provider-aws/issues/4610)) -* **New Resource:** `aws_route53_resolver_rule` ([#7799](https://github.com/terraform-providers/terraform-provider-aws/issues/7799)) -* **New Resource:** `aws_route53_resolver_rule_association` ([#7799](https://github.com/terraform-providers/terraform-provider-aws/issues/7799)) - -ENHANCEMENTS: - -* data-source/aws_eip: Add `private_dns` and `public_dns` attributes ([#7349](https://github.com/terraform-providers/terraform-provider-aws/issues/7349)) -* resource/aws_backup_vault: Support `tags` updates ([#7933](https://github.com/terraform-providers/terraform-provider-aws/issues/7933)) -* resource/aws_dx_bgp_peer: Add `aws_device` and `bgp_peer_id` attributes ([#7131](https://github.com/terraform-providers/terraform-provider-aws/issues/7131)) -* resource/aws_dx_connection: Add `aws_device` and `has_logical_redundancy` attributes ([#7131](https://github.com/terraform-providers/terraform-provider-aws/issues/7131)) -* resource/aws_dx_hosted_private_virtual_interface: Add `aws_device` attribute ([#7131](https://github.com/terraform-providers/terraform-provider-aws/issues/7131)) -* resource/aws_dx_hosted_public_virtual_interface: Add `aws_device` attribute ([#7131](https://github.com/terraform-providers/terraform-provider-aws/issues/7131)) -* resource/aws_dx_lag: Add `has_logical_redundancy` attribute ([#7131](https://github.com/terraform-providers/terraform-provider-aws/issues/7131)) -* resource/aws_dx_private_virtual_interface: Add `aws_device` attribute ([#7131](https://github.com/terraform-providers/terraform-provider-aws/issues/7131)) -* resource/aws_dx_public_virtual_interface: Add `aws_device` attribute ([#7131](https://github.com/terraform-providers/terraform-provider-aws/issues/7131)) -* resource/aws_eip: Add `private_dns` and `public_dns` attributes ([#7349](https://github.com/terraform-providers/terraform-provider-aws/issues/7349)) -* resource/aws_glue_crawler: Add `arn` attribute ([#7948](https://github.com/terraform-providers/terraform-provider-aws/issues/7948)) -* resource/aws_ssm_patch_baseline: Support resource import ([#7838](https://github.com/terraform-providers/terraform-provider-aws/issues/7838)) - -BUG FIXES: - -* resource/aws_cloudfront_distribution: Ensure retain_on_delete disables the CloudFront Distribution before exiting ([#7875](https://github.com/terraform-providers/terraform-provider-aws/issues/7875)) -* resource/aws_cloudwatch_log_metric_filter: Serialize create, update, and delete operations on the same CloudWatch Log Group to prevent `OperationAbortedException` errors ([#7880](https://github.com/terraform-providers/terraform-provider-aws/issues/7880)) -* resource/aws_codebuild_webhook: Only pass BranchFilter configuration if non-empty ([#7841](https://github.com/terraform-providers/terraform-provider-aws/issues/7841)) -* resource/aws_ec2_transit_gateway_vpc_attachment: Prevent errors with Resource Access Manager shared EC2 Transit Gateways ([#7513](https://github.com/terraform-providers/terraform-provider-aws/issues/7513)) -* resource/aws_ecr_repository_policy: Properly read `policy` into the Terraform state ([#7853](https://github.com/terraform-providers/terraform-provider-aws/issues/7853)) -* resource/aws_iam_role_policy_attachment: Prevent `NoSuchEntity` errors from race conditions ([#7855](https://github.com/terraform-providers/terraform-provider-aws/issues/7855)) -* resource/aws_kms_alias: Prevent state removal of resource immediately after creation due to eventual consistency ([#7891](https://github.com/terraform-providers/terraform-provider-aws/issues/7891)) -* resource/aws_s3_bucket: Prevent empty `replication_configuration` `rules` `filter` crash ([#7887](https://github.com/terraform-providers/terraform-provider-aws/issues/7887)) -* resource/aws_s3_bucket: Continue supporting empty string (`""`) `bucket` argument ([#7881](https://github.com/terraform-providers/terraform-provider-aws/issues/7881)) -* resource/aws_s3_bucket: Prevent `NoSuchBucket` errors when putting lifecycle configuration on resource creation ([#7930](https://github.com/terraform-providers/terraform-provider-aws/issues/7930)) -* resource/aws_ses_domain_mail_from: Prevent crash with deleted SES Domain Identity ([#7883](https://github.com/terraform-providers/terraform-provider-aws/issues/7883)) - -## 2.1.0 (March 07, 2019) - -FEATURES: - -* **New Resource:** `aws_route53_resolver_endpoint` ([#6563](https://github.com/terraform-providers/terraform-provider-aws/issues/6563)) - -ENHANCEMENTS: - -* data-source/aws_elastic_beanstalk_hosted_zone: Add eu-north-1 region support ([#7829](https://github.com/terraform-providers/terraform-provider-aws/issues/7829)) -* data-source/aws_redshift_service_account: Add us-gov-east-1 and us-gov-west-1 region mappings ([#7635](https://github.com/terraform-providers/terraform-provider-aws/issues/7635)) -* data-source/aws_s3_bucket: Add `bucket_regional_domain_name` attribute ([#7765](https://github.com/terraform-providers/terraform-provider-aws/issues/7765)) -* resource/aws_autoscaling_group: Support new `mixed_instances_policy` `instance_distribution` `spot_max_price` ability to unset with empty string ([#7821](https://github.com/terraform-providers/terraform-provider-aws/issues/7821)) -* resource/aws_dlm_lifecycle_policy: Add validation support for 2, 3, 4, 6, and 8 in `policy_details` `schedule` `create_rule` `interval` argument (support shorter intervals) ([#7751](https://github.com/terraform-providers/terraform-provider-aws/issues/7751)) -* resource/aws_ec2_client_vpn_endpoint: Add `tags` argument ([#7619](https://github.com/terraform-providers/terraform-provider-aws/issues/7619)) -* resource/aws_ecs_service: Support plan time validation of new `health_check_grace_period_seconds` max of `2147483647` ([#7806](https://github.com/terraform-providers/terraform-provider-aws/issues/7806)) -* resource/aws_lb_target_group: Add `lambda_multi_value_headers_enabled` argument ([#7648](https://github.com/terraform-providers/terraform-provider-aws/issues/7648)) -* resource/aws_ram_resource_share: Add `arn` attribute ([#7634](https://github.com/terraform-providers/terraform-provider-aws/issues/7634)) -* resource/aws_s3_bucket: Add plan time length validation for `bucket` and `bucket_prefix` arguments ([#7778](https://github.com/terraform-providers/terraform-provider-aws/issues/7778)) - -BUG FIXES: - -* resource/aws_autoscaling_group: Allow configuration of `mixed_instances_policy` `instance_distribution` `on_demand_base_capacity` argument to 0 ([#7821](https://github.com/terraform-providers/terraform-provider-aws/issues/7821)) -* resource/aws_cloudfront_distribution: Remove problematic `viewer_certificate` configuration block argument `ConflictsWith` usage from version 2.0.0 ([#7794](https://github.com/terraform-providers/terraform-provider-aws/issues/7794)) -* resource/aws_cloudfront_distribution: Skip disabling distributions on deletion for previously disabled distributions ([#7794](https://github.com/terraform-providers/terraform-provider-aws/issues/7794)) -* resource/aws_cloudfront_distribution: Retry on `PreconditionFailed` error messages after disabling distribution on deletion ([#7794](https://github.com/terraform-providers/terraform-provider-aws/issues/7794)) -* resource/aws_cloudfront_distribution: Wait for creation and update deployments to complete ([#7794](https://github.com/terraform-providers/terraform-provider-aws/issues/7794)) -* resource/aws_cloudfront_distribution: Prevent one minute timeout error for creation and update errors due to throttling ([#7809](https://github.com/terraform-providers/terraform-provider-aws/issues/7809)) -* resource/aws_db_instance: Properly set `engine_version` with `snapshot_identifier` ([#7738](https://github.com/terraform-providers/terraform-provider-aws/issues/7738)) -* resource/aws_dynamodb_table: Prevent perpetual plan differences with `ttl` configuration block `enabled` argument set to `false` ([#3960](https://github.com/terraform-providers/terraform-provider-aws/issues/3960)) -* resource/aws_ecs_service: Ensure `placement_strategy` removal in version 2.0.0 does not force recreation ([#7790](https://github.com/terraform-providers/terraform-provider-aws/issues/7790)) -* resource/aws_guardduty_detector: Prevent GuardDuty member accounts with unconfigured `finding_publishing_frequency` from triggering update errors ([#7804](https://github.com/terraform-providers/terraform-provider-aws/issues/7804)) -* resource/aws_launch_configuration: Prevent `ResourceInUse` errors caused by eventual consistency during deletion ([#7819](https://github.com/terraform-providers/terraform-provider-aws/issues/7819)) -* resource/aws_s3_bucket_notification: Prevent crash with empty filters configuration ([#7791](https://github.com/terraform-providers/terraform-provider-aws/issues/7791)) - -## 2.0.0 (February 27, 2019) - -NOTES: - -* Full documentation about this update, including Terraform provider version pinning and configuration examples, can be found in the [Terraform AWS Provider Version 2 Upgrade Guide](https://www.terraform.io/docs/providers/aws/guides/version-2-upgrade.html) - -BREAKING CHANGES: - -* provider: Return error on AWS Account ID lookup failure during initialization (unless `skip_requesting_account_id = true`) ([#7737](https://github.com/terraform-providers/terraform-provider-aws/issues/7737)) -* data-source/aws_ami: Require `owners` argument ([#5576](https://github.com/terraform-providers/terraform-provider-aws/issues/5576)) -* data-source/aws_ami_ids: Require `owners` argument ([#5576](https://github.com/terraform-providers/terraform-provider-aws/issues/5576)) -* data-source/aws_iam_role: Remove deprecated attributes ([#7696](https://github.com/terraform-providers/terraform-provider-aws/issues/7696)) -* data-source/aws_kms_secret: Remove data source (replaced with `aws_kms_secrets` data source) ([#7657](https://github.com/terraform-providers/terraform-provider-aws/issues/7657)) -* data-source/aws_lambda_function: Returns unqualified (no `:QUALIFIER` or `:VERSION` suffix) value in `arn` attribute by default and qualified (includes `:QUALIFIER` or `:VERSION` suffix) value in `qualified_arn` attribute. Previously the `arn` attribute included `:$LATEST` suffix by default which was not compatible with many other resources. To restore the previous default behavior, set the `qualifier` argument to `$LATEST` and reference the `qualified_arn` attribute. ([#7663](https://github.com/terraform-providers/terraform-provider-aws/issues/7663)) -* data-source/aws_region: Remove deprecated `current` argument ([#7697](https://github.com/terraform-providers/terraform-provider-aws/issues/7697)) -* resource/aws_api_gateway_api_key: Remove deprecated `stage_key` configuration block ([#7698](https://github.com/terraform-providers/terraform-provider-aws/issues/7698)) -* resource/aws_api_gateway_integration: Remove deprecated `request_parameters_in_json` argument (replaced with `request_parameters` argument) ([#7699](https://github.com/terraform-providers/terraform-provider-aws/issues/7699)) -* resource/aws_api-gateway_integration_response: Remove deprecated `response_parameters_in_json` argument (replaced with `response_parameters` argument) ([#7700](https://github.com/terraform-providers/terraform-provider-aws/issues/7700)) -* resource/aws_api_gateway_method: Remove deprecated `request_parameters_in_json` argument (replaced with `request_parameters` argument) ([#7701](https://github.com/terraform-providers/terraform-provider-aws/issues/7701)) -* resource/aws_api_gateway_method_response: Remove deprecated `response_parameters_in_json` argument (replaced with `response_parameters` argument) ([#7704](https://github.com/terraform-providers/terraform-provider-aws/issues/7704)) -* resource/aws_appautoscaling_policy: Remove deprecated arguments (replaced with `step_scaling_policy_configuration` configuration block) ([#7706](https://github.com/terraform-providers/terraform-provider-aws/issues/7706)) -* resource/aws_autoscaling_policy: Remove deprecated `min_adjustment_step` argument (replaced with `min_adjustment_magnitude` argument) ([#7707](https://github.com/terraform-providers/terraform-provider-aws/issues/7707)) -* resource/aws_batch_compute_environment: Remove deprecated `ecc_cluster_arn` attribute (replaced with `ecs_cluster_arn` attribute) ([#7708](https://github.com/terraform-providers/terraform-provider-aws/issues/7708)) -* resource/aws_cloudfront_distribution: Remove deprecated `cache_behaviors` configuration block (replaced with `ordered_cache_behaviors` configuration block) ([#7710](https://github.com/terraform-providers/terraform-provider-aws/issues/7710)) -* resource/aws_cognito_user_pool: Ensure only `email_verification_message` argument or `verification_message_template` configuration block `email_message` argument is configured ([#2425](https://github.com/terraform-providers/terraform-provider-aws/issues/2425)) -* resource/aws_cognito_user_pool: Ensure only `email_verification_subject` argument or `verification_message_template` configuration block `email_subject` argument is configured ([#2425](https://github.com/terraform-providers/terraform-provider-aws/issues/2425)) -* resource/aws_cognito_user_pool: Ensure only `sms_verification_message` argument or `verification_message_template` configuration block `sms_message` argument is defined ([#2425](https://github.com/terraform-providers/terraform-provider-aws/issues/2425)) -* resource/aws_dx_lag: Remove deprecated `number_of_connections` argument and delete unmanaged connection during resource creation ([#7711](https://github.com/terraform-providers/terraform-provider-aws/issues/7711)) -* resource/aws_ecs_service: Remove deprecated `placement_strategy` configuration block (replaced with `ordered_placement_strategy` configuration block) ([#7712](https://github.com/terraform-providers/terraform-provider-aws/issues/7712)) -* resource/aws_efs_file_system: Remove deprecated `reference_name` argument (replaced with `creation_token` argument) ([#7713](https://github.com/terraform-providers/terraform-provider-aws/issues/7713)) -* resource/aws_elasticache_cluster: Remove deprecated `availability_zones` argument (replaced with `preferred_availability_zones` argument) ([#7714](https://github.com/terraform-providers/terraform-provider-aws/issues/7714)) -* resource/aws_instance: Remove deprecated top-level `network_interface_id` attribute ([#1193](https://github.com/terraform-providers/terraform-provider-aws/issues/1193)] / [[#7715](https://github.com/terraform-providers/terraform-provider-aws/issues/7715)) -* resource/aws_instance: Remove hardcoded AWS China prevention of tagging on creation ([#7654](https://github.com/terraform-providers/terraform-provider-aws/issues/7654)) -* resource/aws_lambda_function: Setting `reserved_concurrent_executions` to `0` will now disable Lambda Function invocations, causing downtime for the Lambda Function. Previously `reserved_concurrent_executions` accepted `0` and below for unreserved concurrency, which means it was not previously possible to disable invocations. The argument now differentiates between a new value for unreserved concurrency (`-1`) and disabling Lambda invocations (`0`). If previously configuring this value to `0` for unreserved concurrency, update the configured value to `-1` or the resource will disable Lambda Function invocations on update. If previously unconfigured, the argument does not require any changes. See the [Lambda User Guide](https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html) for more information about concurrency. -* resource/aws_lambda_layer_version: Swap `arn` and `layer_arn` attribute values ([#7664](https://github.com/terraform-providers/terraform-provider-aws/issues/7664)) -* resource/aws_network_acl: Remove deprecated `subnet_id` argument (replaced with `subnet_ids` argument) ([#7716](https://github.com/terraform-providers/terraform-provider-aws/issues/7716)) -* resource/aws_redshift_cluster: Remove deprecated `bucket_name`, `enable_logging`, and `s3_key_prefix` arguments (replaced with `logging` configuration block) ([#7717](https://github.com/terraform-providers/terraform-provider-aws/issues/7717)) -* resource/aws_route_table: Resource import no longer imports `aws_route`, `aws_route_table_association`, and `aws_main_route_table_association` resources into the Terraform state ([#5657](https://github.com/terraform-providers/terraform-provider-aws/issues/5657)) -* resource/aws_route53_record: Require import for existing records (use deprecated `allow_overwrite` argument to temporarily reinstate the old behavior) ([#7734](https://github.com/terraform-providers/terraform-provider-aws/issues/7734)) -* resource/aws_route53_zone: Remove deprecated `vpc_id` and `vpc_region` arguments (replaced with `vpc` configuration block) ([#7695](https://github.com/terraform-providers/terraform-provider-aws/issues/7695)) -* resource/aws_s3_bucket_object: Remove hardcoded AWS China prevention of tagging ([#7654](https://github.com/terraform-providers/terraform-provider-aws/issues/7654)) -* resource/aws_wafregional_byte_match_set: Remove deprecated `byte_match_tuple` configuration block (replaced with `byte_match_tuples` configuration block) ([#7718](https://github.com/terraform-providers/terraform-provider-aws/issues/7718)) - -ENHANCEMENTS: - -* data-source/aws_lambda_function: Add `tags` attribute ([#7663](https://github.com/terraform-providers/terraform-provider-aws/issues/7663)) -* resource/aws_dx_lag: Delete unmanaged connection during resource creation ([#7711](https://github.com/terraform-providers/terraform-provider-aws/issues/7711)) -* resource/aws_lambda_function: Disable Lambda Function invocations by setting `reserved_concurrent_executions` to `0` ([#3806](https://github.com/terraform-providers/terraform-provider-aws/issues/3806)) - -BUG FIXES: - -* data-source/aws_lambda_function: Properly return error for missing function ([#7663](https://github.com/terraform-providers/terraform-provider-aws/issues/7663)) -* resource/aws_appautoscaling_policy: Properly read `step_scaling_policy_configuration` into Terraform state ([#7706](https://github.com/terraform-providers/terraform-provider-aws/issues/7706)) -* resource/aws_cloudfront_distribution: Adjust TypeSet and TypeList attributes for better difference handling ([#7732](https://github.com/terraform-providers/terraform-provider-aws/issues/7732)) -* resource/aws_redshift_cluster: Properly read logging into Terraform state ([#7717](https://github.com/terraform-providers/terraform-provider-aws/issues/7717)) -* resource/aws_route53_record: Existing Route 53 Records are no longer silently overwritten during resource creation by default (use `terraform import` or deprecated `allow_overwrite` argument) ([#7734](https://github.com/terraform-providers/terraform-provider-aws/issues/7734)) -* resource/aws_vpn_connection: Remove configurability of read-only `customer_gateway_configuration`, `routes`, and `vgw_telemetry` attributes ([#7636](https://github.com/terraform-providers/terraform-provider-aws/issues/7636)) - -## 1.60.0 (February 22, 2019) - -ENHANCEMENTS: - -* resource/aws_route53_record: Add validation for alias `name` and `zone_id` arguments ([#7606](https://github.com/terraform-providers/terraform-provider-aws/issues/7606)) - -BUG FIXES: - -* resource/aws_db_instance: Prevent snapshot restore error with `allocated_storage` and io1 `storage_type` ([#5800](https://github.com/terraform-providers/terraform-provider-aws/issues/5800)] / [[#7426](https://github.com/terraform-providers/terraform-provider-aws/issues/7426)) -* resource/aws_flow_log: Prevent crash on unsuccessful flow log creation ([#7528](https://github.com/terraform-providers/terraform-provider-aws/issues/7528)) -* resource/aws_kinesis_analytics_application: Retry input Kinesis Firehose Delivery Stream `InvalidArgumentException` permission errors for IAM eventual consistency during creation ([#7578](https://github.com/terraform-providers/terraform-provider-aws/issues/7578)) -* resource/aws_launch_template: Properly read and write `description` ([#7569](https://github.com/terraform-providers/terraform-provider-aws/issues/7569)) -* resource/aws_rds_cluster: Remove requirement for `master_password` and `master_username` when creating via `global_cluster_identifier` ([#7213](https://github.com/terraform-providers/terraform-provider-aws/issues/7213)) -* resource/aws_vpc_endpoint: Suppress equivalent `policy` differences ([#7645](https://github.com/terraform-providers/terraform-provider-aws/issues/7645)) - -## 1.59.0 (February 14, 2019) - -FEATURES: - -* **New Data Source:** `aws_cur_report_definition` ([#7432](https://github.com/terraform-providers/terraform-provider-aws/issues/7432)) -* **New Resource:** `aws_cur_report_definition` ([#7432](https://github.com/terraform-providers/terraform-provider-aws/issues/7432)) -* **New Resource:** `aws_docdb_cluster_instance` ([#7143](https://github.com/terraform-providers/terraform-provider-aws/issues/7143)) -* **New Resource:** `aws_ram_principal_association` ([#7219](https://github.com/terraform-providers/terraform-provider-aws/issues/7219)] / [[#7563](https://github.com/terraform-providers/terraform-provider-aws/issues/7563)) -* **New Resource:** `aws_ram_resource_association` ([#7449](https://github.com/terraform-providers/terraform-provider-aws/issues/7449)) - -ENHANCEMENTS: - -* data-source/aws_dynamodb_table: Add `billing_mode` and `point_in_time_recovery` attributes ([#7497](https://github.com/terraform-providers/terraform-provider-aws/issues/7497)) -* resource/aws_appmesh_virtual_node: Add support for listener health checks ([#7446](https://github.com/terraform-providers/terraform-provider-aws/issues/7446)) -* resource/aws_cloudwatch_metric_alarm: Add `metric_query` argument (support math expressions) ([#6833](https://github.com/terraform-providers/terraform-provider-aws/issues/6833)) -* resource/aws_cognito_user_pool: Add `user_pool_add_ons` argument (support advanced security mode) ([#7361](https://github.com/terraform-providers/terraform-provider-aws/issues/7361)) -* resource/aws_directory_service_directory: Set `security_group_id` attribute when type is `ADConnector` ([#7487](https://github.com/terraform-providers/terraform-provider-aws/issues/7487)) -* resource/aws_dynamodb_table: Use `update` customizable timeout for individual Global Secondary Index updates and increase default `update` timeout from 10 minutes to 60 minutes ([#7453](https://github.com/terraform-providers/terraform-provider-aws/issues/7453)) -* resource/aws_dms_endpoint: Add `docdb` for `engine_name` validation ([#7491](https://github.com/terraform-providers/terraform-provider-aws/issues/7491)) -* resource/aws_ses_identity_notification_topic: Support resource import ([#7343](https://github.com/terraform-providers/terraform-provider-aws/issues/7343)) -* resource/aws_waf_web_acl: Add `arn` attribute and `logging_configuration` argument ([#6059](https://github.com/terraform-providers/terraform-provider-aws/issues/6059)) -* resource/aws_wafregional_web_acl: Add `arn` attribute and `logging_configuration` argument ([#7480](https://github.com/terraform-providers/terraform-provider-aws/issues/7480)) - -BUG FIXES: - -* resource/aws_api_gateway_rest_api: Prevent timeout errors with large amounts of concurrent resource deletions ([#7554](https://github.com/terraform-providers/terraform-provider-aws/issues/7554)) -* resource/aws_dynamodb_table: Prevent error when updating `billing_mode` from `PAY_PER_REQUEST` to `PROVISIONED` for Tables with Global Secondary Indexes ([#7453](https://github.com/terraform-providers/terraform-provider-aws/issues/7453)) -* resource/aws_ec2_transit_gateway_vpc_attachment: Allow `pendingAcceptance` as available state during resource creation (support shared Transit Gateways with manual acceptance) ([#7489](https://github.com/terraform-providers/terraform-provider-aws/issues/7489)) -* resource/aws_iam_user_login_profile: Properly return all errors during resource creation ([#7519](https://github.com/terraform-providers/terraform-provider-aws/issues/7519)) -* resource/aws_iot_topic_rule: Allow optional `range_key_field` and `range_key_value` arguments ([#7471](https://github.com/terraform-providers/terraform-provider-aws/issues/7471)) -* resource/aws_kinesis_analytics_application: Correctly manage multiple outputs ([#7535](https://github.com/terraform-providers/terraform-provider-aws/issues/7535)) -* resource/aws_ssm_maintenance_window_task: Prevent erroneous `name` and `description` validation errors on resource creation ([#7186](https://github.com/terraform-providers/terraform-provider-aws/issues/7186)) -* resource/aws_ssm_resource_data_sync: Properly trigger resource recreation for argument updates under the `s3_destination` configuration block ([#7490](https://github.com/terraform-providers/terraform-provider-aws/issues/7490)) - -## 1.58.0 (February 08, 2019) - -FEATURES: - -* **New Data Source:** `aws_eks_cluster_auth` ([#7438](https://github.com/terraform-providers/terraform-provider-aws/issues/7438)) -* **New Resource:** `aws_backup_vault` ([#7207](https://github.com/terraform-providers/terraform-provider-aws/issues/7207)) -* **New Resource:** `aws_docdb_cluster` ([#7122](https://github.com/terraform-providers/terraform-provider-aws/issues/7122)) -* **New Resource:** `aws_docdb_cluster_snapshot` ([#7123](https://github.com/terraform-providers/terraform-provider-aws/issues/7123)) -* **New Resource:** `aws_ec2_client_vpn_endpoint` ([#7009](https://github.com/terraform-providers/terraform-provider-aws/issues/7009)) -* **New Resource:** `aws_ec2_client_vpn_network_association` ([#7030](https://github.com/terraform-providers/terraform-provider-aws/issues/7030)) -* **New Resource:** `aws_sagemaker_model` ([#2478](https://github.com/terraform-providers/terraform-provider-aws/issues/2478)) - -ENHANCEMENTS: - -* resource/aws_s3_bucket: Limit no of `expiration` & `noncurrent_version_expiration` blocks to 1 ([#7462](https://github.com/terraform-providers/terraform-provider-aws/issues/7462)) - -BUG FIXES: - -* resource/aws_dynamodb_table: Prevent error when updating `billing_mode` from `PAY_PER_REQUEST` to `PROVISIONED` ([#7363](https://github.com/terraform-providers/terraform-provider-aws/issues/7363)) - -## 1.57.0 (January 26, 2019) - -NOTES: - -* provider: Fairly light release this week due to Terraform 0.12 upgrade and Terraform AWS Provider 2.0 related activities happening behind the scenes, which will continue through at least next week. For additional tracking information about those efforts, see the v2.0.0 milestone in GitHub. - -ENHANCEMENTS - -* data-source/aws_mq_broker: Add `tags` attribute ([#7193](https://github.com/terraform-providers/terraform-provider-aws/issues/7193)) -* provider: Switch codebase dependency management from `govendor` to Go modules ([#7165](https://github.com/terraform-providers/terraform-provider-aws/issues/7165)) -* resource/aws_autoscaling_policy: Support resource import ([#7195](https://github.com/terraform-providers/terraform-provider-aws/issues/7195)) -* resource/aws_lb_listener: Add `TLS` to `protocol` argument validation ([#7338](https://github.com/terraform-providers/terraform-provider-aws/issues/7338)) -* resource/aws_lb_target_group: Add `TLS` to `protocol` argument validation ([#7338](https://github.com/terraform-providers/terraform-provider-aws/issues/7338)) -* resource/aws_mq_broker: Add `tags` argument ([#7193](https://github.com/terraform-providers/terraform-provider-aws/issues/7193)) -* resource/aws_mq_configuration: Add `tags` argument ([#7193](https://github.com/terraform-providers/terraform-provider-aws/issues/7193)) - -BUG FIXES - -* resource/aws_autoscaling_policy: Properly read `step_adjustment` into Terraform state ([#7336](https://github.com/terraform-providers/terraform-provider-aws/issues/7336)) -* resource/aws_emr_cluster: Fix regression with `instance_group` differences when using `name` ([#7324](https://github.com/terraform-providers/terraform-provider-aws/issues/7324)) -* resource/aws_iot_topic_rule: Prevent panic with missing SQS UseBase64 attribute in API response ([#7337](https://github.com/terraform-providers/terraform-provider-aws/issues/7337)) -* resource/aws_lambda_permission: Retry for Lambda function eventual consistency on creation ([#7327](https://github.com/terraform-providers/terraform-provider-aws/issues/7327)) -* resource/aws_rds_cluster_parameter_group: Prevent missing DBClusterParameterGroupName error on creation with generated names and `name_prefix` ([#7326](https://github.com/terraform-providers/terraform-provider-aws/issues/7326)) -* resource/aws_s3_bucket_object: Delete S3 objects with leading '/' in the key name ([#7268](https://github.com/terraform-providers/terraform-provider-aws/issues/7268)) - -## 1.56.0 (January 16, 2019) - -NOTES - -* resource/aws_db_option_group: The Terraform resource is now able to perform drift detection on and import the state of the `option` attribute. The caveat is that while RDS returns only modified options, it will return all option settings whether modified or not from their default values. To workaround this option settings issue, we pass in the options from the Terraform configuration and ignore default values that are not present in the configuration. Some Terraform configurations may require minor updates to match the expected values. - -FEATURES - -* **New Data Source:** `aws_elastic_beanstalk_application` ([#7144](https://github.com/terraform-providers/terraform-provider-aws/issues/7144)) -* **New Resource:** `aws_docdb_subnet_group` ([#7106](https://github.com/terraform-providers/terraform-provider-aws/issues/7106)) -* **New Resource:** `aws_globalaccelerator_accelerator` ([#7002](https://github.com/terraform-providers/terraform-provider-aws/issues/7002)) -* **New Resource:** `aws_lambda_layer_version` ([#6782](https://github.com/terraform-providers/terraform-provider-aws/issues/6782)) -* **New Resource:** `aws_ram_resource_share` ([#6528](https://github.com/terraform-providers/terraform-provider-aws/issues/6528)) -* **New Resource:** `aws_sagemaker_notebook_instance` ([#7139](https://github.com/terraform-providers/terraform-provider-aws/issues/7139)) - -ENHANCEMENTS - -* data-source/aws_lambda_function: Add `layers` attribute ([#7126](https://github.com/terraform-providers/terraform-provider-aws/issues/7126)) -* resource/aws_emr_cluster: Support resource import ([#4488](https://github.com/terraform-providers/terraform-provider-aws/issues/4488)] / [[#6498](https://github.com/terraform-providers/terraform-provider-aws/issues/6498)) -* resource/aws_emr_cluster: Support `instance_group` `autoscaling_policy` updates ([#6498](https://github.com/terraform-providers/terraform-provider-aws/issues/6498)) -* resource/aws_inspector_assessment_target: Allow omitting resource_group_arn argument (support matching all EC2 instances) ([#7112](https://github.com/terraform-providers/terraform-provider-aws/issues/7112)) -* resource/aws_inspector_assessment_target: Support resource import ([#7112](https://github.com/terraform-providers/terraform-provider-aws/issues/7112)) -* resource/aws_lambda_function: Add `layers` argument ([#7126](https://github.com/terraform-providers/terraform-provider-aws/issues/7126)) -* resource/aws_s3_bucket: Add `object_lock_configuration` argument (support S3 Object Lock) ([#6964](https://github.com/terraform-providers/terraform-provider-aws/issues/6964)) - -BUG FIXES - -* resource/aws_acm_certificate: Prevent crash with empty `SubjectAlternativeNames` (e.g. `IMPORTED` type certificates with IP address `CommonName`) ([#7127](https://github.com/terraform-providers/terraform-provider-aws/issues/7127)) -* resource/aws_api_gateway_method_settings: Prevent crash when using `cache_data_encrypted` ([#7133](https://github.com/terraform-providers/terraform-provider-aws/issues/7133)) -* resource/aws_db_option_group: Read `option` attribute into Terraform state for drift detection ([#7125](https://github.com/terraform-providers/terraform-provider-aws/issues/7125)) -* resource/aws_db_option_group: Skip erroneous `ModifyOptionGroup` error when no option updates are being performed ([#7125](https://github.com/terraform-providers/terraform-provider-aws/issues/7125)) -* resource/aws_ec2_transit_gateway_route: Prevent crash with externally removed attachment ([#7117](https://github.com/terraform-providers/terraform-provider-aws/issues/7117)) -* resource/aws_emr_cluster: Properly read `core_instance_count`, `master_instance_type`, and `termination_policies` into Terraform state ([#4488](https://github.com/terraform-providers/terraform-provider-aws/issues/4488)] / [[#6498](https://github.com/terraform-providers/terraform-provider-aws/issues/6498)) -* resource/aws_inspector_assessment_target: Properly read resource_group_arn attribute into Terraform state ([#7112](https://github.com/terraform-providers/terraform-provider-aws/issues/7112)) -* resource/aws_launch_template: Prevent crashes with empty configuration blocks for top-level attributes ([#7134](https://github.com/terraform-providers/terraform-provider-aws/issues/7134)) -* resource/aws_s3_bucket_object: Prevent creating new S3 object version when updating ACL or tags ([#7138](https://github.com/terraform-providers/terraform-provider-aws/issues/7138)) -* resource/aws_s3_bucket_object: Prevent `NoSuchKey` errors reading tags on resource creation ([#7138](https://github.com/terraform-providers/terraform-provider-aws/issues/7138)) -* service/applicationautoscaling: Use proper endpoint information in AWS GovCloud (US) ([#7142](https://github.com/terraform-providers/terraform-provider-aws/issues/7142)) -* service/servicediscovery: Return full error messaging for failed operations ([#7118](https://github.com/terraform-providers/terraform-provider-aws/issues/7118)) - -## 1.55.0 (January 10, 2019) - -FEATURES - -* **New Resource:** `aws_docdb_cluster_parameter_group` ([#7090](https://github.com/terraform-providers/terraform-provider-aws/issues/7090)) -* **New Resource:** `aws_media_package_channel` ([#6957](https://github.com/terraform-providers/terraform-provider-aws/issues/6957)) -* **New Resource:** `aws_resourcegroups_group` ([#6217](https://github.com/terraform-providers/terraform-provider-aws/issues/6217)) - -ENHANCEMENTS - -* resource/aws_app_cookie_stickiness_policy: Support resource import ([#7080](https://github.com/terraform-providers/terraform-provider-aws/issues/7080)) -* resource/aws_elasticsearch_domain: Support in-place updates of `elasticsearch_version` ([#6243](https://github.com/terraform-providers/terraform-provider-aws/issues/6243)) -* resource/aws_kinesis_firehose_delivery_stream: Add `extended_s3_configuration` `error_output_prefix` argument ([#7026](https://github.com/terraform-providers/terraform-provider-aws/issues/7026)) -* resource/aws_sfn_activity: Add `tags` argument ([#7024](https://github.com/terraform-providers/terraform-provider-aws/issues/7024)) -* resource/aws_sfn_state_machine: Add `tags` argument ([#7024](https://github.com/terraform-providers/terraform-provider-aws/issues/7024)) -* resource/aws_ssm_maintenance_window: Add `end_date`, `schedule_timezone`, and `start_date` arguments ([#7040](https://github.com/terraform-providers/terraform-provider-aws/issues/7040)) - -BUG FIXES - -* resource/aws_batch_job_queue: Properly read `compute_environments` into Terraform state ([#7079](https://github.com/terraform-providers/terraform-provider-aws/issues/7079)) -* resource/aws_dynamodb_table: Prevent `BillingMode` `ValidationError` on table creation ([#7064](https://github.com/terraform-providers/terraform-provider-aws/issues/7064)) -* resource/aws_iam_group_policy: Skip `NoSuchEntity` errors on resource deletion without refresh ([#7071](https://github.com/terraform-providers/terraform-provider-aws/issues/7071)) -* resource/aws_iam_role_policy: Skip `NoSuchEntity` errors on resource deletion without refresh ([#7070](https://github.com/terraform-providers/terraform-provider-aws/issues/7070)) -* resource/aws_iam_policy: Present more human readable error message during resource deletion ([#7072](https://github.com/terraform-providers/terraform-provider-aws/issues/7072)) -* resource/aws_iam_user_policy: Skip `NoSuchEntity` errors on resource deletion without refresh ([#7069](https://github.com/terraform-providers/terraform-provider-aws/issues/7069)) -* resource/aws_instance: Skip `InvalidInstanceID.NotFound` error on resource deletion ([#6978](https://github.com/terraform-providers/terraform-provider-aws/issues/6978)) -* resource/aws_kinesis_analytics_application: Retry Lambda permission `InvalidArgumentException` errors for IAM eventual consistency ([#7039](https://github.com/terraform-providers/terraform-provider-aws/issues/7039)) - -## 1.54.0 (December 21, 2018) - -NOTES - -* This will be the last release until early January. Enjoy the rest of your year! - -FEATURES - -* **New Data Source:** `aws_autoscaling_group` ([#6849](https://github.com/terraform-providers/terraform-provider-aws/issues/6849)) -* **New Resource:** `aws_licensemanager_association` ([#6926](https://github.com/terraform-providers/terraform-provider-aws/issues/6926)) -* **New Resource:** `aws_s3_bucket_public_access_block` ([#6607](https://github.com/terraform-providers/terraform-provider-aws/issues/6607)) -* **New Resource:** `aws_securityhub_product_subscription` ([#6921](https://github.com/terraform-providers/terraform-provider-aws/issues/6921)) - -ENHANCEMENTS - -* resource/aws_acm_certificate: Add `certificate_body`, `certificate_chain`, and `private_key` arguments (Support importing/uploading certificate into ACM) ([#5453](https://github.com/terraform-providers/terraform-provider-aws/issues/5453)) -* resource/aws_launch_template: Add `license_specification` argument ([#6926](https://github.com/terraform-providers/terraform-provider-aws/issues/6926)) -* resource/aws_redshift_cluster: Support in-place updates for adding or removing KMS encryption ([#6865](https://github.com/terraform-providers/terraform-provider-aws/issues/6865)) -* resource/aws_transfer_server: Add `force_destroy` argument ([#6935](https://github.com/terraform-providers/terraform-provider-aws/issues/6935)) - -BUG FIXES - -* resource/aws_acm_certificate: Prevent error using Terraform resource import with certificates missing domain validation options ([#5472](https://github.com/terraform-providers/terraform-provider-aws/issues/5472)) - -## 1.53.0 (December 20, 2018) - -FEATURES - -* **New Resource:** `aws_licensemanager_license_configuration` ([#6835](https://github.com/terraform-providers/terraform-provider-aws/issues/6835)) -* **New Resource:** `aws_rds_global_cluster` ([#6861](https://github.com/terraform-providers/terraform-provider-aws/issues/6861)) -* **New Resource:** `aws_s3_account_public_access_block` ([#6851](https://github.com/terraform-providers/terraform-provider-aws/issues/6851)) -* **New Resource:** `aws_securityhub_standards_subscription` ([#6862](https://github.com/terraform-providers/terraform-provider-aws/issues/6862)) -* **New Resource:** `aws_service_discovery_http_namespace` ([#6864](https://github.com/terraform-providers/terraform-provider-aws/issues/6864)) -* **New Resource:** `aws_transfer_ssh_key` ([#6932](https://github.com/terraform-providers/terraform-provider-aws/issues/6932)) -* **New Resource:** `aws_transfer_user` ([#6850](https://github.com/terraform-providers/terraform-provider-aws/issues/6850)) - -ENHANCEMENTS - -* data-source/aws_cloudtrail_service_account: Support `us-gov-east-1` and `us-gov-west-1` regions ([#6893](https://github.com/terraform-providers/terraform-provider-aws/issues/6893)) -* data-source/aws_ecr_repository: Add `tags` attribute ([#6911](https://github.com/terraform-providers/terraform-provider-aws/issues/6911)) -* resource/aws_codebuild_project: Support `source` `report_build_status` for GitHub Enterprise ([#6929](https://github.com/terraform-providers/terraform-provider-aws/issues/6929)) -* resource/aws_db_snapshot: Add `tags` argument ([#6881](https://github.com/terraform-providers/terraform-provider-aws/issues/6881)) -* resource/aws_ecr_repository: Add `tags` argument ([#6911](https://github.com/terraform-providers/terraform-provider-aws/issues/6911)) -* resource/aws_ecs_service: Add `platform_version` argument (ECS Fargate Platform Version Support) ([#6510](https://github.com/terraform-providers/terraform-provider-aws/issues/6510)) -* resource/aws_guardduty_detector: Add `finding_publishing_frequency` argument ([#6922](https://github.com/terraform-providers/terraform-provider-aws/issues/6922)) -* resource/aws_lb_target_group: Add `lambda` as supported `target_type` with omitting `port`, `protocol`, and `vpc_id` arguments (support Lambda target groups) ([#6719](https://github.com/terraform-providers/terraform-provider-aws/issues/6719)) -* resource/aws_rds_cluster: Allow `global` in `engine_mode` validation and add `global_cluster_identifier` argument ([#6861](https://github.com/terraform-providers/terraform-provider-aws/issues/6861)) - -BUG FIXES - -* resource/aws_cloudwatch_log_stream: Trigger resource recreation on `ResourceNotFoundException` error ([#6776](https://github.com/terraform-providers/terraform-provider-aws/issues/6776)) -* resource/aws_s3_bucket: Skip `MethodNotAllowed` error during read for missing S3 Bucket Acceleration functionality (`eu-north-1` region support) ([#6873](https://github.com/terraform-providers/terraform-provider-aws/issues/6873)) -* resource/aws_transfer_server: Prevent error when no `tags` are assigned on resource creation ([#6883](https://github.com/terraform-providers/terraform-provider-aws/issues/6883)) - -## 1.52.0 (December 13, 2018) - -FEATURES - -* **New Data Source:** `aws_api_gateway_vpc_link` ([#6763](https://github.com/terraform-providers/terraform-provider-aws/issues/6763)) -* **New Resource:** `aws_appmesh_route` ([#6766](https://github.com/terraform-providers/terraform-provider-aws/issues/6766)) -* **New Resource:** `aws_appmesh_virtual_node` ([#6764](https://github.com/terraform-providers/terraform-provider-aws/issues/6764)) -* **New Resource:** `aws_rds_cluster_endpoint` ([#6576](https://github.com/terraform-providers/terraform-provider-aws/issues/6576)) -* **New Resource:** `aws_securityhub_account` ([#6839](https://github.com/terraform-providers/terraform-provider-aws/issues/6839)) -* **New Resource:** `aws_transfer_server` ([#6639](https://github.com/terraform-providers/terraform-provider-aws/issues/6639)) - -ENHANCEMENTS - -* data-source/aws_cloudtrail_service_account: Support `ap-northeast-3` and `eu-north-1` regions ([#6836](https://github.com/terraform-providers/terraform-provider-aws/issues/6836)) -* data-source/aws_elb_hosted_zone_id: Support `ap-northeast-3` and `eu-north-1` regions ([#6836](https://github.com/terraform-providers/terraform-provider-aws/issues/6836)) -* data-source/aws_elb_service_account: Support `ap-northeast-3`, `eu-north-1`, and `us-gov-east-1` regions ([#6836](https://github.com/terraform-providers/terraform-provider-aws/issues/6836)) -* data-source/aws_instance: Add `host_id` attribute ([#6767](https://github.com/terraform-providers/terraform-provider-aws/issues/6767)) -* data-source/aws_ip_ranges: Add `url` argument ([#6756](https://github.com/terraform-providers/terraform-provider-aws/issues/6756)) -* data-source/aws_s3_bucket: Support `ap-northeast-3` and `eu-north-1` regions for `hosted_zone_id` ([#6836](https://github.com/terraform-providers/terraform-provider-aws/issues/6836)) -* provider: Support automatic region validation for `eu-north-1` ([#6815](https://github.com/terraform-providers/terraform-provider-aws/issues/6815)) -* resource/aws_acm_certificate: Automatically trim trailing period from `domain_name` and `subject_alternative_names` arguments ([#6844](https://github.com/terraform-providers/terraform-provider-aws/issues/6844)) -* resource/aws_db_instance: Allow `postgresql` and `upgrade` values for `enabled_cloudwatch_logs_exports` (e.g. Postgres specific log exports) ([#6829](https://github.com/terraform-providers/terraform-provider-aws/issues/6829)) -* resource/aws_dynamodb_table: Allow `global_secondary_index` configuration block `read_capacity` and `write_capacity` to be omitted with `billing_mode` set to `PAY_PER_REQUEST` (support on-demand billing with GSIs) ([#6737](https://github.com/terraform-providers/terraform-provider-aws/issues/6737)) -* resource/aws_eks_cluster: Support `version` update ([#6843](https://github.com/terraform-providers/terraform-provider-aws/issues/6843)) -* resource/aws_glue_crawler: Add `security_configuration` argument ([#6797](https://github.com/terraform-providers/terraform-provider-aws/issues/6797)) -* resource/aws_iam_user_ssh_key: Support resource import ([#6727](https://github.com/terraform-providers/terraform-provider-aws/issues/6727)) -* resource/aws_instance: Add `host_id` argument ([#6767](https://github.com/terraform-providers/terraform-provider-aws/issues/6767)) -* resource/aws_s3_bucket: Support `ap-northeast-3` and `eu-north-1` regions for `hosted_zone_id` ([#6836](https://github.com/terraform-providers/terraform-provider-aws/issues/6836)) -* resource/aws_ssm_maintenance_window: Support resource import ([#6747](https://github.com/terraform-providers/terraform-provider-aws/issues/6747)) - -BUG FIXES - -* data-source/aws_lb_listener: Add missing `default_action` attributes from resource ([#6830](https://github.com/terraform-providers/terraform-provider-aws/issues/6830)) -* resource/aws_cloudwatch_log_subscription_filter: Ignore `ResourceNotFound` error on deletion ([#6760](https://github.com/terraform-providers/terraform-provider-aws/issues/6760)) -* resource/aws_ec2_transit_gateway_route: Trigger resource recreation with deleted/deleting route state ([#6817](https://github.com/terraform-providers/terraform-provider-aws/issues/6817)) -* resource/aws_elasticache_parameter_group: Handle API reset issues with `reserved-memory` parameter updates ([#6752](https://github.com/terraform-providers/terraform-provider-aws/issues/6752)) -* resource/aws_lambda_permission: Ignore `ResourceNotFoundException` error on deletion ([#6770](https://github.com/terraform-providers/terraform-provider-aws/issues/6770)) -* resource/aws_lb_listener: Properly return an error when there are issues setting `default_action` attributes in Terraform state ([#6830](https://github.com/terraform-providers/terraform-provider-aws/issues/6830)) -* resource/aws_route53_record: Prevent scanning entire zone for missing record ([#6753](https://github.com/terraform-providers/terraform-provider-aws/issues/6753)) -* resource/aws_ssm_document: Properly batch large `permissions` updates for API limits ([#6735](https://github.com/terraform-providers/terraform-provider-aws/issues/6735)) - -## 1.51.0 (December 05, 2018) - -FEATURES - -* **New Resource:** `aws_appmesh_mesh` ([#6708](https://github.com/terraform-providers/terraform-provider-aws/issues/6708)) -* **New Resource:** `aws_appmesh_virtual_router` ([#6720](https://github.com/terraform-providers/terraform-provider-aws/issues/6720)) - -ENHANCEMENTS - -* data-source/aws_availability_zone: Add `zone_id` attribute ([#6686](https://github.com/terraform-providers/terraform-provider-aws/issues/6686)) -* data-source/aws_availability_zones: Add `zone_ids` attribute ([#6686](https://github.com/terraform-providers/terraform-provider-aws/issues/6686)) -* data-source/aws_iam_policy_document: Provide error if duplicate `sid` are configured across statements ([#6675](https://github.com/terraform-providers/terraform-provider-aws/issues/6675)) -* data-source/aws_iam_policy_document: Add `version` argument ([#6699](https://github.com/terraform-providers/terraform-provider-aws/issues/6699)) -* data-source/aws_internet_gateway: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* data-source/aws_route_table: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* data-source/aws_subnet: Add `availability_zone_id` argument and `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* data-source/aws_subnet: Use API provided `arn` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* data-source/aws_vpc: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* data-source/aws_vpc_dhcp_options: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_cloudtrail: Add `is_organization_trail` argument ([#6580](https://github.com/terraform-providers/terraform-provider-aws/issues/6580)) -* resource/aws_codedeploy_config: Add `compute_platform` and `traffic_routing_config` arguments (support Lambda) ([#6644](https://github.com/terraform-providers/terraform-provider-aws/issues/6644)) -* resource/aws_default_network_acl: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_default_route_table: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_default_subnet: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_default_vpc: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_default_vpc_dhcp_options: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_dynamodb_table: Add `billing_mode` argument (support on-demand capacity) ([#6648](https://github.com/terraform-providers/terraform-provider-aws/issues/6648)) -* resource/aws_ecs_service: Add `propagate_tags` argument ([#6603](https://github.com/terraform-providers/terraform-provider-aws/issues/6603)) -* resource/aws_ecs_task_definition: Support resource import ([#6723](https://github.com/terraform-providers/terraform-provider-aws/issues/6723)) -* resource/aws_iam_group_policy_attachment: Support resource import ([#6625](https://github.com/terraform-providers/terraform-provider-aws/issues/6625)) -* resource/aws_iam_user_policy_attachment: Support resource import ([#6487](https://github.com/terraform-providers/terraform-provider-aws/issues/6487)) -* resource/aws_internet_gateway: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_lambda_alias: Add `invoke_arn` attribute ([#6329](https://github.com/terraform-providers/terraform-provider-aws/issues/6329)) -* resource/aws_lambda_function: Support `provided` in `runtime` validation ([#6676](https://github.com/terraform-providers/terraform-provider-aws/issues/6676)) -* resource/aws_lambda_function: Support `python3.7` in `runtime` validation ([#6583](https://github.com/terraform-providers/terraform-provider-aws/issues/6583)) -* resource/aws_lambda_function: Support `ruby2.5` in `runtime` validation ([#6657](https://github.com/terraform-providers/terraform-provider-aws/issues/6657)) -* resource/aws_network_acl: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_rds_cluster_instance: Add `copy_tags_to_snapshot` argument ([#6582](https://github.com/terraform-providers/terraform-provider-aws/issues/6582)) -* resource/aws_route_table: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_s3_bucket: Support `INTELLIGENT_TIERING` in storage class validations ([#6589](https://github.com/terraform-providers/terraform-provider-aws/issues/6589)) -* resource/aws_s3_bucket: Support replication rule destination storage class `GLACIER` ([#6613](https://github.com/terraform-providers/terraform-provider-aws/issues/6613)) -* resource/aws_s3_bucket_inventory: Support destination bucket `Parquet` in `format` validation ([#6729](https://github.com/terraform-providers/terraform-provider-aws/issues/6729)) -* resource/aws_s3_bucket_object: Support `GLACIER` in `storage_class` validation ([#6610](https://github.com/terraform-providers/terraform-provider-aws/issues/6610)) -* resource/aws_s3_bucket_object: Support `INTELLIGENT_TIERING` in `storage_class` validation ([#6589](https://github.com/terraform-providers/terraform-provider-aws/issues/6589)) -* resource/aws_ses_event_destination: Support multiple `cloudwatch_destination` configuration blocks ([#6690](https://github.com/terraform-providers/terraform-provider-aws/issues/6690)) -* resource/aws_subnet: Add `availability_zone_id` argument and `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_subnet: Use API provided `arn` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_vpc: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) -* resource/aws_vpc_dhcp_options: Add `owner_id` attribute ([#6642](https://github.com/terraform-providers/terraform-provider-aws/issues/6642)) - -BUG FIXES: - -* resource/aws_db_instance: Allow `configuring-iam-database-auth` as pending state ([#6597](https://github.com/terraform-providers/terraform-provider-aws/issues/6597)) -* resource/aws_ec2_transit_gateway_vpc_attachment: Prevent error when Transit Gateway does not have default route table ([#6665](https://github.com/terraform-providers/terraform-provider-aws/issues/6665)) -* resource/aws_iam_user_ssh_key: Properly trigger resource recreation with `encoding` and `public_key` updates ([#6718](https://github.com/terraform-providers/terraform-provider-aws/issues/6718)) -* resource/aws_iot_topic_rule: Omit sending empty string `cloudwatch_metric` configuration block `metric_timestamp` argument to AWS ([#6618](https://github.com/terraform-providers/terraform-provider-aws/issues/6618)) - -## 1.50.0 (November 29, 2018) - -ENHANCEMENTS - -* resource/aws_codedeploy_app: Support `ECS` `compute_platform` ([#6647](https://github.com/terraform-providers/terraform-provider-aws/issues/6647)) -* resource/aws_codedeploy_deployment_group: Add `ecs_service` argument and `load_balancer_info` configuration block `target_group_pair_info` argument (Support ECS Blue/Green Deployment) ([#6647](https://github.com/terraform-providers/terraform-provider-aws/issues/6647)) -* resource/aws_ecs_service: Add `deployment_controller` argument ([#6647](https://github.com/terraform-providers/terraform-provider-aws/issues/6647)) - -## 1.49.0 (November 27, 2018) - -FEATURES - -* **New Data Source:** `aws_ec2_transit_gateway` ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* **New Data Source:** `aws_ec2_transit_gateway_route_table` ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* **New Data Source:** `aws_ec2_transit_gateway_vpc_attachment` ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* **New Resource:** `aws_ec2_transit_gateway` ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* **New Resource:** `aws_ec2_transit_gateway_route` ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* **New Resource:** `aws_ec2_transit_gateway_route_table` ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* **New Resource:** `aws_ec2_transit_gateway_route_table_association` ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* **New Resource:** `aws_ec2_transit_gateway_route_table_propagation` ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* **New Resource:** `aws_ec2_transit_gateway_vpc_attachment` ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) - -ENHANCEMENTS - -* data-source/aws_route: Add `transit_gateway_id` attribute ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* data-source/aws_route_table: Add `route` attribute block `transit_gateway_id` attribute ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* resource/aws_default_route_table: Add `route` configuration block `transit_gateway_id` argument ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* resource/aws_route: Add `transit_gateway_id` argument ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* resource/aws_route_table: Add `route` configuration block `transit_gateway_id` argument ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) -* resource/aws_vpn_connection: Add `transit_gateway_id` argument, mark `vpn_gateway_id` as optional ([#6605](https://github.com/terraform-providers/terraform-provider-aws/issues/6605)) - -## 1.48.0 (November 26, 2018) - -FEATURES - -* **New Resource:** `aws_datasync_agent` ([#6591](https://github.com/terraform-providers/terraform-provider-aws/issues/6591)) -* **New Resource:** `aws_datasync_location_efs` ([#6591](https://github.com/terraform-providers/terraform-provider-aws/issues/6591)) -* **New Resource:** `aws_datasync_location_nfs` ([#6591](https://github.com/terraform-providers/terraform-provider-aws/issues/6591)) -* **New Resource:** `aws_datasync_location_s3` ([#6591](https://github.com/terraform-providers/terraform-provider-aws/issues/6591)) -* **New Resource:** `aws_datasync_task` ([#6591](https://github.com/terraform-providers/terraform-provider-aws/issues/6591)) - -## 1.47.0 (November 26, 2018) - -FEATURES: - -* **New Data Source:** `aws_route53_delegation_set` ([#6152](https://github.com/terraform-providers/terraform-provider-aws/issues/6152)) -* **New Data Source:** `aws_ssm_document` ([#6479](https://github.com/terraform-providers/terraform-provider-aws/issues/6479)) - -ENHANCEMENTS: - -* resource/aws_ecs_service: Add `enable_ecs_managed_tags` argument ([#6544](https://github.com/terraform-providers/terraform-provider-aws/issues/6544)) -* resource/aws_kinesis_firehose_delivery_stream: Add `tags` argument ([#6548](https://github.com/terraform-providers/terraform-provider-aws/issues/6548)) -* resource/aws_organizations_organization: Add `aws_service_access_principals` argument ([#6581](https://github.com/terraform-providers/terraform-provider-aws/issues/6581)) -* resource/aws_s3_bucket_policy: Support resource import ([#6543](https://github.com/terraform-providers/terraform-provider-aws/issues/6543)) -* resource/aws_vpc: Support plan-time validation for `cidr_block` block size ([#6577](https://github.com/terraform-providers/terraform-provider-aws/issues/6577)) - -BUG FIXES: - -* resource/aws_elastic_transcoder_preset: Properly read `video_codec_options` into Terraform state ([#6545](https://github.com/terraform-providers/terraform-provider-aws/issues/6545)) -* resource/aws_subnet: Always set `ipv6_cidr_block_association_id` and `ipv6_cidr_block` attributes in Terraform state ([#6533](https://github.com/terraform-providers/terraform-provider-aws/issues/6533)) - -## 1.46.0 (November 20, 2018) - -FEATURES: - -* **New Data Source:** `aws_api_gateway_api_key` ([#6449](https://github.com/terraform-providers/terraform-provider-aws/issues/6449)) - -ENHANCEMENTS: - -* data-source/aws_eip: Add `association_id`, `domain`, `instance_id`, `network_interface_id`, `network_interface_owner_id`, `private_ip`, and `public_ipv4_pool` attributes ([#6463](https://github.com/terraform-providers/terraform-provider-aws/issues/6463)] / [[#6518](https://github.com/terraform-providers/terraform-provider-aws/issues/6518)) -* resource/aws_ecs_cluster: Add `tags` argument ([#6486](https://github.com/terraform-providers/terraform-provider-aws/issues/6486)) -* resource/aws_ecs_service: Add `tags` argument ([#6486](https://github.com/terraform-providers/terraform-provider-aws/issues/6486)) -* resource/aws_ecs_task_definition: Add `tags` argument ([#6486](https://github.com/terraform-providers/terraform-provider-aws/issues/6486)) -* resource/aws_ecs_task_definition: Add `ipc_mode` and `pid_mode` arguments ([#6515](https://github.com/terraform-providers/terraform-provider-aws/issues/6515)) -* resource/aws_eip: Add `public_ipv4_pool` argument ([#6518](https://github.com/terraform-providers/terraform-provider-aws/issues/6518)) -* resource/aws_iam_role: Add `tags` argument ([#6499](https://github.com/terraform-providers/terraform-provider-aws/issues/6499)) -* resource/aws_iam_user: Add `tags` argument ([#6497](https://github.com/terraform-providers/terraform-provider-aws/issues/6497)) -* resource/aws_sns_topic: Add `kms_master_key_id` argument (support server-side encryption) ([#6502](https://github.com/terraform-providers/terraform-provider-aws/issues/6502)) - -BUG FIXES: - -* resource/aws_kinesis_analytics_application: Properly handle `processing_configuration` argument ([#6495](https://github.com/terraform-providers/terraform-provider-aws/issues/6495)) - -## 1.45.0 (November 15, 2018) - -ENHANCEMENTS: - -* resource/aws_autoscaling_group: Mixed Instances Policy support ([#6465](https://github.com/terraform-providers/terraform-provider-aws/issues/6465)) - -## 1.44.0 (November 14, 2018) - -FEATURES: - -* **New Resource:** `aws_gamelift_game_session_queue` ([#6335](https://github.com/terraform-providers/terraform-provider-aws/issues/6335)) -* **New Resource:** `aws_glacier_vault_lock` ([#6432](https://github.com/terraform-providers/terraform-provider-aws/issues/6432)) - -ENHANCEMENTS: - -* data-source/aws_eip: Add `filter` argument ([#3525](https://github.com/terraform-providers/terraform-provider-aws/issues/3525)) -* data-source/aws_eip: Add `tags` argument ([#3505](https://github.com/terraform-providers/terraform-provider-aws/issues/3505)) -* data-source/aws_eip: Support EC2-Classic Elastic IPs ([#3522](https://github.com/terraform-providers/terraform-provider-aws/issues/3522)) -* resource/aws_codebuild_project: Support `source` `report_build_status` for Bitbucket ([#6426](https://github.com/terraform-providers/terraform-provider-aws/issues/6426)) -* resource/aws_dlm_lifecycle_policy: Add `copy_tags` argument ([#6445](https://github.com/terraform-providers/terraform-provider-aws/issues/6445)) -* resource/aws_ebs_snapshot: Allow retries for `SnapshotCreationPerVolumeRateExceeded` errors on creation ([#6414](https://github.com/terraform-providers/terraform-provider-aws/issues/6414)) -* resource/aws_ebs_volume: Switch to tagging on creation ([#6396](https://github.com/terraform-providers/terraform-provider-aws/issues/6396)) -* resource/aws_elastic_transcoder_pipeline: Support resource import ([#6388](https://github.com/terraform-providers/terraform-provider-aws/issues/6388)) -* resource/aws_elastic_transcoder_preset: Support resource import ([#6388](https://github.com/terraform-providers/terraform-provider-aws/issues/6388)) -* resource/aws_lambda_event_source_mapping: Add `starting_position_timestamp` argument ([#6437](https://github.com/terraform-providers/terraform-provider-aws/issues/6437)) -* resource/aws_route53_health_check: Provide plan-time validation for `type` ([#6460](https://github.com/terraform-providers/terraform-provider-aws/issues/6460)) -* resource/aws_ses_receipt_rule: Support resource import ([#6237](https://github.com/terraform-providers/terraform-provider-aws/issues/6237)) -* resource/aws_ssm_maintenance_window_task: Add `description` and `name` arguments ([#5762](https://github.com/terraform-providers/terraform-provider-aws/issues/5762)) - -BUG FIXES: - -* data-source/aws_ebs_snapshot: Fix `most_recent` ordering ([#6414](https://github.com/terraform-providers/terraform-provider-aws/issues/6414)) -* resource/aws_cloudwatch_log_metric_filter: Properly leave `default_value` empty when unset ([#5933](https://github.com/terraform-providers/terraform-provider-aws/issues/5933)) -* resource/aws_route53_health_check: Properly read `child_healthchecks` into Terraform state ([#6460](https://github.com/terraform-providers/terraform-provider-aws/issues/6460)) -* resource/aws_security_group_rule: Support all non-zero `from_port` and `to_port` configurations with `protocol` ALL/-1 ([#6423](https://github.com/terraform-providers/terraform-provider-aws/issues/6423)) -* resource/aws_sns_platform_application: Properly trigger resource recreation when deleted outside Terraform ([#6436](https://github.com/terraform-providers/terraform-provider-aws/issues/6436)) -* service/ec2: Allow `tags` and `volume_tags` updates to retry based on SDK retries instead of time bounds for EC2 throttling ([#3586](https://github.com/terraform-providers/terraform-provider-aws/issues/3586)) - -## 1.43.2 (November 10, 2018) - -BUG FIXES: - -* resource/aws_security_group_rule: Prevent crash when reading rules from groups containing an `ALL`/`-1` `protocol` rule ([#6419](https://github.com/terraform-providers/terraform-provider-aws/issues/6419)) - -## 1.43.1 (November 09, 2018) - -BUG FIXES: - -* resource/aws_cloudwatch_metric_alarm: Accept EC2 automate reboot ARN ([#6405](https://github.com/terraform-providers/terraform-provider-aws/issues/6405)) -* resource/aws_lambda_function: Handle slower code uploads on creation with configurable timeout ([#6409](https://github.com/terraform-providers/terraform-provider-aws/issues/6409)) -* resource/aws_rds_cluster: Prevent `InvalidParameterCombination` error with `engine_version` and `snapshot_identifier` on creation ([#6391](https://github.com/terraform-providers/terraform-provider-aws/issues/6391)) -* resource/aws_security_group_rule: Properly handle updating description when `protocol` is -1/ALL ([#6407](https://github.com/terraform-providers/terraform-provider-aws/issues/6407)) -* resource/aws_vpc: Always set `assign_generated_ipv6_cidr_block`, `ipv6_association_id`, and `ipv6_cidr_block` attributes in Terraform state ([#2103](https://github.com/terraform-providers/terraform-provider-aws/issues/2103)) -* resource/aws_vpc: Always wait for IPv6 CIDR block association on resource creation if `assign_generated_ipv6_cidr_block` is set ([#6394](https://github.com/terraform-providers/terraform-provider-aws/issues/6394)) -* service/ec2: Properly ignore sending existing tags during updates ([#5108](https://github.com/terraform-providers/terraform-provider-aws/issues/5108)] / [[#6370](https://github.com/terraform-providers/terraform-provider-aws/issues/6370)) - -## 1.43.0 (November 07, 2018) - -NOTES: - -* resource/aws_lb_listener: This resource will now sort the API response based on action ordering. If necessary, sorting your configuration based on `order` should resolve any plan difference. -* resource/aws_lb_listener_rule: This resource will now sort the API response based on action ordering. If necessary, sorting your configuration based on `order` should resolve any plan difference. - -FEATURES: - -* **New Resource:** `aws_dlm_lifecycle_policy` ([#5558](https://github.com/terraform-providers/terraform-provider-aws/issues/5558)) -* **New Resource:** `aws_kinesis_analytics_application` ([#5456](https://github.com/terraform-providers/terraform-provider-aws/issues/5456)) - -ENHANCEMENTS: - -* data-source/aws_efs_file_system: Add `arn` attribute ([#6371](https://github.com/terraform-providers/terraform-provider-aws/issues/6371)) -* data-source/aws_efs_mount_target: Add `file_system_arn` attribute ([#6371](https://github.com/terraform-providers/terraform-provider-aws/issues/6371)) -* data-source/aws_mq_broker: Add `logs` attribute ([#6122](https://github.com/terraform-providers/terraform-provider-aws/issues/6122)) -* resource/aws_efs_file_system: Add `arn` attribute ([#6371](https://github.com/terraform-providers/terraform-provider-aws/issues/6371)) -* resource/aws_efs_mount_target: Add `file_system_arn` attribute ([#6371](https://github.com/terraform-providers/terraform-provider-aws/issues/6371)) -* resource/aws_launch_configuration: Add `capacity_reservation_specification` argument ([#6325](https://github.com/terraform-providers/terraform-provider-aws/issues/6325)) -* resource/aws_mq_broker: Add `logs` argument ([#6122](https://github.com/terraform-providers/terraform-provider-aws/issues/6122)) - -BUG FIXES: - -* resource/aws_ecs_service: Continue supporting replica `deployment_minimum_healthy_percent = 0` and `deployment_maximum_percent = 100` ([#6316](https://github.com/terraform-providers/terraform-provider-aws/issues/6316)) -* resource/aws_flow_log: Automatically trim `:*` suffix from `log_destination` argument ([#6377](https://github.com/terraform-providers/terraform-provider-aws/issues/6377)) -* resource/aws_iam_user: Delete SSH keys with `force_delete` ([#6337](https://github.com/terraform-providers/terraform-provider-aws/issues/6337)) -* resource/aws_lb_listener: Prevent panics with actions deleted outside Terraform ([#6319](https://github.com/terraform-providers/terraform-provider-aws/issues/6319)) -* resource/aws_lb_listener_rule: Prevent panics with actions deleted outside Terraform ([#6319](https://github.com/terraform-providers/terraform-provider-aws/issues/6319)) -* resource/aws_opsworks_application: Properly recreate resource on `short_name` updates ([#6359](https://github.com/terraform-providers/terraform-provider-aws/issues/6359)) -* resource/aws_s3_bucket: Prevent `MalformedXML` error when using cross-region replication V1 with an empty `prefix` ([#6344](https://github.com/terraform-providers/terraform-provider-aws/issues/6344)) - -## 1.42.0 (October 31, 2018) - -NOTES: - -* resource/aws_route53_zone: The `vpc_id` and `vpc_region` arguments have been deprecated in favor of `vpc` configuration block(s). To upgrade, wrap existing `vpc_id` and `vpc_region` arguments with `vpc { ... }`. Since `vpc` is an exclusive set of VPC associations, you may need to define other `vpc` configuration blocks to match the infrastructure, or use lifecycle configuration `ignore_changes` to suppress the plan difference. -* resource/aws_route53_zone_association: Due to the multiple VPC association support now available in the `aws_route53_zone` resource, we recommend removing usage of this resource unless necessary for ordering. To remove this resource from management (without disassociating VPCs), you can use `terraform state rm`. If necessary to keep this resource for ordering, you can use the lifecycle `ignore_changes` in the `aws_route53_zone` resource to suppress plan differences. - -FEATURES: - -* **New Resource:** `aws_ec2_capacity_reservation` ([#6291](https://github.com/terraform-providers/terraform-provider-aws/issues/6291)) -* **New Resource:** `aws_glue_security_configuration` ([#6288](https://github.com/terraform-providers/terraform-provider-aws/issues/6288)) -* **New Resource:** `aws_iot_policy_attachment` ([#5864](https://github.com/terraform-providers/terraform-provider-aws/issues/5864)) -* **New Resource:** `aws_iot_thing_principal_attachment` ([#5868](https://github.com/terraform-providers/terraform-provider-aws/issues/5868)) -* **New Resource:** `aws_pinpoint_apns_sandbox_channel` ([#6233](https://github.com/terraform-providers/terraform-provider-aws/issues/6233)) -* **New Resource:** `aws_pinpoint_apns_voip_channel` ([#6234](https://github.com/terraform-providers/terraform-provider-aws/issues/6234)) -* **New Resource:** `aws_pinpoint_apns_voip_sandbox_channel` ([#6235](https://github.com/terraform-providers/terraform-provider-aws/issues/6235)) - -ENHANCEMENTS: - -* data-source/aws_iot_endpoint: Add `endpoint_type` argument ([#6215](https://github.com/terraform-providers/terraform-provider-aws/issues/6215)) -* data-source/aws_nat_gateway: Support `tags` as argument and attribute ([#6231](https://github.com/terraform-providers/terraform-provider-aws/issues/6231)) -* resource/aws_budgets_budget: Support resource import ([#6226](https://github.com/terraform-providers/terraform-provider-aws/issues/6226)) -* resource/aws_cloudwatch_event_permission: Add `condition` argument (support Organizations access) ([#6261](https://github.com/terraform-providers/terraform-provider-aws/issues/6261)) -* resource/aws_codepipeline_webhook: Support resource import ([#6202](https://github.com/terraform-providers/terraform-provider-aws/issues/6202)) -* resource/aws_cognito_user_pool_domain: Add `certificate_arn` argument (support custom domains) ([#6185](https://github.com/terraform-providers/terraform-provider-aws/issues/6185)) -* resource/aws_dx_hosted_private_virtual_interface: Add `mtu` argument and `jumbo_frame_capable` attribute ([#6142](https://github.com/terraform-providers/terraform-provider-aws/issues/6142)) -* resource/aws_dx_private_virtual_interface: Add `mtu` argument and `jumbo_frame_capable` attribute ([#6141](https://github.com/terraform-providers/terraform-provider-aws/issues/6141)) -* resource/aws_ecs_service: Support `deployment_minimum_healthy_percent` for `DAEMON` strategy ([#6150](https://github.com/terraform-providers/terraform-provider-aws/issues/6150)) -* resource/aws_flow_log: Add `log_destination` and `log_destination_type` arguments (support sending to S3) ([#5509](https://github.com/terraform-providers/terraform-provider-aws/issues/5509)) -* resource/aws_glue_job: Add `security_configuration` argument ([#6232](https://github.com/terraform-providers/terraform-provider-aws/issues/6232)) -* resource/aws_lb_target_group: Improve `name` and `name_prefix` argument plan-time validation ([#6168](https://github.com/terraform-providers/terraform-provider-aws/issues/6168)) -* resource/aws_s3_bucket: Support S3 Cross-Region Replication filtering based on S3 object tags ([#6095](https://github.com/terraform-providers/terraform-provider-aws/issues/6095)) -* resource/aws_secretsmanager_secret: Add `name_prefix` argument ([#6277](https://github.com/terraform-providers/terraform-provider-aws/issues/6277)) -* resource/aws_secretsmanager_secret: Add plan-time validation for `name` argument ([#6277](https://github.com/terraform-providers/terraform-provider-aws/issues/6277)) -* resource/aws_route53_zone: Add `vpc` argument, deprecate `vpc_id` and `vpc_region` arguments (support multiple VPC associations) ([#6299](https://github.com/terraform-providers/terraform-provider-aws/issues/6299)) -* resource/aws_waf_rule: Support resource import ([#6247](https://github.com/terraform-providers/terraform-provider-aws/issues/6247)) - -BUG FIXES: - -* data-source/aws_network_interface: Properly handle reading `private_ip` into Terraform state ([#6284](https://github.com/terraform-providers/terraform-provider-aws/issues/6284)) -* resource/aws_ami_launch_permission: Prevent panic reading public permissions ([#6224](https://github.com/terraform-providers/terraform-provider-aws/issues/6224)) -* resource/aws_budgets_budget: Properly read `time_period_start` and `time_period_end` into Terraform state ([#6226](https://github.com/terraform-providers/terraform-provider-aws/issues/6226)) -* resource/aws_cloudwatch_metric_alarm: Allow EC2 Automate ARNs with `alarm_actions` ([#6206](https://github.com/terraform-providers/terraform-provider-aws/issues/6206)) -* resource/aws_dx_gateway: Allow legacy `amazon_side_asn` in plan-time validation ([#6253](https://github.com/terraform-providers/terraform-provider-aws/issues/6253)) -* resource/aws_egress_only_internet_gateway: Improve eventual consistency logic during creation ([#6190](https://github.com/terraform-providers/terraform-provider-aws/issues/6190)) -* resource/aws_glue_crawler: Suppress `role` difference when using ARN ([#6293](https://github.com/terraform-providers/terraform-provider-aws/issues/6293)) -* resource/aws_iam_role_policy: Properly handle reading attributes into Terraform state after creation and update ([#6304](https://github.com/terraform-providers/terraform-provider-aws/issues/6304)) -* resource/aws_kinesis_firehose_delivery_stream: Properly recreate resource when updating `elasticsearch_configuration` `s3_backup_mode` ([#6305](https://github.com/terraform-providers/terraform-provider-aws/issues/6305)) -* resource/aws_nat_gateway: Remove `network_interface_id`, `private_ip`, and `public_ip` as configurable (they continue to be available as read-only attributes) ([#6225](https://github.com/terraform-providers/terraform-provider-aws/issues/6225)) -* resource/aws_network_acl: Properly handle ICMP code and type with IPv6 ICMP (protocol 58) ([#6264](https://github.com/terraform-providers/terraform-provider-aws/issues/6264)) -* resource/aws_network_acl_rule: Suppress `protocol` differences between name and number ([#2454](https://github.com/terraform-providers/terraform-provider-aws/issues/2454)) -* resource/aws_network_acl_rule: Properly handle ICMP code and type with IPv6 ICMP (protocol 58) ([#6263](https://github.com/terraform-providers/terraform-provider-aws/issues/6263)) -* resource/aws_rds_cluster_parameter_group: Properly read `parameter` `apply_method` into Terraform state ([#6295](https://github.com/terraform-providers/terraform-provider-aws/issues/6295)) - -## 1.41.0 (October 18, 2018) - -FEATURES: - -* **New Data Source:** `aws_cloudhsm_v2_cluster` ([#4125](https://github.com/terraform-providers/terraform-provider-aws/issues/4125)) -* **New Resource:** `aws_cloudhsm_v2_cluster` ([#4125](https://github.com/terraform-providers/terraform-provider-aws/issues/4125)) -* **New Resource:** `aws_cloudhsm_v2_hsm` ([#4125](https://github.com/terraform-providers/terraform-provider-aws/issues/4125)) -* **New Resource:** `aws_codepipeline_webhook` ([#5875](https://github.com/terraform-providers/terraform-provider-aws/issues/5875)) -* **New Resource:** `aws_pinpoint_apns_channel` ([#6194](https://github.com/terraform-providers/terraform-provider-aws/issues/6194)) -* **New Resource:** `aws_redshift_event_subscription` ([#6146](https://github.com/terraform-providers/terraform-provider-aws/issues/6146)) - -ENHANCEMENTS: - -* resource/aws_appsync_datasource: Support resource import ([#6139](https://github.com/terraform-providers/terraform-provider-aws/issues/6139)) -* resource/aws_appsync_datasource: Support `HTTP` `type` and add `http_config` argument ([#6139](https://github.com/terraform-providers/terraform-provider-aws/issues/6139)) -* resource/aws_appsync_datasource: Make `dynamodb_config` and `elasticsearch_config` `region` configuration optional based on resource current region ([#6139](https://github.com/terraform-providers/terraform-provider-aws/issues/6139)) -* resource/aws_appsync_graphql_api: Add `log_config` argument ([#6138](https://github.com/terraform-providers/terraform-provider-aws/issues/6138)) -* resource/aws_appsync_graphql_api: Add `openid_connect_config` argument ([#6138](https://github.com/terraform-providers/terraform-provider-aws/issues/6138)) -* resource/aws_appsync_graphql_api: Add `uris` attribute ([#6138](https://github.com/terraform-providers/terraform-provider-aws/issues/6138)) -* resource/aws_appsync_graphql_api: Make `user_pool_config` `aws_region` configuration optional based on resource current region ([#6138](https://github.com/terraform-providers/terraform-provider-aws/issues/6138)) -* resource/aws_athena_database: Add `encryption_configuration` argument ([#6117](https://github.com/terraform-providers/terraform-provider-aws/issues/6117)) -* resource/aws_cloudwatch_metric_alarm: Validate `alarm_actions` ([#6151](https://github.com/terraform-providers/terraform-provider-aws/issues/6151)) -* resource/aws_codebuild_project: Support `NO_SOURCE` in `source` `type` ([#6140](https://github.com/terraform-providers/terraform-provider-aws/issues/6140)) -* resource/aws_db_instance: Directly restore snapshot with `parameter_group_name` set ([#6200](https://github.com/terraform-providers/terraform-provider-aws/issues/6200)) -* resource/aws_dx_connection: Add `jumbo_frame_capable` attribute ([#6143](https://github.com/terraform-providers/terraform-provider-aws/issues/6143)) -* resource/aws_dynamodb_table: Prevent error `UnknownOperationException: Tagging is not currently supported in DynamoDB Local` ([#6149](https://github.com/terraform-providers/terraform-provider-aws/issues/6149)) -* resource/aws_lb_listener: Allow `default_action` `order` to be based on Terraform configuration ordering ([#6124](https://github.com/terraform-providers/terraform-provider-aws/issues/6124)) -* resource/aws_lb_listener_rule: Allow `action` `order` to be based on Terraform configuration ordering ([#6124](https://github.com/terraform-providers/terraform-provider-aws/issues/6124)) -* resource/aws_rds_cluster: Directly restore snapshot with `db_cluster_parameter_group_name` set ([#6200](https://github.com/terraform-providers/terraform-provider-aws/issues/6200)) - -BUG FIXES: - -* resource/aws_appsync_graphql_api: Properly handle updates by passing all parameters ([#6138](https://github.com/terraform-providers/terraform-provider-aws/issues/6138)) -* resource/aws_ecs_service: Properly handle `random` placement strategy ([#6176](https://github.com/terraform-providers/terraform-provider-aws/issues/6176)) -* resource/aws_lb_listener: Prevent unconfigured `default_action` `order` from showing difference ([#6119](https://github.com/terraform-providers/terraform-provider-aws/issues/6119)) -* resource/aws_lb_listener_rule: Prevent unconfigured `action` `order` from showing difference ([#6119](https://github.com/terraform-providers/terraform-provider-aws/issues/6119)) -* resource/aws_lb_listener_rule: Retry read for eventual consistency after resource creation ([#6154](https://github.com/terraform-providers/terraform-provider-aws/issues/6154)) - -## 1.40.0 (October 10, 2018) - -FEATURES: - -* **New Data Source:** `aws_launch_template` ([#6064](https://github.com/terraform-providers/terraform-provider-aws/issues/6064)) -* **New Data Source:** `aws_workspaces_bundle` ([#3243](https://github.com/terraform-providers/terraform-provider-aws/issues/3243)) -* **New Guide:** [`AWS IAM Policy Documents`](https://www.terraform.io/docs/providers/aws/guides/iam-policy-documents.html) ([#6016](https://github.com/terraform-providers/terraform-provider-aws/issues/6016)) -* **New Resource:** `aws_ebs_snapshot_copy` ([#3086](https://github.com/terraform-providers/terraform-provider-aws/issues/3086)) -* **New Resource:** `aws_pinpoint_adm_channel` ([#6038](https://github.com/terraform-providers/terraform-provider-aws/issues/6038)) -* **New Resource:** `aws_pinpoint_baidu_channel` ([#6111](https://github.com/terraform-providers/terraform-provider-aws/issues/6111)) -* **New Resource:** `aws_pinpoint_email_channel` ([#6110](https://github.com/terraform-providers/terraform-provider-aws/issues/6110)) -* **New Resource:** `aws_pinpoint_event_stream` ([#6069](https://github.com/terraform-providers/terraform-provider-aws/issues/6069)) -* **New Resource:** `aws_pinpoint_gcm_channel` ([#6089](https://github.com/terraform-providers/terraform-provider-aws/issues/6089)) -* **New Resource:** `aws_pinpoint_sms_channel` ([#6088](https://github.com/terraform-providers/terraform-provider-aws/issues/6088)) -* **New Resource:** `aws_redshift_snapshot_copy_grant` ([#5134](https://github.com/terraform-providers/terraform-provider-aws/issues/5134)) - -ENHANCEMENTS: - -* data-source/aws_iam_policy_document: Make `statement` argument optional ([#6052](https://github.com/terraform-providers/terraform-provider-aws/issues/6052)) -* data-source/aws_secretsmanager_secret: Add `policy` attribute ([#6091](https://github.com/terraform-providers/terraform-provider-aws/issues/6091)) -* data-source/aws_secretsmanager_secret_version: Add `secret_binary` attribute ([#6070](https://github.com/terraform-providers/terraform-provider-aws/issues/6070)) -* resource/aws_codebuild_project: Add `environment` `certificate` argument ([#6087](https://github.com/terraform-providers/terraform-provider-aws/issues/6087)) -* resource/aws_ecr_repository: Add configurable `delete` timeout ([#3910](https://github.com/terraform-providers/terraform-provider-aws/issues/3910)) -* resource/aws_elastic_beanstalk_environment: Add `platform_arn` argument (support custom platforms) ([#6093](https://github.com/terraform-providers/terraform-provider-aws/issues/6093)) -* resource/aws_lb_listener: Support Cognito and OIDC authentication ([#6094](https://github.com/terraform-providers/terraform-provider-aws/issues/6094)) -* resource/aws_lb_listener_rule: Support Cognito and OIDC authentication ([#6094](https://github.com/terraform-providers/terraform-provider-aws/issues/6094)) -* resource/aws_mq_broker: Add `instances` `ip_address` attribute ([#6103](https://github.com/terraform-providers/terraform-provider-aws/issues/6103)) -* resource/aws_rds_cluster: Support `engine_version` updates ([#5010](https://github.com/terraform-providers/terraform-provider-aws/issues/5010)) -* resource/aws_s3_bucket: Add replication `access_control_translation` and `account_id` arguments (support cross-account replication ownership) ([#3577](https://github.com/terraform-providers/terraform-provider-aws/issues/3577)) -* resource/aws_secretsmanager_secret_version: Add `secret_binary` argument ([#6070](https://github.com/terraform-providers/terraform-provider-aws/issues/6070)) -* resource/aws_security_group_rule: Support resource import ([#6027](https://github.com/terraform-providers/terraform-provider-aws/issues/6027)) - -BUG FIXES: - -* resource/aws_appautoscaling_policy: Properly handle negative values in step scaling metric intervals ([#3480](https://github.com/terraform-providers/terraform-provider-aws/issues/3480)) -* resource/aws_appsync_datasource: Properly pass all attributes during update ([#5814](https://github.com/terraform-providers/terraform-provider-aws/issues/5814)) -* resource/aws_batch_job_queue: Prevent error during read of non-existent Job Queue ([#6085](https://github.com/terraform-providers/terraform-provider-aws/issues/6085)) -* resource/aws_ecr_repository: Retry read for eventual consistency after resource creation ([#3910](https://github.com/terraform-providers/terraform-provider-aws/issues/3910)) -* resource/aws_ecs_service: Properly remove non-existent services from Terraform state ([#6039](https://github.com/terraform-providers/terraform-provider-aws/issues/6039)) -* resource/aws_iam_instance_profile: Retry for eventual consistency when adding a role ([#6079](https://github.com/terraform-providers/terraform-provider-aws/issues/6079)) -* resource/aws_lb_listener: Retry read for eventual consistency after resource creation ([#5167](https://github.com/terraform-providers/terraform-provider-aws/issues/5167)) - -## 1.39.0 (October 03, 2018) - -FEATURES: - -* **New Resource:** `aws_ec2_fleet` ([#5960](https://github.com/terraform-providers/terraform-provider-aws/issues/5960)) -* **New Resource:** `aws_pinpoint_app` ([#5956](https://github.com/terraform-providers/terraform-provider-aws/issues/5956)) - -ENHANCEMENTS: - -* resource/aws_cloudwatch_event_target: Support additional ECS target arguments ([#5982](https://github.com/terraform-providers/terraform-provider-aws/issues/5982)) -* resource/aws_codedeploy_app: Support resource import ([#6025](https://github.com/terraform-providers/terraform-provider-aws/issues/6025)) -* resource/aws_codedeploy_deployment_config: Support resource import ([#6025](https://github.com/terraform-providers/terraform-provider-aws/issues/6025)) -* resource/aws_codedeploy_deployment_group: Support resource import ([#6025](https://github.com/terraform-providers/terraform-provider-aws/issues/6025)) -* resource/aws_db_instance: Add `deletion_protection` argument ([#6011](https://github.com/terraform-providers/terraform-provider-aws/issues/6011)) -* resource/aws_dx_connection: Support 50Mbps, 100Mbps, 200Mbps, 300Mbps, 400Mbps, 500Mbps as valid `bandwidth` values ([#6057](https://github.com/terraform-providers/terraform-provider-aws/issues/6057)) -* resource/aws_dx_lag: Support 50Mbps, 100Mbps, 200Mbps, 300Mbps, 400Mbps, 500Mbps as valid `connections_bandwidth` values ([#6057](https://github.com/terraform-providers/terraform-provider-aws/issues/6057)) -* resource/aws_elasticsearch_domain: Add `node_to_node_encryption` argument ([#5997](https://github.com/terraform-providers/terraform-provider-aws/issues/5997)) -* resource/aws_rds_cluster: Add `deletion_protection` argument ([#6010](https://github.com/terraform-providers/terraform-provider-aws/issues/6010)) -* resource/aws_sns_topic_subscription: Add `delivery_policy` argument ([#3289](https://github.com/terraform-providers/terraform-provider-aws/issues/3289)) -* resource/aws_spot_fleet_request: Add `instance_pools_to_use_count` argument ([#5955](https://github.com/terraform-providers/terraform-provider-aws/issues/5955)) - -BUG FIXES: - -* resource/aws_api_gateway_deployment: Do not delete stage if it is in use by another deployment ([#3896](https://github.com/terraform-providers/terraform-provider-aws/issues/3896)) -* resource/aws_codedeploy_deployment_group: Include autoscaling groups when updating blue green config ([#5827](https://github.com/terraform-providers/terraform-provider-aws/issues/5827)) -* resource/aws_codedeploy_deployment_group: Properly read `autoscaling_groups` into Terraform state ([#6025](https://github.com/terraform-providers/terraform-provider-aws/issues/6025)) -* resource/aws_ecs_task_definition: Properly handle task scoped docker volume configurations ([#5907](https://github.com/terraform-providers/terraform-provider-aws/issues/5907)) -* resource/aws_network_interface_sg_attachment: Properly handle `InvalidNetworkInterfaceID.NotFound` errors ([#6048](https://github.com/terraform-providers/terraform-provider-aws/issues/6048)) -* resource/aws_rds_cluster: Properly handle `kms_key_id` when restoring from snapshot ([#6012](https://github.com/terraform-providers/terraform-provider-aws/issues/6012)) -* resource/aws_s3_bucket_object: Mark `version_id` as recomputed on `etag` updates ([#3861](https://github.com/terraform-providers/terraform-provider-aws/issues/3861)) -* resource/aws_security_group: Prevent `InvalidNetworkInterfaceID.NotFound` errors when deleting lingering network interfaces ([#6037](https://github.com/terraform-providers/terraform-provider-aws/issues/6037)) -* resource/aws_sns_topic_subscription: Properly read all attributes into Terraform state on reads ([#6023](https://github.com/terraform-providers/terraform-provider-aws/issues/6023)) -* resource/aws_sns_topic_subscription: Properly handle `filter_policy` removal ([#6023](https://github.com/terraform-providers/terraform-provider-aws/issues/6023)) -* resource/aws_subnet: Prevent `InvalidNetworkInterfaceID.NotFound` errors when deleting lingering network interfaces ([#6037](https://github.com/terraform-providers/terraform-provider-aws/issues/6037)) - -## 1.38.0 (September 26, 2018) - -FEATURES: - -* **New Data Source:** `aws_db_event_categories` ([#5514](https://github.com/terraform-providers/terraform-provider-aws/issues/5514)) - -ENHANCEMENTS: - -* data-source/aws_autoscaling_groups: Add `arns` attribute ([#5766](https://github.com/terraform-providers/terraform-provider-aws/issues/5766)) -* resource/aws_ami: Support resource import ([#5990](https://github.com/terraform-providers/terraform-provider-aws/issues/5990)) -* resource/aws_codebuild_project: Add `secondary_artifacts` and `secondary_sources` arguments ([#5939](https://github.com/terraform-providers/terraform-provider-aws/issues/5939)) -* resource/aws_codebuild_project: Add `arn` attribute ([#5973](https://github.com/terraform-providers/terraform-provider-aws/issues/5973)) -* resource/aws_launch_template: Support `credit_specification` configuration of T3 instance types ([#5922](https://github.com/terraform-providers/terraform-provider-aws/issues/5922)) -* resource/aws_launch_template: Allow `network_interface` `ipv6_address_count` configuration ([#5771](https://github.com/terraform-providers/terraform-provider-aws/issues/5771)) -* resource/aws_rds_cluster: Support `parallelquery` `engine_mode` argument ([#5980](https://github.com/terraform-providers/terraform-provider-aws/issues/5980)) - -BUG FIXES: - -* data-source/aws_ami: Prevent panics with AMIs in failed image state ([#5968](https://github.com/terraform-providers/terraform-provider-aws/issues/5968)) -* resource/aws_db_instance: Properly set `backup_retention_period = 0` with `snapshot_identifier` ([#5970](https://github.com/terraform-providers/terraform-provider-aws/issues/5970)) -* resource/aws_dms_replication_instance: Properly handle `engine_version` updates ([#5948](https://github.com/terraform-providers/terraform-provider-aws/issues/5948)) -* resource/aws_launch_template: Prevent `Auto Scaling only supports the 'one-time' Spot instance type with no duration.` error when using `instance_market_options` and AutoScaling Groups ([#5957](https://github.com/terraform-providers/terraform-provider-aws/issues/5957)) -* resource/aws_launch_template: Properly recreate existing resource when deleted ([#5967](https://github.com/terraform-providers/terraform-provider-aws/issues/5967)) -* resource/aws_launch_template: Continue accepting string `"true"` and `"false"` values for `ebs_optimized` argument ([#5995](https://github.com/terraform-providers/terraform-provider-aws/issues/5995)) -* resource/aws_load_balancer_policy: Properly handle resource when ELB is deleted ([#5972](https://github.com/terraform-providers/terraform-provider-aws/issues/5972)) -* resource/aws_rds_cluster_instance: Properly handle `publicly_accessible` updates ([#5991](https://github.com/terraform-providers/terraform-provider-aws/issues/5991)) -* resource/aws_security_group: Properly handle lingering ENIs from Lambda and similar services ([#4884](https://github.com/terraform-providers/terraform-provider-aws/issues/4884)) -* resource/aws_subnet: Properly handle lingering ENIs from Lambda and similar services ([#4884](https://github.com/terraform-providers/terraform-provider-aws/issues/4884)) - -## 1.37.0 (September 19, 2018) - -FEATURES: - -* **New Resource:** `aws_dx_bgp_peer` ([#5886](https://github.com/terraform-providers/terraform-provider-aws/issues/5886)) - -ENHANCEMENTS: - -* data-source/aws_ami_ids: Add `sort_ascending` argument ([#5912](https://github.com/terraform-providers/terraform-provider-aws/issues/5912)) -* resource/aws_iam_role_policy_attachment: Support resource import ([#5910](https://github.com/terraform-providers/terraform-provider-aws/issues/5910)) -* resource/aws_s3_bucket_inventory: Allow SSE-S3 encryption ([#5870](https://github.com/terraform-providers/terraform-provider-aws/issues/5870)) -* resource/aws_security_group: Add `prefix_list_ids` argument for `ingress` rules ([#5916](https://github.com/terraform-providers/terraform-provider-aws/issues/5916)) - -BUG FIXES: - -* resource/aws_config_config_rule: Prevent panic when specifying empty `scope` ([#5852](https://github.com/terraform-providers/terraform-provider-aws/issues/5852)) -* resource/aws_iam_policy: Ensure `description` is properly read into Terraform state during resource creation ([#5884](https://github.com/terraform-providers/terraform-provider-aws/issues/5884)) -* resource/aws_instance: Properly handle `credit_specifications` with T3 instance types ([#5805](https://github.com/terraform-providers/terraform-provider-aws/issues/5805)) -* resource/aws_launch_template: Fix handling of `network_interface` `ipv6_addresses` ([#5883](https://github.com/terraform-providers/terraform-provider-aws/issues/5883)) -* resource/aws_redshift_cluster: Properly disable logging when using `logging` nested argument ([#5895](https://github.com/terraform-providers/terraform-provider-aws/issues/5895)) -* resource/aws_s3_bucket: Prevent panics with various API read failures ([#5842](https://github.com/terraform-providers/terraform-provider-aws/issues/5842)) -* resource/aws_s3_bucket: Prevent `NoSuchBucket` error on deletion ([#5842](https://github.com/terraform-providers/terraform-provider-aws/issues/5842)) -* resource/aws_wafregional_byte_match_set: Properly read `byte_match_tuple` into Terraform state ([#5902](https://github.com/terraform-providers/terraform-provider-aws/issues/5902)) - -## 1.36.0 (September 13, 2018) - -FEATURES: - -* **New Resource:** `aws_cloudfront_public_key` ([#5737](https://github.com/terraform-providers/terraform-provider-aws/issues/5737)) - -ENHANCEMENTS: - -* data-source/aws_db_instance: Add `enabled_cloudwatch_logs_exports` attribute ([#5801](https://github.com/terraform-providers/terraform-provider-aws/issues/5801)) -* resource/aws_api_gateway_stage: Add `xray_tracing_enabled` argument ([#5817](https://github.com/terraform-providers/terraform-provider-aws/issues/5817)) -* resource/aws_cloudfront_distribution: Add `lambda_function_association` `include_body` argument ([#5681](https://github.com/terraform-providers/terraform-provider-aws/issues/5681)) -* resource/aws_db_instance: Add `domain` and `domain_iam_role_name` arguments (support for domain joining RDS instances) ([#5378](https://github.com/terraform-providers/terraform-provider-aws/issues/5378)) -* resource/aws_ecs_task_definition: Suppress `container_definition` differences for equivalent port and host mappings ([#5833](https://github.com/terraform-providers/terraform-provider-aws/issues/5833)) -* resource/aws_ecs_task_definition: Add docker volume configuration ([#5727](https://github.com/terraform-providers/terraform-provider-aws/issues/5727)) -* resource/aws_iam_user: Allow empty string (`""`) value for `permissions_boundary` argument ([#5859](https://github.com/terraform-providers/terraform-provider-aws/issues/5859)) -* resource/aws_iot_topic_rule: Add `firehose` `separator` argument ([#5734](https://github.com/terraform-providers/terraform-provider-aws/issues/5734)) -* resource/aws_launch_template: Allow `network_interface` `ipv4_address_count` configuration ([#5830](https://github.com/terraform-providers/terraform-provider-aws/issues/5830)) -* resource/aws_ssm_document: Add support for `Session` `document_type` ([#5850](https://github.com/terraform-providers/terraform-provider-aws/issues/5850)) - -BUG FIXES: - -* resource/aws_iam_policy: Ensure `description` is available as an attribute when empty ([#5815](https://github.com/terraform-providers/terraform-provider-aws/issues/5815)) -* resource/aws_iam_user: Remove extraneous `DeleteUserPermissionsBoundary` API call during deletion ([#5857](https://github.com/terraform-providers/terraform-provider-aws/issues/5857)) -* resource/aws_lambda_function: Retry on `InvalidParameterValueException` errors relating to KMS-backed environment variables ([#5849](https://github.com/terraform-providers/terraform-provider-aws/issues/5849)) -* resource/aws_launch_template: Ensure `ebs_optimized` argument accepts "unspecified" value ([#5627](https://github.com/terraform-providers/terraform-provider-aws/issues/5627)) - -## 1.35.0 (September 06, 2018) - -ENHANCEMENTS: - -* data-source/aws_eks_cluster: Add `platform_version` attribute ([#5797](https://github.com/terraform-providers/terraform-provider-aws/issues/5797)) -* resource/aws_eks_cluster: Add `platform_version` attribute ([#5797](https://github.com/terraform-providers/terraform-provider-aws/issues/5797)) -* resource/aws_lambda_function: Allow empty lists for `vpc_config` `security_group_ids` and `subnet_ids` arguments to unconfigure VPC ([#1341](https://github.com/terraform-providers/terraform-provider-aws/issues/1341)) -* resource/aws_iam_role: Allow empty string (`""`) value for `permissions_boundary` argument ([#5740](https://github.com/terraform-providers/terraform-provider-aws/issues/5740)) - -BUG FIXES: - -* resource/aws_ecr_repository: Use `RepositoryUri` instead of our building our own URI for the `repository_url` attribute (AWS China fix) ([#5748](https://github.com/terraform-providers/terraform-provider-aws/issues/5748)) -* resource/aws_lambda_function: Properly handle `vpc_config` removal ([#5798](https://github.com/terraform-providers/terraform-provider-aws/issues/5798)) -* resource/aws_redshift_cluster: Properly force new resource when updating `availability_zone` argument ([#5758](https://github.com/terraform-providers/terraform-provider-aws/issues/5758)) - -## 1.34.0 (August 30, 2018) - -NOTES: - -* provider: This is the first release tested against and built with Go 1.11, which required `go fmt` changes to the code. If you are building a custom version of this provider or running tests using the repository Make targets (e.g. `make build`) when using a previous version of Go, you will receive errors. You can use the underlying `go` commands (e.g. `go build`) to workaround the `go fmt` check in the Make targets until you are able to upgrade Go. - -ENHANCEMENTS: - -* provider: `NO_PROXY` environment variable can accept CIDR notation and port -* data-source/aws_ip_ranges: Add `ipv6_cidr_blocks` attribute ([#5675](https://github.com/terraform-providers/terraform-provider-aws/issues/5675)) -* resource/aws_codebuild_project: Add `artifacts` `encryption_disabled` argument ([#5678](https://github.com/terraform-providers/terraform-provider-aws/issues/5678)) -* resource/aws_route: Support route import ([#5687](https://github.com/terraform-providers/terraform-provider-aws/issues/5687)) - -BUG FIXES: - -* data-source/aws_rds_cluster: Prevent error setting `engine_mode` and `scaling_configuration` ([#5660](https://github.com/terraform-providers/terraform-provider-aws/issues/5660)) -* resource/aws_autoscaling_group: Retry creation for eventual consistency with launch template IAM instance profile ([#5633](https://github.com/terraform-providers/terraform-provider-aws/issues/5633)) -* resource/aws_dax_cluster: Properly recreate cluster when updating `server_side_encryption` ([#5664](https://github.com/terraform-providers/terraform-provider-aws/issues/5664)) -* resource/aws_db_instance: Prevent double apply when using `replicate_source_db` parameters that require `ModifyDBInstance` during resource creation ([#5672](https://github.com/terraform-providers/terraform-provider-aws/issues/5672)) -* resource/aws_db_instance: Prevent `pending-reboot` parameter group status on creation with `parameter_group_name` ([#5672](https://github.com/terraform-providers/terraform-provider-aws/issues/5672)) -* resource/aws_lambda_event_source_mapping: Prevent perpetual difference when using function name with `function_name` (argument accepts both name and ARN) ([#5454](https://github.com/terraform-providers/terraform-provider-aws/issues/5454)) -* resource/aws_launch_template: Prevent encrypted flag cannot be specified error with `block_device_mappings` `ebs` argument ([#5632](https://github.com/terraform-providers/terraform-provider-aws/issues/5632)) -* resource/aws_key_pair: Ensure `fingerprint` attribute is saved in Terraform state during creation ([#5732](https://github.com/terraform-providers/terraform-provider-aws/issues/5732)) -* resource/aws_ssm_association: Properly handle updates when multiple arguments are used ([#5537](https://github.com/terraform-providers/terraform-provider-aws/issues/5537)) -* resource/aws_ssm_document: Properly handle deletion of privately shared documents ([#5668](https://github.com/terraform-providers/terraform-provider-aws/issues/5668)) -* resource/aws_ssm_document: Properly update `permissions.account_ids` ([#5685](https://github.com/terraform-providers/terraform-provider-aws/issues/5685)) - -## 1.33.0 (August 22, 2018) - -FEATURES: - -* **New Data Source:** `aws_api_gateway_resource` ([#5629](https://github.com/terraform-providers/terraform-provider-aws/issues/5629)) - -ENHANCEMENTS: - -* data-source/aws_storagegateway_local_disk: Add `disk_node` argument ([#5595](https://github.com/terraform-providers/terraform-provider-aws/issues/5595)) -* resource/aws_api_gateway_base_path_mapping: Support resource import ([#5566](https://github.com/terraform-providers/terraform-provider-aws/issues/5566)) -* resource/aws_api_gateway_gateway_response: Support resource import ([#5567](https://github.com/terraform-providers/terraform-provider-aws/issues/5567)) -* resource/aws_api_gateway_integration: Support resource import ([#5568](https://github.com/terraform-providers/terraform-provider-aws/issues/5568)) -* resource/aws_api_gateway_integration_response: Support resource import ([#5569](https://github.com/terraform-providers/terraform-provider-aws/issues/5569)) -* resource/aws_api_gateway_method: Support resource import ([#5571](https://github.com/terraform-providers/terraform-provider-aws/issues/5571)) -* resource/aws_api_gateway_method_response: Support resource import ([#5570](https://github.com/terraform-providers/terraform-provider-aws/issues/5570)) -* resource/aws_api_gateway_model: Support resource import ([#5572](https://github.com/terraform-providers/terraform-provider-aws/issues/5572)) -* resource/aws_api_gateway_request_validator: Support resource import ([#5573](https://github.com/terraform-providers/terraform-provider-aws/issues/5573)) -* resource/aws_api_gateway_resource: Support resource import ([#5574](https://github.com/terraform-providers/terraform-provider-aws/issues/5574)) -* resource/aws_api_gateway_rest_api: Support resource import ([#5564](https://github.com/terraform-providers/terraform-provider-aws/issues/5564)) -* resource/aws_api_gateway_stage: Support resource import ([#5575](https://github.com/terraform-providers/terraform-provider-aws/issues/5575)) -* resource/aws_dax_cluster: Add `server_side_encryption` argument (support encryption at rest) ([#5508](https://github.com/terraform-providers/terraform-provider-aws/issues/5508)) -* resource/aws_ecs_service: Add retries for target group attachment ([#3535](https://github.com/terraform-providers/terraform-provider-aws/issues/3535)) -* resource/aws_lb_listener: Add support for 'redirect' and 'fixed-response' actions ([#5430](https://github.com/terraform-providers/terraform-provider-aws/issues/5430)) -* resource/aws_lb_listener_rule: Add support for 'redirect' and 'fixed-response' actions ([#5430](https://github.com/terraform-providers/terraform-provider-aws/issues/5430)) -* resource/aws_rds_cluster: Add `scaling_configuration` argument ([#5531](https://github.com/terraform-providers/terraform-provider-aws/issues/5531)) -* resource/aws_secretsmanager_secret: Support `ForceDeleteWithoutRecovery` (via `recovery_window_in_days = 0`) and secret recreation after immediate deletion ([#5583](https://github.com/terraform-providers/terraform-provider-aws/issues/5583)) - -BUG FIXES: - -* provider: Disable AWS SDK retries faster by default for `connection refused` errors ([#5614](https://github.com/terraform-providers/terraform-provider-aws/issues/5614)) -* resource/aws_api_gateway_integration: Properly read `integration_http_method` into Terraform state ([#5568](https://github.com/terraform-providers/terraform-provider-aws/issues/5568)) -* resource/aws_api_gateway_integration_response: Properly read `content_handling` into Terraform state ([#5569](https://github.com/terraform-providers/terraform-provider-aws/issues/5569)) -* resource/aws_api_gateway_integration_response: Properly read `response_templates` into Terraform state ([#5569](https://github.com/terraform-providers/terraform-provider-aws/issues/5569)) -* resource/aws_cloudfront_distribution: Import into `ordered_cache_behavior` instead of deprecated `cache_behavior` ([#5586](https://github.com/terraform-providers/terraform-provider-aws/issues/5586)) -* resource/aws_db_instance: Prevent error when using `snapshot_identifier` with `multi_az` enabled and sqlserver `engine` ([#5613](https://github.com/terraform-providers/terraform-provider-aws/issues/5613)) -* resource/aws_db_instance: Prevent double apply when using `snapshot_identifier` parameters that require `ModifyDBInstance` during resource creation ([#5613](https://github.com/terraform-providers/terraform-provider-aws/issues/5613)] / [[#5621](https://github.com/terraform-providers/terraform-provider-aws/issues/5621)) -* resource/aws_db_instance: Prevent `is already being deleted` error on deletion and wait for deletion completion ([#5624](https://github.com/terraform-providers/terraform-provider-aws/issues/5624)) -* resource/aws_ecs_task_definition: Treat `INACTIVE` task definitions as removed ([#5565](https://github.com/terraform-providers/terraform-provider-aws/issues/5565)) -* resource/aws_elasticache_cluster: Allow `availability_zone` to be specified with `replication_group_id` ([#5585](https://github.com/terraform-providers/terraform-provider-aws/issues/5585)) -* resource/aws_instance: Ignore change of `user_data` from omission to empty string ([#5467](https://github.com/terraform-providers/terraform-provider-aws/issues/5467)) -* resource/aws_service_discovery_public_dns_namespace: Prevent creation error with names longer than 34 characters ([#5610](https://github.com/terraform-providers/terraform-provider-aws/issues/5610)) -* resource/aws_waf_ipset: Properly handle updates and deletions over 1000 IP set descriptors ([#5588](https://github.com/terraform-providers/terraform-provider-aws/issues/5588)) -* resource/aws_wafregional_ipset: Properly handle updates and deletions over 1000 IP set descriptors ([#5588](https://github.com/terraform-providers/terraform-provider-aws/issues/5588)) - -## 1.32.0 (August 16, 2018) - -FEATURES: - -* **New Resource:** `aws_neptune_cluster_snapshot` ([#5492](https://github.com/terraform-providers/terraform-provider-aws/issues/5492)) -* **New Resource:** `aws_storagegateway_cached_iscsi_volume` ([#5476](https://github.com/terraform-providers/terraform-provider-aws/issues/5476)) - -ENHANCEMENTS: - -* data-source/aws_secretsmanager_secret_version: Add `arn` attribute ([#5488](https://github.com/terraform-providers/terraform-provider-aws/issues/5488)) -* data-source/aws_subnet: Add `arn` attribute ([#5486](https://github.com/terraform-providers/terraform-provider-aws/issues/5486)) -* resource/aws_cloudwatch_metric_alarm: Add `arn` attribute ([#5487](https://github.com/terraform-providers/terraform-provider-aws/issues/5487)) -* resource/aws_db_instance: Allow `alert`, `listener`, and `trace` for `enabled_cloudwatch_logs_exports` (e.g. Oracle specific log exports) ([#5494](https://github.com/terraform-providers/terraform-provider-aws/issues/5494)) -* resource/aws_emr_cluster: Support `st1` type EBS volumes ([#5534](https://github.com/terraform-providers/terraform-provider-aws/issues/5534)) -* resource/aws_neptune_event_subscription: Support resource import ([#5491](https://github.com/terraform-providers/terraform-provider-aws/issues/5491)) -* resource/aws_rds_cluster: Add `engine_mode` argument (support RDS Aurora Serverless) ([#5507](https://github.com/terraform-providers/terraform-provider-aws/issues/5507)) -* resource/aws_rds_cluster: Allow `aurora` (MySQL 5.6) `engine_type` to enable Performance Insights ([#5468](https://github.com/terraform-providers/terraform-provider-aws/issues/5468)) -* resource/aws_secretsmanager_secret_version: Add `arn` attribute ([#5488](https://github.com/terraform-providers/terraform-provider-aws/issues/5488)) -* resource/aws_subnet: Add `arn` attribute ([#5486](https://github.com/terraform-providers/terraform-provider-aws/issues/5486)) - -BUG FIXES: - -* storagegateway: Retry API calls on busy gateway proxy connection errors ([#5476](https://github.com/terraform-providers/terraform-provider-aws/issues/5476)) -* resource/aws_cloudtrail: Increase IAM retry threshold from 15 seconds to 1 minute ([#5499](https://github.com/terraform-providers/terraform-provider-aws/issues/5499)) -* resource/aws_cognito_user_pool: Properly pass all attributes during update (prevent perpetual flip-flop apply) ([#3458](https://github.com/terraform-providers/terraform-provider-aws/issues/3458)) -* resource/aws_cognito_user_pool_client: Properly pass all attributes during update (prevent perpetual flip-flop apply) ([#5478](https://github.com/terraform-providers/terraform-provider-aws/issues/5478)) -* resource/aws_db_instance: During S3 restore, lower retry threshold for IAM eventual consistency from 5 minutes to 2 minutes and retry on additional error ([#5536](https://github.com/terraform-providers/terraform-provider-aws/issues/5536)) -* resource/aws_dynamodb_table: Allow simultaneous region deletion retry of 5 minutes to better handle global table deletions ([#5518](https://github.com/terraform-providers/terraform-provider-aws/issues/5518)) -* resource/aws_glue_crawler: Additional IAM eventual consistency retry logic for create and update ([#5502](https://github.com/terraform-providers/terraform-provider-aws/issues/5502)) -* resource/aws_iam_role: Remove extraneous `DeleteRolePermissionsBoundary` API call when deleting IAM role ([#5544](https://github.com/terraform-providers/terraform-provider-aws/issues/5544)) -* resource/aws_kinesis_firehose_delivery_stream: Retry on additional IAM eventual consistency error with ElasticSearch destinations ([#5541](https://github.com/terraform-providers/terraform-provider-aws/issues/5541)) -* resource/aws_storagegateway_cache: Prevent resource recreation due to disk identifier changes after creation ([#5476](https://github.com/terraform-providers/terraform-provider-aws/issues/5476)) - -## 1.31.0 (August 09, 2018) - -FEATURES: - -* **New Data Source:** `aws_db_cluster_snapshot` ([#4526](https://github.com/terraform-providers/terraform-provider-aws/issues/4526)) -* **New Resource:** `aws_db_cluster_snapshot` ([#4526](https://github.com/terraform-providers/terraform-provider-aws/issues/4526)) -* **New Resource:** `aws_neptune_event_subscription` ([#5480](https://github.com/terraform-providers/terraform-provider-aws/issues/5480)) -* **New Resource:** `aws_storagegateway_cache` ([#5282](https://github.com/terraform-providers/terraform-provider-aws/issues/5282)) -* **New Resource:** `aws_storagegateway_smb_file_share` ([#5276](https://github.com/terraform-providers/terraform-provider-aws/issues/5276)) - -ENHANCEMENTS: - -* provider: Allow provider configuration AssumeRoleARN and sts:GetCallerIdentity credential validation call to shortcut account ID and partition lookup ([#5177](https://github.com/terraform-providers/terraform-provider-aws/issues/5177)) -* provider: Improved output for multiple error handler ([#5442](https://github.com/terraform-providers/terraform-provider-aws/issues/5442)) -* data-source/aws_instance: Add `arn` attribute ([#5432](https://github.com/terraform-providers/terraform-provider-aws/issues/5432)) -* resource/aws_elasticsearch_domain: Support `ES_APPLICATION_LOGS` `log_type` in plan-time validation ([#5474](https://github.com/terraform-providers/terraform-provider-aws/issues/5474)) -* resource/aws_instance: Add `arn` attribute ([#5432](https://github.com/terraform-providers/terraform-provider-aws/issues/5432)) -* resource/aws_storagegateway_gateway: Add `smb_active_directory_settings` and `smb_guest_password` arguments ([#5269](https://github.com/terraform-providers/terraform-provider-aws/issues/5269)) - -BUG FIXES: - -* provider: Prefer `USERPROFILE` over `HOMEPATH` for home directory expansion on Windows ([#5443](https://github.com/terraform-providers/terraform-provider-aws/issues/5443)) -* resource/aws_ami_copy: Prevent `ena_support` attribute incorrectly reporting force new resource ([#5433](https://github.com/terraform-providers/terraform-provider-aws/issues/5433)) -* resource/aws_ami_from_instance: Prevent `ena_support` attribute incorrectly reporting force new resource ([#5433](https://github.com/terraform-providers/terraform-provider-aws/issues/5433)) -* resource/aws_elasticsearch_domain: Prevent crash when missing `AutomatedSnapshotStartHour` in API response ([#5451](https://github.com/terraform-providers/terraform-provider-aws/issues/5451)) -* resource/aws_elasticsearch_domain: Suppress plan differences for `dedicated_master_count` and `dedicated_master_type` when `dedicated_master_enabled` is disabled ([#5423](https://github.com/terraform-providers/terraform-provider-aws/issues/5423)) -* resource/aws_rds_cluster: Prevent error when restoring cluster from snapshot with tagging enabled ([#5479](https://github.com/terraform-providers/terraform-provider-aws/issues/5479)) -* resource/aws_ssm_maintenance_window: Properly recreate resource when deleted outside Terraform ([#5416](https://github.com/terraform-providers/terraform-provider-aws/issues/5416)) -* resource/aws_ssm_patch_baseline: Properly recreate resource when deleted outside Terraform ([#5438](https://github.com/terraform-providers/terraform-provider-aws/issues/5438)) -* resource/aws_vpn_gateway: Allow legacy `amazon_side_asn` in plan-time validation (ASNs 10124 and 17493) ([#5441](https://github.com/terraform-providers/terraform-provider-aws/issues/5441)) - -## 1.30.0 (August 02, 2018) - -FEATURES: - -* **New Data Source:** `aws_storagegateway_local_disk` ([#5279](https://github.com/terraform-providers/terraform-provider-aws/issues/5279)) -* **New Resource:** `aws_macie_member_account_association` ([#5283](https://github.com/terraform-providers/terraform-provider-aws/issues/5283)) -* **New Resource:** `aws_neptune_cluster_instance` ([#5376](https://github.com/terraform-providers/terraform-provider-aws/issues/5376)) -* **New Resource:** `aws_storagegateway_nfs_file_share` ([#5255](https://github.com/terraform-providers/terraform-provider-aws/issues/5255)) -* **New Resource:** `aws_storagegateway_upload_buffer` ([#5284](https://github.com/terraform-providers/terraform-provider-aws/issues/5284)) -* **New Resource:** `aws_storagegateway_working_storage` ([#5285](https://github.com/terraform-providers/terraform-provider-aws/issues/5285)) - -ENHANCEMENTS: - -* data-source/aws_rds_cluster: Add `arn` attribute ([#5221](https://github.com/terraform-providers/terraform-provider-aws/issues/5221)) -* resource/aws_ami: Add `ena_support` argument ([#5395](https://github.com/terraform-providers/terraform-provider-aws/issues/5395)) -* resource/aws_api_gateway_domain_name: Support resource import ([#5368](https://github.com/terraform-providers/terraform-provider-aws/issues/5368)) -* resource/aws_efs_file_system: Add `provisioned_throughput_in_mibps` and `throughput_mode` arguments ([#5210](https://github.com/terraform-providers/terraform-provider-aws/issues/5210)) -* resource/aws_elasticsearch_domain: Add `cognito_options` arguments (support Cognito authentication) ([#5346](https://github.com/terraform-providers/terraform-provider-aws/issues/5346)) -* resource/aws_glue_crawler: Add `dynamodb_target` argument ([#5152](https://github.com/terraform-providers/terraform-provider-aws/issues/5152)) -* resource/aws_iam_role: Add `permissions_boundary` argument ([#5184](https://github.com/terraform-providers/terraform-provider-aws/issues/5184)) -* resource/aws_iam_user: Add `permissions_boundary` argument ([#5183](https://github.com/terraform-providers/terraform-provider-aws/issues/5183)) -* resource/aws_neptune_cluster: Support resource import ([#5227](https://github.com/terraform-providers/terraform-provider-aws/issues/5227)) -* resource/aws_rds_cluster: Add `arn` attribute ([#5221](https://github.com/terraform-providers/terraform-provider-aws/issues/5221)) -* resource/aws_ssm_patch_baseline: Add `AMAZON_LINUX_2` and `SUSE` to `operating_system` plan time validation ([#5371](https://github.com/terraform-providers/terraform-provider-aws/issues/5371)) - -BUG FIXES: - -* resource/aws_codebuild_project: Handle additional IAM retry condition during update ([#5238](https://github.com/terraform-providers/terraform-provider-aws/issues/5238)) -* resource/aws_codebuild_project: Remove extraneous UpdateProject API call after CreateProject API call ([#5238](https://github.com/terraform-providers/terraform-provider-aws/issues/5238)) -* resource/aws_db_instance: Prevent error when restoring database from snapshot with tagging enabled ([#5370](https://github.com/terraform-providers/terraform-provider-aws/issues/5370)) -* resource/aws_db_option_group: Prevent error when creating options with new IAM role ([#5389](https://github.com/terraform-providers/terraform-provider-aws/issues/5389)) -* resource/aws_eip: Properly handle if multiple EIPs are returned during API read ([#5331](https://github.com/terraform-providers/terraform-provider-aws/issues/5331)) -* resource/aws_emr_cluster: Add `configurations_json` argument (handles drift detection as compared to `configurations` argument) ([#5191](https://github.com/terraform-providers/terraform-provider-aws/issues/5191)) -* resource/aws_emr_cluster: Ensure `keep_job_flow_alive_when_no_step = false` automatically terminates cluster ([#5415](https://github.com/terraform-providers/terraform-provider-aws/issues/5415)) -* resource/aws_lambda_event_source_mapping: Properly read `enabled` into Terraform state ([#5292](https://github.com/terraform-providers/terraform-provider-aws/issues/5292)) -* resource/aws_launch_template: Exclude `network_interfaces` `associate_public_ip_address` when conflicting `network_interface_id` is set ([#5314](https://github.com/terraform-providers/terraform-provider-aws/issues/5314)) -* resource/aws_launch_template: Set `latest_version` as re-computed on updates (prevent need for double apply) ([#5250](https://github.com/terraform-providers/terraform-provider-aws/issues/5250)) -* resource/aws_lb_listener: Prevent crash from new `fixed-response` and `redirect` actions ([#5367](https://github.com/terraform-providers/terraform-provider-aws/issues/5367)) -* resource/aws_lb_listener_rule: Prevent crash from new `fixed-response` and `redirect` actions ([#5367](https://github.com/terraform-providers/terraform-provider-aws/issues/5367)) -* resource/aws_vpn_gateway: Allow legacy `amazon_side_asn` in plan-time validation (ASNs 7224 and 9059) ([#5291](https://github.com/terraform-providers/terraform-provider-aws/issues/5291)) -* resource/aws_waf_web_acl: Properly read `rules` into Terraform state ([#5342](https://github.com/terraform-providers/terraform-provider-aws/issues/5342)) -* resource/aws_waf_web_acl: Properly update `rules` ([#5380](https://github.com/terraform-providers/terraform-provider-aws/issues/5380)) -* resource/aws_wafregional_rate_based_rule: Fix `rate_limit` updates ([#5356](https://github.com/terraform-providers/terraform-provider-aws/issues/5356)) -* resource/aws_wafregional_web_acl: Properly read `rules` into Terraform state ([#5342](https://github.com/terraform-providers/terraform-provider-aws/issues/5342)) - -## 1.29.0 (July 26, 2018) - -NOTES: - -* data-source/aws_kms_secret: This data source has been deprecated and will be removed in the next major version. This is required to support the upcoming Terraform 0.12. A new `aws_kms_secrets` data source is available that allows for the same multiple KMS secret decryption functionality, but requires different attribute references. Full migration information is available in the [AWS Provider Version 2 Upgrade Guide](https://www.terraform.io/docs/providers/aws/guides/version-2-upgrade.html#data-source-aws_kms_secret). - -FEATURES: - -* **New Data Source:** `aws_kms_secrets` ([#5195](https://github.com/terraform-providers/terraform-provider-aws/issues/5195)) -* **New Data Source:** `aws_network_interfaces` ([#5324](https://github.com/terraform-providers/terraform-provider-aws/issues/5324)) -* **New Guide:** [`AWS Provider Version 2 Upgrade`](https://www.terraform.io/docs/providers/aws/guides/version-2-upgrade.html) ([#5195](https://github.com/terraform-providers/terraform-provider-aws/issues/5195)) - -ENHANCEMENTS: - -* data-source/aws_iam_role: Add `permissions_boundary` attribute ([#5186](https://github.com/terraform-providers/terraform-provider-aws/issues/5186)) -* data-source/aws_vpc: Add `arn` attribute ([#5300](https://github.com/terraform-providers/terraform-provider-aws/issues/5300)) -* resource/aws_default_vpc: Add `arn` attribute ([#5300](https://github.com/terraform-providers/terraform-provider-aws/issues/5300)) -* resource/aws_instance: Add `cpu_core_count` and `cpu_threads_per_core` arguments ([#5159](https://github.com/terraform-providers/terraform-provider-aws/issues/5159)) -* resource/aws_lambda_permission: Add `event_source_token` argument (support Alexa Skills) ([#5264](https://github.com/terraform-providers/terraform-provider-aws/issues/5264)) -* resource/aws_launch_template: Add `arn` attribute ([#5306](https://github.com/terraform-providers/terraform-provider-aws/issues/5306)) -* resource/aws_secretsmanager_secret: Add `policy` argument ([#5290](https://github.com/terraform-providers/terraform-provider-aws/issues/5290)) -* resource/aws_vpc: Add `arn` attribute ([#5300](https://github.com/terraform-providers/terraform-provider-aws/issues/5300)) -* resource/aws_waf_web_acl: Support resource import ([#5337](https://github.com/terraform-providers/terraform-provider-aws/issues/5337)) - -BUG FIXES: - -* data-source/aws_vpc_endpoint_service: Perform client side filtering to workaround server side filtering issues in AWS China and AWS GovCloud (US) ([#4592](https://github.com/terraform-providers/terraform-provider-aws/issues/4592)) -* resource/aws_kinesis_firehose_delivery_stream: Force new resource for `kinesis_source_configuration` argument changes ([#5332](https://github.com/terraform-providers/terraform-provider-aws/issues/5332)) -* resource/aws_route53_record: Prevent DomainLabelEmpty errors when expanding record names with trailing period ([#5312](https://github.com/terraform-providers/terraform-provider-aws/issues/5312)) -* resource/aws_ses_identity_notification_topic: Prevent panic when API returns no attributes ([#5327](https://github.com/terraform-providers/terraform-provider-aws/issues/5327)) -* resource/aws_ssm_parameter: Reduce DescribeParameters API calls by switching filtering logic ([#5325](https://github.com/terraform-providers/terraform-provider-aws/issues/5325)) - -## 1.28.0 (July 18, 2018) - -FEATURES: - -* **New Resource:** `aws_macie_s3_bucket_association` ([#5201](https://github.com/terraform-providers/terraform-provider-aws/issues/5201)) -* **New Resource:** `aws_neptune_cluster` ([#5050](https://github.com/terraform-providers/terraform-provider-aws/issues/5050)) -* **New Resource:** `aws_storagegateway_gateway` ([#5208](https://github.com/terraform-providers/terraform-provider-aws/issues/5208)) - -ENHANCEMENTS: - -* data-source/aws_iam_user: Add `permissions_boundary` attribute ([#5187](https://github.com/terraform-providers/terraform-provider-aws/issues/5187)) -* resource/aws_api_gateway_integration: Add `timeout_milliseconds` argument ([#5199](https://github.com/terraform-providers/terraform-provider-aws/issues/5199)) -* resource/aws_cloudwatch_log_group: Allow `tags` handling in AWS GovCloud (US) and AWS China ([#5175](https://github.com/terraform-providers/terraform-provider-aws/issues/5175)) -* resource/aws_codebuild_project: Add `report_build_status` argument under `source` (support report build status for GitHub source type) ([#5156](https://github.com/terraform-providers/terraform-provider-aws/issues/5156)) -* resource/aws_launch_template: Ignore `credit_specification` when not using T2 `instance_type` ([#5190](https://github.com/terraform-providers/terraform-provider-aws/issues/5190)) -* resource/aws_rds_cluster_instance: Add `arn` attribute ([#5220](https://github.com/terraform-providers/terraform-provider-aws/issues/5220)) -* resource/aws_route: Print more useful error message when missing valid target type ([#5198](https://github.com/terraform-providers/terraform-provider-aws/issues/5198)) -* resource/aws_vpc_endpoint: Add configurable timeouts ([#3418](https://github.com/terraform-providers/terraform-provider-aws/issues/3418)) -* resource/aws_vpc_endpoint_subnet_association: Add configurable timeouts ([#3418](https://github.com/terraform-providers/terraform-provider-aws/issues/3418)) - -BUG FIXES: - -* resource/aws_glue_crawler: Prevent error when deleted outside Terraform ([#5158](https://github.com/terraform-providers/terraform-provider-aws/issues/5158)) -* resource/aws_vpc_endpoint_subnet_association: Add mutex to prevent errors with concurrent `ModifyVpcEndpoint` calls ([#3418](https://github.com/terraform-providers/terraform-provider-aws/issues/3418)) - -## 1.27.0 (July 11, 2018) - -NOTES: - -* resource/aws_codebuild_project: The `service_role` argument is now required to match the API behavior and provide plan time validation. Additional details from AWS Support can be found in: https://github.com/terraform-providers/terraform-provider-aws/pull/4826 -* resource/aws_wafregional_byte_match_set: The `byte_match_tuple` argument name has been deprecated in preference of a new `byte_match_tuples` argument name, for consistency with the `aws_waf_byte_match_set` resource to reduce any confusion working between the two resources and to denote its multiple value support. Its behavior is exactly the same as the old argument. Simply changing the argument name (adding the `s`) to configurations should upgrade without other changes. - -FEATURES: - -* **New Resource:** `aws_appsync_api_key` ([#3827](https://github.com/terraform-providers/terraform-provider-aws/issues/3827)) -* **New Resource:** `aws_swf_domain` ([#2803](https://github.com/terraform-providers/terraform-provider-aws/issues/2803)) - -ENHANCEMENTS: - -* data-source/aws_region: Add `description` attribute ([#5077](https://github.com/terraform-providers/terraform-provider-aws/issues/5077)) -* data-source/aws_vpc: Add `cidr_block_associations` attribute ([#5098](https://github.com/terraform-providers/terraform-provider-aws/issues/5098)) -* resource/aws_cloudwatch_metric_alarm: Add `datapoints_to_alarm` and `evaluation_period` plan time validation ([#5095](https://github.com/terraform-providers/terraform-provider-aws/issues/5095)) -* resource/aws_db_parameter_group: Clarify naming validation error messages ([#5090](https://github.com/terraform-providers/terraform-provider-aws/issues/5090)) -* resource/aws_glue_connection: Add `physical_connection_requirements` argument `availability_zone` (currently required by the API) ([#5039](https://github.com/terraform-providers/terraform-provider-aws/issues/5039)) -* resource/aws_instance: Ignore `credit_specifications` when not using T2 `instance_type` ([#5114](https://github.com/terraform-providers/terraform-provider-aws/issues/5114)) -* resource/aws_instance: Allow AWS GovCloud (US) to perform tagging on creation ([#5106](https://github.com/terraform-providers/terraform-provider-aws/issues/5106)) -* resource/aws_lambda_function: Support `dotnetcore2.1` in `runtime` validation ([#5150](https://github.com/terraform-providers/terraform-provider-aws/issues/5150)) -* resource/aws_route_table: Ignore propagated routes during resource import ([#5100](https://github.com/terraform-providers/terraform-provider-aws/issues/5100)) -* resource/aws_security_group: Authorize and revoke only changed individual `ingress`/`egress` rules despite their configuration grouping (e.g. replacing an individual element in a multiple element `cidr_blocks` list) ([#4726](https://github.com/terraform-providers/terraform-provider-aws/issues/4726)) -* resource/aws_ses_receipt_rule: Add plan time validation for `s3_action` argument `position` ([#5092](https://github.com/terraform-providers/terraform-provider-aws/issues/5092)) -* resource/aws_vpc_ipv4_cidr_block_association: Support resource import ([#5069](https://github.com/terraform-providers/terraform-provider-aws/issues/5069)) -* resource/aws_waf_web_acl: Add `rules` `override_action` argument and support `GROUP` type ([#5053](https://github.com/terraform-providers/terraform-provider-aws/issues/5053)) -* resource/aws_wafregional_web_acl: Add `rules` `override_action` argument and support `GROUP` type ([#5053](https://github.com/terraform-providers/terraform-provider-aws/issues/5053)) - -BUG FIXES: - -* resource/aws_codebuild_project: Prevent panic when empty `vpc_config` block is configured ([#5070](https://github.com/terraform-providers/terraform-provider-aws/issues/5070)) -* resource/aws_codebuild_project: Mark `service_role` as required ([#4826](https://github.com/terraform-providers/terraform-provider-aws/issues/4826)) -* resource/aws_glue_catalog_database: Properly return error when missing colon during import ([#5123](https://github.com/terraform-providers/terraform-provider-aws/issues/5123)) -* resource/aws_glue_catalog_database: Prevent error when deleted outside Terraform ([#5141](https://github.com/terraform-providers/terraform-provider-aws/issues/5141)) -* resource/aws_instance: Allow AWS China to perform volume tagging post-creation on first apply ([#5106](https://github.com/terraform-providers/terraform-provider-aws/issues/5106)) -* resource/aws_kms_grant: Properly return error when listing KMS grants ([#5063](https://github.com/terraform-providers/terraform-provider-aws/issues/5063)) -* resource/aws_rds_cluster_instance: Support `configuring-log-exports` status ([#5124](https://github.com/terraform-providers/terraform-provider-aws/issues/5124)) -* resource/aws_s3_bucket: Prevent extraneous ACL update during resource creation ([#5107](https://github.com/terraform-providers/terraform-provider-aws/issues/5107)) -* resource/aws_wafregional_byte_match_set: Deprecate `byte_match_tuple` argument for `byte_match_tuples` ([#5043](https://github.com/terraform-providers/terraform-provider-aws/issues/5043)) - -## 1.26.0 (July 04, 2018) - -FEATURES: - -* **New Data Source:** `aws_launch_configuration` ([#3624](https://github.com/terraform-providers/terraform-provider-aws/issues/3624)) -* **New Data Source:** `aws_pricing_product` ([#5057](https://github.com/terraform-providers/terraform-provider-aws/issues/5057)) -* **New Resource:** `aws_s3_bucket_inventory` ([#5019](https://github.com/terraform-providers/terraform-provider-aws/issues/5019)) -* **New Resource:** `aws_vpc_ipv4_cidr_block_association` ([#3723](https://github.com/terraform-providers/terraform-provider-aws/issues/3723)) - -ENHANCEMENTS: - -* data-source/aws_elasticache_replication_group: Add `member_clusters` attribute ([#5056](https://github.com/terraform-providers/terraform-provider-aws/issues/5056)) -* data-source/aws_instances: Add `instance_state_names` argument (support non-`running` instances) ([#4950](https://github.com/terraform-providers/terraform-provider-aws/issues/4950)) -* data-source/aws_route_tables: Add `filter` argument ([#5035](https://github.com/terraform-providers/terraform-provider-aws/issues/5035)) -* data-source/aws_subnet_ids: Add `filter` argument ([#5038](https://github.com/terraform-providers/terraform-provider-aws/issues/5038)) -* resource/aws_eip_association: Support resource import ([#5006](https://github.com/terraform-providers/terraform-provider-aws/issues/5006)) -* resource/aws_elasticache_replication_group: Add `member_clusters` attribute ([#5056](https://github.com/terraform-providers/terraform-provider-aws/issues/5056)) -* resource/aws_lambda_alias: Add `routing_config` argument (support traffic shifting) ([#3316](https://github.com/terraform-providers/terraform-provider-aws/issues/3316)) -* resource/aws_lambda_event_source_mapping: Make `starting_position` optional and allow `batch_size` to support default of 10 for SQS ([#5024](https://github.com/terraform-providers/terraform-provider-aws/issues/5024)) -* resource/aws_network_acl_rule: Add plan time conflict validation with `cidr_block` and `ipv6_cidr_block` ([#3951](https://github.com/terraform-providers/terraform-provider-aws/issues/3951)) -* resource/aws_spot_fleet_request: Add `fleet_type` argument ([#5032](https://github.com/terraform-providers/terraform-provider-aws/issues/5032)) -* resource/aws_ssm_document: Add `tags` argument (support tagging) ([#5020](https://github.com/terraform-providers/terraform-provider-aws/issues/5020)) - -BUG FIXES: - -* resource/aws_codebuild_project: Prevent panic with missing environment variable type ([#5052](https://github.com/terraform-providers/terraform-provider-aws/issues/5052)) -* resource/aws_kms_alias: Fix perpetual plan when `target_key_id` is ARN ([#4010](https://github.com/terraform-providers/terraform-provider-aws/issues/4010)) - -## 1.25.0 (June 27, 2018) - -NOTES: - -* resource/aws_instance: Starting around June 21, 2018, the EC2 API began responding with an empty string value for user data for some instances instead of a completely empty response. In Terraform, it would show as a difference of `user_data: "da39a3ee5e6b4b0d3255bfef95601890afd80709" => "" (forces new resource)` if the `user_data` argument was not defined in the Terraform configuration for the resource. This release ignores that difference as equivalent. - -FEATURES: - -* **New Data Source:** `aws_codecommit_repository` ([#4934](https://github.com/terraform-providers/terraform-provider-aws/issues/4934)) -* **New Data Source:** `aws_dx_gateway` ([#4988](https://github.com/terraform-providers/terraform-provider-aws/issues/4988)) -* **New Data Source:** `aws_network_acls` ([#4966](https://github.com/terraform-providers/terraform-provider-aws/issues/4966)) -* **New Data Source:** `aws_route_tables` ([#4841](https://github.com/terraform-providers/terraform-provider-aws/issues/4841)) -* **New Data Source:** `aws_security_groups` ([#2947](https://github.com/terraform-providers/terraform-provider-aws/issues/2947)) -* **New Resource:** `aws_dx_hosted_private_virtual_interface` ([#3255](https://github.com/terraform-providers/terraform-provider-aws/issues/3255)) -* **New Resource:** `aws_dx_hosted_private_virtual_interface_accepter` ([#3255](https://github.com/terraform-providers/terraform-provider-aws/issues/3255)) -* **New Resource:** `aws_dx_hosted_public_virtual_interface` ([#3254](https://github.com/terraform-providers/terraform-provider-aws/issues/3254)) -* **New Resource:** `aws_dx_hosted_public_virtual_interface_accepter` ([#3254](https://github.com/terraform-providers/terraform-provider-aws/issues/3254)) -* **New Resource:** `aws_dx_private_virtual_interface` ([#3253](https://github.com/terraform-providers/terraform-provider-aws/issues/3253)) -* **New Resource:** `aws_dx_public_virtual_interface` ([#3252](https://github.com/terraform-providers/terraform-provider-aws/issues/3252)) -* **New Resource:** `aws_media_store_container_policy` ([#3507](https://github.com/terraform-providers/terraform-provider-aws/issues/3507)) - -ENHANCEMENTS: - -* provider: Support custom endpoint for `autoscaling` ([#4970](https://github.com/terraform-providers/terraform-provider-aws/issues/4970)) -* resource/aws_codebuild_project: Support `WINDOWS_CONTAINER` as valid environment type ([#4960](https://github.com/terraform-providers/terraform-provider-aws/issues/4960)) -* resource/aws_codebuild_project: Support resource import ([#4976](https://github.com/terraform-providers/terraform-provider-aws/issues/4976)) -* resource/aws_ecs_service: Add `scheduling_strategy` argument (support `DAEMON` scheduling strategy) ([#4825](https://github.com/terraform-providers/terraform-provider-aws/issues/4825)) -* resource/aws_iam_instance_profile: Add `create_date` attribute ([#4932](https://github.com/terraform-providers/terraform-provider-aws/issues/4932)) -* resource/aws_media_store_container: Support resource import ([#3501](https://github.com/terraform-providers/terraform-provider-aws/issues/3501)) -* resource/aws_network_acl: Add full mapping of protocol names to protocol numbers ([#4956](https://github.com/terraform-providers/terraform-provider-aws/issues/4956)) -* resource/aws_network_acl_rule: Add full mapping of protocol names to protocol numbers ([#4956](https://github.com/terraform-providers/terraform-provider-aws/issues/4956)) -* resource/aws_sqs_queue: Add .fifo suffix for FIFO queues using `name_prefix` ([#4929](https://github.com/terraform-providers/terraform-provider-aws/issues/4929)) -* resource/aws_vpc: Support update of `instance_tenancy` from `dedicated` to `default` ([#2514](https://github.com/terraform-providers/terraform-provider-aws/issues/2514)) -* resource/aws_waf_ipset: Support resource import ([#4979](https://github.com/terraform-providers/terraform-provider-aws/issues/4979)) -* resource/aws_wafregional_web_acl: Add rule `type` argument (support rate limited rules) ([#4307](https://github.com/terraform-providers/terraform-provider-aws/issues/4307)] / [[#4978](https://github.com/terraform-providers/terraform-provider-aws/issues/4978)) - -BUG FIXES: - -* data-source/aws_rds_cluster: Prevent panic with new CloudWatch logs support (`enabled_cloudwatch_logs_exports`) introduced in 1.23.0 ([#4927](https://github.com/terraform-providers/terraform-provider-aws/issues/4927)) -* resource/aws_codebuild_webhook: Prevent panic when webhook is missing during read ([#4917](https://github.com/terraform-providers/terraform-provider-aws/issues/4917)) -* resource/aws_db_instance: Properly raise any `ListTagsForResource` error instead of presenting a perpetual difference with `tags` ([#4943](https://github.com/terraform-providers/terraform-provider-aws/issues/4943)) -* resource/aws_instance: Prevent extraneous ModifyInstanceAttribute call for `disable_api_termination` on resource creation ([#4941](https://github.com/terraform-providers/terraform-provider-aws/issues/4941)) -* resource/aws_instance: Ignore empty string SHA (`da39a3ee5e6b4b0d3255bfef95601890afd80709`) `user_data` difference due to EC2 API response changes ([#4991](https://github.com/terraform-providers/terraform-provider-aws/issues/4991)) -* resource/aws_launch_template: Prevent error when using `valid_until` ([#4952](https://github.com/terraform-providers/terraform-provider-aws/issues/4952)) -* resource/aws_route: Properly force resource recreation when updating `route_table_id` ([#4946](https://github.com/terraform-providers/terraform-provider-aws/issues/4946)) -* resource/aws_route53_zone: Further prevent HostedZoneAlreadyExists with specified caller reference errors ([#4903](https://github.com/terraform-providers/terraform-provider-aws/issues/4903)) -* resource/aws_ses_receipt_rule: Prevent error with `s3_action` when `kms_key_arn` is not specified ([#4965](https://github.com/terraform-providers/terraform-provider-aws/issues/4965)) - -## 1.24.0 (June 21, 2018) - -FEATURES: - -* **New Data Source:** `aws_cloudformation_export` ([#2180](https://github.com/terraform-providers/terraform-provider-aws/issues/2180)) -* **New Data Source:** `aws_vpc_dhcp_options` ([#4878](https://github.com/terraform-providers/terraform-provider-aws/issues/4878)) -* **New Resource:** `aws_dx_gateway` ([#4896](https://github.com/terraform-providers/terraform-provider-aws/issues/4896)) -* **New Resource:** `aws_dx_gateway_association` ([#4896](https://github.com/terraform-providers/terraform-provider-aws/issues/4896)) -* **New Resource:** `aws_glue_crawler` ([#4484](https://github.com/terraform-providers/terraform-provider-aws/issues/4484)) -* **New Resource:** `aws_neptune_cluster_parameter_group` ([#4860](https://github.com/terraform-providers/terraform-provider-aws/issues/4860)) -* **New Resource:** `aws_neptune_subnet_group` ([#4782](https://github.com/terraform-providers/terraform-provider-aws/issues/4782)) - -ENHANCEMENTS: - -* resource/aws_api_gateway_rest_api: Support `PRIVATE` endpoint type ([#4888](https://github.com/terraform-providers/terraform-provider-aws/issues/4888)) -* resource/aws_codedeploy_app: Add `compute_platform` argument ([#4811](https://github.com/terraform-providers/terraform-provider-aws/issues/4811)) -* resource/aws_kinesis_firehose_delivery_stream: Support extended S3 destination `data_format_conversion_configuration` ([#4842](https://github.com/terraform-providers/terraform-provider-aws/issues/4842)) -* resource/aws_kms_grant: Support ARN for `key_id` argument (external CMKs) ([#4886](https://github.com/terraform-providers/terraform-provider-aws/issues/4886)) -* resource/aws_neptune_parameter_group: Add `tags` argument and `arn` attribute ([#4873](https://github.com/terraform-providers/terraform-provider-aws/issues/4873)) -* resource/aws_rds_cluster: Add `enabled_cloudwatch_logs_exports` argument ([#4875](https://github.com/terraform-providers/terraform-provider-aws/issues/4875)) - -BUG FIXES: - -* resource/aws_batch_job_definition: Force resource recreation on retry_strategy attempts updates ([#4854](https://github.com/terraform-providers/terraform-provider-aws/issues/4854)) -* resource/aws_cognito_user_pool_client: Prevent panic with updating `refresh_token_validity` ([#4868](https://github.com/terraform-providers/terraform-provider-aws/issues/4868)) -* resource/aws_instance: Prevent extraneous ModifyInstanceCreditSpecification call on resource creation ([#4898](https://github.com/terraform-providers/terraform-provider-aws/issues/4898)) -* resource/aws_s3_bucket: Properly detect `cors_rule` drift when it is deleted outside Terraform ([#4887](https://github.com/terraform-providers/terraform-provider-aws/issues/4887)) -* resource/aws_vpn_gateway_attachment: Fix error handling for missing VPN gateway ([#4895](https://github.com/terraform-providers/terraform-provider-aws/issues/4895)) - -## 1.23.0 (June 14, 2018) - -NOTES: - -* resource/aws_elasticache_cluster: The `availability_zones` argument has been deprecated in favor of a new `preferred_availability_zones` argument to allow specifying the same Availability Zone more than once in larger Memcached clusters that also need to specifically set Availability Zones. The argument is still optional and the API will continue to automatically choose Availability Zones for nodes if not specified. The new argument will also continue to match the APIs required behavior that the length of the list must be the same as `num_cache_nodes`. Migration will require recreating the resource or using the resource [lifecycle configuration](https://www.terraform.io/docs/configuration/resources.html#lifecycle) of `ignore_changes = ["availability_zones"]` to prevent recreation. See the resource documentation for additional details. - -FEATURES: - -* **New Data Source:** `aws_vpcs` ([#4736](https://github.com/terraform-providers/terraform-provider-aws/issues/4736)) -* **New Resource:** `aws_neptune_parameter_group` ([#4724](https://github.com/terraform-providers/terraform-provider-aws/issues/4724)) - -ENHANCEMENTS: - -* resource/aws_db_instance: Display input arguments when receiving InvalidParameterValue error on resource creation ([#4803](https://github.com/terraform-providers/terraform-provider-aws/issues/4803)) -* resource/aws_elasticache_cluster: Migrate from `availability_zones` TypeSet attribute to `preferred_availability_zones` TypeList attribute (allow duplicate Availability Zone elements) ([#4741](https://github.com/terraform-providers/terraform-provider-aws/issues/4741)) -* resource/aws_launch_template: Add `tags` argument (support tagging the resource itself) ([#4763](https://github.com/terraform-providers/terraform-provider-aws/issues/4763)) -* resource/aws_launch_template: Add plan time validation for tag_specifications `resource_type` ([#4765](https://github.com/terraform-providers/terraform-provider-aws/issues/4765)) -* resource/aws_waf_ipset: Add `arn` attribute ([#4784](https://github.com/terraform-providers/terraform-provider-aws/issues/4784)) -* resource/aws_wafregional_ipset: Add `arn` attribute ([#4816](https://github.com/terraform-providers/terraform-provider-aws/issues/4816)) - -BUG FIXES: - -* resource/aws_codebuild_webhook: Properly export `secret` (the CodeBuild API only provides its value during resource creation) ([#4775](https://github.com/terraform-providers/terraform-provider-aws/issues/4775)) -* resource/aws_codecommit_repository: Prevent error and trigger recreation when not found during read ([#4761](https://github.com/terraform-providers/terraform-provider-aws/issues/4761)) -* resource/aws_eks_cluster: Properly export `arn` attribute ([#4766](https://github.com/terraform-providers/terraform-provider-aws/issues/4766)] / [[#4767](https://github.com/terraform-providers/terraform-provider-aws/issues/4767)) -* resource/aws_elasticsearch_domain: Skip EBS options update/refresh if EBS is not enabled ([#4802](https://github.com/terraform-providers/terraform-provider-aws/issues/4802)) - -## 1.22.0 (June 05, 2018) - -FEATURES: - -* **New Data Source:** `aws_ecs_service` ([#3617](https://github.com/terraform-providers/terraform-provider-aws/issues/3617)) -* **New Data Source:** `aws_eks_cluster` ([#4749](https://github.com/terraform-providers/terraform-provider-aws/issues/4749)) -* **New Guide:** EKS Getting Started -* **New Resource:** `aws_config_aggregate_authorization` ([#4263](https://github.com/terraform-providers/terraform-provider-aws/issues/4263)) -* **New Resource:** `aws_config_configuration_aggregator` ([#4262](https://github.com/terraform-providers/terraform-provider-aws/issues/4262)) -* **New Resource:** `aws_eks_cluster` ([#4749](https://github.com/terraform-providers/terraform-provider-aws/issues/4749)) - -ENHANCEMENTS: - -* provider: Support custom endpoint for EFS ([#4716](https://github.com/terraform-providers/terraform-provider-aws/issues/4716)) -* resource/aws_api_gateway_method: Add `authorization_scopes` argument ([#4533](https://github.com/terraform-providers/terraform-provider-aws/issues/4533)) -* resource/aws_api_gateway_rest_api: Add `api_key_source` argument ([#4717](https://github.com/terraform-providers/terraform-provider-aws/issues/4717)) -* resource/aws_cloudfront_distribution: Allow create and update retries on InvalidViewerCertificate for eventual consistency with ACM/IAM services ([#4698](https://github.com/terraform-providers/terraform-provider-aws/issues/4698)) -* resource/aws_cognito_identity_pool: Add `arn` attribute ([#4719](https://github.com/terraform-providers/terraform-provider-aws/issues/4719)) -* resource/aws_cognito_user_pool: Add `endpoint` attribute ([#4718](https://github.com/terraform-providers/terraform-provider-aws/issues/4718)) - -BUG FIXES: - -* resource/aws_service_discovery_private_dns_namespace: Prevent creation error with names longer than 34 characters ([#4702](https://github.com/terraform-providers/terraform-provider-aws/issues/4702)) -* resource/aws_vpn_connection: Allow period in `tunnel[1-2]_preshared_key` validation ([#4731](https://github.com/terraform-providers/terraform-provider-aws/issues/4731)) - -## 1.21.0 (May 31, 2018) - -FEATURES: - -* **New Data Source:** `aws_route` ([#4529](https://github.com/terraform-providers/terraform-provider-aws/issues/4529)) -* **New Resource:** `aws_codebuild_webhook` ([#4473](https://github.com/terraform-providers/terraform-provider-aws/issues/4473)) -* **New Resource:** `aws_cognito_identity_provider` ([#3601](https://github.com/terraform-providers/terraform-provider-aws/issues/3601)) -* **New Resource:** `aws_cognito_resource_server` ([#4530](https://github.com/terraform-providers/terraform-provider-aws/issues/4530)) -* **New Resource:** `aws_glue_classifier` ([#4472](https://github.com/terraform-providers/terraform-provider-aws/issues/4472)) - -ENHANCEMENTS: - -* provider: Support custom endpoint for SSM ([#4670](https://github.com/terraform-providers/terraform-provider-aws/issues/4670)) -* resource/aws_codebuild_project: Add `badge_enabled` argument and `badge_url` attribute ([#3504](https://github.com/terraform-providers/terraform-provider-aws/issues/3504)) -* resource/aws_codebuild_project: Add `environment_variable` argument `type` (support parameter store environment variables) ([#2811](https://github.com/terraform-providers/terraform-provider-aws/issues/2811)] / [[#4021](https://github.com/terraform-providers/terraform-provider-aws/issues/4021)) -* resource/aws_codebuild_project: Add `source` argument `git_clone_depth` and `insecure_ssl` ([#3929](https://github.com/terraform-providers/terraform-provider-aws/issues/3929)) -* resource/aws_elasticache_replication_group: Support `number_cache_nodes` updates ([#4504](https://github.com/terraform-providers/terraform-provider-aws/issues/4504)) -* resource/aws_lb_target_group: Add `slow_start` argument ([#4661](https://github.com/terraform-providers/terraform-provider-aws/issues/4661)) -* resource/aws_redshift_cluster: Add `dns_name` attribute ([#4582](https://github.com/terraform-providers/terraform-provider-aws/issues/4582)) -* resource/aws_s3_bucket: Add `bucket_regional_domain_name` attribute ([#4556](https://github.com/terraform-providers/terraform-provider-aws/issues/4556)) - -BUG FIXES: - -* data-source/aws_lambda_function: Qualifiers explicitly set are now honoured ([#4654](https://github.com/terraform-providers/terraform-provider-aws/issues/4654)) -* resource/aws_batch_job_definition: Properly force new resource when updating timeout `attempt_duration_seconds` argument ([#4697](https://github.com/terraform-providers/terraform-provider-aws/issues/4697)) -* resource/aws_budgets_budget: Force new resource when updating `name` ([#4656](https://github.com/terraform-providers/terraform-provider-aws/issues/4656)) -* resource/aws_dms_endpoint: Additionally specify MongoDB connection info in the top-level API namespace to prevent issues connecting ([#4636](https://github.com/terraform-providers/terraform-provider-aws/issues/4636)) -* resource/aws_rds_cluster: Prevent additional retry error during S3 import for IAM/S3 eventual consistency ([#4683](https://github.com/terraform-providers/terraform-provider-aws/issues/4683)) -* resource/aws_sns_sms_preferences: Properly add SNS preferences to website docs ([#4694](https://github.com/terraform-providers/terraform-provider-aws/issues/4694)) - -## 1.20.0 (May 23, 2018) - -NOTES: - -* resource/aws_guardduty_member: Terraform will now try to properly detect if a member account has been invited based on its relationship status (`Disabled`/`Enabled`/`Invited`) and appropriately flag the new `invite` argument for update. You will want to set `invite = true` in your Terraform configuration if you previously handled the invitation process for a member, otherwise the resource will attempt to disassociate the member upon updating the provider to this version. - -FEATURES: - -* **New Data Source:** `aws_glue_script` ([#4481](https://github.com/terraform-providers/terraform-provider-aws/issues/4481)) -* **New Resource:** `aws_glue_trigger` ([#4464](https://github.com/terraform-providers/terraform-provider-aws/issues/4464)) - -ENHANCEMENTS: - -* resource/aws_api_gateway_domain_name: Add `endpoint_configuration` argument, `regional_certificate_arn` argument, `regional_certificate_name` argument, `regional_domain_name` attribute, and `regional_zone_id` attribute (support regional domain names) ([#2866](https://github.com/terraform-providers/terraform-provider-aws/issues/2866)) -* resource/aws_api_gateway_rest_api: Add `endpoint_configuration` argument (support regional endpoint type) ([#2866](https://github.com/terraform-providers/terraform-provider-aws/issues/2866)) -* resource/aws_appautoscaling_policy: Add retry logic for rate exceeded errors during read, update and delete ([#4594](https://github.com/terraform-providers/terraform-provider-aws/issues/4594)) -* resource/aws_ecs_service: Add `container_name` and `container_port` arguments for `service_registry` (support bridge and host network mode for service registry) ([#4623](https://github.com/terraform-providers/terraform-provider-aws/issues/4623)) -* resource/aws_emr_cluster: Add `additional_info` argument ([#4590](https://github.com/terraform-providers/terraform-provider-aws/issues/4590)) -* resource/aws_guardduty_member: Support member account invitation on creation ([#4357](https://github.com/terraform-providers/terraform-provider-aws/issues/4357)) -* resource/aws_guardduty_member: Support `invite` argument updates (invite or disassociate on update) ([#4604](https://github.com/terraform-providers/terraform-provider-aws/issues/4604)) -* resource/aws_ssm_patch_baseline: Add `approval_rule` `enable_non_security` argument ([#4546](https://github.com/terraform-providers/terraform-provider-aws/issues/4546)) - -BUG FIXES: - -* resource/aws_api_gateway_rest_api: Prevent error with `policy` containing special characters (e.g. forward slashes in CIDRs) ([#4606](https://github.com/terraform-providers/terraform-provider-aws/issues/4606)) -* resource/aws_cloudwatch_event_rule: Prevent multiple names on creation ([#4579](https://github.com/terraform-providers/terraform-provider-aws/issues/4579)) -* resource/aws_dynamodb_table: Prevent error with APIs that do not support point in time recovery (e.g. AWS China) ([#4573](https://github.com/terraform-providers/terraform-provider-aws/issues/4573)) -* resource/aws_glue_catalog_table: Prevent multiple potential panic scenarios ([#4621](https://github.com/terraform-providers/terraform-provider-aws/issues/4621)) -* resource/aws_kinesis_stream: Handle tag additions/removals of more than 10 tags ([#4574](https://github.com/terraform-providers/terraform-provider-aws/issues/4574)) -* resource/aws_kinesis_stream: Prevent perpetual `encryption_type` difference with APIs that do not support encryption (e.g. AWS China) ([#4575](https://github.com/terraform-providers/terraform-provider-aws/issues/4575)) -* resource/aws_s3_bucket: Prevent panic from CORS reading errors ([#4603](https://github.com/terraform-providers/terraform-provider-aws/issues/4603)) -* resource/aws_spot_fleet_request: Prevent empty `iam_instance_profile_arn` from overwriting `iam_instance_profile` ([#4591](https://github.com/terraform-providers/terraform-provider-aws/issues/4591)) - -## 1.19.0 (May 16, 2018) - -NOTES: - -* data-source/aws_iam_policy_document: Please note there is a behavior change in the rendering of `principal`/`not_principal` in the case of `type = "AWS"` and `identifiers = ["*"]`. This will now render as `Principal": {"AWS": "*"}` instead of `"Principal": "*"`. This change is required for IAM role trust policy support as well as differentiating between anonymous access versus AWS access in policies. To keep the old behavior of anonymous access, use `type = "*"` and `identifiers = ["*"]`, which will continue to render as `"Principal": "*"`. For additional information, see the [`aws_iam_policy_document` documentation](https://www.terraform.io/docs/providers/aws/d/iam_policy_document.html). - -FEATURES: - -* **New Data Source:** `aws_arn` ([#3996](https://github.com/terraform-providers/terraform-provider-aws/issues/3996)) -* **New Data Source:** `aws_lambda_invocation` ([#4222](https://github.com/terraform-providers/terraform-provider-aws/issues/4222)) -* **New Resource:** `aws_sns_sms_preferences` ([#3858](https://github.com/terraform-providers/terraform-provider-aws/issues/3858)) - -ENHANCEMENTS: - -* data-source/aws_iam_policy_document: Allow rendering of `"Principal": {"AWS": "*"}` (required for IAM role trust policies) ([#4248](https://github.com/terraform-providers/terraform-provider-aws/issues/4248)) -* resource/aws_api_gateway_rest_api: Add `execution_arn` attribute ([#3968](https://github.com/terraform-providers/terraform-provider-aws/issues/3968)) -* resource/aws_db_event_subscription: Add `name_prefix` argument ([#2754](https://github.com/terraform-providers/terraform-provider-aws/issues/2754)) -* resource/aws_dms_endpoint: Add `azuredb` for `engine_name` validation ([#4506](https://github.com/terraform-providers/terraform-provider-aws/issues/4506)) -* resource/aws_rds_cluster: Add `backtrack_window` argument and wait for updates to complete ([#4524](https://github.com/terraform-providers/terraform-provider-aws/issues/4524)) -* resource/aws_spot_fleet_request: Add `launch_specification` `iam_instance_profile_arn` argument ([#4511](https://github.com/terraform-providers/terraform-provider-aws/issues/4511)) - -BUG FIXES: - -* data-source/aws_autoscaling_groups: Use pagination function for DescribeTags filtering ([#4535](https://github.com/terraform-providers/terraform-provider-aws/issues/4535)) -* resource/aws_elb: Ensure `bucket_prefix` for access logging can be updated to `""` ([#4383](https://github.com/terraform-providers/terraform-provider-aws/issues/4383)) -* resource/aws_kinesis_firehose_delivery_stream: Retry on Elasticsearch destination IAM role errors and update IAM errors ([#4518](https://github.com/terraform-providers/terraform-provider-aws/issues/4518)) -* resource/aws_launch_template: Allow `network_interfaces` `device_index` to be set to 0 ([#4367](https://github.com/terraform-providers/terraform-provider-aws/issues/4367)) -* resource/aws_lb: Ensure `bucket_prefix` for access logging can be updated to `""` ([#4383](https://github.com/terraform-providers/terraform-provider-aws/issues/4383)) -* resource/aws_lb: Ensure `access_logs` is properly set into Terraform state ([#4517](https://github.com/terraform-providers/terraform-provider-aws/issues/4517)) -* resource/aws_security_group: Fix rule description handling when gathering multiple rules with same permissions ([#4416](https://github.com/terraform-providers/terraform-provider-aws/issues/4416)) - -## 1.18.0 (May 10, 2018) - -FEATURES: - -* **New Data Source:** `aws_acmpca_certificate_authority` ([#4458](https://github.com/terraform-providers/terraform-provider-aws/issues/4458)) -* **New Resource:** `aws_acmpca_certificate_authority` ([#4458](https://github.com/terraform-providers/terraform-provider-aws/issues/4458)) -* **New Resource:** `aws_glue_catalog_table` ([#4368](https://github.com/terraform-providers/terraform-provider-aws/issues/4368)) - -ENHANCEMENTS: - -* provider: Lower retry threshold for DNS resolution failures ([#4459](https://github.com/terraform-providers/terraform-provider-aws/issues/4459)) -* resource/aws_dms_endpoint: Support `s3` `engine_name` and add `s3_settings` argument ([#1685](https://github.com/terraform-providers/terraform-provider-aws/issues/1685)] and [[#4447](https://github.com/terraform-providers/terraform-provider-aws/issues/4447)) -* resource/aws_glue_job: Add `timeout` argument ([#4460](https://github.com/terraform-providers/terraform-provider-aws/issues/4460)) -* resource/aws_lb_target_group: Add `proxy_protocol_v2` argument ([#4365](https://github.com/terraform-providers/terraform-provider-aws/issues/4365)) -* resource/aws_spot_fleet_request: Mark `spot_price` optional (defaults to on-demand price) ([#4424](https://github.com/terraform-providers/terraform-provider-aws/issues/4424)) -* resource/aws_spot_fleet_request: Add plan time validation for `valid_from` and `valid_until` arguments ([#4463](https://github.com/terraform-providers/terraform-provider-aws/issues/4463)) -* resource/aws_spot_instance_request: Mark `spot_price` optional (defaults to on-demand price) ([#4424](https://github.com/terraform-providers/terraform-provider-aws/issues/4424)) - -BUG FIXES: - -* data-source/aws_autoscaling_groups: Correctly paginate through over 50 results ([#4433](https://github.com/terraform-providers/terraform-provider-aws/issues/4433)) -* resource/aws_elastic_beanstalk_environment: Correctly handle `cname_prefix` attribute in China partition ([#4485](https://github.com/terraform-providers/terraform-provider-aws/issues/4485)) -* resource/aws_glue_job: Remove `allocated_capacity` and `max_concurrent_runs` upper plan time validation limits ([#4461](https://github.com/terraform-providers/terraform-provider-aws/issues/4461)) -* resource/aws_instance: Fix `root_device_mapping` matching of expected root device name with multiple block devices. ([#4489](https://github.com/terraform-providers/terraform-provider-aws/issues/4489)) -* resource/aws_launch_template: Prevent `parameter iops is not supported for gp2 volumes` error ([#4344](https://github.com/terraform-providers/terraform-provider-aws/issues/4344)) -* resource/aws_launch_template: Prevent `'iamInstanceProfile.name' may not be used in combination with 'iamInstanceProfile.arn'` error ([#4344](https://github.com/terraform-providers/terraform-provider-aws/issues/4344)) -* resource/aws_launch_template: Prevent `parameter groupName cannot be used with the parameter subnet` error ([#4344](https://github.com/terraform-providers/terraform-provider-aws/issues/4344)) -* resource/aws_launch_template: Separate usage of `ipv4_address_count`/`ipv6_address_count` from `ipv4_addresses`/`ipv6_addresses` ([#4344](https://github.com/terraform-providers/terraform-provider-aws/issues/4344)) -* resource/aws_redshift_cluster: Properly send all required parameters when resizing ([#3127](https://github.com/terraform-providers/terraform-provider-aws/issues/3127)) -* resource/aws_s3_bucket: Prevent crash from empty string CORS arguments ([#4465](https://github.com/terraform-providers/terraform-provider-aws/issues/4465)) -* resource/aws_ssm_document: Add missing account ID to `arn` attribute ([#4436](https://github.com/terraform-providers/terraform-provider-aws/issues/4436)) - -## 1.17.0 (May 02, 2018) - -NOTES: - -* resource/aws_ecs_service: Please note the `placement_strategy` argument (an unordered list) has been marked deprecated in favor of the `ordered_placement_strategy` argument (an ordered list based on the Terraform configuration ordering). - -FEATURES: - -* **New Data Source:** `aws_mq_broker` ([#3163](https://github.com/terraform-providers/terraform-provider-aws/issues/3163)) -* **New Resource:** `aws_budgets_budget` ([#1879](https://github.com/terraform-providers/terraform-provider-aws/issues/1879)) -* **New Resource:** `aws_iam_user_group_membership` ([#3365](https://github.com/terraform-providers/terraform-provider-aws/issues/3365)) -* **New Resource:** `aws_vpc_peering_connection_options` ([#3909](https://github.com/terraform-providers/terraform-provider-aws/issues/3909)) - -ENHANCEMENTS: - -* data-source/aws_route53_zone: Add `name_servers` attribute ([#4336](https://github.com/terraform-providers/terraform-provider-aws/issues/4336)) -* resource/aws_api_gateway_stage: Add `access_log_settings` argument (Support access logging) ([#4369](https://github.com/terraform-providers/terraform-provider-aws/issues/4369)) -* resource/aws_autoscaling_group: Add `launch_template` argument ([#4305](https://github.com/terraform-providers/terraform-provider-aws/issues/4305)) -* resource/aws_batch_job_definition: Add `timeout` argument ([#4386](https://github.com/terraform-providers/terraform-provider-aws/issues/4386)) -* resource/aws_cloudwatch_event_rule: Add `name_prefix` argument ([#2752](https://github.com/terraform-providers/terraform-provider-aws/issues/2752)) -* resource/aws_cloudwatch_event_rule: Make `name` optional (Terraform can generate unique ID) ([#2752](https://github.com/terraform-providers/terraform-provider-aws/issues/2752)) -* resource/aws_codedeploy_deployment_group: Add `ec2_tag_set` argument (tag group support) ([#4324](https://github.com/terraform-providers/terraform-provider-aws/issues/4324)) -* resource/aws_default_subnet: Allow `map_public_ip_on_launch` updates ([#4396](https://github.com/terraform-providers/terraform-provider-aws/issues/4396)) -* resource/aws_dms_endpoint: Support `mongodb` engine_name and `mongodb_settings` argument ([#4406](https://github.com/terraform-providers/terraform-provider-aws/issues/4406)) -* resource/aws_dynamodb_table: Add `point_in_time_recovery` argument ([#4063](https://github.com/terraform-providers/terraform-provider-aws/issues/4063)) -* resource/aws_ecs_service: Add `ordered_placement_strategy` argument, deprecate `placement_strategy` argument ([#4390](https://github.com/terraform-providers/terraform-provider-aws/issues/4390)) -* resource/aws_ecs_service: Allow `health_check_grace_period_seconds` up to 7200 seconds ([#4420](https://github.com/terraform-providers/terraform-provider-aws/issues/4420)) -* resource/aws_lambda_permission: Add `statement_id_prefix` argument ([#2743](https://github.com/terraform-providers/terraform-provider-aws/issues/2743)) -* resource/aws_lambda_permission: Make `statement_id` optional (Terraform can generate unique ID) ([#2743](https://github.com/terraform-providers/terraform-provider-aws/issues/2743)) -* resource/aws_rds_cluster: Add `s3_import` argument (Support MySQL Backup Restore from S3) ([#4366](https://github.com/terraform-providers/terraform-provider-aws/issues/4366)) -* resource/aws_vpc_peering_connection: Support configurable timeouts ([#3909](https://github.com/terraform-providers/terraform-provider-aws/issues/3909)) - -BUG FIXES: - -* data-source/aws_instance: Bypass `UnsupportedOperation` errors with `DescribeInstanceCreditSpecifications` call ([#4362](https://github.com/terraform-providers/terraform-provider-aws/issues/4362)) -* resource/aws_iam_group_policy: Properly handle generated policy name updates ([#4379](https://github.com/terraform-providers/terraform-provider-aws/issues/4379)) -* resource/aws_instance: Bypass `UnsupportedOperation` errors with `DescribeInstanceCreditSpecifications` call ([#4362](https://github.com/terraform-providers/terraform-provider-aws/issues/4362)) -* resource/aws_launch_template: Appropriately set `security_groups` in network interfaces ([#4364](https://github.com/terraform-providers/terraform-provider-aws/issues/4364)) -* resource/aws_rds_cluster: Add retries for IAM eventual consistency ([#4371](https://github.com/terraform-providers/terraform-provider-aws/issues/4371)) -* resource/aws_rds_cluster_instance: Add retries for IAM eventual consistency ([#4370](https://github.com/terraform-providers/terraform-provider-aws/issues/4370)) -* resource/aws_route53_zone: Add domain name to CallerReference to prevent creation issues with count greater than one ([#4341](https://github.com/terraform-providers/terraform-provider-aws/issues/4341)) - -## 1.16.0 (April 25, 2018) - -FEATURES: - -* **New Data Source:** `aws_batch_compute_environment` ([#4270](https://github.com/terraform-providers/terraform-provider-aws/issues/4270)) -* **New Data Source:** `aws_batch_job_queue` ([#4288](https://github.com/terraform-providers/terraform-provider-aws/issues/4288)) -* **New Data Source:** `aws_iot_endpoint` ([#4303](https://github.com/terraform-providers/terraform-provider-aws/issues/4303)) -* **New Data Source:** `aws_lambda_function` ([#2984](https://github.com/terraform-providers/terraform-provider-aws/issues/2984)) -* **New Data Source:** `aws_redshift_cluster` ([#2603](https://github.com/terraform-providers/terraform-provider-aws/issues/2603)) -* **New Data Source:** `aws_secretsmanager_secret` ([#4272](https://github.com/terraform-providers/terraform-provider-aws/issues/4272)) -* **New Data Source:** `aws_secretsmanager_secret_version` ([#4272](https://github.com/terraform-providers/terraform-provider-aws/issues/4272)) -* **New Resource:** `aws_dax_parameter_group` ([#4299](https://github.com/terraform-providers/terraform-provider-aws/issues/4299)) -* **New Resource:** `aws_dax_subnet_group` ([#4302](https://github.com/terraform-providers/terraform-provider-aws/issues/4302)) -* **New Resource:** `aws_organizations_policy` ([#4249](https://github.com/terraform-providers/terraform-provider-aws/issues/4249)) -* **New Resource:** `aws_organizations_policy_attachment` ([#4253](https://github.com/terraform-providers/terraform-provider-aws/issues/4253)) -* **New Resource:** `aws_secretsmanager_secret` ([#4272](https://github.com/terraform-providers/terraform-provider-aws/issues/4272)) -* **New Resource:** `aws_secretsmanager_secret_version` ([#4272](https://github.com/terraform-providers/terraform-provider-aws/issues/4272)) - -ENHANCEMENTS: - -* data-source/aws_cognito_user_pools: Add `arns` attribute ([#4256](https://github.com/terraform-providers/terraform-provider-aws/issues/4256)) -* data-source/aws_ecs_cluster Return error on multiple clusters ([#4286](https://github.com/terraform-providers/terraform-provider-aws/issues/4286)) -* data-source/aws_iam_instance_profile: Add `role_arn` and `role_name` attributes ([#4300](https://github.com/terraform-providers/terraform-provider-aws/issues/4300)) -* data-source/aws_instance: Add `disable_api_termination` attribute ([#4314](https://github.com/terraform-providers/terraform-provider-aws/issues/4314)) -* resource/aws_api_gateway_rest_api: Add `policy` argument ([#4211](https://github.com/terraform-providers/terraform-provider-aws/issues/4211)) -* resource/aws_api_gateway_stage: Add `tags` argument ([#2858](https://github.com/terraform-providers/terraform-provider-aws/issues/2858)) -* resource/aws_api_gateway_stage: Add `execution_arn` and `invoke_url` attributes ([#3469](https://github.com/terraform-providers/terraform-provider-aws/issues/3469)) -* resource/aws_api_gateway_vpc_link: Support import ([#4306](https://github.com/terraform-providers/terraform-provider-aws/issues/4306)) -* resource/aws_cloudwatch_event_target: Add `batch_target` argument ([#4312](https://github.com/terraform-providers/terraform-provider-aws/issues/4312)) -* resource/aws_cloudwatch_event_target: Add `kinesis_target` and `sqs_target` arguments ([#4323](https://github.com/terraform-providers/terraform-provider-aws/issues/4323)) -* resource/aws_cognito_user_pool: Support `user_migration` in `lambda_config` ([#4301](https://github.com/terraform-providers/terraform-provider-aws/issues/4301)) -* resource/aws_db_instance: Add `s3_import` argument ([#2728](https://github.com/terraform-providers/terraform-provider-aws/issues/2728)) -* resource/aws_elastic_beanstalk_application: Add `appversion_lifecycle` argument ([#1907](https://github.com/terraform-providers/terraform-provider-aws/issues/1907)) -* resource/aws_instance: Add `credit_specification` argument (e.g. t2.unlimited support) ([#2619](https://github.com/terraform-providers/terraform-provider-aws/issues/2619)) -* resource/aws_kinesis_firehose_delivery_stream: Support Redshift `processing_configuration` ([#4251](https://github.com/terraform-providers/terraform-provider-aws/issues/4251)) -* resource/aws_launch_configuration: Add `user_data_base64` argument ([#4257](https://github.com/terraform-providers/terraform-provider-aws/issues/4257)) -* resource/aws_s3_bucket: Add support for `ONEZONE_IA` storage class ([#4287](https://github.com/terraform-providers/terraform-provider-aws/issues/4287)) -* resource/aws_s3_bucket_object: Add support for `ONEZONE_IA` storage class ([#4287](https://github.com/terraform-providers/terraform-provider-aws/issues/4287)) -* resource/aws_spot_instance_request: Add `valid_from` and `valid_until` arguments ([#4018](https://github.com/terraform-providers/terraform-provider-aws/issues/4018)) -* resource/aws_ssm_patch_baseline: Support `CENTOS` `operating_system` argument ([#4268](https://github.com/terraform-providers/terraform-provider-aws/issues/4268)) - -BUG FIXES: - -* data-source/aws_iam_policy_document: Prevent crash with multiple value principal identifiers ([#4277](https://github.com/terraform-providers/terraform-provider-aws/issues/4277)) -* data-source/aws_lb_listener: Ensure attributes are properly set when not used as arguments ([#4317](https://github.com/terraform-providers/terraform-provider-aws/issues/4317)) -* resource/aws_codebuild_project: Mark auth resource attribute as sensitive ([#4284](https://github.com/terraform-providers/terraform-provider-aws/issues/4284)) -* resource/aws_cognito_user_pool_client: Fix import to include user pool ID ([#3762](https://github.com/terraform-providers/terraform-provider-aws/issues/3762)) -* resource/aws_elasticache_cluster: Remove extraneous plan-time validation for `node_type` and `subnet_group_name` ([#4333](https://github.com/terraform-providers/terraform-provider-aws/issues/4333)) -* resource/aws_launch_template: Allow dashes in `name` and `name_prefix` arguments ([#4321](https://github.com/terraform-providers/terraform-provider-aws/issues/4321)) -* resource/aws_launch_template: Properly set `block_device_mappings` EBS information into Terraform state ([#4321](https://github.com/terraform-providers/terraform-provider-aws/issues/4321)) -* resource/aws_launch_template: Properly pass `block_device_mappings` information to EC2 API ([#4321](https://github.com/terraform-providers/terraform-provider-aws/issues/4321)) -* resource/aws_s3_bucket: Prevent panic on lifecycle rule reading errors ([#4282](https://github.com/terraform-providers/terraform-provider-aws/issues/4282)) - -## 1.15.0 (April 18, 2018) - -NOTES: - -* resource/aws_cloudfront_distribution: Please note the `cache_behavior` argument (an unordered list) has been marked deprecated in favor of the `ordered_cache_behavior` argument (an ordered list based on the Terraform configuration ordering). This is to support proper cache behavior precedence within a CloudFront distribution. - -FEATURES: - -* **New Data Source:** `aws_api_gateway_rest_api` ([#4172](https://github.com/terraform-providers/terraform-provider-aws/issues/4172)) -* **New Data Source:** `aws_cloudwatch_log_group` ([#4167](https://github.com/terraform-providers/terraform-provider-aws/issues/4167)) -* **New Data Source:** `aws_cognito_user_pools` ([#4212](https://github.com/terraform-providers/terraform-provider-aws/issues/4212)) -* **New Data Source:** `aws_sqs_queue` ([#2311](https://github.com/terraform-providers/terraform-provider-aws/issues/2311)) -* **New Resource:** `aws_directory_service_conditional_forwarder` ([#4071](https://github.com/terraform-providers/terraform-provider-aws/issues/4071)) -* **New Resource:** `aws_glue_connection` ([#4016](https://github.com/terraform-providers/terraform-provider-aws/issues/4016)) -* **New Resource:** `aws_glue_job` ([#4028](https://github.com/terraform-providers/terraform-provider-aws/issues/4028)) -* **New Resource:** `aws_iam_service_linked_role` ([#2985](https://github.com/terraform-providers/terraform-provider-aws/issues/2985)) -* **New Resource:** `aws_launch_template` ([#2927](https://github.com/terraform-providers/terraform-provider-aws/issues/2927)) -* **New Resource:** `aws_ses_domain_identity_verification` ([#4108](https://github.com/terraform-providers/terraform-provider-aws/issues/4108)) - -ENHANCEMENTS: - -* data-source/aws_iam_server_certificate: Filter by `path_prefix` ([#3801](https://github.com/terraform-providers/terraform-provider-aws/issues/3801)) -* resource/aws_api_gateway_integration: Support VPC connection ([#3428](https://github.com/terraform-providers/terraform-provider-aws/issues/3428)) -* resource/aws_cloudfront_distribution: Added `ordered_cache_behavior` argument, deprecate `cache_behavior` ([#4117](https://github.com/terraform-providers/terraform-provider-aws/issues/4117)) -* resource/aws_db_instance: Support `enabled_cloudwatch_logs_exports` argument ([#4111](https://github.com/terraform-providers/terraform-provider-aws/issues/4111)) -* resource/aws_db_option_group: Support option version argument ([#2590](https://github.com/terraform-providers/terraform-provider-aws/issues/2590)) -* resource/aws_ecs_service: Support ServiceRegistries ([#3906](https://github.com/terraform-providers/terraform-provider-aws/issues/3906)) -* resource/aws_iam_service_linked_role: Support `custom_suffix` and `description` arguments ([#4188](https://github.com/terraform-providers/terraform-provider-aws/issues/4188)) -* resource/aws_service_discovery_service: Support `health_check_custom_config` argument ([#4083](https://github.com/terraform-providers/terraform-provider-aws/issues/4083)) -* resource/aws_spot_fleet_request: Support configurable delete timeout ([#3940](https://github.com/terraform-providers/terraform-provider-aws/issues/3940)) -* resource/aws_spot_instance_request: Support optionally fetching password data ([#4189](https://github.com/terraform-providers/terraform-provider-aws/issues/4189)) -* resource/aws_waf_rate_based_rule: Support `RegexMatch` predicate type ([#4069](https://github.com/terraform-providers/terraform-provider-aws/issues/4069)) -* resource/aws_waf_rule: Support `RegexMatch` predicate type ([#4069](https://github.com/terraform-providers/terraform-provider-aws/issues/4069)) -* resource/aws_wafregional_rate_based_rule: Support `RegexMatch` predicate type ([#4069](https://github.com/terraform-providers/terraform-provider-aws/issues/4069)) - -BUG FIXES: - -* resource/aws_athena_database: Handle database names with uppercase and underscores ([#4133](https://github.com/terraform-providers/terraform-provider-aws/issues/4133)) -* resource/aws_codebuild_project: Retry UpdateProject for IAM eventual consistency ([#4238](https://github.com/terraform-providers/terraform-provider-aws/issues/4238)) -* resource/aws_codedeploy_deployment_config: Force new resource for `minimum_healthy_hosts` updates ([#4194](https://github.com/terraform-providers/terraform-provider-aws/issues/4194)) -* resource/aws_cognito_user_group: Fix `role_arn` updates ([#4237](https://github.com/terraform-providers/terraform-provider-aws/issues/4237)) -* resource/aws_elasticache_replication_group: Increase default create timeout to 60 minutes ([#4093](https://github.com/terraform-providers/terraform-provider-aws/issues/4093)) -* resource/aws_emr_cluster: Force new resource if any of the `ec2_attributes` change ([#4218](https://github.com/terraform-providers/terraform-provider-aws/issues/4218)) -* resource/aws_iam_role: Suppress `NoSuchEntity` errors while detaching policies from role during deletion ([#4209](https://github.com/terraform-providers/terraform-provider-aws/issues/4209)) -* resource/aws_lb: Force new resource if any of the `subnet_mapping` attributes change ([#4086](https://github.com/terraform-providers/terraform-provider-aws/issues/4086)) -* resource/aws_rds_cluster: Properly handle `engine_version` with `snapshot_identifier` ([#4215](https://github.com/terraform-providers/terraform-provider-aws/issues/4215)) -* resource/aws_route53_record: Improved handling of non-alphanumeric record names ([#4183](https://github.com/terraform-providers/terraform-provider-aws/issues/4183)) -* resource/aws_spot_instance_request: Fix `instance_interuption_behaviour` hibernate and stop handling with placement ([#1986](https://github.com/terraform-providers/terraform-provider-aws/issues/1986)) -* resource/aws_vpc_dhcp_options: Handle plural and non-plural `InvalidDhcpOptionsID.NotFound` errors ([#4136](https://github.com/terraform-providers/terraform-provider-aws/issues/4136)) - -## 1.14.1 (April 11, 2018) - -ENHANCEMENTS: - -* resource/aws_db_event_subscription: Add `arn` attribute ([#4151](https://github.com/terraform-providers/terraform-provider-aws/issues/4151)) -* resource/aws_db_event_subscription: Support configurable timeouts ([#4151](https://github.com/terraform-providers/terraform-provider-aws/issues/4151)) - -BUG FIXES: - -* resource/aws_codebuild_project: Properly handle setting cache type `NO_CACHE` ([#4134](https://github.com/terraform-providers/terraform-provider-aws/issues/4134)) -* resource/aws_db_event_subscription: Fix `tag` ARN handling ([#4151](https://github.com/terraform-providers/terraform-provider-aws/issues/4151)) -* resource/aws_dynamodb_table_item: Trigger destructive update if range_key has changed ([#3821](https://github.com/terraform-providers/terraform-provider-aws/issues/3821)) -* resource/aws_elb: Return any errors when updating listeners ([#4159](https://github.com/terraform-providers/terraform-provider-aws/issues/4159)) -* resource/aws_emr_cluster: Prevent crash with missing StateChangeReason ([#4165](https://github.com/terraform-providers/terraform-provider-aws/issues/4165)) -* resource/aws_iam_user: Retry user login profile deletion on `EntityTemporarilyUnmodifiable` ([#4143](https://github.com/terraform-providers/terraform-provider-aws/issues/4143)) -* resource/aws_kinesis_firehose_delivery_stream: Prevent crash with missing CloudWatch logging options ([#4148](https://github.com/terraform-providers/terraform-provider-aws/issues/4148)) -* resource/aws_lambda_alias: Force new resource on `name` change ([#4106](https://github.com/terraform-providers/terraform-provider-aws/issues/4106)) -* resource/aws_lambda_function: Prevent perpetual difference when removing `dead_letter_config` ([#2684](https://github.com/terraform-providers/terraform-provider-aws/issues/2684)) -* resource/aws_launch_configuration: Properly read `security_groups`, `user_data`, and `vpc_classic_link_security_groups` attributes into Terraform state ([#2800](https://github.com/terraform-providers/terraform-provider-aws/issues/2800)) -* resource/aws_network_acl: Prevent error on deletion with already deleted subnets ([#4119](https://github.com/terraform-providers/terraform-provider-aws/issues/4119)) -* resource/aws_network_acl: Prevent error on update with removing associations for already deleted subnets ([#4119](https://github.com/terraform-providers/terraform-provider-aws/issues/4119)) -* resource/aws_rds_cluster: Properly handle `engine_version` during regular creation ([#4139](https://github.com/terraform-providers/terraform-provider-aws/issues/4139)) -* resource/aws_rds_cluster: Set `port` updates to force new resource ([#4144](https://github.com/terraform-providers/terraform-provider-aws/issues/4144)) -* resource/aws_route53_zone: Suppress `name` difference with trailing period ([#3982](https://github.com/terraform-providers/terraform-provider-aws/issues/3982)) -* resource/aws_vpc_peering_connection: Allow active pending state during deletion for eventual consistency ([#4140](https://github.com/terraform-providers/terraform-provider-aws/issues/4140)) - -## 1.14.0 (April 06, 2018) - -NOTES: - -* resource/aws_organizations_account: As noted in the resource documentation, resource deletion from Terraform will _not_ automatically close AWS accounts due to the behavior of the AWS Organizations service. There are also various manual steps required by AWS before the account can be removed from an organization and made into a standalone account, then manually closed if desired. - -FEATURES: - -* **New Resource:** `aws_organizations_account` ([#3524](https://github.com/terraform-providers/terraform-provider-aws/issues/3524)) -* **New Resource:** `aws_ses_identity_notification_topic` ([#2640](https://github.com/terraform-providers/terraform-provider-aws/issues/2640)) - -ENHANCEMENTS: - -* provider: Fallback to SDK default credential chain if credentials not found using provider credential chain ([#2883](https://github.com/terraform-providers/terraform-provider-aws/issues/2883)) -* data-source/aws_iam_role: Add `max_session_duration` attribute ([#4092](https://github.com/terraform-providers/terraform-provider-aws/issues/4092)) -* resource/aws_cloudfront_distribution: Add cache_behavior `field_level_encryption_id` attribute ([#4102](https://github.com/terraform-providers/terraform-provider-aws/issues/4102)) -* resource/aws_codebuild_project: Support `cache` configuration ([#2860](https://github.com/terraform-providers/terraform-provider-aws/issues/2860)) -* resource/aws_elasticache_replication_group: Support Cluster Mode Enabled online shard reconfiguration ([#3932](https://github.com/terraform-providers/terraform-provider-aws/issues/3932)) -* resource/aws_elasticache_replication_group: Configurable create, update, and delete timeouts ([#3932](https://github.com/terraform-providers/terraform-provider-aws/issues/3932)) -* resource/aws_iam_role: Add `max_session_duration` argument ([#3977](https://github.com/terraform-providers/terraform-provider-aws/issues/3977)) -* resource/aws_kinesis_firehose_delivery_stream: Add Elasticsearch destination processing configuration support ([#3621](https://github.com/terraform-providers/terraform-provider-aws/issues/3621)) -* resource/aws_kinesis_firehose_delivery_stream: Add Extended S3 destination backup mode support ([#2987](https://github.com/terraform-providers/terraform-provider-aws/issues/2987)) -* resource/aws_kinesis_firehose_delivery_stream: Add Splunk destination processing configuration support ([#3944](https://github.com/terraform-providers/terraform-provider-aws/issues/3944)) -* resource/aws_lambda_function: Support `nodejs8.10` runtime ([#4020](https://github.com/terraform-providers/terraform-provider-aws/issues/4020)) -* resource/aws_launch_configuration: Add support for `ebs_block_device.*.no_device` ([#4070](https://github.com/terraform-providers/terraform-provider-aws/issues/4070)) -* resource/aws_ssm_maintenance_window_target: Make resource updatable ([#4074](https://github.com/terraform-providers/terraform-provider-aws/issues/4074)) -* resource/aws_wafregional_rule: Validate all predicate types ([#4046](https://github.com/terraform-providers/terraform-provider-aws/issues/4046)) - -BUG FIXES: - -* resource/aws_cognito_user_pool: Trim `custom:` prefix of `developer_only_attribute = false` schema attributes ([#4041](https://github.com/terraform-providers/terraform-provider-aws/issues/4041)) -* resource/aws_cognito_user_pool: Fix `email_message_by_link` max length validation ([#4051](https://github.com/terraform-providers/terraform-provider-aws/issues/4051)) -* resource/aws_elasticache_replication_group: Properly set `cluster_mode` in state ([#3932](https://github.com/terraform-providers/terraform-provider-aws/issues/3932)) -* resource/aws_iam_user_login_profile: Changed password generation to use `crypto/rand` ([#3989](https://github.com/terraform-providers/terraform-provider-aws/issues/3989)) -* resource/aws_kinesis_firehose_delivery_stream: Prevent additional crash scenarios with optional configurations ([#4047](https://github.com/terraform-providers/terraform-provider-aws/issues/4047)) -* resource/aws_lambda_function: IAM retry for "The role defined for the function cannot be assumed by Lambda" on update ([#3988](https://github.com/terraform-providers/terraform-provider-aws/issues/3988)) -* resource/aws_lb: Suppress differences for non-applicable attributes ([#4032](https://github.com/terraform-providers/terraform-provider-aws/issues/4032)) -* resource/aws_rds_cluster_instance: Prevent crash on importing non-cluster instances ([#3961](https://github.com/terraform-providers/terraform-provider-aws/issues/3961)) -* resource/aws_route53_record: Fix ListResourceRecordSet pagination ([#3900](https://github.com/terraform-providers/terraform-provider-aws/issues/3900)) - -## 1.13.0 (March 28, 2018) - -NOTES: - -This release is happening outside the normal release schedule to accommodate a crash fix for the `aws_lb_target_group` resource. It appears an ELBv2 service update rolling out currently is the root cause. The potential for this crash has been present since the initial resource in Terraform 0.7.7 and all versions of the AWS provider up to v1.13.0. - -FEATURES: - -* **New Resource:** `aws_appsync_datasource` ([#2758](https://github.com/terraform-providers/terraform-provider-aws/issues/2758)) -* **New Resource:** `aws_waf_regex_match_set` ([#3947](https://github.com/terraform-providers/terraform-provider-aws/issues/3947)) -* **New Resource:** `aws_waf_regex_pattern_set` ([#3913](https://github.com/terraform-providers/terraform-provider-aws/issues/3913)) -* **New Resource:** `aws_waf_rule_group` ([#3898](https://github.com/terraform-providers/terraform-provider-aws/issues/3898)) -* **New Resource:** `aws_wafregional_geo_match_set` ([#3915](https://github.com/terraform-providers/terraform-provider-aws/issues/3915)) -* **New Resource:** `aws_wafregional_rate_based_rule` ([#3871](https://github.com/terraform-providers/terraform-provider-aws/issues/3871)) -* **New Resource:** `aws_wafregional_regex_match_set` ([#3950](https://github.com/terraform-providers/terraform-provider-aws/issues/3950)) -* **New Resource:** `aws_wafregional_regex_pattern_set` ([#3933](https://github.com/terraform-providers/terraform-provider-aws/issues/3933)) -* **New Resource:** `aws_wafregional_rule_group` ([#3948](https://github.com/terraform-providers/terraform-provider-aws/issues/3948)) - -ENHANCEMENTS: - -* provider: Support custom Elasticsearch endpoint ([#3941](https://github.com/terraform-providers/terraform-provider-aws/issues/3941)) -* resource/aws_appsync_graphql_api: Support import ([#3500](https://github.com/terraform-providers/terraform-provider-aws/issues/3500)) -* resource/aws_elasticache_cluster: Allow port to be optional ([#3835](https://github.com/terraform-providers/terraform-provider-aws/issues/3835)) -* resource/aws_elasticache_cluster: Add `replication_group_id` argument ([#3869](https://github.com/terraform-providers/terraform-provider-aws/issues/3869)) -* resource/aws_elasticache_replication_group: Allow port to be optional ([#3835](https://github.com/terraform-providers/terraform-provider-aws/issues/3835)) - -BUG FIXES: - -* resource/aws_autoscaling_group: Fix updating of `service_linked_role` ([#3942](https://github.com/terraform-providers/terraform-provider-aws/issues/3942)) -* resource/aws_autoscaling_group: Properly set empty `enabled_metrics` in the state during read ([#3899](https://github.com/terraform-providers/terraform-provider-aws/issues/3899)) -* resource/aws_autoscaling_policy: Fix conditional logic based on `policy_type` ([#3739](https://github.com/terraform-providers/terraform-provider-aws/issues/3739)) -* resource/aws_batch_compute_environment: Correctly set `compute_resources` in state ([#3824](https://github.com/terraform-providers/terraform-provider-aws/issues/3824)) -* resource/aws_cognito_user_pool: Correctly set `schema` in state ([#3789](https://github.com/terraform-providers/terraform-provider-aws/issues/3789)) -* resource/aws_iam_user_login_profile: Fix `password_length` validation function regression from 1.12.0 ([#3919](https://github.com/terraform-providers/terraform-provider-aws/issues/3919)) -* resource/aws_lb: Store correct state for http2 and ensure attributes are set on create ([#3854](https://github.com/terraform-providers/terraform-provider-aws/issues/3854)) -* resource/aws_lb: Correctly set `subnet_mappings` in state ([#3822](https://github.com/terraform-providers/terraform-provider-aws/issues/3822)) -* resource/aws_lb_listener: Retry CertificateNotFound errors on update for IAM eventual consistency ([#3901](https://github.com/terraform-providers/terraform-provider-aws/issues/3901)) -* resource/aws_lb_target_group: Prevent crash from missing matcher during read ([#3954](https://github.com/terraform-providers/terraform-provider-aws/issues/3954)) -* resource/aws_security_group: Retry read on creation for EC2 eventual consistency ([#3892](https://github.com/terraform-providers/terraform-provider-aws/issues/3892)) - - -## 1.12.0 (March 23, 2018) - -NOTES: - -* provider: For resources implementing the IAM policy equivalence library (https://github.com/jen20/awspolicyequivalence/) on an attribute via `suppressEquivalentAwsPolicyDiffs`, the dependency has been updated, which should mark additional IAM policies as equivalent. ([#3832](https://github.com/terraform-providers/terraform-provider-aws/issues/3832)) - -FEATURES: - -* **New Resource:** `aws_kms_grant` ([#3038](https://github.com/terraform-providers/terraform-provider-aws/issues/3038)) -* **New Resource:** `aws_waf_geo_match_set` ([#3275](https://github.com/terraform-providers/terraform-provider-aws/issues/3275)) -* **New Resource:** `aws_wafregional_rule` ([#3756](https://github.com/terraform-providers/terraform-provider-aws/issues/3756)) -* **New Resource:** `aws_wafregional_size_constraint_set` ([#3796](https://github.com/terraform-providers/terraform-provider-aws/issues/3796)) -* **New Resource:** `aws_wafregional_sql_injection_match_set` ([#1013](https://github.com/terraform-providers/terraform-provider-aws/issues/1013)) -* **New Resource:** `aws_wafregional_web_acl` ([#3754](https://github.com/terraform-providers/terraform-provider-aws/issues/3754)) -* **New Resource:** `aws_wafregional_web_acl_association` ([#3755](https://github.com/terraform-providers/terraform-provider-aws/issues/3755)) -* **New Resource:** `aws_wafregional_xss_match_set` ([#1014](https://github.com/terraform-providers/terraform-provider-aws/issues/1014)) - -ENHANCEMENTS: - -* provider: Treat IAM policies with account ID principals as equivalent to IAM account root ARN ([#3832](https://github.com/terraform-providers/terraform-provider-aws/issues/3832)) -* provider: Treat additional IAM policy scenarios with empty principal trees as equivalent ([#3832](https://github.com/terraform-providers/terraform-provider-aws/issues/3832)) -* resource/aws_acm_certificate: Retry on ResourceInUseException during deletion for eventual consistency ([#3868](https://github.com/terraform-providers/terraform-provider-aws/issues/3868)) -* resource/aws_api_gateway_rest_api: Add support for content encoding ([#3642](https://github.com/terraform-providers/terraform-provider-aws/issues/3642)) -* resource/aws_autoscaling_group: Add `service_linked_role_arn` argument ([#3812](https://github.com/terraform-providers/terraform-provider-aws/issues/3812)) -* resource/aws_cloudfront_distribution: Validate origin `domain_name` and `origin_id` at plan time ([#3767](https://github.com/terraform-providers/terraform-provider-aws/issues/3767)) -* resource/aws_eip: Support configurable timeouts ([#3769](https://github.com/terraform-providers/terraform-provider-aws/issues/3769)) -* resource/aws_elasticache_cluster: Support plan time validation of az_mode ([#3857](https://github.com/terraform-providers/terraform-provider-aws/issues/3857)) -* resource/aws_elasticache_cluster: Support plan time validation of node_type requiring VPC for cache.t2 instances ([#3857](https://github.com/terraform-providers/terraform-provider-aws/issues/3857)) -* resource/aws_elasticache_cluster: Support plan time validation of num_cache_nodes > 1 for redis ([#3857](https://github.com/terraform-providers/terraform-provider-aws/issues/3857)) -* resource/aws_elasticache_cluster: ForceNew on node_type changes for memcached engine ([#3857](https://github.com/terraform-providers/terraform-provider-aws/issues/3857)) -* resource/aws_elasticache_cluster: ForceNew on engine_version downgrades ([#3857](https://github.com/terraform-providers/terraform-provider-aws/issues/3857)) -* resource/aws_emr_cluster: Add step support ([#3673](https://github.com/terraform-providers/terraform-provider-aws/issues/3673)) -* resource/aws_instance: Support optionally fetching encrypted Windows password data ([#2219](https://github.com/terraform-providers/terraform-provider-aws/issues/2219)) -* resource/aws_launch_configuration: Validate `user_data` length during plan ([#2973](https://github.com/terraform-providers/terraform-provider-aws/issues/2973)) -* resource/aws_lb_target_group: Validate health check threshold for TCP protocol during plan ([#3782](https://github.com/terraform-providers/terraform-provider-aws/issues/3782)) -* resource/aws_security_group: Add arn attribute ([#3751](https://github.com/terraform-providers/terraform-provider-aws/issues/3751)) -* resource/aws_ses_domain_identity: Support trailing period in domain name ([#3840](https://github.com/terraform-providers/terraform-provider-aws/issues/3840)) -* resource/aws_sqs_queue: Support lack of ListQueueTags for all non-standard AWS implementations ([#3794](https://github.com/terraform-providers/terraform-provider-aws/issues/3794)) -* resource/aws_ssm_document: Add `document_format` argument to support YAML ([#3814](https://github.com/terraform-providers/terraform-provider-aws/issues/3814)) -* resource/aws_s3_bucket_object: New `content_base64` argument allows uploading raw binary data created in-memory, rather than reading from disk as with `source`. ([#3788](https://github.com/terraform-providers/terraform-provider-aws/issues/3788)) - -BUG FIXES: - -* resource/aws_api_gateway_client_certificate: Export `*_date` fields correctly ([#3805](https://github.com/terraform-providers/terraform-provider-aws/issues/3805)) -* resource/aws_cognito_user_pool: Detect `auto_verified_attributes` changes ([#3786](https://github.com/terraform-providers/terraform-provider-aws/issues/3786)) -* resource/aws_cognito_user_pool_client: Fix `callback_urls` updates ([#3404](https://github.com/terraform-providers/terraform-provider-aws/issues/3404)) -* resource/aws_db_instance: Support `incompatible-parameters` and `storage-full` state ([#3708](https://github.com/terraform-providers/terraform-provider-aws/issues/3708)) -* resource/aws_dynamodb_table: Update and validate attributes correctly ([#3194](https://github.com/terraform-providers/terraform-provider-aws/issues/3194)) -* resource/aws_ecs_task_definition: Correctly read `volume` attribute into Terraform state ([#3823](https://github.com/terraform-providers/terraform-provider-aws/issues/3823)) -* resource/aws_kinesis_firehose_delivery_stream: Prevent crash on malformed ID for import ([#3834](https://github.com/terraform-providers/terraform-provider-aws/issues/3834)) -* resource/aws_lambda_function: Only retry IAM eventual consistency errors for one minute ([#3765](https://github.com/terraform-providers/terraform-provider-aws/issues/3765)) -* resource/aws_ssm_association: Prevent AssociationDoesNotExist error ([#3776](https://github.com/terraform-providers/terraform-provider-aws/issues/3776)) -* resource/aws_vpc_endpoint: Prevent perpertual diff in non-standard partitions ([#3317](https://github.com/terraform-providers/terraform-provider-aws/issues/3317)) - -## 1.11.0 (March 09, 2018) - -FEATURES: - -* **New Data Source:** `aws_kms_key` ([#2224](https://github.com/terraform-providers/terraform-provider-aws/issues/2224)) -* **New Resource:** `aws_organizations_organization` ([#903](https://github.com/terraform-providers/terraform-provider-aws/issues/903)) -* **New Resource:** `aws_iot_thing` ([#3521](https://github.com/terraform-providers/terraform-provider-aws/issues/3521)) - -ENHANCEMENTS: - -* resource/aws_api_gateway_authorizer: Support COGNITO_USER_POOLS type ([#3156](https://github.com/terraform-providers/terraform-provider-aws/issues/3156)) -* resource/aws_cloud9_environment_ec2: Retry creation for IAM eventual consistency ([#3651](https://github.com/terraform-providers/terraform-provider-aws/issues/3651)) -* resource/aws_cloudfront_distribution: Make `default_ttl`, `max_ttl`, and `min_ttl` arguments optional ([#3571](https://github.com/terraform-providers/terraform-provider-aws/issues/3571)) -* resource/aws_dms_endpoint: Add aurora-postgresql as a target ([#2615](https://github.com/terraform-providers/terraform-provider-aws/issues/2615)) -* resource/aws_dynamodb_table: Support Server Side Encryption ([#3303](https://github.com/terraform-providers/terraform-provider-aws/issues/3303)) -* resource/aws_elastic_beanstalk_environment: Support modifying `tags` ([#3513](https://github.com/terraform-providers/terraform-provider-aws/issues/3513)) -* resource/aws_emr_cluster: Add Kerberos support ([#3553](https://github.com/terraform-providers/terraform-provider-aws/issues/3553)) -* resource/aws_iam_account_alias: Improve error messages to include API errors ([#3590](https://github.com/terraform-providers/terraform-provider-aws/issues/3590)) -* resource/aws_iam_user_policy: Add support for import ([#3198](https://github.com/terraform-providers/terraform-provider-aws/issues/3198)) -* resource/aws_lb: Add `enable_cross_zone_load_balancing` argument for NLBs ([#3537](https://github.com/terraform-providers/terraform-provider-aws/issues/3537)) -* resource/aws_lb: Add `enable_http2` argument for ALBs ([#3609](https://github.com/terraform-providers/terraform-provider-aws/issues/3609)) -* resource/aws_route: Add configurable timeouts ([#3639](https://github.com/terraform-providers/terraform-provider-aws/issues/3639)) -* resource/aws_security_group: Add configurable timeouts ([#3599](https://github.com/terraform-providers/terraform-provider-aws/issues/3599)) -* resource/aws_spot_fleet_request: Add `load_balancers` and `target_group_arns` arguments ([#2564](https://github.com/terraform-providers/terraform-provider-aws/issues/2564)) -* resource/aws_ssm_parameter: Add `allowed_pattern`, `description`, and `tags` arguments ([#1520](https://github.com/terraform-providers/terraform-provider-aws/issues/1520)) -* resource/aws_ssm_parameter: Allow `key_id` updates ([#1520](https://github.com/terraform-providers/terraform-provider-aws/issues/1520)) - -BUG FIXES: - -* data-source/aws_db_instance: Prevent crash with EC2 Classic ([#3619](https://github.com/terraform-providers/terraform-provider-aws/issues/3619)) -* data-source/aws_vpc_endpoint_service: Fix aws-us-gov partition handling ([#3514](https://github.com/terraform-providers/terraform-provider-aws/issues/3514)) -* resource/aws_api_gateway_vpc_link: Ensure `target_arns` is properly read ([#3569](https://github.com/terraform-providers/terraform-provider-aws/issues/3569)) -* resource/aws_batch_compute_environment: Fix `state` updates ([#3508](https://github.com/terraform-providers/terraform-provider-aws/issues/3508)) -* resource/aws_ebs_snapshot: Prevent crash with outside snapshot deletion ([#3462](https://github.com/terraform-providers/terraform-provider-aws/issues/3462)) -* resource/aws_ecs_service: Prevent crash when importing non-existent service ([#3672](https://github.com/terraform-providers/terraform-provider-aws/issues/3672)) -* resource/aws_eip_association: Prevent deletion error InvalidAssociationID.NotFound ([#3653](https://github.com/terraform-providers/terraform-provider-aws/issues/3653)) -* resource/aws_instance: Ensure at least one security group is being attached when modifying vpc_security_group_ids ([#2850](https://github.com/terraform-providers/terraform-provider-aws/issues/2850)) -* resource/aws_lambda_function: Allow PutFunctionConcurrency retries on creation ([#3570](https://github.com/terraform-providers/terraform-provider-aws/issues/3570)) -* resource/aws_spot_instance_request: Retry for 1 minute instead of 15 seconds for IAM eventual consistency ([#3561](https://github.com/terraform-providers/terraform-provider-aws/issues/3561)) -* resource/aws_ssm_activation: Prevent crash with expiration_date ([#3597](https://github.com/terraform-providers/terraform-provider-aws/issues/3597)) - -## 1.10.0 (February 24, 2018) - -NOTES: - -* resource/aws_dx_lag: `number_of_connections` was deprecated and will be removed in future major version. Use `aws_dx_connection` and `aws_dx_connection_association` resources instead. Default connections will be removed as part of LAG creation automatically in future major version. ([#3367](https://github.com/terraform-providers/terraform-provider-aws/issues/3367)) - -FEATURES: - -* **New Data Source:** `aws_inspector_rules_packages` ([#3175](https://github.com/terraform-providers/terraform-provider-aws/issues/3175)) -* **New Resource:** `aws_api_gateway_vpc_link` ([#2512](https://github.com/terraform-providers/terraform-provider-aws/issues/2512)) -* **New Resource:** `aws_appsync_graphql_api` ([#2494](https://github.com/terraform-providers/terraform-provider-aws/issues/2494)) -* **New Resource:** `aws_dax_cluster` ([#2884](https://github.com/terraform-providers/terraform-provider-aws/issues/2884)) -* **New Resource:** `aws_gamelift_alias` ([#3353](https://github.com/terraform-providers/terraform-provider-aws/issues/3353)) -* **New Resource:** `aws_gamelift_fleet` ([#3327](https://github.com/terraform-providers/terraform-provider-aws/issues/3327)) -* **New Resource:** `aws_lb_listener_certificate` ([#2686](https://github.com/terraform-providers/terraform-provider-aws/issues/2686)) -* **New Resource:** `aws_s3_bucket_metric` ([#916](https://github.com/terraform-providers/terraform-provider-aws/issues/916)) -* **New Resource:** `aws_ses_domain_mail_from` ([#2029](https://github.com/terraform-providers/terraform-provider-aws/issues/2029)) -* **New Resource:** `aws_iot_thing_type` ([#3302](https://github.com/terraform-providers/terraform-provider-aws/issues/3302)) - -ENHANCEMENTS: - -* data-source/aws_kms_alias: Always return `target_key_arn` ([#3304](https://github.com/terraform-providers/terraform-provider-aws/issues/3304)) -* resource/aws_autoscaling_policy: Add support for `target_tracking_configuration` ([#2611](https://github.com/terraform-providers/terraform-provider-aws/issues/2611)) -* resource/aws_codebuild_project: Support VPC configuration ([#2547](https://github.com/terraform-providers/terraform-provider-aws/issues/2547)] [[#3324](https://github.com/terraform-providers/terraform-provider-aws/issues/3324)) -* resource/aws_cloudtrail: Add `event_selector` argument ([#2258](https://github.com/terraform-providers/terraform-provider-aws/issues/2258)) -* resource/aws_codedeploy_deployment_group: Validate DeploymentReady and InstanceReady `trigger_events` ([#3412](https://github.com/terraform-providers/terraform-provider-aws/issues/3412)) -* resource/aws_db_parameter_group: Validate underscore `name` during plan ([#3396](https://github.com/terraform-providers/terraform-provider-aws/issues/3396)) -* resource/aws_directory_service_directory Add `edition` argument ([#3421](https://github.com/terraform-providers/terraform-provider-aws/issues/3421)) -* resource/aws_directory_service_directory Validate `size` argument ([#3453](https://github.com/terraform-providers/terraform-provider-aws/issues/3453)) -* resource/aws_dx_connection: Add support for tagging ([#2990](https://github.com/terraform-providers/terraform-provider-aws/issues/2990)) -* resource/aws_dx_connection: Add support for import ([#2992](https://github.com/terraform-providers/terraform-provider-aws/issues/2992)) -* resource/aws_dx_lag: Add support for tagging ([#2990](https://github.com/terraform-providers/terraform-provider-aws/issues/2990)) -* resource/aws_dx_lag: Add support for import ([#2992](https://github.com/terraform-providers/terraform-provider-aws/issues/2992)) -* resource/aws_emr_cluster: Add `autoscaling_policy` argument ([#2877](https://github.com/terraform-providers/terraform-provider-aws/issues/2877)) -* resource/aws_emr_cluster: Add `scale_down_behavior` argument ([#3063](https://github.com/terraform-providers/terraform-provider-aws/issues/3063)) -* resource/aws_instance: Expose reason of `shutting-down` state during creation ([#3371](https://github.com/terraform-providers/terraform-provider-aws/issues/3371)) -* resource/aws_instance: Include size of user_data in validation error message ([#2971](https://github.com/terraform-providers/terraform-provider-aws/issues/2971)) -* resource/aws_instance: Remove extra API call on creation for SGs ([#3426](https://github.com/terraform-providers/terraform-provider-aws/issues/3426)) -* resource/aws_lambda_function: Recompute `version` and `qualified_arn` attributes on publish ([#3032](https://github.com/terraform-providers/terraform-provider-aws/issues/3032)) -* resource/aws_lb_target_group: Allow stickiness block set to false with TCP ([#2954](https://github.com/terraform-providers/terraform-provider-aws/issues/2954)) -* resource/aws_lb_listener_rule: Validate `priority` over 50000 ([#3379](https://github.com/terraform-providers/terraform-provider-aws/issues/3379)) -* resource/aws_lb_listener_rule: Make `priority` argument optional ([#3219](https://github.com/terraform-providers/terraform-provider-aws/issues/3219)) -* resource/aws_rds_cluster: Add `hosted_zone_id` attribute ([#3267](https://github.com/terraform-providers/terraform-provider-aws/issues/3267)) -* resource/aws_rds_cluster: Add support for `source_region` (encrypted cross-region replicas) ([#3415](https://github.com/terraform-providers/terraform-provider-aws/issues/3415)) -* resource/aws_rds_cluster_instance: Support `availability_zone` ([#2812](https://github.com/terraform-providers/terraform-provider-aws/issues/2812)) -* resource/aws_rds_cluster_parameter_group: Validate underscore `name` during plan ([#3396](https://github.com/terraform-providers/terraform-provider-aws/issues/3396)) -* resource/aws_route53_record Add `allow_overwrite` argument ([#2926](https://github.com/terraform-providers/terraform-provider-aws/issues/2926)) -* resource/aws_s3_bucket Ssupport for SSE-KMS replication configuration ([#2625](https://github.com/terraform-providers/terraform-provider-aws/issues/2625)) -* resource/aws_spot_fleet_request: Validate `iam_fleet_role` as ARN during plan ([#3431](https://github.com/terraform-providers/terraform-provider-aws/issues/3431)) -* resource/aws_sqs_queue: Validate `name` during plan ([#2837](https://github.com/terraform-providers/terraform-provider-aws/issues/2837)) -* resource/aws_ssm_association: Allow updating `targets` ([#2807](https://github.com/terraform-providers/terraform-provider-aws/issues/2807)) -* resource/aws_service_discovery_service: Support routing policy and update the type of DNS record ([#3273](https://github.com/terraform-providers/terraform-provider-aws/issues/3273)) - -BUG FIXES: - -* data-source/aws_elb_service_account: Correct GovCloud region ([#3315](https://github.com/terraform-providers/terraform-provider-aws/issues/3315)) -* resource/aws_acm_certificate_validation: Prevent crash on `validation_record_fqdns` ([#3336](https://github.com/terraform-providers/terraform-provider-aws/issues/3336)) -* resource/aws_acm_certificate_validation: Fix `validation_record_fqdns` handling with combined root and wildcard requests ([#3366](https://github.com/terraform-providers/terraform-provider-aws/issues/3366)) -* resource/aws_autoscaling_policy: `cooldown` with zero value not set correctly ([#2809](https://github.com/terraform-providers/terraform-provider-aws/issues/2809)) -* resource/aws_cloudtrail: Now respects initial `include_global_service_events = false` ([#2817](https://github.com/terraform-providers/terraform-provider-aws/issues/2817)) -* resource/aws_dynamodb_table: Retry deletion on ResourceInUseException ([#3355](https://github.com/terraform-providers/terraform-provider-aws/issues/3355)) -* resource/aws_dx_lag: `number_of_connections` deprecated (made Optional). Omitting field may now prevent spurious diffs. ([#3367](https://github.com/terraform-providers/terraform-provider-aws/issues/3367)) -* resource/aws_ecs_service: Retry DescribeServices after creation ([#3387](https://github.com/terraform-providers/terraform-provider-aws/issues/3387)) -* resource/aws_ecs_service: Fix reading `load_balancer` into state ([#3502](https://github.com/terraform-providers/terraform-provider-aws/issues/3502)) -* resource/aws_elasticsearch_domain: Retry creation on `ValidationException` ([#3375](https://github.com/terraform-providers/terraform-provider-aws/issues/3375)) -* resource/aws_iam_user_ssh_key: Correctly set status after creation ([#3390](https://github.com/terraform-providers/terraform-provider-aws/issues/3390)) -* resource/aws_instance: Bump deletion timeout to 20mins ([#3452](https://github.com/terraform-providers/terraform-provider-aws/issues/3452)) -* resource/aws_kinesis_firehose_delivery_stream: Retry on additional IAM eventual consistency errors ([#3381](https://github.com/terraform-providers/terraform-provider-aws/issues/3381)) -* resource/aws_route53_record: Trim trailing dot during import ([#3321](https://github.com/terraform-providers/terraform-provider-aws/issues/3321)) -* resource/aws_s3_bucket: Prevent crashes on location and replication read retry timeouts ([#3338](https://github.com/terraform-providers/terraform-provider-aws/issues/3338)) -* resource/aws_s3_bucket: Always set replication_configuration in state ([#3349](https://github.com/terraform-providers/terraform-provider-aws/issues/3349)) -* resource/aws_security_group: Allow empty rule description ([#2846](https://github.com/terraform-providers/terraform-provider-aws/issues/2846)) -* resource/aws_sns_topic: Fix exit after updating first attribute ([#3360](https://github.com/terraform-providers/terraform-provider-aws/issues/3360)) -* resource/aws_spot_instance_request: Bump delete timeout to 20mins ([#3435](https://github.com/terraform-providers/terraform-provider-aws/issues/3435)) -* resource/aws_sqs_queue: Skip SQS ListQueueTags in aws-us-gov partition ([#3376](https://github.com/terraform-providers/terraform-provider-aws/issues/3376)) -* resource/aws_vpc_endpoint: Treat pending as expected state during deletion ([#3370](https://github.com/terraform-providers/terraform-provider-aws/issues/3370)) -* resource/aws_vpc_peering_connection: Treat `pending-acceptance` as expected during deletion ([#3393](https://github.com/terraform-providers/terraform-provider-aws/issues/3393)) -* resource/aws_cognito_user_pool_client: support `USER_PASSWORD_AUTH` for explicit_auth_flows ([#3417](https://github.com/terraform-providers/terraform-provider-aws/issues/3417)) - -## 1.9.0 (February 09, 2018) - -NOTES: - -* data-source/aws_region: `current` field is deprecated and the data source defaults to the provider region if no endpoint or name is specified ([#3157](https://github.com/terraform-providers/terraform-provider-aws/issues/3157)) -* data-source/aws_iam_policy_document: Statements are now de-duplicated per `Sid`s ([#2890](https://github.com/terraform-providers/terraform-provider-aws/issues/2890)) - -FEATURES: - -* **New Data Source:** `aws_elastic_beanstalk_hosted_zone` ([#3208](https://github.com/terraform-providers/terraform-provider-aws/issues/3208)) -* **New Data Source:** `aws_iam_policy` ([#1999](https://github.com/terraform-providers/terraform-provider-aws/issues/1999)) -* **New Resource:** `aws_acm_certificate` ([#2813](https://github.com/terraform-providers/terraform-provider-aws/issues/2813)) -* **New Resource:** `aws_acm_certificate_validation` ([#2813](https://github.com/terraform-providers/terraform-provider-aws/issues/2813)) -* **New Resource:** `aws_api_gateway_documentation_version` ([#3287](https://github.com/terraform-providers/terraform-provider-aws/issues/3287)) -* **New Resource:** `aws_cloud9_environment_ec2` ([#3291](https://github.com/terraform-providers/terraform-provider-aws/issues/3291)) -* **New Resource:** `aws_cognito_user_group` ([#3010](https://github.com/terraform-providers/terraform-provider-aws/issues/3010)) -* **New Resource:** `aws_dynamodb_table_item` ([#3238](https://github.com/terraform-providers/terraform-provider-aws/issues/3238)) -* **New Resource:** `aws_guardduty_ipset` ([#3161](https://github.com/terraform-providers/terraform-provider-aws/issues/3161)) -* **New Resource:** `aws_guardduty_threatintelset` ([#3200](https://github.com/terraform-providers/terraform-provider-aws/issues/3200)) -* **New Resource:** `aws_iot_topic_rule` ([#1858](https://github.com/terraform-providers/terraform-provider-aws/issues/1858)) -* **New Resource:** `aws_sns_platform_application` ([#1101](https://github.com/terraform-providers/terraform-provider-aws/issues/1101)] [[#3283](https://github.com/terraform-providers/terraform-provider-aws/issues/3283)) -* **New Resource:** `aws_vpc_endpoint_service_allowed_principal` ([#2515](https://github.com/terraform-providers/terraform-provider-aws/issues/2515)) -* **New Resource:** `aws_vpc_endpoint_service_connection_notification` ([#2515](https://github.com/terraform-providers/terraform-provider-aws/issues/2515)) -* **New Resource:** `aws_vpc_endpoint_service` ([#2515](https://github.com/terraform-providers/terraform-provider-aws/issues/2515)) -* **New Resource:** `aws_vpc_endpoint_subnet_association` ([#2515](https://github.com/terraform-providers/terraform-provider-aws/issues/2515)) - -ENHANCEMENTS: - -* provider: Automatically determine AWS partition from configured region ([#3173](https://github.com/terraform-providers/terraform-provider-aws/issues/3173)) -* provider: Automatically validate new regions from AWS SDK ([#3159](https://github.com/terraform-providers/terraform-provider-aws/issues/3159)) -* data-source/aws_acm_certificate Add `most_recent` attribute for filtering ([#1837](https://github.com/terraform-providers/terraform-provider-aws/issues/1837)) -* data-source/aws_iam_policy_document: Support layering via source_json and override_json attributes ([#2890](https://github.com/terraform-providers/terraform-provider-aws/issues/2890)) -* data-source/aws_lb_listener: Support load_balancer_arn and port arguments ([#2886](https://github.com/terraform-providers/terraform-provider-aws/issues/2886)) -* data-source/aws_network_interface: Add filter attribute ([#2851](https://github.com/terraform-providers/terraform-provider-aws/issues/2851)) -* data-source/aws_region: Remove EC2 API call and default to current if no endpoint or name specified ([#3157](https://github.com/terraform-providers/terraform-provider-aws/issues/3157)) -* data-source/aws_vpc_endpoint: Support AWS PrivateLink ([#2515](https://github.com/terraform-providers/terraform-provider-aws/issues/2515)) -* data-source/aws_vpc_endpoint_service: Support AWS PrivateLink ([#2515](https://github.com/terraform-providers/terraform-provider-aws/issues/2515)) -* resource/aws_athena_named_query: Support import ([#3231](https://github.com/terraform-providers/terraform-provider-aws/issues/3231)) -* resource/aws_dynamodb_table: Add custom creation timeout ([#3195](https://github.com/terraform-providers/terraform-provider-aws/issues/3195)) -* resource/aws_dynamodb_table: Validate attribute types ([#3188](https://github.com/terraform-providers/terraform-provider-aws/issues/3188)) -* resource/aws_ecr_lifecycle_policy: Support import ([#3246](https://github.com/terraform-providers/terraform-provider-aws/issues/3246)) -* resource/aws_ecs_service: Support import ([#2764](https://github.com/terraform-providers/terraform-provider-aws/issues/2764)) -* resource/aws_ecs_service: Add public_assign_ip argument for Fargate services ([#2559](https://github.com/terraform-providers/terraform-provider-aws/issues/2559)) -* resource/aws_kinesis_firehose_delivery_stream: Add splunk configuration ([#3117](https://github.com/terraform-providers/terraform-provider-aws/issues/3117)) -* resource/aws_mq_broker: Validate user password ([#3164](https://github.com/terraform-providers/terraform-provider-aws/issues/3164)) -* resource/aws_service_discovery_public_dns_namespace: Support import ([#3229](https://github.com/terraform-providers/terraform-provider-aws/issues/3229)) -* resource/aws_service_discovery_service: Support import ([#3227](https://github.com/terraform-providers/terraform-provider-aws/issues/3227)) -* resource/aws_rds_cluster: Add support for Aurora MySQL 5.7 ([#3278](https://github.com/terraform-providers/terraform-provider-aws/issues/3278)) -* resource/aws_sns_topic: Add support for delivery status ([#2872](https://github.com/terraform-providers/terraform-provider-aws/issues/2872)) -* resource/aws_sns_topic: Add support for name prefixes and fully generated names ([#2753](https://github.com/terraform-providers/terraform-provider-aws/issues/2753)) -* resource/aws_sns_topic_subscription: Support filter policy ([#2806](https://github.com/terraform-providers/terraform-provider-aws/issues/2806)) -* resource/aws_ssm_resource_data_sync: Support import ([#3232](https://github.com/terraform-providers/terraform-provider-aws/issues/3232)) -* resource/aws_vpc_endpoint: Support AWS PrivateLink ([#2515](https://github.com/terraform-providers/terraform-provider-aws/issues/2515)) -* resource/aws_vpc_endpoint_service: Support AWS PrivateLink ([#2515](https://github.com/terraform-providers/terraform-provider-aws/issues/2515)) -* resource/aws_vpn_gateway: Add support for Amazon side private ASN ([#1888](https://github.com/terraform-providers/terraform-provider-aws/issues/1888)) - -BUG FIXES: - -* data-source/aws_kms_alias: Prevent crash on aliases without target key ([#3203](https://github.com/terraform-providers/terraform-provider-aws/issues/3203)) -* data-source/aws_ssm_parameter: Fix wrong arn attribute for full path parameter names ([#3211](https://github.com/terraform-providers/terraform-provider-aws/issues/3211)) -* resource/aws_instance: Fix perpertual diff on default VPC instances using vpc_security_group_ids ([#2338](https://github.com/terraform-providers/terraform-provider-aws/issues/2338)) -* resource/aws_codebuild_project: Prevent crash when using source auth configuration ([#3271](https://github.com/terraform-providers/terraform-provider-aws/issues/3271)) -* resource/aws_cognito_identity_pool_roles_attachment: Fix validation for Token types ([#2894](https://github.com/terraform-providers/terraform-provider-aws/issues/2894)) -* resource/aws_db_parameter_group: fix permanent diff when specifying parameters with database-default values ([#3182](https://github.com/terraform-providers/terraform-provider-aws/issues/3182)) -* resource/aws_ecs_service: Retry only on ECS and IAM related InvalidParameterException ([#3240](https://github.com/terraform-providers/terraform-provider-aws/issues/3240)) -* resource/aws_kinesis_firehose_delivery_stream: Prevent crashes on empty CloudWatchLoggingOptions ([#3301](https://github.com/terraform-providers/terraform-provider-aws/issues/3301)) -* resource/aws_kinesis_firehose_delivery_stream: Fix extended_s3_configuration kms_key_arn handling from AWS API ([#3301](https://github.com/terraform-providers/terraform-provider-aws/issues/3301)) -* resource/aws_kinesis_stream: Retry deletion on `LimitExceededException` ([#3108](https://github.com/terraform-providers/terraform-provider-aws/issues/3108)) -* resource/aws_route53_record: Fix dualstack alias name regression trimming too many characters ([#3187](https://github.com/terraform-providers/terraform-provider-aws/issues/3187)) -* resource/aws_ses_template: Send only specified attributes for update ([#3214](https://github.com/terraform-providers/terraform-provider-aws/issues/3214)) -* resource/aws_dynamodb_table: Allow disabling stream with empty `stream_view_type` ([#3197](https://github.com/terraform-providers/terraform-provider-aws/issues/3197)] [[#3224](https://github.com/terraform-providers/terraform-provider-aws/issues/3224)) -* resource/aws_dx_connection_association: Retry disassociation ([#3212](https://github.com/terraform-providers/terraform-provider-aws/issues/3212)) -* resource/aws_volume_attachment: Allow updating `skip_destroy` and `force_detach` ([#2810](https://github.com/terraform-providers/terraform-provider-aws/issues/2810)) - -## 1.8.0 (January 29, 2018) - -FEATURES: - -* **New Resource:** `aws_dynamodb_global_table` ([#2517](https://github.com/terraform-providers/terraform-provider-aws/issues/2517)) -* **New Resource:** `aws_gamelift_build` ([#2843](https://github.com/terraform-providers/terraform-provider-aws/issues/2843)) - -ENHANCEMENTS: - -* provider: `cn-northwest-1` region is now supported ([#3142](https://github.com/terraform-providers/terraform-provider-aws/issues/3142)) -* data-source/aws_kms_alias: Add target_key_arn attribute ([#2551](https://github.com/terraform-providers/terraform-provider-aws/issues/2551)) -* resource/aws_api_gateway_integration: Allow update of content_handling attributes ([#3123](https://github.com/terraform-providers/terraform-provider-aws/issues/3123)) -* resource/aws_appautoscaling_target: Support updating max_capacity, min_capacity, and role_arn attributes ([#2950](https://github.com/terraform-providers/terraform-provider-aws/issues/2950)) -* resource/aws_cloudwatch_log_subscription_filter: Add support for distribution ([#3046](https://github.com/terraform-providers/terraform-provider-aws/issues/3046)) -* resource/aws_cognito_user_pool: support pre_token_generation in lambda_config ([#3093](https://github.com/terraform-providers/terraform-provider-aws/issues/3093)) -* resource/aws_elasticsearch_domain: Add support for encrypt_at_rest ([#2632](https://github.com/terraform-providers/terraform-provider-aws/issues/2632)) -* resource/aws_emr_cluster: Support CustomAmiId ([#2766](https://github.com/terraform-providers/terraform-provider-aws/issues/2766)) -* resource/aws_kms_alias: Add target_key_arn attribute ([#3096](https://github.com/terraform-providers/terraform-provider-aws/issues/3096)) -* resource/aws_route: Allow adding IPv6 routes to instances and network interfaces ([#2265](https://github.com/terraform-providers/terraform-provider-aws/issues/2265)) -* resource/aws_sqs_queue: Retry queue creation on QueueDeletedRecently error ([#3113](https://github.com/terraform-providers/terraform-provider-aws/issues/3113)) -* resource/aws_vpn_connection: Add inside CIDR and pre-shared key attributes ([#1862](https://github.com/terraform-providers/terraform-provider-aws/issues/1862)) - -BUG FIXES: - -* resource/aws_appautoscaling_policy: Support additional predefined metric types in validation [[#3122](https://github.com/terraform-providers/terraform-provider-aws/issues/3122)]] -* resource/aws_dynamodb_table: Recognize changes in `non_key_attributes` ([#3136](https://github.com/terraform-providers/terraform-provider-aws/issues/3136)) -* resource/aws_ebs_snapshot: Fix `kms_key_id` attribute handling ([#3085](https://github.com/terraform-providers/terraform-provider-aws/issues/3085)) -* resource/aws_eip_association: Retry association for pending instances ([#3072](https://github.com/terraform-providers/terraform-provider-aws/issues/3072)) -* resource/aws_elastic_beanstalk_application: Prevent crash on reading missing application ([#3171](https://github.com/terraform-providers/terraform-provider-aws/issues/3171)) -* resource/aws_kinesis_firehose_delivery_stream: Prevent panic on missing S3 configuration prefix ([#3073](https://github.com/terraform-providers/terraform-provider-aws/issues/3073)) -* resource/aws_lambda_function: Retry updates for IAM eventual consistency ([#3116](https://github.com/terraform-providers/terraform-provider-aws/issues/3116)) -* resource/aws_route53_record: Suppress uppercase alias name diff ([#3119](https://github.com/terraform-providers/terraform-provider-aws/issues/3119)) -* resource/aws_sqs_queue_policy: Prevent missing policy error on read ([#2739](https://github.com/terraform-providers/terraform-provider-aws/issues/2739)) -* resource/aws_rds_cluster: Retry deletion on InvalidDBClusterStateFault ([#3028](https://github.com/terraform-providers/terraform-provider-aws/issues/3028)) - -## 1.7.1 (January 19, 2018) - -BUG FIXES: - -* data-source/aws_db_snapshot: Prevent crash on unfinished snapshots ([#2960](https://github.com/terraform-providers/terraform-provider-aws/issues/2960)) -* resource/aws_cloudfront_distribution: Retry deletion on DistributionNotDisabled ([#3034](https://github.com/terraform-providers/terraform-provider-aws/issues/3034)) -* resource/aws_codebuild_project: Prevent crash on empty source buildspec and location ([#3011](https://github.com/terraform-providers/terraform-provider-aws/issues/3011)) -* resource/aws_codepipeline: Prevent crash on empty artifacts ([#2998](https://github.com/terraform-providers/terraform-provider-aws/issues/2998)) -* resource/aws_appautoscaling_policy: Match correct policy when multiple policies with same name and service ([#3012](https://github.com/terraform-providers/terraform-provider-aws/issues/3012)) -* resource/aws_eip: Do not disassociate EIP on tags-only update ([#2975](https://github.com/terraform-providers/terraform-provider-aws/issues/2975)) -* resource/aws_elastic_beanstalk_application: Retry DescribeApplication after creation ([#3064](https://github.com/terraform-providers/terraform-provider-aws/issues/3064)) -* resource/aws_emr_cluster: Retry creation on `ValidationException` (IAM) ([#3027](https://github.com/terraform-providers/terraform-provider-aws/issues/3027)) -* resource/aws_emr_cluster: Retry creation on `AccessDeniedException` (IAM) ([#3050](https://github.com/terraform-providers/terraform-provider-aws/issues/3050)) -* resource/aws_iam_instance_profile: Allow cleanup during destruction without refresh ([#2983](https://github.com/terraform-providers/terraform-provider-aws/issues/2983)) -* resource/aws_iam_role: Prevent missing attached policy results ([#2857](https://github.com/terraform-providers/terraform-provider-aws/issues/2857)) -* resource/aws_iam_user: Prevent state removal during name attribute update ([#2979](https://github.com/terraform-providers/terraform-provider-aws/issues/2979)) -* resource/aws_iam_user: Allow path attribute update ([#2940](https://github.com/terraform-providers/terraform-provider-aws/issues/2940)) -* resource/aws_iam_user_policy: Fix updates with generated policy names and validate JSON ([#3031](https://github.com/terraform-providers/terraform-provider-aws/issues/3031)) -* resource/aws_instance: Retry IAM instance profile (re)association for eventual consistency on update ([#3055](https://github.com/terraform-providers/terraform-provider-aws/issues/3055)) -* resource/aws_lambda_function: Make EC2 rate limit errors retryable on update ([#2964](https://github.com/terraform-providers/terraform-provider-aws/issues/2964)) -* resource/aws_lambda_function: Retry creation on EC2 throttle error ([#3062](https://github.com/terraform-providers/terraform-provider-aws/issues/3062)) -* resource/aws_lb_target_group: Allow a blank health check path, for TCP healthchecks ([#2980](https://github.com/terraform-providers/terraform-provider-aws/issues/2980)) -* resource/aws_sns_topic_subscription: Prevent crash on subscription attribute update ([#2967](https://github.com/terraform-providers/terraform-provider-aws/issues/2967)) -* resource/aws_kinesis_firehose_delivery_stream: Fix import for S3 destinations ([#2970](https://github.com/terraform-providers/terraform-provider-aws/issues/2970)) -* resource/aws_kinesis_firehose_delivery_stream: Prevent crash on empty Redshift's S3 Backup Description ([#2970](https://github.com/terraform-providers/terraform-provider-aws/issues/2970)) -* resource/aws_kinesis_firehose_delivery_stream: Detect drifts in `processing_configuration` ([#2970](https://github.com/terraform-providers/terraform-provider-aws/issues/2970)) -* resource/aws_kinesis_firehose_delivery_stream: Prevent crash on empty CloudWatch logging opts ([#3052](https://github.com/terraform-providers/terraform-provider-aws/issues/3052)) - -## 1.7.0 (January 12, 2018) - -FEATURES: - -* **New Resource:** `aws_api_gateway_documentation_part` ([#2893](https://github.com/terraform-providers/terraform-provider-aws/issues/2893)) -* **New Resource:** `aws_cloudwatch_event_permission` ([#2888](https://github.com/terraform-providers/terraform-provider-aws/issues/2888)) -* **New Resource:** `aws_cognito_user_pool_client` ([#1803](https://github.com/terraform-providers/terraform-provider-aws/issues/1803)) -* **New Resource:** `aws_cognito_user_pool_domain` ([#2325](https://github.com/terraform-providers/terraform-provider-aws/issues/2325)) -* **New Resource:** `aws_glue_catalog_database` ([#2175](https://github.com/terraform-providers/terraform-provider-aws/issues/2175)) -* **New Resource:** `aws_guardduty_detector` ([#2524](https://github.com/terraform-providers/terraform-provider-aws/issues/2524)) -* **New Resource:** `aws_guardduty_member` ([#2911](https://github.com/terraform-providers/terraform-provider-aws/issues/2911)) -* **New Resource:** `aws_route53_query_log` ([#2770](https://github.com/terraform-providers/terraform-provider-aws/issues/2770)) -* **New Resource:** `aws_service_discovery_service` ([#2613](https://github.com/terraform-providers/terraform-provider-aws/issues/2613)) - -ENHANCEMENTS: - -* provider: `eu-west-3` is now supported ([#2707](https://github.com/terraform-providers/terraform-provider-aws/issues/2707)) -* provider: Endpoints can now be specified for ACM, ECR, ECS, STS and Route 53 ([#2795](https://github.com/terraform-providers/terraform-provider-aws/issues/2795)) -* provider: Endpoints can now be specified for API Gateway and Lambda ([#2641](https://github.com/terraform-providers/terraform-provider-aws/issues/2641)) -* data-source/aws_iam_server_certificate: Add support for retrieving public key ([#2749](https://github.com/terraform-providers/terraform-provider-aws/issues/2749)) -* data-source/aws_vpc_peering_connection: Add support for cross-region VPC peering ([#2508](https://github.com/terraform-providers/terraform-provider-aws/issues/2508)) -* data-source/aws_ssm_parameter: Support returning raw encrypted SecureString value ([#2777](https://github.com/terraform-providers/terraform-provider-aws/issues/2777)) -* resource/aws_kinesis_firehose_delivery_stream: Import is now supported ([#2082](https://github.com/terraform-providers/terraform-provider-aws/issues/2082)) -* resource/aws_cognito_user_pool: The ARN for the pool is now computed and exposed as an attribute ([#2723](https://github.com/terraform-providers/terraform-provider-aws/issues/2723)) -* resource/aws_directory_service_directory: Add `security_group_id` field ([#2688](https://github.com/terraform-providers/terraform-provider-aws/issues/2688)) -* resource/aws_rds_cluster_instance: Support Performance Insights ([#2331](https://github.com/terraform-providers/terraform-provider-aws/issues/2331)) -* resource/aws_rds_cluster_instance: Set `db_subnet_group_name` in state on read if available ([#2606](https://github.com/terraform-providers/terraform-provider-aws/issues/2606)) -* resource/aws_eip: Tagging is now supported ([#2768](https://github.com/terraform-providers/terraform-provider-aws/issues/2768)) -* resource/aws_codepipeline: ARN is now exposed as an attribute ([#2773](https://github.com/terraform-providers/terraform-provider-aws/issues/2773)) -* resource/aws_appautoscaling_scheduled_action: `min_capacity` argument is now honoured ([#2794](https://github.com/terraform-providers/terraform-provider-aws/issues/2794)) -* resource/aws_rds_cluster: Clusters in the `resetting-master-credentials` state no longer cause an error ([#2791](https://github.com/terraform-providers/terraform-provider-aws/issues/2791)) -* resource/aws_cloudwatch_metric_alarm: Support optional datapoints_to_alarm configuration ([#2609](https://github.com/terraform-providers/terraform-provider-aws/issues/2609)) -* resource/aws_ses_event_destination: Add support for SNS destinations ([#1737](https://github.com/terraform-providers/terraform-provider-aws/issues/1737)) -* resource/aws_iam_role: Delete inline policies when `force_detach_policies = true` ([#2388](https://github.com/terraform-providers/terraform-provider-aws/issues/2388)) -* resource/aws_lb_target_group: Improve `health_check` validation ([#2580](https://github.com/terraform-providers/terraform-provider-aws/issues/2580)) -* resource/aws_ecs_service: Add `health_check_grace_period_seconds` attribute ([#2788](https://github.com/terraform-providers/terraform-provider-aws/issues/2788)) -* resource/aws_vpc_peering_connection: Add support for cross-region VPC peering ([#2508](https://github.com/terraform-providers/terraform-provider-aws/issues/2508)) -* resource/aws_vpc_peering_connection_accepter: Add support for cross-region VPC peering ([#2508](https://github.com/terraform-providers/terraform-provider-aws/issues/2508)) -* resource/aws_elasticsearch_domain: export kibana endpoint ([#2804](https://github.com/terraform-providers/terraform-provider-aws/issues/2804)) -* resource/aws_ssm_association: Allow for multiple targets ([#2297](https://github.com/terraform-providers/terraform-provider-aws/issues/2297)) -* resource/aws_instance: Add computed field for volume_id of block device ([#1489](https://github.com/terraform-providers/terraform-provider-aws/issues/1489)) -* resource/aws_api_gateway_integration: Allow update of URI attributes ([#2834](https://github.com/terraform-providers/terraform-provider-aws/issues/2834)) -* resource/aws_ecs_cluster: Support resource import ([#2762](https://github.com/terraform-providers/terraform-provider-aws/issues/2762)) - -BUG FIXES: - -* resource/aws_cognito_user_pool: Update Cognito email message length to 20,000 ([#2692](https://github.com/terraform-providers/terraform-provider-aws/issues/2692)) -* resource/aws_volume_attachment: Changing device name without changing volume or instance ID now correctly produces a diff ([#2720](https://github.com/terraform-providers/terraform-provider-aws/issues/2720)) -* resource/aws_s3_bucket_object: Object tagging is now supported in GovCloud ([#2665](https://github.com/terraform-providers/terraform-provider-aws/issues/2665)) -* resource/aws_elasticsearch_domain: Fixed a crash when no Cloudwatch log group is configured ([#2787](https://github.com/terraform-providers/terraform-provider-aws/issues/2787)) -* resource/aws_s3_bucket_policy: Set the resource ID after successful creation ([#2820](https://github.com/terraform-providers/terraform-provider-aws/issues/2820)) -* resource/aws_db_event_subscription: Set the source type when updating categories ([#2833](https://github.com/terraform-providers/terraform-provider-aws/issues/2833)) -* resource/aws_db_parameter_group: Remove group from state if it's gone ([#2868](https://github.com/terraform-providers/terraform-provider-aws/issues/2868)) -* resource/aws_appautoscaling_target: Make `role_arn` optional & computed ([#2889](https://github.com/terraform-providers/terraform-provider-aws/issues/2889)) -* resource/aws_ssm_maintenance_window: Respect `enabled` during updates ([#2818](https://github.com/terraform-providers/terraform-provider-aws/issues/2818)) -* resource/aws_lb_target_group: Fix max prefix length check ([#2790](https://github.com/terraform-providers/terraform-provider-aws/issues/2790)) -* resource/aws_config_delivery_channel: Retry deletion ([#2910](https://github.com/terraform-providers/terraform-provider-aws/issues/2910)) -* resource/aws_lb+aws_elb: Fix regression with undefined `name` ([#2939](https://github.com/terraform-providers/terraform-provider-aws/issues/2939)) -* resource/aws_lb_target_group: Fix validation rules for LB's healthcheck ([#2906](https://github.com/terraform-providers/terraform-provider-aws/issues/2906)) -* provider: Fix regression affecting empty Optional+Computed fields ([#2348](https://github.com/terraform-providers/terraform-provider-aws/issues/2348)) - -## 1.6.0 (December 18, 2017) - -FEATURES: - -* **New Data Source:** `aws_network_interface` ([#2316](https://github.com/terraform-providers/terraform-provider-aws/issues/2316)) -* **New Data Source:** `aws_elb` ([#2004](https://github.com/terraform-providers/terraform-provider-aws/issues/2004)) -* **New Resource:** `aws_dx_connection_association` ([#2360](https://github.com/terraform-providers/terraform-provider-aws/issues/2360)) -* **New Resource:** `aws_appautoscaling_scheduled_action` ([#2231](https://github.com/terraform-providers/terraform-provider-aws/issues/2231)) -* **New Resource:** `aws_cloudwatch_log_resource_policy` ([#2243](https://github.com/terraform-providers/terraform-provider-aws/issues/2243)) -* **New Resource:** `aws_media_store_container` ([#2448](https://github.com/terraform-providers/terraform-provider-aws/issues/2448)) -* **New Resource:** `aws_service_discovery_public_dns_namespace` ([#2569](https://github.com/terraform-providers/terraform-provider-aws/issues/2569)) -* **New Resource:** `aws_service_discovery_private_dns_namespace` ([#2589](https://github.com/terraform-providers/terraform-provider-aws/issues/2589)) - -IMPROVEMENTS: - -* resource/aws_ssm_association: Add `association_name` ([#2257](https://github.com/terraform-providers/terraform-provider-aws/issues/2257)) -* resource/aws_ecs_service: Add `network_configuration` ([#2299](https://github.com/terraform-providers/terraform-provider-aws/issues/2299)) -* resource/aws_lambda_function: Add `reserved_concurrent_executions` ([#2504](https://github.com/terraform-providers/terraform-provider-aws/issues/2504)) -* resource/aws_ecs_service: Add `launch_type` (Fargate support) ([#2483](https://github.com/terraform-providers/terraform-provider-aws/issues/2483)) -* resource/aws_ecs_task_definition: Add `cpu`, `memory`, `execution_role_arn` & `requires_compatibilities` (Fargate support) ([#2483](https://github.com/terraform-providers/terraform-provider-aws/issues/2483)) -* resource/aws_ecs_cluster: Add arn attribute ([#2552](https://github.com/terraform-providers/terraform-provider-aws/issues/2552)) -* resource/aws_elasticache_security_group: Add import support ([#2277](https://github.com/terraform-providers/terraform-provider-aws/issues/2277)) -* resource/aws_sqs_queue_policy: Support import by queue URL ([#2544](https://github.com/terraform-providers/terraform-provider-aws/issues/2544)) -* resource/aws_elasticsearch_domain: Add `log_publishing_options` ([#2285](https://github.com/terraform-providers/terraform-provider-aws/issues/2285)) -* resource/aws_athena_database: Add `force_destroy` field ([#2363](https://github.com/terraform-providers/terraform-provider-aws/issues/2363)) -* resource/aws_elasticache_replication_group: Add support for Redis auth, in-transit and at-rest encryption ([#2090](https://github.com/terraform-providers/terraform-provider-aws/issues/2090)) -* resource/aws_s3_bucket: Add `server_side_encryption_configuration` block ([#2472](https://github.com/terraform-providers/terraform-provider-aws/issues/2472)) - -BUG FIXES: - -* data-source/aws_instance: Set `placement_group` if available ([#2400](https://github.com/terraform-providers/terraform-provider-aws/issues/2400)) -* resource/aws_elasticache_parameter_group: Add StateFunc to make name lowercase ([#2426](https://github.com/terraform-providers/terraform-provider-aws/issues/2426)) -* resource/aws_elasticache_replication_group: Modify validation, make replication_group_id lowercase ([#2432](https://github.com/terraform-providers/terraform-provider-aws/issues/2432)) -* resource/aws_db_instance: Treat `storage-optimization` as valid state ([#2409](https://github.com/terraform-providers/terraform-provider-aws/issues/2409)) -* resource/aws_dynamodb_table: Ensure `ttl` is properly read ([#2452](https://github.com/terraform-providers/terraform-provider-aws/issues/2452)) -* resource/aws_lb_target_group: fixes to behavior based on protocol type ([#2380](https://github.com/terraform-providers/terraform-provider-aws/issues/2380)) -* resource/aws_mq_broker: Fix crash in hashing function ([#2598](https://github.com/terraform-providers/terraform-provider-aws/issues/2598)) -* resource/aws_ebs_volume_attachment: Allow attachments to instances which are stopped ([#1444](https://github.com/terraform-providers/terraform-provider-aws/issues/1444)) -* resource/aws_ssm_parameter: Path names with a leading '/' no longer generate incorrect ARNs ([#2604](https://github.com/terraform-providers/terraform-provider-aws/issues/2604)) - -## 1.5.0 (November 29, 2017) - -FEATURES: - -* **New Resource:** `aws_mq_broker` ([#2466](https://github.com/terraform-providers/terraform-provider-aws/issues/2466)) -* **New Resource:** `aws_mq_configuration` ([#2466](https://github.com/terraform-providers/terraform-provider-aws/issues/2466)) - -## 1.4.0 (November 29, 2017) - -BUG FIXES: - -* resource/aws_cognito_user_pool: Fix `email_subject_by_link` ([#2395](https://github.com/terraform-providers/terraform-provider-aws/issues/2395)) -* resource/aws_api_gateway_method_response: Fix conflict exception in API gateway method response ([#2393](https://github.com/terraform-providers/terraform-provider-aws/issues/2393)) -* resource/aws_api_gateway_method: Fix typo `authorization_type` -> `authorization` ([#2430](https://github.com/terraform-providers/terraform-provider-aws/issues/2430)) - -IMPROVEMENTS: - -* data-source/aws_nat_gateway: Add missing address attributes to the schema ([#2209](https://github.com/terraform-providers/terraform-provider-aws/issues/2209)) -* resource/aws_ssm_maintenance_window_target: Change MaxItems of targets ([#2361](https://github.com/terraform-providers/terraform-provider-aws/issues/2361)) -* resource/aws_sfn_state_machine: Support Update State machine call ([#2349](https://github.com/terraform-providers/terraform-provider-aws/issues/2349)) -* resource/aws_instance: Set placement_group in state on read if available ([#2398](https://github.com/terraform-providers/terraform-provider-aws/issues/2398)) - -## 1.3.1 (November 20, 2017) - -BUG FIXES: - -* resource/aws_ecs_task_definition: Fix equivalency comparator ([#2339](https://github.com/terraform-providers/terraform-provider-aws/issues/2339)) -* resource/aws_batch_job_queue: Return errors correctly if deletion fails ([#2322](https://github.com/terraform-providers/terraform-provider-aws/issues/2322)) -* resource/aws_security_group_rule: Parse `description` correctly ([#1959](https://github.com/terraform-providers/terraform-provider-aws/issues/1959)) -* Fixed Cognito Lambda Config Validation for optional ARN configurations ([#2370](https://github.com/terraform-providers/terraform-provider-aws/issues/2370)) -* resource/aws_cognito_identity_pool_roles_attachment: Fix typo "authenticated" -> "unauthenticated" ([#2358](https://github.com/terraform-providers/terraform-provider-aws/issues/2358)) - -## 1.3.0 (November 16, 2017) - -NOTES: - -* resource/aws_redshift_cluster: Field `enable_logging`, `bucket_name` and `s3_key_prefix` were deprecated in favour of a new `logging` block ([#2230](https://github.com/terraform-providers/terraform-provider-aws/issues/2230)) -* resource/aws_lb_target_group: We no longer provide defaults for `health_check`'s `path` nor `matcher` in order to support network load balancers where these arguments aren't valid. Creating _new_ ALB will therefore require you to specify these two arguments. Existing deployments are unaffected. ([#2251](https://github.com/terraform-providers/terraform-provider-aws/issues/2251)) - -FEATURES: - -* **New Data Source:** `aws_rds_cluster` ([#2070](https://github.com/terraform-providers/terraform-provider-aws/issues/2070)) -* **New Data Source:** `aws_elasticache_replication_group` ([#2124](https://github.com/terraform-providers/terraform-provider-aws/issues/2124)) -* **New Data Source:** `aws_instances` ([#2266](https://github.com/terraform-providers/terraform-provider-aws/issues/2266)) -* **New Resource:** `aws_ses_template` ([#2003](https://github.com/terraform-providers/terraform-provider-aws/issues/2003)) -* **New Resource:** `aws_dx_lag` ([#2154](https://github.com/terraform-providers/terraform-provider-aws/issues/2154)) -* **New Resource:** `aws_dx_connection` ([#2173](https://github.com/terraform-providers/terraform-provider-aws/issues/2173)) -* **New Resource:** `aws_athena_database` ([#1922](https://github.com/terraform-providers/terraform-provider-aws/issues/1922)) -* **New Resource:** `aws_athena_named_query` ([#1893](https://github.com/terraform-providers/terraform-provider-aws/issues/1893)) -* **New Resource:** `aws_ssm_resource_data_sync` ([#1895](https://github.com/terraform-providers/terraform-provider-aws/issues/1895)) -* **New Resource:** `aws_cognito_user_pool` ([#1419](https://github.com/terraform-providers/terraform-provider-aws/issues/1419)) - -IMPROVEMENTS: - -* provider: Add support for assuming roles via profiles defined in `~/.aws/config` ([#1608](https://github.com/terraform-providers/terraform-provider-aws/issues/1608)) -* data-source/efs_file_system: Added dns_name ([#2105](https://github.com/terraform-providers/terraform-provider-aws/issues/2105)) -* data-source/aws_ssm_parameter: Add `arn` attribute ([#2273](https://github.com/terraform-providers/terraform-provider-aws/issues/2273)) -* data-source/aws_ebs_volume: Add `arn` attribute ([#2271](https://github.com/terraform-providers/terraform-provider-aws/issues/2271)) -* resource/aws_batch_job_queue: Add validation for `name` ([#2159](https://github.com/terraform-providers/terraform-provider-aws/issues/2159)) -* resource/aws_batch_compute_environment: Improve validation for `compute_environment_name` ([#2159](https://github.com/terraform-providers/terraform-provider-aws/issues/2159)) -* resource/aws_ssm_parameter: Add support for import ([#2234](https://github.com/terraform-providers/terraform-provider-aws/issues/2234)) -* resource/aws_redshift_cluster: Add support for `snapshot_copy` ([#2238](https://github.com/terraform-providers/terraform-provider-aws/issues/2238)) -* resource/aws_ecs_task_definition: Print `container_definitions` as JSON instead of checksum ([#1195](https://github.com/terraform-providers/terraform-provider-aws/issues/1195)) -* resource/aws_ssm_parameter: Add `arn` attribute ([#2273](https://github.com/terraform-providers/terraform-provider-aws/issues/2273)) -* resource/aws_elb: Add listener `ssl_certificate_id` ARN validation ([#2276](https://github.com/terraform-providers/terraform-provider-aws/issues/2276)) -* resource/aws_cloudformation_stack: Support updating `tags` ([#2262](https://github.com/terraform-providers/terraform-provider-aws/issues/2262)) -* resource/aws_elb: Add `arn` attribute ([#2272](https://github.com/terraform-providers/terraform-provider-aws/issues/2272)) -* resource/aws_ebs_volume: Add `arn` attribute ([#2271](https://github.com/terraform-providers/terraform-provider-aws/issues/2271)) - -BUG FIXES: - -* resource/aws_appautoscaling_policy: Retry putting policy on invalid token ([#2135](https://github.com/terraform-providers/terraform-provider-aws/issues/2135)) -* resource/aws_batch_compute_environment: `compute_environment_name` allows hyphens ([#2126](https://github.com/terraform-providers/terraform-provider-aws/issues/2126)) -* resource/aws_batch_job_definition: `name` allows hyphens ([#2126](https://github.com/terraform-providers/terraform-provider-aws/issues/2126)) -* resource/aws_elasticache_parameter_group: Raise timeout for retry on pending changes ([#2134](https://github.com/terraform-providers/terraform-provider-aws/issues/2134)) -* resource/aws_kms_key: Retry GetKeyRotationStatus on NotFoundException ([#2133](https://github.com/terraform-providers/terraform-provider-aws/issues/2133)) -* resource/aws_lb_target_group: Fix issue that prevented using `aws_lb_target_group` with - Network type load balancers ([#2251](https://github.com/terraform-providers/terraform-provider-aws/issues/2251)) -* resource/aws_lb: mark subnets as `ForceNew` for network load balancers ([#2310](https://github.com/terraform-providers/terraform-provider-aws/issues/2310)) -* resource/aws_redshift_cluster: Make master_username ForceNew ([#2202](https://github.com/terraform-providers/terraform-provider-aws/issues/2202)) -* resource/aws_cloudwatch_log_metric_filter: Fix pattern length check ([#2107](https://github.com/terraform-providers/terraform-provider-aws/issues/2107)) -* resource/aws_cloudwatch_log_group: Use ID as name ([#2190](https://github.com/terraform-providers/terraform-provider-aws/issues/2190)) -* resource/aws_elasticsearch_domain: Added ForceNew to vpc_options ([#2157](https://github.com/terraform-providers/terraform-provider-aws/issues/2157)) -* resource/aws_redshift_cluster: Make snapshot identifiers `ForceNew` ([#2212](https://github.com/terraform-providers/terraform-provider-aws/issues/2212)) -* resource/aws_elasticsearch_domain_policy: Fix typo in err code ([#2249](https://github.com/terraform-providers/terraform-provider-aws/issues/2249)) -* resource/aws_appautoscaling_policy: Retry PutScalingPolicy on rate exceeded message ([#2275](https://github.com/terraform-providers/terraform-provider-aws/issues/2275)) -* resource/aws_dynamodb_table: Retry creation on `LimitExceededException` w/ different error message ([#2274](https://github.com/terraform-providers/terraform-provider-aws/issues/2274)) - -## 1.2.0 (October 31, 2017) - -INTERNAL: - -* Remove `id` fields from schema definitions ([#1626](https://github.com/terraform-providers/terraform-provider-aws/issues/1626)) - -FEATURES: - -* **New Resource:** `aws_servicecatalog_portfolio` ([#1694](https://github.com/terraform-providers/terraform-provider-aws/issues/1694)) -* **New Resource:** `aws_ses_domain_dkim` ([#1786](https://github.com/terraform-providers/terraform-provider-aws/issues/1786)) -* **New Resource:** `aws_cognito_identity_pool_roles_attachment` ([#863](https://github.com/terraform-providers/terraform-provider-aws/issues/863)) -* **New Resource:** `aws_ecr_lifecycle_policy` ([#2096](https://github.com/terraform-providers/terraform-provider-aws/issues/2096)) -* **New Data Source:** `aws_nat_gateway` ([#1294](https://github.com/terraform-providers/terraform-provider-aws/issues/1294)) -* **New Data Source:** `aws_dynamodb_table` ([#2062](https://github.com/terraform-providers/terraform-provider-aws/issues/2062)) -* **New Data Source:** `aws_cloudtrail_service_account` ([#1774](https://github.com/terraform-providers/terraform-provider-aws/issues/1774)) - -IMPROVEMENTS: - -* resource/aws_ami: Support configurable timeouts ([#1811](https://github.com/terraform-providers/terraform-provider-aws/issues/1811)) -* resource/ami_copy: Support configurable timeouts ([#1811](https://github.com/terraform-providers/terraform-provider-aws/issues/1811)) -* resource/ami_from_instance: Support configurable timeouts ([#1811](https://github.com/terraform-providers/terraform-provider-aws/issues/1811)) -* data-source/aws_security_group: add description ([#1943](https://github.com/terraform-providers/terraform-provider-aws/issues/1943)) -* resource/aws_cloudfront_distribution: Change the default minimum_protocol_version to TLSv1 ([#1856](https://github.com/terraform-providers/terraform-provider-aws/issues/1856)) -* resource/aws_sns_topic: Support SMS in protocols ([#1813](https://github.com/terraform-providers/terraform-provider-aws/issues/1813)) -* resource/aws_spot_fleet_request: Add support for `tags` ([#2042](https://github.com/terraform-providers/terraform-provider-aws/issues/2042)) -* resource/aws_kinesis_firehose_delivery_stream: Add `s3_backup_mode` option ([#1830](https://github.com/terraform-providers/terraform-provider-aws/issues/1830)) -* resource/aws_elasticsearch_domain: Support VPC configuration ([#1958](https://github.com/terraform-providers/terraform-provider-aws/issues/1958)) -* resource/aws_alb_target_group: Add support for `target_type` ([#1589](https://github.com/terraform-providers/terraform-provider-aws/issues/1589)) -* resource/aws_sqs_queue: Add support for `tags` ([#1987](https://github.com/terraform-providers/terraform-provider-aws/issues/1987)) -* resource/aws_security_group: Add `revoke_rules_on_delete` option to force a security group to revoke - rules before deleting the grou ([#2074](https://github.com/terraform-providers/terraform-provider-aws/issues/2074)) -* resource/aws_cloudwatch_log_metric_filter: Add support for DefaultValue ([#1578](https://github.com/terraform-providers/terraform-provider-aws/issues/1578)) -* resource/aws_emr_cluster: Expose error on `TERMINATED_WITH_ERRORS` ([#2081](https://github.com/terraform-providers/terraform-provider-aws/issues/2081)) - -BUG FIXES: - -* resource/aws_elasticache_parameter_group: Add missing return to retry logic ([#1891](https://github.com/terraform-providers/terraform-provider-aws/issues/1891)) -* resource/aws_batch_job_queue: Wait for update completion when disabling ([#1892](https://github.com/terraform-providers/terraform-provider-aws/issues/1892)) -* resource/aws_snapshot_create_volume_permission: Raise creation timeout to 10mins ([#1894](https://github.com/terraform-providers/terraform-provider-aws/issues/1894)) -* resource/aws_snapshot_create_volume_permission: Raise creation timeout to 20mins ([#2049](https://github.com/terraform-providers/terraform-provider-aws/issues/2049)) -* resource/aws_kms_alias: Retry creation on `NotFoundException` ([#1896](https://github.com/terraform-providers/terraform-provider-aws/issues/1896)) -* resource/aws_kms_key: Retry reading tags on `NotFoundException` ([#1900](https://github.com/terraform-providers/terraform-provider-aws/issues/1900)) -* resource/aws_db_snapshot: Raise creation timeout to 20mins ([#1905](https://github.com/terraform-providers/terraform-provider-aws/issues/1905)) -* resource/aws_lb: Allow assigning EIP to network LB ([#1956](https://github.com/terraform-providers/terraform-provider-aws/issues/1956)) -* resource/aws_s3_bucket: Retry tagging on OperationAborted ([#2008](https://github.com/terraform-providers/terraform-provider-aws/issues/2008)) -* resource/aws_cognito_identity_pool: Fixed refresh of providers ([#2015](https://github.com/terraform-providers/terraform-provider-aws/issues/2015)) -* resource/aws_elasticache_replication_group: Raise creation timeout to 50mins ([#2048](https://github.com/terraform-providers/terraform-provider-aws/issues/2048)) -* resource/aws_api_gateway_usag_plan: Fixed setting of rate_limit ([#2076](https://github.com/terraform-providers/terraform-provider-aws/issues/2076)) -* resource/aws_elastic_beanstalk_application: Expose error leading to failed deletion ([#2080](https://github.com/terraform-providers/terraform-provider-aws/issues/2080)) -* resource/aws_s3_bucket: Accept query strings in redirect hosts ([#2059](https://github.com/terraform-providers/terraform-provider-aws/issues/2059)) - -## 1.1.0 (October 16, 2017) +ENHANCEMENTS -NOTES: +* resource/aws_dms_replication_instance: Add `allow_major_version_upgrade` argument [GH-14550] -* resource/aws_alb_* & data-source/aws_alb_*: In order to support network LBs, ALBs were renamed to `aws_lb_*` due to the way APIs "new" (non-Classic) load balancers are structured in AWS. All existing ALB functionality remains untouched and new resources work the same way. `aws_alb_*` resources are still in place as "aliases", but documentation will only mention `aws_lb_*`. -`aws_alb_*` aliases will be removed in future major version. ([#1806](https://github.com/terraform-providers/terraform-provider-aws/issues/1806)) -* Deprecated: - * data-source/aws_alb - * data-source/aws_alb_listener - * data-source/aws_alb_target_group - * resource/aws_alb - * resource/aws_alb_listener - * resource/aws_alb_listener_rule - * resource/aws_alb_target_group - * resource/aws_alb_target_group_attachment +BUG FIXES -FEATURES: +* resource/aws_apigatewayv2_stage: Set `execution_arn` attribute for HTTP APIs [GH-14638] -* **New Resource:** `aws_batch_job_definition` ([#1710](https://github.com/terraform-providers/terraform-provider-aws/issues/1710)) -* **New Resource:** `aws_batch_job_queue` ([#1710](https://github.com/terraform-providers/terraform-provider-aws/issues/1710)) -* **New Resource:** `aws_lb` ([#1806](https://github.com/terraform-providers/terraform-provider-aws/issues/1806)) -* **New Resource:** `aws_lb_listener` ([#1806](https://github.com/terraform-providers/terraform-provider-aws/issues/1806)) -* **New Resource:** `aws_lb_listener_rule` ([#1806](https://github.com/terraform-providers/terraform-provider-aws/issues/1806)) -* **New Resource:** `aws_lb_target_group` ([#1806](https://github.com/terraform-providers/terraform-provider-aws/issues/1806)) -* **New Resource:** `aws_lb_target_group_attachment` ([#1806](https://github.com/terraform-providers/terraform-provider-aws/issues/1806)) -* **New Data Source:** `aws_lb` ([#1806](https://github.com/terraform-providers/terraform-provider-aws/issues/1806)) -* **New Data Source:** `aws_lb_listener` ([#1806](https://github.com/terraform-providers/terraform-provider-aws/issues/1806)) -* **New Data Source:** `aws_lb_target_group` ([#1806](https://github.com/terraform-providers/terraform-provider-aws/issues/1806)) -* **New Data Source:** `aws_iam_user` ([#1805](https://github.com/terraform-providers/terraform-provider-aws/issues/1805)) -* **New Data Source:** `aws_s3_bucket` ([#1505](https://github.com/terraform-providers/terraform-provider-aws/issues/1505)) +## 3.2.0 (August 14, 2020) -IMPROVEMENTS: +ENHANCEMENTS -* data-source/aws_redshift_service_account: Add `arn` attribute ([#1775](https://github.com/terraform-providers/terraform-provider-aws/issues/1775)) -* data-source/aws_vpc_endpoint: Expose `prefix_list_id` ([#1733](https://github.com/terraform-providers/terraform-provider-aws/issues/1733)) -* resource/aws_kinesis_stream: Add support for encryption ([#1139](https://github.com/terraform-providers/terraform-provider-aws/issues/1139)) -* resource/aws_cloudwatch_log_group: Add support for encryption via `kms_key_id` ([#1751](https://github.com/terraform-providers/terraform-provider-aws/issues/1751)) -* resource/aws_spot_instance_request: Add support for `instance_interruption_behaviour` ([#1735](https://github.com/terraform-providers/terraform-provider-aws/issues/1735)) -* resource/aws_ses_event_destination: Add support for `open` & `click` event types ([#1773](https://github.com/terraform-providers/terraform-provider-aws/issues/1773)) -* resource/aws_efs_file_system: Expose `dns_name` ([#1825](https://github.com/terraform-providers/terraform-provider-aws/issues/1825)) -* resource/aws_security_group+aws_security_group_rule: Add support for rule description ([#1587](https://github.com/terraform-providers/terraform-provider-aws/issues/1587)) -* resource/aws_emr_cluster: enable configuration of ebs root volume size ([#1375](https://github.com/terraform-providers/terraform-provider-aws/issues/1375)) -* resource/aws_ami: Add `root_snapshot_id` attribute ([#1572](https://github.com/terraform-providers/terraform-provider-aws/issues/1572)) -* resource/aws_vpn_connection: Mark preshared keys as sensitive ([#1850](https://github.com/terraform-providers/terraform-provider-aws/issues/1850)) -* resource/aws_codedeploy_deployment_group: Support blue/green and in-place deployments with traffic control ([#1162](https://github.com/terraform-providers/terraform-provider-aws/issues/1162)) -* resource/aws_elb: Update ELB idle timeout to 4000s ([#1861](https://github.com/terraform-providers/terraform-provider-aws/issues/1861)) -* resource/aws_spot_fleet_request: Add support for instance_interruption_behaviour ([#1847](https://github.com/terraform-providers/terraform-provider-aws/issues/1847)) -* resource/aws_kinesis_firehose_delivery_stream: Specify kinesis stream as the source of a aws_kinesis_firehose_delivery_stream ([#1605](https://github.com/terraform-providers/terraform-provider-aws/issues/1605)) -* resource/aws_kinesis_firehose_delivery_stream: Output complete error when creation fails ([#1881](https://github.com/terraform-providers/terraform-provider-aws/issues/1881)) +* data-source/aws_launch_configuration: Add `ebs_block_device` `no_device` attribute ([#14583](https://github.com/terraform-providers/terraform-provider-aws/issues/14583)) +* data-source/aws_lb: Add `subnet_mapping` `private_ipv4_address` attribute ([#14545](https://github.com/terraform-providers/terraform-provider-aws/issues/14545)) +* provider: Upgrade to Terraform Plugin SDK V2. There should be no breaking changes from a practitioner's perspective. Some validation errors should now feature enhanced messaging. ([#14432](https://github.com/terraform-providers/terraform-provider-aws/issues/14432)) +* resource/aws_accessanalyzer_analyzer: Support `ORGANIZATION` value in `type` argument ([#14493](https://github.com/terraform-providers/terraform-provider-aws/issues/14493)) +* resource/aws_codebuild_project: Support `WINDOWS_SERVER_2019_CONTAINER` value in `environment` `type` argument plan-time validation ([#14532](https://github.com/terraform-providers/terraform-provider-aws/issues/14532)) +* resource/aws_organizations_organization: Support `AISERVICES_OPT_OUT_POLICY` value in `enabled_policy_types` argument plan-time validation (Support AI Opt Out policies) ([#14650](https://github.com/terraform-providers/terraform-provider-aws/issues/14650)) +* resource/aws_organizations_policy: Support `AISERVICES_OPT_OUT_POLICY` value in `type` argument plan-time validation (Support AI Opt Out policies) ([#14528](https://github.com/terraform-providers/terraform-provider-aws/issues/14528)) +* resource/aws_route53_health_check: Add `disabled` argument ([#14614](https://github.com/terraform-providers/terraform-provider-aws/issues/14614)) -BUG FIXES: +BUG FIXES -* data-source/aws_db_instance: Make `db_instance_arn` expose ARN instead of identifier (use `db_cluster_identifier` for identifier) ([#1766](https://github.com/terraform-providers/terraform-provider-aws/issues/1766)) -* data-source/aws_db_snapshot: Expose `storage_type` (was not exposed) ([#1833](https://github.com/terraform-providers/terraform-provider-aws/issues/1833)) -* data-source/aws_ami: Update the `tags` structure for easier referencing ([#1706](https://github.com/terraform-providers/terraform-provider-aws/issues/1706)) -* data-source/aws_ebs_snapshot: Update the `tags` structure for easier referencing ([#1706](https://github.com/terraform-providers/terraform-provider-aws/issues/1706)) -* data-source/aws_ebs_volume: Update the `tags` structure for easier referencing ([#1706](https://github.com/terraform-providers/terraform-provider-aws/issues/1706)) -* data-source/aws_instance: Update the `tags` structure for easier referencing ([#1706](https://github.com/terraform-providers/terraform-provider-aws/issues/1706)) -* resource/aws_spot_instance_request: Handle `closed` request correctly ([#1903](https://github.com/terraform-providers/terraform-provider-aws/issues/1903)) -* resource/aws_cloudtrail: Raise update retry timeout ([#1820](https://github.com/terraform-providers/terraform-provider-aws/issues/1820)) -* resource/aws_elasticache_parameter_group: Retry resetting group on pending changes ([#1821](https://github.com/terraform-providers/terraform-provider-aws/issues/1821)) -* resource/aws_kms_key: Retry getting rotation status ([#1818](https://github.com/terraform-providers/terraform-provider-aws/issues/1818)) -* resource/aws_kms_key: Retry getting key policy ([#1854](https://github.com/terraform-providers/terraform-provider-aws/issues/1854)) -* resource/aws_vpn_connection: Raise timeout to 40mins ([#1819](https://github.com/terraform-providers/terraform-provider-aws/issues/1819)) -* resource/aws_kinesis_firehose_delivery_stream: Fix crash caused by missing `processing_configuration` ([#1738](https://github.com/terraform-providers/terraform-provider-aws/issues/1738)) -* resource/aws_rds_cluster_instance: Treat `configuring-enhanced-monitoring` as pending state ([#1744](https://github.com/terraform-providers/terraform-provider-aws/issues/1744)) -* resource/aws_rds_cluster_instance: Treat more states as pending ([#1790](https://github.com/terraform-providers/terraform-provider-aws/issues/1790)) -* resource/aws_route_table: Increase number of not-found checks/retries after creation ([#1791](https://github.com/terraform-providers/terraform-provider-aws/issues/1791)) -* resource/aws_batch_compute_environment: Fix ARN attribute name/value (`ecc_cluster_arn` -> `ecs_cluster_arn`) ([#1809](https://github.com/terraform-providers/terraform-provider-aws/issues/1809)) -* resource/aws_kinesis_stream: Retry creation of the stream on `LimitExceededException` (handle throttling) ([#1339](https://github.com/terraform-providers/terraform-provider-aws/issues/1339)) -* resource/aws_vpn_connection_route: Treat route in state `deleted` as deleted ([#1848](https://github.com/terraform-providers/terraform-provider-aws/issues/1848)) -* resource/aws_eip: Avoid disassociating if there's no association ([#1683](https://github.com/terraform-providers/terraform-provider-aws/issues/1683)) -* resource/aws_elasticache_cluster: Allow scaling up cluster by modifying `az_mode` (avoid recreation) ([#1758](https://github.com/terraform-providers/terraform-provider-aws/issues/1758)) -* resource/aws_lambda_function: Fix Lambda Function Updates When Published ([#1797](https://github.com/terraform-providers/terraform-provider-aws/issues/1797)) -* resource/aws_appautoscaling_*: Use dimension to uniquely identify target/policy ([#1808](https://github.com/terraform-providers/terraform-provider-aws/issues/1808)) -* resource/aws_vpn_connection_route: Wait until route is available/deleted ([#1849](https://github.com/terraform-providers/terraform-provider-aws/issues/1849)) -* resource/aws_cloudfront_distribution: Ignore `minimum_protocol_version` if default certificate is used ([#1785](https://github.com/terraform-providers/terraform-provider-aws/issues/1785)) -* resource/aws_security_group: Using `self = false` with `cidr_blocks` should be allowed ([#1839](https://github.com/terraform-providers/terraform-provider-aws/issues/1839)) -* resource/aws_instance: Check VPC array size to avoid crashes on Eucalyptus Cloud ([#1882](https://github.com/terraform-providers/terraform-provider-aws/issues/1882)) +* data-source/aws_launch_template: Prevent type error with `network_interfaces` `delete_on_termination` attribute ([#14599](https://github.com/terraform-providers/terraform-provider-aws/issues/14599)) +* resource/aws_acm_certificate_validation: Prevent panic with missing `DomainValidationOptions` `ResourceRecord` attribute in API response [[#14590](https://github.com/terraform-providers/terraform-provider-aws/issues/14590)] +* resource/aws_ecr_repository: Prevent panic with missing `EncryptionConfiguration` attribute in API response ([#14584](https://github.com/terraform-providers/terraform-provider-aws/issues/14584)) +* resource/aws_wafv2_rule_group: Prevent unnecessary resource recreation with `rule` updates ([#14617](https://github.com/terraform-providers/terraform-provider-aws/issues/14617)) +* resource/aws_wafv2_web_acl: Prevent unnecessary resource recreation with `rule` updates ([#14616](https://github.com/terraform-providers/terraform-provider-aws/issues/14616)) -## 1.0.0 (September 27, 2017) +## 3.1.0 (August 07, 2020) NOTES: -* resource/aws_appautoscaling_policy: Nest step scaling policy fields, deprecate 1st level fields ([#1620](https://github.com/terraform-providers/terraform-provider-aws/issues/1620)) +* resource/aws_route53_zone_association: The addition of cross-account zone association support required the use of new `ListHostedZonesByVPC` API call and adding the VPC Region to the resource ID for new resources. Restrictive IAM permissions for Terraform and cross-region imports may require updates. ([#14215](https://github.com/terraform-providers/terraform-provider-aws/issues/14215)) -FEATURES: - -* **New Resource:** `aws_waf_rate_based_rule` ([#1606](https://github.com/terraform-providers/terraform-provider-aws/issues/1606)) -* **New Resource:** `aws_batch_compute_environment` ([#1048](https://github.com/terraform-providers/terraform-provider-aws/issues/1048)) - -IMPROVEMENTS: - -* provider: Expand shared_credentials_file ([#1511](https://github.com/terraform-providers/terraform-provider-aws/issues/1511)) -* provider: Add support for Task Roles when running on ECS or CodeBuild ([#1425](https://github.com/terraform-providers/terraform-provider-aws/issues/1425)) -* resource/aws_instance: New `user_data_base64` attribute that allows non-UTF8 data (such as gzip) to be assigned to user-data without corruption ([#850](https://github.com/terraform-providers/terraform-provider-aws/issues/850)) -* data-source/aws_vpc: Expose enable_dns_* in aws_vpc data_source ([#1373](https://github.com/terraform-providers/terraform-provider-aws/issues/1373)) -* resource/aws_appautoscaling_policy: Add support for DynamoDB ([#1650](https://github.com/terraform-providers/terraform-provider-aws/issues/1650)) -* resource/aws_directory_service_directory: Add support for `tags` ([#1398](https://github.com/terraform-providers/terraform-provider-aws/issues/1398)) -* resource/aws_rds_cluster: Allow setting of rds cluster engine ([#1415](https://github.com/terraform-providers/terraform-provider-aws/issues/1415)) -* resource/aws_ssm_association: now supports update for `parameters`, `schedule_expression`,`output_location` ([#1421](https://github.com/terraform-providers/terraform-provider-aws/issues/1421)) -* resource/aws_ssm_patch_baseline: now supports update for multiple attributes ([#1421](https://github.com/terraform-providers/terraform-provider-aws/issues/1421)) -* resource/aws_cloudformation_stack: Add support for Import ([#1432](https://github.com/terraform-providers/terraform-provider-aws/issues/1432)) -* resource/aws_rds_cluster_instance: Expose availability_zone attribute ([#1439](https://github.com/terraform-providers/terraform-provider-aws/issues/1439)) -* resource/aws_efs_file_system: Add support for encryption ([#1420](https://github.com/terraform-providers/terraform-provider-aws/issues/1420)) -* resource/aws_db_parameter_group: Allow underscores in names ([#1460](https://github.com/terraform-providers/terraform-provider-aws/issues/1460)) -* resource/aws_elasticsearch_domain: Assign tags right after creation ([#1399](https://github.com/terraform-providers/terraform-provider-aws/issues/1399)) -* resource/aws_route53_record: Allow CAA record type ([#1467](https://github.com/terraform-providers/terraform-provider-aws/issues/1467)) -* resource/aws_codebuild_project: Allowed for BITBUCKET source type ([#1468](https://github.com/terraform-providers/terraform-provider-aws/issues/1468)) -* resource/aws_emr_cluster: Add `instance_group` parameter for EMR clusters ([#1071](https://github.com/terraform-providers/terraform-provider-aws/issues/1071)) -* resource/aws_alb_listener_rule: Populate `listener_arn` field ([#1303](https://github.com/terraform-providers/terraform-provider-aws/issues/1303)) -* resource/aws_api_gateway_rest_api: Add a body property to API Gateway RestAPI for Swagger import support ([#1197](https://github.com/terraform-providers/terraform-provider-aws/issues/1197)) -* resource/aws_opsworks_stack: Add support for tags ([#1523](https://github.com/terraform-providers/terraform-provider-aws/issues/1523)) -* Add retries for AppScaling policies throttling exceptions ([#1430](https://github.com/terraform-providers/terraform-provider-aws/issues/1430)) -* resource/aws_ssm_patch_baseline: Add compliance level to patch approval rules ([#1531](https://github.com/terraform-providers/terraform-provider-aws/issues/1531)) -* resource/aws_ssm_activation: Export ssm activation activation_code ([#1570](https://github.com/terraform-providers/terraform-provider-aws/issues/1570)) -* resource/aws_network_interface: Added private_dns_name to network_interface ([#1599](https://github.com/terraform-providers/terraform-provider-aws/issues/1599)) -* data-source/aws_redshift_service_account: updated with latest redshift service account ID's ([#1614](https://github.com/terraform-providers/terraform-provider-aws/issues/1614)) -* resource/aws_ssm_parameter: Refresh from state on 404 ([#1436](https://github.com/terraform-providers/terraform-provider-aws/issues/1436)) -* resource/aws_api_gateway_rest_api: Allow binary media types to be updated ([#1600](https://github.com/terraform-providers/terraform-provider-aws/issues/1600)) -* resource/aws_waf_rule: Make `predicates`' `data_id` required (it always was on the API's side, it's just reflected in the schema) ([#1606](https://github.com/terraform-providers/terraform-provider-aws/issues/1606)) -* resource/aws_waf_web_acl: Introduce new `type` field in `rules` to allow referencing `RATE_BASED` type ([#1606](https://github.com/terraform-providers/terraform-provider-aws/issues/1606)) -* resource/aws_ssm_association: Migrate the schema to use association_id ([#1579](https://github.com/terraform-providers/terraform-provider-aws/issues/1579)) -* resource/aws_ssm_document: Added name validation ([#1638](https://github.com/terraform-providers/terraform-provider-aws/issues/1638)) -* resource/aws_nat_gateway: Add tags support ([#1625](https://github.com/terraform-providers/terraform-provider-aws/issues/1625)) -* resource/aws_route53_record: Add support for Route53 multi-value answer routing policy ([#1686](https://github.com/terraform-providers/terraform-provider-aws/issues/1686)) -* resource/aws_instance: Read iops only when volume type is io1 ([#1573](https://github.com/terraform-providers/terraform-provider-aws/issues/1573)) -* resource/aws_rds_cluster(+_instance) Allow specifying the engine ([#1591](https://github.com/terraform-providers/terraform-provider-aws/issues/1591)) -* resource/aws_cloudwatch_event_target: Add Input transformer for Cloudwatch Events ([#1343](https://github.com/terraform-providers/terraform-provider-aws/issues/1343)) -* resource/aws_directory_service_directory: Support Import functionality ([#1732](https://github.com/terraform-providers/terraform-provider-aws/issues/1732)) - -BUG FIXES: - -* resource/aws_instance: Fix `associate_public_ip_address` ([#1340](https://github.com/terraform-providers/terraform-provider-aws/issues/1340)) -* resource/aws_instance: Fix import in EC2 Classic ([#1453](https://github.com/terraform-providers/terraform-provider-aws/issues/1453)) -* resource/aws_emr_cluster: Avoid spurious diff of `log_uri` ([#1374](https://github.com/terraform-providers/terraform-provider-aws/issues/1374)) -* resource/aws_cloudwatch_log_subscription_filter: Add support for ResourceNotFound ([#1414](https://github.com/terraform-providers/terraform-provider-aws/issues/1414)) -* resource/aws_sns_topic_subscription: Prevent duplicate (un)subscribe during initial creation ([#1480](https://github.com/terraform-providers/terraform-provider-aws/issues/1480)) -* resource/aws_alb: Cleanup ENIs after deleting ALB ([#1427](https://github.com/terraform-providers/terraform-provider-aws/issues/1427)) -* resource/aws_s3_bucket: Wrap s3 calls in retry to avoid race during creation ([#891](https://github.com/terraform-providers/terraform-provider-aws/issues/891)) -* resource/aws_eip: Remove from state on deletion ([#1551](https://github.com/terraform-providers/terraform-provider-aws/issues/1551)) -* resource/aws_security_group: Adding second scenario where IPv6 is not supported ([#880](https://github.com/terraform-providers/terraform-provider-aws/issues/880)) - -## 0.1.4 (August 08, 2017) - -FEATURES: - -* **New Resource:** `aws_cloudwatch_dashboard` ([#1172](https://github.com/terraform-providers/terraform-provider-aws/issues/1172)) -* **New Data Source:** `aws_internet_gateway` ([#1196](https://github.com/terraform-providers/terraform-provider-aws/issues/1196)) -* **New Data Source:** `aws_efs_mount_target` ([#1255](https://github.com/terraform-providers/terraform-provider-aws/issues/1255)) - -IMPROVEMENTS: - -* AWS SDK to log extra debug details on request errors ([#1210](https://github.com/terraform-providers/terraform-provider-aws/issues/1210)) -* resource/aws_spot_fleet_request: Add support for `wait_for_fulfillment` ([#1241](https://github.com/terraform-providers/terraform-provider-aws/issues/1241)) -* resource/aws_autoscaling_schedule: Allow empty value ([#1268](https://github.com/terraform-providers/terraform-provider-aws/issues/1268)) -* resource/aws_ssm_association: Add support for OutputLocation and Schedule Expression ([#1253](https://github.com/terraform-providers/terraform-provider-aws/issues/1253)) -* resource/aws_ssm_patch_baseline: Update support for Operating System ([#1260](https://github.com/terraform-providers/terraform-provider-aws/issues/1260)) -* resource/aws_db_instance: Expose db_instance ca_cert_identifier ([#1256](https://github.com/terraform-providers/terraform-provider-aws/issues/1256)) -* resource/aws_rds_cluster: Add support for iam_roles to rds_cluster ([#1258](https://github.com/terraform-providers/terraform-provider-aws/issues/1258)) -* resource/aws_rds_cluster_parameter_group: Support > 20 parameters ([#1298](https://github.com/terraform-providers/terraform-provider-aws/issues/1298)) -* data-source/aws_iam_role: Normalize the IAM role data source ([#1330](https://github.com/terraform-providers/terraform-provider-aws/issues/1330)) -* resource/aws_kinesis_stream: Increase Timeouts, add Timeout Support ([#1345](https://github.com/terraform-providers/terraform-provider-aws/issues/1345)) - -BUG FIXES: - -* resource/aws_instance: Guard check for aws_instance UserData to prevent panic ([#1288](https://github.com/terraform-providers/terraform-provider-aws/issues/1288)) -* resource/aws_config: Set AWS Config Configuration recorder & Delivery channel names as ForceNew ([#1247](https://github.com/terraform-providers/terraform-provider-aws/issues/1247)) -* resource/aws_cloudtrail: Retry if IAM role isn't propagated yet ([#1312](https://github.com/terraform-providers/terraform-provider-aws/issues/1312)) -* resource/aws_cloudtrail: Fix CloudWatch role ARN/group updates ([#1357](https://github.com/terraform-providers/terraform-provider-aws/issues/1357)) -* resource/aws_eip_association: Avoid crash in EC2 Classic ([#1344](https://github.com/terraform-providers/terraform-provider-aws/issues/1344)) -* resource/aws_elasticache_parameter_group: Allow removing parameters ([#1309](https://github.com/terraform-providers/terraform-provider-aws/issues/1309)) -* resource/aws_kinesis: add retries for Kinesis throttling exceptions ([#1085](https://github.com/terraform-providers/terraform-provider-aws/issues/1085)) -* resource/aws_kinesis_firehose: adding support for `ExtendedS3DestinationConfiguration` ([#1015](https://github.com/terraform-providers/terraform-provider-aws/issues/1015)) -* resource/aws_spot_fleet_request: Ignore empty `key_name` ([#1203](https://github.com/terraform-providers/terraform-provider-aws/issues/1203)) -* resource/aws_emr_instance_group: fix crash when changing `instance_group.count` ([#1287](https://github.com/terraform-providers/terraform-provider-aws/issues/1287)) -* resource/aws_elasticsearch_domain: Fix updating config when update doesn't involve EBS ([#1131](https://github.com/terraform-providers/terraform-provider-aws/issues/1131)) -* resource/aws_s3_bucket: Avoid crashing when no lifecycle rule is defined ([#1316](https://github.com/terraform-providers/terraform-provider-aws/issues/1316)) -* resource/elastic_transcoder_preset: Fix provider validation ([#1338](https://github.com/terraform-providers/terraform-provider-aws/issues/1338)) -* resource/aws_s3_bucket: Avoid crashing when `filter` is not set ([#1350](https://github.com/terraform-providers/terraform-provider-aws/issues/1350)) - -## 0.1.3 (July 25, 2017) - -FEATURES: - -* **New Data Source:** `aws_iam_instance_profile` ([#1024](https://github.com/terraform-providers/terraform-provider-aws/issues/1024)) -* **New Data Source:** `aws_alb_target_group` ([#1037](https://github.com/terraform-providers/terraform-provider-aws/issues/1037)) -* **New Data Source:** `aws_iam_group` ([#1140](https://github.com/terraform-providers/terraform-provider-aws/issues/1140)) -* **New Resource:** `aws_api_gateway_request_validator` ([#1064](https://github.com/terraform-providers/terraform-provider-aws/issues/1064)) -* **New Resource:** `aws_api_gateway_gateway_response` ([#1168](https://github.com/terraform-providers/terraform-provider-aws/issues/1168)) -* **New Resource:** `aws_iot_policy` ([#986](https://github.com/terraform-providers/terraform-provider-aws/issues/986)) -* **New Resource:** `aws_iot_certificate` ([#1225](https://github.com/terraform-providers/terraform-provider-aws/issues/1225)) - -IMPROVEMENTS: - -* resource/aws_sqs_queue: Add support for Server-Side Encryption ([#962](https://github.com/terraform-providers/terraform-provider-aws/issues/962)) -* resource/aws_vpc: Add support for classiclink_dns_support ([#1079](https://github.com/terraform-providers/terraform-provider-aws/issues/1079)) -* resource/aws_lambda_function: Add support for lambda_function vpc_config update ([#1080](https://github.com/terraform-providers/terraform-provider-aws/issues/1080)) -* resource/aws_lambda_function: Add support for lambda_function dead_letter_config update ([#1080](https://github.com/terraform-providers/terraform-provider-aws/issues/1080)) -* resource/aws_route53_health_check: add support for health_check regions ([#1116](https://github.com/terraform-providers/terraform-provider-aws/issues/1116)) -* resource/aws_spot_instance_request: add support for request launch group ([#1097](https://github.com/terraform-providers/terraform-provider-aws/issues/1097)) -* resource/aws_rds_cluster_instance: Export the RDI Resource ID for the instance ([#1142](https://github.com/terraform-providers/terraform-provider-aws/issues/1142)) -* resource/aws_sns_topic_subscription: Support password-protected HTTPS endpoints ([#861](https://github.com/terraform-providers/terraform-provider-aws/issues/861)) - -BUG FIXES: - -* provider: Remove assumeRoleHash ([#1227](https://github.com/terraform-providers/terraform-provider-aws/issues/1227)) -* resource/aws_ami: Retry on `InvalidAMIID.NotFound` ([#1035](https://github.com/terraform-providers/terraform-provider-aws/issues/1035)) -* resource/aws_iam_server_certificate: Fix restriction on length of `name_prefix` ([#1217](https://github.com/terraform-providers/terraform-provider-aws/issues/1217)) -* resource/aws_autoscaling_group: Fix handling of empty `vpc_zone_identifier` (EC2 classic & default VPC) ([#1191](https://github.com/terraform-providers/terraform-provider-aws/issues/1191)) -* resource/aws_ecr_repository_policy: Add retry logic to work around IAM eventual consistency ([#1165](https://github.com/terraform-providers/terraform-provider-aws/issues/1165)) -* resource/aws_ecs_service: Fixes normalization issues in placement_strategy ([#1025](https://github.com/terraform-providers/terraform-provider-aws/issues/1025)) -* resource/aws_eip: Retry reading EIPs on creation ([#1053](https://github.com/terraform-providers/terraform-provider-aws/issues/1053)) -* resource/aws_elastic_beanstalk_environment: Avoid spurious diffs of JSON-based `setting`s ([#901](https://github.com/terraform-providers/terraform-provider-aws/issues/901)) -* resource/aws_opsworks_permission: Fix 'set permissions' failing to set ssh access ([#1038](https://github.com/terraform-providers/terraform-provider-aws/issues/1038)) -* resource/aws_s3_bucket_notification: Fix missing `bucket` field after import ([#978](https://github.com/terraform-providers/terraform-provider-aws/issues/978)) -* resource/aws_sfn_state_machine: Handle another NotFound exception type ([#1062](https://github.com/terraform-providers/terraform-provider-aws/issues/1062)) -* resource/aws_ssm_parameter: ForceNew on ssm_parameter rename ([#1022](https://github.com/terraform-providers/terraform-provider-aws/issues/1022)) -* resource/aws_instance: Update SourceDestCheck modification on new resources ([#1065](https://github.com/terraform-providers/terraform-provider-aws/issues/1065)) -* resource/aws_spot_instance_request: fixed and issue with network interfaces configuration ([#1070](https://github.com/terraform-providers/terraform-provider-aws/issues/1070)) -* resource/aws_rds_cluster: Modify RDS Cluster after restoring from snapshot, if required ([#926](https://github.com/terraform-providers/terraform-provider-aws/issues/926)) -* resource/aws_kms_alias: Retry lookups after creation ([#1040](https://github.com/terraform-providers/terraform-provider-aws/issues/1040)) -* resource/aws_internet_gateway: Retry deletion properly on `DependencyViolation` ([#1021](https://github.com/terraform-providers/terraform-provider-aws/issues/1021)) -* resource/aws_elb: Cleanup ENIs after deleting ELB ([#1036](https://github.com/terraform-providers/terraform-provider-aws/issues/1036)) -* resource/aws_kms_key: Retry lookups after creation ([#1039](https://github.com/terraform-providers/terraform-provider-aws/issues/1039)) -* resource/aws_dms_replication_instance: Add modifying as a pending creation state ([#1114](https://github.com/terraform-providers/terraform-provider-aws/issues/1114)) -* resource/aws_redshift_cluster: Trigger ForceNew aws_redshift_cluster on encrypted change ([#1120](https://github.com/terraform-providers/terraform-provider-aws/issues/1120)) -* resource/aws_default_network_acl: Add support for ipv6_cidr_block ([#1113](https://github.com/terraform-providers/terraform-provider-aws/issues/1113)) -* resource/aws_autoscaling_group: Suppress diffs when an empty set is specified for `availability_zones` ([#1190](https://github.com/terraform-providers/terraform-provider-aws/issues/1190)) -* resource/aws_vpc: Ignore ClassicLink DNS support in unsupported regions ([#1176](https://github.com/terraform-providers/terraform-provider-aws/issues/1176)) -* resource/elastic_beanstalk_configuration_template: Handle missing platform ([#1222](https://github.com/terraform-providers/terraform-provider-aws/issues/1222)) -* r/elasticache_parameter_group: support more than 20 parameters ([#1221](https://github.com/terraform-providers/terraform-provider-aws/issues/1221)) -* data-source/aws_db_instance: Fix the output of subnet_group_name ([#1141](https://github.com/terraform-providers/terraform-provider-aws/issues/1141)) -* data-source/aws_iam_server_certificate: Fix restriction on length of `name_prefix` ([#1217](https://github.com/terraform-providers/terraform-provider-aws/issues/1217)) - -## 0.1.2 (June 30, 2017) - -FEATURES: - -* **New Resource**: `aws_network_interface_sg_attachment` ([#860](https://github.com/terraform-providers/terraform-provider-aws/issues/860)) -* **New Data Source**: `aws_ecr_repository` ([#944](https://github.com/terraform-providers/terraform-provider-aws/issues/944)) - -IMPROVEMENTS: - -* Added ability to change the deadline for the EC2 metadata API endpoint ([#950](https://github.com/terraform-providers/terraform-provider-aws/issues/950)) -* resource/aws_api_gateway_integration: Add support for specifying cache key parameters ([#893](https://github.com/terraform-providers/terraform-provider-aws/issues/893)) -* resource/aws_cloudwatch_event_target: Add ecs_target ([#977](https://github.com/terraform-providers/terraform-provider-aws/issues/977)) -* resource/aws_vpn_connection: Add BGP related information on aws_vpn_connection ([#973](https://github.com/terraform-providers/terraform-provider-aws/issues/973)) -* resource/aws_cloudformation_stack: Add timeout support ([#994](https://github.com/terraform-providers/terraform-provider-aws/issues/994)) -* resource/aws_ssm_parameter: Add support for ssm parameter overwrite ([#1006](https://github.com/terraform-providers/terraform-provider-aws/issues/1006)) -* resource/aws_codebuild_project: Add support for environment privileged_mode [GH1009] -* resource/aws_dms_endpoint: Add support for dynamodb as an endpoint target ([#1002](https://github.com/terraform-providers/terraform-provider-aws/issues/1002)) -* resource/aws_s3_bucket: Support lifecycle tags filter ([#899](https://github.com/terraform-providers/terraform-provider-aws/issues/899)) -* resource/aws_s3_bucket_object: Allow to set WebsiteRedirect on S3 object ([#1020](https://github.com/terraform-providers/terraform-provider-aws/issues/1020)) - -BUG FIXES: - -* resource/aws_waf: Only set FieldToMatch.Data if not empty ([#953](https://github.com/terraform-providers/terraform-provider-aws/issues/953)) -* resource/aws_elastic_beanstalk_application_version: Scope labels to application ([#956](https://github.com/terraform-providers/terraform-provider-aws/issues/956)) -* resource/aws_s3_bucket: Allow use of `days = 0` with lifecycle transition ([#957](https://github.com/terraform-providers/terraform-provider-aws/issues/957)) -* resource/aws_ssm_maintenance_window_task: Make task_parameters updateable on aws_ssm_maintenance_window_task resource ([#965](https://github.com/terraform-providers/terraform-provider-aws/issues/965)) -* resource/aws_kinesis_stream: don't force stream destroy on shard_count update ([#894](https://github.com/terraform-providers/terraform-provider-aws/issues/894)) -* resource/aws_cloudfront_distribution: Remove validation from custom_origin params ([#987](https://github.com/terraform-providers/terraform-provider-aws/issues/987)) -* resource_aws_route53_record: Allow import of Route 53 records with underscores in the name ([#14717](https://github.com/hashicorp/terraform/pull/14717)) -* d/aws_db_snapshot: Id was being set incorrectly ([#992](https://github.com/terraform-providers/terraform-provider-aws/issues/992)) -* resource/aws_spot_fleet_request: Raise the create timeout to be 10m ([#993](https://github.com/terraform-providers/terraform-provider-aws/issues/993)) -* d/aws_ecs_cluster: Add ARN as an exported param for aws_ecs_cluster ([#991](https://github.com/terraform-providers/terraform-provider-aws/issues/991)) -* resource/aws_ebs_volume: Not setting the state for ebs_volume correctly ([#999](https://github.com/terraform-providers/terraform-provider-aws/issues/999)) -* resource/aws_network_acl: Make action in ingress / egress case insensitive ([#1000](https://github.com/terraform-providers/terraform-provider-aws/issues/1000)) +FEATURES -## 0.1.1 (June 21, 2017) +* **New Data Source:** `aws_ec2_spot_price` ([#12504](https://github.com/terraform-providers/terraform-provider-aws/issues/12504)) +* **New Resource**: `aws_route53_vpc_association_authorization` ([#14215](https://github.com/terraform-providers/terraform-provider-aws/issues/14215)) -BUG FIXES: +ENHANCEMENTS -* Fixing malformed ARN attribute for aws_security_group data source ([#910](https://github.com/terraform-providers/terraform-provider-aws/issues/910)) +* data-source/aws_ecr_repository: Allow `registry_id` as an argument ([#14368](https://github.com/terraform-providers/terraform-provider-aws/issues/14368)) +* data-source/aws_ecr_repository: Add `image_scanning_configuration` and `image_tag_mutability` attributes ([#14368](https://github.com/terraform-providers/terraform-provider-aws/issues/14368)) +* data-source/aws_ecr_repository: Add `encryption_configuration` attribute ([#14520](https://github.com/terraform-providers/terraform-provider-aws/issues/14520)) +* resource/aws_api_gateway_method_settings: Plan-time validation added to `settings` `unauthorized_cache_control_header_strategy` and `logging_level` arguments ([#12651](https://github.com/terraform-providers/terraform-provider-aws/issues/12651)) +* resource/aws_ecr_repository: Add `encryption_configuration` attribute ([#14520](https://github.com/terraform-providers/terraform-provider-aws/issues/14520)) +* resource/aws_lb: Add `subnet_mapping` configuration block `private_ipv4_address` argument ([#11404](https://github.com/terraform-providers/terraform-provider-aws/issues/11404)) +* resource/aws_rds_global_cluster: Add `force_destroy` and `source_db_cluster_identifier` arguments ([#14487](https://github.com/terraform-providers/terraform-provider-aws/issues/14487)) +* resource/aws_rds_global_cluster: Add `global_cluster_members` attribute ([#14487](https://github.com/terraform-providers/terraform-provider-aws/issues/14487)) +* resource/aws_route53_zone_association: Cross-account zone associations can now be created in conjunction with the new `aws_route53_vpc_association_authorization` resource ([#14215](https://github.com/terraform-providers/terraform-provider-aws/issues/14215)) +* resource/aws_ssm_parameter: Add `data_type` argument (support `aws:ec2:image` parameters) ([#13326](https://github.com/terraform-providers/terraform-provider-aws/issues/13326)) -## 0.1.0 (June 20, 2017) +BUG FIXES -BACKWARDS INCOMPATIBILITIES / NOTES: +* data-source/aws_availability_zones: Prevent unexpected plan output every apply with `group_names` attribute ([#14412](https://github.com/terraform-providers/terraform-provider-aws/issues/14412)) +* data-source/aws_s3_bucket: Ensure provider `s3_force_path_style` configuration is passed through for getting S3 Bucket location with non-AWS implementations ([#14481](https://github.com/terraform-providers/terraform-provider-aws/issues/14481)) +* resource/aws_api_gateway_method_settings: Allow `settings` `cache_ttl_in_seconds` argument to be set to 0 ([#12651](https://github.com/terraform-providers/terraform-provider-aws/issues/12651)) +* resource/aws_elastictranscoder_preset: Prevent empty configuration block panics ([#14092](https://github.com/terraform-providers/terraform-provider-aws/issues/14092)) +* resource/aws_lambda_event_source_mapping: Allow `maximum_retry_attempts` argument to be set to 0 ([#12479](https://github.com/terraform-providers/terraform-provider-aws/issues/12479)) +* resource/aws_rds_cluster: Add an `InvalidDBClusterStateFault` retryable error condition for clusters part of a global cluster ([#14420](https://github.com/terraform-providers/terraform-provider-aws/issues/14420)) +* resource/aws_rds_cluster: Increase retry timeout for deletion to 2 minutes ([#14420](https://github.com/terraform-providers/terraform-provider-aws/issues/14420)) +* resource/aws_rds_cluster: Prevent error when both `global_cluster_identifier` and `replication_source_identifier` are configured on creation ([#14490](https://github.com/terraform-providers/terraform-provider-aws/issues/14490)) +* resource/aws_s3_bucket: Ensure provider `s3_force_path_style` configuration is passed through for getting S3 Bucket location with non-AWS implementations ([#14481](https://github.com/terraform-providers/terraform-provider-aws/issues/14481)) +* resource/aws_secretsmanager_secret: Allow retries for IAM eventual consistency errors ([#14459](https://github.com/terraform-providers/terraform-provider-aws/issues/14459)) +* resource/aws_security_group: Ensure `name_prefix` argument with hex digits `a` through `f` is properly imported ([#14475](https://github.com/terraform-providers/terraform-provider-aws/issues/14475)) +* resource/aws_spot_fleet_request: Allow `target_capacity` argument to be updated to 0 ([#12759](https://github.com/terraform-providers/terraform-provider-aws/issues/12759)) +* resource/aws_spot_fleet_request: Wait for modify operation completion (default timeout of 10 minutes) ([#12759](https://github.com/terraform-providers/terraform-provider-aws/issues/12759)) +* resource/aws_vpc_dhcp_options_association: Properly trigger resource recreation when VPC is deleted outside Terraform ([#14367](https://github.com/terraform-providers/terraform-provider-aws/issues/14367)) + +## 3.0.0 (July 31, 2020) + +NOTES: +* provider: This version is built using Go 1.14.5, including security fixes to the crypto/x509 and net/http packages. + +BREAKING CHANGES + +* provider: New versions of the provider can only be automatically installed on Terraform 0.12 and later ([#14143](https://github.com/terraform-providers/terraform-provider-aws/issues/14143)) +* provider: All "removed" attributes are cut, using them would result in a Terraform Core level error ([#14001](https://github.com/terraform-providers/terraform-provider-aws/issues/14001)) +* provider: Credential ordering has changed from static, environment, shared credentials, EC2 metadata, default AWS Go SDK (shared configuration, web identity, ECS, EC2 Metadata) to static, environment, shared credentials, default AWS Go SDK (shared configuration, web identity, ECS, EC2 Metadata) ([#14077](https://github.com/terraform-providers/terraform-provider-aws/issues/14077)) +* provider: The `AWS_METADATA_TIMEOUT` environment variable no longer has any effect as we now depend on the default AWS Go SDK EC2 Metadata client timeout of one second with two retries ([#14077](https://github.com/terraform-providers/terraform-provider-aws/issues/14077)) +* provider: Remove deprecated `kinesis_analytics` and `r53` custom service endpoint arguments ([#14238](https://github.com/terraform-providers/terraform-provider-aws/issues/14238)) +* data-source/aws_availability_zones: Remove deprecated `blacklisted_names` and `blacklisted_zone_ids` arguments ([#14134](https://github.com/terraform-providers/terraform-provider-aws/issues/14134)) +* data-source/aws_directory_service_directory: Return an error when a single result is not found ([#14006](https://github.com/terraform-providers/terraform-provider-aws/issues/14006)) +* data-source/aws_ecr_repository: Return an error when a single result is not found ([#10520](https://github.com/terraform-providers/terraform-provider-aws/issues/10520)) +* data-source/aws_efs_file_system: Return an error when a single result is not found ([#14005](https://github.com/terraform-providers/terraform-provider-aws/issues/14005)) +* data-source/aws_launch_template: Return an error when a single result is not found ([#10521](https://github.com/terraform-providers/terraform-provider-aws/issues/10521)) +* data-source/aws_route53_resolver_rule: Trailing period removed from `domain_name` argument set in data-source ([#14220](https://github.com/terraform-providers/terraform-provider-aws/issues/14220)) +* data-source/aws_route53_zone: Trailing period removed from `name` argument set in data-source ([#14220](https://github.com/terraform-providers/terraform-provider-aws/issues/14220)) +* resource/aws_acm_certificate: `certificate_body`, `certificate_chain`, and `private_key` attributes are no longer stored in the Terraform state with hash values ([#9685](https://github.com/terraform-providers/terraform-provider-aws/issues/9685)) +* resource/aws_acm_certificate: `domain_validation_options` attribute changed from list to set ([#14199](https://github.com/terraform-providers/terraform-provider-aws/issues/14199)) +* resource/aws_acm_certificate: Plan-time validation added to `domain_name` and `subject_alternative_names` arguments to prevent usage of strings with trailing periods ([#14220](https://github.com/terraform-providers/terraform-provider-aws/issues/14220)) +* resource/aws_api_gateway_method_settings: Remove `Computed` property from `throttling_burst_limit` and `throttling_rate_limit` arguments, enabling drift detection ([#14266](https://github.com/terraform-providers/terraform-provider-aws/issues/14266)) +* resource/aws_api_gateway_method_settings: Update `throttling_burst_limit` and `throttling_rate_limit` argument defaults to match API default of `-1` to keep throttling disabled ([#14266](https://github.com/terraform-providers/terraform-provider-aws/issues/14266)) +* resource/aws_autoscaling_group: `availability_zones` and `vpc_zone_identifier` argument conflict now reported at plan-time ([#12927](https://github.com/terraform-providers/terraform-provider-aws/issues/12927)) +* resource/aws_autoscaling_group: Remove `Computed` property from `load_balancers` and `target_group_arns` arguments, enabling drift detection ([#14064](https://github.com/terraform-providers/terraform-provider-aws/issues/14064)) +* resource/aws_cloudfront_distribution: `active_trusted_signers` argument renamed to `trusted_signers` to support accessing `items` in Terraform 0.12 ([#14339](https://github.com/terraform-providers/terraform-provider-aws/issues/14339)) +* resource/aws_cloudwatch_log_group: Automatically trim `:*` suffix from `arn` attribute ([#14214](https://github.com/terraform-providers/terraform-provider-aws/issues/14214)) +* resource/aws_codepipeline: Removes `GITHUB_TOKEN` environment variable ([#14175](https://github.com/terraform-providers/terraform-provider-aws/issues/14175)) +* resource/aws_cognito_user_pool: Remove deprecated `admin_create_user_config` configuration block `unused_account_validity_days` argument ([#14294](https://github.com/terraform-providers/terraform-provider-aws/issues/14294)) +* resource/aws_dx_gateway: Remove automatic `aws_dx_gateway_association` resource import ([#14124](https://github.com/terraform-providers/terraform-provider-aws/issues/14124)) +* resource/aws_dx_gateway_association: Remove deprecated `vpn_gateway_id` argument ([#14144](https://github.com/terraform-providers/terraform-provider-aws/issues/14144)) +* resource/aws_dx_gateway_association_proposal: Remove deprecated `vpn_gateway_id` argument ([#14144](https://github.com/terraform-providers/terraform-provider-aws/issues/14144)) +* resource/aws_ebs_volume: Return an error when `iops` argument set to a value greater than 0 for volume types other than `io1` ([#14310](https://github.com/terraform-providers/terraform-provider-aws/issues/14310)) +* resource/aws_elastic_transcoder_preset: Remove `video` configuration block `max_frame_rate` argument default value ([#7141](https://github.com/terraform-providers/terraform-provider-aws/issues/7141)) +* resource/aws_emr_cluster: Remove deprecated `instance_group` configuration block, `core_instance_count`, `core_instance_type`, and `master_instance_type` arguments ([#14137](https://github.com/terraform-providers/terraform-provider-aws/issues/14137)) +* resource/aws_glue_job: Remove deprecated `allocated_capacity` argument ([#14296](https://github.com/terraform-providers/terraform-provider-aws/issues/14296)) +* resource/aws_iam_access_key: Remove deprecated `ses_smtp_password` attribute ([#14299](https://github.com/terraform-providers/terraform-provider-aws/issues/14299)) +* resource/aws_iam_instance_profile: Remove deprecated `roles` argument ([#14303](https://github.com/terraform-providers/terraform-provider-aws/issues/14303)) +* resource/aws_iam_server_certificate: Remove state hashing from `certificate_body`, `certificate_chain`, and `private_key` arguments for new or recreated resources ([#14187](https://github.com/terraform-providers/terraform-provider-aws/issues/14187)) +* resource/aws_instance: Return an error when `ebs_block_device` `iops` or `root_block_device` `iops` argument set to a value greater than `0` for volume types other than `io1` ([#14310](https://github.com/terraform-providers/terraform-provider-aws/issues/14310)) +* resource/aws_lambda_alias: Resource import no longer converts Lambda Function name to ARN ([#12876](https://github.com/terraform-providers/terraform-provider-aws/issues/12876)) +* resource/aws_launch_template: `network_interfaces` `delete_on_termination` argument changed from `bool` to `string` type ([#8612](https://github.com/terraform-providers/terraform-provider-aws/issues/8612)) +* resource/aws_lb_listener_rule: Remove deprecated `condition` configuration block `field` and `values` arguments ([#14309](https://github.com/terraform-providers/terraform-provider-aws/issues/14309)) +* resource/aws_msk_cluster: Update `encryption_info` `encryption_in_transit` `client_broker` argument default to match API default of `TLS` ([#14132](https://github.com/terraform-providers/terraform-provider-aws/issues/14132)) +* resource/aws_rds_cluster: Update `scaling_configuration` `min_capacity` argument default to match API default of `1` ([#14268](https://github.com/terraform-providers/terraform-provider-aws/issues/14268)) +* resource/aws_route53_resolver_rule: Trailing period removed from `domain_name` argument set in resource ([#14220](https://github.com/terraform-providers/terraform-provider-aws/issues/14220)) +* resource/aws_route53_zone: Trailing period removed from `name` argument set in resource ([#14220](https://github.com/terraform-providers/terraform-provider-aws/issues/14220)) +* resource/aws_s3_bucket: Remove automatic `aws_s3_bucket_policy` resource import ([#14121](https://github.com/terraform-providers/terraform-provider-aws/issues/14121)) +* resource/aws_s3_bucket: Convert `region` to read-only attribute ([#14127](https://github.com/terraform-providers/terraform-provider-aws/issues/14127)) +* resource/aws_s3_bucket_metric: Update `filter` argument to require at least one of the `prefix` or `tags` nested arguments ([#14230](https://github.com/terraform-providers/terraform-provider-aws/issues/14230)) +* resource/aws_security_group: Remove automatic `aws_security_group_rule` resource import ([#12616](https://github.com/terraform-providers/terraform-provider-aws/issues/12616)) +* resource/aws_ses_domain_identity: Plan-time validation added to `domain` argument to prevent usage of strings with trailing periods ([#14220](https://github.com/terraform-providers/terraform-provider-aws/issues/14220)) +* resource/aws_ses_domain_identity_verification: Plan-time validation added to `domain` argument to prevent usage of strings with trailing periods ([#14220](https://github.com/terraform-providers/terraform-provider-aws/issues/14220)) +* resource/aws_sns_platform_application: `platform_credential` and `platform_principal` attributes are no longer stored in the Terraform state with hash values ([#3894](https://github.com/terraform-providers/terraform-provider-aws/issues/3894)) +* resource/aws_spot_fleet_request: Remove 24 hour default for `valid_until` argument ([#9718](https://github.com/terraform-providers/terraform-provider-aws/issues/9718)) +* resource/aws_ssm_maintenance_window_task: Remove deprecated `logging_info` and `task_parameters` configuration blocks ([#14311](https://github.com/terraform-providers/terraform-provider-aws/issues/14311)) -FEATURES: +FEATURES -* **New Resource:** `aws_vpn_gateway_route_propagation` [[#15137](https://github.com/terraform-providers/terraform-provider-aws/issues/15137)](https://github.com/hashicorp/terraform/pull/15137) +* **New Data Source:** aws_workspaces_directory ([#13529](https://github.com/terraform-providers/terraform-provider-aws/issues/13529)) -IMPROVEMENTS: +ENHANCEMENTS -* resource/ebs_snapshot: Add support for tags ([#3](https://github.com/terraform-providers/terraform-provider-aws/issues/3)) -* resource/aws_elasticsearch_domain: now retries on IAM role association failure ([#12](https://github.com/terraform-providers/terraform-provider-aws/issues/12)) -* resource/codebuild_project: Increase timeout for creation retry (IAM) ([#904](https://github.com/terraform-providers/terraform-provider-aws/issues/904)) -* resource/dynamodb_table: Expose stream_label attribute ([#20](https://github.com/terraform-providers/terraform-provider-aws/issues/20)) -* resource/opsworks: Add support for configurable timeouts in AWS OpsWorks Instances. ([#857](https://github.com/terraform-providers/terraform-provider-aws/issues/857)) -* Fix handling of AdRoll's hologram clients ([#17](https://github.com/terraform-providers/terraform-provider-aws/issues/17)) -* resource/sqs_queue: Add support for name_prefix to aws_sqs_queue ([#855](https://github.com/terraform-providers/terraform-provider-aws/issues/855)) -* resource/iam_role: Add support for iam_role tp force_detach_policies ([#890](https://github.com/terraform-providers/terraform-provider-aws/issues/890)) +* provider: Always enable shared configuration file support (no longer require `AWS_SDK_LOAD_CONFIG` environment variable) ([#14077](https://github.com/terraform-providers/terraform-provider-aws/issues/14077)) +* provider: Add `assume_role` configuration block `duration_seconds`, `policy_arns`, `tags`, and `transitive_tag_keys` arguments ([#14077](https://github.com/terraform-providers/terraform-provider-aws/issues/14077)) +* data-source/aws_instance: Add `secondary_private_ips` attribute ([#14079](https://github.com/terraform-providers/terraform-provider-aws/issues/14079)) +* data-source/aws_s3_bucket: Replace `GetBucketLocation` API call with custom HTTP call for FIPS endpoint support ([#14221](https://github.com/terraform-providers/terraform-provider-aws/issues/14221)) +* resource/aws_acm_certificate: Enable `domain_validation_options` usage in downstream resource `count` and `for_each` references ([#14199](https://github.com/terraform-providers/terraform-provider-aws/issues/14199)) +* resource/aws_api_gateway_authorizer: Add plan-time validation to `authorizer_credentials` argument ([#12643](https://github.com/terraform-providers/terraform-provider-aws/issues/12643)) +* resource/aws_api_gateway_method_settings: Add import support ([#14266](https://github.com/terraform-providers/terraform-provider-aws/issues/14266)) +* resource/aws_apigatewayv2_integration: Add `request_parameters` attribute ([#14080](https://github.com/terraform-providers/terraform-provider-aws/issues/14080)) +* resource/aws_apigatewayv2_integration: Add `tls_config` attribute ([#13013](https://github.com/terraform-providers/terraform-provider-aws/issues/13013)) +* resource/aws_apigatewayv2_route: Support for updating route key ([#13833](https://github.com/terraform-providers/terraform-provider-aws/issues/13833)) +* resource/aws_apigatewayv2_stage: Make `deployment_id` a `Computed` attribute ([#13644](https://github.com/terraform-providers/terraform-provider-aws/issues/13644)) +* resource/aws_fsx_lustre_file_system: Add `deployment_type` and `per_unit_storage_throughput` attributes ([#13639](https://github.com/terraform-providers/terraform-provider-aws/issues/13639)) +* resource_aws_fsx_windows_file_system - add `storage_type` argument. ([#14316](https://github.com/terraform-providers/terraform-provider-aws/issues/14316)) +* resource_aws_fsx_windows_file_system: add support for multi-az ([#12676](https://github.com/terraform-providers/terraform-provider-aws/issues/12676)) +* resource_aws_fsx_windows_file_system: add `SINGLE_AZ_2` deployment type ([#12676](https://github.com/terraform-providers/terraform-provider-aws/issues/12676)) +* resource_aws_fsx_windows_file_system: adds `preferred_file_server_ip`, `remote_administration_endpoint` attributes ([#12676](https://github.com/terraform-providers/terraform-provider-aws/issues/12676)) +* resource/aws_instance: Add `secondary_private_ips` argument (conflicts with `network_interface` configuration block) ([#14079](https://github.com/terraform-providers/terraform-provider-aws/issues/14079)) -BUG FIXES: +BUG FIXES -* fix aws cidr validation error [[#15158](https://github.com/terraform-providers/terraform-provider-aws/issues/15158)](https://github.com/hashicorp/terraform/pull/15158) -* resource/elasticache_parameter_group: Retry deletion on InvalidCacheParameterGroupState ([#8](https://github.com/terraform-providers/terraform-provider-aws/issues/8)) -* resource/security_group: Raise creation timeout ([#9](https://github.com/terraform-providers/terraform-provider-aws/issues/9)) -* resource/rds_cluster: Retry modification on InvalidDBClusterStateFault ([#18](https://github.com/terraform-providers/terraform-provider-aws/issues/18)) -* resource/lambda: Fix incorrect GovCloud regexes ([#16](https://github.com/terraform-providers/terraform-provider-aws/issues/16)) -* Allow ipv6_cidr_block to be assigned to peering_connection ([#879](https://github.com/terraform-providers/terraform-provider-aws/issues/879)) -* resource/rds_db_instance: Correctly create cross-region encrypted replica ([#865](https://github.com/terraform-providers/terraform-provider-aws/issues/865)) -* resource/eip: dissociate EIP on update ([#878](https://github.com/terraform-providers/terraform-provider-aws/issues/878)) -* resource/iam_server_certificate: Increase deletion timeout ([#907](https://github.com/terraform-providers/terraform-provider-aws/issues/907)) +* provider: Ensure nil is not passed to RetryError helpers, may result in some bug fixes ([#14104](https://github.com/terraform-providers/terraform-provider-aws/issues/14104)) +* provider: Ensure configured STS endpoint is used during `AssumeRole` API calls ([#14077](https://github.com/terraform-providers/terraform-provider-aws/issues/14077)) +* provider: Prefer AWS shared configuration over EC2 metadata credentials by default ([#14077](https://github.com/terraform-providers/terraform-provider-aws/issues/14077)) +* provider: Prefer CodeBuild, ECS, EKS credentials over EC2 metadata credentials by default ([#14077](https://github.com/terraform-providers/terraform-provider-aws/issues/14077)) +* data-source/aws_lb: `enable_http2` now properly set ([#14167](https://github.com/terraform-providers/terraform-provider-aws/issues/14167)) +* resource/aws_acm_certificate: Prevent unexpected ordering differences with `domain_validation_options` attribute ([#14199](https://github.com/terraform-providers/terraform-provider-aws/issues/14199)) +* resource/aws_api_gateway_authorizer: Allow `authorizer_result_ttl_in_seconds` to be set to 0 ([#12643](https://github.com/terraform-providers/terraform-provider-aws/issues/12643)) +* resource/aws_apigatewayv2_integration: Correctly handle the `integration_method` attribute for AWS Lambda integrations([#13266](https://github.com/terraform-providers/terraform-provider-aws/issues/13266)) +* resource/aws_apigatewayv2_integration: Correctly handle the `passthrough_behavior` attribute for HTTP APIs ([#13062](https://github.com/terraform-providers/terraform-provider-aws/issues/13062)) +* resource/aws_apigatewayv2_stage: Correctly handle `default_route_setting` and `route_setting` `data_trace_enabled` and `logging_level` for HTTP APIs. `logging_level` is now `Computed`, meaning Terraform will only perform drift detection of its value when present in a configuration. ([#13809](https://github.com/terraform-providers/terraform-provider-aws/issues/13809)) +* resource/aws_appautoscaling_target: Only retry `DeregisterScalableTarget` retries on all errors on deletion ([#14259](https://github.com/terraform-providers/terraform-provider-aws/issues/14259)) +* resource/aws_dx_gateway_association: Increase default create/update/delete timeouts to 30 minutes ([#14144](https://github.com/terraform-providers/terraform-provider-aws/issues/14144)) +* resource/aws_codepipeline: Only retry `CreatePipeline` errors for IAM eventual consistency errors ([#14264](https://github.com/terraform-providers/terraform-provider-aws/issues/14264)) +* resource/aws_elasticsearch_domain: Update method to properly set `advanced_security_options` ([#14167](https://github.com/terraform-providers/terraform-provider-aws/issues/14167)) +* resource/aws_lambda_function: Increase IAM retry timeout for creation to standard 2 minute timeout ([#14291](https://github.com/terraform-providers/terraform-provider-aws/issues/14291)) +* resource/aws_lb_cookie_stickiness_policy: `lb_port` now properly set ([#14167](https://github.com/terraform-providers/terraform-provider-aws/issues/14167)) +* resource/aws_network_acl_rule: Immediately return `DescribeNetworkAcls` errors on creation ([#14261](https://github.com/terraform-providers/terraform-provider-aws/issues/14261)) +* resource/aws_s3_bucket: Replace `GetBucketLocation` API call with custom HTTP call for FIPS endpoint support ([#14221](https://github.com/terraform-providers/terraform-provider-aws/issues/14221)) +* resource/aws_sns_topic_subscription: Immediately return `ListSubscriptionsByTopic` errors ([#14262](https://github.com/terraform-providers/terraform-provider-aws/issues/14262)) +* resource/aws_spot_fleet_request: Only retry `RequestSpotFleet` on IAM eventual consistency errors and use standard 2 minute timeout ([#14265](https://github.com/terraform-providers/terraform-provider-aws/issues/14265)) +* resource/aws_spot_instance_request: `primary_network_interface_id` now properly set ([#14167](https://github.com/terraform-providers/terraform-provider-aws/issues/14167)) +* resource/aws_ssm_activation: Only retry `CreateActivation` on IAM eventual consistency errors and use standard 2 minute timeout ([#14263](https://github.com/terraform-providers/terraform-provider-aws/issues/14263)) +* resource/aws_ssm_association: `parameters` now properly set ([#14167](https://github.com/terraform-providers/terraform-provider-aws/issues/14167)) + +## Previous Releases + +For information on prior major releases, see their changelogs: + +* [2.x and earlier](https://github.com/terraform-providers/terraform-provider-aws/blob/release/2.x/CHANGELOG.md) diff --git a/GNUmakefile b/GNUmakefile index 8b86351dce1..a77cf6cea3d 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -3,8 +3,8 @@ TEST?=./... SWEEP_DIR?=./aws GOFMT_FILES?=$$(find . -name '*.go' |grep -v vendor) PKG_NAME=aws -WEBSITE_REPO=github.com/hashicorp/terraform-website TEST_COUNT?=1 +ACCTEST_PARALLELISM?=20 default: build @@ -23,11 +23,21 @@ test: fmtcheck go test $(TEST) $(TESTARGS) -timeout=120s -parallel=4 testacc: fmtcheck - TF_ACC=1 go test $(TEST) -v -count $(TEST_COUNT) -parallel 20 $(TESTARGS) -timeout 120m + @if [ "$(TESTARGS)" = "-run=TestAccXXX" ]; then \ + echo ""; \ + echo "Error: Skipping example acceptance testing pattern. Update TESTARGS to match the test naming in the relevant *_test.go file."; \ + echo ""; \ + echo "For example if updating aws/resource_aws_acm_certificate.go, use the test names in aws/resource_aws_acm_certificate_test.go starting with TestAcc and up to the underscore:"; \ + echo "make testacc TESTARGS='-run=TestAccAWSAcmCertificate_'"; \ + echo ""; \ + echo "See the contributing guide for more information: https://github.com/terraform-providers/terraform-provider-aws/blob/master/docs/contributing/running-and-writing-acceptance-tests.md"; \ + exit 1; \ + fi + TF_ACC=1 go test ./$(PKG_NAME) -v -count $(TEST_COUNT) -parallel $(ACCTEST_PARALLELISM) $(TESTARGS) -timeout 120m fmt: @echo "==> Fixing source code with gofmt..." - gofmt -s -w ./$(PKG_NAME) + gofmt -s -w ./$(PKG_NAME) ./awsproviderlint # Currently required by tf-deploy compile fmtcheck: @@ -49,6 +59,22 @@ depscheck: @git diff --compact-summary --exit-code -- vendor || \ (echo; echo "Unexpected difference in vendor/ directory. Run 'go mod vendor' command or revert any go.mod/go.sum/vendor changes and commit."; exit 1) +docs-lint: + @echo "==> Checking docs against linters..." + @misspell -error -source=text docs/ || (echo; \ + echo "Unexpected misspelling found in docs files."; \ + echo "To automatically fix the misspelling, run 'make docs-lint-fix' and commit the changes."; \ + exit 1) + @docker run -v $(PWD):/markdown 06kellyjac/markdownlint-cli docs/ || (echo; \ + echo "Unexpected issues found in docs Markdown files."; \ + echo "To apply any automatic fixes, run 'make docs-lint-fix' and commit the changes."; \ + exit 1) + +docs-lint-fix: + @echo "==> Applying automatic docs linter fixes..." + @misspell -w -source=text docs/ + @docker run -v $(PWD):/markdown 06kellyjac/markdownlint-cli --fix docs/ + docscheck: @tfproviderdocs check \ -allowed-resource-subcategories-file website/allowed-subcategories.txt \ @@ -56,26 +82,34 @@ docscheck: -require-resource-subcategory @misspell -error -source text CHANGELOG.md -lint: - @echo "==> Checking source code against linters..." +lint: golangci-lint awsproviderlint + +golangci-lint: @golangci-lint run ./$(PKG_NAME)/... + +awsproviderlint: @awsproviderlint \ -c 1 \ -AT001 \ -AT002 \ + -AT003 \ -AT005 \ -AT006 \ -AT007 \ -AT008 \ + -AWSAT001 \ + -AWSAT004 \ -AWSR001 \ -AWSR002 \ -R002 \ -R003 \ -R004 \ + -R005 \ -R006 \ -R007 \ -R008 \ -R009 \ + -R011 \ -R012 \ -R013 \ -R014 \ @@ -84,6 +118,7 @@ lint: -S003 \ -S004 \ -S005 \ + -S006 \ -S007 \ -S008 \ -S009 \ @@ -95,6 +130,7 @@ lint: -S015 \ -S016 \ -S017 \ + -S018 \ -S019 \ -S020 \ -S021 \ @@ -138,13 +174,6 @@ test-compile: fi go test -c $(TEST) $(TESTARGS) -website: -ifeq (,$(wildcard $(GOPATH)/src/$(WEBSITE_REPO))) - echo "$(WEBSITE_REPO) not found in your GOPATH (necessary for layouts and assets), get-ting..." - git clone https://$(WEBSITE_REPO) $(GOPATH)/src/$(WEBSITE_REPO) -endif - @$(MAKE) -C $(GOPATH)/src/$(WEBSITE_REPO) website-provider PROVIDER_PATH=$(shell pwd) PROVIDER_NAME=$(PKG_NAME) - website-link-check: @scripts/markdown-link-check.sh @@ -170,12 +199,4 @@ website-lint-fix: @docker run -v $(PWD):/markdown 06kellyjac/markdownlint-cli --fix website/docs/ @terrafmt fmt ./website --pattern '*.markdown' -website-test: -ifeq (,$(wildcard $(GOPATH)/src/$(WEBSITE_REPO))) - echo "$(WEBSITE_REPO) not found in your GOPATH (necessary for layouts and assets), get-ting..." - git clone https://$(WEBSITE_REPO) $(GOPATH)/src/$(WEBSITE_REPO) -endif - @$(MAKE) -C $(GOPATH)/src/$(WEBSITE_REPO) website-provider-test PROVIDER_PATH=$(shell pwd) PROVIDER_NAME=$(PKG_NAME) - -.PHONY: build gen sweep test testacc fmt fmtcheck lint tools test-compile website website-link-check website-lint website-lint-fix website-test depscheck docscheck - +.PHONY: awsproviderlint build gen golangci-lint sweep test testacc fmt fmtcheck lint tools test-compile website-link-check website-lint website-lint-fix depscheck docscheck diff --git a/README.md b/README.md index fb6fcab76e3..42d2eb0bf22 100644 --- a/README.md +++ b/README.md @@ -1,82 +1,46 @@ -Terraform Provider for AWS -================== + + Terraform logo + -- Website: https://www.terraform.io -- [![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 Provider for AWS - +[![Forums][discuss-badge]][discuss] -Requirements ------------- +[discuss-badge]: https://img.shields.io/badge/discuss-terraform--aws-623CE4.svg?style=flat +[discuss]: https://discuss.hashicorp.com/c/terraform-providers/tf-aws/ -- [Terraform](https://www.terraform.io/downloads.html) 0.10+ -- [Go](https://golang.org/doc/install) 1.13 (to build the provider plugin) +- Website: [terraform.io](https://terraform.io) +- Tutorials: [learn.hashicorp.com](https://learn.hashicorp.com/terraform?track=getting-started#getting-started) +- Forum: [discuss.hashicorp.com](https://discuss.hashicorp.com/c/terraform-providers/tf-aws/) +- Chat: [gitter](https://gitter.im/hashicorp-terraform/Lobby) +- Mailing List: [Google Groups](http://groups.google.com/group/terraform-tool) -Developing the Provider ---------------------- +The Terraform AWS provider is a plugin for Terraform that allows for the full lifecycle management of AWS resources. +This provider is maintained internally by the HashiCorp AWS Provider team. -If you wish to work on the provider, you'll first need [Go](http://www.golang.org) installed on your machine (please check the [requirements](https://github.com/terraform-providers/terraform-provider-aws#requirements) before proceeding). +Please note: We take Terraform's security and our users' trust very seriously. If you believe you have found a security issue in the Terraform AWS Provider, please responsibly disclose by contacting us at security@hashicorp.com. -*Note:* This project uses [Go Modules](https://blog.golang.org/using-go-modules) making it safe to work with it outside of your existing [GOPATH](http://golang.org/doc/code.html#GOPATH). The instructions that follow assume a directory in your home directory outside of the standard GOPATH (i.e `$HOME/development/terraform-providers/`). +## Quick Starts -Clone repository to: `$HOME/development/terraform-providers/` +- [Using the provider](https://www.terraform.io/docs/providers/aws/index.html) +- [Provider development](docs/DEVELOPMENT.md) -```sh -$ mkdir -p $HOME/development/terraform-providers/; cd $HOME/development/terraform-providers/ -$ git clone git@github.com:terraform-providers/terraform-provider-aws -... -``` +## Documentation -Enter the provider directory and run `make tools`. This will install the needed tools for the provider. +Full, comprehensive documentation is available on the Terraform website: -```sh -$ make tools -``` +https://terraform.io/docs/providers/aws/index.html -To compile the provider, run `make build`. This will build the provider and put the provider binary in the `$GOPATH/bin` directory. +## Roadmap -```sh -$ make build -... -$ $GOPATH/bin/terraform-provider-aws -... -``` +Our roadmap for expanding support in Terraform for AWS resources can be found in our [Roadmap](ROADMAP.md) which is published quarterly. -Using the Provider ----------------------- +## Frequently Asked Questions -To use a released provider in your Terraform environment, run [`terraform init`](https://www.terraform.io/docs/commands/init.html) and Terraform will automatically install the provider. To specify a particular provider version when installing released providers, see the [Terraform documentation on provider versioning](https://www.terraform.io/docs/configuration/providers.html#version-provider-versions). +Responses to our most frequently asked questions can be found in our [FAQ](docs/FAQ.md ) -To instead use a custom-built provider in your Terraform environment (e.g. the provider binary from the build instructions above), follow the instructions to [install it as a plugin.](https://www.terraform.io/docs/plugins/basics.html#installing-plugins) After placing the custom-built provider into your plugins directory, run `terraform init` to initialize it. +## Contributing -For either installation method, documentation about the provider specific configuration options can be found on the [provider's website](https://www.terraform.io/docs/providers/aws/index.html). - -Testing the Provider ---------------------------- - -In order to test the provider, you can run `make test`. - -*Note:* Make sure no `AWS_ACCESS_KEY_ID` or `AWS_SECRET_ACCESS_KEY` variables are set, and there's no `[default]` section in the AWS credentials file `~/.aws/credentials`. - -```sh -$ make test -``` - -In order to run the full suite of Acceptance tests, run `make testacc`. - -*Note:* Acceptance tests create real resources, and often cost money to run. Please read [Running an Acceptance Test](https://github.com/terraform-providers/terraform-provider-aws/blob/master/.github/CONTRIBUTING.md#running-an-acceptance-test) in the contribution guidelines for more information on usage. - -```sh -$ make testacc -``` - -Contributing ---------------------------- - -Terraform is the work of thousands of contributors. We appreciate your help! - -To contribute, please read the contribution guidelines: [Contributing to Terraform - AWS Provider](.github/CONTRIBUTING.md) - -Issues on GitHub are intended to be related to bugs or feature requests with provider codebase. See https://www.terraform.io/docs/extend/community/index.html for a list of community resources to ask questions about Terraform. +The Terraform AWS Provider is the work of thousands of contributors. We appreciate your help! +To contribute, please read the contribution guidelines: [Contributing to Terraform - AWS Provider](docs/CONTRIBUTING.md) diff --git a/ROADMAP.md b/ROADMAP.md index e52eb0cb9b1..5665e02ae32 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,94 +1,112 @@ -# Q2 2020 Roadmap - -Each quarter the team will highlight areas of focus for our work and upcoming research. - -We select items for inclusion in the roadmap from the Top 10 Community Issues, [core services](docs/CORE_SERVICES.md), and internal priorities. When community pull requests exist for a given item, we will prioritize working with the original authors to include their contributions. If the author can no longer take on the implementation, HashiCorp will complete any additional work needed. - -Each weekly release will include necessary tasks that lead to the completion of the stated goals as well as community pull requests, enhancements, and features that are not highlighted in the roadmap. - -To make contribution easier, we’ll be using the [`Help Wanted`](https://github.com/terraform-providers/terraform-provider-aws/labels/help%20wanted) tag to point to issues we’d like to include in this quarter’s series of releases. - -This quarter (May-July ‘20) we will be prioritizing the following areas of work: - -## Currently In Progress - -### 3.0.0 - -Milestone: [v3.0.0](https://github.com/terraform-providers/terraform-provider-aws/milestone/70) - -Each year the TF AWS Provider team releases a major version. [Major releases](https://www.terraform.io/docs/extend/best-practices/versioning.html#example-major-number-increments) include code removals, deprecations, and breaking changes. A corresponding “upgrade guide” will be published alongside the release. - -We'll be updating the linked milestone as we work to finalize and complete v3.0.0. - -### WAFv2 - -Issue: [#11406](https://github.com/terraform-providers/terraform-provider-aws/issues/11406) - -_AWS WAFv2 is a web application firewall that lets you monitor the HTTP and HTTPS requests that are forwarded to Amazon CloudFront, an Amazon API Gateway API, or an Application Load Balancer._ - -Support for WAFv2 functionality will be wholly separate from WAF “Classic”. We’ll focus on enabling community contributions to WAFv2 first. If there is not a community contribution, HashiCorp will work to add the missing resource or data source. - -Support for WAFv2 will include: - -#### Resources - -* aws_wafv2_ip_set -* aws_wafv2_regex_pattern_set -* aws_wafv2_rule_group -* aws_wafv2_web_acl -* aws_wafv2_web_acl_association - -#### Data Sources - -* aws_wafv2_ip_set -* aws_wafv2_regex_pattern_set -* aws_wafv2_rule_group -* aws_wafv2_web_acl - -### Amazon Lex - -Issue: [#905](https://github.com/terraform-providers/terraform-provider-aws/issues/905) - -_Amazon Lex is a service for building conversational interfaces into any application using voice and text. Amazon Lex provides the advanced deep learning functionalities of automatic speech recognition (ASR) for converting speech to text, and natural language understanding (NLU) to recognize the intent of the text, to enable you to build applications with highly engaging user experiences and lifelike conversational interactions._ - -We’ll focus on enabling community contributions to Lex first. If there is not a community contribution, HashiCorp will work to add the missing resource or data source. - -Support for Amazon Lex will include: - -#### Resources - -* aws_lex_slot_type -* aws_lex_intent -* aws_lex_bot -* aws_lex_bot_alias - -#### Data Sources - -* aws_lex_slot_type -* aws_lex_intent -* aws_lex_bot -* aws_lex_bot_alias - -### AWS Certificate Manager - -Issue: [#8531](https://github.com/terraform-providers/terraform-provider-aws/issues/8531) - -_AWS Certificate Manager is a service that allows you to easily provision, manage, and deploy public and private Secure Sockets Layer/Transport Layer Security (SSL/TLS) certificates for use with AWS services and your internal connected resources._ - -After evaluating the issue linked above, we concluded that the ACM resource was in need of a redesign. We’ll be prioritizing redesigning and updating the resource while we tackle the open bug reports and enhancements. Our research and redesign work will be tracked [here](https://github.com/terraform-providers/terraform-provider-aws/issues/13053). - +# Roadmap: August - October 2020 + +Every few months, the team will highlight areas of focus for our work and upcoming research. + +We select items for inclusion in the roadmap from the Top 10 Community Issues, [core services](docs/CORE_SERVICES.md), and internal priorities. When community pull requests exist for a given item, we will prioritize working with the original authors to include their contributions. If the author can no longer take on the implementation, HashiCorp will complete any additional work needed. + +Each weekly release will include necessary tasks that lead to the completion of the stated goals as well as community pull requests, enhancements, and features that are not highlighted in the roadmap. To view all the items we've prioritized for this quarter, please see the [Roadmap milestone](https://github.com/terraform-providers/terraform-provider-aws/milestone/138). + +Where community sourced contributions exist we will work with the authors to review and merge their work. Where this does not exist we will create the resources and implementation ourselves. + +From [May through July](docs/roadmaps/2020_May_to_July.md), we committed to adding support for WAFv2 and Lex. We are happy to report that WAFv2 support is now complete and we will be finishing support for Lex immediately following the release of v3.0.0. Additionally, we planned to refactor ACM and will include the redesigned resource as part of the 3.0.0 package. Lastly, we spent some time researching Default Tags and want to extend a thank you to all the folks that volunteered to assist. We’ve written a proposal for the feature that is being reviewed internally and we hope to include the functionality in the product in the future. + +From August-October ‘20, we will be prioritizing the following areas of work: + +## New Services + +### EventBridge + +Issue: [#9330](https://github.com/terraform-providers/terraform-provider-aws/issues/9330) + +_[Amazon EventBridge](https://aws.amazon.com/eventbridge/) is a serverless event bus that makes it easy to connect applications together using data from your own applications, integrated Software-as-a-Service (SaaS) applications, and AWS services. EventBridge delivers a stream of real-time data from event sources, such as Zendesk, Datadog, or Pagerduty, and routes that data to targets like AWS Lambda. You can set up routing rules to determine where to send your data to build application architectures that react in real time to all of your data sources._ + +As EventBridge exists as an addition to existing CloudWatch APIs we will perform a research phase to determine whether Terraform support should exist as separate resources, additions to existing ones, or a combination of the two. + +### EC2 Image Builder + +Issue: [#11084](https://github.com/terraform-providers/terraform-provider-aws/issues/11084) + +_[EC2 Image Builder](https://aws.amazon.com/image-builder/) simplifies the creation, maintenance, validation, sharing, and deployment of Linux or Windows Server images for use with Amazon EC2 and on-premises._ + +Support for EC2 Image Builder will include: + +New Resource(s): +- aws_imagebuilder_component +- aws_imagebuilder_distribution_configuration +- aws_imagebuilder_image +- aws_imagebuilder_image_pipeline +- aws_imagebuilder_image_recipe +- aws_imagebuilder_infrastructure_configuration + +New Data Source(s): +- aws_imagebuilder_image + +### AWS Lake Formation + +Issue: [#9700](https://github.com/terraform-providers/terraform-provider-aws/issues/9700) + +_[AWS Lake Formation](https://aws.amazon.com/lake-formation) is a service that makes it easy to set up a secure data lake in days. A data lake is a centralized, curated, and secured repository that stores all your data, both in its original form and prepared for analysis. A data lake enables you to break down data silos and combine different types of analytics to gain insights and guide better business decisions._ + +Support for AWS Lake Formation will include: + +New Resource(s): + +- aws_lakeformation_resource +- aws_lakeformation_datalake_settings +- aws_lakeformation_permissions + +### AWS Serverless Application Repository + +Issue: [#3981](https://github.com/terraform-providers/terraform-provider-aws/issues/3981) + +_The [AWS Serverless Application Repository](https://aws.amazon.com/serverless/serverlessrepo/) is a managed repository for serverless applications. It enables teams, organizations, and individual developers to store and share reusable applications, and easily assemble and deploy serverless architectures in powerful new ways. Using the Serverless Application Repository, you don't need to clone, build, package, or publish source code to AWS before deploying it. Instead, you can use pre-built applications from the Serverless Application Repository in your serverless architectures, helping you and your teams reduce duplicated work, ensure organizational best practices, and get to market faster. Integration with AWS Identity and Access Management (IAM) provides resource-level control of each application, enabling you to publicly share applications with everyone or privately share them with specific AWS accounts._ + +Support for AWS Serverless Application Repository will include: + +New Resource(s): +- aws_serverlessrepository_stack + +New Data Source(s): +- aws_serverlessrepository_application + +## Issues and Enhancements + +The issues below have gained substantial support via our community. As a result, we want to highlight our commitment to addressing them. + +- [#12690](https://github.com/terraform-providers/terraform-provider-aws/issues/12690) RDS Proxy Support +- [#11281](https://github.com/terraform-providers/terraform-provider-aws/issues/11281) Home Directory Mappings Support for AWS Transfer User +- [#384](https://github.com/terraform-providers/terraform-provider-aws/issues/384) Add support for CreateVPCAssociationAuthorization AWS API +- [#6562](https://github.com/terraform-providers/terraform-provider-aws/issues/6562) Auto Scaling Plans (Dynamic/Predictive Auto Scaling Groups) +- [#5549](https://github.com/terraform-providers/terraform-provider-aws/issues/5549) Terraform constantly updates resource policy on API Gateway +- [#11569](https://github.com/terraform-providers/terraform-provider-aws/issues/11569) aws_transfer_server: support Elastic IPs +- [#5286](https://github.com/terraform-providers/terraform-provider-aws/issues/5286) Point in time restore support for AWS RDS instances + +## United States Federal Focus + +We have added extra engineering and product capacity to enable us to provide the same compatibility and coverage assurances in the GovCloud, C2S, and SC2S regions as we currently do for Commercial AWS regions. Our attention on C2S/SC2S environments should result in better outcomes in other similar air gapped environments. Initially, we will be focusing on GovCloud and users should expect improved experiences within that region in the coming months. + +## Technical Debt Theme + +Each quarter we identify a technical debt theme for the team to focus on alongside new service additions, issue resolutions and enhancements. This quarter we are looking at spending time improving the reliability of our acceptance test framework. We have a number of flaky tests which add friction to the development cycle. Making these more consistent should improve the development experience for both contributors and maintainers. + ## Research Topics - + Research topics include features, architectural changes, and ideas that we are pursuing in the longer term that may significantly impact the core user experience of the AWS provider. Research topics are discovery only and are not guaranteed to be included in a future release. - -### Global Default Tags - -Issue: [#7926](https://github.com/terraform-providers/terraform-provider-aws/issues/7926) - -We’ve been evaluating how users approach tagging their infrastructure in Terraform and the systems and practices that may interact with TF when it comes to tagging. The [initial discussions](https://github.com/hashicorp/terraform/issues/20866) led us to prioritize functionality that allows users to ignore specific tags globally in the AWS provider. As a complement to that feature, we are exploring the ability to supply global default tags to resources defined by the AWS Provider. - -We are interested in your thoughts and feedback about this proposal and encourage you to comment on the issue linked above or schedule time with @maryelizbeth via the link on her [GitHub profile](https://github.com/maryelizbeth) to discuss. - + +We are interested in your thoughts and feedback about the proposals below and encourage you to comment on the linked issues or schedule time with @maryelizbeth via the link on her GitHub profile to discuss. + +### API Calls/IAM Actions Per Terraform Resource (Minimum IAM) + +Issue: [#9154](https://github.com/terraform-providers/terraform-provider-aws/issues/9154) + +To address security concerns and best practices we are considering how Terraform could surface minimally viable IAM policies for taking actions on resources or executing a TF plan. This is in the early stages of research and we are particularly interested in whether or not this would be useful and the resources or services areas for which it is most valuable. + +### Lifecycle: Retain [Add 'retain' attribute to the Terraform lifecycle meta-parameter] + +Issue: [#902](https://github.com/terraform-providers/terraform-provider-aws/issues/902) + +Some resources (e.g. log groups) are intended to be created but never destroyed. Terraform currently does not have a lifecycle attribute for retaining such resources. We are curious as to whether or not retaining resources is a workflow that meets the needs of our community and if so, how and where we might make use of that in the AWS Provider. + ## Disclosures - + The product-development initiatives in this document reflect HashiCorp's current plans and are subject to change and/or cancellation in HashiCorp's sole discretion. diff --git a/aws/autoscaling_tags.go b/aws/autoscaling_tags.go index ffc74eba9b2..3ed28397055 100644 --- a/aws/autoscaling_tags.go +++ b/aws/autoscaling_tags.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) // autoscalingTagSchema returns the schema to use for the tag element. @@ -56,7 +56,7 @@ func setAutoscalingTags(conn *autoscaling.AutoScaling, d *schema.ResourceData) e resourceID := d.Get("name").(string) var createTags, removeTags []*autoscaling.Tag - if d.HasChange("tag") || d.HasChange("tags") { + if d.HasChanges("tag", "tags") { oraw, nraw := d.GetChange("tag") o := setToMapByKey(oraw.(*schema.Set)) n := setToMapByKey(nraw.(*schema.Set)) @@ -80,12 +80,12 @@ func setAutoscalingTags(conn *autoscaling.AutoScaling, d *schema.ResourceData) e removeTags = append(removeTags, r...) oraw, nraw = d.GetChange("tags") - old, err = autoscalingTagsFromList(oraw.([]interface{}), resourceID) + old, err = autoscalingTagsFromList(oraw.(*schema.Set).List(), resourceID) if err != nil { return err } - new, err = autoscalingTagsFromList(nraw.([]interface{}), resourceID) + new, err = autoscalingTagsFromList(nraw.(*schema.Set).List(), resourceID) if err != nil { return err } @@ -165,7 +165,7 @@ func autoscalingTagsFromList(vs []interface{}, resourceID string) ([]*autoscalin result := make([]*autoscaling.Tag, 0, len(vs)) for _, tag := range vs { attr, ok := tag.(map[string]interface{}) - if !ok { + if !ok || len(attr) == 0 { continue } @@ -248,14 +248,21 @@ func autoscalingTagFromMap(attr map[string]interface{}, resourceID string) (*aut return t, nil } -// autoscalingTagDescriptionsToSlice turns the list of tags into a slice. -func autoscalingTagDescriptionsToSlice(ts []*autoscaling.TagDescription) []map[string]interface{} { +// autoscalingTagDescriptionsToSlice turns the list of tags into a slice. If +// forceStrings is true, all values are converted to strings +func autoscalingTagDescriptionsToSlice(ts []*autoscaling.TagDescription, forceStrings bool) []map[string]interface{} { tags := make([]map[string]interface{}, 0, len(ts)) for _, t := range ts { + var propagateAtLaunch interface{} + if forceStrings { + propagateAtLaunch = strconv.FormatBool(aws.BoolValue(t.PropagateAtLaunch)) + } else { + propagateAtLaunch = aws.BoolValue(t.PropagateAtLaunch) + } tags = append(tags, map[string]interface{}{ - "key": *t.Key, - "value": *t.Value, - "propagate_at_launch": *t.PropagateAtLaunch, + "key": aws.StringValue(t.Key), + "value": aws.StringValue(t.Value), + "propagate_at_launch": propagateAtLaunch, }) } diff --git a/aws/autoscaling_tags_test.go b/aws/autoscaling_tags_test.go index b2ec5d3ad20..48570c25e4a 100644 --- a/aws/autoscaling_tags_test.go +++ b/aws/autoscaling_tags_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestDiffAutoscalingTags(t *testing.T) { diff --git a/aws/aws_sweeper_test.go b/aws/aws_sweeper_test.go index b9a63816ea6..fdece2fff54 100644 --- a/aws/aws_sweeper_test.go +++ b/aws/aws_sweeper_test.go @@ -5,7 +5,7 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) // sweeperAwsClients is a shared cache of regional AWSClient diff --git a/aws/awserr.go b/aws/awserr.go index 8c2be2c7502..fee494789d9 100644 --- a/aws/awserr.go +++ b/aws/awserr.go @@ -6,7 +6,7 @@ import ( "time" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) // Returns true if the error matches all these conditions: diff --git a/aws/cloudfront_distribution_configuration_structure.go b/aws/cloudfront_distribution_configuration_structure.go index a9e94e883bf..5d94aee43ab 100644 --- a/aws/cloudfront_distribution_configuration_structure.go +++ b/aws/cloudfront_distribution_configuration_structure.go @@ -14,10 +14,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/cloudfront" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/terraform-providers/terraform-provider-aws/aws/internal/flatmap" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) // cloudFrontRoute53ZoneID defines the route 53 zone ID for CloudFront. This @@ -1097,20 +1096,30 @@ func flattenViewerCertificate(vc *cloudfront.ViewerCertificate) []interface{} { return []interface{}{m} } -// Convert *cloudfront.ActiveTrustedSigners to a flatmap.Map type, which ensures -// it can probably be inserted into the schema.TypeMap type used by the -// active_trusted_signers attribute. -func flattenActiveTrustedSigners(ats *cloudfront.ActiveTrustedSigners) flatmap.Map { - m := make(map[string]interface{}) - s := []interface{}{} - m["enabled"] = *ats.Enabled +func flattenCloudfrontActiveTrustedSigners(ats *cloudfront.ActiveTrustedSigners) []interface{} { + if ats == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "enabled": aws.BoolValue(ats.Enabled), + "items": flattenCloudfrontSigners(ats.Items), + } + + return []interface{}{m} +} - for _, v := range ats.Items { - signer := make(map[string]interface{}) - signer["aws_account_number"] = *v.AwsAccountNumber - signer["key_pair_ids"] = aws.StringValueSlice(v.KeyPairIds.Items) - s = append(s, signer) +func flattenCloudfrontSigners(signers []*cloudfront.Signer) []interface{} { + result := make([]interface{}, 0, len(signers)) + + for _, signer := range signers { + m := map[string]interface{}{ + "aws_account_number": aws.StringValue(signer.AwsAccountNumber), + "key_pair_ids": aws.StringValueSlice(signer.KeyPairIds.Items), + } + + result = append(result, m) } - m["items"] = s - return flatmap.Flatten(m) + + return result } diff --git a/aws/cloudfront_distribution_configuration_structure_test.go b/aws/cloudfront_distribution_configuration_structure_test.go index a1396c02eca..9cc64d67588 100644 --- a/aws/cloudfront_distribution_configuration_structure_test.go +++ b/aws/cloudfront_distribution_configuration_structure_test.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/cloudfront" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func defaultCacheBehaviorConf() map[string]interface{} { diff --git a/aws/config.go b/aws/config.go index 0348e71e5d0..458fcfc04c6 100644 --- a/aws/config.go +++ b/aws/config.go @@ -35,6 +35,7 @@ import ( "github.com/aws/aws-sdk-go/service/cloudwatch" "github.com/aws/aws-sdk-go/service/cloudwatchevents" "github.com/aws/aws-sdk-go/service/cloudwatchlogs" + "github.com/aws/aws-sdk-go/service/codeartifact" "github.com/aws/aws-sdk-go/service/codebuild" "github.com/aws/aws-sdk-go/service/codecommit" "github.com/aws/aws-sdk-go/service/codedeploy" @@ -105,8 +106,10 @@ import ( "github.com/aws/aws-sdk-go/service/mediastoredata" "github.com/aws/aws-sdk-go/service/mq" "github.com/aws/aws-sdk-go/service/neptune" + "github.com/aws/aws-sdk-go/service/networkmanager" "github.com/aws/aws-sdk-go/service/opsworks" "github.com/aws/aws-sdk-go/service/organizations" + "github.com/aws/aws-sdk-go/service/outposts" "github.com/aws/aws-sdk-go/service/personalize" "github.com/aws/aws-sdk-go/service/pinpoint" "github.com/aws/aws-sdk-go/service/pricing" @@ -116,6 +119,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/resourcegroups" + "github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi" "github.com/aws/aws-sdk-go/service/route53" "github.com/aws/aws-sdk-go/service/route53domains" "github.com/aws/aws-sdk-go/service/route53resolver" @@ -138,6 +142,7 @@ import ( "github.com/aws/aws-sdk-go/service/storagegateway" "github.com/aws/aws-sdk-go/service/sts" "github.com/aws/aws-sdk-go/service/swf" + "github.com/aws/aws-sdk-go/service/synthetics" "github.com/aws/aws-sdk-go/service/transfer" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" @@ -147,7 +152,7 @@ import ( "github.com/aws/aws-sdk-go/service/workspaces" "github.com/aws/aws-sdk-go/service/xray" awsbase "github.com/hashicorp/aws-sdk-go-base" - "github.com/hashicorp/terraform-plugin-sdk/helper/logging" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -160,10 +165,14 @@ type Config struct { Region string MaxRetries int - AssumeRoleARN string - AssumeRoleExternalID string - AssumeRoleSessionName string - AssumeRolePolicy string + AssumeRoleARN string + AssumeRoleDurationSeconds int + AssumeRoleExternalID string + AssumeRolePolicy string + AssumeRolePolicyARNs []string + AssumeRoleSessionName string + AssumeRoleTags map[string]string + AssumeRoleTransitiveTagKeys []string AllowedAccountIds []string ForbiddenAccountIds []string @@ -210,6 +219,7 @@ type AWSClient struct { cloudwatchconn *cloudwatch.CloudWatch cloudwatcheventsconn *cloudwatchevents.CloudWatchEvents cloudwatchlogsconn *cloudwatchlogs.CloudWatchLogs + codeartifactconn *codeartifact.CodeArtifact codebuildconn *codebuild.CodeBuild codecommitconn *codecommit.CodeCommit codedeployconn *codedeploy.CodeDeploy @@ -283,8 +293,10 @@ type AWSClient struct { mediastoredataconn *mediastoredata.MediaStoreData mqconn *mq.MQ neptuneconn *neptune.Neptune + networkmanagerconn *networkmanager.NetworkManager opsworksconn *opsworks.OpsWorks organizationsconn *organizations.Organizations + outpostsconn *outposts.Outposts partition string personalizeconn *personalize.Personalize pinpointconn *pinpoint.Pinpoint @@ -297,6 +309,7 @@ type AWSClient struct { redshiftconn *redshift.Redshift region string resourcegroupsconn *resourcegroups.ResourceGroups + resourcegroupstaggingapiconn *resourcegroupstaggingapi.ResourceGroupsTaggingAPI route53domainsconn *route53domains.Route53Domains route53resolverconn *route53resolver.Route53Resolver s3conn *s3.S3 @@ -320,6 +333,7 @@ type AWSClient struct { stsconn *sts.STS supportedplatforms []string swfconn *swf.SWF + syntheticsconn *synthetics.Synthetics terraformVersion string transferconn *transfer.Transfer wafconn *waf.WAF @@ -355,26 +369,31 @@ func (c *Config) Client() (interface{}, error) { } } - log.Println("[INFO] Building AWS auth structure") awsbaseConfig := &awsbase.Config{ - AccessKey: c.AccessKey, - AssumeRoleARN: c.AssumeRoleARN, - AssumeRoleExternalID: c.AssumeRoleExternalID, - AssumeRolePolicy: c.AssumeRolePolicy, - AssumeRoleSessionName: c.AssumeRoleSessionName, - CredsFilename: c.CredsFilename, - DebugLogging: logging.IsDebugOrHigher(), - IamEndpoint: c.Endpoints["iam"], - Insecure: c.Insecure, - MaxRetries: c.MaxRetries, - Profile: c.Profile, - Region: c.Region, - SecretKey: c.SecretKey, - SkipCredsValidation: c.SkipCredsValidation, - SkipMetadataApiCheck: c.SkipMetadataApiCheck, - SkipRequestingAccountId: c.SkipRequestingAccountId, - StsEndpoint: c.Endpoints["sts"], - Token: c.Token, + AccessKey: c.AccessKey, + AssumeRoleARN: c.AssumeRoleARN, + AssumeRoleDurationSeconds: c.AssumeRoleDurationSeconds, + AssumeRoleExternalID: c.AssumeRoleExternalID, + AssumeRolePolicy: c.AssumeRolePolicy, + AssumeRolePolicyARNs: c.AssumeRolePolicyARNs, + AssumeRoleSessionName: c.AssumeRoleSessionName, + AssumeRoleTags: c.AssumeRoleTags, + AssumeRoleTransitiveTagKeys: c.AssumeRoleTransitiveTagKeys, + CallerDocumentationURL: "https://registry.terraform.io/providers/hashicorp/aws", + CallerName: "Terraform AWS Provider", + CredsFilename: c.CredsFilename, + DebugLogging: logging.IsDebugOrHigher(), + IamEndpoint: c.Endpoints["iam"], + Insecure: c.Insecure, + MaxRetries: c.MaxRetries, + Profile: c.Profile, + Region: c.Region, + SecretKey: c.SecretKey, + SkipCredsValidation: c.SkipCredsValidation, + SkipMetadataApiCheck: c.SkipMetadataApiCheck, + SkipRequestingAccountId: c.SkipRequestingAccountId, + StsEndpoint: c.Endpoints["sts"], + Token: c.Token, UserAgentProducts: []*awsbase.UserAgentProduct{ {Name: "APN", Version: "1.0"}, {Name: "HashiCorp", Version: "1.0"}, @@ -385,7 +404,7 @@ func (c *Config) Client() (interface{}, error) { sess, accountID, partition, err := awsbase.GetSessionWithAccountIDAndPartition(awsbaseConfig) if err != nil { - return nil, err + return nil, fmt.Errorf("error configuring Terraform AWS Provider: %w", err) } if accountID == "" { @@ -429,6 +448,7 @@ func (c *Config) Client() (interface{}, error) { cloudwatchconn: cloudwatch.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["cloudwatch"])})), cloudwatcheventsconn: cloudwatchevents.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["cloudwatchevents"])})), cloudwatchlogsconn: cloudwatchlogs.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["cloudwatchlogs"])})), + codeartifactconn: codeartifact.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["codeartifact"])})), codebuildconn: codebuild.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["codebuild"])})), codecommitconn: codecommit.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["codecommit"])})), codedeployconn: codedeploy.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["codedeploy"])})), @@ -500,8 +520,10 @@ func (c *Config) Client() (interface{}, error) { mediastoredataconn: mediastoredata.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["mediastoredata"])})), mqconn: mq.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["mq"])})), neptuneconn: neptune.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["neptune"])})), + networkmanagerconn: networkmanager.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["networkmanager"])})), opsworksconn: opsworks.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["opsworks"])})), organizationsconn: organizations.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["organizations"])})), + outpostsconn: outposts.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["outposts"])})), partition: partition, personalizeconn: personalize.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["personalize"])})), pinpointconn: pinpoint.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["pinpoint"])})), @@ -513,6 +535,7 @@ func (c *Config) Client() (interface{}, error) { redshiftconn: redshift.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["redshift"])})), region: c.Region, resourcegroupsconn: resourcegroups.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["resourcegroups"])})), + resourcegroupstaggingapiconn: resourcegroupstaggingapi.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["resourcegroupstaggingapi"])})), route53domainsconn: route53domains.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["route53domains"])})), route53resolverconn: route53resolver.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["route53resolver"])})), s3controlconn: s3control.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["s3control"])})), @@ -532,6 +555,7 @@ func (c *Config) Client() (interface{}, error) { storagegatewayconn: storagegateway.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["storagegateway"])})), stsconn: sts.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["sts"])})), swfconn: swf.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["swf"])})), + syntheticsconn: synthetics.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["synthetics"])})), terraformVersion: c.terraformVersion, transferconn: transfer.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["transfer"])})), wafconn: waf.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["waf"])})), @@ -565,14 +589,6 @@ func (c *Config) Client() (interface{}, error) { s3Config.DisableRestProtocolURICleaning = aws.Bool(true) client.s3connUriCleaningDisabled = s3.New(sess.Copy(s3Config)) - // Handle deprecated endpoint configurations - if c.Endpoints["kinesis_analytics"] != "" { - client.kinesisanalyticsconn = kinesisanalytics.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["kinesis_analytics"])})) - } - if c.Endpoints["r53"] != "" { - route53Config.Endpoint = aws.String(c.Endpoints["r53"]) - } - // Force "global" services to correct regions switch partition { case endpoints.AwsPartitionID: @@ -709,6 +725,27 @@ func (c *Config) Client() (interface{}, error) { } }) + client.wafv2conn.Handlers.Retry.PushBack(func(r *request.Request) { + if isAWSErr(r.Error, wafv2.ErrCodeWAFInternalErrorException, "Retry your request") { + r.Retryable = aws.Bool(true) + } + + if isAWSErr(r.Error, wafv2.ErrCodeWAFServiceLinkedRoleErrorException, "Retry") { + r.Retryable = aws.Bool(true) + } + + if r.Operation.Name == "CreateIPSet" || r.Operation.Name == "CreateRegexPatternSet" || + r.Operation.Name == "CreateRuleGroup" || r.Operation.Name == "CreateWebACL" { + // WAFv2 supports tag on create which can result in the below error codes according to the documentation + if isAWSErr(r.Error, wafv2.ErrCodeWAFTagOperationException, "Retry your request") { + r.Retryable = aws.Bool(true) + } + if isAWSErr(err, wafv2.ErrCodeWAFTagOperationInternalErrorException, "Retry your request") { + r.Retryable = aws.Bool(true) + } + } + }) + if !c.SkipGetEC2Platforms { supportedPlatforms, err := GetSupportedEC2Platforms(client.ec2conn) if err != nil { diff --git a/aws/configservice.go b/aws/configservice.go index a240ab9bd30..53dbfc10559 100644 --- a/aws/configservice.go +++ b/aws/configservice.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/configservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func configDescribeOrganizationConfigRule(conn *configservice.ConfigService, name string) (*configservice.OrganizationConfigRule, error) { diff --git a/aws/core_acceptance_test.go b/aws/core_acceptance_test.go index e50d4a6bf81..8feff47b3c2 100644 --- a/aws/core_acceptance_test.go +++ b/aws/core_acceptance_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSVpc_coreMismatchedDiffs(t *testing.T) { diff --git a/aws/data_source_aws_acm_certificate.go b/aws/data_source_aws_acm_certificate.go index 7c97530d794..d33567009bb 100644 --- a/aws/data_source_aws_acm_certificate.go +++ b/aws/data_source_aws_acm_certificate.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/acm" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_acm_certificate_test.go b/aws/data_source_aws_acm_certificate_test.go index 3e17c7981c8..0c75f69ff68 100644 --- a/aws/data_source_aws_acm_certificate_test.go +++ b/aws/data_source_aws_acm_certificate_test.go @@ -7,8 +7,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/acm" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) const ACMCertificateRe = `^arn:[^:]+:acm:[^:]+:[^:]+:certificate/.+$` @@ -238,8 +238,8 @@ data "aws_acm_certificate" "test" { func testAccCheckAwsAcmCertificateDataSourceConfigWithMostRecent(domain string, mostRecent bool) string { return fmt.Sprintf(` data "aws_acm_certificate" "test" { - domain = "%s" - most_recent = %v + domain = "%s" + most_recent = %v } `, domain, mostRecent) } @@ -247,9 +247,9 @@ data "aws_acm_certificate" "test" { func testAccCheckAwsAcmCertificateDataSourceConfigWithMostRecentAndStatus(domain, status string, mostRecent bool) string { return fmt.Sprintf(` data "aws_acm_certificate" "test" { - domain = "%s" - statuses = ["%s"] - most_recent = %v + domain = "%s" + statuses = ["%s"] + most_recent = %v } `, domain, status, mostRecent) } @@ -257,9 +257,9 @@ data "aws_acm_certificate" "test" { func testAccCheckAwsAcmCertificateDataSourceConfigWithMostRecentAndTypes(domain, certType string, mostRecent bool) string { return fmt.Sprintf(` data "aws_acm_certificate" "test" { - domain = "%s" - types = ["%s"] - most_recent = %v + domain = "%s" + types = ["%s"] + most_recent = %v } `, domain, certType, mostRecent) } @@ -276,7 +276,7 @@ resource "aws_acm_certificate" "test" { } data "aws_acm_certificate" "test" { - domain = "${aws_acm_certificate.test.domain_name}" + domain = aws_acm_certificate.test.domain_name key_types = ["RSA_4096"] } `, certificate, key, rName) diff --git a/aws/data_source_aws_acmpca_certificate_authority.go b/aws/data_source_aws_acmpca_certificate_authority.go index f8af0c9a27e..84dcff34c1a 100644 --- a/aws/data_source_aws_acmpca_certificate_authority.go +++ b/aws/data_source_aws_acmpca_certificate_authority.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/acmpca" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_acmpca_certificate_authority_test.go b/aws/data_source_aws_acmpca_certificate_authority_test.go index 556e56286e2..0ab047463f0 100644 --- a/aws/data_source_aws_acmpca_certificate_authority_test.go +++ b/aws/data_source_aws_acmpca_certificate_authority_test.go @@ -4,10 +4,10 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccDataSourceAwsAcmpcaCertificateAuthority_Basic(t *testing.T) { +func TestAccDataSourceAwsAcmpcaCertificateAuthority_basic(t *testing.T) { resourceName := "aws_acmpca_certificate_authority.test" datasourceName := "data.aws_acmpca_certificate_authority.test" @@ -69,7 +69,7 @@ resource "aws_acmpca_certificate_authority" "test" { } data "aws_acmpca_certificate_authority" "test" { - arn = "${aws_acmpca_certificate_authority.test.arn}" + arn = aws_acmpca_certificate_authority.test.arn } ` diff --git a/aws/data_source_aws_ami.go b/aws/data_source_aws_ami.go index 0f5e9e12d92..a1d1aba2f54 100644 --- a/aws/data_source_aws_ami.go +++ b/aws/data_source_aws_ami.go @@ -9,10 +9,11 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -21,6 +22,10 @@ func dataSourceAwsAmi() *schema.Resource { Read: dataSourceAwsAmiRead, Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, "filter": dataSourceFiltersSchema(), "executable_users": { Type: schema.TypeList, @@ -149,6 +154,7 @@ func dataSourceAwsAmi() *schema.Resource { "ebs": { Type: schema.TypeMap, Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, }, }, @@ -173,6 +179,7 @@ func dataSourceAwsAmi() *schema.Resource { "state_reason": { Type: schema.TypeMap, Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "tags": tagsSchemaComputed(), }, @@ -182,7 +189,6 @@ func dataSourceAwsAmi() *schema.Resource { // dataSourceAwsAmiDescriptionRead performs the AMI lookup. func dataSourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn - ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig params := &ec2.DescribeImagesInput{ Owners: expandStringList(d.Get("owners").([]interface{})), @@ -208,13 +214,13 @@ func dataSourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error { // 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 == "" { + if image.Name == nil || aws.StringValue(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) + aws.StringValue(image.ImageId), aws.StringValue(image.OwnerId)) continue } - if r.MatchString(*image.Name) { + if r.MatchString(aws.StringValue(image.Name)) { filteredImages = append(filteredImages, image) } } @@ -238,13 +244,15 @@ func dataSourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error { }) } - return amiDescriptionAttributes(d, filteredImages[0], ignoreTagsConfig) + return amiDescriptionAttributes(d, filteredImages[0], meta) } // populate the numerous fields that the image description returns. -func amiDescriptionAttributes(d *schema.ResourceData, image *ec2.Image, ignoreTagsConfig *keyvaluetags.IgnoreConfig) error { +func amiDescriptionAttributes(d *schema.ResourceData, image *ec2.Image, meta interface{}) error { + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + // Simple attributes first - d.SetId(*image.ImageId) + d.SetId(aws.StringValue(image.ImageId)) d.Set("architecture", image.Architecture) d.Set("creation_date", image.CreationDate) if image.Description != nil { @@ -292,6 +300,16 @@ func amiDescriptionAttributes(d *schema.ResourceData, image *ec2.Image, ignoreTa if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(image.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { return fmt.Errorf("error setting tags: %s", err) } + + imageArn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Region: meta.(*AWSClient).region, + Resource: fmt.Sprintf("image/%s", d.Id()), + Service: "ec2", + }.String() + + d.Set("arn", imageArn) + return nil } @@ -346,11 +364,12 @@ func amiRootSnapshotId(image *ec2.Image) string { return "" } for _, bdm := range image.BlockDeviceMappings { - if bdm.DeviceName == nil || *bdm.DeviceName != *image.RootDeviceName { + if bdm.DeviceName == nil || + aws.StringValue(bdm.DeviceName) != aws.StringValue(image.RootDeviceName) { continue } if bdm.Ebs != nil && bdm.Ebs.SnapshotId != nil { - return *bdm.Ebs.SnapshotId + return aws.StringValue(bdm.Ebs.SnapshotId) } } return "" diff --git a/aws/data_source_aws_ami_ids.go b/aws/data_source_aws_ami_ids.go index 5002ab05f6e..fba0271a1cf 100644 --- a/aws/data_source_aws_ami_ids.go +++ b/aws/data_source_aws_ami_ids.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func dataSourceAwsAmiIds() *schema.Resource { diff --git a/aws/data_source_aws_ami_ids_test.go b/aws/data_source_aws_ami_ids_test.go index 75c0e1d6f2b..e2c6ba4689a 100644 --- a/aws/data_source_aws_ami_ids_test.go +++ b/aws/data_source_aws_ami_ids_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAwsAmiIds_basic(t *testing.T) { @@ -60,12 +60,12 @@ func TestAccDataSourceAwsAmiIds_sorted(t *testing.T) { const testAccDataSourceAwsAmiIdsConfig_basic = ` data "aws_ami_ids" "ubuntu" { - owners = ["099720109477"] + owners = ["099720109477"] - filter { - name = "name" - values = ["ubuntu/images/ubuntu-*-*-amd64-server-*"] - } + filter { + name = "name" + values = ["ubuntu/images/ubuntu-*-*-amd64-server-*"] + } } ` diff --git a/aws/data_source_aws_ami_test.go b/aws/data_source_aws_ami_test.go index a5d06a3b78b..7bc5e8c8cc6 100644 --- a/aws/data_source_aws_ami_test.go +++ b/aws/data_source_aws_ami_test.go @@ -5,8 +5,8 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAmiDataSource_natInstance(t *testing.T) { @@ -26,6 +26,7 @@ func TestAccAWSAmiDataSource_natInstance(t *testing.T) { // deep inspection is not included, simply the count is checked. // Tags and product codes may need more testing, but I'm having a hard time finding images with // these attributes set. + testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), resource.TestCheckResourceAttr(resourceName, "architecture", "x86_64"), resource.TestCheckResourceAttr(resourceName, "block_device_mappings.#", "1"), resource.TestMatchResourceAttr(resourceName, "creation_date", regexp.MustCompile("^20[0-9]{2}-")), @@ -170,19 +171,22 @@ data "aws_ami" "nat_ami" { owners = ["amazon"] filter { - name = "name" + name = "name" values = ["amzn-ami-vpc-nat*"] } + filter { - name = "virtualization-type" + name = "virtualization-type" values = ["hvm"] } + filter { - name = "root-device-type" + name = "root-device-type" values = ["ebs"] } + filter { - name = "block-device-mapping.volume-type" + name = "block-device-mapping.volume-type" values = ["standard"] } } @@ -195,19 +199,22 @@ data "aws_ami" "windows_ami" { owners = ["amazon"] filter { - name = "name" + name = "name" values = ["Windows_Server-2012-R2*"] } + filter { - name = "virtualization-type" + name = "virtualization-type" values = ["hvm"] } + filter { - name = "root-device-type" + name = "root-device-type" values = ["ebs"] } + filter { - name = "block-device-mapping.volume-type" + name = "block-device-mapping.volume-type" values = ["gp2"] } } @@ -220,15 +227,17 @@ data "aws_ami" "instance_store_ami" { owners = ["099720109477"] filter { - name = "name" + name = "name" values = ["ubuntu/images/hvm-instance/ubuntu-trusty-14.04-amd64-server*"] } + filter { - name = "virtualization-type" + name = "virtualization-type" values = ["hvm"] } + filter { - name = "root-device-type" + name = "root-device-type" values = ["instance-store"] } } @@ -238,11 +247,13 @@ data "aws_ami" "instance_store_ami" { const testAccCheckAwsAmiDataSourceNameRegexConfig = ` data "aws_ami" "name_regex_filtered_ami" { most_recent = true - owners = ["amazon"] + owners = ["amazon"] + filter { - name = "name" + name = "name" values = ["amzn-ami-*"] } + name_regex = "^amzn-ami-\\d{3}[5].*-ecs-optimized" } ` diff --git a/aws/data_source_aws_api_gateway_api_key.go b/aws/data_source_aws_api_gateway_api_key.go index 5af057c4a62..a76f673ea40 100644 --- a/aws/data_source_aws_api_gateway_api_key.go +++ b/aws/data_source_aws_api_gateway_api_key.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_api_gateway_api_key_test.go b/aws/data_source_aws_api_gateway_api_key_test.go index 4f10d332f48..fc7b2374311 100644 --- a/aws/data_source_aws_api_gateway_api_key_test.go +++ b/aws/data_source_aws_api_gateway_api_key_test.go @@ -4,11 +4,11 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccDataSourceAwsApiGatewayApiKey(t *testing.T) { +func TestAccDataSourceAwsApiGatewayApiKey_basic(t *testing.T) { rName := acctest.RandString(8) resourceName1 := "aws_api_gateway_api_key.example_key" dataSourceName1 := "data.aws_api_gateway_api_key.test_key" @@ -41,7 +41,7 @@ resource "aws_api_gateway_api_key" "example_key" { } data "aws_api_gateway_api_key" "test_key" { - id = "${aws_api_gateway_api_key.example_key.id}" + id = aws_api_gateway_api_key.example_key.id } `, r) } diff --git a/aws/data_source_aws_api_gateway_resource.go b/aws/data_source_aws_api_gateway_resource.go index 1fe3ba4a54f..aa02a6c5f69 100644 --- a/aws/data_source_aws_api_gateway_resource.go +++ b/aws/data_source_aws_api_gateway_resource.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsApiGatewayResource() *schema.Resource { diff --git a/aws/data_source_aws_api_gateway_resource_test.go b/aws/data_source_aws_api_gateway_resource_test.go index b092c55566f..1a1511d55fa 100644 --- a/aws/data_source_aws_api_gateway_resource_test.go +++ b/aws/data_source_aws_api_gateway_resource_test.go @@ -4,11 +4,11 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccDataSourceAwsApiGatewayResource(t *testing.T) { +func TestAccDataSourceAwsApiGatewayResource_basic(t *testing.T) { rName := acctest.RandString(8) resourceName1 := "aws_api_gateway_resource.example_v1" dataSourceName1 := "data.aws_api_gateway_resource.example_v1" @@ -41,24 +41,24 @@ resource "aws_api_gateway_rest_api" "example" { } resource "aws_api_gateway_resource" "example_v1" { - rest_api_id = "${aws_api_gateway_rest_api.example.id}" - parent_id = "${aws_api_gateway_rest_api.example.root_resource_id}" + rest_api_id = aws_api_gateway_rest_api.example.id + parent_id = aws_api_gateway_rest_api.example.root_resource_id path_part = "v1" } resource "aws_api_gateway_resource" "example_v1_endpoint" { - rest_api_id = "${aws_api_gateway_rest_api.example.id}" - parent_id = "${aws_api_gateway_resource.example_v1.id}" + rest_api_id = aws_api_gateway_rest_api.example.id + parent_id = aws_api_gateway_resource.example_v1.id path_part = "endpoint" } data "aws_api_gateway_resource" "example_v1" { - rest_api_id = "${aws_api_gateway_rest_api.example.id}" + rest_api_id = aws_api_gateway_rest_api.example.id path = "/${aws_api_gateway_resource.example_v1.path_part}" } data "aws_api_gateway_resource" "example_v1_endpoint" { - rest_api_id = "${aws_api_gateway_rest_api.example.id}" + rest_api_id = aws_api_gateway_rest_api.example.id path = "/${aws_api_gateway_resource.example_v1.path_part}/${aws_api_gateway_resource.example_v1_endpoint.path_part}" } `, r) diff --git a/aws/data_source_aws_api_gateway_rest_api.go b/aws/data_source_aws_api_gateway_rest_api.go index f6d74b4edb8..e07f70c765a 100644 --- a/aws/data_source_aws_api_gateway_rest_api.go +++ b/aws/data_source_aws_api_gateway_rest_api.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_api_gateway_rest_api_test.go b/aws/data_source_aws_api_gateway_rest_api_test.go index 05cfeea8091..5c993ba7f25 100644 --- a/aws/data_source_aws_api_gateway_rest_api_test.go +++ b/aws/data_source_aws_api_gateway_rest_api_test.go @@ -3,8 +3,8 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAwsApiGatewayRestApi_basic(t *testing.T) { diff --git a/aws/data_source_aws_api_gateway_vpc_link.go b/aws/data_source_aws_api_gateway_vpc_link.go index 4d1edd470ab..7ee7a55c076 100644 --- a/aws/data_source_aws_api_gateway_vpc_link.go +++ b/aws/data_source_aws_api_gateway_vpc_link.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_api_gateway_vpc_link_test.go b/aws/data_source_aws_api_gateway_vpc_link_test.go index c0f7e4f1b5d..7c66203e32f 100644 --- a/aws/data_source_aws_api_gateway_vpc_link_test.go +++ b/aws/data_source_aws_api_gateway_vpc_link_test.go @@ -4,11 +4,11 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccDataSourceAwsApiGatewayVpcLink(t *testing.T) { +func TestAccDataSourceAwsApiGatewayVpcLink_basic(t *testing.T) { rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(8)) resourceName := "aws_api_gateway_vpc_link.vpc_link" dataSourceName := "data.aws_api_gateway_vpc_link.vpc_link" @@ -46,7 +46,7 @@ resource "aws_lb" "apigateway_vpclink_test" { name = "%s" subnets = [ - "${aws_subnet.apigateway_vpclink_test_subnet1.id}", + aws_subnet.apigateway_vpclink_test_subnet1.id, ] load_balancer_type = "network" @@ -64,7 +64,7 @@ resource "aws_lb" "apigateway_vpclink_test2" { name = "%s-wrong" subnets = [ - "${aws_subnet.apigateway_vpclink_test_subnet1.id}", + aws_subnet.apigateway_vpclink_test_subnet1.id, ] load_balancer_type = "network" @@ -79,7 +79,7 @@ resource "aws_lb" "apigateway_vpclink_test2" { } resource "aws_subnet" "apigateway_vpclink_test_subnet1" { - vpc_id = "${aws_vpc.apigateway_vpclink_test.id}" + vpc_id = aws_vpc.apigateway_vpclink_test.id cidr_block = "10.0.1.0/24" tags = { @@ -89,16 +89,16 @@ resource "aws_subnet" "apigateway_vpclink_test_subnet1" { resource "aws_api_gateway_vpc_link" "vpc_link" { name = "%s" - target_arns = ["${aws_lb.apigateway_vpclink_test.arn}"] + target_arns = [aws_lb.apigateway_vpclink_test.arn] } resource "aws_api_gateway_vpc_link" "vpc_link2" { name = "%s-wrong" - target_arns = ["${aws_lb.apigateway_vpclink_test2.arn}"] + target_arns = [aws_lb.apigateway_vpclink_test2.arn] } data "aws_api_gateway_vpc_link" "vpc_link" { - name = "${aws_api_gateway_vpc_link.vpc_link.name}" + name = aws_api_gateway_vpc_link.vpc_link.name } `, r, r, r, r) } diff --git a/aws/data_source_aws_arn.go b/aws/data_source_aws_arn.go index 005805e65b8..f0a7fa5d418 100644 --- a/aws/data_source_aws_arn.go +++ b/aws/data_source_aws_arn.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/aws/aws-sdk-go/aws/arn" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsArn() *schema.Resource { diff --git a/aws/data_source_aws_arn_test.go b/aws/data_source_aws_arn_test.go index a180520d927..88cb34fc97b 100644 --- a/aws/data_source_aws_arn_test.go +++ b/aws/data_source_aws_arn_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccDataSourceAwsArn_basic(t *testing.T) { diff --git a/aws/data_source_aws_autoscaling_group.go b/aws/data_source_aws_autoscaling_group.go index 9e908eb4103..45e18924d81 100644 --- a/aws/data_source_aws_autoscaling_group.go +++ b/aws/data_source_aws_autoscaling_group.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsAutoscalingGroup() *schema.Resource { diff --git a/aws/data_source_aws_autoscaling_group_test.go b/aws/data_source_aws_autoscaling_group_test.go index fdb44b0278e..d7001ba1575 100644 --- a/aws/data_source_aws_autoscaling_group_test.go +++ b/aws/data_source_aws_autoscaling_group_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAwsAutoScalingGroupDataSource_basic(t *testing.T) { @@ -69,7 +69,7 @@ data "aws_availability_zones" "available" { resource "aws_launch_configuration" "data_source_aws_autoscaling_group_test" { name = "%[1]s" - image_id = "${data.aws_ami.ubuntu.id}" + image_id = data.aws_ami.ubuntu.id instance_type = "t2.micro" } @@ -81,8 +81,8 @@ resource "aws_autoscaling_group" "foo" { health_check_type = "ELB" desired_capacity = 0 force_delete = true - launch_configuration = "${aws_launch_configuration.data_source_aws_autoscaling_group_test.name}" - availability_zones = ["${data.aws_availability_zones.available.names[0]}", "${data.aws_availability_zones.available.names[1]}"] + launch_configuration = aws_launch_configuration.data_source_aws_autoscaling_group_test.name + availability_zones = [data.aws_availability_zones.available.names[0], data.aws_availability_zones.available.names[1]] } resource "aws_autoscaling_group" "bar" { @@ -93,12 +93,12 @@ resource "aws_autoscaling_group" "bar" { health_check_type = "ELB" desired_capacity = 0 force_delete = true - launch_configuration = "${aws_launch_configuration.data_source_aws_autoscaling_group_test.name}" - availability_zones = ["${data.aws_availability_zones.available.names[0]}", "${data.aws_availability_zones.available.names[1]}"] + launch_configuration = aws_launch_configuration.data_source_aws_autoscaling_group_test.name + availability_zones = [data.aws_availability_zones.available.names[0], data.aws_availability_zones.available.names[1]] } data "aws_autoscaling_group" "good_match" { - name = "${aws_autoscaling_group.foo.name}" + name = aws_autoscaling_group.foo.name } `, rName) } diff --git a/aws/data_source_aws_autoscaling_groups.go b/aws/data_source_aws_autoscaling_groups.go index 3ac5ba31375..5594920a6f1 100644 --- a/aws/data_source_aws_autoscaling_groups.go +++ b/aws/data_source_aws_autoscaling_groups.go @@ -8,7 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsAutoscalingGroups() *schema.Resource { diff --git a/aws/data_source_aws_autoscaling_groups_test.go b/aws/data_source_aws_autoscaling_groups_test.go index dfad46e0eab..f11a8b8e916 100644 --- a/aws/data_source_aws_autoscaling_groups_test.go +++ b/aws/data_source_aws_autoscaling_groups_test.go @@ -7,9 +7,9 @@ import ( "strconv" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAutoscalingGroups_basic(t *testing.T) { @@ -102,12 +102,12 @@ data "aws_availability_zones" "available" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t1.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] name = "test-asg-%d" max_size = 1 min_size = 0 @@ -115,7 +115,7 @@ resource "aws_autoscaling_group" "bar" { desired_capacity = 0 force_delete = true - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name tag { key = "Foo" @@ -125,7 +125,7 @@ resource "aws_autoscaling_group" "bar" { } resource "aws_autoscaling_group" "foo" { - availability_zones = ["${data.aws_availability_zones.available.names[1]}"] + availability_zones = [data.aws_availability_zones.available.names[1]] name = "test-asg-%d" max_size = 1 min_size = 0 @@ -133,7 +133,7 @@ resource "aws_autoscaling_group" "foo" { desired_capacity = 0 force_delete = true - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name tag { key = "Foo" @@ -143,7 +143,7 @@ resource "aws_autoscaling_group" "foo" { } resource "aws_autoscaling_group" "barbaz" { - availability_zones = ["${data.aws_availability_zones.available.names[2]}"] + availability_zones = [data.aws_availability_zones.available.names[2]] name = "test-asg-%d" max_size = 1 min_size = 0 @@ -151,7 +151,7 @@ resource "aws_autoscaling_group" "barbaz" { desired_capacity = 0 force_delete = true - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name tag { key = "Foo" @@ -184,12 +184,12 @@ data "aws_availability_zones" "available" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t1.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] name = "test-asg-%d" max_size = 1 min_size = 0 @@ -197,7 +197,7 @@ resource "aws_autoscaling_group" "bar" { desired_capacity = 0 force_delete = true - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name tag { key = "Foo" @@ -207,7 +207,7 @@ resource "aws_autoscaling_group" "bar" { } resource "aws_autoscaling_group" "foo" { - availability_zones = ["${data.aws_availability_zones.available.names[1]}"] + availability_zones = [data.aws_availability_zones.available.names[1]] name = "test-asg-%d" max_size = 1 min_size = 0 @@ -215,7 +215,7 @@ resource "aws_autoscaling_group" "foo" { desired_capacity = 0 force_delete = true - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name tag { key = "Foo" @@ -225,7 +225,7 @@ resource "aws_autoscaling_group" "foo" { } resource "aws_autoscaling_group" "barbaz" { - availability_zones = ["${data.aws_availability_zones.available.names[2]}"] + availability_zones = [data.aws_availability_zones.available.names[2]] name = "test-asg-%d" max_size = 1 min_size = 0 @@ -233,7 +233,7 @@ resource "aws_autoscaling_group" "barbaz" { desired_capacity = 0 force_delete = true - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name tag { key = "Foo" diff --git a/aws/data_source_aws_availability_zone.go b/aws/data_source_aws_availability_zone.go index 15db6af609c..e611eda7c80 100644 --- a/aws/data_source_aws_availability_zone.go +++ b/aws/data_source_aws_availability_zone.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsAvailabilityZone() *schema.Resource { diff --git a/aws/data_source_aws_availability_zone_test.go b/aws/data_source_aws_availability_zone_test.go index 0b897c762f5..2718b182ca8 100644 --- a/aws/data_source_aws_availability_zone_test.go +++ b/aws/data_source_aws_availability_zone_test.go @@ -1,11 +1,10 @@ package aws import ( - "fmt" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAwsAvailabilityZone_AllAvailabilityZones(t *testing.T) { @@ -105,7 +104,7 @@ func TestAccDataSourceAwsAvailabilityZone_ZoneId(t *testing.T) { } func testAccDataSourceAwsAvailabilityZoneConfigAllAvailabilityZones() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "test" { state = "available" @@ -119,11 +118,11 @@ data "aws_availability_zone" "test" { all_availability_zones = true name = data.aws_availability_zones.test.names[0] } -`) +` } func testAccDataSourceAwsAvailabilityZoneConfigFilter() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "test" { state = "available" @@ -139,11 +138,11 @@ data "aws_availability_zone" "test" { values = [data.aws_availability_zones.test.names[0]] } } -`) +` } func testAccDataSourceAwsAvailabilityZoneConfigName() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "test" { state = "available" @@ -156,11 +155,11 @@ data "aws_availability_zones" "test" { data "aws_availability_zone" "test" { name = data.aws_availability_zones.test.names[0] } -`) +` } func testAccDataSourceAwsAvailabilityZoneConfigZoneId() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "test" { state = "available" @@ -173,5 +172,5 @@ data "aws_availability_zones" "test" { data "aws_availability_zone" "test" { zone_id = data.aws_availability_zones.test.zone_ids[0] } -`) +` } diff --git a/aws/data_source_aws_availability_zones.go b/aws/data_source_aws_availability_zones.go index bee053e1d9a..58e9c114929 100644 --- a/aws/data_source_aws_availability_zones.go +++ b/aws/data_source_aws_availability_zones.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func dataSourceAwsAvailabilityZones() *schema.Resource { @@ -21,12 +21,12 @@ func dataSourceAwsAvailabilityZones() *schema.Resource { Type: schema.TypeBool, Optional: true, }, - "blacklisted_names": { + "exclude_names": { Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, }, - "blacklisted_zone_ids": { + "exclude_zone_ids": { Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, @@ -34,7 +34,7 @@ func dataSourceAwsAvailabilityZones() *schema.Resource { "filter": ec2CustomFiltersSchema(), "group_names": { Type: schema.TypeSet, - Optional: true, + Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, "names": { @@ -103,8 +103,9 @@ func dataSourceAwsAvailabilityZonesRead(d *schema.ResourceData, meta interface{} return aws.StringValue(resp.AvailabilityZones[i].ZoneName) < aws.StringValue(resp.AvailabilityZones[j].ZoneName) }) - blacklistedNames := d.Get("blacklisted_names").(*schema.Set) - blacklistedZoneIDs := d.Get("blacklisted_zone_ids").(*schema.Set) + excludeNames := d.Get("exclude_names").(*schema.Set) + excludeZoneIDs := d.Get("exclude_zone_ids").(*schema.Set) + groupNames := schema.NewSet(schema.HashString, nil) names := []string{} zoneIds := []string{} @@ -113,11 +114,11 @@ func dataSourceAwsAvailabilityZonesRead(d *schema.ResourceData, meta interface{} name := aws.StringValue(v.ZoneName) zoneID := aws.StringValue(v.ZoneId) - if blacklistedNames.Contains(name) { + if excludeNames.Contains(name) { continue } - if blacklistedZoneIDs.Contains(zoneID) { + if excludeZoneIDs.Contains(zoneID) { continue } diff --git a/aws/data_source_aws_availability_zones_test.go b/aws/data_source_aws_availability_zones_test.go index 00877f12593..28ed3881ad1 100644 --- a/aws/data_source_aws_availability_zones_test.go +++ b/aws/data_source_aws_availability_zones_test.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAvailabilityZonesSort(t *testing.T) { @@ -105,53 +105,53 @@ func TestAccAWSAvailabilityZones_AllAvailabilityZones(t *testing.T) { }) } -func TestAccAWSAvailabilityZones_BlacklistedNames(t *testing.T) { - allDataSourceName := "data.aws_availability_zones.all" - blacklistedDataSourceName := "data.aws_availability_zones.test" +func TestAccAWSAvailabilityZones_Filter(t *testing.T) { + dataSourceName := "data.aws_availability_zones.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { - Config: testAccCheckAwsAvailabilityZonesConfigBlacklistedNames(), + Config: testAccCheckAwsAvailabilityZonesConfigFilter(), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsAvailabilityZonesBlacklisting(allDataSourceName, blacklistedDataSourceName), + testAccCheckAwsAvailabilityZonesMeta(dataSourceName), ), }, }, }) } -func TestAccAWSAvailabilityZones_BlacklistedZoneIds(t *testing.T) { +func TestAccAWSAvailabilityZones_ExcludeNames(t *testing.T) { allDataSourceName := "data.aws_availability_zones.all" - blacklistedDataSourceName := "data.aws_availability_zones.test" + excludeDataSourceName := "data.aws_availability_zones.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { - Config: testAccCheckAwsAvailabilityZonesConfigBlacklistedZoneIds(), + Config: testAccCheckAwsAvailabilityZonesConfigExcludeNames(), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsAvailabilityZonesBlacklisting(allDataSourceName, blacklistedDataSourceName), + testAccCheckAwsAvailabilityZonesExcluded(allDataSourceName, excludeDataSourceName), ), }, }, }) } -func TestAccAWSAvailabilityZones_Filter(t *testing.T) { - dataSourceName := "data.aws_availability_zones.test" +func TestAccAWSAvailabilityZones_ExcludeZoneIds(t *testing.T) { + allDataSourceName := "data.aws_availability_zones.all" + excludeDataSourceName := "data.aws_availability_zones.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { - Config: testAccCheckAwsAvailabilityZonesConfigFilter(), + Config: testAccCheckAwsAvailabilityZonesConfigExcludeZoneIds(), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsAvailabilityZonesMeta(dataSourceName), + testAccCheckAwsAvailabilityZonesExcluded(allDataSourceName, excludeDataSourceName), ), }, }, @@ -198,16 +198,16 @@ func testAccCheckAwsAvailabilityZonesMeta(n string) resource.TestCheckFunc { } } -func testAccCheckAwsAvailabilityZonesBlacklisting(allDataSourceName, blacklistedDataSourceName string) resource.TestCheckFunc { +func testAccCheckAwsAvailabilityZonesExcluded(allDataSourceName, excludeDataSourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { allResourceState, ok := s.RootModule().Resources[allDataSourceName] if !ok { return fmt.Errorf("Resource does not exist: %s", allDataSourceName) } - blacklistedResourceState, ok := s.RootModule().Resources[blacklistedDataSourceName] + excludeResourceState, ok := s.RootModule().Resources[excludeDataSourceName] if !ok { - return fmt.Errorf("Resource does not exist: %s", blacklistedDataSourceName) + return fmt.Errorf("Resource does not exist: %s", excludeDataSourceName) } for _, attribute := range []string{"names.#", "zone_ids.#"} { @@ -217,13 +217,13 @@ func testAccCheckAwsAvailabilityZonesBlacklisting(allDataSourceName, blacklisted return fmt.Errorf("cannot find %s in %s resource state attributes: %+v", attribute, allDataSourceName, allResourceState.Primary.Attributes) } - blacklistedValue, ok := blacklistedResourceState.Primary.Attributes[attribute] + excludeValue, ok := excludeResourceState.Primary.Attributes[attribute] if !ok { - return fmt.Errorf("cannot find %s in %s resource state attributes: %+v", attribute, blacklistedDataSourceName, blacklistedResourceState.Primary.Attributes) + return fmt.Errorf("cannot find %s in %s resource state attributes: %+v", attribute, excludeDataSourceName, excludeResourceState.Primary.Attributes) } - if allValue == blacklistedValue { + if allValue == excludeValue { return fmt.Errorf("expected %s attribute value difference, got: %s", attribute, allValue) } } @@ -296,50 +296,50 @@ func testAccCheckAwsAvailabilityZonesBuildAvailable(attrs map[string]string) ([] } const testAccCheckAwsAvailabilityZonesConfig = ` -data "aws_availability_zones" "availability_zones" { } +data "aws_availability_zones" "availability_zones" {} ` func testAccCheckAwsAvailabilityZonesConfigAllAvailabilityZones() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "test" { all_availability_zones = true } -`) +` } -func testAccCheckAwsAvailabilityZonesConfigBlacklistedNames() string { - return fmt.Sprintf(` -data "aws_availability_zones" "all" {} - +func testAccCheckAwsAvailabilityZonesConfigFilter() string { + return ` data "aws_availability_zones" "test" { - blacklisted_names = ["${data.aws_availability_zones.all.names[0]}"] + filter { + name = "state" + values = ["available"] + } } -`) +` } -func testAccCheckAwsAvailabilityZonesConfigBlacklistedZoneIds() string { - return fmt.Sprintf(` +func testAccCheckAwsAvailabilityZonesConfigExcludeNames() string { + return ` data "aws_availability_zones" "all" {} data "aws_availability_zones" "test" { - blacklisted_zone_ids = ["${data.aws_availability_zones.all.zone_ids[0]}"] + exclude_names = [data.aws_availability_zones.all.names[0]] } -`) +` } -func testAccCheckAwsAvailabilityZonesConfigFilter() string { - return fmt.Sprintf(` +func testAccCheckAwsAvailabilityZonesConfigExcludeZoneIds() string { + return ` +data "aws_availability_zones" "all" {} + data "aws_availability_zones" "test" { - filter { - name = "state" - values = ["available"] - } + exclude_zone_ids = [data.aws_availability_zones.all.zone_ids[0]] } -`) +` } const testAccCheckAwsAvailabilityZonesStateConfig = ` data "aws_availability_zones" "state_filter" { - state = "available" + state = "available" } ` diff --git a/aws/data_source_aws_backup_plan.go b/aws/data_source_aws_backup_plan.go index 05e0a454019..531872ebe4e 100644 --- a/aws/data_source_aws_backup_plan.go +++ b/aws/data_source_aws_backup_plan.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/backup" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_backup_plan_test.go b/aws/data_source_aws_backup_plan_test.go index 1031b1954ff..fdab285ded1 100644 --- a/aws/data_source_aws_backup_plan_test.go +++ b/aws/data_source_aws_backup_plan_test.go @@ -2,11 +2,11 @@ package aws import ( "fmt" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSBackupPlanDataSource_basic(t *testing.T) { @@ -37,8 +37,9 @@ func TestAccAWSBackupPlanDataSource_basic(t *testing.T) { const testAccAwsBackupPlanDataSourceConfig_nonExistent = ` data "aws_backup_plan" "test" { - plan_id = "tf-acc-test-does-not-exist" -}` + plan_id = "tf-acc-test-does-not-exist" +} +` func testAccAwsBackupPlanDataSourceConfig_basic(rInt int) string { return fmt.Sprintf(` @@ -51,7 +52,7 @@ resource "aws_backup_plan" "test" { rule { rule_name = "tf_acc_test_backup_rule_%[1]d" - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" } diff --git a/aws/data_source_aws_backup_selection.go b/aws/data_source_aws_backup_selection.go index cb26f481592..e62ff4caf2d 100644 --- a/aws/data_source_aws_backup_selection.go +++ b/aws/data_source_aws_backup_selection.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/backup" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsBackupSelection() *schema.Resource { diff --git a/aws/data_source_aws_backup_selection_test.go b/aws/data_source_aws_backup_selection_test.go index e7147ba2e8e..5df5cf66a51 100644 --- a/aws/data_source_aws_backup_selection_test.go +++ b/aws/data_source_aws_backup_selection_test.go @@ -2,11 +2,11 @@ package aws import ( "fmt" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSBackupSelectionDataSource_basic(t *testing.T) { @@ -36,9 +36,10 @@ func TestAccAWSBackupSelectionDataSource_basic(t *testing.T) { const testAccAwsBackupSelectionDataSourceConfig_nonExistent = ` data "aws_backup_selection" "test" { - plan_id = "tf-acc-test-does-not-exist" - selection_id = "tf-acc-test-dne" -}` + plan_id = "tf-acc-test-does-not-exist" + selection_id = "tf-acc-test-dne" +} +` func testAccAwsBackupSelectionDataSourceConfig_basic(rInt int) string { return fmt.Sprintf(` @@ -57,13 +58,13 @@ resource "aws_backup_plan" "test" { rule { rule_name = "tf_acc_test_backup_rule_%[1]d" - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" } } resource "aws_backup_selection" "test" { - plan_id = "${aws_backup_plan.test.id}" + plan_id = aws_backup_plan.test.id name = "tf_acc_test_backup_selection_%[1]d" iam_role_arn = "arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:role/service-role/AWSBackupDefaultServiceRole" diff --git a/aws/data_source_aws_backup_vault.go b/aws/data_source_aws_backup_vault.go index 71a911d7f97..e575fd18773 100644 --- a/aws/data_source_aws_backup_vault.go +++ b/aws/data_source_aws_backup_vault.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/backup" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_backup_vault_test.go b/aws/data_source_aws_backup_vault_test.go index 49a804a327b..48b55981b8a 100644 --- a/aws/data_source_aws_backup_vault_test.go +++ b/aws/data_source_aws_backup_vault_test.go @@ -2,11 +2,11 @@ package aws import ( "fmt" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSBackupVaultDataSource_basic(t *testing.T) { @@ -38,7 +38,7 @@ func TestAccAWSBackupVaultDataSource_basic(t *testing.T) { const testAccAwsBackupVaultDataSourceConfig_nonExistent = ` data "aws_backup_vault" "test" { - name = "tf-acc-test-does-not-exist" + name = "tf-acc-test-does-not-exist" } ` diff --git a/aws/data_source_aws_batch_compute_environment.go b/aws/data_source_aws_batch_compute_environment.go index 96c5e8564c6..c3d53a55ab9 100644 --- a/aws/data_source_aws_batch_compute_environment.go +++ b/aws/data_source_aws_batch_compute_environment.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/batch" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsBatchComputeEnvironment() *schema.Resource { diff --git a/aws/data_source_aws_batch_compute_environment_test.go b/aws/data_source_aws_batch_compute_environment_test.go index 9cc335594ab..f0ac233f208 100644 --- a/aws/data_source_aws_batch_compute_environment_test.go +++ b/aws/data_source_aws_batch_compute_environment_test.go @@ -4,12 +4,12 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccDataSourceAwsBatchComputeEnvironment(t *testing.T) { +func TestAccDataSourceAwsBatchComputeEnvironment_basic(t *testing.T) { rName := acctest.RandomWithPrefix("tf_acc_test_") resourceName := "aws_batch_compute_environment.test" datasourceName := "data.aws_batch_compute_environment.by_name" @@ -67,28 +67,28 @@ resource "aws_iam_role" "ecs_instance_role" { assume_role_policy = < 1 { + return fmt.Errorf("multiple EC2 Local Gateway Virtual Interfaces matched; use additional constraints to reduce matches to a single EC2 Local Gateway Virtual Interface") + } + + localGatewayVirtualInterface := output.LocalGatewayVirtualInterfaces[0] + + d.SetId(aws.StringValue(localGatewayVirtualInterface.LocalGatewayVirtualInterfaceId)) + d.Set("local_address", localGatewayVirtualInterface.LocalAddress) + d.Set("local_bgp_asn", localGatewayVirtualInterface.LocalBgpAsn) + d.Set("local_gateway_id", localGatewayVirtualInterface.LocalGatewayId) + d.Set("peer_address", localGatewayVirtualInterface.PeerAddress) + d.Set("peer_bgp_asn", localGatewayVirtualInterface.PeerBgpAsn) + + if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(localGatewayVirtualInterface.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %w", err) + } + + d.Set("vlan", localGatewayVirtualInterface.Vlan) + + return nil +} diff --git a/aws/data_source_aws_ec2_local_gateway_virtual_interface_group.go b/aws/data_source_aws_ec2_local_gateway_virtual_interface_group.go new file mode 100644 index 00000000000..d8a33811d7c --- /dev/null +++ b/aws/data_source_aws_ec2_local_gateway_virtual_interface_group.go @@ -0,0 +1,96 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" +) + +func dataSourceAwsEc2LocalGatewayVirtualInterfaceGroup() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsEc2LocalGatewayVirtualInterfaceGroupRead, + + Schema: map[string]*schema.Schema{ + "filter": ec2CustomFiltersSchema(), + "id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "local_gateway_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "local_gateway_virtual_interface_ids": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "tags": tagsSchemaComputed(), + }, + } +} + +func dataSourceAwsEc2LocalGatewayVirtualInterfaceGroupRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + + input := &ec2.DescribeLocalGatewayVirtualInterfaceGroupsInput{} + + if v, ok := d.GetOk("id"); ok { + input.LocalGatewayVirtualInterfaceGroupIds = []*string{aws.String(v.(string))} + } + + input.Filters = buildEC2AttributeFilterList( + map[string]string{ + "local-gateway-id": d.Get("local_gateway_id").(string), + }, + ) + + input.Filters = append(input.Filters, buildEC2TagFilterList( + keyvaluetags.New(d.Get("tags").(map[string]interface{})).Ec2Tags(), + )...) + + input.Filters = append(input.Filters, buildEC2CustomFilterList( + d.Get("filter").(*schema.Set), + )...) + + if len(input.Filters) == 0 { + // Don't send an empty filters list; the EC2 API won't accept it. + input.Filters = nil + } + + output, err := conn.DescribeLocalGatewayVirtualInterfaceGroups(input) + + if err != nil { + return fmt.Errorf("error describing EC2 Local Gateway Virtual Interface Groups: %w", err) + } + + if output == nil || len(output.LocalGatewayVirtualInterfaceGroups) == 0 { + return fmt.Errorf("no matching EC2 Local Gateway Virtual Interface Group found") + } + + if len(output.LocalGatewayVirtualInterfaceGroups) > 1 { + return fmt.Errorf("multiple EC2 Local Gateway Virtual Interface Groups matched; use additional constraints to reduce matches to a single EC2 Local Gateway Virtual Interface Group") + } + + localGatewayVirtualInterfaceGroup := output.LocalGatewayVirtualInterfaceGroups[0] + + d.SetId(aws.StringValue(localGatewayVirtualInterfaceGroup.LocalGatewayVirtualInterfaceGroupId)) + d.Set("local_gateway_id", localGatewayVirtualInterfaceGroup.LocalGatewayId) + d.Set("local_gateway_virtual_interface_group_id", localGatewayVirtualInterfaceGroup.LocalGatewayVirtualInterfaceGroupId) + + if err := d.Set("local_gateway_virtual_interface_ids", aws.StringValueSlice(localGatewayVirtualInterfaceGroup.LocalGatewayVirtualInterfaceIds)); err != nil { + return fmt.Errorf("error setting local_gateway_virtual_interface_ids: %w", err) + } + + if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(localGatewayVirtualInterfaceGroup.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %w", err) + } + + return nil +} diff --git a/aws/data_source_aws_ec2_local_gateway_virtual_interface_group_test.go b/aws/data_source_aws_ec2_local_gateway_virtual_interface_group_test.go new file mode 100644 index 00000000000..604931b17e4 --- /dev/null +++ b/aws/data_source_aws_ec2_local_gateway_virtual_interface_group_test.go @@ -0,0 +1,116 @@ +package aws + +import ( + "fmt" + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroup_Filter(t *testing.T) { + dataSourceName := "data.aws_ec2_local_gateway_virtual_interface_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupConfigFilter(), + Check: resource.ComposeTestCheckFunc( + resource.TestMatchResourceAttr(dataSourceName, "id", regexp.MustCompile(`^lgw-vif-grp-`)), + resource.TestMatchResourceAttr(dataSourceName, "local_gateway_id", regexp.MustCompile(`^lgw-`)), + resource.TestCheckResourceAttr(dataSourceName, "local_gateway_virtual_interface_ids.#", "2"), + ), + }, + }, + }) +} + +func TestAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroup_LocalGatewayId(t *testing.T) { + dataSourceName := "data.aws_ec2_local_gateway_virtual_interface_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupConfigLocalGatewayId(), + Check: resource.ComposeTestCheckFunc( + resource.TestMatchResourceAttr(dataSourceName, "id", regexp.MustCompile(`^lgw-vif-grp-`)), + resource.TestMatchResourceAttr(dataSourceName, "local_gateway_id", regexp.MustCompile(`^lgw-`)), + resource.TestCheckResourceAttr(dataSourceName, "local_gateway_virtual_interface_ids.#", "2"), + ), + }, + }, + }) +} + +func TestAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroup_Tags(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + sourceDataSourceName := "data.aws_ec2_local_gateway_virtual_interface_group.source" + dataSourceName := "data.aws_ec2_local_gateway_virtual_interface_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupConfigTags(rName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "id", sourceDataSourceName, "id"), + resource.TestCheckResourceAttrPair(dataSourceName, "local_gateway_id", sourceDataSourceName, "local_gateway_id"), + ), + }, + }, + }) +} + +func testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupConfigFilter() string { + return ` +data "aws_ec2_local_gateways" "test" {} + +data "aws_ec2_local_gateway_virtual_interface_group" "test" { + filter { + name = "local-gateway-id" + values = [tolist(data.aws_ec2_local_gateways.test.ids)[0]] + } +} +` +} + +func testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupConfigLocalGatewayId() string { + return ` +data "aws_ec2_local_gateways" "test" {} + +data "aws_ec2_local_gateway_virtual_interface_group" "test" { + local_gateway_id = tolist(data.aws_ec2_local_gateways.test.ids)[0] +} +` +} + +func testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupConfigTags(rName string) string { + return fmt.Sprintf(` +data "aws_ec2_local_gateways" "test" {} + +data "aws_ec2_local_gateway_virtual_interface_group" "source" { + filter { + name = "local-gateway-id" + values = [tolist(data.aws_ec2_local_gateways.test.ids)[0]] + } +} + +resource "aws_ec2_tag" "test" { + key = "TerraformAccTest-aws_ec2_local_gateway_virtual_interface_group" + resource_id = data.aws_ec2_local_gateway_virtual_interface_group.source.id + value = %[1]q +} + +data "aws_ec2_local_gateway_virtual_interface_group" "test" { + tags = { + (aws_ec2_tag.test.key) = aws_ec2_tag.test.value + } +} +`, rName) +} diff --git a/aws/data_source_aws_ec2_local_gateway_virtual_interface_groups.go b/aws/data_source_aws_ec2_local_gateway_virtual_interface_groups.go new file mode 100644 index 00000000000..29e36982290 --- /dev/null +++ b/aws/data_source_aws_ec2_local_gateway_virtual_interface_groups.go @@ -0,0 +1,79 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" +) + +func dataSourceAwsEc2LocalGatewayVirtualInterfaceGroups() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsEc2LocalGatewayVirtualInterfaceGroupsRead, + + Schema: map[string]*schema.Schema{ + "filter": ec2CustomFiltersSchema(), + "ids": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "local_gateway_virtual_interface_ids": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "tags": tagsSchemaComputed(), + }, + } +} + +func dataSourceAwsEc2LocalGatewayVirtualInterfaceGroupsRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + input := &ec2.DescribeLocalGatewayVirtualInterfaceGroupsInput{} + + input.Filters = append(input.Filters, buildEC2TagFilterList( + keyvaluetags.New(d.Get("tags").(map[string]interface{})).Ec2Tags(), + )...) + + input.Filters = append(input.Filters, buildEC2CustomFilterList( + d.Get("filter").(*schema.Set), + )...) + + if len(input.Filters) == 0 { + // Don't send an empty filters list; the EC2 API won't accept it. + input.Filters = nil + } + + output, err := conn.DescribeLocalGatewayVirtualInterfaceGroups(input) + + if err != nil { + return fmt.Errorf("error describing EC2 Virtual Interface Groups: %w", err) + } + + if output == nil || len(output.LocalGatewayVirtualInterfaceGroups) == 0 { + return fmt.Errorf("no matching Virtual Interface Group found") + } + + var ids, localGatewayVirtualInterfaceIds []*string + + for _, group := range output.LocalGatewayVirtualInterfaceGroups { + ids = append(ids, group.LocalGatewayVirtualInterfaceGroupId) + localGatewayVirtualInterfaceIds = append(localGatewayVirtualInterfaceIds, group.LocalGatewayVirtualInterfaceIds...) + } + + d.SetId(resource.UniqueId()) + + if err := d.Set("ids", ids); err != nil { + return fmt.Errorf("error setting ids: %w", err) + } + + if err := d.Set("local_gateway_virtual_interface_ids", localGatewayVirtualInterfaceIds); err != nil { + return fmt.Errorf("error setting local_gateway_virtual_interface_ids: %w", err) + } + + return nil +} diff --git a/aws/data_source_aws_ec2_local_gateway_virtual_interface_groups_test.go b/aws/data_source_aws_ec2_local_gateway_virtual_interface_groups_test.go new file mode 100644 index 00000000000..5cd34d09d2f --- /dev/null +++ b/aws/data_source_aws_ec2_local_gateway_virtual_interface_groups_test.go @@ -0,0 +1,108 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroups_basic(t *testing.T) { + dataSourceName := "data.aws_ec2_local_gateway_virtual_interface_groups.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupsConfig(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "local_gateway_virtual_interface_ids.#", "2"), + ), + }, + }, + }) +} + +func TestAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroups_Filter(t *testing.T) { + dataSourceName := "data.aws_ec2_local_gateway_virtual_interface_groups.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupsConfigFilter(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "local_gateway_virtual_interface_ids.#", "2"), + ), + }, + }, + }) +} + +func TestAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroups_Tags(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + dataSourceName := "data.aws_ec2_local_gateway_virtual_interface_groups.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupsConfigTags(rName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(dataSourceName, "ids.#", "1"), + resource.TestCheckResourceAttr(dataSourceName, "local_gateway_virtual_interface_ids.#", "2"), + ), + }, + }, + }) +} + +func testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupsConfig() string { + return ` +data "aws_ec2_local_gateway_virtual_interface_groups" "test" {} +` +} + +func testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupsConfigFilter() string { + return ` +data "aws_ec2_local_gateways" "test" {} + +data "aws_ec2_local_gateway_virtual_interface_groups" "test" { + filter { + name = "local-gateway-id" + values = [tolist(data.aws_ec2_local_gateways.test.ids)[0]] + } +} +` +} + +func testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceGroupsConfigTags(rName string) string { + return fmt.Sprintf(` +data "aws_ec2_local_gateways" "test" {} + +data "aws_ec2_local_gateway_virtual_interface_groups" "source" { + filter { + name = "local-gateway-id" + values = [tolist(data.aws_ec2_local_gateways.test.ids)[0]] + } +} + +resource "aws_ec2_tag" "test" { + key = "TerraformAccTest-aws_ec2_local_gateway_virtual_interface_groups" + resource_id = tolist(data.aws_ec2_local_gateway_virtual_interface_groups.source.ids)[0] + value = %[1]q +} + +data "aws_ec2_local_gateway_virtual_interface_groups" "test" { + tags = { + (aws_ec2_tag.test.key) = aws_ec2_tag.test.value + } +} +`, rName) +} diff --git a/aws/data_source_aws_ec2_local_gateway_virtual_interface_test.go b/aws/data_source_aws_ec2_local_gateway_virtual_interface_test.go new file mode 100644 index 00000000000..5c9734330c5 --- /dev/null +++ b/aws/data_source_aws_ec2_local_gateway_virtual_interface_test.go @@ -0,0 +1,138 @@ +package aws + +import ( + "fmt" + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccDataSourceAwsEc2LocalGatewayVirtualInterface_Filter(t *testing.T) { + dataSourceName := "data.aws_ec2_local_gateway_virtual_interface.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceConfigFilter(), + Check: resource.ComposeTestCheckFunc( + resource.TestMatchResourceAttr(dataSourceName, "id", regexp.MustCompile(`^lgw-vif-`)), + resource.TestMatchResourceAttr(dataSourceName, "local_address", regexp.MustCompile(`^\d+\.\d+\.\d+\.\d+/\d+$`)), + resource.TestMatchResourceAttr(dataSourceName, "local_bgp_asn", regexp.MustCompile(`^\d+$`)), + resource.TestMatchResourceAttr(dataSourceName, "local_gateway_id", regexp.MustCompile(`^lgw-`)), + resource.TestMatchResourceAttr(dataSourceName, "peer_address", regexp.MustCompile(`^\d+\.\d+\.\d+\.\d+/\d+$`)), + resource.TestMatchResourceAttr(dataSourceName, "peer_bgp_asn", regexp.MustCompile(`^\d+$`)), + resource.TestMatchResourceAttr(dataSourceName, "vlan", regexp.MustCompile(`^\d+$`)), + ), + }, + }, + }) +} + +func TestAccDataSourceAwsEc2LocalGatewayVirtualInterface_Id(t *testing.T) { + dataSourceName := "data.aws_ec2_local_gateway_virtual_interface.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceConfigId(), + Check: resource.ComposeTestCheckFunc( + resource.TestMatchResourceAttr(dataSourceName, "id", regexp.MustCompile(`^lgw-vif-`)), + resource.TestMatchResourceAttr(dataSourceName, "local_address", regexp.MustCompile(`^\d+\.\d+\.\d+\.\d+/\d+$`)), + resource.TestMatchResourceAttr(dataSourceName, "local_bgp_asn", regexp.MustCompile(`^\d+$`)), + resource.TestMatchResourceAttr(dataSourceName, "local_gateway_id", regexp.MustCompile(`^lgw-`)), + resource.TestMatchResourceAttr(dataSourceName, "peer_address", regexp.MustCompile(`^\d+\.\d+\.\d+\.\d+/\d+$`)), + resource.TestMatchResourceAttr(dataSourceName, "peer_bgp_asn", regexp.MustCompile(`^\d+$`)), + resource.TestMatchResourceAttr(dataSourceName, "vlan", regexp.MustCompile(`^\d+$`)), + ), + }, + }, + }) +} + +func TestAccDataSourceAwsEc2LocalGatewayVirtualInterface_Tags(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + sourceDataSourceName := "data.aws_ec2_local_gateway_virtual_interface.source" + dataSourceName := "data.aws_ec2_local_gateway_virtual_interface.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceConfigTags(rName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "id", sourceDataSourceName, "id"), + resource.TestCheckResourceAttrPair(dataSourceName, "local_address", sourceDataSourceName, "local_address"), + resource.TestCheckResourceAttrPair(dataSourceName, "local_bgp_asn", sourceDataSourceName, "local_bgp_asn"), + resource.TestCheckResourceAttrPair(dataSourceName, "local_gateway_id", sourceDataSourceName, "local_gateway_id"), + resource.TestCheckResourceAttrPair(dataSourceName, "peer_address", sourceDataSourceName, "peer_address"), + resource.TestCheckResourceAttrPair(dataSourceName, "peer_bgp_asn", sourceDataSourceName, "peer_bgp_asn"), + resource.TestCheckResourceAttrPair(dataSourceName, "vlan", sourceDataSourceName, "vlan"), + ), + }, + }, + }) +} + +func testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceConfigFilter() string { + return ` +data "aws_ec2_local_gateways" "test" {} + +data "aws_ec2_local_gateway_virtual_interface_group" "test" { + local_gateway_id = tolist(data.aws_ec2_local_gateways.test.ids)[0] +} + +data "aws_ec2_local_gateway_virtual_interface" "test" { + filter { + name = "local-gateway-virtual-interface-id" + values = [tolist(data.aws_ec2_local_gateway_virtual_interface_group.test.local_gateway_virtual_interface_ids)[0]] + } +} +` +} + +func testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceConfigId() string { + return ` +data "aws_ec2_local_gateways" "test" {} + +data "aws_ec2_local_gateway_virtual_interface_group" "test" { + local_gateway_id = tolist(data.aws_ec2_local_gateways.test.ids)[0] +} + +data "aws_ec2_local_gateway_virtual_interface" "test" { + id = tolist(data.aws_ec2_local_gateway_virtual_interface_group.test.local_gateway_virtual_interface_ids)[0] +} +` +} + +func testAccDataSourceAwsEc2LocalGatewayVirtualInterfaceConfigTags(rName string) string { + return fmt.Sprintf(` +data "aws_ec2_local_gateways" "test" {} + +data "aws_ec2_local_gateway_virtual_interface_group" "test" { + local_gateway_id = tolist(data.aws_ec2_local_gateways.test.ids)[0] +} + +data "aws_ec2_local_gateway_virtual_interface" "source" { + id = tolist(data.aws_ec2_local_gateway_virtual_interface_group.test.local_gateway_virtual_interface_ids)[0] +} + +resource "aws_ec2_tag" "test" { + key = "TerraformAccTest-aws_ec2_local_gateway_virtual_interface" + resource_id = data.aws_ec2_local_gateway_virtual_interface.source.id + value = %[1]q +} + +data "aws_ec2_local_gateway_virtual_interface" "test" { + tags = { + (aws_ec2_tag.test.key) = aws_ec2_tag.test.value + } +} +`, rName) +} diff --git a/aws/data_source_aws_ec2_local_gateways.go b/aws/data_source_aws_ec2_local_gateways.go index eba1a867ddf..849d916655a 100644 --- a/aws/data_source_aws_ec2_local_gateways.go +++ b/aws/data_source_aws_ec2_local_gateways.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_ec2_local_gateways_test.go b/aws/data_source_aws_ec2_local_gateways_test.go index 7e8079739c0..18a30150d6d 100644 --- a/aws/data_source_aws_ec2_local_gateways_test.go +++ b/aws/data_source_aws_ec2_local_gateways_test.go @@ -1,26 +1,16 @@ package aws import ( - "os" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAwsEc2LocalGateways_basic(t *testing.T) { - // Hide Outposts testing behind consistent environment variable - outpostArn := os.Getenv("AWS_OUTPOST_ARN") - if outpostArn == "" { - t.Skip( - "Environment variable AWS_OUTPOST_ARN is not set. " + - "This environment variable must be set to the ARN of " + - "a deployed Outpost to enable this test.") - } - dataSourceName := "data.aws_ec2_local_gateways.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { diff --git a/aws/data_source_aws_ec2_spot_price.go b/aws/data_source_aws_ec2_spot_price.go new file mode 100644 index 00000000000..ac0d7edfa74 --- /dev/null +++ b/aws/data_source_aws_ec2_spot_price.go @@ -0,0 +1,88 @@ +package aws + +import ( + "fmt" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceAwsEc2SpotPrice() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsEc2SpotPriceRead, + + Schema: map[string]*schema.Schema{ + "filter": dataSourceFiltersSchema(), + "instance_type": { + Type: schema.TypeString, + Optional: true, + }, + "availability_zone": { + Type: schema.TypeString, + Optional: true, + }, + "spot_price": { + Type: schema.TypeString, + Computed: true, + }, + "spot_price_timestamp": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceAwsEc2SpotPriceRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + now := time.Now() + input := &ec2.DescribeSpotPriceHistoryInput{ + StartTime: &now, + } + + if v, ok := d.GetOk("instance_type"); ok { + instanceType := v.(string) + input.InstanceTypes = []*string{ + aws.String(instanceType), + } + } + + if v, ok := d.GetOk("availability_zone"); ok { + availabilityZone := v.(string) + input.AvailabilityZone = aws.String(availabilityZone) + } + + if v, ok := d.GetOk("filter"); ok { + input.Filters = buildAwsDataSourceFilters(v.(*schema.Set)) + } + + var foundSpotPrice []*ec2.SpotPrice + + err := conn.DescribeSpotPriceHistoryPages(input, func(output *ec2.DescribeSpotPriceHistoryOutput, lastPage bool) bool { + foundSpotPrice = append(foundSpotPrice, output.SpotPriceHistory...) + return true + }) + if err != nil { + return fmt.Errorf("error reading EC2 Spot Price History: %w", err) + } + + if len(foundSpotPrice) == 0 { + return fmt.Errorf("no EC2 Spot Price History found matching criteria; try different search") + } + + if len(foundSpotPrice) > 1 { + return fmt.Errorf("multiple EC2 Spot Price History results found matching criteria; try different search") + } + + resultSpotPrice := foundSpotPrice[0] + + d.Set("spot_price", resultSpotPrice.SpotPrice) + d.Set("spot_price_timestamp", (*resultSpotPrice.Timestamp).Format(time.RFC3339)) + d.SetId(resource.UniqueId()) + + return nil +} diff --git a/aws/data_source_aws_ec2_spot_price_test.go b/aws/data_source_aws_ec2_spot_price_test.go new file mode 100644 index 00000000000..f38974d0c23 --- /dev/null +++ b/aws/data_source_aws_ec2_spot_price_test.go @@ -0,0 +1,139 @@ +package aws + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccAwsEc2SpotPriceDataSource_basic(t *testing.T) { + dataSourceName := "data.aws_ec2_spot_price.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAwsEc2SpotPrice(t) }, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccAwsEc2SpotPriceDataSourceConfig(), + Check: resource.ComposeTestCheckFunc( + resource.TestMatchResourceAttr(dataSourceName, "spot_price", regexp.MustCompile(`^\d+\.\d+$`)), + resource.TestMatchResourceAttr(dataSourceName, "spot_price_timestamp", regexp.MustCompile(rfc3339RegexPattern)), + ), + }, + }, + }) +} + +func TestAccAwsEc2SpotPriceDataSource_Filter(t *testing.T) { + dataSourceName := "data.aws_ec2_spot_price.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAwsEc2SpotPrice(t) }, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccAwsEc2SpotPriceDataSourceFilterConfig(), + Check: resource.ComposeTestCheckFunc( + resource.TestMatchResourceAttr(dataSourceName, "spot_price", regexp.MustCompile(`^\d+\.\d+$`)), + resource.TestMatchResourceAttr(dataSourceName, "spot_price_timestamp", regexp.MustCompile(rfc3339RegexPattern)), + ), + }, + }, + }) +} + +func testAccPreCheckAwsEc2SpotPrice(t *testing.T) { + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + input := &ec2.DescribeSpotPriceHistoryInput{ + MaxResults: aws.Int64(5), + } + + _, err := conn.DescribeSpotPriceHistory(input) + + if testAccPreCheckSkipError(err) { + t.Skipf("skipping acceptance testing: %s", err) + } + + if err != nil { + t.Fatalf("unexpected PreCheck error: %s", err) + } +} + +func testAccAwsEc2SpotPriceDataSourceConfig() string { + return fmt.Sprintf(` +data "aws_region" "current" {} + +data "aws_ec2_instance_type_offering" "test" { + filter { + name = "instance-type" + values = ["m5.xlarge"] + } +} + +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "region-name" + values = [data.aws_region.current.name] + } +} + +data "aws_ec2_spot_price" "test" { + instance_type = data.aws_ec2_instance_type_offering.test.instance_type + + availability_zone = data.aws_availability_zones.available.names[0] + + filter { + name = "product-description" + values = ["Linux/UNIX"] + } +} +`) +} + +func testAccAwsEc2SpotPriceDataSourceFilterConfig() string { + return fmt.Sprintf(` +data "aws_region" "current" {} + +data "aws_ec2_instance_type_offering" "test" { + filter { + name = "instance-type" + values = ["m5.xlarge"] + } +} + +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "region-name" + values = [data.aws_region.current.name] + } +} + +data "aws_ec2_spot_price" "test" { + filter { + name = "product-description" + values = ["Linux/UNIX"] + } + + filter { + name = "instance-type" + values = [data.aws_ec2_instance_type_offering.test.instance_type] + } + + filter { + name = "availability-zone" + values = [data.aws_availability_zones.available.names[0]] + } +} +`) +} diff --git a/aws/data_source_aws_ec2_transit_gateway.go b/aws/data_source_aws_ec2_transit_gateway.go index 4c092513bad..3812c20e565 100644 --- a/aws/data_source_aws_ec2_transit_gateway.go +++ b/aws/data_source_aws_ec2_transit_gateway.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_ec2_transit_gateway_dx_gateway_attachment.go b/aws/data_source_aws_ec2_transit_gateway_dx_gateway_attachment.go index 0c6dac6f884..2df51a7cf66 100644 --- a/aws/data_source_aws_ec2_transit_gateway_dx_gateway_attachment.go +++ b/aws/data_source_aws_ec2_transit_gateway_dx_gateway_attachment.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_ec2_transit_gateway_dx_gateway_attachment_test.go b/aws/data_source_aws_ec2_transit_gateway_dx_gateway_attachment_test.go index adf5af3a8eb..bf0191e562d 100644 --- a/aws/data_source_aws_ec2_transit_gateway_dx_gateway_attachment_test.go +++ b/aws/data_source_aws_ec2_transit_gateway_dx_gateway_attachment_test.go @@ -4,13 +4,13 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSEc2TransitGatewayDxGatewayAttachmentDataSource_TransitGatewayIdAndDxGatewayId(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") - rBgpAsn := randIntRange(64512, 65534) + rBgpAsn := acctest.RandIntRange(64512, 65534) dataSourceName := "data.aws_ec2_transit_gateway_dx_gateway_attachment.test" transitGatewayResourceName := "aws_ec2_transit_gateway.test" dxGatewayResourceName := "aws_dx_gateway.test" @@ -37,7 +37,7 @@ func TestAccAWSEc2TransitGatewayDxGatewayAttachmentDataSource_TransitGatewayIdAn func TestAccAWSEc2TransitGatewayDxGatewayAttachmentDataSource_filter(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") - rBgpAsn := randIntRange(64512, 65534) + rBgpAsn := acctest.RandIntRange(64512, 65534) dataSourceName := "data.aws_ec2_transit_gateway_dx_gateway_attachment.test" transitGatewayResourceName := "aws_ec2_transit_gateway.test" dxGatewayResourceName := "aws_dx_gateway.test" @@ -76,8 +76,8 @@ resource "aws_ec2_transit_gateway" "test" { } resource "aws_dx_gateway_association" "test" { - dx_gateway_id = "${aws_dx_gateway.test.id}" - associated_gateway_id = "${aws_ec2_transit_gateway.test.id}" + dx_gateway_id = aws_dx_gateway.test.id + associated_gateway_id = aws_ec2_transit_gateway.test.id allowed_prefixes = [ "10.255.255.0/30", @@ -86,8 +86,8 @@ resource "aws_dx_gateway_association" "test" { } data "aws_ec2_transit_gateway_dx_gateway_attachment" "test" { - transit_gateway_id = "${aws_dx_gateway_association.test.associated_gateway_id}" - dx_gateway_id = "${aws_dx_gateway_association.test.dx_gateway_id}" + transit_gateway_id = aws_dx_gateway_association.test.associated_gateway_id + dx_gateway_id = aws_dx_gateway_association.test.dx_gateway_id } `, rName, rBgpAsn) } @@ -106,8 +106,8 @@ resource "aws_ec2_transit_gateway" "test" { } resource "aws_dx_gateway_association" "test" { - dx_gateway_id = "${aws_dx_gateway.test.id}" - associated_gateway_id = "${aws_ec2_transit_gateway.test.id}" + dx_gateway_id = aws_dx_gateway.test.id + associated_gateway_id = aws_ec2_transit_gateway.test.id allowed_prefixes = [ "10.255.255.0/30", @@ -118,7 +118,7 @@ resource "aws_dx_gateway_association" "test" { data "aws_ec2_transit_gateway_dx_gateway_attachment" "test" { filter { name = "resource-id" - values = ["${aws_dx_gateway_association.test.dx_gateway_id}"] + values = [aws_dx_gateway_association.test.dx_gateway_id] } } `, rName, rBgpAsn) diff --git a/aws/data_source_aws_ec2_transit_gateway_peering_attachment.go b/aws/data_source_aws_ec2_transit_gateway_peering_attachment.go index 2b00ec2b48b..d2868d512de 100644 --- a/aws/data_source_aws_ec2_transit_gateway_peering_attachment.go +++ b/aws/data_source_aws_ec2_transit_gateway_peering_attachment.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_ec2_transit_gateway_peering_attachment_test.go b/aws/data_source_aws_ec2_transit_gateway_peering_attachment_test.go index a35c66474e7..4f3cb0e1dda 100644 --- a/aws/data_source_aws_ec2_transit_gateway_peering_attachment_test.go +++ b/aws/data_source_aws_ec2_transit_gateway_peering_attachment_test.go @@ -1,12 +1,11 @@ package aws import ( - "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func TestAccAWSEc2TransitGatewayPeeringAttachmentDataSource_Filter_sameAccount(t *testing.T) { @@ -153,59 +152,60 @@ func TestAccAWSEc2TransitGatewayPeeringAttachmentDataSource_Tags(t *testing.T) { func testAccAWSEc2TransitGatewayPeeringAttachmentDataSourceConfigFilter_sameAccount(rName string) string { return composeConfig( testAccAWSEc2TransitGatewayPeeringAttachmentConfigBasic_sameAccount(rName), - fmt.Sprintf(` + ` data "aws_ec2_transit_gateway_peering_attachment" "test" { filter { name = "transit-gateway-attachment-id" - values = ["${aws_ec2_transit_gateway_peering_attachment.test.id}"] + values = [aws_ec2_transit_gateway_peering_attachment.test.id] } } -`)) +`) } func testAccAWSEc2TransitGatewayPeeringAttachmentDataSourceConfigID_sameAccount(rName string) string { return composeConfig( testAccAWSEc2TransitGatewayPeeringAttachmentConfigBasic_sameAccount(rName), - fmt.Sprintf(` + ` data "aws_ec2_transit_gateway_peering_attachment" "test" { - id = "${aws_ec2_transit_gateway_peering_attachment.test.id}" + id = aws_ec2_transit_gateway_peering_attachment.test.id } -`)) +`) } func testAccAWSEc2TransitGatewayPeeringAttachmentDataSourceConfigTags_sameAccount(rName string) string { return composeConfig( testAccAWSEc2TransitGatewayPeeringAttachmentConfigTags1_sameAccount(rName, "Name", rName), - fmt.Sprintf(` + ` data "aws_ec2_transit_gateway_peering_attachment" "test" { tags = { - Name = "${aws_ec2_transit_gateway_peering_attachment.test.tags["Name"]}" + Name = aws_ec2_transit_gateway_peering_attachment.test.tags["Name"] } } -`)) +`) } func testAccAWSEc2TransitGatewayPeeringAttachmentDataSourceConfigFilter_differentAccount(rName string) string { return composeConfig( testAccAWSEc2TransitGatewayPeeringAttachmentConfigBasic_differentAccount(rName), - fmt.Sprintf(` + ` data "aws_ec2_transit_gateway_peering_attachment" "test" { - provider = "aws.alternate" + provider = "awsalternate" + filter { name = "transit-gateway-attachment-id" - values = ["${aws_ec2_transit_gateway_peering_attachment.test.id}"] + values = [aws_ec2_transit_gateway_peering_attachment.test.id] } } -`)) +`) } func testAccAWSEc2TransitGatewayPeeringAttachmentDataSourceConfigID_differentAccount(rName string) string { return composeConfig( testAccAWSEc2TransitGatewayPeeringAttachmentConfigBasic_differentAccount(rName), - fmt.Sprintf(` + ` data "aws_ec2_transit_gateway_peering_attachment" "test" { - provider = "aws.alternate" - id = "${aws_ec2_transit_gateway_peering_attachment.test.id}" + provider = "awsalternate" + id = aws_ec2_transit_gateway_peering_attachment.test.id } -`)) +`) } diff --git a/aws/data_source_aws_ec2_transit_gateway_route_table.go b/aws/data_source_aws_ec2_transit_gateway_route_table.go index 98082192fa2..ded20ddaa41 100644 --- a/aws/data_source_aws_ec2_transit_gateway_route_table.go +++ b/aws/data_source_aws_ec2_transit_gateway_route_table.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_ec2_transit_gateway_route_table_test.go b/aws/data_source_aws_ec2_transit_gateway_route_table_test.go index 331de84e37a..f127fd83416 100644 --- a/aws/data_source_aws_ec2_transit_gateway_route_table_test.go +++ b/aws/data_source_aws_ec2_transit_gateway_route_table_test.go @@ -1,10 +1,9 @@ package aws import ( - "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSEc2TransitGatewayRouteTableDataSource_Filter(t *testing.T) { @@ -52,32 +51,32 @@ func TestAccAWSEc2TransitGatewayRouteTableDataSource_ID(t *testing.T) { } func testAccAWSEc2TransitGatewayRouteTableDataSourceConfigFilter() string { - return fmt.Sprintf(` + return ` resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_route_table" "test" { - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id } data "aws_ec2_transit_gateway_route_table" "test" { filter { name = "transit-gateway-route-table-id" - values = ["${aws_ec2_transit_gateway_route_table.test.id}"] + values = [aws_ec2_transit_gateway_route_table.test.id] } } -`) +` } func testAccAWSEc2TransitGatewayRouteTableDataSourceConfigID() string { - return fmt.Sprintf(` + return ` resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_route_table" "test" { - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id } data "aws_ec2_transit_gateway_route_table" "test" { - id = "${aws_ec2_transit_gateway_route_table.test.id}" + id = aws_ec2_transit_gateway_route_table.test.id } -`) +` } diff --git a/aws/data_source_aws_ec2_transit_gateway_test.go b/aws/data_source_aws_ec2_transit_gateway_test.go index ad018387d85..f681df83cf6 100644 --- a/aws/data_source_aws_ec2_transit_gateway_test.go +++ b/aws/data_source_aws_ec2_transit_gateway_test.go @@ -1,10 +1,9 @@ package aws import ( - "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSEc2TransitGatewayDataSource_Filter(t *testing.T) { @@ -68,24 +67,24 @@ func TestAccAWSEc2TransitGatewayDataSource_ID(t *testing.T) { } func testAccAWSEc2TransitGatewayDataSourceConfigFilter() string { - return fmt.Sprintf(` + return ` resource "aws_ec2_transit_gateway" "test" {} data "aws_ec2_transit_gateway" "test" { filter { name = "transit-gateway-id" - values = ["${aws_ec2_transit_gateway.test.id}"] + values = [aws_ec2_transit_gateway.test.id] } } -`) +` } func testAccAWSEc2TransitGatewayDataSourceConfigID() string { - return fmt.Sprintf(` + return ` resource "aws_ec2_transit_gateway" "test" {} data "aws_ec2_transit_gateway" "test" { - id = "${aws_ec2_transit_gateway.test.id}" + id = aws_ec2_transit_gateway.test.id } -`) +` } diff --git a/aws/data_source_aws_ec2_transit_gateway_vpc_attachment.go b/aws/data_source_aws_ec2_transit_gateway_vpc_attachment.go index 155c188deef..76872b6dd46 100644 --- a/aws/data_source_aws_ec2_transit_gateway_vpc_attachment.go +++ b/aws/data_source_aws_ec2_transit_gateway_vpc_attachment.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_ec2_transit_gateway_vpc_attachment_test.go b/aws/data_source_aws_ec2_transit_gateway_vpc_attachment_test.go index 1acb93589bb..1976549495d 100644 --- a/aws/data_source_aws_ec2_transit_gateway_vpc_attachment_test.go +++ b/aws/data_source_aws_ec2_transit_gateway_vpc_attachment_test.go @@ -1,10 +1,9 @@ package aws import ( - "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSEc2TransitGatewayVpcAttachmentDataSource_Filter(t *testing.T) { @@ -58,11 +57,11 @@ func TestAccAWSEc2TransitGatewayVpcAttachmentDataSource_ID(t *testing.T) { } func testAccAWSEc2TransitGatewayVpcAttachmentDataSourceConfigFilter() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -79,9 +78,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" @@ -91,26 +90,26 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } data "aws_ec2_transit_gateway_vpc_attachment" "test" { filter { name = "transit-gateway-attachment-id" - values = ["${aws_ec2_transit_gateway_vpc_attachment.test.id}"] + values = [aws_ec2_transit_gateway_vpc_attachment.test.id] } } -`) +` } func testAccAWSEc2TransitGatewayVpcAttachmentDataSourceConfigID() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -127,9 +126,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" @@ -139,13 +138,13 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } data "aws_ec2_transit_gateway_vpc_attachment" "test" { - id = "${aws_ec2_transit_gateway_vpc_attachment.test.id}" + id = aws_ec2_transit_gateway_vpc_attachment.test.id } -`) +` } diff --git a/aws/data_source_aws_ec2_transit_gateway_vpn_attachment.go b/aws/data_source_aws_ec2_transit_gateway_vpn_attachment.go index 4a3ed475452..8705566877a 100644 --- a/aws/data_source_aws_ec2_transit_gateway_vpn_attachment.go +++ b/aws/data_source_aws_ec2_transit_gateway_vpn_attachment.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_ec2_transit_gateway_vpn_attachment_test.go b/aws/data_source_aws_ec2_transit_gateway_vpn_attachment_test.go index 95bbfe600cb..c8d7a5f92a3 100644 --- a/aws/data_source_aws_ec2_transit_gateway_vpn_attachment_test.go +++ b/aws/data_source_aws_ec2_transit_gateway_vpn_attachment_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSEc2TransitGatewayVpnAttachmentDataSource_TransitGatewayIdAndVpnConnectionId(t *testing.T) { @@ -79,9 +79,9 @@ resource "aws_customer_gateway" "test" { } resource "aws_vpn_connection" "test" { - customer_gateway_id = "${aws_customer_gateway.test.id}" - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - type = "${aws_customer_gateway.test.type}" + customer_gateway_id = aws_customer_gateway.test.id + transit_gateway_id = aws_ec2_transit_gateway.test.id + type = aws_customer_gateway.test.type tags = { Name = "tf-acc-test-ec2-vpn-connection-transit-gateway-id" @@ -91,21 +91,21 @@ resource "aws_vpn_connection" "test" { } func testAccAWSEc2TransitGatewayVpnAttachmentDataSourceConfigTransitGatewayIdAndVpnConnectionId(rBgpAsn int) string { - return testAccAWSEc2TransitGatewayVpnAttachmentDataSourceConfigBase(rBgpAsn) + fmt.Sprintf(` + return testAccAWSEc2TransitGatewayVpnAttachmentDataSourceConfigBase(rBgpAsn) + ` data "aws_ec2_transit_gateway_vpn_attachment" "test" { - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpn_connection_id = "${aws_vpn_connection.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpn_connection_id = aws_vpn_connection.test.id } -`) +` } func testAccAWSEc2TransitGatewayVpnAttachmentDataSourceConfigFilter(rBgpAsn int) string { - return testAccAWSEc2TransitGatewayVpnAttachmentDataSourceConfigBase(rBgpAsn) + fmt.Sprintf(` + return testAccAWSEc2TransitGatewayVpnAttachmentDataSourceConfigBase(rBgpAsn) + ` data "aws_ec2_transit_gateway_vpn_attachment" "test" { filter { name = "resource-id" - values = ["${aws_vpn_connection.test.id}"] + values = [aws_vpn_connection.test.id] } } -`) +` } diff --git a/aws/data_source_aws_ecr_authorization_token.go b/aws/data_source_aws_ecr_authorization_token.go new file mode 100644 index 00000000000..e77d35ee8ad --- /dev/null +++ b/aws/data_source_aws_ecr_authorization_token.go @@ -0,0 +1,84 @@ +package aws + +import ( + "encoding/base64" + "fmt" + "log" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ecr" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceAwsEcrAuthorizationToken() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsEcrAuthorizationTokenRead, + + Schema: map[string]*schema.Schema{ + "registry_id": { + Type: schema.TypeString, + Optional: true, + }, + "authorization_token": { + Type: schema.TypeString, + Computed: true, + Sensitive: true, + }, + "proxy_endpoint": { + Type: schema.TypeString, + Computed: true, + }, + "expires_at": { + Type: schema.TypeString, + Computed: true, + }, + "user_name": { + Type: schema.TypeString, + Computed: true, + }, + "password": { + Type: schema.TypeString, + Computed: true, + Sensitive: true, + }, + }, + } +} + +func dataSourceAwsEcrAuthorizationTokenRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ecrconn + params := &ecr.GetAuthorizationTokenInput{} + if v, ok := d.GetOk("registry_id"); ok && len(v.(string)) > 0 { + params.RegistryIds = []*string{aws.String(v.(string))} + } + log.Printf("[DEBUG] Getting ECR authorization token") + out, err := conn.GetAuthorizationToken(params) + if err != nil { + return fmt.Errorf("error getting ECR authorization token: %s", err) + } + log.Printf("[DEBUG] Received ECR AuthorizationData %v", out.AuthorizationData) + authorizationData := out.AuthorizationData[0] + authorizationToken := aws.StringValue(authorizationData.AuthorizationToken) + expiresAt := aws.TimeValue(authorizationData.ExpiresAt).Format(time.RFC3339) + proxyEndpoint := aws.StringValue(authorizationData.ProxyEndpoint) + authBytes, err := base64.URLEncoding.DecodeString(authorizationToken) + if err != nil { + d.SetId("") + return fmt.Errorf("error decoding ECR authorization token: %s", err) + } + basicAuthorization := strings.Split(string(authBytes), ":") + if len(basicAuthorization) != 2 { + return fmt.Errorf("unknown ECR authorization token format") + } + userName := basicAuthorization[0] + password := basicAuthorization[1] + d.SetId(time.Now().UTC().String()) + d.Set("authorization_token", authorizationToken) + d.Set("proxy_endpoint", proxyEndpoint) + d.Set("expires_at", expiresAt) + d.Set("user_name", userName) + d.Set("password", password) + return nil +} diff --git a/aws/data_source_aws_ecr_authorization_token_test.go b/aws/data_source_aws_ecr_authorization_token_test.go new file mode 100644 index 00000000000..2994d1a6dba --- /dev/null +++ b/aws/data_source_aws_ecr_authorization_token_test.go @@ -0,0 +1,61 @@ +package aws + +import ( + "fmt" + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccAWSEcrAuthorizationTokenDataSource_basic(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + dataSourceName := "data.aws_ecr_authorization_token.repo" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckAwsEcrAuthorizationTokenDataSourceBasicConfig, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet(dataSourceName, "authorization_token"), + resource.TestCheckResourceAttrSet(dataSourceName, "proxy_endpoint"), + resource.TestCheckResourceAttrSet(dataSourceName, "expires_at"), + resource.TestCheckResourceAttrSet(dataSourceName, "user_name"), + resource.TestMatchResourceAttr(dataSourceName, "user_name", regexp.MustCompile(`AWS`)), + resource.TestCheckResourceAttrSet(dataSourceName, "password"), + ), + }, + { + Config: testAccCheckAwsEcrAuthorizationTokenDataSourceRepositoryConfig(rName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "registry_id", "aws_ecr_repository.repo", "registry_id"), + resource.TestCheckResourceAttrSet(dataSourceName, "authorization_token"), + resource.TestCheckResourceAttrSet(dataSourceName, "proxy_endpoint"), + resource.TestCheckResourceAttrSet(dataSourceName, "expires_at"), + resource.TestCheckResourceAttrSet(dataSourceName, "user_name"), + resource.TestMatchResourceAttr(dataSourceName, "user_name", regexp.MustCompile(`AWS`)), + resource.TestCheckResourceAttrSet(dataSourceName, "password"), + ), + }, + }, + }) +} + +var testAccCheckAwsEcrAuthorizationTokenDataSourceBasicConfig = ` +data "aws_ecr_authorization_token" "repo" {} +` + +func testAccCheckAwsEcrAuthorizationTokenDataSourceRepositoryConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_ecr_repository" "repo" { + name = %q +} + +data "aws_ecr_authorization_token" "repo" { + registry_id = aws_ecr_repository.repo.registry_id +} +`, rName) +} diff --git a/aws/data_source_aws_ecr_image.go b/aws/data_source_aws_ecr_image.go index 28a6dac8f0f..64678285b38 100755 --- a/aws/data_source_aws_ecr_image.go +++ b/aws/data_source_aws_ecr_image.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecr" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func dataSourceAwsEcrImage() *schema.Resource { diff --git a/aws/data_source_aws_ecr_image_test.go b/aws/data_source_aws_ecr_image_test.go index 1ab321c38ba..1d9c1712eb7 100644 --- a/aws/data_source_aws_ecr_image_test.go +++ b/aws/data_source_aws_ecr_image_test.go @@ -5,8 +5,8 @@ import ( "strconv" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSEcrDataSource_ecrImage(t *testing.T) { @@ -43,9 +43,9 @@ data "aws_ecr_image" "by_tag" { } data "aws_ecr_image" "by_digest" { - registry_id = "${data.aws_ecr_image.by_tag.registry_id}" - repository_name = "${data.aws_ecr_image.by_tag.repository_name}" - image_digest = "${data.aws_ecr_image.by_tag.image_digest}" + registry_id = data.aws_ecr_image.by_tag.registry_id + repository_name = data.aws_ecr_image.by_tag.repository_name + image_digest = data.aws_ecr_image.by_tag.image_digest } `, reg, repo, tag) } diff --git a/aws/data_source_aws_ecr_repository.go b/aws/data_source_aws_ecr_repository.go index 6f3b8a95d43..3d551c6606f 100644 --- a/aws/data_source_aws_ecr_repository.go +++ b/aws/data_source_aws_ecr_repository.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecr" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -15,16 +15,49 @@ func dataSourceAwsEcrRepository() *schema.Resource { Read: dataSourceAwsEcrRepositoryRead, Schema: map[string]*schema.Schema{ - "name": { + "arn": { Type: schema.TypeString, - Required: true, + Computed: true, }, - "arn": { + "encryption_configuration": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "encryption_type": { + Type: schema.TypeString, + Computed: true, + }, + "kms_key": { + Type: schema.TypeString, + Computed: true, + }, + }, + }, + }, + "image_scanning_configuration": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "scan_on_push": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, + }, + "image_tag_mutability": { Type: schema.TypeString, Computed: true, }, + "name": { + Type: schema.TypeString, + Required: true, + }, "registry_id": { Type: schema.TypeString, + Optional: true, Computed: true, }, "repository_url": { @@ -40,18 +73,22 @@ func dataSourceAwsEcrRepositoryRead(d *schema.ResourceData, meta interface{}) er conn := meta.(*AWSClient).ecrconn ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + name := d.Get("name").(string) params := &ecr.DescribeRepositoriesInput{ - RepositoryNames: aws.StringSlice([]string{d.Get("name").(string)}), + RepositoryNames: aws.StringSlice([]string{name}), + } + + if v, ok := d.GetOk("registry_id"); ok { + params.RegistryId = aws.String(v.(string)) } - log.Printf("[DEBUG] Reading ECR repository: %s", params) + + log.Printf("[DEBUG] Reading ECR repository: %#v", params) out, err := conn.DescribeRepositories(params) if err != nil { if isAWSErr(err, ecr.ErrCodeRepositoryNotFoundException, "") { - log.Printf("[WARN] ECR Repository %s not found, removing from state", d.Id()) - d.SetId("") - return nil + return fmt.Errorf("ECR Repository (%s) not found", name) } - return fmt.Errorf("error reading ECR repository: %s", err) + return fmt.Errorf("error reading ECR repository: %w", err) } repository := out.Repositories[0] @@ -59,18 +96,25 @@ func dataSourceAwsEcrRepositoryRead(d *schema.ResourceData, meta interface{}) er d.SetId(aws.StringValue(repository.RepositoryName)) d.Set("arn", arn) - d.Set("registry_id", repository.RegistryId) d.Set("name", repository.RepositoryName) + d.Set("registry_id", repository.RegistryId) d.Set("repository_url", repository.RepositoryUri) + d.Set("image_tag_mutability", repository.ImageTagMutability) tags, err := keyvaluetags.EcrListTags(conn, arn) - if err != nil { - return fmt.Errorf("error listing tags for ECR Repository (%s): %s", arn, err) + return fmt.Errorf("error listing tags for ECR Repository (%s): %w", arn, err) } - if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %s", err) + return fmt.Errorf("error setting tags for ECR Repository (%s): %w", arn, err) + } + + if err := d.Set("image_scanning_configuration", flattenImageScanningConfiguration(repository.ImageScanningConfiguration)); err != nil { + return fmt.Errorf("error setting image_scanning_configuration for ECR Repository (%s): %w", arn, err) + } + + if err := d.Set("encryption_configuration", flattenEcrRepositoryEncryptionConfiguration(repository.EncryptionConfiguration)); err != nil { + return fmt.Errorf("error setting encryption_configuration for ECR Repository (%s): %w", arn, err) } return nil diff --git a/aws/data_source_aws_ecr_repository_test.go b/aws/data_source_aws_ecr_repository_test.go index 2458f5c1098..34114e7f2ad 100644 --- a/aws/data_source_aws_ecr_repository_test.go +++ b/aws/data_source_aws_ecr_repository_test.go @@ -5,13 +5,14 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccAWSEcrDataSource_ecrRepository(t *testing.T) { +func TestAccAWSEcrRepositoryDataSource_basic(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") - resourceName := "data.aws_ecr_repository.default" + resourceName := "aws_ecr_repository.test" + dataSourceName := "data.aws_ecr_repository.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -20,20 +21,69 @@ func TestAccAWSEcrDataSource_ecrRepository(t *testing.T) { { Config: testAccCheckAwsEcrRepositoryDataSourceConfig(rName), Check: resource.ComposeTestCheckFunc( - testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ecr", regexp.MustCompile(fmt.Sprintf("repository/%s$", rName))), - resource.TestCheckResourceAttrSet(resourceName, "registry_id"), - resource.TestMatchResourceAttr(resourceName, "repository_url", regexp.MustCompile(fmt.Sprintf(`^\d+\.dkr\.ecr\.%s\.amazonaws\.com/%s$`, testAccGetRegion(), rName))), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.Usage", "original"), + resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "registry_id", dataSourceName, "registry_id"), + resource.TestCheckResourceAttrPair(resourceName, "repository_url", dataSourceName, "repository_url"), + resource.TestCheckResourceAttrPair(resourceName, "tags", dataSourceName, "tags"), + resource.TestCheckResourceAttrPair(resourceName, "image_scanning_configuration.#", dataSourceName, "image_scanning_configuration.#"), + resource.TestCheckResourceAttrPair(resourceName, "image_tag_mutability", dataSourceName, "image_tag_mutability"), + resource.TestCheckResourceAttrPair(resourceName, "encryption_configuration.#", dataSourceName, "encryption_configuration.#"), ), }, }, }) } +func TestAccAWSEcrRepositoryDataSource_encryption(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_ecr_repository.test" + dataSourceName := "data.aws_ecr_repository.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckAwsEcrRepositoryDataSourceConfig_encryption(rName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "registry_id", dataSourceName, "registry_id"), + resource.TestCheckResourceAttrPair(resourceName, "repository_url", dataSourceName, "repository_url"), + resource.TestCheckResourceAttrPair(resourceName, "tags", dataSourceName, "tags"), + resource.TestCheckResourceAttrPair(resourceName, "image_scanning_configuration.#", dataSourceName, "image_scanning_configuration.#"), + resource.TestCheckResourceAttrPair(resourceName, "image_tag_mutability", dataSourceName, "image_tag_mutability"), + resource.TestCheckResourceAttrPair(resourceName, "encryption_configuration.#", dataSourceName, "encryption_configuration.#"), + resource.TestCheckResourceAttrPair(resourceName, "encryption_configuration.0.encryption_type", dataSourceName, "encryption_configuration.0.encryption_type"), + resource.TestCheckResourceAttrPair(resourceName, "encryption_configuration.0.kms_key", dataSourceName, "encryption_configuration.0.kms_key"), + ), + }, + }, + }) +} + +func TestAccAWSEcrRepositoryDataSource_nonExistent(t *testing.T) { + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccCheckAwsEcrRepositoryDataSourceConfig_NonExistent, + ExpectError: regexp.MustCompile(`not found`), + }, + }, + }) +} + +const testAccCheckAwsEcrRepositoryDataSourceConfig_NonExistent = ` +data "aws_ecr_repository" "test" { + name = "tf-acc-test-non-existent" +} +` + func testAccCheckAwsEcrRepositoryDataSourceConfig(rName string) string { return fmt.Sprintf(` -resource "aws_ecr_repository" "default" { +resource "aws_ecr_repository" "test" { name = %q tags = { @@ -42,8 +92,27 @@ resource "aws_ecr_repository" "default" { } } -data "aws_ecr_repository" "default" { - name = "${aws_ecr_repository.default.name}" +data "aws_ecr_repository" "test" { + name = aws_ecr_repository.test.name +} +`, rName) +} + +func testAccCheckAwsEcrRepositoryDataSourceConfig_encryption(rName string) string { + return fmt.Sprintf(` +resource "aws_kms_key" "test" {} + +resource "aws_ecr_repository" "test" { + name = %q + + encryption_configuration { + encryption_type = "KMS" + kms_key = aws_kms_key.test.arn + } +} + +data "aws_ecr_repository" "test" { + name = aws_ecr_repository.test.name } `, rName) } diff --git a/aws/data_source_aws_ecs_cluster.go b/aws/data_source_aws_ecs_cluster.go index bbeab1dff1c..b4efe05a179 100644 --- a/aws/data_source_aws_ecs_cluster.go +++ b/aws/data_source_aws_ecs_cluster.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecs" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsEcsCluster() *schema.Resource { diff --git a/aws/data_source_aws_ecs_cluster_test.go b/aws/data_source_aws_ecs_cluster_test.go index 2c6c1651b2c..e65ddd4aab0 100644 --- a/aws/data_source_aws_ecs_cluster_test.go +++ b/aws/data_source_aws_ecs_cluster_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSEcsDataSource_ecsCluster(t *testing.T) { @@ -53,20 +53,21 @@ resource "aws_ecs_cluster" "default" { } data "aws_ecs_cluster" "default" { - cluster_name = "${aws_ecs_cluster.default.name}" + cluster_name = aws_ecs_cluster.default.name } `, acctest.RandInt()) var testAccCheckAwsEcsClusterDataSourceConfigContainerInsights = fmt.Sprintf(` resource "aws_ecs_cluster" "default" { name = "default-%d" + setting { - name = "containerInsights" + name = "containerInsights" value = "enabled" } } data "aws_ecs_cluster" "default" { - cluster_name = "${aws_ecs_cluster.default.name}" + cluster_name = aws_ecs_cluster.default.name } `, acctest.RandInt()) diff --git a/aws/data_source_aws_ecs_container_definition.go b/aws/data_source_aws_ecs_container_definition.go index eb769f395ef..7c3b71048b6 100644 --- a/aws/data_source_aws_ecs_container_definition.go +++ b/aws/data_source_aws_ecs_container_definition.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecs" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsEcsContainerDefinition() *schema.Resource { diff --git a/aws/data_source_aws_ecs_container_definition_test.go b/aws/data_source_aws_ecs_container_definition_test.go index 04905dab78c..d26183b14f6 100644 --- a/aws/data_source_aws_ecs_container_definition_test.go +++ b/aws/data_source_aws_ecs_container_definition_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSEcsDataSource_ecsContainerDefinition(t *testing.T) { @@ -46,10 +46,12 @@ resource "aws_ecs_task_definition" "mongo" { [ { "cpu": 128, - "environment": [{ - "name": "SECRET", - "value": "KEY" - }], + "environment": [ + { + "name": "SECRET", + "value": "KEY" + } + ], "essential": true, "image": "mongo:latest", "memory": 128, @@ -62,13 +64,13 @@ DEFINITION resource "aws_ecs_service" "mongo" { name = "%s" - cluster = "${aws_ecs_cluster.default.id}" - task_definition = "${aws_ecs_task_definition.mongo.arn}" + cluster = aws_ecs_cluster.default.id + task_definition = aws_ecs_task_definition.mongo.arn desired_count = 1 } data "aws_ecs_container_definition" "mongo" { - task_definition = "${aws_ecs_task_definition.mongo.id}" + task_definition = aws_ecs_task_definition.mongo.id container_name = "mongodb" } `, clusterName, tdName, svcName) diff --git a/aws/data_source_aws_ecs_service.go b/aws/data_source_aws_ecs_service.go index 422018e2ec6..a6449b21251 100644 --- a/aws/data_source_aws_ecs_service.go +++ b/aws/data_source_aws_ecs_service.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecs" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsEcsService() *schema.Resource { diff --git a/aws/data_source_aws_ecs_service_test.go b/aws/data_source_aws_ecs_service_test.go index c6e7d9a29c7..a7516974ad3 100644 --- a/aws/data_source_aws_ecs_service_test.go +++ b/aws/data_source_aws_ecs_service_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSEcsServiceDataSource_basic(t *testing.T) { @@ -38,6 +38,7 @@ resource "aws_ecs_cluster" "test" { resource "aws_ecs_task_definition" "test" { family = "mongodb" + container_definitions = < 1 { + return fmt.Errorf("Search returned %d results, please revise so only one is returned", len(describeResp.FileSystems)) } + fs := describeResp.FileSystems[0] + + d.SetId(aws.StringValue(fs.FileSystemId)) d.Set("creation_token", fs.CreationToken) d.Set("performance_mode", fs.PerformanceMode) @@ -144,12 +138,12 @@ func dataSourceAwsEfsFileSystemRead(d *schema.ResourceData, meta interface{}) er FileSystemId: fs.FileSystemId, }) if err != nil { - return fmt.Errorf("Error describing lifecycle configuration for EFS file system (%s): %s", + return fmt.Errorf("Error describing lifecycle configuration for EFS file system (%s): %w", aws.StringValue(fs.FileSystemId), err) } if err := d.Set("lifecycle_policy", flattenEfsFileSystemLifecyclePolicies(res.LifecyclePolicies)); err != nil { - return fmt.Errorf("error setting lifecycle_policy: %s", err) + return fmt.Errorf("error setting lifecycle_policy: %w", err) } d.Set("dns_name", meta.(*AWSClient).RegionalHostname(fmt.Sprintf("%s.efs", aws.StringValue(fs.FileSystemId)))) diff --git a/aws/data_source_aws_efs_file_system_test.go b/aws/data_source_aws_efs_file_system_test.go index f0dd41d7c47..767bc310495 100644 --- a/aws/data_source_aws_efs_file_system_test.go +++ b/aws/data_source_aws_efs_file_system_test.go @@ -5,8 +5,8 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccDataSourceAwsEfsFileSystem_id(t *testing.T) { @@ -67,6 +67,20 @@ func TestAccDataSourceAwsEfsFileSystem_name(t *testing.T) { }) } +func TestAccDataSourceAwsEfsFileSystem_NonExistent(t *testing.T) { + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsEfsFileSystemIDConfig_NonExistent, + ExpectError: regexp.MustCompile(`error reading EFS FileSystem`), + }, + }, + }) +} + func testAccDataSourceAwsEfsFileSystemCheck(dName, rName string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[dName] @@ -101,11 +115,17 @@ func testAccDataSourceAwsEfsFileSystemCheck(dName, rName string) resource.TestCh } } +const testAccDataSourceAwsEfsFileSystemIDConfig_NonExistent = ` +data "aws_efs_file_system" "test" { + file_system_id = "fs-nonexistent" +} +` + const testAccDataSourceAwsEfsFileSystemNameConfig = ` resource "aws_efs_file_system" "test" {} data "aws_efs_file_system" "test" { -creation_token = "${aws_efs_file_system.test.creation_token}" + creation_token = aws_efs_file_system.test.creation_token } ` @@ -113,6 +133,6 @@ const testAccDataSourceAwsEfsFileSystemIDConfig = ` resource "aws_efs_file_system" "test" {} data "aws_efs_file_system" "test" { - file_system_id = "${aws_efs_file_system.test.id}" + file_system_id = aws_efs_file_system.test.id } ` diff --git a/aws/data_source_aws_efs_mount_target.go b/aws/data_source_aws_efs_mount_target.go index 5d95cdc9216..d24b02474e9 100644 --- a/aws/data_source_aws_efs_mount_target.go +++ b/aws/data_source_aws_efs_mount_target.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/efs" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsEfsMountTarget() *schema.Resource { @@ -34,7 +34,6 @@ func dataSourceAwsEfsMountTarget() *schema.Resource { "security_groups": { Type: schema.TypeSet, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, Computed: true, }, "subnet_id": { @@ -49,19 +48,35 @@ func dataSourceAwsEfsMountTarget() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "mount_target_dns_name": { + Type: schema.TypeString, + Computed: true, + }, + "availability_zone_name": { + Type: schema.TypeString, + Computed: true, + }, + "availability_zone_id": { + Type: schema.TypeString, + Computed: true, + }, + "owner_id": { + Type: schema.TypeString, + Computed: true, + }, }, } } func dataSourceAwsEfsMountTargetRead(d *schema.ResourceData, meta interface{}) error { - efsconn := meta.(*AWSClient).efsconn + conn := meta.(*AWSClient).efsconn describeEfsOpts := &efs.DescribeMountTargetsInput{ MountTargetId: aws.String(d.Get("mount_target_id").(string)), } log.Printf("[DEBUG] Reading EFS Mount Target: %s", describeEfsOpts) - resp, err := efsconn.DescribeMountTargets(describeEfsOpts) + resp, err := conn.DescribeMountTargets(describeEfsOpts) if err != nil { return fmt.Errorf("Error retrieving EFS Mount Target: %s", err) } @@ -73,7 +88,7 @@ func dataSourceAwsEfsMountTargetRead(d *schema.ResourceData, meta interface{}) e log.Printf("[DEBUG] Found EFS mount target: %#v", mt) - d.SetId(*mt.MountTargetId) + d.SetId(aws.StringValue(mt.MountTargetId)) fsARN := arn.ARN{ AccountID: meta.(*AWSClient).accountid, @@ -88,19 +103,23 @@ func dataSourceAwsEfsMountTargetRead(d *schema.ResourceData, meta interface{}) e d.Set("ip_address", mt.IpAddress) d.Set("subnet_id", mt.SubnetId) d.Set("network_interface_id", mt.NetworkInterfaceId) + d.Set("availability_zone_name", mt.AvailabilityZoneName) + d.Set("availability_zone_id", mt.AvailabilityZoneId) + d.Set("owner_id", mt.OwnerId) - sgResp, err := efsconn.DescribeMountTargetSecurityGroups(&efs.DescribeMountTargetSecurityGroupsInput{ + sgResp, err := conn.DescribeMountTargetSecurityGroups(&efs.DescribeMountTargetSecurityGroupsInput{ MountTargetId: aws.String(d.Id()), }) if err != nil { return err } - err = d.Set("security_groups", schema.NewSet(schema.HashString, flattenStringList(sgResp.SecurityGroups))) + err = d.Set("security_groups", flattenStringSet(sgResp.SecurityGroups)) if err != nil { return err } d.Set("dns_name", meta.(*AWSClient).RegionalHostname(fmt.Sprintf("%s.efs", aws.StringValue(mt.FileSystemId)))) + d.Set("mount_target_dns_name", meta.(*AWSClient).RegionalHostname(fmt.Sprintf("%s.%s.efs", aws.StringValue(mt.AvailabilityZoneName), aws.StringValue(mt.FileSystemId)))) return nil } diff --git a/aws/data_source_aws_efs_mount_target_test.go b/aws/data_source_aws_efs_mount_target_test.go index 6e88d10c009..cdf0aa373a4 100644 --- a/aws/data_source_aws_efs_mount_target_test.go +++ b/aws/data_source_aws_efs_mount_target_test.go @@ -4,12 +4,14 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccDataSourceAwsEfsMountTargetByMountTargetId(t *testing.T) { +func TestAccDataSourceAwsEfsMountTarget_basic(t *testing.T) { rName := acctest.RandString(10) + dataSourceName := "data.aws_efs_mount_target.test" + resourceName := "aws_efs_mount_target.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -17,12 +19,17 @@ func TestAccDataSourceAwsEfsMountTargetByMountTargetId(t *testing.T) { { Config: testAccAwsEfsMountTargetConfigByMountTargetId(rName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair("data.aws_efs_mount_target.by_mount_target_id", "file_system_arn", "aws_efs_mount_target.alpha", "file_system_arn"), - resource.TestCheckResourceAttrSet("data.aws_efs_mount_target.by_mount_target_id", "file_system_id"), - resource.TestCheckResourceAttrSet("data.aws_efs_mount_target.by_mount_target_id", "ip_address"), - resource.TestCheckResourceAttrSet("data.aws_efs_mount_target.by_mount_target_id", "subnet_id"), - resource.TestCheckResourceAttrSet("data.aws_efs_mount_target.by_mount_target_id", "network_interface_id"), - resource.TestCheckResourceAttrSet("data.aws_efs_mount_target.by_mount_target_id", "dns_name"), + resource.TestCheckResourceAttrPair(dataSourceName, "file_system_arn", resourceName, "file_system_arn"), + resource.TestCheckResourceAttrPair(dataSourceName, "file_system_id", resourceName, "file_system_id"), + resource.TestCheckResourceAttrPair(dataSourceName, "ip_address", resourceName, "ip_address"), + resource.TestCheckResourceAttrPair(dataSourceName, "subnet_id", resourceName, "subnet_id"), + resource.TestCheckResourceAttrPair(dataSourceName, "network_interface_id", resourceName, "network_interface_id"), + resource.TestCheckResourceAttrPair(dataSourceName, "dns_name", resourceName, "dns_name"), + resource.TestCheckResourceAttrPair(dataSourceName, "mount_target_dns_name", resourceName, "mount_target_dns_name"), + resource.TestCheckResourceAttrPair(dataSourceName, "availability_zone_name", resourceName, "availability_zone_name"), + resource.TestCheckResourceAttrPair(dataSourceName, "availability_zone_id", resourceName, "availability_zone_id"), + resource.TestCheckResourceAttrPair(dataSourceName, "owner_id", resourceName, "owner_id"), + resource.TestCheckResourceAttrPair(dataSourceName, "security_groups", resourceName, "security_groups"), ), }, }, @@ -31,35 +38,48 @@ func TestAccDataSourceAwsEfsMountTargetByMountTargetId(t *testing.T) { func testAccAwsEfsMountTargetConfigByMountTargetId(ct string) string { return fmt.Sprintf(` -resource "aws_efs_file_system" "foo" { +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +resource "aws_efs_file_system" "test" { creation_token = "%s" + + tags = { + Name = "tf-acc-efs-mount-target-test" + } } -resource "aws_efs_mount_target" "alpha" { - file_system_id = "${aws_efs_file_system.foo.id}" - subnet_id = "${aws_subnet.alpha.id}" +resource "aws_efs_mount_target" "test" { + file_system_id = aws_efs_file_system.test.id + subnet_id = aws_subnet.test.id } -resource "aws_vpc" "foo" { +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-efs-mount-target" + Name = "tf-acc-efs-mount-target-test" } } -resource "aws_subnet" "alpha" { - vpc_id = "${aws_vpc.foo.id}" - availability_zone = "us-west-2a" +resource "aws_subnet" "test" { + vpc_id = aws_vpc.test.id + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.1.0/24" tags = { - Name = "tf-acc-efs-mount-target" + Name = "tf-acc-efs-mount-target-test" } } -data "aws_efs_mount_target" "by_mount_target_id" { - mount_target_id = "${aws_efs_mount_target.alpha.id}" +data "aws_efs_mount_target" "test" { + mount_target_id = aws_efs_mount_target.test.id } `, ct) } diff --git a/aws/data_source_aws_eip.go b/aws/data_source_aws_eip.go index f28f2d99556..9abf798902f 100644 --- a/aws/data_source_aws_eip.go +++ b/aws/data_source_aws_eip.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_eip_test.go b/aws/data_source_aws_eip_test.go index bce7029ff1b..3d5499500ec 100644 --- a/aws/data_source_aws_eip_test.go +++ b/aws/data_source_aws_eip_test.go @@ -2,11 +2,10 @@ package aws import ( "fmt" - "os" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAwsEip_Filter(t *testing.T) { @@ -157,33 +156,15 @@ func TestAccDataSourceAwsEip_Instance(t *testing.T) { } func TestAccDataSourceAWSEIP_CustomerOwnedIpv4Pool(t *testing.T) { - // Hide Outposts testing behind consistent environment variable - outpostArn := os.Getenv("AWS_OUTPOST_ARN") - if outpostArn == "" { - t.Skip( - "Environment variable AWS_OUTPOST_ARN is not set. " + - "This environment variable must be set to the ARN of " + - "a deployed Outpost to enable this test.") - } - - // Local Gateway Route Table ID filtering in DescribeCoipPools is not currently working - poolId := os.Getenv("AWS_COIP_POOL_ID") - if poolId == "" { - t.Skip( - "Environment variable AWS_COIP_POOL_ID is not set. " + - "This environment variable must be set to the ID of " + - "a deployed Coip Pool to enable this test.") - } - dataSourceName := "data.aws_eip.test" resourceName := "aws_eip.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { - Config: testAccDataSourceAWSEIPConfigCustomerOwnedIpv4Pool(poolId), + Config: testAccDataSourceAWSEIPConfigCustomerOwnedIpv4Pool(), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "customer_owned_ipv4_pool", dataSourceName, "customer_owned_ipv4_pool"), resource.TestCheckResourceAttrPair(resourceName, "customer_owned_ip", dataSourceName, "customer_owned_ip"), @@ -193,17 +174,19 @@ func TestAccDataSourceAWSEIP_CustomerOwnedIpv4Pool(t *testing.T) { }) } -func testAccDataSourceAWSEIPConfigCustomerOwnedIpv4Pool(customerOwnedIpv4Pool string) string { - return fmt.Sprintf(` +func testAccDataSourceAWSEIPConfigCustomerOwnedIpv4Pool() string { + return ` +data "aws_ec2_coip_pools" "test" {} + resource "aws_eip" "test" { - customer_owned_ipv4_pool = %[1]q + customer_owned_ipv4_pool = tolist(data.aws_ec2_coip_pools.test.pool_ids)[0] vpc = true } data "aws_eip" "test" { id = aws_eip.test.id } -`, customerOwnedIpv4Pool) +` } func testAccDataSourceAwsEipConfigFilter(rName string) string { @@ -219,7 +202,7 @@ resource "aws_eip" "test" { data "aws_eip" "test" { filter { name = "tag:Name" - values = ["${aws_eip.test.tags.Name}"] + values = [aws_eip.test.tags.Name] } } `, rName) @@ -231,7 +214,7 @@ resource "aws_eip" "test" { } data "aws_eip" "test" { - id = "${aws_eip.test.id}" + id = aws_eip.test.id } ` @@ -243,7 +226,7 @@ provider "aws" { resource "aws_eip" "test" {} data "aws_eip" "test" { - public_ip = "${aws_eip.test.public_ip}" + public_ip = aws_eip.test.public_ip } ` @@ -253,7 +236,7 @@ resource "aws_eip" "test" { } data "aws_eip" "test" { - public_ip = "${aws_eip.test.public_ip}" + public_ip = aws_eip.test.public_ip } ` @@ -269,7 +252,7 @@ resource "aws_eip" "test" { data "aws_eip" "test" { tags = { - Name = "${aws_eip.test.tags["Name"]}" + Name = aws_eip.test.tags["Name"] } } `, rName) @@ -281,27 +264,27 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id cidr_block = "10.1.0.0/24" } resource "aws_internet_gateway" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } resource "aws_network_interface" "test" { - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } resource "aws_eip" "test" { - vpc = true - network_interface = "${aws_network_interface.test.id}" + vpc = true + network_interface = aws_network_interface.test.id } data "aws_eip" "test" { filter { name = "network-interface-id" - values = ["${aws_eip.test.network_interface}"] + values = [aws_eip.test.network_interface] } } ` @@ -309,8 +292,8 @@ data "aws_eip" "test" { const testAccDataSourceAwsEipConfigInstance = ` data "aws_availability_zones" "available" { # Error launching source instance: Unsupported: Your requested instance type (t2.micro) is not supported in your requested Availability Zone (us-west-2d). - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -323,13 +306,13 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" - vpc_id = "${aws_vpc.test.id}" - cidr_block = "10.2.0.0/24" + availability_zone = data.aws_availability_zones.available.names[0] + vpc_id = aws_vpc.test.id + cidr_block = "10.2.0.0/24" } resource "aws_internet_gateway" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } data "aws_ami" "test" { @@ -342,20 +325,20 @@ data "aws_ami" "test" { } resource "aws_instance" "test" { - ami = "${data.aws_ami.test.id}" - subnet_id = "${aws_subnet.test.id}" + ami = data.aws_ami.test.id + subnet_id = aws_subnet.test.id instance_type = "t2.micro" } resource "aws_eip" "test" { - vpc = true - instance = "${aws_instance.test.id}" + vpc = true + instance = aws_instance.test.id } data "aws_eip" "test" { filter { - name = "instance-id" - values = ["${aws_eip.test.instance}"] + name = "instance-id" + values = [aws_eip.test.instance] } } ` diff --git a/aws/data_source_aws_eks_cluster.go b/aws/data_source_aws_eks_cluster.go index 9b45c094f24..179487a6656 100644 --- a/aws/data_source_aws_eks_cluster.go +++ b/aws/data_source_aws_eks_cluster.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/eks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_eks_cluster_auth.go b/aws/data_source_aws_eks_cluster_auth.go index d9c2c39a6ae..849fc5badd3 100644 --- a/aws/data_source_aws_eks_cluster_auth.go +++ b/aws/data_source_aws_eks_cluster_auth.go @@ -4,8 +4,8 @@ import ( "fmt" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/eks/token" ) diff --git a/aws/data_source_aws_eks_cluster_auth_test.go b/aws/data_source_aws_eks_cluster_auth_test.go index 97ac0e7f4da..f0222c5485a 100644 --- a/aws/data_source_aws_eks_cluster_auth_test.go +++ b/aws/data_source_aws_eks_cluster_auth_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/eks/token" ) @@ -56,6 +56,6 @@ func testAccCheckAwsEksClusterAuthToken(n string) resource.TestCheckFunc { const testAccCheckAwsEksClusterAuthConfig_basic = ` data "aws_eks_cluster_auth" "test" { - name = "foobar" + name = "foobar" } ` diff --git a/aws/data_source_aws_eks_cluster_test.go b/aws/data_source_aws_eks_cluster_test.go index 964e1c3dc0a..c72469d6ef8 100644 --- a/aws/data_source_aws_eks_cluster_test.go +++ b/aws/data_source_aws_eks_cluster_test.go @@ -5,8 +5,9 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSEksClusterDataSource_basic(t *testing.T) { @@ -15,10 +16,9 @@ func TestAccAWSEksClusterDataSource_basic(t *testing.T) { resourceName := "aws_eks_cluster.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEks(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEksClusterDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEks(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEksClusterDestroy, Steps: []resource.TestStep{ { Config: testAccAWSEksClusterDataSourceConfig_Basic(rName), @@ -28,8 +28,8 @@ func TestAccAWSEksClusterDataSource_basic(t *testing.T) { resource.TestCheckResourceAttrPair(resourceName, "certificate_authority.0.data", dataSourceResourceName, "certificate_authority.0.data"), resource.TestCheckResourceAttrPair(resourceName, "created_at", dataSourceResourceName, "created_at"), resource.TestCheckResourceAttr(dataSourceResourceName, "enabled_cluster_log_types.#", "2"), - resource.TestCheckResourceAttr(dataSourceResourceName, "enabled_cluster_log_types.2902841359", "api"), - resource.TestCheckResourceAttr(dataSourceResourceName, "enabled_cluster_log_types.2451111801", "audit"), + tfawsresource.TestCheckTypeSetElemAttr(dataSourceResourceName, "enabled_cluster_log_types.*", "api"), + tfawsresource.TestCheckTypeSetElemAttr(dataSourceResourceName, "enabled_cluster_log_types.*", "audit"), resource.TestCheckResourceAttrPair(resourceName, "endpoint", dataSourceResourceName, "endpoint"), resource.TestCheckResourceAttrPair(resourceName, "identity.#", dataSourceResourceName, "identity.#"), resource.TestCheckResourceAttrPair(resourceName, "identity.0.oidc.#", dataSourceResourceName, "identity.0.oidc.#"), @@ -58,7 +58,7 @@ func testAccAWSEksClusterDataSourceConfig_Basic(rName string) string { %[1]s data "aws_eks_cluster" "test" { - name = "${aws_eks_cluster.test.name}" + name = aws_eks_cluster.test.name } `, testAccAWSEksClusterConfig_Logging(rName, []string{"api", "audit"})) } diff --git a/aws/data_source_aws_elastic_beanstalk_application.go b/aws/data_source_aws_elastic_beanstalk_application.go index 01d55d1ffd8..d852a48901b 100644 --- a/aws/data_source_aws_elastic_beanstalk_application.go +++ b/aws/data_source_aws_elastic_beanstalk_application.go @@ -5,7 +5,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elasticbeanstalk" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsElasticBeanstalkApplication() *schema.Resource { diff --git a/aws/data_source_aws_elastic_beanstalk_application_test.go b/aws/data_source_aws_elastic_beanstalk_application_test.go index 6209b1e1b4a..bd1c689cce2 100644 --- a/aws/data_source_aws_elastic_beanstalk_application_test.go +++ b/aws/data_source_aws_elastic_beanstalk_application_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAwsElasticBeanstalkApplicationDataSource_basic(t *testing.T) { @@ -39,7 +39,7 @@ func testAccAwsElasticBeanstalkApplicationDataSourceConfig_Basic(rName string) s %s data "aws_elastic_beanstalk_application" "test" { - name = "${aws_elastic_beanstalk_application.tftest.name}" + name = aws_elastic_beanstalk_application.tftest.name } `, testAccBeanstalkAppConfigWithMaxAge(rName)) } diff --git a/aws/data_source_aws_elastic_beanstalk_hosted_zone.go b/aws/data_source_aws_elastic_beanstalk_hosted_zone.go index 286653ab29b..6e2aa3795b4 100644 --- a/aws/data_source_aws_elastic_beanstalk_hosted_zone.go +++ b/aws/data_source_aws_elastic_beanstalk_hosted_zone.go @@ -3,7 +3,7 @@ package aws import ( "fmt" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // See http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region diff --git a/aws/data_source_aws_elastic_beanstalk_hosted_zone_test.go b/aws/data_source_aws_elastic_beanstalk_hosted_zone_test.go index b1a5fd9b92b..a34bbb36775 100644 --- a/aws/data_source_aws_elastic_beanstalk_hosted_zone_test.go +++ b/aws/data_source_aws_elastic_beanstalk_hosted_zone_test.go @@ -5,8 +5,8 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSDataSourceElasticBeanstalkHostedZone_basic(t *testing.T) { diff --git a/aws/data_source_aws_elastic_beanstalk_solution_stack.go b/aws/data_source_aws_elastic_beanstalk_solution_stack.go index 25c0ba94999..2d6fe58b1a9 100644 --- a/aws/data_source_aws_elastic_beanstalk_solution_stack.go +++ b/aws/data_source_aws_elastic_beanstalk_solution_stack.go @@ -6,8 +6,8 @@ import ( "regexp" "github.com/aws/aws-sdk-go/service/elasticbeanstalk" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func dataSourceAwsElasticBeanstalkSolutionStack() *schema.Resource { diff --git a/aws/data_source_aws_elastic_beanstalk_solution_stack_test.go b/aws/data_source_aws_elastic_beanstalk_solution_stack_test.go index 0cf12973c0b..e3a2419a5ac 100644 --- a/aws/data_source_aws_elastic_beanstalk_solution_stack_test.go +++ b/aws/data_source_aws_elastic_beanstalk_solution_stack_test.go @@ -5,11 +5,11 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAWSElasticBeanstalkSolutionStackDataSource(t *testing.T) { +func TestAccAWSElasticBeanstalkSolutionStackDataSource_basic(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -42,7 +42,7 @@ func testAccCheckAwsElasticBeanstalkSolutionStackDataSourceID(n string) resource const testAccCheckAwsElasticBeanstalkSolutionStackDataSourceConfig = ` data "aws_elastic_beanstalk_solution_stack" "multi_docker" { - most_recent = true - name_regex = "^64bit Amazon Linux (.*) Multi-container Docker (.*)$" + most_recent = true + name_regex = "^64bit Amazon Linux (.*) Multi-container Docker (.*)$" } ` diff --git a/aws/data_source_aws_elasticache_cluster.go b/aws/data_source_aws_elasticache_cluster.go index 557f1c2b776..ec042fef781 100644 --- a/aws/data_source_aws_elasticache_cluster.go +++ b/aws/data_source_aws_elasticache_cluster.go @@ -8,7 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/elasticache" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_elasticache_cluster_test.go b/aws/data_source_aws_elasticache_cluster_test.go index 9f9dabbf46c..9891262b660 100644 --- a/aws/data_source_aws_elasticache_cluster_test.go +++ b/aws/data_source_aws_elasticache_cluster_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSDataElasticacheCluster_basic(t *testing.T) { @@ -36,11 +36,11 @@ func TestAccAWSDataElasticacheCluster_basic(t *testing.T) { func testAccAWSElastiCacheClusterConfigWithDataSource(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { - cluster_id = %[1]q - engine = "memcached" - node_type = "cache.t3.small" - num_cache_nodes = 1 - port = 11211 + cluster_id = %[1]q + engine = "memcached" + node_type = "cache.t3.small" + num_cache_nodes = 1 + port = 11211 } data "aws_elasticache_cluster" "test" { diff --git a/aws/data_source_aws_elasticache_replication_group.go b/aws/data_source_aws_elasticache_replication_group.go index 3a5e07def39..b0b8c6262ca 100644 --- a/aws/data_source_aws_elasticache_replication_group.go +++ b/aws/data_source_aws_elasticache_replication_group.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elasticache" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsElasticacheReplicationGroup() *schema.Resource { @@ -49,7 +49,6 @@ func dataSourceAwsElasticacheReplicationGroup() *schema.Resource { Type: schema.TypeSet, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "node_type": { Type: schema.TypeString, @@ -69,31 +68,32 @@ func dataSourceAwsElasticacheReplicationGroup() *schema.Resource { func dataSourceAwsElasticacheReplicationGroupRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).elasticacheconn + + groupID := d.Get("replication_group_id").(string) input := &elasticache.DescribeReplicationGroupsInput{ - ReplicationGroupId: aws.String(d.Get("replication_group_id").(string)), + ReplicationGroupId: aws.String(groupID), } log.Printf("[DEBUG] Reading ElastiCache Replication Group: %s", input) resp, err := conn.DescribeReplicationGroups(input) if err != nil { - return err - } - - var rg *elasticache.ReplicationGroup - for _, r := range resp.ReplicationGroups { - if *r.ReplicationGroupId == d.Get("replication_group_id").(string) { - rg = r + if isAWSErr(err, elasticache.ErrCodeReplicationGroupNotFoundFault, "") { + return fmt.Errorf("ElastiCache Replication Group (%s) not found", groupID) } + return fmt.Errorf("error reading replication group (%s): %w", groupID, err) } - if rg == nil { - return fmt.Errorf("Elasticache Replication Group (%s) not found", d.Get("replication_group_id").(string)) + + if resp == nil || len(resp.ReplicationGroups) == 0 { + return fmt.Errorf("error reading replication group (%s): empty output", groupID) } - d.SetId(*rg.ReplicationGroupId) + rg := resp.ReplicationGroups[0] + + d.SetId(aws.StringValue(rg.ReplicationGroupId)) d.Set("replication_group_description", rg.Description) d.Set("auth_token_enabled", rg.AuthTokenEnabled) if rg.AutomaticFailover != nil { - switch *rg.AutomaticFailover { + switch aws.StringValue(rg.AutomaticFailover) { case elasticache.AutomaticFailoverStatusDisabled, elasticache.AutomaticFailoverStatusDisabling: d.Set("automatic_failover_enabled", false) case elasticache.AutomaticFailoverStatusEnabled, elasticache.AutomaticFailoverStatusEnabling: @@ -106,14 +106,14 @@ func dataSourceAwsElasticacheReplicationGroupRead(d *schema.ResourceData, meta i } else { if rg.NodeGroups == nil { d.SetId("") - return fmt.Errorf("Elasticache Replication Group (%s) doesn't have node groups.", d.Get("replication_group_id").(string)) + return fmt.Errorf("Elasticache Replication Group (%s) doesn't have node groups.", aws.StringValue(rg.ReplicationGroupId)) } d.Set("port", rg.NodeGroups[0].PrimaryEndpoint.Port) d.Set("primary_endpoint_address", rg.NodeGroups[0].PrimaryEndpoint.Address) } d.Set("number_cache_clusters", len(rg.MemberClusters)) if err := d.Set("member_clusters", flattenStringList(rg.MemberClusters)); err != nil { - return fmt.Errorf("error setting member_clusters: %s", err) + return fmt.Errorf("error setting member_clusters: %w", err) } d.Set("node_type", rg.CacheNodeType) d.Set("snapshot_window", rg.SnapshotWindow) diff --git a/aws/data_source_aws_elasticache_replication_group_test.go b/aws/data_source_aws_elasticache_replication_group_test.go index 0472fd626c4..a08e1eedf08 100644 --- a/aws/data_source_aws_elasticache_replication_group_test.go +++ b/aws/data_source_aws_elasticache_replication_group_test.go @@ -2,10 +2,11 @@ package aws import ( "fmt" + "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAwsElasticacheReplicationGroup_basic(t *testing.T) { @@ -61,6 +62,20 @@ func TestAccDataSourceAwsElasticacheReplicationGroup_ClusterMode(t *testing.T) { }) } +func TestAccDataSourceAwsElasticacheReplicationGroup_NonExistent(t *testing.T) { + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAwsElasticacheReplicationGroupConfig_NonExistent, + ExpectError: regexp.MustCompile(`not found`), + }, + }, + }) +} + func testAccDataSourceAwsElasticacheReplicationGroupConfig_basic(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { @@ -109,3 +124,9 @@ data "aws_elasticache_replication_group" "test" { } `, rName) } + +const testAccDataSourceAwsElasticacheReplicationGroupConfig_NonExistent = ` +data "aws_elasticache_replication_group" "test" { + replication_group_id = "tf-acc-test-nonexistent" +} +` diff --git a/aws/data_source_aws_elasticsearch_domain.go b/aws/data_source_aws_elasticsearch_domain.go index aab4877483c..afc8c231a1f 100644 --- a/aws/data_source_aws_elasticsearch_domain.go +++ b/aws/data_source_aws_elasticsearch_domain.go @@ -5,8 +5,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elasticsearchservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -22,6 +22,23 @@ func dataSourceAwsElasticSearchDomain() *schema.Resource { "advanced_options": { Type: schema.TypeMap, Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "advanced_security_options": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "internal_user_database_enabled": { + Type: schema.TypeBool, + Computed: true, + }, + }, + }, }, "domain_name": { Type: schema.TypeString, @@ -136,6 +153,18 @@ func dataSourceAwsElasticSearchDomain() *schema.Resource { Type: schema.TypeBool, Computed: true, }, + "warm_enabled": { + Type: schema.TypeBool, + Optional: true, + }, + "warm_count": { + Type: schema.TypeInt, + Computed: true, + }, + "warm_type": { + Type: schema.TypeString, + Computed: true, + }, }, }, }, @@ -237,7 +266,7 @@ func dataSourceAwsElasticSearchDomain() *schema.Resource { Computed: true, }, "processing": { - Type: schema.TypeString, + Type: schema.TypeBool, Computed: true, }, @@ -284,6 +313,10 @@ func dataSourceAwsElasticSearchDomainRead(d *schema.ResourceData, meta interface d.Set("endpoint", ds.Endpoint) d.Set("kibana_endpoint", getKibanaEndpoint(d)) + if err := d.Set("advanced_security_options", flattenAdvancedSecurityOptions(ds.AdvancedSecurityOptions)); err != nil { + return fmt.Errorf("error setting advanced_security_options: %w", err) + } + if err := d.Set("ebs_options", flattenESEBSOptions(ds.EBSOptions)); err != nil { return fmt.Errorf("error setting ebs_options: %s", err) } diff --git a/aws/data_source_aws_elasticsearch_domain_test.go b/aws/data_source_aws_elasticsearch_domain_test.go index ed9448e7a49..170222f1852 100644 --- a/aws/data_source_aws_elasticsearch_domain_test.go +++ b/aws/data_source_aws_elasticsearch_domain_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSDataElasticsearchDomain_basic(t *testing.T) { @@ -20,6 +20,7 @@ func TestAccAWSDataElasticsearchDomain_basic(t *testing.T) { { Config: testAccAWSElasticsearchDomainConfigWithDataSource(rInt), Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr(datasourceName, "processing", "false"), resource.TestCheckResourceAttrPair(datasourceName, "elasticsearch_version", resourceName, "elasticsearch_version"), resource.TestCheckResourceAttrPair(datasourceName, "cluster_config.#", resourceName, "cluster_config.#"), resource.TestCheckResourceAttrPair(datasourceName, "cluster_config.0.instance_type", resourceName, "cluster_config.0.instance_type"), @@ -32,6 +33,7 @@ func TestAccAWSDataElasticsearchDomain_basic(t *testing.T) { resource.TestCheckResourceAttrPair(datasourceName, "ebs_options.0.volume_size", resourceName, "ebs_options.0.volume_size"), resource.TestCheckResourceAttrPair(datasourceName, "snapshot_options.#", resourceName, "snapshot_options.#"), resource.TestCheckResourceAttrPair(datasourceName, "snapshot_options.0.automated_snapshot_start_hour", resourceName, "snapshot_options.0.automated_snapshot_start_hour"), + resource.TestCheckResourceAttrPair(datasourceName, "advanced_security_options.#", resourceName, "advanced_security_options.#"), ), }, }, @@ -64,6 +66,8 @@ func TestAccAWSDataElasticsearchDomain_advanced(t *testing.T) { resource.TestCheckResourceAttrPair(datasourceName, "snapshot_options.0.automated_snapshot_start_hour", resourceName, "snapshot_options.0.automated_snapshot_start_hour"), resource.TestCheckResourceAttrPair(datasourceName, "log_publishing_options.#", resourceName, "log_publishing_options.#"), resource.TestCheckResourceAttrPair(datasourceName, "vpc_options.#", resourceName, "vpc_options.#"), + resource.TestCheckResourceAttrPair(datasourceName, "advanced_security_options.0.enabled", resourceName, "advanced_security_options.0.enabled"), + resource.TestCheckResourceAttrPair(datasourceName, "advanced_security_options.0.internal_user_database_enabled", resourceName, "advanced_security_options.0.internal_user_database_enabled"), ), }, }, @@ -73,7 +77,7 @@ func TestAccAWSDataElasticsearchDomain_advanced(t *testing.T) { func testAccAWSElasticsearchDomainConfigWithDataSource(rInt int) string { return fmt.Sprintf(` locals { - random_name = "test-es-%d" + random_name = "test-es-%d" } data "aws_region" "current" {} @@ -81,47 +85,55 @@ data "aws_region" "current" {} data "aws_caller_identity" "current" {} resource "aws_elasticsearch_domain" "test" { - domain_name = "${local.random_name}" - elasticsearch_version = "1.5" + domain_name = local.random_name + elasticsearch_version = "1.5" - access_policies = < 1 { + return fmt.Errorf("Search returned %d result(s), please revise so only one is returned", len(dlt.LaunchTemplates)) + } lt := dlt.LaunchTemplates[0] - d.SetId(*lt.LaunchTemplateId) + log.Printf("[DEBUG] Found launch template %s", aws.StringValue(lt.LaunchTemplateId)) + + d.SetId(aws.StringValue(lt.LaunchTemplateId)) d.Set("name", lt.LaunchTemplateName) d.Set("latest_version", lt.LatestVersionNumber) d.Set("default_version", lt.DefaultVersionNumber) if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(lt.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %s", err) + return fmt.Errorf("error setting tags: %w", err) } arn := arn.ARN{ @@ -448,10 +441,14 @@ func dataSourceAwsLaunchTemplateRead(d *schema.ResourceData, meta interface{}) e Versions: []*string{aws.String(version)}, }) if err != nil { - return err + return fmt.Errorf("error reading launch template version (%s) for launch template (%s): %w", version, d.Id(), err) + } + + if dltv == nil || len(dltv.LaunchTemplateVersions) == 0 { + return fmt.Errorf("error reading launch template version (%s) for launch template (%s): empty output", version, d.Id()) } - log.Printf("[DEBUG] Received launch template version %q (version %d)", d.Id(), *lt.LatestVersionNumber) + log.Printf("[DEBUG] Received launch template version %q (version %d)", d.Id(), aws.Int64Value(lt.LatestVersionNumber)) ltData := dltv.LaunchTemplateVersions[0].LaunchTemplateData @@ -462,9 +459,13 @@ func dataSourceAwsLaunchTemplateRead(d *schema.ResourceData, meta interface{}) e d.Set("kernel_id", ltData.KernelId) d.Set("key_name", ltData.KeyName) d.Set("ram_disk_id", ltData.RamDiskId) - d.Set("security_group_names", aws.StringValueSlice(ltData.SecurityGroups)) + if err := d.Set("security_group_names", aws.StringValueSlice(ltData.SecurityGroups)); err != nil { + return fmt.Errorf("error setting security_group_names: %w", err) + } d.Set("user_data", ltData.UserData) - d.Set("vpc_security_group_ids", aws.StringValueSlice(ltData.SecurityGroupIds)) + if err := d.Set("vpc_security_group_ids", aws.StringValueSlice(ltData.SecurityGroupIds)); err != nil { + return fmt.Errorf("error setting vpc_security_group_ids: %w", err) + } d.Set("ebs_optimized", "") if ltData.EbsOptimized != nil { @@ -472,49 +473,49 @@ func dataSourceAwsLaunchTemplateRead(d *schema.ResourceData, meta interface{}) e } if err := d.Set("block_device_mappings", getBlockDeviceMappings(ltData.BlockDeviceMappings)); err != nil { - return fmt.Errorf("error setting block_device_mappings: %s", err) + return fmt.Errorf("error setting block_device_mappings: %w", err) } if strings.HasPrefix(aws.StringValue(ltData.InstanceType), "t2") || strings.HasPrefix(aws.StringValue(ltData.InstanceType), "t3") { if err := d.Set("credit_specification", getCreditSpecification(ltData.CreditSpecification)); err != nil { - return fmt.Errorf("error setting credit_specification: %s", err) + return fmt.Errorf("error setting credit_specification: %w", err) } } if err := d.Set("elastic_gpu_specifications", getElasticGpuSpecifications(ltData.ElasticGpuSpecifications)); err != nil { - return fmt.Errorf("error setting elastic_gpu_specifications: %s", err) + return fmt.Errorf("error setting elastic_gpu_specifications: %w", err) } if err := d.Set("iam_instance_profile", getIamInstanceProfile(ltData.IamInstanceProfile)); err != nil { - return fmt.Errorf("error setting iam_instance_profile: %s", err) + return fmt.Errorf("error setting iam_instance_profile: %w", err) } if err := d.Set("instance_market_options", getInstanceMarketOptions(ltData.InstanceMarketOptions)); err != nil { - return fmt.Errorf("error setting instance_market_options: %s", err) + return fmt.Errorf("error setting instance_market_options: %w", err) } if err := d.Set("metadata_options", flattenLaunchTemplateInstanceMetadataOptions(ltData.MetadataOptions)); err != nil { - return fmt.Errorf("error setting metadata_options: %s", err) + return fmt.Errorf("error setting metadata_options: %w", err) } if err := d.Set("monitoring", getMonitoring(ltData.Monitoring)); err != nil { - return fmt.Errorf("error setting monitoring: %s", err) + return fmt.Errorf("error setting monitoring: %w", err) } if err := d.Set("network_interfaces", getNetworkInterfaces(ltData.NetworkInterfaces)); err != nil { - return fmt.Errorf("error setting network_interfaces: %s", err) + return fmt.Errorf("error setting network_interfaces: %w", err) } if err := d.Set("placement", getPlacement(ltData.Placement)); err != nil { - return fmt.Errorf("error setting placement: %s", err) + return fmt.Errorf("error setting placement: %w", err) } if err := d.Set("hibernation_options", flattenLaunchTemplateHibernationOptions(ltData.HibernationOptions)); err != nil { - return fmt.Errorf("error setting hibernation_options: %s", err) + return fmt.Errorf("error setting hibernation_options: %w", err) } if err := d.Set("tag_specifications", getTagSpecifications(ltData.TagSpecifications)); err != nil { - return fmt.Errorf("error setting tag_specifications: %s", err) + return fmt.Errorf("error setting tag_specifications: %w", err) } return nil diff --git a/aws/data_source_aws_launch_template_test.go b/aws/data_source_aws_launch_template_test.go index 91da898720c..596695bbc6e 100644 --- a/aws/data_source_aws_launch_template_test.go +++ b/aws/data_source_aws_launch_template_test.go @@ -2,10 +2,11 @@ package aws import ( "fmt" + "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSLaunchTemplateDataSource_basic(t *testing.T) { @@ -159,6 +160,55 @@ func TestAccAWSLaunchTemplateDataSource_associatePublicIPAddress(t *testing.T) { }) } +func TestAccAWSLaunchTemplateDataSource_networkInterfaces_deleteOnTermination(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + dataSourceName := "data.aws_launch_template.test" + resourceName := "aws_launch_template.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLaunchTemplateDataSourceConfigNetworkInterfacesDeleteOnTermination(rName, "true"), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "network_interfaces.#", resourceName, "network_interfaces.#"), + resource.TestCheckResourceAttrPair(dataSourceName, "network_interfaces.0.delete_on_termination", resourceName, "network_interfaces.0.delete_on_termination"), + ), + }, + { + Config: testAccAWSLaunchTemplateDataSourceConfigNetworkInterfacesDeleteOnTermination(rName, "false"), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "network_interfaces.#", resourceName, "network_interfaces.#"), + resource.TestCheckResourceAttrPair(dataSourceName, "network_interfaces.0.delete_on_termination", resourceName, "network_interfaces.0.delete_on_termination"), + ), + }, + { + Config: testAccAWSLaunchTemplateDataSourceConfigNetworkInterfacesDeleteOnTermination(rName, "null"), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "network_interfaces.#", resourceName, "network_interfaces.#"), + resource.TestCheckResourceAttrPair(dataSourceName, "network_interfaces.0.delete_on_termination", resourceName, "network_interfaces.0.delete_on_termination"), + ), + }, + }, + }) +} + +func TestAccAWSLaunchTemplateDataSource_NonExistent(t *testing.T) { + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLaunchTemplateDataSourceConfig_NonExistent, + ExpectError: regexp.MustCompile(`not found`), + }, + }, + }) +} + func testAccAWSLaunchTemplateDataSourceConfig_Basic(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { @@ -166,7 +216,7 @@ resource "aws_launch_template" "test" { } data "aws_launch_template" "test" { - name = "${aws_launch_template.test.name}" + name = aws_launch_template.test.name } `, rName) } @@ -180,7 +230,7 @@ resource "aws_launch_template" "test" { data "aws_launch_template" "test" { filter { name = "launch-template-name" - values = ["${aws_launch_template.test.name}"] + values = [aws_launch_template.test.name] } } `, rName) @@ -190,6 +240,7 @@ func testAccAWSLaunchTemplateDataSourceConfigFilterTags(rName string, rInt int) return fmt.Sprintf(` resource "aws_launch_template" "test" { name = %[1]q + tags = { Name = "key1" TestSeed = "%[2]d" @@ -198,7 +249,7 @@ resource "aws_launch_template" "test" { data "aws_launch_template" "test" { tags = { - Name = "${aws_launch_template.test.tags["Name"]}" + Name = aws_launch_template.test.tags["Name"] TestSeed = "%[2]d" } } @@ -229,7 +280,7 @@ resource "aws_launch_template" "test" { name = %[1]q network_interfaces { - associate_public_ip_address = %[2]s + associate_public_ip_address = %[2]s } } @@ -238,3 +289,25 @@ data "aws_launch_template" "test" { } `, rName, associatePublicIPAddress) } + +func testAccAWSLaunchTemplateDataSourceConfigNetworkInterfacesDeleteOnTermination(rName, deleteOnTermination string) string { + return fmt.Sprintf(` +resource "aws_launch_template" "test" { + name = %[1]q + + network_interfaces { + delete_on_termination = %[2]s + } +} + +data "aws_launch_template" "test" { + name = aws_launch_template.test.name +} +`, rName, deleteOnTermination) +} + +const testAccAWSLaunchTemplateDataSourceConfig_NonExistent = ` +data "aws_launch_template" "test" { + name = "tf-acc-test-nonexistent" +} +` diff --git a/aws/data_source_aws_lb.go b/aws/data_source_aws_lb.go index f855bff7459..c918fdd3a33 100644 --- a/aws/data_source_aws_lb.go +++ b/aws/data_source_aws_lb.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsLb() *schema.Resource { @@ -14,9 +14,10 @@ func dataSourceAwsLb() *schema.Resource { Read: dataSourceAwsLbRead, Schema: map[string]*schema.Schema{ "arn": { - Type: schema.TypeString, - Optional: true, - Computed: true, + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validateArn, }, "arn_suffix": { @@ -44,14 +45,12 @@ func dataSourceAwsLb() *schema.Resource { Type: schema.TypeSet, Elem: &schema.Schema{Type: schema.TypeString}, Computed: true, - Set: schema.HashString, }, "subnets": { Type: schema.TypeSet, Elem: &schema.Schema{Type: schema.TypeString}, Computed: true, - Set: schema.HashString, }, "subnet_mapping": { @@ -61,11 +60,15 @@ func dataSourceAwsLb() *schema.Resource { Schema: map[string]*schema.Schema{ "subnet_id": { Type: schema.TypeString, - Required: true, + Computed: true, }, "allocation_id": { Type: schema.TypeString, - Optional: true, + Computed: true, + }, + "private_ipv4_address": { + Type: schema.TypeString, + Computed: true, }, }, }, @@ -97,6 +100,11 @@ func dataSourceAwsLb() *schema.Resource { Computed: true, }, + "enable_http2": { + Type: schema.TypeBool, + Computed: true, + }, + "idle_timeout": { Type: schema.TypeInt, Computed: true, @@ -122,13 +130,18 @@ func dataSourceAwsLb() *schema.Resource { Computed: true, }, + "ip_address_type": { + Type: schema.TypeString, + Computed: true, + }, + "tags": tagsSchemaComputed(), }, } } func dataSourceAwsLbRead(d *schema.ResourceData, meta interface{}) error { - elbconn := meta.(*AWSClient).elbv2conn + conn := meta.(*AWSClient).elbv2conn lbArn := d.Get("arn").(string) lbName := d.Get("name").(string) @@ -141,7 +154,7 @@ func dataSourceAwsLbRead(d *schema.ResourceData, meta interface{}) error { } log.Printf("[DEBUG] Reading Load Balancer: %s", describeLbOpts) - describeResp, err := elbconn.DescribeLoadBalancers(describeLbOpts) + describeResp, err := conn.DescribeLoadBalancers(describeLbOpts) if err != nil { return fmt.Errorf("Error retrieving LB: %s", err) } diff --git a/aws/data_source_aws_lb_listener.go b/aws/data_source_aws_lb_listener.go index f4bca086bd4..27dc8ad6edf 100644 --- a/aws/data_source_aws_lb_listener.go +++ b/aws/data_source_aws_lb_listener.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsLbListener() *schema.Resource { @@ -62,6 +62,7 @@ func dataSourceAwsLbListener() *schema.Resource { "authentication_request_extra_params": { Type: schema.TypeMap, Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "on_unauthenticated_request": { Type: schema.TypeString, @@ -102,6 +103,7 @@ func dataSourceAwsLbListener() *schema.Resource { "authentication_request_extra_params": { Type: schema.TypeMap, Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "authorization_endpoint": { Type: schema.TypeString, diff --git a/aws/data_source_aws_lb_listener_test.go b/aws/data_source_aws_lb_listener_test.go index 4f56e6b4e89..b319be468eb 100644 --- a/aws/data_source_aws_lb_listener_test.go +++ b/aws/data_source_aws_lb_listener_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAWSLBListener_basic(t *testing.T) { @@ -110,12 +110,12 @@ func TestAccDataSourceAWSLBListener_https(t *testing.T) { func testAccDataSourceAWSLBListenerConfigBasic(lbName, targetGroupName string) string { return fmt.Sprintf(` resource "aws_lb_listener" "front_end" { - load_balancer_arn = "${aws_lb.alb_test.id}" + load_balancer_arn = aws_lb.alb_test.id protocol = "HTTP" port = "80" default_action { - target_group_arn = "${aws_lb_target_group.test.id}" + target_group_arn = aws_lb_target_group.test.id type = "forward" } } @@ -123,8 +123,8 @@ resource "aws_lb_listener" "front_end" { resource "aws_lb" "alb_test" { name = "%s" internal = true - security_groups = ["${aws_security_group.alb_test.id}"] - subnets = ["${aws_subnet.alb_test.0.id}", "${aws_subnet.alb_test.1.id}"] + security_groups = [aws_security_group.alb_test.id] + subnets = [aws_subnet.alb_test.0.id, aws_subnet.alb_test.1.id] idle_timeout = 30 enable_deletion_protection = false @@ -138,7 +138,7 @@ resource "aws_lb_target_group" "test" { name = "%s" port = 8080 protocol = "HTTP" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id health_check { path = "/health" @@ -176,10 +176,10 @@ resource "aws_vpc" "alb_test" { resource "aws_subnet" "alb_test" { count = 2 - vpc_id = "${aws_vpc.alb_test.id}" - cidr_block = "${element(var.subnets, count.index)}" + 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)}" + availability_zone = element(data.aws_availability_zones.available.names, count.index) tags = { Name = "tf-acc-lb-listener-data-source-basic" @@ -189,7 +189,7 @@ resource "aws_subnet" "alb_test" { resource "aws_security_group" "alb_test" { name = "allow_all_alb_test" description = "Used for ALB Testing" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id ingress { from_port = 0 @@ -211,24 +211,24 @@ resource "aws_security_group" "alb_test" { } data "aws_lb_listener" "front_end" { - arn = "${aws_lb_listener.front_end.arn}" + arn = aws_lb_listener.front_end.arn } data "aws_lb_listener" "from_lb_and_port" { - load_balancer_arn = "${aws_lb.alb_test.arn}" - port = "${aws_lb_listener.front_end.port}" + load_balancer_arn = aws_lb.alb_test.arn + port = aws_lb_listener.front_end.port } output "front_end_load_balancer_arn" { - value = "${data.aws_lb_listener.front_end.load_balancer_arn}" + value = data.aws_lb_listener.front_end.load_balancer_arn } output "front_end_port" { - value = "${data.aws_lb_listener.front_end.port}" + value = data.aws_lb_listener.front_end.port } output "from_lb_and_port_arn" { - value = "${data.aws_lb_listener.from_lb_and_port.arn}" + value = data.aws_lb_listener.from_lb_and_port.arn } `, lbName, targetGroupName) } @@ -236,12 +236,12 @@ output "from_lb_and_port_arn" { func testAccDataSourceAWSLBListenerConfigBackwardsCompatibility(lbName, targetGroupName string) string { return fmt.Sprintf(` resource "aws_alb_listener" "front_end" { - load_balancer_arn = "${aws_alb.alb_test.id}" + load_balancer_arn = aws_alb.alb_test.id protocol = "HTTP" port = "80" default_action { - target_group_arn = "${aws_alb_target_group.test.id}" + target_group_arn = aws_alb_target_group.test.id type = "forward" } } @@ -249,8 +249,8 @@ resource "aws_alb_listener" "front_end" { resource "aws_alb" "alb_test" { name = "%s" internal = true - security_groups = ["${aws_security_group.alb_test.id}"] - subnets = ["${aws_subnet.alb_test.0.id}", "${aws_subnet.alb_test.1.id}"] + security_groups = [aws_security_group.alb_test.id] + subnets = [aws_subnet.alb_test.0.id, aws_subnet.alb_test.1.id] idle_timeout = 30 enable_deletion_protection = false @@ -264,7 +264,7 @@ resource "aws_alb_target_group" "test" { name = "%s" port = 8080 protocol = "HTTP" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id health_check { path = "/health" @@ -302,10 +302,10 @@ resource "aws_vpc" "alb_test" { resource "aws_subnet" "alb_test" { count = 2 - vpc_id = "${aws_vpc.alb_test.id}" - cidr_block = "${element(var.subnets, count.index)}" + 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)}" + availability_zone = element(data.aws_availability_zones.available.names, count.index) tags = { Name = "tf-acc-lb-listener-data-source-bc" @@ -315,7 +315,7 @@ resource "aws_subnet" "alb_test" { resource "aws_security_group" "alb_test" { name = "allow_all_alb_test" description = "Used for ALB Testing" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id ingress { from_port = 0 @@ -337,12 +337,12 @@ resource "aws_security_group" "alb_test" { } data "aws_alb_listener" "front_end" { - arn = "${aws_alb_listener.front_end.arn}" + arn = aws_alb_listener.front_end.arn } data "aws_alb_listener" "from_lb_and_port" { - load_balancer_arn = "${aws_alb.alb_test.arn}" - port = "${aws_alb_listener.front_end.port}" + load_balancer_arn = aws_alb.alb_test.arn + port = aws_alb_listener.front_end.port } `, lbName, targetGroupName) } @@ -350,14 +350,14 @@ data "aws_alb_listener" "from_lb_and_port" { func testAccDataSourceAWSLBListenerConfigHTTPS(lbName, targetGroupName, certificate, key string) string { return fmt.Sprintf(` resource "aws_lb_listener" "front_end" { - load_balancer_arn = "${aws_lb.alb_test.id}" + load_balancer_arn = aws_lb.alb_test.id protocol = "HTTPS" port = "443" ssl_policy = "ELBSecurityPolicy-2016-08" - certificate_arn = "${aws_iam_server_certificate.test_cert.arn}" + certificate_arn = aws_iam_server_certificate.test_cert.arn default_action { - target_group_arn = "${aws_lb_target_group.test.id}" + target_group_arn = aws_lb_target_group.test.id type = "forward" } } @@ -365,8 +365,8 @@ resource "aws_lb_listener" "front_end" { resource "aws_lb" "alb_test" { name = "%[1]s" internal = false - security_groups = ["${aws_security_group.alb_test.id}"] - subnets = ["${aws_subnet.alb_test.0.id}", "${aws_subnet.alb_test.1.id}"] + security_groups = [aws_security_group.alb_test.id] + subnets = [aws_subnet.alb_test.0.id, aws_subnet.alb_test.1.id] idle_timeout = 30 enable_deletion_protection = false @@ -382,7 +382,7 @@ resource "aws_lb_target_group" "test" { name = "%[2]s" port = 8080 protocol = "HTTP" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id health_check { path = "/health" @@ -419,7 +419,7 @@ resource "aws_vpc" "alb_test" { } resource "aws_internet_gateway" "gw" { - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id tags = { Name = "terraform-testacc-lb-listener-data-source-https" @@ -429,10 +429,10 @@ resource "aws_internet_gateway" "gw" { resource "aws_subnet" "alb_test" { count = 2 - vpc_id = "${aws_vpc.alb_test.id}" - cidr_block = "${element(var.subnets, count.index)}" + 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)}" + availability_zone = element(data.aws_availability_zones.available.names, count.index) tags = { Name = "tf-acc-lb-listener-data-source-https" @@ -442,7 +442,7 @@ resource "aws_subnet" "alb_test" { resource "aws_security_group" "alb_test" { name = "allow_all_alb_test" description = "Used for ALB Testing" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id ingress { from_port = 0 @@ -470,12 +470,12 @@ resource "aws_iam_server_certificate" "test_cert" { } data "aws_lb_listener" "front_end" { - arn = "${aws_lb_listener.front_end.arn}" + arn = aws_lb_listener.front_end.arn } data "aws_lb_listener" "from_lb_and_port" { - load_balancer_arn = "${aws_lb.alb_test.arn}" - port = "${aws_lb_listener.front_end.port}" + load_balancer_arn = aws_lb.alb_test.arn + port = aws_lb_listener.front_end.port } `, lbName, targetGroupName, acctest.RandInt(), certificate, key) } diff --git a/aws/data_source_aws_lb_target_group.go b/aws/data_source_aws_lb_target_group.go index a9f241bd08e..0b2b94a3211 100644 --- a/aws/data_source_aws_lb_target_group.go +++ b/aws/data_source_aws_lb_target_group.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsLbTargetGroup() *schema.Resource { @@ -65,6 +65,11 @@ func dataSourceAwsLbTargetGroup() *schema.Resource { Computed: true, }, + "load_balancing_algorithm_type": { + Type: schema.TypeString, + Computed: true, + }, + "target_type": { Type: schema.TypeString, Computed: true, diff --git a/aws/data_source_aws_lb_target_group_test.go b/aws/data_source_aws_lb_target_group_test.go index 6d2bf779ae7..977eeeb998e 100644 --- a/aws/data_source_aws_lb_target_group_test.go +++ b/aws/data_source_aws_lb_target_group_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAWSALBTargetGroup_basic(t *testing.T) { @@ -26,8 +26,8 @@ func TestAccDataSourceAWSALBTargetGroup_basic(t *testing.T) { resource.TestCheckResourceAttrSet(resourceNameArn, "arn_suffix"), resource.TestCheckResourceAttr(resourceNameArn, "port", "8080"), resource.TestCheckResourceAttr(resourceNameArn, "protocol", "HTTP"), - resource.TestCheckResourceAttr(resourceNameArn, "protocol", "HTTP"), resource.TestCheckResourceAttrSet(resourceNameArn, "vpc_id"), + resource.TestCheckResourceAttrSet(resourceNameArn, "load_balancing_algorithm_type"), resource.TestCheckResourceAttr(resourceNameArn, "deregistration_delay", "300"), resource.TestCheckResourceAttr(resourceNameArn, "slow_start", "0"), resource.TestCheckResourceAttr(resourceNameArn, "tags.%", "1"), @@ -47,6 +47,7 @@ func TestAccDataSourceAWSALBTargetGroup_basic(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "arn_suffix"), resource.TestCheckResourceAttr(resourceName, "port", "8080"), resource.TestCheckResourceAttr(resourceName, "protocol", "HTTP"), + resource.TestCheckResourceAttrSet(resourceName, "load_balancing_algorithm_type"), resource.TestCheckResourceAttrSet(resourceName, "vpc_id"), resource.TestCheckResourceAttr(resourceName, "deregistration_delay", "300"), resource.TestCheckResourceAttr(resourceName, "slow_start", "0"), @@ -67,7 +68,7 @@ func TestAccDataSourceAWSALBTargetGroup_basic(t *testing.T) { }) } -func TestAccDataSourceAWSLBTargetGroupBackwardsCompatibility(t *testing.T) { +func TestAccDataSourceAWSLBTargetGroup_BackwardsCompatibility(t *testing.T) { lbName := fmt.Sprintf("testlb-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) resourceNameArn := "data.aws_alb_target_group.alb_tg_test_with_arn" @@ -129,12 +130,12 @@ func TestAccDataSourceAWSLBTargetGroupBackwardsCompatibility(t *testing.T) { func testAccDataSourceAWSLBTargetGroupConfigBasic(lbName string, targetGroupName string) string { return fmt.Sprintf(` resource "aws_lb_listener" "front_end" { - load_balancer_arn = "${aws_lb.alb_test.id}" + load_balancer_arn = aws_lb.alb_test.id protocol = "HTTP" port = "80" default_action { - target_group_arn = "${aws_lb_target_group.test.id}" + target_group_arn = aws_lb_target_group.test.id type = "forward" } } @@ -142,8 +143,8 @@ resource "aws_lb_listener" "front_end" { resource "aws_lb" "alb_test" { name = "%s" internal = true - security_groups = ["${aws_security_group.alb_test.id}"] - subnets = ["${aws_subnet.alb_test.0.id}", "${aws_subnet.alb_test.1.id}"] + security_groups = [aws_security_group.alb_test.id] + subnets = [aws_subnet.alb_test.0.id, aws_subnet.alb_test.1.id] idle_timeout = 30 enable_deletion_protection = false @@ -157,7 +158,7 @@ resource "aws_lb_target_group" "test" { name = "%s" port = 8080 protocol = "HTTP" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id health_check { path = "/health" @@ -199,10 +200,10 @@ resource "aws_vpc" "alb_test" { resource "aws_subnet" "alb_test" { count = 2 - vpc_id = "${aws_vpc.alb_test.id}" - cidr_block = "${element(var.subnets, count.index)}" + 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)}" + availability_zone = element(data.aws_availability_zones.available.names, count.index) tags = { Name = "tf-acc-lb-data-source-target-group-basic" @@ -212,7 +213,7 @@ resource "aws_subnet" "alb_test" { resource "aws_security_group" "alb_test" { name = "allow_all_alb_test" description = "Used for ALB Testing" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id ingress { from_port = 0 @@ -234,11 +235,11 @@ resource "aws_security_group" "alb_test" { } data "aws_lb_target_group" "alb_tg_test_with_arn" { - arn = "${aws_lb_target_group.test.arn}" + arn = aws_lb_target_group.test.arn } data "aws_lb_target_group" "alb_tg_test_with_name" { - name = "${aws_lb_target_group.test.name}" + name = aws_lb_target_group.test.name } `, lbName, targetGroupName) } @@ -246,12 +247,12 @@ data "aws_lb_target_group" "alb_tg_test_with_name" { func testAccDataSourceAWSLBTargetGroupConfigBackwardsCompatibility(lbName string, targetGroupName string) string { return fmt.Sprintf(` resource "aws_alb_listener" "front_end" { - load_balancer_arn = "${aws_alb.alb_test.id}" + load_balancer_arn = aws_alb.alb_test.id protocol = "HTTP" port = "80" default_action { - target_group_arn = "${aws_alb_target_group.test.id}" + target_group_arn = aws_alb_target_group.test.id type = "forward" } } @@ -259,8 +260,8 @@ resource "aws_alb_listener" "front_end" { resource "aws_alb" "alb_test" { name = "%s" internal = true - security_groups = ["${aws_security_group.alb_test.id}"] - subnets = ["${aws_subnet.alb_test.0.id}", "${aws_subnet.alb_test.1.id}"] + security_groups = [aws_security_group.alb_test.id] + subnets = [aws_subnet.alb_test.0.id, aws_subnet.alb_test.1.id] idle_timeout = 30 enable_deletion_protection = false @@ -274,7 +275,7 @@ resource "aws_alb_target_group" "test" { name = "%s" port = 8080 protocol = "HTTP" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id health_check { path = "/health" @@ -316,10 +317,10 @@ resource "aws_vpc" "alb_test" { resource "aws_subnet" "alb_test" { count = 2 - vpc_id = "${aws_vpc.alb_test.id}" - cidr_block = "${element(var.subnets, count.index)}" + 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)}" + availability_zone = element(data.aws_availability_zones.available.names, count.index) tags = { Name = "tf-acc-lb-data-source-target-group-bc" @@ -329,7 +330,7 @@ resource "aws_subnet" "alb_test" { resource "aws_security_group" "alb_test" { name = "allow_all_alb_test" description = "Used for ALB Testing" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id ingress { from_port = 0 @@ -351,11 +352,11 @@ resource "aws_security_group" "alb_test" { } data "aws_alb_target_group" "alb_tg_test_with_arn" { - arn = "${aws_alb_target_group.test.arn}" + arn = aws_alb_target_group.test.arn } data "aws_alb_target_group" "alb_tg_test_with_name" { - name = "${aws_alb_target_group.test.name}" + name = aws_alb_target_group.test.name } `, lbName, targetGroupName) } diff --git a/aws/data_source_aws_lb_test.go b/aws/data_source_aws_lb_test.go index b1cd11e1184..3ebfcc1d473 100644 --- a/aws/data_source_aws_lb_test.go +++ b/aws/data_source_aws_lb_test.go @@ -4,14 +4,15 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAWSLB_basic(t *testing.T) { lbName := fmt.Sprintf("testaccawslb-basic-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) dataSourceName := "data.aws_lb.alb_test_with_arn" dataSourceName2 := "data.aws_lb.alb_test_with_name" + resourceName := "aws_lb.alb_test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -20,40 +21,46 @@ func TestAccDataSourceAWSLB_basic(t *testing.T) { { Config: testAccDataSourceAWSLBConfigBasic(lbName), Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr(dataSourceName, "name", lbName), - resource.TestCheckResourceAttr(dataSourceName, "internal", "true"), - resource.TestCheckResourceAttr(dataSourceName, "subnets.#", "2"), - resource.TestCheckResourceAttr(dataSourceName, "security_groups.#", "1"), - resource.TestCheckResourceAttr(dataSourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(dataSourceName, "tags.TestName", "TestAccAWSALB_basic"), - resource.TestCheckResourceAttr(dataSourceName, "enable_deletion_protection", "false"), - resource.TestCheckResourceAttr(dataSourceName, "idle_timeout", "30"), - resource.TestCheckResourceAttrSet(dataSourceName, "vpc_id"), - resource.TestCheckResourceAttrSet(dataSourceName, "zone_id"), - resource.TestCheckResourceAttrSet(dataSourceName, "dns_name"), - resource.TestCheckResourceAttrSet(dataSourceName, "arn"), - resource.TestCheckResourceAttr(dataSourceName2, "name", lbName), - resource.TestCheckResourceAttr(dataSourceName2, "internal", "true"), - resource.TestCheckResourceAttr(dataSourceName2, "subnets.#", "2"), - resource.TestCheckResourceAttr(dataSourceName2, "security_groups.#", "1"), - resource.TestCheckResourceAttr(dataSourceName2, "tags.%", "1"), - resource.TestCheckResourceAttr(dataSourceName2, "tags.TestName", "TestAccAWSALB_basic"), - resource.TestCheckResourceAttr(dataSourceName2, "enable_deletion_protection", "false"), - resource.TestCheckResourceAttr(dataSourceName2, "idle_timeout", "30"), - resource.TestCheckResourceAttrSet(dataSourceName2, "vpc_id"), - resource.TestCheckResourceAttrSet(dataSourceName2, "zone_id"), - resource.TestCheckResourceAttrSet(dataSourceName2, "dns_name"), - resource.TestCheckResourceAttrSet(dataSourceName2, "arn"), + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(dataSourceName, "internal", resourceName, "internal"), + resource.TestCheckResourceAttrPair(dataSourceName, "subnets.#", resourceName, "subnets.#"), + resource.TestCheckResourceAttrPair(dataSourceName, "security_groups.#", resourceName, "security_groups.#"), + resource.TestCheckResourceAttrPair(dataSourceName, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(dataSourceName, "tags.TestName", resourceName, "tags.TestName"), + resource.TestCheckResourceAttrPair(dataSourceName, "enable_deletion_protection", resourceName, "enable_deletion_protection"), + resource.TestCheckResourceAttrPair(dataSourceName, "idle_timeout", resourceName, "idle_timeout"), + resource.TestCheckResourceAttrPair(dataSourceName, "vpc_id", resourceName, "vpc_id"), + resource.TestCheckResourceAttrPair(dataSourceName, "zone_id", resourceName, "zone_id"), + resource.TestCheckResourceAttrPair(dataSourceName, "dns_name", resourceName, "dns_name"), + resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(dataSourceName, "ip_address_type", resourceName, "ip_address_type"), + resource.TestCheckResourceAttrPair(dataSourceName, "subnet_mapping.#", resourceName, "subnet_mapping.#"), + resource.TestCheckResourceAttrPair(dataSourceName2, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(dataSourceName2, "internal", resourceName, "internal"), + resource.TestCheckResourceAttrPair(dataSourceName2, "subnets.#", resourceName, "subnets.#"), + resource.TestCheckResourceAttrPair(dataSourceName2, "security_groups.#", resourceName, "security_groups.#"), + resource.TestCheckResourceAttrPair(dataSourceName2, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(dataSourceName2, "tags.TestName", resourceName, "tags.TestName"), + resource.TestCheckResourceAttrPair(dataSourceName2, "enable_deletion_protection", resourceName, "enable_deletion_protection"), + resource.TestCheckResourceAttrPair(dataSourceName2, "idle_timeout", resourceName, "idle_timeout"), + resource.TestCheckResourceAttrPair(dataSourceName2, "vpc_id", resourceName, "vpc_id"), + resource.TestCheckResourceAttrPair(dataSourceName2, "zone_id", resourceName, "zone_id"), + resource.TestCheckResourceAttrPair(dataSourceName2, "dns_name", resourceName, "dns_name"), + resource.TestCheckResourceAttrPair(dataSourceName2, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(dataSourceName2, "ip_address_type", resourceName, "ip_address_type"), + resource.TestCheckResourceAttrPair(dataSourceName2, "subnet_mapping.#", resourceName, "subnet_mapping.#"), ), }, }, }) } -func TestAccDataSourceAWSLBBackwardsCompatibility(t *testing.T) { +func TestAccDataSourceAWSLB_BackwardsCompatibility(t *testing.T) { lbName := fmt.Sprintf("testaccawsalb-basic-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) dataSourceName1 := "data.aws_alb.alb_test_with_arn" dataSourceName2 := "data.aws_alb.alb_test_with_name" + resourceName := "aws_alb.alb_test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -61,30 +68,40 @@ func TestAccDataSourceAWSLBBackwardsCompatibility(t *testing.T) { { Config: testAccDataSourceAWSLBConfigBackardsCompatibility(lbName), Check: resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr(dataSourceName1, "name", lbName), - resource.TestCheckResourceAttr(dataSourceName1, "internal", "true"), - resource.TestCheckResourceAttr(dataSourceName1, "subnets.#", "2"), - resource.TestCheckResourceAttr(dataSourceName1, "security_groups.#", "1"), - resource.TestCheckResourceAttr(dataSourceName1, "tags.%", "1"), - resource.TestCheckResourceAttr(dataSourceName1, "tags.TestName", "TestAccAWSALB_basic"), - resource.TestCheckResourceAttr(dataSourceName1, "enable_deletion_protection", "false"), - resource.TestCheckResourceAttr(dataSourceName1, "idle_timeout", "30"), - resource.TestCheckResourceAttrSet(dataSourceName1, "vpc_id"), - resource.TestCheckResourceAttrSet(dataSourceName1, "zone_id"), - resource.TestCheckResourceAttrSet(dataSourceName1, "dns_name"), - resource.TestCheckResourceAttrSet(dataSourceName1, "arn"), - resource.TestCheckResourceAttr(dataSourceName2, "name", lbName), - resource.TestCheckResourceAttr(dataSourceName2, "internal", "true"), - resource.TestCheckResourceAttr(dataSourceName2, "subnets.#", "2"), - resource.TestCheckResourceAttr(dataSourceName2, "security_groups.#", "1"), - resource.TestCheckResourceAttr(dataSourceName2, "tags.%", "1"), - resource.TestCheckResourceAttr(dataSourceName2, "tags.TestName", "TestAccAWSALB_basic"), - resource.TestCheckResourceAttr(dataSourceName2, "enable_deletion_protection", "false"), - resource.TestCheckResourceAttr(dataSourceName2, "idle_timeout", "30"), - resource.TestCheckResourceAttrSet(dataSourceName2, "vpc_id"), - resource.TestCheckResourceAttrSet(dataSourceName2, "zone_id"), - resource.TestCheckResourceAttrSet(dataSourceName2, "dns_name"), - resource.TestCheckResourceAttrSet(dataSourceName2, "arn"), + resource.TestCheckResourceAttrPair(dataSourceName1, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(dataSourceName1, "internal", resourceName, "internal"), + resource.TestCheckResourceAttrPair(dataSourceName1, "subnets.#", resourceName, "subnets.#"), + resource.TestCheckResourceAttrPair(dataSourceName1, "security_groups.#", resourceName, "security_groups.#"), + resource.TestCheckResourceAttrPair(dataSourceName1, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(dataSourceName1, "tags.TestName", resourceName, "tags.TestName"), + resource.TestCheckResourceAttrPair(dataSourceName1, "enable_deletion_protection", resourceName, "enable_deletion_protection"), + resource.TestCheckResourceAttrPair(dataSourceName1, "idle_timeout", resourceName, "idle_timeout"), + resource.TestCheckResourceAttrPair(dataSourceName1, "vpc_id", resourceName, "vpc_id"), + resource.TestCheckResourceAttrPair(dataSourceName1, "zone_id", resourceName, "zone_id"), + resource.TestCheckResourceAttrPair(dataSourceName1, "dns_name", resourceName, "dns_name"), + resource.TestCheckResourceAttrPair(dataSourceName1, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(dataSourceName1, "ip_address_type", resourceName, "ip_address_type"), + resource.TestCheckResourceAttrPair(dataSourceName1, "subnet_mapping.#", resourceName, "subnet_mapping.#"), + resource.TestCheckResourceAttrPair(dataSourceName1, "drop_invalid_header_fields", resourceName, "drop_invalid_header_fields"), + resource.TestCheckResourceAttrPair(dataSourceName1, "enable_http2", resourceName, "enable_http2"), + resource.TestCheckResourceAttrPair(dataSourceName1, "access_logs.#", resourceName, "access_logs.#"), + resource.TestCheckResourceAttrPair(dataSourceName2, "name", resourceName, "name"), + resource.TestCheckResourceAttrPair(dataSourceName2, "internal", resourceName, "internal"), + resource.TestCheckResourceAttrPair(dataSourceName2, "subnets.#", resourceName, "subnets.#"), + resource.TestCheckResourceAttrPair(dataSourceName2, "security_groups.#", resourceName, "security_groups.#"), + resource.TestCheckResourceAttrPair(dataSourceName2, "tags.%", resourceName, "tags.%"), + resource.TestCheckResourceAttrPair(dataSourceName2, "tags.TestName", resourceName, "tags.TestName"), + resource.TestCheckResourceAttrPair(dataSourceName2, "enable_deletion_protection", resourceName, "enable_deletion_protection"), + resource.TestCheckResourceAttrPair(dataSourceName2, "idle_timeout", resourceName, "idle_timeout"), + resource.TestCheckResourceAttrPair(dataSourceName2, "vpc_id", resourceName, "vpc_id"), + resource.TestCheckResourceAttrPair(dataSourceName2, "zone_id", resourceName, "zone_id"), + resource.TestCheckResourceAttrPair(dataSourceName2, "dns_name", resourceName, "dns_name"), + resource.TestCheckResourceAttrPair(dataSourceName2, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(dataSourceName2, "ip_address_type", resourceName, "ip_address_type"), + resource.TestCheckResourceAttrPair(dataSourceName2, "subnet_mapping.#", resourceName, "subnet_mapping.#"), + resource.TestCheckResourceAttrPair(dataSourceName1, "drop_invalid_header_fields", resourceName, "drop_invalid_header_fields"), + resource.TestCheckResourceAttrPair(dataSourceName1, "enable_http2", resourceName, "enable_http2"), + resource.TestCheckResourceAttrPair(dataSourceName1, "access_logs.#", resourceName, "access_logs.#"), ), }, }, @@ -96,8 +113,8 @@ func testAccDataSourceAWSLBConfigBasic(lbName string) string { resource "aws_lb" "alb_test" { name = "%s" internal = true - security_groups = ["${aws_security_group.alb_test.id}"] - subnets = ["${aws_subnet.alb_test.0.id}", "${aws_subnet.alb_test.1.id}"] + security_groups = [aws_security_group.alb_test.id] + subnets = [aws_subnet.alb_test.0.id, aws_subnet.alb_test.1.id] idle_timeout = 30 enable_deletion_protection = false @@ -131,10 +148,10 @@ resource "aws_vpc" "alb_test" { resource "aws_subnet" "alb_test" { count = 2 - vpc_id = "${aws_vpc.alb_test.id}" - cidr_block = "${element(var.subnets, count.index)}" + 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)}" + availability_zone = element(data.aws_availability_zones.available.names, count.index) tags = { Name = "tf-acc-lb-data-source-basic" @@ -144,7 +161,7 @@ resource "aws_subnet" "alb_test" { resource "aws_security_group" "alb_test" { name = "allow_all_alb_test" description = "Used for ALB Testing" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id ingress { from_port = 0 @@ -166,11 +183,11 @@ resource "aws_security_group" "alb_test" { } data "aws_lb" "alb_test_with_arn" { - arn = "${aws_lb.alb_test.arn}" + arn = aws_lb.alb_test.arn } data "aws_lb" "alb_test_with_name" { - name = "${aws_lb.alb_test.name}" + name = aws_lb.alb_test.name } `, lbName) } @@ -180,8 +197,8 @@ func testAccDataSourceAWSLBConfigBackardsCompatibility(albName string) string { resource "aws_alb" "alb_test" { name = "%s" internal = true - security_groups = ["${aws_security_group.alb_test.id}"] - subnets = ["${aws_subnet.alb_test.0.id}", "${aws_subnet.alb_test.1.id}"] + security_groups = [aws_security_group.alb_test.id] + subnets = [aws_subnet.alb_test.0.id, aws_subnet.alb_test.1.id] idle_timeout = 30 enable_deletion_protection = false @@ -215,10 +232,10 @@ resource "aws_vpc" "alb_test" { resource "aws_subnet" "alb_test" { count = 2 - vpc_id = "${aws_vpc.alb_test.id}" - cidr_block = "${element(var.subnets, count.index)}" + 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)}" + availability_zone = element(data.aws_availability_zones.available.names, count.index) tags = { Name = "tf-acc-lb-data-source-bc" @@ -228,7 +245,7 @@ resource "aws_subnet" "alb_test" { resource "aws_security_group" "alb_test" { name = "allow_all_alb_test" description = "Used for ALB Testing" - vpc_id = "${aws_vpc.alb_test.id}" + vpc_id = aws_vpc.alb_test.id ingress { from_port = 0 @@ -250,11 +267,11 @@ resource "aws_security_group" "alb_test" { } data "aws_alb" "alb_test_with_arn" { - arn = "${aws_alb.alb_test.arn}" + arn = aws_alb.alb_test.arn } data "aws_alb" "alb_test_with_name" { - name = "${aws_alb.alb_test.name}" + name = aws_alb.alb_test.name } `, albName) } diff --git a/aws/data_source_aws_mq_broker.go b/aws/data_source_aws_mq_broker.go index af80a8403d8..5edbe7bce30 100644 --- a/aws/data_source_aws_mq_broker.go +++ b/aws/data_source_aws_mq_broker.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mq" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsMqBroker() *schema.Resource { diff --git a/aws/data_source_aws_mq_broker_test.go b/aws/data_source_aws_mq_broker_test.go index 88ceaedd433..10f8b6a5dd1 100644 --- a/aws/data_source_aws_mq_broker_test.go +++ b/aws/data_source_aws_mq_broker_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAWSMqBroker_basic(t *testing.T) { @@ -110,48 +110,48 @@ resource "aws_vpc" "acctest" { cidr_block = "10.0.0.0/16" tags = { - Name = "${var.prefix}" + Name = var.prefix } } resource "aws_internet_gateway" "acctest" { - vpc_id = "${aws_vpc.acctest.id}" + vpc_id = aws_vpc.acctest.id } resource "aws_route_table" "acctest" { - vpc_id = "${aws_vpc.acctest.id}" + vpc_id = aws_vpc.acctest.id route { cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.acctest.id}" + gateway_id = aws_internet_gateway.acctest.id } } resource "aws_subnet" "acctest" { count = 2 cidr_block = "10.0.${count.index}.0/24" - availability_zone = "${data.aws_availability_zones.available.names[count.index]}" - vpc_id = "${aws_vpc.acctest.id}" + availability_zone = data.aws_availability_zones.available.names[count.index] + vpc_id = aws_vpc.acctest.id tags = { - Name = "${var.prefix}" + Name = var.prefix } } resource "aws_route_table_association" "acctest" { count = 2 - subnet_id = "${aws_subnet.acctest.*.id[count.index]}" - route_table_id = "${aws_route_table.acctest.id}" + subnet_id = aws_subnet.acctest.*.id[count.index] + route_table_id = aws_route_table.acctest.id } resource "aws_security_group" "acctest" { count = 2 name = "${var.prefix}-${count.index}" - vpc_id = "${aws_vpc.acctest.id}" + vpc_id = aws_vpc.acctest.id } resource "aws_mq_configuration" "acctest" { - name = "${var.prefix}" + name = var.prefix engine_type = "ActiveMQ" engine_version = "5.15.0" @@ -168,8 +168,8 @@ resource "aws_mq_broker" "acctest" { broker_name = "%s" configuration { - id = "${aws_mq_configuration.acctest.id}" - revision = "${aws_mq_configuration.acctest.latest_revision}" + id = aws_mq_configuration.acctest.id + revision = aws_mq_configuration.acctest.latest_revision } deployment_mode = "ACTIVE_STANDBY_MULTI_AZ" @@ -184,8 +184,8 @@ resource "aws_mq_broker" "acctest" { } publicly_accessible = true - security_groups = ["${aws_security_group.acctest.0.id}", "${aws_security_group.acctest.1.id}"] - subnet_ids = ["${aws_subnet.acctest.0.id}", "${aws_subnet.acctest.1.id}"] + security_groups = [aws_security_group.acctest.0.id, aws_security_group.acctest.1.id] + subnet_ids = [aws_subnet.acctest.0.id, aws_subnet.acctest.1.id] user { username = "Ender" @@ -205,16 +205,17 @@ resource "aws_mq_broker" "acctest" { } func testAccDataSourceAWSMqBrokerConfig_byId(brokerName, prefix string) string { - return testAccDataSourceAWSMqBrokerConfig_base(brokerName, prefix) + fmt.Sprintf(` + return testAccDataSourceAWSMqBrokerConfig_base(brokerName, prefix) + ` data "aws_mq_broker" "by_id" { - broker_id = "${aws_mq_broker.acctest.id}" + broker_id = aws_mq_broker.acctest.id } -`) +` } func testAccDataSourceAWSMqBrokerConfig_byName(brokerName, prefix string) string { - return testAccDataSourceAWSMqBrokerConfig_base(brokerName, prefix) + fmt.Sprintf(` + return testAccDataSourceAWSMqBrokerConfig_base(brokerName, prefix) + ` data "aws_mq_broker" "by_name" { - broker_name = "${aws_mq_broker.acctest.broker_name}" -}`) + broker_name = aws_mq_broker.acctest.broker_name +} +` } diff --git a/aws/data_source_aws_msk_cluster.go b/aws/data_source_aws_msk_cluster.go index 00f2d18f03e..7797f0a39f9 100644 --- a/aws/data_source_aws_msk_cluster.go +++ b/aws/data_source_aws_msk_cluster.go @@ -5,8 +5,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kafka" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_msk_cluster_test.go b/aws/data_source_aws_msk_cluster_test.go index 738a495ab5a..5659d058c60 100644 --- a/aws/data_source_aws_msk_cluster_test.go +++ b/aws/data_source_aws_msk_cluster_test.go @@ -2,10 +2,11 @@ package aws import ( "fmt" + "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSMskClusterDataSource_Name(t *testing.T) { @@ -22,8 +23,8 @@ func TestAccAWSMskClusterDataSource_Name(t *testing.T) { Config: testAccMskClusterDataSourceConfigName(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(resourceName, "arn", dataSourceName, "arn"), - resource.TestCheckResourceAttrSet(dataSourceName, "bootstrap_brokers"), - resource.TestCheckResourceAttrSet(dataSourceName, "bootstrap_brokers_tls"), + resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), + resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", regexp.MustCompile(`^(([-\w]+\.){1,}[\w]+:\d+,){2,}([-\w]+\.){1,}[\w]+:\d+$`)), // Hostname ordering not guaranteed between resource and data source reads resource.TestCheckResourceAttrPair(resourceName, "cluster_name", dataSourceName, "cluster_name"), resource.TestCheckResourceAttrPair(resourceName, "kafka_version", dataSourceName, "kafka_version"), resource.TestCheckResourceAttrPair(resourceName, "number_of_broker_nodes", dataSourceName, "number_of_broker_nodes"), @@ -43,10 +44,10 @@ resource "aws_msk_cluster" "test" { number_of_broker_nodes = 3 broker_node_group_info { - client_subnets = ["${aws_subnet.example_subnet_az1.id}", "${aws_subnet.example_subnet_az2.id}", "${aws_subnet.example_subnet_az3.id}"] + client_subnets = [aws_subnet.example_subnet_az1.id, aws_subnet.example_subnet_az2.id, aws_subnet.example_subnet_az3.id] ebs_volume_size = 10 instance_type = "kafka.m5.large" - security_groups = ["${aws_security_group.example_sg.id}"] + security_groups = [aws_security_group.example_sg.id] } tags = { @@ -55,7 +56,7 @@ resource "aws_msk_cluster" "test" { } data "aws_msk_cluster" "test" { - cluster_name = "${aws_msk_cluster.test.cluster_name}" + cluster_name = aws_msk_cluster.test.cluster_name } `, rName) } diff --git a/aws/data_source_aws_msk_configuration.go b/aws/data_source_aws_msk_configuration.go index 2449b96a76e..fbcae200968 100644 --- a/aws/data_source_aws_msk_configuration.go +++ b/aws/data_source_aws_msk_configuration.go @@ -5,8 +5,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kafka" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func dataSourceAwsMskConfiguration() *schema.Resource { diff --git a/aws/data_source_aws_msk_configuration_test.go b/aws/data_source_aws_msk_configuration_test.go index c0c704ee9d4..7211f6ea51f 100644 --- a/aws/data_source_aws_msk_configuration_test.go +++ b/aws/data_source_aws_msk_configuration_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSMskConfigurationDataSource_Name(t *testing.T) { @@ -46,7 +46,7 @@ PROPERTIES } data "aws_msk_configuration" "test" { - name = "${aws_msk_configuration.test.name}" + name = aws_msk_configuration.test.name } `, rName) } diff --git a/aws/data_source_aws_nat_gateway.go b/aws/data_source_aws_nat_gateway.go index 1f3f57a753a..f2431ea4d20 100644 --- a/aws/data_source_aws_nat_gateway.go +++ b/aws/data_source_aws_nat_gateway.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_nat_gateway_test.go b/aws/data_source_aws_nat_gateway_test.go index d98e1c74b62..d5237aa760f 100644 --- a/aws/data_source_aws_nat_gateway_test.go +++ b/aws/data_source_aws_nat_gateway_test.go @@ -4,11 +4,11 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccDataSourceAwsNatGateway(t *testing.T) { +func TestAccDataSourceAwsNatGateway_basic(t *testing.T) { // This is used as a portion of CIDR network addresses. rInt := acctest.RandIntRange(4, 254) @@ -52,7 +52,7 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id cidr_block = "172.%d.123.0/24" availability_zone = "us-west-2a" @@ -68,7 +68,7 @@ resource "aws_eip" "test" { # IGWs are required for an NGW to spin up; manual dependency resource "aws_internet_gateway" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "terraform-testacc-nat-gateway-data-source-%d" @@ -76,8 +76,8 @@ resource "aws_internet_gateway" "test" { } resource "aws_nat_gateway" "test" { - subnet_id = "${aws_subnet.test.id}" - allocation_id = "${aws_eip.test.id}" + subnet_id = aws_subnet.test.id + allocation_id = aws_eip.test.id tags = { Name = "terraform-testacc-nat-gw-data-source-%d" @@ -88,16 +88,16 @@ resource "aws_nat_gateway" "test" { } data "aws_nat_gateway" "test_by_id" { - id = "${aws_nat_gateway.test.id}" + id = aws_nat_gateway.test.id } data "aws_nat_gateway" "test_by_subnet_id" { - subnet_id = "${aws_nat_gateway.test.subnet_id}" + subnet_id = aws_nat_gateway.test.subnet_id } data "aws_nat_gateway" "test_by_tags" { tags = { - Name = "${aws_nat_gateway.test.tags["Name"]}" + Name = aws_nat_gateway.test.tags["Name"] } } `, rInt, rInt, rInt, rInt) diff --git a/aws/data_source_aws_network_acls.go b/aws/data_source_aws_network_acls.go index c919d67221c..deb928e7454 100644 --- a/aws/data_source_aws_network_acls.go +++ b/aws/data_source_aws_network_acls.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_network_acls_test.go b/aws/data_source_aws_network_acls_test.go index d14f511283d..9821800de24 100644 --- a/aws/data_source_aws_network_acls_test.go +++ b/aws/data_source_aws_network_acls_test.go @@ -5,8 +5,8 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAwsNetworkAcls_basic(t *testing.T) { @@ -96,7 +96,7 @@ resource "aws_vpc" "test" { resource "aws_network_acl" "acl" { count = 2 - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "testacc-acl-%s" @@ -116,7 +116,7 @@ func testAccDataSourceAwsNetworkAclsConfig_Filter(rName string) string { data "aws_network_acls" "test" { filter { name = "network-acl-id" - values = ["${aws_network_acl.acl.0.id}"] + values = [aws_network_acl.acl.0.id] } } ` @@ -126,7 +126,7 @@ func testAccDataSourceAwsNetworkAclsConfig_Tags(rName string) string { return testAccDataSourceAwsNetworkAclsConfig_Base(rName) + ` data "aws_network_acls" "test" { tags = { - Name = "${aws_network_acl.acl.0.tags.Name}" + Name = aws_network_acl.acl.0.tags.Name } } ` @@ -135,7 +135,7 @@ data "aws_network_acls" "test" { func testAccDataSourceAwsNetworkAclsConfig_VpcID(rName string) string { return testAccDataSourceAwsNetworkAclsConfig_Base(rName) + ` data "aws_network_acls" "test" { - vpc_id = "${aws_network_acl.acl.0.vpc_id}" + vpc_id = aws_network_acl.acl.0.vpc_id } ` } diff --git a/aws/data_source_aws_network_interface.go b/aws/data_source_aws_network_interface.go index bc3a6fa1be4..739f820966f 100644 --- a/aws/data_source_aws_network_interface.go +++ b/aws/data_source_aws_network_interface.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_network_interface_test.go b/aws/data_source_aws_network_interface_test.go index 4de239c7253..1822ef1c669 100644 --- a/aws/data_source_aws_network_interface_test.go +++ b/aws/data_source_aws_network_interface_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAwsNetworkInterface_basic(t *testing.T) { @@ -54,8 +54,8 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.0.0.0/24" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - vpc_id = "${aws_vpc.test.id}" + availability_zone = data.aws_availability_zones.available.names[0] + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-eni-data-source-basic" @@ -64,17 +64,17 @@ resource "aws_subnet" "test" { resource "aws_security_group" "test" { name = "tf-sg-%s" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } resource "aws_network_interface" "test" { - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id private_ips = ["10.0.0.50"] - security_groups = ["${aws_security_group.test.id}"] + security_groups = [aws_security_group.test.id] } data "aws_network_interface" "test" { - id = "${aws_network_interface.test.id}" + id = aws_network_interface.test.id } `, rName) } @@ -117,8 +117,8 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.0.0.0/24" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - vpc_id = "${aws_vpc.test.id}" + availability_zone = data.aws_availability_zones.available.names[0] + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-eni-data-source-filters" @@ -127,19 +127,19 @@ resource "aws_subnet" "test" { resource "aws_security_group" "test" { name = "tf-sg-%s" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } resource "aws_network_interface" "test" { - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id private_ips = ["10.0.0.60"] - security_groups = ["${aws_security_group.test.id}"] + security_groups = [aws_security_group.test.id] } data "aws_network_interface" "test" { filter { name = "network-interface-id" - values = ["${aws_network_interface.test.id}"] + values = [aws_network_interface.test.id] } } `, rName) diff --git a/aws/data_source_aws_network_interfaces.go b/aws/data_source_aws_network_interfaces.go index 228c1fb04b2..13eb917302b 100644 --- a/aws/data_source_aws_network_interfaces.go +++ b/aws/data_source_aws_network_interfaces.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_network_interfaces_test.go b/aws/data_source_aws_network_interfaces_test.go index 431d38c16ba..d1341e75d28 100644 --- a/aws/data_source_aws_network_interfaces_test.go +++ b/aws/data_source_aws_network_interfaces_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAwsNetworkInterfaces_Filter(t *testing.T) { @@ -54,7 +54,7 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "terraform-testacc-eni-data-source-basic-%s" @@ -62,14 +62,14 @@ resource "aws_subnet" "test" { } resource "aws_network_interface" "test" { - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } resource "aws_network_interface" "test1" { - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id tags = { - Name = "${aws_vpc.test.tags.Name}" + Name = aws_vpc.test.tags.Name } } `, rName, rName) @@ -80,7 +80,7 @@ func testAccDataSourceAwsNetworkInterfacesConfig_Filter(rName string) string { data "aws_network_interfaces" "test" { filter { name = "subnet-id" - values = ["${aws_network_interface.test.subnet_id}", "${aws_network_interface.test1.subnet_id}"] + values = [aws_network_interface.test.subnet_id, aws_network_interface.test1.subnet_id] } } ` @@ -90,7 +90,7 @@ func testAccDataSourceAwsNetworkInterfacesConfig_Tags(rName string) string { return testAccDataSourceAwsNetworkInterfacesConfig_Base(rName) + ` data "aws_network_interfaces" "test" { tags = { - Name = "${aws_network_interface.test1.tags.Name}" + Name = aws_network_interface.test1.tags.Name } } ` diff --git a/aws/data_source_aws_organizations_organization.go b/aws/data_source_aws_organizations_organization.go index 5dbff772acb..7d32e078681 100644 --- a/aws/data_source_aws_organizations_organization.go +++ b/aws/data_source_aws_organizations_organization.go @@ -5,7 +5,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsOrganizationsOrganization() *schema.Resource { diff --git a/aws/data_source_aws_organizations_organization_test.go b/aws/data_source_aws_organizations_organization_test.go index 597c3381887..ee6258b56a9 100644 --- a/aws/data_source_aws_organizations_organization_test.go +++ b/aws/data_source_aws_organizations_organization_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func testAccDataSourceAwsOrganizationsOrganization_basic(t *testing.T) { diff --git a/aws/data_source_aws_organizations_organizational_units.go b/aws/data_source_aws_organizations_organizational_units.go index 4c8f2426b41..08d49df5674 100644 --- a/aws/data_source_aws_organizations_organizational_units.go +++ b/aws/data_source_aws_organizations_organizational_units.go @@ -5,8 +5,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsOrganizationsOrganizationalUnits() *schema.Resource { diff --git a/aws/data_source_aws_organizations_organizational_units_test.go b/aws/data_source_aws_organizations_organizational_units_test.go index 8d5b789b515..9301852dcb8 100644 --- a/aws/data_source_aws_organizations_organizational_units_test.go +++ b/aws/data_source_aws_organizations_organizational_units_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func testAccDataSourceAwsOrganizationsOrganizationalUnits_basic(t *testing.T) { @@ -33,11 +33,11 @@ const testAccDataSourceAwsOrganizationsOrganizationalUnitsConfig = ` resource "aws_organizations_organization" "test" {} resource "aws_organizations_organizational_unit" "test" { - name = "test" - parent_id = aws_organizations_organization.test.roots[0].id + name = "test" + parent_id = aws_organizations_organization.test.roots[0].id } data "aws_organizations_organizational_units" "test" { - parent_id = aws_organizations_organizational_unit.test.parent_id + parent_id = aws_organizations_organizational_unit.test.parent_id } ` diff --git a/aws/data_source_aws_outposts_outpost.go b/aws/data_source_aws_outposts_outpost.go new file mode 100644 index 00000000000..c4a1a9eefaa --- /dev/null +++ b/aws/data_source_aws_outposts_outpost.go @@ -0,0 +1,109 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceAwsOutpostsOutpost() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsOutpostsOutpostRead, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "availability_zone": { + Type: schema.TypeString, + Computed: true, + }, + "availability_zone_id": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "owner_id": { + Type: schema.TypeString, + Computed: true, + }, + "site_id": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceAwsOutpostsOutpostRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).outpostsconn + + input := &outposts.ListOutpostsInput{} + + var results []*outposts.Outpost + + err := conn.ListOutpostsPages(input, func(page *outposts.ListOutpostsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, outpost := range page.Outposts { + if outpost == nil { + continue + } + + if v, ok := d.GetOk("id"); ok && v.(string) != aws.StringValue(outpost.OutpostId) { + continue + } + + if v, ok := d.GetOk("name"); ok && v.(string) != aws.StringValue(outpost.Name) { + continue + } + + results = append(results, outpost) + } + + return !lastPage + }) + + if err != nil { + return fmt.Errorf("error listing Outposts Outposts: %w", err) + } + + if len(results) == 0 { + return fmt.Errorf("no Outposts Outpost found matching criteria; try different search") + } + + if len(results) > 1 { + return fmt.Errorf("multiple Outposts Outpost found matching criteria; try different search") + } + + outpost := results[0] + + d.SetId(aws.StringValue(outpost.OutpostId)) + d.Set("arn", outpost.OutpostArn) + d.Set("availability_zone", outpost.AvailabilityZone) + d.Set("availability_zone_id", outpost.AvailabilityZoneId) + d.Set("description", outpost.Description) + d.Set("name", outpost.Name) + d.Set("owner_id", outpost.OwnerId) + d.Set("site_id", outpost.SiteId) + + return nil +} diff --git a/aws/data_source_aws_outposts_outpost_instance_type.go b/aws/data_source_aws_outposts_outpost_instance_type.go new file mode 100644 index 00000000000..d476a1aedb8 --- /dev/null +++ b/aws/data_source_aws_outposts_outpost_instance_type.go @@ -0,0 +1,127 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceAwsOutpostsOutpostInstanceType() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsOutpostsOutpostInstanceTypeRead, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateArn, + }, + "instance_type": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ConflictsWith: []string{"preferred_instance_types"}, + }, + "preferred_instance_types": { + Type: schema.TypeList, + Optional: true, + ConflictsWith: []string{"instance_type"}, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + } +} + +func dataSourceAwsOutpostsOutpostInstanceTypeRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).outpostsconn + + input := &outposts.GetOutpostInstanceTypesInput{ + OutpostId: aws.String(d.Get("arn").(string)), // Accepts both ARN and ID; prefer ARN which is more common + } + + var outpostID string + var foundInstanceTypes []string + + for { + output, err := conn.GetOutpostInstanceTypes(input) + + if err != nil { + return fmt.Errorf("error getting Outpost Instance Types: %w", err) + } + + if output == nil { + break + } + + outpostID = aws.StringValue(output.OutpostId) + + for _, outputInstanceType := range output.InstanceTypes { + foundInstanceTypes = append(foundInstanceTypes, aws.StringValue(outputInstanceType.InstanceType)) + } + + if aws.StringValue(output.NextToken) == "" { + break + } + + input.NextToken = output.NextToken + } + + if len(foundInstanceTypes) == 0 { + return fmt.Errorf("no Outpost Instance Types found matching criteria; try different search") + } + + var resultInstanceType string + + // Check requested instance type + if v, ok := d.GetOk("instance_type"); ok { + for _, foundInstanceType := range foundInstanceTypes { + if foundInstanceType == v.(string) { + resultInstanceType = v.(string) + break + } + } + } + + // Search preferred instance types in their given order and set result + // instance type for first match found + if l := d.Get("preferred_instance_types").([]interface{}); len(l) > 0 { + for _, elem := range l { + preferredInstanceType, ok := elem.(string) + + if !ok { + continue + } + + for _, foundInstanceType := range foundInstanceTypes { + if foundInstanceType == preferredInstanceType { + resultInstanceType = preferredInstanceType + break + } + } + + if resultInstanceType != "" { + break + } + } + } + + if resultInstanceType == "" && len(foundInstanceTypes) > 1 { + return fmt.Errorf("multiple Outpost Instance Types found matching criteria; try different search") + } + + if resultInstanceType == "" && len(foundInstanceTypes) == 1 { + resultInstanceType = foundInstanceTypes[0] + } + + if resultInstanceType == "" { + return fmt.Errorf("no Outpost Instance Types found matching criteria; try different search") + } + + d.Set("instance_type", resultInstanceType) + + d.SetId(outpostID) + + return nil +} diff --git a/aws/data_source_aws_outposts_outpost_instance_type_test.go b/aws/data_source_aws_outposts_outpost_instance_type_test.go new file mode 100644 index 00000000000..5b01b6a9645 --- /dev/null +++ b/aws/data_source_aws_outposts_outpost_instance_type_test.go @@ -0,0 +1,74 @@ +package aws + +import ( + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccAWSOutpostsOutpostInstanceTypeDataSource_InstanceType(t *testing.T) { + dataSourceName := "data.aws_outposts_outpost_instance_type.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccAWSOutpostsOutpostInstanceTypeDataSourceConfigInstanceType(), + Check: resource.ComposeTestCheckFunc( + resource.TestMatchResourceAttr(dataSourceName, "instance_type", regexp.MustCompile(`^.+$`)), + ), + }, + }, + }) +} + +func TestAccAWSOutpostsOutpostInstanceTypeDataSource_PreferredInstanceTypes(t *testing.T) { + dataSourceName := "data.aws_outposts_outpost_instance_type.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccAWSOutpostsOutpostInstanceTypeDataSourceConfigPreferredInstanceTypes(), + Check: resource.ComposeTestCheckFunc( + resource.TestMatchResourceAttr(dataSourceName, "instance_type", regexp.MustCompile(`^.+$`)), + ), + }, + }, + }) +} + +func testAccAWSOutpostsOutpostInstanceTypeDataSourceConfigInstanceType() string { + return ` +data "aws_outposts_outposts" "test" {} + +data "aws_outposts_outpost_instance_types" "test" { + arn = tolist(data.aws_outposts_outposts.test.arns)[0] +} + +data "aws_outposts_outpost_instance_type" "test" { + arn = tolist(data.aws_outposts_outposts.test.arns)[0] + instance_type = tolist(data.aws_outposts_outpost_instance_types.test.instance_types)[0] +} +` +} + +func testAccAWSOutpostsOutpostInstanceTypeDataSourceConfigPreferredInstanceTypes() string { + return ` +data "aws_outposts_outposts" "test" {} + +data "aws_outposts_outpost_instance_types" "test" { + arn = tolist(data.aws_outposts_outposts.test.arns)[0] +} + +data "aws_outposts_outpost_instance_type" "test" { + arn = tolist(data.aws_outposts_outposts.test.arns)[0] + preferred_instance_types = data.aws_outposts_outpost_instance_types.test.instance_types +} +` +} diff --git a/aws/data_source_aws_outposts_outpost_instance_types.go b/aws/data_source_aws_outposts_outpost_instance_types.go new file mode 100644 index 00000000000..11207a2891e --- /dev/null +++ b/aws/data_source_aws_outposts_outpost_instance_types.go @@ -0,0 +1,71 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceAwsOutpostsOutpostInstanceTypes() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsOutpostsOutpostInstanceTypesRead, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateArn, + }, + "instance_types": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + } +} + +func dataSourceAwsOutpostsOutpostInstanceTypesRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).outpostsconn + + input := &outposts.GetOutpostInstanceTypesInput{ + OutpostId: aws.String(d.Get("arn").(string)), // Accepts both ARN and ID; prefer ARN which is more common + } + + var outpostID string + var instanceTypes []string + + for { + output, err := conn.GetOutpostInstanceTypes(input) + + if err != nil { + return fmt.Errorf("error getting Outpost Instance Types: %w", err) + } + + if output == nil { + break + } + + outpostID = aws.StringValue(output.OutpostId) + + for _, outputInstanceType := range output.InstanceTypes { + instanceTypes = append(instanceTypes, aws.StringValue(outputInstanceType.InstanceType)) + } + + if aws.StringValue(output.NextToken) == "" { + break + } + + input.NextToken = output.NextToken + } + + if err := d.Set("instance_types", instanceTypes); err != nil { + return fmt.Errorf("error setting instance_types: %w", err) + } + + d.SetId(outpostID) + + return nil +} diff --git a/aws/data_source_aws_outposts_outpost_instance_types_test.go b/aws/data_source_aws_outposts_outpost_instance_types_test.go new file mode 100644 index 00000000000..be5e3b1cd82 --- /dev/null +++ b/aws/data_source_aws_outposts_outpost_instance_types_test.go @@ -0,0 +1,52 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccAWSOutpostsOutpostInstanceTypesDataSource_basic(t *testing.T) { + dataSourceName := "data.aws_outposts_outpost_instance_types.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccAWSOutpostsOutpostInstanceTypesDataSourceConfig(), + Check: resource.ComposeTestCheckFunc( + testAccCheckOutpostsOutpostInstanceTypesAttributes(dataSourceName), + ), + }, + }, + }) +} + +func testAccCheckOutpostsOutpostInstanceTypesAttributes(dataSourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[dataSourceName] + if !ok { + return fmt.Errorf("Not found: %s", dataSourceName) + } + + if v := rs.Primary.Attributes["instance_types.#"]; v == "0" { + return fmt.Errorf("expected at least one instance_types result, got none") + } + + return nil + } +} + +func testAccAWSOutpostsOutpostInstanceTypesDataSourceConfig() string { + return ` +data "aws_outposts_outposts" "test" {} + +data "aws_outposts_outpost_instance_types" "test" { + arn = tolist(data.aws_outposts_outposts.test.arns)[0] +} +` +} diff --git a/aws/data_source_aws_outposts_outpost_test.go b/aws/data_source_aws_outposts_outpost_test.go new file mode 100644 index 00000000000..2b236dfa120 --- /dev/null +++ b/aws/data_source_aws_outposts_outpost_test.go @@ -0,0 +1,81 @@ +package aws + +import ( + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccAWSOutpostsOutpostDataSource_Id(t *testing.T) { + dataSourceName := "data.aws_outposts_outpost.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccAWSOutpostsOutpostDataSourceConfigId(), + Check: resource.ComposeTestCheckFunc( + testAccMatchResourceAttrRegionalARN(dataSourceName, "arn", "outposts", regexp.MustCompile(`outpost/op-.+$`)), + resource.TestMatchResourceAttr(dataSourceName, "availability_zone", regexp.MustCompile(`^.+$`)), + resource.TestMatchResourceAttr(dataSourceName, "availability_zone_id", regexp.MustCompile(`^.+$`)), + resource.TestCheckResourceAttrSet(dataSourceName, "description"), + resource.TestMatchResourceAttr(dataSourceName, "id", regexp.MustCompile(`^op-.+$`)), + resource.TestMatchResourceAttr(dataSourceName, "name", regexp.MustCompile(`^.+$`)), + testAccCheckResourceAttrAccountID(dataSourceName, "owner_id"), + ), + }, + }, + }) +} + +func TestAccAWSOutpostsOutpostDataSource_Name(t *testing.T) { + sourceDataSourceName := "data.aws_outposts_outpost.source" + dataSourceName := "data.aws_outposts_outpost.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccAWSOutpostsOutpostDataSourceConfigName(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "arn", sourceDataSourceName, "arn"), + resource.TestCheckResourceAttrPair(dataSourceName, "availability_zone", sourceDataSourceName, "availability_zone"), + resource.TestCheckResourceAttrPair(dataSourceName, "availability_zone_id", sourceDataSourceName, "availability_zone_id"), + resource.TestCheckResourceAttrPair(dataSourceName, "description", sourceDataSourceName, "description"), + resource.TestCheckResourceAttrPair(dataSourceName, "id", sourceDataSourceName, "id"), + resource.TestCheckResourceAttrPair(dataSourceName, "name", sourceDataSourceName, "name"), + resource.TestCheckResourceAttrPair(dataSourceName, "owner_id", sourceDataSourceName, "owner_id"), + ), + }, + }, + }) +} + +func testAccAWSOutpostsOutpostDataSourceConfigId() string { + return ` +data "aws_outposts_outposts" "test" {} + +data "aws_outposts_outpost" "test" { + id = tolist(data.aws_outposts_outposts.test.ids)[0] +} +` +} + +func testAccAWSOutpostsOutpostDataSourceConfigName() string { + return ` +data "aws_outposts_outposts" "test" {} + +data "aws_outposts_outpost" "source" { + id = tolist(data.aws_outposts_outposts.test.ids)[0] +} + +data "aws_outposts_outpost" "test" { + name = data.aws_outposts_outpost.source.name +} +` +} diff --git a/aws/data_source_aws_outposts_outposts.go b/aws/data_source_aws_outposts_outposts.go new file mode 100644 index 00000000000..e16fa7526e9 --- /dev/null +++ b/aws/data_source_aws_outposts_outposts.go @@ -0,0 +1,97 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceAwsOutpostsOutposts() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsOutpostsOutpostsRead, + + Schema: map[string]*schema.Schema{ + "arns": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "availability_zone": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "availability_zone_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + "ids": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "site_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + }, + } +} + +func dataSourceAwsOutpostsOutpostsRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).outpostsconn + + input := &outposts.ListOutpostsInput{} + + var arns, ids []string + + err := conn.ListOutpostsPages(input, func(page *outposts.ListOutpostsOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, outpost := range page.Outposts { + if outpost == nil { + continue + } + + if v, ok := d.GetOk("availability_zone"); ok && v.(string) != aws.StringValue(outpost.AvailabilityZone) { + continue + } + + if v, ok := d.GetOk("availability_zone_id"); ok && v.(string) != aws.StringValue(outpost.AvailabilityZoneId) { + continue + } + + if v, ok := d.GetOk("site_id"); ok && v.(string) != aws.StringValue(outpost.SiteId) { + continue + } + + arns = append(arns, aws.StringValue(outpost.OutpostArn)) + ids = append(ids, aws.StringValue(outpost.OutpostId)) + } + + return !lastPage + }) + + if err != nil { + return fmt.Errorf("error listing Outposts Outposts: %w", err) + } + + if err := d.Set("arns", arns); err != nil { + return fmt.Errorf("error setting arns: %w", err) + } + + if err := d.Set("ids", ids); err != nil { + return fmt.Errorf("error setting ids: %w", err) + } + + d.SetId(resource.UniqueId()) + + return nil +} diff --git a/aws/data_source_aws_outposts_outposts_test.go b/aws/data_source_aws_outposts_outposts_test.go new file mode 100644 index 00000000000..ee9920c2a1a --- /dev/null +++ b/aws/data_source_aws_outposts_outposts_test.go @@ -0,0 +1,74 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccAWSOutpostsOutpostsDataSource_basic(t *testing.T) { + dataSourceName := "data.aws_outposts_outposts.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccAWSOutpostsOutpostsDataSourceConfig(), + Check: resource.ComposeTestCheckFunc( + testAccCheckOutpostsOutpostsAttributes(dataSourceName), + ), + }, + }, + }) +} + +func testAccCheckOutpostsOutpostsAttributes(dataSourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[dataSourceName] + if !ok { + return fmt.Errorf("Not found: %s", dataSourceName) + } + + if v := rs.Primary.Attributes["arns.#"]; v == "0" { + return fmt.Errorf("expected at least one arns result, got none") + } + + if v := rs.Primary.Attributes["ids.#"]; v == "0" { + return fmt.Errorf("expected at least one ids result, got none") + } + + return nil + } +} + +func testAccPreCheckAWSOutpostsOutposts(t *testing.T) { + conn := testAccProvider.Meta().(*AWSClient).outpostsconn + + input := &outposts.ListOutpostsInput{} + + output, err := conn.ListOutposts(input) + + if testAccPreCheckSkipError(err) { + t.Skipf("skipping acceptance testing: %s", err) + } + + if err != nil { + t.Fatalf("unexpected PreCheck error: %s", err) + } + + // Ensure there is at least one Outpost + if output == nil || len(output.Outposts) == 0 { + t.Skip("skipping since no Outposts Outpost found") + } +} + +func testAccAWSOutpostsOutpostsDataSourceConfig() string { + return ` +data "aws_outposts_outposts" "test" {} +` +} diff --git a/aws/data_source_aws_outposts_site.go b/aws/data_source_aws_outposts_site.go new file mode 100644 index 00000000000..f25313acb67 --- /dev/null +++ b/aws/data_source_aws_outposts_site.go @@ -0,0 +1,91 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceAwsOutpostsSite() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsOutpostsSiteRead, + + Schema: map[string]*schema.Schema{ + "account_id": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ExactlyOneOf: []string{"id", "name"}, + }, + "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ExactlyOneOf: []string{"id", "name"}, + }, + }, + } +} + +func dataSourceAwsOutpostsSiteRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).outpostsconn + + input := &outposts.ListSitesInput{} + + var results []*outposts.Site + + err := conn.ListSitesPages(input, func(page *outposts.ListSitesOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, site := range page.Sites { + if site == nil { + continue + } + + if v, ok := d.GetOk("id"); ok && v.(string) != aws.StringValue(site.SiteId) { + continue + } + + if v, ok := d.GetOk("name"); ok && v.(string) != aws.StringValue(site.Name) { + continue + } + + results = append(results, site) + } + + return !lastPage + }) + + if err != nil { + return fmt.Errorf("error listing Outposts Sites: %w", err) + } + + if len(results) == 0 { + return fmt.Errorf("no Outposts Site found matching criteria; try different search") + } + + if len(results) > 1 { + return fmt.Errorf("multiple Outposts Sites found matching criteria; try different search") + } + + site := results[0] + + d.SetId(aws.StringValue(site.SiteId)) + d.Set("account_id", site.AccountId) + d.Set("description", site.Description) + d.Set("name", site.Name) + + return nil +} diff --git a/aws/data_source_aws_outposts_site_test.go b/aws/data_source_aws_outposts_site_test.go new file mode 100644 index 00000000000..491e015b1da --- /dev/null +++ b/aws/data_source_aws_outposts_site_test.go @@ -0,0 +1,75 @@ +package aws + +import ( + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccAWSOutpostsSiteDataSource_Id(t *testing.T) { + dataSourceName := "data.aws_outposts_site.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsSites(t) }, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccAWSOutpostsSiteDataSourceConfigId(), + Check: resource.ComposeTestCheckFunc( + testAccCheckResourceAttrAccountID(dataSourceName, "account_id"), + resource.TestCheckResourceAttrSet(dataSourceName, "description"), + resource.TestMatchResourceAttr(dataSourceName, "id", regexp.MustCompile(`^os-.+$`)), + resource.TestMatchResourceAttr(dataSourceName, "name", regexp.MustCompile(`^.+$`)), + ), + }, + }, + }) +} + +func TestAccAWSOutpostsSiteDataSource_Name(t *testing.T) { + sourceDataSourceName := "data.aws_outposts_site.source" + dataSourceName := "data.aws_outposts_site.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsSites(t) }, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccAWSOutpostsSiteDataSourceConfigName(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair(dataSourceName, "account_id", sourceDataSourceName, "account_id"), + resource.TestCheckResourceAttrPair(dataSourceName, "description", sourceDataSourceName, "description"), + resource.TestCheckResourceAttrPair(dataSourceName, "id", sourceDataSourceName, "id"), + resource.TestCheckResourceAttrPair(dataSourceName, "name", sourceDataSourceName, "name"), + ), + }, + }, + }) +} + +func testAccAWSOutpostsSiteDataSourceConfigId() string { + return ` +data "aws_outposts_sites" "test" {} + +data "aws_outposts_site" "test" { + id = tolist(data.aws_outposts_sites.test.ids)[0] +} +` +} + +func testAccAWSOutpostsSiteDataSourceConfigName() string { + return ` +data "aws_outposts_sites" "test" {} + +data "aws_outposts_site" "source" { + id = tolist(data.aws_outposts_sites.test.ids)[0] +} + +data "aws_outposts_site" "test" { + name = data.aws_outposts_site.source.name +} +` +} diff --git a/aws/data_source_aws_outposts_sites.go b/aws/data_source_aws_outposts_sites.go new file mode 100644 index 00000000000..6150f01e95d --- /dev/null +++ b/aws/data_source_aws_outposts_sites.go @@ -0,0 +1,60 @@ +package aws + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceAwsOutpostsSites() *schema.Resource { + return &schema.Resource{ + Read: dataSourceAwsOutpostsSitesRead, + + Schema: map[string]*schema.Schema{ + "ids": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + } +} + +func dataSourceAwsOutpostsSitesRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).outpostsconn + + input := &outposts.ListSitesInput{} + + var ids []string + + err := conn.ListSitesPages(input, func(page *outposts.ListSitesOutput, lastPage bool) bool { + if page == nil { + return !lastPage + } + + for _, site := range page.Sites { + if site == nil { + continue + } + + ids = append(ids, aws.StringValue(site.SiteId)) + } + + return !lastPage + }) + + if err != nil { + return fmt.Errorf("error listing Outposts Sites: %w", err) + } + + if err := d.Set("ids", ids); err != nil { + return fmt.Errorf("error setting ids: %w", err) + } + + d.SetId(resource.UniqueId()) + + return nil +} diff --git a/aws/data_source_aws_outposts_sites_test.go b/aws/data_source_aws_outposts_sites_test.go new file mode 100644 index 00000000000..e5a2dbce1da --- /dev/null +++ b/aws/data_source_aws_outposts_sites_test.go @@ -0,0 +1,70 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/outposts" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccAWSOutpostsSitesDataSource_basic(t *testing.T) { + dataSourceName := "data.aws_outposts_sites.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsSites(t) }, + Providers: testAccProviders, + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccAWSOutpostsSitesDataSourceConfig(), + Check: resource.ComposeTestCheckFunc( + testAccCheckOutpostsSitesAttributes(dataSourceName), + ), + }, + }, + }) +} + +func testAccCheckOutpostsSitesAttributes(dataSourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[dataSourceName] + if !ok { + return fmt.Errorf("Not found: %s", dataSourceName) + } + + if v := rs.Primary.Attributes["ids.#"]; v == "0" { + return fmt.Errorf("expected at least one ids result, got none") + } + + return nil + } +} + +func testAccPreCheckAWSOutpostsSites(t *testing.T) { + conn := testAccProvider.Meta().(*AWSClient).outpostsconn + + input := &outposts.ListSitesInput{} + + output, err := conn.ListSites(input) + + if testAccPreCheckSkipError(err) { + t.Skipf("skipping acceptance testing: %s", err) + } + + if err != nil { + t.Fatalf("unexpected PreCheck error: %s", err) + } + + // Ensure there is at least one Site + if output == nil || len(output.Sites) == 0 { + t.Skip("skipping since no Sites Outpost found") + } +} + +func testAccAWSOutpostsSitesDataSourceConfig() string { + return ` +data "aws_outposts_sites" "test" {} +` +} diff --git a/aws/data_source_aws_partition.go b/aws/data_source_aws_partition.go index d1f26518436..26ee1cff986 100644 --- a/aws/data_source_aws_partition.go +++ b/aws/data_source_aws_partition.go @@ -4,7 +4,7 @@ import ( "log" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsPartition() *schema.Resource { diff --git a/aws/data_source_aws_partition_test.go b/aws/data_source_aws_partition_test.go index 333d9a33de4..d254860377e 100644 --- a/aws/data_source_aws_partition_test.go +++ b/aws/data_source_aws_partition_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSPartition_basic(t *testing.T) { @@ -61,5 +61,5 @@ func testAccCheckAwsDnsSuffix(n string) resource.TestCheckFunc { } const testAccCheckAwsPartitionConfig_basic = ` -data "aws_partition" "current" { } +data "aws_partition" "current" {} ` diff --git a/aws/data_source_aws_prefix_list.go b/aws/data_source_aws_prefix_list.go index 82c8a2ae37f..dd2dd60ed71 100644 --- a/aws/data_source_aws_prefix_list.go +++ b/aws/data_source_aws_prefix_list.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsPrefixList() *schema.Resource { diff --git a/aws/data_source_aws_prefix_list_test.go b/aws/data_source_aws_prefix_list_test.go index e74778a01b3..26a27f9684a 100644 --- a/aws/data_source_aws_prefix_list_test.go +++ b/aws/data_source_aws_prefix_list_test.go @@ -5,8 +5,8 @@ import ( "strconv" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccDataSourceAwsPrefixList_basic(t *testing.T) { @@ -79,7 +79,7 @@ data "aws_prefix_list" "s3_by_id" { } data "aws_prefix_list" "s3_by_name" { - name = "com.amazonaws.us-west-2.s3" + name = "com.amazonaws.us-west-2.s3" } ` diff --git a/aws/data_source_aws_pricing_product.go b/aws/data_source_aws_pricing_product.go index 72b778ffa76..84956598802 100644 --- a/aws/data_source_aws_pricing_product.go +++ b/aws/data_source_aws_pricing_product.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pricing" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func dataSourceAwsPricingProduct() *schema.Resource { diff --git a/aws/data_source_aws_pricing_product_test.go b/aws/data_source_aws_pricing_product_test.go index 425a9cb62d4..593efb9a356 100644 --- a/aws/data_source_aws_pricing_product_test.go +++ b/aws/data_source_aws_pricing_product_test.go @@ -6,8 +6,8 @@ import ( "os" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccDataSourceAwsPricingProduct_ec2(t *testing.T) { @@ -49,62 +49,64 @@ func TestAccDataSourceAwsPricingProduct_redshift(t *testing.T) { } func testAccDataSourceAwsPricingProductConfigEc2(dataName string, instanceType string) string { - return fmt.Sprintf(`data "aws_pricing_product" "%s" { - service_code = "AmazonEC2" - - filters { - field = "instanceType" - value = "%s" - } - - filters { - field = "operatingSystem" - value = "Linux" - } - - filters { - field = "location" - value = "US East (N. Virginia)" - } - - filters { - field = "preInstalledSw" - value = "NA" - } - - filters { - field = "licenseModel" - value = "No License required" - } - - filters { - field = "tenancy" - value = "Shared" - } - - filters { - field = "capacitystatus" - value = "Used" - } + return fmt.Sprintf(` +data "aws_pricing_product" "%s" { + service_code = "AmazonEC2" + + filters { + field = "instanceType" + value = "%s" + } + + filters { + field = "operatingSystem" + value = "Linux" + } + + filters { + field = "location" + value = "US East (N. Virginia)" + } + + filters { + field = "preInstalledSw" + value = "NA" + } + + filters { + field = "licenseModel" + value = "No License required" + } + + filters { + field = "tenancy" + value = "Shared" + } + + filters { + field = "capacitystatus" + value = "Used" + } } `, dataName, instanceType) } func testAccDataSourceAwsPricingProductConfigRedshift() string { - return fmt.Sprintf(`data "aws_pricing_product" "test" { - service_code = "AmazonRedshift" - - filters { - field = "instanceType" - value = "ds1.xlarge" - } - - filters { - field = "location" - value = "US East (N. Virginia)" - } + return ` +data "aws_pricing_product" "test" { + service_code = "AmazonRedshift" + + filters { + field = "instanceType" + value = "ds1.xlarge" + } + + filters { + field = "location" + value = "US East (N. Virginia)" + } } -`) +` } func testAccPricingCheckValueIsJSON(data string) resource.TestCheckFunc { diff --git a/aws/data_source_aws_qldb_ledger.go b/aws/data_source_aws_qldb_ledger.go index 58e3cac689c..4399f6fbf41 100644 --- a/aws/data_source_aws_qldb_ledger.go +++ b/aws/data_source_aws_qldb_ledger.go @@ -5,12 +5,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/qldb" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "log" "regexp" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsQLDBLedger() *schema.Resource { diff --git a/aws/data_source_aws_qldb_ledger_test.go b/aws/data_source_aws_qldb_ledger_test.go index f35e303d780..33a73c97299 100644 --- a/aws/data_source_aws_qldb_ledger_test.go +++ b/aws/data_source_aws_qldb_ledger_test.go @@ -4,12 +4,12 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccDataSourceAwsQLDBLedger(t *testing.T) { +func TestAccDataSourceAwsQLDBLedger_basic(t *testing.T) { rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(7)) // QLDB name cannot be longer than 32 characters resource.ParallelTest(t, resource.TestCase{ @@ -31,22 +31,22 @@ func TestAccDataSourceAwsQLDBLedger(t *testing.T) { func testAccDataSourceAwsQLDBLedgerConfig(rName string) string { return fmt.Sprintf(` resource "aws_qldb_ledger" "tf_wrong1" { - name = "%[1]s1" + name = "%[1]s1" deletion_protection = false } resource "aws_qldb_ledger" "tf_test" { - name = "%[1]s2" + name = "%[1]s2" deletion_protection = false } resource "aws_qldb_ledger" "tf_wrong2" { - name = "%[1]s3" - deletion_protection = false + name = "%[1]s3" + deletion_protection = false } data "aws_qldb_ledger" "by_name" { - name = "${aws_qldb_ledger.tf_test.name}" + name = aws_qldb_ledger.tf_test.name } `, rName) } diff --git a/aws/data_source_aws_ram_resource_share.go b/aws/data_source_aws_ram_resource_share.go index 0f9f4d0373b..a637b0c4a8e 100644 --- a/aws/data_source_aws_ram_resource_share.go +++ b/aws/data_source_aws_ram_resource_share.go @@ -5,8 +5,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ram" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -52,13 +52,13 @@ func dataSourceAwsRamResourceShare() *schema.Resource { Computed: true, }, - "tags": tagsSchemaComputed(), - - "id": { + "owning_account_id": { Type: schema.TypeString, Computed: true, }, + "tags": tagsSchemaComputed(), + "status": { Type: schema.TypeString, Computed: true, diff --git a/aws/data_source_aws_ram_resource_share_test.go b/aws/data_source_aws_ram_resource_share_test.go index 99233c61e6c..9e304bd91e8 100644 --- a/aws/data_source_aws_ram_resource_share_test.go +++ b/aws/data_source_aws_ram_resource_share_test.go @@ -5,11 +5,11 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccDataSourceAwsRamResourceShare_Basic(t *testing.T) { +func TestAccDataSourceAwsRamResourceShare_basic(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_ram_resource_share.test" datasourceName := "data.aws_ram_resource_share.test" @@ -27,6 +27,7 @@ func TestAccDataSourceAwsRamResourceShare_Basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrPair(datasourceName, "name", resourceName, "name"), resource.TestCheckResourceAttrPair(datasourceName, "id", resourceName, "id"), + resource.TestCheckResourceAttrSet(datasourceName, "owning_account_id"), ), }, }, @@ -65,7 +66,7 @@ resource "aws_ram_resource_share" "test" { } data "aws_ram_resource_share" "test" { - name = "${aws_ram_resource_share.test.name}" + name = aws_ram_resource_share.test.name resource_owner = "SELF" } `, rName, rName) @@ -82,7 +83,7 @@ resource "aws_ram_resource_share" "test" { } data "aws_ram_resource_share" "test" { - name = "${aws_ram_resource_share.test.name}" + name = aws_ram_resource_share.test.name resource_owner = "SELF" filter { @@ -95,7 +96,7 @@ data "aws_ram_resource_share" "test" { const testAccDataSourceAwsRamResourceShareConfig_NonExistent = ` data "aws_ram_resource_share" "test" { - name = "tf-acc-test-does-not-exist" - resource_owner = "SELF" + name = "tf-acc-test-does-not-exist" + resource_owner = "SELF" } ` diff --git a/aws/data_source_aws_rds_cluster.go b/aws/data_source_aws_rds_cluster.go index a4a555e1041..308701cbf60 100644 --- a/aws/data_source_aws_rds_cluster.go +++ b/aws/data_source_aws_rds_cluster.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -31,6 +31,11 @@ func dataSourceAwsRdsCluster() *schema.Resource { Set: schema.HashString, }, + "backtrack_window": { + Type: schema.TypeInt, + Computed: true, + }, + "backup_retention_period": { Type: schema.TypeInt, Computed: true, diff --git a/aws/data_source_aws_rds_cluster_test.go b/aws/data_source_aws_rds_cluster_test.go index 1b5079ee49a..7f28118ef69 100644 --- a/aws/data_source_aws_rds_cluster_test.go +++ b/aws/data_source_aws_rds_cluster_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAWSRDSCluster_basic(t *testing.T) { @@ -21,6 +21,7 @@ func TestAccDataSourceAWSRDSCluster_basic(t *testing.T) { Config: testAccDataSourceAwsRdsClusterConfigBasic(clusterName), Check: resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrPair(dataSourceName, "arn", resourceName, "arn"), + resource.TestCheckResourceAttrPair(dataSourceName, "backtrack_window", resourceName, "backtrack_window"), resource.TestCheckResourceAttrPair(dataSourceName, "cluster_identifier", resourceName, "cluster_identifier"), resource.TestCheckResourceAttrPair(dataSourceName, "database_name", resourceName, "database_name"), resource.TestCheckResourceAttrPair(dataSourceName, "db_cluster_parameter_group_name", resourceName, "db_cluster_parameter_group_name"), @@ -41,7 +42,7 @@ resource "aws_rds_cluster" "test" { cluster_identifier = "%s" database_name = "mydb" db_cluster_parameter_group_name = "default.aurora5.6" - db_subnet_group_name = "${aws_db_subnet_group.test.name}" + db_subnet_group_name = aws_db_subnet_group.test.name master_password = "mustbeeightcharacters" master_username = "foo" skip_final_snapshot = true @@ -60,7 +61,7 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "a" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id cidr_block = "10.0.0.0/24" availability_zone = "us-west-2a" @@ -70,7 +71,7 @@ resource "aws_subnet" "a" { } resource "aws_subnet" "b" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id cidr_block = "10.0.1.0/24" availability_zone = "us-west-2b" @@ -81,11 +82,11 @@ resource "aws_subnet" "b" { resource "aws_db_subnet_group" "test" { name = "%s" - subnet_ids = ["${aws_subnet.a.id}", "${aws_subnet.b.id}"] + subnet_ids = [aws_subnet.a.id, aws_subnet.b.id] } data "aws_rds_cluster" "test" { - cluster_identifier = "${aws_rds_cluster.test.cluster_identifier}" + cluster_identifier = aws_rds_cluster.test.cluster_identifier } `, clusterName, clusterName) } diff --git a/aws/data_source_aws_redshift_cluster.go b/aws/data_source_aws_redshift_cluster.go index ea766b3ca26..48f240bed13 100644 --- a/aws/data_source_aws_redshift_cluster.go +++ b/aws/data_source_aws_redshift_cluster.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_redshift_cluster_test.go b/aws/data_source_aws_redshift_cluster_test.go index 0bea6f3f849..4839c052601 100644 --- a/aws/data_source_aws_redshift_cluster_test.go +++ b/aws/data_source_aws_redshift_cluster_test.go @@ -4,8 +4,8 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSDataSourceRedshiftCluster_basic(t *testing.T) { @@ -92,7 +92,7 @@ resource "aws_redshift_cluster" "test" { } data "aws_redshift_cluster" "test" { - cluster_identifier = "${aws_redshift_cluster.test.cluster_identifier}" + cluster_identifier = aws_redshift_cluster.test.cluster_identifier } `, rInt) } @@ -106,23 +106,23 @@ resource "aws_vpc" "test" { resource "aws_subnet" "foo" { cidr_block = "10.1.1.0/24" availability_zone = "us-west-2a" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } resource "aws_subnet" "bar" { cidr_block = "10.1.2.0/24" availability_zone = "us-west-2b" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } resource "aws_redshift_subnet_group" "test" { name = "tf-redshift-subnet-group-%d" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.bar.id}"] + subnet_ids = [aws_subnet.foo.id, aws_subnet.bar.id] } resource "aws_security_group" "test" { name = "tf-redshift-sg-%d" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } resource "aws_redshift_cluster" "test" { @@ -135,13 +135,13 @@ resource "aws_redshift_cluster" "test" { cluster_type = "multi-node" number_of_nodes = 2 publicly_accessible = false - cluster_subnet_group_name = "${aws_redshift_subnet_group.test.name}" - vpc_security_group_ids = ["${aws_security_group.test.id}"] + cluster_subnet_group_name = aws_redshift_subnet_group.test.name + vpc_security_group_ids = [aws_security_group.test.id] skip_final_snapshot = true } data "aws_redshift_cluster" "test" { - cluster_identifier = "${aws_redshift_cluster.test.cluster_identifier}" + cluster_identifier = aws_redshift_cluster.test.cluster_identifier } `, rInt, rInt, rInt) } @@ -161,25 +161,25 @@ data "aws_iam_policy_document" "test" { resources = ["${aws_s3_bucket.test.arn}/*"] principals { - identifiers = ["${data.aws_redshift_service_account.test.arn}"] + identifiers = [data.aws_redshift_service_account.test.arn] type = "AWS" } } statement { actions = ["s3:GetBucketAcl"] - resources = ["${aws_s3_bucket.test.arn}"] + resources = [aws_s3_bucket.test.arn] principals { - identifiers = ["${data.aws_redshift_service_account.test.arn}"] + identifiers = [data.aws_redshift_service_account.test.arn] type = "AWS" } } } resource "aws_s3_bucket_policy" "test" { - bucket = "${aws_s3_bucket.test.bucket}" - policy = "${data.aws_iam_policy_document.test.json}" + bucket = aws_s3_bucket.test.bucket + policy = data.aws_iam_policy_document.test.json } resource "aws_redshift_cluster" "test" { @@ -194,14 +194,14 @@ resource "aws_redshift_cluster" "test" { skip_final_snapshot = true logging { - bucket_name = "${aws_s3_bucket.test.id}" + bucket_name = aws_s3_bucket.test.id enable = true s3_key_prefix = "cluster-logging/" } } data "aws_redshift_cluster" "test" { - cluster_identifier = "${aws_redshift_cluster.test.cluster_identifier}" + cluster_identifier = aws_redshift_cluster.test.cluster_identifier } `, rInt) } diff --git a/aws/data_source_aws_redshift_service_account.go b/aws/data_source_aws_redshift_service_account.go index fa4357cfb55..100af85974f 100644 --- a/aws/data_source_aws_redshift_service_account.go +++ b/aws/data_source_aws_redshift_service_account.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/aws/aws-sdk-go/aws/arn" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // See http://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html#db-auditing-bucket-permissions diff --git a/aws/data_source_aws_redshift_service_account_test.go b/aws/data_source_aws_redshift_service_account_test.go index 66ebbf47c5d..3e6d2be4bba 100644 --- a/aws/data_source_aws_redshift_service_account_test.go +++ b/aws/data_source_aws_redshift_service_account_test.go @@ -3,10 +3,14 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSRedshiftServiceAccount_basic(t *testing.T) { + expectedAccountID := redshiftServiceAccountPerRegionMap[testAccGetRegion()] + + dataSourceName := "data.aws_redshift_service_account.main" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -14,15 +18,28 @@ func TestAccAWSRedshiftServiceAccount_basic(t *testing.T) { { Config: testAccCheckAwsRedshiftServiceAccountConfig, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.aws_redshift_service_account.main", "id", "902366379725"), - resource.TestCheckResourceAttr("data.aws_redshift_service_account.main", "arn", "arn:aws:iam::902366379725:user/logs"), + resource.TestCheckResourceAttr(dataSourceName, "id", expectedAccountID), + testAccCheckResourceAttrGlobalARNAccountID(dataSourceName, "arn", expectedAccountID, "iam", "user/logs"), ), }, + }, + }) +} + +func TestAccAWSRedshiftServiceAccount_Region(t *testing.T) { + expectedAccountID := redshiftServiceAccountPerRegionMap[testAccGetRegion()] + + dataSourceName := "data.aws_redshift_service_account.regional" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ { Config: testAccCheckAwsRedshiftServiceAccountExplicitRegionConfig, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.aws_redshift_service_account.regional", "id", "307160386991"), - resource.TestCheckResourceAttr("data.aws_redshift_service_account.regional", "arn", "arn:aws:iam::307160386991:user/logs"), + resource.TestCheckResourceAttr(dataSourceName, "id", expectedAccountID), + testAccCheckResourceAttrGlobalARNAccountID(dataSourceName, "arn", expectedAccountID, "iam", "user/logs"), ), }, }, @@ -30,11 +47,13 @@ func TestAccAWSRedshiftServiceAccount_basic(t *testing.T) { } const testAccCheckAwsRedshiftServiceAccountConfig = ` -data "aws_redshift_service_account" "main" { } +data "aws_redshift_service_account" "main" {} ` const testAccCheckAwsRedshiftServiceAccountExplicitRegionConfig = ` +data "aws_region" "current" {} + data "aws_redshift_service_account" "regional" { - region = "eu-west-2" + region = data.aws_region.current.name } ` diff --git a/aws/data_source_aws_region.go b/aws/data_source_aws_region.go index dbafe3c4815..a025b7adb05 100644 --- a/aws/data_source_aws_region.go +++ b/aws/data_source_aws_region.go @@ -5,7 +5,7 @@ import ( "strings" "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsRegion() *schema.Resource { @@ -19,13 +19,6 @@ func dataSourceAwsRegion() *schema.Resource { Computed: true, }, - "current": { - Type: schema.TypeBool, - Optional: true, - Computed: true, - Removed: "Defaults to current provider region if no other filtering is enabled", - }, - "endpoint": { Type: schema.TypeString, Optional: true, diff --git a/aws/data_source_aws_region_test.go b/aws/data_source_aws_region_test.go index 972cc5a7ce6..034389c15eb 100644 --- a/aws/data_source_aws_region_test.go +++ b/aws/data_source_aws_region_test.go @@ -6,8 +6,8 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestFindRegionByEc2Endpoint(t *testing.T) { diff --git a/aws/data_source_aws_regions.go b/aws/data_source_aws_regions.go index 0237b032e66..5f58d54f1f0 100644 --- a/aws/data_source_aws_regions.go +++ b/aws/data_source_aws_regions.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsRegions() *schema.Resource { diff --git a/aws/data_source_aws_regions_test.go b/aws/data_source_aws_regions_test.go index b8e523ff046..b4a3c080332 100644 --- a/aws/data_source_aws_regions_test.go +++ b/aws/data_source_aws_regions_test.go @@ -5,11 +5,11 @@ import ( "strconv" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccDataSourceAwsRegions_Basic(t *testing.T) { +func TestAccDataSourceAwsRegions_basic(t *testing.T) { resourceName := "data.aws_regions.empty" resource.ParallelTest(t, resource.TestCase{ @@ -100,7 +100,7 @@ data "aws_regions" "empty" {} func testAccDataSourceAwsRegionsConfig_allRegions() string { return ` data "aws_regions" "all_regions" { - all_regions = "true" + all_regions = "true" } ` } @@ -108,10 +108,10 @@ data "aws_regions" "all_regions" { func testAccDataSourceAwsRegionsConfig_allRegionsFiltered(filter string) string { return fmt.Sprintf(` data "aws_regions" "opt_in_status" { - filter { - name = "opt-in-status" - values = ["%s"] - } + filter { + name = "opt-in-status" + values = ["%s"] + } } `, filter) } diff --git a/aws/data_source_aws_route.go b/aws/data_source_aws_route.go index 26ebc96405a..e88e1ac77b6 100644 --- a/aws/data_source_aws_route.go +++ b/aws/data_source_aws_route.go @@ -5,7 +5,7 @@ import ( "log" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsRoute() *schema.Resource { diff --git a/aws/data_source_aws_route53_delegation_set.go b/aws/data_source_aws_route53_delegation_set.go index f132a59b1db..fc5a73acf66 100644 --- a/aws/data_source_aws_route53_delegation_set.go +++ b/aws/data_source_aws_route53_delegation_set.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsDelegationSet() *schema.Resource { diff --git a/aws/data_source_aws_route53_delegation_set_test.go b/aws/data_source_aws_route53_delegation_set_test.go index 0ae1ea68049..0695ccb2941 100644 --- a/aws/data_source_aws_route53_delegation_set_test.go +++ b/aws/data_source_aws_route53_delegation_set_test.go @@ -4,7 +4,7 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceRoute53DelegationSet_basic(t *testing.T) { @@ -40,10 +40,10 @@ resource "aws_route53_delegation_set" "dset" { resource "aws_route53_zone" "primary" { name = "example.xyz" - delegation_set_id = "${aws_route53_delegation_set.dset.id}" + delegation_set_id = aws_route53_delegation_set.dset.id } data "aws_route53_delegation_set" "dset" { - id = "${aws_route53_delegation_set.dset.id}" + id = aws_route53_delegation_set.dset.id } ` diff --git a/aws/data_source_aws_route53_resolver_rule.go b/aws/data_source_aws_route53_resolver_rule.go index 943a1d9a07f..853a4a56aec 100644 --- a/aws/data_source_aws_route53_resolver_rule.go +++ b/aws/data_source_aws_route53_resolver_rule.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53resolver" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -122,7 +122,9 @@ func dataSourceAwsRoute53ResolverRuleRead(d *schema.ResourceData, meta interface d.SetId(aws.StringValue(rule.Id)) arn := *rule.Arn d.Set("arn", arn) - d.Set("domain_name", rule.DomainName) + // To be consistent with other AWS services that do not accept a trailing period, + // we remove the suffix from the Domain Name returned from the API + d.Set("domain_name", trimTrailingPeriod(aws.StringValue(rule.DomainName))) d.Set("name", rule.Name) d.Set("owner_id", rule.OwnerId) d.Set("resolver_endpoint_id", rule.ResolverEndpointId) diff --git a/aws/data_source_aws_route53_resolver_rule_test.go b/aws/data_source_aws_route53_resolver_rule_test.go index 29d3c0f2a05..250fd658e55 100644 --- a/aws/data_source_aws_route53_resolver_rule_test.go +++ b/aws/data_source_aws_route53_resolver_rule_test.go @@ -4,9 +4,9 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func TestAccDataSourceAwsRoute53ResolverRule_basic(t *testing.T) { @@ -173,16 +173,16 @@ resource "aws_route53_resolver_rule" "example" { } data "aws_route53_resolver_rule" "by_resolver_rule_id" { - resolver_rule_id = "${aws_route53_resolver_rule.example.id}" + resolver_rule_id = aws_route53_resolver_rule.example.id } data "aws_route53_resolver_rule" "by_domain_name" { - domain_name = "${aws_route53_resolver_rule.example.domain_name}" + domain_name = aws_route53_resolver_rule.example.domain_name } data "aws_route53_resolver_rule" "by_name_and_rule_type" { - name = "${aws_route53_resolver_rule.example.name}" - rule_type = "${aws_route53_resolver_rule.example.rule_type}" + name = aws_route53_resolver_rule.example.name + rule_type = aws_route53_resolver_rule.example.rule_type } `, rName) } @@ -194,7 +194,7 @@ resource "aws_route53_resolver_rule" "example" { rule_type = "FORWARD" name = %[1]q - resolver_endpoint_id = "${aws_route53_resolver_endpoint.bar.id}" + resolver_endpoint_id = aws_route53_resolver_endpoint.bar.id target_ip { ip = "192.0.2.7" @@ -207,7 +207,7 @@ resource "aws_route53_resolver_rule" "example" { } data "aws_route53_resolver_rule" "by_resolver_endpoint_id" { - resolver_endpoint_id = "${aws_route53_resolver_rule.example.resolver_endpoint_id}" + resolver_endpoint_id = aws_route53_resolver_rule.example.resolver_endpoint_id } `, rName) } @@ -219,7 +219,7 @@ resource "aws_route53_resolver_rule" "example" { rule_type = "FORWARD" name = %[1]q - resolver_endpoint_id = "${aws_route53_resolver_endpoint.bar.id}" + resolver_endpoint_id = aws_route53_resolver_endpoint.bar.id target_ip { ip = "192.0.2.7" @@ -237,19 +237,19 @@ resource "aws_ram_resource_share" "test" { } resource "aws_ram_resource_association" "test" { - resource_arn = "${aws_route53_resolver_rule.example.arn}" - resource_share_arn = "${aws_ram_resource_share.test.arn}" + resource_arn = aws_route53_resolver_rule.example.arn + resource_share_arn = aws_ram_resource_share.test.arn } data "aws_organizations_organization" "test" {} resource "aws_ram_principal_association" "test" { - principal = "${data.aws_organizations_organization.test.arn}" - resource_share_arn = "${aws_ram_resource_share.test.arn}" + principal = data.aws_organizations_organization.test.arn + resource_share_arn = aws_ram_resource_share.test.arn } data "aws_route53_resolver_rule" "by_resolver_endpoint_id" { - resolver_endpoint_id = "${aws_route53_resolver_rule.example.resolver_endpoint_id}" + resolver_endpoint_id = aws_route53_resolver_rule.example.resolver_endpoint_id depends_on = ["aws_ram_resource_association.test", "aws_ram_principal_association.test"] } @@ -263,7 +263,7 @@ resource "aws_route53_resolver_rule" "example" { rule_type = "FORWARD" name = %[1]q - resolver_endpoint_id = "${aws_route53_resolver_endpoint.bar.id}" + resolver_endpoint_id = aws_route53_resolver_endpoint.bar.id target_ip { ip = "192.0.2.7" @@ -281,21 +281,21 @@ resource "aws_ram_resource_share" "test" { } resource "aws_ram_resource_association" "test" { - resource_arn = "${aws_route53_resolver_rule.example.arn}" - resource_share_arn = "${aws_ram_resource_share.test.arn}" + resource_arn = aws_route53_resolver_rule.example.arn + resource_share_arn = aws_ram_resource_share.test.arn } data "aws_organizations_organization" "test" {} resource "aws_ram_principal_association" "test" { - principal = "${data.aws_organizations_organization.test.arn}" - resource_share_arn = "${aws_ram_resource_share.test.arn}" + principal = data.aws_organizations_organization.test.arn + resource_share_arn = aws_ram_resource_share.test.arn } data "aws_route53_resolver_rule" "by_resolver_endpoint_id" { - provider = "aws.alternate" + provider = "awsalternate" - resolver_endpoint_id = "${aws_route53_resolver_rule.example.resolver_endpoint_id}" + resolver_endpoint_id = aws_route53_resolver_rule.example.resolver_endpoint_id depends_on = ["aws_ram_resource_association.test", "aws_ram_principal_association.test"] } diff --git a/aws/data_source_aws_route53_resolver_rules.go b/aws/data_source_aws_route53_resolver_rules.go index fa0f6011c81..91315f8a118 100644 --- a/aws/data_source_aws_route53_resolver_rules.go +++ b/aws/data_source_aws_route53_resolver_rules.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53resolver" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func dataSourceAwsRoute53ResolverRules() *schema.Resource { diff --git a/aws/data_source_aws_route53_resolver_rules_test.go b/aws/data_source_aws_route53_resolver_rules_test.go index 43d02b57a44..f0617f8049a 100644 --- a/aws/data_source_aws_route53_resolver_rules_test.go +++ b/aws/data_source_aws_route53_resolver_rules_test.go @@ -4,23 +4,23 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccDataSourceAwsRoute53ResolverRules_basic(t *testing.T) { dsResourceName := "data.aws_route53_resolver_rules.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSRoute53Resolver(t) }, - Providers: testAccProviders, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSRoute53Resolver(t) }, + Providers: testAccProviders, Steps: []resource.TestStep{ { Config: testAccDataSourceAwsRoute53ResolverRules_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(dsResourceName, "resolver_rule_ids.#", "1"), - resource.TestCheckResourceAttr(dsResourceName, "resolver_rule_ids.1743502667", "rslvr-autodefined-rr-internet-resolver"), + tfawsresource.TestCheckTypeSetElemAttr(dsResourceName, "resolver_rule_ids.*", "rslvr-autodefined-rr-internet-resolver"), ), }, }, @@ -66,7 +66,7 @@ resource "aws_route53_resolver_rule" "forward" { rule_type = "FORWARD" name = %[1]q - resolver_endpoint_id = "${aws_route53_resolver_endpoint.bar.id}" + resolver_endpoint_id = aws_route53_resolver_endpoint.bar.id target_ip { ip = "192.0.2.7" @@ -80,15 +80,15 @@ resource "aws_route53_resolver_rule" "recursive" { } data "aws_route53_resolver_rules" "by_resolver_endpoint_id" { - owner_id = "${aws_route53_resolver_rule.forward.owner_id}" - resolver_endpoint_id = "${aws_route53_resolver_rule.forward.resolver_endpoint_id}" + owner_id = aws_route53_resolver_rule.forward.owner_id + resolver_endpoint_id = aws_route53_resolver_rule.forward.resolver_endpoint_id } data "aws_route53_resolver_rules" "by_resolver_endpoint_id_rule_type_share_status" { - owner_id = "${aws_route53_resolver_rule.recursive.owner_id}" - resolver_endpoint_id = "${aws_route53_resolver_rule.recursive.resolver_endpoint_id}" - rule_type = "${aws_route53_resolver_rule.recursive.rule_type}" - share_status = "${aws_route53_resolver_rule.recursive.share_status}" + owner_id = aws_route53_resolver_rule.recursive.owner_id + resolver_endpoint_id = aws_route53_resolver_rule.recursive.resolver_endpoint_id + rule_type = aws_route53_resolver_rule.recursive.rule_type + share_status = aws_route53_resolver_rule.recursive.share_status } data "aws_route53_resolver_rules" "by_invalid_owner_id" { diff --git a/aws/data_source_aws_route53_zone.go b/aws/data_source_aws_route53_zone.go index 0feff3f9e76..9c424c0824c 100644 --- a/aws/data_source_aws_route53_zone.go +++ b/aws/data_source_aws_route53_zone.go @@ -3,11 +3,10 @@ package aws import ( "fmt" "log" - "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -72,7 +71,7 @@ func dataSourceAwsRoute53ZoneRead(d *schema.ResourceData, meta interface{}) erro ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig name, nameExists := d.GetOk("name") - name = hostedZoneName(name.(string)) + name = name.(string) id, idExists := d.GetOk("zone_id") vpcId, vpcIdExists := d.GetOk("vpc_id") tags := keyvaluetags.New(d.Get("tags").(map[string]interface{})).IgnoreAws() @@ -101,12 +100,12 @@ func dataSourceAwsRoute53ZoneRead(d *schema.ResourceData, meta interface{}) erro return fmt.Errorf("Error finding Route 53 Hosted Zone: %v", err) } for _, hostedZone := range resp.HostedZones { - hostedZoneId := cleanZoneID(*hostedZone.Id) + hostedZoneId := cleanZoneID(aws.StringValue(hostedZone.Id)) if idExists && hostedZoneId == id.(string) { hostedZoneFound = hostedZone break // we check if the name is the same as requested and if private zone field is the same as requested or if there is a vpc_id - } else if *hostedZone.Name == name && (*hostedZone.Config.PrivateZone == d.Get("private_zone").(bool) || (*hostedZone.Config.PrivateZone && vpcIdExists)) { + } else if (trimTrailingPeriod(aws.StringValue(hostedZone.Name)) == trimTrailingPeriod(name)) && (aws.BoolValue(hostedZone.Config.PrivateZone) == d.Get("private_zone").(bool) || (aws.BoolValue(hostedZone.Config.PrivateZone) && vpcIdExists)) { matchingVPC := false if vpcIdExists { reqHostedZone := &route53.GetHostedZoneInput{} @@ -118,7 +117,7 @@ func dataSourceAwsRoute53ZoneRead(d *schema.ResourceData, meta interface{}) erro } // we go through all VPCs for _, vpc := range respHostedZone.VPCs { - if *vpc.VPCId == vpcId.(string) { + if aws.StringValue(vpc.VPCId) == vpcId.(string) { matchingVPC = true break } @@ -132,7 +131,7 @@ func dataSourceAwsRoute53ZoneRead(d *schema.ResourceData, meta interface{}) erro listTags, err := keyvaluetags.Route53ListTags(conn, hostedZoneId, route53.TagResourceTypeHostedzone) if err != nil { - return fmt.Errorf("Error finding Route 53 Hosted Zone: %v", err) + return fmt.Errorf("Error finding Route 53 Hosted Zone: %w", err) } matchingTags = listTags.ContainsAll(tags) } @@ -156,10 +155,12 @@ func dataSourceAwsRoute53ZoneRead(d *schema.ResourceData, meta interface{}) erro return fmt.Errorf("no matching Route53Zone found") } - idHostedZone := cleanZoneID(*hostedZoneFound.Id) + idHostedZone := cleanZoneID(aws.StringValue(hostedZoneFound.Id)) d.SetId(idHostedZone) d.Set("zone_id", idHostedZone) - d.Set("name", hostedZoneFound.Name) + // To be consistent with other AWS services (e.g. ACM) that do not accept a trailing period, + // we remove the suffix from the Hosted Zone Name returned from the API + d.Set("name", trimTrailingPeriod(aws.StringValue(hostedZoneFound.Name))) d.Set("comment", hostedZoneFound.Config.Comment) d.Set("private_zone", hostedZoneFound.Config.PrivateZone) d.Set("caller_reference", hostedZoneFound.CallerReference) @@ -173,7 +174,9 @@ func dataSourceAwsRoute53ZoneRead(d *schema.ResourceData, meta interface{}) erro if err != nil { return fmt.Errorf("Error finding Route 53 Hosted Zone: %v", err) } - d.Set("name_servers", nameServers) + if err := d.Set("name_servers", nameServers); err != nil { + return fmt.Errorf("error setting name_servers: %w", err) + } tags, err = keyvaluetags.Route53ListTags(conn, idHostedZone, route53.TagResourceTypeHostedzone) @@ -188,15 +191,6 @@ func dataSourceAwsRoute53ZoneRead(d *schema.ResourceData, meta interface{}) erro return nil } -// used to manage trailing . -func hostedZoneName(name string) string { - if strings.HasSuffix(name, ".") { - return name - } - - return name + "." -} - // used to retrieve name servers func hostedZoneNameServers(id string, conn *route53.Route53) ([]string, error) { req := &route53.GetHostedZoneInput{} @@ -214,7 +208,7 @@ func hostedZoneNameServers(id string, conn *route53.Route53) ([]string, error) { servers := []string{} for _, server := range resp.DelegationSet.NameServers { if server != nil { - servers = append(servers, *server) + servers = append(servers, aws.StringValue(server)) } } return servers, nil diff --git a/aws/data_source_aws_route53_zone_test.go b/aws/data_source_aws_route53_zone_test.go index 4c626cb9257..015fad446ca 100644 --- a/aws/data_source_aws_route53_zone_test.go +++ b/aws/data_source_aws_route53_zone_test.go @@ -2,11 +2,10 @@ package aws import ( "fmt" - "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAwsRoute53Zone_id(t *testing.T) { @@ -114,9 +113,9 @@ func TestAccDataSourceAwsRoute53Zone_serviceDiscovery(t *testing.T) { { Config: testAccDataSourceAwsRoute53ZoneConfigServiceDiscovery(rInt), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair(resourceName, "name", dataSourceName, "name"), + resource.TestCheckResourceAttrPair(dataSourceName, "name", resourceName, "name"), resource.TestCheckResourceAttr(dataSourceName, "linked_service_principal", "servicediscovery.amazonaws.com"), - resource.TestMatchResourceAttr(dataSourceName, "linked_service_description", regexp.MustCompile(`^arn:[^:]+:servicediscovery:[^:]+:[^:]+:namespace/ns-\w+$`)), + resource.TestCheckResourceAttrPair(dataSourceName, "linked_service_description", resourceName, "arn"), ), }, }, @@ -130,7 +129,7 @@ resource "aws_route53_zone" "test" { } data "aws_route53_zone" "test" { - zone_id = "${aws_route53_zone.test.zone_id}" + zone_id = aws_route53_zone.test.zone_id } `, rInt) } @@ -142,7 +141,7 @@ resource "aws_route53_zone" "test" { } data "aws_route53_zone" "test" { - name = "${aws_route53_zone.test.name}" + name = aws_route53_zone.test.name } `, rInt) } @@ -159,20 +158,21 @@ resource "aws_vpc" "test" { resource "aws_route53_zone" "test" { name = "terraformtestacchz-%[1]d.com." + vpc { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } tags = { - Environment = "tf-acc-test-%[1]d" - Name = "tf-acc-test-%[1]d" + Environment = "tf-acc-test-%[1]d" + Name = "tf-acc-test-%[1]d" } } data "aws_route53_zone" "test" { - name = "${aws_route53_zone.test.name}" + name = aws_route53_zone.test.name private_zone = true - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Environment = "tf-acc-test-%[1]d" @@ -195,7 +195,7 @@ resource "aws_route53_zone" "test" { name = "test.acc-%[1]d." vpc { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } tags = { @@ -204,9 +204,9 @@ resource "aws_route53_zone" "test" { } data "aws_route53_zone" "test" { - name = "${aws_route53_zone.test.name}" + name = aws_route53_zone.test.name private_zone = true - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } `, rInt) } @@ -222,13 +222,13 @@ resource "aws_vpc" "test" { } resource "aws_service_discovery_private_dns_namespace" "test" { - name = "test.acc-sd-%[1]d." - vpc = "${aws_vpc.test.id}" + name = "test.acc-sd-%[1]d" + vpc = aws_vpc.test.id } data "aws_route53_zone" "test" { - name = "${aws_service_discovery_private_dns_namespace.test.name}" - vpc_id = "${aws_vpc.test.id}" + name = aws_service_discovery_private_dns_namespace.test.name + vpc_id = aws_vpc.test.id } `, rInt) } diff --git a/aws/data_source_aws_route_table.go b/aws/data_source_aws_route_table.go index 4ea77524058..94afd8c9c60 100644 --- a/aws/data_source_aws_route_table.go +++ b/aws/data_source_aws_route_table.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_route_table_test.go b/aws/data_source_aws_route_table_test.go index a25b2f3a5c5..05faae829c5 100644 --- a/aws/data_source_aws_route_table_test.go +++ b/aws/data_source_aws_route_table_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccDataSourceAwsRouteTable_basic(t *testing.T) { @@ -169,26 +169,29 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "172.16.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id + tags = { Name = "tf-acc-route-table-data-source" } } resource "aws_route_table" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id + tags = { Name = "terraform-testacc-routetable-data-source" } } resource "aws_route_table_association" "a" { - subnet_id = "${aws_subnet.test.id}" - route_table_id = "${aws_route_table.test.id}" + subnet_id = aws_subnet.test.id + route_table_id = aws_route_table.test.id } resource "aws_internet_gateway" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id + tags = { Name = "terraform-testacc-routetable-data-source" } @@ -201,19 +204,21 @@ resource "aws_route_table_association" "b" { data "aws_route_table" "by_filter" { filter { - name = "association.route-table-association-id" - values = ["${aws_route_table_association.a.id}"] + name = "association.route-table-association-id" + values = [aws_route_table_association.a.id] } + depends_on = [ - "aws_route_table_association.a", - "aws_route_table_association.b" + "aws_route_table_association.a", + "aws_route_table_association.b" ] } data "aws_route_table" "by_tag" { tags = { - Name = "${aws_route_table.test.tags["Name"]}" + Name = aws_route_table.test.tags["Name"] } + depends_on = [ "aws_route_table_association.a", "aws_route_table_association.b" @@ -221,26 +226,26 @@ data "aws_route_table" "by_tag" { } data "aws_route_table" "by_subnet" { - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id depends_on = [ - "aws_route_table_association.a", - "aws_route_table_association.b" + "aws_route_table_association.a", + "aws_route_table_association.b" ] } data "aws_route_table" "by_gateway" { - gateway_id = "${aws_internet_gateway.test.id}" + gateway_id = aws_internet_gateway.test.id depends_on = [ - "aws_route_table_association.a", - "aws_route_table_association.b" + "aws_route_table_association.a", + "aws_route_table_association.b" ] } - + data "aws_route_table" "by_id" { - route_table_id = "${aws_route_table.test.id}" + route_table_id = aws_route_table.test.id depends_on = [ - "aws_route_table_association.a", - "aws_route_table_association.b" + "aws_route_table_association.a", + "aws_route_table_association.b" ] } ` @@ -256,12 +261,13 @@ resource "aws_vpc" "test" { data "aws_route_table" "by_filter" { filter { - name = "association.main" + name = "association.main" values = ["true"] } + filter { - name = "vpc-id" - values = ["${aws_vpc.test.id}"] + name = "vpc-id" + values = [aws_vpc.test.id] } } ` diff --git a/aws/data_source_aws_route_tables.go b/aws/data_source_aws_route_tables.go index 33001de5a1b..6d1090cc681 100644 --- a/aws/data_source_aws_route_tables.go +++ b/aws/data_source_aws_route_tables.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/data_source_aws_route_tables_test.go b/aws/data_source_aws_route_tables_test.go index ce1c0b20fbe..710f47f8d90 100644 --- a/aws/data_source_aws_route_tables_test.go +++ b/aws/data_source_aws_route_tables_test.go @@ -4,11 +4,11 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccDataSourceAwsRouteTables(t *testing.T) { +func TestAccDataSourceAwsRouteTables_basic(t *testing.T) { rInt := acctest.RandIntRange(0, 256) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -50,7 +50,7 @@ resource "aws_vpc" "test2" { } resource "aws_route_table" "test_public_a" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-route-tables-data-source-public-a" @@ -60,7 +60,7 @@ resource "aws_route_table" "test_public_a" { } resource "aws_route_table" "test_private_a" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-route-tables-data-source-private-a" @@ -70,7 +70,7 @@ resource "aws_route_table" "test_private_a" { } resource "aws_route_table" "test_private_b" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-route-tables-data-source-private-b" @@ -80,7 +80,7 @@ resource "aws_route_table" "test_private_b" { } resource "aws_route_table" "test_private_c" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-route-tables-data-source-private-c" @@ -90,15 +90,15 @@ resource "aws_route_table" "test_private_c" { } data "aws_route_tables" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } data "aws_route_tables" "test2" { - vpc_id = "${aws_vpc.test2.id}" + vpc_id = aws_vpc.test2.id } data "aws_route_tables" "private" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Tier = "Private" @@ -106,7 +106,7 @@ data "aws_route_tables" "private" { } data "aws_route_tables" "filter_test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id filter { name = "tag:Component" @@ -127,7 +127,7 @@ resource "aws_vpc" "test" { } resource "aws_route_table" "test_public_a" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-route-tables-data-source-public-a" @@ -137,7 +137,7 @@ resource "aws_route_table" "test_public_a" { } resource "aws_route_table" "test_private_a" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-route-tables-data-source-private-a" @@ -147,7 +147,7 @@ resource "aws_route_table" "test_private_a" { } resource "aws_route_table" "test_private_b" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-route-tables-data-source-private-b" @@ -157,7 +157,7 @@ resource "aws_route_table" "test_private_b" { } resource "aws_route_table" "test_private_c" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-route-tables-data-source-private-c" diff --git a/aws/data_source_aws_route_test.go b/aws/data_source_aws_route_test.go index 82cba87ac67..c2ccc7e30ce 100644 --- a/aws/data_source_aws_route_test.go +++ b/aws/data_source_aws_route_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSRouteDataSource_basic(t *testing.T) { @@ -15,7 +15,7 @@ func TestAccAWSRouteDataSource_basic(t *testing.T) { Providers: testAccProviders, Steps: []resource.TestStep{ { - Config: testAccDataSourceAwsRouteGroupConfig, + Config: testAccDataSourceAwsRouteGroupConfig(), Check: resource.ComposeTestCheckFunc( testAccDataSourceAwsRouteCheck("data.aws_route.by_destination_cidr_block"), testAccDataSourceAwsRouteCheck("data.aws_route.by_instance_id"), @@ -89,7 +89,8 @@ func testAccDataSourceAwsRouteCheck(name string) resource.TestCheckFunc { } } -const testAccDataSourceAwsRouteGroupConfig = ` +func testAccDataSourceAwsRouteGroupConfig() string { + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + ` resource "aws_vpc" "test" { cidr_block = "172.16.0.0/16" @@ -99,112 +100,89 @@ resource "aws_vpc" "test" { } resource "aws_vpc" "dest" { - cidr_block = "172.17.0.0/16" - - tags = { - Name = "terraform-testacc-route-table-data-source" - } + cidr_block = "172.17.0.0/16" + + tags = { + Name = "terraform-testacc-route-table-data-source" + } } resource "aws_vpc_peering_connection" "test" { - peer_vpc_id = "${aws_vpc.dest.id}" - vpc_id = "${aws_vpc.test.id}" - auto_accept = true + peer_vpc_id = aws_vpc.dest.id + vpc_id = aws_vpc.test.id + auto_accept = true } resource "aws_subnet" "test" { cidr_block = "172.16.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id + tags = { Name = "tf-acc-route-table-data-source" } } resource "aws_route_table" "test" { - vpc_id = "${aws_vpc.test.id}" - tags = { - Name = "terraform-testacc-routetable-data-source" - } + vpc_id = aws_vpc.test.id + + tags = { + Name = "terraform-testacc-routetable-data-source" + } } resource "aws_route" "pcx" { - route_table_id = "${aws_route_table.test.id}" - vpc_peering_connection_id = "${aws_vpc_peering_connection.test.id}" - destination_cidr_block = "10.0.2.0/24" + route_table_id = aws_route_table.test.id + vpc_peering_connection_id = aws_vpc_peering_connection.test.id + destination_cidr_block = "10.0.2.0/24" } resource "aws_route_table_association" "a" { - subnet_id = "${aws_subnet.test.id}" - route_table_id = "${aws_route_table.test.id}" + subnet_id = aws_subnet.test.id + route_table_id = aws_route_table.test.id } -data "aws_ami" "ubuntu" { - most_recent = true - - filter { - name = "name" - values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"] - } - - filter { - name = "virtualization-type" - values = ["hvm"] - } - - owners = ["099720109477"] # Canonical - } - - resource "aws_instance" "web" { - ami = "${data.aws_ami.ubuntu.id}" - instance_type = "t2.micro" - subnet_id = "${aws_subnet.test.id}" - tags = { - Name = "HelloWorld" - } - } +resource "aws_instance" "web" { + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + subnet_id = aws_subnet.test.id + tags = { + Name = "HelloWorld" + } +} resource "aws_route" "test" { - route_table_id = "${aws_route_table.test.id}" - destination_cidr_block = "10.0.1.0/24" - instance_id = "${aws_instance.web.id}" - timeouts { - create ="5m" - } -} + route_table_id = aws_route_table.test.id + destination_cidr_block = "10.0.1.0/24" + instance_id = aws_instance.web.id -data "aws_route" "by_peering_connection_id"{ - route_table_id = "${aws_route_table.test.id}" - vpc_peering_connection_id = "${aws_route.pcx.vpc_peering_connection_id}" + timeouts { + create = "5m" + } } -data "aws_route" "by_destination_cidr_block"{ - route_table_id = "${aws_route_table.test.id}" - destination_cidr_block = "10.0.1.0/24" - depends_on = ["aws_route.test"] +data "aws_route" "by_peering_connection_id" { + route_table_id = aws_route_table.test.id + vpc_peering_connection_id = aws_route.pcx.vpc_peering_connection_id } -data "aws_route" "by_instance_id"{ - route_table_id = "${aws_route_table.test.id}" - instance_id = "${aws_instance.web.id}" - depends_on = ["aws_route.test"] +data "aws_route" "by_destination_cidr_block" { + route_table_id = aws_route_table.test.id + destination_cidr_block = "10.0.1.0/24" + depends_on = ["aws_route.test"] } - +data "aws_route" "by_instance_id" { + route_table_id = aws_route_table.test.id + instance_id = aws_instance.web.id + depends_on = ["aws_route.test"] +} ` +} func testAccAWSRouteDataSourceConfigTransitGatewayID() string { - return fmt.Sprintf(` -data "aws_availability_zones" "available" { - # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + ` +# IncorrectState: Transit Gateway is not available in availability zone us-west-2d resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -215,9 +193,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-route-datasource-transit-gateway-id" @@ -227,20 +205,20 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } resource "aws_route" "test" { destination_cidr_block = "0.0.0.0/0" - route_table_id = "${aws_vpc.test.default_route_table_id}" - transit_gateway_id = "${aws_ec2_transit_gateway_vpc_attachment.test.transit_gateway_id}" + route_table_id = aws_vpc.test.default_route_table_id + transit_gateway_id = aws_ec2_transit_gateway_vpc_attachment.test.transit_gateway_id } data "aws_route" "test" { - route_table_id = "${aws_route.test.route_table_id}" - transit_gateway_id = "${aws_route.test.transit_gateway_id}" + route_table_id = aws_route.test.route_table_id + transit_gateway_id = aws_route.test.transit_gateway_id } -`) +` } diff --git a/aws/data_source_aws_s3_bucket.go b/aws/data_source_aws_s3_bucket.go index d423c83fbf9..83358f75ee5 100644 --- a/aws/data_source_aws_s3_bucket.go +++ b/aws/data_source_aws_s3_bucket.go @@ -1,13 +1,16 @@ package aws import ( + "context" "fmt" "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func dataSourceAwsS3Bucket() *schema.Resource { @@ -91,19 +94,16 @@ func dataSourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { } func bucketLocation(client *AWSClient, d *schema.ResourceData, bucket string) error { - location, err := client.s3conn.GetBucketLocation( - &s3.GetBucketLocationInput{ - Bucket: aws.String(bucket), - }, - ) + region, err := s3manager.GetBucketRegionWithClient(context.Background(), client.s3conn, bucket, func(r *request.Request) { + // By default, GetBucketRegion forces virtual host addressing, which + // is not compatible with many non-AWS implementations. Instead, pass + // the provider s3_force_path_style configuration, which defaults to + // false, but allows override. + r.Config.S3ForcePathStyle = client.s3conn.Config.S3ForcePathStyle + }) if err != nil { return err } - var region string - if location.LocationConstraint != nil { - region = *location.LocationConstraint - } - region = normalizeRegion(region) if err := d.Set("region", region); err != nil { return err } diff --git a/aws/data_source_aws_s3_bucket_object.go b/aws/data_source_aws_s3_bucket_object.go index ec7d78300a0..c16060aa933 100644 --- a/aws/data_source_aws_s3_bucket_object.go +++ b/aws/data_source_aws_s3_bucket_object.go @@ -10,7 +10,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -74,6 +74,7 @@ func dataSourceAwsS3BucketObject() *schema.Resource { "metadata": { Type: schema.TypeMap, Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "object_lock_legal_hold_status": { Type: schema.TypeString, diff --git a/aws/data_source_aws_s3_bucket_object_test.go b/aws/data_source_aws_s3_bucket_object_test.go index 9b942d41784..56308b163c6 100644 --- a/aws/data_source_aws_s3_bucket_object_test.go +++ b/aws/data_source_aws_s3_bucket_object_test.go @@ -8,42 +8,40 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) +const rfc1123RegexPattern = `^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$` + func TestAccDataSourceAWSS3BucketObject_basic(t *testing.T) { rInt := acctest.RandInt() - resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_basic(rInt) var rObj s3.GetObjectOutput var dsObj s3.GetObjectOutput + resourceName := "aws_s3_bucket_object.object" + dataSourceName := "data.aws_s3_bucket_object.obj" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: resourceOnlyConf, - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object", &rObj), - ), - }, - { - Config: conf, + Config: testAccAWSDataSourceS3ObjectConfig_basic(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsS3ObjectDataSourceExists("data.aws_s3_bucket_object.obj", &dsObj), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_length", "11"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_type", "binary/octet-stream"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "etag", "b10a8db164e0754105b7a99be72e3fe5"), - resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "last_modified", - regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_legal_hold_status", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_mode", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_retain_until_date", ""), - resource.TestCheckNoResourceAttr("data.aws_s3_bucket_object.obj", "body"), + testAccCheckAWSS3BucketObjectExists(resourceName, &rObj), + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName, &dsObj), + resource.TestCheckResourceAttr(dataSourceName, "content_length", "11"), + resource.TestCheckResourceAttrPair(dataSourceName, "content_type", resourceName, "content_type"), + resource.TestCheckResourceAttrPair(dataSourceName, "etag", resourceName, "etag"), + resource.TestMatchResourceAttr(dataSourceName, "last_modified", regexp.MustCompile(rfc1123RegexPattern)), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_legal_hold_status", resourceName, "object_lock_legal_hold_status"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_mode", resourceName, "object_lock_mode"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_retain_until_date", resourceName, "object_lock_retain_until_date"), + resource.TestCheckNoResourceAttr(dataSourceName, "body"), ), }, }, @@ -53,7 +51,8 @@ func TestAccDataSourceAWSS3BucketObject_basic(t *testing.T) { func TestAccDataSourceAWSS3BucketObject_basicViaAccessPoint(t *testing.T) { var dsObj, rObj s3.GetObjectOutput rName := acctest.RandomWithPrefix("tf-acc-test") - datasourceName := "data.aws_s3_bucket_object.test" + + dataSourceName := "data.aws_s3_bucket_object.test" resourceName := "aws_s3_bucket_object.test" accessPointResourceName := "aws_s3_access_point.test" @@ -64,10 +63,11 @@ func TestAccDataSourceAWSS3BucketObject_basicViaAccessPoint(t *testing.T) { { Config: testAccAWSDataSourceS3ObjectConfig_basicViaAccessPoint(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsS3ObjectDataSourceExists(datasourceName, &dsObj), testAccCheckAWSS3BucketObjectExists(resourceName, &rObj), - resource.TestCheckResourceAttrPair(datasourceName, "bucket", accessPointResourceName, "arn"), - resource.TestCheckResourceAttrPair(datasourceName, "key", resourceName, "key"), + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName, &dsObj), + testAccCheckAWSS3BucketObjectExists(resourceName, &rObj), + resource.TestCheckResourceAttrPair(dataSourceName, "bucket", accessPointResourceName, "arn"), + resource.TestCheckResourceAttrPair(dataSourceName, "key", resourceName, "key"), ), }, }, @@ -76,35 +76,31 @@ func TestAccDataSourceAWSS3BucketObject_basicViaAccessPoint(t *testing.T) { func TestAccDataSourceAWSS3BucketObject_readableBody(t *testing.T) { rInt := acctest.RandInt() - resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_readableBody(rInt) var rObj s3.GetObjectOutput var dsObj s3.GetObjectOutput + resourceName := "aws_s3_bucket_object.object" + dataSourceName := "data.aws_s3_bucket_object.obj" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: resourceOnlyConf, - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object", &rObj), - ), - }, - { - Config: conf, + Config: testAccAWSDataSourceS3ObjectConfig_readableBody(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsS3ObjectDataSourceExists("data.aws_s3_bucket_object.obj", &dsObj), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_length", "3"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_type", "text/plain"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "etag", "a6105c0a611b41b08f1209506350279e"), - resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "last_modified", - regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_legal_hold_status", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_mode", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_retain_until_date", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "body", "yes"), + testAccCheckAWSS3BucketObjectExists(resourceName, &rObj), + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName, &dsObj), + resource.TestCheckResourceAttr(dataSourceName, "content_length", "3"), + resource.TestCheckResourceAttrPair(dataSourceName, "content_type", resourceName, "content_type"), + resource.TestCheckResourceAttrPair(dataSourceName, "etag", resourceName, "etag"), + resource.TestMatchResourceAttr(dataSourceName, "last_modified", regexp.MustCompile(rfc1123RegexPattern)), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_legal_hold_status", resourceName, "object_lock_legal_hold_status"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_mode", resourceName, "object_lock_mode"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_retain_until_date", resourceName, "object_lock_retain_until_date"), + resource.TestCheckResourceAttr(dataSourceName, "body", "yes"), ), }, }, @@ -113,38 +109,33 @@ func TestAccDataSourceAWSS3BucketObject_readableBody(t *testing.T) { func TestAccDataSourceAWSS3BucketObject_kmsEncrypted(t *testing.T) { rInt := acctest.RandInt() - resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_kmsEncrypted(rInt) var rObj s3.GetObjectOutput var dsObj s3.GetObjectOutput + resourceName := "aws_s3_bucket_object.object" + dataSourceName := "data.aws_s3_bucket_object.obj" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: resourceOnlyConf, - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object", &rObj), - ), - }, - { - Config: conf, + Config: testAccAWSDataSourceS3ObjectConfig_kmsEncrypted(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsS3ObjectDataSourceExists("data.aws_s3_bucket_object.obj", &dsObj), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_length", "22"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_type", "text/plain"), - resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "etag", regexp.MustCompile("^[a-f0-9]{32}$")), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "server_side_encryption", "aws:kms"), - resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "sse_kms_key_id", - regexp.MustCompile(`^arn:aws:kms:[a-z]{2}-[a-z]+-\d{1}:[0-9]{12}:key/[a-z0-9-]{36}$`)), - resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "last_modified", - regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_legal_hold_status", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_mode", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_retain_until_date", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "body", "Keep Calm and Carry On"), + testAccCheckAWSS3BucketObjectExists(resourceName, &rObj), + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName, &dsObj), + resource.TestCheckResourceAttr(dataSourceName, "content_length", "22"), + resource.TestCheckResourceAttrPair(dataSourceName, "content_type", resourceName, "content_type"), + resource.TestCheckResourceAttrPair(dataSourceName, "etag", resourceName, "etag"), + resource.TestCheckResourceAttrPair(dataSourceName, "server_side_encryption", resourceName, "server_side_encryption"), + resource.TestCheckResourceAttrPair(dataSourceName, "sse_kms_key_id", resourceName, "kms_key_id"), + resource.TestMatchResourceAttr(dataSourceName, "last_modified", regexp.MustCompile(rfc1123RegexPattern)), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_legal_hold_status", resourceName, "object_lock_legal_hold_status"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_mode", resourceName, "object_lock_mode"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_retain_until_date", resourceName, "object_lock_retain_until_date"), + resource.TestCheckResourceAttr(dataSourceName, "body", "Keep Calm and Carry On"), ), }, }, @@ -153,51 +144,47 @@ func TestAccDataSourceAWSS3BucketObject_kmsEncrypted(t *testing.T) { func TestAccDataSourceAWSS3BucketObject_allParams(t *testing.T) { rInt := acctest.RandInt() - resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_allParams(rInt) var rObj s3.GetObjectOutput var dsObj s3.GetObjectOutput + resourceName := "aws_s3_bucket_object.object" + dataSourceName := "data.aws_s3_bucket_object.obj" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: resourceOnlyConf, - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object", &rObj), - ), - }, - { - Config: conf, + Config: testAccAWSDataSourceS3ObjectConfig_allParams(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsS3ObjectDataSourceExists("data.aws_s3_bucket_object.obj", &dsObj), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_length", "21"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_type", "application/unknown"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "etag", "723f7a6ac0c57b445790914668f98640"), - resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "last_modified", - regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")), - resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "version_id", regexp.MustCompile("^.{32}$")), - resource.TestCheckNoResourceAttr("data.aws_s3_bucket_object.obj", "body"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "cache_control", "no-cache"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_disposition", "attachment"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_encoding", "identity"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_language", "en-GB"), + testAccCheckAWSS3BucketObjectExists(resourceName, &rObj), + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName, &dsObj), + resource.TestCheckResourceAttr(dataSourceName, "content_length", "25"), + resource.TestCheckResourceAttrPair(dataSourceName, "content_type", resourceName, "content_type"), + resource.TestCheckResourceAttrPair(dataSourceName, "etag", resourceName, "etag"), + resource.TestMatchResourceAttr(dataSourceName, "last_modified", regexp.MustCompile(rfc1123RegexPattern)), + resource.TestCheckResourceAttrPair(dataSourceName, "version_id", resourceName, "version_id"), + resource.TestCheckNoResourceAttr(dataSourceName, "body"), + resource.TestCheckResourceAttrPair(dataSourceName, "cache_control", resourceName, "cache_control"), + resource.TestCheckResourceAttrPair(dataSourceName, "content_disposition", resourceName, "content_disposition"), + resource.TestCheckResourceAttrPair(dataSourceName, "content_encoding", resourceName, "content_encoding"), + resource.TestCheckResourceAttrPair(dataSourceName, "content_language", resourceName, "content_language"), // Encryption is off - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "server_side_encryption", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "sse_kms_key_id", ""), + resource.TestCheckResourceAttrPair(dataSourceName, "server_side_encryption", resourceName, "server_side_encryption"), + resource.TestCheckResourceAttr(dataSourceName, "sse_kms_key_id", ""), // Supported, but difficult to reproduce in short testing time - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "storage_class", "STANDARD"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "expiration", ""), + resource.TestCheckResourceAttrPair(dataSourceName, "storage_class", resourceName, "storage_class"), + resource.TestCheckResourceAttr(dataSourceName, "expiration", ""), // Currently unsupported in aws_s3_bucket_object resource - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "expires", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "website_redirect_location", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "metadata.%", "0"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "tags.%", "1"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_legal_hold_status", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_mode", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_retain_until_date", ""), + resource.TestCheckResourceAttr(dataSourceName, "expires", ""), + resource.TestCheckResourceAttrPair(dataSourceName, "website_redirect_location", resourceName, "website_redirect"), + resource.TestCheckResourceAttr(dataSourceName, "metadata.%", "0"), + resource.TestCheckResourceAttr(dataSourceName, "tags.%", "1"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_legal_hold_status", resourceName, "object_lock_legal_hold_status"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_mode", resourceName, "object_lock_mode"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_retain_until_date", resourceName, "object_lock_retain_until_date"), ), }, }, @@ -206,35 +193,31 @@ func TestAccDataSourceAWSS3BucketObject_allParams(t *testing.T) { func TestAccDataSourceAWSS3BucketObject_ObjectLockLegalHoldOff(t *testing.T) { rInt := acctest.RandInt() - resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_objectLockLegalHoldOff(rInt) var rObj s3.GetObjectOutput var dsObj s3.GetObjectOutput + resourceName := "aws_s3_bucket_object.object" + dataSourceName := "data.aws_s3_bucket_object.obj" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: resourceOnlyConf, - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object", &rObj), - ), - }, - { - Config: conf, + Config: testAccAWSDataSourceS3ObjectConfig_objectLockLegalHoldOff(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsS3ObjectDataSourceExists("data.aws_s3_bucket_object.obj", &dsObj), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_length", "11"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_type", "binary/octet-stream"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "etag", "b10a8db164e0754105b7a99be72e3fe5"), - resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "last_modified", - regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_legal_hold_status", "OFF"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_mode", ""), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_retain_until_date", ""), - resource.TestCheckNoResourceAttr("data.aws_s3_bucket_object.obj", "body"), + testAccCheckAWSS3BucketObjectExists(resourceName, &rObj), + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName, &dsObj), + resource.TestCheckResourceAttr(dataSourceName, "content_length", "11"), + resource.TestCheckResourceAttrPair(dataSourceName, "content_type", resourceName, "content_type"), + resource.TestCheckResourceAttrPair(dataSourceName, "etag", resourceName, "etag"), + resource.TestMatchResourceAttr(dataSourceName, "last_modified", regexp.MustCompile(rfc1123RegexPattern)), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_legal_hold_status", resourceName, "object_lock_legal_hold_status"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_mode", resourceName, "object_lock_mode"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_retain_until_date", resourceName, "object_lock_retain_until_date"), + resource.TestCheckNoResourceAttr(dataSourceName, "body"), ), }, }, @@ -244,35 +227,31 @@ func TestAccDataSourceAWSS3BucketObject_ObjectLockLegalHoldOff(t *testing.T) { func TestAccDataSourceAWSS3BucketObject_ObjectLockLegalHoldOn(t *testing.T) { rInt := acctest.RandInt() retainUntilDate := time.Now().UTC().AddDate(0, 0, 10).Format(time.RFC3339) - resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_objectLockLegalHoldOn(rInt, retainUntilDate) var rObj s3.GetObjectOutput var dsObj s3.GetObjectOutput + resourceName := "aws_s3_bucket_object.object" + dataSourceName := "data.aws_s3_bucket_object.obj" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, PreventPostDestroyRefresh: true, Steps: []resource.TestStep{ { - Config: resourceOnlyConf, - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSS3BucketObjectExists("aws_s3_bucket_object.object", &rObj), - ), - }, - { - Config: conf, + Config: testAccAWSDataSourceS3ObjectConfig_objectLockLegalHoldOn(rInt, retainUntilDate), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsS3ObjectDataSourceExists("data.aws_s3_bucket_object.obj", &dsObj), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_length", "11"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "content_type", "binary/octet-stream"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "etag", "b10a8db164e0754105b7a99be72e3fe5"), - resource.TestMatchResourceAttr("data.aws_s3_bucket_object.obj", "last_modified", - regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_legal_hold_status", "ON"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_mode", "GOVERNANCE"), - resource.TestCheckResourceAttr("data.aws_s3_bucket_object.obj", "object_lock_retain_until_date", retainUntilDate), - resource.TestCheckNoResourceAttr("data.aws_s3_bucket_object.obj", "body"), + testAccCheckAWSS3BucketObjectExists(resourceName, &rObj), + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName, &dsObj), + resource.TestCheckResourceAttr(dataSourceName, "content_length", "11"), + resource.TestCheckResourceAttrPair(dataSourceName, "content_type", resourceName, "content_type"), + resource.TestCheckResourceAttrPair(dataSourceName, "etag", resourceName, "etag"), + resource.TestMatchResourceAttr(dataSourceName, "last_modified", regexp.MustCompile(rfc1123RegexPattern)), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_legal_hold_status", resourceName, "object_lock_legal_hold_status"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_mode", resourceName, "object_lock_mode"), + resource.TestCheckResourceAttrPair(dataSourceName, "object_lock_retain_until_date", resourceName, "object_lock_retain_until_date"), + resource.TestCheckNoResourceAttr(dataSourceName, "body"), ), }, }, @@ -282,10 +261,12 @@ func TestAccDataSourceAWSS3BucketObject_ObjectLockLegalHoldOn(t *testing.T) { func TestAccDataSourceAWSS3BucketObject_LeadingSlash(t *testing.T) { var rObj s3.GetObjectOutput var dsObj1, dsObj2, dsObj3 s3.GetObjectOutput + resourceName := "aws_s3_bucket_object.object" dataSourceName1 := "data.aws_s3_bucket_object.obj1" dataSourceName2 := "data.aws_s3_bucket_object.obj2" dataSourceName3 := "data.aws_s3_bucket_object.obj3" + rInt := acctest.RandInt() resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_leadingSlash(rInt) @@ -305,24 +286,23 @@ func TestAccDataSourceAWSS3BucketObject_LeadingSlash(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsS3ObjectDataSourceExists(dataSourceName1, &dsObj1), resource.TestCheckResourceAttr(dataSourceName1, "content_length", "3"), - resource.TestCheckResourceAttr(dataSourceName1, "content_type", "text/plain"), - resource.TestCheckResourceAttr(dataSourceName1, "etag", "a6105c0a611b41b08f1209506350279e"), - resource.TestMatchResourceAttr(dataSourceName1, "last_modified", - regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")), + resource.TestCheckResourceAttrPair(dataSourceName1, "content_type", resourceName, "content_type"), + resource.TestCheckResourceAttrPair(dataSourceName1, "etag", resourceName, "etag"), + resource.TestMatchResourceAttr(dataSourceName1, "last_modified", regexp.MustCompile(rfc1123RegexPattern)), resource.TestCheckResourceAttr(dataSourceName1, "body", "yes"), + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName2, &dsObj2), resource.TestCheckResourceAttr(dataSourceName2, "content_length", "3"), - resource.TestCheckResourceAttr(dataSourceName2, "content_type", "text/plain"), - resource.TestCheckResourceAttr(dataSourceName2, "etag", "a6105c0a611b41b08f1209506350279e"), - resource.TestMatchResourceAttr(dataSourceName2, "last_modified", - regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")), + resource.TestCheckResourceAttrPair(dataSourceName2, "content_type", resourceName, "content_type"), + resource.TestCheckResourceAttrPair(dataSourceName2, "etag", resourceName, "etag"), + resource.TestMatchResourceAttr(dataSourceName2, "last_modified", regexp.MustCompile(rfc1123RegexPattern)), resource.TestCheckResourceAttr(dataSourceName2, "body", "yes"), + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName3, &dsObj3), resource.TestCheckResourceAttr(dataSourceName3, "content_length", "3"), - resource.TestCheckResourceAttr(dataSourceName3, "content_type", "text/plain"), - resource.TestCheckResourceAttr(dataSourceName3, "etag", "a6105c0a611b41b08f1209506350279e"), - resource.TestMatchResourceAttr(dataSourceName3, "last_modified", - regexp.MustCompile("^[a-zA-Z]{3}, [0-9]+ [a-zA-Z]+ [0-9]{4} [0-9:]+ [A-Z]+$")), + resource.TestCheckResourceAttrPair(dataSourceName3, "content_type", resourceName, "content_type"), + resource.TestCheckResourceAttrPair(dataSourceName3, "etag", resourceName, "etag"), + resource.TestMatchResourceAttr(dataSourceName3, "last_modified", regexp.MustCompile(rfc1123RegexPattern)), resource.TestCheckResourceAttr(dataSourceName3, "body", "yes"), ), }, @@ -333,11 +313,13 @@ func TestAccDataSourceAWSS3BucketObject_LeadingSlash(t *testing.T) { func TestAccDataSourceAWSS3BucketObject_MultipleSlashes(t *testing.T) { var rObj1, rObj2 s3.GetObjectOutput var dsObj1, dsObj2, dsObj3 s3.GetObjectOutput + resourceName1 := "aws_s3_bucket_object.object1" resourceName2 := "aws_s3_bucket_object.object2" dataSourceName1 := "data.aws_s3_bucket_object.obj1" dataSourceName2 := "data.aws_s3_bucket_object.obj2" dataSourceName3 := "data.aws_s3_bucket_object.obj3" + rInt := acctest.RandInt() resourceOnlyConf, conf := testAccAWSDataSourceS3ObjectConfig_multipleSlashes(rInt) @@ -356,17 +338,20 @@ func TestAccDataSourceAWSS3BucketObject_MultipleSlashes(t *testing.T) { { Config: conf, Check: resource.ComposeTestCheckFunc( + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName1, &dsObj1), resource.TestCheckResourceAttr(dataSourceName1, "content_length", "3"), - resource.TestCheckResourceAttr(dataSourceName1, "content_type", "text/plain"), + resource.TestCheckResourceAttrPair(dataSourceName1, "content_type", resourceName1, "content_type"), resource.TestCheckResourceAttr(dataSourceName1, "body", "yes"), + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName2, &dsObj2), resource.TestCheckResourceAttr(dataSourceName2, "content_length", "3"), - resource.TestCheckResourceAttr(dataSourceName2, "content_type", "text/plain"), + resource.TestCheckResourceAttrPair(dataSourceName2, "content_type", resourceName1, "content_type"), resource.TestCheckResourceAttr(dataSourceName2, "body", "yes"), + testAccCheckAwsS3ObjectDataSourceExists(dataSourceName3, &dsObj3), resource.TestCheckResourceAttr(dataSourceName3, "content_length", "2"), - resource.TestCheckResourceAttr(dataSourceName3, "content_type", "text/plain"), + resource.TestCheckResourceAttrPair(dataSourceName3, "content_type", resourceName2, "content_type"), resource.TestCheckResourceAttr(dataSourceName3, "body", "no"), ), }, @@ -402,26 +387,23 @@ func testAccCheckAwsS3ObjectDataSourceExists(n string, obj *s3.GetObjectOutput) } } -func testAccAWSDataSourceS3ObjectConfig_basic(randInt int) (string, string) { - resources := fmt.Sprintf(` +func testAccAWSDataSourceS3ObjectConfig_basic(randInt int) string { + return fmt.Sprintf(` resource "aws_s3_bucket" "object_bucket" { - bucket = "tf-object-test-bucket-%d" + bucket = "tf-object-test-bucket-%[1]d" } + resource "aws_s3_bucket_object" "object" { - bucket = "${aws_s3_bucket.object_bucket.bucket}" - key = "tf-testing-obj-%d" - content = "Hello World" + bucket = aws_s3_bucket.object_bucket.bucket + key = "tf-testing-obj-%[1]d" + content = "Hello World" } -`, randInt, randInt) - both := fmt.Sprintf(`%s data "aws_s3_bucket_object" "obj" { - bucket = "tf-object-test-bucket-%d" - key = "tf-testing-obj-%d" + bucket = aws_s3_bucket.object_bucket.bucket + key = aws_s3_bucket_object.object.key } -`, resources, randInt, randInt) - - return resources, both +`, randInt) } func testAccAWSDataSourceS3ObjectConfig_basicViaAccessPoint(rName string) string { @@ -431,114 +413,110 @@ resource "aws_s3_bucket" "test" { } resource "aws_s3_access_point" "test" { - bucket = "${aws_s3_bucket.test.bucket}" + bucket = aws_s3_bucket.test.bucket name = %[1]q } resource "aws_s3_bucket_object" "test" { - bucket = "${aws_s3_bucket.test.bucket}" + bucket = aws_s3_bucket.test.bucket key = %[1]q content = "Hello World" } data "aws_s3_bucket_object" "test" { - bucket = "${aws_s3_access_point.test.arn}" - key = "${aws_s3_bucket_object.test.key}" + bucket = aws_s3_access_point.test.arn + key = aws_s3_bucket_object.test.key } `, rName) } -func testAccAWSDataSourceS3ObjectConfig_readableBody(randInt int) (string, string) { - resources := fmt.Sprintf(` +func testAccAWSDataSourceS3ObjectConfig_readableBody(randInt int) string { + return fmt.Sprintf(` resource "aws_s3_bucket" "object_bucket" { - bucket = "tf-object-test-bucket-%d" + bucket = "tf-object-test-bucket-%[1]d" } + resource "aws_s3_bucket_object" "object" { - bucket = "${aws_s3_bucket.object_bucket.bucket}" - key = "tf-testing-obj-%d-readable" - content = "yes" - content_type = "text/plain" + bucket = aws_s3_bucket.object_bucket.bucket + key = "tf-testing-obj-%[1]d-readable" + content = "yes" + content_type = "text/plain" } -`, randInt, randInt) - both := fmt.Sprintf(`%s data "aws_s3_bucket_object" "obj" { - bucket = "tf-object-test-bucket-%d" - key = "tf-testing-obj-%d-readable" + bucket = aws_s3_bucket.object_bucket.bucket + key = aws_s3_bucket_object.object.key } -`, resources, randInt, randInt) - - return resources, both +`, randInt) } -func testAccAWSDataSourceS3ObjectConfig_kmsEncrypted(randInt int) (string, string) { - resources := fmt.Sprintf(` +func testAccAWSDataSourceS3ObjectConfig_kmsEncrypted(randInt int) string { + return fmt.Sprintf(` resource "aws_s3_bucket" "object_bucket" { - bucket = "tf-object-test-bucket-%d" + bucket = "tf-object-test-bucket-%[1]d" } + resource "aws_kms_key" "example" { description = "TF Acceptance Test KMS key" deletion_window_in_days = 7 } + resource "aws_s3_bucket_object" "object" { - bucket = "${aws_s3_bucket.object_bucket.bucket}" - key = "tf-testing-obj-%d-encrypted" - content = "Keep Calm and Carry On" - content_type = "text/plain" - kms_key_id = "${aws_kms_key.example.arn}" + bucket = aws_s3_bucket.object_bucket.bucket + key = "tf-testing-obj-%[1]d-encrypted" + content = "Keep Calm and Carry On" + content_type = "text/plain" + kms_key_id = aws_kms_key.example.arn } -`, randInt, randInt) - both := fmt.Sprintf(`%s data "aws_s3_bucket_object" "obj" { - bucket = "tf-object-test-bucket-%d" - key = "tf-testing-obj-%d-encrypted" + bucket = aws_s3_bucket.object_bucket.bucket + key = aws_s3_bucket_object.object.key } -`, resources, randInt, randInt) - - return resources, both +`, randInt) } -func testAccAWSDataSourceS3ObjectConfig_allParams(randInt int) (string, string) { - resources := fmt.Sprintf(` +func testAccAWSDataSourceS3ObjectConfig_allParams(randInt int) string { + return fmt.Sprintf(` resource "aws_s3_bucket" "object_bucket" { - bucket = "tf-object-test-bucket-%d" - versioning { - enabled = true - } + bucket = "tf-object-test-bucket-%[1]d" + + versioning { + enabled = true + } } resource "aws_s3_bucket_object" "object" { - bucket = "${aws_s3_bucket.object_bucket.bucket}" - key = "tf-testing-obj-%d-all-params" - content = < 0 && v[0] != nil { + muo := elasticsearch.MasterUserOptions{} + masterUserOptions := v[0].(map[string]interface{}) + + if v, ok := masterUserOptions["master_user_arn"].(string); ok && v != "" { + muo.MasterUserARN = aws.String(v) + } + + if v, ok := masterUserOptions["master_user_name"].(string); ok && v != "" { + muo.MasterUserName = aws.String(v) + } + + if v, ok := masterUserOptions["master_user_password"].(string); ok && v != "" { + muo.MasterUserPassword = aws.String(v) + } + + config.SetMasterUserOptions(&muo) + } + } + } + } + + return &config +} + +func flattenAdvancedSecurityOptions(advancedSecurityOptions *elasticsearch.AdvancedSecurityOptions) []map[string]interface{} { + if advancedSecurityOptions == nil { + return []map[string]interface{}{} + } + + m := map[string]interface{}{} + m["enabled"] = aws.BoolValue(advancedSecurityOptions.Enabled) + if aws.BoolValue(advancedSecurityOptions.Enabled) { + m["internal_user_database_enabled"] = aws.BoolValue(advancedSecurityOptions.InternalUserDatabaseEnabled) + } + + return []map[string]interface{}{m} +} + +func getMasterUserOptions(d *schema.ResourceData) []interface{} { + if v, ok := d.GetOk("advanced_security_options"); ok { + options := v.([]interface{}) + if len(options) > 0 && options[0] != nil { + m := options[0].(map[string]interface{}) + if opts, ok := m["master_user_options"]; ok { + return opts.([]interface{}) + } + } + } + return []interface{}{} +} + +func getUserDBEnabled(d *schema.ResourceData) bool { + if v, ok := d.GetOk("advanced_security_options"); ok { + options := v.([]interface{}) + if len(options) > 0 && options[0] != nil { + m := options[0].(map[string]interface{}) + if enabled, ok := m["internal_user_database_enabled"]; ok { + return enabled.(bool) + } + } + } + return false +} diff --git a/aws/fsx.go b/aws/fsx.go index 020002f8575..5468112b962 100644 --- a/aws/fsx.go +++ b/aws/fsx.go @@ -5,7 +5,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/fsx" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func describeFsxFileSystem(conn *fsx.FSx, id string) (*fsx.FileSystem, error) { diff --git a/aws/import_aws_cloudfront_distribution.go b/aws/import_aws_cloudfront_distribution.go deleted file mode 100644 index a2635d47bb1..00000000000 --- a/aws/import_aws_cloudfront_distribution.go +++ /dev/null @@ -1,33 +0,0 @@ -package aws - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/cloudfront" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -func resourceAwsCloudFrontDistributionImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - // This is a non API attribute - // We are merely setting this to the same value as the Default setting in the schema - d.Set("retain_on_delete", false) - d.Set("wait_for_deployment", true) - - conn := meta.(*AWSClient).cloudfrontconn - id := d.Id() - resp, err := conn.GetDistributionConfig(&cloudfront.GetDistributionConfigInput{ - Id: aws.String(id), - }) - - if err != nil { - return nil, err - } - - distConfig := resp.DistributionConfig - results := make([]*schema.ResourceData, 1) - err = flattenDistributionConfig(d, distConfig) - if err != nil { - return nil, err - } - results[0] = d - return results, nil -} diff --git a/aws/import_aws_db_event_subscription.go b/aws/import_aws_db_event_subscription.go deleted file mode 100644 index bdc31bad533..00000000000 --- a/aws/import_aws_db_event_subscription.go +++ /dev/null @@ -1,17 +0,0 @@ -package aws - -import "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - -func resourceAwsDbEventSubscriptionImport( - d *schema.ResourceData, - meta interface{}) ([]*schema.ResourceData, error) { - - // The db event subscription Read function only needs the "name" of the event subscription - // in order to populate the necessary values. This takes the "id" from the supplied StateFunc - // and sets it as the "name" attribute, as described in the import documentation. This allows - // the Read function to actually succeed and set the ID of the resource - results := make([]*schema.ResourceData, 1) - d.Set("name", d.Id()) - results[0] = d - return results, nil -} diff --git a/aws/import_aws_network_acl.go b/aws/import_aws_network_acl.go deleted file mode 100644 index be2c6c164bd..00000000000 --- a/aws/import_aws_network_acl.go +++ /dev/null @@ -1,95 +0,0 @@ -package aws - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -// Network ACLs import their rules and associations -func resourceAwsNetworkAclImportState( - d *schema.ResourceData, - meta interface{}) ([]*schema.ResourceData, error) { - conn := meta.(*AWSClient).ec2conn - - // First query the resource itself - resp, err := conn.DescribeNetworkAcls(&ec2.DescribeNetworkAclsInput{ - NetworkAclIds: []*string{aws.String(d.Id())}, - }) - if err != nil { - return nil, err - } - if resp == nil || len(resp.NetworkAcls) < 1 || resp.NetworkAcls[0] == nil { - return nil, fmt.Errorf("network ACL %s is not found", d.Id()) - } - acl := resp.NetworkAcls[0] - - // Start building our results - results := make([]*schema.ResourceData, 1, - 2+len(acl.Associations)+len(acl.Entries)) - results[0] = d - - /* - { - // Construct the entries - subResource := resourceAwsNetworkAclRule() - for _, entry := range acl.Entries { - // Minimal data for route - d := subResource.Data(nil) - d.SetType("aws_network_acl_rule") - d.Set("network_acl_id", acl.NetworkAclId) - d.Set("rule_number", entry.RuleNumber) - d.Set("egress", entry.Egress) - d.Set("protocol", entry.Protocol) - d.SetId(networkAclIdRuleNumberEgressHash( - d.Get("network_acl_id").(string), - d.Get("rule_number").(int), - d.Get("egress").(bool), - d.Get("protocol").(string))) - results = append(results, d) - } - } - - { - // Construct the associations - subResource := resourceAwsRouteTableAssociation() - for _, assoc := range table.Associations { - if *assoc.Main { - // Ignore - continue - } - - // Minimal data for route - d := subResource.Data(nil) - d.SetType("aws_route_table_association") - d.Set("route_table_id", assoc.RouteTableId) - d.SetId(*assoc.RouteTableAssociationId) - results = append(results, d) - } - } - - { - // Construct the main associations. We could do this above but - // I keep this as a separate section since it is a separate resource. - subResource := resourceAwsMainRouteTableAssociation() - for _, assoc := range table.Associations { - if !*assoc.Main { - // Ignore - continue - } - - // Minimal data for route - d := subResource.Data(nil) - d.SetType("aws_main_route_table_association") - d.Set("route_table_id", id) - d.Set("vpc_id", table.VpcId) - d.SetId(*assoc.RouteTableAssociationId) - results = append(results, d) - } - } - */ - - return results, nil -} diff --git a/aws/import_aws_s3_bucket.go b/aws/import_aws_s3_bucket.go deleted file mode 100644 index 987bb180d14..00000000000 --- a/aws/import_aws_s3_bucket.go +++ /dev/null @@ -1,40 +0,0 @@ -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/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -func resourceAwsS3BucketImportState( - d *schema.ResourceData, - meta interface{}) ([]*schema.ResourceData, error) { - - results := make([]*schema.ResourceData, 1) - results[0] = d - - conn := meta.(*AWSClient).s3conn - pol, err := conn.GetBucketPolicy(&s3.GetBucketPolicyInput{ - Bucket: aws.String(d.Id()), - }) - if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchBucketPolicy" { - // Bucket without policy - return results, nil - } - return nil, fmt.Errorf("Error importing AWS S3 bucket policy: %s", err) - } - - policy := resourceAwsS3BucketPolicy() - pData := policy.Data(nil) - pData.SetId(d.Id()) - pData.SetType("aws_s3_bucket_policy") - pData.Set("bucket", d.Id()) - pData.Set("policy", pol.Policy) - results = append(results, pData) - - return results, nil -} diff --git a/aws/import_aws_security_group.go b/aws/import_aws_security_group.go deleted file mode 100644 index de7ceebab8a..00000000000 --- a/aws/import_aws_security_group.go +++ /dev/null @@ -1,192 +0,0 @@ -package aws - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/terraform-providers/terraform-provider-aws/aws/internal/naming" -) - -// Security group import fans out to multiple resources due to the -// security group rules. Instead of creating one resource with nested -// rules, we use the best practices approach of one resource per rule. -func resourceAwsSecurityGroupImportState( - d *schema.ResourceData, - meta interface{}) ([]*schema.ResourceData, error) { - conn := meta.(*AWSClient).ec2conn - - // First query the security group - sgRaw, _, err := SGStateRefreshFunc(conn, d.Id())() - if err != nil { - return nil, err - } - if sgRaw == nil { - return nil, fmt.Errorf("security group not found") - } - sg := sgRaw.(*ec2.SecurityGroup) - - // Perform nil check to avoid ImportStateVerify difference when unconfigured - if namePrefix := naming.NamePrefixFromName(aws.StringValue(sg.GroupName)); namePrefix != nil { - d.Set("name_prefix", namePrefix) - } - - // Start building our results - results := make([]*schema.ResourceData, 1, - 1+len(sg.IpPermissions)+len(sg.IpPermissionsEgress)) - results[0] = d - - // Construct the rules - permMap := map[string][]*ec2.IpPermission{ - "ingress": sg.IpPermissions, - "egress": sg.IpPermissionsEgress, - } - for ruleType, perms := range permMap { - for _, perm := range perms { - ds, err := resourceAwsSecurityGroupImportStatePerm(sg, ruleType, perm) - if err != nil { - return nil, err - } - results = append(results, ds...) - } - } - - return results, nil -} - -func resourceAwsSecurityGroupImportStatePerm(sg *ec2.SecurityGroup, ruleType string, perm *ec2.IpPermission) ([]*schema.ResourceData, error) { - /* - Create a separate Security Group Rule for: - * The collection of IpRanges (cidr_blocks) - * The collection of Ipv6Ranges (ipv6_cidr_blocks) - * Each individual UserIdGroupPair (source_security_group_id) - - If, for example, a security group has rules for: - * 2 IpRanges - * 2 Ipv6Ranges - * 2 UserIdGroupPairs - - This would generate 4 security group rules: - * 1 for the collection of IpRanges - * 1 for the collection of Ipv6Ranges - * 1 for the first UserIdGroupPair - * 1 for the second UserIdGroupPair - */ - var result []*schema.ResourceData - - if perm.IpRanges != nil { - p := &ec2.IpPermission{ - FromPort: perm.FromPort, - IpProtocol: perm.IpProtocol, - PrefixListIds: perm.PrefixListIds, - ToPort: perm.ToPort, - IpRanges: perm.IpRanges, - } - - r, err := resourceAwsSecurityGroupImportStatePermPair(sg, ruleType, p) - if err != nil { - return nil, err - } - result = append(result, r) - } - - if perm.Ipv6Ranges != nil { - p := &ec2.IpPermission{ - FromPort: perm.FromPort, - IpProtocol: perm.IpProtocol, - PrefixListIds: perm.PrefixListIds, - ToPort: perm.ToPort, - Ipv6Ranges: perm.Ipv6Ranges, - } - - r, err := resourceAwsSecurityGroupImportStatePermPair(sg, ruleType, p) - if err != nil { - return nil, err - } - result = append(result, r) - } - - if len(perm.UserIdGroupPairs) > 0 { - for _, pair := range perm.UserIdGroupPairs { - p := &ec2.IpPermission{ - FromPort: perm.FromPort, - IpProtocol: perm.IpProtocol, - PrefixListIds: perm.PrefixListIds, - ToPort: perm.ToPort, - UserIdGroupPairs: []*ec2.UserIdGroupPair{pair}, - } - - r, err := resourceAwsSecurityGroupImportStatePermPair(sg, ruleType, p) - if err != nil { - return nil, err - } - 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 -} - -func resourceAwsSecurityGroupImportStatePermPair(sg *ec2.SecurityGroup, ruleType string, perm *ec2.IpPermission) (*schema.ResourceData, error) { - // Construct the rule. We do this by populating the absolute - // minimum necessary for Refresh on the rule to work. This - // happens to be a lot of fields since they're almost all needed - // for de-dupping. - sgId := sg.GroupId - id := ipPermissionIDHash(*sgId, ruleType, perm) - ruleResource := resourceAwsSecurityGroupRule() - d := ruleResource.Data(nil) - d.SetId(id) - d.SetType("aws_security_group_rule") - d.Set("security_group_id", sgId) - d.Set("type", ruleType) - - // 'self' is false by default. Below, we range over the group ids and set true - // if the parent sg id is found - d.Set("self", false) - - if len(perm.UserIdGroupPairs) > 0 { - s := perm.UserIdGroupPairs[0] - - // Check for Pair that is the same as the Security Group, to denote self. - // Otherwise, mark the group id in source_security_group_id - isVPC := sg.VpcId != nil && *sg.VpcId != "" - if isVPC { - if *s.GroupId == *sg.GroupId { - d.Set("self", true) - // prune the self reference from the UserIdGroupPairs, so we don't - // have duplicate sg ids (both self and in source_security_group_id) - perm.UserIdGroupPairs = append(perm.UserIdGroupPairs[:0], perm.UserIdGroupPairs[0+1:]...) - } - } else { - if *s.GroupName == *sg.GroupName { - d.Set("self", true) - // prune the self reference from the UserIdGroupPairs, so we don't - // have duplicate sg ids (both self and in source_security_group_id) - perm.UserIdGroupPairs = append(perm.UserIdGroupPairs[:0], perm.UserIdGroupPairs[0+1:]...) - } - } - } - - if err := setFromIPPerm(d, sg, perm); err != nil { - return nil, fmt.Errorf("Error importing AWS Security Group: %s", err) - } - - return d, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/encryption/encryption.go b/aws/internal/encryption/encryption.go similarity index 77% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/encryption/encryption.go rename to aws/internal/encryption/encryption.go index 110ed18cd96..ffbce2b726f 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/encryption/encryption.go +++ b/aws/internal/encryption/encryption.go @@ -5,8 +5,7 @@ import ( "fmt" "strings" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/terraform-plugin-sdk/internal/vault/helper/pgpkeys" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/vault/helper/pgpkeys" ) // RetrieveGPGKey returns the PGP key specified as the pgpKey parameter, or queries @@ -19,7 +18,7 @@ func RetrieveGPGKey(pgpKey string) (string, error) { if strings.HasPrefix(pgpKey, keybasePrefix) { publicKeys, err := pgpkeys.FetchKeybasePubkeys([]string{pgpKey}) if err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("Error retrieving Public Key for %s: {{err}}", pgpKey), err) + return "", fmt.Errorf("Error retrieving Public Key for %s: %w", pgpKey, err) } encryptionKey = publicKeys[pgpKey] } @@ -33,7 +32,7 @@ func EncryptValue(encryptionKey, value, description string) (string, string, err fingerprints, encryptedValue, err := pgpkeys.EncryptShares([][]byte{[]byte(value)}, []string{encryptionKey}) if err != nil { - return "", "", errwrap.Wrapf(fmt.Sprintf("Error encrypting %s: {{err}}", description), err) + return "", "", fmt.Errorf("Error encrypting %s: %w", description, err) } return fingerprints[0], base64.StdEncoding.EncodeToString(encryptedValue[0]), nil diff --git a/aws/internal/experimental/sync/sync.go b/aws/internal/experimental/sync/sync.go new file mode 100644 index 00000000000..bf363e89b08 --- /dev/null +++ b/aws/internal/experimental/sync/sync.go @@ -0,0 +1,48 @@ +package sync + +import ( + "fmt" + "os" + "strconv" + "testing" +) + +// Semaphore can be used to limit concurrent executions. This can be used to work with resources with low quotas +type Semaphore chan struct{} + +// InitializeSemaphore initializes a semaphore with a default capacity or overrides it using an environment variable +// NOTE: this is currently an experimental feature and is likely to change. DO NOT USE. +func InitializeSemaphore(envvar string, defaultLimit int) Semaphore { + limit := defaultLimit + x := os.Getenv(envvar) + if x != "" { + var err error + limit, err = strconv.Atoi(x) + if err != nil { + panic(fmt.Errorf("could not parse %q: expected integer, got %q", envvar, x)) + } + } + return make(Semaphore, limit) +} + +// Wait waits for a semaphore before continuing +// NOTE: this is currently an experimental feature and is likely to change. DO NOT USE. +func (s Semaphore) Wait() { + s <- struct{}{} +} + +// Notify releases a semaphore +// NOTE: this is currently an experimental feature and is likely to change. DO NOT USE. +func (s Semaphore) Notify() { + <-s +} + +// TestAccPreCheckSyncronized waits for a semaphore and skips the test if there is no capacity +// NOTE: this is currently an experimental feature and is likely to change. DO NOT USE. +func TestAccPreCheckSyncronize(t *testing.T, semaphore Semaphore, resource string) { + if cap(semaphore) == 0 { + t.Skipf("concurrency for %s testing set to 0", resource) + } + + semaphore.Wait() +} diff --git a/aws/internal/flatmap/README.md b/aws/internal/flatmap/README.md deleted file mode 100644 index 45c85d8c8d0..00000000000 --- a/aws/internal/flatmap/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# flatmap - -This package contains legacy code from `github.com/hashicorp/terraform/flatmap@v0.12.9`. The types and functions within this package should not be used in any future implementations. diff --git a/aws/internal/flatmap/flatten.go b/aws/internal/flatmap/flatten.go deleted file mode 100644 index 9ff6e426526..00000000000 --- a/aws/internal/flatmap/flatten.go +++ /dev/null @@ -1,71 +0,0 @@ -package flatmap - -import ( - "fmt" - "reflect" -) - -// Flatten takes a structure and turns into a flat map[string]string. -// -// Within the "thing" parameter, only primitive values are allowed. Structs are -// not supported. Therefore, it can only be slices, maps, primitives, and -// any combination of those together. -// -// See the tests for examples of what inputs are turned into. -func Flatten(thing map[string]interface{}) Map { - result := make(map[string]string) - - for k, raw := range thing { - flatten(result, k, reflect.ValueOf(raw)) - } - - return Map(result) -} - -func flatten(result map[string]string, prefix string, v reflect.Value) { - if v.Kind() == reflect.Interface { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Bool: - if v.Bool() { - result[prefix] = "true" - } else { - result[prefix] = "false" - } - case reflect.Int: - result[prefix] = fmt.Sprintf("%d", v.Int()) - case reflect.Map: - flattenMap(result, prefix, v) - case reflect.Slice: - flattenSlice(result, prefix, v) - case reflect.String: - result[prefix] = v.String() - default: - panic(fmt.Sprintf("Unknown: %s", v)) - } -} - -func flattenMap(result map[string]string, prefix string, v reflect.Value) { - for _, k := range v.MapKeys() { - if k.Kind() == reflect.Interface { - k = k.Elem() - } - - if k.Kind() != reflect.String { - panic(fmt.Sprintf("%s: map key is not string: %s", prefix, k)) - } - - flatten(result, fmt.Sprintf("%s.%s", prefix, k.String()), v.MapIndex(k)) - } -} - -func flattenSlice(result map[string]string, prefix string, v reflect.Value) { - prefix = prefix + "." - - result[prefix+"#"] = fmt.Sprintf("%d", v.Len()) - for i := 0; i < v.Len(); i++ { - flatten(result, fmt.Sprintf("%s%d", prefix, i), v.Index(i)) - } -} diff --git a/aws/internal/flatmap/flatten_test.go b/aws/internal/flatmap/flatten_test.go deleted file mode 100644 index 9abd22dee9b..00000000000 --- a/aws/internal/flatmap/flatten_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package flatmap - -import ( - "reflect" - "testing" -) - -func TestFlatten(t *testing.T) { - cases := []struct { - Input map[string]interface{} - Output map[string]string - }{ - { - Input: map[string]interface{}{ - "foo": "bar", - "bar": "baz", - }, - Output: map[string]string{ - "foo": "bar", - "bar": "baz", - }, - }, - - { - Input: map[string]interface{}{ - "foo": []string{ - "one", - "two", - }, - }, - Output: map[string]string{ - "foo.#": "2", - "foo.0": "one", - "foo.1": "two", - }, - }, - - { - Input: map[string]interface{}{ - "foo": []map[interface{}]interface{}{ - { - "name": "bar", - "port": 3000, - "enabled": true, - }, - }, - }, - Output: map[string]string{ - "foo.#": "1", - "foo.0.name": "bar", - "foo.0.port": "3000", - "foo.0.enabled": "true", - }, - }, - - { - Input: map[string]interface{}{ - "foo": []map[interface{}]interface{}{ - { - "name": "bar", - "ports": []string{ - "1", - "2", - }, - }, - }, - }, - Output: map[string]string{ - "foo.#": "1", - "foo.0.name": "bar", - "foo.0.ports.#": "2", - "foo.0.ports.0": "1", - "foo.0.ports.1": "2", - }, - }, - } - - for _, tc := range cases { - actual := Flatten(tc.Input) - if !reflect.DeepEqual(actual, Map(tc.Output)) { - t.Fatalf( - "Input:\n\n%#v\n\nOutput:\n\n%#v\n\nExpected:\n\n%#v\n", - tc.Input, - actual, - tc.Output) - } - } -} diff --git a/aws/internal/flatmap/map.go b/aws/internal/flatmap/map.go deleted file mode 100644 index 435e04a39db..00000000000 --- a/aws/internal/flatmap/map.go +++ /dev/null @@ -1,82 +0,0 @@ -package flatmap - -import ( - "strings" -) - -// Map is a wrapper around map[string]string that provides some helpers -// above it that assume the map is in the format that flatmap expects -// (the result of Flatten). -// -// All modifying functions such as Delete are done in-place unless -// otherwise noted. -type Map map[string]string - -// Contains returns true if the map contains the given key. -func (m Map) Contains(key string) bool { - for _, k := range m.Keys() { - if k == key { - return true - } - } - - return false -} - -// Delete deletes a key out of the map with the given prefix. -func (m Map) Delete(prefix string) { - for k := range m { - match := k == prefix - if !match { - if !strings.HasPrefix(k, prefix) { - continue - } - - if k[len(prefix):len(prefix)+1] != "." { - continue - } - } - - delete(m, k) - } -} - -// Keys returns all of the top-level keys in this map -func (m Map) Keys() []string { - ks := make(map[string]struct{}) - for k := range m { - idx := strings.Index(k, ".") - if idx == -1 { - idx = len(k) - } - - ks[k[:idx]] = struct{}{} - } - - result := make([]string, 0, len(ks)) - for k := range ks { - result = append(result, k) - } - - return result -} - -// Merge merges the contents of the other Map into this one. -// -// This merge is smarter than a simple map iteration because it -// will fully replace arrays and other complex structures that -// are present in this map with the other map's. For example, if -// this map has a 3 element "foo" list, and m2 has a 2 element "foo" -// list, then the result will be that m has a 2 element "foo" -// list. -func (m Map) Merge(m2 Map) { - for _, prefix := range m2.Keys() { - m.Delete(prefix) - - for k, v := range m2 { - if strings.HasPrefix(k, prefix) { - m[k] = v - } - } - } -} diff --git a/aws/internal/flatmap/map_test.go b/aws/internal/flatmap/map_test.go deleted file mode 100644 index ea767d54fd5..00000000000 --- a/aws/internal/flatmap/map_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package flatmap - -import ( - "reflect" - "sort" - "testing" -) - -func TestMapContains(t *testing.T) { - cases := []struct { - Input map[string]string - Key string - Result bool - }{ - { - Input: map[string]string{ - "foo": "bar", - "bar": "nope", - }, - Key: "foo", - Result: true, - }, - - { - Input: map[string]string{ - "foo": "bar", - "bar": "nope", - }, - Key: "baz", - Result: false, - }, - } - - for i, tc := range cases { - actual := Map(tc.Input).Contains(tc.Key) - if actual != tc.Result { - t.Fatalf("case %d bad: %#v", i, tc.Input) - } - } -} - -func TestMapDelete(t *testing.T) { - m := Flatten(map[string]interface{}{ - "foo": "bar", - "routes": []map[string]string{ - { - "foo": "bar", - }, - }, - }) - - m.Delete("routes") - - expected := Map(map[string]string{"foo": "bar"}) - if !reflect.DeepEqual(m, expected) { - t.Fatalf("bad: %#v", m) - } -} - -func TestMapKeys(t *testing.T) { - cases := []struct { - Input map[string]string - Output []string - }{ - { - Input: map[string]string{ - "foo": "bar", - "bar.#": "bar", - "bar.0.foo": "bar", - "bar.0.baz": "bar", - }, - Output: []string{ - "bar", - "foo", - }, - }, - } - - for _, tc := range cases { - actual := Map(tc.Input).Keys() - - // Sort so we have a consistent view of the output - sort.Strings(actual) - - if !reflect.DeepEqual(actual, tc.Output) { - t.Fatalf("input: %#v\n\nbad: %#v", tc.Input, actual) - } - } -} - -func TestMapMerge(t *testing.T) { - cases := []struct { - One map[string]string - Two map[string]string - Result map[string]string - }{ - { - One: map[string]string{ - "foo": "bar", - "bar": "nope", - }, - Two: map[string]string{ - "bar": "baz", - "baz": "buz", - }, - Result: map[string]string{ - "foo": "bar", - "bar": "baz", - "baz": "buz", - }, - }, - } - - for i, tc := range cases { - Map(tc.One).Merge(Map(tc.Two)) - if !reflect.DeepEqual(tc.One, tc.Result) { - t.Fatalf("case %d bad: %#v", i, tc.One) - } - } -} diff --git a/aws/internal/hashcode/hashcode.go b/aws/internal/hashcode/hashcode.go new file mode 100644 index 00000000000..64d8263e601 --- /dev/null +++ b/aws/internal/hashcode/hashcode.go @@ -0,0 +1,22 @@ +package hashcode + +import ( + "hash/crc32" +) + +// String hashes a string to a unique hashcode. +// +// crc32 returns a uint32, but for our use we need +// and non negative integer. Here we cast to an integer +// and invert it if the result is negative. +func String(s string) int { + v := int(crc32.ChecksumIEEE([]byte(s))) + if v >= 0 { + return v + } + if -v >= 0 { + return -v + } + // v == MinInt + return 0 +} diff --git a/aws/internal/hashcode/hashcode_test.go b/aws/internal/hashcode/hashcode_test.go new file mode 100644 index 00000000000..1b521823f2c --- /dev/null +++ b/aws/internal/hashcode/hashcode_test.go @@ -0,0 +1,26 @@ +package hashcode + +import ( + "testing" +) + +func TestString(t *testing.T) { + v := "hello, world" + expected := String(v) + for i := 0; i < 100; i++ { + actual := String(v) + if actual != expected { + t.Fatalf("bad: %#v\n\t%#v", actual, expected) + } + } +} + +func TestString_positiveIndex(t *testing.T) { + // "2338615298" hashes to uint32(2147483648) which is math.MinInt32 + ips := []string{"192.168.1.3", "192.168.1.5", "2338615298"} + for _, ip := range ips { + if index := String(ip); index < 0 { + t.Fatalf("Bad Index %#v for ip %s", index, ip) + } + } +} diff --git a/aws/internal/keyvaluetags/README.md b/aws/internal/keyvaluetags/README.md index 681ddad9e73..0b7930f539a 100644 --- a/aws/internal/keyvaluetags/README.md +++ b/aws/internal/keyvaluetags/README.md @@ -19,6 +19,8 @@ Any tagging functions that cannot be generated should be hand implemented in a s ```text aws/internal/keyvaluetags ├── generators +│ ├── createtags (generates create_tags_gen.go) +│ ├── gettag (generates get_tag_gen.go) │ ├── listtags (generates list_tags_gen.go) │ ├── servicetags (generates service_tags_gen.go) │ └── updatetags (generates update_tags_gen.go) diff --git a/aws/internal/keyvaluetags/create_tags_gen.go b/aws/internal/keyvaluetags/create_tags_gen.go index e944ccc4a7d..f30f156e65b 100644 --- a/aws/internal/keyvaluetags/create_tags_gen.go +++ b/aws/internal/keyvaluetags/create_tags_gen.go @@ -11,7 +11,7 @@ import ( "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-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) const EventualConsistencyTimeout = 5 * time.Minute diff --git a/aws/internal/keyvaluetags/generators/createtags/main.go b/aws/internal/keyvaluetags/generators/createtags/main.go index 3355d83a86c..54c505be465 100644 --- a/aws/internal/keyvaluetags/generators/createtags/main.go +++ b/aws/internal/keyvaluetags/generators/createtags/main.go @@ -97,7 +97,7 @@ import ( {{- range .ServiceNames }} "github.com/aws/aws-sdk-go/service/{{ . }}" {{- end }} - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) const EventualConsistencyTimeout = 5 * time.Minute diff --git a/aws/internal/keyvaluetags/generators/gettag/main.go b/aws/internal/keyvaluetags/generators/gettag/main.go new file mode 100644 index 00000000000..b01858bcf50 --- /dev/null +++ b/aws/internal/keyvaluetags/generators/gettag/main.go @@ -0,0 +1,133 @@ +// +build ignore + +package main + +import ( + "bytes" + "go/format" + "log" + "os" + "sort" + "strings" + "text/template" + + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" +) + +const filename = `get_tag_gen.go` + +var serviceNames = []string{ + "dynamodb", + "ec2", + "ecs", + "route53resolver", +} + +type TemplateData struct { + ServiceNames []string +} + +func main() { + // Always sort to reduce any potential generation churn + sort.Strings(serviceNames) + + templateData := TemplateData{ + ServiceNames: serviceNames, + } + templateFuncMap := template.FuncMap{ + "ClientType": keyvaluetags.ServiceClientType, + "ListTagsFunction": keyvaluetags.ServiceListTagsFunction, + "ListTagsInputFilterIdentifierName": keyvaluetags.ServiceListTagsInputFilterIdentifierName, + "ListTagsInputResourceTypeField": keyvaluetags.ServiceListTagsInputResourceTypeField, + "ListTagsOutputTagsField": keyvaluetags.ServiceListTagsOutputTagsField, + "TagPackage": keyvaluetags.ServiceTagPackage, + "Title": strings.Title, + } + + tmpl, err := template.New("gettag").Funcs(templateFuncMap).Parse(templateBody) + + if err != nil { + log.Fatalf("error parsing template: %s", err) + } + + var buffer bytes.Buffer + err = tmpl.Execute(&buffer, templateData) + + if err != nil { + log.Fatalf("error executing template: %s", err) + } + + generatedFileContents, err := format.Source(buffer.Bytes()) + + if err != nil { + log.Fatalf("error formatting generated file: %s", err) + } + + f, err := os.Create(filename) + + if err != nil { + log.Fatalf("error creating file (%s): %s", filename, err) + } + + defer f.Close() + + _, err = f.Write(generatedFileContents) + + if err != nil { + log.Fatalf("error writing to file (%s): %s", filename, err) + } +} + +var templateBody = ` +// Code generated by generators/gettag/main.go; DO NOT EDIT. + +package keyvaluetags + +import ( + "github.com/aws/aws-sdk-go/aws" +{{- range .ServiceNames }} + "github.com/aws/aws-sdk-go/service/{{ . }}" +{{- end }} +) + +{{- range .ServiceNames }} + +// {{ . | Title }}GetTag fetches an individual {{ . }} service tag for a resource. +// Returns whether the key exists, the key value, and any errors. +// This function will optimise the handling over {{ . | Title }}ListTags, if possible. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func {{ . | Title }}GetTag(conn {{ . | ClientType }}, identifier string{{ if . | ListTagsInputResourceTypeField }}, resourceType string{{ end }}, key string) (bool, *string, error) { + {{- if . | ListTagsInputFilterIdentifierName }} + input := &{{ . | TagPackage }}.{{ . | ListTagsFunction }}Input{ + Filters: []*{{ . | TagPackage }}.Filter{ + { + Name: aws.String("{{ . | ListTagsInputFilterIdentifierName }}"), + Values: []*string{aws.String(identifier)}, + }, + { + Name: aws.String("key"), + Values: []*string{aws.String(key)}, + }, + }, + } + + output, err := conn.{{ . | ListTagsFunction }}(input) + + if err != nil { + return false, nil, err + } + + listTags := {{ . | Title }}KeyValueTags(output.{{ . | ListTagsOutputTagsField }}) + {{- else }} + listTags, err := {{ . | Title }}ListTags(conn, identifier{{ if . | ListTagsInputResourceTypeField }}, resourceType{{ end }}) + + if err != nil { + return false, nil, err + } + {{- end }} + + return listTags.KeyExists(key), listTags.KeyValue(key), nil +} +{{- end }} +` diff --git a/aws/internal/keyvaluetags/generators/listtags/main.go b/aws/internal/keyvaluetags/generators/listtags/main.go index d0b4f1cff54..9ce6dd2867b 100644 --- a/aws/internal/keyvaluetags/generators/listtags/main.go +++ b/aws/internal/keyvaluetags/generators/listtags/main.go @@ -51,6 +51,7 @@ var serviceNames = []string{ "dlm", "docdb", "dynamodb", + "ec2", "ecr", "ecs", "efs", @@ -88,6 +89,7 @@ var serviceNames = []string{ "mediastore", "mq", "neptune", + "networkmanager", "opsworks", "organizations", "pinpoint", @@ -99,6 +101,7 @@ var serviceNames = []string{ "route53resolver", "sagemaker", "securityhub", + "servicediscovery", "sfn", "sns", "sqs", @@ -109,6 +112,7 @@ var serviceNames = []string{ "waf", "wafregional", "wafv2", + "worklink", "workspaces", } @@ -126,6 +130,7 @@ func main() { templateFuncMap := template.FuncMap{ "ClientType": keyvaluetags.ServiceClientType, "ListTagsFunction": keyvaluetags.ServiceListTagsFunction, + "ListTagsInputFilterIdentifierName": keyvaluetags.ServiceListTagsInputFilterIdentifierName, "ListTagsInputIdentifierField": keyvaluetags.ServiceListTagsInputIdentifierField, "ListTagsInputIdentifierRequiresSlice": keyvaluetags.ServiceListTagsInputIdentifierRequiresSlice, "ListTagsInputResourceTypeField": keyvaluetags.ServiceListTagsInputResourceTypeField, @@ -186,6 +191,14 @@ import ( // it may also be a different identifier depending on the service. func {{ . | Title }}ListTags(conn {{ . | ClientType }}, identifier string{{ if . | ListTagsInputResourceTypeField }}, resourceType string{{ end }}) (KeyValueTags, error) { input := &{{ . | TagPackage }}.{{ . | ListTagsFunction }}Input{ + {{- if . | ListTagsInputFilterIdentifierName }} + Filters: []*{{ . | TagPackage }}.Filter{ + { + Name: aws.String("{{ . | ListTagsInputFilterIdentifierName }}"), + Values: []*string{aws.String(identifier)}, + }, + }, + {{- else }} {{- if . | ListTagsInputIdentifierRequiresSlice }} {{ . | ListTagsInputIdentifierField }}: aws.StringSlice([]string{identifier}), {{- else }} @@ -194,6 +207,7 @@ func {{ . | Title }}ListTags(conn {{ . | ClientType }}, identifier string{{ if . {{- if . | ListTagsInputResourceTypeField }} {{ . | ListTagsInputResourceTypeField }}: aws.String(resourceType), {{- end }} + {{- end }} } output, err := conn.{{ . | ListTagsFunction }}(input) diff --git a/aws/internal/keyvaluetags/generators/servicetags/main.go b/aws/internal/keyvaluetags/generators/servicetags/main.go index 4382879b7a0..0fbcb7d89ad 100644 --- a/aws/internal/keyvaluetags/generators/servicetags/main.go +++ b/aws/internal/keyvaluetags/generators/servicetags/main.go @@ -71,11 +71,13 @@ var sliceServiceNames = []string{ "lightsail", "mediastore", "neptune", + "networkmanager", "organizations", "quicksight", "ram", "rds", "redshift", + "resourcegroupstaggingapi", "route53", "route53resolver", "s3", @@ -83,6 +85,7 @@ var sliceServiceNames = []string{ "secretsmanager", "serverlessapplicationrepository", "servicecatalog", + "servicediscovery", "sfn", "sns", "ssm", @@ -131,6 +134,8 @@ var mapServiceNames = []string{ "resourcegroups", "securityhub", "sqs", + "synthetics", + "worklink", } type TemplateData struct { @@ -151,6 +156,7 @@ func main() { "TagKeyType": keyvaluetags.ServiceTagKeyType, "TagPackage": keyvaluetags.ServiceTagPackage, "TagType": keyvaluetags.ServiceTagType, + "TagType2": keyvaluetags.ServiceTagType2, "TagTypeKeyField": keyvaluetags.ServiceTagTypeKeyField, "TagTypeValueField": keyvaluetags.ServiceTagTypeValueField, "Title": strings.Title, @@ -255,6 +261,31 @@ func (tags KeyValueTags) {{ . | Title }}Tags() []*{{ . | TagPackage }}.{{ . | Ta } // {{ . | Title }}KeyValueTags creates KeyValueTags from {{ . }} service tags. +{{- if . | TagType2 }} +// Accepts []*{{ . | TagPackage }}.{{ . | TagType }} and []*{{ . | TagPackage }}.{{ . | TagType2 }}. +func {{ . | Title }}KeyValueTags(tags interface{}) KeyValueTags { + switch tags := tags.(type) { + case []*{{ . | TagPackage }}.{{ . | TagType }}: + m := make(map[string]*string, len(tags)) + + for _, tag := range tags { + m[aws.StringValue(tag.{{ . | TagTypeKeyField }})] = tag.{{ . | TagTypeValueField }} + } + + return New(m) + case []*{{ . | TagPackage }}.{{ . | TagType2 }}: + m := make(map[string]*string, len(tags)) + + for _, tag := range tags { + m[aws.StringValue(tag.{{ . | TagTypeKeyField }})] = tag.{{ . | TagTypeValueField }} + } + + return New(m) + default: + return New(nil) + } +} +{{- else }} func {{ . | Title }}KeyValueTags(tags []*{{ . | TagPackage }}.{{ . | TagType }}) KeyValueTags { m := make(map[string]*string, len(tags)) @@ -265,4 +296,5 @@ func {{ . | Title }}KeyValueTags(tags []*{{ . | TagPackage }}.{{ . | TagType }}) return New(m) } {{- end }} +{{- end }} ` diff --git a/aws/internal/keyvaluetags/generators/updatetags/main.go b/aws/internal/keyvaluetags/generators/updatetags/main.go index ee18203bf73..b14f9c6ccd7 100644 --- a/aws/internal/keyvaluetags/generators/updatetags/main.go +++ b/aws/internal/keyvaluetags/generators/updatetags/main.go @@ -92,6 +92,7 @@ var serviceNames = []string{ "mediastore", "mq", "neptune", + "networkmanager", "opsworks", "organizations", "pinpoint", @@ -106,16 +107,19 @@ var serviceNames = []string{ "sagemaker", "secretsmanager", "securityhub", + "servicediscovery", "sfn", "sns", "sqs", "ssm", "storagegateway", "swf", + "synthetics", "transfer", "waf", "wafregional", "wafv2", + "worklink", "workspaces", } diff --git a/aws/internal/keyvaluetags/get_tag_gen.go b/aws/internal/keyvaluetags/get_tag_gen.go new file mode 100644 index 00000000000..f2bf57afd23 --- /dev/null +++ b/aws/internal/keyvaluetags/get_tag_gen.go @@ -0,0 +1,86 @@ +// Code generated by generators/gettag/main.go; DO NOT EDIT. + +package keyvaluetags + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ecs" + "github.com/aws/aws-sdk-go/service/route53resolver" +) + +// DynamodbGetTag fetches an individual dynamodb service tag for a resource. +// Returns whether the key exists, the key value, and any errors. +// This function will optimise the handling over DynamodbListTags, if possible. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func DynamodbGetTag(conn *dynamodb.DynamoDB, identifier string, key string) (bool, *string, error) { + listTags, err := DynamodbListTags(conn, identifier) + + if err != nil { + return false, nil, err + } + + return listTags.KeyExists(key), listTags.KeyValue(key), nil +} + +// Ec2GetTag fetches an individual ec2 service tag for a resource. +// Returns whether the key exists, the key value, and any errors. +// This function will optimise the handling over Ec2ListTags, if possible. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func Ec2GetTag(conn *ec2.EC2, identifier string, key string) (bool, *string, error) { + input := &ec2.DescribeTagsInput{ + Filters: []*ec2.Filter{ + { + Name: aws.String("resource-id"), + Values: []*string{aws.String(identifier)}, + }, + { + Name: aws.String("key"), + Values: []*string{aws.String(key)}, + }, + }, + } + + output, err := conn.DescribeTags(input) + + if err != nil { + return false, nil, err + } + + listTags := Ec2KeyValueTags(output.Tags) + + return listTags.KeyExists(key), listTags.KeyValue(key), nil +} + +// EcsGetTag fetches an individual ecs service tag for a resource. +// Returns whether the key exists, the key value, and any errors. +// This function will optimise the handling over EcsListTags, if possible. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func EcsGetTag(conn *ecs.ECS, identifier string, key string) (bool, *string, error) { + listTags, err := EcsListTags(conn, identifier) + + if err != nil { + return false, nil, err + } + + return listTags.KeyExists(key), listTags.KeyValue(key), nil +} + +// Route53resolverGetTag fetches an individual route53resolver service tag for a resource. +// Returns whether the key exists, the key value, and any errors. +// This function will optimise the handling over Route53resolverListTags, if possible. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func Route53resolverGetTag(conn *route53resolver.Route53Resolver, identifier string, key string) (bool, *string, error) { + listTags, err := Route53resolverListTags(conn, identifier) + + if err != nil { + return false, nil, err + } + + return listTags.KeyExists(key), listTags.KeyValue(key), nil +} diff --git a/aws/internal/keyvaluetags/key_value_tags.go b/aws/internal/keyvaluetags/key_value_tags.go index 58c27c34d73..1b8f57f6933 100644 --- a/aws/internal/keyvaluetags/key_value_tags.go +++ b/aws/internal/keyvaluetags/key_value_tags.go @@ -1,5 +1,6 @@ //go:generate go run -tags generate generators/servicetags/main.go //go:generate go run -tags generate generators/listtags/main.go +//go:generate go run -tags generate generators/gettag/main.go //go:generate go run -tags generate generators/createtags/main.go //go:generate go run -tags generate generators/updatetags/main.go @@ -10,7 +11,7 @@ import ( "net/url" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) const ( @@ -138,6 +139,28 @@ func (tags KeyValueTags) Ignore(ignoreTags KeyValueTags) KeyValueTags { return result } +// KeyExists returns true if a tag key exists. +// If the key is not found, returns nil. +// Use KeyExists to determine if key is present. +func (tags KeyValueTags) KeyExists(key string) bool { + if _, ok := tags[key]; ok { + return true + } + + return false +} + +// KeyValue returns a tag key value. +// If the key is not found, returns nil. +// Use KeyExists to determine if key is present. +func (tags KeyValueTags) KeyValue(key string) *string { + if v, ok := tags[key]; ok { + return v + } + + return nil +} + // Keys returns tag keys. func (tags KeyValueTags) Keys() []string { result := make([]string, 0, len(tags)) diff --git a/aws/internal/keyvaluetags/key_value_tags_test.go b/aws/internal/keyvaluetags/key_value_tags_test.go index dedcc5acaae..789829f8a68 100644 --- a/aws/internal/keyvaluetags/key_value_tags_test.go +++ b/aws/internal/keyvaluetags/key_value_tags_test.go @@ -533,6 +533,102 @@ func TestKeyValueTagsIgnore(t *testing.T) { } } +func TestKeyValueTagsKeyExists(t *testing.T) { + testCases := []struct { + name string + tags KeyValueTags + key string + want bool + }{ + { + name: "empty", + tags: New(map[string]*string{}), + key: "key1", + want: false, + }, + { + name: "non-existent", + tags: New(map[string]*string{"key1": testStringPtr("value1")}), + key: "key2", + want: false, + }, + { + name: "matching with string value", + tags: New(map[string]*string{"key1": testStringPtr("value1")}), + key: "key1", + want: true, + }, + { + name: "matching with nil value", + tags: New(map[string]*string{"key1": nil}), + key: "key1", + want: true, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + got := testCase.tags.KeyExists(testCase.key) + + if got != testCase.want { + t.Fatalf("expected: %t, got: %t", testCase.want, got) + } + }) + } +} + +func TestKeyValueTagsKeyValues(t *testing.T) { + testCases := []struct { + name string + tags KeyValueTags + key string + want *string + }{ + { + name: "empty", + tags: New(map[string]*string{}), + key: "key1", + want: nil, + }, + { + name: "non-existent", + tags: New(map[string]*string{"key1": testStringPtr("value1")}), + key: "key2", + want: nil, + }, + { + name: "matching with string value", + tags: New(map[string]*string{"key1": testStringPtr("value1")}), + key: "key1", + want: testStringPtr("value1"), + }, + { + name: "matching with nil value", + tags: New(map[string]*string{"key1": nil}), + key: "key1", + want: nil, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + got := testCase.tags.KeyValue(testCase.key) + + if testCase.want == nil && got != nil { + t.Fatalf("expected: nil, got: %s", *got) + } + + if testCase.want != nil && got == nil { + t.Fatalf("expected: %s, got: nil", *testCase.want) + } + + if testCase.want != nil && got != nil && *testCase.want != *got { + t.Fatalf("expected: %s, got: %s", *testCase.want, *got) + } + }) + } +} + func TestKeyValueTagsKeys(t *testing.T) { testCases := []struct { name string diff --git a/aws/internal/keyvaluetags/list_tags_gen.go b/aws/internal/keyvaluetags/list_tags_gen.go index 0aa7e650a53..bff556eaeac 100644 --- a/aws/internal/keyvaluetags/list_tags_gen.go +++ b/aws/internal/keyvaluetags/list_tags_gen.go @@ -38,6 +38,7 @@ import ( "github.com/aws/aws-sdk-go/service/dlm" "github.com/aws/aws-sdk-go/service/docdb" "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ecr" "github.com/aws/aws-sdk-go/service/ecs" "github.com/aws/aws-sdk-go/service/efs" @@ -75,6 +76,7 @@ import ( "github.com/aws/aws-sdk-go/service/mediastore" "github.com/aws/aws-sdk-go/service/mq" "github.com/aws/aws-sdk-go/service/neptune" + "github.com/aws/aws-sdk-go/service/networkmanager" "github.com/aws/aws-sdk-go/service/opsworks" "github.com/aws/aws-sdk-go/service/organizations" "github.com/aws/aws-sdk-go/service/pinpoint" @@ -86,6 +88,7 @@ import ( "github.com/aws/aws-sdk-go/service/route53resolver" "github.com/aws/aws-sdk-go/service/sagemaker" "github.com/aws/aws-sdk-go/service/securityhub" + "github.com/aws/aws-sdk-go/service/servicediscovery" "github.com/aws/aws-sdk-go/service/sfn" "github.com/aws/aws-sdk-go/service/sns" "github.com/aws/aws-sdk-go/service/sqs" @@ -96,6 +99,7 @@ import ( "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/aws/aws-sdk-go/service/worklink" "github.com/aws/aws-sdk-go/service/workspaces" ) @@ -677,6 +681,28 @@ func DynamodbListTags(conn *dynamodb.DynamoDB, identifier string) (KeyValueTags, return DynamodbKeyValueTags(output.Tags), nil } +// Ec2ListTags lists ec2 service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func Ec2ListTags(conn *ec2.EC2, identifier string) (KeyValueTags, error) { + input := &ec2.DescribeTagsInput{ + Filters: []*ec2.Filter{ + { + Name: aws.String("resource-id"), + Values: []*string{aws.String(identifier)}, + }, + }, + } + + output, err := conn.DescribeTags(input) + + if err != nil { + return New(nil), err + } + + return Ec2KeyValueTags(output.Tags), nil +} + // EcrListTags lists ecr service tags. // The identifier is typically the Amazon Resource Name (ARN), although // it may also be a different identifier depending on the service. @@ -1306,6 +1332,23 @@ func NeptuneListTags(conn *neptune.Neptune, identifier string) (KeyValueTags, er return NeptuneKeyValueTags(output.TagList), nil } +// NetworkmanagerListTags lists networkmanager service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func NetworkmanagerListTags(conn *networkmanager.NetworkManager, identifier string) (KeyValueTags, error) { + input := &networkmanager.ListTagsForResourceInput{ + ResourceArn: aws.String(identifier), + } + + output, err := conn.ListTagsForResource(input) + + if err != nil { + return New(nil), err + } + + return NetworkmanagerKeyValueTags(output.TagList), nil +} + // OpsworksListTags lists opsworks service tags. // The identifier is typically the Amazon Resource Name (ARN), although // it may also be a different identifier depending on the service. @@ -1494,6 +1537,23 @@ func SecurityhubListTags(conn *securityhub.SecurityHub, identifier string) (KeyV return SecurityhubKeyValueTags(output.Tags), nil } +// ServicediscoveryListTags lists servicediscovery service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func ServicediscoveryListTags(conn *servicediscovery.ServiceDiscovery, identifier string) (KeyValueTags, error) { + input := &servicediscovery.ListTagsForResourceInput{ + ResourceARN: aws.String(identifier), + } + + output, err := conn.ListTagsForResource(input) + + if err != nil { + return New(nil), err + } + + return ServicediscoveryKeyValueTags(output.Tags), nil +} + // SfnListTags lists sfn service tags. // The identifier is typically the Amazon Resource Name (ARN), although // it may also be a different identifier depending on the service. @@ -1665,6 +1725,23 @@ func Wafv2ListTags(conn *wafv2.WAFV2, identifier string) (KeyValueTags, error) { return Wafv2KeyValueTags(output.TagInfoForResource.TagList), nil } +// WorklinkListTags lists worklink service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func WorklinkListTags(conn *worklink.WorkLink, identifier string) (KeyValueTags, error) { + input := &worklink.ListTagsForResourceInput{ + ResourceArn: aws.String(identifier), + } + + output, err := conn.ListTagsForResource(input) + + if err != nil { + return New(nil), err + } + + return WorklinkKeyValueTags(output.Tags), nil +} + // WorkspacesListTags lists workspaces service tags. // The identifier is typically the Amazon Resource Name (ARN), although // it may also be a different identifier depending on the service. diff --git a/aws/internal/keyvaluetags/service_generation_customizations.go b/aws/internal/keyvaluetags/service_generation_customizations.go index 071ce0d9b5b..76237cd6801 100644 --- a/aws/internal/keyvaluetags/service_generation_customizations.go +++ b/aws/internal/keyvaluetags/service_generation_customizations.go @@ -82,6 +82,7 @@ import ( "github.com/aws/aws-sdk-go/service/mediastore" "github.com/aws/aws-sdk-go/service/mq" "github.com/aws/aws-sdk-go/service/neptune" + "github.com/aws/aws-sdk-go/service/networkmanager" "github.com/aws/aws-sdk-go/service/opsworks" "github.com/aws/aws-sdk-go/service/organizations" "github.com/aws/aws-sdk-go/service/pinpoint" @@ -91,21 +92,25 @@ import ( "github.com/aws/aws-sdk-go/service/rds" "github.com/aws/aws-sdk-go/service/redshift" "github.com/aws/aws-sdk-go/service/resourcegroups" + "github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi" "github.com/aws/aws-sdk-go/service/route53" "github.com/aws/aws-sdk-go/service/route53resolver" "github.com/aws/aws-sdk-go/service/sagemaker" "github.com/aws/aws-sdk-go/service/secretsmanager" "github.com/aws/aws-sdk-go/service/securityhub" + "github.com/aws/aws-sdk-go/service/servicediscovery" "github.com/aws/aws-sdk-go/service/sfn" "github.com/aws/aws-sdk-go/service/sns" "github.com/aws/aws-sdk-go/service/sqs" "github.com/aws/aws-sdk-go/service/ssm" "github.com/aws/aws-sdk-go/service/storagegateway" "github.com/aws/aws-sdk-go/service/swf" + "github.com/aws/aws-sdk-go/service/synthetics" "github.com/aws/aws-sdk-go/service/transfer" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/aws/aws-sdk-go/service/worklink" "github.com/aws/aws-sdk-go/service/workspaces" ) @@ -268,6 +273,8 @@ func ServiceClientType(serviceName string) string { funcType = reflect.TypeOf(mq.New) case "neptune": funcType = reflect.TypeOf(neptune.New) + case "networkmanager": + funcType = reflect.TypeOf(networkmanager.New) case "opsworks": funcType = reflect.TypeOf(opsworks.New) case "organizations": @@ -286,6 +293,8 @@ func ServiceClientType(serviceName string) string { funcType = reflect.TypeOf(redshift.New) case "resourcegroups": funcType = reflect.TypeOf(resourcegroups.New) + case "resourcegroupstaggingapi": + funcType = reflect.TypeOf(resourcegroupstaggingapi.New) case "route53": funcType = reflect.TypeOf(route53.New) case "route53resolver": @@ -296,6 +305,8 @@ func ServiceClientType(serviceName string) string { funcType = reflect.TypeOf(secretsmanager.New) case "securityhub": funcType = reflect.TypeOf(securityhub.New) + case "servicediscovery": + funcType = reflect.TypeOf(servicediscovery.New) case "sfn": funcType = reflect.TypeOf(sfn.New) case "sns": @@ -308,6 +319,8 @@ func ServiceClientType(serviceName string) string { funcType = reflect.TypeOf(storagegateway.New) case "swf": funcType = reflect.TypeOf(swf.New) + case "synthetics": + funcType = reflect.TypeOf(synthetics.New) case "transfer": funcType = reflect.TypeOf(transfer.New) case "waf": @@ -316,6 +329,8 @@ func ServiceClientType(serviceName string) string { funcType = reflect.TypeOf(wafregional.New) case "wafv2": funcType = reflect.TypeOf(wafv2.New) + case "worklink": + funcType = reflect.TypeOf(worklink.New) case "workspaces": funcType = reflect.TypeOf(workspaces.New) default: @@ -348,6 +363,8 @@ func ServiceListTagsFunction(serviceName string) string { return "DescribeTags" case "dynamodb": return "ListTagsOfResource" + case "ec2": + return "DescribeTags" case "efs": return "DescribeTags" case "elasticsearchservice": @@ -389,6 +406,17 @@ func ServiceListTagsFunction(serviceName string) string { } } +// ServiceListTagsInputFilterIdentifierName determines the service list tag filter identifier field. +// This causes the implementation to use the Filters field with the Input struct. +func ServiceListTagsInputFilterIdentifierName(serviceName string) string { + switch serviceName { + case "ec2": + return "resource-id" + default: + return "" + } +} + // ServiceListTagsInputIdentifierField determines the service list tag identifier field. func ServiceListTagsInputIdentifierField(serviceName string) string { switch serviceName { @@ -462,6 +490,8 @@ func ServiceListTagsOutputTagsField(serviceName string) string { return "ResourceTags.Tags" case "neptune": return "TagList" + case "networkmanager": + return "TagList" case "pinpoint": return "TagsModel.Tags" case "rds": @@ -684,6 +714,8 @@ func ServiceTagInputIdentifierField(serviceName string) string { return "ResourceId" case "secretsmanager": return "SecretId" + case "servicediscovery": + return "ResourceARN" case "sqs": return "QueueUrl" case "ssm": @@ -802,6 +834,17 @@ func ServiceTagType(serviceName string) string { } } +// ServiceTagType2 determines if the service tagging has a second tag type. +// The two types must be equivalent. +func ServiceTagType2(serviceName string) string { + switch serviceName { + case "ec2": + return "TagDescription" + default: + return "" + } +} + // ServiceTagTypeKeyField determines the service tagging tag type key field. func ServiceTagTypeKeyField(serviceName string) string { switch serviceName { diff --git a/aws/internal/keyvaluetags/service_tags_gen.go b/aws/internal/keyvaluetags/service_tags_gen.go index d39d83a52b7..970b60c31ae 100644 --- a/aws/internal/keyvaluetags/service_tags_gen.go +++ b/aws/internal/keyvaluetags/service_tags_gen.go @@ -56,11 +56,13 @@ import ( "github.com/aws/aws-sdk-go/service/lightsail" "github.com/aws/aws-sdk-go/service/mediastore" "github.com/aws/aws-sdk-go/service/neptune" + "github.com/aws/aws-sdk-go/service/networkmanager" "github.com/aws/aws-sdk-go/service/organizations" "github.com/aws/aws-sdk-go/service/quicksight" "github.com/aws/aws-sdk-go/service/ram" "github.com/aws/aws-sdk-go/service/rds" "github.com/aws/aws-sdk-go/service/redshift" + "github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi" "github.com/aws/aws-sdk-go/service/route53" "github.com/aws/aws-sdk-go/service/route53resolver" "github.com/aws/aws-sdk-go/service/s3" @@ -68,6 +70,7 @@ import ( "github.com/aws/aws-sdk-go/service/secretsmanager" "github.com/aws/aws-sdk-go/service/serverlessapplicationrepository" "github.com/aws/aws-sdk-go/service/servicecatalog" + "github.com/aws/aws-sdk-go/service/servicediscovery" "github.com/aws/aws-sdk-go/service/sfn" "github.com/aws/aws-sdk-go/service/sns" "github.com/aws/aws-sdk-go/service/ssm" @@ -431,6 +434,26 @@ func SqsKeyValueTags(tags map[string]*string) KeyValueTags { return New(tags) } +// SyntheticsTags returns synthetics service tags. +func (tags KeyValueTags) SyntheticsTags() map[string]*string { + return aws.StringMap(tags.Map()) +} + +// SyntheticsKeyValueTags creates KeyValueTags from synthetics service tags. +func SyntheticsKeyValueTags(tags map[string]*string) KeyValueTags { + return New(tags) +} + +// WorklinkTags returns worklink service tags. +func (tags KeyValueTags) WorklinkTags() map[string]*string { + return aws.StringMap(tags.Map()) +} + +// WorklinkKeyValueTags creates KeyValueTags from worklink service tags. +func WorklinkKeyValueTags(tags map[string]*string) KeyValueTags { + return New(tags) +} + // []*SERVICE.Tag handling // AcmTags returns acm service tags. @@ -1098,14 +1121,28 @@ func (tags KeyValueTags) Ec2Tags() []*ec2.Tag { } // Ec2KeyValueTags creates KeyValueTags from ec2 service tags. -func Ec2KeyValueTags(tags []*ec2.Tag) KeyValueTags { - m := make(map[string]*string, len(tags)) +// Accepts []*ec2.Tag and []*ec2.TagDescription. +func Ec2KeyValueTags(tags interface{}) KeyValueTags { + switch tags := tags.(type) { + case []*ec2.Tag: + m := make(map[string]*string, len(tags)) - for _, tag := range tags { - m[aws.StringValue(tag.Key)] = tag.Value - } + for _, tag := range tags { + m[aws.StringValue(tag.Key)] = tag.Value + } - return New(m) + return New(m) + case []*ec2.TagDescription: + m := make(map[string]*string, len(tags)) + + for _, tag := range tags { + m[aws.StringValue(tag.Key)] = tag.Value + } + + return New(m) + default: + return New(nil) + } } // EcrTags returns ecr service tags. @@ -1852,6 +1889,33 @@ func NeptuneKeyValueTags(tags []*neptune.Tag) KeyValueTags { return New(m) } +// NetworkmanagerTags returns networkmanager service tags. +func (tags KeyValueTags) NetworkmanagerTags() []*networkmanager.Tag { + result := make([]*networkmanager.Tag, 0, len(tags)) + + for k, v := range tags.Map() { + tag := &networkmanager.Tag{ + Key: aws.String(k), + Value: aws.String(v), + } + + result = append(result, tag) + } + + return result +} + +// NetworkmanagerKeyValueTags creates KeyValueTags from networkmanager service tags. +func NetworkmanagerKeyValueTags(tags []*networkmanager.Tag) KeyValueTags { + m := make(map[string]*string, len(tags)) + + for _, tag := range tags { + m[aws.StringValue(tag.Key)] = tag.Value + } + + return New(m) +} + // OrganizationsTags returns organizations service tags. func (tags KeyValueTags) OrganizationsTags() []*organizations.Tag { result := make([]*organizations.Tag, 0, len(tags)) @@ -1987,6 +2051,33 @@ func RedshiftKeyValueTags(tags []*redshift.Tag) KeyValueTags { return New(m) } +// ResourcegroupstaggingapiTags returns resourcegroupstaggingapi service tags. +func (tags KeyValueTags) ResourcegroupstaggingapiTags() []*resourcegroupstaggingapi.Tag { + result := make([]*resourcegroupstaggingapi.Tag, 0, len(tags)) + + for k, v := range tags.Map() { + tag := &resourcegroupstaggingapi.Tag{ + Key: aws.String(k), + Value: aws.String(v), + } + + result = append(result, tag) + } + + return result +} + +// ResourcegroupstaggingapiKeyValueTags creates KeyValueTags from resourcegroupstaggingapi service tags. +func ResourcegroupstaggingapiKeyValueTags(tags []*resourcegroupstaggingapi.Tag) KeyValueTags { + m := make(map[string]*string, len(tags)) + + for _, tag := range tags { + m[aws.StringValue(tag.Key)] = tag.Value + } + + return New(m) +} + // Route53Tags returns route53 service tags. func (tags KeyValueTags) Route53Tags() []*route53.Tag { result := make([]*route53.Tag, 0, len(tags)) @@ -2176,6 +2267,33 @@ func ServicecatalogKeyValueTags(tags []*servicecatalog.Tag) KeyValueTags { return New(m) } +// ServicediscoveryTags returns servicediscovery service tags. +func (tags KeyValueTags) ServicediscoveryTags() []*servicediscovery.Tag { + result := make([]*servicediscovery.Tag, 0, len(tags)) + + for k, v := range tags.Map() { + tag := &servicediscovery.Tag{ + Key: aws.String(k), + Value: aws.String(v), + } + + result = append(result, tag) + } + + return result +} + +// ServicediscoveryKeyValueTags creates KeyValueTags from servicediscovery service tags. +func ServicediscoveryKeyValueTags(tags []*servicediscovery.Tag) KeyValueTags { + m := make(map[string]*string, len(tags)) + + for _, tag := range tags { + m[aws.StringValue(tag.Key)] = tag.Value + } + + return New(m) +} + // SfnTags returns sfn service tags. func (tags KeyValueTags) SfnTags() []*sfn.Tag { result := make([]*sfn.Tag, 0, len(tags)) diff --git a/aws/internal/keyvaluetags/update_tags_gen.go b/aws/internal/keyvaluetags/update_tags_gen.go index ce0a1715fdc..76af8214597 100644 --- a/aws/internal/keyvaluetags/update_tags_gen.go +++ b/aws/internal/keyvaluetags/update_tags_gen.go @@ -81,6 +81,7 @@ import ( "github.com/aws/aws-sdk-go/service/mediastore" "github.com/aws/aws-sdk-go/service/mq" "github.com/aws/aws-sdk-go/service/neptune" + "github.com/aws/aws-sdk-go/service/networkmanager" "github.com/aws/aws-sdk-go/service/opsworks" "github.com/aws/aws-sdk-go/service/organizations" "github.com/aws/aws-sdk-go/service/pinpoint" @@ -95,16 +96,19 @@ import ( "github.com/aws/aws-sdk-go/service/sagemaker" "github.com/aws/aws-sdk-go/service/secretsmanager" "github.com/aws/aws-sdk-go/service/securityhub" + "github.com/aws/aws-sdk-go/service/servicediscovery" "github.com/aws/aws-sdk-go/service/sfn" "github.com/aws/aws-sdk-go/service/sns" "github.com/aws/aws-sdk-go/service/sqs" "github.com/aws/aws-sdk-go/service/ssm" "github.com/aws/aws-sdk-go/service/storagegateway" "github.com/aws/aws-sdk-go/service/swf" + "github.com/aws/aws-sdk-go/service/synthetics" "github.com/aws/aws-sdk-go/service/transfer" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/aws/aws-sdk-go/service/worklink" "github.com/aws/aws-sdk-go/service/workspaces" ) @@ -2811,6 +2815,42 @@ func NeptuneUpdateTags(conn *neptune.Neptune, identifier string, oldTagsMap inte return nil } +// NetworkmanagerUpdateTags updates networkmanager service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func NetworkmanagerUpdateTags(conn *networkmanager.NetworkManager, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error { + oldTags := New(oldTagsMap) + newTags := New(newTagsMap) + + if removedTags := oldTags.Removed(newTags); len(removedTags) > 0 { + input := &networkmanager.UntagResourceInput{ + ResourceArn: aws.String(identifier), + TagKeys: aws.StringSlice(removedTags.IgnoreAws().Keys()), + } + + _, err := conn.UntagResource(input) + + if err != nil { + return fmt.Errorf("error untagging resource (%s): %w", identifier, err) + } + } + + if updatedTags := oldTags.Updated(newTags); len(updatedTags) > 0 { + input := &networkmanager.TagResourceInput{ + ResourceArn: aws.String(identifier), + Tags: updatedTags.IgnoreAws().NetworkmanagerTags(), + } + + _, err := conn.TagResource(input) + + if err != nil { + return fmt.Errorf("error tagging resource (%s): %w", identifier, err) + } + } + + return nil +} + // OpsworksUpdateTags updates opsworks service tags. // The identifier is typically the Amazon Resource Name (ARN), although // it may also be a different identifier depending on the service. @@ -3315,6 +3355,42 @@ func SecurityhubUpdateTags(conn *securityhub.SecurityHub, identifier string, old return nil } +// ServicediscoveryUpdateTags updates servicediscovery service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func ServicediscoveryUpdateTags(conn *servicediscovery.ServiceDiscovery, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error { + oldTags := New(oldTagsMap) + newTags := New(newTagsMap) + + if removedTags := oldTags.Removed(newTags); len(removedTags) > 0 { + input := &servicediscovery.UntagResourceInput{ + ResourceARN: aws.String(identifier), + TagKeys: aws.StringSlice(removedTags.IgnoreAws().Keys()), + } + + _, err := conn.UntagResource(input) + + if err != nil { + return fmt.Errorf("error untagging resource (%s): %w", identifier, err) + } + } + + if updatedTags := oldTags.Updated(newTags); len(updatedTags) > 0 { + input := &servicediscovery.TagResourceInput{ + ResourceARN: aws.String(identifier), + Tags: updatedTags.IgnoreAws().ServicediscoveryTags(), + } + + _, err := conn.TagResource(input) + + if err != nil { + return fmt.Errorf("error tagging resource (%s): %w", identifier, err) + } + } + + return nil +} + // SfnUpdateTags updates sfn service tags. // The identifier is typically the Amazon Resource Name (ARN), although // it may also be a different identifier depending on the service. @@ -3533,6 +3609,42 @@ func SwfUpdateTags(conn *swf.SWF, identifier string, oldTagsMap interface{}, new return nil } +// SyntheticsUpdateTags updates synthetics service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func SyntheticsUpdateTags(conn *synthetics.Synthetics, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error { + oldTags := New(oldTagsMap) + newTags := New(newTagsMap) + + if removedTags := oldTags.Removed(newTags); len(removedTags) > 0 { + input := &synthetics.UntagResourceInput{ + ResourceArn: aws.String(identifier), + TagKeys: aws.StringSlice(removedTags.IgnoreAws().Keys()), + } + + _, err := conn.UntagResource(input) + + if err != nil { + return fmt.Errorf("error untagging resource (%s): %w", identifier, err) + } + } + + if updatedTags := oldTags.Updated(newTags); len(updatedTags) > 0 { + input := &synthetics.TagResourceInput{ + ResourceArn: aws.String(identifier), + Tags: updatedTags.IgnoreAws().SyntheticsTags(), + } + + _, err := conn.TagResource(input) + + if err != nil { + return fmt.Errorf("error tagging resource (%s): %w", identifier, err) + } + } + + return nil +} + // TransferUpdateTags updates transfer service tags. // The identifier is typically the Amazon Resource Name (ARN), although // it may also be a different identifier depending on the service. @@ -3677,6 +3789,42 @@ func Wafv2UpdateTags(conn *wafv2.WAFV2, identifier string, oldTagsMap interface{ return nil } +// WorklinkUpdateTags updates worklink service tags. +// The identifier is typically the Amazon Resource Name (ARN), although +// it may also be a different identifier depending on the service. +func WorklinkUpdateTags(conn *worklink.WorkLink, identifier string, oldTagsMap interface{}, newTagsMap interface{}) error { + oldTags := New(oldTagsMap) + newTags := New(newTagsMap) + + if removedTags := oldTags.Removed(newTags); len(removedTags) > 0 { + input := &worklink.UntagResourceInput{ + ResourceArn: aws.String(identifier), + TagKeys: aws.StringSlice(removedTags.IgnoreAws().Keys()), + } + + _, err := conn.UntagResource(input) + + if err != nil { + return fmt.Errorf("error untagging resource (%s): %w", identifier, err) + } + } + + if updatedTags := oldTags.Updated(newTags); len(updatedTags) > 0 { + input := &worklink.TagResourceInput{ + ResourceArn: aws.String(identifier), + Tags: updatedTags.IgnoreAws().WorklinkTags(), + } + + _, err := conn.TagResource(input) + + if err != nil { + return fmt.Errorf("error tagging resource (%s): %w", identifier, err) + } + } + + return nil +} + // WorkspacesUpdateTags updates workspaces service tags. // The identifier is typically the Amazon Resource Name (ARN), although // it may also be a different identifier depending on the service. diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/mutexkv/mutexkv.go b/aws/internal/mutexkv/mutexkv.go similarity index 85% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/mutexkv/mutexkv.go rename to aws/internal/mutexkv/mutexkv.go index 6917f2142bd..e1e67c6bb71 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/mutexkv/mutexkv.go +++ b/aws/internal/mutexkv/mutexkv.go @@ -8,9 +8,6 @@ import ( // MutexKV is a simple key/value store for arbitrary mutexes. It can be used to // serialize changes across arbitrary collaborators that share knowledge of the // keys they must serialize on. -// -// The initial use case is to let aws_security_group_rule resources serialize -// their access to individual security groups based on SG ID. type MutexKV struct { lock sync.Mutex store map[string]*sync.Mutex @@ -43,7 +40,7 @@ func (m *MutexKV) get(key string) *sync.Mutex { return mutex } -// Returns a properly initalized MutexKV +// Returns a properly initialized MutexKV func NewMutexKV() *MutexKV { return &MutexKV{ store: make(map[string]*sync.Mutex), diff --git a/aws/internal/mutexkv/mutexkv_test.go b/aws/internal/mutexkv/mutexkv_test.go new file mode 100644 index 00000000000..98356007479 --- /dev/null +++ b/aws/internal/mutexkv/mutexkv_test.go @@ -0,0 +1,67 @@ +package mutexkv + +import ( + "testing" + "time" +) + +func TestMutexKVLock(t *testing.T) { + mkv := NewMutexKV() + + mkv.Lock("foo") + + doneCh := make(chan struct{}) + + go func() { + mkv.Lock("foo") + close(doneCh) + }() + + select { + case <-doneCh: + t.Fatal("Second lock was able to be taken. This shouldn't happen.") + case <-time.After(50 * time.Millisecond): + // pass + } +} + +func TestMutexKVUnlock(t *testing.T) { + mkv := NewMutexKV() + + mkv.Lock("foo") + mkv.Unlock("foo") + + doneCh := make(chan struct{}) + + go func() { + mkv.Lock("foo") + close(doneCh) + }() + + select { + case <-doneCh: + // pass + case <-time.After(50 * time.Millisecond): + t.Fatal("Second lock blocked after unlock. This shouldn't happen.") + } +} + +func TestMutexKVDifferentKeys(t *testing.T) { + mkv := NewMutexKV() + + mkv.Lock("foo") + + doneCh := make(chan struct{}) + + go func() { + mkv.Lock("bar") + close(doneCh) + }() + + select { + case <-doneCh: + // pass + case <-time.After(50 * time.Millisecond): + t.Fatal("Second lock on a different key blocked. This shouldn't happen.") + } +} diff --git a/aws/internal/naming/naming.go b/aws/internal/naming/naming.go index d1313be3ffa..fb7a2ee457b 100644 --- a/aws/internal/naming/naming.go +++ b/aws/internal/naming/naming.go @@ -5,11 +5,11 @@ import ( "regexp" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -var resourceUniqueIDSuffixRegexpPattern = fmt.Sprintf("\\d{%d}$", resource.UniqueIDSuffixLength) +var resourceUniqueIDSuffixRegexpPattern = fmt.Sprintf("[[:xdigit:]]{%d}$", resource.UniqueIDSuffixLength) var resourceUniqueIDSuffixRegexp = regexp.MustCompile(resourceUniqueIDSuffixRegexpPattern) var resourceUniqueIDRegexpPattern = resourcePrefixedUniqueIDRegexpPattern(resource.UniqueIdPrefix) diff --git a/aws/internal/naming/naming_test.go b/aws/internal/naming/naming_test.go index d08b3b75d00..2d0241e1097 100644 --- a/aws/internal/naming/naming_test.go +++ b/aws/internal/naming/naming_test.go @@ -108,11 +108,21 @@ func TestHasResourceUniqueIdSuffix(t *testing.T) { Input: "test-20060102150405000000000001", Expected: true, }, + { + TestName: "correct suffix with hex, incorrect prefix", + Input: "test-200601021504050000000000a1", + Expected: true, + }, { TestName: "correct suffix, correct prefix", Input: "terraform-20060102150405000000000001", Expected: true, }, + { + TestName: "correct suffix with hex, correct prefix", + Input: "terraform-2006010215040500000000000a", + Expected: true, + }, } for _, testCase := range testCases { @@ -152,6 +162,11 @@ func TestNamePrefixFromName(t *testing.T) { Input: "test-20060102150405000000000001", Expected: strPtr("test-"), }, + { + TestName: "correct prefix with hyphen, correct suffix with hex", + Input: "test-200601021504050000000000f1", + Expected: strPtr("test-"), + }, { TestName: "incorrect prefix, correct suffix", Input: "terraform-20060102150405000000000001", @@ -177,4 +192,20 @@ func TestNamePrefixFromName(t *testing.T) { } }) } + + t.Run("extracting prefix from generated name", func(t *testing.T) { + for i := 0; i < 10; i++ { + prefix := "test-" + input := Generate("", prefix) + got := NamePrefixFromName(input) + + if got == nil { + t.Errorf("run%d: got nil, expected %s for input %s", i, prefix, input) + } + + if got != nil && prefix != *got { + t.Errorf("run%d: got %s, expected %s for input %s", i, *got, prefix, input) + } + } + }) } diff --git a/aws/internal/service/apigatewayv2/waiter/status.go b/aws/internal/service/apigatewayv2/waiter/status.go index 5549c3ece82..478600fa77a 100644 --- a/aws/internal/service/apigatewayv2/waiter/status.go +++ b/aws/internal/service/apigatewayv2/waiter/status.go @@ -5,7 +5,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) // DeploymentStatus fetches the Deployment and its Status diff --git a/aws/internal/service/apigatewayv2/waiter/waiter.go b/aws/internal/service/apigatewayv2/waiter/waiter.go index 9611009c81a..4f3d536f5b9 100644 --- a/aws/internal/service/apigatewayv2/waiter/waiter.go +++ b/aws/internal/service/apigatewayv2/waiter/waiter.go @@ -4,7 +4,7 @@ import ( "time" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) const ( diff --git a/aws/internal/service/batch/equivalency/container_properties.go b/aws/internal/service/batch/equivalency/container_properties.go index 9df82b85748..4fec8fa760c 100644 --- a/aws/internal/service/batch/equivalency/container_properties.go +++ b/aws/internal/service/batch/equivalency/container_properties.go @@ -19,6 +19,11 @@ func (cp *containerProperties) Reduce() error { return aws.StringValue(cp.Environment[i].Name) < aws.StringValue(cp.Environment[j].Name) }) + // Prevent difference of API response that adds an empty array when not configured during the request + if len(cp.Command) == 0 { + cp.Command = nil + } + // Prevent difference of API response that adds an empty array when not configured during the request if len(cp.Environment) == 0 { cp.Environment = nil diff --git a/aws/internal/service/batch/equivalency/container_properties_test.go b/aws/internal/service/batch/equivalency/container_properties_test.go index 0255944352b..e6f6d96b3cc 100644 --- a/aws/internal/service/batch/equivalency/container_properties_test.go +++ b/aws/internal/service/batch/equivalency/container_properties_test.go @@ -205,6 +205,38 @@ func TestEquivalentBatchContainerPropertiesJSON(t *testing.T) { "vcpus": 8, "jobRoleArn": "arn:aws:iam::123456789012:role/example" } +`, + ExpectEquivalent: true, + }, + { + Name: "empty command, mountPoints, resourceRequirements, ulimits, volumes", + ApiJson: ` +{ + "image": "123.dkr.ecr.us-east-1.amazonaws.com/my-app", + "vcpus": 1, + "memory": 4096, + "command": [], + "jobRoleArn": "arn:aws:iam::123:role/role-test", + "volumes": [], + "environment": [{"name":"ENVIRONMENT","value":"test"}], + "mountPoints": [], + "ulimits": [], + "resourceRequirements": [] +} +`, + ConfigurationJson: ` +{ + "image": "123.dkr.ecr.us-east-1.amazonaws.com/my-app", + "memory": 4096, + "vcpus": 1, + "jobRoleArn": "arn:aws:iam::123:role/role-test", + "environment": [ + { + "name": "ENVIRONMENT", + "value": "test" + } + ] +} `, ExpectEquivalent: true, }, diff --git a/aws/internal/service/ec2/errors.go b/aws/internal/service/ec2/errors.go new file mode 100644 index 00000000000..51a142922de --- /dev/null +++ b/aws/internal/service/ec2/errors.go @@ -0,0 +1,30 @@ +package ec2 + +import ( + "errors" + + "github.com/aws/aws-sdk-go/aws/awserr" +) + +// Copied from aws-sdk-go-base +// Can be removed when aws-sdk-go-base v0.6+ is merged +// TODO: +func ErrCodeEquals(err error, code string) bool { + var awsErr awserr.Error + if errors.As(err, &awsErr) { + return awsErr.Code() == code + } + return false +} + +const ( + ErrCodeClientVpnEndpointIdNotFound = "InvalidClientVpnEndpointId.NotFound" + ErrCodeClientVpnAuthorizationRuleNotFound = "InvalidClientVpnEndpointAuthorizationRuleNotFound" + ErrCodeClientVpnAssociationIdNotFound = "InvalidClientVpnAssociationId.NotFound" + ErrCodeClientVpnRouteNotFound = "InvalidClientVpnRouteNotFound" +) + +const ( + InvalidSecurityGroupIDNotFound = "InvalidSecurityGroupID.NotFound" + InvalidGroupNotFound = "InvalidGroup.NotFound" +) diff --git a/aws/internal/service/ec2/filter.go b/aws/internal/service/ec2/filter.go new file mode 100644 index 00000000000..60ca4a2b682 --- /dev/null +++ b/aws/internal/service/ec2/filter.go @@ -0,0 +1,55 @@ +package ec2 + +import ( + "sort" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" +) + +// BuildAttributeFilterList takes a flat map of scalar attributes (most +// likely values extracted from a *schema.ResourceData on an EC2-querying +// data source) and produces a []*ec2.Filter representing an exact match +// for each of the given non-empty attributes. +// +// The keys of the given attributes map are the attribute names expected +// by the EC2 API, which are usually either in camelcase or with dash-separated +// words. We conventionally map these to underscore-separated identifiers +// with the same words when presenting these as data source query attributes +// in Terraform. +// +// It's the callers responsibility to transform any non-string values into +// the appropriate string serialization required by the AWS API when +// encoding the given filter. Any attributes given with empty string values +// are ignored, assuming that the user wishes to leave that attribute +// unconstrained while filtering. +// +// The purpose of this function is to create values to pass in +// for the "Filters" attribute on most of the "Describe..." API functions in +// the EC2 API, to aid in the implementation of Terraform data sources that +// retrieve data about EC2 objects. +func BuildAttributeFilterList(attrs map[string]string) []*ec2.Filter { + var filters []*ec2.Filter + + // sort the filters by name to make the output deterministic + var names []string + for filterName := range attrs { + names = append(names, filterName) + } + + sort.Strings(names) + + for _, filterName := range names { + value := attrs[filterName] + if value == "" { + continue + } + + filters = append(filters, &ec2.Filter{ + Name: aws.String(filterName), + Values: []*string{aws.String(value)}, + }) + } + + return filters +} diff --git a/aws/internal/service/ec2/finder/finder.go b/aws/internal/service/ec2/finder/finder.go new file mode 100644 index 00000000000..03963246074 --- /dev/null +++ b/aws/internal/service/ec2/finder/finder.go @@ -0,0 +1,73 @@ +package finder + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + tfec2 "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/ec2" +) + +func ClientVpnAuthorizationRule(conn *ec2.EC2, endpointID, targetNetworkCidr, accessGroupID string) (*ec2.DescribeClientVpnAuthorizationRulesOutput, error) { + filters := map[string]string{ + "destination-cidr": targetNetworkCidr, + } + if accessGroupID != "" { + filters["group-id"] = accessGroupID + } + + input := &ec2.DescribeClientVpnAuthorizationRulesInput{ + ClientVpnEndpointId: aws.String(endpointID), + Filters: tfec2.BuildAttributeFilterList(filters), + } + + return conn.DescribeClientVpnAuthorizationRules(input) + +} + +func ClientVpnAuthorizationRuleByID(conn *ec2.EC2, authorizationRuleID string) (*ec2.DescribeClientVpnAuthorizationRulesOutput, error) { + endpointID, targetNetworkCidr, accessGroupID, err := tfec2.ClientVpnAuthorizationRuleParseID(authorizationRuleID) + if err != nil { + return nil, err + } + + return ClientVpnAuthorizationRule(conn, endpointID, targetNetworkCidr, accessGroupID) +} + +func ClientVpnRoute(conn *ec2.EC2, endpointID, targetSubnetID, destinationCidr string) (*ec2.DescribeClientVpnRoutesOutput, error) { + filters := map[string]string{ + "target-subnet": targetSubnetID, + "destination-cidr": destinationCidr, + } + + input := &ec2.DescribeClientVpnRoutesInput{ + ClientVpnEndpointId: aws.String(endpointID), + Filters: tfec2.BuildAttributeFilterList(filters), + } + + return conn.DescribeClientVpnRoutes(input) +} + +func ClientVpnRouteByID(conn *ec2.EC2, routeID string) (*ec2.DescribeClientVpnRoutesOutput, error) { + endpointID, targetSubnetID, destinationCidr, err := tfec2.ClientVpnRouteParseID(routeID) + if err != nil { + return nil, err + } + + return ClientVpnRoute(conn, endpointID, targetSubnetID, destinationCidr) +} + +// SecurityGroupByID looks up a security group by ID. When not found, returns nil and potentially an API error. +func SecurityGroupByID(conn *ec2.EC2, id string) (*ec2.SecurityGroup, error) { + req := &ec2.DescribeSecurityGroupsInput{ + GroupIds: aws.StringSlice([]string{id}), + } + result, err := conn.DescribeSecurityGroups(req) + if err != nil { + return nil, err + } + + if result == nil || len(result.SecurityGroups) == 0 || result.SecurityGroups[0] == nil { + return nil, nil + } + + return result.SecurityGroups[0], nil +} diff --git a/aws/internal/service/ec2/id.go b/aws/internal/service/ec2/id.go new file mode 100644 index 00000000000..824e23eaead --- /dev/null +++ b/aws/internal/service/ec2/id.go @@ -0,0 +1,51 @@ +package ec2 + +import ( + "fmt" + "strings" +) + +const clientVpnAuthorizationRuleIDSeparator = "," + +func ClientVpnAuthorizationRuleCreateID(endpointID, targetNetworkCidr, accessGroupID string) string { + parts := []string{endpointID, targetNetworkCidr} + if accessGroupID != "" { + parts = append(parts, accessGroupID) + } + id := strings.Join(parts, clientVpnAuthorizationRuleIDSeparator) + return id +} + +func ClientVpnAuthorizationRuleParseID(id string) (string, string, string, error) { + parts := strings.Split(id, clientVpnAuthorizationRuleIDSeparator) + if len(parts) == 2 && parts[0] != "" && parts[1] != "" { + return parts[0], parts[1], "", nil + } + if len(parts) == 3 && parts[0] != "" && parts[1] != "" && parts[2] != "" { + return parts[0], parts[1], parts[2], nil + } + + return "", "", "", + fmt.Errorf("unexpected format for ID (%q), expected endpoint-id"+clientVpnAuthorizationRuleIDSeparator+ + "target-network-cidr or endpoint-id"+clientVpnAuthorizationRuleIDSeparator+"target-network-cidr"+ + clientVpnAuthorizationRuleIDSeparator+"group-id", id) +} + +const clientVpnRouteIDSeparator = "," + +func ClientVpnRouteCreateID(endpointID, targetSubnetID, destinationCidr string) string { + parts := []string{endpointID, targetSubnetID, destinationCidr} + id := strings.Join(parts, clientVpnRouteIDSeparator) + return id +} + +func ClientVpnRouteParseID(id string) (string, string, string, error) { + parts := strings.Split(id, clientVpnRouteIDSeparator) + if len(parts) == 3 && parts[0] != "" && parts[1] != "" && parts[2] != "" { + return parts[0], parts[1], parts[2], nil + } + + return "", "", "", + fmt.Errorf("unexpected format for ID (%q), expected endpoint-id"+clientVpnRouteIDSeparator+ + "target-subnet-id"+clientVpnRouteIDSeparator+"destination-cidr-block", id) +} diff --git a/aws/internal/service/ec2/waiter/status.go b/aws/internal/service/ec2/waiter/status.go new file mode 100644 index 00000000000..47b65840a4c --- /dev/null +++ b/aws/internal/service/ec2/waiter/status.go @@ -0,0 +1,173 @@ +package waiter + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + tfec2 "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/ec2" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/ec2/finder" +) + +// LocalGatewayRouteTableVpcAssociationState fetches the LocalGatewayRouteTableVpcAssociation and its State +func LocalGatewayRouteTableVpcAssociationState(conn *ec2.EC2, localGatewayRouteTableVpcAssociationID string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + input := &ec2.DescribeLocalGatewayRouteTableVpcAssociationsInput{ + LocalGatewayRouteTableVpcAssociationIds: aws.StringSlice([]string{localGatewayRouteTableVpcAssociationID}), + } + + output, err := conn.DescribeLocalGatewayRouteTableVpcAssociations(input) + + if err != nil { + return nil, "", err + } + + var association *ec2.LocalGatewayRouteTableVpcAssociation + + for _, outputAssociation := range output.LocalGatewayRouteTableVpcAssociations { + if outputAssociation == nil { + continue + } + + if aws.StringValue(outputAssociation.LocalGatewayRouteTableVpcAssociationId) == localGatewayRouteTableVpcAssociationID { + association = outputAssociation + break + } + } + + if association == nil { + return association, ec2.RouteTableAssociationStateCodeDisassociated, nil + } + + return association, aws.StringValue(association.State), nil + } +} + +const ( + ClientVpnEndpointStatusNotFound = "NotFound" + + ClientVpnEndpointStatusUnknown = "Unknown" +) + +// ClientVpnEndpointStatus fetches the Client VPN endpoint and its Status +func ClientVpnEndpointStatus(conn *ec2.EC2, endpointID string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + result, err := conn.DescribeClientVpnEndpoints(&ec2.DescribeClientVpnEndpointsInput{ + ClientVpnEndpointIds: aws.StringSlice([]string{endpointID}), + }) + if tfec2.ErrCodeEquals(err, tfec2.ErrCodeClientVpnEndpointIdNotFound) { + return nil, ClientVpnEndpointStatusNotFound, nil + } + if err != nil { + return nil, ClientVpnEndpointStatusUnknown, err + } + + if result == nil || len(result.ClientVpnEndpoints) == 0 || result.ClientVpnEndpoints[0] == nil { + return nil, ClientVpnEndpointStatusNotFound, nil + } + + endpoint := result.ClientVpnEndpoints[0] + if endpoint.Status == nil || endpoint.Status.Code == nil { + return endpoint, ClientVpnEndpointStatusUnknown, nil + } + + return endpoint, aws.StringValue(endpoint.Status.Code), nil + } +} + +const ( + ClientVpnAuthorizationRuleStatusNotFound = "NotFound" + + ClientVpnAuthorizationRuleStatusUnknown = "Unknown" +) + +// ClientVpnAuthorizationRuleStatus fetches the Client VPN authorization rule and its Status +func ClientVpnAuthorizationRuleStatus(conn *ec2.EC2, authorizationRuleID string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + result, err := finder.ClientVpnAuthorizationRuleByID(conn, authorizationRuleID) + if tfec2.ErrCodeEquals(err, tfec2.ErrCodeClientVpnAuthorizationRuleNotFound) { + return nil, ClientVpnAuthorizationRuleStatusNotFound, nil + } + if err != nil { + return nil, ClientVpnAuthorizationRuleStatusUnknown, err + } + + if result == nil || len(result.AuthorizationRules) == 0 || result.AuthorizationRules[0] == nil { + return nil, ClientVpnAuthorizationRuleStatusNotFound, nil + } + + if len(result.AuthorizationRules) > 1 { + return nil, ClientVpnAuthorizationRuleStatusUnknown, fmt.Errorf("internal error: found %d results for Client VPN authorization rule (%s) status, need 1", len(result.AuthorizationRules), authorizationRuleID) + } + + rule := result.AuthorizationRules[0] + if rule.Status == nil || rule.Status.Code == nil { + return rule, ClientVpnAuthorizationRuleStatusUnknown, nil + } + + return rule, aws.StringValue(rule.Status.Code), nil + } +} + +const ( + ClientVpnRouteStatusNotFound = "NotFound" + + ClientVpnRouteStatusUnknown = "Unknown" +) + +// ClientVpnRouteStatus fetches the Client VPN route and its Status +func ClientVpnRouteStatus(conn *ec2.EC2, routeID string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + result, err := finder.ClientVpnRouteByID(conn, routeID) + if tfec2.ErrCodeEquals(err, tfec2.ErrCodeClientVpnRouteNotFound) { + return nil, ClientVpnRouteStatusNotFound, nil + } + if err != nil { + return nil, ClientVpnRouteStatusUnknown, err + } + + if result == nil || len(result.Routes) == 0 || result.Routes[0] == nil { + return nil, ClientVpnRouteStatusNotFound, nil + } + + if len(result.Routes) > 1 { + return nil, ClientVpnRouteStatusUnknown, fmt.Errorf("internal error: found %d results for Client VPN route (%s) status, need 1", len(result.Routes), routeID) + } + + rule := result.Routes[0] + if rule.Status == nil || rule.Status.Code == nil { + return rule, ClientVpnRouteStatusUnknown, nil + } + + return rule, aws.StringValue(rule.Status.Code), nil + } +} + +const ( + SecurityGroupStatusCreated = "Created" + + SecurityGroupStatusNotFound = "NotFound" + + SecurityGroupStatusUnknown = "Unknown" +) + +// SecurityGroupStatus fetches the security group and its status +func SecurityGroupStatus(conn *ec2.EC2, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + group, err := finder.SecurityGroupByID(conn, id) + if tfec2.ErrCodeEquals(err, tfec2.InvalidSecurityGroupIDNotFound) || + tfec2.ErrCodeEquals(err, tfec2.InvalidGroupNotFound) { + return nil, SecurityGroupStatusNotFound, nil + } + if err != nil { + return nil, SecurityGroupStatusUnknown, err + } + + if group == nil { + return nil, SecurityGroupStatusNotFound, nil + } + + return group, SecurityGroupStatusCreated, nil + } +} diff --git a/aws/internal/service/ec2/waiter/waiter.go b/aws/internal/service/ec2/waiter/waiter.go new file mode 100644 index 00000000000..ce4f6b3f80d --- /dev/null +++ b/aws/internal/service/ec2/waiter/waiter.go @@ -0,0 +1,151 @@ +package waiter + +import ( + "time" + + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // Maximum amount of time to wait for a LocalGatewayRouteTableVpcAssociation to return Associated + LocalGatewayRouteTableVpcAssociationAssociatedTimeout = 5 * time.Minute + + // Maximum amount of time to wait for a LocalGatewayRouteTableVpcAssociation to return Disassociated + LocalGatewayRouteTableVpcAssociationDisassociatedTimeout = 5 * time.Minute +) + +// LocalGatewayRouteTableVpcAssociationAssociated waits for a LocalGatewayRouteTableVpcAssociation to return Associated +func LocalGatewayRouteTableVpcAssociationAssociated(conn *ec2.EC2, localGatewayRouteTableVpcAssociationID string) (*ec2.LocalGatewayRouteTableVpcAssociation, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ec2.RouteTableAssociationStateCodeAssociating}, + Target: []string{ec2.RouteTableAssociationStateCodeAssociated}, + Refresh: LocalGatewayRouteTableVpcAssociationState(conn, localGatewayRouteTableVpcAssociationID), + Timeout: LocalGatewayRouteTableVpcAssociationAssociatedTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*ec2.LocalGatewayRouteTableVpcAssociation); ok { + return output, err + } + + return nil, err +} + +// LocalGatewayRouteTableVpcAssociationDisassociated waits for a LocalGatewayRouteTableVpcAssociation to return Disassociated +func LocalGatewayRouteTableVpcAssociationDisassociated(conn *ec2.EC2, localGatewayRouteTableVpcAssociationID string) (*ec2.LocalGatewayRouteTableVpcAssociation, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ec2.RouteTableAssociationStateCodeDisassociating}, + Target: []string{ec2.RouteTableAssociationStateCodeDisassociated}, + Refresh: LocalGatewayRouteTableVpcAssociationState(conn, localGatewayRouteTableVpcAssociationID), + Timeout: LocalGatewayRouteTableVpcAssociationAssociatedTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*ec2.LocalGatewayRouteTableVpcAssociation); ok { + return output, err + } + + return nil, err +} + +const ( + ClientVpnEndpointDeletedTimout = 5 * time.Minute +) + +func ClientVpnEndpointDeleted(conn *ec2.EC2, id string) (*ec2.ClientVpnEndpoint, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ec2.ClientVpnEndpointStatusCodeDeleting}, + Target: []string{}, + Refresh: ClientVpnEndpointStatus(conn, id), + Timeout: ClientVpnEndpointDeletedTimout, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*ec2.ClientVpnEndpoint); ok { + return output, err + } + + return nil, err +} + +const ( + ClientVpnAuthorizationRuleActiveTimeout = 1 * time.Minute + + ClientVpnAuthorizationRuleRevokedTimeout = 1 * time.Minute +) + +func ClientVpnAuthorizationRuleAuthorized(conn *ec2.EC2, authorizationRuleID string) (*ec2.AuthorizationRule, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ec2.ClientVpnAuthorizationRuleStatusCodeAuthorizing}, + Target: []string{ec2.ClientVpnAuthorizationRuleStatusCodeActive}, + Refresh: ClientVpnAuthorizationRuleStatus(conn, authorizationRuleID), + Timeout: ClientVpnAuthorizationRuleActiveTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*ec2.AuthorizationRule); ok { + return output, err + } + + return nil, err +} + +func ClientVpnAuthorizationRuleRevoked(conn *ec2.EC2, authorizationRuleID string) (*ec2.AuthorizationRule, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ec2.ClientVpnAuthorizationRuleStatusCodeRevoking}, + Target: []string{}, + Refresh: ClientVpnAuthorizationRuleStatus(conn, authorizationRuleID), + Timeout: ClientVpnAuthorizationRuleRevokedTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*ec2.AuthorizationRule); ok { + return output, err + } + + return nil, err +} + +const ( + ClientVpnRouteDeletedTimeout = 1 * time.Minute +) + +func ClientVpnRouteDeleted(conn *ec2.EC2, routeID string) (*ec2.ClientVpnRoute, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ec2.ClientVpnRouteStatusCodeActive, ec2.ClientVpnRouteStatusCodeDeleting}, + Target: []string{}, + Refresh: ClientVpnRouteStatus(conn, routeID), + Timeout: ClientVpnRouteDeletedTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*ec2.ClientVpnRoute); ok { + return output, err + } + + return nil, err +} + +func SecurityGroupCreated(conn *ec2.EC2, id string, timeout time.Duration) (*ec2.SecurityGroup, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{SecurityGroupStatusNotFound}, + Target: []string{SecurityGroupStatusCreated}, + Refresh: SecurityGroupStatus(conn, id), + Timeout: timeout, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*ec2.SecurityGroup); ok { + return output, err + } + + return nil, err +} diff --git a/aws/internal/service/ecs/waiter/status.go b/aws/internal/service/ecs/waiter/status.go new file mode 100644 index 00000000000..9b1ba797bb2 --- /dev/null +++ b/aws/internal/service/ecs/waiter/status.go @@ -0,0 +1,36 @@ +package waiter + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ecs" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // EventSubscription NotFound + CapacityProviderStatusNotFound = "NotFound" + + // EventSubscription Unknown + CapacityProviderStatusUnknown = "Unknown" +) + +// CapacityProviderStatus fetches the Capacity Provider and its Status +func CapacityProviderStatus(conn *ecs.ECS, capacityProvider string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + input := &ecs.DescribeCapacityProvidersInput{ + CapacityProviders: aws.StringSlice([]string{capacityProvider}), + } + + output, err := conn.DescribeCapacityProviders(input) + + if err != nil { + return nil, CapacityProviderStatusUnknown, err + } + + if len(output.CapacityProviders) == 0 { + return nil, CapacityProviderStatusNotFound, nil + } + + return output.CapacityProviders[0], aws.StringValue(output.CapacityProviders[0].Status), nil + } +} diff --git a/aws/internal/service/ecs/waiter/waiter.go b/aws/internal/service/ecs/waiter/waiter.go new file mode 100644 index 00000000000..dd4a3ca4895 --- /dev/null +++ b/aws/internal/service/ecs/waiter/waiter.go @@ -0,0 +1,31 @@ +package waiter + +import ( + "time" + + "github.com/aws/aws-sdk-go/service/ecs" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // Maximum amount of time to wait for a Capacity Provider to return INACTIVE + CapacityProviderInactiveTimeout = 20 * time.Minute +) + +// CapacityProviderInactive waits for a Capacity Provider to return INACTIVE +func CapacityProviderInactive(conn *ecs.ECS, capacityProvider string) (*ecs.CapacityProvider, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ecs.CapacityProviderStatusActive}, + Target: []string{ecs.CapacityProviderStatusInactive}, + Refresh: CapacityProviderStatus(conn, capacityProvider), + Timeout: CapacityProviderInactiveTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if v, ok := outputRaw.(*ecs.CapacityProvider); ok { + return v, err + } + + return nil, err +} diff --git a/aws/internal/service/guardduty/waiter/status.go b/aws/internal/service/guardduty/waiter/status.go index 33df4596100..411e05276a3 100644 --- a/aws/internal/service/guardduty/waiter/status.go +++ b/aws/internal/service/guardduty/waiter/status.go @@ -3,7 +3,7 @@ package waiter import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) const ( diff --git a/aws/internal/service/guardduty/waiter/waiter.go b/aws/internal/service/guardduty/waiter/waiter.go index 7124290afda..85972523476 100644 --- a/aws/internal/service/guardduty/waiter/waiter.go +++ b/aws/internal/service/guardduty/waiter/waiter.go @@ -4,7 +4,7 @@ import ( "time" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) const ( diff --git a/aws/internal/service/kinesisanalytics/waiter/status.go b/aws/internal/service/kinesisanalytics/waiter/status.go new file mode 100644 index 00000000000..eae16ef2aa2 --- /dev/null +++ b/aws/internal/service/kinesisanalytics/waiter/status.go @@ -0,0 +1,38 @@ +package waiter + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/kinesisanalytics" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // ApplicationStatus NotFound + ApplicationStatusNotFound = "NotFound" + + // ApplicationStatus Unknown + ApplicationStatusUnknown = "Unknown" +) + +// ApplicationStatus fetches the Application and its Status +func ApplicationStatus(conn *kinesisanalytics.KinesisAnalytics, applicationName string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + input := &kinesisanalytics.DescribeApplicationInput{ + ApplicationName: aws.String(applicationName), + } + + output, err := conn.DescribeApplication(input) + + if err != nil { + return nil, ApplicationStatusUnknown, err + } + + application := output.ApplicationDetail + + if application == nil { + return application, ApplicationStatusNotFound, nil + } + + return application, aws.StringValue(application.ApplicationStatus), nil + } +} diff --git a/aws/internal/service/kinesisanalytics/waiter/waiter.go b/aws/internal/service/kinesisanalytics/waiter/waiter.go new file mode 100644 index 00000000000..18c2a60f686 --- /dev/null +++ b/aws/internal/service/kinesisanalytics/waiter/waiter.go @@ -0,0 +1,31 @@ +package waiter + +import ( + "time" + + "github.com/aws/aws-sdk-go/service/kinesisanalytics" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // Maximum amount of time to wait for an Application to be deleted + ApplicationDeletedTimeout = 20 * time.Minute +) + +// ApplicationDeleted waits for an Application to be deleted +func ApplicationDeleted(conn *kinesisanalytics.KinesisAnalytics, applicationName string) (*kinesisanalytics.ApplicationSummary, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{kinesisanalytics.ApplicationStatusRunning, kinesisanalytics.ApplicationStatusDeleting}, + Target: []string{ApplicationStatusNotFound}, + Refresh: ApplicationStatus(conn, applicationName), + Timeout: ApplicationDeletedTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if v, ok := outputRaw.(*kinesisanalytics.ApplicationSummary); ok { + return v, err + } + + return nil, err +} diff --git a/aws/internal/service/kms/waiter/status.go b/aws/internal/service/kms/waiter/status.go index d0021759c22..194f73a9347 100644 --- a/aws/internal/service/kms/waiter/status.go +++ b/aws/internal/service/kms/waiter/status.go @@ -3,7 +3,7 @@ package waiter import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) // KeyState fetches the Key and its State diff --git a/aws/internal/service/kms/waiter/waiter.go b/aws/internal/service/kms/waiter/waiter.go index 741178145c5..b1fbc22155c 100644 --- a/aws/internal/service/kms/waiter/waiter.go +++ b/aws/internal/service/kms/waiter/waiter.go @@ -4,7 +4,7 @@ import ( "time" "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) const ( diff --git a/aws/internal/service/neptune/waiter/status.go b/aws/internal/service/neptune/waiter/status.go new file mode 100644 index 00000000000..3c833b0a240 --- /dev/null +++ b/aws/internal/service/neptune/waiter/status.go @@ -0,0 +1,36 @@ +package waiter + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/neptune" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // EventSubscription NotFound + EventSubscriptionStatusNotFound = "NotFound" + + // EventSubscription Unknown + EventSubscriptionStatusUnknown = "Unknown" +) + +// EventSubscriptionStatus fetches the EventSubscription and its Status +func EventSubscriptionStatus(conn *neptune.Neptune, subscriptionName string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + input := &neptune.DescribeEventSubscriptionsInput{ + SubscriptionName: aws.String(subscriptionName), + } + + output, err := conn.DescribeEventSubscriptions(input) + + if err != nil { + return nil, EventSubscriptionStatusUnknown, err + } + + if len(output.EventSubscriptionsList) == 0 { + return nil, EventSubscriptionStatusNotFound, nil + } + + return output.EventSubscriptionsList[0], aws.StringValue(output.EventSubscriptionsList[0].Status), nil + } +} diff --git a/aws/internal/service/neptune/waiter/waiter.go b/aws/internal/service/neptune/waiter/waiter.go new file mode 100644 index 00000000000..061e5e080a9 --- /dev/null +++ b/aws/internal/service/neptune/waiter/waiter.go @@ -0,0 +1,31 @@ +package waiter + +import ( + "time" + + "github.com/aws/aws-sdk-go/service/neptune" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // Maximum amount of time to wait for an EventSubscription to return Deleted + EventSubscriptionDeletedTimeout = 10 * time.Minute +) + +// DeploymentDeployed waits for a EventSubscription to return Deleted +func EventSubscriptionDeleted(conn *neptune.Neptune, subscriptionName string) (*neptune.EventSubscription, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{"deleting"}, + Target: []string{EventSubscriptionStatusNotFound}, + Refresh: EventSubscriptionStatus(conn, subscriptionName), + Timeout: EventSubscriptionDeletedTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if v, ok := outputRaw.(*neptune.EventSubscription); ok { + return v, err + } + + return nil, err +} diff --git a/aws/internal/service/rds/waiter/status.go b/aws/internal/service/rds/waiter/status.go new file mode 100644 index 00000000000..59039e5a825 --- /dev/null +++ b/aws/internal/service/rds/waiter/status.go @@ -0,0 +1,36 @@ +package waiter + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/rds" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // EventSubscription NotFound + EventSubscriptionStatusNotFound = "NotFound" + + // EventSubscription Unknown + EventSubscriptionStatusUnknown = "Unknown" +) + +// EventSubscriptionStatus fetches the EventSubscription and its Status +func EventSubscriptionStatus(conn *rds.RDS, subscriptionName string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + input := &rds.DescribeEventSubscriptionsInput{ + SubscriptionName: aws.String(subscriptionName), + } + + output, err := conn.DescribeEventSubscriptions(input) + + if err != nil { + return nil, EventSubscriptionStatusUnknown, err + } + + if len(output.EventSubscriptionsList) == 0 { + return nil, EventSubscriptionStatusNotFound, nil + } + + return output.EventSubscriptionsList[0], aws.StringValue(output.EventSubscriptionsList[0].Status), nil + } +} diff --git a/aws/internal/service/rds/waiter/waiter.go b/aws/internal/service/rds/waiter/waiter.go new file mode 100644 index 00000000000..aa18ccb2090 --- /dev/null +++ b/aws/internal/service/rds/waiter/waiter.go @@ -0,0 +1,31 @@ +package waiter + +import ( + "time" + + "github.com/aws/aws-sdk-go/service/rds" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // Maximum amount of time to wait for an EventSubscription to return Deleted + EventSubscriptionDeletedTimeout = 10 * time.Minute +) + +// DeploymentDeployed waits for a EventSubscription to return Deleted +func EventSubscriptionDeleted(conn *rds.RDS, subscriptionName string) (*rds.EventSubscription, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{"deleting"}, + Target: []string{EventSubscriptionStatusNotFound}, + Refresh: EventSubscriptionStatus(conn, subscriptionName), + Timeout: EventSubscriptionDeletedTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if v, ok := outputRaw.(*rds.EventSubscription); ok { + return v, err + } + + return nil, err +} diff --git a/aws/internal/service/secretsmanager/waiter/waiter.go b/aws/internal/service/secretsmanager/waiter/waiter.go new file mode 100644 index 00000000000..087f9e82ee8 --- /dev/null +++ b/aws/internal/service/secretsmanager/waiter/waiter.go @@ -0,0 +1,10 @@ +package waiter + +import ( + "time" +) + +const ( + // Maximum amount of time to wait for Secrets Manager deletions to propagate + DeletionPropagationTimeout = 2 * time.Minute +) diff --git a/aws/internal/service/servicediscovery/waiter/status.go b/aws/internal/service/servicediscovery/waiter/status.go index be6d4cfcad6..6768a31cb13 100644 --- a/aws/internal/service/servicediscovery/waiter/status.go +++ b/aws/internal/service/servicediscovery/waiter/status.go @@ -5,7 +5,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicediscovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) // OperationStatus fetches the Operation and its Status diff --git a/aws/internal/service/servicediscovery/waiter/waiter.go b/aws/internal/service/servicediscovery/waiter/waiter.go index ccba30a9bdf..5a6ed7fb2a3 100644 --- a/aws/internal/service/servicediscovery/waiter/waiter.go +++ b/aws/internal/service/servicediscovery/waiter/waiter.go @@ -4,7 +4,7 @@ import ( "time" "github.com/aws/aws-sdk-go/service/servicediscovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) const ( diff --git a/aws/internal/service/sfn/waiter/status.go b/aws/internal/service/sfn/waiter/status.go new file mode 100644 index 00000000000..9df5ac17e28 --- /dev/null +++ b/aws/internal/service/sfn/waiter/status.go @@ -0,0 +1,28 @@ +package waiter + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/sfn" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +// StateMachineStatus fetches the Operation and its Status +func StateMachineStatus(conn *sfn.SFN, stateMachineArn string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + input := &sfn.DescribeStateMachineInput{ + StateMachineArn: aws.String(stateMachineArn), + } + + output, err := conn.DescribeStateMachine(input) + + if err != nil { + return nil, "", err + } + + if output == nil { + return nil, "", nil + } + + return output, aws.StringValue(output.Status), nil + } +} diff --git a/aws/internal/service/sfn/waiter/waiter.go b/aws/internal/service/sfn/waiter/waiter.go new file mode 100644 index 00000000000..7306c478314 --- /dev/null +++ b/aws/internal/service/sfn/waiter/waiter.go @@ -0,0 +1,31 @@ +package waiter + +import ( + "time" + + "github.com/aws/aws-sdk-go/service/sfn" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // Maximum amount of time to wait for an Operation to return Success + StateMachineDeleteTimeout = 5 * time.Minute +) + +// StateMachineDeleted waits for an Operation to return Success +func StateMachineDeleted(conn *sfn.SFN, stateMachineArn string) (*sfn.DescribeStateMachineOutput, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{sfn.StateMachineStatusActive, sfn.StateMachineStatusDeleting}, + Target: []string{}, + Refresh: StateMachineStatus(conn, stateMachineArn), + Timeout: StateMachineDeleteTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if output, ok := outputRaw.(*sfn.DescribeStateMachineOutput); ok { + return output, err + } + + return nil, err +} diff --git a/aws/internal/service/workspaces/waiter/status.go b/aws/internal/service/workspaces/waiter/status.go new file mode 100644 index 00000000000..0a21ef70ba5 --- /dev/null +++ b/aws/internal/service/workspaces/waiter/status.go @@ -0,0 +1,43 @@ +package waiter + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/workspaces" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func DirectoryState(conn *workspaces.WorkSpaces, directoryID string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := conn.DescribeWorkspaceDirectories(&workspaces.DescribeWorkspaceDirectoriesInput{ + DirectoryIds: aws.StringSlice([]string{directoryID}), + }) + if err != nil { + return nil, workspaces.WorkspaceDirectoryStateError, err + } + + if len(output.Directories) == 0 { + return output, workspaces.WorkspaceDirectoryStateDeregistered, nil + } + + directory := output.Directories[0] + return directory, aws.StringValue(directory.State), nil + } +} + +func WorkspaceState(conn *workspaces.WorkSpaces, workspaceID string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + output, err := conn.DescribeWorkspaces(&workspaces.DescribeWorkspacesInput{ + WorkspaceIds: aws.StringSlice([]string{workspaceID}), + }) + if err != nil { + return nil, workspaces.WorkspaceStateError, err + } + + if len(output.Workspaces) == 0 { + return nil, workspaces.WorkspaceStateTerminated, nil + } + + workspace := output.Workspaces[0] + return workspace, aws.StringValue(workspace.State), nil + } +} diff --git a/aws/internal/service/workspaces/waiter/waiter.go b/aws/internal/service/workspaces/waiter/waiter.go new file mode 100644 index 00000000000..e7bcca0f226 --- /dev/null +++ b/aws/internal/service/workspaces/waiter/waiter.go @@ -0,0 +1,151 @@ +package waiter + +import ( + "time" + + "github.com/aws/aws-sdk-go/service/workspaces" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +const ( + // Maximum amount of time to wait for a Directory to return Registered + DirectoryRegisteredTimeout = 10 * time.Minute + + // Maximum amount of time to wait for a Directory to return Deregistered + DirectoryDeregisteredTimeout = 10 * time.Minute + + // Maximum amount of time to wait for a WorkSpace to return Available + WorkspaceAvailableTimeout = 30 * time.Minute + + // Maximum amount of time to wait for a WorkSpace while returning Updating + WorkspaceUpdatingTimeout = 10 * time.Minute + + // Amount of time to delay before checking WorkSpace when updating + WorkspaceUpdatingDelay = 1 * time.Minute + + // Maximum amount of time to wait for a WorkSpace to return Terminated + WorkspaceTerminatedTimeout = 10 * time.Minute +) + +func DirectoryRegistered(conn *workspaces.WorkSpaces, directoryID string) (*workspaces.WorkspaceDirectory, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ + workspaces.WorkspaceDirectoryStateRegistering, + }, + Target: []string{workspaces.WorkspaceDirectoryStateRegistered}, + Refresh: DirectoryState(conn, directoryID), + Timeout: DirectoryRegisteredTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if v, ok := outputRaw.(*workspaces.WorkspaceDirectory); ok { + return v, err + } + + return nil, err +} + +func DirectoryDeregistered(conn *workspaces.WorkSpaces, directoryID string) (*workspaces.WorkspaceDirectory, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ + workspaces.WorkspaceDirectoryStateRegistering, + workspaces.WorkspaceDirectoryStateRegistered, + workspaces.WorkspaceDirectoryStateDeregistering, + }, + Target: []string{ + workspaces.WorkspaceDirectoryStateDeregistered, + }, + Refresh: DirectoryState(conn, directoryID), + Timeout: DirectoryDeregisteredTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if v, ok := outputRaw.(*workspaces.WorkspaceDirectory); ok { + return v, err + } + + return nil, err +} + +func WorkspaceAvailable(conn *workspaces.WorkSpaces, workspaceID string) (*workspaces.Workspace, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ + workspaces.WorkspaceStatePending, + workspaces.WorkspaceStateStarting, + }, + Target: []string{workspaces.WorkspaceStateAvailable}, + Refresh: WorkspaceState(conn, workspaceID), + Timeout: WorkspaceAvailableTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if v, ok := outputRaw.(*workspaces.Workspace); ok { + return v, err + } + + return nil, err +} + +func WorkspaceTerminated(conn *workspaces.WorkSpaces, workspaceID string) (*workspaces.Workspace, error) { + stateConf := &resource.StateChangeConf{ + Pending: []string{ + workspaces.WorkspaceStatePending, + workspaces.WorkspaceStateAvailable, + workspaces.WorkspaceStateImpaired, + workspaces.WorkspaceStateUnhealthy, + workspaces.WorkspaceStateRebooting, + workspaces.WorkspaceStateStarting, + workspaces.WorkspaceStateRebuilding, + workspaces.WorkspaceStateRestoring, + workspaces.WorkspaceStateMaintenance, + workspaces.WorkspaceStateAdminMaintenance, + workspaces.WorkspaceStateSuspended, + workspaces.WorkspaceStateUpdating, + workspaces.WorkspaceStateStopping, + workspaces.WorkspaceStateStopped, + workspaces.WorkspaceStateTerminating, + workspaces.WorkspaceStateError, + }, + Target: []string{ + workspaces.WorkspaceStateTerminated, + }, + Refresh: WorkspaceState(conn, workspaceID), + Timeout: WorkspaceTerminatedTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if v, ok := outputRaw.(*workspaces.Workspace); ok { + return v, err + } + + return nil, err +} + +func WorkspaceUpdated(conn *workspaces.WorkSpaces, workspaceID string) (*workspaces.Workspace, error) { + // OperationInProgressException: The properties of this WorkSpace are currently under modification. Please try again in a moment. + // AWS Workspaces service doesn't change instance status to "Updating" during property modification. Respective AWS Support feature request has been created. Meanwhile, artificial delay is placed here as a workaround. + stateConf := &resource.StateChangeConf{ + Pending: []string{ + workspaces.WorkspaceStateUpdating, + }, + Target: []string{ + workspaces.WorkspaceStateAvailable, + workspaces.WorkspaceStateStopped, + }, + Refresh: WorkspaceState(conn, workspaceID), + Delay: WorkspaceUpdatingDelay, + Timeout: WorkspaceUpdatingTimeout, + } + + outputRaw, err := stateConf.WaitForState() + + if v, ok := outputRaw.(*workspaces.Workspace); ok { + return v, err + } + + return nil, err +} diff --git a/aws/internal/tfawsresource/testing.go b/aws/internal/tfawsresource/testing.go new file mode 100644 index 00000000000..dc38dfc772a --- /dev/null +++ b/aws/internal/tfawsresource/testing.go @@ -0,0 +1,180 @@ +package tfawsresource + +import ( + "fmt" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +const ( + sentinelIndex = "*" +) + +// TestCheckTypeSetElemNestedAttrs is a resource.TestCheckFunc that accepts a resource +// name, an attribute path, which should use the sentinel value '*' for indexing +// into a TypeSet. The function verifies that an element matches the whole value +// map. +// +// You may check for unset keys, however this will also match keys set to empty +// string. Please provide a map with at least 1 non-empty value. +// +// map[string]string{ +// "key1": "value", +// "key2": "", +// } +// +// Use this function over SDK provided TestCheckFunctions when validating a +// TypeSet where its elements are a nested object with their own attrs/values. +// +// Please note, if the provided value map is not granular enough, there exists +// the possibility you match an element you were not intending to, in the TypeSet. +// Provide a full mapping of attributes to be sure the unique element exists. +func TestCheckTypeSetElemNestedAttrs(name, attr string, values map[string]string) resource.TestCheckFunc { + return func(s *terraform.State) error { + is, err := instanceState(s, name) + if err != nil { + return err + } + + matches := make(map[string]int) + attrParts := strings.Split(attr, ".") + if attrParts[len(attrParts)-1] != sentinelIndex { + return fmt.Errorf("%q does not end with the special value %q", attr, sentinelIndex) + } + // account for cases where the user is trying to see if the value is unset/empty + // there may be ambiguous scenarios where a field was deliberately unset vs set + // to the empty string, this will match both, which may be a false positive. + var matchCount int + for _, v := range values { + if v != "" { + matchCount++ + } + } + if matchCount == 0 { + return fmt.Errorf("%#v has no non-empty values", values) + } + for stateKey, stateValue := range is.Attributes { + stateKeyParts := strings.Split(stateKey, ".") + // a Set/List item with nested attrs would have a flatmap address of + // at least length 3 + // foo.0.name = "bar" + if len(stateKeyParts) < 3 { + continue + } + var pathMatch bool + for i := range attrParts { + if attrParts[i] != stateKeyParts[i] && attrParts[i] != sentinelIndex { + break + } + if i == len(attrParts)-1 { + pathMatch = true + } + } + if !pathMatch { + continue + } + id := stateKeyParts[len(attrParts)-1] + nestedAttr := strings.Join(stateKeyParts[len(attrParts):], ".") + if v, keyExists := values[nestedAttr]; keyExists && v == stateValue { + matches[id] = matches[id] + 1 + if matches[id] == matchCount { + return nil + } + } + } + + return fmt.Errorf("%q no TypeSet element %q, with nested attrs %#v in state: %#v", name, attr, values, is.Attributes) + } +} + +// TestCheckTypeSetElemAttr is a resource.TestCheckFunc that accepts a resource +// name, an attribute path, which should use the sentinel value '*' for indexing +// into a TypeSet. The function verifies that an element matches the provided +// value. +// +// Use this function over SDK provided TestCheckFunctions when validating a +// TypeSet where its elements are a simple value +func TestCheckTypeSetElemAttr(name, attr, value string) resource.TestCheckFunc { + return func(s *terraform.State) error { + is, err := instanceState(s, name) + if err != nil { + return err + } + + err = testCheckTypeSetElem(is, attr, value) + if err != nil { + return fmt.Errorf("%q error: %s", name, err) + } + + return nil + } +} + +// TestCheckTypeSetElemAttrPair is a TestCheckFunc that verifies a pair of name/key +// combinations are equal where the first uses the sentinel value to index into a +// TypeSet. +// +// E.g., tfawsresource.TestCheckTypeSetElemAttrPair("aws_autoscaling_group.bar", "availability_zones.*", "data.aws_availability_zones.available", "names.0") +func TestCheckTypeSetElemAttrPair(nameFirst, keyFirst, nameSecond, keySecond string) resource.TestCheckFunc { + return func(s *terraform.State) error { + isFirst, err := instanceState(s, nameFirst) + if err != nil { + return err + } + + isSecond, err := instanceState(s, nameSecond) + if err != nil { + return err + } + + vSecond, okSecond := isSecond.Attributes[keySecond] + if !okSecond { + return fmt.Errorf("%s: Attribute %q not set, cannot be checked against TypeSet", nameSecond, keySecond) + } + + return testCheckTypeSetElem(isFirst, keyFirst, vSecond) + } +} + +// instanceState returns the primary instance state for the given +// resource name in the root module. +func instanceState(s *terraform.State, name string) (*terraform.InstanceState, error) { + ms := s.RootModule() + rs, ok := ms.Resources[name] + if !ok { + return nil, fmt.Errorf("Not found: %s in %s", name, ms.Path) + } + + is := rs.Primary + if is == nil { + return nil, fmt.Errorf("No primary instance: %s in %s", name, ms.Path) + } + + return is, nil +} + +func testCheckTypeSetElem(is *terraform.InstanceState, attr, value string) error { + attrParts := strings.Split(attr, ".") + if attrParts[len(attrParts)-1] != sentinelIndex { + return fmt.Errorf("%q does not end with the special value %q", attr, sentinelIndex) + } + for stateKey, stateValue := range is.Attributes { + if stateValue == value { + stateKeyParts := strings.Split(stateKey, ".") + if len(stateKeyParts) == len(attrParts) { + for i := range attrParts { + if attrParts[i] != stateKeyParts[i] && attrParts[i] != sentinelIndex { + break + } + if i == len(attrParts)-1 { + return nil + } + } + } + } + } + + return fmt.Errorf("no TypeSet element %q, with value %q in state: %#v", attr, value, is.Attributes) +} diff --git a/aws/internal/tfawsresource/testing_test.go b/aws/internal/tfawsresource/testing_test.go new file mode 100644 index 00000000000..4797fd7b779 --- /dev/null +++ b/aws/internal/tfawsresource/testing_test.go @@ -0,0 +1,1710 @@ +package tfawsresource + +import ( + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestTestCheckTypeSetElemAttr(t *testing.T) { + testCases := []struct { + Description string + ResourceAddress string + ResourceAttribute string + Value string + TerraformState *terraform.State + ExpectedError func(err error) bool + }{ + { + Description: "no resources", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Value: "", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{}, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "Not found: example_thing.test") + }, + }, + { + Description: "resource not found", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Value: "", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_other_thing.test": { + Type: "example_other_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "Not found: example_thing.test") + }, + }, + { + Description: "no primary instance", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Value: "", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Deposed: []*terraform.InstanceState{ + { + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + }, + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "No primary instance: example_thing.test") + }, + }, + { + Description: "attribute path does not end with sentinel value", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test", + Value: "", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "does not end with the special value") + }, + }, + { + Description: "attribute not found", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Value: "", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "\"example_thing.test\" error: no TypeSet element \"test.*\"") + }, + }, + { + Description: "single root TypeSet attribute match", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Value: "value1", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "3", + "id": "11111", + "test.%": "1", + "test.12345": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "single root TypeSet attribute mismatch", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Value: "value2", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "3", + "id": "11111", + "test.%": "1", + "test.12345": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "\"example_thing.test\" error: no TypeSet element \"test.*\"") + }, + }, + { + Description: "multiple root TypeSet attribute match", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Value: "value1", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "4", + "id": "11111", + "test.%": "2", + "test.12345": "value2", + "test.67890": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "multiple root TypeSet attribute mismatch", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Value: "value3", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "4", + "id": "11111", + "test.%": "2", + "test.12345": "value2", + "test.67890": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "\"example_thing.test\" error: no TypeSet element \"test.*\"") + }, + }, + { + Description: "single nested TypeSet attribute match", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.0.nested_test.*", + Value: "value1", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "4", + "id": "11111", + "test.%": "1", + "test.0.nested_test.12345": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "single nested TypeSet attribute mismatch", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.0.nested_test.*", + Value: "value2", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "4", + "id": "11111", + "test.%": "1", + "test.0.nested_test.12345": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "\"example_thing.test\" error: no TypeSet element \"test.0.nested_test.*\"") + }, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.Description, func(t *testing.T) { + err := TestCheckTypeSetElemAttr(testCase.ResourceAddress, testCase.ResourceAttribute, testCase.Value)(testCase.TerraformState) + + if err != nil { + if testCase.ExpectedError == nil { + t.Fatalf("expected no error, got error: %s", err) + } + + if !testCase.ExpectedError(err) { + t.Fatalf("unexpected error: %s", err) + } + + t.Logf("received expected error: %s", err) + return + } + + if err == nil && testCase.ExpectedError != nil { + t.Fatalf("expected error, got no error") + } + }) + } +} + +func TestTestCheckTypeSetElemAttrPair(t *testing.T) { + testCases := []struct { + Description string + FirstResourceAddress string + FirstResourceAttribute string + SecondResourceAddress string + SecondResourceAttribute string + TerraformState *terraform.State + ExpectedError func(err error) bool + }{ + { + Description: "first resource no primary instance", + FirstResourceAddress: "asg.bar", + FirstResourceAttribute: "az.*", + SecondResourceAddress: "data.az.available", + SecondResourceAttribute: "names.0", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "asg.bar": { + Type: "asg", + Provider: "example", + }, + "data.az.available": { + Type: "data.az", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "3579", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "3579", + "names.#": "3", + "names.0": "uswst3", + "names.1": "uswst2", + "names.3": "uswst1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "No primary instance") + }, + }, + { + Description: "second resource no primary instance", + FirstResourceAddress: "asg.bar", + FirstResourceAttribute: "az.*", + SecondResourceAddress: "data.az.available", + SecondResourceAttribute: "names.0", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "asg.bar": { + Type: "asg", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + "az.%": "2", + "az.12345": "uswst2", + "az.23456": "uswst3", + }, + }, + }, + "data.az.available": { + Type: "data.az", + Provider: "example", + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "No primary instance") + }, + }, + { + Description: "no resources", + FirstResourceAddress: "asg.bar", + FirstResourceAttribute: "az.*", + SecondResourceAddress: "data.az.available", + SecondResourceAttribute: "names.0", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{}, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "Not found: asg.bar") + }, + }, + { + Description: "first resource not found", + FirstResourceAddress: "asg.bar", + FirstResourceAttribute: "az.*", + SecondResourceAddress: "data.az.available", + SecondResourceAttribute: "names.0", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "data.az.available": { + Type: "data.az", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "3579", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "3579", + "names.#": "3", + "names.0": "uswst3", + "names.1": "uswst2", + "names.3": "uswst1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "Not found: asg.bar") + }, + }, + { + Description: "second resource not found", + FirstResourceAddress: "asg.bar", + FirstResourceAttribute: "az.*", + SecondResourceAddress: "data.az.available", + SecondResourceAttribute: "names.0", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "asg.bar": { + Type: "asg", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + "az.%": "2", + "az.12345": "uswst2", + "az.23456": "uswst3", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "Not found") + }, + }, + { + Description: "first resource attribute not found", + FirstResourceAddress: "asg.bar", + FirstResourceAttribute: "az.*", + SecondResourceAddress: "data.az.available", + SecondResourceAttribute: "names.0", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "asg.bar": { + Type: "asg", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + }, + }, + }, + "data.az.available": { + Type: "data.az", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "3579", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "3579", + "names.#": "3", + "names.0": "uswst3", + "names.1": "uswst2", + "names.3": "uswst1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "no TypeSet element \"az.*\", with value \"uswst3\" in state") + }, + }, + { + Description: "second resource attribute not found", + FirstResourceAddress: "asg.bar", + FirstResourceAttribute: "az.*", + SecondResourceAddress: "data.az.available", + SecondResourceAttribute: "names.0", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "asg.bar": { + Type: "asg", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + "az.%": "2", + "az.12345": "uswst2", + "az.23456": "uswst3", + }, + }, + }, + "data.az.available": { + Type: "data.az", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "3579", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "3579", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), `Attribute "names.0" not set`) + }, + }, + { + Description: "first resource attribute does not end with sentinel", + FirstResourceAddress: "asg.bar", + FirstResourceAttribute: "az.34812", + SecondResourceAddress: "data.az.available", + SecondResourceAttribute: "names.0", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "asg.bar": { + Type: "asg", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + "az.%": "2", + "az.12345": "uswst2", + "az.23456": "uswst3", + }, + }, + }, + "data.az.available": { + Type: "data.az", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "3579", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "3579", + "names.#": "3", + "names.0": "uswst3", + "names.1": "uswst2", + "names.3": "uswst1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "does not end with the special value") + }, + }, + { + Description: "second resource attribute ends with sentinel", + FirstResourceAddress: "asg.bar", + FirstResourceAttribute: "az.*", + SecondResourceAddress: "data.az.available", + SecondResourceAttribute: "names.*", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "asg.bar": { + Type: "asg", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + "az.%": "2", + "az.12345": "uswst2", + "az.23456": "uswst3", + }, + }, + }, + "data.az.available": { + Type: "data.az", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "3579", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "3579", + "names.#": "3", + "names.0": "uswst3", + "names.1": "uswst2", + "names.3": "uswst1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), `data.az.available: Attribute "names.*" not set`) + }, + }, + { + Description: "match zero attribute", + FirstResourceAddress: "asg.bar", + FirstResourceAttribute: "az.*", + SecondResourceAddress: "data.az.available", + SecondResourceAttribute: "names.0", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "asg.bar": { + Type: "asg", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + "az.%": "2", + "az.12345": "uswst2", + "az.23456": "uswst3", + }, + }, + }, + "data.az.available": { + Type: "data.az", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "3579", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "3579", + "names.#": "3", + "names.0": "uswst3", + "names.1": "uswst2", + "names.3": "uswst1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "match non-zero attribute", + FirstResourceAddress: "asg.bar", + FirstResourceAttribute: "az.*", + SecondResourceAddress: "data.az.available", + SecondResourceAttribute: "names.2", + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "asg.bar": { + Type: "asg", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + "az.%": "2", + "az.12345": "uswst1", + "az.23456": "uswst3", + }, + }, + }, + "data.az.available": { + Type: "data.az", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "3579", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "3579", + "names.#": "3", + "names.0": "uswst3", + "names.1": "uswst2", + "names.2": "uswst1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.Description, func(t *testing.T) { + err := TestCheckTypeSetElemAttrPair( + testCase.FirstResourceAddress, + testCase.FirstResourceAttribute, + testCase.SecondResourceAddress, + testCase.SecondResourceAttribute)(testCase.TerraformState) + + if err != nil { + if testCase.ExpectedError == nil { + t.Fatalf("expected no error, got error: %s", err) + } + + if !testCase.ExpectedError(err) { + t.Fatalf("unexpected error: %s", err) + } + + t.Logf("received expected error: %s", err) + return + } + + if err == nil && testCase.ExpectedError != nil { + t.Fatalf("expected error, got no error") + } + }) + } +} + +func TestTestCheckTypeSetElemNestedAttrs(t *testing.T) { + testCases := []struct { + Description string + ResourceAddress string + ResourceAttribute string + Values map[string]string + TerraformState *terraform.State + ExpectedError func(err error) bool + }{ + { + Description: "no resources", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{}, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{}, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "Not found: example_thing.test") + }, + }, + { + Description: "resource not found", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{}, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_other_thing.test": { + Type: "example_other_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "Not found: example_thing.test") + }, + }, + { + Description: "no primary instance", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{}, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Deposed: []*terraform.InstanceState{ + { + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + }, + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "No primary instance: example_thing.test") + }, + }, + { + Description: "value map has no non-empty values", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{"key": ""}, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "has no non-empty values") + }, + }, + { + Description: "attribute path does not end with sentinel value", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test", + Values: map[string]string{}, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "does not end with the special value") + }, + }, + { + Description: "attribute not found", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{"key": "value"}, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "1", + "id": "11111", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "\"example_thing.test\" no TypeSet element \"test.*\"") + }, + }, + { + Description: "single root TypeSet attribute single value match", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{ + "key1": "value1", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "3", + "id": "11111", + "test.%": "1", + "test.12345.key1": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "single root TypeSet attribute single value mismatch", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{ + "key1": "value2", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "3", + "id": "11111", + "test.%": "1", + "test.12345.key1": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "\"example_thing.test\" no TypeSet element \"test.*\"") + }, + }, + { + Description: "single root TypeSet attribute single nested value match", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{ + "key1.0.nested_key1": "value1", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "3", + "id": "11111", + "test.%": "1", + "test.12345.key1.0.nested_key1": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "single root TypeSet attribute single nested value mismatch", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{ + "key1.0.nested_key1": "value2", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "3", + "id": "11111", + "test.%": "1", + "test.12345.key1.0.nested_key1": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "\"example_thing.test\" no TypeSet element \"test.*\"") + }, + }, + { + Description: "single root TypeSet attribute multiple value match", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{ + "key1": "value1", + "key2": "value2", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "4", + "id": "11111", + "test.%": "1", + "test.12345.key1": "value1", + "test.12345.key2": "value2", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "single root TypeSet attribute unset/empty value match", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{ + "key1": "value1", + "key2": "", + "key3": "", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "4", + "id": "11111", + "test.%": "1", + "test.12345.key1": "value1", + "test.12345.key2": "", + // key3 is unset + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "single root TypeSet attribute multiple value mismatch", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{ + "key1": "value1", + "key2": "value3", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "4", + "id": "11111", + "test.%": "1", + "test.12345.key1": "value1", + "test.12345.key2": "value2", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "\"example_thing.test\" no TypeSet element \"test.*\"") + }, + }, + { + Description: "multiple root TypeSet attribute single value match", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{ + "key1": "value1", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "4", + "id": "11111", + "test.%": "2", + "test.12345.key1": "value2", + "test.67890.key1": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "multiple root TypeSet attribute multiple value match", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.*", + Values: map[string]string{ + "key1": "value1", + "key2": "value2", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "6", + "id": "11111", + "test.%": "2", + "test.12345.key1": "value2", + "test.12345.key2": "value3", + "test.67890.key1": "value1", + "test.67890.key2": "value2", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "single nested TypeSet attribute single value match", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.0.nested_test.*", + Values: map[string]string{ + "key1": "value1", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "4", + "id": "11111", + "test.%": "1", + "test.0.nested_test.%": "1", + "test.0.nested_test.12345.key1": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "single nested TypeSet attribute single value mismatch", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.0.nested_test.*", + Values: map[string]string{ + "key1": "value2", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "4", + "id": "11111", + "test.%": "1", + "test.0.nested_test.%": "1", + "test.0.nested_test.12345.key1": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "\"example_thing.test\" no TypeSet element \"test.0.nested_test.*\"") + }, + }, + { + Description: "single nested TypeSet attribute single nested value match", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.0.nested_test.*", + Values: map[string]string{ + "key1.0.nested_key1": "value1", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "5", + "id": "11111", + "test.%": "1", + "test.0.nested_test.%": "1", + "test.0.nested_test.12345.key1.%": "1", + "test.0.nested_test.12345.key1.0.nested_key1": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + }, + { + Description: "single nested TypeSet attribute single nested value mismatch", + ResourceAddress: "example_thing.test", + ResourceAttribute: "test.0.nested_test.*", + Values: map[string]string{ + "key1.0.nested_key1": "value2", + }, + TerraformState: &terraform.State{ + Version: 3, + Modules: []*terraform.ModuleState{ + { + Path: []string{"root"}, + Outputs: map[string]*terraform.OutputState{}, + Resources: map[string]*terraform.ResourceState{ + "example_thing.test": { + Type: "example_thing", + Provider: "example", + Primary: &terraform.InstanceState{ + ID: "11111", + Meta: map[string]interface{}{ + "schema_version": 0, + }, + Attributes: map[string]string{ + "%": "5", + "id": "11111", + "test.%": "1", + "test.0.nested_test.%": "1", + "test.0.nested_test.12345.key1.%": "1", + "test.0.nested_test.12345.key1.0.nested_key1": "value1", + }, + }, + }, + }, + Dependencies: []string{}, + }, + }, + }, + ExpectedError: func(err error) bool { + return strings.Contains(err.Error(), "\"example_thing.test\" no TypeSet element \"test.0.nested_test.*\"") + }, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.Description, func(t *testing.T) { + err := TestCheckTypeSetElemNestedAttrs(testCase.ResourceAddress, testCase.ResourceAttribute, testCase.Values)(testCase.TerraformState) + + if err != nil { + if testCase.ExpectedError == nil { + t.Fatalf("expected no error, got error: %s", err) + } + + if !testCase.ExpectedError(err) { + t.Fatalf("unexpected error: %s", err) + } + + t.Logf("received expected error: %s", err) + return + } + + if err == nil && testCase.ExpectedError != nil { + t.Fatalf("expected error, got no error") + } + }) + } +} diff --git a/aws/internal/vault/helper/pgpkeys/encrypt_decrypt.go b/aws/internal/vault/helper/pgpkeys/encrypt_decrypt.go new file mode 100644 index 00000000000..4090ed0a730 --- /dev/null +++ b/aws/internal/vault/helper/pgpkeys/encrypt_decrypt.go @@ -0,0 +1,121 @@ +package pgpkeys + +import ( + "bytes" + "encoding/base64" + "fmt" + + "github.com/keybase/go-crypto/openpgp" + "github.com/keybase/go-crypto/openpgp/packet" +) + +// EncryptShares takes an ordered set of byte slices to encrypt and the +// corresponding base64-encoded public keys to encrypt them with, encrypts each +// byte slice with the corresponding public key. +// +// Note: There is no corresponding test function; this functionality is +// thoroughly tested in the init and rekey command unit tests +func EncryptShares(input [][]byte, pgpKeys []string) ([]string, [][]byte, error) { + if len(input) != len(pgpKeys) { + return nil, nil, fmt.Errorf("mismatch between number items to encrypt and number of PGP keys") + } + encryptedShares := make([][]byte, 0, len(pgpKeys)) + entities, err := GetEntities(pgpKeys) + if err != nil { + return nil, nil, err + } + for i, entity := range entities { + ctBuf := bytes.NewBuffer(nil) + pt, err := openpgp.Encrypt(ctBuf, []*openpgp.Entity{entity}, nil, nil, nil) + if err != nil { + return nil, nil, fmt.Errorf("error setting up encryption for PGP message: %w", err) + } + _, err = pt.Write(input[i]) + if err != nil { + return nil, nil, fmt.Errorf("error encrypting PGP message: %w", err) + } + pt.Close() + encryptedShares = append(encryptedShares, ctBuf.Bytes()) + } + + fingerprints, err := GetFingerprints(nil, entities) + if err != nil { + return nil, nil, err + } + + return fingerprints, encryptedShares, nil +} + +// GetFingerprints takes in a list of openpgp Entities and returns the +// fingerprints. If entities is nil, it will instead parse both entities and +// fingerprints from the pgpKeys string slice. +func GetFingerprints(pgpKeys []string, entities []*openpgp.Entity) ([]string, error) { + if entities == nil { + var err error + entities, err = GetEntities(pgpKeys) + + if err != nil { + return nil, err + } + } + ret := make([]string, 0, len(entities)) + for _, entity := range entities { + ret = append(ret, fmt.Sprintf("%x", entity.PrimaryKey.Fingerprint)) + } + return ret, nil +} + +// GetEntities takes in a string array of base64-encoded PGP keys and returns +// the openpgp Entities +func GetEntities(pgpKeys []string) ([]*openpgp.Entity, error) { + ret := make([]*openpgp.Entity, 0, len(pgpKeys)) + for _, keystring := range pgpKeys { + data, err := base64.StdEncoding.DecodeString(keystring) + if err != nil { + return nil, fmt.Errorf("error decoding given PGP key: %w", err) + } + entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data))) + if err != nil { + return nil, fmt.Errorf("error parsing given PGP key: %w", err) + } + ret = append(ret, entity) + } + return ret, nil +} + +// DecryptBytes takes in base64-encoded encrypted bytes and the base64-encoded +// private key and decrypts it. A bytes.Buffer is returned to allow the caller +// to do useful thing with it (get it as a []byte, get it as a string, use it +// as an io.Reader, etc), and also because this function doesn't know if what +// comes out is binary data or a string, so let the caller decide. +func DecryptBytes(encodedCrypt, privKey string) (*bytes.Buffer, error) { + privKeyBytes, err := base64.StdEncoding.DecodeString(privKey) + if err != nil { + return nil, fmt.Errorf("error decoding base64 private key: %w", err) + } + + cryptBytes, err := base64.StdEncoding.DecodeString(encodedCrypt) + if err != nil { + return nil, fmt.Errorf("error decoding base64 crypted bytes: %w", err) + } + + entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(privKeyBytes))) + if err != nil { + return nil, fmt.Errorf("error parsing private key: %w", err) + } + + entityList := &openpgp.EntityList{entity} + md, err := openpgp.ReadMessage(bytes.NewBuffer(cryptBytes), entityList, nil, nil) + if err != nil { + return nil, fmt.Errorf("error decrypting the messages: %w", err) + } + + ptBuf := bytes.NewBuffer(nil) + _, err = ptBuf.ReadFrom(md.UnverifiedBody) + + if err != nil { + return nil, fmt.Errorf("error reading the messages: %w", err) + } + + return ptBuf, nil +} diff --git a/aws/internal/vault/helper/pgpkeys/keybase.go b/aws/internal/vault/helper/pgpkeys/keybase.go new file mode 100644 index 00000000000..1ad49b7af38 --- /dev/null +++ b/aws/internal/vault/helper/pgpkeys/keybase.go @@ -0,0 +1,116 @@ +package pgpkeys + +import ( + "bytes" + "encoding/base64" + "fmt" + "strings" + + cleanhttp "github.com/hashicorp/go-cleanhttp" + "github.com/keybase/go-crypto/openpgp" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/vault/sdk/helper/jsonutil" +) + +const ( + kbPrefix = "keybase:" +) + +// FetchKeybasePubkeys fetches public keys from Keybase given a set of +// usernames, which are derived from correctly formatted input entries. It +// doesn't use their client code due to both the API and the fact that it is +// considered alpha and probably best not to rely on it. The keys are returned +// as base64-encoded strings. +func FetchKeybasePubkeys(input []string) (map[string]string, error) { + client := cleanhttp.DefaultClient() + if client == nil { + return nil, fmt.Errorf("unable to create an http client") + } + + if len(input) == 0 { + return nil, nil + } + + usernames := make([]string, 0, len(input)) + for _, v := range input { + if strings.HasPrefix(v, kbPrefix) { + usernames = append(usernames, strings.TrimPrefix(v, kbPrefix)) + } + } + + if len(usernames) == 0 { + return nil, nil + } + + ret := make(map[string]string, len(usernames)) + url := fmt.Sprintf("https://keybase.io/_/api/1.0/user/lookup.json?usernames=%s&fields=public_keys", strings.Join(usernames, ",")) + resp, err := client.Get(url) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + type PublicKeys struct { + Primary struct { + Bundle string + } + } + + type LThem struct { + PublicKeys `json:"public_keys"` + } + + type KbResp struct { + Status struct { + Name string + } + Them []LThem + } + + out := &KbResp{ + Them: []LThem{}, + } + + if err := jsonutil.DecodeJSONFromReader(resp.Body, out); err != nil { + return nil, err + } + + if out.Status.Name != "OK" { + return nil, fmt.Errorf("got non-OK response: %q", out.Status.Name) + } + + missingNames := make([]string, 0, len(usernames)) + var keyReader *bytes.Reader + serializedEntity := bytes.NewBuffer(nil) + for i, themVal := range out.Them { + if themVal.Primary.Bundle == "" { + missingNames = append(missingNames, usernames[i]) + continue + } + keyReader = bytes.NewReader([]byte(themVal.Primary.Bundle)) + entityList, err := openpgp.ReadArmoredKeyRing(keyReader) + if err != nil { + return nil, err + } + if len(entityList) != 1 { + return nil, fmt.Errorf("primary key could not be parsed for user %q", usernames[i]) + } + if entityList[0] == nil { + return nil, fmt.Errorf("primary key was nil for user %q", usernames[i]) + } + + serializedEntity.Reset() + err = entityList[0].Serialize(serializedEntity) + if err != nil { + return nil, fmt.Errorf("error serializing entity for user %q: %w", usernames[i], err) + } + + // The API returns values in the same ordering requested, so this should properly match + ret[kbPrefix+usernames[i]] = base64.StdEncoding.EncodeToString(serializedEntity.Bytes()) + } + + if len(missingNames) > 0 { + return nil, fmt.Errorf("unable to fetch keys for user(s) %q from keybase", strings.Join(missingNames, ",")) + } + + return ret, nil +} diff --git a/aws/internal/vault/helper/pgpkeys/keybase_test.go b/aws/internal/vault/helper/pgpkeys/keybase_test.go new file mode 100644 index 00000000000..ded5af5d76d --- /dev/null +++ b/aws/internal/vault/helper/pgpkeys/keybase_test.go @@ -0,0 +1,42 @@ +package pgpkeys + +import ( + "bytes" + "encoding/base64" + "encoding/hex" + "reflect" + "testing" + + "github.com/keybase/go-crypto/openpgp" + "github.com/keybase/go-crypto/openpgp/packet" +) + +func TestFetchKeybasePubkeys(t *testing.T) { + testset := []string{"keybase:jefferai", "keybase:hashicorp"} + ret, err := FetchKeybasePubkeys(testset) + if err != nil { + t.Fatalf("bad: %v", err) + } + + fingerprints := []string{} + for _, user := range testset { + data, err := base64.StdEncoding.DecodeString(ret[user]) + if err != nil { + t.Fatalf("error decoding key for user %s: %v", user, err) + } + entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data))) + if err != nil { + t.Fatalf("error parsing key for user %s: %v", user, err) + } + fingerprints = append(fingerprints, hex.EncodeToString(entity.PrimaryKey.Fingerprint[:])) + } + + exp := []string{ + "0f801f518ec853daff611e836528efcac6caa3db", + "91a6e7f85d05c65630bef18951852d87348ffc4c", + } + + if !reflect.DeepEqual(fingerprints, exp) { + t.Fatalf("fingerprints do not match; expected \n%#v\ngot\n%#v\n", exp, fingerprints) + } +} diff --git a/aws/internal/vault/sdk/helper/jsonutil/json.go b/aws/internal/vault/sdk/helper/jsonutil/json.go new file mode 100644 index 00000000000..51cca5f2643 --- /dev/null +++ b/aws/internal/vault/sdk/helper/jsonutil/json.go @@ -0,0 +1,25 @@ +package jsonutil + +import ( + "encoding/json" + "fmt" + "io" +) + +// Decodes/Unmarshals the given io.Reader pointing to a JSON, into a desired object +func DecodeJSONFromReader(r io.Reader, out interface{}) error { + if r == nil { + return fmt.Errorf("'io.Reader' being decoded is nil") + } + if out == nil { + return fmt.Errorf("output parameter 'out' is nil") + } + + dec := json.NewDecoder(r) + + // While decoding JSON values, interpret the integer values as `json.Number`s instead of `float64`. + dec.UseNumber() + + // Since 'out' is an interface representing a pointer, pass it to the decoder without an '&' + return dec.Decode(out) +} diff --git a/aws/internal/vault/sdk/helper/jsonutil/json_test.go b/aws/internal/vault/sdk/helper/jsonutil/json_test.go new file mode 100644 index 00000000000..339ea852ccb --- /dev/null +++ b/aws/internal/vault/sdk/helper/jsonutil/json_test.go @@ -0,0 +1,27 @@ +package jsonutil + +import ( + "bytes" + "fmt" + "reflect" + "testing" +) + +func TestJSONUtil_DecodeJSONFromReader(t *testing.T) { + input := `{"test":"data","validation":"process"}` + + var actual map[string]interface{} + + err := DecodeJSONFromReader(bytes.NewReader([]byte(input)), &actual) + if err != nil { + fmt.Printf("decoding err: %v\n", err) + } + + expected := map[string]interface{}{ + "test": "data", + "validation": "process", + } + if !reflect.DeepEqual(actual, expected) { + t.Fatalf("bad: expected:%#v\nactual:%#v", expected, actual) + } +} diff --git a/aws/network_acl_entry.go b/aws/network_acl_entry.go index c08b68e78b8..6b06967fde5 100644 --- a/aws/network_acl_entry.go +++ b/aws/network_acl_entry.go @@ -2,7 +2,6 @@ package aws import ( "fmt" - "net" "strconv" "github.com/aws/aws-sdk-go/aws" @@ -233,17 +232,3 @@ func validatePorts(to int64, from int64, expected expectedPortPair) bool { return true } - -// validateCIDRBlock ensures the passed CIDR block represents an implied -// network, and not an overly-specified IP address. -func validateCIDRBlock(cidr string) error { - _, ipnet, err := net.ParseCIDR(cidr) - if err != nil { - return err - } - if ipnet.String() != cidr { - return fmt.Errorf("%s is not a valid mask; did you mean %s?", cidr, ipnet) - } - - return nil -} diff --git a/aws/network_acl_entry_test.go b/aws/network_acl_entry_test.go index 55a7074a7bf..0f0f72e664c 100644 --- a/aws/network_acl_entry_test.go +++ b/aws/network_acl_entry_test.go @@ -98,23 +98,3 @@ func Test_validatePorts(t *testing.T) { } } } - -func Test_validateCIDRBlock(t *testing.T) { - for _, ts := range []struct { - cidr string - shouldErr bool - }{ - {"10.2.2.0/24", false}, - {"10.2.2.0/1234", true}, - {"10/24", true}, - {"10.2.2.2/24", true}, - } { - err := validateCIDRBlock(ts.cidr) - if ts.shouldErr && err == nil { - t.Fatalf("Input '%s' should error but didn't!", ts.cidr) - } - if !ts.shouldErr && err != nil { - t.Fatalf("Got unexpected error for '%s' input: %s", ts.cidr, err) - } - } -} diff --git a/aws/opsworks_layers.go b/aws/opsworks_layers.go index 53df0fb3559..b41ef254ce0 100644 --- a/aws/opsworks_layers.go +++ b/aws/opsworks_layers.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/provider.go b/aws/provider.go index 0ca59302ae3..34e5c292584 100644 --- a/aws/provider.go +++ b/aws/provider.go @@ -3,15 +3,14 @@ package aws import ( "log" - "github.com/hashicorp/terraform-plugin-sdk/helper/mutexkv" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - homedir "github.com/mitchellh/go-homedir" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/mutexkv" ) -// Provider returns a terraform.ResourceProvider. -func Provider() terraform.ResourceProvider { +// Provider returns a *schema.Provider. +func Provider() *schema.Provider { // TODO: Move the validation to this, requires conditional schemas // TODO: Move the configuration to this, requires validation @@ -167,173 +166,193 @@ func Provider() terraform.ResourceProvider { }, DataSourcesMap: map[string]*schema.Resource{ - "aws_acm_certificate": dataSourceAwsAcmCertificate(), - "aws_acmpca_certificate_authority": dataSourceAwsAcmpcaCertificateAuthority(), - "aws_ami": dataSourceAwsAmi(), - "aws_ami_ids": dataSourceAwsAmiIds(), - "aws_api_gateway_api_key": dataSourceAwsApiGatewayApiKey(), - "aws_api_gateway_resource": dataSourceAwsApiGatewayResource(), - "aws_api_gateway_rest_api": dataSourceAwsApiGatewayRestApi(), - "aws_api_gateway_vpc_link": dataSourceAwsApiGatewayVpcLink(), - "aws_arn": dataSourceAwsArn(), - "aws_autoscaling_group": dataSourceAwsAutoscalingGroup(), - "aws_autoscaling_groups": dataSourceAwsAutoscalingGroups(), - "aws_availability_zone": dataSourceAwsAvailabilityZone(), - "aws_availability_zones": dataSourceAwsAvailabilityZones(), - "aws_backup_plan": dataSourceAwsBackupPlan(), - "aws_backup_selection": dataSourceAwsBackupSelection(), - "aws_backup_vault": dataSourceAwsBackupVault(), - "aws_batch_compute_environment": dataSourceAwsBatchComputeEnvironment(), - "aws_batch_job_queue": dataSourceAwsBatchJobQueue(), - "aws_billing_service_account": dataSourceAwsBillingServiceAccount(), - "aws_caller_identity": dataSourceAwsCallerIdentity(), - "aws_canonical_user_id": dataSourceAwsCanonicalUserId(), - "aws_cloudformation_export": dataSourceAwsCloudFormationExport(), - "aws_cloudformation_stack": dataSourceAwsCloudFormationStack(), - "aws_cloudfront_distribution": dataSourceAwsCloudFrontDistribution(), - "aws_cloudhsm_v2_cluster": dataSourceCloudHsmV2Cluster(), - "aws_cloudtrail_service_account": dataSourceAwsCloudTrailServiceAccount(), - "aws_cloudwatch_log_group": dataSourceAwsCloudwatchLogGroup(), - "aws_cognito_user_pools": dataSourceAwsCognitoUserPools(), - "aws_codecommit_repository": dataSourceAwsCodeCommitRepository(), - "aws_cur_report_definition": dataSourceAwsCurReportDefinition(), - "aws_db_cluster_snapshot": dataSourceAwsDbClusterSnapshot(), - "aws_db_event_categories": dataSourceAwsDbEventCategories(), - "aws_db_instance": dataSourceAwsDbInstance(), - "aws_db_snapshot": dataSourceAwsDbSnapshot(), - "aws_directory_service_directory": dataSourceAwsDirectoryServiceDirectory(), - "aws_dx_gateway": dataSourceAwsDxGateway(), - "aws_dynamodb_table": dataSourceAwsDynamoDbTable(), - "aws_ebs_default_kms_key": dataSourceAwsEbsDefaultKmsKey(), - "aws_ebs_encryption_by_default": dataSourceAwsEbsEncryptionByDefault(), - "aws_ebs_snapshot": dataSourceAwsEbsSnapshot(), - "aws_ebs_snapshot_ids": dataSourceAwsEbsSnapshotIds(), - "aws_ebs_volume": dataSourceAwsEbsVolume(), - "aws_ec2_coip_pool": dataSourceAwsEc2CoipPool(), - "aws_ec2_coip_pools": dataSourceAwsEc2CoipPools(), - "aws_ec2_instance_type_offering": dataSourceAwsEc2InstanceTypeOffering(), - "aws_ec2_instance_type_offerings": dataSourceAwsEc2InstanceTypeOfferings(), - "aws_ec2_local_gateway": dataSourceAwsEc2LocalGateway(), - "aws_ec2_local_gateways": dataSourceAwsEc2LocalGateways(), - "aws_ec2_local_gateway_route_table": dataSourceAwsEc2LocalGatewayRouteTable(), - "aws_ec2_local_gateway_route_tables": dataSourceAwsEc2LocalGatewayRouteTables(), - "aws_ec2_transit_gateway": dataSourceAwsEc2TransitGateway(), - "aws_ec2_transit_gateway_dx_gateway_attachment": dataSourceAwsEc2TransitGatewayDxGatewayAttachment(), - "aws_ec2_transit_gateway_peering_attachment": dataSourceAwsEc2TransitGatewayPeeringAttachment(), - "aws_ec2_transit_gateway_route_table": dataSourceAwsEc2TransitGatewayRouteTable(), - "aws_ec2_transit_gateway_vpc_attachment": dataSourceAwsEc2TransitGatewayVpcAttachment(), - "aws_ec2_transit_gateway_vpn_attachment": dataSourceAwsEc2TransitGatewayVpnAttachment(), - "aws_ecr_image": dataSourceAwsEcrImage(), - "aws_ecr_repository": dataSourceAwsEcrRepository(), - "aws_ecs_cluster": dataSourceAwsEcsCluster(), - "aws_ecs_container_definition": dataSourceAwsEcsContainerDefinition(), - "aws_ecs_service": dataSourceAwsEcsService(), - "aws_ecs_task_definition": dataSourceAwsEcsTaskDefinition(), - "aws_customer_gateway": dataSourceAwsCustomerGateway(), - "aws_efs_file_system": dataSourceAwsEfsFileSystem(), - "aws_efs_mount_target": dataSourceAwsEfsMountTarget(), - "aws_eip": dataSourceAwsEip(), - "aws_eks_cluster": dataSourceAwsEksCluster(), - "aws_eks_cluster_auth": dataSourceAwsEksClusterAuth(), - "aws_elastic_beanstalk_application": dataSourceAwsElasticBeanstalkApplication(), - "aws_elastic_beanstalk_hosted_zone": dataSourceAwsElasticBeanstalkHostedZone(), - "aws_elastic_beanstalk_solution_stack": dataSourceAwsElasticBeanstalkSolutionStack(), - "aws_elasticache_cluster": dataSourceAwsElastiCacheCluster(), - "aws_elasticsearch_domain": dataSourceAwsElasticSearchDomain(), - "aws_elb": dataSourceAwsElb(), - "aws_elasticache_replication_group": dataSourceAwsElasticacheReplicationGroup(), - "aws_elb_hosted_zone_id": dataSourceAwsElbHostedZoneId(), - "aws_elb_service_account": dataSourceAwsElbServiceAccount(), - "aws_glue_script": dataSourceAwsGlueScript(), - "aws_guardduty_detector": dataSourceAwsGuarddutyDetector(), - "aws_iam_account_alias": dataSourceAwsIamAccountAlias(), - "aws_iam_group": dataSourceAwsIAMGroup(), - "aws_iam_instance_profile": dataSourceAwsIAMInstanceProfile(), - "aws_iam_policy": dataSourceAwsIAMPolicy(), - "aws_iam_policy_document": dataSourceAwsIamPolicyDocument(), - "aws_iam_role": dataSourceAwsIAMRole(), - "aws_iam_server_certificate": dataSourceAwsIAMServerCertificate(), - "aws_iam_user": dataSourceAwsIAMUser(), - "aws_internet_gateway": dataSourceAwsInternetGateway(), - "aws_iot_endpoint": dataSourceAwsIotEndpoint(), - "aws_inspector_rules_packages": dataSourceAwsInspectorRulesPackages(), - "aws_instance": dataSourceAwsInstance(), - "aws_instances": dataSourceAwsInstances(), - "aws_ip_ranges": dataSourceAwsIPRanges(), - "aws_kinesis_stream": dataSourceAwsKinesisStream(), - "aws_kms_alias": dataSourceAwsKmsAlias(), - "aws_kms_ciphertext": dataSourceAwsKmsCiphertext(), - "aws_kms_key": dataSourceAwsKmsKey(), - "aws_kms_secret": dataSourceAwsKmsSecret(), - "aws_kms_secrets": dataSourceAwsKmsSecrets(), - "aws_lambda_alias": dataSourceAwsLambdaAlias(), - "aws_lambda_function": dataSourceAwsLambdaFunction(), - "aws_lambda_invocation": dataSourceAwsLambdaInvocation(), - "aws_lambda_layer_version": dataSourceAwsLambdaLayerVersion(), - "aws_launch_configuration": dataSourceAwsLaunchConfiguration(), - "aws_launch_template": dataSourceAwsLaunchTemplate(), - "aws_mq_broker": dataSourceAwsMqBroker(), - "aws_msk_cluster": dataSourceAwsMskCluster(), - "aws_msk_configuration": dataSourceAwsMskConfiguration(), - "aws_nat_gateway": dataSourceAwsNatGateway(), - "aws_network_acls": dataSourceAwsNetworkAcls(), - "aws_network_interface": dataSourceAwsNetworkInterface(), - "aws_network_interfaces": dataSourceAwsNetworkInterfaces(), - "aws_organizations_organization": dataSourceAwsOrganizationsOrganization(), - "aws_organizations_organizational_units": dataSourceAwsOrganizationsOrganizationalUnits(), - "aws_partition": dataSourceAwsPartition(), - "aws_prefix_list": dataSourceAwsPrefixList(), - "aws_pricing_product": dataSourceAwsPricingProduct(), - "aws_qldb_ledger": dataSourceAwsQLDBLedger(), - "aws_ram_resource_share": dataSourceAwsRamResourceShare(), - "aws_rds_cluster": dataSourceAwsRdsCluster(), - "aws_redshift_cluster": dataSourceAwsRedshiftCluster(), - "aws_redshift_service_account": dataSourceAwsRedshiftServiceAccount(), - "aws_region": dataSourceAwsRegion(), - "aws_regions": dataSourceAwsRegions(), - "aws_route": dataSourceAwsRoute(), - "aws_route_table": dataSourceAwsRouteTable(), - "aws_route_tables": dataSourceAwsRouteTables(), - "aws_route53_delegation_set": dataSourceAwsDelegationSet(), - "aws_route53_resolver_rule": dataSourceAwsRoute53ResolverRule(), - "aws_route53_resolver_rules": dataSourceAwsRoute53ResolverRules(), - "aws_route53_zone": dataSourceAwsRoute53Zone(), - "aws_s3_bucket": dataSourceAwsS3Bucket(), - "aws_s3_bucket_object": dataSourceAwsS3BucketObject(), - "aws_s3_bucket_objects": dataSourceAwsS3BucketObjects(), - "aws_secretsmanager_secret": dataSourceAwsSecretsManagerSecret(), - "aws_secretsmanager_secret_version": dataSourceAwsSecretsManagerSecretVersion(), - "aws_servicequotas_service": dataSourceAwsServiceQuotasService(), - "aws_servicequotas_service_quota": dataSourceAwsServiceQuotasServiceQuota(), - "aws_sfn_activity": dataSourceAwsSfnActivity(), - "aws_sfn_state_machine": dataSourceAwsSfnStateMachine(), - "aws_sns_topic": dataSourceAwsSnsTopic(), - "aws_sqs_queue": dataSourceAwsSqsQueue(), - "aws_ssm_document": dataSourceAwsSsmDocument(), - "aws_ssm_parameter": dataSourceAwsSsmParameter(), - "aws_ssm_patch_baseline": dataSourceAwsSsmPatchBaseline(), - "aws_storagegateway_local_disk": dataSourceAwsStorageGatewayLocalDisk(), - "aws_subnet": dataSourceAwsSubnet(), - "aws_subnet_ids": dataSourceAwsSubnetIDs(), - "aws_transfer_server": dataSourceAwsTransferServer(), - "aws_vpcs": dataSourceAwsVpcs(), - "aws_security_group": dataSourceAwsSecurityGroup(), - "aws_security_groups": dataSourceAwsSecurityGroups(), - "aws_vpc": dataSourceAwsVpc(), - "aws_vpc_dhcp_options": dataSourceAwsVpcDhcpOptions(), - "aws_vpc_endpoint": dataSourceAwsVpcEndpoint(), - "aws_vpc_endpoint_service": dataSourceAwsVpcEndpointService(), - "aws_vpc_peering_connection": dataSourceAwsVpcPeeringConnection(), - "aws_vpn_gateway": dataSourceAwsVpnGateway(), - "aws_waf_ipset": dataSourceAwsWafIpSet(), - "aws_waf_rule": dataSourceAwsWafRule(), - "aws_waf_rate_based_rule": dataSourceAwsWafRateBasedRule(), - "aws_waf_web_acl": dataSourceAwsWafWebAcl(), - "aws_wafregional_ipset": dataSourceAwsWafRegionalIpSet(), - "aws_wafregional_rule": dataSourceAwsWafRegionalRule(), - "aws_wafregional_rate_based_rule": dataSourceAwsWafRegionalRateBasedRule(), - "aws_wafregional_web_acl": dataSourceAwsWafRegionalWebAcl(), - "aws_workspaces_bundle": dataSourceAwsWorkspaceBundle(), + "aws_acm_certificate": dataSourceAwsAcmCertificate(), + "aws_acmpca_certificate_authority": dataSourceAwsAcmpcaCertificateAuthority(), + "aws_ami": dataSourceAwsAmi(), + "aws_ami_ids": dataSourceAwsAmiIds(), + "aws_api_gateway_api_key": dataSourceAwsApiGatewayApiKey(), + "aws_api_gateway_resource": dataSourceAwsApiGatewayResource(), + "aws_api_gateway_rest_api": dataSourceAwsApiGatewayRestApi(), + "aws_api_gateway_vpc_link": dataSourceAwsApiGatewayVpcLink(), + "aws_arn": dataSourceAwsArn(), + "aws_autoscaling_group": dataSourceAwsAutoscalingGroup(), + "aws_autoscaling_groups": dataSourceAwsAutoscalingGroups(), + "aws_availability_zone": dataSourceAwsAvailabilityZone(), + "aws_availability_zones": dataSourceAwsAvailabilityZones(), + "aws_backup_plan": dataSourceAwsBackupPlan(), + "aws_backup_selection": dataSourceAwsBackupSelection(), + "aws_backup_vault": dataSourceAwsBackupVault(), + "aws_batch_compute_environment": dataSourceAwsBatchComputeEnvironment(), + "aws_batch_job_queue": dataSourceAwsBatchJobQueue(), + "aws_billing_service_account": dataSourceAwsBillingServiceAccount(), + "aws_caller_identity": dataSourceAwsCallerIdentity(), + "aws_canonical_user_id": dataSourceAwsCanonicalUserId(), + "aws_cloudformation_export": dataSourceAwsCloudFormationExport(), + "aws_cloudformation_stack": dataSourceAwsCloudFormationStack(), + "aws_cloudfront_distribution": dataSourceAwsCloudFrontDistribution(), + "aws_cloudhsm_v2_cluster": dataSourceCloudHsmV2Cluster(), + "aws_cloudtrail_service_account": dataSourceAwsCloudTrailServiceAccount(), + "aws_cloudwatch_log_group": dataSourceAwsCloudwatchLogGroup(), + "aws_cognito_user_pools": dataSourceAwsCognitoUserPools(), + "aws_codecommit_repository": dataSourceAwsCodeCommitRepository(), + "aws_cur_report_definition": dataSourceAwsCurReportDefinition(), + "aws_db_cluster_snapshot": dataSourceAwsDbClusterSnapshot(), + "aws_db_event_categories": dataSourceAwsDbEventCategories(), + "aws_db_instance": dataSourceAwsDbInstance(), + "aws_db_snapshot": dataSourceAwsDbSnapshot(), + "aws_directory_service_directory": dataSourceAwsDirectoryServiceDirectory(), + "aws_dx_gateway": dataSourceAwsDxGateway(), + "aws_dynamodb_table": dataSourceAwsDynamoDbTable(), + "aws_ebs_default_kms_key": dataSourceAwsEbsDefaultKmsKey(), + "aws_ebs_encryption_by_default": dataSourceAwsEbsEncryptionByDefault(), + "aws_ebs_snapshot": dataSourceAwsEbsSnapshot(), + "aws_ebs_snapshot_ids": dataSourceAwsEbsSnapshotIds(), + "aws_ebs_volume": dataSourceAwsEbsVolume(), + "aws_ebs_volumes": dataSourceAwsEbsVolumes(), + "aws_ec2_coip_pool": dataSourceAwsEc2CoipPool(), + "aws_ec2_coip_pools": dataSourceAwsEc2CoipPools(), + "aws_ec2_instance_type_offering": dataSourceAwsEc2InstanceTypeOffering(), + "aws_ec2_instance_type_offerings": dataSourceAwsEc2InstanceTypeOfferings(), + "aws_ec2_local_gateway": dataSourceAwsEc2LocalGateway(), + "aws_ec2_local_gateways": dataSourceAwsEc2LocalGateways(), + "aws_ec2_local_gateway_route_table": dataSourceAwsEc2LocalGatewayRouteTable(), + "aws_ec2_local_gateway_route_tables": dataSourceAwsEc2LocalGatewayRouteTables(), + "aws_ec2_local_gateway_virtual_interface": dataSourceAwsEc2LocalGatewayVirtualInterface(), + "aws_ec2_local_gateway_virtual_interface_group": dataSourceAwsEc2LocalGatewayVirtualInterfaceGroup(), + "aws_ec2_local_gateway_virtual_interface_groups": dataSourceAwsEc2LocalGatewayVirtualInterfaceGroups(), + "aws_ec2_spot_price": dataSourceAwsEc2SpotPrice(), + "aws_ec2_transit_gateway": dataSourceAwsEc2TransitGateway(), + "aws_ec2_transit_gateway_dx_gateway_attachment": dataSourceAwsEc2TransitGatewayDxGatewayAttachment(), + "aws_ec2_transit_gateway_peering_attachment": dataSourceAwsEc2TransitGatewayPeeringAttachment(), + "aws_ec2_transit_gateway_route_table": dataSourceAwsEc2TransitGatewayRouteTable(), + "aws_ec2_transit_gateway_vpc_attachment": dataSourceAwsEc2TransitGatewayVpcAttachment(), + "aws_ec2_transit_gateway_vpn_attachment": dataSourceAwsEc2TransitGatewayVpnAttachment(), + "aws_ecr_authorization_token": dataSourceAwsEcrAuthorizationToken(), + "aws_ecr_image": dataSourceAwsEcrImage(), + "aws_ecr_repository": dataSourceAwsEcrRepository(), + "aws_ecs_cluster": dataSourceAwsEcsCluster(), + "aws_ecs_container_definition": dataSourceAwsEcsContainerDefinition(), + "aws_ecs_service": dataSourceAwsEcsService(), + "aws_ecs_task_definition": dataSourceAwsEcsTaskDefinition(), + "aws_customer_gateway": dataSourceAwsCustomerGateway(), + "aws_efs_access_point": dataSourceAwsEfsAccessPoint(), + "aws_efs_access_points": dataSourceAwsEfsAccessPoints(), + "aws_efs_file_system": dataSourceAwsEfsFileSystem(), + "aws_efs_mount_target": dataSourceAwsEfsMountTarget(), + "aws_eip": dataSourceAwsEip(), + "aws_eks_cluster": dataSourceAwsEksCluster(), + "aws_eks_cluster_auth": dataSourceAwsEksClusterAuth(), + "aws_elastic_beanstalk_application": dataSourceAwsElasticBeanstalkApplication(), + "aws_elastic_beanstalk_hosted_zone": dataSourceAwsElasticBeanstalkHostedZone(), + "aws_elastic_beanstalk_solution_stack": dataSourceAwsElasticBeanstalkSolutionStack(), + "aws_elasticache_cluster": dataSourceAwsElastiCacheCluster(), + "aws_elasticsearch_domain": dataSourceAwsElasticSearchDomain(), + "aws_elb": dataSourceAwsElb(), + "aws_elasticache_replication_group": dataSourceAwsElasticacheReplicationGroup(), + "aws_elb_hosted_zone_id": dataSourceAwsElbHostedZoneId(), + "aws_elb_service_account": dataSourceAwsElbServiceAccount(), + "aws_glue_script": dataSourceAwsGlueScript(), + "aws_guardduty_detector": dataSourceAwsGuarddutyDetector(), + "aws_iam_account_alias": dataSourceAwsIamAccountAlias(), + "aws_iam_group": dataSourceAwsIAMGroup(), + "aws_iam_instance_profile": dataSourceAwsIAMInstanceProfile(), + "aws_iam_policy": dataSourceAwsIAMPolicy(), + "aws_iam_policy_document": dataSourceAwsIamPolicyDocument(), + "aws_iam_role": dataSourceAwsIAMRole(), + "aws_iam_server_certificate": dataSourceAwsIAMServerCertificate(), + "aws_iam_user": dataSourceAwsIAMUser(), + "aws_internet_gateway": dataSourceAwsInternetGateway(), + "aws_iot_endpoint": dataSourceAwsIotEndpoint(), + "aws_inspector_rules_packages": dataSourceAwsInspectorRulesPackages(), + "aws_instance": dataSourceAwsInstance(), + "aws_instances": dataSourceAwsInstances(), + "aws_ip_ranges": dataSourceAwsIPRanges(), + "aws_kinesis_stream": dataSourceAwsKinesisStream(), + "aws_kms_alias": dataSourceAwsKmsAlias(), + "aws_kms_ciphertext": dataSourceAwsKmsCiphertext(), + "aws_kms_key": dataSourceAwsKmsKey(), + "aws_kms_secret": dataSourceAwsKmsSecret(), + "aws_kms_secrets": dataSourceAwsKmsSecrets(), + "aws_lambda_alias": dataSourceAwsLambdaAlias(), + "aws_lambda_function": dataSourceAwsLambdaFunction(), + "aws_lambda_invocation": dataSourceAwsLambdaInvocation(), + "aws_lambda_layer_version": dataSourceAwsLambdaLayerVersion(), + "aws_launch_configuration": dataSourceAwsLaunchConfiguration(), + "aws_launch_template": dataSourceAwsLaunchTemplate(), + "aws_mq_broker": dataSourceAwsMqBroker(), + "aws_msk_cluster": dataSourceAwsMskCluster(), + "aws_msk_configuration": dataSourceAwsMskConfiguration(), + "aws_nat_gateway": dataSourceAwsNatGateway(), + "aws_network_acls": dataSourceAwsNetworkAcls(), + "aws_network_interface": dataSourceAwsNetworkInterface(), + "aws_network_interfaces": dataSourceAwsNetworkInterfaces(), + "aws_organizations_organization": dataSourceAwsOrganizationsOrganization(), + "aws_organizations_organizational_units": dataSourceAwsOrganizationsOrganizationalUnits(), + "aws_outposts_outpost": dataSourceAwsOutpostsOutpost(), + "aws_outposts_outpost_instance_type": dataSourceAwsOutpostsOutpostInstanceType(), + "aws_outposts_outpost_instance_types": dataSourceAwsOutpostsOutpostInstanceTypes(), + "aws_outposts_outposts": dataSourceAwsOutpostsOutposts(), + "aws_outposts_site": dataSourceAwsOutpostsSite(), + "aws_outposts_sites": dataSourceAwsOutpostsSites(), + "aws_partition": dataSourceAwsPartition(), + "aws_prefix_list": dataSourceAwsPrefixList(), + "aws_pricing_product": dataSourceAwsPricingProduct(), + "aws_qldb_ledger": dataSourceAwsQLDBLedger(), + "aws_ram_resource_share": dataSourceAwsRamResourceShare(), + "aws_rds_cluster": dataSourceAwsRdsCluster(), + "aws_redshift_cluster": dataSourceAwsRedshiftCluster(), + "aws_redshift_service_account": dataSourceAwsRedshiftServiceAccount(), + "aws_region": dataSourceAwsRegion(), + "aws_regions": dataSourceAwsRegions(), + "aws_route": dataSourceAwsRoute(), + "aws_route_table": dataSourceAwsRouteTable(), + "aws_route_tables": dataSourceAwsRouteTables(), + "aws_route53_delegation_set": dataSourceAwsDelegationSet(), + "aws_route53_resolver_rule": dataSourceAwsRoute53ResolverRule(), + "aws_route53_resolver_rules": dataSourceAwsRoute53ResolverRules(), + "aws_route53_zone": dataSourceAwsRoute53Zone(), + "aws_s3_bucket": dataSourceAwsS3Bucket(), + "aws_s3_bucket_object": dataSourceAwsS3BucketObject(), + "aws_s3_bucket_objects": dataSourceAwsS3BucketObjects(), + "aws_secretsmanager_secret": dataSourceAwsSecretsManagerSecret(), + "aws_secretsmanager_secret_rotation": dataSourceAwsSecretsManagerSecretRotation(), + "aws_secretsmanager_secret_version": dataSourceAwsSecretsManagerSecretVersion(), + "aws_servicequotas_service": dataSourceAwsServiceQuotasService(), + "aws_servicequotas_service_quota": dataSourceAwsServiceQuotasServiceQuota(), + "aws_sfn_activity": dataSourceAwsSfnActivity(), + "aws_sfn_state_machine": dataSourceAwsSfnStateMachine(), + "aws_sns_topic": dataSourceAwsSnsTopic(), + "aws_sqs_queue": dataSourceAwsSqsQueue(), + "aws_ssm_document": dataSourceAwsSsmDocument(), + "aws_ssm_parameter": dataSourceAwsSsmParameter(), + "aws_ssm_patch_baseline": dataSourceAwsSsmPatchBaseline(), + "aws_storagegateway_local_disk": dataSourceAwsStorageGatewayLocalDisk(), + "aws_subnet": dataSourceAwsSubnet(), + "aws_subnet_ids": dataSourceAwsSubnetIDs(), + "aws_transfer_server": dataSourceAwsTransferServer(), + "aws_vpcs": dataSourceAwsVpcs(), + "aws_security_group": dataSourceAwsSecurityGroup(), + "aws_security_groups": dataSourceAwsSecurityGroups(), + "aws_vpc": dataSourceAwsVpc(), + "aws_vpc_dhcp_options": dataSourceAwsVpcDhcpOptions(), + "aws_vpc_endpoint": dataSourceAwsVpcEndpoint(), + "aws_vpc_endpoint_service": dataSourceAwsVpcEndpointService(), + "aws_vpc_peering_connection": dataSourceAwsVpcPeeringConnection(), + "aws_vpn_gateway": dataSourceAwsVpnGateway(), + "aws_waf_ipset": dataSourceAwsWafIpSet(), + "aws_waf_rule": dataSourceAwsWafRule(), + "aws_waf_rate_based_rule": dataSourceAwsWafRateBasedRule(), + "aws_waf_web_acl": dataSourceAwsWafWebAcl(), + "aws_wafregional_ipset": dataSourceAwsWafRegionalIpSet(), + "aws_wafregional_rule": dataSourceAwsWafRegionalRule(), + "aws_wafregional_rate_based_rule": dataSourceAwsWafRegionalRateBasedRule(), + "aws_wafregional_web_acl": dataSourceAwsWafRegionalWebAcl(), + "aws_wafv2_ip_set": dataSourceAwsWafv2IPSet(), + "aws_wafv2_regex_pattern_set": dataSourceAwsWafv2RegexPatternSet(), + "aws_wafv2_rule_group": dataSourceAwsWafv2RuleGroup(), + "aws_wafv2_web_acl": dataSourceAwsWafv2WebACL(), + "aws_workspaces_bundle": dataSourceAwsWorkspacesBundle(), + "aws_workspaces_directory": dataSourceAwsWorkspacesDirectory(), // Adding the Aliases for the ALB -> LB Rename "aws_lb": dataSourceAwsLb(), @@ -527,9 +546,14 @@ func Provider() terraform.ResourceProvider { "aws_ebs_volume": resourceAwsEbsVolume(), "aws_ec2_availability_zone_group": resourceAwsEc2AvailabilityZoneGroup(), "aws_ec2_capacity_reservation": resourceAwsEc2CapacityReservation(), + "aws_ec2_client_vpn_authorization_rule": resourceAwsEc2ClientVpnAuthorizationRule(), "aws_ec2_client_vpn_endpoint": resourceAwsEc2ClientVpnEndpoint(), "aws_ec2_client_vpn_network_association": resourceAwsEc2ClientVpnNetworkAssociation(), + "aws_ec2_client_vpn_route": resourceAwsEc2ClientVpnRoute(), "aws_ec2_fleet": resourceAwsEc2Fleet(), + "aws_ec2_local_gateway_route": resourceAwsEc2LocalGatewayRoute(), + "aws_ec2_local_gateway_route_table_vpc_association": resourceAwsEc2LocalGatewayRouteTableVpcAssociation(), + "aws_ec2_tag": resourceAwsEc2Tag(), "aws_ec2_traffic_mirror_filter": resourceAwsEc2TrafficMirrorFilter(), "aws_ec2_traffic_mirror_filter_rule": resourceAwsEc2TrafficMirrorFilterRule(), "aws_ec2_traffic_mirror_target": resourceAwsEc2TrafficMirrorTarget(), @@ -550,7 +574,9 @@ func Provider() terraform.ResourceProvider { "aws_ecs_cluster": resourceAwsEcsCluster(), "aws_ecs_service": resourceAwsEcsService(), "aws_ecs_task_definition": resourceAwsEcsTaskDefinition(), + "aws_efs_access_point": resourceAwsEfsAccessPoint(), "aws_efs_file_system": resourceAwsEfsFileSystem(), + "aws_efs_file_system_policy": resourceAwsEfsFileSystemPolicy(), "aws_efs_mount_target": resourceAwsEfsMountTarget(), "aws_egress_only_internet_gateway": resourceAwsEgressOnlyInternetGateway(), "aws_eip": resourceAwsEip(), @@ -744,6 +770,7 @@ func Provider() terraform.ResourceProvider { "aws_route53_query_log": resourceAwsRoute53QueryLog(), "aws_route53_record": resourceAwsRoute53Record(), "aws_route53_zone_association": resourceAwsRoute53ZoneAssociation(), + "aws_route53_vpc_association_authorization": resourceAwsRoute53VPCAssociationAuthorization(), "aws_route53_zone": resourceAwsRoute53Zone(), "aws_route53_health_check": resourceAwsRoute53HealthCheck(), "aws_route53_resolver_endpoint": resourceAwsRoute53ResolverEndpoint(), @@ -760,6 +787,7 @@ func Provider() terraform.ResourceProvider { "aws_sagemaker_notebook_instance": resourceAwsSagemakerNotebookInstance(), "aws_secretsmanager_secret": resourceAwsSecretsManagerSecret(), "aws_secretsmanager_secret_version": resourceAwsSecretsManagerSecretVersion(), + "aws_secretsmanager_secret_rotation": resourceAwsSecretsManagerSecretRotation(), "aws_ses_active_receipt_rule_set": resourceAwsSesActiveReceiptRuleSet(), "aws_ses_domain_identity": resourceAwsSesDomainIdentity(), "aws_ses_domain_identity_verification": resourceAwsSesDomainIdentityVerification(), @@ -882,9 +910,16 @@ func Provider() terraform.ResourceProvider { "aws_wafregional_xss_match_set": resourceAwsWafRegionalXssMatchSet(), "aws_wafregional_web_acl": resourceAwsWafRegionalWebAcl(), "aws_wafregional_web_acl_association": resourceAwsWafRegionalWebAclAssociation(), + "aws_wafv2_ip_set": resourceAwsWafv2IPSet(), + "aws_wafv2_regex_pattern_set": resourceAwsWafv2RegexPatternSet(), + "aws_wafv2_rule_group": resourceAwsWafv2RuleGroup(), + "aws_wafv2_web_acl": resourceAwsWafv2WebACL(), + "aws_wafv2_web_acl_association": resourceAwsWafv2WebACLAssociation(), + "aws_wafv2_web_acl_logging_configuration": resourceAwsWafv2WebACLLoggingConfiguration(), "aws_worklink_fleet": resourceAwsWorkLinkFleet(), "aws_worklink_website_certificate_authority_association": resourceAwsWorkLinkWebsiteCertificateAuthorityAssociation(), "aws_workspaces_directory": resourceAwsWorkspacesDirectory(), + "aws_workspaces_workspace": resourceAwsWorkspacesWorkspace(), "aws_batch_compute_environment": resourceAwsBatchComputeEnvironment(), "aws_batch_job_definition": resourceAwsBatchJobDefinition(), "aws_batch_job_queue": resourceAwsBatchJobQueue(), @@ -985,18 +1020,6 @@ func init() { "i.e., http://s3.amazonaws.com/BUCKET/KEY. By default, the S3 client will\n" + "use virtual hosted bucket addressing when possible\n" + "(http://BUCKET.s3.amazonaws.com/KEY). Specific to the Amazon S3 service.", - - "assume_role_role_arn": "The ARN of an IAM role to assume prior to making API calls.", - - "assume_role_session_name": "The session name to use when assuming the role. If omitted," + - " no session name is passed to the AssumeRole call.", - - "assume_role_external_id": "The external ID to use when assuming the role. If omitted," + - " no external ID is passed to the AssumeRole call.", - - "assume_role_policy": "The permissions applied when assuming a role. You cannot use," + - " this policy to grant further permissions that are in excess to those of the, " + - " role that is being assumed.", } endpointServiceNames = []string{ @@ -1025,6 +1048,7 @@ func init() { "cloudwatch", "cloudwatchevents", "cloudwatchlogs", + "codeartifact", "codebuild", "codecommit", "codedeploy", @@ -1072,7 +1096,6 @@ func init() { "iotanalytics", "iotevents", "kafka", - "kinesis_analytics", "kinesis", "kinesisanalytics", "kinesisanalyticsv2", @@ -1094,18 +1117,20 @@ func init() { "mediastoredata", "mq", "neptune", + "networkmanager", "opsworks", "organizations", + "outposts", "personalize", "pinpoint", "pricing", "qldb", "quicksight", - "r53", "ram", "rds", "redshift", "resourcegroups", + "resourcegroupstaggingapi", "route53", "route53domains", "route53resolver", @@ -1128,6 +1153,7 @@ func init() { "storagegateway", "sts", "swf", + "synthetics", "transfer", "waf", "wafregional", @@ -1146,6 +1172,7 @@ func providerConfigure(d *schema.ResourceData, terraformVersion string) (interfa Profile: d.Get("profile").(string), Token: d.Get("token").(string), Region: d.Get("region").(string), + CredsFilename: d.Get("shared_credentials_file").(string), Endpoints: make(map[string]string), MaxRetries: d.Get("max_retries").(int), IgnoreTagsConfig: expandProviderIgnoreTags(d.Get("ignore_tags").([]interface{})), @@ -1159,28 +1186,68 @@ func providerConfigure(d *schema.ResourceData, terraformVersion string) (interfa terraformVersion: terraformVersion, } - // Set CredsFilename, expanding home directory - credsPath, err := homedir.Expand(d.Get("shared_credentials_file").(string)) - if err != nil { - return nil, err - } - config.CredsFilename = credsPath + if l, ok := d.Get("assume_role").([]interface{}); ok && len(l) > 0 && l[0] != nil { + m := l[0].(map[string]interface{}) - assumeRoleList := d.Get("assume_role").(*schema.Set).List() - if len(assumeRoleList) == 1 { - assumeRole := assumeRoleList[0].(map[string]interface{}) - config.AssumeRoleARN = assumeRole["role_arn"].(string) - config.AssumeRoleSessionName = assumeRole["session_name"].(string) - config.AssumeRoleExternalID = assumeRole["external_id"].(string) + if v, ok := m["duration_seconds"].(int); ok && v != 0 { + config.AssumeRoleDurationSeconds = v + } + + if v, ok := m["external_id"].(string); ok && v != "" { + config.AssumeRoleExternalID = v + } - if v := assumeRole["policy"].(string); v != "" { + if v, ok := m["policy"].(string); ok && v != "" { config.AssumeRolePolicy = v } - log.Printf("[INFO] assume_role configuration set: (ARN: %q, SessionID: %q, ExternalID: %q, Policy: %q)", - config.AssumeRoleARN, config.AssumeRoleSessionName, config.AssumeRoleExternalID, config.AssumeRolePolicy) - } else { - log.Printf("[INFO] No assume_role block read from configuration") + if policyARNSet, ok := m["policy_arns"].(*schema.Set); ok && policyARNSet.Len() > 0 { + for _, policyARNRaw := range policyARNSet.List() { + policyARN, ok := policyARNRaw.(string) + + if !ok { + continue + } + + config.AssumeRolePolicyARNs = append(config.AssumeRolePolicyARNs, policyARN) + } + } + + if v, ok := m["role_arn"].(string); ok && v != "" { + config.AssumeRoleARN = v + } + + if v, ok := m["session_name"].(string); ok && v != "" { + config.AssumeRoleSessionName = v + } + + if tagMapRaw, ok := m["tags"].(map[string]interface{}); ok && len(tagMapRaw) > 0 { + config.AssumeRoleTags = make(map[string]string) + + for k, vRaw := range tagMapRaw { + v, ok := vRaw.(string) + + if !ok { + continue + } + + config.AssumeRoleTags[k] = v + } + } + + if transitiveTagKeySet, ok := m["transitive_tag_keys"].(*schema.Set); ok && transitiveTagKeySet.Len() > 0 { + for _, transitiveTagKeyRaw := range transitiveTagKeySet.List() { + transitiveTagKey, ok := transitiveTagKeyRaw.(string) + + if !ok { + continue + } + + config.AssumeRoleTransitiveTagKeys = append(config.AssumeRoleTransitiveTagKeys, transitiveTagKey) + } + } + + log.Printf("[INFO] assume_role configuration set: (ARN: %q, SessionID: %q, ExternalID: %q)", config.AssumeRoleARN, config.AssumeRoleSessionName, config.AssumeRoleExternalID) } endpointsSet := d.Get("endpoints").(*schema.Set) @@ -1212,33 +1279,53 @@ var awsMutexKV = mutexkv.NewMutexKV() func assumeRoleSchema() *schema.Schema { return &schema.Schema{ - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "role_arn": { + "duration_seconds": { + Type: schema.TypeInt, + Optional: true, + Description: "Seconds to restrict the assume role session duration.", + }, + "external_id": { Type: schema.TypeString, Optional: true, - Description: descriptions["assume_role_role_arn"], + Description: "Unique identifier that might be required for assuming a role in another account.", }, - - "session_name": { + "policy": { Type: schema.TypeString, Optional: true, - Description: descriptions["assume_role_session_name"], + Description: "IAM Policy JSON describing further restricting permissions for the IAM Role being assumed.", }, - - "external_id": { + "policy_arns": { + Type: schema.TypeSet, + Optional: true, + Description: "Amazon Resource Names (ARNs) of IAM Policies describing further restricting permissions for the IAM Role being assumed.", + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "role_arn": { Type: schema.TypeString, Optional: true, - Description: descriptions["assume_role_external_id"], + Description: "Amazon Resource Name of an IAM Role to assume prior to making API calls.", }, - - "policy": { + "session_name": { Type: schema.TypeString, Optional: true, - Description: descriptions["assume_role_policy"], + Description: "Identifier for the assumed role session.", + }, + "tags": { + Type: schema.TypeMap, + Optional: true, + Description: "Assume role session tags.", + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "transitive_tag_keys": { + Type: schema.TypeSet, + Optional: true, + Description: "Assume role session tag keys to pass to any subsequent sessions.", + Elem: &schema.Schema{Type: schema.TypeString}, }, }, }, @@ -1257,10 +1344,6 @@ func endpointsSchema() *schema.Schema { } } - // Since the endpoints attribute is a TypeSet we cannot use ConflictsWith - endpointsAttributes["kinesis_analytics"].Deprecated = "use `endpoints` configuration block `kinesisanalytics` argument instead" - endpointsAttributes["r53"].Deprecated = "use `endpoints` configuration block `route53` argument instead" - return &schema.Schema{ Type: schema.TypeSet, Optional: true, diff --git a/aws/provider_test.go b/aws/provider_test.go index 5c76f99e72e..b2ccb4b6a69 100644 --- a/aws/provider_test.go +++ b/aws/provider_test.go @@ -1,6 +1,7 @@ package aws import ( + "context" "fmt" "log" "os" @@ -14,44 +15,57 @@ import ( "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) const rfc3339RegexPattern = `^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?([Zz]|([+-]([01][0-9]|2[0-3]):[0-5][0-9]))$` +const uuidRegexPattern = `[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[ab89][a-f0-9]{3}-[a-f0-9]{12}` -var testAccProviders map[string]terraform.ResourceProvider -var testAccProviderFactories func(providers *[]*schema.Provider) map[string]terraform.ResourceProviderFactory +// TestAccSkip implements a wrapper for (*testing.T).Skip() to prevent unused linting reports +// +// Reference: https://github.com/dominikh/go-tools/issues/633#issuecomment-606560616 +var TestAccSkip = func(t *testing.T, message string) { + t.Skip(message) +} + +var testAccProviders map[string]*schema.Provider +var testAccProviderFactories func(providers *[]*schema.Provider) map[string]func() (*schema.Provider, error) var testAccProvider *schema.Provider var testAccProviderFunc func() *schema.Provider func init() { - testAccProvider = Provider().(*schema.Provider) - testAccProviders = map[string]terraform.ResourceProvider{ + testAccProvider = Provider() + testAccProviders = map[string]*schema.Provider{ "aws": testAccProvider, } - testAccProviderFactories = func(providers *[]*schema.Provider) map[string]terraform.ResourceProviderFactory { - return map[string]terraform.ResourceProviderFactory{ - "aws": func() (terraform.ResourceProvider, error) { - p := Provider() - *providers = append(*providers, p.(*schema.Provider)) + testAccProviderFactories = func(providers *[]*schema.Provider) map[string]func() (*schema.Provider, error) { + // this is an SDKV2 compatible hack, the "factory" functions are + // effectively singletons for the lifecycle of a resource.Test + var providerNames = []string{"aws", "awseast", "awswest", "awsalternate", "awsus-east-1", "awsalternateaccountalternateregion", "awsalternateaccountsameregion", "awssameaccountalternateregion", "awsthird"} + var factories = make(map[string]func() (*schema.Provider, error), len(providerNames)) + for _, name := range providerNames { + p := Provider() + factories[name] = func() (*schema.Provider, error) { //nolint:unparam return p, nil - }, + } + *providers = append(*providers, p) } + return factories } testAccProviderFunc = func() *schema.Provider { return testAccProvider } } func TestProvider(t *testing.T) { - if err := Provider().(*schema.Provider).InternalValidate(); err != nil { + if err := Provider().InternalValidate(); err != nil { t.Fatalf("err: %s", err) } } func TestProvider_impl(t *testing.T) { - var _ terraform.ResourceProvider = Provider() + var _ *schema.Provider = Provider() } func testAccPreCheck(t *testing.T) { @@ -67,7 +81,7 @@ func testAccPreCheck(t *testing.T) { log.Printf("[INFO] Test: Using %s as test region", region) os.Setenv("AWS_DEFAULT_REGION", region) - err := testAccProvider.Configure(terraform.NewResourceConfigRaw(nil)) + err := testAccProvider.Configure(context.Background(), terraform.NewResourceConfigRaw(nil)) if err != nil { t.Fatal(err) } @@ -125,6 +139,20 @@ func testAccCheckResourceAttrRegionalARNNoAccount(resourceName, attributeName, a } } +// testAccCheckResourceAttrRegionalARNAccountID ensures the Terraform state exactly matches a formatted ARN with region and specific account ID +func testAccCheckResourceAttrRegionalARNAccountID(resourceName, attributeName, arnService, accountID, arnResource string) resource.TestCheckFunc { + return func(s *terraform.State) error { + attributeValue := arn.ARN{ + AccountID: accountID, + Partition: testAccGetPartition(), + Region: testAccGetRegion(), + Resource: arnResource, + Service: arnService, + }.String() + return resource.TestCheckResourceAttr(resourceName, attributeName, attributeValue)(s) + } +} + // testAccMatchResourceAttrRegionalARN ensures the Terraform state regexp matches a formatted ARN with region func testAccMatchResourceAttrRegionalARN(resourceName, attributeName, arnService string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc { return func(s *terraform.State) error { @@ -166,6 +194,27 @@ func testAccMatchResourceAttrRegionalARNNoAccount(resourceName, attributeName, a } } +// testAccMatchResourceAttrRegionalARNAccountID ensures the Terraform state regexp matches a formatted ARN with region and specific account ID +func testAccMatchResourceAttrRegionalARNAccountID(resourceName, attributeName, arnService, accountID string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc { + return func(s *terraform.State) error { + arnRegexp := arn.ARN{ + AccountID: accountID, + Partition: testAccGetPartition(), + Region: testAccGetRegion(), + Resource: arnResourceRegexp.String(), + Service: arnService, + }.String() + + attributeMatch, err := regexp.Compile(arnRegexp) + + if err != nil { + return fmt.Errorf("Unable to compile ARN regexp (%s): %s", arnRegexp, err) + } + + return resource.TestMatchResourceAttr(resourceName, attributeName, attributeMatch)(s) + } +} + // testAccMatchResourceAttrRegionalHostname ensures the Terraform state regexp matches a formatted DNS hostname with region and partition DNS suffix func testAccMatchResourceAttrRegionalHostname(resourceName, attributeName, serviceName string, hostnamePrefixRegexp *regexp.Regexp) resource.TestCheckFunc { return func(s *terraform.State) error { @@ -206,6 +255,19 @@ func testAccCheckResourceAttrGlobalARNNoAccount(resourceName, attributeName, arn } } +// testAccCheckResourceAttrGlobalARNAccountID ensures the Terraform state exactly matches a formatted ARN without region and with specific account ID +func testAccCheckResourceAttrGlobalARNAccountID(resourceName, attributeName, accountID, arnService, arnResource string) resource.TestCheckFunc { + return func(s *terraform.State) error { + attributeValue := arn.ARN{ + AccountID: accountID, + Partition: testAccGetPartition(), + Resource: arnResource, + Service: arnService, + }.String() + return resource.TestCheckResourceAttr(resourceName, attributeName, attributeValue)(s) + } +} + // testAccMatchResourceAttrGlobalARN ensures the Terraform state regexp matches a formatted ARN without region func testAccMatchResourceAttrGlobalARN(resourceName, attributeName, arnService string, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc { return func(s *terraform.State) error { @@ -325,7 +387,7 @@ func primaryInstanceState(s *terraform.State, name string) (*terraform.InstanceS } // testAccGetAccountID returns the account ID of testAccProvider -// Must be used returned within a resource.TestCheckFunc +// Must be used within a resource.TestCheckFunc func testAccGetAccountID() string { return testAccAwsProviderAccountID(testAccProvider) } @@ -346,6 +408,14 @@ func testAccGetAlternateRegion() string { return v } +func testAccGetThirdRegion() string { + v := os.Getenv("AWS_THIRD_REGION") + if v == "" { + return "us-east-2" + } + return v +} + func testAccGetPartition() string { if partition, ok := endpoints.PartitionForRegion(endpoints.DefaultPartitions(), testAccGetRegion()); ok { return partition.ID() @@ -367,6 +437,13 @@ func testAccGetAlternateRegionPartition() string { return "aws" } +func testAccGetThirdRegionPartition() string { + if partition, ok := endpoints.PartitionForRegion(endpoints.DefaultPartitions(), testAccGetThirdRegion()); ok { + return partition.ID() + } + return "aws" +} + func testAccAlternateAccountPreCheck(t *testing.T) { if os.Getenv("AWS_ALTERNATE_PROFILE") == "" && os.Getenv("AWS_ALTERNATE_ACCESS_KEY_ID") == "" { t.Fatal("AWS_ALTERNATE_ACCESS_KEY_ID or AWS_ALTERNATE_PROFILE must be set for acceptance tests") @@ -377,6 +454,7 @@ func testAccAlternateAccountPreCheck(t *testing.T) { } } +// Deprecated: Use testAccMultipleRegionPreCheck instead func testAccAlternateRegionPreCheck(t *testing.T) { if testAccGetRegion() == testAccGetAlternateRegion() { t.Fatal("AWS_DEFAULT_REGION and AWS_ALTERNATE_REGION must be set to different values for acceptance tests") @@ -415,6 +493,37 @@ func testAccPartitionHasServicePreCheck(serviceId string, t *testing.T) { } } +func testAccMultipleRegionPreCheck(t *testing.T, regions int) { + if testAccGetRegion() == testAccGetAlternateRegion() { + t.Fatal("AWS_DEFAULT_REGION and AWS_ALTERNATE_REGION must be set to different values for acceptance tests") + } + + if testAccGetPartition() != testAccGetAlternateRegionPartition() { + t.Fatalf("AWS_ALTERNATE_REGION partition (%s) does not match AWS_DEFAULT_REGION partition (%s)", testAccGetAlternateRegionPartition(), testAccGetPartition()) + } + + if regions >= 3 { + if testAccGetRegion() == testAccGetThirdRegion() { + t.Fatal("AWS_DEFAULT_REGION and AWS_THIRD_REGION must be set to different values for acceptance tests") + } + + if testAccGetAlternateRegion() == testAccGetThirdRegion() { + t.Fatal("AWS_ALTERNATE_REGION and AWS_THIRD_REGION must be set to different values for acceptance tests") + } + + if testAccGetPartition() != testAccGetThirdRegionPartition() { + t.Fatalf("AWS_THIRD_REGION partition (%s) does not match AWS_DEFAULT_REGION partition (%s)", testAccGetThirdRegionPartition(), testAccGetPartition()) + } + } + + if partition, ok := endpoints.PartitionForRegion(endpoints.DefaultPartitions(), testAccGetRegion()); ok { + if len(partition.Regions()) < regions { + t.Skipf("skipping tests; partition includes %d regions, %d expected", len(partition.Regions()), regions) + } + } +} + +// Deprecated: Use testAccMultipleRegionPreCheck instead. func testAccMultipleRegionsPreCheck(t *testing.T) { if partition, ok := endpoints.PartitionForRegion(endpoints.DefaultPartitions(), testAccGetRegion()); ok { if len(partition.Regions()) < 2 { @@ -423,6 +532,20 @@ func testAccMultipleRegionsPreCheck(t *testing.T) { } } +// testAccRegionPreCheck checks that the test region is the specified region. +func testAccRegionPreCheck(t *testing.T, region string) { + if testAccGetRegion() != region { + t.Skipf("skipping tests; AWS_DEFAULT_REGION (%s) does not equal %s", testAccGetRegion(), region) + } +} + +// testAccPartitionPreCheck checks that the test partition is the specified partition. +func testAccPartitionPreCheck(t *testing.T, partition string) { + if testAccGetPartition() != partition { + t.Skipf("skipping tests; partition (%s) does not equal %s", testAccGetPartition(), partition) + } +} + func testAccOrganizationsAccountPreCheck(t *testing.T) { conn := testAccProvider.Meta().(*AWSClient).organizationsconn input := &organizations.DescribeOrganizationInput{} @@ -451,9 +574,8 @@ func testAccOrganizationsEnabledPreCheck(t *testing.T) { func testAccAlternateAccountProviderConfig() string { //lintignore:AT004 return fmt.Sprintf(` -provider "aws" { +provider "awsalternate" { access_key = %[1]q - alias = "alternate" profile = %[2]q secret_key = %[3]q } @@ -463,9 +585,8 @@ provider "aws" { func testAccAlternateAccountAlternateRegionProviderConfig() string { //lintignore:AT004 return fmt.Sprintf(` -provider "aws" { +provider "awsalternate" { access_key = %[1]q - alias = "alternate" profile = %[2]q region = %[3]q secret_key = %[4]q @@ -478,38 +599,57 @@ provider "aws" { func testAccAlternateAccountAndAlternateRegionProviderConfig() string { //lintignore:AT004 return fmt.Sprintf(` -provider "aws" { +provider "awsalternateaccountalternateregion" { access_key = %[1]q - alias = "alternateaccountalternateregion" profile = %[2]q region = %[3]q secret_key = %[4]q } -provider "aws" { +provider "awsalternateaccountsameregion" { access_key = %[1]q - alias = "alternateaccountsameregion" profile = %[2]q secret_key = %[4]q } -provider "aws" { - alias = "sameaccountalternateregion" +provider "awssameaccountalternateregion" { region = %[3]q } `, os.Getenv("AWS_ALTERNATE_ACCESS_KEY_ID"), os.Getenv("AWS_ALTERNATE_PROFILE"), testAccGetAlternateRegion(), os.Getenv("AWS_ALTERNATE_SECRET_ACCESS_KEY")) } +// Deprecated: Use testAccMultipleRegionProviderConfig instead func testAccAlternateRegionProviderConfig() string { //lintignore:AT004 return fmt.Sprintf(` -provider "aws" { - alias = "alternate" +provider "awsalternate" { region = %[1]q } `, testAccGetAlternateRegion()) } +func testAccMultipleRegionProviderConfig(regions int) string { + var config strings.Builder + + //lintignore:AT004 + fmt.Fprintf(&config, ` +provider "awsalternate" { + region = %[1]q +} +`, testAccGetAlternateRegion()) + + if regions >= 3 { + //lintignore:AT004 + fmt.Fprintf(&config, ` +provider "awsthird" { + region = %[1]q +} +`, testAccGetThirdRegion()) + } + + return config.String() +} + func testAccProviderConfigIgnoreTagsKeyPrefixes1(keyPrefix1 string) string { //lintignore:AT004 return fmt.Sprintf(` @@ -540,12 +680,11 @@ provider "aws" { // Cost and Usage Reporting and Pricing services. func testAccUsEast1RegionProviderConfig() string { //lintignore:AT004 - return fmt.Sprintf(` -provider "aws" { - alias = "us-east-1" + return ` +provider "awsus-east-1" { region = "us-east-1" } -`) +` } func testAccAwsRegionProviderFunc(region string, providers *[]*schema.Provider) func() *schema.Provider { @@ -678,6 +817,10 @@ func testSweepSkipSweepError(err error) bool { if isAWSErr(err, "InvalidAction", "is not valid") { return true } + // For example from GovCloud SES.SetActiveReceiptRuleSet. + if isAWSErr(err, "InvalidAction", "Unavailable Operation") { + return true + } return false } @@ -687,11 +830,6 @@ func TestAccAWSProvider_Endpoints(t *testing.T) { // Initialize each endpoint configuration with matching name and value for _, endpointServiceName := range endpointServiceNames { - // Skip deprecated endpoint configurations as they will override expected values - if endpointServiceName == "kinesis_analytics" || endpointServiceName == "r53" { - continue - } - endpoints.WriteString(fmt.Sprintf("%s = \"http://%s\"\n", endpointServiceName, endpointServiceName)) } @@ -710,34 +848,6 @@ func TestAccAWSProvider_Endpoints(t *testing.T) { }) } -func TestAccAWSProvider_Endpoints_Deprecated(t *testing.T) { - var providers []*schema.Provider - var endpointsDeprecated strings.Builder - - // Initialize each deprecated endpoint configuration with matching name and value - for _, endpointServiceName := range endpointServiceNames { - // Only configure deprecated endpoint configurations - if endpointServiceName != "kinesis_analytics" && endpointServiceName != "r53" { - continue - } - - endpointsDeprecated.WriteString(fmt.Sprintf("%s = \"http://%s\"\n", endpointServiceName, endpointServiceName)) - } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories(&providers), - CheckDestroy: nil, - Steps: []resource.TestStep{ - { - Config: testAccAWSProviderConfigEndpoints(endpointsDeprecated.String()), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSProviderEndpointsDeprecated(&providers)), - }, - }, - }) -} - func TestAccAWSProvider_IgnoreTags_EmptyConfigurationBlock(t *testing.T) { var providers []*schema.Provider @@ -925,6 +1035,24 @@ func TestAccAWSProvider_Region_AwsGovCloudUs(t *testing.T) { }) } +func TestAccAWSProvider_AssumeRole_Empty(t *testing.T) { + var providers []*schema.Provider + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProviderFactories: testAccProviderFactories(&providers), + CheckDestroy: nil, + Steps: []resource.TestStep{ + { + Config: testAccCheckAWSProviderConfigAssumeRoleEmpty, + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsCallerIdentityAccountId("data.aws_caller_identity.current"), + ), + }, + }, + }) +} + func testAccCheckAWSProviderDnsSuffix(providers *[]*schema.Provider, expectedDnsSuffix string) resource.TestCheckFunc { return func(s *terraform.State) error { if providers == nil { @@ -1001,61 +1129,6 @@ func testAccCheckAWSProviderEndpoints(providers *[]*schema.Provider) resource.Te providerClient := provider.Meta().(*AWSClient) for _, endpointServiceName := range endpointServiceNames { - // Skip deprecated endpoint configurations as they will override expected values - if endpointServiceName == "kinesis_analytics" || endpointServiceName == "r53" { - continue - } - - providerClientField := reflect.Indirect(reflect.ValueOf(providerClient)).FieldByNameFunc(endpointFieldNameF(endpointServiceName)) - - if !providerClientField.IsValid() { - return fmt.Errorf("unable to match AWSClient struct field name for endpoint name: %s", endpointServiceName) - } - - actualEndpoint := reflect.Indirect(reflect.Indirect(providerClientField).FieldByName("Config").FieldByName("Endpoint")).String() - expectedEndpoint := fmt.Sprintf("http://%s", endpointServiceName) - - if actualEndpoint != expectedEndpoint { - return fmt.Errorf("expected endpoint (%s) value (%s), got: %s", endpointServiceName, expectedEndpoint, actualEndpoint) - } - } - } - - return nil - } -} - -func testAccCheckAWSProviderEndpointsDeprecated(providers *[]*schema.Provider) resource.TestCheckFunc { - return func(s *terraform.State) error { - if providers == nil { - return fmt.Errorf("no providers initialized") - } - - // Match AWSClient struct field names to endpoint configuration names - endpointFieldNameF := func(endpoint string) func(string) bool { - return func(name string) bool { - switch endpoint { - case "kinesis_analytics": - endpoint = "kinesisanalytics" - } - - return name == fmt.Sprintf("%sconn", endpoint) - } - } - - for _, provider := range *providers { - if provider == nil || provider.Meta() == nil || provider.Meta().(*AWSClient) == nil { - continue - } - - providerClient := provider.Meta().(*AWSClient) - - for _, endpointServiceName := range endpointServiceNames { - // Only check deprecated endpoint configurations - if endpointServiceName != "kinesis_analytics" && endpointServiceName != "r53" { - continue - } - providerClientField := reflect.Indirect(reflect.ValueOf(providerClient)).FieldByNameFunc(endpointFieldNameF(endpointServiceName)) if !providerClientField.IsValid() { @@ -1223,16 +1296,19 @@ func testAccCheckAWSProviderPartition(providers *[]*schema.Provider, expectedPar } } -// testAccPreCheckHasDefaultVpcOrEc2Classic checks that the test region has a default VPC or has the EC2-Classic platform. +// testAccPreCheckEc2ClassicOrHasDefaultVpcWithDefaultSubnets checks that the test region has either +// - The EC2-Classic platform available, or +// - A default VPC with default subnets. // This check is useful to ensure that an instance can be launched without specifying a subnet. -func testAccPreCheckHasDefaultVpcOrEc2Classic(t *testing.T) { +func testAccPreCheckEc2ClassicOrHasDefaultVpcWithDefaultSubnets(t *testing.T) { client := testAccProvider.Meta().(*AWSClient) - if !testAccHasDefaultVpc(t) && !hasEc2Classic(client.supportedplatforms) { - t.Skipf("skipping tests; %s does not have a default VPC or EC2-Classic", client.region) + if !hasEc2Classic(client.supportedplatforms) && !(testAccHasDefaultVpc(t) && testAccDefaultSubnetCount(t) > 0) { + t.Skipf("skipping tests; %s does not have EC2-Classic or a default VPC with default subnets", client.region) } } +// testAccHasDefaultVpc returns whether the current AWS region has a default VPC. func testAccHasDefaultVpc(t *testing.T) bool { conn := testAccProvider.Meta().(*AWSClient).ec2conn @@ -1252,6 +1328,26 @@ func testAccHasDefaultVpc(t *testing.T) bool { return true } +// testAccDefaultSubnetCount returns the number of default subnets in the current region's default VPC. +func testAccDefaultSubnetCount(t *testing.T) int { + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + input := &ec2.DescribeSubnetsInput{ + Filters: buildEC2AttributeFilterList(map[string]string{ + "defaultForAz": "true", + }), + } + output, err := conn.DescribeSubnets(input) + if testAccPreCheckSkipError(err) { + return 0 + } + if err != nil { + t.Fatalf("error describing default subnets: %s", err) + } + + return len(output.Subnets) +} + func testAccAWSProviderConfigEndpoints(endpoints string) string { //lintignore:AT004 return fmt.Sprintf(` @@ -1275,7 +1371,7 @@ data "aws_arn" "test" { func testAccAWSProviderConfigIgnoreTagsEmptyConfigurationBlock() string { //lintignore:AT004 - return fmt.Sprintf(` + return ` provider "aws" { ignore_tags {} @@ -1289,12 +1385,12 @@ provider "aws" { data "aws_arn" "test" { arn = "arn:aws:s3:::test" } -`) +` } func testAccAWSProviderConfigIgnoreTagsKeyPrefixes0() string { //lintignore:AT004 - return fmt.Sprintf(` + return ` provider "aws" { skip_credentials_validation = true skip_get_ec2_platforms = true @@ -1306,7 +1402,7 @@ provider "aws" { data "aws_arn" "test" { arn = "arn:aws:s3:::test" } -`) +` } func testAccAWSProviderConfigIgnoreTagsKeyPrefixes1(tagPrefix1 string) string { @@ -1353,7 +1449,7 @@ data "aws_arn" "test" { func testAccAWSProviderConfigIgnoreTagsKeys0() string { //lintignore:AT004 - return fmt.Sprintf(` + return ` provider "aws" { skip_credentials_validation = true skip_get_ec2_platforms = true @@ -1365,7 +1461,7 @@ provider "aws" { data "aws_arn" "test" { arn = "arn:aws:s3:::test" } -`) +` } func testAccAWSProviderConfigIgnoreTagsKeys1(tag1 string) string { @@ -1447,6 +1543,15 @@ provider "aws" { `, os.Getenv("TF_ACC_ASSUME_ROLE_ARN"), policy) } +const testAccCheckAWSProviderConfigAssumeRoleEmpty = ` +provider "aws" { + assume_role { + } +} + +data "aws_caller_identity" "current" {} +` + // composeConfig can be called to concatenate multiple strings to build test configurations func composeConfig(config ...string) string { var str strings.Builder diff --git a/aws/resource_aws_accessanalyzer_analyzer.go b/aws/resource_aws_accessanalyzer_analyzer.go index e28b9cfef05..976e908452b 100644 --- a/aws/resource_aws_accessanalyzer_analyzer.go +++ b/aws/resource_aws_accessanalyzer_analyzer.go @@ -3,15 +3,24 @@ package aws import ( "fmt" "log" + "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/accessanalyzer" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) +const ( + // Maximum amount of time to wait for Organizations eventual consistency on creation + // This timeout value is much higher than usual since the cross-service validation + // appears to be consistently caching for 5 minutes: + // --- PASS: TestAccAWSAccessAnalyzer_serial/Analyzer/Type_Organization (315.86s) + accessAnalyzerOrganizationCreationTimeout = 10 * time.Minute +) + func resourceAwsAccessAnalyzerAnalyzer() *schema.Resource { return &schema.Resource{ Create: resourceAwsAccessAnalyzerAnalyzerCreate, @@ -37,9 +46,11 @@ func resourceAwsAccessAnalyzerAnalyzer() *schema.Resource { "type": { Type: schema.TypeString, Optional: true, + ForceNew: true, Default: accessanalyzer.TypeAccount, ValidateFunc: validation.StringInSlice([]string{ accessanalyzer.TypeAccount, + accessanalyzer.TypeOrganization, }, false), }, }, @@ -57,7 +68,24 @@ func resourceAwsAccessAnalyzerAnalyzerCreate(d *schema.ResourceData, meta interf Type: aws.String(d.Get("type").(string)), } - _, err := conn.CreateAnalyzer(input) + // Handle Organizations eventual consistency + err := resource.Retry(accessAnalyzerOrganizationCreationTimeout, func() *resource.RetryError { + _, err := conn.CreateAnalyzer(input) + + if isAWSErr(err, accessanalyzer.ErrCodeValidationException, "You must create an organization") { + return resource.RetryableError(err) + } + + if err != nil { + return resource.NonRetryableError(err) + } + + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.CreateAnalyzer(input) + } if err != nil { return fmt.Errorf("error creating Access Analyzer Analyzer (%s): %s", analyzerName, err) diff --git a/aws/resource_aws_accessanalyzer_analyzer_test.go b/aws/resource_aws_accessanalyzer_analyzer_test.go index fa80b36a081..a0b94018a15 100644 --- a/aws/resource_aws_accessanalyzer_analyzer_test.go +++ b/aws/resource_aws_accessanalyzer_analyzer_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/accessanalyzer" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // This test can be run via the pattern: TestAccAWSAccessAnalyzer @@ -112,6 +112,38 @@ func testAccAWSAccessAnalyzerAnalyzer_Tags(t *testing.T) { }) } +// This test can be run via the pattern: TestAccAWSAccessAnalyzer +func testAccAWSAccessAnalyzerAnalyzer_Type_Organization(t *testing.T) { + var analyzer accessanalyzer.AnalyzerSummary + + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_accessanalyzer_analyzer.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + testAccPreCheckAWSAccessAnalyzer(t) + testAccOrganizationsAccountPreCheck(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAccessAnalyzerAnalyzerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAccessAnalyzerAnalyzerConfigTypeOrganization(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsAccessAnalyzerAnalyzerExists(resourceName, &analyzer), + resource.TestCheckResourceAttr(resourceName, "type", accessanalyzer.TypeOrganization), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func testAccCheckAccessAnalyzerAnalyzerDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).accessanalyzerconn @@ -218,3 +250,20 @@ resource "aws_accessanalyzer_analyzer" "test" { } `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } + +func testAccAWSAccessAnalyzerAnalyzerConfigTypeOrganization(rName string) string { + return fmt.Sprintf(` +data "aws_partition" "current" {} + +resource "aws_organizations_organization" "test" { + aws_service_access_principals = ["access-analyzer.${data.aws_partition.current.dns_suffix}"] +} + +resource "aws_accessanalyzer_analyzer" "test" { + depends_on = [aws_organizations_organization.test] + + analyzer_name = %[1]q + type = "ORGANIZATION" +} +`, rName) +} diff --git a/aws/resource_aws_accessanalyzer_test.go b/aws/resource_aws_accessanalyzer_test.go index 8599262fc09..638025c99b1 100644 --- a/aws/resource_aws_accessanalyzer_test.go +++ b/aws/resource_aws_accessanalyzer_test.go @@ -8,12 +8,13 @@ import ( // AccessAnalyzer is limited to one per region, so run serially // locally and in TeamCity. -func TestAccAWSAccessAnalyzer(t *testing.T) { +func TestAccAWSAccessAnalyzer_serial(t *testing.T) { testCases := map[string]map[string]func(t *testing.T){ "Analyzer": { - "basic": testAccAWSAccessAnalyzerAnalyzer_basic, - "disappears": testAccAWSAccessAnalyzerAnalyzer_disappears, - "Tags": testAccAWSAccessAnalyzerAnalyzer_Tags, + "basic": testAccAWSAccessAnalyzerAnalyzer_basic, + "disappears": testAccAWSAccessAnalyzerAnalyzer_disappears, + "Tags": testAccAWSAccessAnalyzerAnalyzer_Tags, + "Type_Organization": testAccAWSAccessAnalyzerAnalyzer_Type_Organization, }, } diff --git a/aws/resource_aws_acm_certificate.go b/aws/resource_aws_acm_certificate.go index dcc95600b4f..7512680a897 100644 --- a/aws/resource_aws_acm_certificate.go +++ b/aws/resource_aws_acm_certificate.go @@ -1,20 +1,35 @@ package aws import ( + "context" + "crypto/sha1" + "encoding/hex" "errors" "fmt" "log" + "regexp" "strings" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/acm" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) +const ( + // Maximum amount of time for ACM Certificate cross-service reference propagation. + // Removal of ACM Certificates from API Gateway Custom Domains can take >15 minutes. + AcmCertificateCrossServicePropagationTimeout = 20 * time.Minute + + // Maximum amount of time for ACM Certificate asynchronous DNS validation record assignment. + // This timeout is unrelated to any creation or validation of those assigned DNS records. + AcmCertificateDnsValidationAssignmentTimeout = 5 * time.Minute +) + func resourceAwsAcmCertificate() *schema.Resource { return &schema.Resource{ Create: resourceAwsAcmCertificateCreate, @@ -26,20 +41,16 @@ func resourceAwsAcmCertificate() *schema.Resource { }, Schema: map[string]*schema.Schema{ "certificate_body": { - Type: schema.TypeString, - Optional: true, - StateFunc: normalizeCert, + Type: schema.TypeString, + Optional: true, }, - "certificate_chain": { - Type: schema.TypeString, - Optional: true, - StateFunc: normalizeCert, + Type: schema.TypeString, + Optional: true, }, "private_key": { Type: schema.TypeString, Optional: true, - StateFunc: normalizeCert, Sensitive: true, }, "certificate_authority_arn": { @@ -48,31 +59,30 @@ func resourceAwsAcmCertificate() *schema.Resource { ForceNew: true, }, "domain_name": { + // AWS Provider 3.0.0 aws_route53_zone references no longer contain a + // trailing period, no longer requiring a custom StateFunc + // to prevent ACM API error Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, ConflictsWith: []string{"private_key", "certificate_body", "certificate_chain"}, - StateFunc: func(v interface{}) string { - // AWS Provider 1.42.0+ aws_route53_zone references may contain a - // trailing period, which generates an ACM API error - return strings.TrimSuffix(v.(string), ".") - }, + ValidateFunc: validation.StringDoesNotMatch(regexp.MustCompile(`\.$`), "cannot end with a period"), }, "subject_alternative_names": { - Type: schema.TypeList, - Optional: true, - Computed: true, - ForceNew: true, - ConflictsWith: []string{"private_key", "certificate_body", "certificate_chain"}, + Type: schema.TypeSet, + Optional: true, + Computed: true, + ForceNew: true, Elem: &schema.Schema{ - Type: schema.TypeString, - StateFunc: func(v interface{}) string { - // AWS Provider 1.42.0+ aws_route53_zone references may contain a - // trailing period, which generates an ACM API error - return strings.TrimSuffix(v.(string), ".") - }, + // AWS Provider 3.0.0 aws_route53_zone references no longer contain a + // trailing period, no longer requiring a custom StateFunc + // to prevent ACM API error + Type: schema.TypeString, + ValidateFunc: validation.StringDoesNotMatch(regexp.MustCompile(`\.$`), "cannot end with a period"), }, + Set: schema.HashString, + ConflictsWith: []string{"private_key", "certificate_body", "certificate_chain"}, }, "validation_method": { Type: schema.TypeString, @@ -86,7 +96,7 @@ func resourceAwsAcmCertificate() *schema.Resource { Computed: true, }, "domain_validation_options": { - Type: schema.TypeList, + Type: schema.TypeSet, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -108,6 +118,7 @@ func resourceAwsAcmCertificate() *schema.Resource { }, }, }, + Set: acmDomainValidationOptionsHash, }, "validation_emails": { Type: schema.TypeList, @@ -143,8 +154,48 @@ func resourceAwsAcmCertificate() *schema.Resource { }, }, }, + "status": { + Type: schema.TypeString, + Computed: true, + }, "tags": tagsSchema(), }, + CustomizeDiff: func(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { + // Attempt to calculate the domain validation options based on domains present in domain_name and subject_alternative_names + if diff.Get("validation_method").(string) == "DNS" && (diff.HasChange("domain_name") || diff.HasChange("subject_alternative_names")) { + domainValidationOptionsList := []interface{}{map[string]interface{}{ + // AWS Provider 3.0 -- plan-time validation prevents "domain_name" + // argument to accept a string with trailing period; thus, trim of trailing period + // no longer required here + "domain_name": diff.Get("domain_name").(string), + }} + + if sanSet, ok := diff.Get("subject_alternative_names").(*schema.Set); ok { + for _, sanRaw := range sanSet.List() { + san, ok := sanRaw.(string) + + if !ok { + continue + } + + m := map[string]interface{}{ + // AWS Provider 3.0 -- plan-time validation prevents "subject_alternative_names" + // argument to accept strings with trailing period; thus, trim of trailing period + // no longer required here + "domain_name": san, + } + + domainValidationOptionsList = append(domainValidationOptionsList, m) + } + } + + if err := diff.SetNew("domain_validation_options", schema.NewSet(acmDomainValidationOptionsHash, domainValidationOptionsList)); err != nil { + return fmt.Errorf("error setting new domain_validation_options diff: %w", err) + } + } + + return nil + }, } } @@ -182,7 +233,7 @@ func resourceAwsAcmCertificateCreateImported(d *schema.ResourceData, meta interf func resourceAwsAcmCertificateCreateRequested(d *schema.ResourceData, meta interface{}) error { acmconn := meta.(*AWSClient).acmconn params := &acm.RequestCertificateInput{ - DomainName: aws.String(strings.TrimSuffix(d.Get("domain_name").(string), ".")), + DomainName: aws.String(d.Get("domain_name").(string)), IdempotencyToken: aws.String(resource.PrefixedUniqueId("tf")), // 32 character limit Options: expandAcmCertificateOptions(d.Get("options").([]interface{})), } @@ -196,9 +247,9 @@ func resourceAwsAcmCertificateCreateRequested(d *schema.ResourceData, meta inter } if sans, ok := d.GetOk("subject_alternative_names"); ok { - subjectAlternativeNames := make([]*string, len(sans.([]interface{}))) - for i, sanRaw := range sans.([]interface{}) { - subjectAlternativeNames[i] = aws.String(strings.TrimSuffix(sanRaw.(string), ".")) + subjectAlternativeNames := make([]*string, len(sans.(*schema.Set).List())) + for i, sanRaw := range sans.(*schema.Set).List() { + subjectAlternativeNames[i] = aws.String(sanRaw.(string)) } params.SubjectAlternativeNames = subjectAlternativeNames } @@ -227,7 +278,7 @@ func resourceAwsAcmCertificateRead(d *schema.ResourceData, meta interface{}) err CertificateArn: aws.String(d.Id()), } - return resource.Retry(time.Duration(1)*time.Minute, func() *resource.RetryError { + return resource.Retry(AcmCertificateDnsValidationAssignmentTimeout, func() *resource.RetryError { resp, err := acmconn.DescribeCertificate(params) if err != nil { @@ -259,12 +310,14 @@ func resourceAwsAcmCertificateRead(d *schema.ResourceData, meta interface{}) err return resource.NonRetryableError(err) } - d.Set("validation_method", resourceAwsAcmCertificateGuessValidationMethod(domainValidationOptions, emailValidationOptions)) + d.Set("validation_method", resourceAwsAcmCertificateValidationMethod(resp.Certificate)) if err := d.Set("options", flattenAcmCertificateOptions(resp.Certificate.Options)); err != nil { return resource.NonRetryableError(fmt.Errorf("error setting certificate options: %s", err)) } + d.Set("status", resp.Certificate.Status) + tags, err := keyvaluetags.AcmListTags(acmconn, d.Id()) if err != nil { @@ -278,25 +331,33 @@ func resourceAwsAcmCertificateRead(d *schema.ResourceData, meta interface{}) err return nil }) } -func resourceAwsAcmCertificateGuessValidationMethod(domainValidationOptions []map[string]interface{}, emailValidationOptions []string) string { - // The DescribeCertificate Response doesn't have information on what validation method was used - // so we need to guess from the validation options we see... - if len(domainValidationOptions) > 0 { - return acm.ValidationMethodDns - } else if len(emailValidationOptions) > 0 { - return acm.ValidationMethodEmail - } else { - return "NONE" +func resourceAwsAcmCertificateValidationMethod(certificate *acm.CertificateDetail) string { + if aws.StringValue(certificate.Type) == acm.CertificateTypeAmazonIssued { + for _, domainValidation := range certificate.DomainValidationOptions { + if domainValidation.ValidationMethod != nil { + return aws.StringValue(domainValidation.ValidationMethod) + } + } } + + return "NONE" } func resourceAwsAcmCertificateUpdate(d *schema.ResourceData, meta interface{}) error { acmconn := meta.(*AWSClient).acmconn - if d.HasChange("private_key") || d.HasChange("certificate_body") || d.HasChange("certificate_chain") { - _, err := resourceAwsAcmCertificateImport(acmconn, d, true) - if err != nil { - return fmt.Errorf("Error updating certificate: %s", err) + if d.HasChanges("private_key", "certificate_body", "certificate_chain") { + // Prior to version 3.0.0 of the Terraform AWS Provider, these attributes were stored in state as hashes. + // If the changes to these attributes are only changes only match updating the state value, then skip the API call. + oCBRaw, nCBRaw := d.GetChange("certificate_body") + oCCRaw, nCCRaw := d.GetChange("certificate_chain") + oPKRaw, nPKRaw := d.GetChange("private_key") + + if !isChangeNormalizeCertRemoval(oCBRaw, nCBRaw) || !isChangeNormalizeCertRemoval(oCCRaw, nCCRaw) || !isChangeNormalizeCertRemoval(oPKRaw, nPKRaw) { + _, err := resourceAwsAcmCertificateImport(acmconn, d, true) + if err != nil { + return fmt.Errorf("Error updating certificate: %s", err) + } } } @@ -334,10 +395,10 @@ func convertValidationOptions(certificate *acm.CertificateDetail) ([]map[string] for _, o := range certificate.DomainValidationOptions { if o.ResourceRecord != nil { validationOption := map[string]interface{}{ - "domain_name": *o.DomainName, - "resource_record_name": *o.ResourceRecord.Name, - "resource_record_type": *o.ResourceRecord.Type, - "resource_record_value": *o.ResourceRecord.Value, + "domain_name": aws.StringValue(o.DomainName), + "resource_record_name": aws.StringValue(o.ResourceRecord.Name), + "resource_record_type": aws.StringValue(o.ResourceRecord.Type), + "resource_record_value": aws.StringValue(o.ResourceRecord.Value), } domainValidationResult = append(domainValidationResult, validationOption) } else if o.ValidationEmails != nil && len(o.ValidationEmails) > 0 { @@ -345,8 +406,8 @@ func convertValidationOptions(certificate *acm.CertificateDetail) ([]map[string] emailValidationResult = append(emailValidationResult, *validationEmail) } } else if o.ValidationStatus == nil || aws.StringValue(o.ValidationStatus) == acm.DomainStatusPendingValidation { - log.Printf("[DEBUG] No validation options need to retry: %#v", o) - return nil, nil, fmt.Errorf("No validation options need to retry: %#v", o) + log.Printf("[DEBUG] Asynchronous ACM service domain validation assignment not complete, need to retry: %#v", o) + return nil, nil, fmt.Errorf("asynchronous ACM service domain validation assignment not complete, need to retry: %#v", o) } } case acm.CertificateTypePrivate: @@ -369,7 +430,7 @@ func resourceAwsAcmCertificateDelete(d *schema.ResourceData, meta interface{}) e CertificateArn: aws.String(d.Id()), } - err := resource.Retry(10*time.Minute, func() *resource.RetryError { + err := resource.Retry(AcmCertificateCrossServicePropagationTimeout, func() *resource.RetryError { _, err := acmconn.DeleteCertificate(params) if err != nil { if isAWSErr(err, acm.ErrCodeResourceInUseException, "") { @@ -407,6 +468,20 @@ func resourceAwsAcmCertificateImport(conn *acm.ACM, d *schema.ResourceData, upda return conn.ImportCertificate(params) } +func acmDomainValidationOptionsHash(v interface{}) int { + m, ok := v.(map[string]interface{}) + + if !ok { + return 0 + } + + if v, ok := m["domain_name"].(string); ok { + return hashcode.String(v) + } + + return 0 +} + func expandAcmCertificateOptions(l []interface{}) *acm.CertificateOptions { if len(l) == 0 || l[0] == nil { return nil @@ -430,3 +505,20 @@ func flattenAcmCertificateOptions(co *acm.CertificateOptions) []interface{} { return []interface{}{m} } + +func isChangeNormalizeCertRemoval(oldRaw, newRaw interface{}) bool { + old, ok := oldRaw.(string) + + if !ok { + return false + } + + new, ok := newRaw.(string) + + if !ok { + return false + } + + newCleanVal := sha1.Sum(stripCR([]byte(strings.TrimSpace(new)))) + return hex.EncodeToString(newCleanVal[:]) == old +} diff --git a/aws/resource_aws_acm_certificate_test.go b/aws/resource_aws_acm_certificate_test.go index 35e75fa4007..0c31a6f180d 100644 --- a/aws/resource_aws_acm_certificate_test.go +++ b/aws/resource_aws_acm_certificate_test.go @@ -13,9 +13,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/acm" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -131,6 +132,7 @@ func TestAccAWSAcmCertificate_emailValidation(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "0"), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusPendingValidation), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "0"), resource.TestMatchResourceAttr(resourceName, "validation_emails.0", regexp.MustCompile(`^[^@]+@.+$`)), resource.TestCheckResourceAttr(resourceName, "validation_method", acm.ValidationMethodEmail), @@ -162,10 +164,11 @@ func TestAccAWSAcmCertificate_dnsValidation(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "1"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.domain_name", domain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_value"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": domain, + "resource_record_type": "CNAME", + }), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusPendingValidation), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_emails.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_method", acm.ValidationMethodDns), @@ -195,10 +198,11 @@ func TestAccAWSAcmCertificate_root(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", rootDomain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "1"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.domain_name", rootDomain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_value"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": rootDomain, + "resource_record_type": "CNAME", + }), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusPendingValidation), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_emails.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_method", acm.ValidationMethodDns), @@ -229,6 +233,7 @@ func TestAccAWSAcmCertificate_privateCert(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", fmt.Sprintf("%s.terraformtesting.com", rName)), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "0"), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusFailed), // FailureReason: PCA_INVALID_STATE (PCA State: PENDING_CERTIFICATE) resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_emails.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_method", "NONE"), @@ -244,10 +249,11 @@ func TestAccAWSAcmCertificate_privateCert(t *testing.T) { }) } +// TestAccAWSAcmCertificate_root_TrailingPeriod updated in 3.0 to account for domain_name plan-time validation +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/13510 func TestAccAWSAcmCertificate_root_TrailingPeriod(t *testing.T) { rootDomain := testAccAwsAcmCertificateDomainFromEnv(t) domain := fmt.Sprintf("%s.", rootDomain) - resourceName := "aws_acm_certificate.cert" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -255,24 +261,8 @@ func TestAccAWSAcmCertificate_root_TrailingPeriod(t *testing.T) { CheckDestroy: testAccCheckAcmCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateConfig(domain, acm.ValidationMethodDns), - Check: resource.ComposeTestCheckFunc( - testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile(`certificate/.+`)), - resource.TestCheckResourceAttr(resourceName, "domain_name", strings.TrimSuffix(domain, ".")), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "1"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.domain_name", strings.TrimSuffix(domain, ".")), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_value"), - resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "0"), - resource.TestCheckResourceAttr(resourceName, "validation_emails.#", "0"), - resource.TestCheckResourceAttr(resourceName, "validation_method", acm.ValidationMethodDns), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, + Config: testAccAcmCertificateConfig(domain, acm.ValidationMethodDns), + ExpectError: regexp.MustCompile(`invalid value for domain_name \(cannot end with a period\)`), }, }, }) @@ -294,16 +284,17 @@ func TestAccAWSAcmCertificate_rootAndWildcardSan(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", rootDomain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "2"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.domain_name", rootDomain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_value"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.1.domain_name", wildcardDomain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.1.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.1.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.1.resource_record_value"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": rootDomain, + "resource_record_type": "CNAME", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": wildcardDomain, + "resource_record_type": "CNAME", + }), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusPendingValidation), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "1"), - resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.0", wildcardDomain), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "subject_alternative_names.*", wildcardDomain), resource.TestCheckResourceAttr(resourceName, "validation_emails.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_method", acm.ValidationMethodDns), ), @@ -334,16 +325,17 @@ func TestAccAWSAcmCertificate_san_single(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "2"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.domain_name", domain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_value"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.1.domain_name", sanDomain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.1.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.1.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.1.resource_record_value"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": domain, + "resource_record_type": "CNAME", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": sanDomain, + "resource_record_type": "CNAME", + }), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusPendingValidation), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "1"), - resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.0", sanDomain), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "subject_alternative_names.*", sanDomain), resource.TestCheckResourceAttr(resourceName, "validation_emails.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_method", acm.ValidationMethodDns), ), @@ -375,21 +367,22 @@ func TestAccAWSAcmCertificate_san_multiple(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "3"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.domain_name", domain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_value"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.1.domain_name", sanDomain1), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.1.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.1.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.1.resource_record_value"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.2.domain_name", sanDomain2), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.2.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.2.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.2.resource_record_value"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": domain, + "resource_record_type": "CNAME", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": sanDomain1, + "resource_record_type": "CNAME", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": sanDomain2, + "resource_record_type": "CNAME", + }), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusPendingValidation), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "2"), - resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.0", sanDomain1), - resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.1", sanDomain2), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "subject_alternative_names.*", sanDomain1), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "subject_alternative_names.*", sanDomain2), resource.TestCheckResourceAttr(resourceName, "validation_emails.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_method", acm.ValidationMethodDns), ), @@ -420,16 +413,17 @@ func TestAccAWSAcmCertificate_san_TrailingPeriod(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile(`certificate/.+`)), resource.TestCheckResourceAttr(resourceName, "domain_name", domain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "2"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.domain_name", domain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_value"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.1.domain_name", strings.TrimSuffix(sanDomain, ".")), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.1.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.1.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.1.resource_record_value"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": domain, + "resource_record_type": "CNAME", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": strings.TrimSuffix(sanDomain, "."), + "resource_record_type": "CNAME", + }), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusPendingValidation), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "1"), - resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.0", strings.TrimSuffix(sanDomain, ".")), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "subject_alternative_names.*", strings.TrimSuffix(sanDomain, ".")), resource.TestCheckResourceAttr(resourceName, "validation_emails.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_method", acm.ValidationMethodDns), ), @@ -459,10 +453,11 @@ func TestAccAWSAcmCertificate_wildcard(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", wildcardDomain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "1"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.domain_name", wildcardDomain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_value"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": wildcardDomain, + "resource_record_type": "CNAME", + }), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusPendingValidation), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_emails.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_method", acm.ValidationMethodDns), @@ -493,16 +488,17 @@ func TestAccAWSAcmCertificate_wildcardAndRootSan(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", wildcardDomain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "2"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.domain_name", wildcardDomain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_value"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.1.domain_name", rootDomain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.1.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.1.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.1.resource_record_value"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": rootDomain, + "resource_record_type": "CNAME", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": wildcardDomain, + "resource_record_type": "CNAME", + }), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusPendingValidation), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "1"), - resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.0", rootDomain), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "subject_alternative_names.*", rootDomain), resource.TestCheckResourceAttr(resourceName, "validation_emails.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_method", acm.ValidationMethodDns), ), @@ -531,11 +527,12 @@ func TestAccAWSAcmCertificate_disableCTLogging(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "acm", regexp.MustCompile("certificate/.+$")), resource.TestCheckResourceAttr(resourceName, "domain_name", rootDomain), resource.TestCheckResourceAttr(resourceName, "domain_validation_options.#", "1"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.domain_name", rootDomain), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_name"), - resource.TestCheckResourceAttr(resourceName, "domain_validation_options.0.resource_record_type", "CNAME"), - resource.TestCheckResourceAttrSet(resourceName, "domain_validation_options.0.resource_record_value"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "domain_validation_options.*", map[string]string{ + "domain_name": rootDomain, + "resource_record_type": "CNAME", + }), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "0"), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusPendingValidation), resource.TestCheckResourceAttr(resourceName, "validation_emails.#", "0"), resource.TestCheckResourceAttr(resourceName, "validation_method", acm.ValidationMethodDns), resource.TestCheckResourceAttr(resourceName, "options.#", "1"), @@ -603,23 +600,42 @@ func TestAccAWSAcmCertificate_tags(t *testing.T) { func TestAccAWSAcmCertificate_imported_DomainName(t *testing.T) { resourceName := "aws_acm_certificate.test" + commonName := "example.com" + caKey := tlsRsaPrivateKeyPem(2048) + caCertificate := tlsRsaX509SelfSignedCaCertificatePem(caKey) + key := tlsRsaPrivateKeyPem(2048) + certificate := tlsRsaX509LocallySignedCertificatePem(caKey, caCertificate, key, commonName) + + newCaKey := tlsRsaPrivateKeyPem(2048) + newCaCertificate := tlsRsaX509SelfSignedCaCertificatePem(newCaKey) + newCertificate := tlsRsaX509LocallySignedCertificatePem(newCaKey, newCaCertificate, key, commonName) + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAcmCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateConfigPrivateKey("example.com"), + Config: testAccAcmCertificateConfigPrivateKey(certificate, key, caCertificate), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "domain_name", commonName), + ), + }, + { + Config: testAccAcmCertificateConfigPrivateKey(newCertificate, key, newCaCertificate), Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusIssued), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), + resource.TestCheckResourceAttr(resourceName, "domain_name", commonName), ), }, { - Config: testAccAcmCertificateConfigPrivateKey("example.org"), + Config: testAccAcmCertificateConfigPrivateKeyWithoutChain("example2.com"), Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusIssued), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.org"), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example2.com"), ), }, { @@ -627,7 +643,7 @@ func TestAccAWSAcmCertificate_imported_DomainName(t *testing.T) { ImportState: true, ImportStateVerify: true, // These are not returned by the API - ImportStateVerifyIgnore: []string{"private_key", "certificate_body"}, + ImportStateVerifyIgnore: []string{"private_key", "certificate_body", "certificate_chain"}, }, }, }) @@ -643,9 +659,10 @@ func TestAccAWSAcmCertificate_imported_IpAddress(t *testing.T) { // Reference: h CheckDestroy: testAccCheckAcmCertificateDestroy, Steps: []resource.TestStep{ { - Config: testAccAcmCertificateConfigPrivateKey("1.2.3.4"), + Config: testAccAcmCertificateConfigPrivateKeyWithoutChain("1.2.3.4"), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "domain_name", ""), + resource.TestCheckResourceAttr(resourceName, "status", acm.CertificateStatusIssued), resource.TestCheckResourceAttr(resourceName, "subject_alternative_names.#", "0"), ), }, @@ -730,7 +747,7 @@ resource "aws_acm_certificate" "cert" { `, domainName, validationMethod, tag1Key, tag1Value, tag2Key, tag2Value) } -func testAccAcmCertificateConfigPrivateKey(commonName string) string { +func testAccAcmCertificateConfigPrivateKeyWithoutChain(commonName string) string { key := tlsRsaPrivateKeyPem(2048) certificate := tlsRsaX509SelfSignedCertificatePem(key, commonName) @@ -742,6 +759,16 @@ resource "aws_acm_certificate" "test" { `, tlsPemEscapeNewlines(certificate), tlsPemEscapeNewlines(key)) } +func testAccAcmCertificateConfigPrivateKey(certificate, privateKey, chain string) string { + return fmt.Sprintf(` +resource "aws_acm_certificate" "test" { + certificate_body = "%[1]s" + private_key = "%[2]s" + certificate_chain = "%[3]s" +} +`, tlsPemEscapeNewlines(certificate), tlsPemEscapeNewlines(privateKey), tlsPemEscapeNewlines(chain)) +} + func testAccAcmCertificateConfig_disableCTLogging(domainName, validationMethod string) string { return fmt.Sprintf(` resource "aws_acm_certificate" "cert" { diff --git a/aws/resource_aws_acm_certificate_validation.go b/aws/resource_aws_acm_certificate_validation.go index 4dadcaef81c..89ffc3459e6 100644 --- a/aws/resource_aws_acm_certificate_validation.go +++ b/aws/resource_aws_acm_certificate_validation.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/acm" multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsAcmCertificateValidation() *schema.Resource { @@ -50,10 +50,14 @@ func resourceAwsAcmCertificateValidationCreate(d *schema.ResourceData, meta inte resp, err := acmconn.DescribeCertificate(params) if err != nil { - return fmt.Errorf("Error describing certificate: %s", err) + return fmt.Errorf("Error describing certificate: %w", err) } - if *resp.Certificate.Type != "AMAZON_ISSUED" { + if resp == nil || resp.Certificate == nil { + return fmt.Errorf("Error describing certificate: empty output") + } + + if aws.StringValue(resp.Certificate.Type) != acm.CertificateTypeAmazonIssued { return fmt.Errorf("Certificate %s has type %s, no validation necessary", aws.StringValue(resp.Certificate.CertificateArn), aws.StringValue(resp.Certificate.Status)) } @@ -70,7 +74,7 @@ func resourceAwsAcmCertificateValidationCreate(d *schema.ResourceData, meta inte resp, err := acmconn.DescribeCertificate(params) if err != nil { - return resource.NonRetryableError(fmt.Errorf("Error describing certificate: %s", err)) + return resource.NonRetryableError(fmt.Errorf("Error describing certificate: %w", err)) } if aws.StringValue(resp.Certificate.Status) != acm.CertificateStatusIssued { @@ -78,7 +82,10 @@ func resourceAwsAcmCertificateValidationCreate(d *schema.ResourceData, meta inte } log.Printf("[INFO] ACM Certificate validation for %s done, certificate was issued", certificate_arn) - return resource.NonRetryableError(resourceAwsAcmCertificateValidationRead(d, meta)) + if err := resourceAwsAcmCertificateValidationRead(d, meta); err != nil { + return resource.NonRetryableError(err) + } + return nil }) if isResourceTimeoutError(err) { resp, err = acmconn.DescribeCertificate(params) @@ -87,7 +94,7 @@ func resourceAwsAcmCertificateValidationCreate(d *schema.ResourceData, meta inte } } if err != nil { - return fmt.Errorf("Error describing created certificate: %s", err) + return fmt.Errorf("Error describing created certificate: %w", err) } return nil } @@ -102,13 +109,13 @@ func resourceAwsAcmCertificateCheckValidationRecords(validationRecordFqdns []int var err error var output *acm.DescribeCertificateOutput err = resource.Retry(1*time.Minute, func() *resource.RetryError { - log.Printf("[DEBUG] Certificate domain validation options empty for %q, retrying", *cert.CertificateArn) + log.Printf("[DEBUG] Certificate domain validation options empty for %s, retrying", aws.StringValue(cert.CertificateArn)) output, err = conn.DescribeCertificate(input) if err != nil { return resource.NonRetryableError(err) } if len(output.Certificate.DomainValidationOptions) == 0 { - return resource.RetryableError(fmt.Errorf("Certificate domain validation options empty for %s", *cert.CertificateArn)) + return resource.RetryableError(fmt.Errorf("Certificate domain validation options empty for %s", aws.StringValue(cert.CertificateArn))) } cert = output.Certificate return nil @@ -116,24 +123,30 @@ func resourceAwsAcmCertificateCheckValidationRecords(validationRecordFqdns []int if isResourceTimeoutError(err) { output, err = conn.DescribeCertificate(input) if err != nil { - return fmt.Errorf("Error describing ACM certificate: %s", err) + return fmt.Errorf("Error describing ACM certificate: %w", err) } if len(output.Certificate.DomainValidationOptions) == 0 { - return fmt.Errorf("Certificate domain validation options empty for %s", *cert.CertificateArn) + return fmt.Errorf("Certificate domain validation options empty for %s", aws.StringValue(cert.CertificateArn)) } } if err != nil { - return fmt.Errorf("Error checking certificate domain validation options: %s", err) + return fmt.Errorf("Error checking certificate domain validation options: %w", err) } + if output == nil || output.Certificate == nil { + return fmt.Errorf("Error checking certificate domain validation options: empty output") + } + cert = output.Certificate } for _, v := range cert.DomainValidationOptions { if v.ValidationMethod != nil { - if *v.ValidationMethod != acm.ValidationMethodDns { + if aws.StringValue(v.ValidationMethod) != acm.ValidationMethodDns { return fmt.Errorf("validation_record_fqdns is only valid for DNS validation") } - newExpectedFqdn := strings.TrimSuffix(*v.ResourceRecord.Name, ".") - expectedFqdns[newExpectedFqdn] = v + if v.ResourceRecord != nil && aws.StringValue(v.ResourceRecord.Name) != "" { + newExpectedFqdn := strings.TrimSuffix(aws.StringValue(v.ResourceRecord.Name), ".") + expectedFqdns[newExpectedFqdn] = v + } } else if len(v.ValidationEmails) > 0 { // ACM API sometimes is not sending ValidationMethod for EMAIL validation return fmt.Errorf("validation_record_fqdns is only valid for DNS validation") @@ -147,7 +160,7 @@ func resourceAwsAcmCertificateCheckValidationRecords(validationRecordFqdns []int if len(expectedFqdns) > 0 { var errors error for expectedFqdn, domainValidation := range expectedFqdns { - errors = multierror.Append(errors, fmt.Errorf("missing %s DNS validation record: %s", *domainValidation.DomainName, expectedFqdn)) + errors = multierror.Append(errors, fmt.Errorf("missing %s DNS validation record: %s", aws.StringValue(domainValidation.DomainName), expectedFqdn)) } return errors } @@ -168,14 +181,14 @@ func resourceAwsAcmCertificateValidationRead(d *schema.ResourceData, meta interf d.SetId("") return nil } else if err != nil { - return fmt.Errorf("Error describing certificate: %s", err) + return fmt.Errorf("Error describing certificate: %w", err) } if aws.StringValue(resp.Certificate.Status) != acm.CertificateStatusIssued { log.Printf("[INFO] Certificate status not issued, was %s, tainting validation", aws.StringValue(resp.Certificate.Status)) d.SetId("") } else { - d.SetId((*resp.Certificate.IssuedAt).String()) + d.SetId(aws.TimeValue(resp.Certificate.IssuedAt).String()) } return nil } diff --git a/aws/resource_aws_acm_certificate_validation_test.go b/aws/resource_aws_acm_certificate_validation_test.go index 7b39b0f0c0f..a4499cc47c2 100644 --- a/aws/resource_aws_acm_certificate_validation_test.go +++ b/aws/resource_aws_acm_certificate_validation_test.go @@ -6,13 +6,14 @@ import ( "strconv" "testing" - "github.com/aws/aws-sdk-go/service/acm" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSAcmCertificateValidation_basic(t *testing.T) { rootDomain := testAccAwsAcmCertificateDomainFromEnv(t) domain := testAccAwsAcmCertificateRandomSubDomain(rootDomain) + certificateResourceName := "aws_acm_certificate.test" + resourceName := "aws_acm_certificate_validation.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -23,7 +24,7 @@ func TestAccAWSAcmCertificateValidation_basic(t *testing.T) { { Config: testAccAcmCertificateValidation_basic(rootDomain, domain), Check: resource.ComposeTestCheckFunc( - testAccMatchResourceAttrRegionalARN("aws_acm_certificate_validation.cert", "certificate_arn", "acm", regexp.MustCompile("certificate/.+$")), + resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, }, @@ -50,6 +51,8 @@ func TestAccAWSAcmCertificateValidation_timeout(t *testing.T) { func TestAccAWSAcmCertificateValidation_validationRecordFqdns(t *testing.T) { rootDomain := testAccAwsAcmCertificateDomainFromEnv(t) domain := testAccAwsAcmCertificateRandomSubDomain(rootDomain) + certificateResourceName := "aws_acm_certificate.test" + resourceName := "aws_acm_certificate_validation.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -65,7 +68,7 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdns(t *testing.T) { { Config: testAccAcmCertificateValidation_validationRecordFqdnsOneRoute53Record(rootDomain, domain), Check: resource.ComposeTestCheckFunc( - testAccMatchResourceAttrRegionalARN("aws_acm_certificate_validation.cert", "certificate_arn", "acm", regexp.MustCompile("certificate/.+$")), + resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, }, @@ -91,6 +94,8 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdnsEmail(t *testing.T) func TestAccAWSAcmCertificateValidation_validationRecordFqdnsRoot(t *testing.T) { rootDomain := testAccAwsAcmCertificateDomainFromEnv(t) + certificateResourceName := "aws_acm_certificate.test" + resourceName := "aws_acm_certificate_validation.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -100,7 +105,7 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdnsRoot(t *testing.T) { Config: testAccAcmCertificateValidation_validationRecordFqdnsOneRoute53Record(rootDomain, rootDomain), Check: resource.ComposeTestCheckFunc( - testAccMatchResourceAttrRegionalARN("aws_acm_certificate_validation.cert", "certificate_arn", "acm", regexp.MustCompile("certificate/.+$")), + resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, }, @@ -110,6 +115,8 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdnsRoot(t *testing.T) func TestAccAWSAcmCertificateValidation_validationRecordFqdnsRootAndWildcard(t *testing.T) { rootDomain := testAccAwsAcmCertificateDomainFromEnv(t) wildcardDomain := fmt.Sprintf("*.%s", rootDomain) + certificateResourceName := "aws_acm_certificate.test" + resourceName := "aws_acm_certificate_validation.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -119,7 +126,7 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdnsRootAndWildcard(t * { Config: testAccAcmCertificateValidation_validationRecordFqdnsTwoRoute53Records(rootDomain, rootDomain, strconv.Quote(wildcardDomain)), Check: resource.ComposeTestCheckFunc( - testAccMatchResourceAttrRegionalARN("aws_acm_certificate_validation.cert", "certificate_arn", "acm", regexp.MustCompile("certificate/.+$")), + resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, }, @@ -130,6 +137,8 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdnsSan(t *testing.T) { rootDomain := testAccAwsAcmCertificateDomainFromEnv(t) domain := testAccAwsAcmCertificateRandomSubDomain(rootDomain) sanDomain := testAccAwsAcmCertificateRandomSubDomain(rootDomain) + certificateResourceName := "aws_acm_certificate.test" + resourceName := "aws_acm_certificate_validation.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -139,7 +148,7 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdnsSan(t *testing.T) { { Config: testAccAcmCertificateValidation_validationRecordFqdnsTwoRoute53Records(rootDomain, domain, strconv.Quote(sanDomain)), Check: resource.ComposeTestCheckFunc( - testAccMatchResourceAttrRegionalARN("aws_acm_certificate_validation.cert", "certificate_arn", "acm", regexp.MustCompile("certificate/.+$")), + resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, }, @@ -149,6 +158,8 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdnsSan(t *testing.T) { func TestAccAWSAcmCertificateValidation_validationRecordFqdnsWildcard(t *testing.T) { rootDomain := testAccAwsAcmCertificateDomainFromEnv(t) wildcardDomain := fmt.Sprintf("*.%s", rootDomain) + certificateResourceName := "aws_acm_certificate.test" + resourceName := "aws_acm_certificate_validation.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -158,7 +169,7 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdnsWildcard(t *testing { Config: testAccAcmCertificateValidation_validationRecordFqdnsOneRoute53Record(rootDomain, wildcardDomain), Check: resource.ComposeTestCheckFunc( - testAccMatchResourceAttrRegionalARN("aws_acm_certificate_validation.cert", "certificate_arn", "acm", regexp.MustCompile("certificate/.+$")), + resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, }, @@ -168,6 +179,8 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdnsWildcard(t *testing func TestAccAWSAcmCertificateValidation_validationRecordFqdnsWildcardAndRoot(t *testing.T) { rootDomain := testAccAwsAcmCertificateDomainFromEnv(t) wildcardDomain := fmt.Sprintf("*.%s", rootDomain) + certificateResourceName := "aws_acm_certificate.test" + resourceName := "aws_acm_certificate_validation.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -177,7 +190,7 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdnsWildcardAndRoot(t * { Config: testAccAcmCertificateValidation_validationRecordFqdnsTwoRoute53Records(rootDomain, wildcardDomain, strconv.Quote(rootDomain)), Check: resource.ComposeTestCheckFunc( - testAccMatchResourceAttrRegionalARN("aws_acm_certificate_validation.cert", "certificate_arn", "acm", regexp.MustCompile("certificate/.+$")), + resource.TestCheckResourceAttrPair(resourceName, "certificate_arn", certificateResourceName, "arn"), ), }, }, @@ -186,125 +199,210 @@ func TestAccAWSAcmCertificateValidation_validationRecordFqdnsWildcardAndRoot(t * func testAccAcmCertificateValidation_basic(rootZoneDomain, domainName string) string { return fmt.Sprintf(` -%s +resource "aws_acm_certificate" "test" { + domain_name = %[1]q + validation_method = "DNS" +} -data "aws_route53_zone" "zone" { - name = "%s." +data "aws_route53_zone" "test" { + name = %[2]q private_zone = false } -resource "aws_route53_record" "cert_validation" { - allow_overwrite = true # Enabled for test parallelization - name = "${aws_acm_certificate.cert.domain_validation_options.0.resource_record_name}" - type = "${aws_acm_certificate.cert.domain_validation_options.0.resource_record_type}" - zone_id = "${data.aws_route53_zone.zone.id}" - records = ["${aws_acm_certificate.cert.domain_validation_options.0.resource_record_value}"] +# +# for_each acceptance testing requires SDKv2 +# +# resource "aws_route53_record" "test" { +# for_each = { +# for dvo in aws_acm_certificate.test.domain_validation_options: dvo.domain_name => { +# name = dvo.resource_record_name +# record = dvo.resource_record_value +# type = dvo.resource_record_type +# } +# } + +# allow_overwrite = true +# name = each.value.name +# records = [each.value.record] +# ttl = 60 +# type = each.value.type +# zone_id = data.aws_route53_zone.test.zone_id +# } + +resource "aws_route53_record" "test" { + allow_overwrite = true + name = tolist(aws_acm_certificate.test.domain_validation_options)[0].resource_record_name + records = [tolist(aws_acm_certificate.test.domain_validation_options)[0].resource_record_value] ttl = 60 + type = tolist(aws_acm_certificate.test.domain_validation_options)[0].resource_record_type + zone_id = data.aws_route53_zone.test.zone_id } -resource "aws_acm_certificate_validation" "cert" { - depends_on = ["aws_route53_record.cert_validation"] +resource "aws_acm_certificate_validation" "test" { + depends_on = ["aws_route53_record.test"] - certificate_arn = "${aws_acm_certificate.cert.arn}" + certificate_arn = aws_acm_certificate.test.arn } -`, testAccAcmCertificateConfig(domainName, acm.ValidationMethodDns), rootZoneDomain) +`, domainName, rootZoneDomain) } func testAccAcmCertificateValidation_timeout(domainName string) string { return fmt.Sprintf(` -%s +resource "aws_acm_certificate" "test" { + domain_name = %[1]q + validation_method = "DNS" +} -resource "aws_acm_certificate_validation" "cert" { - certificate_arn = "${aws_acm_certificate.cert.arn}" +resource "aws_acm_certificate_validation" "test" { + certificate_arn = aws_acm_certificate.test.arn timeouts { create = "5s" } } -`, testAccAcmCertificateConfig(domainName, acm.ValidationMethodDns)) +`, domainName) } func testAccAcmCertificateValidation_validationRecordFqdnsEmailValidation(domainName string) string { return fmt.Sprintf(` -%s +resource "aws_acm_certificate" "test" { + domain_name = %[1]q + validation_method = "EMAIL" +} -resource "aws_acm_certificate_validation" "cert" { - certificate_arn = "${aws_acm_certificate.cert.arn}" +resource "aws_acm_certificate_validation" "test" { + certificate_arn = aws_acm_certificate.test.arn validation_record_fqdns = ["wrong-validation-fqdn.example.com"] } -`, testAccAcmCertificateConfig(domainName, acm.ValidationMethodEmail)) +`, domainName) } func testAccAcmCertificateValidation_validationRecordFqdnsOneRoute53Record(rootZoneDomain, domainName string) string { return fmt.Sprintf(` -%s +resource "aws_acm_certificate" "test" { + domain_name = %[1]q + validation_method = "DNS" +} -data "aws_route53_zone" "zone" { - name = "%s." +data "aws_route53_zone" "test" { + name = %[2]q private_zone = false } -resource "aws_route53_record" "cert_validation" { - allow_overwrite = true # Enabled for test parallelization - name = "${aws_acm_certificate.cert.domain_validation_options.0.resource_record_name}" - type = "${aws_acm_certificate.cert.domain_validation_options.0.resource_record_type}" - zone_id = "${data.aws_route53_zone.zone.id}" - records = ["${aws_acm_certificate.cert.domain_validation_options.0.resource_record_value}"] +# +# for_each acceptance testing requires SDKv2 +# +# resource "aws_route53_record" "test" { +# for_each = { +# for dvo in aws_acm_certificate.test.domain_validation_options: dvo.domain_name => { +# name = dvo.resource_record_name +# record = dvo.resource_record_value +# type = dvo.resource_record_type +# } +# } + +# allow_overwrite = true +# name = each.value.name +# records = [each.value.record] +# ttl = 60 +# type = each.value.type +# zone_id = data.aws_route53_zone.test.zone_id +# } + +# resource "aws_acm_certificate_validation" "test" { +# certificate_arn = aws_acm_certificate.test.arn +# validation_record_fqdns = [for record in aws_route53_record.test: record.fqdn] +# } + +resource "aws_route53_record" "test" { + allow_overwrite = true + name = tolist(aws_acm_certificate.test.domain_validation_options)[0].resource_record_name + records = [tolist(aws_acm_certificate.test.domain_validation_options)[0].resource_record_value] ttl = 60 + type = tolist(aws_acm_certificate.test.domain_validation_options)[0].resource_record_type + zone_id = data.aws_route53_zone.test.zone_id } -resource "aws_acm_certificate_validation" "cert" { - certificate_arn = "${aws_acm_certificate.cert.arn}" - validation_record_fqdns = ["${aws_route53_record.cert_validation.fqdn}"] +resource "aws_acm_certificate_validation" "test" { + certificate_arn = aws_acm_certificate.test.arn + validation_record_fqdns = [aws_route53_record.test.fqdn] } -`, testAccAcmCertificateConfig(domainName, acm.ValidationMethodDns), rootZoneDomain) +`, domainName, rootZoneDomain) } func testAccAcmCertificateValidation_validationRecordFqdnsTwoRoute53Records(rootZoneDomain, domainName, subjectAlternativeNames string) string { return fmt.Sprintf(` -%s +resource "aws_acm_certificate" "test" { + domain_name = %[1]q + subject_alternative_names = [%[2]s] + validation_method = "DNS" +} -data "aws_route53_zone" "zone" { - name = "%s." +data "aws_route53_zone" "test" { + name = %[3]q private_zone = false } -resource "aws_route53_record" "cert_validation" { - allow_overwrite = true # Enabled for test parallelization - name = "${aws_acm_certificate.cert.domain_validation_options.0.resource_record_name}" - type = "${aws_acm_certificate.cert.domain_validation_options.0.resource_record_type}" - zone_id = "${data.aws_route53_zone.zone.id}" - records = ["${aws_acm_certificate.cert.domain_validation_options.0.resource_record_value}"] +# +# for_each acceptance testing requires SDKv2 +# +# resource "aws_route53_record" "test" { +# for_each = { +# for dvo in aws_acm_certificate.test.domain_validation_options: dvo.domain_name => { +# name = dvo.resource_record_name +# record = dvo.resource_record_value +# type = dvo.resource_record_type +# } +# } + +# allow_overwrite = true +# name = each.value.name +# records = [each.value.record] +# ttl = 60 +# type = each.value.type +# zone_id = data.aws_route53_zone.test.zone_id +# } + +# resource "aws_acm_certificate_validation" "test" { +# certificate_arn = aws_acm_certificate.test.arn +# validation_record_fqdns = [for record in aws_route53_record.test: record.fqdn] +# } + +resource "aws_route53_record" "test" { + allow_overwrite = true + name = tolist(aws_acm_certificate.test.domain_validation_options)[0].resource_record_name + records = [tolist(aws_acm_certificate.test.domain_validation_options)[0].resource_record_value] ttl = 60 + type = tolist(aws_acm_certificate.test.domain_validation_options)[0].resource_record_type + zone_id = data.aws_route53_zone.test.zone_id } -resource "aws_route53_record" "cert_validation_san" { - allow_overwrite = true # Enabled for test parallelization - name = "${aws_acm_certificate.cert.domain_validation_options.1.resource_record_name}" - type = "${aws_acm_certificate.cert.domain_validation_options.1.resource_record_type}" - zone_id = "${data.aws_route53_zone.zone.id}" - records = ["${aws_acm_certificate.cert.domain_validation_options.1.resource_record_value}"] +resource "aws_route53_record" "test2" { + allow_overwrite = true + name = tolist(aws_acm_certificate.test.domain_validation_options)[1].resource_record_name + records = [tolist(aws_acm_certificate.test.domain_validation_options)[1].resource_record_value] ttl = 60 + type = tolist(aws_acm_certificate.test.domain_validation_options)[1].resource_record_type + zone_id = data.aws_route53_zone.test.zone_id } -resource "aws_acm_certificate_validation" "cert" { - certificate_arn = "${aws_acm_certificate.cert.arn}" - - validation_record_fqdns = [ - "${aws_route53_record.cert_validation.fqdn}", - "${aws_route53_record.cert_validation_san.fqdn}", - ] +resource "aws_acm_certificate_validation" "test" { + certificate_arn = aws_acm_certificate.test.arn + validation_record_fqdns = [aws_route53_record.test.fqdn, aws_route53_record.test2.fqdn] } -`, testAccAcmCertificateConfig_subjectAlternativeNames(domainName, subjectAlternativeNames, acm.ValidationMethodDns), rootZoneDomain) +`, domainName, subjectAlternativeNames, rootZoneDomain) } func testAccAcmCertificateValidation_validationRecordFqdnsWrongFqdn(domainName string) string { return fmt.Sprintf(` -%s +resource "aws_acm_certificate" "test" { + domain_name = %[1]q + validation_method = "DNS" +} -resource "aws_acm_certificate_validation" "cert" { - certificate_arn = "${aws_acm_certificate.cert.arn}" +resource "aws_acm_certificate_validation" "test" { + certificate_arn = aws_acm_certificate.test.arn validation_record_fqdns = ["wrong-validation-fqdn.example.com"] } -`, testAccAcmCertificateConfig(domainName, acm.ValidationMethodDns)) +`, domainName) } diff --git a/aws/resource_aws_acmpca_certificate_authority.go b/aws/resource_aws_acmpca_certificate_authority.go index 138e8232d48..5bf84e542d0 100644 --- a/aws/resource_aws_acmpca_certificate_authority.go +++ b/aws/resource_aws_acmpca_certificate_authority.go @@ -7,13 +7,14 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/acmpca" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) func resourceAwsAcmpcaCertificateAuthority() *schema.Resource { + //lintignore:R011 return &schema.Resource{ Create: resourceAwsAcmpcaCertificateAuthorityCreate, Read: resourceAwsAcmpcaCertificateAuthorityRead, diff --git a/aws/resource_aws_acmpca_certificate_authority_migrate.go b/aws/resource_aws_acmpca_certificate_authority_migrate.go index 32b052b5e28..1e039f8975b 100644 --- a/aws/resource_aws_acmpca_certificate_authority_migrate.go +++ b/aws/resource_aws_acmpca_certificate_authority_migrate.go @@ -4,7 +4,7 @@ import ( "fmt" "log" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func resourceAwsAcmpcaCertificateAuthorityMigrateState(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { diff --git a/aws/resource_aws_acmpca_certificate_authority_migrate_test.go b/aws/resource_aws_acmpca_certificate_authority_migrate_test.go index a7f16d61480..b1a94585451 100644 --- a/aws/resource_aws_acmpca_certificate_authority_migrate_test.go +++ b/aws/resource_aws_acmpca_certificate_authority_migrate_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAwsAcmpcaCertificateAuthorityMigrateState(t *testing.T) { diff --git a/aws/resource_aws_acmpca_certificate_authority_test.go b/aws/resource_aws_acmpca_certificate_authority_test.go index 91659c37ed5..5e9109c885f 100644 --- a/aws/resource_aws_acmpca_certificate_authority_test.go +++ b/aws/resource_aws_acmpca_certificate_authority_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/acmpca" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -60,7 +60,7 @@ func testSweepAcmpcaCertificateAuthorities(region string) error { return nil } -func TestAccAwsAcmpcaCertificateAuthority_Basic(t *testing.T) { +func TestAccAwsAcmpcaCertificateAuthority_basic(t *testing.T) { var certificateAuthority acmpca.CertificateAuthority resourceName := "aws_acmpca_certificate_authority.test" @@ -109,7 +109,7 @@ func TestAccAwsAcmpcaCertificateAuthority_Enabled(t *testing.T) { resourceName := "aws_acmpca_certificate_authority.test" // error updating ACMPCA Certificate Authority: InvalidStateException: The certificate authority must be in the Active or DISABLED state to be updated - t.Skip("We need to fully sign the certificate authority CSR from another CA in order to test this functionality, which requires another resource") + TestAccSkip(t, "We need to fully sign the certificate authority CSR from another CA in order to test this functionality, which requires another resource") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, diff --git a/aws/resource_aws_alb_target_group_test.go b/aws/resource_aws_alb_target_group_test.go index f832679d93d..d5d555e5464 100644 --- a/aws/resource_aws_alb_target_group_test.go +++ b/aws/resource_aws_alb_target_group_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestALBTargetGroupCloudwatchSuffixFromARN(t *testing.T) { diff --git a/aws/resource_aws_ami.go b/aws/resource_aws_ami.go index 9e25b346d2e..c6f3925e495 100644 --- a/aws/resource_aws_ami.go +++ b/aws/resource_aws_ami.go @@ -9,12 +9,13 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -56,7 +57,12 @@ func resourceAwsAmi() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: "x86_64", + Default: ec2.ArchitectureTypeX8664, + ValidateFunc: validation.StringInSlice([]string{ + ec2.ArchitectureTypeX8664, + ec2.ArchitectureValuesI386, + ec2.ArchitectureValuesArm64, + }, false), }, "description": { Type: schema.TypeString, @@ -116,7 +122,14 @@ func resourceAwsAmi() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: "standard", + Default: ec2.VolumeTypeStandard, + ValidateFunc: validation.StringInSlice([]string{ + ec2.VolumeTypeStandard, + ec2.VolumeTypeIo1, + ec2.VolumeTypeGp2, + ec2.VolumeTypeSc1, + ec2.VolumeTypeSt1, + }, false), }, }, }, @@ -202,7 +215,15 @@ func resourceAwsAmi() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: "paravirtual", + Default: ec2.VirtualizationTypeParavirtual, + ValidateFunc: validation.StringInSlice([]string{ + ec2.VirtualizationTypeParavirtual, + ec2.VirtualizationTypeHvm, + }, false), + }, + "arn": { + Type: schema.TypeString, + Computed: true, }, }, } @@ -311,8 +332,7 @@ func resourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error { if d.IsNewResource() { return resource.RetryableError(err) } - - log.Printf("[DEBUG] %s no longer exists, so we'll drop it from the state", id) + log.Printf("[WARN] AMI (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -329,6 +349,7 @@ func resourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error { } if len(res.Images) != 1 { + log.Printf("[WARN] AMI (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -336,7 +357,7 @@ func resourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error { image := res.Images[0] state := *image.State - if state == "pending" { + if state == ec2.ImageStatePending { // This could happen if a user manually adds an image we didn't create // to the state. We'll wait for the image to become available // before we continue. We should never take this branch in normal @@ -349,12 +370,13 @@ func resourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error { state = *image.State } - if state == "deregistered" { + if state == ec2.ImageStateDeregistered { + log.Printf("[WARN] AMI (%s) not found, removing from state", d.Id()) d.SetId("") return nil } - if state != "available" { + if state != ec2.ImageStateAvailable { return fmt.Errorf("AMI has become %s", state) } @@ -370,6 +392,15 @@ func resourceAwsAmiRead(d *schema.ResourceData, meta interface{}) error { d.Set("virtualization_type", image.VirtualizationType) d.Set("ena_support", image.EnaSupport) + imageArn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Region: meta.(*AWSClient).region, + Resource: fmt.Sprintf("image/%s", d.Id()), + Service: "ec2", + }.String() + + d.Set("arn", imageArn) + var ebsBlockDevs []map[string]interface{} var ephemeralBlockDevs []map[string]interface{} @@ -488,7 +519,7 @@ func AMIStateRefreshFunc(client *ec2.EC2, id string) resource.StateRefreshFunc { resp, err := client.DescribeImages(&ec2.DescribeImagesInput{ImageIds: []*string{aws.String(id)}}) if err != nil { - if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidAMIID.NotFound" { + if isAWSErr(err, "InvalidAMIID.NotFound", "") { return emptyResp, "destroyed", nil } else if resp != nil && len(resp.Images) == 0 { return emptyResp, "destroyed", nil @@ -510,7 +541,7 @@ func resourceAwsAmiWaitForDestroy(timeout time.Duration, id string, client *ec2. log.Printf("Waiting for AMI %s to be deleted...", id) stateConf := &resource.StateChangeConf{ - Pending: []string{"available", "pending", "failed"}, + Pending: []string{ec2.ImageStateAvailable, ec2.ImageStatePending, ec2.ImageStateFailed}, Target: []string{"destroyed"}, Refresh: AMIStateRefreshFunc(client, id), Timeout: timeout, @@ -530,8 +561,8 @@ func resourceAwsAmiWaitForAvailable(timeout time.Duration, id string, client *ec log.Printf("Waiting for AMI %s to become available...", id) stateConf := &resource.StateChangeConf{ - Pending: []string{"pending"}, - Target: []string{"available"}, + Pending: []string{ec2.ImageStatePending}, + Target: []string{ec2.ImageStateAvailable}, Refresh: AMIStateRefreshFunc(client, id), Timeout: timeout, Delay: AWSAMIRetryDelay, diff --git a/aws/resource_aws_ami_copy.go b/aws/resource_aws_ami_copy.go index c41c864f1d8..1ed5bb2ea93 100644 --- a/aws/resource_aws_ami_copy.go +++ b/aws/resource_aws_ami_copy.go @@ -6,9 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -182,6 +181,10 @@ func resourceAwsAmiCopy() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "arn": { + Type: schema.TypeString, + Computed: true, + }, }, // The remaining operations are shared with the generic aws_ami resource, diff --git a/aws/resource_aws_ami_copy_test.go b/aws/resource_aws_ami_copy_test.go index e51707437ab..7b0974684f6 100644 --- a/aws/resource_aws_ami_copy_test.go +++ b/aws/resource_aws_ami_copy_test.go @@ -2,13 +2,14 @@ package aws import ( "fmt" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAMICopy_basic(t *testing.T) { @@ -26,6 +27,7 @@ func TestAccAWSAMICopy_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSAMICopyExists(resourceName, &image), testAccCheckAWSAMICopyAttributes(&image, rName), + testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), ), }, }, @@ -181,10 +183,10 @@ func testAccCheckAWSAMICopyDestroy(s *terraform.State) error { func testAccCheckAWSAMICopyAttributes(image *ec2.Image, expectedName string) resource.TestCheckFunc { return func(s *terraform.State) error { - if expected := "available"; aws.StringValue(image.State) != expected { + if expected := ec2.ImageStateAvailable; aws.StringValue(image.State) != expected { return fmt.Errorf("invalid image state; expected %s, got %s", expected, aws.StringValue(image.State)) } - if expected := "machine"; aws.StringValue(image.ImageType) != expected { + if expected := ec2.ImageTypeValuesMachine; aws.StringValue(image.ImageType) != expected { return fmt.Errorf("wrong image type; expected %s, got %s", expected, aws.StringValue(image.ImageType)) } if expected := expectedName; aws.StringValue(image.Name) != expected { @@ -209,7 +211,7 @@ func testAccCheckAWSAMICopyAttributes(image *ec2.Image, expectedName string) res } } -func testAccAWSAMICopyConfigBase() string { +func testAccAWSAMICopyConfigBase(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -226,7 +228,7 @@ resource "aws_ebs_volume" "test" { size = 1 tags = { - Name = "tf-acc-test-ami-copy" + Name = %[1]q } } @@ -234,14 +236,14 @@ resource "aws_ebs_snapshot" "test" { volume_id = "${aws_ebs_volume.test.id}" tags = { - Name = "tf-acc-test-ami-copy" + Name = %[1]q } } -`) +`, rName) } func testAccAWSAMICopyConfigTags1(rName, tagKey1, tagValue1 string) string { - return testAccAWSAMICopyConfigBase() + fmt.Sprintf(` + return testAccAWSAMICopyConfigBase(rName) + fmt.Sprintf(` resource "aws_ami" "test" { name = %[1]q virtualization_type = "hvm" @@ -266,7 +268,7 @@ resource "aws_ami_copy" "test" { } func testAccAWSAMICopyConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return testAccAWSAMICopyConfigBase() + fmt.Sprintf(` + return testAccAWSAMICopyConfigBase(rName) + fmt.Sprintf(` resource "aws_ami" "test" { name = %[1]q virtualization_type = "hvm" @@ -292,7 +294,7 @@ resource "aws_ami_copy" "test" { } func testAccAWSAMICopyConfig(rName string) string { - return testAccAWSAMICopyConfigBase() + fmt.Sprintf(` + return testAccAWSAMICopyConfigBase(rName) + fmt.Sprintf(` resource "aws_ami" "test" { name = "%s-source" virtualization_type = "hvm" @@ -313,7 +315,7 @@ resource "aws_ami_copy" "test" { } func testAccAWSAMICopyConfigDescription(rName, description string) string { - return testAccAWSAMICopyConfigBase() + fmt.Sprintf(` + return testAccAWSAMICopyConfigBase(rName) + fmt.Sprintf(` resource "aws_ami" "test" { name = "%s-source" virtualization_type = "hvm" @@ -335,7 +337,7 @@ resource "aws_ami_copy" "test" { } func testAccAWSAMICopyConfigENASupport(rName string) string { - return testAccAWSAMICopyConfigBase() + fmt.Sprintf(` + return testAccAWSAMICopyConfigBase(rName) + fmt.Sprintf(` resource "aws_ami" "test" { ena_support = true name = "%s-source" diff --git a/aws/resource_aws_ami_from_instance.go b/aws/resource_aws_ami_from_instance.go index 5a4682dfabe..2dc7dbbfb9c 100644 --- a/aws/resource_aws_ami_from_instance.go +++ b/aws/resource_aws_ami_from_instance.go @@ -6,9 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -169,6 +168,10 @@ func resourceAwsAmiFromInstance() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "arn": { + Type: schema.TypeString, + Computed: true, + }, }, // The remaining operations are shared with the generic aws_ami resource, diff --git a/aws/resource_aws_ami_from_instance_test.go b/aws/resource_aws_ami_from_instance_test.go index 20b245d08c8..32a99503823 100644 --- a/aws/resource_aws_ami_from_instance_test.go +++ b/aws/resource_aws_ami_from_instance_test.go @@ -2,18 +2,19 @@ package aws import ( "fmt" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAMIFromInstance_basic(t *testing.T) { var image ec2.Image - rName := acctest.RandomWithPrefix("tf-acc") + rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_ami_from_instance.test" resource.ParallelTest(t, resource.TestCase{ @@ -25,6 +26,7 @@ func TestAccAWSAMIFromInstance_basic(t *testing.T) { Config: testAccAWSAMIFromInstanceConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAMIFromInstanceExists(resourceName, &image), + testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), resource.TestCheckResourceAttr(resourceName, "description", "Testing Terraform aws_ami_from_instance resource"), ), }, @@ -34,7 +36,7 @@ func TestAccAWSAMIFromInstance_basic(t *testing.T) { func TestAccAWSAMIFromInstance_tags(t *testing.T) { var image ec2.Image - rName := acctest.RandomWithPrefix("tf-acc") + rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_ami_from_instance.test" resource.ParallelTest(t, resource.TestCase{ @@ -127,55 +129,38 @@ func testAccCheckAWSAMIFromInstanceDestroy(s *terraform.State) error { return testAccCheckAWSEbsSnapshotDestroy(s) } -func testAccAWSAMIFromInstanceConfigBase() string { - return fmt.Sprintf(` -data "aws_ec2_instance_type_offering" "available" { - filter { - name = "instance-type" - values = ["t3.micro", "t2.micro"] - } - - preferred_instance_types = ["t3.micro", "t2.micro"] -} - -data "aws_ami" "amzn-ami-minimal-hvm-ebs" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-minimal-hvm-*"] - } - - filter { - name = "root-device-type" - values = ["ebs"] - } -} - +func testAccAWSAMIFromInstanceConfigBase(rName string) string { + return composeConfig( + testAccLatestAmazonLinuxHvmEbsAmiConfig(), + testAccAvailableEc2InstanceTypeForRegion("t3.micro", "t2.micro"), + fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = data.aws_ec2_instance_type_offering.available.instance_type tags = { - Name = "testAccAWSAMIFromInstanceConfig_TestAMI" + Name = %[1]q } } -`) +`, rName)) } func testAccAWSAMIFromInstanceConfig(rName string) string { - return testAccAWSAMIFromInstanceConfigBase() + fmt.Sprintf(` + return composeConfig( + testAccAWSAMIFromInstanceConfigBase(rName), + fmt.Sprintf(` resource "aws_ami_from_instance" "test" { name = %[1]q description = "Testing Terraform aws_ami_from_instance resource" source_instance_id = "${aws_instance.test.id}" } -`, rName) +`, rName)) } func testAccAWSAMIFromInstanceConfigTags1(rName, tagKey1, tagValue1 string) string { - return testAccAWSAMIFromInstanceConfigBase() + fmt.Sprintf(` + return composeConfig( + testAccAWSAMIFromInstanceConfigBase(rName), + fmt.Sprintf(` resource "aws_ami_from_instance" "test" { name = %[1]q description = "Testing Terraform aws_ami_from_instance resource" @@ -185,11 +170,13 @@ resource "aws_ami_from_instance" "test" { %[2]q = %[3]q } } -`, rName, tagKey1, tagValue1) +`, rName, tagKey1, tagValue1)) } func testAccAWSAMIFromInstanceConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { - return testAccAWSAMIFromInstanceConfigBase() + fmt.Sprintf(` + return composeConfig( + testAccAWSAMIFromInstanceConfigBase(rName), + fmt.Sprintf(` resource "aws_ami_from_instance" "test" { name = %[1]q description = "Testing Terraform aws_ami_from_instance resource" @@ -200,5 +187,5 @@ resource "aws_ami_from_instance" "test" { %[4]q = %[5]q } } -`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +`, rName, tagKey1, tagValue1, tagKey2, tagValue2)) } diff --git a/aws/resource_aws_ami_launch_permission.go b/aws/resource_aws_ami_launch_permission.go index af47e3dea0a..43bcd8f21f8 100644 --- a/aws/resource_aws_ami_launch_permission.go +++ b/aws/resource_aws_ami_launch_permission.go @@ -8,7 +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/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsAmiLaunchPermission() *schema.Resource { diff --git a/aws/resource_aws_ami_launch_permission_test.go b/aws/resource_aws_ami_launch_permission_test.go index 4f5da34024d..8f8a80ec48b 100644 --- a/aws/resource_aws_ami_launch_permission_test.go +++ b/aws/resource_aws_ami_launch_permission_test.go @@ -6,12 +6,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAWSAMILaunchPermission_Basic(t *testing.T) { +func TestAccAWSAMILaunchPermission_basic(t *testing.T) { resourceName := "aws_ami_launch_permission.test" rName := acctest.RandomWithPrefix("tf-acc-test") diff --git a/aws/resource_aws_ami_test.go b/aws/resource_aws_ami_test.go index f40ed30281c..3c14a9edb7c 100644 --- a/aws/resource_aws_ami_test.go +++ b/aws/resource_aws_ami_test.go @@ -8,11 +8,10 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAMI_basic(t *testing.T) { @@ -26,12 +25,16 @@ func TestAccAWSAMI_basic(t *testing.T) { CheckDestroy: testAccCheckAmiDestroy, Steps: []resource.TestStep{ { - Config: testAccAmiConfig_basic(rName, 8), + Config: testAccAmiConfigBasic(rName, 8), Check: resource.ComposeTestCheckFunc( testAccCheckAmiExists(resourceName, &ami), resource.TestCheckResourceAttr(resourceName, "ena_support", "true"), resource.TestCheckResourceAttr(resourceName, "name", rName), + testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "ec2", regexp.MustCompile(`image/ami-.+`)), + resource.TestCheckResourceAttr(resourceName, "root_device_name", "/dev/sda1"), + resource.TestCheckResourceAttr(resourceName, "virtualization_type", "hvm"), resource.TestMatchResourceAttr(resourceName, "root_snapshot_id", regexp.MustCompile("^snap-")), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { @@ -46,6 +49,44 @@ func TestAccAWSAMI_basic(t *testing.T) { }) } +func TestAccAWSAMI_description(t *testing.T) { + var ami ec2.Image + resourceName := "aws_ami.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + desc := acctest.RandomWithPrefix("desc") + descUpdated := acctest.RandomWithPrefix("desc-updated") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAmiDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAmiConfigDesc(rName, desc, 8), + Check: resource.ComposeTestCheckFunc( + testAccCheckAmiExists(resourceName, &ami), + resource.TestCheckResourceAttr(resourceName, "description", desc), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "manage_ebs_snapshots", + }, + }, + { + Config: testAccAmiConfigDesc(rName, descUpdated, 8), + Check: resource.ComposeTestCheckFunc( + testAccCheckAmiExists(resourceName, &ami), + resource.TestCheckResourceAttr(resourceName, "description", descUpdated), + ), + }, + }, + }) +} + func TestAccAWSAMI_disappears(t *testing.T) { var ami ec2.Image resourceName := "aws_ami.test" @@ -57,10 +98,10 @@ func TestAccAWSAMI_disappears(t *testing.T) { CheckDestroy: testAccCheckAmiDestroy, Steps: []resource.TestStep{ { - Config: testAccAmiConfig_basic(rName, 8), + Config: testAccAmiConfigBasic(rName, 8), Check: resource.ComposeTestCheckFunc( testAccCheckAmiExists(resourceName, &ami), - testAccCheckAmiDisappears(&ami), + testAccCheckResourceDisappears(testAccProvider, resourceAwsAmi(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -135,7 +176,7 @@ func TestAccAWSAMI_snapshotSize(t *testing.T) { CheckDestroy: testAccCheckAmiDestroy, Steps: []resource.TestStep{ { - Config: testAccAmiConfig_basic(rName, 20), + Config: testAccAmiConfigBasic(rName, 20), Check: resource.ComposeTestCheckFunc( testAccCheckAmiExists(resourceName, &ami), testAccCheckAmiBlockDevice(&ami, &bd, "/dev/sda1"), @@ -186,20 +227,6 @@ func testAccCheckAmiDestroy(s *terraform.State) error { return nil } -func testAccCheckAmiDisappears(image *ec2.Image) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - - input := &ec2.DeregisterImageInput{ - ImageId: image.ImageId, - } - - _, err := conn.DeregisterImage(input) - - return err - } -} - func testAccCheckAmiExists(n string, ami *ec2.Image) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -222,8 +249,7 @@ func testAccCheckAmiExists(n string, ami *ec2.Image) resource.TestCheckFunc { resp, err = conn.DescribeImages(opts) if err != nil { // This can be just eventual consistency - awsErr, ok := err.(awserr.Error) - if ok && awsErr.Code() == "InvalidAMIID.NotFound" { + if isAWSErr(err, "InvalidAMIID.NotFound", "") { return resource.RetryableError(err) } @@ -301,7 +327,7 @@ func testAccCheckAmiEbsBlockDevice(bd *ec2.BlockDeviceMapping, ed *ec2.EbsBlockD } } -func testAccAmiConfig_base(rName string, size int) string { +func testAccAmiConfigBase(rName string, size int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -312,7 +338,7 @@ data "aws_availability_zones" "available" { } } -resource "aws_ebs_volume" "foo" { +resource "aws_ebs_volume" "test" { availability_zone = "${data.aws_availability_zones.available.names[0]}" size = %d @@ -321,8 +347,8 @@ resource "aws_ebs_volume" "foo" { } } -resource "aws_ebs_snapshot" "foo" { - volume_id = "${aws_ebs_volume.foo.id}" +resource "aws_ebs_snapshot" "test" { + volume_id = "${aws_ebs_volume.test.id}" tags = { Name = "%[2]s" @@ -332,8 +358,8 @@ resource "aws_ebs_snapshot" "foo" { `, size, rName) } -func testAccAmiConfig_basic(rName string, size int) string { - return testAccAmiConfig_base(rName, size) + fmt.Sprintf(` +func testAccAmiConfigBasic(rName string, size int) string { + return testAccAmiConfigBase(rName, size) + fmt.Sprintf(` resource "aws_ami" "test" { ena_support = true name = %[1]q @@ -342,14 +368,31 @@ resource "aws_ami" "test" { ebs_block_device { device_name = "/dev/sda1" - snapshot_id = "${aws_ebs_snapshot.foo.id}" + snapshot_id = "${aws_ebs_snapshot.test.id}" } } `, rName) } +func testAccAmiConfigDesc(rName, desc string, size int) string { + return testAccAmiConfigBase(rName, size) + fmt.Sprintf(` +resource "aws_ami" "test" { + ena_support = true + name = %[1]q + root_device_name = "/dev/sda1" + virtualization_type = "hvm" + description = %[2]q + + ebs_block_device { + device_name = "/dev/sda1" + snapshot_id = "${aws_ebs_snapshot.test.id}" + } +} +`, rName, desc) +} + func testAccAmiConfigTags1(rName, tagKey1, tagValue1 string, size int) string { - return testAccAmiConfig_base(rName, size) + fmt.Sprintf(` + return testAccAmiConfigBase(rName, size) + fmt.Sprintf(` resource "aws_ami" "test" { ena_support = true name = %[1]q @@ -358,7 +401,7 @@ resource "aws_ami" "test" { ebs_block_device { device_name = "/dev/sda1" - snapshot_id = "${aws_ebs_snapshot.foo.id}" + snapshot_id = "${aws_ebs_snapshot.test.id}" } tags = { @@ -369,7 +412,7 @@ resource "aws_ami" "test" { } func testAccAmiConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string, size int) string { - return testAccAmiConfig_base(rName, size) + fmt.Sprintf(` + return testAccAmiConfigBase(rName, size) + fmt.Sprintf(` resource "aws_ami" "test" { ena_support = true name = %[1]q @@ -378,7 +421,7 @@ resource "aws_ami" "test" { ebs_block_device { device_name = "/dev/sda1" - snapshot_id = "${aws_ebs_snapshot.foo.id}" + snapshot_id = "${aws_ebs_snapshot.test.id}" } tags = { diff --git a/aws/resource_aws_api_gateway_account.go b/aws/resource_aws_api_gateway_account.go index 4084ed79393..d37b831bf93 100644 --- a/aws/resource_aws_api_gateway_account.go +++ b/aws/resource_aws_api_gateway_account.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsApiGatewayAccount() *schema.Resource { diff --git a/aws/resource_aws_api_gateway_account_test.go b/aws/resource_aws_api_gateway_account_test.go index 443fbda2124..f51dee45ff0 100644 --- a/aws/resource_aws_api_gateway_account_test.go +++ b/aws/resource_aws_api_gateway_account_test.go @@ -6,9 +6,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayAccount_basic(t *testing.T) { diff --git a/aws/resource_aws_api_gateway_api_key.go b/aws/resource_aws_api_gateway_api_key.go index eba07fa80f3..2f710857115 100644 --- a/aws/resource_aws_api_gateway_api_key.go +++ b/aws/resource_aws_api_gateway_api_key.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -42,25 +42,6 @@ func resourceAwsApiGatewayApiKey() *schema.Resource { Default: true, }, - "stage_key": { - Type: schema.TypeSet, - Optional: true, - Removed: "Since the API Gateway usage plans feature was launched on August 11, 2016, usage plans are now required to associate an API key with an API stage", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "rest_api_id": { - Type: schema.TypeString, - Required: true, - }, - - "stage_name": { - Type: schema.TypeString, - Required: true, - }, - }, - }, - }, - "created_date": { Type: schema.TypeString, Computed: true, @@ -164,7 +145,7 @@ func resourceAwsApiGatewayApiKeyUpdateOperations(d *schema.ResourceData) []*apig isEnabled = "true" } operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/enabled"), Value: aws.String(isEnabled), }) @@ -172,7 +153,7 @@ func resourceAwsApiGatewayApiKeyUpdateOperations(d *schema.ResourceData) []*apig if d.HasChange("description") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/description"), Value: aws.String(d.Get("description").(string)), }) diff --git a/aws/resource_aws_api_gateway_api_key_test.go b/aws/resource_aws_api_gateway_api_key_test.go index 89e70439034..cb6856ae1f8 100644 --- a/aws/resource_aws_api_gateway_api_key_test.go +++ b/aws/resource_aws_api_gateway_api_key_test.go @@ -8,9 +8,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayApiKey_basic(t *testing.T) { @@ -183,6 +183,28 @@ func TestAccAWSAPIGatewayApiKey_Value(t *testing.T) { }) } +func TestAccAWSAPIGatewayApiKey_disappears(t *testing.T) { + var apiKey1 apigateway.ApiKey + resourceName := "aws_api_gateway_api_key.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayApiKeyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayApiKeyConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayApiKeyExists(resourceName, &apiKey1), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayApiKey(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAWSAPIGatewayApiKeyExists(n string, res *apigateway.ApiKey) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] diff --git a/aws/resource_aws_api_gateway_authorizer.go b/aws/resource_aws_api_gateway_authorizer.go index b37a6f6bf58..aef14d5540c 100644 --- a/aws/resource_aws_api_gateway_authorizer.go +++ b/aws/resource_aws_api_gateway_authorizer.go @@ -1,15 +1,15 @@ package aws import ( + "context" "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/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) const defaultAuthorizerTTL = 300 @@ -65,8 +65,9 @@ func resourceAwsApiGatewayAuthorizer() *schema.Resource { }, false), }, "authorizer_credentials": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validateArn, }, "authorizer_result_ttl_in_seconds": { Type: schema.TypeInt, @@ -94,10 +95,11 @@ func resourceAwsApiGatewayAuthorizerCreate(d *schema.ResourceData, meta interfac conn := meta.(*AWSClient).apigatewayconn input := apigateway.CreateAuthorizerInput{ - IdentitySource: aws.String(d.Get("identity_source").(string)), - Name: aws.String(d.Get("name").(string)), - RestApiId: aws.String(d.Get("rest_api_id").(string)), - Type: aws.String(d.Get("type").(string)), + IdentitySource: aws.String(d.Get("identity_source").(string)), + Name: aws.String(d.Get("name").(string)), + RestApiId: aws.String(d.Get("rest_api_id").(string)), + Type: aws.String(d.Get("type").(string)), + AuthorizerResultTtlInSeconds: aws.Int64(int64(d.Get("authorizer_result_ttl_in_seconds").(int))), } if err := validateAuthorizerType(d); err != nil { @@ -109,23 +111,21 @@ func resourceAwsApiGatewayAuthorizerCreate(d *schema.ResourceData, meta interfac if v, ok := d.GetOk("authorizer_credentials"); ok { input.AuthorizerCredentials = aws.String(v.(string)) } - if v, ok := d.GetOk("authorizer_result_ttl_in_seconds"); ok { - input.AuthorizerResultTtlInSeconds = aws.Int64(int64(v.(int))) - } + if v, ok := d.GetOk("identity_validation_expression"); ok { input.IdentityValidationExpression = aws.String(v.(string)) } if v, ok := d.GetOk("provider_arns"); ok { - input.ProviderARNs = expandStringList(v.(*schema.Set).List()) + input.ProviderARNs = expandStringSet(v.(*schema.Set)) } log.Printf("[INFO] Creating API Gateway Authorizer: %s", input) out, err := conn.CreateAuthorizer(&input) if err != nil { - return fmt.Errorf("Error creating API Gateway Authorizer: %s", err) + return fmt.Errorf("error creating API Gateway Authorizer: %w", err) } - d.SetId(*out.Id) + d.SetId(aws.StringValue(out.Id)) return resourceAwsApiGatewayAuthorizerRead(d, meta) } @@ -141,7 +141,7 @@ func resourceAwsApiGatewayAuthorizerRead(d *schema.ResourceData, meta interface{ authorizer, err := conn.GetAuthorizer(&input) if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == apigateway.ErrCodeNotFoundException { + if isAWSErr(err, apigateway.ErrCodeNotFoundException, "") { log.Printf("[WARN] No API Gateway Authorizer found: %s", input) d.SetId("") return nil @@ -163,7 +163,7 @@ func resourceAwsApiGatewayAuthorizerRead(d *schema.ResourceData, meta interface{ d.Set("identity_validation_expression", authorizer.IdentityValidationExpression) d.Set("name", authorizer.Name) d.Set("type", authorizer.Type) - d.Set("provider_arns", flattenStringList(authorizer.ProviderARNs)) + d.Set("provider_arns", flattenStringSet(authorizer.ProviderARNs)) return nil } @@ -255,7 +255,7 @@ func resourceAwsApiGatewayAuthorizerUpdate(d *schema.ResourceData, meta interfac log.Printf("[INFO] Updating API Gateway Authorizer: %s", input) _, err := conn.UpdateAuthorizer(&input) if err != nil { - return fmt.Errorf("Updating API Gateway Authorizer failed: %s", err) + return fmt.Errorf("updating API Gateway Authorizer failed: %w", err) } return resourceAwsApiGatewayAuthorizerRead(d, meta) @@ -273,14 +273,14 @@ func resourceAwsApiGatewayAuthorizerDelete(d *schema.ResourceData, meta interfac // XXX: Figure out a way to delete the method that depends on the authorizer first // otherwise the authorizer will be dangling until the API is deleted if !strings.Contains(err.Error(), apigateway.ErrCodeConflictException) { - return fmt.Errorf("Deleting API Gateway Authorizer failed: %s", err) + return fmt.Errorf("deleting API Gateway Authorizer failed: %w", err) } } return nil } -func resourceAwsApiGatewayAuthorizerCustomizeDiff(diff *schema.ResourceDiff, v interface{}) error { +func resourceAwsApiGatewayAuthorizerCustomizeDiff(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { // switch type between COGNITO_USER_POOLS and TOKEN/REQUEST will create new resource. if diff.HasChange("type") { o, n := diff.GetChange("type") @@ -304,7 +304,7 @@ func validateAuthorizerType(d *schema.ResourceData) error { } // provider_arns is required for authorizer COGNITO_USER_POOLS. if authType == apigateway.AuthorizerTypeCognitoUserPools { - if v, ok := d.GetOk("provider_arns"); !ok || len(v.(*schema.Set).List()) == 0 { + if v, ok := d.GetOk("provider_arns"); !ok || v.(*schema.Set).Len() == 0 { return fmt.Errorf("provider_arns must be set non-empty when authorizer type is %s", authType) } } diff --git a/aws/resource_aws_api_gateway_authorizer_test.go b/aws/resource_aws_api_gateway_authorizer_test.go index d4e0b6732d9..9622c68197e 100644 --- a/aws/resource_aws_api_gateway_authorizer_test.go +++ b/aws/resource_aws_api_gateway_authorizer_test.go @@ -3,26 +3,23 @@ package aws import ( "fmt" "regexp" + "strconv" "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayAuthorizer_basic(t *testing.T) { var conf apigateway.Authorizer - apiGatewayName := acctest.RandomWithPrefix("tf-acctest-apigw") - authorizerName := acctest.RandomWithPrefix("tf-acctest-igw-authorizer") - lambdaName := acctest.RandomWithPrefix("tf-acctest-igw-auth-lambda") - resourceName := "aws_api_gateway_authorizer.acctest" - - expectedAuthUri := regexp.MustCompile("arn:aws:apigateway:[a-z0-9-]+:lambda:path/2015-03-31/functions/" + - "arn:aws:lambda:[a-z0-9-]+:[0-9]{12}:function:" + lambdaName + "/invocations") - expectedCreds := regexp.MustCompile("arn:aws:iam::[0-9]{12}:role/" + apiGatewayName + "_auth_invocation_role") + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_api_gateway_authorizer.test" + lambdaResourceName := "aws_lambda_function.test" + roleResourceName := "aws_iam_role.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -30,22 +27,15 @@ func TestAccAWSAPIGatewayAuthorizer_basic(t *testing.T) { CheckDestroy: testAccCheckAWSAPIGatewayAuthorizerDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayAuthorizerConfig_lambda(apiGatewayName, authorizerName, lambdaName), + Config: testAccAWSAPIGatewayAuthorizerConfig_lambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayAuthorizerExists(resourceName, &conf), - testAccCheckAWSAPIGatewayAuthorizerAuthorizerUri(&conf, expectedAuthUri), - resource.TestMatchResourceAttr(resourceName, "authorizer_uri", expectedAuthUri), - testAccCheckAWSAPIGatewayAuthorizerIdentitySource(&conf, "method.request.header.Authorization"), + resource.TestCheckResourceAttrPair(resourceName, "authorizer_uri", lambdaResourceName, "invoke_arn"), resource.TestCheckResourceAttr(resourceName, "identity_source", "method.request.header.Authorization"), - testAccCheckAWSAPIGatewayAuthorizerName(&conf, authorizerName), - resource.TestCheckResourceAttr(resourceName, "name", authorizerName), - testAccCheckAWSAPIGatewayAuthorizerType(&conf, "TOKEN"), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "type", "TOKEN"), - testAccCheckAWSAPIGatewayAuthorizerAuthorizerCredentials(&conf, expectedCreds), - resource.TestMatchResourceAttr(resourceName, "authorizer_credentials", expectedCreds), - testAccCheckAWSAPIGatewayAuthorizerAuthorizerResultTtlInSeconds(&conf, aws.Int64(defaultAuthorizerTTL)), - resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", "300"), - testAccCheckAWSAPIGatewayAuthorizerIdentityValidationExpression(&conf, nil), + resource.TestCheckResourceAttrPair(resourceName, "authorizer_credentials", roleResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", strconv.Itoa(defaultAuthorizerTTL)), resource.TestCheckResourceAttr(resourceName, "identity_validation_expression", ""), ), }, @@ -56,22 +46,15 @@ func TestAccAWSAPIGatewayAuthorizer_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSAPIGatewayAuthorizerConfig_lambdaUpdate(apiGatewayName, authorizerName, lambdaName), + Config: testAccAWSAPIGatewayAuthorizerConfig_lambdaUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayAuthorizerExists(resourceName, &conf), - testAccCheckAWSAPIGatewayAuthorizerAuthorizerUri(&conf, expectedAuthUri), - resource.TestMatchResourceAttr(resourceName, "authorizer_uri", expectedAuthUri), - testAccCheckAWSAPIGatewayAuthorizerIdentitySource(&conf, "method.request.header.Authorization"), + resource.TestCheckResourceAttrPair(resourceName, "authorizer_uri", lambdaResourceName, "invoke_arn"), resource.TestCheckResourceAttr(resourceName, "identity_source", "method.request.header.Authorization"), - testAccCheckAWSAPIGatewayAuthorizerName(&conf, authorizerName+"_modified"), - resource.TestCheckResourceAttr(resourceName, "name", authorizerName+"_modified"), - testAccCheckAWSAPIGatewayAuthorizerType(&conf, "TOKEN"), + resource.TestCheckResourceAttr(resourceName, "name", rName+"_modified"), resource.TestCheckResourceAttr(resourceName, "type", "TOKEN"), - testAccCheckAWSAPIGatewayAuthorizerAuthorizerCredentials(&conf, expectedCreds), - resource.TestMatchResourceAttr(resourceName, "authorizer_credentials", expectedCreds), - testAccCheckAWSAPIGatewayAuthorizerAuthorizerResultTtlInSeconds(&conf, aws.Int64(360)), - resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", "360"), - testAccCheckAWSAPIGatewayAuthorizerIdentityValidationExpression(&conf, aws.String(".*")), + resource.TestCheckResourceAttrPair(resourceName, "authorizer_credentials", roleResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", strconv.Itoa(360)), resource.TestCheckResourceAttr(resourceName, "identity_validation_expression", ".*"), ), }, @@ -80,10 +63,8 @@ func TestAccAWSAPIGatewayAuthorizer_basic(t *testing.T) { } func TestAccAWSAPIGatewayAuthorizer_cognito(t *testing.T) { - apiGatewayName := acctest.RandomWithPrefix("tf-acctest-apigw") - authorizerName := acctest.RandomWithPrefix("tf-acctest-igw-authorizer") - cognitoName := acctest.RandomWithPrefix("tf-acctest-cognito-user-pool") - resourceName := "aws_api_gateway_authorizer.acctest" + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_api_gateway_authorizer.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -91,9 +72,10 @@ func TestAccAWSAPIGatewayAuthorizer_cognito(t *testing.T) { CheckDestroy: testAccCheckAWSAPIGatewayAuthorizerDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayAuthorizerConfig_cognito(apiGatewayName, authorizerName, cognitoName), + Config: testAccAWSAPIGatewayAuthorizerConfig_cognito(rName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "name", authorizerName+"-cognito"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "type", "COGNITO_USER_POOLS"), resource.TestCheckResourceAttr(resourceName, "provider_arns.#", "2"), ), }, @@ -104,9 +86,10 @@ func TestAccAWSAPIGatewayAuthorizer_cognito(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSAPIGatewayAuthorizerConfig_cognitoUpdate(apiGatewayName, authorizerName, cognitoName), + Config: testAccAWSAPIGatewayAuthorizerConfig_cognitoUpdate(rName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "name", authorizerName+"-cognito-update"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "type", "COGNITO_USER_POOLS"), resource.TestCheckResourceAttr(resourceName, "provider_arns.#", "3"), ), }, @@ -115,15 +98,10 @@ func TestAccAWSAPIGatewayAuthorizer_cognito(t *testing.T) { } func TestAccAWSAPIGatewayAuthorizer_switchAuthType(t *testing.T) { - apiGatewayName := acctest.RandomWithPrefix("tf-acctest-apigw") - authorizerName := acctest.RandomWithPrefix("tf-acctest-igw-authorizer") - lambdaName := acctest.RandomWithPrefix("tf-acctest-igw-auth-lambda") - cognitoName := acctest.RandomWithPrefix("tf-acctest-cognito-user-pool") - resourceName := "aws_api_gateway_authorizer.acctest" - - expectedAuthUri := regexp.MustCompile("arn:aws:apigateway:[a-z0-9-]+:lambda:path/2015-03-31/functions/" + - "arn:aws:lambda:[a-z0-9-]+:[0-9]{12}:function:" + lambdaName + "/invocations") - expectedCreds := regexp.MustCompile("arn:aws:iam::[0-9]{12}:role/" + apiGatewayName + "_auth_invocation_role") + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_api_gateway_authorizer.test" + lambdaResourceName := "aws_lambda_function.test" + roleResourceName := "aws_iam_role.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -131,12 +109,12 @@ func TestAccAWSAPIGatewayAuthorizer_switchAuthType(t *testing.T) { CheckDestroy: testAccCheckAWSAPIGatewayAuthorizerDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayAuthorizerConfig_lambda(apiGatewayName, authorizerName, lambdaName), + Config: testAccAWSAPIGatewayAuthorizerConfig_lambda(rName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "name", authorizerName), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "type", "TOKEN"), - resource.TestMatchResourceAttr(resourceName, "authorizer_uri", expectedAuthUri), - resource.TestMatchResourceAttr(resourceName, "authorizer_credentials", expectedCreds), + resource.TestCheckResourceAttrPair(resourceName, "authorizer_uri", lambdaResourceName, "invoke_arn"), + resource.TestCheckResourceAttrPair(resourceName, "authorizer_credentials", roleResourceName, "arn"), ), }, { @@ -146,20 +124,20 @@ func TestAccAWSAPIGatewayAuthorizer_switchAuthType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSAPIGatewayAuthorizerConfig_cognito(apiGatewayName, authorizerName, cognitoName), + Config: testAccAWSAPIGatewayAuthorizerConfig_cognito(rName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "name", authorizerName+"-cognito"), + resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "type", "COGNITO_USER_POOLS"), resource.TestCheckResourceAttr(resourceName, "provider_arns.#", "2"), ), }, { - Config: testAccAWSAPIGatewayAuthorizerConfig_lambdaUpdate(apiGatewayName, authorizerName, lambdaName), + Config: testAccAWSAPIGatewayAuthorizerConfig_lambdaUpdate(rName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "name", authorizerName+"_modified"), + resource.TestCheckResourceAttr(resourceName, "name", rName+"_modified"), resource.TestCheckResourceAttr(resourceName, "type", "TOKEN"), - resource.TestMatchResourceAttr(resourceName, "authorizer_uri", expectedAuthUri), - resource.TestMatchResourceAttr(resourceName, "authorizer_credentials", expectedCreds), + resource.TestCheckResourceAttrPair(resourceName, "authorizer_uri", lambdaResourceName, "invoke_arn"), + resource.TestCheckResourceAttrPair(resourceName, "authorizer_credentials", roleResourceName, "arn"), ), }, }, @@ -168,10 +146,8 @@ func TestAccAWSAPIGatewayAuthorizer_switchAuthType(t *testing.T) { func TestAccAWSAPIGatewayAuthorizer_switchAuthorizerTTL(t *testing.T) { var conf apigateway.Authorizer - apiGatewayName := acctest.RandomWithPrefix("tf-acctest-apigw") - authorizerName := acctest.RandomWithPrefix("tf-acctest-igw-authorizer") - lambdaName := acctest.RandomWithPrefix("tf-acctest-igw-auth-lambda") - resourceName := "aws_api_gateway_authorizer.acctest" + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_api_gateway_authorizer.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -179,11 +155,10 @@ func TestAccAWSAPIGatewayAuthorizer_switchAuthorizerTTL(t *testing.T) { CheckDestroy: testAccCheckAWSAPIGatewayAuthorizerDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayAuthorizerConfig_lambda(apiGatewayName, authorizerName, lambdaName), + Config: testAccAWSAPIGatewayAuthorizerConfig_lambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayAuthorizerExists(resourceName, &conf), - testAccCheckAWSAPIGatewayAuthorizerAuthorizerResultTtlInSeconds(&conf, aws.Int64(defaultAuthorizerTTL)), - resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", "300"), + resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", strconv.Itoa(defaultAuthorizerTTL)), ), }, { @@ -193,27 +168,24 @@ func TestAccAWSAPIGatewayAuthorizer_switchAuthorizerTTL(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSAPIGatewayAuthorizerConfig_lambdaUpdate(apiGatewayName, authorizerName, lambdaName), + Config: testAccAWSAPIGatewayAuthorizerConfig_lambdaUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayAuthorizerExists(resourceName, &conf), - testAccCheckAWSAPIGatewayAuthorizerAuthorizerResultTtlInSeconds(&conf, aws.Int64(360)), - resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", "360"), + resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", strconv.Itoa(360)), ), }, { - Config: testAccAWSAPIGatewayAuthorizerConfig_lambdaNoCache(apiGatewayName, authorizerName, lambdaName), + Config: testAccAWSAPIGatewayAuthorizerConfig_lambdaNoCache(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayAuthorizerExists(resourceName, &conf), - resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", "0"), - testAccCheckAWSAPIGatewayAuthorizerAuthorizerResultTtlInSeconds(&conf, aws.Int64(0)), + resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", strconv.Itoa(0)), ), }, { - Config: testAccAWSAPIGatewayAuthorizerConfig_lambda(apiGatewayName, authorizerName, lambdaName), + Config: testAccAWSAPIGatewayAuthorizerConfig_lambda(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayAuthorizerExists(resourceName, &conf), - testAccCheckAWSAPIGatewayAuthorizerAuthorizerResultTtlInSeconds(&conf, aws.Int64(defaultAuthorizerTTL)), - resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", "300"), + resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", strconv.Itoa(defaultAuthorizerTTL)), ), }, }, @@ -221,10 +193,7 @@ func TestAccAWSAPIGatewayAuthorizer_switchAuthorizerTTL(t *testing.T) { } func TestAccAWSAPIGatewayAuthorizer_authTypeValidation(t *testing.T) { - apiGatewayName := acctest.RandomWithPrefix("tf-acctest-apigw") - authorizerName := acctest.RandomWithPrefix("tf-acctest-igw-authorizer") - lambdaName := acctest.RandomWithPrefix("tf-acctest-igw-auth-lambda") - cognitoName := acctest.RandomWithPrefix("tf-acctest-cognito-user-pool") + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -232,27 +201,25 @@ func TestAccAWSAPIGatewayAuthorizer_authTypeValidation(t *testing.T) { CheckDestroy: testAccCheckAWSAPIGatewayAuthorizerDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayAuthorizerConfig_authTypeValidationDefaultToken(apiGatewayName, authorizerName, lambdaName), + Config: testAccAWSAPIGatewayAuthorizerConfig_authTypeValidationDefaultToken(rName), ExpectError: regexp.MustCompile(`authorizer_uri must be set non-empty when authorizer type is TOKEN`), }, { - Config: testAccAWSAPIGatewayAuthorizerConfig_authTypeValidationRequest(apiGatewayName, authorizerName, lambdaName), + Config: testAccAWSAPIGatewayAuthorizerConfig_authTypeValidationRequest(rName), ExpectError: regexp.MustCompile(`authorizer_uri must be set non-empty when authorizer type is REQUEST`), }, { - Config: testAccAWSAPIGatewayAuthorizerConfig_authTypeValidationCognito(apiGatewayName, authorizerName, cognitoName), + Config: testAccAWSAPIGatewayAuthorizerConfig_authTypeValidationCognito(rName), ExpectError: regexp.MustCompile(`provider_arns must be set non-empty when authorizer type is COGNITO_USER_POOLS`), }, }, }) } -func TestAccAWSAPIGatewayAuthorizer_disappears(t *testing.T) { +func TestAccAWSAPIGatewayAuthorizer_zero_ttl(t *testing.T) { var conf apigateway.Authorizer - apiGatewayName := acctest.RandomWithPrefix("tf-acctest-apigw") - authorizerName := acctest.RandomWithPrefix("tf-acctest-igw-authorizer") - lambdaName := acctest.RandomWithPrefix("tf-acctest-igw-auth-lambda") - resourceName := "aws_api_gateway_authorizer.acctest" + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_api_gateway_authorizer.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -260,139 +227,42 @@ func TestAccAWSAPIGatewayAuthorizer_disappears(t *testing.T) { CheckDestroy: testAccCheckAWSAPIGatewayAuthorizerDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayAuthorizerConfig_lambda(apiGatewayName, authorizerName, lambdaName), + Config: testAccAWSAPIGatewayAuthorizerConfig_lambdaNoCache(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayAuthorizerExists(resourceName, &conf), - testAccCheckAWSAPIGatewayAuthorizerDisappears(resourceName), + resource.TestCheckResourceAttr(resourceName, "authorizer_result_ttl_in_seconds", "0"), ), - ExpectNonEmptyPlan: true, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayAuthorizerImportStateIdFunc(resourceName), + ImportStateVerify: true, }, }, }) } -func testAccCheckAWSAPIGatewayAuthorizerDisappears(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No resource ID is set") - } - conn := testAccProvider.Meta().(*AWSClient).apigatewayconn - authorizerId := rs.Primary.ID - restApiId := rs.Primary.Attributes["rest_api_id"] - - input := &apigateway.DeleteAuthorizerInput{ - AuthorizerId: aws.String(authorizerId), - RestApiId: aws.String(restApiId), - } - _, err := conn.DeleteAuthorizer(input) - - return err - } -} - -func testAccCheckAWSAPIGatewayAuthorizerAuthorizerUri(conf *apigateway.Authorizer, expectedUri *regexp.Regexp) resource.TestCheckFunc { - return func(s *terraform.State) error { - if conf.AuthorizerUri == nil { - return fmt.Errorf("Empty AuthorizerUri, expected: %q", expectedUri) - } - - if !expectedUri.MatchString(*conf.AuthorizerUri) { - return fmt.Errorf("AuthorizerUri didn't match. Expected: %q, Given: %q", expectedUri, *conf.AuthorizerUri) - } - return nil - } -} - -func testAccCheckAWSAPIGatewayAuthorizerIdentitySource(conf *apigateway.Authorizer, expectedSource string) resource.TestCheckFunc { - return func(s *terraform.State) error { - if conf.IdentitySource == nil { - return fmt.Errorf("Empty IdentitySource, expected: %q", expectedSource) - } - if *conf.IdentitySource != expectedSource { - return fmt.Errorf("IdentitySource didn't match. Expected: %q, Given: %q", expectedSource, *conf.IdentitySource) - } - return nil - } -} - -func testAccCheckAWSAPIGatewayAuthorizerName(conf *apigateway.Authorizer, expectedName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - if conf.Name == nil { - return fmt.Errorf("Empty Name, expected: %q", expectedName) - } - if *conf.Name != expectedName { - return fmt.Errorf("Name didn't match. Expected: %q, Given: %q", expectedName, *conf.Name) - } - return nil - } -} - -func testAccCheckAWSAPIGatewayAuthorizerType(conf *apigateway.Authorizer, expectedType string) resource.TestCheckFunc { - return func(s *terraform.State) error { - if conf.Type == nil { - return fmt.Errorf("Empty Type, expected: %q", expectedType) - } - if *conf.Type != expectedType { - return fmt.Errorf("Type didn't match. Expected: %q, Given: %q", expectedType, *conf.Type) - } - return nil - } -} - -func testAccCheckAWSAPIGatewayAuthorizerAuthorizerCredentials(conf *apigateway.Authorizer, expectedCreds *regexp.Regexp) resource.TestCheckFunc { - return func(s *terraform.State) error { - if conf.AuthorizerCredentials == nil { - return fmt.Errorf("Empty AuthorizerCredentials, expected: %q", expectedCreds) - } - if !expectedCreds.MatchString(*conf.AuthorizerCredentials) { - return fmt.Errorf("AuthorizerCredentials didn't match. Expected: %q, Given: %q", - expectedCreds, *conf.AuthorizerCredentials) - } - return nil - } -} - -func testAccCheckAWSAPIGatewayAuthorizerAuthorizerResultTtlInSeconds(conf *apigateway.Authorizer, expectedTtl *int64) resource.TestCheckFunc { - return func(s *terraform.State) error { - if expectedTtl == conf.AuthorizerResultTtlInSeconds { - return nil - } - if expectedTtl == nil && conf.AuthorizerResultTtlInSeconds != nil { - return fmt.Errorf("Expected empty AuthorizerResultTtlInSeconds, given: %d", *conf.AuthorizerResultTtlInSeconds) - } - if conf.AuthorizerResultTtlInSeconds == nil { - return fmt.Errorf("Empty AuthorizerResultTtlInSeconds, expected: %d", expectedTtl) - } - if *conf.AuthorizerResultTtlInSeconds != *expectedTtl { - return fmt.Errorf("AuthorizerResultTtlInSeconds didn't match. Expected: %d, Given: %d", - *expectedTtl, *conf.AuthorizerResultTtlInSeconds) - } - return nil - } -} +func TestAccAWSAPIGatewayAuthorizer_disappears(t *testing.T) { + var conf apigateway.Authorizer + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_api_gateway_authorizer.test" -func testAccCheckAWSAPIGatewayAuthorizerIdentityValidationExpression(conf *apigateway.Authorizer, expectedExpression *string) resource.TestCheckFunc { - return func(s *terraform.State) error { - if expectedExpression == conf.IdentityValidationExpression { - return nil - } - if expectedExpression == nil && conf.IdentityValidationExpression != nil { - return fmt.Errorf("Expected empty IdentityValidationExpression, given: %q", *conf.IdentityValidationExpression) - } - if conf.IdentityValidationExpression == nil { - return fmt.Errorf("Empty IdentityValidationExpression, expected: %q", *expectedExpression) - } - if *conf.IdentityValidationExpression != *expectedExpression { - return fmt.Errorf("IdentityValidationExpression didn't match. Expected: %q, Given: %q", - *expectedExpression, *conf.IdentityValidationExpression) - } - return nil - } + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayAuthorizerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayAuthorizerConfig_lambda(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayAuthorizerExists(resourceName, &conf), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayAuthorizer(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) } func testAccCheckAWSAPIGatewayAuthorizerExists(n string, res *apigateway.Authorizer) resource.TestCheckFunc { @@ -466,14 +336,14 @@ func testAccAWSAPIGatewayAuthorizerImportStateIdFunc(resourceName string) resour } } -func testAccAWSAPIGatewayAuthorizerConfig_baseLambda(apiGatewayName, lambdaName string) string { +func testAccAWSAPIGatewayAuthorizerConfigBase(rName string) string { return fmt.Sprintf(` -resource "aws_api_gateway_rest_api" "acctest" { - name = "%s" +resource "aws_api_gateway_rest_api" "test" { + name = %[1]q } -resource "aws_iam_role" "invocation_role" { - name = "%s_auth_invocation_role" +resource "aws_iam_role" "test" { + name = %[1]q path = "/" assume_role_policy = <Foo"), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "timeout_milliseconds", "2000"), + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), + resource.TestCheckResourceAttr(resourceName, "integration_http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "uri", "https://www.google.de"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr(resourceName, "content_handling", "CONVERT_TO_TEXT"), + resource.TestCheckResourceAttr(resourceName, "credentials", ""), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Authorization", "'updated'"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-FooBar", "'Baz'"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/json", "{'foobar': 'bar}"), + resource.TestCheckResourceAttr(resourceName, "request_templates.text/html", "Foo"), + resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "2000"), ), }, { Config: testAccAWSAPIGatewayIntegrationConfigUpdateURI(rName), 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/updated"), - 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.TestCheckResourceAttr("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.TestCheckResourceAttr("aws_api_gateway_integration.test", "timeout_milliseconds", "2000"), + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), + resource.TestCheckResourceAttr(resourceName, "integration_http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "uri", "https://www.google.de/updated"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr(resourceName, "content_handling", "CONVERT_TO_TEXT"), + resource.TestCheckResourceAttr(resourceName, "credentials", ""), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Authorization", "'static'"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Foo", "'Bar'"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/json", ""), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/xml", "#set($inputRoot = $input.path('$'))\n{ }"), + resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "2000"), ), }, { Config: testAccAWSAPIGatewayIntegrationConfigUpdateNoTemplates(rName), 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.TestCheckResourceAttr("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"), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "timeout_milliseconds", "2000"), + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), + resource.TestCheckResourceAttr(resourceName, "integration_http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "uri", "https://www.google.de"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr(resourceName, "content_handling", "CONVERT_TO_TEXT"), + resource.TestCheckResourceAttr(resourceName, "credentials", ""), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "0"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "0"), + resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "2000"), ), }, { Config: testAccAWSAPIGatewayIntegrationConfig(rName), 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.TestCheckResourceAttr("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{ }"), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "timeout_milliseconds", "29000"), + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), + resource.TestCheckResourceAttr(resourceName, "integration_http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "uri", "https://www.google.de"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr(resourceName, "content_handling", "CONVERT_TO_TEXT"), + resource.TestCheckResourceAttr(resourceName, "credentials", ""), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Authorization", "'static'"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/json", ""), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/xml", "#set($inputRoot = $input.path('$'))\n{ }"), + resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "29000"), ), }, { - ResourceName: "aws_api_gateway_integration.test", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSAPIGatewayIntegrationImportStateIdFunc("aws_api_gateway_integration.test"), + ImportStateIdFunc: testAccAWSAPIGatewayIntegrationImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -129,6 +131,7 @@ func TestAccAWSAPIGatewayIntegration_basic(t *testing.T) { func TestAccAWSAPIGatewayIntegration_contentHandling(t *testing.T) { var conf apigateway.Integration rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(7)) + resourceName := "aws_api_gateway_integration.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -138,62 +141,62 @@ func TestAccAWSAPIGatewayIntegration_contentHandling(t *testing.T) { { Config: testAccAWSAPIGatewayIntegrationConfig(rName), 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.TestCheckResourceAttr("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{ }"), + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), + resource.TestCheckResourceAttr(resourceName, "integration_http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "uri", "https://www.google.de"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr(resourceName, "content_handling", "CONVERT_TO_TEXT"), + resource.TestCheckResourceAttr(resourceName, "credentials", ""), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Authorization", "'static'"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Foo", "'Bar'"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/json", ""), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/xml", "#set($inputRoot = $input.path('$'))\n{ }"), ), }, { Config: testAccAWSAPIGatewayIntegrationConfigUpdateContentHandling(rName), 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_BINARY"), - resource.TestCheckResourceAttr("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{ }"), + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), + resource.TestCheckResourceAttr(resourceName, "integration_http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "uri", "https://www.google.de"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr(resourceName, "content_handling", "CONVERT_TO_BINARY"), + resource.TestCheckResourceAttr(resourceName, "credentials", ""), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Authorization", "'static'"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Foo", "'Bar'"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/json", ""), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/xml", "#set($inputRoot = $input.path('$'))\n{ }"), ), }, { Config: testAccAWSAPIGatewayIntegrationConfigRemoveContentHandling(rName), 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", ""), - resource.TestCheckResourceAttr("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{ }"), + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), + resource.TestCheckResourceAttr(resourceName, "integration_http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "uri", "https://www.google.de"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr(resourceName, "content_handling", ""), + resource.TestCheckResourceAttr(resourceName, "credentials", ""), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Authorization", "'static'"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Foo", "'Bar'"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/json", ""), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/xml", "#set($inputRoot = $input.path('$'))\n{ }"), ), }, { - ResourceName: "aws_api_gateway_integration.test", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSAPIGatewayIntegrationImportStateIdFunc("aws_api_gateway_integration.test"), + ImportStateIdFunc: testAccAWSAPIGatewayIntegrationImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -203,39 +206,39 @@ func TestAccAWSAPIGatewayIntegration_contentHandling(t *testing.T) { func TestAccAWSAPIGatewayIntegration_cache_key_parameters(t *testing.T) { var conf apigateway.Integration rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(7)) + resourceName := "aws_api_gateway_integration.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAPIGatewayIntegrationDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayIntegrationDestroy, Steps: []resource.TestStep{ { Config: testAccAWSAPIGatewayIntegrationConfigCacheKeyParameters(rName), 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.TestCheckResourceAttr("aws_api_gateway_integration.test", "credentials", ""), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "request_parameters.%", "3"), - 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_parameters.integration.request.path.param", "method.request.path.param"), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "cache_key_parameters.#", "1"), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "cache_key_parameters.550492954", "method.request.path.param"), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "cache_namespace", "foobar"), - 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{ }"), + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "type", "HTTP"), + resource.TestCheckResourceAttr(resourceName, "integration_http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "uri", "https://www.google.de"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_MATCH"), + resource.TestCheckResourceAttr(resourceName, "content_handling", "CONVERT_TO_TEXT"), + resource.TestCheckResourceAttr(resourceName, "credentials", ""), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "3"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Authorization", "'static'"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.X-Foo", "'Bar'"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.path.param", "method.request.path.param"), + resource.TestCheckResourceAttr(resourceName, "cache_key_parameters.#", "1"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "cache_key_parameters.*", "method.request.path.param"), + resource.TestCheckResourceAttr(resourceName, "cache_namespace", "foobar"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/json", ""), + resource.TestCheckResourceAttr(resourceName, "request_templates.application/xml", "#set($inputRoot = $input.path('$'))\n{ }"), ), }, { - ResourceName: "aws_api_gateway_integration.test", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSAPIGatewayIntegrationImportStateIdFunc("aws_api_gateway_integration.test"), + ImportStateIdFunc: testAccAWSAPIGatewayIntegrationImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -245,6 +248,7 @@ func TestAccAWSAPIGatewayIntegration_cache_key_parameters(t *testing.T) { func TestAccAWSAPIGatewayIntegration_integrationType(t *testing.T) { var conf apigateway.Integration rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(7)) + resourceName := "aws_api_gateway_integration.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -254,37 +258,59 @@ func TestAccAWSAPIGatewayIntegration_integrationType(t *testing.T) { { Config: testAccAWSAPIGatewayIntegrationConfig_IntegrationTypeInternet(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAPIGatewayIntegrationExists("aws_api_gateway_integration.test", &conf), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "connection_type", "INTERNET"), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "connection_id", ""), + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "connection_type", "INTERNET"), + resource.TestCheckResourceAttr(resourceName, "connection_id", ""), ), }, { Config: testAccAWSAPIGatewayIntegrationConfig_IntegrationTypeVpcLink(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAPIGatewayIntegrationExists("aws_api_gateway_integration.test", &conf), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "connection_type", "VPC_LINK"), - resource.TestMatchResourceAttr("aws_api_gateway_integration.test", "connection_id", regexp.MustCompile("^[0-9a-z]+$")), + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "connection_type", "VPC_LINK"), + resource.TestMatchResourceAttr(resourceName, "connection_id", regexp.MustCompile("^[0-9a-z]+$")), ), }, { Config: testAccAWSAPIGatewayIntegrationConfig_IntegrationTypeInternet(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAPIGatewayIntegrationExists("aws_api_gateway_integration.test", &conf), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "connection_type", "INTERNET"), - resource.TestCheckResourceAttr("aws_api_gateway_integration.test", "connection_id", ""), + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "connection_type", "INTERNET"), + resource.TestCheckResourceAttr(resourceName, "connection_id", ""), ), }, { - ResourceName: "aws_api_gateway_integration.test", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSAPIGatewayIntegrationImportStateIdFunc("aws_api_gateway_integration.test"), + ImportStateIdFunc: testAccAWSAPIGatewayIntegrationImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, }) } +func TestAccAWSAPIGatewayIntegration_disappears(t *testing.T) { + var conf apigateway.Integration + rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(7)) + resourceName := "aws_api_gateway_integration.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayIntegrationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayIntegrationConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayIntegrationExists(resourceName, &conf), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayIntegration(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAWSAPIGatewayIntegrationExists(n string, res *apigateway.Integration) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -755,7 +781,7 @@ resource "aws_api_gateway_vpc_link" "test" { } func testAccAWSAPIGatewayIntegrationConfig_IntegrationTypeVpcLink(rName string) string { - return testAccAWSAPIGatewayIntegrationConfig_IntegrationTypeBase(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayIntegrationConfig_IntegrationTypeBase(rName) + ` resource "aws_api_gateway_integration" "test" { rest_api_id = "${aws_api_gateway_rest_api.test.id}" resource_id = "${aws_api_gateway_resource.test.id}" @@ -770,11 +796,11 @@ resource "aws_api_gateway_integration" "test" { connection_type = "VPC_LINK" connection_id = "${aws_api_gateway_vpc_link.test.id}" } -`) +` } func testAccAWSAPIGatewayIntegrationConfig_IntegrationTypeInternet(rName string) string { - return testAccAWSAPIGatewayIntegrationConfig_IntegrationTypeBase(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayIntegrationConfig_IntegrationTypeBase(rName) + ` resource "aws_api_gateway_integration" "test" { rest_api_id = "${aws_api_gateway_rest_api.test.id}" resource_id = "${aws_api_gateway_resource.test.id}" @@ -786,5 +812,5 @@ resource "aws_api_gateway_integration" "test" { passthrough_behavior = "WHEN_NO_MATCH" content_handling = "CONVERT_TO_TEXT" } -`) +` } diff --git a/aws/resource_aws_api_gateway_method.go b/aws/resource_aws_api_gateway_method.go index a8efcafa52b..d989da46595 100644 --- a/aws/resource_aws_api_gateway_method.go +++ b/aws/resource_aws_api_gateway_method.go @@ -7,9 +7,8 @@ import ( "strings" "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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsApiGatewayMethod() *schema.Resource { @@ -90,12 +89,6 @@ func resourceAwsApiGatewayMethod() *schema.Resource { Optional: true, }, - "request_parameters_in_json": { - Type: schema.TypeString, - Optional: true, - Removed: "Use `request_parameters` argument instead", - }, - "request_validator_id": { Type: schema.TypeString, Optional: true, @@ -168,7 +161,7 @@ func resourceAwsApiGatewayMethodRead(d *schema.ResourceData, meta interface{}) e RestApiId: aws.String(d.Get("rest_api_id").(string)), }) if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NotFoundException" { + if isAWSErr(err, apigateway.ErrCodeNotFoundException, "") { log.Printf("[WARN] API Gateway Method (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -206,7 +199,7 @@ func resourceAwsApiGatewayMethodUpdate(d *schema.ResourceData, meta interface{}) operations := make([]*apigateway.PatchOperation, 0) if d.HasChange("resource_id") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/resourceId"), Value: aws.String(d.Get("resource_id").(string)), }) @@ -216,14 +209,6 @@ func resourceAwsApiGatewayMethodUpdate(d *schema.ResourceData, meta interface{}) operations = append(operations, expandApiGatewayRequestResponseModelOperations(d, "request_models", "requestModels")...) } - if d.HasChange("request_parameters_in_json") { - ops, err := deprecatedExpandApiGatewayMethodParametersJSONOperations(d, "request_parameters_in_json", "requestParameters") - if err != nil { - return err - } - operations = append(operations, ops...) - } - if d.HasChange("request_parameters") { parameters := make(map[string]bool) var ok bool @@ -234,16 +219,13 @@ func resourceAwsApiGatewayMethodUpdate(d *schema.ResourceData, meta interface{}) parameters[k] = value } } - ops, err := expandApiGatewayMethodParametersOperations(d, "request_parameters", "requestParameters") - if err != nil { - return err - } + ops := expandApiGatewayMethodParametersOperations(d, "request_parameters", "requestParameters") operations = append(operations, ops...) } if d.HasChange("authorization") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/authorizationType"), Value: aws.String(d.Get("authorization").(string)), }) @@ -251,7 +233,7 @@ func resourceAwsApiGatewayMethodUpdate(d *schema.ResourceData, meta interface{}) if d.HasChange("authorizer_id") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/authorizerId"), Value: aws.String(d.Get("authorizer_id").(string)), }) @@ -267,7 +249,7 @@ func resourceAwsApiGatewayMethodUpdate(d *schema.ResourceData, meta interface{}) additionList := ns.Difference(os) for _, v := range additionList.List() { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("add"), + Op: aws.String(apigateway.OpAdd), Path: aws.String(path), Value: aws.String(v.(string)), }) @@ -276,7 +258,7 @@ func resourceAwsApiGatewayMethodUpdate(d *schema.ResourceData, meta interface{}) removalList := os.Difference(ns) for _, v := range removalList.List() { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("remove"), + Op: aws.String(apigateway.OpRemove), Path: aws.String(path), Value: aws.String(v.(string)), }) @@ -285,7 +267,7 @@ func resourceAwsApiGatewayMethodUpdate(d *schema.ResourceData, meta interface{}) if d.HasChange("api_key_required") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/apiKeyRequired"), Value: aws.String(fmt.Sprintf("%t", d.Get("api_key_required").(bool))), }) @@ -301,7 +283,7 @@ func resourceAwsApiGatewayMethodUpdate(d *schema.ResourceData, meta interface{}) } } operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/requestValidatorId"), Value: request_validator_id, }) diff --git a/aws/resource_aws_api_gateway_method_response.go b/aws/resource_aws_api_gateway_method_response.go index 39239eb03ec..419a047d719 100644 --- a/aws/resource_aws_api_gateway_method_response.go +++ b/aws/resource_aws_api_gateway_method_response.go @@ -8,9 +8,8 @@ import ( "sync" "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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) var resourceAwsApiGatewayMethodResponseMutex = &sync.Mutex{} @@ -76,12 +75,6 @@ func resourceAwsApiGatewayMethodResponse() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeBool}, Optional: true, }, - - "response_parameters_in_json": { - Type: schema.TypeString, - Optional: true, - Removed: "Use `response_parameters` argument instead", - }, }, } } @@ -140,7 +133,7 @@ func resourceAwsApiGatewayMethodResponseRead(d *schema.ResourceData, meta interf StatusCode: aws.String(d.Get("status_code").(string)), }) if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NotFoundException" { + if isAWSErr(err, apigateway.ErrCodeNotFoundException, "") { log.Printf("[WARN] API Gateway Response (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -172,10 +165,7 @@ func resourceAwsApiGatewayMethodResponseUpdate(d *schema.ResourceData, meta inte } if d.HasChange("response_parameters") { - ops, err := expandApiGatewayMethodParametersOperations(d, "response_parameters", "responseParameters") - if err != nil { - return err - } + ops := expandApiGatewayMethodParametersOperations(d, "response_parameters", "responseParameters") operations = append(operations, ops...) } diff --git a/aws/resource_aws_api_gateway_method_response_test.go b/aws/resource_aws_api_gateway_method_response_test.go index 18b3fca5994..f187fcebfcb 100644 --- a/aws/resource_aws_api_gateway_method_response_test.go +++ b/aws/resource_aws_api_gateway_method_response_test.go @@ -7,9 +7,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayMethodResponse_basic(t *testing.T) { @@ -55,6 +55,28 @@ func TestAccAWSAPIGatewayMethodResponse_basic(t *testing.T) { }) } +func TestAccAWSAPIGatewayMethodResponse_disappears(t *testing.T) { + var conf apigateway.MethodResponse + rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + resourceName := "aws_api_gateway_method_response.error" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayMethodResponseDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayMethodResponseConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayMethodResponseExists(resourceName, &conf), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayMethodResponse(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAWSAPIGatewayMethodResponseAttributes(conf *apigateway.MethodResponse) resource.TestCheckFunc { return func(s *terraform.State) error { if *conf.StatusCode == "" { diff --git a/aws/resource_aws_api_gateway_method_settings.go b/aws/resource_aws_api_gateway_method_settings.go index eeba69d1b3e..1815a45ae43 100644 --- a/aws/resource_aws_api_gateway_method_settings.go +++ b/aws/resource_aws_api_gateway_method_settings.go @@ -3,11 +3,12 @@ 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/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsApiGatewayMethodSettings() *schema.Resource { @@ -17,6 +18,10 @@ func resourceAwsApiGatewayMethodSettings() *schema.Resource { Update: resourceAwsApiGatewayMethodSettingsUpdate, Delete: resourceAwsApiGatewayMethodSettingsDelete, + Importer: &schema.ResourceImporter{ + State: resourceAwsApiGatewayMethodSettingsImport, + }, + Schema: map[string]*schema.Schema{ "rest_api_id": { Type: schema.TypeString, @@ -42,42 +47,62 @@ func resourceAwsApiGatewayMethodSettings() *schema.Resource { "metrics_enabled": { Type: schema.TypeBool, Optional: true, + Computed: true, }, "logging_level": { Type: schema.TypeString, Optional: true, + Computed: true, + ValidateFunc: validation.StringInSlice([]string{ + "OFF", + "ERROR", + "INFO", + }, false), }, "data_trace_enabled": { Type: schema.TypeBool, Optional: true, + Computed: true, }, "throttling_burst_limit": { Type: schema.TypeInt, Optional: true, + Default: -1, }, "throttling_rate_limit": { Type: schema.TypeFloat, Optional: true, + Default: -1, }, "caching_enabled": { Type: schema.TypeBool, Optional: true, + Computed: true, }, "cache_ttl_in_seconds": { Type: schema.TypeInt, Optional: true, + Computed: true, }, "cache_data_encrypted": { Type: schema.TypeBool, Optional: true, + Computed: true, }, "require_authorization_for_cache_control": { Type: schema.TypeBool, Optional: true, + Computed: true, }, "unauthorized_cache_control_header_strategy": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + apigateway.UnauthorizedCacheControlHeaderStrategyFailWith403, + apigateway.UnauthorizedCacheControlHeaderStrategySucceedWithResponseHeader, + apigateway.UnauthorizedCacheControlHeaderStrategySucceedWithoutResponseHeader, + }, false), + Computed: true, }, }, }, @@ -86,6 +111,23 @@ func resourceAwsApiGatewayMethodSettings() *schema.Resource { } } +func flattenAwsApiGatewayMethodSettings(settings *apigateway.MethodSetting) []interface{} { + return []interface{}{ + map[string]interface{}{ + "metrics_enabled": settings.MetricsEnabled, + "logging_level": settings.LoggingLevel, + "data_trace_enabled": settings.DataTraceEnabled, + "throttling_burst_limit": settings.ThrottlingBurstLimit, + "throttling_rate_limit": settings.ThrottlingRateLimit, + "caching_enabled": settings.CachingEnabled, + "cache_ttl_in_seconds": settings.CacheTtlInSeconds, + "cache_data_encrypted": settings.CacheDataEncrypted, + "require_authorization_for_cache_control": settings.RequireAuthorizationForCacheControl, + "unauthorized_cache_control_header_strategy": settings.UnauthorizedCacheControlHeaderStrategy, + }, + } +} + func resourceAwsApiGatewayMethodSettingsRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).apigatewayconn @@ -96,7 +138,7 @@ func resourceAwsApiGatewayMethodSettingsRead(d *schema.ResourceData, meta interf } stage, err := conn.GetStage(&input) if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NotFoundException" { + if isAWSErr(err, apigateway.ErrCodeNotFoundException, "") { log.Printf("[WARN] API Gateway Stage (%s) not found, removing method settings", d.Id()) d.SetId("") return nil @@ -113,16 +155,9 @@ func resourceAwsApiGatewayMethodSettingsRead(d *schema.ResourceData, meta interf 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) + if err := d.Set("settings", flattenAwsApiGatewayMethodSettings(settings)); err != nil { + return fmt.Errorf("error setting settings: %w", err) + } return nil } @@ -136,21 +171,21 @@ func resourceAwsApiGatewayMethodSettingsUpdate(d *schema.ResourceData, meta inte ops := make([]*apigateway.PatchOperation, 0) if d.HasChange("settings.0.metrics_enabled") { ops = append(ops, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), 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"), + Op: aws.String(apigateway.OpReplace), 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"), + Op: aws.String(apigateway.OpReplace), Path: aws.String(prefix + "logging/dataTrace"), Value: aws.String(fmt.Sprintf("%t", d.Get("settings.0.data_trace_enabled").(bool))), }) @@ -158,49 +193,51 @@ func resourceAwsApiGatewayMethodSettingsUpdate(d *schema.ResourceData, meta inte if d.HasChange("settings.0.throttling_burst_limit") { ops = append(ops, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), 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"), + Op: aws.String(apigateway.OpReplace), 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"), + Op: aws.String(apigateway.OpReplace), 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") { + + if v, ok := d.GetOkExists("settings.0.cache_ttl_in_seconds"); ok { ops = append(ops, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String(prefix + "caching/ttlInSeconds"), - Value: aws.String(fmt.Sprintf("%d", d.Get("settings.0.cache_ttl_in_seconds").(int))), + Value: aws.String(fmt.Sprintf("%d", v.(int))), }) } + if d.HasChange("settings.0.cache_data_encrypted") { ops = append(ops, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String(prefix + "caching/dataEncrypted"), Value: aws.String(fmt.Sprintf("%t", d.Get("settings.0.cache_data_encrypted").(bool))), }) } if d.HasChange("settings.0.require_authorization_for_cache_control") { ops = append(ops, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), 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"), + Op: aws.String(apigateway.OpReplace), Path: aws.String(prefix + "caching/unauthorizedCacheControlHeaderStrategy"), Value: aws.String(d.Get("settings.0.unauthorized_cache_control_header_strategy").(string)), }) @@ -216,7 +253,7 @@ func resourceAwsApiGatewayMethodSettingsUpdate(d *schema.ResourceData, meta inte 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 fmt.Errorf("updating API Gateway Stage failed: %w", err) } d.SetId(restApiId + "-" + stageName + "-" + methodPath) @@ -233,7 +270,7 @@ func resourceAwsApiGatewayMethodSettingsDelete(d *schema.ResourceData, meta inte StageName: aws.String(d.Get("stage_name").(string)), PatchOperations: []*apigateway.PatchOperation{ { - Op: aws.String("remove"), + Op: aws.String(apigateway.OpRemove), Path: aws.String(fmt.Sprintf("/%s", d.Get("method_path").(string))), }, }, @@ -241,8 +278,23 @@ func resourceAwsApiGatewayMethodSettingsDelete(d *schema.ResourceData, meta inte 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 fmt.Errorf("updating API Gateway Stage failed: %w", err) } return nil } + +func resourceAwsApiGatewayMethodSettingsImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + idParts := strings.SplitN(d.Id(), "/", 3) + if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { + return nil, fmt.Errorf("Unexpected format of ID (%q), expected REST-API-ID/STAGE-NAME/METHOD-PATH", d.Id()) + } + restApiID := idParts[0] + stageName := idParts[1] + methodPath := idParts[2] + d.Set("rest_api_id", restApiID) + d.Set("stage_name", stageName) + d.Set("method_path", methodPath) + d.SetId(fmt.Sprintf("%s-%s-%s", restApiID, stageName, methodPath)) + return []*schema.ResourceData{d}, nil +} diff --git a/aws/resource_aws_api_gateway_method_settings_test.go b/aws/resource_aws_api_gateway_method_settings_test.go index a0040e0acd5..1476b0f1cde 100644 --- a/aws/resource_aws_api_gateway_method_settings_test.go +++ b/aws/resource_aws_api_gateway_method_settings_test.go @@ -7,9 +7,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayMethodSettings_basic(t *testing.T) { @@ -30,6 +30,12 @@ func TestAccAWSAPIGatewayMethodSettings_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "settings.0.logging_level", "INFO"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, }, }) } @@ -60,6 +66,12 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_CacheDataEncrypted(t *testing.T resource.TestCheckResourceAttr(resourceName, "settings.0.cache_data_encrypted", "false"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, }, }) } @@ -74,6 +86,14 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_CacheTtlInSeconds(t *testing.T) Providers: testAccProviders, CheckDestroy: testAccCheckAWSAPIGatewayMethodSettingsDestroy, Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayMethodSettingsConfigSettingsCacheTtlInSeconds(rName, 0), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayMethodSettingsExists(resourceName, &stage1), + resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "settings.0.cache_ttl_in_seconds", "0"), + ), + }, { Config: testAccAWSAPIGatewayMethodSettingsConfigSettingsCacheTtlInSeconds(rName, 1), Check: resource.ComposeTestCheckFunc( @@ -90,6 +110,12 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_CacheTtlInSeconds(t *testing.T) resource.TestCheckResourceAttr(resourceName, "settings.0.cache_ttl_in_seconds", "2"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, }, }) } @@ -120,6 +146,12 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_CachingEnabled(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "settings.0.caching_enabled", "false"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, }, }) } @@ -150,6 +182,12 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_DataTraceEnabled(t *testing.T) resource.TestCheckResourceAttr(resourceName, "settings.0.data_trace_enabled", "false"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, }, }) } @@ -182,6 +220,12 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_LoggingLevel(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "settings.0.logging_level", "OFF"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, }, }) } @@ -214,6 +258,12 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_MetricsEnabled(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "settings.0.metrics_enabled", "false"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, }, }) } @@ -250,6 +300,12 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_Multiple(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "settings.0.logging_level", "OFF"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, }, }) } @@ -280,6 +336,12 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_RequireAuthorizationForCacheCon resource.TestCheckResourceAttr(resourceName, "settings.0.require_authorization_for_cache_control", "false"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, }, }) } @@ -310,6 +372,49 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_ThrottlingBurstLimit(t *testing resource.TestCheckResourceAttr(resourceName, "settings.0.throttling_burst_limit", "2"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/5690 +func TestAccAWSAPIGatewayMethodSettings_Settings_ThrottlingBurstLimitDisabledByDefault(t *testing.T) { + var stage1, stage2 apigateway.Stage + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_api_gateway_method_settings.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayMethodSettingsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayMethodSettingsConfigSettingsLoggingLevel(rName, "INFO"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayMethodSettingsExists(resourceName, &stage2), + resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "settings.0.throttling_burst_limit", "-1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + { + Config: testAccAWSAPIGatewayMethodSettingsConfigSettingsThrottlingBurstLimit(rName, 1), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayMethodSettingsExists(resourceName, &stage1), + resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "settings.0.throttling_burst_limit", "1"), + ), + }, }, }) } @@ -340,6 +445,49 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_ThrottlingRateLimit(t *testing. resource.TestCheckResourceAttr(resourceName, "settings.0.throttling_rate_limit", "2.2"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/5690 +func TestAccAWSAPIGatewayMethodSettings_Settings_ThrottlingRateLimitDisabledByDefault(t *testing.T) { + var stage1, stage2 apigateway.Stage + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_api_gateway_method_settings.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayMethodSettingsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayMethodSettingsConfigSettingsLoggingLevel(rName, "INFO"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayMethodSettingsExists(resourceName, &stage1), + resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "settings.0.throttling_rate_limit", "-1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + { + Config: testAccAWSAPIGatewayMethodSettingsConfigSettingsThrottlingRateLimit(rName, 1.1), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayMethodSettingsExists(resourceName, &stage2), + resource.TestCheckResourceAttr(resourceName, "settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "settings.0.throttling_rate_limit", "1.1"), + ), + }, }, }) } @@ -370,6 +518,12 @@ func TestAccAWSAPIGatewayMethodSettings_Settings_UnauthorizedCacheControlHeaderS resource.TestCheckResourceAttr(resourceName, "settings.0.unauthorized_cache_control_header_strategy", "SUCCEED_WITHOUT_RESPONSE_HEADER"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, }, }) } @@ -407,6 +561,28 @@ func testAccCheckAWSAPIGatewayMethodSettings_loggingLevel(conf *apigateway.Stage } } +func TestAccAWSAPIGatewayMethodSettings_disappears(t *testing.T) { + var stage apigateway.Stage + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_api_gateway_method_settings.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayMethodSettingsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayMethodSettingsConfigSettingsLoggingLevel(rName, "INFO"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayMethodSettingsExists(resourceName, &stage), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayMethodSettings(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAWSAPIGatewayMethodSettingsExists(n string, res *apigateway.Stage) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -464,6 +640,21 @@ func testAccCheckAWSAPIGatewayMethodSettingsDestroy(s *terraform.State) error { return nil } +func testAccAWSAPIGatewayMethodSettingsImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { + return func(s *terraform.State) (string, error) { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return "", fmt.Errorf("not found: %s", resourceName) + } + + restApiID := rs.Primary.Attributes["rest_api_id"] + stageName := rs.Primary.Attributes["stage_name"] + methodPath := rs.Primary.Attributes["method_path"] + + return fmt.Sprintf("%s/%s/%s", restApiID, stageName, methodPath), nil + } +} + func testAccAWSAPIGatewayMethodSettingsConfigBase(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { diff --git a/aws/resource_aws_api_gateway_method_test.go b/aws/resource_aws_api_gateway_method_test.go index 1d7a5923229..afce3bf9e0c 100644 --- a/aws/resource_aws_api_gateway_method_test.go +++ b/aws/resource_aws_api_gateway_method_test.go @@ -8,14 +8,15 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayMethod_basic(t *testing.T) { var conf apigateway.Method rInt := acctest.RandInt() + resourceName := "aws_api_gateway_method.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -25,27 +26,24 @@ func TestAccAWSAPIGatewayMethod_basic(t *testing.T) { { Config: testAccAWSAPIGatewayMethodConfig(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf), + testAccCheckAWSAPIGatewayMethodExists(resourceName, &conf), testAccCheckAWSAPIGatewayMethodAttributes(&conf), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "http_method", "GET"), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "authorization", "NONE"), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "request_models.application/json", "Error"), + resource.TestCheckResourceAttr(resourceName, "http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "authorization", "NONE"), + resource.TestCheckResourceAttr(resourceName, "request_models.application/json", "Error"), ), }, { - ResourceName: "aws_api_gateway_method.test", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSAPIGatewayMethodImportStateIdFunc("aws_api_gateway_method.test"), + ImportStateIdFunc: testAccAWSAPIGatewayMethodImportStateIdFunc(resourceName), ImportStateVerify: true, }, { Config: testAccAWSAPIGatewayMethodConfigUpdate(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf), + testAccCheckAWSAPIGatewayMethodExists(resourceName, &conf), testAccCheckAWSAPIGatewayMethodAttributesUpdate(&conf), ), }, @@ -56,6 +54,7 @@ func TestAccAWSAPIGatewayMethod_basic(t *testing.T) { func TestAccAWSAPIGatewayMethod_customauthorizer(t *testing.T) { var conf apigateway.Method rInt := acctest.RandInt() + resourceName := "aws_api_gateway_method.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -65,34 +64,28 @@ func TestAccAWSAPIGatewayMethod_customauthorizer(t *testing.T) { { Config: testAccAWSAPIGatewayMethodConfigWithCustomAuthorizer(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf), + testAccCheckAWSAPIGatewayMethodExists(resourceName, &conf), testAccCheckAWSAPIGatewayMethodAttributes(&conf), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "http_method", "GET"), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "authorization", "CUSTOM"), - resource.TestMatchResourceAttr( - "aws_api_gateway_method.test", "authorizer_id", regexp.MustCompile("^[a-z0-9]{6}$")), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "request_models.application/json", "Error"), + resource.TestCheckResourceAttr(resourceName, "http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "authorization", "CUSTOM"), + resource.TestMatchResourceAttr(resourceName, "authorizer_id", regexp.MustCompile("^[a-z0-9]{6}$")), + resource.TestCheckResourceAttr(resourceName, "request_models.application/json", "Error"), ), }, { - ResourceName: "aws_api_gateway_method.test", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSAPIGatewayMethodImportStateIdFunc("aws_api_gateway_method.test"), + ImportStateIdFunc: testAccAWSAPIGatewayMethodImportStateIdFunc(resourceName), ImportStateVerify: true, }, { Config: testAccAWSAPIGatewayMethodConfigUpdate(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf), + testAccCheckAWSAPIGatewayMethodExists(resourceName, &conf), testAccCheckAWSAPIGatewayMethodAttributesUpdate(&conf), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "authorization", "NONE"), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "authorizer_id", ""), + resource.TestCheckResourceAttr(resourceName, "authorization", "NONE"), + resource.TestCheckResourceAttr(resourceName, "authorizer_id", ""), ), }, }, @@ -102,6 +95,7 @@ func TestAccAWSAPIGatewayMethod_customauthorizer(t *testing.T) { func TestAccAWSAPIGatewayMethod_cognitoauthorizer(t *testing.T) { var conf apigateway.Method rInt := acctest.RandInt() + resourceName := "aws_api_gateway_method.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -111,40 +105,31 @@ func TestAccAWSAPIGatewayMethod_cognitoauthorizer(t *testing.T) { { Config: testAccAWSAPIGatewayMethodConfigWithCognitoAuthorizer(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf), + testAccCheckAWSAPIGatewayMethodExists(resourceName, &conf), testAccCheckAWSAPIGatewayMethodAttributes(&conf), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "http_method", "GET"), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "authorization", "COGNITO_USER_POOLS"), - resource.TestMatchResourceAttr( - "aws_api_gateway_method.test", "authorizer_id", regexp.MustCompile("^[a-z0-9]{6}$")), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "request_models.application/json", "Error"), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "authorization_scopes.#", "2"), + resource.TestCheckResourceAttr(resourceName, "http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "authorization", "COGNITO_USER_POOLS"), + resource.TestMatchResourceAttr(resourceName, "authorizer_id", regexp.MustCompile("^[a-z0-9]{6}$")), + resource.TestCheckResourceAttr(resourceName, "request_models.application/json", "Error"), + resource.TestCheckResourceAttr(resourceName, "authorization_scopes.#", "2"), ), }, { Config: testAccAWSAPIGatewayMethodConfigWithCognitoAuthorizerUpdate(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf), + testAccCheckAWSAPIGatewayMethodExists(resourceName, &conf), testAccCheckAWSAPIGatewayMethodAttributesUpdate(&conf), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "authorization", "COGNITO_USER_POOLS"), - resource.TestMatchResourceAttr( - "aws_api_gateway_method.test", "authorizer_id", regexp.MustCompile("^[a-z0-9]{6}$")), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "request_models.application/json", "Error"), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "authorization_scopes.#", "3"), + resource.TestCheckResourceAttr(resourceName, "authorization", "COGNITO_USER_POOLS"), + resource.TestMatchResourceAttr(resourceName, "authorizer_id", regexp.MustCompile("^[a-z0-9]{6}$")), + resource.TestCheckResourceAttr(resourceName, "request_models.application/json", "Error"), + resource.TestCheckResourceAttr(resourceName, "authorization_scopes.#", "3"), ), }, { - ResourceName: "aws_api_gateway_method.test", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSAPIGatewayMethodImportStateIdFunc("aws_api_gateway_method.test"), + ImportStateIdFunc: testAccAWSAPIGatewayMethodImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -154,6 +139,7 @@ func TestAccAWSAPIGatewayMethod_cognitoauthorizer(t *testing.T) { func TestAccAWSAPIGatewayMethod_customrequestvalidator(t *testing.T) { var conf apigateway.Method rInt := acctest.RandInt() + resourceName := "aws_api_gateway_method.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -163,38 +149,55 @@ func TestAccAWSAPIGatewayMethod_customrequestvalidator(t *testing.T) { { Config: testAccAWSAPIGatewayMethodConfigWithCustomRequestValidator(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf), + testAccCheckAWSAPIGatewayMethodExists(resourceName, &conf), testAccCheckAWSAPIGatewayMethodAttributes(&conf), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "http_method", "GET"), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "authorization", "NONE"), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "request_models.application/json", "Error"), - resource.TestMatchResourceAttr( - "aws_api_gateway_method.test", "request_validator_id", regexp.MustCompile("^[a-z0-9]{6}$")), + resource.TestCheckResourceAttr(resourceName, "http_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "authorization", "NONE"), + resource.TestCheckResourceAttr(resourceName, "request_models.application/json", "Error"), + resource.TestMatchResourceAttr(resourceName, "request_validator_id", regexp.MustCompile("^[a-z0-9]{6}$")), ), }, { - ResourceName: "aws_api_gateway_method.test", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSAPIGatewayMethodImportStateIdFunc("aws_api_gateway_method.test"), + ImportStateIdFunc: testAccAWSAPIGatewayMethodImportStateIdFunc(resourceName), ImportStateVerify: true, }, { Config: testAccAWSAPIGatewayMethodConfigWithCustomRequestValidatorUpdate(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf), + testAccCheckAWSAPIGatewayMethodExists(resourceName, &conf), testAccCheckAWSAPIGatewayMethodAttributesUpdate(&conf), - resource.TestCheckResourceAttr( - "aws_api_gateway_method.test", "request_validator_id", ""), + resource.TestCheckResourceAttr(resourceName, "request_validator_id", ""), ), }, }, }) } +func TestAccAWSAPIGatewayMethod_disappears(t *testing.T) { + var conf apigateway.Method + rInt := acctest.RandInt() + resourceName := "aws_api_gateway_method.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayMethodDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayMethodConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayMethodExists(resourceName, &conf), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayMethod(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAWSAPIGatewayMethodAttributes(conf *apigateway.Method) resource.TestCheckFunc { return func(s *terraform.State) error { if *conf.HttpMethod != "GET" { diff --git a/aws/resource_aws_api_gateway_model.go b/aws/resource_aws_api_gateway_model.go index 5cf8d439ff8..bd2566ada79 100644 --- a/aws/resource_aws_api_gateway_model.go +++ b/aws/resource_aws_api_gateway_model.go @@ -6,9 +6,8 @@ import ( "strings" "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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsApiGatewayModel() *schema.Resource { @@ -118,7 +117,7 @@ func resourceAwsApiGatewayModelRead(d *schema.ResourceData, meta interface{}) er RestApiId: aws.String(d.Get("rest_api_id").(string)), }) if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NotFoundException" { + if isAWSErr(err, apigateway.ErrCodeNotFoundException, "") { log.Printf("[WARN] API Gateway Model (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -141,14 +140,14 @@ func resourceAwsApiGatewayModelUpdate(d *schema.ResourceData, meta interface{}) operations := make([]*apigateway.PatchOperation, 0) if d.HasChange("description") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/description"), Value: aws.String(d.Get("description").(string)), }) } if d.HasChange("schema") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/schema"), Value: aws.String(d.Get("schema").(string)), }) @@ -178,7 +177,7 @@ func resourceAwsApiGatewayModelDelete(d *schema.ResourceData, meta interface{}) log.Printf("[DEBUG] schema is %#v", d) _, err := conn.DeleteModel(input) - if isAWSErr(err, "NotFoundException", "") { + if isAWSErr(err, apigateway.ErrCodeNotFoundException, "") { return nil } diff --git a/aws/resource_aws_api_gateway_model_test.go b/aws/resource_aws_api_gateway_model_test.go index 49796d4e330..848b64d5a1d 100644 --- a/aws/resource_aws_api_gateway_model_test.go +++ b/aws/resource_aws_api_gateway_model_test.go @@ -7,9 +7,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayModel_basic(t *testing.T) { @@ -47,6 +47,30 @@ func TestAccAWSAPIGatewayModel_basic(t *testing.T) { }) } +func TestAccAWSAPIGatewayModel_disappears(t *testing.T) { + var conf apigateway.Model + rInt := acctest.RandString(10) + rName := fmt.Sprintf("tf-acc-test-%s", rInt) + modelName := fmt.Sprintf("tfacctest%s", rInt) + resourceName := "aws_api_gateway_model.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayModelDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayModelConfig(rName, modelName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayModelExists(resourceName, modelName, &conf), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayModel(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAWSAPIGatewayModelAttributes(conf *apigateway.Model, name string) resource.TestCheckFunc { return func(s *terraform.State) error { if *conf.Name != name { diff --git a/aws/resource_aws_api_gateway_request_validator.go b/aws/resource_aws_api_gateway_request_validator.go index 5a0b19f96ae..c62d9782edd 100644 --- a/aws/resource_aws_api_gateway_request_validator.go +++ b/aws/resource_aws_api_gateway_request_validator.go @@ -6,9 +6,8 @@ import ( "strings" "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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsApiGatewayRequestValidator() *schema.Resource { @@ -25,7 +24,6 @@ func resourceAwsApiGatewayRequestValidator() *schema.Resource { } restApiID := idParts[0] requestValidatorID := idParts[1] - d.Set("request_validator_id", requestValidatorID) d.Set("rest_api_id", restApiID) d.SetId(requestValidatorID) return []*schema.ResourceData{d}, nil @@ -89,7 +87,7 @@ func resourceAwsApiGatewayRequestValidatorRead(d *schema.ResourceData, meta inte out, err := conn.GetRequestValidator(&input) if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == apigateway.ErrCodeNotFoundException { + if isAWSErr(err, apigateway.ErrCodeNotFoundException, "") { log.Printf("[WARN] API Gateway Request Validator (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -112,7 +110,7 @@ func resourceAwsApiGatewayRequestValidatorUpdate(d *schema.ResourceData, meta in if d.HasChange("name") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/name"), Value: aws.String(d.Get("name").(string)), }) @@ -120,7 +118,7 @@ func resourceAwsApiGatewayRequestValidatorUpdate(d *schema.ResourceData, meta in if d.HasChange("validate_request_body") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/validateRequestBody"), Value: aws.String(fmt.Sprintf("%t", d.Get("validate_request_body").(bool))), }) @@ -128,7 +126,7 @@ func resourceAwsApiGatewayRequestValidatorUpdate(d *schema.ResourceData, meta in if d.HasChange("validate_request_parameters") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/validateRequestParameters"), Value: aws.String(fmt.Sprintf("%t", d.Get("validate_request_parameters").(bool))), }) diff --git a/aws/resource_aws_api_gateway_request_validator_test.go b/aws/resource_aws_api_gateway_request_validator_test.go index 46d08aa668c..34d9f1a946a 100644 --- a/aws/resource_aws_api_gateway_request_validator_test.go +++ b/aws/resource_aws_api_gateway_request_validator_test.go @@ -7,9 +7,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayRequestValidator_basic(t *testing.T) { @@ -56,6 +56,28 @@ func TestAccAWSAPIGatewayRequestValidator_basic(t *testing.T) { }) } +func TestAccAWSAPIGatewayRequestValidator_disappears(t *testing.T) { + var conf apigateway.UpdateRequestValidatorOutput + rName := fmt.Sprintf("tf-test-acc-%s", acctest.RandString(8)) + resourceName := "aws_api_gateway_request_validator.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayRequestValidatorDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayRequestValidatorConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayRequestValidatorExists(resourceName, &conf), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayRequestValidator(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAWSAPIGatewayRequestValidatorName(conf *apigateway.UpdateRequestValidatorOutput, expectedName string) resource.TestCheckFunc { return func(s *terraform.State) error { if conf.Name == nil { diff --git a/aws/resource_aws_api_gateway_resource.go b/aws/resource_aws_api_gateway_resource.go index e6961e9949a..46e91905e06 100644 --- a/aws/resource_aws_api_gateway_resource.go +++ b/aws/resource_aws_api_gateway_resource.go @@ -6,9 +6,8 @@ import ( "strings" "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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsApiGatewayResource() *schema.Resource { @@ -25,7 +24,6 @@ func resourceAwsApiGatewayResource() *schema.Resource { } restApiID := idParts[0] resourceID := idParts[1] - d.Set("request_validator_id", resourceID) d.Set("rest_api_id", restApiID) d.SetId(resourceID) return []*schema.ResourceData{d}, nil @@ -87,7 +85,7 @@ func resourceAwsApiGatewayResourceRead(d *schema.ResourceData, meta interface{}) }) if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NotFoundException" { + if isAWSErr(err, apigateway.ErrCodeNotFoundException, "") { log.Printf("[WARN] API Gateway Resource (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -106,7 +104,7 @@ func resourceAwsApiGatewayResourceUpdateOperations(d *schema.ResourceData) []*ap operations := make([]*apigateway.PatchOperation, 0) if d.HasChange("path_part") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/pathPart"), Value: aws.String(d.Get("path_part").(string)), }) @@ -114,7 +112,7 @@ func resourceAwsApiGatewayResourceUpdateOperations(d *schema.ResourceData) []*ap if d.HasChange("parent_id") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/parentId"), Value: aws.String(d.Get("parent_id").(string)), }) diff --git a/aws/resource_aws_api_gateway_resource_test.go b/aws/resource_aws_api_gateway_resource_test.go index d47b1dc1f3e..ce7d845cab2 100644 --- a/aws/resource_aws_api_gateway_resource_test.go +++ b/aws/resource_aws_api_gateway_resource_test.go @@ -7,9 +7,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayResource_basic(t *testing.T) { @@ -86,6 +86,28 @@ func TestAccAWSAPIGatewayResource_update(t *testing.T) { }) } +func TestAccAWSAPIGatewayResource_disappears(t *testing.T) { + var conf apigateway.Resource + rName := fmt.Sprintf("tf-test-acc-%s", acctest.RandString(8)) + resourceName := "aws_api_gateway_resource.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayResourceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayResourceConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayResourceExists(resourceName, &conf), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayResource(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAWSAPIGatewayResourceAttributes(conf *apigateway.Resource, path string) resource.TestCheckFunc { return func(s *terraform.State) error { if *conf.Path != path { diff --git a/aws/resource_aws_api_gateway_rest_api.go b/aws/resource_aws_api_gateway_rest_api.go index d8f74e8ac6a..5b245c1a103 100644 --- a/aws/resource_aws_api_gateway_rest_api.go +++ b/aws/resource_aws_api_gateway_rest_api.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_api_gateway_rest_api_test.go b/aws/resource_aws_api_gateway_rest_api_test.go index f34a8a944fe..9025282a1ac 100644 --- a/aws/resource_aws_api_gateway_rest_api_test.go +++ b/aws/resource_aws_api_gateway_rest_api_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -188,7 +188,7 @@ func TestAccAWSAPIGatewayRestApi_disappears(t *testing.T) { Config: testAccAWSAPIGatewayRestAPIConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayRestAPIExists(resourceName, &restApi), - testAccCheckAWSAPIGatewayRestAPIDisappears(&restApi), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayRestApi(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -647,20 +647,6 @@ func testAccCheckAWSAPIGatewayRestAPIDestroy(s *terraform.State) error { return nil } -func testAccCheckAWSAPIGatewayRestAPIDisappears(restApi *apigateway.RestApi) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).apigatewayconn - - input := &apigateway.DeleteRestApiInput{ - RestApiId: restApi.Id, - } - - _, err := conn.DeleteRestApi(input) - - return err - } -} - func testAccAWSAPIGatewayRestAPIConfig(rName string) string { return fmt.Sprintf(` resource "aws_api_gateway_rest_api" "test" { diff --git a/aws/resource_aws_api_gateway_stage.go b/aws/resource_aws_api_gateway_stage.go index 6131a706f78..a7d4b39f6a5 100644 --- a/aws/resource_aws_api_gateway_stage.go +++ b/aws/resource_aws_api_gateway_stage.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -46,10 +46,6 @@ func resourceAwsApiGatewayStage() *schema.Resource { "destination_arn": { Type: schema.TypeString, Required: true, - StateFunc: func(arn interface{}) string { - // arns coming from a TF reference to a log group contain a trailing `:*` which is not valid - return strings.TrimSuffix(arn.(string), ":*") - }, }, "format": { Type: schema.TypeString, @@ -113,6 +109,7 @@ func resourceAwsApiGatewayStage() *schema.Resource { "variables": { Type: schema.TypeMap, Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "tags": tagsSchema(), "xray_tracing_enabled": { @@ -295,7 +292,7 @@ func resourceAwsApiGatewayStageUpdate(d *schema.ResourceData, meta interface{}) waitForCache := false if d.HasChange("cache_cluster_enabled") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/cacheClusterEnabled"), Value: aws.String(fmt.Sprintf("%t", d.Get("cache_cluster_enabled").(bool))), }) @@ -303,7 +300,7 @@ func resourceAwsApiGatewayStageUpdate(d *schema.ResourceData, meta interface{}) } if d.HasChange("cache_cluster_size") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/cacheClusterSize"), Value: aws.String(d.Get("cache_cluster_size").(string)), }) @@ -311,35 +308,35 @@ func resourceAwsApiGatewayStageUpdate(d *schema.ResourceData, meta interface{}) } if d.HasChange("client_certificate_id") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/clientCertificateId"), Value: aws.String(d.Get("client_certificate_id").(string)), }) } if d.HasChange("deployment_id") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/deploymentId"), Value: aws.String(d.Get("deployment_id").(string)), }) } if d.HasChange("description") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/description"), Value: aws.String(d.Get("description").(string)), }) } if d.HasChange("xray_tracing_enabled") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/tracingEnabled"), Value: aws.String(fmt.Sprintf("%t", d.Get("xray_tracing_enabled").(bool))), }) } if d.HasChange("documentation_version") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/documentationVersion"), Value: aws.String(d.Get("documentation_version").(string)), }) @@ -355,18 +352,17 @@ func resourceAwsApiGatewayStageUpdate(d *schema.ResourceData, meta interface{}) if len(accessLogSettings) == 1 { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), - Path: aws.String("/accessLogSettings/destinationArn"), - // arns coming from a TF reference to a log group contain a trailing `:*` which is not valid - Value: aws.String(strings.TrimSuffix(d.Get("access_log_settings.0.destination_arn").(string), ":*")), + Op: aws.String(apigateway.OpReplace), + Path: aws.String("/accessLogSettings/destinationArn"), + Value: aws.String(d.Get("access_log_settings.0.destination_arn").(string)), }, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/accessLogSettings/format"), Value: aws.String(d.Get("access_log_settings.0.format").(string)), }) } else if len(accessLogSettings) == 0 { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("remove"), + Op: aws.String(apigateway.OpRemove), Path: aws.String("/accessLogSettings"), }) } @@ -417,7 +413,7 @@ func diffVariablesOps(oldVars, newVars map[string]interface{}) []*apigateway.Pat for k := range oldVars { if _, ok := newVars[k]; !ok { ops = append(ops, &apigateway.PatchOperation{ - Op: aws.String("remove"), + Op: aws.String(apigateway.OpRemove), Path: aws.String(prefix + k), }) } @@ -433,7 +429,7 @@ func diffVariablesOps(oldVars, newVars map[string]interface{}) []*apigateway.Pat } } ops = append(ops, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String(prefix + k), Value: aws.String(newValue), }) diff --git a/aws/resource_aws_api_gateway_stage_test.go b/aws/resource_aws_api_gateway_stage_test.go index e9bd93e0183..52943f8b88c 100644 --- a/aws/resource_aws_api_gateway_stage_test.go +++ b/aws/resource_aws_api_gateway_stage_test.go @@ -8,9 +8,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayStage_basic(t *testing.T) { @@ -104,9 +104,32 @@ func TestAccAWSAPIGatewayStage_disappears_ReferencingDeployment(t *testing.T) { }) } +func TestAccAWSAPIGatewayStage_disappears(t *testing.T) { + var stage apigateway.Stage + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_api_gateway_stage.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayStageDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayStageConfigReferencingDeployment(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayStageExists(resourceName, &stage), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayStage(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func TestAccAWSAPIGatewayStage_accessLogSettings(t *testing.T) { var conf apigateway.Stage rName := acctest.RandString(5) + cloudwatchLogGroupResourceName := "aws_cloudwatch_log_group.test" resourceName := "aws_api_gateway_stage.test" clf := `$context.identity.sourceIp $context.identity.caller $context.identity.user [$context.requestTime] "$context.httpMethod $context.resourcePath $context.protocol" $context.status $context.responseLength $context.requestId` json := `{ "requestId":"$context.requestId", "ip": "$context.identity.sourceIp", "caller":"$context.identity.caller", "user":"$context.identity.user", "requestTime":"$context.requestTime", "httpMethod":"$context.httpMethod", "resourcePath":"$context.resourcePath", "status":"$context.status", "protocol":"$context.protocol", "responseLength":"$context.responseLength" }` @@ -124,7 +147,7 @@ func TestAccAWSAPIGatewayStage_accessLogSettings(t *testing.T) { testAccCheckAWSAPIGatewayStageExists(resourceName, &conf), testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/restapis/.+/stages/prod`)), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "1"), - testAccMatchResourceAttrRegionalARN(resourceName, "access_log_settings.0.destination_arn", "logs", regexp.MustCompile(fmt.Sprintf("log-group:foo-bar-%s$", rName))), + resource.TestCheckResourceAttrPair(resourceName, "access_log_settings.0.destination_arn", cloudwatchLogGroupResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "access_log_settings.0.format", clf), ), }, @@ -135,7 +158,7 @@ func TestAccAWSAPIGatewayStage_accessLogSettings(t *testing.T) { testAccCheckAWSAPIGatewayStageExists(resourceName, &conf), testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/restapis/.+/stages/prod`)), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "1"), - testAccMatchResourceAttrRegionalARN(resourceName, "access_log_settings.0.destination_arn", "logs", regexp.MustCompile(fmt.Sprintf("log-group:foo-bar-%s$", rName))), + resource.TestCheckResourceAttrPair(resourceName, "access_log_settings.0.destination_arn", cloudwatchLogGroupResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "access_log_settings.0.format", json), ), }, @@ -145,7 +168,7 @@ func TestAccAWSAPIGatewayStage_accessLogSettings(t *testing.T) { testAccCheckAWSAPIGatewayStageExists(resourceName, &conf), testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/restapis/.+/stages/prod`)), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "1"), - testAccMatchResourceAttrRegionalARN(resourceName, "access_log_settings.0.destination_arn", "logs", regexp.MustCompile(fmt.Sprintf("log-group:foo-bar-%s$", rName))), + resource.TestCheckResourceAttrPair(resourceName, "access_log_settings.0.destination_arn", cloudwatchLogGroupResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "access_log_settings.0.format", xml), ), }, @@ -155,7 +178,7 @@ func TestAccAWSAPIGatewayStage_accessLogSettings(t *testing.T) { testAccCheckAWSAPIGatewayStageExists(resourceName, &conf), testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(`/restapis/.+/stages/prod`)), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "1"), - testAccMatchResourceAttrRegionalARN(resourceName, "access_log_settings.0.destination_arn", "logs", regexp.MustCompile(fmt.Sprintf("log-group:foo-bar-%s$", rName))), + resource.TestCheckResourceAttrPair(resourceName, "access_log_settings.0.destination_arn", cloudwatchLogGroupResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "access_log_settings.0.format", csv), ), }, diff --git a/aws/resource_aws_api_gateway_usage_plan.go b/aws/resource_aws_api_gateway_usage_plan.go index a3397dc5886..a67076299d0 100644 --- a/aws/resource_aws_api_gateway_usage_plan.go +++ b/aws/resource_aws_api_gateway_usage_plan.go @@ -8,10 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -55,7 +54,7 @@ func resourceAwsApiGatewayUsagePlan() *schema.Resource { }, "quota_settings": { - Type: schema.TypeSet, + Type: schema.TypeList, MaxItems: 1, Optional: true, Elem: &schema.Resource{ @@ -85,7 +84,7 @@ func resourceAwsApiGatewayUsagePlan() *schema.Resource { }, "throttle_settings": { - Type: schema.TypeSet, + Type: schema.TypeList, MaxItems: 1, Optional: true, Elem: &schema.Resource{ @@ -155,7 +154,7 @@ func resourceAwsApiGatewayUsagePlanCreate(d *schema.ResourceData, meta interface } if v, ok := d.GetOk("quota_settings"); ok { - settings := v.(*schema.Set).List() + settings := v.([]interface{}) q, ok := settings[0].(map[string]interface{}) if errors := validateApiGatewayUsagePlanQuotaSettings(q); len(errors) > 0 { @@ -184,7 +183,7 @@ func resourceAwsApiGatewayUsagePlanCreate(d *schema.ResourceData, meta interface } if v, ok := d.GetOk("throttle_settings"); ok { - settings := v.(*schema.Set).List() + settings := v.([]interface{}) q, ok := settings[0].(map[string]interface{}) if !ok { @@ -222,7 +221,7 @@ func resourceAwsApiGatewayUsagePlanCreate(d *schema.ResourceData, meta interface UsagePlanId: aws.String(d.Id()), PatchOperations: []*apigateway.PatchOperation{ { - Op: aws.String("add"), + Op: aws.String(apigateway.OpAdd), Path: aws.String("/productCode"), Value: aws.String(v.(string)), }, @@ -248,7 +247,7 @@ func resourceAwsApiGatewayUsagePlanRead(d *schema.ResourceData, meta interface{} UsagePlanId: aws.String(d.Id()), }) if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == apigateway.ErrCodeNotFoundException { + if isAWSErr(err, apigateway.ErrCodeNotFoundException, "") { log.Printf("[WARN] API Gateway Usage Plan (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -301,7 +300,7 @@ func resourceAwsApiGatewayUsagePlanUpdate(d *schema.ResourceData, meta interface if d.HasChange("name") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/name"), Value: aws.String(d.Get("name").(string)), }) @@ -309,7 +308,7 @@ func resourceAwsApiGatewayUsagePlanUpdate(d *schema.ResourceData, meta interface if d.HasChange("description") { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/description"), Value: aws.String(d.Get("description").(string)), }) @@ -320,13 +319,13 @@ func resourceAwsApiGatewayUsagePlanUpdate(d *schema.ResourceData, meta interface if ok { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/productCode"), Value: aws.String(v.(string)), }) } else { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("remove"), + Op: aws.String(apigateway.OpRemove), Path: aws.String("/productCode"), }) } @@ -342,7 +341,7 @@ func resourceAwsApiGatewayUsagePlanUpdate(d *schema.ResourceData, meta interface for _, v := range old { m := v.(map[string]interface{}) operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("remove"), + Op: aws.String(apigateway.OpRemove), Path: aws.String("/apiStages"), Value: aws.String(fmt.Sprintf("%s:%s", m["api_id"].(string), m["stage"].(string))), }) @@ -353,7 +352,7 @@ func resourceAwsApiGatewayUsagePlanUpdate(d *schema.ResourceData, meta interface for _, v := range new { m := v.(map[string]interface{}) operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("add"), + Op: aws.String(apigateway.OpAdd), Path: aws.String("/apiStages"), Value: aws.String(fmt.Sprintf("%s:%s", m["api_id"].(string), m["stage"].(string))), }) @@ -363,15 +362,12 @@ func resourceAwsApiGatewayUsagePlanUpdate(d *schema.ResourceData, meta interface if d.HasChange("throttle_settings") { o, n := d.GetChange("throttle_settings") - - os := o.(*schema.Set) - ns := n.(*schema.Set) - diff := ns.Difference(os).List() + diff := n.([]interface{}) // Handle Removal if len(diff) == 0 { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("remove"), + Op: aws.String(apigateway.OpRemove), Path: aws.String("/throttle"), }) } @@ -382,12 +378,12 @@ func resourceAwsApiGatewayUsagePlanUpdate(d *schema.ResourceData, meta interface // Handle Replaces if o != nil && n != nil { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/throttle/rateLimit"), Value: aws.String(strconv.FormatFloat(d["rate_limit"].(float64), 'f', -1, 64)), }) operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/throttle/burstLimit"), Value: aws.String(strconv.Itoa(d["burst_limit"].(int))), }) @@ -396,12 +392,12 @@ func resourceAwsApiGatewayUsagePlanUpdate(d *schema.ResourceData, meta interface // Handle Additions if o == nil && n != nil { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("add"), + Op: aws.String(apigateway.OpAdd), Path: aws.String("/throttle/rateLimit"), Value: aws.String(strconv.FormatFloat(d["rate_limit"].(float64), 'f', -1, 64)), }) operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("add"), + Op: aws.String(apigateway.OpAdd), Path: aws.String("/throttle/burstLimit"), Value: aws.String(strconv.Itoa(d["burst_limit"].(int))), }) @@ -411,15 +407,12 @@ func resourceAwsApiGatewayUsagePlanUpdate(d *schema.ResourceData, meta interface if d.HasChange("quota_settings") { o, n := d.GetChange("quota_settings") - - os := o.(*schema.Set) - ns := n.(*schema.Set) - diff := ns.Difference(os).List() + diff := n.([]interface{}) // Handle Removal if len(diff) == 0 { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("remove"), + Op: aws.String(apigateway.OpRemove), Path: aws.String("/quota"), }) } @@ -434,17 +427,17 @@ func resourceAwsApiGatewayUsagePlanUpdate(d *schema.ResourceData, meta interface // Handle Replaces if o != nil && n != nil { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/quota/limit"), Value: aws.String(strconv.Itoa(d["limit"].(int))), }) operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/quota/offset"), Value: aws.String(strconv.Itoa(d["offset"].(int))), }) operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("replace"), + Op: aws.String(apigateway.OpReplace), Path: aws.String("/quota/period"), Value: aws.String(d["period"].(string)), }) @@ -453,17 +446,17 @@ func resourceAwsApiGatewayUsagePlanUpdate(d *schema.ResourceData, meta interface // Handle Additions if o == nil && n != nil { operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("add"), + Op: aws.String(apigateway.OpAdd), Path: aws.String("/quota/limit"), Value: aws.String(strconv.Itoa(d["limit"].(int))), }) operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("add"), + Op: aws.String(apigateway.OpAdd), Path: aws.String("/quota/offset"), Value: aws.String(strconv.Itoa(d["offset"].(int))), }) operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("add"), + Op: aws.String(apigateway.OpAdd), Path: aws.String("/quota/period"), Value: aws.String(d["period"].(string)), }) @@ -504,7 +497,7 @@ func resourceAwsApiGatewayUsagePlanDelete(d *schema.ResourceData, meta interface sv := v.(map[string]interface{}) operations = append(operations, &apigateway.PatchOperation{ - Op: aws.String("remove"), + Op: aws.String(apigateway.OpRemove), Path: aws.String("/apiStages"), Value: aws.String(fmt.Sprintf("%s:%s", sv["api_id"].(string), sv["stage"].(string))), }) diff --git a/aws/resource_aws_api_gateway_usage_plan_key.go b/aws/resource_aws_api_gateway_usage_plan_key.go index cc649517a0e..e4768e3b5d3 100644 --- a/aws/resource_aws_api_gateway_usage_plan_key.go +++ b/aws/resource_aws_api_gateway_usage_plan_key.go @@ -6,9 +6,8 @@ import ( "strings" "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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsApiGatewayUsagePlanKey() *schema.Resource { @@ -92,7 +91,7 @@ func resourceAwsApiGatewayUsagePlanKeyRead(d *schema.ResourceData, meta interfac KeyId: aws.String(d.Get("key_id").(string)), }) if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == apigateway.ErrCodeNotFoundException { + if isAWSErr(err, apigateway.ErrCodeNotFoundException, "") { log.Printf("[WARN] API Gateway Usage Plan Key (%s) not found, removing from state", d.Id()) d.SetId("") return nil diff --git a/aws/resource_aws_api_gateway_usage_plan_key_test.go b/aws/resource_aws_api_gateway_usage_plan_key_test.go index b55fa27d8f4..7ba66a1331a 100644 --- a/aws/resource_aws_api_gateway_usage_plan_key_test.go +++ b/aws/resource_aws_api_gateway_usage_plan_key_test.go @@ -8,9 +8,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayUsagePlanKey_basic(t *testing.T) { @@ -84,7 +84,7 @@ func TestAccAWSAPIGatewayUsagePlanKey_disappears(t *testing.T) { Config: testAccAWSApiGatewayUsagePlanKeyBasicConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayUsagePlanKeyExists(resourceName, &conf), - testAccCheckAWSAPIGatewayUsagePlanKeyDisappears(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayUsagePlanKey(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -160,28 +160,6 @@ func testAccCheckAWSAPIGatewayUsagePlanKeyDestroy(s *terraform.State) error { return nil } -func testAccCheckAWSAPIGatewayUsagePlanKeyDisappears(resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceName] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No resource ID is set") - } - conn := testAccProvider.Meta().(*AWSClient).apigatewayconn - - input := &apigateway.DeleteUsagePlanKeyInput{ - KeyId: aws.String(rs.Primary.ID), - UsagePlanId: aws.String(rs.Primary.Attributes["usage_plan_id"]), - } - _, err := conn.DeleteUsagePlanKey(input) - - return err - } -} - func testAccCheckAWSAPIGatewayUsagePlanKeyImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] diff --git a/aws/resource_aws_api_gateway_usage_plan_test.go b/aws/resource_aws_api_gateway_usage_plan_test.go index c006ffd4be5..4f09552adb4 100644 --- a/aws/resource_aws_api_gateway_usage_plan_test.go +++ b/aws/resource_aws_api_gateway_usage_plan_test.go @@ -7,9 +7,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayUsagePlan_basic(t *testing.T) { @@ -74,6 +74,11 @@ func TestAccAWSAPIGatewayUsagePlan_tags(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, { Config: testAccAWSApiGatewayUsagePlanBasicTags2(name, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( @@ -208,10 +213,9 @@ func TestAccAWSAPIGatewayUsagePlan_throttling(t *testing.T) { resourceName := "aws_api_gateway_usage_plan.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy, Steps: []resource.TestStep{ { Config: testAccAWSApiGatewayUsagePlanBasicConfig(rName), @@ -231,8 +235,8 @@ func TestAccAWSAPIGatewayUsagePlan_throttling(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), - resource.TestCheckResourceAttr(resourceName, "throttle_settings.4173790118.burst_limit", "2"), - resource.TestCheckResourceAttr(resourceName, "throttle_settings.4173790118.rate_limit", "5"), + resource.TestCheckResourceAttr(resourceName, "throttle_settings.0.burst_limit", "2"), + resource.TestCheckResourceAttr(resourceName, "throttle_settings.0.rate_limit", "5"), ), }, { @@ -240,8 +244,8 @@ func TestAccAWSAPIGatewayUsagePlan_throttling(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), - resource.TestCheckResourceAttr(resourceName, "throttle_settings.1779463053.burst_limit", "3"), - resource.TestCheckResourceAttr(resourceName, "throttle_settings.1779463053.rate_limit", "6"), + resource.TestCheckResourceAttr(resourceName, "throttle_settings.0.burst_limit", "3"), + resource.TestCheckResourceAttr(resourceName, "throttle_settings.0.rate_limit", "6"), ), }, { @@ -263,16 +267,15 @@ func TestAccAWSAPIGatewayUsagePlan_throttlingInitialRateLimit(t *testing.T) { resourceName := "aws_api_gateway_usage_plan.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy, Steps: []resource.TestStep{ { Config: testAccAWSApiGatewayUsagePlanThrottlingConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayUsagePlanExists(resourceName, &conf), - resource.TestCheckResourceAttr(resourceName, "throttle_settings.4173790118.rate_limit", "5"), + resource.TestCheckResourceAttr(resourceName, "throttle_settings.0.rate_limit", "5"), ), }, { @@ -290,10 +293,9 @@ func TestAccAWSAPIGatewayUsagePlan_quota(t *testing.T) { resourceName := "aws_api_gateway_usage_plan.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy, Steps: []resource.TestStep{ { Config: testAccAWSApiGatewayUsagePlanBasicConfig(rName), @@ -313,9 +315,9 @@ func TestAccAWSAPIGatewayUsagePlan_quota(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), - resource.TestCheckResourceAttr(resourceName, "quota_settings.1956747625.limit", "100"), - resource.TestCheckResourceAttr(resourceName, "quota_settings.1956747625.offset", "6"), - resource.TestCheckResourceAttr(resourceName, "quota_settings.1956747625.period", "WEEK"), + resource.TestCheckResourceAttr(resourceName, "quota_settings.0.limit", "100"), + resource.TestCheckResourceAttr(resourceName, "quota_settings.0.offset", "6"), + resource.TestCheckResourceAttr(resourceName, "quota_settings.0.period", "WEEK"), ), }, { @@ -323,9 +325,9 @@ func TestAccAWSAPIGatewayUsagePlan_quota(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayUsagePlanExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "name", rName), - resource.TestCheckResourceAttr(resourceName, "quota_settings.3909168194.limit", "200"), - resource.TestCheckResourceAttr(resourceName, "quota_settings.3909168194.offset", "20"), - resource.TestCheckResourceAttr(resourceName, "quota_settings.3909168194.period", "MONTH"), + resource.TestCheckResourceAttr(resourceName, "quota_settings.0.limit", "200"), + resource.TestCheckResourceAttr(resourceName, "quota_settings.0.offset", "20"), + resource.TestCheckResourceAttr(resourceName, "quota_settings.0.period", "MONTH"), ), }, { @@ -404,6 +406,28 @@ func TestAccAWSAPIGatewayUsagePlan_apiStages(t *testing.T) { }) } +func TestAccAWSAPIGatewayUsagePlan_disappears(t *testing.T) { + var conf apigateway.UsagePlan + rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + resourceName := "aws_api_gateway_usage_plan.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayUsagePlanDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSApiGatewayUsagePlanBasicConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayUsagePlanExists(resourceName, &conf), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayUsagePlan(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAWSAPIGatewayUsagePlanExists(n string, res *apigateway.UsagePlan) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] diff --git a/aws/resource_aws_api_gateway_vpc_link.go b/aws/resource_aws_api_gateway_vpc_link.go index 473f59d7828..7b37618ecf7 100644 --- a/aws/resource_aws_api_gateway_vpc_link.go +++ b/aws/resource_aws_api_gateway_vpc_link.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -33,7 +33,7 @@ func resourceAwsApiGatewayVpcLink() *schema.Resource { Optional: true, }, "target_arns": { - Type: schema.TypeSet, + Type: schema.TypeList, MaxItems: 1, Required: true, ForceNew: true, @@ -54,7 +54,7 @@ func resourceAwsApiGatewayVpcLinkCreate(d *schema.ResourceData, meta interface{} input := &apigateway.CreateVpcLinkInput{ Name: aws.String(d.Get("name").(string)), - TargetArns: expandStringList(d.Get("target_arns").(*schema.Set).List()), + TargetArns: expandStringList(d.Get("target_arns").([]interface{})), Tags: tags, } if v, ok := d.GetOk("description"); ok { diff --git a/aws/resource_aws_api_gateway_vpc_link_test.go b/aws/resource_aws_api_gateway_vpc_link_test.go index 038db4e50da..595adfe052d 100644 --- a/aws/resource_aws_api_gateway_vpc_link_test.go +++ b/aws/resource_aws_api_gateway_vpc_link_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigateway" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -153,6 +153,27 @@ func TestAccAWSAPIGatewayVpcLink_tags(t *testing.T) { }) } +func TestAccAWSAPIGatewayVpcLink_disappears(t *testing.T) { + rName := acctest.RandString(5) + resourceName := "aws_api_gateway_vpc_link.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsAPIGatewayVpcLinkDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAPIGatewayVpcLinkConfig(rName, "test"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsAPIGatewayVpcLinkExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayVpcLink(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckAwsAPIGatewayVpcLinkDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).apigatewayconn diff --git a/aws/resource_aws_apigatewayv2_api.go b/aws/resource_aws_apigatewayv2_api.go index 67049184e0f..63048054e34 100644 --- a/aws/resource_aws_apigatewayv2_api.go +++ b/aws/resource_aws_apigatewayv2_api.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_apigatewayv2_api_mapping.go b/aws/resource_aws_apigatewayv2_api_mapping.go index 38eede5f4b1..947c81dfb8a 100644 --- a/aws/resource_aws_apigatewayv2_api_mapping.go +++ b/aws/resource_aws_apigatewayv2_api_mapping.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsApiGatewayV2ApiMapping() *schema.Resource { diff --git a/aws/resource_aws_apigatewayv2_api_mapping_test.go b/aws/resource_aws_apigatewayv2_api_mapping_test.go index c3d64e0e678..ad1e38fa8d1 100644 --- a/aws/resource_aws_apigatewayv2_api_mapping_test.go +++ b/aws/resource_aws_apigatewayv2_api_mapping_test.go @@ -8,14 +8,14 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/acm" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) // These tests need to be serialized, else resources get orphaned after "TooManyRequests" errors. -func TestAccAWSAPIGatewayV2ApiMapping(t *testing.T) { +func TestAccAWSAPIGatewayV2ApiMapping_basic(t *testing.T) { var certificateArn string rName := acctest.RandomWithPrefix("tf-acc-test") @@ -264,17 +264,17 @@ resource "aws_apigatewayv2_domain_name" "test" { } func testAccAWSAPIGatewayV2ApiMappingConfig_basic(rName, certificateArn string) string { - return testAccAWSAPIGatewayV2ApiMappingConfig_base(rName, certificateArn) + testAccAWSAPIGatewayV2StageConfig_basic(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2ApiMappingConfig_base(rName, certificateArn) + testAccAWSAPIGatewayV2StageConfig_basicWebSocket(rName) + ` resource "aws_apigatewayv2_api_mapping" "test" { api_id = "${aws_apigatewayv2_api.test.id}" domain_name = "${aws_apigatewayv2_domain_name.test.id}" stage = "${aws_apigatewayv2_stage.test.id}" } -`) +` } func testAccAWSAPIGatewayV2ApiMappingConfig_apiMappingKey(rName, certificateArn, apiMappingKey string) string { - return testAccAWSAPIGatewayV2ApiMappingConfig_base(rName, certificateArn) + testAccAWSAPIGatewayV2StageConfig_basic(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2ApiMappingConfig_base(rName, certificateArn) + testAccAWSAPIGatewayV2StageConfig_basicWebSocket(rName) + fmt.Sprintf(` resource "aws_apigatewayv2_api_mapping" "test" { api_id = "${aws_apigatewayv2_api.test.id}" domain_name = "${aws_apigatewayv2_domain_name.test.id}" diff --git a/aws/resource_aws_apigatewayv2_api_test.go b/aws/resource_aws_apigatewayv2_api_test.go index f95bfd8cea0..8b25d0e72a3 100644 --- a/aws/resource_aws_apigatewayv2_api_test.go +++ b/aws/resource_aws_apigatewayv2_api_test.go @@ -9,9 +9,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -374,10 +375,9 @@ func TestAccAWSAPIGatewayV2Api_CorsConfiguration(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAPIGatewayV2ApiDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2ApiDestroy, Steps: []resource.TestStep{ { Config: testAccAWSAPIGatewayV2ApiConfig_corsConfiguration(rName), @@ -389,12 +389,12 @@ func TestAccAWSAPIGatewayV2Api_CorsConfiguration(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "cors_configuration.#", "1"), resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_credentials", "false"), resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_headers.#", "1"), - resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_headers.2053999599", "Authorization"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "cors_configuration.0.allow_headers.*", "Authorization"), resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_methods.#", "2"), - resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_methods.4248514160", "GET"), - resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_methods.2928708052", "put"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "cors_configuration.0.allow_methods.*", "GET"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "cors_configuration.0.allow_methods.*", "put"), resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_origins.#", "1"), - resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_origins.89023941", "https://www.example.com"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "cors_configuration.0.allow_origins.*", "https://www.example.com"), resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.expose_headers.#", "0"), resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.max_age", "0"), resource.TestCheckResourceAttr(resourceName, "description", ""), @@ -422,12 +422,12 @@ func TestAccAWSAPIGatewayV2Api_CorsConfiguration(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_credentials", "true"), resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_headers.#", "0"), resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_methods.#", "1"), - resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_methods.163128923", "*"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "cors_configuration.0.allow_methods.*", "*"), resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_origins.#", "2"), - resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_origins.1868318776", "HTTP://WWW.EXAMPLE.ORG"), - resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.allow_origins.3551736600", "https://example.io"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "cors_configuration.0.allow_origins.*", "HTTP://WWW.EXAMPLE.ORG"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "cors_configuration.0.allow_origins.*", "https://example.io"), resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.expose_headers.#", "1"), - resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.expose_headers.115091893", "X-Api-Id"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "cors_configuration.0.expose_headers.*", "X-Api-Id"), resource.TestCheckResourceAttr(resourceName, "cors_configuration.0.max_age", "500"), resource.TestCheckResourceAttr(resourceName, "description", ""), testAccMatchResourceAttrRegionalARN(resourceName, "execution_arn", "execute-api", regexp.MustCompile(`.+`)), diff --git a/aws/resource_aws_apigatewayv2_authorizer.go b/aws/resource_aws_apigatewayv2_authorizer.go index e761cbf2ca6..39e79bee38f 100644 --- a/aws/resource_aws_apigatewayv2_authorizer.go +++ b/aws/resource_aws_apigatewayv2_authorizer.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsApiGatewayV2Authorizer() *schema.Resource { diff --git a/aws/resource_aws_apigatewayv2_authorizer_test.go b/aws/resource_aws_apigatewayv2_authorizer_test.go index 6135f2e4a37..fa1dacdeb92 100644 --- a/aws/resource_aws_apigatewayv2_authorizer_test.go +++ b/aws/resource_aws_apigatewayv2_authorizer_test.go @@ -6,9 +6,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSAPIGatewayV2Authorizer_basic(t *testing.T) { @@ -19,10 +20,9 @@ func TestAccAWSAPIGatewayV2Authorizer_basic(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAPIGatewayV2AuthorizerDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2AuthorizerDestroy, Steps: []resource.TestStep{ { Config: testAccAWSAPIGatewayV2AuthorizerConfig_basic(rName), @@ -32,7 +32,7 @@ func TestAccAWSAPIGatewayV2Authorizer_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "authorizer_type", "REQUEST"), resource.TestCheckResourceAttrPair(resourceName, "authorizer_uri", lambdaResourceName, "invoke_arn"), resource.TestCheckResourceAttr(resourceName, "identity_sources.#", "1"), - resource.TestCheckResourceAttr(resourceName, "identity_sources.645907014", "route.request.header.Auth"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "identity_sources.*", "route.request.header.Auth"), resource.TestCheckResourceAttr(resourceName, "jwt_configuration.#", "0"), resource.TestCheckResourceAttr(resourceName, "name", rName), ), @@ -79,10 +79,9 @@ func TestAccAWSAPIGatewayV2Authorizer_Credentials(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAPIGatewayV2AuthorizerDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2AuthorizerDestroy, Steps: []resource.TestStep{ { Config: testAccAWSAPIGatewayV2AuthorizerConfig_credentials(rName), @@ -92,7 +91,7 @@ func TestAccAWSAPIGatewayV2Authorizer_Credentials(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "authorizer_type", "REQUEST"), resource.TestCheckResourceAttrPair(resourceName, "authorizer_uri", lambdaResourceName, "invoke_arn"), resource.TestCheckResourceAttr(resourceName, "identity_sources.#", "1"), - resource.TestCheckResourceAttr(resourceName, "identity_sources.645907014", "route.request.header.Auth"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "identity_sources.*", "route.request.header.Auth"), resource.TestCheckResourceAttr(resourceName, "jwt_configuration.#", "0"), resource.TestCheckResourceAttr(resourceName, "name", rName), ), @@ -111,8 +110,8 @@ func TestAccAWSAPIGatewayV2Authorizer_Credentials(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "authorizer_type", "REQUEST"), resource.TestCheckResourceAttrPair(resourceName, "authorizer_uri", lambdaResourceName, "invoke_arn"), resource.TestCheckResourceAttr(resourceName, "identity_sources.#", "2"), - resource.TestCheckResourceAttr(resourceName, "identity_sources.645907014", "route.request.header.Auth"), - resource.TestCheckResourceAttr(resourceName, "identity_sources.4138478046", "route.request.querystring.Name"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "identity_sources.*", "route.request.header.Auth"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "identity_sources.*", "route.request.querystring.Name"), resource.TestCheckResourceAttr(resourceName, "jwt_configuration.#", "0"), resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("%s-updated", rName)), ), @@ -125,7 +124,7 @@ func TestAccAWSAPIGatewayV2Authorizer_Credentials(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "authorizer_type", "REQUEST"), resource.TestCheckResourceAttrPair(resourceName, "authorizer_uri", lambdaResourceName, "invoke_arn"), resource.TestCheckResourceAttr(resourceName, "identity_sources.#", "1"), - resource.TestCheckResourceAttr(resourceName, "identity_sources.645907014", "route.request.header.Auth"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "identity_sources.*", "route.request.header.Auth"), resource.TestCheckResourceAttr(resourceName, "jwt_configuration.#", "0"), resource.TestCheckResourceAttr(resourceName, "name", rName), ), @@ -141,10 +140,9 @@ func TestAccAWSAPIGatewayV2Authorizer_JWT(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAPIGatewayV2AuthorizerDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2AuthorizerDestroy, Steps: []resource.TestStep{ { Config: testAccAWSAPIGatewayV2AuthorizerConfig_jwt(rName), @@ -154,10 +152,10 @@ func TestAccAWSAPIGatewayV2Authorizer_JWT(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "authorizer_type", "JWT"), resource.TestCheckResourceAttr(resourceName, "authorizer_uri", ""), resource.TestCheckResourceAttr(resourceName, "identity_sources.#", "1"), - resource.TestCheckResourceAttr(resourceName, "identity_sources.2786136151", "$request.header.Authorization"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "identity_sources.*", "$request.header.Authorization"), resource.TestCheckResourceAttr(resourceName, "jwt_configuration.#", "1"), resource.TestCheckResourceAttr(resourceName, "jwt_configuration.0.audience.#", "1"), - resource.TestCheckResourceAttr(resourceName, "jwt_configuration.0.audience.1785148924", "test"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "jwt_configuration.0.audience.*", "test"), resource.TestCheckResourceAttr(resourceName, "name", rName), ), }, @@ -175,11 +173,11 @@ func TestAccAWSAPIGatewayV2Authorizer_JWT(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "authorizer_type", "JWT"), resource.TestCheckResourceAttr(resourceName, "authorizer_uri", ""), resource.TestCheckResourceAttr(resourceName, "identity_sources.#", "1"), - resource.TestCheckResourceAttr(resourceName, "identity_sources.2786136151", "$request.header.Authorization"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "identity_sources.*", "$request.header.Authorization"), resource.TestCheckResourceAttr(resourceName, "jwt_configuration.#", "1"), resource.TestCheckResourceAttr(resourceName, "jwt_configuration.0.audience.#", "2"), - resource.TestCheckResourceAttr(resourceName, "jwt_configuration.0.audience.1785148924", "test"), - resource.TestCheckResourceAttr(resourceName, "jwt_configuration.0.audience.2323796166", "testing"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "jwt_configuration.0.audience.*", "test"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "jwt_configuration.0.audience.*", "testing"), resource.TestCheckResourceAttr(resourceName, "name", rName), ), }, diff --git a/aws/resource_aws_apigatewayv2_deployment.go b/aws/resource_aws_apigatewayv2_deployment.go index 3aaf2edb621..b470c62ac9a 100644 --- a/aws/resource_aws_apigatewayv2_deployment.go +++ b/aws/resource_aws_apigatewayv2_deployment.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/apigatewayv2/waiter" ) diff --git a/aws/resource_aws_apigatewayv2_deployment_test.go b/aws/resource_aws_apigatewayv2_deployment_test.go index fc977974c1f..b6806d404c9 100644 --- a/aws/resource_aws_apigatewayv2_deployment_test.go +++ b/aws/resource_aws_apigatewayv2_deployment_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayV2Deployment_basic(t *testing.T) { diff --git a/aws/resource_aws_apigatewayv2_domain_name.go b/aws/resource_aws_apigatewayv2_domain_name.go index fe512f7d98b..741094e5167 100644 --- a/aws/resource_aws_apigatewayv2_domain_name.go +++ b/aws/resource_aws_apigatewayv2_domain_name.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_apigatewayv2_domain_name_test.go b/aws/resource_aws_apigatewayv2_domain_name_test.go index 3c1f504166a..2a5ae70234e 100644 --- a/aws/resource_aws_apigatewayv2_domain_name_test.go +++ b/aws/resource_aws_apigatewayv2_domain_name_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_apigatewayv2_integration.go b/aws/resource_aws_apigatewayv2_integration.go index eed4e89d9ec..a36934f16dc 100644 --- a/aws/resource_aws_apigatewayv2_integration.go +++ b/aws/resource_aws_apigatewayv2_integration.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsApiGatewayV2Integration() *schema.Resource { @@ -62,6 +62,14 @@ func resourceAwsApiGatewayV2Integration() *schema.Resource { Type: schema.TypeString, Optional: true, ValidateFunc: validateHTTPMethod(), + DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { + // Default HTTP method for Lambda integration is POST. + if v := d.Get("integration_type").(string); (v == apigatewayv2.IntegrationTypeAws || v == apigatewayv2.IntegrationTypeAwsProxy) && old == "POST" && new == "" { + return true + } + + return false + }, }, "integration_response_selection_expression": { Type: schema.TypeString, @@ -92,6 +100,13 @@ func resourceAwsApiGatewayV2Integration() *schema.Resource { apigatewayv2.PassthroughBehaviorNever, apigatewayv2.PassthroughBehaviorWhenNoTemplates, }, false), + DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { + // Not set for HTTP APIs. + if old == "" && new == apigatewayv2.PassthroughBehaviorWhenNoMatch { + return true + } + return false + }, }, "payload_format_version": { Type: schema.TypeString, @@ -102,10 +117,17 @@ func resourceAwsApiGatewayV2Integration() *schema.Resource { "2.0", }, false), }, + "request_parameters": { + Type: schema.TypeMap, + Optional: true, + // Length between [1-512]. + Elem: &schema.Schema{Type: schema.TypeString}, + }, "request_templates": { Type: schema.TypeMap, Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, + // Length between [0-32768]. + Elem: &schema.Schema{Type: schema.TypeString}, }, "template_selection_expression": { Type: schema.TypeString, @@ -117,6 +139,20 @@ func resourceAwsApiGatewayV2Integration() *schema.Resource { Default: 29000, ValidateFunc: validation.IntBetween(50, 29000), }, + "tls_config": { + Type: schema.TypeList, + Optional: true, + MinItems: 0, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "server_name_to_verify": { + Type: schema.TypeString, + Optional: true, + }, + }, + }, + }, }, } } @@ -155,6 +191,9 @@ func resourceAwsApiGatewayV2IntegrationCreate(d *schema.ResourceData, meta inter if v, ok := d.GetOk("payload_format_version"); ok { req.PayloadFormatVersion = aws.String(v.(string)) } + if v, ok := d.GetOk("request_parameters"); ok { + req.RequestParameters = stringMapToPointers(v.(map[string]interface{})) + } if v, ok := d.GetOk("request_templates"); ok { req.RequestTemplates = stringMapToPointers(v.(map[string]interface{})) } @@ -164,6 +203,9 @@ func resourceAwsApiGatewayV2IntegrationCreate(d *schema.ResourceData, meta inter if v, ok := d.GetOk("timeout_milliseconds"); ok { req.TimeoutInMillis = aws.Int64(int64(v.(int))) } + if v, ok := d.GetOk("tls_config"); ok { + req.TlsConfig = expandApiGateway2TlsConfig(v.([]interface{})) + } log.Printf("[DEBUG] Creating API Gateway v2 integration: %s", req) resp, err := conn.CreateIntegration(req) @@ -203,12 +245,19 @@ func resourceAwsApiGatewayV2IntegrationRead(d *schema.ResourceData, meta interfa d.Set("integration_uri", resp.IntegrationUri) d.Set("passthrough_behavior", resp.PassthroughBehavior) d.Set("payload_format_version", resp.PayloadFormatVersion) + err = d.Set("request_parameters", pointersMapToStringList(resp.RequestParameters)) + if err != nil { + return fmt.Errorf("error setting request_parameters: %s", err) + } err = d.Set("request_templates", pointersMapToStringList(resp.RequestTemplates)) if err != nil { return fmt.Errorf("error setting request_templates: %s", err) } d.Set("template_selection_expression", resp.TemplateSelectionExpression) d.Set("timeout_milliseconds", resp.TimeoutInMillis) + if err := d.Set("tls_config", flattenApiGateway2TlsConfig(resp.TlsConfig)); err != nil { + return fmt.Errorf("error setting tls_config: %s", err) + } return nil } @@ -247,6 +296,19 @@ func resourceAwsApiGatewayV2IntegrationUpdate(d *schema.ResourceData, meta inter if d.HasChange("payload_format_version") { req.PayloadFormatVersion = aws.String(d.Get("payload_format_version").(string)) } + if d.HasChange("request_parameters") { + o, n := d.GetChange("request_parameters") + add, del := diffStringMaps(o.(map[string]interface{}), n.(map[string]interface{})) + // Parameters are removed by setting the associated value to "". + for k := range del { + del[k] = aws.String("") + } + variables := del + for k, v := range add { + variables[k] = v + } + req.RequestParameters = variables + } if d.HasChange("request_templates") { req.RequestTemplates = stringMapToPointers(d.Get("request_templates").(map[string]interface{})) } @@ -256,6 +318,9 @@ func resourceAwsApiGatewayV2IntegrationUpdate(d *schema.ResourceData, meta inter if d.HasChange("timeout_milliseconds") { req.TimeoutInMillis = aws.Int64(int64(d.Get("timeout_milliseconds").(int))) } + if d.HasChange("tls_config") { + req.TlsConfig = expandApiGateway2TlsConfig(d.Get("tls_config").([]interface{})) + } log.Printf("[DEBUG] Updating API Gateway v2 integration: %s", req) _, err := conn.UpdateIntegration(req) @@ -312,3 +377,28 @@ func resourceAwsApiGatewayV2IntegrationImport(d *schema.ResourceData, meta inter return []*schema.ResourceData{d}, nil } + +func expandApiGateway2TlsConfig(vConfig []interface{}) *apigatewayv2.TlsConfigInput { + config := &apigatewayv2.TlsConfigInput{} + + if len(vConfig) == 0 || vConfig[0] == nil { + return config + } + mConfig := vConfig[0].(map[string]interface{}) + + if vServerNameToVerify, ok := mConfig["server_name_to_verify"].(string); ok && vServerNameToVerify != "" { + config.ServerNameToVerify = aws.String(vServerNameToVerify) + } + + return config +} + +func flattenApiGateway2TlsConfig(config *apigatewayv2.TlsConfig) []interface{} { + if config == nil { + return []interface{}{} + } + + return []interface{}{map[string]interface{}{ + "server_name_to_verify": aws.StringValue(config.ServerNameToVerify), + }} +} diff --git a/aws/resource_aws_apigatewayv2_integration_response.go b/aws/resource_aws_apigatewayv2_integration_response.go index 3ebc1fa0bc8..26a7de405c0 100644 --- a/aws/resource_aws_apigatewayv2_integration_response.go +++ b/aws/resource_aws_apigatewayv2_integration_response.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsApiGatewayV2IntegrationResponse() *schema.Resource { diff --git a/aws/resource_aws_apigatewayv2_integration_response_test.go b/aws/resource_aws_apigatewayv2_integration_response_test.go index 2fa471c21b7..61f61f76bba 100644 --- a/aws/resource_aws_apigatewayv2_integration_response_test.go +++ b/aws/resource_aws_apigatewayv2_integration_response_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayV2IntegrationResponse_basic(t *testing.T) { @@ -198,17 +198,17 @@ func testAccAWSAPIGatewayV2IntegrationResponseImportStateIdFunc(resourceName str } func testAccAWSAPIGatewayV2IntegrationResponseConfig_basic(rName string) string { - return testAccAWSAPIGatewayV2IntegrationConfig_basic(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2IntegrationConfig_basic(rName) + ` resource "aws_apigatewayv2_integration_response" "test" { api_id = "${aws_apigatewayv2_api.test.id}" integration_id = "${aws_apigatewayv2_integration.test.id}" integration_response_key = "/200/" } -`) +` } func testAccAWSAPIGatewayV2IntegrationResponseConfig_allAttributes(rName string) string { - return testAccAWSAPIGatewayV2IntegrationConfig_basic(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2IntegrationConfig_basic(rName) + ` resource "aws_apigatewayv2_integration_response" "test" { api_id = "${aws_apigatewayv2_api.test.id}" integration_id = "${aws_apigatewayv2_integration.test.id}" @@ -221,11 +221,11 @@ resource "aws_apigatewayv2_integration_response" "test" { "application/json" = "" } } -`) +` } func testAccAWSAPIGatewayV2IntegrationResponseConfig_allAttributesUpdated(rName string) string { - return testAccAWSAPIGatewayV2IntegrationConfig_basic(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2IntegrationConfig_basic(rName) + ` resource "aws_apigatewayv2_integration_response" "test" { api_id = "${aws_apigatewayv2_api.test.id}" integration_id = "${aws_apigatewayv2_integration.test.id}" @@ -239,5 +239,5 @@ resource "aws_apigatewayv2_integration_response" "test" { "application/xml" = "#set($percent=$number/100)" } } -`) +` } diff --git a/aws/resource_aws_apigatewayv2_integration_test.go b/aws/resource_aws_apigatewayv2_integration_test.go index 38de2e89b1b..3075265700e 100644 --- a/aws/resource_aws_apigatewayv2_integration_test.go +++ b/aws/resource_aws_apigatewayv2_integration_test.go @@ -6,12 +6,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAWSAPIGatewayV2Integration_basic(t *testing.T) { +func TestAccAWSAPIGatewayV2Integration_basicWebSocket(t *testing.T) { var apiId string var v apigatewayv2.GetIntegrationOutput resourceName := "aws_apigatewayv2_integration.test" @@ -37,6 +37,49 @@ func TestAccAWSAPIGatewayV2Integration_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "integration_uri", ""), resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_MATCH"), resource.TestCheckResourceAttr(resourceName, "payload_format_version", "1.0"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "0"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "0"), + resource.TestCheckResourceAttr(resourceName, "template_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "29000"), + resource.TestCheckResourceAttr(resourceName, "tls_config.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportStateIdFunc: testAccAWSAPIGatewayV2IntegrationImportStateIdFunc(resourceName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSAPIGatewayV2Integration_basicHttp(t *testing.T) { + var apiId string + var v apigatewayv2.GetIntegrationOutput + resourceName := "aws_apigatewayv2_integration.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2IntegrationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayV2IntegrationConfig_httpProxy(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2IntegrationExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "connection_id", ""), + resource.TestCheckResourceAttr(resourceName, "connection_type", "INTERNET"), + resource.TestCheckResourceAttr(resourceName, "content_handling_strategy", ""), + resource.TestCheckResourceAttr(resourceName, "credentials_arn", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "integration_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "integration_response_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "integration_type", "HTTP_PROXY"), + resource.TestCheckResourceAttr(resourceName, "integration_uri", "https://example.com"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", ""), + resource.TestCheckResourceAttr(resourceName, "payload_format_version", "1.0"), resource.TestCheckResourceAttr(resourceName, "request_templates.%", "0"), resource.TestCheckResourceAttr(resourceName, "template_selection_expression", ""), resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "29000"), @@ -101,10 +144,13 @@ func TestAccAWSAPIGatewayV2Integration_IntegrationTypeHttp(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "integration_uri", "http://www.example.com"), resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_MATCH"), resource.TestCheckResourceAttr(resourceName, "payload_format_version", "1.0"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "1"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.querystring.stage", "'value1'"), resource.TestCheckResourceAttr(resourceName, "request_templates.%", "1"), resource.TestCheckResourceAttr(resourceName, "request_templates.application/json", ""), resource.TestCheckResourceAttr(resourceName, "template_selection_expression", "$request.body.name"), resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "28999"), + resource.TestCheckResourceAttr(resourceName, "tls_config.#", "0"), ), }, { @@ -122,11 +168,15 @@ func TestAccAWSAPIGatewayV2Integration_IntegrationTypeHttp(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "integration_uri", "http://www.example.org"), resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_TEMPLATES"), resource.TestCheckResourceAttr(resourceName, "payload_format_version", "1.0"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "2"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.header.x-userid", "'value2'"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.integration.request.path.op", "'value3'"), resource.TestCheckResourceAttr(resourceName, "request_templates.%", "2"), resource.TestCheckResourceAttr(resourceName, "request_templates.application/json", "#set($number=42)"), resource.TestCheckResourceAttr(resourceName, "request_templates.application/xml", "#set($percent=$number/100)"), resource.TestCheckResourceAttr(resourceName, "template_selection_expression", "$request.body.id"), resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "51"), + resource.TestCheckResourceAttr(resourceName, "tls_config.#", "0"), ), }, { @@ -139,7 +189,7 @@ func TestAccAWSAPIGatewayV2Integration_IntegrationTypeHttp(t *testing.T) { }) } -func TestAccAWSAPIGatewayV2Integration_Lambda(t *testing.T) { +func TestAccAWSAPIGatewayV2Integration_LambdaWebSocket(t *testing.T) { var apiId string var v apigatewayv2.GetIntegrationOutput resourceName := "aws_apigatewayv2_integration.test" @@ -153,7 +203,7 @@ func TestAccAWSAPIGatewayV2Integration_Lambda(t *testing.T) { CheckDestroy: testAccCheckAWSAPIGatewayV2IntegrationDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayV2IntegrationConfig_lambda(rName), + Config: testAccAWSAPIGatewayV2IntegrationConfig_lambdaWebSocket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2IntegrationExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "connection_type", "INTERNET"), @@ -166,9 +216,55 @@ func TestAccAWSAPIGatewayV2Integration_Lambda(t *testing.T) { resource.TestCheckResourceAttrPair(resourceName, "integration_uri", lambdaResourceName, "invoke_arn"), resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "WHEN_NO_MATCH"), resource.TestCheckResourceAttr(resourceName, "payload_format_version", "1.0"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "0"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "0"), + resource.TestCheckResourceAttr(resourceName, "template_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "29000"), + resource.TestCheckResourceAttr(resourceName, "tls_config.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportStateIdFunc: testAccAWSAPIGatewayV2IntegrationImportStateIdFunc(resourceName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSAPIGatewayV2Integration_LambdaHttp(t *testing.T) { + var apiId string + var v apigatewayv2.GetIntegrationOutput + resourceName := "aws_apigatewayv2_integration.test" + callerIdentityDatasourceName := "data.aws_caller_identity.current" + lambdaResourceName := "aws_lambda_function.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2IntegrationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayV2IntegrationConfig_lambdaHttp(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2IntegrationExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "connection_type", "INTERNET"), + resource.TestCheckResourceAttr(resourceName, "content_handling_strategy", ""), + resource.TestCheckResourceAttrPair(resourceName, "credentials_arn", callerIdentityDatasourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "description", "Test Lambda"), + resource.TestCheckResourceAttr(resourceName, "integration_method", "POST"), + resource.TestCheckResourceAttr(resourceName, "integration_response_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "integration_type", "AWS_PROXY"), + resource.TestCheckResourceAttrPair(resourceName, "integration_uri", lambdaResourceName, "invoke_arn"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", ""), + resource.TestCheckResourceAttr(resourceName, "payload_format_version", "2.0"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "0"), resource.TestCheckResourceAttr(resourceName, "request_templates.%", "0"), resource.TestCheckResourceAttr(resourceName, "template_selection_expression", ""), resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "29000"), + resource.TestCheckResourceAttr(resourceName, "tls_config.#", "0"), ), }, { @@ -181,7 +277,7 @@ func TestAccAWSAPIGatewayV2Integration_Lambda(t *testing.T) { }) } -func TestAccAWSAPIGatewayV2Integration_VpcLink(t *testing.T) { +func TestAccAWSAPIGatewayV2Integration_VpcLinkWebSocket(t *testing.T) { var apiId string var v apigatewayv2.GetIntegrationOutput resourceName := "aws_apigatewayv2_integration.test" @@ -194,7 +290,7 @@ func TestAccAWSAPIGatewayV2Integration_VpcLink(t *testing.T) { CheckDestroy: testAccCheckAWSAPIGatewayV2IntegrationDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayV2IntegrationConfig_vpcLink(rName), + Config: testAccAWSAPIGatewayV2IntegrationConfig_vpcLinkWebSocket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2IntegrationExists(resourceName, &apiId, &v), resource.TestCheckResourceAttrPair(resourceName, "connection_id", vpcLinkResourceName, "id"), @@ -208,9 +304,84 @@ func TestAccAWSAPIGatewayV2Integration_VpcLink(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "integration_uri", "http://www.example.net"), resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", "NEVER"), resource.TestCheckResourceAttr(resourceName, "payload_format_version", "1.0"), + resource.TestCheckResourceAttr(resourceName, "request_parameters.%", "0"), resource.TestCheckResourceAttr(resourceName, "request_templates.%", "0"), resource.TestCheckResourceAttr(resourceName, "template_selection_expression", ""), resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "12345"), + resource.TestCheckResourceAttr(resourceName, "tls_config.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportStateIdFunc: testAccAWSAPIGatewayV2IntegrationImportStateIdFunc(resourceName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSAPIGatewayV2Integration_VpcLinkHttp(t *testing.T) { + var apiId string + var v apigatewayv2.GetIntegrationOutput + resourceName := "aws_apigatewayv2_integration.test" + vpcLinkResourceName := "aws_apigatewayv2_vpc_link.test" + lbListenerResourceName := "aws_lb_listener.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2IntegrationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayV2IntegrationConfig_vpcLinkHttp(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2IntegrationExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttrPair(resourceName, "connection_id", vpcLinkResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "connection_type", "VPC_LINK"), + resource.TestCheckResourceAttr(resourceName, "content_handling_strategy", ""), + resource.TestCheckResourceAttr(resourceName, "credentials_arn", ""), + resource.TestCheckResourceAttr(resourceName, "description", "Test private integration"), + resource.TestCheckResourceAttr(resourceName, "integration_method", "GET"), + resource.TestCheckResourceAttr(resourceName, "integration_response_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "integration_type", "HTTP_PROXY"), + resource.TestCheckResourceAttrPair(resourceName, "integration_uri", lbListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", ""), + resource.TestCheckResourceAttr(resourceName, "payload_format_version", "1.0"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "0"), + resource.TestCheckResourceAttr(resourceName, "template_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "5001"), + resource.TestCheckResourceAttr(resourceName, "tls_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "tls_config.0.server_name_to_verify", "www.example.com"), + ), + }, + { + ResourceName: resourceName, + ImportStateIdFunc: testAccAWSAPIGatewayV2IntegrationImportStateIdFunc(resourceName), + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSAPIGatewayV2IntegrationConfig_vpcLinkHttpUpdated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2IntegrationExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttrPair(resourceName, "connection_id", vpcLinkResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "connection_type", "VPC_LINK"), + resource.TestCheckResourceAttr(resourceName, "content_handling_strategy", ""), + resource.TestCheckResourceAttr(resourceName, "credentials_arn", ""), + resource.TestCheckResourceAttr(resourceName, "description", "Test private integration updated"), + resource.TestCheckResourceAttr(resourceName, "integration_method", "POST"), + resource.TestCheckResourceAttr(resourceName, "integration_response_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "integration_type", "HTTP_PROXY"), + resource.TestCheckResourceAttrPair(resourceName, "integration_uri", lbListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "passthrough_behavior", ""), + resource.TestCheckResourceAttr(resourceName, "payload_format_version", "1.0"), + resource.TestCheckResourceAttr(resourceName, "request_templates.%", "0"), + resource.TestCheckResourceAttr(resourceName, "template_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "timeout_milliseconds", "4999"), + resource.TestCheckResourceAttr(resourceName, "tls_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "tls_config.0.server_name_to_verify", "www.example.org"), ), }, { @@ -311,17 +482,72 @@ resource "aws_apigatewayv2_api" "test" { `, rName) } +func testAccAWSAPIGatewayV2IntegrationConfig_apiHttp(rName string) string { + return fmt.Sprintf(` +resource "aws_apigatewayv2_api" "test" { + name = %[1]q + protocol_type = "HTTP" +} +`, rName) +} + +func testAccAWSAPIGatewayV2IntegrationConfig_vpcLinkHttpBase(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2IntegrationConfig_apiHttp(rName), + testAccAWSAPIGatewayV2VpcLinkConfig_basic(rName), + fmt.Sprintf(` +resource "aws_lb" "test" { + name = %[1]q + + internal = true + load_balancer_type = "network" + subnets = ["${aws_subnet.test.*.id[0]}", "${aws_subnet.test.*.id[1]}"] + + tags = { + Name = %[1]q + } +} + +resource "aws_lb_target_group" "test" { + name = %[1]q + port = 80 + protocol = "TCP" + vpc_id = "${aws_vpc.test.id}" + + health_check { + port = 80 + protocol = "TCP" + } + + tags = { + Name = %[1]q + } +} + +resource "aws_lb_listener" "test" { + load_balancer_arn = "${aws_lb.test.arn}" + port = "80" + protocol = "TCP" + + default_action { + target_group_arn = "${aws_lb_target_group.test.arn}" + type = "forward" + } +} +`, rName)) +} + func testAccAWSAPIGatewayV2IntegrationConfig_basic(rName string) string { - return testAccAWSAPIGatewayV2IntegrationConfig_apiWebSocket(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2IntegrationConfig_apiWebSocket(rName) + ` resource "aws_apigatewayv2_integration" "test" { api_id = "${aws_apigatewayv2_api.test.id}" integration_type = "MOCK" } -`) +` } func testAccAWSAPIGatewayV2IntegrationConfig_integrationTypeHttp(rName string) string { - return testAccAWSAPIGatewayV2IntegrationConfig_apiWebSocket(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2IntegrationConfig_apiWebSocket(rName) + ` resource "aws_apigatewayv2_integration" "test" { api_id = "${aws_apigatewayv2_api.test.id}" integration_type = "HTTP" @@ -335,15 +561,19 @@ resource "aws_apigatewayv2_integration" "test" { template_selection_expression = "$request.body.name" timeout_milliseconds = 28999 + request_parameters = { + "integration.request.querystring.stage" = "'value1'" + } + request_templates = { "application/json" = "" } } -`) +` } func testAccAWSAPIGatewayV2IntegrationConfig_integrationTypeHttpUpdated(rName string) string { - return testAccAWSAPIGatewayV2IntegrationConfig_apiWebSocket(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2IntegrationConfig_apiWebSocket(rName) + ` resource "aws_apigatewayv2_integration" "test" { api_id = "${aws_apigatewayv2_api.test.id}" integration_type = "HTTP" @@ -357,16 +587,24 @@ resource "aws_apigatewayv2_integration" "test" { template_selection_expression = "$request.body.id" timeout_milliseconds = 51 + request_parameters = { + "integration.request.header.x-userid" = "'value2'" + "integration.request.path.op" = "'value3'" + } + request_templates = { "application/json" = "#set($number=42)" "application/xml" = "#set($percent=$number/100)" } } -`) +` } -func testAccAWSAPIGatewayV2IntegrationConfig_lambda(rName string) string { - return testAccAWSAPIGatewayV2IntegrationConfig_apiWebSocket(rName) + baseAccAWSLambdaConfig(rName, rName, rName) + fmt.Sprintf(` +func testAccAWSAPIGatewayV2IntegrationConfig_lambdaWebSocket(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2IntegrationConfig_apiWebSocket(rName), + baseAccAWSLambdaConfig(rName, rName, rName), + fmt.Sprintf(` data "aws_caller_identity" "current" {} resource "aws_lambda_function" "test" { @@ -381,19 +619,105 @@ resource "aws_apigatewayv2_integration" "test" { api_id = "${aws_apigatewayv2_api.test.id}" integration_type = "AWS" - connection_type = "INTERNET" - content_handling_strategy = "CONVERT_TO_TEXT" - credentials_arn = "${data.aws_caller_identity.current.arn}" - description = "Test Lambda" - integration_method = "POST" - integration_uri = "${aws_lambda_function.test.invoke_arn}" - passthrough_behavior = "WHEN_NO_MATCH" + connection_type = "INTERNET" + content_handling_strategy = "CONVERT_TO_TEXT" + credentials_arn = "${data.aws_caller_identity.current.arn}" + description = "Test Lambda" + integration_uri = "${aws_lambda_function.test.invoke_arn}" + passthrough_behavior = "WHEN_NO_MATCH" } -`, rName) +`, rName)) +} + +func testAccAWSAPIGatewayV2IntegrationConfig_lambdaHttp(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2IntegrationConfig_apiHttp(rName), + baseAccAWSLambdaConfig(rName, rName, rName), + fmt.Sprintf(` +data "aws_caller_identity" "current" {} + +resource "aws_lambda_function" "test" { + filename = "test-fixtures/lambdatest.zip" + function_name = %[1]q + role = "${aws_iam_role.iam_for_lambda.arn}" + handler = "index.handler" + runtime = "nodejs10.x" +} + +resource "aws_apigatewayv2_integration" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + integration_type = "AWS_PROXY" + + connection_type = "INTERNET" + credentials_arn = "${data.aws_caller_identity.current.arn}" + description = "Test Lambda" + integration_uri = "${aws_lambda_function.test.invoke_arn}" + + payload_format_version = "2.0" +} +`, rName)) +} + +func testAccAWSAPIGatewayV2IntegrationConfig_httpProxy(rName string) string { + return testAccAWSAPIGatewayV2IntegrationConfig_apiHttp(rName) + fmt.Sprintf(` +resource "aws_apigatewayv2_integration" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + integration_type = "HTTP_PROXY" + + integration_method = "GET" + integration_uri = "https://example.com" +} +`) +} + +func testAccAWSAPIGatewayV2IntegrationConfig_vpcLinkHttp(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2IntegrationConfig_vpcLinkHttpBase(rName), + fmt.Sprintf(` +resource "aws_apigatewayv2_integration" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + integration_type = "HTTP_PROXY" + + connection_type = "VPC_LINK" + connection_id = "${aws_apigatewayv2_vpc_link.test.id}" + description = "Test private integration" + integration_method = "GET" + integration_uri = "${aws_lb_listener.test.arn}" + timeout_milliseconds = 5001 + + tls_config { + server_name_to_verify = "www.example.com" + } +} +`)) } -func testAccAWSAPIGatewayV2IntegrationConfig_vpcLink(rName string) string { - return testAccAWSAPIGatewayV2IntegrationConfig_apiWebSocket(rName) + fmt.Sprintf(` +func testAccAWSAPIGatewayV2IntegrationConfig_vpcLinkHttpUpdated(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2IntegrationConfig_vpcLinkHttpBase(rName), + fmt.Sprintf(` +resource "aws_apigatewayv2_integration" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + integration_type = "HTTP_PROXY" + + connection_type = "VPC_LINK" + connection_id = "${aws_apigatewayv2_vpc_link.test.id}" + description = "Test private integration updated" + integration_method = "POST" + integration_uri = "${aws_lb_listener.test.arn}" + timeout_milliseconds = 4999 + + tls_config { + server_name_to_verify = "www.example.org" + } +} +`)) +} + +func testAccAWSAPIGatewayV2IntegrationConfig_vpcLinkWebSocket(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2IntegrationConfig_apiWebSocket(rName), + fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -426,6 +750,10 @@ resource "aws_lb" "test" { internal = true load_balancer_type = "network" subnets = ["${aws_subnet.test.id}"] + + tags = { + Name = %[1]q + } } resource "aws_api_gateway_vpc_link" "test" { @@ -446,5 +774,5 @@ resource "aws_apigatewayv2_integration" "test" { passthrough_behavior = "NEVER" timeout_milliseconds = 12345 } -`, rName) +`, rName)) } diff --git a/aws/resource_aws_apigatewayv2_model.go b/aws/resource_aws_apigatewayv2_model.go index dd297f4142e..8d03a67f7aa 100644 --- a/aws/resource_aws_apigatewayv2_model.go +++ b/aws/resource_aws_apigatewayv2_model.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsApiGatewayV2Model() *schema.Resource { diff --git a/aws/resource_aws_apigatewayv2_model_test.go b/aws/resource_aws_apigatewayv2_model_test.go index c30321d5fb3..c430b0edba2 100644 --- a/aws/resource_aws_apigatewayv2_model_test.go +++ b/aws/resource_aws_apigatewayv2_model_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayV2Model_basic(t *testing.T) { diff --git a/aws/resource_aws_apigatewayv2_route.go b/aws/resource_aws_apigatewayv2_route.go index 185973467b9..4ddb0537b92 100644 --- a/aws/resource_aws_apigatewayv2_route.go +++ b/aws/resource_aws_apigatewayv2_route.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsApiGatewayV2Route() *schema.Resource { @@ -187,6 +187,9 @@ func resourceAwsApiGatewayV2RouteUpdate(d *schema.ResourceData, meta interface{} if d.HasChange("request_models") { req.RequestModels = stringMapToPointers(d.Get("request_models").(map[string]interface{})) } + if d.HasChange("route_key") { + req.RouteKey = aws.String(d.Get("route_key").(string)) + } if d.HasChange("route_response_selection_expression") { req.RouteResponseSelectionExpression = aws.String(d.Get("route_response_selection_expression").(string)) } diff --git a/aws/resource_aws_apigatewayv2_route_response.go b/aws/resource_aws_apigatewayv2_route_response.go index ed8f895aad3..703d765db83 100644 --- a/aws/resource_aws_apigatewayv2_route_response.go +++ b/aws/resource_aws_apigatewayv2_route_response.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsApiGatewayV2RouteResponse() *schema.Resource { diff --git a/aws/resource_aws_apigatewayv2_route_response_test.go b/aws/resource_aws_apigatewayv2_route_response_test.go index d38970eaede..475323aee7c 100644 --- a/aws/resource_aws_apigatewayv2_route_response_test.go +++ b/aws/resource_aws_apigatewayv2_route_response_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayV2RouteResponse_basic(t *testing.T) { @@ -186,17 +186,17 @@ func testAccAWSAPIGatewayV2RouteResponseImportStateIdFunc(resourceName string) r } func testAccAWSAPIGatewayV2RouteResponseConfig_basic(rName string) string { - return testAccAWSAPIGatewayV2RouteConfig_basic(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2RouteConfig_basic(rName) + ` resource "aws_apigatewayv2_route_response" "test" { api_id = "${aws_apigatewayv2_api.test.id}" route_id = "${aws_apigatewayv2_route.test.id}" route_response_key = "$default" } -`) +` } func testAccAWSAPIGatewayV2RouteResponseConfig_model(rName string) string { - return testAccAWSAPIGatewayV2RouteConfig_model(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2RouteConfig_model(rName) + ` resource "aws_apigatewayv2_route_response" "test" { api_id = "${aws_apigatewayv2_api.test.id}" route_id = "${aws_apigatewayv2_route.test.id}" @@ -208,5 +208,5 @@ resource "aws_apigatewayv2_route_response" "test" { "test" = "${aws_apigatewayv2_model.test.name}" } } -`) +` } diff --git a/aws/resource_aws_apigatewayv2_route_test.go b/aws/resource_aws_apigatewayv2_route_test.go index 6023767df98..1d9d2da9880 100644 --- a/aws/resource_aws_apigatewayv2_route_test.go +++ b/aws/resource_aws_apigatewayv2_route_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAPIGatewayV2Route_basic(t *testing.T) { @@ -63,7 +63,7 @@ func TestAccAWSAPIGatewayV2Route_disappears(t *testing.T) { Config: testAccAWSAPIGatewayV2RouteConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2RouteExists(resourceName, &apiId, &v), - testAccCheckAWSAPIGatewayV2RouteDisappears(&apiId, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayV2Route(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -148,7 +148,7 @@ func TestAccAWSAPIGatewayV2Route_JwtAuthorization(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "model_selection_expression", ""), resource.TestCheckResourceAttr(resourceName, "operation_name", ""), resource.TestCheckResourceAttr(resourceName, "request_models.%", "0"), - resource.TestCheckResourceAttr(resourceName, "route_key", "$connect"), + resource.TestCheckResourceAttr(resourceName, "route_key", "GET /test"), resource.TestCheckResourceAttr(resourceName, "route_response_selection_expression", ""), resource.TestCheckResourceAttr(resourceName, "target", ""), ), @@ -170,7 +170,7 @@ func TestAccAWSAPIGatewayV2Route_JwtAuthorization(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "model_selection_expression", ""), resource.TestCheckResourceAttr(resourceName, "operation_name", ""), resource.TestCheckResourceAttr(resourceName, "request_models.%", "0"), - resource.TestCheckResourceAttr(resourceName, "route_key", "$connect"), + resource.TestCheckResourceAttr(resourceName, "route_key", "GET /test"), resource.TestCheckResourceAttr(resourceName, "route_response_selection_expression", ""), resource.TestCheckResourceAttr(resourceName, "target", ""), ), @@ -322,6 +322,57 @@ func TestAccAWSAPIGatewayV2Route_Target(t *testing.T) { }) } +func TestAccAWSAPIGatewayV2Route_UpdateRouteKey(t *testing.T) { + var apiId string + var v apigatewayv2.GetRouteOutput + resourceName := "aws_apigatewayv2_route.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2RouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayV2RouteConfig_routeKey(rName, "GET /path"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2RouteExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "api_key_required", "false"), + resource.TestCheckResourceAttr(resourceName, "authorization_type", apigatewayv2.AuthorizationTypeNone), + resource.TestCheckResourceAttr(resourceName, "authorizer_id", ""), + resource.TestCheckResourceAttr(resourceName, "model_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "operation_name", ""), + resource.TestCheckResourceAttr(resourceName, "request_models.%", "0"), + resource.TestCheckResourceAttr(resourceName, "route_key", "GET /path"), + resource.TestCheckResourceAttr(resourceName, "route_response_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "target", ""), + ), + }, + { + Config: testAccAWSAPIGatewayV2RouteConfig_routeKey(rName, "POST /new/path"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2RouteExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "api_key_required", "false"), + resource.TestCheckResourceAttr(resourceName, "authorization_type", apigatewayv2.AuthorizationTypeNone), + resource.TestCheckResourceAttr(resourceName, "authorizer_id", ""), + resource.TestCheckResourceAttr(resourceName, "model_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "operation_name", ""), + resource.TestCheckResourceAttr(resourceName, "request_models.%", "0"), + resource.TestCheckResourceAttr(resourceName, "route_key", "POST /new/path"), + resource.TestCheckResourceAttr(resourceName, "route_response_selection_expression", ""), + resource.TestCheckResourceAttr(resourceName, "target", ""), + ), + }, + { + ResourceName: resourceName, + ImportStateIdFunc: testAccAWSAPIGatewayV2RouteImportStateIdFunc(resourceName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func testAccCheckAWSAPIGatewayV2RouteDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).apigatewayv2conn @@ -347,19 +398,6 @@ func testAccCheckAWSAPIGatewayV2RouteDestroy(s *terraform.State) error { return nil } -func testAccCheckAWSAPIGatewayV2RouteDisappears(apiId *string, v *apigatewayv2.GetRouteOutput) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).apigatewayv2conn - - _, err := conn.DeleteRoute(&apigatewayv2.DeleteRouteInput{ - ApiId: apiId, - RouteId: v.RouteId, - }) - - return err - } -} - func testAccCheckAWSAPIGatewayV2RouteExists(n string, vApiId *string, v *apigatewayv2.GetRouteOutput) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -421,17 +459,26 @@ resource "aws_apigatewayv2_api" "test" { `, rName) } +func testAccAWSAPIGatewayV2RouteConfig_apiHttp(rName string) string { + return fmt.Sprintf(` +resource "aws_apigatewayv2_api" "test" { + name = %[1]q + protocol_type = "HTTP" +} +`, rName) +} + func testAccAWSAPIGatewayV2RouteConfig_basic(rName string) string { - return testAccAWSAPIGatewayV2RouteConfig_apiWebSocket(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2RouteConfig_apiWebSocket(rName) + ` resource "aws_apigatewayv2_route" "test" { api_id = "${aws_apigatewayv2_api.test.id}" route_key = "$default" } -`) +` } func testAccAWSAPIGatewayV2RouteConfig_authorizer(rName string) string { - return testAccAWSAPIGatewayV2AuthorizerConfig_basic(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2AuthorizerConfig_basic(rName) + ` resource "aws_apigatewayv2_route" "test" { api_id = "${aws_apigatewayv2_api.test.id}" route_key = "$connect" @@ -439,46 +486,46 @@ resource "aws_apigatewayv2_route" "test" { authorization_type = "CUSTOM" authorizer_id = "${aws_apigatewayv2_authorizer.test.id}" } -`) +` } func testAccAWSAPIGatewayV2RouteConfig_authorizerUpdated(rName string) string { - return testAccAWSAPIGatewayV2AuthorizerConfig_basic(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2AuthorizerConfig_basic(rName) + ` resource "aws_apigatewayv2_route" "test" { api_id = "${aws_apigatewayv2_api.test.id}" route_key = "$connect" authorization_type = "AWS_IAM" } -`) +` } func testAccAWSAPIGatewayV2RouteConfig_jwtAuthorization(rName string) string { - return testAccAWSAPIGatewayV2AuthorizerConfig_jwt(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2AuthorizerConfig_jwt(rName) + ` resource "aws_apigatewayv2_route" "test" { api_id = "${aws_apigatewayv2_api.test.id}" - route_key = "$connect" + route_key = "GET /test" authorization_type = "JWT" authorizer_id = "${aws_apigatewayv2_authorizer.test.id}" authorization_scopes = ["user.id", "user.email"] } -`) +` } func testAccAWSAPIGatewayV2RouteConfig_jwtAuthorizationUpdated(rName string) string { - return testAccAWSAPIGatewayV2AuthorizerConfig_jwt(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2AuthorizerConfig_jwt(rName) + ` resource "aws_apigatewayv2_route" "test" { api_id = "${aws_apigatewayv2_api.test.id}" - route_key = "$connect" + route_key = "GET /test" authorization_type = "JWT" authorizer_id = "${aws_apigatewayv2_authorizer.test.id}" authorization_scopes = ["user.email"] } -`) +` } func testAccAWSAPIGatewayV2RouteConfig_model(rName string) string { @@ -495,7 +542,7 @@ func testAccAWSAPIGatewayV2RouteConfig_model(rName string) string { } ` - return testAccAWSAPIGatewayV2ModelConfig_basic(rName, schema) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2ModelConfig_basic(rName, schema) + ` resource "aws_apigatewayv2_route" "test" { api_id = "${aws_apigatewayv2_api.test.id}" route_key = "$default" @@ -506,12 +553,23 @@ resource "aws_apigatewayv2_route" "test" { "test" = "${aws_apigatewayv2_model.test.name}" } } -`) +` +} + +func testAccAWSAPIGatewayV2RouteConfig_routeKey(rName, routeKey string) string { + return composeConfig( + testAccAWSAPIGatewayV2RouteConfig_apiHttp(rName), + fmt.Sprintf(` +resource "aws_apigatewayv2_route" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + route_key = %[1]q +} +`, routeKey)) } // Simple attributes - No authorization, models or targets. func testAccAWSAPIGatewayV2RouteConfig_simpleAttributes(rName string) string { - return testAccAWSAPIGatewayV2RouteConfig_apiWebSocket(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2RouteConfig_apiWebSocket(rName) + ` resource "aws_apigatewayv2_route" "test" { api_id = "${aws_apigatewayv2_api.test.id}" route_key = "$default" @@ -520,16 +578,16 @@ resource "aws_apigatewayv2_route" "test" { operation_name = "GET" route_response_selection_expression = "$default" } -`) +` } func testAccAWSAPIGatewayV2RouteConfig_target(rName string) string { - return testAccAWSAPIGatewayV2IntegrationConfig_basic(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2IntegrationConfig_basic(rName) + ` resource "aws_apigatewayv2_route" "test" { api_id = "${aws_apigatewayv2_api.test.id}" route_key = "$default" target = "integrations/${aws_apigatewayv2_integration.test.id}" } -`) +` } diff --git a/aws/resource_aws_apigatewayv2_stage.go b/aws/resource_aws_apigatewayv2_stage.go index 7817fd79369..ffbfaa37f33 100644 --- a/aws/resource_aws_apigatewayv2_stage.go +++ b/aws/resource_aws_apigatewayv2_stage.go @@ -9,12 +9,16 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) +const ( + apigatewayv2DefaultStageName = "$default" +) + func resourceAwsApiGatewayV2Stage() *schema.Resource { return &schema.Resource{ Create: resourceAwsApiGatewayV2StageCreate, @@ -37,9 +41,6 @@ func resourceAwsApiGatewayV2Stage() *schema.Resource { Type: schema.TypeString, Required: true, ValidateFunc: validateArn, - StateFunc: func(v interface{}) string { - return strings.TrimSuffix(v.(string), ":*") - }, }, "format": { Type: schema.TypeString, @@ -87,7 +88,7 @@ func resourceAwsApiGatewayV2Stage() *schema.Resource { "logging_level": { Type: schema.TypeString, Optional: true, - Default: apigatewayv2.LoggingLevelOff, + Computed: true, ValidateFunc: validation.StringInSlice([]string{ apigatewayv2.LoggingLevelError, apigatewayv2.LoggingLevelInfo, @@ -108,6 +109,7 @@ func resourceAwsApiGatewayV2Stage() *schema.Resource { "deployment_id": { Type: schema.TypeString, Optional: true, + Computed: true, }, "description": { Type: schema.TypeString, @@ -147,7 +149,7 @@ func resourceAwsApiGatewayV2Stage() *schema.Resource { "logging_level": { Type: schema.TypeString, Optional: true, - Default: apigatewayv2.LoggingLevelOff, + Computed: true, ValidateFunc: validation.StringInSlice([]string{ apigatewayv2.LoggingLevelError, apigatewayv2.LoggingLevelInfo, @@ -183,8 +185,19 @@ func resourceAwsApiGatewayV2Stage() *schema.Resource { func resourceAwsApiGatewayV2StageCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).apigatewayv2conn + apiId := d.Get("api_id").(string) + + apiOutput, err := conn.GetApi(&apigatewayv2.GetApiInput{ + ApiId: aws.String(apiId), + }) + if err != nil { + return fmt.Errorf("error reading API Gateway v2 API (%s): %s", apiId, err) + } + + protocolType := aws.StringValue(apiOutput.ProtocolType) + req := &apigatewayv2.CreateStageInput{ - ApiId: aws.String(d.Get("api_id").(string)), + ApiId: aws.String(apiId), AutoDeploy: aws.Bool(d.Get("auto_deploy").(bool)), StageName: aws.String(d.Get("name").(string)), Tags: keyvaluetags.New(d.Get("tags").(map[string]interface{})).IgnoreAws().Apigatewayv2Tags(), @@ -196,7 +209,7 @@ func resourceAwsApiGatewayV2StageCreate(d *schema.ResourceData, meta interface{} req.ClientCertificateId = aws.String(v.(string)) } if v, ok := d.GetOk("default_route_settings"); ok { - req.DefaultRouteSettings = expandApiGatewayV2DefaultRouteSettings(v.([]interface{})) + req.DefaultRouteSettings = expandApiGatewayV2DefaultRouteSettings(v.([]interface{}), protocolType) } if v, ok := d.GetOk("deployment_id"); ok { req.DeploymentId = aws.String(v.(string)) @@ -205,7 +218,7 @@ func resourceAwsApiGatewayV2StageCreate(d *schema.ResourceData, meta interface{} req.Description = aws.String(v.(string)) } if v, ok := d.GetOk("route_settings"); ok { - req.RouteSettings = expandApiGatewayV2RouteSettings(v.(*schema.Set)) + req.RouteSettings = expandApiGatewayV2RouteSettings(v.(*schema.Set), protocolType) } if v, ok := d.GetOk("stage_variables"); ok { req.StageVariables = stringMapToPointers(v.(map[string]interface{})) @@ -269,7 +282,6 @@ func resourceAwsApiGatewayV2StageRead(d *schema.ResourceData, meta interface{}) Resource: fmt.Sprintf("%s/%s", apiId, stageName), }.String() d.Set("execution_arn", executionArn) - d.Set("invoke_url", fmt.Sprintf("wss://%s.execute-api.%s.amazonaws.com/%s", apiId, region, stageName)) d.Set("name", stageName) err = d.Set("route_settings", flattenApiGatewayV2RouteSettings(resp.RouteSettings)) if err != nil { @@ -283,6 +295,24 @@ func resourceAwsApiGatewayV2StageRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("error setting tags: %s", err) } + apiOutput, err := conn.GetApi(&apigatewayv2.GetApiInput{ + ApiId: aws.String(apiId), + }) + if err != nil { + return fmt.Errorf("error reading API Gateway v2 API (%s): %s", apiId, err) + } + + switch aws.StringValue(apiOutput.ProtocolType) { + case apigatewayv2.ProtocolTypeWebsocket: + d.Set("invoke_url", fmt.Sprintf("wss://%s.execute-api.%s.amazonaws.com/%s", apiId, region, stageName)) + case apigatewayv2.ProtocolTypeHttp: + if stageName == apigatewayv2DefaultStageName { + d.Set("invoke_url", fmt.Sprintf("https://%s.execute-api.%s.amazonaws.com/", apiId, region)) + } else { + d.Set("invoke_url", fmt.Sprintf("https://%s.execute-api.%s.amazonaws.com/%s", apiId, region, stageName)) + } + } + return nil } @@ -292,8 +322,19 @@ func resourceAwsApiGatewayV2StageUpdate(d *schema.ResourceData, meta interface{} if d.HasChanges("access_log_settings", "auto_deploy", "client_certificate_id", "default_route_settings", "deployment_id", "description", "route_settings", "stage_variables") { + apiId := d.Get("api_id").(string) + + apiOutput, err := conn.GetApi(&apigatewayv2.GetApiInput{ + ApiId: aws.String(apiId), + }) + if err != nil { + return fmt.Errorf("error reading API Gateway v2 API (%s): %s", apiId, err) + } + + protocolType := aws.StringValue(apiOutput.ProtocolType) + req := &apigatewayv2.UpdateStageInput{ - ApiId: aws.String(d.Get("api_id").(string)), + ApiId: aws.String(apiId), StageName: aws.String(d.Id()), } if d.HasChange("access_log_settings") { @@ -306,7 +347,7 @@ func resourceAwsApiGatewayV2StageUpdate(d *schema.ResourceData, meta interface{} req.ClientCertificateId = aws.String(d.Get("client_certificate_id").(string)) } if d.HasChange("default_route_settings") { - req.DefaultRouteSettings = expandApiGatewayV2DefaultRouteSettings(d.Get("default_route_settings").([]interface{})) + req.DefaultRouteSettings = expandApiGatewayV2DefaultRouteSettings(d.Get("default_route_settings").([]interface{}), protocolType) } if d.HasChange("deployment_id") { req.DeploymentId = aws.String(d.Get("deployment_id").(string)) @@ -315,7 +356,7 @@ func resourceAwsApiGatewayV2StageUpdate(d *schema.ResourceData, meta interface{} req.Description = aws.String(d.Get("description").(string)) } if d.HasChange("route_settings") { - req.RouteSettings = expandApiGatewayV2RouteSettings(d.Get("route_settings").(*schema.Set)) + req.RouteSettings = expandApiGatewayV2RouteSettings(d.Get("route_settings").(*schema.Set), protocolType) } if d.HasChange("stage_variables") { o, n := d.GetChange("stage_variables") @@ -332,7 +373,7 @@ func resourceAwsApiGatewayV2StageUpdate(d *schema.ResourceData, meta interface{} } log.Printf("[DEBUG] Updating API Gateway v2 stage: %s", req) - _, err := conn.UpdateStage(req) + _, err = conn.UpdateStage(req) if err != nil { return fmt.Errorf("error updating API Gateway v2 stage (%s): %s", d.Id(), err) } @@ -424,7 +465,7 @@ func flattenApiGatewayV2AccessLogSettings(settings *apigatewayv2.AccessLogSettin }} } -func expandApiGatewayV2DefaultRouteSettings(vSettings []interface{}) *apigatewayv2.RouteSettings { +func expandApiGatewayV2DefaultRouteSettings(vSettings []interface{}, protocolType string) *apigatewayv2.RouteSettings { routeSettings := &apigatewayv2.RouteSettings{} if len(vSettings) == 0 || vSettings[0] == nil { @@ -432,13 +473,13 @@ func expandApiGatewayV2DefaultRouteSettings(vSettings []interface{}) *apigateway } mSettings := vSettings[0].(map[string]interface{}) - if vDataTraceEnabled, ok := mSettings["data_trace_enabled"].(bool); ok { + if vDataTraceEnabled, ok := mSettings["data_trace_enabled"].(bool); ok && protocolType == apigatewayv2.ProtocolTypeWebsocket { routeSettings.DataTraceEnabled = aws.Bool(vDataTraceEnabled) } if vDetailedMetricsEnabled, ok := mSettings["detailed_metrics_enabled"].(bool); ok { routeSettings.DetailedMetricsEnabled = aws.Bool(vDetailedMetricsEnabled) } - if vLoggingLevel, ok := mSettings["logging_level"].(string); ok && vLoggingLevel != "" { + if vLoggingLevel, ok := mSettings["logging_level"].(string); ok && vLoggingLevel != "" && protocolType == apigatewayv2.ProtocolTypeWebsocket { routeSettings.LoggingLevel = aws.String(vLoggingLevel) } if vThrottlingBurstLimit, ok := mSettings["throttling_burst_limit"].(int); ok { @@ -465,7 +506,7 @@ func flattenApiGatewayV2DefaultRouteSettings(routeSettings *apigatewayv2.RouteSe }} } -func expandApiGatewayV2RouteSettings(vSettings *schema.Set) map[string]*apigatewayv2.RouteSettings { +func expandApiGatewayV2RouteSettings(vSettings *schema.Set, protocolType string) map[string]*apigatewayv2.RouteSettings { settings := map[string]*apigatewayv2.RouteSettings{} for _, v := range vSettings.List() { @@ -473,13 +514,13 @@ func expandApiGatewayV2RouteSettings(vSettings *schema.Set) map[string]*apigatew mSettings := v.(map[string]interface{}) - if v, ok := mSettings["data_trace_enabled"].(bool); ok { + if v, ok := mSettings["data_trace_enabled"].(bool); ok && protocolType == apigatewayv2.ProtocolTypeWebsocket { routeSettings.DataTraceEnabled = aws.Bool(v) } if v, ok := mSettings["detailed_metrics_enabled"].(bool); ok { routeSettings.DetailedMetricsEnabled = aws.Bool(v) } - if v, ok := mSettings["logging_level"].(string); ok { + if v, ok := mSettings["logging_level"].(string); ok && v != "" && protocolType == apigatewayv2.ProtocolTypeWebsocket { routeSettings.LoggingLevel = aws.String(v) } if v, ok := mSettings["throttling_burst_limit"].(int); ok { diff --git a/aws/resource_aws_apigatewayv2_stage_test.go b/aws/resource_aws_apigatewayv2_stage_test.go index 1fd65816371..019a78da619 100644 --- a/aws/resource_aws_apigatewayv2_stage_test.go +++ b/aws/resource_aws_apigatewayv2_stage_test.go @@ -3,17 +3,17 @@ package aws import ( "fmt" "regexp" - "strings" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) -func TestAccAWSAPIGatewayV2Stage_basic(t *testing.T) { +func TestAccAWSAPIGatewayV2Stage_basicWebSocket(t *testing.T) { var apiId string var v apigatewayv2.GetStageOutput resourceName := "aws_apigatewayv2_stage.test" @@ -25,11 +25,11 @@ func TestAccAWSAPIGatewayV2Stage_basic(t *testing.T) { CheckDestroy: testAccCheckAWSAPIGatewayV2StageDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayV2StageConfig_basic(rName), + Config: testAccAWSAPIGatewayV2StageConfig_basicWebSocket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), - testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(fmt.Sprintf("/apis/.+/stages/%s", rName))), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), @@ -40,7 +40,7 @@ func TestAccAWSAPIGatewayV2Stage_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), resource.TestCheckResourceAttr(resourceName, "description", ""), - testAccMatchResourceAttrRegionalARN(resourceName, "execution_arn", "execute-api", regexp.MustCompile(fmt.Sprintf(".+/%s", rName))), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("wss://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), @@ -58,6 +58,167 @@ func TestAccAWSAPIGatewayV2Stage_basic(t *testing.T) { }) } +func TestAccAWSAPIGatewayV2Stage_basicHttp(t *testing.T) { + var apiId string + var v apigatewayv2.GetStageOutput + resourceName := "aws_apigatewayv2_stage.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2StageDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayV2StageConfig_basicHttp(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), + resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("https://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportStateIdFunc: testAccAWSAPIGatewayV2StageImportStateIdFunc(resourceName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSAPIGatewayV2Stage_defaultHttpStage(t *testing.T) { + var apiId string + var v apigatewayv2.GetStageOutput + resourceName := "aws_apigatewayv2_stage.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2StageDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayV2StageConfig_defaultHttpStage(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), + resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("https://.+\\.execute-api\\.%s.amazonaws\\.com/", testAccGetRegion()))), + resource.TestCheckResourceAttr(resourceName, "name", "$default"), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportStateIdFunc: testAccAWSAPIGatewayV2StageImportStateIdFunc(resourceName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSAPIGatewayV2Stage_autoDeployHttp(t *testing.T) { + var apiId string + var v apigatewayv2.GetStageOutput + resourceName := "aws_apigatewayv2_stage.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2StageDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayV2StageConfig_autoDeployHttp(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), + resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("https://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + Config: testAccAWSAPIGatewayV2StageConfig_autoDeployHttp(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "true"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), + // The stage's DeploymentId attribute will be set asynchronously as deployments are done automatically. + // resource.TestCheckResourceAttrSet(resourceName, "deployment_id"), + resource.TestCheckResourceAttr(resourceName, "description", ""), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), + resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("https://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportStateIdFunc: testAccAWSAPIGatewayV2StageImportStateIdFunc(resourceName), + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"deployment_id"}, + }, + }, + }) +} + func TestAccAWSAPIGatewayV2Stage_disappears(t *testing.T) { var apiId string var v apigatewayv2.GetStageOutput @@ -70,10 +231,10 @@ func TestAccAWSAPIGatewayV2Stage_disappears(t *testing.T) { CheckDestroy: testAccCheckAWSAPIGatewayV2StageDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayV2StageConfig_basic(rName), + Config: testAccAWSAPIGatewayV2StageConfig_basicWebSocket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), - testAccCheckAWSAPIGatewayV2StageDisappears(&apiId, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayV2Stage(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -98,9 +259,9 @@ func TestAccAWSAPIGatewayV2Stage_AccessLogSettings(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "1"), - testAccCheckAWSAPIGatewayV2StageAccessLogDestinationArn(resourceName, "access_log_settings.0.destination_arn", cloudWatchResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "access_log_settings.0.destination_arn", cloudWatchResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "access_log_settings.0.format", "$context.identity.sourceIp $context.requestId"), - testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(fmt.Sprintf("/apis/.+/stages/%s", rName))), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), @@ -111,7 +272,7 @@ func TestAccAWSAPIGatewayV2Stage_AccessLogSettings(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), resource.TestCheckResourceAttr(resourceName, "description", ""), - testAccMatchResourceAttrRegionalARN(resourceName, "execution_arn", "execute-api", regexp.MustCompile(fmt.Sprintf(".+/%s", rName))), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("wss://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), @@ -130,7 +291,7 @@ func TestAccAWSAPIGatewayV2Stage_AccessLogSettings(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "1"), - testAccCheckAWSAPIGatewayV2StageAccessLogDestinationArn(resourceName, "access_log_settings.0.destination_arn", cloudWatchResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "access_log_settings.0.destination_arn", cloudWatchResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "access_log_settings.0.format", "$context.requestId"), resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), @@ -169,7 +330,7 @@ func TestAccAWSAPIGatewayV2Stage_ClientCertificateIdAndDescription(t *testing.T) Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), - testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(fmt.Sprintf("/apis/.+/stages/%s", rName))), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), resource.TestCheckResourceAttrPair(resourceName, "client_certificate_id", certificateResourceName, "id"), resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), @@ -180,7 +341,7 @@ func TestAccAWSAPIGatewayV2Stage_ClientCertificateIdAndDescription(t *testing.T) resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), resource.TestCheckResourceAttr(resourceName, "description", "Test stage"), - testAccMatchResourceAttrRegionalARN(resourceName, "execution_arn", "execute-api", regexp.MustCompile(fmt.Sprintf(".+/%s", rName))), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("wss://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), @@ -199,8 +360,8 @@ func TestAccAWSAPIGatewayV2Stage_ClientCertificateIdAndDescription(t *testing.T) Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), - testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(fmt.Sprintf("/apis/.+/stages/%s", rName))), - resource.TestCheckResourceAttr(resourceName, "auto_deploy", "true"), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), @@ -210,7 +371,7 @@ func TestAccAWSAPIGatewayV2Stage_ClientCertificateIdAndDescription(t *testing.T) resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), resource.TestCheckResourceAttr(resourceName, "description", "Test stage updated"), - testAccMatchResourceAttrRegionalARN(resourceName, "execution_arn", "execute-api", regexp.MustCompile(fmt.Sprintf(".+/%s", rName))), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("wss://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), @@ -222,7 +383,7 @@ func TestAccAWSAPIGatewayV2Stage_ClientCertificateIdAndDescription(t *testing.T) }) } -func TestAccAWSAPIGatewayV2Stage_DefaultRouteSettings(t *testing.T) { +func TestAccAWSAPIGatewayV2Stage_DefaultRouteSettingsWebSocket(t *testing.T) { var apiId string var v apigatewayv2.GetStageOutput resourceName := "aws_apigatewayv2_stage.test" @@ -234,11 +395,11 @@ func TestAccAWSAPIGatewayV2Stage_DefaultRouteSettings(t *testing.T) { CheckDestroy: testAccCheckAWSAPIGatewayV2StageDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayV2StageConfig_defaultRouteSettings(rName), + Config: testAccAWSAPIGatewayV2StageConfig_defaultRouteSettingsWebSocket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), - testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(fmt.Sprintf("/apis/.+/stages/%s", rName))), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), @@ -249,7 +410,31 @@ func TestAccAWSAPIGatewayV2Stage_DefaultRouteSettings(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "8888"), resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), resource.TestCheckResourceAttr(resourceName, "description", ""), - testAccMatchResourceAttrRegionalARN(resourceName, "execution_arn", "execute-api", regexp.MustCompile(fmt.Sprintf(".+/%s", rName))), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), + resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("wss://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + Config: testAccAWSAPIGatewayV2StageConfig_defaultRouteSettingsWebSocketUpdated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", "INFO"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "1111"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "9999"), + resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("wss://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), @@ -264,7 +449,7 @@ func TestAccAWSAPIGatewayV2Stage_DefaultRouteSettings(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSAPIGatewayV2StageConfig_basic(rName), + Config: testAccAWSAPIGatewayV2StageConfig_basicWebSocket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), @@ -273,7 +458,97 @@ func TestAccAWSAPIGatewayV2Stage_DefaultRouteSettings(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", "OFF"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", "INFO"), // No drift detection if not configured + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + }, + }) +} + +func TestAccAWSAPIGatewayV2Stage_DefaultRouteSettingsHttp(t *testing.T) { + var apiId string + var v apigatewayv2.GetStageOutput + resourceName := "aws_apigatewayv2_stage.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2StageDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayV2StageConfig_defaultRouteSettingsHttp(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "2222"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "8888"), + resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), + resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("https://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + Config: testAccAWSAPIGatewayV2StageConfig_defaultRouteSettingsHttpUpdated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "1111"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "9999"), + resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), + resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("https://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportStateIdFunc: testAccAWSAPIGatewayV2StageImportStateIdFunc(resourceName), + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSAPIGatewayV2StageConfig_basicHttp(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", ""), resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), @@ -305,7 +580,7 @@ func TestAccAWSAPIGatewayV2Stage_Deployment(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), - testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(fmt.Sprintf("/apis/.+/stages/%s", rName))), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), @@ -316,7 +591,7 @@ func TestAccAWSAPIGatewayV2Stage_Deployment(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), resource.TestCheckResourceAttrPair(resourceName, "deployment_id", deploymentResourceName, "id"), resource.TestCheckResourceAttr(resourceName, "description", ""), - testAccMatchResourceAttrRegionalARN(resourceName, "execution_arn", "execute-api", regexp.MustCompile(fmt.Sprintf(".+/%s", rName))), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("wss://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), @@ -334,24 +609,23 @@ func TestAccAWSAPIGatewayV2Stage_Deployment(t *testing.T) { }) } -func TestAccAWSAPIGatewayV2Stage_RouteSettings(t *testing.T) { +func TestAccAWSAPIGatewayV2Stage_RouteSettingsWebSocket(t *testing.T) { var apiId string var v apigatewayv2.GetStageOutput resourceName := "aws_apigatewayv2_stage.test" rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAPIGatewayV2StageDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2StageDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAPIGatewayV2StageConfig_routeSettings(rName), + Config: testAccAWSAPIGatewayV2StageConfig_routeSettingsWebSocket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), - testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(fmt.Sprintf("/apis/.+/stages/%s", rName))), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), @@ -362,22 +636,71 @@ func TestAccAWSAPIGatewayV2Stage_RouteSettings(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), resource.TestCheckResourceAttr(resourceName, "description", ""), - testAccMatchResourceAttrRegionalARN(resourceName, "execution_arn", "execute-api", regexp.MustCompile(fmt.Sprintf(".+/%s", rName))), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("wss://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "route_settings.#", "2"), - resource.TestCheckResourceAttr(resourceName, "route_settings.4093656941.data_trace_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "route_settings.4093656941.detailed_metrics_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "route_settings.4093656941.logging_level", "OFF"), - resource.TestCheckResourceAttr(resourceName, "route_settings.4093656941.route_key", "$default"), - resource.TestCheckResourceAttr(resourceName, "route_settings.4093656941.throttling_burst_limit", "0"), - resource.TestCheckResourceAttr(resourceName, "route_settings.4093656941.throttling_rate_limit", "0"), - resource.TestCheckResourceAttr(resourceName, "route_settings.3867839051.data_trace_enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "route_settings.3867839051.detailed_metrics_enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "route_settings.3867839051.logging_level", "ERROR"), - resource.TestCheckResourceAttr(resourceName, "route_settings.3867839051.route_key", "$connect"), - resource.TestCheckResourceAttr(resourceName, "route_settings.3867839051.throttling_burst_limit", "2222"), - resource.TestCheckResourceAttr(resourceName, "route_settings.3867839051.throttling_rate_limit", "8888"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "route_settings.*", map[string]string{ + "data_trace_enabled": "false", + "detailed_metrics_enabled": "false", + "route_key": "$default", + "throttling_burst_limit": "0", + "throttling_rate_limit": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "route_settings.*", map[string]string{ + "data_trace_enabled": "true", + "detailed_metrics_enabled": "true", + "logging_level": "ERROR", + "route_key": "$connect", + "throttling_burst_limit": "2222", + "throttling_rate_limit": "8888", + }), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + Config: testAccAWSAPIGatewayV2StageConfig_routeSettingsWebSocketUpdated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", "OFF"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), + resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("wss://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "3"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "route_settings.*", map[string]string{ + "data_trace_enabled": "false", + "detailed_metrics_enabled": "false", + "route_key": "$default", + "throttling_burst_limit": "1111", + "throttling_rate_limit": "9999", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "route_settings.*", map[string]string{ + "data_trace_enabled": "false", + "detailed_metrics_enabled": "false", + "logging_level": "INFO", + "route_key": "$connect", + "throttling_burst_limit": "0", + "throttling_rate_limit": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "route_settings.*", map[string]string{ + "data_trace_enabled": "false", + "detailed_metrics_enabled": "false", + "route_key": "$disconnect", + "throttling_burst_limit": "0", + "throttling_rate_limit": "0", + }), resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), @@ -389,7 +712,7 @@ func TestAccAWSAPIGatewayV2Stage_RouteSettings(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSAPIGatewayV2StageConfig_basic(rName), + Config: testAccAWSAPIGatewayV2StageConfig_basicWebSocket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), @@ -413,6 +736,110 @@ func TestAccAWSAPIGatewayV2Stage_RouteSettings(t *testing.T) { }) } +func TestAccAWSAPIGatewayV2Stage_RouteSettingsHttp(t *testing.T) { + var apiId string + var v apigatewayv2.GetStageOutput + resourceName := "aws_apigatewayv2_stage.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAPIGatewayV2StageDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAPIGatewayV2StageConfig_routeSettingsHttp(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), + resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("https://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "route_settings.*", map[string]string{ + "data_trace_enabled": "false", + "detailed_metrics_enabled": "true", + "route_key": "$default", + "throttling_burst_limit": "2222", + "throttling_rate_limit": "8888", + }), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + Config: testAccAWSAPIGatewayV2StageConfig_routeSettingsHttpUpdated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), + resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("https://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "route_settings.*", map[string]string{ + "data_trace_enabled": "false", + "detailed_metrics_enabled": "false", + "route_key": "$default", + "throttling_burst_limit": "1111", + "throttling_rate_limit": "9999", + }), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportStateIdFunc: testAccAWSAPIGatewayV2StageImportStateIdFunc(resourceName), + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSAPIGatewayV2StageConfig_basicHttp(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), + resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), + resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), + resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.data_trace_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.detailed_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.logging_level", ""), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), + resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), + resource.TestCheckResourceAttr(resourceName, "stage_variables.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + }, + }) +} + func TestAccAWSAPIGatewayV2Stage_StageVariables(t *testing.T) { var apiId string var v apigatewayv2.GetStageOutput @@ -429,7 +856,7 @@ func TestAccAWSAPIGatewayV2Stage_StageVariables(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), - testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(fmt.Sprintf("/apis/.+/stages/%s", rName))), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), @@ -440,7 +867,7 @@ func TestAccAWSAPIGatewayV2Stage_StageVariables(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), resource.TestCheckResourceAttr(resourceName, "description", ""), - testAccMatchResourceAttrRegionalARN(resourceName, "execution_arn", "execute-api", regexp.MustCompile(fmt.Sprintf(".+/%s", rName))), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("wss://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), @@ -457,7 +884,7 @@ func TestAccAWSAPIGatewayV2Stage_StageVariables(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSAPIGatewayV2StageConfig_basic(rName), + Config: testAccAWSAPIGatewayV2StageConfig_basicWebSocket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), @@ -497,7 +924,7 @@ func TestAccAWSAPIGatewayV2Stage_Tags(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), - testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "arn", "apigateway", regexp.MustCompile(fmt.Sprintf("/apis/.+/stages/%s", rName))), + testAccCheckAWSAPIGatewayV2StageARN(resourceName, "arn", &apiId, &v), resource.TestCheckResourceAttr(resourceName, "auto_deploy", "false"), resource.TestCheckResourceAttr(resourceName, "client_certificate_id", ""), resource.TestCheckResourceAttr(resourceName, "deployment_id", ""), @@ -508,7 +935,7 @@ func TestAccAWSAPIGatewayV2Stage_Tags(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_burst_limit", "0"), resource.TestCheckResourceAttr(resourceName, "default_route_settings.0.throttling_rate_limit", "0"), resource.TestCheckResourceAttr(resourceName, "description", ""), - testAccMatchResourceAttrRegionalARN(resourceName, "execution_arn", "execute-api", regexp.MustCompile(fmt.Sprintf(".+/%s", rName))), + testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, "execution_arn", &apiId, &v), resource.TestMatchResourceAttr(resourceName, "invoke_url", regexp.MustCompile(fmt.Sprintf("wss://.+\\.execute-api\\.%s.amazonaws\\.com/%s", testAccGetRegion(), rName))), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "route_settings.#", "0"), @@ -525,7 +952,7 @@ func TestAccAWSAPIGatewayV2Stage_Tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSAPIGatewayV2StageConfig_basic(rName), + Config: testAccAWSAPIGatewayV2StageConfig_basicWebSocket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAPIGatewayV2StageExists(resourceName, &apiId, &v), resource.TestCheckResourceAttr(resourceName, "access_log_settings.#", "0"), @@ -574,19 +1001,6 @@ func testAccCheckAWSAPIGatewayV2StageDestroy(s *terraform.State) error { return nil } -func testAccCheckAWSAPIGatewayV2StageDisappears(apiId *string, v *apigatewayv2.GetStageOutput) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).apigatewayv2conn - - _, err := conn.DeleteStage(&apigatewayv2.DeleteStageInput{ - ApiId: apiId, - StageName: v.StageName, - }) - - return err - } -} - func testAccCheckAWSAPIGatewayV2StageExists(n string, vApiId *string, v *apigatewayv2.GetStageOutput) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -616,6 +1030,18 @@ func testAccCheckAWSAPIGatewayV2StageExists(n string, vApiId *string, v *apigate } } +func testAccCheckAWSAPIGatewayV2StageARN(resourceName, attributeName string, vApiId *string, v *apigatewayv2.GetStageOutput) resource.TestCheckFunc { + return func(s *terraform.State) error { + return testAccCheckResourceAttrRegionalARNNoAccount(resourceName, attributeName, "apigateway", fmt.Sprintf("/apis/%s/stages/%s", *vApiId, *v.StageName))(s) + } +} + +func testAccCheckAWSAPIGatewayV2StageExecutionARN(resourceName, attributeName string, vApiId *string, v *apigatewayv2.GetStageOutput) resource.TestCheckFunc { + return func(s *terraform.State) error { + return testAccCheckResourceAttrRegionalARN(resourceName, attributeName, "execute-api", fmt.Sprintf("%s/%s", *vApiId, *v.StageName))(s) + } +} + func testAccAWSAPIGatewayV2StageImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] @@ -627,22 +1053,7 @@ func testAccAWSAPIGatewayV2StageImportStateIdFunc(resourceName string) resource. } } -func testAccCheckAWSAPIGatewayV2StageAccessLogDestinationArn(resourceName, resourceKey, cloudWatchResourceName, cloudWatchResourceKey string) resource.TestCheckFunc { - return func(s *terraform.State) error { - cwRs, ok := s.RootModule().Resources[cloudWatchResourceName] - if !ok { - return fmt.Errorf("Resource not found: %s", cloudWatchResourceName) - } - cwArn, ok := cwRs.Primary.Attributes[cloudWatchResourceKey] - if !ok { - return fmt.Errorf("Attribute %q not found in resource %s", cloudWatchResourceKey, cloudWatchResourceName) - } - - return resource.TestCheckResourceAttr(resourceName, resourceKey, strings.TrimSuffix(cwArn, ":*"))(s) - } -} - -func testAccAWSAPIGatewayV2StageConfig_api(rName string) string { +func testAccAWSAPIGatewayV2StageConfig_apiWebSocket(rName string) string { return fmt.Sprintf(` resource "aws_apigatewayv2_api" "test" { name = %[1]q @@ -652,8 +1063,17 @@ resource "aws_apigatewayv2_api" "test" { `, rName) } -func testAccAWSAPIGatewayV2StageConfig_basic(rName string) string { - return testAccAWSAPIGatewayV2StageConfig_api(rName) + fmt.Sprintf(` +func testAccAWSAPIGatewayV2StageConfig_apiHttp(rName string) string { + return fmt.Sprintf(` +resource "aws_apigatewayv2_api" "test" { + name = %[1]q + protocol_type = "HTTP" +} +`, rName) +} + +func testAccAWSAPIGatewayV2StageConfig_basicWebSocket(rName string) string { + return testAccAWSAPIGatewayV2StageConfig_apiWebSocket(rName) + fmt.Sprintf(` resource "aws_apigatewayv2_stage" "test" { api_id = "${aws_apigatewayv2_api.test.id}" name = %[1]q @@ -661,8 +1081,43 @@ resource "aws_apigatewayv2_stage" "test" { `, rName) } +func testAccAWSAPIGatewayV2StageConfig_basicHttp(rName string) string { + return testAccAWSAPIGatewayV2StageConfig_apiHttp(rName) + fmt.Sprintf(` +resource "aws_apigatewayv2_stage" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + name = %[1]q +} +`, rName) +} + +func testAccAWSAPIGatewayV2StageConfig_defaultHttpStage(rName string) string { + return testAccAWSAPIGatewayV2StageConfig_apiHttp(rName) + ` +resource "aws_apigatewayv2_stage" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + name = "$default" +} +` +} + +func testAccAWSAPIGatewayV2StageConfig_autoDeployHttp(rName string, autoDeploy bool) string { + return testAccAWSAPIGatewayV2IntegrationConfig_httpProxy(rName) + fmt.Sprintf(` +resource "aws_apigatewayv2_route" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + route_key = "GET /test" + target = "integrations/${aws_apigatewayv2_integration.test.id}" +} + +resource "aws_apigatewayv2_stage" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + name = %[1]q + + auto_deploy = %[2]t +} +`, rName, autoDeploy) +} + func testAccAWSAPIGatewayV2StageConfig_accessLogSettings(rName, format string) string { - return testAccAWSAPIGatewayV2StageConfig_api(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2StageConfig_apiWebSocket(rName) + fmt.Sprintf(` resource "aws_iam_role" "test" { name = %[1]q @@ -725,7 +1180,7 @@ resource "aws_apigatewayv2_stage" "test" { } func testAccAWSAPIGatewayV2StageConfig_clientCertificateIdAndDescription(rName string) string { - return testAccAWSAPIGatewayV2StageConfig_api(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2StageConfig_apiWebSocket(rName) + fmt.Sprintf(` resource "aws_api_gateway_client_certificate" "test" { description = %[1]q } @@ -741,7 +1196,7 @@ resource "aws_apigatewayv2_stage" "test" { } func testAccAWSAPIGatewayV2StageConfig_clientCertificateIdAndDescriptionUpdated(rName string) string { - return testAccAWSAPIGatewayV2StageConfig_api(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2StageConfig_apiWebSocket(rName) + fmt.Sprintf(` resource "aws_api_gateway_client_certificate" "test" { description = %[1]q } @@ -751,13 +1206,14 @@ resource "aws_apigatewayv2_stage" "test" { name = %[1]q description = "Test stage updated" - auto_deploy = true } `, rName) } -func testAccAWSAPIGatewayV2StageConfig_defaultRouteSettings(rName string) string { - return testAccAWSAPIGatewayV2StageConfig_api(rName) + fmt.Sprintf(` +func testAccAWSAPIGatewayV2StageConfig_defaultRouteSettingsWebSocket(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2StageConfig_apiWebSocket(rName), + fmt.Sprintf(` resource "aws_apigatewayv2_stage" "test" { api_id = "${aws_apigatewayv2_api.test.id}" name = %[1]q @@ -770,7 +1226,59 @@ resource "aws_apigatewayv2_stage" "test" { throttling_rate_limit = 8888 } } -`, rName) +`, rName)) +} + +func testAccAWSAPIGatewayV2StageConfig_defaultRouteSettingsWebSocketUpdated(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2StageConfig_apiWebSocket(rName), + fmt.Sprintf(` +resource "aws_apigatewayv2_stage" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + name = %[1]q + + default_route_settings { + data_trace_enabled = false + detailed_metrics_enabled = true + logging_level = "INFO" + throttling_burst_limit = 1111 + throttling_rate_limit = 9999 + } +} +`, rName)) +} + +func testAccAWSAPIGatewayV2StageConfig_defaultRouteSettingsHttp(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2StageConfig_apiHttp(rName), + fmt.Sprintf(` +resource "aws_apigatewayv2_stage" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + name = %[1]q + + default_route_settings { + detailed_metrics_enabled = true + throttling_burst_limit = 2222 + throttling_rate_limit = 8888 + } +} +`, rName)) +} + +func testAccAWSAPIGatewayV2StageConfig_defaultRouteSettingsHttpUpdated(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2StageConfig_apiHttp(rName), + fmt.Sprintf(` +resource "aws_apigatewayv2_stage" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + name = %[1]q + + default_route_settings { + throttling_burst_limit = 1111 + throttling_rate_limit = 9999 + } +} +`, rName)) } func testAccAWSAPIGatewayV2StageConfig_deployment(rName string) string { @@ -784,8 +1292,10 @@ resource "aws_apigatewayv2_stage" "test" { `, rName) } -func testAccAWSAPIGatewayV2StageConfig_routeSettings(rName string) string { - return testAccAWSAPIGatewayV2StageConfig_api(rName) + fmt.Sprintf(` +func testAccAWSAPIGatewayV2StageConfig_routeSettingsWebSocket(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2StageConfig_apiWebSocket(rName), + fmt.Sprintf(` resource "aws_apigatewayv2_stage" "test" { api_id = "${aws_apigatewayv2_api.test.id}" name = %[1]q @@ -804,11 +1314,76 @@ resource "aws_apigatewayv2_stage" "test" { throttling_rate_limit = 8888 } } -`, rName) +`, rName)) +} + +func testAccAWSAPIGatewayV2StageConfig_routeSettingsWebSocketUpdated(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2StageConfig_apiWebSocket(rName), + fmt.Sprintf(` +resource "aws_apigatewayv2_stage" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + name = %[1]q + + route_settings { + route_key = "$default" + + throttling_burst_limit = 1111 + throttling_rate_limit = 9999 + } + + route_settings { + route_key = "$connect" + + logging_level = "INFO" + } + + route_settings { + route_key = "$disconnect" + } +} +`, rName)) +} + +func testAccAWSAPIGatewayV2StageConfig_routeSettingsHttp(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2StageConfig_apiHttp(rName), + fmt.Sprintf(` +resource "aws_apigatewayv2_stage" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + name = %[1]q + + route_settings { + route_key = "$default" + + detailed_metrics_enabled = true + throttling_burst_limit = 2222 + throttling_rate_limit = 8888 + } +} +`, rName)) +} + +func testAccAWSAPIGatewayV2StageConfig_routeSettingsHttpUpdated(rName string) string { + return composeConfig( + testAccAWSAPIGatewayV2StageConfig_apiHttp(rName), + fmt.Sprintf(` +resource "aws_apigatewayv2_stage" "test" { + api_id = "${aws_apigatewayv2_api.test.id}" + name = %[1]q + + route_settings { + route_key = "$default" + + throttling_burst_limit = 1111 + throttling_rate_limit = 9999 + } +} +`, rName)) } func testAccAWSAPIGatewayV2StageConfig_stageVariables(rName string) string { - return testAccAWSAPIGatewayV2StageConfig_api(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2StageConfig_apiWebSocket(rName) + fmt.Sprintf(` resource "aws_apigatewayv2_stage" "test" { api_id = "${aws_apigatewayv2_api.test.id}" name = %[1]q @@ -822,7 +1397,7 @@ resource "aws_apigatewayv2_stage" "test" { } func testAccAWSAPIGatewayV2StageConfig_tags(rName string) string { - return testAccAWSAPIGatewayV2StageConfig_api(rName) + fmt.Sprintf(` + return testAccAWSAPIGatewayV2StageConfig_apiWebSocket(rName) + fmt.Sprintf(` resource "aws_apigatewayv2_stage" "test" { api_id = "${aws_apigatewayv2_api.test.id}" name = %[1]q diff --git a/aws/resource_aws_apigatewayv2_vpc_link.go b/aws/resource_aws_apigatewayv2_vpc_link.go index 0befd1e2121..3bafee3ab64 100644 --- a/aws/resource_aws_apigatewayv2_vpc_link.go +++ b/aws/resource_aws_apigatewayv2_vpc_link.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/apigatewayv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/apigatewayv2/waiter" ) diff --git a/aws/resource_aws_apigatewayv2_vpc_link_test.go b/aws/resource_aws_apigatewayv2_vpc_link_test.go index 844dcffae89..2660e7ac94d 100644 --- a/aws/resource_aws_apigatewayv2_vpc_link_test.go +++ b/aws/resource_aws_apigatewayv2_vpc_link_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/apigatewayv2" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/apigatewayv2/waiter" ) diff --git a/aws/resource_aws_app_cookie_stickiness_policy.go b/aws/resource_aws_app_cookie_stickiness_policy.go index 36de9b7e3f0..71be5ef2878 100644 --- a/aws/resource_aws_app_cookie_stickiness_policy.go +++ b/aws/resource_aws_app_cookie_stickiness_policy.go @@ -10,7 +10,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsAppCookieStickinessPolicy() *schema.Resource { diff --git a/aws/resource_aws_app_cookie_stickiness_policy_test.go b/aws/resource_aws_app_cookie_stickiness_policy_test.go index 675e8dcd2fa..d3227e03dd5 100644 --- a/aws/resource_aws_app_cookie_stickiness_policy_test.go +++ b/aws/resource_aws_app_cookie_stickiness_policy_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAppCookieStickinessPolicy_basic(t *testing.T) { diff --git a/aws/resource_aws_appautoscaling_policy.go b/aws/resource_aws_appautoscaling_policy.go index 612c1f98ea5..08c745a9245 100644 --- a/aws/resource_aws_appautoscaling_policy.go +++ b/aws/resource_aws_appautoscaling_policy.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/applicationautoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsAppautoscalingPolicy() *schema.Resource { @@ -102,47 +102,6 @@ func resourceAwsAppautoscalingPolicy() *schema.Resource { }, }, }, - "adjustment_type": { - Type: schema.TypeString, - Optional: true, - Removed: "Use `step_scaling_policy_configuration` configuration block `adjustment_type` argument instead", - }, - "cooldown": { - Type: schema.TypeInt, - Optional: true, - Removed: "Use `step_scaling_policy_configuration` configuration block `cooldown` argument instead", - }, - "metric_aggregation_type": { - Type: schema.TypeString, - Optional: true, - Removed: "Use `step_scaling_policy_configuration` configuration block `metric_aggregation_type` argument instead", - }, - "min_adjustment_magnitude": { - Type: schema.TypeInt, - Optional: true, - Removed: "Use `step_scaling_policy_configuration` configuration block `min_adjustment_magnitude` argument instead", - }, - "step_adjustment": { - Type: schema.TypeSet, - Optional: true, - Removed: "Use `step_scaling_policy_configuration` configuration block `step_adjustment` configuration block instead", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "metric_interval_lower_bound": { - Type: schema.TypeString, - Optional: true, - }, - "metric_interval_upper_bound": { - Type: schema.TypeString, - Optional: true, - }, - "scaling_adjustment": { - Type: schema.TypeInt, - Required: true, - }, - }, - }, - }, "target_tracking_scaling_policy_configuration": { Type: schema.TypeList, MaxItems: 1, diff --git a/aws/resource_aws_appautoscaling_policy_test.go b/aws/resource_aws_appautoscaling_policy_test.go index d8c4642cd57..ef7dff542e0 100644 --- a/aws/resource_aws_appautoscaling_policy_test.go +++ b/aws/resource_aws_appautoscaling_policy_test.go @@ -9,9 +9,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/applicationautoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestValidateAppautoscalingPolicyImportInput(t *testing.T) { @@ -84,10 +85,9 @@ func TestAccAWSAppautoScalingPolicy_basic(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAppautoscalingPolicyDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAppautoscalingPolicyDestroy, Steps: []resource.TestStep{ { Config: testAccAWSAppautoscalingPolicyConfig(rName), @@ -101,9 +101,11 @@ func TestAccAWSAppautoScalingPolicy_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "step_scaling_policy_configuration.0.adjustment_type", "ChangeInCapacity"), resource.TestCheckResourceAttr(resourceName, "step_scaling_policy_configuration.0.cooldown", "60"), resource.TestCheckResourceAttr(resourceName, "step_scaling_policy_configuration.0.step_adjustment.#", "1"), - resource.TestCheckResourceAttr(resourceName, "step_scaling_policy_configuration.0.step_adjustment.207530251.scaling_adjustment", "1"), - resource.TestCheckResourceAttr(resourceName, "step_scaling_policy_configuration.0.step_adjustment.207530251.metric_interval_lower_bound", "0"), - resource.TestCheckResourceAttr(resourceName, "step_scaling_policy_configuration.0.step_adjustment.207530251.metric_interval_upper_bound", ""), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "step_scaling_policy_configuration.0.step_adjustment.*", map[string]string{ + "scaling_adjustment": "1", + "metric_interval_lower_bound": "0", + "metric_interval_upper_bound": "", + }), ), }, { @@ -145,10 +147,9 @@ func TestAccAWSAppautoScalingPolicy_scaleOutAndIn(t *testing.T) { randPolicyNamePrefix := fmt.Sprintf("terraform-test-foobar-%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAppautoscalingPolicyDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAppautoscalingPolicyDestroy, Steps: []resource.TestStep{ { Config: testAccAWSAppautoscalingPolicyScaleOutAndInConfig(randClusterName, randPolicyNamePrefix), @@ -157,15 +158,21 @@ func TestAccAWSAppautoScalingPolicy_scaleOutAndIn(t *testing.T) { resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.adjustment_type", "PercentChangeInCapacity"), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.cooldown", "60"), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.#", "3"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.2218643358.metric_interval_lower_bound", "3"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.2218643358.metric_interval_upper_bound", ""), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.2218643358.scaling_adjustment", "3"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.594919880.metric_interval_lower_bound", "1"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.594919880.metric_interval_upper_bound", "3"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.594919880.scaling_adjustment", "2"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.2601972131.metric_interval_lower_bound", "0"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.2601972131.metric_interval_upper_bound", "1"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.2601972131.scaling_adjustment", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.*", map[string]string{ + "metric_interval_lower_bound": "3", + "metric_interval_upper_bound": "", + "scaling_adjustment": "3", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.*", map[string]string{ + "metric_interval_lower_bound": "1", + "metric_interval_upper_bound": "3", + "scaling_adjustment": "2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_appautoscaling_policy.foobar_out", "step_scaling_policy_configuration.0.step_adjustment.*", map[string]string{ + "metric_interval_lower_bound": "0", + "metric_interval_upper_bound": "1", + "scaling_adjustment": "1", + }), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "name", fmt.Sprintf("%s-out", randPolicyNamePrefix)), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "policy_type", "StepScaling"), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_out", "resource_id", fmt.Sprintf("service/%s/foobar", randClusterName)), @@ -175,15 +182,21 @@ func TestAccAWSAppautoScalingPolicy_scaleOutAndIn(t *testing.T) { resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.adjustment_type", "PercentChangeInCapacity"), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.cooldown", "60"), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.#", "3"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.3898905432.metric_interval_lower_bound", "-1"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.3898905432.metric_interval_upper_bound", "0"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.3898905432.scaling_adjustment", "-1"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.386467692.metric_interval_lower_bound", "-3"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.386467692.metric_interval_upper_bound", "-1"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.386467692.scaling_adjustment", "-2"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.602910043.metric_interval_lower_bound", ""), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.602910043.metric_interval_upper_bound", "-3"), - resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.602910043.scaling_adjustment", "-3"), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.*", map[string]string{ + "metric_interval_lower_bound": "-1", + "metric_interval_upper_bound": "0", + "scaling_adjustment": "-1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.*", map[string]string{ + "metric_interval_lower_bound": "-3", + "metric_interval_upper_bound": "-1", + "scaling_adjustment": "-2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_appautoscaling_policy.foobar_in", "step_scaling_policy_configuration.0.step_adjustment.*", map[string]string{ + "metric_interval_lower_bound": "", + "metric_interval_upper_bound": "-3", + "scaling_adjustment": "-3", + }), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "name", fmt.Sprintf("%s-in", randPolicyNamePrefix)), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "policy_type", "StepScaling"), resource.TestCheckResourceAttr("aws_appautoscaling_policy.foobar_in", "resource_id", fmt.Sprintf("service/%s/foobar", randClusterName)), diff --git a/aws/resource_aws_appautoscaling_scheduled_action.go b/aws/resource_aws_appautoscaling_scheduled_action.go index 498e70fc0f8..cc1f79d5a8c 100644 --- a/aws/resource_aws_appautoscaling_scheduled_action.go +++ b/aws/resource_aws_appautoscaling_scheduled_action.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/applicationautoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) const awsAppautoscalingScheduleTimeLayout = "2006-01-02T15:04:05Z" diff --git a/aws/resource_aws_appautoscaling_scheduled_action_test.go b/aws/resource_aws_appautoscaling_scheduled_action_test.go index c136ea48887..342e3860109 100644 --- a/aws/resource_aws_appautoscaling_scheduled_action_test.go +++ b/aws/resource_aws_appautoscaling_scheduled_action_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/applicationautoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAppautoscalingScheduledAction_dynamo(t *testing.T) { @@ -233,8 +233,8 @@ func testAccAppautoscalingScheduledActionConfig_EMR(rName, ts string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { # The requested instance type c4.large is not supported in the requested availability zone. - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -256,9 +256,14 @@ resource "aws_emr_cluster" "hoge" { instance_profile = "${aws_iam_instance_profile.instance_profile.arn}" } - master_instance_type = "c4.large" - core_instance_type = "c4.large" - core_instance_count = 2 + master_instance_group { + instance_type = "c4.large" + } + + core_instance_group { + instance_count = 2 + instance_type = "c4.large" + } tags = { role = "rolename" diff --git a/aws/resource_aws_appautoscaling_target.go b/aws/resource_aws_appautoscaling_target.go index 80b4e125a01..6cfbf04a9de 100644 --- a/aws/resource_aws_appautoscaling_target.go +++ b/aws/resource_aws_appautoscaling_target.go @@ -3,15 +3,13 @@ package aws import ( "fmt" "log" + "strings" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/applicationautoscaling" - "strings" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsAppautoscalingTarget() *schema.Resource { @@ -148,46 +146,29 @@ func resourceAwsAppautoscalingTargetRead(d *schema.ResourceData, meta interface{ func resourceAwsAppautoscalingTargetDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).appautoscalingconn - namespace := d.Get("service_namespace").(string) - dimension := d.Get("scalable_dimension").(string) - - t, err := getAwsAppautoscalingTarget(d.Id(), namespace, dimension, conn) - if err != nil { - return err - } - if t == nil { - log.Printf("[INFO] Application AutoScaling Target %q not found", d.Id()) - return nil - } - - log.Printf("[DEBUG] Application AutoScaling Target destroy: %#v", d.Id()) - deleteOpts := applicationautoscaling.DeregisterScalableTargetInput{ + input := &applicationautoscaling.DeregisterScalableTargetInput{ ResourceId: aws.String(d.Get("resource_id").(string)), ServiceNamespace: aws.String(d.Get("service_namespace").(string)), ScalableDimension: aws.String(d.Get("scalable_dimension").(string)), } - err = resource.Retry(5*time.Minute, func() *resource.RetryError { - if _, err := conn.DeregisterScalableTarget(&deleteOpts); err != nil { - if awserr, ok := err.(awserr.Error); ok { - // @TODO: We should do stuff here depending on the actual error returned - return resource.RetryableError(awserr) - } - // Non recognized error, no retry. - return resource.NonRetryableError(err) - } - // Successful delete - return nil - }) + _, err := conn.DeregisterScalableTarget(input) + if err != nil { - return err + return fmt.Errorf("error deleting Application AutoScaling Target (%s): %w", d.Id(), err) } return resource.Retry(5*time.Minute, func() *resource.RetryError { - if t, _ = getAwsAppautoscalingTarget(d.Id(), namespace, dimension, conn); t != nil { - return resource.RetryableError( - fmt.Errorf("Application AutoScaling Target still exists")) + t, err := getAwsAppautoscalingTarget(d.Get("resource_id").(string), d.Get("service_namespace").(string), d.Get("scalable_dimension").(string), conn) + + if err != nil { + return resource.NonRetryableError(err) } + + if t != nil { + return resource.RetryableError(fmt.Errorf("Application AutoScaling Target (%s) still exists", d.Id())) + } + return nil }) } diff --git a/aws/resource_aws_appautoscaling_target_test.go b/aws/resource_aws_appautoscaling_target_test.go index fe255056d7b..7f261e9d2bf 100644 --- a/aws/resource_aws_appautoscaling_target_test.go +++ b/aws/resource_aws_appautoscaling_target_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/applicationautoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAppautoScalingTarget_basic(t *testing.T) { @@ -53,6 +53,28 @@ func TestAccAWSAppautoScalingTarget_basic(t *testing.T) { }) } +func TestAccAWSAppautoScalingTarget_disappears(t *testing.T) { + var target applicationautoscaling.ScalableTarget + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_appautoscaling_target.bar" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAppautoscalingTargetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAppautoscalingTargetConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAppautoscalingTargetExists(resourceName, &target), + testAccCheckResourceDisappears(testAccProvider, resourceAwsAppautoscalingTarget(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func TestAccAWSAppautoScalingTarget_spotFleetRequest(t *testing.T) { var target applicationautoscaling.ScalableTarget validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) @@ -322,8 +344,8 @@ func testAccAWSAppautoscalingTargetEmrClusterConfig(rInt int) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { # The requested instance type m3.xlarge is not supported in the requested availability zone. - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -345,9 +367,14 @@ resource "aws_emr_cluster" "tf-test-cluster" { instance_profile = "${aws_iam_instance_profile.emr_profile.arn}" } - master_instance_type = "m3.xlarge" - core_instance_type = "m3.xlarge" - core_instance_count = 2 + master_instance_group { + instance_type = "m3.xlarge" + } + + core_instance_group { + instance_count = 2 + instance_type = "m3.xlarge" + } tags = { role = "rolename" @@ -561,8 +588,8 @@ EOT } resource "aws_iam_instance_profile" "emr_profile" { - name = "emr_profile_%d" - roles = ["${aws_iam_role.iam_emr_profile_role.name}"] + name = "emr_profile_%d" + role = aws_iam_role.iam_emr_profile_role.name } resource "aws_iam_role_policy_attachment" "profile-attach" { diff --git a/aws/resource_aws_appmesh_mesh.go b/aws/resource_aws_appmesh_mesh.go index 3514e37821d..883b3f01b2c 100644 --- a/aws/resource_aws_appmesh_mesh.go +++ b/aws/resource_aws_appmesh_mesh.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appmesh" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_appmesh_mesh_test.go b/aws/resource_aws_appmesh_mesh_test.go index 0849a8ccac2..ca727cbd553 100644 --- a/aws/resource_aws_appmesh_mesh_test.go +++ b/aws/resource_aws_appmesh_mesh_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appmesh" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_appmesh_route.go b/aws/resource_aws_appmesh_route.go index 7d6024bb6a4..f592c897734 100644 --- a/aws/resource_aws_appmesh_route.go +++ b/aws/resource_aws_appmesh_route.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appmesh" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_appmesh_route_test.go b/aws/resource_aws_appmesh_route_test.go index 74addbea822..f91773a82c9 100644 --- a/aws/resource_aws_appmesh_route_test.go +++ b/aws/resource_aws_appmesh_route_test.go @@ -7,9 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appmesh" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -159,6 +160,29 @@ func testAccAwsAppmeshRoute_httpRoute(t *testing.T) { testAccCheckResourceAttrRegionalARN(resourceName, "arn", "appmesh", fmt.Sprintf("mesh/%s/virtualRouter/%s/route/%s", meshName, vrName, rName)), ), }, + { + Config: testAccAppmeshRouteConfig_httpRouteUpdatedWithZeroWeight(meshName, vrName, vn1Name, vn2Name, rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAppmeshRouteExists(resourceName, &r), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "mesh_name", meshName), + resource.TestCheckResourceAttr(resourceName, "virtual_router_name", vrName), + resource.TestCheckResourceAttr(resourceName, "spec.#", "1"), + resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.#", "1"), + resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.action.0.weighted_target.#", "2"), + resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.#", "1"), + resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.#", "0"), + resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.method", ""), + resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.prefix", "/path"), + resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.scheme", ""), + resource.TestCheckResourceAttr(resourceName, "spec.0.priority", "0"), + resource.TestCheckResourceAttr(resourceName, "spec.0.tcp_route.#", "0"), + resource.TestCheckResourceAttrSet(resourceName, "created_date"), + resource.TestCheckResourceAttrSet(resourceName, "last_updated_date"), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "appmesh", fmt.Sprintf("mesh/%s/virtualRouter/%s/route/%s", meshName, vrName, rName)), + ), + }, { ResourceName: resourceName, ImportStateIdFunc: testAccAwsAppmeshRouteImportStateIdFunc(resourceName), @@ -219,6 +243,24 @@ func testAccAwsAppmeshRoute_tcpRoute(t *testing.T) { testAccCheckResourceAttrRegionalARN(resourceName, "arn", "appmesh", fmt.Sprintf("mesh/%s/virtualRouter/%s/route/%s", meshName, vrName, rName)), ), }, + { + Config: testAccAppmeshRouteConfig_tcpRouteUpdatedWithZeroWeight(meshName, vrName, vn1Name, vn2Name, rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAppmeshRouteExists(resourceName, &r), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "mesh_name", meshName), + resource.TestCheckResourceAttr(resourceName, "virtual_router_name", vrName), + resource.TestCheckResourceAttr(resourceName, "spec.#", "1"), + resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.#", "0"), + resource.TestCheckResourceAttr(resourceName, "spec.0.priority", "0"), + resource.TestCheckResourceAttr(resourceName, "spec.0.tcp_route.#", "1"), + resource.TestCheckResourceAttr(resourceName, "spec.0.tcp_route.0.action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "spec.0.tcp_route.0.action.0.weighted_target.#", "2"), + resource.TestCheckResourceAttrSet(resourceName, "created_date"), + resource.TestCheckResourceAttrSet(resourceName, "last_updated_date"), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "appmesh", fmt.Sprintf("mesh/%s/virtualRouter/%s/route/%s", meshName, vrName, rName)), + ), + }, { ResourceName: resourceName, ImportStateIdFunc: testAccAwsAppmeshRouteImportStateIdFunc(resourceName), @@ -295,10 +337,9 @@ func testAccAwsAppmeshRoute_httpHeader(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAppmeshRouteDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAppmeshRouteDestroy, Steps: []resource.TestStep{ { Config: testAccAwsAppmeshRouteConfig_httpHeader(meshName, vrName, vn1Name, vn2Name, rName), @@ -313,9 +354,11 @@ func testAccAwsAppmeshRoute_httpHeader(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.action.0.weighted_target.#", "1"), resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.#", "1"), resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.2366200004.invert", "false"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.2366200004.match.#", "0"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.2366200004.name", "X-Testing1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "spec.0.http_route.0.match.0.header.*", map[string]string{ + "invert": "false", + "match.#": "0", + "name": "X-Testing1", + }), resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.method", "POST"), resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.prefix", "/"), resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.scheme", "http"), @@ -339,19 +382,23 @@ func testAccAwsAppmeshRoute_httpHeader(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.action.0.weighted_target.#", "1"), resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.#", "1"), resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.#", "2"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.2971741486.invert", "true"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.2971741486.match.#", "0"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.2971741486.name", "X-Testing1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.3147536248.invert", "false"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.3147536248.match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.3147536248.match.0.exact", ""), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.3147536248.match.0.prefix", ""), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.3147536248.match.0.range.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.3147536248.match.0.range.0.end", "7"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.3147536248.match.0.range.0.start", "2"), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.3147536248.match.0.regex", ""), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.3147536248.match.0.suffix", ""), - resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.header.3147536248.name", "X-Testing2"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "spec.0.http_route.0.match.0.header.*", map[string]string{ + "invert": "true", + "match.#": "0", + "name": "X-Testing1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "spec.0.http_route.0.match.0.header.*", map[string]string{ + "invert": "false", + "match.#": "1", + "match.0.exact": "", + "match.0.prefix": "", + "match.0.range.#": "1", + "match.0.range.0.end": "7", + "range.0.start": "2", + "match.0.regex": "", + "match.0.suffix": "", + "name": "X-Testing2", + }), resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.method", "PUT"), resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.prefix", "/path"), resource.TestCheckResourceAttr(resourceName, "spec.0.http_route.0.match.0.scheme", "https"), @@ -596,6 +643,36 @@ resource "aws_appmesh_route" "test" { `, rName) } +func testAccAppmeshRouteConfig_httpRouteUpdatedWithZeroWeight(meshName, vrName, vn1Name, vn2Name, rName string) string { + return testAccAppmeshRouteConfigBase(meshName, vrName, vn1Name, vn2Name) + fmt.Sprintf(` +resource "aws_appmesh_route" "test" { + name = %[1]q + mesh_name = "${aws_appmesh_mesh.test.id}" + virtual_router_name = "${aws_appmesh_virtual_router.test.name}" + + spec { + http_route { + match { + prefix = "/path" + } + + action { + weighted_target { + virtual_node = "${aws_appmesh_virtual_node.foo.name}" + weight = 99 + } + + weighted_target { + virtual_node = "${aws_appmesh_virtual_node.bar.name}" + weight = 0 + } + } + } + } +} +`, rName) +} + func testAccAppmeshRouteConfig_tcpRoute(meshName, vrName, vn1Name, vn2Name, rName string) string { return testAccAppmeshRouteConfigBase(meshName, vrName, vn1Name, vn2Name) + fmt.Sprintf(` resource "aws_appmesh_route" "test" { @@ -643,6 +720,32 @@ resource "aws_appmesh_route" "test" { `, rName) } +func testAccAppmeshRouteConfig_tcpRouteUpdatedWithZeroWeight(meshName, vrName, vn1Name, vn2Name, rName string) string { + return testAccAppmeshRouteConfigBase(meshName, vrName, vn1Name, vn2Name) + fmt.Sprintf(` +resource "aws_appmesh_route" "test" { + name = %[1]q + mesh_name = "${aws_appmesh_mesh.test.id}" + virtual_router_name = "${aws_appmesh_virtual_router.test.name}" + + spec { + tcp_route { + action { + weighted_target { + virtual_node = "${aws_appmesh_virtual_node.foo.name}" + weight = 99 + } + + weighted_target { + virtual_node = "${aws_appmesh_virtual_node.bar.name}" + weight = 0 + } + } + } + } +} +`, rName) +} + func testAccAppmeshRouteConfigWithTags(meshName, vrName, vn1Name, vn2Name, rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccAppmeshRouteConfigBase(meshName, vrName, vn1Name, vn2Name) + fmt.Sprintf(` resource "aws_appmesh_route" "test" { diff --git a/aws/resource_aws_appmesh_test.go b/aws/resource_aws_appmesh_test.go index 86bb8a44f76..fb1e6ca33a5 100644 --- a/aws/resource_aws_appmesh_test.go +++ b/aws/resource_aws_appmesh_test.go @@ -4,7 +4,7 @@ import ( "testing" ) -func TestAccAWSAppmesh(t *testing.T) { +func TestAccAWSAppmesh_serial(t *testing.T) { testCases := map[string]map[string]func(t *testing.T){ "Mesh": { "basic": testAccAwsAppmeshMesh_basic, diff --git a/aws/resource_aws_appmesh_virtual_node.go b/aws/resource_aws_appmesh_virtual_node.go index e7ddc3b8263..8efb77ec728 100644 --- a/aws/resource_aws_appmesh_virtual_node.go +++ b/aws/resource_aws_appmesh_virtual_node.go @@ -9,13 +9,14 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appmesh" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) func resourceAwsAppmeshVirtualNode() *schema.Resource { + //lintignore:R011 return &schema.Resource{ Create: resourceAwsAppmeshVirtualNodeCreate, Read: resourceAwsAppmeshVirtualNodeRead, @@ -50,14 +51,6 @@ func resourceAwsAppmeshVirtualNode() *schema.Resource { MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "backends": { - Type: schema.TypeSet, - Removed: "Use `backend` configuration blocks instead", - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "backend": { Type: schema.TypeSet, Optional: true, @@ -86,7 +79,7 @@ func resourceAwsAppmeshVirtualNode() *schema.Resource { }, "listener": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, MinItems: 0, MaxItems: 1, @@ -173,7 +166,6 @@ func resourceAwsAppmeshVirtualNode() *schema.Resource { }, }, }, - Set: appmeshVirtualNodeListenerHash, }, "logging": { @@ -256,13 +248,6 @@ func resourceAwsAppmeshVirtualNode() *schema.Resource { ConflictsWith: []string{"spec.0.service_discovery.0.aws_cloud_map"}, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "service_name": { - Type: schema.TypeString, - Removed: "Use `hostname` argument instead", - Optional: true, - Computed: true, - }, - "hostname": { Type: schema.TypeString, Required: true, @@ -451,41 +436,3 @@ func appmeshVirtualNodeBackendHash(vBackend interface{}) int { } return hashcode.String(buf.String()) } - -func appmeshVirtualNodeListenerHash(vListener interface{}) int { - var buf bytes.Buffer - mListener := vListener.(map[string]interface{}) - if vHealthCheck, ok := mListener["health_check"].([]interface{}); ok && len(vHealthCheck) > 0 && vHealthCheck[0] != nil { - mHealthCheck := vHealthCheck[0].(map[string]interface{}) - if v, ok := mHealthCheck["healthy_threshold"].(int); ok { - buf.WriteString(fmt.Sprintf("%d-", v)) - } - if v, ok := mHealthCheck["interval_millis"].(int); ok { - buf.WriteString(fmt.Sprintf("%d-", v)) - } - if v, ok := mHealthCheck["path"].(string); ok { - buf.WriteString(fmt.Sprintf("%s-", v)) - } - // Don't include "port" in the hash as it's Optional/Computed. - // If present it must match the "port_mapping.port" value, so changes will be detected. - if v, ok := mHealthCheck["protocol"].(string); ok { - buf.WriteString(fmt.Sprintf("%s-", v)) - } - if v, ok := mHealthCheck["timeout_millis"].(int); ok { - buf.WriteString(fmt.Sprintf("%d-", v)) - } - if v, ok := mHealthCheck["unhealthy_threshold"].(int); ok { - buf.WriteString(fmt.Sprintf("%d-", v)) - } - } - if vPortMapping, ok := mListener["port_mapping"].([]interface{}); ok && len(vPortMapping) > 0 && vPortMapping[0] != nil { - mPortMapping := vPortMapping[0].(map[string]interface{}) - if v, ok := mPortMapping["port"].(int); ok { - buf.WriteString(fmt.Sprintf("%d-", v)) - } - if v, ok := mPortMapping["protocol"].(string); ok { - buf.WriteString(fmt.Sprintf("%s-", v)) - } - } - return hashcode.String(buf.String()) -} diff --git a/aws/resource_aws_appmesh_virtual_node_migrate.go b/aws/resource_aws_appmesh_virtual_node_migrate.go index dde6d59766a..2619070f713 100644 --- a/aws/resource_aws_appmesh_virtual_node_migrate.go +++ b/aws/resource_aws_appmesh_virtual_node_migrate.go @@ -5,7 +5,7 @@ import ( "log" "strings" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func resourceAwsAppmeshVirtualNodeMigrateState(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { diff --git a/aws/resource_aws_appmesh_virtual_node_migrate_test.go b/aws/resource_aws_appmesh_virtual_node_migrate_test.go index 8862c07be77..959ad31bb79 100644 --- a/aws/resource_aws_appmesh_virtual_node_migrate_test.go +++ b/aws/resource_aws_appmesh_virtual_node_migrate_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAWSAppmeshVirtualNodeMigrateState(t *testing.T) { diff --git a/aws/resource_aws_appmesh_virtual_node_test.go b/aws/resource_aws_appmesh_virtual_node_test.go index d05e2a155d0..00285aed723 100644 --- a/aws/resource_aws_appmesh_virtual_node_test.go +++ b/aws/resource_aws_appmesh_virtual_node_test.go @@ -7,9 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appmesh" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -176,10 +177,9 @@ func testAccAwsAppmeshVirtualNode_listenerHealthChecks(t *testing.T) { vnName := acctest.RandomWithPrefix("tf-acc-test") resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAppmeshVirtualNodeDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAppmeshVirtualNodeDestroy, Steps: []resource.TestStep{ { Config: testAccAppmeshVirtualNodeConfig_listenerHealthChecks(meshName, vnName), @@ -189,20 +189,22 @@ func testAccAwsAppmeshVirtualNode_listenerHealthChecks(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "mesh_name", meshName), resource.TestCheckResourceAttr(resourceName, "spec.#", "1"), resource.TestCheckResourceAttr(resourceName, "spec.0.backend.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.backend.2622272660.virtual_service.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.backend.2622272660.virtual_service.0.virtual_service_name", "servicea.simpleapp.local"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "spec.0.backend.*", map[string]string{ + "virtual_service.#": "1", + "virtual_service.0.virtual_service_name": "servicea.simpleapp.local", + }), resource.TestCheckResourceAttr(resourceName, "spec.0.listener.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.433446196.health_check.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.433446196.health_check.0.healthy_threshold", "3"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.433446196.health_check.0.interval_millis", "5000"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.433446196.health_check.0.path", "/ping"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.433446196.health_check.0.port", "8080"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.433446196.health_check.0.protocol", "http"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.433446196.health_check.0.timeout_millis", "2000"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.433446196.health_check.0.unhealthy_threshold", "5"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.433446196.port_mapping.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.433446196.port_mapping.0.port", "8080"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.433446196.port_mapping.0.protocol", "http"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.#", "1"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.healthy_threshold", "3"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.interval_millis", "5000"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.path", "/ping"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.port", "8080"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.protocol", "http"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.timeout_millis", "2000"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.unhealthy_threshold", "5"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.port_mapping.#", "1"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.port_mapping.0.port", "8080"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.port_mapping.0.protocol", "http"), resource.TestCheckResourceAttr(resourceName, "spec.0.logging.#", "0"), resource.TestCheckResourceAttr(resourceName, "spec.0.service_discovery.#", "1"), resource.TestCheckResourceAttr(resourceName, "spec.0.service_discovery.0.dns.#", "1"), @@ -220,21 +222,25 @@ func testAccAwsAppmeshVirtualNode_listenerHealthChecks(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "mesh_name", meshName), resource.TestCheckResourceAttr(resourceName, "spec.#", "1"), resource.TestCheckResourceAttr(resourceName, "spec.0.backend.#", "2"), - resource.TestCheckResourceAttr(resourceName, "spec.0.backend.2576932631.virtual_service.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.backend.2576932631.virtual_service.0.virtual_service_name", "servicec.simpleapp.local"), - resource.TestCheckResourceAttr(resourceName, "spec.0.backend.2025248115.virtual_service.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.backend.2025248115.virtual_service.0.virtual_service_name", "serviced.simpleapp.local"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "spec.0.backend.*", map[string]string{ + "virtual_service.#": "1", + "virtual_service.0.virtual_service_name": "servicec.simpleapp.local", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "spec.0.backend.*", map[string]string{ + "virtual_service.#": "1", + "virtual_service.0.virtual_service_name": "serviced.simpleapp.local", + }), resource.TestCheckResourceAttr(resourceName, "spec.0.listener.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.3446683576.health_check.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.3446683576.health_check.0.healthy_threshold", "4"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.3446683576.health_check.0.interval_millis", "7000"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.3446683576.health_check.0.port", "8081"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.3446683576.health_check.0.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.3446683576.health_check.0.timeout_millis", "3000"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.3446683576.health_check.0.unhealthy_threshold", "9"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.3446683576.port_mapping.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.3446683576.port_mapping.0.port", "8081"), - resource.TestCheckResourceAttr(resourceName, "spec.0.listener.3446683576.port_mapping.0.protocol", "http"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.#", "1"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.healthy_threshold", "4"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.interval_millis", "7000"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.port", "8081"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.protocol", "tcp"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.timeout_millis", "3000"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.health_check.0.unhealthy_threshold", "9"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.port_mapping.#", "1"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.port_mapping.0.port", "8081"), + resource.TestCheckResourceAttr(resourceName, "spec.0.listener.0.port_mapping.0.protocol", "http"), resource.TestCheckResourceAttr(resourceName, "spec.0.logging.#", "0"), resource.TestCheckResourceAttr(resourceName, "spec.0.service_discovery.#", "1"), resource.TestCheckResourceAttr(resourceName, "spec.0.service_discovery.0.dns.#", "1"), diff --git a/aws/resource_aws_appmesh_virtual_router.go b/aws/resource_aws_appmesh_virtual_router.go index a11d1d3eb51..770c2d0e113 100644 --- a/aws/resource_aws_appmesh_virtual_router.go +++ b/aws/resource_aws_appmesh_virtual_router.go @@ -1,7 +1,6 @@ package aws import ( - "bytes" "fmt" "log" "strings" @@ -9,13 +8,13 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appmesh" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) func resourceAwsAppmeshVirtualRouter() *schema.Resource { + //lintignore:R011 return &schema.Resource{ Create: resourceAwsAppmeshVirtualRouterCreate, Read: resourceAwsAppmeshVirtualRouterRead, @@ -50,16 +49,8 @@ func resourceAwsAppmeshVirtualRouter() *schema.Resource { MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "service_names": { - Type: schema.TypeSet, - Removed: "Use `aws_appmesh_virtual_service` resources instead", - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "listener": { - Type: schema.TypeSet, + Type: schema.TypeList, Required: true, MinItems: 1, MaxItems: 1, @@ -91,7 +82,6 @@ func resourceAwsAppmeshVirtualRouter() *schema.Resource { }, }, }, - Set: appmeshVirtualRouterListenerHash, }, }, }, @@ -258,18 +248,3 @@ func resourceAwsAppmeshVirtualRouterImport(d *schema.ResourceData, meta interfac return []*schema.ResourceData{d}, nil } - -func appmeshVirtualRouterListenerHash(vListener interface{}) int { - var buf bytes.Buffer - mListener := vListener.(map[string]interface{}) - if vPortMapping, ok := mListener["port_mapping"].([]interface{}); ok && len(vPortMapping) > 0 && vPortMapping[0] != nil { - mPortMapping := vPortMapping[0].(map[string]interface{}) - if v, ok := mPortMapping["port"].(int); ok { - buf.WriteString(fmt.Sprintf("%d-", v)) - } - if v, ok := mPortMapping["protocol"].(string); ok { - buf.WriteString(fmt.Sprintf("%s-", v)) - } - } - return hashcode.String(buf.String()) -} diff --git a/aws/resource_aws_appmesh_virtual_router_migrate.go b/aws/resource_aws_appmesh_virtual_router_migrate.go index 8b4f82e4336..cda91f250b0 100644 --- a/aws/resource_aws_appmesh_virtual_router_migrate.go +++ b/aws/resource_aws_appmesh_virtual_router_migrate.go @@ -5,7 +5,7 @@ import ( "log" "strings" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func resourceAwsAppmeshVirtualRouterMigrateState(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { diff --git a/aws/resource_aws_appmesh_virtual_router_migrate_test.go b/aws/resource_aws_appmesh_virtual_router_migrate_test.go index c82c5bf90f6..613b108c4f2 100644 --- a/aws/resource_aws_appmesh_virtual_router_migrate_test.go +++ b/aws/resource_aws_appmesh_virtual_router_migrate_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAWSAppmeshVirtualRouterMigrateState(t *testing.T) { diff --git a/aws/resource_aws_appmesh_virtual_router_test.go b/aws/resource_aws_appmesh_virtual_router_test.go index 849cde5619f..ccec9f02d12 100644 --- a/aws/resource_aws_appmesh_virtual_router_test.go +++ b/aws/resource_aws_appmesh_virtual_router_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appmesh" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -88,10 +88,9 @@ func testAccAwsAppmeshVirtualRouter_basic(t *testing.T) { vrName := acctest.RandomWithPrefix("tf-acc-test") resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAppmeshVirtualRouterDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAppmeshVirtualRouterDestroy, Steps: []resource.TestStep{ { Config: testAccAppmeshVirtualRouterConfig_basic(meshName, vrName), @@ -107,11 +106,11 @@ func testAccAwsAppmeshVirtualRouter_basic(t *testing.T) { resource.TestCheckResourceAttr( resourceName, "spec.0.listener.#", "1"), resource.TestCheckResourceAttr( - resourceName, "spec.0.listener.2279702354.port_mapping.#", "1"), + resourceName, "spec.0.listener.0.port_mapping.#", "1"), resource.TestCheckResourceAttr( - resourceName, "spec.0.listener.2279702354.port_mapping.0.port", "8080"), + resourceName, "spec.0.listener.0.port_mapping.0.port", "8080"), resource.TestCheckResourceAttr( - resourceName, "spec.0.listener.2279702354.port_mapping.0.protocol", "http"), + resourceName, "spec.0.listener.0.port_mapping.0.protocol", "http"), resource.TestCheckResourceAttrSet( resourceName, "created_date"), resource.TestCheckResourceAttrSet( @@ -134,11 +133,11 @@ func testAccAwsAppmeshVirtualRouter_basic(t *testing.T) { resource.TestCheckResourceAttr( resourceName, "spec.0.listener.#", "1"), resource.TestCheckResourceAttr( - resourceName, "spec.0.listener.563508454.port_mapping.#", "1"), + resourceName, "spec.0.listener.0.port_mapping.#", "1"), resource.TestCheckResourceAttr( - resourceName, "spec.0.listener.563508454.port_mapping.0.port", "8081"), + resourceName, "spec.0.listener.0.port_mapping.0.port", "8081"), resource.TestCheckResourceAttr( - resourceName, "spec.0.listener.563508454.port_mapping.0.protocol", "http"), + resourceName, "spec.0.listener.0.port_mapping.0.protocol", "http"), ), }, { diff --git a/aws/resource_aws_appmesh_virtual_service.go b/aws/resource_aws_appmesh_virtual_service.go index 1332f725d30..a3446ab0712 100644 --- a/aws/resource_aws_appmesh_virtual_service.go +++ b/aws/resource_aws_appmesh_virtual_service.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appmesh" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_appmesh_virtual_service_test.go b/aws/resource_aws_appmesh_virtual_service_test.go index e520b6aa2c2..afe3f40cc0a 100644 --- a/aws/resource_aws_appmesh_virtual_service_test.go +++ b/aws/resource_aws_appmesh_virtual_service_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appmesh" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_appsync_api_key.go b/aws/resource_aws_appsync_api_key.go index 95bcdcbecea..bb0c9e8c4b1 100644 --- a/aws/resource_aws_appsync_api_key.go +++ b/aws/resource_aws_appsync_api_key.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appsync" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsAppsyncApiKey() *schema.Resource { diff --git a/aws/resource_aws_appsync_api_key_test.go b/aws/resource_aws_appsync_api_key_test.go index f7a93ae764d..f2e2ced971a 100644 --- a/aws/resource_aws_appsync_api_key_test.go +++ b/aws/resource_aws_appsync_api_key_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appsync" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAppsyncApiKey_basic(t *testing.T) { diff --git a/aws/resource_aws_appsync_datasource.go b/aws/resource_aws_appsync_datasource.go index befa9b0b238..da693a564df 100644 --- a/aws/resource_aws_appsync_datasource.go +++ b/aws/resource_aws_appsync_datasource.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appsync" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsAppsyncDatasource() *schema.Resource { diff --git a/aws/resource_aws_appsync_datasource_test.go b/aws/resource_aws_appsync_datasource_test.go index dc56d9e3bc3..494870f1687 100644 --- a/aws/resource_aws_appsync_datasource_test.go +++ b/aws/resource_aws_appsync_datasource_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appsync" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAwsAppsyncDatasource_basic(t *testing.T) { diff --git a/aws/resource_aws_appsync_function.go b/aws/resource_aws_appsync_function.go index ea9912cb752..42d4566f4e5 100644 --- a/aws/resource_aws_appsync_function.go +++ b/aws/resource_aws_appsync_function.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appsync" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsAppsyncFunction() *schema.Resource { diff --git a/aws/resource_aws_appsync_function_test.go b/aws/resource_aws_appsync_function_test.go index ae8091feabd..19be026749f 100644 --- a/aws/resource_aws_appsync_function_test.go +++ b/aws/resource_aws_appsync_function_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appsync" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAwsAppsyncFunction_basic(t *testing.T) { diff --git a/aws/resource_aws_appsync_graphql_api.go b/aws/resource_aws_appsync_graphql_api.go index e91676547a7..d807a9b6d73 100644 --- a/aws/resource_aws_appsync_graphql_api.go +++ b/aws/resource_aws_appsync_graphql_api.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appsync" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_appsync_graphql_api_test.go b/aws/resource_aws_appsync_graphql_api_test.go index 3c693fa804b..6430f506501 100644 --- a/aws/resource_aws_appsync_graphql_api_test.go +++ b/aws/resource_aws_appsync_graphql_api_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appsync" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_appsync_resolver.go b/aws/resource_aws_appsync_resolver.go index 470f47ef3eb..fd16d129dbf 100644 --- a/aws/resource_aws_appsync_resolver.go +++ b/aws/resource_aws_appsync_resolver.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appsync" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsAppsyncResolver() *schema.Resource { @@ -77,6 +77,27 @@ func resourceAwsAppsyncResolver() *schema.Resource { }, }, }, + "caching_config": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "caching_keys": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Set: schema.HashString, + }, + "ttl": { + Type: schema.TypeInt, + Optional: true, + }, + }, + }, + }, "arn": { Type: schema.TypeString, Computed: true, @@ -108,6 +129,10 @@ func resourceAwsAppsyncResolverCreate(d *schema.ResourceData, meta interface{}) } } + if v, ok := d.GetOk("caching_config"); ok { + input.CachingConfig = expandAppsyncResolverCachingConfig(v.([]interface{})) + } + mutexKey := fmt.Sprintf("appsync-schema-%s", d.Get("api_id").(string)) awsMutexKV.Lock(mutexKey) defer awsMutexKV.Unlock(mutexKey) @@ -165,6 +190,10 @@ func resourceAwsAppsyncResolverRead(d *schema.ResourceData, meta interface{}) er return fmt.Errorf("Error setting pipeline_config: %s", err) } + if err := d.Set("caching_config", flattenAppsyncCachingConfig(resp.Resolver.CachingConfig)); err != nil { + return fmt.Errorf("Error setting caching_config: %s", err) + } + return nil } @@ -191,6 +220,10 @@ func resourceAwsAppsyncResolverUpdate(d *schema.ResourceData, meta interface{}) } } + if v, ok := d.GetOk("caching_config"); ok { + input.CachingConfig = expandAppsyncResolverCachingConfig(v.([]interface{})) + } + mutexKey := fmt.Sprintf("appsync-schema-%s", d.Get("api_id").(string)) awsMutexKV.Lock(mutexKey) defer awsMutexKV.Unlock(mutexKey) @@ -243,3 +276,54 @@ func decodeAppsyncResolverID(id string) (string, string, string, error) { } return idParts[0], idParts[1], idParts[2], nil } + +func expandAppsyncResolverCachingConfig(l []interface{}) *appsync.CachingConfig { + if len(l) < 1 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + cachingConfig := &appsync.CachingConfig{ + CachingKeys: expandStringSet(m["caching_keys"].(*schema.Set)), + } + + if v, ok := m["ttl"].(int); ok && v != 0 { + cachingConfig.Ttl = aws.Int64(int64(v)) + } + + return cachingConfig +} + +func flattenAppsyncPipelineConfig(c *appsync.PipelineConfig) []interface{} { + if c == nil { + return nil + } + + if len(c.Functions) == 0 { + return nil + } + + m := map[string]interface{}{ + "functions": flattenStringList(c.Functions), + } + + return []interface{}{m} +} + +func flattenAppsyncCachingConfig(c *appsync.CachingConfig) []interface{} { + if c == nil { + return nil + } + + if len(c.CachingKeys) == 0 && *(c.Ttl) == 0 { + return nil + } + + m := map[string]interface{}{ + "caching_keys": flattenStringSet(c.CachingKeys), + "ttl": int(aws.Int64Value(c.Ttl)), + } + + return []interface{}{m} +} diff --git a/aws/resource_aws_appsync_resolver_test.go b/aws/resource_aws_appsync_resolver_test.go index 7b18942e7b1..e55ad2d191b 100644 --- a/aws/resource_aws_appsync_resolver_test.go +++ b/aws/resource_aws_appsync_resolver_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/appsync" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAwsAppsyncResolver_basic(t *testing.T) { @@ -220,6 +220,33 @@ func TestAccAwsAppsyncResolver_PipelineConfig(t *testing.T) { }) } +func TestAccAwsAppsyncResolver_CachingConfig(t *testing.T) { + var resolver appsync.Resolver + rName := fmt.Sprintf("tfacctest%d", acctest.RandInt()) + resourceName := "aws_appsync_resolver.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsAppsyncResolverDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAppsyncResolver_cachingConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsAppsyncResolverExists(resourceName, &resolver), + resource.TestCheckResourceAttr(resourceName, "caching_config.0.caching_keys.#", "2"), + resource.TestCheckResourceAttr(resourceName, "caching_config.0.ttl", "60"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func testAccCheckAwsAppsyncResolverDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).appsyncconn for _, rs := range s.RootModule().Resources { @@ -739,3 +766,74 @@ EOF `, rName) } + +func testAccAppsyncResolver_cachingConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_appsync_graphql_api" "test" { + authentication_type = "API_KEY" + name = "%[1]s" + schema = < 0 ? aws_lb_target_group.test[*].arn : [] - vpc_zone_identifier = [aws_subnet.test.id] - - launch_template { - id = aws_launch_template.test.id - } -} -`, rName, tgCount) -} - func TestAccAWSAutoScalingGroup_initialLifecycleHook(t *testing.T) { var group autoscaling.Group randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSAutoScalingGroupWithHookConfig(randName), @@ -1007,10 +933,11 @@ func TestAccAWSAutoScalingGroup_initialLifecycleHook(t *testing.T) { testAccCheckAWSAutoScalingGroupHealthyCapacity(&group, 2), resource.TestCheckResourceAttr( "aws_autoscaling_group.bar", "initial_lifecycle_hook.#", "1"), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "initial_lifecycle_hook.391359060.default_result", "CONTINUE"), - resource.TestCheckResourceAttr( - "aws_autoscaling_group.bar", "initial_lifecycle_hook.391359060.name", "launching"), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_autoscaling_group.bar", "initial_lifecycle_hook.*", map[string]string{ + "default_result": "CONTINUE", + "name": "launching", + }), + // TODO: TypeSet check rewrite check to avoid hash reference testAccCheckAWSAutoScalingGroupInitialLifecycleHookExists( "aws_autoscaling_group.bar", "initial_lifecycle_hook.391359060.name"), ), @@ -1106,10 +1033,6 @@ func testAccCheckAWSAutoScalingGroupDestroy(s *terraform.State) error { func testAccCheckAWSAutoScalingGroupAttributes(group *autoscaling.Group, name string) resource.TestCheckFunc { return func(s *terraform.State) error { - if *group.AvailabilityZones[0] != "us-west-2a" { - return fmt.Errorf("Bad availability_zones: %#v", group.AvailabilityZones[0]) - } - if *group.AutoScalingGroupName != name { return fmt.Errorf("Bad Autoscaling Group name, expected (%s), got (%s)", name, *group.AutoScalingGroupName) } @@ -1321,7 +1244,7 @@ func TestAccAWSAutoScalingGroup_classicVpcZoneIdentifier(t *testing.T) { CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAutoScalingGroupConfig_classicVpcZoneIdentifier, + Config: testAccAWSAutoScalingGroupConfig_classicVpcZoneIdentifier(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.test", &group), resource.TestCheckResourceAttr("aws_autoscaling_group.test", "vpc_zone_identifier.#", "0"), @@ -1345,39 +1268,6 @@ func TestAccAWSAutoScalingGroup_classicVpcZoneIdentifier(t *testing.T) { }) } -func TestAccAWSAutoScalingGroup_emptyAvailabilityZones(t *testing.T) { - var group autoscaling.Group - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSAutoScalingGroupConfig_emptyAvailabilityZones, - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.test", &group), - resource.TestCheckResourceAttr("aws_autoscaling_group.test", "availability_zones.#", "1"), - ), - }, - { - ResourceName: "aws_autoscaling_group.test", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{ - "force_delete", - "initial_lifecycle_hook", - "name_prefix", - "tag", - "tags", - "wait_for_capacity_timeout", - "wait_for_elb_capacity", - }, - }, - }, - }) -} - func TestAccAWSAutoScalingGroup_launchTemplate(t *testing.T) { var group autoscaling.Group @@ -1387,7 +1277,7 @@ func TestAccAWSAutoScalingGroup_launchTemplate(t *testing.T) { CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate, + Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), resource.TestCheckResourceAttrSet( @@ -1421,7 +1311,7 @@ func TestAccAWSAutoScalingGroup_launchTemplate_update(t *testing.T) { CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate, + Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), resource.TestCheckResourceAttrSet( @@ -1443,7 +1333,7 @@ func TestAccAWSAutoScalingGroup_launchTemplate_update(t *testing.T) { }, }, { - Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchConfig, + Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchConfig(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), resource.TestCheckResourceAttrSet( @@ -1454,7 +1344,7 @@ func TestAccAWSAutoScalingGroup_launchTemplate_update(t *testing.T) { }, { - Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateName, + Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateName(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), resource.TestCheckResourceAttr( @@ -1467,7 +1357,7 @@ func TestAccAWSAutoScalingGroup_launchTemplate_update(t *testing.T) { }, { - Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateVersion, + Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateVersion(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), resource.TestCheckResourceAttr( @@ -1476,7 +1366,7 @@ func TestAccAWSAutoScalingGroup_launchTemplate_update(t *testing.T) { }, { - Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate, + Config: testAccAWSAutoScalingGroupConfig_withLaunchTemplate(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.bar", &group), resource.TestCheckResourceAttrSet( @@ -1708,6 +1598,67 @@ func TestAccAWSAutoScalingGroup_MixedInstancesPolicy_InstancesDistribution_OnDem }) } +// Test to verify fix for behavior in GH-ISSUE 7368 +func TestAccAWSAutoScalingGroup_MixedInstancesPolicy_InstancesDistribution_UpdateToZeroOnDemandBaseCapacity(t *testing.T) { + var group autoscaling.Group + resourceName := "aws_autoscaling_group.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandBaseCapacity(rName, 1), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAutoScalingGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.0.on_demand_base_capacity", "1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "force_delete", + "initial_lifecycle_hook", + "name_prefix", + "tag", + "tags", + "wait_for_capacity_timeout", + "wait_for_elb_capacity", + }, + }, + { + Config: testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandBaseCapacity(rName, 0), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAutoScalingGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.#", "1"), + resource.TestCheckResourceAttr(resourceName, "mixed_instances_policy.0.instances_distribution.0.on_demand_base_capacity", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "force_delete", + "initial_lifecycle_hook", + "name_prefix", + "tag", + "tags", + "wait_for_capacity_timeout", + "wait_for_elb_capacity", + }, + }, + }, + }) +} + func TestAccAWSAutoScalingGroup_MixedInstancesPolicy_InstancesDistribution_OnDemandPercentageAboveBaseCapacity(t *testing.T) { var group autoscaling.Group resourceName := "aws_autoscaling_group.test" @@ -2069,7 +2020,43 @@ func TestAccAWSAutoScalingGroup_MixedInstancesPolicy_LaunchTemplate_Override_Wei }) } -const testAccAWSAutoScalingGroupConfig_autoGeneratedName = ` +func TestAccAWSAutoScalingGroup_launchTempPartitionNum(t *testing.T) { + var group autoscaling.Group + + randName := fmt.Sprintf("terraform-test-%s", acctest.RandString(10)) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAutoScalingGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSAutoScalingGroupPartitionConfig(randName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSAutoScalingGroupExists("aws_autoscaling_group.test", &group), + ), + }, + { + ResourceName: "aws_autoscaling_group.test", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "force_delete", + "initial_lifecycle_hook", + "name_prefix", + "tag", + "tags", + "wait_for_capacity_timeout", + "wait_for_elb_capacity", + }, + }, + }, + }) +} + +func testAccAWSAutoScalingGroupConfig_autoGeneratedName() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2081,20 +2068,23 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = "${aws_launch_configuration.foobar.name}" + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + launch_configuration = aws_launch_configuration.foobar.name +} +`) } -` -const testAccAWSAutoScalingGroupConfig_namePrefix = ` +func testAccAWSAutoScalingGroupConfig_namePrefix() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2106,21 +2096,24 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "test" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "test" { - availability_zones = ["us-west-2a"] - desired_capacity = 0 - max_size = 0 - min_size = 0 - name_prefix = "tf-test-" - launch_configuration = "${aws_launch_configuration.test.name}" + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + name_prefix = "tf-test-" + launch_configuration = aws_launch_configuration.test.name +} +`) } -` -const testAccAWSAutoScalingGroupConfig_terminationPoliciesEmpty = ` +func testAccAWSAutoScalingGroupConfig_terminationPoliciesEmpty() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2132,21 +2125,24 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] - max_size = 0 - min_size = 0 - desired_capacity = 0 + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + desired_capacity = 0 - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name +} +`) } -` -const testAccAWSAutoScalingGroupConfig_terminationPoliciesExplicitDefault = ` +func testAccAWSAutoScalingGroupConfig_terminationPoliciesExplicitDefault() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2158,22 +2154,25 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] - max_size = 0 - min_size = 0 - desired_capacity = 0 + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + desired_capacity = 0 termination_policies = ["Default"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name +} +`) } -` -const testAccAWSAutoScalingGroupConfig_terminationPoliciesUpdate = ` +func testAccAWSAutoScalingGroupConfig_terminationPoliciesUpdate() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2185,23 +2184,25 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] - max_size = 0 - min_size = 0 - desired_capacity = 0 + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 0 + min_size = 0 + desired_capacity = 0 termination_policies = ["OldestInstance"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name +} +`) } -` func testAccAWSAutoScalingGroupConfig(name string) string { - return fmt.Sprintf(` + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2213,7 +2214,7 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } @@ -2223,7 +2224,7 @@ resource "aws_placement_group" "test" { } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[0]] name = "%s" max_size = 5 min_size = 2 @@ -2232,7 +2233,7 @@ resource "aws_autoscaling_group" "bar" { force_delete = true termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name tags = [ { @@ -2241,13 +2242,13 @@ resource "aws_autoscaling_group" "bar" { propagate_at_launch = true }, { - key = "FromTags2" - value = "value2" + key = "FromTags3" + value = "value3" propagate_at_launch = true }, { - key = "FromTags3" - value = "value3" + key = "FromTags2" + value = "value2" propagate_at_launch = true }, ] @@ -2256,7 +2257,8 @@ resource "aws_autoscaling_group" "bar" { } func testAccAWSAutoScalingGroupConfigUpdate(name string) string { - return fmt.Sprintf(` + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2268,17 +2270,17 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_launch_configuration" "new" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[0]] name = "%s" max_size = 5 min_size = 2 @@ -2289,7 +2291,7 @@ resource "aws_autoscaling_group" "bar" { termination_policies = ["ClosestToNextInstanceHour"] protect_from_scale_in = true - launch_configuration = "${aws_launch_configuration.new.name}" + launch_configuration = aws_launch_configuration.new.name tags = [ { @@ -2312,7 +2314,11 @@ resource "aws_autoscaling_group" "bar" { `, name) } -const testAccAWSAutoScalingGroupConfigWithLoadBalancer = ` +func testAccAWSAutoScalingGroupConfigWithLoadBalancer() string { + return composeConfig( + testAccLatestAmazonLinuxHvmEbsAmiConfig(), + testAccAvailableAZsNoOptInDefaultExcludeConfig(), + ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" tags = { @@ -2321,103 +2327,91 @@ resource "aws_vpc" "foo" { } resource "aws_internet_gateway" "gw" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } -data "aws_availability_zones" "available" { - # t2.micro is not supported in us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - - resource "aws_subnet" "foo" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.1.1.0/24" - vpc_id = "${aws_vpc.foo.id}" - tags = { - Name = "tf-acc-autoscaling-group-with-load-balancer" - } + availability_zone = data.aws_availability_zones.available.names[0] + cidr_block = "10.1.1.0/24" + vpc_id = aws_vpc.foo.id + tags = { + Name = "tf-acc-autoscaling-group-with-load-balancer" + } } resource "aws_security_group" "foo" { - vpc_id="${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id ingress { - protocol = "-1" - from_port = 0 - to_port = 0 + protocol = "-1" + from_port = 0 + to_port = 0 cidr_blocks = ["0.0.0.0/0"] } egress { - protocol = "-1" - from_port = 0 - to_port = 0 + protocol = "-1" + from_port = 0 + to_port = 0 cidr_blocks = ["0.0.0.0/0"] } } resource "aws_elb" "bar" { - subnets = ["${aws_subnet.foo.id}"] - security_groups = ["${aws_security_group.foo.id}"] + subnets = [aws_subnet.foo.id] + security_groups = [aws_security_group.foo.id] listener { - instance_port = 80 + instance_port = 80 instance_protocol = "http" - lb_port = 80 - lb_protocol = "http" + lb_port = 80 + lb_protocol = "http" } health_check { - healthy_threshold = 2 + healthy_threshold = 2 unhealthy_threshold = 2 - target = "HTTP:80/" - interval = 5 - timeout = 2 + target = "HTTP:80/" + interval = 5 + timeout = 2 } - depends_on = ["aws_internet_gateway.gw"] + depends_on = ["aws_internet_gateway.gw"] } -// need an AMI that listens on :80 at boot, this is: -data "aws_ami" "test_ami" { - most_recent = true - - owners = ["979382823631"] +resource "aws_launch_configuration" "foobar" { + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + security_groups = [aws_security_group.foo.id] - filter { - name = "name" - values = ["bitnami-nginxstack-*-linux-debian-9-x86_64-hvm-ebs"] - } -} - -resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" - instance_type = "t2.micro" - security_groups = ["${aws_security_group.foo.id}"] + # Need the instance to listen on port 80 at boot + user_data = < index.html +nohup python -m SimpleHTTPServer 80 & +EOF } resource "aws_autoscaling_group" "bar" { - vpc_zone_identifier = ["${aws_subnet.foo.id}"] - max_size = 2 - min_size = 2 + vpc_zone_identifier = [aws_subnet.foo.id] + max_size = 2 + min_size = 2 health_check_grace_period = 300 - health_check_type = "ELB" - wait_for_elb_capacity = 2 - force_delete = true + health_check_type = "ELB" + wait_for_elb_capacity = 2 + force_delete = true - launch_configuration = "${aws_launch_configuration.foobar.name}" - load_balancers = ["${aws_elb.bar.name}"] + launch_configuration = aws_launch_configuration.foobar.name + load_balancers = [aws_elb.bar.name] +} +`) } -` -const testAccAWSAutoScalingGroupConfigWithTargetGroup = ` +func testAccAWSAutoScalingGroupConfigWithTargetGroup() string { + return composeConfig( + testAccLatestAmazonLinuxHvmEbsAmiConfig(), + testAccAvailableAZsNoOptInDefaultExcludeConfig(), + ` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" tags = { @@ -2426,43 +2420,32 @@ resource "aws_vpc" "foo" { } resource "aws_internet_gateway" "gw" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } -data "aws_availability_zones" "available" { - # t2.micro is not supported in us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - resource "aws_subnet" "foo" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.1.1.0/24" - vpc_id = "${aws_vpc.foo.id}" - tags = { - Name = "tf-acc-autoscaling-group-with-target-group" - } + availability_zone = data.aws_availability_zones.available.names[0] + cidr_block = "10.1.1.0/24" + vpc_id = aws_vpc.foo.id + tags = { + Name = "tf-acc-autoscaling-group-with-target-group" + } } resource "aws_security_group" "foo" { - vpc_id="${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id ingress { - protocol = "-1" - from_port = 0 - to_port = 0 + protocol = "-1" + from_port = 0 + to_port = 0 cidr_blocks = ["0.0.0.0/0"] } egress { - protocol = "-1" - from_port = 0 - to_port = 0 + protocol = "-1" + from_port = 0 + to_port = 0 cidr_blocks = ["0.0.0.0/0"] } } @@ -2470,65 +2453,62 @@ resource "aws_security_group" "foo" { resource "aws_lb_target_group" "foo" { port = 80 protocol = "HTTP" - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } resource "aws_elb" "bar" { - subnets = ["${aws_subnet.foo.id}"] - security_groups = ["${aws_security_group.foo.id}"] + subnets = [aws_subnet.foo.id] + security_groups = [aws_security_group.foo.id] listener { - instance_port = 80 + instance_port = 80 instance_protocol = "http" - lb_port = 80 - lb_protocol = "http" + lb_port = 80 + lb_protocol = "http" } health_check { - healthy_threshold = 2 + healthy_threshold = 2 unhealthy_threshold = 2 - target = "HTTP:80/" - interval = 5 - timeout = 2 + target = "HTTP:80/" + interval = 5 + timeout = 2 } - depends_on = ["aws_internet_gateway.gw"] -} - -// need an AMI that listens on :80 at boot, this is: -data "aws_ami" "test_ami" { - most_recent = true - - owners = ["979382823631"] - - filter { - name = "name" - values = ["bitnami-nginxstack-*-linux-debian-9-x86_64-hvm-ebs"] - } + depends_on = ["aws_internet_gateway.gw"] } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" - instance_type = "t2.micro" - security_groups = ["${aws_security_group.foo.id}"] + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + security_groups = [aws_security_group.foo.id] + + # Need the instance to listen on port 80 at boot + user_data = < index.html +nohup python -m SimpleHTTPServer 80 & +EOF } resource "aws_autoscaling_group" "bar" { - availability_zones = ["${aws_subnet.foo.availability_zone}"] - vpc_zone_identifier = ["${aws_subnet.foo.id}"] - max_size = 2 - min_size = 2 + vpc_zone_identifier = [aws_subnet.foo.id] + max_size = 2 + min_size = 2 health_check_grace_period = 300 - health_check_type = "ELB" - wait_for_elb_capacity = 2 - force_delete = true + health_check_type = "ELB" + wait_for_elb_capacity = 2 + force_delete = true - launch_configuration = "${aws_launch_configuration.foobar.name}" - target_group_arns = ["${aws_lb_target_group.foo.arn}"] + launch_configuration = aws_launch_configuration.foobar.name + target_group_arns = [aws_lb_target_group.foo.arn] +} +`) } -` -const testAccAWSAutoScalingGroupConfigWithAZ = ` +func testAccAWSAutoScalingGroupConfigWithAZ() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` resource "aws_vpc" "default" { cidr_block = "10.0.0.0/16" tags = { @@ -2537,9 +2517,9 @@ resource "aws_vpc" "default" { } resource "aws_subnet" "main" { - vpc_id = "${aws_vpc.default.id}" - cidr_block = "10.0.1.0/24" - availability_zone = "us-west-2a" + vpc_id = aws_vpc.default.id + cidr_block = "10.0.1.0/24" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-autoscaling-group-with-az" } @@ -2556,22 +2536,25 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { availability_zones = [ - "us-west-2a" + data.aws_availability_zones.available.names[0] ] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = "${aws_launch_configuration.foobar.name}" + desired_capacity = 0 + max_size = 0 + min_size = 0 + launch_configuration = aws_launch_configuration.foobar.name +} +`) } -` -const testAccAWSAutoScalingGroupConfigWithVPCIdent = ` +func testAccAWSAutoScalingGroupConfigWithVPCIdent() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` resource "aws_vpc" "default" { cidr_block = "10.0.0.0/16" tags = { @@ -2580,9 +2563,9 @@ resource "aws_vpc" "default" { } resource "aws_subnet" "main" { - vpc_id = "${aws_vpc.default.id}" - cidr_block = "10.0.1.0/24" - availability_zone = "us-west-2a" + vpc_id = aws_vpc.default.id + cidr_block = "10.0.1.0/24" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-autoscaling-group-with-vpc-id" } @@ -2599,23 +2582,25 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { vpc_zone_identifier = [ - "${aws_subnet.main.id}", + aws_subnet.main.id, ] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = "${aws_launch_configuration.foobar.name}" + desired_capacity = 0 + max_size = 0 + min_size = 0 + launch_configuration = aws_launch_configuration.foobar.name +} +`) } -` func testAccAWSAutoScalingGroupConfig_withPlacementGroup(name string) string { - return fmt.Sprintf(` + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2627,7 +2612,7 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "c3.large" } @@ -2637,7 +2622,7 @@ resource "aws_placement_group" "test" { } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[0]] name = "%s" max_size = 1 min_size = 1 @@ -2646,9 +2631,9 @@ resource "aws_autoscaling_group" "bar" { desired_capacity = 1 force_delete = true termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] - placement_group = "${aws_placement_group.test.name}" + placement_group = aws_placement_group.test.name - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name tag { key = "Foo" @@ -2659,7 +2644,9 @@ resource "aws_autoscaling_group" "bar" { `, name, name) } -const testAccAWSAutoScalingGroupConfig_withServiceLinkedRoleARN = ` +func testAccAWSAutoScalingGroupConfig_withServiceLinkedRoleARN() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2675,21 +2662,24 @@ data "aws_iam_role" "autoscaling_service_linked_role" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = "${aws_launch_configuration.foobar.name}" - service_linked_role_arn = "${data.aws_iam_role.autoscaling_service_linked_role.arn}" + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + launch_configuration = aws_launch_configuration.foobar.name + service_linked_role_arn = data.aws_iam_role.autoscaling_service_linked_role.arn +} +`) } -` -const testAccAWSAutoScalingGroupConfig_withMaxInstanceLifetime = ` +func testAccAWSAutoScalingGroupConfig_withMaxInstanceLifetime() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2701,21 +2691,24 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = "${aws_launch_configuration.foobar.name}" + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + launch_configuration = aws_launch_configuration.foobar.name max_instance_lifetime = "864000" } -` +`) +} -const testAccAWSAutoScalingGroupConfig_withMaxInstanceLifetime_update = ` +func testAccAWSAutoScalingGroupConfig_withMaxInstanceLifetime_update() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2727,21 +2720,24 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = "${aws_launch_configuration.foobar.name}" + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + launch_configuration = aws_launch_configuration.foobar.name max_instance_lifetime = "604800" } -` +`) +} -const testAccAWSAutoscalingMetricsCollectionConfig_allMetricsCollected = ` +func testAccAWSAutoscalingMetricsCollectionConfig_allMetricsCollected() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2753,39 +2749,42 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] - max_size = 1 - min_size = 0 + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 1 + min_size = 0 health_check_grace_period = 300 - health_check_type = "EC2" - desired_capacity = 0 - force_delete = true - termination_policies = ["OldestInstance","ClosestToNextInstanceHour"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + health_check_type = "EC2" + desired_capacity = 0 + force_delete = true + termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] + launch_configuration = aws_launch_configuration.foobar.name enabled_metrics = ["GroupTotalInstances", - "GroupPendingInstances", - "GroupTerminatingInstances", - "GroupDesiredCapacity", - "GroupInServiceInstances", - "GroupMinSize", - "GroupMaxSize", - "GroupPendingCapacity", - "GroupInServiceCapacity", - "GroupStandbyCapacity", - "GroupTotalCapacity", - "GroupTerminatingCapacity", - "GroupStandbyInstances" + "GroupPendingInstances", + "GroupTerminatingInstances", + "GroupDesiredCapacity", + "GroupInServiceInstances", + "GroupMinSize", + "GroupMaxSize", + "GroupPendingCapacity", + "GroupInServiceCapacity", + "GroupStandbyCapacity", + "GroupTotalCapacity", + "GroupTerminatingCapacity", + "GroupStandbyInstances" ] metrics_granularity = "1Minute" } -` +`) +} -const testAccAWSAutoscalingMetricsCollectionConfig_updatingMetricsCollected = ` +func testAccAWSAutoscalingMetricsCollectionConfig_updatingMetricsCollected() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -2797,31 +2796,34 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] - max_size = 1 - min_size = 0 + availability_zones = [data.aws_availability_zones.available.names[0]] + max_size = 1 + min_size = 0 health_check_grace_period = 300 - health_check_type = "EC2" - desired_capacity = 0 - force_delete = true - termination_policies = ["OldestInstance","ClosestToNextInstanceHour"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + health_check_type = "EC2" + desired_capacity = 0 + force_delete = true + termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] + launch_configuration = aws_launch_configuration.foobar.name enabled_metrics = ["GroupTotalInstances", - "GroupPendingInstances", - "GroupTerminatingInstances", - "GroupDesiredCapacity", - "GroupMaxSize" + "GroupPendingInstances", + "GroupTerminatingInstances", + "GroupDesiredCapacity", + "GroupMaxSize" ] metrics_granularity = "1Minute" } -` +`) +} -const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_pre = ` +func testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_pre() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` resource "aws_vpc" "default" { cidr_block = "10.0.0.0/16" @@ -2834,13 +2836,13 @@ resource "aws_lb_target_group" "test" { name = "tf-example-alb-tg" port = 80 protocol = "HTTP" - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id } resource "aws_subnet" "main" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id cidr_block = "10.0.1.0/24" - availability_zone = "us-west-2a" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-autoscaling-group-alb-target-group-main" @@ -2848,9 +2850,9 @@ resource "aws_subnet" "main" { } resource "aws_subnet" "alt" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id cidr_block = "10.0.2.0/24" - availability_zone = "us-west-2b" + availability_zone = data.aws_availability_zones.available.names[1] tags = { Name = "tf-acc-autoscaling-group-alb-target-group-alt" @@ -2868,15 +2870,15 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" enable_monitoring = false } resource "aws_autoscaling_group" "bar" { vpc_zone_identifier = [ - "${aws_subnet.main.id}", - "${aws_subnet.alt.id}", + aws_subnet.main.id, + aws_subnet.alt.id, ] max_size = 2 @@ -2886,14 +2888,14 @@ resource "aws_autoscaling_group" "bar" { desired_capacity = 0 force_delete = true termination_policies = ["OldestInstance"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name } resource "aws_security_group" "tf_test_self" { name = "tf_test_alb_asg" description = "tf_test_alb_asg" - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id ingress { from_port = 80 @@ -2906,9 +2908,12 @@ resource "aws_security_group" "tf_test_self" { Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup" } } -` +`) +} -const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post = ` +func testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` resource "aws_vpc" "default" { cidr_block = "10.0.0.0/16" @@ -2921,13 +2926,13 @@ resource "aws_lb_target_group" "test" { name = "tf-example-alb-tg" port = 80 protocol = "HTTP" - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id } resource "aws_subnet" "main" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id cidr_block = "10.0.1.0/24" - availability_zone = "us-west-2a" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-autoscaling-group-alb-target-group-main" @@ -2935,9 +2940,9 @@ resource "aws_subnet" "main" { } resource "aws_subnet" "alt" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id cidr_block = "10.0.2.0/24" - availability_zone = "us-west-2b" + availability_zone = data.aws_availability_zones.available.names[1] tags = { Name = "tf-acc-autoscaling-group-alb-target-group-alt" @@ -2955,18 +2960,18 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" enable_monitoring = false } resource "aws_autoscaling_group" "bar" { vpc_zone_identifier = [ - "${aws_subnet.main.id}", - "${aws_subnet.alt.id}", + aws_subnet.main.id, + aws_subnet.alt.id, ] - target_group_arns = ["${aws_lb_target_group.test.arn}"] + target_group_arns = [aws_lb_target_group.test.arn] max_size = 2 min_size = 0 @@ -2975,14 +2980,14 @@ resource "aws_autoscaling_group" "bar" { desired_capacity = 0 force_delete = true termination_policies = ["OldestInstance"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name } resource "aws_security_group" "tf_test_self" { name = "tf_test_alb_asg" description = "tf_test_alb_asg" - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id ingress { from_port = 80 @@ -2995,9 +3000,12 @@ resource "aws_security_group" "tf_test_self" { Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup" } } -` +`) +} -const testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post_duo = ` +func testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_post_duo() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` resource "aws_vpc" "default" { cidr_block = "10.0.0.0/16" @@ -3010,20 +3018,20 @@ resource "aws_lb_target_group" "test" { name = "tf-example-alb-tg" port = 80 protocol = "HTTP" - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id } resource "aws_lb_target_group" "test_more" { name = "tf-example-alb-tg-more" port = 80 protocol = "HTTP" - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id } resource "aws_subnet" "main" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id cidr_block = "10.0.1.0/24" - availability_zone = "us-west-2a" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-autoscaling-group-alb-target-group-main" @@ -3031,9 +3039,9 @@ resource "aws_subnet" "main" { } resource "aws_subnet" "alt" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id cidr_block = "10.0.2.0/24" - availability_zone = "us-west-2b" + availability_zone = data.aws_availability_zones.available.names[1] tags = { Name = "tf-acc-autoscaling-group-alb-target-group-alt" @@ -3051,21 +3059,21 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" enable_monitoring = false } resource "aws_autoscaling_group" "bar" { vpc_zone_identifier = [ - "${aws_subnet.main.id}", - "${aws_subnet.alt.id}", + aws_subnet.main.id, + aws_subnet.alt.id, ] - target_group_arns = [ - "${aws_lb_target_group.test.arn}", - "${aws_lb_target_group.test_more.arn}", - ] + target_group_arns = [ + aws_lb_target_group.test.arn, + aws_lb_target_group.test_more.arn, + ] max_size = 2 min_size = 0 @@ -3074,14 +3082,14 @@ resource "aws_autoscaling_group" "bar" { desired_capacity = 0 force_delete = true termination_policies = ["OldestInstance"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name } resource "aws_security_group" "tf_test_self" { name = "tf_test_alb_asg" description = "tf_test_alb_asg" - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id ingress { from_port = 80 @@ -3094,10 +3102,71 @@ resource "aws_security_group" "tf_test_self" { Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup" } } -` +`) +} + +func testAccAWSAutoScalingGroupConfig_TargetGroupArns(rName string, tgCount int) string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` +data "aws_ami" "test" { + most_recent = true + owners = ["amazon"] + + filter { + name = "name" + values = ["amzn-ami-hvm-*-x86_64-gp2"] + } +} + +resource "aws_launch_template" "test" { + image_id = data.aws_ami.test.id + instance_type = "t3.micro" + name = %[1]q +} + +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_subnet" "test" { + availability_zone = data.aws_availability_zones.available.names[0] + cidr_block = "10.0.0.0/24" + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } +} + +resource "aws_lb_target_group" "test" { + count = %[2]d + + port = 80 + protocol = "HTTP" + vpc_id = aws_vpc.test.id +} + +resource "aws_autoscaling_group" "test" { + force_delete = true + max_size = 0 + min_size = 0 + target_group_arns = length(aws_lb_target_group.test) > 0 ? aws_lb_target_group.test[*].arn : [] + vpc_zone_identifier = [aws_subnet.test.id] + + launch_template { + id = aws_launch_template.test.id + } +} +`, rName, tgCount) +} func testAccAWSAutoScalingGroupWithHookConfig(name string) string { - return fmt.Sprintf(` + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -3109,12 +3178,12 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[0]] name = "%s" max_size = 5 min_size = 2 @@ -3123,12 +3192,12 @@ resource "aws_autoscaling_group" "bar" { force_delete = true termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name initial_lifecycle_hook { name = "launching" default_result = "CONTINUE" - heartbeat_timeout = 30 # minimum value + heartbeat_timeout = 30 # minimum value lifecycle_transition = "autoscaling:EC2_INSTANCE_LAUNCHING" } } @@ -3136,7 +3205,8 @@ resource "aws_autoscaling_group" "bar" { } func testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity(rInt int) string { - return fmt.Sprintf(` + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` resource "aws_vpc" "default" { cidr_block = "10.0.0.0/16" enable_dns_hostnames = "true" @@ -3148,7 +3218,7 @@ resource "aws_vpc" "default" { } resource "aws_lb" "test_lb" { - subnets = ["${aws_subnet.main.id}", "${aws_subnet.alt.id}"] + subnets = [aws_subnet.main.id, aws_subnet.alt.id] tags = { Name = "testAccAWSAutoScalingGroupConfig_ALB_TargetGroup_ELBCapacity" @@ -3156,11 +3226,11 @@ resource "aws_lb" "test_lb" { } resource "aws_lb_listener" "test_listener" { - load_balancer_arn = "${aws_lb.test_lb.arn}" + load_balancer_arn = aws_lb.test_lb.arn port = "80" default_action { - target_group_arn = "${aws_lb_target_group.test.arn}" + target_group_arn = aws_lb_target_group.test.arn type = "forward" } } @@ -3169,7 +3239,7 @@ resource "aws_lb_target_group" "test" { name = "tf-alb-test-%d" port = 80 protocol = "HTTP" - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id health_check { path = "/" @@ -3185,9 +3255,9 @@ resource "aws_lb_target_group" "test" { } resource "aws_subnet" "main" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id cidr_block = "10.0.1.0/24" - availability_zone = "us-west-2a" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-autoscaling-group-alb-target-group-elb-capacity-main" @@ -3195,9 +3265,9 @@ resource "aws_subnet" "main" { } resource "aws_subnet" "alt" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id cidr_block = "10.0.2.0/24" - availability_zone = "us-west-2b" + availability_zone = data.aws_availability_zones.available.names[1] tags = { Name = "tf-acc-autoscaling-group-alb-target-group-elb-capacity-alt" @@ -3205,27 +3275,27 @@ resource "aws_subnet" "alt" { } resource "aws_internet_gateway" "internet_gateway" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id } resource "aws_route_table" "route_table" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id } resource "aws_route_table_association" "route_table_association_main" { - subnet_id = "${aws_subnet.main.id}" - route_table_id = "${aws_route_table.route_table.id}" + subnet_id = aws_subnet.main.id + route_table_id = aws_route_table.route_table.id } resource "aws_route_table_association" "route_table_association_alt" { - subnet_id = "${aws_subnet.alt.id}" - route_table_id = "${aws_route_table.route_table.id}" + subnet_id = aws_subnet.alt.id + route_table_id = aws_route_table.route_table.id } resource "aws_route" "public_default_route" { - route_table_id = "${aws_route_table.route_table.id}" + route_table_id = aws_route_table.route_table.id destination_cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.internet_gateway.id}" + gateway_id = aws_internet_gateway.internet_gateway.id } data "aws_ami" "test_ami" { @@ -3239,7 +3309,7 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" associate_public_ip_address = "true" @@ -3254,11 +3324,11 @@ EOS resource "aws_autoscaling_group" "bar" { vpc_zone_identifier = [ - "${aws_subnet.main.id}", - "${aws_subnet.alt.id}", + aws_subnet.main.id, + aws_subnet.alt.id, ] - target_group_arns = ["${aws_lb_target_group.test.arn}"] + target_group_arns = [aws_lb_target_group.test.arn] max_size = 2 min_size = 2 @@ -3268,13 +3338,14 @@ resource "aws_autoscaling_group" "bar" { wait_for_elb_capacity = 2 force_delete = true termination_policies = ["OldestInstance"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name } `, rInt) } func testAccAWSAutoScalingGroupConfigWithSuspendedProcesses(name string) string { - return fmt.Sprintf(` + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -3286,7 +3357,7 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } @@ -3296,7 +3367,7 @@ resource "aws_placement_group" "test" { } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[0]] name = "%s" max_size = 5 min_size = 2 @@ -3305,7 +3376,7 @@ resource "aws_autoscaling_group" "bar" { force_delete = true termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name suspended_processes = ["AlarmNotification", "ScheduledActions"] @@ -3319,7 +3390,8 @@ resource "aws_autoscaling_group" "bar" { } func testAccAWSAutoScalingGroupConfigWithSuspendedProcessesUpdated(name string) string { - return fmt.Sprintf(` + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -3331,7 +3403,7 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "foobar" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } @@ -3341,7 +3413,7 @@ resource "aws_placement_group" "test" { } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[0]] name = "%s" max_size = 5 min_size = 2 @@ -3350,7 +3422,7 @@ resource "aws_autoscaling_group" "bar" { force_delete = true termination_policies = ["OldestInstance", "ClosestToNextInstanceHour"] - launch_configuration = "${aws_launch_configuration.foobar.name}" + launch_configuration = aws_launch_configuration.foobar.name suspended_processes = ["AZRebalance", "ScheduledActions"] @@ -3363,14 +3435,15 @@ resource "aws_autoscaling_group" "bar" { `, name, name) } -const testAccAWSAutoScalingGroupConfig_classicVpcZoneIdentifier = ` +func testAccAWSAutoScalingGroupConfig_classicVpcZoneIdentifier() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { min_size = 0 max_size = 0 - availability_zones = ["us-west-2a"] - launch_configuration = "${aws_launch_configuration.test.name}" - vpc_zone_identifier = [] + availability_zones = [data.aws_availability_zones.available.names[0]] + launch_configuration = aws_launch_configuration.test.name } data "aws_ami" "test_ami" { @@ -3384,65 +3457,15 @@ data "aws_ami" "test_ami" { } resource "aws_launch_configuration" "test" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t1.micro" } -` - -const testAccAWSAutoScalingGroupConfig_emptyAvailabilityZones = ` -resource "aws_vpc" "test" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-autoscaling-group-empty-azs" - } -} - -data "aws_availability_zones" "available" { - # t2.micro is not supported in us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - -resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" - vpc_id = "${aws_vpc.test.id}" - cidr_block = "10.0.0.0/16" - tags = { - Name = "tf-acc-autoscaling-group-empty-availability-zones" - } -} - -resource "aws_autoscaling_group" "test" { - min_size = 0 - max_size = 0 - - availability_zones = [] - launch_configuration = "${aws_launch_configuration.test.name}" - vpc_zone_identifier = ["${aws_subnet.test.id}"] -} - -data "aws_ami" "test_ami" { - most_recent = true - owners = ["amazon"] - - filter { - name = "name" - values = ["amzn-ami-hvm-*-x86_64-gp2"] - } -} - -resource "aws_launch_configuration" "test" { - image_id = "${data.aws_ami.test_ami.id}" - instance_type = "t2.micro" +`) } -` -const testAccAWSAutoScalingGroupConfig_withLaunchTemplate = ` +func testAccAWSAutoScalingGroupConfig_withLaunchTemplate() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -3454,33 +3477,27 @@ data "aws_ami" "test_ami" { } resource "aws_launch_template" "foobar" { - name_prefix = "foobar" - image_id = "${data.aws_ami.test_ami.id}" + name_prefix = "foobar" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - resource "aws_autoscaling_group" "bar" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] - desired_capacity = 0 - max_size = 0 - min_size = 0 + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 launch_template { - id = "${aws_launch_template.foobar.id}" - version = "${aws_launch_template.foobar.default_version}" + id = aws_launch_template.foobar.id + version = aws_launch_template.foobar.default_version } } -` +`) +} -const testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchConfig = ` +func testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchConfig() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -3492,35 +3509,29 @@ data "aws_ami" "test_ami" { } resource "aws_launch_template" "foobar" { - name_prefix = "foobar" - image_id = "${data.aws_ami.test_ami.id}" + name_prefix = "foobar" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_launch_configuration" "test" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - resource "aws_autoscaling_group" "bar" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] - desired_capacity = 0 - max_size = 0 - min_size = 0 - launch_configuration = "${aws_launch_configuration.test.name}" + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 + launch_configuration = aws_launch_configuration.test.name +} +`) } -` -const testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateName = ` +func testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateName() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -3532,43 +3543,37 @@ data "aws_ami" "test_ami" { } resource "aws_launch_template" "foobar" { - name_prefix = "foobar" - image_id = "${data.aws_ami.test_ami.id}" + name_prefix = "foobar" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_launch_configuration" "test" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_launch_template" "foobar2" { - name = "foobar2" - image_id = "${data.aws_ami.test_ami.id}" + name = "foobar2" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - resource "aws_autoscaling_group" "bar" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] - desired_capacity = 0 - max_size = 0 - min_size = 0 + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 launch_template { name = "foobar2" } } -` +`) +} -const testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateVersion = ` +func testAccAWSAutoScalingGroupConfig_withLaunchTemplate_toLaunchTemplateVersion() string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test_ami" { most_recent = true owners = ["amazon"] @@ -3580,45 +3585,38 @@ data "aws_ami" "test_ami" { } resource "aws_launch_template" "foobar" { - name_prefix = "foobar" - image_id = "${data.aws_ami.test_ami.id}" + name_prefix = "foobar" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_launch_configuration" "test" { - image_id = "${data.aws_ami.test_ami.id}" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } resource "aws_launch_template" "foobar2" { - name = "foobar2" - image_id = "${data.aws_ami.test_ami.id}" + name = "foobar2" + image_id = data.aws_ami.test_ami.id instance_type = "t2.micro" } -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - resource "aws_autoscaling_group" "bar" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] - desired_capacity = 0 - max_size = 0 - min_size = 0 + availability_zones = [data.aws_availability_zones.available.names[0]] + desired_capacity = 0 + max_size = 0 + min_size = 0 launch_template { - id = "${aws_launch_template.foobar.id}" + id = aws_launch_template.foobar.id version = "$Latest" } } -` +`) +} func testAccAWSAutoScalingGroupConfig_LaunchTemplate_IAMInstanceProfile(rName string) string { - return fmt.Sprintf(` + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test" { most_recent = true owners = ["amazon"] @@ -3629,51 +3627,43 @@ data "aws_ami" "test" { } } -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - resource "aws_iam_role" "test" { assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}" name = %q } resource "aws_iam_instance_profile" "test" { - name = %q - roles = ["${aws_iam_role.test.name}"] + name = %q + role = aws_iam_role.test.name } resource "aws_launch_template" "test" { - image_id = "${data.aws_ami.test.id}" + image_id = data.aws_ami.test.id instance_type = "t2.micro" name = %q iam_instance_profile { - name = "${aws_iam_instance_profile.test.id}" + name = aws_iam_instance_profile.test.id } } resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 name = %q launch_template { - id = "${aws_launch_template.test.id}" + id = aws_launch_template.test.id } } `, rName, rName, rName, rName) } func testAccAWSAutoScalingGroupConfig_LoadBalancers(rName string, elbCount int) string { - return fmt.Sprintf(` + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test" { most_recent = true owners = ["amazon"] @@ -3684,17 +3674,6 @@ data "aws_ami" "test" { } } -data "aws_availability_zones" "available" { - # t2.micro is not supported in us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - resource "aws_launch_template" "test" { image_id = data.aws_ami.test.id instance_type = "t3.micro" @@ -3752,7 +3731,8 @@ resource "aws_autoscaling_group" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName string) string { - return fmt.Sprintf(` + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` data "aws_ami" "test" { most_recent = true owners = ["amazon"] @@ -3763,17 +3743,8 @@ data "aws_ami" "test" { } } -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - resource "aws_launch_template" "test" { - image_id = "${data.aws_ami.test.id}" + image_id = data.aws_ami.test.id instance_type = "t3.micro" name = %q } @@ -3781,9 +3752,10 @@ resource "aws_launch_template" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy(rName string) string { - return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + fmt.Sprintf(` + return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 @@ -3792,7 +3764,7 @@ resource "aws_autoscaling_group" "test" { mixed_instances_policy { launch_template { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" + launch_template_id = aws_launch_template.test.id } override { @@ -3810,9 +3782,10 @@ resource "aws_autoscaling_group" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandAllocationStrategy(rName, onDemandAllocationStrategy string) string { - return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + fmt.Sprintf(` + return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 @@ -3825,7 +3798,7 @@ resource "aws_autoscaling_group" "test" { launch_template { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" + launch_template_id = aws_launch_template.test.id } override { @@ -3841,9 +3814,10 @@ resource "aws_autoscaling_group" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandBaseCapacity(rName string, onDemandBaseCapacity int) string { - return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + fmt.Sprintf(` + return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 2 min_size = 0 @@ -3856,7 +3830,7 @@ resource "aws_autoscaling_group" "test" { launch_template { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" + launch_template_id = aws_launch_template.test.id } override { @@ -3872,9 +3846,10 @@ resource "aws_autoscaling_group" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_InstancesDistribution_OnDemandPercentageAboveBaseCapacity(rName string, onDemandPercentageAboveBaseCapacity int) string { - return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + fmt.Sprintf(` + return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 @@ -3887,7 +3862,7 @@ resource "aws_autoscaling_group" "test" { launch_template { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" + launch_template_id = aws_launch_template.test.id } override { @@ -3903,9 +3878,10 @@ resource "aws_autoscaling_group" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotAllocationStrategy(rName, spotAllocationStrategy string) string { - return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + fmt.Sprintf(` + return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 @@ -3918,7 +3894,7 @@ resource "aws_autoscaling_group" "test" { launch_template { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" + launch_template_id = aws_launch_template.test.id } override { @@ -3934,9 +3910,10 @@ resource "aws_autoscaling_group" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotInstancePools(rName string, spotInstancePools int) string { - return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + fmt.Sprintf(` + return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 @@ -3949,7 +3926,7 @@ resource "aws_autoscaling_group" "test" { launch_template { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" + launch_template_id = aws_launch_template.test.id } override { @@ -3965,9 +3942,10 @@ resource "aws_autoscaling_group" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_InstancesDistribution_SpotMaxPrice(rName, spotMaxPrice string) string { - return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + fmt.Sprintf(` + return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 @@ -3980,7 +3958,7 @@ resource "aws_autoscaling_group" "test" { launch_template { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" + launch_template_id = aws_launch_template.test.id } override { @@ -3996,9 +3974,10 @@ resource "aws_autoscaling_group" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_LaunchTemplate_LaunchTemplateSpecification_LaunchTemplateName(rName string) string { - return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + fmt.Sprintf(` + return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 @@ -4007,7 +3986,7 @@ resource "aws_autoscaling_group" "test" { mixed_instances_policy { launch_template { launch_template_specification { - launch_template_name = "${aws_launch_template.test.name}" + launch_template_name = aws_launch_template.test.name } override { @@ -4023,9 +4002,10 @@ resource "aws_autoscaling_group" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_LaunchTemplate_LaunchTemplateSpecification_Version(rName, version string) string { - return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + fmt.Sprintf(` + return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 @@ -4034,7 +4014,7 @@ resource "aws_autoscaling_group" "test" { mixed_instances_policy { launch_template { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" + launch_template_id = aws_launch_template.test.id version = %q } @@ -4051,9 +4031,10 @@ resource "aws_autoscaling_group" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_LaunchTemplate_Override_InstanceType(rName, instanceType string) string { - return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + fmt.Sprintf(` + return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 0 max_size = 0 min_size = 0 @@ -4062,7 +4043,7 @@ resource "aws_autoscaling_group" "test" { mixed_instances_policy { launch_template { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" + launch_template_id = aws_launch_template.test.id } override { @@ -4078,9 +4059,10 @@ resource "aws_autoscaling_group" "test" { } func testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_LaunchTemplate_Override_WeightedCapacity(rName string) string { - return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + fmt.Sprintf(` + return testAccAWSAutoScalingGroupConfig_MixedInstancesPolicy_Base(rName) + + fmt.Sprintf(` resource "aws_autoscaling_group" "test" { - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] desired_capacity = 4 max_size = 6 min_size = 2 @@ -4089,7 +4071,7 @@ resource "aws_autoscaling_group" "test" { mixed_instances_policy { launch_template { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" + launch_template_id = aws_launch_template.test.id } override { @@ -4105,3 +4087,46 @@ resource "aws_autoscaling_group" "test" { } `, rName) } + +func testAccAWSAutoScalingGroupPartitionConfig(rName string) string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` +data "aws_ami" "test_ami" { + most_recent = true + owners = ["amazon"] + + filter { + name = "name" + values = ["amzn-ami-hvm-*-x86_64-gp2"] + } +} + +resource "aws_launch_template" "this" { + name = %[1]q + image_id = data.aws_ami.test_ami.id + instance_type = "m5.large" + + placement { + tenancy = "default" + group_name = aws_placement_group.test.id + } +} + +resource "aws_placement_group" "test" { + name = %[1]q + strategy = "cluster" +} + +resource "aws_autoscaling_group" "test" { + name_prefix = "test" + availability_zones = [data.aws_availability_zones.available.names[0]] + min_size = 0 + max_size = 0 + + launch_template { + id = aws_launch_template.this.id + version = "$Latest" + } +} +`, rName) +} diff --git a/aws/resource_aws_autoscaling_group_waiting.go b/aws/resource_aws_autoscaling_group_waiting.go index 247bd1f0fc0..1e3279c3d3d 100644 --- a/aws/resource_aws_autoscaling_group_waiting.go +++ b/aws/resource_aws_autoscaling_group_waiting.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // waitForASGCapacityTimeout gathers the current numbers of healthy instances diff --git a/aws/resource_aws_autoscaling_lifecycle_hook.go b/aws/resource_aws_autoscaling_lifecycle_hook.go index aa96aa0e586..1e9ac0cf2a2 100644 --- a/aws/resource_aws_autoscaling_lifecycle_hook.go +++ b/aws/resource_aws_autoscaling_lifecycle_hook.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsAutoscalingLifecycleHook() *schema.Resource { diff --git a/aws/resource_aws_autoscaling_lifecycle_hook_test.go b/aws/resource_aws_autoscaling_lifecycle_hook_test.go index 41f04ed1087..9dcc3099086 100644 --- a/aws/resource_aws_autoscaling_lifecycle_hook_test.go +++ b/aws/resource_aws_autoscaling_lifecycle_hook_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAutoscalingLifecycleHook_basic(t *testing.T) { @@ -125,10 +125,10 @@ func testAccAWSAutoscalingLifecycleHookImportStateIdFunc(resourceName string) re } func testAccAWSAutoscalingLifecycleHookConfig(name string) string { - return fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_launch_configuration" "foobar" { name = "%s" - image_id = "ami-21f78e11" + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t1.micro" } @@ -177,8 +177,17 @@ resource "aws_iam_role_policy" "foobar" { EOF } +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_autoscaling_group" "foobar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[1]] name = "%s" max_size = 5 min_size = 2 @@ -215,10 +224,10 @@ EOF } func testAccAWSAutoscalingLifecycleHookConfig_omitDefaultResult(name string, rInt int) string { - return fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_launch_configuration" "foobar" { name = "%s" - image_id = "ami-21f78e11" + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t1.micro" } @@ -267,8 +276,17 @@ resource "aws_iam_role_policy" "foobar" { EOF } +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_autoscaling_group" "foobar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[1]] name = "%s" max_size = 5 min_size = 2 diff --git a/aws/resource_aws_autoscaling_notification.go b/aws/resource_aws_autoscaling_notification.go index a07d3c8a06f..72f59c9a625 100644 --- a/aws/resource_aws_autoscaling_notification.go +++ b/aws/resource_aws_autoscaling_notification.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsAutoscalingNotification() *schema.Resource { diff --git a/aws/resource_aws_autoscaling_notification_test.go b/aws/resource_aws_autoscaling_notification_test.go index 9dff23b450d..fdaa2fad5a9 100644 --- a/aws/resource_aws_autoscaling_notification_test.go +++ b/aws/resource_aws_autoscaling_notification_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSASGNotification_basic(t *testing.T) { @@ -71,7 +71,7 @@ func TestAccAWSASGNotification_Pagination(t *testing.T) { CheckDestroy: testAccCheckASGNDestroy, Steps: []resource.TestStep{ { - Config: testAccASGNotificationConfig_pagination, + Config: testAccASGNotificationConfig_pagination(), Check: resource.ComposeTestCheckFunc( testAccCheckASGNotificationExists("aws_autoscaling_notification.example", []string{ @@ -211,19 +211,28 @@ func testAccCheckAWSASGNotificationAttributes(n string, asgn *autoscaling.Descri } func testAccASGNotificationConfig_basic(rName string) string { - return fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_sns_topic" "topic_example" { name = "user-updates-topic-%s" } resource "aws_launch_configuration" "foobar" { name = "foobarautoscaling-terraform-test-%s" - image_id = "ami-21f78e11" - instance_type = "t1.micro" + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" +} + +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[1]] name = "foobar1-terraform-test-%s" max_size = 1 min_size = 1 @@ -249,19 +258,28 @@ resource "aws_autoscaling_notification" "example" { } func testAccASGNotificationConfig_update(rName string) string { - return fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_sns_topic" "topic_example" { name = "user-updates-topic-%s" } resource "aws_launch_configuration" "foobar" { name = "foobarautoscaling-terraform-test-%s" - image_id = "ami-21f78e11" - instance_type = "t1.micro" + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" } +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[1]] name = "foobar1-terraform-test-%s" max_size = 1 min_size = 1 @@ -274,7 +292,7 @@ resource "aws_autoscaling_group" "bar" { } resource "aws_autoscaling_group" "foo" { - availability_zones = ["us-west-2b"] + availability_zones = [data.aws_availability_zones.available.names[2]] name = "barfoo-terraform-test-%s" max_size = 1 min_size = 1 @@ -303,18 +321,28 @@ resource "aws_autoscaling_notification" "example" { `, rName, rName, rName, rName) } -const testAccASGNotificationConfig_pagination = ` +func testAccASGNotificationConfig_pagination() string { + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_sns_topic" "user_updates" { name = "user-updates-topic" } resource "aws_launch_configuration" "foobar" { - image_id = "ami-21f78e11" - instance_type = "t1.micro" + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" +} + +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } } resource "aws_autoscaling_group" "bar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[1]] count = 20 name = "foobar3-terraform-test-${count.index}" max_size = 1 @@ -357,4 +385,5 @@ resource "aws_autoscaling_notification" "example" { "autoscaling:TEST_NOTIFICATION" ] topic_arn = "${aws_sns_topic.user_updates.arn}" -}` +}`) +} diff --git a/aws/resource_aws_autoscaling_policy.go b/aws/resource_aws_autoscaling_policy.go index fc84a550557..63198d8214a 100644 --- a/aws/resource_aws_autoscaling_policy.go +++ b/aws/resource_aws_autoscaling_policy.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsAutoscalingPolicy() *schema.Resource { @@ -71,11 +71,6 @@ func resourceAwsAutoscalingPolicy() *schema.Resource { Optional: true, ValidateFunc: validation.IntAtLeast(1), }, - "min_adjustment_step": { - Type: schema.TypeInt, - Optional: true, - Removed: "Use `min_adjustment_magnitude` argument instead", - }, "scaling_adjustment": { Type: schema.TypeInt, Optional: true, diff --git a/aws/resource_aws_autoscaling_policy_test.go b/aws/resource_aws_autoscaling_policy_test.go index 0b490b0078d..1b07a6f32ba 100644 --- a/aws/resource_aws_autoscaling_policy_test.go +++ b/aws/resource_aws_autoscaling_policy_test.go @@ -8,9 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSAutoscalingPolicy_basic(t *testing.T) { @@ -19,10 +20,9 @@ func TestAccAWSAutoscalingPolicy_basic(t *testing.T) { name := fmt.Sprintf("terraform-testacc-asp-%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSAutoscalingPolicyDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSAutoscalingPolicyDestroy, Steps: []resource.TestStep{ { Config: testAccAWSAutoscalingPolicyConfig_basic(name), @@ -41,7 +41,9 @@ func TestAccAWSAutoscalingPolicy_basic(t *testing.T) { resource.TestCheckResourceAttr("aws_autoscaling_policy.foobar_step", "metric_aggregation_type", "Minimum"), resource.TestCheckResourceAttr("aws_autoscaling_policy.foobar_step", "estimated_instance_warmup", "200"), resource.TestCheckResourceAttr("aws_autoscaling_policy.foobar_step", "autoscaling_group_name", name), - resource.TestCheckResourceAttr("aws_autoscaling_policy.foobar_step", "step_adjustment.2042107634.scaling_adjustment", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_autoscaling_policy.foobar_step", "step_adjustment.*", map[string]string{ + "scaling_adjustment": "1", + }), testAccCheckScalingPolicyExists("aws_autoscaling_policy.foobar_target_tracking", &policy), resource.TestCheckResourceAttr("aws_autoscaling_policy.foobar_target_tracking", "policy_type", "TargetTrackingScaling"), resource.TestCheckResourceAttr("aws_autoscaling_policy.foobar_target_tracking", "name", name+"-foobar_target_tracking"), @@ -80,7 +82,9 @@ func TestAccAWSAutoscalingPolicy_basic(t *testing.T) { testAccCheckScalingPolicyExists("aws_autoscaling_policy.foobar_step", &policy), resource.TestCheckResourceAttr("aws_autoscaling_policy.foobar_step", "policy_type", "StepScaling"), resource.TestCheckResourceAttr("aws_autoscaling_policy.foobar_step", "estimated_instance_warmup", "20"), - resource.TestCheckResourceAttr("aws_autoscaling_policy.foobar_step", "step_adjustment.997979330.scaling_adjustment", "10"), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_autoscaling_policy.foobar_step", "step_adjustment.*", map[string]string{ + "scaling_adjustment": "10", + }), testAccCheckScalingPolicyExists("aws_autoscaling_policy.foobar_target_tracking", &policy), resource.TestCheckResourceAttr("aws_autoscaling_policy.foobar_target_tracking", "policy_type", "TargetTrackingScaling"), resource.TestCheckResourceAttr("aws_autoscaling_policy.foobar_target_tracking", "target_tracking_configuration.#", "1"), diff --git a/aws/resource_aws_autoscaling_schedule.go b/aws/resource_aws_autoscaling_schedule.go index 660d98e089f..d57fb39a02d 100644 --- a/aws/resource_aws_autoscaling_schedule.go +++ b/aws/resource_aws_autoscaling_schedule.go @@ -9,7 +9,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) const awsAutoscalingScheduleTimeLayout = "2006-01-02T15:04:05Z" diff --git a/aws/resource_aws_autoscaling_schedule_test.go b/aws/resource_aws_autoscaling_schedule_test.go index 386f5f9c816..fe9730f0ffe 100644 --- a/aws/resource_aws_autoscaling_schedule_test.go +++ b/aws/resource_aws_autoscaling_schedule_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSAutoscalingSchedule_basic(t *testing.T) { @@ -267,15 +267,24 @@ func testAccCheckScalingScheduleHasNoDesiredCapacity( } func testAccAWSAutoscalingScheduleConfig(r, start, end string) string { - return fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_launch_configuration" "foobar" { name = "%s" - image_id = "ami-21f78e11" + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t1.micro" } +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_autoscaling_group" "foobar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[1]] name = "%s" max_size = 1 min_size = 1 @@ -305,15 +314,24 @@ resource "aws_autoscaling_schedule" "foobar" { } func testAccAWSAutoscalingScheduleConfig_recurrence(r string) string { - return fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_launch_configuration" "foobar" { name = "%s" - image_id = "ami-21f78e11" + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t1.micro" } +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_autoscaling_group" "foobar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[1]] name = "%s" max_size = 1 min_size = 1 @@ -342,15 +360,24 @@ resource "aws_autoscaling_schedule" "foobar" { } func testAccAWSAutoscalingScheduleConfig_zeroValues(r, start, end string) string { - return fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_launch_configuration" "foobar" { name = "%s" - image_id = "ami-21f78e11" + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t1.micro" } +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_autoscaling_group" "foobar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[1]] name = "%s" max_size = 1 min_size = 1 @@ -380,15 +407,24 @@ resource "aws_autoscaling_schedule" "foobar" { } func testAccAWSAutoscalingScheduleConfig_negativeOne(r, start, end string) string { - return fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_launch_configuration" "foobar" { name = "%s" - image_id = "ami-21f78e11" + image_id = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t1.micro" } +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_autoscaling_group" "foobar" { - availability_zones = ["us-west-2a"] + availability_zones = [data.aws_availability_zones.available.names[1]] name = "%s" max_size = 1 min_size = 1 diff --git a/aws/resource_aws_backup_plan.go b/aws/resource_aws_backup_plan.go index 75995a71707..fa548c044c8 100644 --- a/aws/resource_aws_backup_plan.go +++ b/aws/resource_aws_backup_plan.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/backup" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_backup_plan_test.go b/aws/resource_aws_backup_plan_test.go index 028771c64a5..79ab7db1cbd 100644 --- a/aws/resource_aws_backup_plan_test.go +++ b/aws/resource_aws_backup_plan_test.go @@ -7,10 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/backup" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAwsBackupPlan_basic(t *testing.T) { @@ -547,7 +547,7 @@ resource "aws_backup_plan" "test" { rule { rule_name = %[1]q - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" } } @@ -565,7 +565,7 @@ resource "aws_backup_plan" "test" { rule { rule_name = %[1]q - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" } @@ -589,7 +589,7 @@ resource "aws_backup_plan" "test" { rule { rule_name = %[1]q - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" } @@ -613,12 +613,12 @@ resource "aws_backup_plan" "test" { rule { rule_name = "%[1]s_1" - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" } rule { rule_name = "%[1]s_2" - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 6 * * ? *)" } } @@ -636,17 +636,17 @@ resource "aws_backup_plan" "test" { rule { rule_name = "%[1]s_1" - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 6 * * ? *)" } rule { rule_name = "%[1]s_2" - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" } rule { rule_name = "%[1]s_3" - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 18 * * ? *)" } } @@ -664,7 +664,7 @@ resource "aws_backup_plan" "test" { rule { rule_name = %[1]q - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" lifecycle { @@ -686,7 +686,7 @@ resource "aws_backup_plan" "test" { rule { rule_name = %[1]q - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" lifecycle { @@ -708,7 +708,7 @@ resource "aws_backup_plan" "test" { rule { rule_name = %[1]q - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" lifecycle { @@ -731,7 +731,7 @@ resource "aws_backup_plan" "test" { rule { rule_name = %[1]q - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" recovery_point_tags = { @@ -755,7 +755,7 @@ resource "aws_backup_plan" "test" { rule { rule_name = %[1]q - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" recovery_point_tags = { @@ -860,7 +860,7 @@ resource "aws_backup_vault" "test" { } resource "aws_backup_vault" "test2" { - provider = "aws.alternate" + provider = "awsalternate" name = "%[1]s-2" } @@ -869,7 +869,7 @@ resource "aws_backup_plan" "test" { rule { rule_name = %[1]q - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" lifecycle { @@ -883,7 +883,7 @@ resource "aws_backup_plan" "test" { delete_after = 180 } - destination_vault_arn = "${aws_backup_vault.test2.arn}" + destination_vault_arn = aws_backup_vault.test2.arn } } } diff --git a/aws/resource_aws_backup_selection.go b/aws/resource_aws_backup_selection.go index db0fadcc4cb..483ddf0d8bd 100644 --- a/aws/resource_aws_backup_selection.go +++ b/aws/resource_aws_backup_selection.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/backup" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsBackupSelection() *schema.Resource { @@ -145,7 +145,8 @@ func resourceAwsBackupSelectionRead(d *schema.ResourceData, meta interface{}) er } resp, err := conn.GetBackupSelection(input) - if isAWSErr(err, backup.ErrCodeResourceNotFoundException, "") { + if isAWSErr(err, backup.ErrCodeResourceNotFoundException, "") || + isAWSErr(err, backup.ErrCodeInvalidParameterValueException, "Cannot find Backup plan") { log.Printf("[WARN] Backup Selection (%s) not found, removing from state", d.Id()) d.SetId("") return nil diff --git a/aws/resource_aws_backup_selection_test.go b/aws/resource_aws_backup_selection_test.go index 647c83f05fa..8465223070d 100644 --- a/aws/resource_aws_backup_selection_test.go +++ b/aws/resource_aws_backup_selection_test.go @@ -6,22 +6,23 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/backup" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAwsBackupSelection_basic(t *testing.T) { var selection1 backup.GetBackupSelectionOutput resourceName := "aws_backup_selection.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSBackup(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAwsBackupSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigBasic(rInt), + Config: testAccBackupSelectionConfigBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsBackupSelectionExists(resourceName, &selection1), ), @@ -38,8 +39,31 @@ func TestAccAwsBackupSelection_basic(t *testing.T) { func TestAccAwsBackupSelection_disappears(t *testing.T) { var selection1 backup.GetBackupSelectionOutput - rInt := acctest.RandInt() resourceName := "aws_backup_selection.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSBackup(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsBackupSelectionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccBackupSelectionConfigBasic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsBackupSelectionExists(resourceName, &selection1), + testAccCheckResourceDisappears(testAccProvider, resourceAwsBackupSelection(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAwsBackupSelection_backupPlanDisappears(t *testing.T) { + var selection1 backup.GetBackupSelectionOutput + resourceName := "aws_backup_selection.test" + backupPlanResourceName := "aws_backup_plan.test" + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSBackup(t) }, @@ -47,10 +71,11 @@ func TestAccAwsBackupSelection_disappears(t *testing.T) { CheckDestroy: testAccCheckAwsBackupSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigBasic(rInt), + Config: testAccBackupSelectionConfigBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsBackupSelectionExists(resourceName, &selection1), testAccCheckResourceDisappears(testAccProvider, resourceAwsBackupSelection(), resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsBackupPlan(), backupPlanResourceName), ), ExpectNonEmptyPlan: true, }, @@ -61,14 +86,15 @@ func TestAccAwsBackupSelection_disappears(t *testing.T) { func TestAccAwsBackupSelection_withTags(t *testing.T) { var selection1 backup.GetBackupSelectionOutput resourceName := "aws_backup_selection.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSBackup(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAwsBackupSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigWithTags(rInt), + Config: testAccBackupSelectionConfigWithTags(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsBackupSelectionExists(resourceName, &selection1), resource.TestCheckResourceAttr(resourceName, "selection_tag.#", "2"), @@ -87,14 +113,15 @@ func TestAccAwsBackupSelection_withTags(t *testing.T) { func TestAccAwsBackupSelection_withResources(t *testing.T) { var selection1 backup.GetBackupSelectionOutput resourceName := "aws_backup_selection.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSBackup(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAwsBackupSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigWithResources(rInt), + Config: testAccBackupSelectionConfigWithResources(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsBackupSelectionExists(resourceName, &selection1), resource.TestCheckResourceAttr(resourceName, "resources.#", "2"), @@ -113,20 +140,21 @@ func TestAccAwsBackupSelection_withResources(t *testing.T) { func TestAccAwsBackupSelection_updateTag(t *testing.T) { var selection1, selection2 backup.GetBackupSelectionOutput resourceName := "aws_backup_selection.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSBackup(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAwsBackupSelectionDestroy, Steps: []resource.TestStep{ { - Config: testAccBackupSelectionConfigBasic(rInt), + Config: testAccBackupSelectionConfigBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsBackupSelectionExists(resourceName, &selection1), ), }, { - Config: testAccBackupSelectionConfigUpdateTag(rInt), + Config: testAccBackupSelectionConfigUpdateTag(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsBackupSelectionExists(resourceName, &selection2), testAccCheckAwsBackupSelectionRecreated(t, &selection1, &selection2), @@ -217,36 +245,41 @@ func testAccAWSBackupSelectionImportStateIDFunc(resourceName string) resource.Im } } -func testAccBackupSelectionConfigBase(rInt int) string { +func testAccBackupSelectionConfigBase(rName string) string { return fmt.Sprintf(` -data "aws_caller_identity" "current" {} +data "aws_caller_identity" "current" { +} -data "aws_partition" "current" {} +data "aws_partition" "current" { +} -data "aws_region" "current" {} +data "aws_region" "current" { +} resource "aws_backup_vault" "test" { - name = "tf_acc_test_backup_vault_%d" + name = %[1]q } resource "aws_backup_plan" "test" { - name = "tf_acc_test_backup_plan_%d" + name = %[1]q rule { - rule_name = "tf_acc_test_backup_rule_%d" - target_vault_name = "${aws_backup_vault.test.name}" + rule_name = %[1]q + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" } } -`, rInt, rInt, rInt) +`, rName) } -func testAccBackupSelectionConfigBasic(rInt int) string { - return testAccBackupSelectionConfigBase(rInt) + fmt.Sprintf(` +func testAccBackupSelectionConfigBasic(rName string) string { + return composeConfig( + testAccBackupSelectionConfigBase(rName), + fmt.Sprintf(` resource "aws_backup_selection" "test" { - plan_id = "${aws_backup_plan.test.id}" + plan_id = aws_backup_plan.test.id - name = "tf_acc_test_backup_selection_%d" + name = %[1]q iam_role_arn = "arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:role/service-role/AWSBackupDefaultServiceRole" selection_tag { @@ -259,15 +292,17 @@ resource "aws_backup_selection" "test" { "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:volume/" ] } -`, rInt) +`, rName)) } -func testAccBackupSelectionConfigWithTags(rInt int) string { - return testAccBackupSelectionConfigBase(rInt) + fmt.Sprintf(` +func testAccBackupSelectionConfigWithTags(rName string) string { + return composeConfig( + testAccBackupSelectionConfigBase(rName), + fmt.Sprintf(` resource "aws_backup_selection" "test" { - plan_id = "${aws_backup_plan.test.id}" + plan_id = aws_backup_plan.test.id - name = "tf_acc_test_backup_selection_%d" + name = %[1]q iam_role_arn = "arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:role/service-role/AWSBackupDefaultServiceRole" selection_tag { @@ -286,11 +321,13 @@ resource "aws_backup_selection" "test" { "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:volume/" ] } -`, rInt) +`, rName)) } -func testAccBackupSelectionConfigWithResources(rInt int) string { - return testAccBackupSelectionConfigBase(rInt) + fmt.Sprintf(` +func testAccBackupSelectionConfigWithResources(rName string) string { + return composeConfig( + testAccBackupSelectionConfigBase(rName), + fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -303,14 +340,18 @@ data "aws_availability_zones" "available" { resource "aws_ebs_volume" "test" { count = 2 - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] size = 1 + + tags = { + Name = %[1]q + } } resource "aws_backup_selection" "test" { - plan_id = "${aws_backup_plan.test.id}" + plan_id = aws_backup_plan.test.id - name = "tf_acc_test_backup_selection_%d" + name = %[1]q iam_role_arn = "arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:role/service-role/AWSBackupDefaultServiceRole" selection_tag { @@ -320,19 +361,21 @@ resource "aws_backup_selection" "test" { } resources = [ - "${aws_ebs_volume.test.0.arn}", - "${aws_ebs_volume.test.1.arn}", + aws_ebs_volume.test.0.arn, + aws_ebs_volume.test.1.arn, ] } -`, rInt) +`, rName)) } -func testAccBackupSelectionConfigUpdateTag(rInt int) string { - return testAccBackupSelectionConfigBase(rInt) + fmt.Sprintf(` +func testAccBackupSelectionConfigUpdateTag(rName string) string { + return composeConfig( + testAccBackupSelectionConfigBase(rName), + fmt.Sprintf(` resource "aws_backup_selection" "test" { - plan_id = "${aws_backup_plan.test.id}" + plan_id = aws_backup_plan.test.id - name = "tf_acc_test_backup_selection_%d" + name = %[1]q iam_role_arn = "arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:role/service-role/AWSBackupDefaultServiceRole" selection_tag { @@ -345,5 +388,5 @@ resource "aws_backup_selection" "test" { "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:volume/" ] } -`, rInt) +`, rName)) } diff --git a/aws/resource_aws_backup_vault.go b/aws/resource_aws_backup_vault.go index 2dd312d8e72..1f4a4fa31f2 100644 --- a/aws/resource_aws_backup_vault.go +++ b/aws/resource_aws_backup_vault.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/backup" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_backup_vault_test.go b/aws/resource_aws_backup_vault_test.go index 5ce6282c93f..011cf0b9f58 100644 --- a/aws/resource_aws_backup_vault_test.go +++ b/aws/resource_aws_backup_vault_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/backup" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAwsBackupVault_basic(t *testing.T) { @@ -210,7 +210,7 @@ resource "aws_kms_key" "test" { resource "aws_backup_vault" "test" { name = "tf_acc_test_backup_vault_%d" - kms_key_arn = "${aws_kms_key.test.arn}" + kms_key_arn = aws_kms_key.test.arn } `, randInt) } diff --git a/aws/resource_aws_batch_compute_environment.go b/aws/resource_aws_batch_compute_environment.go index b605d3dc014..f6eea4eb297 100644 --- a/aws/resource_aws_batch_compute_environment.go +++ b/aws/resource_aws_batch_compute_environment.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/batch" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -66,6 +66,7 @@ func resourceAwsBatchComputeEnvironment() *schema.Resource { "desired_vcpus": { Type: schema.TypeInt, Optional: true, + Computed: true, }, "ec2_key_pair": { Type: schema.TypeString, @@ -173,11 +174,6 @@ func resourceAwsBatchComputeEnvironment() *schema.Resource { Type: schema.TypeString, Computed: true, }, - "ecc_cluster_arn": { - Type: schema.TypeString, - Computed: true, - Removed: "Use `ecs_cluster_arn` attribute instead", - }, "ecs_cluster_arn": { Type: schema.TypeString, Computed: true, @@ -264,7 +260,7 @@ func resourceAwsBatchComputeEnvironmentCreate(d *schema.ResourceData, meta inter if v, ok := computeResource["bid_percentage"]; ok { input.ComputeResources.BidPercentage = aws.Int64(int64(v.(int))) } - if v, ok := computeResource["desired_vcpus"]; ok { + if v, ok := computeResource["desired_vcpus"]; ok && v.(int) > 0 { input.ComputeResources.DesiredvCpus = aws.Int64(int64(v.(int))) } if v, ok := computeResource["ec2_key_pair"]; ok { @@ -331,13 +327,17 @@ func resourceAwsBatchComputeEnvironmentRead(d *schema.ResourceData, meta interfa log.Printf("[DEBUG] Read compute environment %s.\n", input) result, err := conn.DescribeComputeEnvironments(input) + if err != nil { - return err + return fmt.Errorf("error reading Batch Compute Environment (%s): %w", d.Id(), err) } if len(result.ComputeEnvironments) == 0 { - return fmt.Errorf("One compute environment is expected, but AWS return no compute environment") + log.Printf("[WARN] Batch Compute Environment (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } + computeEnvironment := result.ComputeEnvironments[0] d.Set("service_role", computeEnvironment.ServiceRole) @@ -432,7 +432,10 @@ func resourceAwsBatchComputeEnvironmentUpdate(d *schema.ResourceData, meta inter } computeResource := computeResources[0].(map[string]interface{}) - input.ComputeResources.DesiredvCpus = aws.Int64(int64(computeResource["desired_vcpus"].(int))) + if d.HasChange("compute_resources.0.desired_vcpus") { + input.ComputeResources.DesiredvCpus = aws.Int64(int64(computeResource["desired_vcpus"].(int))) + } + input.ComputeResources.MaxvCpus = aws.Int64(int64(computeResource["max_vcpus"].(int))) input.ComputeResources.MinvCpus = aws.Int64(int64(computeResource["min_vcpus"].(int))) } @@ -440,7 +443,19 @@ func resourceAwsBatchComputeEnvironmentUpdate(d *schema.ResourceData, meta inter log.Printf("[DEBUG] Update compute environment %s.\n", input) if _, err := conn.UpdateComputeEnvironment(input); err != nil { - return err + return fmt.Errorf("error updating Batch Compute Environment (%s): %w", d.Id(), err) + } + + stateConf := &resource.StateChangeConf{ + Pending: []string{batch.CEStatusUpdating}, + Target: []string{batch.CEStatusValid}, + Refresh: resourceAwsBatchComputeEnvironmentStatusRefreshFunc(computeEnvironmentName, conn), + Timeout: d.Timeout(schema.TimeoutUpdate), + MinTimeout: 5 * time.Second, + } + + if _, err := stateConf.WaitForState(); err != nil { + return fmt.Errorf("error waiting for Batch Compute Environment (%s) update: %w", d.Id(), err) } return resourceAwsBatchComputeEnvironmentRead(d, meta) diff --git a/aws/resource_aws_batch_compute_environment_test.go b/aws/resource_aws_batch_compute_environment_test.go index 913c0da0cce..4b51fe4d80c 100644 --- a/aws/resource_aws_batch_compute_environment_test.go +++ b/aws/resource_aws_batch_compute_environment_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/batch" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -63,6 +63,27 @@ func testSweepBatchComputeEnvironments(region string) error { return nil } +func TestAccAWSBatchComputeEnvironment_disappears(t *testing.T) { + rInt := acctest.RandInt() + resourceName := "aws_batch_compute_environment.ec2" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSBatch(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSBatchComputeEnvironmentConfigEC2(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsBatchComputeEnvironmentExists(), + testAccCheckResourceDisappears(testAccProvider, resourceAwsBatchComputeEnvironment(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func TestAccAWSBatchComputeEnvironment_createEc2(t *testing.T) { rInt := acctest.RandInt() @@ -163,7 +184,7 @@ func TestAccAWSBatchComputeEnvironment_createUnmanaged(t *testing.T) { }) } -func TestAccAWSBatchComputeEnvironment_updateMaxvCpus(t *testing.T) { +func TestAccAWSBatchComputeEnvironment_ComputeResources_DesiredVcpus_Computed(t *testing.T) { rInt := acctest.RandInt() resourceName := "aws_batch_compute_environment.ec2" @@ -173,17 +194,99 @@ func TestAccAWSBatchComputeEnvironment_updateMaxvCpus(t *testing.T) { CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSBatchComputeEnvironmentConfigEC2(rInt), + Config: testAccAWSBatchComputeEnvironmentConfigComputeResourcesMaxVcpusMinVcpus(rInt, 8, 4), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsBatchComputeEnvironmentExists(), + ), + }, + { + Config: testAccAWSBatchComputeEnvironmentConfigComputeResourcesMaxVcpusMinVcpus(rInt, 4, 2), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsBatchComputeEnvironmentExists(), + ), + }, + { + Config: testAccAWSBatchComputeEnvironmentConfigComputeResourcesMaxVcpusMinVcpus(rInt, 8, 8), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsBatchComputeEnvironmentExists(), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSBatchComputeEnvironment_ComputeResources_MinVcpus(t *testing.T) { + rInt := acctest.RandInt() + resourceName := "aws_batch_compute_environment.ec2" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSBatch(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSBatchComputeEnvironmentConfigComputeResourcesMaxVcpusMinVcpus(rInt, 4, 0), Check: resource.ComposeTestCheckFunc( testAccCheckAwsBatchComputeEnvironmentExists(), - resource.TestCheckResourceAttr(resourceName, "compute_resources.0.max_vcpus", "16"), + resource.TestCheckResourceAttr(resourceName, "compute_resources.0.min_vcpus", "0"), ), }, { - Config: testAccAWSBatchComputeEnvironmentConfigEC2UpdateMaxvCpus(rInt), + Config: testAccAWSBatchComputeEnvironmentConfigComputeResourcesMaxVcpusMinVcpus(rInt, 4, 4), Check: resource.ComposeTestCheckFunc( testAccCheckAwsBatchComputeEnvironmentExists(), - resource.TestCheckResourceAttr(resourceName, "compute_resources.0.max_vcpus", "32"), + resource.TestCheckResourceAttr(resourceName, "compute_resources.0.min_vcpus", "4"), + ), + }, + { + Config: testAccAWSBatchComputeEnvironmentConfigComputeResourcesMaxVcpusMinVcpus(rInt, 4, 2), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsBatchComputeEnvironmentExists(), + resource.TestCheckResourceAttr(resourceName, "compute_resources.0.min_vcpus", "2"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSBatchComputeEnvironment_ComputeResources_MaxVcpus(t *testing.T) { + rInt := acctest.RandInt() + resourceName := "aws_batch_compute_environment.ec2" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSBatch(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckBatchComputeEnvironmentDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSBatchComputeEnvironmentConfigComputeResourcesMaxVcpusMinVcpus(rInt, 4, 0), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsBatchComputeEnvironmentExists(), + resource.TestCheckResourceAttr(resourceName, "compute_resources.0.max_vcpus", "4"), + ), + }, + { + Config: testAccAWSBatchComputeEnvironmentConfigComputeResourcesMaxVcpusMinVcpus(rInt, 8, 0), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsBatchComputeEnvironmentExists(), + resource.TestCheckResourceAttr(resourceName, "compute_resources.0.max_vcpus", "8"), + ), + }, + { + Config: testAccAWSBatchComputeEnvironmentConfigComputeResourcesMaxVcpusMinVcpus(rInt, 2, 0), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsBatchComputeEnvironmentExists(), + resource.TestCheckResourceAttr(resourceName, "compute_resources.0.max_vcpus", "2"), ), }, { @@ -498,7 +601,8 @@ func testAccPreCheckAWSBatch(t *testing.T) { func testAccAWSBatchComputeEnvironmentConfigBase(rInt int) string { return fmt.Sprintf(` -data "aws_partition" "current" {} +data "aws_partition" "current" { +} ########## ecs_instance_role ########## @@ -519,16 +623,17 @@ resource "aws_iam_role" "ecs_instance_role" { ] } EOF + } resource "aws_iam_role_policy_attachment" "ecs_instance_role" { - role = "${aws_iam_role.ecs_instance_role.name}" + role = aws_iam_role.ecs_instance_role.name policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role" } resource "aws_iam_instance_profile" "ecs_instance_role" { name = "tf_acc_test_batch_ip_%d" - role = "${aws_iam_role.ecs_instance_role.name}" + role = aws_iam_role.ecs_instance_role.name } ########## aws_batch_service_role ########## @@ -550,10 +655,11 @@ resource "aws_iam_role" "aws_batch_service_role" { ] } EOF + } resource "aws_iam_role_policy_attachment" "aws_batch_service_role" { - role = "${aws_iam_role.aws_batch_service_role.name}" + role = aws_iam_role.aws_batch_service_role.name policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AWSBatchServiceRole" } @@ -576,17 +682,19 @@ resource "aws_iam_role" "aws_ec2_spot_fleet_role" { ] } EOF + } resource "aws_iam_role_policy_attachment" "aws_ec2_spot_fleet_role" { - role = "${aws_iam_role.aws_ec2_spot_fleet_role.name}" + role = aws_iam_role.aws_ec2_spot_fleet_role.name policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AmazonEC2SpotFleetTaggingRole" } ########## security group ########## resource "aws_security_group" "test_acc" { - name = "tf_acc_test_batch_sg_%d" + name = "tf_acc_test_batch_sg_%d" + vpc_id = aws_vpc.test_acc.id } ########## subnets ########## @@ -600,7 +708,7 @@ resource "aws_vpc" "test_acc" { } resource "aws_subnet" "test_acc" { - vpc_id = "${aws_vpc.test_acc.id}" + vpc_id = aws_vpc.test_acc.id cidr_block = "10.1.1.0/24" tags = { @@ -614,24 +722,26 @@ func testAccAWSBatchComputeEnvironmentConfigEC2(rInt int) string { return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "ec2" { compute_environment_name = "tf_acc_test_%d" + compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", ] max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "EC2" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt) } @@ -640,24 +750,26 @@ func testAccAWSBatchComputeEnvironmentConfigNamePrefix(rInt int) string { return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + ` resource "aws_batch_compute_environment" "ec2" { compute_environment_name_prefix = "tf_acc_test" + compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", ] max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "EC2" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } ` } @@ -666,27 +778,29 @@ func testAccAWSBatchComputeEnvironmentConfigEC2WithTags(rInt int) string { return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "ec2" { compute_environment_name = "tf_acc_test_%d" + compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", ] max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "EC2" tags = { Key1 = "Value1" } } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt) } @@ -695,26 +809,28 @@ func testAccAWSBatchComputeEnvironmentConfigSpot(rInt int) string { return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "spot" { compute_environment_name = "tf_acc_test_%d" + compute_resources { bid_percentage = 100 - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", ] max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] - spot_iam_fleet_role = "${aws_iam_role.aws_ec2_spot_fleet_role.arn}" + spot_iam_fleet_role = aws_iam_role.aws_ec2_spot_fleet_role.arn subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "SPOT" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt) } @@ -723,45 +839,46 @@ func testAccAWSBatchComputeEnvironmentConfigUnmanaged(rInt int) string { return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "unmanaged" { compute_environment_name = "tf_acc_test_%d" - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "UNMANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + service_role = aws_iam_role.aws_batch_service_role.arn + type = "UNMANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt) } -func testAccAWSBatchComputeEnvironmentConfigEC2UpdateMaxvCpus(rInt int) string { +func testAccAWSBatchComputeEnvironmentConfigComputeResourcesMaxVcpusMinVcpus(rInt int, maxVcpus int, minVcpus int) string { return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "ec2" { - compute_environment_name = "tf_acc_test_%d" + compute_environment_name = "tf_acc_test_%[1]d" + compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" - instance_type = [ - "c4.large", - ] - max_vcpus = 32 - min_vcpus = 0 + instance_role = aws_iam_instance_profile.ecs_instance_role.arn + instance_type = ["optimal"] + max_vcpus = %[2]d + min_vcpus = %[3]d security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] - subnets = [ - "${aws_subnet.test_acc.id}" + subnets = [ + aws_subnet.test_acc.id ] - type = "EC2" + type = "EC2" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } -`, rInt) +`, rInt, maxVcpus, minVcpus) } func testAccAWSBatchComputeEnvironmentConfigEC2UpdateInstanceType(rInt int) string { return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "ec2" { compute_environment_name = "tf_acc_test_%d" + compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", "c4.xlarge", @@ -769,16 +886,17 @@ resource "aws_batch_compute_environment" "ec2" { max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "EC2" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt) } @@ -787,25 +905,27 @@ func testAccAWSBatchComputeEnvironmentConfigEC2UpdateState(rInt int, state strin return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "ec2" { compute_environment_name = "tf_acc_test_%d" + compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", ] max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "EC2" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - state = "%s" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + state = "%s" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt, state) } @@ -814,24 +934,26 @@ func testAccAWSBatchComputeEnvironmentConfigEC2UpdateComputeEnvironmentName(rInt return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "ec2" { compute_environment_name = "tf_acc_test_updated_%d" + compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", ] max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "EC2" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt) } @@ -840,9 +962,9 @@ func testAccAWSBatchComputeEnvironmentConfigEC2WithoutComputeResources(rInt int) return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "ec2" { compute_environment_name = "tf_acc_test_%d" - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt) } @@ -851,24 +973,26 @@ func testAccAWSBatchComputeEnvironmentConfigUnmanagedWithComputeResources(rInt i return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "unmanaged" { compute_environment_name = "tf_acc_test_%d" + compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", ] max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "EC2" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "UNMANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "UNMANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt) } @@ -877,26 +1001,28 @@ func testAccAWSBatchComputeEnvironmentConfigSpotWithAllocationStrategy(rInt int) return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "ec2" { compute_environment_name = "tf_acc_test_%d" + compute_resources { - allocation_strategy = "BEST_FIT" - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + allocation_strategy = "BEST_FIT" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", ] max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" - ] - spot_iam_fleet_role = "${aws_iam_role.aws_ec2_spot_fleet_role.arn}" + aws_security_group.test_acc.id + ] + spot_iam_fleet_role = aws_iam_role.aws_ec2_spot_fleet_role.arn subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "SPOT" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt) } @@ -905,24 +1031,26 @@ func testAccAWSBatchComputeEnvironmentConfigSpotWithoutBidPercentage(rInt int) s return testAccAWSBatchComputeEnvironmentConfigBase(rInt) + fmt.Sprintf(` resource "aws_batch_compute_environment" "ec2" { compute_environment_name = "tf_acc_test_%d" + compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", ] max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "SPOT" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt) } @@ -935,28 +1063,32 @@ resource "aws_launch_template" "foo" { resource "aws_batch_compute_environment" "ec2" { compute_environment_name = "tf_acc_test_%d" + compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", ] + launch_template { - launch_template_name = "${aws_launch_template.foo.name}" - } + launch_template_name = aws_launch_template.foo.name + } + max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] - spot_iam_fleet_role = "${aws_iam_role.aws_ec2_spot_fleet_role.arn}" + spot_iam_fleet_role = aws_iam_role.aws_ec2_spot_fleet_role.arn subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "SPOT" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt, rInt) } @@ -969,29 +1101,33 @@ resource "aws_launch_template" "foo" { resource "aws_batch_compute_environment" "ec2" { compute_environment_name = "tf_acc_test_%d" + compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", ] + launch_template { - launch_template_name = "${aws_launch_template.foo.name}" - version = "%s" - } + launch_template_name = aws_launch_template.foo.name + version = "%s" + } + max_vcpus = 16 min_vcpus = 0 security_group_ids = [ - "${aws_security_group.test_acc.id}" + aws_security_group.test_acc.id ] - spot_iam_fleet_role = "${aws_iam_role.aws_ec2_spot_fleet_role.arn}" + spot_iam_fleet_role = aws_iam_role.aws_ec2_spot_fleet_role.arn subnets = [ - "${aws_subnet.test_acc.id}" + aws_subnet.test_acc.id ] type = "SPOT" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" - type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + + service_role = aws_iam_role.aws_batch_service_role.arn + type = "MANAGED" + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } `, rInt, rInt, version) } diff --git a/aws/resource_aws_batch_job_definition.go b/aws/resource_aws_batch_job_definition.go index 715c7d2bbdc..158c6592d0d 100644 --- a/aws/resource_aws_batch_job_definition.go +++ b/aws/resource_aws_batch_job_definition.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/private/protocol/json/jsonutil" "github.com/aws/aws-sdk-go/service/batch" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/batch/equivalency" ) diff --git a/aws/resource_aws_batch_job_definition_test.go b/aws/resource_aws_batch_job_definition_test.go index c63f1ee04e5..972de59dc7c 100644 --- a/aws/resource_aws_batch_job_definition_test.go +++ b/aws/resource_aws_batch_job_definition_test.go @@ -2,16 +2,72 @@ package aws import ( "fmt" + "log" "reflect" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/batch" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) +func init() { + resource.AddTestSweepers("aws_batch_job_definition", &resource.Sweeper{ + Name: "aws_batch_job_definition", + F: testSweepBatchJobDefinitions, + Dependencies: []string{ + "aws_batch_job_queue", + }, + }) +} + +func testSweepBatchJobDefinitions(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).batchconn + input := &batch.DescribeJobDefinitionsInput{ + Status: aws.String("ACTIVE"), + } + var sweeperErrs *multierror.Error + + err = conn.DescribeJobDefinitionsPages(input, func(page *batch.DescribeJobDefinitionsOutput, isLast bool) bool { + if page == nil { + return !isLast + } + + for _, jobDefinition := range page.JobDefinitions { + arn := aws.StringValue(jobDefinition.JobDefinitionArn) + + log.Printf("[INFO] Deleting Batch Job Definition: %s", arn) + _, err := conn.DeregisterJobDefinition(&batch.DeregisterJobDefinitionInput{ + JobDefinition: aws.String(arn), + }) + if err != nil { + sweeperErr := fmt.Errorf("error deleting Batch Job Definition (%s): %w", arn, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + } + + return !isLast + }) + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping Batch Job Definitions sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors + } + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving Batch Job Definitions: %w", err)) + } + + return sweeperErrs.ErrorOrNil() +} + func TestAccAWSBatchJobDefinition_basic(t *testing.T) { var jd batch.JobDefinition rName := acctest.RandomWithPrefix("tf-acc-test") @@ -211,19 +267,19 @@ func testAccCheckBatchJobDefinitionDestroy(s *terraform.State) error { func testAccBatchJobDefinitionConfigContainerPropertiesAdvanced(rName string) string { return fmt.Sprintf(` resource "aws_batch_job_definition" "test" { - name = %[1]q - type = "container" - parameters = { - param1 = "val1" - param2 = "val2" - } - retry_strategy { - attempts = 1 - } - timeout { - attempt_duration_seconds = 60 - } - container_properties = < 0 { - auth := v.(*schema.Set).List()[0].(map[string]interface{}) - + // Probe data for auth details (max of 1 auth per ProjectSource object) + if v, ok := data["auth"]; ok && len(v.([]interface{})) > 0 { + if auths := v.([]interface{}); auths[0] != nil { + auth := auths[0].(map[string]interface{}) projectSource.Auth = &codebuild.SourceAuth{ Type: aws.String(auth["type"].(string)), Resource: aws.String(auth["resource"].(string)), @@ -1047,8 +1046,8 @@ func expandProjectSourceData(data map[string]interface{}) codebuild.ProjectSourc } } - // Only valid for CODECOMMIT source types. - if sourceType == codebuild.SourceTypeCodecommit { + // Only valid for CODECOMMIT, GITHUB, GITHUB_ENTERPRISE source types. + if sourceType == codebuild.SourceTypeCodecommit || sourceType == codebuild.SourceTypeGithub || sourceType == codebuild.SourceTypeGithubEnterprise { if v, ok := data["git_submodules_config"]; ok && len(v.([]interface{})) > 0 { config := v.([]interface{})[0].(map[string]interface{}) @@ -1092,7 +1091,7 @@ func resourceAwsCodeBuildProjectRead(d *schema.ResourceData, meta interface{}) e return fmt.Errorf("error setting artifacts: %s", err) } - if err := d.Set("environment", schema.NewSet(resourceAwsCodeBuildProjectEnvironmentHash, flattenAwsCodeBuildProjectEnvironment(project.Environment))); err != nil { + if err := d.Set("environment", flattenAwsCodeBuildProjectEnvironment(project.Environment)); err != nil { return fmt.Errorf("error setting environment: %s", err) } @@ -1329,38 +1328,38 @@ func flattenAwsCodeBuildProjectArtifacts(artifacts *codebuild.ProjectArtifacts) func flattenAwsCodeBuildProjectArtifactsData(artifacts codebuild.ProjectArtifacts) map[string]interface{} { values := map[string]interface{}{} - values["type"] = *artifacts.Type + values["type"] = aws.StringValue(artifacts.Type) if artifacts.ArtifactIdentifier != nil { - values["artifact_identifier"] = *artifacts.ArtifactIdentifier + values["artifact_identifier"] = aws.StringValue(artifacts.ArtifactIdentifier) } if artifacts.EncryptionDisabled != nil { - values["encryption_disabled"] = *artifacts.EncryptionDisabled + values["encryption_disabled"] = aws.BoolValue(artifacts.EncryptionDisabled) } if artifacts.OverrideArtifactName != nil { - values["override_artifact_name"] = *artifacts.OverrideArtifactName + values["override_artifact_name"] = aws.BoolValue(artifacts.OverrideArtifactName) } if artifacts.Location != nil { - values["location"] = *artifacts.Location + values["location"] = aws.StringValue(artifacts.Location) } if artifacts.Name != nil { - values["name"] = *artifacts.Name + values["name"] = aws.StringValue(artifacts.Name) } if artifacts.NamespaceType != nil { - values["namespace_type"] = *artifacts.NamespaceType + values["namespace_type"] = aws.StringValue(artifacts.NamespaceType) } if artifacts.Packaging != nil { - values["packaging"] = *artifacts.Packaging + values["packaging"] = aws.StringValue(artifacts.Packaging) } if artifacts.Path != nil { - values["path"] = *artifacts.Path + values["path"] = aws.StringValue(artifacts.Path) } return values } @@ -1382,12 +1381,12 @@ func flattenAwsCodebuildProjectCache(cache *codebuild.ProjectCache) []interface{ func flattenAwsCodeBuildProjectEnvironment(environment *codebuild.ProjectEnvironment) []interface{} { envConfig := map[string]interface{}{} - envConfig["type"] = *environment.Type - envConfig["compute_type"] = *environment.ComputeType - envConfig["image"] = *environment.Image + envConfig["type"] = aws.StringValue(environment.Type) + envConfig["compute_type"] = aws.StringValue(environment.ComputeType) + envConfig["image"] = aws.StringValue(environment.Image) envConfig["certificate"] = aws.StringValue(environment.Certificate) - envConfig["privileged_mode"] = *environment.PrivilegedMode - envConfig["image_pull_credentials_type"] = *environment.ImagePullCredentialsType + envConfig["privileged_mode"] = aws.BoolValue(environment.PrivilegedMode) + envConfig["image_pull_credentials_type"] = aws.StringValue(environment.ImagePullCredentialsType) envConfig["registry_credential"] = flattenAwsCodebuildRegistryCredential(environment.RegistryCredential) @@ -1442,7 +1441,7 @@ func flattenAwsCodeBuildProjectSourceData(source *codebuild.ProjectSource) inter m["git_submodules_config"] = flattenAwsCodebuildProjectGitSubmodulesConfig(source.GitSubmodulesConfig) if source.Auth != nil { - m["auth"] = schema.NewSet(resourceAwsCodeBuildProjectSourceAuthHash, []interface{}{sourceAuthToMap(source.Auth)}) + m["auth"] = []interface{}{sourceAuthToMap(source.Auth)} } if source.SourceIdentifier != nil { m["source_identifier"] = aws.StringValue(source.SourceIdentifier) @@ -1467,7 +1466,7 @@ func flattenAwsCodeBuildVpcConfig(vpcConfig *codebuild.VpcConfig) []interface{} if vpcConfig != nil { values := map[string]interface{}{} - values["vpc_id"] = *vpcConfig.VpcId + values["vpc_id"] = aws.StringValue(vpcConfig.VpcId) values["subnets"] = schema.NewSet(schema.HashString, flattenStringList(vpcConfig.Subnets)) values["security_group_ids"] = schema.NewSet(schema.HashString, flattenStringList(vpcConfig.SecurityGroupIds)) @@ -1515,107 +1514,16 @@ func resourceAwsCodeBuildProjectArtifactsHash(v interface{}) int { return hashcode.String(buf.String()) } -func resourceAwsCodeBuildProjectEnvironmentHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - - environmentType := m["type"].(string) - computeType := m["compute_type"].(string) - image := m["image"].(string) - privilegedMode := m["privileged_mode"].(bool) - imagePullCredentialsType := m["image_pull_credentials_type"].(string) - environmentVariables := m["environment_variable"].([]interface{}) - buf.WriteString(fmt.Sprintf("%s-", environmentType)) - buf.WriteString(fmt.Sprintf("%s-", computeType)) - buf.WriteString(fmt.Sprintf("%s-", image)) - buf.WriteString(fmt.Sprintf("%t-", privilegedMode)) - buf.WriteString(fmt.Sprintf("%s-", imagePullCredentialsType)) - if v, ok := m["certificate"]; ok && v.(string) != "" { - buf.WriteString(fmt.Sprintf("%s-", v.(string))) - } - if v, ok := m["registry_credential"]; ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - m := v.([]interface{})[0].(map[string]interface{}) - - if v, ok := m["credential"]; ok && v.(string) != "" { - buf.WriteString(fmt.Sprintf("%s-", v.(string))) - } - - if v, ok := m["credential_provider"]; ok && v.(string) != "" { - buf.WriteString(fmt.Sprintf("%s-", v.(string))) - } - } - for _, e := range environmentVariables { - if e != nil { // Old statefiles might have nil values in them - ev := e.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s:", ev["name"].(string))) - // type is sometimes not returned by the API - if v, ok := ev["type"]; ok { - buf.WriteString(fmt.Sprintf("%s:", v.(string))) - } - buf.WriteString(fmt.Sprintf("%s-", ev["value"].(string))) - } - } - - return hashcode.String(buf.String()) -} - -func resourceAwsCodeBuildProjectSourceHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - - buf.WriteString(fmt.Sprintf("%s-", m["type"].(string))) - if v, ok := m["source_identifier"]; ok { - buf.WriteString(fmt.Sprintf("%s-", strconv.Itoa(v.(int)))) - } - if v, ok := m["buildspec"]; ok { - buf.WriteString(fmt.Sprintf("%s-", v.(string))) - } - if v, ok := m["location"]; ok { - buf.WriteString(fmt.Sprintf("%s-", v.(string))) - } - if v, ok := m["git_clone_depth"]; ok { - buf.WriteString(fmt.Sprintf("%s-", strconv.Itoa(v.(int)))) - } - if v, ok := m["git_submodules_config"]; ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { - m := v.([]interface{})[0].(map[string]interface{}) - - if v, ok := m["fetch_submodules"]; ok { - buf.WriteString(fmt.Sprintf("%s-", strconv.FormatBool(v.(bool)))) - } - } - if v, ok := m["insecure_ssl"]; ok { - buf.WriteString(fmt.Sprintf("%s-", strconv.FormatBool(v.(bool)))) - } - if v, ok := m["report_build_status"]; ok { - buf.WriteString(fmt.Sprintf("%s-", strconv.FormatBool(v.(bool)))) - } - - return hashcode.String(buf.String()) -} - -func resourceAwsCodeBuildProjectSourceAuthHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - - buf.WriteString(fmt.Sprintf("%s-", m["type"].(string))) - - if m["resource"] != nil { - buf.WriteString(fmt.Sprintf("%s-", m["resource"].(string))) - } - - return hashcode.String(buf.String()) -} - func environmentVariablesToMap(environmentVariables []*codebuild.EnvironmentVariable) []interface{} { envVariables := []interface{}{} if len(environmentVariables) > 0 { for _, env := range environmentVariables { item := map[string]interface{}{} - item["name"] = *env.Name - item["value"] = *env.Value + item["name"] = aws.StringValue(env.Name) + item["value"] = aws.StringValue(env.Value) if env.Type != nil { - item["type"] = *env.Type + item["type"] = aws.StringValue(env.Type) } envVariables = append(envVariables, item) } @@ -1627,10 +1535,10 @@ func environmentVariablesToMap(environmentVariables []*codebuild.EnvironmentVari func sourceAuthToMap(sourceAuth *codebuild.SourceAuth) map[string]interface{} { auth := map[string]interface{}{} - auth["type"] = *sourceAuth.Type + auth["type"] = aws.StringValue(sourceAuth.Type) if sourceAuth.Resource != nil { - auth["resource"] = *sourceAuth.Resource + auth["resource"] = aws.StringValue(sourceAuth.Resource) } return auth diff --git a/aws/resource_aws_codebuild_project_test.go b/aws/resource_aws_codebuild_project_test.go index 7ddf463f760..1d3f6c87d32 100644 --- a/aws/resource_aws_codebuild_project_test.go +++ b/aws/resource_aws_codebuild_project_test.go @@ -6,13 +6,13 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/codebuild" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) // This is used for testing aws_codebuild_webhook as well as aws_codebuild_project. @@ -42,13 +42,14 @@ func testAccAWSCodeBuildGitHubSourceLocationFromEnv() string { func TestAccAWSCodeBuildProject_basic(t *testing.T) { var project codebuild.Project rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_codebuild_project.test" + roleResourceName := "aws_iam_role.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_basic(rName), @@ -60,26 +61,26 @@ func TestAccAWSCodeBuildProject_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "build_timeout", "60"), resource.TestCheckResourceAttr(resourceName, "queued_timeout", "480"), resource.TestCheckResourceAttr(resourceName, "cache.#", "1"), - resource.TestCheckResourceAttr(resourceName, "cache.0.type", "NO_CACHE"), + resource.TestCheckResourceAttr(resourceName, "cache.0.type", codebuild.CacheTypeNoCache), resource.TestCheckResourceAttr(resourceName, "description", ""), - resource.TestMatchResourceAttr(resourceName, "encryption_key", regexp.MustCompile(`^arn:[^:]+:kms:[^:]+:[^:]+:alias/aws/s3$`)), + testAccCheckResourceAttrRegionalARN(resourceName, "encryption_key", "kms", "alias/aws/s3"), resource.TestCheckResourceAttr(resourceName, "environment.#", "1"), - resource.TestCheckResourceAttr(resourceName, "environment.2300252877.compute_type", "BUILD_GENERAL1_SMALL"), - resource.TestCheckResourceAttr(resourceName, "environment.2300252877.environment_variable.#", "0"), - resource.TestCheckResourceAttr(resourceName, "environment.2300252877.image", "2"), - resource.TestCheckResourceAttr(resourceName, "environment.2300252877.privileged_mode", "false"), - resource.TestCheckResourceAttr(resourceName, "environment.2300252877.type", "LINUX_CONTAINER"), - resource.TestCheckResourceAttr(resourceName, "environment.2300252877.image_pull_credentials_type", "CODEBUILD"), - resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.status", "ENABLED"), - resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.status", "DISABLED"), - resource.TestMatchResourceAttr(resourceName, "service_role", regexp.MustCompile(`^arn:[^:]+:iam::[^:]+:role/tf-acc-test-[0-9]+$`)), + resource.TestCheckResourceAttr(resourceName, "environment.0.compute_type", codebuild.ComputeTypeBuildGeneral1Small), + resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.#", "0"), + resource.TestCheckResourceAttr(resourceName, "environment.0.image", "2"), + resource.TestCheckResourceAttr(resourceName, "environment.0.privileged_mode", "false"), + resource.TestCheckResourceAttr(resourceName, "environment.0.type", codebuild.EnvironmentTypeLinuxContainer), + resource.TestCheckResourceAttr(resourceName, "environment.0.image_pull_credentials_type", codebuild.ImagePullCredentialsTypeCodebuild), + resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.status", codebuild.LogsConfigStatusTypeEnabled), + resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.status", codebuild.LogsConfigStatusTypeDisabled), + resource.TestCheckResourceAttrPair(resourceName, "service_role", roleResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "source.#", "1"), - resource.TestCheckResourceAttr(resourceName, "source.1441597390.auth.#", "0"), - resource.TestCheckResourceAttr(resourceName, "source.1441597390.git_clone_depth", "0"), - resource.TestCheckResourceAttr(resourceName, "source.1441597390.insecure_ssl", "false"), - resource.TestCheckResourceAttr(resourceName, "source.1441597390.location", "https://github.com/hashibot-test/aws-test.git"), - resource.TestCheckResourceAttr(resourceName, "source.1441597390.report_build_status", "false"), - resource.TestCheckResourceAttr(resourceName, "source.1441597390.type", "GITHUB"), + resource.TestCheckResourceAttr(resourceName, "source.0.auth.#", "0"), + resource.TestCheckResourceAttr(resourceName, "source.0.git_clone_depth", "0"), + resource.TestCheckResourceAttr(resourceName, "source.0.insecure_ssl", "false"), + resource.TestCheckResourceAttr(resourceName, "source.0.location", "https://github.com/hashibot-test/aws-test.git"), + resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "false"), + resource.TestCheckResourceAttr(resourceName, "source.0.type", "GITHUB"), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "0"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), @@ -201,11 +202,11 @@ func TestAccAWSCodeBuildProject_Cache(t *testing.T) { ExpectError: regexp.MustCompile(`cache location is required when cache type is "S3"`), }, { - Config: testAccAWSCodeBuildProjectConfig_Cache(rName, "", "NO_CACHE"), + Config: testAccAWSCodeBuildProjectConfig_Cache(rName, "", codebuild.CacheTypeNoCache), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "cache.#", "1"), - resource.TestCheckResourceAttr(resourceName, "cache.0.type", "NO_CACHE"), + resource.TestCheckResourceAttr(resourceName, "cache.0.type", codebuild.CacheTypeNoCache), ), }, { @@ -218,7 +219,7 @@ func TestAccAWSCodeBuildProject_Cache(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "cache.#", "1"), - resource.TestCheckResourceAttr(resourceName, "cache.0.type", "NO_CACHE"), + resource.TestCheckResourceAttr(resourceName, "cache.0.type", codebuild.CacheTypeNoCache), ), }, { @@ -244,7 +245,7 @@ func TestAccAWSCodeBuildProject_Cache(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "cache.#", "1"), - resource.TestCheckResourceAttr(resourceName, "cache.0.type", "NO_CACHE"), + resource.TestCheckResourceAttr(resourceName, "cache.0.type", codebuild.CacheTypeNoCache), ), }, { @@ -346,16 +347,14 @@ func TestAccAWSCodeBuildProject_Environment_EnvironmentVariable(t *testing.T) { resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_One(rName), + Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_One(rName, "KEY1", "VALUE1"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project1), - resource.TestCheckResourceAttr(resourceName, "environment.1380979031.environment_variable.#", "1"), ), }, { @@ -364,10 +363,9 @@ func TestAccAWSCodeBuildProject_Environment_EnvironmentVariable(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_Two(rName), + Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_Two(rName, "KEY1", "VALUE1UPDATED", "KEY2", "VALUE2"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project2), - resource.TestCheckResourceAttr(resourceName, "environment.4178155002.environment_variable.#", "2"), ), }, { @@ -379,7 +377,7 @@ func TestAccAWSCodeBuildProject_Environment_EnvironmentVariable(t *testing.T) { Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_Zero(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project3), - resource.TestCheckResourceAttr(resourceName, "environment.2300252877.environment_variable.#", "0"), + resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.#", "0"), ), }, { @@ -397,17 +395,16 @@ func TestAccAWSCodeBuildProject_Environment_EnvironmentVariable_Type(t *testing. resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_Type(rName, "PLAINTEXT"), + Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_Type(rName, codebuild.EnvironmentVariableTypePlaintext), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "environment.4178155002.environment_variable.0.type", "PLAINTEXT"), - resource.TestCheckResourceAttr(resourceName, "environment.4178155002.environment_variable.1.type", "PLAINTEXT"), + resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.0.type", codebuild.EnvironmentVariableTypePlaintext), + resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.1.type", codebuild.EnvironmentVariableTypePlaintext), ), }, { @@ -416,17 +413,72 @@ func TestAccAWSCodeBuildProject_Environment_EnvironmentVariable_Type(t *testing. ImportStateVerify: true, }, { - Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_Type(rName, "PARAMETER_STORE"), + Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_Type(rName, codebuild.EnvironmentVariableTypeParameterStore), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project), + resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.0.type", codebuild.EnvironmentVariableTypePlaintext), + resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.1.type", codebuild.EnvironmentVariableTypeParameterStore), + ), + }, + { + Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_Type(rName, codebuild.EnvironmentVariableTypeSecretsManager), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "environment.1701234421.environment_variable.0.type", "PLAINTEXT"), - resource.TestCheckResourceAttr(resourceName, "environment.1701234421.environment_variable.1.type", "PARAMETER_STORE"), + resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.0.type", codebuild.EnvironmentVariableTypePlaintext), + resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.1.type", codebuild.EnvironmentVariableTypeSecretsManager), ), }, }, }) } +func TestAccAWSCodeBuildProject_Environment_EnvironmentVariable_Value(t *testing.T) { + var project1, project2, project3 codebuild.Project + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_codebuild_project.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_One(rName, "KEY1", ""), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project1), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_One(rName, "KEY1", "VALUE1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project2), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSCodeBuildProjectConfig_Environment_EnvironmentVariable_One(rName, "KEY1", ""), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project3), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func TestAccAWSCodeBuildProject_Environment_Certificate(t *testing.T) { var project codebuild.Project rName := acctest.RandomWithPrefix("tf-acc-test") @@ -466,28 +518,28 @@ func TestAccAWSCodeBuildProject_LogsConfig_CloudWatchLogs(t *testing.T) { CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSCodeBuildProjectConfig_LogsConfig_CloudWatchLogs(rName, "ENABLED", "group-name", ""), + Config: testAccAWSCodeBuildProjectConfig_LogsConfig_CloudWatchLogs(rName, codebuild.LogsConfigStatusTypeEnabled, "group-name", ""), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.status", "ENABLED"), + resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.status", codebuild.LogsConfigStatusTypeEnabled), resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.group_name", "group-name"), resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.stream_name", ""), ), }, { - Config: testAccAWSCodeBuildProjectConfig_LogsConfig_CloudWatchLogs(rName, "ENABLED", "group-name", "stream-name"), + Config: testAccAWSCodeBuildProjectConfig_LogsConfig_CloudWatchLogs(rName, codebuild.LogsConfigStatusTypeEnabled, "group-name", "stream-name"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.status", "ENABLED"), + resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.status", codebuild.LogsConfigStatusTypeEnabled), resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.group_name", "group-name"), resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.stream_name", "stream-name"), ), }, { - Config: testAccAWSCodeBuildProjectConfig_LogsConfig_CloudWatchLogs(rName, "DISABLED", "", ""), + Config: testAccAWSCodeBuildProjectConfig_LogsConfig_CloudWatchLogs(rName, codebuild.LogsConfigStatusTypeDisabled, "", ""), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.status", "DISABLED"), + resource.TestCheckResourceAttr(resourceName, "logs_config.0.cloudwatch_logs.0.status", codebuild.LogsConfigStatusTypeDisabled), ), }, { @@ -511,28 +563,28 @@ func TestAccAWSCodeBuildProject_LogsConfig_S3Logs(t *testing.T) { CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSCodeBuildProjectConfig_LogsConfig_S3Logs(rName, bName, "ENABLED", bName+"/build-log", false), + Config: testAccAWSCodeBuildProjectConfig_LogsConfig_S3Logs(rName, bName, codebuild.LogsConfigStatusTypeEnabled, bName+"/build-log", false), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.status", "ENABLED"), + resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.status", codebuild.LogsConfigStatusTypeEnabled), resource.TestMatchResourceAttr(resourceName, "logs_config.0.s3_logs.0.location", regexp.MustCompile(`tf-acc-test-bucket-[0-9]+/build-log$`)), resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.encryption_disabled", "false"), ), }, { - Config: testAccAWSCodeBuildProjectConfig_LogsConfig_S3Logs(rName, bName, "ENABLED", bName+"/build-log", true), + Config: testAccAWSCodeBuildProjectConfig_LogsConfig_S3Logs(rName, bName, codebuild.LogsConfigStatusTypeEnabled, bName+"/build-log", true), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.status", "ENABLED"), + resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.status", codebuild.LogsConfigStatusTypeEnabled), resource.TestMatchResourceAttr(resourceName, "logs_config.0.s3_logs.0.location", regexp.MustCompile(`tf-acc-test-bucket-[0-9]+/build-log$`)), resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.encryption_disabled", "true"), ), }, { - Config: testAccAWSCodeBuildProjectConfig_LogsConfig_S3Logs(rName, bName, "DISABLED", "", false), + Config: testAccAWSCodeBuildProjectConfig_LogsConfig_S3Logs(rName, bName, codebuild.LogsConfigStatusTypeDisabled, "", false), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.status", "DISABLED"), + resource.TestCheckResourceAttr(resourceName, "logs_config.0.s3_logs.0.status", codebuild.LogsConfigStatusTypeDisabled), ), }, { @@ -550,10 +602,9 @@ func TestAccAWSCodeBuildProject_Source_Auth(t *testing.T) { resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_Source_Auth(rName, "FAKERESOURCE1", "INVALID"), @@ -563,9 +614,9 @@ func TestAccAWSCodeBuildProject_Source_Auth(t *testing.T) { Config: testAccAWSCodeBuildProjectConfig_Source_Auth(rName, "FAKERESOURCE1", "OAUTH"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.3680505372.auth.#", "1"), - resource.TestCheckResourceAttr(resourceName, "source.3680505372.auth.2706882902.resource", "FAKERESOURCE1"), - resource.TestCheckResourceAttr(resourceName, "source.3680505372.auth.2706882902.type", "OAUTH"), + resource.TestCheckResourceAttr(resourceName, "source.0.auth.#", "1"), + resource.TestCheckResourceAttr(resourceName, "source.0.auth.0.resource", "FAKERESOURCE1"), + resource.TestCheckResourceAttr(resourceName, "source.0.auth.0.type", "OAUTH"), ), }, { @@ -583,16 +634,15 @@ func TestAccAWSCodeBuildProject_Source_GitCloneDepth(t *testing.T) { resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_Source_GitCloneDepth(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.1181740906.git_clone_depth", "1"), + resource.TestCheckResourceAttr(resourceName, "source.0.git_clone_depth", "1"), ), }, { @@ -604,30 +654,134 @@ func TestAccAWSCodeBuildProject_Source_GitCloneDepth(t *testing.T) { Config: testAccAWSCodeBuildProjectConfig_Source_GitCloneDepth(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.974047921.git_clone_depth", "2"), + resource.TestCheckResourceAttr(resourceName, "source.0.git_clone_depth", "2"), + ), + }, + }, + }) +} + +func TestAccAWSCodeBuildProject_Source_GitSubmodulesConfig_CodeCommit(t *testing.T) { + var project codebuild.Project + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_codebuild_project.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCodeBuildProjectConfig_Source_GitSubmodulesConfig_CodeCommit(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project), + resource.TestCheckResourceAttr(resourceName, "source.0.git_submodules_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "source.0.git_submodules_config.0.fetch_submodules", "true"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSCodeBuildProjectConfig_Source_GitSubmodulesConfig_CodeCommit(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project), + resource.TestCheckResourceAttr(resourceName, "source.0.git_submodules_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "source.0.git_submodules_config.0.fetch_submodules", "false"), + ), + }, + }, + }) +} + +func TestAccAWSCodeBuildProject_Source_GitSubmodulesConfig_GitHub(t *testing.T) { + var project codebuild.Project + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_codebuild_project.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCodeBuildProjectConfig_Source_GitSubmodulesConfig_GitHub(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSCodeBuildProjectConfig_Source_GitSubmodulesConfig_GitHub(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project), + ), + }, + }, + }) +} + +func TestAccAWSCodeBuildProject_Source_GitSubmodulesConfig_GitHubEnterprise(t *testing.T) { + var project codebuild.Project + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_codebuild_project.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCodeBuildProjectConfig_Source_GitSubmodulesConfig_GitHubEnterprise(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSCodeBuildProjectConfig_Source_GitSubmodulesConfig_GitHubEnterprise(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project), ), }, }, }) } -func TestAccAWSCodeBuildProject_Source_GitSubmodulesConfig(t *testing.T) { +func TestAccAWSCodeBuildProject_SecondarySources_GitSubmodulesConfig_CodeCommit(t *testing.T) { var project codebuild.Project rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSCodeBuildProjectConfig_Source_GitSubmodulesConfig(rName, true), + Config: testAccAWSCodeBuildProjectConfig_SecondarySources_GitSubmodulesConfig_CodeCommit(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.3389748318.git_submodules_config.#", "1"), - resource.TestCheckResourceAttr(resourceName, "source.3389748318.git_submodules_config.0.fetch_submodules", "true"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_sources.*", map[string]string{ + "source_identifier": "secondarySource1", + "git_submodules_config.#": "1", + "git_submodules_config.0.fetch_submodules": "true", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_sources.*", map[string]string{ + "source_identifier": "secondarySource2", + "git_submodules_config.#": "1", + "git_submodules_config.0.fetch_submodules": "true", + }), ), }, { @@ -636,36 +790,39 @@ func TestAccAWSCodeBuildProject_Source_GitSubmodulesConfig(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSCodeBuildProjectConfig_Source_GitSubmodulesConfig(rName, false), + Config: testAccAWSCodeBuildProjectConfig_SecondarySources_GitSubmodulesConfig_CodeCommit(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.3338377709.git_submodules_config.#", "1"), - resource.TestCheckResourceAttr(resourceName, "source.3338377709.git_submodules_config.0.fetch_submodules", "false"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_sources.*", map[string]string{ + "source_identifier": "secondarySource1", + "git_submodules_config.#": "1", + "git_submodules_config.0.fetch_submodules": "false", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_sources.*", map[string]string{ + "source_identifier": "secondarySource2", + "git_submodules_config.#": "1", + "git_submodules_config.0.fetch_submodules": "false", + }), ), }, }, }) } -func TestAccAWSCodeBuildProject_SecondarySources_GitSubmodulesConfig(t *testing.T) { +func TestAccAWSCodeBuildProject_SecondarySources_GitSubmodulesConfig_GitHub(t *testing.T) { var project codebuild.Project rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSCodeBuildProjectConfig_SecondarySources_GitSubmodulesConfig(rName, true), + Config: testAccAWSCodeBuildProjectConfig_SecondarySources_GitSubmodulesConfig_GitHub(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "secondary_sources.2336845252.git_submodules_config.#", "1"), - resource.TestCheckResourceAttr(resourceName, "secondary_sources.2336845252.git_submodules_config.0.fetch_submodules", "true"), - resource.TestCheckResourceAttr(resourceName, "secondary_sources.2080741754.git_submodules_config.#", "1"), - resource.TestCheckResourceAttr(resourceName, "secondary_sources.2080741754.git_submodules_config.0.fetch_submodules", "true"), ), }, { @@ -674,13 +831,40 @@ func TestAccAWSCodeBuildProject_SecondarySources_GitSubmodulesConfig(t *testing. ImportStateVerify: true, }, { - Config: testAccAWSCodeBuildProjectConfig_SecondarySources_GitSubmodulesConfig(rName, false), + Config: testAccAWSCodeBuildProjectConfig_SecondarySources_GitSubmodulesConfig_GitHub(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project), + ), + }, + }, + }) +} + +func TestAccAWSCodeBuildProject_SecondarySources_GitSubmodulesConfig_GitHubEnterprise(t *testing.T) { + var project codebuild.Project + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_codebuild_project.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCodeBuildProjectConfig_SecondarySources_GitSubmodulesConfig_GitHubEnterprise(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSCodeBuildProjectConfig_SecondarySources_GitSubmodulesConfig_GitHubEnterprise(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "secondary_sources.3511868825.git_submodules_config.#", "1"), - resource.TestCheckResourceAttr(resourceName, "secondary_sources.3511868825.git_submodules_config.0.fetch_submodules", "false"), - resource.TestCheckResourceAttr(resourceName, "secondary_sources.1651171204.git_submodules_config.#", "1"), - resource.TestCheckResourceAttr(resourceName, "secondary_sources.1651171204.git_submodules_config.0.fetch_submodules", "false"), ), }, }, @@ -693,16 +877,15 @@ func TestAccAWSCodeBuildProject_Source_InsecureSSL(t *testing.T) { resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_Source_InsecureSSL(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.1976396802.insecure_ssl", "true"), + resource.TestCheckResourceAttr(resourceName, "source.0.insecure_ssl", "true"), ), }, { @@ -714,7 +897,7 @@ func TestAccAWSCodeBuildProject_Source_InsecureSSL(t *testing.T) { Config: testAccAWSCodeBuildProjectConfig_Source_InsecureSSL(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.3680505372.insecure_ssl", "false"), + resource.TestCheckResourceAttr(resourceName, "source.0.insecure_ssl", "false"), ), }, }, @@ -727,16 +910,15 @@ func TestAccAWSCodeBuildProject_Source_ReportBuildStatus_Bitbucket(t *testing.T) resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_Source_ReportBuildStatus_Bitbucket(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.2876219937.report_build_status", "true"), + resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "true"), ), }, { @@ -748,7 +930,7 @@ func TestAccAWSCodeBuildProject_Source_ReportBuildStatus_Bitbucket(t *testing.T) Config: testAccAWSCodeBuildProjectConfig_Source_ReportBuildStatus_Bitbucket(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.3210444828.report_build_status", "false"), + resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "false"), ), }, }, @@ -761,16 +943,15 @@ func TestAccAWSCodeBuildProject_Source_ReportBuildStatus_GitHub(t *testing.T) { resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_Source_ReportBuildStatus_GitHub(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.4215890488.report_build_status", "true"), + resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "true"), ), }, { @@ -782,7 +963,7 @@ func TestAccAWSCodeBuildProject_Source_ReportBuildStatus_GitHub(t *testing.T) { Config: testAccAWSCodeBuildProjectConfig_Source_ReportBuildStatus_GitHub(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.3680505372.report_build_status", "false"), + resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "false"), ), }, }, @@ -795,16 +976,15 @@ func TestAccAWSCodeBuildProject_Source_ReportBuildStatus_GitHubEnterprise(t *tes resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_Source_ReportBuildStatus_GitHubEnterprise(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.2964899175.report_build_status", "true"), + resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "true"), ), }, { @@ -816,7 +996,7 @@ func TestAccAWSCodeBuildProject_Source_ReportBuildStatus_GitHubEnterprise(t *tes Config: testAccAWSCodeBuildProjectConfig_Source_ReportBuildStatus_GitHubEnterprise(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.553628638.report_build_status", "false"), + resource.TestCheckResourceAttr(resourceName, "source.0.report_build_status", "false"), ), }, }, @@ -829,16 +1009,15 @@ func TestAccAWSCodeBuildProject_Source_Type_Bitbucket(t *testing.T) { resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_Source_Type_Bitbucket(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.3210444828.type", "BITBUCKET"), + resource.TestCheckResourceAttr(resourceName, "source.0.type", "BITBUCKET"), ), }, { @@ -856,16 +1035,15 @@ func TestAccAWSCodeBuildProject_Source_Type_CodeCommit(t *testing.T) { resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_Source_Type_CodeCommit(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.3715340088.type", "CODECOMMIT"), + resource.TestCheckResourceAttr(resourceName, "source.0.type", "CODECOMMIT"), ), }, { @@ -883,16 +1061,15 @@ func TestAccAWSCodeBuildProject_Source_Type_CodePipeline(t *testing.T) { resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_Source_Type_CodePipeline(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.2280907000.type", "CODEPIPELINE"), + resource.TestCheckResourceAttr(resourceName, "source.0.type", "CODEPIPELINE"), ), }, { @@ -910,16 +1087,15 @@ func TestAccAWSCodeBuildProject_Source_Type_GitHubEnterprise(t *testing.T) { resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_Source_Type_GitHubEnterprise(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.553628638.type", "GITHUB_ENTERPRISE"), + resource.TestCheckResourceAttr(resourceName, "source.0.type", "GITHUB_ENTERPRISE"), ), }, { @@ -965,19 +1141,19 @@ version: 0.2 phases: build: commands: - - rspec hello_world_spec.rb` + - rspec hello_world_spec.rb +` resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_Source_Type_NoSource(rName, "", rBuildspec), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.2726343112.type", "NO_SOURCE"), + resource.TestCheckResourceAttr(resourceName, "source.0.type", "NO_SOURCE"), ), }, { @@ -996,7 +1172,8 @@ version: 0.2 phases: build: commands: - - rspec hello_world_spec.rb` + - rspec hello_world_spec.rb +` resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, @@ -1104,22 +1281,53 @@ func TestAccAWSCodeBuildProject_WindowsContainer(t *testing.T) { resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_WindowsContainer(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "environment.#", "1"), - resource.TestCheckResourceAttr(resourceName, "environment.2306861956.compute_type", "BUILD_GENERAL1_MEDIUM"), - resource.TestCheckResourceAttr(resourceName, "environment.2306861956.environment_variable.#", "0"), - resource.TestCheckResourceAttr(resourceName, "environment.2306861956.image", "2"), - resource.TestCheckResourceAttr(resourceName, "environment.2306861956.privileged_mode", "false"), - resource.TestCheckResourceAttr(resourceName, "environment.2306861956.image_pull_credentials_type", "CODEBUILD"), - resource.TestCheckResourceAttr(resourceName, "environment.2306861956.type", "WINDOWS_CONTAINER"), + resource.TestCheckResourceAttr(resourceName, "environment.0.compute_type", codebuild.ComputeTypeBuildGeneral1Medium), + resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.#", "0"), + resource.TestCheckResourceAttr(resourceName, "environment.0.image", "2"), + resource.TestCheckResourceAttr(resourceName, "environment.0.privileged_mode", "false"), + resource.TestCheckResourceAttr(resourceName, "environment.0.image_pull_credentials_type", codebuild.ImagePullCredentialsTypeCodebuild), + resource.TestCheckResourceAttr(resourceName, "environment.0.type", codebuild.EnvironmentTypeWindowsContainer), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSCodeBuildProject_WindowsServer2019Container(t *testing.T) { + var project codebuild.Project + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_codebuild_project.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCodeBuildProjectConfig_WindowsServer2019Container(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSCodeBuildProjectExists(resourceName, &project), + resource.TestCheckResourceAttr(resourceName, "environment.#", "1"), + resource.TestCheckResourceAttr(resourceName, "environment.0.compute_type", codebuild.ComputeTypeBuildGeneral1Medium), + resource.TestCheckResourceAttr(resourceName, "environment.0.environment_variable.#", "0"), + resource.TestCheckResourceAttr(resourceName, "environment.0.image", "2"), + resource.TestCheckResourceAttr(resourceName, "environment.0.privileged_mode", "false"), + resource.TestCheckResourceAttr(resourceName, "environment.0.image_pull_credentials_type", codebuild.ImagePullCredentialsTypeCodebuild), + resource.TestCheckResourceAttr(resourceName, "environment.0.type", codebuild.EnvironmentTypeWindowsServer2019Container), ), }, { @@ -1523,21 +1731,19 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_ArtifactIdentifier(t *testing artifactIdentifier1 := "artifactIdentifier1" artifactIdentifier2 := "artifactIdentifier2" - hash1 := artifactHash(artifactIdentifier1, "false", bName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - hash2 := artifactHash(artifactIdentifier2, "false", bName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodebuildProjectConfig_SecondaryArtifacts_ArtifactIdentifier(rName, bName, artifactIdentifier1), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.artifact_identifier", hash1), artifactIdentifier1), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "artifact_identifier": artifactIdentifier1, + }), ), }, { @@ -1550,7 +1756,9 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_ArtifactIdentifier(t *testing Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.artifact_identifier", hash2), artifactIdentifier2), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "artifact_identifier": artifactIdentifier2, + }), ), }, }, @@ -1563,21 +1771,19 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_OverrideArtifactName(t *testi bName := acctest.RandomWithPrefix("tf-acc-test-bucket") resourceName := "aws_codebuild_project.test" - hash1 := artifactHash("secondaryArtifact1", "false", bName, codebuild.ArtifactNamespaceNone, "true", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - hash2 := artifactHash("secondaryArtifact1", "false", bName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodebuildProjectConfig_SecondaryArtifacts_OverrideArtifactName(rName, bName, true), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.override_artifact_name", hash1), "true"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "override_artifact_name": "true", + }), ), }, { @@ -1590,7 +1796,9 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_OverrideArtifactName(t *testi Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.override_artifact_name", hash2), "false"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "override_artifact_name": "false", + }), ), }, }, @@ -1603,21 +1811,19 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_EncryptionDisabled(t *testing bName := acctest.RandomWithPrefix("tf-acc-test-bucket") resourceName := "aws_codebuild_project.test" - hash1 := artifactHash("secondaryArtifact1", "true", bName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - hash2 := artifactHash("secondaryArtifact1", "false", bName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodebuildProjectConfig_SecondaryArtifacts_EncryptionDisabled(rName, bName, true), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.encryption_disabled", hash1), "true"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "encryption_disabled": "true", + }), ), }, { @@ -1630,7 +1836,9 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_EncryptionDisabled(t *testing Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.encryption_disabled", hash2), "false"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "encryption_disabled": "false", + }), ), }, }, @@ -1644,21 +1852,19 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_Location(t *testing.T) { bName2 := acctest.RandomWithPrefix("tf-acc-test-bucket2") resourceName := "aws_codebuild_project.test" - hash1 := artifactHash("secondaryArtifact1", "false", bName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - hash2 := artifactHash("secondaryArtifact1", "false", bName2, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodebuildProjectConfig_SecondaryArtifacts_Location(rName, bName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.location", hash1), bName), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "location": bName, + }), ), }, { @@ -1671,7 +1877,9 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_Location(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.location", hash2), bName2), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "location": bName2, + }), ), }, }, @@ -1679,7 +1887,7 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_Location(t *testing.T) { } func TestAccAWSCodeBuildProject_SecondaryArtifacts_Name(t *testing.T) { - t.Skip("Currently no solution to allow updates on name attribute") + TestAccSkip(t, "Currently no solution to allow updates on name attribute") var project codebuild.Project rName := acctest.RandomWithPrefix("tf-acc-test") @@ -1689,9 +1897,6 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_Name(t *testing.T) { name1 := "name1" name2 := "name2" - hash1 := artifactHash("secondaryArtifact1", "false", bName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - hash2 := artifactHash("secondaryArtifact1", "false", bName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, Providers: testAccProviders, @@ -1702,7 +1907,9 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_Name(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.name", hash1), name1), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "name": name1, + }), ), }, { @@ -1715,7 +1922,9 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_Name(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.name", hash2), name2), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "name": name2, + }), ), }, }, @@ -1727,21 +1936,19 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_NamespaceType(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_codebuild_project.test" - hash1 := artifactHash("secondaryArtifact1", "false", rName, codebuild.ArtifactNamespaceBuildId, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - hash2 := artifactHash("secondaryArtifact1", "false", rName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodebuildProjectConfig_SecondaryArtifacts_NamespaceType(rName, codebuild.ArtifactNamespaceBuildId), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.namespace_type", hash1), codebuild.ArtifactNamespaceBuildId), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "namespace_type": codebuild.ArtifactNamespaceBuildId, + }), ), }, { @@ -1754,7 +1961,9 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_NamespaceType(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.namespace_type", hash2), codebuild.ArtifactNamespaceNone), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "namespace_type": codebuild.ArtifactNamespaceNone, + }), ), }, }, @@ -1766,21 +1975,19 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_Packaging(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_codebuild_project.test" - hash1 := artifactHash("secondaryArtifact1", "false", rName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingZip, "", codebuild.ArtifactsTypeS3) - hash2 := artifactHash("secondaryArtifact1", "false", rName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", codebuild.ArtifactsTypeS3) - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodebuildProjectConfig_SecondaryArtifacts_Packaging(rName, codebuild.ArtifactPackagingZip), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.packaging", hash1), codebuild.ArtifactPackagingZip), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "packaging": codebuild.ArtifactPackagingZip, + }), ), }, { @@ -1793,7 +2000,9 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_Packaging(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.packaging", hash2), codebuild.ArtifactPackagingNone), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "packaging": codebuild.ArtifactPackagingNone, + }), ), }, }, @@ -1808,21 +2017,19 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_Path(t *testing.T) { path1 := "path1" path2 := "path2" - hash1 := artifactHash("secondaryArtifact1", "false", rName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, path1, codebuild.ArtifactsTypeS3) - hash2 := artifactHash("secondaryArtifact1", "false", rName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, path2, codebuild.ArtifactsTypeS3) - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodebuildProjectConfig_SecondaryArtifacts_Path(rName, path1), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.path", hash1), path1), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "path": path1, + }), ), }, { @@ -1835,7 +2042,9 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_Path(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.path", hash2), path2), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "path": path2, + }), ), }, }, @@ -1848,22 +2057,19 @@ func TestAccAWSCodeBuildProject_SecondaryArtifacts_Type(t *testing.T) { bName := acctest.RandomWithPrefix("tf-acc-test-bucket") resourceName := "aws_codebuild_project.test" - type1 := codebuild.ArtifactsTypeS3 - - hash1 := artifactHash("secondaryArtifact1", "false", bName, codebuild.ArtifactNamespaceNone, "false", codebuild.ArtifactPackagingNone, "", type1) - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSCodebuildProjectConfig_SecondaryArtifacts_Type(rName, bName, type1), + Config: testAccAWSCodebuildProjectConfig_SecondaryArtifacts_Type(rName, bName, codebuild.ArtifactsTypeS3), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), resource.TestCheckResourceAttr(resourceName, "secondary_artifacts.#", "1"), - resource.TestCheckResourceAttr(resourceName, fmt.Sprintf("secondary_artifacts.%d.type", hash1), type1), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_artifacts.*", map[string]string{ + "type": codebuild.ArtifactsTypeS3, + }), ), }, { @@ -1881,18 +2087,21 @@ func TestAccAWSCodeBuildProject_SecondarySources_CodeCommit(t *testing.T) { resourceName := "aws_codebuild_project.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSCodeBuild(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCodeBuildProjectDestroy, Steps: []resource.TestStep{ { Config: testAccAWSCodeBuildProjectConfig_SecondarySources_CodeCommit(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSCodeBuildProjectExists(resourceName, &project), - resource.TestCheckResourceAttr(resourceName, "source.3715340088.type", "CODECOMMIT"), - resource.TestCheckResourceAttr(resourceName, "secondary_sources.493771744.source_identifier", "secondarySource1"), - resource.TestCheckResourceAttr(resourceName, "secondary_sources.1385902896.source_identifier", "secondarySource2"), + resource.TestCheckResourceAttr(resourceName, "source.0.type", "CODECOMMIT"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_sources.*", map[string]string{ + "source_identifier": "secondarySource1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "secondary_sources.*", map[string]string{ + "source_identifier": "secondarySource2", + }), ), }, { @@ -2072,10 +2281,11 @@ resource "aws_iam_role" "test" { ] } EOF + } resource "aws_iam_role_policy" "test" { - role = "${aws_iam_role.test.name}" + role = aws_iam_role.test.name policy = < 0 }), - customdiff.ForceNewIfChange("organization_aggregation_source", func(old, new, meta interface{}) bool { + customdiff.ForceNewIfChange("organization_aggregation_source", func(_ context.Context, old, new, meta interface{}) bool { return len(old.([]interface{})) == 0 && len(new.([]interface{})) > 0 }), ), diff --git a/aws/resource_aws_config_configuration_aggregator_test.go b/aws/resource_aws_config_configuration_aggregator_test.go index 19e71c3ce55..ca9f8aa08f3 100644 --- a/aws/resource_aws_config_configuration_aggregator_test.go +++ b/aws/resource_aws_config_configuration_aggregator_test.go @@ -3,14 +3,13 @@ package aws import ( "fmt" "log" - "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/configservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -75,7 +74,7 @@ func TestAccAWSConfigConfigurationAggregator_account(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "account_aggregation_source.#", "1"), resource.TestCheckResourceAttr(resourceName, "account_aggregation_source.0.account_ids.#", "1"), - resource.TestMatchResourceAttr(resourceName, "account_aggregation_source.0.account_ids.0", regexp.MustCompile(`^\d{12}$`)), + testAccCheckResourceAttrAccountID(resourceName, "account_aggregation_source.0.account_ids.0"), resource.TestCheckResourceAttr(resourceName, "account_aggregation_source.0.regions.#", "1"), resource.TestCheckResourceAttr(resourceName, "account_aggregation_source.0.regions.0", "us-west-2"), ), @@ -266,27 +265,29 @@ resource "aws_config_configuration_aggregator" "example" { name = %[1]q account_aggregation_source { - account_ids = ["${data.aws_caller_identity.current.account_id}"] + account_ids = [data.aws_caller_identity.current.account_id] regions = ["us-west-2"] } } -data "aws_caller_identity" "current" {} +data "aws_caller_identity" "current" { +} `, rName) } func testAccAWSConfigConfigurationAggregatorConfig_organization(rName string) string { return fmt.Sprintf(` -resource "aws_organizations_organization" "test" {} +resource "aws_organizations_organization" "test" { +} resource "aws_config_configuration_aggregator" "example" { - depends_on = ["aws_iam_role_policy_attachment.example"] + depends_on = [aws_iam_role_policy_attachment.example] name = %[1]q organization_aggregation_source { all_regions = true - role_arn = "${aws_iam_role.example.arn}" + role_arn = aws_iam_role.example.arn } } @@ -308,10 +309,11 @@ resource "aws_iam_role" "example" { ] } EOF + } resource "aws_iam_role_policy_attachment" "example" { - role = "${aws_iam_role.example.name}" + role = aws_iam_role.example.name policy_arn = "arn:aws:iam::aws:policy/service-role/AWSConfigRoleForOrganizations" } `, rName) @@ -323,14 +325,14 @@ resource "aws_config_configuration_aggregator" "example" { name = %[1]q account_aggregation_source { - account_ids = ["${data.aws_caller_identity.current.account_id}"] + account_ids = [data.aws_caller_identity.current.account_id] regions = ["us-west-2"] } tags = { - Name = %[1]q - %[2]s = %[3]q - %[4]s = %[5]q + Name = %[1]q + %[2]s = %[3]q + %[4]s = %[5]q } } diff --git a/aws/resource_aws_config_configuration_recorder.go b/aws/resource_aws_config_configuration_recorder.go index aa05a0e3ca7..b709e9b5c12 100644 --- a/aws/resource_aws_config_configuration_recorder.go +++ b/aws/resource_aws_config_configuration_recorder.go @@ -4,8 +4,8 @@ import ( "fmt" "log" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/configservice" diff --git a/aws/resource_aws_config_configuration_recorder_status.go b/aws/resource_aws_config_configuration_recorder_status.go index 34afae3bb84..c5779871a80 100644 --- a/aws/resource_aws_config_configuration_recorder_status.go +++ b/aws/resource_aws_config_configuration_recorder_status.go @@ -4,7 +4,7 @@ import ( "fmt" "log" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/configservice" diff --git a/aws/resource_aws_config_configuration_recorder_status_test.go b/aws/resource_aws_config_configuration_recorder_status_test.go index 2ea57d5e340..27aa6a8bd4c 100644 --- a/aws/resource_aws_config_configuration_recorder_status_test.go +++ b/aws/resource_aws_config_configuration_recorder_status_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/configservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccConfigConfigurationRecorderStatus_basic(t *testing.T) { @@ -172,7 +172,7 @@ func testAccConfigConfigurationRecorderStatusConfig(randInt int, enabled bool) s return fmt.Sprintf(` resource "aws_config_configuration_recorder" "foo" { name = "tf-acc-test-%d" - role_arn = "${aws_iam_role.r.arn}" + role_arn = aws_iam_role.r.arn } resource "aws_iam_role" "r" { @@ -193,11 +193,12 @@ resource "aws_iam_role" "r" { ] } POLICY + } resource "aws_iam_role_policy" "p" { name = "tf-acc-test-awsconfig-%d" - role = "${aws_iam_role.r.id}" + role = aws_iam_role.r.id policy = < 0 { @@ -105,7 +123,7 @@ func resourceAwsCustomerGatewayCreate(d *schema.ResourceData, meta interface{}) } } - return nil + return resourceAwsCustomerGatewayRead(d, meta) } func customerGatewayRefreshFunc(conn *ec2.EC2, gatewayId string) resource.StateRefreshFunc { @@ -119,7 +137,7 @@ func customerGatewayRefreshFunc(conn *ec2.EC2, gatewayId string) resource.StateR Filters: []*ec2.Filter{gatewayFilter}, }) if err != nil { - if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidCustomerGatewayID.NotFound" { + if isAWSErr(err, "InvalidCustomerGatewayID.NotFound", "") { resp = nil } else { log.Printf("Error on CustomerGatewayRefresh: %s", err) @@ -137,7 +155,7 @@ func customerGatewayRefreshFunc(conn *ec2.EC2, gatewayId string) resource.StateR } } -func resourceAwsCustomerGatewayExists(vpnType, ipAddress string, bgpAsn int, conn *ec2.EC2) (bool, error) { +func resourceAwsCustomerGatewayExists(vpnType, ipAddress, bgpAsn string, conn *ec2.EC2) (bool, error) { ipAddressFilter := &ec2.Filter{ Name: aws.String("ip-address"), Values: []*string{aws.String(ipAddress)}, @@ -148,10 +166,9 @@ func resourceAwsCustomerGatewayExists(vpnType, ipAddress string, bgpAsn int, con Values: []*string{aws.String(vpnType)}, } - bgp := strconv.Itoa(bgpAsn) bgpAsnFilter := &ec2.Filter{ Name: aws.String("bgp-asn"), - Values: []*string{aws.String(bgp)}, + Values: []*string{aws.String(bgpAsn)}, } resp, err := conn.DescribeCustomerGateways(&ec2.DescribeCustomerGatewaysInput{ @@ -161,7 +178,7 @@ func resourceAwsCustomerGatewayExists(vpnType, ipAddress string, bgpAsn int, con return false, err } - if len(resp.CustomerGateways) > 0 && *resp.CustomerGateways[0].State != "deleted" { + if len(resp.CustomerGateways) > 0 && aws.StringValue(resp.CustomerGateways[0].State) != "deleted" { return true, nil } @@ -181,7 +198,8 @@ func resourceAwsCustomerGatewayRead(d *schema.ResourceData, meta interface{}) er Filters: []*ec2.Filter{gatewayFilter}, }) if err != nil { - if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidCustomerGatewayID.NotFound" { + if isAWSErr(err, "InvalidCustomerGatewayID.NotFound", "") { + log.Printf("[WARN] Customer Gateway (%s) not found, removing from state", d.Id()) d.SetId("") return nil } else { @@ -194,13 +212,14 @@ func resourceAwsCustomerGatewayRead(d *schema.ResourceData, meta interface{}) er return fmt.Errorf("Error finding CustomerGateway: %s", d.Id()) } - if *resp.CustomerGateways[0].State == "deleted" { + if aws.StringValue(resp.CustomerGateways[0].State) == "deleted" { log.Printf("[INFO] Customer Gateway is in `deleted` state: %s", d.Id()) d.SetId("") return nil } customerGateway := resp.CustomerGateways[0] + d.Set("bgp_asn", customerGateway.BgpAsn) d.Set("ip_address", customerGateway.IpAddress) d.Set("type", customerGateway.Type) @@ -208,14 +227,15 @@ func resourceAwsCustomerGatewayRead(d *schema.ResourceData, meta interface{}) er return fmt.Errorf("error setting tags: %s", err) } - if *customerGateway.BgpAsn != "" { - val, err := strconv.ParseInt(*customerGateway.BgpAsn, 0, 0) - if err != nil { - return fmt.Errorf("error parsing bgp_asn: %s", err) - } + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Service: "ec2", + Region: meta.(*AWSClient).region, + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("customer-gateway/%s", d.Id()), + }.String() - d.Set("bgp_asn", int(val)) - } + d.Set("arn", arn) return nil } @@ -241,7 +261,7 @@ func resourceAwsCustomerGatewayDelete(d *schema.ResourceData, meta interface{}) CustomerGatewayId: aws.String(d.Id()), }) if err != nil { - if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidCustomerGatewayID.NotFound" { + if isAWSErr(err, "InvalidCustomerGatewayID.NotFound", "") { return nil } else { return fmt.Errorf("[ERROR] Error deleting CustomerGateway: %s", err) @@ -294,9 +314,10 @@ func checkGatewayDeleteResponse(resp *ec2.DescribeCustomerGatewaysOutput, id str return fmt.Errorf("Error finding CustomerGateway for delete: %s", id) } - switch *resp.CustomerGateways[0].State { + cgState := aws.StringValue(resp.CustomerGateways[0].State) + switch cgState { case "pending", "available", "deleting": - return fmt.Errorf("Gateway (%s) in state (%s), retrying", id, *resp.CustomerGateways[0].State) + return fmt.Errorf("Gateway (%s) in state (%s), retrying", id, cgState) case "deleted": return nil default: diff --git a/aws/resource_aws_customer_gateway_test.go b/aws/resource_aws_customer_gateway_test.go index 5956f57dfef..da6220f4625 100644 --- a/aws/resource_aws_customer_gateway_test.go +++ b/aws/resource_aws_customer_gateway_test.go @@ -2,23 +2,20 @@ package aws import ( "fmt" - "regexp" - "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" + "regexp" + "strconv" + "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSCustomerGateway_basic(t *testing.T) { var gateway ec2.CustomerGateway rBgpAsn := acctest.RandIntRange(64512, 65534) - rInt := acctest.RandInt() resourceName := "aws_customer_gateway.test" resource.ParallelTest(t, resource.TestCase{ @@ -28,9 +25,12 @@ func TestAccAWSCustomerGateway_basic(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayConfig(rInt, rBgpAsn), + Config: testAccCustomerGatewayConfig(rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGateway(resourceName, &gateway), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`customer-gateway/cgw-.+`)), + resource.TestCheckResourceAttr(resourceName, "bgp_asn", strconv.Itoa(rBgpAsn)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { @@ -39,16 +39,52 @@ func TestAccAWSCustomerGateway_basic(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCustomerGatewayConfigUpdateTags(rInt, rBgpAsn), + Config: testAccCustomerGatewayConfigForceReplace(rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGateway(resourceName, &gateway), ), }, + }, + }) +} + +func TestAccAWSCustomerGateway_tags(t *testing.T) { + var gateway ec2.CustomerGateway + rBgpAsn := acctest.RandIntRange(64512, 65534) + resourceName := "aws_customer_gateway.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckCustomerGatewayDestroy, + Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayConfigForceReplace(rInt, rBgpAsn), + Config: testAccCustomerGatewayConfigTags1(rBgpAsn, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGateway(resourceName, &gateway), - ), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1")), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccCustomerGatewayConfigTags2(rBgpAsn, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckCustomerGateway(resourceName, &gateway), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2")), + }, + { + Config: testAccCustomerGatewayConfigTags1(rBgpAsn, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckCustomerGateway(resourceName, &gateway), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2")), }, }, }) @@ -56,7 +92,6 @@ func TestAccAWSCustomerGateway_basic(t *testing.T) { func TestAccAWSCustomerGateway_similarAlreadyExists(t *testing.T) { var gateway ec2.CustomerGateway - rInt := acctest.RandInt() rBgpAsn := acctest.RandIntRange(64512, 65534) resourceName := "aws_customer_gateway.test" @@ -67,7 +102,7 @@ func TestAccAWSCustomerGateway_similarAlreadyExists(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayConfig(rInt, rBgpAsn), + Config: testAccCustomerGatewayConfig(rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGateway(resourceName, &gateway), ), @@ -78,7 +113,7 @@ func TestAccAWSCustomerGateway_similarAlreadyExists(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCustomerGatewayConfigIdentical(rInt, rBgpAsn), + Config: testAccCustomerGatewayConfigIdentical(rBgpAsn), ExpectError: regexp.MustCompile("An existing customer gateway"), }, }, @@ -86,7 +121,6 @@ func TestAccAWSCustomerGateway_similarAlreadyExists(t *testing.T) { } func TestAccAWSCustomerGateway_disappears(t *testing.T) { - rInt := acctest.RandInt() rBgpAsn := acctest.RandIntRange(64512, 65534) var gateway ec2.CustomerGateway resourceName := "aws_customer_gateway.test" @@ -97,10 +131,10 @@ func TestAccAWSCustomerGateway_disappears(t *testing.T) { CheckDestroy: testAccCheckCustomerGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCustomerGatewayConfig(rInt, rBgpAsn), + Config: testAccCustomerGatewayConfig(rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccCheckCustomerGateway(resourceName, &gateway), - testAccAWSCustomerGatewayDisappears(&gateway), + testAccCheckResourceDisappears(testAccProvider, resourceAwsCustomerGateway(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -108,35 +142,33 @@ func TestAccAWSCustomerGateway_disappears(t *testing.T) { }) } -func testAccAWSCustomerGatewayDisappears(gateway *ec2.CustomerGateway) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - opts := &ec2.DeleteCustomerGatewayInput{ - CustomerGatewayId: gateway.CustomerGatewayId, - } - if _, err := conn.DeleteCustomerGateway(opts); err != nil { - return err - } - return resource.Retry(40*time.Minute, func() *resource.RetryError { - opts := &ec2.DescribeCustomerGatewaysInput{ - CustomerGatewayIds: []*string{gateway.CustomerGatewayId}, - } - resp, err := conn.DescribeCustomerGateways(opts) - if err != nil { - cgw, ok := err.(awserr.Error) - if ok && cgw.Code() == "InvalidCustomerGatewayID.NotFound" { - return nil - } - return resource.NonRetryableError( - fmt.Errorf("Error retrieving Customer Gateway: %s", err)) - } - if *resp.CustomerGateways[0].State == "deleted" { - return nil - } - return resource.RetryableError(fmt.Errorf( - "Waiting for Customer Gateway: %v", gateway.CustomerGatewayId)) - }) - } +func TestAccAWSCustomerGateway_4ByteAsn(t *testing.T) { + var gateway ec2.CustomerGateway + rBgpAsn := strconv.FormatInt(int64(acctest.RandIntRange(64512, 65534))*10000, 10) + resourceName := "aws_customer_gateway.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckCustomerGatewayDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCustomerGatewayConfig4ByteAsn(rBgpAsn), + Check: resource.ComposeTestCheckFunc( + testAccCheckCustomerGateway(resourceName, &gateway), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`customer-gateway/cgw-.+`)), + resource.TestCheckResourceAttr(resourceName, "bgp_asn", rBgpAsn), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) } func testAccCheckCustomerGatewayDestroy(s *terraform.State) error { @@ -156,7 +188,7 @@ func testAccCheckCustomerGatewayDestroy(s *terraform.State) error { Filters: []*ec2.Filter{gatewayFilter}, }) - if ae, ok := err.(awserr.Error); ok && ae.Code() == "InvalidCustomerGatewayID.NotFound" { + if isAWSErr(err, "InvalidCustomerGatewayID.NotFound", "") { continue } @@ -165,7 +197,7 @@ func testAccCheckCustomerGatewayDestroy(s *terraform.State) error { return fmt.Errorf("Customer gateway still exists: %v", resp.CustomerGateways) } - if *resp.CustomerGateways[0].State == "deleted" { + if aws.StringValue(resp.CustomerGateways[0].State) == "deleted" { continue } } @@ -213,72 +245,78 @@ func testAccCheckCustomerGateway(gatewayResource string, cgw *ec2.CustomerGatewa } } -func testAccCustomerGatewayConfig(rInt, rBgpAsn int) string { +func testAccCustomerGatewayConfig(rBgpAsn int) string { return fmt.Sprintf(` resource "aws_customer_gateway" "test" { bgp_asn = %d ip_address = "172.0.0.1" type = "ipsec.1" - - tags = { - Name = "test-gateway-%d" - } } -`, rBgpAsn, rInt) +`, rBgpAsn) } -func testAccCustomerGatewayConfigIdentical(randInt, rBgpAsn int) string { +func testAccCustomerGatewayConfigTags1(rBgpAsn int, tagKey1, tagValue1 string) string { return fmt.Sprintf(` resource "aws_customer_gateway" "test" { - bgp_asn = %d + bgp_asn = %[1]d ip_address = "172.0.0.1" type = "ipsec.1" tags = { - Name = "test-gateway-%d" + %[2]q = %[3]q } } +`, rBgpAsn, tagKey1, tagValue1) +} -resource "aws_customer_gateway" "identical" { - bgp_asn = %d +func testAccCustomerGatewayConfigTags2(rBgpAsn int, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_customer_gateway" "test" { + bgp_asn = %[1]d ip_address = "172.0.0.1" type = "ipsec.1" tags = { - Name = "test-gateway-identical-%d" + %[2]q = %[3]q + %[4]q = %[5]q } } -`, rBgpAsn, randInt, rBgpAsn, randInt) +`, rBgpAsn, tagKey1, tagValue1, tagKey2, tagValue2) } -// Add the Another: "tag" tag. -func testAccCustomerGatewayConfigUpdateTags(rInt, rBgpAsn int) string { +func testAccCustomerGatewayConfigIdentical(rBgpAsn int) string { return fmt.Sprintf(` resource "aws_customer_gateway" "test" { - bgp_asn = %d + bgp_asn = %[1]d ip_address = "172.0.0.1" type = "ipsec.1" +} - tags = { - Name = "test-gateway-%d" - Another = "tag" - } +resource "aws_customer_gateway" "identical" { + bgp_asn = %[1]d + ip_address = "172.0.0.1" + type = "ipsec.1" } -`, rBgpAsn, rInt) +`, rBgpAsn) } // Change the ip_address. -func testAccCustomerGatewayConfigForceReplace(rInt, rBgpAsn int) string { +func testAccCustomerGatewayConfigForceReplace(rBgpAsn int) string { return fmt.Sprintf(` resource "aws_customer_gateway" "test" { bgp_asn = %d ip_address = "172.10.10.1" type = "ipsec.1" +} +`, rBgpAsn) +} - tags = { - Name = "test-gateway-%d" - Another = "tag" - } +func testAccCustomerGatewayConfig4ByteAsn(rBgpAsn string) string { + return fmt.Sprintf(` +resource "aws_customer_gateway" "test" { + bgp_asn = %[1]q + ip_address = "172.0.0.1" + type = "ipsec.1" } -`, rBgpAsn, rInt) +`, rBgpAsn) } diff --git a/aws/resource_aws_datapipeline_pipeline.go b/aws/resource_aws_datapipeline_pipeline.go index 41195f5b8ae..64f8161cdf3 100644 --- a/aws/resource_aws_datapipeline_pipeline.go +++ b/aws/resource_aws_datapipeline_pipeline.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datapipeline" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_datapipeline_pipeline_test.go b/aws/resource_aws_datapipeline_pipeline_test.go index 45a72834aff..29a64f14cf1 100644 --- a/aws/resource_aws_datapipeline_pipeline_test.go +++ b/aws/resource_aws_datapipeline_pipeline_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datapipeline" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSDataPipelinePipeline_basic(t *testing.T) { diff --git a/aws/resource_aws_datasync_agent.go b/aws/resource_aws_datasync_agent.go index 5046e40bda3..fc5ded31666 100644 --- a/aws/resource_aws_datasync_agent.go +++ b/aws/resource_aws_datasync_agent.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_datasync_agent_test.go b/aws/resource_aws_datasync_agent_test.go index b71a5b75c21..81796720b31 100644 --- a/aws/resource_aws_datasync_agent_test.go +++ b/aws/resource_aws_datasync_agent_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -285,7 +285,7 @@ func testAccCheckAWSDataSyncAgentNotRecreated(i, j *datasync.DescribeAgentOutput // testAccAWSDataSyncAgentConfigAgentBase uses the "thinstaller" AMI func testAccAWSDataSyncAgentConfigAgentBase() string { - return fmt.Sprintf(` + return ` data "aws_ami" "aws-thinstaller" { most_recent = true owners = ["amazon"] @@ -306,7 +306,7 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-datasync-agent" @@ -314,7 +314,7 @@ resource "aws_subnet" "test" { } resource "aws_internet_gateway" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-datasync-agent" @@ -322,11 +322,11 @@ resource "aws_internet_gateway" "test" { } resource "aws_route_table" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id route { cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.test.id}" + gateway_id = aws_internet_gateway.test.id } tags = { @@ -335,12 +335,12 @@ resource "aws_route_table" "test" { } resource "aws_route_table_association" "test" { - subnet_id = "${aws_subnet.test.id}" - route_table_id = "${aws_route_table.test.id}" + subnet_id = aws_subnet.test.id + route_table_id = aws_route_table.test.id } resource "aws_security_group" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id egress { from_port = 0 @@ -362,35 +362,35 @@ resource "aws_security_group" "test" { } resource "aws_instance" "test" { - depends_on = ["aws_internet_gateway.test"] + depends_on = [aws_internet_gateway.test] - ami = "${data.aws_ami.aws-thinstaller.id}" + ami = data.aws_ami.aws-thinstaller.id associate_public_ip_address = true # Default instance type from sync.sh instance_type = "c5.2xlarge" - vpc_security_group_ids = ["${aws_security_group.test.id}"] - subnet_id = "${aws_subnet.test.id}" + vpc_security_group_ids = [aws_security_group.test.id] + subnet_id = aws_subnet.test.id tags = { Name = "tf-acc-test-datasync-agent" } } -`) +` } func testAccAWSDataSyncAgentConfig() string { - return testAccAWSDataSyncAgentConfigAgentBase() + fmt.Sprintf(` + return testAccAWSDataSyncAgentConfigAgentBase() + ` resource "aws_datasync_agent" "test" { - ip_address = "${aws_instance.test.public_ip}" + ip_address = aws_instance.test.public_ip } -`) +` } func testAccAWSDataSyncAgentConfigName(rName string) string { return testAccAWSDataSyncAgentConfigAgentBase() + fmt.Sprintf(` resource "aws_datasync_agent" "test" { - ip_address = "${aws_instance.test.public_ip}" + ip_address = aws_instance.test.public_ip name = %q } `, rName) @@ -399,7 +399,7 @@ resource "aws_datasync_agent" "test" { func testAccAWSDataSyncAgentConfigTags1(key1, value1 string) string { return testAccAWSDataSyncAgentConfigAgentBase() + fmt.Sprintf(` resource "aws_datasync_agent" "test" { - ip_address = "${aws_instance.test.public_ip}" + ip_address = aws_instance.test.public_ip tags = { %q = %q @@ -411,7 +411,7 @@ resource "aws_datasync_agent" "test" { func testAccAWSDataSyncAgentConfigTags2(key1, value1, key2, value2 string) string { return testAccAWSDataSyncAgentConfigAgentBase() + fmt.Sprintf(` resource "aws_datasync_agent" "test" { - ip_address = "${aws_instance.test.public_ip}" + ip_address = aws_instance.test.public_ip tags = { %q = %q diff --git a/aws/resource_aws_datasync_location_efs.go b/aws/resource_aws_datasync_location_efs.go index e30d4c6a9c8..e796b16d1df 100644 --- a/aws/resource_aws_datasync_location_efs.go +++ b/aws/resource_aws_datasync_location_efs.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_datasync_location_efs_test.go b/aws/resource_aws_datasync_location_efs_test.go index d693493daf1..d8a616a5567 100644 --- a/aws/resource_aws_datasync_location_efs_test.go +++ b/aws/resource_aws_datasync_location_efs_test.go @@ -10,8 +10,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -285,7 +285,7 @@ func testAccCheckAWSDataSyncLocationEfsNotRecreated(i, j *datasync.DescribeLocat } func testAccAWSDataSyncLocationEfsConfigBase() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -296,7 +296,7 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-datasync-location-efs" @@ -304,7 +304,7 @@ resource "aws_subnet" "test" { } resource "aws_security_group" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-datasync-location-efs" @@ -314,34 +314,34 @@ resource "aws_security_group" "test" { resource "aws_efs_file_system" "test" {} resource "aws_efs_mount_target" "test" { - file_system_id = "${aws_efs_file_system.test.id}" - subnet_id = "${aws_subnet.test.id}" + file_system_id = aws_efs_file_system.test.id + subnet_id = aws_subnet.test.id } -`) +` } func testAccAWSDataSyncLocationEfsConfig() string { - return testAccAWSDataSyncLocationEfsConfigBase() + fmt.Sprintf(` + return testAccAWSDataSyncLocationEfsConfigBase() + ` resource "aws_datasync_location_efs" "test" { - efs_file_system_arn = "${aws_efs_mount_target.test.file_system_arn}" + efs_file_system_arn = aws_efs_mount_target.test.file_system_arn ec2_config { - security_group_arns = ["${aws_security_group.test.arn}"] - subnet_arn = "${aws_subnet.test.arn}" + security_group_arns = [aws_security_group.test.arn] + subnet_arn = aws_subnet.test.arn } } -`) +` } func testAccAWSDataSyncLocationEfsConfigSubdirectory(subdirectory string) string { return testAccAWSDataSyncLocationEfsConfigBase() + fmt.Sprintf(` resource "aws_datasync_location_efs" "test" { - efs_file_system_arn = "${aws_efs_mount_target.test.file_system_arn}" + efs_file_system_arn = aws_efs_mount_target.test.file_system_arn subdirectory = %q ec2_config { - security_group_arns = ["${aws_security_group.test.arn}"] - subnet_arn = "${aws_subnet.test.arn}" + security_group_arns = [aws_security_group.test.arn] + subnet_arn = aws_subnet.test.arn } } `, subdirectory) @@ -350,11 +350,11 @@ resource "aws_datasync_location_efs" "test" { func testAccAWSDataSyncLocationEfsConfigTags1(key1, value1 string) string { return testAccAWSDataSyncLocationEfsConfigBase() + fmt.Sprintf(` resource "aws_datasync_location_efs" "test" { - efs_file_system_arn = "${aws_efs_mount_target.test.file_system_arn}" + efs_file_system_arn = aws_efs_mount_target.test.file_system_arn ec2_config { - security_group_arns = ["${aws_security_group.test.arn}"] - subnet_arn = "${aws_subnet.test.arn}" + security_group_arns = [aws_security_group.test.arn] + subnet_arn = aws_subnet.test.arn } tags = { @@ -370,8 +370,8 @@ resource "aws_datasync_location_efs" "test" { efs_file_system_arn = "${aws_efs_mount_target.test.file_system_arn}" ec2_config { - security_group_arns = ["${aws_security_group.test.arn}"] - subnet_arn = "${aws_subnet.test.arn}" + security_group_arns = [aws_security_group.test.arn] + subnet_arn = aws_subnet.test.arn } tags = { diff --git a/aws/resource_aws_datasync_location_nfs.go b/aws/resource_aws_datasync_location_nfs.go index 1f6b3fd455b..fa8e7cea9d0 100644 --- a/aws/resource_aws_datasync_location_nfs.go +++ b/aws/resource_aws_datasync_location_nfs.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_datasync_location_nfs_test.go b/aws/resource_aws_datasync_location_nfs_test.go index 87b6a229a63..a805b26c724 100644 --- a/aws/resource_aws_datasync_location_nfs_test.go +++ b/aws/resource_aws_datasync_location_nfs_test.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -336,7 +336,7 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-datasync-location-nfs" @@ -344,7 +344,7 @@ resource "aws_subnet" "test" { } resource "aws_internet_gateway" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-datasync-location-nfs" @@ -352,11 +352,11 @@ resource "aws_internet_gateway" "test" { } resource "aws_route_table" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id route { cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.test.id}" + gateway_id = aws_internet_gateway.test.id } tags = { @@ -365,12 +365,12 @@ resource "aws_route_table" "test" { } resource "aws_route_table_association" "test" { - subnet_id = "${aws_subnet.test.id}" - route_table_id = "${aws_route_table.test.id}" + subnet_id = aws_subnet.test.id + route_table_id = aws_route_table.test.id } resource "aws_security_group" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id egress { from_port = 0 @@ -392,15 +392,15 @@ resource "aws_security_group" "test" { } resource "aws_instance" "test" { - depends_on = ["aws_internet_gateway.test"] + depends_on = [aws_internet_gateway.test] - ami = "${data.aws_ami.aws-thinstaller.id}" + ami = data.aws_ami.aws-thinstaller.id associate_public_ip_address = true # Default instance type from sync.sh instance_type = "c5.2xlarge" - vpc_security_group_ids = ["${aws_security_group.test.id}"] - subnet_id = "${aws_subnet.test.id}" + vpc_security_group_ids = [aws_security_group.test.id] + subnet_id = aws_subnet.test.id tags = { Name = "tf-acc-test-datasync-location-nfs" @@ -408,23 +408,23 @@ resource "aws_instance" "test" { } resource "aws_datasync_agent" "test" { - ip_address = "${aws_instance.test.public_ip}" + ip_address = aws_instance.test.public_ip name = %q } `, rName) } func testAccAWSDataSyncLocationNfsConfig(rName string) string { - return testAccAWSDataSyncLocationNfsConfigBase(rName) + fmt.Sprintf(` + return testAccAWSDataSyncLocationNfsConfigBase(rName) + ` resource "aws_datasync_location_nfs" "test" { server_hostname = "example.com" subdirectory = "/" on_prem_config { - agent_arns = ["${aws_datasync_agent.test.arn}"] + agent_arns = [aws_datasync_agent.test.arn] } } -`) +` } func testAccAWSDataSyncLocationNfsConfigAgentArnsMultiple(rName string) string { @@ -432,12 +432,12 @@ func testAccAWSDataSyncLocationNfsConfigAgentArnsMultiple(rName string) string { resource "aws_instance" "test2" { depends_on = ["aws_internet_gateway.test"] - ami = "${data.aws_ami.aws-thinstaller.id}" + ami = data.aws_ami.aws-thinstaller.id associate_public_ip_address = true # Default instance type from sync.sh instance_type = "c5.2xlarge" - vpc_security_group_ids = ["${aws_security_group.test.id}"] - subnet_id = "${aws_subnet.test.id}" + vpc_security_group_ids = [aws_security_group.test.id] + subnet_id = aws_subnet.test.id tags = { Name = "tf-acc-test-datasync-location-nfs" @@ -445,7 +445,7 @@ resource "aws_instance" "test2" { } resource "aws_datasync_agent" "test2" { - ip_address = "${aws_instance.test2.public_ip}" + ip_address = aws_instance.test2.public_ip name = "%s2" } @@ -455,8 +455,8 @@ resource "aws_datasync_location_nfs" "test" { on_prem_config { agent_arns = [ - "${aws_datasync_agent.test.arn}", - "${aws_datasync_agent.test2.arn}", + aws_datasync_agent.test.arn, + aws_datasync_agent.test2.arn, ] } } @@ -470,7 +470,7 @@ resource "aws_datasync_location_nfs" "test" { subdirectory = %q on_prem_config { - agent_arns = ["${aws_datasync_agent.test.arn}"] + agent_arns = [aws_datasync_agent.test.arn] } } `, subdirectory) @@ -483,7 +483,7 @@ resource "aws_datasync_location_nfs" "test" { subdirectory = "/" on_prem_config { - agent_arns = ["${aws_datasync_agent.test.arn}"] + agent_arns = [aws_datasync_agent.test.arn] } tags = { @@ -500,7 +500,7 @@ resource "aws_datasync_location_nfs" "test" { subdirectory = "/" on_prem_config { - agent_arns = ["${aws_datasync_agent.test.arn}"] + agent_arns = [aws_datasync_agent.test.arn] } tags = { diff --git a/aws/resource_aws_datasync_location_s3.go b/aws/resource_aws_datasync_location_s3.go index 9a3c8e4b1fb..68a348abf6c 100644 --- a/aws/resource_aws_datasync_location_s3.go +++ b/aws/resource_aws_datasync_location_s3.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_datasync_location_s3_test.go b/aws/resource_aws_datasync_location_s3_test.go index 62d7c0fa03e..d74b10cc2a7 100644 --- a/aws/resource_aws_datasync_location_s3_test.go +++ b/aws/resource_aws_datasync_location_s3_test.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -309,28 +309,28 @@ resource "aws_s3_bucket" "test" { } func testAccAWSDataSyncLocationS3Config(rName string) string { - return testAccAWSDataSyncLocationS3ConfigBase(rName) + fmt.Sprintf(` + return testAccAWSDataSyncLocationS3ConfigBase(rName) + ` resource "aws_datasync_location_s3" "test" { - s3_bucket_arn = "${aws_s3_bucket.test.arn}" + s3_bucket_arn = aws_s3_bucket.test.arn subdirectory = "/test" s3_config { - bucket_access_role_arn = "${aws_iam_role.test.arn}" + bucket_access_role_arn = aws_iam_role.test.arn } depends_on = [aws_iam_role_policy.test] } -`) +` } func testAccAWSDataSyncLocationS3ConfigTags1(rName, key1, value1 string) string { return testAccAWSDataSyncLocationS3ConfigBase(rName) + fmt.Sprintf(` resource "aws_datasync_location_s3" "test" { - s3_bucket_arn = "${aws_s3_bucket.test.arn}" + s3_bucket_arn = aws_s3_bucket.test.arn subdirectory = "/test" s3_config { - bucket_access_role_arn = "${aws_iam_role.test.arn}" + bucket_access_role_arn = aws_iam_role.test.arn } tags = { @@ -345,11 +345,11 @@ resource "aws_datasync_location_s3" "test" { func testAccAWSDataSyncLocationS3ConfigTags2(rName, key1, value1, key2, value2 string) string { return testAccAWSDataSyncLocationS3ConfigBase(rName) + fmt.Sprintf(` resource "aws_datasync_location_s3" "test" { - s3_bucket_arn = "${aws_s3_bucket.test.arn}" + s3_bucket_arn = aws_s3_bucket.test.arn subdirectory = "/test" s3_config { - bucket_access_role_arn = "${aws_iam_role.test.arn}" + bucket_access_role_arn = aws_iam_role.test.arn } tags = { diff --git a/aws/resource_aws_datasync_location_smb.go b/aws/resource_aws_datasync_location_smb.go index 9768a87db0f..58f35f384e3 100644 --- a/aws/resource_aws_datasync_location_smb.go +++ b/aws/resource_aws_datasync_location_smb.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_datasync_location_smb_test.go b/aws/resource_aws_datasync_location_smb_test.go index 8c5010ceffa..c509ecb0140 100644 --- a/aws/resource_aws_datasync_location_smb_test.go +++ b/aws/resource_aws_datasync_location_smb_test.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -274,10 +274,11 @@ data "aws_ami" "aws_thinstaller" { data "aws_ami" "aws_datasync" { most_recent = true - # I do not know why, but only in us-west-2 - # does the datasync ami _not_ have the amazon-alias. - # Reverting to amazon-owner id. - owners = ["633936118553"] + + # I do not know why, but only in us-west-2 + # does the datasync ami _not_ have the amazon-alias. + # Reverting to amazon-owner id. + owners = ["633936118553"] filter { name = "name" @@ -295,7 +296,7 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-datasync-location-smb" @@ -303,7 +304,7 @@ resource "aws_subnet" "test" { } resource "aws_internet_gateway" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-datasync-location-smb" @@ -311,11 +312,11 @@ resource "aws_internet_gateway" "test" { } resource "aws_route_table" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id route { cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.test.id}" + gateway_id = aws_internet_gateway.test.id } tags = { @@ -324,8 +325,8 @@ resource "aws_route_table" "test" { } resource "aws_route_table_association" "test" { - subnet_id = "${aws_subnet.test.id}" - route_table_id = "${aws_route_table.test.id}" + subnet_id = aws_subnet.test.id + route_table_id = aws_route_table.test.id } resource "aws_iam_role" "test" { @@ -344,10 +345,11 @@ resource "aws_iam_role" "test" { ] } POLICY + } resource "aws_iam_role_policy" "test" { - role = "${aws_iam_role.test.name}" + role = aws_iam_role.test.name policy = < "/dev/xvdc" (forces new resource) # We expect this data source value to change due to how Storage Gateway works. lifecycle { - ignore_changes = ["disk_id"] + ignore_changes = [disk_id] } - disk_id = "${data.aws_storagegateway_local_disk.test.id}" - gateway_arn = "${aws_storagegateway_gateway.test.arn}" + disk_id = data.aws_storagegateway_local_disk.test.id + gateway_arn = aws_storagegateway_gateway.test.arn } resource "aws_storagegateway_smb_file_share" "test" { # Use GuestAccess to simplify testing authentication = "GuestAccess" - gateway_arn = "${aws_storagegateway_gateway.test.arn}" - location_arn = "${aws_s3_bucket.test.arn}" - role_arn = "${aws_iam_role.test.arn}" + gateway_arn = aws_storagegateway_gateway.test.arn + location_arn = aws_s3_bucket.test.arn + role_arn = aws_iam_role.test.arn - # I'm not super sure why this depends_on sadness is required in - # the test framework but not the binary so... yolo! - depends_on = ["aws_storagegateway_cache.test"] + # I'm not super sure why this depends_on sadness is required in + # the test framework but not the binary so... yolo! + depends_on = [aws_storagegateway_cache.test] } resource "aws_instance" "test_datasync" { - depends_on = ["aws_internet_gateway.test"] + depends_on = [aws_internet_gateway.test] - ami = "${data.aws_ami.aws_datasync.id}" + ami = data.aws_ami.aws_datasync.id associate_public_ip_address = true instance_type = "c5.large" - vpc_security_group_ids = ["${aws_security_group.test.id}"] - subnet_id = "${aws_subnet.test.id}" + vpc_security_group_ids = [aws_security_group.test.id] + subnet_id = aws_subnet.test.id tags = { Name = "tf-acc-test-datasync-smb" @@ -478,34 +480,32 @@ resource "aws_instance" "test_datasync" { } resource "aws_datasync_agent" "test" { - ip_address = "${aws_instance.test_datasync.public_ip}" + ip_address = aws_instance.test_datasync.public_ip name = "datasyncsmb-%s" } `, gatewayUid, gatewayUid) } func testAccAWSDataSyncLocationSmbConfig() string { - return testAccAWSDataSyncLocationSmbConfigBase() + fmt.Sprintf(` + return testAccAWSDataSyncLocationSmbConfigBase() + ` resource "aws_datasync_location_smb" "test" { - user = "Guest" - password = "ZaphodBeeblebroxPW" - subdirectory = "/${aws_s3_bucket.test.id}/" - - server_hostname = "${aws_instance.test_datasync.public_ip}" - agent_arns = ["${aws_datasync_agent.test.arn}"] + agent_arns = [aws_datasync_agent.test.arn] + password = "ZaphodBeeblebroxPW" + server_hostname = aws_instance.test_datasync.public_ip + subdirectory = "/${aws_s3_bucket.test.id}/" + user = "Guest" } -`) +` } func testAccAWSDataSyncLocationSmbConfigTags1(key1, value1 string) string { return testAccAWSDataSyncLocationSmbConfigBase() + fmt.Sprintf(` resource "aws_datasync_location_smb" "test" { - user = "Guest" - password = "ZaphodBeeblebroxPW" - subdirectory = "/${aws_s3_bucket.test.id}/" - - server_hostname = "${aws_instance.test_datasync.public_ip}" - agent_arns = ["${aws_datasync_agent.test.arn}"] + agent_arns = [aws_datasync_agent.test.arn] + password = "ZaphodBeeblebroxPW" + server_hostname = aws_instance.test_datasync.public_ip + subdirectory = "/${aws_s3_bucket.test.id}/" + user = "Guest" tags = { %q = %q @@ -517,12 +517,11 @@ resource "aws_datasync_location_smb" "test" { func testAccAWSDataSyncLocationSmbConfigTags2(key1, value1, key2, value2 string) string { return testAccAWSDataSyncLocationSmbConfigBase() + fmt.Sprintf(` resource "aws_datasync_location_smb" "test" { - user = "Guest" - password = "ZaphodBeeblebroxPW" - subdirectory = "/${aws_s3_bucket.test.id}/" - - server_hostname = "${aws_instance.test_datasync.public_ip}" - agent_arns = ["${aws_datasync_agent.test.arn}"] + agent_arns = [aws_datasync_agent.test.arn] + password = "ZaphodBeeblebroxPW" + server_hostname = aws_instance.test_datasync.public_ip + subdirectory = "/${aws_s3_bucket.test.id}/" + user = "Guest" tags = { %q = %q diff --git a/aws/resource_aws_datasync_task.go b/aws/resource_aws_datasync_task.go index 65405532107..046beccac40 100644 --- a/aws/resource_aws_datasync_task.go +++ b/aws/resource_aws_datasync_task.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -139,6 +139,7 @@ func resourceAwsDataSyncTask() *schema.Resource { ValidateFunc: validation.StringInSlice([]string{ datasync.VerifyModeNone, datasync.VerifyModePointInTimeConsistent, + datasync.VerifyModeOnlyFilesTransferred, }, false), }, }, @@ -277,7 +278,7 @@ func resourceAwsDataSyncTaskRead(d *schema.ResourceData, meta interface{}) error func resourceAwsDataSyncTaskUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).datasyncconn - if d.HasChange("options") || d.HasChange("name") { + if d.HasChanges("options", "name") { input := &datasync.UpdateTaskInput{ Options: expandDataSyncOptions(d.Get("options").([]interface{})), Name: aws.String(d.Get("name").(string)), diff --git a/aws/resource_aws_datasync_task_test.go b/aws/resource_aws_datasync_task_test.go index d1471807c44..5fea2711d40 100644 --- a/aws/resource_aws_datasync_task_test.go +++ b/aws/resource_aws_datasync_task_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/datasync" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -421,7 +421,7 @@ func TestAccAWSDataSyncTask_DefaultSyncOptions_Uid(t *testing.T) { } func TestAccAWSDataSyncTask_DefaultSyncOptions_VerifyMode(t *testing.T) { - var task1, task2 datasync.DescribeTaskOutput + var task1, task2, task3 datasync.DescribeTaskOutput rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_datasync_task.test" @@ -452,12 +452,21 @@ func TestAccAWSDataSyncTask_DefaultSyncOptions_VerifyMode(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "options.0.verify_mode", "POINT_IN_TIME_CONSISTENT"), ), }, + { + Config: testAccAWSDataSyncTaskConfigDefaultSyncOptionsVerifyMode(rName, "ONLY_FILES_TRANSFERRED"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSDataSyncTaskExists(resourceName, &task3), + testAccCheckAWSDataSyncTaskNotRecreated(&task2, &task3), + resource.TestCheckResourceAttr(resourceName, "options.#", "1"), + resource.TestCheckResourceAttr(resourceName, "options.0.verify_mode", "ONLY_FILES_TRANSFERRED"), + ), + }, }, }) } func TestAccAWSDataSyncTask_Tags(t *testing.T) { - t.Skip("Tagging on creation is inconsistent") + TestAccSkip(t, "Tagging on creation is inconsistent") var task1, task2, task3 datasync.DescribeTaskOutput rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_datasync_task.test" @@ -650,11 +659,11 @@ POLICY } resource "aws_datasync_location_s3" "destination" { - s3_bucket_arn = "${aws_s3_bucket.destination.arn}" + s3_bucket_arn = aws_s3_bucket.destination.arn subdirectory = "/destination" s3_config { - bucket_access_role_arn = "${aws_iam_role.destination.arn}" + bucket_access_role_arn = aws_iam_role.destination.arn } depends_on = [aws_iam_role_policy.destination] @@ -689,13 +698,13 @@ resource "aws_vpc_dhcp_options" "source" { } resource "aws_vpc_dhcp_options_association" "source" { - dhcp_options_id = "${aws_vpc_dhcp_options.source.id}" - vpc_id = "${aws_vpc.source.id}" + dhcp_options_id = aws_vpc_dhcp_options.source.id + vpc_id = aws_vpc.source.id } resource "aws_subnet" "source" { cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.source.id}" + vpc_id = aws_vpc.source.id tags = { Name = "tf-acc-test-datasync-task" @@ -703,7 +712,7 @@ resource "aws_subnet" "source" { } resource "aws_internet_gateway" "source" { - vpc_id = "${aws_vpc.source.id}" + vpc_id = aws_vpc.source.id tags = { Name = "tf-acc-test-datasync-task" @@ -711,11 +720,11 @@ resource "aws_internet_gateway" "source" { } resource "aws_route_table" "source" { - vpc_id = "${aws_vpc.source.id}" + vpc_id = aws_vpc.source.id route { cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.source.id}" + gateway_id = aws_internet_gateway.source.id } tags = { @@ -724,12 +733,12 @@ resource "aws_route_table" "source" { } resource "aws_route_table_association" "source" { - subnet_id = "${aws_subnet.source.id}" - route_table_id = "${aws_route_table.source.id}" + subnet_id = aws_subnet.source.id + route_table_id = aws_route_table.source.id } resource "aws_security_group" "source" { - vpc_id = "${aws_vpc.source.id}" + vpc_id = aws_vpc.source.id egress { from_port = 0 @@ -751,24 +760,28 @@ resource "aws_security_group" "source" { } # EFS as our NFS server -resource "aws_efs_file_system" "source" {} +resource "aws_efs_file_system" "source" { +} resource "aws_efs_mount_target" "source" { - file_system_id = "${aws_efs_file_system.source.id}" - security_groups = ["${aws_security_group.source.id}"] - subnet_id = "${aws_subnet.source.id}" + file_system_id = aws_efs_file_system.source.id + security_groups = [aws_security_group.source.id] + subnet_id = aws_subnet.source.id } resource "aws_instance" "source" { - depends_on = ["aws_internet_gateway.source", "aws_vpc_dhcp_options_association.source"] + depends_on = [ + aws_internet_gateway.source, + aws_vpc_dhcp_options_association.source, + ] - ami = "${data.aws_ami.source-aws-thinstaller.id}" + ami = data.aws_ami.source-aws-thinstaller.id associate_public_ip_address = true # Default instance type from sync.sh instance_type = "c5.2xlarge" - vpc_security_group_ids = ["${aws_security_group.source.id}"] - subnet_id = "${aws_subnet.source.id}" + vpc_security_group_ids = [aws_security_group.source.id] + subnet_id = aws_subnet.source.id tags = { Name = "tf-acc-test-datasync-task" @@ -776,19 +789,19 @@ resource "aws_instance" "source" { } resource "aws_datasync_agent" "source" { - ip_address = "${aws_instance.source.public_ip}" + ip_address = aws_instance.source.public_ip name = %q } # Using EFS File System DNS name due to DNS propagation delays resource "aws_datasync_location_nfs" "source" { - depends_on = ["aws_efs_mount_target.source"] + depends_on = [aws_efs_mount_target.source] - server_hostname = "${aws_efs_file_system.source.dns_name}" + server_hostname = aws_efs_file_system.source.dns_name subdirectory = "/" on_prem_config { - agent_arns = ["${aws_datasync_agent.source.arn}"] + agent_arns = [aws_datasync_agent.source.arn] } } `, rName) @@ -797,9 +810,9 @@ resource "aws_datasync_location_nfs" "source" { func testAccAWSDataSyncTaskConfig(rName string) string { return testAccAWSDataSyncTaskConfigDestinationLocationS3Base(rName) + testAccAWSDataSyncTaskConfigSourceLocationNfsBase(rName) + fmt.Sprintf(` resource "aws_datasync_task" "test" { - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn } `, rName) } @@ -811,10 +824,10 @@ resource "aws_cloudwatch_log_group" "test" { } resource "aws_datasync_task" "test" { - cloudwatch_log_group_arn = "${replace(aws_cloudwatch_log_group.test.arn, ":*", "")}" - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + cloudwatch_log_group_arn = aws_cloudwatch_log_group.test.arn + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn } `, rName, rName) } @@ -822,9 +835,9 @@ resource "aws_datasync_task" "test" { func testAccAWSDataSyncTaskConfigDefaultSyncOptionsAtimeMtime(rName, atime, mtime string) string { return testAccAWSDataSyncTaskConfigDestinationLocationS3Base(rName) + testAccAWSDataSyncTaskConfigSourceLocationNfsBase(rName) + fmt.Sprintf(` resource "aws_datasync_task" "test" { - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn options { atime = %q @@ -837,9 +850,9 @@ resource "aws_datasync_task" "test" { func testAccAWSDataSyncTaskConfigDefaultSyncOptionsBytesPerSecond(rName string, bytesPerSecond int) string { return testAccAWSDataSyncTaskConfigDestinationLocationS3Base(rName) + testAccAWSDataSyncTaskConfigSourceLocationNfsBase(rName) + fmt.Sprintf(` resource "aws_datasync_task" "test" { - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn options { bytes_per_second = %d @@ -851,9 +864,9 @@ resource "aws_datasync_task" "test" { func testAccAWSDataSyncTaskConfigDefaultSyncOptionsGid(rName, gid string) string { return testAccAWSDataSyncTaskConfigDestinationLocationS3Base(rName) + testAccAWSDataSyncTaskConfigSourceLocationNfsBase(rName) + fmt.Sprintf(` resource "aws_datasync_task" "test" { - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn options { gid = %q @@ -865,9 +878,9 @@ resource "aws_datasync_task" "test" { func testAccAWSDataSyncTaskConfigDefaultSyncOptionsPosixPermissions(rName, posixPermissions string) string { return testAccAWSDataSyncTaskConfigDestinationLocationS3Base(rName) + testAccAWSDataSyncTaskConfigSourceLocationNfsBase(rName) + fmt.Sprintf(` resource "aws_datasync_task" "test" { - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn options { posix_permissions = %q @@ -879,9 +892,9 @@ resource "aws_datasync_task" "test" { func testAccAWSDataSyncTaskConfigDefaultSyncOptionsPreserveDeletedFiles(rName, preserveDeletedFiles string) string { return testAccAWSDataSyncTaskConfigDestinationLocationS3Base(rName) + testAccAWSDataSyncTaskConfigSourceLocationNfsBase(rName) + fmt.Sprintf(` resource "aws_datasync_task" "test" { - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn options { preserve_deleted_files = %q @@ -893,9 +906,9 @@ resource "aws_datasync_task" "test" { func testAccAWSDataSyncTaskConfigDefaultSyncOptionsPreserveDevices(rName, preserveDevices string) string { return testAccAWSDataSyncTaskConfigDestinationLocationS3Base(rName) + testAccAWSDataSyncTaskConfigSourceLocationNfsBase(rName) + fmt.Sprintf(` resource "aws_datasync_task" "test" { - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn options { preserve_devices = %q @@ -907,9 +920,9 @@ resource "aws_datasync_task" "test" { func testAccAWSDataSyncTaskConfigDefaultSyncOptionsUid(rName, uid string) string { return testAccAWSDataSyncTaskConfigDestinationLocationS3Base(rName) + testAccAWSDataSyncTaskConfigSourceLocationNfsBase(rName) + fmt.Sprintf(` resource "aws_datasync_task" "test" { - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn options { uid = %q @@ -921,9 +934,9 @@ resource "aws_datasync_task" "test" { func testAccAWSDataSyncTaskConfigDefaultSyncOptionsVerifyMode(rName, verifyMode string) string { return testAccAWSDataSyncTaskConfigDestinationLocationS3Base(rName) + testAccAWSDataSyncTaskConfigSourceLocationNfsBase(rName) + fmt.Sprintf(` resource "aws_datasync_task" "test" { - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn options { verify_mode = %q @@ -935,9 +948,9 @@ resource "aws_datasync_task" "test" { func testAccAWSDataSyncTaskConfigTags1(rName, key1, value1 string) string { return testAccAWSDataSyncTaskConfigDestinationLocationS3Base(rName) + testAccAWSDataSyncTaskConfigSourceLocationNfsBase(rName) + fmt.Sprintf(` resource "aws_datasync_task" "test" { - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn tags = { %q = %q @@ -949,9 +962,9 @@ resource "aws_datasync_task" "test" { func testAccAWSDataSyncTaskConfigTags2(rName, key1, value1, key2, value2 string) string { return testAccAWSDataSyncTaskConfigDestinationLocationS3Base(rName) + testAccAWSDataSyncTaskConfigSourceLocationNfsBase(rName) + fmt.Sprintf(` resource "aws_datasync_task" "test" { - destination_location_arn = "${aws_datasync_location_s3.destination.arn}" + destination_location_arn = aws_datasync_location_s3.destination.arn name = %q - source_location_arn = "${aws_datasync_location_nfs.source.arn}" + source_location_arn = aws_datasync_location_nfs.source.arn tags = { %q = %q diff --git a/aws/resource_aws_dax_cluster.go b/aws/resource_aws_dax_cluster.go index 63af0594cf9..069c417c910 100644 --- a/aws/resource_aws_dax_cluster.go +++ b/aws/resource_aws_dax_cluster.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dax" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_dax_cluster_test.go b/aws/resource_aws_dax_cluster_test.go index eb86c61d625..44f8969d238 100644 --- a/aws/resource_aws_dax_cluster_test.go +++ b/aws/resource_aws_dax_cluster_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dax" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -309,7 +309,7 @@ EOF } resource "aws_iam_role_policy" "test" { - role = "${aws_iam_role.test.id}" + role = aws_iam_role.test.id policy = < 0 { // We can only modify 20 parameters at a time, so walk them until @@ -276,7 +270,7 @@ func resourceAwsDbParameterGroupUpdate(d *schema.ResourceData, meta interface{}) } log.Printf("[DEBUG] Modify DB Parameter Group: %s", modifyOpts) - _, err = rdsconn.ModifyDBParameterGroup(&modifyOpts) + _, err := rdsconn.ModifyDBParameterGroup(&modifyOpts) if err != nil { return fmt.Errorf("Error modifying DB Parameter Group: %s", err) } @@ -284,10 +278,7 @@ func resourceAwsDbParameterGroupUpdate(d *schema.ResourceData, meta interface{}) } // Reset parameters that have been removed - resetParameters, err := expandParameters(os.Difference(ns).List()) - if err != nil { - return err - } + resetParameters := expandParameters(os.Difference(ns).List()) if len(resetParameters) > 0 { maxParams := 20 for resetParameters != nil { @@ -306,7 +297,7 @@ func resourceAwsDbParameterGroupUpdate(d *schema.ResourceData, meta interface{}) } log.Printf("[DEBUG] Reset DB Parameter Group: %s", resetOpts) - _, err = rdsconn.ResetDBParameterGroup(&resetOpts) + _, err := rdsconn.ResetDBParameterGroup(&resetOpts) if err != nil { return fmt.Errorf("Error resetting DB Parameter Group: %s", err) } diff --git a/aws/resource_aws_db_parameter_group_test.go b/aws/resource_aws_db_parameter_group_test.go index e5786f3c0e6..b93e6f25dfe 100644 --- a/aws/resource_aws_db_parameter_group_test.go +++ b/aws/resource_aws_db_parameter_group_test.go @@ -10,9 +10,10 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -79,10 +80,9 @@ func TestAccAWSDBParameterGroup_basic(t *testing.T) { groupName := fmt.Sprintf("parameter-group-test-terraform-%d", acctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSDBParameterGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDBParameterGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSDBParameterGroupConfig(groupName), @@ -91,12 +91,18 @@ func TestAccAWSDBParameterGroup_basic(t *testing.T) { testAccCheckAWSDBParameterGroupAttributes(&v, groupName), resource.TestCheckResourceAttr(resourceName, "name", groupName), resource.TestCheckResourceAttr(resourceName, "family", "mysql5.6"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.name", "character_set_results"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.name", "character_set_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.name", "character_set_client"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.value", "utf8"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_results", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_server", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_client", + "value": "utf8", + }), testAccMatchResourceAttrRegionalARN(resourceName, "arn", "rds", regexp.MustCompile(fmt.Sprintf("pg:%s$", groupName))), ), }, @@ -112,16 +118,26 @@ func TestAccAWSDBParameterGroup_basic(t *testing.T) { testAccCheckAWSDBParameterGroupAttributes(&v, groupName), resource.TestCheckResourceAttr(resourceName, "name", groupName), resource.TestCheckResourceAttr(resourceName, "family", "mysql5.6"), - resource.TestCheckResourceAttr(resourceName, "parameter.1706463059.name", "collation_connection"), - resource.TestCheckResourceAttr(resourceName, "parameter.1706463059.value", "utf8_unicode_ci"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.name", "character_set_results"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.name", "character_set_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2475805061.name", "collation_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.2475805061.value", "utf8_unicode_ci"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.name", "character_set_client"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.value", "utf8"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "collation_connection", + "value": "utf8_unicode_ci", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_results", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_server", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "collation_server", + "value": "utf8_unicode_ci", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_client", + "value": "utf8", + }), testAccMatchResourceAttrRegionalARN(resourceName, "arn", "rds", regexp.MustCompile(fmt.Sprintf("pg:%s$", groupName))), ), }, @@ -132,8 +148,19 @@ func TestAccAWSDBParameterGroup_basic(t *testing.T) { testAccCheckAWSDBParameterGroupAttributes(&v, groupName), testAccCheckAWSDBParameterNotUserDefined(resourceName, "collation_connection"), testAccCheckAWSDBParameterNotUserDefined(resourceName, "collation_server"), - resource.TestCheckNoResourceAttr(resourceName, "parameter.2475805061.value"), - resource.TestCheckNoResourceAttr(resourceName, "parameter.1706463059.value"), + resource.TestCheckResourceAttr(resourceName, "parameter.#", "3"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_results", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_server", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_client", + "value": "utf8", + }), ), }, }, @@ -146,10 +173,9 @@ func TestAccAWSDBParameterGroup_limit(t *testing.T) { groupName := fmt.Sprintf("parameter-group-test-terraform-%d", acctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSDBParameterGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDBParameterGroupDestroy, Steps: []resource.TestStep{ { Config: createAwsDbParameterGroupsExceedDefaultAwsLimit(groupName), @@ -159,88 +185,170 @@ func TestAccAWSDBParameterGroup_limit(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", groupName), resource.TestCheckResourceAttr(resourceName, "family", "mysql5.6"), resource.TestCheckResourceAttr(resourceName, "description", "RDS default parameter group: Exceed default AWS parameter group limit of twenty"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.name", "character_set_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.name", "character_set_client"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.1680942586.name", "collation_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.1680942586.value", "utf8_general_ci"), - resource.TestCheckResourceAttr(resourceName, "parameter.2450940716.name", "collation_connection"), - resource.TestCheckResourceAttr(resourceName, "parameter.2450940716.value", "utf8_general_ci"), - resource.TestCheckResourceAttr(resourceName, "parameter.242489837.name", "join_buffer_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.242489837.value", "16777216"), - resource.TestCheckResourceAttr(resourceName, "parameter.2026669454.name", "key_buffer_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.2026669454.value", "67108864"), - resource.TestCheckResourceAttr(resourceName, "parameter.2705275319.name", "max_connections"), - resource.TestCheckResourceAttr(resourceName, "parameter.2705275319.value", "3200"), - resource.TestCheckResourceAttr(resourceName, "parameter.3512697936.name", "max_heap_table_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.3512697936.value", "67108864"), - resource.TestCheckResourceAttr(resourceName, "parameter.780730667.name", "performance_schema"), - resource.TestCheckResourceAttr(resourceName, "parameter.780730667.value", "1"), - resource.TestCheckResourceAttr(resourceName, "parameter.2020346918.name", "performance_schema_users_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.2020346918.value", "1048576"), - resource.TestCheckResourceAttr(resourceName, "parameter.1460834103.name", "query_cache_limit"), - resource.TestCheckResourceAttr(resourceName, "parameter.1460834103.value", "2097152"), - resource.TestCheckResourceAttr(resourceName, "parameter.484865451.name", "query_cache_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.484865451.value", "67108864"), - resource.TestCheckResourceAttr(resourceName, "parameter.255276438.name", "sort_buffer_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.255276438.value", "16777216"), - resource.TestCheckResourceAttr(resourceName, "parameter.2981725119.name", "table_open_cache"), - resource.TestCheckResourceAttr(resourceName, "parameter.2981725119.value", "4096"), - resource.TestCheckResourceAttr(resourceName, "parameter.2703661820.name", "tmp_table_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.2703661820.value", "67108864"), - resource.TestCheckResourceAttr(resourceName, "parameter.2386583229.name", "binlog_cache_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.2386583229.value", "131072"), - resource.TestCheckResourceAttr(resourceName, "parameter.4012389720.name", "innodb_flush_log_at_trx_commit"), - resource.TestCheckResourceAttr(resourceName, "parameter.4012389720.value", "0"), - resource.TestCheckResourceAttr(resourceName, "parameter.2688783017.name", "innodb_open_files"), - resource.TestCheckResourceAttr(resourceName, "parameter.2688783017.value", "4000"), - resource.TestCheckResourceAttr(resourceName, "parameter.782983977.name", "innodb_read_io_threads"), - resource.TestCheckResourceAttr(resourceName, "parameter.782983977.value", "64"), - resource.TestCheckResourceAttr(resourceName, "parameter.2809980413.name", "innodb_thread_concurrency"), - resource.TestCheckResourceAttr(resourceName, "parameter.2809980413.value", "0"), - resource.TestCheckResourceAttr(resourceName, "parameter.3599115250.name", "innodb_write_io_threads"), - resource.TestCheckResourceAttr(resourceName, "parameter.3599115250.value", "64"), - resource.TestCheckResourceAttr(resourceName, "parameter.2557156277.name", "character_set_connection"), - resource.TestCheckResourceAttr(resourceName, "parameter.2557156277.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2475346812.name", "character_set_database"), - resource.TestCheckResourceAttr(resourceName, "parameter.2475346812.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.1986528518.name", "character_set_filesystem"), - resource.TestCheckResourceAttr(resourceName, "parameter.1986528518.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.name", "character_set_results"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.1937131004.name", "event_scheduler"), - resource.TestCheckResourceAttr(resourceName, "parameter.1937131004.value", "ON"), - resource.TestCheckResourceAttr(resourceName, "parameter.3437079877.name", "innodb_buffer_pool_dump_at_shutdown"), - resource.TestCheckResourceAttr(resourceName, "parameter.3437079877.value", "1"), - resource.TestCheckResourceAttr(resourceName, "parameter.1092112861.name", "innodb_file_format"), - resource.TestCheckResourceAttr(resourceName, "parameter.1092112861.value", "barracuda"), - resource.TestCheckResourceAttr(resourceName, "parameter.615571931.name", "innodb_io_capacity"), - resource.TestCheckResourceAttr(resourceName, "parameter.615571931.value", "2000"), - resource.TestCheckResourceAttr(resourceName, "parameter.1065962799.name", "innodb_io_capacity_max"), - resource.TestCheckResourceAttr(resourceName, "parameter.1065962799.value", "3000"), - resource.TestCheckResourceAttr(resourceName, "parameter.1411161182.name", "innodb_lock_wait_timeout"), - resource.TestCheckResourceAttr(resourceName, "parameter.1411161182.value", "120"), - resource.TestCheckResourceAttr(resourceName, "parameter.3133315879.name", "innodb_max_dirty_pages_pct"), - resource.TestCheckResourceAttr(resourceName, "parameter.3133315879.value", "90"), - resource.TestCheckResourceAttr(resourceName, "parameter.950177639.name", "log_bin_trust_function_creators"), - resource.TestCheckResourceAttr(resourceName, "parameter.950177639.value", "1"), - resource.TestCheckResourceAttr(resourceName, "parameter.591700516.name", "log_warnings"), - resource.TestCheckResourceAttr(resourceName, "parameter.591700516.value", "2"), - resource.TestCheckResourceAttr(resourceName, "parameter.1918306725.name", "log_output"), - resource.TestCheckResourceAttr(resourceName, "parameter.1918306725.value", "FILE"), - resource.TestCheckResourceAttr(resourceName, "parameter.386204433.name", "max_allowed_packet"), - resource.TestCheckResourceAttr(resourceName, "parameter.386204433.value", "1073741824"), - resource.TestCheckResourceAttr(resourceName, "parameter.1700901269.name", "max_connect_errors"), - resource.TestCheckResourceAttr(resourceName, "parameter.1700901269.value", "100"), - resource.TestCheckResourceAttr(resourceName, "parameter.2839701698.name", "query_cache_min_res_unit"), - resource.TestCheckResourceAttr(resourceName, "parameter.2839701698.value", "512"), - resource.TestCheckResourceAttr(resourceName, "parameter.427634017.name", "slow_query_log"), - resource.TestCheckResourceAttr(resourceName, "parameter.427634017.value", "1"), - resource.TestCheckResourceAttr(resourceName, "parameter.881816039.name", "sync_binlog"), - resource.TestCheckResourceAttr(resourceName, "parameter.881816039.value", "0"), - resource.TestCheckResourceAttr(resourceName, "parameter.748684209.name", "tx_isolation"), - resource.TestCheckResourceAttr(resourceName, "parameter.748684209.value", "REPEATABLE-READ"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_server", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_client", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "collation_server", + "value": "utf8_general_ci", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "collation_connection", + "value": "utf8_general_ci", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "join_buffer_size", + "value": "16777216", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "key_buffer_size", + "value": "67108864", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "max_connections", + "value": "3200", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "max_heap_table_size", + "value": "67108864", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "performance_schema", + "value": "1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "performance_schema_users_size", + "value": "1048576", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "query_cache_limit", + "value": "2097152", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "query_cache_size", + "value": "67108864", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "sort_buffer_size", + "value": "16777216", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "table_open_cache", + "value": "4096", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "tmp_table_size", + "value": "67108864", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "binlog_cache_size", + "value": "131072", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_flush_log_at_trx_commit", + "value": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_open_files", + "value": "4000", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_read_io_threads", + "value": "64", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_thread_concurrency", + "value": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_write_io_threads", + "value": "64", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_connection", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_database", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_filesystem", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_results", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "event_scheduler", + "value": "ON", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_buffer_pool_dump_at_shutdown", + "value": "1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_file_format", + "value": "barracuda", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_io_capacity", + "value": "2000", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_io_capacity_max", + "value": "3000", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_lock_wait_timeout", + "value": "120", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_max_dirty_pages_pct", + "value": "90", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "log_bin_trust_function_creators", + "value": "1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "log_warnings", + "value": "2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "log_output", + "value": "FILE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "max_allowed_packet", + "value": "1073741824", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "max_connect_errors", + "value": "100", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "query_cache_min_res_unit", + "value": "512", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "slow_query_log", + "value": "1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "sync_binlog", + "value": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "tx_isolation", + "value": "REPEATABLE-READ", + }), ), }, { @@ -256,88 +364,170 @@ func TestAccAWSDBParameterGroup_limit(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", groupName), resource.TestCheckResourceAttr(resourceName, "family", "mysql5.6"), resource.TestCheckResourceAttr(resourceName, "description", "Updated RDS default parameter group: Exceed default AWS parameter group limit of twenty"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.name", "character_set_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.name", "character_set_client"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.1680942586.name", "collation_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.1680942586.value", "utf8_general_ci"), - resource.TestCheckResourceAttr(resourceName, "parameter.2450940716.name", "collation_connection"), - resource.TestCheckResourceAttr(resourceName, "parameter.2450940716.value", "utf8_general_ci"), - resource.TestCheckResourceAttr(resourceName, "parameter.242489837.name", "join_buffer_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.242489837.value", "16777216"), - resource.TestCheckResourceAttr(resourceName, "parameter.2026669454.name", "key_buffer_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.2026669454.value", "67108864"), - resource.TestCheckResourceAttr(resourceName, "parameter.2705275319.name", "max_connections"), - resource.TestCheckResourceAttr(resourceName, "parameter.2705275319.value", "3200"), - resource.TestCheckResourceAttr(resourceName, "parameter.3512697936.name", "max_heap_table_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.3512697936.value", "67108864"), - resource.TestCheckResourceAttr(resourceName, "parameter.780730667.name", "performance_schema"), - resource.TestCheckResourceAttr(resourceName, "parameter.780730667.value", "1"), - resource.TestCheckResourceAttr(resourceName, "parameter.2020346918.name", "performance_schema_users_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.2020346918.value", "1048576"), - resource.TestCheckResourceAttr(resourceName, "parameter.1460834103.name", "query_cache_limit"), - resource.TestCheckResourceAttr(resourceName, "parameter.1460834103.value", "2097152"), - resource.TestCheckResourceAttr(resourceName, "parameter.484865451.name", "query_cache_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.484865451.value", "67108864"), - resource.TestCheckResourceAttr(resourceName, "parameter.255276438.name", "sort_buffer_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.255276438.value", "16777216"), - resource.TestCheckResourceAttr(resourceName, "parameter.2981725119.name", "table_open_cache"), - resource.TestCheckResourceAttr(resourceName, "parameter.2981725119.value", "4096"), - resource.TestCheckResourceAttr(resourceName, "parameter.2703661820.name", "tmp_table_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.2703661820.value", "67108864"), - resource.TestCheckResourceAttr(resourceName, "parameter.2386583229.name", "binlog_cache_size"), - resource.TestCheckResourceAttr(resourceName, "parameter.2386583229.value", "131072"), - resource.TestCheckResourceAttr(resourceName, "parameter.4012389720.name", "innodb_flush_log_at_trx_commit"), - resource.TestCheckResourceAttr(resourceName, "parameter.4012389720.value", "0"), - resource.TestCheckResourceAttr(resourceName, "parameter.2688783017.name", "innodb_open_files"), - resource.TestCheckResourceAttr(resourceName, "parameter.2688783017.value", "4000"), - resource.TestCheckResourceAttr(resourceName, "parameter.782983977.name", "innodb_read_io_threads"), - resource.TestCheckResourceAttr(resourceName, "parameter.782983977.value", "64"), - resource.TestCheckResourceAttr(resourceName, "parameter.2809980413.name", "innodb_thread_concurrency"), - resource.TestCheckResourceAttr(resourceName, "parameter.2809980413.value", "0"), - resource.TestCheckResourceAttr(resourceName, "parameter.3599115250.name", "innodb_write_io_threads"), - resource.TestCheckResourceAttr(resourceName, "parameter.3599115250.value", "64"), - resource.TestCheckResourceAttr(resourceName, "parameter.2557156277.name", "character_set_connection"), - resource.TestCheckResourceAttr(resourceName, "parameter.2557156277.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2475346812.name", "character_set_database"), - resource.TestCheckResourceAttr(resourceName, "parameter.2475346812.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.1986528518.name", "character_set_filesystem"), - resource.TestCheckResourceAttr(resourceName, "parameter.1986528518.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.name", "character_set_results"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.1937131004.name", "event_scheduler"), - resource.TestCheckResourceAttr(resourceName, "parameter.1937131004.value", "ON"), - resource.TestCheckResourceAttr(resourceName, "parameter.3437079877.name", "innodb_buffer_pool_dump_at_shutdown"), - resource.TestCheckResourceAttr(resourceName, "parameter.3437079877.value", "1"), - resource.TestCheckResourceAttr(resourceName, "parameter.1092112861.name", "innodb_file_format"), - resource.TestCheckResourceAttr(resourceName, "parameter.1092112861.value", "barracuda"), - resource.TestCheckResourceAttr(resourceName, "parameter.615571931.name", "innodb_io_capacity"), - resource.TestCheckResourceAttr(resourceName, "parameter.615571931.value", "2000"), - resource.TestCheckResourceAttr(resourceName, "parameter.1065962799.name", "innodb_io_capacity_max"), - resource.TestCheckResourceAttr(resourceName, "parameter.1065962799.value", "3000"), - resource.TestCheckResourceAttr(resourceName, "parameter.1411161182.name", "innodb_lock_wait_timeout"), - resource.TestCheckResourceAttr(resourceName, "parameter.1411161182.value", "120"), - resource.TestCheckResourceAttr(resourceName, "parameter.3133315879.name", "innodb_max_dirty_pages_pct"), - resource.TestCheckResourceAttr(resourceName, "parameter.3133315879.value", "90"), - resource.TestCheckResourceAttr(resourceName, "parameter.950177639.name", "log_bin_trust_function_creators"), - resource.TestCheckResourceAttr(resourceName, "parameter.950177639.value", "1"), - resource.TestCheckResourceAttr(resourceName, "parameter.591700516.name", "log_warnings"), - resource.TestCheckResourceAttr(resourceName, "parameter.591700516.value", "2"), - resource.TestCheckResourceAttr(resourceName, "parameter.1918306725.name", "log_output"), - resource.TestCheckResourceAttr(resourceName, "parameter.1918306725.value", "FILE"), - resource.TestCheckResourceAttr(resourceName, "parameter.386204433.name", "max_allowed_packet"), - resource.TestCheckResourceAttr(resourceName, "parameter.386204433.value", "1073741824"), - resource.TestCheckResourceAttr(resourceName, "parameter.1700901269.name", "max_connect_errors"), - resource.TestCheckResourceAttr(resourceName, "parameter.1700901269.value", "100"), - resource.TestCheckResourceAttr(resourceName, "parameter.2839701698.name", "query_cache_min_res_unit"), - resource.TestCheckResourceAttr(resourceName, "parameter.2839701698.value", "512"), - resource.TestCheckResourceAttr(resourceName, "parameter.427634017.name", "slow_query_log"), - resource.TestCheckResourceAttr(resourceName, "parameter.427634017.value", "1"), - resource.TestCheckResourceAttr(resourceName, "parameter.881816039.name", "sync_binlog"), - resource.TestCheckResourceAttr(resourceName, "parameter.881816039.value", "0"), - resource.TestCheckResourceAttr(resourceName, "parameter.748684209.name", "tx_isolation"), - resource.TestCheckResourceAttr(resourceName, "parameter.748684209.value", "REPEATABLE-READ"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_server", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_client", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "collation_server", + "value": "utf8_general_ci", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "collation_connection", + "value": "utf8_general_ci", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "join_buffer_size", + "value": "16777216", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "key_buffer_size", + "value": "67108864", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "max_connections", + "value": "3200", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "max_heap_table_size", + "value": "67108864", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "performance_schema", + "value": "1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "performance_schema_users_size", + "value": "1048576", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "query_cache_limit", + "value": "2097152", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "query_cache_size", + "value": "67108864", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "sort_buffer_size", + "value": "16777216", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "table_open_cache", + "value": "4096", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "tmp_table_size", + "value": "67108864", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "binlog_cache_size", + "value": "131072", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_flush_log_at_trx_commit", + "value": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_open_files", + "value": "4000", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_read_io_threads", + "value": "64", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_thread_concurrency", + "value": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_write_io_threads", + "value": "64", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_connection", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_database", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_filesystem", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_results", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "event_scheduler", + "value": "ON", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_buffer_pool_dump_at_shutdown", + "value": "1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_file_format", + "value": "barracuda", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_io_capacity", + "value": "2000", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_io_capacity_max", + "value": "3000", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_lock_wait_timeout", + "value": "120", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "innodb_max_dirty_pages_pct", + "value": "90", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "log_bin_trust_function_creators", + "value": "1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "log_warnings", + "value": "2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "log_output", + "value": "FILE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "max_allowed_packet", + "value": "1073741824", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "max_connect_errors", + "value": "100", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "query_cache_min_res_unit", + "value": "512", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "slow_query_log", + "value": "1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "sync_binlog", + "value": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "tx_isolation", + "value": "REPEATABLE-READ", + }), ), }, }, @@ -409,10 +599,9 @@ func TestAccAWSDBParameterGroup_withApplyMethod(t *testing.T) { groupName := fmt.Sprintf("parameter-group-test-terraform-%d", acctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSDBParameterGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDBParameterGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSDBParameterGroupConfigWithApplyMethod(groupName), @@ -422,12 +611,16 @@ func TestAccAWSDBParameterGroup_withApplyMethod(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", groupName), resource.TestCheckResourceAttr(resourceName, "family", "mysql5.6"), resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.name", "character_set_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.apply_method", "immediate"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.name", "character_set_client"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.apply_method", "pending-reboot"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_server", + "value": "utf8", + "apply_method": "immediate", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_client", + "value": "utf8", + "apply_method": "pending-reboot", + }), ), }, { @@ -683,8 +876,8 @@ resource "aws_db_parameter_group" "test" { func testAccAWSDBParameterGroupAddParametersConfig(n string) string { return fmt.Sprintf(` resource "aws_db_parameter_group" "test" { - name = "%s" - family = "mysql5.6" + name = "%s" + family = "mysql5.6" parameter { name = "character_set_server" @@ -1181,23 +1374,23 @@ resource "aws_db_parameter_group" "test" { const testAccDBParameterGroupConfig_namePrefix = ` resource "aws_db_parameter_group" "test" { - name_prefix = "tf-test-" - family = "mysql5.6" + name_prefix = "tf-test-" + family = "mysql5.6" - parameter { - name = "sync_binlog" - value = 0 - } + parameter { + name = "sync_binlog" + value = 0 + } } ` const testAccDBParameterGroupConfig_generatedName = ` resource "aws_db_parameter_group" "test" { - family = "mysql5.6" + family = "mysql5.6" - parameter { - name = "sync_binlog" - value = 0 - } + parameter { + name = "sync_binlog" + value = 0 + } } ` diff --git a/aws/resource_aws_db_security_group.go b/aws/resource_aws_db_security_group.go index 218490e86e5..9243c2786db 100644 --- a/aws/resource_aws_db_security_group.go +++ b/aws/resource_aws_db_security_group.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_db_security_group_test.go b/aws/resource_aws_db_security_group_test.go index 1ac04f865b1..d82871b1e5b 100644 --- a/aws/resource_aws_db_security_group_test.go +++ b/aws/resource_aws_db_security_group_test.go @@ -9,9 +9,10 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSDBSecurityGroup_basic(t *testing.T) { @@ -24,10 +25,9 @@ func TestAccAWSDBSecurityGroup_basic(t *testing.T) { rName := fmt.Sprintf("tf-acc-%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccEC2ClassicPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSDBSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccEC2ClassicPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDBSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSDBSecurityGroupConfig(rName), @@ -37,7 +37,9 @@ func TestAccAWSDBSecurityGroup_basic(t *testing.T) { testAccMatchResourceAttrRegionalARN(resourceName, "arn", "rds", regexp.MustCompile(fmt.Sprintf("secgrp:%s$", rName))), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), - resource.TestCheckResourceAttr(resourceName, "ingress.3363517775.cidr", "10.0.0.1/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr": "10.0.0.1/24", + }), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), ), diff --git a/aws/resource_aws_db_snapshot.go b/aws/resource_aws_db_snapshot.go index ac0f8f4d61e..1e5255216e2 100644 --- a/aws/resource_aws_db_snapshot.go +++ b/aws/resource_aws_db_snapshot.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_db_snapshot_test.go b/aws/resource_aws_db_snapshot_test.go index 8bdb3eab40f..c80d1393c79 100644 --- a/aws/resource_aws_db_snapshot_test.go +++ b/aws/resource_aws_db_snapshot_test.go @@ -4,20 +4,24 @@ import ( "fmt" "log" "regexp" + "strings" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { resource.AddTestSweepers("aws_db_snapshot", &resource.Sweeper{ Name: "aws_db_snapshot", F: testSweepDbSnapshots, + Dependencies: []string{ + "aws_db_instance", + }, }) } @@ -47,6 +51,11 @@ func testSweepDbSnapshots(region string) error { DBSnapshotIdentifier: dbSnapshot.DBSnapshotIdentifier, } + if strings.HasPrefix(id, "rds:") { + log.Printf("[INFO] Skipping RDS Automated DB Snapshot: %s", id) + continue + } + log.Printf("[INFO] Deleting RDS DB Snapshot: %s", id) _, err := conn.DeleteDBSnapshot(input) @@ -263,7 +272,7 @@ resource "aws_db_instance" "test" { func testAccAwsDbSnapshotConfig(rName string) string { return testAccAwsDbSnapshotConfigBase(rName) + fmt.Sprintf(` resource "aws_db_snapshot" "test" { - db_instance_identifier = "${aws_db_instance.test.id}" + db_instance_identifier = aws_db_instance.test.id db_snapshot_identifier = %[1]q } `, rName) @@ -272,7 +281,7 @@ resource "aws_db_snapshot" "test" { func testAccAwsDbSnapshotConfigTags1(rName, tag1Key, tag1Value string) string { return testAccAwsDbSnapshotConfigBase(rName) + fmt.Sprintf(` resource "aws_db_snapshot" "test" { - db_instance_identifier = "${aws_db_instance.test.id}" + db_instance_identifier = aws_db_instance.test.id db_snapshot_identifier = %[1]q tags = { @@ -285,7 +294,7 @@ resource "aws_db_snapshot" "test" { func testAccAwsDbSnapshotConfigTags2(rName, tag1Key, tag1Value, tag2Key, tag2Value string) string { return testAccAwsDbSnapshotConfigBase(rName) + fmt.Sprintf(` resource "aws_db_snapshot" "test" { - db_instance_identifier = "${aws_db_instance.test.id}" + db_instance_identifier = aws_db_instance.test.id db_snapshot_identifier = %[1]q tags = { diff --git a/aws/resource_aws_db_subnet_group.go b/aws/resource_aws_db_subnet_group.go index 548e4a42a27..911a90ae03f 100644 --- a/aws/resource_aws_db_subnet_group.go +++ b/aws/resource_aws_db_subnet_group.go @@ -9,8 +9,8 @@ import ( "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-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -167,7 +167,7 @@ func resourceAwsDbSubnetGroupRead(d *schema.ResourceData, meta interface{}) erro func resourceAwsDbSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).rdsconn - if d.HasChange("subnet_ids") || d.HasChange("description") { + if d.HasChanges("subnet_ids", "description") { _, n := d.GetChange("subnet_ids") if n == nil { n = new(schema.Set) diff --git a/aws/resource_aws_db_subnet_group_test.go b/aws/resource_aws_db_subnet_group_test.go index a53f4baca50..88480287763 100644 --- a/aws/resource_aws_db_subnet_group_test.go +++ b/aws/resource_aws_db_subnet_group_test.go @@ -6,9 +6,9 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" @@ -283,8 +283,8 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.1.1.0/24" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - vpc_id = "${aws_vpc.test.id}" + availability_zone = data.aws_availability_zones.available.names[0] + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-db-subnet-group-1" @@ -293,8 +293,8 @@ resource "aws_subnet" "test" { resource "aws_subnet" "bar" { cidr_block = "10.1.2.0/24" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - vpc_id = "${aws_vpc.test.id}" + availability_zone = data.aws_availability_zones.available.names[1] + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-db-subnet-group-2" @@ -303,7 +303,7 @@ resource "aws_subnet" "bar" { resource "aws_db_subnet_group" "test" { name = "%s" - subnet_ids = ["${aws_subnet.test.id}", "${aws_subnet.bar.id}"] + subnet_ids = [aws_subnet.test.id, aws_subnet.bar.id] tags = { Name = "tf-dbsubnet-group-test" @@ -333,8 +333,8 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.1.1.0/24" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - vpc_id = "${aws_vpc.test.id}" + availability_zone = data.aws_availability_zones.available.names[0] + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-db-subnet-group-1" @@ -343,8 +343,8 @@ resource "aws_subnet" "test" { resource "aws_subnet" "bar" { cidr_block = "10.1.2.0/24" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - vpc_id = "${aws_vpc.test.id}" + availability_zone = data.aws_availability_zones.available.names[1] + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-db-subnet-group-2" @@ -354,7 +354,7 @@ resource "aws_subnet" "bar" { resource "aws_db_subnet_group" "test" { name = "%s" description = "test description updated" - subnet_ids = ["${aws_subnet.test.id}", "${aws_subnet.bar.id}"] + subnet_ids = [aws_subnet.test.id, aws_subnet.bar.id] tags = { Name = "tf-dbsubnet-group-test" @@ -374,33 +374,33 @@ data "aws_availability_zones" "available" { } resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - tags = { - Name = "terraform-testacc-db-subnet-group-name-prefix" - } + cidr_block = "10.1.0.0/16" + tags = { + Name = "terraform-testacc-db-subnet-group-name-prefix" + } } resource "aws_subnet" "a" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "10.1.1.0/24" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - tags = { - Name = "tf-acc-db-subnet-group-name-prefix-a" - } + vpc_id = aws_vpc.test.id + cidr_block = "10.1.1.0/24" + availability_zone = data.aws_availability_zones.available.names[0] + tags = { + Name = "tf-acc-db-subnet-group-name-prefix-a" + } } resource "aws_subnet" "b" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "10.1.2.0/24" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - tags = { - Name = "tf-acc-db-subnet-group-name-prefix-b" - } + vpc_id = aws_vpc.test.id + cidr_block = "10.1.2.0/24" + availability_zone = data.aws_availability_zones.available.names[1] + tags = { + Name = "tf-acc-db-subnet-group-name-prefix-b" + } } resource "aws_db_subnet_group" "test" { - name_prefix = "tf_test-" - subnet_ids = ["${aws_subnet.a.id}", "${aws_subnet.b.id}"] + name_prefix = "tf_test-" + subnet_ids = [aws_subnet.a.id, aws_subnet.b.id] }` const testAccDBSubnetGroupConfig_generatedName = ` @@ -414,32 +414,32 @@ data "aws_availability_zones" "available" { } resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - tags = { - Name = "terraform-testacc-db-subnet-group-generated-name" - } + cidr_block = "10.1.0.0/16" + tags = { + Name = "terraform-testacc-db-subnet-group-generated-name" + } } resource "aws_subnet" "a" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "10.1.1.0/24" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - tags = { - Name = "tf-acc-db-subnet-group-generated-name-a" - } + vpc_id = aws_vpc.test.id + cidr_block = "10.1.1.0/24" + availability_zone = data.aws_availability_zones.available.names[0] + tags = { + Name = "tf-acc-db-subnet-group-generated-name-a" + } } resource "aws_subnet" "b" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "10.1.2.0/24" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - tags = { - Name = "tf-acc-db-subnet-group-generated-name-a" - } + vpc_id = aws_vpc.test.id + cidr_block = "10.1.2.0/24" + availability_zone = data.aws_availability_zones.available.names[1] + tags = { + Name = "tf-acc-db-subnet-group-generated-name-a" + } } resource "aws_db_subnet_group" "test" { - subnet_ids = ["${aws_subnet.a.id}", "${aws_subnet.b.id}"] + subnet_ids = [aws_subnet.a.id, aws_subnet.b.id] }` const testAccDBSubnetGroupConfig_withUnderscoresAndPeriodsAndSpaces = ` @@ -453,45 +453,45 @@ data "aws_availability_zones" "available" { } resource "aws_vpc" "main" { - cidr_block = "192.168.0.0/16" - tags = { - Name = "terraform-testacc-db-subnet-group-w-underscores-etc" - } + cidr_block = "192.168.0.0/16" + tags = { + Name = "terraform-testacc-db-subnet-group-w-underscores-etc" + } } resource "aws_subnet" "frontend" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "192.168.1.0/24" + vpc_id = aws_vpc.main.id + availability_zone = data.aws_availability_zones.available.names[0] + cidr_block = "192.168.1.0/24" tags = { Name = "tf-acc-db-subnet-group-w-underscores-etc-front" } } resource "aws_subnet" "backend" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - cidr_block = "192.168.2.0/24" + vpc_id = aws_vpc.main.id + availability_zone = data.aws_availability_zones.available.names[1] + cidr_block = "192.168.2.0/24" tags = { Name = "tf-acc-db-subnet-group-w-underscores-etc-back" } } resource "aws_db_subnet_group" "underscores" { - name = "with_underscores" - description = "Our main group of subnets" - subnet_ids = ["${aws_subnet.frontend.id}", "${aws_subnet.backend.id}"] + name = "with_underscores" + description = "Our main group of subnets" + subnet_ids = [aws_subnet.frontend.id, aws_subnet.backend.id] } resource "aws_db_subnet_group" "periods" { - name = "with.periods" - description = "Our main group of subnets" - subnet_ids = ["${aws_subnet.frontend.id}", "${aws_subnet.backend.id}"] + name = "with.periods" + description = "Our main group of subnets" + subnet_ids = [aws_subnet.frontend.id, aws_subnet.backend.id] } resource "aws_db_subnet_group" "spaces" { - name = "with spaces" - description = "Our main group of subnets" - subnet_ids = ["${aws_subnet.frontend.id}", "${aws_subnet.backend.id}"] + name = "with spaces" + description = "Our main group of subnets" + subnet_ids = [aws_subnet.frontend.id, aws_subnet.backend.id] } ` diff --git a/aws/resource_aws_default_network_acl.go b/aws/resource_aws_default_network_acl.go index ea3ffad7196..a0ad9d815c5 100644 --- a/aws/resource_aws_default_network_acl.go +++ b/aws/resource_aws_default_network_acl.go @@ -6,7 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -34,6 +35,10 @@ func resourceAwsDefaultNetworkAcl() *schema.Resource { }, Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, "vpc_id": { Type: schema.TypeString, Computed: true, @@ -53,7 +58,6 @@ func resourceAwsDefaultNetworkAcl() *schema.Resource { Type: schema.TypeSet, Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, // We want explicit management of Rules here, so we do not allow them to be // computed. Instead, an empty config will enforce just that; removal of the @@ -64,20 +68,27 @@ func resourceAwsDefaultNetworkAcl() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "from_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IsPortNumberOrZero, }, "to_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IsPortNumberOrZero, }, "rule_no": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, 32766), }, "action": { Type: schema.TypeString, Required: true, + ValidateFunc: validation.StringInSlice([]string{ + ec2.RuleActionAllow, + ec2.RuleActionDeny, + }, true), }, "protocol": { Type: schema.TypeString, @@ -86,10 +97,18 @@ func resourceAwsDefaultNetworkAcl() *schema.Resource { "cidr_block": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validation.IsCIDR, + ), }, "ipv6_cidr_block": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validation.IsCIDR, + ), }, "icmp_type": { Type: schema.TypeInt, @@ -109,20 +128,27 @@ func resourceAwsDefaultNetworkAcl() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "from_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IsPortNumberOrZero, }, "to_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IsPortNumberOrZero, }, "rule_no": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, 32766), }, "action": { Type: schema.TypeString, Required: true, + ValidateFunc: validation.StringInSlice([]string{ + ec2.RuleActionAllow, + ec2.RuleActionDeny, + }, true), }, "protocol": { Type: schema.TypeString, @@ -131,10 +157,18 @@ func resourceAwsDefaultNetworkAcl() *schema.Resource { "cidr_block": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validation.IsCIDR, + ), }, "ipv6_cidr_block": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validation.IsCIDR, + ), }, "icmp_type": { Type: schema.TypeInt, @@ -277,14 +311,14 @@ func revokeAllNetworkACLEntries(netaclId string, meta interface{}) error { for _, e := range networkAcl.Entries { // Skip the default rules added by AWS. They can be neither // configured or deleted by users. See http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html#default-network-acl - if *e.RuleNumber == awsDefaultAclRuleNumberIpv4 || - *e.RuleNumber == awsDefaultAclRuleNumberIpv6 { + if aws.Int64Value(e.RuleNumber) == awsDefaultAclRuleNumberIpv4 || + aws.Int64Value(e.RuleNumber) == awsDefaultAclRuleNumberIpv6 { continue } // track if this is an egress or ingress rule, for logging purposes rt := "ingress" - if *e.Egress { + if aws.BoolValue(e.Egress) { rt = "egress" } diff --git a/aws/resource_aws_default_network_acl_test.go b/aws/resource_aws_default_network_acl_test.go index 9a8068bb766..faf3790a45a 100644 --- a/aws/resource_aws_default_network_acl_test.go +++ b/aws/resource_aws_default_network_acl_test.go @@ -2,12 +2,13 @@ package aws import ( "fmt" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) var defaultEgressAcl = &ec2.NetworkAclEntry{ @@ -27,6 +28,7 @@ var ipv6IngressAcl = &ec2.NetworkAclEntry{ func TestAccAWSDefaultNetworkAcl_basic(t *testing.T) { var networkAcl ec2.NetworkAcl + resourceName := "aws_default_network_acl.default" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -36,13 +38,14 @@ func TestAccAWSDefaultNetworkAcl_basic(t *testing.T) { { Config: testAccAWSDefaultNetworkConfig_basic, Check: resource.ComposeTestCheckFunc( - testAccGetAWSDefaultNetworkAcl("aws_default_network_acl.default", &networkAcl), + testAccGetAWSDefaultNetworkAcl(resourceName, &networkAcl), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`network-acl/acl-.+`)), testAccCheckAWSDefaultACLAttributes(&networkAcl, []*ec2.NetworkAclEntry{}, 0, 2), - testAccCheckResourceAttrAccountID("aws_default_network_acl.default", "owner_id"), + testAccCheckResourceAttrAccountID(resourceName, "owner_id"), ), }, { - ResourceName: "aws_default_network_acl.default", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -52,6 +55,7 @@ func TestAccAWSDefaultNetworkAcl_basic(t *testing.T) { func TestAccAWSDefaultNetworkAcl_basicIpv6Vpc(t *testing.T) { var networkAcl ec2.NetworkAcl + resourceName := "aws_default_network_acl.default" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -61,12 +65,12 @@ func TestAccAWSDefaultNetworkAcl_basicIpv6Vpc(t *testing.T) { { Config: testAccAWSDefaultNetworkConfig_basicIpv6Vpc, Check: resource.ComposeTestCheckFunc( - testAccGetAWSDefaultNetworkAcl("aws_default_network_acl.default", &networkAcl), + testAccGetAWSDefaultNetworkAcl(resourceName, &networkAcl), testAccCheckAWSDefaultACLAttributes(&networkAcl, []*ec2.NetworkAclEntry{}, 0, 4), ), }, { - ResourceName: "aws_default_network_acl.default", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -79,6 +83,7 @@ func TestAccAWSDefaultNetworkAcl_deny_ingress(t *testing.T) { // not Egress. We then expect there to be 3 rules, 2 AWS defaults and 1 // additional Egress. var networkAcl ec2.NetworkAcl + resourceName := "aws_default_network_acl.default" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -88,12 +93,12 @@ func TestAccAWSDefaultNetworkAcl_deny_ingress(t *testing.T) { { Config: testAccAWSDefaultNetworkConfig_deny_ingress, Check: resource.ComposeTestCheckFunc( - testAccGetAWSDefaultNetworkAcl("aws_default_network_acl.default", &networkAcl), + testAccGetAWSDefaultNetworkAcl(resourceName, &networkAcl), testAccCheckAWSDefaultACLAttributes(&networkAcl, []*ec2.NetworkAclEntry{defaultEgressAcl}, 0, 2), ), }, { - ResourceName: "aws_default_network_acl.default", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -103,6 +108,7 @@ func TestAccAWSDefaultNetworkAcl_deny_ingress(t *testing.T) { func TestAccAWSDefaultNetworkAcl_withIpv6Ingress(t *testing.T) { var networkAcl ec2.NetworkAcl + resourceName := "aws_default_network_acl.default" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -112,12 +118,12 @@ func TestAccAWSDefaultNetworkAcl_withIpv6Ingress(t *testing.T) { { Config: testAccAWSDefaultNetworkConfig_includingIpv6Rule, Check: resource.ComposeTestCheckFunc( - testAccGetAWSDefaultNetworkAcl("aws_default_network_acl.default", &networkAcl), + testAccGetAWSDefaultNetworkAcl(resourceName, &networkAcl), testAccCheckAWSDefaultACLAttributes(&networkAcl, []*ec2.NetworkAclEntry{ipv6IngressAcl}, 0, 2), ), }, { - ResourceName: "aws_default_network_acl.default", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -127,6 +133,7 @@ func TestAccAWSDefaultNetworkAcl_withIpv6Ingress(t *testing.T) { func TestAccAWSDefaultNetworkAcl_SubnetRemoval(t *testing.T) { var networkAcl ec2.NetworkAcl + resourceName := "aws_default_network_acl.default" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -136,12 +143,12 @@ func TestAccAWSDefaultNetworkAcl_SubnetRemoval(t *testing.T) { { Config: testAccAWSDefaultNetworkConfig_Subnets, Check: resource.ComposeTestCheckFunc( - testAccGetAWSDefaultNetworkAcl("aws_default_network_acl.default", &networkAcl), + testAccGetAWSDefaultNetworkAcl(resourceName, &networkAcl), testAccCheckAWSDefaultACLAttributes(&networkAcl, []*ec2.NetworkAclEntry{}, 2, 2), ), }, { - ResourceName: "aws_default_network_acl.default", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -152,13 +159,13 @@ func TestAccAWSDefaultNetworkAcl_SubnetRemoval(t *testing.T) { { Config: testAccAWSDefaultNetworkConfig_Subnets_remove, Check: resource.ComposeTestCheckFunc( - testAccGetAWSDefaultNetworkAcl("aws_default_network_acl.default", &networkAcl), + testAccGetAWSDefaultNetworkAcl(resourceName, &networkAcl), testAccCheckAWSDefaultACLAttributes(&networkAcl, []*ec2.NetworkAclEntry{}, 2, 2), ), ExpectNonEmptyPlan: true, }, { - ResourceName: "aws_default_network_acl.default", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -168,6 +175,7 @@ func TestAccAWSDefaultNetworkAcl_SubnetRemoval(t *testing.T) { func TestAccAWSDefaultNetworkAcl_SubnetReassign(t *testing.T) { var networkAcl ec2.NetworkAcl + resourceName := "aws_default_network_acl.default" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -177,12 +185,12 @@ func TestAccAWSDefaultNetworkAcl_SubnetReassign(t *testing.T) { { Config: testAccAWSDefaultNetworkConfig_Subnets, Check: resource.ComposeTestCheckFunc( - testAccGetAWSDefaultNetworkAcl("aws_default_network_acl.default", &networkAcl), + testAccGetAWSDefaultNetworkAcl(resourceName, &networkAcl), testAccCheckAWSDefaultACLAttributes(&networkAcl, []*ec2.NetworkAclEntry{}, 2, 2), ), }, { - ResourceName: "aws_default_network_acl.default", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -202,12 +210,12 @@ func TestAccAWSDefaultNetworkAcl_SubnetReassign(t *testing.T) { { Config: testAccAWSDefaultNetworkConfig_Subnets_move, Check: resource.ComposeTestCheckFunc( - testAccGetAWSDefaultNetworkAcl("aws_default_network_acl.default", &networkAcl), + testAccGetAWSDefaultNetworkAcl(resourceName, &networkAcl), testAccCheckAWSDefaultACLAttributes(&networkAcl, []*ec2.NetworkAclEntry{}, 0, 2), ), }, { - ResourceName: "aws_default_network_acl.default", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -260,7 +268,8 @@ func testAccGetAWSDefaultNetworkAcl(n string, networkAcl *ec2.NetworkAcl) resour return err } - if len(resp.NetworkAcls) > 0 && *resp.NetworkAcls[0].NetworkAclId == rs.Primary.ID { + if len(resp.NetworkAcls) > 0 && + aws.StringValue(resp.NetworkAcls[0].NetworkAclId) == rs.Primary.ID { *networkAcl = *resp.NetworkAcls[0] return nil } @@ -279,7 +288,7 @@ resource "aws_vpc" "tftestvpc" { } resource "aws_default_network_acl" "default" { - default_network_acl_id = "${aws_vpc.tftestvpc.default_network_acl_id}" + default_network_acl_id = aws_vpc.tftestvpc.default_network_acl_id tags = { Name = "tf-acc-default-acl-basic" @@ -297,15 +306,15 @@ resource "aws_vpc" "tftestvpc" { } resource "aws_default_network_acl" "default" { - default_network_acl_id = "${aws_vpc.tftestvpc.default_network_acl_id}" + default_network_acl_id = aws_vpc.tftestvpc.default_network_acl_id ingress { - protocol = -1 - rule_no = 101 - action = "allow" + protocol = -1 + rule_no = 101 + action = "allow" ipv6_cidr_block = "::/0" - from_port = 0 - to_port = 0 + from_port = 0 + to_port = 0 } tags = { @@ -324,7 +333,7 @@ resource "aws_vpc" "tftestvpc" { } resource "aws_default_network_acl" "default" { - default_network_acl_id = "${aws_vpc.tftestvpc.default_network_acl_id}" + default_network_acl_id = aws_vpc.tftestvpc.default_network_acl_id egress { protocol = -1 @@ -352,7 +361,7 @@ resource "aws_vpc" "foo" { resource "aws_subnet" "one" { cidr_block = "10.1.111.0/24" - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "tf-acc-default-network-acl-one" @@ -361,7 +370,7 @@ resource "aws_subnet" "one" { resource "aws_subnet" "two" { cidr_block = "10.1.1.0/24" - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "tf-acc-default-network-acl-two" @@ -369,7 +378,7 @@ resource "aws_subnet" "two" { } resource "aws_network_acl" "bar" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "tf-acc-default-acl-subnets" @@ -377,9 +386,9 @@ resource "aws_network_acl" "bar" { } resource "aws_default_network_acl" "default" { - default_network_acl_id = "${aws_vpc.foo.default_network_acl_id}" + default_network_acl_id = aws_vpc.foo.default_network_acl_id - subnet_ids = ["${aws_subnet.one.id}", "${aws_subnet.two.id}"] + subnet_ids = [aws_subnet.one.id, aws_subnet.two.id] tags = { Name = "tf-acc-default-acl-subnets" @@ -398,7 +407,7 @@ resource "aws_vpc" "foo" { resource "aws_subnet" "one" { cidr_block = "10.1.111.0/24" - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "tf-acc-default-network-acl-subnets-remove-one" @@ -407,7 +416,7 @@ resource "aws_subnet" "one" { resource "aws_subnet" "two" { cidr_block = "10.1.1.0/24" - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "tf-acc-default-network-acl-subnets-remove-two" @@ -415,7 +424,7 @@ resource "aws_subnet" "two" { } resource "aws_network_acl" "bar" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "tf-acc-default-acl-subnets-remove" @@ -423,7 +432,7 @@ resource "aws_network_acl" "bar" { } resource "aws_default_network_acl" "default" { - default_network_acl_id = "${aws_vpc.foo.default_network_acl_id}" + default_network_acl_id = aws_vpc.foo.default_network_acl_id tags = { Name = "tf-acc-default-acl-subnets-remove" @@ -442,7 +451,7 @@ resource "aws_vpc" "foo" { resource "aws_subnet" "one" { cidr_block = "10.1.111.0/24" - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "tf-acc-default-network-acl-subnets-move-one" @@ -451,7 +460,7 @@ resource "aws_subnet" "one" { resource "aws_subnet" "two" { cidr_block = "10.1.1.0/24" - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "tf-acc-default-network-acl-subnets-move-two" @@ -459,9 +468,9 @@ resource "aws_subnet" "two" { } resource "aws_network_acl" "bar" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id - subnet_ids = ["${aws_subnet.one.id}", "${aws_subnet.two.id}"] + subnet_ids = [aws_subnet.one.id, aws_subnet.two.id] tags = { Name = "tf-acc-default-acl-subnets-move" @@ -469,9 +478,9 @@ resource "aws_network_acl" "bar" { } resource "aws_default_network_acl" "default" { - default_network_acl_id = "${aws_vpc.foo.default_network_acl_id}" + default_network_acl_id = aws_vpc.foo.default_network_acl_id - depends_on = ["aws_network_acl.bar"] + depends_on = [aws_network_acl.bar] tags = { Name = "tf-acc-default-acl-subnets-move" @@ -481,16 +490,16 @@ resource "aws_default_network_acl" "default" { const testAccAWSDefaultNetworkConfig_basicIpv6Vpc = ` resource "aws_vpc" "tftestvpc" { - cidr_block = "10.1.0.0/16" - assign_generated_ipv6_cidr_block = true + cidr_block = "10.1.0.0/16" + assign_generated_ipv6_cidr_block = true - tags = { - Name = "terraform-testacc-default-network-acl-basic-ipv6-vpc" - } + tags = { + Name = "terraform-testacc-default-network-acl-basic-ipv6-vpc" + } } resource "aws_default_network_acl" "default" { - default_network_acl_id = "${aws_vpc.tftestvpc.default_network_acl_id}" + default_network_acl_id = aws_vpc.tftestvpc.default_network_acl_id tags = { Name = "tf-acc-default-acl-subnets-basic-ipv6-vpc" diff --git a/aws/resource_aws_default_route_table.go b/aws/resource_aws_default_route_table.go index e3ad506f883..710e339dc19 100644 --- a/aws/resource_aws_default_route_table.go +++ b/aws/resource_aws_default_route_table.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -51,15 +51,21 @@ func resourceAwsDefaultRouteTable() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cidr_block": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.IsCIDR, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validateIpv4CIDRNetworkAddress, + ), }, "ipv6_cidr_block": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.IsCIDR, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validateIpv6CIDRNetworkAddress, + ), }, "egress_only_gateway_id": { diff --git a/aws/resource_aws_default_route_table_test.go b/aws/resource_aws_default_route_table_test.go index 5b648aa1d90..100f0eb5cbc 100644 --- a/aws/resource_aws_default_route_table_test.go +++ b/aws/resource_aws_default_route_table_test.go @@ -7,9 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSDefaultRouteTable_basic(t *testing.T) { @@ -252,6 +253,46 @@ func TestAccAWSDefaultRouteTable_tags(t *testing.T) { }) } +func TestAccAWSDefaultRouteTable_ConditionalCidrBlock(t *testing.T) { + var routeTable ec2.RouteTable + resourceName := "aws_default_route_table.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSRouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSDefaultRouteTableConfigConditionalIpv4Ipv6(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckRouteTableExists(resourceName, &routeTable), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "route.*", map[string]string{ + "cidr_block": "0.0.0.0/0", + "ipv6_cidr_block": "", + }), + ), + }, + { + Config: testAccAWSDefaultRouteTableConfigConditionalIpv4Ipv6(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckRouteTableExists(resourceName, &routeTable), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "route.*", map[string]string{ + "cidr_block": "", + "ipv6_cidr_block": "::/0", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSDefaultRouteTableImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + func testAccCheckDefaultRouteTableDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn @@ -290,7 +331,7 @@ resource "aws_default_route_table" "test" { } func testAccDefaultRouteTableConfigRequired() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" } @@ -298,7 +339,7 @@ resource "aws_vpc" "test" { resource "aws_default_route_table" "test" { default_route_table_id = aws_vpc.test.default_route_table_id } -`) +` } const testAccDefaultRouteTableConfig = ` @@ -312,11 +353,11 @@ resource "aws_vpc" "foo" { } resource "aws_default_route_table" "foo" { - default_route_table_id = "${aws_vpc.foo.default_route_table_id}" + default_route_table_id = aws_vpc.foo.default_route_table_id route { cidr_block = "10.0.1.0/32" - gateway_id = "${aws_internet_gateway.gw.id}" + gateway_id = aws_internet_gateway.gw.id } tags = { @@ -325,7 +366,7 @@ resource "aws_default_route_table" "foo" { } resource "aws_internet_gateway" "gw" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "tf-default-route-table-test" @@ -343,7 +384,7 @@ resource "aws_vpc" "foo" { } resource "aws_default_route_table" "foo" { - default_route_table_id = "${aws_vpc.foo.default_route_table_id}" + default_route_table_id = aws_vpc.foo.default_route_table_id tags = { Name = "tf-default-route-table-test" @@ -351,7 +392,7 @@ resource "aws_default_route_table" "foo" { } resource "aws_internet_gateway" "gw" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "tf-default-route-table-test" @@ -369,7 +410,7 @@ resource "aws_vpc" "foo" { } resource "aws_default_route_table" "foo" { - default_route_table_id = "${aws_vpc.foo.default_route_table_id}" + default_route_table_id = aws_vpc.foo.default_route_table_id route = [] @@ -379,7 +420,7 @@ resource "aws_default_route_table" "foo" { } resource "aws_internet_gateway" "gw" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "tf-default-route-table-test" @@ -397,11 +438,11 @@ resource "aws_vpc" "foo" { } resource "aws_default_route_table" "foo" { - default_route_table_id = "${aws_vpc.foo.default_route_table_id}" + default_route_table_id = aws_vpc.foo.default_route_table_id route { cidr_block = "10.0.1.0/32" - gateway_id = "${aws_internet_gateway.gw.id}" + gateway_id = aws_internet_gateway.gw.id } tags = { @@ -410,7 +451,7 @@ resource "aws_default_route_table" "foo" { } resource "aws_internet_gateway" "gw" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "main-igw" @@ -419,11 +460,11 @@ resource "aws_internet_gateway" "gw" { # Thing to help testing changes resource "aws_route_table" "r" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id route { cidr_block = "10.0.1.0/24" - gateway_id = "${aws_internet_gateway.gw.id}" + gateway_id = aws_internet_gateway.gw.id } tags = { @@ -443,11 +484,11 @@ resource "aws_vpc" "foo" { } resource "aws_default_route_table" "foo" { - default_route_table_id = "${aws_vpc.foo.default_route_table_id}" + default_route_table_id = aws_vpc.foo.default_route_table_id route { cidr_block = "10.0.1.0/32" - gateway_id = "${aws_internet_gateway.gw.id}" + gateway_id = aws_internet_gateway.gw.id } tags = { @@ -456,7 +497,7 @@ resource "aws_default_route_table" "foo" { } resource "aws_internet_gateway" "gw" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "main-igw" @@ -465,11 +506,11 @@ resource "aws_internet_gateway" "gw" { # Thing to help testing changes resource "aws_route_table" "r" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id route { cidr_block = "10.0.1.0/24" - gateway_id = "${aws_internet_gateway.gw.id}" + gateway_id = aws_internet_gateway.gw.id } tags = { @@ -478,13 +519,13 @@ resource "aws_route_table" "r" { } resource "aws_main_route_table_association" "a" { - vpc_id = "${aws_vpc.foo.id}" - route_table_id = "${aws_route_table.r.id}" + vpc_id = aws_vpc.foo.id + route_table_id = aws_route_table.r.id } ` func testAccAWSDefaultRouteTableConfigRouteTransitGatewayID() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -495,7 +536,7 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-default-route-table-transit-gateway-id" @@ -509,9 +550,9 @@ resource "aws_ec2_transit_gateway" "test" { } resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-default-route-table-transit-gateway-id" @@ -519,14 +560,14 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { } resource "aws_default_route_table" "test" { - default_route_table_id = "${aws_vpc.test.default_route_table_id}" + default_route_table_id = aws_vpc.test.default_route_table_id route { cidr_block = "0.0.0.0/0" - transit_gateway_id = "${aws_ec2_transit_gateway_vpc_attachment.test.transit_gateway_id}" + transit_gateway_id = aws_ec2_transit_gateway_vpc_attachment.test.transit_gateway_id } } -`) +` } const testAccDefaultRouteTable_vpc_endpoint = ` @@ -541,7 +582,7 @@ resource "aws_vpc" "test" { } resource "aws_internet_gateway" "igw" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "terraform-testacc-default-route-table-vpc-endpoint" @@ -549,9 +590,9 @@ resource "aws_internet_gateway" "igw" { } resource "aws_vpc_endpoint" "s3" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id service_name = "com.amazonaws.${data.aws_region.current.name}.s3" - route_table_ids = ["${aws_vpc.test.default_route_table_id}"] + route_table_ids = [aws_vpc.test.default_route_table_id] tags = { Name = "terraform-testacc-default-route-table-vpc-endpoint" @@ -559,7 +600,7 @@ resource "aws_vpc_endpoint" "s3" { } resource "aws_default_route_table" "foo" { - default_route_table_id = "${aws_vpc.test.default_route_table_id}" + default_route_table_id = aws_vpc.test.default_route_table_id tags = { Name = "test" @@ -567,7 +608,7 @@ resource "aws_default_route_table" "foo" { route { cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.igw.id}" + gateway_id = aws_internet_gateway.igw.id } } ` @@ -613,6 +654,56 @@ resource "aws_default_route_table" "test" { `, rName, tagKey1, tagValue1, tagKey2, tagValue2) } +func testAccAWSDefaultRouteTableConfigConditionalIpv4Ipv6(rName string, ipv6Route bool) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + + assign_generated_ipv6_cidr_block = true + + tags = { + Name = %[1]q + } +} + +resource "aws_egress_only_internet_gateway" "test" { + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } +} + +resource "aws_internet_gateway" "test" { + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } +} + +locals { + ipv6 = %[2]t + destination = "0.0.0.0/0" + destination_ipv6 = "::/0" +} + +resource "aws_default_route_table" "test" { + default_route_table_id = aws_vpc.test.default_route_table_id + + route { + cidr_block = local.ipv6 ? "" : local.destination + ipv6_cidr_block = local.ipv6 ? local.destination_ipv6 : "" + gateway_id = aws_internet_gateway.test.id + } + + tags = { + Name = %[1]q + } +} +`, rName, ipv6Route) +} + func testAccAWSDefaultRouteTableImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] diff --git a/aws/resource_aws_default_security_group.go b/aws/resource_aws_default_security_group.go index b6076f721e5..59177072b9a 100644 --- a/aws/resource_aws_default_security_group.go +++ b/aws/resource_aws_default_security_group.go @@ -1,40 +1,191 @@ package aws import ( + "bytes" "fmt" "log" + "sort" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/ec2/finder" ) +const DefaultSecurityGroupName = "default" + func resourceAwsDefaultSecurityGroup() *schema.Resource { - // reuse aws_security_group_rule schema, and methods for READ, UPDATE - dsg := resourceAwsSecurityGroup() - dsg.Create = resourceAwsDefaultSecurityGroupCreate - dsg.Delete = resourceAwsDefaultSecurityGroupDelete - - // description is a computed value for Default Security Groups and cannot be changed - dsg.Schema["description"] = &schema.Schema{ - Type: schema.TypeString, - Computed: true, - } - - // name is a computed value for Default Security Groups and cannot be changed - delete(dsg.Schema, "name_prefix") - dsg.Schema["name"] = &schema.Schema{ - Type: schema.TypeString, - Computed: true, - } - - // We want explicit management of Rules here, so we do not allow them to be - // computed. Instead, an empty config will enforce just that; removal of the - // rules - dsg.Schema["ingress"].Computed = false - dsg.Schema["egress"].Computed = false - return dsg + //lintignore:R011 + return &schema.Resource{ + Create: resourceAwsDefaultSecurityGroupCreate, + Read: resourceAwsDefaultSecurityGroupRead, + Update: resourceAwsDefaultSecurityGroupUpdate, + Delete: resourceAwsDefaultSecurityGroupDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + SchemaVersion: 1, + MigrateState: resourceAwsDefaultSecurityGroupMigrateState, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Computed: true, + }, + "vpc_id": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Computed: true, + }, + "ingress": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + ConfigMode: schema.SchemaConfigModeAttr, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cidr_blocks": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validateCIDRNetworkAddress, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validateSecurityGroupRuleDescription, + }, + "from_port": { + Type: schema.TypeInt, + Required: true, + }, + "ipv6_cidr_blocks": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validateCIDRNetworkAddress, + }, + }, + "prefix_list_ids": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "protocol": { + Type: schema.TypeString, + Required: true, + StateFunc: protocolStateFunc, + }, + "security_groups": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + "self": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "to_port": { + Type: schema.TypeInt, + Required: true, + }, + }, + }, + Set: resourceAwsDefaultSecurityGroupRuleHash, + }, + "egress": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + ConfigMode: schema.SchemaConfigModeAttr, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cidr_blocks": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validateCIDRNetworkAddress, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validateSecurityGroupRuleDescription, + }, + "from_port": { + Type: schema.TypeInt, + Required: true, + }, + "ipv6_cidr_blocks": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validateCIDRNetworkAddress, + }, + }, + "prefix_list_ids": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "protocol": { + Type: schema.TypeString, + Required: true, + StateFunc: protocolStateFunc, + }, + "security_groups": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, + "self": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "to_port": { + Type: schema.TypeInt, + Required: true, + }, + }, + }, + Set: resourceAwsDefaultSecurityGroupRuleHash, + }, + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "owner_id": { + Type: schema.TypeString, + Computed: true, + }, + "tags": tagsSchema(), + // This is not implemented. Added to prevent breaking changes. + "revoke_rules_on_delete": { + Type: schema.TypeBool, + Default: false, + Optional: true, + }, + }, + } } func resourceAwsDefaultSecurityGroupCreate(d *schema.ResourceData, meta interface{}) error { @@ -43,17 +194,17 @@ func resourceAwsDefaultSecurityGroupCreate(d *schema.ResourceData, meta interfac Filters: []*ec2.Filter{ { Name: aws.String("group-name"), - Values: []*string{aws.String("default")}, + Values: aws.StringSlice([]string{DefaultSecurityGroupName}), }, }, } - var vpcId string + var vpcID string if v, ok := d.GetOk("vpc_id"); ok { - vpcId = v.(string) + vpcID = v.(string) securityGroupOpts.Filters = append(securityGroupOpts.Filters, &ec2.Filter{ Name: aws.String("vpc-id"), - Values: []*string{aws.String(vpcId)}, + Values: aws.StringSlice([]string{vpcID}), }) } @@ -61,11 +212,11 @@ func resourceAwsDefaultSecurityGroupCreate(d *schema.ResourceData, meta interfac log.Printf("[DEBUG] Commandeer Default Security Group: %s", securityGroupOpts) resp, err := conn.DescribeSecurityGroups(securityGroupOpts) if err != nil { - return fmt.Errorf("Error creating Default Security Group: %s", err) + return fmt.Errorf("Error creating Default Security Group: %w", err) } var g *ec2.SecurityGroup - if vpcId != "" { + if vpcID != "" { // if vpcId contains a value, then we expect just a single Security Group // returned, as default is a protected name for each VPC, and for each // Region on EC2 Classic @@ -77,8 +228,9 @@ func resourceAwsDefaultSecurityGroupCreate(d *schema.ResourceData, meta interfac // we need to filter through any returned security groups for the group // named "default", and does not belong to a VPC for _, sg := range resp.SecurityGroups { - if sg.VpcId == nil && *sg.GroupName == "default" { + if sg.VpcId == nil && aws.StringValue(sg.GroupName) == DefaultSecurityGroupName { g = sg + break } } } @@ -87,21 +239,111 @@ func resourceAwsDefaultSecurityGroupCreate(d *schema.ResourceData, meta interfac return fmt.Errorf("Error finding default security group: no matching group found") } - d.SetId(*g.GroupId) + d.SetId(aws.StringValue(g.GroupId)) log.Printf("[INFO] Default Security Group ID: %s", d.Id()) if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { if err := keyvaluetags.Ec2CreateTags(conn, d.Id(), v); err != nil { - return fmt.Errorf("error adding EC2 Default Security Group (%s) tags: %s", d.Id(), err) + return fmt.Errorf("error adding EC2 Default Security Group (%s) tags: %w", d.Id(), err) } } if err := revokeDefaultSecurityGroupRules(meta, g); err != nil { - return fmt.Errorf("%s", err) + return err + } + + return resourceAwsDefaultSecurityGroupUpdate(d, meta) +} + +func resourceAwsDefaultSecurityGroupRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + + group, err := finder.SecurityGroupByID(conn, d.Id()) + if err != nil { + return err + } + if group == nil { + log.Printf("[WARN] Security group (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + remoteIngressRules := resourceAwsSecurityGroupIPPermGather(d.Id(), group.IpPermissions, group.OwnerId) + remoteEgressRules := resourceAwsSecurityGroupIPPermGather(d.Id(), group.IpPermissionsEgress, group.OwnerId) + + localIngressRules := d.Get("ingress").(*schema.Set).List() + localEgressRules := d.Get("egress").(*schema.Set).List() + + // Loop through the local state of rules, doing a match against the remote + // ruleSet we built above. + ingressRules := matchRules("ingress", localIngressRules, remoteIngressRules) + egressRules := matchRules("egress", localEgressRules, remoteEgressRules) + + sgArn := arn.ARN{ + AccountID: aws.StringValue(group.OwnerId), + Partition: meta.(*AWSClient).partition, + Region: meta.(*AWSClient).region, + Resource: fmt.Sprintf("security-group/%s", aws.StringValue(group.GroupId)), + Service: ec2.ServiceName, + } + + d.Set("arn", sgArn.String()) + d.Set("description", group.Description) + d.Set("name", group.GroupName) + d.Set("owner_id", group.OwnerId) + d.Set("vpc_id", group.VpcId) + + if err := d.Set("ingress", ingressRules); err != nil { + return fmt.Errorf("error setting Ingress rule set for (%s): %w", d.Id(), err) + } + + if err := d.Set("egress", egressRules); err != nil { + return fmt.Errorf("error setting Egress rule set for (%s): %w", d.Id(), err) } - return resourceAwsSecurityGroupUpdate(d, meta) + if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(group.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags for (%s): %w", d.Id(), err) + } + + return nil +} + +func resourceAwsDefaultSecurityGroupUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + group, err := finder.SecurityGroupByID(conn, d.Id()) + if err != nil { + return err + } + if group == nil { + log.Printf("[WARN] Security group (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + err = resourceAwsSecurityGroupUpdateRules(d, "ingress", meta, group) + if err != nil { + return err + } + + if d.Get("vpc_id") != nil { + err = resourceAwsSecurityGroupUpdateRules(d, "egress", meta, group) + if err != nil { + return err + } + } + + if d.HasChange("tags") && !d.IsNewResource() { + o, n := d.GetChange("tags") + + if err := keyvaluetags.Ec2UpdateTags(conn, d.Id(), o, n); err != nil { + return fmt.Errorf("error updating EC2 Security Group (%s) tags: %w", d.Id(), err) + } + } + + return resourceAwsDefaultSecurityGroupRead(d, meta) } func resourceAwsDefaultSecurityGroupDelete(d *schema.ResourceData, meta interface{}) error { @@ -112,18 +354,17 @@ func resourceAwsDefaultSecurityGroupDelete(d *schema.ResourceData, meta interfac func revokeDefaultSecurityGroupRules(meta interface{}, g *ec2.SecurityGroup) error { conn := meta.(*AWSClient).ec2conn - log.Printf("[WARN] Removing all ingress and egress rules found on Default Security Group (%s)", *g.GroupId) + groupID := aws.StringValue(g.GroupId) + log.Printf("[WARN] Removing all ingress and egress rules found on Default Security Group (%s)", groupID) if len(g.IpPermissionsEgress) > 0 { req := &ec2.RevokeSecurityGroupEgressInput{ GroupId: g.GroupId, IpPermissions: g.IpPermissionsEgress, } - log.Printf("[DEBUG] Revoking default egress rules for Default Security Group for %s", *g.GroupId) + log.Printf("[DEBUG] Revoking default egress rules for Default Security Group for %s", groupID) if _, err := conn.RevokeSecurityGroupEgress(req); err != nil { - return fmt.Errorf( - "Error revoking default egress rules for Default Security Group (%s): %s", - *g.GroupId, err) + return fmt.Errorf("error revoking default egress rules for Default Security Group (%s): %w", groupID, err) } } if len(g.IpPermissions) > 0 { @@ -141,13 +382,103 @@ func revokeDefaultSecurityGroupRules(meta interface{}, g *ec2.SecurityGroup) err IpPermissions: g.IpPermissions, } - log.Printf("[DEBUG] Revoking default ingress rules for Default Security Group for (%s): %s", *g.GroupId, req) + log.Printf("[DEBUG] Revoking default ingress rules for Default Security Group for (%s): %s", groupID, req) if _, err := conn.RevokeSecurityGroupIngress(req); err != nil { - return fmt.Errorf( - "Error revoking default ingress rules for Default Security Group (%s): %s", - *g.GroupId, err) + return fmt.Errorf("Error revoking default ingress rules for Default Security Group (%s): %w", groupID, err) } } return nil } + +func resourceAwsDefaultSecurityGroupRuleHash(v interface{}) int { + var buf bytes.Buffer + m := v.(map[string]interface{}) + buf.WriteString(fmt.Sprintf("%d-", m["from_port"].(int))) + buf.WriteString(fmt.Sprintf("%d-", m["to_port"].(int))) + p := protocolForValue(m["protocol"].(string)) + buf.WriteString(fmt.Sprintf("%s-", p)) + buf.WriteString(fmt.Sprintf("%t-", m["self"].(bool))) + + // We need to make sure to sort the strings below so that we always + // generate the same hash code no matter what is in the set. + if v, ok := m["cidr_blocks"]; ok { + vs := v.([]interface{}) + s := make([]string, len(vs)) + for i, raw := range vs { + s[i] = raw.(string) + } + sort.Strings(s) + + for _, v := range s { + buf.WriteString(fmt.Sprintf("%s-", v)) + } + } + if v, ok := m["ipv6_cidr_blocks"]; ok { + vs := v.([]interface{}) + s := make([]string, len(vs)) + for i, raw := range vs { + s[i] = raw.(string) + } + sort.Strings(s) + + for _, v := range s { + buf.WriteString(fmt.Sprintf("%s-", v)) + } + } + if v, ok := m["prefix_list_ids"]; ok { + vs := v.([]interface{}) + s := make([]string, len(vs)) + for i, raw := range vs { + s[i] = raw.(string) + } + sort.Strings(s) + + for _, v := range s { + buf.WriteString(fmt.Sprintf("%s-", v)) + } + } + if v, ok := m["security_groups"]; ok { + vs := v.(*schema.Set).List() + s := make([]string, len(vs)) + for i, raw := range vs { + s[i] = raw.(string) + } + sort.Strings(s) + + for _, v := range s { + buf.WriteString(fmt.Sprintf("%s-", v)) + } + } + if m["description"].(string) != "" { + buf.WriteString(fmt.Sprintf("%s-", m["description"].(string))) + } + + return hashcode.String(buf.String()) +} + +func resourceAwsDefaultSecurityGroupMigrateState( + v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { + switch v { + case 0: + log.Println("[INFO] Found AWS Default Security Group state v0; migrating to v1") + return migrateAwsDefaultSecurityGroupStateV0toV1(is) + default: + return is, fmt.Errorf("Unexpected schema version: %d", v) + } +} + +func migrateAwsDefaultSecurityGroupStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) { + if is.Empty() || is.Attributes == nil { + log.Println("[DEBUG] Empty InstanceState; nothing to migrate.") + return is, nil + } + + log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes) + + // set default for revoke_rules_on_delete + is.Attributes["revoke_rules_on_delete"] = "false" + + log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes) + return is, nil +} diff --git a/aws/resource_aws_default_security_group_test.go b/aws/resource_aws_default_security_group_test.go index c9a51338c0d..ea2a257a442 100644 --- a/aws/resource_aws_default_security_group_test.go +++ b/aws/resource_aws_default_security_group_test.go @@ -2,77 +2,173 @@ package aws import ( "fmt" - "reflect" + "os" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) -func TestAccAWSDefaultSecurityGroup_basic(t *testing.T) { +func TestAccAWSDefaultSecurityGroup_Vpc_basic(t *testing.T) { var group ec2.SecurityGroup + resourceName := "aws_default_security_group.test" + vpcResourceName := "aws_vpc.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_default_security_group.web", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSDefaultSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDefaultSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSDefaultSecurityGroupConfig, + Config: testAccAWSDefaultSecurityGroupConfig_Vpc, Check: resource.ComposeTestCheckFunc( - testAccCheckAWSDefaultSecurityGroupExists("aws_default_security_group.web", &group), - testAccCheckAWSDefaultSecurityGroupAttributes(&group), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "name", "default"), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "description", "default VPC security group"), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "ingress.3629188364.protocol", "tcp"), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "ingress.3629188364.from_port", "80"), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "ingress.3629188364.to_port", "8000"), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "ingress.3629188364.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "ingress.3629188364.cidr_blocks.0", "10.0.0.0/8"), + testAccCheckAWSDefaultSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "name", "default"), + resource.TestCheckResourceAttr(resourceName, "description", "default VPC security group"), + resource.TestCheckResourceAttrPair(resourceName, "vpc_id", vpcResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "tcp", + "from_port": "80", + "to_port": "8000", + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + }), + resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "protocol": "tcp", + "from_port": "80", + "to_port": "8000", + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + }), + testAccCheckAWSDefaultSecurityGroupARN(resourceName, &group), + testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", "tf-acc-test"), ), }, + { + Config: testAccAWSDefaultSecurityGroupConfig_Vpc, + PlanOnly: true, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + }, }, }) } -func TestAccAWSDefaultSecurityGroup_classic(t *testing.T) { +func TestAccAWSDefaultSecurityGroup_Vpc_empty(t *testing.T) { var group ec2.SecurityGroup + resourceName := "aws_default_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_default_security_group.web", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSDefaultSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDefaultSecurityGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSDefaultSecurityGroupConfig_classic, + Config: testAccAWSDefaultSecurityGroupConfig_Vpc_empty, Check: resource.ComposeTestCheckFunc( - testAccCheckAWSDefaultSecurityGroupExists("aws_default_security_group.web", &group), - testAccCheckAWSDefaultSecurityGroupAttributes(&group), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "name", "default"), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "ingress.3629188364.protocol", "tcp"), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "ingress.3629188364.from_port", "80"), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "ingress.3629188364.to_port", "8000"), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "ingress.3629188364.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr( - "aws_default_security_group.web", "ingress.3629188364.cidr_blocks.0", "10.0.0.0/8"), + testAccCheckAWSDefaultSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), + resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + }, + }, + }) +} + +func TestAccAWSDefaultSecurityGroup_Classic_basic(t *testing.T) { + oldvar := os.Getenv("AWS_DEFAULT_REGION") + os.Setenv("AWS_DEFAULT_REGION", "us-east-1") + defer os.Setenv("AWS_DEFAULT_REGION", oldvar) + + var group ec2.SecurityGroup + resourceName := "aws_default_security_group.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccEC2ClassicPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDefaultSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSDefaultSecurityGroupConfig_Classic, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSDefaultSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "name", "default"), + resource.TestCheckResourceAttr(resourceName, "description", "default group"), + resource.TestCheckResourceAttr(resourceName, "vpc_id", ""), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "tcp", + "from_port": "80", + "to_port": "8000", + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + }), + resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), + testAccCheckAWSDefaultSecurityGroupARN(resourceName, &group), + testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", "tf-acc-test"), + ), + }, + { + Config: testAccAWSDefaultSecurityGroupConfig_Classic, + PlanOnly: true, + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + }, + }, + }) +} + +func TestAccAWSDefaultSecurityGroup_Classic_empty(t *testing.T) { + + TestAccSkip(t, "This resource does not currently clear tags when adopting the resource") + // Additional references: + // * https://github.com/terraform-providers/terraform-provider-aws/issues/14631 + + oldvar := os.Getenv("AWS_DEFAULT_REGION") + os.Setenv("AWS_DEFAULT_REGION", "us-east-1") + defer os.Setenv("AWS_DEFAULT_REGION", oldvar) + + var group ec2.SecurityGroup + resourceName := "aws_default_security_group.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccEC2ClassicPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDefaultSecurityGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSDefaultSecurityGroupConfig_Classic_empty, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSDefaultSecurityGroupExists(resourceName, &group), + resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), + resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), ), }, }, @@ -113,45 +209,23 @@ func testAccCheckAWSDefaultSecurityGroupExists(n string, group *ec2.SecurityGrou } } -func testAccCheckAWSDefaultSecurityGroupAttributes(group *ec2.SecurityGroup) resource.TestCheckFunc { +func testAccCheckAWSDefaultSecurityGroupARN(resourceName string, group *ec2.SecurityGroup) resource.TestCheckFunc { return func(s *terraform.State) error { - p := &ec2.IpPermission{ - FromPort: aws.Int64(80), - ToPort: aws.Int64(8000), - IpProtocol: aws.String("tcp"), - IpRanges: []*ec2.IpRange{{CidrIp: aws.String("10.0.0.0/8")}}, - } - - if *group.GroupName != "default" { - return fmt.Errorf("Bad name: %s", *group.GroupName) - } - - if len(group.IpPermissions) == 0 { - return fmt.Errorf("No IPPerms") - } - - // Compare our ingress - if !reflect.DeepEqual(group.IpPermissions[0], p) { - return fmt.Errorf( - "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - group.IpPermissions[0], - p) - } - - return nil + return testAccCheckResourceAttrRegionalARN(resourceName, "arn", "ec2", fmt.Sprintf("security-group/%s", aws.StringValue(group.GroupId)))(s) } } -const testAccAWSDefaultSecurityGroupConfig = ` -resource "aws_vpc" "foo" { +const testAccAWSDefaultSecurityGroupConfig_Vpc = ` +resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" - tags = { - Name = "terraform-testacc-default-security-group" - } + + tags = { + Name = "terraform-testacc-default-security-group" + } } -resource "aws_default_security_group" "web" { - vpc_id = "${aws_vpc.foo.id}" +resource "aws_default_security_group" "test" { + vpc_id = aws_vpc.test.id ingress { protocol = "6" @@ -173,12 +247,22 @@ resource "aws_default_security_group" "web" { } ` -const testAccAWSDefaultSecurityGroupConfig_classic = ` -provider "aws" { - region = "us-east-1" +const testAccAWSDefaultSecurityGroupConfig_Vpc_empty = ` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + + tags = { + Name = "terraform-testacc-default-security-group" + } } -resource "aws_default_security_group" "web" { +resource "aws_default_security_group" "test" { + vpc_id = aws_vpc.test.id +} +` + +const testAccAWSDefaultSecurityGroupConfig_Classic = ` +resource "aws_default_security_group" "test" { ingress { protocol = "6" from_port = 80 @@ -189,4 +273,75 @@ resource "aws_default_security_group" "web" { tags = { Name = "tf-acc-test" } -}` +} +` + +const testAccAWSDefaultSecurityGroupConfig_Classic_empty = ` +resource "aws_default_security_group" "test" { + # No attributes set. +} +` + +func TestAWSDefaultSecurityGroupMigrateState(t *testing.T) { + cases := map[string]struct { + StateVersion int + Attributes map[string]string + Expected map[string]string + Meta interface{} + }{ + "v0": { + StateVersion: 0, + Attributes: map[string]string{ + "name": "test", + }, + Expected: map[string]string{ + "name": "test", + "revoke_rules_on_delete": "false", + }, + }, + } + + for tn, tc := range cases { + is := &terraform.InstanceState{ + ID: "i-abc123", + Attributes: tc.Attributes, + } + is, err := resourceAwsDefaultSecurityGroupMigrateState( + tc.StateVersion, is, tc.Meta) + + if err != nil { + t.Fatalf("bad: %s, err: %#v", tn, err) + } + + for k, v := range tc.Expected { + if is.Attributes[k] != v { + t.Fatalf( + "bad: %s\n\n expected: %#v -> %#v\n got: %#v -> %#v\n in: %#v", + tn, k, v, k, is.Attributes[k], is.Attributes) + } + } + } +} + +func TestAWSDefaultSecurityGroupMigrateState_empty(t *testing.T) { + var is *terraform.InstanceState + var meta interface{} + + // should handle nil + is, err := resourceAwsDefaultSecurityGroupMigrateState(0, is, meta) + + if err != nil { + t.Fatalf("err: %#v", err) + } + if is != nil { + t.Fatalf("expected nil instancestate, got: %#v", is) + } + + // should handle non-nil but empty + is = &terraform.InstanceState{} + _, err = resourceAwsDefaultSecurityGroupMigrateState(0, is, meta) + + if err != nil { + t.Fatalf("err: %#v", err) + } +} diff --git a/aws/resource_aws_default_subnet.go b/aws/resource_aws_default_subnet.go index dfa74f83fb7..368ec5067ca 100644 --- a/aws/resource_aws_default_subnet.go +++ b/aws/resource_aws_default_subnet.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsDefaultSubnet() *schema.Resource { diff --git a/aws/resource_aws_default_subnet_test.go b/aws/resource_aws_default_subnet_test.go index 9dba79e6cd9..cb552ef44cc 100644 --- a/aws/resource_aws_default_subnet_test.go +++ b/aws/resource_aws_default_subnet_test.go @@ -4,8 +4,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSDefaultSubnet_basic(t *testing.T) { diff --git a/aws/resource_aws_default_vpc.go b/aws/resource_aws_default_vpc.go index 4cda17641bd..79235c3f7a6 100644 --- a/aws/resource_aws_default_vpc.go +++ b/aws/resource_aws_default_vpc.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsDefaultVpc() *schema.Resource { diff --git a/aws/resource_aws_default_vpc_dhcp_options.go b/aws/resource_aws_default_vpc_dhcp_options.go index ea7cf94bb46..1e4c631dbfe 100644 --- a/aws/resource_aws_default_vpc_dhcp_options.go +++ b/aws/resource_aws_default_vpc_dhcp_options.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsDefaultVpcDhcpOptions() *schema.Resource { diff --git a/aws/resource_aws_default_vpc_dhcp_options_test.go b/aws/resource_aws_default_vpc_dhcp_options_test.go index d8dd8f51afb..ab4fa86be84 100644 --- a/aws/resource_aws_default_vpc_dhcp_options_test.go +++ b/aws/resource_aws_default_vpc_dhcp_options_test.go @@ -1,15 +1,17 @@ package aws import ( + "regexp" "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSDefaultVpcDhcpOptions_basic(t *testing.T) { var d ec2.DhcpOptions + resourceName := "aws_default_vpc_dhcp_options.foo" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -19,16 +21,13 @@ func TestAccAWSDefaultVpcDhcpOptions_basic(t *testing.T) { { 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"), - testAccCheckResourceAttrAccountID("aws_default_vpc_dhcp_options.foo", "owner_id"), + testAccCheckDHCPOptionsExists(resourceName, &d), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`dhcp-options/dopt-.+`)), + resource.TestCheckResourceAttr(resourceName, "domain_name", "us-west-2.compute.internal"), + resource.TestCheckResourceAttr(resourceName, "domain_name_servers", "AmazonProvidedDNS"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", "Default DHCP Option Set"), + testAccCheckResourceAttrAccountID(resourceName, "owner_id"), ), }, }, diff --git a/aws/resource_aws_default_vpc_test.go b/aws/resource_aws_default_vpc_test.go index bb133b61bd4..956179377d9 100644 --- a/aws/resource_aws_default_vpc_test.go +++ b/aws/resource_aws_default_vpc_test.go @@ -4,8 +4,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSDefaultVpc_basic(t *testing.T) { @@ -49,8 +49,8 @@ func testAccCheckAWSDefaultVpcDestroy(s *terraform.State) error { const testAccAWSDefaultVpcConfigBasic = ` resource "aws_default_vpc" "foo" { - tags = { - Name = "Default VPC" - } + tags = { + Name = "Default VPC" + } } ` diff --git a/aws/resource_aws_devicefarm_project.go b/aws/resource_aws_devicefarm_project.go index 9b62ad28b41..08b3760c38c 100644 --- a/aws/resource_aws_devicefarm_project.go +++ b/aws/resource_aws_devicefarm_project.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/devicefarm" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsDevicefarmProject() *schema.Resource { @@ -15,6 +15,9 @@ func resourceAwsDevicefarmProject() *schema.Resource { Read: resourceAwsDevicefarmProjectRead, Update: resourceAwsDevicefarmProjectUpdate, Delete: resourceAwsDevicefarmProjectDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, Schema: map[string]*schema.Schema{ "arn": { @@ -66,6 +69,11 @@ func resourceAwsDevicefarmProjectRead(d *schema.ResourceData, meta interface{}) log.Printf("[DEBUG] Reading DeviceFarm Project: %s", d.Id()) out, err := conn.GetProject(input) if err != nil { + if isAWSErr(err, devicefarm.ErrCodeNotFoundException, "") { + log.Printf("[WARN] DeviceFarm Project (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } return fmt.Errorf("Error reading DeviceFarm Project: %s", err) } diff --git a/aws/resource_aws_devicefarm_project_test.go b/aws/resource_aws_devicefarm_project_test.go index bea4e4e601b..85f924370b6 100644 --- a/aws/resource_aws_devicefarm_project_test.go +++ b/aws/resource_aws_devicefarm_project_test.go @@ -2,20 +2,20 @@ package aws import ( "fmt" + "regexp" "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSDeviceFarmProject_basic(t *testing.T) { - var afterCreate, afterUpdate devicefarm.Project - beforeInt := acctest.RandInt() - afterInt := acctest.RandInt() + var proj devicefarm.Project + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_devicefarm_project.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -23,40 +23,44 @@ func TestAccAWSDeviceFarmProject_basic(t *testing.T) { CheckDestroy: testAccCheckDeviceFarmProjectDestroy, Steps: []resource.TestStep{ { - Config: testAccDeviceFarmProjectConfig(beforeInt), + Config: testAccDeviceFarmProjectConfig(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckDeviceFarmProjectExists( - "aws_devicefarm_project.foo", &afterCreate), - resource.TestCheckResourceAttr( - "aws_devicefarm_project.foo", "name", fmt.Sprintf("tf-testproject-%d", beforeInt)), + testAccCheckDeviceFarmProjectExists(resourceName, &proj), + resource.TestCheckResourceAttr(resourceName, "name", rName), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "devicefarm", regexp.MustCompile(`project:.+`)), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} +func TestAccAWSDeviceFarmProject_disappears(t *testing.T) { + var proj devicefarm.Project + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_devicefarm_project.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDeviceFarmProjectDestroy, + Steps: []resource.TestStep{ { - Config: testAccDeviceFarmProjectConfig(afterInt), + Config: testAccDeviceFarmProjectConfig(rName), 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), + testAccCheckDeviceFarmProjectExists(resourceName, &proj), + testAccCheckResourceDisappears(testAccProvider, resourceAwsDevicefarmProject(), resourceName), ), + ExpectNonEmptyPlan: true, }, }, }) } -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] @@ -103,7 +107,7 @@ func testAccCheckDeviceFarmProjectDestroy(s *terraform.State) error { return nil } - if dferr, ok := err.(awserr.Error); ok && dferr.Code() == "DeviceFarmProjectNotFoundFault" { + if isAWSErr(err, devicefarm.ErrCodeNotFoundException, "") { return nil } } @@ -111,10 +115,10 @@ func testAccCheckDeviceFarmProjectDestroy(s *terraform.State) error { return nil } -func testAccDeviceFarmProjectConfig(rInt int) string { +func testAccDeviceFarmProjectConfig(rName string) string { return fmt.Sprintf(` -resource "aws_devicefarm_project" "foo" { - name = "tf-testproject-%d" +resource "aws_devicefarm_project" "test" { + name = %[1]q } -`, rInt) +`, rName) } diff --git a/aws/resource_aws_directory_service_conditional_forwarder.go b/aws/resource_aws_directory_service_conditional_forwarder.go index 66c4350c946..24fcaea8ada 100644 --- a/aws/resource_aws_directory_service_conditional_forwarder.go +++ b/aws/resource_aws_directory_service_conditional_forwarder.go @@ -6,8 +6,8 @@ import ( "regexp" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/directoryservice" diff --git a/aws/resource_aws_directory_service_conditional_forwarder_test.go b/aws/resource_aws_directory_service_conditional_forwarder_test.go index f0d0c3e4148..4d2a3af5f75 100644 --- a/aws/resource_aws_directory_service_conditional_forwarder_test.go +++ b/aws/resource_aws_directory_service_conditional_forwarder_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/directoryservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSDirectoryServiceConditionForwarder_basic(t *testing.T) { @@ -152,8 +152,8 @@ resource "aws_directory_service_directory" "bar" { edition = "Standard" vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.bar.id}"] + vpc_id = aws_vpc.main.id + subnet_ids = [aws_subnet.foo.id, aws_subnet.bar.id] } tags = { @@ -170,8 +170,8 @@ resource "aws_vpc" "main" { } resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + vpc_id = aws_vpc.main.id + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.1.0/24" tags = { @@ -180,8 +180,8 @@ resource "aws_subnet" "foo" { } resource "aws_subnet" "bar" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" + vpc_id = aws_vpc.main.id + availability_zone = data.aws_availability_zones.available.names[1] cidr_block = "10.0.2.0/24" tags = { @@ -190,7 +190,7 @@ resource "aws_subnet" "bar" { } resource "aws_directory_service_conditional_forwarder" "fwd" { - directory_id = "${aws_directory_service_directory.bar.id}" + directory_id = aws_directory_service_directory.bar.id remote_domain_name = "test.example.com" diff --git a/aws/resource_aws_directory_service_directory.go b/aws/resource_aws_directory_service_directory.go index fcd49045671..369680f3055 100644 --- a/aws/resource_aws_directory_service_directory.go +++ b/aws/resource_aws_directory_service_directory.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/directoryservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -82,6 +82,11 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource { Required: true, ForceNew: true, }, + "availability_zones": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, }, }, }, @@ -92,6 +97,12 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource { ForceNew: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + "connect_ips": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + Set: schema.HashString, + }, "customer_username": { Type: schema.TypeString, Required: true, @@ -101,8 +112,11 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource { Type: schema.TypeSet, Required: true, ForceNew: true, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.IsIPAddress, + }, + Set: schema.HashString, }, "subnet_ids": { Type: schema.TypeSet, @@ -116,6 +130,11 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource { Required: true, ForceNew: true, }, + "availability_zones": { + Type: schema.TypeSet, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, }, }, }, @@ -147,6 +166,7 @@ func resourceAwsDirectoryServiceDirectory() *schema.Resource { directoryservice.DirectoryTypeAdconnector, directoryservice.DirectoryTypeMicrosoftAd, directoryservice.DirectoryTypeSimpleAd, + directoryservice.DirectoryTypeSharedMicrosoftAd, }, false), }, "edition": { @@ -457,17 +477,24 @@ func resourceAwsDirectoryServiceDirectoryRead(d *schema.ResourceData, meta inter d.Set("description", dir.Description) if *dir.Type == directoryservice.DirectoryTypeAdconnector { - d.Set("dns_ip_addresses", schema.NewSet(schema.HashString, flattenStringList(dir.ConnectSettings.ConnectIps))) + d.Set("dns_ip_addresses", flattenStringSet(dir.ConnectSettings.ConnectIps)) } else { - d.Set("dns_ip_addresses", schema.NewSet(schema.HashString, flattenStringList(dir.DnsIpAddrs))) + d.Set("dns_ip_addresses", flattenStringSet(dir.DnsIpAddrs)) } d.Set("name", dir.Name) d.Set("short_name", dir.ShortName) d.Set("size", dir.Size) d.Set("edition", dir.Edition) d.Set("type", dir.Type) - d.Set("vpc_settings", flattenDSVpcSettings(dir.VpcSettings)) - d.Set("connect_settings", flattenDSConnectSettings(dir.DnsIpAddrs, dir.ConnectSettings)) + + if err := d.Set("vpc_settings", flattenDSVpcSettings(dir.VpcSettings)); err != nil { + return fmt.Errorf("error setting VPC settings: %s", err) + } + + if err := d.Set("connect_settings", flattenDSConnectSettings(dir.DnsIpAddrs, dir.ConnectSettings)); err != nil { + return fmt.Errorf("error setting connect settings: %s", err) + } + d.Set("enable_sso", dir.SsoEnabled) if aws.StringValue(dir.Type) == directoryservice.DirectoryTypeAdconnector { diff --git a/aws/resource_aws_directory_service_directory_test.go b/aws/resource_aws_directory_service_directory_test.go index 546265ea1b9..f806dd6f44e 100644 --- a/aws/resource_aws_directory_service_directory_test.go +++ b/aws/resource_aws_directory_service_directory_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/directoryservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -72,6 +72,7 @@ func testSweepDirectoryServiceDirectories(region string) error { } func TestAccAWSDirectoryServiceDirectory_basic(t *testing.T) { + var ds directoryservice.DirectoryDescription resourceName := "aws_directory_service_directory.test" resource.ParallelTest(t, resource.TestCase{ @@ -86,8 +87,8 @@ func TestAccAWSDirectoryServiceDirectory_basic(t *testing.T) { { Config: testAccDirectoryServiceDirectoryConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckServiceDirectoryExists("aws_directory_service_directory.test"), - resource.TestCheckResourceAttrSet("aws_directory_service_directory.test", "security_group_id"), + testAccCheckServiceDirectoryExists(resourceName, &ds), + resource.TestCheckResourceAttrSet(resourceName, "security_group_id"), ), }, { @@ -103,6 +104,7 @@ func TestAccAWSDirectoryServiceDirectory_basic(t *testing.T) { } func TestAccAWSDirectoryServiceDirectory_tags(t *testing.T) { + var ds directoryservice.DirectoryDescription resourceName := "aws_directory_service_directory.test" resource.ParallelTest(t, resource.TestCase{ @@ -117,10 +119,10 @@ func TestAccAWSDirectoryServiceDirectory_tags(t *testing.T) { { Config: testAccDirectoryServiceDirectoryTagsConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckServiceDirectoryExists("aws_directory_service_directory.test"), - resource.TestCheckResourceAttr("aws_directory_service_directory.test", "tags.%", "2"), - resource.TestCheckResourceAttr("aws_directory_service_directory.test", "tags.foo", "test"), - resource.TestCheckResourceAttr("aws_directory_service_directory.test", "tags.project", "test"), + testAccCheckServiceDirectoryExists(resourceName, &ds), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.foo", "test"), + resource.TestCheckResourceAttr(resourceName, "tags.project", "test"), ), }, { @@ -134,19 +136,19 @@ func TestAccAWSDirectoryServiceDirectory_tags(t *testing.T) { { Config: testAccDirectoryServiceDirectoryUpdateTagsConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckServiceDirectoryExists("aws_directory_service_directory.test"), - resource.TestCheckResourceAttr("aws_directory_service_directory.test", "tags.%", "3"), - resource.TestCheckResourceAttr("aws_directory_service_directory.test", "tags.foo", "test"), - resource.TestCheckResourceAttr("aws_directory_service_directory.test", "tags.project", "test2"), - resource.TestCheckResourceAttr("aws_directory_service_directory.test", "tags.fizz", "buzz"), + testAccCheckServiceDirectoryExists(resourceName, &ds), + resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), + resource.TestCheckResourceAttr(resourceName, "tags.foo", "test"), + resource.TestCheckResourceAttr(resourceName, "tags.project", "test2"), + resource.TestCheckResourceAttr(resourceName, "tags.fizz", "buzz"), ), }, { Config: testAccDirectoryServiceDirectoryRemoveTagsConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckServiceDirectoryExists("aws_directory_service_directory.test"), - resource.TestCheckResourceAttr("aws_directory_service_directory.test", "tags.%", "1"), - resource.TestCheckResourceAttr("aws_directory_service_directory.test", "tags.foo", "test"), + testAccCheckServiceDirectoryExists(resourceName, &ds), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.foo", "test"), ), }, }, @@ -154,6 +156,7 @@ func TestAccAWSDirectoryServiceDirectory_tags(t *testing.T) { } func TestAccAWSDirectoryServiceDirectory_microsoft(t *testing.T) { + var ds directoryservice.DirectoryDescription resourceName := "aws_directory_service_directory.test" resource.ParallelTest(t, resource.TestCase{ @@ -164,8 +167,8 @@ func TestAccAWSDirectoryServiceDirectory_microsoft(t *testing.T) { { Config: testAccDirectoryServiceDirectoryConfig_microsoft, Check: resource.ComposeTestCheckFunc( - testAccCheckServiceDirectoryExists("aws_directory_service_directory.test"), - resource.TestCheckResourceAttr("aws_directory_service_directory.test", "edition", directoryservice.DirectoryEditionEnterprise), + testAccCheckServiceDirectoryExists(resourceName, &ds), + resource.TestCheckResourceAttr(resourceName, "edition", directoryservice.DirectoryEditionEnterprise), ), }, { @@ -181,6 +184,7 @@ func TestAccAWSDirectoryServiceDirectory_microsoft(t *testing.T) { } func TestAccAWSDirectoryServiceDirectory_microsoftStandard(t *testing.T) { + var ds directoryservice.DirectoryDescription resourceName := "aws_directory_service_directory.test" resource.ParallelTest(t, resource.TestCase{ @@ -191,8 +195,8 @@ func TestAccAWSDirectoryServiceDirectory_microsoftStandard(t *testing.T) { { Config: testAccDirectoryServiceDirectoryConfig_microsoftStandard, Check: resource.ComposeTestCheckFunc( - testAccCheckServiceDirectoryExists("aws_directory_service_directory.test"), - resource.TestCheckResourceAttr("aws_directory_service_directory.test", "edition", directoryservice.DirectoryEditionStandard), + testAccCheckServiceDirectoryExists(resourceName, &ds), + resource.TestCheckResourceAttr(resourceName, "edition", directoryservice.DirectoryEditionStandard), ), }, { @@ -208,6 +212,7 @@ func TestAccAWSDirectoryServiceDirectory_microsoftStandard(t *testing.T) { } func TestAccAWSDirectoryServiceDirectory_connector(t *testing.T) { + var ds directoryservice.DirectoryDescription resourceName := "aws_directory_service_directory.test" resource.ParallelTest(t, resource.TestCase{ @@ -222,8 +227,9 @@ func TestAccAWSDirectoryServiceDirectory_connector(t *testing.T) { { Config: testAccDirectoryServiceDirectoryConfig_connector, Check: resource.ComposeTestCheckFunc( - testAccCheckServiceDirectoryExists("aws_directory_service_directory.connector"), - resource.TestCheckResourceAttrSet("aws_directory_service_directory.connector", "security_group_id"), + testAccCheckServiceDirectoryExists(resourceName, &ds), + resource.TestCheckResourceAttrSet(resourceName, "security_group_id"), + resource.TestCheckResourceAttrSet(resourceName, "connect_settings.0.connect_ips.#"), ), }, { @@ -239,8 +245,9 @@ func TestAccAWSDirectoryServiceDirectory_connector(t *testing.T) { } func TestAccAWSDirectoryServiceDirectory_withAliasAndSso(t *testing.T) { + var ds directoryservice.DirectoryDescription alias := acctest.RandomWithPrefix("tf-acc-test") - resourceName := "aws_directory_service_directory.test2" + resourceName := "aws_directory_service_directory.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { @@ -254,9 +261,9 @@ func TestAccAWSDirectoryServiceDirectory_withAliasAndSso(t *testing.T) { { Config: testAccDirectoryServiceDirectoryConfig_withAlias(alias), Check: resource.ComposeTestCheckFunc( - testAccCheckServiceDirectoryExists("aws_directory_service_directory.test2"), - testAccCheckServiceDirectoryAlias("aws_directory_service_directory.test2", alias), - testAccCheckServiceDirectorySso("aws_directory_service_directory.test2", false), + testAccCheckServiceDirectoryExists(resourceName, &ds), + testAccCheckServiceDirectoryAlias(resourceName, alias), + testAccCheckServiceDirectorySso(resourceName, false), ), }, { @@ -270,17 +277,17 @@ func TestAccAWSDirectoryServiceDirectory_withAliasAndSso(t *testing.T) { { Config: testAccDirectoryServiceDirectoryConfig_withSso(alias), Check: resource.ComposeTestCheckFunc( - testAccCheckServiceDirectoryExists("aws_directory_service_directory.test2"), - testAccCheckServiceDirectoryAlias("aws_directory_service_directory.test2", alias), - testAccCheckServiceDirectorySso("aws_directory_service_directory.test2", true), + testAccCheckServiceDirectoryExists(resourceName, &ds), + testAccCheckServiceDirectoryAlias(resourceName, alias), + testAccCheckServiceDirectorySso(resourceName, true), ), }, { Config: testAccDirectoryServiceDirectoryConfig_withSso_modified(alias), Check: resource.ComposeTestCheckFunc( - testAccCheckServiceDirectoryExists("aws_directory_service_directory.test2"), - testAccCheckServiceDirectoryAlias("aws_directory_service_directory.test2", alias), - testAccCheckServiceDirectorySso("aws_directory_service_directory.test2", false), + testAccCheckServiceDirectoryExists(resourceName, &ds), + testAccCheckServiceDirectoryAlias(resourceName, alias), + testAccCheckServiceDirectorySso(resourceName, false), ), }, }, @@ -288,7 +295,7 @@ func TestAccAWSDirectoryServiceDirectory_withAliasAndSso(t *testing.T) { } func testAccCheckDirectoryServiceDirectoryDestroy(s *terraform.State) error { - dsconn := testAccProvider.Meta().(*AWSClient).dsconn + conn := testAccProvider.Meta().(*AWSClient).dsconn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_directory_service_directory" { @@ -298,9 +305,9 @@ func testAccCheckDirectoryServiceDirectoryDestroy(s *terraform.State) error { input := directoryservice.DescribeDirectoriesInput{ DirectoryIds: []*string{aws.String(rs.Primary.ID)}, } - out, err := dsconn.DescribeDirectories(&input) + out, err := conn.DescribeDirectories(&input) - if isAWSErr(err, "EntityDoesNotExistException", "") { + if isAWSErr(err, directoryservice.ErrCodeEntityDoesNotExistException, "") { continue } @@ -316,7 +323,32 @@ func testAccCheckDirectoryServiceDirectoryDestroy(s *terraform.State) error { return nil } -func testAccCheckServiceDirectoryExists(name string) resource.TestCheckFunc { +func TestAccAWSDirectoryServiceDirectory_disappears(t *testing.T) { + var ds directoryservice.DirectoryDescription + resourceName := "aws_directory_service_directory.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + testAccPreCheckAWSDirectoryService(t) + testAccPreCheckAWSDirectoryServiceSimpleDirectory(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDirectoryServiceDirectoryDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDirectoryServiceDirectoryConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckServiceDirectoryExists(resourceName, &ds), + testAccCheckResourceDisappears(testAccProvider, resourceAwsDirectoryServiceDirectory(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckServiceDirectoryExists(name string, ds *directoryservice.DirectoryDescription) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[name] if !ok { @@ -327,8 +359,8 @@ func testAccCheckServiceDirectoryExists(name string) resource.TestCheckFunc { return fmt.Errorf("No ID is set") } - dsconn := testAccProvider.Meta().(*AWSClient).dsconn - out, err := dsconn.DescribeDirectories(&directoryservice.DescribeDirectoriesInput{ + conn := testAccProvider.Meta().(*AWSClient).dsconn + out, err := conn.DescribeDirectories(&directoryservice.DescribeDirectoriesInput{ DirectoryIds: []*string{aws.String(rs.Primary.ID)}, }) @@ -345,6 +377,8 @@ func testAccCheckServiceDirectoryExists(name string) resource.TestCheckFunc { *out.DirectoryDescriptions[0].DirectoryId, rs.Primary.ID) } + *ds = *out.DirectoryDescriptions[0] + return nil } } @@ -360,8 +394,8 @@ func testAccCheckServiceDirectoryAlias(name, alias string) resource.TestCheckFun return fmt.Errorf("No ID is set") } - dsconn := testAccProvider.Meta().(*AWSClient).dsconn - out, err := dsconn.DescribeDirectories(&directoryservice.DescribeDirectoriesInput{ + conn := testAccProvider.Meta().(*AWSClient).dsconn + out, err := conn.DescribeDirectories(&directoryservice.DescribeDirectoriesInput{ DirectoryIds: []*string{aws.String(rs.Primary.ID)}, }) @@ -389,8 +423,8 @@ func testAccCheckServiceDirectorySso(name string, ssoEnabled bool) resource.Test return fmt.Errorf("No ID is set") } - dsconn := testAccProvider.Meta().(*AWSClient).dsconn - out, err := dsconn.DescribeDirectories(&directoryservice.DescribeDirectoriesInput{ + conn := testAccProvider.Meta().(*AWSClient).dsconn + out, err := conn.DescribeDirectories(&directoryservice.DescribeDirectoriesInput{ DirectoryIds: []*string{aws.String(rs.Primary.ID)}, }) @@ -446,7 +480,7 @@ func testAccPreCheckAWSDirectoryServiceSimpleDirectory(t *testing.T) { } } -const testAccDirectoryServiceDirectoryConfig = ` +const testAccDirectoryServiceDirectoryConfigBase = ` data "aws_availability_zones" "available" { state = "available" @@ -456,492 +490,197 @@ data "aws_availability_zones" "available" { } } -resource "aws_directory_service_directory" "test" { - name = "corp.notexample.com" - password = "SuperSecretPassw0rd" - size = "Small" - - vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.test.id}"] - } -} - -resource "aws_vpc" "main" { +resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-directory-service-directory" - } + tags = { + Name = "terraform-testacc-directory-service-directory-tags" + } } -resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.0.1.0/24" +resource "aws_subnet" "test1" { + vpc_id = aws_vpc.test.id + availability_zone = data.aws_availability_zones.available.names[0] + cidr_block = "10.0.1.0/24" tags = { Name = "tf-acc-directory-service-directory-foo" } } -resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - cidr_block = "10.0.2.0/24" +resource "aws_subnet" "test2" { + vpc_id = aws_vpc.test.id + availability_zone = data.aws_availability_zones.available.names[1] + cidr_block = "10.0.2.0/24" tags = { Name = "tf-acc-directory-service-directory-test" } } ` -const testAccDirectoryServiceDirectoryTagsConfig = ` -data "aws_availability_zones" "available" { - state = "available" +const testAccDirectoryServiceDirectoryConfig = testAccDirectoryServiceDirectoryConfigBase + ` +resource "aws_directory_service_directory" "test" { + name = "corp.notexample.com" + password = "SuperSecretPassw0rd" + size = "Small" - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] + vpc_settings { + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] } } +` +const testAccDirectoryServiceDirectoryTagsConfig = testAccDirectoryServiceDirectoryConfigBase + ` resource "aws_directory_service_directory" "test" { name = "corp.notexample.com" password = "SuperSecretPassw0rd" size = "Small" vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.test.id}"] + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] } - tags = { - foo = "test" - project = "test" - } -} - -resource "aws_vpc" "main" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-directory-service-directory-tags" - } -} - -resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.0.1.0/24" tags = { - Name = "tf-acc-directory-service-directory-tags-foo" - } -} -resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - cidr_block = "10.0.2.0/24" - tags = { - Name = "tf-acc-directory-service-directory-tags-test" + foo = "test" + project = "test" } } ` -const testAccDirectoryServiceDirectoryUpdateTagsConfig = ` -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - +const testAccDirectoryServiceDirectoryUpdateTagsConfig = testAccDirectoryServiceDirectoryConfigBase + ` resource "aws_directory_service_directory" "test" { - name = "corp.notexample.com" + name = "corp.notexample.com" password = "SuperSecretPassw0rd" - size = "Small" + size = "Small" vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.test.id}"] + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] } - tags = { - foo = "test" - project = "test2" - fizz = "buzz" - } -} - -resource "aws_vpc" "main" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-directory-service-directory-tags" - } -} - -resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.0.1.0/24" tags = { - Name = "tf-acc-directory-service-directory-tags-foo" - } -} -resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - cidr_block = "10.0.2.0/24" - tags = { - Name = "tf-acc-directory-service-directory-tags-test" + foo = "test" + project = "test2" + fizz = "buzz" } } ` -const testAccDirectoryServiceDirectoryRemoveTagsConfig = ` -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - +const testAccDirectoryServiceDirectoryRemoveTagsConfig = testAccDirectoryServiceDirectoryConfigBase + ` resource "aws_directory_service_directory" "test" { name = "corp.notexample.com" password = "SuperSecretPassw0rd" size = "Small" vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.test.id}"] + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] } - tags = { - foo = "test" - } -} - -resource "aws_vpc" "main" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-directory-service-directory-tags" - } -} - -resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.0.1.0/24" tags = { - Name = "tf-acc-directory-service-directory-tags-foo" - } -} -resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - cidr_block = "10.0.2.0/24" - tags = { - Name = "tf-acc-directory-service-directory-tags-test" + foo = "test" } } ` -const testAccDirectoryServiceDirectoryConfig_connector = ` -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - -resource "aws_directory_service_directory" "test" { +const testAccDirectoryServiceDirectoryConfig_connector = testAccDirectoryServiceDirectoryConfigBase + ` +resource "aws_directory_service_directory" "base" { name = "corp.notexample.com" password = "SuperSecretPassw0rd" size = "Small" vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.test.id}"] + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] } } -resource "aws_directory_service_directory" "connector" { - name = "corp.notexample.com" +resource "aws_directory_service_directory" "test" { + name = "corp.notexample.com" password = "SuperSecretPassw0rd" - size = "Small" - type = "ADConnector" + size = "Small" + type = "ADConnector" connect_settings { - customer_dns_ips = aws_directory_service_directory.test.dns_ip_addresses + customer_dns_ips = aws_directory_service_directory.base.dns_ip_addresses customer_username = "Administrator" - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.test.id}"] - } -} - -resource "aws_vpc" "main" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-directory-service-directory-connector" - } -} - -resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.0.1.0/24" - tags = { - Name = "tf-acc-directory-service-directory-connector-foo" - } -} -resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - cidr_block = "10.0.2.0/24" - tags = { - Name = "tf-acc-directory-service-directory-connector-test" + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] } } ` -const testAccDirectoryServiceDirectoryConfig_microsoft = ` -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - +const testAccDirectoryServiceDirectoryConfig_microsoft = testAccDirectoryServiceDirectoryConfigBase + ` resource "aws_directory_service_directory" "test" { - name = "corp.notexample.com" + name = "corp.notexample.com" password = "SuperSecretPassw0rd" - type = "MicrosoftAD" + type = "MicrosoftAD" vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.test.id}"] - } -} - -resource "aws_vpc" "main" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-directory-service-directory-microsoft" - } -} - -resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.0.1.0/24" - tags = { - Name = "tf-acc-directory-service-directory-microsoft-foo" - } -} -resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - cidr_block = "10.0.2.0/24" - tags = { - Name = "tf-acc-directory-service-directory-microsoft-test" + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] } } ` -const testAccDirectoryServiceDirectoryConfig_microsoftStandard = ` -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - +const testAccDirectoryServiceDirectoryConfig_microsoftStandard = testAccDirectoryServiceDirectoryConfigBase + ` resource "aws_directory_service_directory" "test" { - name = "corp.notexample.com" + name = "corp.notexample.com" password = "SuperSecretPassw0rd" - type = "MicrosoftAD" - edition = "Standard" + type = "MicrosoftAD" + edition = "Standard" vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.test.id}"] - } -} - -resource "aws_vpc" "main" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-directory-service-directory-microsoft" - } -} - -resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.0.1.0/24" - tags = { - Name = "tf-acc-directory-service-directory-microsoft-foo" - } -} -resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - cidr_block = "10.0.2.0/24" - tags = { - Name = "tf-acc-directory-service-directory-microsoft-test" + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] } } ` func testAccDirectoryServiceDirectoryConfig_withAlias(alias string) string { - return fmt.Sprintf(` -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - -resource "aws_directory_service_directory" "test2" { - name = "corp.notexample.com" + return testAccDirectoryServiceDirectoryConfigBase + fmt.Sprintf(` +resource "aws_directory_service_directory" "test" { + name = "corp.notexample.com" password = "SuperSecretPassw0rd" - size = "Small" - alias = %[1]q + size = "Small" + alias = %[1]q vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.test.id}"] - } -} - -resource "aws_vpc" "main" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-directory-service-directory-with-alias" - } -} - -resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.0.1.0/24" - tags = { - Name = "tf-acc-directory-service-directory-with-alias-foo" - } -} -resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - cidr_block = "10.0.2.0/24" - tags = { - Name = "tf-acc-directory-service-directory-with-alias-test" + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] } } `, alias) } func testAccDirectoryServiceDirectoryConfig_withSso(alias string) string { - return fmt.Sprintf(` -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - -resource "aws_directory_service_directory" "test2" { - name = "corp.notexample.com" - password = "SuperSecretPassw0rd" - size = "Small" - alias = %[1]q + return testAccDirectoryServiceDirectoryConfigBase + fmt.Sprintf(` +resource "aws_directory_service_directory" "test" { + name = "corp.notexample.com" + password = "SuperSecretPassw0rd" + size = "Small" + alias = %[1]q enable_sso = true vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.test.id}"] - } -} - -resource "aws_vpc" "main" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-directory-service-directory-with-sso" - } -} - -resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.0.1.0/24" - tags = { - Name = "tf-acc-directory-service-directory-with-sso-foo" - } -} -resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - cidr_block = "10.0.2.0/24" - tags = { - Name = "tf-acc-directory-service-directory-with-sso-test" + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] } } `, alias) } func testAccDirectoryServiceDirectoryConfig_withSso_modified(alias string) string { - return fmt.Sprintf(` -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - -resource "aws_directory_service_directory" "test2" { - name = "corp.notexample.com" - password = "SuperSecretPassw0rd" - size = "Small" - alias = %[1]q + return testAccDirectoryServiceDirectoryConfigBase + fmt.Sprintf(` +resource "aws_directory_service_directory" "test" { + name = "corp.notexample.com" + password = "SuperSecretPassw0rd" + size = "Small" + alias = %[1]q enable_sso = false vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.test.id}"] - } -} - -resource "aws_vpc" "main" { - cidr_block = "10.0.0.0/16" - tags = { - Name = "terraform-testacc-directory-service-directory-with-sso-modified" - } -} - -resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cidr_block = "10.0.1.0/24" - tags = { - Name = "tf-acc-directory-service-directory-with-sso-foo" - } -} -resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - cidr_block = "10.0.2.0/24" - tags = { - Name = "tf-acc-directory-service-directory-with-sso-test" + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test1.id, aws_subnet.test2.id] } } `, alias) diff --git a/aws/resource_aws_directory_service_log_subscription.go b/aws/resource_aws_directory_service_log_subscription.go index b000cd28d64..a38e07b119e 100644 --- a/aws/resource_aws_directory_service_log_subscription.go +++ b/aws/resource_aws_directory_service_log_subscription.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/directoryservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsDirectoryServiceLogSubscription() *schema.Resource { diff --git a/aws/resource_aws_directory_service_log_subscription_test.go b/aws/resource_aws_directory_service_log_subscription_test.go index 0b455330f94..2799e9bf359 100644 --- a/aws/resource_aws_directory_service_log_subscription_test.go +++ b/aws/resource_aws_directory_service_log_subscription_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/directoryservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSDirectoryServiceLogSubscription_basic(t *testing.T) { @@ -119,8 +119,8 @@ resource "aws_directory_service_directory" "bar" { edition = "Standard" vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.foo.id}", "${aws_subnet.bar.id}"] + vpc_id = aws_vpc.main.id + subnet_ids = [aws_subnet.foo.id, aws_subnet.bar.id] } tags = { @@ -137,8 +137,8 @@ resource "aws_vpc" "main" { } resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + vpc_id = aws_vpc.main.id + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.1.0/24" tags = { @@ -147,8 +147,8 @@ resource "aws_subnet" "foo" { } resource "aws_subnet" "bar" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "${data.aws_availability_zones.available.names[1]}" + vpc_id = aws_vpc.main.id + availability_zone = data.aws_availability_zones.available.names[1] cidr_block = "10.0.2.0/24" tags = { @@ -157,7 +157,7 @@ resource "aws_subnet" "bar" { } resource "aws_cloudwatch_log_group" "logs" { - name = "%s" + name = "%s" retention_in_days = 1 } @@ -165,28 +165,28 @@ data "aws_iam_policy_document" "ad-log-policy" { statement { actions = [ "logs:CreateLogStream", - "logs:PutLogEvents" + "logs:PutLogEvents", ] - + principals { identifiers = ["ds.amazonaws.com"] - type = "Service" + type = "Service" } - - resources = ["${aws_cloudwatch_log_group.logs.arn}"] - + + resources = ["${aws_cloudwatch_log_group.logs.arn}:*"] + effect = "Allow" } } - + resource "aws_cloudwatch_log_resource_policy" "ad-log-policy" { - policy_document = "${data.aws_iam_policy_document.ad-log-policy.json}" - policy_name = "ad-log-policy" + policy_document = data.aws_iam_policy_document.ad-log-policy.json + policy_name = "ad-log-policy" } resource "aws_directory_service_log_subscription" "subscription" { - directory_id = "${aws_directory_service_directory.bar.id}" - log_group_name = "${aws_cloudwatch_log_group.logs.name}" + directory_id = aws_directory_service_directory.bar.id + log_group_name = aws_cloudwatch_log_group.logs.name } `, logGroupName) } diff --git a/aws/resource_aws_dlm_lifecycle_policy.go b/aws/resource_aws_dlm_lifecycle_policy.go index 9c3f27ad115..194dbb6066a 100644 --- a/aws/resource_aws_dlm_lifecycle_policy.go +++ b/aws/resource_aws_dlm_lifecycle_policy.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dlm" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -115,6 +115,7 @@ func resourceAwsDlmLifecyclePolicy() *schema.Resource { "tags_to_add": { Type: schema.TypeMap, Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, }, }, @@ -122,6 +123,7 @@ func resourceAwsDlmLifecyclePolicy() *schema.Resource { "target_tags": { Type: schema.TypeMap, Required: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, }, }, diff --git a/aws/resource_aws_dlm_lifecycle_policy_test.go b/aws/resource_aws_dlm_lifecycle_policy_test.go index 10b84f5be56..fe009b0c337 100644 --- a/aws/resource_aws_dlm_lifecycle_policy_test.go +++ b/aws/resource_aws_dlm_lifecycle_policy_test.go @@ -7,12 +7,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dlm" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAWSDlmLifecyclePolicy_Basic(t *testing.T) { +func TestAccAWSDlmLifecyclePolicy_basic(t *testing.T) { resourceName := "aws_dlm_lifecycle_policy.basic" rName := acctest.RandomWithPrefix("tf-acc-test") @@ -229,11 +229,12 @@ resource "aws_iam_role" "dlm_lifecycle_role" { ] } EOF + } resource "aws_dlm_lifecycle_policy" "basic" { description = "tf-acc-basic" - execution_role_arn = "${aws_iam_role.dlm_lifecycle_role.arn}" + execution_role_arn = aws_iam_role.dlm_lifecycle_role.arn policy_details { resource_types = ["VOLUME"] @@ -278,11 +279,12 @@ resource "aws_iam_role" "dlm_lifecycle_role" { ] } EOF + } resource "aws_dlm_lifecycle_policy" "full" { description = "tf-acc-full" - execution_role_arn = "${aws_iam_role.dlm_lifecycle_role.arn}" + execution_role_arn = aws_iam_role.dlm_lifecycle_role.arn state = "ENABLED" policy_details { @@ -336,6 +338,7 @@ resource "aws_iam_role" "dlm_lifecycle_role" { ] } EOF + } resource "aws_dlm_lifecycle_policy" "full" { diff --git a/aws/resource_aws_dms_certificate.go b/aws/resource_aws_dms_certificate.go index 3b60802270d..c0a9849f752 100644 --- a/aws/resource_aws_dms_certificate.go +++ b/aws/resource_aws_dms_certificate.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsDmsCertificate() *schema.Resource { diff --git a/aws/resource_aws_dms_certificate_test.go b/aws/resource_aws_dms_certificate_test.go index b82e719f02b..9d7d99ccd99 100644 --- a/aws/resource_aws_dms_certificate_test.go +++ b/aws/resource_aws_dms_certificate_test.go @@ -6,13 +6,13 @@ import ( "github.com/aws/aws-sdk-go/aws" dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAWSDmsCertificateBasic(t *testing.T) { +func TestAccAWSDmsCertificate_basic(t *testing.T) { resourceName := "aws_dms_certificate.dms_certificate" randId := acctest.RandString(8) diff --git a/aws/resource_aws_dms_endpoint.go b/aws/resource_aws_dms_endpoint.go index 3be6a980bed..cc67a6d5789 100644 --- a/aws/resource_aws_dms_endpoint.go +++ b/aws/resource_aws_dms_endpoint.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -588,17 +588,10 @@ func resourceAwsDmsEndpointUpdate(d *schema.ResourceData, meta interface{}) erro hasChanges = true } case "mongodb": - if d.HasChange("username") || - d.HasChange("password") || - d.HasChange("server_name") || - d.HasChange("port") || - d.HasChange("database_name") || - d.HasChange("mongodb_settings.0.auth_type") || - d.HasChange("mongodb_settings.0.auth_mechanism") || - d.HasChange("mongodb_settings.0.nesting_level") || - d.HasChange("mongodb_settings.0.extract_doc_id") || - d.HasChange("mongodb_settings.0.docs_to_investigate") || - d.HasChange("mongodb_settings.0.auth_source") { + if d.HasChanges( + "username", "password", "server_name", "port", "database_name", "mongodb_settings.0.auth_type", + "mongodb_settings.0.auth_mechanism", "mongodb_settings.0.nesting_level", "mongodb_settings.0.extract_doc_id", + "mongodb_settings.0.docs_to_investigate", "mongodb_settings.0.auth_source") { request.MongoDbSettings = &dms.MongoDbSettings{ Username: aws.String(d.Get("username").(string)), Password: aws.String(d.Get("password").(string)), @@ -626,13 +619,10 @@ func resourceAwsDmsEndpointUpdate(d *schema.ResourceData, meta interface{}) erro hasChanges = true } case "s3": - if d.HasChange("s3_settings.0.service_access_role_arn") || - d.HasChange("s3_settings.0.external_table_definition") || - d.HasChange("s3_settings.0.csv_row_delimiter") || - d.HasChange("s3_settings.0.csv_delimiter") || - d.HasChange("s3_settings.0.bucket_folder") || - d.HasChange("s3_settings.0.bucket_name") || - d.HasChange("s3_settings.0.compression_type") { + if d.HasChanges( + "s3_settings.0.service_access_role_arn", "s3_settings.0.external_table_definition", + "s3_settings.0.csv_row_delimiter", "s3_settings.0.csv_delimiter", "s3_settings.0.bucket_folder", + "s3_settings.0.bucket_name", "s3_settings.0.compression_type") { request.S3Settings = &dms.S3Settings{ ServiceAccessRoleArn: aws.String(d.Get("s3_settings.0.service_access_role_arn").(string)), ExternalTableDefinition: aws.String(d.Get("s3_settings.0.external_table_definition").(string)), diff --git a/aws/resource_aws_dms_endpoint_test.go b/aws/resource_aws_dms_endpoint_test.go index 2c951e13c00..b93ef43afd0 100644 --- a/aws/resource_aws_dms_endpoint_test.go +++ b/aws/resource_aws_dms_endpoint_test.go @@ -6,12 +6,12 @@ import ( "github.com/aws/aws-sdk-go/aws" dms "github.com/aws/aws-sdk-go/service/databasemigrationservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAwsDmsEndpoint_Basic(t *testing.T) { +func TestAccAwsDmsEndpoint_basic(t *testing.T) { resourceName := "aws_dms_endpoint.dms_endpoint" randId := acctest.RandString(8) + "-basic" @@ -564,7 +564,7 @@ resource "aws_dms_endpoint" "dms_endpoint" { endpoint_id = "tf-test-dms-endpoint-%[1]s" endpoint_type = "target" engine_name = "dynamodb" - service_access_role = "${aws_iam_role.iam_role.arn}" + service_access_role = aws_iam_role.iam_role.arn ssl_mode = "none" tags = { @@ -573,7 +573,7 @@ resource "aws_dms_endpoint" "dms_endpoint" { Remove = "to-remove" } - depends_on = ["aws_iam_role_policy.dms_dynamodb_access"] + depends_on = [aws_iam_role_policy.dms_dynamodb_access] } resource "aws_iam_role" "iam_role" { @@ -593,11 +593,12 @@ resource "aws_iam_role" "iam_role" { ] } EOF + } resource "aws_iam_role_policy" "dms_dynamodb_access" { name = "tf-test-iam-dynamodb-role-policy-%[1]s" - role = "${aws_iam_role.iam_role.name}" + role = aws_iam_role.iam_role.name policy = < 0 { // We can only modify 20 parameters at a time, so walk them until // we've got them all. diff --git a/aws/resource_aws_docdb_cluster_parameter_group_test.go b/aws/resource_aws_docdb_cluster_parameter_group_test.go index f7697e7f0e2..e38bc9429c8 100644 --- a/aws/resource_aws_docdb_cluster_parameter_group_test.go +++ b/aws/resource_aws_docdb_cluster_parameter_group_test.go @@ -8,9 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/docdb" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSDocDBClusterParameterGroup_basic(t *testing.T) { @@ -152,10 +153,9 @@ func TestAccAWSDocDBClusterParameterGroup_Parameter(t *testing.T) { parameterGroupName := fmt.Sprintf("cluster-parameter-group-test-tf-%d", acctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSDocDBClusterParameterGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDocDBClusterParameterGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSDocDBClusterParameterGroupConfig_Parameter(parameterGroupName, "tls", "disabled"), @@ -163,9 +163,11 @@ func TestAccAWSDocDBClusterParameterGroup_Parameter(t *testing.T) { testAccCheckAWSDocDBClusterParameterGroupExists(resourceName, &v), testAccCheckAWSDocDBClusterParameterGroupAttributes(&v, parameterGroupName), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), - resource.TestCheckResourceAttr(resourceName, "parameter.3297634353.apply_method", "pending-reboot"), - resource.TestCheckResourceAttr(resourceName, "parameter.3297634353.name", "tls"), - resource.TestCheckResourceAttr(resourceName, "parameter.3297634353.value", "disabled"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "apply_method": "pending-reboot", + "name": "tls", + "value": "disabled", + }), ), }, { @@ -179,9 +181,11 @@ func TestAccAWSDocDBClusterParameterGroup_Parameter(t *testing.T) { testAccCheckAWSDocDBClusterParameterGroupExists(resourceName, &v), testAccCheckAWSDocDBClusterParameterGroupAttributes(&v, parameterGroupName), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), - resource.TestCheckResourceAttr(resourceName, "parameter.4005179180.apply_method", "pending-reboot"), - resource.TestCheckResourceAttr(resourceName, "parameter.4005179180.name", "tls"), - resource.TestCheckResourceAttr(resourceName, "parameter.4005179180.value", "enabled"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "apply_method": "pending-reboot", + "name": "tls", + "value": "enabled", + }), ), }, }, @@ -382,11 +386,11 @@ resource "aws_docdb_cluster_parameter_group" "bar" { const testAccAWSDocDBClusterParameterGroupConfig_namePrefix = ` resource "aws_docdb_cluster_parameter_group" "test" { name_prefix = "tf-test-" - family = "docdb3.6" + family = "docdb3.6" } ` const testAccAWSDocDBClusterParameterGroupConfig_generatedName = ` resource "aws_docdb_cluster_parameter_group" "test" { - family = "docdb3.6" + family = "docdb3.6" } ` diff --git a/aws/resource_aws_docdb_cluster_snapshot.go b/aws/resource_aws_docdb_cluster_snapshot.go index 73f84036142..441e82d9d1e 100644 --- a/aws/resource_aws_docdb_cluster_snapshot.go +++ b/aws/resource_aws_docdb_cluster_snapshot.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/docdb" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsDocDBClusterSnapshot() *schema.Resource { diff --git a/aws/resource_aws_docdb_cluster_snapshot_test.go b/aws/resource_aws_docdb_cluster_snapshot_test.go index 6afa257748a..f1a24da3e28 100644 --- a/aws/resource_aws_docdb_cluster_snapshot_test.go +++ b/aws/resource_aws_docdb_cluster_snapshot_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/docdb" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSDocDBClusterSnapshot_basic(t *testing.T) { @@ -130,9 +130,9 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { count = 2 - availability_zone = "${data.aws_availability_zones.available.names[count.index]}" + availability_zone = data.aws_availability_zones.available.names[count.index] cidr_block = "192.168.${count.index}.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = %q @@ -141,19 +141,19 @@ resource "aws_subnet" "test" { resource "aws_docdb_subnet_group" "test" { name = %q - subnet_ids = ["${aws_subnet.test.*.id[0]}", "${aws_subnet.test.*.id[1]}"] + subnet_ids = [aws_subnet.test[0].id, aws_subnet.test[1].id] } resource "aws_docdb_cluster" "test" { cluster_identifier = %q - db_subnet_group_name = "${aws_docdb_subnet_group.test.name}" + db_subnet_group_name = aws_docdb_subnet_group.test.name master_password = "barbarbarbar" master_username = "foo" skip_final_snapshot = true } resource "aws_docdb_cluster_snapshot" "test" { - db_cluster_identifier = "${aws_docdb_cluster.test.id}" + db_cluster_identifier = aws_docdb_cluster.test.id db_cluster_snapshot_identifier = %q } `, rName, rName, rName, rName, rName) diff --git a/aws/resource_aws_docdb_cluster_test.go b/aws/resource_aws_docdb_cluster_test.go index 222a33cc854..814d0275b3c 100644 --- a/aws/resource_aws_docdb_cluster_test.go +++ b/aws/resource_aws_docdb_cluster_test.go @@ -7,10 +7,10 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" @@ -622,9 +622,9 @@ func testAccDocDBClusterConfig_namePrefix() string { return ` resource "aws_docdb_cluster" "test" { cluster_identifier_prefix = "tf-test-" - master_username = "root" - master_password = "password" - skip_final_snapshot = true + master_username = "root" + master_password = "password" + skip_final_snapshot = true } ` } @@ -632,8 +632,8 @@ resource "aws_docdb_cluster" "test" { func testAccDocDBClusterConfig_generatedName() string { return ` resource "aws_docdb_cluster" "test" { - master_username = "root" - master_password = "password" + master_username = "root" + master_password = "password" skip_final_snapshot = true } ` @@ -703,48 +703,48 @@ resource "aws_docdb_cluster" "default" { func testAccDocDBClusterConfig_kmsKey(n int) string { return fmt.Sprintf(` +resource "aws_kms_key" "foo" { + description = "Terraform acc test %d" + policy = < 0 { - log.Printf("[WARN] IOPs is only valid for storate type io1 for EBS Volumes") - } else if t == ec2.VolumeTypeIo1 { + if iops := d.Get("iops").(int); iops > 0 { + if t != ec2.VolumeTypeIo1 { + if t == "" { + // Volume creation would default to gp2 + t = ec2.VolumeTypeGp2 + } + return fmt.Errorf("error creating ebs_volume: iops attribute not supported for type %s", t) + } // We add the iops value without validating it's size, to allow AWS to // enforce a size requirement (currently 100) request.Iops = aws.Int64(int64(iops)) } - log.Printf( - "[DEBUG] EBS Volume create opts: %s", request) + log.Printf("[DEBUG] EBS Volume create opts: %s", request) result, err := conn.CreateVolume(request) if err != nil { return fmt.Errorf("Error creating EC2 volume: %s", err) diff --git a/aws/resource_aws_ebs_volume_test.go b/aws/resource_aws_ebs_volume_test.go index bb0bf6d7c52..0f7b7a32c46 100644 --- a/aws/resource_aws_ebs_volume_test.go +++ b/aws/resource_aws_ebs_volume_test.go @@ -3,15 +3,14 @@ package aws import ( "fmt" "log" - "os" "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -287,6 +286,22 @@ func TestAccAWSEBSVolume_NoIops(t *testing.T) { }) } +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/12667 +func TestAccAWSEBSVolume_InvalidIopsForType(t *testing.T) { + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckVolumeDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsEbsVolumeConfigWithInvalidIopsForType, + ExpectError: regexp.MustCompile(`error creating ebs_volume: iops attribute not supported for type gp2`), + }, + }, + }) +} + func TestAccAWSEBSVolume_withTags(t *testing.T) { var v ec2.Volume resourceName := "aws_ebs_volume.test" @@ -343,27 +358,20 @@ func TestAccAWSEBSVolume_multiAttach(t *testing.T) { func TestAccAWSEBSVolume_outpost(t *testing.T) { var v ec2.Volume + outpostDataSourceName := "data.aws_outposts_outpost.test" resourceName := "aws_ebs_volume.test" - outpostArn := os.Getenv("AWS_OUTPOST_ARN") - if outpostArn == "" { - t.Skip( - "Environment variable AWS_OUTPOST_ARN is not set. " + - "This environment variable must be set to the ARN of " + - "a deployed Outpost to enable this test.") - } - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, IDRefreshName: resourceName, Providers: testAccProviders, CheckDestroy: testAccCheckVolumeDestroy, Steps: []resource.TestStep{ { - Config: testAccAwsEbsVolumeConfigOutpost(outpostArn), + Config: testAccAwsEbsVolumeConfigOutpost(), Check: resource.ComposeTestCheckFunc( testAccCheckVolumeExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "outpost_arn", outpostArn), + resource.TestCheckResourceAttrPair(resourceName, "outpost_arn", outpostDataSourceName, "arn"), ), }, { @@ -467,9 +475,9 @@ data "aws_availability_zones" "available" { } resource "aws_ebs_volume" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" - type = "gp2" - size = 1 + availability_zone = data.aws_availability_zones.available.names[0] + type = "gp2" + size = 1 } ` @@ -501,7 +509,7 @@ data "aws_ami" "debian_jessie_latest" { } resource "aws_instance" "test" { - ami = "${data.aws_ami.debian_jessie_latest.id}" + ami = data.aws_ami.debian_jessie_latest.id instance_type = "t2.medium" root_block_device { @@ -525,17 +533,17 @@ data "aws_availability_zones" "available" { } resource "aws_ebs_volume" "test" { - depends_on = ["aws_instance.test"] - availability_zone = "${aws_instance.test.availability_zone}" - type = "gp2" - size = "10" + 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"] + depends_on = [aws_ebs_volume.test] device_name = "/dev/xvdg" - volume_id = "${aws_ebs_volume.test.id}" - instance_id = "${aws_instance.test.id}" + volume_id = aws_ebs_volume.test.id + instance_id = aws_instance.test.id } ` @@ -567,7 +575,7 @@ data "aws_ami" "debian_jessie_latest" { } resource "aws_instance" "test" { - ami = "${data.aws_ami.debian_jessie_latest.id}" + ami = data.aws_ami.debian_jessie_latest.id instance_type = "t2.medium" root_block_device { @@ -577,22 +585,22 @@ resource "aws_instance" "test" { } tags = { - Name = "test-terraform" + Name = "test-terraform" } } resource "aws_ebs_volume" "test" { - depends_on = ["aws_instance.test"] - availability_zone = "${aws_instance.test.availability_zone}" - type = "gp2" - size = "20" + 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"] + depends_on = [aws_ebs_volume.test] device_name = "/dev/xvdg" - volume_id = "${aws_ebs_volume.test.id}" - instance_id = "${aws_instance.test.id}" + volume_id = aws_ebs_volume.test.id + instance_id = aws_instance.test.id } ` @@ -607,9 +615,10 @@ data "aws_availability_zones" "available" { } resource "aws_ebs_volume" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" - type = "gp2" - size = 10 + availability_zone = data.aws_availability_zones.available.names[0] + type = "gp2" + size = 10 + tags = { Name = "tf-acc-test-ebs-volume-test" } @@ -627,9 +636,10 @@ data "aws_availability_zones" "available" { } resource "aws_ebs_volume" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" - type = "sc1" - size = 500 + availability_zone = data.aws_availability_zones.available.names[0] + type = "sc1" + size = 500 + tags = { Name = "tf-acc-test-ebs-volume-test" } @@ -647,10 +657,11 @@ data "aws_availability_zones" "available" { } resource "aws_ebs_volume" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" - type = "io1" - size = 4 - iops = 100 + availability_zone = data.aws_availability_zones.available.names[0] + type = "io1" + size = 4 + iops = 100 + tags = { Name = "tf-acc-test-ebs-volume-test" } @@ -668,10 +679,11 @@ data "aws_availability_zones" "available" { } resource "aws_ebs_volume" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" - type = "io1" - size = 4 - iops = 200 + availability_zone = data.aws_availability_zones.available.names[0] + type = "io1" + size = 4 + iops = 200 + tags = { Name = "tf-acc-test-ebs-volume-test" } @@ -681,7 +693,7 @@ resource "aws_ebs_volume" "test" { const testAccAwsEbsVolumeConfigWithKmsKey = ` resource "aws_kms_key" "test" { description = "Terraform acc test %d" - policy = < 1 { + return fmt.Errorf("internal error: found %d results for Client VPN route (%s) status, need 1", len(resp.Routes), d.Id()) + } + + route := resp.Routes[0] + d.Set("client_vpn_endpoint_id", route.ClientVpnEndpointId) + d.Set("destination_cidr_block", route.DestinationCidr) + d.Set("description", route.Description) + d.Set("target_vpc_subnet_id", route.TargetSubnet) + d.Set("origin", route.Origin) + d.Set("type", route.Type) + + return nil +} + +func resourceAwsEc2ClientVpnRouteDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + err := deleteClientVpnRoute(conn, &ec2.DeleteClientVpnRouteInput{ + ClientVpnEndpointId: aws.String(d.Get("client_vpn_endpoint_id").(string)), + DestinationCidrBlock: aws.String(d.Get("destination_cidr_block").(string)), + TargetVpcSubnetId: aws.String(d.Get("target_vpc_subnet_id").(string)), + }) + if err != nil { + return fmt.Errorf("error deleting client VPN route %q: %w", d.Id(), err) + } + + return nil +} + +func deleteClientVpnRoute(conn *ec2.EC2, input *ec2.DeleteClientVpnRouteInput) error { + id := tfec2.ClientVpnRouteCreateID( + aws.StringValue(input.ClientVpnEndpointId), + aws.StringValue(input.TargetVpcSubnetId), + aws.StringValue(input.DestinationCidrBlock), + ) + + _, err := conn.DeleteClientVpnRoute(input) + if isAWSErr(err, tfec2.ErrCodeClientVpnRouteNotFound, "") { + return nil + } + if err != nil { + return err + } + + _, err = waiter.ClientVpnRouteDeleted(conn, id) + + return err +} + +func resourceAwsEc2ClientVpnRouteImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + endpointID, targetSubnetID, destinationCidr, err := tfec2.ClientVpnRouteParseID(d.Id()) + if err != nil { + return nil, err + } + + d.Set("client_vpn_endpoint_id", endpointID) + d.Set("target_vpc_subnet_id", targetSubnetID) + d.Set("destination_cidr_block", destinationCidr) + + return []*schema.ResourceData{d}, nil +} diff --git a/aws/resource_aws_ec2_client_vpn_route_test.go b/aws/resource_aws_ec2_client_vpn_route_test.go new file mode 100644 index 00000000000..e7a1b263736 --- /dev/null +++ b/aws/resource_aws_ec2_client_vpn_route_test.go @@ -0,0 +1,269 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + tfec2 "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/ec2" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/ec2/finder" +) + +func testAccAwsEc2ClientVpnRoute_basic(t *testing.T) { + var v ec2.ClientVpnRoute + rStr := acctest.RandString(5) + + resourceName := "aws_ec2_client_vpn_route.test" + endpointResourceName := "aws_ec2_client_vpn_endpoint.test" + subnetResourceName := "aws_subnet.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheckClientVPNSyncronize(t); testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsEc2ClientVpnRouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEc2ClientVpnRouteConfigBasic(rStr), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEc2ClientVpnRouteExists(resourceName, &v), + resource.TestCheckResourceAttrPair(resourceName, "client_vpn_endpoint_id", endpointResourceName, "id"), + resource.TestCheckResourceAttrPair(resourceName, "target_vpc_subnet_id", subnetResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "destination_cidr_block", "0.0.0.0/0"), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "origin", "add-route"), + resource.TestCheckResourceAttr(resourceName, "type", "Nat"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccAwsEc2ClientVpnRoute_description(t *testing.T) { + var v ec2.ClientVpnRoute + rStr := acctest.RandString(5) + + resourceName := "aws_ec2_client_vpn_route.test" + endpointResourceName := "aws_ec2_client_vpn_endpoint.test" + subnetResourceName := "aws_subnet.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheckClientVPNSyncronize(t); testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsEc2ClientVpnRouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEc2ClientVpnRouteConfigDescription(rStr), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEc2ClientVpnRouteExists(resourceName, &v), + resource.TestCheckResourceAttrPair(resourceName, "client_vpn_endpoint_id", endpointResourceName, "id"), + resource.TestCheckResourceAttrPair(resourceName, "target_vpc_subnet_id", subnetResourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "description", "test client VPN route"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccAwsEc2ClientVpnRoute_disappears(t *testing.T) { + var v ec2.ClientVpnRoute + rStr := acctest.RandString(5) + + resourceName := "aws_ec2_client_vpn_route.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheckClientVPNSyncronize(t); testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsEc2ClientVpnRouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEc2ClientVpnRouteConfigBasic(rStr), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEc2ClientVpnRouteExists(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEc2ClientVpnRoute(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckAwsEc2ClientVpnRouteDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_ec2_client_vpn_route" { + continue + } + + _, err := finder.ClientVpnRouteByID(conn, rs.Primary.ID) + if err == nil { + return fmt.Errorf("Client VPN route (%s) still exists", rs.Primary.ID) + } + if isAWSErr(err, tfec2.ErrCodeClientVpnRouteNotFound, "") { + continue + } + } + + return nil +} + +func testAccCheckAwsEc2ClientVpnRouteExists(name string, route *ec2.ClientVpnRoute) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + resp, err := finder.ClientVpnRouteByID(conn, rs.Primary.ID) + if err != nil { + return fmt.Errorf("Error reading Client VPN route (%s): %w", rs.Primary.ID, err) + } + + if resp != nil || len(resp.Routes) == 1 || resp.Routes[0] != nil { + *route = *resp.Routes[0] + return nil + } + + return fmt.Errorf("Client VPN route (%s) not found", rs.Primary.ID) + } +} + +func testAccEc2ClientVpnRouteConfigBasic(rName string) string { + return composeConfig( + testAccEc2ClientVpnRouteVpcBase(rName, 1), + testAccEc2ClientVpnRouteAcmCertificateBase(), + fmt.Sprintf(` +resource "aws_ec2_client_vpn_route" "test" { + client_vpn_endpoint_id = aws_ec2_client_vpn_endpoint.test.id + destination_cidr_block = "0.0.0.0/0" + target_vpc_subnet_id = aws_subnet.test[0].id + + depends_on = [ + aws_ec2_client_vpn_network_association.test, + ] +} + +resource "aws_ec2_client_vpn_network_association" "test" { + client_vpn_endpoint_id = aws_ec2_client_vpn_endpoint.test.id + subnet_id = aws_subnet.test[0].id +} + +resource "aws_ec2_client_vpn_endpoint" "test" { + description = "terraform-testacc-clientvpn-%s" + server_certificate_arn = aws_acm_certificate.test.arn + client_cidr_block = "10.0.0.0/16" + + authentication_options { + type = "certificate-authentication" + root_certificate_chain_arn = aws_acm_certificate.test.arn + } + + connection_log_options { + enabled = false + } +} +`, rName)) +} + +func testAccEc2ClientVpnRouteConfigDescription(rName string) string { + return composeConfig( + testAccEc2ClientVpnRouteVpcBase(rName, 1), + testAccEc2ClientVpnRouteAcmCertificateBase(), + fmt.Sprintf(` +resource "aws_ec2_client_vpn_route" "test" { + client_vpn_endpoint_id = aws_ec2_client_vpn_endpoint.test.id + destination_cidr_block = "0.0.0.0/0" + target_vpc_subnet_id = aws_subnet.test[0].id + description = "test client VPN route" + + depends_on = [ + aws_ec2_client_vpn_network_association.test, + ] +} + +resource "aws_ec2_client_vpn_network_association" "test" { + client_vpn_endpoint_id = aws_ec2_client_vpn_endpoint.test.id + subnet_id = aws_subnet.test[0].id +} + +resource "aws_ec2_client_vpn_endpoint" "test" { + description = "terraform-testacc-clientvpn-%s" + server_certificate_arn = aws_acm_certificate.test.arn + client_cidr_block = "10.0.0.0/16" + + authentication_options { + type = "certificate-authentication" + root_certificate_chain_arn = aws_acm_certificate.test.arn + } + + connection_log_options { + enabled = false + } +} +`, rName)) +} + +func testAccEc2ClientVpnRouteVpcBase(rName string, subnetCount int) string { + return fmt.Sprintf(` +data "aws_availability_zones" "available" { + # InvalidParameterValue: AZ us-west-2d is not currently supported. Please choose another az in this region + exclude_zone_ids = ["usw2-az4"] + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + + tags = { + Name = "terraform-testacc-subnet-%[1]s" + } +} + +resource "aws_subnet" "test" { + count = %[2]d + availability_zone = data.aws_availability_zones.available.names[count.index] + cidr_block = cidrsubnet(aws_vpc.test.cidr_block, 8, count.index) + vpc_id = aws_vpc.test.id + map_public_ip_on_launch = true + + tags = { + Name = "tf-acc-subnet-%[1]s" + } +} +`, rName, subnetCount) +} + +func testAccEc2ClientVpnRouteAcmCertificateBase() string { + key := tlsRsaPrivateKeyPem(2048) + certificate := tlsRsaX509SelfSignedCertificatePem(key, "example.com") + + return fmt.Sprintf(` +resource "aws_acm_certificate" "test" { + certificate_body = "%[1]s" + private_key = "%[2]s" +} +`, tlsPemEscapeNewlines(certificate), tlsPemEscapeNewlines(key)) +} diff --git a/aws/resource_aws_ec2_fleet.go b/aws/resource_aws_ec2_fleet.go index 6a94cca4a16..41ccfa40de7 100644 --- a/aws/resource_aws_ec2_fleet.go +++ b/aws/resource_aws_ec2_fleet.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_ec2_fleet_test.go b/aws/resource_aws_ec2_fleet_test.go index 20ce10cbae9..375453add60 100644 --- a/aws/resource_aws_ec2_fleet_test.go +++ b/aws/resource_aws_ec2_fleet_test.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSEc2Fleet_basic(t *testing.T) { @@ -333,7 +333,7 @@ func TestAccAWSEc2Fleet_LaunchTemplateConfig_Override_InstanceType(t *testing.T) } func TestAccAWSEc2Fleet_LaunchTemplateConfig_Override_MaxPrice(t *testing.T) { - t.Skip("EC2 API is not correctly returning MaxPrice override") + TestAccSkip(t, "EC2 API is not correctly returning MaxPrice override") var fleet1, fleet2 ec2.FleetData resourceName := "aws_ec2_fleet.test" @@ -1014,106 +1014,106 @@ func TestAccAWSEc2Fleet_TemplateMultipleNetworkInterfaces(t *testing.T) { func testAccAWSEc2FleetConfig_multipleNetworkInterfaces(rInt int) string { return fmt.Sprintf(` data "aws_ami" "test" { - most_recent = true + most_recent = true - filter { - name = "name" - values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"] - } + filter { + name = "name" + values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"] + } - filter { - name = "virtualization-type" - values = ["hvm"] - } + filter { + name = "virtualization-type" + values = ["hvm"] + } - owners = ["099720109477"] # Canonical + owners = ["099720109477"] # Canonical } resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" + cidr_block = "10.1.0.0/16" } resource "aws_internet_gateway" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } resource "aws_subnet" "test" { - cidr_block = "10.1.0.0/24" - vpc_id = "${aws_vpc.test.id}" + cidr_block = "10.1.0.0/24" + vpc_id = aws_vpc.test.id } resource "aws_security_group" "test" { - name = "security-group-%d" - description = "Testacc SSH security group" - vpc_id = "${aws_vpc.test.id}" - - ingress { - protocol = "tcp" - from_port = 22 - to_port = 22 - cidr_blocks = ["0.0.0.0/0"] - } - egress { - protocol = "-1" - from_port = 0 - to_port = 0 - cidr_blocks = ["0.0.0.0/0"] - } + name = "security-group-%d" + description = "Testacc SSH security group" + vpc_id = aws_vpc.test.id + + ingress { + protocol = "tcp" + from_port = 22 + to_port = 22 + cidr_blocks = ["0.0.0.0/0"] + } + egress { + protocol = "-1" + from_port = 0 + to_port = 0 + cidr_blocks = ["0.0.0.0/0"] + } } resource "aws_network_interface" "test" { - subnet_id = "${aws_subnet.test.id}" - security_groups = ["${aws_security_group.test.id}"] + subnet_id = aws_subnet.test.id + security_groups = [aws_security_group.test.id] } resource "aws_launch_template" "test" { - name = "testacc-lt-%d" - image_id = "${data.aws_ami.test.id}" - - instance_market_options { - spot_options { - spot_instance_type = "persistent" - } - market_type="spot" - } + name = "testacc-lt-%d" + image_id = data.aws_ami.test.id - network_interfaces { - device_index = 0 - delete_on_termination = true - network_interface_id = "${aws_network_interface.test.id}" - } - network_interfaces { - device_index = 1 - delete_on_termination = true - subnet_id = "${aws_subnet.test.id}" - } + instance_market_options { + spot_options { + spot_instance_type = "persistent" + } + market_type = "spot" + } + network_interfaces { + device_index = 0 + delete_on_termination = true + network_interface_id = aws_network_interface.test.id + } + network_interfaces { + device_index = 1 + delete_on_termination = true + subnet_id = aws_subnet.test.id + } } resource "aws_ec2_fleet" "test" { - terminate_instances = true + terminate_instances = true - launch_template_config { - launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" - } - # allow to choose from several instance types if there is no spot capacity for some type - override { - instance_type = "t2.micro" - } - override { - instance_type = "t3.micro" - } - override { - instance_type = "t3.small" - } - } + launch_template_config { + launch_template_specification { + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version + } - target_capacity_specification { - default_target_capacity_type = "spot" - total_target_capacity = 1 - } + # allow to choose from several instance types if there is no spot capacity for some type + override { + instance_type = "t2.micro" + } + override { + instance_type = "t3.micro" + } + override { + instance_type = "t3.small" + } + } + + target_capacity_specification { + default_target_capacity_type = "spot" + total_target_capacity = 1 + } } `, rInt, rInt) } @@ -1331,7 +1331,7 @@ data "aws_ami" "test" { } resource "aws_launch_template" "test" { - image_id = "${data.aws_ami.test.id}" + image_id = data.aws_ami.test.id instance_type = "t3.micro" name = %q } @@ -1345,8 +1345,8 @@ resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } @@ -1371,13 +1371,13 @@ data "aws_ami" "test" { } resource "aws_launch_template" "test1" { - image_id = "${data.aws_ami.test.id}" + image_id = data.aws_ami.test.id instance_type = "t3.micro" name = "%s1" } resource "aws_launch_template" "test2" { - image_id = "${data.aws_ami.test.id}" + image_id = data.aws_ami.test.id instance_type = "t3.micro" name = "%s2" } @@ -1411,13 +1411,13 @@ data "aws_ami" "test" { } resource "aws_launch_template" "test1" { - image_id = "${data.aws_ami.test.id}" + image_id = data.aws_ami.test.id instance_type = "t3.micro" name = "%s1" } resource "aws_launch_template" "test2" { - image_id = "${data.aws_ami.test.id}" + image_id = data.aws_ami.test.id instance_type = "t3.micro" name = "%s2" } @@ -1451,7 +1451,7 @@ data "aws_ami" "test" { } resource "aws_launch_template" "test" { - image_id = "${data.aws_ami.test.id}" + image_id = data.aws_ami.test.id instance_type = %q name = %q } @@ -1459,8 +1459,8 @@ resource "aws_launch_template" "test" { resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } @@ -1486,8 +1486,8 @@ data "aws_availability_zones" "available" { resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } override { @@ -1508,8 +1508,8 @@ func testAccAWSEc2FleetConfig_LaunchTemplateConfig_Override_InstanceType(rName, resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } override { @@ -1530,8 +1530,8 @@ func testAccAWSEc2FleetConfig_LaunchTemplateConfig_Override_MaxPrice(rName, maxP resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } override { @@ -1552,8 +1552,8 @@ func testAccAWSEc2FleetConfig_LaunchTemplateConfig_Override_Priority(rName strin resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } override { @@ -1574,12 +1574,12 @@ func testAccAWSEc2FleetConfig_LaunchTemplateConfig_Override_Priority_Multiple(rN resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } override { - instance_type = "${aws_launch_template.test.instance_type}" + instance_type = aws_launch_template.test.instance_type priority = %d } @@ -1607,7 +1607,7 @@ resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { - Name = "${var.TestAccNameTag}" + Name = var.TestAccNameTag } } @@ -1618,15 +1618,15 @@ resource "aws_subnet" "test" { vpc_id = "${aws_vpc.test.id}" tags = { - Name = "${var.TestAccNameTag}" + Name = var.TestAccNameTag } } resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } override { @@ -1647,8 +1647,8 @@ func testAccAWSEc2FleetConfig_LaunchTemplateConfig_Override_WeightedCapacity(rNa resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } override { @@ -1669,12 +1669,12 @@ func testAccAWSEc2FleetConfig_LaunchTemplateConfig_Override_WeightedCapacity_Mul resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } override { - instance_type = "${aws_launch_template.test.instance_type}" + instance_type = aws_launch_template.test.instance_type weighted_capacity = %d } @@ -1697,8 +1697,8 @@ func testAccAWSEc2FleetConfig_OnDemandOptions_AllocationStrategy(rName, allocati resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } @@ -1721,8 +1721,8 @@ resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } @@ -1739,8 +1739,8 @@ func testAccAWSEc2FleetConfig_SpotOptions_AllocationStrategy(rName, allocationSt resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } @@ -1761,8 +1761,8 @@ func testAccAWSEc2FleetConfig_SpotOptions_InstanceInterruptionBehavior(rName, in resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } @@ -1783,8 +1783,8 @@ func testAccAWSEc2FleetConfig_SpotOptions_InstancePoolsToUseCount(rName string, resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } @@ -1805,8 +1805,8 @@ func testAccAWSEc2FleetConfig_Tags(rName, key1, value1 string) string { resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } @@ -1827,8 +1827,8 @@ func testAccAWSEc2FleetConfig_TargetCapacitySpecification_DefaultTargetCapacityT resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } @@ -1847,8 +1847,8 @@ resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } @@ -1867,8 +1867,8 @@ resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } @@ -1887,8 +1887,8 @@ resource "aws_ec2_fleet" "test" { launch_template_config { launch_template_specification { - launch_template_id = "${aws_launch_template.test.id}" - version = "${aws_launch_template.test.latest_version}" + launch_template_id = aws_launch_template.test.id + version = aws_launch_template.test.latest_version } } diff --git a/aws/resource_aws_ec2_local_gateway_route.go b/aws/resource_aws_ec2_local_gateway_route.go new file mode 100644 index 00000000000..8d637c34e0b --- /dev/null +++ b/aws/resource_aws_ec2_local_gateway_route.go @@ -0,0 +1,205 @@ +package aws + +import ( + "fmt" + "log" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +const ( + ec2LocalGatewayRouteEventualConsistencyTimeout = 1 * time.Minute +) + +func resourceAwsEc2LocalGatewayRoute() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsEc2LocalGatewayRouteCreate, + Read: resourceAwsEc2LocalGatewayRouteRead, + Delete: resourceAwsEc2LocalGatewayRouteDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "destination_cidr_block": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateCIDRNetworkAddress, + }, + "local_gateway_route_table_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "local_gateway_virtual_interface_group_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + } +} + +func resourceAwsEc2LocalGatewayRouteCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + destination := d.Get("destination_cidr_block").(string) + localGatewayRouteTableID := d.Get("local_gateway_route_table_id").(string) + + input := &ec2.CreateLocalGatewayRouteInput{ + DestinationCidrBlock: aws.String(destination), + LocalGatewayRouteTableId: aws.String(localGatewayRouteTableID), + LocalGatewayVirtualInterfaceGroupId: aws.String(d.Get("local_gateway_virtual_interface_group_id").(string)), + } + + _, err := conn.CreateLocalGatewayRoute(input) + + if err != nil { + return fmt.Errorf("error creating EC2 Local Gateway Route: %s", err) + } + + d.SetId(fmt.Sprintf("%s_%s", localGatewayRouteTableID, destination)) + + return resourceAwsEc2LocalGatewayRouteRead(d, meta) +} + +func resourceAwsEc2LocalGatewayRouteRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + localGatewayRouteTableID, destination, err := decodeEc2LocalGatewayRouteID(d.Id()) + if err != nil { + return err + } + + var localGatewayRoute *ec2.LocalGatewayRoute + err = resource.Retry(ec2LocalGatewayRouteEventualConsistencyTimeout, func() *resource.RetryError { + var err error + localGatewayRoute, err = getEc2LocalGatewayRoute(conn, localGatewayRouteTableID, destination) + + if err != nil { + return resource.NonRetryableError(err) + } + + if d.IsNewResource() && localGatewayRoute == nil { + return resource.RetryableError(&resource.NotFoundError{}) + } + + return nil + }) + + if isResourceTimeoutError(err) { + localGatewayRoute, err = getEc2LocalGatewayRoute(conn, localGatewayRouteTableID, destination) + } + + if isAWSErr(err, "InvalidRouteTableID.NotFound", "") { + log.Printf("[WARN] EC2 Local Gateway Route Table (%s) not found, removing from state", localGatewayRouteTableID) + d.SetId("") + return nil + } + + if !d.IsNewResource() && isResourceNotFoundError(err) { + log.Printf("[WARN] EC2 Local Gateway Route (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("error reading EC2 Local Gateway Route: %s", err) + } + + if localGatewayRoute == nil { + log.Printf("[WARN] EC2 Local Gateway Route (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + state := aws.StringValue(localGatewayRoute.State) + if state == ec2.LocalGatewayRouteStateDeleted || state == ec2.LocalGatewayRouteStateDeleting { + log.Printf("[WARN] EC2 Local Gateway Route (%s) deleted, removing from state", d.Id()) + d.SetId("") + return nil + } + + d.Set("destination_cidr_block", localGatewayRoute.DestinationCidrBlock) + d.Set("local_gateway_virtual_interface_group_id", localGatewayRoute.LocalGatewayVirtualInterfaceGroupId) + d.Set("local_gateway_route_table_id", localGatewayRoute.LocalGatewayRouteTableId) + + return nil +} + +func resourceAwsEc2LocalGatewayRouteDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + localGatewayRouteTableID, destination, err := decodeEc2LocalGatewayRouteID(d.Id()) + if err != nil { + return err + } + + input := &ec2.DeleteLocalGatewayRouteInput{ + DestinationCidrBlock: aws.String(destination), + LocalGatewayRouteTableId: aws.String(localGatewayRouteTableID), + } + + log.Printf("[DEBUG] Deleting EC2 Local Gateway Route (%s): %s", d.Id(), input) + _, err = conn.DeleteLocalGatewayRoute(input) + + if isAWSErr(err, "InvalidRoute.NotFound", "") || isAWSErr(err, "InvalidRouteTableID.NotFound", "") { + return nil + } + + if err != nil { + return fmt.Errorf("error deleting EC2 Local Gateway Route: %s", err) + } + + return nil +} + +func decodeEc2LocalGatewayRouteID(id string) (string, string, error) { + parts := strings.Split(id, "_") + + if len(parts) != 2 { + return "", "", fmt.Errorf("Unexpected format of ID (%q), expected tgw-rtb-ID_DESTINATION", id) + } + + return parts[0], parts[1], nil +} + +func getEc2LocalGatewayRoute(conn *ec2.EC2, localGatewayRouteTableID, destination string) (*ec2.LocalGatewayRoute, error) { + input := &ec2.SearchLocalGatewayRoutesInput{ + Filters: []*ec2.Filter{ + { + Name: aws.String("type"), + Values: aws.StringSlice([]string{"static"}), + }, + }, + LocalGatewayRouteTableId: aws.String(localGatewayRouteTableID), + } + + output, err := conn.SearchLocalGatewayRoutes(input) + + if err != nil { + return nil, err + } + + if output == nil || len(output.Routes) == 0 { + return nil, nil + } + + for _, route := range output.Routes { + if route == nil { + continue + } + + if aws.StringValue(route.DestinationCidrBlock) == destination { + return route, nil + } + } + + return nil, nil +} diff --git a/aws/resource_aws_ec2_local_gateway_route_table_vpc_association.go b/aws/resource_aws_ec2_local_gateway_route_table_vpc_association.go new file mode 100644 index 00000000000..e016418e17a --- /dev/null +++ b/aws/resource_aws_ec2_local_gateway_route_table_vpc_association.go @@ -0,0 +1,174 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/ec2/waiter" +) + +const ( + // Missing constant in AWS Go SDK + ec2ResourceTypeLocalGatewayRouteTableVpcAssociation = "local-gateway-route-table-vpc-association" +) + +func resourceAwsEc2LocalGatewayRouteTableVpcAssociation() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsEc2LocalGatewayRouteTableVpcAssociationCreate, + Read: resourceAwsEc2LocalGatewayRouteTableVpcAssociationRead, + Update: resourceAwsEc2LocalGatewayRouteTableVpcAssociationUpdate, + Delete: resourceAwsEc2LocalGatewayRouteTableVpcAssociationDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "local_gateway_id": { + Type: schema.TypeString, + Computed: true, + }, + "local_gateway_route_table_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "tags": tagsSchema(), + "vpc_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + }, + } +} + +func resourceAwsEc2LocalGatewayRouteTableVpcAssociationCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + req := &ec2.CreateLocalGatewayRouteTableVpcAssociationInput{ + LocalGatewayRouteTableId: aws.String(d.Get("local_gateway_route_table_id").(string)), + TagSpecifications: ec2TagSpecificationsFromMap(d.Get("tags").(map[string]interface{}), ec2ResourceTypeLocalGatewayRouteTableVpcAssociation), + VpcId: aws.String(d.Get("vpc_id").(string)), + } + + output, err := conn.CreateLocalGatewayRouteTableVpcAssociation(req) + + if err != nil { + return fmt.Errorf("error creating EC2 Local Gateway Route Table VPC Association: %w", err) + } + + d.SetId(aws.StringValue(output.LocalGatewayRouteTableVpcAssociation.LocalGatewayRouteTableVpcAssociationId)) + + if _, err := waiter.LocalGatewayRouteTableVpcAssociationAssociated(conn, d.Id()); err != nil { + return fmt.Errorf("error waiting for EC2 Local Gateway Route Table VPC Association (%s) to associate: %w", d.Id(), err) + } + + return resourceAwsEc2LocalGatewayRouteTableVpcAssociationRead(d, meta) +} + +func resourceAwsEc2LocalGatewayRouteTableVpcAssociationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + + association, err := getEc2LocalGatewayRouteTableVpcAssociation(conn, d.Id()) + + if err != nil { + return fmt.Errorf("error reading EC2 Local Gateway Route Table VPC Association (%s): %w", d.Id(), err) + } + + if association == nil { + log.Printf("[WARN] EC2 Local Gateway Route Table VPC Association (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if aws.StringValue(association.State) != ec2.RouteTableAssociationStateCodeAssociated { + log.Printf("[WARN] EC2 Local Gateway Route Table VPC Association (%s) status (%s), removing from state", d.Id(), aws.StringValue(association.State)) + d.SetId("") + return nil + } + + d.Set("local_gateway_id", association.LocalGatewayId) + d.Set("local_gateway_route_table_id", association.LocalGatewayRouteTableId) + + if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(association.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) + } + + d.Set("vpc_id", association.VpcId) + + return nil +} + +func resourceAwsEc2LocalGatewayRouteTableVpcAssociationUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + if d.HasChange("tags") { + o, n := d.GetChange("tags") + + if err := keyvaluetags.Ec2UpdateTags(conn, d.Id(), o, n); err != nil { + return fmt.Errorf("error updating EC2 Local Gateway Route Table VPC Association (%s) tags: %w", d.Id(), err) + } + } + + return resourceAwsEc2LocalGatewayRouteTableVpcAssociationRead(d, meta) +} + +func resourceAwsEc2LocalGatewayRouteTableVpcAssociationDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + input := &ec2.DeleteLocalGatewayRouteTableVpcAssociationInput{ + LocalGatewayRouteTableVpcAssociationId: aws.String(d.Id()), + } + + _, err := conn.DeleteLocalGatewayRouteTableVpcAssociation(input) + + if isAWSErr(err, "InvalidLocalGatewayRouteTableVpcAssociationID.NotFound", "") { + return nil + } + + if err != nil { + return fmt.Errorf("error deleting EC2 Local Gateway Route Table VPC Association (%s): %w", d.Id(), err) + } + + if _, err := waiter.LocalGatewayRouteTableVpcAssociationDisassociated(conn, d.Id()); err != nil { + return fmt.Errorf("error waiting for EC2 Local Gateway Route Table VPC Association (%s) to disassociate: %w", d.Id(), err) + } + + return nil +} + +func getEc2LocalGatewayRouteTableVpcAssociation(conn *ec2.EC2, localGatewayRouteTableVpcAssociationID string) (*ec2.LocalGatewayRouteTableVpcAssociation, error) { + input := &ec2.DescribeLocalGatewayRouteTableVpcAssociationsInput{ + LocalGatewayRouteTableVpcAssociationIds: aws.StringSlice([]string{localGatewayRouteTableVpcAssociationID}), + } + + output, err := conn.DescribeLocalGatewayRouteTableVpcAssociations(input) + + if err != nil { + return nil, err + } + + if output == nil { + return nil, fmt.Errorf("empty response") + } + + var association *ec2.LocalGatewayRouteTableVpcAssociation + + for _, outputAssociation := range output.LocalGatewayRouteTableVpcAssociations { + if outputAssociation == nil { + continue + } + + if aws.StringValue(outputAssociation.LocalGatewayRouteTableVpcAssociationId) == localGatewayRouteTableVpcAssociationID { + association = outputAssociation + break + } + } + + return association, nil +} diff --git a/aws/resource_aws_ec2_local_gateway_route_table_vpc_association_test.go b/aws/resource_aws_ec2_local_gateway_route_table_vpc_association_test.go new file mode 100644 index 00000000000..1c6a8e681c8 --- /dev/null +++ b/aws/resource_aws_ec2_local_gateway_route_table_vpc_association_test.go @@ -0,0 +1,219 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccAwsEc2LocalGatewayRouteTableVpcAssociation_basic(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + localGatewayRouteTableDataSourceName := "data.aws_ec2_local_gateway_route_table.test" + resourceName := "aws_ec2_local_gateway_route_table_vpc_association.test" + vpcResourceName := "aws_vpc.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsEc2LocalGatewayRouteTableVpcAssociationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEc2LocalGatewayRouteTableVpcAssociationExists(resourceName), + resource.TestCheckResourceAttrPair(resourceName, "local_gateway_id", localGatewayRouteTableDataSourceName, "local_gateway_id"), + resource.TestCheckResourceAttrPair(resourceName, "local_gateway_route_table_id", localGatewayRouteTableDataSourceName, "id"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttrPair(resourceName, "vpc_id", vpcResourceName, "id"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAwsEc2LocalGatewayRouteTableVpcAssociation_disappears(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_ec2_local_gateway_route_table_vpc_association.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsEc2LocalGatewayRouteTableVpcAssociationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEc2LocalGatewayRouteTableVpcAssociationExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEc2LocalGatewayRouteTableVpcAssociation(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAwsEc2LocalGatewayRouteTableVpcAssociation_Tags(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_ec2_local_gateway_route_table_vpc_association.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsEc2LocalGatewayRouteTableVpcAssociationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfigTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEc2LocalGatewayRouteTableVpcAssociationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEc2LocalGatewayRouteTableVpcAssociationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfigTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsEc2LocalGatewayRouteTableVpcAssociationExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func testAccCheckAwsEc2LocalGatewayRouteTableVpcAssociationExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Not found: %s", resourceName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("%s: missing resource ID", resourceName) + } + + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + association, err := getEc2LocalGatewayRouteTableVpcAssociation(conn, rs.Primary.ID) + + if err != nil { + return err + } + + if association == nil { + return fmt.Errorf("EC2 Local Gateway Route Table VPC Association (%s) not found", rs.Primary.ID) + } + + if aws.StringValue(association.State) != ec2.RouteTableAssociationStateCodeAssociated { + return fmt.Errorf("EC2 Local Gateway Route Table VPC Association (%s) not in associated state: %s", rs.Primary.ID, aws.StringValue(association.State)) + } + + return nil + } +} + +func testAccCheckAwsEc2LocalGatewayRouteTableVpcAssociationDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_ec2_local_gateway_route_table_vpc_association" { + continue + } + + association, err := getEc2LocalGatewayRouteTableVpcAssociation(conn, rs.Primary.ID) + + if err != nil { + return err + } + + if association != nil && aws.StringValue(association.State) != ec2.RouteTableAssociationStateCodeDisassociated { + return fmt.Errorf("EC2 Local Gateway Route Table VPC Association (%s) still exists in state: %s", rs.Primary.ID, aws.StringValue(association.State)) + } + } + + return nil +} + +func testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfigBase(rName string) string { + return fmt.Sprintf(` +data "aws_outposts_outposts" "test" {} + +data "aws_ec2_local_gateway_route_table" "test" { + outpost_arn = tolist(data.aws_outposts_outposts.test.arns)[0] +} + +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} +`, rName) +} + +func testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfig(rName string) string { + return composeConfig( + testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfigBase(rName), + ` +resource "aws_ec2_local_gateway_route_table_vpc_association" "test" { + local_gateway_route_table_id = data.aws_ec2_local_gateway_route_table.test.id + vpc_id = aws_vpc.test.id +} +`) +} + +func testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfigTags1(rName, tagKey1, tagValue1 string) string { + return composeConfig( + testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfigBase(rName), + fmt.Sprintf(` +resource "aws_ec2_local_gateway_route_table_vpc_association" "test" { + local_gateway_route_table_id = data.aws_ec2_local_gateway_route_table.test.id + vpc_id = aws_vpc.test.id + + tags = { + %[1]q = %[2]q + } +} +`, tagKey1, tagValue1)) +} + +func testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return composeConfig( + testAccAwsEc2LocalGatewayRouteTableVpcAssociationConfigBase(rName), + fmt.Sprintf(` +resource "aws_ec2_local_gateway_route_table_vpc_association" "test" { + local_gateway_route_table_id = data.aws_ec2_local_gateway_route_table.test.id + vpc_id = aws_vpc.test.id + + tags = { + %[1]q = %[2]q + %[3]q = %[4]q + } +} +`, tagKey1, tagValue1, tagKey2, tagValue2)) +} diff --git a/aws/resource_aws_ec2_local_gateway_route_test.go b/aws/resource_aws_ec2_local_gateway_route_test.go new file mode 100644 index 00000000000..acefe135050 --- /dev/null +++ b/aws/resource_aws_ec2_local_gateway_route_test.go @@ -0,0 +1,149 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccAWSEc2LocalGatewayRoute_basic(t *testing.T) { + rInt := acctest.RandIntRange(0, 255) + destinationCidrBlock := fmt.Sprintf("172.16.%d.0/24", rInt) + localGatewayRouteTableDataSourceName := "data.aws_ec2_local_gateway_route_table.test" + localGatewayVirtualInterfaceGroupDataSourceName := "data.aws_ec2_local_gateway_virtual_interface_group.test" + resourceName := "aws_ec2_local_gateway_route.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEc2LocalGatewayRouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEc2LocalGatewayRouteConfigDestinationCidrBlock(destinationCidrBlock), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEc2LocalGatewayRouteExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "destination_cidr_block", destinationCidrBlock), + resource.TestCheckResourceAttrPair(resourceName, "local_gateway_route_table_id", localGatewayRouteTableDataSourceName, "id"), + resource.TestCheckResourceAttrPair(resourceName, "local_gateway_virtual_interface_group_id", localGatewayVirtualInterfaceGroupDataSourceName, "id"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSEc2LocalGatewayRoute_disappears(t *testing.T) { + rInt := acctest.RandIntRange(0, 255) + destinationCidrBlock := fmt.Sprintf("172.16.%d.0/24", rInt) + resourceName := "aws_ec2_local_gateway_route.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEc2LocalGatewayRouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEc2LocalGatewayRouteConfigDestinationCidrBlock(destinationCidrBlock), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEc2LocalGatewayRouteExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEc2LocalGatewayRoute(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckAWSEc2LocalGatewayRouteExists(resourceName string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Not found: %s", resourceName) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No EC2 Local Gateway Route ID is set") + } + + localGatewayRouteTableID, destination, err := decodeEc2LocalGatewayRouteID(rs.Primary.ID) + + if err != nil { + return err + } + + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + route, err := getEc2LocalGatewayRoute(conn, localGatewayRouteTableID, destination) + + if err != nil { + return err + } + + if route == nil { + return fmt.Errorf("EC2 Local Gateway Route (%s) not found", rs.Primary.ID) + } + + return nil + } +} + +func testAccCheckAWSEc2LocalGatewayRouteDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_ec2_local_gateway_route" { + continue + } + + localGatewayRouteTableID, destination, err := decodeEc2LocalGatewayRouteID(rs.Primary.ID) + + if err != nil { + return err + } + + route, err := getEc2LocalGatewayRoute(conn, localGatewayRouteTableID, destination) + + if isAWSErr(err, "InvalidRouteTableID.NotFound", "") { + continue + } + + if err != nil { + return err + } + + if route == nil { + continue + } + + return fmt.Errorf("EC2 Local Gateway Route (%s) still exists", rs.Primary.ID) + } + + return nil +} + +func testAccAWSEc2LocalGatewayRouteConfigDestinationCidrBlock(destinationCidrBlock string) string { + return fmt.Sprintf(` +data "aws_ec2_local_gateways" "test" {} + +data "aws_ec2_local_gateway_route_table" "test" { + local_gateway_id = tolist(data.aws_ec2_local_gateways.test.ids)[0] +} + +data "aws_ec2_local_gateway_virtual_interface_group" "test" { + local_gateway_id = tolist(data.aws_ec2_local_gateways.test.ids)[0] +} + +resource "aws_ec2_local_gateway_route" "test" { + destination_cidr_block = %[1]q + local_gateway_route_table_id = data.aws_ec2_local_gateway_route_table.test.id + local_gateway_virtual_interface_group_id = data.aws_ec2_local_gateway_virtual_interface_group.test.id +} +`, destinationCidrBlock) +} diff --git a/aws/resource_aws_ec2_tag.go b/aws/resource_aws_ec2_tag.go new file mode 100644 index 00000000000..eedc3ce9c7a --- /dev/null +++ b/aws/resource_aws_ec2_tag.go @@ -0,0 +1,122 @@ +package aws + +import ( + "fmt" + "log" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" +) + +func resourceAwsEc2Tag() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsEc2TagCreate, + Read: resourceAwsEc2TagRead, + Update: resourceAwsEc2TagUpdate, + Delete: resourceAwsEc2TagDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "resource_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "key": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "value": { + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +func extractResourceIDAndKeyFromEc2TagID(id string) (string, string, error) { + parts := strings.SplitN(id, ",", 2) + + if len(parts) != 2 { + return "", "", fmt.Errorf("Invalid resource ID; cannot look up resource: %s", id) + } + + return parts[0], parts[1], nil +} + +func resourceAwsEc2TagCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + + resourceID := d.Get("resource_id").(string) + key := d.Get("key").(string) + value := d.Get("value").(string) + + if err := keyvaluetags.Ec2CreateTags(conn, resourceID, map[string]string{key: value}); err != nil { + return fmt.Errorf("error creating EC2 Tag (%s) for resource (%s): %w", key, resourceID, err) + } + + d.SetId(fmt.Sprintf("%s,%s", resourceID, key)) + + return resourceAwsEc2TagRead(d, meta) +} + +func resourceAwsEc2TagRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + resourceID, key, err := extractResourceIDAndKeyFromEc2TagID(d.Id()) + + if err != nil { + return err + } + + exists, value, err := keyvaluetags.Ec2GetTag(conn, resourceID, key) + + if err != nil { + return fmt.Errorf("error reading EC2 Tag (%s) for resource (%s): %w", key, resourceID, err) + } + + if !exists { + log.Printf("[WARN] EC2 Tag (%s) for resource (%s) not found, removing from state", key, resourceID) + d.SetId("") + return nil + } + + d.Set("key", key) + d.Set("resource_id", resourceID) + d.Set("value", value) + + return nil +} + +func resourceAwsEc2TagUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + resourceID, key, err := extractResourceIDAndKeyFromEc2TagID(d.Id()) + + if err != nil { + return err + } + + if err := keyvaluetags.Ec2UpdateTags(conn, resourceID, nil, map[string]string{key: d.Get("value").(string)}); err != nil { + return fmt.Errorf("error updating EC2 Tag (%s) for resource (%s): %w", key, resourceID, err) + } + + return resourceAwsEc2TagRead(d, meta) +} + +func resourceAwsEc2TagDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).ec2conn + resourceID, key, err := extractResourceIDAndKeyFromEc2TagID(d.Id()) + + if err != nil { + return err + } + + if err := keyvaluetags.Ec2UpdateTags(conn, resourceID, map[string]string{key: d.Get("value").(string)}, nil); err != nil { + return fmt.Errorf("error deleting EC2 Tag (%s) for resource (%s): %w", key, resourceID, err) + } + + return nil +} diff --git a/aws/resource_aws_ec2_tag_test.go b/aws/resource_aws_ec2_tag_test.go new file mode 100644 index 00000000000..a542e6222fb --- /dev/null +++ b/aws/resource_aws_ec2_tag_test.go @@ -0,0 +1,177 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" +) + +func TestAccAWSEc2Tag_basic(t *testing.T) { + rBgpAsn := acctest.RandIntRange(64512, 65534) + resourceName := "aws_ec2_tag.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2TransitGateway(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEc2TagDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEc2TagConfig(rBgpAsn, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckEc2TagExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "key", "key1"), + resource.TestCheckResourceAttr(resourceName, "value", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSEc2Tag_disappears(t *testing.T) { + rBgpAsn := acctest.RandIntRange(64512, 65534) + resourceName := "aws_ec2_tag.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2TransitGateway(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEc2TagDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEc2TagConfig(rBgpAsn, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckEc2TagExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEc2Tag(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAWSEc2Tag_Value(t *testing.T) { + rBgpAsn := acctest.RandIntRange(64512, 65534) + resourceName := "aws_ec2_tag.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2TransitGateway(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEc2TagDestroy, + Steps: []resource.TestStep{ + { + Config: testAccEc2TagConfig(rBgpAsn, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckEc2TagExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "key", "key1"), + resource.TestCheckResourceAttr(resourceName, "value", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccEc2TagConfig(rBgpAsn, "key1", "value1updated"), + Check: resource.ComposeTestCheckFunc( + testAccCheckEc2TagExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "key", "key1"), + resource.TestCheckResourceAttr(resourceName, "value", "value1updated"), + ), + }, + }, + }) +} + +func testAccCheckEc2TagDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_ec2_tag" { + continue + } + + resourceID, key, err := extractResourceIDAndKeyFromEc2TagID(rs.Primary.ID) + + if err != nil { + return err + } + + exists, _, err := keyvaluetags.Ec2GetTag(conn, resourceID, key) + + if err != nil { + return err + } + + if exists { + return fmt.Errorf("Tag (%s) for resource (%s) still exists", key, resourceID) + } + } + + return nil +} + +func testAccCheckEc2TagExists(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") + } + + resourceID, key, err := extractResourceIDAndKeyFromEc2TagID(rs.Primary.ID) + + if err != nil { + return err + } + + conn := testAccProvider.Meta().(*AWSClient).ec2conn + + exists, _, err := keyvaluetags.Ec2GetTag(conn, resourceID, key) + + if err != nil { + return err + } + + if !exists { + return fmt.Errorf("Tag (%s) for resource (%s) not found", key, resourceID) + } + + return nil + } +} + +func testAccEc2TagConfig(rBgpAsn int, key string, value string) string { + return fmt.Sprintf(` +resource "aws_ec2_transit_gateway" "test" {} + +resource "aws_customer_gateway" "test" { + bgp_asn = %[1]d + ip_address = "172.0.0.1" + type = "ipsec.1" +} + +resource "aws_vpn_connection" "test" { + customer_gateway_id = aws_customer_gateway.test.id + transit_gateway_id = aws_ec2_transit_gateway.test.id + type = aws_customer_gateway.test.type +} + +resource "aws_ec2_tag" "test" { + resource_id = aws_vpn_connection.test.transit_gateway_attachment_id + key = %[2]q + value = %[3]q +} +`, rBgpAsn, key, value) +} diff --git a/aws/resource_aws_ec2_traffic_mirror_filter.go b/aws/resource_aws_ec2_traffic_mirror_filter.go index 0a3809c8814..abc2216cbbb 100644 --- a/aws/resource_aws_ec2_traffic_mirror_filter.go +++ b/aws/resource_aws_ec2_traffic_mirror_filter.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_ec2_traffic_mirror_filter_rule.go b/aws/resource_aws_ec2_traffic_mirror_filter_rule.go index 792d054b307..815b843e5c7 100644 --- a/aws/resource_aws_ec2_traffic_mirror_filter_rule.go +++ b/aws/resource_aws_ec2_traffic_mirror_filter_rule.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsEc2TrafficMirrorFilterRule() *schema.Resource { diff --git a/aws/resource_aws_ec2_traffic_mirror_filter_rule_test.go b/aws/resource_aws_ec2_traffic_mirror_filter_rule_test.go index cf5c6789f53..9d1dee21b5a 100644 --- a/aws/resource_aws_ec2_traffic_mirror_filter_rule_test.go +++ b/aws/resource_aws_ec2_traffic_mirror_filter_rule_test.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSEc2TrafficMirrorFilterRule_basic(t *testing.T) { @@ -155,12 +155,12 @@ resource "aws_ec2_traffic_mirror_filter" "filter" { } resource "aws_ec2_traffic_mirror_filter_rule" "rule" { - traffic_mirror_filter_id = "${aws_ec2_traffic_mirror_filter.filter.id}" - destination_cidr_block = "%s" - rule_action = "%s" - rule_number = %d - source_cidr_block = "%s" - traffic_direction = "%s" + traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id + destination_cidr_block = "%s" + rule_action = "%s" + rule_number = %d + source_cidr_block = "%s" + traffic_direction = "%s" } `, dstCidr, action, num, srcCidr, dir) } @@ -171,22 +171,22 @@ resource "aws_ec2_traffic_mirror_filter" "filter" { } resource "aws_ec2_traffic_mirror_filter_rule" "rule" { - traffic_mirror_filter_id = "${aws_ec2_traffic_mirror_filter.filter.id}" - destination_cidr_block = "%s" - rule_action = "%s" - rule_number = %d - source_cidr_block = "%s" - traffic_direction = "%s" - description = "%s" - protocol = %d - source_port_range { - from_port = %d - to_port = %d - } - destination_port_range { - from_port = %d - to_port = %d - } + traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id + destination_cidr_block = "%s" + rule_action = "%s" + rule_number = %d + source_cidr_block = "%s" + traffic_direction = "%s" + description = "%s" + protocol = %d + source_port_range { + from_port = %d + to_port = %d + } + destination_port_range { + from_port = %d + to_port = %d + } } `, dstCidr, action, ruleNum, srcCidr, dir, description, protocol, srcPortFrom, srcPortTo, dstPortFrom, dstPortTo) } diff --git a/aws/resource_aws_ec2_traffic_mirror_filter_test.go b/aws/resource_aws_ec2_traffic_mirror_filter_test.go index 260adfcc857..8a53d8fed7e 100644 --- a/aws/resource_aws_ec2_traffic_mirror_filter_test.go +++ b/aws/resource_aws_ec2_traffic_mirror_filter_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSEc2TrafficMirrorFilter_basic(t *testing.T) { diff --git a/aws/resource_aws_ec2_traffic_mirror_session.go b/aws/resource_aws_ec2_traffic_mirror_session.go index 49970292c07..b3aa6b152da 100644 --- a/aws/resource_aws_ec2_traffic_mirror_session.go +++ b/aws/resource_aws_ec2_traffic_mirror_session.go @@ -5,9 +5,10 @@ import ( "log" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -21,6 +22,10 @@ func resourceAwsEc2TrafficMirrorSession() *schema.Resource { State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, "description": { Type: schema.TypeString, Optional: true, @@ -92,7 +97,7 @@ func resourceAwsEc2TrafficMirrorSessionCreate(d *schema.ResourceData, meta inter return fmt.Errorf("Error creating traffic mirror session %v", err) } - d.SetId(*out.TrafficMirrorSession.TrafficMirrorSessionId) + d.SetId(aws.StringValue(out.TrafficMirrorSession.TrafficMirrorSessionId)) return resourceAwsEc2TrafficMirrorSessionRead(d, meta) } @@ -212,6 +217,16 @@ func resourceAwsEc2TrafficMirrorSessionRead(d *schema.ResourceData, meta interfa return fmt.Errorf("error setting tags: %s", err) } + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Service: "ec2", + Region: meta.(*AWSClient).region, + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("traffic-mirror-session/%s", d.Id()), + }.String() + + d.Set("arn", arn) + return nil } diff --git a/aws/resource_aws_ec2_traffic_mirror_session_test.go b/aws/resource_aws_ec2_traffic_mirror_session_test.go index dfa43b39db6..20fd08b852a 100644 --- a/aws/resource_aws_ec2_traffic_mirror_session_test.go +++ b/aws/resource_aws_ec2_traffic_mirror_session_test.go @@ -6,13 +6,13 @@ import ( "strconv" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSEc2TrafficMirrorSession_basic(t *testing.T) { @@ -42,6 +42,7 @@ func TestAccAWSEc2TrafficMirrorSession_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "session_number", strconv.Itoa(session)), resource.TestMatchResourceAttr(resourceName, "virtual_network_id", regexp.MustCompile(`\d+`)), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`traffic-mirror-session/tms-.+`)), ), }, // update of description, packet length and VNI @@ -142,7 +143,7 @@ func TestAccAWSEc2TrafficMirrorSession_disappears(t *testing.T) { Config: testAccTrafficMirrorSessionConfig(rName, session), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEc2TrafficMirrorSessionExists(resourceName, &v), - testAccCheckAWSEc2TrafficMirrorSessionDisappears(&v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEc2TrafficMirrorSession(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -181,17 +182,6 @@ func testAccCheckAWSEc2TrafficMirrorSessionExists(name string, session *ec2.Traf } } -func testAccCheckAWSEc2TrafficMirrorSessionDisappears(session *ec2.TrafficMirrorSession) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - _, err := conn.DeleteTrafficMirrorSession(&ec2.DeleteTrafficMirrorSessionInput{ - TrafficMirrorSessionId: session.TrafficMirrorSessionId, - }) - - return err - } -} - func testAccTrafficMirrorSessionConfigBase(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "azs" { @@ -207,12 +197,12 @@ data "aws_ami" "amzn-linux" { most_recent = true filter { - name = "name" + name = "name" values = ["amzn2-ami-hvm-2.0*"] } filter { - name = "architecture" + name = "architecture" values = ["x86_64"] } @@ -228,9 +218,9 @@ resource "aws_vpc" "vpc" { } resource "aws_subnet" "sub1" { - vpc_id = "${aws_vpc.vpc.id}" - cidr_block = "10.0.0.0/24" - availability_zone = "${data.aws_availability_zones.azs.names[0]}" + vpc_id = aws_vpc.vpc.id + cidr_block = "10.0.0.0/24" + availability_zone = data.aws_availability_zones.azs.names[0] tags = { Name = %[1]q @@ -238,9 +228,9 @@ resource "aws_subnet" "sub1" { } resource "aws_subnet" "sub2" { - vpc_id = "${aws_vpc.vpc.id}" - cidr_block = "10.0.1.0/24" - availability_zone = "${data.aws_availability_zones.azs.names[1]}" + vpc_id = aws_vpc.vpc.id + cidr_block = "10.0.1.0/24" + availability_zone = data.aws_availability_zones.azs.names[1] tags = { Name = %[1]q @@ -248,9 +238,9 @@ resource "aws_subnet" "sub2" { } resource "aws_instance" "src" { - ami = "${data.aws_ami.amzn-linux.id}" + ami = data.aws_ami.amzn-linux.id instance_type = "m5.large" # m5.large required because only Nitro instances support mirroring - subnet_id = "${aws_subnet.sub1.id}" + subnet_id = aws_subnet.sub1.id tags = { Name = %[1]q @@ -261,12 +251,12 @@ resource "aws_lb" "lb" { name = %[1]q internal = true load_balancer_type = "network" - subnets = ["${aws_subnet.sub1.id}", "${aws_subnet.sub2.id}"] + subnets = [aws_subnet.sub1.id, aws_subnet.sub2.id] - enable_deletion_protection = false + enable_deletion_protection = false tags = { - Name = %[1]q + Name = %[1]q Environment = "production" } } @@ -275,19 +265,18 @@ resource "aws_ec2_traffic_mirror_filter" "filter" { } resource "aws_ec2_traffic_mirror_target" "target" { - network_load_balancer_arn = "${aws_lb.lb.arn}" + network_load_balancer_arn = aws_lb.lb.arn } - `, rName) } func testAccTrafficMirrorSessionConfig(rName string, session int) string { return testAccTrafficMirrorSessionConfigBase(rName) + fmt.Sprintf(` resource "aws_ec2_traffic_mirror_session" "test" { - traffic_mirror_filter_id = "${aws_ec2_traffic_mirror_filter.filter.id}" - traffic_mirror_target_id = "${aws_ec2_traffic_mirror_target.target.id}" - network_interface_id = "${aws_instance.src.primary_network_interface_id}" - session_number = %d + traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id + traffic_mirror_target_id = aws_ec2_traffic_mirror_target.target.id + network_interface_id = aws_instance.src.primary_network_interface_id + session_number = %d } `, session) } @@ -295,10 +284,10 @@ resource "aws_ec2_traffic_mirror_session" "test" { func testAccTrafficMirrorSessionConfigTags1(rName, tagKey1, tagValue1 string, session int) string { return testAccTrafficMirrorSessionConfigBase(rName) + fmt.Sprintf(` resource "aws_ec2_traffic_mirror_session" "test" { - traffic_mirror_filter_id = "${aws_ec2_traffic_mirror_filter.filter.id}" - traffic_mirror_target_id = "${aws_ec2_traffic_mirror_target.target.id}" - network_interface_id = "${aws_instance.src.primary_network_interface_id}" - session_number = %[3]d + traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id + traffic_mirror_target_id = aws_ec2_traffic_mirror_target.target.id + network_interface_id = aws_instance.src.primary_network_interface_id + session_number = %[3]d tags = { %[1]q = %[2]q @@ -310,10 +299,10 @@ resource "aws_ec2_traffic_mirror_session" "test" { func testAccTrafficMirrorSessionConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string, session int) string { return testAccTrafficMirrorSessionConfigBase(rName) + fmt.Sprintf(` resource "aws_ec2_traffic_mirror_session" "test" { - traffic_mirror_filter_id = "${aws_ec2_traffic_mirror_filter.filter.id}" - traffic_mirror_target_id = "${aws_ec2_traffic_mirror_target.target.id}" - network_interface_id = "${aws_instance.src.primary_network_interface_id}" - session_number = %[5]d + traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id + traffic_mirror_target_id = aws_ec2_traffic_mirror_target.target.id + network_interface_id = aws_instance.src.primary_network_interface_id + session_number = %[5]d tags = { %[1]q = %[2]q @@ -328,13 +317,13 @@ func testAccTrafficMirrorSessionConfigWithOptionals(description string, rName st %s resource "aws_ec2_traffic_mirror_session" "test" { - description = "%s" - traffic_mirror_filter_id = "${aws_ec2_traffic_mirror_filter.filter.id}" - traffic_mirror_target_id = "${aws_ec2_traffic_mirror_target.target.id}" - network_interface_id = "${aws_instance.src.primary_network_interface_id}" - session_number = %d - packet_length = %d - virtual_network_id = %d + description = "%s" + traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id + traffic_mirror_target_id = aws_ec2_traffic_mirror_target.target.id + network_interface_id = aws_instance.src.primary_network_interface_id + session_number = %d + packet_length = %d + virtual_network_id = %d } `, testAccTrafficMirrorSessionConfigBase(rName), description, session, pLen, vni) } diff --git a/aws/resource_aws_ec2_traffic_mirror_target.go b/aws/resource_aws_ec2_traffic_mirror_target.go index feb367fb90a..59a48a1739a 100644 --- a/aws/resource_aws_ec2_traffic_mirror_target.go +++ b/aws/resource_aws_ec2_traffic_mirror_target.go @@ -5,8 +5,9 @@ import ( "log" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -45,6 +46,10 @@ func resourceAwsEc2TrafficMirrorTarget() *schema.Resource { ValidateFunc: validateArn, }, "tags": tagsSchema(), + "arn": { + Type: schema.TypeString, + Computed: true, + }, }, } } @@ -74,7 +79,7 @@ func resourceAwsEc2TrafficMirrorTargetCreate(d *schema.ResourceData, meta interf return fmt.Errorf("Error creating traffic mirror target %v", err) } - d.SetId(*out.TrafficMirrorTarget.TrafficMirrorTargetId) + d.SetId(aws.StringValue(out.TrafficMirrorTarget.TrafficMirrorTargetId)) return resourceAwsEc2TrafficMirrorTargetRead(d, meta) } @@ -128,6 +133,16 @@ func resourceAwsEc2TrafficMirrorTargetRead(d *schema.ResourceData, meta interfac return fmt.Errorf("error setting tags: %s", err) } + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Service: "ec2", + Region: meta.(*AWSClient).region, + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("traffic-mirror-target/%s", d.Id()), + }.String() + + d.Set("arn", arn) + return nil } diff --git a/aws/resource_aws_ec2_traffic_mirror_target_test.go b/aws/resource_aws_ec2_traffic_mirror_target_test.go index e7cf61520bf..9348a2cf5a5 100644 --- a/aws/resource_aws_ec2_traffic_mirror_target_test.go +++ b/aws/resource_aws_ec2_traffic_mirror_target_test.go @@ -5,13 +5,13 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSEc2TrafficMirrorTarget_nlb(t *testing.T) { @@ -32,6 +32,7 @@ func TestAccAWSEc2TrafficMirrorTarget_nlb(t *testing.T) { Config: testAccTrafficMirrorTargetConfigNlb(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEc2TrafficMirrorTargetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`traffic-mirror-target/tmt-.+`)), resource.TestCheckResourceAttr(resourceName, "description", description), resource.TestCheckResourceAttrPair(resourceName, "network_load_balancer_arn", "aws_lb.lb", "arn"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -144,7 +145,7 @@ func TestAccAWSEc2TrafficMirrorTarget_disappears(t *testing.T) { Config: testAccTrafficMirrorTargetConfigNlb(rName, description), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEc2TrafficMirrorTargetExists(resourceName, &v), - testAccCheckAWSEc2TrafficMirrorTargetDisappears(&v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEc2TrafficMirrorTarget(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -183,17 +184,6 @@ func testAccCheckAWSEc2TrafficMirrorTargetExists(name string, target *ec2.Traffi } } -func testAccCheckAWSEc2TrafficMirrorTargetDisappears(target *ec2.TrafficMirrorTarget) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - _, err := conn.DeleteTrafficMirrorTarget(&ec2.DeleteTrafficMirrorTargetInput{ - TrafficMirrorTargetId: target.TrafficMirrorTargetId, - }) - - return err - } -} - func testAccTrafficMirrorTargetConfigBase(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "azs" { @@ -214,9 +204,9 @@ resource "aws_vpc" "vpc" { } resource "aws_subnet" "sub1" { - vpc_id = "${aws_vpc.vpc.id}" - cidr_block = "10.0.0.0/24" - availability_zone = "${data.aws_availability_zones.azs.names[0]}" + vpc_id = aws_vpc.vpc.id + cidr_block = "10.0.0.0/24" + availability_zone = data.aws_availability_zones.azs.names[0] tags = { Name = %[1]q @@ -224,9 +214,9 @@ resource "aws_subnet" "sub1" { } resource "aws_subnet" "sub2" { - vpc_id = "${aws_vpc.vpc.id}" - cidr_block = "10.0.1.0/24" - availability_zone = "${data.aws_availability_zones.azs.names[1]}" + vpc_id = aws_vpc.vpc.id + cidr_block = "10.0.1.0/24" + availability_zone = data.aws_availability_zones.azs.names[1] tags = { Name = %[1]q @@ -241,7 +231,7 @@ resource "aws_lb" "lb" { name = %[1]q internal = true load_balancer_type = "network" - subnets = ["${aws_subnet.sub1.id}", "${aws_subnet.sub2.id}"] + subnets = [aws_subnet.sub1.id, aws_subnet.sub2.id] enable_deletion_protection = false @@ -252,8 +242,8 @@ resource "aws_lb" "lb" { } resource "aws_ec2_traffic_mirror_target" "test" { - description = %[2]q - network_load_balancer_arn = "${aws_lb.lb.arn}" + description = %[2]q + network_load_balancer_arn = aws_lb.lb.arn } `, rName, description) } @@ -277,9 +267,9 @@ data "aws_ami" "amzn-linux" { } resource "aws_instance" "src" { - ami = "${data.aws_ami.amzn-linux.id}" + ami = data.aws_ami.amzn-linux.id instance_type = "t2.micro" - subnet_id = "${aws_subnet.sub1.id}" + subnet_id = aws_subnet.sub1.id tags = { Name = %[1]q @@ -287,8 +277,8 @@ resource "aws_instance" "src" { } resource "aws_ec2_traffic_mirror_target" "test" { - description = %[2]q - network_interface_id = "${aws_instance.src.primary_network_interface_id}" + description = %[2]q + network_interface_id = aws_instance.src.primary_network_interface_id } `, rName, description) } @@ -299,7 +289,7 @@ resource "aws_lb" "lb" { name = %[1]q internal = true load_balancer_type = "network" - subnets = ["${aws_subnet.sub1.id}", "${aws_subnet.sub2.id}"] + subnets = [aws_subnet.sub1.id, aws_subnet.sub2.id] enable_deletion_protection = false @@ -310,8 +300,8 @@ resource "aws_lb" "lb" { } resource "aws_ec2_traffic_mirror_target" "test" { - description = %[2]q - network_load_balancer_arn = "${aws_lb.lb.arn}" + description = %[2]q + network_load_balancer_arn = aws_lb.lb.arn tags = { %[3]q = %[4]q @@ -326,7 +316,7 @@ resource "aws_lb" "lb" { name = %[1]q internal = true load_balancer_type = "network" - subnets = ["${aws_subnet.sub1.id}", "${aws_subnet.sub2.id}"] + subnets = [aws_subnet.sub1.id, aws_subnet.sub2.id] enable_deletion_protection = false @@ -337,8 +327,8 @@ resource "aws_lb" "lb" { } resource "aws_ec2_traffic_mirror_target" "test" { - description = %[2]q - network_load_balancer_arn = "${aws_lb.lb.arn}" + description = %[2]q + network_load_balancer_arn = aws_lb.lb.arn tags = { %[3]q = %[4]q diff --git a/aws/resource_aws_ec2_transit_gateway.go b/aws/resource_aws_ec2_transit_gateway.go index a9ef4791175..090647d866b 100644 --- a/aws/resource_aws_ec2_transit_gateway.go +++ b/aws/resource_aws_ec2_transit_gateway.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_ec2_transit_gateway_peering_attachment.go b/aws/resource_aws_ec2_transit_gateway_peering_attachment.go index fca4bf559f9..f09864e7a7a 100644 --- a/aws/resource_aws_ec2_transit_gateway_peering_attachment.go +++ b/aws/resource_aws_ec2_transit_gateway_peering_attachment.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_ec2_transit_gateway_peering_attachment_accepter.go b/aws/resource_aws_ec2_transit_gateway_peering_attachment_accepter.go index 59ac333781f..1704dde89b0 100644 --- a/aws/resource_aws_ec2_transit_gateway_peering_attachment_accepter.go +++ b/aws/resource_aws_ec2_transit_gateway_peering_attachment_accepter.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_ec2_transit_gateway_peering_attachment_accepter_test.go b/aws/resource_aws_ec2_transit_gateway_peering_attachment_accepter_test.go index 7ef25573463..b2a218f67da 100644 --- a/aws/resource_aws_ec2_transit_gateway_peering_attachment_accepter_test.go +++ b/aws/resource_aws_ec2_transit_gateway_peering_attachment_accepter_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func TestAccAWSEc2TransitGatewayPeeringAttachmentAccepter_basic_sameAccount(t *testing.T) { @@ -150,14 +150,14 @@ resource "aws_ec2_transit_gateway" "test" { } resource "aws_ec2_transit_gateway" "peer" { - provider = "aws.alternate" + provider = "awsalternate" tags = { Name = %[1]q } } resource "aws_ec2_transit_gateway_peering_attachment" "test" { - provider = "aws.alternate" + provider = "awsalternate" peer_account_id = aws_ec2_transit_gateway.test.owner_id peer_region = data.aws_region.current.name @@ -171,11 +171,11 @@ func testAccAWSEc2TransitGatewayPeeringAttachmentAccepterConfig_basic_sameAccoun return composeConfig( testAccAlternateRegionProviderConfig(), testAccAWSEc2TransitGatewayPeeringAttachmentAccepterConfigBase(rName), - fmt.Sprintf(` + ` resource "aws_ec2_transit_gateway_peering_attachment_accepter" "test" { transit_gateway_attachment_id = aws_ec2_transit_gateway_peering_attachment.test.id } -`)) +`) } func testAccAWSEc2TransitGatewayPeeringAttachmentAccepterConfig_tags_sameAccount(rName string) string { diff --git a/aws/resource_aws_ec2_transit_gateway_peering_attachment_test.go b/aws/resource_aws_ec2_transit_gateway_peering_attachment_test.go index 51d73597036..e7422f9760c 100644 --- a/aws/resource_aws_ec2_transit_gateway_peering_attachment_test.go +++ b/aws/resource_aws_ec2_transit_gateway_peering_attachment_test.go @@ -8,10 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -331,7 +331,7 @@ resource "aws_ec2_transit_gateway" "test" { } resource "aws_ec2_transit_gateway" "peer" { - provider = "aws.alternate" + provider = "awsalternate" tags = { Name = %[1]q @@ -352,8 +352,8 @@ func testAccAWSEc2TransitGatewayPeeringAttachmentConfigBasic_sameAccount(rName s return testAccAWSEc2TransitGatewayPeeringAttachmentConfig_sameAccount_base(rName) + fmt.Sprintf(` resource "aws_ec2_transit_gateway_peering_attachment" "test" { peer_region = %[1]q - peer_transit_gateway_id = "${aws_ec2_transit_gateway.peer.id}" - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" + peer_transit_gateway_id = aws_ec2_transit_gateway.peer.id + transit_gateway_id = aws_ec2_transit_gateway.test.id } `, testAccGetAlternateRegion()) } @@ -361,10 +361,10 @@ resource "aws_ec2_transit_gateway_peering_attachment" "test" { func testAccAWSEc2TransitGatewayPeeringAttachmentConfigBasic_differentAccount(rName string) string { return testAccAWSEc2TransitGatewayPeeringAttachmentConfig_differentAccount_base(rName) + fmt.Sprintf(` resource "aws_ec2_transit_gateway_peering_attachment" "test" { - peer_account_id = "${aws_ec2_transit_gateway.peer.owner_id}" + peer_account_id = aws_ec2_transit_gateway.peer.owner_id peer_region = %[1]q - peer_transit_gateway_id = "${aws_ec2_transit_gateway.peer.id}" - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" + peer_transit_gateway_id = aws_ec2_transit_gateway.peer.id + transit_gateway_id = aws_ec2_transit_gateway.test.id } `, testAccGetAlternateRegion()) } @@ -373,8 +373,8 @@ func testAccAWSEc2TransitGatewayPeeringAttachmentConfigTags1_sameAccount(rName, return testAccAWSEc2TransitGatewayPeeringAttachmentConfig_sameAccount_base(rName) + fmt.Sprintf(` resource "aws_ec2_transit_gateway_peering_attachment" "test" { peer_region = %[1]q - peer_transit_gateway_id = "${aws_ec2_transit_gateway.peer.id}" - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" + peer_transit_gateway_id = aws_ec2_transit_gateway.peer.id + transit_gateway_id = aws_ec2_transit_gateway.test.id tags = { Name = %[2]q @@ -388,8 +388,8 @@ func testAccAWSEc2TransitGatewayPeeringAttachmentConfigTags2_sameAccount(rName, return testAccAWSEc2TransitGatewayPeeringAttachmentConfig_sameAccount_base(rName) + fmt.Sprintf(` resource "aws_ec2_transit_gateway_peering_attachment" "test" { peer_region = %[1]q - peer_transit_gateway_id = "${aws_ec2_transit_gateway.peer.id}" - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" + peer_transit_gateway_id = aws_ec2_transit_gateway.peer.id + transit_gateway_id = aws_ec2_transit_gateway.test.id tags = { Name = %[2]q diff --git a/aws/resource_aws_ec2_transit_gateway_route.go b/aws/resource_aws_ec2_transit_gateway_route.go index a28412be6cb..b897cceb67a 100644 --- a/aws/resource_aws_ec2_transit_gateway_route.go +++ b/aws/resource_aws_ec2_transit_gateway_route.go @@ -5,12 +5,12 @@ import ( "log" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsEc2TransitGatewayRoute() *schema.Resource { diff --git a/aws/resource_aws_ec2_transit_gateway_route_table.go b/aws/resource_aws_ec2_transit_gateway_route_table.go index f19e19546ee..a336f505e0b 100644 --- a/aws/resource_aws_ec2_transit_gateway_route_table.go +++ b/aws/resource_aws_ec2_transit_gateway_route_table.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_ec2_transit_gateway_route_table_association.go b/aws/resource_aws_ec2_transit_gateway_route_table_association.go index c25dd5b0bf6..74279bbb4b1 100644 --- a/aws/resource_aws_ec2_transit_gateway_route_table_association.go +++ b/aws/resource_aws_ec2_transit_gateway_route_table_association.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsEc2TransitGatewayRouteTableAssociation() *schema.Resource { diff --git a/aws/resource_aws_ec2_transit_gateway_route_table_association_test.go b/aws/resource_aws_ec2_transit_gateway_route_table_association_test.go index 5f10b151a8b..4ef5527f375 100644 --- a/aws/resource_aws_ec2_transit_gateway_route_table_association_test.go +++ b/aws/resource_aws_ec2_transit_gateway_route_table_association_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSEc2TransitGatewayRouteTableAssociation_basic(t *testing.T) { @@ -109,7 +109,7 @@ func testAccCheckAWSEc2TransitGatewayRouteTableAssociationDestroy(s *terraform.S } func testAccAWSEc2TransitGatewayRouteTableAssociationConfig() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -120,7 +120,7 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-route" @@ -130,19 +130,19 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] + subnet_ids = [aws_subnet.test.id] transit_gateway_default_route_table_association = false - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } resource "aws_ec2_transit_gateway_route_table" "test" { - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id } resource "aws_ec2_transit_gateway_route_table_association" "test" { - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.test.id}" - transit_gateway_route_table_id = "${aws_ec2_transit_gateway_route_table.test.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.test.id + transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.test.id } -`) +` } diff --git a/aws/resource_aws_ec2_transit_gateway_route_table_propagation.go b/aws/resource_aws_ec2_transit_gateway_route_table_propagation.go index 61581e0e128..65cc21127d4 100644 --- a/aws/resource_aws_ec2_transit_gateway_route_table_propagation.go +++ b/aws/resource_aws_ec2_transit_gateway_route_table_propagation.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsEc2TransitGatewayRouteTablePropagation() *schema.Resource { diff --git a/aws/resource_aws_ec2_transit_gateway_route_table_propagation_test.go b/aws/resource_aws_ec2_transit_gateway_route_table_propagation_test.go index abdbc204283..ef1577bbb2e 100644 --- a/aws/resource_aws_ec2_transit_gateway_route_table_propagation_test.go +++ b/aws/resource_aws_ec2_transit_gateway_route_table_propagation_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSEc2TransitGatewayRouteTablePropagation_basic(t *testing.T) { @@ -109,7 +109,7 @@ func testAccCheckAWSEc2TransitGatewayRouteTablePropagationDestroy(s *terraform.S } func testAccAWSEc2TransitGatewayRouteTablePropagationConfig() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -120,7 +120,7 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-route" @@ -130,18 +130,18 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } resource "aws_ec2_transit_gateway_route_table" "test" { - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id } resource "aws_ec2_transit_gateway_route_table_propagation" "test" { - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.test.id}" - transit_gateway_route_table_id = "${aws_ec2_transit_gateway_route_table.test.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.test.id + transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.test.id } -`) +` } diff --git a/aws/resource_aws_ec2_transit_gateway_route_table_test.go b/aws/resource_aws_ec2_transit_gateway_route_table_test.go index f99d2b5d0a9..2258abb5020 100644 --- a/aws/resource_aws_ec2_transit_gateway_route_table_test.go +++ b/aws/resource_aws_ec2_transit_gateway_route_table_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSEc2TransitGatewayRouteTable_basic(t *testing.T) { @@ -77,7 +77,7 @@ func TestAccAWSEc2TransitGatewayRouteTable_disappears_TransitGateway(t *testing. Check: resource.ComposeTestCheckFunc( testAccCheckAWSEc2TransitGatewayExists(transitGatewayResourceName, &transitGateway1), testAccCheckAWSEc2TransitGatewayRouteTableExists(resourceName, &transitGatewayRouteTable1), - testAccCheckAWSEc2TransitGatewayDisappears(&transitGateway1), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEc2TransitGateway(), transitGatewayResourceName), ), ExpectNonEmptyPlan: true, }, @@ -222,13 +222,13 @@ func testAccCheckAWSEc2TransitGatewayRouteTableNotRecreated(i, j *ec2.TransitGat } func testAccAWSEc2TransitGatewayRouteTableConfig() string { - return fmt.Sprintf(` + return ` resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_route_table" "test" { - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id } -`) +` } func testAccAWSEc2TransitGatewayRouteTableConfigTags1(tagKey1, tagValue1 string) string { @@ -236,7 +236,7 @@ func testAccAWSEc2TransitGatewayRouteTableConfigTags1(tagKey1, tagValue1 string) resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_route_table" "test" { - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id tags = { %q = %q @@ -250,7 +250,7 @@ func testAccAWSEc2TransitGatewayRouteTableConfigTags2(tagKey1, tagValue1, tagKey resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_route_table" "test" { - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id tags = { %q = %q diff --git a/aws/resource_aws_ec2_transit_gateway_route_test.go b/aws/resource_aws_ec2_transit_gateway_route_test.go index e51161a9a3c..667c69e9921 100644 --- a/aws/resource_aws_ec2_transit_gateway_route_test.go +++ b/aws/resource_aws_ec2_transit_gateway_route_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSEc2TransitGatewayRoute_basic(t *testing.T) { @@ -204,11 +204,11 @@ func testAccCheckAWSEc2TransitGatewayRouteDisappears(transitGateway *ec2.Transit } func testAccAWSEc2TransitGatewayRouteConfigDestinationCidrBlock() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -225,9 +225,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-route" @@ -237,21 +237,21 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } resource "aws_ec2_transit_gateway_route" "test" { destination_cidr_block = "0.0.0.0/0" - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.test.id}" - transit_gateway_route_table_id = "${aws_ec2_transit_gateway.test.association_default_route_table_id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.test.id + transit_gateway_route_table_id = aws_ec2_transit_gateway.test.association_default_route_table_id } resource "aws_ec2_transit_gateway_route" "test_blackhole" { destination_cidr_block = "10.1.0.0/16" blackhole = true - transit_gateway_route_table_id = "${aws_ec2_transit_gateway.test.association_default_route_table_id}" + transit_gateway_route_table_id = aws_ec2_transit_gateway.test.association_default_route_table_id } -`) +` } diff --git a/aws/resource_aws_ec2_transit_gateway_test.go b/aws/resource_aws_ec2_transit_gateway_test.go index 1c0a8b4c684..e227df97440 100644 --- a/aws/resource_aws_ec2_transit_gateway_test.go +++ b/aws/resource_aws_ec2_transit_gateway_test.go @@ -4,13 +4,14 @@ import ( "errors" "fmt" "log" + "regexp" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -121,7 +122,7 @@ func TestAccAWSEc2TransitGateway_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSEc2TransitGatewayExists(resourceName, &transitGateway1), resource.TestCheckResourceAttr(resourceName, "amazon_side_asn", "64512"), - resource.TestCheckResourceAttrSet(resourceName, "arn"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`transit-gateway/tgw-.+`)), resource.TestCheckResourceAttrSet(resourceName, "association_default_route_table_id"), resource.TestCheckResourceAttr(resourceName, "auto_accept_shared_attachments", ec2.AutoAcceptSharedAttachmentsValueDisable), resource.TestCheckResourceAttr(resourceName, "default_route_table_association", ec2.DefaultRouteTableAssociationValueEnable), @@ -156,7 +157,7 @@ func TestAccAWSEc2TransitGateway_disappears(t *testing.T) { Config: testAccAWSEc2TransitGatewayConfig(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEc2TransitGatewayExists(resourceName, &transitGateway1), - testAccCheckAWSEc2TransitGatewayDisappears(&transitGateway1), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEc2TransitGateway(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -529,24 +530,6 @@ func testAccCheckAWSEc2TransitGatewayDestroy(s *terraform.State) error { return nil } -func testAccCheckAWSEc2TransitGatewayDisappears(transitGateway *ec2.TransitGateway) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - - input := &ec2.DeleteTransitGatewayInput{ - TransitGatewayId: transitGateway.TransitGatewayId, - } - - _, err := conn.DeleteTransitGateway(input) - - if err != nil { - return err - } - - return waitForEc2TransitGatewayDeletion(conn, aws.StringValue(transitGateway.TransitGatewayId)) - } -} - func testAccCheckAWSEc2TransitGatewayNotRecreated(i, j *ec2.TransitGateway) resource.TestCheckFunc { return func(s *terraform.State) error { if aws.StringValue(i.TransitGatewayId) != aws.StringValue(j.TransitGatewayId) { @@ -666,9 +649,9 @@ func testAccPreCheckAWSEc2TransitGateway(t *testing.T) { } func testAccAWSEc2TransitGatewayConfig() string { - return fmt.Sprintf(` + return ` resource "aws_ec2_transit_gateway" "test" {} -`) +` } func testAccAWSEc2TransitGatewayConfigAmazonSideASN(amazonSideASN int) string { @@ -688,12 +671,12 @@ resource "aws_ec2_transit_gateway" "test" { } func testAccAWSEc2TransitGatewayConfigDefaultRouteTableAssociationAndPropagationDisabled() string { - return fmt.Sprintf(` + return ` resource "aws_ec2_transit_gateway" "test" { default_route_table_association = "disable" default_route_table_propagation = "disable" } -`) +` } func testAccAWSEc2TransitGatewayConfigDefaultRouteTableAssociation(defaultRouteTableAssociation string) string { diff --git a/aws/resource_aws_ec2_transit_gateway_vpc_attachment.go b/aws/resource_aws_ec2_transit_gateway_vpc_attachment.go index 0b241e7e2ee..afc7d8524d8 100644 --- a/aws/resource_aws_ec2_transit_gateway_vpc_attachment.go +++ b/aws/resource_aws_ec2_transit_gateway_vpc_attachment.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -211,7 +211,7 @@ func resourceAwsEc2TransitGatewayVpcAttachmentRead(d *schema.ResourceData, meta func resourceAwsEc2TransitGatewayVpcAttachmentUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn - if d.HasChange("dns_support") || d.HasChange("ipv6_support") || d.HasChange("subnet_ids") { + if d.HasChanges("dns_support", "ipv6_support", "subnet_ids") { input := &ec2.ModifyTransitGatewayVpcAttachmentInput{ Options: &ec2.ModifyTransitGatewayVpcAttachmentRequestOptions{ DnsSupport: aws.String(d.Get("dns_support").(string)), @@ -241,7 +241,7 @@ func resourceAwsEc2TransitGatewayVpcAttachmentUpdate(d *schema.ResourceData, met } } - if d.HasChange("transit_gateway_default_route_table_association") || d.HasChange("transit_gateway_default_route_table_propagation") { + if d.HasChanges("transit_gateway_default_route_table_association", "transit_gateway_default_route_table_propagation") { transitGatewayID := d.Get("transit_gateway_id").(string) transitGateway, err := ec2DescribeTransitGateway(conn, transitGatewayID) diff --git a/aws/resource_aws_ec2_transit_gateway_vpc_attachment_accepter.go b/aws/resource_aws_ec2_transit_gateway_vpc_attachment_accepter.go index c12bd7ad9b8..6466dfb0aa7 100644 --- a/aws/resource_aws_ec2_transit_gateway_vpc_attachment_accepter.go +++ b/aws/resource_aws_ec2_transit_gateway_vpc_attachment_accepter.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -190,7 +190,7 @@ func resourceAwsEc2TransitGatewayVpcAttachmentAccepterRead(d *schema.ResourceDat func resourceAwsEc2TransitGatewayVpcAttachmentAccepterUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn - if d.HasChange("transit_gateway_default_route_table_association") || d.HasChange("transit_gateway_default_route_table_propagation") { + if d.HasChanges("transit_gateway_default_route_table_association", "transit_gateway_default_route_table_propagation") { transitGatewayID := d.Get("transit_gateway_id").(string) transitGateway, err := ec2DescribeTransitGateway(conn, transitGatewayID) diff --git a/aws/resource_aws_ec2_transit_gateway_vpc_attachment_accepter_test.go b/aws/resource_aws_ec2_transit_gateway_vpc_attachment_accepter_test.go index ca9c284ead8..2ec0eaaeacf 100644 --- a/aws/resource_aws_ec2_transit_gateway_vpc_attachment_accepter_test.go +++ b/aws/resource_aws_ec2_transit_gateway_vpc_attachment_accepter_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func TestAccAWSEc2TransitGatewayVpcAttachmentAccepter_basic(t *testing.T) { @@ -193,8 +193,8 @@ func testAccAWSEc2TransitGatewayVpcAttachmentAccepterConfig_base(rName string) s return testAccAlternateAccountProviderConfig() + fmt.Sprintf(` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -217,22 +217,22 @@ resource "aws_ram_resource_share" "test" { } resource "aws_ram_resource_association" "test" { - resource_arn = "${aws_ec2_transit_gateway.test.arn}" - resource_share_arn = "${aws_ram_resource_share.test.id}" + resource_arn = aws_ec2_transit_gateway.test.arn + resource_share_arn = aws_ram_resource_share.test.id } resource "aws_ram_principal_association" "test" { - principal = "${data.aws_caller_identity.creator.account_id}" - resource_share_arn = "${aws_ram_resource_share.test.id}" + principal = data.aws_caller_identity.creator.account_id + resource_share_arn = aws_ram_resource_share.test.id } # VPC attachment creator. data "aws_caller_identity" "creator" { - provider = "aws.alternate" + provider = "awsalternate" } resource "aws_vpc" "test" { - provider = "aws.alternate" + provider = "awsalternate" cidr_block = "10.0.0.0/16" @@ -242,11 +242,11 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - provider = "aws.alternate" + provider = "awsalternate" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = %[1]q @@ -254,13 +254,13 @@ resource "aws_subnet" "test" { } resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - provider = "aws.alternate" + provider = "awsalternate" - depends_on = ["aws_ram_principal_association.test", "aws_ram_resource_association.test"] + depends_on = [aws_ram_principal_association.test, aws_ram_resource_association.test] - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id tags = { Name = %[1]q @@ -271,17 +271,17 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { } func testAccAWSEc2TransitGatewayVpcAttachmentAccepterConfig_basic(rName string) string { - return testAccAWSEc2TransitGatewayVpcAttachmentAccepterConfig_base(rName) + fmt.Sprintf(` + return testAccAWSEc2TransitGatewayVpcAttachmentAccepterConfig_base(rName) + ` resource "aws_ec2_transit_gateway_vpc_attachment_accepter" "test" { - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.test.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.test.id } -`) +` } func testAccAWSEc2TransitGatewayVpcAttachmentAccepterConfig_tags(rName string) string { return testAccAWSEc2TransitGatewayVpcAttachmentAccepterConfig_base(rName) + fmt.Sprintf(` resource "aws_ec2_transit_gateway_vpc_attachment_accepter" "test" { - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.test.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.test.id tags = { Name = %[1]q @@ -296,7 +296,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment_accepter" "test" { func testAccAWSEc2TransitGatewayVpcAttachmentAccepterConfig_tagsUpdated(rName string) string { return testAccAWSEc2TransitGatewayVpcAttachmentAccepterConfig_base(rName) + fmt.Sprintf(` resource "aws_ec2_transit_gateway_vpc_attachment_accepter" "test" { - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.test.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.test.id tags = { Name = %[1]q @@ -311,7 +311,7 @@ resource "aws_ec2_transit_gateway_vpc_attachment_accepter" "test" { func testAccAWSEc2TransitGatewayVpcAttachmentAccepterConfig_defaultRouteTableAssociationAndPropagation(rName string, association, propagation bool) string { return testAccAWSEc2TransitGatewayVpcAttachmentAccepterConfig_base(rName) + fmt.Sprintf(` resource "aws_ec2_transit_gateway_vpc_attachment_accepter" "test" { - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.test.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.test.id tags = { Name = %[1]q diff --git a/aws/resource_aws_ec2_transit_gateway_vpc_attachment_test.go b/aws/resource_aws_ec2_transit_gateway_vpc_attachment_test.go index b7bea1599a8..d7b8d0562df 100644 --- a/aws/resource_aws_ec2_transit_gateway_vpc_attachment_test.go +++ b/aws/resource_aws_ec2_transit_gateway_vpc_attachment_test.go @@ -9,10 +9,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -542,11 +542,11 @@ func testAccCheckAWSEc2TransitGatewayVpcAttachmentNotRecreated(i, j *ec2.Transit } func testAccAWSEc2TransitGatewayVpcAttachmentConfig() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -563,9 +563,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" @@ -575,19 +575,19 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } -`) +` } func testAccAWSEc2TransitGatewayVpcAttachmentConfigDnsSupport(dnsSupport string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -604,22 +604,23 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" } } -resource "aws_ec2_transit_gateway" "test" {} +resource "aws_ec2_transit_gateway" "test" { +} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { dns_support = %q - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } `, dnsSupport) } @@ -628,8 +629,8 @@ func testAccAWSEc2TransitGatewayVpcAttachmentConfigIpv6Support(ipv6Support strin return fmt.Sprintf(` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -647,23 +648,24 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - ipv6_cidr_block = "${cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1)}" - vpc_id = "${aws_vpc.test.id}" + ipv6_cidr_block = cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1) + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" } } -resource "aws_ec2_transit_gateway" "test" {} +resource "aws_ec2_transit_gateway" "test" { +} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { ipv6_support = %q - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } `, ipv6Support) } @@ -672,8 +674,8 @@ func testAccAWSEc2TransitGatewayVpcAttachmentConfigSharedTransitGateway(rName st return testAccAlternateAccountProviderConfig() + fmt.Sprintf(` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -684,27 +686,27 @@ data "aws_availability_zones" "available" { data "aws_organizations_organization" "test" {} resource "aws_ec2_transit_gateway" "test" { - provider = "aws.alternate" + provider = "awsalternate" } resource "aws_ram_resource_share" "test" { - provider = "aws.alternate" + provider = "awsalternate" name = %[1]q } resource "aws_ram_resource_association" "test" { - provider = "aws.alternate" + provider = "awsalternate" - resource_arn = "${aws_ec2_transit_gateway.test.arn}" - resource_share_arn = "${aws_ram_resource_share.test.id}" + resource_arn = aws_ec2_transit_gateway.test.arn + resource_share_arn = aws_ram_resource_share.test.id } resource "aws_ram_principal_association" "test" { - provider = "aws.alternate" + provider = "awsalternate" - principal = "${data.aws_organizations_organization.test.arn}" - resource_share_arn = "${aws_ram_resource_share.test.id}" + principal = data.aws_organizations_organization.test.arn + resource_share_arn = aws_ram_resource_share.test.id } resource "aws_vpc" "test" { @@ -716,9 +718,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" @@ -726,21 +728,21 @@ resource "aws_subnet" "test" { } resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - depends_on = ["aws_ram_principal_association.test", "aws_ram_resource_association.test"] + depends_on = [aws_ram_principal_association.test, aws_ram_resource_association.test] - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } `, rName) } func testAccAWSEc2TransitGatewayVpcAttachmentConfigSubnetIds1() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -759,9 +761,9 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { count = "2" - availability_zone = "${data.aws_availability_zones.available.names[count.index]}" + availability_zone = data.aws_availability_zones.available.names[count.index] cidr_block = "10.0.${count.index}.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" @@ -771,19 +773,19 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.0.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.0.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } -`) +` } func testAccAWSEc2TransitGatewayVpcAttachmentConfigSubnetIds2() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -802,9 +804,9 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { count = "2" - availability_zone = "${data.aws_availability_zones.available.names[count.index]}" + availability_zone = data.aws_availability_zones.available.names[count.index] cidr_block = "10.0.${count.index}.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" @@ -814,19 +816,19 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.0.id}", "${aws_subnet.test.1.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.0.id, aws_subnet.test.1.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } -`) +` } func testAccAWSEc2TransitGatewayVpcAttachmentConfigTags1(tagKey1, tagValue1 string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -843,9 +845,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" @@ -855,9 +857,9 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id tags = { %q = %q @@ -870,8 +872,8 @@ func testAccAWSEc2TransitGatewayVpcAttachmentConfigTags2(tagKey1, tagValue1, tag return fmt.Sprintf(` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -888,9 +890,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" @@ -900,9 +902,9 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id tags = { %q = %q @@ -913,11 +915,11 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "test" { } func testAccAWSEc2TransitGatewayVpcAttachmentConfigTransitGatewayDefaultRouteTableAssociationAndPropagationDisabled() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -934,9 +936,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" @@ -949,21 +951,21 @@ resource "aws_ec2_transit_gateway" "test" { } resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] + subnet_ids = [aws_subnet.test.id] transit_gateway_default_route_table_association = false transit_gateway_default_route_table_propagation = false - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } -`) +` } func testAccAWSEc2TransitGatewayVpcAttachmentConfigTransitGatewayDefaultRouteTableAssociation(transitGatewayDefaultRouteTableAssociation bool) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -980,22 +982,23 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" } } -resource "aws_ec2_transit_gateway" "test" {} +resource "aws_ec2_transit_gateway" "test" { +} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] + subnet_ids = [aws_subnet.test.id] transit_gateway_default_route_table_association = %t - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } `, transitGatewayDefaultRouteTableAssociation) } @@ -1004,8 +1007,8 @@ func testAccAWSEc2TransitGatewayVpcAttachmentConfigTransitGatewayDefaultRouteTab return fmt.Sprintf(` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -1022,22 +1025,23 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-transit-gateway-vpc-attachment" } } -resource "aws_ec2_transit_gateway" "test" {} +resource "aws_ec2_transit_gateway" "test" { +} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] + subnet_ids = [aws_subnet.test.id] transit_gateway_default_route_table_propagation = %t - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } `, transitGatewayDefaultRouteTablePropagation) } diff --git a/aws/resource_aws_ecr_lifecycle_policy.go b/aws/resource_aws_ecr_lifecycle_policy.go index 643a5e15593..aae91879514 100644 --- a/aws/resource_aws_ecr_lifecycle_policy.go +++ b/aws/resource_aws_ecr_lifecycle_policy.go @@ -3,8 +3,8 @@ package aws import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecr" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsEcrLifecyclePolicy() *schema.Resource { diff --git a/aws/resource_aws_ecr_lifecycle_policy_test.go b/aws/resource_aws_ecr_lifecycle_policy_test.go index 3b84a49c443..1aa8ea19258 100644 --- a/aws/resource_aws_ecr_lifecycle_policy_test.go +++ b/aws/resource_aws_ecr_lifecycle_policy_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecr" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSEcrLifecyclePolicy_basic(t *testing.T) { @@ -88,7 +88,7 @@ resource "aws_ecr_repository" "test" { } resource "aws_ecr_lifecycle_policy" "test" { - repository = "${aws_ecr_repository.test.name}" + repository = aws_ecr_repository.test.name policy = < 0 { - var pc []*ecs.PlacementConstraint - for _, raw := range constraints { - p := raw.(map[string]interface{}) - t := p["type"].(string) - e := p["expression"].(string) - if err := validateAwsEcsPlacementConstraint(t, e); err != nil { - return err - } - constraint := &ecs.PlacementConstraint{ - Type: aws.String(t), - } - if e != "" { - constraint.Expression = aws.String(e) - } + if v, ok := d.Get("placement_constraints").(*schema.Set); ok { + pc, err := expandPlacementConstraints(v.List()) - pc = append(pc, constraint) + if err != nil { + return err } + input.PlacementConstraints = pc } - serviceRegistries := d.Get("service_registries").(*schema.Set).List() + serviceRegistries := d.Get("service_registries").([]interface{}) if len(serviceRegistries) > 0 { srs := make([]*ecs.ServiceRegistry, 0, len(serviceRegistries)) for _, v := range serviceRegistries { @@ -619,12 +599,17 @@ func resourceAwsEcsServiceRead(d *schema.ResourceData, meta interface{}) error { d.SetId(aws.StringValue(service.ServiceArn)) d.Set("name", service.ServiceName) - // Save task definition in the same format - if strings.HasPrefix(d.Get("task_definition").(string), "arn:"+meta.(*AWSClient).partition+":ecs:") { - d.Set("task_definition", service.TaskDefinition) - } else { - taskDefinition := buildFamilyAndRevisionFromARN(*service.TaskDefinition) - d.Set("task_definition", taskDefinition) + // When creating a service that uses the EXTERNAL deployment controller, + // you can specify only parameters that aren't controlled at the task set level + // hence TaskDefinition will not be set by aws sdk + if service.TaskDefinition != nil { + // Save task definition in the same format + if strings.HasPrefix(d.Get("task_definition").(string), "arn:"+meta.(*AWSClient).partition+":ecs:") { + d.Set("task_definition", service.TaskDefinition) + } else { + taskDefinition := buildFamilyAndRevisionFromARN(*service.TaskDefinition) + d.Set("task_definition", taskDefinition) + } } d.Set("scheduling_strategy", service.SchedulingStrategy) @@ -797,6 +782,40 @@ func flattenEcsCapacityProviderStrategy(cps []*ecs.CapacityProviderStrategyItem) return results } +func expandPlacementConstraints(tfList []interface{}) ([]*ecs.PlacementConstraint, error) { + if len(tfList) == 0 { + return nil, nil + } + + var result []*ecs.PlacementConstraint + + for _, tfMapRaw := range tfList { + if tfMapRaw == nil { + continue + } + + tfMap := tfMapRaw.(map[string]interface{}) + + apiObject := &ecs.PlacementConstraint{} + + if v, ok := tfMap["expression"].(string); ok && v != "" { + apiObject.Expression = aws.String(v) + } + + if v, ok := tfMap["type"].(string); ok && v != "" { + apiObject.Type = aws.String(v) + } + + if err := validateAwsEcsPlacementConstraint(aws.StringValue(apiObject.Type), aws.StringValue(apiObject.Expression)); err != nil { + return result, err + } + + result = append(result, apiObject) + } + + return result, nil +} + func flattenServicePlacementConstraints(pcs []*ecs.PlacementConstraint) []map[string]interface{} { if len(pcs) == 0 { return nil @@ -820,9 +839,24 @@ func expandPlacementStrategy(s []interface{}) ([]*ecs.PlacementStrategy, error) } pss := make([]*ecs.PlacementStrategy, 0) for _, raw := range s { - p := raw.(map[string]interface{}) - t := p["type"].(string) - f := p["field"].(string) + p, ok := raw.(map[string]interface{}) + + if !ok { + continue + } + + t, ok := p["type"].(string) + + if !ok { + return nil, fmt.Errorf("missing type attribute in placement strategy configuration block") + } + + f, ok := p["field"].(string) + + if !ok { + return nil, fmt.Errorf("missing field attribute in placement strategy configuration block") + } + if err := validateAwsEcsPlacementStrategy(t, f); err != nil { return nil, err } @@ -889,8 +923,9 @@ func resourceAwsEcsServiceUpdate(d *schema.ResourceData, meta interface{}) error updateService := false input := ecs.UpdateServiceInput{ - Service: aws.String(d.Id()), - Cluster: aws.String(d.Get("cluster").(string)), + Cluster: aws.String(d.Get("cluster").(string)), + ForceNewDeployment: aws.Bool(d.Get("force_new_deployment").(bool)), + Service: aws.String(d.Id()), } schedulingStrategy := d.Get("scheduling_strategy").(string) @@ -908,7 +943,7 @@ func resourceAwsEcsServiceUpdate(d *schema.ResourceData, meta interface{}) error input.DesiredCount = aws.Int64(int64(d.Get("desired_count").(int))) } - if d.HasChange("deployment_maximum_percent") || d.HasChange("deployment_minimum_healthy_percent") { + if d.HasChanges("deployment_maximum_percent", "deployment_minimum_healthy_percent") { updateService = true input.DeploymentConfiguration = &ecs.DeploymentConfiguration{ MaximumPercent: aws.Int64(int64(d.Get("deployment_maximum_percent").(int))), @@ -917,6 +952,40 @@ func resourceAwsEcsServiceUpdate(d *schema.ResourceData, meta interface{}) error } } + if d.HasChange("ordered_placement_strategy") { + updateService = true + // Reference: https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html#ECS-UpdateService-request-placementStrategy + // To remove an existing placement strategy, specify an empty object. + input.PlacementStrategy = []*ecs.PlacementStrategy{} + + if v, ok := d.GetOk("ordered_placement_strategy"); ok && len(v.([]interface{})) > 0 { + ps, err := expandPlacementStrategy(v.([]interface{})) + + if err != nil { + return err + } + + input.PlacementStrategy = ps + } + } + + if d.HasChange("placement_constraints") { + updateService = true + // Reference: https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html#ECS-UpdateService-request-placementConstraints + // To remove all existing placement constraints, specify an empty array. + input.PlacementConstraints = []*ecs.PlacementConstraint{} + + if v, ok := d.Get("placement_constraints").(*schema.Set); ok && v.Len() > 0 { + pc, err := expandPlacementConstraints(v.List()) + + if err != nil { + return err + } + + input.PlacementConstraints = pc + } + } + if d.HasChange("platform_version") { updateService = true input.PlatformVersion = aws.String(d.Get("platform_version").(string)) @@ -1022,7 +1091,7 @@ func resourceAwsEcsServiceDelete(d *schema.ResourceData, meta interface{}) error Cluster: aws.String(d.Get("cluster").(string)), } // Wait until the ECS service is drained - err = resource.Retry(5*time.Minute, func() *resource.RetryError { + err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError { log.Printf("[DEBUG] Trying to delete ECS service %s", input) _, err := conn.DeleteService(&input) if err != nil { diff --git a/aws/resource_aws_ecs_service_test.go b/aws/resource_aws_ecs_service_test.go index 6e2c2222ffe..4fc7bee856c 100644 --- a/aws/resource_aws_ecs_service_test.go +++ b/aws/resource_aws_ecs_service_test.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecs" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -443,7 +443,7 @@ func TestAccAWSEcsService_withDeploymentController_Type_CodeDeploy(t *testing.T) Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsServiceExists(resourceName, &service), resource.TestCheckResourceAttr(resourceName, "deployment_controller.#", "1"), - resource.TestCheckResourceAttr(resourceName, "deployment_controller.0.type", "CODE_DEPLOY"), + resource.TestCheckResourceAttr(resourceName, "deployment_controller.0.type", ecs.DeploymentControllerTypeCodeDeploy), ), }, { @@ -458,6 +458,34 @@ func TestAccAWSEcsService_withDeploymentController_Type_CodeDeploy(t *testing.T) }) } +func TestAccAWSEcsService_withDeploymentController_Type_External(t *testing.T) { + var service ecs.Service + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_ecs_service.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcsServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEcsServiceConfigDeploymentControllerTypeExternal(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEcsServiceExists(resourceName, &service), + resource.TestCheckResourceAttr(resourceName, "deployment_controller.#", "1"), + resource.TestCheckResourceAttr(resourceName, "deployment_controller.0.type", ecs.DeploymentControllerTypeExternal), + ), + }, + { + ResourceName: resourceName, + ImportStateId: fmt.Sprintf("%s/%s", rName, rName), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func TestAccAWSEcsService_withDeploymentValues(t *testing.T) { var service ecs.Service rString := acctest.RandString(8) @@ -617,8 +645,44 @@ func TestAccAWSEcsService_withMultipleTargetGroups(t *testing.T) { }, }) } + +func TestAccAWSEcsService_withForceNewDeployment(t *testing.T) { + var service1, service2 ecs.Service + resourceName := "aws_ecs_service.mongo" + rString := acctest.RandString(8) + + clusterName := fmt.Sprintf("tf-acc-cluster-svc-w-ps-%s", rString) + tdName := fmt.Sprintf("tf-acc-td-svc-w-ps-%s", rString) + svcName := fmt.Sprintf("tf-acc-svc-w-ps-%s", rString) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcsServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEcsService(clusterName, tdName, svcName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEcsServiceExists(resourceName, &service1), + resource.TestCheckResourceAttr(resourceName, "ordered_placement_strategy.#", "0"), + ), + }, + { + Config: testAccAWSEcsServiceWithForceNewDeployment(clusterName, tdName, svcName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEcsServiceExists(resourceName, &service2), + testAccCheckAWSEcsServiceNotRecreated(&service1, &service2), + resource.TestCheckResourceAttr(resourceName, "ordered_placement_strategy.#", "1"), + resource.TestCheckResourceAttr(resourceName, "ordered_placement_strategy.0.type", "binpack"), + resource.TestCheckResourceAttr(resourceName, "ordered_placement_strategy.0.field", "memory"), + ), + }, + }, + }) +} + func TestAccAWSEcsService_withPlacementStrategy(t *testing.T) { - var service ecs.Service + var service1, service2, service3, service4 ecs.Service rString := acctest.RandString(8) clusterName := fmt.Sprintf("tf-acc-cluster-svc-w-ps-%s", rString) @@ -633,14 +697,15 @@ func TestAccAWSEcsService_withPlacementStrategy(t *testing.T) { { Config: testAccAWSEcsService(clusterName, tdName, svcName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo", &service), + testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo", &service1), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "ordered_placement_strategy.#", "0"), ), }, { Config: testAccAWSEcsServiceWithPlacementStrategy(clusterName, tdName, svcName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo", &service), + testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo", &service2), + testAccCheckAWSEcsServiceNotRecreated(&service1, &service2), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "ordered_placement_strategy.#", "1"), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "ordered_placement_strategy.0.type", "binpack"), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "ordered_placement_strategy.0.field", "memory"), @@ -649,7 +714,8 @@ func TestAccAWSEcsService_withPlacementStrategy(t *testing.T) { { Config: testAccAWSEcsServiceWithRandomPlacementStrategy(clusterName, tdName, svcName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo", &service), + testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo", &service3), + testAccCheckAWSEcsServiceNotRecreated(&service2, &service3), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "ordered_placement_strategy.#", "1"), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "ordered_placement_strategy.0.type", "random"), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "ordered_placement_strategy.0.field", ""), @@ -658,7 +724,8 @@ func TestAccAWSEcsService_withPlacementStrategy(t *testing.T) { { Config: testAccAWSEcsServiceWithMultiPlacementStrategy(clusterName, tdName, svcName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo", &service), + testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo", &service4), + testAccCheckAWSEcsServiceNotRecreated(&service3, &service4), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "ordered_placement_strategy.#", "2"), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "ordered_placement_strategy.0.type", "binpack"), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "ordered_placement_strategy.0.field", "memory"), @@ -670,8 +737,25 @@ func TestAccAWSEcsService_withPlacementStrategy(t *testing.T) { }) } +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/13146 +func TestAccAWSEcsService_withPlacementStrategy_Type_Missing(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcsServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEcsServiceWithPlacementStrategyType(rName, ""), + ExpectError: regexp.MustCompile(`expected ordered_placement_strategy.0.type to be one of`), + }, + }, + }) +} + func TestAccAWSEcsService_withPlacementConstraints(t *testing.T) { - var service ecs.Service + var service1, service2 ecs.Service rString := acctest.RandString(8) clusterName := fmt.Sprintf("tf-acc-cluster-svc-w-pc-%s", rString) @@ -686,7 +770,15 @@ func TestAccAWSEcsService_withPlacementConstraints(t *testing.T) { { Config: testAccAWSEcsServiceWithPlacementConstraint(clusterName, tdName, svcName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo", &service), + testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo", &service1), + resource.TestCheckResourceAttr("aws_ecs_service.mongo", "placement_constraints.#", "1"), + ), + }, + { + Config: testAccAWSEcsServiceWithPlacementConstraintEmptyExpression(clusterName, tdName, svcName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEcsServiceExists("aws_ecs_service.mongo", &service2), + testAccCheckAWSEcsServiceNotRecreated(&service1, &service2), resource.TestCheckResourceAttr("aws_ecs_service.mongo", "placement_constraints.#", "1"), ), }, @@ -1186,6 +1278,16 @@ func testAccCheckAWSEcsServiceDisappears(service *ecs.Service) resource.TestChec } } +func testAccCheckAWSEcsServiceNotRecreated(i, j *ecs.Service) resource.TestCheckFunc { + return func(s *terraform.State) error { + if aws.TimeValue(i.CreatedAt) != aws.TimeValue(j.CreatedAt) { + return fmt.Errorf("ECS Service (%s) unexpectedly recreated", aws.StringValue(j.ServiceArn)) + } + + return nil + } +} + func testAccAWSEcsService(clusterName, tdName, svcName string) string { return fmt.Sprintf(` resource "aws_ecs_cluster" "default" { @@ -1206,12 +1308,13 @@ resource "aws_ecs_task_definition" "mongo" { } ] DEFINITION + } resource "aws_ecs_service" "mongo" { name = "%s" - cluster = "${aws_ecs_cluster.default.id}" - task_definition = "${aws_ecs_task_definition.mongo.arn}" + cluster = aws_ecs_cluster.default.id + task_definition = aws_ecs_task_definition.mongo.arn desired_count = 1 } `, clusterName, tdName, svcName) @@ -1237,12 +1340,13 @@ resource "aws_ecs_task_definition" "mongo" { } ] DEFINITION + } resource "aws_ecs_service" "mongo" { name = "%s" - cluster = "${aws_ecs_cluster.default.id}" - task_definition = "${aws_ecs_task_definition.mongo.arn}" + cluster = aws_ecs_cluster.default.id + task_definition = aws_ecs_task_definition.mongo.arn desired_count = 2 } `, clusterName, tdName, svcName) @@ -1268,12 +1372,13 @@ resource "aws_ecs_task_definition" "mongo" { } ] DEFINITION + } resource "aws_ecs_service" "mongo" { name = "%s" - cluster = "${aws_ecs_cluster.default.id}" - task_definition = "${aws_ecs_task_definition.mongo.arn}" + cluster = aws_ecs_cluster.default.id + task_definition = aws_ecs_task_definition.mongo.arn desired_count = 1 ordered_placement_strategy { @@ -1288,6 +1393,7 @@ func testAccAWSEcsServiceWithCapacityProviderStrategy(providerName, clusterName, return testAccAWSEcsCapacityProviderConfigBase(providerName) + fmt.Sprintf(` resource "aws_ecs_capacity_provider" "test" { name = %q + auto_scaling_group_provider { auto_scaling_group_arn = aws_autoscaling_group.test.arn } @@ -1315,8 +1421,8 @@ DEFINITION resource "aws_ecs_service" "mongo" { name = "%s" - cluster = "${aws_ecs_cluster.default.id}" - task_definition = "${aws_ecs_task_definition.mongo.arn}" + cluster = aws_ecs_cluster.default.id + task_definition = aws_ecs_task_definition.mongo.arn desired_count = 1 capacity_provider_strategy { @@ -1376,19 +1482,19 @@ DEFINITION resource "aws_security_group" "allow_all" { name = "%s" description = "Allow all inbound traffic" - vpc_id = "${aws_vpc.main.id}" + vpc_id = aws_vpc.main.id ingress { protocol = "tcp" from_port = 80 to_port = 8000 - cidr_blocks = ["${aws_vpc.main.cidr_block}"] + cidr_blocks = [aws_vpc.main.cidr_block] } } resource "aws_subnet" "main" { - cidr_block = "${cidrsubnet(aws_vpc.main.cidr_block, 8, 1)}" - vpc_id = "${aws_vpc.main.id}" + cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, 1) + vpc_id = aws_vpc.main.id tags = { Name = "tf-acc-ecs-service-with-multiple-capacity-providers" @@ -1405,6 +1511,44 @@ resource "aws_vpc" "main" { `, tdName, svcName, sgName) } +func testAccAWSEcsServiceWithForceNewDeployment(clusterName, tdName, svcName string) string { + return fmt.Sprintf(` +resource "aws_ecs_cluster" "default" { + name = "%s" +} + +resource "aws_ecs_task_definition" "mongo" { + family = "%s" + + container_definitions = < 0 && v.([]interface{})[0] != nil { + m := v.([]interface{})[0].(map[string]interface{}) + + if v, ok := m["file_system_id"]; ok && v.(string) != "" { + buf.WriteString(fmt.Sprintf("%s-", v.(string))) + } + + if v, ok := m["root_directory"]; ok && v.(string) != "" { + buf.WriteString(fmt.Sprintf("%s-", v.(string))) + } + + if v, ok := m["transit_encryption"]; ok && v.(string) != "" { + buf.WriteString(fmt.Sprintf("%s-", v.(string))) + } + if v, ok := m["transit_encryption_port"]; ok && v.(int) > 0 { + buf.WriteString(fmt.Sprintf("%d-", v.(int))) + } + if v, ok := m["authorization_config"]; ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil { + m := v.([]interface{})[0].(map[string]interface{}) + if v, ok := m["access_point_id"]; ok && v.(string) != "" { + buf.WriteString(fmt.Sprintf("%s-", v.(string))) + } + if v, ok := m["iam"]; ok && v.(string) != "" { + buf.WriteString(fmt.Sprintf("%s-", v.(string))) + } + } + + } + return hashcode.String(buf.String()) } @@ -608,7 +683,7 @@ func flattenEcsInferenceAccelerators(list []*ecs.InferenceAccelerator) []map[str return result } -func expandEcsInferenceAccelerators(configured []interface{}) ([]*ecs.InferenceAccelerator, error) { +func expandEcsInferenceAccelerators(configured []interface{}) []*ecs.InferenceAccelerator { iAccs := make([]*ecs.InferenceAccelerator, 0, len(configured)) for _, lRaw := range configured { data := lRaw.(map[string]interface{}) @@ -619,5 +694,5 @@ func expandEcsInferenceAccelerators(configured []interface{}) ([]*ecs.InferenceA iAccs = append(iAccs, l) } - return iAccs, nil + return iAccs } diff --git a/aws/resource_aws_ecs_task_definition_migrate.go b/aws/resource_aws_ecs_task_definition_migrate.go index b0bbe57d5e1..4fc433397a1 100644 --- a/aws/resource_aws_ecs_task_definition_migrate.go +++ b/aws/resource_aws_ecs_task_definition_migrate.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/private/protocol/json/jsonutil" "github.com/aws/aws-sdk-go/service/ecs" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func resourceAwsEcsTaskDefinitionMigrateState(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { diff --git a/aws/resource_aws_ecs_task_definition_test.go b/aws/resource_aws_ecs_task_definition_test.go index 5e581f91d8b..43be93084ec 100644 --- a/aws/resource_aws_ecs_task_definition_test.go +++ b/aws/resource_aws_ecs_task_definition_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecs" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -135,26 +135,15 @@ func TestAccAWSEcsTaskDefinition_withDockerVolume(t *testing.T) { resourceName := "aws_ecs_task_definition.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, Steps: []resource.TestStep{ { Config: testAccAWSEcsTaskDefinitionWithDockerVolumes(tdName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.#", "1"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.scope", "shared"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.autoprovision", "true"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.driver", "local"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.driver_opts.%", "2"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.driver_opts.uid", "1000"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.driver_opts.device", "tmpfs"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.labels.%", "2"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.labels.stack", "april"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.labels.environment", "test"), ), }, { @@ -174,19 +163,15 @@ func TestAccAWSEcsTaskDefinition_withDockerVolumeMinimalConfig(t *testing.T) { resourceName := "aws_ecs_task_definition.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, Steps: []resource.TestStep{ { Config: testAccAWSEcsTaskDefinitionWithDockerVolumesMinimalConfig(tdName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.#", "1"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.scope", "task"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.driver", "local"), ), }, { @@ -204,21 +189,17 @@ func TestAccAWSEcsTaskDefinition_withEFSVolumeMinimal(t *testing.T) { tdName := acctest.RandomWithPrefix("tf-acc-td-with-efs-volume-min") resourceName := "aws_ecs_task_definition.test" - efsResourceName := "aws_efs_file_system.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, Steps: []resource.TestStep{ { Config: testAccAWSEcsTaskDefinitionWithEFSVolumeMinimal(tdName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.efs_volume_configuration.#", "1"), - resource.TestCheckResourceAttrPair(resourceName, "volume.584193650.efs_volume_configuration.0.file_system_id", efsResourceName, "id"), ), }, { @@ -236,22 +217,72 @@ func TestAccAWSEcsTaskDefinition_withEFSVolume(t *testing.T) { tdName := acctest.RandomWithPrefix("tf-acc-td-with-efs-volume") resourceName := "aws_ecs_task_definition.test" - efsResourceName := "aws_efs_file_system.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, Steps: []resource.TestStep{ { Config: testAccAWSEcsTaskDefinitionWithEFSVolume(tdName, "/home/test"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEcsTaskDefinitionExists(resourceName, &def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.efs_volume_configuration.#", "1"), - resource.TestCheckResourceAttrPair(resourceName, "volume.584193650.efs_volume_configuration.0.file_system_id", efsResourceName, "id"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.efs_volume_configuration.0.root_directory", "/home/test"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSEcsTaskDefinitionImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSEcsTaskDefinition_withTransitEncryptionEFSVolume(t *testing.T) { + var def ecs.TaskDefinition + + tdName := acctest.RandomWithPrefix("tf-acc-td-with-efs-volume") + resourceName := "aws_ecs_task_definition.test" + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEcsTaskDefinitionWithTransitEncryptionEFSVolume(tdName, "ENABLED", 2999), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEcsTaskDefinitionExists(resourceName, &def), + resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSEcsTaskDefinitionImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSEcsTaskDefinition_withEFSAccessPoint(t *testing.T) { + var def ecs.TaskDefinition + + tdName := acctest.RandomWithPrefix("tf-acc-td-with-efs-volume") + resourceName := "aws_ecs_task_definition.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEcsTaskDefinitionWithEFSAccessPoint(tdName, "DISABLED"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEcsTaskDefinitionExists(resourceName, &def), + resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), ), }, { @@ -271,10 +302,9 @@ func TestAccAWSEcsTaskDefinition_withTaskScopedDockerVolume(t *testing.T) { resourceName := "aws_ecs_task_definition.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEcsTaskDefinitionDestroy, Steps: []resource.TestStep{ { Config: testAccAWSEcsTaskDefinitionWithTaskScopedDockerVolume(tdName), @@ -282,8 +312,6 @@ func TestAccAWSEcsTaskDefinition_withTaskScopedDockerVolume(t *testing.T) { testAccCheckAWSEcsTaskDefinitionExists(resourceName, &def), testAccCheckAWSTaskDefinitionDockerVolumeConfigurationAutoprovisionNil(&def), resource.TestCheckResourceAttr(resourceName, "volume.#", "1"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.#", "1"), - resource.TestCheckResourceAttr(resourceName, "volume.584193650.docker_volume_configuration.0.scope", "task"), ), }, { @@ -775,20 +803,20 @@ resource "aws_ecs_cluster" "test" { } resource "aws_ecs_task_definition" "test" { - family = %q + family = %q network_mode = "awsvpc" proxy_configuration { - type = %q + type = %q container_name = %q properties = { - IgnoredUID = %q - IgnoredGID = %q - AppPorts = %q - ProxyIngressPort = %q - ProxyEgressPort = %q + IgnoredUID = %q + IgnoredGID = %q + AppPorts = %q + ProxyIngressPort = %q + ProxyEgressPort = %q EgressIgnoredPorts = %q - EgressIgnoredIPs = %q + EgressIgnoredIPs = %q } } @@ -1010,6 +1038,7 @@ resource "aws_ecs_task_definition" "test" { ] TASK_DEFINITION + volume { name = "jenkins-home" host_path = "/ecs/jenkins-home" @@ -1067,6 +1096,7 @@ resource "aws_ecs_task_definition" "test" { ] TASK_DEFINITION + volume { name = "jenkins-home" host_path = "/ecs/jenkins-home" @@ -1119,6 +1149,7 @@ resource "aws_ecs_task_definition" "test" { ] TASK_DEFINITION + volume { name = "jenkins-home" host_path = "/ecs/jenkins" @@ -1220,6 +1251,7 @@ resource "aws_ecs_task_definition" "test" { ] TASK_DEFINITION + volume { name = "vol1" host_path = "/host/vol1" @@ -1260,6 +1292,7 @@ resource "aws_ecs_task_definition" "test" { } ] TASK_DEFINITION + } `, tdName, portMappings) } @@ -1284,6 +1317,7 @@ resource "aws_iam_role" "test" { ] } EOF + } resource "aws_iam_policy" "test" { @@ -1309,16 +1343,17 @@ resource "aws_iam_policy" "test" { ] } EOF + } resource "aws_iam_role_policy_attachment" "test" { - role = "${aws_iam_role.test.name}" - policy_arn = "${aws_iam_policy.test.arn}" + role = aws_iam_role.test.name + policy_arn = aws_iam_policy.test.arn } resource "aws_ecs_task_definition" "test" { family = "%s" - execution_role_arn = "${aws_iam_role.test.arn}" + execution_role_arn = aws_iam_role.test.arn container_definitions = < 0 { + return false + } + return true +} + +func expandEfsAccessPointPosixUser(pUser []interface{}) *efs.PosixUser { + if len(pUser) < 1 || pUser[0] == nil { + return nil + } + + m := pUser[0].(map[string]interface{}) + + posixUser := &efs.PosixUser{ + Gid: aws.Int64(int64(m["gid"].(int))), + Uid: aws.Int64(int64(m["uid"].(int))), + } + + if v, ok := m["secondary_gids"].(*schema.Set); ok && len(v.List()) > 0 { + posixUser.SecondaryGids = expandInt64Set(v) + } + + return posixUser +} + +func expandEfsAccessPointRootDirectory(rDir []interface{}) *efs.RootDirectory { + if len(rDir) < 1 || rDir[0] == nil { + return nil + } + + m := rDir[0].(map[string]interface{}) + + rootDir := &efs.RootDirectory{} + + if v, ok := m["path"]; ok { + rootDir.Path = aws.String(v.(string)) + } + + if v, ok := m["creation_info"]; ok { + rootDir.CreationInfo = expandEfsAccessPointRootDirectoryCreationInfo(v.([]interface{})) + } + + return rootDir +} + +func expandEfsAccessPointRootDirectoryCreationInfo(cInfo []interface{}) *efs.CreationInfo { + if len(cInfo) < 1 || cInfo[0] == nil { + return nil + } + + m := cInfo[0].(map[string]interface{}) + + creationInfo := &efs.CreationInfo{ + OwnerGid: aws.Int64(int64(m["owner_gid"].(int))), + OwnerUid: aws.Int64(int64(m["owner_uid"].(int))), + Permissions: aws.String(m["permissions"].(string)), + } + + return creationInfo +} + +func flattenEfsAccessPointPosixUser(posixUser *efs.PosixUser) []interface{} { + if posixUser == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "gid": aws.Int64Value(posixUser.Gid), + "uid": aws.Int64Value(posixUser.Uid), + "secondary_gids": aws.Int64ValueSlice(posixUser.SecondaryGids), + } + + return []interface{}{m} +} + +func flattenEfsAccessPointRootDirectory(rDir *efs.RootDirectory) []interface{} { + if rDir == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "path": aws.StringValue(rDir.Path), + "creation_info": flattenEfsAccessPointRootDirectoryCreationInfo(rDir.CreationInfo), + } + + return []interface{}{m} +} + +func flattenEfsAccessPointRootDirectoryCreationInfo(cInfo *efs.CreationInfo) []interface{} { + if cInfo == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "owner_gid": aws.Int64Value(cInfo.OwnerGid), + "owner_uid": aws.Int64Value(cInfo.OwnerUid), + "permissions": aws.StringValue(cInfo.Permissions), + } + + return []interface{}{m} +} diff --git a/aws/resource_aws_efs_access_point_test.go b/aws/resource_aws_efs_access_point_test.go new file mode 100644 index 00000000000..ea197b5237a --- /dev/null +++ b/aws/resource_aws_efs_access_point_test.go @@ -0,0 +1,476 @@ +package aws + +import ( + "fmt" + "log" + "regexp" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/efs" + + multierror "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func init() { + resource.AddTestSweepers("aws_efs_access_point", &resource.Sweeper{ + Name: "aws_efs_access_point", + F: testSweepEfsAccessPoints, + }) +} + +func testSweepEfsAccessPoints(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %s", err) + } + conn := client.(*AWSClient).efsconn + + var errors error + input := &efs.DescribeFileSystemsInput{} + err = conn.DescribeFileSystemsPages(input, func(page *efs.DescribeFileSystemsOutput, lastPage bool) bool { + for _, filesystem := range page.FileSystems { + id := aws.StringValue(filesystem.FileSystemId) + log.Printf("[INFO] Deleting access points for EFS File System: %s", id) + + var errors error + input := &efs.DescribeAccessPointsInput{ + FileSystemId: filesystem.FileSystemId, + } + for { + out, err := conn.DescribeAccessPoints(input) + if err != nil { + errors = multierror.Append(errors, fmt.Errorf("error retrieving EFS access points on File System %q: %w", id, err)) + break + } + + if out == nil || len(out.AccessPoints) == 0 { + log.Printf("[INFO] No EFS access points to sweep on File System %q", id) + break + } + + for _, AccessPoint := range out.AccessPoints { + id := aws.StringValue(AccessPoint.AccessPointId) + + log.Printf("[INFO] Deleting EFS access point: %s", id) + _, err := conn.DeleteAccessPoint(&efs.DeleteAccessPointInput{ + AccessPointId: AccessPoint.AccessPointId, + }) + if err != nil { + errors = multierror.Append(errors, fmt.Errorf("error deleting EFS access point %q: %w", id, err)) + continue + } + + err = waitForDeleteEfsAccessPoint(conn, id, 10*time.Minute) + if err != nil { + errors = multierror.Append(errors, fmt.Errorf("error waiting for EFS access point %q to delete: %w", id, err)) + continue + } + } + + if out.NextToken == nil { + break + } + input.NextToken = out.NextToken + } + } + return true + }) + if err != nil { + errors = multierror.Append(errors, fmt.Errorf("error retrieving EFS File Systems: %w", err)) + } + + return errors +} + +func TestAccAWSEFSAccessPoint_basic(t *testing.T) { + var ap efs.AccessPointDescription + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_efs_access_point.test" + fsResourceName := "aws_efs_file_system.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEfsAccessPointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEFSAccessPointConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsAccessPointExists(resourceName, &ap), + resource.TestCheckResourceAttrPair(resourceName, "file_system_arn", fsResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "file_system_id", fsResourceName, "id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticfilesystem", regexp.MustCompile(`access-point/fsap-.+`)), + resource.TestCheckResourceAttrSet(resourceName, "owner_id"), + resource.TestCheckResourceAttr(resourceName, "tags.#", "0"), + resource.TestCheckResourceAttr(resourceName, "posix_user.#", "0"), + resource.TestCheckResourceAttr(resourceName, "root_directory.#", "1"), + resource.TestCheckResourceAttr(resourceName, "root_directory.0.path", "/"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSEFSAccessPoint_root_directory(t *testing.T) { + var ap efs.AccessPointDescription + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_efs_access_point.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEfsAccessPointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEFSAccessPointConfigRootDirectory(rName, "/home/test"), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsAccessPointExists(resourceName, &ap), + resource.TestCheckResourceAttr(resourceName, "root_directory.#", "1"), + resource.TestCheckResourceAttr(resourceName, "root_directory.0.path", "/home/test"), + resource.TestCheckResourceAttr(resourceName, "root_directory.0.creation_info.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSEFSAccessPoint_root_directory_creation_info(t *testing.T) { + var ap efs.AccessPointDescription + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_efs_access_point.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEfsAccessPointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEFSAccessPointConfigRootDirectoryCreationInfo(rName, "/home/test"), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsAccessPointExists(resourceName, &ap), + resource.TestCheckResourceAttr(resourceName, "root_directory.#", "1"), + resource.TestCheckResourceAttr(resourceName, "root_directory.0.path", "/home/test"), + resource.TestCheckResourceAttr(resourceName, "root_directory.0.creation_info.#", "1"), + resource.TestCheckResourceAttr(resourceName, "root_directory.0.creation_info.0.owner_gid", "1001"), + resource.TestCheckResourceAttr(resourceName, "root_directory.0.creation_info.0.owner_uid", "1001"), + resource.TestCheckResourceAttr(resourceName, "root_directory.0.creation_info.0.permissions", "755"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSEFSAccessPoint_posix_user(t *testing.T) { + var ap efs.AccessPointDescription + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_efs_access_point.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEfsAccessPointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEFSAccessPointConfigPosixUser(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsAccessPointExists(resourceName, &ap), + resource.TestCheckResourceAttr(resourceName, "posix_user.#", "1"), + resource.TestCheckResourceAttr(resourceName, "posix_user.0.gid", "1001"), + resource.TestCheckResourceAttr(resourceName, "posix_user.0.uid", "1001"), + resource.TestCheckResourceAttr(resourceName, "posix_user.0.secondary_gids.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSEFSAccessPoint_posix_user_secondary_gids(t *testing.T) { + var ap efs.AccessPointDescription + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_efs_access_point.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEfsAccessPointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEFSAccessPointConfigPosixUserSecondaryGids(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsAccessPointExists(resourceName, &ap), + resource.TestCheckResourceAttr(resourceName, "posix_user.#", "1"), + resource.TestCheckResourceAttr(resourceName, "posix_user.0.gid", "1001"), + resource.TestCheckResourceAttr(resourceName, "posix_user.0.uid", "1001"), + resource.TestCheckResourceAttr(resourceName, "posix_user.0.secondary_gids.#", "1")), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSEFSAccessPoint_tags(t *testing.T) { + var ap efs.AccessPointDescription + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_efs_access_point.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEfsAccessPointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEFSAccessPointConfigTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsAccessPointExists(resourceName, &ap), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSEFSAccessPointConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsAccessPointExists(resourceName, &ap), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccAWSEFSAccessPointConfigTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsAccessPointExists(resourceName, &ap), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func TestAccAWSEFSAccessPoint_disappears(t *testing.T) { + var ap efs.AccessPointDescription + resourceName := "aws_efs_access_point.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEfsAccessPointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEFSAccessPointConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsAccessPointExists(resourceName, &ap), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEfsAccessPoint(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckEfsAccessPointDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).efsconn + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_efs_access_point" { + continue + } + + resp, err := conn.DescribeAccessPoints(&efs.DescribeAccessPointsInput{ + AccessPointId: aws.String(rs.Primary.ID), + }) + if err != nil { + if isAWSErr(err, efs.ErrCodeAccessPointNotFound, "") { + continue + } + return fmt.Errorf("Error describing EFS access point in tests: %s", err) + } + if len(resp.AccessPoints) > 0 { + return fmt.Errorf("EFS access point %q still exists", rs.Primary.ID) + } + } + + return nil +} + +func testAccCheckEfsAccessPointExists(resourceID string, mount *efs.AccessPointDescription) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceID] + if !ok { + return fmt.Errorf("Not found: %s", resourceID) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + fs, ok := s.RootModule().Resources[resourceID] + if !ok { + return fmt.Errorf("Not found: %s", resourceID) + } + + conn := testAccProvider.Meta().(*AWSClient).efsconn + mt, err := conn.DescribeAccessPoints(&efs.DescribeAccessPointsInput{ + AccessPointId: aws.String(fs.Primary.ID), + }) + if err != nil { + return err + } + + if *mt.AccessPoints[0].AccessPointId != fs.Primary.ID { + return fmt.Errorf("access point ID mismatch: %q != %q", + *mt.AccessPoints[0].AccessPointId, fs.Primary.ID) + } + + *mount = *mt.AccessPoints[0] + + return nil + } +} + +func testAccAWSEFSAccessPointConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_efs_file_system" "test" { + creation_token = "%s" +} + +resource "aws_efs_access_point" "test" { + file_system_id = aws_efs_file_system.test.id +} +`, rName) +} + +func testAccAWSEFSAccessPointConfigRootDirectory(rName, dir string) string { + return fmt.Sprintf(` +resource "aws_efs_file_system" "test" { + creation_token = %[1]q +} + +resource "aws_efs_access_point" "test" { + file_system_id = aws_efs_file_system.test.id + root_directory { + path = %[2]q + } +} +`, rName, dir) +} + +func testAccAWSEFSAccessPointConfigRootDirectoryCreationInfo(rName, dir string) string { + return fmt.Sprintf(` +resource "aws_efs_file_system" "test" { + creation_token = %[1]q +} + +resource "aws_efs_access_point" "test" { + file_system_id = aws_efs_file_system.test.id + root_directory { + path = %[2]q + creation_info { + owner_gid = 1001 + owner_uid = 1001 + permissions = "755" + } + } +} +`, rName, dir) +} + +func testAccAWSEFSAccessPointConfigPosixUser(rName string) string { + return fmt.Sprintf(` +resource "aws_efs_file_system" "test" { + creation_token = "%s" +} + +resource "aws_efs_access_point" "test" { + file_system_id = aws_efs_file_system.test.id + posix_user { + gid = 1001 + uid = 1001 + } +} +`, rName) +} + +func testAccAWSEFSAccessPointConfigPosixUserSecondaryGids(rName string) string { + return fmt.Sprintf(` +resource "aws_efs_file_system" "test" { + creation_token = "%s" +} + +resource "aws_efs_access_point" "test" { + file_system_id = aws_efs_file_system.test.id + posix_user { + gid = 1001 + uid = 1001 + secondary_gids = [1002] + } +} +`, rName) +} + +func testAccAWSEFSAccessPointConfigTags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_efs_file_system" "test" { + creation_token = %[1]q +} + +resource "aws_efs_access_point" "test" { + file_system_id = aws_efs_file_system.test.id + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccAWSEFSAccessPointConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_efs_file_system" "test" { + creation_token = %[1]q +} + +resource "aws_efs_access_point" "test" { + file_system_id = aws_efs_file_system.test.id + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} diff --git a/aws/resource_aws_efs_file_system.go b/aws/resource_aws_efs_file_system.go index edb5027f5ef..aa9bb0e7300 100644 --- a/aws/resource_aws_efs_file_system.go +++ b/aws/resource_aws_efs_file_system.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/efs" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -40,13 +40,6 @@ func resourceAwsEfsFileSystem() *schema.Resource { ValidateFunc: validation.StringLenBetween(0, 64), }, - "reference_name": { - Type: schema.TypeString, - Optional: true, - Computed: true, - Removed: "Use `creation_token` argument instead", - }, - "performance_mode": { Type: schema.TypeString, Optional: true, @@ -201,7 +194,7 @@ func resourceAwsEfsFileSystemCreate(d *schema.ResourceData, meta interface{}) er func resourceAwsEfsFileSystemUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).efsconn - if d.HasChange("provisioned_throughput_in_mibps") || d.HasChange("throughput_mode") { + if d.HasChanges("provisioned_throughput_in_mibps", "throughput_mode") { throughputMode := d.Get("throughput_mode").(string) input := &efs.UpdateFileSystemInput{ diff --git a/aws/resource_aws_efs_file_system_policy.go b/aws/resource_aws_efs_file_system_policy.go new file mode 100644 index 00000000000..0a6f2513f88 --- /dev/null +++ b/aws/resource_aws_efs_file_system_policy.go @@ -0,0 +1,100 @@ +package aws + +import ( + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/efs" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func resourceAwsEfsFileSystemPolicy() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsEfsFileSystemPolicyPut, + Read: resourceAwsEfsFileSystemPolicyRead, + Update: resourceAwsEfsFileSystemPolicyPut, + Delete: resourceAwsEfsFileSystemPolicyDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "file_system_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "policy": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringIsJSON, + DiffSuppressFunc: suppressEquivalentJsonDiffs, + }, + }, + } +} + +func resourceAwsEfsFileSystemPolicyPut(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).efsconn + + fsId := d.Get("file_system_id").(string) + input := &efs.PutFileSystemPolicyInput{ + FileSystemId: aws.String(fsId), + Policy: aws.String(d.Get("policy").(string)), + } + log.Printf("[DEBUG] Adding EFS File System Policy: %#v", input) + _, err := conn.PutFileSystemPolicy(input) + if err != nil { + return fmt.Errorf("error creating EFS File System Policy %q: %s", d.Id(), err.Error()) + } + + d.SetId(fsId) + + return resourceAwsEfsFileSystemPolicyRead(d, meta) +} + +func resourceAwsEfsFileSystemPolicyRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).efsconn + + var policyRes *efs.DescribeFileSystemPolicyOutput + policyRes, err := conn.DescribeFileSystemPolicy(&efs.DescribeFileSystemPolicyInput{ + FileSystemId: aws.String(d.Id()), + }) + if err != nil { + if isAWSErr(err, efs.ErrCodeFileSystemNotFound, "") { + log.Printf("[WARN] EFS File System (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + if isAWSErr(err, efs.ErrCodePolicyNotFound, "") { + log.Printf("[WARN] EFS File System Policy (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + return fmt.Errorf("error describing policy for EFS file system (%s): %s", d.Id(), err) + } + + d.Set("file_system_id", policyRes.FileSystemId) + d.Set("policy", policyRes.Policy) + + return nil +} + +func resourceAwsEfsFileSystemPolicyDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).efsconn + + log.Printf("[DEBUG] Deleting EFS File System Policy: %s", d.Id()) + _, err := conn.DeleteFileSystemPolicy(&efs.DeleteFileSystemPolicyInput{ + FileSystemId: aws.String(d.Id()), + }) + if err != nil { + return fmt.Errorf("error deleting EFS File System Policy: %s with err %s", d.Id(), err.Error()) + } + + log.Printf("[DEBUG] EFS File System Policy %q deleted.", d.Id()) + + return nil +} diff --git a/aws/resource_aws_efs_file_system_policy_test.go b/aws/resource_aws_efs_file_system_policy_test.go new file mode 100644 index 00000000000..795f56b2f67 --- /dev/null +++ b/aws/resource_aws_efs_file_system_policy_test.go @@ -0,0 +1,193 @@ +package aws + +import ( + "fmt" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/efs" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccAWSEFSFileSystemPolicy_basic(t *testing.T) { + var desc efs.DescribeFileSystemPolicyOutput + resourceName := "aws_efs_file_system_policy.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEfsFileSystemDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEFSFileSystemPolicyConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsFileSystemPolicy(resourceName, &desc), + resource.TestCheckResourceAttrSet(resourceName, "policy"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSEFSFileSystemPolicyConfigUpdated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsFileSystemPolicy(resourceName, &desc), + resource.TestCheckResourceAttrSet(resourceName, "policy"), + ), + }, + }, + }) +} + +func TestAccAWSEFSFileSystemPolicy_disappears(t *testing.T) { + var desc efs.DescribeFileSystemPolicyOutput + resourceName := "aws_efs_file_system_policy.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckEfsFileSystemPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEFSFileSystemPolicyConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckEfsFileSystemPolicy(resourceName, &desc), + testAccCheckResourceDisappears(testAccProvider, resourceAwsEfsFileSystemPolicy(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckEfsFileSystemPolicyDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).efsconn + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_efs_file_system_policy" { + continue + } + + resp, err := conn.DescribeFileSystemPolicy(&efs.DescribeFileSystemPolicyInput{ + FileSystemId: aws.String(rs.Primary.ID), + }) + if err != nil { + if isAWSErr(err, efs.ErrCodeFileSystemNotFound, "") || + isAWSErr(err, efs.ErrCodePolicyNotFound, "") { + return nil + } + return fmt.Errorf("error describing EFS file system policy in tests: %s", err) + } + if resp != nil { + return fmt.Errorf("EFS file system policy %q still exists", rs.Primary.ID) + } + } + + return nil +} + +func testAccCheckEfsFileSystemPolicy(resourceID string, efsFsPolicy *efs.DescribeFileSystemPolicyOutput) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceID] + if !ok { + return fmt.Errorf("Not found: %s", resourceID) + } + + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).efsconn + fs, err := conn.DescribeFileSystemPolicy(&efs.DescribeFileSystemPolicyInput{ + FileSystemId: aws.String(rs.Primary.ID), + }) + + if err != nil { + return err + } + + *efsFsPolicy = *fs + + return nil + } +} + +func testAccAWSEFSFileSystemPolicyConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_efs_file_system" "test" { + creation_token = %q +} + +resource "aws_efs_file_system_policy" "test" { + file_system_id = aws_efs_file_system.test.id + + policy = < 0 { - input.InstanceTypes = expandStringSet(v) + if v := d.Get("instance_types").([]interface{}); len(v) > 0 { + input.InstanceTypes = expandStringList(v) } if v := d.Get("labels").(map[string]interface{}); len(v) > 0 { @@ -338,7 +342,7 @@ func resourceAwsEksNodeGroupUpdate(d *schema.ResourceData, meta interface{}) err return err } - if d.HasChange("labels") || d.HasChange("scaling_config") { + if d.HasChanges("labels", "scaling_config") { oldLabelsRaw, newLabelsRaw := d.GetChange("labels") input := &eks.UpdateNodegroupConfigInput{ @@ -370,15 +374,15 @@ func resourceAwsEksNodeGroupUpdate(d *schema.ResourceData, meta interface{}) err } } - if d.HasChange("release_version") || d.HasChange("version") { + if d.HasChanges("release_version", "version") { input := &eks.UpdateNodegroupVersionInput{ ClientRequestToken: aws.String(resource.UniqueId()), ClusterName: aws.String(clusterName), - Force: aws.Bool(false), + Force: aws.Bool(d.Get("force_update_version").(bool)), NodegroupName: aws.String(nodeGroupName), } - if v, ok := d.GetOk("release_version"); ok { + if v, ok := d.GetOk("release_version"); ok && d.HasChange("release_version") { input.ReleaseVersion = aws.String(v.(string)) } diff --git a/aws/resource_aws_eks_node_group_test.go b/aws/resource_aws_eks_node_group_test.go index 28bfdf51a2b..b071c9060f2 100644 --- a/aws/resource_aws_eks_node_group_test.go +++ b/aws/resource_aws_eks_node_group_test.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/eks" multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -198,6 +198,40 @@ func TestAccAWSEksNodeGroup_DiskSize(t *testing.T) { }) } +func TestAccAWSEksNodeGroup_ForceUpdateVersion(t *testing.T) { + var nodeGroup1 eks.Nodegroup + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_eks_node_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEks(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEksNodeGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEksNodeGroupConfigForceUpdateVersion(rName, "1.15"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEksNodeGroupExists(resourceName, &nodeGroup1), + resource.TestCheckResourceAttr(resourceName, "version", "1.15"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"force_update_version"}, + }, + { + Config: testAccAWSEksNodeGroupConfigForceUpdateVersion(rName, "1.16"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEksNodeGroupExists(resourceName, &nodeGroup1), + resource.TestCheckResourceAttr(resourceName, "version", "1.16"), + ), + }, + }, + }) +} + func TestAccAWSEksNodeGroup_InstanceTypes(t *testing.T) { var nodeGroup1 eks.Nodegroup rName := acctest.RandomWithPrefix("tf-acc-test") @@ -271,6 +305,7 @@ func TestAccAWSEksNodeGroup_Labels(t *testing.T) { func TestAccAWSEksNodeGroup_ReleaseVersion(t *testing.T) { var nodeGroup1 eks.Nodegroup rName := acctest.RandomWithPrefix("tf-acc-test") + ssmParameterDataSourceName := "data.aws_ssm_parameter.test" resourceName := "aws_eks_node_group.test" resource.ParallelTest(t, resource.TestCase{ @@ -279,10 +314,10 @@ func TestAccAWSEksNodeGroup_ReleaseVersion(t *testing.T) { CheckDestroy: testAccCheckAWSEksNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSEksNodeGroupConfigReleaseVersion(rName, "1.14.8-20191213"), + Config: testAccAWSEksNodeGroupConfigReleaseVersion(rName, "1.15"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEksNodeGroupExists(resourceName, &nodeGroup1), - resource.TestCheckResourceAttr(resourceName, "release_version", "1.14.8-20191213"), + resource.TestCheckResourceAttrPair(resourceName, "release_version", ssmParameterDataSourceName, "value"), ), }, { @@ -290,6 +325,13 @@ func TestAccAWSEksNodeGroup_ReleaseVersion(t *testing.T) { ImportState: true, ImportStateVerify: true, }, + { + Config: testAccAWSEksNodeGroupConfigReleaseVersion(rName, "1.16"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEksNodeGroupExists(resourceName, &nodeGroup1), + resource.TestCheckResourceAttrPair(resourceName, "release_version", ssmParameterDataSourceName, "value"), + ), + }, }, }) } @@ -520,10 +562,10 @@ func TestAccAWSEksNodeGroup_Version(t *testing.T) { CheckDestroy: testAccCheckAWSEksNodeGroupDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSEksNodeGroupConfigVersion(rName, "1.14"), + Config: testAccAWSEksNodeGroupConfigVersion(rName, "1.15"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSEksNodeGroupExists(resourceName, &nodeGroup1), - resource.TestCheckResourceAttr(resourceName, "version", "1.14"), + resource.TestCheckResourceAttr(resourceName, "version", "1.15"), ), }, { @@ -531,6 +573,13 @@ func TestAccAWSEksNodeGroup_Version(t *testing.T) { ImportState: true, ImportStateVerify: true, }, + { + Config: testAccAWSEksNodeGroupConfigVersion(rName, "1.16"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEksNodeGroupExists(resourceName, &nodeGroup1), + resource.TestCheckResourceAttr(resourceName, "version", "1.16"), + ), + }, }, }) } @@ -637,7 +686,7 @@ func testAccCheckAWSEksNodeGroupDisappears(nodeGroup *eks.Nodegroup) resource.Te } } -func testAccAWSEksNodeGroupConfigBase(rName string) string { +func testAccAWSEksNodeGroupConfigBaseIamAndVpc(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -673,11 +722,6 @@ resource "aws_iam_role_policy_attachment" "cluster-AmazonEKSClusterPolicy" { role = aws_iam_role.cluster.name } -resource "aws_iam_role_policy_attachment" "cluster-AmazonEKSServicePolicy" { - policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/AmazonEKSServicePolicy" - role = aws_iam_role.cluster.name -} - resource "aws_iam_role" "node" { name = "%[1]s-node" @@ -759,16 +803,23 @@ resource "aws_security_group" "test" { resource "aws_subnet" "test" { count = 2 - availability_zone = data.aws_availability_zones.available.names[count.index] - cidr_block = cidrsubnet(aws_vpc.test.cidr_block, 8, count.index) - vpc_id = aws_vpc.test.id + availability_zone = data.aws_availability_zones.available.names[count.index] + cidr_block = cidrsubnet(aws_vpc.test.cidr_block, 8, count.index) + map_public_ip_on_launch = true + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-eks-node-group" "kubernetes.io/cluster/%[1]s" = "shared" } } +`, rName) +} +func testAccAWSEksNodeGroupConfigBase(rName string) string { + return composeConfig( + testAccAWSEksNodeGroupConfigBaseIamAndVpc(rName), + fmt.Sprintf(` resource "aws_eks_cluster" "test" { name = %[1]q role_arn = aws_iam_role.cluster.arn @@ -779,11 +830,31 @@ resource "aws_eks_cluster" "test" { depends_on = [ "aws_iam_role_policy_attachment.cluster-AmazonEKSClusterPolicy", - "aws_iam_role_policy_attachment.cluster-AmazonEKSServicePolicy", "aws_main_route_table_association.test", ] } -`, rName) +`, rName)) +} + +func testAccAWSEksNodeGroupConfigBaseVersion(rName string, version string) string { + return composeConfig( + testAccAWSEksNodeGroupConfigBaseIamAndVpc(rName), + fmt.Sprintf(` +resource "aws_eks_cluster" "test" { + name = %[1]q + role_arn = aws_iam_role.cluster.arn + version = %[2]q + + vpc_config { + subnet_ids = aws_subnet.test[*].id + } + + depends_on = [ + "aws_iam_role_policy_attachment.cluster-AmazonEKSClusterPolicy", + "aws_main_route_table_association.test", + ] +} +`, rName, version)) } func testAccAWSEksNodeGroupConfigNodeGroupName(rName string) string { @@ -857,6 +928,31 @@ resource "aws_eks_node_group" "test" { `, rName, diskSize) } +func testAccAWSEksNodeGroupConfigForceUpdateVersion(rName, version string) string { + return testAccAWSEksNodeGroupConfigBaseVersion(rName, version) + fmt.Sprintf(` +resource "aws_eks_node_group" "test" { + cluster_name = aws_eks_cluster.test.name + force_update_version = true + node_group_name = %[1]q + node_role_arn = aws_iam_role.node.arn + subnet_ids = aws_subnet.test[*].id + version = aws_eks_cluster.test.version + + scaling_config { + desired_size = 1 + max_size = 1 + min_size = 1 + } + + depends_on = [ + "aws_iam_role_policy_attachment.node-AmazonEKSWorkerNodePolicy", + "aws_iam_role_policy_attachment.node-AmazonEKS_CNI_Policy", + "aws_iam_role_policy_attachment.node-AmazonEC2ContainerRegistryReadOnly", + ] +} +`, rName) +} + func testAccAWSEksNodeGroupConfigInstanceTypes1(rName, instanceType1 string) string { return testAccAWSEksNodeGroupConfigBase(rName) + fmt.Sprintf(` resource "aws_eks_node_group" "test" { @@ -936,14 +1032,19 @@ resource "aws_eks_node_group" "test" { `, rName, labelKey1, labelValue1, labelKey2, labelValue2) } -func testAccAWSEksNodeGroupConfigReleaseVersion(rName, releaseVersion string) string { - return testAccAWSEksNodeGroupConfigBase(rName) + fmt.Sprintf(` +func testAccAWSEksNodeGroupConfigReleaseVersion(rName string, version string) string { + return testAccAWSEksNodeGroupConfigBaseVersion(rName, version) + fmt.Sprintf(` +data "aws_ssm_parameter" "test" { + name = "/aws/service/eks/optimized-ami/${aws_eks_cluster.test.version}/amazon-linux-2/recommended/release_version" +} + resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name node_group_name = %[1]q node_role_arn = aws_iam_role.node.arn - release_version = %[2]q + release_version = data.aws_ssm_parameter.test.value subnet_ids = aws_subnet.test[*].id + version = aws_eks_cluster.test.version scaling_config { desired_size = 1 @@ -957,7 +1058,7 @@ resource "aws_eks_node_group" "test" { "aws_iam_role_policy_attachment.node-AmazonEC2ContainerRegistryReadOnly", ] } -`, rName, releaseVersion) +`, rName) } func testAccAWSEksNodeGroupConfigRemoteAccessEc2SshKey(rName string) string { @@ -1104,13 +1205,13 @@ resource "aws_eks_node_group" "test" { } func testAccAWSEksNodeGroupConfigVersion(rName, version string) string { - return testAccAWSEksNodeGroupConfigBase(rName) + fmt.Sprintf(` + return testAccAWSEksNodeGroupConfigBaseVersion(rName, version) + fmt.Sprintf(` resource "aws_eks_node_group" "test" { cluster_name = aws_eks_cluster.test.name node_group_name = %[1]q node_role_arn = aws_iam_role.node.arn subnet_ids = aws_subnet.test[*].id - version = %[2]q + version = aws_eks_cluster.test.version scaling_config { desired_size = 1 @@ -1124,5 +1225,5 @@ resource "aws_eks_node_group" "test" { "aws_iam_role_policy_attachment.node-AmazonEC2ContainerRegistryReadOnly", ] } -`, rName, version) +`, rName) } diff --git a/aws/resource_aws_elastic_beanstalk_application.go b/aws/resource_aws_elastic_beanstalk_application.go index 6501ac55961..4d4cffa7980 100644 --- a/aws/resource_aws_elastic_beanstalk_application.go +++ b/aws/resource_aws_elastic_beanstalk_application.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elasticbeanstalk" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_elastic_beanstalk_application_test.go b/aws/resource_aws_elastic_beanstalk_application_test.go index a7485c58f39..087fcb06a80 100644 --- a/aws/resource_aws_elastic_beanstalk_application_test.go +++ b/aws/resource_aws_elastic_beanstalk_application_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elasticbeanstalk" multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -318,11 +318,12 @@ resource "aws_iam_role" "beanstalk_service" { ] } EOF + } resource "aws_iam_role_policy" "beanstalk_service" { name = "%[1]s" - role = "${aws_iam_role.beanstalk_service.id}" + role = aws_iam_role.beanstalk_service.id policy = < 1`) }, - func(diff *schema.ResourceDiff, v interface{}) error { + func(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { // Engine memcached does not currently support vertical scaling // InvalidParameterCombination: Scaling is not supported for engine memcached // https://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Scaling.Memcached.html#Scaling.Memcached.Vertically diff --git a/aws/resource_aws_elasticache_cluster_test.go b/aws/resource_aws_elasticache_cluster_test.go index f72b0b5c6ee..3e2465aae96 100644 --- a/aws/resource_aws_elasticache_cluster_test.go +++ b/aws/resource_aws_elasticache_cluster_test.go @@ -14,9 +14,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elasticache" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -915,46 +915,47 @@ resource "aws_elasticache_cluster" "test" { var testAccAWSElasticacheClusterConfig_SecurityGroup = fmt.Sprintf(` resource "aws_security_group" "test" { - name = "tf-test-security-group-%03d" - description = "tf-test-security-group-descr" - ingress { - from_port = -1 - to_port = -1 - protocol = "icmp" - cidr_blocks = ["0.0.0.0/0"] - } + name = "tf-test-security-group-%03d" + description = "tf-test-security-group-descr" + + ingress { + from_port = -1 + to_port = -1 + protocol = "icmp" + cidr_blocks = ["0.0.0.0/0"] + } - tags = { - Name = "TestAccAWSElasticacheCluster_basic" - } + tags = { + Name = "TestAccAWSElasticacheCluster_basic" + } } resource "aws_elasticache_security_group" "test" { - name = "tf-test-security-group-%03d" - description = "tf-test-security-group-descr" - security_group_names = ["${aws_security_group.test.name}"] + name = "tf-test-security-group-%03d" + description = "tf-test-security-group-descr" + security_group_names = [aws_security_group.test.name] } resource "aws_elasticache_cluster" "test" { - cluster_id = "tf-%s" - engine = "memcached" - node_type = "cache.m3.medium" - num_cache_nodes = 1 - port = 11211 - security_group_names = ["${aws_elasticache_security_group.test.name}"] + cluster_id = "tf-%s" + engine = "memcached" + node_type = "cache.m3.medium" + num_cache_nodes = 1 + port = 11211 + security_group_names = [aws_elasticache_security_group.test.name] } `, acctest.RandInt(), acctest.RandInt(), acctest.RandString(10)) func testAccAWSElasticacheClusterConfig_snapshots(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { - cluster_id = "tf-%s" - engine = "redis" - node_type = "cache.t3.small" - num_cache_nodes = 1 - port = 6379 - snapshot_window = "05:00-09:00" - snapshot_retention_limit = 3 + cluster_id = "tf-%s" + engine = "redis" + node_type = "cache.t3.small" + num_cache_nodes = 1 + port = 6379 + snapshot_window = "05:00-09:00" + snapshot_retention_limit = 3 } `, rName) } @@ -962,14 +963,14 @@ resource "aws_elasticache_cluster" "test" { func testAccAWSElasticacheClusterConfig_snapshotsUpdated(rName string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { - cluster_id = "tf-%s" - engine = "redis" - node_type = "cache.t3.small" - num_cache_nodes = 1 - port = 6379 - snapshot_window = "07:00-09:00" - snapshot_retention_limit = 7 - apply_immediately = true + cluster_id = "tf-%s" + engine = "redis" + node_type = "cache.t3.small" + num_cache_nodes = 1 + port = 6379 + snapshot_window = "07:00-09:00" + snapshot_retention_limit = 7 + apply_immediately = true } `, rName) } @@ -989,7 +990,7 @@ resource "aws_elasticache_cluster" "test" { func testAccAWSElasticacheClusterConfig_NumCacheNodesWithPreferredAvailabilityZones(rName string, numCacheNodes int) string { preferredAvailabilityZones := make([]string, numCacheNodes) for i := range preferredAvailabilityZones { - preferredAvailabilityZones[i] = `"${data.aws_availability_zones.available.names[0]}"` + preferredAvailabilityZones[i] = `data.aws_availability_zones.available.names[0]` } return fmt.Sprintf(` @@ -1024,54 +1025,57 @@ data "aws_availability_zones" "available" { } resource "aws_vpc" "test" { - cidr_block = "192.168.0.0/16" - tags = { - Name = "terraform-testacc-elasticache-cluster-in-vpc" - } + cidr_block = "192.168.0.0/16" + + tags = { + Name = "terraform-testacc-elasticache-cluster-in-vpc" + } } resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "192.168.0.0/20" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - tags = { - Name = "tf-acc-elasticache-cluster-in-vpc" - } + vpc_id = aws_vpc.test.id + cidr_block = "192.168.0.0/20" + availability_zone = data.aws_availability_zones.available.names[0] + + tags = { + Name = "tf-acc-elasticache-cluster-in-vpc" + } } resource "aws_elasticache_subnet_group" "test" { - name = "tf-test-cache-subnet-%03d" - description = "tf-test-cache-subnet-group-descr" - subnet_ids = ["${aws_subnet.test.id}"] + name = "tf-test-cache-subnet-%03d" + description = "tf-test-cache-subnet-group-descr" + subnet_ids = [aws_subnet.test.id] } resource "aws_security_group" "test" { - name = "tf-test-security-group-%03d" - description = "tf-test-security-group-descr" - vpc_id = "${aws_vpc.test.id}" - ingress { - from_port = -1 - to_port = -1 - protocol = "icmp" - cidr_blocks = ["0.0.0.0/0"] - } + name = "tf-test-security-group-%03d" + description = "tf-test-security-group-descr" + vpc_id = aws_vpc.test.id + + ingress { + from_port = -1 + to_port = -1 + protocol = "icmp" + cidr_blocks = ["0.0.0.0/0"] + } } resource "aws_elasticache_cluster" "test" { - // Including uppercase letters in this name to ensure - // that we correctly handle the fact that the API - // normalizes names to lowercase. - cluster_id = "tf-%s" - node_type = "cache.t3.small" - num_cache_nodes = 1 - engine = "redis" - engine_version = "2.8.19" - port = 6379 - subnet_group_name = "${aws_elasticache_subnet_group.test.name}" - security_group_ids = ["${aws_security_group.test.id}"] - parameter_group_name = "default.redis2.8" - notification_topic_arn = "${aws_sns_topic.test.arn}" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + # Including uppercase letters in this name to ensure + # that we correctly handle the fact that the API + # normalizes names to lowercase. + cluster_id = "tf-%s" + node_type = "cache.t3.small" + num_cache_nodes = 1 + engine = "redis" + engine_version = "2.8.19" + port = 6379 + subnet_group_name = aws_elasticache_subnet_group.test.name + security_group_ids = [aws_security_group.test.id] + parameter_group_name = "default.redis2.8" + notification_topic_arn = aws_sns_topic.test.arn + availability_zone = data.aws_availability_zones.available.names[0] } resource "aws_sns_topic" "test" { @@ -1090,71 +1094,75 @@ data "aws_availability_zones" "available" { } resource "aws_vpc" "test" { - cidr_block = "192.168.0.0/16" - tags = { - Name = "terraform-testacc-elasticache-cluster-multi-az-in-vpc" - } + cidr_block = "192.168.0.0/16" + + tags = { + Name = "terraform-testacc-elasticache-cluster-multi-az-in-vpc" + } } resource "aws_subnet" "test1" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "192.168.0.0/20" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - tags = { - Name = "tf-acc-elasticache-cluster-multi-az-in-vpc-foo" - } + vpc_id = aws_vpc.test.id + cidr_block = "192.168.0.0/20" + availability_zone = data.aws_availability_zones.available.names[0] + + tags = { + Name = "tf-acc-elasticache-cluster-multi-az-in-vpc-foo" + } } resource "aws_subnet" "test2" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "192.168.16.0/20" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - tags = { + vpc_id = aws_vpc.test.id + cidr_block = "192.168.16.0/20" + availability_zone = data.aws_availability_zones.available.names[1] + + tags = { Name = "tf-acc-elasticache-cluster-multi-az-in-vpc-bar" } } resource "aws_elasticache_subnet_group" "test" { - name = "tf-test-cache-subnet-%03d" - description = "tf-test-cache-subnet-group-descr" - subnet_ids = [ - "${aws_subnet.test1.id}", - "${aws_subnet.test2.id}" - ] + name = "tf-test-cache-subnet-%03d" + description = "tf-test-cache-subnet-group-descr" + subnet_ids = [ + aws_subnet.test1.id, + aws_subnet.test2.id, + ] } resource "aws_security_group" "test" { - name = "tf-test-security-group-%03d" - description = "tf-test-security-group-descr" - vpc_id = "${aws_vpc.test.id}" - ingress { - from_port = -1 - to_port = -1 - protocol = "icmp" - cidr_blocks = ["0.0.0.0/0"] - } + name = "tf-test-security-group-%03d" + description = "tf-test-security-group-descr" + vpc_id = aws_vpc.test.id + + ingress { + from_port = -1 + to_port = -1 + protocol = "icmp" + cidr_blocks = ["0.0.0.0/0"] + } } resource "aws_elasticache_cluster" "test" { - cluster_id = "tf-%s" - engine = "memcached" - node_type = "cache.t3.small" - num_cache_nodes = 2 - port = 11211 - subnet_group_name = "${aws_elasticache_subnet_group.test.name}" - security_group_ids = ["${aws_security_group.test.id}"] - az_mode = "cross-az" - preferred_availability_zones = [ - "${data.aws_availability_zones.available.names[0]}", - "${data.aws_availability_zones.available.names[1]}" - ] + cluster_id = "tf-%s" + engine = "memcached" + node_type = "cache.t3.small" + num_cache_nodes = 2 + port = 11211 + subnet_group_name = aws_elasticache_subnet_group.test.name + security_group_ids = [aws_security_group.test.id] + az_mode = "cross-az" + preferred_availability_zones = [ + data.aws_availability_zones.available.names[0], + data.aws_availability_zones.available.names[1] + ] } `, acctest.RandInt(), acctest.RandInt(), acctest.RandString(10)) var testAccAWSElasticacheClusterConfig_RedisDefaultPort = ` resource "aws_security_group" "test" { - name = "tf-test-security-group" - description = "tf-test-security-group-descr" + name = "tf-test-security-group" + description = "tf-test-security-group-descr" } resource "aws_security_group_rule" "test" { @@ -1167,25 +1175,25 @@ resource "aws_security_group_rule" "test" { } resource "aws_elasticache_cluster" "test" { - cluster_id = "foo-cluster" - engine = "redis" - engine_version = "5.0.4" - node_type = "cache.t2.micro" - num_cache_nodes = 1 - parameter_group_name = "default.redis5.0" + cluster_id = "foo-cluster" + engine = "redis" + engine_version = "5.0.4" + node_type = "cache.t2.micro" + num_cache_nodes = 1 + parameter_group_name = "default.redis5.0" } ` func testAccAWSElasticacheClusterConfig_AZMode_Memcached(rName, azMode string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { - apply_immediately = true - az_mode = "%[2]s" - cluster_id = "%[1]s" - engine = "memcached" - node_type = "cache.m3.medium" - num_cache_nodes = 1 - port = 11211 + apply_immediately = true + az_mode = "%[2]s" + cluster_id = "%[1]s" + engine = "memcached" + node_type = "cache.m3.medium" + num_cache_nodes = 1 + port = 11211 } `, rName, azMode) } @@ -1193,13 +1201,13 @@ resource "aws_elasticache_cluster" "test" { func testAccAWSElasticacheClusterConfig_AZMode_Redis(rName, azMode string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { - apply_immediately = true - az_mode = "%[2]s" - cluster_id = "%[1]s" - engine = "redis" - node_type = "cache.m3.medium" - num_cache_nodes = 1 - port = 6379 + apply_immediately = true + az_mode = "%[2]s" + cluster_id = "%[1]s" + engine = "redis" + node_type = "cache.m3.medium" + num_cache_nodes = 1 + port = 6379 } `, rName, azMode) } @@ -1207,13 +1215,13 @@ resource "aws_elasticache_cluster" "test" { func testAccAWSElasticacheClusterConfig_EngineVersion_Memcached(rName, engineVersion string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { - apply_immediately = true - cluster_id = "%[1]s" - engine = "memcached" - engine_version = "%[2]s" - node_type = "cache.m3.medium" - num_cache_nodes = 1 - port = 11211 + apply_immediately = true + cluster_id = "%[1]s" + engine = "memcached" + engine_version = "%[2]s" + node_type = "cache.m3.medium" + num_cache_nodes = 1 + port = 11211 } `, rName, engineVersion) } @@ -1221,13 +1229,13 @@ resource "aws_elasticache_cluster" "test" { func testAccAWSElasticacheClusterConfig_EngineVersion_Redis(rName, engineVersion string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { - apply_immediately = true - cluster_id = "%[1]s" - engine = "redis" - engine_version = "%[2]s" - node_type = "cache.m3.medium" - num_cache_nodes = 1 - port = 6379 + apply_immediately = true + cluster_id = "%[1]s" + engine = "redis" + engine_version = "%[2]s" + node_type = "cache.m3.medium" + num_cache_nodes = 1 + port = 6379 } `, rName, engineVersion) } @@ -1235,12 +1243,12 @@ resource "aws_elasticache_cluster" "test" { func testAccAWSElasticacheClusterConfig_NodeType_Memcached(rName, nodeType string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { - apply_immediately = true - cluster_id = "%[1]s" - engine = "memcached" - node_type = "%[2]s" - num_cache_nodes = 1 - port = 11211 + apply_immediately = true + cluster_id = "%[1]s" + engine = "memcached" + node_type = "%[2]s" + num_cache_nodes = 1 + port = 11211 } `, rName, nodeType) } @@ -1248,12 +1256,12 @@ resource "aws_elasticache_cluster" "test" { func testAccAWSElasticacheClusterConfig_NodeType_Redis(rName, nodeType string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { - apply_immediately = true - cluster_id = "%[1]s" - engine = "redis" - node_type = "%[2]s" - num_cache_nodes = 1 - port = 6379 + apply_immediately = true + cluster_id = "%[1]s" + engine = "redis" + node_type = "%[2]s" + num_cache_nodes = 1 + port = 6379 } `, rName, nodeType) } @@ -1261,12 +1269,12 @@ resource "aws_elasticache_cluster" "test" { func testAccAWSElasticacheClusterConfig_NumCacheNodes_Redis(rName string, numCacheNodes int) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { - apply_immediately = true - cluster_id = "%[1]s" - engine = "redis" - node_type = "cache.m3.medium" - num_cache_nodes = %[2]d - port = 6379 + apply_immediately = true + cluster_id = "%[1]s" + engine = "redis" + node_type = "cache.m3.medium" + num_cache_nodes = %[2]d + port = 6379 } `, rName, numCacheNodes) } @@ -1274,9 +1282,9 @@ resource "aws_elasticache_cluster" "test" { func testAccAWSElasticacheClusterConfig_ReplicationGroupID_InvalidAttribute(rName, attrName, attrValue string) string { return fmt.Sprintf(` resource "aws_elasticache_cluster" "test" { - cluster_id = "%[1]s" - replication_group_id = "non-existent-id" - %[2]s = "%[3]s" + cluster_id = "%[1]s" + replication_group_id = "non-existent-id" + %[2]s = "%[3]s" } `, rName, attrName, attrValue) } @@ -1293,21 +1301,21 @@ data "aws_availability_zones" "available" { } resource "aws_elasticache_replication_group" "test" { - replication_group_description = "Terraform Acceptance Testing" - replication_group_id = "%[1]s" - node_type = "cache.m3.medium" - number_cache_clusters = 1 - port = 6379 - - lifecycle { - ignore_changes = ["number_cache_clusters"] - } + replication_group_description = "Terraform Acceptance Testing" + replication_group_id = "%[1]s" + node_type = "cache.m3.medium" + number_cache_clusters = 1 + port = 6379 + + lifecycle { + ignore_changes = [number_cache_clusters] + } } resource "aws_elasticache_cluster" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" - cluster_id = "%[1]s1" - replication_group_id = "${aws_elasticache_replication_group.test.id}" + availability_zone = data.aws_availability_zones.available.names[0] + cluster_id = "%[1]s1" + replication_group_id = aws_elasticache_replication_group.test.id } `, rName) } @@ -1315,21 +1323,21 @@ resource "aws_elasticache_cluster" "test" { func testAccAWSElasticacheClusterConfig_ReplicationGroupID_Replica(rName string, count int) string { return fmt.Sprintf(` resource "aws_elasticache_replication_group" "test" { - replication_group_description = "Terraform Acceptance Testing" - replication_group_id = "%[1]s" - node_type = "cache.m3.medium" - number_cache_clusters = 1 - port = 6379 - - lifecycle { - ignore_changes = ["number_cache_clusters"] - } + replication_group_description = "Terraform Acceptance Testing" + replication_group_id = "%[1]s" + node_type = "cache.m3.medium" + number_cache_clusters = 1 + port = 6379 + + lifecycle { + ignore_changes = [number_cache_clusters] + } } resource "aws_elasticache_cluster" "test" { count = %[2]d cluster_id = "%[1]s${count.index}" - replication_group_id = "${aws_elasticache_replication_group.test.id}" + replication_group_id = aws_elasticache_replication_group.test.id } `, rName, count) } diff --git a/aws/resource_aws_elasticache_parameter_group.go b/aws/resource_aws_elasticache_parameter_group.go index eb288ef498f..a64a7f4ff44 100644 --- a/aws/resource_aws_elasticache_parameter_group.go +++ b/aws/resource_aws_elasticache_parameter_group.go @@ -7,13 +7,13 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elasticache" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsElasticacheParameterGroup() *schema.Resource { @@ -100,7 +100,7 @@ func resourceAwsElasticacheParameterGroupRead(d *schema.ResourceData, meta inter } if len(describeResp.CacheParameterGroups) != 1 || - *describeResp.CacheParameterGroups[0].CacheParameterGroupName != d.Id() { + aws.StringValue(describeResp.CacheParameterGroups[0].CacheParameterGroupName) != d.Id() { return fmt.Errorf("Unable to find Parameter Group: %#v", describeResp.CacheParameterGroups) } @@ -139,17 +139,11 @@ func resourceAwsElasticacheParameterGroupUpdate(d *schema.ResourceData, meta int os := o.(*schema.Set) ns := n.(*schema.Set) - toRemove, err := expandElastiCacheParameters(os.Difference(ns).List()) - if err != nil { - return err - } + toRemove := expandElastiCacheParameters(os.Difference(ns).List()) log.Printf("[DEBUG] Parameters to remove: %#v", toRemove) - toAdd, err := expandElastiCacheParameters(ns.Difference(os).List()) - if err != nil { - return err - } + toAdd := expandElastiCacheParameters(ns.Difference(os).List()) log.Printf("[DEBUG] Parameters to add: %#v", toAdd) @@ -171,7 +165,7 @@ func resourceAwsElasticacheParameterGroupUpdate(d *schema.ResourceData, meta int log.Printf("[DEBUG] Reset Cache Parameter Group: %s", resetOpts) err := resource.Retry(30*time.Second, func() *resource.RetryError { - _, err = conn.ResetCacheParameterGroup(&resetOpts) + _, err := conn.ResetCacheParameterGroup(&resetOpts) if err != nil { if isAWSErr(err, "InvalidCacheParameterGroupState", " has pending changes") { return resource.RetryableError(err) @@ -206,7 +200,7 @@ func resourceAwsElasticacheParameterGroupUpdate(d *schema.ResourceData, meta int tryReservedMemoryPercentageWorkaround := true - allConfiguredParameters, err := expandElastiCacheParameters(d.Get("parameter").(*schema.Set).List()) + allConfiguredParameters := expandElastiCacheParameters(d.Get("parameter").(*schema.Set).List()) if err != nil { return fmt.Errorf("error expanding parameter configuration: %s", err) } @@ -293,7 +287,7 @@ func resourceAwsElasticacheParameterGroupUpdate(d *schema.ResourceData, meta int } log.Printf("[DEBUG] Modify Cache Parameter Group: %s", modifyOpts) - _, err = conn.ModifyCacheParameterGroup(&modifyOpts) + _, err := conn.ModifyCacheParameterGroup(&modifyOpts) if err != nil { return fmt.Errorf("Error modifying Cache Parameter Group: %s", err) } diff --git a/aws/resource_aws_elasticache_parameter_group_test.go b/aws/resource_aws_elasticache_parameter_group_test.go index 2c696656d59..25331d5475c 100644 --- a/aws/resource_aws_elasticache_parameter_group_test.go +++ b/aws/resource_aws_elasticache_parameter_group_test.go @@ -7,9 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elasticache" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSElasticacheParameterGroup_basic(t *testing.T) { @@ -46,20 +47,19 @@ func TestAccAWSElasticacheParameterGroup_addParameter(t *testing.T) { rName := fmt.Sprintf("parameter-group-test-terraform-%d", acctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSElasticacheParameterGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSElasticacheParameterGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSElasticacheParameterGroupConfigParameter1(rName, "redis2.8", "appendonly", "yes"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSElasticacheParameterGroupExists("aws_elasticache_parameter_group.bar", &v), resource.TestCheckResourceAttr("aws_elasticache_parameter_group.bar", "parameter.#", "1"), - resource.TestCheckResourceAttr( - "aws_elasticache_parameter_group.bar", "parameter.283487565.name", "appendonly"), - resource.TestCheckResourceAttr( - "aws_elasticache_parameter_group.bar", "parameter.283487565.value", "yes"), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_elasticache_parameter_group.bar", "parameter.*", map[string]string{ + "name": "appendonly", + "value": "yes", + }), ), }, { @@ -72,14 +72,14 @@ func TestAccAWSElasticacheParameterGroup_addParameter(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSElasticacheParameterGroupExists("aws_elasticache_parameter_group.bar", &v), resource.TestCheckResourceAttr("aws_elasticache_parameter_group.bar", "parameter.#", "2"), - resource.TestCheckResourceAttr( - "aws_elasticache_parameter_group.bar", "parameter.283487565.name", "appendonly"), - resource.TestCheckResourceAttr( - "aws_elasticache_parameter_group.bar", "parameter.283487565.value", "yes"), - resource.TestCheckResourceAttr( - "aws_elasticache_parameter_group.bar", "parameter.2196914567.name", "appendfsync"), - resource.TestCheckResourceAttr( - "aws_elasticache_parameter_group.bar", "parameter.2196914567.value", "always"), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_elasticache_parameter_group.bar", "parameter.*", map[string]string{ + "name": "appendonly", + "value": "yes", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs("aws_elasticache_parameter_group.bar", "parameter.*", map[string]string{ + "name": "appendfsync", + "value": "always", + }), ), }, }, diff --git a/aws/resource_aws_elasticache_replication_group.go b/aws/resource_aws_elasticache_replication_group.go index d0b95faae5a..b64193bd09e 100644 --- a/aws/resource_aws_elasticache_replication_group.go +++ b/aws/resource_aws_elasticache_replication_group.go @@ -9,14 +9,15 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elasticache" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) func resourceAwsElasticacheReplicationGroup() *schema.Resource { + //lintignore:R011 return &schema.Resource{ Create: resourceAwsElasticacheReplicationGroupCreate, Read: resourceAwsElasticacheReplicationGroupRead, diff --git a/aws/resource_aws_elasticache_replication_group_test.go b/aws/resource_aws_elasticache_replication_group_test.go index c434043cac6..5b465cffb4d 100644 --- a/aws/resource_aws_elasticache_replication_group_test.go +++ b/aws/resource_aws_elasticache_replication_group_test.go @@ -11,9 +11,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elasticache" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -869,9 +869,9 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { count = 2 - availability_zone = "${data.aws_availability_zones.available.names[count.index]}" + availability_zone = data.aws_availability_zones.available.names[count.index] cidr_block = "192.168.${count.index}.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-elasticache-replication-group-number-cache-clusters" @@ -880,7 +880,7 @@ resource "aws_subnet" "test" { resource "aws_elasticache_subnet_group" "test" { name = %[1]q - subnet_ids = ["${aws_subnet.test.*.id[0]}", "${aws_subnet.test.*.id[1]}"] + subnet_ids = [aws_subnet.test[0].id, aws_subnet.test[1].id] } resource "aws_elasticache_replication_group" "test" { @@ -889,7 +889,7 @@ resource "aws_elasticache_replication_group" "test" { port = 6379 replication_group_description = "test description" replication_group_id = %[1]q - subnet_group_name = "${aws_elasticache_subnet_group.test.name}" + subnet_group_name = aws_elasticache_subnet_group.test.name } `, rName) } @@ -993,49 +993,52 @@ data "aws_availability_zones" "available" { } resource "aws_vpc" "test" { - cidr_block = "192.168.0.0/16" + cidr_block = "192.168.0.0/16" + tags = { - Name = "terraform-testacc-elasticache-replication-group-in-vpc" - } + Name = "terraform-testacc-elasticache-replication-group-in-vpc" + } } resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "192.168.0.0/20" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + vpc_id = aws_vpc.test.id + cidr_block = "192.168.0.0/20" + availability_zone = data.aws_availability_zones.available.names[0] + tags = { - Name = "tf-acc-elasticache-replication-group-in-vpc" - } + Name = "tf-acc-elasticache-replication-group-in-vpc" + } } resource "aws_elasticache_subnet_group" "test" { - name = "tf-test-cache-subnet-%03d" - description = "tf-test-cache-subnet-group-descr" - subnet_ids = ["${aws_subnet.test.id}"] + name = "tf-test-cache-subnet-%03d" + description = "tf-test-cache-subnet-group-descr" + subnet_ids = [aws_subnet.test.id] } resource "aws_security_group" "test" { - name = "tf-test-security-group-%03d" - description = "tf-test-security-group-descr" - vpc_id = "${aws_vpc.test.id}" - ingress { - from_port = -1 - to_port = -1 - protocol = "icmp" - cidr_blocks = ["0.0.0.0/0"] - } + name = "tf-test-security-group-%03d" + description = "tf-test-security-group-descr" + vpc_id = aws_vpc.test.id + + ingress { + from_port = -1 + to_port = -1 + protocol = "icmp" + cidr_blocks = ["0.0.0.0/0"] + } } resource "aws_elasticache_replication_group" "test" { - replication_group_id = "tf-%s" - replication_group_description = "test description" - node_type = "cache.t3.small" - number_cache_clusters = 1 - port = 6379 - subnet_group_name = "${aws_elasticache_subnet_group.test.name}" - security_group_ids = ["${aws_security_group.test.id}"] - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] - auto_minor_version_upgrade = false + replication_group_id = "tf-%s" + replication_group_description = "test description" + node_type = "cache.t3.small" + number_cache_clusters = 1 + port = 6379 + subnet_group_name = aws_elasticache_subnet_group.test.name + security_group_ids = [aws_security_group.test.id] + availability_zones = [data.aws_availability_zones.available.names[0]} + auto_minor_version_upgrade = false } `, acctest.RandInt(), acctest.RandInt(), acctest.RandString(10)) @@ -1048,130 +1051,150 @@ data "aws_availability_zones" "available" { values = ["opt-in-not-required"] } } + resource "aws_vpc" "test" { - cidr_block = "192.168.0.0/16" + cidr_block = "192.168.0.0/16" + tags = { - Name = "terraform-testacc-elasticache-replication-group-multi-az-in-vpc" - } + Name = "terraform-testacc-elasticache-replication-group-multi-az-in-vpc" + } } + resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "192.168.0.0/20" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + vpc_id = aws_vpc.test.id + cidr_block = "192.168.0.0/20" + availability_zone = data.aws_availability_zones.available.names[0] + tags = { - Name = "tf-acc-elasticache-replication-group-multi-az-in-vpc-foo" - } + Name = "tf-acc-elasticache-replication-group-multi-az-in-vpc-foo" + } } + resource "aws_subnet" "test2" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "192.168.16.0/20" - availability_zone = "${data.aws_availability_zones.available.names[1]}" + vpc_id = aws_vpc.test.id + cidr_block = "192.168.16.0/20" + availability_zone = data.aws_availability_zones.available.names[1] + tags = { - Name = "tf-acc-elasticache-replication-group-multi-az-in-vpc-bar" - } + Name = "tf-acc-elasticache-replication-group-multi-az-in-vpc-bar" + } } + resource "aws_elasticache_subnet_group" "test" { - name = "tf-test-cache-subnet-%03d" - description = "tf-test-cache-subnet-group-descr" - subnet_ids = [ - "${aws_subnet.test.id}", - "${aws_subnet.test2.id}" - ] + name = "tf-test-cache-subnet-%03d" + description = "tf-test-cache-subnet-group-descr" + subnet_ids = [ + aws_subnet.test.id, + aws_subnet.test2.id, + ] } + resource "aws_security_group" "test" { - name = "tf-test-security-group-%03d" - description = "tf-test-security-group-descr" - vpc_id = "${aws_vpc.test.id}" - ingress { - from_port = -1 - to_port = -1 - protocol = "icmp" - cidr_blocks = ["0.0.0.0/0"] - } + name = "tf-test-security-group-%03d" + description = "tf-test-security-group-descr" + vpc_id = aws_vpc.test.id + + ingress { + from_port = -1 + to_port = -1 + protocol = "icmp" + cidr_blocks = ["0.0.0.0/0"] + } } + resource "aws_elasticache_replication_group" "test" { - replication_group_id = "tf-%s" - replication_group_description = "test description" - node_type = "cache.t3.small" - number_cache_clusters = 2 - port = 6379 - subnet_group_name = "${aws_elasticache_subnet_group.test.name}" - security_group_ids = ["${aws_security_group.test.id}"] - availability_zones = ["${data.aws_availability_zones.available.names[0]}","${data.aws_availability_zones.available.names[1]}"] - automatic_failover_enabled = true - snapshot_window = "02:00-03:00" - snapshot_retention_limit = 7 + replication_group_id = "tf-%s" + replication_group_description = "test description" + node_type = "cache.t3.small" + number_cache_clusters = 2 + port = 6379 + subnet_group_name = aws_elasticache_subnet_group.test.name + security_group_ids = [aws_security_group.test.id] + availability_zones = [data.aws_availability_zones.available.names[0], data.aws_availability_zones.available.names[1]] + automatic_failover_enabled = true + snapshot_window = "02:00-03:00" + snapshot_retention_limit = 7 } `, acctest.RandInt(), acctest.RandInt(), acctest.RandString(10)) var testAccAWSElasticacheReplicationGroupRedisClusterInVPCConfig = fmt.Sprintf(` data "aws_availability_zones" "available" { # InvalidParameterValue: Specified node type cache.m3.medium is not available in AZ us-east-1b. - blacklisted_zone_ids = ["use1-az1"] - state = "available" + exclude_zone_ids = ["use1-az1"] + state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } - resource "aws_vpc" "test" { - cidr_block = "192.168.0.0/16" - tags = { - Name = "terraform-testacc-elasticache-replication-group-redis-cluster-in-vpc" - } - } - resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "192.168.0.0/20" - availability_zone = "${data.aws_availability_zones.available.names[0]}" - tags = { - Name = "tf-acc-elasticache-replication-group-redis-cluster-in-vpc-foo" - } - } - resource "aws_subnet" "test2" { - vpc_id = "${aws_vpc.test.id}" - cidr_block = "192.168.16.0/20" - availability_zone = "${data.aws_availability_zones.available.names[1]}" - tags = { - Name = "tf-acc-elasticache-replication-group-redis-cluster-in-vpc-bar" - } + +resource "aws_vpc" "test" { + cidr_block = "192.168.0.0/16" + + tags = { + Name = "terraform-testacc-elasticache-replication-group-redis-cluster-in-vpc" } - resource "aws_elasticache_subnet_group" "test" { - name = "tf-test-cache-subnet-%03d" - description = "tf-test-cache-subnet-group-descr" - subnet_ids = [ - "${aws_subnet.test.id}", - "${aws_subnet.test2.id}" - ] +} + +resource "aws_subnet" "test" { + vpc_id = aws_vpc.test.id + cidr_block = "192.168.0.0/20" + availability_zone = data.aws_availability_zones.available.names[0] + + tags = { + Name = "tf-acc-elasticache-replication-group-redis-cluster-in-vpc-foo" } - resource "aws_security_group" "test" { - name = "tf-test-security-group-%03d" - description = "tf-test-security-group-descr" - vpc_id = "${aws_vpc.test.id}" - ingress { - from_port = -1 - to_port = -1 - protocol = "icmp" - cidr_blocks = ["0.0.0.0/0"] - } +} + +resource "aws_subnet" "test2" { + vpc_id = aws_vpc.test.id + cidr_block = "192.168.16.0/20" + availability_zone = data.aws_availability_zones.available.names[1] + + tags = { + Name = "tf-acc-elasticache-replication-group-redis-cluster-in-vpc-bar" } - resource "aws_elasticache_replication_group" "test" { - replication_group_id = "tf-%s" - replication_group_description = "test description" - node_type = "cache.m3.medium" - number_cache_clusters = "2" - port = 6379 - subnet_group_name = "${aws_elasticache_subnet_group.test.name}" - security_group_ids = ["${aws_security_group.test.id}"] - availability_zones = ["${data.aws_availability_zones.available.names[0]}","${data.aws_availability_zones.available.names[1]}"] - automatic_failover_enabled = false - snapshot_window = "02:00-03:00" - snapshot_retention_limit = 7 - engine_version = "3.2.4" - maintenance_window = "thu:03:00-thu:04:00" +} + +resource "aws_elasticache_subnet_group" "test" { + name = "tf-test-cache-subnet-%03d" + description = "tf-test-cache-subnet-group-descr" + subnet_ids = [ + aws_subnet.test.id, + aws_subnet.test2.id, + ] +} + +resource "aws_security_group" "test" { + name = "tf-test-security-group-%03d" + description = "tf-test-security-group-descr" + vpc_id = aws_vpc.test.id + + ingress { + from_port = -1 + to_port = -1 + protocol = "icmp" + cidr_blocks = ["0.0.0.0/0"] } - `, acctest.RandInt(), acctest.RandInt(), acctest.RandString(10)) +} + +resource "aws_elasticache_replication_group" "test" { + replication_group_id = "tf-%s" + replication_group_description = "test description" + node_type = "cache.m3.medium" + number_cache_clusters = "2" + port = 6379 + subnet_group_name = aws_elasticache_subnet_group.test.name + security_group_ids = [aws_security_group.test.id] + availability_zones = [data.aws_availability_zones.available.names[0], data.aws_availability_zones.available.names[1]] + automatic_failover_enabled = false + snapshot_window = "02:00-03:00" + snapshot_retention_limit = 7 + engine_version = "3.2.4" + maintenance_window = "thu:03:00-thu:04:00" +} +`, acctest.RandInt(), acctest.RandInt(), acctest.RandString(10)) func testAccAWSElasticacheReplicationGroupNativeRedisClusterErrorConfig(rInt int, rName string) string { return fmt.Sprintf(` @@ -1193,9 +1216,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id cidr_block = "192.168.0.0/20" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-elasticache-replication-group-native-redis-cluster-err-test" @@ -1203,9 +1226,9 @@ resource "aws_subnet" "test" { } resource "aws_subnet" "test2" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id cidr_block = "192.168.16.0/20" - availability_zone = "${data.aws_availability_zones.available.names[1]}" + availability_zone = data.aws_availability_zones.available.names[1] tags = { Name = "tf-acc-elasticache-replication-group-native-redis-cluster-err-test" @@ -1217,15 +1240,15 @@ resource "aws_elasticache_subnet_group" "test" { description = "tf-test-cache-subnet-group-descr" subnet_ids = [ - "${aws_subnet.test.id}", - "${aws_subnet.test.id}", + aws_subnet.test.id, + aws_subnet.test.id, ] } resource "aws_security_group" "test" { name = "tf-test-security-group-%03d" description = "tf-test-security-group-descr" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id ingress { from_port = -1 @@ -1240,8 +1263,8 @@ resource "aws_elasticache_replication_group" "test" { replication_group_description = "test description" node_type = "cache.t2.micro" port = 6379 - subnet_group_name = "${aws_elasticache_subnet_group.test.name}" - security_group_ids = ["${aws_security_group.test.id}"] + subnet_group_name = aws_elasticache_subnet_group.test.name + security_group_ids = [aws_security_group.test.id] automatic_failover_enabled = true cluster_mode { @@ -1274,9 +1297,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id cidr_block = "192.168.0.0/20" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-elasticache-replication-group-native-redis-cluster-test" @@ -1284,9 +1307,9 @@ resource "aws_subnet" "test" { } resource "aws_subnet" "test2" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id cidr_block = "192.168.16.0/20" - availability_zone = "${data.aws_availability_zones.available.names[1]}" + availability_zone = data.aws_availability_zones.available.names[1] tags = { Name = "tf-acc-elasticache-replication-group-native-redis-cluster-test" @@ -1298,15 +1321,15 @@ resource "aws_elasticache_subnet_group" "test" { description = "tf-test-cache-subnet-group-descr" subnet_ids = [ - "${aws_subnet.test.id}", - "${aws_subnet.test.id}", + aws_subnet.test.id, + aws_subnet.test.id, ] } resource "aws_security_group" "test" { name = "tf-test-%[1]s" description = "tf-test-security-group-descr" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id ingress { from_port = -1 @@ -1321,8 +1344,8 @@ resource "aws_elasticache_replication_group" "test" { replication_group_description = "test description" node_type = "cache.t2.micro" port = 6379 - subnet_group_name = "${aws_elasticache_subnet_group.test.name}" - security_group_ids = ["${aws_security_group.test.id}"] + subnet_group_name = aws_elasticache_subnet_group.test.name + security_group_ids = [aws_security_group.test.id] automatic_failover_enabled = true cluster_mode { @@ -1353,9 +1376,9 @@ resource "aws_vpc" "foo" { } resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id cidr_block = "192.168.0.0/20" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-elasticache-replication-group-at-rest-encryption" @@ -1367,14 +1390,14 @@ resource "aws_elasticache_subnet_group" "bar" { description = "tf-test-cache-subnet-group-descr" subnet_ids = [ - "${aws_subnet.foo.id}", + aws_subnet.foo.id, ] } resource "aws_security_group" "bar" { name = "tf-test-security-group-%03d" description = "tf-test-security-group-descr" - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id ingress { from_port = -1 @@ -1385,7 +1408,7 @@ resource "aws_security_group" "bar" { } resource "aws_kms_key" "bar" { - description = "tf-test-cmk-kms-key-id" + description = "tf-test-cmk-kms-key-id" } resource "aws_elasticache_replication_group" "bar" { @@ -1394,13 +1417,13 @@ resource "aws_elasticache_replication_group" "bar" { node_type = "cache.t2.micro" number_cache_clusters = "1" port = 6379 - subnet_group_name = "${aws_elasticache_subnet_group.bar.name}" - security_group_ids = ["${aws_security_group.bar.id}"] + subnet_group_name = aws_elasticache_subnet_group.bar.name + security_group_ids = [aws_security_group.bar.id] parameter_group_name = "default.redis3.2" - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] engine_version = "3.2.6" - at_rest_encryption_enabled = true - kms_key_id = "${aws_kms_key.bar.arn}" + at_rest_encryption_enabled = true + kms_key_id = aws_kms_key.bar.arn } `, rInt, rInt, rString) } @@ -1425,9 +1448,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id cidr_block = "192.168.0.0/20" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-elasticache-replication-group-at-rest-encryption" @@ -1439,14 +1462,14 @@ resource "aws_elasticache_subnet_group" "test" { description = "tf-test-cache-subnet-group-descr" subnet_ids = [ - "${aws_subnet.test.id}", + aws_subnet.test.id, ] } resource "aws_security_group" "test" { name = "tf-test-security-group-%03d" description = "tf-test-security-group-descr" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id ingress { from_port = -1 @@ -1462,10 +1485,10 @@ resource "aws_elasticache_replication_group" "test" { node_type = "cache.t2.micro" number_cache_clusters = "1" port = 6379 - subnet_group_name = "${aws_elasticache_subnet_group.test.name}" - security_group_ids = ["${aws_security_group.test.id}"] + subnet_group_name = aws_elasticache_subnet_group.test.name + security_group_ids = [aws_security_group.test.id] parameter_group_name = "default.redis3.2" - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] engine_version = "3.2.6" at_rest_encryption_enabled = true } @@ -1492,9 +1515,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id cidr_block = "192.168.0.0/20" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-elasticache-replication-group-auth-token-transit-encryption" @@ -1506,14 +1529,14 @@ resource "aws_elasticache_subnet_group" "test" { description = "tf-test-cache-subnet-group-descr" subnet_ids = [ - "${aws_subnet.test.id}", + aws_subnet.test.id, ] } resource "aws_security_group" "test" { name = "tf-test-security-group-%03d" description = "tf-test-security-group-descr" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id ingress { from_port = -1 @@ -1529,10 +1552,10 @@ resource "aws_elasticache_replication_group" "test" { node_type = "cache.t2.micro" number_cache_clusters = "1" port = 6379 - subnet_group_name = "${aws_elasticache_subnet_group.test.name}" - security_group_ids = ["${aws_security_group.test.id}"] + subnet_group_name = aws_elasticache_subnet_group.test.name + security_group_ids = [aws_security_group.test.id] parameter_group_name = "default.redis3.2" - availability_zones = ["${data.aws_availability_zones.available.names[0]}"] + availability_zones = [data.aws_availability_zones.available.names[0]] engine_version = "3.2.6" transit_encryption_enabled = true auth_token = "%s" @@ -1544,8 +1567,8 @@ func testAccAWSElasticacheReplicationGroupConfig_NumberCacheClusters(rName strin return fmt.Sprintf(` data "aws_availability_zones" "available" { # InvalidParameterValue: Specified node type cache.m3.medium is not available in AZ us-east-1b. - blacklisted_zone_ids = ["use1-az1"] - state = "available" + exclude_zone_ids = ["use1-az1"] + state = "available" filter { name = "opt-in-status" @@ -1564,9 +1587,9 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { count = 2 - availability_zone = "${data.aws_availability_zones.available.names[count.index]}" + availability_zone = data.aws_availability_zones.available.names[count.index] cidr_block = "192.168.${count.index}.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-elasticache-replication-group-number-cache-clusters" @@ -1575,7 +1598,7 @@ resource "aws_subnet" "test" { resource "aws_elasticache_subnet_group" "test" { name = "%[1]s" - subnet_ids = ["${aws_subnet.test.*.id[0]}", "${aws_subnet.test.*.id[1]}"] + subnet_ids = [aws_subnet.test[0].id, aws_subnet.test[1].id] } resource "aws_elasticache_replication_group" "test" { @@ -1585,7 +1608,7 @@ resource "aws_elasticache_replication_group" "test" { number_cache_clusters = %[3]d replication_group_id = "%[1]s" replication_group_description = "Terraform Acceptance Testing - number_cache_clusters" - subnet_group_name = "${aws_elasticache_subnet_group.test.name}" + subnet_group_name = aws_elasticache_subnet_group.test.name } `, rName, autoFailover, numberCacheClusters) } diff --git a/aws/resource_aws_elasticache_security_group.go b/aws/resource_aws_elasticache_security_group.go index 1c1cffbc138..d3e297374c7 100644 --- a/aws/resource_aws_elasticache_security_group.go +++ b/aws/resource_aws_elasticache_security_group.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/service/elasticache" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsElasticacheSecurityGroup() *schema.Resource { diff --git a/aws/resource_aws_elasticache_security_group_test.go b/aws/resource_aws_elasticache_security_group_test.go index 35276d4b4fd..54ee8c89f5d 100644 --- a/aws/resource_aws_elasticache_security_group_test.go +++ b/aws/resource_aws_elasticache_security_group_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elasticache" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -158,6 +158,6 @@ resource "aws_security_group" "test" { resource "aws_elasticache_security_group" "test" { name = "tf-test-security-group-%03d" - security_group_names = ["${aws_security_group.test.name}"] + security_group_names = [aws_security_group.test.name] } `, acctest.RandInt(), acctest.RandInt()) diff --git a/aws/resource_aws_elasticache_subnet_group.go b/aws/resource_aws_elasticache_subnet_group.go index de959072fcf..c4f20a16c2e 100644 --- a/aws/resource_aws_elasticache_subnet_group.go +++ b/aws/resource_aws_elasticache_subnet_group.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elasticache" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsElasticacheSubnetGroup() *schema.Resource { @@ -127,7 +127,7 @@ func resourceAwsElasticacheSubnetGroupRead(d *schema.ResourceData, meta interfac func resourceAwsElasticacheSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).elasticacheconn - if d.HasChange("subnet_ids") || d.HasChange("description") { + if d.HasChanges("subnet_ids", "description") { var subnets []*string if v := d.Get("subnet_ids"); v != nil { for _, v := range v.(*schema.Set).List() { diff --git a/aws/resource_aws_elasticache_subnet_group_test.go b/aws/resource_aws_elasticache_subnet_group_test.go index 0b60ddf3e84..46e9bb65456 100644 --- a/aws/resource_aws_elasticache_subnet_group_test.go +++ b/aws/resource_aws_elasticache_subnet_group_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elasticache" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSElasticacheSubnetGroup_basic(t *testing.T) { @@ -156,85 +156,92 @@ func testAccCheckAWSElastiCacheSubnetGroupAttrs(csg *elasticache.CacheSubnetGrou var testAccAWSElasticacheSubnetGroupConfig = ` resource "aws_vpc" "foo" { - cidr_block = "192.168.0.0/16" + cidr_block = "192.168.0.0/16" + tags = { - Name = "terraform-testacc-elasticache-subnet-group" - } + Name = "terraform-testacc-elasticache-subnet-group" + } } resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "192.168.0.0/20" - availability_zone = "us-west-2a" + vpc_id = aws_vpc.foo.id + cidr_block = "192.168.0.0/20" + availability_zone = "us-west-2a" + tags = { - Name = "tf-acc-elasticache-subnet-group" - } + Name = "tf-acc-elasticache-subnet-group" + } } resource "aws_elasticache_subnet_group" "test" { - // Including uppercase letters in this name to ensure - // that we correctly handle the fact that the API - // normalizes names to lowercase. - name = "tf-TEST-cache-subnet-%03d" - subnet_ids = ["${aws_subnet.foo.id}"] + # Including uppercase letters in this name to ensure + # that we correctly handle the fact that the API + # normalizes names to lowercase. + name = "tf-TEST-cache-subnet-%03d" + subnet_ids = [aws_subnet.foo.id] } ` var testAccAWSElasticacheSubnetGroupUpdateConfigPre = ` resource "aws_vpc" "foo" { - cidr_block = "10.0.0.0/16" + cidr_block = "10.0.0.0/16" + tags = { - Name = "terraform-testacc-elasticache-subnet-group-update" - } + Name = "terraform-testacc-elasticache-subnet-group-update" + } } resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "10.0.1.0/24" - availability_zone = "us-west-2a" + vpc_id = aws_vpc.foo.id + cidr_block = "10.0.1.0/24" + availability_zone = "us-west-2a" + tags = { - Name = "tf-acc-elasticache-subnet-group-update-foo" - } + Name = "tf-acc-elasticache-subnet-group-update-foo" + } } resource "aws_elasticache_subnet_group" "test" { - name = "tf-test-cache-subnet-%03d" - description = "tf-test-cache-subnet-group-descr" - subnet_ids = ["${aws_subnet.foo.id}"] + name = "tf-test-cache-subnet-%03d" + description = "tf-test-cache-subnet-group-descr" + subnet_ids = [aws_subnet.foo.id] } ` var testAccAWSElasticacheSubnetGroupUpdateConfigPost = ` resource "aws_vpc" "foo" { - cidr_block = "10.0.0.0/16" + cidr_block = "10.0.0.0/16" + tags = { - Name = "terraform-testacc-elasticache-subnet-group-update" - } + Name = "terraform-testacc-elasticache-subnet-group-update" + } } resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "10.0.1.0/24" - availability_zone = "us-west-2a" + vpc_id = aws_vpc.foo.id + cidr_block = "10.0.1.0/24" + availability_zone = "us-west-2a" + tags = { - Name = "tf-acc-elasticache-subnet-group-update-foo" - } + Name = "tf-acc-elasticache-subnet-group-update-foo" + } } resource "aws_subnet" "test" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "10.0.2.0/24" - availability_zone = "us-west-2a" + vpc_id = aws_vpc.foo.id + cidr_block = "10.0.2.0/24" + availability_zone = "us-west-2a" + tags = { - Name = "tf-acc-elasticache-subnet-group-update-test" - } + Name = "tf-acc-elasticache-subnet-group-update-test" + } } resource "aws_elasticache_subnet_group" "test" { - name = "tf-test-cache-subnet-%03d" - description = "tf-test-cache-subnet-group-descr-edited" - subnet_ids = [ - "${aws_subnet.foo.id}", - "${aws_subnet.test.id}", - ] + name = "tf-test-cache-subnet-%03d" + description = "tf-test-cache-subnet-group-descr-edited" + subnet_ids = [ + aws_subnet.foo.id, + aws_subnet.test.id, + ] } ` diff --git a/aws/resource_aws_elasticsearch_domain.go b/aws/resource_aws_elasticsearch_domain.go index d870352eeda..094b1bd7042 100644 --- a/aws/resource_aws_elasticsearch_domain.go +++ b/aws/resource_aws_elasticsearch_domain.go @@ -1,6 +1,7 @@ package aws import ( + "context" "fmt" "log" "regexp" @@ -10,11 +11,11 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/customdiff" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -33,7 +34,7 @@ func resourceAwsElasticSearchDomain() *schema.Resource { }, CustomizeDiff: customdiff.Sequence( - customdiff.ForceNewIf("elasticsearch_version", func(d *schema.ResourceDiff, meta interface{}) bool { + customdiff.ForceNewIf("elasticsearch_version", func(_ context.Context, d *schema.ResourceDiff, meta interface{}) bool { newVersion := d.Get("elasticsearch_version").(string) domainName := d.Get("domain_name").(string) @@ -69,19 +70,58 @@ func resourceAwsElasticSearchDomain() *schema.Resource { Type: schema.TypeMap, Optional: true, Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "advanced_security_options": { + Type: schema.TypeList, + Optional: true, + Computed: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Required: true, + ForceNew: true, + }, + "internal_user_database_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "master_user_options": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "master_user_arn": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validateArn, + }, + "master_user_name": { + Type: schema.TypeString, + Optional: true, + }, + "master_user_password": { + Type: schema.TypeString, + Optional: true, + Sensitive: true, + }, + }, + }, + }, + }, + }, }, "domain_name": { Type: schema.TypeString, Required: true, ForceNew: true, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if !regexp.MustCompile(`^[a-z][0-9a-z\-]{2,27}$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q must start with a lowercase alphabet and be at least 3 and no more than 28 characters long. Valid characters are a-z (lowercase letters), 0-9, and - (hyphen).", k)) - } - return - }, + ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[a-z][0-9a-z\-]{2,27}$`), + "must start with a lowercase alphabet and be at least 3 and no more than 28 characters long."+ + " Valid characters are a-z (lowercase letters), 0-9, and - (hyphen)."), }, "arn": { Type: schema.TypeString, @@ -145,6 +185,14 @@ func resourceAwsElasticSearchDomain() *schema.Resource { Type: schema.TypeString, Optional: true, Computed: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validation.StringInSlice([]string{ + elasticsearch.VolumeTypeStandard, + elasticsearch.VolumeTypeGp2, + elasticsearch.VolumeTypeIo1, + }, false), + ), }, }, }, @@ -216,7 +264,7 @@ func resourceAwsElasticSearchDomain() *schema.Resource { "instance_type": { Type: schema.TypeString, Optional: true, - Default: "m3.medium.elasticsearch", + Default: elasticsearch.ESPartitionInstanceTypeM3MediumElasticsearch, }, "zone_awareness_config": { Type: schema.TypeList, @@ -238,6 +286,24 @@ func resourceAwsElasticSearchDomain() *schema.Resource { Type: schema.TypeBool, Optional: true, }, + "warm_enabled": { + Type: schema.TypeBool, + Optional: true, + }, + "warm_count": { + Type: schema.TypeInt, + Optional: true, + ValidateFunc: validation.IntBetween(2, 150), + }, + "warm_type": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + elasticsearch.ESWarmPartitionInstanceTypeUltrawarm1MediumElasticsearch, + elasticsearch.ESWarmPartitionInstanceTypeUltrawarm1LargeElasticsearch, + "ultrawarm1.xlarge.elasticsearch", + }, false), + }, }, }, }, @@ -307,8 +373,9 @@ func resourceAwsElasticSearchDomain() *schema.Resource { }, false), }, "cloudwatch_log_group_arn": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validateArn, }, "enabled": { Type: schema.TypeBool, @@ -345,8 +412,9 @@ func resourceAwsElasticSearchDomain() *schema.Resource { Required: true, }, "role_arn": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validateArn, }, }, }, @@ -389,6 +457,10 @@ func resourceAwsElasticSearchDomainCreate(d *schema.ResourceData, meta interface input.AdvancedOptions = stringMapToPointers(v.(map[string]interface{})) } + if v, ok := d.GetOk("advanced_security_options"); ok { + input.AdvancedSecurityOptions = expandAdvancedSecurityOptions(v.([]interface{})) + } + if v, ok := d.GetOk("ebs_options"); ok { options := v.([]interface{}) @@ -559,7 +631,7 @@ func waitForElasticSearchDomainCreation(conn *elasticsearch.ElasticsearchService return resource.NonRetryableError(err) } - if !*out.DomainStatus.Processing && (out.DomainStatus.Endpoint != nil || out.DomainStatus.Endpoints != nil) { + if !aws.BoolValue(out.DomainStatus.Processing) && (out.DomainStatus.Endpoint != nil || out.DomainStatus.Endpoints != nil) { return nil } @@ -571,7 +643,7 @@ func waitForElasticSearchDomainCreation(conn *elasticsearch.ElasticsearchService if err != nil { return fmt.Errorf("Error describing ElasticSearch domain: %s", err) } - if !*out.DomainStatus.Processing && (out.DomainStatus.Endpoint != nil || out.DomainStatus.Endpoints != nil) { + if !aws.BoolValue(out.DomainStatus.Processing) && (out.DomainStatus.Endpoint != nil || out.DomainStatus.Endpoints != nil) { return nil } } @@ -638,6 +710,22 @@ func resourceAwsElasticSearchDomainRead(d *schema.ResourceData, meta interface{} return err } + // Populate AdvancedSecurityOptions with values returned from + // DescribeElasticsearchDomainConfig, if enabled, else use + // values from resource; additionally, append MasterUserOptions + // from resource as they are not returned from the API + if ds.AdvancedSecurityOptions != nil { + advSecOpts := flattenAdvancedSecurityOptions(ds.AdvancedSecurityOptions) + if !aws.BoolValue(ds.AdvancedSecurityOptions.Enabled) { + advSecOpts[0]["internal_user_database_enabled"] = getUserDBEnabled(d) + } + advSecOpts[0]["master_user_options"] = getMasterUserOptions(d) + + if err := d.Set("advanced_security_options", advSecOpts); err != nil { + return fmt.Errorf("error setting advanced_security_options: %w", err) + } + } + if err := d.Set("snapshot_options", flattenESSnapshotOptions(ds.SnapshotOptions)); err != nil { return fmt.Errorf("error setting snapshot_options: %s", err) } @@ -722,11 +810,15 @@ func resourceAwsElasticSearchDomainUpdate(d *schema.ResourceData, meta interface input.AdvancedOptions = stringMapToPointers(d.Get("advanced_options").(map[string]interface{})) } + if d.HasChange("advanced_security_options") { + input.AdvancedSecurityOptions = expandAdvancedSecurityOptions(d.Get("advanced_security_options").([]interface{})) + } + if d.HasChange("domain_endpoint_options") { input.DomainEndpointOptions = expandESDomainEndpointOptions(d.Get("domain_endpoint_options").([]interface{})) } - if d.HasChange("ebs_options") || d.HasChange("cluster_config") { + if d.HasChanges("ebs_options", "cluster_config") { options := d.Get("ebs_options").([]interface{}) if len(options) == 1 { @@ -797,7 +889,7 @@ func resourceAwsElasticSearchDomainUpdate(d *schema.ResourceData, meta interface return resource.NonRetryableError(err) } - if !*out.DomainStatus.Processing { + if !aws.BoolValue(out.DomainStatus.Processing) { return nil } @@ -809,7 +901,7 @@ func resourceAwsElasticSearchDomainUpdate(d *schema.ResourceData, meta interface if err != nil { return fmt.Errorf("Error describing ElasticSearch domain: %s", err) } - if !*out.DomainStatus.Processing { + if !aws.BoolValue(out.DomainStatus.Processing) { return nil } } @@ -970,3 +1062,118 @@ func flattenESNodeToNodeEncryptionOptions(o *elasticsearch.NodeToNodeEncryptionO return []map[string]interface{}{m} } + +func expandESClusterConfig(m map[string]interface{}) *elasticsearch.ElasticsearchClusterConfig { + config := elasticsearch.ElasticsearchClusterConfig{} + + if v, ok := m["dedicated_master_enabled"]; ok { + isEnabled := v.(bool) + config.DedicatedMasterEnabled = aws.Bool(isEnabled) + + if isEnabled { + if v, ok := m["dedicated_master_count"]; ok && v.(int) > 0 { + config.DedicatedMasterCount = aws.Int64(int64(v.(int))) + } + if v, ok := m["dedicated_master_type"]; ok && v.(string) != "" { + config.DedicatedMasterType = aws.String(v.(string)) + } + } + } + + if v, ok := m["instance_count"]; ok { + config.InstanceCount = aws.Int64(int64(v.(int))) + } + if v, ok := m["instance_type"]; ok { + config.InstanceType = aws.String(v.(string)) + } + + if v, ok := m["zone_awareness_enabled"]; ok { + isEnabled := v.(bool) + config.ZoneAwarenessEnabled = aws.Bool(isEnabled) + + if isEnabled { + if v, ok := m["zone_awareness_config"]; ok { + config.ZoneAwarenessConfig = expandElasticsearchZoneAwarenessConfig(v.([]interface{})) + } + } + } + + if v, ok := m["warm_enabled"]; ok { + isEnabled := v.(bool) + config.WarmEnabled = aws.Bool(isEnabled) + + if isEnabled { + if v, ok := m["warm_count"]; ok { + config.WarmCount = aws.Int64(int64(v.(int))) + } + + if v, ok := m["warm_type"]; ok { + config.WarmType = aws.String(v.(string)) + } + } + } + + return &config +} + +func expandElasticsearchZoneAwarenessConfig(l []interface{}) *elasticsearch.ZoneAwarenessConfig { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + zoneAwarenessConfig := &elasticsearch.ZoneAwarenessConfig{} + + if v, ok := m["availability_zone_count"]; ok && v.(int) > 0 { + zoneAwarenessConfig.AvailabilityZoneCount = aws.Int64(int64(v.(int))) + } + + return zoneAwarenessConfig +} + +func flattenESClusterConfig(c *elasticsearch.ElasticsearchClusterConfig) []map[string]interface{} { + m := map[string]interface{}{ + "zone_awareness_config": flattenElasticsearchZoneAwarenessConfig(c.ZoneAwarenessConfig), + "zone_awareness_enabled": aws.BoolValue(c.ZoneAwarenessEnabled), + } + + if c.DedicatedMasterCount != nil { + m["dedicated_master_count"] = aws.Int64Value(c.DedicatedMasterCount) + } + if c.DedicatedMasterEnabled != nil { + m["dedicated_master_enabled"] = aws.BoolValue(c.DedicatedMasterEnabled) + } + if c.DedicatedMasterType != nil { + m["dedicated_master_type"] = aws.StringValue(c.DedicatedMasterType) + } + if c.InstanceCount != nil { + m["instance_count"] = aws.Int64Value(c.InstanceCount) + } + if c.InstanceType != nil { + m["instance_type"] = aws.StringValue(c.InstanceType) + } + if c.WarmEnabled != nil { + m["warm_enabled"] = aws.BoolValue(c.WarmEnabled) + } + if c.WarmCount != nil { + m["warm_count"] = aws.Int64Value(c.WarmCount) + } + if c.WarmType != nil { + m["warm_type"] = aws.StringValue(c.WarmType) + } + + return []map[string]interface{}{m} +} + +func flattenElasticsearchZoneAwarenessConfig(zoneAwarenessConfig *elasticsearch.ZoneAwarenessConfig) []interface{} { + if zoneAwarenessConfig == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "availability_zone_count": aws.Int64Value(zoneAwarenessConfig.AvailabilityZoneCount), + } + + return []interface{}{m} +} diff --git a/aws/resource_aws_elasticsearch_domain_policy.go b/aws/resource_aws_elasticsearch_domain_policy.go index 5a4a89da232..69f88f00745 100644 --- a/aws/resource_aws_elasticsearch_domain_policy.go +++ b/aws/resource_aws_elasticsearch_domain_policy.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsElasticSearchDomainPolicy() *schema.Resource { diff --git a/aws/resource_aws_elasticsearch_domain_policy_test.go b/aws/resource_aws_elasticsearch_domain_policy_test.go index 973836e3d2d..78f691ac687 100644 --- a/aws/resource_aws_elasticsearch_domain_policy_test.go +++ b/aws/resource_aws_elasticsearch_domain_policy_test.go @@ -5,9 +5,9 @@ import ( "testing" elasticsearch "github.com/aws/aws-sdk-go/service/elasticsearchservice" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSElasticSearchDomainPolicy_basic(t *testing.T) { @@ -97,11 +97,12 @@ resource "aws_elasticsearch_domain" "example" { } resource "aws_elasticsearch_domain_policy" "main" { - domain_name = "${aws_elasticsearch_domain.example.domain_name}" + domain_name = aws_elasticsearch_domain.example.domain_name access_policies = < 0 && coreInstanceType == "") { - return fmt.Errorf("Must specify both `core_instance_count` and `core_instance_type`") - } else if coreInstanceCount > 0 && coreInstanceType != "" { - coreInstanceGroupConfig := &emr.InstanceGroupConfig{ - InstanceCount: aws.Int64(int64(d.Get("core_instance_count").(int))), - InstanceRole: aws.String(emr.InstanceRoleTypeCore), - InstanceType: aws.String(d.Get("core_instance_type").(string)), - } - instanceConfig.InstanceGroups = append(instanceConfig.InstanceGroups, coreInstanceGroupConfig) - } - var instanceProfile string if a, ok := d.GetOk("ec2_attributes"); ok { ec2Attributes := a.([]interface{}) @@ -794,18 +606,6 @@ func resourceAwsEMRClusterCreate(d *schema.ResourceData, meta interface{}) error } } - // DEPRECATED: Remove in a future major version - if v, ok := d.GetOk("instance_group"); ok { - instanceGroupConfigs := v.(*schema.Set).List() - instanceGroups, err := expandInstanceGroupConfigs(instanceGroupConfigs) - - if err != nil { - return fmt.Errorf("error parsing EMR instance groups configuration: %s", err) - } - - instanceConfig.InstanceGroups = instanceGroups - } - emrApps := expandApplications(applications) params := &emr.RunJobFlowInput{ @@ -1003,27 +803,6 @@ func resourceAwsEMRClusterRead(d *schema.ResourceData, meta interface{}) error { coreGroup := emrCoreInstanceGroup(instanceGroups) masterGroup := findMasterGroup(instanceGroups) - d.Set("core_instance_count", 0) - d.Set("core_instance_type", "") - d.Set("master_instance_type", "") - - if coreGroup != nil { - d.Set("core_instance_type", coreGroup.InstanceType) - d.Set("core_instance_count", coreGroup.RequestedInstanceCount) - } - - if masterGroup != nil { - d.Set("master_instance_type", masterGroup.InstanceType) - } - - flattenedInstanceGroups, err := flattenInstanceGroups(instanceGroups) - if err != nil { - return fmt.Errorf("error flattening instance groups: %s", err) - } - if err := d.Set("instance_group", flattenedInstanceGroups); err != nil { - return fmt.Errorf("error setting instance_group: %s", err) - } - flattenedCoreInstanceGroup, err := flattenEmrCoreInstanceGroup(coreGroup) if err != nil { @@ -1126,59 +905,6 @@ func resourceAwsEMRClusterRead(d *schema.ResourceData, meta interface{}) error { func resourceAwsEMRClusterUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).emrconn - if d.HasChange("core_instance_count") { - log.Printf("[DEBUG] Modify EMR cluster") - groups, err := fetchAllEMRInstanceGroups(conn, d.Id()) - if err != nil { - log.Printf("[DEBUG] Error finding all instance groups: %s", err) - return err - } - - coreInstanceCount := d.Get("core_instance_count").(int) - coreGroup := emrCoreInstanceGroup(groups) - if coreGroup == nil { - return fmt.Errorf("Error finding core group") - } - - params := &emr.ModifyInstanceGroupsInput{ - InstanceGroups: []*emr.InstanceGroupModifyConfig{ - { - InstanceGroupId: coreGroup.Id, - InstanceCount: aws.Int64(int64(coreInstanceCount) - 1), - }, - }, - } - _, errModify := conn.ModifyInstanceGroups(params) - if errModify != nil { - log.Printf("[ERROR] %s", errModify) - return errModify - } - - log.Printf("[DEBUG] Modify EMR Cluster done...") - - log.Println("[INFO] Waiting for EMR Cluster to be available") - - stateConf := &resource.StateChangeConf{ - Pending: []string{ - emr.ClusterStateBootstrapping, - emr.ClusterStateStarting, - }, - Target: []string{ - emr.ClusterStateRunning, - emr.ClusterStateWaiting, - }, - Refresh: resourceAwsEMRClusterStateRefreshFunc(d, meta), - Timeout: 40 * time.Minute, - MinTimeout: 10 * time.Second, - Delay: 5 * time.Second, - } - - _, err = stateConf.WaitForState() - if err != nil { - return fmt.Errorf("Error waiting for EMR Cluster state to be \"WAITING\" or \"RUNNING\" after modification: %s", err) - } - } - if d.HasChange("visible_to_all_users") { _, errModify := conn.SetVisibleToAllUsers(&emr.SetVisibleToAllUsersInput{ JobFlowIds: []*string{aws.String(d.Id())}, @@ -1684,49 +1410,6 @@ func flattenEmrStepSummary(stepSummary *emr.StepSummary) map[string]interface{} return m } -func flattenInstanceGroup(ig *emr.InstanceGroup) (map[string]interface{}, error) { - attrs := map[string]interface{}{} - if ig.BidPrice != nil { - attrs["bid_price"] = *ig.BidPrice - } - - attrs["id"] = *ig.Id - attrs["ebs_config"] = flattenEBSConfig(ig.EbsBlockDevices) - attrs["instance_count"] = int(*ig.RequestedInstanceCount) - attrs["instance_role"] = *ig.InstanceGroupType - attrs["instance_type"] = *ig.InstanceType - if ig.Name != nil { - attrs["name"] = *ig.Name - } - - autoscalingPolicy, err := flattenEmrAutoScalingPolicyDescription(ig.AutoScalingPolicy) - - if err != nil { - return nil, err - } - - attrs["autoscaling_policy"] = autoscalingPolicy - - if attrs["name"] != nil { - attrs["name"] = *ig.Name - } - - return attrs, nil -} - -func flattenInstanceGroups(igs []*emr.InstanceGroup) (*schema.Set, error) { - instanceGroupSet := []interface{}{} - for _, ig := range igs { - flattenedInstanceGroup, err := flattenInstanceGroup(ig) - if err != nil { - return nil, err - } - instanceGroupSet = append(instanceGroupSet, flattenedInstanceGroup) - } - - return schema.NewSet(resourceAwsEMRClusterInstanceGroupHash, instanceGroupSet), nil -} - func flattenEBSConfig(ebsBlockDevices []*emr.EbsBlockDevice) *schema.Set { ebsConfig := make([]interface{}, 0) @@ -1869,54 +1552,6 @@ func expandEmrStepConfigs(l []interface{}) []*emr.StepConfig { return stepConfigs } -func expandInstanceGroupConfigs(instanceGroupConfigs []interface{}) ([]*emr.InstanceGroupConfig, error) { - instanceGroupConfig := []*emr.InstanceGroupConfig{} - - for _, raw := range instanceGroupConfigs { - configAttributes := raw.(map[string]interface{}) - configInstanceRole := configAttributes["instance_role"].(string) - configInstanceCount := configAttributes["instance_count"].(int) - configInstanceType := configAttributes["instance_type"].(string) - configName := configAttributes["name"].(string) - config := &emr.InstanceGroupConfig{ - Name: aws.String(configName), - InstanceRole: aws.String(configInstanceRole), - InstanceType: aws.String(configInstanceType), - InstanceCount: aws.Int64(int64(configInstanceCount)), - } - - expandBidPrice(config, configAttributes) - expandEbsConfig(configAttributes, config) - - if v, ok := configAttributes["autoscaling_policy"]; ok && v.(string) != "" { - var autoScalingPolicy *emr.AutoScalingPolicy - - err := json.Unmarshal([]byte(v.(string)), &autoScalingPolicy) - - if err != nil { - return []*emr.InstanceGroupConfig{}, fmt.Errorf("error parsing EMR Auto Scaling Policy JSON: %s", err) - } - - config.AutoScalingPolicy = autoScalingPolicy - } - - instanceGroupConfig = append(instanceGroupConfig, config) - } - - return instanceGroupConfig, nil -} - -func expandBidPrice(config *emr.InstanceGroupConfig, configAttributes map[string]interface{}) { - if bidPrice, ok := configAttributes["bid_price"]; ok { - if bidPrice != "" { - config.BidPrice = aws.String(bidPrice.(string)) - config.Market = aws.String("SPOT") - } else { - config.Market = aws.String("ON_DEMAND") - } - } -} - func expandEbsConfig(configAttributes map[string]interface{}, config *emr.InstanceGroupConfig) { if rawEbsConfigs, ok := configAttributes["ebs_config"]; ok { ebsConfig := &emr.EbsConfiguration{} @@ -2064,42 +1699,6 @@ func findMasterGroup(instanceGroups []*emr.InstanceGroup) *emr.InstanceGroup { return nil } -// EMRCluster always has an instance role of either master, core, or task -// Name is optional for core and master(only group allowed for this type) but needed for task -// since you can have multiple task instance groups. -func resourceAwsEMRClusterInstanceGroupHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%s-", m["instance_role"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["instance_type"].(string))) - buf.WriteString(fmt.Sprintf("%d-", m["instance_count"].(int))) - if v, ok := m["name"]; ok { - buf.WriteString(fmt.Sprintf("%s-", v.(string))) - } - if v, ok := m["bid_price"]; ok { - buf.WriteString(fmt.Sprintf("%s-", v.(string))) - } - - if v, ok := m["autoscaling_policy"]; ok { - pleaseWork, _ := structure.NormalizeJsonString(v.(string)) - buf.WriteString(fmt.Sprintf("%s-", pleaseWork)) - } - - if v, ok := m["ebs_config"]; ok { - configs := v.(*schema.Set).List() - - // There is an issue where an `ebs_config` is automatically configured when not specified in Terraform and - // this causes the hashcode to change. Instead, we'll ignore that configuration when setting up the hashcode. - if len(configs) > 1 { - for _, ebsConfigs := range configs { - buf.WriteString(fmt.Sprintf("%d-", resourceAwsEMRClusterEBSConfigHash(ebsConfigs.(map[string]interface{})))) - } - } - } - - return hashcode.String(buf.String()) -} - func resourceAwsEMRClusterEBSConfigHash(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) diff --git a/aws/resource_aws_emr_cluster_test.go b/aws/resource_aws_emr_cluster_test.go index 65ea77d7b80..7904971d6f8 100644 --- a/aws/resource_aws_emr_cluster_test.go +++ b/aws/resource_aws_emr_cluster_test.go @@ -11,9 +11,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/emr" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -99,10 +99,14 @@ func TestAccAWSEMRCluster_basic(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -135,10 +139,15 @@ func TestAccAWSEMRCluster_additionalInfo(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps", "additional_info"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "additional_info", + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -185,10 +194,14 @@ func TestAccAWSEMRCluster_configurationsJson(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -279,10 +292,14 @@ func TestAccAWSEMRCluster_CoreInstanceGroup_AutoscalingPolicy(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfigCoreInstanceGroupAutoscalingPolicy(rName, autoscalingPolicy2), @@ -325,10 +342,14 @@ func TestAccAWSEMRCluster_CoreInstanceGroup_BidPrice(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfigCoreInstanceGroupBidPrice(rName, "0.51"), @@ -362,10 +383,14 @@ func TestAccAWSEMRCluster_CoreInstanceGroup_InstanceCount(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfigCoreInstanceGroupInstanceCount(rName, 1), @@ -408,10 +433,14 @@ func TestAccAWSEMRCluster_CoreInstanceGroup_InstanceType(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfigCoreInstanceGroupInstanceType(rName, "m4.xlarge"), @@ -426,78 +455,6 @@ func TestAccAWSEMRCluster_CoreInstanceGroup_InstanceType(t *testing.T) { }) } -func TestAccAWSEMRCluster_CoreInstanceGroup_Migration_CoreInstanceType(t *testing.T) { - var cluster1, cluster2 emr.Cluster - rName := acctest.RandomWithPrefix("tf-acc-test") - resourceName := "aws_emr_cluster.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEmrDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSEmrClusterConfigCoreInstanceType(rName, "m4.large"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster1), - resource.TestCheckResourceAttr(resourceName, "core_instance_type", "m4.large"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, - }, - { - Config: testAccAWSEmrClusterConfigCoreInstanceGroupInstanceType(rName, "m4.large"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster2), - testAccCheckAWSEmrClusterNotRecreated(&cluster1, &cluster2), - resource.TestCheckResourceAttr(resourceName, "core_instance_group.#", "1"), - resource.TestCheckResourceAttr(resourceName, "core_instance_group.0.instance_type", "m4.large"), - ), - }, - }, - }) -} - -func TestAccAWSEMRCluster_CoreInstanceGroup_Migration_InstanceGroup(t *testing.T) { - var cluster1, cluster2 emr.Cluster - rName := acctest.RandomWithPrefix("tf-acc-test") - resourceName := "aws_emr_cluster.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEmrDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSEmrClusterConfigInstanceGroupCoreInstanceType(rName, "m4.large"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster1), - resource.TestCheckResourceAttr(resourceName, "instance_group.#", "2"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, - }, - { - Config: testAccAWSEmrClusterConfigCoreInstanceGroupInstanceType(rName, "m4.large"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster2), - testAccCheckAWSEmrClusterNotRecreated(&cluster1, &cluster2), - resource.TestCheckResourceAttr(resourceName, "core_instance_group.#", "1"), - resource.TestCheckResourceAttr(resourceName, "core_instance_group.0.instance_type", "m4.large"), - ), - }, - }, - }) -} - func TestAccAWSEMRCluster_CoreInstanceGroup_Name(t *testing.T) { var cluster1, cluster2 emr.Cluster rName := acctest.RandomWithPrefix("tf-acc-test") @@ -517,10 +474,14 @@ func TestAccAWSEMRCluster_CoreInstanceGroup_Name(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfigCoreInstanceGroupName(rName, "name2"), @@ -535,153 +496,6 @@ func TestAccAWSEMRCluster_CoreInstanceGroup_Name(t *testing.T) { }) } -func TestAccAWSEMRCluster_instance_group(t *testing.T) { - var cluster emr.Cluster - - resourceName := "aws_emr_cluster.tf-test-cluster" - rName := acctest.RandomWithPrefix("tf-acc-test") - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEmrDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSEmrClusterConfigInstanceGroups(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster), - resource.TestCheckResourceAttr(resourceName, "instance_group.#", "2"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, - }, - }, - }) -} - -func TestAccAWSEMRCluster_instance_group_names(t *testing.T) { - var cluster emr.Cluster - - resourceName := "aws_emr_cluster.tf-test-cluster" - rName := acctest.RandomWithPrefix("tf-acc-test") - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEmrDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSEmrClusterConfigInstanceGroupsName(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster), - resource.TestCheckResourceAttr(resourceName, "instance_group.#", "3"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, - }, - }, - }) -} - -func TestAccAWSEMRCluster_instance_group_update(t *testing.T) { - var cluster emr.Cluster - - resourceName := "aws_emr_cluster.tf-test-cluster" - rName := acctest.RandomWithPrefix("tf-acc-test") - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEmrDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSEmrClusterConfigInstanceGroups(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster), - resource.TestCheckResourceAttr(resourceName, "instance_group.#", "2"), - ), - }, - { - Config: testAccAWSEmrClusterConfigInstanceGroupsUpdate(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster), - resource.TestCheckResourceAttr(resourceName, "instance_group.#", "2"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, - }, - }, - }) -} - -func TestAccAWSEMRCluster_instance_group_EBSVolumeType_st1(t *testing.T) { - var cluster emr.Cluster - - resourceName := "aws_emr_cluster.tf-test-cluster" - rName := acctest.RandomWithPrefix("tf-acc-test") - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEmrDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSEmrClusterConfigInstanceGroups_st1(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster), - resource.TestCheckResourceAttr(resourceName, "instance_group.#", "2"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, - }, - }, - }) -} - -func TestAccAWSEMRCluster_updateAutoScalingPolicy(t *testing.T) { - var cluster emr.Cluster - - resourceName := "aws_emr_cluster.tf-test-cluster" - rName := acctest.RandomWithPrefix("tf-acc-test") - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEmrDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSEmrClusterConfigInstanceGroups_st1(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster), - ), - }, - { - Config: testAccAWSEmrClusterConfigInstanceGroups_updateAutoScalingPolicy(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, - }, - }, - }) -} - func TestAccAWSEMRCluster_Ec2Attributes_DefaultManagedSecurityGroups(t *testing.T) { var cluster emr.Cluster var vpc ec2.Vpc @@ -745,10 +559,15 @@ func TestAccAWSEMRCluster_Kerberos_ClusterDedicatedKdc(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps", "kerberos_attributes.0.kdc_admin_password"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + "kerberos_attributes.0.kdc_admin_password", + }, }, }, }) @@ -773,10 +592,14 @@ func TestAccAWSEMRCluster_MasterInstanceGroup_BidPrice(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfigMasterInstanceGroupBidPrice(rName, "0.51"), @@ -810,10 +633,14 @@ func TestAccAWSEMRCluster_MasterInstanceGroup_InstanceCount(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfigMasterInstanceGroupInstanceCount(rName, 1), @@ -847,10 +674,14 @@ func TestAccAWSEMRCluster_MasterInstanceGroup_InstanceType(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfigMasterInstanceGroupInstanceType(rName, "m4.xlarge"), @@ -865,78 +696,6 @@ func TestAccAWSEMRCluster_MasterInstanceGroup_InstanceType(t *testing.T) { }) } -func TestAccAWSEMRCluster_MasterInstanceGroup_Migration_InstanceGroup(t *testing.T) { - var cluster1, cluster2 emr.Cluster - rName := acctest.RandomWithPrefix("tf-acc-test") - resourceName := "aws_emr_cluster.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEmrDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSEmrClusterConfigInstanceGroupMasterInstanceType(rName, "m4.large"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster1), - resource.TestCheckResourceAttr(resourceName, "instance_group.#", "1"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, - }, - { - Config: testAccAWSEmrClusterConfigMasterInstanceGroupInstanceType(rName, "m4.large"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster2), - testAccCheckAWSEmrClusterNotRecreated(&cluster1, &cluster2), - resource.TestCheckResourceAttr(resourceName, "master_instance_group.#", "1"), - resource.TestCheckResourceAttr(resourceName, "master_instance_group.0.instance_type", "m4.large"), - ), - }, - }, - }) -} - -func TestAccAWSEMRCluster_MasterInstanceGroup_Migration_MasterInstanceType(t *testing.T) { - var cluster1, cluster2 emr.Cluster - rName := acctest.RandomWithPrefix("tf-acc-test") - resourceName := "aws_emr_cluster.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSEmrDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSEmrClusterConfigMasterInstanceType(rName, "m4.large"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster1), - resource.TestCheckResourceAttr(resourceName, "master_instance_type", "m4.large"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, - }, - { - Config: testAccAWSEmrClusterConfigMasterInstanceGroupInstanceType(rName, "m4.large"), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSEmrClusterExists(resourceName, &cluster2), - testAccCheckAWSEmrClusterNotRecreated(&cluster1, &cluster2), - resource.TestCheckResourceAttr(resourceName, "master_instance_group.#", "1"), - resource.TestCheckResourceAttr(resourceName, "master_instance_group.0.instance_type", "m4.large"), - ), - }, - }, - }) -} - func TestAccAWSEMRCluster_MasterInstanceGroup_Name(t *testing.T) { var cluster1, cluster2 emr.Cluster rName := acctest.RandomWithPrefix("tf-acc-test") @@ -956,10 +715,14 @@ func TestAccAWSEMRCluster_MasterInstanceGroup_Name(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfigMasterInstanceGroupName(rName, "name2"), @@ -992,10 +755,14 @@ func TestAccAWSEMRCluster_security_config(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1025,10 +792,14 @@ func TestAccAWSEMRCluster_Step_Basic(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1052,10 +823,14 @@ func TestAccAWSEMRCluster_Step_ConfigMode(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"cluster_state", "configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfig_Step_NoBlocks(rName), @@ -1065,10 +840,14 @@ func TestAccAWSEMRCluster_Step_ConfigMode(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"cluster_state", "configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfig_Step_Zeroed(rName), @@ -1078,10 +857,14 @@ func TestAccAWSEMRCluster_Step_ConfigMode(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"cluster_state", "configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1115,10 +898,14 @@ func TestAccAWSEMRCluster_Step_Multiple(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1150,10 +937,14 @@ func TestAccAWSEMRCluster_bootstrap_ordering(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfig_bootstrapAdd(rName), @@ -1176,10 +967,14 @@ func TestAccAWSEMRCluster_bootstrap_ordering(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfig_bootstrapReorder(rName), @@ -1202,10 +997,14 @@ func TestAccAWSEMRCluster_bootstrap_ordering(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1236,10 +1035,14 @@ func TestAccAWSEMRCluster_terminationProtected(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { //Need to turn off termination_protection to allow the job to be deleted @@ -1250,10 +1053,14 @@ func TestAccAWSEMRCluster_terminationProtected(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1277,10 +1084,14 @@ func TestAccAWSEMRCluster_keepJob(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1304,10 +1115,14 @@ func TestAccAWSEMRCluster_visibleToAllUsers(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, { Config: testAccAWSEmrClusterConfigVisibleToAllUsersUpdated(rName), @@ -1317,10 +1132,14 @@ func TestAccAWSEMRCluster_visibleToAllUsers(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1345,10 +1164,14 @@ func TestAccAWSEMRCluster_s3Logging(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1385,10 +1208,14 @@ func TestAccAWSEMRCluster_tags(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1419,10 +1246,14 @@ func TestAccAWSEMRCluster_root_volume_size(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1452,10 +1283,14 @@ func TestAccAWSEMRCluster_step_concurrency_level(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1479,10 +1314,14 @@ func TestAccAWSEMRCluster_custom_ami_id(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"configurations", "keep_job_flow_alive_when_no_steps"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "cluster_state", // Ignore RUNNING versus WAITING changes + "configurations", + "keep_job_flow_alive_when_no_steps", + }, }, }, }) @@ -1741,22 +1580,28 @@ resource "aws_emr_cluster" "test" { release_label = "emr-5.0.0" applications = ["Hadoop", "Hive"] log_uri = "s3n://terraform/testlog/" - master_instance_type = "c4.large" - core_instance_type = "c4.large" - core_instance_count = 1 - service_role = "${aws_iam_role.emr_service.arn}" + master_instance_group { + instance_type = "c4.large" + } + + core_instance_group { + instance_count = 1 + instance_type = "c4.large" + } + + service_role = aws_iam_role.emr_service.arn depends_on = [ - "aws_route_table_association.test", - "aws_iam_role_policy_attachment.emr_service", - "aws_iam_role_policy_attachment.emr_instance_profile", + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, ] ec2_attributes { - subnet_id = "${aws_subnet.test.id}" - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" - instance_profile = "${aws_iam_instance_profile.emr_instance_profile.arn}" + subnet_id = aws_subnet.test.id + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn } bootstrap_action { @@ -1797,22 +1642,28 @@ resource "aws_emr_cluster" "test" { release_label = "emr-5.0.0" applications = ["Hadoop", "Hive"] log_uri = "s3n://terraform/testlog/" - master_instance_type = "c4.large" - core_instance_type = "c4.large" - core_instance_count = 1 - service_role = "${aws_iam_role.emr_service.arn}" + master_instance_group { + instance_type = "c4.large" + } + + core_instance_group { + instance_count = 1 + instance_type = "c4.large" + } + + service_role = aws_iam_role.emr_service.arn depends_on = [ - "aws_route_table_association.test", - "aws_iam_role_policy_attachment.emr_service", - "aws_iam_role_policy_attachment.emr_instance_profile", + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, ] ec2_attributes { - subnet_id = "${aws_subnet.test.id}" - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" - instance_profile = "${aws_iam_instance_profile.emr_instance_profile.arn}" + subnet_id = aws_subnet.test.id + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn } bootstrap_action { @@ -1820,6 +1671,7 @@ resource "aws_emr_cluster" "test" { name = "runif" args = ["instance.isMaster=true", "echo running on master node"] } + bootstrap_action { path = "s3://${aws_s3_bucket_object.testobject.bucket}/${aws_s3_bucket_object.testobject.key}" name = "test" @@ -1836,6 +1688,7 @@ resource "aws_emr_cluster" "test" { "10", ] } + bootstrap_action { path = "s3://elasticmapreduce/bootstrap-actions/run-if" name = "runif-2" @@ -1857,22 +1710,28 @@ resource "aws_emr_cluster" "test" { release_label = "emr-5.0.0" applications = ["Hadoop", "Hive"] log_uri = "s3n://terraform/testlog/" - master_instance_type = "c4.large" - core_instance_type = "c4.large" - core_instance_count = 1 - service_role = "${aws_iam_role.emr_service.arn}" + master_instance_group { + instance_type = "c4.large" + } + + core_instance_group { + instance_count = 1 + instance_type = "c4.large" + } + + service_role = aws_iam_role.emr_service.arn depends_on = [ - "aws_route_table_association.test", - "aws_iam_role_policy_attachment.emr_service", - "aws_iam_role_policy_attachment.emr_instance_profile", + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, ] ec2_attributes { - subnet_id = "${aws_subnet.test.id}" - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" - instance_profile = "${aws_iam_instance_profile.emr_instance_profile.arn}" + subnet_id = aws_subnet.test.id + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn } bootstrap_action { @@ -1920,15 +1779,20 @@ resource "aws_emr_cluster" "tf-test-cluster" { applications = ["Spark"] ec2_attributes { - subnet_id = "${aws_subnet.test.id}" - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" - instance_profile = "${aws_iam_instance_profile.emr_instance_profile.arn}" + subnet_id = aws_subnet.test.id + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn } - master_instance_type = "c4.large" - core_instance_type = "c4.large" - core_instance_count = 1 + master_instance_group { + instance_type = "c4.large" + } + + core_instance_group { + instance_count = 1 + instance_type = "c4.large" + } tags = { role = "rolename" @@ -1945,14 +1809,14 @@ resource "aws_emr_cluster" "tf-test-cluster" { configurations = "test-fixtures/emr_configurations.json" depends_on = [ - "aws_route_table_association.test", - "aws_iam_role_policy_attachment.emr_service", - "aws_iam_role_policy_attachment.emr_instance_profile", - "aws_iam_role_policy_attachment.emr_autoscaling_role", + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, + aws_iam_role_policy_attachment.emr_autoscaling_role, ] - service_role = "${aws_iam_role.emr_service.arn}" - autoscaling_role = "${aws_iam_role.emr_autoscaling_role.arn}" + service_role = aws_iam_role.emr_service.arn + autoscaling_role = aws_iam_role.emr_autoscaling_role.arn ebs_root_volume_size = 21 } `, r), @@ -1980,15 +1844,20 @@ resource "aws_emr_cluster" "tf-test-cluster" { EOF ec2_attributes { - subnet_id = "${aws_subnet.test.id}" - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" - instance_profile = "${aws_iam_instance_profile.emr_instance_profile.arn}" + subnet_id = aws_subnet.test.id + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn + } + + master_instance_group { + instance_type = "c4.large" } - master_instance_type = "c4.large" - core_instance_type = "c4.large" - core_instance_count = 1 + core_instance_group { + instance_count = 1 + instance_type = "c4.large" + } tags = { role = "rolename" @@ -2005,14 +1874,14 @@ EOF configurations = "test-fixtures/emr_configurations.json" depends_on = [ - "aws_route_table_association.test", - "aws_iam_role_policy_attachment.emr_service", - "aws_iam_role_policy_attachment.emr_instance_profile", - "aws_iam_role_policy_attachment.emr_autoscaling_role", + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, + aws_iam_role_policy_attachment.emr_autoscaling_role, ] - service_role = "${aws_iam_role.emr_service.arn}" - autoscaling_role = "${aws_iam_role.emr_autoscaling_role.arn}" + service_role = aws_iam_role.emr_service.arn + autoscaling_role = aws_iam_role.emr_autoscaling_role.arn ebs_root_volume_size = 21 } `, r), @@ -2030,15 +1899,20 @@ resource "aws_emr_cluster" "tf-test-cluster" { applications = ["Hadoop", "Spark"] ec2_attributes { - subnet_id = "${aws_subnet.test.id}" - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" - instance_profile = "${aws_iam_instance_profile.emr_instance_profile.arn}" + subnet_id = aws_subnet.test.id + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn + } + + master_instance_group { + instance_type = "c4.large" } - master_instance_type = "c4.large" - core_instance_type = "c4.large" - core_instance_count = 1 + core_instance_group { + instance_count = 1 + instance_type = "c4.large" + } keep_job_flow_alive_when_no_steps = true termination_protection = false @@ -2073,12 +1947,12 @@ resource "aws_emr_cluster" "tf-test-cluster" { EOF depends_on = [ - "aws_route_table_association.test", - "aws_iam_role_policy_attachment.emr_service", - "aws_iam_role_policy_attachment.emr_instance_profile", + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, ] - service_role = "${aws_iam_role.emr_service.arn}" + service_role = aws_iam_role.emr_service.arn ebs_root_volume_size = 21 } `, r), @@ -2104,21 +1978,27 @@ EOF resource "aws_emr_cluster" "tf-test-cluster" { applications = ["Spark"] - core_instance_count = 1 - core_instance_type = "c4.large" keep_job_flow_alive_when_no_steps = true - master_instance_type = "c4.large" name = "%[1]s" release_label = "emr-5.12.0" - security_configuration = "${aws_emr_security_configuration.foo.name}" + security_configuration = aws_emr_security_configuration.foo.name service_role = "EMR_DefaultRole" termination_protection = false + master_instance_group { + instance_type = "c4.large" + } + + core_instance_group { + instance_count = 1 + instance_type = "c4.large" + } + ec2_attributes { - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id instance_profile = "EMR_EC2_DefaultRole" - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } kerberos_attributes { @@ -2126,7 +2006,7 @@ resource "aws_emr_cluster" "tf-test-cluster" { realm = "EC2.INTERNAL" } - depends_on = ["aws_route_table_association.test"] + depends_on = [aws_route_table_association.test] } `, r, password)) } @@ -2143,17 +2023,22 @@ resource "aws_emr_cluster" "tf-test-cluster" { applications = ["Spark"] ec2_attributes { - subnet_id = "${aws_subnet.test.id}" - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" - instance_profile = "${aws_iam_instance_profile.emr_instance_profile.arn}" + subnet_id = aws_subnet.test.id + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn + } + + master_instance_group { + instance_type = "c4.large" } - master_instance_type = "c4.large" - core_instance_type = "c4.large" - core_instance_count = 1 + core_instance_group { + instance_count = 1 + instance_type = "c4.large" + } - security_configuration = "${aws_emr_security_configuration.foo.name}" + security_configuration = aws_emr_security_configuration.foo.name tags = { role = "rolename" @@ -2168,14 +2053,14 @@ resource "aws_emr_cluster" "tf-test-cluster" { configurations = "test-fixtures/emr_configurations.json" depends_on = [ - "aws_route_table_association.test", - "aws_iam_role_policy_attachment.emr_service", - "aws_iam_role_policy_attachment.emr_instance_profile", - "aws_iam_role_policy_attachment.emr_autoscaling_role", + aws_route_table_association.test, + aws_iam_role_policy_attachment.emr_service, + aws_iam_role_policy_attachment.emr_instance_profile, + aws_iam_role_policy_attachment.emr_autoscaling_role, ] - service_role = "${aws_iam_role.emr_service.arn}" - autoscaling_role = "${aws_iam_role.emr_autoscaling_role.arn}" + service_role = aws_iam_role.emr_service.arn + autoscaling_role = aws_iam_role.emr_autoscaling_role.arn } resource "aws_emr_security_configuration" "foo" { @@ -2270,26 +2155,32 @@ func testAccAWSEmrClusterConfig_Step(r string, stepConfig string) string { return testAccAWSEmrComposeConfig(false, fmt.Sprintf(` resource "aws_emr_cluster" "tf-test-cluster" { applications = ["Spark"] - core_instance_count = 1 - core_instance_type = "c4.large" keep_job_flow_alive_when_no_steps = true log_uri = "s3://${aws_s3_bucket.test.bucket}/" - master_instance_type = "c4.large" name = "%[1]s" release_label = "emr-5.12.0" service_role = "EMR_DefaultRole" termination_protection = false + master_instance_group { + instance_type = "c4.large" + } + + core_instance_group { + instance_count = 1 + instance_type = "c4.large" + } + ec2_attributes { - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id instance_profile = "EMR_EC2_DefaultRole" - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } %[2]s - depends_on = ["aws_route_table_association.test"] + depends_on = [aws_route_table_association.test] } resource "aws_s3_bucket" "test" { @@ -2320,27 +2211,27 @@ data "aws_partition" "current" {} resource "aws_iam_role" "test" { name = %[1]q - assume_role_policy = "${data.aws_iam_policy_document.test.json}" + assume_role_policy = data.aws_iam_policy_document.test.json } resource "aws_iam_role_policy_attachment" "test" { - role = "${aws_iam_role.test.name}" + role = aws_iam_role.test.name policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AmazonElasticMapReduceforAutoScalingRole" } resource "aws_emr_cluster" "test" { applications = ["Spark"] - autoscaling_role = "${aws_iam_role.test.arn}" + autoscaling_role = aws_iam_role.test.arn keep_job_flow_alive_when_no_steps = true name = %[1]q release_label = "emr-5.12.0" service_role = "EMR_DefaultRole" ec2_attributes { - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id instance_profile = "EMR_EC2_DefaultRole" - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } master_instance_group { @@ -2355,8 +2246,8 @@ POLICY } depends_on = [ - "aws_route_table_association.test", - "aws_iam_role_policy_attachment.test", + aws_route_table_association.test, + aws_iam_role_policy_attachment.test, ] } `, rName, autoscalingPolicy), @@ -2384,27 +2275,27 @@ data "aws_partition" "current" {} resource "aws_iam_role" "test" { name = %[1]q - assume_role_policy = "${data.aws_iam_policy_document.test.json}" + assume_role_policy = data.aws_iam_policy_document.test.json } resource "aws_iam_role_policy_attachment" "test" { - role = "${aws_iam_role.test.name}" + role = aws_iam_role.test.name policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AmazonElasticMapReduceforAutoScalingRole" } resource "aws_emr_cluster" "test" { applications = ["Spark"] - autoscaling_role = "${aws_iam_role.test.arn}" + autoscaling_role = aws_iam_role.test.arn keep_job_flow_alive_when_no_steps = true name = %[1]q release_label = "emr-5.12.0" service_role = "EMR_DefaultRole" ec2_attributes { - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id instance_profile = "EMR_EC2_DefaultRole" - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } master_instance_group { @@ -2416,8 +2307,8 @@ resource "aws_emr_cluster" "test" { } depends_on = [ - "aws_route_table_association.test", - "aws_iam_role_policy_attachment.test", + aws_route_table_association.test, + aws_iam_role_policy_attachment.test, ] } `, rName), @@ -2434,10 +2325,10 @@ resource "aws_emr_cluster" "test" { service_role = "EMR_DefaultRole" ec2_attributes { - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id instance_profile = "EMR_EC2_DefaultRole" - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } master_instance_group { @@ -2449,7 +2340,7 @@ resource "aws_emr_cluster" "test" { instance_type = "m4.large" } - depends_on = ["aws_route_table_association.test"] + depends_on = [aws_route_table_association.test] } `, rName, bidPrice), ) @@ -2465,10 +2356,10 @@ resource "aws_emr_cluster" "test" { service_role = "EMR_DefaultRole" ec2_attributes { - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id instance_profile = "EMR_EC2_DefaultRole" - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } master_instance_group { @@ -2480,7 +2371,7 @@ resource "aws_emr_cluster" "test" { instance_type = "m4.large" } - depends_on = ["aws_route_table_association.test"] + depends_on = [aws_route_table_association.test] } `, rName, instanceCount), ) @@ -2496,10 +2387,10 @@ resource "aws_emr_cluster" "test" { service_role = "EMR_DefaultRole" ec2_attributes { - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id instance_profile = "EMR_EC2_DefaultRole" - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } master_instance_group { @@ -2510,7 +2401,7 @@ resource "aws_emr_cluster" "test" { instance_type = %[2]q } - depends_on = ["aws_route_table_association.test"] + depends_on = [aws_route_table_association.test] } `, rName, instanceType), ) @@ -2526,10 +2417,10 @@ resource "aws_emr_cluster" "test" { service_role = "EMR_DefaultRole" ec2_attributes { - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id instance_profile = "EMR_EC2_DefaultRole" - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } master_instance_group { @@ -2541,75 +2432,99 @@ resource "aws_emr_cluster" "test" { name = %[2]q } - depends_on = ["aws_route_table_association.test"] + depends_on = [aws_route_table_association.test] } `, rName, instanceGroupName), ) } -func testAccAWSEmrClusterConfigCoreInstanceType(rName, coreInstanceType string) string { +func testAccAWSEmrClusterConfigEc2AttributesDefaultManagedSecurityGroups(rName string) string { + return testAccAWSEmrComposeConfig(false, fmt.Sprintf(` +resource "aws_emr_cluster" "tf-test-cluster" { + applications = ["Spark"] + keep_job_flow_alive_when_no_steps = true + name = %[1]q + release_label = "emr-5.28.0" + service_role = "EMR_DefaultRole" + + ec2_attributes { + instance_profile = "EMR_EC2_DefaultRole" + subnet_id = aws_subnet.test.id + } + + master_instance_group { + instance_type = "m4.large" + } + + depends_on = [aws_route_table_association.test] +} +`, rName), + ) +} + +func testAccAWSEmrClusterConfigMasterInstanceGroupBidPrice(rName, bidPrice string) string { return testAccAWSEmrComposeConfig(false, fmt.Sprintf(` resource "aws_emr_cluster" "test" { applications = ["Spark"] keep_job_flow_alive_when_no_steps = true - core_instance_count = 1 - core_instance_type = %[2]q name = %[1]q release_label = "emr-5.12.0" service_role = "EMR_DefaultRole" ec2_attributes { - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id instance_profile = "EMR_EC2_DefaultRole" - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } master_instance_group { + bid_price = %[2]q instance_type = "m4.large" } - depends_on = ["aws_route_table_association.test"] + depends_on = [aws_route_table_association.test] } -`, rName, coreInstanceType), +`, rName, bidPrice), ) } -func testAccAWSEmrClusterConfigInstanceGroupCoreInstanceType(rName, coreInstanceType string) string { - return testAccAWSEmrComposeConfig(false, fmt.Sprintf(` +func testAccAWSEmrClusterConfigMasterInstanceGroupInstanceCount(rName string, instanceCount int) string { + return testAccAWSEmrComposeConfig(true, fmt.Sprintf(` resource "aws_emr_cluster" "test" { applications = ["Spark"] keep_job_flow_alive_when_no_steps = true name = %[1]q - release_label = "emr-5.12.0" + release_label = "emr-5.24.1" service_role = "EMR_DefaultRole" + # Termination protection is automatically enabled for multiple master clusters + termination_protection = false + ec2_attributes { - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id instance_profile = "EMR_EC2_DefaultRole" - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } - instance_group { - instance_count = 1 - instance_role = "MASTER" + master_instance_group { + instance_count = %[2]d instance_type = "m4.large" } - instance_group { - instance_count = 1 - instance_role = "CORE" - instance_type = %[2]q + # core_instance_group is required with multiple masters + core_instance_group { + instance_type = "m4.large" } - depends_on = ["aws_route_table_association.test"] + depends_on = [aws_route_table_association.test] } -`, rName, coreInstanceType), +`, rName, instanceCount), ) } -func testAccAWSEmrClusterConfigInstanceGroupMasterInstanceType(rName, masterInstanceType string) string { +func testAccAWSEmrClusterConfigMasterInstanceGroupInstanceType(rName, instanceType string) string { return testAccAWSEmrComposeConfig(false, fmt.Sprintf(` resource "aws_emr_cluster" "test" { applications = ["Spark"] @@ -2619,25 +2534,50 @@ resource "aws_emr_cluster" "test" { service_role = "EMR_DefaultRole" ec2_attributes { - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id instance_profile = "EMR_EC2_DefaultRole" - subnet_id = "${aws_subnet.test.id}" + subnet_id = aws_subnet.test.id } - instance_group { - instance_count = 1 - instance_role = "MASTER" - instance_type = %[2]q + master_instance_group { + instance_type = %[2]q + } + + depends_on = [aws_route_table_association.test] +} +`, rName, instanceType), + ) +} + +func testAccAWSEmrClusterConfigMasterInstanceGroupName(rName, instanceGroupName string) string { + return testAccAWSEmrComposeConfig(false, fmt.Sprintf(` +resource "aws_emr_cluster" "test" { + applications = ["Spark"] + keep_job_flow_alive_when_no_steps = true + name = %[1]q + release_label = "emr-5.12.0" + service_role = "EMR_DefaultRole" + + ec2_attributes { + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id + instance_profile = "EMR_EC2_DefaultRole" + subnet_id = aws_subnet.test.id + } + + master_instance_group { + instance_type = "m4.large" + name = %[2]q } - depends_on = ["aws_route_table_association.test"] + depends_on = [aws_route_table_association.test] } -`, rName, masterInstanceType), +`, rName, instanceGroupName), ) } -func testAccAWSEmrClusterConfigInstanceGroups(r string) string { +func testAccAWSEmrClusterConfigTerminationPolicy(r string, term string) string { return testAccAWSEmrComposeConfig(false, testAccAWSEmrClusterConfigIAMServiceRoleBase(r), testAccAWSEmrClusterConfigIAMInstanceProfileBase(r), @@ -2649,64 +2589,19 @@ resource "aws_emr_cluster" "tf-test-cluster" { applications = ["Spark"] ec2_attributes { - subnet_id = "${aws_subnet.test.id}" - emr_managed_master_security_group = "${aws_security_group.test.id}" - emr_managed_slave_security_group = "${aws_security_group.test.id}" - instance_profile = "${aws_iam_instance_profile.emr_instance_profile.arn}" + subnet_id = aws_subnet.test.id + emr_managed_master_security_group = aws_security_group.test.id + emr_managed_slave_security_group = aws_security_group.test.id + instance_profile = aws_iam_instance_profile.emr_instance_profile.arn } - instance_group { - instance_role = "CORE" - instance_type = "c4.large" - instance_count = "1" - - ebs_config { - size = "40" - type = "gp2" - volumes_per_instance = 1 - } - - bid_price = "0.30" - - autoscaling_policy = < 0 { + input.Tags = keyvaluetags.New(v).IgnoreAws().GuarddutyTags() + } + log.Printf("[DEBUG] Creating GuardDuty Detector: %s", input) output, err := conn.CreateDetector(&input) if err != nil { @@ -66,6 +77,8 @@ func resourceAwsGuardDutyDetectorCreate(d *schema.ResourceData, meta interface{} func resourceAwsGuardDutyDetectorRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).guarddutyconn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + input := guardduty.GetDetectorInput{ DetectorId: aws.String(d.Id()), } @@ -81,26 +94,49 @@ func resourceAwsGuardDutyDetectorRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("Reading GuardDuty Detector '%s' failed: %s", d.Id(), err.Error()) } + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Region: meta.(*AWSClient).region, + Service: "guardduty", + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("detector/%s", d.Id()), + }.String() + d.Set("arn", arn) + d.Set("account_id", meta.(*AWSClient).accountid) d.Set("enable", *gdo.Status == guardduty.DetectorStatusEnabled) d.Set("finding_publishing_frequency", gdo.FindingPublishingFrequency) + if err := d.Set("tags", keyvaluetags.GuarddutyKeyValueTags(gdo.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) + } + return nil } func resourceAwsGuardDutyDetectorUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).guarddutyconn - input := guardduty.UpdateDetectorInput{ - DetectorId: aws.String(d.Id()), - Enable: aws.Bool(d.Get("enable").(bool)), - FindingPublishingFrequency: aws.String(d.Get("finding_publishing_frequency").(string)), + if d.HasChanges("enable", "finding_publishing_frequency") { + input := guardduty.UpdateDetectorInput{ + DetectorId: aws.String(d.Id()), + Enable: aws.Bool(d.Get("enable").(bool)), + FindingPublishingFrequency: aws.String(d.Get("finding_publishing_frequency").(string)), + } + + log.Printf("[DEBUG] Update GuardDuty Detector: %s", input) + _, err := conn.UpdateDetector(&input) + if err != nil { + return fmt.Errorf("Updating GuardDuty Detector '%s' failed: %s", d.Id(), err.Error()) + } } - log.Printf("[DEBUG] Update GuardDuty Detector: %s", input) - _, err := conn.UpdateDetector(&input) - if err != nil { - return fmt.Errorf("Updating GuardDuty Detector '%s' failed: %s", d.Id(), err.Error()) + if d.HasChange("tags") { + o, n := d.GetChange("tags") + + if err := keyvaluetags.GuarddutyUpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating GuardDuty Detector (%s) tags: %s", d.Get("arn").(string), err) + } } return resourceAwsGuardDutyDetectorRead(d, meta) diff --git a/aws/resource_aws_guardduty_detector_test.go b/aws/resource_aws_guardduty_detector_test.go index 4441d06426c..b94068a3080 100644 --- a/aws/resource_aws_guardduty_detector_test.go +++ b/aws/resource_aws_guardduty_detector_test.go @@ -3,13 +3,14 @@ package aws import ( "fmt" "log" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/guardduty" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -75,8 +76,10 @@ func testAccAwsGuardDutyDetector_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsGuardDutyDetectorExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "account_id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "guardduty", regexp.MustCompile("detector/.+$")), resource.TestCheckResourceAttr(resourceName, "enable", "true"), resource.TestCheckResourceAttr(resourceName, "finding_publishing_frequency", "SIX_HOURS"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { @@ -109,6 +112,48 @@ func testAccAwsGuardDutyDetector_basic(t *testing.T) { }) } +func testAccAwsGuardDutyDetector_tags(t *testing.T) { + resourceName := "aws_guardduty_detector.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsGuardDutyDetectorDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGuardDutyDetectorConfigTags1("key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsGuardDutyDetectorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccGuardDutyDetectorConfigTags2("key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsGuardDutyDetectorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccGuardDutyDetectorConfigTags1("key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsGuardDutyDetectorExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + func testAccCheckAwsGuardDutyDetectorDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).guarddutyconn @@ -163,3 +208,24 @@ const testAccGuardDutyDetectorConfig_basic4 = ` resource "aws_guardduty_detector" "test" { finding_publishing_frequency = "FIFTEEN_MINUTES" }` + +func testAccGuardDutyDetectorConfigTags1(tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_guardduty_detector" "test" { + tags = { + %[1]q = %[2]q + } +} +`, tagKey1, tagValue1) +} + +func testAccGuardDutyDetectorConfigTags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_guardduty_detector" "test" { + tags = { + %[1]q = %[2]q + %[3]q = %[4]q + } +} +`, tagKey1, tagValue1, tagKey2, tagValue2) +} diff --git a/aws/resource_aws_guardduty_invite_accepter.go b/aws/resource_aws_guardduty_invite_accepter.go index 896b542598c..97693281ded 100644 --- a/aws/resource_aws_guardduty_invite_accepter.go +++ b/aws/resource_aws_guardduty_invite_accepter.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsGuardDutyInviteAccepter() *schema.Resource { diff --git a/aws/resource_aws_guardduty_invite_accepter_test.go b/aws/resource_aws_guardduty_invite_accepter_test.go index b992d103e39..54d73f292c2 100644 --- a/aws/resource_aws_guardduty_invite_accepter_test.go +++ b/aws/resource_aws_guardduty_invite_accepter_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAwsGuardDutyInviteAccepter_basic(t *testing.T) { @@ -110,13 +110,13 @@ func testAccCheckAwsGuardDutyInviteAccepterExists(resourceName string) resource. func testAccAwsGuardDutyInviteAccepterConfig_basic(email string) string { return testAccAlternateAccountProviderConfig() + fmt.Sprintf(` resource "aws_guardduty_detector" "master" { - provider = "aws.alternate" + provider = "awsalternate" } resource "aws_guardduty_detector" "member" {} resource "aws_guardduty_member" "member" { - provider = "aws.alternate" + provider = "awsalternate" account_id = "${aws_guardduty_detector.member.account_id}" detector_id = "${aws_guardduty_detector.master.id}" diff --git a/aws/resource_aws_guardduty_ipset.go b/aws/resource_aws_guardduty_ipset.go index ea07fc37e53..a4f7e0e2277 100644 --- a/aws/resource_aws_guardduty_ipset.go +++ b/aws/resource_aws_guardduty_ipset.go @@ -7,10 +7,12 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) func resourceAwsGuardDutyIpset() *schema.Resource { @@ -25,6 +27,10 @@ func resourceAwsGuardDutyIpset() *schema.Resource { }, Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, "detector_id": { Type: schema.TypeString, Required: true, @@ -55,6 +61,7 @@ func resourceAwsGuardDutyIpset() *schema.Resource { Type: schema.TypeBool, Required: true, }, + "tags": tagsSchema(), }, } } @@ -71,6 +78,10 @@ func resourceAwsGuardDutyIpsetCreate(d *schema.ResourceData, meta interface{}) e Activate: aws.Bool(d.Get("activate").(bool)), } + if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { + input.Tags = keyvaluetags.New(v).IgnoreAws().GuarddutyTags() + } + resp, err := conn.CreateIPSet(input) if err != nil { return err @@ -95,6 +106,7 @@ func resourceAwsGuardDutyIpsetCreate(d *schema.ResourceData, meta interface{}) e func resourceAwsGuardDutyIpsetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).guarddutyconn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig ipSetId, detectorId, err := decodeGuardDutyIpsetID(d.Id()) if err != nil { @@ -115,11 +127,25 @@ func resourceAwsGuardDutyIpsetRead(d *schema.ResourceData, meta interface{}) err return err } + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Region: meta.(*AWSClient).region, + Service: "guardduty", + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("detector/%s/ipset/%s", detectorId, ipSetId), + }.String() + d.Set("arn", arn) + d.Set("detector_id", detectorId) d.Set("format", resp.Format) d.Set("location", resp.Location) d.Set("name", resp.Name) d.Set("activate", *resp.Status == guardduty.IpSetStatusActive) + + if err := d.Set("tags", keyvaluetags.GuarddutyKeyValueTags(resp.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) + } + return nil } @@ -130,24 +156,35 @@ func resourceAwsGuardDutyIpsetUpdate(d *schema.ResourceData, meta interface{}) e if err != nil { return err } - input := &guardduty.UpdateIPSetInput{ - DetectorId: aws.String(detectorId), - IpSetId: aws.String(ipSetId), - } - if d.HasChange("name") { - input.Name = aws.String(d.Get("name").(string)) - } - if d.HasChange("location") { - input.Location = aws.String(d.Get("location").(string)) - } - if d.HasChange("activate") { - input.Activate = aws.Bool(d.Get("activate").(bool)) + if d.HasChanges("activate", "location", "name") { + input := &guardduty.UpdateIPSetInput{ + DetectorId: aws.String(detectorId), + IpSetId: aws.String(ipSetId), + } + + if d.HasChange("name") { + input.Name = aws.String(d.Get("name").(string)) + } + if d.HasChange("location") { + input.Location = aws.String(d.Get("location").(string)) + } + if d.HasChange("activate") { + input.Activate = aws.Bool(d.Get("activate").(bool)) + } + + _, err = conn.UpdateIPSet(input) + if err != nil { + return err + } } - _, err = conn.UpdateIPSet(input) - if err != nil { - return err + if d.HasChange("tags") { + o, n := d.GetChange("tags") + + if err := keyvaluetags.GuarddutyUpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating GuardDuty IP Set (%s) tags: %s", d.Get("arn").(string), err) + } } return resourceAwsGuardDutyIpsetRead(d, meta) diff --git a/aws/resource_aws_guardduty_ipset_test.go b/aws/resource_aws_guardduty_ipset_test.go index 64650ae96d9..8839c1210b4 100644 --- a/aws/resource_aws_guardduty_ipset_test.go +++ b/aws/resource_aws_guardduty_ipset_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAwsGuardDutyIpset_basic(t *testing.T) { @@ -18,6 +18,8 @@ func testAccAwsGuardDutyIpset_basic(t *testing.T) { keyName2 := fmt.Sprintf("tf-%s", acctest.RandString(5)) ipsetName1 := fmt.Sprintf("tf-%s", acctest.RandString(5)) ipsetName2 := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resourceName := "aws_guardduty_ipset.test" + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -26,34 +28,35 @@ func testAccAwsGuardDutyIpset_basic(t *testing.T) { { Config: testAccGuardDutyIpsetConfig_basic(bucketName, keyName1, ipsetName1, true), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsGuardDutyIpsetExists("aws_guardduty_ipset.test"), - resource.TestCheckResourceAttr("aws_guardduty_ipset.test", "name", ipsetName1), - resource.TestCheckResourceAttr("aws_guardduty_ipset.test", "activate", "true"), - resource.TestMatchResourceAttr( - "aws_guardduty_ipset.test", "location", regexp.MustCompile(fmt.Sprintf("%s/%s$", bucketName, keyName1)), - ), + testAccCheckAwsGuardDutyIpsetExists(resourceName), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "guardduty", regexp.MustCompile("detector/.+/ipset/.+$")), + resource.TestCheckResourceAttr(resourceName, "name", ipsetName1), + resource.TestCheckResourceAttr(resourceName, "activate", "true"), + resource.TestMatchResourceAttr(resourceName, "location", regexp.MustCompile(fmt.Sprintf("%s/%s$", bucketName, keyName1))), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, { Config: testAccGuardDutyIpsetConfig_basic(bucketName, keyName2, ipsetName2, false), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsGuardDutyIpsetExists("aws_guardduty_ipset.test"), - resource.TestCheckResourceAttr("aws_guardduty_ipset.test", "name", ipsetName2), - resource.TestCheckResourceAttr("aws_guardduty_ipset.test", "activate", "false"), - resource.TestMatchResourceAttr( - "aws_guardduty_ipset.test", "location", regexp.MustCompile(fmt.Sprintf("%s/%s$", bucketName, keyName2)), - ), + testAccCheckAwsGuardDutyIpsetExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", ipsetName2), + resource.TestCheckResourceAttr(resourceName, "activate", "false"), + resource.TestMatchResourceAttr(resourceName, "location", regexp.MustCompile(fmt.Sprintf("%s/%s$", bucketName, keyName2))), ), }, }, }) } -func testAccAwsGuardDutyIpset_import(t *testing.T) { +func testAccAwsGuardDutyIpset_tags(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_guardduty_ipset.test" - bucketName := fmt.Sprintf("tf-test-%s", acctest.RandString(5)) - keyName := fmt.Sprintf("tf-%s", acctest.RandString(5)) - ipsetName := fmt.Sprintf("tf-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -61,14 +64,35 @@ func testAccAwsGuardDutyIpset_import(t *testing.T) { CheckDestroy: testAccCheckAwsGuardDutyIpsetDestroy, Steps: []resource.TestStep{ { - Config: testAccGuardDutyIpsetConfig_basic(bucketName, keyName, ipsetName, true), + Config: testAccGuardDutyIpsetConfigTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsGuardDutyIpsetExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), }, - { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, + { + Config: testAccGuardDutyIpsetConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsGuardDutyIpsetExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccGuardDutyIpsetConfigTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsGuardDutyIpsetExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, }, }) } @@ -133,7 +157,7 @@ func testAccCheckAwsGuardDutyIpsetExists(name string) resource.TestCheckFunc { func testAccGuardDutyIpsetConfig_basic(bucketName, keyName, ipsetName string, activate bool) string { return fmt.Sprintf(` -%s +resource "aws_guardduty_detector" "test" {} resource "aws_s3_bucket" "test" { acl = "private" @@ -155,5 +179,68 @@ resource "aws_guardduty_ipset" "test" { location = "https://s3.amazonaws.com/${aws_s3_bucket_object.test.bucket}/${aws_s3_bucket_object.test.key}" activate = %t } -`, testAccGuardDutyDetectorConfig_basic1, bucketName, keyName, ipsetName, activate) +`, bucketName, keyName, ipsetName, activate) +} + +func testAccGuardDutyIpsetConfigTags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_guardduty_detector" "test" {} + +resource "aws_s3_bucket" "test" { + acl = "private" + bucket = %[1]q + force_destroy = true +} + +resource "aws_s3_bucket_object" "test" { + acl = "public-read" + content = "10.0.0.0/8\n" + bucket = aws_s3_bucket.test.id + key = %[1]q +} + +resource "aws_guardduty_ipset" "test" { + activate = true + detector_id = aws_guardduty_detector.test.id + format = "TXT" + location = "https://s3.amazonaws.com/${aws_s3_bucket_object.test.bucket}/${aws_s3_bucket_object.test.key}" + name = %[1]q + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccGuardDutyIpsetConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_guardduty_detector" "test" {} + +resource "aws_s3_bucket" "test" { + acl = "private" + bucket = %[1]q + force_destroy = true +} + +resource "aws_s3_bucket_object" "test" { + acl = "public-read" + content = "10.0.0.0/8\n" + bucket = aws_s3_bucket.test.id + key = %[1]q +} + +resource "aws_guardduty_ipset" "test" { + activate = true + detector_id = aws_guardduty_detector.test.id + format = "TXT" + location = "https://s3.amazonaws.com/${aws_s3_bucket_object.test.bucket}/${aws_s3_bucket_object.test.key}" + name = %[1]q + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) } diff --git a/aws/resource_aws_guardduty_member.go b/aws/resource_aws_guardduty_member.go index 3004f8d6cab..136d543a935 100644 --- a/aws/resource_aws_guardduty_member.go +++ b/aws/resource_aws_guardduty_member.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsGuardDutyMember() *schema.Resource { diff --git a/aws/resource_aws_guardduty_member_test.go b/aws/resource_aws_guardduty_member_test.go index 531bc66e176..6e7f2a56f8a 100644 --- a/aws/resource_aws_guardduty_member_test.go +++ b/aws/resource_aws_guardduty_member_test.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAwsGuardDutyMember_basic(t *testing.T) { diff --git a/aws/resource_aws_guardduty_organization_admin_account.go b/aws/resource_aws_guardduty_organization_admin_account.go index cb2f308a703..96031224f94 100644 --- a/aws/resource_aws_guardduty_organization_admin_account.go +++ b/aws/resource_aws_guardduty_organization_admin_account.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/guardduty/waiter" ) diff --git a/aws/resource_aws_guardduty_organization_admin_account_test.go b/aws/resource_aws_guardduty_organization_admin_account_test.go index ab35c8a65bc..c84baad899a 100644 --- a/aws/resource_aws_guardduty_organization_admin_account_test.go +++ b/aws/resource_aws_guardduty_organization_admin_account_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAwsGuardDutyOrganizationAdminAccount_basic(t *testing.T) { diff --git a/aws/resource_aws_guardduty_organization_configuration.go b/aws/resource_aws_guardduty_organization_configuration.go index 33c9fea2818..2a1857bb230 100644 --- a/aws/resource_aws_guardduty_organization_configuration.go +++ b/aws/resource_aws_guardduty_organization_configuration.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsGuardDutyOrganizationConfiguration() *schema.Resource { diff --git a/aws/resource_aws_guardduty_organization_configuration_test.go b/aws/resource_aws_guardduty_organization_configuration_test.go index 01a7f153bb1..7efdefc5176 100644 --- a/aws/resource_aws_guardduty_organization_configuration_test.go +++ b/aws/resource_aws_guardduty_organization_configuration_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func testAccAwsGuardDutyOrganizationConfiguration_basic(t *testing.T) { diff --git a/aws/resource_aws_guardduty_test.go b/aws/resource_aws_guardduty_test.go index 17dec84814c..2c507424505 100644 --- a/aws/resource_aws_guardduty_test.go +++ b/aws/resource_aws_guardduty_test.go @@ -5,10 +5,11 @@ import ( "testing" ) -func TestAccAWSGuardDuty(t *testing.T) { +func TestAccAWSGuardDuty_serial(t *testing.T) { testCases := map[string]map[string]func(t *testing.T){ "Detector": { "basic": testAccAwsGuardDutyDetector_basic, + "tags": testAccAwsGuardDutyDetector_tags, "datasource_basic": testAccAWSGuarddutyDetectorDataSource_basic, "datasource_id": testAccAWSGuarddutyDetectorDataSource_Id, }, @@ -16,8 +17,8 @@ func TestAccAWSGuardDuty(t *testing.T) { "basic": testAccAwsGuardDutyInviteAccepter_basic, }, "IPSet": { - "basic": testAccAwsGuardDutyIpset_basic, - "import": testAccAwsGuardDutyIpset_import, + "basic": testAccAwsGuardDutyIpset_basic, + "tags": testAccAwsGuardDutyIpset_tags, }, "OrganizationAdminAccount": { "basic": testAccAwsGuardDutyOrganizationAdminAccount_basic, @@ -26,8 +27,8 @@ func TestAccAWSGuardDuty(t *testing.T) { "basic": testAccAwsGuardDutyOrganizationConfiguration_basic, }, "ThreatIntelSet": { - "basic": testAccAwsGuardDutyThreatintelset_basic, - "import": testAccAwsGuardDutyThreatintelset_import, + "basic": testAccAwsGuardDutyThreatintelset_basic, + "tags": testAccAwsGuardDutyThreatintelset_tags, }, "Member": { "basic": testAccAwsGuardDutyMember_basic, diff --git a/aws/resource_aws_guardduty_threatintelset.go b/aws/resource_aws_guardduty_threatintelset.go index ad2d26499eb..b8f5dfde4b5 100644 --- a/aws/resource_aws_guardduty_threatintelset.go +++ b/aws/resource_aws_guardduty_threatintelset.go @@ -7,10 +7,12 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) func resourceAwsGuardDutyThreatintelset() *schema.Resource { @@ -25,6 +27,10 @@ func resourceAwsGuardDutyThreatintelset() *schema.Resource { }, Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, "detector_id": { Type: schema.TypeString, Required: true, @@ -55,6 +61,7 @@ func resourceAwsGuardDutyThreatintelset() *schema.Resource { Type: schema.TypeBool, Required: true, }, + "tags": tagsSchema(), }, } } @@ -71,6 +78,10 @@ func resourceAwsGuardDutyThreatintelsetCreate(d *schema.ResourceData, meta inter Activate: aws.Bool(d.Get("activate").(bool)), } + if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { + input.Tags = keyvaluetags.New(v).IgnoreAws().GuarddutyTags() + } + resp, err := conn.CreateThreatIntelSet(input) if err != nil { return err @@ -96,6 +107,7 @@ func resourceAwsGuardDutyThreatintelsetCreate(d *schema.ResourceData, meta inter func resourceAwsGuardDutyThreatintelsetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).guarddutyconn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig threatIntelSetId, detectorId, err := decodeGuardDutyThreatintelsetID(d.Id()) if err != nil { @@ -116,11 +128,25 @@ func resourceAwsGuardDutyThreatintelsetRead(d *schema.ResourceData, meta interfa return err } + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Region: meta.(*AWSClient).region, + Service: "guardduty", + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("detector/%s/threatintelset/%s", detectorId, threatIntelSetId), + }.String() + d.Set("arn", arn) + d.Set("detector_id", detectorId) d.Set("format", resp.Format) d.Set("location", resp.Location) d.Set("name", resp.Name) d.Set("activate", *resp.Status == guardduty.ThreatIntelSetStatusActive) + + if err := d.Set("tags", keyvaluetags.GuarddutyKeyValueTags(resp.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) + } + return nil } @@ -131,24 +157,35 @@ func resourceAwsGuardDutyThreatintelsetUpdate(d *schema.ResourceData, meta inter if err != nil { return err } - input := &guardduty.UpdateThreatIntelSetInput{ - DetectorId: aws.String(detectorId), - ThreatIntelSetId: aws.String(threatIntelSetID), - } - if d.HasChange("name") { - input.Name = aws.String(d.Get("name").(string)) - } - if d.HasChange("location") { - input.Location = aws.String(d.Get("location").(string)) - } - if d.HasChange("activate") { - input.Activate = aws.Bool(d.Get("activate").(bool)) + if d.HasChanges("activate", "location", "name") { + input := &guardduty.UpdateThreatIntelSetInput{ + DetectorId: aws.String(detectorId), + ThreatIntelSetId: aws.String(threatIntelSetID), + } + + if d.HasChange("name") { + input.Name = aws.String(d.Get("name").(string)) + } + if d.HasChange("location") { + input.Location = aws.String(d.Get("location").(string)) + } + if d.HasChange("activate") { + input.Activate = aws.Bool(d.Get("activate").(bool)) + } + + _, err = conn.UpdateThreatIntelSet(input) + if err != nil { + return err + } } - _, err = conn.UpdateThreatIntelSet(input) - if err != nil { - return err + if d.HasChange("tags") { + o, n := d.GetChange("tags") + + if err := keyvaluetags.GuarddutyUpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating GuardDuty Threat Intel Set (%s) tags: %s", d.Get("arn").(string), err) + } } return resourceAwsGuardDutyThreatintelsetRead(d, meta) diff --git a/aws/resource_aws_guardduty_threatintelset_test.go b/aws/resource_aws_guardduty_threatintelset_test.go index 53ad5b6d95e..7b6c0e8b466 100644 --- a/aws/resource_aws_guardduty_threatintelset_test.go +++ b/aws/resource_aws_guardduty_threatintelset_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/guardduty" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAwsGuardDutyThreatintelset_basic(t *testing.T) { @@ -18,6 +18,8 @@ func testAccAwsGuardDutyThreatintelset_basic(t *testing.T) { keyName2 := fmt.Sprintf("tf-%s", acctest.RandString(5)) threatintelsetName1 := fmt.Sprintf("tf-%s", acctest.RandString(5)) threatintelsetName2 := fmt.Sprintf("tf-%s", acctest.RandString(5)) + resourceName := "aws_guardduty_threatintelset.test" + resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -26,34 +28,35 @@ func testAccAwsGuardDutyThreatintelset_basic(t *testing.T) { { Config: testAccGuardDutyThreatintelsetConfig_basic(bucketName, keyName1, threatintelsetName1, true), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsGuardDutyThreatintelsetExists("aws_guardduty_threatintelset.test"), - resource.TestCheckResourceAttr("aws_guardduty_threatintelset.test", "name", threatintelsetName1), - resource.TestCheckResourceAttr("aws_guardduty_threatintelset.test", "activate", "true"), - resource.TestMatchResourceAttr( - "aws_guardduty_threatintelset.test", "location", regexp.MustCompile(fmt.Sprintf("%s/%s$", bucketName, keyName1)), - ), + testAccCheckAwsGuardDutyThreatintelsetExists(resourceName), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "guardduty", regexp.MustCompile("detector/.+/threatintelset/.+$")), + resource.TestCheckResourceAttr(resourceName, "name", threatintelsetName1), + resource.TestCheckResourceAttr(resourceName, "activate", "true"), + resource.TestMatchResourceAttr(resourceName, "location", regexp.MustCompile(fmt.Sprintf("%s/%s$", bucketName, keyName1))), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, { Config: testAccGuardDutyThreatintelsetConfig_basic(bucketName, keyName2, threatintelsetName2, false), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsGuardDutyThreatintelsetExists("aws_guardduty_threatintelset.test"), - resource.TestCheckResourceAttr("aws_guardduty_threatintelset.test", "name", threatintelsetName2), - resource.TestCheckResourceAttr("aws_guardduty_threatintelset.test", "activate", "false"), - resource.TestMatchResourceAttr( - "aws_guardduty_threatintelset.test", "location", regexp.MustCompile(fmt.Sprintf("%s/%s$", bucketName, keyName2)), - ), + testAccCheckAwsGuardDutyThreatintelsetExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "name", threatintelsetName2), + resource.TestCheckResourceAttr(resourceName, "activate", "false"), + resource.TestMatchResourceAttr(resourceName, "location", regexp.MustCompile(fmt.Sprintf("%s/%s$", bucketName, keyName2))), ), }, }, }) } -func testAccAwsGuardDutyThreatintelset_import(t *testing.T) { +func testAccAwsGuardDutyThreatintelset_tags(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_guardduty_threatintelset.test" - bucketName := fmt.Sprintf("tf-test-%s", acctest.RandString(5)) - keyName := fmt.Sprintf("tf-%s", acctest.RandString(5)) - threatintelsetName := fmt.Sprintf("tf-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -61,14 +64,35 @@ func testAccAwsGuardDutyThreatintelset_import(t *testing.T) { CheckDestroy: testAccCheckAwsGuardDutyThreatintelsetDestroy, Steps: []resource.TestStep{ { - Config: testAccGuardDutyThreatintelsetConfig_basic(bucketName, keyName, threatintelsetName, true), + Config: testAccGuardDutyThreatintelsetConfigTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsGuardDutyThreatintelsetExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), }, - { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, + { + Config: testAccGuardDutyThreatintelsetConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsGuardDutyThreatintelsetExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccGuardDutyThreatintelsetConfigTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsGuardDutyThreatintelsetExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, }, }) } @@ -133,7 +157,7 @@ func testAccCheckAwsGuardDutyThreatintelsetExists(name string) resource.TestChec func testAccGuardDutyThreatintelsetConfig_basic(bucketName, keyName, threatintelsetName string, activate bool) string { return fmt.Sprintf(` -%s +resource "aws_guardduty_detector" "test" {} resource "aws_s3_bucket" "test" { acl = "private" @@ -155,5 +179,68 @@ resource "aws_guardduty_threatintelset" "test" { location = "https://s3.amazonaws.com/${aws_s3_bucket_object.test.bucket}/${aws_s3_bucket_object.test.key}" activate = %t } -`, testAccGuardDutyDetectorConfig_basic1, bucketName, keyName, threatintelsetName, activate) +`, bucketName, keyName, threatintelsetName, activate) +} + +func testAccGuardDutyThreatintelsetConfigTags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_guardduty_detector" "test" {} + +resource "aws_s3_bucket" "test" { + acl = "private" + bucket = %[1]q + force_destroy = true +} + +resource "aws_s3_bucket_object" "test" { + acl = "public-read" + content = "10.0.0.0/8\n" + bucket = aws_s3_bucket.test.id + key = %[1]q +} + +resource "aws_guardduty_threatintelset" "test" { + activate = true + detector_id = aws_guardduty_detector.test.id + format = "TXT" + location = "https://s3.amazonaws.com/${aws_s3_bucket_object.test.bucket}/${aws_s3_bucket_object.test.key}" + name = %[1]q + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccGuardDutyThreatintelsetConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_guardduty_detector" "test" {} + +resource "aws_s3_bucket" "test" { + acl = "private" + bucket = %[1]q + force_destroy = true +} + +resource "aws_s3_bucket_object" "test" { + acl = "public-read" + content = "10.0.0.0/8\n" + bucket = aws_s3_bucket.test.id + key = %[1]q +} + +resource "aws_guardduty_threatintelset" "test" { + activate = true + detector_id = aws_guardduty_detector.test.id + format = "TXT" + location = "https://s3.amazonaws.com/${aws_s3_bucket_object.test.bucket}/${aws_s3_bucket_object.test.key}" + name = %[1]q + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) } diff --git a/aws/resource_aws_iam_access_key.go b/aws/resource_aws_iam_access_key.go index af8f853f67b..7d65fe21e29 100644 --- a/aws/resource_aws_iam_access_key.go +++ b/aws/resource_aws_iam_access_key.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/encryption" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/encryption" ) func resourceAwsIamAccessKey() *schema.Resource { @@ -42,12 +42,6 @@ func resourceAwsIamAccessKey() *schema.Resource { Computed: true, Sensitive: true, }, - "ses_smtp_password": { - Type: schema.TypeString, - Computed: true, - Sensitive: true, - Deprecated: "AWS SigV2 for SES SMTP passwords isy deprecated.\nUse 'ses_smtp_password_v4' for region-specific AWS SigV4 signed SES SMTP password instead.", - }, "ses_smtp_password_v4": { Type: schema.TypeString, Computed: true, @@ -111,14 +105,6 @@ func resourceAwsIamAccessKeyCreate(d *schema.ResourceData, meta interface{}) err } } - // AWS SigV2 - sesSMTPPassword, err := sesSmtpPasswordFromSecretKeySigV2(createResp.AccessKey.SecretAccessKey) - if err != nil { - return fmt.Errorf("error getting SES SigV2 SMTP Password from Secret Access Key: %s", err) - } - d.Set("ses_smtp_password", sesSMTPPassword) - - // AWS SigV4 sesSMTPPasswordV4, err := sesSmtpPasswordFromSecretKeySigV4(createResp.AccessKey.SecretAccessKey, meta.(*AWSClient).region) if err != nil { return fmt.Errorf("error getting SES SigV4 SMTP Password from Secret Access Key: %s", err) @@ -252,21 +238,3 @@ func sesSmtpPasswordFromSecretKeySigV4(key *string, region string) (string, erro versionedSig = append(versionedSig, rawSig...) return base64.StdEncoding.EncodeToString(versionedSig), nil } - -func sesSmtpPasswordFromSecretKeySigV2(key *string) (string, error) { - if key == nil { - return "", nil - } - version := byte(0x02) - message := []byte("SendRawEmail") - hmacKey := []byte(*key) - h := hmac.New(sha256.New, hmacKey) - if _, err := h.Write(message); err != nil { - return "", err - } - rawSig := h.Sum(nil) - versionedSig := make([]byte, 0, len(rawSig)+1) - versionedSig = append(versionedSig, version) - versionedSig = append(versionedSig, rawSig...) - return base64.StdEncoding.EncodeToString(versionedSig), nil -} diff --git a/aws/resource_aws_iam_access_key_test.go b/aws/resource_aws_iam_access_key_test.go index 03e400834c0..d08ce660b34 100644 --- a/aws/resource_aws_iam_access_key_test.go +++ b/aws/resource_aws_iam_access_key_test.go @@ -9,10 +9,10 @@ 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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/hashicorp/vault/helper/pgpkeys" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/vault/helper/pgpkeys" ) func TestAccAWSAccessKey_basic(t *testing.T) { @@ -256,23 +256,3 @@ func TestSesSmtpPasswordFromSecretKeySigV4(t *testing.T) { } } } - -func TestSesSmtpPasswordFromSecretKeySigV2(t *testing.T) { - cases := []struct { - Input string - Expected string - }{ - {"some+secret+key", "AnkqhOiWEcszZZzTMCQbOY1sPGoLFgMH9zhp4eNgSjo4"}, - {"another+secret+key", "Akwqr0Giwi8FsQFgW3DXWCC2DiiQ/jZjqLDWK8TeTBgL"}, - } - - for _, tc := range cases { - actual, err := sesSmtpPasswordFromSecretKeySigV2(&tc.Input) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - if actual != tc.Expected { - t.Fatalf("%q: expected %q, got %q", tc.Input, tc.Expected, actual) - } - } -} diff --git a/aws/resource_aws_iam_account_alias.go b/aws/resource_aws_iam_account_alias.go index 52889acb154..e8ed8ed1919 100644 --- a/aws/resource_aws_iam_account_alias.go +++ b/aws/resource_aws_iam_account_alias.go @@ -5,7 +5,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamAccountAlias() *schema.Resource { diff --git a/aws/resource_aws_iam_account_alias_test.go b/aws/resource_aws_iam_account_alias_test.go index d360e318a76..1b15f7ccd40 100644 --- a/aws/resource_aws_iam_account_alias_test.go +++ b/aws/resource_aws_iam_account_alias_test.go @@ -6,12 +6,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAWSIAMAccountAlias(t *testing.T) { +func TestAccAWSIAMAccountAlias_serial(t *testing.T) { testCases := map[string]map[string]func(t *testing.T){ "Basic": { "basic": testAccAWSIAMAccountAlias_basic_with_datasource, diff --git a/aws/resource_aws_iam_account_password_policy.go b/aws/resource_aws_iam_account_password_policy.go index 53f28a9139e..0087de07733 100644 --- a/aws/resource_aws_iam_account_password_policy.go +++ b/aws/resource_aws_iam_account_password_policy.go @@ -8,7 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamAccountPasswordPolicy() *schema.Resource { diff --git a/aws/resource_aws_iam_account_password_policy_test.go b/aws/resource_aws_iam_account_password_policy_test.go index a56764768d5..4386b92edf0 100644 --- a/aws/resource_aws_iam_account_password_policy_test.go +++ b/aws/resource_aws_iam_account_password_policy_test.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIAMAccountPasswordPolicy_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_group.go b/aws/resource_aws_iam_group.go index 1e92696e4f3..3f8f4e69b68 100644 --- a/aws/resource_aws_iam_group.go +++ b/aws/resource_aws_iam_group.go @@ -8,7 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsIamGroup() *schema.Resource { @@ -31,9 +32,12 @@ func resourceAwsIamGroup() *schema.Resource { Computed: true, }, "name": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validateAwsIamGroupName, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringMatch( + regexp.MustCompile(`^[0-9A-Za-z=,.@\-_+]+$`), + "must only contain alphanumeric characters, hyphens, underscores, commas, periods, @ symbols, plus and equals signs", + ), }, "path": { Type: schema.TypeString, @@ -98,7 +102,7 @@ func resourceAwsIamGroupReadResult(d *schema.ResourceData, group *iam.Group) err } func resourceAwsIamGroupUpdate(d *schema.ResourceData, meta interface{}) error { - if d.HasChange("name") || d.HasChange("path") { + if d.HasChanges("name", "path") { iamconn := meta.(*AWSClient).iamconn on, nn := d.GetChange("name") _, np := d.GetChange("path") @@ -131,12 +135,81 @@ func resourceAwsIamGroupDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func validateAwsIamGroupName(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, hyphens, underscores, commas, periods, @ symbols, plus and equals signs allowed in %q: %q", - k, value)) +func deleteAwsIamGroupPolicyAttachments(conn *iam.IAM, groupName string) error { + var attachedPolicies []*iam.AttachedPolicy + input := &iam.ListAttachedGroupPoliciesInput{ + GroupName: aws.String(groupName), + } + + err := conn.ListAttachedGroupPoliciesPages(input, func(page *iam.ListAttachedGroupPoliciesOutput, lastPage bool) bool { + attachedPolicies = append(attachedPolicies, page.AttachedPolicies...) + + return !lastPage + }) + + if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") { + return nil + } + + if err != nil { + return fmt.Errorf("error listing IAM Group (%s) policy attachments for deletion: %w", groupName, err) + } + + for _, attachedPolicy := range attachedPolicies { + input := &iam.DetachGroupPolicyInput{ + GroupName: aws.String(groupName), + PolicyArn: attachedPolicy.PolicyArn, + } + + _, err := conn.DetachGroupPolicy(input) + + if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") { + continue + } + + if err != nil { + return fmt.Errorf("error detaching IAM Group (%s) policy (%s): %w", groupName, aws.StringValue(attachedPolicy.PolicyArn), err) + } } - return + + return nil +} + +func deleteAwsIamGroupPolicies(conn *iam.IAM, groupName string) error { + var inlinePolicies []*string + input := &iam.ListGroupPoliciesInput{ + GroupName: aws.String(groupName), + } + + err := conn.ListGroupPoliciesPages(input, func(page *iam.ListGroupPoliciesOutput, lastPage bool) bool { + inlinePolicies = append(inlinePolicies, page.PolicyNames...) + return !lastPage + }) + + if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") { + return nil + } + + if err != nil { + return fmt.Errorf("error listing IAM Group (%s) inline policies for deletion: %w", groupName, err) + } + + for _, policyName := range inlinePolicies { + input := &iam.DeleteGroupPolicyInput{ + GroupName: aws.String(groupName), + PolicyName: policyName, + } + + _, err := conn.DeleteGroupPolicy(input) + + if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") { + continue + } + + if err != nil { + return fmt.Errorf("error deleting IAM Group (%s) inline policy (%s): %w", groupName, aws.StringValue(policyName), err) + } + } + + return nil } diff --git a/aws/resource_aws_iam_group_membership.go b/aws/resource_aws_iam_group_membership.go index 485466eda7d..1d69c710bf4 100644 --- a/aws/resource_aws_iam_group_membership.go +++ b/aws/resource_aws_iam_group_membership.go @@ -6,7 +6,7 @@ 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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamGroupMembership() *schema.Resource { diff --git a/aws/resource_aws_iam_group_membership_test.go b/aws/resource_aws_iam_group_membership_test.go index 1db76f25015..01564ac05ea 100644 --- a/aws/resource_aws_iam_group_membership_test.go +++ b/aws/resource_aws_iam_group_membership_test.go @@ -8,9 +8,9 @@ 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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSGroupMembership_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_group_policy.go b/aws/resource_aws_iam_group_policy.go index 2578b1ee712..f84156ab1f1 100644 --- a/aws/resource_aws_iam_group_policy.go +++ b/aws/resource_aws_iam_group_policy.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamGroupPolicy() *schema.Resource { diff --git a/aws/resource_aws_iam_group_policy_attachment.go b/aws/resource_aws_iam_group_policy_attachment.go index 97cb66d28a6..ea00767168b 100644 --- a/aws/resource_aws_iam_group_policy_attachment.go +++ b/aws/resource_aws_iam_group_policy_attachment.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/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamGroupPolicyAttachment() *schema.Resource { diff --git a/aws/resource_aws_iam_group_policy_attachment_test.go b/aws/resource_aws_iam_group_policy_attachment_test.go index 167b6ef1942..9365acc8882 100644 --- a/aws/resource_aws_iam_group_policy_attachment_test.go +++ b/aws/resource_aws_iam_group_policy_attachment_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIAMGroupPolicyAttachment_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_group_policy_test.go b/aws/resource_aws_iam_group_policy_test.go index 53ccf2455a3..c837fa14adb 100644 --- a/aws/resource_aws_iam_group_policy_test.go +++ b/aws/resource_aws_iam_group_policy_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIAMGroupPolicy_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_group_test.go b/aws/resource_aws_iam_group_test.go index d51efa3effe..4ec537bfc2d 100644 --- a/aws/resource_aws_iam_group_test.go +++ b/aws/resource_aws_iam_group_test.go @@ -3,51 +3,97 @@ package aws import ( "errors" "fmt" + "log" "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestValidateIamGroupName(t *testing.T) { - validNames := []string{ - "test-group", - "test_group", - "testgroup123", - "TestGroup", - "Test-Group", - "test.group", - "test.123,group", - "testgroup@hashicorp", - "test+group@hashicorp.com", +func init() { + resource.AddTestSweepers("aws_iam_group", &resource.Sweeper{ + Name: "aws_iam_group", + F: testSweepIamGroups, + Dependencies: []string{ + "aws_iam_user", + }, + }) +} + +func testSweepIamGroups(region string) error { + client, err := sharedClientForRegion(region) + + if err != nil { + return fmt.Errorf("error getting client: %w", err) } - for _, v := range validNames { - _, errs := validateAwsIamGroupName(v, "name") - if len(errs) != 0 { - t.Fatalf("%q should be a valid IAM Group name: %q", v, errs) + + conn := client.(*AWSClient).iamconn + input := &iam.ListGroupsInput{} + var sweeperErrs *multierror.Error + + err = conn.ListGroupsPages(input, func(page *iam.ListGroupsOutput, isLast bool) bool { + if page == nil { + return !isLast } - } - invalidNames := []string{ - "!", - "/", - " ", - ":", - ";", - "test name", - "/slash-at-the-beginning", - "slash-at-the-end/", - } - for _, v := range invalidNames { - _, errs := validateAwsIamGroupName(v, "name") - if len(errs) == 0 { - t.Fatalf("%q should be an invalid IAM Group name", v) + for _, group := range page.Groups { + input := &iam.DeleteGroupInput{ + GroupName: group.GroupName, + } + name := aws.StringValue(group.GroupName) + + if name == "Admin" || name == "TerraformAccTests" { + continue + } + + log.Printf("[INFO] Deleting IAM Group: %s", name) + + if err := deleteAwsIamGroupPolicyAttachments(conn, name); err != nil { + sweeperErr := fmt.Errorf("error deleting IAM Group (%s) policy attachments: %w", name, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + + if err := deleteAwsIamGroupPolicies(conn, name); err != nil { + sweeperErr := fmt.Errorf("error deleting IAM Group (%s) policies: %w", name, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + + _, err := conn.DeleteGroup(input) + + if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") { + continue + } + + if err != nil { + sweeperErr := fmt.Errorf("error deleting IAM Group (%s): %w", name, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } } + + return !isLast + }) + + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping IAM Group sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() } + + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving IAM Groups: %w", err)) + } + + return sweeperErrs.ErrorOrNil() } func TestAccAWSIAMGroup_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_instance_profile.go b/aws/resource_aws_iam_instance_profile.go index af183db58f4..0af8603450f 100644 --- a/aws/resource_aws_iam_instance_profile.go +++ b/aws/resource_aws_iam_instance_profile.go @@ -9,8 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsIamInstanceProfile() *schema.Resource { @@ -45,19 +46,10 @@ func resourceAwsIamInstanceProfile() *schema.Resource { Computed: true, ForceNew: true, ConflictsWith: []string{"name_prefix"}, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - // https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8196-L8201 - value := v.(string) - if len(value) > 128 { - errors = append(errors, fmt.Errorf( - "%q cannot be longer than 128 characters", k)) - } - if !regexp.MustCompile(`^[\w+=,.@-]+$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q must match [\\w+=,.@-]", k)) - } - return - }, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 128), + validation.StringMatch(regexp.MustCompile(`^[\w+=,.@-]*$`), "must match [\\w+=,.@-]"), + ), }, "name_prefix": { @@ -65,19 +57,10 @@ func resourceAwsIamInstanceProfile() *schema.Resource { Optional: true, ForceNew: true, ConflictsWith: []string{"name"}, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - // https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8196-L8201 - value := v.(string) - if len(value) > 64 { - errors = append(errors, fmt.Errorf( - "%q cannot be longer than 64 characters, name is limited to 128", k)) - } - if !regexp.MustCompile(`^[\w+=,.@-]+$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q must match [\\w+=,.@-]", k)) - } - return - }, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 64), + validation.StringMatch(regexp.MustCompile(`^[\w+=,.@-]*$`), "must match [\\w+=,.@-]"), + ), }, "path": { @@ -87,21 +70,9 @@ func resourceAwsIamInstanceProfile() *schema.Resource { ForceNew: true, }, - "roles": { - Type: schema.TypeSet, - Optional: true, - Computed: true, - ConflictsWith: []string{"role"}, - Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, - Deprecated: "Use `role` instead. Only a single role can be passed to an IAM Instance Profile", - }, - "role": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ConflictsWith: []string{"roles"}, + Type: schema.TypeString, + Optional: true, }, }, } @@ -190,50 +161,14 @@ func instanceProfileRemoveRole(iamconn *iam.IAM, profileName, roleName string) e return err } -func instanceProfileSetRoles(d *schema.ResourceData, iamconn *iam.IAM) error { - oldInterface, newInterface := d.GetChange("roles") - oldRoles := oldInterface.(*schema.Set) - newRoles := newInterface.(*schema.Set) - - currentRoles := schema.CopySet(oldRoles) - - for _, role := range oldRoles.Difference(newRoles).List() { - err := instanceProfileRemoveRole(iamconn, d.Id(), role.(string)) - if err != nil { - return fmt.Errorf("Error removing role %s from IAM instance profile %s: %s", role, d.Id(), err) - } - currentRoles.Remove(role) - d.Set("roles", currentRoles) - } - - for _, role := range newRoles.Difference(oldRoles).List() { - err := instanceProfileAddRole(iamconn, d.Id(), role.(string)) - if err != nil { - return fmt.Errorf("Error adding role %s to IAM instance profile %s: %s", role, d.Id(), err) - } - currentRoles.Add(role) - d.Set("roles", currentRoles) - } - - return nil -} - func instanceProfileRemoveAllRoles(d *schema.ResourceData, iamconn *iam.IAM) error { - role, hasRole := d.GetOk("role") - roles, hasRoles := d.GetOk("roles") - if hasRole && !hasRoles { // "roles" will always be a superset of "role", if set + if role, ok := d.GetOk("role"); ok { err := instanceProfileRemoveRole(iamconn, d.Id(), role.(string)) if err != nil { return fmt.Errorf("Error removing role %s from IAM instance profile %s: %s", role, d.Id(), err) } - } else { - for _, role := range roles.(*schema.Set).List() { - err := instanceProfileRemoveRole(iamconn, d.Id(), role.(string)) - if err != nil { - return fmt.Errorf("Error removing role %s from IAM instance profile %s: %s", role, d.Id(), err) - } - } } + return nil } @@ -258,10 +193,6 @@ func resourceAwsIamInstanceProfileUpdate(d *schema.ResourceData, meta interface{ } } - if d.HasChange("roles") { - return instanceProfileSetRoles(d, iamconn) - } - return nil } @@ -323,10 +254,5 @@ func instanceProfileReadResult(d *schema.ResourceData, result *iam.InstanceProfi 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) - } - err := d.Set("roles", roles) - return err + return nil } diff --git a/aws/resource_aws_iam_instance_profile_test.go b/aws/resource_aws_iam_instance_profile_test.go index 300e6279560..0a44adee6cc 100644 --- a/aws/resource_aws_iam_instance_profile_test.go +++ b/aws/resource_aws_iam_instance_profile_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIAMInstanceProfile_basic(t *testing.T) { @@ -37,32 +37,6 @@ func TestAccAWSIAMInstanceProfile_basic(t *testing.T) { }) } -func TestAccAWSIAMInstanceProfile_withRoleNotRoles(t *testing.T) { - var conf iam.GetInstanceProfileOutput - resourceName := "aws_iam_instance_profile.test" - - rName := acctest.RandString(5) - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSInstanceProfileDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSInstanceProfileWithRoleSpecified(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSInstanceProfileExists(resourceName, &conf), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"name_prefix"}, - }, - }, - }) -} - func TestAccAWSIAMInstanceProfile_withoutRole(t *testing.T) { var conf iam.GetInstanceProfileOutput resourceName := "aws_iam_instance_profile.test" @@ -195,8 +169,8 @@ resource "aws_iam_role" "test" { } resource "aws_iam_instance_profile" "test" { - name = "test" - roles = ["${aws_iam_role.test.name}"] + name = "test-%[1]s" + role = aws_iam_role.test.name } `, rName) } @@ -218,21 +192,7 @@ resource "aws_iam_role" "test" { resource "aws_iam_instance_profile" "test" { name_prefix = "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}" + role = aws_iam_role.test.name } `, rName) } diff --git a/aws/resource_aws_iam_openid_connect_provider.go b/aws/resource_aws_iam_openid_connect_provider.go index c146bf3ff16..1a0dc9dd05c 100644 --- a/aws/resource_aws_iam_openid_connect_provider.go +++ b/aws/resource_aws_iam_openid_connect_provider.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamOpenIDConnectProvider() *schema.Resource { diff --git a/aws/resource_aws_iam_openid_connect_provider_test.go b/aws/resource_aws_iam_openid_connect_provider_test.go index 613b6e3d649..03455670936 100644 --- a/aws/resource_aws_iam_openid_connect_provider_test.go +++ b/aws/resource_aws_iam_openid_connect_provider_test.go @@ -7,9 +7,9 @@ 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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIAMOpenIDConnectProvider_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_policy.go b/aws/resource_aws_iam_policy.go index 79185240f4a..c83ab1ba616 100644 --- a/aws/resource_aws_iam_policy.go +++ b/aws/resource_aws_iam_policy.go @@ -9,8 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsIamPolicy() *schema.Resource { @@ -47,38 +48,20 @@ func resourceAwsIamPolicy() *schema.Resource { Computed: true, ForceNew: true, ConflictsWith: []string{"name_prefix"}, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - // https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8329-L8334 - value := v.(string) - if len(value) > 128 { - errors = append(errors, fmt.Errorf( - "%q cannot be longer than 128 characters", k)) - } - if !regexp.MustCompile(`^[\w+=,.@-]*$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q must match [\\w+=,.@-]", k)) - } - return - }, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 128), + validation.StringMatch(regexp.MustCompile(`^[\w+=,.@-]*$`), "must match [\\w+=,.@-]"), + ), }, "name_prefix": { Type: schema.TypeString, Optional: true, ForceNew: true, ConflictsWith: []string{"name"}, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - // https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8329-L8334 - value := v.(string) - if len(value) > 96 { - errors = append(errors, fmt.Errorf( - "%q cannot be longer than 96 characters, name is limited to 128", k)) - } - if !regexp.MustCompile(`^[\w+=,.@-]*$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q must match [\\w+=,.@-]", k)) - } - return - }, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 96), + validation.StringMatch(regexp.MustCompile(`^[\w+=,.@-]*$`), "must match [\\w+=,.@-]"), + ), }, "arn": { Type: schema.TypeString, diff --git a/aws/resource_aws_iam_policy_attachment.go b/aws/resource_aws_iam_policy_attachment.go index 16b39853ff9..c63b0db4b76 100644 --- a/aws/resource_aws_iam_policy_attachment.go +++ b/aws/resource_aws_iam_policy_attachment.go @@ -7,8 +7,8 @@ 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-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsIamPolicyAttachment() *schema.Resource { diff --git a/aws/resource_aws_iam_policy_attachment_test.go b/aws/resource_aws_iam_policy_attachment_test.go index 3d93c91e3fa..755cdacd218 100644 --- a/aws/resource_aws_iam_policy_attachment_test.go +++ b/aws/resource_aws_iam_policy_attachment_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIAMPolicyAttachment_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_policy_test.go b/aws/resource_aws_iam_policy_test.go index 6d66a1b3b9a..7e44a792b78 100644 --- a/aws/resource_aws_iam_policy_test.go +++ b/aws/resource_aws_iam_policy_test.go @@ -2,16 +2,98 @@ package aws import ( "fmt" + "log" "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) +func init() { + resource.AddTestSweepers("aws_iam_policy", &resource.Sweeper{ + Name: "aws_iam_policy", + F: testSweepIamPolicies, + Dependencies: []string{ + "aws_iam_group", + "aws_iam_role", + "aws_iam_user", + }, + }) +} + +func testSweepIamPolicies(region string) error { + client, err := sharedClientForRegion(region) + + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + + conn := client.(*AWSClient).iamconn + input := &iam.ListPoliciesInput{ + Scope: aws.String(iam.PolicyScopeTypeLocal), + } + var sweeperErrs *multierror.Error + + err = conn.ListPoliciesPages(input, func(page *iam.ListPoliciesOutput, isLast bool) bool { + if page == nil { + return !isLast + } + + for _, policy := range page.Policies { + arn := aws.StringValue(policy.Arn) + input := &iam.DeletePolicyInput{ + PolicyArn: policy.Arn, + } + + log.Printf("[INFO] Deleting IAM Policy: %s", arn) + if err := iamPolicyDeleteNondefaultVersions(arn, conn); err != nil { + sweeperErr := fmt.Errorf("error deleting IAM Policy (%s) non-default versions: %w", arn, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + + _, err := conn.DeletePolicy(input) + + // Treat this sweeper as best effort for now. There are a lot of edge cases + // with lingering aws_iam_role resources in the HashiCorp testing accounts. + if isAWSErr(err, iam.ErrCodeDeleteConflictException, "") { + log.Printf("[WARN] Ignoring IAM Policy (%s) deletion error: %s", arn, err) + continue + } + + if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") { + continue + } + + if err != nil { + sweeperErr := fmt.Errorf("error deleting IAM Policy (%s): %w", arn, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + } + + return !isLast + }) + + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping IAM Policy sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() + } + + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving IAM Policies: %w", err)) + } + + return sweeperErrs.ErrorOrNil() +} + func TestAccAWSIAMPolicy_basic(t *testing.T) { var out iam.GetPolicyOutput rName := acctest.RandomWithPrefix("tf-acc-test") diff --git a/aws/resource_aws_iam_role.go b/aws/resource_aws_iam_role.go index 38ea148435a..aee1a84d417 100644 --- a/aws/resource_aws_iam_role.go +++ b/aws/resource_aws_iam_role.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -43,19 +43,10 @@ func resourceAwsIamRole() *schema.Resource { Computed: true, ForceNew: true, ConflictsWith: []string{"name_prefix"}, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - // https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8329-L8334 - value := v.(string) - if len(value) > 64 { - errors = append(errors, fmt.Errorf( - "%q cannot be longer than 64 characters", k)) - } - if !regexp.MustCompile(`^[\w+=,.@-]*$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q must match [\\w+=,.@-]", k)) - } - return - }, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 64), + validation.StringMatch(regexp.MustCompile(`^[\w+=,.@-]*$`), "must match [\\w+=,.@-]"), + ), }, "name_prefix": { @@ -63,19 +54,10 @@ func resourceAwsIamRole() *schema.Resource { Optional: true, ForceNew: true, ConflictsWith: []string{"name"}, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - // https://github.com/boto/botocore/blob/2485f5c/botocore/data/iam/2010-05-08/service-2.json#L8329-L8334 - value := v.(string) - if len(value) > 32 { - errors = append(errors, fmt.Errorf( - "%q cannot be longer than 32 characters, name is limited to 64", k)) - } - if !regexp.MustCompile(`^[\w+=,.@-]*$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q must match [\\w+=,.@-]", k)) - } - return - }, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 32), + validation.StringMatch(regexp.MustCompile(`^[\w+=,.@-]*$`), "must match [\\w+=,.@-]"), + ), }, "path": { @@ -176,7 +158,10 @@ func resourceAwsIamRoleCreate(d *schema.ResourceData, meta interface{}) error { if isAWSErr(err, "MalformedPolicyDocument", "Invalid principal in policy") { return resource.RetryableError(err) } - return resource.NonRetryableError(err) + if err != nil { + return resource.NonRetryableError(err) + } + return nil }) if isResourceTimeoutError(err) { createResp, err = iamconn.CreateRole(request) diff --git a/aws/resource_aws_iam_role_policy.go b/aws/resource_aws_iam_role_policy.go index 78aad42b291..4aeeebf50bc 100644 --- a/aws/resource_aws_iam_role_policy.go +++ b/aws/resource_aws_iam_role_policy.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamRolePolicy() *schema.Resource { diff --git a/aws/resource_aws_iam_role_policy_attachment.go b/aws/resource_aws_iam_role_policy_attachment.go index 2d5fca92ee9..19fb402868c 100644 --- a/aws/resource_aws_iam_role_policy_attachment.go +++ b/aws/resource_aws_iam_role_policy_attachment.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamRolePolicyAttachment() *schema.Resource { diff --git a/aws/resource_aws_iam_role_policy_attachment_test.go b/aws/resource_aws_iam_role_policy_attachment_test.go index a0c1debc6af..26afcc0a83f 100644 --- a/aws/resource_aws_iam_role_policy_attachment_test.go +++ b/aws/resource_aws_iam_role_policy_attachment_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSRolePolicyAttachment_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_role_policy_test.go b/aws/resource_aws_iam_role_policy_test.go index fba4d77c75a..a42680f3b3f 100644 --- a/aws/resource_aws_iam_role_policy_test.go +++ b/aws/resource_aws_iam_role_policy_test.go @@ -9,9 +9,9 @@ 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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIAMRolePolicy_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_role_test.go b/aws/resource_aws_iam_role_test.go index ab53ef0ae1b..ec3c9a59e07 100644 --- a/aws/resource_aws_iam_role_test.go +++ b/aws/resource_aws_iam_role_test.go @@ -10,9 +10,9 @@ 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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -51,18 +51,45 @@ func testSweepIamRoles(region string) error { } conn := client.(*AWSClient).iamconn prefixes := []string{ + "another_rds", + "batch_tf_acc_test", + "codepipeline-", + "cognito_authenticated_", + "cognito_unauthenticated_", + "CWLtoKinesisRole_", "ecs_instance_role", "ecs_tf", - "EMR_AutoScaling_DefaultRole", + "EMR_AutoScaling_DefaultRole_", + "enhanced-monitoring-role-", + "es-domain-role-", + "event_", + "firehose", + "foo_role", + "foo-role", + "foobar", "iam_emr", + "iam_for_lambda", + "iam_for_sfn", + "rds", + "role", + "sns-delivery-status", + "ssm_role", + "ssm-role", "terraform-", "test", "tf", } + // Some acceptance tests use acctest.RandString(10) rather than acctest.RandomWithPrefix() + regex := regexp.MustCompile(`^[a-zA-Z0-9]{10}$`) roles := make([]*iam.Role, 0) err = conn.ListRolesPages(&iam.ListRolesInput{}, func(page *iam.ListRolesOutput, lastPage bool) bool { for _, role := range page.Roles { + if regex.MatchString(aws.StringValue(role.RoleName)) { + roles = append(roles, role) + continue + } + for _, prefix := range prefixes { if strings.HasPrefix(aws.StringValue(role.RoleName), prefix) { roles = append(roles, role) @@ -718,9 +745,9 @@ EOF } resource "aws_iam_instance_profile" "role_update_test" { - name = "role_update_test_%s" - path = "/test/" - roles = ["${aws_iam_role.test.name}"] + name = "role_update_test_%s" + path = "/test/" + role = aws_iam_role.test.name } `, rName, rName, rName) } @@ -772,9 +799,9 @@ EOF } resource "aws_iam_instance_profile" "role_update_test" { - name = "role_update_test_%s" - path = "/test/" - roles = ["${aws_iam_role.test.name}"] + name = "role_update_test_%s" + path = "/test/" + role = aws_iam_role.test.name } `, rName, rName, rName) } diff --git a/aws/resource_aws_iam_saml_provider.go b/aws/resource_aws_iam_saml_provider.go index d114c881c00..dbe8e7a824a 100644 --- a/aws/resource_aws_iam_saml_provider.go +++ b/aws/resource_aws_iam_saml_provider.go @@ -3,14 +3,13 @@ package aws import ( "fmt" "log" - "regexp" + "strings" "time" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/iam" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamSamlProvider() *schema.Resource { @@ -47,14 +46,14 @@ func resourceAwsIamSamlProvider() *schema.Resource { } func resourceAwsIamSamlProviderCreate(d *schema.ResourceData, meta interface{}) error { - iamconn := meta.(*AWSClient).iamconn + conn := meta.(*AWSClient).iamconn input := &iam.CreateSAMLProviderInput{ Name: aws.String(d.Get("name").(string)), SAMLMetadataDocument: aws.String(d.Get("saml_metadata_document").(string)), } - out, err := iamconn.CreateSAMLProvider(input) + out, err := conn.CreateSAMLProvider(input) if err != nil { return err } @@ -65,14 +64,14 @@ func resourceAwsIamSamlProviderCreate(d *schema.ResourceData, meta interface{}) } func resourceAwsIamSamlProviderRead(d *schema.ResourceData, meta interface{}) error { - iamconn := meta.(*AWSClient).iamconn + conn := meta.(*AWSClient).iamconn input := &iam.GetSAMLProviderInput{ SAMLProviderArn: aws.String(d.Id()), } - out, err := iamconn.GetSAMLProvider(input) + out, err := conn.GetSAMLProvider(input) if err != nil { - if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" { + if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") { log.Printf("[WARN] IAM SAML Provider %q not found.", d.Id()) d.SetId("") return nil @@ -81,7 +80,7 @@ func resourceAwsIamSamlProviderRead(d *schema.ResourceData, meta interface{}) er } d.Set("arn", d.Id()) - name, err := extractNameFromIAMSamlProviderArn(d.Id(), meta.(*AWSClient).partition) + name, err := extractNameFromIAMSamlProviderArn(d.Id()) if err != nil { return err } @@ -93,13 +92,13 @@ func resourceAwsIamSamlProviderRead(d *schema.ResourceData, meta interface{}) er } func resourceAwsIamSamlProviderUpdate(d *schema.ResourceData, meta interface{}) error { - iamconn := meta.(*AWSClient).iamconn + conn := meta.(*AWSClient).iamconn input := &iam.UpdateSAMLProviderInput{ SAMLProviderArn: aws.String(d.Id()), SAMLMetadataDocument: aws.String(d.Get("saml_metadata_document").(string)), } - _, err := iamconn.UpdateSAMLProvider(input) + _, err := conn.UpdateSAMLProvider(input) if err != nil { return err } @@ -108,22 +107,23 @@ func resourceAwsIamSamlProviderUpdate(d *schema.ResourceData, meta interface{}) } func resourceAwsIamSamlProviderDelete(d *schema.ResourceData, meta interface{}) error { - iamconn := meta.(*AWSClient).iamconn + conn := meta.(*AWSClient).iamconn input := &iam.DeleteSAMLProviderInput{ SAMLProviderArn: aws.String(d.Id()), } - _, err := iamconn.DeleteSAMLProvider(input) + _, err := conn.DeleteSAMLProvider(input) return err } -func extractNameFromIAMSamlProviderArn(arn, partition string) (string, error) { - // arn:aws:iam::123456789012:saml-provider/tf-salesforce-test - r := regexp.MustCompile(fmt.Sprintf("^arn:%s:iam::[0-9]{12}:saml-provider/(.+)$", partition)) - submatches := r.FindStringSubmatch(arn) - if len(submatches) != 2 { - return "", fmt.Errorf("Unable to extract name from a given ARN: %q", arn) +func extractNameFromIAMSamlProviderArn(samlArn string) (string, error) { + parsedArn, err := arn.Parse(samlArn) + if err != nil { + return "", fmt.Errorf("Unable to extract name from a given ARN: %q", samlArn) } - return submatches[1], nil + + name := strings.TrimPrefix(parsedArn.Resource, "saml-provider/") + + return name, nil } diff --git a/aws/resource_aws_iam_saml_provider_test.go b/aws/resource_aws_iam_saml_provider_test.go index 28b60b6f8ab..0331fc04fcb 100644 --- a/aws/resource_aws_iam_saml_provider_test.go +++ b/aws/resource_aws_iam_saml_provider_test.go @@ -2,13 +2,14 @@ package aws import ( "fmt" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIAMSamlProvider_basic(t *testing.T) { @@ -24,6 +25,7 @@ func TestAccAWSIAMSamlProvider_basic(t *testing.T) { Config: testAccIAMSamlProviderConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckIAMSamlProviderExists(resourceName), + testAccMatchResourceAttrGlobalARN(resourceName, "arn", "iam", regexp.MustCompile(`saml-provider/.+`)), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttrSet(resourceName, "saml_metadata_document"), ), @@ -45,8 +47,29 @@ func TestAccAWSIAMSamlProvider_basic(t *testing.T) { }) } +func TestAccAWSIAMSamlProvider_disappears(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_iam_saml_provider.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckIAMSamlProviderDestroy, + Steps: []resource.TestStep{ + { + Config: testAccIAMSamlProviderConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckIAMSamlProviderExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsIamSamlProvider(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckIAMSamlProviderDestroy(s *terraform.State) error { - iamconn := testAccProvider.Meta().(*AWSClient).iamconn + conn := testAccProvider.Meta().(*AWSClient).iamconn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_iam_saml_provider" { @@ -56,7 +79,7 @@ func testAccCheckIAMSamlProviderDestroy(s *terraform.State) error { input := &iam.GetSAMLProviderInput{ SAMLProviderArn: aws.String(rs.Primary.ID), } - out, err := iamconn.GetSAMLProvider(input) + out, err := conn.GetSAMLProvider(input) if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") { continue @@ -85,8 +108,8 @@ func testAccCheckIAMSamlProviderExists(id string) resource.TestCheckFunc { return fmt.Errorf("No ID is set") } - iamconn := testAccProvider.Meta().(*AWSClient).iamconn - _, err := iamconn.GetSAMLProvider(&iam.GetSAMLProviderInput{ + conn := testAccProvider.Meta().(*AWSClient).iamconn + _, err := conn.GetSAMLProvider(&iam.GetSAMLProviderInput{ SAMLProviderArn: aws.String(rs.Primary.ID), }) diff --git a/aws/resource_aws_iam_server_certificate.go b/aws/resource_aws_iam_server_certificate.go index 658bc181f9b..870d19537f9 100644 --- a/aws/resource_aws_iam_server_certificate.go +++ b/aws/resource_aws_iam_server_certificate.go @@ -13,9 +13,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsIAMServerCertificate() *schema.Resource { @@ -29,17 +29,19 @@ func resourceAwsIAMServerCertificate() *schema.Resource { Schema: map[string]*schema.Schema{ "certificate_body": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: normalizeCert, + Type: schema.TypeString, + Required: true, + ForceNew: true, + DiffSuppressFunc: suppressNormalizeCertRemoval, + StateFunc: StateTrimSpace, }, "certificate_chain": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - StateFunc: normalizeCert, + Type: schema.TypeString, + Optional: true, + ForceNew: true, + DiffSuppressFunc: suppressNormalizeCertRemoval, + StateFunc: StateTrimSpace, }, "path": { @@ -50,11 +52,12 @@ func resourceAwsIAMServerCertificate() *schema.Resource { }, "private_key": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: normalizeCert, - Sensitive: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + Sensitive: true, + DiffSuppressFunc: suppressNormalizeCertRemoval, + StateFunc: StateTrimSpace, }, "name": { @@ -112,13 +115,10 @@ func resourceAwsIAMServerCertificateCreate(d *schema.ResourceData, meta interfac log.Printf("[DEBUG] Creating IAM Server Certificate with opts: %s", createOpts) resp, err := conn.UploadServerCertificate(createOpts) if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - return fmt.Errorf("Error uploading server certificate, error: %s: %s", awsErr.Code(), awsErr.Message()) - } - return fmt.Errorf("Error uploading server certificate, error: %s", err) + return fmt.Errorf("error uploading server certificate: %w", err) } - d.SetId(*resp.ServerCertificateMetadata.ServerCertificateId) + d.SetId(aws.StringValue(resp.ServerCertificateMetadata.ServerCertificateId)) d.Set("name", sslCertName) return resourceAwsIAMServerCertificateRead(d, meta) @@ -130,29 +130,20 @@ func resourceAwsIAMServerCertificateRead(d *schema.ResourceData, meta interface{ ServerCertificateName: aws.String(d.Get("name").(string)), }) - if err != nil { - if awsErr, ok := err.(awserr.Error); ok { - if awsErr.Code() == "NoSuchEntity" { - log.Printf("[WARN] IAM Server Cert (%s) not found, removing from state", d.Id()) - d.SetId("") - return nil - } - return fmt.Errorf("Error reading IAM Server Certificate: %s: %s", awsErr.Code(), awsErr.Message()) - } - return fmt.Errorf("Error reading IAM Server Certificate: %s", err) + if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") { + log.Printf("[WARN] IAM Server Certificate (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } - d.SetId(*resp.ServerCertificate.ServerCertificateMetadata.ServerCertificateId) - - // these values should always be present, and have a default if not set in - // configuration, and so safe to reference with nil checks - d.Set("certificate_body", normalizeCert(resp.ServerCertificate.CertificateBody)) - - c := normalizeCert(resp.ServerCertificate.CertificateChain) - if c != "" { - d.Set("certificate_chain", c) + if err != nil { + return fmt.Errorf("error reading IAM Server Certificate (%s): %w", d.Id(), err) } + d.SetId(aws.StringValue(resp.ServerCertificate.ServerCertificateMetadata.ServerCertificateId)) + + d.Set("certificate_body", resp.ServerCertificate.CertificateBody) + d.Set("certificate_chain", resp.ServerCertificate.CertificateChain) d.Set("path", resp.ServerCertificate.ServerCertificateMetadata.Path) d.Set("arn", resp.ServerCertificate.ServerCertificateMetadata.Arn) @@ -247,3 +238,9 @@ func stripCR(b []byte) []byte { } return c[:i] } + +// Terraform AWS Provider version 3.0.0 removed state hash storage. +// This DiffSuppressFunc prevents the resource from triggering needless recreation. +func suppressNormalizeCertRemoval(k, old, new string, d *schema.ResourceData) bool { + return normalizeCert(new) == old +} diff --git a/aws/resource_aws_iam_server_certificate_test.go b/aws/resource_aws_iam_server_certificate_test.go index 334f24c346f..99238daa1ab 100644 --- a/aws/resource_aws_iam_server_certificate_test.go +++ b/aws/resource_aws_iam_server_certificate_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_iam_service_linked_role.go b/aws/resource_aws_iam_service_linked_role.go index 182f6d4c7ff..91547db8b20 100644 --- a/aws/resource_aws_iam_service_linked_role.go +++ b/aws/resource_aws_iam_service_linked_role.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsIamServiceLinkedRole() *schema.Resource { diff --git a/aws/resource_aws_iam_service_linked_role_test.go b/aws/resource_aws_iam_service_linked_role_test.go index 765f8583f39..b993797848d 100644 --- a/aws/resource_aws_iam_service_linked_role_test.go +++ b/aws/resource_aws_iam_service_linked_role_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_iam_user.go b/aws/resource_aws_iam_user.go index 1b2e099d54a..77073b041f1 100644 --- a/aws/resource_aws_iam_user.go +++ b/aws/resource_aws_iam_user.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -43,9 +43,12 @@ func resourceAwsIamUser() *schema.Resource { Computed: true, }, "name": { - Type: schema.TypeString, - Required: true, - ValidateFunc: validateAwsIamUserName, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringMatch( + regexp.MustCompile(`^[0-9A-Za-z=,.@\-_+]+$`), + "must only contain alphanumeric characters, hyphens, underscores, commas, periods, @ symbols, plus and equals signs", + ), }, "path": { Type: schema.TypeString, @@ -139,7 +142,7 @@ func resourceAwsIamUserRead(d *schema.ResourceData, meta interface{}) error { func resourceAwsIamUserUpdate(d *schema.ResourceData, meta interface{}) error { iamconn := meta.(*AWSClient).iamconn - if d.HasChange("name") || d.HasChange("path") { + if d.HasChanges("name", "path") { on, nn := d.GetChange("name") _, np := d.GetChange("path") @@ -249,16 +252,6 @@ func resourceAwsIamUserDelete(d *schema.ResourceData, meta interface{}) error { return nil } -func validateAwsIamUserName(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, hyphens, underscores, commas, periods, @ symbols, plus and equals signs allowed in %q: %q", - k, value)) - } - return -} - func deleteAwsIamUserGroupMemberships(conn *iam.IAM, username string) error { var groups []string listGroups := &iam.ListGroupsForUserInput{ diff --git a/aws/resource_aws_iam_user_group_membership.go b/aws/resource_aws_iam_user_group_membership.go index 503cd3b14d5..a9f275c01e2 100644 --- a/aws/resource_aws_iam_user_group_membership.go +++ b/aws/resource_aws_iam_user_group_membership.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamUserGroupMembership() *schema.Resource { diff --git a/aws/resource_aws_iam_user_group_membership_test.go b/aws/resource_aws_iam_user_group_membership_test.go index 3acd14dfe5c..45a33cd3113 100644 --- a/aws/resource_aws_iam_user_group_membership_test.go +++ b/aws/resource_aws_iam_user_group_membership_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSUserGroupMembership_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_user_login_profile.go b/aws/resource_aws_iam_user_login_profile.go index 38ff10a3277..37aab38e8cf 100644 --- a/aws/resource_aws_iam_user_login_profile.go +++ b/aws/resource_aws_iam_user_login_profile.go @@ -12,10 +12,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/encryption" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/encryption" ) func resourceAwsIamUserLoginProfile() *schema.Resource { diff --git a/aws/resource_aws_iam_user_login_profile_test.go b/aws/resource_aws_iam_user_login_profile_test.go index 9dbef6998a9..1a229fcf8ee 100644 --- a/aws/resource_aws_iam_user_login_profile_test.go +++ b/aws/resource_aws_iam_user_login_profile_test.go @@ -12,10 +12,10 @@ import ( "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/hashicorp/vault/helper/pgpkeys" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/vault/helper/pgpkeys" ) func TestGenerateIAMPassword(t *testing.T) { diff --git a/aws/resource_aws_iam_user_policy.go b/aws/resource_aws_iam_user_policy.go index 9b7ec1b345a..716085d8b0c 100644 --- a/aws/resource_aws_iam_user_policy.go +++ b/aws/resource_aws_iam_user_policy.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamUserPolicy() *schema.Resource { diff --git a/aws/resource_aws_iam_user_policy_attachment.go b/aws/resource_aws_iam_user_policy_attachment.go index 7595d899831..4f25dd40e68 100644 --- a/aws/resource_aws_iam_user_policy_attachment.go +++ b/aws/resource_aws_iam_user_policy_attachment.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/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIamUserPolicyAttachment() *schema.Resource { diff --git a/aws/resource_aws_iam_user_policy_attachment_test.go b/aws/resource_aws_iam_user_policy_attachment_test.go index bbce09e4eda..e731c08c5f2 100644 --- a/aws/resource_aws_iam_user_policy_attachment_test.go +++ b/aws/resource_aws_iam_user_policy_attachment_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSUserPolicyAttachment_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_user_policy_test.go b/aws/resource_aws_iam_user_policy_test.go index 3f981831ef4..7caf120e5d2 100644 --- a/aws/resource_aws_iam_user_policy_test.go +++ b/aws/resource_aws_iam_user_policy_test.go @@ -9,9 +9,9 @@ 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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIAMUserPolicy_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_user_ssh_key.go b/aws/resource_aws_iam_user_ssh_key.go index 0220a74dba2..36949ccf7e9 100644 --- a/aws/resource_aws_iam_user_ssh_key.go +++ b/aws/resource_aws_iam_user_ssh_key.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/iam" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsIamUserSshKey() *schema.Resource { diff --git a/aws/resource_aws_iam_user_ssh_key_test.go b/aws/resource_aws_iam_user_ssh_key_test.go index b4317eea6a2..09185a580a3 100644 --- a/aws/resource_aws_iam_user_ssh_key_test.go +++ b/aws/resource_aws_iam_user_ssh_key_test.go @@ -7,9 +7,9 @@ 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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSUserSSHKey_basic(t *testing.T) { diff --git a/aws/resource_aws_iam_user_test.go b/aws/resource_aws_iam_user_test.go index 2293ae9619f..cf9e8fcd08c 100644 --- a/aws/resource_aws_iam_user_test.go +++ b/aws/resource_aws_iam_user_test.go @@ -12,49 +12,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iam" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/pquerna/otp/totp" ) -func TestValidateIamUserName(t *testing.T) { - validNames := []string{ - "test-user", - "test_user", - "testuser123", - "TestUser", - "Test-User", - "test.user", - "test.123,user", - "testuser@hashicorp", - "test+user@hashicorp.com", - } - for _, v := range validNames { - _, errors := validateAwsIamUserName(v, "name") - if len(errors) != 0 { - t.Fatalf("%q should be a valid IAM User name: %q", v, errors) - } - } - - invalidNames := []string{ - "!", - "/", - " ", - ":", - ";", - "test name", - "/slash-at-the-beginning", - "slash-at-the-end/", - } - for _, v := range invalidNames { - _, errors := validateAwsIamUserName(v, "name") - if len(errors) == 0 { - t.Fatalf("%q should be an invalid IAM User name", v) - } - } -} - func init() { resource.AddTestSweepers("aws_iam_user", &resource.Sweeper{ Name: "aws_iam_user", @@ -70,7 +33,9 @@ func testSweepIamUsers(region string) error { conn := client.(*AWSClient).iamconn prefixes := []string{ "test-user", - "tf-acc-test", + "test_user", + "tf-acc", + "tf_acc", } users := make([]*iam.User, 0) diff --git a/aws/resource_aws_inspector_assessment_target.go b/aws/resource_aws_inspector_assessment_target.go index 47bb7db954a..a426630380d 100644 --- a/aws/resource_aws_inspector_assessment_target.go +++ b/aws/resource_aws_inspector_assessment_target.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/inspector" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAWSInspectorAssessmentTarget() *schema.Resource { diff --git a/aws/resource_aws_inspector_assessment_target_test.go b/aws/resource_aws_inspector_assessment_target_test.go index 821dd3090ef..3582ee2cd6a 100644 --- a/aws/resource_aws_inspector_assessment_target_test.go +++ b/aws/resource_aws_inspector_assessment_target_test.go @@ -6,9 +6,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/inspector" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSInspectorTarget_basic(t *testing.T) { diff --git a/aws/resource_aws_inspector_assessment_template.go b/aws/resource_aws_inspector_assessment_template.go index 0acc5b589b9..f83eaaed4e7 100644 --- a/aws/resource_aws_inspector_assessment_template.go +++ b/aws/resource_aws_inspector_assessment_template.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" // "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/inspector" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_inspector_assessment_template_test.go b/aws/resource_aws_inspector_assessment_template_test.go index 23467b63042..7eb5d180659 100644 --- a/aws/resource_aws_inspector_assessment_template_test.go +++ b/aws/resource_aws_inspector_assessment_template_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/inspector" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSInspectorTemplate_basic(t *testing.T) { diff --git a/aws/resource_aws_inspector_resource_group.go b/aws/resource_aws_inspector_resource_group.go index 47de0a45f2d..fe44c473d58 100644 --- a/aws/resource_aws_inspector_resource_group.go +++ b/aws/resource_aws_inspector_resource_group.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/inspector" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAWSInspectorResourceGroup() *schema.Resource { @@ -20,6 +20,7 @@ func resourceAWSInspectorResourceGroup() *schema.Resource { ForceNew: true, Required: true, Type: schema.TypeMap, + Elem: &schema.Schema{Type: schema.TypeString}, }, "arn": { Type: schema.TypeString, diff --git a/aws/resource_aws_inspector_resource_group_test.go b/aws/resource_aws_inspector_resource_group_test.go index 02ed90200b9..2ca6d00841b 100644 --- a/aws/resource_aws_inspector_resource_group_test.go +++ b/aws/resource_aws_inspector_resource_group_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/inspector" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSInspectorResourceGroup_basic(t *testing.T) { @@ -34,7 +34,7 @@ func TestAccAWSInspectorResourceGroup_basic(t *testing.T) { testAccCheckAWSInspectorResourceGroupExists(resourceName, &v2), testAccMatchResourceAttrRegionalARN(resourceName, "arn", "inspector", regexp.MustCompile(`resourcegroup/.+`)), resource.TestCheckResourceAttr(resourceName, "tags.Name", "bar"), - testAccCheckAWSInspectorResourceGroupRecreated(t, &v1, &v2), + testAccCheckAWSInspectorResourceGroupRecreated(&v1, &v2), ), }, }, @@ -69,7 +69,7 @@ func testAccCheckAWSInspectorResourceGroupExists(name string, rg *inspector.Reso } } -func testAccCheckAWSInspectorResourceGroupRecreated(t *testing.T, v1, v2 *inspector.ResourceGroup) resource.TestCheckFunc { +func testAccCheckAWSInspectorResourceGroupRecreated(v1, v2 *inspector.ResourceGroup) resource.TestCheckFunc { return func(s *terraform.State) error { if v2.CreatedAt.Equal(*v1.CreatedAt) { return fmt.Errorf("Inspector resource group not recreated when changing tags") diff --git a/aws/resource_aws_instance.go b/aws/resource_aws_instance.go index 3682993ac4d..47b11d7d047 100644 --- a/aws/resource_aws_instance.go +++ b/aws/resource_aws_instance.go @@ -13,16 +13,16 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) func resourceAwsInstance() *schema.Resource { + //lintignore:R011 return &schema.Resource{ Create: resourceAwsInstanceCreate, Read: resourceAwsInstanceRead, @@ -109,6 +109,20 @@ func resourceAwsInstance() *schema.Resource { Optional: true, ForceNew: true, Computed: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validation.IsIPv4Address, + ), + }, + + "secondary_private_ips": { + Type: schema.TypeSet, + Optional: true, + Computed: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.IsIPv4Address, + }, }, "source_dest_check": { @@ -190,19 +204,13 @@ func resourceAwsInstance() *schema.Resource { Computed: true, }, - "network_interface_id": { - Type: schema.TypeString, - Computed: true, - Removed: "Use `primary_network_interface_id` attribute instead", - }, - "primary_network_interface_id": { Type: schema.TypeString, Computed: true, }, "network_interface": { - ConflictsWith: []string{"associate_public_ip_address", "subnet_id", "private_ip", "vpc_security_group_ids", "security_groups", "ipv6_addresses", "ipv6_address_count", "source_dest_check"}, + ConflictsWith: []string{"associate_public_ip_address", "subnet_id", "private_ip", "secondary_private_ips", "vpc_security_group_ids", "security_groups", "ipv6_addresses", "ipv6_address_count", "source_dest_check"}, Type: schema.TypeSet, Optional: true, Computed: true, @@ -288,7 +296,8 @@ func resourceAwsInstance() *schema.Resource { Computed: true, ForceNew: true, Elem: &schema.Schema{ - Type: schema.TypeString, + Type: schema.TypeString, + ValidateFunc: validation.IsIPv6Address, }, }, @@ -297,6 +306,11 @@ func resourceAwsInstance() *schema.Resource { Optional: true, Computed: true, ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + ec2.TenancyDedicated, + ec2.TenancyDefault, + ec2.TenancyHost, + }, false), }, "host_id": { Type: schema.TypeString, @@ -382,6 +396,13 @@ func resourceAwsInstance() *schema.Resource { Optional: true, Computed: true, ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + ec2.VolumeTypeStandard, + ec2.VolumeTypeIo1, + ec2.VolumeTypeGp2, + ec2.VolumeTypeSc1, + ec2.VolumeTypeSt1, + }, false), }, "volume_id": { @@ -486,6 +507,13 @@ func resourceAwsInstance() *schema.Resource { Type: schema.TypeString, Optional: true, Computed: true, + ValidateFunc: validation.StringInSlice([]string{ + ec2.VolumeTypeStandard, + ec2.VolumeTypeIo1, + ec2.VolumeTypeGp2, + ec2.VolumeTypeSc1, + ec2.VolumeTypeSt1, + }, false), }, "volume_id": { @@ -564,11 +592,11 @@ func resourceAwsInstance() *schema.Resource { } func iopsDiffSuppressFunc(k, old, new string, d *schema.ResourceData) bool { - // Suppress diff if volume_type is not io1 + // Suppress diff if volume_type is not io1 and iops is unset or configured as 0 i := strings.LastIndexByte(k, '.') vt := k[:i+1] + "volume_type" v := d.Get(vt).(string) - return strings.ToLower(v) != ec2.VolumeTypeIo1 + return strings.ToLower(v) != ec2.VolumeTypeIo1 && new == "0" } func resourceAwsInstanceCreate(d *schema.ResourceData, meta interface{}) error { @@ -636,7 +664,10 @@ func resourceAwsInstanceCreate(d *schema.ResourceData, meta interface{}) error { log.Print("[DEBUG] IAM Instance Profile appears to have no IAM roles, retrying...") return resource.RetryableError(err) } - return resource.NonRetryableError(err) + if err != nil { + return resource.NonRetryableError(err) + } + return nil }) if isResourceTimeoutError(err) { runResp, err = conn.RunInstances(runOpts) @@ -645,7 +676,7 @@ func resourceAwsInstanceCreate(d *schema.ResourceData, meta interface{}) error { // where a user uses group ids in security_groups for the Default VPC. // See https://github.com/hashicorp/terraform/issues/3798 if isAWSErr(err, "InvalidParameterValue", "groupId is invalid") { - return fmt.Errorf("Error launching instance, possible mismatch of Security Group IDs and Names. See AWS Instance docs here: %s.\n\n\tAWS Error: %s", "https://terraform.io/docs/providers/aws/r/instance.html", err.(awserr.Error).Message()) + return fmt.Errorf("Error launching instance, possible mismatch of Security Group IDs and Names. See AWS Instance docs here: %s.\n\n\tAWS Error: %w", "https://terraform.io/docs/providers/aws/r/instance.html", err) } if err != nil { return fmt.Errorf("Error launching source instance: %s", err) @@ -655,21 +686,21 @@ func resourceAwsInstanceCreate(d *schema.ResourceData, meta interface{}) error { } instance := runResp.Instances[0] - log.Printf("[INFO] Instance ID: %s", *instance.InstanceId) + log.Printf("[INFO] Instance ID: %s", aws.StringValue(instance.InstanceId)) // Store the resulting ID so we can look this up later - d.SetId(*instance.InstanceId) + d.SetId(aws.StringValue(instance.InstanceId)) // Wait for the instance to become running so we can get some attributes // that aren't available until later. log.Printf( "[DEBUG] Waiting for instance (%s) to become running", - *instance.InstanceId) + aws.StringValue(instance.InstanceId)) stateConf := &resource.StateChangeConf{ - Pending: []string{"pending"}, - Target: []string{"running"}, - Refresh: InstanceStateRefreshFunc(conn, *instance.InstanceId, []string{"terminated", "shutting-down"}), + Pending: []string{ec2.InstanceStateNamePending}, + Target: []string{ec2.InstanceStateNameRunning}, + Refresh: InstanceStateRefreshFunc(conn, aws.StringValue(instance.InstanceId), []string{ec2.InstanceStateNameTerminated, ec2.InstanceStateNameShuttingDown}), Timeout: d.Timeout(schema.TimeoutCreate), Delay: 10 * time.Second, MinTimeout: 3 * time.Second, @@ -679,7 +710,7 @@ func resourceAwsInstanceCreate(d *schema.ResourceData, meta interface{}) error { if err != nil { return fmt.Errorf( "Error waiting for instance (%s) to become ready: %s", - *instance.InstanceId, err) + aws.StringValue(instance.InstanceId), err) } instance = instanceRaw.(*ec2.Instance) @@ -688,12 +719,12 @@ func resourceAwsInstanceCreate(d *schema.ResourceData, meta interface{}) error { if instance.PublicIpAddress != nil { d.SetConnInfo(map[string]string{ "type": "ssh", - "host": *instance.PublicIpAddress, + "host": aws.StringValue(instance.PublicIpAddress), }) } else if instance.PrivateIpAddress != nil { d.SetConnInfo(map[string]string{ "type": "ssh", - "host": *instance.PrivateIpAddress, + "host": aws.StringValue(instance.PrivateIpAddress), }) } @@ -709,7 +740,7 @@ func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error { if err != nil { // If the instance was not found, return nil so that we can show // that the instance is gone. - if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" { + if isAWSErr(err, "InvalidInstanceID.NotFound", "") { d.SetId("") return nil } @@ -726,7 +757,7 @@ func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error { if instance.State != nil { // If the instance is terminated, then it is gone - if *instance.State.Name == "terminated" { + if aws.StringValue(instance.State.Name) == ec2.InstanceStateNameTerminated { d.SetId("") return nil } @@ -783,22 +814,23 @@ func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error { } } + var secondaryPrivateIPs []string var ipv6Addresses []string if len(instance.NetworkInterfaces) > 0 { var primaryNetworkInterface ec2.InstanceNetworkInterface var networkInterfaces []map[string]interface{} for _, iNi := range instance.NetworkInterfaces { ni := make(map[string]interface{}) - if *iNi.Attachment.DeviceIndex == 0 { + if aws.Int64Value(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 + if index == int(aws.Int64Value(iNi.Attachment.DeviceIndex)) { + ni["device_index"] = aws.Int64Value(iNi.Attachment.DeviceIndex) + ni["network_interface_id"] = aws.StringValue(iNi.NetworkInterfaceId) + ni["delete_on_termination"] = aws.BoolValue(iNi.Attachment.DeleteOnTermination) } } // Don't add empty network interfaces to schema @@ -827,8 +859,14 @@ func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error { d.Set("associate_public_ip_address", primaryNetworkInterface.Association != nil) + for _, address := range primaryNetworkInterface.PrivateIpAddresses { + if !aws.BoolValue(address.Primary) { + secondaryPrivateIPs = append(secondaryPrivateIPs, aws.StringValue(address.PrivateIpAddress)) + } + } + for _, address := range primaryNetworkInterface.Ipv6Addresses { - ipv6Addresses = append(ipv6Addresses, *address.Ipv6Address) + ipv6Addresses = append(ipv6Addresses, aws.StringValue(address.Ipv6Address)) } } else { @@ -838,18 +876,22 @@ func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error { d.Set("subnet_id", instance.SubnetId) } + if err := d.Set("secondary_private_ips", secondaryPrivateIPs); err != nil { + return fmt.Errorf("Error setting private_ips for AWS Instance (%s): %w", d.Id(), err) + } + if err := d.Set("ipv6_addresses", ipv6Addresses); err != nil { log.Printf("[WARN] Error setting ipv6_addresses for AWS Instance (%s): %s", d.Id(), err) } d.Set("ebs_optimized", instance.EbsOptimized) - if instance.SubnetId != nil && *instance.SubnetId != "" { + if aws.StringValue(instance.SubnetId) != "" { d.Set("source_dest_check", instance.SourceDestCheck) } if instance.Monitoring != nil && instance.Monitoring.State != nil { - monitoringState := *instance.Monitoring.State - d.Set("monitoring", monitoringState == "enabled" || monitoringState == "pending") + monitoringState := aws.StringValue(instance.Monitoring.State) + d.Set("monitoring", monitoringState == ec2.MonitoringStateEnabled || monitoringState == ec2.MonitoringStatePending) } if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(instance.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { @@ -915,7 +957,7 @@ func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error { if b64 { d.Set("user_data_base64", attr.UserData.Value) } else { - d.Set("user_data", userDataHashSum(*attr.UserData.Value)) + d.Set("user_data", userDataHashSum(aws.StringValue(attr.UserData.Value))) } } } @@ -937,7 +979,7 @@ func resourceAwsInstanceRead(d *schema.ResourceData, meta interface{}) error { } if d.Get("get_password_data").(bool) { - passwordData, err := getAwsEc2InstancePasswordData(*instance.InstanceId, conn) + passwordData, err := getAwsEc2InstancePasswordData(aws.StringValue(instance.InstanceId), conn) if err != nil { return err } @@ -1075,58 +1117,100 @@ func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error { }, }) if err != nil { - if ec2err, ok := err.(awserr.Error); ok { - // Tolerate InvalidParameterCombination error in Classic, otherwise - // return the error - if ec2err.Code() != "InvalidParameterCombination" { - return err - } - log.Printf("[WARN] Attempted to modify SourceDestCheck on non VPC instance: %s", ec2err.Message()) + // Tolerate InvalidParameterCombination error in Classic, otherwise + // return the error + if !isAWSErr(err, "InvalidParameterCombination", "") { + return err } + log.Printf("[WARN] Attempted to modify SourceDestCheck on non VPC instance: %s", err) } } } - if d.HasChange("vpc_security_group_ids") && !d.IsNewResource() { - var groups []*string - if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 { - for _, v := range v.List() { - groups = append(groups, aws.String(v.(string))) - } - } - - if len(groups) < 1 { - return fmt.Errorf("VPC-based instances require at least one security group to be attached.") - } - // 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()) + if d.HasChanges("secondary_private_ips", "vpc_security_group_ids") && !d.IsNewResource() { instance, err := resourceAwsInstanceFindByID(conn, d.Id()) if err != nil { return fmt.Errorf("error retrieving instance %q: %w", d.Id(), err) } var primaryInterface ec2.InstanceNetworkInterface for _, ni := range instance.NetworkInterfaces { - if *ni.Attachment.DeviceIndex == 0 { + if aws.Int64Value(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 d.HasChange("secondary_private_ips") { + if primaryInterface.NetworkInterfaceId == nil { + return fmt.Errorf("Failed to update secondary_private_ips on %q, which does not contain a primary network interface", + d.Id()) + } + o, n := d.GetChange("secondary_private_ips") + if o == nil { + o = new(schema.Set) + } + if n == nil { + n = new(schema.Set) + } + + os := o.(*schema.Set) + ns := n.(*schema.Set) + + // Unassign old IP addresses + unassignIps := os.Difference(ns) + if unassignIps.Len() != 0 { + input := &ec2.UnassignPrivateIpAddressesInput{ + NetworkInterfaceId: primaryInterface.NetworkInterfaceId, + PrivateIpAddresses: expandStringSet(unassignIps), + } + log.Printf("[INFO] Unassigning secondary_private_ips on Instance %q", d.Id()) + _, err := conn.UnassignPrivateIpAddresses(input) + if err != nil { + return fmt.Errorf("Failure to unassign Secondary Private IPs: %w", err) + } + } + + // Assign new IP addresses + assignIps := ns.Difference(os) + if assignIps.Len() != 0 { + input := &ec2.AssignPrivateIpAddressesInput{ + NetworkInterfaceId: primaryInterface.NetworkInterfaceId, + PrivateIpAddresses: expandStringSet(assignIps), + } + log.Printf("[INFO] Assigning secondary_private_ips on Instance %q", d.Id()) + _, err := conn.AssignPrivateIpAddresses(input) + if err != nil { + return fmt.Errorf("Failure to assign Secondary Private IPs: %w", err) + } + } } - if _, err := conn.ModifyNetworkInterfaceAttribute(&ec2.ModifyNetworkInterfaceAttributeInput{ - NetworkInterfaceId: primaryInterface.NetworkInterfaceId, - Groups: groups, - }); err != nil { - return err + if d.HasChange("vpc_security_group_ids") { + if primaryInterface.NetworkInterfaceId == nil { + return fmt.Errorf("Failed to update vpc_security_group_ids on %q, which does not contain a primary network interface", + d.Id()) + } + var groups []*string + if v := d.Get("vpc_security_group_ids").(*schema.Set); v.Len() > 0 { + for _, v := range v.List() { + groups = append(groups, aws.String(v.(string))) + } + } + + if len(groups) < 1 { + return fmt.Errorf("VPC-based instances require at least one security group to be attached.") + } + // 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()) + if _, err := conn.ModifyNetworkInterfaceAttribute(&ec2.ModifyNetworkInterfaceAttributeInput{ + NetworkInterfaceId: primaryInterface.NetworkInterfaceId, + Groups: groups, + }); err != nil { + return err + } } } @@ -1163,9 +1247,9 @@ func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error { } stateConf := &resource.StateChangeConf{ - Pending: []string{"pending", "stopped"}, - Target: []string{"running"}, - Refresh: InstanceStateRefreshFunc(conn, d.Id(), []string{"terminated"}), + Pending: []string{ec2.InstanceStateNamePending, ec2.InstanceStateNameStopped}, + Target: []string{ec2.InstanceStateNameRunning}, + Refresh: InstanceStateRefreshFunc(conn, d.Id(), []string{ec2.InstanceStateNameTerminated}), Timeout: d.Timeout(schema.TimeoutUpdate), Delay: 10 * time.Second, MinTimeout: 3 * time.Second, @@ -1283,6 +1367,15 @@ func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error { } if d.HasChange("root_block_device.0.iops") { if v, ok := d.Get("root_block_device.0.iops").(int); ok && v != 0 { + // Enforce IOPs usage with a valid volume type + // Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/12667 + if t, ok := d.Get("root_block_device.0.volume_type").(string); ok && t != ec2.VolumeTypeIo1 { + if t == "" { + // Volume defaults to gp2 + t = ec2.VolumeTypeGp2 + } + return fmt.Errorf("error updating instance: iops attribute not supported for type %s", t) + } modifyVolume = true input.Iops = aws.Int64(int64(v)) } @@ -1297,9 +1390,9 @@ func resourceAwsInstanceUpdate(d *schema.ResourceData, meta interface{}) error { // Optimization can take hours. e.g. a full 1 TiB drive takes approximately 6 hours to optimize, // according to https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-volume-modifications.html stateConf := &resource.StateChangeConf{ - Pending: []string{"modifying"}, - Target: []string{"completed", "optimizing"}, - Refresh: VolumeStateRefreshFunc(conn, volumeID, "failed"), + Pending: []string{ec2.VolumeModificationStateModifying}, + Target: []string{ec2.VolumeModificationStateCompleted, ec2.VolumeModificationStateOptimizing}, + Refresh: VolumeStateRefreshFunc(conn, volumeID, ec2.VolumeModificationStateFailed), Timeout: d.Timeout(schema.TimeoutUpdate), Delay: 30 * time.Second, MinTimeout: 30 * time.Second, @@ -1411,10 +1504,10 @@ func VolumeStateRefreshFunc(conn *ec2.EC2, volumeID, failState string) resource. func stringifyStateReason(sr *ec2.StateReason) string { if sr.Message != nil { - return *sr.Message + return aws.StringValue(sr.Message) } if sr.Code != nil { - return *sr.Code + return aws.StringValue(sr.Code) } return sr.String() @@ -1426,6 +1519,20 @@ func readBlockDevices(d *schema.ResourceData, instance *ec2.Instance, conn *ec2. return err } + // This handles cases where the root device block is of type "EBS" + // and #readBlockDevicesFromInstance only returns 1 reference to a block-device + // stored in ibds["root"] + if _, ok := d.GetOk("ebs_block_device"); ok { + if len(ibds["ebs"].([]map[string]interface{})) == 0 { + ebs := make(map[string]interface{}) + for k, v := range ibds["root"].(map[string]interface{}) { + ebs[k] = v + } + ebs["snapshot_id"] = ibds["snapshot_id"] + ibds["ebs"] = append(ibds["ebs"].([]map[string]interface{}), ebs) + } + } + if err := d.Set("ebs_block_device", ibds["ebs"]); err != nil { return err } @@ -1492,7 +1599,7 @@ func readBlockDevicesFromInstance(instance *ec2.Instance, conn *ec2.EC2) (map[st instanceBlockDevices := make(map[string]*ec2.InstanceBlockDeviceMapping) for _, bd := range instance.BlockDeviceMappings { if bd.Ebs != nil { - instanceBlockDevices[*bd.Ebs.VolumeId] = bd + instanceBlockDevices[aws.StringValue(bd.Ebs.VolumeId)] = bd } } @@ -1515,7 +1622,7 @@ func readBlockDevicesFromInstance(instance *ec2.Instance, conn *ec2.EC2) (map[st } for _, vol := range volResp.Volumes { - instanceBd := instanceBlockDevices[*vol.VolumeId] + instanceBd := instanceBlockDevices[aws.StringValue(vol.VolumeId)] bd := make(map[string]interface{}) bd["volume_id"] = aws.StringValue(vol.VolumeId) @@ -1552,6 +1659,13 @@ func readBlockDevicesFromInstance(instance *ec2.Instance, conn *ec2.EC2) (map[st blockDevices["ebs"] = append(blockDevices["ebs"].([]map[string]interface{}), bd) } } + // If we determine the root device is the only block device mapping + // in the instance (including ephemerals) after returning from this function, + // we'll need to set the ebs_block_device as a clone of the root device + // with the snapshot_id populated; thus, we store the ID for safe-keeping + if blockDevices["root"] != nil && len(blockDevices["ebs"].([]map[string]interface{})) == 0 { + blockDevices["snapshot_id"] = volResp.Volumes[0].SnapshotId + } return blockDevices, nil } @@ -1559,7 +1673,7 @@ func readBlockDevicesFromInstance(instance *ec2.Instance, conn *ec2.EC2) (map[st func blockDeviceIsRoot(bd *ec2.InstanceBlockDeviceMapping, instance *ec2.Instance) bool { return bd.DeviceName != nil && instance.RootDeviceName != nil && - *bd.DeviceName == *instance.RootDeviceName + aws.StringValue(bd.DeviceName) == aws.StringValue(instance.RootDeviceName) } func fetchRootDeviceName(ami string, conn *ec2.EC2) (*string, error) { @@ -1584,7 +1698,7 @@ func fetchRootDeviceName(ami string, conn *ec2.EC2) (*string, error) { rootDeviceName := image.RootDeviceName // Instance store backed AMIs do not provide a root device name. - if *image.RootDeviceType == ec2.DeviceTypeInstanceStore { + if aws.StringValue(image.RootDeviceType) == ec2.DeviceTypeInstanceStore { return nil, nil } @@ -1644,6 +1758,10 @@ func buildNetworkInterfaceOpts(d *schema.ResourceData, groups []*string, nInterf ni.PrivateIpAddress = aws.String(v.(string)) } + if v, ok := d.GetOk("secondary_private_ips"); ok && v.(*schema.Set).Len() > 0 { + ni.PrivateIpAddresses = expandSecondaryPrivateIPAddresses(v.(*schema.Set).List()) + } + if v, ok := d.GetOk("ipv6_address_count"); ok { ni.Ipv6AddressCount = aws.Int64(int64(v.(int))) } @@ -1714,13 +1832,17 @@ func readBlockDeviceMappingsFromConfig(d *schema.ResourceData, conn *ec2.EC2) ([ if v, ok := bd["volume_type"].(string); ok && v != "" { ebs.VolumeType = aws.String(v) - if ec2.VolumeTypeIo1 == strings.ToLower(v) { - // Condition: This parameter is required for requests to create io1 - // volumes; it is not used in requests to create gp2, st1, sc1, or - // standard volumes. - // See: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_EbsBlockDevice.html - if v, ok := bd["iops"].(int); ok && v > 0 { - ebs.Iops = aws.Int64(int64(v)) + if iops, ok := bd["iops"].(int); ok && iops > 0 { + if ec2.VolumeTypeIo1 == strings.ToLower(v) { + // Condition: This parameter is required for requests to create io1 + // volumes; it is not used in requests to create gp2, st1, sc1, or + // standard volumes. + // See: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_EbsBlockDevice.html + ebs.Iops = aws.Int64(int64(iops)) + } else { + // Enforce IOPs usage with a valid volume type + // Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/12667 + return nil, fmt.Errorf("error creating resource: iops attribute not supported for ebs_block_device with volume_type %s", v) } } } @@ -1776,18 +1898,20 @@ func readBlockDeviceMappingsFromConfig(d *schema.ResourceData, conn *ec2.EC2) ([ if v, ok := bd["volume_type"].(string); ok && v != "" { ebs.VolumeType = aws.String(v) - } - - if v, ok := bd["iops"].(int); ok && v > 0 && *ebs.VolumeType == "io1" { - // Only set the iops attribute if the volume type is io1. Setting otherwise - // can trigger a refresh/plan loop based on the computed value that is given - // from AWS, and prevent us from specifying 0 as a valid iops. - // See https://github.com/hashicorp/terraform/pull/4146 - // See https://github.com/hashicorp/terraform/issues/7765 - ebs.Iops = aws.Int64(int64(v)) - } else if v, ok := bd["iops"].(int); ok && v > 0 && *ebs.VolumeType != "io1" { - // Message user about incompatibility - log.Print("[WARN] IOPs is only valid for storate type io1 for EBS Volumes") + if iops, ok := bd["iops"].(int); ok && iops > 0 { + if ec2.VolumeTypeIo1 == strings.ToLower(v) { + // Only set the iops attribute if the volume type is io1. Setting otherwise + // can trigger a refresh/plan loop based on the computed value that is given + // from AWS, and prevent us from specifying 0 as a valid iops. + // See https://github.com/hashicorp/terraform/pull/4146 + // See https://github.com/hashicorp/terraform/issues/7765 + ebs.Iops = aws.Int64(int64(iops)) + } else { + // Enforce IOPs usage with a valid volume type + // Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/12667 + return nil, fmt.Errorf("error creating resource: iops attribute not supported for root_block_device with volume_type %s", v) + } + } } if dn, err := fetchRootDeviceName(d.Get("ami").(string), conn); err == nil { @@ -1835,22 +1959,22 @@ func readVolumeTags(conn *ec2.EC2, instanceId string) ([]*ec2.Tag, error) { // config determine which one to use in Plan and Apply. func readSecurityGroups(d *schema.ResourceData, instance *ec2.Instance, conn *ec2.EC2) error { // An instance with a subnet is in a VPC; an instance without a subnet is in EC2-Classic. - hasSubnet := instance.SubnetId != nil && *instance.SubnetId != "" + hasSubnet := aws.StringValue(instance.SubnetId) != "" useID, useName := hasSubnet, !hasSubnet // If the instance is in a VPC, find out if that VPC is Default to determine // whether to store names. - if instance.VpcId != nil && *instance.VpcId != "" { + if aws.StringValue(instance.VpcId) != "" { out, err := conn.DescribeVpcs(&ec2.DescribeVpcsInput{ VpcIds: []*string{instance.VpcId}, }) if err != nil { - log.Printf("[WARN] Unable to describe VPC %q: %s", *instance.VpcId, err) + log.Printf("[WARN] Unable to describe VPC %q: %s", aws.StringValue(instance.VpcId), err) } else if len(out.Vpcs) == 0 { // This may happen in Eucalyptus Cloud log.Printf("[WARN] Unable to retrieve VPCs") } else { - isInDefaultVpc := *out.Vpcs[0].IsDefault + isInDefaultVpc := aws.BoolValue(out.Vpcs[0].IsDefault) useName = isInDefaultVpc } } @@ -1859,7 +1983,7 @@ func readSecurityGroups(d *schema.ResourceData, instance *ec2.Instance, conn *ec if useID { sgs := make([]string, 0, len(instance.SecurityGroups)) for _, sg := range instance.SecurityGroups { - sgs = append(sgs, *sg.GroupId) + sgs = append(sgs, aws.StringValue(sg.GroupId)) } log.Printf("[DEBUG] Setting Security Group IDs: %#v", sgs) if err := d.Set("vpc_security_group_ids", sgs); err != nil { @@ -1873,7 +1997,7 @@ func readSecurityGroups(d *schema.ResourceData, instance *ec2.Instance, conn *ec if useName { sgs := make([]string, 0, len(instance.SecurityGroups)) for _, sg := range instance.SecurityGroups { - sgs = append(sgs, *sg.GroupName) + sgs = append(sgs, aws.StringValue(sg.GroupName)) } log.Printf("[DEBUG] Setting Security Group Names: %#v", sgs) if err := d.Set("security_groups", sgs); err != nil { @@ -1903,11 +2027,11 @@ func getAwsEc2InstancePasswordData(instanceID string, conn *ec2.EC2) (string, er return resource.NonRetryableError(err) } - if resp.PasswordData == nil || *resp.PasswordData == "" { + if resp.PasswordData == nil || aws.StringValue(resp.PasswordData) == "" { return resource.RetryableError(fmt.Errorf("Password data is blank for instance ID: %s", instanceID)) } - passwordData = strings.TrimSpace(*resp.PasswordData) + passwordData = strings.TrimSpace(aws.StringValue(resp.PasswordData)) log.Printf("[INFO] Password data read for instance %s", instanceID) return nil @@ -1917,10 +2041,10 @@ func getAwsEc2InstancePasswordData(instanceID string, conn *ec2.EC2) (string, er if err != nil { return "", fmt.Errorf("Error getting password data: %s", err) } - if resp.PasswordData == nil || *resp.PasswordData == "" { + if resp.PasswordData == nil || aws.StringValue(resp.PasswordData) == "" { return "", fmt.Errorf("Password data is blank for instance ID: %s", instanceID) } - passwordData = strings.TrimSpace(*resp.PasswordData) + passwordData = strings.TrimSpace(aws.StringValue(resp.PasswordData)) } if err != nil { return "", err @@ -1955,8 +2079,7 @@ type awsInstanceOpts struct { MetadataOptions *ec2.InstanceMetadataOptionsRequest } -func buildAwsInstanceOpts( - d *schema.ResourceData, meta interface{}) (*awsInstanceOpts, error) { +func buildAwsInstanceOpts(d *schema.ResourceData, meta interface{}) (*awsInstanceOpts, error) { conn := meta.(*AWSClient).ec2conn instanceType := d.Get("instance_type").(string) @@ -2082,7 +2205,7 @@ func buildAwsInstanceOpts( opts.PrivateIPAddress = aws.String(v.(string)) } if opts.SubnetID != nil && - *opts.SubnetID != "" { + aws.StringValue(opts.SubnetID) != "" { opts.SecurityGroupIDs = groups } else { opts.SecurityGroups = groups @@ -2132,7 +2255,7 @@ func awsTerminateInstance(conn *ec2.EC2, id string, timeout time.Duration) error InstanceIds: []*string{aws.String(id)}, } if _, err := conn.TerminateInstances(req); err != nil { - if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidInstanceID.NotFound" { + if isAWSErr(err, "InvalidInstanceID.NotFound", "") { return nil } return err @@ -2145,8 +2268,9 @@ func waitForInstanceStopping(conn *ec2.EC2, id string, timeout time.Duration) er log.Printf("[DEBUG] Waiting for instance (%s) to become stopped", id) stateConf := &resource.StateChangeConf{ - Pending: []string{"pending", "running", "shutting-down", "stopped", "stopping"}, - Target: []string{"stopped"}, + Pending: []string{ec2.InstanceStateNamePending, ec2.InstanceStateNameRunning, + ec2.InstanceStateNameShuttingDown, ec2.InstanceStateNameStopped, ec2.InstanceStateNameStopping}, + Target: []string{ec2.InstanceStateNameStopped}, Refresh: InstanceStateRefreshFunc(conn, id, []string{}), Timeout: timeout, Delay: 10 * time.Second, @@ -2166,8 +2290,9 @@ func waitForInstanceDeletion(conn *ec2.EC2, id string, timeout time.Duration) er log.Printf("[DEBUG] Waiting for instance (%s) to become terminated", id) stateConf := &resource.StateChangeConf{ - Pending: []string{"pending", "running", "shutting-down", "stopped", "stopping"}, - Target: []string{"terminated"}, + Pending: []string{ec2.InstanceStateNamePending, ec2.InstanceStateNameRunning, + ec2.InstanceStateNameShuttingDown, ec2.InstanceStateNameStopped, ec2.InstanceStateNameStopping}, + Target: []string{ec2.InstanceStateNameTerminated}, Refresh: InstanceStateRefreshFunc(conn, id, []string{}), Timeout: timeout, Delay: 10 * time.Second, @@ -2187,7 +2312,7 @@ func iamInstanceProfileArnToName(ip *ec2.IamInstanceProfile) string { if ip == nil || ip.Arn == nil { return "" } - parts := strings.Split(*ip.Arn, "/") + parts := strings.Split(aws.StringValue(ip.Arn), "/") return parts[len(parts)-1] } @@ -2267,6 +2392,19 @@ func expandEc2InstanceMetadataOptions(l []interface{}) *ec2.InstanceMetadataOpti return opts } +//Expands an array of secondary Private IPs into a ec2 Private IP Address Spec +func expandSecondaryPrivateIPAddresses(ips []interface{}) []*ec2.PrivateIpAddressSpecification { + specs := make([]*ec2.PrivateIpAddressSpecification, 0, len(ips)) + for _, v := range ips { + spec := &ec2.PrivateIpAddressSpecification{ + PrivateIpAddress: aws.String(v.(string)), + } + + specs = append(specs, spec) + } + return specs +} + func flattenEc2InstanceMetadataOptions(opts *ec2.InstanceMetadataOptionsResponse) []interface{} { if opts == nil { return nil diff --git a/aws/resource_aws_instance_migrate.go b/aws/resource_aws_instance_migrate.go index 17065d1e79c..e53b7d57695 100644 --- a/aws/resource_aws_instance_migrate.go +++ b/aws/resource_aws_instance_migrate.go @@ -6,8 +6,8 @@ import ( "strconv" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsInstanceMigrateState( @@ -45,9 +45,7 @@ func migrateAwsInstanceStateV0toV1(is *terraform.InstanceState) (*terraform.Inst is.Attributes["root_block_device.#"] = "0" } for _, oldBd := range oldBds { - if err := writeV1BlockDevice(is, oldBd); err != nil { - return is, err - } + writeV1BlockDevice(is, oldBd) } log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes) return is, nil @@ -76,7 +74,7 @@ func readV0BlockDevices(is *terraform.InstanceState) (map[string]map[string]stri } func writeV1BlockDevice( - is *terraform.InstanceState, oldBd map[string]string) error { + is *terraform.InstanceState, oldBd map[string]string) { code := hashcode.String(oldBd["device_name"]) bdType := "ebs_block_device" if vn, ok := oldBd["virtual_name"]; ok && strings.HasPrefix(vn, "ephemeral") { @@ -107,5 +105,4 @@ func writeV1BlockDevice( countAttr := fmt.Sprintf("%s.#", bdType) count, _ := strconv.Atoi(is.Attributes[countAttr]) is.Attributes[countAttr] = strconv.Itoa(count + 1) - return nil } diff --git a/aws/resource_aws_instance_migrate_test.go b/aws/resource_aws_instance_migrate_test.go index 839a018dbec..ee1de39a583 100644 --- a/aws/resource_aws_instance_migrate_test.go +++ b/aws/resource_aws_instance_migrate_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAWSInstanceMigrateState(t *testing.T) { diff --git a/aws/resource_aws_instance_test.go b/aws/resource_aws_instance_test.go index 8112fb11024..dcf2648a2f8 100644 --- a/aws/resource_aws_instance_test.go +++ b/aws/resource_aws_instance_test.go @@ -6,6 +6,7 @@ import ( "os" "reflect" "regexp" + "strconv" "strings" "testing" "time" @@ -14,16 +15,21 @@ import ( "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { resource.AddTestSweepers("aws_instance", &resource.Sweeper{ Name: "aws_instance", F: testSweepInstances, + Dependencies: []string{ + "aws_autoscaling_group", + "aws_spot_fleet_request", + }, }) } @@ -230,26 +236,40 @@ func TestAccAWSInstance_inEc2Classic(t *testing.T) { func TestAccAWSInstance_basic(t *testing.T) { var v ec2.Instance - var vol *ec2.Volume resourceName := "aws_instance.test" - rInt := acctest.RandInt() - - testCheck := func(rInt int) func(*terraform.State) error { - return func(*terraform.State) error { - if *v.Placement.AvailabilityZone != "us-west-2a" { - return fmt.Errorf("bad availability zone: %#v", *v.Placement.AvailabilityZone) - } - if len(v.SecurityGroups) == 0 { - return fmt.Errorf("no security groups: %#v", v.SecurityGroups) - } - if *v.SecurityGroups[0].GroupName != fmt.Sprintf("tf_test_%d", rInt) { - return fmt.Errorf("no security groups: %#v", v.SecurityGroups) - } + resource.ParallelTest(t, resource.TestCase{ + // No subnet_id specified requires default VPC with default subnets or EC2-Classic. + PreCheck: func() { + testAccPreCheck(t) + testAccPreCheckEc2ClassicOrHasDefaultVpcWithDefaultSubnets(t) + }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfigBasic(), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`instance/i-[a-z0-9]+`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + // Required for EC2-Classic. + ImportStateVerifyIgnore: []string{"source_dest_check"}, + }, + }, + }) +} - return nil - } - } +func TestAccAWSInstance_atLeastOneOtherEbsVolume(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -257,25 +277,10 @@ func TestAccAWSInstance_basic(t *testing.T) { Providers: testAccProviders, CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ - // Create a volume to cover https://github.com/hashicorp/terraform/issues/1249 - { - // Need a resource in this config so the provisioner will be available - Config: testAccInstanceConfig_pre(rInt), - Check: func(*terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - var err error - vol, err = conn.CreateVolume(&ec2.CreateVolumeInput{ - AvailabilityZone: aws.String("us-west-2a"), - Size: aws.Int64(int64(5)), - }) - return err - }, - }, { - Config: testAccInstanceConfig(rInt), + Config: testAccInstanceConfigAtLeastOneOtherEbsVolume(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), - testCheck(rInt), resource.TestCheckResourceAttr(resourceName, "user_data", "3dc39dda39be1205215e776bad998da361a5955d"), resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "0"), // This is an instance store AMI resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "0"), @@ -292,23 +297,13 @@ func TestAccAWSInstance_basic(t *testing.T) { // that the user data hash stuff is working without generating // an incorrect diff. { - Config: testAccInstanceConfig(rInt), + Config: testAccInstanceConfigAtLeastOneOtherEbsVolume(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), - testCheck(rInt), resource.TestCheckResourceAttr(resourceName, "user_data", "3dc39dda39be1205215e776bad998da361a5955d"), resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "0"), ), }, - // Clean up volume created above - { - Config: testAccInstanceConfig(rInt), - Check: func(*terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - _, err := conn.DeleteVolume(&ec2.DeleteVolumeInput{VolumeId: vol.VolumeId}) - return err - }, - }, }, }) } @@ -319,17 +314,19 @@ func TestAccAWSInstance_EbsBlockDevice_KmsKeyArn(t *testing.T) { resourceName := "aws_instance.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckInstanceDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigEbsBlockDeviceKmsKeyArn, + Config: testAccInstanceConfigEbsBlockDeviceKmsKeyArn(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance), resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2634515331.encrypted", "true"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "encrypted": "true", + }), + // TODO: TypeSet check implement attr pair helper resource.TestCheckResourceAttrPair(resourceName, "ebs_block_device.2634515331.kms_key_id", kmsKeyResourceName, "arn"), ), }, @@ -337,10 +334,27 @@ func TestAccAWSInstance_EbsBlockDevice_KmsKeyArn(t *testing.T) { }) } +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/12667 +func TestAccAWSInstance_EbsBlockDevice_InvalidIopsForVolumeType(t *testing.T) { + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckInstanceConfigEBSBlockDeviceInvalidIops, + ExpectError: regexp.MustCompile(`error creating resource: iops attribute not supported for ebs_block_device with volume_type gp2`), + }, + }, + }) +} + func TestAccAWSInstance_RootBlockDevice_KmsKeyArn(t *testing.T) { var instance ec2.Instance kmsKeyResourceName := "aws_kms_key.test" resourceName := "aws_instance.test" + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -348,7 +362,7 @@ func TestAccAWSInstance_RootBlockDevice_KmsKeyArn(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigRootBlockDeviceKmsKeyArn, + Config: testAccInstanceConfigRootBlockDeviceKmsKeyArn(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &instance), resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), @@ -368,7 +382,7 @@ func TestAccAWSInstance_RootBlockDevice_KmsKeyArn(t *testing.T) { func TestAccAWSInstance_userDataBase64(t *testing.T) { var v ec2.Instance resourceName := "aws_instance.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -377,7 +391,7 @@ func TestAccAWSInstance_userDataBase64(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithUserDataBase64(rInt), + Config: testAccInstanceConfigWithUserDataBase64(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "user_data_base64", "aGVsbG8gd29ybGQ="), @@ -407,8 +421,8 @@ func TestAccAWSInstance_GP2IopsDevice(t *testing.T) { } // Check if the root block device exists. - if _, ok := blockDevices["/dev/sda1"]; !ok { - return fmt.Errorf("block device doesn't exist: /dev/sda1") + if _, ok := blockDevices["/dev/xvda"]; !ok { + return fmt.Errorf("block device doesn't exist: /dev/xvda") } return nil @@ -423,7 +437,7 @@ func TestAccAWSInstance_GP2IopsDevice(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceGP2IopsDevice, + Config: testAccInstanceGP2IopsDevice(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), @@ -442,30 +456,19 @@ func TestAccAWSInstance_GP2IopsDevice(t *testing.T) { }) } +// TestAccAWSInstance_GP2WithIopsValue updated in v3.0.0 +// to account for apply-time validation of the root_block_device.iops attribute for supported volume types +// Reference: https://github.com/terraform-providers/terraform-provider-aws/pull/14310 func TestAccAWSInstance_GP2WithIopsValue(t *testing.T) { - var v ec2.Instance - resourceName := "aws_instance.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - IDRefreshIgnore: []string{"ephemeral_block_device", "user_data"}, - Providers: testAccProviders, - CheckDestroy: testAccCheckInstanceDestroy, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceGP2WithIopsValue, - Check: testAccCheckInstanceExists(resourceName, &v), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - { - Config: testAccInstanceGP2WithIopsValue, - PlanOnly: true, - ExpectNonEmptyPlan: false, + Config: testAccInstanceGP2WithIopsValue(), + ExpectError: regexp.MustCompile(`error creating resource: iops attribute not supported for root_block_device with volume_type gp2`), }, }, }) @@ -485,8 +488,8 @@ func TestAccAWSInstance_blockDevices(t *testing.T) { } // Check if the root block device exists. - if _, ok := blockDevices["/dev/sda1"]; !ok { - return fmt.Errorf("block device doesn't exist: /dev/sda1") + if _, ok := blockDevices["/dev/xvda"]; !ok { + return fmt.Errorf("block device doesn't exist: /dev/xvda") } // Check if the secondary block device exists. @@ -511,12 +514,11 @@ func TestAccAWSInstance_blockDevices(t *testing.T) { rootVolumeSize := "11" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - IDRefreshIgnore: []string{"ephemeral_block_device"}, - Providers: testAccProviders, - CheckDestroy: testAccCheckInstanceDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + IDRefreshIgnore: []string{"ephemeral_block_device"}, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { Config: testAccAwsEc2InstanceConfigBlockDevices(rootVolumeSize), @@ -527,22 +529,33 @@ func TestAccAWSInstance_blockDevices(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", rootVolumeSize), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_type", "gp2"), resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "3"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2576023345.device_name", "/dev/sdb"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "device_name": "/dev/sdb", + "volume_size": "9", + "volume_type": "gp2", + }), + // TODO: TypeSet check develop regex support resource.TestMatchResourceAttr(resourceName, "ebs_block_device.2576023345.volume_id", regexp.MustCompile("vol-[a-z0-9]+")), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2576023345.volume_size", "9"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2576023345.volume_type", "gp2"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2554893574.device_name", "/dev/sdc"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "device_name": "/dev/sdc", + "volume_size": "10", + "volume_type": "io1", + "iops": "100", + }), + // TODO: TypeSet check develop regex support resource.TestMatchResourceAttr(resourceName, "ebs_block_device.2554893574.volume_id", regexp.MustCompile("vol-[a-z0-9]+")), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2554893574.volume_size", "10"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2554893574.volume_type", "io1"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2554893574.iops", "100"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2634515331.device_name", "/dev/sdd"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "device_name": "/dev/sdd", + "encrypted": "true", + "volume_size": "12", + }), + // TODO: TypeSet check develop regex support resource.TestMatchResourceAttr(resourceName, "ebs_block_device.2634515331.volume_id", regexp.MustCompile("vol-[a-z0-9]+")), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2634515331.encrypted", "true"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2634515331.volume_size", "12"), resource.TestCheckResourceAttr(resourceName, "ephemeral_block_device.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ephemeral_block_device.1692014856.device_name", "/dev/sde"), - resource.TestCheckResourceAttr(resourceName, "ephemeral_block_device.1692014856.virtual_name", "ephemeral0"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ephemeral_block_device.*", map[string]string{ + "device_name": "/dev/sde", + "virtual_name": "ephemeral0", + }), testCheck(), ), }, @@ -567,23 +580,11 @@ func TestAccAWSInstance_rootInstanceStore(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: ` - resource "aws_instance" "test" { - # us-west-2 - # Amazon Linux HVM Instance Store 64-bit (2016.09.0) - # https://aws.amazon.com/amazon-linux-ami - ami = "ami-44c36524" - - # Only certain instance types support ephemeral root instance stores. - # http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html - instance_type = "m3.medium" - }`, + Config: testAccInstanceConfigRootInstanceStore(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "ami", "ami-44c36524"), resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "0"), resource.TestCheckResourceAttr(resourceName, "ebs_optimized", "false"), - resource.TestCheckResourceAttr(resourceName, "instance_type", "m3.medium"), resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "0"), ), }, @@ -628,48 +629,30 @@ func TestAccAWSInstance_noAMIEphemeralDevices(t *testing.T) { } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - IDRefreshIgnore: []string{"ephemeral_block_device"}, - Providers: testAccProviders, - CheckDestroy: testAccCheckInstanceDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + IDRefreshIgnore: []string{"ephemeral_block_device"}, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: ` - resource "aws_instance" "test" { - # us-west-2 - ami = "ami-01f05461" // This AMI (Ubuntu) contains two ephemerals - - instance_type = "c3.large" - - root_block_device { - volume_type = "gp2" - volume_size = 11 - } - ephemeral_block_device { - device_name = "/dev/sdb" - no_device = true - } - ephemeral_block_device { - device_name = "/dev/sdc" - no_device = true - } - }`, + Config: testAccInstanceConfigNoAMIEphemeralDevices(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "ami", "ami-01f05461"), resource.TestCheckResourceAttr(resourceName, "ebs_optimized", "false"), - resource.TestCheckResourceAttr(resourceName, "instance_type", "c3.large"), resource.TestCheckResourceAttr(resourceName, "root_block_device.#", "1"), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", "11"), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_type", "gp2"), resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "0"), resource.TestCheckResourceAttr(resourceName, "ephemeral_block_device.#", "2"), - resource.TestCheckResourceAttr(resourceName, "ephemeral_block_device.172787947.device_name", "/dev/sdb"), - resource.TestCheckResourceAttr(resourceName, "ephemeral_block_device.172787947.no_device", "true"), - resource.TestCheckResourceAttr(resourceName, "ephemeral_block_device.3336996981.device_name", "/dev/sdc"), - resource.TestCheckResourceAttr(resourceName, "ephemeral_block_device.3336996981.no_device", "true"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ephemeral_block_device.*", map[string]string{ + "device_name": "/dev/sdb", + "no_device": "true", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ephemeral_block_device.*", map[string]string{ + "device_name": "/dev/sdc", + "no_device": "true", + }), testCheck(), ), }, @@ -820,30 +803,21 @@ func TestAccAWSInstance_vpc(t *testing.T) { func TestAccAWSInstance_outpost(t *testing.T) { var v ec2.Instance + outpostDataSourceName := "data.aws_outposts_outpost.test" resourceName := "aws_instance.test" - outpostArn := os.Getenv("AWS_OUTPOST_ARN") - if outpostArn == "" { - t.Skip( - "Environment variable AWS_OUTPOST_ARN is not set. " + - "This environment variable must be set to the ARN of " + - "a deployed Outpost to enable this test.") - } - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) }, IDRefreshName: resourceName, IDRefreshIgnore: []string{"associate_public_ip_address"}, Providers: testAccProviders, CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigOutpost(outpostArn), + Config: testAccInstanceConfigOutpost(), Check: resource.ComposeTestCheckFunc( - testAccCheckInstanceExists( - resourceName, &v), - resource.TestCheckResourceAttr( - resourceName, "outpost_arn", outpostArn), + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttrPair(resourceName, "outpost_arn", outpostDataSourceName, "arn"), ), }, { @@ -960,7 +934,7 @@ func TestAccAWSInstance_multipleRegions(t *testing.T) { var providers []*schema.Provider resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, + PreCheck: func() { testAccPreCheck(t); testAccPartitionPreCheck(t, "aws") }, ProviderFactories: testAccProviderFactories(&providers), CheckDestroy: testAccCheckWithProviders(testAccCheckInstanceDestroyWithProvider, &providers), Steps: []resource.TestStep{ @@ -1077,7 +1051,7 @@ func TestAccAWSInstance_tags(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckInstanceConfigTags, + Config: testAccCheckInstanceConfigTags(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1090,7 +1064,7 @@ func TestAccAWSInstance_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCheckInstanceConfigTagsUpdate, + Config: testAccCheckInstanceConfigTagsUpdate(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -1111,7 +1085,7 @@ func TestAccAWSInstance_volumeTags(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckInstanceConfigNoVolumeTags, + Config: testAccCheckInstanceConfigNoVolumeTags(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckNoResourceAttr(resourceName, "volume_tags"), @@ -1124,7 +1098,7 @@ func TestAccAWSInstance_volumeTags(t *testing.T) { ImportStateVerifyIgnore: []string{"ephemeral_block_device"}, }, { - Config: testAccCheckInstanceConfigWithVolumeTags, + Config: testAccCheckInstanceConfigWithVolumeTags(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "volume_tags.%", "1"), @@ -1132,7 +1106,7 @@ func TestAccAWSInstance_volumeTags(t *testing.T) { ), }, { - Config: testAccCheckInstanceConfigWithVolumeTagsUpdate, + Config: testAccCheckInstanceConfigWithVolumeTagsUpdate(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "volume_tags.%", "2"), @@ -1141,7 +1115,7 @@ func TestAccAWSInstance_volumeTags(t *testing.T) { ), }, { - Config: testAccCheckInstanceConfigNoVolumeTags, + Config: testAccCheckInstanceConfigNoVolumeTags(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckNoResourceAttr(resourceName, "volume_tags"), @@ -1161,7 +1135,7 @@ func TestAccAWSInstance_volumeTagsComputed(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckInstanceConfigWithAttachedVolume, + Config: testAccCheckInstanceConfigWithAttachedVolume(), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), ), @@ -1344,6 +1318,45 @@ func TestAccAWSInstance_associatePublicIPAndPrivateIP(t *testing.T) { }) } +// Allow Empty Private IP +// https://github.com/terraform-providers/terraform-provider-aws/issues/13626 +func TestAccAWSInstance_Empty_PrivateIP(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + + testCheckPrivateIP := func() resource.TestCheckFunc { + return func(*terraform.State) error { + if aws.StringValue(v.PrivateIpAddress) == "" { + return fmt.Errorf("bad computed private IP: %s", aws.StringValue(v.PrivateIpAddress)) + } + + return nil + } + } + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfigEmptyPrivateIP(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + testCheckPrivateIP(), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + // Guard against regression with KeyPairs // https://github.com/hashicorp/terraform/issues/2302 func TestAccAWSInstance_keyPairCheck(t *testing.T) { @@ -1385,10 +1398,10 @@ func TestAccAWSInstance_keyPairCheck(t *testing.T) { func TestAccAWSInstance_rootBlockDeviceMismatch(t *testing.T) { var v ec2.Instance resourceName := "aws_instance.test" - rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, + PreCheck: func() { testAccPreCheck(t); testAccRegionPreCheck(t, "us-west-2") }, Providers: testAccProviders, CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ @@ -1456,6 +1469,7 @@ func TestAccAWSInstance_changeInstanceType(t *testing.T) { var before ec2.Instance var after ec2.Instance resourceName := "aws_instance.test" + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -1463,7 +1477,7 @@ func TestAccAWSInstance_changeInstanceType(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfigWithSmallInstanceType, + Config: testAccInstanceConfigWithSmallInstanceType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &before), ), @@ -1474,7 +1488,7 @@ func TestAccAWSInstance_changeInstanceType(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccInstanceConfigUpdateInstanceType, + Config: testAccInstanceConfigUpdateInstanceType(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &after), testAccCheckInstanceNotRecreated(t, &before, &after), @@ -1725,19 +1739,24 @@ func TestAccAWSInstance_EbsRootDevice_MultipleBlockDevices_ModifySize(t *testing updatedRootVolumeSize := "14" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckInstanceDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { Config: testAccAwsEc2InstanceConfigBlockDevicesWithDeleteOnTerminate(originalRootVolumeSize, deleteOnTermination), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", originalRootVolumeSize), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2576023345.volume_size", "9"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2554893574.volume_size", "10"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2634515331.volume_size", "12"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "9", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "10", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "12", + }), ), }, { @@ -1746,9 +1765,15 @@ func TestAccAWSInstance_EbsRootDevice_MultipleBlockDevices_ModifySize(t *testing testAccCheckInstanceExists(resourceName, &after), testAccCheckInstanceNotRecreated(t, &before, &after), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", updatedRootVolumeSize), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2576023345.volume_size", "9"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2554893574.volume_size", "10"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2634515331.volume_size", "12"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "9", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "10", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "12", + }), ), }, }, @@ -1766,10 +1791,9 @@ func TestAccAWSInstance_EbsRootDevice_MultipleBlockDevices_ModifyDeleteOnTermina updatedDeleteOnTermination := "true" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckInstanceDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { Config: testAccAwsEc2InstanceConfigBlockDevicesWithDeleteOnTerminate(rootVolumeSize, originalDeleteOnTermination), @@ -1777,9 +1801,15 @@ func TestAccAWSInstance_EbsRootDevice_MultipleBlockDevices_ModifyDeleteOnTermina testAccCheckInstanceExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", rootVolumeSize), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.delete_on_termination", originalDeleteOnTermination), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2576023345.volume_size", "9"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2554893574.volume_size", "10"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2634515331.volume_size", "12"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "9", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "10", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "12", + }), ), }, { @@ -1789,11 +1819,68 @@ func TestAccAWSInstance_EbsRootDevice_MultipleBlockDevices_ModifyDeleteOnTermina testAccCheckInstanceNotRecreated(t, &before, &after), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.volume_size", rootVolumeSize), resource.TestCheckResourceAttr(resourceName, "root_block_device.0.delete_on_termination", updatedDeleteOnTermination), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2576023345.volume_size", "9"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2554893574.volume_size", "10"), - resource.TestCheckResourceAttr(resourceName, "ebs_block_device.2634515331.volume_size", "12"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "9", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "10", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "volume_size": "12", + }), + ), + }, + }, + }) +} + +// Test to validate fix for GH-ISSUE #1318 (dynamic ebs_block_devices forcing replacement after state refresh) +func TestAccAWSInstance_EbsRootDevice_MultipleDynamicEBSBlockDevices(t *testing.T) { + var instance ec2.Instance + + resourceName := "aws_instance.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsEc2InstanceConfigDynamicEBSBlockDevices(), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &instance), + resource.TestCheckResourceAttr(resourceName, "ebs_block_device.#", "3"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "delete_on_termination": "true", + "device_name": "/dev/sdc", + "encrypted": "false", + "iops": "100", + "volume_size": "10", + "volume_type": "gp2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "delete_on_termination": "true", + "device_name": "/dev/sdb", + "encrypted": "false", + "iops": "100", + "volume_size": "10", + "volume_type": "gp2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_block_device.*", map[string]string{ + "delete_on_termination": "true", + "device_name": "/dev/sda", + "encrypted": "false", + "iops": "100", + "volume_size": "10", + "volume_type": "gp2", + }), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, }, }) } @@ -1934,11 +2021,11 @@ func TestAccAWSInstance_addSecurityGroupNetworkInterface(t *testing.T) { }) } -// https://github.com/terraform-providers/terraform-provider-aws/issues/227 -func TestAccAWSInstance_associatePublic_defaultPrivate(t *testing.T) { +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/7063 +func TestAccAWSInstance_NewNetworkInterface_PublicIPAndSecondaryPrivateIPs(t *testing.T) { var v ec2.Instance resourceName := "aws_instance.test" - rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -1946,11 +2033,21 @@ func TestAccAWSInstance_associatePublic_defaultPrivate(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_defaultPrivate(rName), + Config: testAccInstanceConfigPublicAndPrivateSecondaryIPs(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), + resource.TestCheckResourceAttrSet(resourceName, "public_ip"), + resource.TestCheckResourceAttr(resourceName, "secondary_private_ips.#", "2"), + ), + }, + { + Config: testAccInstanceConfigPublicAndPrivateSecondaryIPs(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "false"), resource.TestCheckResourceAttr(resourceName, "public_ip", ""), + resource.TestCheckResourceAttr(resourceName, "secondary_private_ips.#", "2"), ), }, { @@ -1962,11 +2059,12 @@ func TestAccAWSInstance_associatePublic_defaultPrivate(t *testing.T) { }) } -// https://github.com/terraform-providers/terraform-provider-aws/issues/227 -func TestAccAWSInstance_associatePublic_defaultPublic(t *testing.T) { +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/7063 +func TestAccAWSInstance_NewNetworkInterface_EmptyPrivateIPAndSecondaryPrivateIPs(t *testing.T) { var v ec2.Instance resourceName := "aws_instance.test" - rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + rName := acctest.RandomWithPrefix("tf-acc-test") + secondaryIPs := fmt.Sprintf("%q, %q", "10.1.1.42", "10.1.1.43") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -1974,11 +2072,11 @@ func TestAccAWSInstance_associatePublic_defaultPublic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_defaultPublic(rName), + Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, "", secondaryIPs), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), - resource.TestCheckResourceAttrSet(resourceName, "public_ip"), + resource.TestCheckResourceAttrSet(resourceName, "private_ip"), + resource.TestCheckResourceAttr(resourceName, "secondary_private_ips.#", "2"), ), }, { @@ -1990,11 +2088,13 @@ func TestAccAWSInstance_associatePublic_defaultPublic(t *testing.T) { }) } -// https://github.com/terraform-providers/terraform-provider-aws/issues/227 -func TestAccAWSInstance_associatePublic_explicitPublic(t *testing.T) { +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/7063 +func TestAccAWSInstance_NewNetworkInterface_EmptyPrivateIPAndSecondaryPrivateIPsUpdate(t *testing.T) { var v ec2.Instance resourceName := "aws_instance.test" - rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + rName := acctest.RandomWithPrefix("tf-acc-test") + secondaryIP := fmt.Sprintf("%q", "10.1.1.42") + secondaryIPs := fmt.Sprintf("%s, %q", secondaryIP, "10.1.1.43") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -2002,11 +2102,27 @@ func TestAccAWSInstance_associatePublic_explicitPublic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_explicitPublic(rName), + Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, "", secondaryIPs), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), - resource.TestCheckResourceAttrSet(resourceName, "public_ip"), + resource.TestCheckResourceAttrSet(resourceName, "private_ip"), + resource.TestCheckResourceAttr(resourceName, "secondary_private_ips.#", "2"), + ), + }, + { + Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, "", ""), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttrSet(resourceName, "private_ip"), + resource.TestCheckResourceAttr(resourceName, "secondary_private_ips.#", "0"), + ), + }, + { + Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, "", secondaryIP), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttrSet(resourceName, "private_ip"), + resource.TestCheckResourceAttr(resourceName, "secondary_private_ips.#", "1"), ), }, { @@ -2018,11 +2134,13 @@ func TestAccAWSInstance_associatePublic_explicitPublic(t *testing.T) { }) } -// https://github.com/terraform-providers/terraform-provider-aws/issues/227 -func TestAccAWSInstance_associatePublic_explicitPrivate(t *testing.T) { +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/7063 +func TestAccAWSInstance_NewNetworkInterface_PrivateIPAndSecondaryPrivateIPs(t *testing.T) { var v ec2.Instance resourceName := "aws_instance.test" - rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + rName := acctest.RandomWithPrefix("tf-acc-test") + privateIP := "10.1.1.42" + secondaryIPs := fmt.Sprintf("%q, %q", "10.1.1.43", "10.1.1.44") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -2030,11 +2148,11 @@ func TestAccAWSInstance_associatePublic_explicitPrivate(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_explicitPrivate(rName), + Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, privateIP, secondaryIPs), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "false"), - resource.TestCheckResourceAttr(resourceName, "public_ip", ""), + resource.TestCheckResourceAttr(resourceName, "private_ip", privateIP), + resource.TestCheckResourceAttr(resourceName, "secondary_private_ips.#", "2"), ), }, { @@ -2046,11 +2164,14 @@ func TestAccAWSInstance_associatePublic_explicitPrivate(t *testing.T) { }) } -// https://github.com/terraform-providers/terraform-provider-aws/issues/227 -func TestAccAWSInstance_associatePublic_overridePublic(t *testing.T) { +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/7063 +func TestAccAWSInstance_NewNetworkInterface_PrivateIPAndSecondaryPrivateIPsUpdate(t *testing.T) { var v ec2.Instance resourceName := "aws_instance.test" - rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + rName := acctest.RandomWithPrefix("tf-acc-test") + privateIP := "10.1.1.42" + secondaryIP := fmt.Sprintf("%q", "10.1.1.43") + secondaryIPs := fmt.Sprintf("%s, %q", secondaryIP, "10.1.1.44") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -2058,11 +2179,27 @@ func TestAccAWSInstance_associatePublic_overridePublic(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_overridePublic(rName), + Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, privateIP, secondaryIPs), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), - resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), - resource.TestCheckResourceAttrSet(resourceName, "public_ip"), + resource.TestCheckResourceAttr(resourceName, "private_ip", privateIP), + resource.TestCheckResourceAttr(resourceName, "secondary_private_ips.#", "2"), + ), + }, + { + Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, privateIP, ""), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttrSet(resourceName, "private_ip"), + resource.TestCheckResourceAttr(resourceName, "secondary_private_ips.#", "0"), + ), + }, + { + Config: testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, privateIP, secondaryIP), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "private_ip", privateIP), + resource.TestCheckResourceAttr(resourceName, "secondary_private_ips.#", "1"), ), }, { @@ -2075,7 +2212,7 @@ func TestAccAWSInstance_associatePublic_overridePublic(t *testing.T) { } // https://github.com/terraform-providers/terraform-provider-aws/issues/227 -func TestAccAWSInstance_associatePublic_overridePrivate(t *testing.T) { +func TestAccAWSInstance_associatePublic_defaultPrivate(t *testing.T) { var v ec2.Instance resourceName := "aws_instance.test" rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) @@ -2086,7 +2223,7 @@ func TestAccAWSInstance_associatePublic_overridePrivate(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_associatePublic_overridePrivate(rName), + Config: testAccInstanceConfig_associatePublic_defaultPrivate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckInstanceExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "false"), @@ -2102,8 +2239,9 @@ func TestAccAWSInstance_associatePublic_overridePrivate(t *testing.T) { }) } -func TestAccAWSInstance_getPasswordData_falseToTrue(t *testing.T) { - var before, after ec2.Instance +// https://github.com/terraform-providers/terraform-provider-aws/issues/227 +func TestAccAWSInstance_associatePublic_defaultPublic(t *testing.T) { + var v ec2.Instance resourceName := "aws_instance.test" rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) @@ -2113,11 +2251,11 @@ func TestAccAWSInstance_getPasswordData_falseToTrue(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_getPasswordData(rName, false), + Config: testAccInstanceConfig_associatePublic_defaultPublic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckInstanceExists(resourceName, &before), - resource.TestCheckResourceAttr(resourceName, "get_password_data", "false"), - resource.TestCheckResourceAttr(resourceName, "password_data", ""), + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), + resource.TestCheckResourceAttrSet(resourceName, "public_ip"), ), }, { @@ -2125,21 +2263,13 @@ func TestAccAWSInstance_getPasswordData_falseToTrue(t *testing.T) { ImportState: true, ImportStateVerify: true, }, - { - Config: testAccInstanceConfig_getPasswordData(rName, true), - Check: resource.ComposeTestCheckFunc( - testAccCheckInstanceExists(resourceName, &after), - testAccCheckInstanceNotRecreated(t, &before, &after), - resource.TestCheckResourceAttr(resourceName, "get_password_data", "true"), - resource.TestCheckResourceAttrSet(resourceName, "password_data"), - ), - }, }, }) } -func TestAccAWSInstance_getPasswordData_trueToFalse(t *testing.T) { - var before, after ec2.Instance +// https://github.com/terraform-providers/terraform-provider-aws/issues/227 +func TestAccAWSInstance_associatePublic_explicitPublic(t *testing.T) { + var v ec2.Instance resourceName := "aws_instance.test" rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) @@ -2149,11 +2279,158 @@ func TestAccAWSInstance_getPasswordData_trueToFalse(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig_getPasswordData(rName, true), + Config: testAccInstanceConfig_associatePublic_explicitPublic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckInstanceExists(resourceName, &before), - resource.TestCheckResourceAttr(resourceName, "get_password_data", "true"), - resource.TestCheckResourceAttrSet(resourceName, "password_data"), + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), + resource.TestCheckResourceAttrSet(resourceName, "public_ip"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +// https://github.com/terraform-providers/terraform-provider-aws/issues/227 +func TestAccAWSInstance_associatePublic_explicitPrivate(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_associatePublic_explicitPrivate(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "false"), + resource.TestCheckResourceAttr(resourceName, "public_ip", ""), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +// https://github.com/terraform-providers/terraform-provider-aws/issues/227 +func TestAccAWSInstance_associatePublic_overridePublic(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_associatePublic_overridePublic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "true"), + resource.TestCheckResourceAttrSet(resourceName, "public_ip"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +// https://github.com/terraform-providers/terraform-provider-aws/issues/227 +func TestAccAWSInstance_associatePublic_overridePrivate(t *testing.T) { + var v ec2.Instance + resourceName := "aws_instance.test" + rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_associatePublic_overridePrivate(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "associate_public_ip_address", "false"), + resource.TestCheckResourceAttr(resourceName, "public_ip", ""), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSInstance_getPasswordData_falseToTrue(t *testing.T) { + var before, after ec2.Instance + resourceName := "aws_instance.test" + rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_getPasswordData(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &before), + resource.TestCheckResourceAttr(resourceName, "get_password_data", "false"), + resource.TestCheckResourceAttr(resourceName, "password_data", ""), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccInstanceConfig_getPasswordData(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &after), + testAccCheckInstanceNotRecreated(t, &before, &after), + resource.TestCheckResourceAttr(resourceName, "get_password_data", "true"), + resource.TestCheckResourceAttrSet(resourceName, "password_data"), + ), + }, + }, + }) +} + +func TestAccAWSInstance_getPasswordData_trueToFalse(t *testing.T) { + var before, after ec2.Instance + resourceName := "aws_instance.test" + rName := fmt.Sprintf("tf-testacc-instance-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfig_getPasswordData(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &before), + resource.TestCheckResourceAttr(resourceName, "get_password_data", "true"), + resource.TestCheckResourceAttrSet(resourceName, "password_data"), ), }, { @@ -2666,8 +2943,7 @@ func TestAccAWSInstance_creditSpecification_unlimitedCpuCredits_t2Tot3Taint(t *t } func TestAccAWSInstance_disappears(t *testing.T) { - var conf ec2.Instance - rInt := acctest.RandInt() + var v ec2.Instance resourceName := "aws_instance.test" resource.ParallelTest(t, resource.TestCase{ @@ -2676,10 +2952,10 @@ func TestAccAWSInstance_disappears(t *testing.T) { CheckDestroy: testAccCheckInstanceDestroy, Steps: []resource.TestStep{ { - Config: testAccInstanceConfig(rInt), + Config: testAccInstanceConfigBasic(), Check: resource.ComposeTestCheckFunc( - testAccCheckInstanceExists(resourceName, &conf), - testAccCheckInstanceDisappears(&conf), + testAccCheckInstanceExists(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsInstance(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -2789,11 +3065,7 @@ func TestAccAWSInstance_metadataOptions(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ - // No subnet_id specified requires default VPC or EC2-Classic. - PreCheck: func() { - testAccPreCheck(t) - testAccPreCheckHasDefaultVpcOrEc2Classic(t) - }, + PreCheck: func() { testAccPreCheck(t) }, IDRefreshName: resourceName, Providers: testAccProviders, CheckDestroy: testAccCheckInstanceDestroy, @@ -2910,22 +3182,6 @@ func testAccCheckInstanceExistsWithProvider(n string, i *ec2.Instance, providerF } } -func testAccCheckInstanceDisappears(conf *ec2.Instance) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - - params := &ec2.TerminateInstancesInput{ - InstanceIds: []*string{conf.InstanceId}, - } - - if _, err := conn.TerminateInstances(params); err != nil { - return err - } - - return waitForInstanceDeletion(conn, *conf.InstanceId, 10*time.Minute) - } -} - func testAccCheckStopInstance(instance *ec2.Instance) resource.TestCheckFunc { return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn @@ -2941,22 +3197,6 @@ func testAccCheckStopInstance(instance *ec2.Instance) resource.TestCheckFunc { } } -func TestInstanceTenancySchema(t *testing.T) { - actualSchema := resourceAwsInstance().Schema["tenancy"] - expectedSchema := &schema.Schema{ - Type: schema.TypeString, - Optional: true, - Computed: true, - ForceNew: true, - } - if !reflect.DeepEqual(actualSchema, expectedSchema) { - t.Fatalf( - "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - actualSchema, - expectedSchema) - } -} - func TestInstanceHostIDSchema(t *testing.T) { actualSchema := resourceAwsInstance().Schema["host_id"] expectedSchema := &schema.Schema{ @@ -3021,19 +3261,42 @@ func driftTags(instance *ec2.Instance) resource.TestCheckFunc { } } -func testAccInstanceConfigInDefaultVpcBySgName(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` -data "aws_availability_zones" "current" { - # Exclude usw2-az4 (us-west-2d) as it has limited instance types. - blacklisted_zone_ids = ["usw2-az4"] - state = "available" +func testAccAvailableAZsNoOptInDefaultExcludeConfig() string { + // Exclude usw2-az4 (us-west-2d) as it has limited instance types. + return testAccAvailableAZsNoOptInExcludeConfig("usw2-az4", "usgw1-az2") +} + +func testAccAvailableAZsNoOptInExcludeConfig(excludeZoneIds ...string) string { + return fmt.Sprintf(` +data "aws_availability_zones" "available" { + exclude_zone_ids = ["%[1]v"] + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} +`, strings.Join(excludeZoneIds, "\", \"")) +} + +func testAccAvailableAZsNoOptInConfig() string { + return ` +data "aws_availability_zones" "available" { + state = "available" filter { name = "opt-in-status" values = ["opt-in-not-required"] } } +` +} +func testAccInstanceConfigInDefaultVpcBySgName(rName string) string { + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + testAccLatestAmazonLinuxHvmEbsAmiConfig() + + fmt.Sprintf(` data "aws_vpc" "default" { default = true } @@ -3048,24 +3311,15 @@ resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.micro" security_groups = ["${aws_security_group.test.name}"] - availability_zone = "${data.aws_availability_zones.current.names[0]}" + availability_zone = "${data.aws_availability_zones.available.names[0]}" } `, rName) } func testAccInstanceConfigInDefaultVpcBySgId(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` -data "aws_availability_zones" "current" { - # Exclude usw2-az4 (us-west-2d) as it has limited instance types. - blacklisted_zone_ids = ["usw2-az4"] - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + testAccLatestAmazonLinuxHvmEbsAmiConfig() + + fmt.Sprintf(` data "aws_vpc" "default" { default = true } @@ -3080,119 +3334,89 @@ resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.micro" vpc_security_group_ids = ["${aws_security_group.test.id}"] - availability_zone = "${data.aws_availability_zones.current.names[0]}" + availability_zone = "${data.aws_availability_zones.available.names[0]}" } `, rName) } func testAccInstanceConfigInEc2Classic(rInt int) string { - return fmt.Sprintf(` + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), fmt.Sprintf(` provider "aws" { region = "us-east-1" } -data "aws_ami" "ubuntu" { - most_recent = true - - filter { - name = "name" - values = ["ubuntu/images/ubuntu-trusty-14.04-amd64-server-*"] - } - - filter { - name = "virtualization-type" - values = ["paravirtual"] - } - - owners = ["099720109477"] # Canonical -} - resource "aws_security_group" "sg" { name = "tf_acc_test_%d" description = "Test security group" } resource "aws_instance" "test" { - ami = "${data.aws_ami.ubuntu.id}" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m3.medium" security_groups = ["${aws_security_group.sg.name}"] } -`, rInt) +`, rInt)) } -func testAccInstanceConfig_pre(rInt int) string { - return fmt.Sprintf(` -resource "aws_security_group" "tf_test_test" { - name = "tf_test_%d" - description = "test" - - ingress { - protocol = "icmp" - from_port = -1 - to_port = -1 - cidr_blocks = ["0.0.0.0/0"] - } +func testAccInstanceConfigBasic() string { + return composeConfig( + testAccLatestAmazonLinuxHvmEbsAmiConfig(), + // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-classic-platform.html#ec2-classic-instance-types + testAccAvailableEc2InstanceTypeForRegion("t1.micro", "m1.small", "t3.micro", "t2.micro"), + fmt.Sprintf(` +resource "aws_instance" "test" { + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = data.aws_ec2_instance_type_offering.available.instance_type + # Explicitly no tags so as to test creation without tags. } -`, rInt) +`)) } -func testAccInstanceConfig(rInt int) string { - return fmt.Sprintf(` -resource "aws_security_group" "tf_test_test" { - name = "tf_test_%d" - description = "test" +func testAccInstanceConfigAtLeastOneOtherEbsVolume(rName string) string { + return composeConfig(testAccLatestAmazonLinuxHvmInstanceStoreAmiConfig(), testAccAwsInstanceVpcConfig(rName, false), fmt.Sprintf(` +# Ensure that there is at least 1 EBS volume in the current region. +# See https://github.com/hashicorp/terraform/issues/1249. +resource "aws_ebs_volume" "test" { + availability_zone = data.aws_availability_zones.available.names[0] + size = 5 - ingress { - protocol = "icmp" - from_port = -1 - to_port = -1 - cidr_blocks = ["0.0.0.0/0"] + tags = { + Name = %[1]q } } resource "aws_instance" "test" { - # us-west-2 - ami = "ami-4fccb37f" - availability_zone = "us-west-2a" - - instance_type = "m1.small" - security_groups = ["${aws_security_group.tf_test_test.name}"] - user_data = "foo:-with-character's" -} -`, rInt) -} - -func testAccInstanceConfigWithUserDataBase64(rInt int) string { - return fmt.Sprintf(` -resource "aws_security_group" "tf_test_test" { - name = "tf_test_%d" - description = "test" + ami = data.aws_ami.amzn-ami-minimal-hvm-instance-store.id + instance_type = "m1.small" + subnet_id = aws_subnet.test.id + user_data = "foo:-with-character's" - ingress { - protocol = "icmp" - from_port = -1 - to_port = -1 - cidr_blocks = ["0.0.0.0/0"] + tags = { + Name = %[1]q } + + depends_on = ["aws_ebs_volume.test"] +} +`, rName)) } +func testAccInstanceConfigWithUserDataBase64(rName string) string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), testAccAwsInstanceVpcConfig(rName, false), fmt.Sprintf(` resource "aws_instance" "test" { - # us-west-2 - ami = "ami-4fccb37f" - availability_zone = "us-west-2a" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" + subnet_id = "${aws_subnet.test.id}" instance_type = "m1.small" - security_groups = ["${aws_security_group.tf_test_test.name}"] user_data_base64 = "${base64encode("hello world")}" } -`, rInt) +`)) } -const testAccInstanceConfigWithSmallInstanceType = ` +func testAccInstanceConfigWithSmallInstanceType(rName string) string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), testAccAwsInstanceVpcConfig(rName, false), fmt.Sprintf(` resource "aws_instance" "test" { - # us-west-2 - ami = "ami-55a7ea65" - availability_zone = "us-west-2a" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" + subnet_id = "${aws_subnet.test.id}" instance_type = "m3.medium" @@ -3200,13 +3424,14 @@ resource "aws_instance" "test" { Name = "tf-acctest" } } -` +`)) +} -const testAccInstanceConfigUpdateInstanceType = ` +func testAccInstanceConfigUpdateInstanceType(rName string) string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), testAccAwsInstanceVpcConfig(rName, false), fmt.Sprintf(` resource "aws_instance" "test" { - # us-west-2 - ami = "ami-55a7ea65" - availability_zone = "us-west-2a" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" + subnet_id = "${aws_subnet.test.id}" instance_type = "m3.large" @@ -3214,12 +3439,13 @@ resource "aws_instance" "test" { Name = "tf-acctest" } } -` +`)) +} -const testAccInstanceGP2IopsDevice = ` +func testAccInstanceGP2IopsDevice() string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), fmt.Sprintf(` resource "aws_instance" "test" { - # us-west-2 - ami = "ami-55a7ea65" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" # In order to attach an encrypted volume to an instance you need to have an # m3.medium or larger. See "Supported Instance Types" in: @@ -3231,12 +3457,13 @@ resource "aws_instance" "test" { volume_size = 11 } } -` +`)) +} -const testAccInstanceGP2WithIopsValue = ` +func testAccInstanceGP2WithIopsValue() string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), fmt.Sprintf(` resource "aws_instance" "test" { - # us-west-2 - ami = "ami-55a7ea65" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" # In order to attach an encrypted volume to an instance you need to have an # m3.medium or larger. See "Supported Instance Types" in: @@ -3250,7 +3477,61 @@ resource "aws_instance" "test" { iops = 10 } } -` +`)) +} + +func testAccInstanceConfigRootInstanceStore() string { + return composeConfig(testAccLatestAmazonLinuxHvmInstanceStoreAmiConfig(), fmt.Sprintf(` +resource "aws_instance" "test" { + ami = "${data.aws_ami.amzn-ami-minimal-hvm-instance-store.id}" + + # Only certain instance types support ephemeral root instance stores. + # http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html + instance_type = "m3.medium" +} +`)) +} + +func testAccInstanceConfigNoAMIEphemeralDevices() string { + return composeConfig(testAccLatestAmazonLinuxHvmInstanceStoreAmiConfig(), fmt.Sprintf(` +# This AMI has 2 ephemeral block devices. +data "aws_ami" "test" { + most_recent = true + owners = ["099720109477"] # Canonical + + filter { + name = "name" + values = ["ubuntu/images/hvm-ssd/ubuntu-eoan-19.10-amd64-server-*"] + } + + filter { + name = "root-device-type" + values = ["ebs"] + } +} + +resource "aws_instance" "test" { + ami = "${data.aws_ami.test.id}" + + instance_type = "c3.large" + + root_block_device { + volume_type = "gp2" + volume_size = 11 + } + + ephemeral_block_device { + device_name = "/dev/sdb" + no_device = true + } + + ephemeral_block_device { + device_name = "/dev/sdc" + no_device = true + } +} +`)) +} func testAccAwsEc2InstanceEbsRootDeviceBasic() string { return composeConfig(testAccAwsEc2InstanceAmiWithEbsRootVolume, ` @@ -3315,10 +3596,10 @@ func testAccAwsEc2InstanceConfigBlockDevicesWithDeleteOnTerminate(size, delete s if delete == "" { delete = "null" } - return fmt.Sprintf(` + + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), fmt.Sprintf(` resource "aws_instance" "test" { - # us-west-2 - ami = "ami-55a7ea65" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" # In order to attach an encrypted volume to an instance you need to have an # m3.medium or larger. See "Supported Instance Types" in: @@ -3355,28 +3636,28 @@ resource "aws_instance" "test" { virtual_name = "ephemeral0" } } -`, size, delete) +`, size, delete)) } func testAccInstanceConfigSourceDestEnable(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m1.small" subnet_id = "${aws_subnet.test.id}" } -`) +` } func testAccInstanceConfigSourceDestDisable(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m1.small" subnet_id = "${aws_subnet.test.id}" source_dest_check = false } -`) +` } func testAccInstanceConfigDisableAPITermination(rName string, val bool) string { @@ -3391,7 +3672,7 @@ resource "aws_instance" "test" { } func testAccInstanceConfigVPC(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m1.small" @@ -3401,42 +3682,45 @@ resource "aws_instance" "test" { # pre-encoded base64 data user_data = "3dc39dda39be1205215e776bad998da361a5955d" } -`) +` } -func testAccInstanceConfigOutpost(outpostArn string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceOutpostConfig(outpostArn) + fmt.Sprintf(` -resource "aws_instance" "test" { - ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" - instance_type = "m5.large" - subnet_id = "${aws_subnet.test.id}" +func testAccInstanceConfigOutpost() string { + return composeConfig( + testAccLatestAmazonLinuxHvmEbsAmiConfig(), + ` +data "aws_outposts_outposts" "test" {} - root_block_device { - volume_type = "gp2" - volume_size = 8 - } -} -`) +data "aws_outposts_outpost" "test" { + id = tolist(data.aws_outposts_outposts.test.ids)[0] } -func testAccAwsInstanceOutpostConfig(outpostArn string) string { - return fmt.Sprintf(` -data "aws_availability_zones" "current" { - # Exclude usw2-az4 (us-west-2d) as it has limited instance types. - blacklisted_zone_ids = ["usw2-az4"] +data "aws_outposts_outpost_instance_types" "test" { + arn = data.aws_outposts_outpost.test.arn } resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" } -resource "aws_subnet" "test" { - cidr_block = "10.1.1.0/24" - vpc_id = "${aws_vpc.test.id}" - availability_zone = "${data.aws_availability_zones.current.names[0]}" - outpost_arn = "%s" +resource "aws_subnet" "test" { + availability_zone = data.aws_outposts_outpost.test.availability_zone + cidr_block = "10.1.1.0/24" + outpost_arn = data.aws_outposts_outpost.test.arn + vpc_id = aws_vpc.test.id +} + +resource "aws_instance" "test" { + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = tolist(data.aws_outposts_outpost_instance_types.test.instance_types)[0] + subnet_id = aws_subnet.test.id + + root_block_device { + volume_type = "gp2" + volume_size = 8 + } } -`, outpostArn) +`) } func testAccInstanceConfigPlacementGroup(rName string) string { @@ -3508,48 +3792,48 @@ resource "aws_instance" "test" { } const testAccInstanceConfigMultipleRegions = ` -provider "aws" { - alias = "west" +provider "awswest" { region = "us-west-2" } -provider "aws" { - alias = "east" +provider "awseast" { region = "us-east-1" } resource "aws_instance" "test" { # us-west-2 - provider = "aws.west" + provider = "awswest" ami = "ami-4fccb37f" instance_type = "m1.small" } resource "aws_instance" "test2" { # us-east-1 - provider = "aws.east" + provider = "awseast" ami = "ami-8c6ea9e4" instance_type = "m1.small" } ` -const testAccCheckInstanceConfigTags = ` +func testAccCheckInstanceConfigTags() string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), fmt.Sprintf(` resource "aws_instance" "test" { - ami = "ami-4fccb37f" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m1.small" tags = { test = "test2" } } -` +`)) +} -const testAccInstanceConfigEbsBlockDeviceKmsKeyArn = ` +func testAccInstanceConfigEbsBlockDeviceKmsKeyArn() string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 } resource "aws_instance" "test" { - # us-west-2 - ami = "ami-55a7ea65" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" # In order to attach an encrypted volume to an instance you need to have an # m3.medium or larger. See "Supported Instance Types" in: @@ -3569,33 +3853,17 @@ resource "aws_instance" "test" { volume_size = 12 } } -` - -const testAccInstanceConfigRootBlockDeviceKmsKeyArn = ` -resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" - - tags = { - Name = "terraform-testacc-instance-source-dest-enable" - } -} - -resource "aws_subnet" "test" { - cidr_block = "10.1.1.0/24" - vpc_id = "${aws_vpc.test.id}" - availability_zone = "us-west-2a" - - tags = { - Name = "tf-acc-instance-source-dest-enable" - } +`)) } +func testAccInstanceConfigRootBlockDeviceKmsKeyArn(rName string) string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), testAccAwsInstanceVpcConfig(rName, false), fmt.Sprintf(` resource "aws_kms_key" "test" { deletion_window_in_days = 7 } resource "aws_instance" "test" { - ami = "ami-08692d171e3cf02d6" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t3.nano" subnet_id = "${aws_subnet.test.id}" @@ -3605,37 +3873,13 @@ resource "aws_instance" "test" { kms_key_id = "${aws_kms_key.test.arn}" } } -` - -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 +`)) } +func testAccCheckInstanceConfigWithAttachedVolume() string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), fmt.Sprintf(` resource "aws_instance" "test" { - ami = "${data.aws_ami.debian_jessie_latest.id}" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.medium" root_block_device { @@ -3664,11 +3908,13 @@ resource "aws_volume_attachment" "test" { volume_id = "${aws_ebs_volume.test.id}" instance_id = "${aws_instance.test.id}" } -` +`)) +} -const testAccCheckInstanceConfigNoVolumeTags = ` +func testAccCheckInstanceConfigNoVolumeTags() string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), fmt.Sprintf(` resource "aws_instance" "test" { - ami = "ami-55a7ea65" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m3.medium" @@ -3698,11 +3944,29 @@ resource "aws_instance" "test" { virtual_name = "ephemeral0" } } -` +`)) +} + +var testAccCheckInstanceConfigEBSBlockDeviceInvalidIops = composeConfig(testAccAwsEc2InstanceAmiWithEbsRootVolume, + ` +resource "aws_instance" "test" { + ami = data.aws_ami.ami.id + + instance_type = "m3.medium" + + ebs_block_device { + device_name = "/dev/sdc" + volume_size = 10 + volume_type = "gp2" + iops = 100 + } +} +`) -const testAccCheckInstanceConfigWithVolumeTags = ` +func testAccCheckInstanceConfigWithVolumeTags() string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), fmt.Sprintf(` resource "aws_instance" "test" { - ami = "ami-55a7ea65" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m3.medium" @@ -3736,11 +4000,13 @@ resource "aws_instance" "test" { Name = "acceptance-test-volume-tag" } } -` +`)) +} -const testAccCheckInstanceConfigWithVolumeTagsUpdate = ` +func testAccCheckInstanceConfigWithVolumeTagsUpdate() string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), fmt.Sprintf(` resource "aws_instance" "test" { - ami = "ami-55a7ea65" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m3.medium" @@ -3775,17 +4041,20 @@ resource "aws_instance" "test" { Environment = "dev" } } -` +`)) +} -const testAccCheckInstanceConfigTagsUpdate = ` +func testAccCheckInstanceConfigTagsUpdate() string { + return composeConfig(testAccLatestAmazonLinuxHvmEbsAmiConfig(), fmt.Sprintf(` resource "aws_instance" "test" { - ami = "ami-4fccb37f" + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m1.small" tags = { test2 = "test3" } } -` +`)) +} func testAccInstanceConfigWithoutInstanceProfile(rName string) string { return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` @@ -3813,8 +4082,8 @@ resource "aws_iam_role" "test" { } resource "aws_iam_instance_profile" "test" { - name = %[1]q - roles = ["${aws_iam_role.test.name}"] + name = %[1]q + role = aws_iam_role.test.name } resource "aws_instance" "test" { @@ -3830,18 +4099,29 @@ resource "aws_instance" "test" { } func testAccInstanceConfigPrivateIP(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.micro" subnet_id = "${aws_subnet.test.id}" private_ip = "10.1.1.42" } -`) +` +} + +func testAccInstanceConfigEmptyPrivateIP(rName string) string { + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` +resource "aws_instance" "test" { + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" + instance_type = "t2.micro" + subnet_id = "${aws_subnet.test.id}" + private_ip = "" +} +` } func testAccInstanceConfigAssociatePublicIPAndPrivateIP(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.micro" @@ -3849,14 +4129,14 @@ resource "aws_instance" "test" { associate_public_ip_address = true private_ip = "10.1.1.42" } -`) +` } func testAccInstanceNetworkInstanceSecurityGroups(rName string) string { return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + testAccAwsInstanceVpcSecurityGroupConfig(rName) + - fmt.Sprintf(` + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t1.micro" @@ -3871,14 +4151,14 @@ resource "aws_eip" "test" { vpc = true depends_on = ["aws_internet_gateway.test"] } -`) +` } func testAccInstanceNetworkInstanceVPCSecurityGroupIDs(rName string) string { return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + testAccAwsInstanceVpcSecurityGroupConfig(rName) + - fmt.Sprintf(` + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t1.micro" @@ -3892,14 +4172,14 @@ resource "aws_eip" "test" { vpc = true depends_on = ["aws_internet_gateway.test"] } -`) +` } func testAccInstanceNetworkInstanceVPCRemoveSecurityGroupIDs(rName string) string { return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + testAccAwsInstanceVpcSecurityGroupConfig(rName) + - fmt.Sprintf(` + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t1.micro" @@ -3913,7 +4193,7 @@ resource "aws_eip" "test" { vpc = true depends_on = ["aws_internet_gateway.test"] } -`) +` } func testAccInstanceConfigKeyPair(rName string) string { @@ -3936,9 +4216,9 @@ resource "aws_instance" "test" { } func testAccInstanceConfigRootBlockDeviceMismatch(rName string) string { - return testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { - // This is an AMI with RootDeviceName: "/dev/sda1"; actual root: "/dev/sda" + // This is an AMI in us-west-2 with RootDeviceName: "/dev/sda1"; actual root: "/dev/sda" ami = "ami-ef5b69df" instance_type = "t1.micro" subnet_id = "${aws_subnet.test.id}" @@ -3947,27 +4227,27 @@ resource "aws_instance" "test" { volume_size = 13 } } -`) +` } func testAccInstanceConfigForceNewAndTagsDrift(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.nano" subnet_id = "${aws_subnet.test.id}" } -`) +` } func testAccInstanceConfigForceNewAndTagsDrift_Update(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.micro" subnet_id = "${aws_subnet.test.id}" } -`) +` } func testAccInstanceConfigPrimaryNetworkInterface(rName string) string { @@ -4092,7 +4372,7 @@ func testAccInstanceConfigAddSecurityGroupBefore(rName string) string { resource "aws_subnet" "test2" { cidr_block = "10.1.2.0/24" vpc_id = "${aws_vpc.test.id}" - availability_zone = "${data.aws_availability_zones.current.names[0]}" + availability_zone = "${data.aws_availability_zones.available.names[0]}" tags = { Name = %[1]q @@ -4149,7 +4429,7 @@ func testAccInstanceConfigAddSecurityGroupAfter(rName string) string { resource "aws_subnet" "test2" { cidr_block = "10.1.2.0/24" vpc_id = "${aws_vpc.test.id}" - availability_zone = "${data.aws_availability_zones.current.names[0]}" + availability_zone = "${data.aws_availability_zones.available.names[0]}" tags = { Name = %[1]q @@ -4202,6 +4482,61 @@ resource "aws_network_interface" "test" { `, rName) } +func testAccInstanceConfigPublicAndPrivateSecondaryIPs(rName string, isPublic bool) string { + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` +resource "aws_security_group" "test" { + vpc_id = "${aws_vpc.test.id}" + description = "%[1]s" + name = "%[1]s" +} + +resource "aws_instance" "test" { + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" + instance_type = "t3.small" + subnet_id = "${aws_subnet.test.id}" + + associate_public_ip_address = %[2]t + + secondary_private_ips = ["10.1.1.42", "10.1.1.43"] + + vpc_security_group_ids = [ + "${aws_security_group.test.id}" + ] + + tags = { + Name = %[1]q + } +} +`, rName, isPublic) +} + +func testAccInstanceConfigPrivateIPAndSecondaryIPs(rName, privateIP, secondaryIPs string) string { + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` +resource "aws_security_group" "test" { + vpc_id = "${aws_vpc.test.id}" + description = "%[1]s" + name = "%[1]s" +} + +resource "aws_instance" "test" { + ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" + instance_type = "t3.small" + subnet_id = "${aws_subnet.test.id}" + + private_ip = "%[2]s" + secondary_private_ips = [%[3]s] + + vpc_security_group_ids = [ + "${aws_security_group.test.id}" + ] + + tags = { + Name = %[1]q + } +} +`, rName, privateIP, secondaryIPs) +} + func testAccInstanceConfig_associatePublic_defaultPrivate(rName string) string { return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` resource "aws_instance" "test" { @@ -4308,7 +4643,7 @@ resource "aws_instance" "test" { } func testAccInstanceConfig_CreditSpecification_Empty_NonBurstable(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m5.large" @@ -4316,42 +4651,42 @@ resource "aws_instance" "test" { credit_specification {} } -`) +` } func testAccInstanceConfig_CreditSpecification_Unspecified_NonBurstable(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m5.large" subnet_id = "${aws_subnet.test.id}" } -`) +` } func testAccInstanceConfig_creditSpecification_unspecified(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.micro" subnet_id = "${aws_subnet.test.id}" } -`) +` } func testAccInstanceConfig_creditSpecification_unspecified_t3(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t3.micro" subnet_id = "${aws_subnet.test.id}" } -`) +` } func testAccInstanceConfig_creditSpecification_standardCpuCredits(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.micro" @@ -4361,11 +4696,11 @@ resource "aws_instance" "test" { cpu_credits = "standard" } } -`) +` } func testAccInstanceConfig_creditSpecification_standardCpuCredits_t3(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t3.micro" @@ -4375,11 +4710,11 @@ resource "aws_instance" "test" { cpu_credits = "standard" } } -`) +` } func testAccInstanceConfig_creditSpecification_unlimitedCpuCredits(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.micro" @@ -4389,11 +4724,11 @@ resource "aws_instance" "test" { cpu_credits = "unlimited" } } -`) +` } func testAccInstanceConfig_creditSpecification_unlimitedCpuCredits_t3(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t3.micro" @@ -4403,11 +4738,11 @@ resource "aws_instance" "test" { cpu_credits = "unlimited" } } -`) +` } func testAccInstanceConfig_creditSpecification_isNotAppliedToNonBurstable(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "m1.small" @@ -4417,7 +4752,7 @@ resource "aws_instance" "test" { cpu_credits = "standard" } } -`) +` } func testAccInstanceConfig_creditSpecification_unknownCpuCredits(rName, instanceType string) string { @@ -4433,31 +4768,31 @@ resource "aws_instance" "test" { } func testAccInstanceConfig_UserData_Unspecified(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.micro" subnet_id = "${aws_subnet.test.id}" } -`) +` } func testAccInstanceConfig_UserData_EmptyString(rName string) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + testAccAwsInstanceVpcConfig(rName, false) + ` resource "aws_instance" "test" { ami = "${data.aws_ami.amzn-ami-minimal-hvm-ebs.id}" instance_type = "t2.micro" subnet_id = "${aws_subnet.test.id}" user_data = "" } -`) +` } // testAccLatestAmazonLinuxHvmEbsAmiConfig returns the configuration for a data source that // describes the latest Amazon Linux AMI using HVM virtualization and an EBS root device. // The data source is named 'amzn-ami-minimal-hvm-ebs'. func testAccLatestAmazonLinuxHvmEbsAmiConfig() string { - return fmt.Sprintf(` + return ` data "aws_ami" "amzn-ami-minimal-hvm-ebs" { most_recent = true owners = ["amazon"] @@ -4472,16 +4807,37 @@ data "aws_ami" "amzn-ami-minimal-hvm-ebs" { values = ["ebs"] } } -`) +` +} + +// testAccLatestAmazonLinuxHvmInstanceStoreAmiConfig returns the configuration for a data source that +// describes the latest Amazon Linux AMI using HVM virtualization and an instance store root device. +// The data source is named 'amzn-ami-minimal-hvm-instance-store'. +func testAccLatestAmazonLinuxHvmInstanceStoreAmiConfig() string { + return ` +data "aws_ami" "amzn-ami-minimal-hvm-instance-store" { + most_recent = true + owners = ["amazon"] + + filter { + name = "name" + values = ["amzn-ami-minimal-hvm-*"] + } + + filter { + name = "root-device-type" + values = ["instance-store"] + } +} +` } // testAccLatestAmazonLinuxPvEbsAmiConfig returns the configuration for a data source that // describes the latest Amazon Linux AMI using PV virtualization and an EBS root device. // The data source is named 'amzn-ami-minimal-pv-ebs'. -/* func testAccLatestAmazonLinuxPvEbsAmiConfig() string { return fmt.Sprintf(` -data "aws_ami" "amzn-ami-minimal-hvm-ebs" { +data "aws_ami" "amzn-ami-minimal-pv-ebs" { most_recent = true owners = ["amazon"] @@ -4497,13 +4853,12 @@ data "aws_ami" "amzn-ami-minimal-hvm-ebs" { } `) } -*/ // testAccLatestWindowsServer2016CoreAmiConfig returns the configuration for a data source that // describes the latest Microsoft Windows Server 2016 Core AMI. // The data source is named 'win2016core-ami'. func testAccLatestWindowsServer2016CoreAmiConfig() string { - return fmt.Sprintf(` + return ` data "aws_ami" "win2016core-ami" { most_recent = true owners = ["amazon"] @@ -4513,28 +4868,40 @@ data "aws_ami" "win2016core-ami" { values = ["Windows_Server-2016-English-Core-Base-*"] } } -`) +` } // testAccAwsInstanceVpcConfig returns the configuration for tests that create -// 1) a VPC with IPv6 support -// 2) a subnet in the VPC +// 1) a VPC without IPv6 support +// 2) a subnet in the VPC that optionally assigns public IP addresses to ENIs // The resources are named 'test'. func testAccAwsInstanceVpcConfig(rName string, mapPublicIpOnLaunch bool) string { - return fmt.Sprintf(` -data "aws_availability_zones" "current" { - # Exclude usw2-az4 (us-west-2d) as it has limited instance types. - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + return composeConfig(testAccAvailableAZsNoOptInDefaultExcludeConfig(), fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] + tags = { + Name = %[1]q + } +} + +resource "aws_subnet" "test" { + cidr_block = "10.1.1.0/24" + vpc_id = aws_vpc.test.id + availability_zone = data.aws_availability_zones.available.names[0] + map_public_ip_on_launch = %[2]t + + tags = { + Name = %[1]q } } +`, rName, mapPublicIpOnLaunch)) +} +func testAccAwsInstanceVpcConfigBasic(rName string) string { + return composeConfig(testAccAvailableAZsNoOptInConfig(), fmt.Sprintf(` resource "aws_vpc" "test" { - cidr_block = "10.1.0.0/16" + cidr_block = "10.0.0.0/16" tags = { Name = %[1]q @@ -4542,16 +4909,15 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - cidr_block = "10.1.1.0/24" - vpc_id = "${aws_vpc.test.id}" - availability_zone = "${data.aws_availability_zones.current.names[0]}" - map_public_ip_on_launch = %[2]t + availability_zone = data.aws_availability_zones.available.names[0] + cidr_block = "10.0.0.0/24" + vpc_id = aws_vpc.test.id tags = { Name = %[1]q } } -`, rName, mapPublicIpOnLaunch) +`, rName)) } // testAccAwsInstanceVpcSecurityGroupConfig returns the configuration for tests that create @@ -4589,21 +4955,10 @@ resource "aws_security_group" "test" { // testAccAwsInstanceVpcIpv6Config returns the configuration for tests that create // 1) a VPC with IPv6 support -// 2) a subnet in the VPC +// 2) a subnet in the VPC with an assigned IPv6 CIDR block // The resources are named 'test'. func testAccAwsInstanceVpcIpv6Config(rName string) string { - return fmt.Sprintf(` -data "aws_availability_zones" "current" { - # Exclude usw2-az4 (us-west-2d) as it has limited instance types. - blacklisted_zone_ids = ["usw2-az4"] - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - + return composeConfig(testAccAvailableAZsNoOptInDefaultExcludeConfig(), fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -4616,15 +4971,15 @@ resource "aws_vpc" "test" { resource "aws_subnet" "test" { cidr_block = "10.1.1.0/24" - vpc_id = "${aws_vpc.test.id}" - availability_zone = "${data.aws_availability_zones.current.names[0]}" - ipv6_cidr_block = "${cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1)}" + vpc_id = aws_vpc.test.id + availability_zone = data.aws_availability_zones.available.names[0] + ipv6_cidr_block = cidrsubnet(aws_vpc.test.ipv6_cidr_block, 8, 1) tags = { Name = %[1]q } } -`, rName) +`, rName)) } func testAccInstanceConfigHibernation(hibernation bool) string { @@ -4679,11 +5034,13 @@ resource "aws_instance" "test" { func testAccInstanceConfigMetadataOptions(rName string) string { return composeConfig( testAccLatestAmazonLinuxHvmEbsAmiConfig(), + testAccAwsInstanceVpcConfig(rName, false), testAccAvailableEc2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = data.aws_ec2_instance_type_offering.available.instance_type + subnet_id = aws_subnet.test.id tags = { Name = %[1]q @@ -4703,11 +5060,13 @@ data "aws_instance" "test" { func testAccInstanceConfigMetadataOptionsUpdated(rName string) string { return composeConfig( testAccLatestAmazonLinuxHvmEbsAmiConfig(), + testAccAwsInstanceVpcConfig(rName, false), testAccAvailableEc2InstanceTypeForRegion("t3.micro", "t2.micro"), fmt.Sprintf(` resource "aws_instance" "test" { ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = data.aws_ec2_instance_type_offering.available.instance_type + subnet_id = aws_subnet.test.id tags = { Name = %[1]q @@ -4722,6 +5081,25 @@ resource "aws_instance" "test" { `, rName)) } +func testAccAwsEc2InstanceConfigDynamicEBSBlockDevices() string { + return composeConfig(testAccLatestAmazonLinuxPvEbsAmiConfig(), ` +resource "aws_instance" "test" { + ami = data.aws_ami.amzn-ami-minimal-pv-ebs.id + instance_type = "m3.medium" + + dynamic "ebs_block_device" { + for_each = ["a", "b", "c"] + iterator = device + content { + device_name = format("/dev/sd%s", device.value) + volume_size = "10" + volume_type = "gp2" + } + } +} +`) +} + // testAccAvailableEc2InstanceTypeForRegion returns the configuration for a data source that describes // the first available EC2 instance type offering in the current region from a list of preferred instance types. // The data source is named 'available'. @@ -4737,3 +5115,33 @@ data "aws_ec2_instance_type_offering" "available" { } `, strings.Join(preferredInstanceTypes, "\", \"")) } + +// testAccAvailableEc2InstanceTypeForAvailabilityZone returns the configuration for a data source that describes +// the first available EC2 instance type offering in the specified availability zone from a list of preferred instance types. +// The first argument is either an Availability Zone name or Terraform configuration reference to one, e.g. +// * data.aws_availability_zones.available.names[0] +// * aws_subnet.test.availability_zone +// * us-west-2a +// The data source is named 'available'. +func testAccAvailableEc2InstanceTypeForAvailabilityZone(availabilityZoneName string, preferredInstanceTypes ...string) string { + if !strings.Contains(availabilityZoneName, ".") { + availabilityZoneName = strconv.Quote(availabilityZoneName) + } + + return fmt.Sprintf(` +data "aws_ec2_instance_type_offering" "available" { + filter { + name = "instance-type" + values = ["%[2]v"] + } + + filter { + name = "location" + values = [%[1]s] + } + + location_type = "availability-zone" + preferred_instance_types = ["%[2]v"] +} +`, availabilityZoneName, strings.Join(preferredInstanceTypes, "\", \"")) +} diff --git a/aws/resource_aws_internet_gateway.go b/aws/resource_aws_internet_gateway.go index 2d5ff0f2ebe..7dbbdfde905 100644 --- a/aws/resource_aws_internet_gateway.go +++ b/aws/resource_aws_internet_gateway.go @@ -6,10 +6,11 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -33,6 +34,10 @@ func resourceAwsInternetGateway() *schema.Resource { Type: schema.TypeString, Computed: true, }, + "arn": { + Type: schema.TypeString, + Computed: true, + }, }, } } @@ -59,7 +64,7 @@ func resourceAwsInternetGatewayCreate(d *schema.ResourceData, meta interface{}) return nil } if err == nil { - return resource.RetryableError(err) + return resource.RetryableError(&resource.NotFoundError{}) } else { return resource.NonRetryableError(err) } @@ -98,7 +103,7 @@ func resourceAwsInternetGatewayRead(d *schema.ResourceData, meta interface{}) er return err } if igRaw == nil { - // Seems we have lost our internet gateway + log.Printf("[WARN] Internet Gateway (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -117,6 +122,16 @@ func resourceAwsInternetGatewayRead(d *schema.ResourceData, meta interface{}) er d.Set("owner_id", ig.OwnerId) + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Service: "ec2", + Region: meta.(*AWSClient).region, + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("internet-gateway/%s", d.Id()), + }.String() + + d.Set("arn", arn) + return nil } @@ -227,7 +242,7 @@ func resourceAwsInternetGatewayAttach(d *schema.ResourceData, meta interface{}) // Wait for it to be fully attached before continuing log.Printf("[DEBUG] Waiting for internet gateway (%s) to attach", d.Id()) stateConf := &resource.StateChangeConf{ - Pending: []string{"detached", "attaching"}, + Pending: []string{ec2.AttachmentStatusDetached, ec2.AttachmentStatusAttaching}, Target: []string{"available"}, Refresh: IGAttachStateRefreshFunc(conn, d.Id(), "available"), Timeout: 4 * time.Minute, @@ -262,8 +277,8 @@ func resourceAwsInternetGatewayDetach(d *schema.ResourceData, meta interface{}) // Wait for it to be fully detached before continuing log.Printf("[DEBUG] Waiting for internet gateway (%s) to detach", d.Id()) stateConf := &resource.StateChangeConf{ - Pending: []string{"detaching"}, - Target: []string{"detached"}, + Pending: []string{ec2.AttachmentStatusDetaching}, + Target: []string{ec2.AttachmentStatusDetached}, Refresh: detachIGStateRefreshFunc(conn, d.Id(), vpcID.(string)), Timeout: 15 * time.Minute, Delay: 10 * time.Second, @@ -294,7 +309,7 @@ func detachIGStateRefreshFunc(conn *ec2.EC2, gatewayID, vpcID string) resource.S return nil, "", nil case "Gateway.NotAttached": - return 42, "detached", nil + return 42, ec2.AttachmentStatusDetached, nil case "DependencyViolation": // This can be caused by associated public IPs left (e.g. by ELBs) @@ -308,7 +323,7 @@ func detachIGStateRefreshFunc(conn *ec2.EC2, gatewayID, vpcID string) resource.S len(out.NetworkInterfaces), out.NetworkInterfaces) } - return 42, "detaching", nil + return 42, ec2.AttachmentStatusDetaching, nil } } return 42, "", err @@ -316,7 +331,7 @@ func detachIGStateRefreshFunc(conn *ec2.EC2, gatewayID, vpcID string) resource.S // DetachInternetGateway only returns an error, so if it's nil, assume we're // detached - return 42, "detached", nil + return 42, ec2.AttachmentStatusDetached, nil } } @@ -343,8 +358,7 @@ func IGStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc { InternetGatewayIds: []*string{aws.String(id)}, }) if err != nil { - ec2err, ok := err.(awserr.Error) - if ok && ec2err.Code() == "InvalidInternetGatewayID.NotFound" { + if isAWSErr(err, "InvalidInternetGatewayID.NotFound", "") { resp = nil } else { log.Printf("[ERROR] Error on IGStateRefresh: %s", err) @@ -376,8 +390,7 @@ func IGAttachStateRefreshFunc(conn *ec2.EC2, id string, expected string) resourc InternetGatewayIds: []*string{aws.String(id)}, }) if err != nil { - ec2err, ok := err.(awserr.Error) - if ok && ec2err.Code() == "InvalidInternetGatewayID.NotFound" { + if isAWSErr(err, "InvalidInternetGatewayID.NotFound", "") { resp = nil } else { log.Printf("[ERROR] Error on IGStateRefresh: %s", err) @@ -399,7 +412,7 @@ func IGAttachStateRefreshFunc(conn *ec2.EC2, id string, expected string) resourc if len(ig.Attachments) == 0 { // No attachments, we're detached - return ig, "detached", nil + return ig, ec2.AttachmentStatusDetached, nil } return ig, *ig.Attachments[0].State, nil diff --git a/aws/resource_aws_internet_gateway_test.go b/aws/resource_aws_internet_gateway_test.go index 5993eafb5ae..84c72766711 100644 --- a/aws/resource_aws_internet_gateway_test.go +++ b/aws/resource_aws_internet_gateway_test.go @@ -3,14 +3,14 @@ package aws import ( "fmt" "log" + "regexp" "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-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -86,8 +86,8 @@ func testSweepInternetGateways(region string) error { } stateConf := &resource.StateChangeConf{ - Pending: []string{"detaching"}, - Target: []string{"detached"}, + Pending: []string{ec2.AttachmentStatusDetaching}, + Target: []string{ec2.AttachmentStatusDetached}, Refresh: detachIGStateRefreshFunc(conn, aws.StringValue(internetGateway.InternetGatewayId), aws.StringValue(attachment.VpcId)), Timeout: 10 * time.Minute, Delay: 10 * time.Second, @@ -148,9 +148,10 @@ func TestAccAWSInternetGateway_basic(t *testing.T) { { Config: testAccInternetGatewayConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckInternetGatewayExists( - resourceName, &v), + testAccCheckInternetGatewayExists(resourceName, &v), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`internet-gateway/igw-.+`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { @@ -161,8 +162,7 @@ func TestAccAWSInternetGateway_basic(t *testing.T) { { Config: testAccInternetGatewayConfigChangeVPC, Check: resource.ComposeTestCheckFunc( - testAccCheckInternetGatewayExists( - resourceName, &v2), + testAccCheckInternetGatewayExists(resourceName, &v2), testNotEqual, testAccCheckResourceAttrAccountID(resourceName, "owner_id"), ), @@ -243,6 +243,27 @@ func TestAccAWSInternetGateway_tags(t *testing.T) { }) } +func TestAccAWSInternetGateway_disappears(t *testing.T) { + var v ec2.InternetGateway + resourceName := "aws_internet_gateway.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckInternetGatewayDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInternetGatewayConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckInternetGatewayExists(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsInternetGateway(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckInternetGatewayDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn @@ -264,11 +285,7 @@ func testAccCheckInternetGatewayDestroy(s *terraform.State) error { } // Verify the error is what we want - ec2err, ok := err.(awserr.Error) - if !ok { - return err - } - if ec2err.Code() != "InvalidInternetGatewayID.NotFound" { + if !isAWSErr(err, "InvalidInternetGatewayID.NotFound", "") { return err } } @@ -323,9 +340,6 @@ resource "aws_vpc" "test" { resource "aws_internet_gateway" "test" { vpc_id = "${aws_vpc.test.id}" - tags = { - Name = "terraform-testacc-internet-gateway" - } } ` diff --git a/aws/resource_aws_iot_certificate.go b/aws/resource_aws_iot_certificate.go index 6d8a54f6704..be291736ea2 100644 --- a/aws/resource_aws_iot_certificate.go +++ b/aws/resource_aws_iot_certificate.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iot" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIotCertificate() *schema.Resource { diff --git a/aws/resource_aws_iot_certificate_test.go b/aws/resource_aws_iot_certificate_test.go index 344b316301c..fb5a94d4c9c 100644 --- a/aws/resource_aws_iot_certificate_test.go +++ b/aws/resource_aws_iot_certificate_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/iot" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIoTCertificate_csr(t *testing.T) { diff --git a/aws/resource_aws_iot_policy.go b/aws/resource_aws_iot_policy.go index 19ad04456af..13efc9fbc86 100644 --- a/aws/resource_aws_iot_policy.go +++ b/aws/resource_aws_iot_policy.go @@ -1,11 +1,12 @@ package aws import ( + "fmt" "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iot" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIotPolicy() *schema.Resource { @@ -14,14 +15,20 @@ func resourceAwsIotPolicy() *schema.Resource { Read: resourceAwsIotPolicyRead, Update: resourceAwsIotPolicyUpdate, Delete: resourceAwsIotPolicyDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, + ForceNew: true, }, "policy": { - Type: schema.TypeString, - Required: true, + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: suppressEquivalentAwsPolicyDiffs, }, "arn": { Type: schema.TypeString, @@ -45,11 +52,10 @@ func resourceAwsIotPolicyCreate(d *schema.ResourceData, meta interface{}) error }) if err != nil { - log.Printf("[ERROR] %s", err) - return err + return fmt.Errorf("error creating IoT Policy: %s", err) } - d.SetId(*out.PolicyName) + d.SetId(aws.StringValue(out.PolicyName)) return resourceAwsIotPolicyRead(d, meta) } @@ -61,13 +67,20 @@ func resourceAwsIotPolicyRead(d *schema.ResourceData, meta interface{}) error { PolicyName: aws.String(d.Id()), }) + if isAWSErr(err, iot.ErrCodeResourceNotFoundException, "") { + log.Printf("[WARN] IoT Policy (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + if err != nil { - log.Printf("[ERROR] %s", err) - return err + return fmt.Errorf("error reading IoT Policy (%s): %s", d.Id(), err) } d.Set("arn", out.PolicyArn) d.Set("default_version_id", out.DefaultVersionId) + d.Set("name", out.PolicyName) + d.Set("policy", out.PolicyDocument) return nil } @@ -83,8 +96,7 @@ func resourceAwsIotPolicyUpdate(d *schema.ResourceData, meta interface{}) error }) if err != nil { - log.Printf("[ERROR] %s", err) - return err + return fmt.Errorf("error updating IoT Policy (%s): %s", d.Id(), err) } } @@ -100,19 +112,23 @@ func resourceAwsIotPolicyDelete(d *schema.ResourceData, meta interface{}) error }) if err != nil { - return err + return fmt.Errorf("error listing IoT Policy (%s) versions: %s", d.Id(), err) } // Delete all non-default versions of the policy for _, ver := range out.PolicyVersions { - if !*ver.IsDefaultVersion { + if !aws.BoolValue(ver.IsDefaultVersion) { _, err = conn.DeletePolicyVersion(&iot.DeletePolicyVersionInput{ PolicyName: aws.String(d.Id()), PolicyVersionId: ver.VersionId, }) + + if isAWSErr(err, iot.ErrCodeResourceNotFoundException, "") { + continue + } + if err != nil { - log.Printf("[ERROR] %s", err) - return err + return fmt.Errorf("error deleting IoT Policy (%s) version (%s): %s", d.Id(), aws.StringValue(ver.VersionId), err) } } } @@ -122,9 +138,12 @@ func resourceAwsIotPolicyDelete(d *schema.ResourceData, meta interface{}) error PolicyName: aws.String(d.Id()), }) + if isAWSErr(err, iot.ErrCodeResourceNotFoundException, "") { + return nil + } + if err != nil { - log.Printf("[ERROR] %s", err) - return err + return fmt.Errorf("error deleting IoT Policy (%s): %s", d.Id(), err) } return nil diff --git a/aws/resource_aws_iot_policy_attachment.go b/aws/resource_aws_iot_policy_attachment.go index 9e2ce528b90..389e599d2d2 100644 --- a/aws/resource_aws_iot_policy_attachment.go +++ b/aws/resource_aws_iot_policy_attachment.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iot" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsIotPolicyAttachment() *schema.Resource { diff --git a/aws/resource_aws_iot_policy_attachment_test.go b/aws/resource_aws_iot_policy_attachment_test.go index 30a189fd419..bd13094f906 100644 --- a/aws/resource_aws_iot_policy_attachment_test.go +++ b/aws/resource_aws_iot_policy_attachment_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iot" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIotPolicyAttachment_basic(t *testing.T) { diff --git a/aws/resource_aws_iot_policy_test.go b/aws/resource_aws_iot_policy_test.go index 44f040ce13d..5f8c7fb82bf 100644 --- a/aws/resource_aws_iot_policy_test.go +++ b/aws/resource_aws_iot_policy_test.go @@ -8,13 +8,15 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/iot" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSIoTPolicy_basic(t *testing.T) { - rName := acctest.RandomWithPrefix("PubSubToAnyTopic-") + var v iot.GetPolicyOutput + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_iot_policy.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -24,18 +26,46 @@ func TestAccAWSIoTPolicy_basic(t *testing.T) { { Config: testAccAWSIoTPolicyConfigInitialState(rName), Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("aws_iot_policy.pubsub", "name", rName), - resource.TestCheckResourceAttrSet("aws_iot_policy.pubsub", "arn"), - resource.TestCheckResourceAttrSet("aws_iot_policy.pubsub", "default_version_id"), - resource.TestCheckResourceAttrSet("aws_iot_policy.pubsub", "policy"), + testAccCheckAWSIoTPolicyExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "name", rName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "iot", fmt.Sprintf("policy/%s", rName)), + resource.TestCheckResourceAttrSet(resourceName, "default_version_id"), + resource.TestCheckResourceAttrSet(resourceName, "policy"), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSIoTPolicy_disappears(t *testing.T) { + var v iot.GetPolicyOutput + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_iot_policy.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSIoTPolicyDestroy_basic, + Steps: []resource.TestStep{ + { + Config: testAccAWSIoTPolicyConfigInitialState(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSIoTPolicyExists(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsIotPolicy(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, }, }) } func TestAccAWSIoTPolicy_invalidJson(t *testing.T) { - rName := acctest.RandomWithPrefix("PubSubToAnyTopic-") + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -83,9 +113,35 @@ func testAccCheckAWSIoTPolicyDestroy_basic(s *terraform.State) error { return nil } +func testAccCheckAWSIoTPolicyExists(n string, v *iot.GetPolicyOutput) 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 IoT Policy ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).iotconn + + resp, err := conn.GetPolicy(&iot.GetPolicyInput{ + PolicyName: aws.String(rs.Primary.ID), + }) + if err != nil { + return err + } + + *v = *resp + + return nil + } +} + func testAccAWSIoTPolicyConfigInitialState(rName string) string { return fmt.Sprintf(` -resource "aws_iot_policy" "pubsub" { +resource "aws_iot_policy" "test" { name = "%s" policy = < 0 { + for k, v := range errorAction[0].(map[string]interface{}) { + switch k { + case "cloudwatch_alarm": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotCloudwatchAlarmAction([]interface{}{tfMapRaw}) + if action == nil { + continue + } + + iotErrorAction = &iot.Action{CloudwatchAlarm: action} + + } + case "cloudwatch_metric": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotCloudwatchMetricAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{CloudwatchMetric: action} + } + case "dynamodb": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotDynamoDBAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{DynamoDB: action} + } + case "dynamodbv2": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotDynamoDBv2Action([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{DynamoDBv2: action} + } + case "elasticsearch": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotElasticsearchAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{Elasticsearch: action} + } + case "firehose": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotFirehoseAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{Firehose: action} + } + case "iot_analytics": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotIotAnalyticsAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{IotAnalytics: action} + } + case "iot_events": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotIotEventsAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{IotEvents: action} + } + case "kinesis": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotKinesisAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{Kinesis: action} + } + case "lambda": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotLambdaAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{Lambda: action} + } + case "republish": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotRepublishAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{Republish: action} + } + case "s3": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotS3Action([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{S3: action} + } + case "sns": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotSnsAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{Sns: action} + } + case "sqs": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotSqsAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{Sqs: action} + } + case "step_functions": + for _, tfMapRaw := range v.([]interface{}) { + action := expandIotStepFunctionsAction([]interface{}{tfMapRaw}) + + if action == nil { + continue + } + + iotErrorAction = &iot.Action{StepFunctions: action} + } + } + } + } + + return &iot.TopicRulePayload{ + Actions: actions, + AwsIotSqlVersion: aws.String(d.Get("sql_version").(string)), + Description: aws.String(d.Get("description").(string)), + RuleDisabled: aws.Bool(!d.Get("enabled").(bool)), + Sql: aws.String(d.Get("sql").(string)), + ErrorAction: iotErrorAction, + } +} + +func flattenIotCloudwatchAlarmAction(apiObject *iot.CloudwatchAlarmAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.AlarmName; v != nil { + tfMap["alarm_name"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + if v := apiObject.StateReason; v != nil { + tfMap["state_reason"] = aws.StringValue(v) + } + + if v := apiObject.StateValue; v != nil { + tfMap["state_value"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotCloudWatchAlarmActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.CloudwatchAlarm; v != nil { + results = append(results, flattenIotCloudwatchAlarmAction(v)...) + } + } + + return results +} + +// Legacy root attribute handling +func flattenIotCloudwatchMetricActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.CloudwatchMetric; v != nil { + results = append(results, flattenIotCloudwatchMetricAction(v)...) + } + } + + return results +} + +func flattenIotCloudwatchMetricAction(apiObject *iot.CloudwatchMetricAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.MetricName; v != nil { + tfMap["metric_name"] = aws.StringValue(v) + } + + if v := apiObject.MetricNamespace; v != nil { + tfMap["metric_namespace"] = aws.StringValue(v) + } + + if v := apiObject.MetricTimestamp; v != nil { + tfMap["metric_timestamp"] = aws.StringValue(v) + } + + if v := apiObject.MetricUnit; v != nil { + tfMap["metric_unit"] = aws.StringValue(v) + } + + if v := apiObject.MetricValue; v != nil { + tfMap["metric_value"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotDynamoDbActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.DynamoDB; v != nil { + results = append(results, flattenIotDynamoDBAction(v)...) + } + } + + return results +} + +func flattenIotDynamoDBAction(apiObject *iot.DynamoDBAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.HashKeyField; v != nil { + tfMap["hash_key_field"] = aws.StringValue(v) + } + + if v := apiObject.HashKeyType; v != nil { + tfMap["hash_key_type"] = aws.StringValue(v) + } + + if v := apiObject.HashKeyValue; v != nil { + tfMap["hash_key_value"] = aws.StringValue(v) + } + + if v := apiObject.PayloadField; v != nil { + tfMap["payload_field"] = aws.StringValue(v) + } + + if v := apiObject.Operation; v != nil { + tfMap["operation"] = aws.StringValue(v) + } + + if v := apiObject.RangeKeyField; v != nil { + tfMap["range_key_field"] = aws.StringValue(v) + } + + if v := apiObject.RangeKeyType; v != nil { + tfMap["range_key_type"] = aws.StringValue(v) + } + + if v := apiObject.RangeKeyValue; v != nil { + tfMap["range_key_value"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + if v := apiObject.TableName; v != nil { + tfMap["table_name"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotDynamoDbv2Actions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.DynamoDBv2; v != nil { + results = append(results, flattenIotDynamoDBv2Action(v)...) + } + } + + return results +} + +func flattenIotDynamoDBv2Action(apiObject *iot.DynamoDBv2Action) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.PutItem; v != nil { + tfMap["put_item"] = flattenIotPutItemInput(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotElasticsearchActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.Elasticsearch; v != nil { + results = append(results, flattenIotElasticsearchAction(v)...) + } + } + + return results +} + +func flattenIotElasticsearchAction(apiObject *iot.ElasticsearchAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.Endpoint; v != nil { + tfMap["endpoint"] = aws.StringValue(v) + } + + if v := apiObject.Id; v != nil { + tfMap["id"] = aws.StringValue(v) + } + + if v := apiObject.Index; v != nil { + tfMap["index"] = aws.StringValue(v) + } + + if v := apiObject.Type; v != nil { + tfMap["type"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotFirehoseActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.Firehose; v != nil { + results = append(results, flattenIotFirehoseAction(v)...) + } + } + + return results +} + +func flattenIotFirehoseAction(apiObject *iot.FirehoseAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.DeliveryStreamName; v != nil { + tfMap["delivery_stream_name"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + if v := apiObject.Separator; v != nil { + tfMap["separator"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotIotAnalyticsActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.IotAnalytics; v != nil { + results = append(results, flattenIotIotAnalyticsAction(v)...) + } + } + + return results +} + +func flattenIotIotAnalyticsAction(apiObject *iot.IotAnalyticsAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.ChannelName; v != nil { + tfMap["channel_name"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotIotEventsActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.IotEvents; v != nil { + results = append(results, flattenIotIotEventsAction(v)...) + } + } + + return results +} + +func flattenIotIotEventsAction(apiObject *iot.IotEventsAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.InputName; v != nil { + tfMap["input_name"] = aws.StringValue(v) + } + + if v := apiObject.MessageId; v != nil { + tfMap["message_id"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotKinesisActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.Kinesis; v != nil { + results = append(results, flattenIotKinesisAction(v)...) + } + } + + return results +} + +func flattenIotKinesisAction(apiObject *iot.KinesisAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.PartitionKey; v != nil { + tfMap["partition_key"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + if v := apiObject.StreamName; v != nil { + tfMap["stream_name"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotLambdaActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.Lambda; v != nil { + results = append(results, flattenIotLambdaAction(v)...) + } + } + + return results +} + +func flattenIotLambdaAction(apiObject *iot.LambdaAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.FunctionArn; v != nil { + tfMap["function_arn"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +func flattenIotPutItemInput(apiObject *iot.PutItemInput) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.TableName; v != nil { + tfMap["table_name"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotRepublishActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.Republish; v != nil { + results = append(results, flattenIotRepublishAction(v)...) + } + } + + return results +} + +func flattenIotRepublishAction(apiObject *iot.RepublishAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.Qos; v != nil { + tfMap["qos"] = aws.Int64Value(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + if v := apiObject.Topic; v != nil { + tfMap["topic"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotS3Actions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.S3; v != nil { + results = append(results, flattenIotS3Action(v)...) + } + } + + return results +} + +func flattenIotS3Action(apiObject *iot.S3Action) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.BucketName; v != nil { + tfMap["bucket_name"] = aws.StringValue(v) + } + + if v := apiObject.Key; v != nil { + tfMap["key"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotSnsActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.Sns; v != nil { + results = append(results, flattenIotSnsAction(v)...) + } + } + + return results +} + +func flattenIotSnsAction(apiObject *iot.SnsAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.MessageFormat; v != nil { + tfMap["message_format"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + if v := apiObject.TargetArn; v != nil { + tfMap["target_arn"] = aws.StringValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotSqsActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.Sqs; v != nil { + results = append(results, flattenIotSqsAction(v)...) + } + } + + return results +} + +func flattenIotSqsAction(apiObject *iot.SqsAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.QueueUrl; v != nil { + tfMap["queue_url"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + if v := apiObject.UseBase64; v != nil { + tfMap["use_base64"] = aws.BoolValue(v) + } + + return []interface{}{tfMap} +} + +// Legacy root attribute handling +func flattenIotStepFunctionsActions(actions []*iot.Action) []interface{} { + results := make([]interface{}, 0) + + for _, action := range actions { + if action == nil { + continue + } + + if v := action.StepFunctions; v != nil { + results = append(results, flattenIotStepFunctionsAction(v)...) + } + } + + return results +} + +func flattenIotErrorAction(errorAction *iot.Action) []map[string]interface{} { + results := make([]map[string]interface{}, 0) + + if errorAction == nil { + return results + } + input := []*iot.Action{errorAction} + if errorAction.CloudwatchAlarm != nil { + results = append(results, map[string]interface{}{"cloudwatch_alarm": flattenIotCloudWatchAlarmActions(input)}) + return results + } + if errorAction.CloudwatchMetric != nil { + results = append(results, map[string]interface{}{"cloudwatch_metric": flattenIotCloudwatchMetricActions(input)}) + return results + } + if errorAction.DynamoDB != nil { + results = append(results, map[string]interface{}{"dynamodb": flattenIotDynamoDbActions(input)}) + return results + } + if errorAction.DynamoDBv2 != nil { + results = append(results, map[string]interface{}{"dynamodbv2": flattenIotDynamoDbv2Actions(input)}) + return results + } + if errorAction.Elasticsearch != nil { + results = append(results, map[string]interface{}{"elasticsearch": flattenIotElasticsearchActions(input)}) + return results + } + if errorAction.Firehose != nil { + results = append(results, map[string]interface{}{"firehose": flattenIotFirehoseActions(input)}) + return results + } + if errorAction.IotAnalytics != nil { + results = append(results, map[string]interface{}{"iot_analytics": flattenIotIotAnalyticsActions(input)}) + return results + } + if errorAction.IotEvents != nil { + results = append(results, map[string]interface{}{"iot_events": flattenIotIotEventsActions(input)}) + return results + } + if errorAction.Kinesis != nil { + results = append(results, map[string]interface{}{"kinesis": flattenIotKinesisActions(input)}) + return results + } + if errorAction.Lambda != nil { + results = append(results, map[string]interface{}{"lambda": flattenIotLambdaActions(input)}) + return results + } + if errorAction.Republish != nil { + results = append(results, map[string]interface{}{"republish": flattenIotRepublishActions(input)}) + return results + } + if errorAction.S3 != nil { + results = append(results, map[string]interface{}{"s3": flattenIotS3Actions(input)}) + return results + } + if errorAction.Sns != nil { + results = append(results, map[string]interface{}{"sns": flattenIotSnsActions(input)}) + return results + } + if errorAction.Sqs != nil { + results = append(results, map[string]interface{}{"sqs": flattenIotSqsActions(input)}) + return results + } + if errorAction.StepFunctions != nil { + results = append(results, map[string]interface{}{"step_functions": flattenIotStepFunctionsActions(input)}) + return results + } + + return results +} + +func flattenIotStepFunctionsAction(apiObject *iot.StepFunctionsAction) []interface{} { + if apiObject == nil { + return nil + } + + tfMap := make(map[string]interface{}) + + if v := apiObject.ExecutionNamePrefix; v != nil { + tfMap["execution_name_prefix"] = aws.StringValue(v) + } + + if v := apiObject.StateMachineName; v != nil { + tfMap["state_machine_name"] = aws.StringValue(v) + } + + if v := apiObject.RoleArn; v != nil { + tfMap["role_arn"] = aws.StringValue(v) + } + + return []interface{}{tfMap} } diff --git a/aws/resource_aws_iot_topic_rule_test.go b/aws/resource_aws_iot_topic_rule_test.go index 4ebbed7c95b..e30b8023686 100644 --- a/aws/resource_aws_iot_topic_rule_test.go +++ b/aws/resource_aws_iot_topic_rule_test.go @@ -2,14 +2,71 @@ package aws import ( "fmt" + "log" "testing" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/iot" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) +func init() { + resource.AddTestSweepers("aws_iot_topic_rule", &resource.Sweeper{ + Name: "aws_iot_topic_rule", + F: testSweepIotTopicRules, + }) +} + +func testSweepIotTopicRules(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).iotconn + input := &iot.ListTopicRulesInput{} + var sweeperErrs *multierror.Error + + for { + output, err := conn.ListTopicRules(input) + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping IoT Topic Rules sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors + } + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving IoT Topic Rules: %w", err)) + return sweeperErrs + } + + for _, rule := range output.Rules { + name := aws.StringValue(rule.RuleName) + + log.Printf("[INFO] Deleting IoT Topic Rule: %s", name) + _, err := conn.DeleteTopicRule(&iot.DeleteTopicRuleInput{ + RuleName: aws.String(name), + }) + if isAWSErr(err, iot.ErrCodeUnauthorizedException, "") { + continue + } + if err != nil { + sweeperErr := fmt.Errorf("error deleting IoT Topic Rule (%s): %w", name, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + } + + if aws.StringValue(output.NextToken) == "" { + break + } + input.NextToken = output.NextToken + } + + return sweeperErrs.ErrorOrNil() +} + func TestAccAWSIoTTopicRule_basic(t *testing.T) { rName := acctest.RandString(5) resourceName := "aws_iot_topic_rule.rule" @@ -22,12 +79,13 @@ func TestAccAWSIoTTopicRule_basic(t *testing.T) { { Config: testAccAWSIoTTopicRule_basic(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), resource.TestCheckResourceAttr("aws_iot_topic_rule.rule", "name", fmt.Sprintf("test_rule_%s", rName)), resource.TestCheckResourceAttr("aws_iot_topic_rule.rule", "description", "Example rule"), resource.TestCheckResourceAttr("aws_iot_topic_rule.rule", "enabled", "true"), resource.TestCheckResourceAttr("aws_iot_topic_rule.rule", "sql", "SELECT * FROM 'topic/test'"), resource.TestCheckResourceAttr("aws_iot_topic_rule.rule", "sql_version", "2015-10-08"), + resource.TestCheckResourceAttr("aws_iot_topic_rule.rule", "tags.%", "0"), ), }, { @@ -51,7 +109,7 @@ func TestAccAWSIoTTopicRule_cloudwatchalarm(t *testing.T) { { Config: testAccAWSIoTTopicRule_cloudwatchalarm(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -75,7 +133,7 @@ func TestAccAWSIoTTopicRule_cloudwatchmetric(t *testing.T) { { Config: testAccAWSIoTTopicRule_cloudwatchmetric(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -99,7 +157,7 @@ func TestAccAWSIoTTopicRule_dynamodb(t *testing.T) { { Config: testAccAWSIoTTopicRule_dynamodb(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -110,7 +168,25 @@ func TestAccAWSIoTTopicRule_dynamodb(t *testing.T) { { Config: testAccAWSIoTTopicRule_dynamodb_rangekeys(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), + ), + }, + }, + }) +} + +func TestAccAWSIoTTopicRule_dynamoDbv2(t *testing.T) { + rName := acctest.RandString(5) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSIoTTopicRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSIoTTopicRule_dynamoDbv2(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, }, @@ -129,7 +205,7 @@ func TestAccAWSIoTTopicRule_elasticsearch(t *testing.T) { { Config: testAccAWSIoTTopicRule_elasticsearch(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -153,7 +229,7 @@ func TestAccAWSIoTTopicRule_firehose(t *testing.T) { { Config: testAccAWSIoTTopicRule_firehose(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -177,7 +253,7 @@ func TestAccAWSIoTTopicRule_firehose_separator(t *testing.T) { { Config: testAccAWSIoTTopicRule_firehose_separator(rName, "\n"), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -188,7 +264,7 @@ func TestAccAWSIoTTopicRule_firehose_separator(t *testing.T) { { Config: testAccAWSIoTTopicRule_firehose_separator(rName, ","), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, }, @@ -207,7 +283,7 @@ func TestAccAWSIoTTopicRule_kinesis(t *testing.T) { { Config: testAccAWSIoTTopicRule_kinesis(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -231,7 +307,7 @@ func TestAccAWSIoTTopicRule_lambda(t *testing.T) { { Config: testAccAWSIoTTopicRule_lambda(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -255,7 +331,31 @@ func TestAccAWSIoTTopicRule_republish(t *testing.T) { { Config: testAccAWSIoTTopicRule_republish(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSIoTTopicRule_republish_with_qos(t *testing.T) { + rName := acctest.RandString(5) + resourceName := "aws_iot_topic_rule.rule" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSIoTTopicRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSIoTTopicRule_republish_with_qos(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -279,7 +379,7 @@ func TestAccAWSIoTTopicRule_s3(t *testing.T) { { Config: testAccAWSIoTTopicRule_s3(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -303,7 +403,7 @@ func TestAccAWSIoTTopicRule_sns(t *testing.T) { { Config: testAccAWSIoTTopicRule_sns(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -327,7 +427,134 @@ func TestAccAWSIoTTopicRule_sqs(t *testing.T) { { Config: testAccAWSIoTTopicRule_sqs(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSIoTTopicRuleExists_basic("aws_iot_topic_rule.rule"), + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSIoTTopicRule_step_functions(t *testing.T) { + rName := acctest.RandString(5) + resourceName := "aws_iot_topic_rule.rule" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSIoTTopicRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSIoTTopicRule_step_functions(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSIoTTopicRule_iot_analytics(t *testing.T) { + rName := acctest.RandString(5) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSIoTTopicRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSIoTTopicRule_iot_analytics(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), + ), + }, + }, + }) +} + +func TestAccAWSIoTTopicRule_iot_events(t *testing.T) { + rName := acctest.RandString(5) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSIoTTopicRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSIoTTopicRule_iot_events(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), + ), + }, + }, + }) +} + +func TestAccAWSIoTTopicRule_Tags(t *testing.T) { + rName := acctest.RandString(5) + resourceName := "aws_iot_topic_rule.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSIoTTopicRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSIoTTopicRuleTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSIoTTopicRuleExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSIoTTopicRuleTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSIoTTopicRuleExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccAWSIoTTopicRuleTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSIoTTopicRuleExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + +func TestAccAWSIoTTopicRule_errorAction(t *testing.T) { + rName := acctest.RandString(5) + resourceName := "aws_iot_topic_rule.rule" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSIoTTopicRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSIoTTopicRule_errorAction(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSIoTTopicRuleExists("aws_iot_topic_rule.rule"), ), }, { @@ -347,7 +574,9 @@ func testAccCheckAWSIoTTopicRuleDestroy(s *terraform.State) error { continue } - out, err := conn.ListTopicRules(&iot.ListTopicRulesInput{}) + input := &iot.ListTopicRulesInput{} + + out, err := conn.ListTopicRules(input) if err != nil { return err @@ -364,14 +593,29 @@ func testAccCheckAWSIoTTopicRuleDestroy(s *terraform.State) error { return nil } -func testAccCheckAWSIoTTopicRuleExists_basic(name string) resource.TestCheckFunc { +func testAccCheckAWSIoTTopicRuleExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { - _, ok := s.RootModule().Resources[name] + rs, ok := s.RootModule().Resources[name] if !ok { return fmt.Errorf("Not found: %s", name) } - return nil + conn := testAccProvider.Meta().(*AWSClient).iotconn + input := &iot.ListTopicRulesInput{} + + output, err := conn.ListTopicRules(input) + + if err != nil { + return err + } + + for _, rule := range output.Rules { + if aws.StringValue(rule.RuleName) == rs.Primary.ID { + return nil + } + } + + return fmt.Errorf("IoT Topic Rule (%s) not found", rs.Primary.ID) } } @@ -467,6 +711,26 @@ resource "aws_iot_topic_rule" "rule" { `, rName) } +func testAccAWSIoTTopicRule_dynamoDbv2(rName string) string { + return fmt.Sprintf(testAccAWSIoTTopicRuleRole+` +resource "aws_iot_topic_rule" "rule" { + name = "test_rule_%[1]s" + description = "Example rule" + enabled = true + sql = "SELECT field as column_name FROM 'topic/test'" + sql_version = "2015-10-08" + + dynamodbv2 { + put_item { + table_name = "test" + } + + role_arn = aws_iam_role.iot_role.arn + } +} +`, rName) +} + func testAccAWSIoTTopicRule_dynamodb(rName string) string { return fmt.Sprintf(testAccAWSIoTTopicRuleRole+` resource "aws_iot_topic_rule" "rule" { @@ -481,7 +745,7 @@ resource "aws_iot_topic_rule" "rule" { hash_key_value = "hash_key_value" payload_field = "payload_field" role_arn = "${aws_iam_role.iot_role.arn}" - table_name = "table_name" + table_name = "table_name" } } `, rName) @@ -504,7 +768,8 @@ resource "aws_iot_topic_rule" "rule" { range_key_value = "range_key_value" range_key_type = "STRING" role_arn = "${aws_iam_role.iot_role.arn}" - table_name = "table_name" + table_name = "table_name" + operation = "INSERT" } } `, rName) @@ -617,6 +882,24 @@ resource "aws_iot_topic_rule" "rule" { `, rName) } +func testAccAWSIoTTopicRule_republish_with_qos(rName string) string { + return fmt.Sprintf(testAccAWSIoTTopicRuleRole+` +resource "aws_iot_topic_rule" "rule" { + name = "test_rule_%[1]s" + description = "Example rule" + enabled = true + sql = "SELECT * FROM 'topic/test'" + sql_version = "2015-10-08" + + republish { + role_arn = "${aws_iam_role.iot_role.arn}" + topic = "mytopic" + qos = 1 + } +} +`, rName) +} + func testAccAWSIoTTopicRule_s3(rName string) string { return fmt.Sprintf(testAccAWSIoTTopicRuleRole+` resource "aws_iot_topic_rule" "rule" { @@ -669,3 +952,109 @@ resource "aws_iot_topic_rule" "rule" { } `, rName) } + +func testAccAWSIoTTopicRule_step_functions(rName string) string { + return fmt.Sprintf(testAccAWSIoTTopicRuleRole+` +resource "aws_iot_topic_rule" "rule" { + name = "test_rule_%[1]s" + description = "Example rule" + enabled = true + sql = "SELECT * FROM 'topic/test'" + sql_version = "2015-10-08" + + step_functions { + execution_name_prefix = "myprefix" + state_machine_name = "mystatemachine" + role_arn = "${aws_iam_role.iot_role.arn}" + } +} +`, rName) +} + +func testAccAWSIoTTopicRule_iot_analytics(rName string) string { + return fmt.Sprintf(testAccAWSIoTTopicRuleRole+` +resource "aws_iot_topic_rule" "rule" { + name = "test_rule_%[1]s" + description = "Example rule" + enabled = true + sql = "SELECT * FROM 'topic/test'" + sql_version = "2015-10-08" + + iot_analytics { + channel_name = "fakedata" + role_arn = "${aws_iam_role.iot_role.arn}" + } +} +`, rName) +} + +func testAccAWSIoTTopicRule_iot_events(rName string) string { + return fmt.Sprintf(testAccAWSIoTTopicRuleRole+` +resource "aws_iot_topic_rule" "rule" { + name = "test_rule_%[1]s" + description = "Example rule" + enabled = true + sql = "SELECT * FROM 'topic/test'" + sql_version = "2015-10-08" + + iot_events { + input_name = "fake_input_name" + role_arn = "${aws_iam_role.iot_role.arn}" + message_id = "fake_message_id" + } +} +`, rName) +} + +func testAccAWSIoTTopicRuleTags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(testAccAWSIoTTopicRuleRole+` +resource "aws_iot_topic_rule" "test" { + name = "test_rule_%[1]s" + enabled = true + sql = "SELECT * FROM 'topic/test'" + sql_version = "2015-10-08" + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccAWSIoTTopicRuleTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(testAccAWSIoTTopicRuleRole+` +resource "aws_iot_topic_rule" "test" { + name = "test_rule_%[1]s" + enabled = true + sql = "SELECT * FROM 'topic/test'" + sql_version = "2015-10-08" + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} + +func testAccAWSIoTTopicRule_errorAction(rName string) string { + return fmt.Sprintf(testAccAWSIoTTopicRuleRole+` +resource "aws_iot_topic_rule" "rule" { + name = "test_rule_%[1]s" + description = "Example rule" + enabled = true + sql = "SELECT * FROM 'topic/test'" + sql_version = "2015-10-08" + kinesis { + stream_name = "mystream" + role_arn = "${aws_iam_role.iot_role.arn}" + } + error_action { + kinesis { + stream_name = "mystream" + role_arn = "${aws_iam_role.iot_role.arn}" + } + } +} +`, rName) +} diff --git a/aws/resource_aws_key_pair.go b/aws/resource_aws_key_pair.go index 8ff134a3e8c..82334aa091e 100644 --- a/aws/resource_aws_key_pair.go +++ b/aws/resource_aws_key_pair.go @@ -2,17 +2,20 @@ package aws import ( "fmt" + "log" "strings" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) func resourceAwsKeyPair() *schema.Resource { + //lintignore:R011 return &schema.Resource{ Create: resourceAwsKeyPairCreate, Read: resourceAwsKeyPairRead, @@ -63,6 +66,10 @@ func resourceAwsKeyPair() *schema.Resource { Computed: true, }, "tags": tagsSchema(), + "arn": { + Type: schema.TypeString, + Computed: true, + }, }, } } @@ -92,7 +99,7 @@ func resourceAwsKeyPairCreate(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("Error import KeyPair: %s", err) } - d.SetId(*resp.KeyName) + d.SetId(aws.StringValue(resp.KeyName)) return resourceAwsKeyPairRead(d, meta) } @@ -107,25 +114,43 @@ func resourceAwsKeyPairRead(d *schema.ResourceData, meta interface{}) error { resp, err := conn.DescribeKeyPairs(req) if err != nil { if isAWSErr(err, "InvalidKeyPair.NotFound", "") { + log.Printf("[WARN] Key Pair (%s) not found, removing from state", d.Id()) d.SetId("") return nil } return fmt.Errorf("Error retrieving KeyPair: %s", err) } - for _, keyPair := range resp.KeyPairs { - if *keyPair.KeyName == d.Id() { - d.Set("key_name", keyPair.KeyName) - d.Set("fingerprint", keyPair.KeyFingerprint) - d.Set("key_pair_id", keyPair.KeyPairId) - if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(keyPair.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %s", err) - } - return nil - } + if len(resp.KeyPairs) == 0 { + log.Printf("[WARN] Key Pair (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + kp := resp.KeyPairs[0] + + if aws.StringValue(kp.KeyName) != d.Id() { + return fmt.Errorf("Unable to find key pair within: %#v", resp.KeyPairs) + } + + d.Set("key_name", kp.KeyName) + d.Set("fingerprint", kp.KeyFingerprint) + d.Set("key_pair_id", kp.KeyPairId) + if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(kp.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) } - return fmt.Errorf("Unable to find key pair within: %#v", resp.KeyPairs) + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Service: "ec2", + Region: meta.(*AWSClient).region, + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("key-pair/%s", d.Id()), + }.String() + + d.Set("arn", arn) + + return nil } func resourceAwsKeyPairUpdate(d *schema.ResourceData, meta interface{}) error { diff --git a/aws/resource_aws_key_pair_migrate.go b/aws/resource_aws_key_pair_migrate.go index 1f3560969c9..36ca58e3152 100644 --- a/aws/resource_aws_key_pair_migrate.go +++ b/aws/resource_aws_key_pair_migrate.go @@ -5,7 +5,7 @@ import ( "log" "strings" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func resourceAwsKeyPairMigrateState( diff --git a/aws/resource_aws_key_pair_migrate_test.go b/aws/resource_aws_key_pair_migrate_test.go index 36359464665..2c8171fd8a5 100644 --- a/aws/resource_aws_key_pair_migrate_test.go +++ b/aws/resource_aws_key_pair_migrate_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAWSKeyPairMigrateState(t *testing.T) { diff --git a/aws/resource_aws_key_pair_test.go b/aws/resource_aws_key_pair_test.go index 9ef05cdc3fc..8c7d64077db 100644 --- a/aws/resource_aws_key_pair_test.go +++ b/aws/resource_aws_key_pair_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -72,6 +72,7 @@ func TestAccAWSKeyPair_basic(t *testing.T) { Config: testAccAWSKeyPairConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSKeyPairExists(resourceName, &keyPair), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "ec2", fmt.Sprintf("key-pair/%s", rName)), testAccCheckAWSKeyPairFingerprint(&keyPair, fingerprint), resource.TestCheckResourceAttr(resourceName, "fingerprint", fingerprint), resource.TestCheckResourceAttr(resourceName, "key_name", rName), @@ -202,7 +203,7 @@ func TestAccAWSKeyPair_disappears(t *testing.T) { Config: testAccAWSKeyPairConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSKeyPairExists(resourceName, &keyPair), - testAccCheckAWSKeyPairDisappears(&keyPair), + testAccCheckResourceDisappears(testAccProvider, resourceAwsKeyPair(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -237,21 +238,6 @@ func testAccCheckAWSKeyPairDestroy(s *terraform.State) error { return nil } -func testAccCheckAWSKeyPairDisappears(keyPair *ec2.KeyPairInfo) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - - req := &ec2.DeleteKeyPairInput{ - KeyName: keyPair.KeyName, - } - if _, err := conn.DeleteKeyPair(req); err != nil { - return err - } - - return nil - } -} - func testAccCheckAWSKeyPairFingerprint(conf *ec2.KeyPairInfo, expectedFingerprint string) resource.TestCheckFunc { return func(s *terraform.State) error { if aws.StringValue(conf.KeyFingerprint) != expectedFingerprint { @@ -290,7 +276,7 @@ func testAccCheckAWSKeyPairExists(n string, res *ec2.KeyPairInfo) resource.TestC return err } if len(resp.KeyPairs) != 1 || - *resp.KeyPairs[0].KeyName != rs.Primary.ID { + aws.StringValue(resp.KeyPairs[0].KeyName) != rs.Primary.ID { return fmt.Errorf("KeyPair not found") } diff --git a/aws/resource_aws_kinesis_analytics_application.go b/aws/resource_aws_kinesis_analytics_application.go index 95d3c6f425d..c2e9411be8f 100644 --- a/aws/resource_aws_kinesis_analytics_application.go +++ b/aws/resource_aws_kinesis_analytics_application.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kinesisanalytics" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -704,10 +704,7 @@ func resourceAwsKinesisAnalyticsApplicationUpdate(d *schema.ResourceData, meta i CurrentApplicationVersionId: aws.Int64(int64(version)), } - applicationUpdate, err := createApplicationUpdateOpts(d) - if err != nil { - return err - } + applicationUpdate := createApplicationUpdateOpts(d) if !reflect.DeepEqual(applicationUpdate, &kinesisanalytics.ApplicationUpdate{}) { updateApplicationOpts.SetApplicationUpdate(applicationUpdate) @@ -1085,7 +1082,7 @@ func expandKinesisAnalyticsReferenceData(rd map[string]interface{}) *kinesisanal return referenceData } -func createApplicationUpdateOpts(d *schema.ResourceData) (*kinesisanalytics.ApplicationUpdate, error) { +func createApplicationUpdateOpts(d *schema.ResourceData) *kinesisanalytics.ApplicationUpdate { applicationUpdate := &kinesisanalytics.ApplicationUpdate{} if d.HasChange("code") { @@ -1154,7 +1151,7 @@ func createApplicationUpdateOpts(d *schema.ResourceData) (*kinesisanalytics.Appl } } - return applicationUpdate, nil + return applicationUpdate } func expandKinesisAnalyticsInputUpdate(vL map[string]interface{}) *kinesisanalytics.InputUpdate { diff --git a/aws/resource_aws_kinesis_analytics_application_test.go b/aws/resource_aws_kinesis_analytics_application_test.go index 36bf1348106..c42b8c82842 100644 --- a/aws/resource_aws_kinesis_analytics_application_test.go +++ b/aws/resource_aws_kinesis_analytics_application_test.go @@ -2,15 +2,102 @@ package aws import ( "fmt" + "log" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kinesisanalytics" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/kinesisanalytics/waiter" ) +func init() { + resource.AddTestSweepers("aws_kinesis_analytics_application", &resource.Sweeper{ + Name: "aws_kinesis_analytics_application", + F: testSweepKinesisAnalyticsApplications, + }) +} + +func testSweepKinesisAnalyticsApplications(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).kinesisanalyticsconn + input := &kinesisanalytics.ListApplicationsInput{} + var sweeperErrs *multierror.Error + + for { + output, err := conn.ListApplications(input) + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping Kinesis Analytics Application sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors + } + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving Kinesis Analytics Applications: %w", err)) + return sweeperErrs + } + + var name string + for _, applicationSummary := range output.ApplicationSummaries { + name = aws.StringValue(applicationSummary.ApplicationName) + + output, err := conn.DescribeApplication(&kinesisanalytics.DescribeApplicationInput{ + ApplicationName: aws.String(name), + }) + if isAWSErr(err, kinesisanalytics.ErrCodeResourceNotFoundException, "") { + continue + } + if err != nil { + sweeperErr := fmt.Errorf("error describing Kinesis Analytics Application (%s): %w", name, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + + if output.ApplicationDetail == nil { + continue + } + + log.Printf("[INFO] Deleting Kinesis Analytics Application: %s", name) + _, err = conn.DeleteApplication(&kinesisanalytics.DeleteApplicationInput{ + ApplicationName: aws.String(name), + CreateTimestamp: output.ApplicationDetail.CreateTimestamp, + }) + if isAWSErr(err, kinesisanalytics.ErrCodeResourceNotFoundException, "") { + continue + } + if err != nil { + sweeperErr := fmt.Errorf("error deleting Kinesis Analytics Application (%s): %w", name, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + + _, err = waiter.ApplicationDeleted(conn, name) + if isAWSErr(err, kinesisanalytics.ErrCodeResourceNotFoundException, "") { + continue + } + if err != nil { + sweeperErr := fmt.Errorf("error waiting for Kinesis Analytics Application (%s) to be deleted: %w", name, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + } + + if !aws.BoolValue(output.HasMoreApplications) { + break + } + input.ExclusiveStartApplicationName = aws.String(name) + } + + return sweeperErrs.ErrorOrNil() +} + func TestAccAWSKinesisAnalyticsApplication_basic(t *testing.T) { var application kinesisanalytics.ApplicationDetail resName := "aws_kinesis_analytics_application.test" diff --git a/aws/resource_aws_kinesis_firehose_delivery_stream.go b/aws/resource_aws_kinesis_firehose_delivery_stream.go index 09b4b2e6fd4..94efd6b7566 100644 --- a/aws/resource_aws_kinesis_firehose_delivery_stream.go +++ b/aws/resource_aws_kinesis_firehose_delivery_stream.go @@ -1,7 +1,6 @@ package aws import ( - "bytes" "fmt" "log" "strings" @@ -10,10 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/firehose" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -23,7 +21,7 @@ const ( func cloudWatchLoggingOptionsSchema() *schema.Schema { return &schema.Schema{ - Type: schema.TypeSet, + Type: schema.TypeList, MaxItems: 1, Optional: true, Computed: true, @@ -76,7 +74,7 @@ func s3ConfigurationSchema() *schema.Schema { "compression_format": { Type: schema.TypeString, Optional: true, - Default: "UNCOMPRESSED", + Default: firehose.CompressionFormatUncompressed, }, "kms_key_arn": { @@ -126,26 +124,18 @@ func processingConfigurationSchema() *schema.Schema { "parameter_name": { Type: schema.TypeString, Required: true, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if value != "LambdaArn" && value != "NumberOfRetries" && value != "RoleArn" && value != "BufferSizeInMBs" && value != "BufferIntervalInSeconds" { - errors = append(errors, fmt.Errorf( - "%q must be one of 'LambdaArn', 'NumberOfRetries', 'RoleArn', 'BufferSizeInMBs', 'BufferIntervalInSeconds'", k)) - } - return - }, + ValidateFunc: validation.StringInSlice([]string{ + firehose.ProcessorParameterNameLambdaArn, + firehose.ProcessorParameterNameNumberOfRetries, + firehose.ProcessorParameterNameRoleArn, + firehose.ProcessorParameterNameBufferSizeInMbs, + firehose.ProcessorParameterNameBufferIntervalInSeconds, + }, false), }, "parameter_value": { - Type: schema.TypeString, - Required: true, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if len(value) < 1 || len(value) > 512 { - errors = append(errors, fmt.Errorf( - "%q must be at least one character long and at most 512 characters long", k)) - } - return - }, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 512), }, }, }, @@ -153,14 +143,9 @@ func processingConfigurationSchema() *schema.Schema { "type": { Type: schema.TypeString, Required: true, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if value != "Lambda" { - errors = append(errors, fmt.Errorf( - "%q must be 'Lambda'", k)) - } - return - }, + ValidateFunc: validation.StringInSlice([]string{ + firehose.ProcessorTypeLambda, + }, false), }, }, }, @@ -170,20 +155,9 @@ func processingConfigurationSchema() *schema.Schema { } } -func cloudwatchLoggingOptionsHash(v interface{}) int { - var buf bytes.Buffer - m := v.(map[string]interface{}) - buf.WriteString(fmt.Sprintf("%t-", m["enabled"].(bool))) - if m["enabled"].(bool) { - buf.WriteString(fmt.Sprintf("%s-", m["log_group_name"].(string))) - buf.WriteString(fmt.Sprintf("%s-", m["log_stream_name"].(string))) - } - return hashcode.String(buf.String()) -} - -func flattenCloudwatchLoggingOptions(clo *firehose.CloudWatchLoggingOptions) *schema.Set { +func flattenCloudwatchLoggingOptions(clo *firehose.CloudWatchLoggingOptions) []interface{} { if clo == nil { - return schema.NewSet(cloudwatchLoggingOptionsHash, []interface{}{}) + return []interface{}{} } cloudwatchLoggingOptions := map[string]interface{}{ @@ -193,7 +167,7 @@ func flattenCloudwatchLoggingOptions(clo *firehose.CloudWatchLoggingOptions) *sc cloudwatchLoggingOptions["log_group_name"] = aws.StringValue(clo.LogGroupName) cloudwatchLoggingOptions["log_stream_name"] = aws.StringValue(clo.LogStreamName) } - return schema.NewSet(cloudwatchLoggingOptionsHash, []interface{}{cloudwatchLoggingOptions}) + return []interface{}{cloudwatchLoggingOptions} } func flattenFirehoseElasticsearchConfiguration(description *firehose.ElasticsearchDestinationDescription) []map[string]interface{} { @@ -597,6 +571,19 @@ func flattenProcessingConfiguration(pc *firehose.ProcessingConfiguration, roleAr return processingConfiguration } +func flattenFirehoseKinesisSourceConfiguration(desc *firehose.KinesisStreamSourceDescription) []interface{} { + if desc == nil { + return []interface{}{} + } + + mDesc := map[string]interface{}{ + "kinesis_stream_arn": aws.StringValue(desc.KinesisStreamARN), + "role_arn": aws.StringValue(desc.RoleARN), + } + + return []interface{}{mDesc} +} + func flattenKinesisFirehoseDeliveryStream(d *schema.ResourceData, s *firehose.DeliveryStreamDescription) error { d.Set("version_id", s.VersionId) d.Set("arn", s.DeliveryStreamARN) @@ -612,6 +599,12 @@ func flattenKinesisFirehoseDeliveryStream(d *schema.ResourceData, s *firehose.De return fmt.Errorf("error setting server_side_encryption: %s", err) } + if s.Source != nil { + if err := d.Set("kinesis_source_configuration", flattenFirehoseKinesisSourceConfiguration(s.Source.KinesisStreamSourceDescription)); err != nil { + return fmt.Errorf("error setting kinesis_source_configuration: %s", err) + } + } + if len(s.Destinations) > 0 { destination := s.Destinations[0] if destination.RedshiftDestinationDescription != nil { @@ -652,10 +645,12 @@ func flattenKinesisFirehoseDeliveryStream(d *schema.ResourceData, s *firehose.De } d.Set("destination_id", destination.DestinationId) } + return nil } func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { + //lintignore:R011 return &schema.Resource{ Create: resourceAwsKinesisFirehoseDeliveryStreamCreate, Read: resourceAwsKinesisFirehoseDeliveryStreamRead, @@ -682,17 +677,10 @@ func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { MigrateState: resourceAwsKinesisFirehoseMigrateState, Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if len(value) > 64 { - errors = append(errors, fmt.Errorf( - "%q cannot be longer than 64 characters", k)) - } - return - }, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 64), }, "tags": tagsSchema(), @@ -747,14 +735,13 @@ func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { value := v.(string) return strings.ToLower(value) }, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if value != "s3" && value != "extended_s3" && value != "redshift" && value != "elasticsearch" && value != "splunk" { - errors = append(errors, fmt.Errorf( - "%q must be one of 's3', 'extended_s3', 'redshift', 'elasticsearch', 'splunk'", k)) - } - return - }, + ValidateFunc: validation.StringInSlice([]string{ + "elasticsearch", + "extended_s3", + "redshift", + "s3", + "splunk", + }, false), }, "s3_configuration": s3ConfigurationSchema(), @@ -786,7 +773,7 @@ func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { "compression_format": { Type: schema.TypeString, Optional: true, - Default: "UNCOMPRESSED", + Default: firehose.CompressionFormatUncompressed, }, "data_format_conversion_configuration": { @@ -1071,15 +1058,11 @@ func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { "s3_backup_mode": { Type: schema.TypeString, Optional: true, - Default: "Disabled", - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if value != "Disabled" && value != "Enabled" { - errors = append(errors, fmt.Errorf( - "%q must be one of 'Disabled', 'Enabled'", k)) - } - return - }, + Default: firehose.S3BackupModeDisabled, + ValidateFunc: validation.StringInSlice([]string{ + firehose.S3BackupModeDisabled, + firehose.S3BackupModeEnabled, + }, false), }, "s3_backup_configuration": s3ConfigurationSchema(), @@ -1123,15 +1106,11 @@ func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { "s3_backup_mode": { Type: schema.TypeString, Optional: true, - Default: "Disabled", - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if value != "Disabled" && value != "Enabled" { - errors = append(errors, fmt.Errorf( - "%q must be one of 'Disabled', 'Enabled'", k)) - } - return - }, + Default: firehose.S3BackupModeDisabled, + ValidateFunc: validation.StringInSlice([]string{ + firehose.S3BackupModeDisabled, + firehose.S3BackupModeEnabled, + }, false), }, "s3_backup_configuration": s3ConfigurationSchema(), @@ -1217,15 +1196,14 @@ func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { "index_rotation_period": { Type: schema.TypeString, Optional: true, - Default: "OneDay", - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if value != "NoRotation" && value != "OneHour" && value != "OneDay" && value != "OneWeek" && value != "OneMonth" { - errors = append(errors, fmt.Errorf( - "%q must be one of 'NoRotation', 'OneHour', 'OneDay', 'OneWeek', 'OneMonth'", k)) - } - return - }, + Default: firehose.ElasticsearchIndexRotationPeriodOneDay, + ValidateFunc: validation.StringInSlice([]string{ + firehose.ElasticsearchIndexRotationPeriodNoRotation, + firehose.ElasticsearchIndexRotationPeriodOneHour, + firehose.ElasticsearchIndexRotationPeriodOneDay, + firehose.ElasticsearchIndexRotationPeriodOneWeek, + firehose.ElasticsearchIndexRotationPeriodOneMonth, + }, false), }, "retry_duration": { @@ -1251,15 +1229,11 @@ func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { Type: schema.TypeString, ForceNew: true, Optional: true, - Default: "FailedDocumentsOnly", - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if value != "FailedDocumentsOnly" && value != "AllDocuments" { - errors = append(errors, fmt.Errorf( - "%q must be one of 'FailedDocumentsOnly', 'AllDocuments'", k)) - } - return - }, + Default: firehose.ElasticsearchS3BackupModeFailedDocumentsOnly, + ValidateFunc: validation.StringInSlice([]string{ + firehose.ElasticsearchS3BackupModeFailedDocumentsOnly, + firehose.ElasticsearchS3BackupModeAllDocuments, + }, false), }, "type_name": { @@ -1304,14 +1278,10 @@ func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { Type: schema.TypeString, Optional: true, Default: firehose.HECEndpointTypeRaw, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if value != firehose.HECEndpointTypeRaw && value != firehose.HECEndpointTypeEvent { - errors = append(errors, fmt.Errorf( - "%q must be one of 'Raw', 'Event'", k)) - } - return - }, + ValidateFunc: validation.StringInSlice([]string{ + firehose.HECEndpointTypeRaw, + firehose.HECEndpointTypeEvent, + }, false), }, "hec_token": { @@ -1323,14 +1293,10 @@ func resourceAwsKinesisFirehoseDeliveryStream() *schema.Resource { Type: schema.TypeString, Optional: true, Default: firehose.SplunkS3BackupModeFailedEventsOnly, - ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if value != firehose.SplunkS3BackupModeFailedEventsOnly && value != firehose.SplunkS3BackupModeAllEvents { - errors = append(errors, fmt.Errorf( - "%q must be one of 'FailedEventsOnly', 'AllEvents'", k)) - } - return - }, + ValidateFunc: validation.StringInSlice([]string{ + firehose.SplunkS3BackupModeFailedEventsOnly, + firehose.SplunkS3BackupModeAllEvents, + }, false), }, "retry_duration": { @@ -1804,7 +1770,7 @@ func extractEncryptionConfiguration(s3 map[string]interface{}) *firehose.Encrypt } func extractCloudWatchLoggingConfiguration(s3 map[string]interface{}) *firehose.CloudWatchLoggingOptions { - config := s3["cloudwatch_logging_options"].(*schema.Set).List() + config := s3["cloudwatch_logging_options"].([]interface{}) if len(config) == 0 { return nil } diff --git a/aws/resource_aws_kinesis_firehose_delivery_stream_migrate.go b/aws/resource_aws_kinesis_firehose_delivery_stream_migrate.go index 9ae0f9bb92a..2a04ede035f 100644 --- a/aws/resource_aws_kinesis_firehose_delivery_stream_migrate.go +++ b/aws/resource_aws_kinesis_firehose_delivery_stream_migrate.go @@ -4,7 +4,7 @@ import ( "fmt" "log" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func resourceAwsKinesisFirehoseMigrateState( diff --git a/aws/resource_aws_kinesis_firehose_delivery_stream_migrate_test.go b/aws/resource_aws_kinesis_firehose_delivery_stream_migrate_test.go index 58338c88475..035f0610fbf 100644 --- a/aws/resource_aws_kinesis_firehose_delivery_stream_migrate_test.go +++ b/aws/resource_aws_kinesis_firehose_delivery_stream_migrate_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAWSKinesisFirehoseMigrateState(t *testing.T) { diff --git a/aws/resource_aws_kinesis_firehose_delivery_stream_test.go b/aws/resource_aws_kinesis_firehose_delivery_stream_test.go index 099f901f27b..fc06f4fa9c6 100644 --- a/aws/resource_aws_kinesis_firehose_delivery_stream_test.go +++ b/aws/resource_aws_kinesis_firehose_delivery_stream_test.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/firehose" "github.com/aws/aws-sdk-go/service/lambda" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -125,6 +125,36 @@ func TestAccAWSKinesisFirehoseDeliveryStream_basic(t *testing.T) { }) } +func TestAccAWSKinesisFirehoseDeliveryStream_disappears(t *testing.T) { + resourceName := "aws_kinesis_firehose_delivery_stream.test" + rInt := acctest.RandInt() + + funcName := fmt.Sprintf("aws_kinesis_firehose_ds_import_%d", rInt) + policyName := fmt.Sprintf("tf_acc_policy_%d", rInt) + roleName := fmt.Sprintf("tf_acc_role_%d", rInt) + var stream firehose.DeliveryStreamDescription + + config := testAccFirehoseAWSLambdaConfigBasic(funcName, policyName, roleName) + + fmt.Sprintf(testAccKinesisFirehoseDeliveryStreamConfig_extendedS3basic, + rInt, rInt, rInt, rInt) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckKinesisFirehoseDeliveryStreamDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testAccCheckKinesisFirehoseDeliveryStreamExists(resourceName, &stream), + testAccCheckResourceDisappears(testAccProvider, resourceAwsKinesisFirehoseDeliveryStream(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func TestAccAWSKinesisFirehoseDeliveryStream_s3basic(t *testing.T) { var stream firehose.DeliveryStreamDescription ri := acctest.RandInt() @@ -761,7 +791,7 @@ func TestAccAWSKinesisFirehoseDeliveryStream_ExtendedS3KmsKeyArn(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckKinesisFirehoseDeliveryStreamExists(resourceName, &stream), testAccCheckAWSKinesisFirehoseDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil), - resource.TestMatchResourceAttr(resourceName, "extended_s3_configuration.0.kms_key_arn", regexp.MustCompile(`^arn:[^:]+:kms:[^:]+:[^:]+:key/.+$`)), + resource.TestCheckResourceAttrPair(resourceName, "extended_s3_configuration.0.kms_key_arn", "aws_kms_key.test", "arn"), ), }, { @@ -862,20 +892,39 @@ func TestAccAWSKinesisFirehoseDeliveryStream_ExtendedS3Updates(t *testing.T) { }) } -func TestAccAWSKinesisFirehoseDeliveryStream_RedshiftConfigUpdates(t *testing.T) { +func TestAccAWSKinesisFirehoseDeliveryStream_ExtendedS3_KinesisStreamSource(t *testing.T) { var stream firehose.DeliveryStreamDescription + ri := acctest.RandInt() + resourceName := "aws_kinesis_firehose_delivery_stream.test" + config := fmt.Sprintf(testAccKinesisFirehoseDeliveryStreamConfig_extendedS3_KinesisStreamSource, + ri, ri, ri, ri, ri, ri, ri) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckKinesisFirehoseDeliveryStreamDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testAccCheckKinesisFirehoseDeliveryStreamExists(resourceName, &stream), + testAccCheckAWSKinesisFirehoseDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} +func TestAccAWSKinesisFirehoseDeliveryStream_RedshiftConfigUpdates(t *testing.T) { + var stream firehose.DeliveryStreamDescription + rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_kinesis_firehose_delivery_stream.test" - ri := acctest.RandInt() - rString := acctest.RandString(8) - funcName := fmt.Sprintf("aws_kinesis_firehose_delivery_stream_test_%s", rString) - policyName := fmt.Sprintf("tf_acc_policy_%s", rString) - roleName := fmt.Sprintf("tf_acc_role_%s", rString) - preConfig := fmt.Sprintf(testAccKinesisFirehoseDeliveryStreamConfig_RedshiftBasic, - ri, ri, ri, ri, ri) - postConfig := testAccFirehoseAWSLambdaConfigBasic(funcName, policyName, roleName) + - fmt.Sprintf(testAccKinesisFirehoseDeliveryStreamConfig_RedshiftUpdates, - ri, ri, ri, ri, ri) updatedRedshiftConfig := &firehose.RedshiftDestinationDescription{ CopyCommand: &firehose.CopyCommand{ @@ -904,7 +953,7 @@ func TestAccAWSKinesisFirehoseDeliveryStream_RedshiftConfigUpdates(t *testing.T) CheckDestroy: testAccCheckKinesisFirehoseDeliveryStreamDestroy, Steps: []resource.TestStep{ { - Config: preConfig, + Config: testAccKinesisFirehoseDeliveryStreamRedshiftConfig(rName, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisFirehoseDeliveryStreamExists(resourceName, &stream), testAccCheckAWSKinesisFirehoseDeliveryStreamAttributes(&stream, nil, nil, nil, nil, nil), @@ -917,7 +966,7 @@ func TestAccAWSKinesisFirehoseDeliveryStream_RedshiftConfigUpdates(t *testing.T) ImportStateVerifyIgnore: []string{"redshift_configuration.0.password"}, }, { - Config: postConfig, + Config: testAccKinesisFirehoseDeliveryStreamRedshiftConfigUpdates(rName, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisFirehoseDeliveryStreamExists(resourceName, &stream), testAccCheckAWSKinesisFirehoseDeliveryStreamAttributes(&stream, nil, nil, updatedRedshiftConfig, nil, nil), @@ -1110,7 +1159,7 @@ func testAccCheckKinesisFirehoseDeliveryStreamExists(n string, stream *firehose. func testAccCheckAWSKinesisFirehoseDeliveryStreamAttributes(stream *firehose.DeliveryStreamDescription, s3config interface{}, extendedS3config interface{}, redshiftConfig interface{}, elasticsearchConfig interface{}, splunkConfig interface{}) resource.TestCheckFunc { return func(s *terraform.State) error { - if !strings.HasPrefix(*stream.DeliveryStreamName, "terraform-kinesis-firehose") { + if !strings.HasPrefix(*stream.DeliveryStreamName, "terraform-kinesis-firehose") && !strings.HasPrefix(*stream.DeliveryStreamName, "tf-acc-test") { return fmt.Errorf("Bad Stream name: %s", *stream.DeliveryStreamName) } for _, rs := range s.RootModule().Resources { @@ -1721,6 +1770,21 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { } ` +var testAccKinesisFirehoseDeliveryStreamConfig_extendedS3_KinesisStreamSource = testAccKinesisFirehoseDeliveryStreamBaseConfig + testAccFirehoseKinesisStreamSource + ` +resource "aws_kinesis_firehose_delivery_stream" "test" { + depends_on = ["aws_iam_role_policy.firehose", "aws_iam_role_policy.kinesis_source"] + name = "terraform-kinesis-firehose-basictest-%d" + kinesis_source_configuration { + kinesis_stream_arn = "${aws_kinesis_stream.source.arn}" + role_arn = "${aws_iam_role.kinesis_source.arn}" + } + destination = "extended_s3" + extended_s3_configuration { + role_arn = "${aws_iam_role.firehose.arn}" + bucket_arn = "${aws_s3_bucket.bucket.arn}" + } +}` + func testAccKinesisFirehoseDeliveryStreamConfig_ExtendedS3_DataFormatConversionConfiguration_Enabled(rName string, rInt int, enabled bool) string { return fmt.Sprintf(testAccKinesisFirehoseDeliveryStreamBaseConfig, rInt, rInt, rInt) + fmt.Sprintf(` resource "aws_glue_catalog_database" "test" { @@ -2119,72 +2183,131 @@ resource "aws_kinesis_firehose_delivery_stream" "test" { } ` -var testAccKinesisFirehoseDeliveryStreamBaseRedshiftConfig = testAccKinesisFirehoseDeliveryStreamBaseConfig + ` -resource "aws_redshift_cluster" "test_cluster" { - cluster_identifier = "tf-redshift-cluster-%d" - database_name = "test" - master_username = "testuser" - master_password = "T3stPass" - node_type = "dc1.large" - cluster_type = "single-node" - skip_final_snapshot = true -}` +func testAccKinesisFirehoseDeliveryStreamRedshiftConfigBase(rName string, rInt int) string { + return composeConfig( + fmt.Sprintf(testAccKinesisFirehoseDeliveryStreamBaseConfig, rInt, rInt, rInt), + fmt.Sprintf(` +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_subnet" "test" { + cidr_block = "10.1.1.0/24" + vpc_id = "${aws_vpc.test.id}" + availability_zone = "${data.aws_availability_zones.available.names[0]}" + + tags = { + Name = %[1]q + } +} + +resource "aws_redshift_subnet_group" "test" { + name = %[1]q + description = "test" + subnet_ids = ["${aws_subnet.test.id}"] + } + +resource "aws_redshift_cluster" "test" { + cluster_identifier = %[1]q + availability_zone = "${data.aws_availability_zones.available.names[0]}" + database_name = "test" + master_username = "testuser" + master_password = "T3stPass" + node_type = "dc1.large" + cluster_type = "single-node" + skip_final_snapshot = true + cluster_subnet_group_name = "${aws_redshift_subnet_group.test.id}" + publicly_accessible = false +} +`, rName)) +} -var testAccKinesisFirehoseDeliveryStreamConfig_RedshiftBasic = testAccKinesisFirehoseDeliveryStreamBaseRedshiftConfig + ` +func testAccKinesisFirehoseDeliveryStreamRedshiftConfig(rName string, rInt int) string { + return composeConfig( + testAccKinesisFirehoseDeliveryStreamRedshiftConfigBase(rName, rInt), + fmt.Sprintf(` resource "aws_kinesis_firehose_delivery_stream" "test" { - depends_on = ["aws_iam_role_policy.firehose", "aws_redshift_cluster.test_cluster"] - name = "terraform-kinesis-firehose-basicredshifttest-%d" + name = %[1]q destination = "redshift" + s3_configuration { - role_arn = "${aws_iam_role.firehose.arn}" + role_arn = "${aws_iam_role.firehose.arn}" bucket_arn = "${aws_s3_bucket.bucket.arn}" } + redshift_configuration { - role_arn = "${aws_iam_role.firehose.arn}" - cluster_jdbcurl = "jdbc:redshift://${aws_redshift_cluster.test_cluster.endpoint}/${aws_redshift_cluster.test_cluster.database_name}" - username = "testuser" - password = "T3stPass" + role_arn = "${aws_iam_role.firehose.arn}" + cluster_jdbcurl = "jdbc:redshift://${aws_redshift_cluster.test.endpoint}/${aws_redshift_cluster.test.database_name}" + username = "testuser" + password = "T3stPass" data_table_name = "test-table" } -}` +} +`, rName)) +} -var testAccKinesisFirehoseDeliveryStreamConfig_RedshiftUpdates = testAccKinesisFirehoseDeliveryStreamBaseRedshiftConfig + ` +func testAccKinesisFirehoseDeliveryStreamRedshiftConfigUpdates(rName string, rInt int) string { + return composeConfig( + testAccFirehoseAWSLambdaConfigBasic(rName, rName, rName), + testAccKinesisFirehoseDeliveryStreamRedshiftConfigBase(rName, rInt), + fmt.Sprintf(` resource "aws_kinesis_firehose_delivery_stream" "test" { - depends_on = ["aws_iam_role_policy.firehose", "aws_redshift_cluster.test_cluster"] - name = "terraform-kinesis-firehose-basicredshifttest-%d" + name = %[1]q destination = "redshift" + s3_configuration { - role_arn = "${aws_iam_role.firehose.arn}" - bucket_arn = "${aws_s3_bucket.bucket.arn}" - buffer_size = 10 - buffer_interval = 400 + role_arn = "${aws_iam_role.firehose.arn}" + bucket_arn = "${aws_s3_bucket.bucket.arn}" + buffer_size = 10 + buffer_interval = 400 compression_format = "GZIP" } + redshift_configuration { - role_arn = "${aws_iam_role.firehose.arn}" - cluster_jdbcurl = "jdbc:redshift://${aws_redshift_cluster.test_cluster.endpoint}/${aws_redshift_cluster.test_cluster.database_name}" - username = "testuser" - password = "T3stPass" - s3_backup_mode = "Enabled" + role_arn = "${aws_iam_role.firehose.arn}" + cluster_jdbcurl = "jdbc:redshift://${aws_redshift_cluster.test.endpoint}/${aws_redshift_cluster.test.database_name}" + username = "testuser" + password = "T3stPass" + s3_backup_mode = "Enabled" + s3_backup_configuration { - role_arn = "${aws_iam_role.firehose.arn}" + role_arn = "${aws_iam_role.firehose.arn}" bucket_arn = "${aws_s3_bucket.bucket.arn}" } - data_table_name = "test-table" - copy_options = "GZIP" + + data_table_name = "test-table" + copy_options = "GZIP" data_table_columns = "test-col" + processing_configuration { enabled = false + processors { type = "Lambda" + parameters { - parameter_name = "LambdaArn" + parameter_name = "LambdaArn" parameter_value = "${aws_lambda_function.lambda_function_test.arn}:$LATEST" } } } } -}` +} +`, rName)) +} var testAccKinesisFirehoseDeliveryStreamConfig_SplunkBasic = testAccKinesisFirehoseDeliveryStreamBaseConfig + ` resource "aws_kinesis_firehose_delivery_stream" "test" { diff --git a/aws/resource_aws_kinesis_stream.go b/aws/resource_aws_kinesis_stream.go index ba5c287cdfb..560ada5a10a 100644 --- a/aws/resource_aws_kinesis_stream.go +++ b/aws/resource_aws_kinesis_stream.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/kinesis" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_kinesis_stream_migrate.go b/aws/resource_aws_kinesis_stream_migrate.go index 842d9b26e79..2c2ac0f2e74 100644 --- a/aws/resource_aws_kinesis_stream_migrate.go +++ b/aws/resource_aws_kinesis_stream_migrate.go @@ -1,7 +1,9 @@ package aws import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "context" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsKinesisStreamResourceV0() *schema.Resource { @@ -52,7 +54,7 @@ func resourceAwsKinesisStreamResourceV0() *schema.Resource { } } -func resourceAwsKinesisStreamStateUpgradeV0(rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) { +func resourceAwsKinesisStreamStateUpgradeV0(_ context.Context, rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) { rawState["enforce_consumer_deletion"] = false return rawState, nil diff --git a/aws/resource_aws_kinesis_stream_migrate_test.go b/aws/resource_aws_kinesis_stream_migrate_test.go index 45a620ef317..3e783b0673f 100644 --- a/aws/resource_aws_kinesis_stream_migrate_test.go +++ b/aws/resource_aws_kinesis_stream_migrate_test.go @@ -1,6 +1,7 @@ package aws import ( + "context" "reflect" "testing" ) @@ -35,7 +36,7 @@ func testResourceAwsKinesisStreamStateDataV1() map[string]interface{} { func TestResourceAwsKinesisStreamStateUpgradeV0(t *testing.T) { expected := testResourceAwsKinesisStreamStateDataV1() - actual, err := resourceAwsKinesisStreamStateUpgradeV0(testResourceAwsKinesisStreamStateDataV0(), nil) + actual, err := resourceAwsKinesisStreamStateUpgradeV0(context.Background(), testResourceAwsKinesisStreamStateDataV0(), nil) if err != nil { t.Fatalf("error migrating state: %s", err) } diff --git a/aws/resource_aws_kinesis_stream_test.go b/aws/resource_aws_kinesis_stream_test.go index c8a192c059f..ad75c658eec 100644 --- a/aws/resource_aws_kinesis_stream_test.go +++ b/aws/resource_aws_kinesis_stream_test.go @@ -11,9 +11,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kinesis" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_kinesis_video_stream.go b/aws/resource_aws_kinesis_video_stream.go index ebf9642a783..94407af3c21 100644 --- a/aws/resource_aws_kinesis_video_stream.go +++ b/aws/resource_aws_kinesis_video_stream.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kinesisvideo" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_kinesis_video_stream_test.go b/aws/resource_aws_kinesis_video_stream_test.go index e434366be44..3c3f3273271 100644 --- a/aws/resource_aws_kinesis_video_stream_test.go +++ b/aws/resource_aws_kinesis_video_stream_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kinesisvideo" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSKinesisVideoStream_basic(t *testing.T) { @@ -156,7 +156,7 @@ func TestAccAWSKinesisVideoStream_disappears(t *testing.T) { Config: testAccKinesisVideoStreamConfig(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckKinesisVideoStreamExists(resourceName, &stream), - testAccCheckKinesisVideoStreamDisappears(resourceName, &stream), + testAccCheckKinesisVideoStreamDisappears(resourceName), ), ExpectNonEmptyPlan: true, }, @@ -164,7 +164,7 @@ func TestAccAWSKinesisVideoStream_disappears(t *testing.T) { }) } -func testAccCheckKinesisVideoStreamDisappears(resourceName string, stream *kinesisvideo.StreamInfo) resource.TestCheckFunc { +func testAccCheckKinesisVideoStreamDisappears(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).kinesisvideoconn diff --git a/aws/resource_aws_kms_alias.go b/aws/resource_aws_kms_alias.go index 5371dbfbed5..1ea7d5699e7 100644 --- a/aws/resource_aws_kms_alias.go +++ b/aws/resource_aws_kms_alias.go @@ -6,8 +6,8 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" diff --git a/aws/resource_aws_kms_alias_test.go b/aws/resource_aws_kms_alias_test.go index 68b17dd4354..3c35502ca15 100644 --- a/aws/resource_aws_kms_alias_test.go +++ b/aws/resource_aws_kms_alias_test.go @@ -5,9 +5,9 @@ import ( "testing" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSKmsAlias_basic(t *testing.T) { diff --git a/aws/resource_aws_kms_ciphertext.go b/aws/resource_aws_kms_ciphertext.go index 9bda95a7cee..be54bf8ff7e 100644 --- a/aws/resource_aws_kms_ciphertext.go +++ b/aws/resource_aws_kms_ciphertext.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsKmsCiphertext() *schema.Resource { diff --git a/aws/resource_aws_kms_ciphertext_test.go b/aws/resource_aws_kms_ciphertext_test.go index ab9e243f47e..f28c10821b5 100644 --- a/aws/resource_aws_kms_ciphertext_test.go +++ b/aws/resource_aws_kms_ciphertext_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccResourceAwsKmsCiphertext_basic(t *testing.T) { diff --git a/aws/resource_aws_kms_external_key.go b/aws/resource_aws_kms_external_key.go index fd571b491a4..a32fb33ddbf 100644 --- a/aws/resource_aws_kms_external_key.go +++ b/aws/resource_aws_kms_external_key.go @@ -12,10 +12,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" iamwaiter "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/iam/waiter" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/kms/waiter" diff --git a/aws/resource_aws_kms_external_key_test.go b/aws/resource_aws_kms_external_key_test.go index 10c309cbad2..35248a181a1 100644 --- a/aws/resource_aws_kms_external_key_test.go +++ b/aws/resource_aws_kms_external_key_test.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" awspolicy "github.com/jen20/awspolicyequivalence" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/kms/waiter" ) @@ -511,9 +511,9 @@ func testAccCheckAWSKmsExternalKeyRecreated(i, j *kms.KeyMetadata) resource.Test } func testAccAWSKmsExternalKeyConfig() string { - return fmt.Sprintf(` + return ` resource "aws_kms_external_key" "test" {} -`) +` } func testAccAWSKmsExternalKeyConfigDeletionWindowInDays(deletionWindowInDays int) string { diff --git a/aws/resource_aws_kms_grant.go b/aws/resource_aws_kms_grant.go index b1cda29b6d4..dca81af1b54 100644 --- a/aws/resource_aws_kms_grant.go +++ b/aws/resource_aws_kms_grant.go @@ -10,10 +10,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsKmsGrant() *schema.Resource { @@ -356,7 +356,10 @@ func waitForKmsGrantToBeRevoked(conn *kms.KMS, keyId string, grantId string) err fmt.Errorf("Grant still exists while expected to be revoked, retyring revocation check: %s", *grant.GrantId)) } - return resource.NonRetryableError(err) + if err != nil { + return resource.NonRetryableError(err) + } + return nil }) if isResourceTimeoutError(err) { grant, err = findKmsGrantById(conn, keyId, grantId, nil) diff --git a/aws/resource_aws_kms_grant_test.go b/aws/resource_aws_kms_grant_test.go index efd905ad9a0..981d5bec2eb 100644 --- a/aws/resource_aws_kms_grant_test.go +++ b/aws/resource_aws_kms_grant_test.go @@ -6,20 +6,20 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) -func TestAccAWSKmsGrant_Basic(t *testing.T) { +func TestAccAWSKmsGrant_basic(t *testing.T) { resourceName := "aws_kms_grant.test" rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSKmsGrantDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSKmsGrantDestroy, Steps: []resource.TestStep{ { Config: testAccAWSKmsGrant_Basic(rName, "\"Encrypt\", \"Decrypt\""), @@ -27,8 +27,8 @@ func TestAccAWSKmsGrant_Basic(t *testing.T) { testAccCheckAWSKmsGrantExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "operations.#", "2"), - resource.TestCheckResourceAttr(resourceName, "operations.2238845196", "Encrypt"), - resource.TestCheckResourceAttr(resourceName, "operations.1237510779", "Decrypt"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "operations.*", "Encrypt"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "operations.*", "Decrypt"), resource.TestCheckResourceAttrSet(resourceName, "grantee_principal"), resource.TestCheckResourceAttrSet(resourceName, "key_id"), ), @@ -48,10 +48,9 @@ func TestAccAWSKmsGrant_withConstraints(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSKmsGrantDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSKmsGrantDestroy, Steps: []resource.TestStep{ { Config: testAccAWSKmsGrant_withConstraints(rName, "encryption_context_equals", `foo = "bar" @@ -60,9 +59,11 @@ func TestAccAWSKmsGrant_withConstraints(t *testing.T) { testAccCheckAWSKmsGrantExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "constraints.#", "1"), - resource.TestCheckResourceAttr(resourceName, "constraints.449762259.encryption_context_equals.%", "2"), - resource.TestCheckResourceAttr(resourceName, "constraints.449762259.encryption_context_equals.baz", "kaz"), - resource.TestCheckResourceAttr(resourceName, "constraints.449762259.encryption_context_equals.foo", "bar"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "constraints.*", map[string]string{ + "encryption_context_equals.%": "2", + "encryption_context_equals.baz": "kaz", + "encryption_context_equals.foo": "bar", + }), ), }, { @@ -78,9 +79,11 @@ func TestAccAWSKmsGrant_withConstraints(t *testing.T) { testAccCheckAWSKmsGrantExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "constraints.#", "1"), - resource.TestCheckResourceAttr(resourceName, "constraints.2645649985.encryption_context_subset.%", "2"), - resource.TestCheckResourceAttr(resourceName, "constraints.2645649985.encryption_context_subset.baz", "kaz"), - resource.TestCheckResourceAttr(resourceName, "constraints.2645649985.encryption_context_subset.foo", "bar"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "constraints.*", map[string]string{ + "encryption_context_subset.%": "2", + "encryption_context_subset.baz": "kaz", + "encryption_context_subset.foo": "bar", + }), ), }, }, @@ -146,10 +149,9 @@ func TestAccAWSKmsGrant_ARN(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSKmsGrantDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSKmsGrantDestroy, Steps: []resource.TestStep{ { Config: testAccAWSKmsGrant_ARN(rName, "\"Encrypt\", \"Decrypt\""), @@ -157,8 +159,8 @@ func TestAccAWSKmsGrant_ARN(t *testing.T) { testAccCheckAWSKmsGrantExists(resourceName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "operations.#", "2"), - resource.TestCheckResourceAttr(resourceName, "operations.2238845196", "Encrypt"), - resource.TestCheckResourceAttr(resourceName, "operations.1237510779", "Decrypt"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "operations.*", "Encrypt"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "operations.*", "Decrypt"), resource.TestCheckResourceAttrSet(resourceName, "grantee_principal"), resource.TestCheckResourceAttrSet(resourceName, "key_id"), ), @@ -305,13 +307,13 @@ resource "aws_kms_grant" "test" { } func testAccAWSKmsGrant_bare(rName string) string { - return testAccAWSKmsGrantConfigBase(rName) + fmt.Sprintf(` + return testAccAWSKmsGrantConfigBase(rName) + ` resource "aws_kms_grant" "test" { key_id = "${aws_kms_key.test.key_id}" grantee_principal = "${aws_iam_role.test.arn}" operations = ["ReEncryptTo", "CreateGrant"] } -`) +` } func testAccAWSKmsGrant_ARN(rName string, operations string) string { diff --git a/aws/resource_aws_kms_key.go b/aws/resource_aws_kms_key.go index 38d89ba8f05..0c72ef40706 100644 --- a/aws/resource_aws_kms_key.go +++ b/aws/resource_aws_kms_key.go @@ -8,10 +8,10 @@ import ( "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/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" iamwaiter "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/iam/waiter" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/kms/waiter" @@ -124,7 +124,10 @@ func resourceAwsKmsKeyCreate(d *schema.ResourceData, meta interface{}) error { if isAWSErr(err, kms.ErrCodeMalformedPolicyDocumentException, "") { return resource.RetryableError(err) } - return resource.NonRetryableError(err) + if err != nil { + return resource.NonRetryableError(err) + } + return nil }) if isResourceTimeoutError(err) { resp, err = conn.CreateKey(req) diff --git a/aws/resource_aws_kms_key_test.go b/aws/resource_aws_kms_key_test.go index 3aab3fea5ae..ad418781cea 100644 --- a/aws/resource_aws_kms_key_test.go +++ b/aws/resource_aws_kms_key_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kms" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" awspolicy "github.com/jen20/awspolicyequivalence" ) diff --git a/aws/resource_aws_lambda_alias.go b/aws/resource_aws_lambda_alias.go index 50ec672a2c6..e05837862de 100644 --- a/aws/resource_aws_lambda_alias.go +++ b/aws/resource_aws_lambda_alias.go @@ -8,7 +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/lambda" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsLambdaAlias() *schema.Resource { @@ -207,16 +207,8 @@ func resourceAwsLambdaAliasImport(d *schema.ResourceData, meta interface{}) ([]* functionName := idParts[0] alias := idParts[1] - log.Printf("[DEBUG] Importing Lambda Alias %s for function name %s", alias, functionName) - conn := meta.(*AWSClient).lambdaconn - - getFunctionOutput, err := conn.GetFunction(&lambda.GetFunctionInput{FunctionName: &functionName}) - if err != nil { - return nil, err - } - - d.Set("function_name", getFunctionOutput.Configuration.FunctionArn) + d.Set("function_name", functionName) d.Set("name", alias) return []*schema.ResourceData{d}, nil } diff --git a/aws/resource_aws_lambda_alias_test.go b/aws/resource_aws_lambda_alias_test.go index 5b857c5b2bc..c860b98a0ce 100644 --- a/aws/resource_aws_lambda_alias_test.go +++ b/aws/resource_aws_lambda_alias_test.go @@ -2,19 +2,18 @@ package aws import ( "fmt" - "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/lambda" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLambdaAlias_basic(t *testing.T) { var conf lambda.AliasConfiguration - resourceName := "aws_lambda_alias.lambda_alias_test" + resourceName := "aws_lambda_alias.test" rString := acctest.RandString(8) roleName := fmt.Sprintf("tf_acc_role_lambda_alias_basic_%s", rString) @@ -23,6 +22,8 @@ func TestAccAWSLambdaAlias_basic(t *testing.T) { funcName := fmt.Sprintf("tf_acc_lambda_func_alias_basic_%s", rString) aliasName := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", rString) + functionArnResourcePart := fmt.Sprintf("function:%s:%s", funcName, aliasName) + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -32,16 +33,16 @@ func TestAccAWSLambdaAlias_basic(t *testing.T) { Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaAliasExists(resourceName, &conf), - testAccCheckAwsLambdaAttributes(&conf), + testAccCheckAwsLambdaAliasAttributes(&conf), testAccCheckAwsLambdaAliasRoutingConfigDoesNotExist(&conf), - testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)), - resource.TestMatchResourceAttr(resourceName, "invoke_arn", regexp.MustCompile(fmt.Sprintf("^arn:[^:]+:apigateway:[^:]+:lambda:path/2015-03-31/functions/arn:[^:]+:lambda:[^:]+:[^:]+:function:%s:%s/invocations$", funcName, aliasName))), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", functionArnResourcePart), + testAccCheckAwsLambdaAliasInvokeArn(resourceName, &conf), ), }, { ResourceName: resourceName, ImportState: true, - ImportStateId: fmt.Sprintf("%s/%s", funcName, aliasName), + ImportStateIdFunc: testAccAwsLambdaAliasImportStateIdFunc(resourceName), ImportStateVerify: true, }, { @@ -52,9 +53,40 @@ func TestAccAWSLambdaAlias_basic(t *testing.T) { }) } +func TestAccAWSLambdaAlias_FunctionName_Name(t *testing.T) { + var conf lambda.AliasConfiguration + + resourceName := "aws_lambda_alias.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsLambdaAliasDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsLambdaAliasConfigUsingFunctionName(rName, rName, rName, rName, rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsLambdaAliasExists(resourceName, &conf), + testAccCheckAwsLambdaAliasAttributes(&conf), + testAccCheckAwsLambdaAliasRoutingConfigDoesNotExist(&conf), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", rName, rName)), + testAccCheckAwsLambdaAliasInvokeArn(resourceName, &conf), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAwsLambdaAliasImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + func TestAccAWSLambdaAlias_nameupdate(t *testing.T) { var conf lambda.AliasConfiguration - resourceName := "aws_lambda_alias.lambda_alias_test" + resourceName := "aws_lambda_alias.test" rString := acctest.RandString(8) roleName := fmt.Sprintf("tf_acc_role_lambda_alias_basic_%s", rString) @@ -64,6 +96,9 @@ func TestAccAWSLambdaAlias_nameupdate(t *testing.T) { aliasName := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", rString) aliasNameUpdate := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", acctest.RandString(8)) + functionArnResourcePart := fmt.Sprintf("function:%s:%s", funcName, aliasName) + functionArnResourcePartUpdate := fmt.Sprintf("function:%s:%s", funcName, aliasNameUpdate) + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -73,16 +108,22 @@ func TestAccAWSLambdaAlias_nameupdate(t *testing.T) { Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaAliasExists(resourceName, &conf), - testAccCheckAwsLambdaAttributes(&conf), - testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)), + testAccCheckAwsLambdaAliasAttributes(&conf), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", functionArnResourcePart), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAwsLambdaAliasImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, { Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasNameUpdate), Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaAliasExists(resourceName, &conf), - testAccCheckAwsLambdaAttributes(&conf), - testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasNameUpdate)), + testAccCheckAwsLambdaAliasAttributes(&conf), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", functionArnResourcePartUpdate), ), }, }, @@ -91,7 +132,7 @@ func TestAccAWSLambdaAlias_nameupdate(t *testing.T) { func TestAccAWSLambdaAlias_routingconfig(t *testing.T) { var conf lambda.AliasConfiguration - resourceName := "aws_lambda_alias.lambda_alias_test" + resourceName := "aws_lambda_alias.test" rString := acctest.RandString(8) roleName := fmt.Sprintf("tf_acc_role_lambda_alias_basic_%s", rString) @@ -100,6 +141,8 @@ func TestAccAWSLambdaAlias_routingconfig(t *testing.T) { funcName := fmt.Sprintf("tf_acc_lambda_func_alias_basic_%s", rString) aliasName := fmt.Sprintf("tf_acc_lambda_alias_basic_%s", rString) + functionArnResourcePart := fmt.Sprintf("function:%s:%s", funcName, aliasName) + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -109,26 +152,32 @@ func TestAccAWSLambdaAlias_routingconfig(t *testing.T) { Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaAliasExists(resourceName, &conf), - testAccCheckAwsLambdaAttributes(&conf), - testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)), + testAccCheckAwsLambdaAliasAttributes(&conf), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", functionArnResourcePart), ), }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAwsLambdaAliasImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, { Config: testAccAwsLambdaAliasConfigWithRoutingConfig(roleName, policyName, attachmentName, funcName, aliasName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaAliasExists(resourceName, &conf), - testAccCheckAwsLambdaAttributes(&conf), + testAccCheckAwsLambdaAliasAttributes(&conf), testAccCheckAwsLambdaAliasRoutingConfigExists(&conf), - testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", functionArnResourcePart), ), }, { Config: testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, aliasName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaAliasExists(resourceName, &conf), - testAccCheckAwsLambdaAttributes(&conf), + testAccCheckAwsLambdaAliasAttributes(&conf), testAccCheckAwsLambdaAliasRoutingConfigDoesNotExist(&conf), - testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, aliasName)), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", functionArnResourcePart), ), }, }, @@ -185,7 +234,7 @@ func testAccCheckAwsLambdaAliasExists(n string, mapping *lambda.AliasConfigurati } } -func testAccCheckAwsLambdaAttributes(mapping *lambda.AliasConfiguration) resource.TestCheckFunc { +func testAccCheckAwsLambdaAliasAttributes(mapping *lambda.AliasConfiguration) resource.TestCheckFunc { return func(s *terraform.State) error { name := *mapping.Name arn := *mapping.AliasArn @@ -199,6 +248,13 @@ func testAccCheckAwsLambdaAttributes(mapping *lambda.AliasConfiguration) resourc } } +func testAccCheckAwsLambdaAliasInvokeArn(name string, mapping *lambda.AliasConfiguration) resource.TestCheckFunc { + return func(s *terraform.State) error { + arn := aws.StringValue(mapping.AliasArn) + return testAccCheckResourceAttrRegionalARNAccountID(name, "invoke_arn", "apigateway", "lambda", fmt.Sprintf("path/2015-03-31/functions/%s/invocations", arn))(s) + } +} + func testAccCheckAwsLambdaAliasRoutingConfigExists(mapping *lambda.AliasConfiguration) resource.TestCheckFunc { return func(s *terraform.State) error { routingConfig := mapping.RoutingConfig @@ -223,6 +279,18 @@ func testAccCheckAwsLambdaAliasRoutingConfigDoesNotExist(mapping *lambda.AliasCo return nil } } + +func testAccAwsLambdaAliasImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { + return func(s *terraform.State) (string, error) { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return "", fmt.Errorf("Not found: %s", resourceName) + } + + return fmt.Sprintf("%s/%s", rs.Primary.Attributes["function_name"], rs.Primary.Attributes["name"]), nil + } +} + func testAccAwsLambdaAliasBaseConfig(roleName, policyName, attachmentName string) string { return fmt.Sprintf(` resource "aws_iam_role" "iam_for_lambda" { @@ -278,7 +346,7 @@ func testAccAwsLambdaAliasConfig(roleName, policyName, attachmentName, funcName, return composeConfig( testAccAwsLambdaAliasBaseConfig(roleName, policyName, attachmentName), fmt.Sprintf(` -resource "aws_lambda_function" "lambda_function_test_create" { +resource "aws_lambda_function" "test" { filename = "test-fixtures/lambdatest.zip" function_name = "%s" role = "${aws_iam_role.iam_for_lambda.arn}" @@ -288,10 +356,10 @@ resource "aws_lambda_function" "lambda_function_test_create" { publish = "true" } -resource "aws_lambda_alias" "lambda_alias_test" { +resource "aws_lambda_alias" "test" { name = "%s" description = "a sample description" - function_name = "${aws_lambda_function.lambda_function_test_create.arn}" + function_name = "${aws_lambda_function.test.arn}" function_version = "1" } `, funcName, aliasName)) @@ -301,7 +369,7 @@ func testAccAwsLambdaAliasConfigUsingFunctionName(roleName, policyName, attachme return composeConfig( testAccAwsLambdaAliasBaseConfig(roleName, policyName, attachmentName), fmt.Sprintf(` -resource "aws_lambda_function" "lambda_function_test_create" { +resource "aws_lambda_function" "test" { filename = "test-fixtures/lambdatest.zip" function_name = "%s" role = "${aws_iam_role.iam_for_lambda.arn}" @@ -311,10 +379,10 @@ resource "aws_lambda_function" "lambda_function_test_create" { publish = "true" } -resource "aws_lambda_alias" "lambda_alias_test" { +resource "aws_lambda_alias" "test" { name = "%s" description = "a sample description" - function_name = "${aws_lambda_function.lambda_function_test_create.function_name}" + function_name = "${aws_lambda_function.test.function_name}" function_version = "1" } `, funcName, aliasName)) @@ -324,7 +392,7 @@ func testAccAwsLambdaAliasConfigWithRoutingConfig(roleName, policyName, attachme return composeConfig( testAccAwsLambdaAliasBaseConfig(roleName, policyName, attachmentName), fmt.Sprintf(` -resource "aws_lambda_function" "lambda_function_test_create" { +resource "aws_lambda_function" "test" { filename = "test-fixtures/lambdatest_modified.zip" function_name = "%s" role = "${aws_iam_role.iam_for_lambda.arn}" @@ -334,10 +402,10 @@ resource "aws_lambda_function" "lambda_function_test_create" { publish = "true" } -resource "aws_lambda_alias" "lambda_alias_test" { +resource "aws_lambda_alias" "test" { name = "%s" description = "a sample description" - function_name = "${aws_lambda_function.lambda_function_test_create.arn}" + function_name = "${aws_lambda_function.test.arn}" function_version = "1" routing_config { diff --git a/aws/resource_aws_lambda_event_source_mapping.go b/aws/resource_aws_lambda_event_source_mapping.go index c9cce2768ef..786b358c135 100644 --- a/aws/resource_aws_lambda_event_source_mapping.go +++ b/aws/resource_aws_lambda_event_source_mapping.go @@ -13,9 +13,9 @@ import ( "github.com/aws/aws-sdk-go/service/lambda" "github.com/aws/aws-sdk-go/service/sqs" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsLambdaEventSourceMapping() *schema.Resource { @@ -210,7 +210,7 @@ func resourceAwsLambdaEventSourceMappingCreate(d *schema.ResourceData, meta inte params.ParallelizationFactor = aws.Int64(int64(parallelizationFactor.(int))) } - if maximumRetryAttempts, ok := d.GetOk("maximum_retry_attempts"); ok { + if maximumRetryAttempts, ok := d.GetOkExists("maximum_retry_attempts"); ok { params.MaximumRetryAttempts = aws.Int64(int64(maximumRetryAttempts.(int))) } @@ -372,7 +372,7 @@ func resourceAwsLambdaEventSourceMappingUpdate(d *schema.ResourceData, meta inte params.SetParallelizationFactor(int64(parallelizationFactor.(int))) } - if maximumRetryAttempts, ok := d.GetOk("maximum_retry_attempts"); ok { + if maximumRetryAttempts, ok := d.GetOkExists("maximum_retry_attempts"); ok { params.SetMaximumRetryAttempts(int64(maximumRetryAttempts.(int))) } diff --git a/aws/resource_aws_lambda_event_source_mapping_test.go b/aws/resource_aws_lambda_event_source_mapping_test.go index 3d5fa27e330..19612913e60 100644 --- a/aws/resource_aws_lambda_event_source_mapping_test.go +++ b/aws/resource_aws_lambda_event_source_mapping_test.go @@ -2,7 +2,6 @@ package aws import ( "fmt" - "regexp" "strconv" "testing" "time" @@ -10,15 +9,18 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/lambda" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLambdaEventSourceMapping_kinesis_basic(t *testing.T) { var conf lambda.EventSourceMappingConfiguration resourceName := "aws_lambda_event_source_mapping.lambda_event_source_mapping_test" + functionResourceName := "aws_lambda_function.lambda_function_test_create" + functionResourceNameUpdated := "aws_lambda_function.lambda_function_test_update" + eventSourceResourceName := "aws_kinesis_stream.kinesis_stream_test" rString := acctest.RandString(8) roleName := fmt.Sprintf("tf_acc_role_lambda_esm_basic_%s", rString) @@ -27,7 +29,6 @@ func TestAccAWSLambdaEventSourceMapping_kinesis_basic(t *testing.T) { streamName := fmt.Sprintf("tf_acc_stream_lambda_esm_basic_%s", rString) funcName := fmt.Sprintf("tf_acc_lambda_esm_basic_%s", rString) uFuncName := fmt.Sprintf("tf_acc_lambda_esm_basic_updated_%s", rString) - uFuncArnRe := regexp.MustCompile(":" + uFuncName + "$") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -40,6 +41,9 @@ func TestAccAWSLambdaEventSourceMapping_kinesis_basic(t *testing.T) { testAccCheckAwsLambdaEventSourceMappingExists(resourceName, &conf), testAccCheckAWSLambdaEventSourceMappingAttributes(&conf), testAccCheckResourceAttrRfc3339(resourceName, "last_modified"), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "function_arn", functionResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "event_source_arn", eventSourceResourceName, "arn"), ), }, { @@ -54,7 +58,9 @@ func TestAccAWSLambdaEventSourceMapping_kinesis_basic(t *testing.T) { testAccCheckAwsLambdaEventSourceMappingExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "batch_size", strconv.Itoa(200)), resource.TestCheckResourceAttr(resourceName, "enabled", strconv.FormatBool(false)), - resource.TestMatchResourceAttr(resourceName, "function_arn", uFuncArnRe), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceNameUpdated, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "function_arn", functionResourceNameUpdated, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "event_source_arn", eventSourceResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "starting_position", "TRIM_HORIZON"), ), }, @@ -114,6 +120,9 @@ func TestAccAWSLambdaEventSourceMapping_sqs_basic(t *testing.T) { var conf lambda.EventSourceMappingConfiguration resourceName := "aws_lambda_event_source_mapping.lambda_event_source_mapping_test" + functionResourceName := "aws_lambda_function.lambda_function_test_create" + functionResourceNameUpdated := "aws_lambda_function.lambda_function_test_update" + eventSourceResourceName := "aws_sqs_queue.sqs_queue_test" rString := acctest.RandString(8) roleName := fmt.Sprintf("tf_acc_role_lambda_sqs_basic_%s", rString) @@ -122,7 +131,6 @@ func TestAccAWSLambdaEventSourceMapping_sqs_basic(t *testing.T) { streamName := fmt.Sprintf("tf_acc_stream_lambda_sqs_basic_%s", rString) funcName := fmt.Sprintf("tf_acc_lambda_sqs_basic_%s", rString) uFuncName := fmt.Sprintf("tf_acc_lambda_sqs_basic_updated_%s", rString) - uFuncArnRe := regexp.MustCompile(":" + uFuncName + "$") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -134,9 +142,11 @@ func TestAccAWSLambdaEventSourceMapping_sqs_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaEventSourceMappingExists(resourceName, &conf), testAccCheckAWSLambdaEventSourceMappingAttributes(&conf), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "function_arn", functionResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "event_source_arn", eventSourceResourceName, "arn"), testAccCheckResourceAttrRfc3339(resourceName, "last_modified"), - resource.TestCheckNoResourceAttr(resourceName, - "starting_position"), + resource.TestCheckNoResourceAttr(resourceName, "starting_position"), ), }, { @@ -151,7 +161,9 @@ func TestAccAWSLambdaEventSourceMapping_sqs_basic(t *testing.T) { testAccCheckAwsLambdaEventSourceMappingExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "batch_size", strconv.Itoa(5)), resource.TestCheckResourceAttr(resourceName, "enabled", strconv.FormatBool(false)), - resource.TestMatchResourceAttr(resourceName, "function_arn", uFuncArnRe), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceNameUpdated, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "function_arn", functionResourceNameUpdated, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "event_source_arn", eventSourceResourceName, "arn"), resource.TestCheckNoResourceAttr(resourceName, "starting_position"), ), }, @@ -163,6 +175,7 @@ func TestAccAWSLambdaEventSourceMapping_sqs_withFunctionName(t *testing.T) { var conf lambda.EventSourceMappingConfiguration resourceName := "aws_lambda_event_source_mapping.lambda_event_source_mapping_test" + functionResourceName := "aws_lambda_function.lambda_function_test_create" rString := acctest.RandString(8) roleName := fmt.Sprintf("tf_acc_role_lambda_sqs_basic_%s", rString) @@ -170,7 +183,6 @@ func TestAccAWSLambdaEventSourceMapping_sqs_withFunctionName(t *testing.T) { attName := fmt.Sprintf("tf_acc_att_lambda_sqs_basic_%s", rString) streamName := fmt.Sprintf("tf_acc_stream_lambda_sqs_basic_%s", rString) funcName := fmt.Sprintf("tf_acc_lambda_sqs_basic_%s", rString) - funcArnRe := regexp.MustCompile(":" + funcName + "$") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -182,8 +194,8 @@ func TestAccAWSLambdaEventSourceMapping_sqs_withFunctionName(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaEventSourceMappingExists(resourceName, &conf), testAccCheckAWSLambdaEventSourceMappingAttributes(&conf), - resource.TestMatchResourceAttr(resourceName, "function_arn", funcArnRe), - resource.TestMatchResourceAttr(resourceName, "function_name", funcArnRe), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "function_arn", functionResourceName, "arn"), resource.TestCheckNoResourceAttr(resourceName, "starting_position"), ), }, @@ -430,6 +442,52 @@ func TestAccAWSLambdaEventSourceMapping_MaximumRetryAttempts(t *testing.T) { }) } +func TestAccAWSLambdaEventSourceMapping_MaximumRetryAttemptsZero(t *testing.T) { + var conf lambda.EventSourceMappingConfiguration + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_lambda_event_source_mapping.test" + maximumRetryAttempts := int64(0) + maximumRetryAttemptsUpdate := int64(100) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckLambdaEventSourceMappingDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLambdaEventSourceMappingConfigKinesisMaximumRetryAttempts(rName, maximumRetryAttempts), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsLambdaEventSourceMappingExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "maximum_retry_attempts", strconv.Itoa(int(maximumRetryAttempts))), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "starting_position", + "starting_position_timestamp", + }, + }, + { + Config: testAccAWSLambdaEventSourceMappingConfigKinesisMaximumRetryAttempts(rName, maximumRetryAttemptsUpdate), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsLambdaEventSourceMappingExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "maximum_retry_attempts", strconv.Itoa(int(maximumRetryAttemptsUpdate))), + ), + }, + { + Config: testAccAWSLambdaEventSourceMappingConfigKinesisMaximumRetryAttempts(rName, maximumRetryAttempts), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsLambdaEventSourceMappingExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "maximum_retry_attempts", strconv.Itoa(int(maximumRetryAttempts))), + ), + }, + }, + }) +} + func TestAccAWSLambdaEventSourceMapping_MaximumRecordAgeInSeconds(t *testing.T) { var conf lambda.EventSourceMappingConfiguration rName := acctest.RandomWithPrefix("tf-acc-test") @@ -512,10 +570,12 @@ func TestAccAWSLambdaEventSourceMapping_KinesisDestinationConfig(t *testing.T) { var conf lambda.EventSourceMappingConfiguration rName := acctest.RandomWithPrefix("tf-acc-test") rString := acctest.RandString(8) - resourceName := "aws_lambda_event_source_mapping.test" streamName := fmt.Sprintf("tf_acc_stream_dest_config_%s", rString) streamNameUpdated := fmt.Sprintf("tf_acc_stream_dest_config_updated_%s", rString) + resourceName := "aws_lambda_event_source_mapping.test" + sqsResourceName := "aws_sqs_queue.sqs_queue_test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -527,7 +587,7 @@ func TestAccAWSLambdaEventSourceMapping_KinesisDestinationConfig(t *testing.T) { testAccCheckAwsLambdaEventSourceMappingExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "destination_config.#", "1"), resource.TestCheckResourceAttr(resourceName, "destination_config.0.on_failure.#", "1"), - resource.TestCheckResourceAttrPair(resourceName, "destination_config.0.on_failure.0.destination_arn", "aws_sqs_queue.sqs_queue_test", "arn"), + resource.TestCheckResourceAttrPair(resourceName, "destination_config.0.on_failure.0.destination_arn", sqsResourceName, "arn"), ), }, { @@ -545,7 +605,7 @@ func TestAccAWSLambdaEventSourceMapping_KinesisDestinationConfig(t *testing.T) { testAccCheckAwsLambdaEventSourceMappingExists(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "destination_config.#", "1"), resource.TestCheckResourceAttr(resourceName, "destination_config.0.on_failure.#", "1"), - resource.TestCheckResourceAttrPair(resourceName, "destination_config.0.on_failure.0.destination_arn", "aws_sqs_queue.sqs_queue_test", "arn"), + resource.TestCheckResourceAttrPair(resourceName, "destination_config.0.on_failure.0.destination_arn", sqsResourceName, "arn"), ), }, }, diff --git a/aws/resource_aws_lambda_function.go b/aws/resource_aws_lambda_function.go index cca57540a8b..3596322a86b 100644 --- a/aws/resource_aws_lambda_function.go +++ b/aws/resource_aws_lambda_function.go @@ -1,9 +1,11 @@ package aws import ( + "context" "fmt" "io/ioutil" "log" + "regexp" "time" "github.com/aws/aws-sdk-go/aws" @@ -14,10 +16,11 @@ import ( "errors" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" + iamwaiter "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/iam/waiter" ) const awsMutexLambdaKey = `aws_lambda_function` @@ -103,6 +106,29 @@ func resourceAwsLambdaFunction() *schema.Resource { }, }, }, + "file_system_config": { + Type: schema.TypeList, + Optional: true, + MinItems: 0, + // Lambda file system supports 1 EFS file system per lambda function. This might increase in future. + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + // EFS access point arn + "arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateArn, + }, + // Local mount path inside a lambda function. Must start with "/mnt/". + "local_mount_path": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringMatch(regexp.MustCompile(`^/mnt/[a-zA-Z0-9-_.]+$`), "must start with '/mnt/'"), + }, + }, + }, + }, "function_name": { Type: schema.TypeString, Required: true, @@ -192,7 +218,7 @@ func resourceAwsLambdaFunction() *schema.Resource { return false } - if d.HasChange("vpc_config.0.security_group_ids") || d.HasChange("vpc_config.0.subnet_ids") { + if d.HasChanges("vpc_config.0.security_group_ids", "vpc_config.0.subnet_ids") { return false } @@ -268,7 +294,7 @@ func resourceAwsLambdaFunction() *schema.Resource { } } -func updateComputedAttributesOnPublish(d *schema.ResourceDiff, meta interface{}) error { +func updateComputedAttributesOnPublish(_ context.Context, d *schema.ResourceDiff, meta interface{}) error { if needsFunctionCodeUpdate(d) { d.SetNewComputed("last_modified") publish := d.Get("publish").(bool) @@ -357,6 +383,10 @@ func resourceAwsLambdaFunctionCreate(d *schema.ResourceData, meta interface{}) e } } + if v, ok := d.GetOk("file_system_config"); ok && len(v.([]interface{})) > 0 { + params.FileSystemConfigs = expandLambdaFileSystemConfigs(v.([]interface{})) + } + if v, ok := d.GetOk("vpc_config"); ok && len(v.([]interface{})) > 0 { config := v.([]interface{})[0].(map[string]interface{}) @@ -398,8 +428,8 @@ func resourceAwsLambdaFunctionCreate(d *schema.ResourceData, meta interface{}) e params.Tags = keyvaluetags.New(v.(map[string]interface{})).IgnoreAws().LambdaTags() } - // IAM changes can take 1 minute to propagate in AWS - err := resource.Retry(1*time.Minute, func() *resource.RetryError { + // IAM changes can take some time to propagate in AWS + err := resource.Retry(iamwaiter.PropagationTimeout, func() *resource.RetryError { _, err := conn.CreateFunction(params) if err != nil { log.Printf("[DEBUG] Error creating Lambda Function: %s", err) @@ -549,6 +579,12 @@ func resourceAwsLambdaFunctionRead(d *schema.ResourceData, meta interface{}) err d.Set("source_code_hash", function.CodeSha256) d.Set("source_code_size", function.CodeSize) + fileSystemConfigs := flattenLambdaFileSystemConfigs(function.FileSystemConfigs) + log.Printf("[INFO] Setting Lambda %s file system configs %#v from API", d.Id(), fileSystemConfigs) + if err := d.Set("file_system_config", fileSystemConfigs); err != nil { + return fmt.Errorf("Error setting file system config for Lambda Function (%s): %s", d.Id(), err) + } + layers := flattenLambdaLayers(function.Layers) log.Printf("[INFO] Setting Lambda %s Layers %#v from API", d.Id(), layers) if err := d.Set("layers", layers); err != nil { @@ -695,6 +731,13 @@ func resourceAwsLambdaFunctionUpdate(d *schema.ResourceData, meta interface{}) e configReq.Handler = aws.String(d.Get("handler").(string)) configUpdate = true } + if d.HasChange("file_system_config") { + configReq.FileSystemConfigs = make([]*lambda.FileSystemConfig, 0) + if v, ok := d.GetOk("file_system_config"); ok && len(v.([]interface{})) > 0 { + configReq.FileSystemConfigs = expandLambdaFileSystemConfigs(v.([]interface{})) + } + configUpdate = true + } if d.HasChange("memory_size") { configReq.MemorySize = aws.Int64(int64(d.Get("memory_size").(int))) configUpdate = true @@ -1030,3 +1073,27 @@ func waitForLambdaFunctionUpdate(conn *lambda.Lambda, functionName string, timeo return err } + +func flattenLambdaFileSystemConfigs(fscList []*lambda.FileSystemConfig) []map[string]interface{} { + results := make([]map[string]interface{}, 0, len(fscList)) + for _, fsc := range fscList { + f := make(map[string]interface{}) + f["arn"] = *fsc.Arn + f["local_mount_path"] = *fsc.LocalMountPath + + results = append(results, f) + } + return results +} + +func expandLambdaFileSystemConfigs(fscMaps []interface{}) []*lambda.FileSystemConfig { + fileSystemConfigs := make([]*lambda.FileSystemConfig, 0, len(fscMaps)) + for _, fsc := range fscMaps { + fscMap := fsc.(map[string]interface{}) + fileSystemConfigs = append(fileSystemConfigs, &lambda.FileSystemConfig{ + Arn: aws.String(fscMap["arn"].(string)), + LocalMountPath: aws.String(fscMap["local_mount_path"].(string)), + }) + } + return fileSystemConfigs +} diff --git a/aws/resource_aws_lambda_function_event_invoke_config.go b/aws/resource_aws_lambda_function_event_invoke_config.go index c8bf754f115..f3b33f5269c 100644 --- a/aws/resource_aws_lambda_function_event_invoke_config.go +++ b/aws/resource_aws_lambda_function_event_invoke_config.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/lambda" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsLambdaFunctionEventInvokeConfig() *schema.Resource { diff --git a/aws/resource_aws_lambda_function_event_invoke_config_test.go b/aws/resource_aws_lambda_function_event_invoke_config_test.go index 58c7130ae70..00bdfb13ad8 100644 --- a/aws/resource_aws_lambda_function_event_invoke_config_test.go +++ b/aws/resource_aws_lambda_function_event_invoke_config_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/lambda" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLambdaFunctionEventInvokeConfig_basic(t *testing.T) { @@ -666,19 +666,19 @@ resource "aws_lambda_function_event_invoke_config" "test" { } func testAccAWSLambdaFunctionEventInvokeConfigFunctionName(rName string) string { - return testAccAWSLambdaFunctionEventInvokeConfigBase(rName) + fmt.Sprintf(` + return testAccAWSLambdaFunctionEventInvokeConfigBase(rName) + ` resource "aws_lambda_function_event_invoke_config" "test" { function_name = aws_lambda_function.test.function_name } -`) +` } func testAccAWSLambdaFunctionEventInvokeConfigFunctionNameArn(rName string) string { - return testAccAWSLambdaFunctionEventInvokeConfigBase(rName) + fmt.Sprintf(` + return testAccAWSLambdaFunctionEventInvokeConfigBase(rName) + ` resource "aws_lambda_function_event_invoke_config" "test" { function_name = aws_lambda_function.test.arn } -`) +` } func testAccAWSLambdaFunctionEventInvokeConfigMaximumEventAgeInSeconds(rName string, maximumEventAgeInSeconds int) string { @@ -700,7 +700,7 @@ resource "aws_lambda_function_event_invoke_config" "test" { } func testAccAWSLambdaFunctionEventInvokeConfigQualifierAliasName(rName string) string { - return testAccAWSLambdaFunctionEventInvokeConfigBase(rName) + fmt.Sprintf(` + return testAccAWSLambdaFunctionEventInvokeConfigBase(rName) + ` resource "aws_lambda_alias" "test" { function_name = aws_lambda_function.test.function_name function_version = aws_lambda_function.test.version @@ -711,23 +711,23 @@ resource "aws_lambda_function_event_invoke_config" "test" { function_name = aws_lambda_alias.test.function_name qualifier = aws_lambda_alias.test.name } -`) +` } func testAccAWSLambdaFunctionEventInvokeConfigQualifierFunctionVersion(rName string) string { - return testAccAWSLambdaFunctionEventInvokeConfigBase(rName) + fmt.Sprintf(` + return testAccAWSLambdaFunctionEventInvokeConfigBase(rName) + ` resource "aws_lambda_function_event_invoke_config" "test" { function_name = aws_lambda_function.test.function_name qualifier = aws_lambda_function.test.version } -`) +` } func testAccAWSLambdaFunctionEventInvokeConfigQualifierLatest(rName string) string { - return testAccAWSLambdaFunctionEventInvokeConfigBase(rName) + fmt.Sprintf(` + return testAccAWSLambdaFunctionEventInvokeConfigBase(rName) + ` resource "aws_lambda_function_event_invoke_config" "test" { function_name = aws_lambda_function.test.function_name qualifier = "$LATEST" } -`) +` } diff --git a/aws/resource_aws_lambda_function_test.go b/aws/resource_aws_lambda_function_test.go index 7c65022548c..c76b82c5c80 100644 --- a/aws/resource_aws_lambda_function_test.go +++ b/aws/resource_aws_lambda_function_test.go @@ -14,9 +14,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/lambda" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -81,9 +81,8 @@ func TestAccAWSLambdaFunction_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), - testAccMatchResourceAttrRegionalARN(resourceName, "arn", "lambda", regexp.MustCompile(`function.+`)), - resource.TestMatchResourceAttr(resourceName, "invoke_arn", regexp.MustCompile(fmt.Sprintf("^arn:[^:]+:apigateway:[^:]+:lambda:path/2015-03-31/functions/arn:[^:]+:lambda:[^:]+:[^:]+:function:%s/invocations$", funcName))), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), + testAccCheckAwsLambdaFunctionInvokeArn(resourceName, &conf), resource.TestCheckResourceAttr(resourceName, "reserved_concurrent_executions", "-1"), ), }, @@ -140,7 +139,7 @@ func TestAccAWSLambdaFunction_concurrency(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "reserved_concurrent_executions", "111"), ), }, @@ -155,7 +154,7 @@ func TestAccAWSLambdaFunction_concurrency(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "reserved_concurrent_executions", "222"), ), }, @@ -183,7 +182,7 @@ func TestAccAWSLambdaFunction_concurrencyCycle(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "reserved_concurrent_executions", "-1"), ), }, @@ -198,7 +197,7 @@ func TestAccAWSLambdaFunction_concurrencyCycle(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "reserved_concurrent_executions", "222"), ), }, @@ -207,7 +206,7 @@ func TestAccAWSLambdaFunction_concurrencyCycle(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "reserved_concurrent_executions", "-1"), ), }, @@ -294,7 +293,7 @@ func TestAccAWSLambdaFunction_envVariables(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckNoResourceAttr(resourceName, "environment"), ), }, @@ -309,7 +308,7 @@ func TestAccAWSLambdaFunction_envVariables(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "environment.0.variables.foo", "bar"), ), }, @@ -318,7 +317,7 @@ func TestAccAWSLambdaFunction_envVariables(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "environment.0.variables.foo", "baz"), resource.TestCheckResourceAttr(resourceName, "environment.0.variables.foo1", "bar1"), ), @@ -328,7 +327,7 @@ func TestAccAWSLambdaFunction_envVariables(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckNoResourceAttr(resourceName, "environment"), ), }, @@ -357,7 +356,7 @@ func TestAccAWSLambdaFunction_encryptedEnvVariables(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "environment.0.variables.foo", "bar"), testAccMatchResourceAttrRegionalARN(resourceName, "kms_key_arn", "kms", regexp.MustCompile(`key/.+`)), ), @@ -373,7 +372,7 @@ func TestAccAWSLambdaFunction_encryptedEnvVariables(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "environment.0.variables.foo", "bar"), resource.TestCheckResourceAttr(resourceName, "kms_key_arn", ""), ), @@ -392,6 +391,8 @@ func TestAccAWSLambdaFunction_versioned(t *testing.T) { sgName := fmt.Sprintf("tf_acc_sg_lambda_func_versioned_%s", rString) resourceName := "aws_lambda_function.test" + version := "1" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -402,11 +403,11 @@ func TestAccAWSLambdaFunction_versioned(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), - resource.TestMatchResourceAttr(resourceName, "version", - regexp.MustCompile("^[0-9]+$")), - resource.TestMatchResourceAttr(resourceName, "qualified_arn", - regexp.MustCompile(":"+funcName+":[0-9]+$")), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), + resource.TestMatchResourceAttr(resourceName, "version", regexp.MustCompile("^[0-9]+$")), + resource.TestCheckResourceAttr(resourceName, "version", version), + testAccMatchResourceAttrRegionalARN(resourceName, "qualified_arn", "lambda", regexp.MustCompile(fmt.Sprintf("function:%s:[0-9]+$", funcName))), + testAccCheckResourceAttrRegionalARN(resourceName, "qualified_arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, version)), ), }, { @@ -437,6 +438,9 @@ func TestAccAWSLambdaFunction_versionedUpdate(t *testing.T) { var timeBeforeUpdate time.Time + version := "2" + versionUpdated := "3" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -456,11 +460,9 @@ func TestAccAWSLambdaFunction_versionedUpdate(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), - resource.TestMatchResourceAttr(resourceName, "version", - regexp.MustCompile("^2$")), - resource.TestMatchResourceAttr(resourceName, "qualified_arn", - regexp.MustCompile(":"+funcName+":[0-9]+$")), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), + resource.TestCheckResourceAttr(resourceName, "version", "2"), + testAccCheckResourceAttrRegionalARN(resourceName, "qualified_arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, version)), func(s *terraform.State) error { return testAccCheckAttributeIsDateAfter(s, resourceName, "last_modified", timeBeforeUpdate) }, @@ -474,11 +476,9 @@ func TestAccAWSLambdaFunction_versionedUpdate(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), - resource.TestMatchResourceAttr(resourceName, "version", - regexp.MustCompile("^3$")), - resource.TestMatchResourceAttr(resourceName, "qualified_arn", - regexp.MustCompile(":"+funcName+":[0-9]+$")), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), + resource.TestMatchResourceAttr(resourceName, "version", regexp.MustCompile("^3$")), + testAccCheckResourceAttrRegionalARN(resourceName, "qualified_arn", "lambda", fmt.Sprintf("function:%s:%s", funcName, versionUpdated)), resource.TestCheckResourceAttr(resourceName, "runtime", lambda.RuntimeNodejs10X), func(s *terraform.State) error { return testAccCheckAttributeIsDateAfter(s, resourceName, "last_modified", timeBeforeUpdate) @@ -516,7 +516,7 @@ func TestAccAWSLambdaFunction_DeadLetterConfig(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), func(s *terraform.State) error { if !strings.HasSuffix(*conf.Configuration.DeadLetterConfig.TargetArn, ":"+topicName) { return fmt.Errorf( @@ -550,7 +550,6 @@ func TestAccAWSLambdaFunction_DeadLetterConfigUpdated(t *testing.T) { rString := acctest.RandString(8) funcName := fmt.Sprintf("tf_acc_lambda_func_dlcfg_upd_%s", rString) - uFuncName := fmt.Sprintf("tf_acc_lambda_func_dlcfg_upd_%s", rString) policyName := fmt.Sprintf("tf_acc_policy_lambda_func_dlcfg_upd_%s", rString) roleName := fmt.Sprintf("tf_acc_role_lambda_func_dlcfg_upd_%s", rString) sgName := fmt.Sprintf("tf_acc_sg_lambda_func_dlcfg_upd_%s", rString) @@ -567,7 +566,7 @@ func TestAccAWSLambdaFunction_DeadLetterConfigUpdated(t *testing.T) { Config: testAccAWSLambdaConfigWithDeadLetterConfig(funcName, topic1Name, policyName, roleName, sgName), }, { - Config: testAccAWSLambdaConfigWithDeadLetterConfigUpdated(funcName, topic1Name, topic2Name, policyName, roleName, sgName, uFuncName), + Config: testAccAWSLambdaConfigWithDeadLetterConfigUpdated(funcName, topic1Name, topic2Name, policyName, roleName, sgName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), func(s *terraform.State) error { @@ -611,6 +610,61 @@ func TestAccAWSLambdaFunction_nilDeadLetterConfig(t *testing.T) { }) } +func TestAccAWSLambdaFunction_FileSystemConfig(t *testing.T) { + var conf lambda.GetFunctionOutput + resourceName := "aws_lambda_function.test" + + rString := acctest.RandString(8) + funcName := fmt.Sprintf("tf_acc_lambda_func_basic_%s", rString) + policyName := fmt.Sprintf("tf_acc_policy_lambda_func_basic_%s", rString) + roleName := fmt.Sprintf("tf_acc_role_lambda_func_basic_%s", rString) + sgName := fmt.Sprintf("tf_acc_sg_lambda_func_basic_%s", rString) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckLambdaFunctionDestroy, + Steps: []resource.TestStep{ + // Ensure a function with lambda file system configuration can be created + { + Config: testAccAWSLambdaFileSystemConfig(funcName, policyName, roleName, sgName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), + testAccCheckAwsLambdaFunctionName(&conf, funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), + testAccCheckAwsLambdaFunctionInvokeArn(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "file_system_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "file_system_config.0.local_mount_path", "/mnt/efs"), + ), + }, + // Ensure configuration can be imported + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"filename", "publish"}, + }, + // Ensure lambda file system configuration can be updated + { + Config: testAccAWSLambdaFileSystemUpdateConfig(funcName, policyName, roleName, sgName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), + resource.TestCheckResourceAttr(resourceName, "file_system_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "file_system_config.0.local_mount_path", "/mnt/lambda"), + ), + }, + // Ensure lambda file system configuration can be removed + { + Config: testAccAWSLambdaConfigBasic(funcName, policyName, roleName, sgName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), + resource.TestCheckResourceAttr(resourceName, "file_system_config.#", "0"), + ), + }, + }, + }) +} + func TestAccAWSLambdaFunction_tracingConfig(t *testing.T) { var conf lambda.GetFunctionOutput @@ -635,7 +689,7 @@ func TestAccAWSLambdaFunction_tracingConfig(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "tracing_config.0.mode", "Active"), ), }, @@ -650,7 +704,7 @@ func TestAccAWSLambdaFunction_tracingConfig(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "tracing_config.0.mode", "PassThrough"), ), }, @@ -712,7 +766,7 @@ func TestAccAWSLambdaFunction_Layers(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAWSLambdaFunctionVersion(&conf, "$LATEST"), resource.TestCheckResourceAttr(resourceName, "layers.#", "1"), ), @@ -749,7 +803,7 @@ func TestAccAWSLambdaFunction_LayersUpdate(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAWSLambdaFunctionVersion(&conf, "$LATEST"), resource.TestCheckResourceAttr(resourceName, "layers.#", "1"), ), @@ -765,7 +819,7 @@ func TestAccAWSLambdaFunction_LayersUpdate(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAWSLambdaFunctionVersion(&conf, "$LATEST"), resource.TestCheckResourceAttr(resourceName, "layers.#", "2"), ), @@ -794,7 +848,7 @@ func TestAccAWSLambdaFunction_VPC(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAWSLambdaFunctionVersion(&conf, "$LATEST"), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "1"), resource.TestCheckResourceAttr(resourceName, "vpc_config.0.subnet_ids.#", "1"), @@ -868,7 +922,7 @@ func TestAccAWSLambdaFunction_VPCUpdate(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAWSLambdaFunctionVersion(&conf, "$LATEST"), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "1"), resource.TestCheckResourceAttr(resourceName, "vpc_config.0.subnet_ids.#", "1"), @@ -886,7 +940,7 @@ func TestAccAWSLambdaFunction_VPCUpdate(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAWSLambdaFunctionVersion(&conf, "$LATEST"), resource.TestCheckResourceAttr(resourceName, "vpc_config.#", "1"), resource.TestCheckResourceAttr(resourceName, "vpc_config.0.subnet_ids.#", "2"), @@ -1009,7 +1063,7 @@ func TestAccAWSLambdaFunction_s3(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAWSLambdaFunctionVersion(&conf, "$LATEST"), ), }, @@ -1054,7 +1108,7 @@ func TestAccAWSLambdaFunction_localUpdate(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAwsLambdaSourceCodeHash(&conf, "8DPiX+G1l2LQ8hjBkwRchQFf1TSCEvPrYGRKlM9UoyY="), ), }, @@ -1075,7 +1129,7 @@ func TestAccAWSLambdaFunction_localUpdate(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAwsLambdaSourceCodeHash(&conf, "0tdaP9H9hsk9c2CycSwOG/sa/x5JyAmSYunA/ce99Pg="), func(s *terraform.State) error { return testAccCheckAttributeIsDateAfter(s, resourceName, "last_modified", timeBeforeUpdate) @@ -1121,7 +1175,7 @@ func TestAccAWSLambdaFunction_localUpdate_nameOnly(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAwsLambdaSourceCodeHash(&conf, "8DPiX+G1l2LQ8hjBkwRchQFf1TSCEvPrYGRKlM9UoyY="), ), }, @@ -1141,7 +1195,7 @@ func TestAccAWSLambdaFunction_localUpdate_nameOnly(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAwsLambdaSourceCodeHash(&conf, "0tdaP9H9hsk9c2CycSwOG/sa/x5JyAmSYunA/ce99Pg="), ), }, @@ -1182,7 +1236,7 @@ func TestAccAWSLambdaFunction_s3Update_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAwsLambdaSourceCodeHash(&conf, "8DPiX+G1l2LQ8hjBkwRchQFf1TSCEvPrYGRKlM9UoyY="), ), }, @@ -1203,7 +1257,7 @@ func TestAccAWSLambdaFunction_s3Update_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAwsLambdaSourceCodeHash(&conf, "0tdaP9H9hsk9c2CycSwOG/sa/x5JyAmSYunA/ce99Pg="), ), }, @@ -1244,7 +1298,7 @@ func TestAccAWSLambdaFunction_s3Update_unversioned(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAwsLambdaSourceCodeHash(&conf, "8DPiX+G1l2LQ8hjBkwRchQFf1TSCEvPrYGRKlM9UoyY="), ), }, @@ -1265,7 +1319,7 @@ func TestAccAWSLambdaFunction_s3Update_unversioned(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), testAccCheckAwsLambdaSourceCodeHash(&conf, "0tdaP9H9hsk9c2CycSwOG/sa/x5JyAmSYunA/ce99Pg="), ), }, @@ -1473,7 +1527,7 @@ func TestAccAWSLambdaFunction_tags(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckNoResourceAttr(resourceName, "tags"), ), }, @@ -1488,7 +1542,7 @@ func TestAccAWSLambdaFunction_tags(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.Key1", "Value One"), resource.TestCheckResourceAttr(resourceName, "tags.Description", "Very interesting"), @@ -1499,7 +1553,7 @@ func TestAccAWSLambdaFunction_tags(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsLambdaFunctionExists(resourceName, funcName, &conf), testAccCheckAwsLambdaFunctionName(&conf, funcName), - testAccCheckAwsLambdaFunctionArnHasSuffix(&conf, ":"+funcName), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "lambda", fmt.Sprintf("function:%s", funcName)), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), resource.TestCheckResourceAttr(resourceName, "tags.Key1", "Value One Changed"), resource.TestCheckResourceAttr(resourceName, "tags.Key2", "Value Two"), @@ -1793,6 +1847,13 @@ func testAccCheckAwsLambdaFunctionExists(res, funcName string, function *lambda. } } +func testAccCheckAwsLambdaFunctionInvokeArn(name string, function *lambda.GetFunctionOutput) resource.TestCheckFunc { + return func(s *terraform.State) error { + arn := aws.StringValue(function.Configuration.FunctionArn) + return testAccCheckResourceAttrRegionalARNAccountID(name, "invoke_arn", "apigateway", "lambda", fmt.Sprintf("path/2015-03-31/functions/%s/invocations", arn))(s) + } +} + func testAccAwsInvokeLambdaFunction(function *lambda.GetFunctionOutput) resource.TestCheckFunc { return func(s *terraform.State) error { f := function.Configuration @@ -1828,17 +1889,6 @@ func testAccCheckAWSLambdaFunctionVersion(function *lambda.GetFunctionOutput, ex } } -func testAccCheckAwsLambdaFunctionArnHasSuffix(function *lambda.GetFunctionOutput, arnSuffix string) resource.TestCheckFunc { - return func(s *terraform.State) error { - c := function.Configuration - if !strings.HasSuffix(*c.FunctionArn, arnSuffix) { - return fmt.Errorf("Expected function ARN %s to have suffix %s", *c.FunctionArn, arnSuffix) - } - - return nil - } -} - func testAccCheckAwsLambdaSourceCodeHash(function *lambda.GetFunctionOutput, expectedHash string) resource.TestCheckFunc { return func(s *terraform.State) error { c := function.Configuration @@ -1926,6 +1976,15 @@ func baseAccAWSLambdaConfig(policyName, roleName, sgName string) string { return fmt.Sprintf(` data "aws_partition" "current" {} +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_iam_role_policy" "iam_policy_for_lambda" { name = "%s" role = "${aws_iam_role.iam_for_lambda.id}" @@ -2006,14 +2065,27 @@ resource "aws_vpc" "vpc_for_lambda" { } resource "aws_subnet" "subnet_for_lambda" { - vpc_id = "${aws_vpc.vpc_for_lambda.id}" - cidr_block = "10.0.1.0/24" + vpc_id = "${aws_vpc.vpc_for_lambda.id}" + cidr_block = "10.0.1.0/24" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-lambda-function-1" } } +# This is defined here, rather than only in test cases where it's needed is to +# prevent a timeout issue when fully removing Lambda Filesystems +resource "aws_subnet" "subnet_for_lambda_az2" { + vpc_id = "${aws_vpc.vpc_for_lambda.id}" + cidr_block = "10.0.2.0/24" + availability_zone = data.aws_availability_zones.available.names[1] + + tags = { + Name = "tf-acc-lambda-function-2" + } +} + resource "aws_security_group" "sg_for_lambda" { name = "%s" description = "Allow all inbound traffic for lambda test" @@ -2234,6 +2306,118 @@ resource "aws_lambda_function" "test" { `, fileName, funcName) } +func testAccAWSLambdaFileSystemConfig(funcName, policyName, roleName, sgName string) string { + return fmt.Sprintf(baseAccAWSLambdaConfig(policyName, roleName, sgName)+` +resource "aws_efs_file_system" "efs_for_lambda" { + tags = { + Name = "efs_for_lambda" + } +} + +resource "aws_efs_mount_target" "mount_target_az1" { + file_system_id = "${aws_efs_file_system.efs_for_lambda.id}" + subnet_id = "${aws_subnet.subnet_for_lambda.id}" + security_groups = ["${aws_security_group.sg_for_lambda.id}"] +} + +resource "aws_efs_access_point" "access_point_1" { + file_system_id = "${aws_efs_file_system.efs_for_lambda.id}" + + root_directory { + path = "/lambda1" + creation_info { + owner_gid = 1000 + owner_uid = 1000 + permissions = "777" + } + } + + posix_user { + gid = 1000 + uid = 1000 + } +} + +resource "aws_lambda_function" "test" { + filename = "test-fixtures/lambdatest.zip" + function_name = "%s" + publish = true + role = "${aws_iam_role.iam_for_lambda.arn}" + handler = "exports.example" + runtime = "nodejs12.x" + + vpc_config { + subnet_ids = ["${aws_subnet.subnet_for_lambda.id}"] + security_group_ids = ["${aws_security_group.sg_for_lambda.id}"] + } + + file_system_config { + arn = "${aws_efs_access_point.access_point_1.arn}" + local_mount_path = "/mnt/efs" + } + + depends_on = [aws_efs_mount_target.mount_target_az1] + +} +`, funcName) +} + +func testAccAWSLambdaFileSystemUpdateConfig(funcName, policyName, roleName, sgName string) string { + return fmt.Sprintf(baseAccAWSLambdaConfig(policyName, roleName, sgName)+` +resource "aws_efs_file_system" "efs_for_lambda" { + tags = { + Name = "efs_for_lambda" + } +} + +resource "aws_efs_mount_target" "mount_target_az2" { + file_system_id = "${aws_efs_file_system.efs_for_lambda.id}" + subnet_id = "${aws_subnet.subnet_for_lambda_az2.id}" + security_groups = ["${aws_security_group.sg_for_lambda.id}"] +} + +resource "aws_efs_access_point" "access_point_2" { + file_system_id = "${aws_efs_file_system.efs_for_lambda.id}" + + root_directory { + path = "/lambda2" + creation_info { + owner_gid = 1000 + owner_uid = 1000 + permissions = "777" + } + } + + posix_user { + gid = 1000 + uid = 1000 + } +} + +resource "aws_lambda_function" "test" { + filename = "test-fixtures/lambdatest.zip" + function_name = "%s" + publish = true + role = "${aws_iam_role.iam_for_lambda.arn}" + handler = "exports.example" + runtime = "nodejs12.x" + + vpc_config { + subnet_ids = ["${aws_subnet.subnet_for_lambda_az2.id}"] + security_group_ids = ["${aws_security_group.sg_for_lambda.id}"] + } + + file_system_config { + arn = "${aws_efs_access_point.access_point_2.arn}" + local_mount_path = "/mnt/lambda" + } + + depends_on = [aws_efs_mount_target.mount_target_az2] + +} +`, funcName) +} + func testAccAWSLambdaConfigVersionedNodeJs10xRuntime(fileName, funcName, policyName, roleName, sgName string) string { return fmt.Sprintf(baseAccAWSLambdaConfig(policyName, roleName, sgName)+` resource "aws_lambda_function" "test" { @@ -2377,7 +2561,7 @@ resource "aws_sns_topic" "test" { } func testAccAWSLambdaConfigWithDeadLetterConfigUpdated(funcName, topic1Name, topic2Name, policyName, - roleName, sgName, uFuncName string) string { + roleName, sgName string) string { return fmt.Sprintf(baseAccAWSLambdaConfig(policyName, roleName, sgName)+` resource "aws_lambda_function" "test" { filename = "test-fixtures/lambdatest.zip" @@ -2398,7 +2582,7 @@ resource "aws_sns_topic" "test" { resource "aws_sns_topic" "test_2" { name = "%s" } -`, uFuncName, topic1Name, topic2Name) +`, funcName, topic1Name, topic2Name) } func testAccAWSLambdaConfigWithNilDeadLetterConfig(funcName, policyName, roleName, sgName string) string { @@ -2527,20 +2711,11 @@ resource "aws_lambda_function" "test" { runtime = "nodejs12.x" vpc_config { - subnet_ids = ["${aws_subnet.subnet_for_lambda.id}", "${aws_subnet.subnet_for_lambda_2.id}"] + subnet_ids = ["${aws_subnet.subnet_for_lambda.id}", "${aws_subnet.subnet_for_lambda_az2.id}"] security_group_ids = ["${aws_security_group.sg_for_lambda.id}", "${aws_security_group.sg_for_lambda_2.id}"] } } -resource "aws_subnet" "subnet_for_lambda_2" { - vpc_id = "${aws_vpc.vpc_for_lambda.id}" - cidr_block = "10.0.2.0/24" - - tags = { - Name = "tf-acc-lambda-function-2" - } -} - resource "aws_security_group" "sg_for_lambda_2" { name = "sg_for_lambda_%s" description = "Allow all inbound traffic for lambda test" diff --git a/aws/resource_aws_lambda_layer_version.go b/aws/resource_aws_lambda_layer_version.go index 92d564f38f2..9248901daa2 100644 --- a/aws/resource_aws_lambda_layer_version.go +++ b/aws/resource_aws_lambda_layer_version.go @@ -10,8 +10,8 @@ import ( "github.com/aws/aws-sdk-go/aws" arn2 "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/lambda" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) const awsMutexLambdaLayerKey = `aws_lambda_layer_version` diff --git a/aws/resource_aws_lambda_layer_version_test.go b/aws/resource_aws_lambda_layer_version_test.go index faa08e5b6aa..fc54fafc762 100644 --- a/aws/resource_aws_lambda_layer_version_test.go +++ b/aws/resource_aws_lambda_layer_version_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/lambda" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_lambda_permission.go b/aws/resource_aws_lambda_permission.go index 13432902100..d7dd2365543 100644 --- a/aws/resource_aws_lambda_permission.go +++ b/aws/resource_aws_lambda_permission.go @@ -11,8 +11,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/lambda" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) var LambdaFunctionRegexp = `^(arn:[\w-]+:lambda:)?([a-z]{2}-(?:[a-z]+-){1,2}\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?$` @@ -385,8 +385,7 @@ func getLambdaPolicyStatement(out *lambda.GetPolicyOutput, statemendId string) ( return findLambdaPolicyStatementById(&policy, statemendId) } -func findLambdaPolicyStatementById(policy *LambdaPolicy, id string) ( - *LambdaPolicyStatement, error) { +func findLambdaPolicyStatementById(policy *LambdaPolicy, id string) (*LambdaPolicyStatement, error) { log.Printf("[DEBUG] Received %d statements in Lambda policy: %s", len(policy.Statement), policy.Statement) for _, statement := range policy.Statement { diff --git a/aws/resource_aws_lambda_permission_test.go b/aws/resource_aws_lambda_permission_test.go index 12f651111e5..95e5ce55dc7 100644 --- a/aws/resource_aws_lambda_permission_test.go +++ b/aws/resource_aws_lambda_permission_test.go @@ -12,9 +12,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/lambda" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestLambdaPermissionUnmarshalling(t *testing.T) { @@ -170,7 +170,9 @@ func TestAccAWSLambdaPermission_basic(t *testing.T) { rString := acctest.RandString(8) funcName := fmt.Sprintf("tf_acc_lambda_perm_basic_%s", rString) roleName := fmt.Sprintf("tf_acc_role_lambda_perm_basic_%s", rString) - funcArnRe := regexp.MustCompile(":function:" + funcName + "$") + + resourceName := "aws_lambda_permission.allow_cloudwatch" + functionResourceName := "aws_lambda_function.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -180,19 +182,19 @@ func TestAccAWSLambdaPermission_basic(t *testing.T) { { Config: testAccAWSLambdaPermissionConfig(funcName, roleName), Check: resource.ComposeTestCheckFunc( - testAccCheckLambdaPermissionExists("aws_lambda_permission.allow_cloudwatch", &statement), - resource.TestCheckResourceAttr("aws_lambda_permission.allow_cloudwatch", "action", "lambda:InvokeFunction"), - resource.TestCheckResourceAttr("aws_lambda_permission.allow_cloudwatch", "principal", "events.amazonaws.com"), - resource.TestCheckResourceAttr("aws_lambda_permission.allow_cloudwatch", "statement_id", "AllowExecutionFromCloudWatch"), - resource.TestCheckResourceAttr("aws_lambda_permission.allow_cloudwatch", "qualifier", ""), - resource.TestMatchResourceAttr("aws_lambda_permission.allow_cloudwatch", "function_name", funcArnRe), - resource.TestCheckResourceAttr("aws_lambda_permission.allow_cloudwatch", "event_source_token", "test-event-source-token"), + testAccCheckLambdaPermissionExists(resourceName, &statement), + resource.TestCheckResourceAttr(resourceName, "action", "lambda:InvokeFunction"), + resource.TestCheckResourceAttr(resourceName, "principal", "events.amazonaws.com"), + resource.TestCheckResourceAttr(resourceName, "statement_id", "AllowExecutionFromCloudWatch"), + resource.TestCheckResourceAttr(resourceName, "qualifier", ""), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "event_source_token", "test-event-source-token"), ), }, { - ResourceName: "aws_lambda_permission.allow_cloudwatch", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc("aws_lambda_permission.allow_cloudwatch"), + ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -221,7 +223,9 @@ func TestAccAWSLambdaPermission_withRawFunctionName(t *testing.T) { rString := acctest.RandString(8) funcName := fmt.Sprintf("tf_acc_lambda_perm_w_raw_fname_%s", rString) roleName := fmt.Sprintf("tf_acc_role_lambda_perm_w_raw_fname_%s", rString) - funcArnRe := regexp.MustCompile(":function:" + funcName + "$") + + resourceName := "aws_lambda_permission.with_raw_func_name" + functionResourceName := "aws_lambda_function.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -231,17 +235,17 @@ func TestAccAWSLambdaPermission_withRawFunctionName(t *testing.T) { { Config: testAccAWSLambdaPermissionConfig_withRawFunctionName(funcName, roleName), Check: resource.ComposeTestCheckFunc( - testAccCheckLambdaPermissionExists("aws_lambda_permission.with_raw_func_name", &statement), - resource.TestCheckResourceAttr("aws_lambda_permission.with_raw_func_name", "action", "lambda:InvokeFunction"), - resource.TestCheckResourceAttr("aws_lambda_permission.with_raw_func_name", "principal", "events.amazonaws.com"), - resource.TestCheckResourceAttr("aws_lambda_permission.with_raw_func_name", "statement_id", "AllowExecutionWithRawFuncName"), - resource.TestMatchResourceAttr("aws_lambda_permission.with_raw_func_name", "function_name", funcArnRe), + testAccCheckLambdaPermissionExists(resourceName, &statement), + resource.TestCheckResourceAttr(resourceName, "action", "lambda:InvokeFunction"), + resource.TestCheckResourceAttr(resourceName, "principal", "events.amazonaws.com"), + resource.TestCheckResourceAttr(resourceName, "statement_id", "AllowExecutionWithRawFuncName"), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceName, "arn"), ), }, { - ResourceName: "aws_lambda_permission.with_raw_func_name", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc("aws_lambda_permission.with_raw_func_name"), + ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -252,9 +256,11 @@ func TestAccAWSLambdaPermission_withStatementIdPrefix(t *testing.T) { var statement LambdaPolicyStatement rName := acctest.RandomWithPrefix("tf-acc-test") - endsWithFuncName := regexp.MustCompile(":function:lambda_function_name_perm$") startsWithPrefix := regexp.MustCompile("^AllowExecutionWithStatementIdPrefix-") + resourceName := "aws_lambda_permission.with_statement_id_prefix" + functionResourceName := "aws_lambda_function.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -263,17 +269,17 @@ func TestAccAWSLambdaPermission_withStatementIdPrefix(t *testing.T) { { Config: testAccAWSLambdaPermissionConfig_withStatementIdPrefix(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckLambdaPermissionExists("aws_lambda_permission.with_statement_id_prefix", &statement), - resource.TestCheckResourceAttr("aws_lambda_permission.with_statement_id_prefix", "action", "lambda:InvokeFunction"), - resource.TestCheckResourceAttr("aws_lambda_permission.with_statement_id_prefix", "principal", "events.amazonaws.com"), - resource.TestMatchResourceAttr("aws_lambda_permission.with_statement_id_prefix", "statement_id", startsWithPrefix), - resource.TestMatchResourceAttr("aws_lambda_permission.with_statement_id_prefix", "function_name", endsWithFuncName), + testAccCheckLambdaPermissionExists(resourceName, &statement), + resource.TestCheckResourceAttr(resourceName, "action", "lambda:InvokeFunction"), + resource.TestCheckResourceAttr(resourceName, "principal", "events.amazonaws.com"), + resource.TestMatchResourceAttr(resourceName, "statement_id", startsWithPrefix), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceName, "arn"), ), }, { - ResourceName: "aws_lambda_permission.with_statement_id_prefix", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc("aws_lambda_permission.with_statement_id_prefix"), + ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc(resourceName), ImportStateVerify: true, ImportStateVerifyIgnore: []string{"statement_id_prefix"}, }, @@ -288,7 +294,9 @@ func TestAccAWSLambdaPermission_withQualifier(t *testing.T) { aliasName := fmt.Sprintf("tf_acc_lambda_perm_alias_w_qualifier_%s", rString) funcName := fmt.Sprintf("tf_acc_lambda_perm_w_qualifier_%s", rString) roleName := fmt.Sprintf("tf_acc_role_lambda_perm_w_qualifier_%s", rString) - funcArnRe := regexp.MustCompile(":function:" + funcName + "$") + + resourceName := "aws_lambda_permission.with_qualifier" + functionResourceName := "aws_lambda_function.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -298,18 +306,18 @@ func TestAccAWSLambdaPermission_withQualifier(t *testing.T) { { Config: testAccAWSLambdaPermissionConfig_withQualifier(aliasName, funcName, roleName), Check: resource.ComposeTestCheckFunc( - testAccCheckLambdaPermissionExists("aws_lambda_permission.with_qualifier", &statement), - resource.TestCheckResourceAttr("aws_lambda_permission.with_qualifier", "action", "lambda:InvokeFunction"), - resource.TestCheckResourceAttr("aws_lambda_permission.with_qualifier", "principal", "events.amazonaws.com"), - resource.TestCheckResourceAttr("aws_lambda_permission.with_qualifier", "statement_id", "AllowExecutionWithQualifier"), - resource.TestMatchResourceAttr("aws_lambda_permission.with_qualifier", "function_name", funcArnRe), - resource.TestCheckResourceAttr("aws_lambda_permission.with_qualifier", "qualifier", aliasName), + testAccCheckLambdaPermissionExists(resourceName, &statement), + resource.TestCheckResourceAttr(resourceName, "action", "lambda:InvokeFunction"), + resource.TestCheckResourceAttr(resourceName, "principal", "events.amazonaws.com"), + resource.TestCheckResourceAttr(resourceName, "statement_id", "AllowExecutionWithQualifier"), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "qualifier", aliasName), ), }, { - ResourceName: "aws_lambda_permission.with_qualifier", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc("aws_lambda_permission.with_qualifier"), + ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -317,12 +325,12 @@ func TestAccAWSLambdaPermission_withQualifier(t *testing.T) { } func TestAccAWSLambdaPermission_disappears(t *testing.T) { - var statement LambdaPolicyStatement - rString := acctest.RandString(8) funcName := fmt.Sprintf("tf_acc_lambda_perm_multi_%s", rString) roleName := fmt.Sprintf("tf_acc_role_lambda_perm_multi_%s", rString) + resourceName := "aws_lambda_permission.first" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -333,7 +341,7 @@ func TestAccAWSLambdaPermission_disappears(t *testing.T) { { Config: testAccAWSLambdaPermissionConfig_multiplePerms(funcName, roleName), Check: resource.ComposeTestCheckFunc( - testAccAWSLambdaPermissionDisappears("aws_lambda_permission.first", &statement), + testAccAWSLambdaPermissionDisappears(resourceName), ), ExpectNonEmptyPlan: true, }, @@ -351,7 +359,12 @@ func TestAccAWSLambdaPermission_multiplePerms(t *testing.T) { rString := acctest.RandString(8) funcName := fmt.Sprintf("tf_acc_lambda_perm_multi_%s", rString) roleName := fmt.Sprintf("tf_acc_role_lambda_perm_multi_%s", rString) - funcArnRe := regexp.MustCompile(":function:" + funcName + "$") + + resourceNameFirst := "aws_lambda_permission.first" + resourceNameSecond := "aws_lambda_permission.second" + resourceNameSecondModified := "aws_lambda_permission.sec0nd" + resourceNameThird := "aws_lambda_permission.third" + functionResourceName := "aws_lambda_function.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -362,52 +375,52 @@ func TestAccAWSLambdaPermission_multiplePerms(t *testing.T) { Config: testAccAWSLambdaPermissionConfig_multiplePerms(funcName, roleName), Check: resource.ComposeTestCheckFunc( // 1st - testAccCheckLambdaPermissionExists("aws_lambda_permission.first", &firstStatement), - resource.TestCheckResourceAttr("aws_lambda_permission.first", "action", "lambda:InvokeFunction"), - resource.TestCheckResourceAttr("aws_lambda_permission.first", "principal", "events.amazonaws.com"), - resource.TestCheckResourceAttr("aws_lambda_permission.first", "statement_id", "AllowExecutionFirst"), - resource.TestMatchResourceAttr("aws_lambda_permission.first", "function_name", funcArnRe), + testAccCheckLambdaPermissionExists(resourceNameFirst, &firstStatement), + resource.TestCheckResourceAttr(resourceNameFirst, "action", "lambda:InvokeFunction"), + resource.TestCheckResourceAttr(resourceNameFirst, "principal", "events.amazonaws.com"), + resource.TestCheckResourceAttr(resourceNameFirst, "statement_id", "AllowExecutionFirst"), + resource.TestCheckResourceAttrPair(resourceNameFirst, "function_name", functionResourceName, "arn"), // 2nd - testAccCheckLambdaPermissionExists("aws_lambda_permission.second", &firstStatementModified), - resource.TestCheckResourceAttr("aws_lambda_permission.second", "action", "lambda:*"), - resource.TestCheckResourceAttr("aws_lambda_permission.second", "principal", "events.amazonaws.com"), - resource.TestCheckResourceAttr("aws_lambda_permission.second", "statement_id", "AllowExecutionSecond"), - resource.TestMatchResourceAttr("aws_lambda_permission.second", "function_name", funcArnRe), + testAccCheckLambdaPermissionExists(resourceNameSecond, &firstStatementModified), + resource.TestCheckResourceAttr(resourceNameSecond, "action", "lambda:*"), + resource.TestCheckResourceAttr(resourceNameSecond, "principal", "events.amazonaws.com"), + resource.TestCheckResourceAttr(resourceNameSecond, "statement_id", "AllowExecutionSecond"), + resource.TestCheckResourceAttrPair(resourceNameSecond, "function_name", functionResourceName, "arn"), ), }, { Config: testAccAWSLambdaPermissionConfig_multiplePermsModified(funcName, roleName), Check: resource.ComposeTestCheckFunc( // 1st - testAccCheckLambdaPermissionExists("aws_lambda_permission.first", &secondStatement), - resource.TestCheckResourceAttr("aws_lambda_permission.first", "action", "lambda:InvokeFunction"), - resource.TestCheckResourceAttr("aws_lambda_permission.first", "principal", "events.amazonaws.com"), - resource.TestCheckResourceAttr("aws_lambda_permission.first", "statement_id", "AllowExecutionFirst"), - resource.TestMatchResourceAttr("aws_lambda_permission.first", "function_name", funcArnRe), + testAccCheckLambdaPermissionExists(resourceNameFirst, &secondStatement), + resource.TestCheckResourceAttr(resourceNameFirst, "action", "lambda:InvokeFunction"), + resource.TestCheckResourceAttr(resourceNameFirst, "principal", "events.amazonaws.com"), + resource.TestCheckResourceAttr(resourceNameFirst, "statement_id", "AllowExecutionFirst"), + resource.TestCheckResourceAttrPair(resourceNameFirst, "function_name", functionResourceName, "arn"), // 2nd - testAccCheckLambdaPermissionExists("aws_lambda_permission.sec0nd", &secondStatementModified), - resource.TestCheckResourceAttr("aws_lambda_permission.sec0nd", "action", "lambda:*"), - resource.TestCheckResourceAttr("aws_lambda_permission.sec0nd", "principal", "events.amazonaws.com"), - resource.TestCheckResourceAttr("aws_lambda_permission.sec0nd", "statement_id", "AllowExecutionSec0nd"), - resource.TestMatchResourceAttr("aws_lambda_permission.sec0nd", "function_name", funcArnRe), + testAccCheckLambdaPermissionExists(resourceNameSecondModified, &secondStatementModified), + resource.TestCheckResourceAttr(resourceNameSecondModified, "action", "lambda:*"), + resource.TestCheckResourceAttr(resourceNameSecondModified, "principal", "events.amazonaws.com"), + resource.TestCheckResourceAttr(resourceNameSecondModified, "statement_id", "AllowExecutionSec0nd"), + resource.TestCheckResourceAttrPair(resourceNameSecondModified, "function_name", functionResourceName, "arn"), // 3rd - testAccCheckLambdaPermissionExists("aws_lambda_permission.third", &thirdStatement), - resource.TestCheckResourceAttr("aws_lambda_permission.third", "action", "lambda:*"), - resource.TestCheckResourceAttr("aws_lambda_permission.third", "principal", "events.amazonaws.com"), - resource.TestCheckResourceAttr("aws_lambda_permission.third", "statement_id", "AllowExecutionThird"), - resource.TestMatchResourceAttr("aws_lambda_permission.third", "function_name", funcArnRe), + testAccCheckLambdaPermissionExists(resourceNameThird, &thirdStatement), + resource.TestCheckResourceAttr(resourceNameThird, "action", "lambda:*"), + resource.TestCheckResourceAttr(resourceNameThird, "principal", "events.amazonaws.com"), + resource.TestCheckResourceAttr(resourceNameThird, "statement_id", "AllowExecutionThird"), + resource.TestCheckResourceAttrPair(resourceNameThird, "function_name", functionResourceName, "arn"), ), }, { - ResourceName: "aws_lambda_permission.first", + ResourceName: resourceNameFirst, ImportState: true, - ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc("aws_lambda_permission.first"), + ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc(resourceNameFirst), ImportStateVerify: true, }, { - ResourceName: "aws_lambda_permission.sec0nd", + ResourceName: resourceNameSecondModified, ImportState: true, - ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc("aws_lambda_permission.sec0nd"), + ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc(resourceNameSecondModified), ImportStateVerify: true, }, }, @@ -421,7 +434,10 @@ func TestAccAWSLambdaPermission_withS3(t *testing.T) { bucketName := fmt.Sprintf("tf-acc-bucket-lambda-perm-w-s3-%s", rString) funcName := fmt.Sprintf("tf_acc_lambda_perm_w_s3_%s", rString) roleName := fmt.Sprintf("tf_acc_role_lambda_perm_w_s3_%s", rString) - funcArnRe := regexp.MustCompile(":function:" + funcName + "$") + + resourceName := "aws_lambda_permission.with_s3" + functionResourceName := "aws_lambda_function.test" + bucketResourceName := "aws_s3_bucket.default" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -431,19 +447,18 @@ func TestAccAWSLambdaPermission_withS3(t *testing.T) { { Config: testAccAWSLambdaPermissionConfig_withS3(bucketName, funcName, roleName), Check: resource.ComposeTestCheckFunc( - testAccCheckLambdaPermissionExists("aws_lambda_permission.with_s3", &statement), - resource.TestCheckResourceAttr("aws_lambda_permission.with_s3", "action", "lambda:InvokeFunction"), - resource.TestCheckResourceAttr("aws_lambda_permission.with_s3", "principal", "s3.amazonaws.com"), - resource.TestCheckResourceAttr("aws_lambda_permission.with_s3", "statement_id", "AllowExecutionFromS3"), - resource.TestMatchResourceAttr("aws_lambda_permission.with_s3", "function_name", funcArnRe), - resource.TestCheckResourceAttr("aws_lambda_permission.with_s3", "source_arn", - fmt.Sprintf("arn:aws:s3:::%s", bucketName)), + testAccCheckLambdaPermissionExists(resourceName, &statement), + resource.TestCheckResourceAttr(resourceName, "action", "lambda:InvokeFunction"), + resource.TestCheckResourceAttr(resourceName, "principal", "s3.amazonaws.com"), + resource.TestCheckResourceAttr(resourceName, "statement_id", "AllowExecutionFromS3"), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "source_arn", bucketResourceName, "arn"), ), }, { - ResourceName: "aws_lambda_permission.with_s3", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc("aws_lambda_permission.with_s3"), + ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -458,8 +473,9 @@ func TestAccAWSLambdaPermission_withSNS(t *testing.T) { funcName := fmt.Sprintf("tf_acc_lambda_perm_w_sns_%s", rString) roleName := fmt.Sprintf("tf_acc_role_lambda_perm_w_sns_%s", rString) - funcArnRe := regexp.MustCompile(":function:" + funcName + "$") - topicArnRe := regexp.MustCompile(":" + topicName + "$") + resourceName := "aws_lambda_permission.with_sns" + functionResourceName := "aws_lambda_function.test" + snsTopicResourceName := "aws_sns_topic.default" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -469,18 +485,18 @@ func TestAccAWSLambdaPermission_withSNS(t *testing.T) { { Config: testAccAWSLambdaPermissionConfig_withSNS(topicName, funcName, roleName), Check: resource.ComposeTestCheckFunc( - testAccCheckLambdaPermissionExists("aws_lambda_permission.with_sns", &statement), - resource.TestCheckResourceAttr("aws_lambda_permission.with_sns", "action", "lambda:InvokeFunction"), - resource.TestCheckResourceAttr("aws_lambda_permission.with_sns", "principal", "sns.amazonaws.com"), - resource.TestCheckResourceAttr("aws_lambda_permission.with_sns", "statement_id", "AllowExecutionFromSNS"), - resource.TestMatchResourceAttr("aws_lambda_permission.with_sns", "function_name", funcArnRe), - resource.TestMatchResourceAttr("aws_lambda_permission.with_sns", "source_arn", topicArnRe), + testAccCheckLambdaPermissionExists(resourceName, &statement), + resource.TestCheckResourceAttr(resourceName, "action", "lambda:InvokeFunction"), + resource.TestCheckResourceAttr(resourceName, "principal", "sns.amazonaws.com"), + resource.TestCheckResourceAttr(resourceName, "statement_id", "AllowExecutionFromSNS"), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "source_arn", snsTopicResourceName, "arn"), ), }, { - ResourceName: "aws_lambda_permission.with_sns", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc("aws_lambda_permission.with_sns"), + ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, @@ -493,8 +509,10 @@ func TestAccAWSLambdaPermission_withIAMRole(t *testing.T) { rString := acctest.RandString(8) funcName := fmt.Sprintf("tf_acc_lambda_perm_w_iam_%s", rString) roleName := fmt.Sprintf("tf_acc_role_lambda_perm_w_iam_%s", rString) - funcArnRe := regexp.MustCompile(":function:" + funcName + "$") - roleArnRe := regexp.MustCompile("/" + roleName + "$") + + resourceName := "aws_lambda_permission.iam_role" + iamRoleResourceName := "aws_iam_role.test" + functionResourceName := "aws_lambda_function.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -504,24 +522,24 @@ func TestAccAWSLambdaPermission_withIAMRole(t *testing.T) { { Config: testAccAWSLambdaPermissionConfig_withIAMRole(funcName, roleName), Check: resource.ComposeTestCheckFunc( - testAccCheckLambdaPermissionExists("aws_lambda_permission.iam_role", &statement), - resource.TestCheckResourceAttr("aws_lambda_permission.iam_role", "action", "lambda:InvokeFunction"), - resource.TestMatchResourceAttr("aws_lambda_permission.iam_role", "principal", roleArnRe), - resource.TestCheckResourceAttr("aws_lambda_permission.iam_role", "statement_id", "AllowExecutionFromIAMRole"), - resource.TestMatchResourceAttr("aws_lambda_permission.iam_role", "function_name", funcArnRe), + testAccCheckLambdaPermissionExists(resourceName, &statement), + resource.TestCheckResourceAttr(resourceName, "action", "lambda:InvokeFunction"), + resource.TestCheckResourceAttrPair(resourceName, "principal", iamRoleResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "statement_id", "AllowExecutionFromIAMRole"), + resource.TestCheckResourceAttrPair(resourceName, "function_name", functionResourceName, "arn"), ), }, { - ResourceName: "aws_lambda_permission.iam_role", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc("aws_lambda_permission.iam_role"), + ImportStateIdFunc: testAccAWSCLambdaPermissionImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, }) } -func testAccAWSLambdaPermissionDisappears(n string, statement *LambdaPolicyStatement) resource.TestCheckFunc { +func testAccAWSLambdaPermissionDisappears(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -704,12 +722,12 @@ func testAccAWSLambdaPermissionConfig(funcName, roleName string) string { resource "aws_lambda_permission" "allow_cloudwatch" { statement_id = "AllowExecutionFromCloudWatch" action = "lambda:InvokeFunction" - function_name = aws_lambda_function.test_lambda.arn + function_name = aws_lambda_function.test.arn principal = "events.amazonaws.com" event_source_token = "test-event-source-token" } -resource "aws_lambda_function" "test_lambda" { +resource "aws_lambda_function" "test" { filename = "test-fixtures/lambdatest.zip" function_name = "%s" role = aws_iam_role.iam_for_lambda.arn @@ -792,11 +810,11 @@ func testAccAWSLambdaPermissionConfig_withRawFunctionName(funcName, roleName str resource "aws_lambda_permission" "with_raw_func_name" { statement_id = "AllowExecutionWithRawFuncName" action = "lambda:InvokeFunction" - function_name = aws_lambda_function.test_lambda.arn + function_name = aws_lambda_function.test.arn principal = "events.amazonaws.com" } -resource "aws_lambda_function" "test_lambda" { +resource "aws_lambda_function" "test" { filename = "test-fixtures/lambdatest.zip" function_name = "%s" role = aws_iam_role.iam_for_lambda.arn @@ -831,11 +849,11 @@ func testAccAWSLambdaPermissionConfig_withStatementIdPrefix(rName string) string resource "aws_lambda_permission" "with_statement_id_prefix" { statement_id_prefix = "AllowExecutionWithStatementIdPrefix-" action = "lambda:InvokeFunction" - function_name = aws_lambda_function.test_lambda.arn + function_name = aws_lambda_function.test.arn principal = "events.amazonaws.com" } -resource "aws_lambda_function" "test_lambda" { +resource "aws_lambda_function" "test" { filename = "test-fixtures/lambdatest.zip" function_name = "lambda_function_name_perm" role = aws_iam_role.iam_for_lambda.arn @@ -870,7 +888,7 @@ func testAccAWSLambdaPermissionConfig_withQualifier(aliasName, funcName, roleNam resource "aws_lambda_permission" "with_qualifier" { statement_id = "AllowExecutionWithQualifier" action = "lambda:InvokeFunction" - function_name = aws_lambda_function.test_lambda.arn + function_name = aws_lambda_function.test.arn principal = "events.amazonaws.com" source_account = "111122223333" source_arn = "arn:aws:events:eu-west-1:111122223333:rule/RunDaily" @@ -880,11 +898,11 @@ resource "aws_lambda_permission" "with_qualifier" { resource "aws_lambda_alias" "test_alias" { name = "%s" description = "a sample description" - function_name = aws_lambda_function.test_lambda.arn + function_name = aws_lambda_function.test.arn function_version = "$LATEST" } -resource "aws_lambda_function" "test_lambda" { +resource "aws_lambda_function" "test" { filename = "test-fixtures/lambdatest.zip" function_name = "%s" role = aws_iam_role.iam_for_lambda.arn @@ -918,19 +936,19 @@ var testAccAWSLambdaPermissionConfig_multiplePerms_tpl = ` resource "aws_lambda_permission" "first" { statement_id = "AllowExecutionFirst" action = "lambda:InvokeFunction" - function_name = aws_lambda_function.test_lambda.arn + function_name = aws_lambda_function.test.arn principal = "events.amazonaws.com" } resource "aws_lambda_permission" "%s" { statement_id = "%s" action = "lambda:*" - function_name = aws_lambda_function.test_lambda.arn + function_name = aws_lambda_function.test.arn principal = "events.amazonaws.com" } %s -resource "aws_lambda_function" "test_lambda" { +resource "aws_lambda_function" "test" { filename = "test-fixtures/lambdatest.zip" function_name = "%s" role = aws_iam_role.iam_for_lambda.arn @@ -969,7 +987,7 @@ func testAccAWSLambdaPermissionConfig_multiplePermsModified(funcName, roleName s resource "aws_lambda_permission" "third" { statement_id = "AllowExecutionThird" action = "lambda:*" - function_name = aws_lambda_function.test_lambda.arn + function_name = aws_lambda_function.test.arn principal = "events.amazonaws.com" } `, funcName, roleName) @@ -980,7 +998,7 @@ func testAccAWSLambdaPermissionConfig_withS3(bucketName, funcName, roleName stri resource "aws_lambda_permission" "with_s3" { statement_id = "AllowExecutionFromS3" action = "lambda:InvokeFunction" - function_name = aws_lambda_function.my-func.arn + function_name = aws_lambda_function.test.arn principal = "s3.amazonaws.com" source_arn = aws_s3_bucket.default.arn } @@ -990,15 +1008,15 @@ resource "aws_s3_bucket" "default" { acl = "private" } -resource "aws_lambda_function" "my-func" { +resource "aws_lambda_function" "test" { filename = "test-fixtures/lambdatest.zip" function_name = "%s" - role = aws_iam_role.police.arn + role = aws_iam_role.test.arn handler = "exports.handler" runtime = "nodejs12.x" } -resource "aws_iam_role" "police" { +resource "aws_iam_role" "test" { name = "%s" assume_role_policy = < 0 { raw, ok := networkInterface["ipv6_addresses"] if !ok { @@ -1457,8 +1517,12 @@ func readNetworkInterfacesFromConfig(ni map[string]interface{}) (*ec2.LaunchTemp var privateIpAddress string networkInterface := &ec2.LaunchTemplateInstanceNetworkInterfaceSpecificationRequest{} - if v, ok := ni["delete_on_termination"]; ok { - networkInterface.DeleteOnTermination = aws.Bool(v.(bool)) + if v, ok := ni["delete_on_termination"]; ok && v.(string) != "" { + vBool, err := strconv.ParseBool(v.(string)) + if err != nil { + return nil, fmt.Errorf("error converting delete_on_termination %q from string to boolean: %w", v.(string), err) + } + networkInterface.DeleteOnTermination = aws.Bool(vBool) } if v, ok := ni["description"].(string); ok && v != "" { @@ -1707,9 +1771,39 @@ func readPlacementFromConfig(p map[string]interface{}) *ec2.LaunchTemplatePlacem placement.Tenancy = aws.String(v) } - if v, ok := p["partition_number"].(int); ok { + if v, ok := p["partition_number"].(int); ok && v != 0 { placement.PartitionNumber = aws.Int64(int64(v)) } return placement } + +var updateKeys = []string{ + "block_device_mappings", + "capacity_reservation_specification", + "cpu_options", + "credit_specification", + "description", + "disable_api_termination", + "ebs_optimized", + "elastic_gpu_specifications", + "elastic_inference_accelerator", + "hibernation_options", + "iam_instance_profile", + "image_id", + "instance_initiated_shutdown_behavior", + "instance_market_options", + "instance_type", + "kernel_id", + "key_name", + "license_specification", + "metadata_options", + "monitoring", + "network_interfaces", + "placement", + "ram_disk_id", + "security_group_names", + "tag_specifications", + "user_data", + "vpc_security_group_ids", +} diff --git a/aws/resource_aws_launch_template_test.go b/aws/resource_aws_launch_template_test.go index 413599fb214..14dfef386f0 100644 --- a/aws/resource_aws_launch_template_test.go +++ b/aws/resource_aws_launch_template_test.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -77,7 +77,7 @@ func testSweepLaunchTemplates(region string) error { func TestAccAWSLaunchTemplate_basic(t *testing.T) { var template ec2.LaunchTemplate resourceName := "aws_launch_template.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -85,7 +85,7 @@ func TestAccAWSLaunchTemplate_basic(t *testing.T) { CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLaunchTemplateConfig_basic(rInt), + Config: testAccAWSLaunchTemplateConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "default_version", "1"), @@ -107,7 +107,7 @@ func TestAccAWSLaunchTemplate_basic(t *testing.T) { func TestAccAWSLaunchTemplate_disappears(t *testing.T) { var launchTemplate ec2.LaunchTemplate resourceName := "aws_launch_template.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -115,7 +115,7 @@ func TestAccAWSLaunchTemplate_disappears(t *testing.T) { CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLaunchTemplateConfig_basic(rInt), + Config: testAccAWSLaunchTemplateConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchTemplateExists(resourceName, &launchTemplate), testAccCheckAWSLaunchTemplateDisappears(&launchTemplate), @@ -285,10 +285,65 @@ func TestAccAWSLaunchTemplate_ElasticInferenceAccelerator(t *testing.T) { }) } +func TestAccAWSLaunchTemplate_NetworkInterfaces_DeleteOnTermination(t *testing.T) { + var template ec2.LaunchTemplate + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_launch_template.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLaunchTemplateConfig_NetworkInterfaces_DeleteOnTermination(rName, "true"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSLaunchTemplateExists(resourceName, &template), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.security_groups.#", "1"), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.delete_on_termination", "true"), + ), + }, + { + Config: testAccAWSLaunchTemplateConfig_NetworkInterfaces_DeleteOnTermination(rName, "false"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSLaunchTemplateExists(resourceName, &template), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.security_groups.#", "1"), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.delete_on_termination", "false"), + ), + }, + { + Config: testAccAWSLaunchTemplateConfig_NetworkInterfaces_DeleteOnTermination(rName, "\"\""), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSLaunchTemplateExists(resourceName, &template), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.security_groups.#", "1"), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.delete_on_termination", ""), + ), + }, + { + Config: testAccAWSLaunchTemplateConfig_NetworkInterfaces_DeleteOnTermination(rName, "null"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSLaunchTemplateExists(resourceName, &template), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.security_groups.#", "1"), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.delete_on_termination", ""), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + func TestAccAWSLaunchTemplate_data(t *testing.T) { var template ec2.LaunchTemplate resourceName := "aws_launch_template.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -296,7 +351,7 @@ func TestAccAWSLaunchTemplate_data(t *testing.T) { CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLaunchTemplateConfig_data(rInt), + Config: testAccAWSLaunchTemplateConfig_data(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "block_device_mappings.#", "1"), @@ -313,6 +368,7 @@ func TestAccAWSLaunchTemplate_data(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "monitoring.#", "1"), resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.security_groups.#", "1"), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.delete_on_termination", ""), resource.TestCheckResourceAttr(resourceName, "placement.#", "1"), resource.TestCheckResourceAttrSet(resourceName, "ram_disk_id"), resource.TestCheckResourceAttr(resourceName, "vpc_security_group_ids.#", "1"), @@ -404,7 +460,7 @@ func TestAccAWSLaunchTemplate_update(t *testing.T) { func TestAccAWSLaunchTemplate_tags(t *testing.T) { var template ec2.LaunchTemplate resourceName := "aws_launch_template.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -412,7 +468,7 @@ func TestAccAWSLaunchTemplate_tags(t *testing.T) { CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLaunchTemplateConfig_basic(rInt), + Config: testAccAWSLaunchTemplateConfig_basic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -425,7 +481,7 @@ func TestAccAWSLaunchTemplate_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSLaunchTemplateConfig_tagsUpdate(rInt), + Config: testAccAWSLaunchTemplateConfig_tagsUpdate(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -439,7 +495,7 @@ func TestAccAWSLaunchTemplate_tags(t *testing.T) { func TestAccAWSLaunchTemplate_capacityReservation_preference(t *testing.T) { var template ec2.LaunchTemplate resourceName := "aws_launch_template.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -447,7 +503,7 @@ func TestAccAWSLaunchTemplate_capacityReservation_preference(t *testing.T) { CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLaunchTemplateConfig_capacityReservation_preference(rInt, "open"), + Config: testAccAWSLaunchTemplateConfig_capacityReservation_preference(rName, "open"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchTemplateExists(resourceName, &template), ), @@ -464,7 +520,7 @@ func TestAccAWSLaunchTemplate_capacityReservation_preference(t *testing.T) { func TestAccAWSLaunchTemplate_capacityReservation_target(t *testing.T) { var template ec2.LaunchTemplate resourceName := "aws_launch_template.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -472,7 +528,7 @@ func TestAccAWSLaunchTemplate_capacityReservation_target(t *testing.T) { CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLaunchTemplateConfig_capacityReservation_target(rInt), + Config: testAccAWSLaunchTemplateConfig_capacityReservation_target(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchTemplateExists(resourceName, &template), ), @@ -625,6 +681,7 @@ func TestAccAWSLaunchTemplate_networkInterface(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), resource.TestCheckResourceAttrSet(resourceName, "network_interfaces.0.network_interface_id"), resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.associate_public_ip_address", ""), + resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.delete_on_termination", ""), resource.TestCheckResourceAttr(resourceName, "network_interfaces.0.ipv4_address_count", "2"), ), }, @@ -640,6 +697,7 @@ func TestAccAWSLaunchTemplate_networkInterface(t *testing.T) { func TestAccAWSLaunchTemplate_networkInterfaceAddresses(t *testing.T) { var template ec2.LaunchTemplate resourceName := "aws_launch_template.test" + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -647,7 +705,7 @@ func TestAccAWSLaunchTemplate_networkInterfaceAddresses(t *testing.T) { CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLaunchTemplateConfig_networkInterfaceAddresses, + Config: testAccAWSLaunchTemplateConfig_networkInterfaceAddresses(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), @@ -777,7 +835,7 @@ func TestAccAWSLaunchTemplate_networkInterface_ipv6Addresses(t *testing.T) { func TestAccAWSLaunchTemplate_networkInterface_ipv6AddressCount(t *testing.T) { var template ec2.LaunchTemplate resourceName := "aws_launch_template.test" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -785,7 +843,7 @@ func TestAccAWSLaunchTemplate_networkInterface_ipv6AddressCount(t *testing.T) { CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLaunchTemplateConfig_ipv6_count(rInt), + Config: testAccAWSLaunchTemplateConfig_ipv6_count(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "network_interfaces.#", "1"), @@ -847,7 +905,7 @@ func TestAccAWSLaunchTemplate_instanceMarketOptions(t *testing.T) { func TestAccAWSLaunchTemplate_licenseSpecification(t *testing.T) { var template ec2.LaunchTemplate resourceName := "aws_launch_template.example" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -855,7 +913,7 @@ func TestAccAWSLaunchTemplate_licenseSpecification(t *testing.T) { CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLaunchTemplateConfig_licenseSpecification(rInt), + Config: testAccAWSLaunchTemplateConfig_licenseSpecification(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSLaunchTemplateExists(resourceName, &template), resource.TestCheckResourceAttr(resourceName, "license_specification.#", "1"), @@ -939,6 +997,108 @@ func TestAccAWSLaunchTemplate_hibernation(t *testing.T) { }) } +func TestAccAWSLaunchTemplate_defaultVersion(t *testing.T) { + resourceName := "aws_launch_template.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + description := "Test Description 1" + descriptionNew := "Test Description 2" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLaunchTemplateConfig_description(rName, description), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "default_version", "1"), + resource.TestCheckResourceAttr(resourceName, "latest_version", "1"), + ), + }, + // An updated config should cause a new version to be created + // but keep the default_version unchanged if unset + { + Config: testAccAWSLaunchTemplateConfig_description(rName, descriptionNew), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "default_version", "1"), + resource.TestCheckResourceAttr(resourceName, "latest_version", "2"), + ), + }, + // An updated config to set the default_version to an existing version + // should not cause a new version to be created + { + Config: testAccAWSLaunchTemplateConfig_descriptionDefaultVersion(rName, descriptionNew, 2), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "default_version", "2"), + resource.TestCheckResourceAttr(resourceName, "latest_version", "2"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSLaunchTemplate_updateDefaultVersion(t *testing.T) { + resourceName := "aws_launch_template.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + description := "Test Description 1" + descriptionNew := "Test Description 2" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLaunchTemplateDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLaunchTemplateConfig_description(rName, description), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "default_version", "1"), + resource.TestCheckResourceAttr(resourceName, "latest_version", "1"), + ), + }, + // Updating a field should create a new version but not update the default_version + // if update_default_version is set to false + { + Config: testAccAWSLaunchTemplateconfig_descriptionUpdateDefaultVersion(rName, descriptionNew, false), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "default_version", "1"), + resource.TestCheckResourceAttr(resourceName, "latest_version", "2"), + ), + }, + // Only updating the update_default_version to true should not create a new version + // but update the template version to the latest available + { + Config: testAccAWSLaunchTemplateconfig_descriptionUpdateDefaultVersion(rName, descriptionNew, true), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "default_version", "2"), + resource.TestCheckResourceAttr(resourceName, "latest_version", "2"), + ), + }, + // Updating a field should create a new version and update the default_version + // if update_default_version is set to true + { + Config: testAccAWSLaunchTemplateconfig_descriptionUpdateDefaultVersion(rName, description, true), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "default_version", "3"), + resource.TestCheckResourceAttr(resourceName, "latest_version", "3"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "update_default_version", + }, + }, + }, + }) +} + func testAccCheckAWSLaunchTemplateExists(n string, t *ec2.LaunchTemplate) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -1011,28 +1171,28 @@ func testAccCheckAWSLaunchTemplateDisappears(launchTemplate *ec2.LaunchTemplate) } } -func testAccAWSLaunchTemplateConfig_basic(rInt int) string { +func testAccAWSLaunchTemplateConfig_basic(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { - name = "test_%d" + name = %q tags = { test = "bar" } } -`, rInt) +`, rName) } -func testAccAWSLaunchTemplateConfig_ipv6_count(rInt int) string { +func testAccAWSLaunchTemplateConfig_ipv6_count(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { - name = "set_ipv6_count_test_%d" + name = %q network_interfaces { ipv6_address_count = 1 } } -`, rInt) +`, rName) } func testAccAWSLaunchTemplateConfig_BlockDeviceMappings_EBS(rName string) string { @@ -1150,6 +1310,20 @@ resource "aws_autoscaling_group" "test" { `, rName, deleteOnTermination, rName) } +func testAccAWSLaunchTemplateConfig_NetworkInterfaces_DeleteOnTermination(rName string, deleteOnTermination string) string { + return fmt.Sprintf(` +resource "aws_launch_template" "test" { + name = %q + + network_interfaces { + network_interface_id = "eni-123456ab" + security_groups = ["sg-1a23bc45"] + delete_on_termination = %s + } +} +`, rName, deleteOnTermination) +} + func testAccAWSLaunchTemplateConfig_EbsOptimized(rName, ebsOptimized string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { @@ -1171,10 +1345,10 @@ resource "aws_launch_template" "test" { `, rName, elasticInferenceAcceleratorType) } -func testAccAWSLaunchTemplateConfig_data(rInt int) string { +func testAccAWSLaunchTemplateConfig_data(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { - name = "test_%d" + name = %q block_device_mappings { device_name = "test" @@ -1231,34 +1405,34 @@ resource "aws_launch_template" "test" { } } } -`, rInt) +`, rName) //lintignore:AWSAT002 } -func testAccAWSLaunchTemplateConfig_tagsUpdate(rInt int) string { +func testAccAWSLaunchTemplateConfig_tagsUpdate(rName string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { - name = "test_%d" + name = %q tags = { bar = "baz" } } -`, rInt) +`, rName) } -func testAccAWSLaunchTemplateConfig_capacityReservation_preference(rInt int, preference string) string { +func testAccAWSLaunchTemplateConfig_capacityReservation_preference(rName string, preference string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { - name = "test_%d" + name = %q capacity_reservation_specification { capacity_reservation_preference = %q } } -`, rInt, preference) +`, rName, preference) } -func testAccAWSLaunchTemplateConfig_capacityReservation_target(rInt int) string { +func testAccAWSLaunchTemplateConfig_capacityReservation_target(rName string) string { return fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1277,7 +1451,7 @@ resource "aws_ec2_capacity_reservation" "test" { } resource "aws_launch_template" "test" { - name = "test_%d" + name = %q capacity_reservation_specification { capacity_reservation_target { @@ -1285,7 +1459,7 @@ resource "aws_launch_template" "test" { } } } -`, rInt) +`, rName) } func testAccAWSLaunchTemplateConfig_cpuOptions(rName string, coreCount, threadsPerCore int) string { @@ -1324,7 +1498,7 @@ resource "aws_launch_template" "test" { `, rName) } -func testAccAWSLaunchTemplateConfig_licenseSpecification(rInt int) string { +func testAccAWSLaunchTemplateConfig_licenseSpecification(rName string) string { return fmt.Sprintf(` resource "aws_licensemanager_license_configuration" "example" { name = "Example" @@ -1332,20 +1506,20 @@ resource "aws_licensemanager_license_configuration" "example" { } resource "aws_launch_template" "example" { - name = "test_%d" + name = %q license_specification { license_configuration_arn = "${aws_licensemanager_license_configuration.example.id}" } } -`, rInt) +`, rName) } func testAccAWSLaunchTemplateConfig_description(rName, description string) string { return fmt.Sprintf(` resource "aws_launch_template" "test" { - name = "%s" - description = "%s" + name = %q + description = %q } `, rName, description) } @@ -1398,7 +1572,8 @@ resource "aws_launch_template" "test" { `, rName, partNum) } -const testAccAWSLaunchTemplateConfig_networkInterfaceAddresses = ` +func testAccAWSLaunchTemplateConfig_networkInterfaceAddresses(rName string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" } @@ -1413,14 +1588,16 @@ resource "aws_network_interface" "test" { } resource "aws_launch_template" "test" { - name = "network-interface-launch-template" + name = %q network_interfaces { network_interface_id = "${aws_network_interface.test.id}" ipv4_addresses = ["10.1.0.10", "10.1.0.11"] } } -` +`, rName) + +} func testAccAWSLaunchTemplateConfig_associatePublicIpAddress(rName, associatePublicIPAddress string) string { return fmt.Sprintf(` @@ -1658,3 +1835,30 @@ resource "aws_launch_template" "test" { } `, rName, enabled) } + +func testAccAWSLaunchTemplateConfig_descriptionDefaultVersion(rName, description string, version int) string { + return fmt.Sprintf(` +resource "aws_launch_template" "test" { + name = %q + description = %q + default_version = %d + + tags = { + test = "baz" + } +} +`, rName, description, version) +} + +func testAccAWSLaunchTemplateconfig_descriptionUpdateDefaultVersion(rName, description string, update bool) string { + return fmt.Sprintf(` +resource "aws_launch_template" "test" { + name = %q + description = %q + update_default_version = %v + + tags = { + test = "baz" + } +}`, rName, description, update) +} diff --git a/aws/resource_aws_lb.go b/aws/resource_aws_lb.go index 1b1abe80443..09beab16265 100644 --- a/aws/resource_aws_lb.go +++ b/aws/resource_aws_lb.go @@ -2,6 +2,7 @@ package aws import ( "bytes" + "context" "fmt" "log" "regexp" @@ -11,10 +12,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -115,6 +116,12 @@ func resourceAwsLb() *schema.Resource { Optional: true, ForceNew: true, }, + "private_ipv4_address": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.IsIPv4Address, + }, }, }, Set: func(v interface{}) int { @@ -124,6 +131,9 @@ func resourceAwsLb() *schema.Resource { if m["allocation_id"] != "" { buf.WriteString(fmt.Sprintf("%s-", m["allocation_id"].(string))) } + if m["private_ipv4_address"] != "" { + buf.WriteString(fmt.Sprintf("%s-", m["private_ipv4_address"].(string))) + } return hashcode.String(buf.String()) }, }, @@ -276,6 +286,10 @@ func resourceAwsLbCreate(d *schema.ResourceData, meta interface{}) error { if subnetMap["allocation_id"].(string) != "" { elbOpts.SubnetMappings[i].AllocationId = aws.String(subnetMap["allocation_id"].(string)) } + + if subnetMap["private_ipv4_address"].(string) != "" { + elbOpts.SubnetMappings[i].PrivateIPv4Address = aws.String(subnetMap["private_ipv4_address"].(string)) + } } } @@ -689,6 +703,7 @@ func flattenSubnetMappingsFromAvailabilityZones(availabilityZones []*elbv2.Avail for _, loadBalancerAddress := range availabilityZone.LoadBalancerAddresses { m["allocation_id"] = aws.StringValue(loadBalancerAddress.AllocationId) + m["private_ipv4_address"] = aws.StringValue(loadBalancerAddress.PrivateIPv4Address) } l = append(l, m) @@ -801,7 +816,7 @@ func flattenAwsLbResource(d *schema.ResourceData, meta interface{}, lb *elbv2.Lo // Load balancers of type 'network' cannot have their subnets updated at // this time. If the type is 'network' and subnets have changed, mark the // diff as a ForceNew operation -func customizeDiffNLBSubnets(diff *schema.ResourceDiff, v interface{}) error { +func customizeDiffNLBSubnets(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { // The current criteria for determining if the operation should be ForceNew: // - lb of type "network" // - existing resource (id is not "") diff --git a/aws/resource_aws_lb_cookie_stickiness_policy.go b/aws/resource_aws_lb_cookie_stickiness_policy.go index ec1c169d863..17a4460b365 100644 --- a/aws/resource_aws_lb_cookie_stickiness_policy.go +++ b/aws/resource_aws_lb_cookie_stickiness_policy.go @@ -3,13 +3,14 @@ package aws import ( "fmt" "log" + "strconv" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsLBCookieStickinessPolicy() *schema.Resource { @@ -129,11 +130,19 @@ func resourceAwsLBCookieStickinessPolicyRead(d *schema.ResourceData, meta interf if *cookieAttr.AttributeName != "CookieExpirationPeriod" { return fmt.Errorf("Unable to find cookie expiration period.") } - d.Set("cookie_expiration_period", cookieAttr.AttributeValue) + cookieVal, err := strconv.Atoi(aws.StringValue(cookieAttr.AttributeValue)) + if err != nil { + return fmt.Errorf("Error parsing cookie expiration period: %s", err) + } + d.Set("cookie_expiration_period", cookieVal) d.Set("name", policyName) d.Set("load_balancer", lbName) - d.Set("lb_port", lbPort) + lbPortInt, err := strconv.Atoi(lbPort) + if err != nil { + return err + } + d.Set("lb_port", lbPortInt) return nil } diff --git a/aws/resource_aws_lb_cookie_stickiness_policy_test.go b/aws/resource_aws_lb_cookie_stickiness_policy_test.go index 6826dbce683..da37cfe1c47 100644 --- a/aws/resource_aws_lb_cookie_stickiness_policy_test.go +++ b/aws/resource_aws_lb_cookie_stickiness_policy_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLBCookieStickinessPolicy_basic(t *testing.T) { diff --git a/aws/resource_aws_lb_listener.go b/aws/resource_aws_lb_listener.go index 81976c0e739..8fc14d26d45 100644 --- a/aws/resource_aws_lb_listener.go +++ b/aws/resource_aws_lb_listener.go @@ -12,9 +12,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsLbListener() *schema.Resource { @@ -103,13 +103,64 @@ func resourceAwsLbListener() *schema.Resource { "target_group_arn": { Type: schema.TypeString, Optional: true, - DiffSuppressFunc: suppressIfDefaultActionTypeNot("forward"), + DiffSuppressFunc: suppressIfDefaultActionTypeNot(elbv2.ActionTypeEnumForward), + }, + + "forward": { + Type: schema.TypeList, + Optional: true, + DiffSuppressFunc: suppressIfDefaultActionTypeNot(elbv2.ActionTypeEnumForward), + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "target_group": { + Type: schema.TypeSet, + MinItems: 2, + MaxItems: 5, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Required: true, + }, + "weight": { + Type: schema.TypeInt, + ValidateFunc: validation.IntBetween(0, 999), + Default: 1, + Optional: true, + }, + }, + }, + }, + "stickiness": { + Type: schema.TypeList, + Optional: true, + DiffSuppressFunc: suppressMissingOptionalConfigurationBlock, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "duration": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, 604800), + }, + }, + }, + }, + }, + }, }, "redirect": { Type: schema.TypeList, Optional: true, - DiffSuppressFunc: suppressIfDefaultActionTypeNot("redirect"), + DiffSuppressFunc: suppressIfDefaultActionTypeNot(elbv2.ActionTypeEnumRedirect), MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -163,7 +214,7 @@ func resourceAwsLbListener() *schema.Resource { "fixed_response": { Type: schema.TypeList, Optional: true, - DiffSuppressFunc: suppressIfDefaultActionTypeNot("fixed-response"), + DiffSuppressFunc: suppressIfDefaultActionTypeNot(elbv2.ActionTypeEnumFixedResponse), MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -197,13 +248,14 @@ func resourceAwsLbListener() *schema.Resource { "authenticate_cognito": { Type: schema.TypeList, Optional: true, - DiffSuppressFunc: suppressIfDefaultActionTypeNot("authenticate-cognito"), + DiffSuppressFunc: suppressIfDefaultActionTypeNot(elbv2.ActionTypeEnumAuthenticateCognito), MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "authentication_request_extra_params": { Type: schema.TypeMap, Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "on_unauthenticated_request": { Type: schema.TypeString, @@ -249,13 +301,14 @@ func resourceAwsLbListener() *schema.Resource { "authenticate_oidc": { Type: schema.TypeList, Optional: true, - DiffSuppressFunc: suppressIfDefaultActionTypeNot("authenticate-oidc"), + DiffSuppressFunc: suppressIfDefaultActionTypeNot(elbv2.ActionTypeEnumAuthenticateOidc), MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "authentication_request_extra_params": { Type: schema.TypeMap, Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "authorization_endpoint": { Type: schema.TypeString, @@ -369,10 +422,12 @@ func resourceAwsLbListenerCreate(d *schema.ResourceData, meta interface{}) error } switch defaultActionMap["type"].(string) { - case "forward": - action.TargetGroupArn = aws.String(defaultActionMap["target_group_arn"].(string)) + case elbv2.ActionTypeEnumForward: + if err := lbListenerRuleActionForward(defaultActionMap, action); err != nil { + return err + } - case "redirect": + case elbv2.ActionTypeEnumRedirect: redirectList := defaultActionMap["redirect"].([]interface{}) if len(redirectList) == 1 { @@ -390,7 +445,7 @@ func resourceAwsLbListenerCreate(d *schema.ResourceData, meta interface{}) error return errors.New("for actions of type 'redirect', you must specify a 'redirect' block") } - case "fixed-response": + case elbv2.ActionTypeEnumFixedResponse: fixedResponseList := defaultActionMap["fixed_response"].([]interface{}) if len(fixedResponseList) == 1 { @@ -583,10 +638,33 @@ func resourceAwsLbListenerRead(d *schema.ResourceData, meta interface{}) error { defaultActionMap["order"] = aws.Int64Value(defaultAction.Order) switch aws.StringValue(defaultAction.Type) { - case "forward": - defaultActionMap["target_group_arn"] = aws.StringValue(defaultAction.TargetGroupArn) + case elbv2.ActionTypeEnumForward: + if aws.StringValue(defaultAction.TargetGroupArn) != "" { + defaultActionMap["target_group_arn"] = aws.StringValue(defaultAction.TargetGroupArn) + } else { + targetGroups := make([]map[string]interface{}, 0, len(defaultAction.ForwardConfig.TargetGroups)) + for _, targetGroup := range defaultAction.ForwardConfig.TargetGroups { + targetGroups = append(targetGroups, + map[string]interface{}{ + "arn": aws.StringValue(targetGroup.TargetGroupArn), + "weight": aws.Int64Value(targetGroup.Weight), + }, + ) + } + defaultActionMap["forward"] = []map[string]interface{}{ + { + "target_group": targetGroups, + "stickiness": []map[string]interface{}{ + { + "enabled": aws.BoolValue(defaultAction.ForwardConfig.TargetGroupStickinessConfig.Enabled), + "duration": aws.Int64Value(defaultAction.ForwardConfig.TargetGroupStickinessConfig.DurationSeconds), + }, + }, + }, + } + } - case "redirect": + case elbv2.ActionTypeEnumRedirect: defaultActionMap["redirect"] = []map[string]interface{}{ { "host": aws.StringValue(defaultAction.RedirectConfig.Host), @@ -598,7 +676,7 @@ func resourceAwsLbListenerRead(d *schema.ResourceData, meta interface{}) error { }, } - case "fixed-response": + case elbv2.ActionTypeEnumFixedResponse: defaultActionMap["fixed_response"] = []map[string]interface{}{ { "content_type": aws.StringValue(defaultAction.FixedResponseConfig.ContentType), @@ -607,7 +685,7 @@ func resourceAwsLbListenerRead(d *schema.ResourceData, meta interface{}) error { }, } - case "authenticate-cognito": + case elbv2.ActionTypeEnumAuthenticateCognito: authenticationRequestExtraParams := make(map[string]interface{}) for key, value := range defaultAction.AuthenticateCognitoConfig.AuthenticationRequestExtraParams { authenticationRequestExtraParams[key] = aws.StringValue(value) @@ -625,7 +703,7 @@ func resourceAwsLbListenerRead(d *schema.ResourceData, meta interface{}) error { }, } - case "authenticate-oidc": + case elbv2.ActionTypeEnumAuthenticateOidc: authenticationRequestExtraParams := make(map[string]interface{}) for key, value := range defaultAction.AuthenticateOidcConfig.AuthenticationRequestExtraParams { authenticationRequestExtraParams[key] = aws.StringValue(value) @@ -698,10 +776,12 @@ func resourceAwsLbListenerUpdate(d *schema.ResourceData, meta interface{}) error } switch defaultActionMap["type"].(string) { - case "forward": - action.TargetGroupArn = aws.String(defaultActionMap["target_group_arn"].(string)) + case elbv2.ActionTypeEnumForward: + if err := lbListenerRuleActionForward(defaultActionMap, action); err != nil { + return err + } - case "redirect": + case elbv2.ActionTypeEnumRedirect: redirectList := defaultActionMap["redirect"].([]interface{}) if len(redirectList) == 1 { @@ -719,7 +799,7 @@ func resourceAwsLbListenerUpdate(d *schema.ResourceData, meta interface{}) error return errors.New("for actions of type 'redirect', you must specify a 'redirect' block") } - case "fixed-response": + case elbv2.ActionTypeEnumFixedResponse: fixedResponseList := defaultActionMap["fixed_response"].([]interface{}) if len(fixedResponseList) == 1 { @@ -734,7 +814,7 @@ func resourceAwsLbListenerUpdate(d *schema.ResourceData, meta interface{}) error return errors.New("for actions of type 'fixed-response', you must specify a 'fixed_response' block") } - case "authenticate-cognito": + case elbv2.ActionTypeEnumAuthenticateCognito: authenticateCognitoList := defaultActionMap["authenticate_cognito"].([]interface{}) if len(authenticateCognitoList) == 1 { @@ -768,7 +848,7 @@ func resourceAwsLbListenerUpdate(d *schema.ResourceData, meta interface{}) error return errors.New("for actions of type 'authenticate-cognito', you must specify a 'authenticate_cognito' block") } - case "authenticate-oidc": + case elbv2.ActionTypeEnumAuthenticateOidc: authenticateOidcList := defaultActionMap["authenticate_oidc"].([]interface{}) if len(authenticateOidcList) == 1 { diff --git a/aws/resource_aws_lb_listener_certificate.go b/aws/resource_aws_lb_listener_certificate.go index 5683b643da2..bb567f85e08 100644 --- a/aws/resource_aws_lb_listener_certificate.go +++ b/aws/resource_aws_lb_listener_certificate.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsLbListenerCertificate() *schema.Resource { diff --git a/aws/resource_aws_lb_listener_certificate_test.go b/aws/resource_aws_lb_listener_certificate_test.go index 90473f16098..7f9fd6ffbd3 100644 --- a/aws/resource_aws_lb_listener_certificate_test.go +++ b/aws/resource_aws_lb_listener_certificate_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAwsLbListenerCertificate_basic(t *testing.T) { @@ -225,12 +225,12 @@ resource "aws_lb_listener" "test" { } func testAccLbListenerCertificateConfig(rName, key, certificate string) string { - return testAccLbListenerCertificateConfigLbListenerBase(rName, key, certificate) + fmt.Sprintf(` + return testAccLbListenerCertificateConfigLbListenerBase(rName, key, certificate) + ` resource "aws_lb_listener_certificate" "test" { certificate_arn = "${aws_iam_server_certificate.test.arn}" listener_arn = "${aws_lb_listener.test.arn}" } -`) +` } func testAccLbListenerCertificateConfigMultiple(rName string, keys, certificates []string) string { diff --git a/aws/resource_aws_lb_listener_rule.go b/aws/resource_aws_lb_listener_rule.go index ab72c11dc20..893b16aa3b8 100644 --- a/aws/resource_aws_lb_listener_rule.go +++ b/aws/resource_aws_lb_listener_rule.go @@ -12,10 +12,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsLbbListenerRule() *schema.Resource { @@ -71,13 +70,64 @@ func resourceAwsLbbListenerRule() *schema.Resource { "target_group_arn": { Type: schema.TypeString, Optional: true, - DiffSuppressFunc: suppressIfActionTypeNot("forward"), + DiffSuppressFunc: suppressIfActionTypeNot(elbv2.ActionTypeEnumForward), + }, + + "forward": { + Type: schema.TypeList, + Optional: true, + DiffSuppressFunc: suppressIfActionTypeNot(elbv2.ActionTypeEnumForward), + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "target_group": { + Type: schema.TypeSet, + MinItems: 2, + MaxItems: 5, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Required: true, + }, + "weight": { + Type: schema.TypeInt, + ValidateFunc: validation.IntBetween(0, 999), + Default: 1, + Optional: true, + }, + }, + }, + }, + "stickiness": { + Type: schema.TypeList, + Optional: true, + DiffSuppressFunc: suppressMissingOptionalConfigurationBlock, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "enabled": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "duration": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, 604800), + }, + }, + }, + }, + }, + }, }, "redirect": { Type: schema.TypeList, Optional: true, - DiffSuppressFunc: suppressIfActionTypeNot("redirect"), + DiffSuppressFunc: suppressIfActionTypeNot(elbv2.ActionTypeEnumRedirect), MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -131,7 +181,7 @@ func resourceAwsLbbListenerRule() *schema.Resource { "fixed_response": { Type: schema.TypeList, Optional: true, - DiffSuppressFunc: suppressIfActionTypeNot("fixed-response"), + DiffSuppressFunc: suppressIfActionTypeNot(elbv2.ActionTypeEnumFixedResponse), MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -172,6 +222,7 @@ func resourceAwsLbbListenerRule() *schema.Resource { "authentication_request_extra_params": { Type: schema.TypeMap, Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "on_unauthenticated_request": { Type: schema.TypeString, @@ -224,6 +275,7 @@ func resourceAwsLbbListenerRule() *schema.Resource { "authentication_request_extra_params": { Type: schema.TypeMap, Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "authorization_endpoint": { Type: schema.TypeString, @@ -284,31 +336,18 @@ func resourceAwsLbbListenerRule() *schema.Resource { "condition": { Type: schema.TypeSet, Required: true, - Set: lbListenerRuleConditionSetHash, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "field": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ValidateFunc: validation.StringInSlice([]string{ - "host-header", - "path-pattern", - }, true), - Deprecated: "use 'host_header' or 'path_pattern' attribute instead", - }, "host_header": { Type: schema.TypeList, MaxItems: 1, Optional: true, - Computed: true, // Deprecated: remove Computed Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "values": { - Type: schema.TypeSet, - // Deprecated: Change Optional & Computed to Required in next major version of the provider - Optional: true, - Computed: true, + Type: schema.TypeSet, + Required: true, + MinItems: 1, Elem: &schema.Schema{ Type: schema.TypeString, ValidateFunc: validation.StringLenBetween(1, 128), @@ -363,14 +402,12 @@ func resourceAwsLbbListenerRule() *schema.Resource { Type: schema.TypeList, MaxItems: 1, Optional: true, - Computed: true, // Deprecated: remove Computed Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "values": { - Type: schema.TypeSet, - // Deprecated: Change Optional & Computed to Required in next major version of the provider - Optional: true, - Computed: true, + Type: schema.TypeSet, + Required: true, + MinItems: 1, Elem: &schema.Schema{ Type: schema.TypeString, ValidateFunc: validation.StringLenBetween(1, 128), @@ -395,7 +432,6 @@ func resourceAwsLbbListenerRule() *schema.Resource { }, }, }, - Set: lbListenerRuleConditionQueryStringHash, }, "source_ip": { Type: schema.TypeList, @@ -415,17 +451,6 @@ func resourceAwsLbbListenerRule() *schema.Resource { }, }, }, - "values": { - Type: schema.TypeList, - MaxItems: 1, - Elem: &schema.Schema{ - Type: schema.TypeString, - ValidateFunc: validation.StringLenBetween(1, 128), - }, - Optional: true, - Computed: true, - Deprecated: "use 'host_header' or 'path_pattern' attribute instead", - }, }, }, }, @@ -433,92 +458,6 @@ func resourceAwsLbbListenerRule() *schema.Resource { } } -/* DEPRECATED Backwards compatibility: This primarily exists to set a hash that handles the values to host_header or path_pattern migration. -Can probably be removed on the next major version of the provider. -*/ -func lbListenerRuleConditionSetHash(v interface{}) int { - if v == nil { - return 0 - } - - var field string - var buf strings.Builder - - m := v.(map[string]interface{}) - - if hostHeader, ok := m["host_header"].([]interface{}); ok && len(hostHeader) > 0 { - if hostHeader[0] != nil { - field = "host-header" - values := hostHeader[0].(map[string]interface{})["values"].(*schema.Set) - for _, l := range values.List() { - fmt.Fprint(&buf, l, "-") - } - } - } else if m["field"].(string) == "host-header" { - // Backwards compatibility - field = "host-header" - for _, l := range m["values"].([]interface{}) { - fmt.Fprint(&buf, l, "-") - } - } - - if httpHeader, ok := m["http_header"].([]interface{}); ok && len(httpHeader) > 0 && httpHeader[0] != nil { - field = "http-header" - httpHeaderMap := httpHeader[0].(map[string]interface{}) - fmt.Fprint(&buf, httpHeaderMap["http_header_name"].(string), ":") - httpHeaderValues := httpHeaderMap["values"].(*schema.Set) - for _, l := range httpHeaderValues.List() { - fmt.Fprint(&buf, l, "-") - } - } - - if httpRequestMethod, ok := m["http_request_method"].([]interface{}); ok && len(httpRequestMethod) > 0 && httpRequestMethod[0] != nil { - field = "http-request-method" - values := httpRequestMethod[0].(map[string]interface{})["values"].(*schema.Set) - for _, l := range values.List() { - fmt.Fprint(&buf, l, "-") - } - } - - if pathPattern, ok := m["path_pattern"].([]interface{}); ok && len(pathPattern) > 0 { - if pathPattern[0] != nil { - field = "path-pattern" - values := pathPattern[0].(map[string]interface{})["values"].(*schema.Set) - for _, l := range values.List() { - fmt.Fprint(&buf, l, "-") - } - } - } else if m["field"].(string) == "path-pattern" { - // Backwards compatibility - field = "path-pattern" - for _, l := range m["values"].([]interface{}) { - fmt.Fprint(&buf, l, "-") - } - } - - if queryString, ok := m["query_string"].(*schema.Set); ok && queryString.Len() > 0 { - field = "query-string" - for _, l := range queryString.List() { - fmt.Fprint(&buf, lbListenerRuleConditionQueryStringHash(l), "-") - } - } - - if sourceIp, ok := m["source_ip"].([]interface{}); ok && len(sourceIp) > 0 && sourceIp[0] != nil { - field = "source-ip" - values := sourceIp[0].(map[string]interface{})["values"].(*schema.Set) - for _, l := range values.List() { - fmt.Fprint(&buf, l, "-") - } - } - - return hashcode.String(fmt.Sprintf("%s-%s", field, buf.String())) -} - -func lbListenerRuleConditionQueryStringHash(v interface{}) int { - m := v.(map[string]interface{}) - return hashcode.String(fmt.Sprintf("%s-%s", m["key"], m["value"])) -} - func suppressIfActionTypeNot(t string) schema.SchemaDiffSuppressFunc { return func(k, old, new string, d *schema.ResourceData) bool { take := 2 @@ -557,10 +496,12 @@ func resourceAwsLbListenerRuleCreate(d *schema.ResourceData, meta interface{}) e } switch actionMap["type"].(string) { - case "forward": - action.TargetGroupArn = aws.String(actionMap["target_group_arn"].(string)) + case elbv2.ActionTypeEnumForward: + if err := lbListenerRuleActionForward(actionMap, action); err != nil { + return err + } - case "redirect": + case elbv2.ActionTypeEnumRedirect: redirectList := actionMap["redirect"].([]interface{}) if len(redirectList) == 1 { @@ -578,7 +519,7 @@ func resourceAwsLbListenerRuleCreate(d *schema.ResourceData, meta interface{}) e return errors.New("for actions of type 'redirect', you must specify a 'redirect' block") } - case "fixed-response": + case elbv2.ActionTypeEnumFixedResponse: fixedResponseList := actionMap["fixed_response"].([]interface{}) if len(fixedResponseList) == 1 { @@ -593,7 +534,7 @@ func resourceAwsLbListenerRuleCreate(d *schema.ResourceData, meta interface{}) e return errors.New("for actions of type 'fixed-response', you must specify a 'fixed_response' block") } - case "authenticate-cognito": + case elbv2.ActionTypeEnumAuthenticateCognito: authenticateCognitoList := actionMap["authenticate_cognito"].([]interface{}) if len(authenticateCognitoList) == 1 { @@ -627,7 +568,7 @@ func resourceAwsLbListenerRuleCreate(d *schema.ResourceData, meta interface{}) e return errors.New("for actions of type 'authenticate-cognito', you must specify a 'authenticate_cognito' block") } - case "authenticate-oidc": + case elbv2.ActionTypeEnumAuthenticateOidc: authenticateOidcList := actionMap["authenticate_oidc"].([]interface{}) if len(authenticateOidcList) == 1 { @@ -786,10 +727,33 @@ func resourceAwsLbListenerRuleRead(d *schema.ResourceData, meta interface{}) err actionMap["order"] = aws.Int64Value(action.Order) switch actionMap["type"] { - case "forward": - actionMap["target_group_arn"] = aws.StringValue(action.TargetGroupArn) + case elbv2.ActionTypeEnumForward: + if aws.StringValue(action.TargetGroupArn) != "" { + actionMap["target_group_arn"] = aws.StringValue(action.TargetGroupArn) + } else { + targetGroups := make([]map[string]interface{}, 0, len(action.ForwardConfig.TargetGroups)) + for _, targetGroup := range action.ForwardConfig.TargetGroups { + targetGroups = append(targetGroups, + map[string]interface{}{ + "arn": aws.StringValue(targetGroup.TargetGroupArn), + "weight": aws.Int64Value(targetGroup.Weight), + }, + ) + } + actionMap["forward"] = []map[string]interface{}{ + { + "target_group": targetGroups, + "stickiness": []map[string]interface{}{ + { + "enabled": aws.BoolValue(action.ForwardConfig.TargetGroupStickinessConfig.Enabled), + "duration": aws.Int64Value(action.ForwardConfig.TargetGroupStickinessConfig.DurationSeconds), + }, + }, + }, + } + } - case "redirect": + case elbv2.ActionTypeEnumRedirect: actionMap["redirect"] = []map[string]interface{}{ { "host": aws.StringValue(action.RedirectConfig.Host), @@ -801,7 +765,7 @@ func resourceAwsLbListenerRuleRead(d *schema.ResourceData, meta interface{}) err }, } - case "fixed-response": + case elbv2.ActionTypeEnumFixedResponse: actionMap["fixed_response"] = []map[string]interface{}{ { "content_type": aws.StringValue(action.FixedResponseConfig.ContentType), @@ -810,7 +774,7 @@ func resourceAwsLbListenerRuleRead(d *schema.ResourceData, meta interface{}) err }, } - case "authenticate-cognito": + case elbv2.ActionTypeEnumAuthenticateCognito: authenticationRequestExtraParams := make(map[string]interface{}) for key, value := range action.AuthenticateCognitoConfig.AuthenticationRequestExtraParams { authenticationRequestExtraParams[key] = aws.StringValue(value) @@ -829,7 +793,7 @@ func resourceAwsLbListenerRuleRead(d *schema.ResourceData, meta interface{}) err }, } - case "authenticate-oidc": + case elbv2.ActionTypeEnumAuthenticateOidc: authenticationRequestExtraParams := make(map[string]interface{}) for key, value := range action.AuthenticateOidcConfig.AuthenticationRequestExtraParams { authenticationRequestExtraParams[key] = aws.StringValue(value) @@ -864,11 +828,7 @@ func resourceAwsLbListenerRuleRead(d *schema.ResourceData, meta interface{}) err for i, condition := range rule.Conditions { conditionMap := make(map[string]interface{}) - // Deprecated: remove in next major version of provider - conditionMap["field"] = aws.StringValue(condition.Field) - conditionMap["values"] = aws.StringValueSlice(condition.Values) - - switch conditionMap["field"] { + switch aws.StringValue(condition.Field) { case "host-header": conditionMap["host_header"] = []interface{}{ map[string]interface{}{ @@ -906,7 +866,7 @@ func resourceAwsLbListenerRuleRead(d *schema.ResourceData, meta interface{}) err "value": aws.StringValue(value.Value), } } - conditionMap["query_string"] = schema.NewSet(lbListenerRuleConditionQueryStringHash, values) + conditionMap["query_string"] = values case "source-ip": conditionMap["source_ip"] = []interface{}{ @@ -965,10 +925,12 @@ func resourceAwsLbListenerRuleUpdate(d *schema.ResourceData, meta interface{}) e } switch actionMap["type"].(string) { - case "forward": - action.TargetGroupArn = aws.String(actionMap["target_group_arn"].(string)) + case elbv2.ActionTypeEnumForward: + if err := lbListenerRuleActionForward(actionMap, action); err != nil { + return err + } - case "redirect": + case elbv2.ActionTypeEnumRedirect: redirectList := actionMap["redirect"].([]interface{}) if len(redirectList) == 1 { @@ -986,7 +948,7 @@ func resourceAwsLbListenerRuleUpdate(d *schema.ResourceData, meta interface{}) e return errors.New("for actions of type 'redirect', you must specify a 'redirect' block") } - case "fixed-response": + case elbv2.ActionTypeEnumFixedResponse: fixedResponseList := actionMap["fixed_response"].([]interface{}) if len(fixedResponseList) == 1 { @@ -1001,7 +963,7 @@ func resourceAwsLbListenerRuleUpdate(d *schema.ResourceData, meta interface{}) e return errors.New("for actions of type 'fixed-response', you must specify a 'fixed_response' block") } - case "authenticate-cognito": + case elbv2.ActionTypeEnumAuthenticateCognito: authenticateCognitoList := actionMap["authenticate_cognito"].([]interface{}) if len(authenticateCognitoList) == 1 { @@ -1035,7 +997,7 @@ func resourceAwsLbListenerRuleUpdate(d *schema.ResourceData, meta interface{}) e return errors.New("for actions of type 'authenticate-cognito', you must specify a 'authenticate_cognito' block") } - case "authenticate-oidc": + case elbv2.ActionTypeEnumAuthenticateOidc: authenticateOidcList := actionMap["authenticate_oidc"].([]interface{}) if len(authenticateOidcList) == 1 { @@ -1255,44 +1217,53 @@ func lbListenerRuleConditions(conditions []interface{}) ([]*elbv2.RuleCondition, } } - // Deprecated backwards compatibility - // This code is also hit during an update when the condition has not been modified. Issues: GH-11232 and GH-11362 - if cmField, ok := conditionMap["field"].(string); ok && (cmField == "host-header" || cmField == "path-pattern") { - // When the condition is not being updated Terraform feeds in the existing state which has host header and - // path pattern set in both locations with identical values. - if field == cmField { - values := schema.NewSet(schema.HashString, conditionMap["values"].([]interface{})) - var values2 *schema.Set - if cmField == "host-header" { - values2 = conditionMap["host_header"].([]interface{})[0].(map[string]interface{})["values"].(*schema.Set) - } else { - values2 = conditionMap["path_pattern"].([]interface{})[0].(map[string]interface{})["values"].(*schema.Set) - } - if !values2.Equal(values) { - attrs += 1 - } - } else { - field = cmField - attrs += 1 - values := conditionMap["values"].([]interface{}) - if len(values) == 0 { - return nil, errors.New("Both field and values must be set in a condition block") - } - elbConditions[i].Values = expandStringList(values) - } - } - // FIXME Rework this and use ConflictsWith when it finally works with collections: // https://github.com/hashicorp/terraform/issues/13016 // Still need to ensure that one of the condition attributes is set. if attrs == 0 { return nil, errors.New("One of host_header, http_header, http_request_method, path_pattern, query_string or source_ip must be set in a condition block") } else if attrs > 1 { - // Deprecated: remove `field` from message - return nil, errors.New("Only one of field, host_header, http_header, http_request_method, path_pattern, query_string or source_ip can be set in a condition block") + return nil, errors.New("Only one of host_header, http_header, http_request_method, path_pattern, query_string or source_ip can be set in a condition block") } elbConditions[i].Field = aws.String(field) } return elbConditions, nil } + +func lbListenerRuleActionForward(actionMap map[string]interface{}, action *elbv2.Action) error { + forwardList := actionMap["forward"].([]interface{}) + targetGroupArn := actionMap["target_group_arn"].(string) + + if targetGroupArn != "" { + action.TargetGroupArn = aws.String(targetGroupArn) + } else if len(forwardList) == 1 { + forwardMap := forwardList[0].(map[string]interface{}) + targetGroupsInput := forwardMap["target_group"].(*schema.Set).List() + weightedTargetGroups := make([]*elbv2.TargetGroupTuple, len(targetGroupsInput)) + + for i, input := range targetGroupsInput { + weightedTargetGroup := input.(map[string]interface{}) + weightedTargetGroups[i] = &elbv2.TargetGroupTuple{ + TargetGroupArn: aws.String(weightedTargetGroup["arn"].(string)), + Weight: aws.Int64(int64(weightedTargetGroup["weight"].(int))), + } + } + + action.ForwardConfig = &elbv2.ForwardActionConfig{ + TargetGroups: weightedTargetGroups, + } + + stickinessInput := forwardMap["stickiness"].([]interface{}) + if len(stickinessInput) != 0 { + stickyInputMap := stickinessInput[0].(map[string]interface{}) + action.ForwardConfig.TargetGroupStickinessConfig = &elbv2.TargetGroupStickinessConfig{ + Enabled: aws.Bool(stickyInputMap["enabled"].(bool)), + DurationSeconds: aws.Int64(int64(stickyInputMap["duration"].(int))), + } + } + } else { + return errors.New("for actions of type 'forward', you must specify a 'forward' block or 'target_group_arn'") + } + return nil +} diff --git a/aws/resource_aws_lb_listener_rule_test.go b/aws/resource_aws_lb_listener_rule_test.go index 6c46befc047..b23d57759ee 100644 --- a/aws/resource_aws_lb_listener_rule_test.go +++ b/aws/resource_aws_lb_listener_rule_test.go @@ -8,9 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestLBListenerARNFromRuleARN(t *testing.T) { @@ -56,84 +57,169 @@ func TestLBListenerARNFromRuleARN(t *testing.T) { func TestAccAWSLBListenerRule_basic(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) - targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandString(13)) + targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandString(10)) + + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" + targetGroupResourceName := "aws_lb_target_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_basic(lbName, targetGroupName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.order", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.type", "forward"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "action.0.target_group_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.redirect.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.fixed_response.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.authenticate_cognito.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.authenticate_oidc.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.447032695.field", "path-pattern"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.447032695.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.447032695.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.447032695.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.447032695.path_pattern.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.447032695.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.447032695.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.447032695.values.#", "1"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "condition.447032695.values.0"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.type", "forward"), + resource.TestCheckResourceAttrPair(resourceName, "action.0.target_group_arn", targetGroupResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_cognito.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.#", "0"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "0", + "http_request_method.#": "0", + "path_pattern.#": "1", + "path_pattern.0.values.#": "1", + "query_string.#": "0", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.path_pattern.0.values.*", "/static/*"), + ), + }, + }, + }) +} + +func TestAccAWSLBListenerRule_forwardWeighted(t *testing.T) { + var conf elbv2.Rule + lbName := fmt.Sprintf("testrule-weighted-%s", acctest.RandString(13)) + targetGroupName1 := fmt.Sprintf("testtargetgroup-%s", acctest.RandString(10)) + targetGroupName2 := fmt.Sprintf("testtargetgroup-%s", acctest.RandString(10)) + + resourceName := "aws_lb_listener_rule.weighted" + frontEndListenerResourceName := "aws_lb_listener.front_end" + targetGroup1ResourceName := "aws_lb_target_group.test1" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLBListenerRuleConfig_forwardWeighted(lbName, targetGroupName1, targetGroupName2), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.type", "forward"), + resource.TestCheckResourceAttr(resourceName, "action.0.forward.#", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.forward.0.target_group.#", "2"), + resource.TestCheckResourceAttr(resourceName, "action.0.forward.0.stickiness.0.enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "action.0.forward.0.stickiness.0.duration", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_cognito.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.#", "0"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), + ), + }, + { + Config: testAccAWSLBListenerRuleConfig_changeForwardWeightedStickiness(lbName, targetGroupName1, targetGroupName2), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.type", "forward"), + resource.TestCheckResourceAttr(resourceName, "action.0.forward.#", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.forward.0.target_group.#", "2"), + resource.TestCheckResourceAttr(resourceName, "action.0.forward.0.stickiness.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "action.0.forward.0.stickiness.0.duration", "3600"), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_cognito.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.#", "0"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), + ), + }, + { + Config: testAccAWSLBListenerRuleConfig_changeForwardWeightedToBasic(lbName, targetGroupName1, targetGroupName2), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.type", "forward"), + resource.TestCheckResourceAttrPair(resourceName, "action.0.target_group_arn", targetGroup1ResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_cognito.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.#", "0"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), ), }, }, }) } -func TestAccAWSLBListenerRuleBackwardsCompatibility(t *testing.T) { +func TestAccAWSLBListenerRule_BackwardsCompatibility(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) - targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandString(13)) + targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandString(10)) + + resourceName := "aws_alb_listener_rule.static" + frontEndListenerResourceName := "aws_alb_listener.front_end" + targetGroupResourceName := "aws_alb_target_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_alb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfigBackwardsCompatibility(lbName, targetGroupName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_alb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_alb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_alb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "action.0.order", "1"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "action.0.type", "forward"), - resource.TestCheckResourceAttrSet("aws_alb_listener_rule.static", "action.0.target_group_arn"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "action.0.redirect.#", "0"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "action.0.fixed_response.#", "0"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "action.0.authenticate_cognito.#", "0"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "action.0.authenticate_oidc.#", "0"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.#", "1"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.447032695.field", "path-pattern"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.447032695.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.447032695.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.447032695.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.447032695.path_pattern.#", "1"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.447032695.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.447032695.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_alb_listener_rule.static", "condition.447032695.values.#", "1"), - resource.TestCheckResourceAttrSet("aws_alb_listener_rule.static", "condition.447032695.values.0"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.type", "forward"), + resource.TestCheckResourceAttrPair(resourceName, "action.0.target_group_arn", targetGroupResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_cognito.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.#", "0"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "0", + "http_request_method.#": "0", + "path_pattern.#": "1", + "path_pattern.0.values.#": "1", + "query_string.#": "0", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.path_pattern.0.values.*", "/static/*"), ), }, }, @@ -142,36 +228,38 @@ func TestAccAWSLBListenerRuleBackwardsCompatibility(t *testing.T) { func TestAccAWSLBListenerRule_redirect(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-redirect-%s", acctest.RandStringFromCharSet(14, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-redirect-%s", acctest.RandString(14)) + + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_redirect(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.order", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.type", "redirect"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.target_group_arn", ""), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.redirect.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.redirect.0.host", "#{host}"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.redirect.0.path", "/#{path}"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.redirect.0.port", "443"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.redirect.0.protocol", "HTTPS"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.redirect.0.query", "#{query}"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.redirect.0.status_code", "HTTP_301"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.fixed_response.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.authenticate_cognito.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.authenticate_oidc.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "1"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.type", "redirect"), + resource.TestCheckResourceAttr(resourceName, "action.0.target_group_arn", ""), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.#", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.0.host", "#{host}"), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.0.path", "/#{path}"), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.0.port", "443"), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.0.protocol", "HTTPS"), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.0.query", "#{query}"), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.0.status_code", "HTTP_301"), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_cognito.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.#", "0"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), ), }, }, @@ -180,33 +268,35 @@ func TestAccAWSLBListenerRule_redirect(t *testing.T) { func TestAccAWSLBListenerRule_fixedResponse(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-fixedresponse-%s", acctest.RandStringFromCharSet(9, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-fixedresponse-%s", acctest.RandString(9)) + + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_fixedResponse(lbName, "Fixed response content"), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.order", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.type", "fixed-response"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.target_group_arn", ""), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.redirect.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.fixed_response.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.fixed_response.0.content_type", "text/plain"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.fixed_response.0.message_body", "Fixed response content"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.fixed_response.0.status_code", "200"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.authenticate_cognito.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.authenticate_oidc.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "1"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.type", "fixed-response"), + resource.TestCheckResourceAttr(resourceName, "action.0.target_group_arn", ""), + resource.TestCheckResourceAttr(resourceName, "action.0.redirect.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.#", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.0.content_type", "text/plain"), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.0.message_body", "Fixed response content"), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.0.status_code", "200"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_cognito.#", "0"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.#", "0"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), ), }, }, @@ -216,26 +306,27 @@ func TestAccAWSLBListenerRule_fixedResponse(t *testing.T) { // Updating Action breaks Condition change logic GH-11323 and GH-11362 func TestAccAWSLBListenerRule_updateFixedResponse(t *testing.T) { var rule elbv2.Rule - lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandString(13)) + + resourceName := "aws_lb_listener_rule.static" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_fixedResponse(lbName, "Fixed Response 1"), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &rule), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.fixed_response.0.message_body", "Fixed Response 1"), + testAccCheckAWSLBListenerRuleExists(resourceName, &rule), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.0.message_body", "Fixed Response 1"), ), }, { Config: testAccAWSLBListenerRuleConfig_fixedResponse(lbName, "Fixed Response 2"), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &rule), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.0.fixed_response.0.message_body", "Fixed Response 2"), + testAccCheckAWSLBListenerRuleExists(resourceName, &rule), + resource.TestCheckResourceAttr(resourceName, "action.0.fixed_response.0.message_body", "Fixed Response 2"), ), }, }, @@ -244,27 +335,28 @@ func TestAccAWSLBListenerRule_updateFixedResponse(t *testing.T) { func TestAccAWSLBListenerRule_updateRulePriority(t *testing.T) { var rule elbv2.Rule - lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) - targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandString(13)) + targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandString(10)) + + resourceName := "aws_lb_listener_rule.static" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_basic(lbName, targetGroupName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &rule), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), + testAccCheckAWSLBListenerRuleExists(resourceName, &rule), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), ), }, { Config: testAccAWSLBListenerRuleConfig_updateRulePriority(lbName, targetGroupName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &rule), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "101"), + testAccCheckAWSLBListenerRuleExists(resourceName, &rule), + resource.TestCheckResourceAttr(resourceName, "priority", "101"), ), }, }, @@ -273,25 +365,26 @@ func TestAccAWSLBListenerRule_updateRulePriority(t *testing.T) { func TestAccAWSLBListenerRule_changeListenerRuleArnForcesNew(t *testing.T) { var before, after elbv2.Rule - lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) - targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandString(13)) + targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandString(10)) + + resourceName := "aws_lb_listener_rule.static" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_basic(lbName, targetGroupName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &before), + testAccCheckAWSLBListenerRuleExists(resourceName, &before), ), }, { Config: testAccAWSLBListenerRuleConfig_changeRuleArn(lbName, targetGroupName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &after), + testAccCheckAWSLBListenerRuleExists(resourceName, &after), testAccCheckAWSLbListenerRuleRecreated(t, &before, &after), ), }, @@ -299,33 +392,15 @@ func TestAccAWSLBListenerRule_changeListenerRuleArnForcesNew(t *testing.T) { }) } -func TestAccAWSLBListenerRule_multipleConditionThrowsError(t *testing.T) { - lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) - targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) +func TestAccAWSLBListenerRule_priority(t *testing.T) { + var rule elbv2.Rule + lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandString(13)) + targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandString(10)) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSLBListenerRuleConfig_multipleConditions(lbName, targetGroupName), - ExpectError: regexp.MustCompile(`attribute supports 1 item maximum`), - }, - }, - }) -} - -func TestAccAWSLBListenerRule_priority(t *testing.T) { - var rule elbv2.Rule - lbName := fmt.Sprintf("testrule-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) - targetGroupName := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.first", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_priorityFirst(lbName, targetGroupName), @@ -394,33 +469,39 @@ func TestAccAWSLBListenerRule_cognito(t *testing.T) { var conf elbv2.Rule key := tlsRsaPrivateKeyPem(2048) certificate := tlsRsaX509SelfSignedCertificatePem(key, "example.com") - rName := acctest.RandomWithPrefix("tf-acc-test") + lbName := acctest.RandomWithPrefix("tf-acc-test") + + resourceName := "aws_lb_listener_rule.cognito" + frontEndListenerResourceName := "aws_lb_listener.front_end" + targetGroupResourceName := "aws_lb_target_group.test" + cognitoPoolResourceName := "aws_cognito_user_pool.test" + cognitoPoolClientResourceName := "aws_cognito_user_pool_client.test" + cognitoPoolDomainResourceName := "aws_cognito_user_pool_domain.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.cognito", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLBListenerRuleConfig_cognito(rName, key, certificate), + Config: testAccAWSLBListenerRuleConfig_cognito(lbName, key, certificate), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.cognito", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.cognito", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.cognito", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.cognito", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.cognito", "action.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.cognito", "action.0.order", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.cognito", "action.0.type", "authenticate-cognito"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.cognito", "action.0.authenticate_cognito.0.user_pool_arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.cognito", "action.0.authenticate_cognito.0.user_pool_client_id"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.cognito", "action.0.authenticate_cognito.0.user_pool_domain"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.cognito", "action.0.authenticate_cognito.0.authentication_request_extra_params.%", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.cognito", "action.0.authenticate_cognito.0.authentication_request_extra_params.param", "test"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.cognito", "action.1.order", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.cognito", "action.1.type", "forward"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.cognito", "action.1.target_group_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.cognito", "condition.#", "1"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "2"), + resource.TestCheckResourceAttr(resourceName, "action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.type", "authenticate-cognito"), + resource.TestCheckResourceAttrPair(resourceName, "action.0.authenticate_cognito.0.user_pool_arn", cognitoPoolResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "action.0.authenticate_cognito.0.user_pool_client_id", cognitoPoolClientResourceName, "id"), + resource.TestCheckResourceAttrPair(resourceName, "action.0.authenticate_cognito.0.user_pool_domain", cognitoPoolDomainResourceName, "domain"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_cognito.0.authentication_request_extra_params.%", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_cognito.0.authentication_request_extra_params.param", "test"), + resource.TestCheckResourceAttr(resourceName, "action.1.order", "2"), + resource.TestCheckResourceAttr(resourceName, "action.1.type", "forward"), + resource.TestCheckResourceAttrPair(resourceName, "action.1.target_group_arn", targetGroupResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), ), }, }, @@ -431,36 +512,39 @@ func TestAccAWSLBListenerRule_oidc(t *testing.T) { var conf elbv2.Rule key := tlsRsaPrivateKeyPem(2048) certificate := tlsRsaX509SelfSignedCertificatePem(key, "example.com") - rName := acctest.RandomWithPrefix("tf-acc-test") + lbName := acctest.RandomWithPrefix("tf-acc-test") + + resourceName := "aws_lb_listener_rule.oidc" + frontEndListenerResourceName := "aws_lb_listener.front_end" + targetGroupResourceName := "aws_lb_target_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.oidc", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLBListenerRuleConfig_oidc(rName, key, certificate), + Config: testAccAWSLBListenerRuleConfig_oidc(lbName, key, certificate), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.oidc", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.oidc", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.oidc", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.0.order", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.0.type", "authenticate-oidc"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.0.authenticate_oidc.0.authorization_endpoint", "https://example.com/authorization_endpoint"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.0.authenticate_oidc.0.client_id", "s6BhdRkqt3"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.0.authenticate_oidc.0.client_secret", "7Fjfp0ZBr1KtDRbnfVdmIw"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.0.authenticate_oidc.0.issuer", "https://example.com"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.0.authenticate_oidc.0.token_endpoint", "https://example.com/token_endpoint"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.0.authenticate_oidc.0.user_info_endpoint", "https://example.com/user_info_endpoint"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.0.authenticate_oidc.0.authentication_request_extra_params.%", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.0.authenticate_oidc.0.authentication_request_extra_params.param", "test"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.1.order", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "action.1.type", "forward"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.oidc", "action.1.target_group_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.oidc", "condition.#", "1"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "2"), + resource.TestCheckResourceAttr(resourceName, "action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.type", "authenticate-oidc"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.0.authorization_endpoint", "https://example.com/authorization_endpoint"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.0.client_id", "s6BhdRkqt3"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.0.client_secret", "7Fjfp0ZBr1KtDRbnfVdmIw"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.0.issuer", "https://example.com"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.0.token_endpoint", "https://example.com/token_endpoint"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.0.user_info_endpoint", "https://example.com/user_info_endpoint"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.0.authentication_request_extra_params.%", "1"), + resource.TestCheckResourceAttr(resourceName, "action.0.authenticate_oidc.0.authentication_request_extra_params.param", "test"), + resource.TestCheckResourceAttr(resourceName, "action.1.order", "2"), + resource.TestCheckResourceAttr(resourceName, "action.1.type", "forward"), + resource.TestCheckResourceAttrPair(resourceName, "action.1.target_group_arn", targetGroupResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), ), }, }, @@ -521,27 +605,13 @@ func TestAccAWSLBListenerRule_Action_Order_Recreates(t *testing.T) { } func TestAccAWSLBListenerRule_conditionAttributesCount(t *testing.T) { - err_zero := regexp.MustCompile("One of host_header, http_header, http_request_method, path_pattern, query_string or source_ip must be set in a condition block") - err_many := regexp.MustCompile("Only one of field, host_header, http_header, http_request_method, path_pattern, query_string or source_ip can be set in a condition block") - err_deprecated := regexp.MustCompile("Both field and values must be set in a condition block") + err_many := regexp.MustCompile("Only one of host_header, http_header, http_request_method, path_pattern, query_string or source_ip can be set in a condition block") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ - { - Config: testAccAWSLBListenerRuleConfig_conditionAttributesCount_empty(), - ExpectError: err_zero, - }, - { - Config: testAccAWSLBListenerRuleConfig_conditionAttributesCount_field(), - ExpectError: err_deprecated, - }, - { - Config: testAccAWSLBListenerRuleConfig_conditionAttributesCount_values(), - ExpectError: err_zero, - }, { Config: testAccAWSLBListenerRuleConfig_conditionAttributesCount_http_header(), ExpectError: err_many, @@ -562,84 +632,42 @@ func TestAccAWSLBListenerRule_conditionAttributesCount(t *testing.T) { Config: testAccAWSLBListenerRuleConfig_conditionAttributesCount_source_ip(), ExpectError: err_many, }, - { - Config: testAccAWSLBListenerRuleConfig_conditionAttributesCount_classic(), - ExpectError: err_many, - }, }, }) } func TestAccAWSLBListenerRule_conditionHostHeader(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-hostHeader-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, - Steps: []resource.TestStep{ - { - Config: testAccAWSLBListenerRuleConfig_conditionHostHeader(lbName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.field", "host-header"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.host_header.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.host_header.0.values.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.host_header.0.values.3069857465", "example.com"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.host_header.0.values.785793723", "www.example.com"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.values.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.values.0", "example.com"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1089289132.values.1", "www.example.com"), - ), - }, - }, - }) -} + lbName := fmt.Sprintf("testrule-hostHeader-%s", acctest.RandString(12)) -func TestAccAWSLBListenerRule_conditionHostHeader_deprecated(t *testing.T) { - var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-hostHeader-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLBListenerRuleConfig_conditionHostHeader_deprecated(lbName), + Config: testAccAWSLBListenerRuleConfig_conditionHostHeader(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.field", "host-header"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.host_header.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.host_header.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.host_header.0.values.3069857465", "example.com"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.values.0", "example.com"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "1", + "host_header.0.values.#": "2", + "http_header.#": "0", + "http_request_method.#": "0", + "path_pattern.#": "0", + "query_string.#": "0", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.host_header.0.values.*", "example.com"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.host_header.0.values.*", "www.example.com"), ), }, }, @@ -648,47 +676,48 @@ func TestAccAWSLBListenerRule_conditionHostHeader_deprecated(t *testing.T) { func TestAccAWSLBListenerRule_conditionHttpHeader(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-httpHeader-%s", acctest.RandStringFromCharSet(12, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-httpHeader-%s", acctest.RandString(12)) + + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_conditionHttpHeader(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.field", "http-header"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.http_header.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.http_header.0.http_header_name", "X-Forwarded-For"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.http_header.0.values.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.http_header.0.values.2895841407", "10.0.0.*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.http_header.0.values.35666611", "192.168.1.*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.168627567.values.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4090220723.field", "http-header"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4090220723.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4090220723.http_header.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4090220723.http_header.0.http_header_name", "Zz9~|_^.-+*'&%$#!0aA"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4090220723.http_header.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4090220723.http_header.0.values.1801271041", "RFC7230 Validity"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4090220723.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4090220723.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4090220723.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4090220723.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4090220723.values.#", "0"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "2"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "1", + "http_header.0.http_header_name": "X-Forwarded-For", + "http_header.0.values.#": "2", + "http_request_method.#": "0", + "path_pattern.#": "0", + "query_string.#": "0", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.http_header.0.values.*", "10.0.0.*"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.http_header.0.values.*", "192.168.1.*"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "1", + "http_header.0.http_header_name": "Zz9~|_^.-+*'&%$#!0aA", + "http_header.0.values.#": "1", + "http_request_method.#": "0", + "path_pattern.#": "0", + "query_string.#": "0", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.http_header.0.values.*", "RFC7230 Validity"), ), }, }, @@ -711,35 +740,36 @@ func TestAccAWSLBListenerRule_conditionHttpHeader_invalid(t *testing.T) { func TestAccAWSLBListenerRule_conditionHttpRequestMethod(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-httpRequest-%s", acctest.RandStringFromCharSet(11, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-httpRequest-%s", acctest.RandString(11)) + + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_conditionHttpRequestMethod(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2223521492.field", "http-request-method"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2223521492.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2223521492.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2223521492.http_request_method.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2223521492.http_request_method.0.values.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2223521492.http_request_method.0.values.1805413626", "GET"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2223521492.http_request_method.0.values.1814004025", "POST"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2223521492.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2223521492.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2223521492.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2223521492.values.#", "0"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "0", + "http_request_method.#": "1", + "http_request_method.0.values.#": "2", + "path_pattern.#": "0", + "query_string.#": "0", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.http_request_method.0.values.*", "GET"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.http_request_method.0.values.*", "POST"), ), }, }, @@ -748,132 +778,36 @@ func TestAccAWSLBListenerRule_conditionHttpRequestMethod(t *testing.T) { func TestAccAWSLBListenerRule_conditionPathPattern(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-pathPattern-%s", acctest.RandStringFromCharSet(11, acctest.CharSetAlphaNum)) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, - Steps: []resource.TestStep{ - { - Config: testAccAWSLBListenerRuleConfig_conditionPathPattern(lbName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.field", "path-pattern"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.path_pattern.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.path_pattern.0.values.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.path_pattern.0.values.1764929539", "/cgi-bin/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.path_pattern.0.values.1973895062", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.values.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.values.0", "/cgi-bin/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.values.1", "/public/*"), - ), - }, - }, - }) -} - -func TestAccAWSLBListenerRule_conditionPathPattern_deprecated(t *testing.T) { - var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-pathPattern-%s", acctest.RandStringFromCharSet(11, acctest.CharSetAlphaNum)) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, - Steps: []resource.TestStep{ - { - Config: testAccAWSLBListenerRuleConfig_conditionPathPattern_deprecated(lbName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.field", "path-pattern"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.0.values.1973895062", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.values.0", "/public/*"), - ), - }, - }, - }) -} + lbName := fmt.Sprintf("testrule-pathPattern-%s", acctest.RandString(11)) -func TestAccAWSLBListenerRule_conditionUpdatePathPattern_deprecated(t *testing.T) { - var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-pathPattern-%s", acctest.RandStringFromCharSet(11, acctest.CharSetAlphaNum)) + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ - { - Config: testAccAWSLBListenerRuleConfig_conditionPathPattern_deprecated(lbName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.field", "path-pattern"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.0.values.1973895062", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.values.0", "/public/*"), - ), - }, - { - Config: testAccAWSLBListenerRuleConfig_conditionPathPattern_deprecatedUpdated(lbName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3300407761.path_pattern.0.values.1764929539", "/cgi-bin/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3300407761.values.0", "/cgi-bin/*"), - ), - }, - { - Config: testAccAWSLBListenerRuleConfig_conditionPathPattern_migrated(lbName), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3300407761.path_pattern.0.values.1764929539", "/cgi-bin/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3300407761.values.0", "/cgi-bin/*"), - ), - }, { Config: testAccAWSLBListenerRuleConfig_conditionPathPattern(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.path_pattern.0.values.1764929539", "/cgi-bin/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.path_pattern.0.values.1973895062", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.values.0", "/cgi-bin/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2177156802.values.1", "/public/*"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "0", + "http_request_method.#": "0", + "path_pattern.#": "1", + "path_pattern.0.values.#": "2", + "query_string.#": "0", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.path_pattern.0.values.*", "/cgi-bin/*"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.path_pattern.0.values.*", "/public/*"), ), }, }, @@ -882,48 +816,60 @@ func TestAccAWSLBListenerRule_conditionUpdatePathPattern_deprecated(t *testing.T func TestAccAWSLBListenerRule_conditionQueryString(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-queryString-%s", acctest.RandStringFromCharSet(11, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-queryString-%s", acctest.RandString(11)) + + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_conditionQueryString(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.field", "query-string"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.query_string.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.query_string.167408634.key", ""), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.query_string.167408634.value", "surprise"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.query_string.4042884147.key", ""), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.query_string.4042884147.value", "blank"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.1697057359.values.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.field", "query-string"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.query_string.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.query_string.1123504603.key", "foo"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.query_string.1123504603.value", "baz"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.query_string.1278007785.key", "foo"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.query_string.1278007785.value", "bar"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.863121889.values.#", "0"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "2"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "0", + "http_request_method.#": "0", + "path_pattern.#": "0", + "query_string.#": "2", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*.query_string.*", map[string]string{ + "key": "", + "value": "surprise", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*.query_string.*", map[string]string{ + "key": "", + "value": "blank", + }), + // TODO: TypeSet check helpers cannot make distinction between the 2 set items + // because we had to write a new check for the "downstream" nested set + // a distinguishing attribute on the outer set would be solve this. + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "0", + "http_request_method.#": "0", + "path_pattern.#": "0", + "query_string.#": "2", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*.query_string.*", map[string]string{ + "key": "foo", + "value": "baz", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*.query_string.*", map[string]string{ + "key": "foo", + "value": "bar", + }), ), }, }, @@ -932,35 +878,36 @@ func TestAccAWSLBListenerRule_conditionQueryString(t *testing.T) { func TestAccAWSLBListenerRule_conditionSourceIp(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-sourceIp-%s", acctest.RandStringFromCharSet(14, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-sourceIp-%s", acctest.RandString(14)) + + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_conditionSourceIp(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3009583077.field", "source-ip"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3009583077.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3009583077.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3009583077.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3009583077.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3009583077.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3009583077.source_ip.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3009583077.source_ip.0.values.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3009583077.source_ip.0.values.1567875353", "dead:cafe::/64"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3009583077.source_ip.0.values.3901788224", "192.168.0.0/16"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3009583077.values.#", "0"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "0", + "http_request_method.#": "0", + "path_pattern.#": "0", + "query_string.#": "0", + "source_ip.#": "1", + "source_ip.0.values.#": "2", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.source_ip.0.values.*", "dead:cafe::/64"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.source_ip.0.values.*", "192.168.0.0/16"), ), }, }, @@ -969,67 +916,71 @@ func TestAccAWSLBListenerRule_conditionSourceIp(t *testing.T) { func TestAccAWSLBListenerRule_conditionUpdateMixed(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-mixed-%s", acctest.RandStringFromCharSet(17, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-mixed-%s", acctest.RandString(17)) + + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_conditionMixed(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.field", "path-pattern"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.0.values.1973895062", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.values.0", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.field", "source-ip"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.source_ip.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.source_ip.0.values.3901788224", "192.168.0.0/16"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "2"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "path_pattern.#": "1", + "path_pattern.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.path_pattern.0.values.*", "/public/*"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "source_ip.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.source_ip.0.values.*", "192.168.0.0/16"), ), }, { Config: testAccAWSLBListenerRuleConfig_conditionMixed_updated(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.field", "path-pattern"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.0.values.1973895062", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.values.0", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2685063104.field", "source-ip"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2685063104.source_ip.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2685063104.source_ip.0.values.1567875353", "dead:cafe::/64"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "2"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "path_pattern.#": "1", + "path_pattern.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.path_pattern.0.values.*", "/public/*"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "source_ip.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.source_ip.0.values.*", "dead:cafe::/64"), ), }, { Config: testAccAWSLBListenerRuleConfig_conditionMixed_updated2(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "2"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3300407761.field", "path-pattern"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3300407761.path_pattern.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3300407761.path_pattern.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3300407761.path_pattern.0.values.1764929539", "/cgi-bin/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.3300407761.values.0", "/cgi-bin/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2685063104.field", "source-ip"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2685063104.source_ip.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2685063104.source_ip.0.values.1567875353", "dead:cafe::/64"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "2"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "path_pattern.#": "1", + "path_pattern.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.path_pattern.0.values.*", "/cgi-bin/*"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "source_ip.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.source_ip.0.values.*", "dead:cafe::/64"), ), }, }, @@ -1038,77 +989,80 @@ func TestAccAWSLBListenerRule_conditionUpdateMixed(t *testing.T) { func TestAccAWSLBListenerRule_conditionMultiple(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-condMulti-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-condMulti-%s", acctest.RandString(13)) + + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_conditionMultiple(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "priority", "100"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "5"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.field", "http-header"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.http_header.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.http_header.0.http_header_name", "X-Forwarded-For"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.http_header.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.http_header.0.values.35666611", "192.168.1.*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.values.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.field", "source-ip"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.source_ip.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.source_ip.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.source_ip.0.values.3901788224", "192.168.0.0/16"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.values.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.field", "http-request-method"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.http_request_method.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.http_request_method.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.http_request_method.0.values.1805413626", "GET"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.values.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.field", "path-pattern"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.host_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.0.values.1973895062", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.values.0", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.field", "host-header"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.host_header.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.host_header.0.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.host_header.0.values.3069857465", "example.com"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.http_header.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.http_request_method.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.path_pattern.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.query_string.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.source_ip.#", "0"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.values.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.values.0", "example.com"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "priority", "100"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "5"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "1", + "http_header.0.http_header_name": "X-Forwarded-For", + "http_header.0.values.#": "1", + "http_request_method.#": "0", + "path_pattern.#": "0", + "query_string.#": "0", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.http_header.0.values.*", "192.168.1.*"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "0", + "http_request_method.#": "0", + "path_pattern.#": "0", + "query_string.#": "0", + "source_ip.#": "1", + "source_ip.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.source_ip.0.values.*", "192.168.0.0/16"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "0", + "http_request_method.#": "1", + "http_request_method.0.values.#": "1", + "path_pattern.#": "0", + "query_string.#": "0", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.http_request_method.0.values.*", "GET"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "0", + "http_header.#": "0", + "http_request_method.#": "0", + "path_pattern.#": "1", + "path_pattern.0.values.#": "1", + "query_string.#": "0", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.path_pattern.0.values.*", "/public/*"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "1", + "host_header.0.values.#": "1", + "http_header.#": "0", + "http_request_method.#": "0", + "path_pattern.#": "0", + "query_string.#": "0", + "source_ip.#": "0", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.host_header.0.values.*", "example.com"), ), }, }, @@ -1117,59 +1071,94 @@ func TestAccAWSLBListenerRule_conditionMultiple(t *testing.T) { func TestAccAWSLBListenerRule_conditionUpdateMultiple(t *testing.T) { var conf elbv2.Rule - lbName := fmt.Sprintf("testrule-condMulti-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) + lbName := fmt.Sprintf("testrule-condMulti-%s", acctest.RandString(13)) + + resourceName := "aws_lb_listener_rule.static" + frontEndListenerResourceName := "aws_lb_listener.front_end" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: "aws_lb_listener_rule.static", - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSLBListenerRuleConfig_conditionMultiple(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "5"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.field", "http-header"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.http_header.0.http_header_name", "X-Forwarded-For"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.139999317.http_header.0.values.35666611", "192.168.1.*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.field", "source-ip"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2986919393.source_ip.0.values.3901788224", "192.168.0.0/16"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.field", "http-request-method"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.4038921246.http_request_method.0.values.1805413626", "GET"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.field", "path-pattern"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.path_pattern.0.values.1973895062", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.837782343.values.0", "/public/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.field", "host-header"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.host_header.0.values.3069857465", "example.com"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.887624213.values.0", "example.com"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "5"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "http_header.#": "1", + "http_header.0.http_header_name": "X-Forwarded-For", + "http_header.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.http_header.0.values.*", "192.168.1.*"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "source_ip.#": "1", + "source_ip.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.source_ip.0.values.*", "192.168.0.0/16"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "http_request_method.#": "1", + "http_request_method.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.http_request_method.0.values.*", "GET"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "path_pattern.#": "1", + "path_pattern.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.path_pattern.0.values.*", "/public/*"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "1", + "host_header.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.host_header.0.values.*", "example.com"), ), }, { Config: testAccAWSLBListenerRuleConfig_conditionMultiple_updated(lbName), Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckAWSLBListenerRuleExists("aws_lb_listener_rule.static", &conf), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "arn"), - resource.TestCheckResourceAttrSet("aws_lb_listener_rule.static", "listener_arn"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "action.#", "1"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.#", "5"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.451778491.field", "http-header"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.451778491.http_header.0.http_header_name", "X-Forwarded-For"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.451778491.http_header.0.values.6718698", "192.168.2.*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2188908858.field", "source-ip"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.2188908858.source_ip.0.values.766747311", "192.168.0.0/24"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.736971867.field", "http-request-method"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.736971867.http_request_method.0.values.1814004025", "POST"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.941005625.field", "path-pattern"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.941005625.path_pattern.0.values.188114058", "/public/2/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.941005625.values.0", "/public/2/*"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.923495315.field", "host-header"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.923495315.host_header.0.values.854267206", "foobar.com"), - resource.TestCheckResourceAttr("aws_lb_listener_rule.static", "condition.923495315.values.0", "foobar.com"), + testAccCheckAWSLBListenerRuleExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile(fmt.Sprintf(`listener-rule/app/%s/.+$`, lbName))), + resource.TestCheckResourceAttrPair(resourceName, "listener_arn", frontEndListenerResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "condition.#", "5"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "http_header.#": "1", + "http_header.0.http_header_name": "X-Forwarded-For", + "http_header.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.http_header.0.values.*", "192.168.2.*"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "source_ip.#": "1", + "source_ip.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.source_ip.0.values.*", "192.168.0.0/24"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "http_request_method.#": "1", + "http_request_method.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.http_request_method.0.values.*", "POST"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "path_pattern.#": "1", + "path_pattern.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.path_pattern.0.values.*", "/public/2/*"), + + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "condition.*", map[string]string{ + "host_header.#": "1", + "host_header.0.values.#": "1", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "condition.*.host_header.0.values.*", "foobar.com"), ), }, }, @@ -1204,91 +1193,374 @@ func testAccCheckAWSLBListenerRuleActionOrderDisappears(rule *elbv2.Rule, action } } -func testAccCheckAWSLbListenerRuleRecreated(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 testAccCheckAWSLbListenerRuleRecreated(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 testAccCheckAWSLBListenerRuleExists(n string, res *elbv2.Rule) 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 Listener Rule ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).elbv2conn + + describe, err := conn.DescribeRules(&elbv2.DescribeRulesInput{ + RuleArns: []*string{aws.String(rs.Primary.ID)}, + }) + + if err != nil { + return err + } + + if len(describe.Rules) != 1 || + *describe.Rules[0].RuleArn != rs.Primary.ID { + return errors.New("Listener Rule not found") + } + + *res = *describe.Rules[0] + return nil + } +} + +func testAccCheckAWSLBListenerRuleDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).elbv2conn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_lb_listener_rule" && rs.Type != "aws_alb_listener_rule" { + continue + } + + describe, err := conn.DescribeRules(&elbv2.DescribeRulesInput{ + RuleArns: []*string{aws.String(rs.Primary.ID)}, + }) + + if err == nil { + if len(describe.Rules) != 0 && + *describe.Rules[0].RuleArn == rs.Primary.ID { + return fmt.Errorf("Listener Rule %q still exists", rs.Primary.ID) + } + } + + // Verify the error + if isAWSErr(err, elbv2.ErrCodeRuleNotFoundException, "") { + return nil + } else { + return fmt.Errorf("Unexpected error checking LB Listener Rule destroyed: %s", err) + } + } + + return nil +} + +func testAccAWSLBListenerRuleConfig_basic(lbName, targetGroupName string) string { + return fmt.Sprintf(` +resource "aws_lb_listener_rule" "static" { + listener_arn = "${aws_lb_listener.front_end.arn}" + priority = 100 + + action { + type = "forward" + target_group_arn = "${aws_lb_target_group.test.arn}" + } + + condition { + path_pattern { + values = ["/static/*"] + } + } +} + +resource "aws_lb_listener" "front_end" { + load_balancer_arn = "${aws_lb.alb_test.id}" + protocol = "HTTP" + port = "80" + + default_action { + target_group_arn = "${aws_lb_target_group.test.id}" + type = "forward" + } +} + +resource "aws_lb" "alb_test" { + name = "%s" + internal = true + security_groups = ["${aws_security_group.alb_test.id}"] + subnets = ["${aws_subnet.alb_test.*.id[0]}", "${aws_subnet.alb_test.*.id[1]}"] + + idle_timeout = 30 + enable_deletion_protection = false + + tags = { + Name = "TestAccAWSALB_basic" + } +} + +resource "aws_lb_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" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +resource "aws_vpc" "alb_test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = "terraform-testacc-lb-listener-rule-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 = { + Name = "tf-acc-lb-listener-rule-basic-${count.index}" + } +} + +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 = { + Name = "TestAccAWSALB_basic" + } +} +`, lbName, targetGroupName) +} + +func testAccAWSLBListenerRuleConfig_forwardWeighted(lbName, targetGroupName1 string, targetGroupName2 string) string { + return fmt.Sprintf(` +resource "aws_lb_listener_rule" "weighted" { + listener_arn = "${aws_lb_listener.front_end.arn}" + priority = 100 + + action { + type = "forward" + forward { + target_group { + arn = "${aws_lb_target_group.test1.arn}" + weight = 1 + } + target_group { + arn = "${aws_lb_target_group.test2.arn}" + weight = 1 + } + } + } + + condition { + path_pattern { + values = ["/weighted/*"] + } + } +} + +resource "aws_lb_listener" "front_end" { + load_balancer_arn = "${aws_lb.alb_test.id}" + protocol = "HTTP" + port = "80" + + default_action { + target_group_arn = "${aws_lb_target_group.test1.arn}" + type = "forward" + } +} + +resource "aws_lb" "alb_test" { + name = "%s" + internal = true + security_groups = ["${aws_security_group.alb_test.id}"] + subnets = ["${aws_subnet.alb_test.*.id[0]}", "${aws_subnet.alb_test.*.id[1]}"] + + idle_timeout = 30 + enable_deletion_protection = false + + tags = { + Name = "TestAccAWSALB_basic" + } +} + +resource "aws_lb_target_group" "test1" { + 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" + } } -func testAccCheckAWSLBListenerRuleExists(n string, res *elbv2.Rule) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } +resource "aws_lb_target_group" "test2" { + name = "%s" + port = 8080 + protocol = "HTTP" + vpc_id = "${aws_vpc.alb_test.id}" - if rs.Primary.ID == "" { - return errors.New("No Listener Rule ID is set") - } + health_check { + path = "/health" + interval = 60 + port = 8081 + protocol = "HTTP" + timeout = 3 + healthy_threshold = 3 + unhealthy_threshold = 3 + matcher = "200-299" + } +} - conn := testAccProvider.Meta().(*AWSClient).elbv2conn +variable "subnets" { + default = ["10.0.1.0/24", "10.0.2.0/24"] + type = "list" +} - describe, err := conn.DescribeRules(&elbv2.DescribeRulesInput{ - RuleArns: []*string{aws.String(rs.Primary.ID)}, - }) +data "aws_availability_zones" "available" { + state = "available" - if err != nil { - return err - } + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} - if len(describe.Rules) != 1 || - *describe.Rules[0].RuleArn != rs.Primary.ID { - return errors.New("Listener Rule not found") - } +resource "aws_vpc" "alb_test" { + cidr_block = "10.0.0.0/16" - *res = *describe.Rules[0] - return nil - } + tags = { + Name = "terraform-testacc-lb-listener-rule-basic" + } } -func testAccCheckAWSLBListenerRuleDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).elbv2conn +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)}" - for _, rs := range s.RootModule().Resources { - if rs.Type != "aws_lb_listener_rule" && rs.Type != "aws_alb_listener_rule" { - continue - } + tags = { + Name = "tf-acc-lb-listener-rule-basic-${count.index}" + } +} - describe, err := conn.DescribeRules(&elbv2.DescribeRulesInput{ - RuleArns: []*string{aws.String(rs.Primary.ID)}, - }) +resource "aws_security_group" "alb_test" { + name = "allow_all_alb_test" + description = "Used for ALB Testing" + vpc_id = "${aws_vpc.alb_test.id}" - if err == nil { - if len(describe.Rules) != 0 && - *describe.Rules[0].RuleArn == rs.Primary.ID { - return fmt.Errorf("Listener Rule %q still exists", rs.Primary.ID) - } - } + ingress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } - // Verify the error - if isAWSErr(err, elbv2.ErrCodeRuleNotFoundException, "") { - return nil - } else { - return fmt.Errorf("Unexpected error checking LB Listener Rule destroyed: %s", err) - } - } + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } - return nil + tags = { + Name = "TestAccAWSALB_basic" + } +} +`, lbName, targetGroupName1, targetGroupName2) } -func testAccAWSLBListenerRuleConfig_multipleConditions(lbName, targetGroupName string) string { +func testAccAWSLBListenerRuleConfig_changeForwardWeightedStickiness(lbName, targetGroupName1 string, targetGroupName2 string) string { return fmt.Sprintf(` -resource "aws_lb_listener_rule" "static" { +resource "aws_lb_listener_rule" "weighted" { listener_arn = "${aws_lb_listener.front_end.arn}" priority = 100 action { - type = "forward" - target_group_arn = "${aws_lb_target_group.test.arn}" + type = "forward" + forward { + target_group { + arn = "${aws_lb_target_group.test1.arn}" + weight = 1 + } + target_group { + arn = "${aws_lb_target_group.test2.arn}" + weight = 1 + } + stickiness { + enabled = true + duration = 3600 + } + } } condition { - field = "path-pattern" - values = ["/static/*", "static"] + path_pattern { + values = ["/weighted/*"] + } } } @@ -1298,7 +1570,7 @@ resource "aws_lb_listener" "front_end" { port = "80" default_action { - target_group_arn = "${aws_lb_target_group.test.id}" + target_group_arn = "${aws_lb_target_group.test1.arn}" type = "forward" } } @@ -1317,7 +1589,25 @@ resource "aws_lb" "alb_test" { } } -resource "aws_lb_target_group" "test" { +resource "aws_lb_target_group" "test1" { + 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" + } +} + +resource "aws_lb_target_group" "test2" { name = "%s" port = 8080 protocol = "HTTP" @@ -1353,7 +1643,7 @@ resource "aws_vpc" "alb_test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-lb-listener-rule-multiple-conditions" + Name = "terraform-testacc-lb-listener-rule-basic" } } @@ -1365,7 +1655,7 @@ resource "aws_subnet" "alb_test" { availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}" tags = { - Name = "tf-acc-lb-listener-rule-multiple-conditions-${count.index}" + Name = "tf-acc-lb-listener-rule-basic-${count.index}" } } @@ -1392,23 +1682,24 @@ resource "aws_security_group" "alb_test" { Name = "TestAccAWSALB_basic" } } -`, lbName, targetGroupName) +`, lbName, targetGroupName1, targetGroupName2) } -func testAccAWSLBListenerRuleConfig_basic(lbName, targetGroupName string) string { +func testAccAWSLBListenerRuleConfig_changeForwardWeightedToBasic(lbName, targetGroupName1 string, targetGroupName2 string) string { return fmt.Sprintf(` -resource "aws_lb_listener_rule" "static" { +resource "aws_lb_listener_rule" "weighted" { listener_arn = "${aws_lb_listener.front_end.arn}" priority = 100 action { type = "forward" - target_group_arn = "${aws_lb_target_group.test.arn}" + target_group_arn = "${aws_lb_target_group.test1.arn}" } condition { - field = "path-pattern" - values = ["/static/*"] + path_pattern { + values = ["/weighted/*"] + } } } @@ -1418,7 +1709,7 @@ resource "aws_lb_listener" "front_end" { port = "80" default_action { - target_group_arn = "${aws_lb_target_group.test.id}" + target_group_arn = "${aws_lb_target_group.test1.arn}" type = "forward" } } @@ -1437,7 +1728,25 @@ resource "aws_lb" "alb_test" { } } -resource "aws_lb_target_group" "test" { +resource "aws_lb_target_group" "test1" { + 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" + } +} + +resource "aws_lb_target_group" "test2" { name = "%s" port = 8080 protocol = "HTTP" @@ -1512,7 +1821,7 @@ resource "aws_security_group" "alb_test" { Name = "TestAccAWSALB_basic" } } -`, lbName, targetGroupName) +`, lbName, targetGroupName1, targetGroupName2) } func testAccAWSLBListenerRuleConfigBackwardsCompatibility(lbName, targetGroupName string) string { @@ -1527,8 +1836,9 @@ resource "aws_alb_listener_rule" "static" { } condition { - field = "path-pattern" - values = ["/static/*"] + path_pattern { + values = ["/static/*"] + } } } @@ -1652,8 +1962,9 @@ resource "aws_lb_listener_rule" "static" { } condition { - field = "path-pattern" - values = ["/static/*"] + path_pattern { + values = ["/static/*"] + } } } @@ -1764,8 +2075,9 @@ resource "aws_lb_listener_rule" "static" { } condition { - field = "path-pattern" - values = ["/static/*"] + path_pattern { + values = ["/static/*"] + } } } @@ -1871,8 +2183,9 @@ resource "aws_lb_listener_rule" "static" { } condition { - field = "path-pattern" - values = ["/static/*"] + path_pattern { + values = ["/static/*"] + } } } @@ -1991,8 +2304,9 @@ resource "aws_lb_listener_rule" "static" { } condition { - field = "path-pattern" - values = ["/static/*"] + path_pattern { + values = ["/static/*"] + } } } @@ -2216,7 +2530,7 @@ resource "aws_security_group" "alb_test" { } func testAccAWSLBListenerRuleConfig_priorityFirst(lbName, targetGroupName string) string { - return testAccAWSLBListenerRuleConfig_priorityBase(lbName, targetGroupName) + fmt.Sprintf(` + return testAccAWSLBListenerRuleConfig_priorityBase(lbName, targetGroupName) + ` resource "aws_lb_listener_rule" "first" { listener_arn = "${aws_lb_listener.front_end.arn}" @@ -2226,8 +2540,9 @@ resource "aws_lb_listener_rule" "first" { } condition { - field = "path-pattern" - values = ["/first/*"] + path_pattern { + values = ["/first/*"] + } } } @@ -2241,17 +2556,18 @@ resource "aws_lb_listener_rule" "third" { } condition { - field = "path-pattern" - values = ["/third/*"] + path_pattern { + values = ["/third/*"] + } } depends_on = ["aws_lb_listener_rule.first"] } -`) +` } func testAccAWSLBListenerRuleConfig_priorityLast(lbName, targetGroupName string) string { - return testAccAWSLBListenerRuleConfig_priorityFirst(lbName, targetGroupName) + fmt.Sprintf(` + return testAccAWSLBListenerRuleConfig_priorityFirst(lbName, targetGroupName) + ` resource "aws_lb_listener_rule" "last" { listener_arn = "${aws_lb_listener.front_end.arn}" @@ -2261,15 +2577,16 @@ resource "aws_lb_listener_rule" "last" { } condition { - field = "path-pattern" - values = ["/last/*"] + path_pattern { + values = ["/last/*"] + } } } -`) +` } func testAccAWSLBListenerRuleConfig_priorityStatic(lbName, targetGroupName string) string { - return testAccAWSLBListenerRuleConfig_priorityFirst(lbName, targetGroupName) + fmt.Sprintf(` + return testAccAWSLBListenerRuleConfig_priorityFirst(lbName, targetGroupName) + ` resource "aws_lb_listener_rule" "last" { listener_arn = "${aws_lb_listener.front_end.arn}" priority = 7 @@ -2280,15 +2597,16 @@ resource "aws_lb_listener_rule" "last" { } condition { - field = "path-pattern" - values = ["/last/*"] + path_pattern { + values = ["/last/*"] + } } } -`) +` } func testAccAWSLBListenerRuleConfig_priorityParallelism(lbName, targetGroupName string) string { - return testAccAWSLBListenerRuleConfig_priorityStatic(lbName, targetGroupName) + fmt.Sprintf(` + return testAccAWSLBListenerRuleConfig_priorityStatic(lbName, targetGroupName) + ` resource "aws_lb_listener_rule" "parallelism" { count = 10 @@ -2300,15 +2618,16 @@ resource "aws_lb_listener_rule" "parallelism" { } condition { - field = "path-pattern" - values = ["/${count.index}/*"] + path_pattern { + values = ["/${count.index}/*"] + } } } -`) +` } func testAccAWSLBListenerRuleConfig_priority50000(lbName, targetGroupName string) string { - return testAccAWSLBListenerRuleConfig_priorityBase(lbName, targetGroupName) + fmt.Sprintf(` + return testAccAWSLBListenerRuleConfig_priorityBase(lbName, targetGroupName) + ` resource "aws_lb_listener_rule" "priority50000" { listener_arn = "${aws_lb_listener.front_end.arn}" priority = 50000 @@ -2319,16 +2638,17 @@ resource "aws_lb_listener_rule" "priority50000" { } condition { - field = "path-pattern" - values = ["/50000/*"] + path_pattern { + values = ["/50000/*"] + } } } -`) +` } // priority out of range (1, 50000) func testAccAWSLBListenerRuleConfig_priority50001(lbName, targetGroupName string) string { - return testAccAWSLBListenerRuleConfig_priority50000(lbName, targetGroupName) + fmt.Sprintf(` + return testAccAWSLBListenerRuleConfig_priority50000(lbName, targetGroupName) + ` resource "aws_lb_listener_rule" "priority50001" { listener_arn = "${aws_lb_listener.front_end.arn}" @@ -2338,15 +2658,16 @@ resource "aws_lb_listener_rule" "priority50001" { } condition { - field = "path-pattern" - values = ["/50001/*"] + path_pattern { + values = ["/50001/*"] + } } } -`) +` } func testAccAWSLBListenerRuleConfig_priorityInUse(lbName, targetGroupName string) string { - return testAccAWSLBListenerRuleConfig_priority50000(lbName, targetGroupName) + fmt.Sprintf(` + return testAccAWSLBListenerRuleConfig_priority50000(lbName, targetGroupName) + ` resource "aws_lb_listener_rule" "priority50000_in_use" { listener_arn = "${aws_lb_listener.front_end.arn}" priority = 50000 @@ -2357,11 +2678,12 @@ resource "aws_lb_listener_rule" "priority50000_in_use" { } condition { - field = "path-pattern" - values = ["/50000_in_use/*"] + path_pattern { + values = ["/50000_in_use/*"] + } } } -`) +` } func testAccAWSLBListenerRuleConfig_cognito(rName, key, certificate string) string { @@ -2390,8 +2712,9 @@ resource "aws_lb_listener_rule" "cognito" { } condition { - field = "path-pattern" - values = ["/static/*"] + path_pattern { + values = ["/static/*"] + } } } @@ -2556,8 +2879,9 @@ resource "aws_lb_listener_rule" "oidc" { } condition { - field = "path-pattern" - values = ["/static/*"] + path_pattern { + values = ["/static/*"] + } } } @@ -2715,8 +3039,9 @@ resource "aws_lb_listener_rule" "test" { } condition { - field = "path-pattern" - values = ["/static/*"] + path_pattern { + values = ["/static/*"] + } } } @@ -2831,18 +3156,6 @@ resource "aws_lb_listener_rule" "error" { `, condition) } -func testAccAWSLBListenerRuleConfig_conditionAttributesCount_empty() string { - return testAccAWSLBListenerRuleConfig_condition_error("condition {}") -} - -func testAccAWSLBListenerRuleConfig_conditionAttributesCount_field() string { - return testAccAWSLBListenerRuleConfig_condition_error(`condition { field = "host-header" }`) -} - -func testAccAWSLBListenerRuleConfig_conditionAttributesCount_values() string { - return testAccAWSLBListenerRuleConfig_condition_error(`condition { values = ["example.com"] }`) -} - func testAccAWSLBListenerRuleConfig_conditionAttributesCount_http_header() string { return testAccAWSLBListenerRuleConfig_condition_error(` condition { @@ -2905,17 +3218,6 @@ condition { }`) } -func testAccAWSLBListenerRuleConfig_conditionAttributesCount_classic() string { - return testAccAWSLBListenerRuleConfig_condition_error(` -condition { - host_header { - values = ["example.com"] - } - field = "host-header" - values = ["example2.com"] -}`) -} - func testAccAWSLBListenerRuleConfig_condition_base(condition, name, lbName string) string { return fmt.Sprintf(` resource "aws_lb_listener_rule" "static" { @@ -3035,15 +3337,6 @@ condition { `, "HostHeader", lbName) } -func testAccAWSLBListenerRuleConfig_conditionHostHeader_deprecated(lbName string) string { - return testAccAWSLBListenerRuleConfig_condition_base(` -condition { - field = "host-header" - values = ["example.com"] -} -`, "HostHeaderDep", lbName) -} - func testAccAWSLBListenerRuleConfig_conditionHttpHeader(lbName string) string { return testAccAWSLBListenerRuleConfig_condition_base(` condition { @@ -3108,34 +3401,6 @@ condition { `, "PathPattern", lbName) } -func testAccAWSLBListenerRuleConfig_conditionPathPattern_deprecated(lbName string) string { - return testAccAWSLBListenerRuleConfig_condition_base(` -condition { - field = "path-pattern" - values = ["/public/*"] -} -`, "PathPattern", lbName) -} - -func testAccAWSLBListenerRuleConfig_conditionPathPattern_deprecatedUpdated(lbName string) string { - return testAccAWSLBListenerRuleConfig_condition_base(` -condition { - field = "path-pattern" - values = ["/cgi-bin/*"] -} -`, "PathPattern", lbName) -} - -func testAccAWSLBListenerRuleConfig_conditionPathPattern_migrated(lbName string) string { - return testAccAWSLBListenerRuleConfig_condition_base(` -condition { - path_pattern { - values = ["/cgi-bin/*"] - } -} -`, "PathPattern", lbName) -} - func testAccAWSLBListenerRuleConfig_conditionQueryString(lbName string) string { return testAccAWSLBListenerRuleConfig_condition_base(` condition { @@ -3177,8 +3442,9 @@ condition { func testAccAWSLBListenerRuleConfig_conditionMixed(lbName string) string { return testAccAWSLBListenerRuleConfig_condition_base(` condition { - field = "path-pattern" - values = ["/public/*"] + path_pattern { + values = ["/public/*"] + } } condition { @@ -3195,8 +3461,9 @@ condition { func testAccAWSLBListenerRuleConfig_conditionMixed_updated(lbName string) string { return testAccAWSLBListenerRuleConfig_condition_base(` condition { - field = "path-pattern" - values = ["/public/*"] + path_pattern { + values = ["/public/*"] + } } condition { @@ -3213,8 +3480,9 @@ condition { func testAccAWSLBListenerRuleConfig_conditionMixed_updated2(lbName string) string { return testAccAWSLBListenerRuleConfig_condition_base(` condition { - field = "path-pattern" - values = ["/cgi-bin/*"] + path_pattern { + values = ["/cgi-bin/*"] + } } condition { diff --git a/aws/resource_aws_lb_listener_test.go b/aws/resource_aws_lb_listener_test.go index d711bcd586a..c2782c61a52 100644 --- a/aws/resource_aws_lb_listener_test.go +++ b/aws/resource_aws_lb_listener_test.go @@ -3,13 +3,14 @@ package aws import ( "errors" "fmt" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLBListener_basic(t *testing.T) { @@ -43,6 +44,79 @@ func TestAccAWSLBListener_basic(t *testing.T) { }) } +func TestAccAWSLBListener_forwardWeighted(t *testing.T) { + var conf elbv2.Listener + resourceName := "aws_lb_listener.weighted" + lbName := fmt.Sprintf("testlistener-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) + targetGroupName1 := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + targetGroupName2 := fmt.Sprintf("testtargetgroup-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBListenerDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLBListenerConfig_forwardWeighted(lbName, targetGroupName1, targetGroupName2), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSLBListenerExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "load_balancer_arn", "elasticloadbalancing", regexp.MustCompile("loadbalancer/.+$")), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile("listener/.+$")), + resource.TestCheckResourceAttr(resourceName, "protocol", "HTTP"), + resource.TestCheckResourceAttr(resourceName, "port", "80"), + resource.TestCheckResourceAttr(resourceName, "default_action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.type", "forward"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.forward.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.forward.0.target_group.#", "2"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.forward.0.stickiness.0.enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.forward.0.stickiness.0.duration", "0"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.redirect.#", "0"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.fixed_response.#", "0"), + ), + }, + { + Config: testAccAWSLBListenerConfig_changeForwardWeightedStickiness(lbName, targetGroupName1, targetGroupName2), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSLBListenerExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "load_balancer_arn", "elasticloadbalancing", regexp.MustCompile("loadbalancer/.+$")), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile("listener/.+$")), + resource.TestCheckResourceAttr(resourceName, "protocol", "HTTP"), + resource.TestCheckResourceAttr(resourceName, "port", "80"), + resource.TestCheckResourceAttr(resourceName, "default_action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.type", "forward"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.forward.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.forward.0.target_group.#", "2"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.forward.0.stickiness.0.enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.forward.0.stickiness.0.duration", "3600"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.redirect.#", "0"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.fixed_response.#", "0"), + ), + }, + { + Config: testAccAWSLBListenerConfig_changeForwardWeightedToBasic(lbName, targetGroupName1, targetGroupName2), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSLBListenerExists(resourceName, &conf), + testAccMatchResourceAttrRegionalARN(resourceName, "load_balancer_arn", "elasticloadbalancing", regexp.MustCompile("loadbalancer/.+$")), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "elasticloadbalancing", regexp.MustCompile("listener/.+$")), + resource.TestCheckResourceAttr(resourceName, "protocol", "HTTP"), + resource.TestCheckResourceAttr(resourceName, "port", "80"), + resource.TestCheckResourceAttr(resourceName, "default_action.#", "1"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.order", "1"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.type", "forward"), + resource.TestCheckResourceAttrSet(resourceName, "default_action.0.target_group_arn"), + testAccMatchResourceAttrRegionalARN(resourceName, "default_action.0.target_group_arn", "elasticloadbalancing", regexp.MustCompile("targetgroup/.+$")), + resource.TestCheckResourceAttrPair(resourceName, "default_action.0.target_group_arn", "aws_lb_target_group.test1", "arn"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.redirect.#", "0"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.fixed_response.#", "0"), + ), + }, + }, + }) +} + func TestAccAWSLBListener_basicUdp(t *testing.T) { var conf elbv2.Listener lbName := fmt.Sprintf("testlistener-basic-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) @@ -555,6 +629,397 @@ resource "aws_security_group" "alb_test" { `, lbName, targetGroupName) } +func testAccAWSLBListenerConfig_forwardWeighted(lbName, targetGroupName1 string, targetGroupName2 string) string { + return fmt.Sprintf(` +resource "aws_lb_listener" "weighted" { + load_balancer_arn = "${aws_lb.alb_test.id}" + protocol = "HTTP" + port = "80" + + default_action { + type = "forward" + forward { + target_group { + arn = "${aws_lb_target_group.test1.arn}" + weight = 1 + } + target_group { + arn = "${aws_lb_target_group.test2.arn}" + weight = 1 + } + } + } +} + +resource "aws_lb" "alb_test" { + name = "%s" + internal = true + security_groups = ["${aws_security_group.alb_test.id}"] + subnets = ["${aws_subnet.alb_test.*.id[0]}", "${aws_subnet.alb_test.*.id[1]}"] + + idle_timeout = 30 + enable_deletion_protection = false + + tags = { + Name = "TestAccAWSALB_basic" + } +} + +resource "aws_lb_target_group" "test1" { + 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" + } +} + +resource "aws_lb_target_group" "test2" { + 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" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +resource "aws_vpc" "alb_test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = "terraform-testacc-lb-listener-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 = { + Name = "tf-acc-lb-listener-basic-${count.index}" + } +} + +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 = { + Name = "TestAccAWSALB_basic" + } +} +`, lbName, targetGroupName1, targetGroupName2) +} + +func testAccAWSLBListenerConfig_changeForwardWeightedStickiness(lbName, targetGroupName1 string, targetGroupName2 string) string { + return fmt.Sprintf(` +resource "aws_lb_listener" "weighted" { + load_balancer_arn = "${aws_lb.alb_test.id}" + protocol = "HTTP" + port = "80" + + default_action { + type = "forward" + forward { + target_group { + arn = "${aws_lb_target_group.test1.arn}" + weight = 1 + } + target_group { + arn = "${aws_lb_target_group.test2.arn}" + weight = 1 + } + stickiness { + enabled = true + duration = 3600 + } + } + } +} + +resource "aws_lb" "alb_test" { + name = "%s" + internal = true + security_groups = ["${aws_security_group.alb_test.id}"] + subnets = ["${aws_subnet.alb_test.*.id[0]}", "${aws_subnet.alb_test.*.id[1]}"] + + idle_timeout = 30 + enable_deletion_protection = false + + tags = { + Name = "TestAccAWSALB_basic" + } +} + +resource "aws_lb_target_group" "test1" { + 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" + } +} + +resource "aws_lb_target_group" "test2" { + 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" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +resource "aws_vpc" "alb_test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = "terraform-testacc-lb-listener-rule-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 = { + Name = "tf-acc-lb-listener-rule-basic-${count.index}" + } +} + +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 = { + Name = "TestAccAWSALB_basic" + } +} +`, lbName, targetGroupName1, targetGroupName2) +} + +func testAccAWSLBListenerConfig_changeForwardWeightedToBasic(lbName, targetGroupName1 string, targetGroupName2 string) string { + return fmt.Sprintf(` +resource "aws_lb_listener" "weighted" { + load_balancer_arn = "${aws_lb.alb_test.id}" + protocol = "HTTP" + port = "80" + + default_action { + target_group_arn = "${aws_lb_target_group.test1.arn}" + type = "forward" + } +} + +resource "aws_lb" "alb_test" { + name = "%s" + internal = true + security_groups = ["${aws_security_group.alb_test.id}"] + subnets = ["${aws_subnet.alb_test.*.id[0]}", "${aws_subnet.alb_test.*.id[1]}"] + + idle_timeout = 30 + enable_deletion_protection = false + + tags = { + Name = "TestAccAWSALB_basic" + } +} + +resource "aws_lb_target_group" "test1" { + 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" + } +} + +resource "aws_lb_target_group" "test2" { + 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" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +resource "aws_vpc" "alb_test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = "terraform-testacc-lb-listener-rule-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 = { + Name = "tf-acc-lb-listener-rule-basic-${count.index}" + } +} + +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 = { + Name = "TestAccAWSALB_basic" + } +} +`, lbName, targetGroupName1, targetGroupName2) +} + func testAccAWSLBListenerConfig_basicUdp(lbName, targetGroupName string) string { return fmt.Sprintf(` resource "aws_lb_listener" "front_end" { diff --git a/aws/resource_aws_lb_ssl_negotiation_policy.go b/aws/resource_aws_lb_ssl_negotiation_policy.go index 17e6af10534..b0ca01e50d7 100644 --- a/aws/resource_aws_lb_ssl_negotiation_policy.go +++ b/aws/resource_aws_lb_ssl_negotiation_policy.go @@ -4,13 +4,14 @@ import ( "bytes" "fmt" "log" + "strconv" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsLBSSLNegotiationPolicy() *schema.Resource { @@ -80,12 +81,8 @@ func resourceAwsLBSSLNegotiationPolicyCreate(d *schema.ResourceData, meta interf // Check for Policy Attributes if v, ok := d.GetOk("attribute"); ok { - var err error // Expand the "attribute" set to aws-sdk-go compat []*elb.PolicyAttribute - lbspOpts.PolicyAttributes, err = expandPolicyAttributes(v.(*schema.Set).List()) - if err != nil { - return err - } + lbspOpts.PolicyAttributes = expandPolicyAttributes(v.(*schema.Set).List()) } log.Printf("[DEBUG] Load Balancer Policy opts: %#v", lbspOpts) @@ -114,7 +111,10 @@ func resourceAwsLBSSLNegotiationPolicyCreate(d *schema.ResourceData, meta interf func resourceAwsLBSSLNegotiationPolicyRead(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbconn - lbName, lbPort, policyName := resourceAwsLBSSLNegotiationPolicyParseId(d.Id()) + lbName, lbPort, policyName, err := resourceAwsLBSSLNegotiationPolicyParseId(d.Id()) + if err != nil { + return err + } request := &elb.DescribeLoadBalancerPoliciesInput{ LoadBalancerName: aws.String(lbName), @@ -139,22 +139,35 @@ func resourceAwsLBSSLNegotiationPolicyRead(d *schema.ResourceData, meta interfac return fmt.Errorf("Unable to find policy %#v", getResp.PolicyDescriptions) } - // We can get away with this because there's only one policy returned - policyDesc := getResp.PolicyDescriptions[0] - attributes := flattenPolicyAttributes(policyDesc.PolicyAttributeDescriptions) - d.Set("attributes", attributes) - d.Set("name", policyName) d.Set("load_balancer", lbName) d.Set("lb_port", lbPort) + // TODO: fix attribute + // This was previously erroneously setting "attributes", however this cannot + // be changed without introducing problematic side effects. The ELB service + // automatically expands the results to include all SSL attributes + // (unordered, so we'd need to switch to TypeSet anyways), which we would be + // quite impractical to force practitioners to write out and potentially + // update each time the API updates since there is nearly 100 attributes. + + // We can get away with this because there's only one policy returned + // policyDesc := getResp.PolicyDescriptions[0] + // attributes := flattenPolicyAttributes(policyDesc.PolicyAttributeDescriptions) + // if err := d.Set("attribute", attributes); err != nil { + // return fmt.Errorf("error setting attribute: %s", err) + // } + return nil } func resourceAwsLBSSLNegotiationPolicyDelete(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbconn - lbName, _, policyName := resourceAwsLBSSLNegotiationPolicyParseId(d.Id()) + lbName, _, policyName, err := resourceAwsLBSSLNegotiationPolicyParseId(d.Id()) + if err != nil { + return err + } // Perversely, if we Set an empty list of PolicyNames, we detach the // policies attached to a listener, which is required to delete the @@ -183,7 +196,16 @@ func resourceAwsLBSSLNegotiationPolicyDelete(d *schema.ResourceData, meta interf // resourceAwsLBSSLNegotiationPolicyParseId takes an ID and parses it into // it's constituent parts. You need three axes (LB name, policy name, and LB // port) to create or identify an SSL negotiation policy in AWS's API. -func resourceAwsLBSSLNegotiationPolicyParseId(id string) (string, string, string) { +func resourceAwsLBSSLNegotiationPolicyParseId(id string) (string, int, string, error) { parts := strings.SplitN(id, ":", 3) - return parts[0], parts[1], parts[2] + if n := len(parts); n != 3 { + return "", 0, "", fmt.Errorf("incorrect format of SSL negotiation policy resource ID. Expected %d parts, got %d", 3, n) + } + + port, err := strconv.Atoi(parts[1]) + if err != nil { + return "", 0, "", fmt.Errorf("error parsing SSL negotiation policy resource ID port: %w", err) + } + + return parts[0], port, parts[2], nil } diff --git a/aws/resource_aws_lb_ssl_negotiation_policy_test.go b/aws/resource_aws_lb_ssl_negotiation_policy_test.go index 31f4b658e22..4c659fb7520 100644 --- a/aws/resource_aws_lb_ssl_negotiation_policy_test.go +++ b/aws/resource_aws_lb_ssl_negotiation_policy_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLBSSLNegotiationPolicy_basic(t *testing.T) { @@ -96,8 +96,12 @@ func testAccCheckLBSSLNegotiationPolicyDestroy(s *terraform.State) error { } } else { // Check that the SSL Negotiation Policy is destroyed - elbName, _, policyName := resourceAwsLBSSLNegotiationPolicyParseId(rs.Primary.ID) - _, err := elbconn.DescribeLoadBalancerPolicies(&elb.DescribeLoadBalancerPoliciesInput{ + elbName, _, policyName, err := resourceAwsLBSSLNegotiationPolicyParseId(rs.Primary.ID) + if err != nil { + return err + } + + _, err = elbconn.DescribeLoadBalancerPolicies(&elb.DescribeLoadBalancerPoliciesInput{ LoadBalancerName: aws.String(elbName), PolicyNames: []*string{aws.String(policyName)}, }) @@ -129,7 +133,11 @@ func testAccCheckLBSSLNegotiationPolicy(elbResource string, policyResource strin elbconn := testAccProvider.Meta().(*AWSClient).elbconn - elbName, _, policyName := resourceAwsLBSSLNegotiationPolicyParseId(policy.Primary.ID) + elbName, _, policyName, err := resourceAwsLBSSLNegotiationPolicyParseId(policy.Primary.ID) + if err != nil { + return err + } + resp, err := elbconn.DescribeLoadBalancerPolicies(&elb.DescribeLoadBalancerPoliciesInput{ LoadBalancerName: aws.String(elbName), PolicyNames: []*string{aws.String(policyName)}, diff --git a/aws/resource_aws_lb_target_group.go b/aws/resource_aws_lb_target_group.go index 7f116eb9790..804ed0a8f53 100644 --- a/aws/resource_aws_lb_target_group.go +++ b/aws/resource_aws_lb_target_group.go @@ -1,18 +1,20 @@ package aws import ( + "context" "errors" "fmt" "log" "regexp" "strconv" "strings" + "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -495,9 +497,29 @@ func resourceAwsLbTargetGroupUpdate(d *schema.ResourceData, meta interface{}) er func resourceAwsLbTargetGroupDelete(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbv2conn - _, err := elbconn.DeleteTargetGroup(&elbv2.DeleteTargetGroupInput{ + input := &elbv2.DeleteTargetGroupInput{ TargetGroupArn: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Deleting Target Group (%s): %s", d.Id(), input) + err := resource.Retry(2*time.Minute, func() *resource.RetryError { + _, err := elbconn.DeleteTargetGroup(input) + + if isAWSErr(err, "ResourceInUse", "is currently in use by a listener or a rule") { + return resource.RetryableError(err) + } + + if err != nil { + return resource.NonRetryableError(err) + } + + return nil }) + + if isResourceTimeoutError(err) { + _, err = elbconn.DeleteTargetGroup(input) + } + if err != nil { return fmt.Errorf("Error deleting Target Group: %s", err) } @@ -701,7 +723,7 @@ func flattenAwsLbTargetGroupStickiness(d *schema.ResourceData, attributes []*elb return nil } -func resourceAwsLbTargetGroupCustomizeDiff(diff *schema.ResourceDiff, v interface{}) error { +func resourceAwsLbTargetGroupCustomizeDiff(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { protocol := diff.Get("protocol").(string) if protocol == elbv2.ProtocolEnumTcp { // TCP load balancers do not support stickiness diff --git a/aws/resource_aws_lb_target_group_attachment.go b/aws/resource_aws_lb_target_group_attachment.go index cb5292d291a..5f971040838 100644 --- a/aws/resource_aws_lb_target_group_attachment.go +++ b/aws/resource_aws_lb_target_group_attachment.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsLbTargetGroupAttachment() *schema.Resource { diff --git a/aws/resource_aws_lb_target_group_attachment_test.go b/aws/resource_aws_lb_target_group_attachment_test.go index 4a6ffa861e7..349c936d8d2 100644 --- a/aws/resource_aws_lb_target_group_attachment_test.go +++ b/aws/resource_aws_lb_target_group_attachment_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLBTargetGroupAttachment_basic(t *testing.T) { @@ -238,11 +238,11 @@ func testAccCheckAWSLBTargetGroupAttachmentDestroy(s *terraform.State) error { } func testAccAWSLBTargetGroupAttachmentConfigInstanceBase() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "available" { # t2.micro instance type is not available in these Availability Zones - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -288,7 +288,7 @@ resource "aws_vpc" "test" { Name = "tf-acc-test-lb-target-group-attachment" } } -`) +` } func testAccAWSLBTargetGroupAttachmentConfigTargetIdInstance(rName string) string { diff --git a/aws/resource_aws_lb_target_group_test.go b/aws/resource_aws_lb_target_group_test.go index 585a9d98ceb..82655eb24c3 100644 --- a/aws/resource_aws_lb_target_group_test.go +++ b/aws/resource_aws_lb_target_group_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -421,7 +421,7 @@ func TestAccAWSLBTargetGroup_TCP_HTTPHealthCheck(t *testing.T) { }) } -func TestAccAWSLBTargetGroupBackwardsCompatibility(t *testing.T) { +func TestAccAWSLBTargetGroup_BackwardsCompatibility(t *testing.T) { var conf elbv2.TargetGroup targetGroupName := fmt.Sprintf("test-target-group-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) resourceName := "aws_alb_target_group.test" diff --git a/aws/resource_aws_lb_test.go b/aws/resource_aws_lb_test.go index f1facebb960..e3d883cc8a0 100644 --- a/aws/resource_aws_lb_test.go +++ b/aws/resource_aws_lb_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elbv2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -191,7 +191,36 @@ func TestAccAWSLB_networkLoadbalancerEIP(t *testing.T) { }) } -func TestAccAWSLBBackwardsCompatibility(t *testing.T) { +func TestAccAWSLB_NLB_privateipv4address(t *testing.T) { + var conf elbv2.LoadBalancer + lbName := fmt.Sprintf("testaccawslb-pipv4a-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) + resourceName := "aws_lb.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSLBDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSLBConfig_networkLoadBalancerPrivateIPV4Address(lbName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSLBExists(resourceName, &conf), + resource.TestCheckResourceAttr(resourceName, "internal", "true"), + resource.TestCheckResourceAttr(resourceName, "load_balancer_type", "network"), + resource.TestCheckResourceAttr(resourceName, "subnet_mapping.#", "1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSLB_BackwardsCompatibility(t *testing.T) { var conf elbv2.LoadBalancer lbName := fmt.Sprintf("testaccawslb-basic-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) resourceName := "aws_alb.lb_test" @@ -1770,6 +1799,54 @@ resource "aws_eip" "lb" { `, lbName) } +func testAccAWSLBConfig_networkLoadBalancerPrivateIPV4Address(lbName string) string { + return fmt.Sprintf(` +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +resource "aws_lb" "test" { + name = "%s" + internal = true + load_balancer_type = "network" + enable_deletion_protection = false + + subnet_mapping { + subnet_id = aws_subnet.test.id + private_ipv4_address = "10.10.0.15" + } + + tags = { + Name = "TestAccAWSALB_privateipv4address" + } +} + +resource "aws_vpc" "test" { + cidr_block = "10.10.0.0/16" + + tags = { + Name = "TestAccAWSALB_privateipv4address" + } +} + +resource "aws_subnet" "test" { + vpc_id = aws_vpc.test.id + cidr_block = "10.10.0.0/21" + map_public_ip_on_launch = true + availability_zone = data.aws_availability_zones.available.names[0] + + tags = { + Name = "TestAccAWSALB_privateipv4address" + } +} +`, lbName) +} + func testAccAWSLBConfigBackwardsCompatibility(lbName string) string { return fmt.Sprintf(` resource "aws_alb" "lb_test" { @@ -1923,7 +2000,7 @@ resource "aws_security_group" "alb_test" { } func testAccAWSLBConfig_generatedName() string { - return fmt.Sprintf(` + return ` resource "aws_lb" "lb_test" { internal = true security_groups = ["${aws_security_group.alb_test.id}"] @@ -2001,11 +2078,11 @@ resource "aws_security_group" "alb_test" { tags = { Name = "TestAccAWSALB_basic" } -}`) +}` } func testAccAWSLBConfig_zeroValueName() string { - return fmt.Sprintf(` + return ` resource "aws_lb" "lb_test" { name = "" internal = true @@ -2089,11 +2166,11 @@ resource "aws_security_group" "alb_test" { tags = { Name = "TestAccAWSALB_basic" } -}`) +}` } func testAccAWSLBConfig_namePrefix() string { - return fmt.Sprintf(` + return ` resource "aws_lb" "lb_test" { name_prefix = "tf-lb-" internal = true @@ -2164,7 +2241,7 @@ resource "aws_security_group" "alb_test" { tags = { Name = "TestAccAWSALB_basic" } -}`) +}` } func testAccAWSLBConfig_updatedTags(lbName string) string { return fmt.Sprintf(` diff --git a/aws/resource_aws_licensemanager_association.go b/aws/resource_aws_licensemanager_association.go index ea58edcf3ee..a378bb18ff0 100644 --- a/aws/resource_aws_licensemanager_association.go +++ b/aws/resource_aws_licensemanager_association.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/licensemanager" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsLicenseManagerAssociation() *schema.Resource { diff --git a/aws/resource_aws_licensemanager_association_test.go b/aws/resource_aws_licensemanager_association_test.go index 4c61c883875..5faddd85319 100644 --- a/aws/resource_aws_licensemanager_association_test.go +++ b/aws/resource_aws_licensemanager_association_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/licensemanager" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLicenseManagerAssociation_basic(t *testing.T) { diff --git a/aws/resource_aws_licensemanager_license_configuration.go b/aws/resource_aws_licensemanager_license_configuration.go index a87fd26aa49..71dcca97554 100644 --- a/aws/resource_aws_licensemanager_license_configuration.go +++ b/aws/resource_aws_licensemanager_license_configuration.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/licensemanager" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_licensemanager_license_configuration_test.go b/aws/resource_aws_licensemanager_license_configuration_test.go index 03bc4fbb4da..bd3abb5728d 100644 --- a/aws/resource_aws_licensemanager_license_configuration_test.go +++ b/aws/resource_aws_licensemanager_license_configuration_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/licensemanager" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_lightsail_domain.go b/aws/resource_aws_lightsail_domain.go index 27fb0278f64..628badfec78 100644 --- a/aws/resource_aws_lightsail_domain.go +++ b/aws/resource_aws_lightsail_domain.go @@ -6,7 +6,7 @@ import ( "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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsLightsailDomain() *schema.Resource { diff --git a/aws/resource_aws_lightsail_domain_test.go b/aws/resource_aws_lightsail_domain_test.go index 2f2c1b033c9..3ded3ef2eb1 100644 --- a/aws/resource_aws_lightsail_domain_test.go +++ b/aws/resource_aws_lightsail_domain_test.go @@ -8,9 +8,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLightsailDomain_basic(t *testing.T) { diff --git a/aws/resource_aws_lightsail_instance.go b/aws/resource_aws_lightsail_instance.go index 46c482d4fe1..9f4cb4a2a14 100644 --- a/aws/resource_aws_lightsail_instance.go +++ b/aws/resource_aws_lightsail_instance.go @@ -4,15 +4,14 @@ import ( "fmt" "log" "regexp" - "strconv" "time" "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-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -89,7 +88,7 @@ func resourceAwsLightsailInstance() *schema.Resource { Computed: true, }, "ram_size": { - Type: schema.TypeInt, + Type: schema.TypeFloat, Computed: true, }, "ipv6_address": { @@ -209,7 +208,7 @@ func resourceAwsLightsailInstanceRead(d *schema.ResourceData, meta interface{}) d.Set("username", i.Username) d.Set("created_at", i.CreatedAt.Format(time.RFC3339)) d.Set("cpu_count", i.Hardware.CpuCount) - d.Set("ram_size", strconv.FormatFloat(*i.Hardware.RamSizeInGb, 'f', 0, 64)) + d.Set("ram_size", i.Hardware.RamSizeInGb) d.Set("ipv6_address", i.Ipv6Address) d.Set("is_static_ip", i.IsStaticIp) d.Set("private_ip_address", i.PrivateIpAddress) diff --git a/aws/resource_aws_lightsail_instance_test.go b/aws/resource_aws_lightsail_instance_test.go index 50d137dd9c9..ff0fca34376 100644 --- a/aws/resource_aws_lightsail_instance_test.go +++ b/aws/resource_aws_lightsail_instance_test.go @@ -12,9 +12,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/lightsail" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -91,6 +91,7 @@ func TestAccAWSLightsailInstance_basic(t *testing.T) { resource.TestCheckResourceAttrSet("aws_lightsail_instance.lightsail_instance_test", "bundle_id"), resource.TestCheckResourceAttrSet("aws_lightsail_instance.lightsail_instance_test", "key_pair_name"), resource.TestCheckResourceAttr("aws_lightsail_instance.lightsail_instance_test", "tags.%", "0"), + resource.TestMatchResourceAttr("aws_lightsail_instance.lightsail_instance_test", "ram_size", regexp.MustCompile(`\d+(.\d+)?`)), ), }, }, diff --git a/aws/resource_aws_lightsail_key_pair.go b/aws/resource_aws_lightsail_key_pair.go index 2979ece10f4..ac97aefc73b 100644 --- a/aws/resource_aws_lightsail_key_pair.go +++ b/aws/resource_aws_lightsail_key_pair.go @@ -8,9 +8,9 @@ import ( "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-plugin-sdk/helper/encryption" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/encryption" ) func resourceAwsLightsailKeyPair() *schema.Resource { diff --git a/aws/resource_aws_lightsail_key_pair_test.go b/aws/resource_aws_lightsail_key_pair_test.go index 8796ba6eeab..46c5945a198 100644 --- a/aws/resource_aws_lightsail_key_pair_test.go +++ b/aws/resource_aws_lightsail_key_pair_test.go @@ -8,9 +8,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLightsailKeyPair_basic(t *testing.T) { @@ -46,7 +46,7 @@ func TestAccAWSLightsailKeyPair_publicKey(t *testing.T) { CheckDestroy: testAccCheckAWSLightsailKeyPairDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSLightsailKeyPairConfig_imported(lightsailName, testLightsailKeyPairPubKey1), + Config: testAccAWSLightsailKeyPairConfig_imported(lightsailName, lightsailPubKey), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSLightsailKeyPairExists("aws_lightsail_key_pair.lightsail_key_pair_test", &conf), resource.TestCheckResourceAttrSet("aws_lightsail_key_pair.lightsail_key_pair_test", "arn"), @@ -175,14 +175,14 @@ resource "aws_lightsail_key_pair" "lightsail_key_pair_test" { `, lightsailName) } -func testAccAWSLightsailKeyPairConfig_imported(lightsailName, key string) string { +func testAccAWSLightsailKeyPairConfig_imported(lightsailName, publicKey string) string { return fmt.Sprintf(` resource "aws_lightsail_key_pair" "lightsail_key_pair_test" { name = "%s" public_key = "%s" } -`, lightsailName, lightsailPubKey) +`, lightsailName, publicKey) } func testAccAWSLightsailKeyPairConfig_encrypted(lightsailName, key string) string { @@ -198,13 +198,13 @@ EOF } func testAccAWSLightsailKeyPairConfig_prefixed() string { - return fmt.Sprintf(` + return ` resource "aws_lightsail_key_pair" "lightsail_key_pair_test_omit" {} resource "aws_lightsail_key_pair" "lightsail_key_pair_test_prefixed" { name_prefix = "cts" } -`) +` } const lightsailPubKey = `ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD3F6tyPEFEzV0LX3X8BsXdMsQz1x2cEikKDEY0aIj41qgxMCP/iteneqXSIFZBp5vizPvaoIR3Um9xK7PGoW8giupGn+EPuxIA4cDM4vzOqOkiMPhz5XK0whEjkVzTo4+S0puvDZuwIsdiW9mxhJc7tgBNL0cYlWSYVkz4G/fslNfRPW5mYAM49f4fhtxPb5ok4Q2Lg9dPKVHO/Bgeu5woMc7RY0p1ej6D4CKFE6lymSDJpW0YHX/wqE9+cfEauh7xZcG0q9t2ta6F6fmX0agvpFyZo8aFbXeUBr7osSCJNgvavWbM/06niWrOvYX2xwWdhXmXSrbX8ZbabVohBK41 phodgson@thoughtworks.com` diff --git a/aws/resource_aws_lightsail_static_ip.go b/aws/resource_aws_lightsail_static_ip.go index 72024ed0ea1..0d64418dfd5 100644 --- a/aws/resource_aws_lightsail_static_ip.go +++ b/aws/resource_aws_lightsail_static_ip.go @@ -6,7 +6,7 @@ import ( "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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsLightsailStaticIp() *schema.Resource { diff --git a/aws/resource_aws_lightsail_static_ip_attachment.go b/aws/resource_aws_lightsail_static_ip_attachment.go index 78709b8a2b3..ffd0acfb111 100644 --- a/aws/resource_aws_lightsail_static_ip_attachment.go +++ b/aws/resource_aws_lightsail_static_ip_attachment.go @@ -6,7 +6,7 @@ import ( "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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsLightsailStaticIpAttachment() *schema.Resource { diff --git a/aws/resource_aws_lightsail_static_ip_attachment_test.go b/aws/resource_aws_lightsail_static_ip_attachment_test.go index 731c310ca5f..51344106765 100644 --- a/aws/resource_aws_lightsail_static_ip_attachment_test.go +++ b/aws/resource_aws_lightsail_static_ip_attachment_test.go @@ -8,9 +8,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLightsailStaticIpAttachment_basic(t *testing.T) { diff --git a/aws/resource_aws_lightsail_static_ip_test.go b/aws/resource_aws_lightsail_static_ip_test.go index 74ff6078f04..4259a1be607 100644 --- a/aws/resource_aws_lightsail_static_ip_test.go +++ b/aws/resource_aws_lightsail_static_ip_test.go @@ -9,9 +9,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_load_balancer_backend_server_policy.go b/aws/resource_aws_load_balancer_backend_server_policy.go index 2db9c73130d..41d9c573def 100644 --- a/aws/resource_aws_load_balancer_backend_server_policy.go +++ b/aws/resource_aws_load_balancer_backend_server_policy.go @@ -8,7 +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/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsLoadBalancerBackendServerPolicies() *schema.Resource { @@ -100,7 +100,11 @@ func resourceAwsLoadBalancerBackendServerPoliciesRead(d *schema.ResourceData, me } d.Set("load_balancer_name", loadBalancerName) - d.Set("instance_port", instancePort) + instancePortVal, err := strconv.ParseInt(instancePort, 10, 64) + if err != nil { + return fmt.Errorf("error parsing instance port: %s", err) + } + d.Set("instance_port", instancePortVal) d.Set("policy_names", flattenStringList(policyNames)) return nil diff --git a/aws/resource_aws_load_balancer_backend_server_policy_test.go b/aws/resource_aws_load_balancer_backend_server_policy_test.go index 51e9f40c3ea..c5f5adcd69e 100644 --- a/aws/resource_aws_load_balancer_backend_server_policy_test.go +++ b/aws/resource_aws_load_balancer_backend_server_policy_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLoadBalancerBackendServerPolicy_basic(t *testing.T) { diff --git a/aws/resource_aws_load_balancer_listener_policy.go b/aws/resource_aws_load_balancer_listener_policy.go index ff7ada242e7..b7979a8eede 100644 --- a/aws/resource_aws_load_balancer_listener_policy.go +++ b/aws/resource_aws_load_balancer_listener_policy.go @@ -8,7 +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/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsLoadBalancerListenerPolicies() *schema.Resource { @@ -100,7 +100,11 @@ func resourceAwsLoadBalancerListenerPoliciesRead(d *schema.ResourceData, meta in } d.Set("load_balancer_name", loadBalancerName) - d.Set("load_balancer_port", loadBalancerPort) + loadBalancerPortVal, err := strconv.ParseInt(loadBalancerPort, 10, 64) + if err != nil { + return fmt.Errorf("error parsing load balancer port: %s", err) + } + d.Set("load_balancer_port", loadBalancerPortVal) d.Set("policy_names", flattenStringList(policyNames)) return nil diff --git a/aws/resource_aws_load_balancer_listener_policy_test.go b/aws/resource_aws_load_balancer_listener_policy_test.go index 356f787f9cf..134078dc83b 100644 --- a/aws/resource_aws_load_balancer_listener_policy_test.go +++ b/aws/resource_aws_load_balancer_listener_policy_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLoadBalancerListenerPolicy_basic(t *testing.T) { diff --git a/aws/resource_aws_load_balancer_policy.go b/aws/resource_aws_load_balancer_policy.go index ac473f0332c..d151aaa6b80 100644 --- a/aws/resource_aws_load_balancer_policy.go +++ b/aws/resource_aws_load_balancer_policy.go @@ -8,7 +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/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsLoadBalancerPolicy() *schema.Resource { diff --git a/aws/resource_aws_load_balancer_policy_test.go b/aws/resource_aws_load_balancer_policy_test.go index 1cb979ee14c..f53a47b53b7 100644 --- a/aws/resource_aws_load_balancer_policy_test.go +++ b/aws/resource_aws_load_balancer_policy_test.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSLoadBalancerPolicy_basic(t *testing.T) { diff --git a/aws/resource_aws_macie_member_account_association.go b/aws/resource_aws_macie_member_account_association.go index 7a81851dfa8..f3f0e5be529 100644 --- a/aws/resource_aws_macie_member_account_association.go +++ b/aws/resource_aws_macie_member_account_association.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/macie" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsMacieMemberAccountAssociation() *schema.Resource { diff --git a/aws/resource_aws_macie_member_account_association_test.go b/aws/resource_aws_macie_member_account_association_test.go index 1918683078c..124bfbac159 100644 --- a/aws/resource_aws_macie_member_account_association_test.go +++ b/aws/resource_aws_macie_member_account_association_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/macie" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSMacieMemberAccountAssociation_basic(t *testing.T) { diff --git a/aws/resource_aws_macie_s3_bucket_association.go b/aws/resource_aws_macie_s3_bucket_association.go index e7c53af2907..2f350dcf86a 100644 --- a/aws/resource_aws_macie_s3_bucket_association.go +++ b/aws/resource_aws_macie_s3_bucket_association.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/macie" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsMacieS3BucketAssociation() *schema.Resource { diff --git a/aws/resource_aws_macie_s3_bucket_association_test.go b/aws/resource_aws_macie_s3_bucket_association_test.go index 793e5d4a3f3..f8bf9b4f2e9 100644 --- a/aws/resource_aws_macie_s3_bucket_association_test.go +++ b/aws/resource_aws_macie_s3_bucket_association_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/macie" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSMacieS3BucketAssociation_basic(t *testing.T) { diff --git a/aws/resource_aws_main_route_table_association.go b/aws/resource_aws_main_route_table_association.go index 4aca0fed7e8..3d148b09c76 100644 --- a/aws/resource_aws_main_route_table_association.go +++ b/aws/resource_aws_main_route_table_association.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsMainRouteTableAssociation() *schema.Resource { diff --git a/aws/resource_aws_main_route_table_association_test.go b/aws/resource_aws_main_route_table_association_test.go index e63a43e561b..6d63835ca67 100644 --- a/aws/resource_aws_main_route_table_association_test.go +++ b/aws/resource_aws_main_route_table_association_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSMainRouteTableAssociation_basic(t *testing.T) { @@ -18,21 +18,13 @@ func TestAccAWSMainRouteTableAssociation_basic(t *testing.T) { { Config: testAccMainRouteTableAssociationConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckMainRouteTableAssociation( - "aws_main_route_table_association.foo", - "aws_vpc.foo", - "aws_route_table.foo", - ), + testAccCheckMainRouteTableAssociation("aws_main_route_table_association.foo", "aws_vpc.foo"), ), }, { Config: testAccMainRouteTableAssociationConfigUpdate, Check: resource.ComposeTestCheckFunc( - testAccCheckMainRouteTableAssociation( - "aws_main_route_table_association.foo", - "aws_vpc.foo", - "aws_route_table.bar", - ), + testAccCheckMainRouteTableAssociation("aws_main_route_table_association.foo", "aws_vpc.foo"), ), }, }, @@ -67,10 +59,7 @@ func testAccCheckMainRouteTableAssociationDestroy(s *terraform.State) error { return nil } -func testAccCheckMainRouteTableAssociation( - mainRouteTableAssociationResource string, - vpcResource string, - routeTableResource string) resource.TestCheckFunc { +func testAccCheckMainRouteTableAssociation(mainRouteTableAssociationResource string, vpcResource string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[mainRouteTableAssociationResource] if !ok { diff --git a/aws/resource_aws_media_convert_queue.go b/aws/resource_aws_media_convert_queue.go index b1c6b541910..5792b8ec34a 100644 --- a/aws/resource_aws_media_convert_queue.go +++ b/aws/resource_aws_media_convert_queue.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/mediaconvert" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -174,7 +174,7 @@ func resourceAwsMediaConvertQueueUpdate(d *schema.ResourceData, meta interface{} return fmt.Errorf("Error getting Media Convert Account Client: %s", err) } - if d.HasChange("description") || d.HasChange("reservation_plan_settings") || d.HasChange("status") { + if d.HasChanges("description", "reservation_plan_settings", "status") { updateOpts := &mediaconvert.UpdateQueueInput{ Name: aws.String(d.Id()), diff --git a/aws/resource_aws_media_convert_queue_test.go b/aws/resource_aws_media_convert_queue_test.go index d033c935dab..ffc32e89a45 100644 --- a/aws/resource_aws_media_convert_queue_test.go +++ b/aws/resource_aws_media_convert_queue_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mediaconvert" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSMediaConvertQueue_basic(t *testing.T) { @@ -43,7 +43,7 @@ func TestAccAWSMediaConvertQueue_basic(t *testing.T) { } func TestAccAWSMediaConvertQueue_ReservationPlanSettings(t *testing.T) { - t.Skip("MediaConvert Reserved Queues are $400/month and cannot be deleted for 1 year.") + TestAccSkip(t, "MediaConvert Reserved Queues are $400/month and cannot be deleted for 1 year.") var queue mediaconvert.Queue resourceName := "aws_media_convert_queue.test" diff --git a/aws/resource_aws_media_package_channel.go b/aws/resource_aws_media_package_channel.go index 1e211e12f25..f7e6e3a98d5 100644 --- a/aws/resource_aws_media_package_channel.go +++ b/aws/resource_aws_media_package_channel.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mediapackage" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_media_package_channel_test.go b/aws/resource_aws_media_package_channel_test.go index ae0abda207f..eb0b8cf4415 100644 --- a/aws/resource_aws_media_package_channel_test.go +++ b/aws/resource_aws_media_package_channel_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mediapackage" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSMediaPackageChannel_basic(t *testing.T) { diff --git a/aws/resource_aws_media_store_container.go b/aws/resource_aws_media_store_container.go index fc1e1c85eb3..efdd262260a 100644 --- a/aws/resource_aws_media_store_container.go +++ b/aws/resource_aws_media_store_container.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mediastore" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_media_store_container_policy.go b/aws/resource_aws_media_store_container_policy.go index 9b370c07249..b0fe53fdb8a 100644 --- a/aws/resource_aws_media_store_container_policy.go +++ b/aws/resource_aws_media_store_container_policy.go @@ -5,7 +5,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mediastore" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsMediaStoreContainerPolicy() *schema.Resource { diff --git a/aws/resource_aws_media_store_container_policy_test.go b/aws/resource_aws_media_store_container_policy_test.go index 83fe451da2d..7a705312444 100644 --- a/aws/resource_aws_media_store_container_policy_test.go +++ b/aws/resource_aws_media_store_container_policy_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mediastore" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSMediaStoreContainerPolicy_basic(t *testing.T) { diff --git a/aws/resource_aws_media_store_container_test.go b/aws/resource_aws_media_store_container_test.go index f3fddec938d..6d4dfbaa970 100644 --- a/aws/resource_aws_media_store_container_test.go +++ b/aws/resource_aws_media_store_container_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mediastore" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSMediaStoreContainer_basic(t *testing.T) { diff --git a/aws/resource_aws_mq_broker.go b/aws/resource_aws_mq_broker.go index 8a47b3f7164..5b81fd20cc8 100644 --- a/aws/resource_aws_mq_broker.go +++ b/aws/resource_aws_mq_broker.go @@ -9,11 +9,11 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mq" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/mitchellh/copystructure" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -424,7 +424,7 @@ func resourceAwsMqBrokerUpdate(d *schema.ResourceData, meta interface{}) error { } } - if d.HasChange("configuration") || d.HasChange("logs") { + if d.HasChanges("configuration", "logs") { _, err := conn.UpdateBroker(&mq.UpdateBrokerRequest{ BrokerId: aws.String(d.Id()), Configuration: expandMqConfigurationId(d.Get("configuration").([]interface{})), diff --git a/aws/resource_aws_mq_broker_test.go b/aws/resource_aws_mq_broker_test.go index a33a6635a55..27bc2adaa45 100644 --- a/aws/resource_aws_mq_broker_test.go +++ b/aws/resource_aws_mq_broker_test.go @@ -9,10 +9,11 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mq" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -240,10 +241,9 @@ func TestAccAWSMqBroker_basic(t *testing.T) { resourceName := "aws_mq_broker.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSMq(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAwsMqBrokerDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSMq(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsMqBrokerDestroy, Steps: []resource.TestStep{ { Config: testAccMqBrokerConfig(sgName, brokerName), @@ -271,10 +271,12 @@ func TestAccAWSMqBroker_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "security_groups.#", "1"), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "1"), resource.TestCheckResourceAttr(resourceName, "user.#", "1"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.console_access", "false"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.username", "Test"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.password", "TestTest1234"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ + "console_access": "false", + "groups.#": "0", + "username": "Test", + "password": "TestTest1234", + }), testAccMatchResourceAttrRegionalARN(resourceName, "arn", "mq", regexp.MustCompile(`broker:+.`)), resource.TestCheckResourceAttr(resourceName, "instances.#", "1"), resource.TestMatchResourceAttr(resourceName, "instances.0.console_url", @@ -320,10 +322,9 @@ func TestAccAWSMqBroker_allFieldsDefaultVpc(t *testing.T) { ` resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSMq(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAwsMqBrokerDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSMq(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsMqBrokerDestroy, Steps: []resource.TestStep{ { Config: testAccMqBrokerConfig_allFieldsDefaultVpc(sgName, cfgNameBefore, cfgBodyBefore, brokerName), @@ -349,17 +350,21 @@ func TestAccAWSMqBroker_allFieldsDefaultVpc(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "security_groups.#", "2"), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "2"), resource.TestCheckResourceAttr(resourceName, "user.#", "2"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.console_access", "true"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.groups.#", "3"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.groups.2456940119", "first"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.groups.3055489385", "second"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.groups.607264868", "third"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.password", "SecondTestTest1234"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.username", "SecondTest"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.console_access", "false"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.password", "TestTest1234"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.username", "Test"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ + "console_access": "true", + "groups.#": "3", + "username": "SecondTest", + "password": "SecondTestTest1234", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "user.*.groups.*", "first"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "user.*.groups.*", "second"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "user.*.groups.*", "third"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ + "console_access": "false", + "groups.#": "0", + "username": "Test", + "password": "TestTest1234", + }), testAccMatchResourceAttrRegionalARN(resourceName, "arn", "mq", regexp.MustCompile(`broker:+.`)), resource.TestCheckResourceAttr(resourceName, "instances.#", "2"), resource.TestMatchResourceAttr(resourceName, "instances.0.console_url", @@ -437,10 +442,9 @@ func TestAccAWSMqBroker_allFieldsCustomVpc(t *testing.T) { ` resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSMq(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAwsMqBrokerDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSMq(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsMqBrokerDestroy, Steps: []resource.TestStep{ { Config: testAccMqBrokerConfig_allFieldsCustomVpc(sgName, cfgNameBefore, cfgBodyBefore, brokerName), @@ -466,17 +470,21 @@ func TestAccAWSMqBroker_allFieldsCustomVpc(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "security_groups.#", "2"), resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "2"), resource.TestCheckResourceAttr(resourceName, "user.#", "2"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.console_access", "true"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.groups.#", "3"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.groups.2456940119", "first"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.groups.3055489385", "second"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.groups.607264868", "third"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.password", "SecondTestTest1234"), - resource.TestCheckResourceAttr(resourceName, "user.1344916805.username", "SecondTest"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.console_access", "false"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.password", "TestTest1234"), - resource.TestCheckResourceAttr(resourceName, "user.3793764891.username", "Test"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ + "console_access": "true", + "groups.#": "3", + "username": "SecondTest", + "password": "SecondTestTest1234", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "user.*.groups.*", "first"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "user.*.groups.*", "second"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "user.*.groups.*", "third"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ + "console_access": "false", + "groups.#": "0", + "username": "Test", + "password": "TestTest1234", + }), testAccMatchResourceAttrRegionalARN(resourceName, "arn", "mq", regexp.MustCompile(`broker:+.`)), resource.TestCheckResourceAttr(resourceName, "instances.#", "2"), resource.TestMatchResourceAttr(resourceName, "instances.0.console_url", @@ -626,20 +634,21 @@ func TestAccAWSMqBroker_updateUsers(t *testing.T) { resourceName := "aws_mq_broker.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSMq(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAwsMqBrokerDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSMq(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsMqBrokerDestroy, Steps: []resource.TestStep{ { Config: testAccMqBrokerConfig_updateUsers1(sgName, brokerName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsMqBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "user.#", "1"), - resource.TestCheckResourceAttr(resourceName, "user.3400735725.console_access", "false"), - resource.TestCheckResourceAttr(resourceName, "user.3400735725.groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "user.3400735725.password", "TestTest1111"), - resource.TestCheckResourceAttr(resourceName, "user.3400735725.username", "first"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ + "console_access": "false", + "groups.#": "0", + "username": "first", + "password": "TestTest1111", + }), ), }, { @@ -654,14 +663,18 @@ func TestAccAWSMqBroker_updateUsers(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsMqBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "user.#", "2"), - resource.TestCheckResourceAttr(resourceName, "user.1074486012.console_access", "false"), - resource.TestCheckResourceAttr(resourceName, "user.1074486012.groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "user.1074486012.password", "TestTest2222"), - resource.TestCheckResourceAttr(resourceName, "user.1074486012.username", "second"), - resource.TestCheckResourceAttr(resourceName, "user.1166726986.console_access", "true"), - resource.TestCheckResourceAttr(resourceName, "user.1166726986.groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "user.1166726986.password", "TestTest1111updated"), - resource.TestCheckResourceAttr(resourceName, "user.1166726986.username", "first"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ + "console_access": "false", + "groups.#": "0", + "username": "second", + "password": "TestTest2222", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ + "console_access": "true", + "groups.#": "0", + "username": "first", + "password": "TestTest1111updated", + }), ), }, // Deleting user + modify existing @@ -670,11 +683,13 @@ func TestAccAWSMqBroker_updateUsers(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsMqBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "user.#", "1"), - resource.TestCheckResourceAttr(resourceName, "user.2244717082.console_access", "false"), - resource.TestCheckResourceAttr(resourceName, "user.2244717082.groups.#", "1"), - resource.TestCheckResourceAttr(resourceName, "user.2244717082.groups.2282622326", "admin"), - resource.TestCheckResourceAttr(resourceName, "user.2244717082.password", "TestTest2222"), - resource.TestCheckResourceAttr(resourceName, "user.2244717082.username", "second"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ + "console_access": "false", + "groups.#": "1", + "username": "second", + "password": "TestTest2222", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "user.*.groups.*", "admin"), ), }, }, @@ -736,10 +751,9 @@ func TestAccAWSMqBroker_updateSecurityGroup(t *testing.T) { resourceName := "aws_mq_broker.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSMq(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAwsMqBrokerDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSMq(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsMqBrokerDestroy, Steps: []resource.TestStep{ { Config: testAccMqBrokerConfig(sgName, brokerName), @@ -769,8 +783,10 @@ func TestAccAWSMqBroker_updateSecurityGroup(t *testing.T) { testAccCheckAwsMqBrokerExists(resourceName, &broker), resource.TestCheckResourceAttr(resourceName, "security_groups.#", "1"), resource.TestCheckResourceAttr(resourceName, "user.#", "1"), - resource.TestCheckResourceAttr(resourceName, "user.2209734970.username", "Test"), - resource.TestCheckResourceAttr(resourceName, "user.2209734970.password", "TestTest9999"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "user.*", map[string]string{ + "username": "Test", + "password": "TestTest9999", + }), ), }, }, diff --git a/aws/resource_aws_mq_configuration.go b/aws/resource_aws_mq_configuration.go index 884cef2e971..6d3eb0785cb 100644 --- a/aws/resource_aws_mq_configuration.go +++ b/aws/resource_aws_mq_configuration.go @@ -1,14 +1,15 @@ package aws import ( + "context" "encoding/base64" "fmt" "log" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mq" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -21,7 +22,7 @@ func resourceAwsMqConfiguration() *schema.Resource { Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, - CustomizeDiff: func(diff *schema.ResourceDiff, v interface{}) error { + CustomizeDiff: func(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { if diff.HasChange("description") { return diff.SetNewComputed("latest_revision") } diff --git a/aws/resource_aws_mq_configuration_test.go b/aws/resource_aws_mq_configuration_test.go index dff90f465fa..8d3c507fc7d 100644 --- a/aws/resource_aws_mq_configuration_test.go +++ b/aws/resource_aws_mq_configuration_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/mq" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSMqConfiguration_basic(t *testing.T) { diff --git a/aws/resource_aws_msk_cluster.go b/aws/resource_aws_msk_cluster.go index 0330e580126..d6688b6a86b 100644 --- a/aws/resource_aws_msk_cluster.go +++ b/aws/resource_aws_msk_cluster.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kafka" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -166,7 +166,7 @@ func resourceAwsMskCluster() *schema.Resource { Type: schema.TypeString, Optional: true, ForceNew: true, - Default: kafka.ClientBrokerTlsPlaintext, + Default: kafka.ClientBrokerTls, ValidateFunc: validation.StringInSlice([]string{ kafka.ClientBrokerPlaintext, kafka.ClientBrokerTlsPlaintext, @@ -537,7 +537,7 @@ func resourceAwsMskClusterUpdate(d *schema.ResourceData, meta interface{}) error } } - if d.HasChange("enhanced_monitoring") || d.HasChange("open_monitoring") || d.HasChange("logging_info") { + if d.HasChanges("enhanced_monitoring", "open_monitoring", "logging_info") { input := &kafka.UpdateMonitoringInput{ ClusterArn: aws.String(d.Id()), CurrentVersion: aws.String(d.Get("current_version").(string)), diff --git a/aws/resource_aws_msk_cluster_test.go b/aws/resource_aws_msk_cluster_test.go index 9ba563e2b35..0f333564533 100644 --- a/aws/resource_aws_msk_cluster_test.go +++ b/aws/resource_aws_msk_cluster_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kafka" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -71,7 +71,7 @@ func TestAccAWSMskCluster_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckMskClusterExists(resourceName, &cluster), testAccMatchResourceAttrRegionalARN(resourceName, "arn", "kafka", regexp.MustCompile(`cluster/.+`)), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers", regexp.MustCompile(`^(([-\w]+\.){1,}[\w]+:\d+,){2,}([-\w]+\.){1,}[\w]+:\d+$`)), + resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", regexp.MustCompile(`^(([-\w]+\.){1,}[\w]+:\d+,){2,}([-\w]+\.){1,}[\w]+:\d+$`)), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.0.az_distribution", kafka.BrokerAZDistributionDefault), @@ -89,7 +89,7 @@ func TestAccAWSMskCluster_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "encryption_info.#", "1"), testAccMatchResourceAttrRegionalARN(resourceName, "encryption_info.0.encryption_at_rest_kms_key_arn", "kms", regexp.MustCompile(`key/.+`)), resource.TestCheckResourceAttr(resourceName, "encryption_info.0.encryption_in_transit.#", "1"), - resource.TestCheckResourceAttr(resourceName, "encryption_info.0.encryption_in_transit.0.client_broker", "TLS_PLAINTEXT"), + resource.TestCheckResourceAttr(resourceName, "encryption_info.0.encryption_in_transit.0.client_broker", "TLS"), resource.TestCheckResourceAttr(resourceName, "encryption_info.0.encryption_in_transit.0.in_cluster", "true"), resource.TestCheckResourceAttr(resourceName, "enhanced_monitoring", kafka.EnhancedMonitoringDefault), resource.TestCheckResourceAttr(resourceName, "kafka_version", "2.2.1"), @@ -153,7 +153,7 @@ func TestAccAWSMskCluster_BrokerNodeGroupInfo_EbsVolumeSize(t *testing.T) { } func TestAccAWSMskCluster_ClientAuthentication_Tls_CertificateAuthorityArns(t *testing.T) { - t.Skip("Requires the aws_acmpca_certificate_authority resource to support importing the root CA certificate") + TestAccSkip(t, "Requires the aws_acmpca_certificate_authority resource to support importing the root CA certificate") var cluster1 kafka.ClusterInfo rName := acctest.RandomWithPrefix("tf-acc-test") @@ -187,7 +187,7 @@ func TestAccAWSMskCluster_ClientAuthentication_Tls_CertificateAuthorityArns(t *t } func TestAccAWSMskCluster_ConfigurationInfo_Revision(t *testing.T) { - t.Skip("aws_msk_cluster is correctly calling UpdateClusterConfiguration however API is always returning 429 and 500 errors") + TestAccSkip(t, "aws_msk_cluster is correctly calling UpdateClusterConfiguration however API is always returning 429 and 500 errors") var cluster1, cluster2 kafka.ClusterInfo rName := acctest.RandomWithPrefix("tf-acc-test") @@ -377,7 +377,7 @@ func TestAccAWSMskCluster_NumberOfBrokerNodes(t *testing.T) { Config: testAccMskClusterConfigNumberOfBrokerNodes(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckMskClusterExists(resourceName, &cluster1), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers", regexp.MustCompile(`^(([-\w]+\.){1,}[\w]+:\d+,){2,}([-\w]+\.){1,}[\w]+:\d+$`)), + resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", regexp.MustCompile(`^(([-\w]+\.){1,}[\w]+:\d+,){2,}([-\w]+\.){1,}[\w]+:\d+$`)), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.0.client_subnets.#", "3"), @@ -401,7 +401,7 @@ func TestAccAWSMskCluster_NumberOfBrokerNodes(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckMskClusterExists(resourceName, &cluster2), testAccCheckMskClusterNotRecreated(&cluster1, &cluster2), - resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers", regexp.MustCompile(`^(([-\w]+\.){1,}[\w]+:\d+,){2,}([-\w]+\.){1,}[\w]+:\d+$`)), + resource.TestCheckResourceAttr(resourceName, "bootstrap_brokers", ""), resource.TestMatchResourceAttr(resourceName, "bootstrap_brokers_tls", regexp.MustCompile(`^(([-\w]+\.){1,}[\w]+:\d+,){2,}([-\w]+\.){1,}[\w]+:\d+$`)), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.#", "1"), resource.TestCheckResourceAttr(resourceName, "broker_node_group_info.0.client_subnets.#", "3"), @@ -666,7 +666,7 @@ func testAccPreCheckAWSMsk(t *testing.T) { } func testAccMskClusterBaseConfig() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "example_vpc" { cidr_block = "192.168.0.0/22" @@ -717,7 +717,7 @@ resource "aws_subnet" "example_subnet_az3" { resource "aws_security_group" "example_sg" { vpc_id = "${aws_vpc.example_vpc.id}" } -`) +` } func testAccMskClusterConfig_basic(rName string) string { @@ -727,12 +727,6 @@ resource "aws_msk_cluster" "test" { kafka_version = "2.2.1" number_of_broker_nodes = 3 - encryption_info { - encryption_in_transit { - client_broker = "TLS_PLAINTEXT" - } - } - broker_node_group_info { client_subnets = ["${aws_subnet.example_subnet_az1.id}", "${aws_subnet.example_subnet_az2.id}", "${aws_subnet.example_subnet_az3.id}"] ebs_volume_size = 10 @@ -750,12 +744,6 @@ resource "aws_msk_cluster" "test" { kafka_version = "2.2.1" number_of_broker_nodes = 3 - encryption_info { - encryption_in_transit { - client_broker = "TLS_PLAINTEXT" - } - } - broker_node_group_info { client_subnets = ["${aws_subnet.example_subnet_az1.id}", "${aws_subnet.example_subnet_az2.id}", "${aws_subnet.example_subnet_az3.id}"] ebs_volume_size = %[2]d @@ -822,12 +810,6 @@ resource "aws_msk_cluster" "test" { kafka_version = "2.2.1" number_of_broker_nodes = 3 - encryption_info { - encryption_in_transit { - client_broker = "TLS_PLAINTEXT" - } - } - broker_node_group_info { client_subnets = ["${aws_subnet.example_subnet_az1.id}", "${aws_subnet.example_subnet_az2.id}", "${aws_subnet.example_subnet_az3.id}"] ebs_volume_size = 10 @@ -904,9 +886,6 @@ resource "aws_msk_cluster" "test" { encryption_info { encryption_at_rest_kms_key_arn = "${aws_kms_key.example_key.arn}" - encryption_in_transit { - client_broker = "TLS_PLAINTEXT" - } } } `, rName) @@ -952,7 +931,6 @@ resource "aws_msk_cluster" "test" { encryption_info { encryption_in_transit { - client_broker = "TLS_PLAINTEXT" in_cluster = %[2]t } } @@ -968,12 +946,6 @@ resource "aws_msk_cluster" "test" { kafka_version = "2.2.1" number_of_broker_nodes = 3 - encryption_info { - encryption_in_transit { - client_broker = "TLS_PLAINTEXT" - } - } - broker_node_group_info { client_subnets = ["${aws_subnet.example_subnet_az1.id}", "${aws_subnet.example_subnet_az2.id}", "${aws_subnet.example_subnet_az3.id}"] ebs_volume_size = 10 @@ -992,12 +964,6 @@ resource "aws_msk_cluster" "test" { kafka_version = "2.2.1" number_of_broker_nodes = %[2]d - encryption_info { - encryption_in_transit { - client_broker = "TLS_PLAINTEXT" - } - } - broker_node_group_info { client_subnets = ["${aws_subnet.example_subnet_az1.id}", "${aws_subnet.example_subnet_az2.id}", "${aws_subnet.example_subnet_az3.id}"] ebs_volume_size = 10 @@ -1016,12 +982,6 @@ resource "aws_msk_cluster" "test" { kafka_version = "2.2.1" number_of_broker_nodes = 3 - encryption_info { - encryption_in_transit { - client_broker = "TLS_PLAINTEXT" - } - } - broker_node_group_info { client_subnets = ["${aws_subnet.example_subnet_az1.id}", "${aws_subnet.example_subnet_az2.id}", "${aws_subnet.example_subnet_az3.id}"] ebs_volume_size = 10 @@ -1114,12 +1074,6 @@ resource "aws_msk_cluster" "test" { kafka_version = "2.2.1" number_of_broker_nodes = 3 - encryption_info { - encryption_in_transit { - client_broker = "TLS_PLAINTEXT" - } - } - broker_node_group_info { client_subnets = ["${aws_subnet.example_subnet_az1.id}", "${aws_subnet.example_subnet_az2.id}", "${aws_subnet.example_subnet_az3.id}"] ebs_volume_size = 10 @@ -1155,12 +1109,6 @@ resource "aws_msk_cluster" "test" { kafka_version = "2.2.1" number_of_broker_nodes = 3 - encryption_info { - encryption_in_transit { - client_broker = "TLS_PLAINTEXT" - } - } - broker_node_group_info { client_subnets = ["${aws_subnet.example_subnet_az1.id}", "${aws_subnet.example_subnet_az2.id}", "${aws_subnet.example_subnet_az3.id}"] ebs_volume_size = 10 @@ -1182,12 +1130,6 @@ resource "aws_msk_cluster" "test" { kafka_version = "2.2.1" number_of_broker_nodes = 3 - encryption_info { - encryption_in_transit { - client_broker = "TLS_PLAINTEXT" - } - } - broker_node_group_info { client_subnets = ["${aws_subnet.example_subnet_az1.id}", "${aws_subnet.example_subnet_az2.id}", "${aws_subnet.example_subnet_az3.id}"] ebs_volume_size = 10 diff --git a/aws/resource_aws_msk_configuration.go b/aws/resource_aws_msk_configuration.go index 862d4befa15..86fa4d97b30 100644 --- a/aws/resource_aws_msk_configuration.go +++ b/aws/resource_aws_msk_configuration.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kafka" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsMskConfiguration() *schema.Resource { diff --git a/aws/resource_aws_msk_configuration_test.go b/aws/resource_aws_msk_configuration_test.go index 59040233599..47c863a9a29 100644 --- a/aws/resource_aws_msk_configuration_test.go +++ b/aws/resource_aws_msk_configuration_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/kafka" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSMskConfiguration_basic(t *testing.T) { diff --git a/aws/resource_aws_nat_gateway.go b/aws/resource_aws_nat_gateway.go index 9639fcf3f62..5d4d23e4552 100644 --- a/aws/resource_aws_nat_gateway.go +++ b/aws/resource_aws_nat_gateway.go @@ -9,8 +9,8 @@ import ( "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-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_nat_gateway_test.go b/aws/resource_aws_nat_gateway_test.go index d041ad9f9e6..2b6648dd5b8 100644 --- a/aws/resource_aws_nat_gateway_test.go +++ b/aws/resource_aws_nat_gateway_test.go @@ -9,8 +9,8 @@ import ( "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-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_neptune_cluster.go b/aws/resource_aws_neptune_cluster.go index 9b26405ab12..9563277e3b8 100644 --- a/aws/resource_aws_neptune_cluster.go +++ b/aws/resource_aws_neptune_cluster.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -21,6 +21,8 @@ const ( // is not currently available in the AWS sdk-for-go // https://docs.aws.amazon.com/sdk-for-go/api/service/neptune/#pkg-constants CloudwatchLogsExportsAudit = "audit" + + neptuneDefaultPort = 8182 ) func resourceAwsNeptuneCluster() *schema.Resource { @@ -194,7 +196,7 @@ func resourceAwsNeptuneCluster() *schema.Resource { "port": { Type: schema.TypeInt, Optional: true, - Default: 8182, + Default: neptuneDefaultPort, ForceNew: true, }, diff --git a/aws/resource_aws_neptune_cluster_instance.go b/aws/resource_aws_neptune_cluster_instance.go index 87d7738974a..867b7869ee4 100644 --- a/aws/resource_aws_neptune_cluster_instance.go +++ b/aws/resource_aws_neptune_cluster_instance.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -134,7 +134,7 @@ func resourceAwsNeptuneClusterInstance() *schema.Resource { "port": { Type: schema.TypeInt, Optional: true, - Default: 8182, + Default: neptuneDefaultPort, ForceNew: true, }, diff --git a/aws/resource_aws_neptune_cluster_instance_test.go b/aws/resource_aws_neptune_cluster_instance_test.go index 0e913a1ce31..6c320f5f32f 100644 --- a/aws/resource_aws_neptune_cluster_instance_test.go +++ b/aws/resource_aws_neptune_cluster_instance_test.go @@ -3,18 +3,26 @@ package aws import ( "fmt" "regexp" + "strconv" "strings" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSNeptuneClusterInstance_basic(t *testing.T) { var v neptune.DBInstance + rInt := acctest.RandInt() + + resourceName := "aws_neptune_cluster_instance.cluster_instances" + clusterResourceName := "aws_neptune_cluster.default" + parameterGroupResourceName := "aws_neptune_parameter_group.test" + + clusterInstanceName := fmt.Sprintf("tf-cluster-instance-%d", rInt) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -22,40 +30,38 @@ func TestAccAWSNeptuneClusterInstance_basic(t *testing.T) { CheckDestroy: testAccCheckAWSNeptuneClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSNeptuneClusterInstanceConfig(acctest.RandInt()), + Config: testAccAWSNeptuneClusterInstanceConfig(clusterInstanceName, rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterInstanceExists("aws_neptune_cluster_instance.cluster_instances", &v), + testAccCheckAWSNeptuneClusterInstanceExists(resourceName, &v), testAccCheckAWSNeptuneClusterInstanceAttributes(&v), - resource.TestCheckResourceAttrSet("aws_neptune_cluster_instance.cluster_instances", "address"), - resource.TestMatchResourceAttr("aws_neptune_cluster_instance.cluster_instances", "arn", regexp.MustCompile(`^arn:[^:]+:rds:[^:]+:[^:]+:db:.+`)), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "auto_minor_version_upgrade", "true"), - resource.TestMatchResourceAttr("aws_neptune_cluster_instance.cluster_instances", "availability_zone", regexp.MustCompile(fmt.Sprintf("^%s", testAccGetRegion()))), - resource.TestCheckResourceAttrSet("aws_neptune_cluster_instance.cluster_instances", "cluster_identifier"), - resource.TestCheckResourceAttrSet("aws_neptune_cluster_instance.cluster_instances", "dbi_resource_id"), - resource.TestMatchResourceAttr("aws_neptune_cluster_instance.cluster_instances", "endpoint", regexp.MustCompile(`:8182$`)), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "engine", "neptune"), - resource.TestCheckResourceAttrSet("aws_neptune_cluster_instance.cluster_instances", "engine_version"), - resource.TestCheckResourceAttrSet("aws_neptune_cluster_instance.cluster_instances", "identifier"), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "instance_class", "db.r4.large"), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "kms_key_arn", ""), - resource.TestMatchResourceAttr("aws_neptune_cluster_instance.cluster_instances", "neptune_parameter_group_name", regexp.MustCompile(`^tf-cluster-test-group-`)), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "neptune_subnet_group_name", "default"), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "port", "8182"), - resource.TestCheckResourceAttrSet("aws_neptune_cluster_instance.cluster_instances", "preferred_backup_window"), - resource.TestCheckResourceAttrSet("aws_neptune_cluster_instance.cluster_instances", "preferred_maintenance_window"), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "promotion_tier", "3"), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "publicly_accessible", "false"), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "storage_encrypted", "false"), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "tags.%", "0"), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "writer", "true"), + testAccCheckNeptuneClusterAddress(&v, resourceName, neptuneDefaultPort), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "rds", fmt.Sprintf("db:%s", clusterInstanceName)), + resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "true"), + resource.TestMatchResourceAttr(resourceName, "availability_zone", regexp.MustCompile(fmt.Sprintf("^%s[a-z]{1}$", testAccGetRegion()))), + resource.TestCheckResourceAttrPair(resourceName, "cluster_identifier", clusterResourceName, "id"), + resource.TestCheckResourceAttrSet(resourceName, "dbi_resource_id"), + resource.TestCheckResourceAttr(resourceName, "engine", "neptune"), + resource.TestCheckResourceAttrSet(resourceName, "engine_version"), + resource.TestCheckResourceAttr(resourceName, "identifier", clusterInstanceName), + resource.TestCheckResourceAttr(resourceName, "instance_class", "db.r4.large"), + resource.TestCheckResourceAttr(resourceName, "kms_key_arn", ""), + resource.TestCheckResourceAttrPair(resourceName, "neptune_parameter_group_name", parameterGroupResourceName, "name"), + resource.TestCheckResourceAttr(resourceName, "neptune_subnet_group_name", "default"), + resource.TestCheckResourceAttrSet(resourceName, "preferred_backup_window"), + resource.TestCheckResourceAttrSet(resourceName, "preferred_maintenance_window"), + resource.TestCheckResourceAttr(resourceName, "promotion_tier", "3"), + resource.TestCheckResourceAttr(resourceName, "publicly_accessible", "false"), + resource.TestCheckResourceAttr(resourceName, "storage_encrypted", "false"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "writer", "true"), ), }, { - Config: testAccAWSNeptuneClusterInstanceConfigModified(acctest.RandInt()), + Config: testAccAWSNeptuneClusterInstanceConfigModified(clusterInstanceName, rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterInstanceExists("aws_neptune_cluster_instance.cluster_instances", &v), + testAccCheckAWSNeptuneClusterInstanceExists(resourceName, &v), testAccCheckAWSNeptuneClusterInstanceAttributes(&v), - resource.TestCheckResourceAttr("aws_neptune_cluster_instance.cluster_instances", "auto_minor_version_upgrade", "false"), + resource.TestCheckResourceAttr(resourceName, "auto_minor_version_upgrade", "false"), ), }, }, @@ -64,6 +70,10 @@ func TestAccAWSNeptuneClusterInstance_basic(t *testing.T) { func TestAccAWSNeptuneClusterInstance_withaz(t *testing.T) { var v neptune.DBInstance + rInt := acctest.RandInt() + + resourceName := "aws_neptune_cluster_instance.cluster_instances" + availabiltyZonesDataSourceName := "data.aws_availability_zones.available" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -71,11 +81,12 @@ func TestAccAWSNeptuneClusterInstance_withaz(t *testing.T) { CheckDestroy: testAccCheckAWSNeptuneClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSNeptuneClusterInstanceConfig_az(acctest.RandInt()), + Config: testAccAWSNeptuneClusterInstanceConfig_az(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterInstanceExists("aws_neptune_cluster_instance.cluster_instances", &v), + testAccCheckAWSNeptuneClusterInstanceExists(resourceName, &v), testAccCheckAWSNeptuneClusterInstanceAttributes(&v), - resource.TestMatchResourceAttr("aws_neptune_cluster_instance.cluster_instances", "availability_zone", regexp.MustCompile("^us-west-2[a-z]{1}$")), + resource.TestMatchResourceAttr(resourceName, "availability_zone", regexp.MustCompile(fmt.Sprintf("^%s[a-z]{1}$", testAccGetRegion()))), // NOPE + resource.TestCheckResourceAttrPair(resourceName, "availability_zone", availabiltyZonesDataSourceName, "names.0"), ), }, }, @@ -86,18 +97,21 @@ func TestAccAWSNeptuneClusterInstance_namePrefix(t *testing.T) { var v neptune.DBInstance rInt := acctest.RandInt() + resourceName := "aws_neptune_cluster_instance.test" + + namePrefix := "tf-cluster-instance-" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSNeptuneClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSNeptuneClusterInstanceConfig_namePrefix(rInt), + Config: testAccAWSNeptuneClusterInstanceConfig_namePrefix(namePrefix, rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterInstanceExists("aws_neptune_cluster_instance.test", &v), + testAccCheckAWSNeptuneClusterInstanceExists(resourceName, &v), testAccCheckAWSNeptuneClusterInstanceAttributes(&v), - resource.TestMatchResourceAttr( - "aws_neptune_cluster_instance.test", "identifier", regexp.MustCompile("^tf-cluster-instance-")), + resource.TestMatchResourceAttr(resourceName, "identifier", regexp.MustCompile(fmt.Sprintf("^%s", namePrefix))), ), }, }, @@ -108,6 +122,9 @@ func TestAccAWSNeptuneClusterInstance_withSubnetGroup(t *testing.T) { var v neptune.DBInstance rInt := acctest.RandInt() + resourceName := "aws_neptune_cluster_instance.test" + subnetGroupResourceName := "aws_neptune_subnet_group.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -116,10 +133,9 @@ func TestAccAWSNeptuneClusterInstance_withSubnetGroup(t *testing.T) { { Config: testAccAWSNeptuneClusterInstanceConfig_withSubnetGroup(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterInstanceExists("aws_neptune_cluster_instance.test", &v), + testAccCheckAWSNeptuneClusterInstanceExists(resourceName, &v), testAccCheckAWSNeptuneClusterInstanceAttributes(&v), - resource.TestCheckResourceAttr( - "aws_neptune_cluster_instance.test", "neptune_subnet_group_name", fmt.Sprintf("tf-test-%d", rInt)), + resource.TestCheckResourceAttrPair(resourceName, "neptune_subnet_group_name", subnetGroupResourceName, "name"), ), }, }, @@ -128,6 +144,9 @@ func TestAccAWSNeptuneClusterInstance_withSubnetGroup(t *testing.T) { func TestAccAWSNeptuneClusterInstance_generatedName(t *testing.T) { var v neptune.DBInstance + rInt := acctest.RandInt() + + resourceName := "aws_neptune_cluster_instance.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -135,12 +154,11 @@ func TestAccAWSNeptuneClusterInstance_generatedName(t *testing.T) { CheckDestroy: testAccCheckAWSNeptuneClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSNeptuneClusterInstanceConfig_generatedName(acctest.RandInt()), + Config: testAccAWSNeptuneClusterInstanceConfig_generatedName(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterInstanceExists("aws_neptune_cluster_instance.test", &v), + testAccCheckAWSNeptuneClusterInstanceExists(resourceName, &v), testAccCheckAWSNeptuneClusterInstanceAttributes(&v), - resource.TestMatchResourceAttr( - "aws_neptune_cluster_instance.test", "identifier", regexp.MustCompile("^tf-")), + resource.TestMatchResourceAttr(resourceName, "identifier", regexp.MustCompile("^tf-")), ), }, }, @@ -149,7 +167,10 @@ func TestAccAWSNeptuneClusterInstance_generatedName(t *testing.T) { func TestAccAWSNeptuneClusterInstance_kmsKey(t *testing.T) { var v neptune.DBInstance - keyRegex := regexp.MustCompile("^arn:aws:kms:") + rInt := acctest.RandInt() + + resourceName := "aws_neptune_cluster_instance.cluster_instances" + kmsKeyResourceName := "aws_kms_key.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -157,11 +178,10 @@ func TestAccAWSNeptuneClusterInstance_kmsKey(t *testing.T) { CheckDestroy: testAccCheckAWSNeptuneClusterDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSNeptuneClusterInstanceConfigKmsKey(acctest.RandInt()), + Config: testAccAWSNeptuneClusterInstanceConfigKmsKey(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterInstanceExists("aws_neptune_cluster_instance.cluster_instances", &v), - resource.TestMatchResourceAttr( - "aws_neptune_cluster_instance.cluster_instances", "kms_key_arn", keyRegex), + testAccCheckAWSNeptuneClusterInstanceExists(resourceName, &v), + resource.TestCheckResourceAttrPair(resourceName, "kms_key_arn", kmsKeyResourceName, "arn"), ), }, }, @@ -214,24 +234,46 @@ func testAccCheckAWSNeptuneClusterInstanceAttributes(v *neptune.DBInstance) reso } } -func testAccAWSNeptuneClusterInstanceConfig(n int) string { - return fmt.Sprintf(` -resource "aws_neptune_cluster" "default" { - cluster_identifier = "tf-neptune-cluster-test-%d" - availability_zones = ["us-west-2a", "us-west-2b", "us-west-2c"] - skip_final_snapshot = true +func testAccCheckNeptuneClusterAddress(v *neptune.DBInstance, resourceName string, portNumber int) resource.TestCheckFunc { + return func(s *terraform.State) error { + address := aws.StringValue(v.Endpoint.Address) + if err := resource.TestCheckResourceAttr(resourceName, "address", address)(s); err != nil { + return err + } + + port := strconv.Itoa(portNumber) + if err := resource.TestCheckResourceAttr(resourceName, "port", port)(s); err != nil { + return err + } + + if err := resource.TestCheckResourceAttr(resourceName, "endpoint", fmt.Sprintf("%s:%s", address, port))(s); err != nil { + return err + } + + return nil + } } +func testAccAWSNeptuneClusterInstanceConfig(instanceName string, n int) string { + return composeConfig( + testAccAWSNeptuneClusterConfigBase, + fmt.Sprintf(` resource "aws_neptune_cluster_instance" "cluster_instances" { - identifier = "tf-cluster-instance-%d" + identifier = %[1]q cluster_identifier = "${aws_neptune_cluster.default.id}" instance_class = "db.r4.large" - neptune_parameter_group_name = "${aws_neptune_parameter_group.bar.name}" + neptune_parameter_group_name = "${aws_neptune_parameter_group.test.name}" promotion_tier = "3" } -resource "aws_neptune_parameter_group" "bar" { - name = "tf-cluster-test-group-%d" +resource "aws_neptune_cluster" "default" { + cluster_identifier = "tf-neptune-cluster-test-%[2]d" + availability_zones = local.availability_zone_names + skip_final_snapshot = true +} + +resource "aws_neptune_parameter_group" "test" { + name = "tf-cluster-test-group-%[2]d" family = "neptune1" parameter { @@ -240,31 +282,33 @@ resource "aws_neptune_parameter_group" "bar" { } tags = { - foo = "bar" + Name = "test" } } -`, n, n, n) -} - -func testAccAWSNeptuneClusterInstanceConfigModified(n int) string { - return fmt.Sprintf(` -resource "aws_neptune_cluster" "default" { - cluster_identifier = "tf-neptune-cluster-test-%d" - availability_zones = ["us-west-2a", "us-west-2b", "us-west-2c"] - skip_final_snapshot = true +`, instanceName, n)) } +func testAccAWSNeptuneClusterInstanceConfigModified(instanceName string, n int) string { + return composeConfig( + testAccAWSNeptuneClusterConfigBase, + fmt.Sprintf(` resource "aws_neptune_cluster_instance" "cluster_instances" { - identifier = "tf-cluster-instance-%d" + identifier = %[1]q cluster_identifier = "${aws_neptune_cluster.default.id}" instance_class = "db.r4.large" - neptune_parameter_group_name = "${aws_neptune_parameter_group.bar.name}" + neptune_parameter_group_name = "${aws_neptune_parameter_group.test.name}" auto_minor_version_upgrade = false promotion_tier = "3" } -resource "aws_neptune_parameter_group" "bar" { - name = "tf-cluster-test-group-%d" +resource "aws_neptune_cluster" "default" { + cluster_identifier = "tf-neptune-cluster-test-%[2]d" + availability_zones = local.availability_zone_names + skip_final_snapshot = true +} + +resource "aws_neptune_parameter_group" "test" { + name = "tf-cluster-test-group-%[2]d" family = "neptune1" parameter { @@ -273,40 +317,33 @@ resource "aws_neptune_parameter_group" "bar" { } tags = { - foo = "bar" + Name = "test" } } -`, n, n, n) +`, instanceName, n)) } func testAccAWSNeptuneClusterInstanceConfig_az(n int) string { - return fmt.Sprintf(` -data "aws_availability_zones" "available" { - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} - -resource "aws_neptune_cluster" "default" { - cluster_identifier = "tf-neptune-cluster-test-%d" - availability_zones = ["${data.aws_availability_zones.available.names[0]}", "${data.aws_availability_zones.available.names[1]}", "${data.aws_availability_zones.available.names[2]}"] - skip_final_snapshot = true -} - + return composeConfig( + testAccAWSNeptuneClusterConfigBase, + fmt.Sprintf(` resource "aws_neptune_cluster_instance" "cluster_instances" { - identifier = "tf-cluster-instance-%d" + identifier = "tf-cluster-instance-%[1]d" cluster_identifier = "${aws_neptune_cluster.default.id}" instance_class = "db.r4.large" - neptune_parameter_group_name = "${aws_neptune_parameter_group.bar.name}" + neptune_parameter_group_name = "${aws_neptune_parameter_group.test.name}" promotion_tier = "3" - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] +} + +resource "aws_neptune_cluster" "default" { + cluster_identifier = "tf-neptune-cluster-test-%[1]d" + availability_zones = local.availability_zone_names + skip_final_snapshot = true } -resource "aws_neptune_parameter_group" "bar" { - name = "tf-cluster-test-group-%d" +resource "aws_neptune_parameter_group" "test" { + name = "tf-cluster-test-group-%[1]d" family = "neptune1" parameter { @@ -315,22 +352,24 @@ resource "aws_neptune_parameter_group" "bar" { } tags = { - foo = "bar" + Name = "test" } } -`, n, n, n) +`, n)) } func testAccAWSNeptuneClusterInstanceConfig_withSubnetGroup(n int) string { - return fmt.Sprintf(` + return composeConfig( + testAccAWSNeptuneClusterConfigBase, + fmt.Sprintf(` resource "aws_neptune_cluster_instance" "test" { - identifier = "tf-cluster-instance-%d" + identifier = "tf-cluster-instance-%[1]d" cluster_identifier = "${aws_neptune_cluster.test.id}" instance_class = "db.r4.large" } resource "aws_neptune_cluster" "test" { - cluster_identifier = "tf-neptune-cluster-%d" + cluster_identifier = "tf-neptune-cluster-%[1]d" neptune_subnet_group_name = "${aws_neptune_subnet_group.test.name}" skip_final_snapshot = true } @@ -364,22 +403,24 @@ resource "aws_subnet" "b" { } resource "aws_neptune_subnet_group" "test" { - name = "tf-test-%d" + name = "tf-test-%[1]d" subnet_ids = ["${aws_subnet.a.id}", "${aws_subnet.b.id}"] } -`, n, n, n) +`, n)) } -func testAccAWSNeptuneClusterInstanceConfig_namePrefix(n int) string { - return fmt.Sprintf(` +func testAccAWSNeptuneClusterInstanceConfig_namePrefix(namePrefix string, n int) string { + return composeConfig( + testAccAWSNeptuneClusterConfigBase, + fmt.Sprintf(` resource "aws_neptune_cluster_instance" "test" { - identifier_prefix = "tf-cluster-instance-" + identifier_prefix = %[1]q cluster_identifier = "${aws_neptune_cluster.test.id}" instance_class = "db.r4.large" } resource "aws_neptune_cluster" "test" { - cluster_identifier = "tf-neptune-cluster-%d" + cluster_identifier = "tf-neptune-cluster-%[2]d" neptune_subnet_group_name = "${aws_neptune_subnet_group.test.name}" skip_final_snapshot = true } @@ -413,21 +454,23 @@ resource "aws_subnet" "b" { } resource "aws_neptune_subnet_group" "test" { - name = "tf-test-%d" + name = "tf-test-%[2]d" subnet_ids = ["${aws_subnet.a.id}", "${aws_subnet.b.id}"] } -`, n, n) +`, namePrefix, n)) } func testAccAWSNeptuneClusterInstanceConfig_generatedName(n int) string { - return fmt.Sprintf(` + return composeConfig( + testAccAWSNeptuneClusterConfigBase, + fmt.Sprintf(` resource "aws_neptune_cluster_instance" "test" { cluster_identifier = "${aws_neptune_cluster.test.id}" instance_class = "db.r4.large" } resource "aws_neptune_cluster" "test" { - cluster_identifier = "tf-neptune-cluster-%d" + cluster_identifier = "tf-neptune-cluster-%[1]d" neptune_subnet_group_name = "${aws_neptune_subnet_group.test.name}" skip_final_snapshot = true } @@ -461,16 +504,18 @@ resource "aws_subnet" "b" { } resource "aws_neptune_subnet_group" "test" { - name = "tf-test-%d" + name = "tf-test-%[1]d" subnet_ids = ["${aws_subnet.a.id}", "${aws_subnet.b.id}"] } -`, n, n) +`, n)) } func testAccAWSNeptuneClusterInstanceConfigKmsKey(n int) string { - return fmt.Sprintf(` -resource "aws_kms_key" "foo" { - description = "Terraform acc test %d" + return composeConfig( + testAccAWSNeptuneClusterConfigBase, + fmt.Sprintf(` +resource "aws_kms_key" "test" { + description = "Terraform acc test %[1]d" policy = < 0 { // We can only modify 20 parameters at a time, so walk them until @@ -217,7 +214,7 @@ func resourceAwsNeptuneClusterParameterGroupUpdate(d *schema.ResourceData, meta } log.Printf("[DEBUG] Modify Neptune Cluster Parameter Group: %s", modifyOpts) - _, err = conn.ModifyDBClusterParameterGroup(&modifyOpts) + _, err := conn.ModifyDBClusterParameterGroup(&modifyOpts) if err != nil { return fmt.Errorf("Error modifying Neptune Cluster Parameter Group: %s", err) } diff --git a/aws/resource_aws_neptune_cluster_parameter_group_test.go b/aws/resource_aws_neptune_cluster_parameter_group_test.go index ca0bfe826d6..a6625f9c505 100644 --- a/aws/resource_aws_neptune_cluster_parameter_group_test.go +++ b/aws/resource_aws_neptune_cluster_parameter_group_test.go @@ -8,15 +8,18 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSNeptuneClusterParameterGroup_basic(t *testing.T) { var v neptune.DBClusterParameterGroup - parameterGroupName := fmt.Sprintf("cluster-parameter-group-test-terraform-%d", acctest.RandInt()) + parameterGroupName := acctest.RandomWithPrefix("cluster-parameter-group-test-terraform") + + resourceName := "aws_neptune_cluster_parameter_group.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -26,22 +29,18 @@ func TestAccAWSNeptuneClusterParameterGroup_basic(t *testing.T) { { Config: testAccAWSNeptuneClusterParameterGroupConfig(parameterGroupName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterParameterGroupExists("aws_neptune_cluster_parameter_group.bar", &v), + testAccCheckAWSNeptuneClusterParameterGroupExists(resourceName, &v), testAccCheckAWSNeptuneClusterParameterGroupAttributes(&v, parameterGroupName), - resource.TestMatchResourceAttr( - "aws_neptune_cluster_parameter_group.bar", "arn", regexp.MustCompile(fmt.Sprintf("^arn:[^:]+:rds:[^:]+:\\d{12}:cluster-pg:%s", parameterGroupName))), - resource.TestCheckResourceAttr( - "aws_neptune_cluster_parameter_group.bar", "name", parameterGroupName), - resource.TestCheckResourceAttr( - "aws_neptune_cluster_parameter_group.bar", "family", "neptune1"), - resource.TestCheckResourceAttr( - "aws_neptune_cluster_parameter_group.bar", "description", "Managed by Terraform"), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "parameter.#", "0"), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "tags.%", "0"), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "rds", fmt.Sprintf("cluster-pg:%s", parameterGroupName)), + resource.TestCheckResourceAttr(resourceName, "name", parameterGroupName), + resource.TestCheckResourceAttr(resourceName, "family", "neptune1"), + resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), + resource.TestCheckResourceAttr(resourceName, "parameter.#", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { - ResourceName: "aws_neptune_cluster_parameter_group.bar", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -52,6 +51,8 @@ func TestAccAWSNeptuneClusterParameterGroup_basic(t *testing.T) { func TestAccAWSNeptuneClusterParameterGroup_namePrefix(t *testing.T) { var v neptune.DBClusterParameterGroup + resourceName := "aws_neptune_cluster_parameter_group.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -60,13 +61,12 @@ func TestAccAWSNeptuneClusterParameterGroup_namePrefix(t *testing.T) { { Config: testAccAWSNeptuneClusterParameterGroupConfig_namePrefix, Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterParameterGroupExists("aws_neptune_cluster_parameter_group.test", &v), - resource.TestMatchResourceAttr( - "aws_neptune_cluster_parameter_group.test", "name", regexp.MustCompile("^tf-test-")), + testAccCheckAWSNeptuneClusterParameterGroupExists(resourceName, &v), + resource.TestMatchResourceAttr(resourceName, "name", regexp.MustCompile("^tf-test-")), ), }, { - ResourceName: "aws_neptune_cluster_parameter_group.test", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"name_prefix"}, @@ -78,6 +78,8 @@ func TestAccAWSNeptuneClusterParameterGroup_namePrefix(t *testing.T) { func TestAccAWSNeptuneClusterParameterGroup_generatedName(t *testing.T) { var v neptune.DBClusterParameterGroup + resourceName := "aws_neptune_cluster_parameter_group.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -86,11 +88,11 @@ func TestAccAWSNeptuneClusterParameterGroup_generatedName(t *testing.T) { { Config: testAccAWSNeptuneClusterParameterGroupConfig_generatedName, Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterParameterGroupExists("aws_neptune_cluster_parameter_group.test", &v), + testAccCheckAWSNeptuneClusterParameterGroupExists(resourceName, &v), ), }, { - ResourceName: "aws_neptune_cluster_parameter_group.test", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -101,7 +103,9 @@ func TestAccAWSNeptuneClusterParameterGroup_generatedName(t *testing.T) { func TestAccAWSNeptuneClusterParameterGroup_Description(t *testing.T) { var v neptune.DBClusterParameterGroup - parameterGroupName := fmt.Sprintf("cluster-parameter-group-test-terraform-%d", acctest.RandInt()) + resourceName := "aws_neptune_cluster_parameter_group.test" + + parameterGroupName := acctest.RandomWithPrefix("cluster-parameter-group-test-terraform") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -111,13 +115,13 @@ func TestAccAWSNeptuneClusterParameterGroup_Description(t *testing.T) { { Config: testAccAWSNeptuneClusterParameterGroupConfig_Description(parameterGroupName, "custom description"), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterParameterGroupExists("aws_neptune_cluster_parameter_group.bar", &v), + testAccCheckAWSNeptuneClusterParameterGroupExists(resourceName, &v), testAccCheckAWSNeptuneClusterParameterGroupAttributes(&v, parameterGroupName), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "description", "custom description"), + resource.TestCheckResourceAttr(resourceName, "description", "custom description"), ), }, { - ResourceName: "aws_neptune_cluster_parameter_group.bar", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -128,39 +132,44 @@ func TestAccAWSNeptuneClusterParameterGroup_Description(t *testing.T) { func TestAccAWSNeptuneClusterParameterGroup_Parameter(t *testing.T) { var v neptune.DBClusterParameterGroup - parameterGroupName := fmt.Sprintf("cluster-parameter-group-test-tf-%d", acctest.RandInt()) + resourceName := "aws_neptune_cluster_parameter_group.test" + + parameterGroupName := acctest.RandomWithPrefix("cluster-parameter-group-test-tf") resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSNeptuneClusterParameterGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSNeptuneClusterParameterGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSNeptuneClusterParameterGroupConfig_Parameter(parameterGroupName, "neptune_enable_audit_log", "1"), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterParameterGroupExists("aws_neptune_cluster_parameter_group.bar", &v), + testAccCheckAWSNeptuneClusterParameterGroupExists(resourceName, &v), testAccCheckAWSNeptuneClusterParameterGroupAttributes(&v, parameterGroupName), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "parameter.#", "1"), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "parameter.709171678.apply_method", "pending-reboot"), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "parameter.709171678.name", "neptune_enable_audit_log"), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "parameter.709171678.value", "1"), + resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "apply_method": "pending-reboot", + "name": "neptune_enable_audit_log", + "value": "1", + }), ), }, { - ResourceName: "aws_neptune_cluster_parameter_group.bar", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, { Config: testAccAWSNeptuneClusterParameterGroupConfig_Parameter(parameterGroupName, "neptune_enable_audit_log", "0"), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterParameterGroupExists("aws_neptune_cluster_parameter_group.bar", &v), + testAccCheckAWSNeptuneClusterParameterGroupExists(resourceName, &v), testAccCheckAWSNeptuneClusterParameterGroupAttributes(&v, parameterGroupName), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "parameter.#", "1"), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "parameter.861808799.apply_method", "pending-reboot"), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "parameter.861808799.name", "neptune_enable_audit_log"), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "parameter.861808799.value", "0"), + resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "apply_method": "pending-reboot", + "name": "neptune_enable_audit_log", + "value": "0", + }), ), }, }, @@ -170,7 +179,9 @@ func TestAccAWSNeptuneClusterParameterGroup_Parameter(t *testing.T) { func TestAccAWSNeptuneClusterParameterGroup_Tags(t *testing.T) { var v neptune.DBClusterParameterGroup - parameterGroupName := fmt.Sprintf("cluster-parameter-group-test-tf-%d", acctest.RandInt()) + resourceName := "aws_neptune_cluster_parameter_group.test" + + parameterGroupName := acctest.RandomWithPrefix("cluster-parameter-group-test-tf") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -180,33 +191,33 @@ func TestAccAWSNeptuneClusterParameterGroup_Tags(t *testing.T) { { Config: testAccAWSNeptuneClusterParameterGroupConfig_Tags(parameterGroupName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterParameterGroupExists("aws_neptune_cluster_parameter_group.bar", &v), + testAccCheckAWSNeptuneClusterParameterGroupExists(resourceName, &v), testAccCheckAWSNeptuneClusterParameterGroupAttributes(&v, parameterGroupName), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "tags.%", "1"), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "tags.key1", "value1"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, { - ResourceName: "aws_neptune_cluster_parameter_group.bar", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, { Config: testAccAWSNeptuneClusterParameterGroupConfig_Tags(parameterGroupName, "key1", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterParameterGroupExists("aws_neptune_cluster_parameter_group.bar", &v), + testAccCheckAWSNeptuneClusterParameterGroupExists(resourceName, &v), testAccCheckAWSNeptuneClusterParameterGroupAttributes(&v, parameterGroupName), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "tags.%", "1"), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "tags.key1", "value2"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value2"), ), }, { Config: testAccAWSNeptuneClusterParameterGroupConfig_Tags(parameterGroupName, "key2", "value2"), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneClusterParameterGroupExists("aws_neptune_cluster_parameter_group.bar", &v), + testAccCheckAWSNeptuneClusterParameterGroupExists(resourceName, &v), testAccCheckAWSNeptuneClusterParameterGroupAttributes(&v, parameterGroupName), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "tags.%", "1"), - resource.TestCheckResourceAttr("aws_neptune_cluster_parameter_group.bar", "tags.key2", "value2"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, }, @@ -295,7 +306,7 @@ func testAccCheckAWSNeptuneClusterParameterGroupExists(n string, v *neptune.DBCl func testAccAWSNeptuneClusterParameterGroupConfig_Description(name, description string) string { return fmt.Sprintf(` -resource "aws_neptune_cluster_parameter_group" "bar" { +resource "aws_neptune_cluster_parameter_group" "test" { description = "%s" family = "neptune1" name = "%s" @@ -305,7 +316,7 @@ resource "aws_neptune_cluster_parameter_group" "bar" { func testAccAWSNeptuneClusterParameterGroupConfig_Parameter(name, pName, pValue string) string { return fmt.Sprintf(` -resource "aws_neptune_cluster_parameter_group" "bar" { +resource "aws_neptune_cluster_parameter_group" "test" { family = "neptune1" name = "%s" @@ -319,7 +330,7 @@ resource "aws_neptune_cluster_parameter_group" "bar" { func testAccAWSNeptuneClusterParameterGroupConfig_Tags(name, tKey, tValue string) string { return fmt.Sprintf(` -resource "aws_neptune_cluster_parameter_group" "bar" { +resource "aws_neptune_cluster_parameter_group" "test" { family = "neptune1" name = "%s" @@ -332,7 +343,7 @@ resource "aws_neptune_cluster_parameter_group" "bar" { func testAccAWSNeptuneClusterParameterGroupConfig(name string) string { return fmt.Sprintf(` -resource "aws_neptune_cluster_parameter_group" "bar" { +resource "aws_neptune_cluster_parameter_group" "test" { family = "neptune1" name = "%s" } diff --git a/aws/resource_aws_neptune_cluster_snapshot.go b/aws/resource_aws_neptune_cluster_snapshot.go index 41b4a7ffcce..c195cf31182 100644 --- a/aws/resource_aws_neptune_cluster_snapshot.go +++ b/aws/resource_aws_neptune_cluster_snapshot.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsNeptuneClusterSnapshot() *schema.Resource { diff --git a/aws/resource_aws_neptune_cluster_snapshot_test.go b/aws/resource_aws_neptune_cluster_snapshot_test.go index 2e1885976b8..4abe1a7a802 100644 --- a/aws/resource_aws_neptune_cluster_snapshot_test.go +++ b/aws/resource_aws_neptune_cluster_snapshot_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSNeptuneClusterSnapshot_basic(t *testing.T) { @@ -28,7 +28,7 @@ func TestAccAWSNeptuneClusterSnapshot_basic(t *testing.T) { testAccCheckNeptuneClusterSnapshotExists(resourceName, &dbClusterSnapshot), resource.TestCheckResourceAttrSet(resourceName, "allocated_storage"), resource.TestCheckResourceAttrSet(resourceName, "availability_zones.#"), - resource.TestMatchResourceAttr(resourceName, "db_cluster_snapshot_arn", regexp.MustCompile(`^arn:[^:]+:rds:[^:]+:\d{12}:cluster-snapshot:.+`)), + testAccCheckResourceAttrRegionalARN(resourceName, "db_cluster_snapshot_arn", "rds", fmt.Sprintf("cluster-snapshot:%s", rName)), resource.TestCheckResourceAttrSet(resourceName, "engine"), resource.TestCheckResourceAttrSet(resourceName, "engine_version"), resource.TestCheckResourceAttr(resourceName, "kms_key_id", ""), @@ -113,13 +113,13 @@ func testAccCheckNeptuneClusterSnapshotExists(resourceName string, dbClusterSnap func testAccAwsNeptuneClusterSnapshotConfig(rName string) string { return fmt.Sprintf(` resource "aws_neptune_cluster" "test" { - cluster_identifier = %q + cluster_identifier = %[1]q skip_final_snapshot = true } resource "aws_neptune_cluster_snapshot" "test" { db_cluster_identifier = "${aws_neptune_cluster.test.id}" - db_cluster_snapshot_identifier = %q + db_cluster_snapshot_identifier = %[1]q } -`, rName, rName) +`, rName) } diff --git a/aws/resource_aws_neptune_cluster_test.go b/aws/resource_aws_neptune_cluster_test.go index 964745d1757..b351af59094 100644 --- a/aws/resource_aws_neptune_cluster_test.go +++ b/aws/resource_aws_neptune_cluster_test.go @@ -9,10 +9,11 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSNeptuneCluster_basic(t *testing.T) { @@ -360,10 +361,9 @@ func TestAccAWSNeptuneCluster_updateCloudwatchLogsExports(t *testing.T) { resourceName := "aws_neptune_cluster.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSNeptuneClusterDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSNeptuneClusterDestroy, Steps: []resource.TestStep{ { Config: testAccAWSNeptuneClusterConfig(rName), @@ -377,7 +377,7 @@ func TestAccAWSNeptuneCluster_updateCloudwatchLogsExports(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSNeptuneClusterExists(resourceName, &dbCluster), resource.TestCheckResourceAttr(resourceName, "enable_cloudwatch_logs_exports.#", "1"), - resource.TestCheckResourceAttr(resourceName, "enable_cloudwatch_logs_exports.2451111801", "audit"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "enable_cloudwatch_logs_exports.*", "audit"), ), }, { @@ -571,7 +571,7 @@ func testAccCheckAWSNeptuneClusterSnapshot(rName string) resource.TestCheckFunc } var testAccAWSNeptuneClusterConfigBase = ` -data "aws_availability_zones" "test" { +data "aws_availability_zones" "available" { state = "available" filter { @@ -579,13 +579,17 @@ data "aws_availability_zones" "test" { values = ["opt-in-not-required"] } } + +locals { + availability_zone_names = slice(data.aws_availability_zones.available.names, 0, min(3, length(data.aws_availability_zones.available.names))) +} ` func testAccAWSNeptuneClusterConfig(rName string) string { return testAccAWSNeptuneClusterConfigBase + fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names engine = "neptune" neptune_cluster_parameter_group_name = "default.neptune1" skip_final_snapshot = true @@ -597,11 +601,11 @@ func testAccAWSNeptuneClusterConfigDeleteProtection(rName string, isProtected bo return testAccAWSNeptuneClusterConfigBase + fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names engine = "neptune" neptune_cluster_parameter_group_name = "default.neptune1" skip_final_snapshot = true - deletion_protection = %t + deletion_protection = %t } `, rName, isProtected) } @@ -621,7 +625,7 @@ func testAccAWSNeptuneClusterConfigWithFinalSnapshot(rName string) string { return testAccAWSNeptuneClusterConfigBase + fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %[1]q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names neptune_cluster_parameter_group_name = "default.neptune1" final_snapshot_identifier = %[1]q } @@ -632,7 +636,7 @@ func testAccAWSNeptuneClusterConfigTags1(rName, tagKey1, tagValue1 string) strin return testAccAWSNeptuneClusterConfigBase + fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %[1]q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names engine = "neptune" neptune_cluster_parameter_group_name = "default.neptune1" skip_final_snapshot = true @@ -648,7 +652,7 @@ func testAccAWSNeptuneClusterConfigTags2(rName, tagKey1, tagValue1, tagKey2, tag return testAccAWSNeptuneClusterConfigBase + fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %[1]q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names engine = "neptune" neptune_cluster_parameter_group_name = "default.neptune1" skip_final_snapshot = true @@ -739,7 +743,7 @@ EOF resource "aws_neptune_cluster" "test" { cluster_identifier = %[1]q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names neptune_cluster_parameter_group_name = "default.neptune1" skip_final_snapshot = true @@ -826,7 +830,7 @@ EOF resource "aws_neptune_cluster" "test" { cluster_identifier = %[1]q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names skip_final_snapshot = true iam_roles = ["${aws_iam_role.test.arn}", "${aws_iam_role.test-2.arn}"] @@ -876,7 +880,7 @@ EOF resource "aws_neptune_cluster" "test" { cluster_identifier = %[1]q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names skip_final_snapshot = true iam_roles = ["${aws_iam_role.test.arn}"] @@ -911,7 +915,7 @@ func testAccAWSNeptuneClusterConfig_kmsKey(rName string) string { resource "aws_neptune_cluster" "test" { cluster_identifier = %q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names neptune_cluster_parameter_group_name = "default.neptune1" storage_encrypted = true kms_key_arn = "${aws_kms_key.test.arn}" @@ -923,7 +927,7 @@ func testAccAWSNeptuneClusterConfig_encrypted(rName string) string { return testAccAWSNeptuneClusterConfigBase + fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names storage_encrypted = true skip_final_snapshot = true } @@ -934,7 +938,7 @@ func testAccAWSNeptuneClusterConfig_backups(rName string) string { return testAccAWSNeptuneClusterConfigBase + fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names backup_retention_period = 5 preferred_backup_window = "07:00-09:00" preferred_maintenance_window = "tue:04:00-tue:04:30" @@ -947,7 +951,7 @@ func testAccAWSNeptuneClusterConfig_backupsUpdate(rName string) string { return testAccAWSNeptuneClusterConfigBase + fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names backup_retention_period = 10 preferred_backup_window = "03:00-09:00" preferred_maintenance_window = "wed:01:00-wed:01:30" @@ -961,7 +965,7 @@ func testAccAWSNeptuneClusterConfig_iamAuth(rName string) string { return testAccAWSNeptuneClusterConfigBase + fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names iam_database_authentication_enabled = true skip_final_snapshot = true } @@ -972,7 +976,7 @@ func testAccAWSNeptuneClusterConfig_cloudwatchLogsExports(rName string) string { return testAccAWSNeptuneClusterConfigBase + fmt.Sprintf(` resource "aws_neptune_cluster" "test" { cluster_identifier = %q - availability_zones = "${slice(data.aws_availability_zones.test.names,0,3)}" + availability_zones = local.availability_zone_names skip_final_snapshot = true enable_cloudwatch_logs_exports = ["audit"] } diff --git a/aws/resource_aws_neptune_event_subscription.go b/aws/resource_aws_neptune_event_subscription.go index 3e9250922fa..ad370224add 100644 --- a/aws/resource_aws_neptune_event_subscription.go +++ b/aws/resource_aws_neptune_event_subscription.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_neptune_event_subscription_test.go b/aws/resource_aws_neptune_event_subscription_test.go index 697951382c2..7a226306f06 100644 --- a/aws/resource_aws_neptune_event_subscription_test.go +++ b/aws/resource_aws_neptune_event_subscription_test.go @@ -2,51 +2,117 @@ package aws import ( "fmt" + "log" "regexp" "testing" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/neptune/waiter" ) +func init() { + resource.AddTestSweepers("aws_neptune_event_subscription", &resource.Sweeper{ + Name: "aws_neptune_event_subscription", + F: testSweepNeptuneEventSubscriptions, + }) +} + +func testSweepNeptuneEventSubscriptions(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).neptuneconn + var sweeperErrs *multierror.Error + + err = conn.DescribeEventSubscriptionsPages(&neptune.DescribeEventSubscriptionsInput{}, func(page *neptune.DescribeEventSubscriptionsOutput, isLast bool) bool { + if page == nil { + return !isLast + } + + for _, eventSubscription := range page.EventSubscriptionsList { + name := aws.StringValue(eventSubscription.CustSubscriptionId) + + log.Printf("[INFO] Deleting Neptune Event Subscription: %s", name) + _, err = conn.DeleteEventSubscription(&neptune.DeleteEventSubscriptionInput{ + SubscriptionName: aws.String(name), + }) + if isAWSErr(err, neptune.ErrCodeSubscriptionNotFoundFault, "") { + continue + } + if err != nil { + sweeperErr := fmt.Errorf("error deleting Neptune Event Subscription (%s): %w", name, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + + _, err = waiter.EventSubscriptionDeleted(conn, name) + if isAWSErr(err, neptune.ErrCodeSubscriptionNotFoundFault, "") { + continue + } + if err != nil { + sweeperErr := fmt.Errorf("error waiting for Neptune Event Subscription (%s) deletion: %w", name, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + } + + return !isLast + }) + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping Neptune Event Subscriptions sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors + } + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving Neptune Event Subscriptions: %w", err)) + } + + return sweeperErrs.ErrorOrNil() +} + func TestAccAWSNeptuneEventSubscription_basic(t *testing.T) { var v neptune.EventSubscription rInt := acctest.RandInt() rName := fmt.Sprintf("tf-acc-test-neptune-event-subs-%d", rInt) + resourceName := "aws_neptune_event_subscription.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSNeptuneEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSNeptuneEventSubscriptionConfig(rInt), + Config: testAccAWSNeptuneEventSubscriptionConfig(rName, rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneEventSubscriptionExists("aws_neptune_event_subscription.bar", &v), - resource.TestMatchResourceAttr("aws_neptune_event_subscription.bar", "arn", regexp.MustCompile(fmt.Sprintf("^arn:[^:]+:rds:[^:]+:[^:]+:es:%s$", rName))), - resource.TestCheckResourceAttr("aws_neptune_event_subscription.bar", "enabled", "true"), - resource.TestCheckResourceAttr("aws_neptune_event_subscription.bar", "source_type", "db-instance"), - resource.TestCheckResourceAttr("aws_neptune_event_subscription.bar", "name", rName), - resource.TestCheckResourceAttr("aws_neptune_event_subscription.bar", "tags.%", "1"), - resource.TestCheckResourceAttr("aws_neptune_event_subscription.bar", "tags.Name", "tf-acc-test"), + testAccCheckAWSNeptuneEventSubscriptionExists(resourceName, &v), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "rds", fmt.Sprintf("es:%s", rName)), + resource.TestCheckResourceAttr(resourceName, "enabled", "true"), + resource.TestCheckResourceAttr(resourceName, "source_type", "db-instance"), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", "tf-acc-test"), ), }, { - Config: testAccAWSNeptuneEventSubscriptionConfigUpdate(rInt), + Config: testAccAWSNeptuneEventSubscriptionConfigUpdate(rName, rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneEventSubscriptionExists("aws_neptune_event_subscription.bar", &v), - resource.TestCheckResourceAttr("aws_neptune_event_subscription.bar", "enabled", "false"), - resource.TestCheckResourceAttr("aws_neptune_event_subscription.bar", "source_type", "db-parameter-group"), - resource.TestCheckResourceAttr("aws_neptune_event_subscription.bar", "tags.%", "1"), - resource.TestCheckResourceAttr("aws_neptune_event_subscription.bar", "tags.Name", "tf-acc-test1"), + testAccCheckAWSNeptuneEventSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "source_type", "db-parameter-group"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", "tf-acc-test1"), ), }, { - ResourceName: "aws_neptune_event_subscription.bar", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -59,6 +125,8 @@ func TestAccAWSNeptuneEventSubscription_withPrefix(t *testing.T) { rInt := acctest.RandInt() startsWithPrefix := regexp.MustCompile("^tf-acc-test-neptune-event-subs-") + resourceName := "aws_neptune_event_subscription.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -67,13 +135,12 @@ func TestAccAWSNeptuneEventSubscription_withPrefix(t *testing.T) { { Config: testAccAWSNeptuneEventSubscriptionConfigWithPrefix(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneEventSubscriptionExists("aws_neptune_event_subscription.bar", &v), - resource.TestMatchResourceAttr( - "aws_neptune_event_subscription.bar", "name", startsWithPrefix), + testAccCheckAWSNeptuneEventSubscriptionExists(resourceName, &v), + resource.TestMatchResourceAttr(resourceName, "name", startsWithPrefix), ), }, { - ResourceName: "aws_neptune_event_subscription.bar", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, ImportStateVerifyIgnore: []string{"name_prefix"}, @@ -86,6 +153,8 @@ func TestAccAWSNeptuneEventSubscription_withSourceIds(t *testing.T) { var v neptune.EventSubscription rInt := acctest.RandInt() + resourceName := "aws_neptune_event_subscription.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -94,25 +163,21 @@ func TestAccAWSNeptuneEventSubscription_withSourceIds(t *testing.T) { { Config: testAccAWSNeptuneEventSubscriptionConfigWithSourceIds(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneEventSubscriptionExists("aws_neptune_event_subscription.bar", &v), - resource.TestCheckResourceAttr( - "aws_neptune_event_subscription.bar", "source_type", "db-parameter-group"), - resource.TestCheckResourceAttr( - "aws_neptune_event_subscription.bar", "source_ids.#", "1"), + testAccCheckAWSNeptuneEventSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "source_type", "db-parameter-group"), + resource.TestCheckResourceAttr(resourceName, "source_ids.#", "1"), ), }, { Config: testAccAWSNeptuneEventSubscriptionConfigUpdateSourceIds(rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneEventSubscriptionExists("aws_neptune_event_subscription.bar", &v), - resource.TestCheckResourceAttr( - "aws_neptune_event_subscription.bar", "source_type", "db-parameter-group"), - resource.TestCheckResourceAttr( - "aws_neptune_event_subscription.bar", "source_ids.#", "2"), + testAccCheckAWSNeptuneEventSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "source_type", "db-parameter-group"), + resource.TestCheckResourceAttr(resourceName, "source_ids.#", "2"), ), }, { - ResourceName: "aws_neptune_event_subscription.bar", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -123,6 +188,9 @@ func TestAccAWSNeptuneEventSubscription_withSourceIds(t *testing.T) { func TestAccAWSNeptuneEventSubscription_withCategories(t *testing.T) { var v neptune.EventSubscription rInt := acctest.RandInt() + rName := fmt.Sprintf("tf-acc-test-neptune-event-subs-%d", rInt) + + resourceName := "aws_neptune_event_subscription.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -130,27 +198,23 @@ func TestAccAWSNeptuneEventSubscription_withCategories(t *testing.T) { CheckDestroy: testAccCheckAWSNeptuneEventSubscriptionDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSNeptuneEventSubscriptionConfig(rInt), + Config: testAccAWSNeptuneEventSubscriptionConfig(rName, rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneEventSubscriptionExists("aws_neptune_event_subscription.bar", &v), - resource.TestCheckResourceAttr( - "aws_neptune_event_subscription.bar", "source_type", "db-instance"), - resource.TestCheckResourceAttr( - "aws_neptune_event_subscription.bar", "event_categories.#", "5"), + testAccCheckAWSNeptuneEventSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "source_type", "db-instance"), + resource.TestCheckResourceAttr(resourceName, "event_categories.#", "5"), ), }, { - Config: testAccAWSNeptuneEventSubscriptionConfigUpdateCategories(rInt), + Config: testAccAWSNeptuneEventSubscriptionConfigUpdateCategories(rName, rInt), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNeptuneEventSubscriptionExists("aws_neptune_event_subscription.bar", &v), - resource.TestCheckResourceAttr( - "aws_neptune_event_subscription.bar", "source_type", "db-instance"), - resource.TestCheckResourceAttr( - "aws_neptune_event_subscription.bar", "event_categories.#", "1"), + testAccCheckAWSNeptuneEventSubscriptionExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "source_type", "db-instance"), + resource.TestCheckResourceAttr(resourceName, "event_categories.#", "1"), ), }, { - ResourceName: "aws_neptune_event_subscription.bar", + ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, @@ -205,37 +269,31 @@ func testAccCheckAWSNeptuneEventSubscriptionDestroy(s *terraform.State) error { SubscriptionName: aws.String(rs.Primary.ID), }) - if ae, ok := err.(awserr.Error); ok && ae.Code() == "SubscriptionNotFound" { + if isAWSErr(err, neptune.ErrCodeSubscriptionNotFoundFault, "") { continue } - if err == nil { - if len(resp.EventSubscriptionsList) != 0 && - aws.StringValue(resp.EventSubscriptionsList[0].CustSubscriptionId) == rs.Primary.ID { - return fmt.Errorf("Event Subscription still exists") - } - } - - newerr, ok := err.(awserr.Error) - if !ok { + if err != nil { return err } - if newerr.Code() != "SubscriptionNotFound" { - return err + + if len(resp.EventSubscriptionsList) != 0 && + aws.StringValue(resp.EventSubscriptionsList[0].CustSubscriptionId) == rs.Primary.ID { + return fmt.Errorf("Event Subscription still exists") } } return nil } -func testAccAWSNeptuneEventSubscriptionConfig(rInt int) string { +func testAccAWSNeptuneEventSubscriptionConfig(subscriptionName string, rInt int) string { return fmt.Sprintf(` resource "aws_sns_topic" "aws_sns_topic" { - name = "tf-acc-test-neptune-event-subs-sns-topic-%d" + name = "tf-acc-test-neptune-event-subs-sns-topic-%[1]d" } -resource "aws_neptune_event_subscription" "bar" { - name = "tf-acc-test-neptune-event-subs-%d" +resource "aws_neptune_event_subscription" "test" { + name = %[2]q sns_topic_arn = "${aws_sns_topic.aws_sns_topic.arn}" source_type = "db-instance" @@ -251,17 +309,17 @@ resource "aws_neptune_event_subscription" "bar" { Name = "tf-acc-test" } } -`, rInt, rInt) +`, rInt, subscriptionName) } -func testAccAWSNeptuneEventSubscriptionConfigUpdate(rInt int) string { +func testAccAWSNeptuneEventSubscriptionConfigUpdate(subscriptionName string, rInt int) string { return fmt.Sprintf(` resource "aws_sns_topic" "aws_sns_topic" { - name = "tf-acc-test-neptune-event-subs-sns-topic-%d" + name = "tf-acc-test-neptune-event-subs-sns-topic-%[1]d" } -resource "aws_neptune_event_subscription" "bar" { - name = "tf-acc-test-neptune-event-subs-%d" +resource "aws_neptune_event_subscription" "test" { + name = %[2]q sns_topic_arn = "${aws_sns_topic.aws_sns_topic.arn}" enabled = false source_type = "db-parameter-group" @@ -274,7 +332,7 @@ resource "aws_neptune_event_subscription" "bar" { Name = "tf-acc-test1" } } -`, rInt, rInt) +`, rInt, subscriptionName) } func testAccAWSNeptuneEventSubscriptionConfigWithPrefix(rInt int) string { @@ -283,7 +341,7 @@ resource "aws_sns_topic" "aws_sns_topic" { name = "tf-acc-test-neptune-event-subs-sns-topic-%d" } -resource "aws_neptune_event_subscription" "bar" { +resource "aws_neptune_event_subscription" "test" { name_prefix = "tf-acc-test-neptune-event-subs-" sns_topic_arn = "${aws_sns_topic.aws_sns_topic.arn}" source_type = "db-instance" @@ -306,20 +364,20 @@ resource "aws_neptune_event_subscription" "bar" { func testAccAWSNeptuneEventSubscriptionConfigWithSourceIds(rInt int) string { return fmt.Sprintf(` resource "aws_sns_topic" "aws_sns_topic" { - name = "tf-acc-test-neptune-event-subs-sns-topic-%d" + name = "tf-acc-test-neptune-event-subs-sns-topic-%[1]d" } -resource "aws_neptune_parameter_group" "bar" { - name = "neptune-parameter-group-event-%d" +resource "aws_neptune_parameter_group" "test" { + name = "neptune-parameter-group-event-%[1]d" family = "neptune1" description = "Test parameter group for terraform" } -resource "aws_neptune_event_subscription" "bar" { - name = "tf-acc-test-neptune-event-subs-with-ids-%d" +resource "aws_neptune_event_subscription" "test" { + name = "tf-acc-test-neptune-event-subs-with-ids-%[1]d" sns_topic_arn = "${aws_sns_topic.aws_sns_topic.arn}" source_type = "db-parameter-group" - source_ids = ["${aws_neptune_parameter_group.bar.id}"] + source_ids = ["${aws_neptune_parameter_group.test.id}"] event_categories = [ "configuration change", @@ -329,32 +387,32 @@ resource "aws_neptune_event_subscription" "bar" { Name = "tf-acc-test" } } -`, rInt, rInt, rInt) +`, rInt) } func testAccAWSNeptuneEventSubscriptionConfigUpdateSourceIds(rInt int) string { return fmt.Sprintf(` resource "aws_sns_topic" "aws_sns_topic" { - name = "tf-acc-test-neptune-event-subs-sns-topic-%d" + name = "tf-acc-test-neptune-event-subs-sns-topic-%[1]d" } -resource "aws_neptune_parameter_group" "bar" { - name = "neptune-parameter-group-event-%d" +resource "aws_neptune_parameter_group" "test" { + name = "neptune-parameter-group-event-%[1]d" family = "neptune1" description = "Test parameter group for terraform" } -resource "aws_neptune_parameter_group" "foo" { - name = "neptune-parameter-group-event-2-%d" +resource "aws_neptune_parameter_group" "test_2" { + name = "neptune-parameter-group-event-2-%[1]d" family = "neptune1" description = "Test parameter group for terraform" } -resource "aws_neptune_event_subscription" "bar" { - name = "tf-acc-test-neptune-event-subs-with-ids-%d" +resource "aws_neptune_event_subscription" "test" { + name = "tf-acc-test-neptune-event-subs-with-ids-%[1]d" sns_topic_arn = "${aws_sns_topic.aws_sns_topic.arn}" source_type = "db-parameter-group" - source_ids = ["${aws_neptune_parameter_group.bar.id}", "${aws_neptune_parameter_group.foo.id}"] + source_ids = ["${aws_neptune_parameter_group.test.id}", "${aws_neptune_parameter_group.test_2.id}"] event_categories = [ "configuration change", @@ -364,17 +422,17 @@ resource "aws_neptune_event_subscription" "bar" { Name = "tf-acc-test" } } -`, rInt, rInt, rInt, rInt) +`, rInt) } -func testAccAWSNeptuneEventSubscriptionConfigUpdateCategories(rInt int) string { +func testAccAWSNeptuneEventSubscriptionConfigUpdateCategories(subscriptionName string, rInt int) string { return fmt.Sprintf(` resource "aws_sns_topic" "aws_sns_topic" { - name = "tf-acc-test-neptune-event-subs-sns-topic-%d" + name = "tf-acc-test-neptune-event-subs-sns-topic-%[1]d" } -resource "aws_neptune_event_subscription" "bar" { - name = "tf-acc-test-neptune-event-subs-%d" +resource "aws_neptune_event_subscription" "test" { + name = %[2]q sns_topic_arn = "${aws_sns_topic.aws_sns_topic.arn}" source_type = "db-instance" @@ -386,5 +444,5 @@ resource "aws_neptune_event_subscription" "bar" { Name = "tf-acc-test" } } -`, rInt, rInt) +`, rInt, subscriptionName) } diff --git a/aws/resource_aws_neptune_parameter_group.go b/aws/resource_aws_neptune_parameter_group.go index b3c057c7c92..ffc13ee0965 100644 --- a/aws/resource_aws_neptune_parameter_group.go +++ b/aws/resource_aws_neptune_parameter_group.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -97,7 +97,7 @@ func resourceAwsNeptuneParameterGroupCreate(d *schema.ResourceData, meta interfa return fmt.Errorf("Error creating Neptune Parameter Group: %s", err) } - d.SetId(*resp.DBParameterGroup.DBParameterGroupName) + d.SetId(aws.StringValue(resp.DBParameterGroup.DBParameterGroupName)) d.Set("arn", resp.DBParameterGroup.DBParameterGroupArn) log.Printf("[INFO] Neptune Parameter Group ID: %s", d.Id()) @@ -185,17 +185,11 @@ func resourceAwsNeptuneParameterGroupUpdate(d *schema.ResourceData, meta interfa os := o.(*schema.Set) ns := n.(*schema.Set) - toRemove, err := expandNeptuneParameters(os.Difference(ns).List()) - if err != nil { - return err - } + toRemove := expandNeptuneParameters(os.Difference(ns).List()) log.Printf("[DEBUG] Parameters to remove: %#v", toRemove) - toAdd, err := expandNeptuneParameters(ns.Difference(os).List()) - if err != nil { - return err - } + toAdd := expandNeptuneParameters(ns.Difference(os).List()) log.Printf("[DEBUG] Parameters to add: %#v", toAdd) @@ -213,7 +207,7 @@ func resourceAwsNeptuneParameterGroupUpdate(d *schema.ResourceData, meta interfa log.Printf("[DEBUG] Reset Neptune Parameter Group: %s", resetOpts) err := resource.Retry(30*time.Second, func() *resource.RetryError { - _, err = conn.ResetDBParameterGroup(&resetOpts) + _, err := conn.ResetDBParameterGroup(&resetOpts) if err != nil { if isAWSErr(err, "InvalidDBParameterGroupState", " has pending changes") { return resource.RetryableError(err) @@ -243,7 +237,7 @@ func resourceAwsNeptuneParameterGroupUpdate(d *schema.ResourceData, meta interfa } log.Printf("[DEBUG] Modify Neptune Parameter Group: %s", modifyOpts) - _, err = conn.ModifyDBParameterGroup(&modifyOpts) + _, err := conn.ModifyDBParameterGroup(&modifyOpts) if err != nil { return fmt.Errorf("Error modifying Neptune Parameter Group: %s", err) } diff --git a/aws/resource_aws_neptune_parameter_group_test.go b/aws/resource_aws_neptune_parameter_group_test.go index 6df73b9e985..61fe2973ba5 100644 --- a/aws/resource_aws_neptune_parameter_group_test.go +++ b/aws/resource_aws_neptune_parameter_group_test.go @@ -7,9 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSNeptuneParameterGroup_basic(t *testing.T) { @@ -27,7 +28,7 @@ func TestAccAWSNeptuneParameterGroup_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSNeptuneParameterGroupExists(resourceName, &v), testAccCheckAWSNeptuneParameterGroupAttributes(&v, rName), - resource.TestMatchResourceAttr(resourceName, "arn", regexp.MustCompile(fmt.Sprintf("^arn:[^:]+:rds:[^:]+:\\d{12}:pg:%s", rName))), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "rds", fmt.Sprintf("pg:%s", rName)), resource.TestCheckResourceAttr(resourceName, "description", "Managed by Terraform"), resource.TestCheckResourceAttr(resourceName, "family", "neptune1"), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -77,10 +78,9 @@ func TestAccAWSNeptuneParameterGroup_Parameter(t *testing.T) { resourceName := "aws_neptune_parameter_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSNeptuneParameterGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSNeptuneParameterGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSNeptuneParameterGroupConfig_Parameter(rName, "neptune_query_timeout", "25", "pending-reboot"), @@ -88,9 +88,11 @@ func TestAccAWSNeptuneParameterGroup_Parameter(t *testing.T) { testAccCheckAWSNeptuneParameterGroupExists(resourceName, &v), testAccCheckAWSNeptuneParameterGroupAttributes(&v, rName), resource.TestCheckResourceAttr(resourceName, "parameter.#", "1"), - resource.TestCheckResourceAttr(resourceName, "parameter.2423897584.apply_method", "pending-reboot"), - resource.TestCheckResourceAttr(resourceName, "parameter.2423897584.name", "neptune_query_timeout"), - resource.TestCheckResourceAttr(resourceName, "parameter.2423897584.value", "25"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "apply_method": "pending-reboot", + "name": "neptune_query_timeout", + "value": "25", + }), ), }, { diff --git a/aws/resource_aws_neptune_subnet_group.go b/aws/resource_aws_neptune_subnet_group.go index e547dbedddc..355abd95cf9 100644 --- a/aws/resource_aws_neptune_subnet_group.go +++ b/aws/resource_aws_neptune_subnet_group.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/neptune" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -163,7 +163,7 @@ func resourceAwsNeptuneSubnetGroupRead(d *schema.ResourceData, meta interface{}) func resourceAwsNeptuneSubnetGroupUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).neptuneconn - if d.HasChange("subnet_ids") || d.HasChange("description") { + if d.HasChanges("subnet_ids", "description") { _, n := d.GetChange("subnet_ids") if n == nil { n = new(schema.Set) diff --git a/aws/resource_aws_neptune_subnet_group_test.go b/aws/resource_aws_neptune_subnet_group_test.go index ba6c9f389f6..748625c1c94 100644 --- a/aws/resource_aws_neptune_subnet_group_test.go +++ b/aws/resource_aws_neptune_subnet_group_test.go @@ -5,9 +5,9 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" diff --git a/aws/resource_aws_network_acl.go b/aws/resource_aws_network_acl.go index aed8ea1ed99..2f541619ea5 100644 --- a/aws/resource_aws_network_acl.go +++ b/aws/resource_aws_network_acl.go @@ -4,17 +4,17 @@ import ( "bytes" "fmt" "log" - "sort" "strconv" "strings" "time" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -26,27 +26,24 @@ func resourceAwsNetworkAcl() *schema.Resource { Delete: resourceAwsNetworkAclDelete, Update: resourceAwsNetworkAclUpdate, Importer: &schema.ResourceImporter{ - State: resourceAwsNetworkAclImportState, + State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ - "vpc_id": { + "arn": { Type: schema.TypeString, - Required: true, - ForceNew: true, + Computed: true, }, - "subnet_id": { + "vpc_id": { Type: schema.TypeString, - Optional: true, + Required: true, ForceNew: true, - Removed: "Use `subnet_ids` argument instead", }, "subnet_ids": { Type: schema.TypeSet, Optional: true, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, - Set: schema.HashString, }, "ingress": { Type: schema.TypeSet, @@ -56,16 +53,19 @@ func resourceAwsNetworkAcl() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "from_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IsPortNumberOrZero, }, "to_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IsPortNumberOrZero, }, "rule_no": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, 32766), }, "action": { Type: schema.TypeString, @@ -73,6 +73,10 @@ func resourceAwsNetworkAcl() *schema.Resource { DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { return strings.EqualFold(old, new) }, + ValidateFunc: validation.StringInSlice([]string{ + ec2.RuleActionAllow, + ec2.RuleActionDeny, + }, true), }, "protocol": { Type: schema.TypeString, @@ -81,10 +85,18 @@ func resourceAwsNetworkAcl() *schema.Resource { "cidr_block": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validation.IsCIDR, + ), }, "ipv6_cidr_block": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validation.IsCIDR, + ), }, "icmp_type": { Type: schema.TypeInt, @@ -106,16 +118,19 @@ func resourceAwsNetworkAcl() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "from_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IsPortNumberOrZero, }, "to_port": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IsPortNumberOrZero, }, "rule_no": { - Type: schema.TypeInt, - Required: true, + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(1, 32766), }, "action": { Type: schema.TypeString, @@ -123,6 +138,10 @@ func resourceAwsNetworkAcl() *schema.Resource { DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { return strings.EqualFold(old, new) }, + ValidateFunc: validation.StringInSlice([]string{ + ec2.RuleActionAllow, + ec2.RuleActionDeny, + }, true), }, "protocol": { Type: schema.TypeString, @@ -131,10 +150,18 @@ func resourceAwsNetworkAcl() *schema.Resource { "cidr_block": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validation.IsCIDR, + ), }, "ipv6_cidr_block": { Type: schema.TypeString, Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validation.IsCIDR, + ), }, "icmp_type": { Type: schema.TypeInt, @@ -174,7 +201,7 @@ func resourceAwsNetworkAclCreate(d *schema.ResourceData, meta interface{}) error // Get the ID and store it networkAcl := resp.NetworkAcl - d.SetId(*networkAcl.NetworkAclId) + d.SetId(aws.StringValue(networkAcl.NetworkAclId)) if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { if err := keyvaluetags.Ec2CreateTags(conn, d.Id(), v); err != nil { @@ -195,12 +222,10 @@ func resourceAwsNetworkAclRead(d *schema.ResourceData, meta interface{}) error { }) if err != nil { - if ec2err, ok := err.(awserr.Error); ok { - if ec2err.Code() == "InvalidNetworkAclID.NotFound" { - log.Printf("[DEBUG] Network ACL (%s) not found", d.Id()) - d.SetId("") - return nil - } + if isAWSErr(err, "InvalidNetworkAclID.NotFound", "") { + log.Printf("[WARN] Network ACL (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil } return err } @@ -216,12 +241,12 @@ func resourceAwsNetworkAclRead(d *schema.ResourceData, meta interface{}) error { for _, e := range networkAcl.Entries { // Skip the default rules added by AWS. They can be neither // configured or deleted by users. - if *e.RuleNumber == awsDefaultAclRuleNumberIpv4 || - *e.RuleNumber == awsDefaultAclRuleNumberIpv6 { + if aws.Int64Value(e.RuleNumber) == awsDefaultAclRuleNumberIpv4 || + aws.Int64Value(e.RuleNumber) == awsDefaultAclRuleNumberIpv6 { continue } - if *e.Egress { + if aws.BoolValue(e.Egress) { egressEntries = append(egressEntries, e) } else { ingressEntries = append(ingressEntries, e) @@ -236,12 +261,11 @@ func resourceAwsNetworkAclRead(d *schema.ResourceData, meta interface{}) error { d.Set("owner_id", networkAcl.OwnerId) - var s []string + var subnetIds []*string for _, a := range networkAcl.Associations { - s = append(s, *a.SubnetId) + subnetIds = append(subnetIds, a.SubnetId) } - sort.Strings(s) - if err := d.Set("subnet_ids", s); err != nil { + if err := d.Set("subnet_ids", flattenStringSet(subnetIds)); err != nil { return err } @@ -252,6 +276,16 @@ func resourceAwsNetworkAclRead(d *schema.ResourceData, meta interface{}) error { return err } + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Service: "ec2", + Region: meta.(*AWSClient).region, + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("network-acl/%s", d.Id()), + }.String() + + d.Set("arn", arn) + return nil } @@ -303,13 +337,16 @@ func resourceAwsNetworkAclUpdate(d *schema.ResourceData, meta interface{}) error } return fmt.Errorf("Failed to find acl association: acl %s with subnet %s: %s", d.Id(), r, err) } - log.Printf("DEBUG] Replacing Network Acl Association (%s) with Default Network ACL ID (%s)", *association.NetworkAclAssociationId, *defaultAcl.NetworkAclId) + log.Printf("[DEBUG] Replacing Network Acl Association (%s) with Default Network ACL ID (%s)", *association.NetworkAclAssociationId, *defaultAcl.NetworkAclId) _, err = conn.ReplaceNetworkAclAssociation(&ec2.ReplaceNetworkAclAssociationInput{ AssociationId: association.NetworkAclAssociationId, NetworkAclId: defaultAcl.NetworkAclId, }) if err != nil { - return err + if isAWSErr(err, "InvalidAssociationID.NotFound", "") { + continue + } + return fmt.Errorf("Error Replacing Default Network Acl Association: %s", err) } } } @@ -366,13 +403,13 @@ func updateNetworkAclEntries(d *schema.ResourceData, entryType string, conn *ec2 // neither modified nor destroyed. They have a custom rule // number that is out of bounds for any other rule. If we // encounter it, just continue. There's no work to be done. - if *remove.RuleNumber == awsDefaultAclRuleNumberIpv4 || - *remove.RuleNumber == awsDefaultAclRuleNumberIpv6 { + if aws.Int64Value(remove.RuleNumber) == awsDefaultAclRuleNumberIpv4 || + aws.Int64Value(remove.RuleNumber) == awsDefaultAclRuleNumberIpv6 { continue } // Delete old Acl - log.Printf("[DEBUG] Destroying Network ACL Entry number (%d)", int(*remove.RuleNumber)) + log.Printf("[DEBUG] Destroying Network ACL Entry number (%d)", int(aws.Int64Value(remove.RuleNumber))) _, err := conn.DeleteNetworkAclEntry(&ec2.DeleteNetworkAclEntryInput{ NetworkAclId: aws.String(d.Id()), RuleNumber: remove.RuleNumber, @@ -392,9 +429,9 @@ func updateNetworkAclEntries(d *schema.ResourceData, entryType string, conn *ec2 // hash differently when being read out of the API. Force the user // to set from_port and to_port to 0 for these rules, to keep the // hashing consistent. - if *add.Protocol == "-1" { - to := *add.PortRange.To - from := *add.PortRange.From + if aws.StringValue(add.Protocol) == "-1" { + to := aws.Int64Value(add.PortRange.To) + from := aws.Int64Value(add.PortRange.From) expected := &expectedPortPair{ to_port: 0, from_port: 0, @@ -406,12 +443,17 @@ func updateNetworkAclEntries(d *schema.ResourceData, entryType string, conn *ec2 } } - if add.CidrBlock != nil && *add.CidrBlock != "" { - // AWS mutates the CIDR block into a network implied by the IP and - // mask provided. This results in hashing inconsistencies between - // the local config file and the state returned by the API. Error - // if the user provides a CIDR block with an inappropriate mask - if err := validateCIDRBlock(*add.CidrBlock); err != nil { + // AWS mutates the CIDR block into a network implied by the IP and + // mask provided. This results in hashing inconsistencies between + // the local config file and the state returned by the API. Error + // if the user provides a CIDR block with an inappropriate mask + if cidrBlock := aws.StringValue(add.CidrBlock); cidrBlock != "" { + if err := validateIpv4CIDRBlock(cidrBlock); err != nil { + return err + } + } + if ipv6CidrBlock := aws.StringValue(add.Ipv6CidrBlock); ipv6CidrBlock != "" { + if err := validateIpv6CIDRBlock(ipv6CidrBlock); err != nil { return err } } @@ -426,11 +468,11 @@ func updateNetworkAclEntries(d *schema.ResourceData, entryType string, conn *ec2 IcmpTypeCode: add.IcmpTypeCode, } - if add.CidrBlock != nil && *add.CidrBlock != "" { + if add.CidrBlock != nil && aws.StringValue(add.CidrBlock) != "" { createOpts.CidrBlock = add.CidrBlock } - if add.Ipv6CidrBlock != nil && *add.Ipv6CidrBlock != "" { + if add.Ipv6CidrBlock != nil && aws.StringValue(add.Ipv6CidrBlock) != "" { createOpts.Ipv6CidrBlock = add.Ipv6CidrBlock } @@ -516,28 +558,27 @@ func cleanUpDependencyViolations(d *schema.ResourceData, conn *ec2.EC2) error { } for _, a := range associations { - log.Printf("DEBUG] Replacing Network Acl Association (%s) with Default Network ACL ID (%s)", *a.NetworkAclAssociationId, *defaultAcl.NetworkAclId) + log.Printf("DEBUG] Replacing Network Acl Association (%s) with Default Network ACL ID (%s)", + aws.StringValue(a.NetworkAclAssociationId), aws.StringValue(defaultAcl.NetworkAclId)) _, replaceErr := conn.ReplaceNetworkAclAssociation(&ec2.ReplaceNetworkAclAssociationInput{ AssociationId: a.NetworkAclAssociationId, NetworkAclId: defaultAcl.NetworkAclId, }) if replaceErr != nil { - if replaceEc2err, ok := replaceErr.(awserr.Error); ok { - // It's possible that during an attempt to replace this - // association, the Subnet in question has already been moved to - // another ACL. This can happen if you're destroying a network acl - // and simultaneously re-associating it's subnet(s) with another - // ACL; Terraform may have already re-associated the subnet(s) by - // the time we attempt to destroy them, even between the time we - // list them and then try to destroy them. In this case, the - // association we're trying to replace will no longer exist and - // this call will fail. Here we trap that error and fail - // gracefully; the association we tried to replace gone, we trust - // someone else has taken ownership. - if replaceEc2err.Code() == "InvalidAssociationID.NotFound" { - log.Printf("[WARN] Network Association (%s) no longer found; Network Association likely updated or removed externally, removing from state", *a.NetworkAclAssociationId) - continue - } + // It's possible that during an attempt to replace this + // association, the Subnet in question has already been moved to + // another ACL. This can happen if you're destroying a network acl + // and simultaneously re-associating it's subnet(s) with another + // ACL; Terraform may have already re-associated the subnet(s) by + // the time we attempt to destroy them, even between the time we + // list them and then try to destroy them. In this case, the + // association we're trying to replace will no longer exist and + // this call will fail. Here we trap that error and fail + // gracefully; the association we tried to replace gone, we trust + // someone else has taken ownership. + if isAWSErr(replaceErr, "InvalidAssociationID.NotFound", "") { + log.Printf("[WARN] Network Association (%s) no longer found; Network Association likely updated or removed externally, removing from state", aws.StringValue(a.NetworkAclAssociationId)) + continue } log.Printf("[ERR] Non retry-able error in replacing associations for Network ACL (%s): %s", d.Id(), replaceErr) return fmt.Errorf("Error replacing network ACL associations: %s", err) @@ -587,7 +628,7 @@ func resourceAwsNetworkAclEntryHash(v interface{}) int { return hashcode.String(buf.String()) } -func getDefaultNetworkAcl(vpc_id string, conn *ec2.EC2) (defaultAcl *ec2.NetworkAcl, err error) { +func getDefaultNetworkAcl(vpcId string, conn *ec2.EC2) (defaultAcl *ec2.NetworkAcl, err error) { resp, err := conn.DescribeNetworkAcls(&ec2.DescribeNetworkAclsInput{ Filters: []*ec2.Filter{ { @@ -596,7 +637,7 @@ func getDefaultNetworkAcl(vpc_id string, conn *ec2.EC2) (defaultAcl *ec2.Network }, { Name: aws.String("vpc-id"), - Values: []*string{aws.String(vpc_id)}, + Values: []*string{aws.String(vpcId)}, }, }, }) @@ -640,33 +681,33 @@ func networkAclEntriesToMapList(networkAcls []*ec2.NetworkAclEntry) []map[string result := make([]map[string]interface{}, 0, len(networkAcls)) for _, entry := range networkAcls { acl := make(map[string]interface{}) - acl["rule_no"] = *entry.RuleNumber - acl["action"] = *entry.RuleAction + acl["rule_no"] = aws.Int64Value(entry.RuleNumber) + acl["action"] = aws.StringValue(entry.RuleAction) if entry.CidrBlock != nil { - acl["cidr_block"] = *entry.CidrBlock + acl["cidr_block"] = aws.StringValue(entry.CidrBlock) } if entry.Ipv6CidrBlock != nil { - acl["ipv6_cidr_block"] = *entry.Ipv6CidrBlock + acl["ipv6_cidr_block"] = aws.StringValue(entry.Ipv6CidrBlock) } // The AWS network ACL API only speaks protocol numbers, and // that's all we record. - if _, err := strconv.Atoi(*entry.Protocol); err != nil { + if _, err := strconv.Atoi(aws.StringValue(entry.Protocol)); err != nil { // We're a protocol name. Look up the number. - acl["protocol"] = protocolIntegers()[*entry.Protocol] + acl["protocol"] = protocolIntegers()[aws.StringValue(entry.Protocol)] } else { // We're a protocol number. Pass through. - acl["protocol"] = *entry.Protocol + acl["protocol"] = aws.StringValue(entry.Protocol) } - acl["protocol"] = *entry.Protocol + acl["protocol"] = aws.StringValue(entry.Protocol) if entry.PortRange != nil { - acl["from_port"] = *entry.PortRange.From - acl["to_port"] = *entry.PortRange.To + acl["from_port"] = aws.Int64Value(entry.PortRange.From) + acl["to_port"] = aws.Int64Value(entry.PortRange.To) } if entry.IcmpTypeCode != nil { - acl["icmp_type"] = *entry.IcmpTypeCode.Type - acl["icmp_code"] = *entry.IcmpTypeCode.Code + acl["icmp_type"] = aws.Int64Value(entry.IcmpTypeCode.Type) + acl["icmp_code"] = aws.Int64Value(entry.IcmpTypeCode.Code) } result = append(result, acl) diff --git a/aws/resource_aws_network_acl_rule.go b/aws/resource_aws_network_acl_rule.go index c8adab7a897..ca11f71b304 100644 --- a/aws/resource_aws_network_acl_rule.go +++ b/aws/resource_aws_network_acl_rule.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsNetworkAclRule() *schema.Resource { @@ -198,7 +198,7 @@ func resourceAwsNetworkAclRuleCreate(d *schema.ResourceData, meta interface{}) e err = resource.Retry(3*time.Minute, func() *resource.RetryError { r, err = findNetworkAclRule(d, meta) if err != nil { - return resource.RetryableError(err) + return resource.NonRetryableError(err) } if r == nil { return resource.RetryableError(fmt.Errorf("Network ACL rule (%s) not found", d.Id())) diff --git a/aws/resource_aws_network_acl_rule_test.go b/aws/resource_aws_network_acl_rule_test.go index 60cdd3e134e..505da982d62 100644 --- a/aws/resource_aws_network_acl_rule_test.go +++ b/aws/resource_aws_network_acl_rule_test.go @@ -9,13 +9,12 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSNetworkAclRule_basic(t *testing.T) { - var networkAcl ec2.NetworkAcl resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -25,9 +24,9 @@ func TestAccAWSNetworkAclRule_basic(t *testing.T) { { Config: testAccAWSNetworkAclRuleBasicConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.baz", &networkAcl), - testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.qux", &networkAcl), - testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.wibble", &networkAcl), + testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.baz"), + testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.qux"), + testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.wibble"), ), }, { @@ -53,7 +52,6 @@ func TestAccAWSNetworkAclRule_basic(t *testing.T) { } func TestAccAWSNetworkAclRule_disappears(t *testing.T) { - var networkAcl ec2.NetworkAcl resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -63,7 +61,7 @@ func TestAccAWSNetworkAclRule_disappears(t *testing.T) { { Config: testAccAWSNetworkAclRuleBasicConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.baz", &networkAcl), + testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.baz"), testAccCheckAWSNetworkAclRuleDelete("aws_network_acl_rule.baz"), ), ExpectNonEmptyPlan: true, @@ -73,7 +71,6 @@ func TestAccAWSNetworkAclRule_disappears(t *testing.T) { } func TestAccAWSNetworkAclRule_ingressEgressSameNumberDisappears(t *testing.T) { - var networkAcl ec2.NetworkAcl resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -83,7 +80,7 @@ func TestAccAWSNetworkAclRule_ingressEgressSameNumberDisappears(t *testing.T) { { Config: testAccAWSNetworkAclRuleIngressEgressSameNumberMissing, Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.baz", &networkAcl), + testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.baz"), testAccCheckAWSNetworkAclRuleDelete("aws_network_acl_rule.baz"), ), ExpectNonEmptyPlan: true, @@ -105,7 +102,7 @@ func TestAccAWSNetworkAclRule_disappears_NetworkAcl(t *testing.T) { Config: testAccAWSNetworkAclRuleBasicConfig, Check: resource.ComposeTestCheckFunc( testAccCheckAWSNetworkAclExists(resourceName, &networkAcl), - testAccCheckAWSNetworkAclDisappears(&networkAcl), + testAccCheckResourceDisappears(testAccProvider, resourceAwsNetworkAcl(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -129,7 +126,6 @@ func TestAccAWSNetworkAclRule_missingParam(t *testing.T) { } func TestAccAWSNetworkAclRule_ipv6(t *testing.T) { - var networkAcl ec2.NetworkAcl resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -139,7 +135,7 @@ func TestAccAWSNetworkAclRule_ipv6(t *testing.T) { { Config: testAccAWSNetworkAclRuleIpv6Config, Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.baz", &networkAcl), + testAccCheckAWSNetworkAclRuleExists("aws_network_acl_rule.baz"), ), }, { @@ -153,7 +149,6 @@ func TestAccAWSNetworkAclRule_ipv6(t *testing.T) { } func TestAccAWSNetworkAclRule_ipv6ICMP(t *testing.T) { - var networkAcl ec2.NetworkAcl rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_network_acl_rule.test" @@ -165,7 +160,7 @@ func TestAccAWSNetworkAclRule_ipv6ICMP(t *testing.T) { { Config: testAccAWSNetworkAclRuleConfigIpv6ICMP(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSNetworkAclRuleExists(resourceName, &networkAcl), + testAccCheckAWSNetworkAclRuleExists(resourceName), ), }, { @@ -180,7 +175,6 @@ func TestAccAWSNetworkAclRule_ipv6ICMP(t *testing.T) { // Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/6710 func TestAccAWSNetworkAclRule_ipv6VpcAssignGeneratedIpv6CidrBlockUpdate(t *testing.T) { - var networkAcl ec2.NetworkAcl var vpc ec2.Vpc vpcResourceName := "aws_vpc.test" resourceName := "aws_network_acl_rule.test" @@ -204,7 +198,7 @@ func TestAccAWSNetworkAclRule_ipv6VpcAssignGeneratedIpv6CidrBlockUpdate(t *testi testAccCheckVpcExists(vpcResourceName, &vpc), resource.TestCheckResourceAttr(vpcResourceName, "assign_generated_ipv6_cidr_block", "true"), resource.TestMatchResourceAttr(vpcResourceName, "ipv6_cidr_block", regexp.MustCompile(`/56$`)), - testAccCheckAWSNetworkAclRuleExists(resourceName, &networkAcl), + testAccCheckAWSNetworkAclRuleExists(resourceName), ), }, { @@ -340,7 +334,7 @@ func testAccCheckAWSNetworkAclRuleDestroy(s *terraform.State) error { return nil } -func testAccCheckAWSNetworkAclRuleExists(n string, networkAcl *ec2.NetworkAcl) resource.TestCheckFunc { +func testAccCheckAWSNetworkAclRuleExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn rs, ok := s.RootModule().Resources[n] diff --git a/aws/resource_aws_network_acl_test.go b/aws/resource_aws_network_acl_test.go index f55382b2a06..53b0be4d04a 100644 --- a/aws/resource_aws_network_acl_test.go +++ b/aws/resource_aws_network_acl_test.go @@ -3,14 +3,16 @@ package aws import ( "fmt" "log" + "regexp" "testing" "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -115,6 +117,7 @@ func TestAccAWSNetworkAcl_basic(t *testing.T) { Config: testAccAWSNetworkAclEgressNIngressConfig, Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSNetworkAclExists(resourceName, &networkAcl), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`network-acl/acl-.+`)), ), }, { @@ -139,7 +142,7 @@ func TestAccAWSNetworkAcl_disappears(t *testing.T) { Config: testAccAWSNetworkAclEgressNIngressConfig, Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSNetworkAclExists(resourceName, &networkAcl), - testAccCheckAWSNetworkAclDisappears(&networkAcl), + testAccCheckResourceDisappears(testAccProvider, resourceAwsNetworkAcl(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -256,40 +259,31 @@ func TestAccAWSNetworkAcl_EgressAndIngressRules(t *testing.T) { resourceName := "aws_network_acl.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSNetworkAclDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSNetworkAclDestroy, Steps: []resource.TestStep{ { Config: testAccAWSNetworkAclEgressNIngressConfig, Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSNetworkAclExists(resourceName, &networkAcl), - resource.TestCheckResourceAttr( - resourceName, "ingress.1871939009.protocol", "6"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1871939009.rule_no", "1"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1871939009.from_port", "80"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1871939009.to_port", "80"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1871939009.action", "allow"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1871939009.cidr_block", "10.3.0.0/18"), - resource.TestCheckResourceAttr( - resourceName, "egress.3111164687.protocol", "6"), - resource.TestCheckResourceAttr( - resourceName, "egress.3111164687.rule_no", "2"), - resource.TestCheckResourceAttr( - resourceName, "egress.3111164687.from_port", "443"), - resource.TestCheckResourceAttr( - resourceName, "egress.3111164687.to_port", "443"), - resource.TestCheckResourceAttr( - resourceName, "egress.3111164687.cidr_block", "10.3.0.0/18"), - resource.TestCheckResourceAttr( - resourceName, "egress.3111164687.action", "allow"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "6", + "rule_no": "1", + "from_port": "80", + "to_port": "80", + "action": "allow", + "cidr_block": "10.3.0.0/18", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "protocol": "6", + "rule_no": "2", + "from_port": "443", + "to_port": "443", + "action": "allow", + "cidr_block": "10.3.0.0/18", + }), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), ), }, @@ -307,28 +301,23 @@ func TestAccAWSNetworkAcl_OnlyIngressRules_basic(t *testing.T) { resourceName := "aws_network_acl.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSNetworkAclDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSNetworkAclDestroy, Steps: []resource.TestStep{ { Config: testAccAWSNetworkAclIngressConfig, Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSNetworkAclExists(resourceName, &networkAcl), - resource.TestCheckResourceAttr( - resourceName, "ingress.4245812720.protocol", "6"), - resource.TestCheckResourceAttr( - resourceName, "ingress.4245812720.rule_no", "2"), - resource.TestCheckResourceAttr( - resourceName, "ingress.4245812720.from_port", "443"), - resource.TestCheckResourceAttr( - resourceName, "ingress.4245812720.to_port", "443"), - resource.TestCheckResourceAttr( - resourceName, "ingress.4245812720.action", "deny"), - resource.TestCheckResourceAttr( - resourceName, "ingress.4245812720.cidr_block", "10.2.0.0/18"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "6", + "rule_no": "2", + "from_port": "443", + "to_port": "443", + "action": "deny", + "cidr_block": "10.2.0.0/18", + }), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), ), }, @@ -346,33 +335,28 @@ func TestAccAWSNetworkAcl_OnlyIngressRules_update(t *testing.T) { resourceName := "aws_network_acl.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSNetworkAclDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSNetworkAclDestroy, Steps: []resource.TestStep{ { Config: testAccAWSNetworkAclIngressConfig, Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSNetworkAclExists(resourceName, &networkAcl), testIngressRuleLength(&networkAcl, 2), - resource.TestCheckResourceAttr( - resourceName, "ingress.401088754.protocol", "6"), - resource.TestCheckResourceAttr( - resourceName, "ingress.401088754.rule_no", "1"), - resource.TestCheckResourceAttr( - resourceName, "ingress.401088754.from_port", "0"), - resource.TestCheckResourceAttr( - resourceName, "ingress.401088754.to_port", "22"), - resource.TestCheckResourceAttr( - resourceName, "ingress.401088754.action", "deny"), - resource.TestCheckResourceAttr( - resourceName, "ingress.4245812720.cidr_block", "10.2.0.0/18"), - resource.TestCheckResourceAttr( - resourceName, "ingress.4245812720.from_port", "443"), - resource.TestCheckResourceAttr( - resourceName, "ingress.4245812720.rule_no", "2"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "6", + "rule_no": "1", + "from_port": "0", + "to_port": "22", + "action": "deny", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_block": "10.2.0.0/18", + "from_port": "443", + "rule_no": "2", + }), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), ), }, @@ -386,18 +370,14 @@ func TestAccAWSNetworkAcl_OnlyIngressRules_update(t *testing.T) { Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSNetworkAclExists(resourceName, &networkAcl), testIngressRuleLength(&networkAcl, 1), - resource.TestCheckResourceAttr( - resourceName, "ingress.401088754.protocol", "6"), - resource.TestCheckResourceAttr( - resourceName, "ingress.401088754.rule_no", "1"), - resource.TestCheckResourceAttr( - resourceName, "ingress.401088754.from_port", "0"), - resource.TestCheckResourceAttr( - resourceName, "ingress.401088754.to_port", "22"), - resource.TestCheckResourceAttr( - resourceName, "ingress.401088754.action", "deny"), - resource.TestCheckResourceAttr( - resourceName, "ingress.401088754.cidr_block", "10.2.0.0/18"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "6", + "rule_no": "1", + "from_port": "0", + "to_port": "22", + "action": "deny", + "cidr_block": "10.2.0.0/18", + }), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), ), }, @@ -592,11 +572,10 @@ func TestAccAWSNetworkAcl_ipv6Rules(t *testing.T) { resourceName := "aws_network_acl.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSNetworkAclDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSNetworkAclDestroy, Steps: []resource.TestStep{ { Config: testAccAWSNetworkAclIpv6Config, @@ -604,18 +583,14 @@ func TestAccAWSNetworkAcl_ipv6Rules(t *testing.T) { testAccCheckAWSNetworkAclExists(resourceName, &networkAcl), resource.TestCheckResourceAttr( resourceName, "ingress.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1976110835.protocol", "6"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1976110835.rule_no", "1"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1976110835.from_port", "0"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1976110835.to_port", "22"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1976110835.action", "allow"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1976110835.ipv6_cidr_block", "::/0"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "6", + "rule_no": "1", + "from_port": "0", + "to_port": "22", + "action": "allow", + "ipv6_cidr_block": "::/0", + }), ), }, { @@ -652,11 +627,10 @@ func TestAccAWSNetworkAcl_ipv6VpcRules(t *testing.T) { resourceName := "aws_network_acl.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSNetworkAclDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSNetworkAclDestroy, Steps: []resource.TestStep{ { Config: testAccAWSNetworkAclIpv6VpcConfig, @@ -664,8 +638,9 @@ func TestAccAWSNetworkAcl_ipv6VpcRules(t *testing.T) { testAccCheckAWSNetworkAclExists(resourceName, &networkAcl), resource.TestCheckResourceAttr( resourceName, "ingress.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "ingress.1296304962.ipv6_cidr_block", "2600:1f16:d1e:9a00::/56"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "ipv6_cidr_block": "2600:1f16:d1e:9a00::/56", + }), ), }, { @@ -735,20 +710,6 @@ func testAccCheckAWSNetworkAclDestroy(s *terraform.State) error { return nil } -func testAccCheckAWSNetworkAclDisappears(networkAcl *ec2.NetworkAcl) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - - input := &ec2.DeleteNetworkAclInput{ - NetworkAclId: networkAcl.NetworkAclId, - } - - _, err := conn.DeleteNetworkAcl(input) - - return err - } -} - func testAccCheckAWSNetworkAclExists(n string, networkAcl *ec2.NetworkAcl) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -1385,7 +1346,7 @@ resource "aws_network_acl" "test" { ` func testAccAWSNetworkAclConfigEgressConfigModeBlocks() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1419,11 +1380,11 @@ resource "aws_network_acl" "test" { to_port = 0 } } -`) +` } func testAccAWSNetworkAclConfigEgressConfigModeNoBlocks() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1439,11 +1400,11 @@ resource "aws_network_acl" "test" { vpc_id = "${aws_vpc.test.id}" } -`) +` } func testAccAWSNetworkAclConfigEgressConfigModeZeroed() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1461,11 +1422,11 @@ resource "aws_network_acl" "test" { vpc_id = "${aws_vpc.test.id}" } -`) +` } func testAccAWSNetworkAclConfigIngressConfigModeBlocks() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1499,11 +1460,11 @@ resource "aws_network_acl" "test" { to_port = 0 } } -`) +` } func testAccAWSNetworkAclConfigIngressConfigModeNoBlocks() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1519,11 +1480,11 @@ resource "aws_network_acl" "test" { vpc_id = "${aws_vpc.test.id}" } -`) +` } func testAccAWSNetworkAclConfigIngressConfigModeZeroed() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1541,5 +1502,5 @@ resource "aws_network_acl" "test" { vpc_id = "${aws_vpc.test.id}" } -`) +` } diff --git a/aws/resource_aws_network_interface.go b/aws/resource_aws_network_interface.go index 00ae2408bee..6c1f50dc709 100644 --- a/aws/resource_aws_network_interface.go +++ b/aws/resource_aws_network_interface.go @@ -11,9 +11,9 @@ import ( "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-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_network_interface_attachment.go b/aws/resource_aws_network_interface_attachment.go index 6fa31fa96cc..7f9c2ad6215 100644 --- a/aws/resource_aws_network_interface_attachment.go +++ b/aws/resource_aws_network_interface_attachment.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/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsNetworkInterfaceAttachment() *schema.Resource { diff --git a/aws/resource_aws_network_interface_attachment_test.go b/aws/resource_aws_network_interface_attachment_test.go index 1e1eaf7fd17..c04a9ce708c 100644 --- a/aws/resource_aws_network_interface_attachment_test.go +++ b/aws/resource_aws_network_interface_attachment_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSNetworkInterfaceAttachment_basic(t *testing.T) { @@ -40,7 +40,7 @@ func TestAccAWSNetworkInterfaceAttachment_basic(t *testing.T) { } func testAccAWSNetworkInterfaceAttachmentConfig_basic(rInt int) string { - return fmt.Sprintf(` + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "172.16.0.0/16" @@ -49,10 +49,19 @@ resource "aws_vpc" "foo" { } } +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_subnet" "foo" { vpc_id = "${aws_vpc.foo.id}" cidr_block = "172.16.10.0/24" - availability_zone = "us-west-2a" + availability_zone = data.aws_availability_zones.available.names[0] tags = { Name = "tf-acc-network-iface-attachment-basic" @@ -84,7 +93,7 @@ resource "aws_network_interface" "bar" { } resource "aws_instance" "foo" { - ami = "ami-c5eabbf5" + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id instance_type = "t2.micro" subnet_id = "${aws_subnet.foo.id}" diff --git a/aws/resource_aws_network_interface_sg_attachment.go b/aws/resource_aws_network_interface_sg_attachment.go index 9b6c3ac93eb..54635a72769 100644 --- a/aws/resource_aws_network_interface_sg_attachment.go +++ b/aws/resource_aws_network_interface_sg_attachment.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsNetworkInterfaceSGAttachment() *schema.Resource { diff --git a/aws/resource_aws_network_interface_sg_attachment_test.go b/aws/resource_aws_network_interface_sg_attachment_test.go index 33f050da593..06a59b5dfea 100644 --- a/aws/resource_aws_network_interface_sg_attachment_test.go +++ b/aws/resource_aws_network_interface_sg_attachment_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSNetworkInterfaceSGAttachment_basic(t *testing.T) { diff --git a/aws/resource_aws_network_interface_test.go b/aws/resource_aws_network_interface_test.go index a7aa4362825..cf6dbe1b3b0 100644 --- a/aws/resource_aws_network_interface_test.go +++ b/aws/resource_aws_network_interface_test.go @@ -3,13 +3,14 @@ package aws import ( "fmt" "log" + "strings" "testing" "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-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -77,10 +78,11 @@ func TestAccAWSENI_basic(t *testing.T) { CheckDestroy: testAccCheckAWSENIDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSENIConfig, + Config: testAccAWSENIConfig(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSENIExists("aws_network_interface.bar", &conf), testAccCheckAWSENIAttributes(&conf), + testAccCheckAWSENIAvailabilityZone("data.aws_availability_zones.available", "names.0", &conf), resource.TestCheckResourceAttr( "aws_network_interface.bar", "private_ips.#", "1"), resource.TestCheckResourceAttrSet( @@ -114,7 +116,7 @@ func TestAccAWSENI_disappears(t *testing.T) { CheckDestroy: testAccCheckAWSENIDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSENIConfig, + Config: testAccAWSENIConfig(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSENIExists(resourceName, &networkInterface), testAccCheckAWSENIDisappears(&networkInterface), @@ -135,7 +137,7 @@ func TestAccAWSENI_updatedDescription(t *testing.T) { CheckDestroy: testAccCheckAWSENIDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSENIConfig, + Config: testAccAWSENIConfig(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSENIExists("aws_network_interface.bar", &conf), resource.TestCheckResourceAttr( @@ -148,7 +150,7 @@ func TestAccAWSENI_updatedDescription(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSENIConfigUpdatedDescription, + Config: testAccAWSENIConfigUpdatedDescription(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSENIExists("aws_network_interface.bar", &conf), resource.TestCheckResourceAttr( @@ -169,10 +171,11 @@ func TestAccAWSENI_attached(t *testing.T) { CheckDestroy: testAccCheckAWSENIDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSENIConfigWithAttachment, + Config: testAccAWSENIConfigWithAttachment(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSENIExists("aws_network_interface.bar", &conf), testAccCheckAWSENIAttributesWithAttachment(&conf), + testAccCheckAWSENIAvailabilityZone("data.aws_availability_zones.available", "names.0", &conf), resource.TestCheckResourceAttr( "aws_network_interface.bar", "private_ips.#", "1"), resource.TestCheckResourceAttr( @@ -198,10 +201,11 @@ func TestAccAWSENI_ignoreExternalAttachment(t *testing.T) { CheckDestroy: testAccCheckAWSENIDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSENIConfigExternalAttachment, + Config: testAccAWSENIConfigExternalAttachment(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSENIExists("aws_network_interface.bar", &conf), testAccCheckAWSENIAttributes(&conf), + testAccCheckAWSENIAvailabilityZone("data.aws_availability_zones.available", "names.0", &conf), testAccCheckAWSENIMakeExternalAttachment("aws_instance.foo", &conf), ), }, @@ -224,7 +228,7 @@ func TestAccAWSENI_sourceDestCheck(t *testing.T) { CheckDestroy: testAccCheckAWSENIDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSENIConfigWithSourceDestCheck, + Config: testAccAWSENIConfigWithSourceDestCheck(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSENIExists("aws_network_interface.bar", &conf), resource.TestCheckResourceAttr( @@ -250,7 +254,7 @@ func TestAccAWSENI_computedIPs(t *testing.T) { CheckDestroy: testAccCheckAWSENIDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSENIConfigWithNoPrivateIPs, + Config: testAccAWSENIConfigWithNoPrivateIPs(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSENIExists("aws_network_interface.bar", &conf), resource.TestCheckResourceAttr( @@ -366,10 +370,6 @@ func testAccCheckAWSENIAttributes(conf *ec2.NetworkInterface) resource.TestCheck return fmt.Errorf("expected attachment to be nil") } - if *conf.AvailabilityZone != "us-west-2a" { - return fmt.Errorf("expected availability_zone to be us-west-2a, but was %s", *conf.AvailabilityZone) - } - if len(conf.Groups) != 1 && *conf.Groups[0].GroupName != "foo" { return fmt.Errorf("expected security group to be foo, but was %#v", conf.Groups) } @@ -378,8 +378,8 @@ func testAccCheckAWSENIAttributes(conf *ec2.NetworkInterface) resource.TestCheck return fmt.Errorf("expected private ip to be 172.16.10.100, but was %s", *conf.PrivateIpAddress) } - if *conf.PrivateDnsName != "ip-172-16-10-100.us-west-2.compute.internal" { - return fmt.Errorf("expected private dns name to be ip-172-16-10-100.us-west-2.compute.internal, but was %s", *conf.PrivateDnsName) + if !strings.HasPrefix(*conf.PrivateDnsName, "ip-172-16-10-100.") || !strings.HasSuffix(*conf.PrivateDnsName, ".compute.internal") { + return fmt.Errorf("expected private dns name to be ip-172-16-10-100..compute.internal, but was %s", *conf.PrivateDnsName) } if len(*conf.MacAddress) == 0 { @@ -398,6 +398,21 @@ func testAccCheckAWSENIAttributes(conf *ec2.NetworkInterface) resource.TestCheck } } +func testAccCheckAWSENIAvailabilityZone(name, attr string, conf *ec2.NetworkInterface) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok || rs.Primary.ID == "" { + return fmt.Errorf("Not found: %s", name) + } + + if rs.Primary.Attributes[attr] != *conf.AvailabilityZone { + return fmt.Errorf("%s", fmt.Sprintf("expected %s, found %s", rs.Primary.Attributes[attr], *conf.AvailabilityZone)) + } + + return nil + } +} + func testAccCheckAWSENIAttributesWithAttachment(conf *ec2.NetworkInterface) resource.TestCheckFunc { return func(s *terraform.State) error { @@ -409,10 +424,6 @@ func testAccCheckAWSENIAttributesWithAttachment(conf *ec2.NetworkInterface) reso return fmt.Errorf("expected attachment device index to be 1, but was %d", *conf.Attachment.DeviceIndex) } - if *conf.AvailabilityZone != "us-west-2a" { - return fmt.Errorf("expected availability_zone to be us-west-2a, but was %s", *conf.AvailabilityZone) - } - if len(conf.Groups) != 1 && *conf.Groups[0].GroupName != "foo" { return fmt.Errorf("expected security group to be foo, but was %#v", conf.Groups) } @@ -421,8 +432,8 @@ func testAccCheckAWSENIAttributesWithAttachment(conf *ec2.NetworkInterface) reso return fmt.Errorf("expected private ip to be 172.16.10.100, but was %s", *conf.PrivateIpAddress) } - if *conf.PrivateDnsName != "ip-172-16-10-100.us-west-2.compute.internal" { - return fmt.Errorf("expected private dns name to be ip-172-16-10-100.us-west-2.compute.internal, but was %s", *conf.PrivateDnsName) + if !strings.HasPrefix(*conf.PrivateDnsName, "ip-172-16-10-100.") || !strings.HasSuffix(*conf.PrivateDnsName, ".compute.internal") { + return fmt.Errorf("expected private dns name to be ip-172-16-10-100..compute.internal, but was %s", *conf.PrivateDnsName) } return nil @@ -486,250 +497,315 @@ func testAccCheckAWSENIMakeExternalAttachment(n string, conf *ec2.NetworkInterfa } } -const testAccAWSENIConfig = ` +func testAccAWSENIConfig() string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { - cidr_block = "172.16.0.0/16" - enable_dns_hostnames = true - tags = { - Name = "terraform-testacc-network-interface" - } + cidr_block = "172.16.0.0/16" + enable_dns_hostnames = true + tags = { + Name = "terraform-testacc-network-interface" + } } +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } + } + resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "172.16.10.0/24" - availability_zone = "us-west-2a" + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = data.aws_availability_zones.available.names[0] tags = { - Name = "tf-acc-network-interface" - } + Name = "tf-acc-network-interface" + } } resource "aws_security_group" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = "${aws_vpc.foo.id}" description = "foo" - name = "foo" + name = "foo" - egress { - from_port = 0 - to_port = 0 - protocol = "tcp" - cidr_blocks = ["10.0.0.0/16"] - } + 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" + 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" - } + Name = "bar_interface" + } +} +`) } -` -const testAccAWSENIConfigUpdatedDescription = ` +func testAccAWSENIConfigUpdatedDescription() string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { - cidr_block = "172.16.0.0/16" - enable_dns_hostnames = true - tags = { - Name = "terraform-testacc-network-interface-update-desc" - } + cidr_block = "172.16.0.0/16" + enable_dns_hostnames = true + tags = { + Name = "terraform-testacc-network-interface-update-desc" + } +} + +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } } resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "172.16.10.0/24" - availability_zone = "us-west-2a" + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = data.aws_availability_zones.available.names[0] tags = { - Name = "tf-acc-network-interface-update-desc" - } + Name = "tf-acc-network-interface-update-desc" + } } resource "aws_security_group" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = "${aws_vpc.foo.id}" description = "foo" - name = "foo" + name = "foo" - egress { - from_port = 0 - to_port = 0 - protocol = "tcp" - cidr_blocks = ["10.0.0.0/16"] - } + 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 = "Updated ENI Description" + subnet_id = "${aws_subnet.foo.id}" + private_ips = ["172.16.10.100"] + security_groups = ["${aws_security_group.foo.id}"] + description = "Updated ENI Description" tags = { - Name = "bar_interface" - } + Name = "bar_interface" + } +} +`) } -` -const testAccAWSENIConfigWithSourceDestCheck = ` +func testAccAWSENIConfigWithSourceDestCheck() string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { - cidr_block = "172.16.0.0/16" - enable_dns_hostnames = true - tags = { - Name = "terraform-testacc-network-interface-w-source-dest-check" - } + cidr_block = "172.16.0.0/16" + enable_dns_hostnames = true + tags = { + Name = "terraform-testacc-network-interface-w-source-dest-check" + } +} + +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } } resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "172.16.10.0/24" - availability_zone = "us-west-2a" + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = data.aws_availability_zones.available.names[0] tags = { - Name = "tf-acc-network-interface-w-source-dest-check" - } + Name = "tf-acc-network-interface-w-source-dest-check" + } } resource "aws_network_interface" "bar" { - subnet_id = "${aws_subnet.foo.id}" - source_dest_check = false - private_ips = ["172.16.10.100"] + subnet_id = "${aws_subnet.foo.id}" + source_dest_check = false + private_ips = ["172.16.10.100"] +} +`) } -` -const testAccAWSENIConfigWithNoPrivateIPs = ` +func testAccAWSENIConfigWithNoPrivateIPs() string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { - cidr_block = "172.16.0.0/16" - enable_dns_hostnames = true - tags = { - Name = "terraform-testacc-network-interface-w-no-private-ips" - } + cidr_block = "172.16.0.0/16" + enable_dns_hostnames = true + tags = { + Name = "terraform-testacc-network-interface-w-no-private-ips" + } +} + +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } } resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "172.16.10.0/24" - availability_zone = "us-west-2a" + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = data.aws_availability_zones.available.names[0] tags = { - Name = "tf-acc-network-interface-w-no-private-ips" - } + Name = "tf-acc-network-interface-w-no-private-ips" + } } resource "aws_network_interface" "bar" { - subnet_id = "${aws_subnet.foo.id}" - source_dest_check = false + subnet_id = "${aws_subnet.foo.id}" + source_dest_check = false +} +`) } -` -const testAccAWSENIConfigWithAttachment = ` +func testAccAWSENIConfigWithAttachment() string { + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_vpc" "foo" { - cidr_block = "172.16.0.0/16" - enable_dns_hostnames = true + cidr_block = "172.16.0.0/16" + enable_dns_hostnames = true tags = { - Name = "terraform-testacc-network-interface-w-attachment" - } + Name = "terraform-testacc-network-interface-w-attachment" + } } +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } + } + resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "172.16.10.0/24" - availability_zone = "us-west-2a" + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = data.aws_availability_zones.available.names[0] tags = { - Name = "tf-acc-network-interface-w-attachment-foo" - } + Name = "tf-acc-network-interface-w-attachment-foo" + } } resource "aws_subnet" "bar" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "172.16.11.0/24" - availability_zone = "us-west-2a" + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.11.0/24" + availability_zone = data.aws_availability_zones.available.names[0] tags = { - Name = "tf-acc-network-interface-w-attachment-bar" - } + Name = "tf-acc-network-interface-w-attachment-bar" + } } resource "aws_security_group" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = "${aws_vpc.foo.id}" description = "foo" - name = "foo" + name = "foo" } resource "aws_instance" "foo" { - ami = "ami-c5eabbf5" - instance_type = "t2.micro" - subnet_id = "${aws_subnet.bar.id}" - associate_public_ip_address = false - private_ip = "172.16.11.50" + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + subnet_id = "${aws_subnet.bar.id}" + associate_public_ip_address = false + private_ip = "172.16.11.50" tags = { - Name = "foo-tf-eni-test" - } + Name = "foo-tf-eni-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 - } + 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" - } + Name = "bar_interface" + } +}`) } -` -const testAccAWSENIConfigExternalAttachment = ` +func testAccAWSENIConfigExternalAttachment() string { + return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` resource "aws_vpc" "foo" { - cidr_block = "172.16.0.0/16" - enable_dns_hostnames = true + cidr_block = "172.16.0.0/16" + enable_dns_hostnames = true tags = { - Name = "terraform-testacc-network-interface-external-attachment" - } + Name = "terraform-testacc-network-interface-external-attachment" + } } +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } + } + resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "172.16.10.0/24" - availability_zone = "us-west-2a" + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.10.0/24" + availability_zone = data.aws_availability_zones.available.names[0] tags = { - Name = "tf-acc-network-interface-external-attachment-foo" - } + Name = "tf-acc-network-interface-external-attachment-foo" + } } resource "aws_subnet" "bar" { - vpc_id = "${aws_vpc.foo.id}" - cidr_block = "172.16.11.0/24" - availability_zone = "us-west-2a" + vpc_id = "${aws_vpc.foo.id}" + cidr_block = "172.16.11.0/24" + availability_zone = data.aws_availability_zones.available.names[0] tags = { - Name = "tf-acc-network-interface-external-attachment-bar" - } + Name = "tf-acc-network-interface-external-attachment-bar" + } } resource "aws_security_group" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = "${aws_vpc.foo.id}" description = "foo" - name = "foo" + name = "foo" } resource "aws_instance" "foo" { - ami = "ami-c5eabbf5" - instance_type = "t2.micro" - subnet_id = "${aws_subnet.bar.id}" - associate_public_ip_address = false - private_ip = "172.16.11.50" + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = "t2.micro" + subnet_id = "${aws_subnet.bar.id}" + associate_public_ip_address = false + private_ip = "172.16.11.50" tags = { - Name = "tf-eni-test" - } + Name = "tf-eni-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}"] + subnet_id = "${aws_subnet.foo.id}" + private_ips = ["172.16.10.100"] + security_groups = ["${aws_security_group.foo.id}"] tags = { - Name = "bar_interface" - } + Name = "bar_interface" + } +} +`) } -` func testAccAWSENIConfigPrivateIpsCount(privateIpsCount int) string { return fmt.Sprintf(` diff --git a/aws/resource_aws_opsworks_application.go b/aws/resource_aws_opsworks_application.go index 759ec59d18b..eda091b5beb 100644 --- a/aws/resource_aws_opsworks_application.go +++ b/aws/resource_aws_opsworks_application.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsOpsworksApplication() *schema.Resource { @@ -387,37 +387,42 @@ func resourceAwsOpsworksApplicationDelete(d *schema.ResourceData, meta interface return err } -func resourceAwsOpsworksSetApplicationEnvironmentVariable(d *schema.ResourceData, v []*opsworks.EnvironmentVariable) { - log.Printf("[DEBUG] envs: %s %d", v, len(v)) - if len(v) == 0 { +func resourceAwsOpsworksFindEnvironmentVariable(key string, vs []*opsworks.EnvironmentVariable) *opsworks.EnvironmentVariable { + for _, v := range vs { + if aws.StringValue(v.Key) == key { + return v + } + } + return nil +} + +func resourceAwsOpsworksSetApplicationEnvironmentVariable(d *schema.ResourceData, vs []*opsworks.EnvironmentVariable) { + if len(vs) == 0 { d.Set("environment", nil) return } - newValue := make([]*map[string]interface{}, len(v)) - - for i := 0; i < len(v); i++ { - config := v[i] - data := make(map[string]interface{}) - newValue[i] = &data - if config.Key != nil { - data["key"] = *config.Key - } - if config.Value != nil { - data["value"] = *config.Value - } - if config.Secure != nil { + // sensitive variables are returned obfuscated from the API, this creates a + // permadiff between the obfuscated API response and the config value. We + // start with the existing state so it can passthrough when the key is secure + values := d.Get("environment").(*schema.Set).List() - if aws.BoolValue(config.Secure) { - data["secure"] = &opsworksTrueString - } else { - data["secure"] = &opsworksFalseString + for i := 0; i < len(values); i++ { + value := values[i].(map[string]interface{}) + if v := resourceAwsOpsworksFindEnvironmentVariable(value["key"].(string), vs); v != nil { + if !aws.BoolValue(v.Secure) { + value["secure"] = aws.BoolValue(v.Secure) + value["key"] = aws.StringValue(v.Key) + value["value"] = aws.StringValue(v.Value) + values[i] = value } + } else { + // delete if not found in API response + values = append(values[:i], values[i+1:]...) } - log.Printf("[DEBUG] v: %s", data) } - d.Set("environment", newValue) + d.Set("environment", values) } func resourceAwsOpsworksApplicationEnvironmentVariable(d *schema.ResourceData) []*opsworks.EnvironmentVariable { diff --git a/aws/resource_aws_opsworks_application_test.go b/aws/resource_aws_opsworks_application_test.go index d70312d9e89..1ad5fe837aa 100644 --- a/aws/resource_aws_opsworks_application_test.go +++ b/aws/resource_aws_opsworks_application_test.go @@ -7,9 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSOpsworksApplication_basic(t *testing.T) { @@ -19,10 +20,9 @@ func TestAccAWSOpsworksApplication_basic(t *testing.T) { resourceName := "aws_opsworks_application.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAwsOpsworksApplicationDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsOpsworksApplicationDestroy, Steps: []resource.TestStep{ { Config: testAccAwsOpsworksApplicationCreate(rName), @@ -35,9 +35,11 @@ func TestAccAWSOpsworksApplication_basic(t *testing.T) { resource.TestCheckNoResourceAttr(resourceName, "ssl_configuration"), resource.TestCheckNoResourceAttr(resourceName, "domains"), resource.TestCheckNoResourceAttr(resourceName, "app_source"), - resource.TestCheckResourceAttr(resourceName, "environment.3077298702.key", "key1"), - resource.TestCheckResourceAttr(resourceName, "environment.3077298702.value", "value1"), - resource.TestCheckNoResourceAttr(resourceName, "environment.3077298702.secret"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "environment.*", map[string]string{ + "key": "key1", + "value": "value1", + "secret": "", + }), resource.TestCheckResourceAttr(resourceName, "document_root", "foo"), ), }, @@ -45,6 +47,7 @@ func TestAccAWSOpsworksApplication_basic(t *testing.T) { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, + // TODO: TypeSet check ImportStateVerifyIgnore with hash keys ImportStateVerifyIgnore: []string{"environment.3077298702.key", "environment.#", "environment.3077298702.secure", "environment.3077298702.value"}, }, @@ -66,12 +69,16 @@ func TestAccAWSOpsworksApplication_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "app_source.0.type", "git"), resource.TestCheckResourceAttr(resourceName, "app_source.0.url", "https://github.com/aws/example.git"), resource.TestCheckResourceAttr(resourceName, "app_source.0.username", ""), - resource.TestCheckResourceAttr(resourceName, "environment.2107898637.key", "key2"), - resource.TestCheckResourceAttr(resourceName, "environment.2107898637.value", "value2"), - resource.TestCheckResourceAttr(resourceName, "environment.2107898637.secure", "true"), - resource.TestCheckResourceAttr(resourceName, "environment.3077298702.key", "key1"), - resource.TestCheckResourceAttr(resourceName, "environment.3077298702.value", "value1"), - resource.TestCheckNoResourceAttr(resourceName, "environment.3077298702.secret"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "environment.*", map[string]string{ + "key": "key2", + "value": "value2", + "secure": "true", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "environment.*", map[string]string{ + "key": "key1", + "value": "value1", + "secret": "", + }), resource.TestCheckResourceAttr(resourceName, "document_root", "root"), resource.TestCheckResourceAttr(resourceName, "auto_bundle_on_deploy", "true"), resource.TestCheckResourceAttr(resourceName, "rails_env", "staging"), diff --git a/aws/resource_aws_opsworks_custom_layer.go b/aws/resource_aws_opsworks_custom_layer.go index 9ab614525ab..969d08f2cce 100644 --- a/aws/resource_aws_opsworks_custom_layer.go +++ b/aws/resource_aws_opsworks_custom_layer.go @@ -2,7 +2,7 @@ package aws import ( "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOpsworksCustomLayer() *schema.Resource { diff --git a/aws/resource_aws_opsworks_custom_layer_test.go b/aws/resource_aws_opsworks_custom_layer_test.go index d44b280bcbf..91bc1647c0b 100644 --- a/aws/resource_aws_opsworks_custom_layer_test.go +++ b/aws/resource_aws_opsworks_custom_layer_test.go @@ -7,9 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) // These tests assume the existence of predefined Opsworks IAM roles named `aws-opsworks-ec2-role` @@ -21,10 +22,9 @@ func TestAccAWSOpsworksCustomLayer_basic(t *testing.T) { resourceName := "aws_opsworks_custom_layer.tf-acc" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAwsOpsworksCustomLayerDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsOpsworksCustomLayerDestroy, Steps: []resource.TestStep{ { Config: testAccAwsOpsworksCustomLayerConfigVpcCreate(name), @@ -37,14 +37,16 @@ func TestAccAWSOpsworksCustomLayer_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "instance_shutdown_timeout", "300"), resource.TestCheckResourceAttr(resourceName, "custom_security_group_ids.#", "2"), resource.TestCheckResourceAttr(resourceName, "system_packages.#", "2"), - resource.TestCheckResourceAttr(resourceName, "system_packages.1368285564", "git"), - resource.TestCheckResourceAttr(resourceName, "system_packages.2937857443", "golang"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "system_packages.*", "git"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "system_packages.*", "golang"), resource.TestCheckResourceAttr(resourceName, "ebs_volume.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.type", "gp2"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.number_of_disks", "2"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.mount_point", "/home"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.size", "100"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.encrypted", "false"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_volume.*", map[string]string{ + "type": "gp2", + "number_of_disks": "2", + "mount_point": "/home", + "size": "100", + "encrypted": "false", + }), ), }, { @@ -106,10 +108,9 @@ func TestAccAWSOpsworksCustomLayer_noVPC(t *testing.T) { resourceName := "aws_opsworks_custom_layer.tf-acc" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAwsOpsworksCustomLayerDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsOpsworksCustomLayerDestroy, Steps: []resource.TestStep{ { Config: testAccAwsOpsworksCustomLayerConfigNoVpcCreate(stackName), @@ -123,14 +124,16 @@ func TestAccAWSOpsworksCustomLayer_noVPC(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "instance_shutdown_timeout", "300"), resource.TestCheckResourceAttr(resourceName, "custom_security_group_ids.#", "2"), resource.TestCheckResourceAttr(resourceName, "system_packages.#", "2"), - resource.TestCheckResourceAttr(resourceName, "system_packages.1368285564", "git"), - resource.TestCheckResourceAttr(resourceName, "system_packages.2937857443", "golang"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "system_packages.*", "git"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "system_packages.*", "golang"), resource.TestCheckResourceAttr(resourceName, "ebs_volume.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.type", "gp2"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.number_of_disks", "2"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.mount_point", "/home"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.size", "100"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.encrypted", "false"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_volume.*", map[string]string{ + "type": "gp2", + "number_of_disks": "2", + "mount_point": "/home", + "size": "100", + "encrypted": "false", + }), ), }, { @@ -141,21 +144,25 @@ func TestAccAWSOpsworksCustomLayer_noVPC(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "instance_shutdown_timeout", "120"), resource.TestCheckResourceAttr(resourceName, "custom_security_group_ids.#", "3"), resource.TestCheckResourceAttr(resourceName, "system_packages.#", "3"), - resource.TestCheckResourceAttr(resourceName, "system_packages.1368285564", "git"), - resource.TestCheckResourceAttr(resourceName, "system_packages.2937857443", "golang"), - resource.TestCheckResourceAttr(resourceName, "system_packages.4101929740", "subversion"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "system_packages.*", "git"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "system_packages.*", "golang"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "system_packages.*", "subversion"), resource.TestCheckResourceAttr(resourceName, "ebs_volume.#", "2"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.type", "gp2"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.number_of_disks", "2"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.mount_point", "/home"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.3575749636.size", "100"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.1266957920.type", "io1"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.1266957920.number_of_disks", "4"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.1266957920.mount_point", "/var"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.1266957920.size", "100"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.1266957920.raid_level", "1"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.1266957920.iops", "3000"), - resource.TestCheckResourceAttr(resourceName, "ebs_volume.1266957920.encrypted", "true"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_volume.*", map[string]string{ + "type": "gp2", + "number_of_disks": "2", + "mount_point": "/home", + "size": "100", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ebs_volume.*", map[string]string{ + "type": "io1", + "number_of_disks": "4", + "mount_point": "/var", + "size": "100", + "raid_level": "1", + "iops": "3000", + "encrypted": "true", + }), resource.TestCheckResourceAttr(resourceName, "custom_json", `{"layer_key":"layer_value2"}`), ), }, diff --git a/aws/resource_aws_opsworks_ganglia_layer.go b/aws/resource_aws_opsworks_ganglia_layer.go index 5dde96c656b..62985cbbc22 100644 --- a/aws/resource_aws_opsworks_ganglia_layer.go +++ b/aws/resource_aws_opsworks_ganglia_layer.go @@ -2,7 +2,7 @@ package aws import ( "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOpsworksGangliaLayer() *schema.Resource { diff --git a/aws/resource_aws_opsworks_ganglia_layer_test.go b/aws/resource_aws_opsworks_ganglia_layer_test.go index 1eb81e70656..3a83a8f7bc0 100644 --- a/aws/resource_aws_opsworks_ganglia_layer_test.go +++ b/aws/resource_aws_opsworks_ganglia_layer_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSOpsworksGangliaLayer_basic(t *testing.T) { diff --git a/aws/resource_aws_opsworks_haproxy_layer.go b/aws/resource_aws_opsworks_haproxy_layer.go index 04e30c0f962..e0afda10d5f 100644 --- a/aws/resource_aws_opsworks_haproxy_layer.go +++ b/aws/resource_aws_opsworks_haproxy_layer.go @@ -2,7 +2,7 @@ package aws import ( "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOpsworksHaproxyLayer() *schema.Resource { diff --git a/aws/resource_aws_opsworks_haproxy_layer_test.go b/aws/resource_aws_opsworks_haproxy_layer_test.go index 4ae6e11cc32..6767d739324 100644 --- a/aws/resource_aws_opsworks_haproxy_layer_test.go +++ b/aws/resource_aws_opsworks_haproxy_layer_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSOpsworksHAProxyLayer_basic(t *testing.T) { diff --git a/aws/resource_aws_opsworks_instance.go b/aws/resource_aws_opsworks_instance.go index d8b3c9737a1..17ef4b3319a 100644 --- a/aws/resource_aws_opsworks_instance.go +++ b/aws/resource_aws_opsworks_instance.go @@ -6,14 +6,13 @@ import ( "log" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/opsworks" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsOpsworksInstance() *schema.Resource { @@ -488,11 +487,9 @@ func resourceAwsOpsworksInstanceRead(d *schema.ResourceData, meta interface{}) e resp, err := client.DescribeInstances(req) if err != nil { - if awserr, ok := err.(awserr.Error); ok { - if awserr.Code() == "ResourceNotFoundException" { - d.SetId("") - return nil - } + if isAWSErr(err, opsworks.ErrCodeResourceNotFoundException, "") { + d.SetId("") + return nil } return err } @@ -529,7 +526,7 @@ func resourceAwsOpsworksInstanceRead(d *schema.ResourceData, meta interface{}) e d.Set("last_service_error_id", instance.LastServiceErrorId) var layerIds []string for _, v := range instance.LayerIds { - layerIds = append(layerIds, *v) + layerIds = append(layerIds, aws.StringValue(v)) } layerIds, err = sortListBasedonTFFile(layerIds, d) if err != nil { @@ -561,10 +558,7 @@ func resourceAwsOpsworksInstanceRead(d *schema.ResourceData, meta interface{}) e d.Set("virtualization_type", instance.VirtualizationType) // Read BlockDeviceMapping - ibds, err := readOpsworksBlockDevices(instance) - if err != nil { - return err - } + ibds := readOpsworksBlockDevices(instance) if err := d.Set("ebs_block_device", ibds["ebs"]); err != nil { return err @@ -739,7 +733,7 @@ func resourceAwsOpsworksInstanceCreate(d *schema.ResourceData, meta interface{}) return fmt.Errorf("Error launching instance: no instance returned in response") } - instanceId := *resp.InstanceId + instanceId := aws.StringValue(resp.InstanceId) d.SetId(instanceId) if v, ok := d.GetOk("state"); ok && v.(string) == "running" { @@ -939,7 +933,7 @@ func stopOpsworksInstance(d *schema.ResourceData, meta interface{}, timeout time return nil } -func readOpsworksBlockDevices(instance *opsworks.Instance) (map[string]interface{}, error) { +func readOpsworksBlockDevices(instance *opsworks.Instance) map[string]interface{} { blockDevices := make(map[string]interface{}) blockDevices["ebs"] = make([]map[string]interface{}, 0) @@ -947,41 +941,41 @@ func readOpsworksBlockDevices(instance *opsworks.Instance) (map[string]interface blockDevices["root"] = nil if len(instance.BlockDeviceMappings) == 0 { - return nil, nil + return nil } for _, bdm := range instance.BlockDeviceMappings { bd := make(map[string]interface{}) if bdm.Ebs != nil && bdm.Ebs.DeleteOnTermination != nil { - bd["delete_on_termination"] = *bdm.Ebs.DeleteOnTermination + bd["delete_on_termination"] = aws.BoolValue(bdm.Ebs.DeleteOnTermination) } if bdm.Ebs != nil && bdm.Ebs.VolumeSize != nil { - bd["volume_size"] = *bdm.Ebs.VolumeSize + bd["volume_size"] = aws.Int64Value(bdm.Ebs.VolumeSize) } if bdm.Ebs != nil && bdm.Ebs.VolumeType != nil { - bd["volume_type"] = *bdm.Ebs.VolumeType + bd["volume_type"] = aws.StringValue(bdm.Ebs.VolumeType) } if bdm.Ebs != nil && bdm.Ebs.Iops != nil { - bd["iops"] = *bdm.Ebs.Iops + bd["iops"] = aws.Int64Value(bdm.Ebs.Iops) } - if bdm.DeviceName != nil && *bdm.DeviceName == "ROOT_DEVICE" { + if aws.StringValue(bdm.DeviceName) == "ROOT_DEVICE" { blockDevices["root"] = bd } else { if bdm.DeviceName != nil { - bd["device_name"] = *bdm.DeviceName + bd["device_name"] = aws.StringValue(bdm.DeviceName) } if bdm.VirtualName != nil { - bd["virtual_name"] = *bdm.VirtualName + bd["virtual_name"] = aws.StringValue(bdm.VirtualName) blockDevices["ephemeral"] = append(blockDevices["ephemeral"].([]map[string]interface{}), bd) } else { if bdm.Ebs != nil && bdm.Ebs.SnapshotId != nil { - bd["snapshot_id"] = *bdm.Ebs.SnapshotId + bd["snapshot_id"] = aws.StringValue(bdm.Ebs.SnapshotId) } blockDevices["ebs"] = append(blockDevices["ebs"].([]map[string]interface{}), bd) } } } - return blockDevices, nil + return blockDevices } func OpsworksInstanceStateRefreshFunc(conn *opsworks.OpsWorks, instanceID string) resource.StateRefreshFunc { @@ -990,8 +984,7 @@ func OpsworksInstanceStateRefreshFunc(conn *opsworks.OpsWorks, instanceID string InstanceIds: []*string{aws.String(instanceID)}, }) if err != nil { - if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "ResourceNotFoundException" { - // Set this to nil as if we didn't find anything. + if isAWSErr(err, opsworks.ErrCodeResourceNotFoundException, "") { resp = nil } else { log.Printf("Error on OpsworksInstanceStateRefresh: %s", err) @@ -1006,6 +999,6 @@ func OpsworksInstanceStateRefreshFunc(conn *opsworks.OpsWorks, instanceID string } i := resp.Instances[0] - return i, *i.Status, nil + return i, aws.StringValue(i.Status), nil } } diff --git a/aws/resource_aws_opsworks_instance_test.go b/aws/resource_aws_opsworks_instance_test.go index f1cdc8c3278..2a6c9687a8d 100644 --- a/aws/resource_aws_opsworks_instance_test.go +++ b/aws/resource_aws_opsworks_instance_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSOpsworksInstance_basic(t *testing.T) { diff --git a/aws/resource_aws_opsworks_java_app_layer.go b/aws/resource_aws_opsworks_java_app_layer.go index 018dbc4ddd3..e79fa0b5f2e 100644 --- a/aws/resource_aws_opsworks_java_app_layer.go +++ b/aws/resource_aws_opsworks_java_app_layer.go @@ -2,7 +2,7 @@ package aws import ( "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOpsworksJavaAppLayer() *schema.Resource { diff --git a/aws/resource_aws_opsworks_java_app_layer_test.go b/aws/resource_aws_opsworks_java_app_layer_test.go index b93107ed5ad..5e866b2a1a5 100644 --- a/aws/resource_aws_opsworks_java_app_layer_test.go +++ b/aws/resource_aws_opsworks_java_app_layer_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // These tests assume the existence of predefined Opsworks IAM roles named `aws-opsworks-ec2-role` diff --git a/aws/resource_aws_opsworks_memcached_layer.go b/aws/resource_aws_opsworks_memcached_layer.go index 9e1bb7deb89..61a5e012de8 100644 --- a/aws/resource_aws_opsworks_memcached_layer.go +++ b/aws/resource_aws_opsworks_memcached_layer.go @@ -2,7 +2,7 @@ package aws import ( "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOpsworksMemcachedLayer() *schema.Resource { diff --git a/aws/resource_aws_opsworks_memcached_layer_test.go b/aws/resource_aws_opsworks_memcached_layer_test.go index aa3c0051f63..a4ea82dbaf1 100644 --- a/aws/resource_aws_opsworks_memcached_layer_test.go +++ b/aws/resource_aws_opsworks_memcached_layer_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // These tests assume the existence of predefined Opsworks IAM roles named `aws-opsworks-ec2-role` diff --git a/aws/resource_aws_opsworks_mysql_layer.go b/aws/resource_aws_opsworks_mysql_layer.go index c3d1d7b6c73..6af55fcc053 100644 --- a/aws/resource_aws_opsworks_mysql_layer.go +++ b/aws/resource_aws_opsworks_mysql_layer.go @@ -2,7 +2,7 @@ package aws import ( "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOpsworksMysqlLayer() *schema.Resource { diff --git a/aws/resource_aws_opsworks_mysql_layer_test.go b/aws/resource_aws_opsworks_mysql_layer_test.go index f5506036739..afd99c94672 100644 --- a/aws/resource_aws_opsworks_mysql_layer_test.go +++ b/aws/resource_aws_opsworks_mysql_layer_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // These tests assume the existence of predefined Opsworks IAM roles named `aws-opsworks-ec2-role` diff --git a/aws/resource_aws_opsworks_nodejs_app_layer.go b/aws/resource_aws_opsworks_nodejs_app_layer.go index c13be2f8a85..4b6a3d256fe 100644 --- a/aws/resource_aws_opsworks_nodejs_app_layer.go +++ b/aws/resource_aws_opsworks_nodejs_app_layer.go @@ -2,7 +2,7 @@ package aws import ( "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOpsworksNodejsAppLayer() *schema.Resource { diff --git a/aws/resource_aws_opsworks_nodejs_app_layer_test.go b/aws/resource_aws_opsworks_nodejs_app_layer_test.go index 3f7c4d973cb..c6dab46fee9 100644 --- a/aws/resource_aws_opsworks_nodejs_app_layer_test.go +++ b/aws/resource_aws_opsworks_nodejs_app_layer_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // These tests assume the existence of predefined Opsworks IAM roles named `aws-opsworks-ec2-role` diff --git a/aws/resource_aws_opsworks_permission.go b/aws/resource_aws_opsworks_permission.go index ddb8e5d0ddc..03b0700717f 100644 --- a/aws/resource_aws_opsworks_permission.go +++ b/aws/resource_aws_opsworks_permission.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsOpsworksPermission() *schema.Resource { diff --git a/aws/resource_aws_opsworks_permission_test.go b/aws/resource_aws_opsworks_permission_test.go index c96769f0066..10c7c1438b4 100644 --- a/aws/resource_aws_opsworks_permission_test.go +++ b/aws/resource_aws_opsworks_permission_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSOpsworksPermission_basic(t *testing.T) { diff --git a/aws/resource_aws_opsworks_php_app_layer.go b/aws/resource_aws_opsworks_php_app_layer.go index 82ee2d05d3d..1d87ff6a97a 100644 --- a/aws/resource_aws_opsworks_php_app_layer.go +++ b/aws/resource_aws_opsworks_php_app_layer.go @@ -2,7 +2,7 @@ package aws import ( "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOpsworksPhpAppLayer() *schema.Resource { diff --git a/aws/resource_aws_opsworks_php_app_layer_test.go b/aws/resource_aws_opsworks_php_app_layer_test.go index 731851b0800..9daa251716a 100644 --- a/aws/resource_aws_opsworks_php_app_layer_test.go +++ b/aws/resource_aws_opsworks_php_app_layer_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // These tests assume the existence of predefined Opsworks IAM roles named `aws-opsworks-ec2-role` diff --git a/aws/resource_aws_opsworks_rails_app_layer.go b/aws/resource_aws_opsworks_rails_app_layer.go index 42898aabecd..100baab42c7 100644 --- a/aws/resource_aws_opsworks_rails_app_layer.go +++ b/aws/resource_aws_opsworks_rails_app_layer.go @@ -2,7 +2,7 @@ package aws import ( "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOpsworksRailsAppLayer() *schema.Resource { diff --git a/aws/resource_aws_opsworks_rails_app_layer_test.go b/aws/resource_aws_opsworks_rails_app_layer_test.go index 88cec67d60d..4c38f64bbd0 100644 --- a/aws/resource_aws_opsworks_rails_app_layer_test.go +++ b/aws/resource_aws_opsworks_rails_app_layer_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // These tests assume the existence of predefined Opsworks IAM roles named `aws-opsworks-ec2-role` diff --git a/aws/resource_aws_opsworks_rds_db_instance.go b/aws/resource_aws_opsworks_rds_db_instance.go index 028f0c45bee..bbc40a16807 100644 --- a/aws/resource_aws_opsworks_rds_db_instance.go +++ b/aws/resource_aws_opsworks_rds_db_instance.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOpsworksRdsDbInstance() *schema.Resource { diff --git a/aws/resource_aws_opsworks_rds_db_instance_test.go b/aws/resource_aws_opsworks_rds_db_instance_test.go index 69765af9f49..d75def14b5d 100644 --- a/aws/resource_aws_opsworks_rds_db_instance_test.go +++ b/aws/resource_aws_opsworks_rds_db_instance_test.go @@ -7,12 +7,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAWSOpsworksRdsDbInstance(t *testing.T) { +func TestAccAWSOpsworksRdsDbInstance_basic(t *testing.T) { sName := fmt.Sprintf("test-db-instance-%d", acctest.RandInt()) var opsdb opsworks.RdsDbInstance resource.ParallelTest(t, resource.TestCase{ diff --git a/aws/resource_aws_opsworks_stack.go b/aws/resource_aws_opsworks_stack.go index 12ada7a149d..4f918b6021b 100644 --- a/aws/resource_aws_opsworks_stack.go +++ b/aws/resource_aws_opsworks_stack.go @@ -11,8 +11,8 @@ import ( "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_opsworks_stack_test.go b/aws/resource_aws_opsworks_stack_test.go index 6d32bb47fde..ff8552fd057 100644 --- a/aws/resource_aws_opsworks_stack_test.go +++ b/aws/resource_aws_opsworks_stack_test.go @@ -4,9 +4,9 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" diff --git a/aws/resource_aws_opsworks_static_web_layer.go b/aws/resource_aws_opsworks_static_web_layer.go index e05d71f6e40..c5b5673f0f7 100644 --- a/aws/resource_aws_opsworks_static_web_layer.go +++ b/aws/resource_aws_opsworks_static_web_layer.go @@ -2,7 +2,7 @@ package aws import ( "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOpsworksStaticWebLayer() *schema.Resource { diff --git a/aws/resource_aws_opsworks_static_web_layer_test.go b/aws/resource_aws_opsworks_static_web_layer_test.go index 8b7bebaeaac..35e9e809aeb 100644 --- a/aws/resource_aws_opsworks_static_web_layer_test.go +++ b/aws/resource_aws_opsworks_static_web_layer_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // These tests assume the existence of predefined Opsworks IAM roles named `aws-opsworks-ec2-role` diff --git a/aws/resource_aws_opsworks_user_profile.go b/aws/resource_aws_opsworks_user_profile.go index 8ed47148074..3b03be3789f 100644 --- a/aws/resource_aws_opsworks_user_profile.go +++ b/aws/resource_aws_opsworks_user_profile.go @@ -3,7 +3,7 @@ package aws import ( "log" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" diff --git a/aws/resource_aws_opsworks_user_profile_test.go b/aws/resource_aws_opsworks_user_profile_test.go index 658d6fef8dd..b6947ddfd0a 100644 --- a/aws/resource_aws_opsworks_user_profile_test.go +++ b/aws/resource_aws_opsworks_user_profile_test.go @@ -7,12 +7,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/opsworks" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAWSOpsworksUserProfile(t *testing.T) { +func TestAccAWSOpsworksUserProfile_basic(t *testing.T) { rName := fmt.Sprintf("test-user-%d", acctest.RandInt()) updateRName := fmt.Sprintf("test-user-%d", acctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ diff --git a/aws/resource_aws_organizations_account.go b/aws/resource_aws_organizations_account.go index 1d6c543e596..c604ace92f2 100644 --- a/aws/resource_aws_organizations_account.go +++ b/aws/resource_aws_organizations_account.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -54,10 +54,13 @@ func resourceAwsOrganizationsAccount() *schema.Resource { ValidateFunc: validation.StringLenBetween(1, 50), }, "email": { - ForceNew: true, - Type: schema.TypeString, - Required: true, - ValidateFunc: validateAwsOrganizationsAccountEmail, + ForceNew: true, + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.All( + validation.StringLenBetween(6, 64), + validation.StringMatch(regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`), "must be a valid email address"), + ), }, "iam_user_access_to_billing": { ForceNew: true, @@ -69,7 +72,7 @@ func resourceAwsOrganizationsAccount() *schema.Resource { ForceNew: true, Type: schema.TypeString, Optional: true, - ValidateFunc: validateAwsOrganizationsAccountRoleName, + ValidateFunc: validation.StringMatch(regexp.MustCompile(`^[\w+=,.@-]{1,64}$`), "must consist of uppercase letters, lowercase letters, digits with no spaces, and any of the following characters"), }, "tags": tagsSchema(), }, @@ -301,36 +304,6 @@ func resourceAwsOrganizationsAccountStateRefreshFunc(conn *organizations.Organiz } } -func validateAwsOrganizationsAccountEmail(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if !regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q must be a valid email address", value)) - } - - if len(value) < 6 { - errors = append(errors, fmt.Errorf( - "%q cannot be less than 6 characters", value)) - } - - if len(value) > 64 { - errors = append(errors, fmt.Errorf( - "%q cannot be greater than 64 characters", value)) - } - - return -} - -func validateAwsOrganizationsAccountRoleName(v interface{}, k string) (ws []string, errors []error) { - value := v.(string) - if !regexp.MustCompile(`^[\w+=,.@-]{1,64}$`).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q must consist of uppercase letters, lowercase letters, digits with no spaces, and any of the following characters: =,.@-", value)) - } - - return -} - func resourceAwsOrganizationsAccountGetParentId(conn *organizations.Organizations, childId string) (string, error) { input := &organizations.ListParentsInput{ ChildId: aws.String(childId), diff --git a/aws/resource_aws_organizations_account_test.go b/aws/resource_aws_organizations_account_test.go index 3555e38b267..ef71baa8c6e 100644 --- a/aws/resource_aws_organizations_account_test.go +++ b/aws/resource_aws_organizations_account_test.go @@ -6,20 +6,20 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAwsOrganizationsAccount_basic(t *testing.T) { - t.Skip("AWS Organizations Account testing is not currently automated due to manual account deletion steps.") + TestAccSkip(t, "AWS Organizations Account testing is not currently automated due to manual account deletion steps.") var account organizations.Account orgsEmailDomain, ok := os.LookupEnv("TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN") if !ok { - t.Skip("'TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN' not set, skipping test.") + TestAccSkip(t, "'TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN' not set, skipping test.") } rInt := acctest.RandInt() @@ -55,14 +55,14 @@ func testAccAwsOrganizationsAccount_basic(t *testing.T) { } func testAccAwsOrganizationsAccount_ParentId(t *testing.T) { - t.Skip("AWS Organizations Account testing is not currently automated due to manual account deletion steps.") + TestAccSkip(t, "AWS Organizations Account testing is not currently automated due to manual account deletion steps.") var account organizations.Account orgsEmailDomain, ok := os.LookupEnv("TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN") if !ok { - t.Skip("'TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN' not set, skipping test.") + TestAccSkip(t, "'TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN' not set, skipping test.") } rInt := acctest.RandInt() @@ -101,14 +101,14 @@ func testAccAwsOrganizationsAccount_ParentId(t *testing.T) { } func testAccAwsOrganizationsAccount_Tags(t *testing.T) { - t.Skip("AWS Organizations Account testing is not currently automated due to manual account deletion steps.") + TestAccSkip(t, "AWS Organizations Account testing is not currently automated due to manual account deletion steps.") var account organizations.Account orgsEmailDomain, ok := os.LookupEnv("TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN") if !ok { - t.Skip("'TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN' not set, skipping test.") + TestAccSkip(t, "'TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN' not set, skipping test.") } rInt := acctest.RandInt() diff --git a/aws/resource_aws_organizations_organization.go b/aws/resource_aws_organizations_organization.go index 41bceff5ed5..8e832f60b4b 100644 --- a/aws/resource_aws_organizations_organization.go +++ b/aws/resource_aws_organizations_organization.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) const organizationsPolicyTypeStatusDisabled = "DISABLED" @@ -144,6 +144,8 @@ func resourceAwsOrganizationsOrganization() *schema.Resource { Elem: &schema.Schema{ Type: schema.TypeString, ValidateFunc: validation.StringInSlice([]string{ + organizations.PolicyTypeAiservicesOptOutPolicy, + organizations.PolicyTypeBackupPolicy, organizations.PolicyTypeServiceControlPolicy, organizations.PolicyTypeTagPolicy, }, false), diff --git a/aws/resource_aws_organizations_organization_test.go b/aws/resource_aws_organizations_organization_test.go index c081ec29be2..6a02c6688ef 100644 --- a/aws/resource_aws_organizations_organization_test.go +++ b/aws/resource_aws_organizations_organization_test.go @@ -7,8 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func testAccAwsOrganizationsOrganization_basic(t *testing.T) { @@ -65,7 +66,7 @@ func testAccAwsOrganizationsOrganization_AwsServiceAccessPrincipals(t *testing.T Check: resource.ComposeTestCheckFunc( testAccCheckAwsOrganizationsOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "aws_service_access_principals.#", "1"), - resource.TestCheckResourceAttr(resourceName, "aws_service_access_principals.553690328", "config.amazonaws.com"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "aws_service_access_principals.*", "config.amazonaws.com"), ), }, { @@ -78,8 +79,8 @@ func testAccAwsOrganizationsOrganization_AwsServiceAccessPrincipals(t *testing.T Check: resource.ComposeTestCheckFunc( testAccCheckAwsOrganizationsOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "aws_service_access_principals.#", "2"), - resource.TestCheckResourceAttr(resourceName, "aws_service_access_principals.553690328", "config.amazonaws.com"), - resource.TestCheckResourceAttr(resourceName, "aws_service_access_principals.3567899500", "ds.amazonaws.com"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "aws_service_access_principals.*", "config.amazonaws.com"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "aws_service_access_principals.*", "ds.amazonaws.com"), ), }, { @@ -87,7 +88,7 @@ func testAccAwsOrganizationsOrganization_AwsServiceAccessPrincipals(t *testing.T Check: resource.ComposeTestCheckFunc( testAccCheckAwsOrganizationsOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "aws_service_access_principals.#", "1"), - resource.TestCheckResourceAttr(resourceName, "aws_service_access_principals.4066123156", "fms.amazonaws.com"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "aws_service_access_principals.*", "fms.amazonaws.com"), ), }, }, @@ -108,6 +109,7 @@ func testAccAwsOrganizationsOrganization_EnabledPolicyTypes(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsOrganizationsOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"), + resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.0", organizations.PolicyTypeServiceControlPolicy), ), }, { @@ -122,19 +124,36 @@ func testAccAwsOrganizationsOrganization_EnabledPolicyTypes(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "0"), ), }, + { + Config: testAccAwsOrganizationsOrganizationConfigEnabledPolicyTypes1(organizations.PolicyTypeAiservicesOptOutPolicy), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsOrganizationsOrganizationExists(resourceName, &organization), + resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"), + resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.0", organizations.PolicyTypeAiservicesOptOutPolicy), + ), + }, { Config: testAccAwsOrganizationsOrganizationConfigEnabledPolicyTypes1(organizations.PolicyTypeServiceControlPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckAwsOrganizationsOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"), + resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.0", organizations.PolicyTypeServiceControlPolicy), + ), + }, + { + Config: testAccAwsOrganizationsOrganizationConfigEnabledPolicyTypes1(organizations.PolicyTypeBackupPolicy), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsOrganizationsOrganizationExists(resourceName, &organization), + resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"), + resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.0", organizations.PolicyTypeBackupPolicy), ), }, - { Config: testAccAwsOrganizationsOrganizationConfigEnabledPolicyTypes1(organizations.PolicyTypeTagPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckAwsOrganizationsOrganizationExists(resourceName, &organization), resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.#", "1"), + resource.TestCheckResourceAttr(resourceName, "enabled_policy_types.0", organizations.PolicyTypeTagPolicy), ), }, { diff --git a/aws/resource_aws_organizations_organizational_unit.go b/aws/resource_aws_organizations_organizational_unit.go index 806dc224fb4..70ab43c4ba7 100644 --- a/aws/resource_aws_organizations_organizational_unit.go +++ b/aws/resource_aws_organizations_organizational_unit.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsOrganizationsOrganizationalUnit() *schema.Resource { diff --git a/aws/resource_aws_organizations_organizational_unit_test.go b/aws/resource_aws_organizations_organizational_unit_test.go index e00f28dee91..c4f44c378d1 100644 --- a/aws/resource_aws_organizations_organizational_unit_test.go +++ b/aws/resource_aws_organizations_organizational_unit_test.go @@ -6,9 +6,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAwsOrganizationsOrganizationalUnit_basic(t *testing.T) { diff --git a/aws/resource_aws_organizations_policy.go b/aws/resource_aws_organizations_policy.go index 0bd1bb7415a..c87406da2c3 100644 --- a/aws/resource_aws_organizations_policy.go +++ b/aws/resource_aws_organizations_policy.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsOrganizationsPolicy() *schema.Resource { @@ -47,6 +47,8 @@ func resourceAwsOrganizationsPolicy() *schema.Resource { ForceNew: true, Default: organizations.PolicyTypeServiceControlPolicy, ValidateFunc: validation.StringInSlice([]string{ + organizations.PolicyTypeAiservicesOptOutPolicy, + organizations.PolicyTypeBackupPolicy, organizations.PolicyTypeServiceControlPolicy, organizations.PolicyTypeTagPolicy, }, false), diff --git a/aws/resource_aws_organizations_policy_attachment.go b/aws/resource_aws_organizations_policy_attachment.go index 8834511ec5c..b69f7d92670 100644 --- a/aws/resource_aws_organizations_policy_attachment.go +++ b/aws/resource_aws_organizations_policy_attachment.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsOrganizationsPolicyAttachment() *schema.Resource { diff --git a/aws/resource_aws_organizations_policy_attachment_test.go b/aws/resource_aws_organizations_policy_attachment_test.go index 4db48c1e39b..8fbeccd227f 100644 --- a/aws/resource_aws_organizations_policy_attachment_test.go +++ b/aws/resource_aws_organizations_policy_attachment_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAwsOrganizationsPolicyAttachment_Account(t *testing.T) { diff --git a/aws/resource_aws_organizations_policy_test.go b/aws/resource_aws_organizations_policy_test.go index e0d8b9d829b..af661f67713 100644 --- a/aws/resource_aws_organizations_policy_test.go +++ b/aws/resource_aws_organizations_policy_test.go @@ -7,9 +7,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/organizations" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAwsOrganizationsPolicy_basic(t *testing.T) { @@ -28,7 +28,7 @@ func testAccAwsOrganizationsPolicy_basic(t *testing.T) { Config: testAccAwsOrganizationsPolicyConfig_Required(rName, content1), Check: resource.ComposeTestCheckFunc( testAccCheckAwsOrganizationsPolicyExists(resourceName, &policy), - resource.TestMatchResourceAttr(resourceName, "arn", regexp.MustCompile(`^arn:[^:]+:organizations::[^:]+:policy/o-.+/service_control_policy/p-.+$`)), + testAccMatchResourceAttrGlobalARN(resourceName, "arn", "organizations", regexp.MustCompile("policy/o-.+/service_control_policy/p-.+$")), resource.TestCheckResourceAttr(resourceName, "content", content1), resource.TestCheckResourceAttr(resourceName, "description", ""), resource.TestCheckResourceAttr(resourceName, "name", rName), @@ -113,13 +113,102 @@ func testAccAwsOrganizationsPolicy_description(t *testing.T) { }) } -func testAccAwsOrganizationsPolicy_type(t *testing.T) { +func testAccAwsOrganizationsPolicy_type_AI_OPT_OUT(t *testing.T) { var policy organizations.Policy rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_organizations_policy.test" + // Reference: https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out_syntax.html + AiOptOutPolicyContent := `{ "services": { "rekognition": { "opt_out_policy": { "@@assign": "optOut" } }, "lex": { "opt_out_policy": { "@@assign": "optIn" } } } }` + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccOrganizationsAccountPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsOrganizationsPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsOrganizationsPolicyConfig_Type(rName, AiOptOutPolicyContent, organizations.PolicyTypeAiservicesOptOutPolicy), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsOrganizationsPolicyExists(resourceName, &policy), + resource.TestCheckResourceAttr(resourceName, "type", organizations.PolicyTypeAiservicesOptOutPolicy), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccAwsOrganizationsPolicy_type_Backup(t *testing.T) { + var policy organizations.Policy + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_organizations_policy.test" + // Reference: https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_backup_syntax.html + backupPolicyContent := `{ + "plans": { + "PII_Backup_Plan": { + "regions": { "@@assign": [ "ap-northeast-2", "us-east-1", "eu-north-1" ] }, + "rules": { + "Hourly": { + "schedule_expression": { "@@assign": "cron(0 5/1 ? * * *)" }, + "start_backup_window_minutes": { "@@assign": "480" }, + "complete_backup_window_minutes": { "@@assign": "10080" }, + "lifecycle": { + "move_to_cold_storage_after_days": { "@@assign": "180" }, + "delete_after_days": { "@@assign": "270" } + }, + "target_backup_vault_name": { "@@assign": "FortKnox" }, + "copy_actions": { + "arn:aws:backup:us-east-1:$account:backup-vault:secondary_vault": { + "lifecycle": { + "delete_after_days": { "@@assign": "100" }, + "move_to_cold_storage_after_days": { "@@assign": "10" } + } + } + } + } + }, + "selections": { + "tags": { + "datatype": { + "iam_role_arn": { "@@assign": "arn:aws:iam::$account:role/MyIamRole" }, + "tag_key": { "@@assign": "dataType" }, + "tag_value": { "@@assign": [ "PII", "RED" ] } + } + } + } + } + } +}` + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccOrganizationsAccountPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsOrganizationsPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsOrganizationsPolicyConfig_Type(rName, backupPolicyContent, organizations.PolicyTypeBackupPolicy), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsOrganizationsPolicyExists(resourceName, &policy), + resource.TestCheckResourceAttr(resourceName, "type", organizations.PolicyTypeBackupPolicy), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccAwsOrganizationsPolicy_type_SCP(t *testing.T) { + var policy organizations.Policy + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_organizations_policy.test" serviceControlPolicyContent := `{"Version": "2012-10-17", "Statement": { "Effect": "Allow", "Action": "*", "Resource": "*"}}` - tagPolicyContent := `{ "tags": { "Product": { "tag_key": { "@@assign": "Product" }, "enforced_for": { "@@assign": [ "ec2:instance" ] } } } }` resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccOrganizationsAccountPreCheck(t) }, @@ -134,17 +223,37 @@ func testAccAwsOrganizationsPolicy_type(t *testing.T) { ), }, { - Config: testAccAwsOrganizationsPolicyConfig_Type(rName, tagPolicyContent, organizations.PolicyTypeTagPolicy), + Config: testAccAwsOrganizationsPolicyConfig_Required(rName, serviceControlPolicyContent), Check: resource.ComposeTestCheckFunc( testAccCheckAwsOrganizationsPolicyExists(resourceName, &policy), - resource.TestCheckResourceAttr(resourceName, "type", organizations.PolicyTypeTagPolicy), + resource.TestCheckResourceAttr(resourceName, "type", organizations.PolicyTypeServiceControlPolicy), ), }, { - Config: testAccAwsOrganizationsPolicyConfig_Required(rName, serviceControlPolicyContent), + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccAwsOrganizationsPolicy_type_Tag(t *testing.T) { + var policy organizations.Policy + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_organizations_policy.test" + tagPolicyContent := `{ "tags": { "Product": { "tag_key": { "@@assign": "Product" }, "enforced_for": { "@@assign": [ "ec2:instance" ] } } } }` + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccOrganizationsAccountPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsOrganizationsPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsOrganizationsPolicyConfig_Type(rName, tagPolicyContent, organizations.PolicyTypeTagPolicy), Check: resource.ComposeTestCheckFunc( testAccCheckAwsOrganizationsPolicyExists(resourceName, &policy), - resource.TestCheckResourceAttr(resourceName, "type", organizations.PolicyTypeServiceControlPolicy), + resource.TestCheckResourceAttr(resourceName, "type", organizations.PolicyTypeTagPolicy), ), }, { diff --git a/aws/resource_aws_organizations_test.go b/aws/resource_aws_organizations_test.go index b2ed655f5e0..06659e2e50d 100644 --- a/aws/resource_aws_organizations_test.go +++ b/aws/resource_aws_organizations_test.go @@ -4,7 +4,7 @@ import ( "testing" ) -func TestAccAWSOrganizations(t *testing.T) { +func TestAccAWSOrganizations_serial(t *testing.T) { testCases := map[string]map[string]func(t *testing.T){ "Organization": { "basic": testAccAwsOrganizationsOrganization_basic, @@ -26,10 +26,13 @@ func TestAccAWSOrganizations(t *testing.T) { "DataSource": testAccDataSourceAwsOrganizationsOrganizationalUnits_basic, }, "Policy": { - "basic": testAccAwsOrganizationsPolicy_basic, - "concurrent": testAccAwsOrganizationsPolicy_concurrent, - "Description": testAccAwsOrganizationsPolicy_description, - "Type": testAccAwsOrganizationsPolicy_type, + "basic": testAccAwsOrganizationsPolicy_basic, + "concurrent": testAccAwsOrganizationsPolicy_concurrent, + "Description": testAccAwsOrganizationsPolicy_description, + "Type_AI_OPT_OUT": testAccAwsOrganizationsPolicy_type_AI_OPT_OUT, + "Type_Backup": testAccAwsOrganizationsPolicy_type_Backup, + "Type_SCP": testAccAwsOrganizationsPolicy_type_SCP, + "Type_Tag": testAccAwsOrganizationsPolicy_type_Tag, }, "PolicyAttachment": { "Account": testAccAwsOrganizationsPolicyAttachment_Account, diff --git a/aws/resource_aws_pinpoint_adm_channel.go b/aws/resource_aws_pinpoint_adm_channel.go index 750fa6854ad..5afe413ee9c 100644 --- a/aws/resource_aws_pinpoint_adm_channel.go +++ b/aws/resource_aws_pinpoint_adm_channel.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsPinpointADMChannel() *schema.Resource { diff --git a/aws/resource_aws_pinpoint_adm_channel_test.go b/aws/resource_aws_pinpoint_adm_channel_test.go index 0ba073da11c..15fc0596756 100644 --- a/aws/resource_aws_pinpoint_adm_channel_test.go +++ b/aws/resource_aws_pinpoint_adm_channel_test.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/service/pinpoint" "github.com/aws/aws-sdk-go/aws" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) /** diff --git a/aws/resource_aws_pinpoint_apns_channel.go b/aws/resource_aws_pinpoint_apns_channel.go index f1fb37734f3..226508527a8 100644 --- a/aws/resource_aws_pinpoint_apns_channel.go +++ b/aws/resource_aws_pinpoint_apns_channel.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsPinpointAPNSChannel() *schema.Resource { diff --git a/aws/resource_aws_pinpoint_apns_channel_test.go b/aws/resource_aws_pinpoint_apns_channel_test.go index 2a449ed75d8..3ef31171be1 100644 --- a/aws/resource_aws_pinpoint_apns_channel_test.go +++ b/aws/resource_aws_pinpoint_apns_channel_test.go @@ -10,8 +10,8 @@ import ( "github.com/aws/aws-sdk-go/service/pinpoint" "github.com/aws/aws-sdk-go/aws" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) /** diff --git a/aws/resource_aws_pinpoint_apns_sandbox_channel.go b/aws/resource_aws_pinpoint_apns_sandbox_channel.go index 33b30b21579..c16031726a6 100644 --- a/aws/resource_aws_pinpoint_apns_sandbox_channel.go +++ b/aws/resource_aws_pinpoint_apns_sandbox_channel.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsPinpointAPNSSandboxChannel() *schema.Resource { diff --git a/aws/resource_aws_pinpoint_apns_sandbox_channel_test.go b/aws/resource_aws_pinpoint_apns_sandbox_channel_test.go index a350cbcc00b..81543335254 100644 --- a/aws/resource_aws_pinpoint_apns_sandbox_channel_test.go +++ b/aws/resource_aws_pinpoint_apns_sandbox_channel_test.go @@ -10,8 +10,8 @@ import ( "github.com/aws/aws-sdk-go/service/pinpoint" "github.com/aws/aws-sdk-go/aws" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) /** diff --git a/aws/resource_aws_pinpoint_apns_voip_channel.go b/aws/resource_aws_pinpoint_apns_voip_channel.go index 9ca64f4cf52..9d92e87cb58 100644 --- a/aws/resource_aws_pinpoint_apns_voip_channel.go +++ b/aws/resource_aws_pinpoint_apns_voip_channel.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsPinpointAPNSVoipChannel() *schema.Resource { diff --git a/aws/resource_aws_pinpoint_apns_voip_channel_test.go b/aws/resource_aws_pinpoint_apns_voip_channel_test.go index acb190ea839..fce4f86030a 100644 --- a/aws/resource_aws_pinpoint_apns_voip_channel_test.go +++ b/aws/resource_aws_pinpoint_apns_voip_channel_test.go @@ -10,8 +10,8 @@ import ( "github.com/aws/aws-sdk-go/service/pinpoint" "github.com/aws/aws-sdk-go/aws" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) /** diff --git a/aws/resource_aws_pinpoint_apns_voip_sandbox_channel.go b/aws/resource_aws_pinpoint_apns_voip_sandbox_channel.go index c668835ec19..061f06a0a23 100644 --- a/aws/resource_aws_pinpoint_apns_voip_sandbox_channel.go +++ b/aws/resource_aws_pinpoint_apns_voip_sandbox_channel.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsPinpointAPNSVoipSandboxChannel() *schema.Resource { diff --git a/aws/resource_aws_pinpoint_apns_voip_sandbox_channel_test.go b/aws/resource_aws_pinpoint_apns_voip_sandbox_channel_test.go index dc10b25f37d..4eda2501c82 100644 --- a/aws/resource_aws_pinpoint_apns_voip_sandbox_channel_test.go +++ b/aws/resource_aws_pinpoint_apns_voip_sandbox_channel_test.go @@ -10,8 +10,8 @@ import ( "github.com/aws/aws-sdk-go/service/pinpoint" "github.com/aws/aws-sdk-go/aws" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) /** diff --git a/aws/resource_aws_pinpoint_app.go b/aws/resource_aws_pinpoint_app.go index a22085d0a4c..508b9722190 100644 --- a/aws/resource_aws_pinpoint_app.go +++ b/aws/resource_aws_pinpoint_app.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_pinpoint_app_test.go b/aws/resource_aws_pinpoint_app_test.go index 674fa4d8723..abafa6d439f 100644 --- a/aws/resource_aws_pinpoint_app_test.go +++ b/aws/resource_aws_pinpoint_app_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_pinpoint_baidu_channel.go b/aws/resource_aws_pinpoint_baidu_channel.go index 43acd25d054..4db2db74f67 100644 --- a/aws/resource_aws_pinpoint_baidu_channel.go +++ b/aws/resource_aws_pinpoint_baidu_channel.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsPinpointBaiduChannel() *schema.Resource { diff --git a/aws/resource_aws_pinpoint_baidu_channel_test.go b/aws/resource_aws_pinpoint_baidu_channel_test.go index 3e2b1bf62f1..3d440dfcf53 100644 --- a/aws/resource_aws_pinpoint_baidu_channel_test.go +++ b/aws/resource_aws_pinpoint_baidu_channel_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/service/pinpoint" "github.com/aws/aws-sdk-go/aws" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSPinpointBaiduChannel_basic(t *testing.T) { diff --git a/aws/resource_aws_pinpoint_email_channel.go b/aws/resource_aws_pinpoint_email_channel.go index 606a9dfac07..b77e9ec458d 100644 --- a/aws/resource_aws_pinpoint_email_channel.go +++ b/aws/resource_aws_pinpoint_email_channel.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsPinpointEmailChannel() *schema.Resource { diff --git a/aws/resource_aws_pinpoint_email_channel_test.go b/aws/resource_aws_pinpoint_email_channel_test.go index e5156d5f2a4..0aebeca550a 100644 --- a/aws/resource_aws_pinpoint_email_channel_test.go +++ b/aws/resource_aws_pinpoint_email_channel_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/service/pinpoint" "github.com/aws/aws-sdk-go/aws" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSPinpointEmailChannel_basic(t *testing.T) { diff --git a/aws/resource_aws_pinpoint_event_stream.go b/aws/resource_aws_pinpoint_event_stream.go index 78eb88faa08..89e60aa4277 100644 --- a/aws/resource_aws_pinpoint_event_stream.go +++ b/aws/resource_aws_pinpoint_event_stream.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsPinpointEventStream() *schema.Resource { diff --git a/aws/resource_aws_pinpoint_event_stream_test.go b/aws/resource_aws_pinpoint_event_stream_test.go index d9d7cdf9e18..f5ba1270a20 100644 --- a/aws/resource_aws_pinpoint_event_stream_test.go +++ b/aws/resource_aws_pinpoint_event_stream_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSPinpointEventStream_basic(t *testing.T) { diff --git a/aws/resource_aws_pinpoint_gcm_channel.go b/aws/resource_aws_pinpoint_gcm_channel.go index 6f12797735b..18288e09daa 100644 --- a/aws/resource_aws_pinpoint_gcm_channel.go +++ b/aws/resource_aws_pinpoint_gcm_channel.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsPinpointGCMChannel() *schema.Resource { diff --git a/aws/resource_aws_pinpoint_gcm_channel_test.go b/aws/resource_aws_pinpoint_gcm_channel_test.go index 552a1afb5f3..6c7bb8eed96 100644 --- a/aws/resource_aws_pinpoint_gcm_channel_test.go +++ b/aws/resource_aws_pinpoint_gcm_channel_test.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/service/pinpoint" "github.com/aws/aws-sdk-go/aws" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) /** diff --git a/aws/resource_aws_pinpoint_sms_channel.go b/aws/resource_aws_pinpoint_sms_channel.go index f021b7ed88d..3838e110ab3 100644 --- a/aws/resource_aws_pinpoint_sms_channel.go +++ b/aws/resource_aws_pinpoint_sms_channel.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/pinpoint" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsPinpointSMSChannel() *schema.Resource { diff --git a/aws/resource_aws_pinpoint_sms_channel_test.go b/aws/resource_aws_pinpoint_sms_channel_test.go index 3c25e0464b8..c473a5a8b73 100644 --- a/aws/resource_aws_pinpoint_sms_channel_test.go +++ b/aws/resource_aws_pinpoint_sms_channel_test.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/service/pinpoint" "github.com/aws/aws-sdk-go/aws" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSPinpointSMSChannel_basic(t *testing.T) { diff --git a/aws/resource_aws_placement_group.go b/aws/resource_aws_placement_group.go index b7fe7931232..c24489b91f7 100644 --- a/aws/resource_aws_placement_group.go +++ b/aws/resource_aws_placement_group.go @@ -6,10 +6,11 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -24,6 +25,10 @@ func resourceAwsPlacementGroup() *schema.Resource { }, Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, "name": { Type: schema.TypeString, Required: true, @@ -87,7 +92,7 @@ func resourceAwsPlacementGroupCreate(d *schema.ResourceData, meta interface{}) e } pg := out.PlacementGroups[0] - return out, *pg.State, nil + return out, aws.StringValue(pg.State), nil }, } @@ -131,6 +136,16 @@ func resourceAwsPlacementGroupRead(d *schema.ResourceData, meta interface{}) err return fmt.Errorf("error setting tags: %s", err) } + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Service: "ec2", + Region: meta.(*AWSClient).region, + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("placement-group/%s", d.Id()), + }.String() + + d.Set("arn", arn) + return nil } @@ -182,11 +197,12 @@ func resourceAwsPlacementGroupDelete(d *schema.ResourceData, meta interface{}) e } pg := out.PlacementGroups[0] - if *pg.State == ec2.PlacementGroupStateAvailable { - log.Printf("[DEBUG] Accepted status when deleting EC2 Placement group: %q %v", d.Id(), *pg.State) + if aws.StringValue(pg.State) == ec2.PlacementGroupStateAvailable { + log.Printf("[DEBUG] Accepted status when deleting EC2 Placement group: %q %v", d.Id(), + aws.StringValue(pg.State)) } - return out, *pg.State, nil + return out, aws.StringValue(pg.State), nil }, } diff --git a/aws/resource_aws_placement_group_test.go b/aws/resource_aws_placement_group_test.go index 7a1815bb0c1..ec4b27f8044 100644 --- a/aws/resource_aws_placement_group_test.go +++ b/aws/resource_aws_placement_group_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSPlacementGroup_basic(t *testing.T) { @@ -27,6 +27,7 @@ func TestAccAWSPlacementGroup_basic(t *testing.T) { testAccCheckAWSPlacementGroupExists(resourceName, &pg), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "strategy", "cluster"), + testAccCheckResourceAttrRegionalARN(resourceName, "arn", "ec2", fmt.Sprintf("placement-group/%s", rName)), ), }, { @@ -95,7 +96,7 @@ func TestAccAWSPlacementGroup_disappears(t *testing.T) { Config: testAccAWSPlacementGroupConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSPlacementGroupExists(resourceName, &pg), - testAccCheckAWSPlacementGroupDisappears(&pg), + testAccCheckResourceDisappears(testAccProvider, resourceAwsPlacementGroup(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -128,16 +129,6 @@ func testAccCheckAWSPlacementGroupDestroy(s *terraform.State) error { return nil } -func testAccCheckAWSPlacementGroupDisappears(pg *ec2.PlacementGroup) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - req := &ec2.DeletePlacementGroupInput{GroupName: pg.GroupName} - _, err := conn.DeletePlacementGroup(req) - - return err - } -} - func testAccCheckAWSPlacementGroupExists(n string, pg *ec2.PlacementGroup) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] diff --git a/aws/resource_aws_proxy_protocol_policy.go b/aws/resource_aws_proxy_protocol_policy.go index 94cf95823e0..14452c7cabe 100644 --- a/aws/resource_aws_proxy_protocol_policy.go +++ b/aws/resource_aws_proxy_protocol_policy.go @@ -8,7 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsProxyProtocolPolicy() *schema.Resource { diff --git a/aws/resource_aws_proxy_protocol_policy_test.go b/aws/resource_aws_proxy_protocol_policy_test.go index 46212498ebd..bdd314a7a95 100644 --- a/aws/resource_aws_proxy_protocol_policy_test.go +++ b/aws/resource_aws_proxy_protocol_policy_test.go @@ -6,18 +6,18 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/elb" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSProxyProtocolPolicy_basic(t *testing.T) { lbName := fmt.Sprintf("tf-test-lb-%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckProxyProtocolPolicyDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckProxyProtocolPolicyDestroy, Steps: []resource.TestStep{ { Config: testAccProxyProtocolPolicyConfig(lbName), @@ -26,8 +26,7 @@ func TestAccAWSProxyProtocolPolicy_basic(t *testing.T) { "aws_proxy_protocol_policy.smtp", "load_balancer", lbName), resource.TestCheckResourceAttr( "aws_proxy_protocol_policy.smtp", "instance_ports.#", "1"), - resource.TestCheckResourceAttr( - "aws_proxy_protocol_policy.smtp", "instance_ports.4196041389", "25"), + tfawsresource.TestCheckTypeSetElemAttr("aws_proxy_protocol_policy.smtp", "instance_ports.*", "25"), ), }, { @@ -37,10 +36,8 @@ func TestAccAWSProxyProtocolPolicy_basic(t *testing.T) { "aws_proxy_protocol_policy.smtp", "load_balancer", lbName), resource.TestCheckResourceAttr( "aws_proxy_protocol_policy.smtp", "instance_ports.#", "2"), - resource.TestCheckResourceAttr( - "aws_proxy_protocol_policy.smtp", "instance_ports.4196041389", "25"), - resource.TestCheckResourceAttr( - "aws_proxy_protocol_policy.smtp", "instance_ports.1925441437", "587"), + tfawsresource.TestCheckTypeSetElemAttr("aws_proxy_protocol_policy.smtp", "instance_ports.*", "25"), + tfawsresource.TestCheckTypeSetElemAttr("aws_proxy_protocol_policy.smtp", "instance_ports.*", "587"), ), }, }, diff --git a/aws/resource_aws_qldb_ledger.go b/aws/resource_aws_qldb_ledger.go index 442b226e5ad..9e3e1b0ad43 100644 --- a/aws/resource_aws_qldb_ledger.go +++ b/aws/resource_aws_qldb_ledger.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/qldb" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsQLDBLedger() *schema.Resource { diff --git a/aws/resource_aws_qldb_ledger_test.go b/aws/resource_aws_qldb_ledger_test.go index 61626712996..187e96b8617 100644 --- a/aws/resource_aws_qldb_ledger_test.go +++ b/aws/resource_aws_qldb_ledger_test.go @@ -7,10 +7,10 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/qldb" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" ) diff --git a/aws/resource_aws_quicksight_group.go b/aws/resource_aws_quicksight_group.go index 8376a415868..ef171abea75 100644 --- a/aws/resource_aws_quicksight_group.go +++ b/aws/resource_aws_quicksight_group.go @@ -5,8 +5,8 @@ import ( "log" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/quicksight" diff --git a/aws/resource_aws_quicksight_group_test.go b/aws/resource_aws_quicksight_group_test.go index 6d2756f5a93..6b2f229523a 100644 --- a/aws/resource_aws_quicksight_group_test.go +++ b/aws/resource_aws_quicksight_group_test.go @@ -5,9 +5,9 @@ import ( "strings" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" diff --git a/aws/resource_aws_quicksight_user.go b/aws/resource_aws_quicksight_user.go index 63f2145b8c8..2150b67a5be 100644 --- a/aws/resource_aws_quicksight_user.go +++ b/aws/resource_aws_quicksight_user.go @@ -5,8 +5,8 @@ import ( "log" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/quicksight" diff --git a/aws/resource_aws_quicksight_user_test.go b/aws/resource_aws_quicksight_user_test.go index d83438c8dc0..4cff5b7a8f0 100644 --- a/aws/resource_aws_quicksight_user_test.go +++ b/aws/resource_aws_quicksight_user_test.go @@ -5,9 +5,9 @@ import ( "strings" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" diff --git a/aws/resource_aws_ram_principal_association.go b/aws/resource_aws_ram_principal_association.go index 6812d5075eb..9d91795fe9e 100644 --- a/aws/resource_aws_ram_principal_association.go +++ b/aws/resource_aws_ram_principal_association.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ram" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsRamPrincipalAssociation() *schema.Resource { diff --git a/aws/resource_aws_ram_principal_association_test.go b/aws/resource_aws_ram_principal_association_test.go index c6a4976bf08..f0a779eceb6 100644 --- a/aws/resource_aws_ram_principal_association_test.go +++ b/aws/resource_aws_ram_principal_association_test.go @@ -4,9 +4,9 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ram" diff --git a/aws/resource_aws_ram_resource_association.go b/aws/resource_aws_ram_resource_association.go index 8e127446a68..94ce715a84b 100644 --- a/aws/resource_aws_ram_resource_association.go +++ b/aws/resource_aws_ram_resource_association.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ram" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsRamResourceAssociation() *schema.Resource { diff --git a/aws/resource_aws_ram_resource_association_test.go b/aws/resource_aws_ram_resource_association_test.go index c48145bde40..0ef25f831f3 100644 --- a/aws/resource_aws_ram_resource_association_test.go +++ b/aws/resource_aws_ram_resource_association_test.go @@ -4,9 +4,9 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ram" diff --git a/aws/resource_aws_ram_resource_share.go b/aws/resource_aws_ram_resource_share.go index 09443ae58b7..1c15f49f5ea 100644 --- a/aws/resource_aws_ram_resource_share.go +++ b/aws/resource_aws_ram_resource_share.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ram" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -132,7 +132,7 @@ func resourceAwsRamResourceShareRead(d *schema.ResourceData, meta interface{}) e func resourceAwsRamResourceShareUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ramconn - if d.HasChange("name") || d.HasChange("allow_external_principals") { + if d.HasChanges("name", "allow_external_principals") { request := &ram.UpdateResourceShareInput{ ResourceShareArn: aws.String(d.Id()), Name: aws.String(d.Get("name").(string)), diff --git a/aws/resource_aws_ram_resource_share_accepter.go b/aws/resource_aws_ram_resource_share_accepter.go index 8a15023255a..61132d95763 100644 --- a/aws/resource_aws_ram_resource_share_accepter.go +++ b/aws/resource_aws_ram_resource_share_accepter.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ram" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsRamResourceShareAccepter() *schema.Resource { @@ -151,7 +151,7 @@ func resourceAwsRamResourceShareAccepterRead(d *schema.ResourceData, meta interf shares, err := conn.GetResourceShares(listResourceSharesInput) if err != nil { - return fmt.Errorf("Error retrieving resource shares: %s", err) + return fmt.Errorf("error retrieving resource shares: %w", err) } if len(shares.ResourceShares) != 1 { diff --git a/aws/resource_aws_ram_resource_share_accepter_test.go b/aws/resource_aws_ram_resource_share_accepter_test.go index ec93a33c892..87a67e6f03f 100644 --- a/aws/resource_aws_ram_resource_share_accepter_test.go +++ b/aws/resource_aws_ram_resource_share_accepter_test.go @@ -5,10 +5,10 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ram" @@ -17,6 +17,8 @@ import ( func TestAccAwsRamResourceShareAccepter_basic(t *testing.T) { var providers []*schema.Provider resourceName := "aws_ram_resource_share_accepter.test" + principalAssociationResourceName := "aws_ram_principal_association.test" + shareName := fmt.Sprintf("tf-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) resource.ParallelTest(t, resource.TestCase{ @@ -31,11 +33,11 @@ func TestAccAwsRamResourceShareAccepter_basic(t *testing.T) { Config: testAccAwsRamResourceShareAccepterBasic(shareName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsRamResourceShareAccepterExists(resourceName), - resource.TestMatchResourceAttr(resourceName, "share_arn", regexp.MustCompile(`^arn\:aws\:ram\:.*resource-share/.+$`)), - resource.TestMatchResourceAttr(resourceName, "invitation_arn", regexp.MustCompile(`^arn\:aws\:ram\:.*resource-share-invitation/.+$`)), - resource.TestMatchResourceAttr(resourceName, "share_id", regexp.MustCompile(`^rs-.+$`)), + resource.TestCheckResourceAttrPair(resourceName, "share_arn", principalAssociationResourceName, "resource_share_arn"), + testAccMatchResourceAttrRegionalARNAccountID(resourceName, "invitation_arn", "ram", `\d{12}`, regexp.MustCompile(fmt.Sprintf("resource-share-invitation/%s$", uuidRegexPattern))), + resource.TestMatchResourceAttr(resourceName, "share_id", regexp.MustCompile(fmt.Sprintf(`^rs-%s$`, uuidRegexPattern))), resource.TestCheckResourceAttr(resourceName, "status", ram.ResourceShareStatusActive), - resource.TestMatchResourceAttr(resourceName, "receiver_account_id", regexp.MustCompile(`\d{12}`)), + testAccCheckResourceAttrAccountID(resourceName, "receiver_account_id"), resource.TestMatchResourceAttr(resourceName, "sender_account_id", regexp.MustCompile(`\d{12}`)), resource.TestCheckResourceAttr(resourceName, "share_name", shareName), resource.TestCheckResourceAttr(resourceName, "resources.%", "0"), @@ -106,8 +108,12 @@ func testAccCheckAwsRamResourceShareAccepterExists(name string) resource.TestChe func testAccAwsRamResourceShareAccepterBasic(shareName string) string { return testAccAlternateAccountProviderConfig() + fmt.Sprintf(` +resource "aws_ram_resource_share_accepter" "test" { + share_arn = "${aws_ram_principal_association.test.resource_share_arn}" +} + resource "aws_ram_resource_share" "test" { - provider = "aws.alternate" + provider = "awsalternate" name = %[1]q allow_external_principals = true @@ -118,16 +124,12 @@ resource "aws_ram_resource_share" "test" { } resource "aws_ram_principal_association" "test" { - provider = "aws.alternate" + provider = "awsalternate" principal = "${data.aws_caller_identity.receiver.account_id}" resource_share_arn = "${aws_ram_resource_share.test.arn}" } data "aws_caller_identity" "receiver" {} - -resource "aws_ram_resource_share_accepter" "test" { - share_arn = "${aws_ram_principal_association.test.resource_share_arn}" -} `, shareName) } diff --git a/aws/resource_aws_ram_resource_share_test.go b/aws/resource_aws_ram_resource_share_test.go index e4a6ca31ef2..6c5b8da402e 100644 --- a/aws/resource_aws_ram_resource_share_test.go +++ b/aws/resource_aws_ram_resource_share_test.go @@ -5,9 +5,9 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ram" diff --git a/aws/resource_aws_rds_cluster.go b/aws/resource_aws_rds_cluster.go index 05dbbe43f0a..7e31b3080c6 100644 --- a/aws/resource_aws_rds_cluster.go +++ b/aws/resource_aws_rds_cluster.go @@ -10,15 +10,16 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) const ( - rdsClusterScalingConfiguration_DefaultMinCapacity = 2 + rdsClusterScalingConfiguration_DefaultMinCapacity = 1 rdsClusterScalingConfiguration_DefaultMaxCapacity = 16 + rdsClusterTimeoutDelete = 2 * time.Minute ) func resourceAwsRDSCluster() *schema.Resource { @@ -452,7 +453,7 @@ func resourceAwsRDSClusterCreate(d *schema.ResourceData, meta interface{}) error DeletionProtection: aws.Bool(d.Get("deletion_protection").(bool)), Engine: aws.String(d.Get("engine").(string)), EngineMode: aws.String(d.Get("engine_mode").(string)), - ScalingConfiguration: expandRdsClusterScalingConfiguration(d.Get("scaling_configuration").([]interface{}), d.Get("engine_mode").(string)), + ScalingConfiguration: expandRdsClusterScalingConfiguration(d.Get("scaling_configuration").([]interface{})), SnapshotIdentifier: aws.String(d.Get("snapshot_identifier").(string)), Tags: tags, } @@ -540,98 +541,6 @@ func resourceAwsRDSClusterCreate(d *schema.ResourceData, meta interface{}) error if err != nil { return fmt.Errorf("Error creating RDS Cluster: %s", err) } - } else if _, ok := d.GetOk("replication_source_identifier"); ok { - createOpts := &rds.CreateDBClusterInput{ - CopyTagsToSnapshot: aws.Bool(d.Get("copy_tags_to_snapshot").(bool)), - DBClusterIdentifier: aws.String(identifier), - DeletionProtection: aws.Bool(d.Get("deletion_protection").(bool)), - Engine: aws.String(d.Get("engine").(string)), - EngineMode: aws.String(d.Get("engine_mode").(string)), - ReplicationSourceIdentifier: aws.String(d.Get("replication_source_identifier").(string)), - ScalingConfiguration: expandRdsClusterScalingConfiguration(d.Get("scaling_configuration").([]interface{}), d.Get("engine_mode").(string)), - Tags: tags, - } - - // Need to check value > 0 due to: - // InvalidParameterValue: Backtrack is not enabled for the aurora-postgresql engine. - if v, ok := d.GetOk("backtrack_window"); ok && v.(int) > 0 { - createOpts.BacktrackWindow = aws.Int64(int64(v.(int))) - } - - if attr, ok := d.GetOk("port"); ok { - createOpts.Port = aws.Int64(int64(attr.(int))) - } - - if attr, ok := d.GetOk("db_subnet_group_name"); ok { - createOpts.DBSubnetGroupName = aws.String(attr.(string)) - } - - if attr, ok := d.GetOk("db_cluster_parameter_group_name"); ok { - createOpts.DBClusterParameterGroupName = aws.String(attr.(string)) - } - - if attr, ok := d.GetOk("engine_version"); ok { - createOpts.EngineVersion = aws.String(attr.(string)) - } - - if attr := d.Get("vpc_security_group_ids").(*schema.Set); attr.Len() > 0 { - createOpts.VpcSecurityGroupIds = expandStringList(attr.List()) - } - - if attr := d.Get("availability_zones").(*schema.Set); attr.Len() > 0 { - createOpts.AvailabilityZones = expandStringList(attr.List()) - } - - if v, ok := d.GetOk("backup_retention_period"); ok { - createOpts.BackupRetentionPeriod = aws.Int64(int64(v.(int))) - } - - if v, ok := d.GetOk("preferred_backup_window"); ok { - createOpts.PreferredBackupWindow = aws.String(v.(string)) - } - - if v, ok := d.GetOk("preferred_maintenance_window"); ok { - createOpts.PreferredMaintenanceWindow = aws.String(v.(string)) - } - - if attr, ok := d.GetOk("kms_key_id"); ok { - createOpts.KmsKeyId = aws.String(attr.(string)) - } - - if attr, ok := d.GetOk("source_region"); ok { - createOpts.SourceRegion = aws.String(attr.(string)) - } - - if attr, ok := d.GetOkExists("storage_encrypted"); ok { - createOpts.StorageEncrypted = aws.Bool(attr.(bool)) - } - - if attr, ok := d.GetOk("enabled_cloudwatch_logs_exports"); ok && len(attr.([]interface{})) > 0 { - createOpts.EnableCloudwatchLogsExports = expandStringList(attr.([]interface{})) - } - - log.Printf("[DEBUG] Create RDS Cluster as read replica: %s", createOpts) - var resp *rds.CreateDBClusterOutput - err := resource.Retry(1*time.Minute, func() *resource.RetryError { - var err error - resp, err = conn.CreateDBCluster(createOpts) - if err != nil { - if isAWSErr(err, "InvalidParameterValue", "IAM role ARN value is invalid or does not include the required permissions") { - return resource.RetryableError(err) - } - return resource.NonRetryableError(err) - } - return nil - }) - if isResourceTimeoutError(err) { - resp, err = conn.CreateDBCluster(createOpts) - } - if err != nil { - return fmt.Errorf("error creating RDS cluster: %s", err) - } - - log.Printf("[DEBUG]: RDS Cluster create response: %s", resp) - } else if v, ok := d.GetOk("s3_import"); ok { if _, ok := d.GetOk("master_password"); !ok { return fmt.Errorf(`provider.aws: aws_db_instance: %s: "master_password": required field is not set`, d.Get("name").(string)) @@ -751,26 +660,20 @@ func resourceAwsRDSClusterCreate(d *schema.ResourceData, meta interface{}) error } else { - if _, ok := d.GetOk("global_cluster_identifier"); !ok { - if _, ok := d.GetOk("master_password"); !ok { - return fmt.Errorf(`provider.aws: aws_db_instance: %s: "master_password": required field is not set`, d.Get("database_name").(string)) - } - - if _, ok := d.GetOk("master_username"); !ok { - return fmt.Errorf(`provider.aws: aws_db_instance: %s: "master_username": required field is not set`, d.Get("database_name").(string)) - } - } - createOpts := &rds.CreateDBClusterInput{ CopyTagsToSnapshot: aws.Bool(d.Get("copy_tags_to_snapshot").(bool)), DBClusterIdentifier: aws.String(identifier), DeletionProtection: aws.Bool(d.Get("deletion_protection").(bool)), Engine: aws.String(d.Get("engine").(string)), EngineMode: aws.String(d.Get("engine_mode").(string)), - ScalingConfiguration: expandRdsClusterScalingConfiguration(d.Get("scaling_configuration").([]interface{}), d.Get("engine_mode").(string)), + ScalingConfiguration: expandRdsClusterScalingConfiguration(d.Get("scaling_configuration").([]interface{})), Tags: tags, } + // Note: Username and password credentials are required and valid + // unless the cluster is a read-replica. This also applies to clusters + // within a global cluster. Providing a password and/or username for + // a replica will result in an InvalidParameterValue error. if v, ok := d.GetOk("master_password"); ok && v.(string) != "" { createOpts.MasterUserPassword = aws.String(v.(string)) } @@ -848,6 +751,10 @@ func resourceAwsRDSClusterCreate(d *schema.ResourceData, meta interface{}) error createOpts.EnableCloudwatchLogsExports = expandStringList(attr.([]interface{})) } + if attr, ok := d.GetOk("replication_source_identifier"); ok && createOpts.GlobalClusterIdentifier == nil { + createOpts.ReplicationSourceIdentifier = aws.String(attr.(string)) + } + if attr, ok := d.GetOkExists("storage_encrypted"); ok { createOpts.StorageEncrypted = aws.Bool(attr.(bool)) } @@ -1140,7 +1047,7 @@ func resourceAwsRDSClusterUpdate(d *schema.ResourceData, meta interface{}) error } if d.HasChange("scaling_configuration") { - req.ScalingConfiguration = expandRdsClusterScalingConfiguration(d.Get("scaling_configuration").([]interface{}), d.Get("engine_mode").(string)) + req.ScalingConfiguration = expandRdsClusterScalingConfiguration(d.Get("scaling_configuration").([]interface{})) requestUpdate = true } @@ -1283,12 +1190,15 @@ func resourceAwsRDSClusterDelete(d *schema.ResourceData, meta interface{}) error log.Printf("[DEBUG] RDS Cluster delete options: %s", deleteOpts) - err := resource.Retry(1*time.Minute, func() *resource.RetryError { + err := resource.Retry(rdsClusterTimeoutDelete, func() *resource.RetryError { _, err := conn.DeleteDBCluster(&deleteOpts) if err != nil { if isAWSErr(err, rds.ErrCodeInvalidDBClusterStateFault, "is not currently in the available state") { return resource.RetryableError(err) } + if isAWSErr(err, rds.ErrCodeInvalidDBClusterStateFault, "cluster is a part of a global cluster") { + return resource.RetryableError(err) + } if isAWSErr(err, rds.ErrCodeDBClusterNotFoundFault, "") { return nil } diff --git a/aws/resource_aws_rds_cluster_endpoint.go b/aws/resource_aws_rds_cluster_endpoint.go index f5f2c073cd6..7523e3beb51 100644 --- a/aws/resource_aws_rds_cluster_endpoint.go +++ b/aws/resource_aws_rds_cluster_endpoint.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_rds_cluster_endpoint_test.go b/aws/resource_aws_rds_cluster_endpoint_test.go index eebb9cdd920..f502c4d6762 100644 --- a/aws/resource_aws_rds_cluster_endpoint_test.go +++ b/aws/resource_aws_rds_cluster_endpoint_test.go @@ -9,10 +9,10 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSRDSClusterEndpoint_basic(t *testing.T) { diff --git a/aws/resource_aws_rds_cluster_instance.go b/aws/resource_aws_rds_cluster_instance.go index f8ee14d79c6..3e823b672a2 100644 --- a/aws/resource_aws_rds_cluster_instance.go +++ b/aws/resource_aws_rds_cluster_instance.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/rds" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -496,7 +496,7 @@ func resourceAwsRDSClusterInstanceUpdate(d *schema.ResourceData, meta interface{ requestUpdate = true } - if d.HasChange("performance_insights_enabled") || d.HasChange("performance_insights_kms_key_id") { + if d.HasChanges("performance_insights_enabled", "performance_insights_kms_key_id") { req.EnablePerformanceInsights = aws.Bool(d.Get("performance_insights_enabled").(bool)) if v, ok := d.GetOk("performance_insights_kms_key_id"); ok { diff --git a/aws/resource_aws_rds_cluster_instance_test.go b/aws/resource_aws_rds_cluster_instance_test.go index 075e80bb342..8a001834d03 100644 --- a/aws/resource_aws_rds_cluster_instance_test.go +++ b/aws/resource_aws_rds_cluster_instance_test.go @@ -7,9 +7,9 @@ import ( "testing" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" @@ -192,7 +192,7 @@ func TestAccAWSRDSClusterInstance_generatedName(t *testing.T) { func TestAccAWSRDSClusterInstance_kmsKey(t *testing.T) { var v rds.DBInstance - keyRegex := regexp.MustCompile("^arn:aws:kms:") + kmsKeyResourceName := "aws_kms_key.foo" resourceName := "aws_rds_cluster_instance.cluster_instances" resource.ParallelTest(t, resource.TestCase{ @@ -204,7 +204,7 @@ func TestAccAWSRDSClusterInstance_kmsKey(t *testing.T) { Config: testAccAWSClusterInstanceConfigKmsKey(acctest.RandInt()), Check: resource.ComposeTestCheckFunc( testAccCheckAWSClusterInstanceExists(resourceName, &v), - resource.TestMatchResourceAttr(resourceName, "kms_key_id", keyRegex), + resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", kmsKeyResourceName, "arn"), ), }, { diff --git a/aws/resource_aws_rds_cluster_parameter_group.go b/aws/resource_aws_rds_cluster_parameter_group.go index ee38be2dc36..97f53cf18dc 100644 --- a/aws/resource_aws_rds_cluster_parameter_group.go +++ b/aws/resource_aws_rds_cluster_parameter_group.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/rds" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -141,7 +141,7 @@ func resourceAwsRDSClusterParameterGroupRead(d *schema.ResourceData, meta interf } if len(describeResp.DBClusterParameterGroups) != 1 || - *describeResp.DBClusterParameterGroups[0].DBClusterParameterGroupName != d.Id() { + aws.StringValue(describeResp.DBClusterParameterGroups[0].DBClusterParameterGroupName) != d.Id() { return fmt.Errorf("Unable to find Cluster Parameter Group: %#v", describeResp.DBClusterParameterGroups) } @@ -196,11 +196,7 @@ func resourceAwsRDSClusterParameterGroupUpdate(d *schema.ResourceData, meta inte ns := n.(*schema.Set) // Expand the "parameter" set to aws-sdk-go compat []rds.Parameter - parameters, err := expandParameters(ns.Difference(os).List()) - if err != nil { - return err - } - + parameters := expandParameters(ns.Difference(os).List()) if len(parameters) > 0 { // We can only modify 20 parameters at a time, so walk them until // we've got them all. @@ -218,7 +214,7 @@ func resourceAwsRDSClusterParameterGroupUpdate(d *schema.ResourceData, meta inte } log.Printf("[DEBUG] Modify DB Cluster Parameter Group: %s", modifyOpts) - _, err = rdsconn.ModifyDBClusterParameterGroup(&modifyOpts) + _, err := rdsconn.ModifyDBClusterParameterGroup(&modifyOpts) if err != nil { return fmt.Errorf("error modifying DB Cluster Parameter Group: %s", err) } @@ -226,10 +222,7 @@ func resourceAwsRDSClusterParameterGroupUpdate(d *schema.ResourceData, meta inte } // Reset parameters that have been removed - parameters, err = expandParameters(os.Difference(ns).List()) - if err != nil { - return err - } + parameters = expandParameters(os.Difference(ns).List()) if len(parameters) > 0 { for parameters != nil { parameterGroupName := d.Get("name").(string) diff --git a/aws/resource_aws_rds_cluster_parameter_group_test.go b/aws/resource_aws_rds_cluster_parameter_group_test.go index 0097ea4fde2..28ce0d0db04 100644 --- a/aws/resource_aws_rds_cluster_parameter_group_test.go +++ b/aws/resource_aws_rds_cluster_parameter_group_test.go @@ -12,9 +12,10 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -89,10 +90,9 @@ func TestAccAWSDBClusterParameterGroup_basic(t *testing.T) { parameterGroupName := fmt.Sprintf("cluster-parameter-group-test-terraform-%d", acctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSDBClusterParameterGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDBClusterParameterGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSDBClusterParameterGroupConfig(parameterGroupName), @@ -103,12 +103,18 @@ func TestAccAWSDBClusterParameterGroup_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", parameterGroupName), resource.TestCheckResourceAttr(resourceName, "family", "aurora5.6"), resource.TestCheckResourceAttr(resourceName, "description", "Test cluster parameter group for terraform"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.name", "character_set_results"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.name", "character_set_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.name", "character_set_client"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.value", "utf8"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_results", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_server", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_client", + "value": "utf8", + }), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), ), }, @@ -125,16 +131,26 @@ func TestAccAWSDBClusterParameterGroup_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", parameterGroupName), resource.TestCheckResourceAttr(resourceName, "family", "aurora5.6"), resource.TestCheckResourceAttr(resourceName, "description", "Test cluster parameter group for terraform"), - resource.TestCheckResourceAttr(resourceName, "parameter.1706463059.name", "collation_connection"), - resource.TestCheckResourceAttr(resourceName, "parameter.1706463059.value", "utf8_unicode_ci"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.name", "character_set_results"), - resource.TestCheckResourceAttr(resourceName, "parameter.1708034931.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.name", "character_set_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2475805061.name", "collation_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.2475805061.value", "utf8_unicode_ci"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.name", "character_set_client"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.value", "utf8"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "collation_connection", + "value": "utf8_unicode_ci", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_results", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_server", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "collation_server", + "value": "utf8_unicode_ci", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_client", + "value": "utf8", + }), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), ), }, @@ -145,8 +161,19 @@ func TestAccAWSDBClusterParameterGroup_basic(t *testing.T) { testAccCheckAWSDBClusterParameterGroupAttributes(&v, parameterGroupName), testAccCheckAWSRDSClusterParameterNotUserDefined(resourceName, "collation_connection"), testAccCheckAWSRDSClusterParameterNotUserDefined(resourceName, "collation_server"), - resource.TestCheckNoResourceAttr(resourceName, "parameter.2475805061.value"), - resource.TestCheckNoResourceAttr(resourceName, "parameter.1706463059.value"), + resource.TestCheckResourceAttr(resourceName, "parameter.#", "3"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_results", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_server", + "value": "utf8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_client", + "value": "utf8", + }), ), }, }, @@ -159,10 +186,9 @@ func TestAccAWSDBClusterParameterGroup_withApplyMethod(t *testing.T) { resourceName := "aws_rds_cluster_parameter_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSDBClusterParameterGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSDBClusterParameterGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSDBClusterParameterGroupConfigWithApplyMethod(parameterGroupName), @@ -173,12 +199,16 @@ func TestAccAWSDBClusterParameterGroup_withApplyMethod(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", parameterGroupName), resource.TestCheckResourceAttr(resourceName, "family", "aurora5.6"), resource.TestCheckResourceAttr(resourceName, "description", "Test cluster parameter group for terraform"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.name", "character_set_server"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2421266705.apply_method", "immediate"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.name", "character_set_client"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.value", "utf8"), - resource.TestCheckResourceAttr(resourceName, "parameter.2478663599.apply_method", "pending-reboot"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_server", + "value": "utf8", + "apply_method": "immediate", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "character_set_client", + "value": "utf8", + "apply_method": "pending-reboot", + }), ), }, { diff --git a/aws/resource_aws_rds_cluster_test.go b/aws/resource_aws_rds_cluster_test.go index 5cf30b59e26..e8f298f0d9e 100644 --- a/aws/resource_aws_rds_cluster_test.go +++ b/aws/resource_aws_rds_cluster_test.go @@ -8,10 +8,10 @@ import ( "testing" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" @@ -380,8 +380,9 @@ func TestAccAWSRDSCluster_takeFinalSnapshot(t *testing.T) { }) } -/// This is a regression test to make sure that we always cover the scenario as hightlighted in -/// https://github.com/hashicorp/terraform/issues/11568 +// This is a regression test to make sure that we always cover the scenario as highlighted in +// https://github.com/hashicorp/terraform/issues/11568 +// Expected error updated to match API response func TestAccAWSRDSCluster_missingUserNameCausesError(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -390,7 +391,7 @@ func TestAccAWSRDSCluster_missingUserNameCausesError(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccAWSClusterConfigWithoutUserNameAndPassword(acctest.RandInt()), - ExpectError: regexp.MustCompile(`required field is not set`), + ExpectError: regexp.MustCompile(`InvalidParameterValue: The parameter MasterUsername must be provided`), }, }, }) @@ -669,12 +670,12 @@ func TestAccAWSRDSCluster_copyTagsToSnapshot(t *testing.T) { }) } -func TestAccAWSRDSCluster_EncryptedCrossRegionReplication(t *testing.T) { +func TestAccAWSRDSCluster_ReplicationSourceIdentifier_KmsKeyId(t *testing.T) { var primaryCluster rds.DBCluster var replicaCluster rds.DBCluster resourceName := "aws_rds_cluster.test" resourceName2 := "aws_rds_cluster.alternate" - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") // record the initialized providers so that we can use them to // check for the cluster in each region @@ -683,21 +684,20 @@ func TestAccAWSRDSCluster_EncryptedCrossRegionReplication(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) - testAccMultipleRegionsPreCheck(t) - testAccAlternateRegionPreCheck(t) + testAccMultipleRegionPreCheck(t, 2) }, ProviderFactories: testAccProviderFactories(&providers), CheckDestroy: testAccCheckWithProviders(testAccCheckAWSClusterDestroyWithProvider, &providers), Steps: []resource.TestStep{ { - Config: testAccAWSClusterConfigEncryptedCrossRegionReplica(rInt), + Config: testAccAWSClusterConfigReplicationSourceIdentifierKmsKeyId(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSClusterExistsWithProvider(resourceName, &primaryCluster, testAccAwsRegionProviderFunc(testAccGetRegion(), &providers)), testAccCheckAWSClusterExistsWithProvider(resourceName2, &replicaCluster, testAccAwsRegionProviderFunc(testAccGetAlternateRegion(), &providers)), ), }, { - Config: testAccAWSClusterConfigEncryptedCrossRegionReplica(rInt), + Config: testAccAWSClusterConfigReplicationSourceIdentifierKmsKeyId(rName), ResourceName: resourceName, ImportState: true, ImportStateVerify: true, @@ -1026,7 +1026,7 @@ func TestAccAWSRDSCluster_EngineVersion(t *testing.T) { }, { Config: testAccAWSClusterConfig_EngineVersion(rInt, "aurora-postgresql", "9.6.6"), - ExpectError: regexp.MustCompile(`Cannot modify engine version without a primary instance in DB cluster`), + ExpectError: regexp.MustCompile(`Cannot modify engine version without a healthy primary instance in DB cluster`), }, }, }) @@ -1264,6 +1264,63 @@ func TestAccAWSRDSCluster_GlobalClusterIdentifier_EngineMode_Provisioned(t *test }) } +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/13126 +func TestAccAWSRDSCluster_GlobalClusterIdentifier_PrimarySecondaryClusters(t *testing.T) { + var providers []*schema.Provider + var primaryDbCluster, secondaryDbCluster rds.DBCluster + + rNameGlobal := acctest.RandomWithPrefix("tf-acc-test-global") + rNamePrimary := acctest.RandomWithPrefix("tf-acc-test-primary") + rNameSecondary := acctest.RandomWithPrefix("tf-acc-test-secondary") + + resourceNamePrimary := "aws_rds_cluster.primary" + resourceNameSecondary := "aws_rds_cluster.secondary" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + ProviderFactories: testAccProviderFactories(&providers), + CheckDestroy: testAccCheckAWSClusterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSRDSClusterConfig_GlobalClusterIdentifier_PrimarySecondaryClusters(rNameGlobal, rNamePrimary, rNameSecondary), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSClusterExistsWithProvider(resourceNamePrimary, &primaryDbCluster, testAccAwsRegionProviderFunc(testAccGetRegion(), &providers)), + testAccCheckAWSClusterExistsWithProvider(resourceNameSecondary, &secondaryDbCluster, testAccAwsRegionProviderFunc(testAccGetAlternateRegion(), &providers)), + ), + }, + }, + }) +} + +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/13715 +func TestAccAWSRDSCluster_GlobalClusterIdentifier_ReplicationSourceIdentifier(t *testing.T) { + var providers []*schema.Provider + var primaryDbCluster, secondaryDbCluster rds.DBCluster + + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceNamePrimary := "aws_rds_cluster.primary" + resourceNameSecondary := "aws_rds_cluster.secondary" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + testAccMultipleRegionPreCheck(t, 2) + testAccPreCheckAWSRdsGlobalCluster(t) + }, + ProviderFactories: testAccProviderFactories(&providers), + CheckDestroy: testAccCheckAWSClusterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSRDSClusterConfig_GlobalClusterIdentifier_ReplicationSourceIdentifier(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSClusterExistsWithProvider(resourceNamePrimary, &primaryDbCluster, testAccAwsRegionProviderFunc(testAccGetRegion(), &providers)), + testAccCheckAWSClusterExistsWithProvider(resourceNameSecondary, &secondaryDbCluster, testAccAwsRegionProviderFunc(testAccGetAlternateRegion(), &providers)), + ), + }, + }, + }) +} + func TestAccAWSRDSCluster_Port(t *testing.T) { var dbCluster1, dbCluster2 rds.DBCluster rInt := acctest.RandInt() @@ -1356,6 +1413,46 @@ func TestAccAWSRDSCluster_ScalingConfiguration(t *testing.T) { }) } +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/11698 +func TestAccAWSRDSCluster_ScalingConfiguration_DefaultMinCapacity(t *testing.T) { + var dbCluster rds.DBCluster + + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_rds_cluster.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSClusterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSRDSClusterConfig_ScalingConfiguration_DefaultMinCapacity(rName, false, 128, 301, "RollbackCapacityChange"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSClusterExists(resourceName, &dbCluster), + resource.TestCheckResourceAttr(resourceName, "scaling_configuration.#", "1"), + resource.TestCheckResourceAttr(resourceName, "scaling_configuration.0.auto_pause", "false"), + resource.TestCheckResourceAttr(resourceName, "scaling_configuration.0.max_capacity", "128"), + resource.TestCheckResourceAttr(resourceName, "scaling_configuration.0.min_capacity", "1"), + resource.TestCheckResourceAttr(resourceName, "scaling_configuration.0.seconds_until_auto_pause", "301"), + resource.TestCheckResourceAttr(resourceName, "scaling_configuration.0.timeout_action", "RollbackCapacityChange"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "apply_immediately", + "cluster_identifier_prefix", + "master_password", + "skip_final_snapshot", + "snapshot_identifier", + }, + }, + }, + }) +} + func TestAccAWSRDSCluster_SnapshotIdentifier(t *testing.T) { var dbCluster, sourceDbCluster rds.DBCluster var dbClusterSnapshot rds.DBClusterSnapshot @@ -2265,18 +2362,15 @@ data "aws_availability_zones" "available" { } } -data "aws_region" "current" {} - resource "aws_s3_bucket" "xtrabackup" { bucket = %[1]q - region = "${data.aws_region.current.name}" } resource "aws_s3_bucket_object" "xtrabackup_db" { bucket = "${aws_s3_bucket.xtrabackup.id}" key = "%[2]s/mysql-5-6-xtrabackup.tar.gz" - source = "../files/mysql-5-6-xtrabackup.tar.gz" - etag = "${filemd5("../files/mysql-5-6-xtrabackup.tar.gz")}" + source = "./testdata/mysql-5-6-xtrabackup.tar.gz" + etag = "${filemd5("./testdata/mysql-5-6-xtrabackup.tar.gz")}" } resource "aws_iam_role" "rds_s3_access_role" { @@ -2350,13 +2444,13 @@ resource "aws_rds_cluster" "test" { } func testAccAWSClusterConfig_generatedName() string { - return fmt.Sprintf(` + return ` resource "aws_rds_cluster" "test" { master_username = "root" master_password = "password" skip_final_snapshot = true } -`) +` } func testAccAWSClusterConfigWithFinalSnapshot(n int) string { @@ -2591,7 +2685,7 @@ func testAccAWSClusterConfig_Port(rInt, port int) string { resource "aws_rds_cluster" "test" { cluster_identifier = "tf-acc-test-%d" database_name = "mydb" - db_cluster_parameter_group_name = "default.aurora-postgresql10" + db_cluster_parameter_group_name = "default.aurora-postgresql11" engine = "aurora-postgresql" master_password = "mustbeeightcharaters" master_username = "foo" @@ -2845,10 +2939,12 @@ resource "aws_rds_cluster" "test" { `, n, n, n) } -func testAccAWSClusterConfigEncryptedCrossRegionReplica(n int) string { - return testAccAlternateRegionProviderConfig() + fmt.Sprintf(` +func testAccAWSClusterConfigReplicationSourceIdentifierKmsKeyId(rName string) string { + return composeConfig( + testAccMultipleRegionProviderConfig(2), + fmt.Sprintf(` data "aws_availability_zones" "alternate" { - provider = "aws.alternate" + provider = "awsalternate" state = "available" @@ -2863,7 +2959,7 @@ data "aws_caller_identity" "current" {} data "aws_region" "current" {} resource "aws_rds_cluster_parameter_group" "test" { - name = "tf-aurora-prm-grp-%[1]d" + name = %[1]q family = "aurora5.6" description = "RDS default cluster parameter group" @@ -2875,7 +2971,7 @@ resource "aws_rds_cluster_parameter_group" "test" { } resource "aws_rds_cluster" "test" { - cluster_identifier = "tf-test-primary-%[1]d" + cluster_identifier = "%[1]s-primary" db_cluster_parameter_group_name = aws_rds_cluster_parameter_group.test.name database_name = "mydb" master_username = "foo" @@ -2885,14 +2981,14 @@ resource "aws_rds_cluster" "test" { } resource "aws_rds_cluster_instance" "test" { - identifier = "tf-aurora-instance-%[1]d" + identifier = "%[1]s-primary" cluster_identifier = aws_rds_cluster.test.id instance_class = "db.t2.small" } resource "aws_kms_key" "alternate" { - provider = "aws.alternate" - description = "Terraform acc test %[1]d" + provider = "awsalternate" + description = %[1]q policy = < 1 { @@ -931,7 +910,10 @@ func deleteAwsRedshiftCluster(opts *redshift.DeleteClusterInput, conn *redshift. return resource.RetryableError(err) } - return resource.NonRetryableError(err) + if err != nil { + return resource.NonRetryableError(err) + } + return nil }) if isResourceTimeoutError(err) { _, err = conn.DeleteCluster(opts) diff --git a/aws/resource_aws_redshift_cluster_snapshot_test.go b/aws/resource_aws_redshift_cluster_snapshot_test.go new file mode 100644 index 00000000000..e7c4761cc7d --- /dev/null +++ b/aws/resource_aws_redshift_cluster_snapshot_test.go @@ -0,0 +1,62 @@ +package aws + +import ( + "fmt" + "log" + "strings" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/redshift" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func init() { + resource.AddTestSweepers("aws_redshift_cluster_snapshot", &resource.Sweeper{ + Name: "aws_redshift_cluster_snapshot", + F: testSweepRedshiftClusterSnapshots, + Dependencies: []string{ + "aws_redshift_cluster", + }, + }) +} + +func testSweepRedshiftClusterSnapshots(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).redshiftconn + + err = conn.DescribeClusterSnapshotsPages(&redshift.DescribeClusterSnapshotsInput{}, func(resp *redshift.DescribeClusterSnapshotsOutput, isLast bool) bool { + if len(resp.Snapshots) == 0 { + log.Print("[DEBUG] No Redshift cluster snapshots to sweep") + return false + } + + for _, s := range resp.Snapshots { + id := aws.StringValue(s.SnapshotIdentifier) + + if !strings.EqualFold(aws.StringValue(s.SnapshotType), "manual") || !strings.EqualFold(aws.StringValue(s.Status), "available") { + log.Printf("[INFO] Skipping Redshift cluster snapshot: %s", id) + continue + } + + log.Printf("[INFO] Deleting Redshift cluster snapshot: %s", id) + _, err := conn.DeleteClusterSnapshot(&redshift.DeleteClusterSnapshotInput{ + SnapshotIdentifier: s.SnapshotIdentifier, + }) + if err != nil { + log.Printf("[ERROR] Failed deleting Redshift cluster snapshot (%s): %s", id, err) + } + } + return !isLast + }) + if err != nil { + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping Redshift Cluster Snapshot sweep for %s: %s", region, err) + return nil + } + return fmt.Errorf("Error retrieving Redshift cluster snapshots: %w", err) + } + return nil +} diff --git a/aws/resource_aws_redshift_cluster_test.go b/aws/resource_aws_redshift_cluster_test.go index 89945de5c0f..13d38d638ba 100644 --- a/aws/resource_aws_redshift_cluster_test.go +++ b/aws/resource_aws_redshift_cluster_test.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -128,9 +128,10 @@ func TestAccAWSRedshiftCluster_withFinalSnapshot(t *testing.T) { func TestAccAWSRedshiftCluster_kmsKey(t *testing.T) { var v redshift.Cluster + resourceName := "aws_redshift_cluster.default" + kmsResourceName := "aws_kms_key.foo" + ri := acctest.RandInt() - config := testAccAWSRedshiftClusterConfig_kmsKey(ri) - keyRegex := regexp.MustCompile(`^arn:aws:([a-zA-Z0-9\-])+:([a-z]{2}-[a-z]+-\d{1})?:(\d{12})?:(.*)$`) resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -138,14 +139,12 @@ func TestAccAWSRedshiftCluster_kmsKey(t *testing.T) { CheckDestroy: testAccCheckAWSRedshiftClusterDestroy, Steps: []resource.TestStep{ { - Config: config, + Config: testAccAWSRedshiftClusterConfig_kmsKey(ri), Check: resource.ComposeTestCheckFunc( - testAccCheckAWSRedshiftClusterExists("aws_redshift_cluster.default", &v), - resource.TestCheckResourceAttr( - "aws_redshift_cluster.default", "cluster_type", "single-node"), - resource.TestCheckResourceAttr( - "aws_redshift_cluster.default", "publicly_accessible", "true"), - resource.TestMatchResourceAttr("aws_redshift_cluster.default", "kms_key_id", keyRegex), + testAccCheckAWSRedshiftClusterExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "cluster_type", "single-node"), + resource.TestCheckResourceAttr(resourceName, "publicly_accessible", "true"), + resource.TestCheckResourceAttrPair(resourceName, "kms_key_id", kmsResourceName, "arn"), ), }, { diff --git a/aws/resource_aws_redshift_event_subscription.go b/aws/resource_aws_redshift_event_subscription.go index 24e7a9eee10..2442039b904 100644 --- a/aws/resource_aws_redshift_event_subscription.go +++ b/aws/resource_aws_redshift_event_subscription.go @@ -8,7 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_redshift_event_subscription_test.go b/aws/resource_aws_redshift_event_subscription_test.go index bf47f132fa0..c9a3271bb04 100644 --- a/aws/resource_aws_redshift_event_subscription_test.go +++ b/aws/resource_aws_redshift_event_subscription_test.go @@ -2,16 +2,68 @@ package aws import ( "fmt" + "log" "testing" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) +func init() { + resource.AddTestSweepers("aws_redshift_event_subscription", &resource.Sweeper{ + Name: "aws_redshift_event_subscription", + F: testSweepRedshiftEventSubscriptions, + }) +} + +func testSweepRedshiftEventSubscriptions(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).redshiftconn + var sweeperErrs *multierror.Error + + err = conn.DescribeEventSubscriptionsPages(&redshift.DescribeEventSubscriptionsInput{}, func(page *redshift.DescribeEventSubscriptionsOutput, isLast bool) bool { + if page == nil { + return !isLast + } + + for _, eventSubscription := range page.EventSubscriptionsList { + name := aws.StringValue(eventSubscription.CustSubscriptionId) + + log.Printf("[INFO] Deleting Redshift Event Subscription: %s", name) + _, err = conn.DeleteEventSubscription(&redshift.DeleteEventSubscriptionInput{ + SubscriptionName: aws.String(name), + }) + if isAWSErr(err, redshift.ErrCodeSubscriptionNotFoundFault, "") { + continue + } + if err != nil { + sweeperErr := fmt.Errorf("error deleting Redshift Event Subscription (%s): %w", name, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + } + + return !isLast + }) + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping Redshift Event Subscriptions sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors + } + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving Redshift Event Subscriptions: %w", err)) + } + + return sweeperErrs.ErrorOrNil() +} + func TestAccAWSRedshiftEventSubscription_basicUpdate(t *testing.T) { var v redshift.EventSubscription rInt := acctest.RandInt() @@ -268,24 +320,17 @@ func testAccCheckAWSRedshiftEventSubscriptionDestroy(s *terraform.State) error { SubscriptionName: aws.String(rs.Primary.ID), }) - if ae, ok := err.(awserr.Error); ok && ae.Code() == "SubscriptionNotFound" { + if isAWSErr(err, redshift.ErrCodeSubscriptionNotFoundFault, "") { continue } - if err == nil { - if len(resp.EventSubscriptionsList) != 0 && - *resp.EventSubscriptionsList[0].CustSubscriptionId == rs.Primary.ID { - return fmt.Errorf("Event Subscription still exists") - } - } - - // Verify the error - newerr, ok := err.(awserr.Error) - if !ok { + if err != nil { return err } - if newerr.Code() != "SubscriptionNotFound" { - return err + + if len(resp.EventSubscriptionsList) != 0 && + *resp.EventSubscriptionsList[0].CustSubscriptionId == rs.Primary.ID { + return fmt.Errorf("Event Subscription still exists") } } diff --git a/aws/resource_aws_redshift_parameter_group.go b/aws/resource_aws_redshift_parameter_group.go index 91aaaf941a8..e5966e749cf 100644 --- a/aws/resource_aws_redshift_parameter_group.go +++ b/aws/resource_aws_redshift_parameter_group.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -101,11 +101,7 @@ func resourceAwsRedshiftParameterGroupCreate(d *schema.ResourceData, meta interf d.SetId(*createOpts.ParameterGroupName) if v := d.Get("parameter").(*schema.Set); v.Len() > 0 { - parameters, err := expandRedshiftParameters(v.List()) - - if err != nil { - return fmt.Errorf("error expanding parameter: %s", err) - } + parameters := expandRedshiftParameters(v.List()) modifyOpts := redshift.ModifyClusterParameterGroupInput{ ParameterGroupName: aws.String(d.Id()), @@ -134,7 +130,7 @@ func resourceAwsRedshiftParameterGroupRead(d *schema.ResourceData, meta interfac } if len(describeResp.ParameterGroups) != 1 || - *describeResp.ParameterGroups[0].ParameterGroupName != d.Id() { + aws.StringValue(describeResp.ParameterGroups[0].ParameterGroupName) != d.Id() { d.SetId("") return fmt.Errorf("Unable to find Parameter Group: %#v", describeResp.ParameterGroups) } @@ -186,10 +182,7 @@ func resourceAwsRedshiftParameterGroupUpdate(d *schema.ResourceData, meta interf ns := n.(*schema.Set) // Expand the "parameter" set to aws-sdk-go compat []redshift.Parameter - parameters, err := expandRedshiftParameters(ns.Difference(os).List()) - if err != nil { - return err - } + parameters := expandRedshiftParameters(ns.Difference(os).List()) if len(parameters) > 0 { modifyOpts := redshift.ModifyClusterParameterGroupInput{ @@ -198,7 +191,7 @@ func resourceAwsRedshiftParameterGroupUpdate(d *schema.ResourceData, meta interf } log.Printf("[DEBUG] Modify Redshift Parameter Group: %s", modifyOpts) - _, err = conn.ModifyClusterParameterGroup(&modifyOpts) + _, err := conn.ModifyClusterParameterGroup(&modifyOpts) if err != nil { return fmt.Errorf("Error modifying Redshift Parameter Group: %s", err) } diff --git a/aws/resource_aws_redshift_parameter_group_test.go b/aws/resource_aws_redshift_parameter_group_test.go index ceb06ca29e8..4e18be8d65a 100644 --- a/aws/resource_aws_redshift_parameter_group_test.go +++ b/aws/resource_aws_redshift_parameter_group_test.go @@ -7,9 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSRedshiftParameterGroup_basic(t *testing.T) { @@ -43,10 +44,9 @@ func TestAccAWSRedshiftParameterGroup_withParameters(t *testing.T) { resourceName := "aws_redshift_parameter_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSRedshiftParameterGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSRedshiftParameterGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSRedshiftParameterGroupConfig(rInt), @@ -58,18 +58,18 @@ func TestAccAWSRedshiftParameterGroup_withParameters(t *testing.T) { resourceName, "family", "redshift-1.0"), resource.TestCheckResourceAttr( resourceName, "description", "Managed by Terraform"), - resource.TestCheckResourceAttr( - resourceName, "parameter.490804664.name", "require_ssl"), - resource.TestCheckResourceAttr( - resourceName, "parameter.490804664.value", "true"), - resource.TestCheckResourceAttr( - resourceName, "parameter.2036118857.name", "query_group"), - resource.TestCheckResourceAttr( - resourceName, "parameter.2036118857.value", "example"), - resource.TestCheckResourceAttr( - resourceName, "parameter.484080973.name", "enable_user_activity_logging"), - resource.TestCheckResourceAttr( - resourceName, "parameter.484080973.value", "true"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "require_ssl", + "value": "true", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "query_group", + "value": "example", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "parameter.*", map[string]string{ + "name": "enable_user_activity_logging", + "value": "true", + }), ), }, { diff --git a/aws/resource_aws_redshift_security_group.go b/aws/resource_aws_redshift_security_group.go index a306848e240..f89b2d205ca 100644 --- a/aws/resource_aws_redshift_security_group.go +++ b/aws/resource_aws_redshift_security_group.go @@ -11,10 +11,10 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/redshift" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsRedshiftSecurityGroup() *schema.Resource { @@ -24,7 +24,7 @@ func resourceAwsRedshiftSecurityGroup() *schema.Resource { Update: resourceAwsRedshiftSecurityGroupUpdate, Delete: resourceAwsRedshiftSecurityGroupDelete, Importer: &schema.ResourceImporter{ - State: resourceAwsRedshiftClusterImport, + State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ @@ -174,10 +174,7 @@ func resourceAwsRedshiftSecurityGroupUpdate(d *schema.ResourceData, meta interfa os := o.(*schema.Set) ns := n.(*schema.Set) - removeIngressRules, err := expandRedshiftSGRevokeIngress(os.Difference(ns).List()) - if err != nil { - return err - } + removeIngressRules := expandRedshiftSGRevokeIngress(os.Difference(ns).List()) if len(removeIngressRules) > 0 { for _, r := range removeIngressRules { r.ClusterSecurityGroupName = aws.String(d.Id()) @@ -189,10 +186,7 @@ func resourceAwsRedshiftSecurityGroupUpdate(d *schema.ResourceData, meta interfa } } - addIngressRules, err := expandRedshiftSGAuthorizeIngress(ns.Difference(os).List()) - if err != nil { - return err - } + addIngressRules := expandRedshiftSGAuthorizeIngress(ns.Difference(os).List()) if len(addIngressRules) > 0 { for _, r := range addIngressRules { r.ClusterSecurityGroupName = aws.String(d.Id()) @@ -330,7 +324,7 @@ func resourceAwsRedshiftSecurityGroupStateRefreshFunc( } } -func expandRedshiftSGAuthorizeIngress(configured []interface{}) ([]redshift.AuthorizeClusterSecurityGroupIngressInput, error) { +func expandRedshiftSGAuthorizeIngress(configured []interface{}) []redshift.AuthorizeClusterSecurityGroupIngressInput { var ingress []redshift.AuthorizeClusterSecurityGroupIngressInput // Loop over our configured parameters and create @@ -355,10 +349,10 @@ func expandRedshiftSGAuthorizeIngress(configured []interface{}) ([]redshift.Auth ingress = append(ingress, i) } - return ingress, nil + return ingress } -func expandRedshiftSGRevokeIngress(configured []interface{}) ([]redshift.RevokeClusterSecurityGroupIngressInput, error) { +func expandRedshiftSGRevokeIngress(configured []interface{}) []redshift.RevokeClusterSecurityGroupIngressInput { var ingress []redshift.RevokeClusterSecurityGroupIngressInput // Loop over our configured parameters and create @@ -383,5 +377,5 @@ func expandRedshiftSGRevokeIngress(configured []interface{}) ([]redshift.RevokeC ingress = append(ingress, i) } - return ingress, nil + return ingress } diff --git a/aws/resource_aws_redshift_security_group_test.go b/aws/resource_aws_redshift_security_group_test.go index c2f018439b6..e2cf4024924 100644 --- a/aws/resource_aws_redshift_security_group_test.go +++ b/aws/resource_aws_redshift_security_group_test.go @@ -8,9 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSRedshiftSecurityGroup_basic(t *testing.T) { @@ -53,10 +54,9 @@ func TestAccAWSRedshiftSecurityGroup_ingressCidr(t *testing.T) { resourceName := "aws_redshift_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccEC2ClassicPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSRedshiftSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccEC2ClassicPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSRedshiftSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSRedshiftSecurityGroupConfig_ingressCidr(rInt), @@ -66,8 +66,9 @@ func TestAccAWSRedshiftSecurityGroup_ingressCidr(t *testing.T) { resourceName, "name", fmt.Sprintf("redshift-sg-terraform-%d", rInt)), resource.TestCheckResourceAttr( resourceName, "description", "Managed by Terraform"), - resource.TestCheckResourceAttr( - resourceName, "ingress.2735652665.cidr", "10.0.0.1/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr": "10.0.0.1/24", + }), resource.TestCheckResourceAttr( resourceName, "ingress.#", "1"), ), diff --git a/aws/resource_aws_redshift_snapshot_copy_grant.go b/aws/resource_aws_redshift_snapshot_copy_grant.go index 2f6296a6c3a..36a5297a23c 100644 --- a/aws/resource_aws_redshift_snapshot_copy_grant.go +++ b/aws/resource_aws_redshift_snapshot_copy_grant.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_redshift_snapshot_copy_grant_test.go b/aws/resource_aws_redshift_snapshot_copy_grant_test.go index 6b94094f99e..22bec08e831 100644 --- a/aws/resource_aws_redshift_snapshot_copy_grant_test.go +++ b/aws/resource_aws_redshift_snapshot_copy_grant_test.go @@ -6,12 +6,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAWSRedshiftSnapshotCopyGrant_Basic(t *testing.T) { +func TestAccAWSRedshiftSnapshotCopyGrant_basic(t *testing.T) { resourceName := "aws_redshift_snapshot_copy_grant.test" rName := acctest.RandomWithPrefix("tf-acc-test") diff --git a/aws/resource_aws_redshift_snapshot_schedule.go b/aws/resource_aws_redshift_snapshot_schedule.go index 97aaad450bc..8d9c9eb26c1 100644 --- a/aws/resource_aws_redshift_snapshot_schedule.go +++ b/aws/resource_aws_redshift_snapshot_schedule.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_redshift_snapshot_schedule_association.go b/aws/resource_aws_redshift_snapshot_schedule_association.go index ce46e2b2923..87eacb009c8 100644 --- a/aws/resource_aws_redshift_snapshot_schedule_association.go +++ b/aws/resource_aws_redshift_snapshot_schedule_association.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsRedshiftSnapshotScheduleAssociation() *schema.Resource { diff --git a/aws/resource_aws_redshift_snapshot_schedule_association_test.go b/aws/resource_aws_redshift_snapshot_schedule_association_test.go index 8fda65755a4..c7618029231 100644 --- a/aws/resource_aws_redshift_snapshot_schedule_association_test.go +++ b/aws/resource_aws_redshift_snapshot_schedule_association_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSRedshiftSnapshotScheduleAssociation_basic(t *testing.T) { diff --git a/aws/resource_aws_redshift_snapshot_schedule_test.go b/aws/resource_aws_redshift_snapshot_schedule_test.go index f18c101e5d8..c3035e79895 100644 --- a/aws/resource_aws_redshift_snapshot_schedule_test.go +++ b/aws/resource_aws_redshift_snapshot_schedule_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_redshift_subnet_group.go b/aws/resource_aws_redshift_subnet_group.go index 33091d3533e..9d1b0e88b82 100644 --- a/aws/resource_aws_redshift_subnet_group.go +++ b/aws/resource_aws_redshift_subnet_group.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -139,7 +139,7 @@ func resourceAwsRedshiftSubnetGroupUpdate(d *schema.ResourceData, meta interface } } - if d.HasChange("subnet_ids") || d.HasChange("description") { + if d.HasChanges("subnet_ids", "description") { _, n := d.GetChange("subnet_ids") if n == nil { n = new(schema.Set) diff --git a/aws/resource_aws_redshift_subnet_group_test.go b/aws/resource_aws_redshift_subnet_group_test.go index 2604ca610a2..cfe2cbd83cf 100644 --- a/aws/resource_aws_redshift_subnet_group_test.go +++ b/aws/resource_aws_redshift_subnet_group_test.go @@ -7,9 +7,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/redshift" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSRedshiftSubnetGroup_basic(t *testing.T) { diff --git a/aws/resource_aws_resourcegroups_group.go b/aws/resource_aws_resourcegroups_group.go index f5da289eb1e..2c7558db14c 100644 --- a/aws/resource_aws_resourcegroups_group.go +++ b/aws/resource_aws_resourcegroups_group.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/resourcegroups" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_resourcegroups_group_test.go b/aws/resource_aws_resourcegroups_group_test.go index a8a6a6843c6..7f7f09354de 100644 --- a/aws/resource_aws_resourcegroups_group_test.go +++ b/aws/resource_aws_resourcegroups_group_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/resourcegroups" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSResourceGroup_basic(t *testing.T) { diff --git a/aws/resource_aws_route.go b/aws/resource_aws_route.go index c4cb8ac4369..9883fa71125 100644 --- a/aws/resource_aws_route.go +++ b/aws/resource_aws_route.go @@ -9,10 +9,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) // How long to sleep if a limit-exceeded event happens @@ -53,19 +53,24 @@ func resourceAwsRoute() *schema.Resource { Schema: map[string]*schema.Schema{ "destination_cidr_block": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ValidateFunc: validation.IsCIDR, + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validateIpv4CIDRNetworkAddress, + ), }, + "destination_ipv6_cidr_block": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ValidateFunc: validation.IsCIDR, - DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { - return isIpv6CidrsEquals(old, new) - }, + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validateIpv6CIDRNetworkAddress, + ), + DiffSuppressFunc: suppressEqualCIDRBlockDiffs, }, "destination_prefix_list_id": { @@ -285,8 +290,12 @@ func resourceAwsRouteCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("destination_cidr_block"); ok { err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { route, err = resourceAwsRouteFindRoute(conn, d.Get("route_table_id").(string), v.(string), "") - if err == nil && route != nil { - return nil + if err == nil { + if route != nil { + return nil + } else { + err = errors.New("Route not found") + } } return resource.RetryableError(err) @@ -305,8 +314,12 @@ func resourceAwsRouteCreate(d *schema.ResourceData, meta interface{}) error { if v, ok := d.GetOk("destination_ipv6_cidr_block"); ok { err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { route, err = resourceAwsRouteFindRoute(conn, d.Get("route_table_id").(string), "", v.(string)) - if err == nil && route != nil { - return nil + if err == nil { + if route != nil { + return nil + } else { + err = errors.New("Route not found") + } } return resource.RetryableError(err) @@ -323,15 +336,14 @@ func resourceAwsRouteCreate(d *schema.ResourceData, meta interface{}) error { } d.SetId(resourceAwsRouteID(d, route)) - resourceAwsRouteSetResourceData(d, route) - return nil + return resourceAwsRouteRead(d, meta) } func resourceAwsRouteRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn - routeTableId := d.Get("route_table_id").(string) + routeTableId := d.Get("route_table_id").(string) destinationCidrBlock := d.Get("destination_cidr_block").(string) destinationIpv6CidrBlock := d.Get("destination_ipv6_cidr_block").(string) @@ -351,12 +363,8 @@ func resourceAwsRouteRead(d *schema.ResourceData, meta interface{}) error { return nil } - resourceAwsRouteSetResourceData(d, route) - - return nil -} - -func resourceAwsRouteSetResourceData(d *schema.ResourceData, route *ec2.Route) { + d.Set("destination_cidr_block", route.DestinationCidrBlock) + d.Set("destination_ipv6_cidr_block", route.DestinationIpv6CidrBlock) d.Set("destination_prefix_list_id", route.DestinationPrefixListId) d.Set("gateway_id", route.GatewayId) d.Set("egress_only_gateway_id", route.EgressOnlyInternetGatewayId) @@ -368,6 +376,8 @@ func resourceAwsRouteSetResourceData(d *schema.ResourceData, route *ec2.Route) { d.Set("state", route.State) d.Set("transit_gateway_id", route.TransitGatewayId) d.Set("vpc_peering_connection_id", route.VpcPeeringConnectionId) + + return nil } func resourceAwsRouteUpdate(d *schema.ResourceData, meta interface{}) error { @@ -545,7 +555,7 @@ func resourceAwsRouteFindRoute(conn *ec2.EC2, rtbid string, cidr string, ipv6cid if ipv6cidr != "" { for _, route := range (*resp.RouteTables[0]).Routes { - if route.DestinationIpv6CidrBlock != nil && isIpv6CidrsEquals(aws.StringValue(route.DestinationIpv6CidrBlock), ipv6cidr) { + if cidrBlocksEqual(aws.StringValue(route.DestinationIpv6CidrBlock), ipv6cidr) { return route, nil } } diff --git a/aws/resource_aws_route53_delegation_set.go b/aws/resource_aws_route53_delegation_set.go index 08924a3d736..117ea08764c 100644 --- a/aws/resource_aws_route53_delegation_set.go +++ b/aws/resource_aws_route53_delegation_set.go @@ -5,8 +5,8 @@ import ( "sort" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53" diff --git a/aws/resource_aws_route53_delegation_set_test.go b/aws/resource_aws_route53_delegation_set_test.go index fc6fb95ef3a..20a358158bf 100644 --- a/aws/resource_aws_route53_delegation_set_test.go +++ b/aws/resource_aws_route53_delegation_set_test.go @@ -5,9 +5,9 @@ import ( "reflect" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53" diff --git a/aws/resource_aws_route53_health_check.go b/aws/resource_aws_route53_health_check.go index e3ed4e8aedd..8046cef58f4 100644 --- a/aws/resource_aws_route53_health_check.go +++ b/aws/resource_aws_route53_health_check.go @@ -6,9 +6,9 @@ import ( "net" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" "github.com/aws/aws-sdk-go/aws" @@ -148,6 +148,12 @@ func resourceAwsRoute53HealthCheck() *schema.Resource { Set: schema.HashString, }, + "disabled": { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, + "tags": tagsSchema(), }, } @@ -192,7 +198,7 @@ func resourceAwsRoute53HealthCheckUpdate(d *schema.ResourceData, meta interface{ updateHealthCheck.SearchString = aws.String(d.Get("search_string").(string)) } - if d.HasChange("cloudwatch_alarm_name") || d.HasChange("cloudwatch_alarm_region") { + if d.HasChanges("cloudwatch_alarm_name", "cloudwatch_alarm_region") { cloudwatchAlarm := &route53.AlarmIdentifier{ Name: aws.String(d.Get("cloudwatch_alarm_name").(string)), Region: aws.String(d.Get("cloudwatch_alarm_region").(string)), @@ -213,6 +219,10 @@ func resourceAwsRoute53HealthCheckUpdate(d *schema.ResourceData, meta interface{ updateHealthCheck.Regions = expandStringList(d.Get("regions").(*schema.Set).List()) } + if d.HasChange("disabled") { + updateHealthCheck.Disabled = aws.Bool(d.Get("disabled").(bool)) + } + _, err := conn.UpdateHealthCheck(updateHealthCheck) if err != nil { return err @@ -315,6 +325,10 @@ func resourceAwsRoute53HealthCheckCreate(d *schema.ResourceData, meta interface{ callerRef = fmt.Sprintf("%s-%s", v.(string), callerRef) } + if v, ok := d.GetOk("disabled"); ok { + healthConfig.Disabled = aws.Bool(v.(bool)) + } + input := &route53.CreateHealthCheckInput{ CallerReference: aws.String(callerRef), HealthCheckConfig: healthConfig, @@ -364,6 +378,7 @@ func resourceAwsRoute53HealthCheckRead(d *schema.ResourceData, meta interface{}) d.Set("resource_path", updated.ResourcePath) d.Set("measure_latency", updated.MeasureLatency) d.Set("invert_healthcheck", updated.Inverted) + d.Set("disabled", updated.Disabled) if err := d.Set("child_healthchecks", flattenStringList(updated.ChildHealthChecks)); err != nil { return fmt.Errorf("error setting child_healthchecks: %s", err) diff --git a/aws/resource_aws_route53_health_check_test.go b/aws/resource_aws_route53_health_check_test.go index 58a6c0b8e4d..ad9aa7a4507 100644 --- a/aws/resource_aws_route53_health_check_test.go +++ b/aws/resource_aws_route53_health_check_test.go @@ -6,8 +6,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/route53" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSRoute53HealthCheck_basic(t *testing.T) { @@ -285,6 +285,45 @@ func TestAccAWSRoute53HealthCheck_withSNI(t *testing.T) { }) } +func TestAccAWSRoute53HealthCheck_Disabled(t *testing.T) { + var check route53.HealthCheck + resourceName := "aws_route53_health_check.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckRoute53HealthCheckDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRoute53HealthCheckConfigDisabled(true), + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53HealthCheckExists(resourceName, &check), + resource.TestCheckResourceAttr(resourceName, "disabled", "true"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccRoute53HealthCheckConfigDisabled(false), + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53HealthCheckExists(resourceName, &check), + resource.TestCheckResourceAttr(resourceName, "disabled", "false"), + ), + }, + { + Config: testAccRoute53HealthCheckConfigDisabled(true), + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53HealthCheckExists(resourceName, &check), + resource.TestCheckResourceAttr(resourceName, "disabled", "true"), + ), + }, + }, + }) +} + func TestAccAWSRoute53HealthCheck_disappears(t *testing.T) { var check route53.HealthCheck resourceName := "aws_route53_health_check.test" @@ -636,3 +675,17 @@ resource "aws_route53_health_check" "test" { } } ` + +func testAccRoute53HealthCheckConfigDisabled(disabled bool) string { + return fmt.Sprintf(` +resource "aws_route53_health_check" "test" { + disabled = %[1]t + failure_threshold = "2" + fqdn = "dev.notexample.com" + port = 80 + request_interval = "30" + resource_path = "/" + type = "HTTP" +} +`, disabled) +} diff --git a/aws/resource_aws_route53_query_log.go b/aws/resource_aws_route53_query_log.go index 33a70e3e9a4..cd70785dc85 100644 --- a/aws/resource_aws_route53_query_log.go +++ b/aws/resource_aws_route53_query_log.go @@ -4,7 +4,7 @@ import ( "fmt" "log" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53" diff --git a/aws/resource_aws_route53_query_log_test.go b/aws/resource_aws_route53_query_log_test.go index c241a2df125..7eacfa83daa 100644 --- a/aws/resource_aws_route53_query_log_test.go +++ b/aws/resource_aws_route53_query_log_test.go @@ -2,19 +2,73 @@ package aws import ( "fmt" + "log" "os" "strings" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53" - - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAWSRoute53QueryLog_Basic(t *testing.T) { +func init() { + resource.AddTestSweepers("aws_route53_query_log", &resource.Sweeper{ + Name: "aws_route53_query_log", + F: testSweepRoute53QueryLogs, + }) +} + +func testSweepRoute53QueryLogs(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).r53conn + var sweeperErrs *multierror.Error + + err = conn.ListQueryLoggingConfigsPages(&route53.ListQueryLoggingConfigsInput{}, func(page *route53.ListQueryLoggingConfigsOutput, isLast bool) bool { + if page == nil { + return !isLast + } + + for _, queryLoggingConfig := range page.QueryLoggingConfigs { + id := aws.StringValue(queryLoggingConfig.Id) + + log.Printf("[INFO] Deleting Route53 query logging configuration: %s", id) + _, err := conn.DeleteQueryLoggingConfig(&route53.DeleteQueryLoggingConfigInput{ + Id: aws.String(id), + }) + if isAWSErr(err, route53.ErrCodeNoSuchQueryLoggingConfig, "") { + continue + } + if err != nil { + sweeperErr := fmt.Errorf("error deleting Route53 query logging configuration (%s): %w", id, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + } + + return !isLast + }) + // In unsupported AWS partitions, the API may return an error even the SDK cannot handle. + // Reference: https://github.com/aws/aws-sdk-go/issues/3313 + if testSweepSkipSweepError(err) || isAWSErr(err, "SerializationError", "failed to unmarshal error message") || isAWSErr(err, "AccessDeniedException", "Unable to determine service/operation name to be authorized") { + log.Printf("[WARN] Skipping Route53 query logging configurations sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors + } + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving Route53 query logging configurations: %w", err)) + } + + return sweeperErrs.ErrorOrNil() +} + +func TestAccAWSRoute53QueryLog_basic(t *testing.T) { // The underlying resources are sensitive to where they are located // Use us-east-1 for testing oldRegion := os.Getenv("AWS_DEFAULT_REGION") diff --git a/aws/resource_aws_route53_record.go b/aws/resource_aws_route53_record.go index 2d285f344cb..63e1e26ee47 100644 --- a/aws/resource_aws_route53_record.go +++ b/aws/resource_aws_route53_record.go @@ -10,14 +10,13 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/route53" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) var r53NoRecordsFound = errors.New("No matching records found") @@ -25,6 +24,7 @@ var r53NoHostedZoneFound = errors.New("No matching Hosted Zone found") var r53ValidRecordTypes = regexp.MustCompile("^(A|AAAA|CAA|CNAME|MX|NAPTR|NS|PTR|SOA|SPF|SRV|TXT)$") func resourceAwsRoute53Record() *schema.Resource { + //lintignore:R011 return &schema.Resource{ Create: resourceAwsRoute53RecordCreate, Read: resourceAwsRoute53RecordRead, @@ -41,6 +41,9 @@ func resourceAwsRoute53Record() *schema.Resource { Required: true, ForceNew: true, StateFunc: func(v interface{}) string { + // AWS Provider aws_acm_certification.domain_validation_options.resource_record_name + // references (and perhaps others) contain a trailing period, requiring a custom StateFunc + // to trim the string to prevent Route53 API error value := strings.TrimSuffix(v.(string), ".") return strings.ToLower(value) }, @@ -272,7 +275,7 @@ func resourceAwsRoute53RecordUpdate(d *schema.ResourceData, meta interface{}) er } // Build the to be deleted record - en := expandRecordName(d.Get("name").(string), *zoneRecord.HostedZone.Name) + en := expandRecordName(d.Get("name").(string), aws.StringValue(zoneRecord.HostedZone.Name)) typeo, _ := d.GetChange("type") oldRec := &route53.ResourceRecordSet{ @@ -317,12 +320,17 @@ func resourceAwsRoute53RecordUpdate(d *schema.ResourceData, meta interface{}) er } } + // If health check id is present send that to AWS + if v, _ := d.GetChange("health_check_id"); v.(string) != "" { + oldRec.HealthCheckId = aws.String(v.(string)) + } + if v, _ := d.GetChange("set_identifier"); v.(string) != "" { oldRec.SetIdentifier = aws.String(v.(string)) } // Build the to be created record - rec, err := resourceAwsRoute53RecordBuildSet(d, *zoneRecord.HostedZone.Name) + rec, err := resourceAwsRoute53RecordBuildSet(d, aws.StringValue(zoneRecord.HostedZone.Name)) if err != nil { return err } @@ -334,27 +342,27 @@ func resourceAwsRoute53RecordUpdate(d *schema.ResourceData, meta interface{}) er Comment: aws.String("Managed by Terraform"), Changes: []*route53.Change{ { - Action: aws.String("DELETE"), + Action: aws.String(route53.ChangeActionDelete), ResourceRecordSet: oldRec, }, { - Action: aws.String("CREATE"), + Action: aws.String(route53.ChangeActionCreate), ResourceRecordSet: rec, }, }, } input := &route53.ChangeResourceRecordSetsInput{ - HostedZoneId: aws.String(cleanZoneID(*zoneRecord.HostedZone.Id)), + HostedZoneId: aws.String(cleanZoneID(aws.StringValue(zoneRecord.HostedZone.Id))), ChangeBatch: changeBatch, } log.Printf("[DEBUG] Updating resource records for zone: %s, name: %s\n\n%s", - zone, *rec.Name, input) + zone, aws.StringValue(rec.Name), input) respRaw, err := changeRoute53RecordSet(conn, input) if err != nil { - return fmt.Errorf("[ERR]: Error building changeset: %s", err) + return fmt.Errorf("[ERR]: Error building changeset: %w", err) } changeInfo := respRaw.(*route53.ChangeResourceRecordSetsOutput).ChangeInfo @@ -371,7 +379,7 @@ func resourceAwsRoute53RecordUpdate(d *schema.ResourceData, meta interface{}) er d.SetId(strings.Join(vars, "_")) - err = waitForRoute53RecordSetToSync(conn, cleanChangeID(*changeInfo.Id)) + err = waitForRoute53RecordSetToSync(conn, cleanChangeID(aws.StringValue(changeInfo.Id))) if err != nil { return err } @@ -394,7 +402,7 @@ func resourceAwsRoute53RecordCreate(d *schema.ResourceData, meta interface{}) er } // Build the record - rec, err := resourceAwsRoute53RecordBuildSet(d, *zoneRecord.HostedZone.Name) + rec, err := resourceAwsRoute53RecordBuildSet(d, aws.StringValue(zoneRecord.HostedZone.Name)) if err != nil { return err } @@ -404,9 +412,9 @@ func resourceAwsRoute53RecordCreate(d *schema.ResourceData, meta interface{}) er // Else CREATE is used and fail if the same record exists var action string if d.Get("allow_overwrite").(bool) || !d.IsNewResource() { - action = "UPSERT" + action = route53.ChangeActionUpsert } else { - action = "CREATE" + action = route53.ChangeActionCreate } // Create the new records. We abuse StateChangeConf for this to @@ -423,16 +431,16 @@ func resourceAwsRoute53RecordCreate(d *schema.ResourceData, meta interface{}) er } req := &route53.ChangeResourceRecordSetsInput{ - HostedZoneId: aws.String(cleanZoneID(*zoneRecord.HostedZone.Id)), + HostedZoneId: aws.String(cleanZoneID(aws.StringValue(zoneRecord.HostedZone.Id))), ChangeBatch: changeBatch, } log.Printf("[DEBUG] Creating resource records for zone: %s, name: %s\n\n%s", - zone, *rec.Name, req) + zone, aws.StringValue(rec.Name), req) respRaw, err := changeRoute53RecordSet(conn, req) if err != nil { - return fmt.Errorf("[ERR]: Error building changeset: %s", err) + return fmt.Errorf("[ERR]: Error building changeset: %w", err) } changeInfo := respRaw.(*route53.ChangeResourceRecordSetsOutput).ChangeInfo @@ -449,7 +457,7 @@ func resourceAwsRoute53RecordCreate(d *schema.ResourceData, meta interface{}) er d.SetId(strings.Join(vars, "_")) - err = waitForRoute53RecordSetToSync(conn, cleanChangeID(*changeInfo.Id)) + err = waitForRoute53RecordSetToSync(conn, cleanChangeID(aws.StringValue(changeInfo.Id))) if err != nil { return err } @@ -463,7 +471,7 @@ func changeRoute53RecordSet(conn *route53.Route53, input *route53.ChangeResource err := resource.Retry(1*time.Minute, func() *resource.RetryError { var err error out, err = conn.ChangeResourceRecordSets(input) - if isAWSErr(err, "NoSuchHostedZone", "") { + if isAWSErr(err, route53.ErrCodeNoSuchHostedZone, "") { log.Print("[DEBUG] Hosted Zone not found, retrying...") return resource.RetryableError(err) } @@ -482,8 +490,8 @@ func changeRoute53RecordSet(conn *route53.Route53, input *route53.ChangeResource func waitForRoute53RecordSetToSync(conn *route53.Route53, requestId string) error { wait := resource.StateChangeConf{ Delay: 30 * time.Second, - Pending: []string{"PENDING"}, - Target: []string{"INSYNC"}, + Pending: []string{route53.ChangeStatusPending}, + Target: []string{route53.ChangeStatusInsync}, Timeout: 30 * time.Minute, MinTimeout: 5 * time.Second, Refresh: func() (result interface{}, state string, err error) { @@ -527,18 +535,18 @@ func resourceAwsRoute53RecordRead(d *schema.ResourceData, meta interface{}) erro } } - err = d.Set("records", flattenResourceRecords(record.ResourceRecords, *record.Type)) + err = d.Set("records", flattenResourceRecords(record.ResourceRecords, aws.StringValue(record.Type))) if err != nil { - return fmt.Errorf("Error setting records for: %s, error: %#v", d.Id(), err) + return fmt.Errorf("Error setting records for: %s, error: %w", d.Id(), err) } if alias := record.AliasTarget; alias != nil { - name := normalizeAwsAliasName(*alias.DNSName) + name := normalizeAwsAliasName(aws.StringValue(alias.DNSName)) d.Set("alias", []interface{}{ map[string]interface{}{ - "zone_id": *alias.HostedZoneId, + "zone_id": aws.StringValue(alias.HostedZoneId), "name": name, - "evaluate_target_health": *alias.EvaluateTargetHealth, + "evaluate_target_health": aws.BoolValue(alias.EvaluateTargetHealth), }, }) } @@ -550,7 +558,7 @@ func resourceAwsRoute53RecordRead(d *schema.ResourceData, meta interface{}) erro "type": aws.StringValue(record.Failover), }} if err := d.Set("failover_routing_policy", v); err != nil { - return fmt.Errorf("Error setting failover records for: %s, error: %#v", d.Id(), err) + return fmt.Errorf("Error setting failover records for: %s, error: %w", d.Id(), err) } } @@ -561,7 +569,7 @@ func resourceAwsRoute53RecordRead(d *schema.ResourceData, meta interface{}) erro "subdivision": aws.StringValue(record.GeoLocation.SubdivisionCode), }} if err := d.Set("geolocation_routing_policy", v); err != nil { - return fmt.Errorf("Error setting gelocation records for: %s, error: %#v", d.Id(), err) + return fmt.Errorf("Error setting gelocation records for: %s, error: %w", d.Id(), err) } } @@ -570,7 +578,7 @@ func resourceAwsRoute53RecordRead(d *schema.ResourceData, meta interface{}) erro "region": aws.StringValue(record.Region), }} if err := d.Set("latency_routing_policy", v); err != nil { - return fmt.Errorf("Error setting latency records for: %s, error: %#v", d.Id(), err) + return fmt.Errorf("Error setting latency records for: %s, error: %w", d.Id(), err) } } @@ -579,13 +587,13 @@ func resourceAwsRoute53RecordRead(d *schema.ResourceData, meta interface{}) erro "weight": aws.Int64Value((record.Weight)), }} if err := d.Set("weighted_routing_policy", v); err != nil { - return fmt.Errorf("Error setting weighted records for: %s, error: %#v", d.Id(), err) + return fmt.Errorf("Error setting weighted records for: %s, error: %w", d.Id(), err) } } if record.MultiValueAnswer != nil { if err := d.Set("multivalue_answer_routing_policy", record.MultiValueAnswer); err != nil { - return fmt.Errorf("Error setting multivalue answer records for: %s, error: %#v", d.Id(), err) + return fmt.Errorf("Error setting multivalue answer records for: %s, error: %w", d.Id(), err) } } @@ -618,19 +626,30 @@ func findRecord(d *schema.ResourceData, meta interface{}) (*route53.ResourceReco // get expanded name zoneRecord, err := conn.GetHostedZone(&route53.GetHostedZoneInput{Id: aws.String(zone)}) if err != nil { - if r53err, ok := err.(awserr.Error); ok && r53err.Code() == "NoSuchHostedZone" { + if isAWSErr(err, route53.ErrCodeNoSuchHostedZone, "") { return nil, r53NoHostedZoneFound } + return nil, err } - en := expandRecordName(d.Get("name").(string), *zoneRecord.HostedZone.Name) + var name string + // If we're dealing with a change of record name, but we're operating on the old, rather than + // the new, resource, then we need to use the old name to find it (in order to delete it). + if !d.IsNewResource() && d.HasChange("name") { + oldName, _ := d.GetChange("name") + name = oldName.(string) + } else { + name = d.Get("name").(string) + } + + en := expandRecordName(name, aws.StringValue(zoneRecord.HostedZone.Name)) log.Printf("[DEBUG] Expanded record name: %s", en) d.Set("fqdn", en) recordName := FQDN(strings.ToLower(en)) recordType := d.Get("type").(string) - recordSetIdentifier := d.Get("set_identifier") + recordSetIdentifier := d.Get("set_identifier").(string) // If this isn't a Weighted, Latency, Geo, or Failover resource with // a SetIdentifier we only need to look at the first record in the response since there can be @@ -662,7 +681,7 @@ func findRecord(d *schema.ResourceData, meta interface{}) (*route53.ResourceReco for _, recordSet := range resp.ResourceRecordSets { responseName := strings.ToLower(cleanRecordName(*recordSet.Name)) - responseType := strings.ToUpper(*recordSet.Type) + responseType := strings.ToUpper(aws.StringValue(recordSet.Type)) if recordName != responseName { continue @@ -670,7 +689,7 @@ func findRecord(d *schema.ResourceData, meta interface{}) (*route53.ResourceReco if recordType != responseType { continue } - if recordSet.SetIdentifier != nil && *recordSet.SetIdentifier != recordSetIdentifier { + if aws.StringValue(recordSet.SetIdentifier) != recordSetIdentifier { continue } @@ -719,7 +738,7 @@ func resourceAwsRoute53RecordDelete(d *schema.ResourceData, meta interface{}) er Comment: aws.String("Deleted by Terraform"), Changes: []*route53.Change{ { - Action: aws.String("DELETE"), + Action: aws.String(route53.ChangeActionDelete), ResourceRecordSet: rec, }, }, @@ -734,7 +753,7 @@ func resourceAwsRoute53RecordDelete(d *schema.ResourceData, meta interface{}) er respRaw, err := deleteRoute53RecordSet(conn, req) if err != nil { - return fmt.Errorf("[ERR]: Error building changeset: %s", err) + return fmt.Errorf("[ERR]: Error building changeset: %w", err) } changeInfo := respRaw.(*route53.ChangeResourceRecordSetsOutput).ChangeInfo @@ -743,13 +762,13 @@ func resourceAwsRoute53RecordDelete(d *schema.ResourceData, meta interface{}) er return nil } - err = waitForRoute53RecordSetToSync(conn, cleanChangeID(*changeInfo.Id)) + err = waitForRoute53RecordSetToSync(conn, cleanChangeID(aws.StringValue(changeInfo.Id))) return err } func deleteRoute53RecordSet(conn *route53.Route53, input *route53.ChangeResourceRecordSetsInput) (interface{}, error) { out, err := conn.ChangeResourceRecordSets(input) - if isAWSErr(err, "InvalidChangeBatch", "") { + if isAWSErr(err, route53.ErrCodeInvalidChangeBatch, "") { return out, nil } diff --git a/aws/resource_aws_route53_record_migrate.go b/aws/resource_aws_route53_record_migrate.go index d34de7cd55d..f8a7a5ca7df 100644 --- a/aws/resource_aws_route53_record_migrate.go +++ b/aws/resource_aws_route53_record_migrate.go @@ -5,7 +5,7 @@ import ( "log" "strings" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func resourceAwsRoute53RecordMigrateState( @@ -13,10 +13,7 @@ func resourceAwsRoute53RecordMigrateState( switch v { case 0: log.Println("[INFO] Found AWS Route53 Record State v0; migrating to v1 then v2") - v1InstanceState, err := migrateRoute53RecordStateV0toV1(is) - if err != nil { - return v1InstanceState, err - } + v1InstanceState := migrateRoute53RecordStateV0toV1(is) return migrateRoute53RecordStateV1toV2(v1InstanceState) case 1: log.Println("[INFO] Found AWS Route53 Record State v1; migrating to v2") @@ -26,17 +23,17 @@ func resourceAwsRoute53RecordMigrateState( } } -func migrateRoute53RecordStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) { +func migrateRoute53RecordStateV0toV1(is *terraform.InstanceState) *terraform.InstanceState { if is.Empty() { log.Println("[DEBUG] Empty InstanceState; nothing to migrate.") - return is, nil + return is } log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes) newName := strings.TrimSuffix(is.Attributes["name"], ".") is.Attributes["name"] = newName log.Printf("[DEBUG] Attributes after migration: %#v, new name: %s", is.Attributes, newName) - return is, nil + return is } func migrateRoute53RecordStateV1toV2(is *terraform.InstanceState) (*terraform.InstanceState, error) { @@ -47,12 +44,12 @@ func migrateRoute53RecordStateV1toV2(is *terraform.InstanceState) (*terraform.In log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes) if is.Attributes["weight"] != "" && is.Attributes["weight"] != "-1" { is.Attributes["weighted_routing_policy.#"] = "1" - key := fmt.Sprintf("weighted_routing_policy.0.weight") + key := "weighted_routing_policy.0.weight" is.Attributes[key] = is.Attributes["weight"] } if is.Attributes["failover"] != "" { is.Attributes["failover_routing_policy.#"] = "1" - key := fmt.Sprintf("failover_routing_policy.0.type") + key := "failover_routing_policy.0.type" is.Attributes[key] = is.Attributes["failover"] } delete(is.Attributes, "weight") diff --git a/aws/resource_aws_route53_record_migrate_test.go b/aws/resource_aws_route53_record_migrate_test.go index bc4511e090a..69b4dfdb722 100644 --- a/aws/resource_aws_route53_record_migrate_test.go +++ b/aws/resource_aws_route53_record_migrate_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAWSRoute53RecordMigrateState(t *testing.T) { diff --git a/aws/resource_aws_route53_record_test.go b/aws/resource_aws_route53_record_test.go index 9bdbac17294..23bb7b7b8cc 100644 --- a/aws/resource_aws_route53_record_test.go +++ b/aws/resource_aws_route53_record_test.go @@ -5,9 +5,10 @@ import ( "strings" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" "regexp" @@ -244,6 +245,34 @@ func TestAccAWSRoute53Record_basic_fqdn(t *testing.T) { }) } +// TestAccAWSRoute53Record_basic_trailingPeriodAndZoneID ensures an aws_route53_record +// created with a name configured with a trailing period and explicit zone_id gets imported correctly +func TestAccAWSRoute53Record_basic_trailingPeriodAndZoneID(t *testing.T) { + var record1 route53.ResourceRecordSet + resourceName := "aws_route53_record.default" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckRoute53RecordDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRoute53RecordConfig_nameWithTrailingPeriod, + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53RecordExists(resourceName, &record1), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"allow_overwrite", "weight"}, + }, + }, + }) +} + func TestAccAWSRoute53Record_txtSupport(t *testing.T) { var record1 route53.ResourceRecordSet resourceName := "aws_route53_record.default" @@ -276,18 +305,16 @@ func TestAccAWSRoute53Record_spfSupport(t *testing.T) { resourceName := "aws_route53_record.default" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckRoute53RecordDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckRoute53RecordDestroy, Steps: []resource.TestStep{ { Config: testAccRoute53RecordConfigSPF, Check: resource.ComposeTestCheckFunc( testAccCheckRoute53RecordExists(resourceName, &record1), - resource.TestCheckResourceAttr( - resourceName, "records.2930149397", "include:notexample.com"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "records.*", "include:notexample.com"), ), }, { @@ -305,18 +332,16 @@ func TestAccAWSRoute53Record_caaSupport(t *testing.T) { resourceName := "aws_route53_record.default" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckRoute53RecordDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckRoute53RecordDestroy, Steps: []resource.TestStep{ { Config: testAccRoute53RecordConfigCAA, Check: resource.ComposeTestCheckFunc( testAccCheckRoute53RecordExists(resourceName, &record1), - resource.TestCheckResourceAttr( - resourceName, "records.2965463512", "0 issue \"exampleca.com;\""), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "records.*", "0 issue \"exampleca.com;\""), ), }, { @@ -652,6 +677,70 @@ func TestAccAWSRoute53Record_geolocation_basic(t *testing.T) { }) } +func TestAccAWSRoute53Record_HealthCheckId_SetIdentifierChange(t *testing.T) { + var record1, record2 route53.ResourceRecordSet + resourceName := "aws_route53_record.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckRoute53RecordDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRoute53RecordConfigHealthCheckIdSetIdentifier("test1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53RecordExists(resourceName, &record1), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"allow_overwrite", "weight"}, + }, + { + Config: testAccRoute53RecordConfigHealthCheckIdSetIdentifier("test2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53RecordExists(resourceName, &record2), + ), + }, + }, + }) +} + +func TestAccAWSRoute53Record_HealthCheckId_TypeChange(t *testing.T) { + var record1, record2 route53.ResourceRecordSet + resourceName := "aws_route53_record.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckRoute53RecordDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRoute53RecordConfigHealthCheckIdTypeCname(), + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53RecordExists(resourceName, &record1), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"allow_overwrite", "weight"}, + }, + { + Config: testAccRoute53RecordConfigHealthCheckIdTypeA(), + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53RecordExists(resourceName, &record2), + ), + }, + }, + }) +} + func TestAccAWSRoute53Record_latency_basic(t *testing.T) { var record1, record2, record3 route53.ResourceRecordSet resourceName := "aws_route53_record.us-east-1" @@ -713,6 +802,41 @@ func TestAccAWSRoute53Record_TypeChange(t *testing.T) { }) } +func TestAccAWSRoute53Record_NameChange(t *testing.T) { + var record1, record2 route53.ResourceRecordSet + resourceName := "aws_route53_record.sample" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckRoute53RecordDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRoute53RecordNameChangePre, + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53RecordExists(resourceName, &record1), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"allow_overwrite", "weight"}, + }, + + // Cause a change, which will trigger a refresh + { + Config: testAccRoute53RecordNameChangePost, + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53RecordExists(resourceName, &record2), + testAccCheckRoute53RecordDoesNotExist("aws_route53_zone.main", "sample", "CNAME"), + ), + }, + }, + }) +} + func TestAccAWSRoute53Record_SetIdentifierChange(t *testing.T) { var record1, record2 route53.ResourceRecordSet resourceName := "aws_route53_record.basic_to_weighted" @@ -1003,6 +1127,43 @@ func testAccCheckRoute53RecordExists(n string, resourceRecordSet *route53.Resour } } +func testAccCheckRoute53RecordDoesNotExist(zoneResourceName string, recordName string, recordType string) resource.TestCheckFunc { + return func(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).r53conn + zoneResource, ok := s.RootModule().Resources[zoneResourceName] + if !ok { + return fmt.Errorf("Not found: %s", zoneResourceName) + } + + zoneId := zoneResource.Primary.ID + en := expandRecordName(recordName, zoneResource.Primary.Attributes["zone_id"]) + + lopts := &route53.ListResourceRecordSetsInput{ + HostedZoneId: aws.String(cleanZoneID(zoneId)), + } + + resp, err := conn.ListResourceRecordSets(lopts) + if err != nil { + return err + } + + found := false + for _, rec := range resp.ResourceRecordSets { + recName := cleanRecordName(*rec.Name) + if FQDN(strings.ToLower(recName)) == FQDN(strings.ToLower(en)) && *rec.Type == recordType { + found = true + break + } + } + + if found { + return fmt.Errorf("Record exists but should not: %s", en) + } + + return nil + } +} + func testAccRoute53RecordConfig_allowOverwrite(allowOverwrite bool) string { return fmt.Sprintf(` resource "aws_route53_zone" "main" { @@ -1044,6 +1205,20 @@ resource "aws_route53_record" "default" { } ` +const testAccRoute53RecordConfig_nameWithTrailingPeriod = ` +resource "aws_route53_zone" "main" { + name = "notexample.com" +} + +resource "aws_route53_record" "default" { + zone_id = "${aws_route53_zone.main.zone_id}" + name = "www.NOTexamplE.com." + type = "A" + ttl = "30" + records = ["127.0.0.1", "127.0.0.27"] +} +` + const testAccRoute53RecordConfigMultiple = ` resource "aws_route53_zone" "test" { name = "notexample.com" @@ -1378,6 +1553,15 @@ resource "aws_route53_record" "ap-northeast-1" { ` const testAccRoute53RecordConfigAliasElb = ` +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_route53_zone" "main" { name = "notexample.com" } @@ -1396,7 +1580,7 @@ resource "aws_route53_record" "alias" { resource "aws_elb" "main" { name = "foobar-terraform-elb-%s" - availability_zones = ["us-west-2a"] + availability_zones = slice(data.aws_availability_zones.available.names, 0, 1) listener { instance_port = 80 @@ -1408,6 +1592,15 @@ resource "aws_elb" "main" { ` const testAccRoute53RecordConfigAliasElbUppercase = ` +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_route53_zone" "main" { name = "notexample.com" } @@ -1426,7 +1619,7 @@ resource "aws_route53_record" "alias" { resource "aws_elb" "main" { name = "FOOBAR-TERRAFORM-ELB-%s" - availability_zones = ["us-west-2a"] + availability_zones = slice(data.aws_availability_zones.available.names, 0, 1) listener { instance_port = 80 @@ -1466,6 +1659,102 @@ resource "aws_route53_record" "alias" { `, rName) } +func testAccRoute53RecordConfigHealthCheckIdSetIdentifier(setIdentifier string) string { + return fmt.Sprintf(` +resource "aws_route53_zone" "test" { + force_destroy = true + name = "notexample.com" +} + +resource "aws_route53_health_check" "test" { + failure_threshold = "2" + fqdn = "test.notexample.com" + port = 80 + request_interval = "30" + resource_path = "/" + type = "HTTP" +} + +resource "aws_route53_record" "test" { + zone_id = aws_route53_zone.test.zone_id + health_check_id = aws_route53_health_check.test.id + name = "test" + records = ["127.0.0.1"] + set_identifier = %[1]q + ttl = "5" + type = "A" + + weighted_routing_policy { + weight = 1 + } +} +`, setIdentifier) +} + +func testAccRoute53RecordConfigHealthCheckIdTypeA() string { + return ` +resource "aws_route53_zone" "test" { + force_destroy = true + name = "notexample.com" +} + +resource "aws_route53_health_check" "test" { + failure_threshold = "2" + fqdn = "test.notexample.com" + port = 80 + request_interval = "30" + resource_path = "/" + type = "HTTP" +} + +resource "aws_route53_record" "test" { + zone_id = aws_route53_zone.test.zone_id + health_check_id = aws_route53_health_check.test.id + name = "test" + records = ["127.0.0.1"] + set_identifier = "test" + ttl = "5" + type = "A" + + weighted_routing_policy { + weight = 1 + } +} +` +} + +func testAccRoute53RecordConfigHealthCheckIdTypeCname() string { + return ` +resource "aws_route53_zone" "test" { + force_destroy = true + name = "notexample.com" +} + +resource "aws_route53_health_check" "test" { + failure_threshold = "2" + fqdn = "test.notexample.com" + port = 80 + request_interval = "30" + resource_path = "/" + type = "HTTP" +} + +resource "aws_route53_record" "test" { + zone_id = aws_route53_zone.test.zone_id + health_check_id = aws_route53_health_check.test.id + name = "test" + records = ["test1.notexample.com"] + set_identifier = "test" + ttl = "5" + type = "CNAME" + + weighted_routing_policy { + weight = 1 + } +} +` +} + func testAccRoute53CustomVpcEndpointBase(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { @@ -1492,8 +1781,13 @@ resource "aws_lb" "test" { subnets = ["${aws_subnet.test.id}"] } -resource "aws_default_security_group" "test" { +resource "aws_security_group" "test" { + name = %[1]q vpc_id = "${aws_vpc.test.id}" + + tags = { + Name = %[1]q + } } resource "aws_vpc_endpoint_service" "test" { @@ -1503,7 +1797,7 @@ resource "aws_vpc_endpoint_service" "test" { resource "aws_vpc_endpoint" "test" { private_dns_enabled = false - security_group_ids = ["${aws_default_security_group.test.id}"] + security_group_ids = ["${aws_security_group.test.id}"] service_name = "${aws_vpc_endpoint_service.test.service_name}" subnet_ids = ["${aws_subnet.test.id}"] vpc_endpoint_type = "Interface" @@ -1521,7 +1815,7 @@ resource "aws_route53_zone" "test" { } func testAccRoute53RecordConfigAliasCustomVpcEndpointSwappedAliasAttributes(rName string) string { - return testAccRoute53CustomVpcEndpointBase(rName) + fmt.Sprintf(` + return testAccRoute53CustomVpcEndpointBase(rName) + ` resource "aws_route53_record" "test" { name = "test" type = "A" @@ -1533,11 +1827,11 @@ resource "aws_route53_record" "test" { zone_id = "${lookup(aws_vpc_endpoint.test.dns_entry[0], "dns_name")}" } } -`) +` } func testAccRoute53RecordConfigCustomVpcEndpoint(rName string) string { - return testAccRoute53CustomVpcEndpointBase(rName) + fmt.Sprintf(` + return testAccRoute53CustomVpcEndpointBase(rName) + ` resource "aws_route53_record" "test" { name = "test" type = "A" @@ -1549,17 +1843,26 @@ resource "aws_route53_record" "test" { zone_id = "${lookup(aws_vpc_endpoint.test.dns_entry[0], "hosted_zone_id")}" } } -`) +` } const testAccRoute53WeightedElbAliasRecord = ` +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_route53_zone" "main" { name = "notexample.com" } resource "aws_elb" "live" { name = "foobar-terraform-elb-live" - availability_zones = ["us-west-2a"] + availability_zones = slice(data.aws_availability_zones.available.names, 0, 1) listener { instance_port = 80 @@ -1588,7 +1891,7 @@ resource "aws_route53_record" "elb_weighted_alias_live" { resource "aws_elb" "dev" { name = "foobar-terraform-elb-dev" - availability_zones = ["us-west-2a"] + availability_zones = slice(data.aws_availability_zones.available.names, 0, 1) listener { instance_port = 80 @@ -1678,7 +1981,7 @@ resource "aws_route53_zone" "main" { } resource "aws_route53_record" "sample" { - zone_id = "${aws_route53_zone.main.zone_id}" + zone_id = "${aws_route53_zone.main.zone_id}" name = "sample" type = "CNAME" ttl = "30" @@ -1700,6 +2003,34 @@ resource "aws_route53_record" "sample" { } ` +const testAccRoute53RecordNameChangePre = ` +resource "aws_route53_zone" "main" { + name = "notexample.com" +} + +resource "aws_route53_record" "sample" { + zone_id = "${aws_route53_zone.main.zone_id}" + name = "sample" + type = "CNAME" + ttl = "30" + records = ["www.terraform.io"] +} +` + +const testAccRoute53RecordNameChangePost = ` +resource "aws_route53_zone" "main" { + name = "notexample.com" +} + +resource "aws_route53_record" "sample" { + zone_id = "${aws_route53_zone.main.zone_id}" + name = "sample-new" + type = "CNAME" + ttl = "30" + records = ["www.terraform.io"] +} +` + const testAccRoute53RecordSetIdentifierChangePre = ` resource "aws_route53_zone" "main" { name = "notexample.com" @@ -1733,13 +2064,22 @@ resource "aws_route53_record" "basic_to_weighted" { ` const testAccRoute53RecordAliasChangePre = ` +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_route53_zone" "main" { name = "notexample.com" } resource "aws_elb" "alias_change" { name = "foobar-tf-elb-alias-change" - availability_zones = ["us-west-2a"] + availability_zones = slice(data.aws_availability_zones.available.names, 0, 1) listener { instance_port = 80 diff --git a/aws/resource_aws_route53_resolver_endpoint.go b/aws/resource_aws_route53_resolver_endpoint.go index 95d6a86e5a8..33920babe0d 100644 --- a/aws/resource_aws_route53_resolver_endpoint.go +++ b/aws/resource_aws_route53_resolver_endpoint.go @@ -8,10 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53resolver" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_route53_resolver_endpoint_test.go b/aws/resource_aws_route53_resolver_endpoint_test.go index 71506f58a92..3cbbe8723bf 100644 --- a/aws/resource_aws_route53_resolver_endpoint_test.go +++ b/aws/resource_aws_route53_resolver_endpoint_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53resolver" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_route53_resolver_rule.go b/aws/resource_aws_route53_resolver_rule.go index 0627220c3de..0f17d1a34d2 100644 --- a/aws/resource_aws_route53_resolver_rule.go +++ b/aws/resource_aws_route53_resolver_rule.go @@ -2,16 +2,17 @@ package aws import ( "bytes" + "context" "fmt" "log" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53resolver" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -38,11 +39,11 @@ func resourceAwsRoute53ResolverRule() *schema.Resource { Schema: map[string]*schema.Schema{ "domain_name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - DiffSuppressFunc: suppressRoute53ZoneNameWithTrailingDot, - ValidateFunc: validation.StringLenBetween(1, 256), + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 256), + StateFunc: trimTrailingPeriod, }, "rule_type": { @@ -163,7 +164,9 @@ func resourceAwsRoute53ResolverRuleRead(d *schema.ResourceData, meta interface{} rule := ruleRaw.(*route53resolver.ResolverRule) d.Set("arn", rule.Arn) - d.Set("domain_name", rule.DomainName) + // To be consistent with other AWS services that do not accept a trailing period, + // we remove the suffix from the Domain Name returned from the API + d.Set("domain_name", trimTrailingPeriod(aws.StringValue(rule.DomainName))) d.Set("name", rule.Name) d.Set("owner_id", rule.OwnerId) d.Set("resolver_endpoint_id", rule.ResolverEndpointId) @@ -189,7 +192,7 @@ func resourceAwsRoute53ResolverRuleRead(d *schema.ResourceData, meta interface{} func resourceAwsRoute53ResolverRuleUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).route53resolverconn - if d.HasChange("name") || d.HasChange("resolver_endpoint_id") || d.HasChange("target_ip") { + if d.HasChanges("name", "resolver_endpoint_id", "target_ip") { req := &route53resolver.UpdateResolverRuleInput{ ResolverRuleId: aws.String(d.Id()), Config: &route53resolver.ResolverRuleConfig{}, @@ -252,7 +255,7 @@ func resourceAwsRoute53ResolverRuleDelete(d *schema.ResourceData, meta interface return nil } -func resourceAwsRoute53ResolverRuleCustomizeDiff(diff *schema.ResourceDiff, v interface{}) error { +func resourceAwsRoute53ResolverRuleCustomizeDiff(_ context.Context, diff *schema.ResourceDiff, v interface{}) error { if diff.Id() != "" { if diff.HasChange("resolver_endpoint_id") { if _, n := diff.GetChange("resolver_endpoint_id"); n.(string) == "" { diff --git a/aws/resource_aws_route53_resolver_rule_association.go b/aws/resource_aws_route53_resolver_rule_association.go index a371832174f..a8bed3d291f 100644 --- a/aws/resource_aws_route53_resolver_rule_association.go +++ b/aws/resource_aws_route53_resolver_rule_association.go @@ -5,9 +5,9 @@ import ( "log" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53resolver" diff --git a/aws/resource_aws_route53_resolver_rule_association_test.go b/aws/resource_aws_route53_resolver_rule_association_test.go index 14cd84c1511..9faa484049c 100644 --- a/aws/resource_aws_route53_resolver_rule_association_test.go +++ b/aws/resource_aws_route53_resolver_rule_association_test.go @@ -7,9 +7,9 @@ import ( "time" multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53resolver" diff --git a/aws/resource_aws_route53_resolver_rule_test.go b/aws/resource_aws_route53_resolver_rule_test.go index 684c24645d8..3602c57607b 100644 --- a/aws/resource_aws_route53_resolver_rule_test.go +++ b/aws/resource_aws_route53_resolver_rule_test.go @@ -7,9 +7,10 @@ import ( "time" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53resolver" @@ -94,7 +95,7 @@ func TestAccAwsRoute53ResolverRule_basic(t *testing.T) { Config: testAccRoute53ResolverRuleConfig_basicNoTags, Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ResolverRuleExists(resourceName, &rule), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com."), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), resource.TestCheckResourceAttr(resourceName, "rule_type", "SYSTEM"), resource.TestCheckResourceAttr(resourceName, "share_status", "NOT_SHARED"), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), @@ -123,7 +124,7 @@ func TestAccAwsRoute53ResolverRule_tags(t *testing.T) { Config: testAccRoute53ResolverRuleConfig_basicTags, Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ResolverRuleExists(resourceName, &rule), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com."), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), resource.TestCheckResourceAttr(resourceName, "rule_type", "SYSTEM"), resource.TestCheckResourceAttr(resourceName, "share_status", "NOT_SHARED"), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -139,7 +140,7 @@ func TestAccAwsRoute53ResolverRule_tags(t *testing.T) { Config: testAccRoute53ResolverRuleConfig_basicTagsChanged, Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ResolverRuleExists(resourceName, &rule), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com."), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), resource.TestCheckResourceAttr(resourceName, "rule_type", "SYSTEM"), resource.TestCheckResourceAttr(resourceName, "share_status", "NOT_SHARED"), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -150,7 +151,7 @@ func TestAccAwsRoute53ResolverRule_tags(t *testing.T) { Config: testAccRoute53ResolverRuleConfig_basicNoTags, Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ResolverRuleExists(resourceName, &rule), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com."), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), resource.TestCheckResourceAttr(resourceName, "rule_type", "SYSTEM"), resource.TestCheckResourceAttr(resourceName, "share_status", "NOT_SHARED"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -175,7 +176,7 @@ func TestAccAwsRoute53ResolverRule_updateName(t *testing.T) { Config: testAccRoute53ResolverRuleConfig_basicName(name1), Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ResolverRuleExists(resourceName, &rule1), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com."), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), resource.TestCheckResourceAttr(resourceName, "name", name1), resource.TestCheckResourceAttr(resourceName, "rule_type", "SYSTEM"), ), @@ -190,7 +191,7 @@ func TestAccAwsRoute53ResolverRule_updateName(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ResolverRuleExists(resourceName, &rule2), testAccCheckRoute53ResolverRulesSame(&rule2, &rule1), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com."), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), resource.TestCheckResourceAttr(resourceName, "name", name2), resource.TestCheckResourceAttr(resourceName, "rule_type", "SYSTEM"), ), @@ -207,22 +208,23 @@ func TestAccAwsRoute53ResolverRule_forward(t *testing.T) { name := fmt.Sprintf("terraform-testacc-r53-resolver-%d", acctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSRoute53Resolver(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckRoute53ResolverRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSRoute53Resolver(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckRoute53ResolverRuleDestroy, Steps: []resource.TestStep{ { Config: testAccRoute53ResolverRuleConfig_forward(name), Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ResolverRuleExists(resourceName, &rule1), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com."), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), resource.TestCheckResourceAttr(resourceName, "name", name), resource.TestCheckResourceAttr(resourceName, "rule_type", "FORWARD"), resource.TestCheckResourceAttrPair(resourceName, "resolver_endpoint_id", resourceNameEp1, "id"), resource.TestCheckResourceAttr(resourceName, "target_ip.#", "1"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1379138419.ip", "192.0.2.6"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1379138419.port", "53"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "target_ip.*", map[string]string{ + "ip": "192.0.2.6", + "port": "53", + }), ), }, { @@ -235,15 +237,19 @@ func TestAccAwsRoute53ResolverRule_forward(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ResolverRuleExists(resourceName, &rule2), testAccCheckRoute53ResolverRulesSame(&rule2, &rule1), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com."), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), resource.TestCheckResourceAttr(resourceName, "name", name), resource.TestCheckResourceAttrPair(resourceName, "resolver_endpoint_id", resourceNameEp1, "id"), resource.TestCheckResourceAttr(resourceName, "rule_type", "FORWARD"), resource.TestCheckResourceAttr(resourceName, "target_ip.#", "2"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1867764419.ip", "192.0.2.7"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1867764419.port", "53"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1677112772.ip", "192.0.2.17"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1677112772.port", "54"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "target_ip.*", map[string]string{ + "ip": "192.0.2.7", + "port": "53", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "target_ip.*", map[string]string{ + "ip": "192.0.2.17", + "port": "54", + }), ), }, { @@ -251,15 +257,19 @@ func TestAccAwsRoute53ResolverRule_forward(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ResolverRuleExists(resourceName, &rule3), testAccCheckRoute53ResolverRulesSame(&rule3, &rule2), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com."), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), resource.TestCheckResourceAttr(resourceName, "name", name), resource.TestCheckResourceAttrPair(resourceName, "resolver_endpoint_id", resourceNameEp2, "id"), resource.TestCheckResourceAttr(resourceName, "rule_type", "FORWARD"), resource.TestCheckResourceAttr(resourceName, "target_ip.#", "2"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1867764419.ip", "192.0.2.7"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1867764419.port", "53"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1677112772.ip", "192.0.2.17"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1677112772.port", "54"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "target_ip.*", map[string]string{ + "ip": "192.0.2.7", + "port": "53", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "target_ip.*", map[string]string{ + "ip": "192.0.2.17", + "port": "54", + }), ), }, }, @@ -273,22 +283,23 @@ func TestAccAwsRoute53ResolverRule_forwardEndpointRecreate(t *testing.T) { name := fmt.Sprintf("terraform-testacc-r53-resolver-%d", acctest.RandInt()) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSRoute53Resolver(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckRoute53ResolverRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSRoute53Resolver(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckRoute53ResolverRuleDestroy, Steps: []resource.TestStep{ { Config: testAccRoute53ResolverRuleConfig_forward(name), Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ResolverRuleExists(resourceName, &rule1), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com."), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), resource.TestCheckResourceAttr(resourceName, "name", name), resource.TestCheckResourceAttr(resourceName, "rule_type", "FORWARD"), resource.TestCheckResourceAttrPair(resourceName, "resolver_endpoint_id", resourceNameEp, "id"), resource.TestCheckResourceAttr(resourceName, "target_ip.#", "1"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1379138419.ip", "192.0.2.6"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1379138419.port", "53"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "target_ip.*", map[string]string{ + "ip": "192.0.2.6", + "port": "53", + }), ), }, { @@ -296,13 +307,16 @@ func TestAccAwsRoute53ResolverRule_forwardEndpointRecreate(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ResolverRuleExists(resourceName, &rule2), testAccCheckRoute53ResolverRulesDifferent(&rule2, &rule1), - resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com."), + resource.TestCheckResourceAttr(resourceName, "domain_name", "example.com"), resource.TestCheckResourceAttr(resourceName, "name", name), resource.TestCheckResourceAttr(resourceName, "rule_type", "FORWARD"), resource.TestCheckResourceAttrPair(resourceName, "resolver_endpoint_id", resourceNameEp, "id"), resource.TestCheckResourceAttr(resourceName, "target_ip.#", "1"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1379138419.ip", "192.0.2.6"), - resource.TestCheckResourceAttr(resourceName, "target_ip.1379138419.port", "53")), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "target_ip.*", map[string]string{ + "ip": "192.0.2.6", + "port": "53", + }), + ), }, }, }) diff --git a/aws/resource_aws_route53_vpc_association_authorization.go b/aws/resource_aws_route53_vpc_association_authorization.go new file mode 100644 index 00000000000..df8dd9c38ff --- /dev/null +++ b/aws/resource_aws_route53_vpc_association_authorization.go @@ -0,0 +1,155 @@ +package aws + +import ( + "fmt" + "log" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/route53" +) + +func resourceAwsRoute53VPCAssociationAuthorization() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsRoute53VPCAssociationAuthorizationCreate, + Read: resourceAwsRoute53VPCAssociationAuthorizationRead, + Delete: resourceAwsRoute53VPCAssociationAuthorizationDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "zone_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "vpc_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "vpc_region": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + } +} + +func resourceAwsRoute53VPCAssociationAuthorizationCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).r53conn + + req := &route53.CreateVPCAssociationAuthorizationInput{ + HostedZoneId: aws.String(d.Get("zone_id").(string)), + VPC: &route53.VPC{ + VPCId: aws.String(d.Get("vpc_id").(string)), + VPCRegion: aws.String(meta.(*AWSClient).region), + }, + } + + if v, ok := d.GetOk("vpc_region"); ok { + req.VPC.VPCRegion = aws.String(v.(string)) + } + + log.Printf("[DEBUG] Creating Route53 VPC Association Authorization for hosted zone %s with VPC %s and region %s", *req.HostedZoneId, *req.VPC.VPCId, *req.VPC.VPCRegion) + _, err := conn.CreateVPCAssociationAuthorization(req) + if err != nil { + return fmt.Errorf("Error creating Route53 VPC Association Authorization: %s", err) + } + + // Store association id + d.SetId(fmt.Sprintf("%s:%s", *req.HostedZoneId, *req.VPC.VPCId)) + + return resourceAwsRoute53VPCAssociationAuthorizationRead(d, meta) +} + +func resourceAwsRoute53VPCAssociationAuthorizationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).r53conn + + zone_id, vpc_id, err := resourceAwsRoute53VPCAssociationAuthorizationParseId(d.Id()) + if err != nil { + return err + } + + req := route53.ListVPCAssociationAuthorizationsInput{ + HostedZoneId: aws.String(zone_id), + } + + for { + log.Printf("[DEBUG] Listing Route53 VPC Association Authorizations for hosted zone %s", zone_id) + res, err := conn.ListVPCAssociationAuthorizations(&req) + + if isAWSErr(err, route53.ErrCodeNoSuchHostedZone, "") { + log.Printf("[WARN] Route53 VPC Association Authorization (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + if err != nil { + return fmt.Errorf("Error listing Route53 VPC Association Authorizations: %s", err) + } + + for _, vpc := range res.VPCs { + if vpc_id == aws.StringValue(vpc.VPCId) { + d.Set("vpc_id", vpc.VPCId) + d.Set("vpc_region", vpc.VPCRegion) + d.Set("zone_id", zone_id) + return nil + } + } + + // Loop till we find our authorization or we reach the end + if res.NextToken != nil { + req.NextToken = res.NextToken + } else { + break + } + } + + // no association found + log.Printf("[WARN] Route53 VPC Association Authorization (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil +} + +func resourceAwsRoute53VPCAssociationAuthorizationDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).r53conn + + zone_id, vpc_id, err := resourceAwsRoute53VPCAssociationAuthorizationParseId(d.Id()) + if err != nil { + return err + } + + req := route53.DeleteVPCAssociationAuthorizationInput{ + HostedZoneId: aws.String(zone_id), + VPC: &route53.VPC{ + VPCId: aws.String(vpc_id), + VPCRegion: aws.String(d.Get("vpc_region").(string)), + }, + } + + log.Printf("[DEBUG] Deleting Route53 Assocatiation Authorization for hosted zone %s for VPC %s", zone_id, vpc_id) + _, err = conn.DeleteVPCAssociationAuthorization(&req) + if err != nil { + return fmt.Errorf("Error deleting Route53 VPC Association Authorization: %s", err) + } + + return nil +} + +func resourceAwsRoute53VPCAssociationAuthorizationParseId(id string) (string, string, error) { + parts := strings.SplitN(id, ":", 2) + + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", "", fmt.Errorf("Unexpected format of ID (%q), expected ZONEID:VPCID", id) + } + + return parts[0], parts[1], nil +} diff --git a/aws/resource_aws_route53_vpc_association_authorization_test.go b/aws/resource_aws_route53_vpc_association_authorization_test.go new file mode 100644 index 00000000000..04c37cf16fe --- /dev/null +++ b/aws/resource_aws_route53_vpc_association_authorization_test.go @@ -0,0 +1,165 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/route53" +) + +func TestAccAWSRoute53VpcAssociationAuthorization_basic(t *testing.T) { + var providers []*schema.Provider + resourceName := "aws_route53_vpc_association_authorization.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + testAccAlternateAccountPreCheck(t) + }, + ProviderFactories: testAccProviderFactories(&providers), + CheckDestroy: testAccCheckRoute53VPCAssociationAuthorizationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRoute53VPCAssociationAuthorizationConfig(), + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53VPCAssociationAuthorizationExists(resourceName), + ), + }, + { + Config: testAccRoute53VPCAssociationAuthorizationConfig(), + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSRoute53VpcAssociationAuthorization_disappears(t *testing.T) { + var providers []*schema.Provider + resourceName := "aws_route53_vpc_association_authorization.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + testAccAlternateAccountPreCheck(t) + }, + ProviderFactories: testAccProviderFactories(&providers), + CheckDestroy: testAccCheckRoute53VPCAssociationAuthorizationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRoute53VPCAssociationAuthorizationConfig(), + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53VPCAssociationAuthorizationExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsRoute53VPCAssociationAuthorization(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckRoute53VPCAssociationAuthorizationDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).r53conn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_route53_vpc_association_authorization" { + continue + } + + zone_id, vpc_id, err := resourceAwsRoute53VPCAssociationAuthorizationParseId(rs.Primary.ID) + if err != nil { + return err + } + + req := route53.ListVPCAssociationAuthorizationsInput{ + HostedZoneId: aws.String(zone_id), + } + + res, err := conn.ListVPCAssociationAuthorizations(&req) + if isAWSErr(err, route53.ErrCodeNoSuchHostedZone, "") { + return nil + } + if err != nil { + return err + } + + for _, vpc := range res.VPCs { + if vpc_id == *vpc.VPCId { + return fmt.Errorf("VPC association authorization for zone %v with %v still exists", zone_id, vpc_id) + } + } + } + return nil +} + +func testAccCheckRoute53VPCAssociationAuthorizationExists(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 VPC association authorization ID is set") + } + + zone_id, vpc_id, err := resourceAwsRoute53VPCAssociationAuthorizationParseId(rs.Primary.ID) + if err != nil { + return err + } + + conn := testAccProvider.Meta().(*AWSClient).r53conn + + req := route53.ListVPCAssociationAuthorizationsInput{ + HostedZoneId: aws.String(zone_id), + } + + res, err := conn.ListVPCAssociationAuthorizations(&req) + if err != nil { + return err + } + + for _, vpc := range res.VPCs { + if vpc_id == *vpc.VPCId { + return nil + } + } + + return fmt.Errorf("VPC association authorization not found") + } +} + +func testAccRoute53VPCAssociationAuthorizationConfig() string { + return testAccAlternateAccountProviderConfig() + ` +resource "aws_vpc" "test" { + cidr_block = "10.6.0.0/16" + enable_dns_hostnames = true + enable_dns_support = true +} + +resource "aws_route53_zone" "test" { + name = "example.com" + vpc { + vpc_id = aws_vpc.test.id + } +} + +resource "aws_vpc" "alternate" { + provider = "awsalternate" + cidr_block = "10.7.0.0/16" + enable_dns_hostnames = true + enable_dns_support = true +} + +resource "aws_route53_vpc_association_authorization" "test" { + zone_id = aws_route53_zone.test.id + vpc_id = aws_vpc.alternate.id +} +` +} diff --git a/aws/resource_aws_route53_zone.go b/aws/resource_aws_route53_zone.go index e12c609f489..cb7ff868f62 100644 --- a/aws/resource_aws_route53_zone.go +++ b/aws/resource_aws_route53_zone.go @@ -10,10 +10,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -29,10 +29,14 @@ func resourceAwsRoute53Zone() *schema.Resource { Schema: map[string]*schema.Schema{ "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - DiffSuppressFunc: suppressRoute53ZoneNameWithTrailingDot, + // AWS Provider 3.0.0 - trailing period removed from name + // returned from API, no longer requiring custom DiffSuppressFunc; + // instead a StateFunc allows input to be provided + // with or without the trailing period + Type: schema.TypeString, + Required: true, + ForceNew: true, + StateFunc: trimTrailingPeriod, }, "comment": { @@ -63,22 +67,6 @@ func resourceAwsRoute53Zone() *schema.Resource { Set: route53HostedZoneVPCHash, }, - "vpc_id": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Computed: true, - Removed: "use 'vpc' configuration block instead", - }, - - "vpc_region": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - Computed: true, - Removed: "use 'vpc' configuration block instead", - }, - "zone_id": { Type: schema.TypeString, Computed: true, @@ -195,7 +183,9 @@ func resourceAwsRoute53ZoneRead(d *schema.ResourceData, meta interface{}) error d.Set("comment", "") d.Set("delegation_set_id", "") - d.Set("name", output.HostedZone.Name) + // To be consistent with other AWS services (e.g. ACM) that do not accept a trailing period, + // we remove the suffix from the Hosted Zone Name returned from the API + d.Set("name", trimTrailingPeriod(aws.StringValue(output.HostedZone.Name))) d.Set("zone_id", cleanZoneID(aws.StringValue(output.HostedZone.Id))) var nameServers []string @@ -405,6 +395,22 @@ func cleanZoneID(ID string) string { return strings.TrimPrefix(ID, "/hostedzone/") } +// trimTrailingPeriod is used to remove the trailing period +// of "name" or "domain name" attributes often returned from +// the Route53 API or provided as user input +func trimTrailingPeriod(v interface{}) string { + var str string + switch value := v.(type) { + case *string: + str = *value + case string: + str = value + default: + return "" + } + return strings.TrimSuffix(str, ".") +} + func getNameServers(zoneId string, zoneName string, r53 *route53.Route53) ([]string, error) { resp, err := r53.ListResourceRecordSets(&route53.ListResourceRecordSetsInput{ HostedZoneId: aws.String(zoneId), diff --git a/aws/resource_aws_route53_zone_association.go b/aws/resource_aws_route53_zone_association.go index 63b00a75476..6d018711666 100644 --- a/aws/resource_aws_route53_zone_association.go +++ b/aws/resource_aws_route53_zone_association.go @@ -6,8 +6,8 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53" @@ -41,52 +41,56 @@ func resourceAwsRoute53ZoneAssociation() *schema.Resource { Computed: true, ForceNew: true, }, + + "owning_account": { + Type: schema.TypeString, + Computed: true, + }, }, } } func resourceAwsRoute53ZoneAssociationCreate(d *schema.ResourceData, meta interface{}) error { - r53 := meta.(*AWSClient).r53conn + conn := meta.(*AWSClient).r53conn - req := &route53.AssociateVPCWithHostedZoneInput{ - HostedZoneId: aws.String(d.Get("zone_id").(string)), + vpcRegion := meta.(*AWSClient).region + vpcID := d.Get("vpc_id").(string) + zoneID := d.Get("zone_id").(string) + + if v, ok := d.GetOk("vpc_region"); ok { + vpcRegion = v.(string) + } + + input := &route53.AssociateVPCWithHostedZoneInput{ + HostedZoneId: aws.String(zoneID), VPC: &route53.VPC{ - VPCId: aws.String(d.Get("vpc_id").(string)), - VPCRegion: aws.String(meta.(*AWSClient).region), + VPCId: aws.String(vpcID), + VPCRegion: aws.String(vpcRegion), }, Comment: aws.String("Managed by Terraform"), } - if w := d.Get("vpc_region"); w != "" { - req.VPC.VPCRegion = aws.String(w.(string)) - } - log.Printf("[DEBUG] Associating Route53 Private Zone %s with VPC %s with region %s", *req.HostedZoneId, *req.VPC.VPCId, *req.VPC.VPCRegion) - var err error - resp, err := r53.AssociateVPCWithHostedZone(req) + output, err := conn.AssociateVPCWithHostedZone(input) + if err != nil { - return err + return fmt.Errorf("error associating Route 53 Hosted Zone (%s) to EC2 VPC (%s): %w", zoneID, vpcID, err) } - // Store association id - d.SetId(fmt.Sprintf("%s:%s", *req.HostedZoneId, *req.VPC.VPCId)) - - // Wait until we are done initializing - wait := resource.StateChangeConf{ - Delay: 30 * time.Second, - Pending: []string{"PENDING"}, - Target: []string{"INSYNC"}, - Timeout: 10 * time.Minute, - MinTimeout: 2 * time.Second, - Refresh: func() (result interface{}, state string, err error) { - changeRequest := &route53.GetChangeInput{ - Id: aws.String(cleanChangeID(*resp.ChangeInfo.Id)), - } - return resourceAwsGoRoute53Wait(r53, changeRequest) - }, - } - _, err = wait.WaitForState() - if err != nil { - return err + d.SetId(fmt.Sprintf("%s:%s:%s", zoneID, vpcID, vpcRegion)) + + if output != nil && output.ChangeInfo != nil && output.ChangeInfo.Id != nil { + wait := resource.StateChangeConf{ + Delay: 30 * time.Second, + Pending: []string{route53.ChangeStatusPending}, + Target: []string{route53.ChangeStatusInsync}, + Timeout: 10 * time.Minute, + MinTimeout: 2 * time.Second, + Refresh: resourceAwsRoute53ZoneAssociationRefreshFunc(conn, cleanChangeID(aws.StringValue(output.ChangeInfo.Id)), d.Id()), + } + + if _, err := wait.WaitForState(); err != nil { + return fmt.Errorf("error waiting for Route 53 Zone Association (%s) synchronization: %w", d.Id(), err) + } } return resourceAwsRoute53ZoneAssociationRead(d, meta) @@ -95,33 +99,47 @@ func resourceAwsRoute53ZoneAssociationCreate(d *schema.ResourceData, meta interf func resourceAwsRoute53ZoneAssociationRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).r53conn - zoneID, vpcID, err := resourceAwsRoute53ZoneAssociationParseId(d.Id()) + zoneID, vpcID, vpcRegion, err := resourceAwsRoute53ZoneAssociationParseId(d.Id()) if err != nil { return err } - vpc, err := route53GetZoneAssociation(conn, zoneID, vpcID) + // Continue supporting older resources without VPC Region in ID + if vpcRegion == "" { + vpcRegion = d.Get("vpc_region").(string) + } + + if vpcRegion == "" { + vpcRegion = meta.(*AWSClient).region + } + + hostedZoneSummary, err := route53GetZoneAssociation(conn, zoneID, vpcID, vpcRegion) - if isAWSErr(err, route53.ErrCodeNoSuchHostedZone, "") { - log.Printf("[WARN] Route 53 Hosted Zone (%s) not found, removing from state", zoneID) + if isAWSErr(err, "AccessDenied", "is not owned by you") && !d.IsNewResource() { + log.Printf("[WARN] Route 53 Zone Association (%s) not found, removing from state", d.Id()) d.SetId("") return nil } if err != nil { - return fmt.Errorf("error getting Route 53 Hosted Zone (%s): %s", zoneID, err) + return fmt.Errorf("error getting Route 53 Zone Association (%s): %w", d.Id(), err) } - if vpc == nil { + if hostedZoneSummary == nil { + if d.IsNewResource() { + return fmt.Errorf("error getting Route 53 Zone Association (%s): missing after creation", d.Id()) + } + log.Printf("[WARN] Route 53 Hosted Zone (%s) Association (%s) not found, removing from state", zoneID, vpcID) d.SetId("") return nil } - d.Set("vpc_id", vpc.VPCId) - d.Set("vpc_region", vpc.VPCRegion) + d.Set("vpc_id", vpcID) + d.Set("vpc_region", vpcRegion) d.Set("zone_id", zoneID) + d.Set("owning_account", hostedZoneSummary.Owner.OwningAccount) return nil } @@ -129,58 +147,86 @@ func resourceAwsRoute53ZoneAssociationRead(d *schema.ResourceData, meta interfac func resourceAwsRoute53ZoneAssociationDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).r53conn - zoneID, vpcID, err := resourceAwsRoute53ZoneAssociationParseId(d.Id()) + zoneID, vpcID, vpcRegion, err := resourceAwsRoute53ZoneAssociationParseId(d.Id()) if err != nil { return err } - log.Printf("[DEBUG] Disassociating Route 53 Hosted Zone (%s) Association: %s", zoneID, vpcID) + // Continue supporting older resources without VPC Region in ID + if vpcRegion == "" { + vpcRegion = d.Get("vpc_region").(string) + } + + if vpcRegion == "" { + vpcRegion = meta.(*AWSClient).region + } - req := &route53.DisassociateVPCFromHostedZoneInput{ + input := &route53.DisassociateVPCFromHostedZoneInput{ HostedZoneId: aws.String(zoneID), VPC: &route53.VPC{ VPCId: aws.String(vpcID), - VPCRegion: aws.String(d.Get("vpc_region").(string)), + VPCRegion: aws.String(vpcRegion), }, Comment: aws.String("Managed by Terraform"), } - _, err = conn.DisassociateVPCFromHostedZone(req) + _, err = conn.DisassociateVPCFromHostedZone(input) if err != nil { - return fmt.Errorf("error disassociating Route 53 Hosted Zone (%s) Association (%s): %s", zoneID, vpcID, err) + return fmt.Errorf("error disassociating Route 53 Hosted Zone (%s) from EC2 VPC (%s): %w", zoneID, vpcID, err) } return nil } -func resourceAwsRoute53ZoneAssociationParseId(id string) (string, string, error) { +func resourceAwsRoute53ZoneAssociationParseId(id string) (string, string, string, error) { parts := strings.Split(id, ":") + + if len(parts) == 3 && parts[0] != "" && parts[1] != "" && parts[2] != "" { + return parts[0], parts[1], parts[2], nil + } + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { - return "", "", fmt.Errorf("Unexpected format of ID (%q), expected ZONEID:VPCID", id) + return "", "", "", fmt.Errorf("Unexpected format of ID (%q), expected ZONEID:VPCID or ZONEID:VPCID:VPCREGION", id) + } + + return parts[0], parts[1], "", nil +} + +func resourceAwsRoute53ZoneAssociationRefreshFunc(conn *route53.Route53, changeId, id string) resource.StateRefreshFunc { + return func() (interface{}, string, error) { + changeRequest := &route53.GetChangeInput{ + Id: aws.String(changeId), + } + result, state, err := resourceAwsGoRoute53Wait(conn, changeRequest) + if isAWSErr(err, "AccessDenied", "") { + log.Printf("[WARN] AccessDenied when trying to get Route 53 change progress for %s - ignoring due to likely cross account issue", id) + return true, route53.ChangeStatusInsync, nil + } + return result, state, err } - return parts[0], parts[1], nil } -func route53GetZoneAssociation(conn *route53.Route53, zoneID, vpcID string) (*route53.VPC, error) { - input := &route53.GetHostedZoneInput{ - Id: aws.String(zoneID), +func route53GetZoneAssociation(conn *route53.Route53, zoneID, vpcID, vpcRegion string) (*route53.HostedZoneSummary, error) { + input := &route53.ListHostedZonesByVPCInput{ + VPCId: aws.String(vpcID), + VPCRegion: aws.String(vpcRegion), } - output, err := conn.GetHostedZone(input) + output, err := conn.ListHostedZonesByVPC(input) if err != nil { return nil, err } - var vpc *route53.VPC - for _, zoneVPC := range output.VPCs { - if vpcID == aws.StringValue(zoneVPC.VPCId) { - vpc = zoneVPC + var associatedHostedZoneSummary *route53.HostedZoneSummary + for _, hostedZoneSummary := range output.HostedZoneSummaries { + if zoneID == aws.StringValue(hostedZoneSummary.HostedZoneId) { + associatedHostedZoneSummary = hostedZoneSummary break } } - return vpc, nil + return associatedHostedZoneSummary, nil } diff --git a/aws/resource_aws_route53_zone_association_test.go b/aws/resource_aws_route53_zone_association_test.go index 7dbf1f5ef0a..a8f5ffe3ff3 100644 --- a/aws/resource_aws_route53_zone_association_test.go +++ b/aws/resource_aws_route53_zone_association_test.go @@ -4,17 +4,12 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/route53" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSRoute53ZoneAssociation_basic(t *testing.T) { - var vpc route53.VPC resourceName := "aws_route53_zone_association.foobar" resource.ParallelTest(t, resource.TestCase{ @@ -25,7 +20,7 @@ func TestAccAWSRoute53ZoneAssociation_basic(t *testing.T) { { Config: testAccRoute53ZoneAssociationConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckRoute53ZoneAssociationExists(resourceName, &vpc), + testAccCheckRoute53ZoneAssociationExists(resourceName), ), }, { @@ -38,10 +33,7 @@ func TestAccAWSRoute53ZoneAssociation_basic(t *testing.T) { } func TestAccAWSRoute53ZoneAssociation_disappears(t *testing.T) { - var vpc route53.VPC - var zone route53.GetHostedZoneOutput resourceName := "aws_route53_zone_association.foobar" - route53ZoneResourceName := "aws_route53_zone.foo" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -51,9 +43,8 @@ func TestAccAWSRoute53ZoneAssociation_disappears(t *testing.T) { { Config: testAccRoute53ZoneAssociationConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckRoute53ZoneExists(route53ZoneResourceName, &zone), - testAccCheckRoute53ZoneAssociationExists(resourceName, &vpc), - testAccCheckRoute53ZoneAssociationDisappears(&zone, &vpc), + testAccCheckRoute53ZoneAssociationExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsRoute53ZoneAssociation(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -62,8 +53,6 @@ func TestAccAWSRoute53ZoneAssociation_disappears(t *testing.T) { } func TestAccAWSRoute53ZoneAssociation_disappears_VPC(t *testing.T) { - var ec2Vpc ec2.Vpc - var route53Vpc route53.VPC resourceName := "aws_route53_zone_association.foobar" vpcResourceName := "aws_vpc.bar" @@ -75,9 +64,8 @@ func TestAccAWSRoute53ZoneAssociation_disappears_VPC(t *testing.T) { { Config: testAccRoute53ZoneAssociationConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckRoute53ZoneAssociationExists(resourceName, &route53Vpc), - testAccCheckVpcExists(vpcResourceName, &ec2Vpc), - testAccCheckVpcDisappears(&ec2Vpc), + testAccCheckRoute53ZoneAssociationExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsVpc(), vpcResourceName), ), ExpectNonEmptyPlan: true, }, @@ -86,8 +74,6 @@ func TestAccAWSRoute53ZoneAssociation_disappears_VPC(t *testing.T) { } func TestAccAWSRoute53ZoneAssociation_disappears_Zone(t *testing.T) { - var vpc route53.VPC - var zone route53.GetHostedZoneOutput resourceName := "aws_route53_zone_association.foobar" route53ZoneResourceName := "aws_route53_zone.foo" @@ -99,9 +85,8 @@ func TestAccAWSRoute53ZoneAssociation_disappears_Zone(t *testing.T) { { Config: testAccRoute53ZoneAssociationConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckRoute53ZoneExists(route53ZoneResourceName, &zone), - testAccCheckRoute53ZoneAssociationExists(resourceName, &vpc), - testAccCheckRoute53ZoneDisappears(&zone), + testAccCheckRoute53ZoneAssociationExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsRoute53Zone(), route53ZoneResourceName), ), ExpectNonEmptyPlan: true, }, @@ -109,8 +94,38 @@ func TestAccAWSRoute53ZoneAssociation_disappears_Zone(t *testing.T) { }) } -func TestAccAWSRoute53ZoneAssociation_region(t *testing.T) { - var vpc route53.VPC +func TestAccAWSRoute53ZoneAssociation_CrossAccount(t *testing.T) { + resourceName := "aws_route53_zone_association.test" + + // record the initialized providers so that we can use them to + // check for the instances in each region + var providers []*schema.Provider + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + testAccAlternateAccountPreCheck(t) + }, + ProviderFactories: testAccProviderFactories(&providers), + CheckDestroy: testAccCheckRoute53ZoneAssociationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccRoute53ZoneAssociationCrossAccountConfig(), + Check: resource.ComposeTestCheckFunc( + testAccCheckRoute53ZoneAssociationExists(resourceName), + ), + }, + { + Config: testAccRoute53ZoneAssociationCrossAccountConfig(), + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSRoute53ZoneAssociation_CrossRegion(t *testing.T) { resourceName := "aws_route53_zone_association.test" // record the initialized providers so that we can use them to @@ -120,8 +135,7 @@ func TestAccAWSRoute53ZoneAssociation_region(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) - testAccMultipleRegionsPreCheck(t) - testAccAlternateRegionPreCheck(t) + testAccMultipleRegionPreCheck(t, 2) }, ProviderFactories: testAccProviderFactories(&providers), CheckDestroy: testAccCheckRoute53ZoneAssociationDestroy, @@ -129,7 +143,7 @@ func TestAccAWSRoute53ZoneAssociation_region(t *testing.T) { { Config: testAccRoute53ZoneAssociationRegionConfig(), Check: resource.ComposeTestCheckFunc( - testAccCheckRoute53ZoneAssociationExists(resourceName, &vpc), + testAccCheckRoute53ZoneAssociationExists(resourceName), ), }, { @@ -149,15 +163,15 @@ func testAccCheckRoute53ZoneAssociationDestroy(s *terraform.State) error { continue } - zoneID, vpcID, err := resourceAwsRoute53ZoneAssociationParseId(rs.Primary.ID) + zoneID, vpcID, vpcRegion, err := resourceAwsRoute53ZoneAssociationParseId(rs.Primary.ID) if err != nil { return err } - vpc, err := route53GetZoneAssociation(conn, zoneID, vpcID) + hostedZoneSummary, err := route53GetZoneAssociation(conn, zoneID, vpcID, vpcRegion) - if isAWSErr(err, route53.ErrCodeNoSuchHostedZone, "") { + if isAWSErr(err, "AccessDenied", "is not owned by you") { continue } @@ -165,25 +179,25 @@ func testAccCheckRoute53ZoneAssociationDestroy(s *terraform.State) error { return err } - if vpc != nil { - return fmt.Errorf("Route 53 Hosted Zone (%s) Association (%s) still exists", zoneID, vpcID) + if hostedZoneSummary != nil { + return fmt.Errorf("Route 53 Zone Association (%s) still exists", rs.Primary.ID) } } return nil } -func testAccCheckRoute53ZoneAssociationExists(n string, vpc *route53.VPC) resource.TestCheckFunc { +func testAccCheckRoute53ZoneAssociationExists(resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] + rs, ok := s.RootModule().Resources[resourceName] if !ok { - return fmt.Errorf("Not found: %s", n) + return fmt.Errorf("Not found: %s", resourceName) } if rs.Primary.ID == "" { return fmt.Errorf("No zone association ID is set") } - zoneID, vpcID, err := resourceAwsRoute53ZoneAssociationParseId(rs.Primary.ID) + zoneID, vpcID, vpcRegion, err := resourceAwsRoute53ZoneAssociationParseId(rs.Primary.ID) if err != nil { return err @@ -191,38 +205,20 @@ func testAccCheckRoute53ZoneAssociationExists(n string, vpc *route53.VPC) resour conn := testAccProvider.Meta().(*AWSClient).r53conn - associationVPC, err := route53GetZoneAssociation(conn, zoneID, vpcID) + hostedZoneSummary, err := route53GetZoneAssociation(conn, zoneID, vpcID, vpcRegion) if err != nil { return err } - if associationVPC == nil { + if hostedZoneSummary == nil { return fmt.Errorf("Route 53 Hosted Zone (%s) Association (%s) not found", zoneID, vpcID) } - *vpc = *associationVPC - return nil } } -func testAccCheckRoute53ZoneAssociationDisappears(zone *route53.GetHostedZoneOutput, vpc *route53.VPC) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).r53conn - - input := &route53.DisassociateVPCFromHostedZoneInput{ - HostedZoneId: zone.HostedZone.Id, - VPC: vpc, - Comment: aws.String("Managed by Terraform"), - } - - _, err := conn.DisassociateVPCFromHostedZone(input) - - return err - } -} - const testAccRoute53ZoneAssociationConfig = ` resource "aws_vpc" "foo" { cidr_block = "10.6.0.0/16" @@ -258,10 +254,58 @@ resource "aws_route53_zone_association" "foobar" { } ` +func testAccRoute53ZoneAssociationCrossAccountConfig() string { + return composeConfig( + testAccAlternateAccountProviderConfig(), + ` +resource "aws_vpc" "alternate" { + provider = "awsalternate" + + cidr_block = "10.7.0.0/16" + enable_dns_hostnames = true + enable_dns_support = true +} + +resource "aws_vpc" "test" { + cidr_block = "10.6.0.0/16" + enable_dns_hostnames = true + enable_dns_support = true +} + +resource "aws_route53_zone" "test" { + provider = "awsalternate" + + name = "foo.com" + + vpc { + vpc_id = aws_vpc.alternate.id + } + + lifecycle { + ignore_changes = [vpc] + } +} + +resource "aws_route53_vpc_association_authorization" "test" { + provider = "awsalternate" + + vpc_id = aws_vpc.test.id + zone_id = aws_route53_zone.test.id +} + +resource "aws_route53_zone_association" "test" { + vpc_id = aws_route53_vpc_association_authorization.test.vpc_id + zone_id = aws_route53_vpc_association_authorization.test.zone_id +} +`) +} + func testAccRoute53ZoneAssociationRegionConfig() string { - return testAccAlternateRegionProviderConfig() + ` + return composeConfig( + testAccMultipleRegionProviderConfig(2), + ` data "aws_region" "alternate" { - provider = "aws.alternate" + provider = "awsalternate" } data "aws_region" "current" {} @@ -277,7 +321,7 @@ resource "aws_vpc" "test" { } resource "aws_vpc" "alternate" { - provider = "aws.alternate" + provider = "awsalternate" cidr_block = "10.7.0.0/16" enable_dns_hostnames = true @@ -306,5 +350,5 @@ resource "aws_route53_zone_association" "test" { vpc_region = data.aws_region.alternate.name zone_id = aws_route53_zone.test.id } -` +`) } diff --git a/aws/resource_aws_route53_zone_test.go b/aws/resource_aws_route53_zone_test.go index 8c8c0229525..41877f90117 100644 --- a/aws/resource_aws_route53_zone_test.go +++ b/aws/resource_aws_route53_zone_test.go @@ -8,10 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/route53" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestCleanZoneID(t *testing.T) { @@ -48,6 +48,23 @@ func TestCleanChangeID(t *testing.T) { } } +func TestTrimTrailingPeriod(t *testing.T) { + cases := []struct { + Input, Output string + }{ + {"example.com", "example.com"}, + {"example.com.", "example.com"}, + {"www.example.com.", "www.example.com"}, + } + + for _, tc := range cases { + actual := trimTrailingPeriod(tc.Input) + if actual != tc.Output { + t.Fatalf("input: %s\noutput: %s", tc.Input, actual) + } + } +} + func TestAccAWSRoute53Zone_basic(t *testing.T) { var zone route53.GetHostedZoneOutput @@ -64,7 +81,7 @@ func TestAccAWSRoute53Zone_basic(t *testing.T) { Config: testAccRoute53ZoneConfig(zoneName), Check: resource.ComposeTestCheckFunc( testAccCheckRoute53ZoneExists(resourceName, &zone), - resource.TestCheckResourceAttr(resourceName, "name", fmt.Sprintf("%s.", zoneName)), + resource.TestCheckResourceAttr(resourceName, "name", zoneName), resource.TestCheckResourceAttr(resourceName, "name_servers.#", "4"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), resource.TestCheckResourceAttr(resourceName, "vpc.#", "0"), @@ -554,7 +571,7 @@ func testAccCheckDomainName(zone *route53.GetHostedZoneOutput, domain string) re return fmt.Errorf("Empty name in HostedZone for domain %s", domain) } - if *zone.HostedZone.Name == domain { + if aws.StringValue(zone.HostedZone.Name) == domain { return nil } @@ -570,13 +587,13 @@ resource "aws_route53_zone" "test" { } func testAccRoute53ZoneConfigMultiple() string { - return fmt.Sprintf(` + return ` resource "aws_route53_zone" "test" { count = 5 name = "subdomain${count.index}.terraformtest.com" } -`) +` } func testAccRoute53ZoneConfigComment(zoneName, comment string) string { diff --git a/aws/resource_aws_route_table.go b/aws/resource_aws_route_table.go index 9ec855178cc..f56ae3e0e4c 100644 --- a/aws/resource_aws_route_table.go +++ b/aws/resource_aws_route_table.go @@ -8,10 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -50,15 +50,21 @@ func resourceAwsRouteTable() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "cidr_block": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.IsCIDR, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validateIpv4CIDRNetworkAddress, + ), }, "ipv6_cidr_block": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validation.IsCIDR, + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.Any( + validation.StringIsEmpty, + validateIpv6CIDRNetworkAddress, + ), }, "egress_only_gateway_id": { @@ -228,6 +234,7 @@ func resourceAwsRouteTableRead(d *schema.ResourceData, meta interface{}) error { } d.Set("route", route) + // Tags if err := d.Set("tags", keyvaluetags.Ec2KeyValueTags(rt.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { return fmt.Errorf("error setting tags: %s", err) } diff --git a/aws/resource_aws_route_table_association.go b/aws/resource_aws_route_table_association.go index c63095b0796..24243673f81 100644 --- a/aws/resource_aws_route_table_association.go +++ b/aws/resource_aws_route_table_association.go @@ -9,8 +9,8 @@ import ( "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-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsRouteTableAssociation() *schema.Resource { diff --git a/aws/resource_aws_route_table_association_test.go b/aws/resource_aws_route_table_association_test.go index 5276cb81953..2deb7aac2e1 100644 --- a/aws/resource_aws_route_table_association_test.go +++ b/aws/resource_aws_route_table_association_test.go @@ -7,8 +7,8 @@ import ( "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-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSRouteTableAssociation_Subnet_basic(t *testing.T) { diff --git a/aws/resource_aws_route_table_test.go b/aws/resource_aws_route_table_test.go index 40914d93893..67de64cb3d5 100644 --- a/aws/resource_aws_route_table_test.go +++ b/aws/resource_aws_route_table_test.go @@ -8,8 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -514,6 +516,45 @@ func TestAccAWSRouteTable_vgwRoutePropagation(t *testing.T) { }) } +func TestAccAWSRouteTable_ConditionalCidrBlock(t *testing.T) { + var routeTable ec2.RouteTable + resourceName := "aws_route_table.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSRouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSRouteTableConfigConditionalIpv4Ipv6(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckRouteTableExists(resourceName, &routeTable), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "route.*", map[string]string{ + "cidr_block": "0.0.0.0/0", + "ipv6_cidr_block": "", + }), + ), + }, + { + Config: testAccAWSRouteTableConfigConditionalIpv4Ipv6(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckRouteTableExists(resourceName, &routeTable), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "route.*", map[string]string{ + "cidr_block": "", + "ipv6_cidr_block": "::/0", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + const testAccRouteTableConfig = ` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" @@ -771,7 +812,7 @@ resource "aws_route_table" "test" { ` func testAccAWSRouteTableConfigRouteConfigModeBlocks() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -801,11 +842,11 @@ resource "aws_route_table" "test" { gateway_id = "${aws_internet_gateway.test.id}" } } -`) +` } func testAccAWSRouteTableConfigRouteConfigModeNoBlocks() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -825,11 +866,11 @@ resource "aws_internet_gateway" "test" { resource "aws_route_table" "test" { vpc_id = "${aws_vpc.test.id}" } -`) +` } func testAccAWSRouteTableConfigRouteConfigModeZeroed() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -850,15 +891,15 @@ resource "aws_route_table" "test" { route = [] vpc_id = "${aws_vpc.test.id}" } -`) +` } func testAccAWSRouteTableConfigRouteTransitGatewayID() string { - return fmt.Sprintf(` + return ` data "aws_availability_zones" "available" { # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + exclude_zone_ids = ["usw2-az4"] + state = "available" filter { name = "opt-in-status" @@ -900,5 +941,56 @@ resource "aws_route_table" "test" { transit_gateway_id = "${aws_ec2_transit_gateway_vpc_attachment.test.transit_gateway_id}" } } -`) +` +} + +func testAccAWSRouteTableConfigConditionalIpv4Ipv6(rName string, ipv6Route bool) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + + assign_generated_ipv6_cidr_block = true + + tags = { + Name = %[1]q + } +} + +resource "aws_egress_only_internet_gateway" "test" { + vpc_id = "${aws_vpc.test.id}" + + tags = { + Name = %[1]q + } +} + +resource "aws_internet_gateway" "test" { + vpc_id = "${aws_vpc.test.id}" + + tags = { + Name = %[1]q + } +} + + +locals { + ipv6 = %[2]t + destination = "0.0.0.0/0" + destination_ipv6 = "::/0" +} + +resource "aws_route_table" "test" { + vpc_id = "${aws_vpc.test.id}" + + route { + cidr_block = "${local.ipv6 ? "" : local.destination}" + ipv6_cidr_block = "${local.ipv6 ? local.destination_ipv6 : ""}" + gateway_id = "${aws_internet_gateway.test.id}" + } + + tags = { + Name = %[1]q + } +} +`, rName, ipv6Route) } diff --git a/aws/resource_aws_route_test.go b/aws/resource_aws_route_test.go index 0a9abb77b36..d5f24d0a212 100644 --- a/aws/resource_aws_route_test.go +++ b/aws/resource_aws_route_test.go @@ -5,8 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSRoute_basic(t *testing.T) { @@ -39,7 +40,7 @@ func TestAccAWSRoute_basic(t *testing.T) { CheckDestroy: testAccCheckAWSRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRouteBasicConfig, + Config: testAccAWSRouteBasicConfig(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.bar", &route), testCheck, @@ -66,7 +67,7 @@ func TestAccAWSRoute_disappears(t *testing.T) { CheckDestroy: testAccCheckAWSRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRouteBasicConfig, + Config: testAccAWSRouteBasicConfig(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.bar", &route), testAccCheckResourceDisappears(testAccProvider, resourceAwsRoute(), "aws_route.bar"), @@ -104,7 +105,7 @@ func TestAccAWSRoute_ipv6Support(t *testing.T) { CheckDestroy: testAccCheckAWSRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRouteConfigIpv6, + Config: testAccAWSRouteConfigIpv6(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.bar", &route), testCheck, @@ -118,7 +119,7 @@ func TestAccAWSRoute_ipv6Support(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSRouteConfigIpv6Expanded, + Config: testAccAWSRouteConfigIpv6Expanded(), PlanOnly: true, }, }, @@ -136,7 +137,7 @@ func TestAccAWSRoute_ipv6ToInternetGateway(t *testing.T) { CheckDestroy: testAccCheckAWSRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRouteConfigIpv6InternetGateway, + Config: testAccAWSRouteConfigIpv6InternetGateway(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.igw", &route), ), @@ -162,7 +163,7 @@ func TestAccAWSRoute_ipv6ToInstance(t *testing.T) { CheckDestroy: testAccCheckAWSRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRouteConfigIpv6Instance, + Config: testAccAWSRouteConfigIpv6Instance(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.internal-default-route-ipv6", &route), ), @@ -174,7 +175,7 @@ func TestAccAWSRoute_ipv6ToInstance(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccAWSRouteConfigIpv6InstanceExpanded, + Config: testAccAWSRouteConfigIpv6InstanceExpanded(), PlanOnly: true, }, }, @@ -192,7 +193,7 @@ func TestAccAWSRoute_ipv6ToNetworkInterface(t *testing.T) { CheckDestroy: testAccCheckAWSRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRouteConfigIpv6NetworkInterface, + Config: testAccAWSRouteConfigIpv6NetworkInterface(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.internal-default-route-ipv6", &route), ), @@ -218,7 +219,7 @@ func TestAccAWSRoute_ipv6ToPeeringConnection(t *testing.T) { CheckDestroy: testAccCheckAWSRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRouteConfigIpv6PeeringConnection, + Config: testAccAWSRouteConfigIpv6PeeringConnection(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.pc", &route), ), @@ -245,13 +246,13 @@ func TestAccAWSRoute_changeRouteTable(t *testing.T) { CheckDestroy: testAccCheckAWSRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRouteBasicConfig, + Config: testAccAWSRouteBasicConfig(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.bar", &before), ), }, { - Config: testAccAWSRouteNewRouteTable, + Config: testAccAWSRouteNewRouteTable(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.bar", &after), ), @@ -319,14 +320,14 @@ func TestAccAWSRoute_changeCidr(t *testing.T) { CheckDestroy: testAccCheckAWSRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRouteBasicConfig, + Config: testAccAWSRouteBasicConfig(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.bar", &route), testCheck, ), }, { - Config: testAccAWSRouteBasicConfigChangeCidr, + Config: testAccAWSRouteBasicConfigChangeCidr(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.bar", &route), testAccCheckRouteTableExists("aws_route_table.foo", &routeTable), @@ -363,14 +364,14 @@ func TestAccAWSRoute_noopdiff(t *testing.T) { CheckDestroy: testAccCheckAWSRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRouteNoopChange, + Config: testAccAWSRouteNoopChange(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.test", &route), testCheck, ), }, { - Config: testAccAWSRouteNoopChange, + Config: testAccAWSRouteNoopChange(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.test", &route), testAccCheckRouteTableExists("aws_route_table.test", &routeTable), @@ -396,7 +397,7 @@ func TestAccAWSRoute_doesNotCrashWithVPCEndpoint(t *testing.T) { CheckDestroy: testAccCheckAWSRouteDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSRouteWithVPCEndpoint, + Config: testAccAWSRouteWithVPCEndpoint(), Check: resource.ComposeTestCheckFunc( testAccCheckAWSRouteExists("aws_route.bar", &route), ), @@ -438,6 +439,42 @@ func TestAccAWSRoute_TransitGatewayID_DestinationCidrBlock(t *testing.T) { }) } +func TestAccAWSRoute_ConditionalCidrBlock(t *testing.T) { + var route ec2.Route + resourceName := "aws_route.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSRouteDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSRouteConfigConditionalIpv4Ipv6(rName, false), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSRouteExists(resourceName, &route), + resource.TestCheckResourceAttr(resourceName, "destination_cidr_block", "0.0.0.0/0"), + resource.TestCheckResourceAttr(resourceName, "destination_ipv6_cidr_block", ""), + ), + }, + { + Config: testAccAWSRouteConfigConditionalIpv4Ipv6(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSRouteExists(resourceName, &route), + resource.TestCheckResourceAttr(resourceName, "destination_cidr_block", ""), + resource.TestCheckResourceAttr(resourceName, "destination_ipv6_cidr_block", "::/0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccAWSRouteImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + }, + }) +} + func testAccCheckAWSRouteExists(n string, res *ec2.Route) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -501,79 +538,88 @@ func testAccAWSRouteImportStateIdFunc(resourceName string) resource.ImportStateI } destination := rs.Primary.Attributes["destination_cidr_block"] - if _, ok := rs.Primary.Attributes["destination_ipv6_cidr_block"]; ok { - destination = rs.Primary.Attributes["destination_ipv6_cidr_block"] + if v, ok := rs.Primary.Attributes["destination_ipv6_cidr_block"]; ok && v != "" { + destination = v } return fmt.Sprintf("%s_%s", rs.Primary.Attributes["route_table_id"], destination), nil } } -var testAccAWSRouteBasicConfig = fmt.Sprint(` +func testAccAWSRouteBasicConfig() string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { - cidr_block = "10.1.0.0/16" - tags = { - Name = "terraform-testacc-route-basic" - } + cidr_block = "10.1.0.0/16" + + tags = { + Name = "terraform-testacc-route-basic" + } } resource "aws_internet_gateway" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id - tags = { - Name = "terraform-testacc-route-basic" - } + tags = { + Name = "terraform-testacc-route-basic" + } } resource "aws_route_table" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } resource "aws_route" "bar" { - route_table_id = "${aws_route_table.foo.id}" - destination_cidr_block = "10.3.0.0/16" - gateway_id = "${aws_internet_gateway.foo.id}" + route_table_id = aws_route_table.foo.id + destination_cidr_block = "10.3.0.0/16" + gateway_id = aws_internet_gateway.foo.id } `) +} -var testAccAWSRouteConfigIpv6InternetGateway = fmt.Sprintf(` +func testAccAWSRouteConfigIpv6InternetGateway() string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { - cidr_block = "10.1.0.0/16" + cidr_block = "10.1.0.0/16" assign_generated_ipv6_cidr_block = true + tags = { Name = "terraform-testacc-route-ipv6-igw" } } resource "aws_egress_only_internet_gateway" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } resource "aws_internet_gateway" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id - tags = { - Name = "terraform-testacc-route-ipv6-igw" - } + tags = { + Name = "terraform-testacc-route-ipv6-igw" + } } resource "aws_route_table" "external" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } resource "aws_route" "igw" { - route_table_id = "${aws_route_table.external.id}" + route_table_id = aws_route_table.external.id destination_ipv6_cidr_block = "::/0" - gateway_id = "${aws_internet_gateway.foo.id}" + gateway_id = aws_internet_gateway.foo.id } - `) +} -var testAccAWSRouteConfigIpv6NetworkInterface = fmt.Sprintf(` +func testAccAWSRouteConfigIpv6NetworkInterface() string { + return testAccAvailableEc2InstanceTypeForAvailabilityZone("aws_subnet.router-network.availability_zone", "t2.small", "t3.small") + + testAccLatestAmazonLinuxHvmEbsAmiConfig() + + fmt.Sprintf(` resource "aws_vpc" "examplevpc" { - cidr_block = "10.100.0.0/16" - enable_dns_hostnames = true + cidr_block = "10.100.0.0/16" + enable_dns_hostnames = true assign_generated_ipv6_cidr_block = true + tags = { Name = "terraform-testacc-route-ipv6-network-interface" } @@ -589,7 +635,7 @@ data "aws_availability_zones" "available" { } resource "aws_internet_gateway" "internet" { - vpc_id = "${aws_vpc.examplevpc.id}" + vpc_id = aws_vpc.examplevpc.id tags = { Name = "terraform-testacc-route-ipv6-network-interface" @@ -597,99 +643,92 @@ resource "aws_internet_gateway" "internet" { } resource "aws_route" "igw" { - route_table_id = "${aws_vpc.examplevpc.main_route_table_id}" + route_table_id = aws_vpc.examplevpc.main_route_table_id destination_cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.internet.id}" + gateway_id = aws_internet_gateway.internet.id } resource "aws_route" "igw-ipv6" { - route_table_id = "${aws_vpc.examplevpc.main_route_table_id}" + route_table_id = aws_vpc.examplevpc.main_route_table_id destination_ipv6_cidr_block = "::/0" - gateway_id = "${aws_internet_gateway.internet.id}" + gateway_id = aws_internet_gateway.internet.id } resource "aws_subnet" "router-network" { - cidr_block = "10.100.1.0/24" - vpc_id = "${aws_vpc.examplevpc.id}" - ipv6_cidr_block = "${cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 1)}" + cidr_block = "10.100.1.0/24" + vpc_id = aws_vpc.examplevpc.id + ipv6_cidr_block = cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 1) assign_ipv6_address_on_creation = true - map_public_ip_on_launch = true - availability_zone = "${data.aws_availability_zones.available.names[0]}" + map_public_ip_on_launch = true + availability_zone = data.aws_availability_zones.available.names[0] + tags = { Name = "tf-acc-route-ipv6-network-interface-router" } } resource "aws_subnet" "client-network" { - cidr_block = "10.100.10.0/24" - vpc_id = "${aws_vpc.examplevpc.id}" - ipv6_cidr_block = "${cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 2)}" + cidr_block = "10.100.10.0/24" + vpc_id = aws_vpc.examplevpc.id + ipv6_cidr_block = cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 2) assign_ipv6_address_on_creation = true - map_public_ip_on_launch = false - availability_zone = "${data.aws_availability_zones.available.names[0]}" + map_public_ip_on_launch = false + availability_zone = data.aws_availability_zones.available.names[0] + tags = { Name = "tf-acc-route-ipv6-network-interface-client" } } resource "aws_route_table" "client-routes" { - vpc_id = "${aws_vpc.examplevpc.id}" + vpc_id = aws_vpc.examplevpc.id } resource "aws_route_table_association" "client-routes" { - route_table_id = "${aws_route_table.client-routes.id}" - subnet_id = "${aws_subnet.client-network.id}" -} - -data "aws_ami" "ubuntu" { - most_recent = true - filter { - name = "name" - values = ["ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-*"] - } - filter { - name = "virtualization-type" - values = ["hvm"] - } - owners = ["099720109477"] + route_table_id = aws_route_table.client-routes.id + subnet_id = aws_subnet.client-network.id } resource "aws_instance" "test-router" { - ami = "${data.aws_ami.ubuntu.image_id}" - instance_type = "t2.small" - subnet_id = "${aws_subnet.router-network.id}" + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = data.aws_ec2_instance_type_offering.available.instance_type + subnet_id = aws_subnet.router-network.id } resource "aws_network_interface" "router-internal" { - subnet_id = "${aws_subnet.client-network.id}" + subnet_id = aws_subnet.client-network.id source_dest_check = false } resource "aws_network_interface_attachment" "router-internal" { - device_index = 1 - instance_id = "${aws_instance.test-router.id}" - network_interface_id = "${aws_network_interface.router-internal.id}" + device_index = 1 + instance_id = aws_instance.test-router.id + network_interface_id = aws_network_interface.router-internal.id } resource "aws_route" "internal-default-route" { - route_table_id = "${aws_route_table.client-routes.id}" + route_table_id = aws_route_table.client-routes.id destination_cidr_block = "0.0.0.0/0" - network_interface_id = "${aws_network_interface.router-internal.id}" + network_interface_id = aws_network_interface.router-internal.id } resource "aws_route" "internal-default-route-ipv6" { - route_table_id = "${aws_route_table.client-routes.id}" + route_table_id = aws_route_table.client-routes.id destination_ipv6_cidr_block = "::/0" - network_interface_id = "${aws_network_interface.router-internal.id}" + network_interface_id = aws_network_interface.router-internal.id } - `) +} -var testAccAWSRouteConfigIpv6Instance = fmt.Sprintf(` +func testAccAWSRouteConfigIpv6Instance() string { + return testAccAvailableEc2InstanceTypeForAvailabilityZone("aws_subnet.router-network.availability_zone", "t2.small", "t3.small") + + testAccLatestAmazonLinuxHvmEbsAmiConfig() + + fmt.Sprintf(` resource "aws_vpc" "examplevpc" { - cidr_block = "10.100.0.0/16" - enable_dns_hostnames = true + cidr_block = "10.100.0.0/16" + enable_dns_hostnames = true assign_generated_ipv6_cidr_block = true + tags = { Name = "terraform-testacc-route-ipv6-instance" } @@ -705,7 +744,7 @@ data "aws_availability_zones" "available" { } resource "aws_internet_gateway" "internet" { - vpc_id = "${aws_vpc.examplevpc.id}" + vpc_id = aws_vpc.examplevpc.id tags = { Name = "terraform-testacc-route-ipv6-instance" @@ -713,87 +752,81 @@ resource "aws_internet_gateway" "internet" { } resource "aws_route" "igw" { - route_table_id = "${aws_vpc.examplevpc.main_route_table_id}" + route_table_id = aws_vpc.examplevpc.main_route_table_id destination_cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.internet.id}" + gateway_id = aws_internet_gateway.internet.id } resource "aws_route" "igw-ipv6" { - route_table_id = "${aws_vpc.examplevpc.main_route_table_id}" + route_table_id = aws_vpc.examplevpc.main_route_table_id destination_ipv6_cidr_block = "::/0" - gateway_id = "${aws_internet_gateway.internet.id}" + gateway_id = aws_internet_gateway.internet.id } resource "aws_subnet" "router-network" { - cidr_block = "10.100.1.0/24" - vpc_id = "${aws_vpc.examplevpc.id}" - ipv6_cidr_block = "${cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 1)}" + cidr_block = "10.100.1.0/24" + vpc_id = aws_vpc.examplevpc.id + ipv6_cidr_block = cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 1) assign_ipv6_address_on_creation = true - map_public_ip_on_launch = true - availability_zone = "${data.aws_availability_zones.available.names[0]}" + map_public_ip_on_launch = true + availability_zone = data.aws_availability_zones.available.names[0] + tags = { Name = "tf-acc-route-ipv6-instance-router" } } resource "aws_subnet" "client-network" { - cidr_block = "10.100.10.0/24" - vpc_id = "${aws_vpc.examplevpc.id}" - ipv6_cidr_block = "${cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 2)}" + cidr_block = "10.100.10.0/24" + vpc_id = aws_vpc.examplevpc.id + ipv6_cidr_block = cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 2) assign_ipv6_address_on_creation = true - map_public_ip_on_launch = false - availability_zone = "${data.aws_availability_zones.available.names[0]}" + map_public_ip_on_launch = false + availability_zone = data.aws_availability_zones.available.names[0] + tags = { Name = "tf-acc-route-ipv6-instance-client" } } resource "aws_route_table" "client-routes" { - vpc_id = "${aws_vpc.examplevpc.id}" + vpc_id = aws_vpc.examplevpc.id } resource "aws_route_table_association" "client-routes" { - route_table_id = "${aws_route_table.client-routes.id}" - subnet_id = "${aws_subnet.client-network.id}" -} - -data "aws_ami" "ubuntu" { - most_recent = true - filter { - name = "name" - values = ["ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-*"] - } - filter { - name = "virtualization-type" - values = ["hvm"] - } - owners = ["099720109477"] + route_table_id = aws_route_table.client-routes.id + subnet_id = aws_subnet.client-network.id } resource "aws_instance" "test-router" { - ami = "${data.aws_ami.ubuntu.image_id}" - instance_type = "t2.small" - subnet_id = "${aws_subnet.router-network.id}" + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = data.aws_ec2_instance_type_offering.available.instance_type + subnet_id = aws_subnet.router-network.id } resource "aws_route" "internal-default-route" { - route_table_id = "${aws_route_table.client-routes.id}" + route_table_id = aws_route_table.client-routes.id destination_cidr_block = "0.0.0.0/0" - instance_id = "${aws_instance.test-router.id}" + instance_id = aws_instance.test-router.id } resource "aws_route" "internal-default-route-ipv6" { - route_table_id = "${aws_route_table.client-routes.id}" + route_table_id = aws_route_table.client-routes.id destination_ipv6_cidr_block = "::/0" - instance_id = "${aws_instance.test-router.id}" + instance_id = aws_instance.test-router.id } `) +} -var testAccAWSRouteConfigIpv6InstanceExpanded = fmt.Sprintf(` +func testAccAWSRouteConfigIpv6InstanceExpanded() string { + return testAccAvailableEc2InstanceTypeForAvailabilityZone("aws_subnet.router-network.availability_zone", "t2.small", "t3.small") + + testAccLatestAmazonLinuxHvmEbsAmiConfig() + + fmt.Sprintf(` resource "aws_vpc" "examplevpc" { - cidr_block = "10.100.0.0/16" - enable_dns_hostnames = true + cidr_block = "10.100.0.0/16" + enable_dns_hostnames = true assign_generated_ipv6_cidr_block = true + tags = { Name = "terraform-testacc-route-ipv6-instance" } @@ -809,7 +842,7 @@ data "aws_availability_zones" "available" { } resource "aws_internet_gateway" "internet" { - vpc_id = "${aws_vpc.examplevpc.id}" + vpc_id = aws_vpc.examplevpc.id tags = { Name = "terraform-testacc-route-ipv6-instance" @@ -817,115 +850,108 @@ resource "aws_internet_gateway" "internet" { } resource "aws_route" "igw" { - route_table_id = "${aws_vpc.examplevpc.main_route_table_id}" + route_table_id = aws_vpc.examplevpc.main_route_table_id destination_cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.internet.id}" + gateway_id = aws_internet_gateway.internet.id } resource "aws_route" "igw-ipv6" { - route_table_id = "${aws_vpc.examplevpc.main_route_table_id}" + route_table_id = aws_vpc.examplevpc.main_route_table_id destination_ipv6_cidr_block = "::0/0" - gateway_id = "${aws_internet_gateway.internet.id}" + gateway_id = aws_internet_gateway.internet.id } resource "aws_subnet" "router-network" { - cidr_block = "10.100.1.0/24" - vpc_id = "${aws_vpc.examplevpc.id}" - ipv6_cidr_block = "${cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 1)}" + cidr_block = "10.100.1.0/24" + vpc_id = aws_vpc.examplevpc.id + ipv6_cidr_block = cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 1) assign_ipv6_address_on_creation = true - map_public_ip_on_launch = true - availability_zone = "${data.aws_availability_zones.available.names[0]}" + map_public_ip_on_launch = true + availability_zone = data.aws_availability_zones.available.names[0] + tags = { Name = "tf-acc-route-ipv6-instance-router" } } resource "aws_subnet" "client-network" { - cidr_block = "10.100.10.0/24" - vpc_id = "${aws_vpc.examplevpc.id}" - ipv6_cidr_block = "${cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 2)}" + cidr_block = "10.100.10.0/24" + vpc_id = aws_vpc.examplevpc.id + ipv6_cidr_block = cidrsubnet(aws_vpc.examplevpc.ipv6_cidr_block, 8, 2) assign_ipv6_address_on_creation = true - map_public_ip_on_launch = false - availability_zone = "${data.aws_availability_zones.available.names[0]}" + map_public_ip_on_launch = false + availability_zone = data.aws_availability_zones.available.names[0] + tags = { Name = "tf-acc-route-ipv6-instance-client" } } resource "aws_route_table" "client-routes" { - vpc_id = "${aws_vpc.examplevpc.id}" + vpc_id = aws_vpc.examplevpc.id } resource "aws_route_table_association" "client-routes" { - route_table_id = "${aws_route_table.client-routes.id}" - subnet_id = "${aws_subnet.client-network.id}" -} - -data "aws_ami" "ubuntu" { - most_recent = true - filter { - name = "name" - values = ["ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-*"] - } - filter { - name = "virtualization-type" - values = ["hvm"] - } - owners = ["099720109477"] + route_table_id = aws_route_table.client-routes.id + subnet_id = aws_subnet.client-network.id } resource "aws_instance" "test-router" { - ami = "${data.aws_ami.ubuntu.image_id}" - instance_type = "t2.small" - subnet_id = "${aws_subnet.router-network.id}" + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = data.aws_ec2_instance_type_offering.available.instance_type + subnet_id = aws_subnet.router-network.id } resource "aws_route" "internal-default-route" { - route_table_id = "${aws_route_table.client-routes.id}" + route_table_id = aws_route_table.client-routes.id destination_cidr_block = "0.0.0.0/0" - instance_id = "${aws_instance.test-router.id}" + instance_id = aws_instance.test-router.id } resource "aws_route" "internal-default-route-ipv6" { - route_table_id = "${aws_route_table.client-routes.id}" + route_table_id = aws_route_table.client-routes.id destination_ipv6_cidr_block = "::0/0" - instance_id = "${aws_instance.test-router.id}" + instance_id = aws_instance.test-router.id } `) +} -var testAccAWSRouteConfigIpv6PeeringConnection = fmt.Sprintf(` +func testAccAWSRouteConfigIpv6PeeringConnection() string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { - cidr_block = "10.0.0.0/16" - assign_generated_ipv6_cidr_block = true - tags = { - Name = "terraform-testacc-route-ipv6-peering-connection" - } + cidr_block = "10.0.0.0/16" + assign_generated_ipv6_cidr_block = true + + tags = { + Name = "terraform-testacc-route-ipv6-peering-connection" + } } resource "aws_vpc" "bar" { - cidr_block = "10.1.0.0/16" - assign_generated_ipv6_cidr_block = true + cidr_block = "10.1.0.0/16" + assign_generated_ipv6_cidr_block = true } resource "aws_vpc_peering_connection" "foo" { - vpc_id = "${aws_vpc.foo.id}" - peer_vpc_id = "${aws_vpc.bar.id}" - auto_accept = true + vpc_id = aws_vpc.foo.id + peer_vpc_id = aws_vpc.bar.id + auto_accept = true } resource "aws_route_table" "peering" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } resource "aws_route" "pc" { - route_table_id = "${aws_route_table.peering.id}" - destination_ipv6_cidr_block = "${aws_vpc.bar.ipv6_cidr_block}" - vpc_peering_connection_id = "${aws_vpc_peering_connection.foo.id}" + route_table_id = aws_route_table.peering.id + destination_ipv6_cidr_block = aws_vpc.bar.ipv6_cidr_block + vpc_peering_connection_id = aws_vpc_peering_connection.foo.id } - `) +} -var testAccAWSRouteConfigIpv6 = fmt.Sprintf(` +func testAccAWSRouteConfigIpv6() string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" assign_generated_ipv6_cidr_block = true @@ -936,21 +962,23 @@ resource "aws_vpc" "foo" { } resource "aws_egress_only_internet_gateway" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } resource "aws_route_table" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } resource "aws_route" "bar" { - route_table_id = "${aws_route_table.foo.id}" + route_table_id = aws_route_table.foo.id destination_ipv6_cidr_block = "::/0" - egress_only_gateway_id = "${aws_egress_only_internet_gateway.foo.id}" + egress_only_gateway_id = aws_egress_only_internet_gateway.foo.id } `) +} -var testAccAWSRouteConfigIpv6Expanded = fmt.Sprintf(` +func testAccAWSRouteConfigIpv6Expanded() string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" assign_generated_ipv6_cidr_block = true @@ -961,52 +989,57 @@ resource "aws_vpc" "foo" { } resource "aws_egress_only_internet_gateway" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } resource "aws_route_table" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } resource "aws_route" "bar" { - route_table_id = "${aws_route_table.foo.id}" + route_table_id = aws_route_table.foo.id destination_ipv6_cidr_block = "::0/0" - egress_only_gateway_id = "${aws_egress_only_internet_gateway.foo.id}" + egress_only_gateway_id = aws_egress_only_internet_gateway.foo.id } `) +} -var testAccAWSRouteBasicConfigChangeCidr = fmt.Sprint(` +func testAccAWSRouteBasicConfigChangeCidr() string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { - cidr_block = "10.1.0.0/16" - tags = { - Name = "terraform-testacc-route-change-cidr" - } + cidr_block = "10.1.0.0/16" + + tags = { + Name = "terraform-testacc-route-change-cidr" + } } resource "aws_internet_gateway" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id - tags = { - Name = "terraform-testacc-route-change-cidr" - } + tags = { + Name = "terraform-testacc-route-change-cidr" + } } resource "aws_route_table" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } resource "aws_route" "bar" { - route_table_id = "${aws_route_table.foo.id}" - destination_cidr_block = "10.2.0.0/16" - gateway_id = "${aws_internet_gateway.foo.id}" + route_table_id = aws_route_table.foo.id + destination_cidr_block = "10.2.0.0/16" + gateway_id = aws_internet_gateway.foo.id } `) +} -var testAccAWSRouteNoopChange = fmt.Sprint(` +func testAccAWSRouteNoopChange() string { + return testAccAvailableEc2InstanceTypeForAvailabilityZone("aws_subnet.test.availability_zone", "t2.nano", "t3.nano") + + testAccLatestAmazonLinuxHvmEbsAmiConfig() + + fmt.Sprint(` data "aws_availability_zones" "available" { - # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" + state = "available" filter { name = "opt-in-status" @@ -1016,47 +1049,54 @@ data "aws_availability_zones" "available" { resource "aws_vpc" "test" { cidr_block = "10.10.0.0/16" + tags = { Name = "terraform-testacc-route-noop-change" } } resource "aws_route_table" "test" { - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" - vpc_id = "${aws_vpc.test.id}" - cidr_block = "10.10.10.0/24" + availability_zone = data.aws_availability_zones.available.names[0] + vpc_id = aws_vpc.test.id + cidr_block = "10.10.10.0/24" + tags = { Name = "tf-acc-route-noop-change" } } resource "aws_route" "test" { - route_table_id = "${aws_route_table.test.id}" + route_table_id = aws_route_table.test.id destination_cidr_block = "0.0.0.0/0" - instance_id = "${aws_instance.nat.id}" + instance_id = aws_instance.nat.id } resource "aws_instance" "nat" { - ami = "ami-9abea4fb" - instance_type = "t2.nano" - subnet_id = "${aws_subnet.test.id}" + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + instance_type = data.aws_ec2_instance_type_offering.available.instance_type + subnet_id = aws_subnet.test.id } `) +} + +func testAccAWSRouteWithVPCEndpoint() string { + return fmt.Sprintf(` +data "aws_region" "current" {} -var testAccAWSRouteWithVPCEndpoint = fmt.Sprint(` resource "aws_vpc" "foo" { cidr_block = "10.1.0.0/16" + tags = { Name = "terraform-testacc-route-with-vpc-endpoint" } } resource "aws_internet_gateway" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id tags = { Name = "terraform-testacc-route-with-vpc-endpoint" @@ -1064,91 +1104,88 @@ resource "aws_internet_gateway" "foo" { } resource "aws_route_table" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id } resource "aws_route" "bar" { - route_table_id = "${aws_route_table.foo.id}" + route_table_id = aws_route_table.foo.id destination_cidr_block = "10.3.0.0/16" - gateway_id = "${aws_internet_gateway.foo.id}" + gateway_id = aws_internet_gateway.foo.id # Forcing endpoint to create before route - without this the crash is a race. depends_on = ["aws_vpc_endpoint.baz"] } resource "aws_vpc_endpoint" "baz" { - vpc_id = "${aws_vpc.foo.id}" - service_name = "com.amazonaws.us-west-2.s3" - route_table_ids = ["${aws_route_table.foo.id}"] + vpc_id = aws_vpc.foo.id + service_name = "com.amazonaws.${data.aws_region.current.name}.s3" + route_table_ids = [aws_route_table.foo.id] } `) +} -var testAccAWSRouteNewRouteTable = fmt.Sprint(` +func testAccAWSRouteNewRouteTable() string { + return fmt.Sprintf(` resource "aws_vpc" "foo" { - cidr_block = "10.1.0.0/16" - tags = { - Name = "terraform-testacc-route-basic" - } + cidr_block = "10.1.0.0/16" + + tags = { + Name = "terraform-testacc-route-basic" + } } resource "aws_vpc" "bar" { - cidr_block = "10.2.0.0/16" - tags = { - Name = "terraform-testacc-route-new-route-table" - } + cidr_block = "10.2.0.0/16" + + tags = { + Name = "terraform-testacc-route-new-route-table" + } } resource "aws_internet_gateway" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id - tags = { - Name = "terraform-testacc-route-basic" - } + tags = { + Name = "terraform-testacc-route-basic" + } } resource "aws_internet_gateway" "bar" { - vpc_id = "${aws_vpc.bar.id}" + vpc_id = aws_vpc.bar.id - tags = { - Name = "terraform-testacc-route-new-route-table" - } + tags = { + Name = "terraform-testacc-route-new-route-table" + } } resource "aws_route_table" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id - tags = { - Name = "terraform-testacc-route-basic" - } + tags = { + Name = "terraform-testacc-route-basic" + } } resource "aws_route_table" "bar" { - vpc_id = "${aws_vpc.bar.id}" + vpc_id = aws_vpc.bar.id - tags = { - Name = "terraform-testacc-route-new-route-table" - } + tags = { + Name = "terraform-testacc-route-new-route-table" + } } resource "aws_route" "bar" { - route_table_id = "${aws_route_table.bar.id}" - destination_cidr_block = "10.4.0.0/16" - gateway_id = "${aws_internet_gateway.bar.id}" + route_table_id = aws_route_table.bar.id + destination_cidr_block = "10.4.0.0/16" + gateway_id = aws_internet_gateway.bar.id } `) +} func testAccAWSRouteConfigTransitGatewayIDDestinatationCidrBlock() string { - return fmt.Sprintf(` -data "aws_availability_zones" "available" { - # IncorrectState: Transit Gateway is not available in availability zone us-west-2d - blacklisted_zone_ids = ["usw2-az4"] - state = "available" - - filter { - name = "opt-in-status" - values = ["opt-in-not-required"] - } -} + return testAccAvailableAZsNoOptInDefaultExcludeConfig() + + fmt.Sprintf(` +# IncorrectState: Transit Gateway is not available in availability zone usw2-az4 resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -1159,9 +1196,9 @@ resource "aws_vpc" "test" { } resource "aws_subnet" "test" { - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.test.id}" + vpc_id = aws_vpc.test.id tags = { Name = "tf-acc-test-ec2-route-transit-gateway-id" @@ -1171,15 +1208,66 @@ resource "aws_subnet" "test" { resource "aws_ec2_transit_gateway" "test" {} resource "aws_ec2_transit_gateway_vpc_attachment" "test" { - subnet_ids = ["${aws_subnet.test.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.test.id}" - vpc_id = "${aws_vpc.test.id}" + subnet_ids = [aws_subnet.test.id] + transit_gateway_id = aws_ec2_transit_gateway.test.id + vpc_id = aws_vpc.test.id } resource "aws_route" "test" { destination_cidr_block = "0.0.0.0/0" - route_table_id = "${aws_vpc.test.default_route_table_id}" - transit_gateway_id = "${aws_ec2_transit_gateway_vpc_attachment.test.transit_gateway_id}" + route_table_id = aws_vpc.test.default_route_table_id + transit_gateway_id = aws_ec2_transit_gateway_vpc_attachment.test.transit_gateway_id } `) } + +func testAccAWSRouteConfigConditionalIpv4Ipv6(rName string, ipv6Route bool) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + assign_generated_ipv6_cidr_block = true + + tags = { + Name = %[1]q + } +} + +resource "aws_egress_only_internet_gateway" "test" { + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } +} + +resource "aws_internet_gateway" "test" { + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } +} + +resource "aws_route_table" "test" { + vpc_id = aws_vpc.test.id + + tags = { + Name = %[1]q + } +} + +locals { + ipv6 = %[2]t + destination = "0.0.0.0/0" + destination_ipv6 = "::/0" +} + +resource "aws_route" "test" { + route_table_id = aws_route_table.test.id + gateway_id = aws_internet_gateway.test.id + + destination_cidr_block = local.ipv6 ? "" : local.destination + destination_ipv6_cidr_block = local.ipv6 ? local.destination_ipv6 : "" +} +`, rName, ipv6Route) +} diff --git a/aws/resource_aws_s3_access_point.go b/aws/resource_aws_s3_access_point.go index 6d7e4e42a95..393557580d5 100644 --- a/aws/resource_aws_s3_access_point.go +++ b/aws/resource_aws_s3_access_point.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/s3control" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsS3AccessPoint() *schema.Resource { diff --git a/aws/resource_aws_s3_access_point_test.go b/aws/resource_aws_s3_access_point_test.go index c091c13f71c..159453c3546 100644 --- a/aws/resource_aws_s3_access_point_test.go +++ b/aws/resource_aws_s3_access_point_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3control" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" awspolicy "github.com/jen20/awspolicyequivalence" ) diff --git a/aws/resource_aws_s3_account_public_access_block.go b/aws/resource_aws_s3_account_public_access_block.go index 82a35fbaf89..446a266e8d6 100644 --- a/aws/resource_aws_s3_account_public_access_block.go +++ b/aws/resource_aws_s3_account_public_access_block.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3control" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsS3AccountPublicAccessBlock() *schema.Resource { diff --git a/aws/resource_aws_s3_account_public_access_block_test.go b/aws/resource_aws_s3_account_public_access_block_test.go index d9057a6111f..6492ea3969d 100644 --- a/aws/resource_aws_s3_account_public_access_block_test.go +++ b/aws/resource_aws_s3_account_public_access_block_test.go @@ -7,13 +7,13 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3control" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // S3 account-level settings must run serialized // for TeamCity environment -func TestAccAWSS3Account(t *testing.T) { +func TestAccAWSS3Account_serial(t *testing.T) { testCases := map[string]map[string]func(t *testing.T){ "PublicAccessBlock": { "basic": testAccAWSS3AccountPublicAccessBlock_basic, @@ -392,19 +392,17 @@ func testAccCheckAWSS3AccountPublicAccessBlockDisappears() resource.TestCheckFun } func testAccAWSS3AccountPublicAccessBlockConfig() string { - return fmt.Sprintf(` -resource "aws_s3_account_public_access_block" "test" {} -`) + return `resource "aws_s3_account_public_access_block" "test" {}` } func testAccAWSS3AccountPublicAccessBlockConfigAccountId() string { - return fmt.Sprintf(` + return ` data "aws_caller_identity" "test" {} resource "aws_s3_account_public_access_block" "test" { account_id = "${data.aws_caller_identity.test.account_id}" } -`) +` } func testAccAWSS3AccountPublicAccessBlockConfigBlockPublicAcls(blockPublicAcls bool) string { diff --git a/aws/resource_aws_s3_bucket.go b/aws/resource_aws_s3_bucket.go index 8d95bb5dd55..f1f54217e62 100644 --- a/aws/resource_aws_s3_bucket.go +++ b/aws/resource_aws_s3_bucket.go @@ -2,6 +2,7 @@ package aws import ( "bytes" + "context" "encoding/json" "fmt" "log" @@ -14,12 +15,14 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/endpoints" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -32,7 +35,7 @@ func resourceAwsS3Bucket() *schema.Resource { Update: resourceAwsS3BucketUpdate, Delete: resourceAwsS3BucketDelete, Importer: &schema.ResourceImporter{ - State: resourceAwsS3BucketImportState, + State: schema.ImportStatePassthrough, }, Schema: map[string]*schema.Schema{ @@ -205,7 +208,6 @@ func resourceAwsS3Bucket() *schema.Resource { "region": { Type: schema.TypeString, - Optional: true, Computed: true, }, "website_endpoint": { @@ -289,9 +291,8 @@ func resourceAwsS3Bucket() *schema.Resource { Optional: true, }, "expiration": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, - Set: expirationHash, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ @@ -313,10 +314,9 @@ func resourceAwsS3Bucket() *schema.Resource { }, }, "noncurrent_version_expiration": { - Type: schema.TypeSet, + Type: schema.TypeList, MaxItems: 1, Optional: true, - Set: expirationHash, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "days": { @@ -422,11 +422,10 @@ func resourceAwsS3Bucket() *schema.Resource { ValidateFunc: validation.StringLenBetween(0, 255), }, "destination": { - Type: schema.TypeSet, + Type: schema.TypeList, MaxItems: 1, MinItems: 1, Required: true, - Set: destinationHash, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "account_id": { @@ -477,19 +476,17 @@ func resourceAwsS3Bucket() *schema.Resource { }, }, "source_selection_criteria": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, MinItems: 1, MaxItems: 1, - Set: sourceSelectionCriteriaHash, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "sse_kms_encrypted_objects": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, MinItems: 1, MaxItems: 1, - Set: sourceSseKmsObjectsHash, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "enabled": { @@ -671,12 +668,7 @@ func resourceAwsS3BucketCreate(d *schema.ResourceData, meta interface{}) error { log.Printf("[DEBUG] S3 bucket %s has canned ACL %s", bucket, acl) } - var awsRegion string - if region, ok := d.GetOk("region"); ok { - awsRegion = region.(string) - } else { - awsRegion = meta.(*AWSClient).region - } + awsRegion := meta.(*AWSClient).region log.Printf("[DEBUG] S3 bucket create: %s, using region: %s", bucket, awsRegion) // Special case us-east-1 region and do not set the LocationConstraint. @@ -887,7 +879,7 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { return err } } else { - policy, err := structure.NormalizeJsonString(*v) + policy, err := structure.NormalizeJsonString(aws.StringValue(v)) if err != nil { return fmt.Errorf("policy contains an invalid JSON: %s", err) } @@ -940,7 +932,7 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { rule["expose_headers"] = flattenStringList(ruleObject.ExposeHeaders) } if ruleObject.MaxAgeSeconds != nil { - rule["max_age_seconds"] = int(*ruleObject.MaxAgeSeconds) + rule["max_age_seconds"] = int(aws.Int64Value(ruleObject.MaxAgeSeconds)) } corsRules = append(corsRules, rule) } @@ -964,34 +956,34 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { w := make(map[string]interface{}) if v := ws.IndexDocument; v != nil { - w["index_document"] = *v.Suffix + w["index_document"] = aws.StringValue(v.Suffix) } if v := ws.ErrorDocument; v != nil { - w["error_document"] = *v.Key + w["error_document"] = aws.StringValue(v.Key) } if v := ws.RedirectAllRequestsTo; v != nil { if v.Protocol == nil { - w["redirect_all_requests_to"] = *v.HostName + w["redirect_all_requests_to"] = aws.StringValue(v.HostName) } else { var host string var path string var query string - parsedHostName, err := url.Parse(*v.HostName) + parsedHostName, err := url.Parse(aws.StringValue(v.HostName)) if err == nil { host = parsedHostName.Host path = parsedHostName.Path query = parsedHostName.RawQuery } else { - host = *v.HostName + host = aws.StringValue(v.HostName) path = "" } w["redirect_all_requests_to"] = (&url.URL{ Host: host, Path: path, - Scheme: *v.Protocol, + Scheme: aws.StringValue(v.Protocol), RawQuery: query, }).String() } @@ -1029,13 +1021,13 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { vcl := make([]map[string]interface{}, 0, 1) if versioning, ok := versioningResponse.(*s3.GetBucketVersioningOutput); ok { vc := make(map[string]interface{}) - if versioning.Status != nil && *versioning.Status == s3.BucketVersioningStatusEnabled { + if versioning.Status != nil && aws.StringValue(versioning.Status) == s3.BucketVersioningStatusEnabled { vc["enabled"] = true } else { vc["enabled"] = false } - if versioning.MFADelete != nil && *versioning.MFADelete == s3.MFADeleteEnabled { + if versioning.MFADelete != nil && aws.StringValue(versioning.MFADelete) == s3.MFADeleteEnabled { vc["mfa_delete"] = true } else { vc["mfa_delete"] = false @@ -1093,11 +1085,11 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { if logging, ok := loggingResponse.(*s3.GetBucketLoggingOutput); ok && logging.LoggingEnabled != nil { v := logging.LoggingEnabled lc := make(map[string]interface{}) - if *v.TargetBucket != "" { - lc["target_bucket"] = *v.TargetBucket + if aws.StringValue(v.TargetBucket) != "" { + lc["target_bucket"] = aws.StringValue(v.TargetBucket) } - if *v.TargetPrefix != "" { - lc["target_prefix"] = *v.TargetPrefix + if aws.StringValue(v.TargetPrefix) != "" { + lc["target_prefix"] = aws.StringValue(v.TargetPrefix) } lcl = append(lcl, lc) } @@ -1125,15 +1117,15 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { rule := make(map[string]interface{}) // ID - if lifecycleRule.ID != nil && *lifecycleRule.ID != "" { - rule["id"] = *lifecycleRule.ID + if lifecycleRule.ID != nil && aws.StringValue(lifecycleRule.ID) != "" { + rule["id"] = aws.StringValue(lifecycleRule.ID) } filter := lifecycleRule.Filter if filter != nil { if filter.And != nil { // Prefix - if filter.And.Prefix != nil && *filter.And.Prefix != "" { - rule["prefix"] = *filter.And.Prefix + if filter.And.Prefix != nil && aws.StringValue(filter.And.Prefix) != "" { + rule["prefix"] = aws.StringValue(filter.And.Prefix) } // Tag if len(filter.And.Tags) > 0 { @@ -1141,8 +1133,8 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { } } else { // Prefix - if filter.Prefix != nil && *filter.Prefix != "" { - rule["prefix"] = *filter.Prefix + if filter.Prefix != nil && aws.StringValue(filter.Prefix) != "" { + rule["prefix"] = aws.StringValue(filter.Prefix) } // Tag if filter.Tag != nil { @@ -1151,13 +1143,13 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { } } else { if lifecycleRule.Prefix != nil { - rule["prefix"] = *lifecycleRule.Prefix + rule["prefix"] = aws.StringValue(lifecycleRule.Prefix) } } // Enabled if lifecycleRule.Status != nil { - if *lifecycleRule.Status == s3.ExpirationStatusEnabled { + if aws.StringValue(lifecycleRule.Status) == s3.ExpirationStatusEnabled { rule["enabled"] = true } else { rule["enabled"] = false @@ -1167,7 +1159,7 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { // AbortIncompleteMultipartUploadDays if lifecycleRule.AbortIncompleteMultipartUpload != nil { if lifecycleRule.AbortIncompleteMultipartUpload.DaysAfterInitiation != nil { - rule["abort_incomplete_multipart_upload_days"] = int(*lifecycleRule.AbortIncompleteMultipartUpload.DaysAfterInitiation) + rule["abort_incomplete_multipart_upload_days"] = int(aws.Int64Value(lifecycleRule.AbortIncompleteMultipartUpload.DaysAfterInitiation)) } } @@ -1175,23 +1167,23 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { if lifecycleRule.Expiration != nil { e := make(map[string]interface{}) if lifecycleRule.Expiration.Date != nil { - e["date"] = (*lifecycleRule.Expiration.Date).Format("2006-01-02") + e["date"] = (aws.TimeValue(lifecycleRule.Expiration.Date)).Format("2006-01-02") } if lifecycleRule.Expiration.Days != nil { - e["days"] = int(*lifecycleRule.Expiration.Days) + e["days"] = int(aws.Int64Value(lifecycleRule.Expiration.Days)) } if lifecycleRule.Expiration.ExpiredObjectDeleteMarker != nil { - e["expired_object_delete_marker"] = *lifecycleRule.Expiration.ExpiredObjectDeleteMarker + e["expired_object_delete_marker"] = aws.BoolValue(lifecycleRule.Expiration.ExpiredObjectDeleteMarker) } - rule["expiration"] = schema.NewSet(expirationHash, []interface{}{e}) + rule["expiration"] = []interface{}{e} } // noncurrent_version_expiration if lifecycleRule.NoncurrentVersionExpiration != nil { e := make(map[string]interface{}) if lifecycleRule.NoncurrentVersionExpiration.NoncurrentDays != nil { - e["days"] = int(*lifecycleRule.NoncurrentVersionExpiration.NoncurrentDays) + e["days"] = int(aws.Int64Value(lifecycleRule.NoncurrentVersionExpiration.NoncurrentDays)) } - rule["noncurrent_version_expiration"] = schema.NewSet(expirationHash, []interface{}{e}) + rule["noncurrent_version_expiration"] = []interface{}{e} } //// transition if len(lifecycleRule.Transitions) > 0 { @@ -1199,13 +1191,13 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { for _, v := range lifecycleRule.Transitions { t := make(map[string]interface{}) if v.Date != nil { - t["date"] = (*v.Date).Format("2006-01-02") + t["date"] = (aws.TimeValue(v.Date)).Format("2006-01-02") } if v.Days != nil { - t["days"] = int(*v.Days) + t["days"] = int(aws.Int64Value(v.Days)) } if v.StorageClass != nil { - t["storage_class"] = *v.StorageClass + t["storage_class"] = aws.StringValue(v.StorageClass) } transitions = append(transitions, t) } @@ -1217,10 +1209,10 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { for _, v := range lifecycleRule.NoncurrentVersionTransitions { t := make(map[string]interface{}) if v.NoncurrentDays != nil { - t["days"] = int(*v.NoncurrentDays) + t["days"] = int(aws.Int64Value(v.NoncurrentDays)) } if v.StorageClass != nil { - t["storage_class"] = *v.StorageClass + t["storage_class"] = aws.StringValue(v.StorageClass) } transitions = append(transitions, t) } @@ -1282,23 +1274,20 @@ func resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error { } // Add the region as an attribute - - locationResponse, err := retryOnAwsCode(s3.ErrCodeNoSuchBucket, func() (interface{}, error) { - return s3conn.GetBucketLocation( - &s3.GetBucketLocationInput{ - Bucket: aws.String(d.Id()), - }, - ) + discoveredRegion, err := retryOnAwsCode("NotFound", func() (interface{}, error) { + return s3manager.GetBucketRegionWithClient(context.Background(), s3conn, d.Id(), func(r *request.Request) { + // By default, GetBucketRegion forces virtual host addressing, which + // is not compatible with many non-AWS implementations. Instead, pass + // the provider s3_force_path_style configuration, which defaults to + // false, but allows override. + r.Config.S3ForcePathStyle = s3conn.Config.S3ForcePathStyle + }) }) if err != nil { return fmt.Errorf("error getting S3 Bucket location: %s", err) } - var region string - if location, ok := locationResponse.(*s3.GetBucketLocationOutput); ok && location.LocationConstraint != nil { - region = *location.LocationConstraint - } - region = normalizeRegion(region) + region := discoveredRegion.(string) if err := d.Set("region", region); err != nil { return err } @@ -1713,7 +1702,7 @@ func websiteEndpoint(client *AWSClient, d *schema.ResourceData) (*S3Website, err location := locationResponse.(*s3.GetBucketLocationOutput) var region string if location.LocationConstraint != nil { - region = *location.LocationConstraint + region = aws.StringValue(location.LocationConstraint) } return WebsiteEndpoint(client, bucket, region), nil @@ -1747,7 +1736,7 @@ func WebsiteDomainUrl(client *AWSClient, region string) string { if isOldRegion(region) { return fmt.Sprintf("s3-website-%s.amazonaws.com", region) //lintignore:AWSR001 } - return client.RegionalHostname(fmt.Sprintf("s3-website")) + return client.RegionalHostname("s3-website") } func isOldRegion(region string) bool { @@ -2036,48 +2025,53 @@ func resourceAwsS3BucketReplicationConfigurationUpdate(s3conn *s3.S3, d *schema. } ruleDestination := &s3.Destination{} - if dest, ok := rr["destination"].(*schema.Set); ok && dest.Len() > 0 { - bd := dest.List()[0].(map[string]interface{}) - ruleDestination.Bucket = aws.String(bd["bucket"].(string)) + if dest, ok := rr["destination"].([]interface{}); ok && len(dest) > 0 { + if dest[0] != nil { + bd := dest[0].(map[string]interface{}) + ruleDestination.Bucket = aws.String(bd["bucket"].(string)) - if storageClass, ok := bd["storage_class"]; ok && storageClass != "" { - ruleDestination.StorageClass = aws.String(storageClass.(string)) - } + if storageClass, ok := bd["storage_class"]; ok && storageClass != "" { + ruleDestination.StorageClass = aws.String(storageClass.(string)) + } - if replicaKmsKeyId, ok := bd["replica_kms_key_id"]; ok && replicaKmsKeyId != "" { - ruleDestination.EncryptionConfiguration = &s3.EncryptionConfiguration{ - ReplicaKmsKeyID: aws.String(replicaKmsKeyId.(string)), + if replicaKmsKeyId, ok := bd["replica_kms_key_id"]; ok && replicaKmsKeyId != "" { + ruleDestination.EncryptionConfiguration = &s3.EncryptionConfiguration{ + ReplicaKmsKeyID: aws.String(replicaKmsKeyId.(string)), + } } - } - if account, ok := bd["account_id"]; ok && account != "" { - ruleDestination.Account = aws.String(account.(string)) - } + if account, ok := bd["account_id"]; ok && account != "" { + ruleDestination.Account = aws.String(account.(string)) + } - if aclTranslation, ok := bd["access_control_translation"].([]interface{}); ok && len(aclTranslation) > 0 { - aclTranslationValues := aclTranslation[0].(map[string]interface{}) - ruleAclTranslation := &s3.AccessControlTranslation{} - ruleAclTranslation.Owner = aws.String(aclTranslationValues["owner"].(string)) - ruleDestination.AccessControlTranslation = ruleAclTranslation + if aclTranslation, ok := bd["access_control_translation"].([]interface{}); ok && len(aclTranslation) > 0 { + aclTranslationValues := aclTranslation[0].(map[string]interface{}) + ruleAclTranslation := &s3.AccessControlTranslation{} + ruleAclTranslation.Owner = aws.String(aclTranslationValues["owner"].(string)) + ruleDestination.AccessControlTranslation = ruleAclTranslation + } } - } rcRule.Destination = ruleDestination - if ssc, ok := rr["source_selection_criteria"].(*schema.Set); ok && ssc.Len() > 0 { - sscValues := ssc.List()[0].(map[string]interface{}) - ruleSsc := &s3.SourceSelectionCriteria{} - if sseKms, ok := sscValues["sse_kms_encrypted_objects"].(*schema.Set); ok && sseKms.Len() > 0 { - sseKmsValues := sseKms.List()[0].(map[string]interface{}) - sseKmsEncryptedObjects := &s3.SseKmsEncryptedObjects{} - if sseKmsValues["enabled"].(bool) { - sseKmsEncryptedObjects.Status = aws.String(s3.SseKmsEncryptedObjectsStatusEnabled) - } else { - sseKmsEncryptedObjects.Status = aws.String(s3.SseKmsEncryptedObjectsStatusDisabled) + if ssc, ok := rr["source_selection_criteria"].([]interface{}); ok && len(ssc) > 0 { + if ssc[0] != nil { + sscValues := ssc[0].(map[string]interface{}) + ruleSsc := &s3.SourceSelectionCriteria{} + if sseKms, ok := sscValues["sse_kms_encrypted_objects"].([]interface{}); ok && len(sseKms) > 0 { + if sseKms[0] != nil { + sseKmsValues := sseKms[0].(map[string]interface{}) + sseKmsEncryptedObjects := &s3.SseKmsEncryptedObjects{} + if sseKmsValues["enabled"].(bool) { + sseKmsEncryptedObjects.Status = aws.String(s3.SseKmsEncryptedObjectsStatusEnabled) + } else { + sseKmsEncryptedObjects.Status = aws.String(s3.SseKmsEncryptedObjectsStatusDisabled) + } + ruleSsc.SseKmsEncryptedObjects = sseKmsEncryptedObjects + } } - ruleSsc.SseKmsEncryptedObjects = sseKmsEncryptedObjects + rcRule.SourceSelectionCriteria = ruleSsc } - rcRule.SourceSelectionCriteria = ruleSsc } if f, ok := rr["filter"].([]interface{}); ok && len(f) > 0 && f[0] != nil { @@ -2137,7 +2131,7 @@ func resourceAwsS3BucketLifecycleUpdate(s3conn *s3.S3, d *schema.ResourceData) e lifecycleRules := d.Get("lifecycle_rule").([]interface{}) - if len(lifecycleRules) == 0 { + if len(lifecycleRules) == 0 || lifecycleRules[0] == nil { i := &s3.DeleteBucketLifecycleInput{ Bucket: aws.String(bucket), } @@ -2191,11 +2185,10 @@ func resourceAwsS3BucketLifecycleUpdate(s3conn *s3.S3, d *schema.ResourceData) e } // Expiration - expiration := d.Get(fmt.Sprintf("lifecycle_rule.%d.expiration", i)).(*schema.Set).List() - if len(expiration) > 0 { + expiration := d.Get(fmt.Sprintf("lifecycle_rule.%d.expiration", i)).([]interface{}) + if len(expiration) > 0 && expiration[0] != nil { e := expiration[0].(map[string]interface{}) i := &s3.LifecycleExpiration{} - if val, ok := e["date"].(string); ok && val != "" { t, err := time.Parse(time.RFC3339, fmt.Sprintf("%sT00:00:00Z", val)) if err != nil { @@ -2211,8 +2204,8 @@ func resourceAwsS3BucketLifecycleUpdate(s3conn *s3.S3, d *schema.ResourceData) e } // NoncurrentVersionExpiration - nc_expiration := d.Get(fmt.Sprintf("lifecycle_rule.%d.noncurrent_version_expiration", i)).(*schema.Set).List() - if len(nc_expiration) > 0 { + nc_expiration := d.Get(fmt.Sprintf("lifecycle_rule.%d.noncurrent_version_expiration", i)).([]interface{}) + if len(nc_expiration) > 0 && nc_expiration[0] != nil { e := nc_expiration[0].(map[string]interface{}) if val, ok := e["days"].(int); ok && val > 0 { @@ -2263,6 +2256,14 @@ func resourceAwsS3BucketLifecycleUpdate(s3conn *s3.S3, d *schema.ResourceData) e } } + // As a lifecycle rule requires 1 or more transition/expiration actions, + // we explicitly pass a default ExpiredObjectDeleteMarker value to be able to create + // the rule while keeping the policy unaffected if the conditions are not met. + if rule.Expiration == nil && rule.NoncurrentVersionExpiration == nil && + rule.Transitions == nil && rule.NoncurrentVersionTransitions == nil { + rule.Expiration = &s3.LifecycleExpiration{ExpiredObjectDeleteMarker: aws.Bool(false)} + } + rules = append(rules, rule) } @@ -2311,8 +2312,8 @@ func flattenAwsS3BucketReplicationConfiguration(r *s3.ReplicationConfiguration) m := make(map[string]interface{}) - if r.Role != nil && *r.Role != "" { - m["role"] = *r.Role + if r.Role != nil && aws.StringValue(r.Role) != "" { + m["role"] = aws.StringValue(r.Role) } rules := make([]interface{}, 0, len(r.Rules)) @@ -2321,18 +2322,18 @@ func flattenAwsS3BucketReplicationConfiguration(r *s3.ReplicationConfiguration) if v.Destination != nil { rd := make(map[string]interface{}) if v.Destination.Bucket != nil { - rd["bucket"] = *v.Destination.Bucket + rd["bucket"] = aws.StringValue(v.Destination.Bucket) } if v.Destination.StorageClass != nil { - rd["storage_class"] = *v.Destination.StorageClass + rd["storage_class"] = aws.StringValue(v.Destination.StorageClass) } if v.Destination.EncryptionConfiguration != nil { if v.Destination.EncryptionConfiguration.ReplicaKmsKeyID != nil { - rd["replica_kms_key_id"] = *v.Destination.EncryptionConfiguration.ReplicaKmsKeyID + rd["replica_kms_key_id"] = aws.StringValue(v.Destination.EncryptionConfiguration.ReplicaKmsKeyID) } } if v.Destination.Account != nil { - rd["account_id"] = *v.Destination.Account + rd["account_id"] = aws.StringValue(v.Destination.Account) } if v.Destination.AccessControlTranslation != nil { rdt := map[string]interface{}{ @@ -2340,30 +2341,30 @@ func flattenAwsS3BucketReplicationConfiguration(r *s3.ReplicationConfiguration) } rd["access_control_translation"] = []interface{}{rdt} } - t["destination"] = schema.NewSet(destinationHash, []interface{}{rd}) + t["destination"] = []interface{}{rd} } if v.ID != nil { - t["id"] = *v.ID + t["id"] = aws.StringValue(v.ID) } if v.Prefix != nil { - t["prefix"] = *v.Prefix + t["prefix"] = aws.StringValue(v.Prefix) } if v.Status != nil { - t["status"] = *v.Status + t["status"] = aws.StringValue(v.Status) } if vssc := v.SourceSelectionCriteria; vssc != nil { tssc := make(map[string]interface{}) if vssc.SseKmsEncryptedObjects != nil { tSseKms := make(map[string]interface{}) - if *vssc.SseKmsEncryptedObjects.Status == s3.SseKmsEncryptedObjectsStatusEnabled { + if aws.StringValue(vssc.SseKmsEncryptedObjects.Status) == s3.SseKmsEncryptedObjectsStatusEnabled { tSseKms["enabled"] = true - } else if *vssc.SseKmsEncryptedObjects.Status == s3.SseKmsEncryptedObjectsStatusDisabled { + } else if aws.StringValue(vssc.SseKmsEncryptedObjects.Status) == s3.SseKmsEncryptedObjectsStatusDisabled { tSseKms["enabled"] = false } - tssc["sse_kms_encrypted_objects"] = schema.NewSet(sourceSseKmsObjectsHash, []interface{}{tSseKms}) + tssc["sse_kms_encrypted_objects"] = []interface{}{tSseKms} } - t["source_selection_criteria"] = schema.NewSet(sourceSelectionCriteriaHash, []interface{}{tssc}) + t["source_selection_criteria"] = []interface{}{tssc} } if v.Priority != nil { @@ -2504,26 +2505,6 @@ func grantHash(v interface{}) int { return hashcode.String(buf.String()) } -func expirationHash(v interface{}) int { - var buf bytes.Buffer - m, ok := v.(map[string]interface{}) - - if !ok { - return 0 - } - - if v, ok := m["date"]; ok { - buf.WriteString(fmt.Sprintf("%s-", v.(string))) - } - if v, ok := m["days"]; ok { - buf.WriteString(fmt.Sprintf("%d-", v.(int))) - } - if v, ok := m["expired_object_delete_marker"]; ok { - buf.WriteString(fmt.Sprintf("%t-", v.(bool))) - } - return hashcode.String(buf.String()) -} - func transitionHash(v interface{}) int { var buf bytes.Buffer m, ok := v.(map[string]interface{}) @@ -2561,11 +2542,11 @@ func rulesHash(v interface{}) int { if v, ok := m["status"]; ok { buf.WriteString(fmt.Sprintf("%s-", v.(string))) } - if v, ok := m["destination"].(*schema.Set); ok && v.Len() > 0 { - buf.WriteString(fmt.Sprintf("%d-", destinationHash(v.List()[0]))) + if v, ok := m["destination"].([]interface{}); ok && len(v) > 0 && v[0] != nil { + buf.WriteString(fmt.Sprintf("%d-", destinationHash(v[0]))) } - if v, ok := m["source_selection_criteria"].(*schema.Set); ok && v.Len() > 0 && v.List()[0] != nil { - buf.WriteString(fmt.Sprintf("%d-", sourceSelectionCriteriaHash(v.List()[0]))) + if v, ok := m["source_selection_criteria"].([]interface{}); ok && len(v) > 0 && v[0] != nil { + buf.WriteString(fmt.Sprintf("%d-", sourceSelectionCriteriaHash(v[0]))) } if v, ok := m["priority"]; ok { buf.WriteString(fmt.Sprintf("%d-", v.(int))) @@ -2641,8 +2622,8 @@ func sourceSelectionCriteriaHash(v interface{}) int { return 0 } - if v, ok := m["sse_kms_encrypted_objects"].(*schema.Set); ok && v.Len() > 0 { - buf.WriteString(fmt.Sprintf("%d-", sourceSseKmsObjectsHash(v.List()[0]))) + if v, ok := m["sse_kms_encrypted_objects"].([]interface{}); ok && len(v) > 0 && v[0] != nil { + buf.WriteString(fmt.Sprintf("%d-", sourceSseKmsObjectsHash(v[0]))) } return hashcode.String(buf.String()) } diff --git a/aws/resource_aws_s3_bucket_analytics_configuration.go b/aws/resource_aws_s3_bucket_analytics_configuration.go index 0929e0a5fed..e50f771c73e 100644 --- a/aws/resource_aws_s3_bucket_analytics_configuration.go +++ b/aws/resource_aws_s3_bucket_analytics_configuration.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -50,6 +50,7 @@ func resourceAwsS3BucketAnalyticsConfiguration() *schema.Resource { Type: schema.TypeMap, Optional: true, AtLeastOneOf: filterAtLeastOneOfKeys, + Elem: &schema.Schema{Type: schema.TypeString}, }, }, }, diff --git a/aws/resource_aws_s3_bucket_analytics_configuration_test.go b/aws/resource_aws_s3_bucket_analytics_configuration_test.go index e08f0cbe9f0..5c3cc5568e4 100644 --- a/aws/resource_aws_s3_bucket_analytics_configuration_test.go +++ b/aws/resource_aws_s3_bucket_analytics_configuration_test.go @@ -10,9 +10,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSS3BucketAnalyticsConfiguration_basic(t *testing.T) { @@ -134,7 +134,7 @@ func TestAccAWSS3BucketAnalyticsConfiguration_WithFilter_Empty(t *testing.T) { Steps: []resource.TestStep{ { Config: testAccAWSS3BucketAnalyticsConfigurationWithEmptyFilter(rName, rName), - ExpectError: regexp.MustCompile(`config is invalid:`), + ExpectError: regexp.MustCompile(`one of .* must be specified`), }, }, }) @@ -365,7 +365,7 @@ func TestAccAWSS3BucketAnalyticsConfiguration_WithStorageClassAnalysis_Empty(t * Steps: []resource.TestStep{ { Config: testAccAWSS3BucketAnalyticsConfigurationWithEmptyStorageClassAnalysis(rName, rName), - ExpectError: regexp.MustCompile(`config is invalid:`), + ExpectError: regexp.MustCompile(`required field is not set`), }, }, }) diff --git a/aws/resource_aws_s3_bucket_inventory.go b/aws/resource_aws_s3_bucket_inventory.go index f503e3ff0f7..0eec3467790 100644 --- a/aws/resource_aws_s3_bucket_inventory.go +++ b/aws/resource_aws_s3_bucket_inventory.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsS3BucketInventory() *schema.Resource { diff --git a/aws/resource_aws_s3_bucket_inventory_test.go b/aws/resource_aws_s3_bucket_inventory_test.go index 960a0e67e1d..81701422a62 100644 --- a/aws/resource_aws_s3_bucket_inventory_test.go +++ b/aws/resource_aws_s3_bucket_inventory_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSS3BucketInventory_basic(t *testing.T) { diff --git a/aws/resource_aws_s3_bucket_metric.go b/aws/resource_aws_s3_bucket_metric.go index b4116535ce7..d367419ccc3 100644 --- a/aws/resource_aws_s3_bucket_metric.go +++ b/aws/resource_aws_s3_bucket_metric.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -36,10 +36,16 @@ func resourceAwsS3BucketMetric() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "prefix": { - Type: schema.TypeString, - Optional: true, + Type: schema.TypeString, + Optional: true, + AtLeastOneOf: filterAtLeastOneOfKeys, + }, + "tags": { + Type: schema.TypeMap, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + AtLeastOneOf: filterAtLeastOneOfKeys, }, - "tags": tagsSchema(), }, }, }, diff --git a/aws/resource_aws_s3_bucket_metric_test.go b/aws/resource_aws_s3_bucket_metric_test.go index 1affeb7896c..7b5ea0a4747 100644 --- a/aws/resource_aws_s3_bucket_metric_test.go +++ b/aws/resource_aws_s3_bucket_metric_test.go @@ -4,13 +4,14 @@ import ( "fmt" "log" "reflect" + "regexp" "sort" "testing" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" @@ -292,6 +293,8 @@ func TestAccAWSS3BucketMetric_basic(t *testing.T) { }) } +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/11813 +// Disallow Empty filter block func TestAccAWSS3BucketMetric_WithEmptyFilter(t *testing.T) { var conf s3.MetricsConfiguration rInt := acctest.RandInt() @@ -310,6 +313,7 @@ func TestAccAWSS3BucketMetric_WithEmptyFilter(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSS3BucketMetricsConfigExists(resourceName, &conf), ), + ExpectError: regexp.MustCompile(`one of .* must be specified`), }, }, }) diff --git a/aws/resource_aws_s3_bucket_notification.go b/aws/resource_aws_s3_bucket_notification.go index fd494a8f71e..fb6e34dd4ed 100644 --- a/aws/resource_aws_s3_bucket_notification.go +++ b/aws/resource_aws_s3_bucket_notification.go @@ -6,8 +6,8 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" diff --git a/aws/resource_aws_s3_bucket_notification_test.go b/aws/resource_aws_s3_bucket_notification_test.go index 2acba0841fc..a34748e30dc 100644 --- a/aws/resource_aws_s3_bucket_notification_test.go +++ b/aws/resource_aws_s3_bucket_notification_test.go @@ -7,9 +7,9 @@ import ( "testing" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" diff --git a/aws/resource_aws_s3_bucket_object.go b/aws/resource_aws_s3_bucket_object.go index fadd327d328..124bcc1e050 100644 --- a/aws/resource_aws_s3_bucket_object.go +++ b/aws/resource_aws_s3_bucket_object.go @@ -2,6 +2,7 @@ package aws import ( "bytes" + "context" "encoding/base64" "fmt" "io" @@ -14,8 +15,8 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/kms" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/mitchellh/go-homedir" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -454,7 +455,7 @@ func resourceAwsS3BucketObjectUpdate(d *schema.ResourceData, meta interface{}) e } } - if d.HasChange("object_lock_mode") || d.HasChange("object_lock_retain_until_date") { + if d.HasChanges("object_lock_mode", "object_lock_retain_until_date") { req := &s3.PutObjectRetentionInput{ Bucket: aws.String(bucket), Key: aws.String(key), @@ -525,7 +526,7 @@ func validateMetadataIsLowerCase(v interface{}, k string) (ws []string, errors [ return } -func resourceAwsS3BucketObjectCustomizeDiff(d *schema.ResourceDiff, meta interface{}) error { +func resourceAwsS3BucketObjectCustomizeDiff(_ context.Context, d *schema.ResourceDiff, meta interface{}) error { if d.HasChange("etag") { d.SetNewComputed("version_id") } diff --git a/aws/resource_aws_s3_bucket_object_test.go b/aws/resource_aws_s3_bucket_object_test.go index 097f17d2eba..091d3d75b8c 100644 --- a/aws/resource_aws_s3_bucket_object_test.go +++ b/aws/resource_aws_s3_bucket_object_test.go @@ -15,9 +15,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { diff --git a/aws/resource_aws_s3_bucket_policy.go b/aws/resource_aws_s3_bucket_policy.go index 89e7bd9dfe4..1c272f3d679 100644 --- a/aws/resource_aws_s3_bucket_policy.go +++ b/aws/resource_aws_s3_bucket_policy.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsS3BucketPolicy() *schema.Resource { diff --git a/aws/resource_aws_s3_bucket_policy_test.go b/aws/resource_aws_s3_bucket_policy_test.go index b223d1d4814..1cb04f7cf64 100644 --- a/aws/resource_aws_s3_bucket_policy_test.go +++ b/aws/resource_aws_s3_bucket_policy_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" awspolicy "github.com/jen20/awspolicyequivalence" ) diff --git a/aws/resource_aws_s3_bucket_public_access_block.go b/aws/resource_aws_s3_bucket_public_access_block.go index 4a5e33842f8..c4cd28e5d03 100644 --- a/aws/resource_aws_s3_bucket_public_access_block.go +++ b/aws/resource_aws_s3_bucket_public_access_block.go @@ -6,11 +6,11 @@ import ( "time" "github.com/aws/aws-sdk-go/service/s3control" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsS3BucketPublicAccessBlock() *schema.Resource { diff --git a/aws/resource_aws_s3_bucket_public_access_block_test.go b/aws/resource_aws_s3_bucket_public_access_block_test.go index 6387a3a1f13..ea9c3d222f9 100644 --- a/aws/resource_aws_s3_bucket_public_access_block_test.go +++ b/aws/resource_aws_s3_bucket_public_access_block_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSS3BucketPublicAccessBlock_basic(t *testing.T) { diff --git a/aws/resource_aws_s3_bucket_test.go b/aws/resource_aws_s3_bucket_test.go index 208255d9671..2541993941a 100644 --- a/aws/resource_aws_s3_bucket_test.go +++ b/aws/resource_aws_s3_bucket_test.go @@ -1,6 +1,7 @@ package aws import ( + "context" "encoding/json" "fmt" "log" @@ -14,12 +15,15 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/cloudformation" "github.com/aws/aws-sdk-go/service/s3" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -125,21 +129,18 @@ func testSweepS3Buckets(region string) error { } func testS3BucketRegion(conn *s3.S3, bucket string) (string, error) { - input := &s3.GetBucketLocationInput{ - Bucket: aws.String(bucket), - } - - output, err := conn.GetBucketLocation(input) - + region, err := s3manager.GetBucketRegionWithClient(context.Background(), conn, bucket, func(r *request.Request) { + // By default, GetBucketRegion forces virtual host addressing, which + // is not compatible with many non-AWS implementations. Instead, pass + // the provider s3_force_path_style configuration, which defaults to + // false, but allows override. + r.Config.S3ForcePathStyle = conn.Config.S3ForcePathStyle + }) if err != nil { return "", err } - if output == nil || output.LocationConstraint == nil { - return "us-east-1", nil - } - - return aws.StringValue(output.LocationConstraint), nil + return region, nil } func testS3BucketObjectLockEnabled(conn *s3.S3, bucket string) (bool, error) { @@ -434,26 +435,6 @@ func TestAccAWSS3Bucket_generatedName(t *testing.T) { }) } -func TestAccAWSS3Bucket_region(t *testing.T) { - resourceName := "aws_s3_bucket.test" - rName := acctest.RandomWithPrefix("tf-acc-test") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSS3BucketDestroy, - Steps: []resource.TestStep{ - { - Config: testAccAWSS3BucketConfigWithRegion(rName), - Check: resource.ComposeTestCheckFunc( - testAccCheckAWSS3BucketExists(resourceName), - resource.TestCheckResourceAttr(resourceName, "region", testAccGetRegion()), - ), - }, - }, - }) -} - func TestAccAWSS3Bucket_acceleration(t *testing.T) { bucketName := acctest.RandomWithPrefix("tf-test-bucket") resourceName := "aws_s3_bucket.bucket" @@ -530,24 +511,6 @@ func TestAccAWSS3Bucket_Policy(t *testing.T) { partition := testAccGetPartition() resourceName := "aws_s3_bucket.bucket" - checkFn := func(s []*terraform.InstanceState) error { - // Expect 2: bucket + policy - if len(s) != 2 { - return fmt.Errorf("expected 2 states: %#v", s) - } - bucketState, policyState := s[0], s[1] - - if bucketState.ID != bucketName { - return fmt.Errorf("expected bucket of ID %s, %s received", bucketName, bucketState.ID) - } - - if policyState.ID != bucketName { - return fmt.Errorf("expected policy of ID %s, %s received", bucketName, bucketState.ID) - } - - return nil - } - resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, @@ -561,9 +524,20 @@ func TestAccAWSS3Bucket_Policy(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: checkFn, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "acl", + "force_destroy", + "grant", + // NOTE: Prior to Terraform AWS Provider 3.0, this attribute did not import correctly either. + // The Read function does not require GetBucketPolicy, if the argument is not configured. + // Rather than introduce that breaking change as well with 3.0, instead we leave the + // current Read behavior and note this will be deprecated in a later 3.x release along + // with other inline policy attributes across the provider. + "policy", + }, }, { Config: testAccAWSS3BucketConfig_Basic(bucketName), @@ -621,10 +595,9 @@ func TestAccAWSS3Bucket_UpdateGrant(t *testing.T) { resourceName := "aws_s3_bucket.bucket" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSS3BucketDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSS3BucketDestroy, Steps: []resource.TestStep{ { Config: testAccAWSS3BucketConfigWithGrants(bucketName), @@ -1203,10 +1176,9 @@ func TestAccAWSS3Bucket_LifecycleBasic(t *testing.T) { resourceName := "aws_s3_bucket.bucket" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSS3BucketDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSS3BucketDestroy, Steps: []resource.TestStep{ { Config: testAccAWSS3BucketConfigWithLifecycle(bucketName), @@ -1214,32 +1186,44 @@ func TestAccAWSS3Bucket_LifecycleBasic(t *testing.T) { testAccCheckAWSS3BucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.id", "id1"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.prefix", "path1/"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.2613713285.days", "365"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.2613713285.date", ""), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.2613713285.expired_object_delete_marker", "false"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.2000431762.date", ""), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.2000431762.days", "30"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.2000431762.storage_class", "STANDARD_IA"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.3601168188.date", ""), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.3601168188.days", "60"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.3601168188.storage_class", "INTELLIGENT_TIERING"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.3854926587.date", ""), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.3854926587.days", "90"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.3854926587.storage_class", "ONEZONE_IA"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.962205413.date", ""), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.962205413.days", "120"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.962205413.storage_class", "GLACIER"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.1571523406.date", ""), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.1571523406.days", "210"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.transition.1571523406.storage_class", "DEEP_ARCHIVE"), + resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.0.days", "365"), + resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.0.date", ""), + resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.0.expired_object_delete_marker", "false"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "lifecycle_rule.0.transition.*", map[string]string{ + "date": "", + "days": "30", + "storage_class": "STANDARD_IA", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "lifecycle_rule.0.transition.*", map[string]string{ + "date": "", + "days": "60", + "storage_class": "INTELLIGENT_TIERING", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "lifecycle_rule.0.transition.*", map[string]string{ + "date": "", + "days": "90", + "storage_class": "ONEZONE_IA", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "lifecycle_rule.0.transition.*", map[string]string{ + "date": "", + "days": "120", + "storage_class": "GLACIER", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "lifecycle_rule.0.transition.*", map[string]string{ + "date": "", + "days": "210", + "storage_class": "DEEP_ARCHIVE", + }), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.id", "id2"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.prefix", "path2/"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.expiration.2855832418.date", "2016-01-12"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.expiration.2855832418.days", "0"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.expiration.2855832418.expired_object_delete_marker", "false"), + resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.expiration.0.date", "2016-01-12"), + resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.expiration.0.days", "0"), + resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.expiration.0.expired_object_delete_marker", "false"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.2.id", "id3"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.2.prefix", "path3/"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.2.transition.460947558.days", "0"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "lifecycle_rule.2.transition.*", map[string]string{ + "days": "0", + }), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.3.id", "id4"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.3.prefix", "path4/"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.3.tags.tagKey", "tagValue"), @@ -1247,12 +1231,16 @@ func TestAccAWSS3Bucket_LifecycleBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.4.id", "id5"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.4.tags.tagKey", "tagValue"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.4.tags.terraform", "hashicorp"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.4.transition.460947558.days", "0"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.4.transition.460947558.storage_class", "GLACIER"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "lifecycle_rule.4.transition.*", map[string]string{ + "days": "0", + "storage_class": "GLACIER", + }), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.5.id", "id6"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.5.tags.tagKey", "tagValue"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.5.transition.460947558.days", "0"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.5.transition.460947558.storage_class", "GLACIER"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "lifecycle_rule.5.transition.*", map[string]string{ + "days": "0", + "storage_class": "GLACIER", + }), ), }, { @@ -1268,19 +1256,25 @@ func TestAccAWSS3Bucket_LifecycleBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.id", "id1"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.prefix", "path1/"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.enabled", "true"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.noncurrent_version_expiration.80908210.days", "365"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.noncurrent_version_transition.1377917700.days", "30"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.noncurrent_version_transition.1377917700.storage_class", "STANDARD_IA"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.noncurrent_version_transition.2528035817.days", "60"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.noncurrent_version_transition.2528035817.storage_class", "GLACIER"), + resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.noncurrent_version_expiration.0.days", "365"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "lifecycle_rule.0.noncurrent_version_transition.*", map[string]string{ + "days": "30", + "storage_class": "STANDARD_IA", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "lifecycle_rule.0.noncurrent_version_transition.*", map[string]string{ + "days": "60", + "storage_class": "GLACIER", + }), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.id", "id2"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.prefix", "path2/"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.noncurrent_version_expiration.80908210.days", "365"), + resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.1.noncurrent_version_expiration.0.days", "365"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.2.id", "id3"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.2.prefix", "path3/"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.2.noncurrent_version_transition.3732708140.days", "0"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.2.noncurrent_version_transition.3732708140.storage_class", "GLACIER"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "lifecycle_rule.2.noncurrent_version_transition.*", map[string]string{ + "days": "0", + "storage_class": "GLACIER", + }), ), }, { @@ -1298,10 +1292,9 @@ func TestAccAWSS3Bucket_LifecycleExpireMarkerOnly(t *testing.T) { resourceName := "aws_s3_bucket.bucket" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSS3BucketDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSS3BucketDestroy, Steps: []resource.TestStep{ { Config: testAccAWSS3BucketConfigWithLifecycleExpireMarker(bucketName), @@ -1309,9 +1302,9 @@ func TestAccAWSS3Bucket_LifecycleExpireMarkerOnly(t *testing.T) { testAccCheckAWSS3BucketExists(resourceName), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.id", "id1"), resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.prefix", "path1/"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.3591068768.days", "0"), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.3591068768.date", ""), - resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.3591068768.expired_object_delete_marker", "true"), + resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.0.days", "0"), + resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.0.date", ""), + resource.TestCheckResourceAttr(resourceName, "lifecycle_rule.0.expiration.0.expired_object_delete_marker", "true"), ), }, { @@ -1937,6 +1930,60 @@ func TestAccAWSS3Bucket_ReplicationSchemaV2(t *testing.T) { }) } +func TestAccAWSS3Bucket_SameRegionReplicationSchemaV2(t *testing.T) { + resourceName := "aws_s3_bucket.bucket" + rName := acctest.RandomWithPrefix("tf-acc-test") + destinationResourceName := "aws_s3_bucket.destination" + rNameDestination := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSS3BucketDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSS3BucketConfigSameRegionReplicationWithV2ConfigurationNoTags(rName, rNameDestination), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSS3BucketExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "replication_configuration.#", "1"), + testAccCheckResourceAttrGlobalARN(resourceName, "replication_configuration.0.role", "iam", fmt.Sprintf("role/%s", rName)), + resource.TestCheckResourceAttr(resourceName, "replication_configuration.0.rules.#", "1"), + testAccCheckAWSS3BucketExists(destinationResourceName), + testAccCheckAWSS3BucketReplicationRules( + resourceName, + testAccProviderFunc, + []*s3.ReplicationRule{ + { + ID: aws.String("testid"), + Destination: &s3.Destination{ + Bucket: aws.String(fmt.Sprintf("arn:%s:s3:::%s", testAccGetPartition(), rNameDestination)), + StorageClass: aws.String(s3.ObjectStorageClassStandard), + }, + Status: aws.String(s3.ReplicationRuleStatusEnabled), + Filter: &s3.ReplicationRuleFilter{ + Prefix: aws.String("testprefix"), + }, + Priority: aws.Int64(0), + DeleteMarkerReplication: &s3.DeleteMarkerReplication{ + Status: aws.String(s3.DeleteMarkerReplicationStatusDisabled), + }, + }, + }, + ), + ), + }, + { + Config: testAccAWSS3BucketConfigSameRegionReplicationWithV2ConfigurationNoTags(rName, rNameDestination), + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{ + "force_destroy", "acl"}, + }, + }, + }) +} + func TestAccAWSS3Bucket_objectLock(t *testing.T) { bucketName := acctest.RandomWithPrefix("tf-test-bucket") resourceName := "aws_s3_bucket.arbitrary" @@ -2836,21 +2883,15 @@ func testAccCheckAWSS3BucketReplicationRules(n string, providerF func() *schema. func testAccCheckAWSS3BucketUpdateGrantSingle(resourceName string) func(s *terraform.State) error { return func(s *terraform.State) error { - id := s.RootModule().Resources["data.aws_canonical_user_id.current"].Primary.ID - gh := fmt.Sprintf("grant.%v", grantHash(map[string]interface{}{ - "id": id, - "type": "CanonicalUser", - "uri": "", - "permissions": schema.NewSet( - schema.HashString, - []interface{}{"FULL_CONTROL", "WRITE"}, - ), - })) for _, t := range []resource.TestCheckFunc{ - resource.TestCheckResourceAttr(resourceName, gh+".permissions.#", "2"), - resource.TestCheckResourceAttr(resourceName, gh+".permissions.3535167073", "FULL_CONTROL"), - resource.TestCheckResourceAttr(resourceName, gh+".permissions.2319431919", "WRITE"), - resource.TestCheckResourceAttr(resourceName, gh+".type", "CanonicalUser"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "grant.*", map[string]string{ + "permissions.#": "2", + }), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "grant.*.permissions.*", "FULL_CONTROL"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "grant.*.permissions.*", "WRITE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "grant.*", map[string]string{ + "type": "CanonicalUser", + }), } { if err := t(s); err != nil { return err @@ -2882,13 +2923,19 @@ func testAccCheckAWSS3BucketUpdateGrantMulti(resourceName string) func(s *terraf ), })) for _, t := range []resource.TestCheckFunc{ + // TODO TypeSet Check to differentiate between sets resource.TestCheckResourceAttr(resourceName, gh1+".permissions.#", "1"), - resource.TestCheckResourceAttr(resourceName, gh1+".permissions.2931993811", "READ"), - resource.TestCheckResourceAttr(resourceName, gh1+".type", "CanonicalUser"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "grant.*.permissions.*", "READ"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "grant.*", map[string]string{ + "type": "CanonicalUser", + }), + // TODO TypeSet Check to differentiate between sets resource.TestCheckResourceAttr(resourceName, gh2+".permissions.#", "1"), - resource.TestCheckResourceAttr(resourceName, gh2+".permissions.1600971645", "READ_ACP"), - resource.TestCheckResourceAttr(resourceName, gh2+".type", "Group"), - resource.TestCheckResourceAttr(resourceName, gh2+".uri", "http://acs.amazonaws.com/groups/s3/LogDelivery"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "grant.*.permissions.*", "READ_ACP"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "grant.*", map[string]string{ + "type": "Group", + "uri": "http://acs.amazonaws.com/groups/s3/LogDelivery", + }), } { if err := t(s); err != nil { return err @@ -3058,17 +3105,6 @@ resource "aws_s3_bucket" "bucket6" { `, randInt) } -func testAccAWSS3BucketConfigWithRegion(bucketName string) string { - return fmt.Sprintf(` -data "aws_region" "current" {} - -resource "aws_s3_bucket" "test" { - bucket = %[1]q - region = data.aws_region.current.name -} -`, bucketName) -} - func testAccAWSS3BucketWebsiteConfig(bucketName string) string { return fmt.Sprintf(` resource "aws_s3_bucket" "bucket" { @@ -3621,7 +3657,7 @@ POLICY } resource "aws_s3_bucket" "destination" { - provider = "aws.alternate" + provider = "awsalternate" bucket = "tf-test-bucket-destination-%[1]d" versioning { @@ -3674,7 +3710,7 @@ resource "aws_s3_bucket" "bucket" { func testAccAWSS3BucketConfigReplicationWithSseKmsEncryptedObjects(randInt int) string { return testAccAWSS3BucketConfigReplicationBasic(randInt) + fmt.Sprintf(` resource "aws_kms_key" "replica" { - provider = "aws.alternate" + provider = "awsalternate" description = "TF Acceptance Test S3 repl KMS key" deletion_window_in_days = 7 } @@ -3781,7 +3817,7 @@ func testAccAWSS3BucketConfigReplicationWithSseKmsEncryptedObjectsAndAccessContr data "aws_caller_identity" "current" {} resource "aws_kms_key" "replica" { - provider = "aws.alternate" + provider = "awsalternate" description = "TF Acceptance Test S3 repl KMS key" deletion_window_in_days = 7 } @@ -3898,6 +3934,44 @@ resource "aws_s3_bucket" "bucket" { `, randInt) } +func testAccAWSS3BucketConfigSameRegionReplicationWithV2ConfigurationNoTags(rName, rNameDestination string) string { + return composeConfig(testAccAWSS3BucketReplicationConfig_iamPolicy(rName), fmt.Sprintf(` +resource "aws_s3_bucket" "bucket" { + bucket = %[1]q + acl = "private" + + versioning { + enabled = true + } + + replication_configuration { + role = "${aws_iam_role.test.arn}" + rules { + id = "testid" + status = "Enabled" + + filter { + prefix = "testprefix" + } + + destination { + bucket = "${aws_s3_bucket.destination.arn}" + storage_class = "STANDARD" + } + } + } +} + +resource "aws_s3_bucket" "destination" { + bucket = %[2]q + + versioning { + enabled = true + } +} +`, rName, rNameDestination)) +} + func testAccAWSS3BucketConfigReplicationWithV2ConfigurationNoTags(randInt int) string { return testAccAWSS3BucketConfigReplicationBasic(randInt) + fmt.Sprintf(` resource "aws_s3_bucket" "bucket" { @@ -4092,6 +4166,28 @@ resource "aws_s3_bucket" "bucket" { `, bucketName) } +func testAccAWSS3BucketReplicationConfig_iamPolicy(rName string) string { + return fmt.Sprintf(` +resource "aws_iam_role" "test" { + name = %[1]q + + assume_role_policy = <= 7 && value <= 30 { - return - } - errors = append(errors, fmt.Errorf("%q must be 0 or between 7 and 30", k)) - return - }, + ValidateFunc: validation.Any( + validation.IntBetween(7, 30), + validation.IntInSlice([]int{0}), + ), }, "rotation_enabled": { - Type: schema.TypeBool, - Computed: true, + Deprecated: "Use the aws_secretsmanager_secret_rotation resource instead", + Type: schema.TypeBool, + Computed: true, }, "rotation_lambda_arn": { - Type: schema.TypeString, - Optional: true, + Deprecated: "Use the aws_secretsmanager_secret_rotation resource instead", + Type: schema.TypeString, + Optional: true, + Computed: true, }, "rotation_rules": { - Type: schema.TypeList, - Optional: true, - MaxItems: 1, + Deprecated: "Use the aws_secretsmanager_secret_rotation resource instead", + Type: schema.TypeList, + Computed: true, + Optional: true, + MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "automatically_after_days": { @@ -130,7 +130,7 @@ func resourceAwsSecretsManagerSecretCreate(d *schema.ResourceData, meta interfac // Retry for secret recreation after deletion var output *secretsmanager.CreateSecretOutput - err := resource.Retry(2*time.Minute, func() *resource.RetryError { + err := resource.Retry(waiter.DeletionPropagationTimeout, func() *resource.RetryError { var err error output, err = conn.CreateSecret(input) // Temporarily retry on these errors to support immediate secret recreation: @@ -148,7 +148,7 @@ func resourceAwsSecretsManagerSecretCreate(d *schema.ResourceData, meta interfac output, err = conn.CreateSecret(input) } if err != nil { - return fmt.Errorf("error creating Secrets Manager Secret: %s", err) + return fmt.Errorf("error creating Secrets Manager Secret: %w", err) } d.SetId(aws.StringValue(output.ARN)) @@ -159,10 +159,23 @@ func resourceAwsSecretsManagerSecretCreate(d *schema.ResourceData, meta interfac SecretId: aws.String(d.Id()), } - log.Printf("[DEBUG] Setting Secrets Manager Secret resource policy; %s", input) - _, err := conn.PutResourcePolicy(input) + err := resource.Retry(iamwaiter.PropagationTimeout, func() *resource.RetryError { + var err error + _, err = conn.PutResourcePolicy(input) + if isAWSErr(err, secretsmanager.ErrCodeMalformedPolicyDocumentException, + "This resource policy contains an unsupported principal") { + return resource.RetryableError(err) + } + if err != nil { + return resource.NonRetryableError(err) + } + return nil + }) + if isResourceTimeoutError(err) { + _, err = conn.PutResourcePolicy(input) + } if err != nil { - return fmt.Errorf("error setting Secrets Manager Secret %q policy: %s", d.Id(), err) + return fmt.Errorf("error setting Secrets Manager Secret %q policy: %w", d.Id(), err) } } @@ -189,7 +202,7 @@ func resourceAwsSecretsManagerSecretCreate(d *schema.ResourceData, meta interfac _, err = conn.RotateSecret(input) } if err != nil { - return fmt.Errorf("error enabling Secrets Manager Secret %q rotation: %s", d.Id(), err) + return fmt.Errorf("error enabling Secrets Manager Secret %q rotation: %w", d.Id(), err) } } @@ -212,7 +225,7 @@ func resourceAwsSecretsManagerSecretRead(d *schema.ResourceData, meta interface{ d.SetId("") return nil } - return fmt.Errorf("error reading Secrets Manager Secret: %s", err) + return fmt.Errorf("error reading Secrets Manager Secret: %w", err) } d.Set("arn", output.ARN) @@ -226,13 +239,13 @@ func resourceAwsSecretsManagerSecretRead(d *schema.ResourceData, meta interface{ log.Printf("[DEBUG] Reading Secrets Manager Secret policy: %s", pIn) pOut, err := conn.GetResourcePolicy(pIn) if err != nil { - return fmt.Errorf("error reading Secrets Manager Secret policy: %s", err) + return fmt.Errorf("error reading Secrets Manager Secret policy: %w", err) } if pOut.ResourcePolicy != nil { policy, err := structure.NormalizeJsonString(aws.StringValue(pOut.ResourcePolicy)) if err != nil { - return fmt.Errorf("policy contains an invalid JSON: %s", err) + return fmt.Errorf("policy contains an invalid JSON: %w", err) } d.Set("policy", policy) } @@ -242,7 +255,7 @@ func resourceAwsSecretsManagerSecretRead(d *schema.ResourceData, meta interface{ if aws.BoolValue(output.RotationEnabled) { d.Set("rotation_lambda_arn", output.RotationLambdaARN) if err := d.Set("rotation_rules", flattenSecretsManagerRotationRules(output.RotationRules)); err != nil { - return fmt.Errorf("error setting rotation_rules: %s", err) + return fmt.Errorf("error setting rotation_rules: %w", err) } } else { d.Set("rotation_lambda_arn", "") @@ -250,7 +263,7 @@ func resourceAwsSecretsManagerSecretRead(d *schema.ResourceData, meta interface{ } if err := d.Set("tags", keyvaluetags.SecretsmanagerKeyValueTags(output.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { - return fmt.Errorf("error setting tags: %s", err) + return fmt.Errorf("error setting tags: %w", err) } return nil @@ -259,7 +272,7 @@ func resourceAwsSecretsManagerSecretRead(d *schema.ResourceData, meta interface{ func resourceAwsSecretsManagerSecretUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).secretsmanagerconn - if d.HasChange("description") || d.HasChange("kms_key_id") { + if d.HasChanges("description", "kms_key_id") { input := &secretsmanager.UpdateSecretInput{ Description: aws.String(d.Get("description").(string)), SecretId: aws.String(d.Id()), @@ -272,7 +285,7 @@ func resourceAwsSecretsManagerSecretUpdate(d *schema.ResourceData, meta interfac log.Printf("[DEBUG] Updating Secrets Manager Secret: %s", input) _, err := conn.UpdateSecret(input) if err != nil { - return fmt.Errorf("error updating Secrets Manager Secret: %s", err) + return fmt.Errorf("error updating Secrets Manager Secret: %w", err) } } @@ -280,32 +293,46 @@ func resourceAwsSecretsManagerSecretUpdate(d *schema.ResourceData, meta interfac if v, ok := d.GetOk("policy"); ok && v.(string) != "" { policy, err := structure.NormalizeJsonString(v.(string)) if err != nil { - return fmt.Errorf("policy contains an invalid JSON: %s", err) + return fmt.Errorf("policy contains an invalid JSON: %w", err) } input := &secretsmanager.PutResourcePolicyInput{ ResourcePolicy: aws.String(policy), SecretId: aws.String(d.Id()), } - log.Printf("[DEBUG] Setting Secrets Manager Secret resource policy; %s", input) - _, err = conn.PutResourcePolicy(input) + log.Printf("[DEBUG] Setting Secrets Manager Secret resource policy; %#v", input) + err = resource.Retry(iamwaiter.PropagationTimeout, func() *resource.RetryError { + var err error + _, err = conn.PutResourcePolicy(input) + if isAWSErr(err, secretsmanager.ErrCodeMalformedPolicyDocumentException, + "This resource policy contains an unsupported principal") { + return resource.RetryableError(err) + } + if err != nil { + return resource.NonRetryableError(err) + } + return nil + }) + if isResourceTimeoutError(err) { + _, err = conn.PutResourcePolicy(input) + } if err != nil { - return fmt.Errorf("error setting Secrets Manager Secret %q policy: %s", d.Id(), err) + return fmt.Errorf("error setting Secrets Manager Secret %q policy: %w", d.Id(), err) } } else { input := &secretsmanager.DeleteResourcePolicyInput{ SecretId: aws.String(d.Id()), } - log.Printf("[DEBUG] Removing Secrets Manager Secret policy: %s", input) + log.Printf("[DEBUG] Removing Secrets Manager Secret policy: %#v", input) _, err := conn.DeleteResourcePolicy(input) if err != nil { - return fmt.Errorf("error removing Secrets Manager Secret %q policy: %s", d.Id(), err) + return fmt.Errorf("error removing Secrets Manager Secret %q policy: %w", d.Id(), err) } } } - if d.HasChange("rotation_lambda_arn") || d.HasChange("rotation_rules") { + if d.HasChanges("rotation_lambda_arn", "rotation_rules") { if v, ok := d.GetOk("rotation_lambda_arn"); ok && v.(string) != "" { input := &secretsmanager.RotateSecretInput{ RotationLambdaARN: aws.String(v.(string)), @@ -329,7 +356,7 @@ func resourceAwsSecretsManagerSecretUpdate(d *schema.ResourceData, meta interfac _, err = conn.RotateSecret(input) } if err != nil { - return fmt.Errorf("error updating Secrets Manager Secret %q rotation: %s", d.Id(), err) + return fmt.Errorf("error updating Secrets Manager Secret %q rotation: %w", d.Id(), err) } } else { input := &secretsmanager.CancelRotateSecretInput{ @@ -339,7 +366,7 @@ func resourceAwsSecretsManagerSecretUpdate(d *schema.ResourceData, meta interfac log.Printf("[DEBUG] Cancelling Secrets Manager Secret rotation: %s", input) _, err := conn.CancelRotateSecret(input) if err != nil { - return fmt.Errorf("error cancelling Secret Manager Secret %q rotation: %s", d.Id(), err) + return fmt.Errorf("error cancelling Secret Manager Secret %q rotation: %w", d.Id(), err) } } } @@ -347,7 +374,7 @@ func resourceAwsSecretsManagerSecretUpdate(d *schema.ResourceData, meta interfac if d.HasChange("tags") { o, n := d.GetChange("tags") if err := keyvaluetags.SecretsmanagerUpdateTags(conn, d.Id(), o, n); err != nil { - return fmt.Errorf("error updating tags: %s", err) + return fmt.Errorf("error updating tags: %w", err) } } @@ -374,34 +401,8 @@ func resourceAwsSecretsManagerSecretDelete(d *schema.ResourceData, meta interfac if isAWSErr(err, secretsmanager.ErrCodeResourceNotFoundException, "") { return nil } - return fmt.Errorf("error deleting Secrets Manager Secret: %s", err) + return fmt.Errorf("error deleting Secrets Manager Secret: %w", err) } return nil } - -func expandSecretsManagerRotationRules(l []interface{}) *secretsmanager.RotationRulesType { - if len(l) == 0 { - return nil - } - - m := l[0].(map[string]interface{}) - - rules := &secretsmanager.RotationRulesType{ - AutomaticallyAfterDays: aws.Int64(int64(m["automatically_after_days"].(int))), - } - - return rules -} - -func flattenSecretsManagerRotationRules(rules *secretsmanager.RotationRulesType) []interface{} { - if rules == nil { - return []interface{}{} - } - - m := map[string]interface{}{ - "automatically_after_days": int(aws.Int64Value(rules.AutomaticallyAfterDays)), - } - - return []interface{}{m} -} diff --git a/aws/resource_aws_secretsmanager_secret_rotation.go b/aws/resource_aws_secretsmanager_secret_rotation.go new file mode 100644 index 00000000000..21f2da3d451 --- /dev/null +++ b/aws/resource_aws_secretsmanager_secret_rotation.go @@ -0,0 +1,218 @@ +package aws + +import ( + "fmt" + "log" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/secretsmanager" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func resourceAwsSecretsManagerSecretRotation() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsSecretsManagerSecretRotationCreate, + Read: resourceAwsSecretsManagerSecretRotationRead, + Update: resourceAwsSecretsManagerSecretRotationUpdate, + Delete: resourceAwsSecretsManagerSecretRotationDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "secret_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "rotation_enabled": { + Type: schema.TypeBool, + Computed: true, + }, + "rotation_lambda_arn": { + Type: schema.TypeString, + Required: true, + }, + "rotation_rules": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "automatically_after_days": { + Type: schema.TypeInt, + Required: true, + }, + }, + }, + }, + "tags": tagsSchema(), + }, + } +} + +func resourceAwsSecretsManagerSecretRotationCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).secretsmanagerconn + secretID := d.Get("secret_id").(string) + + if v, ok := d.GetOk("rotation_lambda_arn"); ok && v.(string) != "" { + input := &secretsmanager.RotateSecretInput{ + RotationLambdaARN: aws.String(v.(string)), + RotationRules: expandSecretsManagerRotationRules(d.Get("rotation_rules").([]interface{})), + SecretId: aws.String(secretID), + } + + log.Printf("[DEBUG] Enabling Secrets Manager Secret rotation: %s", input) + err := resource.Retry(1*time.Minute, func() *resource.RetryError { + output, err := conn.RotateSecret(input) + if err != nil { + // AccessDeniedException: Secrets Manager cannot invoke the specified Lambda function. + if isAWSErr(err, "AccessDeniedException", "") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + + d.SetId(aws.StringValue(output.ARN)) + + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.RotateSecret(input) + } + + if err != nil { + return fmt.Errorf("error enabling Secrets Manager Secret %q rotation: %s", d.Id(), err) + } + } + + return resourceAwsSecretsManagerSecretRotationRead(d, meta) +} + +func resourceAwsSecretsManagerSecretRotationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).secretsmanagerconn + + input := &secretsmanager.DescribeSecretInput{ + SecretId: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Reading Secrets Manager Secret Rotation: %s", input) + output, err := conn.DescribeSecret(input) + if err != nil { + if isAWSErr(err, secretsmanager.ErrCodeResourceNotFoundException, "") { + log.Printf("[WARN] Secrets Manager Secret Rotation %q not found - removing from state", d.Id()) + d.SetId("") + return nil + } + return fmt.Errorf("error reading Secrets Manager Secret Rotation: %s", err) + } + + d.Set("secret_id", d.Id()) + d.Set("rotation_enabled", output.RotationEnabled) + + if aws.BoolValue(output.RotationEnabled) { + d.Set("rotation_lambda_arn", output.RotationLambdaARN) + if err := d.Set("rotation_rules", flattenSecretsManagerRotationRules(output.RotationRules)); err != nil { + return fmt.Errorf("error setting rotation_rules: %s", err) + } + } else { + d.Set("rotation_lambda_arn", "") + d.Set("rotation_rules", []interface{}{}) + } + + return nil +} + +func resourceAwsSecretsManagerSecretRotationUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).secretsmanagerconn + secretID := d.Get("secret_id").(string) + + if d.HasChanges("rotation_lambda_arn", "rotation_rules") { + if v, ok := d.GetOk("rotation_lambda_arn"); ok && v.(string) != "" { + input := &secretsmanager.RotateSecretInput{ + RotationLambdaARN: aws.String(v.(string)), + RotationRules: expandSecretsManagerRotationRules(d.Get("rotation_rules").([]interface{})), + SecretId: aws.String(secretID), + } + + log.Printf("[DEBUG] Enabling Secrets Manager Secret Rotation: %s", input) + err := resource.Retry(1*time.Minute, func() *resource.RetryError { + _, err := conn.RotateSecret(input) + if err != nil { + // AccessDeniedException: Secrets Manager cannot invoke the specified Lambda function. + if isAWSErr(err, "AccessDeniedException", "") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.RotateSecret(input) + } + + if err != nil { + return fmt.Errorf("error updating Secrets Manager Secret Rotation %q : %s", d.Id(), err) + } + } else { + input := &secretsmanager.CancelRotateSecretInput{ + SecretId: aws.String(d.Id()), + } + + log.Printf("[DEBUG] Cancelling Secrets Manager Secret Rotation: %s", input) + _, err := conn.CancelRotateSecret(input) + if err != nil { + return fmt.Errorf("error cancelling Secret Manager Secret Rotation %q : %s", d.Id(), err) + } + } + } + + return resourceAwsSecretsManagerSecretRotationRead(d, meta) +} + +func resourceAwsSecretsManagerSecretRotationDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).secretsmanagerconn + secretID := d.Get("secret_id").(string) + + input := &secretsmanager.CancelRotateSecretInput{ + SecretId: aws.String(secretID), + } + + log.Printf("[DEBUG] Deleting Secrets Manager Rotation: %s", input) + _, err := conn.CancelRotateSecret(input) + if err != nil { + return fmt.Errorf("error cancelling Secret Manager Secret %q rotation: %s", d.Id(), err) + } + + return nil +} + +func expandSecretsManagerRotationRules(l []interface{}) *secretsmanager.RotationRulesType { + if len(l) == 0 { + return nil + } + + m := l[0].(map[string]interface{}) + + rules := &secretsmanager.RotationRulesType{ + AutomaticallyAfterDays: aws.Int64(int64(m["automatically_after_days"].(int))), + } + + return rules +} + +func flattenSecretsManagerRotationRules(rules *secretsmanager.RotationRulesType) []interface{} { + if rules == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "automatically_after_days": int(aws.Int64Value(rules.AutomaticallyAfterDays)), + } + + return []interface{}{m} +} diff --git a/aws/resource_aws_secretsmanager_secret_rotation_test.go b/aws/resource_aws_secretsmanager_secret_rotation_test.go new file mode 100644 index 00000000000..b323f111d74 --- /dev/null +++ b/aws/resource_aws_secretsmanager_secret_rotation_test.go @@ -0,0 +1,169 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/secretsmanager" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccAwsSecretsManagerSecretRotation_basic(t *testing.T) { + var secret secretsmanager.DescribeSecretOutput + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_secretsmanager_secret_rotation.test" + lambdaFunctionResourceName := "aws_lambda_function.test1" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSSecretsManager(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsSecretsManagerSecretRotationDestroy, + Steps: []resource.TestStep{ + // Test creating secret rotation resource + { + Config: testAccAwsSecretsManagerSecretRotationConfig(rName, 7), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsSecretsManagerSecretRotationExists(resourceName, &secret), + resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), + resource.TestCheckResourceAttrPair(resourceName, "rotation_lambda_arn", lambdaFunctionResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "rotation_rules.#", "1"), + resource.TestCheckResourceAttr(resourceName, "rotation_rules.0.automatically_after_days", "7"), + ), + }, + // Test updating rotation + // We need a valid rotation function for this testing + // InvalidRequestException: A previous rotation isn’t complete. That rotation will be reattempted. + /* + { + Config: testAccAwsSecretsManagerSecretConfig_Updated(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsSecretsManagerSecretRotationExists(resourceName, &secret), + resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), + resource.TestMatchResourceAttr(resourceName, "rotation_lambda_arn", regexp.MustCompile(fmt.Sprintf("^arn:[^:]+:lambda:[^:]+:[^:]+:function:%s-2$", rName))), + ), + }, + */ + // Test importing secret rotation + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckAwsSecretsManagerSecretRotationDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).secretsmanagerconn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_secretsmanager_secret_rotation" { + continue + } + + input := &secretsmanager.DescribeSecretInput{ + SecretId: aws.String(rs.Primary.ID), + } + + output, err := conn.DescribeSecret(input) + + if err != nil { + if isAWSErr(err, secretsmanager.ErrCodeResourceNotFoundException, "") { + continue + } + return err + } + + if output != nil && aws.BoolValue(output.RotationEnabled) { + return fmt.Errorf("Secret rotation for %q still enabled", rs.Primary.ID) + } + } + + return nil +} + +func testAccCheckAwsSecretsManagerSecretRotationExists(resourceName string, secret *secretsmanager.DescribeSecretOutput) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return fmt.Errorf("Not found: %s", resourceName) + } + + conn := testAccProvider.Meta().(*AWSClient).secretsmanagerconn + input := &secretsmanager.DescribeSecretInput{ + SecretId: aws.String(rs.Primary.ID), + } + + output, err := conn.DescribeSecret(input) + + if err != nil { + return err + } + + if output == nil { + return fmt.Errorf("Secret %q does not exist", rs.Primary.ID) + } + + if !aws.BoolValue(output.RotationEnabled) { + return fmt.Errorf("Secret rotation %q is not enabled", rs.Primary.ID) + } + + *secret = *output + + return nil + } +} + +func testAccAwsSecretsManagerSecretRotationConfig(rName string, automaticallyAfterDays int) string { + return baseAccAWSLambdaConfig(rName, rName, rName) + fmt.Sprintf(` +# Not a real rotation function +resource "aws_lambda_function" "test1" { + filename = "test-fixtures/lambdatest.zip" + function_name = "%[1]s-1" + handler = "exports.example" + role = "${aws_iam_role.iam_for_lambda.arn}" + runtime = "nodejs12.x" +} + +resource "aws_lambda_permission" "test1" { + action = "lambda:InvokeFunction" + function_name = "${aws_lambda_function.test1.function_name}" + principal = "secretsmanager.amazonaws.com" + statement_id = "AllowExecutionFromSecretsManager1" +} + +# Not a real rotation function +resource "aws_lambda_function" "test2" { + filename = "test-fixtures/lambdatest.zip" + function_name = "%[1]s-2" + handler = "exports.example" + role = "${aws_iam_role.iam_for_lambda.arn}" + runtime = "nodejs12.x" +} + +resource "aws_lambda_permission" "test2" { + action = "lambda:InvokeFunction" + function_name = "${aws_lambda_function.test2.function_name}" + principal = "secretsmanager.amazonaws.com" + statement_id = "AllowExecutionFromSecretsManager2" +} + +resource "aws_secretsmanager_secret" "test" { + name = "%[1]s" +} + +resource "aws_secretsmanager_secret_rotation" "test" { + secret_id = "${aws_secretsmanager_secret.test.id}" + rotation_lambda_arn = "${aws_lambda_function.test1.arn}" + + rotation_rules { + automatically_after_days = %[2]d + } + + depends_on = ["aws_lambda_permission.test1"] +} +`, rName, automaticallyAfterDays) +} diff --git a/aws/resource_aws_secretsmanager_secret_test.go b/aws/resource_aws_secretsmanager_secret_test.go index c6605b0e9c5..7c4029a8741 100644 --- a/aws/resource_aws_secretsmanager_secret_test.go +++ b/aws/resource_aws_secretsmanager_secret_test.go @@ -8,10 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/secretsmanager" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - awspolicy "github.com/jen20/awspolicyequivalence" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/secretsmanager/waiter" ) func init() { @@ -64,7 +64,7 @@ func testSweepSecretsManagerSecrets(region string) error { return nil } -func TestAccAwsSecretsManagerSecret_Basic(t *testing.T) { +func TestAccAwsSecretsManagerSecret_basic(t *testing.T) { var secret secretsmanager.DescribeSecretOutput rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_secretsmanager_secret.test" @@ -275,8 +275,7 @@ func TestAccAwsSecretsManagerSecret_RotationLambdaARN(t *testing.T) { Config: testAccAwsSecretsManagerSecretConfig_Name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsSecretsManagerSecretExists(resourceName, &secret), - resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "rotation_lambda_arn", ""), + resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), // Must be removed with aws_secretsmanager_secret_rotation after version 2.67.0 ), }, }, @@ -329,8 +328,7 @@ func TestAccAwsSecretsManagerSecret_RotationRules(t *testing.T) { Config: testAccAwsSecretsManagerSecretConfig_Name(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsSecretsManagerSecretExists(resourceName, &secret), - resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "false"), - resource.TestCheckResourceAttr(resourceName, "rotation_rules.#", "0"), + resource.TestCheckResourceAttr(resourceName, "rotation_enabled", "true"), // Must be removed with aws_secretsmanager_secret_rotation after version 2.67.0 ), }, }, @@ -394,7 +392,6 @@ func TestAccAwsSecretsManagerSecret_policy(t *testing.T) { var secret secretsmanager.DescribeSecretOutput rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_secretsmanager_secret.test" - expectedPolicyText := `{"Version":"2012-10-17","Statement":[{"Sid":"EnableAllPermissions","Effect":"Allow","Principal":{"AWS":"*"},"Action":"secretsmanager:GetSecretValue","Resource":"*"}]}` resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSSecretsManager(t) }, @@ -405,7 +402,23 @@ func TestAccAwsSecretsManagerSecret_policy(t *testing.T) { Config: testAccAwsSecretsManagerSecretConfig_Policy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsSecretsManagerSecretExists(resourceName, &secret), - testAccCheckAwsSecretsManagerSecretHasPolicy(resourceName, expectedPolicyText), + resource.TestMatchResourceAttr(resourceName, "policy", + regexp.MustCompile(`{"Action":"secretsmanager:GetSecretValue".+`)), + ), + }, + { + Config: testAccAwsSecretsManagerSecretConfig_Name(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsSecretsManagerSecretExists(resourceName, &secret), + resource.TestCheckResourceAttr(resourceName, "policy", ""), + ), + }, + { + Config: testAccAwsSecretsManagerSecretConfig_Policy(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsSecretsManagerSecretExists(resourceName, &secret), + resource.TestMatchResourceAttr(resourceName, "policy", + regexp.MustCompile(`{"Action":"secretsmanager:GetSecretValue".+`)), ), }, }, @@ -424,12 +437,32 @@ func testAccCheckAwsSecretsManagerSecretDestroy(s *terraform.State) error { SecretId: aws.String(rs.Primary.ID), } - output, err := conn.DescribeSecret(input) + var output *secretsmanager.DescribeSecretOutput - if err != nil { - if isAWSErr(err, secretsmanager.ErrCodeResourceNotFoundException, "") { - return nil + err := resource.Retry(waiter.DeletionPropagationTimeout, func() *resource.RetryError { + var err error + output, err = conn.DescribeSecret(input) + + if err != nil { + return resource.NonRetryableError(err) } + + if output != nil && output.DeletedDate == nil { + return resource.RetryableError(fmt.Errorf("Secret %q still exists", rs.Primary.ID)) + } + + return nil + }) + + if isResourceTimeoutError(err) { + output, err = conn.DescribeSecret(input) + } + + if isAWSErr(err, secretsmanager.ErrCodeResourceNotFoundException, "") { + continue + } + + if err != nil { return err } @@ -470,39 +503,6 @@ func testAccCheckAwsSecretsManagerSecretExists(resourceName string, secret *secr } } -func testAccCheckAwsSecretsManagerSecretHasPolicy(name string, expectedPolicyText string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - conn := testAccProvider.Meta().(*AWSClient).secretsmanagerconn - input := &secretsmanager.GetResourcePolicyInput{ - SecretId: aws.String(rs.Primary.ID), - } - - out, err := conn.GetResourcePolicy(input) - - if err != nil { - return err - } - - actualPolicyText := *out.ResourcePolicy - - equivalent, err := awspolicy.PoliciesAreEquivalent(actualPolicyText, expectedPolicyText) - if err != nil { - return fmt.Errorf("error testing policy equivalence: %w", err) - } - if !equivalent { - return fmt.Errorf("non-equivalent policy error:\n\nexpected: %s\n\n got: %s", - expectedPolicyText, actualPolicyText) - } - - return nil - } -} - func testAccPreCheckAWSSecretsManager(t *testing.T) { conn := testAccProvider.Meta().(*AWSClient).secretsmanagerconn @@ -700,8 +700,28 @@ resource "aws_secretsmanager_secret" "test" { func testAccAwsSecretsManagerSecretConfig_Policy(rName string) string { return fmt.Sprintf(` +resource "aws_iam_role" "test" { + name = %[1]q + + assume_role_policy = < 0 { - for _, gp := range rule.UserIdGroupPairs { - if _, ok := groupIds[*gp.GroupId]; !ok { - continue + switch len(components) { + case 2: + userId := components[0] + groupId := components[1] + + for _, gp := range rule.UserIdGroupPairs { + if aws.StringValue(gp.GroupId) != groupId || aws.StringValue(gp.UserId) != userId { + continue + } + + if desc := aws.StringValue(gp.Description); desc != "" { + return desc + } } + case 1: + groupId := components[0] + for _, gp := range rule.UserIdGroupPairs { + if aws.StringValue(gp.GroupId) != groupId { + continue + } - if desc := aws.StringValue(gp.Description); desc != "" { - return desc + if desc := aws.StringValue(gp.Description); desc != "" { + return desc + } } } } @@ -978,8 +1002,14 @@ func populateSecurityGroupRuleFromImport(d *schema.ResourceData, importParts []s sgID := importParts[0] ruleType := importParts[1] protocol := importParts[2] - fromPort, _ := strconv.Atoi(importParts[3]) - toPort, _ := strconv.Atoi(importParts[4]) + fromPort, err := strconv.Atoi(importParts[3]) + if err != nil { + return err + } + toPort, err := strconv.Atoi(importParts[4]) + if err != nil { + return err + } sources := importParts[5:] d.Set("security_group_id", sgID) diff --git a/aws/resource_aws_security_group_rule_migrate.go b/aws/resource_aws_security_group_rule_migrate.go index 81c60453fac..68e3c027a20 100644 --- a/aws/resource_aws_security_group_rule_migrate.go +++ b/aws/resource_aws_security_group_rule_migrate.go @@ -8,7 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func resourceAwsSecurityGroupRuleMigrateState( diff --git a/aws/resource_aws_security_group_rule_migrate_test.go b/aws/resource_aws_security_group_rule_migrate_test.go index d4c850eb4e1..1611631d494 100644 --- a/aws/resource_aws_security_group_rule_migrate_test.go +++ b/aws/resource_aws_security_group_rule_migrate_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAWSSecurityGroupRuleMigrateState(t *testing.T) { diff --git a/aws/resource_aws_security_group_rule_test.go b/aws/resource_aws_security_group_rule_test.go index cb6be2babff..34de3b3e8e1 100644 --- a/aws/resource_aws_security_group_rule_test.go +++ b/aws/resource_aws_security_group_rule_test.go @@ -12,9 +12,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestIpPermissionIDHash(t *testing.T) { @@ -154,6 +154,40 @@ func TestAccAWSSecurityGroupRule_Ingress_VPC(t *testing.T) { }) } +func TestAccAWSSecurityGroupRule_Ingress_Source_With_Account_Id(t *testing.T) { + var group ec2.SecurityGroup + + rInt := acctest.RandInt() + + ruleName := "aws_security_group_rule.allow_self" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupRuleDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSSecurityGroupRule_Ingress_Source_with_AccountId(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSSecurityGroupRuleExists("aws_security_group.web", &group), + resource.TestCheckResourceAttrPair( + ruleName, "security_group_id", "aws_security_group.web", "id"), + resource.TestMatchResourceAttr( + ruleName, "source_security_group_id", regexp.MustCompile("^[0-9]{12}/sg-[0-9a-z]{17}$")), + resource.TestCheckResourceAttr( + ruleName, "description", "some description"), + resource.TestCheckResourceAttr( + ruleName, "from_port", "0"), + resource.TestCheckResourceAttr( + ruleName, "to_port", "0"), + resource.TestCheckResourceAttr( + ruleName, "protocol", "-1"), + ), + }, + }, + }) +} + func TestAccAWSSecurityGroupRule_Ingress_Protocol(t *testing.T) { var group ec2.SecurityGroup @@ -1606,7 +1640,7 @@ resource "aws_security_group_rule" "%[2]s_rule_3" { `, rInt, rType)) if rType == "egress" { - b.WriteString(fmt.Sprintf(` + b.WriteString(` resource "aws_security_group_rule" "egress_rule_4" { security_group_id = "${aws_security_group.worker.id}" description = "Prefix List Description" @@ -1616,7 +1650,7 @@ resource "aws_security_group_rule" "egress_rule_4" { to_port = 22 prefix_list_ids = ["${aws_vpc_endpoint.s3-us-west-2.prefix_list_id}"] } - `)) + `) } return b.String() @@ -2046,6 +2080,36 @@ resource "aws_security_group_rule" "allow_self" { `, rInt) } +func testAccAWSSecurityGroupRule_Ingress_Source_with_AccountId(rInt int) string { + return fmt.Sprintf(` +data "aws_caller_identity" "current" {} + +resource "aws_vpc" "foo" { + cidr_block = "10.1.0.0/16" + + tags = { + Name = "terraform-testacc-security-group-rule-self-ingress" + } +} + +resource "aws_security_group" "web" { + name = "allow_all-%d" + description = "Allow all inbound traffic" + vpc_id = "${aws_vpc.foo.id}" +} + +resource "aws_security_group_rule" "allow_self" { + type = "ingress" + from_port = 0 + to_port = 0 + protocol = "-1" + description = "some description" + security_group_id = "${aws_security_group.web.id}" + source_security_group_id = "${data.aws_caller_identity.current.account_id}/${aws_security_group.web.id}" +} +`, rInt) +} + func testAccAWSSecurityGroupRuleExpectInvalidType(rInt int) string { return fmt.Sprintf(` resource "aws_vpc" "foo" { diff --git a/aws/resource_aws_security_group_rules_matching_test.go b/aws/resource_aws_security_group_rules_matching_test.go index bc8af322139..5ca6bcaefe7 100644 --- a/aws/resource_aws_security_group_rules_matching_test.go +++ b/aws/resource_aws_security_group_rules_matching_test.go @@ -4,7 +4,7 @@ import ( "log" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // testing rulesForGroupPermissions diff --git a/aws/resource_aws_security_group_test.go b/aws/resource_aws_security_group_test.go index 839d0a3eb9c..16e639244dd 100644 --- a/aws/resource_aws_security_group_test.go +++ b/aws/resource_aws_security_group_test.go @@ -13,11 +13,12 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/terraform-providers/terraform-provider-aws/aws/internal/naming" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) // add sweeper to delete known test sgs @@ -642,7 +643,6 @@ func TestAccAWSSecurityGroup_IPRangeAndSecurityGroupWithSameRules(t *testing.T) { ResourceName: resourceName, ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(4), ImportStateVerify: true, ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, @@ -668,7 +668,6 @@ func TestAccAWSSecurityGroup_IPRangesWithSameRules(t *testing.T) { { ResourceName: resourceName, ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(3), ImportStateVerify: true, ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, @@ -681,11 +680,10 @@ func TestAccAWSSecurityGroup_basic(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfig, @@ -696,25 +694,24 @@ func TestAccAWSSecurityGroup_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.description", ""), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(2), - // NOTE: These ImportStateVerify functions are currently broken because of known issues with multi-import. - // Once those are fixed we can uncomment all these. - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -737,11 +734,10 @@ func TestAccAWSSecurityGroup_egressConfigMode(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(3), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { Config: testAccAWSSecurityGroupConfigEgressConfigModeNoBlocks(), @@ -778,11 +774,10 @@ func TestAccAWSSecurityGroup_ingressConfigMode(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(3), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { Config: testAccAWSSecurityGroupConfigIngressConfigModeNoBlocks(), @@ -818,73 +813,84 @@ func TestAccAWSSecurityGroup_ruleGathering(t *testing.T) { testAccCheckAWSSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", sgName), resource.TestCheckResourceAttr(resourceName, "egress.#", "3"), - resource.TestCheckResourceAttr(resourceName, "egress.2760422146.cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.2760422146.description", "egress for all ipv6"), - resource.TestCheckResourceAttr(resourceName, "egress.2760422146.from_port", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.2760422146.ipv6_cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.2760422146.ipv6_cidr_blocks.0", "::/0"), - resource.TestCheckResourceAttr(resourceName, "egress.2760422146.prefix_list_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.2760422146.protocol", "-1"), - resource.TestCheckResourceAttr(resourceName, "egress.2760422146.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.2760422146.self", "false"), - resource.TestCheckResourceAttr(resourceName, "egress.2760422146.to_port", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3161496341.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.3161496341.cidr_blocks.0", "0.0.0.0/0"), - resource.TestCheckResourceAttr(resourceName, "egress.3161496341.description", "egress for all ipv4"), - resource.TestCheckResourceAttr(resourceName, "egress.3161496341.from_port", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3161496341.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3161496341.prefix_list_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3161496341.protocol", "-1"), - resource.TestCheckResourceAttr(resourceName, "egress.3161496341.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3161496341.self", "false"), - resource.TestCheckResourceAttr(resourceName, "egress.3161496341.to_port", "0"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "0", + "description": "egress for all ipv6", + "from_port": "0", + "ipv6_cidr_blocks.#": "1", + "ipv6_cidr_blocks.0": "::/0", + "prefix_list_ids.#": "0", + "protocol": "-1", + "security_groups.#": "0", + "self": "false", + "to_port": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "0.0.0.0/0", + "description": "egress for all ipv4", + "from_port": "0", + "ipv6_cidr_blocks.#": "0", + "prefix_list_ids.#": "0", + "protocol": "-1", + "security_groups.#": "0", + "self": "false", + "to_port": "0", + }), resource.TestCheckResourceAttr(resourceName, "ingress.#", "5"), - resource.TestCheckResourceAttr(resourceName, "ingress.1274017860.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.1274017860.cidr_blocks.0", "192.168.0.0/16"), - resource.TestCheckResourceAttr(resourceName, "ingress.1274017860.description", "ingress from 192.168.0.0/16"), - resource.TestCheckResourceAttr(resourceName, "ingress.1274017860.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.1274017860.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.1274017860.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.1274017860.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.1274017860.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.1274017860.to_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.1396402051.cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.1396402051.description", "ingress from all ipv6"), - resource.TestCheckResourceAttr(resourceName, "ingress.1396402051.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.1396402051.ipv6_cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.1396402051.ipv6_cidr_blocks.0", "::/0"), - resource.TestCheckResourceAttr(resourceName, "ingress.1396402051.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.1396402051.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.1396402051.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.1396402051.to_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.1889111182.cidr_blocks.#", "2"), - resource.TestCheckResourceAttr(resourceName, "ingress.1889111182.cidr_blocks.0", "10.0.2.0/24"), - resource.TestCheckResourceAttr(resourceName, "ingress.1889111182.cidr_blocks.1", "10.0.3.0/24"), - resource.TestCheckResourceAttr(resourceName, "ingress.1889111182.description", "ingress from 10.0.0.0/16"), - resource.TestCheckResourceAttr(resourceName, "ingress.1889111182.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.1889111182.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.1889111182.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.1889111182.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.1889111182.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.1889111182.to_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.2038285407.cidr_blocks.#", "2"), - resource.TestCheckResourceAttr(resourceName, "ingress.2038285407.cidr_blocks.0", "10.0.0.0/24"), - resource.TestCheckResourceAttr(resourceName, "ingress.2038285407.cidr_blocks.1", "10.0.1.0/24"), - resource.TestCheckResourceAttr(resourceName, "ingress.2038285407.description", ""), - resource.TestCheckResourceAttr(resourceName, "ingress.2038285407.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.2038285407.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.2038285407.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.2038285407.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.2038285407.self", "true"), - resource.TestCheckResourceAttr(resourceName, "ingress.2038285407.to_port", "80"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "192.168.0.0/16", + "description": "ingress from 192.168.0.0/16", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "80", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "0", + "description": "ingress from all ipv6", + "from_port": "80", + "ipv6_cidr_blocks.#": "1", + "ipv6_cidr_blocks.0": "::/0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "80", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "2", + "cidr_blocks.0": "10.0.2.0/24", + "cidr_blocks.1": "10.0.3.0/24", + "description": "ingress from 10.0.0.0/16", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "80", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "2", + "cidr_blocks.0": "10.0.0.0/24", + "cidr_blocks.1": "10.0.1.0/24", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "true", + "to_port": "80", + }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(8), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -923,11 +929,10 @@ func TestAccAWSSecurityGroup_forceRevokeRulesTrue(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(2), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, // Verify the DependencyViolation error by using a configuration with the // groups removed. Terraform tries to destroy them but cannot. Expect a @@ -1005,11 +1010,10 @@ func TestAccAWSSecurityGroup_forceRevokeRulesFalse(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(2), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, // Verify the DependencyViolation error by using a configuration with the // groups removed, and the Groups not configured to revoke their ruls. @@ -1042,11 +1046,10 @@ func TestAccAWSSecurityGroup_ipv6(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfigIpv6, @@ -1055,33 +1058,36 @@ func TestAccAWSSecurityGroup_ipv6(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.2293451516.cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.2293451516.description", ""), - resource.TestCheckResourceAttr(resourceName, "egress.2293451516.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "egress.2293451516.ipv6_cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.2293451516.ipv6_cidr_blocks.0", "::/0"), - resource.TestCheckResourceAttr(resourceName, "egress.2293451516.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "egress.2293451516.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.2293451516.self", "false"), - resource.TestCheckResourceAttr(resourceName, "egress.2293451516.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "0", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "1", + "ipv6_cidr_blocks.0": "::/0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.2293451516.cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.2293451516.description", ""), - resource.TestCheckResourceAttr(resourceName, "ingress.2293451516.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.2293451516.ipv6_cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.2293451516.ipv6_cidr_blocks.0", "::/0"), - resource.TestCheckResourceAttr(resourceName, "ingress.2293451516.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.2293451516.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.2293451516.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.2293451516.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "0", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "1", + "ipv6_cidr_blocks.0": "::/0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(3), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1132,11 +1138,10 @@ func TestAccAWSSecurityGroup_self(t *testing.T) { } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfigSelf, @@ -1144,19 +1149,20 @@ func TestAccAWSSecurityGroup_self(t *testing.T) { testAccCheckAWSSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "name", "terraform_acceptance_test_example"), resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), - resource.TestCheckResourceAttr(resourceName, "ingress.3971148406.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.3971148406.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.3971148406.to_port", "8000"), - resource.TestCheckResourceAttr(resourceName, "ingress.3971148406.self", "true"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "tcp", + "from_port": "80", + "to_port": "8000", + "self": "true", + }), checkSelf, ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(3), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1167,11 +1173,10 @@ func TestAccAWSSecurityGroup_vpc(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfigVpc, @@ -1182,35 +1187,28 @@ func TestAccAWSSecurityGroup_vpc(t *testing.T) { resourceName, "name", "terraform_acceptance_test_example"), resource.TestCheckResourceAttr( resourceName, "description", "Used in the terraform acceptance tests"), - resource.TestCheckResourceAttr( - resourceName, "ingress.3629188364.protocol", "tcp"), - resource.TestCheckResourceAttr( - resourceName, "ingress.3629188364.from_port", "80"), - resource.TestCheckResourceAttr( - resourceName, "ingress.3629188364.to_port", "8000"), - resource.TestCheckResourceAttr( - resourceName, "ingress.3629188364.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "ingress.3629188364.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr( - resourceName, "egress.3629188364.protocol", "tcp"), - resource.TestCheckResourceAttr( - resourceName, "egress.3629188364.from_port", "80"), - resource.TestCheckResourceAttr( - resourceName, "egress.3629188364.to_port", "8000"), - resource.TestCheckResourceAttr( - resourceName, "egress.3629188364.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "egress.3629188364.cidr_blocks.0", "10.0.0.0/8"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "tcp", + "from_port": "80", + "to_port": "8000", + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "protocol": "tcp", + "from_port": "80", + "to_port": "8000", + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + }), testAccAWSSecurityGroupCheckVPCIDExists(&group), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(3), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1221,11 +1219,10 @@ func TestAccAWSSecurityGroup_vpcNegOneIngress(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfigVpcNegOneIngress, @@ -1236,25 +1233,21 @@ func TestAccAWSSecurityGroup_vpcNegOneIngress(t *testing.T) { resourceName, "name", "terraform_acceptance_test_example"), resource.TestCheckResourceAttr( resourceName, "description", "Used in the terraform acceptance tests"), - resource.TestCheckResourceAttr( - resourceName, "ingress.956249133.protocol", "-1"), - resource.TestCheckResourceAttr( - resourceName, "ingress.956249133.from_port", "0"), - resource.TestCheckResourceAttr( - resourceName, "ingress.956249133.to_port", "0"), - resource.TestCheckResourceAttr( - resourceName, "ingress.956249133.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "ingress.956249133.cidr_blocks.0", "10.0.0.0/8"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "-1", + "from_port": "0", + "to_port": "0", + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + }), testAccAWSSecurityGroupCheckVPCIDExists(&group), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(2), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1264,11 +1257,10 @@ func TestAccAWSSecurityGroup_vpcProtoNumIngress(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfigVpcProtoNumIngress, @@ -1278,25 +1270,21 @@ func TestAccAWSSecurityGroup_vpcProtoNumIngress(t *testing.T) { resourceName, "name", "terraform_acceptance_test_example"), resource.TestCheckResourceAttr( resourceName, "description", "Used in the terraform acceptance tests"), - resource.TestCheckResourceAttr( - resourceName, "ingress.2449525218.protocol", "50"), - resource.TestCheckResourceAttr( - resourceName, "ingress.2449525218.from_port", "0"), - resource.TestCheckResourceAttr( - resourceName, "ingress.2449525218.to_port", "0"), - resource.TestCheckResourceAttr( - resourceName, "ingress.2449525218.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "ingress.2449525218.cidr_blocks.0", "10.0.0.0/8"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "protocol": "50", + "from_port": "0", + "to_port": "0", + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + }), testAccAWSSecurityGroupCheckVPCIDExists(&group), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(2), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1318,11 +1306,10 @@ func TestAccAWSSecurityGroup_multiIngress(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(3), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1345,11 +1332,10 @@ func TestAccAWSSecurityGroup_change(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(2), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, { Config: testAccAWSSecurityGroupConfigChange, @@ -1367,45 +1353,47 @@ func TestAccAWSSecurityGroup_ruleDescription(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - IDRefreshName: resourceName, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfigRuleDescription("Egress description", "Ingress description"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.2129912301.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.2129912301.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "egress.2129912301.description", "Egress description"), - resource.TestCheckResourceAttr(resourceName, "egress.2129912301.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "egress.2129912301.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.2129912301.prefix_list_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.2129912301.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "egress.2129912301.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.2129912301.self", "false"), - resource.TestCheckResourceAttr(resourceName, "egress.2129912301.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "Egress description", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "prefix_list_ids.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.1147649399.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.1147649399.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "ingress.1147649399.description", "Ingress description"), - resource.TestCheckResourceAttr(resourceName, "ingress.1147649399.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.1147649399.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.1147649399.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.1147649399.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.1147649399.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.1147649399.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "Ingress description", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(3), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, // Change just the rule descriptions. { @@ -1413,26 +1401,30 @@ func TestAccAWSSecurityGroup_ruleDescription(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.746197026.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.746197026.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "egress.746197026.description", "New egress description"), - resource.TestCheckResourceAttr(resourceName, "egress.746197026.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "egress.746197026.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.746197026.prefix_list_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.746197026.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "egress.746197026.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.746197026.self", "false"), - resource.TestCheckResourceAttr(resourceName, "egress.746197026.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "New egress description", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "prefix_list_ids.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.1341057959.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.1341057959.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "ingress.1341057959.description", "New ingress description"), - resource.TestCheckResourceAttr(resourceName, "ingress.1341057959.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.1341057959.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.1341057959.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.1341057959.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.1341057959.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.1341057959.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "New ingress description", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), ), }, // Remove just the rule descriptions. @@ -1441,23 +1433,27 @@ func TestAccAWSSecurityGroup_ruleDescription(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.description", ""), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.self", "false"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "", + "from_port": "80", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), resource.TestCheckResourceAttr(resourceName, "ingress.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.description", ""), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "", + "from_port": "80", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), ), }, }, @@ -1507,11 +1503,10 @@ func TestAccAWSSecurityGroup_defaultEgressVPC(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(2), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1540,7 +1535,6 @@ func TestAccAWSSecurityGroup_defaultEgressClassic(t *testing.T) { { ResourceName: resourceName, ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(1), ImportStateVerify: true, ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, @@ -1554,10 +1548,9 @@ func TestAccAWSSecurityGroup_drift(t *testing.T) { var group ec2.SecurityGroup resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfig_drift(), @@ -1566,32 +1559,38 @@ func TestAccAWSSecurityGroup_drift(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.description", ""), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.to_port", "8000"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.cidr_blocks.0", "206.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.description", ""), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "206.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(2), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + // In rules with cidr_block drift, import only creates a single ingress + // rule with the cidr_blocks de-normalized. During subsequent apply, its + // normalized to create the 2 ingress rules seen in checks above. + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete", "ingress", "egress"}, }, }, }) @@ -1602,10 +1601,9 @@ func TestAccAWSSecurityGroup_driftComplex(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfig_drift_complex(), @@ -1613,53 +1611,63 @@ func TestAccAWSSecurityGroup_driftComplex(t *testing.T) { testAccCheckAWSSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "description", "Used in the terraform acceptance tests"), resource.TestCheckResourceAttr(resourceName, "egress.#", "3"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.description", ""), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.prefix_list_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.self", "false"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.to_port", "8000"), - resource.TestCheckResourceAttr(resourceName, "egress.657243763.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.657243763.cidr_blocks.0", "206.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "egress.657243763.description", ""), - resource.TestCheckResourceAttr(resourceName, "egress.657243763.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "egress.657243763.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.657243763.prefix_list_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.657243763.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "egress.657243763.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.657243763.self", "false"), - resource.TestCheckResourceAttr(resourceName, "egress.657243763.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "prefix_list_ids.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "206.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "prefix_list_ids.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), resource.TestCheckResourceAttr(resourceName, "ingress.#", "3"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.description", ""), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.3629188364.to_port", "8000"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.cidr_blocks.0", "206.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.description", ""), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.657243763.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "206.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(5), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + // In rules with cidr_block drift, import only creates a single ingress + // rule with the cidr_blocks de-normalized. During subsequent apply, its + // normalized to create the 2 ingress rules seen in checks above. + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete", "ingress", "egress"}, }, }, }) @@ -1711,7 +1719,6 @@ func TestAccAWSSecurityGroup_tags(t *testing.T) { { ResourceName: resourceName, ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(1), ImportStateVerify: true, ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, @@ -1745,11 +1752,10 @@ func TestAccAWSSecurityGroup_CIDRandGroups(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(5), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1760,10 +1766,9 @@ func TestAccAWSSecurityGroup_ingressWithCidrAndSGsVPC(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfig_ingressWithCidrAndSGs, @@ -1771,34 +1776,37 @@ func TestAccAWSSecurityGroup_ingressWithCidrAndSGsVPC(t *testing.T) { testAccCheckAWSSecurityGroupExists(resourceName, &group), testAccCheckAWSSecurityGroupSGandCidrAttributes(&group), resource.TestCheckResourceAttr(resourceName, "egress.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.cidr_blocks.0", "10.0.0.0/8"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.description", ""), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.from_port", "80"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.prefix_list_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.self", "false"), - resource.TestCheckResourceAttr(resourceName, "egress.3629188364.to_port", "8000"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "10.0.0.0/8", + "description": "", + "from_port": "80", + "ipv6_cidr_blocks.#": "0", + "prefix_list_ids.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "8000", + }), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.cidr_blocks.0", "192.168.0.1/32"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.description", ""), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.from_port", "22"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.to_port", "22"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "192.168.0.1/32", + "description": "", + "from_port": "22", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "22", + }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(5), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1813,10 +1821,9 @@ func TestAccAWSSecurityGroup_ingressWithCidrAndSGsClassic(t *testing.T) { defer os.Setenv("AWS_DEFAULT_REGION", oldvar) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccEC2ClassicPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccEC2ClassicPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfig_ingressWithCidrAndSGs_classic, @@ -1825,23 +1832,24 @@ func TestAccAWSSecurityGroup_ingressWithCidrAndSGsClassic(t *testing.T) { testAccCheckAWSSecurityGroupSGandCidrAttributes(&group), resource.TestCheckResourceAttr(resourceName, "egress.#", "0"), resource.TestCheckResourceAttr(resourceName, "ingress.#", "2"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.cidr_blocks.0", "192.168.0.1/32"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.description", ""), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.from_port", "22"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.protocol", "tcp"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.self", "false"), - resource.TestCheckResourceAttr(resourceName, "ingress.3893008652.to_port", "22"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ingress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "192.168.0.1/32", + "description": "", + "from_port": "22", + "ipv6_cidr_blocks.#": "0", + "protocol": "tcp", + "security_groups.#": "0", + "self": "false", + "to_port": "22", + }), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(4), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1866,11 +1874,10 @@ func TestAccAWSSecurityGroup_egressWithPrefixList(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(2), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1895,11 +1902,10 @@ func TestAccAWSSecurityGroup_ingressWithPrefixList(t *testing.T) { ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(2), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete"}, }, }, }) @@ -1910,59 +1916,52 @@ func TestAccAWSSecurityGroup_ipv4andipv6Egress(t *testing.T) { resourceName := "aws_security_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSecurityGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSecurityGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSSecurityGroupConfigIpv4andIpv6Egress, Check: resource.ComposeTestCheckFunc( testAccCheckAWSSecurityGroupExists(resourceName, &group), resource.TestCheckResourceAttr(resourceName, "egress.#", "2"), - resource.TestCheckResourceAttr(resourceName, "egress.482069346.cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.482069346.cidr_blocks.0", "0.0.0.0/0"), - resource.TestCheckResourceAttr(resourceName, "egress.482069346.description", ""), - resource.TestCheckResourceAttr(resourceName, "egress.482069346.from_port", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.482069346.ipv6_cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.482069346.prefix_list_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.482069346.protocol", "-1"), - resource.TestCheckResourceAttr(resourceName, "egress.482069346.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.482069346.self", "false"), - resource.TestCheckResourceAttr(resourceName, "egress.482069346.to_port", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.706749478.cidr_blocks.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.706749478.description", ""), - resource.TestCheckResourceAttr(resourceName, "egress.706749478.from_port", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.706749478.ipv6_cidr_blocks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "egress.706749478.ipv6_cidr_blocks.0", "::/0"), - resource.TestCheckResourceAttr(resourceName, "egress.706749478.prefix_list_ids.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.706749478.protocol", "-1"), - resource.TestCheckResourceAttr(resourceName, "egress.706749478.security_groups.#", "0"), - resource.TestCheckResourceAttr(resourceName, "egress.706749478.self", "false"), - resource.TestCheckResourceAttr(resourceName, "egress.706749478.to_port", "0"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "1", + "cidr_blocks.0": "0.0.0.0/0", + "description": "", + "from_port": "0", + "ipv6_cidr_blocks.#": "0", + "prefix_list_ids.#": "0", + "protocol": "-1", + "security_groups.#": "0", + "self": "false", + "to_port": "0", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "egress.*", map[string]string{ + "cidr_blocks.#": "0", + "description": "", + "from_port": "0", + "ipv6_cidr_blocks.#": "1", + "ipv6_cidr_blocks.0": "::/0", + "prefix_list_ids.#": "0", + "protocol": "-1", + "security_groups.#": "0", + "self": "false", + "to_port": "0", + }), resource.TestCheckResourceAttr(resourceName, "ingress.#", "0"), ), }, { - ResourceName: resourceName, - ImportState: true, - ImportStateCheck: testAccAWSSecurityGroupImportStateCheckFunc(3), - //ImportStateVerify: true, - //ImportStateVerifyIgnore: []string{"revoke_rules_on_delete", "egress"}, + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"revoke_rules_on_delete", "egress"}, }, }, }) } -func testAccAWSSecurityGroupImportStateCheckFunc(expectedStates int) resource.ImportStateCheckFunc { - return func(s []*terraform.InstanceState) error { - if len(s) != expectedStates { - return fmt.Errorf("expected %d states, got %d: %#v", expectedStates, len(s), s) - } - return nil - } -} - func testAccAWSSecurityGroupCheckVPCIDExists(group *ec2.SecurityGroup) resource.TestCheckFunc { return func(*terraform.State) error { if *group.VpcId == "" { @@ -4126,7 +4125,7 @@ resource "aws_security_group" "test" { ` func testAccAWSSecurityGroupConfigEgressConfigModeBlocks() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4156,11 +4155,11 @@ resource "aws_security_group" "test" { to_port = 0 } } -`) +` } func testAccAWSSecurityGroupConfigEgressConfigModeNoBlocks() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4176,11 +4175,11 @@ resource "aws_security_group" "test" { vpc_id = "${aws_vpc.test.id}" } -`) +` } func testAccAWSSecurityGroupConfigEgressConfigModeZeroed() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4198,11 +4197,11 @@ resource "aws_security_group" "test" { vpc_id = "${aws_vpc.test.id}" } -`) +` } func testAccAWSSecurityGroupConfigIngressConfigModeBlocks() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4232,11 +4231,11 @@ resource "aws_security_group" "test" { to_port = 0 } } -`) +` } func testAccAWSSecurityGroupConfigIngressConfigModeNoBlocks() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4252,11 +4251,11 @@ resource "aws_security_group" "test" { vpc_id = "${aws_vpc.test.id}" } -`) +` } func testAccAWSSecurityGroupConfigIngressConfigModeZeroed() string { - return fmt.Sprintf(` + return ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -4274,5 +4273,5 @@ resource "aws_security_group" "test" { vpc_id = "${aws_vpc.test.id}" } -`) +` } diff --git a/aws/resource_aws_securityhub_account.go b/aws/resource_aws_securityhub_account.go index edb1aa9771a..49bb9fc4a4c 100644 --- a/aws/resource_aws_securityhub_account.go +++ b/aws/resource_aws_securityhub_account.go @@ -5,7 +5,7 @@ import ( "log" "github.com/aws/aws-sdk-go/service/securityhub" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsSecurityHubAccount() *schema.Resource { diff --git a/aws/resource_aws_securityhub_account_test.go b/aws/resource_aws_securityhub_account_test.go index 2ddbd232f0f..70eb39b3cc3 100644 --- a/aws/resource_aws_securityhub_account_test.go +++ b/aws/resource_aws_securityhub_account_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/securityhub" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAWSSecurityHubAccount_basic(t *testing.T) { diff --git a/aws/resource_aws_securityhub_member.go b/aws/resource_aws_securityhub_member.go index 6eaaec33739..9c02b7bbe83 100644 --- a/aws/resource_aws_securityhub_member.go +++ b/aws/resource_aws_securityhub_member.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/securityhub" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) const ( diff --git a/aws/resource_aws_securityhub_member_test.go b/aws/resource_aws_securityhub_member_test.go index 82f5672ab19..5278badbabe 100644 --- a/aws/resource_aws_securityhub_member_test.go +++ b/aws/resource_aws_securityhub_member_test.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/securityhub" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAWSSecurityHubMember_basic(t *testing.T) { diff --git a/aws/resource_aws_securityhub_product_subscription.go b/aws/resource_aws_securityhub_product_subscription.go index 358aecb9b61..596660e4968 100644 --- a/aws/resource_aws_securityhub_product_subscription.go +++ b/aws/resource_aws_securityhub_product_subscription.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/securityhub" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsSecurityHubProductSubscription() *schema.Resource { diff --git a/aws/resource_aws_securityhub_product_subscription_test.go b/aws/resource_aws_securityhub_product_subscription_test.go index 5ed2ff317be..6cfa934c4d7 100644 --- a/aws/resource_aws_securityhub_product_subscription_test.go +++ b/aws/resource_aws_securityhub_product_subscription_test.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/securityhub" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAWSSecurityHubProductSubscription_basic(t *testing.T) { diff --git a/aws/resource_aws_securityhub_standards_subscription.go b/aws/resource_aws_securityhub_standards_subscription.go index 5444842a410..371c03b4a0d 100644 --- a/aws/resource_aws_securityhub_standards_subscription.go +++ b/aws/resource_aws_securityhub_standards_subscription.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/securityhub" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsSecurityHubStandardsSubscription() *schema.Resource { diff --git a/aws/resource_aws_securityhub_standards_subscription_test.go b/aws/resource_aws_securityhub_standards_subscription_test.go index af7ab73b134..d6b1131cd47 100644 --- a/aws/resource_aws_securityhub_standards_subscription_test.go +++ b/aws/resource_aws_securityhub_standards_subscription_test.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/securityhub" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAWSSecurityHubStandardsSubscription_basic(t *testing.T) { diff --git a/aws/resource_aws_securityhub_test.go b/aws/resource_aws_securityhub_test.go index a6151c71392..fc0c7555873 100644 --- a/aws/resource_aws_securityhub_test.go +++ b/aws/resource_aws_securityhub_test.go @@ -4,7 +4,7 @@ import ( "testing" ) -func TestAccAWSSecurityHub(t *testing.T) { +func TestAccAWSSecurityHub_serial(t *testing.T) { testCases := map[string]map[string]func(t *testing.T){ "Account": { "basic": testAccAWSSecurityHubAccount_basic, diff --git a/aws/resource_aws_service_discovery_http_namespace.go b/aws/resource_aws_service_discovery_http_namespace.go index 29b0e6f4bea..25b9f8a5369 100644 --- a/aws/resource_aws_service_discovery_http_namespace.go +++ b/aws/resource_aws_service_discovery_http_namespace.go @@ -5,8 +5,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicediscovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/servicediscovery/waiter" ) @@ -14,6 +15,7 @@ func resourceAwsServiceDiscoveryHttpNamespace() *schema.Resource { return &schema.Resource{ Create: resourceAwsServiceDiscoveryHttpNamespaceCreate, Read: resourceAwsServiceDiscoveryHttpNamespaceRead, + Update: resourceAwsServiceDiscoveryHttpNamespaceUpdate, Delete: resourceAwsServiceDiscoveryHttpNamespaceDelete, Importer: &schema.ResourceImporter{ @@ -32,6 +34,7 @@ func resourceAwsServiceDiscoveryHttpNamespace() *schema.Resource { Optional: true, ForceNew: true, }, + "tags": tagsSchema(), "arn": { Type: schema.TypeString, Computed: true, @@ -47,6 +50,7 @@ func resourceAwsServiceDiscoveryHttpNamespaceCreate(d *schema.ResourceData, meta input := &servicediscovery.CreateHttpNamespaceInput{ Name: aws.String(name), + Tags: keyvaluetags.New(d.Get("tags").(map[string]interface{})).IgnoreAws().ServicediscoveryTags(), CreatorRequestId: aws.String(resource.UniqueId()), } @@ -87,6 +91,7 @@ func resourceAwsServiceDiscoveryHttpNamespaceCreate(d *schema.ResourceData, meta func resourceAwsServiceDiscoveryHttpNamespaceRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).sdconn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig input := &servicediscovery.GetNamespaceInput{ Id: aws.String(d.Id()), @@ -101,13 +106,37 @@ func resourceAwsServiceDiscoveryHttpNamespaceRead(d *schema.ResourceData, meta i return fmt.Errorf("error reading Service Discovery HTTP Namespace (%s): %s", d.Id(), err) } + arn := aws.StringValue(resp.Namespace.Arn) d.Set("name", resp.Namespace.Name) d.Set("description", resp.Namespace.Description) - d.Set("arn", resp.Namespace.Arn) + d.Set("arn", arn) + + tags, err := keyvaluetags.ServicediscoveryListTags(conn, arn) + + if err != nil { + return fmt.Errorf("error listing tags for resource (%s): %s", arn, err) + } + + if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) + } return nil } +func resourceAwsServiceDiscoveryHttpNamespaceUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).sdconn + + if d.HasChange("tags") { + o, n := d.GetChange("tags") + if err := keyvaluetags.ServicediscoveryUpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating Service Discovery HTTP Namespace (%s) tags: %s", d.Id(), err) + } + } + + return resourceAwsServiceDiscoveryHttpNamespaceRead(d, meta) +} + func resourceAwsServiceDiscoveryHttpNamespaceDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).sdconn diff --git a/aws/resource_aws_service_discovery_http_namespace_test.go b/aws/resource_aws_service_discovery_http_namespace_test.go index 771471f522f..1af657a7aa7 100644 --- a/aws/resource_aws_service_discovery_http_namespace_test.go +++ b/aws/resource_aws_service_discovery_http_namespace_test.go @@ -3,14 +3,15 @@ package aws import ( "fmt" "log" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicediscovery" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/servicediscovery/waiter" ) @@ -105,9 +106,11 @@ func TestAccAWSServiceDiscoveryHttpNamespace_basic(t *testing.T) { Config: testAccServiceDiscoveryHttpNamespaceConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAwsServiceDiscoveryHttpNamespaceExists(resourceName), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "servicediscovery", regexp.MustCompile(`namespace/.+`)), resource.TestCheckResourceAttrSet(resourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "description", ""), resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { @@ -119,6 +122,27 @@ func TestAccAWSServiceDiscoveryHttpNamespace_basic(t *testing.T) { }) } +func TestAccAWSServiceDiscoveryHttpNamespace_disappears(t *testing.T) { + resourceName := "aws_service_discovery_http_namespace.test" + rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(8, acctest.CharSetAlpha)) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsServiceDiscoveryHttpNamespaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccServiceDiscoveryHttpNamespaceConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryHttpNamespaceExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsServiceDiscoveryHttpNamespace(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func TestAccAWSServiceDiscoveryHttpNamespace_Description(t *testing.T) { resourceName := "aws_service_discovery_http_namespace.test" rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(8, acctest.CharSetAlpha)) @@ -144,6 +168,49 @@ func TestAccAWSServiceDiscoveryHttpNamespace_Description(t *testing.T) { }) } +func TestAccAWSServiceDiscoveryHttpNamespace_Tags(t *testing.T) { + resourceName := "aws_service_discovery_http_namespace.test" + rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(8, acctest.CharSetAlpha)) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsServiceDiscoveryHttpNamespaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccServiceDiscoveryHttpNamespaceConfigTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryHttpNamespaceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccServiceDiscoveryHttpNamespaceConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryHttpNamespaceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccServiceDiscoveryHttpNamespaceConfigTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryHttpNamespaceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + func testAccCheckAwsServiceDiscoveryHttpNamespaceDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).sdconn @@ -188,7 +255,7 @@ func testAccCheckAwsServiceDiscoveryHttpNamespaceExists(name string) resource.Te func testAccServiceDiscoveryHttpNamespaceConfig(rName string) string { return fmt.Sprintf(` resource "aws_service_discovery_http_namespace" "test" { - name = %q + name = %[1]q } `, rName) } @@ -196,8 +263,33 @@ resource "aws_service_discovery_http_namespace" "test" { func testAccServiceDiscoveryHttpNamespaceConfigDescription(rName, description string) string { return fmt.Sprintf(` resource "aws_service_discovery_http_namespace" "test" { - description = %q - name = %q + description = %[1]q + name = %[2]q } `, description, rName) } + +func testAccServiceDiscoveryHttpNamespaceConfigTags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_service_discovery_http_namespace" "test" { + name = %[1]q + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccServiceDiscoveryHttpNamespaceConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_service_discovery_http_namespace" "test" { + name = %[1]q + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} diff --git a/aws/resource_aws_service_discovery_private_dns_namespace.go b/aws/resource_aws_service_discovery_private_dns_namespace.go index c04567287ab..542e72ab7f6 100644 --- a/aws/resource_aws_service_discovery_private_dns_namespace.go +++ b/aws/resource_aws_service_discovery_private_dns_namespace.go @@ -6,8 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicediscovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/servicediscovery/waiter" ) @@ -15,6 +16,7 @@ func resourceAwsServiceDiscoveryPrivateDnsNamespace() *schema.Resource { return &schema.Resource{ Create: resourceAwsServiceDiscoveryPrivateDnsNamespaceCreate, Read: resourceAwsServiceDiscoveryPrivateDnsNamespaceRead, + Update: resourceAwsServiceDiscoveryPrivateDnsNamespaceUpdate, Delete: resourceAwsServiceDiscoveryPrivateDnsNamespaceDelete, Importer: &schema.ResourceImporter{ State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { @@ -44,6 +46,7 @@ func resourceAwsServiceDiscoveryPrivateDnsNamespace() *schema.Resource { Required: true, ForceNew: true, }, + "tags": tagsSchema(), "arn": { Type: schema.TypeString, Computed: true, @@ -70,6 +73,7 @@ func resourceAwsServiceDiscoveryPrivateDnsNamespaceCreate(d *schema.ResourceData input := &servicediscovery.CreatePrivateDnsNamespaceInput{ Name: aws.String(name), + Tags: keyvaluetags.New(d.Get("tags").(map[string]interface{})).IgnoreAws().ServicediscoveryTags(), Vpc: aws.String(d.Get("vpc").(string)), CreatorRequestId: aws.String(requestId), } @@ -111,6 +115,7 @@ func resourceAwsServiceDiscoveryPrivateDnsNamespaceCreate(d *schema.ResourceData func resourceAwsServiceDiscoveryPrivateDnsNamespaceRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).sdconn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig input := &servicediscovery.GetNamespaceInput{ Id: aws.String(d.Id()), @@ -125,15 +130,40 @@ func resourceAwsServiceDiscoveryPrivateDnsNamespaceRead(d *schema.ResourceData, return err } + arn := aws.StringValue(resp.Namespace.Arn) d.Set("description", resp.Namespace.Description) - d.Set("arn", resp.Namespace.Arn) + d.Set("arn", arn) d.Set("name", resp.Namespace.Name) if resp.Namespace.Properties != nil { d.Set("hosted_zone", resp.Namespace.Properties.DnsProperties.HostedZoneId) } + + tags, err := keyvaluetags.ServicediscoveryListTags(conn, arn) + + if err != nil { + return fmt.Errorf("error listing tags for resource (%s): %s", arn, err) + } + + if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) + } + return nil } +func resourceAwsServiceDiscoveryPrivateDnsNamespaceUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).sdconn + + if d.HasChange("tags") { + o, n := d.GetChange("tags") + if err := keyvaluetags.ServicediscoveryUpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating Service Discovery Private DNS Namespace (%s) tags: %s", d.Id(), err) + } + } + + return resourceAwsServiceDiscoveryHttpNamespaceRead(d, meta) +} + func resourceAwsServiceDiscoveryPrivateDnsNamespaceDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).sdconn diff --git a/aws/resource_aws_service_discovery_private_dns_namespace_test.go b/aws/resource_aws_service_discovery_private_dns_namespace_test.go index 13b36491dee..dcc24a065f6 100644 --- a/aws/resource_aws_service_discovery_private_dns_namespace_test.go +++ b/aws/resource_aws_service_discovery_private_dns_namespace_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicediscovery" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/servicediscovery/waiter" ) @@ -94,7 +94,8 @@ func testSweepServiceDiscoveryPrivateDnsNamespaces(region string) error { } func TestAccAWSServiceDiscoveryPrivateDnsNamespace_basic(t *testing.T) { - rName := acctest.RandString(5) + ".example.com" + resourceName := "aws_service_discovery_private_dns_namespace.test" + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, @@ -104,23 +105,26 @@ func TestAccAWSServiceDiscoveryPrivateDnsNamespace_basic(t *testing.T) { { Config: testAccServiceDiscoveryPrivateDnsNamespaceConfig(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsServiceDiscoveryPrivateDnsNamespaceExists("aws_service_discovery_private_dns_namespace.test"), - resource.TestCheckResourceAttrSet("aws_service_discovery_private_dns_namespace.test", "arn"), - resource.TestCheckResourceAttrSet("aws_service_discovery_private_dns_namespace.test", "hosted_zone"), + testAccCheckAwsServiceDiscoveryPrivateDnsNamespaceExists(resourceName), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "servicediscovery", regexp.MustCompile(`namespace/.+`)), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttrSet(resourceName, "hosted_zone"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { - ResourceName: "aws_service_discovery_private_dns_namespace.test", + ResourceName: resourceName, ImportState: true, - ImportStateIdFunc: testAccServiceDiscoveryPrivateDnsNamespaceImportStateIdFunc("aws_service_discovery_private_dns_namespace.test"), + ImportStateIdFunc: testAccServiceDiscoveryPrivateDnsNamespaceImportStateIdFunc(resourceName), ImportStateVerify: true, }, }, }) } -func TestAccAWSServiceDiscoveryPrivateDnsNamespace_longname(t *testing.T) { - rName := acctest.RandString(64-len("example.com")) + ".example.com" +func TestAccAWSServiceDiscoveryPrivateDnsNamespace_disappears(t *testing.T) { + resourceName := "aws_service_discovery_private_dns_namespace.test" + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, @@ -130,16 +134,30 @@ func TestAccAWSServiceDiscoveryPrivateDnsNamespace_longname(t *testing.T) { { Config: testAccServiceDiscoveryPrivateDnsNamespaceConfig(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsServiceDiscoveryPrivateDnsNamespaceExists("aws_service_discovery_private_dns_namespace.test"), - resource.TestCheckResourceAttrSet("aws_service_discovery_private_dns_namespace.test", "arn"), - resource.TestCheckResourceAttrSet("aws_service_discovery_private_dns_namespace.test", "hosted_zone"), + testAccCheckAwsServiceDiscoveryPrivateDnsNamespaceExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsServiceDiscoveryPrivateDnsNamespace(), resourceName), ), + ExpectNonEmptyPlan: true, }, + }, + }) +} + +func TestAccAWSServiceDiscoveryPrivateDnsNamespace_Description(t *testing.T) { + resourceName := "aws_service_discovery_private_dns_namespace.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsServiceDiscoveryPrivateDnsNamespaceDestroy, + Steps: []resource.TestStep{ { - ResourceName: "aws_service_discovery_private_dns_namespace.test", - ImportState: true, - ImportStateIdFunc: testAccServiceDiscoveryPrivateDnsNamespaceImportStateIdFunc("aws_service_discovery_private_dns_namespace.test"), - ImportStateVerify: true, + Config: testAccServiceDiscoveryPrivateDnsNamespaceConfigDescription(rName, "test"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryPrivateDnsNamespaceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "test"), + ), }, }, }) @@ -149,7 +167,7 @@ func TestAccAWSServiceDiscoveryPrivateDnsNamespace_longname(t *testing.T) { // * https://github.com/terraform-providers/terraform-provider-aws/issues/2830 // * https://github.com/terraform-providers/terraform-provider-aws/issues/5532 func TestAccAWSServiceDiscoveryPrivateDnsNamespace_error_Overlap(t *testing.T) { - rName := acctest.RandString(5) + ".example.com" + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, @@ -164,6 +182,50 @@ func TestAccAWSServiceDiscoveryPrivateDnsNamespace_error_Overlap(t *testing.T) { }) } +func TestAccAWSServiceDiscoveryPrivateDnsNamespace_Tags(t *testing.T) { + resourceName := "aws_service_discovery_private_dns_namespace.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsServiceDiscoveryPrivateDnsNamespaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccServiceDiscoveryPrivateDnsNamespaceConfigTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryPrivateDnsNamespaceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateIdFunc: testAccServiceDiscoveryPrivateDnsNamespaceImportStateIdFunc(resourceName), + ImportStateVerify: true, + }, + { + Config: testAccServiceDiscoveryPrivateDnsNamespaceConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryPrivateDnsNamespaceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccServiceDiscoveryPrivateDnsNamespaceConfigTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryPrivateDnsNamespaceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + func testAccCheckAwsServiceDiscoveryPrivateDnsNamespaceDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).sdconn @@ -220,30 +282,47 @@ resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-service-discovery-private-dns-ns" + Name = %[1]q } } resource "aws_service_discovery_private_dns_namespace" "test" { - name = "%s" - description = "test" - vpc = "${aws_vpc.test.id}" + name = "%[1]s.tf" + vpc = "${aws_vpc.test.id}" } `, rName) } -func testAccServiceDiscoveryPrivateDnsNamespaceConfigOverlapping(topDomain string) string { +func testAccServiceDiscoveryPrivateDnsNamespaceConfigDescription(rName, description string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[2]q + } +} + +resource "aws_service_discovery_private_dns_namespace" "test" { + description = %[1]q + name = "%[2]s.tf" + vpc = "${aws_vpc.test.id}" +} +`, description, rName) +} + +func testAccServiceDiscoveryPrivateDnsNamespaceConfigOverlapping(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-service-discovery-private-dns-ns" + Name = %[1]q } } resource "aws_service_discovery_private_dns_namespace" "top" { - name = %q + name = "%[1]s.tf" vpc = "${aws_vpc.test.id}" } @@ -252,7 +331,50 @@ resource "aws_service_discovery_private_dns_namespace" "subdomain" { name = "${aws_service_discovery_private_dns_namespace.top.name}" vpc = "${aws_service_discovery_private_dns_namespace.top.vpc}" } -`, topDomain) +`, rName) +} + +func testAccServiceDiscoveryPrivateDnsNamespaceConfigTags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_service_discovery_private_dns_namespace" "test" { + name = "%[1]s.tf" + vpc = "${aws_vpc.test.id}" + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccServiceDiscoveryPrivateDnsNamespaceConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_vpc" "test" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = %[1]q + } +} + +resource "aws_service_discovery_private_dns_namespace" "test" { + name = "%[1]s.tf" + vpc = "${aws_vpc.test.id}" + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) } func testAccServiceDiscoveryPrivateDnsNamespaceImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { diff --git a/aws/resource_aws_service_discovery_public_dns_namespace.go b/aws/resource_aws_service_discovery_public_dns_namespace.go index 7536c3b73b1..f26fea7623f 100644 --- a/aws/resource_aws_service_discovery_public_dns_namespace.go +++ b/aws/resource_aws_service_discovery_public_dns_namespace.go @@ -5,8 +5,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicediscovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/servicediscovery/waiter" ) @@ -14,6 +15,7 @@ func resourceAwsServiceDiscoveryPublicDnsNamespace() *schema.Resource { return &schema.Resource{ Create: resourceAwsServiceDiscoveryPublicDnsNamespaceCreate, Read: resourceAwsServiceDiscoveryPublicDnsNamespaceRead, + Update: resourceAwsServiceDiscoveryPublicDnsNamespaceUpdate, Delete: resourceAwsServiceDiscoveryPublicDnsNamespaceDelete, Importer: &schema.ResourceImporter{ @@ -31,6 +33,7 @@ func resourceAwsServiceDiscoveryPublicDnsNamespace() *schema.Resource { Optional: true, ForceNew: true, }, + "tags": tagsSchema(), "arn": { Type: schema.TypeString, Computed: true, @@ -57,6 +60,7 @@ func resourceAwsServiceDiscoveryPublicDnsNamespaceCreate(d *schema.ResourceData, input := &servicediscovery.CreatePublicDnsNamespaceInput{ Name: aws.String(name), + Tags: keyvaluetags.New(d.Get("tags").(map[string]interface{})).IgnoreAws().ServicediscoveryTags(), CreatorRequestId: aws.String(requestId), } @@ -97,6 +101,7 @@ func resourceAwsServiceDiscoveryPublicDnsNamespaceCreate(d *schema.ResourceData, func resourceAwsServiceDiscoveryPublicDnsNamespaceRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).sdconn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig input := &servicediscovery.GetNamespaceInput{ Id: aws.String(d.Id()), @@ -111,15 +116,40 @@ func resourceAwsServiceDiscoveryPublicDnsNamespaceRead(d *schema.ResourceData, m return err } + arn := aws.StringValue(resp.Namespace.Arn) d.Set("name", resp.Namespace.Name) d.Set("description", resp.Namespace.Description) - d.Set("arn", resp.Namespace.Arn) + d.Set("arn", arn) if resp.Namespace.Properties != nil { d.Set("hosted_zone", resp.Namespace.Properties.DnsProperties.HostedZoneId) } + + tags, err := keyvaluetags.ServicediscoveryListTags(conn, arn) + + if err != nil { + return fmt.Errorf("error listing tags for resource (%s): %s", arn, err) + } + + if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) + } + return nil } +func resourceAwsServiceDiscoveryPublicDnsNamespaceUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).sdconn + + if d.HasChange("tags") { + o, n := d.GetChange("tags") + if err := keyvaluetags.ServicediscoveryUpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating Service Discovery Public DNS Namespace (%s) tags: %s", d.Id(), err) + } + } + + return resourceAwsServiceDiscoveryHttpNamespaceRead(d, meta) +} + func resourceAwsServiceDiscoveryPublicDnsNamespaceDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).sdconn diff --git a/aws/resource_aws_service_discovery_public_dns_namespace_test.go b/aws/resource_aws_service_discovery_public_dns_namespace_test.go index 424aef4a63c..c2c703ca8c1 100644 --- a/aws/resource_aws_service_discovery_public_dns_namespace_test.go +++ b/aws/resource_aws_service_discovery_public_dns_namespace_test.go @@ -3,14 +3,15 @@ package aws import ( "fmt" "log" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicediscovery" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/servicediscovery/waiter" ) @@ -94,7 +95,7 @@ func testSweepServiceDiscoveryPublicDnsNamespaces(region string) error { func TestAccAWSServiceDiscoveryPublicDnsNamespace_basic(t *testing.T) { resourceName := "aws_service_discovery_public_dns_namespace.test" - rName := acctest.RandStringFromCharSet(5, acctest.CharSetAlpha) + ".terraformtesting.com" + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, @@ -104,9 +105,11 @@ func TestAccAWSServiceDiscoveryPublicDnsNamespace_basic(t *testing.T) { { Config: testAccServiceDiscoveryPublicDnsNamespaceConfig(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsServiceDiscoveryPublicDnsNamespaceExists("aws_service_discovery_public_dns_namespace.test"), - resource.TestCheckResourceAttrSet("aws_service_discovery_public_dns_namespace.test", "arn"), - resource.TestCheckResourceAttrSet("aws_service_discovery_public_dns_namespace.test", "hosted_zone"), + testAccCheckAwsServiceDiscoveryPublicDnsNamespaceExists(resourceName), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "servicediscovery", regexp.MustCompile(`namespace/.+`)), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttrSet(resourceName, "hosted_zone"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { @@ -118,9 +121,9 @@ func TestAccAWSServiceDiscoveryPublicDnsNamespace_basic(t *testing.T) { }) } -func TestAccAWSServiceDiscoveryPublicDnsNamespace_longname(t *testing.T) { +func TestAccAWSServiceDiscoveryPublicDnsNamespace_disappears(t *testing.T) { resourceName := "aws_service_discovery_public_dns_namespace.test" - rName := acctest.RandStringFromCharSet(64-len("terraformtesting.com"), acctest.CharSetAlpha) + ".terraformtesting.com" + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, @@ -130,9 +133,50 @@ func TestAccAWSServiceDiscoveryPublicDnsNamespace_longname(t *testing.T) { { Config: testAccServiceDiscoveryPublicDnsNamespaceConfig(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsServiceDiscoveryPublicDnsNamespaceExists("aws_service_discovery_public_dns_namespace.test"), - resource.TestCheckResourceAttrSet("aws_service_discovery_public_dns_namespace.test", "arn"), - resource.TestCheckResourceAttrSet("aws_service_discovery_public_dns_namespace.test", "hosted_zone"), + testAccCheckAwsServiceDiscoveryPublicDnsNamespaceExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsServiceDiscoveryPublicDnsNamespace(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAWSServiceDiscoveryPublicDnsNamespace_Description(t *testing.T) { + resourceName := "aws_service_discovery_public_dns_namespace.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsServiceDiscoveryPublicDnsNamespaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccServiceDiscoveryPublicDnsNamespaceConfigDescription(rName, "test"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryPublicDnsNamespaceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "description", "test"), + ), + }, + }, + }) +} + +func TestAccAWSServiceDiscoveryPublicDnsNamespace_Tags(t *testing.T) { + resourceName := "aws_service_discovery_public_dns_namespace.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsServiceDiscoveryPublicDnsNamespaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccServiceDiscoveryPublicDnsNamespaceConfigTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryPublicDnsNamespaceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, { @@ -140,6 +184,23 @@ func TestAccAWSServiceDiscoveryPublicDnsNamespace_longname(t *testing.T) { ImportState: true, ImportStateVerify: true, }, + { + Config: testAccServiceDiscoveryPublicDnsNamespaceConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryPublicDnsNamespaceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccServiceDiscoveryPublicDnsNamespaceConfigTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryPublicDnsNamespaceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, }, }) } @@ -188,8 +249,41 @@ func testAccCheckAwsServiceDiscoveryPublicDnsNamespaceExists(name string) resour func testAccServiceDiscoveryPublicDnsNamespaceConfig(rName string) string { return fmt.Sprintf(` resource "aws_service_discovery_public_dns_namespace" "test" { - name = %q - description = "test" + name = "%[1]s.tf" } `, rName) } + +func testAccServiceDiscoveryPublicDnsNamespaceConfigDescription(rName, description string) string { + return fmt.Sprintf(` +resource "aws_service_discovery_public_dns_namespace" "test" { + description = %[1]q + name = "%[2]s.tf" +} +`, description, rName) +} + +func testAccServiceDiscoveryPublicDnsNamespaceConfigTags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_service_discovery_public_dns_namespace" "test" { + name = "%[1]s.tf" + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccServiceDiscoveryPublicDnsNamespaceConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_service_discovery_public_dns_namespace" "test" { + name = "%[1]s.tf" + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) +} diff --git a/aws/resource_aws_service_discovery_service.go b/aws/resource_aws_service_discovery_service.go index a898663dbcd..db0113a5924 100644 --- a/aws/resource_aws_service_discovery_service.go +++ b/aws/resource_aws_service_discovery_service.go @@ -6,8 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicediscovery" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/servicediscovery/waiter" ) @@ -127,6 +128,7 @@ func resourceAwsServiceDiscoveryService() *schema.Resource { }, }, }, + "tags": tagsSchema(), "arn": { Type: schema.TypeString, Computed: true, @@ -140,6 +142,7 @@ func resourceAwsServiceDiscoveryServiceCreate(d *schema.ResourceData, meta inter input := &servicediscovery.CreateServiceInput{ Name: aws.String(d.Get("name").(string)), + Tags: keyvaluetags.New(d.Get("tags").(map[string]interface{})).IgnoreAws().ServicediscoveryTags(), } dnsConfig := d.Get("dns_config").([]interface{}) @@ -170,13 +173,14 @@ func resourceAwsServiceDiscoveryServiceCreate(d *schema.ResourceData, meta inter return err } - d.SetId(*resp.Service.Id) - d.Set("arn", resp.Service.Arn) - return nil + d.SetId(aws.StringValue(resp.Service.Id)) + + return resourceAwsServiceDiscoveryServiceRead(d, meta) } func resourceAwsServiceDiscoveryServiceRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).sdconn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig input := &servicediscovery.GetServiceInput{ Id: aws.String(d.Id()), @@ -193,47 +197,62 @@ func resourceAwsServiceDiscoveryServiceRead(d *schema.ResourceData, meta interfa } service := resp.Service - d.Set("arn", service.Arn) + arn := aws.StringValue(service.Arn) + d.Set("arn", arn) d.Set("name", service.Name) d.Set("description", service.Description) d.Set("namespace_id", service.NamespaceId) d.Set("dns_config", flattenServiceDiscoveryDnsConfig(service.DnsConfig)) d.Set("health_check_config", flattenServiceDiscoveryHealthCheckConfig(service.HealthCheckConfig)) d.Set("health_check_custom_config", flattenServiceDiscoveryHealthCheckCustomConfig(service.HealthCheckCustomConfig)) - return nil -} -func resourceAwsServiceDiscoveryServiceUpdate(d *schema.ResourceData, meta interface{}) error { - conn := meta.(*AWSClient).sdconn + tags, err := keyvaluetags.ServicediscoveryListTags(conn, arn) - input := &servicediscovery.UpdateServiceInput{ - Id: aws.String(d.Id()), + if err != nil { + return fmt.Errorf("error listing tags for resource (%s): %s", arn, err) } - sc := &servicediscovery.ServiceChange{ - DnsConfig: expandServiceDiscoveryDnsConfigChange(d.Get("dns_config").([]interface{})[0].(map[string]interface{})), + if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) } - if d.HasChange("description") { - sc.Description = aws.String(d.Get("description").(string)) - } + return nil +} + +func resourceAwsServiceDiscoveryServiceUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).sdconn + + if d.HasChanges("description", "dns_config", "health_check_config") { + input := &servicediscovery.UpdateServiceInput{ + Id: aws.String(d.Id()), + Service: &servicediscovery.ServiceChange{ + Description: aws.String(d.Get("description").(string)), + DnsConfig: expandServiceDiscoveryDnsConfigChange(d.Get("dns_config").([]interface{})[0].(map[string]interface{})), + }, + } - if d.HasChange("health_check_config") { hcconfig := d.Get("health_check_config").([]interface{}) - sc.HealthCheckConfig = expandServiceDiscoveryHealthCheckConfig(hcconfig[0].(map[string]interface{})) - } + if len(hcconfig) > 0 { + input.Service.HealthCheckConfig = expandServiceDiscoveryHealthCheckConfig(hcconfig[0].(map[string]interface{})) + } - input.Service = sc + output, err := conn.UpdateService(input) - output, err := conn.UpdateService(input) + if err != nil { + return fmt.Errorf("error updating Service Discovery Service (%s): %w", d.Id(), err) + } - if err != nil { - return fmt.Errorf("error updating Service Discovery Service (%s): %w", d.Id(), err) + if output != nil && output.OperationId != nil { + if _, err := waiter.OperationSuccess(conn, aws.StringValue(output.OperationId)); err != nil { + return fmt.Errorf("error waiting for Service Discovery Service (%s) update: %w", d.Id(), err) + } + } } - if output != nil && output.OperationId != nil { - if _, err := waiter.OperationSuccess(conn, aws.StringValue(output.OperationId)); err != nil { - return fmt.Errorf("error waiting for Service Discovery Service (%s) update: %w", d.Id(), err) + if d.HasChange("tags") { + o, n := d.GetChange("tags") + if err := keyvaluetags.ServicediscoveryUpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating Service Discovery Private DNS Namespace (%s) tags: %s", d.Id(), err) } } diff --git a/aws/resource_aws_service_discovery_service_test.go b/aws/resource_aws_service_discovery_service_test.go index 024f04aa654..11657827e14 100644 --- a/aws/resource_aws_service_discovery_service_test.go +++ b/aws/resource_aws_service_discovery_service_test.go @@ -3,14 +3,15 @@ package aws import ( "fmt" "log" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicediscovery" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -114,7 +115,7 @@ func testSweepServiceDiscoveryServices(region string) error { func TestAccAWSServiceDiscoveryService_private(t *testing.T) { resourceName := "aws_service_discovery_service.test" - rName := acctest.RandString(5) + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSServiceDiscovery(t) }, @@ -130,7 +131,9 @@ func TestAccAWSServiceDiscoveryService_private(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "dns_config.0.dns_records.0.type", "A"), resource.TestCheckResourceAttr(resourceName, "dns_config.0.dns_records.0.ttl", "5"), resource.TestCheckResourceAttr(resourceName, "dns_config.0.routing_policy", "MULTIVALUE"), - resource.TestCheckResourceAttrSet(resourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "servicediscovery", regexp.MustCompile(`service/.+`)), ), }, { @@ -147,7 +150,9 @@ func TestAccAWSServiceDiscoveryService_private(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "dns_config.0.dns_records.0.ttl", "10"), resource.TestCheckResourceAttr(resourceName, "dns_config.0.dns_records.1.type", "AAAA"), resource.TestCheckResourceAttr(resourceName, "dns_config.0.dns_records.1.ttl", "5"), - resource.TestCheckResourceAttrSet(resourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "description", "test"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "servicediscovery", regexp.MustCompile(`service/.+`)), ), }, }, @@ -155,7 +160,7 @@ func TestAccAWSServiceDiscoveryService_private(t *testing.T) { } func TestAccAWSServiceDiscoveryService_public(t *testing.T) { - rName := acctest.RandString(5) + rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_service_discovery_service.test" resource.ParallelTest(t, resource.TestCase{ @@ -171,7 +176,9 @@ func TestAccAWSServiceDiscoveryService_public(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "health_check_config.0.failure_threshold", "5"), resource.TestCheckResourceAttr(resourceName, "health_check_config.0.resource_path", "/path"), resource.TestCheckResourceAttr(resourceName, "dns_config.0.routing_policy", "WEIGHTED"), - resource.TestCheckResourceAttrSet(resourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "description", "test"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "servicediscovery", regexp.MustCompile(`service/.+`)), ), }, { @@ -186,7 +193,19 @@ func TestAccAWSServiceDiscoveryService_public(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "health_check_config.0.type", "HTTP"), resource.TestCheckResourceAttr(resourceName, "health_check_config.0.failure_threshold", "3"), resource.TestCheckResourceAttr(resourceName, "health_check_config.0.resource_path", "/updated-path"), - resource.TestCheckResourceAttrSet(resourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "description", "test"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "servicediscovery", regexp.MustCompile(`service/.+`)), + ), + }, + { + Config: testAccServiceDiscoveryServiceConfig_public_update_noHealthCheckConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "health_check_config.#", "0"), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "servicediscovery", regexp.MustCompile(`service/.+`)), ), }, }, @@ -194,7 +213,7 @@ func TestAccAWSServiceDiscoveryService_public(t *testing.T) { } func TestAccAWSServiceDiscoveryService_http(t *testing.T) { - rName := acctest.RandStringFromCharSet(5, acctest.CharSetAlpha) + rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(8, acctest.CharSetAlpha)) resourceName := "aws_service_discovery_service.test" resource.ParallelTest(t, resource.TestCase{ @@ -207,7 +226,8 @@ func TestAccAWSServiceDiscoveryService_http(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAwsServiceDiscoveryServiceExists(resourceName), resource.TestCheckResourceAttrSet(resourceName, "namespace_id"), - resource.TestCheckResourceAttrSet(resourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "servicediscovery", regexp.MustCompile(`service/.+`)), ), }, { @@ -219,6 +239,70 @@ func TestAccAWSServiceDiscoveryService_http(t *testing.T) { }) } +func TestAccAWSServiceDiscoveryService_disappears(t *testing.T) { + rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(8, acctest.CharSetAlpha)) + resourceName := "aws_service_discovery_service.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsServiceDiscoveryServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccServiceDiscoveryServiceConfig_http(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryServiceExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsServiceDiscoveryService(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAWSServiceDiscoveryService_Tags(t *testing.T) { + rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(8, acctest.CharSetAlpha)) + resourceName := "aws_service_discovery_service.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsServiceDiscoveryServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccServiceDiscoveryServiceConfigTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccServiceDiscoveryServiceConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccServiceDiscoveryServiceConfigTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsServiceDiscoveryServiceExists(resourceName), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + func testAccCheckAwsServiceDiscoveryServiceDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).sdconn @@ -266,18 +350,17 @@ resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-service-discovery-service-private" + Name = %[1]q } } resource "aws_service_discovery_private_dns_namespace" "test" { - name = "tf-sd-%s.terraform.local" - description = "test" - vpc = "${aws_vpc.test.id}" + name = "%[1]s.tf" + vpc = "${aws_vpc.test.id}" } resource "aws_service_discovery_service" "test" { - name = "tf-sd-%s" + name = %[1]q dns_config { namespace_id = "${aws_service_discovery_private_dns_namespace.test.id}" @@ -289,10 +372,10 @@ resource "aws_service_discovery_service" "test" { } health_check_custom_config { - failure_threshold = %d + failure_threshold = %[2]d } } -`, rName, rName, th) +`, rName, th) } func testAccServiceDiscoveryServiceConfig_private_update(rName string, th int) string { @@ -301,18 +384,19 @@ resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { - Name = "terraform-testacc-service-discovery-service-private" + Name = %[1]q } } resource "aws_service_discovery_private_dns_namespace" "test" { - name = "tf-sd-%s.terraform.local" - description = "test" + name = "%[1]s.tf" vpc = "${aws_vpc.test.id}" } resource "aws_service_discovery_service" "test" { - name = "tf-sd-%s" + name = %[1]q + + description = "test" dns_config { namespace_id = "${aws_service_discovery_private_dns_namespace.test.id}" @@ -331,21 +415,22 @@ resource "aws_service_discovery_service" "test" { } health_check_custom_config { - failure_threshold = %d + failure_threshold = %[2]d } } -`, rName, rName, th) +`, rName, th) } func testAccServiceDiscoveryServiceConfig_public(rName string, th int, path string) string { return fmt.Sprintf(` resource "aws_service_discovery_public_dns_namespace" "test" { - name = "tf-sd-%s.terraform.com" - description = "test" + name = "%[1]s.tf" } resource "aws_service_discovery_service" "test" { - name = "tf-sd-%s" + name = %[1]q + + description = "test" dns_config { namespace_id = "${aws_service_discovery_public_dns_namespace.test.id}" @@ -359,24 +444,81 @@ resource "aws_service_discovery_service" "test" { } health_check_config { - failure_threshold = %d - resource_path = "%s" + failure_threshold = %[2]d + resource_path = %[3]q type = "HTTP" } } -`, rName, rName, th, path) +`, rName, th, path) +} + +func testAccServiceDiscoveryServiceConfig_public_update_noHealthCheckConfig(rName string) string { + return fmt.Sprintf(` +resource "aws_service_discovery_public_dns_namespace" "test" { + name = "%[1]s.tf" +} + +resource "aws_service_discovery_service" "test" { + name = %[1]q + + dns_config { + namespace_id = "${aws_service_discovery_public_dns_namespace.test.id}" + + dns_records { + ttl = 5 + type = "A" + } + + routing_policy = "WEIGHTED" + } +} +`, rName) } func testAccServiceDiscoveryServiceConfig_http(rName string) string { return fmt.Sprintf(` resource "aws_service_discovery_http_namespace" "test" { - name = "tf-sd-ns-%s" - description = "test" + name = %[1]q +} + +resource "aws_service_discovery_service" "test" { + name = %[1]q + namespace_id = "${aws_service_discovery_http_namespace.test.id}" +} +`, rName) +} + +func testAccServiceDiscoveryServiceConfigTags1(rName, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_service_discovery_http_namespace" "test" { + name = %[1]q +} + +resource "aws_service_discovery_service" "test" { + name = %[1]q + namespace_id = "${aws_service_discovery_http_namespace.test.id}" + + tags = { + %[2]q = %[3]q + } +} +`, rName, tagKey1, tagValue1) +} + +func testAccServiceDiscoveryServiceConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_service_discovery_http_namespace" "test" { + name = %[1]q } resource "aws_service_discovery_service" "test" { - name = "tf-sd-%s" + name = %[1]q namespace_id = "${aws_service_discovery_http_namespace.test.id}" + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } } -`, rName, rName) +`, rName, tagKey1, tagValue1, tagKey2, tagValue2) } diff --git a/aws/resource_aws_servicecatalog_portfolio.go b/aws/resource_aws_servicecatalog_portfolio.go index 71348415293..50b72fe782f 100644 --- a/aws/resource_aws_servicecatalog_portfolio.go +++ b/aws/resource_aws_servicecatalog_portfolio.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/servicecatalog" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_servicecatalog_portfolio_test.go b/aws/resource_aws_servicecatalog_portfolio_test.go index 63e51594c39..8ae0229b81a 100644 --- a/aws/resource_aws_servicecatalog_portfolio_test.go +++ b/aws/resource_aws_servicecatalog_portfolio_test.go @@ -7,14 +7,14 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicecatalog" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "testing" ) -func TestAccAWSServiceCatalogPortfolio_Basic(t *testing.T) { +func TestAccAWSServiceCatalogPortfolio_basic(t *testing.T) { resourceName := "aws_servicecatalog_portfolio.test" name := acctest.RandString(5) var dpo servicecatalog.DescribePortfolioOutput diff --git a/aws/resource_aws_servicequotas_service_quota.go b/aws/resource_aws_servicequotas_service_quota.go index 6452a3ec626..630b4b24674 100644 --- a/aws/resource_aws_servicequotas_service_quota.go +++ b/aws/resource_aws_servicequotas_service_quota.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/servicequotas" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsServiceQuotasServiceQuota() *schema.Resource { diff --git a/aws/resource_aws_servicequotas_service_quota_test.go b/aws/resource_aws_servicequotas_service_quota_test.go index 2ef3d3f6d88..9f12f5cb9aa 100644 --- a/aws/resource_aws_servicequotas_service_quota_test.go +++ b/aws/resource_aws_servicequotas_service_quota_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/servicequotas" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) // This resource is different than many since quotas are pre-existing diff --git a/aws/resource_aws_ses_active_receipt_rule_set.go b/aws/resource_aws_ses_active_receipt_rule_set.go index a06faa8b988..ccdd8ff2743 100644 --- a/aws/resource_aws_ses_active_receipt_rule_set.go +++ b/aws/resource_aws_ses_active_receipt_rule_set.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsSesActiveReceiptRuleSet() *schema.Resource { @@ -51,6 +51,11 @@ func resourceAwsSesActiveReceiptRuleSetRead(d *schema.ResourceData, meta interfa response, err := conn.DescribeActiveReceiptRuleSet(describeOpts) if err != nil { + if isAWSErr(err, ses.ErrCodeRuleSetDoesNotExistException, "") { + log.Printf("[WARN] SES Receipt Rule Set (%s) belonging to SES Active Receipt Rule Set not found, removing from state", d.Id()) + d.SetId("") + return nil + } return err } diff --git a/aws/resource_aws_ses_active_receipt_rule_set_test.go b/aws/resource_aws_ses_active_receipt_rule_set_test.go index 5beecdef39a..44f5281b807 100644 --- a/aws/resource_aws_ses_active_receipt_rule_set_test.go +++ b/aws/resource_aws_ses_active_receipt_rule_set_test.go @@ -2,14 +2,19 @@ package aws import ( "fmt" + "github.com/aws/aws-sdk-go/aws" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "testing" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSSESActiveReceiptRuleSet_basic(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_ses_active_receipt_rule_set.test" + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -19,15 +24,39 @@ func TestAccAWSSESActiveReceiptRuleSet_basic(t *testing.T) { CheckDestroy: testAccCheckSESActiveReceiptRuleSetDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSESActiveReceiptRuleSetConfig, + Config: testAccAWSSESActiveReceiptRuleSetConfig(rName), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsSESActiveReceiptRuleSetExists("aws_ses_active_receipt_rule_set.test"), + testAccCheckAwsSESActiveReceiptRuleSetExists(resourceName), ), }, }, }) } +func TestAccAWSSESActiveReceiptRuleSet_disappears(t *testing.T) { + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_ses_active_receipt_rule_set.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + testAccPreCheckAWSSES(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckSESActiveReceiptRuleSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSSESActiveReceiptRuleSetConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsSESActiveReceiptRuleSetExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsSesActiveReceiptRuleSet(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckSESActiveReceiptRuleSetDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).sesconn @@ -41,7 +70,7 @@ func testAccCheckSESActiveReceiptRuleSetDestroy(s *terraform.State) error { return err } - if response.Metadata != nil && *response.Metadata.Name == "test-receipt-rule" { + if response.Metadata != nil && (aws.StringValue(response.Metadata.Name) == rs.Primary.ID) { return fmt.Errorf("Active receipt rule set still exists") } @@ -69,20 +98,22 @@ func testAccCheckAwsSESActiveReceiptRuleSetExists(n string) resource.TestCheckFu return err } - if *response.Metadata.Name != "test-receipt-rule" { - return fmt.Errorf("The active receipt rule set (%s) was not set to test-receipt-rule", *response.Metadata.Name) + if response.Metadata != nil && (aws.StringValue(response.Metadata.Name) != rs.Primary.ID) { + return fmt.Errorf("The active receipt rule set (%s) was not set to %s", aws.StringValue(response.Metadata.Name), rs.Primary.ID) } return nil } } -const testAccAWSSESActiveReceiptRuleSetConfig = ` +func testAccAWSSESActiveReceiptRuleSetConfig(name string) string { + return fmt.Sprintf(` resource "aws_ses_receipt_rule_set" "test" { - rule_set_name = "test-receipt-rule" + rule_set_name = "%s" } resource "aws_ses_active_receipt_rule_set" "test" { - rule_set_name = "${aws_ses_receipt_rule_set.test.rule_set_name}" + rule_set_name = "${aws_ses_receipt_rule_set.test.rule_set_name}" +} +`, name) } -` diff --git a/aws/resource_aws_ses_configuration_set.go b/aws/resource_aws_ses_configuration_set.go index 3e2ed511aad..883a132335d 100644 --- a/aws/resource_aws_ses_configuration_set.go +++ b/aws/resource_aws_ses_configuration_set.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsSesConfigurationSet() *schema.Resource { @@ -50,19 +50,24 @@ func resourceAwsSesConfigurationSetCreate(d *schema.ResourceData, meta interface } func resourceAwsSesConfigurationSetRead(d *schema.ResourceData, meta interface{}) error { - configurationSetExists, err := findConfigurationSet(d.Id(), nil, meta) + conn := meta.(*AWSClient).sesconn - if !configurationSetExists { - log.Printf("[WARN] SES Configuration Set (%s) not found", d.Id()) - d.SetId("") - return nil + configSetInput := &ses.DescribeConfigurationSetInput{ + ConfigurationSetName: aws.String(d.Id()), } + response, err := conn.DescribeConfigurationSet(configSetInput) + if err != nil { + if isAWSErr(err, ses.ErrCodeConfigurationSetDoesNotExistException, "") { + log.Printf("[WARN] SES Configuration Set (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } return err } - d.Set("name", d.Id()) + d.Set("name", aws.StringValue(response.ConfigurationSet.Name)) return nil } @@ -77,30 +82,3 @@ func resourceAwsSesConfigurationSetDelete(d *schema.ResourceData, meta interface return err } - -func findConfigurationSet(name string, token *string, meta interface{}) (bool, error) { - conn := meta.(*AWSClient).sesconn - - configurationSetExists := false - - listOpts := &ses.ListConfigurationSetsInput{ - NextToken: token, - } - - response, err := conn.ListConfigurationSets(listOpts) - for _, element := range response.ConfigurationSets { - if *element.Name == name { - configurationSetExists = true - } - } - - if err != nil && !configurationSetExists && response.NextToken != nil { - configurationSetExists, err = findConfigurationSet(name, response.NextToken, meta) - } - - if err != nil { - return false, err - } - - return configurationSetExists, nil -} diff --git a/aws/resource_aws_ses_configuration_set_test.go b/aws/resource_aws_ses_configuration_set_test.go index 1999f22bca6..e26f52856b5 100644 --- a/aws/resource_aws_ses_configuration_set_test.go +++ b/aws/resource_aws_ses_configuration_set_test.go @@ -2,15 +2,74 @@ package aws import ( "fmt" + "log" "testing" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) +func init() { + resource.AddTestSweepers("aws_ses_configuration_set", &resource.Sweeper{ + Name: "aws_ses_configuration_set", + F: testSweepSesConfigurationSets, + }) +} + +func testSweepSesConfigurationSets(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).sesconn + input := &ses.ListConfigurationSetsInput{} + var sweeperErrs *multierror.Error + + for { + output, err := conn.ListConfigurationSets(input) + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping SES Configuration Sets sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors + } + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving SES Configuration Sets: %w", err)) + return sweeperErrs + } + + for _, configurationSet := range output.ConfigurationSets { + name := aws.StringValue(configurationSet.Name) + + log.Printf("[INFO] Deleting SES Configuration Set: %s", name) + _, err := conn.DeleteConfigurationSet(&ses.DeleteConfigurationSetInput{ + ConfigurationSetName: aws.String(name), + }) + if isAWSErr(err, ses.ErrCodeConfigurationSetDoesNotExistException, "") { + continue + } + if err != nil { + sweeperErr := fmt.Errorf("error deleting SES Configuration Set (%s): %w", name, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + } + + if aws.StringValue(output.NextToken) == "" { + break + } + input.NextToken = output.NextToken + } + + return sweeperErrs.ErrorOrNil() +} + func TestAccAWSSESConfigurationSet_basic(t *testing.T) { + var escRandomInteger = acctest.RandInt() + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) @@ -20,7 +79,7 @@ func TestAccAWSSESConfigurationSet_basic(t *testing.T) { CheckDestroy: testAccCheckSESConfigurationSetDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSESConfigurationSetConfig, + Config: testAccAWSSESConfigurationSetConfig(escRandomInteger), Check: resource.ComposeTestCheckFunc( testAccCheckAwsSESConfigurationSetExists("aws_ses_configuration_set.test"), ), @@ -34,36 +93,6 @@ func TestAccAWSSESConfigurationSet_basic(t *testing.T) { }) } -func testAccCheckSESConfigurationSetDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).sesconn - - for _, rs := range s.RootModule().Resources { - if rs.Type != "aws_ses_configuration_set" { - continue - } - - response, err := conn.ListConfigurationSets(&ses.ListConfigurationSetsInput{}) - if err != nil { - return err - } - - found := false - for _, element := range response.ConfigurationSets { - if *element.Name == fmt.Sprintf("some-configuration-set-%d", escRandomInteger) { - found = true - } - } - - if found { - return fmt.Errorf("The configuration set still exists") - } - - } - - return nil - -} - func testAccCheckAwsSESConfigurationSetExists(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] @@ -77,29 +106,48 @@ func testAccCheckAwsSESConfigurationSetExists(n string) resource.TestCheckFunc { conn := testAccProvider.Meta().(*AWSClient).sesconn - response, err := conn.ListConfigurationSets(&ses.ListConfigurationSetsInput{}) + response, err := conn.DescribeConfigurationSet(&ses.DescribeConfigurationSetInput{ + ConfigurationSetName: aws.String(rs.Primary.ID), + }) + if err != nil { return err } - found := false - for _, element := range response.ConfigurationSets { - if *element.Name == fmt.Sprintf("some-configuration-set-%d", escRandomInteger) { - found = true - } + if aws.StringValue(response.ConfigurationSet.Name) != rs.Primary.ID { + return fmt.Errorf("The configuration set was not created") } + return nil - if !found { - return fmt.Errorf("The configuration set was not created") + } +} + +func testAccCheckSESConfigurationSetDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).sesconn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_ses_configuration_set" { + continue } - return nil + _, err := conn.DescribeConfigurationSet(&ses.DescribeConfigurationSetInput{ + ConfigurationSetName: aws.String(rs.Primary.ID), + }) + + if err != nil { + if isAWSErr(err, ses.ErrCodeConfigurationSetDoesNotExistException, "") { + return nil + } + return err + } } + return nil } -var escRandomInteger = acctest.RandInt() -var testAccAWSSESConfigurationSetConfig = fmt.Sprintf(` +func testAccAWSSESConfigurationSetConfig(escRandomInteger int) string { + return fmt.Sprintf(` resource "aws_ses_configuration_set" "test" { name = "some-configuration-set-%d" } `, escRandomInteger) +} diff --git a/aws/resource_aws_ses_domain_dkim.go b/aws/resource_aws_ses_domain_dkim.go index 3c101f467e9..e3e89ccd395 100644 --- a/aws/resource_aws_ses_domain_dkim.go +++ b/aws/resource_aws_ses_domain_dkim.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsSesDomainDkim() *schema.Resource { diff --git a/aws/resource_aws_ses_domain_dkim_test.go b/aws/resource_aws_ses_domain_dkim_test.go index a372a47d607..bb2de2924aa 100644 --- a/aws/resource_aws_ses_domain_dkim_test.go +++ b/aws/resource_aws_ses_domain_dkim_test.go @@ -8,12 +8,13 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSSESDomainDkim_basic(t *testing.T) { + resourceName := "aws_ses_domain_dkim.test" domain := fmt.Sprintf( "%s.terraformtesting.com", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum)) @@ -29,8 +30,8 @@ func TestAccAWSSESDomainDkim_basic(t *testing.T) { { Config: fmt.Sprintf(testAccAwsSESDomainDkimConfig, domain), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsSESDomainDkimExists("aws_ses_domain_dkim.test"), - testAccCheckAwsSESDomainDkimTokens("aws_ses_domain_dkim.test", domain), + testAccCheckAwsSESDomainDkimExists(resourceName), + testAccCheckAwsSESDomainDkimTokens(resourceName), ), }, }, @@ -99,7 +100,7 @@ func testAccCheckAwsSESDomainDkimExists(n string) resource.TestCheckFunc { } } -func testAccCheckAwsSESDomainDkimTokens(n string, domain string) resource.TestCheckFunc { +func testAccCheckAwsSESDomainDkimTokens(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs := s.RootModule().Resources[n] diff --git a/aws/resource_aws_ses_domain_identity.go b/aws/resource_aws_ses_domain_identity.go index 4dd77bd63e1..f234a005160 100644 --- a/aws/resource_aws_ses_domain_identity.go +++ b/aws/resource_aws_ses_domain_identity.go @@ -3,12 +3,13 @@ package aws import ( "fmt" "log" - "strings" + "regexp" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsSesDomainIdentity() *schema.Resource { @@ -26,12 +27,10 @@ func resourceAwsSesDomainIdentity() *schema.Resource { Computed: true, }, "domain": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: func(v interface{}) string { - return strings.TrimSuffix(v.(string), ".") - }, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringDoesNotMatch(regexp.MustCompile(`\.$`), "cannot end with a period"), }, "verification_token": { Type: schema.TypeString, @@ -45,7 +44,6 @@ func resourceAwsSesDomainIdentityCreate(d *schema.ResourceData, meta interface{} conn := meta.(*AWSClient).sesconn domainName := d.Get("domain").(string) - domainName = strings.TrimSuffix(domainName, ".") createOpts := &ses.VerifyDomainIdentityInput{ Domain: aws.String(domainName), diff --git a/aws/resource_aws_ses_domain_identity_test.go b/aws/resource_aws_ses_domain_identity_test.go index f7249b221d8..e9491ae2664 100644 --- a/aws/resource_aws_ses_domain_identity_test.go +++ b/aws/resource_aws_ses_domain_identity_test.go @@ -2,17 +2,71 @@ package aws import ( "fmt" + "log" + "regexp" "strings" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) +func init() { + resource.AddTestSweepers("aws_ses_domain_identity", &resource.Sweeper{ + Name: "aws_ses_domain_identity", + F: func(region string) error { return testSweepSesIdentities(region, ses.IdentityTypeDomain) }, + }) +} + +func testSweepSesIdentities(region, identityType string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).sesconn + input := &ses.ListIdentitiesInput{ + IdentityType: aws.String(identityType), + } + var sweeperErrs *multierror.Error + + err = conn.ListIdentitiesPages(input, func(page *ses.ListIdentitiesOutput, isLast bool) bool { + if page == nil { + return !isLast + } + + for _, identity := range page.Identities { + identity := aws.StringValue(identity) + + log.Printf("[INFO] Deleting SES Identity: %s", identity) + _, err = conn.DeleteIdentity(&ses.DeleteIdentityInput{ + Identity: aws.String(identity), + }) + if err != nil { + sweeperErr := fmt.Errorf("error deleting SES Identity (%s): %w", identity, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + } + + return !isLast + }) + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping SES Identities sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors + } + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving SES Identities: %w", err)) + } + + return sweeperErrs.ErrorOrNil() +} + func TestAccAWSSESDomainIdentity_basic(t *testing.T) { domain := fmt.Sprintf( "%s.terraformtesting.com", @@ -56,6 +110,8 @@ func TestAccAWSSESDomainIdentity_disappears(t *testing.T) { }) } +// TestAccAWSSESDomainIdentity_trailingPeriod updated in 3.0 to account for domain plan-time validation +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/13510 func TestAccAWSSESDomainIdentity_trailingPeriod(t *testing.T) { domain := fmt.Sprintf( "%s.terraformtesting.com.", @@ -67,11 +123,8 @@ func TestAccAWSSESDomainIdentity_trailingPeriod(t *testing.T) { CheckDestroy: testAccCheckAwsSESDomainIdentityDestroy, Steps: []resource.TestStep{ { - Config: testAccAwsSESDomainIdentityConfig(domain), - Check: resource.ComposeTestCheckFunc( - testAccCheckAwsSESDomainIdentityExists("aws_ses_domain_identity.test"), - testAccCheckAwsSESDomainIdentityArn("aws_ses_domain_identity.test", domain), - ), + Config: testAccAwsSESDomainIdentityConfig(domain), + ExpectError: regexp.MustCompile(`invalid value for domain \(cannot end with a period\)`), }, }, }) diff --git a/aws/resource_aws_ses_domain_identity_verification.go b/aws/resource_aws_ses_domain_identity_verification.go index a14d0424fd0..a8f9704c773 100644 --- a/aws/resource_aws_ses_domain_identity_verification.go +++ b/aws/resource_aws_ses_domain_identity_verification.go @@ -3,14 +3,15 @@ package aws import ( "fmt" "log" - "strings" + "regexp" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsSesDomainIdentityVerification() *schema.Resource { @@ -25,12 +26,10 @@ func resourceAwsSesDomainIdentityVerification() *schema.Resource { Computed: true, }, "domain": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - StateFunc: func(v interface{}) string { - return strings.TrimSuffix(v.(string), ".") - }, + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringDoesNotMatch(regexp.MustCompile(`\.$`), "cannot end with a period"), }, }, Timeouts: &schema.ResourceTimeout{ @@ -56,7 +55,7 @@ func getAwsSesIdentityVerificationAttributes(conn *ses.SES, domainName string) ( func resourceAwsSesDomainIdentityVerificationCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).sesconn - domainName := strings.TrimSuffix(d.Get("domain").(string), ".") + domainName := d.Get("domain").(string) err := resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError { att, err := getAwsSesIdentityVerificationAttributes(conn, domainName) if err != nil { diff --git a/aws/resource_aws_ses_domain_identity_verification_test.go b/aws/resource_aws_ses_domain_identity_verification_test.go index 0960d3b1a06..ab843bfdec6 100644 --- a/aws/resource_aws_ses_domain_identity_verification_test.go +++ b/aws/resource_aws_ses_domain_identity_verification_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func testAccAwsSesDomainIdentityDomainFromEnv(t *testing.T) string { diff --git a/aws/resource_aws_ses_domain_mail_from.go b/aws/resource_aws_ses_domain_mail_from.go index c7d58429579..ff6060220c4 100644 --- a/aws/resource_aws_ses_domain_mail_from.go +++ b/aws/resource_aws_ses_domain_mail_from.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsSesDomainMailFrom() *schema.Resource { diff --git a/aws/resource_aws_ses_domain_mail_from_test.go b/aws/resource_aws_ses_domain_mail_from_test.go index 2ce388f60a5..2d4451656d4 100644 --- a/aws/resource_aws_ses_domain_mail_from_test.go +++ b/aws/resource_aws_ses_domain_mail_from_test.go @@ -6,9 +6,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSSESDomainMailFrom_basic(t *testing.T) { diff --git a/aws/resource_aws_ses_email_identity.go b/aws/resource_aws_ses_email_identity.go index 15d218ab34c..b9f02173f7f 100644 --- a/aws/resource_aws_ses_email_identity.go +++ b/aws/resource_aws_ses_email_identity.go @@ -8,7 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsSesEmailIdentity() *schema.Resource { diff --git a/aws/resource_aws_ses_email_identity_test.go b/aws/resource_aws_ses_email_identity_test.go index 7104cf1b26e..0fa5bcc595f 100644 --- a/aws/resource_aws_ses_email_identity_test.go +++ b/aws/resource_aws_ses_email_identity_test.go @@ -8,11 +8,18 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) +func init() { + resource.AddTestSweepers("aws_ses_email_identity", &resource.Sweeper{ + Name: "aws_ses_email_identity", + F: func(region string) error { return testSweepSesIdentities(region, ses.IdentityTypeEmailAddress) }, + }) +} + func TestAccAWSSESEmailIdentity_basic(t *testing.T) { email := fmt.Sprintf( "%s@terraformtesting.com", diff --git a/aws/resource_aws_ses_event_destination.go b/aws/resource_aws_ses_event_destination.go index e82c806f04c..83dd660a7b3 100644 --- a/aws/resource_aws_ses_event_destination.go +++ b/aws/resource_aws_ses_event_destination.go @@ -3,11 +3,12 @@ package aws import ( "fmt" "log" + "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsSesEventDestination() *schema.Resource { @@ -16,7 +17,7 @@ func resourceAwsSesEventDestination() *schema.Resource { Read: resourceAwsSesEventDestinationRead, Delete: resourceAwsSesEventDestinationDelete, Importer: &schema.ResourceImporter{ - State: schema.ImportStatePassthrough, + State: resourceAwsSesEventDestinationImport, }, Schema: map[string]*schema.Schema{ @@ -90,7 +91,7 @@ func resourceAwsSesEventDestination() *schema.Resource { }, "kinesis_destination": { - Type: schema.TypeSet, + Type: schema.TypeList, Optional: true, ForceNew: true, MaxItems: 1, @@ -111,7 +112,7 @@ func resourceAwsSesEventDestination() *schema.Resource { }, "sns_destination": { - Type: schema.TypeSet, + Type: schema.TypeList, MaxItems: 1, Optional: true, ForceNew: true, @@ -155,7 +156,7 @@ func resourceAwsSesEventDestinationCreate(d *schema.ResourceData, meta interface } if v, ok := d.GetOk("kinesis_destination"); ok { - destination := v.(*schema.Set).List() + destination := v.([]interface{}) kinesis := destination[0].(map[string]interface{}) createOpts.EventDestination.KinesisFirehoseDestination = &ses.KinesisFirehoseDestination{ @@ -166,7 +167,7 @@ func resourceAwsSesEventDestinationCreate(d *schema.ResourceData, meta interface } if v, ok := d.GetOk("sns_destination"); ok { - destination := v.(*schema.Set).List() + destination := v.([]interface{}) sns := destination[0].(map[string]interface{}) createOpts.EventDestination.SNSDestination = &ses.SNSDestination{ TopicARN: aws.String(sns["topic_arn"].(string)), @@ -186,6 +187,52 @@ func resourceAwsSesEventDestinationCreate(d *schema.ResourceData, meta interface } func resourceAwsSesEventDestinationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).sesconn + + configurationSetName := d.Get("configuration_set_name").(string) + input := &ses.DescribeConfigurationSetInput{ + ConfigurationSetAttributeNames: aws.StringSlice([]string{ses.ConfigurationSetAttributeEventDestinations}), + ConfigurationSetName: aws.String(configurationSetName), + } + + output, err := conn.DescribeConfigurationSet(input) + if isAWSErr(err, ses.ErrCodeConfigurationSetDoesNotExistException, "") { + log.Printf("[WARN] SES Configuration Set (%s) not found, removing from state", configurationSetName) + d.SetId("") + return nil + } + if err != nil { + return fmt.Errorf("error reading SES Configuration Set Event Destination (%s): %w", d.Id(), err) + } + + var thisEventDestination *ses.EventDestination + for _, eventDestination := range output.EventDestinations { + if aws.StringValue(eventDestination.Name) == d.Id() { + thisEventDestination = eventDestination + break + } + } + if thisEventDestination == nil { + log.Printf("[WARN] SES Configuration Set Event Destination (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + d.Set("configuration_set_name", output.ConfigurationSet.Name) + d.Set("enabled", thisEventDestination.Enabled) + d.Set("name", thisEventDestination.Name) + if err := d.Set("cloudwatch_destination", flattenSesCloudWatchDestination(thisEventDestination.CloudWatchDestination)); err != nil { + return fmt.Errorf("error setting cloudwatch_destination: %w", err) + } + if err := d.Set("kinesis_destination", flattenSesKinesisFirehoseDestination(thisEventDestination.KinesisFirehoseDestination)); err != nil { + return fmt.Errorf("error setting kinesis_destination: %w", err) + } + if err := d.Set("matching_types", flattenStringSet(thisEventDestination.MatchingEventTypes)); err != nil { + return fmt.Errorf("error setting matching_types: %w", err) + } + if err := d.Set("sns_destination", flattenSesSnsDestination(thisEventDestination.SNSDestination)); err != nil { + return fmt.Errorf("error setting sns_destination: %w", err) + } return nil } @@ -202,6 +249,22 @@ func resourceAwsSesEventDestinationDelete(d *schema.ResourceData, meta interface return err } +func resourceAwsSesEventDestinationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + parts := strings.Split(d.Id(), "/") + if len(parts) != 2 { + return []*schema.ResourceData{}, fmt.Errorf("Wrong format of resource: %s. Please follow 'configuration-set-name/event-destination-name'", d.Id()) + } + + configurationSetName := parts[0] + eventDestinationName := parts[1] + log.Printf("[DEBUG] Importing SES event destination %s from configuration set %s", eventDestinationName, configurationSetName) + + d.SetId(eventDestinationName) + d.Set("configuration_set_name", configurationSetName) + + return []*schema.ResourceData{d}, nil +} + func generateCloudWatchDestination(v []interface{}) []*ses.CloudWatchDimensionConfiguration { b := make([]*ses.CloudWatchDimensionConfiguration, len(v)) @@ -217,3 +280,48 @@ func generateCloudWatchDestination(v []interface{}) []*ses.CloudWatchDimensionCo return b } + +func flattenSesCloudWatchDestination(destination *ses.CloudWatchDestination) []interface{} { + if destination == nil { + return []interface{}{} + } + + vDimensionConfigurations := []interface{}{} + + for _, dimensionConfiguration := range destination.DimensionConfigurations { + mDimensionConfiguration := map[string]interface{}{ + "default_value": aws.StringValue(dimensionConfiguration.DefaultDimensionValue), + "dimension_name": aws.StringValue(dimensionConfiguration.DimensionName), + "value_source": aws.StringValue(dimensionConfiguration.DimensionValueSource), + } + + vDimensionConfigurations = append(vDimensionConfigurations, mDimensionConfiguration) + } + + return vDimensionConfigurations +} + +func flattenSesKinesisFirehoseDestination(destination *ses.KinesisFirehoseDestination) []interface{} { + if destination == nil { + return []interface{}{} + } + + mDestination := map[string]interface{}{ + "role_arn": aws.StringValue(destination.IAMRoleARN), + "stream_arn": aws.StringValue(destination.DeliveryStreamARN), + } + + return []interface{}{mDestination} +} + +func flattenSesSnsDestination(destination *ses.SNSDestination) []interface{} { + if destination == nil { + return []interface{}{} + } + + mDestination := map[string]interface{}{ + "topic_arn": aws.StringValue(destination.TopicARN), + } + + return []interface{}{mDestination} +} diff --git a/aws/resource_aws_ses_event_destination_test.go b/aws/resource_aws_ses_event_destination_test.go index 877be95b087..d7741323378 100644 --- a/aws/resource_aws_ses_event_destination_test.go +++ b/aws/resource_aws_ses_event_destination_test.go @@ -4,24 +4,21 @@ import ( "fmt" "testing" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ses" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSSESEventDestination_basic(t *testing.T) { - rString := acctest.RandString(8) - - bucketName := fmt.Sprintf("tf-acc-bucket-ses-event-dst-%s", rString) - roleName := fmt.Sprintf("tf_acc_role_ses_event_dst_%s", rString) - streamName := fmt.Sprintf("tf_acc_stream_ses_event_dst_%s", rString) - policyName := fmt.Sprintf("tf_acc_policy_ses_event_dst_%s", rString) - topicName := fmt.Sprintf("tf_acc_topic_ses_event_dst_%s", rString) - sesCfgSetName := fmt.Sprintf("tf_acc_cfg_ses_event_dst_%s", rString) - sesEventDstNameKinesis := fmt.Sprintf("tf_acc_event_dst_kinesis_%s", rString) - sesEventDstNameCw := fmt.Sprintf("tf_acc_event_dst_cloudwatch_%s", rString) - sesEventDstNameSns := fmt.Sprintf("tf_acc_event_dst_sns_%s", rString) + rName1 := acctest.RandomWithPrefix("tf-acc-test") + rName2 := acctest.RandomWithPrefix("tf-acc-test") + rName3 := acctest.RandomWithPrefix("tf-acc-test") + cloudwatchDestinationResourceName := "aws_ses_event_destination.cloudwatch" + kinesisDestinationResourceName := "aws_ses_event_destination.kinesis" + snsDestinationResourceName := "aws_ses_event_destination.sns" + var v1, v2, v3 ses.EventDestination resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { @@ -32,18 +29,67 @@ func TestAccAWSSESEventDestination_basic(t *testing.T) { CheckDestroy: testAccCheckSESEventDestinationDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSESEventDestinationConfig(bucketName, roleName, streamName, policyName, topicName, - sesCfgSetName, sesEventDstNameKinesis, sesEventDstNameCw, sesEventDstNameSns), + Config: testAccAWSSESEventDestinationConfig(rName1, rName2, rName3), Check: resource.ComposeTestCheckFunc( - testAccCheckAwsSESEventDestinationExists("aws_ses_configuration_set.test"), - resource.TestCheckResourceAttr( - "aws_ses_event_destination.kinesis", "name", sesEventDstNameKinesis), - resource.TestCheckResourceAttr( - "aws_ses_event_destination.cloudwatch", "name", sesEventDstNameCw), - resource.TestCheckResourceAttr( - "aws_ses_event_destination.sns", "name", sesEventDstNameSns), + testAccCheckAwsSESEventDestinationExists(cloudwatchDestinationResourceName, &v1), + testAccCheckAwsSESEventDestinationExists(kinesisDestinationResourceName, &v2), + testAccCheckAwsSESEventDestinationExists(snsDestinationResourceName, &v3), + resource.TestCheckResourceAttr(cloudwatchDestinationResourceName, "name", rName1), + resource.TestCheckResourceAttr(kinesisDestinationResourceName, "name", rName2), + resource.TestCheckResourceAttr(snsDestinationResourceName, "name", rName3), ), }, + { + ResourceName: cloudwatchDestinationResourceName, + ImportStateId: fmt.Sprintf("%s/%s", rName1, rName1), + ImportState: true, + ImportStateVerify: true, + }, + { + ResourceName: kinesisDestinationResourceName, + ImportStateId: fmt.Sprintf("%s/%s", rName1, rName2), + ImportState: true, + ImportStateVerify: true, + }, + { + ResourceName: snsDestinationResourceName, + ImportStateId: fmt.Sprintf("%s/%s", rName1, rName3), + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSSESEventDestination_disappears(t *testing.T) { + rName1 := acctest.RandomWithPrefix("tf-acc-test") + rName2 := acctest.RandomWithPrefix("tf-acc-test") + rName3 := acctest.RandomWithPrefix("tf-acc-test") + cloudwatchDestinationResourceName := "aws_ses_event_destination.cloudwatch" + kinesisDestinationResourceName := "aws_ses_event_destination.kinesis" + snsDestinationResourceName := "aws_ses_event_destination.sns" + var v1, v2, v3 ses.EventDestination + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheck(t) + testAccPreCheckAWSSES(t) + }, + Providers: testAccProviders, + CheckDestroy: testAccCheckSESEventDestinationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSSESEventDestinationConfig(rName1, rName2, rName3), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsSESEventDestinationExists(cloudwatchDestinationResourceName, &v1), + testAccCheckAwsSESEventDestinationExists(kinesisDestinationResourceName, &v2), + testAccCheckAwsSESEventDestinationExists(snsDestinationResourceName, &v3), + testAccCheckResourceDisappears(testAccProvider, resourceAwsSesEventDestination(), cloudwatchDestinationResourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsSesEventDestination(), kinesisDestinationResourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsSesEventDestination(), snsDestinationResourceName), + ), + ExpectNonEmptyPlan: true, + }, }, }) } @@ -78,7 +124,7 @@ func testAccCheckSESEventDestinationDestroy(s *terraform.State) error { } -func testAccCheckAwsSESEventDestinationExists(n string) resource.TestCheckFunc { +func testAccCheckAwsSESEventDestinationExists(n string, v *ses.EventDestination) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -91,36 +137,34 @@ func testAccCheckAwsSESEventDestinationExists(n string) resource.TestCheckFunc { conn := testAccProvider.Meta().(*AWSClient).sesconn - response, err := conn.ListConfigurationSets(&ses.ListConfigurationSetsInput{}) + response, err := conn.DescribeConfigurationSet(&ses.DescribeConfigurationSetInput{ + ConfigurationSetAttributeNames: aws.StringSlice([]string{ses.ConfigurationSetAttributeEventDestinations}), + ConfigurationSetName: aws.String(rs.Primary.Attributes["configuration_set_name"]), + }) if err != nil { return err } - found := false - for _, element := range response.ConfigurationSets { - if *element.Name == rs.Primary.ID { - found = true + for _, eventDestination := range response.EventDestinations { + if aws.StringValue(eventDestination.Name) == rs.Primary.ID { + *v = *eventDestination + return nil } } - if !found { - return fmt.Errorf("The configuration set was not created") - } - - return nil + return fmt.Errorf("The SES Configuration Set Event Destination was not found") } } -func testAccAWSSESEventDestinationConfig(bucketName, roleName, streamName, policyName, topicName, - sesCfgSetName, sesEventDstNameKinesis, sesEventDstNameCw, sesEventDstNameSns string) string { +func testAccAWSSESEventDestinationConfig(rName1, rName2, rName3 string) string { return fmt.Sprintf(` -resource "aws_s3_bucket" "bucket" { - bucket = "%s" +resource "aws_s3_bucket" "test" { + bucket = %[2]q acl = "private" } -resource "aws_iam_role" "firehose_role" { - name = "%s" +resource "aws_iam_role" "test" { + name = %[2]q assume_role_policy = < 0 { - attrmap := attributeOutput.Attributes - resource := *resourceAwsSnsPlatformApplication() - // iKey = internal struct key, oKey = AWS Attribute Map key - for iKey, oKey := range snsPlatformApplicationAttributeMap { - log.Printf("[DEBUG] Updating %s => %s", iKey, oKey) - - if attrmap[oKey] != nil { - // Some of the fetched attributes are stateful properties such as - // the number of subscriptions, the owner, etc. skip those - if resource.Schema[iKey] != nil { - value := aws.StringValue(attrmap[oKey]) - log.Printf("[DEBUG] Updating %s => %s -> %s", iKey, oKey, value) - d.Set(iKey, value) - } - } - } + if output == nil || output.Attributes == nil { + return fmt.Errorf("error getting SNS Platform Application (%s) attributes: empty response", d.Id()) + } + + if v, ok := output.Attributes["EventDeliveryFailure"]; ok { + d.Set("event_delivery_failure_topic_arn", v) + } + + if v, ok := output.Attributes["EventEndpointCreated"]; ok { + d.Set("event_endpoint_created_topic_arn", v) + } + + if v, ok := output.Attributes["EventEndpointDeleted"]; ok { + d.Set("event_endpoint_deleted_topic_arn", v) + } + + if v, ok := output.Attributes["EventEndpointUpdated"]; ok { + d.Set("event_endpoint_updated_topic_arn", v) + } + + if v, ok := output.Attributes["FailureFeedbackRoleArn"]; ok { + d.Set("failure_feedback_role_arn", v) + } + + if v, ok := output.Attributes["PlatformPrincipal"]; ok { + d.Set("platform_principal", v) + } + + if v, ok := output.Attributes["SuccessFeedbackRoleArn"]; ok { + d.Set("success_feedback_role_arn", v) + } + + if v, ok := output.Attributes["SuccessFeedbackSampleRate"]; ok { + d.Set("success_feedback_sample_rate", v) } return nil @@ -271,8 +307,20 @@ func decodeResourceAwsSnsPlatformApplicationID(input string) (arnS, name, platfo return } -func hashSum(contents interface{}) string { - return fmt.Sprintf("%x", sha256.Sum256([]byte(contents.(string)))) +func isChangeSha256Removal(oldRaw, newRaw interface{}) bool { + old, ok := oldRaw.(string) + + if !ok { + return false + } + + new, ok := newRaw.(string) + + if !ok { + return false + } + + return fmt.Sprintf("%x", sha256.Sum256([]byte(new))) == old } func validateAwsSnsPlatformApplication(d *schema.ResourceDiff) error { diff --git a/aws/resource_aws_sns_platform_application_test.go b/aws/resource_aws_sns_platform_application_test.go index 7fc9ed4cce8..7613447965e 100644 --- a/aws/resource_aws_sns_platform_application_test.go +++ b/aws/resource_aws_sns_platform_application_test.go @@ -9,14 +9,66 @@ import ( "strings" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sns" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) +func init() { + resource.AddTestSweepers("aws_sns_platform_application", &resource.Sweeper{ + Name: "aws_sns_platform_application", + F: testSweepSnsPlatformApplications, + }) +} + +func testSweepSnsPlatformApplications(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).snsconn + var sweeperErrs *multierror.Error + + err = conn.ListPlatformApplicationsPages(&sns.ListPlatformApplicationsInput{}, func(page *sns.ListPlatformApplicationsOutput, isLast bool) bool { + if page == nil { + return !isLast + } + + for _, platformApplication := range page.PlatformApplications { + arn := aws.StringValue(platformApplication.PlatformApplicationArn) + + log.Printf("[INFO] Deleting SNS Platform Application: %s", arn) + _, err := conn.DeletePlatformApplication(&sns.DeletePlatformApplicationInput{ + PlatformApplicationArn: aws.String(arn), + }) + if isAWSErr(err, sns.ErrCodeNotFoundException, "") { + continue + } + if err != nil { + sweeperErr := fmt.Errorf("error deleting SNS Platform Application (%s): %w", arn, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + } + + return !isLast + }) + + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping SNS Platform Applications sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors + } + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving SNS Platform Applications: %w", err)) + } + + return sweeperErrs.ErrorOrNil() +} + /** Before running this test, at least one of these ENV variables combinations must be set: @@ -183,7 +235,7 @@ func TestAccAWSSnsPlatformApplication_basic(t *testing.T) { Config: testAccAwsSnsPlatformApplicationConfig_basic(name, platform), Check: resource.ComposeTestCheckFunc( testAccCheckAwsSnsPlatformApplicationExists(resourceName), - resource.TestMatchResourceAttr(resourceName, "arn", regexp.MustCompile(fmt.Sprintf("^arn:[^:]+:sns:[^:]+:[^:]+:app/%s/%s$", platform.Name, name))), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "sns", regexp.MustCompile(fmt.Sprintf("app/%s/%s$", platform.Name, name))), resource.TestCheckResourceAttr(resourceName, "name", name), resource.TestCheckResourceAttr(resourceName, "platform", platform.Name), resource.TestCheckResourceAttrSet(resourceName, "platform_credential"), diff --git a/aws/resource_aws_sns_sms_preferences.go b/aws/resource_aws_sns_sms_preferences.go index 759e04c9c9e..da4018628db 100644 --- a/aws/resource_aws_sns_sms_preferences.go +++ b/aws/resource_aws_sns_sms_preferences.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sns" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func validateMonthlySpend(v interface{}, k string) (ws []string, errors []error) { diff --git a/aws/resource_aws_sns_sms_preferences_test.go b/aws/resource_aws_sns_sms_preferences_test.go index 82eab3f6710..682e96edf17 100644 --- a/aws/resource_aws_sns_sms_preferences_test.go +++ b/aws/resource_aws_sns_sms_preferences_test.go @@ -7,12 +7,12 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sns" multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // The preferences are account-wide, so the tests must be serialized -func TestAccAWSSNSSMSPreferences(t *testing.T) { +func TestAccAWSSNSSMSPreferences_serial(t *testing.T) { testCases := map[string]func(t *testing.T){ "almostAll": testAccAWSSNSSMSPreferences_almostAll, "defaultSMSType": testAccAWSSNSSMSPreferences_defaultSMSType, diff --git a/aws/resource_aws_sns_topic.go b/aws/resource_aws_sns_topic.go index 0a9f320b380..9b48c8f5caf 100644 --- a/aws/resource_aws_sns_topic.go +++ b/aws/resource_aws_sns_topic.go @@ -3,38 +3,18 @@ package aws import ( "fmt" "log" + "strconv" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sns" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) -// Mutable attributes -var SNSAttributeMap = map[string]string{ - "application_failure_feedback_role_arn": "ApplicationFailureFeedbackRoleArn", - "application_success_feedback_role_arn": "ApplicationSuccessFeedbackRoleArn", - "application_success_feedback_sample_rate": "ApplicationSuccessFeedbackSampleRate", - "arn": "TopicArn", - "delivery_policy": "DeliveryPolicy", - "display_name": "DisplayName", - "http_failure_feedback_role_arn": "HTTPFailureFeedbackRoleArn", - "http_success_feedback_role_arn": "HTTPSuccessFeedbackRoleArn", - "http_success_feedback_sample_rate": "HTTPSuccessFeedbackSampleRate", - "kms_master_key_id": "KmsMasterKeyId", - "lambda_failure_feedback_role_arn": "LambdaFailureFeedbackRoleArn", - "lambda_success_feedback_role_arn": "LambdaSuccessFeedbackRoleArn", - "lambda_success_feedback_sample_rate": "LambdaSuccessFeedbackSampleRate", - "policy": "Policy", - "sqs_failure_feedback_role_arn": "SQSFailureFeedbackRoleArn", - "sqs_success_feedback_role_arn": "SQSSuccessFeedbackRoleArn", - "sqs_success_feedback_sample_rate": "SQSSuccessFeedbackSampleRate", -} - func resourceAwsSnsTopic() *schema.Resource { return &schema.Resource{ Create: resourceAwsSnsTopicCreate, @@ -176,13 +156,107 @@ func resourceAwsSnsTopicCreate(d *schema.ResourceData, meta interface{}) error { d.SetId(*output.TopicArn) - for terraformAttrName, snsAttrName := range SNSAttributeMap { - if d.HasChange(terraformAttrName) { - _, terraformAttrValue := d.GetChange(terraformAttrName) - err := updateAwsSnsTopicAttribute(d.Id(), snsAttrName, terraformAttrValue, snsconn) - if err != nil { - return err - } + // update mutable attributes + if d.HasChange("application_failure_feedback_role_arn") { + _, v := d.GetChange("application_failure_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "ApplicationFailureFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("application_success_feedback_role_arn") { + _, v := d.GetChange("application_success_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "ApplicationSuccessFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("arn") { + _, v := d.GetChange("arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "TopicArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("delivery_policy") { + _, v := d.GetChange("delivery_policy") + if err := updateAwsSnsTopicAttribute(d.Id(), "DeliveryPolicy", v, snsconn); err != nil { + return err + } + } + if d.HasChange("display_name") { + _, v := d.GetChange("display_name") + if err := updateAwsSnsTopicAttribute(d.Id(), "DisplayName", v, snsconn); err != nil { + return err + } + } + if d.HasChange("http_failure_feedback_role_arn") { + _, v := d.GetChange("http_failure_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "HTTPFailureFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("http_success_feedback_role_arn") { + _, v := d.GetChange("http_success_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "HTTPSuccessFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("kms_master_key_id") { + _, v := d.GetChange("kms_master_key_id") + if err := updateAwsSnsTopicAttribute(d.Id(), "KmsMasterKeyId", v, snsconn); err != nil { + return err + } + } + if d.HasChange("lambda_failure_feedback_role_arn") { + _, v := d.GetChange("lambda_failure_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "LambdaFailureFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("lambda_success_feedback_role_arn") { + _, v := d.GetChange("lambda_success_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "LambdaSuccessFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("policy") { + _, v := d.GetChange("policy") + if err := updateAwsSnsTopicAttribute(d.Id(), "Policy", v, snsconn); err != nil { + return err + } + } + if d.HasChange("sqs_failure_feedback_role_arn") { + _, v := d.GetChange("sqs_failure_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "SQSFailureFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("sqs_success_feedback_role_arn") { + _, v := d.GetChange("sqs_success_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "SQSSuccessFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("application_success_feedback_sample_rate") { + _, v := d.GetChange("application_success_feedback_sample_rate") + if err := updateAwsSnsTopicAttribute(d.Id(), "ApplicationSuccessFeedbackSampleRate", v, snsconn); err != nil { + return err + } + } + if d.HasChange("http_success_feedback_sample_rate") { + _, v := d.GetChange("http_success_feedback_sample_rate") + if err := updateAwsSnsTopicAttribute(d.Id(), "HTTPSuccessFeedbackSampleRate", v, snsconn); err != nil { + return err + } + } + if d.HasChange("lambda_success_feedback_sample_rate") { + _, v := d.GetChange("lambda_success_feedback_sample_rate") + if err := updateAwsSnsTopicAttribute(d.Id(), "LambdaSuccessFeedbackSampleRate", v, snsconn); err != nil { + return err + } + } + if d.HasChange("sqs_success_feedback_sample_rate") { + _, v := d.GetChange("sqs_success_feedback_sample_rate") + if err := updateAwsSnsTopicAttribute(d.Id(), "SQSSuccessFeedbackSampleRate", v, snsconn); err != nil { + return err } } @@ -190,21 +264,115 @@ func resourceAwsSnsTopicCreate(d *schema.ResourceData, meta interface{}) error { } func resourceAwsSnsTopicUpdate(d *schema.ResourceData, meta interface{}) error { - conn := meta.(*AWSClient).snsconn + snsconn := meta.(*AWSClient).snsconn - for terraformAttrName, snsAttrName := range SNSAttributeMap { - if d.HasChange(terraformAttrName) { - _, terraformAttrValue := d.GetChange(terraformAttrName) - err := updateAwsSnsTopicAttribute(d.Id(), snsAttrName, terraformAttrValue, conn) - if err != nil { - return err - } + // update mutable attributes + if d.HasChange("application_failure_feedback_role_arn") { + _, v := d.GetChange("application_failure_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "ApplicationFailureFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("application_success_feedback_role_arn") { + _, v := d.GetChange("application_success_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "ApplicationSuccessFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("arn") { + _, v := d.GetChange("arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "TopicArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("delivery_policy") { + _, v := d.GetChange("delivery_policy") + if err := updateAwsSnsTopicAttribute(d.Id(), "DeliveryPolicy", v, snsconn); err != nil { + return err + } + } + if d.HasChange("display_name") { + _, v := d.GetChange("display_name") + if err := updateAwsSnsTopicAttribute(d.Id(), "DisplayName", v, snsconn); err != nil { + return err + } + } + if d.HasChange("http_failure_feedback_role_arn") { + _, v := d.GetChange("http_failure_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "HTTPFailureFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("http_success_feedback_role_arn") { + _, v := d.GetChange("http_success_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "HTTPSuccessFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("kms_master_key_id") { + _, v := d.GetChange("kms_master_key_id") + if err := updateAwsSnsTopicAttribute(d.Id(), "KmsMasterKeyId", v, snsconn); err != nil { + return err + } + } + if d.HasChange("lambda_failure_feedback_role_arn") { + _, v := d.GetChange("lambda_failure_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "LambdaFailureFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("lambda_success_feedback_role_arn") { + _, v := d.GetChange("lambda_success_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "LambdaSuccessFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("policy") { + _, v := d.GetChange("policy") + if err := updateAwsSnsTopicAttribute(d.Id(), "Policy", v, snsconn); err != nil { + return err + } + } + if d.HasChange("sqs_failure_feedback_role_arn") { + _, v := d.GetChange("sqs_failure_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "SQSFailureFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("sqs_success_feedback_role_arn") { + _, v := d.GetChange("sqs_success_feedback_role_arn") + if err := updateAwsSnsTopicAttribute(d.Id(), "SQSSuccessFeedbackRoleArn", v, snsconn); err != nil { + return err + } + } + if d.HasChange("application_success_feedback_sample_rate") { + _, v := d.GetChange("application_success_feedback_sample_rate") + if err := updateAwsSnsTopicAttribute(d.Id(), "ApplicationSuccessFeedbackSampleRate", v, snsconn); err != nil { + return err + } + } + if d.HasChange("http_success_feedback_sample_rate") { + _, v := d.GetChange("http_success_feedback_sample_rate") + if err := updateAwsSnsTopicAttribute(d.Id(), "HTTPSuccessFeedbackSampleRate", v, snsconn); err != nil { + return err + } + } + if d.HasChange("lambda_success_feedback_sample_rate") { + _, v := d.GetChange("lambda_success_feedback_sample_rate") + if err := updateAwsSnsTopicAttribute(d.Id(), "LambdaSuccessFeedbackSampleRate", v, snsconn); err != nil { + return err + } + } + if d.HasChange("sqs_success_feedback_sample_rate") { + _, v := d.GetChange("sqs_success_feedback_sample_rate") + if err := updateAwsSnsTopicAttribute(d.Id(), "SQSSuccessFeedbackSampleRate", v, snsconn); err != nil { + return err } } if d.HasChange("tags") { o, n := d.GetChange("tags") - if err := keyvaluetags.SnsUpdateTags(conn, d.Id(), o, n); err != nil { + if err := keyvaluetags.SnsUpdateTags(snsconn, d.Id(), o, n); err != nil { return fmt.Errorf("error updating tags: %s", err) } } @@ -230,14 +398,62 @@ func resourceAwsSnsTopicRead(d *schema.ResourceData, meta interface{}) error { return err } + // set the mutable attributes if attributeOutput.Attributes != nil && len(attributeOutput.Attributes) > 0 { - attrmap := attributeOutput.Attributes - for terraformAttrName, snsAttrName := range SNSAttributeMap { - d.Set(terraformAttrName, attrmap[snsAttrName]) + // set the string values + d.Set("application_failure_feedback_role_arn", aws.StringValue(attributeOutput.Attributes["ApplicationFailureFeedbackRoleArn"])) + d.Set("application_success_feedback_role_arn", aws.StringValue(attributeOutput.Attributes["ApplicationSuccessFeedbackRoleArn"])) + d.Set("arn", aws.StringValue(attributeOutput.Attributes["TopicArn"])) + d.Set("delivery_policy", aws.StringValue(attributeOutput.Attributes["DeliveryPolicy"])) + d.Set("display_name", aws.StringValue(attributeOutput.Attributes["DisplayName"])) + d.Set("http_failure_feedback_role_arn", aws.StringValue(attributeOutput.Attributes["HTTPFailureFeedbackRoleArn"])) + d.Set("http_success_feedback_role_arn", aws.StringValue(attributeOutput.Attributes["HTTPSuccessFeedbackRoleArn"])) + d.Set("kms_master_key_id", aws.StringValue(attributeOutput.Attributes["KmsMasterKeyId"])) + d.Set("lambda_failure_feedback_role_arn", aws.StringValue(attributeOutput.Attributes["LambdaFailureFeedbackRoleArn"])) + d.Set("lambda_success_feedback_role_arn", aws.StringValue(attributeOutput.Attributes["LambdaSuccessFeedbackRoleArn"])) + d.Set("policy", aws.StringValue(attributeOutput.Attributes["Policy"])) + d.Set("sqs_failure_feedback_role_arn", aws.StringValue(attributeOutput.Attributes["SQSFailureFeedbackRoleArn"])) + d.Set("sqs_success_feedback_role_arn", aws.StringValue(attributeOutput.Attributes["SQSSuccessFeedbackRoleArn"])) + + // set the number values + var vStr string + var v int64 + var err error + + vStr = aws.StringValue(attributeOutput.Attributes["ApplicationSuccessFeedbackSampleRate"]) + if vStr != "" { + v, err = strconv.ParseInt(vStr, 10, 64) + if err != nil { + return fmt.Errorf("error parsing integer attribute 'ApplicationSuccessFeedbackSampleRate': %s", err) + } + d.Set("application_success_feedback_sample_rate", v) } - } else { - for terraformAttrName := range SNSAttributeMap { - d.Set(terraformAttrName, "") + + vStr = aws.StringValue(attributeOutput.Attributes["HTTPSuccessFeedbackSampleRate"]) + if vStr != "" { + v, err = strconv.ParseInt(vStr, 10, 64) + if err != nil { + return fmt.Errorf("error parsing integer attribute 'HTTPSuccessFeedbackSampleRate': %s", err) + } + d.Set("http_success_feedback_sample_rate", v) + } + + vStr = aws.StringValue(attributeOutput.Attributes["LambdaSuccessFeedbackSampleRate"]) + if vStr != "" { + v, err = strconv.ParseInt(vStr, 10, 64) + if err != nil { + return fmt.Errorf("error parsing integer attribute 'LambdaSuccessFeedbackSampleRate': %s", err) + } + d.Set("lambda_success_feedback_sample_rate", v) + } + + vStr = aws.StringValue(attributeOutput.Attributes["SQSSuccessFeedbackSampleRate"]) + if vStr != "" { + v, err = strconv.ParseInt(vStr, 10, 64) + if err != nil { + return fmt.Errorf("error parsing integer attribute 'SQSSuccessFeedbackSampleRate': %s", err) + } + d.Set("sqs_success_feedback_sample_rate", v) } } diff --git a/aws/resource_aws_sns_topic_policy.go b/aws/resource_aws_sns_topic_policy.go index 200a45ce7ed..9895deea307 100644 --- a/aws/resource_aws_sns_topic_policy.go +++ b/aws/resource_aws_sns_topic_policy.go @@ -5,8 +5,8 @@ import ( "log" "regexp" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" diff --git a/aws/resource_aws_sns_topic_policy_test.go b/aws/resource_aws_sns_topic_policy_test.go index 96a9f12d60a..0d5aa685dd3 100644 --- a/aws/resource_aws_sns_topic_policy_test.go +++ b/aws/resource_aws_sns_topic_policy_test.go @@ -4,7 +4,7 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccAWSSNSTopicPolicy_basic(t *testing.T) { diff --git a/aws/resource_aws_sns_topic_subscription.go b/aws/resource_aws_sns_topic_subscription.go index 2f665448675..a3ced00e586 100644 --- a/aws/resource_aws_sns_topic_subscription.go +++ b/aws/resource_aws_sns_topic_subscription.go @@ -9,10 +9,10 @@ import ( "strings" "time" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" @@ -235,18 +235,16 @@ func subscribeToSNSTopic(d *schema.ResourceData, snsconn *sns.SNS) (output *sns. subscription, err := findSubscriptionByNonID(d, snsconn) - if subscription != nil { - output.SubscriptionArn = subscription.SubscriptionArn - return nil + if err != nil { + return resource.NonRetryableError(err) } - if err != nil { - return resource.RetryableError( - fmt.Errorf("Error fetching subscriptions for SNS topic %s: %s", topic_arn, err)) + if subscription == nil { + return resource.RetryableError(fmt.Errorf("Endpoint (%s) did not autoconfirm the subscription for topic %s", endpoint, topic_arn)) } - return resource.RetryableError( - fmt.Errorf("Endpoint (%s) did not autoconfirm the subscription for topic %s", endpoint, topic_arn)) + output.SubscriptionArn = subscription.SubscriptionArn + return nil }) if isResourceTimeoutError(err) { @@ -268,37 +266,52 @@ func subscribeToSNSTopic(d *schema.ResourceData, snsconn *sns.SNS) (output *sns. } // finds a subscription using protocol, endpoint and topic_arn (which is a key in sns subscription) -func findSubscriptionByNonID(d *schema.ResourceData, snsconn *sns.SNS) (*sns.Subscription, error) { +func findSubscriptionByNonID(d *schema.ResourceData, conn *sns.SNS) (*sns.Subscription, error) { protocol := d.Get("protocol").(string) endpoint := d.Get("endpoint").(string) - topic_arn := d.Get("topic_arn").(string) + topicARN := d.Get("topic_arn").(string) obfuscatedEndpoint := obfuscateEndpoint(endpoint) - req := &sns.ListSubscriptionsByTopicInput{ - TopicArn: aws.String(topic_arn), + input := &sns.ListSubscriptionsByTopicInput{ + TopicArn: aws.String(topicARN), } + var result *sns.Subscription - for { - res, err := snsconn.ListSubscriptionsByTopic(req) - - if err != nil { - return nil, fmt.Errorf("Error fetching subscriptions for topic %s : %s", topic_arn, err) + err := conn.ListSubscriptionsByTopicPages(input, func(page *sns.ListSubscriptionsByTopicOutput, lastPage bool) bool { + if page == nil { + return !lastPage } - for _, subscription := range res.Subscriptions { - log.Printf("[DEBUG] check subscription with Subscription EndPoint %s (local: %s), Protocol %s, topicARN %s and SubscriptionARN %s", *subscription.Endpoint, obfuscatedEndpoint, *subscription.Protocol, *subscription.TopicArn, *subscription.SubscriptionArn) - if *subscription.Endpoint == obfuscatedEndpoint && *subscription.Protocol == protocol && *subscription.TopicArn == topic_arn && !subscriptionHasPendingConfirmation(subscription.SubscriptionArn) { - return subscription, nil + for _, subscription := range page.Subscriptions { + if subscription == nil { + continue + } + + if aws.StringValue(subscription.Endpoint) != obfuscatedEndpoint { + continue } - } - // if there are more than 100 subscriptions then go to the next 100 otherwise return an error - if res.NextToken != nil { - req.NextToken = res.NextToken - } else { - return nil, fmt.Errorf("Error finding subscription for topic %s with endpoint %s and protocol %s", topic_arn, endpoint, protocol) + if aws.StringValue(subscription.Protocol) != protocol { + continue + } + + if aws.StringValue(subscription.TopicArn) != topicARN { + continue + } + + if subscriptionHasPendingConfirmation(subscription.SubscriptionArn) { + continue + } + + result = subscription + + return false } - } + + return !lastPage + }) + + return result, err } // returns true if arn is nil or has both pending and confirmation words in the arn diff --git a/aws/resource_aws_sns_topic_subscription_test.go b/aws/resource_aws_sns_topic_subscription_test.go index 55c5887c6e0..3ba3800115c 100644 --- a/aws/resource_aws_sns_topic_subscription_test.go +++ b/aws/resource_aws_sns_topic_subscription_test.go @@ -11,9 +11,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/sns" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestSuppressEquivalentSnsTopicSubscriptionDeliveryPolicy(t *testing.T) { @@ -749,7 +749,6 @@ resource "aws_api_gateway_authorizer" "test" { name = "tf-acc-test-api-gw-authorizer-%d" rest_api_id = "${aws_api_gateway_rest_api.test.id}" authorizer_uri = "${aws_lambda_function.authorizer.invoke_arn}" - authorizer_result_ttl_in_seconds = "0" authorizer_credentials = "${aws_iam_role.invocation_role.arn}" } diff --git a/aws/resource_aws_sns_topic_test.go b/aws/resource_aws_sns_topic_test.go index 229b1125335..447123722ef 100644 --- a/aws/resource_aws_sns_topic_test.go +++ b/aws/resource_aws_sns_topic_test.go @@ -2,18 +2,89 @@ package aws import ( "fmt" + "log" "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sns" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" awspolicy "github.com/jen20/awspolicyequivalence" ) +func init() { + resource.AddTestSweepers("aws_sns_topic", &resource.Sweeper{ + Name: "aws_sns_topic", + F: testSweepSnsTopics, + Dependencies: []string{ + "aws_autoscaling_group", + "aws_budgets_budget", + "aws_config_delivery_channel", + "aws_dax_cluster", + "aws_db_event_subscription", + "aws_elasticache_cluster", + "aws_elasticache_replication_group", + "aws_glacier_vault", + "aws_iot_topic_rule", + "aws_neptune_event_subscription", + "aws_redshift_event_subscription", + "aws_s3_bucket", + "aws_ses_configuration_set", + "aws_ses_domain_identity", + "aws_ses_email_identity", + "aws_ses_receipt_rule_set", + "aws_sns_platform_application", + }, + }) +} + +func testSweepSnsTopics(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).snsconn + var sweeperErrs *multierror.Error + + err = conn.ListTopicsPages(&sns.ListTopicsInput{}, func(page *sns.ListTopicsOutput, isLast bool) bool { + if page == nil { + return !isLast + } + + for _, topic := range page.Topics { + arn := aws.StringValue(topic.TopicArn) + + log.Printf("[INFO] Deleting SNS Topic: %s", arn) + _, err := conn.DeleteTopic(&sns.DeleteTopicInput{ + TopicArn: aws.String(arn), + }) + if isAWSErr(err, sns.ErrCodeNotFoundException, "") { + continue + } + if err != nil { + sweeperErr := fmt.Errorf("error deleting SNS Topic (%s): %w", arn, err) + log.Printf("[ERROR] %s", sweeperErr) + sweeperErrs = multierror.Append(sweeperErrs, sweeperErr) + continue + } + } + + return !isLast + }) + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping SNS Topics sweep for %s: %s", region, err) + return sweeperErrs.ErrorOrNil() // In case we have completed some pages, but had errors + } + if err != nil { + sweeperErrs = multierror.Append(sweeperErrs, fmt.Errorf("error retrieving SNS Topics: %w", err)) + } + + return sweeperErrs.ErrorOrNil() +} + func TestAccAWSSNSTopic_basic(t *testing.T) { attributes := make(map[string]string) resourceName := "aws_sns_topic.test" @@ -189,22 +260,9 @@ func TestAccAWSSNSTopic_withDeliveryPolicy(t *testing.T) { func TestAccAWSSNSTopic_deliveryStatus(t *testing.T) { attributes := make(map[string]string) resourceName := "aws_sns_topic.test" + iamRoleResourceName := "aws_iam_role.example" + rName := acctest.RandString(10) - arnRegex := regexp.MustCompile("^arn:aws:iam::[0-9]{12}:role/sns-delivery-status-role-") - expectedAttributes := map[string]*regexp.Regexp{ - "ApplicationFailureFeedbackRoleArn": arnRegex, - "ApplicationSuccessFeedbackRoleArn": arnRegex, - "ApplicationSuccessFeedbackSampleRate": regexp.MustCompile(`^100$`), - "HTTPFailureFeedbackRoleArn": arnRegex, - "HTTPSuccessFeedbackRoleArn": arnRegex, - "HTTPSuccessFeedbackSampleRate": regexp.MustCompile(`^80$`), - "LambdaFailureFeedbackRoleArn": arnRegex, - "LambdaSuccessFeedbackRoleArn": arnRegex, - "LambdaSuccessFeedbackSampleRate": regexp.MustCompile(`^90$`), - "SQSFailureFeedbackRoleArn": arnRegex, - "SQSSuccessFeedbackRoleArn": arnRegex, - "SQSSuccessFeedbackSampleRate": regexp.MustCompile(`^70$`), - } resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -216,19 +274,18 @@ func TestAccAWSSNSTopic_deliveryStatus(t *testing.T) { Config: testAccAWSSNSTopicConfig_deliveryStatus(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSSNSTopicExists(resourceName, attributes), - testAccCheckAWSSNSTopicAttributes(attributes, expectedAttributes), - resource.TestMatchResourceAttr(resourceName, "application_success_feedback_role_arn", arnRegex), + resource.TestCheckResourceAttrPair(resourceName, "application_success_feedback_role_arn", iamRoleResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "application_success_feedback_sample_rate", "100"), - resource.TestMatchResourceAttr(resourceName, "application_failure_feedback_role_arn", arnRegex), - resource.TestMatchResourceAttr(resourceName, "lambda_success_feedback_role_arn", arnRegex), + resource.TestCheckResourceAttrPair(resourceName, "application_failure_feedback_role_arn", iamRoleResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "lambda_success_feedback_role_arn", iamRoleResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "lambda_success_feedback_sample_rate", "90"), - resource.TestMatchResourceAttr(resourceName, "lambda_failure_feedback_role_arn", arnRegex), - resource.TestMatchResourceAttr(resourceName, "http_success_feedback_role_arn", arnRegex), + resource.TestCheckResourceAttrPair(resourceName, "lambda_failure_feedback_role_arn", iamRoleResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "http_success_feedback_role_arn", iamRoleResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "http_success_feedback_sample_rate", "80"), - resource.TestMatchResourceAttr(resourceName, "http_failure_feedback_role_arn", arnRegex), - resource.TestMatchResourceAttr(resourceName, "sqs_success_feedback_role_arn", arnRegex), + resource.TestCheckResourceAttrPair(resourceName, "http_failure_feedback_role_arn", iamRoleResourceName, "arn"), + resource.TestCheckResourceAttrPair(resourceName, "sqs_success_feedback_role_arn", iamRoleResourceName, "arn"), resource.TestCheckResourceAttr(resourceName, "sqs_success_feedback_sample_rate", "70"), - resource.TestMatchResourceAttr(resourceName, "sqs_failure_feedback_role_arn", arnRegex), + resource.TestCheckResourceAttrPair(resourceName, "sqs_failure_feedback_role_arn", iamRoleResourceName, "arn"), ), }, }, @@ -322,7 +379,7 @@ func testAccCheckAWSNSTopicHasPolicy(n string, expectedPolicyText string) resour } if rs.Primary.ID == "" { - return fmt.Errorf("No Queue URL specified!") + return fmt.Errorf("no Queue URL specified") } if !ok { @@ -356,7 +413,7 @@ func testAccCheckAWSNSTopicHasPolicy(n string, expectedPolicyText string) resour return fmt.Errorf("Error testing policy equivalence: %s", err) } if !equivalent { - return fmt.Errorf("Non-equivalent policy error:\n\nexpected: %s\n\n got: %s\n", + return fmt.Errorf("Non-equivalent policy error:\n\nexpected: %s\n\n got: %s", expectedPolicyText, actualPolicyText) } @@ -372,7 +429,7 @@ func testAccCheckAWSNSTopicHasDeliveryPolicy(n string, expectedPolicyText string } if rs.Primary.ID == "" { - return fmt.Errorf("No Queue URL specified!") + return fmt.Errorf("no Queue URL specified") } conn := testAccProvider.Meta().(*AWSClient).snsconn @@ -396,7 +453,7 @@ func testAccCheckAWSNSTopicHasDeliveryPolicy(n string, expectedPolicyText string equivalent := suppressEquivalentJsonDiffs("", actualPolicyText, expectedPolicyText, nil) if !equivalent { - return fmt.Errorf("Non-equivalent delivery policy error:\n\nexpected: %s\n\n got: %s\n", + return fmt.Errorf("Non-equivalent delivery policy error:\n\nexpected: %s\n\n got: %s", expectedPolicyText, actualPolicyText) } @@ -423,25 +480,12 @@ func testAccCheckAWSSNSTopicDestroy(s *terraform.State) error { } return err } - return fmt.Errorf("Topic exists when it should be destroyed!") + return fmt.Errorf("SNS topic (%s) exists when it should be destroyed", rs.Primary.ID) } return nil } -func testAccCheckAWSSNSTopicAttributes(attributes map[string]string, expectedAttributes map[string]*regexp.Regexp) resource.TestCheckFunc { - return func(s *terraform.State) error { - var errors error - for k, expectedR := range expectedAttributes { - if v, ok := attributes[k]; !ok || !expectedR.MatchString(v) { - err := fmt.Errorf("expected SNS topic attribute %q to match %q, received: %q", k, expectedR.String(), v) - errors = multierror.Append(errors, err) - } - } - return errors - } -} - func testAccCheckAWSSNSTopicExists(n string, attributes map[string]string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] diff --git a/aws/resource_aws_spot_datafeed_subscription.go b/aws/resource_aws_spot_datafeed_subscription.go index 2923e9b6784..26937029498 100644 --- a/aws/resource_aws_spot_datafeed_subscription.go +++ b/aws/resource_aws_spot_datafeed_subscription.go @@ -7,7 +7,7 @@ import ( "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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsSpotDataFeedSubscription() *schema.Resource { diff --git a/aws/resource_aws_spot_datafeed_subscription_test.go b/aws/resource_aws_spot_datafeed_subscription_test.go index 7233cd0f5a7..12be280f572 100644 --- a/aws/resource_aws_spot_datafeed_subscription_test.go +++ b/aws/resource_aws_spot_datafeed_subscription_test.go @@ -7,12 +7,12 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccAWSSpotDatafeedSubscription(t *testing.T) { +func TestAccAWSSpotDatafeedSubscription_serial(t *testing.T) { cases := map[string]func(t *testing.T){ "basic": testAccAWSSpotDatafeedSubscription_basic, "disappears": testAccAWSSpotDatafeedSubscription_disappears, diff --git a/aws/resource_aws_spot_fleet_request.go b/aws/resource_aws_spot_fleet_request.go index 6566271e1f9..e7fe6fb0e4f 100644 --- a/aws/resource_aws_spot_fleet_request.go +++ b/aws/resource_aws_spot_fleet_request.go @@ -9,14 +9,16 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" + iamwaiter "github.com/terraform-providers/terraform-provider-aws/aws/internal/service/iam/waiter" ) func resourceAwsSpotFleetRequest() *schema.Resource { + //lintignore:R011 return &schema.Resource{ Create: resourceAwsSpotFleetRequestCreate, Read: resourceAwsSpotFleetRequestRead, @@ -30,7 +32,7 @@ func resourceAwsSpotFleetRequest() *schema.Resource { }, Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(10 * time.Minute), - Delete: schema.DefaultTimeout(5 * time.Minute), + Delete: schema.DefaultTimeout(15 * time.Minute), }, SchemaVersion: 1, @@ -311,6 +313,7 @@ func resourceAwsSpotFleetRequest() *schema.Resource { Type: schema.TypeMap, Optional: true, ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, }, }, @@ -764,7 +767,7 @@ func buildAwsSpotFleetLaunchSpecifications( return specs, nil } -func buildLaunchTemplateConfigs(d *schema.ResourceData) ([]*ec2.LaunchTemplateConfig, error) { +func buildLaunchTemplateConfigs(d *schema.ResourceData) []*ec2.LaunchTemplateConfig { launchTemplateConfigs := d.Get("launch_template_config").(*schema.Set) configs := make([]*ec2.LaunchTemplateConfig, 0) @@ -838,7 +841,7 @@ func buildLaunchTemplateConfigs(d *schema.ResourceData) ([]*ec2.LaunchTemplateCo configs = append(configs, ltc) } - return configs, nil + return configs } func resourceAwsSpotFleetRequestCreate(d *schema.ResourceData, meta interface{}) error { @@ -869,10 +872,7 @@ func resourceAwsSpotFleetRequestCreate(d *schema.ResourceData, meta interface{}) } if launchTemplateConfigsOk { - launchTemplates, err := buildLaunchTemplateConfigs(d) - if err != nil { - return err - } + launchTemplates := buildLaunchTemplateConfigs(d) spotFleetConfig.LaunchTemplateConfigs = launchTemplates } @@ -883,7 +883,7 @@ func resourceAwsSpotFleetRequestCreate(d *schema.ResourceData, meta interface{}) if v, ok := d.GetOk("allocation_strategy"); ok { spotFleetConfig.AllocationStrategy = aws.String(v.(string)) } else { - spotFleetConfig.AllocationStrategy = aws.String("lowestPrice") + spotFleetConfig.AllocationStrategy = aws.String(ec2.AllocationStrategyLowestPrice) } if v, ok := d.GetOk("instance_pools_to_use_count"); ok && v.(int) != 1 { @@ -908,9 +908,6 @@ func resourceAwsSpotFleetRequestCreate(d *schema.ResourceData, meta interface{}) return err } spotFleetConfig.ValidUntil = aws.Time(validUntil) - } else { - validUntil := time.Now().Add(24 * time.Hour) - spotFleetConfig.ValidUntil = aws.Time(validUntil) } if v, ok := d.GetOk("load_balancers"); ok && v.(*schema.Set).Len() > 0 { @@ -954,19 +951,22 @@ func resourceAwsSpotFleetRequestCreate(d *schema.ResourceData, meta interface{}) // Since IAM is eventually consistent, we retry creation as a newly created role may not // take effect immediately, resulting in an InvalidSpotFleetRequestConfig error var resp *ec2.RequestSpotFleetOutput - err := resource.Retry(10*time.Minute, func() *resource.RetryError { + err := resource.Retry(iamwaiter.PropagationTimeout, func() *resource.RetryError { var err error resp, err = conn.RequestSpotFleet(spotFleetOpts) - if isAWSErr(err, "InvalidSpotFleetRequestConfig", "Duplicate: Parameter combination") { - return resource.NonRetryableError(fmt.Errorf("Error creating Spot fleet request: %s", err)) + if isAWSErr(err, "InvalidSpotFleetRequestConfig", "Parameter: SpotFleetRequestConfig.IamFleetRole is invalid") { + return resource.RetryableError(err) } - if isAWSErr(err, "InvalidSpotFleetRequestConfig", "") { - return resource.RetryableError(fmt.Errorf("Error creating Spot fleet request, retrying: %s", err)) + + if isAWSErr(err, "InvalidSpotFleetRequestConfig", "The provided SpotFleetRequestConfig.IamFleetRole does not have permission to call") { + return resource.RetryableError(err) } + if err != nil { return resource.NonRetryableError(err) } + return nil }) @@ -1483,11 +1483,10 @@ func resourceAwsSpotFleetRequestUpdate(d *schema.ResourceData, meta interface{}) updateFlag := false if d.HasChange("target_capacity") { - if val, ok := d.GetOk("target_capacity"); ok { + if val, ok := d.GetOkExists("target_capacity"); ok { req.TargetCapacity = aws.Int64(int64(val.(int))) + updateFlag = true } - - updateFlag = true } if d.HasChange("excess_capacity_termination_policy") { @@ -1499,9 +1498,25 @@ func resourceAwsSpotFleetRequestUpdate(d *schema.ResourceData, meta interface{}) } if updateFlag { + log.Printf("[DEBUG] Modifying Spot Fleet Request: %#v", req) if _, err := conn.ModifySpotFleetRequest(req); err != nil { return fmt.Errorf("error updating spot request (%s): %s", d.Id(), err) } + + log.Println("[INFO] Waiting for Spot Fleet Request to be modified") + stateConf := &resource.StateChangeConf{ + Pending: []string{ec2.BatchStateModifying}, + Target: []string{ec2.BatchStateActive}, + Refresh: resourceAwsSpotFleetRequestStateRefreshFunc(d, meta), + Timeout: 10 * time.Minute, + MinTimeout: 10 * time.Second, + Delay: 30 * time.Second, + } + + _, err := stateConf.WaitForState() + if err != nil { + return err + } } if d.HasChange("tags") { @@ -1605,11 +1620,11 @@ func hashLaunchSpecification(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) buf.WriteString(fmt.Sprintf("%s-", m["ami"].(string))) - if m["availability_zone"] != "" { - buf.WriteString(fmt.Sprintf("%s-", m["availability_zone"].(string))) + if v, ok := m["availability_zone"].(string); ok && v != "" { + buf.WriteString(fmt.Sprintf("%s-", v)) } - if m["subnet_id"] != "" { - buf.WriteString(fmt.Sprintf("%s-", m["subnet_id"].(string))) + if v, ok := m["subnet_id"].(string); ok && v != "" { + buf.WriteString(fmt.Sprintf("%s-", v)) } buf.WriteString(fmt.Sprintf("%s-", m["instance_type"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["spot_price"].(string))) diff --git a/aws/resource_aws_spot_fleet_request_migrate.go b/aws/resource_aws_spot_fleet_request_migrate.go index 0d64dfdc980..b06f50635ea 100644 --- a/aws/resource_aws_spot_fleet_request_migrate.go +++ b/aws/resource_aws_spot_fleet_request_migrate.go @@ -4,7 +4,7 @@ import ( "fmt" "log" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func resourceAwsSpotFleetRequestMigrateState( diff --git a/aws/resource_aws_spot_fleet_request_migrate_test.go b/aws/resource_aws_spot_fleet_request_migrate_test.go index 098771845f1..2d498e2ce11 100644 --- a/aws/resource_aws_spot_fleet_request_migrate_test.go +++ b/aws/resource_aws_spot_fleet_request_migrate_test.go @@ -3,7 +3,7 @@ package aws import ( "testing" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAWSSpotFleetRequestMigrateState(t *testing.T) { diff --git a/aws/resource_aws_spot_fleet_request_test.go b/aws/resource_aws_spot_fleet_request_test.go index 221bc063a56..71cafbf1f5f 100644 --- a/aws/resource_aws_spot_fleet_request_test.go +++ b/aws/resource_aws_spot_fleet_request_test.go @@ -10,9 +10,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -39,7 +40,7 @@ func testSweepSpotFleetRequests(region string) error { id := aws.StringValue(config.SpotFleetRequestId) log.Printf("[INFO] Deleting Spot Fleet Request: %s", id) - err := deleteSpotFleetRequest(id, true, 5*time.Minute, conn) + err := deleteSpotFleetRequest(id, true, 15*time.Minute, conn) if err != nil { log.Printf("[ERROR] Failed to delete Spot Fleet Request (%s): %s", id, err) } @@ -58,8 +59,7 @@ func testSweepSpotFleetRequests(region string) error { func TestAccAWSSpotFleetRequest_basic(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -69,7 +69,7 @@ func TestAccAWSSpotFleetRequest_basic(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -90,8 +90,7 @@ func TestAccAWSSpotFleetRequest_basic(t *testing.T) { func TestAccAWSSpotFleetRequest_tags(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -101,7 +100,7 @@ func TestAccAWSSpotFleetRequest_tags(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigTags1(rName, validUntil, "key1", "value1", rInt), + Config: testAccAWSSpotFleetRequestConfigTags1(rName, validUntil, "key1", "value1"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -115,7 +114,7 @@ func TestAccAWSSpotFleetRequest_tags(t *testing.T) { ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccAWSSpotFleetRequestConfigTags2(rName, validUntil, "key1", "value1updated", "key2", "value2", rInt), + Config: testAccAWSSpotFleetRequestConfigTags2(rName, validUntil, "key1", "value1updated", "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -124,7 +123,7 @@ func TestAccAWSSpotFleetRequest_tags(t *testing.T) { ), }, { - Config: testAccAWSSpotFleetRequestConfigTags1(rName, validUntil, "key2", "value2", rInt), + Config: testAccAWSSpotFleetRequestConfigTags1(rName, validUntil, "key2", "value2"), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -137,24 +136,24 @@ func TestAccAWSSpotFleetRequest_tags(t *testing.T) { func TestAccAWSSpotFleetRequest_associatePublicIpAddress(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigAssociatePublicIpAddress(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigAssociatePublicIpAddress(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), resource.TestCheckResourceAttr(resourceName, "launch_specification.#", "1"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.24370212.associate_public_ip_address", "true"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*", map[string]string{ + "associate_public_ip_address": "true", + }), ), }, { @@ -169,8 +168,7 @@ func TestAccAWSSpotFleetRequest_associatePublicIpAddress(t *testing.T) { func TestAccAWSSpotFleetRequest_launchTemplate(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -180,7 +178,7 @@ func TestAccAWSSpotFleetRequest_launchTemplate(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestLaunchTemplateConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestLaunchTemplateConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -200,8 +198,7 @@ func TestAccAWSSpotFleetRequest_launchTemplate(t *testing.T) { func TestAccAWSSpotFleetRequest_launchTemplate_multiple(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -211,7 +208,7 @@ func TestAccAWSSpotFleetRequest_launchTemplate_multiple(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestLaunchTemplateMultipleConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestLaunchTemplateMultipleConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -225,8 +222,7 @@ func TestAccAWSSpotFleetRequest_launchTemplate_multiple(t *testing.T) { func TestAccAWSSpotFleetRequest_launchTemplateWithOverrides(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -236,7 +232,7 @@ func TestAccAWSSpotFleetRequest_launchTemplateWithOverrides(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestLaunchTemplateConfigWithOverrides(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestLaunchTemplateConfigWithOverrides(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -256,18 +252,17 @@ func TestAccAWSSpotFleetRequest_launchTemplateWithOverrides(t *testing.T) { func TestAccAWSSpotFleetRequest_launchTemplateToLaunchSpec(t *testing.T) { var before, after ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" - resource.Test(t, resource.TestCase{ + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestLaunchTemplateConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestLaunchTemplateConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -282,11 +277,11 @@ func TestAccAWSSpotFleetRequest_launchTemplateToLaunchSpec(t *testing.T) { ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccAWSSpotFleetRequestConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), - resource.TestCheckResourceAttr(resourceName, "spot_price", "0.005"), + resource.TestCheckResourceAttr(resourceName, "spot_price", "0.05"), resource.TestCheckResourceAttr(resourceName, "launch_specification.#", "1"), testAccCheckAWSSpotFleetRequestConfigRecreated(t, &before, &after), ), @@ -297,27 +292,26 @@ func TestAccAWSSpotFleetRequest_launchTemplateToLaunchSpec(t *testing.T) { func TestAccAWSSpotFleetRequest_launchSpecToLaunchTemplate(t *testing.T) { var before, after ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" - resource.Test(t, resource.TestCase{ + resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), - resource.TestCheckResourceAttr(resourceName, "spot_price", "0.005"), + resource.TestCheckResourceAttr(resourceName, "spot_price", "0.05"), resource.TestCheckResourceAttr(resourceName, "launch_specification.#", "1"), ), }, { - Config: testAccAWSSpotFleetRequestLaunchTemplateConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestLaunchTemplateConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -332,8 +326,7 @@ func TestAccAWSSpotFleetRequest_launchSpecToLaunchTemplate(t *testing.T) { func TestAccAWSSpotFleetRequest_instanceInterruptionBehavior(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -343,7 +336,7 @@ func TestAccAWSSpotFleetRequest_instanceInterruptionBehavior(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -362,8 +355,7 @@ func TestAccAWSSpotFleetRequest_instanceInterruptionBehavior(t *testing.T) { func TestAccAWSSpotFleetRequest_fleetType(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -373,7 +365,7 @@ func TestAccAWSSpotFleetRequest_fleetType(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigFleetType(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigFleetType(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -392,8 +384,7 @@ func TestAccAWSSpotFleetRequest_fleetType(t *testing.T) { func TestAccAWSSpotFleetRequest_iamInstanceProfileArn(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -403,7 +394,7 @@ func TestAccAWSSpotFleetRequest_iamInstanceProfileArn(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigIamInstanceProfileArn(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigIamInstanceProfileArn(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -422,8 +413,7 @@ func TestAccAWSSpotFleetRequest_iamInstanceProfileArn(t *testing.T) { func TestAccAWSSpotFleetRequest_changePriceForcesNewRequest(t *testing.T) { var before, after ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -433,11 +423,11 @@ func TestAccAWSSpotFleetRequest_changePriceForcesNewRequest(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), - resource.TestCheckResourceAttr(resourceName, "spot_price", "0.005"), + resource.TestCheckResourceAttr(resourceName, "spot_price", "0.05"), resource.TestCheckResourceAttr(resourceName, "launch_specification.#", "1"), ), }, @@ -448,12 +438,12 @@ func TestAccAWSSpotFleetRequest_changePriceForcesNewRequest(t *testing.T) { ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccAWSSpotFleetRequestConfigChangeSpotBidPrice(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigChangeSpotBidPrice(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), resource.TestCheckResourceAttr(resourceName, "launch_specification.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spot_price", "0.01"), + resource.TestCheckResourceAttr(resourceName, "spot_price", "0.05"), testAccCheckAWSSpotFleetRequestConfigRecreated(t, &before, &after), ), }, @@ -463,8 +453,7 @@ func TestAccAWSSpotFleetRequest_changePriceForcesNewRequest(t *testing.T) { func TestAccAWSSpotFleetRequest_updateTargetCapacity(t *testing.T) { var before, after ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -474,7 +463,7 @@ func TestAccAWSSpotFleetRequest_updateTargetCapacity(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -488,14 +477,14 @@ func TestAccAWSSpotFleetRequest_updateTargetCapacity(t *testing.T) { ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccAWSSpotFleetRequestConfigTargetCapacity(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigTargetCapacity(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "target_capacity", "3"), ), }, { - Config: testAccAWSSpotFleetRequestConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -508,8 +497,7 @@ func TestAccAWSSpotFleetRequest_updateTargetCapacity(t *testing.T) { func TestAccAWSSpotFleetRequest_updateExcessCapacityTerminationPolicy(t *testing.T) { var before, after ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -519,7 +507,7 @@ func TestAccAWSSpotFleetRequest_updateExcessCapacityTerminationPolicy(t *testing CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -533,7 +521,7 @@ func TestAccAWSSpotFleetRequest_updateExcessCapacityTerminationPolicy(t *testing ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, }, { - Config: testAccAWSSpotFleetRequestConfigExcessCapacityTermination(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigExcessCapacityTermination(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "excess_capacity_termination_policy", "NoTermination"), @@ -545,8 +533,7 @@ func TestAccAWSSpotFleetRequest_updateExcessCapacityTerminationPolicy(t *testing func TestAccAWSSpotFleetRequest_lowestPriceAzOrSubnetInRegion(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -556,7 +543,7 @@ func TestAccAWSSpotFleetRequest_lowestPriceAzOrSubnetInRegion(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -575,25 +562,27 @@ func TestAccAWSSpotFleetRequest_lowestPriceAzOrSubnetInRegion(t *testing.T) { func TestAccAWSSpotFleetRequest_lowestPriceAzInGivenList(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigWithAzs(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigWithAzs(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), resource.TestCheckResourceAttr(resourceName, "launch_specification.#", "2"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.1991689378.availability_zone", "us-west-2a"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.19404370.availability_zone", "us-west-2b"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*", map[string]string{ + "availability_zone": "us-west-2a", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*", map[string]string{ + "availability_zone": "us-west-2b", + }), ), }, { @@ -608,8 +597,7 @@ func TestAccAWSSpotFleetRequest_lowestPriceAzInGivenList(t *testing.T) { func TestAccAWSSpotFleetRequest_lowestPriceSubnetInGivenList(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -619,7 +607,7 @@ func TestAccAWSSpotFleetRequest_lowestPriceSubnetInGivenList(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigWithSubnet(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigWithSubnet(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -638,27 +626,29 @@ func TestAccAWSSpotFleetRequest_lowestPriceSubnetInGivenList(t *testing.T) { func TestAccAWSSpotFleetRequest_multipleInstanceTypesInSameAz(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigMultipleInstanceTypesinSameAz(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigMultipleInstanceTypesinSameAz(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), resource.TestCheckResourceAttr(resourceName, "launch_specification.#", "2"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.1991689378.instance_type", "m1.small"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.1991689378.availability_zone", "us-west-2a"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.590403189.instance_type", "m3.large"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.590403189.availability_zone", "us-west-2a"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*", map[string]string{ + "instance_type": "m1.small", + "availability_zone": "us-west-2a", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*", map[string]string{ + "instance_type": "m3.large", + "availability_zone": "us-west-2a", + }), ), }, { @@ -671,33 +661,9 @@ func TestAccAWSSpotFleetRequest_multipleInstanceTypesInSameAz(t *testing.T) { }) } -func testAccCheckAWSSpotFleetRequest_IamInstanceProfileArn( - sfr *ec2.SpotFleetRequestConfig) resource.TestCheckFunc { - return func(s *terraform.State) error { - if len(sfr.SpotFleetRequestConfig.LaunchSpecifications) == 0 { - return errors.New("Missing launch specification") - } - - spec := *sfr.SpotFleetRequestConfig.LaunchSpecifications[0] - - profile := spec.IamInstanceProfile - if profile == nil { - return fmt.Errorf("Expected IamInstanceProfile to be set, got nil") - } - //Validate the string whether it is ARN - re := regexp.MustCompile(`arn:aws:iam::\d{12}:instance-profile/?[a-zA-Z0-9+=,.@-_].*`) - if !re.MatchString(*profile.Arn) { - return fmt.Errorf("Expected IamInstanceProfile input as ARN, got %s", *profile.Arn) - } - - return nil - } -} - func TestAccAWSSpotFleetRequest_multipleInstanceTypesInSameSubnet(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -707,7 +673,7 @@ func TestAccAWSSpotFleetRequest_multipleInstanceTypesInSameSubnet(t *testing.T) CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigMultipleInstanceTypesinSameSubnet(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigMultipleInstanceTypesinSameSubnet(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -726,28 +692,30 @@ func TestAccAWSSpotFleetRequest_multipleInstanceTypesInSameSubnet(t *testing.T) func TestAccAWSSpotFleetRequest_overriddingSpotPrice(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigOverridingSpotPrice(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigOverridingSpotPrice(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), - resource.TestCheckResourceAttr(resourceName, "spot_price", "0.035"), + resource.TestCheckResourceAttr(resourceName, "spot_price", "0.05"), resource.TestCheckResourceAttr(resourceName, "launch_specification.#", "2"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.4143232216.spot_price", "0.01"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.4143232216.instance_type", "m3.large"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.1991689378.spot_price", ""), //there will not be a value here since it's not overriding - resource.TestCheckResourceAttr(resourceName, "launch_specification.1991689378.instance_type", "m1.small"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*", map[string]string{ + "spot_price": "0.05", + "instance_type": "m3.large", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*", map[string]string{ + "spot_price": "", //there will not be a value here since it's not overriding + "instance_type": "m1.small", + }), ), }, { @@ -762,8 +730,7 @@ func TestAccAWSSpotFleetRequest_overriddingSpotPrice(t *testing.T) { func TestAccAWSSpotFleetRequest_withoutSpotPrice(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -773,7 +740,7 @@ func TestAccAWSSpotFleetRequest_withoutSpotPrice(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigWithoutSpotPrice(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigWithoutSpotPrice(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -792,8 +759,7 @@ func TestAccAWSSpotFleetRequest_withoutSpotPrice(t *testing.T) { func TestAccAWSSpotFleetRequest_diversifiedAllocation(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -803,7 +769,7 @@ func TestAccAWSSpotFleetRequest_diversifiedAllocation(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigDiversifiedAllocation(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigDiversifiedAllocation(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -823,8 +789,7 @@ func TestAccAWSSpotFleetRequest_diversifiedAllocation(t *testing.T) { func TestAccAWSSpotFleetRequest_multipleInstancePools(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -834,7 +799,7 @@ func TestAccAWSSpotFleetRequest_multipleInstancePools(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigMultipleInstancePools(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigMultipleInstancePools(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -855,8 +820,7 @@ func TestAccAWSSpotFleetRequest_multipleInstancePools(t *testing.T) { func TestAccAWSSpotFleetRequest_withWeightedCapacity(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -875,22 +839,25 @@ func TestAccAWSSpotFleetRequest_withWeightedCapacity(t *testing.T) { } resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigWithWeightedCapacity(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigWithWeightedCapacity(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( fulfillSleep(), testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), resource.TestCheckResourceAttr(resourceName, "launch_specification.#", "2"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.4120185872.weighted_capacity", "3"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.4120185872.instance_type", "r3.large"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.590403189.weighted_capacity", "6"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.590403189.instance_type", "m3.large"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*", map[string]string{ + "weighted_capacity": "3", + "instance_type": "r3.large", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*", map[string]string{ + "weighted_capacity": "6", + "instance_type": "m3.large", + }), ), }, { @@ -905,8 +872,7 @@ func TestAccAWSSpotFleetRequest_withWeightedCapacity(t *testing.T) { func TestAccAWSSpotFleetRequest_withEBSDisk(t *testing.T) { var config ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -916,7 +882,7 @@ func TestAccAWSSpotFleetRequest_withEBSDisk(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestEBSConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestEBSConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &config), testAccCheckAWSSpotFleetRequest_EBSAttributes(&config), @@ -934,8 +900,7 @@ func TestAccAWSSpotFleetRequest_withEBSDisk(t *testing.T) { func TestAccAWSSpotFleetRequest_LaunchSpecification_EbsBlockDevice_KmsKeyId(t *testing.T) { var config ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -945,7 +910,7 @@ func TestAccAWSSpotFleetRequest_LaunchSpecification_EbsBlockDevice_KmsKeyId(t *t CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestLaunchSpecificationEbsBlockDeviceKmsKeyId(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestLaunchSpecificationEbsBlockDeviceKmsKeyId(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &config), ), @@ -962,8 +927,7 @@ func TestAccAWSSpotFleetRequest_LaunchSpecification_EbsBlockDevice_KmsKeyId(t *t func TestAccAWSSpotFleetRequest_LaunchSpecification_RootBlockDevice_KmsKeyId(t *testing.T) { var config ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -973,7 +937,7 @@ func TestAccAWSSpotFleetRequest_LaunchSpecification_RootBlockDevice_KmsKeyId(t * CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestLaunchSpecificationRootBlockDeviceKmsKeyId(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestLaunchSpecificationRootBlockDeviceKmsKeyId(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &config), ), @@ -990,24 +954,24 @@ func TestAccAWSSpotFleetRequest_LaunchSpecification_RootBlockDevice_KmsKeyId(t * func TestAccAWSSpotFleetRequest_withTags(t *testing.T) { var config ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestTagsConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestTagsConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &config), - resource.TestCheckResourceAttr(resourceName, "launch_specification.24370212.tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.24370212.tags.First", "TfAccTest"), - resource.TestCheckResourceAttr(resourceName, "launch_specification.24370212.tags.Second", "Terraform"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "launch_specification.*", map[string]string{ + "tags.%": "2", + "tags.First": "TfAccTest", + "tags.Second": "Terraform", + }), ), }, { @@ -1022,8 +986,7 @@ func TestAccAWSSpotFleetRequest_withTags(t *testing.T) { func TestAccAWSSpotFleetRequest_placementTenancyAndGroup(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -1033,7 +996,7 @@ func TestAccAWSSpotFleetRequest_placementTenancyAndGroup(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestTenancyGroupConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestTenancyGroupConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -1052,8 +1015,7 @@ func TestAccAWSSpotFleetRequest_placementTenancyAndGroup(t *testing.T) { func TestAccAWSSpotFleetRequest_WithELBs(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -1063,7 +1025,7 @@ func TestAccAWSSpotFleetRequest_WithELBs(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigWithELBs(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigWithELBs(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -1083,8 +1045,7 @@ func TestAccAWSSpotFleetRequest_WithELBs(t *testing.T) { func TestAccAWSSpotFleetRequest_WithTargetGroups(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" resource.ParallelTest(t, resource.TestCase{ @@ -1093,7 +1054,7 @@ func TestAccAWSSpotFleetRequest_WithTargetGroups(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfigWithTargetGroups(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfigWithTargetGroups(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), resource.TestCheckResourceAttr(resourceName, "spot_request_state", "active"), @@ -1111,10 +1072,51 @@ func TestAccAWSSpotFleetRequest_WithTargetGroups(t *testing.T) { }) } +func TestAccAWSSpotFleetRequest_zero_capacity(t *testing.T) { + var sfr ec2.SpotFleetRequestConfig + rName := acctest.RandomWithPrefix("tf-acc-test") + validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) + resourceName := "aws_spot_fleet_request.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEc2SpotFleetRequest(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSSpotFleetRequestZeroCapacityConfig(rName, validUntil), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), + resource.TestCheckResourceAttr(resourceName, "target_capacity", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"wait_for_fulfillment"}, + }, + { + Config: testAccAWSSpotFleetRequestConfig(rName, validUntil), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), + resource.TestCheckResourceAttr(resourceName, "target_capacity", "2"), + ), + }, + { + Config: testAccAWSSpotFleetRequestZeroCapacityConfig(rName, validUntil), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), + resource.TestCheckResourceAttr(resourceName, "target_capacity", "0"), + ), + }, + }, + }) +} + func TestAccAWSSpotFleetRequest_WithInstanceStoreAmi(t *testing.T) { - t.Skip("Test fails due to test harness constraints") - rName := acctest.RandString(10) - rInt := acctest.RandInt() + TestAccSkip(t, "Test fails due to test harness constraints") + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resource.ParallelTest(t, resource.TestCase{ @@ -1123,7 +1125,7 @@ func TestAccAWSSpotFleetRequest_WithInstanceStoreAmi(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestLaunchSpecificationWithInstanceStoreAmi(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestLaunchSpecificationWithInstanceStoreAmi(rName, validUntil), ExpectError: regexp.MustCompile("Instance store backed AMIs do not provide a root device name"), }, }, @@ -1132,8 +1134,7 @@ func TestAccAWSSpotFleetRequest_WithInstanceStoreAmi(t *testing.T) { func TestAccAWSSpotFleetRequest_disappears(t *testing.T) { var sfr ec2.SpotFleetRequestConfig - rName := acctest.RandString(10) - rInt := acctest.RandInt() + rName := acctest.RandomWithPrefix("tf-acc-test") validUntil := time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339) resourceName := "aws_spot_fleet_request.test" @@ -1143,10 +1144,10 @@ func TestAccAWSSpotFleetRequest_disappears(t *testing.T) { CheckDestroy: testAccCheckAWSSpotFleetRequestDestroy, Steps: []resource.TestStep{ { - Config: testAccAWSSpotFleetRequestConfig(rName, rInt, validUntil), + Config: testAccAWSSpotFleetRequestConfig(rName, validUntil), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSSpotFleetRequestExists(resourceName, &sfr), - testAccCheckAWSSpotFleetRequestDisappears(&sfr), + testAccCheckResourceDisappears(testAccProvider, resourceAwsSpotFleetRequest(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -1197,16 +1198,6 @@ func testAccCheckAWSSpotFleetRequestExists( } } -func testAccCheckAWSSpotFleetRequestDisappears(sfr *ec2.SpotFleetRequestConfig) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - sfrId := aws.StringValue(sfr.SpotFleetRequestId) - err := deleteSpotFleetRequest(sfrId, true, 5*time.Minute, conn) - - return err - } -} - func testAccCheckAWSSpotFleetRequestDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn @@ -1295,8 +1286,33 @@ func testAccPreCheckAWSEc2SpotFleetRequest(t *testing.T) { } } -func testAccAWSSpotFleetRequestConfigBase(rName string, rInt int) string { - return testAccLatestAmazonLinuxHvmEbsAmiConfig() + fmt.Sprintf(` +func testAccCheckAWSSpotFleetRequest_IamInstanceProfileArn(sfr *ec2.SpotFleetRequestConfig) resource.TestCheckFunc { + return func(s *terraform.State) error { + if len(sfr.SpotFleetRequestConfig.LaunchSpecifications) == 0 { + return errors.New("Missing launch specification") + } + + spec := *sfr.SpotFleetRequestConfig.LaunchSpecifications[0] + + profile := spec.IamInstanceProfile + if profile == nil { + return fmt.Errorf("Expected IamInstanceProfile to be set, got nil") + } + //Validate the string whether it is ARN + re := regexp.MustCompile(`arn:aws:iam::\d{12}:instance-profile/?[a-zA-Z0-9+=,.@-_].*`) + if !re.MatchString(*profile.Arn) { + return fmt.Errorf("Expected IamInstanceProfile input as ARN, got %s", *profile.Arn) + } + + return nil + } +} + +func testAccAWSSpotFleetRequestConfigBase(rName string) string { + return composeConfig( + testAccLatestAmazonLinuxHvmEbsAmiConfig(), + testAccAvailableEc2InstanceTypeForRegion("t3.micro", "t2.micro"), + fmt.Sprintf(` data "aws_availability_zones" "available" { state = "available" @@ -1305,16 +1321,17 @@ data "aws_availability_zones" "available" { values = ["opt-in-not-required"] } } + resource "aws_key_pair" "test" { key_name = %[1]q public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD3F6tyPEFEzV0LX3X8BsXdMsQz1x2cEikKDEY0aIj41qgxMCP/iteneqXSIFZBp5vizPvaoIR3Um9xK7PGoW8giupGn+EPuxIA4cDM4vzOqOkiMPhz5XK0whEjkVzTo4+S0puvDZuwIsdiW9mxhJc7tgBNL0cYlWSYVkz4G/fslNfRPW5mYAM49f4fhtxPb5ok4Q2Lg9dPKVHO/Bgeu5woMc7RY0p1ej6D4CKFE6lymSDJpW0YHX/wqE9+cfEauh7xZcG0q9t2ta6F6fmX0agvpFyZo8aFbXeUBr7osSCJNgvavWbM/06niWrOvYX2xwWdhXmXSrbX8ZbabVohBK41 phodgson@thoughtworks.com" tags = { - Name = %[1]q + Name = %[1]q } } -resource "aws_iam_role" "test-role" { +resource "aws_iam_role" "test" { name = %[1]q assume_role_policy = < %s", - d.Get("vpc_id").(string), - d.Get("dhcp_options_id").(string)) + vpcId := d.Get("vpc_id").(string) + optsID := d.Get("dhcp_options_id").(string) - optsID := aws.String(d.Get("dhcp_options_id").(string)) - vpcID := aws.String(d.Get("vpc_id").(string)) + log.Printf("[INFO] Creating DHCP Options association: %s => %s", vpcId, optsID) if _, err := conn.AssociateDhcpOptions(&ec2.AssociateDhcpOptionsInput{ - DhcpOptionsId: optsID, - VpcId: vpcID, + DhcpOptionsId: aws.String(optsID), + VpcId: aws.String(vpcId), }); err != nil { return err } // Set the ID and return - d.SetId(*optsID + "-" + *vpcID) - log.Printf("[INFO] Association ID: %s", d.Id()) + d.SetId(fmt.Sprintf("%s-%s", optsID, vpcId)) - return nil + log.Printf("[INFO] VPC DHCP Association ID: %s", d.Id()) + + return resourceAwsVpcDhcpOptionsAssociationRead(d, meta) } func resourceAwsVpcDhcpOptionsAssociationRead(d *schema.ResourceData, meta interface{}) error { @@ -92,11 +91,15 @@ func resourceAwsVpcDhcpOptionsAssociationRead(d *schema.ResourceData, meta inter } vpc := vpcRaw.(*ec2.Vpc) - if *vpc.VpcId != d.Get("vpc_id") || *vpc.DhcpOptionsId != d.Get("dhcp_options_id") { + if aws.StringValue(vpc.VpcId) != d.Get("vpc_id") || + aws.StringValue(vpc.DhcpOptionsId) != d.Get("dhcp_options_id") { log.Printf("[INFO] It seems the DHCP Options association is gone. Deleting reference from Graph...") d.SetId("") } + d.Set("vpc_id", vpc.VpcId) + d.Set("dhcp_options_id", vpc.DhcpOptionsId) + return nil } @@ -116,5 +119,9 @@ func resourceAwsVpcDhcpOptionsAssociationDelete(d *schema.ResourceData, meta int VpcId: aws.String(d.Get("vpc_id").(string)), }) + if isAWSErr(err, "InvalidVpcID.NotFound", "") { + return nil + } + return err } diff --git a/aws/resource_aws_vpc_dhcp_options_association_test.go b/aws/resource_aws_vpc_dhcp_options_association_test.go index 1b8255da979..5616b55cec1 100644 --- a/aws/resource_aws_vpc_dhcp_options_association_test.go +++ b/aws/resource_aws_vpc_dhcp_options_association_test.go @@ -4,15 +4,16 @@ import ( "fmt" "testing" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSDHCPOptionsAssociation_basic(t *testing.T) { var v ec2.Vpc var d ec2.DhcpOptions - resourceName := "aws_vpc_dhcp_options_association.foo" + resourceName := "aws_vpc_dhcp_options_association.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -22,9 +23,9 @@ func TestAccAWSDHCPOptionsAssociation_basic(t *testing.T) { { Config: testAccDHCPOptionsAssociationConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckDHCPOptionsExists("aws_vpc_dhcp_options.foo", &d), - testAccCheckVpcExists("aws_vpc.foo", &v), - testAccCheckDHCPOptionsAssociationExist("aws_vpc_dhcp_options_association.foo", &v), + testAccCheckDHCPOptionsExists("aws_vpc_dhcp_options.test", &d), + testAccCheckVpcExists("aws_vpc.test", &v), + testAccCheckDHCPOptionsAssociationExist(resourceName, &v), ), }, { @@ -37,6 +38,54 @@ func TestAccAWSDHCPOptionsAssociation_basic(t *testing.T) { }) } +func TestAccAWSDHCPOptionsAssociation_disappears_vpc(t *testing.T) { + var v ec2.Vpc + var d ec2.DhcpOptions + resourceName := "aws_vpc_dhcp_options_association.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDHCPOptionsAssociationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDHCPOptionsAssociationConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckDHCPOptionsExists("aws_vpc_dhcp_options.test", &d), + testAccCheckVpcExists("aws_vpc.test", &v), + testAccCheckDHCPOptionsAssociationExist(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsVpc(), "aws_vpc.test"), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAWSDHCPOptionsAssociation_disappears_dhcp(t *testing.T) { + var v ec2.Vpc + var d ec2.DhcpOptions + resourceName := "aws_vpc_dhcp_options_association.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDHCPOptionsAssociationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDHCPOptionsAssociationConfig, + Check: resource.ComposeTestCheckFunc( + testAccCheckDHCPOptionsExists("aws_vpc_dhcp_options.test", &d), + testAccCheckVpcExists("aws_vpc.test", &v), + testAccCheckDHCPOptionsAssociationExist(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsVpcDhcpOptions(), "aws_vpc_dhcp_options.test"), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccDHCPOptionsAssociationVPCImportIdFunc(resourceName string) resource.ImportStateIdFunc { return func(s *terraform.State) (string, error) { rs, ok := s.RootModule().Resources[resourceName] @@ -81,12 +130,14 @@ func testAccCheckDHCPOptionsAssociationExist(n string, vpc *ec2.Vpc) resource.Te return fmt.Errorf("No DHCP Options Set association ID is set") } - if *vpc.DhcpOptionsId != rs.Primary.Attributes["dhcp_options_id"] { - return fmt.Errorf("VPC %s does not have DHCP Options Set %s associated", *vpc.VpcId, rs.Primary.Attributes["dhcp_options_id"]) + if aws.StringValue(vpc.DhcpOptionsId) != rs.Primary.Attributes["dhcp_options_id"] { + return fmt.Errorf("VPC %s does not have DHCP Options Set %s associated", + aws.StringValue(vpc.VpcId), rs.Primary.Attributes["dhcp_options_id"]) } - if *vpc.VpcId != rs.Primary.Attributes["vpc_id"] { - return fmt.Errorf("DHCP Options Set %s is not associated with VPC %s", rs.Primary.Attributes["dhcp_options_id"], *vpc.VpcId) + if aws.StringValue(vpc.VpcId) != rs.Primary.Attributes["vpc_id"] { + return fmt.Errorf("DHCP Options Set %s is not associated with VPC %s", + rs.Primary.Attributes["dhcp_options_id"], aws.StringValue(vpc.VpcId)) } return nil @@ -94,27 +145,28 @@ func testAccCheckDHCPOptionsAssociationExist(n string, vpc *ec2.Vpc) resource.Te } const testAccDHCPOptionsAssociationConfig = ` -resource "aws_vpc" "foo" { - cidr_block = "10.1.0.0/16" - tags = { - Name = "terraform-testacc-vpc-dhcp-options-association" - } +resource "aws_vpc" "test" { + cidr_block = "10.1.0.0/16" + + tags = { + Name = "terraform-testacc-vpc-dhcp-options-association" + } } -resource "aws_vpc_dhcp_options" "foo" { - domain_name = "service.consul" - domain_name_servers = ["127.0.0.1", "10.0.0.2"] - ntp_servers = ["127.0.0.1"] - netbios_name_servers = ["127.0.0.1"] - netbios_node_type = 2 +resource "aws_vpc_dhcp_options" "test" { + domain_name = "service.consul" + domain_name_servers = ["127.0.0.1", "10.0.0.2"] + ntp_servers = ["127.0.0.1"] + netbios_name_servers = ["127.0.0.1"] + netbios_node_type = 2 - tags = { - Name = "foo" - } + tags = { + Name = "terraform-testacc-vpc-dhcp-options-association" + } } -resource "aws_vpc_dhcp_options_association" "foo" { - vpc_id = "${aws_vpc.foo.id}" - dhcp_options_id = "${aws_vpc_dhcp_options.foo.id}" +resource "aws_vpc_dhcp_options_association" "test" { + vpc_id = "${aws_vpc.test.id}" + dhcp_options_id = "${aws_vpc_dhcp_options.test.id}" } ` diff --git a/aws/resource_aws_vpc_dhcp_options_test.go b/aws/resource_aws_vpc_dhcp_options_test.go index 3c5dd67f836..2137945224b 100644 --- a/aws/resource_aws_vpc_dhcp_options_test.go +++ b/aws/resource_aws_vpc_dhcp_options_test.go @@ -3,13 +3,14 @@ package aws import ( "fmt" "log" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -101,6 +102,7 @@ func TestAccAWSDHCPOptions_basic(t *testing.T) { Config: testAccDHCPOptionsConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckDHCPOptionsExists(resourceName, &d), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`dhcp-options/dopt-.+`)), resource.TestCheckResourceAttr(resourceName, "domain_name", fmt.Sprintf("service.%s", rName)), resource.TestCheckResourceAttr(resourceName, "domain_name_servers.0", "127.0.0.1"), resource.TestCheckResourceAttr(resourceName, "domain_name_servers.1", "10.0.0.2"), @@ -186,6 +188,28 @@ func TestAccAWSDHCPOptions_tags(t *testing.T) { }) } +func TestAccAWSDHCPOptions_disappears(t *testing.T) { + var d ec2.DhcpOptions + resourceName := "aws_vpc_dhcp_options.test" + rName := acctest.RandString(5) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckDHCPOptionsDestroy, + Steps: []resource.TestStep{ + { + Config: testAccDHCPOptionsConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckDHCPOptionsExists(resourceName, &d), + testAccCheckResourceDisappears(testAccProvider, resourceAwsVpcDhcpOptions(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func testAccCheckDHCPOptionsDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn diff --git a/aws/resource_aws_vpc_endpoint.go b/aws/resource_aws_vpc_endpoint.go index f58966f47ff..bd56eb76a96 100644 --- a/aws/resource_aws_vpc_endpoint.go +++ b/aws/resource_aws_vpc_endpoint.go @@ -7,11 +7,12 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -26,6 +27,10 @@ func resourceAwsVpcEndpoint() *schema.Resource { }, Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, "auto_accept": { Type: schema.TypeBool, Optional: true, @@ -178,14 +183,14 @@ func resourceAwsVpcEndpointCreate(d *schema.ResourceData, meta interface{}) erro vpce := resp.VpcEndpoint d.SetId(aws.StringValue(vpce.VpcEndpointId)) - if _, ok := d.GetOk("auto_accept"); ok && aws.StringValue(vpce.State) == "pendingAcceptance" { - if err := vpcEndpointAccept(conn, d.Id(), aws.StringValue(vpce.ServiceName)); err != nil { + if v, ok := d.GetOk("auto_accept"); ok && v.(bool) && aws.StringValue(vpce.State) == "pendingAcceptance" { + if err := vpcEndpointAccept(conn, d.Id(), aws.StringValue(vpce.ServiceName), d.Timeout(schema.TimeoutCreate)); err != nil { return err } } if err := vpcEndpointWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil { - return err + return fmt.Errorf("error waiting for VPC Endpoint (%s) to become available: %s", d.Id(), err) } return resourceAwsVpcEndpointRead(d, meta) @@ -215,6 +220,15 @@ func resourceAwsVpcEndpointRead(d *schema.ResourceData, meta interface{}) error vpce := vpceRaw.(*ec2.VpcEndpoint) + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Service: "ec2", + Region: meta.(*AWSClient).region, + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("vpc-endpoint/%s", d.Id()), + }.String() + d.Set("arn", arn) + serviceName := aws.StringValue(vpce.ServiceName) d.Set("service_name", serviceName) d.Set("state", vpce.State) @@ -287,44 +301,46 @@ func resourceAwsVpcEndpointRead(d *schema.ResourceData, meta interface{}) error func resourceAwsVpcEndpointUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn - if _, ok := d.GetOk("auto_accept"); ok && d.Get("state").(string) == "pendingAcceptance" { - if err := vpcEndpointAccept(conn, d.Id(), d.Get("service_name").(string)); err != nil { + if d.HasChange("auto_accept") && d.Get("auto_accept").(bool) && d.Get("state").(string) == "pendingAcceptance" { + if err := vpcEndpointAccept(conn, d.Id(), d.Get("service_name").(string), d.Timeout(schema.TimeoutUpdate)); err != nil { return err } } - req := &ec2.ModifyVpcEndpointInput{ - VpcEndpointId: aws.String(d.Id()), - } - - if d.HasChange("policy") { - policy, err := structure.NormalizeJsonString(d.Get("policy")) - if err != nil { - return fmt.Errorf("policy contains an invalid JSON: %s", err) + if d.HasChanges("policy", "route_table_ids", "subnet_ids", "security_group_ids", "private_dns_enabled") { + req := &ec2.ModifyVpcEndpointInput{ + VpcEndpointId: aws.String(d.Id()), } - if policy == "" { - req.ResetPolicy = aws.Bool(true) - } else { - req.PolicyDocument = aws.String(policy) + if d.HasChange("policy") { + policy, err := structure.NormalizeJsonString(d.Get("policy")) + if err != nil { + return fmt.Errorf("policy contains an invalid JSON: %s", err) + } + + if policy == "" { + req.ResetPolicy = aws.Bool(true) + } else { + req.PolicyDocument = aws.String(policy) + } } - } - setVpcEndpointUpdateLists(d, "route_table_ids", &req.AddRouteTableIds, &req.RemoveRouteTableIds) - setVpcEndpointUpdateLists(d, "subnet_ids", &req.AddSubnetIds, &req.RemoveSubnetIds) - setVpcEndpointUpdateLists(d, "security_group_ids", &req.AddSecurityGroupIds, &req.RemoveSecurityGroupIds) + setVpcEndpointUpdateLists(d, "route_table_ids", &req.AddRouteTableIds, &req.RemoveRouteTableIds) + setVpcEndpointUpdateLists(d, "subnet_ids", &req.AddSubnetIds, &req.RemoveSubnetIds) + setVpcEndpointUpdateLists(d, "security_group_ids", &req.AddSecurityGroupIds, &req.RemoveSecurityGroupIds) - if d.HasChange("private_dns_enabled") { - req.PrivateDnsEnabled = aws.Bool(d.Get("private_dns_enabled").(bool)) - } + if d.HasChange("private_dns_enabled") { + req.PrivateDnsEnabled = aws.Bool(d.Get("private_dns_enabled").(bool)) + } - log.Printf("[DEBUG] Updating VPC Endpoint: %#v", req) - if _, err := conn.ModifyVpcEndpoint(req); err != nil { - return fmt.Errorf("Error updating VPC Endpoint: %s", err) - } + log.Printf("[DEBUG] Updating VPC Endpoint: %#v", req) + if _, err := conn.ModifyVpcEndpoint(req); err != nil { + return fmt.Errorf("Error updating VPC Endpoint: %s", err) + } - if err := vpcEndpointWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { - return err + if err := vpcEndpointWaitUntilAvailable(conn, d.Id(), d.Timeout(schema.TimeoutUpdate)); err != nil { + return err + } } if d.HasChange("tags") { @@ -359,7 +375,7 @@ func resourceAwsVpcEndpointDelete(d *schema.ResourceData, meta interface{}) erro return nil } -func vpcEndpointAccept(conn *ec2.EC2, vpceId, svcName string) error { +func vpcEndpointAccept(conn *ec2.EC2, vpceId, svcName string, timeout time.Duration) error { describeSvcReq := &ec2.DescribeVpcEndpointServiceConfigurationsInput{} describeSvcReq.Filters = buildEC2AttributeFilterList( map[string]string{ @@ -369,7 +385,7 @@ func vpcEndpointAccept(conn *ec2.EC2, vpceId, svcName string) error { describeSvcResp, err := conn.DescribeVpcEndpointServiceConfigurations(describeSvcReq) if err != nil { - return fmt.Errorf("Error reading VPC Endpoint Service: %s", err) + return fmt.Errorf("error reading VPC Endpoint Service (%s): %s", svcName, err) } if describeSvcResp == nil || len(describeSvcResp.ServiceConfigurations) == 0 { return fmt.Errorf("No matching VPC Endpoint Service found") @@ -383,7 +399,21 @@ func vpcEndpointAccept(conn *ec2.EC2, vpceId, svcName string) error { log.Printf("[DEBUG] Accepting VPC Endpoint connection: %#v", acceptEpReq) _, err = conn.AcceptVpcEndpointConnections(acceptEpReq) if err != nil { - return fmt.Errorf("Error accepting VPC Endpoint connection: %s", err) + return fmt.Errorf("error accepting VPC Endpoint (%s) connection: %s", vpceId, err) + } + + stateConf := &resource.StateChangeConf{ + Pending: []string{"pendingAcceptance"}, + Target: []string{"available"}, + Refresh: vpcEndpointStateRefresh(conn, vpceId), + Timeout: timeout, + Delay: 5 * time.Second, + MinTimeout: 5 * time.Second, + } + + _, err = stateConf.WaitForState() + if err != nil { + return fmt.Errorf("error waiting for VPC Endpoint (%s) to be accepted: %s", vpceId, err) } return nil @@ -432,11 +462,10 @@ func vpcEndpointWaitUntilAvailable(conn *ec2.EC2, vpceId string, timeout time.Du Delay: 5 * time.Second, MinTimeout: 5 * time.Second, } - if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf("Error waiting for VPC Endpoint (%s) to become available: %s", vpceId, err) - } - return nil + _, err := stateConf.WaitForState() + + return err } func vpcEndpointWaitUntilDeleted(conn *ec2.EC2, vpceId string, timeout time.Duration) error { diff --git a/aws/resource_aws_vpc_endpoint_connection_notification.go b/aws/resource_aws_vpc_endpoint_connection_notification.go index 171c10f5ec4..4dfc76727d1 100644 --- a/aws/resource_aws_vpc_endpoint_connection_notification.go +++ b/aws/resource_aws_vpc_endpoint_connection_notification.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsVpcEndpointConnectionNotification() *schema.Resource { diff --git a/aws/resource_aws_vpc_endpoint_connection_notification_test.go b/aws/resource_aws_vpc_endpoint_connection_notification_test.go index 4e716cd59ef..7c7d6306010 100644 --- a/aws/resource_aws_vpc_endpoint_connection_notification_test.go +++ b/aws/resource_aws_vpc_endpoint_connection_notification_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSVpcEndpointConnectionNotification_basic(t *testing.T) { diff --git a/aws/resource_aws_vpc_endpoint_route_table_association.go b/aws/resource_aws_vpc_endpoint_route_table_association.go index 448848ddfcb..e9ef933fe60 100644 --- a/aws/resource_aws_vpc_endpoint_route_table_association.go +++ b/aws/resource_aws_vpc_endpoint_route_table_association.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/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsVpcEndpointRouteTableAssociation() *schema.Resource { diff --git a/aws/resource_aws_vpc_endpoint_route_table_association_test.go b/aws/resource_aws_vpc_endpoint_route_table_association_test.go index 09360933a2c..8c678514e37 100644 --- a/aws/resource_aws_vpc_endpoint_route_table_association_test.go +++ b/aws/resource_aws_vpc_endpoint_route_table_association_test.go @@ -7,9 +7,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSVpcEndpointRouteTableAssociation_basic(t *testing.T) { diff --git a/aws/resource_aws_vpc_endpoint_service.go b/aws/resource_aws_vpc_endpoint_service.go index bf7521ede16..23beacb44a2 100644 --- a/aws/resource_aws_vpc_endpoint_service.go +++ b/aws/resource_aws_vpc_endpoint_service.go @@ -7,9 +7,10 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -35,6 +36,10 @@ func resourceAwsVpcEndpointService() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, Set: schema.HashString, }, + "arn": { + Type: schema.TypeString, + Computed: true, + }, "availability_zones": { Type: schema.TypeSet, Elem: &schema.Schema{Type: schema.TypeString}, @@ -137,12 +142,17 @@ func resourceAwsVpcEndpointServiceRead(d *schema.ResourceData, meta interface{}) return nil } + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Service: "ec2", + Region: meta.(*AWSClient).region, + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("vpc-endpoint-service/%s", d.Id()), + }.String() + d.Set("arn", arn) + svcCfg := svcCfgRaw.(*ec2.ServiceConfiguration) d.Set("acceptance_required", svcCfg.AcceptanceRequired) - err = d.Set("network_load_balancer_arns", flattenStringSet(svcCfg.NetworkLoadBalancerArns)) - if err != nil { - return fmt.Errorf("error setting network_load_balancer_arns: %s", err) - } err = d.Set("availability_zones", flattenStringSet(svcCfg.AvailabilityZones)) if err != nil { return fmt.Errorf("error setting availability_zones: %s", err) @@ -152,6 +162,10 @@ func resourceAwsVpcEndpointServiceRead(d *schema.ResourceData, meta interface{}) return fmt.Errorf("error setting base_endpoint_dns_names: %s", err) } d.Set("manages_vpc_endpoints", svcCfg.ManagesVpcEndpoints) + err = d.Set("network_load_balancer_arns", flattenStringSet(svcCfg.NetworkLoadBalancerArns)) + if err != nil { + return fmt.Errorf("error setting network_load_balancer_arns: %s", err) + } d.Set("private_dns_name", svcCfg.PrivateDnsName) d.Set("service_name", svcCfg.ServiceName) d.Set("service_type", svcCfg.ServiceType[0].ServiceType) @@ -179,35 +193,36 @@ func resourceAwsVpcEndpointServiceRead(d *schema.ResourceData, meta interface{}) func resourceAwsVpcEndpointServiceUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).ec2conn - svcId := d.Id() + if d.HasChanges("acceptance_required", "network_load_balancer_arns") { + modifyCfgReq := &ec2.ModifyVpcEndpointServiceConfigurationInput{ + ServiceId: aws.String(d.Id()), + } + + if d.HasChange("acceptance_required") { + modifyCfgReq.AcceptanceRequired = aws.Bool(d.Get("acceptance_required").(bool)) + } + + setVpcEndpointServiceUpdateLists(d, "network_load_balancer_arns", + &modifyCfgReq.AddNetworkLoadBalancerArns, &modifyCfgReq.RemoveNetworkLoadBalancerArns) - modifyCfgReq := &ec2.ModifyVpcEndpointServiceConfigurationInput{ - ServiceId: aws.String(svcId), - } - modifyCfg := false - if d.HasChange("acceptance_required") { - modifyCfgReq.AcceptanceRequired = aws.Bool(d.Get("acceptance_required").(bool)) - modifyCfg = true - } - if setVpcEndpointServiceUpdateLists(d, "network_load_balancer_arns", - &modifyCfgReq.AddNetworkLoadBalancerArns, &modifyCfgReq.RemoveNetworkLoadBalancerArns) { - modifyCfg = true - } - if modifyCfg { log.Printf("[DEBUG] Modifying VPC Endpoint Service configuration: %#v", modifyCfgReq) if _, err := conn.ModifyVpcEndpointServiceConfiguration(modifyCfgReq); err != nil { return fmt.Errorf("Error modifying VPC Endpoint Service configuration: %s", err.Error()) } + if err := vpcEndpointServiceWaitUntilAvailable(d, conn); err != nil { return err } } - modifyPermReq := &ec2.ModifyVpcEndpointServicePermissionsInput{ - ServiceId: aws.String(svcId), - } - if setVpcEndpointServiceUpdateLists(d, "allowed_principals", - &modifyPermReq.AddAllowedPrincipals, &modifyPermReq.RemoveAllowedPrincipals) { + if d.HasChange("allowed_principals") { + modifyPermReq := &ec2.ModifyVpcEndpointServicePermissionsInput{ + ServiceId: aws.String(d.Id()), + } + + setVpcEndpointServiceUpdateLists(d, "allowed_principals", + &modifyPermReq.AddAllowedPrincipals, &modifyPermReq.RemoveAllowedPrincipals) + log.Printf("[DEBUG] Modifying VPC Endpoint Service permissions: %#v", modifyPermReq) if _, err := conn.ModifyVpcEndpointServicePermissions(modifyPermReq); err != nil { return fmt.Errorf("Error modifying VPC Endpoint Service permissions: %s", err.Error()) @@ -302,26 +317,22 @@ func waitForVpcEndpointServiceDeletion(conn *ec2.EC2, serviceID string) error { return err } -func setVpcEndpointServiceUpdateLists(d *schema.ResourceData, key string, a, r *[]*string) bool { - if !d.HasChange(key) { - return false - } - - o, n := d.GetChange(key) - os := o.(*schema.Set) - ns := n.(*schema.Set) +func setVpcEndpointServiceUpdateLists(d *schema.ResourceData, key string, a, r *[]*string) { + if d.HasChange(key) { + o, n := d.GetChange(key) + os := o.(*schema.Set) + ns := n.(*schema.Set) - add := expandStringList(ns.Difference(os).List()) - if len(add) > 0 { - *a = add - } + add := expandStringList(ns.Difference(os).List()) + if len(add) > 0 { + *a = add + } - remove := expandStringList(os.Difference(ns).List()) - if len(remove) > 0 { - *r = remove + remove := expandStringList(os.Difference(ns).List()) + if len(remove) > 0 { + *r = remove + } } - - return true } func flattenVpcEndpointServiceAllowedPrincipals(allowedPrincipals []*ec2.AllowedPrincipal) *schema.Set { diff --git a/aws/resource_aws_vpc_endpoint_service_allowed_principal.go b/aws/resource_aws_vpc_endpoint_service_allowed_principal.go index 7b43a751ab3..a315cd80eaf 100644 --- a/aws/resource_aws_vpc_endpoint_service_allowed_principal.go +++ b/aws/resource_aws_vpc_endpoint_service_allowed_principal.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsVpcEndpointServiceAllowedPrincipal() *schema.Resource { diff --git a/aws/resource_aws_vpc_endpoint_service_allowed_principal_test.go b/aws/resource_aws_vpc_endpoint_service_allowed_principal_test.go index 3d78817765c..2d41749f3e8 100644 --- a/aws/resource_aws_vpc_endpoint_service_allowed_principal_test.go +++ b/aws/resource_aws_vpc_endpoint_service_allowed_principal_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSVpcEndpointServiceAllowedPrincipal_basic(t *testing.T) { diff --git a/aws/resource_aws_vpc_endpoint_service_test.go b/aws/resource_aws_vpc_endpoint_service_test.go index a81c265c5aa..13f3d33cebd 100644 --- a/aws/resource_aws_vpc_endpoint_service_test.go +++ b/aws/resource_aws_vpc_endpoint_service_test.go @@ -3,14 +3,14 @@ package aws import ( "fmt" "log" + "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -82,8 +82,8 @@ func testSweepEc2VpcEndpointServices(region string) error { func TestAccAWSVpcEndpointService_basic(t *testing.T) { var svcCfg ec2.ServiceConfiguration resourceName := "aws_vpc_endpoint_service.test" - rName1 := fmt.Sprintf("tf-testacc-vpcesvc-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) - rName2 := fmt.Sprintf("tf-testacc-vpcesvc-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) + rName1 := acctest.RandomWithPrefix("tf-acc-test") + rName2 := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -99,6 +99,7 @@ func TestAccAWSVpcEndpointService_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "allowed_principals.#", "0"), resource.TestCheckResourceAttr(resourceName, "manages_vpc_endpoints", "false"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), ), }, { @@ -110,11 +111,11 @@ func TestAccAWSVpcEndpointService_basic(t *testing.T) { }) } -func TestAccAWSVpcEndpointService_AllowedPrincipalsAndTags(t *testing.T) { +func TestAccAWSVpcEndpointService_AllowedPrincipals(t *testing.T) { var svcCfg ec2.ServiceConfiguration resourceName := "aws_vpc_endpoint_service.test" - rName1 := fmt.Sprintf("tf-testacc-vpcesvc-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) - rName2 := fmt.Sprintf("tf-testacc-vpcesvc-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) + rName1 := acctest.RandomWithPrefix("tf-acc-test") + rName2 := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -122,17 +123,16 @@ func TestAccAWSVpcEndpointService_AllowedPrincipalsAndTags(t *testing.T) { CheckDestroy: testAccCheckVpcEndpointServiceDestroy, Steps: []resource.TestStep{ { - Config: testAccVpcEndpointServiceConfig_allowedPrincipalsAndTags(rName1, rName2), + Config: testAccVpcEndpointServiceConfig_allowedPrincipals(rName1, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckVpcEndpointServiceExists(resourceName, &svcCfg), resource.TestCheckResourceAttr(resourceName, "acceptance_required", "false"), resource.TestCheckResourceAttr(resourceName, "network_load_balancer_arns.#", "1"), resource.TestCheckResourceAttr(resourceName, "allowed_principals.#", "1"), resource.TestCheckResourceAttr(resourceName, "manages_vpc_endpoints", "false"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), - resource.TestCheckResourceAttr(resourceName, "tags.Environment", "test"), - resource.TestCheckResourceAttr(resourceName, "tags.Usage", "original"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.Name", rName1), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint-service/vpce-svc-.+`)), ), }, { @@ -141,14 +141,13 @@ func TestAccAWSVpcEndpointService_AllowedPrincipalsAndTags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccVpcEndpointServiceConfig_allowedPrincipalsAndTagsUpdated(rName1, rName2), + Config: testAccVpcEndpointServiceConfig_allowedPrincipalsUpdated(rName1, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckVpcEndpointServiceExists(resourceName, &svcCfg), resource.TestCheckResourceAttr(resourceName, "acceptance_required", "true"), resource.TestCheckResourceAttr(resourceName, "network_load_balancer_arns.#", "2"), resource.TestCheckResourceAttr(resourceName, "allowed_principals.#", "0"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.Usage", "changed"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.Name", rName1), ), }, @@ -156,21 +155,11 @@ func TestAccAWSVpcEndpointService_AllowedPrincipalsAndTags(t *testing.T) { }) } -func TestAccAWSVpcEndpointService_removed(t *testing.T) { +func TestAccAWSVpcEndpointService_disappears(t *testing.T) { var svcCfg ec2.ServiceConfiguration resourceName := "aws_vpc_endpoint_service.test" - rName1 := fmt.Sprintf("tf-testacc-vpcesvc-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) - rName2 := fmt.Sprintf("tf-testacc-vpcesvc-%s", acctest.RandStringFromCharSet(13, acctest.CharSetAlphaNum)) - - testDestroy := func(*terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - - _, err := conn.DeleteVpcEndpointServiceConfigurations(&ec2.DeleteVpcEndpointServiceConfigurationsInput{ - ServiceIds: []*string{svcCfg.ServiceId}, - }) - - return err - } + rName1 := acctest.RandomWithPrefix("tf-acc-test") + rName2 := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -181,7 +170,7 @@ func TestAccAWSVpcEndpointService_removed(t *testing.T) { Config: testAccVpcEndpointServiceConfig_basic(rName1, rName2), Check: resource.ComposeTestCheckFunc( testAccCheckVpcEndpointServiceExists(resourceName, &svcCfg), - testDestroy, + testAccCheckResourceDisappears(testAccProvider, resourceAwsVpcEndpointService(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -189,6 +178,51 @@ func TestAccAWSVpcEndpointService_removed(t *testing.T) { }) } +func TestAccAWSVpcEndpointService_tags(t *testing.T) { + var svcCfg ec2.ServiceConfiguration + resourceName := "aws_vpc_endpoint_service.test" + rName1 := acctest.RandomWithPrefix("tf-acc-test") + rName2 := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckVpcEndpointServiceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVpcEndpointServiceConfigTags1(rName1, rName2, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVpcEndpointServiceExists(resourceName, &svcCfg), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccVpcEndpointServiceConfigTags2(rName1, rName2, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVpcEndpointServiceExists(resourceName, &svcCfg), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccVpcEndpointServiceConfigTags1(rName1, rName2, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVpcEndpointServiceExists(resourceName, &svcCfg), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + func testAccCheckVpcEndpointServiceDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn @@ -326,7 +360,9 @@ data "aws_caller_identity" "current" {} } func testAccVpcEndpointServiceConfig_basic(rName1, rName2 string) string { - return testAccVpcEndpointServiceConfig_base(rName1, rName2) + fmt.Sprintf(` + return composeConfig( + testAccVpcEndpointServiceConfig_base(rName1, rName2), + ` resource "aws_vpc_endpoint_service" "test" { acceptance_required = false @@ -337,8 +373,10 @@ resource "aws_vpc_endpoint_service" "test" { `) } -func testAccVpcEndpointServiceConfig_allowedPrincipalsAndTags(rName1, rName2 string) string { - return testAccVpcEndpointServiceConfig_base(rName1, rName2) + fmt.Sprintf(` +func testAccVpcEndpointServiceConfig_allowedPrincipals(rName1, rName2 string) string { + return composeConfig( + testAccVpcEndpointServiceConfig_base(rName1, rName2), + fmt.Sprintf(` resource "aws_vpc_endpoint_service" "test" { acceptance_required = false @@ -351,16 +389,16 @@ resource "aws_vpc_endpoint_service" "test" { ] tags = { - Environment = "test" - Usage = "original" - Name = %[1]q + Name = %[1]q } } -`, rName1) +`, rName1)) } -func testAccVpcEndpointServiceConfig_allowedPrincipalsAndTagsUpdated(rName1, rName2 string) string { - return testAccVpcEndpointServiceConfig_base(rName1, rName2) + fmt.Sprintf(` +func testAccVpcEndpointServiceConfig_allowedPrincipalsUpdated(rName1, rName2 string) string { + return composeConfig( + testAccVpcEndpointServiceConfig_base(rName1, rName2), + fmt.Sprintf(` resource "aws_vpc_endpoint_service" "test" { acceptance_required = true @@ -372,9 +410,45 @@ resource "aws_vpc_endpoint_service" "test" { allowed_principals = [] tags = { - Usage = "changed" Name = %[1]q } } -`, rName1) +`, rName1)) +} + +func testAccVpcEndpointServiceConfigTags1(rName1, rName2, tagKey1, tagValue1 string) string { + return composeConfig( + testAccVpcEndpointServiceConfig_base(rName1, rName2), + fmt.Sprintf(` +resource "aws_vpc_endpoint_service" "test" { + acceptance_required = false + + network_load_balancer_arns = [ + "${aws_lb.test1.arn}", + ] + + tags = { + %[1]q = %[2]q + } +} +`, tagKey1, tagValue1)) +} + +func testAccVpcEndpointServiceConfigTags2(rName1, rName2, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return composeConfig( + testAccVpcEndpointServiceConfig_base(rName1, rName2), + fmt.Sprintf(` +resource "aws_vpc_endpoint_service" "test" { + acceptance_required = false + + network_load_balancer_arns = [ + "${aws_lb.test1.arn}", + ] + + tags = { + %[1]q = %[2]q + %[3]q = %[4]q + } +} +`, tagKey1, tagValue1, tagKey2, tagValue2)) } diff --git a/aws/resource_aws_vpc_endpoint_subnet_association.go b/aws/resource_aws_vpc_endpoint_subnet_association.go index 45d952c7236..ddf9bfeb68b 100644 --- a/aws/resource_aws_vpc_endpoint_subnet_association.go +++ b/aws/resource_aws_vpc_endpoint_subnet_association.go @@ -8,9 +8,9 @@ import ( "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-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsVpcEndpointSubnetAssociation() *schema.Resource { diff --git a/aws/resource_aws_vpc_endpoint_subnet_association_test.go b/aws/resource_aws_vpc_endpoint_subnet_association_test.go index 0e94dee4e39..7f705487112 100644 --- a/aws/resource_aws_vpc_endpoint_subnet_association_test.go +++ b/aws/resource_aws_vpc_endpoint_subnet_association_test.go @@ -7,8 +7,8 @@ import ( "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-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSVpcEndpointSubnetAssociation_basic(t *testing.T) { diff --git a/aws/resource_aws_vpc_endpoint_test.go b/aws/resource_aws_vpc_endpoint_test.go index f7e1c9c54ed..a24a5a70008 100644 --- a/aws/resource_aws_vpc_endpoint_test.go +++ b/aws/resource_aws_vpc_endpoint_test.go @@ -3,6 +3,7 @@ package aws import ( "fmt" "log" + "regexp" "strconv" "strings" "testing" @@ -11,10 +12,9 @@ import ( "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -84,7 +84,7 @@ func testSweepEc2VpcEndpoints(region string) error { func TestAccAWSVpcEndpoint_gatewayBasic(t *testing.T) { var endpoint ec2.VpcEndpoint resourceName := "aws_vpc_endpoint.test" - rName := acctest.RandomWithPrefix("tf-testacc-vpce") + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -92,7 +92,7 @@ func TestAccAWSVpcEndpoint_gatewayBasic(t *testing.T) { CheckDestroy: testAccCheckVpcEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccVpcEndpointConfig_gatewayWithoutRouteTableOrPolicyOrTags(rName), + Config: testAccVpcEndpointConfig_gatewayBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVpcEndpointExists(resourceName, &endpoint), testAccCheckVpcEndpointPrefixListAvailable(resourceName), @@ -105,6 +105,7 @@ func TestAccAWSVpcEndpoint_gatewayBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { @@ -116,12 +117,12 @@ func TestAccAWSVpcEndpoint_gatewayBasic(t *testing.T) { }) } -func TestAccAWSVpcEndpoint_gatewayWithRouteTableAndPolicyAndTags(t *testing.T) { +func TestAccAWSVpcEndpoint_gatewayWithRouteTableAndPolicy(t *testing.T) { var endpoint ec2.VpcEndpoint var routeTable ec2.RouteTable resourceName := "aws_vpc_endpoint.test" - resourceNameRt := "aws_route_table.test" - rName := acctest.RandomWithPrefix("tf-testacc-vpce") + routeTableResourceName := "aws_route_table.test" + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -129,10 +130,10 @@ func TestAccAWSVpcEndpoint_gatewayWithRouteTableAndPolicyAndTags(t *testing.T) { CheckDestroy: testAccCheckVpcEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccVpcEndpointConfig_gatewayWithRouteTableAndPolicyAndTags(rName), + Config: testAccVpcEndpointConfig_gatewayWithRouteTableAndPolicy(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVpcEndpointExists(resourceName, &endpoint), - testAccCheckRouteTableExists(resourceNameRt, &routeTable), + testAccCheckRouteTableExists(routeTableResourceName, &routeTable), testAccCheckVpcEndpointPrefixListAvailable(resourceName), resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Gateway"), resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "1"), @@ -141,18 +142,17 @@ func TestAccAWSVpcEndpoint_gatewayWithRouteTableAndPolicyAndTags(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "0"), resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), - resource.TestCheckResourceAttr(resourceName, "tags.Environment", "test"), - resource.TestCheckResourceAttr(resourceName, "tags.Usage", "original"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { - Config: testAccVpcEndpointConfig_gatewayWithRouteTableAndPolicyAndTagsModified(rName), + Config: testAccVpcEndpointConfig_gatewayWithRouteTableAndPolicyModified(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVpcEndpointExists(resourceName, &endpoint), - testAccCheckRouteTableExists(resourceNameRt, &routeTable), + testAccCheckRouteTableExists(routeTableResourceName, &routeTable), testAccCheckVpcEndpointPrefixListAvailable(resourceName), resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Gateway"), resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), @@ -161,10 +161,10 @@ func TestAccAWSVpcEndpoint_gatewayWithRouteTableAndPolicyAndTags(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "0"), resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), - resource.TestCheckResourceAttr(resourceName, "tags.Usage", "changed"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { @@ -210,7 +210,7 @@ func TestAccAWSVpcEndpoint_gatewayPolicy(t *testing.T) { } ` resourceName := "aws_vpc_endpoint.test" - rName := acctest.RandomWithPrefix("tf-testacc-vpce") + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -241,7 +241,7 @@ func TestAccAWSVpcEndpoint_gatewayPolicy(t *testing.T) { func TestAccAWSVpcEndpoint_interfaceBasic(t *testing.T) { var endpoint ec2.VpcEndpoint resourceName := "aws_vpc_endpoint.test" - rName := acctest.RandomWithPrefix("tf-testacc-vpce") + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -249,7 +249,7 @@ func TestAccAWSVpcEndpoint_interfaceBasic(t *testing.T) { CheckDestroy: testAccCheckVpcEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccVpcEndpointConfig_interfaceWithoutSubnet(rName), + Config: testAccVpcEndpointConfig_interfaceBasic(rName), Check: resource.ComposeTestCheckFunc( testAccCheckVpcEndpointExists(resourceName, &endpoint), resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), @@ -263,6 +263,7 @@ func TestAccAWSVpcEndpoint_interfaceBasic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { @@ -277,7 +278,7 @@ func TestAccAWSVpcEndpoint_interfaceBasic(t *testing.T) { func TestAccAWSVpcEndpoint_interfaceWithSubnetAndSecurityGroup(t *testing.T) { var endpoint ec2.VpcEndpoint resourceName := "aws_vpc_endpoint.test" - rName := acctest.RandomWithPrefix("tf-testacc-vpce") + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -300,6 +301,7 @@ func TestAccAWSVpcEndpoint_interfaceWithSubnetAndSecurityGroup(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { @@ -315,8 +317,10 @@ func TestAccAWSVpcEndpoint_interfaceWithSubnetAndSecurityGroup(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "true"), resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), - resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { @@ -328,10 +332,10 @@ func TestAccAWSVpcEndpoint_interfaceWithSubnetAndSecurityGroup(t *testing.T) { }) } -func TestAccAWSVpcEndpoint_interfaceNonAWSService(t *testing.T) { +func TestAccAWSVpcEndpoint_interfaceNonAWSServiceAcceptOnCreate(t *testing.T) { var endpoint ec2.VpcEndpoint resourceName := "aws_vpc_endpoint.test" - rName := acctest.RandomWithPrefix("tf-acc-vpce") + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -339,7 +343,7 @@ func TestAccAWSVpcEndpoint_interfaceNonAWSService(t *testing.T) { CheckDestroy: testAccCheckVpcEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccVpcEndpointConfig_interfaceNonAWSService(rName), + Config: testAccVpcEndpointConfig_interfaceNonAWSService(rName, true), Check: resource.ComposeTestCheckFunc( testAccCheckVpcEndpointExists(resourceName, &endpoint), resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), @@ -355,6 +359,7 @@ func TestAccAWSVpcEndpoint_interfaceNonAWSService(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), }, { @@ -367,10 +372,10 @@ func TestAccAWSVpcEndpoint_interfaceNonAWSService(t *testing.T) { }) } -func TestAccAWSVpcEndpoint_removed(t *testing.T) { +func TestAccAWSVpcEndpoint_interfaceNonAWSServiceAcceptOnUpdate(t *testing.T) { var endpoint ec2.VpcEndpoint resourceName := "aws_vpc_endpoint.test" - rName := acctest.RandomWithPrefix("tf-testacc-vpce") + rName := acctest.RandomWithPrefix("tf-acc-test") resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -378,28 +383,120 @@ func TestAccAWSVpcEndpoint_removed(t *testing.T) { CheckDestroy: testAccCheckVpcEndpointDestroy, Steps: []resource.TestStep{ { - Config: testAccVpcEndpointConfig_gatewayWithoutRouteTableOrPolicyOrTags(rName), + Config: testAccVpcEndpointConfig_interfaceNonAWSService(rName, false), Check: resource.ComposeTestCheckFunc( testAccCheckVpcEndpointExists(resourceName, &endpoint), - testAccCheckVpcEndpointDisappears(&endpoint), + resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Interface"), + resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), + resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "0"), + resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "0"), + resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), + resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), + resource.TestCheckResourceAttr(resourceName, "state", "pendingAcceptance"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), + testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), ), - ExpectNonEmptyPlan: true, + }, + { + Config: testAccVpcEndpointConfig_interfaceNonAWSService(rName, true), + Check: resource.ComposeTestCheckFunc( + testAccCheckVpcEndpointExists(resourceName, &endpoint), + resource.TestCheckNoResourceAttr(resourceName, "prefix_list_id"), + resource.TestCheckResourceAttr(resourceName, "cidr_blocks.#", "0"), + resource.TestCheckResourceAttr(resourceName, "vpc_endpoint_type", "Interface"), + resource.TestCheckResourceAttr(resourceName, "route_table_ids.#", "0"), + resource.TestCheckResourceAttr(resourceName, "subnet_ids.#", "0"), + resource.TestCheckResourceAttr(resourceName, "network_interface_ids.#", "0"), + resource.TestCheckResourceAttr(resourceName, "security_group_ids.#", "1"), + resource.TestCheckResourceAttr(resourceName, "private_dns_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "requester_managed", "false"), + resource.TestCheckResourceAttr(resourceName, "state", "available"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), + testAccCheckResourceAttrAccountID(resourceName, "owner_id"), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpc-endpoint/vpce-.+`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"auto_accept"}, }, }, }) } -func testAccCheckVpcEndpointDisappears(endpoint *ec2.VpcEndpoint) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - input := &ec2.DeleteVpcEndpointsInput{ - VpcEndpointIds: []*string{endpoint.VpcEndpointId}, - } +func TestAccAWSVpcEndpoint_disappears(t *testing.T) { + var endpoint ec2.VpcEndpoint + resourceName := "aws_vpc_endpoint.test" + rName := acctest.RandomWithPrefix("tf-acc-test") + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckVpcEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVpcEndpointConfig_gatewayBasic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckVpcEndpointExists(resourceName, &endpoint), + testAccCheckResourceDisappears(testAccProvider, resourceAwsVpcEndpoint(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} - _, err := conn.DeleteVpcEndpoints(input) +func TestAccAWSVpcEndpoint_tags(t *testing.T) { + var endpoint ec2.VpcEndpoint + resourceName := "aws_vpc_endpoint.test" + rName := acctest.RandomWithPrefix("tf-acc-test") - return err - } + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccCheckVpcEndpointDestroy, + Steps: []resource.TestStep{ + { + Config: testAccVpcEndpointConfigTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVpcEndpointExists(resourceName, &endpoint), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccVpcEndpointConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVpcEndpointExists(resourceName, &endpoint), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccVpcEndpointConfigTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVpcEndpointExists(resourceName, &endpoint), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) } func testAccCheckVpcEndpointDestroy(s *terraform.State) error { @@ -492,7 +589,7 @@ func testAccCheckVpcEndpointPrefixListAvailable(n string) resource.TestCheckFunc } } -func testAccVpcEndpointConfig_gatewayWithoutRouteTableOrPolicyOrTags(rName string) string { +func testAccVpcEndpointConfig_gatewayBasic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -511,7 +608,7 @@ resource "aws_vpc_endpoint" "test" { `, rName) } -func testAccVpcEndpointConfig_gatewayWithRouteTableAndPolicyAndTags(rName string) string { +func testAccVpcEndpointConfig_gatewayWithRouteTableAndPolicy(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -554,9 +651,7 @@ resource "aws_vpc_endpoint" "test" { POLICY tags = { - Environment = "test" - Usage = "original" - Name = %[1]q + Name = %[1]q } } @@ -575,7 +670,7 @@ resource "aws_route_table_association" "test" { `, rName) } -func testAccVpcEndpointConfig_gatewayWithRouteTableAndPolicyAndTagsModified(rName string) string { +func testAccVpcEndpointConfig_gatewayWithRouteTableAndPolicyModified(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -605,7 +700,6 @@ resource "aws_vpc_endpoint" "test" { policy = "" tags = { - Usage = "changed" Name = %[1]q } } @@ -638,7 +732,7 @@ resource "aws_route_table_association" "test" { `, rName) } -func testAccVpcEndpointConfig_interfaceWithoutSubnet(rName string) string { +func testAccVpcEndpointConfig_interfaceBasic(rName string) string { return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" @@ -685,6 +779,10 @@ resource "aws_vpc_endpoint" "test" { policy = < 64) { - errors = append(errors, fmt.Errorf("%q must be between 8 and 64 characters in length", k)) - } - - if strings.HasPrefix(value, "0") { - errors = append(errors, fmt.Errorf("%q cannot start with zero character", k)) - } - - if !regexp.MustCompile(`^[0-9a-zA-Z_.]+$`).MatchString(value) { - errors = append(errors, fmt.Errorf("%q can only contain alphanumeric, period and underscore characters", k)) - } - - return +func validateVpnConnectionTunnelPreSharedKey() schema.SchemaValidateFunc { + return validation.All( + validation.StringLenBetween(8, 64), + validation.StringDoesNotMatch(regexp.MustCompile(`^0`), "cannot start with zero character"), + validation.StringMatch(regexp.MustCompile(`^[0-9a-zA-Z_.]+$`), "can only contain alphanumeric, period and underscore characters"), + ) } // https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_VpnTunnelOptionsSpecification.html -func validateVpnConnectionTunnelInsideCIDR(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 parsing: %s", k, err)) - return - } - - if !strings.HasSuffix(ipnet.String(), "/30") { - errors = append(errors, fmt.Errorf("%q must be /30 CIDR", k)) - } - - if !strings.HasPrefix(ipnet.String(), "169.254.") { - errors = append(errors, fmt.Errorf("%q must be within 169.254.0.0/16", k)) - } else if ipnet.String() == "169.254.0.0/30" { - errors = append(errors, fmt.Errorf("%q cannot be 169.254.0.0/30", k)) - } else if ipnet.String() == "169.254.1.0/30" { - errors = append(errors, fmt.Errorf("%q cannot be 169.254.1.0/30", k)) - } else if ipnet.String() == "169.254.2.0/30" { - errors = append(errors, fmt.Errorf("%q cannot be 169.254.2.0/30", k)) - } else if ipnet.String() == "169.254.3.0/30" { - errors = append(errors, fmt.Errorf("%q cannot be 169.254.3.0/30", k)) - } else if ipnet.String() == "169.254.4.0/30" { - errors = append(errors, fmt.Errorf("%q cannot be 169.254.4.0/30", k)) - } else if ipnet.String() == "169.254.5.0/30" { - errors = append(errors, fmt.Errorf("%q cannot be 169.254.5.0/30", k)) - } else if ipnet.String() == "169.254.169.252/30" { - errors = append(errors, fmt.Errorf("%q cannot be 169.254.169.252/30", k)) - } - - return +func validateVpnConnectionTunnelInsideCIDR() schema.SchemaValidateFunc { + disallowedCidrs := []string{ + "169.254.0.0/30", + "169.254.1.0/30", + "169.254.2.0/30", + "169.254.3.0/30", + "169.254.4.0/30", + "169.254.5.0/30", + "169.254.169.252/30", + } + + return validation.All( + validation.IsCIDRNetwork(30, 30), + validation.StringMatch(regexp.MustCompile(`^169\.254\.`), "must be within 169.254.0.0/16"), + validation.StringNotInSlice(disallowedCidrs, false), + ) } diff --git a/aws/resource_aws_vpn_connection_route.go b/aws/resource_aws_vpn_connection_route.go index b8fac5de86a..65e77edfb4e 100644 --- a/aws/resource_aws_vpn_connection_route.go +++ b/aws/resource_aws_vpn_connection_route.go @@ -10,8 +10,8 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsVpnConnectionRoute() *schema.Resource { diff --git a/aws/resource_aws_vpn_connection_route_test.go b/aws/resource_aws_vpn_connection_route_test.go index 862c675d572..3b07ee1620f 100644 --- a/aws/resource_aws_vpn_connection_route_test.go +++ b/aws/resource_aws_vpn_connection_route_test.go @@ -8,9 +8,9 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSVpnConnectionRoute_basic(t *testing.T) { @@ -23,23 +23,13 @@ func TestAccAWSVpnConnectionRoute_basic(t *testing.T) { { Config: testAccAwsVpnConnectionRouteConfig(rBgpAsn), Check: resource.ComposeTestCheckFunc( - testAccAwsVpnConnectionRoute( - "aws_vpn_gateway.vpn_gateway", - "aws_customer_gateway.customer_gateway", - "aws_vpn_connection.vpn_connection", - "aws_vpn_connection_route.foo", - ), + testAccAwsVpnConnectionRoute("aws_vpn_connection_route.foo"), ), }, { Config: testAccAwsVpnConnectionRouteConfigUpdate(rBgpAsn), Check: resource.ComposeTestCheckFunc( - testAccAwsVpnConnectionRoute( - "aws_vpn_gateway.vpn_gateway", - "aws_customer_gateway.customer_gateway", - "aws_vpn_connection.vpn_connection", - "aws_vpn_connection_route.foo", - ), + testAccAwsVpnConnectionRoute("aws_vpn_connection_route.foo"), ), }, }, @@ -100,11 +90,7 @@ func testAccAwsVpnConnectionRouteDestroy(s *terraform.State) error { return fmt.Errorf("Fall through error, Check Destroy criteria not met") } -func testAccAwsVpnConnectionRoute( - vpnGatewayResource string, - customerGatewayResource string, - vpnConnectionResource string, - vpnConnectionRouteResource string) resource.TestCheckFunc { +func testAccAwsVpnConnectionRoute(vpnConnectionRouteResource string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[vpnConnectionRouteResource] if !ok { diff --git a/aws/resource_aws_vpn_connection_test.go b/aws/resource_aws_vpn_connection_test.go index 387b9923fe7..a192a7f070a 100644 --- a/aws/resource_aws_vpn_connection_test.go +++ b/aws/resource_aws_vpn_connection_test.go @@ -5,15 +5,13 @@ import ( "log" "regexp" "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-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -90,6 +88,8 @@ func TestAccAWSVpnConnection_basic(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccAwsVpnConnectionExists(resourceName, &vpn), resource.TestCheckResourceAttr(resourceName, "transit_gateway_attachment_id", ""), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpn-connection/vpn-.+`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { @@ -139,6 +139,7 @@ func TestAccAWSVpnConnection_TransitGatewayID(t *testing.T) { } func TestAccAWSVpnConnection_tunnelOptions(t *testing.T) { + badCidrRangeErr := regexp.MustCompile(`expected \w+ to not be any of \[[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/30\s?]+\]`) rBgpAsn := acctest.RandIntRange(64512, 65534) resourceName := "aws_vpn_connection.test" var vpn ec2.VpnConnection @@ -153,11 +154,11 @@ func TestAccAWSVpnConnection_tunnelOptions(t *testing.T) { // Checking CIDR blocks { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "12345678", "not-a-cidr"), - ExpectError: regexp.MustCompile(`must contain a valid CIDR`), + ExpectError: regexp.MustCompile(`invalid CIDR address: not-a-cidr`), }, { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "12345678", "169.254.254.0/31"), - ExpectError: regexp.MustCompile(`must be /30 CIDR`), + ExpectError: regexp.MustCompile(`expected "\w+" to contain a network Value with between 30 and 30 significant bits`), }, { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "12345678", "172.16.0.0/30"), @@ -165,41 +166,41 @@ func TestAccAWSVpnConnection_tunnelOptions(t *testing.T) { }, { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "12345678", "169.254.0.0/30"), - ExpectError: regexp.MustCompile(`cannot be 169.254.0.0/30`), + ExpectError: badCidrRangeErr, }, { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "12345678", "169.254.1.0/30"), - ExpectError: regexp.MustCompile(`cannot be 169.254.1.0/30`), + ExpectError: badCidrRangeErr, }, { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "12345678", "169.254.2.0/30"), - ExpectError: regexp.MustCompile(`cannot be 169.254.2.0/30`), + ExpectError: badCidrRangeErr, }, { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "12345678", "169.254.3.0/30"), - ExpectError: regexp.MustCompile(`cannot be 169.254.3.0/30`), + ExpectError: badCidrRangeErr, }, { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "12345678", "169.254.4.0/30"), - ExpectError: regexp.MustCompile(`cannot be 169.254.4.0/30`), + ExpectError: badCidrRangeErr, }, { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "12345678", "169.254.5.0/30"), - ExpectError: regexp.MustCompile(`cannot be 169.254.5.0/30`), + ExpectError: badCidrRangeErr, }, { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "12345678", "169.254.169.252/30"), - ExpectError: regexp.MustCompile(`cannot be 169.254.169.252/30`), + ExpectError: badCidrRangeErr, }, // Checking PreShared Key { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "1234567", "169.254.254.0/30"), - ExpectError: regexp.MustCompile(`must be between 8 and 64 characters in length`), + ExpectError: regexp.MustCompile(`expected length of \w+ to be in the range \(8 - 64\)`), }, { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, acctest.RandStringFromCharSet(65, acctest.CharSetAlpha), "169.254.254.0/30"), - ExpectError: regexp.MustCompile(`must be between 8 and 64 characters in length`), + ExpectError: regexp.MustCompile(`expected length of \w+ to be in the range \(8 - 64\)`), }, { Config: testAccAwsVpnConnectionConfigSingleTunnelOptions(rBgpAsn, "01234567", "169.254.254.0/30"), @@ -257,6 +258,51 @@ func TestAccAWSVpnConnection_withoutStaticRoutes(t *testing.T) { }) } +func TestAccAWSVpnConnection_tags(t *testing.T) { + rBgpAsn := acctest.RandIntRange(64512, 65534) + resourceName := "aws_vpn_connection.test" + var vpn ec2.VpnConnection + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: resourceName, + Providers: testAccProviders, + CheckDestroy: testAccAwsVpnConnectionDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsVpnConnectionConfigTags1(rBgpAsn, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccAwsVpnConnectionExists(resourceName, &vpn), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAwsVpnConnectionConfigTags2(rBgpAsn, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccAwsVpnConnectionExists(resourceName, &vpn), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccAwsVpnConnectionConfigTags1(rBgpAsn, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccAwsVpnConnectionExists(resourceName, &vpn), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) +} + func TestAccAWSVpnConnection_disappears(t *testing.T) { rBgpAsn := acctest.RandIntRange(64512, 65534) resourceName := "aws_vpn_connection.test" @@ -271,7 +317,7 @@ func TestAccAWSVpnConnection_disappears(t *testing.T) { Config: testAccAwsVpnConnectionConfig(rBgpAsn), Check: resource.ComposeTestCheckFunc( testAccAwsVpnConnectionExists(resourceName, &vpn), - testAccAWSVpnConnectionDisappears(&vpn), + testAccCheckResourceDisappears(testAccProvider, resourceAwsVpnConnection(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -279,44 +325,6 @@ func TestAccAWSVpnConnection_disappears(t *testing.T) { }) } -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 { - 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 { @@ -575,6 +583,69 @@ resource "aws_vpn_connection" "test" { `, rBgpAsn, tunnelCidr, psk, tunnelCidr2, psk2) } +func testAccAwsVpnConnectionConfigTags1(rBgpAsn int, tagKey1, tagValue1 string) string { + return fmt.Sprintf(` +resource "aws_vpn_gateway" "vpn_gateway" { + tags = { + Name = "vpn_gateway" + } +} + +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" "test" { + 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 + + tags = { + %[2]q = %[3]q + } +} +`, rBgpAsn, tagKey1, tagValue1) +} + +func testAccAwsVpnConnectionConfigTags2(rBgpAsn int, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` +resource "aws_vpn_gateway" "vpn_gateway" { + tags = { + Name = "vpn_gateway" + } +} + +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" "test" { + 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 + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } +} +`, rBgpAsn, tagKey1, tagValue1, tagKey2, tagValue2) +} + // Test our VPN tunnel config XML parsing const testAccAwsVpnTunnelInfoXML = ` diff --git a/aws/resource_aws_vpn_gateway.go b/aws/resource_aws_vpn_gateway.go index 9fe22725bae..c8318026dad 100644 --- a/aws/resource_aws_vpn_gateway.go +++ b/aws/resource_aws_vpn_gateway.go @@ -7,10 +7,10 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -25,6 +25,10 @@ func resourceAwsVpnGateway() *schema.Resource { }, Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, "availability_zone": { Type: schema.TypeString, Optional: true, @@ -55,7 +59,7 @@ func resourceAwsVpnGatewayCreate(d *schema.ResourceData, meta interface{}) error createOpts := &ec2.CreateVpnGatewayInput{ AvailabilityZone: aws.String(d.Get("availability_zone").(string)), - Type: aws.String("ipsec.1"), + Type: aws.String(ec2.GatewayTypeIpsec1), } if asn, ok := d.GetOk("amazon_side_asn"); ok { i, err := strconv.ParseInt(asn.(string), 10, 64) @@ -97,7 +101,8 @@ func resourceAwsVpnGatewayRead(d *schema.ResourceData, meta interface{}) error { VpnGatewayIds: []*string{aws.String(d.Id())}, }) if err != nil { - if ec2err, ok := err.(awserr.Error); ok && ec2err.Code() == "InvalidVpnGatewayID.NotFound" { + if isAWSErr(err, "InvalidVpnGatewayID.NotFound", "") { + log.Printf("[WARN] VPC Gateway (%s) not found, removing from state", d.Id()) d.SetId("") return nil } else { @@ -107,8 +112,8 @@ func resourceAwsVpnGatewayRead(d *schema.ResourceData, meta interface{}) error { } vpnGateway := resp.VpnGateways[0] - if vpnGateway == nil || *vpnGateway.State == "deleted" { - // Seems we have lost our VPN gateway + if vpnGateway == nil || aws.StringValue(vpnGateway.State) == ec2.VpnStateDeleted { + log.Printf("[WARN] VPC Gateway (%s) not found, removing from state", d.Id()) d.SetId("") return nil } @@ -121,7 +126,7 @@ func resourceAwsVpnGatewayRead(d *schema.ResourceData, meta interface{}) error { d.Set("vpc_id", vpnAttachment.VpcId) } - if vpnGateway.AvailabilityZone != nil && *vpnGateway.AvailabilityZone != "" { + if vpnGateway.AvailabilityZone != nil && aws.StringValue(vpnGateway.AvailabilityZone) != "" { d.Set("availability_zone", vpnGateway.AvailabilityZone) } d.Set("amazon_side_asn", strconv.FormatInt(aws.Int64Value(vpnGateway.AmazonSideAsn), 10)) @@ -130,6 +135,16 @@ func resourceAwsVpnGatewayRead(d *schema.ResourceData, meta interface{}) error { return fmt.Errorf("error setting tags: %s", err) } + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Service: "ec2", + Region: meta.(*AWSClient).region, + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("vpn-gateway/%s", d.Id()), + }.String() + + d.Set("arn", arn) + return nil } @@ -205,9 +220,7 @@ func resourceAwsVpnGatewayAttach(d *schema.ResourceData, meta interface{}) error vpcId := d.Get("vpc_id").(string) if vpcId == "" { - log.Printf( - "[DEBUG] Not attaching VPN Gateway '%s' as no VPC ID is set", - d.Id()) + log.Printf("[DEBUG] Not attaching VPN Gateway '%s' as no VPC ID is set", d.Id()) return nil } @@ -242,15 +255,13 @@ func resourceAwsVpnGatewayAttach(d *schema.ResourceData, meta interface{}) error // Wait for it to be fully attached before continuing log.Printf("[DEBUG] Waiting for VPN gateway (%s) to attach", d.Id()) stateConf := &resource.StateChangeConf{ - Pending: []string{"detached", "attaching"}, - Target: []string{"attached"}, + Pending: []string{ec2.AttachmentStatusDetached, ec2.AttachmentStatusAttaching}, + Target: []string{ec2.AttachmentStatusAttached}, Refresh: vpnGatewayAttachmentStateRefresh(conn, vpcId, d.Id()), Timeout: 15 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf( - "Error waiting for VPN gateway (%s) to attach: %s", - d.Id(), err) + return fmt.Errorf("Error waiting for VPN gateway (%s) to attach: %s", d.Id(), err) } return nil @@ -281,15 +292,13 @@ func resourceAwsVpnGatewayDetach(d *schema.ResourceData, meta interface{}) error VpcId: aws.String(vpcId), }) if err != nil { - ec2err, ok := err.(awserr.Error) - if ok { - if ec2err.Code() == "InvalidVpnGatewayID.NotFound" { - err = nil - wait = false - } else if ec2err.Code() == "InvalidVpnGatewayAttachment.NotFound" { - err = nil - wait = false - } + if isAWSErr(err, "InvalidVpnGatewayID.NotFound", "") { + err = nil + wait = false + } + if isAWSErr(err, "InvalidVpnGatewayAttachment.NotFound", "") { + err = nil + wait = false } if err != nil { @@ -304,15 +313,13 @@ func resourceAwsVpnGatewayDetach(d *schema.ResourceData, meta interface{}) error // Wait for it to be fully detached before continuing log.Printf("[DEBUG] Waiting for VPN gateway (%s) to detach", d.Id()) stateConf := &resource.StateChangeConf{ - Pending: []string{"attached", "detaching", "available"}, - Target: []string{"detached"}, + Pending: []string{ec2.AttachmentStatusAttached, ec2.AttachmentStatusDetaching, "available"}, + Target: []string{ec2.AttachmentStatusDetached}, Refresh: vpnGatewayAttachmentStateRefresh(conn, vpcId, d.Id()), Timeout: 10 * time.Minute, } if _, err := stateConf.WaitForState(); err != nil { - return fmt.Errorf( - "Error waiting for vpn gateway (%s) to detach: %s", - d.Id(), err) + return fmt.Errorf("Error waiting for vpn gateway (%s) to detach: %s", d.Id(), err) } return nil diff --git a/aws/resource_aws_vpn_gateway_attachment.go b/aws/resource_aws_vpn_gateway_attachment.go index e4906ade09e..7d7fae06cd9 100644 --- a/aws/resource_aws_vpn_gateway_attachment.go +++ b/aws/resource_aws_vpn_gateway_attachment.go @@ -8,9 +8,9 @@ import ( "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-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsVpnGatewayAttachment() *schema.Resource { diff --git a/aws/resource_aws_vpn_gateway_attachment_test.go b/aws/resource_aws_vpn_gateway_attachment_test.go index c427cc018df..bdf208d57c8 100644 --- a/aws/resource_aws_vpn_gateway_attachment_test.go +++ b/aws/resource_aws_vpn_gateway_attachment_test.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSVpnGatewayAttachment_basic(t *testing.T) { diff --git a/aws/resource_aws_vpn_gateway_route_propagation.go b/aws/resource_aws_vpn_gateway_route_propagation.go index 4ba1b4cd079..b1cc68b6fec 100644 --- a/aws/resource_aws_vpn_gateway_route_propagation.go +++ b/aws/resource_aws_vpn_gateway_route_propagation.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsVpnGatewayRoutePropagation() *schema.Resource { diff --git a/aws/resource_aws_vpn_gateway_route_propagation_test.go b/aws/resource_aws_vpn_gateway_route_propagation_test.go index ad8fde53ade..478003a0da8 100644 --- a/aws/resource_aws_vpn_gateway_route_propagation_test.go +++ b/aws/resource_aws_vpn_gateway_route_propagation_test.go @@ -6,8 +6,8 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSVPNGatewayRoutePropagation_basic(t *testing.T) { diff --git a/aws/resource_aws_vpn_gateway_test.go b/aws/resource_aws_vpn_gateway_test.go index 9d0b197e50e..8f11e1e7899 100644 --- a/aws/resource_aws_vpn_gateway_test.go +++ b/aws/resource_aws_vpn_gateway_test.go @@ -3,14 +3,15 @@ package aws import ( "fmt" "log" + "regexp" "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-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // add sweeper to delete known test VPN Gateways @@ -73,8 +74,8 @@ func testSweepVPNGateways(region string) error { } stateConf := &resource.StateChangeConf{ - Pending: []string{"attached", "detaching"}, - Target: []string{"detached"}, + Pending: []string{ec2.AttachmentStatusAttached, ec2.AttachmentStatusDetaching}, + Target: []string{ec2.AttachmentStatusDetached}, Refresh: vpnGatewayAttachmentStateRefresh(conn, aws.StringValue(vpcAttachment.VpcId), aws.StringValue(vpng.VpnGatewayId)), Timeout: 10 * time.Minute, } @@ -134,8 +135,9 @@ func TestAccAWSVpnGateway_basic(t *testing.T) { { Config: testAccVpnGatewayConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckVpnGatewayExists( - resourceName, &v), + testAccCheckVpnGatewayExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "ec2", regexp.MustCompile(`vpn-gateway/vgw-.+`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, { @@ -146,8 +148,7 @@ func TestAccAWSVpnGateway_basic(t *testing.T) { { Config: testAccVpnGatewayConfigChangeVPC, Check: resource.ComposeTestCheckFunc( - testAccCheckVpnGatewayExists( - resourceName, &v2), + testAccCheckVpnGatewayExists(resourceName, &v2), testNotEqual, ), }, @@ -168,8 +169,7 @@ func TestAccAWSVpnGateway_withAvailabilityZoneSetToState(t *testing.T) { Config: testAccVpnGatewayConfigWithAZ, Check: resource.ComposeTestCheckFunc( testAccCheckVpnGatewayExists(resourceName, &v), - resource.TestCheckResourceAttr( - resourceName, "availability_zone", "us-west-2a"), + resource.TestCheckResourceAttr(resourceName, "availability_zone", "us-west-2a"), ), }, { @@ -209,6 +209,7 @@ func TestAccAWSVpnGateway_withAmazonSideAsnSetToState(t *testing.T) { func TestAccAWSVpnGateway_disappears(t *testing.T) { var v ec2.VpnGateway + resourceName := "aws_vpn_gateway.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, @@ -218,8 +219,8 @@ func TestAccAWSVpnGateway_disappears(t *testing.T) { { Config: testAccVpnGatewayConfig, Check: resource.ComposeTestCheckFunc( - testAccCheckVpnGatewayExists("aws_vpn_gateway.test", &v), - testAccAWSVpnGatewayDisappears(&v), + testAccCheckVpnGatewayExists(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsVpnGateway(), resourceName), ), ExpectNonEmptyPlan: true, }, @@ -366,11 +367,11 @@ func TestAccAWSVpnGateway_tags(t *testing.T) { CheckDestroy: testAccCheckVpnGatewayDestroy, Steps: []resource.TestStep{ { - Config: testAccCheckVpnGatewayConfigTags, + Config: testAccCheckVpnGatewayConfigTags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckVpnGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", "terraform-testacc-vpn-gateway-tags"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, { @@ -379,61 +380,26 @@ func TestAccAWSVpnGateway_tags(t *testing.T) { ImportStateVerify: true, }, { - Config: testAccCheckVpnGatewayConfigTagsUpdate, + Config: testAccCheckVpnGatewayConfigTags2("key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckVpnGatewayExists(resourceName, &v), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccCheckVpnGatewayConfigTags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckVpnGatewayExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), - resource.TestCheckResourceAttr(resourceName, "tags.Name", "terraform-testacc-vpn-gateway-tags-updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, }, }) } -func testAccAWSVpnGatewayDisappears(gateway *ec2.VpnGateway) resource.TestCheckFunc { - return func(s *terraform.State) error { - conn := testAccProvider.Meta().(*AWSClient).ec2conn - - _, err := conn.DetachVpnGateway(&ec2.DetachVpnGatewayInput{ - VpnGatewayId: gateway.VpnGatewayId, - VpcId: gateway.VpcAttachments[0].VpcId, - }) - if err != nil { - return err - } - - opts := &ec2.DeleteVpnGatewayInput{ - VpnGatewayId: gateway.VpnGatewayId, - } - if _, err := conn.DeleteVpnGateway(opts); err != nil { - return err - } - return resource.Retry(40*time.Minute, func() *resource.RetryError { - opts := &ec2.DescribeVpnGatewaysInput{ - VpnGatewayIds: []*string{gateway.VpnGatewayId}, - } - resp, err := conn.DescribeVpnGateways(opts) - if err != nil { - cgw, ok := err.(awserr.Error) - if ok && cgw.Code() == "InvalidVpnGatewayID.NotFound" { - return nil - } - if ok && cgw.Code() == "IncorrectState" { - return resource.RetryableError(fmt.Errorf( - "Waiting for VPN Gateway to be in the correct state: %v", gateway.VpnGatewayId)) - } - return resource.NonRetryableError( - fmt.Errorf("Error retrieving VPN Gateway: %s", err)) - } - if *resp.VpnGateways[0].State == "deleted" { - return nil - } - return resource.RetryableError(fmt.Errorf( - "Waiting for VPN Gateway: %v", gateway.VpnGatewayId)) - }) - } -} - func testAccCheckVpnGatewayDestroy(s *terraform.State) error { ec2conn := testAccProvider.Meta().(*AWSClient).ec2conn @@ -525,9 +491,6 @@ resource "aws_vpc" "test" { resource "aws_vpn_gateway" "test" { vpc_id = "${aws_vpc.test.id}" - tags = { - Name = "terraform-testacc-vpn-gateway-basic" - } } ` @@ -547,7 +510,8 @@ resource "aws_vpn_gateway" "test" { } ` -const testAccCheckVpnGatewayConfigTags = ` +func testAccCheckVpnGatewayConfigTags1(tagKey1, tagValue1 string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { @@ -557,13 +521,16 @@ resource "aws_vpc" "test" { resource "aws_vpn_gateway" "test" { vpc_id = "${aws_vpc.test.id}" + tags = { - Name = "terraform-testacc-vpn-gateway-tags" + %[1]q = %[2]q } } -` +`, tagKey1, tagValue1) +} -const testAccCheckVpnGatewayConfigTagsUpdate = ` +func testAccCheckVpnGatewayConfigTags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return fmt.Sprintf(` resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { @@ -573,11 +540,14 @@ resource "aws_vpc" "test" { resource "aws_vpn_gateway" "test" { vpc_id = "${aws_vpc.test.id}" + tags = { - Name = "terraform-testacc-vpn-gateway-tags-updated" + %[1]q = %[2]q + %[3]q = %[4]q } } -` +`, tagKey1, tagValue1, tagKey2, tagValue2) +} const testAccCheckVpnGatewayConfigReattach = ` resource "aws_vpc" "test" { @@ -640,6 +610,15 @@ resource "aws_vpn_gateway" "test2" { ` const testAccVpnGatewayConfigWithAZ = ` +data "aws_availability_zones" "azs" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + resource "aws_vpc" "test" { cidr_block = "10.1.0.0/16" tags = { @@ -648,8 +627,9 @@ resource "aws_vpc" "test" { } resource "aws_vpn_gateway" "test" { - vpc_id = "${aws_vpc.test.id}" - availability_zone = "us-west-2a" + vpc_id = "${aws_vpc.test.id}" + availability_zone = "${data.aws_availability_zones.azs.names[0]}" + tags = { Name = "terraform-testacc-vpn-gateway-with-az" } diff --git a/aws/resource_aws_waf_byte_match_set.go b/aws/resource_aws_waf_byte_match_set.go index 075438f45af..4d06a2b2fc7 100644 --- a/aws/resource_aws_waf_byte_match_set.go +++ b/aws/resource_aws_waf_byte_match_set.go @@ -2,12 +2,12 @@ package aws import ( "fmt" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "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/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafByteMatchSet() *schema.Resource { @@ -32,7 +32,7 @@ func resourceAwsWafByteMatchSet() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "field_to_match": { - Type: schema.TypeSet, + Type: schema.TypeList, Required: true, MaxItems: 1, Elem: &schema.Resource{ @@ -44,6 +44,15 @@ func resourceAwsWafByteMatchSet() *schema.Resource { "type": { Type: schema.TypeString, Required: true, + ValidateFunc: validation.StringInSlice([]string{ + waf.MatchFieldTypeUri, + waf.MatchFieldTypeQueryString, + waf.MatchFieldTypeHeader, + waf.MatchFieldTypeMethod, + waf.MatchFieldTypeBody, + waf.MatchFieldTypeSingleQueryArg, + waf.MatchFieldTypeAllQueryArgs, + }, false), }, }, }, @@ -85,7 +94,7 @@ func resourceAwsWafByteMatchSetCreate(d *schema.ResourceData, meta interface{}) } resp := out.(*waf.CreateByteMatchSetOutput) - d.SetId(*resp.ByteMatchSet.ByteMatchSetId) + d.SetId(aws.StringValue(resp.ByteMatchSet.ByteMatchSetId)) return resourceAwsWafByteMatchSetUpdate(d, meta) } @@ -99,7 +108,7 @@ func resourceAwsWafByteMatchSetRead(d *schema.ResourceData, meta interface{}) er resp, err := conn.GetByteMatchSet(params) if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "WAFNonexistentItemException" { + if isAWSErr(err, waf.ErrCodeNonexistentItemException, "") { log.Printf("[WARN] WAF IPSet (%s) not found, removing from state", d.Id()) d.SetId("") return nil @@ -185,9 +194,9 @@ func flattenWafByteMatchTuples(bmt []*waf.ByteMatchTuple) []interface{} { if t.FieldToMatch != nil { m["field_to_match"] = flattenFieldToMatch(t.FieldToMatch) } - m["positional_constraint"] = *t.PositionalConstraint + m["positional_constraint"] = aws.StringValue(t.PositionalConstraint) m["target_string"] = string(t.TargetString) - m["text_transformation"] = *t.TextTransformation + m["text_transformation"] = aws.StringValue(t.TextTransformation) out[i] = m } @@ -208,7 +217,7 @@ func diffWafByteMatchSetTuples(oldT, newT []interface{}) []*waf.ByteMatchSetUpda 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{})), + FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), PositionalConstraint: aws.String(tuple["positional_constraint"].(string)), TargetString: []byte(tuple["target_string"].(string)), TextTransformation: aws.String(tuple["text_transformation"].(string)), @@ -222,7 +231,7 @@ func diffWafByteMatchSetTuples(oldT, newT []interface{}) []*waf.ByteMatchSetUpda 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{})), + FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), PositionalConstraint: aws.String(tuple["positional_constraint"].(string)), TargetString: []byte(tuple["target_string"].(string)), TextTransformation: aws.String(tuple["text_transformation"].(string)), diff --git a/aws/resource_aws_waf_byte_match_set_test.go b/aws/resource_aws_waf_byte_match_set_test.go index b56517bede1..78ea630b0bd 100644 --- a/aws/resource_aws_waf_byte_match_set_test.go +++ b/aws/resource_aws_waf_byte_match_set_test.go @@ -4,13 +4,14 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" "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/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" ) func TestAccAWSWafByteMatchSet_basic(t *testing.T) { @@ -19,10 +20,9 @@ func TestAccAWSWafByteMatchSet_basic(t *testing.T) { resourceName := "aws_waf_byte_match_set.byte_set" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafByteMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafByteMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafByteMatchSetConfig(byteMatchSet), @@ -30,18 +30,22 @@ func TestAccAWSWafByteMatchSet_basic(t *testing.T) { testAccCheckAWSWafByteMatchSetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", byteMatchSet), resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.#", "2"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.field_to_match.2991901334.data", "referer"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.field_to_match.2991901334.type", "HEADER"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.target_string", "badrefer1"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.text_transformation", "NONE"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.field_to_match.2991901334.data", "referer"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.field_to_match.2991901334.type", "HEADER"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.target_string", "badrefer2"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer1", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer2", + "text_transformation": "NONE", + }), ), }, { @@ -95,10 +99,9 @@ func TestAccAWSWafByteMatchSet_changeTuples(t *testing.T) { resourceName := "aws_waf_byte_match_set.byte_set" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafByteMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafByteMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafByteMatchSetConfig(byteMatchSetName), @@ -106,18 +109,22 @@ func TestAccAWSWafByteMatchSet_changeTuples(t *testing.T) { testAccCheckAWSWafByteMatchSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", byteMatchSetName), resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.#", "2"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.field_to_match.2991901334.data", "referer"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.field_to_match.2991901334.type", "HEADER"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.target_string", "badrefer1"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.text_transformation", "NONE"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.field_to_match.2991901334.data", "referer"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.field_to_match.2991901334.type", "HEADER"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.target_string", "badrefer2"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.839525137.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer1", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer2", + "text_transformation": "NONE", + }), ), }, { @@ -126,18 +133,22 @@ func TestAccAWSWafByteMatchSet_changeTuples(t *testing.T) { testAccCheckAWSWafByteMatchSetExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", byteMatchSetName), resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.#", "2"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.field_to_match.2991901334.data", "referer"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.field_to_match.2991901334.type", "HEADER"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.target_string", "badrefer1"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.2174619346.text_transformation", "NONE"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.4224486115.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.4224486115.field_to_match.4253810390.data", "GET"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.4224486115.field_to_match.4253810390.type", "METHOD"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.4224486115.positional_constraint", "CONTAINS_WORD"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.4224486115.target_string", "blah"), - resource.TestCheckResourceAttr(resourceName, "byte_match_tuples.4224486115.text_transformation", "URL_DECODE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer1", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "METHOD", + "positional_constraint": "CONTAINS_WORD", + "target_string": "blah", + "text_transformation": "URL_DECODE", + }), ), }, { @@ -386,7 +397,7 @@ resource "aws_waf_byte_match_set" "byte_set" { field_to_match { type = "METHOD" - data = "GET" + # data field omitted as the type is neither "HEADER" nor "SINGLE_QUERY_ARG" } } } diff --git a/aws/resource_aws_waf_geo_match_set.go b/aws/resource_aws_waf_geo_match_set.go index 6c99f9bad5f..2d863317352 100644 --- a/aws/resource_aws_waf_geo_match_set.go +++ b/aws/resource_aws_waf_geo_match_set.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafGeoMatchSet() *schema.Resource { diff --git a/aws/resource_aws_waf_geo_match_set_test.go b/aws/resource_aws_waf_geo_match_set_test.go index 3a360450100..2bae4ac652d 100644 --- a/aws/resource_aws_waf_geo_match_set_test.go +++ b/aws/resource_aws_waf_geo_match_set_test.go @@ -5,12 +5,13 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" ) func TestAccAWSWafGeoMatchSet_basic(t *testing.T) { @@ -19,10 +20,9 @@ func TestAccAWSWafGeoMatchSet_basic(t *testing.T) { resourceName := "aws_waf_geo_match_set.geo_match_set" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafGeoMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafGeoMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafGeoMatchSetConfig(geoMatchSet), @@ -31,10 +31,14 @@ func TestAccAWSWafGeoMatchSet_basic(t *testing.T) { testAccMatchResourceAttrGlobalARN(resourceName, "arn", "waf", regexp.MustCompile(`geomatchset/.+`)), resource.TestCheckResourceAttr(resourceName, "name", geoMatchSet), resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.#", "2"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.384465307.type", "Country"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.384465307.value", "US"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.1991628426.type", "Country"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.1991628426.value", "CA"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "US", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "CA", + }), ), }, { @@ -110,10 +114,9 @@ func TestAccAWSWafGeoMatchSet_changeConstraints(t *testing.T) { resourceName := "aws_waf_geo_match_set.geo_match_set" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafGeoMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafGeoMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafGeoMatchSetConfig(setName), @@ -121,10 +124,14 @@ func TestAccAWSWafGeoMatchSet_changeConstraints(t *testing.T) { testAccCheckAWSWafGeoMatchSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", setName), resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.#", "2"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.384465307.type", "Country"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.384465307.value", "US"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.1991628426.type", "Country"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.1991628426.value", "CA"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "US", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "CA", + }), ), }, { @@ -133,10 +140,14 @@ func TestAccAWSWafGeoMatchSet_changeConstraints(t *testing.T) { testAccCheckAWSWafGeoMatchSetExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", setName), resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.#", "2"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.1174390936.type", "Country"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.1174390936.value", "RU"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.4046309957.type", "Country"), - resource.TestCheckResourceAttr(resourceName, "geo_match_constraint.4046309957.value", "CN"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "RU", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "CN", + }), ), }, { diff --git a/aws/resource_aws_waf_ipset.go b/aws/resource_aws_waf_ipset.go index 19b90da7296..53d35950e33 100644 --- a/aws/resource_aws_waf_ipset.go +++ b/aws/resource_aws_waf_ipset.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) // WAF requires UpdateIPSet operations be split into batches of 1000 Updates diff --git a/aws/resource_aws_waf_ipset_test.go b/aws/resource_aws_waf_ipset_test.go index 1005fd3da17..f1b9612bdc2 100644 --- a/aws/resource_aws_waf_ipset_test.go +++ b/aws/resource_aws_waf_ipset_test.go @@ -10,9 +10,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSWafIPSet_basic(t *testing.T) { @@ -21,18 +22,19 @@ func TestAccAWSWafIPSet_basic(t *testing.T) { resourceName := "aws_waf_ipset.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafIPSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafIPSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafIPSetConfig(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSWafIPSetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.4037960608.type", "IPV4"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.4037960608.value", "192.0.7.0/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ip_set_descriptors.*", map[string]string{ + "type": "IPV4", + "value": "192.0.7.0/24", + }), testAccMatchResourceAttrGlobalARN(resourceName, "arn", "waf", regexp.MustCompile("ipset/.+$")), ), }, @@ -74,18 +76,19 @@ func TestAccAWSWafIPSet_changeNameForceNew(t *testing.T) { resourceName := "aws_waf_ipset.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafIPSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafIPSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafIPSetConfig(rName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSWafIPSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", rName), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.4037960608.type", "IPV4"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.4037960608.value", "192.0.7.0/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ip_set_descriptors.*", map[string]string{ + "type": "IPV4", + "value": "192.0.7.0/24", + }), ), }, { @@ -98,8 +101,10 @@ func TestAccAWSWafIPSet_changeNameForceNew(t *testing.T) { Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSWafIPSetExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", uName), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.4037960608.type", "IPV4"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.4037960608.value", "192.0.7.0/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ip_set_descriptors.*", map[string]string{ + "type": "IPV4", + "value": "192.0.7.0/24", + }), ), }, }, @@ -112,10 +117,9 @@ func TestAccAWSWafIPSet_changeDescriptors(t *testing.T) { resourceName := "aws_waf_ipset.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafIPSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafIPSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafIPSetConfig(rName), @@ -123,8 +127,10 @@ func TestAccAWSWafIPSet_changeDescriptors(t *testing.T) { testAccCheckAWSWafIPSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.4037960608.type", "IPV4"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.4037960608.value", "192.0.7.0/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ip_set_descriptors.*", map[string]string{ + "type": "IPV4", + "value": "192.0.7.0/24", + }), ), }, { @@ -138,8 +144,10 @@ func TestAccAWSWafIPSet_changeDescriptors(t *testing.T) { testAccCheckAWSWafIPSetExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.115741513.type", "IPV4"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptors.115741513.value", "192.0.8.0/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ip_set_descriptors.*", map[string]string{ + "type": "IPV4", + "value": "192.0.8.0/24", + }), ), }, }, diff --git a/aws/resource_aws_waf_rate_based_rule.go b/aws/resource_aws_waf_rate_based_rule.go index 6b2cbabd8fc..ea8fdf68a40 100644 --- a/aws/resource_aws_waf_rate_based_rule.go +++ b/aws/resource_aws_waf_rate_based_rule.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_waf_rate_based_rule_test.go b/aws/resource_aws_waf_rate_based_rule_test.go index 8979a948d94..e297c78745a 100644 --- a/aws/resource_aws_waf_rate_based_rule_test.go +++ b/aws/resource_aws_waf_rate_based_rule_test.go @@ -5,14 +5,15 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" "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/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" ) func TestAccAWSWafRateBasedRule_basic(t *testing.T) { @@ -114,10 +115,9 @@ func TestAccAWSWafRateBasedRule_changePredicates(t *testing.T) { resourceName := "aws_waf_rate_based_rule.wafrule" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRateBasedRuleConfig(ruleName), @@ -127,8 +127,10 @@ func TestAccAWSWafRateBasedRule_changePredicates(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", ruleName), resource.TestCheckResourceAttr(resourceName, "predicates.#", "1"), computeWafRateBasedRulePredicateWithIpSet(&ipset, false, "IPMatch", &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicates.%d.negated", &idx, "false"), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicates.%d.type", &idx, "IPMatch"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "predicate.*", map[string]string{ + "negated": "false", + "type": "IPMatch", + }), ), }, { @@ -139,8 +141,10 @@ func TestAccAWSWafRateBasedRule_changePredicates(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", ruleName), resource.TestCheckResourceAttr(resourceName, "predicates.#", "1"), computeWafRateBasedRulePredicateWithByteMatchSet(&byteMatchSet, true, "ByteMatch", &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicates.%d.negated", &idx, "true"), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicates.%d.type", &idx, "ByteMatch"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "predicate.*", map[string]string{ + "negated": "true", + "type": "ByteMatch", + }), ), }, { diff --git a/aws/resource_aws_waf_regex_match_set.go b/aws/resource_aws_waf_regex_match_set.go index af8ef7ff054..8898683fa81 100644 --- a/aws/resource_aws_waf_regex_match_set.go +++ b/aws/resource_aws_waf_regex_match_set.go @@ -8,7 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafRegexMatchSet() *schema.Resource { diff --git a/aws/resource_aws_waf_regex_match_set_test.go b/aws/resource_aws_waf_regex_match_set_test.go index 7c915209430..8b6718841f1 100644 --- a/aws/resource_aws_waf_regex_match_set_test.go +++ b/aws/resource_aws_waf_regex_match_set_test.go @@ -8,9 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -77,7 +78,7 @@ func testSweepWafRegexMatchSet(region string) error { // Serialized acceptance tests due to WAF account limits // https://docs.aws.amazon.com/waf/latest/developerguide/limits.html -func TestAccAWSWafRegexMatchSet(t *testing.T) { +func TestAccAWSWafRegexMatchSet_serial(t *testing.T) { testCases := map[string]func(t *testing.T){ "basic": testAccAWSWafRegexMatchSet_basic, "changePatterns": testAccAWSWafRegexMatchSet_changePatterns, @@ -108,10 +109,9 @@ func testAccAWSWafRegexMatchSet_basic(t *testing.T) { } resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegexMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegexMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegexMatchSetConfig(matchSetName, patternSetName), @@ -122,10 +122,12 @@ func testAccAWSWafRegexMatchSet_basic(t *testing.T) { computeWafRegexMatchSetTuple(&patternSet, &fieldToMatch, "NONE", &idx), resource.TestCheckResourceAttr(resourceName, "name", matchSetName), resource.TestCheckResourceAttr(resourceName, "regex_match_tuple.#", "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.#", &idx, "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.data", &idx, "user-agent"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.type", &idx, "HEADER"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.text_transformation", &idx, "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "regex_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "user-agent", + "field_to_match.0.type": "HEADER", + "text_transformation": "NONE", + }), ), }, { @@ -147,10 +149,9 @@ func testAccAWSWafRegexMatchSet_changePatterns(t *testing.T) { resourceName := "aws_waf_regex_match_set.test" resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegexMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegexMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegexMatchSetConfig(matchSetName, patternSetName), @@ -160,10 +161,12 @@ func testAccAWSWafRegexMatchSet_changePatterns(t *testing.T) { computeWafRegexMatchSetTuple(&patternSet, &waf.FieldToMatch{Data: aws.String("User-Agent"), Type: aws.String("HEADER")}, "NONE", &idx1), resource.TestCheckResourceAttr(resourceName, "name", matchSetName), resource.TestCheckResourceAttr(resourceName, "regex_match_tuple.#", "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.#", &idx1, "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.data", &idx1, "user-agent"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.type", &idx1, "HEADER"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.text_transformation", &idx1, "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "regex_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "user-agent", + "field_to_match.0.type": "HEADER", + "text_transformation": "NONE", + }), ), }, { @@ -174,10 +177,12 @@ func testAccAWSWafRegexMatchSet_changePatterns(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "regex_match_tuple.#", "1"), computeWafRegexMatchSetTuple(&patternSet, &waf.FieldToMatch{Data: aws.String("Referer"), Type: aws.String("HEADER")}, "COMPRESS_WHITE_SPACE", &idx2), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.#", &idx2, "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.data", &idx2, "referer"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.type", &idx2, "HEADER"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.text_transformation", &idx2, "COMPRESS_WHITE_SPACE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "regex_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "text_transformation": "COMPRESS_WHITE_SPACE", + }), ), }, { diff --git a/aws/resource_aws_waf_regex_pattern_set.go b/aws/resource_aws_waf_regex_pattern_set.go index 0767255f221..96a66135a76 100644 --- a/aws/resource_aws_waf_regex_pattern_set.go +++ b/aws/resource_aws_waf_regex_pattern_set.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafRegexPatternSet() *schema.Resource { diff --git a/aws/resource_aws_waf_regex_pattern_set_test.go b/aws/resource_aws_waf_regex_pattern_set_test.go index 966d5bbd8d5..bd033611233 100644 --- a/aws/resource_aws_waf_regex_pattern_set_test.go +++ b/aws/resource_aws_waf_regex_pattern_set_test.go @@ -7,14 +7,15 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) // Serialized acceptance tests due to WAF account limits // https://docs.aws.amazon.com/waf/latest/developerguide/limits.html -func TestAccAWSWafRegexPatternSet(t *testing.T) { +func TestAccAWSWafRegexPatternSet_serial(t *testing.T) { testCases := map[string]func(t *testing.T){ "basic": testAccAWSWafRegexPatternSet_basic, "changePatterns": testAccAWSWafRegexPatternSet_changePatterns, @@ -36,10 +37,9 @@ func testAccAWSWafRegexPatternSet_basic(t *testing.T) { resourceName := "aws_waf_regex_pattern_set.test" resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegexPatternSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegexPatternSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegexPatternSetConfig(patternSetName), @@ -48,8 +48,8 @@ func testAccAWSWafRegexPatternSet_basic(t *testing.T) { testAccMatchResourceAttrGlobalARN(resourceName, "arn", "waf", regexp.MustCompile(`regexpatternset/.+`)), resource.TestCheckResourceAttr(resourceName, "name", patternSetName), resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.#", "2"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.2848565413", "one"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.3351840846", "two"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "one"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "two"), ), }, { @@ -67,10 +67,9 @@ func testAccAWSWafRegexPatternSet_changePatterns(t *testing.T) { resourceName := "aws_waf_regex_pattern_set.test" resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegexPatternSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegexPatternSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegexPatternSetConfig(patternSetName), @@ -78,8 +77,8 @@ func testAccAWSWafRegexPatternSet_changePatterns(t *testing.T) { testAccCheckAWSWafRegexPatternSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", patternSetName), resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.#", "2"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.2848565413", "one"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.3351840846", "two"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "one"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "two"), ), }, { @@ -88,9 +87,9 @@ func testAccAWSWafRegexPatternSet_changePatterns(t *testing.T) { testAccCheckAWSWafRegexPatternSetExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", patternSetName), resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.#", "3"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.3351840846", "two"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.2929247714", "three"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.1294846542", "four"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "two"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "three"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "four"), ), }, { diff --git a/aws/resource_aws_waf_rule.go b/aws/resource_aws_waf_rule.go index 59b133c14f1..4ba58ea6af9 100644 --- a/aws/resource_aws_waf_rule.go +++ b/aws/resource_aws_waf_rule.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_waf_rule_group.go b/aws/resource_aws_waf_rule_group.go index 7bf3ed6429a..8f8fc6fe900 100644 --- a/aws/resource_aws_waf_rule_group.go +++ b/aws/resource_aws_waf_rule_group.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_waf_rule_group_test.go b/aws/resource_aws_waf_rule_group_test.go index c86f6328ae6..3661840b086 100644 --- a/aws/resource_aws_waf_rule_group_test.go +++ b/aws/resource_aws_waf_rule_group_test.go @@ -8,10 +8,11 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -73,10 +74,9 @@ func TestAccAWSWafRuleGroup_basic(t *testing.T) { resourceName := "aws_waf_rule_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRuleGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRuleGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRuleGroupConfig(ruleName, groupName), @@ -87,9 +87,11 @@ func TestAccAWSWafRuleGroup_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "activated_rule.#", "1"), resource.TestCheckResourceAttr(resourceName, "metric_name", groupName), computeWafActivatedRuleWithRuleId(&rule, "COUNT", 50, &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.action.0.type", &idx, "COUNT"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.priority", &idx, "50"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.type", &idx, waf.WafRuleTypeRegular), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "activated_rule.*", map[string]string{ + "action.0.type": "COUNT", + "priority": "50", + "type": waf.WafRuleTypeRegular, + }), testAccMatchResourceAttrGlobalARN(resourceName, "arn", "waf", regexp.MustCompile(`rulegroup/.+`)), ), }, @@ -177,10 +179,9 @@ func TestAccAWSWafRuleGroup_changeActivatedRules(t *testing.T) { resourceName := "aws_waf_rule_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRuleGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRuleGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRuleGroupConfig(ruleName1, groupName), @@ -190,9 +191,11 @@ func TestAccAWSWafRuleGroup_changeActivatedRules(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", groupName), resource.TestCheckResourceAttr(resourceName, "activated_rule.#", "1"), computeWafActivatedRuleWithRuleId(&rule0, "COUNT", 50, &idx0), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.action.0.type", &idx0, "COUNT"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.priority", &idx0, "50"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.type", &idx0, waf.WafRuleTypeRegular), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "activated_rule.*", map[string]string{ + "action.0.type": "COUNT", + "priority": "50", + "type": waf.WafRuleTypeRegular, + }), ), }, { @@ -204,21 +207,27 @@ func TestAccAWSWafRuleGroup_changeActivatedRules(t *testing.T) { testAccCheckAWSWafRuleExists("aws_waf_rule.test", &rule1), computeWafActivatedRuleWithRuleId(&rule1, "BLOCK", 10, &idx1), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.action.0.type", &idx1, "BLOCK"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.priority", &idx1, "10"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.type", &idx1, waf.WafRuleTypeRegular), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "activated_rule.*", map[string]string{ + "action.0.type": "BLOCK", + "priority": "10", + "type": waf.WafRuleTypeRegular, + }), testAccCheckAWSWafRuleExists("aws_waf_rule.test2", &rule2), computeWafActivatedRuleWithRuleId(&rule2, "COUNT", 1, &idx2), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.action.0.type", &idx2, "COUNT"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.priority", &idx2, "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.type", &idx2, waf.WafRuleTypeRegular), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "activated_rule.*", map[string]string{ + "action.0.type": "COUNT", + "priority": "1", + "type": waf.WafRuleTypeRegular, + }), testAccCheckAWSWafRuleExists("aws_waf_rule.test3", &rule3), computeWafActivatedRuleWithRuleId(&rule3, "BLOCK", 15, &idx3), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.action.0.type", &idx3, "BLOCK"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.priority", &idx3, "15"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.type", &idx3, waf.WafRuleTypeRegular), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "activated_rule.*", map[string]string{ + "action.0.type": "BLOCK", + "priority": "15", + "type": waf.WafRuleTypeRegular, + }), ), }, { diff --git a/aws/resource_aws_waf_rule_test.go b/aws/resource_aws_waf_rule_test.go index a47ff8bf5e9..68ec2bf65ad 100644 --- a/aws/resource_aws_waf_rule_test.go +++ b/aws/resource_aws_waf_rule_test.go @@ -5,14 +5,15 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/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/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSWafRule_basic(t *testing.T) { @@ -108,10 +109,9 @@ func TestAccAWSWafRule_changePredicates(t *testing.T) { resourceName := "aws_waf_rule.wafrule" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRuleConfig(ruleName), @@ -121,8 +121,10 @@ func TestAccAWSWafRule_changePredicates(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", ruleName), resource.TestCheckResourceAttr(resourceName, "predicates.#", "1"), computeWafRulePredicateWithIpSet(&ipset, false, "IPMatch", &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicates.%d.negated", &idx, "false"), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicates.%d.type", &idx, "IPMatch"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "predicates.*", map[string]string{ + "negated": "false", + "type": "IPMatch", + }), ), }, { @@ -133,8 +135,10 @@ func TestAccAWSWafRule_changePredicates(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", ruleName), resource.TestCheckResourceAttr(resourceName, "predicates.#", "1"), computeWafRulePredicateWithByteMatchSet(&byteMatchSet, true, "ByteMatch", &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicates.%d.negated", &idx, "true"), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicates.%d.type", &idx, "ByteMatch"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "predicates.*", map[string]string{ + "negated": "true", + "type": "ByteMatch", + }), ), }, }, @@ -150,10 +154,9 @@ func TestAccAWSWafRule_geoMatchSetPredicate(t *testing.T) { resourceName := "aws_waf_rule.wafrule" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRuleConfig_geoMatchSetPredicate(ruleName), @@ -163,8 +166,10 @@ func TestAccAWSWafRule_geoMatchSetPredicate(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", ruleName), resource.TestCheckResourceAttr(resourceName, "predicates.#", "1"), computeWafRulePredicateWithGeoMatchSet(&geoMatchSet, true, "GeoMatch", &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicates.%d.negated", &idx, "true"), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicates.%d.type", &idx, "GeoMatch"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "predicates.*", map[string]string{ + "negated": "true", + "type": "GeoMatch", + }), ), }, }, @@ -228,12 +233,6 @@ func computeWafRulePredicateWithGeoMatchSet(set *waf.GeoMatchSet, negated bool, } } -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)) diff --git a/aws/resource_aws_waf_size_constraint_set.go b/aws/resource_aws_waf_size_constraint_set.go index f14ee9ddb52..30c65a42dc6 100644 --- a/aws/resource_aws_waf_size_constraint_set.go +++ b/aws/resource_aws_waf_size_constraint_set.go @@ -8,7 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafSizeConstraintSet() *schema.Resource { diff --git a/aws/resource_aws_waf_size_constraint_set_test.go b/aws/resource_aws_waf_size_constraint_set_test.go index 5bcd85c0c89..553d88275e4 100644 --- a/aws/resource_aws_waf_size_constraint_set_test.go +++ b/aws/resource_aws_waf_size_constraint_set_test.go @@ -5,13 +5,14 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" "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/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" ) func TestAccAWSWafSizeConstraintSet_basic(t *testing.T) { @@ -20,10 +21,9 @@ func TestAccAWSWafSizeConstraintSet_basic(t *testing.T) { resourceName := "aws_waf_size_constraint_set.size_constraint_set" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafSizeConstraintSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafSizeConstraintSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafSizeConstraintSetConfig(sizeConstraintSet), @@ -32,12 +32,16 @@ func TestAccAWSWafSizeConstraintSet_basic(t *testing.T) { testAccMatchResourceAttrGlobalARN(resourceName, "arn", "waf", regexp.MustCompile(`sizeconstraintset/.+`)), resource.TestCheckResourceAttr(resourceName, "name", sizeConstraintSet), resource.TestCheckResourceAttr(resourceName, "size_constraints.#", "1"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.comparison_operator", "EQ"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.field_to_match.281401076.data", ""), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.field_to_match.281401076.type", "BODY"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.size", "4096"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*", map[string]string{ + "comparison_operator": "EQ", + "field_to_match.#": "1", + "size": "4096", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*.field_to_match.*", map[string]string{ + "data": "", + "type": "BODY", + }), ), }, { @@ -113,10 +117,9 @@ func TestAccAWSWafSizeConstraintSet_changeConstraints(t *testing.T) { resourceName := "aws_waf_size_constraint_set.size_constraint_set" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafSizeConstraintSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafSizeConstraintSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafSizeConstraintSetConfig(setName), @@ -124,12 +127,16 @@ func TestAccAWSWafSizeConstraintSet_changeConstraints(t *testing.T) { testAccCheckAWSWafSizeConstraintSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", setName), resource.TestCheckResourceAttr(resourceName, "size_constraints.#", "1"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.comparison_operator", "EQ"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.field_to_match.281401076.data", ""), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.field_to_match.281401076.type", "BODY"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.size", "4096"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.2029852522.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*", map[string]string{ + "comparison_operator": "EQ", + "field_to_match.#": "1", + "size": "4096", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*.field_to_match.*", map[string]string{ + "data": "", + "type": "BODY", + }), ), }, { @@ -138,12 +145,16 @@ func TestAccAWSWafSizeConstraintSet_changeConstraints(t *testing.T) { testAccCheckAWSWafSizeConstraintSetExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", setName), resource.TestCheckResourceAttr(resourceName, "size_constraints.#", "1"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.3222308386.comparison_operator", "GE"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.3222308386.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.3222308386.field_to_match.281401076.data", ""), - resource.TestCheckResourceAttr(resourceName, "size_constraints.3222308386.field_to_match.281401076.type", "BODY"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.3222308386.size", "1024"), - resource.TestCheckResourceAttr(resourceName, "size_constraints.3222308386.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*", map[string]string{ + "comparison_operator": "GE", + "field_to_match.#": "1", + "size": "1024", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*.field_to_match.*", map[string]string{ + "data": "", + "type": "BODY", + }), ), }, { diff --git a/aws/resource_aws_waf_sql_injection_match_set.go b/aws/resource_aws_waf_sql_injection_match_set.go index 66aa8e399e0..6f34281b6b1 100644 --- a/aws/resource_aws_waf_sql_injection_match_set.go +++ b/aws/resource_aws_waf_sql_injection_match_set.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafSqlInjectionMatchSet() *schema.Resource { @@ -31,7 +31,7 @@ func resourceAwsWafSqlInjectionMatchSet() *schema.Resource { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "field_to_match": { - Type: schema.TypeSet, + Type: schema.TypeList, Required: true, MaxItems: 1, Elem: &schema.Resource{ @@ -198,7 +198,7 @@ func diffWafSqlInjectionMatchTuples(oldT, newT []interface{}) []*waf.SqlInjectio updates = append(updates, &waf.SqlInjectionMatchSetUpdate{ Action: aws.String(waf.ChangeActionDelete), SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), + FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), TextTransformation: aws.String(tuple["text_transformation"].(string)), }, }) @@ -210,7 +210,7 @@ func diffWafSqlInjectionMatchTuples(oldT, newT []interface{}) []*waf.SqlInjectio updates = append(updates, &waf.SqlInjectionMatchSetUpdate{ Action: aws.String(waf.ChangeActionInsert), SqlInjectionMatchTuple: &waf.SqlInjectionMatchTuple{ - FieldToMatch: expandFieldToMatch(tuple["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), + FieldToMatch: expandFieldToMatch(tuple["field_to_match"].([]interface{})[0].(map[string]interface{})), TextTransformation: aws.String(tuple["text_transformation"].(string)), }, }) diff --git a/aws/resource_aws_waf_sql_injection_match_set_test.go b/aws/resource_aws_waf_sql_injection_match_set_test.go index afd330ef8ab..ba92fd78f3e 100644 --- a/aws/resource_aws_waf_sql_injection_match_set_test.go +++ b/aws/resource_aws_waf_sql_injection_match_set_test.go @@ -4,12 +4,13 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" ) func TestAccAWSWafSqlInjectionMatchSet_basic(t *testing.T) { @@ -18,10 +19,9 @@ func TestAccAWSWafSqlInjectionMatchSet_basic(t *testing.T) { resourceName := "aws_waf_sql_injection_match_set.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafSqlInjectionMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafSqlInjectionMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafSqlInjectionMatchSetConfig(rName), @@ -29,10 +29,12 @@ func TestAccAWSWafSqlInjectionMatchSet_basic(t *testing.T) { testAccCheckAWSWafSqlInjectionMatchSetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "sql_injection_match_tuples.#", "1"), - resource.TestCheckResourceAttr(resourceName, "sql_injection_match_tuples.3367958210.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "sql_injection_match_tuples.3367958210.field_to_match.2316364334.data", ""), - resource.TestCheckResourceAttr(resourceName, "sql_injection_match_tuples.3367958210.field_to_match.2316364334.type", "QUERY_STRING"), - resource.TestCheckResourceAttr(resourceName, "sql_injection_match_tuples.3367958210.text_transformation", "URL_DECODE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "sql_injection_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "QUERY_STRING", + "text_transformation": "URL_DECODE", + }), ), }, { @@ -108,10 +110,9 @@ func TestAccAWSWafSqlInjectionMatchSet_changeTuples(t *testing.T) { resourceName := "aws_waf_sql_injection_match_set.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafSqlInjectionMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafSqlInjectionMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafSqlInjectionMatchSetConfig(rName), @@ -119,10 +120,12 @@ func TestAccAWSWafSqlInjectionMatchSet_changeTuples(t *testing.T) { testAccCheckAWSWafSqlInjectionMatchSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "sql_injection_match_tuples.#", "1"), - resource.TestCheckResourceAttr(resourceName, "sql_injection_match_tuples.3367958210.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "sql_injection_match_tuples.3367958210.field_to_match.2316364334.data", ""), - resource.TestCheckResourceAttr(resourceName, "sql_injection_match_tuples.3367958210.field_to_match.2316364334.type", "QUERY_STRING"), - resource.TestCheckResourceAttr(resourceName, "sql_injection_match_tuples.3367958210.text_transformation", "URL_DECODE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "sql_injection_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "QUERY_STRING", + "text_transformation": "URL_DECODE", + }), ), }, { diff --git a/aws/resource_aws_waf_web_acl.go b/aws/resource_aws_waf_web_acl.go index aca664f62b9..e3b522ca1a7 100644 --- a/aws/resource_aws_waf_web_acl.go +++ b/aws/resource_aws_waf_web_acl.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -33,7 +33,7 @@ func resourceAwsWafWebAcl() *schema.Resource { ForceNew: true, }, "default_action": { - Type: schema.TypeSet, + Type: schema.TypeList, Required: true, MaxItems: 1, Elem: &schema.Resource{ @@ -154,7 +154,7 @@ func resourceAwsWafWebAclCreate(d *schema.ResourceData, meta interface{}) error out, err := wr.RetryWithToken(func(token *string) (interface{}, error) { params := &waf.CreateWebACLInput{ ChangeToken: token, - DefaultAction: expandWafAction(d.Get("default_action").(*schema.Set).List()), + DefaultAction: expandWafAction(d.Get("default_action").([]interface{})), MetricName: aws.String(d.Get("metric_name").(string)), Name: aws.String(d.Get("name").(string)), } @@ -196,7 +196,7 @@ func resourceAwsWafWebAclCreate(d *schema.ResourceData, meta interface{}) error _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { req := &waf.UpdateWebACLInput{ ChangeToken: token, - DefaultAction: expandWafAction(d.Get("default_action").(*schema.Set).List()), + DefaultAction: expandWafAction(d.Get("default_action").([]interface{})), Updates: diffWafWebAclRules([]interface{}{}, rules), WebACLId: aws.String(d.Id()), } @@ -282,7 +282,7 @@ func resourceAwsWafWebAclRead(d *schema.ResourceData, meta interface{}) error { func resourceAwsWafWebAclUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).wafconn - if d.HasChange("default_action") || d.HasChange("rules") { + if d.HasChanges("default_action", "rules") { o, n := d.GetChange("rules") oldR, newR := o.(*schema.Set).List(), n.(*schema.Set).List() @@ -290,7 +290,7 @@ func resourceAwsWafWebAclUpdate(d *schema.ResourceData, meta interface{}) error _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { req := &waf.UpdateWebACLInput{ ChangeToken: token, - DefaultAction: expandWafAction(d.Get("default_action").(*schema.Set).List()), + DefaultAction: expandWafAction(d.Get("default_action").([]interface{})), Updates: diffWafWebAclRules(oldR, newR), WebACLId: aws.String(d.Id()), } @@ -347,7 +347,7 @@ func resourceAwsWafWebAclDelete(d *schema.ResourceData, meta interface{}) error _, err := wr.RetryWithToken(func(token *string) (interface{}, error) { req := &waf.UpdateWebACLInput{ ChangeToken: token, - DefaultAction: expandWafAction(d.Get("default_action").(*schema.Set).List()), + DefaultAction: expandWafAction(d.Get("default_action").([]interface{})), Updates: diffWafWebAclRules(rules, []interface{}{}), WebACLId: aws.String(d.Id()), } diff --git a/aws/resource_aws_waf_web_acl_test.go b/aws/resource_aws_waf_web_acl_test.go index 1309e31d38d..5844f45bd24 100644 --- a/aws/resource_aws_waf_web_acl_test.go +++ b/aws/resource_aws_waf_web_acl_test.go @@ -9,9 +9,9 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { @@ -120,17 +120,16 @@ func TestAccAWSWafWebAcl_basic(t *testing.T) { resourceName := "aws_waf_web_acl.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafWebAclDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafWebAclDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafWebAclConfig_Required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSWafWebAclExists(resourceName, &webACL), resource.TestCheckResourceAttr(resourceName, "default_action.#", "1"), - resource.TestCheckResourceAttr(resourceName, "default_action.4234791575.type", "ALLOW"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.type", "ALLOW"), resource.TestCheckResourceAttr(resourceName, "metric_name", rName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -154,17 +153,16 @@ func TestAccAWSWafWebAcl_changeNameForceNew(t *testing.T) { resourceName := "aws_waf_web_acl.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafWebAclDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafWebAclDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafWebAclConfig_Required(rName1), Check: resource.ComposeTestCheckFunc( testAccCheckAWSWafWebAclExists(resourceName, &webACL), resource.TestCheckResourceAttr(resourceName, "default_action.#", "1"), - resource.TestCheckResourceAttr(resourceName, "default_action.4234791575.type", "ALLOW"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.type", "ALLOW"), resource.TestCheckResourceAttr(resourceName, "metric_name", rName1), resource.TestCheckResourceAttr(resourceName, "name", rName1), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -176,7 +174,7 @@ func TestAccAWSWafWebAcl_changeNameForceNew(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSWafWebAclExists(resourceName, &webACL), resource.TestCheckResourceAttr(resourceName, "default_action.#", "1"), - resource.TestCheckResourceAttr(resourceName, "default_action.4234791575.type", "ALLOW"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.type", "ALLOW"), resource.TestCheckResourceAttr(resourceName, "metric_name", rName2), resource.TestCheckResourceAttr(resourceName, "name", rName2), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), @@ -198,17 +196,16 @@ func TestAccAWSWafWebAcl_DefaultAction(t *testing.T) { resourceName := "aws_waf_web_acl.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafWebAclDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafWebAclDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafWebAclConfig_DefaultAction(rName, "ALLOW"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSWafWebAclExists(resourceName, &webACL), resource.TestCheckResourceAttr(resourceName, "default_action.#", "1"), - resource.TestCheckResourceAttr(resourceName, "default_action.4234791575.type", "ALLOW"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.type", "ALLOW"), ), }, { @@ -216,7 +213,7 @@ func TestAccAWSWafWebAcl_DefaultAction(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSWafWebAclExists(resourceName, &webACL), resource.TestCheckResourceAttr(resourceName, "default_action.#", "1"), - resource.TestCheckResourceAttr(resourceName, "default_action.2267395054.type", "BLOCK"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.type", "BLOCK"), ), }, { @@ -350,17 +347,16 @@ func TestAccAWSWafWebAcl_Tags(t *testing.T) { resourceName := "aws_waf_web_acl.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafWebAclDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafWebAclDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafWebAclConfigTags1(rName, "key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSWafWebAclExists(resourceName, &webACL), resource.TestCheckResourceAttr(resourceName, "default_action.#", "1"), - resource.TestCheckResourceAttr(resourceName, "default_action.4234791575.type", "ALLOW"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.type", "ALLOW"), resource.TestCheckResourceAttr(resourceName, "metric_name", rName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), @@ -373,7 +369,7 @@ func TestAccAWSWafWebAcl_Tags(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSWafWebAclExists(resourceName, &webACL), resource.TestCheckResourceAttr(resourceName, "default_action.#", "1"), - resource.TestCheckResourceAttr(resourceName, "default_action.4234791575.type", "ALLOW"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.type", "ALLOW"), resource.TestCheckResourceAttr(resourceName, "metric_name", rName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), @@ -387,7 +383,7 @@ func TestAccAWSWafWebAcl_Tags(t *testing.T) { Check: resource.ComposeTestCheckFunc( testAccCheckAWSWafWebAclExists(resourceName, &webACL), resource.TestCheckResourceAttr(resourceName, "default_action.#", "1"), - resource.TestCheckResourceAttr(resourceName, "default_action.4234791575.type", "ALLOW"), + resource.TestCheckResourceAttr(resourceName, "default_action.0.type", "ALLOW"), resource.TestCheckResourceAttr(resourceName, "metric_name", rName), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), diff --git a/aws/resource_aws_waf_xss_match_set.go b/aws/resource_aws_waf_xss_match_set.go index bd14289fef5..2e29716aa5d 100644 --- a/aws/resource_aws_waf_xss_match_set.go +++ b/aws/resource_aws_waf_xss_match_set.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsWafXssMatchSet() *schema.Resource { diff --git a/aws/resource_aws_waf_xss_match_set_test.go b/aws/resource_aws_waf_xss_match_set_test.go index 91bb27cb3a7..58c5b73b0dc 100644 --- a/aws/resource_aws_waf_xss_match_set_test.go +++ b/aws/resource_aws_waf_xss_match_set_test.go @@ -7,9 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSWafXssMatchSet_basic(t *testing.T) { @@ -18,10 +19,9 @@ func TestAccAWSWafXssMatchSet_basic(t *testing.T) { resourceName := "aws_waf_xss_match_set.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafXssMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafXssMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafXssMatchSetConfig(rName), @@ -30,14 +30,18 @@ func TestAccAWSWafXssMatchSet_basic(t *testing.T) { testAccMatchResourceAttrGlobalARN(resourceName, "arn", "waf", regexp.MustCompile(`xssmatchset/.+`)), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.#", "2"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.41660541.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.41660541.field_to_match.0.data", ""), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.41660541.field_to_match.0.type", "URI"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.41660541.text_transformation", "NONE"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.599421078.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.599421078.field_to_match.0.data", ""), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.599421078.field_to_match.0.type", "QUERY_STRING"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.599421078.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "URI", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "QUERY_STRING", + "text_transformation": "NONE", + }), ), }, { @@ -113,10 +117,9 @@ func TestAccAWSWafXssMatchSet_changeTuples(t *testing.T) { resourceName := "aws_waf_xss_match_set.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafXssMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSWaf(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafXssMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafXssMatchSetConfig(setName), @@ -124,14 +127,18 @@ func TestAccAWSWafXssMatchSet_changeTuples(t *testing.T) { testAccCheckAWSWafXssMatchSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", setName), resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.#", "2"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.599421078.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.599421078.field_to_match.0.data", ""), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.599421078.field_to_match.0.type", "QUERY_STRING"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.599421078.text_transformation", "NONE"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.41660541.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.41660541.field_to_match.0.data", ""), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.41660541.field_to_match.0.type", "URI"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.41660541.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "QUERY_STRING", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "URI", + "text_transformation": "NONE", + }), ), }, { @@ -140,14 +147,18 @@ func TestAccAWSWafXssMatchSet_changeTuples(t *testing.T) { testAccCheckAWSWafXssMatchSetExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", setName), resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.#", "2"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.42378128.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.42378128.field_to_match.0.data", "GET"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.42378128.field_to_match.0.type", "METHOD"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.42378128.text_transformation", "HTML_ENTITY_DECODE"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.3815294338.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.3815294338.field_to_match.0.data", ""), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.3815294338.field_to_match.0.type", "BODY"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuples.3815294338.text_transformation", "CMD_LINE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "GET", + "field_to_match.0.type": "METHOD", + "text_transformation": "HTML_ENTITY_DECODE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "BODY", + "text_transformation": "CMD_LINE", + }), ), }, { diff --git a/aws/resource_aws_wafregional_byte_match_set.go b/aws/resource_aws_wafregional_byte_match_set.go index 399bec8401f..4a53d1da49e 100644 --- a/aws/resource_aws_wafregional_byte_match_set.go +++ b/aws/resource_aws_wafregional_byte_match_set.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafRegionalByteMatchSet() *schema.Resource { @@ -26,44 +26,6 @@ func resourceAwsWafRegionalByteMatchSet() *schema.Resource { Required: true, ForceNew: true, }, - "byte_match_tuple": { - Type: schema.TypeSet, - Optional: true, - Removed: "use `byte_match_tuples` configuration block(s) instead", - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "field_to_match": { - Type: schema.TypeList, - 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": { - Type: schema.TypeString, - Required: true, - }, - "target_string": { - Type: schema.TypeString, - Optional: true, - }, - "text_transformation": { - Type: schema.TypeString, - Required: true, - }, - }, - }, - }, "byte_match_tuples": { Type: schema.TypeSet, Optional: true, diff --git a/aws/resource_aws_wafregional_byte_match_set_test.go b/aws/resource_aws_wafregional_byte_match_set_test.go index d6ee51f4dc3..5b436349619 100644 --- a/aws/resource_aws_wafregional_byte_match_set_test.go +++ b/aws/resource_aws_wafregional_byte_match_set_test.go @@ -4,12 +4,13 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" ) func TestAccAWSWafRegionalByteMatchSet_basic(t *testing.T) { @@ -18,10 +19,9 @@ func TestAccAWSWafRegionalByteMatchSet_basic(t *testing.T) { resourceName := "aws_wafregional_byte_match_set.byte_set" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalByteMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalByteMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalByteMatchSetConfig(byteMatchSet), @@ -31,30 +31,22 @@ func TestAccAWSWafRegionalByteMatchSet_basic(t *testing.T) { resourceName, "name", byteMatchSet), resource.TestCheckResourceAttr( resourceName, "byte_match_tuples.#", "2"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.field_to_match.0.data", "referer"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.field_to_match.0.type", "HEADER"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.target_string", "badrefer1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.text_transformation", "NONE"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.field_to_match.0.data", "referer"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.field_to_match.0.type", "HEADER"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.target_string", "badrefer2"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer1", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer2", + "text_transformation": "NONE", + }), ), }, { @@ -73,10 +65,9 @@ func TestAccAWSWafRegionalByteMatchSet_changeNameForceNew(t *testing.T) { resourceName := "aws_wafregional_byte_match_set.byte_set" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalByteMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalByteMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalByteMatchSetConfig(byteMatchSet), @@ -86,30 +77,22 @@ func TestAccAWSWafRegionalByteMatchSet_changeNameForceNew(t *testing.T) { resourceName, "name", byteMatchSet), resource.TestCheckResourceAttr( resourceName, "byte_match_tuples.#", "2"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.field_to_match.0.data", "referer"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.field_to_match.0.type", "HEADER"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.target_string", "badrefer1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.text_transformation", "NONE"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.field_to_match.0.data", "referer"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.field_to_match.0.type", "HEADER"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.target_string", "badrefer2"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer1", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer2", + "text_transformation": "NONE", + }), ), }, { @@ -120,30 +103,22 @@ func TestAccAWSWafRegionalByteMatchSet_changeNameForceNew(t *testing.T) { resourceName, "name", byteMatchSetNewName), resource.TestCheckResourceAttr( resourceName, "byte_match_tuples.#", "2"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.field_to_match.0.data", "referer"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.field_to_match.0.type", "HEADER"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.target_string", "badrefer1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.text_transformation", "NONE"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.field_to_match.0.data", "referer"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.field_to_match.0.type", "HEADER"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.target_string", "badrefer2"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer1", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer2", + "text_transformation": "NONE", + }), ), }, { @@ -161,10 +136,9 @@ func TestAccAWSWafRegionalByteMatchSet_changeByteMatchTuples(t *testing.T) { resourceName := "aws_wafregional_byte_match_set.byte_set" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalByteMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalByteMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalByteMatchSetConfig(byteMatchSetName), @@ -174,26 +148,20 @@ func TestAccAWSWafRegionalByteMatchSet_changeByteMatchTuples(t *testing.T) { resourceName, "name", byteMatchSetName), resource.TestCheckResourceAttr( resourceName, "byte_match_tuples.#", "2"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.field_to_match.0.data", "referer"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.field_to_match.0.type", "HEADER"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.target_string", "badrefer1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.3483354334.text_transformation", "NONE"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.field_to_match.0.data", "referer"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.field_to_match.0.type", "HEADER"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.positional_constraint", "CONTAINS"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.target_string", "badrefer2"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2081155357.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer1", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "positional_constraint": "CONTAINS", + "target_string": "badrefer2", + "text_transformation": "NONE", + }), ), }, { @@ -204,30 +172,22 @@ func TestAccAWSWafRegionalByteMatchSet_changeByteMatchTuples(t *testing.T) { resourceName, "name", byteMatchSetName), resource.TestCheckResourceAttr( resourceName, "byte_match_tuples.#", "2"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2069994922.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2069994922.field_to_match.0.data", ""), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2069994922.field_to_match.0.type", "METHOD"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2069994922.positional_constraint", "EXACTLY"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2069994922.target_string", "GET"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2069994922.text_transformation", "NONE"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2506804529.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2506804529.field_to_match.0.data", ""), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2506804529.field_to_match.0.type", "URI"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2506804529.positional_constraint", "ENDS_WITH"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2506804529.target_string", "badrefer2+"), - resource.TestCheckResourceAttr( - resourceName, "byte_match_tuples.2506804529.text_transformation", "LOWERCASE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "METHOD", + "positional_constraint": "EXACTLY", + "target_string": "GET", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "byte_match_tuples.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "URI", + "positional_constraint": "ENDS_WITH", + "target_string": "badrefer2+", + "text_transformation": "LOWERCASE", + }), ), }, { diff --git a/aws/resource_aws_wafregional_geo_match_set.go b/aws/resource_aws_wafregional_geo_match_set.go index 8e573002c09..22e70b6084b 100644 --- a/aws/resource_aws_wafregional_geo_match_set.go +++ b/aws/resource_aws_wafregional_geo_match_set.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafRegionalGeoMatchSet() *schema.Resource { diff --git a/aws/resource_aws_wafregional_geo_match_set_test.go b/aws/resource_aws_wafregional_geo_match_set_test.go index b7854e2408c..bb46f6a5f1c 100644 --- a/aws/resource_aws_wafregional_geo_match_set_test.go +++ b/aws/resource_aws_wafregional_geo_match_set_test.go @@ -6,9 +6,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSWafRegionalGeoMatchSet_basic(t *testing.T) { @@ -17,10 +18,9 @@ func TestAccAWSWafRegionalGeoMatchSet_basic(t *testing.T) { geoMatchSet := fmt.Sprintf("tfacc-%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalGeoMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalGeoMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalGeoMatchSetConfig(geoMatchSet), @@ -30,14 +30,14 @@ func TestAccAWSWafRegionalGeoMatchSet_basic(t *testing.T) { resourceName, "name", geoMatchSet), resource.TestCheckResourceAttr( resourceName, "geo_match_constraint.#", "2"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.384465307.type", "Country"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.384465307.value", "US"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.1991628426.type", "Country"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.1991628426.value", "CA"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "US", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "CA", + }), ), }, { @@ -118,10 +118,9 @@ func TestAccAWSWafRegionalGeoMatchSet_changeConstraints(t *testing.T) { setName := fmt.Sprintf("tfacc-%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalGeoMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalGeoMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalGeoMatchSetConfig(setName), @@ -131,14 +130,14 @@ func TestAccAWSWafRegionalGeoMatchSet_changeConstraints(t *testing.T) { resourceName, "name", setName), resource.TestCheckResourceAttr( resourceName, "geo_match_constraint.#", "2"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.384465307.type", "Country"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.384465307.value", "US"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.1991628426.type", "Country"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.1991628426.value", "CA"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "US", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "CA", + }), ), }, { @@ -149,14 +148,14 @@ func TestAccAWSWafRegionalGeoMatchSet_changeConstraints(t *testing.T) { resourceName, "name", setName), resource.TestCheckResourceAttr( resourceName, "geo_match_constraint.#", "2"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.1174390936.type", "Country"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.1174390936.value", "RU"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.4046309957.type", "Country"), - resource.TestCheckResourceAttr( - resourceName, "geo_match_constraint.4046309957.value", "CN"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "RU", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "geo_match_constraint.*", map[string]string{ + "type": "Country", + "value": "CN", + }), ), }, { diff --git a/aws/resource_aws_wafregional_ipset.go b/aws/resource_aws_wafregional_ipset.go index 2fee9e44b2b..bb5240dc47d 100644 --- a/aws/resource_aws_wafregional_ipset.go +++ b/aws/resource_aws_wafregional_ipset.go @@ -9,7 +9,7 @@ import ( "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-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafRegionalIPSet() *schema.Resource { diff --git a/aws/resource_aws_wafregional_ipset_test.go b/aws/resource_aws_wafregional_ipset_test.go index c4546f3f8e8..ae2b6206ac9 100644 --- a/aws/resource_aws_wafregional_ipset_test.go +++ b/aws/resource_aws_wafregional_ipset_test.go @@ -8,14 +8,15 @@ import ( "strings" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" "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-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" ) func TestAccAWSWafRegionalIPSet_basic(t *testing.T) { @@ -24,18 +25,19 @@ func TestAccAWSWafRegionalIPSet_basic(t *testing.T) { ipsetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalIPSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalIPSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalIPSetConfig(ipsetName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSWafRegionalIPSetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", ipsetName), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.4037960608.type", "IPV4"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.4037960608.value", "192.0.7.0/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ip_set_descriptor.*", map[string]string{ + "type": "IPV4", + "value": "192.0.7.0/24", + }), testAccMatchResourceAttrRegionalARN(resourceName, "arn", "waf-regional", regexp.MustCompile("ipset/.+$")), ), }, @@ -76,18 +78,19 @@ func TestAccAWSWafRegionalIPSet_changeNameForceNew(t *testing.T) { ipsetNewName := fmt.Sprintf("ip-set-new-%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalIPSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalIPSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalIPSetConfig(ipsetName), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSWafRegionalIPSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", ipsetName), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.4037960608.type", "IPV4"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.4037960608.value", "192.0.7.0/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ip_set_descriptor.*", map[string]string{ + "type": "IPV4", + "value": "192.0.7.0/24", + }), ), }, { @@ -95,8 +98,10 @@ func TestAccAWSWafRegionalIPSet_changeNameForceNew(t *testing.T) { Check: resource.ComposeAggregateTestCheckFunc( testAccCheckAWSWafRegionalIPSetExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", ipsetNewName), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.4037960608.type", "IPV4"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.4037960608.value", "192.0.7.0/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ip_set_descriptor.*", map[string]string{ + "type": "IPV4", + "value": "192.0.7.0/24", + }), ), }, { @@ -114,10 +119,9 @@ func TestAccAWSWafRegionalIPSet_changeDescriptors(t *testing.T) { ipsetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalIPSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalIPSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalIPSetConfig(ipsetName), @@ -125,8 +129,10 @@ func TestAccAWSWafRegionalIPSet_changeDescriptors(t *testing.T) { testAccCheckAWSWafRegionalIPSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", ipsetName), resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.4037960608.type", "IPV4"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.4037960608.value", "192.0.7.0/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ip_set_descriptor.*", map[string]string{ + "type": "IPV4", + "value": "192.0.7.0/24", + }), ), }, { @@ -135,8 +141,10 @@ func TestAccAWSWafRegionalIPSet_changeDescriptors(t *testing.T) { testAccCheckAWSWafRegionalIPSetExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", ipsetName), resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.#", "1"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.115741513.type", "IPV4"), - resource.TestCheckResourceAttr(resourceName, "ip_set_descriptor.115741513.value", "192.0.8.0/24"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "ip_set_descriptor.*", map[string]string{ + "type": "IPV4", + "value": "192.0.8.0/24", + }), ), }, { diff --git a/aws/resource_aws_wafregional_rate_based_rule.go b/aws/resource_aws_wafregional_rate_based_rule.go index 4073489c98d..c82b0500484 100644 --- a/aws/resource_aws_wafregional_rate_based_rule.go +++ b/aws/resource_aws_wafregional_rate_based_rule.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -172,7 +172,7 @@ func resourceAwsWafRegionalRateBasedRuleUpdate(d *schema.ResourceData, meta inte conn := meta.(*AWSClient).wafregionalconn region := meta.(*AWSClient).region - if d.HasChange("predicate") || d.HasChange("rate_limit") { + if d.HasChanges("predicate", "rate_limit") { o, n := d.GetChange("predicate") oldP, newP := o.(*schema.Set).List(), n.(*schema.Set).List() rateLimit := d.Get("rate_limit") diff --git a/aws/resource_aws_wafregional_rate_based_rule_test.go b/aws/resource_aws_wafregional_rate_based_rule_test.go index ec3c4811575..153d15b6f59 100644 --- a/aws/resource_aws_wafregional_rate_based_rule_test.go +++ b/aws/resource_aws_wafregional_rate_based_rule_test.go @@ -9,10 +9,11 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -259,10 +260,9 @@ func TestAccAWSWafRegionalRateBasedRule_changePredicates(t *testing.T) { ruleName := fmt.Sprintf("wafrule%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalRateBasedRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalRateBasedRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalRateBasedRuleConfig(ruleName), @@ -272,8 +272,10 @@ func TestAccAWSWafRegionalRateBasedRule_changePredicates(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", ruleName), resource.TestCheckResourceAttr(resourceName, "predicate.#", "1"), computeWafRegionalRateBasedRulePredicateWithIpSet(&ipset, false, "IPMatch", &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicate.%d.negated", &idx, "false"), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicate.%d.type", &idx, "IPMatch"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "predicates.*", map[string]string{ + "negated": "false", + "type": "IPMatch", + }), ), }, { @@ -284,8 +286,10 @@ func TestAccAWSWafRegionalRateBasedRule_changePredicates(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", ruleName), resource.TestCheckResourceAttr(resourceName, "predicate.#", "1"), computeWafRegionalRateBasedRulePredicateWithByteMatchSet(&byteMatchSet, true, "ByteMatch", &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicate.%d.negated", &idx, "true"), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicate.%d.type", &idx, "ByteMatch"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "predicates.*", map[string]string{ + "negated": "true", + "type": "ByteMatch", + }), ), }, { diff --git a/aws/resource_aws_wafregional_regex_match_set.go b/aws/resource_aws_wafregional_regex_match_set.go index fe16df030df..a6d68b0cc82 100644 --- a/aws/resource_aws_wafregional_regex_match_set.go +++ b/aws/resource_aws_wafregional_regex_match_set.go @@ -8,7 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafRegionalRegexMatchSet() *schema.Resource { diff --git a/aws/resource_aws_wafregional_regex_match_set_test.go b/aws/resource_aws_wafregional_regex_match_set_test.go index a48bac580b6..1985a7055e1 100644 --- a/aws/resource_aws_wafregional_regex_match_set_test.go +++ b/aws/resource_aws_wafregional_regex_match_set_test.go @@ -8,9 +8,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -77,7 +78,7 @@ func testSweepWafRegionalRegexMatchSet(region string) error { // Serialized acceptance tests due to WAF account limits // https://docs.aws.amazon.com/waf/latest/developerguide/limits.html -func TestAccAWSWafRegionalRegexMatchSet(t *testing.T) { +func TestAccAWSWafRegionalRegexMatchSet_serial(t *testing.T) { testCases := map[string]func(t *testing.T){ "basic": testAccAWSWafRegionalRegexMatchSet_basic, "changePatterns": testAccAWSWafRegionalRegexMatchSet_changePatterns, @@ -108,10 +109,9 @@ func testAccAWSWafRegionalRegexMatchSet_basic(t *testing.T) { } resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalRegexMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalRegexMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalRegexMatchSetConfig(matchSetName, patternSetName), @@ -121,10 +121,12 @@ func testAccAWSWafRegionalRegexMatchSet_basic(t *testing.T) { computeWafRegexMatchSetTuple(&patternSet, &fieldToMatch, "NONE", &idx), resource.TestCheckResourceAttr(resourceName, "name", matchSetName), resource.TestCheckResourceAttr(resourceName, "regex_match_tuple.#", "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.#", &idx, "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.data", &idx, "user-agent"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.type", &idx, "HEADER"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.text_transformation", &idx, "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "regex_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "user-agent", + "field_to_match.0.type": "HEADER", + "text_transformation": "NONE", + }), ), }, { @@ -146,10 +148,9 @@ func testAccAWSWafRegionalRegexMatchSet_changePatterns(t *testing.T) { patternSetName := fmt.Sprintf("tfacc-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalRegexMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalRegexMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalRegexMatchSetConfig(matchSetName, patternSetName), @@ -159,10 +160,12 @@ func testAccAWSWafRegionalRegexMatchSet_changePatterns(t *testing.T) { computeWafRegexMatchSetTuple(&patternSet, &waf.FieldToMatch{Data: aws.String("User-Agent"), Type: aws.String("HEADER")}, "NONE", &idx1), resource.TestCheckResourceAttr(resourceName, "name", matchSetName), resource.TestCheckResourceAttr(resourceName, "regex_match_tuple.#", "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.#", &idx1, "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.data", &idx1, "user-agent"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.type", &idx1, "HEADER"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.text_transformation", &idx1, "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "regex_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "user-agent", + "field_to_match.0.type": "HEADER", + "text_transformation": "NONE", + }), ), }, { @@ -173,10 +176,12 @@ func testAccAWSWafRegionalRegexMatchSet_changePatterns(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "regex_match_tuple.#", "1"), computeWafRegexMatchSetTuple(&patternSet, &waf.FieldToMatch{Data: aws.String("Referer"), Type: aws.String("HEADER")}, "COMPRESS_WHITE_SPACE", &idx2), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.#", &idx2, "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.data", &idx2, "referer"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.field_to_match.0.type", &idx2, "HEADER"), - testCheckResourceAttrWithIndexesAddr(resourceName, "regex_match_tuple.%d.text_transformation", &idx2, "COMPRESS_WHITE_SPACE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "regex_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "referer", + "field_to_match.0.type": "HEADER", + "text_transformation": "COMPRESS_WHITE_SPACE", + }), ), }, { diff --git a/aws/resource_aws_wafregional_regex_pattern_set.go b/aws/resource_aws_wafregional_regex_pattern_set.go index 29a0f15fc81..be7a2d8bd35 100644 --- a/aws/resource_aws_wafregional_regex_pattern_set.go +++ b/aws/resource_aws_wafregional_regex_pattern_set.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafRegionalRegexPatternSet() *schema.Resource { diff --git a/aws/resource_aws_wafregional_regex_pattern_set_test.go b/aws/resource_aws_wafregional_regex_pattern_set_test.go index 385c625dfdd..b89f185a53f 100644 --- a/aws/resource_aws_wafregional_regex_pattern_set_test.go +++ b/aws/resource_aws_wafregional_regex_pattern_set_test.go @@ -7,14 +7,15 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) // Serialized acceptance tests due to WAF account limits // https://docs.aws.amazon.com/waf/latest/developerguide/limits.html -func TestAccAWSWafRegionalRegexPatternSet(t *testing.T) { +func TestAccAWSWafRegionalRegexPatternSet_serial(t *testing.T) { testCases := map[string]func(t *testing.T){ "basic": testAccAWSWafRegionalRegexPatternSet_basic, "changePatterns": testAccAWSWafRegionalRegexPatternSet_changePatterns, @@ -36,10 +37,9 @@ func testAccAWSWafRegionalRegexPatternSet_basic(t *testing.T) { resourceName := "aws_wafregional_regex_pattern_set.test" resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalRegexPatternSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalRegexPatternSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalRegexPatternSetConfig(patternSetName), @@ -47,8 +47,8 @@ func testAccAWSWafRegionalRegexPatternSet_basic(t *testing.T) { testAccCheckAWSWafRegionalRegexPatternSetExists(resourceName, &patternSet), resource.TestCheckResourceAttr(resourceName, "name", patternSetName), resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.#", "2"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.2848565413", "one"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.3351840846", "two"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "one"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "two"), ), }, { @@ -66,10 +66,9 @@ func testAccAWSWafRegionalRegexPatternSet_changePatterns(t *testing.T) { resourceName := "aws_wafregional_regex_pattern_set.test" resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalRegexPatternSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalRegexPatternSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalRegexPatternSetConfig(patternSetName), @@ -77,8 +76,8 @@ func testAccAWSWafRegionalRegexPatternSet_changePatterns(t *testing.T) { testAccCheckAWSWafRegionalRegexPatternSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", patternSetName), resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.#", "2"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.2848565413", "one"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.3351840846", "two"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "one"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "two"), ), }, { @@ -87,9 +86,9 @@ func testAccAWSWafRegionalRegexPatternSet_changePatterns(t *testing.T) { testAccCheckAWSWafRegionalRegexPatternSetExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", patternSetName), resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.#", "3"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.3351840846", "two"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.2929247714", "three"), - resource.TestCheckResourceAttr(resourceName, "regex_pattern_strings.1294846542", "four"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "two"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "three"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "regex_pattern_strings.*", "four"), ), }, { diff --git a/aws/resource_aws_wafregional_rule.go b/aws/resource_aws_wafregional_rule.go index a95036cf245..4e52026fd8d 100644 --- a/aws/resource_aws_wafregional_rule.go +++ b/aws/resource_aws_wafregional_rule.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_wafregional_rule_group.go b/aws/resource_aws_wafregional_rule_group.go index a797398d2a1..79dc35afea2 100644 --- a/aws/resource_aws_wafregional_rule_group.go +++ b/aws/resource_aws_wafregional_rule_group.go @@ -8,7 +8,7 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) diff --git a/aws/resource_aws_wafregional_rule_group_test.go b/aws/resource_aws_wafregional_rule_group_test.go index ec1dbb9f9fd..a92ff205bf5 100644 --- a/aws/resource_aws_wafregional_rule_group_test.go +++ b/aws/resource_aws_wafregional_rule_group_test.go @@ -9,9 +9,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -70,10 +71,9 @@ func TestAccAWSWafRegionalRuleGroup_basic(t *testing.T) { resourceName := "aws_wafregional_rule_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalRuleGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalRuleGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalRuleGroupConfig(ruleName, groupName), @@ -85,9 +85,11 @@ func TestAccAWSWafRegionalRuleGroup_basic(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "activated_rule.#", "1"), resource.TestCheckResourceAttr(resourceName, "metric_name", groupName), computeWafActivatedRuleWithRuleId(&rule, "COUNT", 50, &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.action.0.type", &idx, "COUNT"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.priority", &idx, "50"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.type", &idx, waf.WafRuleTypeRegular), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "activated_rule.*", map[string]string{ + "action.0.type": "COUNT", + "priority": "50", + "type": waf.WafRuleTypeRegular, + }), ), }, { @@ -224,10 +226,9 @@ func TestAccAWSWafRegionalRuleGroup_changeActivatedRules(t *testing.T) { resourceName := "aws_wafregional_rule_group.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalRuleGroupDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalRuleGroupDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalRuleGroupConfig(ruleName1, groupName), @@ -237,9 +238,11 @@ func TestAccAWSWafRegionalRuleGroup_changeActivatedRules(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", groupName), resource.TestCheckResourceAttr(resourceName, "activated_rule.#", "1"), computeWafActivatedRuleWithRuleId(&rule0, "COUNT", 50, &idx0), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.action.0.type", &idx0, "COUNT"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.priority", &idx0, "50"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.type", &idx0, waf.WafRuleTypeRegular), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "activated_rule.*", map[string]string{ + "action.0.type": "COUNT", + "priority": "50", + "type": waf.WafRuleTypeRegular, + }), ), }, { @@ -251,21 +254,27 @@ func TestAccAWSWafRegionalRuleGroup_changeActivatedRules(t *testing.T) { testAccCheckAWSWafRegionalRuleExists("aws_wafregional_rule.test", &rule1), computeWafActivatedRuleWithRuleId(&rule1, "BLOCK", 10, &idx1), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.action.0.type", &idx1, "BLOCK"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.priority", &idx1, "10"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.type", &idx1, waf.WafRuleTypeRegular), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "activated_rule.*", map[string]string{ + "action.0.type": "BLOCK", + "priority": "10", + "type": waf.WafRuleTypeRegular, + }), testAccCheckAWSWafRegionalRuleExists("aws_wafregional_rule.test2", &rule2), computeWafActivatedRuleWithRuleId(&rule2, "COUNT", 1, &idx2), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.action.0.type", &idx2, "COUNT"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.priority", &idx2, "1"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.type", &idx2, waf.WafRuleTypeRegular), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "activated_rule.*", map[string]string{ + "action.0.type": "COUNT", + "priority": "1", + "type": waf.WafRuleTypeRegular, + }), testAccCheckAWSWafRegionalRuleExists("aws_wafregional_rule.test3", &rule3), computeWafActivatedRuleWithRuleId(&rule3, "BLOCK", 15, &idx3), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.action.0.type", &idx3, "BLOCK"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.priority", &idx3, "15"), - testCheckResourceAttrWithIndexesAddr(resourceName, "activated_rule.%d.type", &idx3, waf.WafRuleTypeRegular), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "activated_rule.*", map[string]string{ + "action.0.type": "BLOCK", + "priority": "15", + "type": waf.WafRuleTypeRegular, + }), ), }, { diff --git a/aws/resource_aws_wafregional_rule_test.go b/aws/resource_aws_wafregional_rule_test.go index f1886c6fc69..a43808b50aa 100644 --- a/aws/resource_aws_wafregional_rule_test.go +++ b/aws/resource_aws_wafregional_rule_test.go @@ -9,10 +9,11 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func init() { @@ -287,10 +288,9 @@ func TestAccAWSWafRegionalRule_changePredicates(t *testing.T) { resourceName := "aws_wafregional_rule.wafrule" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRuleDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRuleDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalRuleConfig(ruleName), @@ -300,8 +300,10 @@ func TestAccAWSWafRegionalRule_changePredicates(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", ruleName), resource.TestCheckResourceAttr(resourceName, "predicate.#", "1"), computeWafRegionalRulePredicate(&ipset.IPSetId, false, "IPMatch", &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicate.%d.negated", &idx, "false"), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicate.%d.type", &idx, "IPMatch"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "predicate.*", map[string]string{ + "negated": "false", + "type": "IPMatch", + }), ), }, { @@ -312,11 +314,15 @@ func TestAccAWSWafRegionalRule_changePredicates(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", ruleName), resource.TestCheckResourceAttr(resourceName, "predicate.#", "2"), computeWafRegionalRulePredicate(&xssMatchSet.XssMatchSetId, true, "XssMatch", &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicate.%d.negated", &idx, "true"), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicate.%d.type", &idx, "XssMatch"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "predicate.*", map[string]string{ + "negated": "true", + "type": "XssMatch", + }), computeWafRegionalRulePredicate(&ipset.IPSetId, true, "IPMatch", &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicate.%d.negated", &idx, "true"), - testCheckResourceAttrWithIndexesAddr(resourceName, "predicate.%d.type", &idx, "IPMatch"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "predicate.*", map[string]string{ + "negated": "true", + "type": "IPMatch", + }), ), }, { diff --git a/aws/resource_aws_wafregional_size_constraint_set.go b/aws/resource_aws_wafregional_size_constraint_set.go index 3d97749a328..07283acddc8 100644 --- a/aws/resource_aws_wafregional_size_constraint_set.go +++ b/aws/resource_aws_wafregional_size_constraint_set.go @@ -7,7 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafRegionalSizeConstraintSet() *schema.Resource { diff --git a/aws/resource_aws_wafregional_size_constraint_set_test.go b/aws/resource_aws_wafregional_size_constraint_set_test.go index e7829d64d33..c85360a6b4a 100644 --- a/aws/resource_aws_wafregional_size_constraint_set_test.go +++ b/aws/resource_aws_wafregional_size_constraint_set_test.go @@ -4,13 +4,14 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" ) func TestAccAWSWafRegionalSizeConstraintSet_basic(t *testing.T) { @@ -19,10 +20,9 @@ func TestAccAWSWafRegionalSizeConstraintSet_basic(t *testing.T) { resourceName := "aws_wafregional_size_constraint_set.size_constraint_set" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalSizeConstraintSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalSizeConstraintSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalSizeConstraintSetConfig(sizeConstraintSet), @@ -32,18 +32,16 @@ func TestAccAWSWafRegionalSizeConstraintSet_basic(t *testing.T) { resourceName, "name", sizeConstraintSet), resource.TestCheckResourceAttr( resourceName, "size_constraints.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.comparison_operator", "EQ"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.field_to_match.281401076.data", ""), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.field_to_match.281401076.type", "BODY"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.size", "4096"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*", map[string]string{ + "comparison_operator": "EQ", + "field_to_match.#": "1", + "size": "4096", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*.field_to_match.*", map[string]string{ + "data": "", + "type": "BODY", + }), ), }, { @@ -123,10 +121,9 @@ func TestAccAWSWafRegionalSizeConstraintSet_changeConstraints(t *testing.T) { resourceName := "aws_wafregional_size_constraint_set.size_constraint_set" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalSizeConstraintSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalSizeConstraintSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalSizeConstraintSetConfig(setName), @@ -136,18 +133,16 @@ func TestAccAWSWafRegionalSizeConstraintSet_changeConstraints(t *testing.T) { resourceName, "name", setName), resource.TestCheckResourceAttr( resourceName, "size_constraints.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.comparison_operator", "EQ"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.field_to_match.281401076.data", ""), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.field_to_match.281401076.type", "BODY"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.size", "4096"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.2029852522.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*", map[string]string{ + "comparison_operator": "EQ", + "field_to_match.#": "1", + "size": "4096", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*.field_to_match.*", map[string]string{ + "data": "", + "type": "BODY", + }), ), }, { @@ -158,18 +153,16 @@ func TestAccAWSWafRegionalSizeConstraintSet_changeConstraints(t *testing.T) { resourceName, "name", setName), resource.TestCheckResourceAttr( resourceName, "size_constraints.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.3222308386.comparison_operator", "GE"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.3222308386.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.3222308386.field_to_match.281401076.data", ""), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.3222308386.field_to_match.281401076.type", "BODY"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.3222308386.size", "1024"), - resource.TestCheckResourceAttr( - resourceName, "size_constraints.3222308386.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*", map[string]string{ + "comparison_operator": "GE", + "field_to_match.#": "1", + "size": "1024", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "size_constraints.*.field_to_match.*", map[string]string{ + "data": "", + "type": "BODY", + }), ), }, { diff --git a/aws/resource_aws_wafregional_sql_injection_match_set.go b/aws/resource_aws_wafregional_sql_injection_match_set.go index c5f7369b459..25df03a43fb 100644 --- a/aws/resource_aws_wafregional_sql_injection_match_set.go +++ b/aws/resource_aws_wafregional_sql_injection_match_set.go @@ -9,8 +9,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func resourceAwsWafRegionalSqlInjectionMatchSet() *schema.Resource { diff --git a/aws/resource_aws_wafregional_sql_injection_match_set_test.go b/aws/resource_aws_wafregional_sql_injection_match_set_test.go index 0a9ead72933..759925cb97f 100644 --- a/aws/resource_aws_wafregional_sql_injection_match_set_test.go +++ b/aws/resource_aws_wafregional_sql_injection_match_set_test.go @@ -7,9 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSWafRegionalSqlInjectionMatchSet_basic(t *testing.T) { @@ -18,10 +19,9 @@ func TestAccAWSWafRegionalSqlInjectionMatchSet_basic(t *testing.T) { sqlInjectionMatchSet := fmt.Sprintf("sqlInjectionMatchSet-%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalSqlInjectionMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalSqlInjectionMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalSqlInjectionMatchSetConfig(sqlInjectionMatchSet), @@ -29,16 +29,12 @@ func TestAccAWSWafRegionalSqlInjectionMatchSet_basic(t *testing.T) { testAccCheckAWSWafRegionalSqlInjectionMatchSetExists(resourceName, &v), resource.TestCheckResourceAttr( resourceName, "name", sqlInjectionMatchSet), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.1913782288.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.1913782288.field_to_match.0.data", ""), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.1913782288.field_to_match.0.type", "QUERY_STRING"), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.1913782288.text_transformation", "URL_DECODE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "sql_injection_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "QUERY_STRING", + "text_transformation": "URL_DECODE", + }), ), }, { @@ -118,10 +114,9 @@ func TestAccAWSWafRegionalSqlInjectionMatchSet_changeTuples(t *testing.T) { setName := fmt.Sprintf("sqlInjectionMatchSet-%s", acctest.RandString(5)) resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalSqlInjectionMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalSqlInjectionMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalSqlInjectionMatchSetConfig(setName), @@ -131,14 +126,12 @@ func TestAccAWSWafRegionalSqlInjectionMatchSet_changeTuples(t *testing.T) { resourceName, "name", setName), resource.TestCheckResourceAttr( resourceName, "sql_injection_match_tuple.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.1913782288.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.1913782288.field_to_match.0.data", ""), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.1913782288.field_to_match.0.type", "QUERY_STRING"), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.1913782288.text_transformation", "URL_DECODE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "sql_injection_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "QUERY_STRING", + "text_transformation": "URL_DECODE", + }), ), }, { @@ -149,14 +142,12 @@ func TestAccAWSWafRegionalSqlInjectionMatchSet_changeTuples(t *testing.T) { resourceName, "name", setName), resource.TestCheckResourceAttr( resourceName, "sql_injection_match_tuple.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.3961339938.field_to_match.#", "1"), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.3961339938.field_to_match.0.data", "user-agent"), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.3961339938.field_to_match.0.type", "HEADER"), - resource.TestCheckResourceAttr( - resourceName, "sql_injection_match_tuple.3961339938.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "sql_injection_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "user-agent", + "field_to_match.0.type": "HEADER", + "text_transformation": "NONE", + }), ), }, { diff --git a/aws/resource_aws_wafregional_web_acl.go b/aws/resource_aws_wafregional_web_acl.go index 96b7db8d928..45d8355d15d 100644 --- a/aws/resource_aws_wafregional_web_acl.go +++ b/aws/resource_aws_wafregional_web_acl.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws/arn" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -323,7 +323,7 @@ func resourceAwsWafRegionalWebAclUpdate(d *schema.ResourceData, meta interface{} conn := meta.(*AWSClient).wafregionalconn region := meta.(*AWSClient).region - if d.HasChange("default_action") || d.HasChange("rule") { + if d.HasChanges("default_action", "rule") { o, n := d.GetChange("rule") oldR, newR := o.(*schema.Set).List(), n.(*schema.Set).List() diff --git a/aws/resource_aws_wafregional_web_acl_association.go b/aws/resource_aws_wafregional_web_acl_association.go index c7814f654e4..7eb56bd3bc2 100644 --- a/aws/resource_aws_wafregional_web_acl_association.go +++ b/aws/resource_aws_wafregional_web_acl_association.go @@ -8,8 +8,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func resourceAwsWafRegionalWebAclAssociation() *schema.Resource { @@ -78,7 +78,7 @@ func resourceAwsWafRegionalWebAclAssociationCreate(d *schema.ResourceData, meta func resourceAwsWafRegionalWebAclAssociationRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).wafregionalconn - _, resourceArn := resourceAwsWafRegionalWebAclAssociationParseId(d.Id()) + resourceArn := resourceAwsWafRegionalWebAclAssociationParseId(d.Id()) input := &wafregional.GetWebACLForResourceInput{ ResourceArn: aws.String(resourceArn), @@ -111,7 +111,7 @@ func resourceAwsWafRegionalWebAclAssociationRead(d *schema.ResourceData, meta in func resourceAwsWafRegionalWebAclAssociationDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).wafregionalconn - _, resourceArn := resourceAwsWafRegionalWebAclAssociationParseId(d.Id()) + resourceArn := resourceAwsWafRegionalWebAclAssociationParseId(d.Id()) log.Printf("[INFO] Deleting WAF Regional Web ACL association: %s", resourceArn) @@ -124,9 +124,8 @@ func resourceAwsWafRegionalWebAclAssociationDelete(d *schema.ResourceData, meta return err } -func resourceAwsWafRegionalWebAclAssociationParseId(id string) (webAclId, resourceArn string) { +func resourceAwsWafRegionalWebAclAssociationParseId(id string) (resourceArn string) { parts := strings.SplitN(id, ":", 2) - webAclId = parts[0] resourceArn = parts[1] return } diff --git a/aws/resource_aws_wafregional_web_acl_association_test.go b/aws/resource_aws_wafregional_web_acl_association_test.go index c2836645abe..0c4d2ff30c7 100644 --- a/aws/resource_aws_wafregional_web_acl_association_test.go +++ b/aws/resource_aws_wafregional_web_acl_association_test.go @@ -4,9 +4,9 @@ import ( "fmt" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/wafregional" @@ -109,7 +109,7 @@ func testAccCheckWafRegionalWebAclAssociationDestroy(s *terraform.State) error { continue } - _, resourceArn := resourceAwsWafRegionalWebAclAssociationParseId(rs.Primary.ID) + resourceArn := resourceAwsWafRegionalWebAclAssociationParseId(rs.Primary.ID) input := &wafregional.GetWebACLForResourceInput{ ResourceArn: aws.String(resourceArn), @@ -142,7 +142,7 @@ func testAccCheckWafRegionalWebAclAssociationExists(n string) resource.TestCheck return fmt.Errorf("No WebACL association ID is set") } - _, resourceArn := resourceAwsWafRegionalWebAclAssociationParseId(rs.Primary.ID) + resourceArn := resourceAwsWafRegionalWebAclAssociationParseId(rs.Primary.ID) conn := testAccProvider.Meta().(*AWSClient).wafregionalconn @@ -169,7 +169,7 @@ func testAccCheckWafRegionalWebAclAssociationDisappears(resourceName string) res return fmt.Errorf("No WebACL association ID is set") } - _, resourceArn := resourceAwsWafRegionalWebAclAssociationParseId(rs.Primary.ID) + resourceArn := resourceAwsWafRegionalWebAclAssociationParseId(rs.Primary.ID) conn := testAccProvider.Meta().(*AWSClient).wafregionalconn diff --git a/aws/resource_aws_wafregional_web_acl_test.go b/aws/resource_aws_wafregional_web_acl_test.go index 01ac022d639..746d659a849 100644 --- a/aws/resource_aws_wafregional_web_acl_test.go +++ b/aws/resource_aws_wafregional_web_acl_test.go @@ -6,14 +6,15 @@ import ( "regexp" "testing" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" ) func init() { @@ -395,10 +396,9 @@ func TestAccAWSWafRegionalWebAcl_changeRules(t *testing.T) { resourceName := "aws_wafregional_web_acl.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalWebAclDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalWebAclDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalWebAclConfig(wafAclName), @@ -410,7 +410,9 @@ func TestAccAWSWafRegionalWebAcl_changeRules(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "name", wafAclName), resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), computeWafRegionalWebAclRuleIndex(&r.RuleId, 1, "REGULAR", "BLOCK", &idx), - testCheckResourceAttrWithIndexesAddr(resourceName, "rule.%d.priority", &idx, "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "priority": "1", + }), ), }, { diff --git a/aws/resource_aws_wafregional_xss_match_set.go b/aws/resource_aws_wafregional_xss_match_set.go index 568cf62d0a5..6e294b785ad 100644 --- a/aws/resource_aws_wafregional_xss_match_set.go +++ b/aws/resource_aws_wafregional_xss_match_set.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsWafRegionalXssMatchSet() *schema.Resource { diff --git a/aws/resource_aws_wafregional_xss_match_set_test.go b/aws/resource_aws_wafregional_xss_match_set_test.go index 16e212a0679..672193462a2 100644 --- a/aws/resource_aws_wafregional_xss_match_set_test.go +++ b/aws/resource_aws_wafregional_xss_match_set_test.go @@ -7,9 +7,10 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/wafregional" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" ) func TestAccAWSWafRegionalXssMatchSet_basic(t *testing.T) { @@ -18,10 +19,9 @@ func TestAccAWSWafRegionalXssMatchSet_basic(t *testing.T) { resourceName := "aws_wafregional_xss_match_set.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalXssMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalXssMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalXssMatchSetConfig(rName), @@ -29,14 +29,18 @@ func TestAccAWSWafRegionalXssMatchSet_basic(t *testing.T) { testAccCheckAWSWafRegionalXssMatchSetExists(resourceName, &v), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.#", "2"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.599421078.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.599421078.field_to_match.0.data", ""), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.599421078.field_to_match.0.type", "QUERY_STRING"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.599421078.text_transformation", "NONE"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.41660541.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.41660541.field_to_match.0.data", ""), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.41660541.field_to_match.0.type", "URI"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.41660541.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "QUERY_STRING", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "URI", + "text_transformation": "NONE", + }), ), }, { @@ -112,10 +116,9 @@ func TestAccAWSWafRegionalXssMatchSet_changeTuples(t *testing.T) { resourceName := "aws_wafregional_xss_match_set.test" resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckAWSWafRegionalXssMatchSetDestroy, - DisableBinaryDriver: true, + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafRegionalXssMatchSetDestroy, Steps: []resource.TestStep{ { Config: testAccAWSWafRegionalXssMatchSetConfig(rName), @@ -123,14 +126,18 @@ func TestAccAWSWafRegionalXssMatchSet_changeTuples(t *testing.T) { testAccCheckAWSWafRegionalXssMatchSetExists(resourceName, &before), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.#", "2"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.599421078.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.599421078.field_to_match.0.data", ""), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.599421078.field_to_match.0.type", "QUERY_STRING"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.599421078.text_transformation", "NONE"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.41660541.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.41660541.field_to_match.0.data", ""), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.41660541.field_to_match.0.type", "URI"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.41660541.text_transformation", "NONE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "QUERY_STRING", + "text_transformation": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "URI", + "text_transformation": "NONE", + }), ), }, { @@ -144,14 +151,18 @@ func TestAccAWSWafRegionalXssMatchSet_changeTuples(t *testing.T) { testAccCheckAWSWafRegionalXssMatchSetExists(resourceName, &after), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.#", "2"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.42378128.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.42378128.field_to_match.0.data", "GET"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.42378128.field_to_match.0.type", "METHOD"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.42378128.text_transformation", "HTML_ENTITY_DECODE"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.3815294338.field_to_match.#", "1"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.3815294338.field_to_match.0.data", ""), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.3815294338.field_to_match.0.type", "BODY"), - resource.TestCheckResourceAttr(resourceName, "xss_match_tuple.3815294338.text_transformation", "CMD_LINE"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "GET", + "field_to_match.0.type": "METHOD", + "text_transformation": "HTML_ENTITY_DECODE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "xss_match_tuple.*", map[string]string{ + "field_to_match.#": "1", + "field_to_match.0.data": "", + "field_to_match.0.type": "BODY", + "text_transformation": "CMD_LINE", + }), ), }, }, diff --git a/aws/resource_aws_wafv2_ip_set.go b/aws/resource_aws_wafv2_ip_set.go new file mode 100644 index 00000000000..1eceaf0e4ce --- /dev/null +++ b/aws/resource_aws_wafv2_ip_set.go @@ -0,0 +1,262 @@ +package aws + +import ( + "fmt" + "log" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" +) + +func resourceAwsWafv2IPSet() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsWafv2IPSetCreate, + Read: resourceAwsWafv2IPSetRead, + Update: resourceAwsWafv2IPSetUpdate, + Delete: resourceAwsWafv2IPSetDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + idParts := strings.Split(d.Id(), "/") + if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { + return nil, fmt.Errorf("Unexpected format of ID (%q), expected ID/NAME/SCOPE", d.Id()) + } + id := idParts[0] + name := idParts[1] + scope := idParts[2] + d.SetId(id) + d.Set("name", name) + d.Set("scope", scope) + return []*schema.ResourceData{d}, nil + }, + }, + + Schema: map[string]*schema.Schema{ + "addresses": { + Type: schema.TypeSet, + Optional: true, + MaxItems: 10000, + Elem: &schema.Schema{Type: schema.TypeString}, + DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool { + o, n := d.GetChange("addresses") + oldAddresses := o.(*schema.Set).List() + newAddresses := n.(*schema.Set).List() + if len(oldAddresses) == len(newAddresses) { + for _, ov := range oldAddresses { + hasAddress := false + for _, nv := range newAddresses { + if cidrBlocksEqual(ov.(string), nv.(string)) { + hasAddress = true + break + } + } + if !hasAddress { + return false + } + } + return true + } + return false + }, + }, + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(1, 256), + }, + "ip_address_version": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + wafv2.IPAddressVersionIpv4, + wafv2.IPAddressVersionIpv6, + }, false), + }, + "lock_token": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + "scope": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + wafv2.ScopeCloudfront, + wafv2.ScopeRegional, + }, false), + }, + "tags": tagsSchema(), + }, + } +} + +func resourceAwsWafv2IPSetCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + params := &wafv2.CreateIPSetInput{ + Addresses: aws.StringSlice([]string{}), + IPAddressVersion: aws.String(d.Get("ip_address_version").(string)), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + } + + if v, ok := d.GetOk("addresses"); ok && v.(*schema.Set).Len() > 0 { + params.Addresses = expandStringSet(v.(*schema.Set)) + } + + if v, ok := d.GetOk("description"); ok { + params.Description = aws.String(v.(string)) + } + + if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { + params.Tags = keyvaluetags.New(v).IgnoreAws().Wafv2Tags() + } + + resp, err := conn.CreateIPSet(params) + + if err != nil { + return fmt.Errorf("Error creating WAFv2 IPSet: %s", err) + } + + if resp == nil || resp.Summary == nil { + return fmt.Errorf("Error creating WAFv2 IPSet") + } + + d.SetId(aws.StringValue(resp.Summary.Id)) + + return resourceAwsWafv2IPSetRead(d, meta) +} + +func resourceAwsWafv2IPSetRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + + params := &wafv2.GetIPSetInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + } + + resp, err := conn.GetIPSet(params) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFNonexistentItemException, "") { + log.Printf("[WARN] WAFv2 IPSet (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + return err + } + + if resp == nil || resp.IPSet == nil { + return fmt.Errorf("Error reading WAFv2 IPSet") + } + + d.Set("name", aws.StringValue(resp.IPSet.Name)) + d.Set("description", aws.StringValue(resp.IPSet.Description)) + d.Set("ip_address_version", aws.StringValue(resp.IPSet.IPAddressVersion)) + d.Set("arn", aws.StringValue(resp.IPSet.ARN)) + d.Set("lock_token", aws.StringValue(resp.LockToken)) + + if err := d.Set("addresses", flattenStringSet(resp.IPSet.Addresses)); err != nil { + return fmt.Errorf("Error setting addresses: %s", err) + } + + arn := aws.StringValue(resp.IPSet.ARN) + tags, err := keyvaluetags.Wafv2ListTags(conn, arn) + if err != nil { + return fmt.Errorf("Error listing tags for WAFv2 IpSet (%s): %s", arn, err) + } + + if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("Error setting tags: %s", err) + } + + return nil +} + +func resourceAwsWafv2IPSetUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + + log.Printf("[INFO] Updating WAFv2 IPSet %s", d.Id()) + + params := &wafv2.UpdateIPSetInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + Addresses: aws.StringSlice([]string{}), + LockToken: aws.String(d.Get("lock_token").(string)), + } + + if v, ok := d.GetOk("addresses"); ok && v.(*schema.Set).Len() > 0 { + params.Addresses = expandStringSet(v.(*schema.Set)) + } + + if v, ok := d.GetOk("description"); ok && len(v.(string)) > 0 { + params.Description = aws.String(v.(string)) + } + + _, err := conn.UpdateIPSet(params) + + if err != nil { + return fmt.Errorf("Error updating WAFv2 IPSet: %s", err) + } + + if d.HasChange("tags") { + o, n := d.GetChange("tags") + if err := keyvaluetags.Wafv2UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("Error updating tags: %s", err) + } + } + + return resourceAwsWafv2IPSetRead(d, meta) +} + +func resourceAwsWafv2IPSetDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + + log.Printf("[INFO] Deleting WAFv2 IPSet %s", d.Id()) + + params := &wafv2.DeleteIPSetInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + LockToken: aws.String(d.Get("lock_token").(string)), + } + + err := resource.Retry(5*time.Minute, func() *resource.RetryError { + var err error + _, err = conn.DeleteIPSet(params) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFAssociatedItemException, "") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.DeleteIPSet(params) + } + + if err != nil { + return fmt.Errorf("Error deleting WAFv2 IPSet: %s", err) + } + + return nil +} diff --git a/aws/resource_aws_wafv2_ip_set_test.go b/aws/resource_aws_wafv2_ip_set_test.go new file mode 100644 index 00000000000..c0ccfef127d --- /dev/null +++ b/aws/resource_aws_wafv2_ip_set_test.go @@ -0,0 +1,461 @@ +package aws + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" +) + +func TestAccAwsWafv2IPSet_basic(t *testing.T) { + var v wafv2.IPSet + ipSetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + resourceName := "aws_wafv2_ip_set.ip_set" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2IPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2IPSetConfig(ipSetName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2IPSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/ipset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", ipSetName), + resource.TestCheckResourceAttr(resourceName, "description", ipSetName), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "ip_address_version", wafv2.IPAddressVersionIpv4), + resource.TestCheckResourceAttr(resourceName, "addresses.#", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"), + ), + }, + { + Config: testAccAwsWafv2IPSetConfigUpdate(ipSetName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2IPSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/ipset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", ipSetName), + resource.TestCheckResourceAttr(resourceName, "description", "Updated"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "ip_address_version", wafv2.IPAddressVersionIpv4), + resource.TestCheckResourceAttr(resourceName, "addresses.#", "3"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAWSWafv2IPSetImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2IPSet_Disappears(t *testing.T) { + var r wafv2.IPSet + ipSetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + resourceName := "aws_wafv2_ip_set.ip_set" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2IPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2IPSetConfig(ipSetName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2IPSetExists(resourceName, &r), + testAccCheckResourceDisappears(testAccProvider, resourceAwsWafv2IPSet(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAwsWafv2IPSet_IPv6(t *testing.T) { + var v wafv2.IPSet + ipSetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + resourceName := "aws_wafv2_ip_set.ip_set" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2IPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2IPSetConfigIPv6(ipSetName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2IPSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/ipset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", ipSetName), + resource.TestCheckResourceAttr(resourceName, "description", ipSetName), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "ip_address_version", wafv2.IPAddressVersionIpv6), + resource.TestCheckResourceAttr(resourceName, "addresses.#", "3"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "addresses.*", "1234:5678:9abc:6811:0000:0000:0000:0000/64"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "addresses.*", "2001:db8::/32"), + tfawsresource.TestCheckTypeSetElemAttr(resourceName, "addresses.*", "1111:0000:0000:0000:0000:0000:0000:0111/128"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAWSWafv2IPSetImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2IPSet_Minimal(t *testing.T) { + var v wafv2.IPSet + ipSetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + resourceName := "aws_wafv2_ip_set.ip_set" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2IPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2IPSetConfigMinimal(ipSetName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2IPSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/ipset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", ipSetName), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "ip_address_version", wafv2.IPAddressVersionIpv4), + resource.TestCheckResourceAttr(resourceName, "addresses.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAWSWafv2IPSetImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2IPSet_ChangeNameForceNew(t *testing.T) { + var before, after wafv2.IPSet + ipSetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + ipSetNewName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + resourceName := "aws_wafv2_ip_set.ip_set" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2IPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2IPSetConfig(ipSetName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2IPSetExists(resourceName, &before), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/ipset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", ipSetName), + resource.TestCheckResourceAttr(resourceName, "description", ipSetName), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "ip_address_version", wafv2.IPAddressVersionIpv4), + resource.TestCheckResourceAttr(resourceName, "addresses.#", "2"), + ), + }, + { + Config: testAccAwsWafv2IPSetConfig(ipSetNewName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2IPSetExists(resourceName, &after), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/ipset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", ipSetNewName), + resource.TestCheckResourceAttr(resourceName, "description", ipSetNewName), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "ip_address_version", wafv2.IPAddressVersionIpv4), + resource.TestCheckResourceAttr(resourceName, "addresses.#", "2"), + ), + }, + }, + }) +} + +func TestAccAwsWafv2IPSet_Tags(t *testing.T) { + var v wafv2.IPSet + ipSetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + resourceName := "aws_wafv2_ip_set.ip_set" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2IPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2IPSetConfigOneTag(ipSetName, "Tag1", "Value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2IPSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/ipset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAWSWafv2IPSetImportStateIdFunc(resourceName), + }, + { + Config: testAccAwsWafv2IPSetConfigTwoTags(ipSetName, "Tag1", "Value1Updated", "Tag2", "Value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2IPSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/ipset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1Updated"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"), + ), + }, + { + Config: testAccAwsWafv2IPSetConfigOneTag(ipSetName, "Tag2", "Value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2IPSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/ipset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"), + ), + }, + }, + }) +} + +func TestAccAwsWafv2IPSet_Large(t *testing.T) { + var v wafv2.IPSet + ipSetName := fmt.Sprintf("ip-set-%s", acctest.RandString(5)) + resourceName := "aws_wafv2_ip_set.ip_set" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2IPSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2IPSetConfigLarge(ipSetName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2IPSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/ipset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", ipSetName), + resource.TestCheckResourceAttr(resourceName, "description", ipSetName), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "ip_address_version", wafv2.IPAddressVersionIpv4), + resource.TestCheckResourceAttr(resourceName, "addresses.#", "50"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAWSWafv2IPSetImportStateIdFunc(resourceName), + }, + }, + }) +} + +func testAccCheckAWSWafv2IPSetDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_wafv2_ip_set" { + continue + } + + conn := testAccProvider.Meta().(*AWSClient).wafv2conn + resp, err := conn.GetIPSet( + &wafv2.GetIPSetInput{ + Id: aws.String(rs.Primary.ID), + Name: aws.String(rs.Primary.Attributes["name"]), + Scope: aws.String(rs.Primary.Attributes["scope"]), + }) + + if err == nil { + if resp == nil || resp.IPSet == nil { + return fmt.Errorf("Error getting WAFv2 IPSet") + } + if aws.StringValue(resp.IPSet.Id) == rs.Primary.ID { + return fmt.Errorf("WAFv2 IPSet %s still exists", rs.Primary.ID) + } + return nil + } + + // Return nil if the IPSet is already destroyed + if isAWSErr(err, wafv2.ErrCodeWAFNonexistentItemException, "") { + return nil + } + + return err + } + + return nil +} + +func testAccCheckAWSWafv2IPSetExists(n string, v *wafv2.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 WAFv2 IPSet ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).wafv2conn + resp, err := conn.GetIPSet(&wafv2.GetIPSetInput{ + Id: aws.String(rs.Primary.ID), + Name: aws.String(rs.Primary.Attributes["name"]), + Scope: aws.String(rs.Primary.Attributes["scope"]), + }) + + if err != nil { + return err + } + + if resp == nil || resp.IPSet == nil { + return fmt.Errorf("Error getting WAFv2 IPSet") + } + + if aws.StringValue(resp.IPSet.Id) == rs.Primary.ID { + *v = *resp.IPSet + return nil + } + + return fmt.Errorf("WAFv2 IPSet (%s) not found", rs.Primary.ID) + } +} + +func testAccAwsWafv2IPSetConfig(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_ip_set" "ip_set" { + name = "%s" + description = "%s" + scope = "REGIONAL" + ip_address_version = "IPV4" + addresses = ["1.2.3.4/32", "5.6.7.8/32"] + + tags = { + Tag1 = "Value1" + Tag2 = "Value2" + } +} +`, name, name) +} + +func testAccAwsWafv2IPSetConfigUpdate(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_ip_set" "ip_set" { + name = "%s" + description = "Updated" + scope = "REGIONAL" + ip_address_version = "IPV4" + addresses = ["1.1.1.1/32", "2.2.2.2/32", "3.3.3.3/32"] +} +`, name) +} + +func testAccAwsWafv2IPSetConfigIPv6(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_ip_set" "ip_set" { + name = "%s" + description = "%s" + scope = "REGIONAL" + ip_address_version = "IPV6" + addresses = [ + "1111:0000:0000:0000:0000:0000:0000:0111/128", + "1234:5678:9abc:6811:0000:0000:0000:0000/64", + "2001:db8::/32" + ] +} +`, name, name) +} + +func testAccAwsWafv2IPSetConfigMinimal(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_ip_set" "ip_set" { + name = "%s" + scope = "REGIONAL" + ip_address_version = "IPV4" +} +`, name) +} + +func testAccAwsWafv2IPSetConfigOneTag(name, tagKey, tagValue string) string { + return fmt.Sprintf(` +resource "aws_wafv2_ip_set" "ip_set" { + name = "%s" + description = "%s" + scope = "REGIONAL" + ip_address_version = "IPV4" + addresses = ["1.2.3.4/32", "5.6.7.8/32"] + + tags = { + "%s" = "%s" + } +} +`, name, name, tagKey, tagValue) +} + +func testAccAwsWafv2IPSetConfigTwoTags(name, tag1Key, tag1Value, tag2Key, tag2Value string) string { + return fmt.Sprintf(` +resource "aws_wafv2_ip_set" "ip_set" { + name = "%s" + description = "%s" + scope = "REGIONAL" + ip_address_version = "IPV4" + addresses = ["1.2.3.4/32", "5.6.7.8/32"] + + tags = { + "%s" = "%s" + "%s" = "%s" + } +} +`, name, name, tag1Key, tag1Value, tag2Key, tag2Value) +} + +func testAccAwsWafv2IPSetConfigLarge(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_ip_set" "ip_set" { + name = "%s" + description = "%s" + scope = "REGIONAL" + ip_address_version = "IPV4" + addresses = [ + "1.1.1.50/32", "1.1.1.73/32", "1.1.1.15/32", "2.2.2.30/32", "1.1.1.38/32", + "2.2.2.53/32", "1.1.1.21/32", "2.2.2.24/32", "1.1.1.44/32", "1.1.1.1/32", + "1.1.1.67/32", "2.2.2.76/32", "2.2.2.99/32", "1.1.1.26/32", "2.2.2.93/32", + "2.2.2.64/32", "1.1.1.32/32", "2.2.2.12/32", "2.2.2.47/32", "1.1.1.91/32", + "1.1.1.78/32", "2.2.2.82/32", "2.2.2.58/32", "1.1.1.85/32", "2.2.2.4/32", + "2.2.2.65/32", "2.2.2.23/32", "2.2.2.17/32", "2.2.2.42/32", "1.1.1.56/32", + "1.1.1.79/32", "2.2.2.81/32", "2.2.2.36/32", "2.2.2.59/32", "2.2.2.9/32", + "1.1.1.7/32", "1.1.1.84/32", "1.1.1.51/32", "2.2.2.70/32", "2.2.2.87/32", + "1.1.1.39/32", "1.1.1.90/32", "2.2.2.31/32", "1.1.1.62/32", "1.1.1.14/32", + "1.1.1.20/32", "2.2.2.25/32", "1.1.1.45/32", "1.1.1.2/32", "2.2.2.98/32" + ] +} +`, name, name) +} + +func testAccAWSWafv2IPSetImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { + return func(s *terraform.State) (string, error) { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return "", fmt.Errorf("Not found: %s", resourceName) + } + + return fmt.Sprintf("%s/%s/%s", rs.Primary.ID, rs.Primary.Attributes["name"], rs.Primary.Attributes["scope"]), nil + } +} diff --git a/aws/resource_aws_wafv2_regex_pattern_set.go b/aws/resource_aws_wafv2_regex_pattern_set.go new file mode 100644 index 00000000000..2440ecabb9c --- /dev/null +++ b/aws/resource_aws_wafv2_regex_pattern_set.go @@ -0,0 +1,279 @@ +package aws + +import ( + "fmt" + "log" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" +) + +func resourceAwsWafv2RegexPatternSet() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsWafv2RegexPatternSetCreate, + Read: resourceAwsWafv2RegexPatternSetRead, + Update: resourceAwsWafv2RegexPatternSetUpdate, + Delete: resourceAwsWafv2RegexPatternSetDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + idParts := strings.Split(d.Id(), "/") + if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { + return nil, fmt.Errorf("Unexpected format of ID (%q), expected ID/NAME/SCOPE", d.Id()) + } + id := idParts[0] + name := idParts[1] + scope := idParts[2] + d.SetId(id) + d.Set("name", name) + d.Set("scope", scope) + return []*schema.ResourceData{d}, nil + }, + }, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(1, 256), + }, + "lock_token": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + "regular_expression": { + Type: schema.TypeSet, + Optional: true, + MaxItems: 10, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "regex_string": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 200), + }, + }, + }, + }, + "scope": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + wafv2.ScopeCloudfront, + wafv2.ScopeRegional, + }, false), + }, + "tags": tagsSchema(), + }, + } +} + +func resourceAwsWafv2RegexPatternSetCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + params := &wafv2.CreateRegexPatternSetInput{ + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + RegularExpressionList: []*wafv2.Regex{}, + } + + if v, ok := d.GetOk("description"); ok { + params.Description = aws.String(v.(string)) + } + + if v, ok := d.GetOk("regular_expression"); ok && v.(*schema.Set).Len() > 0 { + params.RegularExpressionList = expandWafv2RegexPatternSet(v.(*schema.Set).List()) + } + + if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { + params.Tags = keyvaluetags.New(v).IgnoreAws().Wafv2Tags() + } + + resp, err := conn.CreateRegexPatternSet(params) + + if err != nil { + return fmt.Errorf("Error creating WAFv2 RegexPatternSet: %s", err) + } + + if resp == nil || resp.Summary == nil { + return fmt.Errorf("Error creating WAFv2 RegexPatternSet") + } + + d.SetId(aws.StringValue(resp.Summary.Id)) + + return resourceAwsWafv2RegexPatternSetRead(d, meta) +} + +func resourceAwsWafv2RegexPatternSetRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + params := &wafv2.GetRegexPatternSetInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + } + + resp, err := conn.GetRegexPatternSet(params) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFNonexistentItemException, "") { + log.Printf("[WARN] WAFv2 RegexPatternSet (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + return err + } + + if resp == nil || resp.RegexPatternSet == nil { + return fmt.Errorf("Error getting WAFv2 RegexPatternSet") + } + + d.Set("name", aws.StringValue(resp.RegexPatternSet.Name)) + d.Set("description", aws.StringValue(resp.RegexPatternSet.Description)) + d.Set("arn", aws.StringValue(resp.RegexPatternSet.ARN)) + d.Set("lock_token", aws.StringValue(resp.LockToken)) + + if err := d.Set("regular_expression", flattenWafv2RegexPatternSet(resp.RegexPatternSet.RegularExpressionList)); err != nil { + return fmt.Errorf("Error setting regular_expression: %s", err) + } + + tags, err := keyvaluetags.Wafv2ListTags(conn, aws.StringValue(resp.RegexPatternSet.ARN)) + if err != nil { + return fmt.Errorf("Error listing tags for WAFv2 RegexPatternSet (%s): %s", aws.StringValue(resp.RegexPatternSet.ARN), err) + } + + if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("Error setting tags: %s", err) + } + + return nil +} + +func resourceAwsWafv2RegexPatternSetUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + + log.Printf("[INFO] Updating WAFv2 RegexPatternSet %s", d.Id()) + + params := &wafv2.UpdateRegexPatternSetInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + LockToken: aws.String(d.Get("lock_token").(string)), + RegularExpressionList: []*wafv2.Regex{}, + } + + if v, ok := d.GetOk("regular_expression"); ok && v.(*schema.Set).Len() > 0 { + params.RegularExpressionList = expandWafv2RegexPatternSet(v.(*schema.Set).List()) + } + + if v, ok := d.GetOk("description"); ok { + params.Description = aws.String(v.(string)) + } + + _, err := conn.UpdateRegexPatternSet(params) + + if err != nil { + return fmt.Errorf("Error updating WAFv2 RegexPatternSet: %s", err) + } + + if d.HasChange("tags") { + o, n := d.GetChange("tags") + if err := keyvaluetags.Wafv2UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("Error updating tags: %s", err) + } + } + + return resourceAwsWafv2RegexPatternSetRead(d, meta) +} + +func resourceAwsWafv2RegexPatternSetDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + + log.Printf("[INFO] Deleting WAFv2 RegexPatternSet %s", d.Id()) + params := &wafv2.DeleteRegexPatternSetInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + LockToken: aws.String(d.Get("lock_token").(string)), + } + err := resource.Retry(5*time.Minute, func() *resource.RetryError { + _, err := conn.DeleteRegexPatternSet(params) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFAssociatedItemException, "") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.DeleteRegexPatternSet(params) + } + + if err != nil { + return fmt.Errorf("Error deleting WAFv2 RegexPatternSet: %s", err) + } + + return nil +} + +func expandWafv2RegexPatternSet(l []interface{}) []*wafv2.Regex { + if len(l) == 0 || l[0] == nil { + return nil + } + + regexPatterns := make([]*wafv2.Regex, 0) + for _, regexPattern := range l { + if regexPattern == nil { + continue + } + regexPatterns = append(regexPatterns, expandWafv2Regex(regexPattern.(map[string]interface{}))) + } + + return regexPatterns +} + +func expandWafv2Regex(m map[string]interface{}) *wafv2.Regex { + if m == nil { + return nil + } + + return &wafv2.Regex{ + RegexString: aws.String(m["regex_string"].(string)), + } +} + +func flattenWafv2RegexPatternSet(r []*wafv2.Regex) interface{} { + if r == nil { + return []interface{}{} + } + + regexPatterns := make([]interface{}, 0) + + for _, regexPattern := range r { + if regexPattern == nil { + continue + } + d := map[string]interface{}{ + "regex_string": aws.StringValue(regexPattern.RegexString), + } + regexPatterns = append(regexPatterns, d) + } + + return regexPatterns +} diff --git a/aws/resource_aws_wafv2_regex_pattern_set_test.go b/aws/resource_aws_wafv2_regex_pattern_set_test.go new file mode 100644 index 00000000000..091d9b6f4ea --- /dev/null +++ b/aws/resource_aws_wafv2_regex_pattern_set_test.go @@ -0,0 +1,373 @@ +package aws + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" +) + +func TestAccAwsWafv2RegexPatternSet_basic(t *testing.T) { + var v wafv2.RegexPatternSet + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_regex_pattern_set.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RegexPatternSetConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2RegexPatternSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "description", rName), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "regular_expression.#", "2"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "regular_expression.*", map[string]string{ + "regex_string": "one", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "regular_expression.*", map[string]string{ + "regex_string": "two", + }), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + Config: testAccAwsWafv2RegexPatternSetConfig_Update(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2RegexPatternSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "description", "Updated"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "regular_expression.#", "3"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "regular_expression.*", map[string]string{ + "regex_string": "one", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "regular_expression.*", map[string]string{ + "regex_string": "two", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "regular_expression.*", map[string]string{ + "regex_string": "three", + }), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAWSWafv2RegexPatternSetImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2RegexPatternSet_Disappears(t *testing.T) { + var v wafv2.RegexPatternSet + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_regex_pattern_set.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RegexPatternSetConfig_Minimal(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2RegexPatternSetExists(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsWafv2RegexPatternSet(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAwsWafv2RegexPatternSet_Minimal(t *testing.T) { + var v wafv2.RegexPatternSet + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_regex_pattern_set.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RegexPatternSetConfig_Minimal(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2RegexPatternSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "regular_expression.#", "0"), + ), + }, + }, + }) +} + +func TestAccAwsWafv2RegexPatternSet_ChangeNameForceNew(t *testing.T) { + var before, after wafv2.RegexPatternSet + rName := acctest.RandomWithPrefix("tf-acc-test") + rNewName := fmt.Sprintf("regex-pattern-set-%s", acctest.RandString(5)) + resourceName := "aws_wafv2_regex_pattern_set.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RegexPatternSetConfig(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2RegexPatternSetExists(resourceName, &before), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", rName), + resource.TestCheckResourceAttr(resourceName, "description", rName), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "regular_expression.#", "2"), + ), + }, + { + Config: testAccAwsWafv2RegexPatternSetConfig(rNewName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2RegexPatternSetExists(resourceName, &after), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "name", rNewName), + resource.TestCheckResourceAttr(resourceName, "description", rNewName), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "regular_expression.#", "2"), + ), + }, + }, + }) +} + +func TestAccAwsWafv2RegexPatternSet_Tags(t *testing.T) { + var v wafv2.RegexPatternSet + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_regex_pattern_set.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2RegexPatternSetDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RegexPatternSetConfig_OneTag(rName, "Tag1", "Value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2RegexPatternSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAWSWafv2RegexPatternSetImportStateIdFunc(resourceName), + }, + { + Config: testAccAwsWafv2RegexPatternSetConfig_TwoTags(rName, "Tag1", "Value1Updated", "Tag2", "Value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2RegexPatternSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1Updated"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"), + ), + }, + { + Config: testAccAwsWafv2RegexPatternSetConfig_OneTag(rName, "Tag2", "Value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2RegexPatternSetExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/regexpatternset/.+$`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"), + ), + }, + }, + }) +} + +func testAccCheckAWSWafv2RegexPatternSetDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_wafv2_regex_pattern_set" { + continue + } + + conn := testAccProvider.Meta().(*AWSClient).wafv2conn + resp, err := conn.GetRegexPatternSet( + &wafv2.GetRegexPatternSetInput{ + Id: aws.String(rs.Primary.ID), + Name: aws.String(rs.Primary.Attributes["name"]), + Scope: aws.String(rs.Primary.Attributes["scope"]), + }) + + if err == nil { + if resp != nil && resp.RegexPatternSet != nil && aws.StringValue(resp.RegexPatternSet.Id) == rs.Primary.ID { + return fmt.Errorf("WAFv2 RegexPatternSet %s still exists", rs.Primary.ID) + } + return nil + } + + // Return nil if the RegexPatternSet is already destroyed + if isAWSErr(err, wafv2.ErrCodeWAFNonexistentItemException, "") { + return nil + } + + return err + } + + return nil +} + +func testAccCheckAWSWafv2RegexPatternSetExists(n string, v *wafv2.RegexPatternSet) 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 WAFv2 RegexPatternSet ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).wafv2conn + resp, err := conn.GetRegexPatternSet(&wafv2.GetRegexPatternSetInput{ + Id: aws.String(rs.Primary.ID), + Name: aws.String(rs.Primary.Attributes["name"]), + Scope: aws.String(rs.Primary.Attributes["scope"]), + }) + + if err != nil { + return err + } + + if resp == nil || resp.RegexPatternSet == nil { + return fmt.Errorf("Error getting WAFv2 RegexPatternSet for %s", rs.Primary.ID) + } + + if aws.StringValue(resp.RegexPatternSet.Id) == rs.Primary.ID { + *v = *resp.RegexPatternSet + return nil + } + + return fmt.Errorf("WAFv2 RegexPatternSet (%s) not found", rs.Primary.ID) + } +} + +func testAccAwsWafv2RegexPatternSetConfig(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_regex_pattern_set" "test" { + name = "%s" + description = "%s" + scope = "REGIONAL" + + regular_expression { + regex_string = "one" + } + + regular_expression { + regex_string = "two" + } +} +`, name, name) +} + +func testAccAwsWafv2RegexPatternSetConfig_Update(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_regex_pattern_set" "test" { + name = "%s" + description = "Updated" + scope = "REGIONAL" + + regular_expression { + regex_string = "one" + } + + regular_expression { + regex_string = "two" + } + + regular_expression { + regex_string = "three" + } +} +`, name) +} + +func testAccAwsWafv2RegexPatternSetConfig_Minimal(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_regex_pattern_set" "test" { + name = "%s" + scope = "REGIONAL" +} +`, name) +} + +func testAccAwsWafv2RegexPatternSetConfig_OneTag(name, tagKey, tagValue string) string { + return fmt.Sprintf(` +resource "aws_wafv2_regex_pattern_set" "test" { + name = "%s" + description = "%s" + scope = "REGIONAL" + + regular_expression { + regex_string = "one" + } + + regular_expression { + regex_string = "two" + } + + tags = { + "%s" = "%s" + } +} +`, name, name, tagKey, tagValue) +} + +func testAccAwsWafv2RegexPatternSetConfig_TwoTags(name, tag1Key, tag1Value, tag2Key, tag2Value string) string { + return fmt.Sprintf(` +resource "aws_wafv2_regex_pattern_set" "test" { + name = "%s" + description = "%s" + scope = "REGIONAL" + + regular_expression { + regex_string = "one" + } + + tags = { + "%s" = "%s" + "%s" = "%s" + } +} +`, name, name, tag1Key, tag1Value, tag2Key, tag2Value) +} + +func testAccAWSWafv2RegexPatternSetImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { + return func(s *terraform.State) (string, error) { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return "", fmt.Errorf("Not found: %s", resourceName) + } + + return fmt.Sprintf("%s/%s/%s", rs.Primary.ID, rs.Primary.Attributes["name"], rs.Primary.Attributes["scope"]), nil + } +} diff --git a/aws/resource_aws_wafv2_rule_group.go b/aws/resource_aws_wafv2_rule_group.go new file mode 100644 index 00000000000..b523161891a --- /dev/null +++ b/aws/resource_aws_wafv2_rule_group.go @@ -0,0 +1,297 @@ +package aws + +import ( + "fmt" + "log" + "regexp" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" +) + +func resourceAwsWafv2RuleGroup() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsWafv2RuleGroupCreate, + Read: resourceAwsWafv2RuleGroupRead, + Update: resourceAwsWafv2RuleGroupUpdate, + Delete: resourceAwsWafv2RuleGroupDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + idParts := strings.Split(d.Id(), "/") + if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { + return nil, fmt.Errorf("Unexpected format of ID (%q), expected ID/NAME/SCOPE", d.Id()) + } + id := idParts[0] + name := idParts[1] + scope := idParts[2] + d.SetId(id) + d.Set("name", name) + d.Set("scope", scope) + return []*schema.ResourceData{d}, nil + }, + }, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "capacity": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + ValidateFunc: validation.IntAtLeast(1), + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(1, 256), + }, + "lock_token": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 128), + validation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9-_]+$`), "must contain only alphanumeric hyphen and underscore characters"), + ), + }, + "scope": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + wafv2.ScopeCloudfront, + wafv2.ScopeRegional, + }, false), + }, + "rule": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "action": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "allow": wafv2EmptySchema(), + "block": wafv2EmptySchema(), + "count": wafv2EmptySchema(), + }, + }, + }, + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + "priority": { + Type: schema.TypeInt, + Required: true, + }, + "statement": wafv2RootStatementSchema(3), + "visibility_config": wafv2VisibilityConfigSchema(), + }, + }, + }, + "tags": tagsSchema(), + "visibility_config": wafv2VisibilityConfigSchema(), + }, + } +} + +func resourceAwsWafv2RuleGroupCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + var resp *wafv2.CreateRuleGroupOutput + + params := &wafv2.CreateRuleGroupInput{ + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + Capacity: aws.Int64(int64(d.Get("capacity").(int))), + Rules: expandWafv2Rules(d.Get("rule").(*schema.Set).List()), + VisibilityConfig: expandWafv2VisibilityConfig(d.Get("visibility_config").([]interface{})), + } + + if v, ok := d.GetOk("description"); ok { + params.Description = aws.String(v.(string)) + } + + if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { + params.Tags = keyvaluetags.New(v).IgnoreAws().Wafv2Tags() + } + + err := resource.Retry(5*time.Minute, func() *resource.RetryError { + var err error + resp, err = conn.CreateRuleGroup(params) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFUnavailableEntityException, "") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.CreateRuleGroup(params) + } + + if err != nil { + return fmt.Errorf("Error creating WAFv2 RuleGroup: %s", err) + } + + if resp == nil || resp.Summary == nil { + return fmt.Errorf("Error creating WAFv2 RuleGroup") + } + + d.SetId(aws.StringValue(resp.Summary.Id)) + + return resourceAwsWafv2RuleGroupRead(d, meta) +} + +func resourceAwsWafv2RuleGroupRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + + params := &wafv2.GetRuleGroupInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + } + + resp, err := conn.GetRuleGroup(params) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFNonexistentItemException, "") { + log.Printf("[WARN] WAFv2 RuleGroup (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + return err + } + + if resp == nil || resp.RuleGroup == nil { + return fmt.Errorf("Error getting WAFv2 RuleGroup") + } + + d.Set("name", aws.StringValue(resp.RuleGroup.Name)) + d.Set("capacity", aws.Int64Value(resp.RuleGroup.Capacity)) + d.Set("description", aws.StringValue(resp.RuleGroup.Description)) + d.Set("arn", aws.StringValue(resp.RuleGroup.ARN)) + d.Set("lock_token", aws.StringValue(resp.LockToken)) + + if err := d.Set("rule", flattenWafv2Rules(resp.RuleGroup.Rules)); err != nil { + return fmt.Errorf("Error setting rule: %s", err) + } + + if err := d.Set("visibility_config", flattenWafv2VisibilityConfig(resp.RuleGroup.VisibilityConfig)); err != nil { + return fmt.Errorf("Error setting visibility_config: %s", err) + } + + arn := aws.StringValue(resp.RuleGroup.ARN) + tags, err := keyvaluetags.Wafv2ListTags(conn, arn) + if err != nil { + return fmt.Errorf("Error listing tags for WAFv2 RuleGroup (%s): %s", arn, err) + } + + if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("Error setting tags: %s", err) + } + + return nil +} + +func resourceAwsWafv2RuleGroupUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + + log.Printf("[INFO] Updating WAFv2 RuleGroup %s", d.Id()) + + u := &wafv2.UpdateRuleGroupInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + LockToken: aws.String(d.Get("lock_token").(string)), + Rules: expandWafv2Rules(d.Get("rule").(*schema.Set).List()), + VisibilityConfig: expandWafv2VisibilityConfig(d.Get("visibility_config").([]interface{})), + } + + if v, ok := d.GetOk("description"); ok { + u.Description = aws.String(v.(string)) + } + + err := resource.Retry(5*time.Minute, func() *resource.RetryError { + _, err := conn.UpdateRuleGroup(u) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFUnavailableEntityException, "") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.UpdateRuleGroup(u) + } + + if err != nil { + return fmt.Errorf("Error updating WAFv2 RuleGroup: %s", err) + } + + if d.HasChange("tags") { + o, n := d.GetChange("tags") + if err := keyvaluetags.Wafv2UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("Error updating tags: %s", err) + } + } + + return resourceAwsWafv2RuleGroupRead(d, meta) +} + +func resourceAwsWafv2RuleGroupDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + + log.Printf("[INFO] Deleting WAFv2 RuleGroup %s", d.Id()) + + r := &wafv2.DeleteRuleGroupInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + LockToken: aws.String(d.Get("lock_token").(string)), + } + + err := resource.Retry(5*time.Minute, func() *resource.RetryError { + _, err := conn.DeleteRuleGroup(r) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFAssociatedItemException, "") { + return resource.RetryableError(err) + } + if isAWSErr(err, wafv2.ErrCodeWAFUnavailableEntityException, "") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.DeleteRuleGroup(r) + } + + if err != nil { + return fmt.Errorf("Error deleting WAFv2 RuleGroup: %s", err) + } + + return nil +} diff --git a/aws/resource_aws_wafv2_rule_group_test.go b/aws/resource_aws_wafv2_rule_group_test.go new file mode 100644 index 00000000000..0b2f6737e9e --- /dev/null +++ b/aws/resource_aws_wafv2_rule_group_test.go @@ -0,0 +1,2794 @@ +package aws + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" +) + +func TestAccAwsWafv2RuleGroup_basic(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_Basic(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "rule.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_updateRule(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_Basic(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "rule.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_BasicUpdate(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "50"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", "Updated"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "name": "rule-1", + "priority": "1", + "action.#": "1", + "action.0.allow.#": "0", + "action.0.block.#": "0", + "action.0.count.#": "1", + "statement.#": "1", + "statement.0.geo_match_statement.#": "1", + "statement.0.geo_match_statement.0.country_codes.#": "2", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_updateRuleProperties(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + ruleName2 := fmt.Sprintf("%s-2", ruleGroupName) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_BasicUpdate(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "50"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", "Updated"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "name": "rule-1", + "priority": "1", + "action.#": "1", + "action.0.allow.#": "0", + "action.0.block.#": "0", + "action.0.count.#": "1", + "visibility_config.0.cloudwatch_metrics_enabled": "false", + "visibility_config.0.metric_name": "friendly-rule-metric-name", + "visibility_config.0.sampled_requests_enabled": "false", + "statement.#": "1", + "statement.0.geo_match_statement.#": "1", + "statement.0.geo_match_statement.0.country_codes.#": "2", + }), + ), + }, + { + // Test step verifies addition of a rule block with the first block unchanged + Config: testAccAwsWafv2RuleGroupConfig_UpdateMultipleRules(ruleGroupName, "rule-1", ruleName2, 1, 2), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "50"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", "Updated"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "rule.#", "2"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "name": "rule-1", + "priority": "1", + "action.#": "1", + "action.0.allow.#": "0", + "action.0.block.#": "0", + "action.0.count.#": "1", + "visibility_config.#": "1", + "visibility_config.0.cloudwatch_metrics_enabled": "false", + "visibility_config.0.metric_name": "rule-1", + "visibility_config.0.sampled_requests_enabled": "false", + "statement.#": "1", + "statement.0.geo_match_statement.#": "1", + "statement.0.geo_match_statement.0.country_codes.#": "2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "name": ruleName2, + "priority": "2", + "action.#": "1", + "action.0.allow.#": "0", + "action.0.block.#": "1", + "action.0.count.#": "0", + "visibility_config.#": "1", + "visibility_config.0.cloudwatch_metrics_enabled": "false", + "visibility_config.0.metric_name": ruleName2, + "visibility_config.0.sampled_requests_enabled": "false", + "statement.#": "1", + "statement.0.size_constraint_statement.#": "1", + "statement.0.size_constraint_statement.0.comparison_operator": "LT", + "statement.0.size_constraint_statement.0.field_to_match.#": "1", + "statement.0.size_constraint_statement.0.field_to_match.0.query_string.#": "1", + "statement.0.size_constraint_statement.0.size": "50", + "statement.0.size_constraint_statement.0.text_transformation.#": "2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.size_constraint_statement.0.text_transformation.*", map[string]string{ + "priority": "2", + "type": "CMD_LINE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.size_constraint_statement.0.text_transformation.*", map[string]string{ + "priority": "5", + "type": "NONE", + }), + ), + }, + { + // Test step to verify a change in priority for rule #1 and a change in name and priority for rule #2 + Config: testAccAwsWafv2RuleGroupConfig_UpdateMultipleRules(ruleGroupName, "rule-1", "updated", 5, 10), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "50"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", "Updated"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "rule.#", "2"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "name": "rule-1", + "priority": "5", + "action.#": "1", + "action.0.allow.#": "0", + "action.0.block.#": "0", + "action.0.count.#": "1", + "visibility_config.#": "1", + "visibility_config.0.cloudwatch_metrics_enabled": "false", + "visibility_config.0.metric_name": "rule-1", + "visibility_config.0.sampled_requests_enabled": "false", + "statement.#": "1", + "statement.0.geo_match_statement.#": "1", + "statement.0.geo_match_statement.0.country_codes.#": "2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "name": "updated", + "priority": "10", + "action.#": "1", + "action.0.allow.#": "0", + "action.0.block.#": "1", + "action.0.count.#": "0", + "visibility_config.#": "1", + "visibility_config.0.cloudwatch_metrics_enabled": "false", + "visibility_config.0.metric_name": "updated", + "visibility_config.0.sampled_requests_enabled": "false", + "statement.#": "1", + "statement.0.size_constraint_statement.#": "1", + "statement.0.size_constraint_statement.0.comparison_operator": "LT", + "statement.0.size_constraint_statement.0.field_to_match.#": "1", + "statement.0.size_constraint_statement.0.field_to_match.0.query_string.#": "1", + "statement.0.size_constraint_statement.0.size": "50", + "statement.0.size_constraint_statement.0.text_transformation.#": "2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.size_constraint_statement.0.text_transformation.*", map[string]string{ + "priority": "2", + "type": "CMD_LINE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.size_constraint_statement.0.text_transformation.*", map[string]string{ + "priority": "5", + "type": "NONE", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_ByteMatchStatement(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_ByteMatchStatement(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.byte_match_statement.#": "1", + "statement.0.byte_match_statement.0.positional_constraint": "CONTAINS", + "statement.0.byte_match_statement.0.search_string": "word", + "statement.0.byte_match_statement.0.text_transformation.#": "2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.byte_match_statement.0.text_transformation.*", map[string]string{ + "priority": "5", + "type": "NONE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.byte_match_statement.0.text_transformation.*", map[string]string{ + "priority": "2", + "type": "LOWERCASE", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_Update(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.byte_match_statement.#": "1", + "statement.0.byte_match_statement.0.positional_constraint": "EXACTLY", + "statement.0.byte_match_statement.0.search_string": "sentence", + "statement.0.byte_match_statement.0.text_transformation.#": "1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.byte_match_statement.0.text_transformation.*", map[string]string{ + "priority": "3", + "type": "CMD_LINE", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_ByteMatchStatement_FieldToMatch(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchAllQueryArguments(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.byte_match_statement.#": "1", + "statement.0.byte_match_statement.0.field_to_match.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.all_query_arguments.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.body.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.method.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.query_string.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_header.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_query_argument.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.uri_path.#": "0", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchBody(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.byte_match_statement.#": "1", + "statement.0.byte_match_statement.0.field_to_match.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.all_query_arguments.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.body.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.method.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.query_string.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_header.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_query_argument.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.uri_path.#": "0", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchMethod(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.byte_match_statement.#": "1", + "statement.0.byte_match_statement.0.field_to_match.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.all_query_arguments.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.body.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.method.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.query_string.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_header.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_query_argument.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.uri_path.#": "0", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchQueryString(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.byte_match_statement.#": "1", + "statement.0.byte_match_statement.0.field_to_match.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.all_query_arguments.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.body.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.method.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.query_string.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.single_header.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_query_argument.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.uri_path.#": "0", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchSingleHeader(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.byte_match_statement.#": "1", + "statement.0.byte_match_statement.0.field_to_match.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.all_query_arguments.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.body.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.method.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.query_string.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_header.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.single_header.0.name": "a-forty-character-long-header-name-40-40", + "statement.0.byte_match_statement.0.field_to_match.0.single_query_argument.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.uri_path.#": "0", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchSingleQueryArgument(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.byte_match_statement.#": "1", + "statement.0.byte_match_statement.0.field_to_match.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.all_query_arguments.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.body.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.method.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.query_string.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_header.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_query_argument.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.single_query_argument.0.name": "a-max-30-characters-long-name-", + "statement.0.byte_match_statement.0.field_to_match.0.uri_path.#": "0", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchUriPath(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.byte_match_statement.#": "1", + "statement.0.byte_match_statement.0.field_to_match.#": "1", + "statement.0.byte_match_statement.0.field_to_match.0.all_query_arguments.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.body.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.method.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.query_string.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_header.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.single_query_argument.#": "0", + "statement.0.byte_match_statement.0.field_to_match.0.uri_path.#": "1", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_ChangeNameForceNew(t *testing.T) { + var before, after wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + ruleGroupNewName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_Basic(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &before), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "rule.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_Basic(ruleGroupNewName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &after), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupNewName), + resource.TestCheckResourceAttr(resourceName, "description", ruleGroupNewName), + resource.TestCheckResourceAttr(resourceName, "rule.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + ), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_ChangeCapacityForceNew(t *testing.T) { + var before, after wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_Basic(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &before), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "rule.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_UpdateCapacity(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &after), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "3"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "rule.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + ), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_ChangeMetricNameForceNew(t *testing.T) { + var before, after wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_Basic(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &before), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "rule.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_UpdateMetricName(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &after), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "rule.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "updated-friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + ), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_Disappears(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_Minimal(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsWafv2RuleGroup(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_GeoMatchStatement(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_GeoMatchStatement(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.geo_match_statement.#": "1", + "statement.0.geo_match_statement.0.country_codes.#": "2", + "statement.0.geo_match_statement.0.country_codes.0": "US", + "statement.0.geo_match_statement.0.country_codes.1": "NL", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_GeoMatchStatement_Update(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.geo_match_statement.#": "1", + "statement.0.geo_match_statement.0.country_codes.#": "3", + "statement.0.geo_match_statement.0.country_codes.0": "ZM", + "statement.0.geo_match_statement.0.country_codes.1": "EE", + "statement.0.geo_match_statement.0.country_codes.2": "MM", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_IpSetReferenceStatement(t *testing.T) { + var v wafv2.RuleGroup + var idx int + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_IpSetReferenceStatement(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + computeWafv2IpSetRefStatementIndex(&v, &idx), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.ip_set_reference_statement.#": "1", + }), + // TODO: TypeSet check need regex helper + testAccMatchResourceAttrArnWithIndexesAddr(resourceName, "rule.%d.statement.0.ip_set_reference_statement.0.arn", &idx, regexp.MustCompile(`regional/ipset/.+$`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_LogicalRuleStatements(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_LogicalRuleStatement_And(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.and_statement.#": "1", + "statement.0.and_statement.0.statement.#": "2", + "statement.0.and_statement.0.statement.0.geo_match_statement.#": "1", + "statement.0.and_statement.0.statement.1.geo_match_statement.#": "1", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_LogicalRuleStatement_NotAnd(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.not_statement.#": "1", + "statement.0.not_statement.0.statement.#": "1", + "statement.0.not_statement.0.statement.0.and_statement.#": "1", + "statement.0.not_statement.0.statement.0.and_statement.0.statement.#": "2", + "statement.0.not_statement.0.statement.0.and_statement.0.statement.0.geo_match_statement.#": "1", + "statement.0.not_statement.0.statement.0.and_statement.0.statement.1.geo_match_statement.#": "1", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_LogicalRuleStatement_OrNotAnd(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.or_statement.#": "1", + "statement.0.or_statement.0.statement.#": "2", + "statement.0.or_statement.0.statement.0.not_statement.#": "1", + "statement.0.or_statement.0.statement.0.not_statement.0.statement.#": "1", + "statement.0.or_statement.0.statement.0.not_statement.0.statement.0.geo_match_statement.#": "1", + "statement.0.or_statement.0.statement.1.and_statement.#": "1", + "statement.0.or_statement.0.statement.1.and_statement.0.statement.#": "2", + "statement.0.or_statement.0.statement.1.and_statement.0.statement.0.geo_match_statement.#": "1", + "statement.0.or_statement.0.statement.1.and_statement.0.statement.1.geo_match_statement.#": "1", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_Minimal(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_Minimal(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "rule.#", "0"), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.cloudwatch_metrics_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.metric_name", "friendly-metric-name"), + resource.TestCheckResourceAttr(resourceName, "visibility_config.0.sampled_requests_enabled", "false"), + ), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_RegexPatternSetReferenceStatement(t *testing.T) { + var v wafv2.RuleGroup + var idx int + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_RegexPatternSetReferenceStatement(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + computeWafv2RegexSetRefStatementIndex(&v, &idx), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.regex_pattern_set_reference_statement.#": "1", + "statement.0.regex_pattern_set_reference_statement.0.field_to_match.#": "1", + "statement.0.regex_pattern_set_reference_statement.0.text_transformation.#": "1", + }), + // TODO: TypeSet check need regex helper + testAccMatchResourceAttrArnWithIndexesAddr(resourceName, "rule.%d.statement.0.regex_pattern_set_reference_statement.0.arn", &idx, regexp.MustCompile(`regional/regexpatternset/.+$`)), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_RuleAction(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_RuleActionAllow(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "action.#": "1", + "action.0.allow.#": "1", + "action.0.block.#": "0", + "action.0.count.#": "0", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_RuleActionBlock(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "action.#": "1", + "action.0.allow.#": "0", + "action.0.block.#": "1", + "action.0.count.#": "0", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_RuleActionCount(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "capacity", "2"), + resource.TestCheckResourceAttr(resourceName, "name", ruleGroupName), + resource.TestCheckResourceAttr(resourceName, "description", ""), + resource.TestCheckResourceAttr(resourceName, "scope", wafv2.ScopeRegional), + resource.TestCheckResourceAttr(resourceName, "visibility_config.#", "1"), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "action.#": "1", + "action.0.allow.#": "0", + "action.0.block.#": "0", + "action.0.count.#": "1", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} +func TestAccAwsWafv2RuleGroup_SizeConstraintStatement(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_SizeConstraintStatement(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.size_constraint_statement.#": "1", + "statement.0.size_constraint_statement.0.comparison_operator": "GT", + "statement.0.size_constraint_statement.0.size": "100", + "statement.0.size_constraint_statement.0.field_to_match.#": "1", + "statement.0.size_constraint_statement.0.field_to_match.0.method.#": "1", + "statement.0.size_constraint_statement.0.text_transformation.#": "1", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_SizeConstraintStatement_Update(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.size_constraint_statement.#": "1", + "statement.0.size_constraint_statement.0.comparison_operator": "LT", + "statement.0.size_constraint_statement.0.size": "50", + "statement.0.size_constraint_statement.0.field_to_match.#": "1", + "statement.0.size_constraint_statement.0.field_to_match.0.query_string.#": "1", + "statement.0.size_constraint_statement.0.text_transformation.#": "2", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} +func TestAccAwsWafv2RuleGroup_SqliMatchStatement(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_SqliMatchStatement(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.sqli_match_statement.#": "1", + "statement.0.sqli_match_statement.0.field_to_match.#": "1", + "statement.0.sqli_match_statement.0.field_to_match.0.all_query_arguments.#": "1", + "statement.0.sqli_match_statement.0.text_transformation.#": "2", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.sqli_match_statement.0.text_transformation.*", map[string]string{ + "priority": "5", + "type": "URL_DECODE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.sqli_match_statement.0.text_transformation.*", map[string]string{ + "priority": "2", + "type": "LOWERCASE", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_SqliMatchStatement_Update(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.sqli_match_statement.#": "1", + "statement.0.sqli_match_statement.0.field_to_match.#": "1", + "statement.0.sqli_match_statement.0.field_to_match.0.body.#": "1", + "statement.0.sqli_match_statement.0.text_transformation.#": "3", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.sqli_match_statement.0.text_transformation.*", map[string]string{ + "priority": "5", + "type": "URL_DECODE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.sqli_match_statement.0.text_transformation.*", map[string]string{ + "priority": "4", + "type": "HTML_ENTITY_DECODE", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.sqli_match_statement.0.text_transformation.*", map[string]string{ + "priority": "3", + "type": "COMPRESS_WHITE_SPACE", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_Tags(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_OneTag(ruleGroupName, "Tag1", "Value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_TwoTags(ruleGroupName, "Tag1", "Value1Updated", "Tag2", "Value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag1", "Value1Updated"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_OneTag(ruleGroupName, "Tag2", "Value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.Tag2", "Value2"), + ), + }, + }, + }) +} + +func TestAccAwsWafv2RuleGroup_XssMatchStatement(t *testing.T) { + var v wafv2.RuleGroup + ruleGroupName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_rule_group.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2RuleGroupDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2RuleGroupConfig_XssMatchStatement(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.xss_match_statement.#": "1", + "statement.0.xss_match_statement.0.field_to_match.#": "1", + "statement.0.xss_match_statement.0.field_to_match.0.body.#": "1", + "statement.0.xss_match_statement.0.text_transformation.#": "1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.xss_match_statement.0.text_transformation.*", map[string]string{ + "priority": "2", + "type": "NONE", + }), + ), + }, + { + Config: testAccAwsWafv2RuleGroupConfig_XssMatchStatement_Update(ruleGroupName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2RuleGroupExists(resourceName, &v), + testAccMatchResourceAttrRegionalARN(resourceName, "arn", "wafv2", regexp.MustCompile(`regional/rulegroup/.+$`)), + resource.TestCheckResourceAttr(resourceName, "rule.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*", map[string]string{ + "statement.#": "1", + "statement.0.xss_match_statement.#": "1", + "statement.0.xss_match_statement.0.field_to_match.#": "1", + "statement.0.xss_match_statement.0.field_to_match.0.body.#": "1", + "statement.0.xss_match_statement.0.text_transformation.#": "1", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "rule.*.statement.0.xss_match_statement.0.text_transformation.*", map[string]string{ + "priority": "2", + "type": "URL_DECODE", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName), + }, + }, + }) +} + +func testAccMatchResourceAttrArnWithIndexesAddr(name, format string, idx *int, arnResourceRegexp *regexp.Regexp) resource.TestCheckFunc { + return func(s *terraform.State) error { + return testAccMatchResourceAttrRegionalARN(name, fmt.Sprintf(format, *idx), "wafv2", arnResourceRegexp)(s) + } +} + +// Calculates the index which isn't static because ARN is generated as part of the test +func computeWafv2IpSetRefStatementIndex(r *wafv2.RuleGroup, idx *int) resource.TestCheckFunc { + return func(s *terraform.State) error { + ruleResource := resourceAwsWafv2RuleGroup().Schema["rule"].Elem.(*schema.Resource) + + rule := map[string]interface{}{ + "name": "rule-1", + "priority": 1, + "action": []interface{}{ + map[string]interface{}{ + "allow": make([]interface{}, 1), + "block": []interface{}{}, + "count": []interface{}{}, + }, + }, + "statement": []interface{}{ + map[string]interface{}{ + "and_statement": []interface{}{}, + "byte_match_statement": []interface{}{}, + "geo_match_statement": []interface{}{}, + "ip_set_reference_statement": []interface{}{ + map[string]interface{}{ + "arn": aws.StringValue(r.Rules[0].Statement.IPSetReferenceStatement.ARN), + }, + }, + "not_statement": []interface{}{}, + "or_statement": []interface{}{}, + "regex_pattern_set_reference_statement": []interface{}{}, + "size_constraint_statement": []interface{}{}, + "sqli_match_statement": []interface{}{}, + "xss_match_statement": []interface{}{}, + }, + }, + "visibility_config": []interface{}{ + map[string]interface{}{ + "cloudwatch_metrics_enabled": false, + "metric_name": "friendly-rule-metric-name", + "sampled_requests_enabled": false, + }, + }, + } + + f := schema.HashResource(ruleResource) + *idx = f(rule) + + return nil + } +} + +// Calculates the index which isn't static because ARN is generated as part of the test +func computeWafv2RegexSetRefStatementIndex(r *wafv2.RuleGroup, idx *int) resource.TestCheckFunc { + return func(s *terraform.State) error { + ruleResource := resourceAwsWafv2RuleGroup().Schema["rule"].Elem.(*schema.Resource) + textTransformationResource := ruleResource.Schema["statement"].Elem.(*schema.Resource).Schema["regex_pattern_set_reference_statement"].Elem.(*schema.Resource).Schema["text_transformation"].Elem.(*schema.Resource) + rule := map[string]interface{}{ + "name": "rule-1", + "priority": 1, + "action": []interface{}{ + map[string]interface{}{ + "allow": make([]interface{}, 1), + "block": []interface{}{}, + "count": []interface{}{}, + }, + }, + "statement": []interface{}{ + map[string]interface{}{ + "and_statement": []interface{}{}, + "byte_match_statement": []interface{}{}, + "geo_match_statement": []interface{}{}, + "ip_set_reference_statement": []interface{}{}, + "not_statement": []interface{}{}, + "or_statement": []interface{}{}, + "regex_pattern_set_reference_statement": []interface{}{ + map[string]interface{}{ + "arn": aws.StringValue(r.Rules[0].Statement.RegexPatternSetReferenceStatement.ARN), + "field_to_match": []interface{}{ + map[string]interface{}{ + "all_query_arguments": []interface{}{}, + "body": make([]interface{}, 1), + "method": []interface{}{}, + "query_string": []interface{}{}, + "single_header": []interface{}{}, + "single_query_argument": []interface{}{}, + "uri_path": []interface{}{}, + }, + }, + "text_transformation": schema.NewSet(schema.HashResource(textTransformationResource), []interface{}{ + map[string]interface{}{ + "priority": 2, + "type": "NONE", + }, + }), + }, + }, + "size_constraint_statement": []interface{}{}, + "sqli_match_statement": []interface{}{}, + "xss_match_statement": []interface{}{}, + }, + }, + "visibility_config": []interface{}{ + map[string]interface{}{ + "cloudwatch_metrics_enabled": false, + "metric_name": "friendly-rule-metric-name", + "sampled_requests_enabled": false, + }, + }, + } + + f := schema.HashResource(ruleResource) + *idx = f(rule) + + return nil + } +} + +func testAccCheckAwsWafv2RuleGroupDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_wafv2_rule_group" { + continue + } + + conn := testAccProvider.Meta().(*AWSClient).wafv2conn + resp, err := conn.GetRuleGroup( + &wafv2.GetRuleGroupInput{ + Id: aws.String(rs.Primary.ID), + Name: aws.String(rs.Primary.Attributes["name"]), + Scope: aws.String(rs.Primary.Attributes["scope"]), + }) + + if err == nil { + if resp == nil || resp.RuleGroup == nil { + return fmt.Errorf("Error getting WAFv2 RuleGroup") + } + + if aws.StringValue(resp.RuleGroup.Id) == rs.Primary.ID { + return fmt.Errorf("WAFv2 RuleGroup %s still exists", rs.Primary.ID) + } + + return nil + } + + // Return nil if the RuleGroup is already destroyed + if isAWSErr(err, wafv2.ErrCodeWAFNonexistentItemException, "") { + return nil + } + + return err + } + + return nil +} + +func testAccCheckAwsWafv2RuleGroupExists(n string, v *wafv2.RuleGroup) 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 WAFv2 RuleGroup ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).wafv2conn + resp, err := conn.GetRuleGroup(&wafv2.GetRuleGroupInput{ + Id: aws.String(rs.Primary.ID), + Name: aws.String(rs.Primary.Attributes["name"]), + Scope: aws.String(rs.Primary.Attributes["scope"]), + }) + + if err != nil { + return err + } + + if resp == nil || resp.RuleGroup == nil { + return fmt.Errorf("Error getting WAFv2 RuleGroup") + } + + if aws.StringValue(resp.RuleGroup.Id) == rs.Primary.ID { + *v = *resp.RuleGroup + return nil + } + + return fmt.Errorf("WAFv2 RuleGroup (%s) not found", rs.Primary.ID) + } +} + +func testAccAwsWafv2RuleGroupConfig_Basic(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + description = "%s" + scope = "REGIONAL" + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name, name) +} + +func testAccAwsWafv2RuleGroupConfig_BasicUpdate(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 50 + name = "%s" + description = "Updated" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + count {} + } + + statement { + geo_match_statement { + country_codes = ["US", "NL"] + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_UpdateMultipleRules(name string, ruleName1, ruleName2 string, priority1, priority2 int) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 50 + name = "%[1]s" + description = "Updated" + scope = "REGIONAL" + + rule { + name = "%[2]s" + priority = %[3]d + + action { + count {} + } + + statement { + geo_match_statement { + country_codes = ["US", "NL"] + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "%[2]s" + sampled_requests_enabled = false + } + } + + rule { + name = "%[4]s" + priority = %[5]d + + action { + block {} + } + + statement { + size_constraint_statement { + comparison_operator = "LT" + size = 50 + + field_to_match { + query_string {} + } + + text_transformation { + priority = 5 + type = "NONE" + } + + text_transformation { + priority = 2 + type = "CMD_LINE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "%[4]s" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name, ruleName1, priority1, ruleName2, priority2) +} + +func testAccAwsWafv2RuleGroupConfig_UpdateCapacity(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 3 + name = "%s" + description = "%s" + scope = "REGIONAL" + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name, name) +} + +func testAccAwsWafv2RuleGroupConfig_UpdateMetricName(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + description = "%s" + scope = "REGIONAL" + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "updated-friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name, name) +} + +func testAccAwsWafv2RuleGroupConfig_Minimal(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + scope = "REGIONAL" + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_RuleActionAllow(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + geo_match_statement { + country_codes = ["US", "NL"] + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_RuleActionBlock(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + block {} + } + + statement { + geo_match_statement { + country_codes = ["US", "NL"] + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_RuleActionCount(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + count {} + } + + statement { + geo_match_statement { + country_codes = ["US", "NL"] + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_ByteMatchStatement(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 300 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + byte_match_statement { + positional_constraint = "CONTAINS" + search_string = "word" + + field_to_match { + all_query_arguments {} + } + + text_transformation { + priority = 5 + type = "NONE" + } + + text_transformation { + priority = 2 + type = "LOWERCASE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_Update(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 30 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + byte_match_statement { + positional_constraint = "EXACTLY" + search_string = "sentence" + + field_to_match { + all_query_arguments {} + } + + text_transformation { + priority = 3 + type = "CMD_LINE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchAllQueryArguments(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 30 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + byte_match_statement { + positional_constraint = "CONTAINS" + search_string = "word" + + field_to_match { + all_query_arguments {} + } + + text_transformation { + priority = 5 + type = "NONE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchBody(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 15 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + byte_match_statement { + positional_constraint = "CONTAINS" + search_string = "word" + + field_to_match { + body {} + } + + text_transformation { + priority = 1 + type = "NONE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchMethod(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 15 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + byte_match_statement { + positional_constraint = "CONTAINS" + search_string = "word" + + field_to_match { + method {} + } + + text_transformation { + priority = 1 + type = "NONE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchQueryString(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 15 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + byte_match_statement { + positional_constraint = "CONTAINS" + search_string = "word" + + field_to_match { + query_string {} + } + + text_transformation { + priority = 1 + type = "NONE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchSingleHeader(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 15 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + byte_match_statement { + positional_constraint = "CONTAINS" + search_string = "word" + + field_to_match { + single_header { + name = "a-forty-character-long-header-name-40-40" + } + } + + text_transformation { + priority = 1 + type = "NONE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchSingleQueryArgument(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 30 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + byte_match_statement { + positional_constraint = "CONTAINS" + search_string = "word" + + field_to_match { + single_query_argument { + name = "a-max-30-characters-long-name-" + } + } + + text_transformation { + priority = 1 + type = "NONE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_ByteMatchStatement_FieldToMatchUriPath(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 15 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + byte_match_statement { + positional_constraint = "CONTAINS" + search_string = "word" + + field_to_match { + uri_path {} + } + + text_transformation { + priority = 1 + type = "NONE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_IpSetReferenceStatement(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_ip_set" "test" { + name = "ip-set-%s" + scope = "REGIONAL" + ip_address_version = "IPV4" + addresses = ["1.1.1.1/32", "2.2.2.2/32"] +} + +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + ip_set_reference_statement { + arn = aws_wafv2_ip_set.test.arn + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name, name) +} + +func testAccAwsWafv2RuleGroupConfig_GeoMatchStatement(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + geo_match_statement { + country_codes = ["US", "NL"] + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_GeoMatchStatement_Update(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + geo_match_statement { + country_codes = ["ZM", "EE", "MM"] + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_LogicalRuleStatement_And(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + and_statement { + statement { + geo_match_statement { + country_codes = ["US"] + } + } + statement { + geo_match_statement { + country_codes = ["NL"] + } + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_LogicalRuleStatement_NotAnd(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + not_statement { + statement { + and_statement { + statement { + geo_match_statement { + country_codes = ["US"] + } + } + statement { + geo_match_statement { + country_codes = ["NL"] + } + } + } + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_LogicalRuleStatement_OrNotAnd(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 3 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + or_statement { + statement { + not_statement { + statement { + geo_match_statement { + country_codes = ["DE"] + } + } + } + } + statement { + and_statement { + statement { + geo_match_statement { + country_codes = ["US"] + } + } + statement { + geo_match_statement { + country_codes = ["NL"] + } + } + } + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_RegexPatternSetReferenceStatement(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_regex_pattern_set" "test" { + name = "regex-pattern-set-%s" + scope = "REGIONAL" + + regular_expression { + regex_string = "one" + } +} + +resource "aws_wafv2_rule_group" "test" { + capacity = 50 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + regex_pattern_set_reference_statement { + arn = aws_wafv2_regex_pattern_set.test.arn + + field_to_match { + body {} + } + + text_transformation { + priority = 2 + type = "NONE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name, name) +} + +func testAccAwsWafv2RuleGroupConfig_SizeConstraintStatement(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 30 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + size_constraint_statement { + comparison_operator = "GT" + size = 100 + + field_to_match { + method {} + } + + text_transformation { + priority = 5 + type = "NONE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_SizeConstraintStatement_Update(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 30 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + size_constraint_statement { + comparison_operator = "LT" + size = 50 + + field_to_match { + query_string {} + } + + text_transformation { + priority = 5 + type = "NONE" + } + + text_transformation { + priority = 2 + type = "CMD_LINE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_SqliMatchStatement(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 300 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + sqli_match_statement { + field_to_match { + all_query_arguments {} + } + + text_transformation { + priority = 5 + type = "URL_DECODE" + } + + text_transformation { + priority = 2 + type = "LOWERCASE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_SqliMatchStatement_Update(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 300 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + sqli_match_statement { + field_to_match { + body {} + } + + text_transformation { + priority = 5 + type = "URL_DECODE" + } + + text_transformation { + priority = 4 + type = "HTML_ENTITY_DECODE" + } + + text_transformation { + priority = 3 + type = "COMPRESS_WHITE_SPACE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_XssMatchStatement(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 300 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + block {} + } + + statement { + xss_match_statement { + + field_to_match { + body {} + } + + text_transformation { + priority = 2 + type = "NONE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_XssMatchStatement_Update(name string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 300 + name = "%s" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + allow {} + } + + statement { + xss_match_statement { + field_to_match { + body {} + } + + text_transformation { + priority = 2 + type = "URL_DECODE" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +`, name) +} + +func testAccAwsWafv2RuleGroupConfig_OneTag(name, tagKey, tagValue string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + description = "%s" + scope = "REGIONAL" + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } + + tags = { + "%s" = "%s" + } +} +`, name, name, tagKey, tagValue) +} + +func testAccAwsWafv2RuleGroupConfig_TwoTags(name, tag1Key, tag1Value, tag2Key, tag2Value string) string { + return fmt.Sprintf(` +resource "aws_wafv2_rule_group" "test" { + capacity = 2 + name = "%s" + description = "%s" + scope = "REGIONAL" + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } + + tags = { + "%s" = "%s" + "%s" = "%s" + } +} +`, name, name, tag1Key, tag1Value, tag2Key, tag2Value) +} + +func testAccAwsWafv2RuleGroupImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { + return func(s *terraform.State) (string, error) { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return "", fmt.Errorf("Not found: %s", resourceName) + } + + return fmt.Sprintf("%s/%s/%s", rs.Primary.ID, rs.Primary.Attributes["name"], rs.Primary.Attributes["scope"]), nil + } +} diff --git a/aws/resource_aws_wafv2_web_acl.go b/aws/resource_aws_wafv2_web_acl.go new file mode 100644 index 00000000000..437f4e669b0 --- /dev/null +++ b/aws/resource_aws_wafv2_web_acl.go @@ -0,0 +1,854 @@ +package aws + +import ( + "fmt" + "log" + "regexp" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" +) + +const ( + Wafv2WebACLCreateTimeout = 5 * time.Minute + Wafv2WebACLUpdateTimeout = 5 * time.Minute + Wafv2WebACLDeleteTimeout = 5 * time.Minute +) + +func resourceAwsWafv2WebACL() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsWafv2WebACLCreate, + Read: resourceAwsWafv2WebACLRead, + Update: resourceAwsWafv2WebACLUpdate, + Delete: resourceAwsWafv2WebACLDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + idParts := strings.Split(d.Id(), "/") + if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { + return nil, fmt.Errorf("Unexpected format of ID (%q), expected ID/NAME/SCOPE", d.Id()) + } + id := idParts[0] + name := idParts[1] + scope := idParts[2] + d.SetId(id) + d.Set("name", name) + d.Set("scope", scope) + return []*schema.ResourceData{d}, nil + }, + }, + + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Computed: true, + }, + "capacity": { + Type: schema.TypeInt, + Computed: true, + }, + "default_action": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "allow": wafv2EmptySchema(), + "block": wafv2EmptySchema(), + }, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringLenBetween(1, 256), + }, + "lock_token": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 128), + validation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9-_]+$`), "must contain only alphanumeric hyphen and underscore characters"), + ), + }, + "scope": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + wafv2.ScopeCloudfront, + wafv2.ScopeRegional, + }, false), + }, + "rule": { + Type: schema.TypeSet, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "action": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "allow": wafv2EmptySchema(), + "block": wafv2EmptySchema(), + "count": wafv2EmptySchema(), + }, + }, + }, + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + "override_action": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "count": wafv2EmptySchema(), + "none": wafv2EmptySchema(), + }, + }, + }, + "priority": { + Type: schema.TypeInt, + Required: true, + }, + "statement": wafv2WebACLRootStatementSchema(3), + "visibility_config": wafv2VisibilityConfigSchema(), + }, + }, + }, + "tags": tagsSchema(), + "visibility_config": wafv2VisibilityConfigSchema(), + }, + } +} + +func resourceAwsWafv2WebACLCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + var resp *wafv2.CreateWebACLOutput + + params := &wafv2.CreateWebACLInput{ + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + DefaultAction: expandWafv2DefaultAction(d.Get("default_action").([]interface{})), + Rules: expandWafv2WebACLRules(d.Get("rule").(*schema.Set).List()), + VisibilityConfig: expandWafv2VisibilityConfig(d.Get("visibility_config").([]interface{})), + } + + if v, ok := d.GetOk("description"); ok { + params.Description = aws.String(v.(string)) + } + + if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { + params.Tags = keyvaluetags.New(v).IgnoreAws().Wafv2Tags() + } + + err := resource.Retry(Wafv2WebACLCreateTimeout, func() *resource.RetryError { + var err error + resp, err = conn.CreateWebACL(params) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFUnavailableEntityException, "") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.CreateWebACL(params) + } + + if err != nil { + return fmt.Errorf("Error creating WAFv2 WebACL: %w", err) + } + + if resp == nil || resp.Summary == nil { + return fmt.Errorf("Error creating WAFv2 WebACL") + } + + d.SetId(aws.StringValue(resp.Summary.Id)) + + return resourceAwsWafv2WebACLRead(d, meta) +} + +func resourceAwsWafv2WebACLRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + + params := &wafv2.GetWebACLInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + } + + resp, err := conn.GetWebACL(params) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFNonexistentItemException, "") { + log.Printf("[WARN] WAFv2 WebACL (%s) not found, removing from state", d.Id()) + d.SetId("") + return nil + } + return err + } + + if resp == nil || resp.WebACL == nil { + return fmt.Errorf("Error getting WAFv2 WebACL") + } + + d.Set("name", aws.StringValue(resp.WebACL.Name)) + d.Set("capacity", aws.Int64Value(resp.WebACL.Capacity)) + d.Set("description", aws.StringValue(resp.WebACL.Description)) + d.Set("arn", aws.StringValue(resp.WebACL.ARN)) + d.Set("lock_token", aws.StringValue(resp.LockToken)) + + if err := d.Set("default_action", flattenWafv2DefaultAction(resp.WebACL.DefaultAction)); err != nil { + return fmt.Errorf("Error setting default_action: %w", err) + } + + if err := d.Set("rule", flattenWafv2WebACLRules(resp.WebACL.Rules)); err != nil { + return fmt.Errorf("Error setting rule: %w", err) + } + + if err := d.Set("visibility_config", flattenWafv2VisibilityConfig(resp.WebACL.VisibilityConfig)); err != nil { + return fmt.Errorf("Error setting visibility_config: %w", err) + } + + arn := aws.StringValue(resp.WebACL.ARN) + tags, err := keyvaluetags.Wafv2ListTags(conn, arn) + if err != nil { + return fmt.Errorf("Error listing tags for WAFv2 WebACL (%s): %w", arn, err) + } + + if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("Error setting tags: %w", err) + } + + return nil +} + +func resourceAwsWafv2WebACLUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + + if d.HasChanges("default_action", "description", "rule", "visibility_config") { + u := &wafv2.UpdateWebACLInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + LockToken: aws.String(d.Get("lock_token").(string)), + DefaultAction: expandWafv2DefaultAction(d.Get("default_action").([]interface{})), + Rules: expandWafv2WebACLRules(d.Get("rule").(*schema.Set).List()), + VisibilityConfig: expandWafv2VisibilityConfig(d.Get("visibility_config").([]interface{})), + } + + if v, ok := d.GetOk("description"); ok && len(v.(string)) > 0 { + u.Description = aws.String(v.(string)) + } + + err := resource.Retry(Wafv2WebACLUpdateTimeout, func() *resource.RetryError { + _, err := conn.UpdateWebACL(u) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFUnavailableEntityException, "") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.UpdateWebACL(u) + } + + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFOptimisticLockException, "") { + return fmt.Errorf("Error updating WAFv2 WebACL, resource has changed since last refresh please run a new plan before applying again: %w", err) + } + return fmt.Errorf("Error updating WAFv2 WebACL: %w", err) + } + } + + if d.HasChange("tags") { + o, n := d.GetChange("tags") + if err := keyvaluetags.Wafv2UpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating tags: %w", err) + } + } + + return resourceAwsWafv2WebACLRead(d, meta) +} + +func resourceAwsWafv2WebACLDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + + log.Printf("[INFO] Deleting WAFv2 WebACL %s", d.Id()) + + r := &wafv2.DeleteWebACLInput{ + Id: aws.String(d.Id()), + Name: aws.String(d.Get("name").(string)), + Scope: aws.String(d.Get("scope").(string)), + LockToken: aws.String(d.Get("lock_token").(string)), + } + + err := resource.Retry(Wafv2WebACLDeleteTimeout, func() *resource.RetryError { + _, err := conn.DeleteWebACL(r) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFAssociatedItemException, "") { + return resource.RetryableError(err) + } + if isAWSErr(err, wafv2.ErrCodeWAFUnavailableEntityException, "") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.DeleteWebACL(r) + } + + if err != nil { + return fmt.Errorf("Error deleting WAFv2 WebACL: %w", err) + } + + return nil +} + +func wafv2WebACLRootStatementSchema(level int) *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "and_statement": wafv2StatementSchema(level), + "byte_match_statement": wafv2ByteMatchStatementSchema(), + "geo_match_statement": wafv2GeoMatchStatementSchema(), + "ip_set_reference_statement": wafv2IpSetReferenceStatementSchema(), + "managed_rule_group_statement": wafv2ManagedRuleGroupStatementSchema(), + "not_statement": wafv2StatementSchema(level), + "or_statement": wafv2StatementSchema(level), + "rate_based_statement": wafv2RateBasedStatementSchema(level), + "regex_pattern_set_reference_statement": wafv2RegexPatternSetReferenceStatementSchema(), + "rule_group_reference_statement": wafv2RuleGroupReferenceStatementSchema(), + "size_constraint_statement": wafv2SizeConstraintSchema(), + "sqli_match_statement": wafv2SqliMatchStatementSchema(), + "xss_match_statement": wafv2XssMatchStatementSchema(), + }, + }, + } +} + +func wafv2ManagedRuleGroupStatementSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "excluded_rule": wafv2ExcludedRuleSchema(), + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + "vendor_name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + }, + }, + } +} + +func wafv2ExcludedRuleSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 128), + }, + }, + }, + } +} + +func wafv2RateBasedStatementSchema(level int) *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + // Required field but currently only supports "IP" + "aggregate_key_type": { + Type: schema.TypeString, + Optional: true, + Default: wafv2.RateBasedStatementAggregateKeyTypeIp, + ValidateFunc: validation.StringInSlice([]string{ + wafv2.RateBasedStatementAggregateKeyTypeIp, + }, false), + }, + "limit": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(100, 2000000000), + }, + "scope_down_statement": wafv2ScopeDownStatementSchema(level - 1), + }, + }, + } +} + +func wafv2ScopeDownStatementSchema(level int) *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "and_statement": wafv2StatementSchema(level), + "byte_match_statement": wafv2ByteMatchStatementSchema(), + "geo_match_statement": wafv2GeoMatchStatementSchema(), + "ip_set_reference_statement": wafv2IpSetReferenceStatementSchema(), + "not_statement": wafv2StatementSchema(level), + "or_statement": wafv2StatementSchema(level), + "regex_pattern_set_reference_statement": wafv2RegexPatternSetReferenceStatementSchema(), + "size_constraint_statement": wafv2SizeConstraintSchema(), + "sqli_match_statement": wafv2SqliMatchStatementSchema(), + "xss_match_statement": wafv2XssMatchStatementSchema(), + }, + }, + } +} + +func wafv2RuleGroupReferenceStatementSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateArn, + }, + "excluded_rule": wafv2ExcludedRuleSchema(), + }, + }, + } +} + +func expandWafv2WebACLRules(l []interface{}) []*wafv2.Rule { + if len(l) == 0 || l[0] == nil { + return nil + } + + rules := make([]*wafv2.Rule, 0) + + for _, rule := range l { + if rule == nil { + continue + } + rules = append(rules, expandWafv2WebACLRule(rule.(map[string]interface{}))) + } + + return rules +} + +func expandWafv2WebACLRule(m map[string]interface{}) *wafv2.Rule { + if m == nil { + return nil + } + + return &wafv2.Rule{ + Name: aws.String(m["name"].(string)), + Priority: aws.Int64(int64(m["priority"].(int))), + Action: expandWafv2RuleAction(m["action"].([]interface{})), + OverrideAction: expandWafv2OverrideAction(m["override_action"].([]interface{})), + Statement: expandWafv2WebACLRootStatement(m["statement"].([]interface{})), + VisibilityConfig: expandWafv2VisibilityConfig(m["visibility_config"].([]interface{})), + } +} + +func expandWafv2OverrideAction(l []interface{}) *wafv2.OverrideAction { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + action := &wafv2.OverrideAction{} + + if v, ok := m["count"]; ok && len(v.([]interface{})) > 0 { + action.Count = &wafv2.CountAction{} + } + + if v, ok := m["none"]; ok && len(v.([]interface{})) > 0 { + action.None = &wafv2.NoneAction{} + } + + return action +} + +func expandWafv2DefaultAction(l []interface{}) *wafv2.DefaultAction { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + action := &wafv2.DefaultAction{} + + if v, ok := m["allow"]; ok && len(v.([]interface{})) > 0 { + action.Allow = &wafv2.AllowAction{} + } + + if v, ok := m["block"]; ok && len(v.([]interface{})) > 0 { + action.Block = &wafv2.BlockAction{} + } + + return action +} + +func expandWafv2WebACLRootStatement(l []interface{}) *wafv2.Statement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return expandWafv2WebACLStatement(m) +} + +func expandWafv2WebACLStatement(m map[string]interface{}) *wafv2.Statement { + if m == nil { + return nil + } + + statement := &wafv2.Statement{} + + if v, ok := m["and_statement"]; ok { + statement.AndStatement = expandWafv2AndStatement(v.([]interface{})) + } + + if v, ok := m["byte_match_statement"]; ok { + statement.ByteMatchStatement = expandWafv2ByteMatchStatement(v.([]interface{})) + } + + if v, ok := m["ip_set_reference_statement"]; ok { + statement.IPSetReferenceStatement = expandWafv2IpSetReferenceStatement(v.([]interface{})) + } + + if v, ok := m["geo_match_statement"]; ok { + statement.GeoMatchStatement = expandWafv2GeoMatchStatement(v.([]interface{})) + } + + if v, ok := m["managed_rule_group_statement"]; ok { + statement.ManagedRuleGroupStatement = expandWafv2ManagedRuleGroupStatement(v.([]interface{})) + } + + if v, ok := m["not_statement"]; ok { + statement.NotStatement = expandWafv2NotStatement(v.([]interface{})) + } + + if v, ok := m["or_statement"]; ok { + statement.OrStatement = expandWafv2OrStatement(v.([]interface{})) + } + + if v, ok := m["rate_based_statement"]; ok { + statement.RateBasedStatement = expandWafv2RateBasedStatement(v.([]interface{})) + } + + if v, ok := m["regex_pattern_set_reference_statement"]; ok { + statement.RegexPatternSetReferenceStatement = expandWafv2RegexPatternSetReferenceStatement(v.([]interface{})) + } + + if v, ok := m["rule_group_reference_statement"]; ok { + statement.RuleGroupReferenceStatement = expandWafv2RuleGroupReferenceStatement(v.([]interface{})) + } + + if v, ok := m["size_constraint_statement"]; ok { + statement.SizeConstraintStatement = expandWafv2SizeConstraintStatement(v.([]interface{})) + } + + if v, ok := m["sqli_match_statement"]; ok { + statement.SqliMatchStatement = expandWafv2SqliMatchStatement(v.([]interface{})) + } + + if v, ok := m["xss_match_statement"]; ok { + statement.XssMatchStatement = expandWafv2XssMatchStatement(v.([]interface{})) + } + + return statement +} + +func expandWafv2ManagedRuleGroupStatement(l []interface{}) *wafv2.ManagedRuleGroupStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + return &wafv2.ManagedRuleGroupStatement{ + ExcludedRules: expandWafv2ExcludedRules(m["excluded_rule"].([]interface{})), + Name: aws.String(m["name"].(string)), + VendorName: aws.String(m["vendor_name"].(string)), + } +} + +func expandWafv2RateBasedStatement(l []interface{}) *wafv2.RateBasedStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + r := &wafv2.RateBasedStatement{ + AggregateKeyType: aws.String(m["aggregate_key_type"].(string)), + Limit: aws.Int64(int64(m["limit"].(int))), + } + + s := m["scope_down_statement"].([]interface{}) + if len(s) > 0 && s[0] != nil { + r.ScopeDownStatement = expandWafv2Statement(s[0].(map[string]interface{})) + } + + return r +} + +func expandWafv2RuleGroupReferenceStatement(l []interface{}) *wafv2.RuleGroupReferenceStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.RuleGroupReferenceStatement{ + ARN: aws.String(m["arn"].(string)), + ExcludedRules: expandWafv2ExcludedRules(m["excluded_rule"].([]interface{})), + } +} + +func expandWafv2ExcludedRules(l []interface{}) []*wafv2.ExcludedRule { + if len(l) == 0 || l[0] == nil { + return nil + } + + rules := make([]*wafv2.ExcludedRule, 0) + + for _, rule := range l { + if rule == nil { + continue + } + rules = append(rules, expandWafv2ExcludedRule(rule.(map[string]interface{}))) + } + + return rules +} + +func expandWafv2ExcludedRule(m map[string]interface{}) *wafv2.ExcludedRule { + if m == nil { + return nil + } + + return &wafv2.ExcludedRule{ + Name: aws.String(m["name"].(string)), + } +} + +func flattenWafv2WebACLRootStatement(s *wafv2.Statement) interface{} { + if s == nil { + return []interface{}{} + } + + return []interface{}{flattenWafv2WebACLStatement(s)} +} + +func flattenWafv2WebACLStatement(s *wafv2.Statement) map[string]interface{} { + if s == nil { + return map[string]interface{}{} + } + + m := map[string]interface{}{} + + if s.AndStatement != nil { + m["and_statement"] = flattenWafv2AndStatement(s.AndStatement) + } + + if s.ByteMatchStatement != nil { + m["byte_match_statement"] = flattenWafv2ByteMatchStatement(s.ByteMatchStatement) + } + + if s.IPSetReferenceStatement != nil { + m["ip_set_reference_statement"] = flattenWafv2IpSetReferenceStatement(s.IPSetReferenceStatement) + } + + if s.GeoMatchStatement != nil { + m["geo_match_statement"] = flattenWafv2GeoMatchStatement(s.GeoMatchStatement) + } + + if s.ManagedRuleGroupStatement != nil { + m["managed_rule_group_statement"] = flattenWafv2ManagedRuleGroupStatement(s.ManagedRuleGroupStatement) + } + + if s.NotStatement != nil { + m["not_statement"] = flattenWafv2NotStatement(s.NotStatement) + } + + if s.OrStatement != nil { + m["or_statement"] = flattenWafv2OrStatement(s.OrStatement) + } + + if s.RateBasedStatement != nil { + m["rate_based_statement"] = flattenWafv2RateBasedStatement(s.RateBasedStatement) + } + + if s.RegexPatternSetReferenceStatement != nil { + m["regex_pattern_set_reference_statement"] = flattenWafv2RegexPatternSetReferenceStatement(s.RegexPatternSetReferenceStatement) + } + + if s.RuleGroupReferenceStatement != nil { + m["rule_group_reference_statement"] = flattenWafv2RuleGroupReferenceStatement(s.RuleGroupReferenceStatement) + } + + if s.SizeConstraintStatement != nil { + m["size_constraint_statement"] = flattenWafv2SizeConstraintStatement(s.SizeConstraintStatement) + } + + if s.SqliMatchStatement != nil { + m["sqli_match_statement"] = flattenWafv2SqliMatchStatement(s.SqliMatchStatement) + } + + if s.XssMatchStatement != nil { + m["xss_match_statement"] = flattenWafv2XssMatchStatement(s.XssMatchStatement) + } + + return m +} + +func flattenWafv2WebACLRules(r []*wafv2.Rule) interface{} { + out := make([]map[string]interface{}, len(r)) + for i, rule := range r { + m := make(map[string]interface{}) + m["action"] = flattenWafv2RuleAction(rule.Action) + m["override_action"] = flattenWafv2OverrideAction(rule.OverrideAction) + m["name"] = aws.StringValue(rule.Name) + m["priority"] = int(aws.Int64Value(rule.Priority)) + m["statement"] = flattenWafv2WebACLRootStatement(rule.Statement) + m["visibility_config"] = flattenWafv2VisibilityConfig(rule.VisibilityConfig) + out[i] = m + } + + return out +} + +func flattenWafv2OverrideAction(a *wafv2.OverrideAction) interface{} { + if a == nil { + return []interface{}{} + } + + m := map[string]interface{}{} + + if a.Count != nil { + m["count"] = make([]map[string]interface{}, 1) + } + + if a.None != nil { + m["none"] = make([]map[string]interface{}, 1) + } + + return []interface{}{m} +} + +func flattenWafv2DefaultAction(a *wafv2.DefaultAction) interface{} { + if a == nil { + return []interface{}{} + } + + m := map[string]interface{}{} + + if a.Allow != nil { + m["allow"] = make([]map[string]interface{}, 1) + } + + if a.Block != nil { + m["block"] = make([]map[string]interface{}, 1) + } + + return []interface{}{m} +} + +func flattenWafv2ManagedRuleGroupStatement(r *wafv2.ManagedRuleGroupStatement) interface{} { + if r == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "excluded_rule": flattenWafv2ExcludedRules(r.ExcludedRules), + "name": aws.StringValue(r.Name), + "vendor_name": aws.StringValue(r.VendorName), + } + + return []interface{}{m} +} + +func flattenWafv2RateBasedStatement(r *wafv2.RateBasedStatement) interface{} { + if r == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "limit": int(aws.Int64Value(r.Limit)), + "aggregate_key_type": aws.StringValue(r.AggregateKeyType), + "scope_down_statement": nil, + } + + if r.ScopeDownStatement != nil { + m["scope_down_statement"] = []interface{}{flattenWafv2Statement(r.ScopeDownStatement)} + } + + return []interface{}{m} +} + +func flattenWafv2RuleGroupReferenceStatement(r *wafv2.RuleGroupReferenceStatement) interface{} { + if r == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "excluded_rule": flattenWafv2ExcludedRules(r.ExcludedRules), + "arn": aws.StringValue(r.ARN), + } + + return []interface{}{m} +} + +func flattenWafv2ExcludedRules(r []*wafv2.ExcludedRule) interface{} { + out := make([]map[string]interface{}, len(r)) + for i, rule := range r { + m := make(map[string]interface{}) + m["name"] = aws.StringValue(rule.Name) + out[i] = m + } + + return out +} diff --git a/aws/resource_aws_wafv2_web_acl_association.go b/aws/resource_aws_wafv2_web_acl_association.go new file mode 100644 index 00000000000..d143f69c029 --- /dev/null +++ b/aws/resource_aws_wafv2_web_acl_association.go @@ -0,0 +1,137 @@ +package aws + +import ( + "fmt" + "log" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +const ( + Wafv2WebACLAssociationCreateTimeout = 2 * time.Minute +) + +func resourceAwsWafv2WebACLAssociation() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsWafv2WebACLAssociationCreate, + Read: resourceAwsWafv2WebACLAssociationRead, + Delete: resourceAwsWafv2WebACLAssociationDelete, + Importer: &schema.ResourceImporter{ + State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + webAclArn, resourceArn, err := resourceAwsWafv2ACLAssociationDecodeId(d.Id()) + if err != nil { + return nil, fmt.Errorf("Error reading resource ID: %s", err) + } + d.Set("resource_arn", resourceArn) + d.Set("web_acl_arn", webAclArn) + return []*schema.ResourceData{d}, nil + }, + }, + + Schema: map[string]*schema.Schema{ + "resource_arn": { + Type: schema.TypeString, + ForceNew: true, + Required: true, + ValidateFunc: validateArn, + }, + "web_acl_arn": { + Type: schema.TypeString, + ForceNew: true, + Required: true, + ValidateFunc: validateArn, + }, + }, + } +} + +func resourceAwsWafv2WebACLAssociationCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + resourceArn := d.Get("resource_arn").(string) + webAclArn := d.Get("web_acl_arn").(string) + params := &wafv2.AssociateWebACLInput{ + ResourceArn: aws.String(resourceArn), + WebACLArn: aws.String(webAclArn), + } + + err := resource.Retry(Wafv2WebACLAssociationCreateTimeout, func() *resource.RetryError { + var err error + _, err = conn.AssociateWebACL(params) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFUnavailableEntityException, "") { + return resource.RetryableError(err) + } + return resource.NonRetryableError(err) + } + return nil + }) + + if isResourceTimeoutError(err) { + _, err = conn.AssociateWebACL(params) + } + + if err != nil { + return err + } + d.SetId(fmt.Sprintf("%s,%s", webAclArn, resourceArn)) + + return resourceAwsWafv2WebACLAssociationRead(d, meta) +} + +func resourceAwsWafv2WebACLAssociationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + resourceArn := d.Get("resource_arn").(string) + webAclArn := d.Get("web_acl_arn").(string) + params := &wafv2.GetWebACLForResourceInput{ + ResourceArn: aws.String(resourceArn), + } + + resp, err := conn.GetWebACLForResource(params) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFNonexistentItemException, "") { + log.Printf("[WARN] WAFv2 Web ACL (%s) not found, removing from state", webAclArn) + d.SetId("") + return nil + } + return err + } + + if resp == nil || resp.WebACL == nil { + log.Printf("[WARN] WAFv2 Web ACL associated resource (%s) not found, removing from state", resourceArn) + d.SetId("") + } + + return nil +} + +func resourceAwsWafv2WebACLAssociationDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + + log.Printf("[INFO] Deleting WAFv2 Web ACL Association %s", d.Id()) + + params := &wafv2.DisassociateWebACLInput{ + ResourceArn: aws.String(d.Get("resource_arn").(string)), + } + + _, err := conn.DisassociateWebACL(params) + if err != nil { + return fmt.Errorf("Error disassociating WAFv2 Web ACL: %s", err) + } + + return nil +} + +func resourceAwsWafv2ACLAssociationDecodeId(id string) (string, string, error) { + parts := strings.SplitN(id, ",", 2) + + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", "", fmt.Errorf("Unexpected format of ID (%s), expected WEB-ACL-ARN,RESOURCE-ARN", id) + } + + return parts[0], parts[1], nil +} diff --git a/aws/resource_aws_wafv2_web_acl_association_test.go b/aws/resource_aws_wafv2_web_acl_association_test.go new file mode 100644 index 00000000000..36acd2bf0f9 --- /dev/null +++ b/aws/resource_aws_wafv2_web_acl_association_test.go @@ -0,0 +1,183 @@ +package aws + +import ( + "fmt" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccAwsWafv2WebACLAssociation_basic(t *testing.T) { + testName := fmt.Sprintf("web-acl-association-%s", acctest.RandString(5)) + resourceName := "aws_wafv2_web_acl_association.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2WebACLAssociationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2WebACLAssociationConfig(testName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2WebACLAssociationExists(resourceName), + testAccMatchResourceAttrRegionalARNNoAccount(resourceName, "resource_arn", "apigateway", regexp.MustCompile(fmt.Sprintf("/restapis/.*/stages/%s", testName))), + testAccMatchResourceAttrRegionalARN(resourceName, "web_acl_arn", "wafv2", regexp.MustCompile(fmt.Sprintf("regional/webacl/%s/.*", testName))), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: testAccAWSWafv2WebACLAssociationImportStateIdFunc(resourceName), + }, + }, + }) +} + +func TestAccAwsWafv2WebACLAssociation_Disappears(t *testing.T) { + testName := fmt.Sprintf("web-acl-association-%s", acctest.RandString(5)) + resourceName := "aws_wafv2_web_acl_association.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSWafv2WebACLAssociationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2WebACLAssociationConfig(testName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2WebACLAssociationExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsWafv2WebACLAssociation(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + { + Config: testAccAwsWafv2WebACLAssociationConfig(testName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSWafv2WebACLAssociationExists(resourceName), + testAccCheckResourceDisappears(testAccProvider, resourceAwsApiGatewayStage(), "aws_api_gateway_stage.test"), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckAWSWafv2WebACLAssociationDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_wafv2_web_acl_association" { + continue + } + + conn := testAccProvider.Meta().(*AWSClient).wafv2conn + resp, err := conn.GetWebACLForResource(&wafv2.GetWebACLForResourceInput{ + ResourceArn: aws.String(rs.Primary.Attributes["resource_arn"]), + }) + + if err == nil { + if resp == nil || resp.WebACL == nil { + return fmt.Errorf("Error getting WAFv2 WebACLAssociation") + } + + id := fmt.Sprintf("%s,%s", aws.StringValue(resp.WebACL.ARN), rs.Primary.Attributes["resource_arn"]) + if id == rs.Primary.ID { + return fmt.Errorf("WAFv2 WebACLAssociation %s still exists", rs.Primary.ID) + } + return nil + } + + // Return nil if the Web ACL Association is already destroyed + if isAWSErr(err, wafv2.ErrCodeWAFNonexistentItemException, "") { + return nil + } + + return err + } + + return nil +} + +func testAccCheckAWSWafv2WebACLAssociationExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + _, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + return nil + } +} + +func testAccAwsWafv2WebACLAssociationConfig(name string) string { + return fmt.Sprintf(` +resource "aws_api_gateway_stage" "test" { + stage_name = "%s" + rest_api_id = aws_api_gateway_rest_api.test.id + deployment_id = aws_api_gateway_deployment.test.id +} + +resource "aws_api_gateway_rest_api" "test" { + name = "%s" +} + +resource "aws_api_gateway_deployment" "test" { + rest_api_id = aws_api_gateway_rest_api.test.id + depends_on = [aws_api_gateway_integration.test] +} + +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" +} + +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 = "mytestresource" +} + +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" +} + +resource "aws_wafv2_web_acl" "test" { + name = "%s" + scope = "REGIONAL" + + default_action { + allow {} + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} + +resource "aws_wafv2_web_acl_association" "test" { + resource_arn = aws_api_gateway_stage.test.arn + web_acl_arn = aws_wafv2_web_acl.test.arn +} +`, name, name, name) +} + +func testAccAWSWafv2WebACLAssociationImportStateIdFunc(resourceName string) resource.ImportStateIdFunc { + return func(s *terraform.State) (string, error) { + rs, ok := s.RootModule().Resources[resourceName] + if !ok { + return "", fmt.Errorf("Not found: %s", resourceName) + } + + return fmt.Sprintf("%s,%s", rs.Primary.Attributes["web_acl_arn"], rs.Primary.Attributes["resource_arn"]), nil + } +} diff --git a/aws/resource_aws_wafv2_web_acl_logging_configuration.go b/aws/resource_aws_wafv2_web_acl_logging_configuration.go new file mode 100644 index 00000000000..fe4ca6758e2 --- /dev/null +++ b/aws/resource_aws_wafv2_web_acl_logging_configuration.go @@ -0,0 +1,142 @@ +package aws + +import ( + "fmt" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "log" +) + +func resourceAwsWafv2WebACLLoggingConfiguration() *schema.Resource { + return &schema.Resource{ + Create: resourceAwsWafv2WebACLLoggingConfigurationPut, + Read: resourceAwsWafv2WebACLLoggingConfigurationRead, + Update: resourceAwsWafv2WebACLLoggingConfigurationPut, + Delete: resourceAwsWafv2WebACLLoggingConfigurationDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "log_destination_configs": { + Type: schema.TypeSet, + Required: true, + ForceNew: true, + MinItems: 1, + MaxItems: 100, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validateArn, + }, + Description: "AWS Kinesis Firehose Delivery Stream ARNs", + }, + "redacted_fields": { + Type: schema.TypeSet, + Optional: true, + MaxItems: 100, + Elem: wafv2FieldToMatchBaseSchema(), + Description: "Parts of the request to exclude from logs", + }, + "resource_arn": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateArn, + Description: "AWS WebACL ARN", + }, + }, + } +} + +func resourceAwsWafv2WebACLLoggingConfigurationPut(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + + resourceArn := d.Get("resource_arn").(string) + config := &wafv2.LoggingConfiguration{ + LogDestinationConfigs: expandStringList(d.Get("log_destination_configs").(*schema.Set).List()), + ResourceArn: aws.String(resourceArn), + } + + if v, ok := d.GetOk("redacted_fields"); ok && v.(*schema.Set).Len() > 0 { + config.RedactedFields = expandWafv2RedactedFields(v.(*schema.Set).List()) + } else { + config.RedactedFields = []*wafv2.FieldToMatch{} + } + + input := &wafv2.PutLoggingConfigurationInput{ + LoggingConfiguration: config, + } + output, err := conn.PutLoggingConfiguration(input) + if err != nil { + return fmt.Errorf("error putting WAFv2 Logging Configuration for resource (%s): %w", resourceArn, err) + } + if output == nil || output.LoggingConfiguration == nil { + return fmt.Errorf("error putting WAFv2 Logging Configuration for resource (%s): empty response", resourceArn) + } + + d.SetId(aws.StringValue(output.LoggingConfiguration.ResourceArn)) + + return resourceAwsWafv2WebACLLoggingConfigurationRead(d, meta) +} + +func resourceAwsWafv2WebACLLoggingConfigurationRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + input := &wafv2.GetLoggingConfigurationInput{ + ResourceArn: aws.String(d.Id()), + } + output, err := conn.GetLoggingConfiguration(input) + if err != nil { + if isAWSErr(err, wafv2.ErrCodeWAFNonexistentItemException, "") { + log.Printf("[WARN] WAFv2 Logging Configuration for WebACL with ARN %s not found, removing from state", d.Id()) + d.SetId("") + return nil + } + return fmt.Errorf("error reading WAFv2 Logging Configuration for resource (%s): %w", d.Id(), err) + } + if output == nil || output.LoggingConfiguration == nil { + return fmt.Errorf("error reading WAFv2 Logging Configuration for resource (%s): empty response", d.Id()) + } + + if err := d.Set("log_destination_configs", flattenStringList(output.LoggingConfiguration.LogDestinationConfigs)); err != nil { + return fmt.Errorf("error setting log_destination_configs: %w", err) + } + + if err := d.Set("redacted_fields", flattenWafv2RedactedFields(output.LoggingConfiguration.RedactedFields)); err != nil { + return fmt.Errorf("error setting redacted_fields: %w", err) + } + + d.Set("resource_arn", output.LoggingConfiguration.ResourceArn) + + return nil +} + +func resourceAwsWafv2WebACLLoggingConfigurationDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).wafv2conn + input := &wafv2.DeleteLoggingConfigurationInput{ + ResourceArn: aws.String(d.Id()), + } + _, err := conn.DeleteLoggingConfiguration(input) + if err != nil { + return fmt.Errorf("error deleting WAFv2 Logging Configuration for resource (%s): %w", d.Id(), err) + } + + return nil +} + +func flattenWafv2RedactedFields(fields []*wafv2.FieldToMatch) []map[string]interface{} { + redactedFields := make([]map[string]interface{}, 0, len(fields)) + for _, field := range fields { + redactedFields = append(redactedFields, flattenWafv2FieldToMatch(field).([]interface{})[0].(map[string]interface{})) + } + return redactedFields +} + +func expandWafv2RedactedFields(fields []interface{}) []*wafv2.FieldToMatch { + redactedFields := make([]*wafv2.FieldToMatch, 0, len(fields)) + for _, field := range fields { + redactedFields = append(redactedFields, expandWafv2FieldToMatch([]interface{}{field})) + } + return redactedFields +} diff --git a/aws/resource_aws_wafv2_web_acl_logging_configuration_test.go b/aws/resource_aws_wafv2_web_acl_logging_configuration_test.go new file mode 100644 index 00000000000..3bf794fc9f3 --- /dev/null +++ b/aws/resource_aws_wafv2_web_acl_logging_configuration_test.go @@ -0,0 +1,459 @@ +package aws + +import ( + "fmt" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/tfawsresource" +) + +func TestAccAwsWafv2WebACLLoggingConfiguration_basic(t *testing.T) { + var v wafv2.LoggingConfiguration + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_web_acl_logging_configuration.test" + webACLResourceName := "aws_wafv2_web_acl.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2WebACLLoggingConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2WebACLLoggingConfiguration_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2WebACLLoggingConfigurationExists(resourceName, &v), + resource.TestCheckResourceAttrPair(resourceName, "resource_arn", webACLResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "log_destination_configs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "redacted_fields.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAwsWafv2WebACLLoggingConfiguration_update(t *testing.T) { + var v wafv2.LoggingConfiguration + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_web_acl_logging_configuration.test" + webACLResourceName := "aws_wafv2_web_acl.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2WebACLLoggingConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2WebACLLoggingConfiguration_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2WebACLLoggingConfigurationExists(resourceName, &v), + resource.TestCheckResourceAttrPair(resourceName, "resource_arn", webACLResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "log_destination_configs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "redacted_fields.#", "0"), + ), + }, + { + Config: testAccAwsWafv2WebACLLoggingConfiguration_updateTwoRedactedFields(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2WebACLLoggingConfigurationExists(resourceName, &v), + resource.TestCheckResourceAttrPair(resourceName, "resource_arn", webACLResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "log_destination_configs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "redacted_fields.#", "2"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "redacted_fields.*", map[string]string{ + "single_header.0.name": "referer", + }), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "redacted_fields.*", map[string]string{ + "single_header.0.name": "user-agent", + }), + ), + }, + { + Config: testAccAwsWafv2WebACLLoggingConfiguration_updateOneRedactedField(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2WebACLLoggingConfigurationExists(resourceName, &v), + resource.TestCheckResourceAttrPair(resourceName, "resource_arn", webACLResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "log_destination_configs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "redacted_fields.#", "1"), + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "redacted_fields.*", map[string]string{ + "single_header.0.name": "user-agent", + }), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAwsWafv2WebACLLoggingConfiguration_changeResourceARNForceNew(t *testing.T) { + var before, after wafv2.LoggingConfiguration + rName := acctest.RandomWithPrefix("tf-acc-test") + rNameNew := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_web_acl_logging_configuration.test" + webACLResourceName := "aws_wafv2_web_acl.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2WebACLLoggingConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2WebACLLoggingConfiguration_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2WebACLLoggingConfigurationExists(resourceName, &before), + resource.TestCheckResourceAttr(webACLResourceName, "name", rName), + resource.TestCheckResourceAttrPair(resourceName, "resource_arn", webACLResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "log_destination_configs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "redacted_fields.#", "0"), + ), + }, + { + Config: testAccAwsWafv2WebACLLoggingConfiguration_basic(rNameNew), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2WebACLLoggingConfigurationExists(resourceName, &after), + resource.TestCheckResourceAttr(webACLResourceName, "name", rNameNew), + resource.TestCheckResourceAttrPair(resourceName, "resource_arn", webACLResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "log_destination_configs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "redacted_fields.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAwsWafv2WebACLLoggingConfiguration_changeLogDestinationConfigsForceNew(t *testing.T) { + var before, after wafv2.LoggingConfiguration + rName := acctest.RandomWithPrefix("tf-acc-test") + rNameNew := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_web_acl_logging_configuration.test" + webACLResourceName := "aws_wafv2_web_acl.test" + kinesisResourceName := "aws_kinesis_firehose_delivery_stream.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2WebACLLoggingConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2WebACLLoggingConfiguration_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2WebACLLoggingConfigurationExists(resourceName, &before), + resource.TestCheckResourceAttr(kinesisResourceName, "name", fmt.Sprintf("aws-waf-logs-%s", rName)), + resource.TestCheckResourceAttrPair(resourceName, "resource_arn", webACLResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "log_destination_configs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "redacted_fields.#", "0"), + ), + }, + { + Config: testAccAwsWafv2WebACLLoggingConfiguration_updateLogDestination(rName, rNameNew), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2WebACLLoggingConfigurationExists(resourceName, &after), + resource.TestCheckResourceAttr(kinesisResourceName, "name", fmt.Sprintf("aws-waf-logs-%s", rNameNew)), + resource.TestCheckResourceAttrPair(resourceName, "resource_arn", webACLResourceName, "arn"), + resource.TestCheckResourceAttr(resourceName, "log_destination_configs.#", "1"), + resource.TestCheckResourceAttr(resourceName, "redacted_fields.#", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAwsWafv2WebACLLoggingConfiguration_disappears(t *testing.T) { + var v wafv2.LoggingConfiguration + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_web_acl_logging_configuration.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2WebACLLoggingConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2WebACLLoggingConfiguration_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2WebACLLoggingConfigurationExists(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsWafv2WebACLLoggingConfiguration(), resourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func TestAccAwsWafv2WebACLLoggingConfiguration_webACLDisappears(t *testing.T) { + var v wafv2.LoggingConfiguration + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_wafv2_web_acl_logging_configuration.test" + webACLResourceName := "aws_wafv2_web_acl.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWafv2WebACLLoggingConfigurationDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAwsWafv2WebACLLoggingConfiguration_basic(rName), + Check: resource.ComposeTestCheckFunc( + testAccCheckAwsWafv2WebACLLoggingConfigurationExists(resourceName, &v), + testAccCheckResourceDisappears(testAccProvider, resourceAwsWafv2WebACL(), webACLResourceName), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testAccCheckAwsWafv2WebACLLoggingConfigurationDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_wafv2_web_acl_logging_configuration" { + continue + } + + conn := testAccProvider.Meta().(*AWSClient).wafv2conn + resp, err := conn.GetLoggingConfiguration( + &wafv2.GetLoggingConfigurationInput{ + ResourceArn: aws.String(rs.Primary.ID), + }) + + if err != nil { + // Continue checking resources in state if a WebACL Logging Configuration is already destroyed + if isAWSErr(err, wafv2.ErrCodeWAFNonexistentItemException, "") { + continue + } + return err + } + + if resp == nil || resp.LoggingConfiguration == nil { + return fmt.Errorf("Error getting WAFv2 WebACL Logging Configuration") + } + if aws.StringValue(resp.LoggingConfiguration.ResourceArn) == rs.Primary.ID { + return fmt.Errorf("WAFv2 WebACL Logging Configuration for WebACL ARN %s still exists", rs.Primary.ID) + } + } + + return nil +} + +func testAccCheckAwsWafv2WebACLLoggingConfigurationExists(n string, v *wafv2.LoggingConfiguration) 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 WAFv2 WebACL Logging Configuration ID is set") + } + + conn := testAccProvider.Meta().(*AWSClient).wafv2conn + resp, err := conn.GetLoggingConfiguration(&wafv2.GetLoggingConfigurationInput{ + ResourceArn: aws.String(rs.Primary.ID), + }) + + if err != nil { + return err + } + + if resp == nil || resp.LoggingConfiguration == nil { + return fmt.Errorf("Error getting WAFv2 WebACL Logging Configuration") + } + + if aws.StringValue(resp.LoggingConfiguration.ResourceArn) == rs.Primary.ID { + *v = *resp.LoggingConfiguration + return nil + } + + return fmt.Errorf("WAFv2 WebACL Logging Configuration (%s) not found", rs.Primary.ID) + } +} + +func testAccWebACLLoggingConfigurationDependenciesConfig(rName string) string { + return fmt.Sprintf(` +data "aws_partition" "current" {} + +data "aws_caller_identity" "current" {} + +resource "aws_iam_role" "firehose" { + name = "%[1]s" + assume_role_policy = < 0 { + return fmt.Errorf("workspace creation failed: %s", *wsFail[0].ErrorMessage) + } + + workspaceID := aws.StringValue(resp.PendingRequests[0].WorkspaceId) + + log.Printf("[DEBUG] Waiting for workspace %q to be available...", workspaceID) + _, err = waiter.WorkspaceAvailable(conn, workspaceID) + if err != nil { + return fmt.Errorf("workspace %q is not available: %s", workspaceID, err) + } + + d.SetId(workspaceID) + log.Printf("[DEBUG] Workspace %q is available", workspaceID) + + return resourceAwsWorkspacesWorkspaceRead(d, meta) +} + +func resourceAwsWorkspacesWorkspaceRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).workspacesconn + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + + rawOutput, state, err := waiter.WorkspaceState(conn, d.Id())() + if err != nil { + return fmt.Errorf("error reading workspace (%s): %s", d.Id(), err) + } + if state == workspaces.WorkspaceStateTerminated { + log.Printf("[WARN] workspace (%s) is not found, removing from state", d.Id()) + d.SetId("") + return nil + } + + workspace := rawOutput.(*workspaces.Workspace) + d.Set("bundle_id", workspace.BundleId) + d.Set("directory_id", workspace.DirectoryId) + d.Set("ip_address", workspace.IpAddress) + d.Set("computer_name", workspace.ComputerName) + d.Set("state", workspace.State) + d.Set("root_volume_encryption_enabled", workspace.RootVolumeEncryptionEnabled) + d.Set("user_name", workspace.UserName) + d.Set("user_volume_encryption_enabled", workspace.UserVolumeEncryptionEnabled) + d.Set("volume_encryption_key", workspace.VolumeEncryptionKey) + if err := d.Set("workspace_properties", flattenWorkspaceProperties(workspace.WorkspaceProperties)); err != nil { + return fmt.Errorf("error setting workspace properties: %s", err) + } + + tags, err := keyvaluetags.WorkspacesListTags(conn, d.Id()) + if err != nil { + return fmt.Errorf("error listing tags: %s", err) + } + + if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) + } + + return nil +} + +func resourceAwsWorkspacesWorkspaceUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).workspacesconn + + // IMPORTANT: Only one workspace property could be changed in a time. + // I've create AWS Support feature request to allow multiple properties modification in a time. + // https://docs.aws.amazon.com/workspaces/latest/adminguide/modify-workspaces.html + + if d.HasChange("workspace_properties.0.compute_type_name") { + if err := workspacePropertyUpdate("compute_type_name", conn, d); err != nil { + return err + } + } + + if d.HasChange("workspace_properties.0.root_volume_size_gib") { + if err := workspacePropertyUpdate("root_volume_size_gib", conn, d); err != nil { + return err + } + } + + if d.HasChange("workspace_properties.0.running_mode") { + if err := workspacePropertyUpdate("running_mode", conn, d); err != nil { + return err + } + } + + if d.HasChange("workspace_properties.0.running_mode_auto_stop_timeout_in_minutes") { + if err := workspacePropertyUpdate("running_mode_auto_stop_timeout_in_minutes", conn, d); err != nil { + return err + } + } + + if d.HasChange("workspace_properties.0.user_volume_size_gib") { + if err := workspacePropertyUpdate("user_volume_size_gib", conn, d); err != nil { + return err + } + } + + if d.HasChange("tags") { + o, n := d.GetChange("tags") + if err := keyvaluetags.WorkspacesUpdateTags(conn, d.Id(), o, n); err != nil { + return fmt.Errorf("error updating tags: %s", err) + } + } + + return resourceAwsWorkspacesWorkspaceRead(d, meta) +} + +func resourceAwsWorkspacesWorkspaceDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*AWSClient).workspacesconn + + err := workspaceDelete(d.Id(), conn) + if err != nil { + return err + } + + return nil +} + +func workspaceDelete(id string, conn *workspaces.WorkSpaces) error { + log.Printf("[DEBUG] Terminating workspace %q", id) + _, err := conn.TerminateWorkspaces(&workspaces.TerminateWorkspacesInput{ + TerminateWorkspaceRequests: []*workspaces.TerminateRequest{ + { + WorkspaceId: aws.String(id), + }, + }, + }) + if err != nil { + return err + } + + log.Printf("[DEBUG] Waiting for workspace %q to be terminated", id) + _, err = waiter.WorkspaceTerminated(conn, id) + if err != nil { + return fmt.Errorf("workspace %q was not terminated: %s", id, err) + } + log.Printf("[DEBUG] Workspace %q is terminated", id) + + return nil +} + +func workspacePropertyUpdate(p string, conn *workspaces.WorkSpaces, d *schema.ResourceData) error { + id := d.Id() + + log.Printf("[DEBUG] Modifying workspace %q %s property...", id, p) + + var wsp *workspaces.WorkspaceProperties + + switch p { + case "compute_type_name": + wsp = &workspaces.WorkspaceProperties{ + ComputeTypeName: aws.String(d.Get("workspace_properties.0.compute_type_name").(string)), + } + case "root_volume_size_gib": + wsp = &workspaces.WorkspaceProperties{ + RootVolumeSizeGib: aws.Int64(int64(d.Get("workspace_properties.0.root_volume_size_gib").(int))), + } + case "running_mode": + wsp = &workspaces.WorkspaceProperties{ + RunningMode: aws.String(d.Get("workspace_properties.0.running_mode").(string)), + } + case "running_mode_auto_stop_timeout_in_minutes": + if d.Get("workspace_properties.0.running_mode") != workspaces.RunningModeAutoStop { + log.Printf("[DEBUG] Property running_mode_auto_stop_timeout_in_minutes makes sense only for AUTO_STOP running mode") + return nil + } + + wsp = &workspaces.WorkspaceProperties{ + RunningModeAutoStopTimeoutInMinutes: aws.Int64(int64(d.Get("workspace_properties.0.running_mode_auto_stop_timeout_in_minutes").(int))), + } + case "user_volume_size_gib": + wsp = &workspaces.WorkspaceProperties{ + UserVolumeSizeGib: aws.Int64(int64(d.Get("workspace_properties.0.user_volume_size_gib").(int))), + } + } + + _, err := conn.ModifyWorkspaceProperties(&workspaces.ModifyWorkspacePropertiesInput{ + WorkspaceId: aws.String(id), + WorkspaceProperties: wsp, + }) + if err != nil { + return fmt.Errorf("workspace %q %s property was not modified: %w", d.Id(), p, err) + } + + log.Printf("[DEBUG] Waiting for workspace %q %s property to be modified...", d.Id(), p) + _, err = waiter.WorkspaceUpdated(conn, d.Id()) + if err != nil { + return fmt.Errorf("error modifying workspace %q property %q was not modified: %w", d.Id(), p, err) + } + log.Printf("[DEBUG] Workspace %q %s property is modified", d.Id(), p) + + return nil +} + +func expandWorkspaceProperties(properties []interface{}) *workspaces.WorkspaceProperties { + log.Printf("[DEBUG] Expand Workspace properties: %+v ", properties) + + if len(properties) == 0 || properties[0] == nil { + return nil + } + + p := properties[0].(map[string]interface{}) + + return &workspaces.WorkspaceProperties{ + ComputeTypeName: aws.String(p["compute_type_name"].(string)), + RootVolumeSizeGib: aws.Int64(int64(p["root_volume_size_gib"].(int))), + RunningMode: aws.String(p["running_mode"].(string)), + RunningModeAutoStopTimeoutInMinutes: aws.Int64(int64(p["running_mode_auto_stop_timeout_in_minutes"].(int))), + UserVolumeSizeGib: aws.Int64(int64(p["user_volume_size_gib"].(int))), + } +} + +func flattenWorkspaceProperties(properties *workspaces.WorkspaceProperties) []map[string]interface{} { + log.Printf("[DEBUG] Flatten workspace properties: %+v ", properties) + + if properties == nil { + return []map[string]interface{}{} + } + + return []map[string]interface{}{ + { + "compute_type_name": aws.StringValue(properties.ComputeTypeName), + "root_volume_size_gib": int(aws.Int64Value(properties.RootVolumeSizeGib)), + "running_mode": aws.StringValue(properties.RunningMode), + "running_mode_auto_stop_timeout_in_minutes": int(aws.Int64Value(properties.RunningModeAutoStopTimeoutInMinutes)), + "user_volume_size_gib": int(aws.Int64Value(properties.UserVolumeSizeGib)), + }, + } +} diff --git a/aws/resource_aws_workspaces_workspace_test.go b/aws/resource_aws_workspaces_workspace_test.go new file mode 100644 index 00000000000..185874009f5 --- /dev/null +++ b/aws/resource_aws_workspaces_workspace_test.go @@ -0,0 +1,547 @@ +package aws + +import ( + "fmt" + "log" + "reflect" + "regexp" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/workspaces" + multierror "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func init() { + resource.AddTestSweepers("aws_workspaces_workspace", &resource.Sweeper{ + Name: "aws_workspaces_workspace", + F: testSweepWorkspacesWorkspace, + }) +} + +func testSweepWorkspacesWorkspace(region string) error { + client, err := sharedClientForRegion(region) + if err != nil { + return fmt.Errorf("error getting client: %w", err) + } + conn := client.(*AWSClient).workspacesconn + + var errors error + input := &workspaces.DescribeWorkspacesInput{} + err = conn.DescribeWorkspacesPages(input, func(resp *workspaces.DescribeWorkspacesOutput, _ bool) bool { + for _, workspace := range resp.Workspaces { + err := workspaceDelete(aws.StringValue(workspace.WorkspaceId), conn) + if err != nil { + errors = multierror.Append(errors, err) + } + + } + return true + }) + if testSweepSkipSweepError(err) { + log.Printf("[WARN] Skipping workspaces sweep for %s: %s", region, err) + return errors // In case we have completed some pages, but had errors + } + if err != nil { + errors = multierror.Append(errors, fmt.Errorf("error listing workspaces: %s", err)) + } + + return errors +} + +func TestAccAwsWorkspacesWorkspace_basic(t *testing.T) { + var v workspaces.Workspace + rName := acctest.RandString(8) + + resourceName := "aws_workspaces_workspace.test" + directoryResourceName := "aws_workspaces_directory.test" + bundleDataSourceName := "data.aws_workspaces_bundle.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckHasIAMRole(t, "workspaces_DefaultRole") }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWorkspacesWorkspaceDestroy, + Steps: []resource.TestStep{ + { + Destroy: false, + Config: testAccWorkspacesWorkspaceConfig(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAwsWorkspacesWorkspaceExists(resourceName, &v), + resource.TestCheckResourceAttrPair(resourceName, "directory_id", directoryResourceName, "id"), + resource.TestCheckResourceAttrPair(resourceName, "bundle_id", bundleDataSourceName, "id"), + resource.TestMatchResourceAttr(resourceName, "ip_address", regexp.MustCompile(`\d+\.\d+\.\d+\.\d+`)), + resource.TestCheckResourceAttr(resourceName, "state", workspaces.WorkspaceStateAvailable), + resource.TestCheckResourceAttr(resourceName, "root_volume_encryption_enabled", "false"), + resource.TestCheckResourceAttr(resourceName, "user_name", "Administrator"), + resource.TestCheckResourceAttr(resourceName, "volume_encryption_key", ""), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.#", "1"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.compute_type_name", workspaces.ComputeValue), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.root_volume_size_gib", "80"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.running_mode", workspaces.RunningModeAlwaysOn), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.running_mode_auto_stop_timeout_in_minutes", "0"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.user_volume_size_gib", "10"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAwsWorkspacesWorkspace_tags(t *testing.T) { + var v1, v2, v3 workspaces.Workspace + rName := acctest.RandString(8) + + resourceName := "aws_workspaces_workspace.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckHasIAMRole(t, "workspaces_DefaultRole") }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWorkspacesWorkspaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccWorkspacesWorkspaceConfig_TagsA(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAwsWorkspacesWorkspaceExists(resourceName, &v1), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.TerraformProviderAwsTest", "true"), + resource.TestCheckResourceAttr(resourceName, "tags.Alpha", "1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccWorkspacesWorkspaceConfig_TagsB(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAwsWorkspacesWorkspaceExists(resourceName, &v2), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.TerraformProviderAwsTest", "true"), + resource.TestCheckResourceAttr(resourceName, "tags.Beta", "2"), + ), + }, + { + Config: testAccWorkspacesWorkspaceConfig_TagsC(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAwsWorkspacesWorkspaceExists(resourceName, &v3), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.TerraformProviderAwsTest", "true"), + ), + }, + }, + }) +} + +func TestAccAwsWorkspacesWorkspace_workspaceProperties(t *testing.T) { + var v1, v2, v3 workspaces.Workspace + rName := acctest.RandString(8) + + resourceName := "aws_workspaces_workspace.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckHasIAMRole(t, "workspaces_DefaultRole") }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWorkspacesWorkspaceDestroy, + Steps: []resource.TestStep{ + { + Destroy: false, + Config: testAccWorkspacesWorkspaceConfig_WorkspacePropertiesA(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAwsWorkspacesWorkspaceExists(resourceName, &v1), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.#", "1"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.compute_type_name", workspaces.ComputeValue), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.root_volume_size_gib", "80"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.running_mode", workspaces.RunningModeAutoStop), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.running_mode_auto_stop_timeout_in_minutes", "120"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.user_volume_size_gib", "10"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccWorkspacesWorkspaceConfig_WorkspacePropertiesB(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAwsWorkspacesWorkspaceExists(resourceName, &v2), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.#", "1"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.compute_type_name", workspaces.ComputeValue), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.root_volume_size_gib", "80"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.running_mode", workspaces.RunningModeAlwaysOn), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.running_mode_auto_stop_timeout_in_minutes", "0"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.user_volume_size_gib", "10"), + ), + }, + { + Config: testAccWorkspacesWorkspaceConfig_WorkspacePropertiesC(rName), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckAwsWorkspacesWorkspaceExists(resourceName, &v3), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.#", "1"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.compute_type_name", workspaces.ComputeValue), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.root_volume_size_gib", "80"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.running_mode", workspaces.RunningModeAlwaysOn), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.running_mode_auto_stop_timeout_in_minutes", "0"), + resource.TestCheckResourceAttr(resourceName, "workspace_properties.0.user_volume_size_gib", "10"), + ), + }, + }, + }) +} + +func TestAccAwsWorkspacesWorkspace_validateRootVolumeSize(t *testing.T) { + rName := acctest.RandString(8) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWorkspacesWorkspaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccWorkspacesWorkspaceConfig_validateRootVolumeSize(rName), + ExpectError: regexp.MustCompile(regexp.QuoteMeta("expected workspace_properties.0.root_volume_size_gib to be one of [80], got 90")), + }, + }, + }) +} + +func TestAccAwsWorkspacesWorkspace_validateUserVolumeSize(t *testing.T) { + rName := acctest.RandString(8) + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAwsWorkspacesWorkspaceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccWorkspacesWorkspaceConfig_validateUserVolumeSize(rName), + ExpectError: regexp.MustCompile(regexp.QuoteMeta("workspace_properties.0.user_volume_size_gib to be one of [10 50], got 60")), + }, + }, + }) +} + +func testAccCheckAwsWorkspacesWorkspaceDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*AWSClient).workspacesconn + + for _, rs := range s.RootModule().Resources { + if rs.Type != "aws_workspace" { + continue + } + + resp, err := conn.DescribeWorkspaces(&workspaces.DescribeWorkspacesInput{ + WorkspaceIds: []*string{aws.String(rs.Primary.ID)}, + }) + if err != nil { + return err + } + + if len(resp.Workspaces) == 0 { + return fmt.Errorf("workspace %q was not terminated", rs.Primary.ID) + } + ws := resp.Workspaces[0] + + if *ws.State != workspaces.WorkspaceStateTerminating && *ws.State != workspaces.WorkspaceStateTerminated { + return fmt.Errorf("workspace %q was not terminated", rs.Primary.ID) + } + } + + return nil +} + +func testAccCheckAwsWorkspacesWorkspaceExists(n string, v *workspaces.Workspace) 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().(*AWSClient).workspacesconn + + output, err := conn.DescribeWorkspaces(&workspaces.DescribeWorkspacesInput{ + WorkspaceIds: []*string{aws.String(rs.Primary.ID)}, + }) + if err != nil { + return err + } + + if *output.Workspaces[0].WorkspaceId == rs.Primary.ID { + *v = *output.Workspaces[0] + return nil + } + + return fmt.Errorf("workspace %q not found", rs.Primary.ID) + } +} + +func testAccAwsWorkspacesWorkspaceConfig_Prerequisites(rName string) string { + return composeConfig( + testAccAwsWorkspacesDirectoryConfig_Prerequisites(rName), + ` +data "aws_workspaces_bundle" "test" { + bundle_id = "wsb-bh8rsxt14" # Value with Windows 10 (English) +} + +resource "aws_workspaces_directory" "test" { + directory_id = "${aws_directory_service_directory.main.id}" +} +`) +} + +func testAccWorkspacesWorkspaceConfig(rName string) string { + return testAccAwsWorkspacesWorkspaceConfig_Prerequisites(rName) + ` +resource "aws_workspaces_workspace" "test" { + bundle_id = "${data.aws_workspaces_bundle.test.id}" + directory_id = "${aws_workspaces_directory.test.id}" + + # NOTE: WorkSpaces API doesn't allow creating users in the directory. + # However, "Administrator"" user is always present in a bare directory. + user_name = "Administrator" +} +` +} + +func testAccWorkspacesWorkspaceConfig_TagsA(rName string) string { + return testAccAwsWorkspacesWorkspaceConfig_Prerequisites(rName) + ` +resource "aws_workspaces_workspace" "test" { + bundle_id = "${data.aws_workspaces_bundle.test.id}" + directory_id = "${aws_workspaces_directory.test.id}" + + # NOTE: WorkSpaces API doesn't allow creating users in the directory. + # However, "Administrator"" user is always present in a bare directory. + user_name = "Administrator" + + tags = { + TerraformProviderAwsTest = true + Alpha = 1 + } +} +` +} + +func testAccWorkspacesWorkspaceConfig_TagsB(rName string) string { + return testAccAwsWorkspacesWorkspaceConfig_Prerequisites(rName) + ` +resource "aws_workspaces_workspace" "test" { + bundle_id = "${data.aws_workspaces_bundle.test.id}" + directory_id = "${aws_workspaces_directory.test.id}" + + # NOTE: WorkSpaces API doesn't allow creating users in the directory. + # However, "Administrator"" user is always present in a bare directory. + user_name = "Administrator" + + tags = { + TerraformProviderAwsTest = true + Beta = 2 + } +} +` +} + +func testAccWorkspacesWorkspaceConfig_TagsC(rName string) string { + return testAccAwsWorkspacesWorkspaceConfig_Prerequisites(rName) + ` +resource "aws_workspaces_workspace" "test" { + bundle_id = "${data.aws_workspaces_bundle.test.id}" + directory_id = "${aws_workspaces_directory.test.id}" + + # NOTE: WorkSpaces API doesn't allow creating users in the directory. + # However, "Administrator"" user is always present in a bare directory. + user_name = "Administrator" + + tags = { + TerraformProviderAwsTest = true + } +} +` +} + +func testAccWorkspacesWorkspaceConfig_WorkspacePropertiesA(rName string) string { + return testAccAwsWorkspacesWorkspaceConfig_Prerequisites(rName) + ` +resource "aws_workspaces_workspace" "test" { + bundle_id = "${data.aws_workspaces_bundle.test.id}" + directory_id = "${aws_workspaces_directory.test.id}" + + # NOTE: WorkSpaces API doesn't allow creating users in the directory. + # However, "Administrator"" user is always present in a bare directory. + user_name = "Administrator" + + workspace_properties { + # NOTE: Compute type and volume size update not allowed within 6 hours after creation. + running_mode = "AUTO_STOP" + running_mode_auto_stop_timeout_in_minutes = 120 + } + + tags = { + TerraformProviderAwsTest = true + } +} +` +} + +func testAccWorkspacesWorkspaceConfig_WorkspacePropertiesB(rName string) string { + return testAccAwsWorkspacesWorkspaceConfig_Prerequisites(rName) + ` +resource "aws_workspaces_workspace" "test" { + bundle_id = "${data.aws_workspaces_bundle.test.id}" + directory_id = "${aws_workspaces_directory.test.id}" + + # NOTE: WorkSpaces API doesn't allow creating users in the directory. + # However, "Administrator"" user is always present in a bare directory. + user_name = "Administrator" + + workspace_properties { + # NOTE: Compute type and volume size update not allowed within 6 hours after creation. + running_mode = "ALWAYS_ON" + } + + tags = { + TerraformProviderAwsTest = true + } +} +` +} + +func testAccWorkspacesWorkspaceConfig_WorkspacePropertiesC(rName string) string { + return testAccAwsWorkspacesWorkspaceConfig_Prerequisites(rName) + ` +resource "aws_workspaces_workspace" "test" { + bundle_id = "${data.aws_workspaces_bundle.test.id}" + directory_id = "${aws_workspaces_directory.test.id}" + + # NOTE: WorkSpaces API doesn't allow creating users in the directory. + # However, "Administrator"" user is always present in a bare directory. + user_name = "Administrator" + + workspace_properties { + } +} +` +} + +func testAccWorkspacesWorkspaceConfig_validateRootVolumeSize(rName string) string { + return testAccAwsWorkspacesWorkspaceConfig_Prerequisites(rName) + ` +resource "aws_workspaces_workspace" "test" { + bundle_id = "${data.aws_workspaces_bundle.test.id}" + directory_id = "${aws_workspaces_directory.test.id}" + + # NOTE: WorkSpaces API doesn't allow creating users in the directory. + # However, "Administrator"" user is always present in a bare directory. + user_name = "Administrator" + + workspace_properties { + root_volume_size_gib = 90 + user_volume_size_gib = 50 + } + + tags = { + TerraformProviderAwsTest = true + } +} +` +} + +func testAccWorkspacesWorkspaceConfig_validateUserVolumeSize(rName string) string { + return testAccAwsWorkspacesWorkspaceConfig_Prerequisites(rName) + ` +resource "aws_workspaces_workspace" "test" { + bundle_id = "${data.aws_workspaces_bundle.test.id}" + directory_id = "${aws_workspaces_directory.test.id}" + + # NOTE: WorkSpaces API doesn't allow creating users in the directory. + # However, "Administrator"" user is always present in a bare directory. + user_name = "Administrator" + + workspace_properties { + root_volume_size_gib = 80 + user_volume_size_gib = 60 + } + + tags = { + TerraformProviderAwsTest = true + } +} +` +} + +func TestExpandWorkspaceProperties(t *testing.T) { + cases := []struct { + input []interface{} + expected *workspaces.WorkspaceProperties + }{ + // Empty + { + input: []interface{}{}, + expected: nil, + }, + // Full + { + input: []interface{}{ + map[string]interface{}{ + "compute_type_name": workspaces.ComputeValue, + "root_volume_size_gib": 80, + "running_mode": workspaces.RunningModeAutoStop, + "running_mode_auto_stop_timeout_in_minutes": 60, + "user_volume_size_gib": 10, + }, + }, + expected: &workspaces.WorkspaceProperties{ + ComputeTypeName: aws.String(workspaces.ComputeValue), + RootVolumeSizeGib: aws.Int64(80), + RunningMode: aws.String(workspaces.RunningModeAutoStop), + RunningModeAutoStopTimeoutInMinutes: aws.Int64(60), + UserVolumeSizeGib: aws.Int64(10), + }, + }, + } + + for _, c := range cases { + actual := expandWorkspaceProperties(c.input) + if !reflect.DeepEqual(actual, c.expected) { + t.Fatalf("expected\n\n%#+v\n\ngot\n\n%#+v", c.expected, actual) + } + } +} + +func TestFlattenWorkspaceProperties(t *testing.T) { + cases := []struct { + input *workspaces.WorkspaceProperties + expected []map[string]interface{} + }{ + // Empty + { + input: nil, + expected: []map[string]interface{}{}, + }, + // Full + { + input: &workspaces.WorkspaceProperties{ + ComputeTypeName: aws.String(workspaces.ComputeValue), + RootVolumeSizeGib: aws.Int64(80), + RunningMode: aws.String(workspaces.RunningModeAutoStop), + RunningModeAutoStopTimeoutInMinutes: aws.Int64(60), + UserVolumeSizeGib: aws.Int64(10), + }, + expected: []map[string]interface{}{ + { + "compute_type_name": workspaces.ComputeValue, + "root_volume_size_gib": 80, + "running_mode": workspaces.RunningModeAutoStop, + "running_mode_auto_stop_timeout_in_minutes": 60, + "user_volume_size_gib": 10, + }, + }, + }, + } + + for _, c := range cases { + actual := flattenWorkspaceProperties(c.input) + if !reflect.DeepEqual(actual, c.expected) { + t.Fatalf("expected\n\n%#+v\n\ngot\n\n%#+v", c.expected, actual) + } + } +} diff --git a/aws/resource_aws_xray_sampling_rule.go b/aws/resource_aws_xray_sampling_rule.go index 81ba29acde1..80cbc674069 100644 --- a/aws/resource_aws_xray_sampling_rule.go +++ b/aws/resource_aws_xray_sampling_rule.go @@ -6,8 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/xray" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) func resourceAwsXraySamplingRule() *schema.Resource { diff --git a/aws/resource_aws_xray_sampling_rule_test.go b/aws/resource_aws_xray_sampling_rule_test.go index f21c4419b9b..41e2fa008c9 100644 --- a/aws/resource_aws_xray_sampling_rule_test.go +++ b/aws/resource_aws_xray_sampling_rule_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/xray" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccAWSXraySamplingRule_basic(t *testing.T) { diff --git a/aws/state_funcs.go b/aws/state_funcs.go new file mode 100644 index 00000000000..9485b2c6878 --- /dev/null +++ b/aws/state_funcs.go @@ -0,0 +1,17 @@ +package aws + +import "strings" + +// StateTrimSpace is a StateFunc that trims extraneous whitespace from strings. +// +// This prevents differences caused by an API canonicalizing a string with a +// trailing newline character removed. +func StateTrimSpace(v interface{}) string { + s, ok := v.(string) + + if !ok { + return "" + } + + return strings.TrimSpace(s) +} diff --git a/aws/structure.go b/aws/structure.go index 6a733e9fbb2..9782f58ff84 100644 --- a/aws/structure.go +++ b/aws/structure.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/json" "fmt" - "net" "reflect" "regexp" "sort" @@ -15,7 +14,6 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/json/jsonutil" "github.com/aws/aws-sdk-go/service/apigateway" "github.com/aws/aws-sdk-go/service/appmesh" - "github.com/aws/aws-sdk-go/service/appsync" "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/aws/aws-sdk-go/service/cloudformation" "github.com/aws/aws-sdk-go/service/cloudwatchlogs" @@ -47,10 +45,10 @@ import ( "github.com/aws/aws-sdk-go/service/waf" "github.com/aws/aws-sdk-go/service/worklink" "github.com/beevik/etree" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" "github.com/mitchellh/copystructure" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" "gopkg.in/yaml.v2" ) @@ -101,7 +99,7 @@ func expandListeners(configured []interface{}) ([]*elb.Listener, error) { // Takes the result of flatmap. Expand for an array of listeners and // returns ECS Volume compatible objects -func expandEcsVolumes(configured []interface{}) ([]*ecs.Volume, error) { +func expandEcsVolumes(configured []interface{}) []*ecs.Volume { volumes := make([]*ecs.Volume, 0, len(configured)) // Loop over our configured volumes and create @@ -161,12 +159,33 @@ func expandEcsVolumes(configured []interface{}) ([]*ecs.Volume, error) { if v, ok := config["root_directory"].(string); ok && v != "" { l.EfsVolumeConfiguration.RootDirectory = aws.String(v) } + if v, ok := config["transit_encryption"].(string); ok && v != "" { + l.EfsVolumeConfiguration.TransitEncryption = aws.String(v) + } + + if v, ok := config["transit_encryption_port"].(int); ok && v > 0 { + l.EfsVolumeConfiguration.TransitEncryptionPort = aws.Int64(int64(v)) + } + authConfig, ok := config["authorization_config"].([]interface{}) + if ok && len(authConfig) > 0 { + authconfig := authConfig[0].(map[string]interface{}) + l.EfsVolumeConfiguration.RootDirectory = nil + l.EfsVolumeConfiguration.AuthorizationConfig = &ecs.EFSAuthorizationConfig{} + + if v, ok := authconfig["access_point_id"].(string); ok && v != "" { + l.EfsVolumeConfiguration.AuthorizationConfig.AccessPointId = aws.String(v) + } + + if v, ok := authconfig["iam"].(string); ok && v != "" { + l.EfsVolumeConfiguration.AuthorizationConfig.Iam = aws.String(v) + } + } } volumes = append(volumes, l) } - return volumes, nil + return volumes } // Takes JSON in a string. Decodes JSON into @@ -322,7 +341,7 @@ func expandIPPerms( // Takes the result of flatmap.Expand for an array of parameters and // returns Parameter API compatible objects -func expandParameters(configured []interface{}) ([]*rds.Parameter, error) { +func expandParameters(configured []interface{}) []*rds.Parameter { var parameters []*rds.Parameter // Loop over our configured parameters and create @@ -343,10 +362,10 @@ func expandParameters(configured []interface{}) ([]*rds.Parameter, error) { parameters = append(parameters, p) } - return parameters, nil + return parameters } -func expandRedshiftParameters(configured []interface{}) ([]*redshift.Parameter, error) { +func expandRedshiftParameters(configured []interface{}) []*redshift.Parameter { var parameters []*redshift.Parameter // Loop over our configured parameters and create @@ -366,12 +385,12 @@ func expandRedshiftParameters(configured []interface{}) ([]*redshift.Parameter, parameters = append(parameters, p) } - return parameters, nil + return parameters } // Takes the result of flatmap.Expand for an array of parameters and // returns Parameter API compatible objects -func expandDocDBParameters(configured []interface{}) ([]*docdb.Parameter, error) { +func expandDocDBParameters(configured []interface{}) []*docdb.Parameter { parameters := make([]*docdb.Parameter, 0, len(configured)) // Loop over our configured parameters and create @@ -388,7 +407,7 @@ func expandDocDBParameters(configured []interface{}) ([]*docdb.Parameter, error) parameters = append(parameters, p) } - return parameters, nil + return parameters } func expandOptionConfiguration(configured []interface{}) []*rds.OptionConfiguration { @@ -455,7 +474,7 @@ func expandOptionSetting(list []interface{}) []*rds.OptionSetting { // Takes the result of flatmap.Expand for an array of parameters and // returns Parameter API compatible objects -func expandElastiCacheParameters(configured []interface{}) ([]*elasticache.ParameterNameValue, error) { +func expandElastiCacheParameters(configured []interface{}) []*elasticache.ParameterNameValue { parameters := make([]*elasticache.ParameterNameValue, 0, len(configured)) // Loop over our configured parameters and create @@ -471,12 +490,12 @@ func expandElastiCacheParameters(configured []interface{}) ([]*elasticache.Param parameters = append(parameters, p) } - return parameters, nil + return parameters } // Takes the result of flatmap.Expand for an array of parameters and // returns Parameter API compatible objects -func expandNeptuneParameters(configured []interface{}) ([]*neptune.Parameter, error) { +func expandNeptuneParameters(configured []interface{}) []*neptune.Parameter { parameters := make([]*neptune.Parameter, 0, len(configured)) // Loop over our configured parameters and create @@ -493,7 +512,7 @@ func expandNeptuneParameters(configured []interface{}) ([]*neptune.Parameter, er parameters = append(parameters, p) } - return parameters, nil + return parameters } // Flattens an access log into something that flatmap.Flatten() can handle @@ -701,7 +720,7 @@ func flattenEcsVolumes(list []*ecs.Volume) []map[string]interface{} { l["docker_volume_configuration"] = flattenDockerVolumeConfiguration(volume.DockerVolumeConfiguration) } - if volume.DockerVolumeConfiguration != nil { + if volume.EfsVolumeConfiguration != nil { l["efs_volume_configuration"] = flattenEFSVolumeConfiguration(volume.EfsVolumeConfiguration) } @@ -749,6 +768,33 @@ func flattenEFSVolumeConfiguration(config *ecs.EFSVolumeConfiguration) []interfa if v := config.RootDirectory; v != nil { m["root_directory"] = aws.StringValue(v) } + if v := config.TransitEncryption; v != nil { + m["transit_encryption"] = aws.StringValue(v) + } + + if v := config.TransitEncryptionPort; v != nil { + m["transit_encryption_port"] = int(aws.Int64Value(v)) + } + + if v := config.AuthorizationConfig; v != nil { + m["authorization_config"] = flattenEFSVolumeAuthorizationConfig(v) + } + } + + items = append(items, m) + return items +} + +func flattenEFSVolumeAuthorizationConfig(config *ecs.EFSAuthorizationConfig) []interface{} { + var items []interface{} + m := make(map[string]interface{}) + if config != nil { + if v := config.AccessPointId; v != nil { + m["access_point_id"] = aws.StringValue(v) + } + if v := config.Iam; v != nil { + m["iam"] = aws.StringValue(v) + } } items = append(items, m) @@ -972,6 +1018,16 @@ func expandStringList(configured []interface{}) []*string { return vs } +// Takes the result of flatmap.Expand for an array of int64 +// and returns a []*int64 +func expandInt64List(configured []interface{}) []*int64 { + vs := make([]*int64, 0, len(configured)) + for _, v := range configured { + vs = append(vs, aws.Int64(int64(v.(int)))) + } + return vs +} + // Expands a map of string to interface to a map of string to *float func expandFloat64Map(m map[string]interface{}) map[string]*float64 { float64Map := make(map[string]*float64, len(m)) @@ -986,6 +1042,11 @@ func expandStringSet(configured *schema.Set) []*string { return expandStringList(configured.List()) } +// Takes the result of schema.Set of strings and returns a []*int64 +func expandInt64Set(configured *schema.Set) []*int64 { + return expandInt64List(configured.List()) +} + // Takes list of pointers to strings. Expand to an array // of raw strings and returns a []interface{} // to keep compatibility w/ schema.NewSetschema.NewSet @@ -1224,98 +1285,6 @@ func expandTxtEntry(s string) string { } return s } - -func expandESClusterConfig(m map[string]interface{}) *elasticsearch.ElasticsearchClusterConfig { - config := elasticsearch.ElasticsearchClusterConfig{} - - if v, ok := m["dedicated_master_enabled"]; ok { - isEnabled := v.(bool) - config.DedicatedMasterEnabled = aws.Bool(isEnabled) - - if isEnabled { - if v, ok := m["dedicated_master_count"]; ok && v.(int) > 0 { - config.DedicatedMasterCount = aws.Int64(int64(v.(int))) - } - if v, ok := m["dedicated_master_type"]; ok && v.(string) != "" { - config.DedicatedMasterType = aws.String(v.(string)) - } - } - } - - if v, ok := m["instance_count"]; ok { - config.InstanceCount = aws.Int64(int64(v.(int))) - } - if v, ok := m["instance_type"]; ok { - config.InstanceType = aws.String(v.(string)) - } - - if v, ok := m["zone_awareness_enabled"]; ok { - isEnabled := v.(bool) - config.ZoneAwarenessEnabled = aws.Bool(isEnabled) - - if isEnabled { - if v, ok := m["zone_awareness_config"]; ok { - config.ZoneAwarenessConfig = expandElasticsearchZoneAwarenessConfig(v.([]interface{})) - } - } - } - - return &config -} - -func expandElasticsearchZoneAwarenessConfig(l []interface{}) *elasticsearch.ZoneAwarenessConfig { - if len(l) == 0 || l[0] == nil { - return nil - } - - m := l[0].(map[string]interface{}) - - zoneAwarenessConfig := &elasticsearch.ZoneAwarenessConfig{} - - if v, ok := m["availability_zone_count"]; ok && v.(int) > 0 { - zoneAwarenessConfig.AvailabilityZoneCount = aws.Int64(int64(v.(int))) - } - - return zoneAwarenessConfig -} - -func flattenESClusterConfig(c *elasticsearch.ElasticsearchClusterConfig) []map[string]interface{} { - m := map[string]interface{}{ - "zone_awareness_config": flattenElasticsearchZoneAwarenessConfig(c.ZoneAwarenessConfig), - "zone_awareness_enabled": aws.BoolValue(c.ZoneAwarenessEnabled), - } - - if c.DedicatedMasterCount != nil { - m["dedicated_master_count"] = *c.DedicatedMasterCount - } - if c.DedicatedMasterEnabled != nil { - m["dedicated_master_enabled"] = *c.DedicatedMasterEnabled - } - if c.DedicatedMasterType != nil { - m["dedicated_master_type"] = *c.DedicatedMasterType - } - if c.InstanceCount != nil { - m["instance_count"] = *c.InstanceCount - } - if c.InstanceType != nil { - m["instance_type"] = *c.InstanceType - } - - return []map[string]interface{}{m} -} - -func flattenElasticsearchZoneAwarenessConfig(zoneAwarenessConfig *elasticsearch.ZoneAwarenessConfig) []interface{} { - if zoneAwarenessConfig == nil { - return []interface{}{} - } - - m := map[string]interface{}{ - "availability_zone_count": aws.Int64Value(zoneAwarenessConfig.AvailabilityZoneCount), - } - - return []interface{}{m} -} - func expandESCognitoOptions(c []interface{}) *elasticsearch.CognitoOptions { options := &elasticsearch.CognitoOptions{ Enabled: aws.Bool(false), @@ -1606,8 +1575,9 @@ func flattenDSVpcSettings( return nil } - settings["subnet_ids"] = schema.NewSet(schema.HashString, flattenStringList(s.SubnetIds)) - settings["vpc_id"] = *s.VpcId + settings["subnet_ids"] = flattenStringSet(s.SubnetIds) + settings["vpc_id"] = aws.StringValue(s.VpcId) + settings["availability_zones"] = flattenStringSet(s.AvailabilityZones) return []map[string]interface{}{settings} } @@ -1722,11 +1692,12 @@ func flattenDSConnectSettings( settings := make(map[string]interface{}) - settings["customer_dns_ips"] = schema.NewSet(schema.HashString, flattenStringList(customerDnsIps)) - settings["connect_ips"] = schema.NewSet(schema.HashString, flattenStringList(s.ConnectIps)) - settings["customer_username"] = *s.CustomerUserName - settings["subnet_ids"] = schema.NewSet(schema.HashString, flattenStringList(s.SubnetIds)) - settings["vpc_id"] = *s.VpcId + settings["customer_dns_ips"] = flattenStringSet(customerDnsIps) + settings["connect_ips"] = flattenStringSet(s.ConnectIps) + settings["customer_username"] = aws.StringValue(s.CustomerUserName) + settings["subnet_ids"] = flattenStringSet(s.SubnetIds) + settings["vpc_id"] = aws.StringValue(s.VpcId) + settings["availability_zones"] = flattenStringSet(s.AvailabilityZones) return []map[string]interface{}{settings} } @@ -1848,59 +1819,7 @@ func expandApiGatewayRequestResponseModelOperations(d *schema.ResourceData, key return operations } -func deprecatedExpandApiGatewayMethodParametersJSONOperations(d *schema.ResourceData, key string, prefix string) ([]*apigateway.PatchOperation, error) { - operations := make([]*apigateway.PatchOperation, 0) - oldParameters, newParameters := d.GetChange(key) - oldParametersMap := make(map[string]interface{}) - newParametersMap := make(map[string]interface{}) - - if err := json.Unmarshal([]byte(oldParameters.(string)), &oldParametersMap); err != nil { - err := fmt.Errorf("Error unmarshaling old %s: %s", key, err) - return operations, err - } - - if err := json.Unmarshal([]byte(newParameters.(string)), &newParametersMap); err != nil { - err := fmt.Errorf("Error unmarshaling new %s: %s", key, err) - return operations, err - } - - for k := range oldParametersMap { - operation := apigateway.PatchOperation{ - Op: aws.String("remove"), - Path: aws.String(fmt.Sprintf("/%s/%s", prefix, k)), - } - - for nK, nV := range newParametersMap { - if nK == k { - operation.Op = aws.String("replace") - operation.Value = aws.String(strconv.FormatBool(nV.(bool))) - } - } - - operations = append(operations, &operation) - } - - for nK, nV := range newParametersMap { - exists := false - for k := range oldParametersMap { - if k == nK { - exists = true - } - } - if !exists { - operation := apigateway.PatchOperation{ - Op: aws.String("add"), - Path: aws.String(fmt.Sprintf("/%s/%s", prefix, nK)), - Value: aws.String(strconv.FormatBool(nV.(bool))), - } - operations = append(operations, &operation) - } - } - - return operations, nil -} - -func expandApiGatewayMethodParametersOperations(d *schema.ResourceData, key string, prefix string) ([]*apigateway.PatchOperation, error) { +func expandApiGatewayMethodParametersOperations(d *schema.ResourceData, key string, prefix string) []*apigateway.PatchOperation { operations := make([]*apigateway.PatchOperation, 0) oldParameters, newParameters := d.GetChange(key) @@ -1950,7 +1869,7 @@ func expandApiGatewayMethodParametersOperations(d *schema.ResourceData, key stri } } - return operations, nil + return operations } func expandCloudWatchLogMetricTransformations(m map[string]interface{}) []*cloudwatchlogs.MetricTransformation { @@ -1972,14 +1891,14 @@ func flattenCloudWatchLogMetricTransformations(ts []*cloudwatchlogs.MetricTransf mts := make([]interface{}, 0) m := make(map[string]interface{}) - m["name"] = *ts[0].MetricName - m["namespace"] = *ts[0].MetricNamespace - m["value"] = *ts[0].MetricValue + m["name"] = aws.StringValue(ts[0].MetricName) + m["namespace"] = aws.StringValue(ts[0].MetricNamespace) + m["value"] = aws.StringValue(ts[0].MetricValue) if ts[0].DefaultValue == nil { m["default_value"] = "" } else { - m["default_value"] = *ts[0].DefaultValue + m["default_value"] = strconv.FormatFloat(aws.Float64Value(ts[0].DefaultValue), 'f', -1, 64) } mts = append(mts, m) @@ -2107,7 +2026,7 @@ func flattenApiGatewayThrottleSettings(settings *apigateway.ThrottleSettings) [] // Takes the result of flatmap.Expand for an array of policy attributes and // returns ELB API compatible objects -func expandPolicyAttributes(configured []interface{}) ([]*elb.PolicyAttribute, error) { +func expandPolicyAttributes(configured []interface{}) []*elb.PolicyAttribute { attributes := make([]*elb.PolicyAttribute, 0, len(configured)) // Loop over our configured attributes and create @@ -2124,7 +2043,7 @@ func expandPolicyAttributes(configured []interface{}) ([]*elb.PolicyAttribute, e } - return attributes, nil + return attributes } // Flattens an array of PolicyAttributes into a []interface{} @@ -2555,8 +2474,6 @@ func expandCognitoUserPoolAdminCreateUserConfig(config map[string]interface{}) * } } - configs.UnusedAccountValidityDays = aws.Int64(int64(config["unused_account_validity_days"].(int))) - return configs } @@ -2591,8 +2508,6 @@ func flattenCognitoUserPoolAdminCreateUserConfig(s *cognitoidentityprovider.Admi } } - config["unused_account_validity_days"] = *s.UnusedAccountValidityDays - return []map[string]interface{}{config} } @@ -2772,234 +2687,6 @@ func flattenCognitoUserPoolUserPoolAddOns(s *cognitoidentityprovider.UserPoolAdd return []map[string]interface{}{config} } -func flattenIoTRuleCloudWatchAlarmActions(actions []*iot.Action) []map[string]interface{} { - results := make([]map[string]interface{}, 0) - - for _, a := range actions { - result := make(map[string]interface{}) - v := a.CloudwatchAlarm - if v != nil { - result["alarm_name"] = *v.AlarmName - result["role_arn"] = *v.RoleArn - result["state_reason"] = *v.StateReason - result["state_value"] = *v.StateValue - - results = append(results, result) - } - } - - return results -} - -func flattenIoTRuleCloudWatchMetricActions(actions []*iot.Action) []map[string]interface{} { - results := make([]map[string]interface{}, 0) - - for _, a := range actions { - result := make(map[string]interface{}) - v := a.CloudwatchMetric - if v != nil { - result["metric_name"] = *v.MetricName - result["role_arn"] = *v.RoleArn - result["metric_namespace"] = *v.MetricNamespace - result["metric_unit"] = *v.MetricUnit - result["metric_value"] = *v.MetricValue - - if v.MetricTimestamp != nil { - result["metric_timestamp"] = *v.MetricTimestamp - } - - results = append(results, result) - } - } - - return results -} - -func flattenIoTRuleDynamoDbActions(actions []*iot.Action) []map[string]interface{} { - items := make([]map[string]interface{}, 0, len(actions)) - - for _, a := range actions { - m := make(map[string]interface{}) - v := a.DynamoDB - if v != nil { - m["hash_key_field"] = aws.StringValue(v.HashKeyField) - m["hash_key_value"] = aws.StringValue(v.HashKeyValue) - m["role_arn"] = aws.StringValue(v.RoleArn) - m["table_name"] = aws.StringValue(v.TableName) - - if v.HashKeyType != nil { - m["hash_key_type"] = aws.StringValue(v.HashKeyType) - } - - if v.PayloadField != nil { - m["payload_field"] = aws.StringValue(v.PayloadField) - } - - if v.RangeKeyField != nil { - m["range_key_field"] = aws.StringValue(v.RangeKeyField) - } - - if v.RangeKeyType != nil { - m["range_key_type"] = aws.StringValue(v.RangeKeyType) - } - - if v.RangeKeyValue != nil { - m["range_key_value"] = aws.StringValue(v.RangeKeyValue) - } - - items = append(items, m) - } - } - - return items -} - -func flattenIoTRuleElasticSearchActions(actions []*iot.Action) []map[string]interface{} { - results := make([]map[string]interface{}, 0) - - for _, a := range actions { - result := make(map[string]interface{}) - v := a.Elasticsearch - if v != nil { - result["role_arn"] = *v.RoleArn - result["endpoint"] = *v.Endpoint - result["id"] = *v.Id - result["index"] = *v.Index - result["type"] = *v.Type - - results = append(results, result) - } - } - - return results -} - -func flattenIoTRuleFirehoseActions(actions []*iot.Action) []map[string]interface{} { - results := make([]map[string]interface{}, 0) - - for _, a := range actions { - result := make(map[string]interface{}) - v := a.Firehose - if v != nil { - result["role_arn"] = aws.StringValue(v.RoleArn) - result["delivery_stream_name"] = aws.StringValue(v.DeliveryStreamName) - result["separator"] = aws.StringValue(v.Separator) - - results = append(results, result) - } - } - - return results -} - -func flattenIoTRuleKinesisActions(actions []*iot.Action) []map[string]interface{} { - results := make([]map[string]interface{}, 0) - - for _, a := range actions { - result := make(map[string]interface{}) - v := a.Kinesis - if v != nil { - result["role_arn"] = *v.RoleArn - result["stream_name"] = *v.StreamName - - if v.PartitionKey != nil { - result["partition_key"] = *v.PartitionKey - } - - results = append(results, result) - } - } - - return results -} - -func flattenIoTRuleLambdaActions(actions []*iot.Action) []map[string]interface{} { - results := make([]map[string]interface{}, 0) - - for _, a := range actions { - result := make(map[string]interface{}) - v := a.Lambda - if v != nil { - result["function_arn"] = *v.FunctionArn - - results = append(results, result) - } - } - - return results -} - -func flattenIoTRuleRepublishActions(actions []*iot.Action) []map[string]interface{} { - results := make([]map[string]interface{}, 0) - - for _, a := range actions { - result := make(map[string]interface{}) - v := a.Republish - if v != nil { - result["role_arn"] = *v.RoleArn - result["topic"] = *v.Topic - - results = append(results, result) - } - } - - return results -} - -func flattenIoTRuleS3Actions(actions []*iot.Action) []map[string]interface{} { - results := make([]map[string]interface{}, 0) - - for _, a := range actions { - result := make(map[string]interface{}) - v := a.S3 - if v != nil { - result["role_arn"] = *v.RoleArn - result["bucket_name"] = *v.BucketName - result["key"] = *v.Key - - results = append(results, result) - } - } - - return results -} - -func flattenIoTRuleSnsActions(actions []*iot.Action) []map[string]interface{} { - results := make([]map[string]interface{}, 0) - - for _, a := range actions { - result := make(map[string]interface{}) - v := a.Sns - if v != nil { - result["message_format"] = *v.MessageFormat - result["role_arn"] = *v.RoleArn - result["target_arn"] = *v.TargetArn - - results = append(results, result) - } - } - - return results -} - -func flattenIoTRuleSqsActions(actions []*iot.Action) []map[string]interface{} { - results := make([]map[string]interface{}, 0) - - for _, a := range actions { - result := make(map[string]interface{}) - v := a.Sqs - if v != nil { - result["role_arn"] = aws.StringValue(v.RoleArn) - result["use_base64"] = aws.BoolValue(v.UseBase64) - result["queue_url"] = aws.StringValue(v.QueueUrl) - - results = append(results, result) - } - } - - return results -} - func flattenCognitoUserPoolPasswordPolicy(s *cognitoidentityprovider.PasswordPolicyType) []map[string]interface{} { m := map[string]interface{}{} @@ -3571,6 +3258,20 @@ func expandAwsSsmTargets(in []interface{}) []*ssm.Target { return targets } +func flattenAwsSsmParameters(parameters map[string][]*string) map[string]string { + result := make(map[string]string) + for p, values := range parameters { + var vs []string + for _, vPtr := range values { + if v := aws.StringValue(vPtr); v != "" { + vs = append(vs, v) + } + } + result[p] = strings.Join(vs, ",") + } + return result +} + func flattenAwsSsmTargets(targets []*ssm.Target) []map[string]interface{} { if len(targets) == 0 { return nil @@ -4841,17 +4542,9 @@ func flattenDaxEncryptAtRestOptions(options *dax.SSEDescription) []map[string]in return []map[string]interface{}{m} } -func expandRdsClusterScalingConfiguration(l []interface{}, engineMode string) *rds.ScalingConfiguration { +func expandRdsClusterScalingConfiguration(l []interface{}) *rds.ScalingConfiguration { if len(l) == 0 || l[0] == nil { - // Our default value for MinCapacity is different from AWS's. - // We need to override it here to avoid a non-empty plan with an empty ScalingConfiguration. - if engineMode == "serverless" { - return &rds.ScalingConfiguration{ - MinCapacity: aws.Int64(int64(rdsClusterScalingConfiguration_DefaultMinCapacity)), - } - } else { - return nil - } + return nil } m := l[0].(map[string]interface{}) @@ -4935,10 +4628,10 @@ func expandAppmeshVirtualRouterSpec(vSpec []interface{}) *appmesh.VirtualRouterS } mSpec := vSpec[0].(map[string]interface{}) - if vListeners, ok := mSpec["listener"].(*schema.Set); ok && vListeners.Len() > 0 { + if vListeners, ok := mSpec["listener"].([]interface{}); ok && len(vListeners) > 0 && vListeners[0] != nil { listeners := []*appmesh.VirtualRouterListener{} - for _, vListener := range vListeners.List() { + for _, vListener := range vListeners { listener := &appmesh.VirtualRouterListener{} mListener := vListener.(map[string]interface{}) @@ -4955,10 +4648,8 @@ func expandAppmeshVirtualRouterSpec(vSpec []interface{}) *appmesh.VirtualRouterS listener.PortMapping.Protocol = aws.String(vProtocol) } } - listeners = append(listeners, listener) } - spec.Listeners = listeners } @@ -4969,27 +4660,19 @@ func flattenAppmeshVirtualRouterSpec(spec *appmesh.VirtualRouterSpec) []interfac if spec == nil { return []interface{}{} } - - mSpec := map[string]interface{}{} - - if spec.Listeners != nil { - vListeners := []interface{}{} - - for _, listener := range spec.Listeners { - mListener := map[string]interface{}{} - - if listener.PortMapping != nil { - mPortMapping := map[string]interface{}{ - "port": int(aws.Int64Value(listener.PortMapping.Port)), - "protocol": aws.StringValue(listener.PortMapping.Protocol), - } - mListener["port_mapping"] = []interface{}{mPortMapping} + mSpec := make(map[string]interface{}) + if spec.Listeners != nil && spec.Listeners[0] != nil { + // Per schema definition, set at most 1 Listener + listener := spec.Listeners[0] + mListener := make(map[string]interface{}) + if listener.PortMapping != nil { + mPortMapping := map[string]interface{}{ + "port": int(aws.Int64Value(listener.PortMapping.Port)), + "protocol": aws.StringValue(listener.PortMapping.Protocol), } - - vListeners = append(vListeners, mListener) + mListener["port_mapping"] = []interface{}{mPortMapping} } - - mSpec["listener"] = schema.NewSet(appmeshVirtualNodeListenerHash, vListeners) + mSpec["listener"] = []interface{}{mListener} } return []interface{}{mSpec} @@ -5027,10 +4710,10 @@ func expandAppmeshVirtualNodeSpec(vSpec []interface{}) *appmesh.VirtualNodeSpec spec.Backends = backends } - if vListeners, ok := mSpec["listener"].(*schema.Set); ok && vListeners.Len() > 0 { + if vListeners, ok := mSpec["listener"].([]interface{}); ok && len(vListeners) > 0 && vListeners[0] != nil { listeners := []*appmesh.Listener{} - for _, vListener := range vListeners.List() { + for _, vListener := range vListeners { listener := &appmesh.Listener{} mListener := vListener.(map[string]interface{}) @@ -5174,37 +4857,33 @@ func flattenAppmeshVirtualNodeSpec(spec *appmesh.VirtualNodeSpec) []interface{} mSpec["backend"] = schema.NewSet(appmeshVirtualNodeBackendHash, vBackends) } - if spec.Listeners != nil { - vListeners := []interface{}{} - - for _, listener := range spec.Listeners { - mListener := map[string]interface{}{} - - if listener.HealthCheck != nil { - mHealthCheck := map[string]interface{}{ - "healthy_threshold": int(aws.Int64Value(listener.HealthCheck.HealthyThreshold)), - "interval_millis": int(aws.Int64Value(listener.HealthCheck.IntervalMillis)), - "path": aws.StringValue(listener.HealthCheck.Path), - "port": int(aws.Int64Value(listener.HealthCheck.Port)), - "protocol": aws.StringValue(listener.HealthCheck.Protocol), - "timeout_millis": int(aws.Int64Value(listener.HealthCheck.TimeoutMillis)), - "unhealthy_threshold": int(aws.Int64Value(listener.HealthCheck.UnhealthyThreshold)), - } - mListener["health_check"] = []interface{}{mHealthCheck} + if spec.Listeners != nil && spec.Listeners[0] != nil { + // Per schema definition, set at most 1 Listener + listener := spec.Listeners[0] + mListener := map[string]interface{}{} + + if listener.HealthCheck != nil { + mHealthCheck := map[string]interface{}{ + "healthy_threshold": int(aws.Int64Value(listener.HealthCheck.HealthyThreshold)), + "interval_millis": int(aws.Int64Value(listener.HealthCheck.IntervalMillis)), + "path": aws.StringValue(listener.HealthCheck.Path), + "port": int(aws.Int64Value(listener.HealthCheck.Port)), + "protocol": aws.StringValue(listener.HealthCheck.Protocol), + "timeout_millis": int(aws.Int64Value(listener.HealthCheck.TimeoutMillis)), + "unhealthy_threshold": int(aws.Int64Value(listener.HealthCheck.UnhealthyThreshold)), } + mListener["health_check"] = []interface{}{mHealthCheck} + } - if listener.PortMapping != nil { - mPortMapping := map[string]interface{}{ - "port": int(aws.Int64Value(listener.PortMapping.Port)), - "protocol": aws.StringValue(listener.PortMapping.Protocol), - } - mListener["port_mapping"] = []interface{}{mPortMapping} + if listener.PortMapping != nil { + mPortMapping := map[string]interface{}{ + "port": int(aws.Int64Value(listener.PortMapping.Port)), + "protocol": aws.StringValue(listener.PortMapping.Protocol), } - - vListeners = append(vListeners, mListener) + mListener["port_mapping"] = []interface{}{mPortMapping} } - mSpec["listener"] = schema.NewSet(appmeshVirtualNodeListenerHash, vListeners) + mSpec["listener"] = []interface{}{mListener} } if spec.Logging != nil && spec.Logging.AccessLog != nil && spec.Logging.AccessLog.File != nil { @@ -5358,7 +5037,7 @@ func expandAppmeshRouteSpec(vSpec []interface{}) *appmesh.RouteSpec { if vVirtualNode, ok := mWeightedTarget["virtual_node"].(string); ok && vVirtualNode != "" { weightedTarget.VirtualNode = aws.String(vVirtualNode) } - if vWeight, ok := mWeightedTarget["weight"].(int); ok && vWeight > 0 { + if vWeight, ok := mWeightedTarget["weight"].(int); ok { weightedTarget.Weight = aws.Int64(int64(vWeight)) } @@ -5462,7 +5141,7 @@ func expandAppmeshRouteSpec(vSpec []interface{}) *appmesh.RouteSpec { if vVirtualNode, ok := mWeightedTarget["virtual_node"].(string); ok && vVirtualNode != "" { weightedTarget.VirtualNode = aws.String(vVirtualNode) } - if vWeight, ok := mWeightedTarget["weight"].(int); ok && vWeight > 0 { + if vWeight, ok := mWeightedTarget["weight"].(int); ok { weightedTarget.Weight = aws.Int64(int64(vWeight)) } @@ -5587,22 +5266,6 @@ func flattenAppmeshRouteSpec(spec *appmesh.RouteSpec) []interface{} { return []interface{}{mSpec} } -func flattenAppsyncPipelineConfig(c *appsync.PipelineConfig) []interface{} { - if c == nil { - return nil - } - - if len(c.Functions) == 0 { - return nil - } - - m := map[string]interface{}{ - "functions": flattenStringList(c.Functions), - } - - return []interface{}{m} -} - func expandRoute53ResolverEndpointIpAddresses(vIpAddresses *schema.Set) []*route53resolver.IpAddressRequest { ipAddressRequests := []*route53resolver.IpAddressRequest{} @@ -5701,13 +5364,3 @@ func flattenRoute53ResolverRuleTargetIps(targetAddresses []*route53resolver.Targ return vTargetIps } - -func isIpv6CidrsEquals(first, second string) bool { - if first == "" || second == "" { - return false - } - _, firstMask, _ := net.ParseCIDR(first) - _, secondMask, _ := net.ParseCIDR(second) - - return firstMask.String() == secondMask.String() -} diff --git a/aws/structure_test.go b/aws/structure_test.go index 45dc8e08643..43aa0da03c4 100644 --- a/aws/structure_test.go +++ b/aws/structure_test.go @@ -17,7 +17,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/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func TestDiffStringMaps(t *testing.T) { @@ -172,49 +172,49 @@ func TestExpandIPPerms(t *testing.T) { exp := expected[0] perm := perms[0] - if *exp.FromPort != *perm.FromPort { + if aws.Int64Value(exp.FromPort) != aws.Int64Value(perm.FromPort) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.FromPort, - *exp.FromPort) + aws.Int64Value(perm.FromPort), + aws.Int64Value(exp.FromPort)) } - if *exp.IpRanges[0].CidrIp != *perm.IpRanges[0].CidrIp { + if aws.StringValue(exp.IpRanges[0].CidrIp) != aws.StringValue(perm.IpRanges[0].CidrIp) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.IpRanges[0].CidrIp, - *exp.IpRanges[0].CidrIp) + aws.StringValue(perm.IpRanges[0].CidrIp), + aws.StringValue(exp.IpRanges[0].CidrIp)) } - if *exp.UserIdGroupPairs[0].UserId != *perm.UserIdGroupPairs[0].UserId { + if aws.StringValue(exp.UserIdGroupPairs[0].UserId) != aws.StringValue(perm.UserIdGroupPairs[0].UserId) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.UserIdGroupPairs[0].UserId, - *exp.UserIdGroupPairs[0].UserId) + aws.StringValue(perm.UserIdGroupPairs[0].UserId), + aws.StringValue(exp.UserIdGroupPairs[0].UserId)) } - if *exp.UserIdGroupPairs[0].GroupId != *perm.UserIdGroupPairs[0].GroupId { + if aws.StringValue(exp.UserIdGroupPairs[0].GroupId) != aws.StringValue(perm.UserIdGroupPairs[0].GroupId) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.UserIdGroupPairs[0].GroupId, - *exp.UserIdGroupPairs[0].GroupId) + aws.StringValue(perm.UserIdGroupPairs[0].GroupId), + aws.StringValue(exp.UserIdGroupPairs[0].GroupId)) } - if *exp.UserIdGroupPairs[1].GroupId != *perm.UserIdGroupPairs[1].GroupId { + if aws.StringValue(exp.UserIdGroupPairs[1].GroupId) != aws.StringValue(perm.UserIdGroupPairs[1].GroupId) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.UserIdGroupPairs[1].GroupId, - *exp.UserIdGroupPairs[1].GroupId) + aws.StringValue(perm.UserIdGroupPairs[1].GroupId), + aws.StringValue(exp.UserIdGroupPairs[1].GroupId)) } exp = expected[1] perm = perms[1] - if *exp.UserIdGroupPairs[0].GroupId != *perm.UserIdGroupPairs[0].GroupId { + if aws.StringValue(exp.UserIdGroupPairs[0].GroupId) != aws.StringValue(perm.UserIdGroupPairs[0].GroupId) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.UserIdGroupPairs[0].GroupId, - *exp.UserIdGroupPairs[0].GroupId) + aws.StringValue(perm.UserIdGroupPairs[0].GroupId), + aws.StringValue(exp.UserIdGroupPairs[0].GroupId)) } } @@ -264,25 +264,25 @@ func TestExpandIPPerms_NegOneProtocol(t *testing.T) { exp := expected[0] perm := perms[0] - if *exp.FromPort != *perm.FromPort { + if aws.Int64Value(exp.FromPort) != aws.Int64Value(perm.FromPort) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.FromPort, - *exp.FromPort) + aws.Int64Value(perm.FromPort), + aws.Int64Value(exp.FromPort)) } - if *exp.IpRanges[0].CidrIp != *perm.IpRanges[0].CidrIp { + if aws.StringValue(exp.IpRanges[0].CidrIp) != aws.StringValue(perm.IpRanges[0].CidrIp) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.IpRanges[0].CidrIp, - *exp.IpRanges[0].CidrIp) + aws.StringValue(perm.IpRanges[0].CidrIp), + aws.StringValue(exp.IpRanges[0].CidrIp)) } - if *exp.UserIdGroupPairs[0].UserId != *perm.UserIdGroupPairs[0].UserId { + if aws.StringValue(exp.UserIdGroupPairs[0].UserId) != aws.StringValue(perm.UserIdGroupPairs[0].UserId) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.UserIdGroupPairs[0].UserId, - *exp.UserIdGroupPairs[0].UserId) + aws.StringValue(perm.UserIdGroupPairs[0].UserId), + aws.StringValue(exp.UserIdGroupPairs[0].UserId)) } // Now test the error case. This *should* error when either from_port @@ -369,42 +369,42 @@ func TestExpandIPPerms_nonVPC(t *testing.T) { exp := expected[0] perm := perms[0] - if *exp.FromPort != *perm.FromPort { + if aws.Int64Value(exp.FromPort) != aws.Int64Value(perm.FromPort) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.FromPort, - *exp.FromPort) + aws.Int64Value(perm.FromPort), + aws.Int64Value(exp.FromPort)) } - if *exp.IpRanges[0].CidrIp != *perm.IpRanges[0].CidrIp { + if aws.StringValue(exp.IpRanges[0].CidrIp) != aws.StringValue(perm.IpRanges[0].CidrIp) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.IpRanges[0].CidrIp, - *exp.IpRanges[0].CidrIp) + aws.StringValue(perm.IpRanges[0].CidrIp), + aws.StringValue(exp.IpRanges[0].CidrIp)) } - if *exp.UserIdGroupPairs[0].GroupName != *perm.UserIdGroupPairs[0].GroupName { + if aws.StringValue(exp.UserIdGroupPairs[0].GroupName) != aws.StringValue(perm.UserIdGroupPairs[0].GroupName) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.UserIdGroupPairs[0].GroupName, - *exp.UserIdGroupPairs[0].GroupName) + aws.StringValue(perm.UserIdGroupPairs[0].GroupName), + aws.StringValue(exp.UserIdGroupPairs[0].GroupName)) } - if *exp.UserIdGroupPairs[1].GroupName != *perm.UserIdGroupPairs[1].GroupName { + if aws.StringValue(exp.UserIdGroupPairs[1].GroupName) != aws.StringValue(perm.UserIdGroupPairs[1].GroupName) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.UserIdGroupPairs[1].GroupName, - *exp.UserIdGroupPairs[1].GroupName) + aws.StringValue(perm.UserIdGroupPairs[1].GroupName), + aws.StringValue(exp.UserIdGroupPairs[1].GroupName)) } exp = expected[1] perm = perms[1] - if *exp.UserIdGroupPairs[0].GroupName != *perm.UserIdGroupPairs[0].GroupName { + if aws.StringValue(exp.UserIdGroupPairs[0].GroupName) != aws.StringValue(perm.UserIdGroupPairs[0].GroupName) { t.Fatalf( "Got:\n\n%#v\n\nExpected:\n\n%#v\n", - *perm.UserIdGroupPairs[0].GroupName, - *exp.UserIdGroupPairs[0].GroupName) + aws.StringValue(perm.UserIdGroupPairs[0].GroupName), + aws.StringValue(exp.UserIdGroupPairs[0].GroupName)) } } @@ -566,10 +566,7 @@ func TestExpandParameters(t *testing.T) { "apply_method": "immediate", }, } - parameters, err := expandParameters(expanded) - if err != nil { - t.Fatalf("bad: %#v", err) - } + parameters := expandParameters(expanded) expected := &rds.Parameter{ ParameterName: aws.String("character_set_client"), @@ -592,10 +589,7 @@ func TestExpandRedshiftParameters(t *testing.T) { "value": "utf8", }, } - parameters, err := expandRedshiftParameters(expanded) - if err != nil { - t.Fatalf("bad: %#v", err) - } + parameters := expandRedshiftParameters(expanded) expected := &redshift.Parameter{ ParameterName: aws.String("character_set_client"), @@ -618,10 +612,7 @@ func TestExpandElasticacheParameters(t *testing.T) { "apply_method": "immediate", }, } - parameters, err := expandElastiCacheParameters(expanded) - if err != nil { - t.Fatalf("bad: %#v", err) - } + parameters := expandElastiCacheParameters(expanded) expected := &elasticache.ParameterNameValue{ ParameterName: aws.String("activerehashing"), @@ -830,12 +821,12 @@ func TestExpandPrivateIPAddresses(t *testing.T) { t.Fatalf("expected result had %d elements, but got %d", 2, len(result)) } - if *result[0].PrivateIpAddress != "192.168.0.1" || !*result[0].Primary { - t.Fatalf("expected ip to be 192.168.0.1 and Primary, but got %v, %t", *result[0].PrivateIpAddress, *result[0].Primary) + if aws.StringValue(result[0].PrivateIpAddress) != "192.168.0.1" || !aws.BoolValue(result[0].Primary) { + t.Fatalf("expected ip to be 192.168.0.1 and Primary, but got %v, %t", aws.StringValue(result[0].PrivateIpAddress), aws.BoolValue(result[0].Primary)) } - if *result[1].PrivateIpAddress != "192.168.0.2" || *result[1].Primary { - t.Fatalf("expected ip to be 192.168.0.2 and not Primary, but got %v, %t", *result[1].PrivateIpAddress, *result[1].Primary) + if aws.StringValue(result[1].PrivateIpAddress) != "192.168.0.2" || aws.BoolValue(result[1].Primary) { + t.Fatalf("expected ip to be 192.168.0.2 and not Primary, but got %v, %t", aws.StringValue(result[1].PrivateIpAddress), aws.BoolValue(result[1].Primary)) } } @@ -1159,10 +1150,7 @@ func TestExpandPolicyAttributes(t *testing.T) { "value": "true", }, } - attributes, err := expandPolicyAttributes(expanded) - if err != nil { - t.Fatalf("bad: %#v", err) - } + attributes := expandPolicyAttributes(expanded) if len(attributes) != 3 { t.Fatalf("expected number of attributes to be 3, but got %d", len(attributes)) @@ -1188,10 +1176,7 @@ func TestExpandPolicyAttributes_invalid(t *testing.T) { "value": "true", }, } - attributes, err := expandPolicyAttributes(expanded) - if err != nil { - t.Fatalf("bad: %#v", err) - } + attributes := expandPolicyAttributes(expanded) expected := &elb.PolicyAttribute{ AttributeName: aws.String("Protocol-TLSv1.2"), @@ -1209,10 +1194,7 @@ func TestExpandPolicyAttributes_invalid(t *testing.T) { func TestExpandPolicyAttributes_empty(t *testing.T) { var expanded []interface{} - attributes, err := expandPolicyAttributes(expanded) - if err != nil { - t.Fatalf("bad: %#v", err) - } + attributes := expandPolicyAttributes(expanded) if len(attributes) != 0 { t.Fatalf("expected number of attributes to be 0, but got %d", len(attributes)) @@ -1629,57 +1611,10 @@ const testExampleXML_from_msdn_flawed = ` ` -func TestExpandRdsClusterScalingConfiguration_serverless(t *testing.T) { - type testCase struct { - EngineMode string - Input []interface{} - Expected *rds.ScalingConfiguration - } - cases := []testCase{ - { - EngineMode: "serverless", - Input: []interface{}{ - map[string]interface{}{ - "auto_pause": false, - "max_capacity": 32, - "min_capacity": 4, - "seconds_until_auto_pause": 600, - "timeout_action": "ForceApplyCapacityChange", - }, - }, - Expected: &rds.ScalingConfiguration{ - AutoPause: aws.Bool(false), - MaxCapacity: aws.Int64(32), - MinCapacity: aws.Int64(4), - SecondsUntilAutoPause: aws.Int64(600), - TimeoutAction: aws.String("ForceApplyCapacityChange"), - }, - }, - { - EngineMode: "serverless", - Input: []interface{}{}, - Expected: &rds.ScalingConfiguration{ - MinCapacity: aws.Int64(2), - }, - }, - { - EngineMode: "serverless", - Input: []interface{}{ - nil, - }, - Expected: &rds.ScalingConfiguration{ - MinCapacity: aws.Int64(2), - }, - }, - } - - for _, tc := range cases { - output := expandRdsClusterScalingConfiguration(tc.Input, tc.EngineMode) - if !reflect.DeepEqual(output, tc.Expected) { - t.Errorf("EngineMode: %s\nExpected: %v,\nGot: %v", tc.EngineMode, tc.Expected, output) - } - } -} +// TestExpandRdsClusterScalingConfiguration_serverless removed in v3.0.0 +// as all engine_modes are treated equal when expanding scaling_configuration +// and an override of min_capacity is no longer needed +// Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/11698 func TestExpandRdsClusterScalingConfiguration_basic(t *testing.T) { type testCase struct { @@ -1691,7 +1626,7 @@ func TestExpandRdsClusterScalingConfiguration_basic(t *testing.T) { // RDS Cluster Scaling Configuration is only valid for serverless, but we're relying on AWS errors. // If Terraform adds whole-resource validation, we can do our own validation at plan time. - for _, engineMode := range []string{"global", "multimaster", "parallelquery", "provisioned"} { + for _, engineMode := range []string{"global", "multimaster", "parallelquery", "provisioned", "serverless"} { cases = append(cases, []testCase{ { EngineMode: engineMode, @@ -1721,7 +1656,7 @@ func TestExpandRdsClusterScalingConfiguration_basic(t *testing.T) { } for _, tc := range cases { - output := expandRdsClusterScalingConfiguration(tc.Input, tc.EngineMode) + output := expandRdsClusterScalingConfiguration(tc.Input) if tc.ExpectNil != (output == nil) { t.Errorf("EngineMode %q: Expected nil: %t, Got: %v", tc.EngineMode, tc.ExpectNil, output) } diff --git a/aws/tags.go b/aws/tags.go index c35f62ef62d..8abb4db0c55 100644 --- a/aws/tags.go +++ b/aws/tags.go @@ -3,7 +3,7 @@ package aws import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags" ) @@ -13,6 +13,7 @@ func tagsSchema() *schema.Schema { return &schema.Schema{ Type: schema.TypeMap, Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, } } @@ -21,6 +22,7 @@ func tagsSchemaComputed() *schema.Schema { Type: schema.TypeMap, Optional: true, Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, } } @@ -29,6 +31,7 @@ func tagsSchemaForceNew() *schema.Schema { Type: schema.TypeMap, Optional: true, ForceNew: true, + Elem: &schema.Schema{Type: schema.TypeString}, } } diff --git a/files/mysql-5-6-xtrabackup.tar.gz b/aws/testdata/mysql-5-6-xtrabackup.tar.gz similarity index 100% rename from files/mysql-5-6-xtrabackup.tar.gz rename to aws/testdata/mysql-5-6-xtrabackup.tar.gz diff --git a/aws/utils.go b/aws/utils.go index 262d8c8a0c5..bb39a679164 100644 --- a/aws/utils.go +++ b/aws/utils.go @@ -6,7 +6,7 @@ import ( "reflect" "regexp" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) // Base64Encode encodes data if the input isn't already encoded using base64.StdEncoding.EncodeToString. diff --git a/aws/validators.go b/aws/validators.go index 5b1b685d960..b146c8445b8 100644 --- a/aws/validators.go +++ b/aws/validators.go @@ -16,10 +16,10 @@ import ( "github.com/aws/aws-sdk-go/service/configservice" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" - "github.com/hashicorp/terraform-plugin-sdk/helper/validation" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) const ( @@ -725,22 +725,114 @@ func validatePolicyStatementId(v interface{}, k string) (ws []string, errors []e // validateCIDRNetworkAddress ensures that the string value is a valid CIDR that // represents a network address - it adds an error otherwise func validateCIDRNetworkAddress(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 parsing: %s", k, err)) + if err := validateCIDRBlock(v.(string)); err != nil { + errors = append(errors, err) return } - if ipnet == nil || value != ipnet.String() { - errors = append(errors, fmt.Errorf( - "%q must contain a valid network CIDR, got %q", k, value)) + return +} + +// validateIpv4CIDRNetworkAddress ensures that the string value is a valid IPv4 CIDR that +// represents a network address - it adds an error otherwise +func validateIpv4CIDRNetworkAddress(v interface{}, k string) (ws []string, errors []error) { + if err := validateIpv4CIDRBlock(v.(string)); err != nil { + errors = append(errors, err) + return + } + + return +} + +// validateIpv6CIDRNetworkAddress ensures that the string value is a valid IPv6 CIDR that +// represents a network address - it adds an error otherwise +func validateIpv6CIDRNetworkAddress(v interface{}, k string) (ws []string, errors []error) { + if err := validateIpv6CIDRBlock(v.(string)); err != nil { + errors = append(errors, err) + return } return } +// validateCIDRBlock validates that the specified CIDR block is valid: +// - The CIDR block parses to an IP address and network +// - The CIDR block is the CIDR block for the network +func validateCIDRBlock(cidr string) error { + _, ipnet, err := net.ParseCIDR(cidr) + if err != nil { + return fmt.Errorf("%q is not a valid CIDR block: %w", cidr, err) + } + + if !cidrBlocksEqual(cidr, ipnet.String()) { + return fmt.Errorf("%q is not a valid CIDR block; did you mean %q?", cidr, ipnet) + } + + return nil +} + +// validateIpv4CIDRBlock validates that the specified CIDR block is valid: +// - The CIDR block parses to an IP address and network +// - The IP address is an IPv4 address +// - The CIDR block is the CIDR block for the network +func validateIpv4CIDRBlock(cidr string) error { + ip, ipnet, err := net.ParseCIDR(cidr) + if err != nil { + return fmt.Errorf("%q is not a valid CIDR block: %w", cidr, err) + } + + ipv4 := ip.To4() + if ipv4 == nil { + return fmt.Errorf("%q is not a valid IPv4 CIDR block", cidr) + } + + if !cidrBlocksEqual(cidr, ipnet.String()) { + return fmt.Errorf("%q is not a valid IPv4 CIDR block; did you mean %q?", cidr, ipnet) + } + + return nil +} + +// validateIpv6CIDRBlock validates that the specified CIDR block is valid: +// - The CIDR block parses to an IP address and network +// - The IP address is an IPv6 address +// - The CIDR block is the CIDR block for the network +func validateIpv6CIDRBlock(cidr string) error { + ip, ipnet, err := net.ParseCIDR(cidr) + if err != nil { + return fmt.Errorf("%q is not a valid CIDR block: %w", cidr, err) + } + + ipv4 := ip.To4() + if ipv4 != nil { + return fmt.Errorf("%q is not a valid IPv6 CIDR block", cidr) + } + + if !cidrBlocksEqual(cidr, ipnet.String()) { + return fmt.Errorf("%q is not a valid IPv6 CIDR block; did you mean %q?", cidr, ipnet) + } + + return nil +} + +// cidrBlocksEqual returns whether or not two CIDR blocks are equal: +// - Both CIDR blocks parse to an IP address and network +// - The string representation of the IP addresses are equal +// - The string representation of the networks are equal +// This function is especially useful for IPv6 CIDR blocks which have multiple valid representations. +func cidrBlocksEqual(cidr1, cidr2 string) bool { + ip1, ipnet1, err := net.ParseCIDR(cidr1) + if err != nil { + return false + } + ip2, ipnet2, err := net.ParseCIDR(cidr2) + if err != nil { + return false + } + + return ip2.String() == ip1.String() && ipnet2.String() == ipnet1.String() +} + func validateHTTPMethod() schema.SchemaValidateFunc { return validation.StringInSlice([]string{ "ANY", @@ -2034,6 +2126,21 @@ func validateAmazonSideAsn(v interface{}, k string) (ws []string, errors []error return } +func validate4ByteAsn(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + + asn, err := strconv.ParseInt(value, 10, 64) + if err != nil { + errors = append(errors, fmt.Errorf("%q (%q) must be a 64-bit integer", k, v)) + return + } + + if asn < 0 || asn > 4294967295 { + errors = append(errors, fmt.Errorf("%q (%q) must be in the range 0 to 4294967295", k, v)) + } + return +} + func validateIotThingTypeName(v interface{}, k string) (ws []string, errors []error) { value := v.(string) if !regexp.MustCompile(`[a-zA-Z0-9:_-]+`).MatchString(value) { diff --git a/aws/validators_test.go b/aws/validators_test.go index 05a2b73c327..ec996f73152 100644 --- a/aws/validators_test.go +++ b/aws/validators_test.go @@ -3,7 +3,7 @@ package aws import ( "fmt" "github.com/aws/aws-sdk-go/service/cognitoidentity" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "regexp" "strings" "testing" @@ -425,9 +425,11 @@ func TestValidateCIDRNetworkAddress(t *testing.T) { CIDR string ExpectedErrSubstr string }{ - {"notacidr", `must contain a valid CIDR`}, - {"10.0.1.0/16", `must contain a valid network CIDR`}, + {"notacidr", `is not a valid CIDR block`}, + {"10.0.1.0/16", `is not a valid CIDR block; did you mean`}, {"10.0.1.0/24", ``}, + {"2001:db8::/122", ``}, + {"2001::/15", `is not a valid CIDR block; did you mean`}, } for i, tc := range cases { @@ -450,6 +452,98 @@ func TestValidateCIDRNetworkAddress(t *testing.T) { } } +func Test_validateCIDRBlock(t *testing.T) { + for _, ts := range []struct { + cidr string + valid bool + }{ + {"10.2.2.0/24", true}, + {"10.2.2.0/1234", false}, + {"10.2.2.2/24", false}, + {"::/0", true}, + {"::0/0", true}, + {"2000::/15", true}, + {"2001::/15", false}, + {"", false}, + } { + err := validateCIDRBlock(ts.cidr) + if !ts.valid && err == nil { + t.Fatalf("Input '%s' should error but didn't!", ts.cidr) + } + if ts.valid && err != nil { + t.Fatalf("Got unexpected error for '%s' input: %s", ts.cidr, err) + } + } +} + +func Test_validateIpv4CIDRBlock(t *testing.T) { + for _, ts := range []struct { + cidr string + valid bool + }{ + {"10.2.2.0/24", true}, + {"10.2.2.0/1234", false}, + {"10/24", false}, + {"10.2.2.2/24", false}, + {"::/0", false}, + {"2000::/15", false}, + {"", false}, + } { + err := validateIpv4CIDRBlock(ts.cidr) + if !ts.valid && err == nil { + t.Fatalf("Input '%s' should error but didn't!", ts.cidr) + } + if ts.valid && err != nil { + t.Fatalf("Got unexpected error for '%s' input: %s", ts.cidr, err) + } + } +} + +func Test_validateIpv6CIDRBlock(t *testing.T) { + for _, ts := range []struct { + cidr string + valid bool + }{ + {"10.2.2.0/24", false}, + {"10.2.2.0/1234", false}, + {"::/0", true}, + {"::0/0", true}, + {"2000::/15", true}, + {"2001::/15", false}, + {"2001:db8::/122", true}, + {"", false}, + } { + err := validateIpv6CIDRBlock(ts.cidr) + if !ts.valid && err == nil { + t.Fatalf("Input '%s' should error but didn't!", ts.cidr) + } + if ts.valid && err != nil { + t.Fatalf("Got unexpected error for '%s' input: %s", ts.cidr, err) + } + } +} + +func Test_cidrBlocksEqual(t *testing.T) { + for _, ts := range []struct { + cidr1 string + cidr2 string + equal bool + }{ + {"10.2.2.0/24", "10.2.2.0/24", true}, + {"10.2.2.0/1234", "10.2.2.0/24", false}, + {"10.2.2.0/24", "10.2.2.0/1234", false}, + {"2001::/15", "2001::/15", true}, + {"::/0", "2001::/15", false}, + {"::/0", "::0/0", true}, + {"", "", false}, + } { + equal := cidrBlocksEqual(ts.cidr1, ts.cidr2) + if ts.equal != equal { + t.Fatalf("cidrBlocksEqual(%q, %q) should be: %t", ts.cidr1, ts.cidr2, ts.equal) + } + } +} + func TestValidateLogMetricFilterName(t *testing.T) { validNames := []string{ "YadaHereAndThere", @@ -2633,6 +2727,37 @@ func TestValidateAmazonSideAsn(t *testing.T) { } } +func TestValidate4ByteAsn(t *testing.T) { + validAsns := []string{ + "0", + "1", + "65534", + "65535", + "4294967294", + "4294967295", + } + for _, v := range validAsns { + _, errors := validate4ByteAsn(v, "bgp_asn") + if len(errors) != 0 { + t.Fatalf("%q should be a valid ASN: %q", v, errors) + } + } + + invalidAsns := []string{ + "-1", + "ABCDEFG", + "", + "4294967296", + "9999999999", + } + for _, v := range invalidAsns { + _, errors := validate4ByteAsn(v, "bgp_asn") + if len(errors) == 0 { + t.Fatalf("%q should be an invalid ASN", v) + } + } +} + func TestValidateLaunchTemplateName(t *testing.T) { validNames := []string{ "fooBAR123", diff --git a/aws/waf_helpers.go b/aws/waf_helpers.go index 917f44f480f..9a4e22ac00a 100644 --- a/aws/waf_helpers.go +++ b/aws/waf_helpers.go @@ -7,8 +7,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/terraform-providers/terraform-provider-aws/aws/internal/hashcode" ) func wafSizeConstraintSetSchema() map[string]*schema.Schema { @@ -28,7 +28,7 @@ func wafSizeConstraintSetSchema() map[string]*schema.Schema { Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "field_to_match": { - Type: schema.TypeSet, + Type: schema.TypeList, Required: true, MaxItems: 1, Elem: &schema.Resource{ @@ -76,7 +76,7 @@ func diffWafSizeConstraints(oldS, newS []interface{}) []*waf.SizeConstraintSetUp updates = append(updates, &waf.SizeConstraintSetUpdate{ Action: aws.String(waf.ChangeActionDelete), SizeConstraint: &waf.SizeConstraint{ - FieldToMatch: expandFieldToMatch(constraint["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), + FieldToMatch: expandFieldToMatch(constraint["field_to_match"].([]interface{})[0].(map[string]interface{})), ComparisonOperator: aws.String(constraint["comparison_operator"].(string)), Size: aws.Int64(int64(constraint["size"].(int))), TextTransformation: aws.String(constraint["text_transformation"].(string)), @@ -90,7 +90,7 @@ func diffWafSizeConstraints(oldS, newS []interface{}) []*waf.SizeConstraintSetUp updates = append(updates, &waf.SizeConstraintSetUpdate{ Action: aws.String(waf.ChangeActionInsert), SizeConstraint: &waf.SizeConstraint{ - FieldToMatch: expandFieldToMatch(constraint["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})), + FieldToMatch: expandFieldToMatch(constraint["field_to_match"].([]interface{})[0].(map[string]interface{})), ComparisonOperator: aws.String(constraint["comparison_operator"].(string)), Size: aws.Int64(int64(constraint["size"].(int))), TextTransformation: aws.String(constraint["text_transformation"].(string)), diff --git a/aws/waf_token_handlers.go b/aws/waf_token_handlers.go index 31fe92b4259..729a7642a2d 100644 --- a/aws/waf_token_handlers.go +++ b/aws/waf_token_handlers.go @@ -6,7 +6,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/waf" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) type WafRetryer struct { diff --git a/aws/wafregionl_token_handlers.go b/aws/wafregionl_token_handlers.go index 30ace061288..0c9cb6e4d2e 100644 --- a/aws/wafregionl_token_handlers.go +++ b/aws/wafregionl_token_handlers.go @@ -7,7 +7,7 @@ import ( "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-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) type WafRegionalRetryer struct { diff --git a/aws/wafv2_helper.go b/aws/wafv2_helper.go new file mode 100644 index 00000000000..4c85ed08cbb --- /dev/null +++ b/aws/wafv2_helper.go @@ -0,0 +1,1061 @@ +package aws + +import ( + "math" + "regexp" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/wafv2" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func wafv2EmptySchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{}, + }, + } +} + +func wafv2RootStatementSchema(level int) *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "and_statement": wafv2StatementSchema(level - 1), + "byte_match_statement": wafv2ByteMatchStatementSchema(), + "geo_match_statement": wafv2GeoMatchStatementSchema(), + "ip_set_reference_statement": wafv2IpSetReferenceStatementSchema(), + "not_statement": wafv2StatementSchema(level - 1), + "or_statement": wafv2StatementSchema(level - 1), + "regex_pattern_set_reference_statement": wafv2RegexPatternSetReferenceStatementSchema(), + "size_constraint_statement": wafv2SizeConstraintSchema(), + "sqli_match_statement": wafv2SqliMatchStatementSchema(), + "xss_match_statement": wafv2XssMatchStatementSchema(), + }, + }, + } +} + +func wafv2StatementSchema(level int) *schema.Schema { + if level > 1 { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "statement": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "and_statement": wafv2StatementSchema(level - 1), + "byte_match_statement": wafv2ByteMatchStatementSchema(), + "geo_match_statement": wafv2GeoMatchStatementSchema(), + "ip_set_reference_statement": wafv2IpSetReferenceStatementSchema(), + "not_statement": wafv2StatementSchema(level - 1), + "or_statement": wafv2StatementSchema(level - 1), + "regex_pattern_set_reference_statement": wafv2RegexPatternSetReferenceStatementSchema(), + "size_constraint_statement": wafv2SizeConstraintSchema(), + "sqli_match_statement": wafv2SqliMatchStatementSchema(), + "xss_match_statement": wafv2XssMatchStatementSchema(), + }, + }, + }, + }, + }, + } + } + + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "statement": { + Type: schema.TypeList, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "byte_match_statement": wafv2ByteMatchStatementSchema(), + "geo_match_statement": wafv2GeoMatchStatementSchema(), + "ip_set_reference_statement": wafv2IpSetReferenceStatementSchema(), + "regex_pattern_set_reference_statement": wafv2RegexPatternSetReferenceStatementSchema(), + "size_constraint_statement": wafv2SizeConstraintSchema(), + "sqli_match_statement": wafv2SqliMatchStatementSchema(), + "xss_match_statement": wafv2XssMatchStatementSchema(), + }, + }, + }, + }, + }, + } +} + +func wafv2ByteMatchStatementSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "field_to_match": wafv2FieldToMatchSchema(), + "positional_constraint": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + wafv2.PositionalConstraintContains, + wafv2.PositionalConstraintContainsWord, + wafv2.PositionalConstraintEndsWith, + wafv2.PositionalConstraintExactly, + wafv2.PositionalConstraintStartsWith, + }, false), + }, + "search_string": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringLenBetween(1, 200), + }, + "text_transformation": wafv2TextTransformationSchema(), + }, + }, + } +} + +func wafv2GeoMatchStatementSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "country_codes": { + Type: schema.TypeList, + Required: true, + MinItems: 1, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + } +} + +func wafv2IpSetReferenceStatementSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateArn, + }, + }, + }, + } +} + +func wafv2RegexPatternSetReferenceStatementSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "arn": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validateArn, + }, + "field_to_match": wafv2FieldToMatchSchema(), + "text_transformation": wafv2TextTransformationSchema(), + }, + }, + } +} + +func wafv2SizeConstraintSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "comparison_operator": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + wafv2.ComparisonOperatorEq, + wafv2.ComparisonOperatorGe, + wafv2.ComparisonOperatorGt, + wafv2.ComparisonOperatorLe, + wafv2.ComparisonOperatorLt, + wafv2.ComparisonOperatorNe, + }, false), + }, + "field_to_match": wafv2FieldToMatchSchema(), + "size": { + Type: schema.TypeInt, + Required: true, + ValidateFunc: validation.IntBetween(0, math.MaxInt32), + }, + "text_transformation": wafv2TextTransformationSchema(), + }, + }, + } +} + +func wafv2SqliMatchStatementSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "field_to_match": wafv2FieldToMatchSchema(), + "text_transformation": wafv2TextTransformationSchema(), + }, + }, + } +} + +func wafv2XssMatchStatementSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "field_to_match": wafv2FieldToMatchSchema(), + "text_transformation": wafv2TextTransformationSchema(), + }, + }, + } +} +func wafv2FieldToMatchBaseSchema() *schema.Resource { + return &schema.Resource{ + Schema: map[string]*schema.Schema{ + "all_query_arguments": wafv2EmptySchema(), + "body": wafv2EmptySchema(), + "method": wafv2EmptySchema(), + "query_string": wafv2EmptySchema(), + "single_header": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 40), + // The value is returned in lower case by the API. + // Trying to solve it with StateFunc and/or DiffSuppressFunc resulted in hash problem of the rule field or didn't work. + validation.StringMatch(regexp.MustCompile(`^[a-z0-9-_]+$`), "must contain only lowercase alphanumeric characters, underscores, and hyphens"), + ), + }, + }, + }, + }, + "single_query_argument": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 30), + // The value is returned in lower case by the API. + // Trying to solve it with StateFunc and/or DiffSuppressFunc resulted in hash problem of the rule field or didn't work. + validation.StringMatch(regexp.MustCompile(`^[a-z0-9-_]+$`), "must contain only lowercase alphanumeric characters, underscores, and hyphens"), + ), + }, + }, + }, + }, + "uri_path": wafv2EmptySchema(), + }, + } +} + +func wafv2FieldToMatchSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: wafv2FieldToMatchBaseSchema(), + } +} + +func wafv2TextTransformationSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeSet, + Required: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "priority": { + Type: schema.TypeInt, + Required: true, + }, + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringInSlice([]string{ + wafv2.TextTransformationTypeCmdLine, + wafv2.TextTransformationTypeCompressWhiteSpace, + wafv2.TextTransformationTypeHtmlEntityDecode, + wafv2.TextTransformationTypeLowercase, + wafv2.TextTransformationTypeNone, + wafv2.TextTransformationTypeUrlDecode, + }, false), + }, + }, + }, + } +} + +func wafv2VisibilityConfigSchema() *schema.Schema { + return &schema.Schema{ + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cloudwatch_metrics_enabled": { + Type: schema.TypeBool, + Required: true, + }, + "metric_name": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.All( + validation.StringLenBetween(1, 128), + validation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9-_]+$`), "must contain only alphanumeric hyphen and underscore characters"), + ), + }, + "sampled_requests_enabled": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, + } +} + +func expandWafv2Rules(l []interface{}) []*wafv2.Rule { + if len(l) == 0 || l[0] == nil { + return nil + } + + rules := make([]*wafv2.Rule, 0) + + for _, rule := range l { + if rule == nil { + continue + } + rules = append(rules, expandWafv2Rule(rule.(map[string]interface{}))) + } + + return rules +} + +func expandWafv2Rule(m map[string]interface{}) *wafv2.Rule { + if m == nil { + return nil + } + + return &wafv2.Rule{ + Name: aws.String(m["name"].(string)), + Priority: aws.Int64(int64(m["priority"].(int))), + Action: expandWafv2RuleAction(m["action"].([]interface{})), + Statement: expandWafv2RootStatement(m["statement"].([]interface{})), + VisibilityConfig: expandWafv2VisibilityConfig(m["visibility_config"].([]interface{})), + } +} + +func expandWafv2RuleAction(l []interface{}) *wafv2.RuleAction { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + action := &wafv2.RuleAction{} + + if v, ok := m["allow"]; ok && len(v.([]interface{})) > 0 { + action.Allow = &wafv2.AllowAction{} + } + + if v, ok := m["block"]; ok && len(v.([]interface{})) > 0 { + action.Block = &wafv2.BlockAction{} + } + + if v, ok := m["count"]; ok && len(v.([]interface{})) > 0 { + action.Count = &wafv2.CountAction{} + } + + return action +} + +func expandWafv2VisibilityConfig(l []interface{}) *wafv2.VisibilityConfig { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + configuration := &wafv2.VisibilityConfig{} + + if v, ok := m["cloudwatch_metrics_enabled"]; ok { + configuration.CloudWatchMetricsEnabled = aws.Bool(v.(bool)) + } + + if v, ok := m["metric_name"]; ok && len(v.(string)) > 0 { + configuration.MetricName = aws.String(v.(string)) + } + + if v, ok := m["sampled_requests_enabled"]; ok { + configuration.SampledRequestsEnabled = aws.Bool(v.(bool)) + } + + return configuration +} + +func expandWafv2RootStatement(l []interface{}) *wafv2.Statement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return expandWafv2Statement(m) +} + +func expandWafv2Statements(l []interface{}) []*wafv2.Statement { + if len(l) == 0 || l[0] == nil { + return nil + } + + statements := make([]*wafv2.Statement, 0) + + for _, statement := range l { + if statement == nil { + continue + } + statements = append(statements, expandWafv2Statement(statement.(map[string]interface{}))) + } + + return statements +} + +func expandWafv2Statement(m map[string]interface{}) *wafv2.Statement { + if m == nil { + return nil + } + + statement := &wafv2.Statement{} + + if v, ok := m["and_statement"]; ok { + statement.AndStatement = expandWafv2AndStatement(v.([]interface{})) + } + + if v, ok := m["byte_match_statement"]; ok { + statement.ByteMatchStatement = expandWafv2ByteMatchStatement(v.([]interface{})) + } + + if v, ok := m["ip_set_reference_statement"]; ok { + statement.IPSetReferenceStatement = expandWafv2IpSetReferenceStatement(v.([]interface{})) + } + + if v, ok := m["geo_match_statement"]; ok { + statement.GeoMatchStatement = expandWafv2GeoMatchStatement(v.([]interface{})) + } + + if v, ok := m["not_statement"]; ok { + statement.NotStatement = expandWafv2NotStatement(v.([]interface{})) + } + + if v, ok := m["or_statement"]; ok { + statement.OrStatement = expandWafv2OrStatement(v.([]interface{})) + } + + if v, ok := m["regex_pattern_set_reference_statement"]; ok { + statement.RegexPatternSetReferenceStatement = expandWafv2RegexPatternSetReferenceStatement(v.([]interface{})) + } + + if v, ok := m["size_constraint_statement"]; ok { + statement.SizeConstraintStatement = expandWafv2SizeConstraintStatement(v.([]interface{})) + } + + if v, ok := m["sqli_match_statement"]; ok { + statement.SqliMatchStatement = expandWafv2SqliMatchStatement(v.([]interface{})) + } + + if v, ok := m["xss_match_statement"]; ok { + statement.XssMatchStatement = expandWafv2XssMatchStatement(v.([]interface{})) + } + + return statement +} + +func expandWafv2AndStatement(l []interface{}) *wafv2.AndStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.AndStatement{ + Statements: expandWafv2Statements(m["statement"].([]interface{})), + } +} + +func expandWafv2ByteMatchStatement(l []interface{}) *wafv2.ByteMatchStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.ByteMatchStatement{ + FieldToMatch: expandWafv2FieldToMatch(m["field_to_match"].([]interface{})), + PositionalConstraint: aws.String(m["positional_constraint"].(string)), + SearchString: []byte(m["search_string"].(string)), + TextTransformations: expandWafv2TextTransformations(m["text_transformation"].(*schema.Set).List()), + } +} + +func expandWafv2FieldToMatch(l []interface{}) *wafv2.FieldToMatch { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + f := &wafv2.FieldToMatch{} + + if v, ok := m["all_query_arguments"]; ok && len(v.([]interface{})) > 0 { + f.AllQueryArguments = &wafv2.AllQueryArguments{} + } + + if v, ok := m["body"]; ok && len(v.([]interface{})) > 0 { + f.Body = &wafv2.Body{} + } + + if v, ok := m["method"]; ok && len(v.([]interface{})) > 0 { + f.Method = &wafv2.Method{} + } + + if v, ok := m["query_string"]; ok && len(v.([]interface{})) > 0 { + f.QueryString = &wafv2.QueryString{} + } + + if v, ok := m["single_header"]; ok && len(v.([]interface{})) > 0 { + f.SingleHeader = expandWafv2SingleHeader(m["single_header"].([]interface{})) + } + + if v, ok := m["single_query_argument"]; ok && len(v.([]interface{})) > 0 { + f.SingleQueryArgument = expandWafv2SingleQueryArgument(m["single_query_argument"].([]interface{})) + } + + if v, ok := m["uri_path"]; ok && len(v.([]interface{})) > 0 { + f.UriPath = &wafv2.UriPath{} + } + + return f +} + +func expandWafv2SingleHeader(l []interface{}) *wafv2.SingleHeader { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.SingleHeader{ + Name: aws.String(m["name"].(string)), + } +} + +func expandWafv2SingleQueryArgument(l []interface{}) *wafv2.SingleQueryArgument { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.SingleQueryArgument{ + Name: aws.String(m["name"].(string)), + } +} + +func expandWafv2TextTransformations(l []interface{}) []*wafv2.TextTransformation { + if len(l) == 0 || l[0] == nil { + return nil + } + + rules := make([]*wafv2.TextTransformation, 0) + + for _, rule := range l { + if rule == nil { + continue + } + rules = append(rules, expandWafv2TextTransformation(rule.(map[string]interface{}))) + } + + return rules +} + +func expandWafv2TextTransformation(m map[string]interface{}) *wafv2.TextTransformation { + if m == nil { + return nil + } + + return &wafv2.TextTransformation{ + Priority: aws.Int64(int64(m["priority"].(int))), + Type: aws.String(m["type"].(string)), + } +} + +func expandWafv2IpSetReferenceStatement(l []interface{}) *wafv2.IPSetReferenceStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.IPSetReferenceStatement{ + ARN: aws.String(m["arn"].(string)), + } +} + +func expandWafv2GeoMatchStatement(l []interface{}) *wafv2.GeoMatchStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.GeoMatchStatement{ + CountryCodes: expandStringList(m["country_codes"].([]interface{})), + } +} + +func expandWafv2NotStatement(l []interface{}) *wafv2.NotStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + s := m["statement"].([]interface{}) + + if len(s) == 0 || s[0] == nil { + return nil + } + + m = s[0].(map[string]interface{}) + + return &wafv2.NotStatement{ + Statement: expandWafv2Statement(m), + } +} + +func expandWafv2OrStatement(l []interface{}) *wafv2.OrStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.OrStatement{ + Statements: expandWafv2Statements(m["statement"].([]interface{})), + } +} + +func expandWafv2RegexPatternSetReferenceStatement(l []interface{}) *wafv2.RegexPatternSetReferenceStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.RegexPatternSetReferenceStatement{ + ARN: aws.String(m["arn"].(string)), + FieldToMatch: expandWafv2FieldToMatch(m["field_to_match"].([]interface{})), + TextTransformations: expandWafv2TextTransformations(m["text_transformation"].(*schema.Set).List()), + } +} + +func expandWafv2SizeConstraintStatement(l []interface{}) *wafv2.SizeConstraintStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.SizeConstraintStatement{ + ComparisonOperator: aws.String(m["comparison_operator"].(string)), + FieldToMatch: expandWafv2FieldToMatch(m["field_to_match"].([]interface{})), + Size: aws.Int64(int64(m["size"].(int))), + TextTransformations: expandWafv2TextTransformations(m["text_transformation"].(*schema.Set).List()), + } +} + +func expandWafv2SqliMatchStatement(l []interface{}) *wafv2.SqliMatchStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.SqliMatchStatement{ + FieldToMatch: expandWafv2FieldToMatch(m["field_to_match"].([]interface{})), + TextTransformations: expandWafv2TextTransformations(m["text_transformation"].(*schema.Set).List()), + } +} + +func expandWafv2XssMatchStatement(l []interface{}) *wafv2.XssMatchStatement { + if len(l) == 0 || l[0] == nil { + return nil + } + + m := l[0].(map[string]interface{}) + + return &wafv2.XssMatchStatement{ + FieldToMatch: expandWafv2FieldToMatch(m["field_to_match"].([]interface{})), + TextTransformations: expandWafv2TextTransformations(m["text_transformation"].(*schema.Set).List()), + } +} + +func flattenWafv2Rules(r []*wafv2.Rule) interface{} { + out := make([]map[string]interface{}, len(r)) + for i, rule := range r { + m := make(map[string]interface{}) + m["action"] = flattenWafv2RuleAction(rule.Action) + m["name"] = aws.StringValue(rule.Name) + m["priority"] = int(aws.Int64Value(rule.Priority)) + m["statement"] = flattenWafv2RootStatement(rule.Statement) + m["visibility_config"] = flattenWafv2VisibilityConfig(rule.VisibilityConfig) + out[i] = m + } + + return out +} + +func flattenWafv2RuleAction(a *wafv2.RuleAction) interface{} { + if a == nil { + return []interface{}{} + } + + m := map[string]interface{}{} + + if a.Allow != nil { + m["allow"] = make([]map[string]interface{}, 1) + } + + if a.Block != nil { + m["block"] = make([]map[string]interface{}, 1) + } + + if a.Count != nil { + m["count"] = make([]map[string]interface{}, 1) + } + + return []interface{}{m} +} + +func flattenWafv2RootStatement(s *wafv2.Statement) interface{} { + if s == nil { + return []interface{}{} + } + + return []interface{}{flattenWafv2Statement(s)} +} + +func flattenWafv2Statements(s []*wafv2.Statement) interface{} { + out := make([]interface{}, len(s)) + for i, statement := range s { + out[i] = flattenWafv2Statement(statement) + } + + return out +} + +func flattenWafv2Statement(s *wafv2.Statement) map[string]interface{} { + if s == nil { + return map[string]interface{}{} + } + + m := map[string]interface{}{} + + if s.AndStatement != nil { + m["and_statement"] = flattenWafv2AndStatement(s.AndStatement) + } + + if s.ByteMatchStatement != nil { + m["byte_match_statement"] = flattenWafv2ByteMatchStatement(s.ByteMatchStatement) + } + + if s.IPSetReferenceStatement != nil { + m["ip_set_reference_statement"] = flattenWafv2IpSetReferenceStatement(s.IPSetReferenceStatement) + } + + if s.GeoMatchStatement != nil { + m["geo_match_statement"] = flattenWafv2GeoMatchStatement(s.GeoMatchStatement) + } + + if s.NotStatement != nil { + m["not_statement"] = flattenWafv2NotStatement(s.NotStatement) + } + + if s.OrStatement != nil { + m["or_statement"] = flattenWafv2OrStatement(s.OrStatement) + } + + if s.RegexPatternSetReferenceStatement != nil { + m["regex_pattern_set_reference_statement"] = flattenWafv2RegexPatternSetReferenceStatement(s.RegexPatternSetReferenceStatement) + } + + if s.SizeConstraintStatement != nil { + m["size_constraint_statement"] = flattenWafv2SizeConstraintStatement(s.SizeConstraintStatement) + } + + if s.SqliMatchStatement != nil { + m["sqli_match_statement"] = flattenWafv2SqliMatchStatement(s.SqliMatchStatement) + } + + if s.XssMatchStatement != nil { + m["xss_match_statement"] = flattenWafv2XssMatchStatement(s.XssMatchStatement) + } + + return m +} + +func flattenWafv2AndStatement(a *wafv2.AndStatement) interface{} { + if a == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "statement": flattenWafv2Statements(a.Statements), + } + + return []interface{}{m} +} + +func flattenWafv2ByteMatchStatement(b *wafv2.ByteMatchStatement) interface{} { + if b == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "field_to_match": flattenWafv2FieldToMatch(b.FieldToMatch), + "positional_constraint": aws.StringValue(b.PositionalConstraint), + "search_string": string(b.SearchString), + "text_transformation": flattenWafv2TextTransformations(b.TextTransformations), + } + + return []interface{}{m} +} + +func flattenWafv2FieldToMatch(f *wafv2.FieldToMatch) interface{} { + if f == nil { + return []interface{}{} + } + + m := map[string]interface{}{} + + if f.AllQueryArguments != nil { + m["all_query_arguments"] = make([]map[string]interface{}, 1) + } + + if f.Body != nil { + m["body"] = make([]map[string]interface{}, 1) + } + + if f.Method != nil { + m["method"] = make([]map[string]interface{}, 1) + } + + if f.QueryString != nil { + m["query_string"] = make([]map[string]interface{}, 1) + } + + if f.SingleHeader != nil { + m["single_header"] = flattenWafv2SingleHeader(f.SingleHeader) + } + + if f.SingleQueryArgument != nil { + m["single_query_argument"] = flattenWafv2SingleQueryArgument(f.SingleQueryArgument) + } + + if f.UriPath != nil { + m["uri_path"] = make([]map[string]interface{}, 1) + } + + return []interface{}{m} +} + +func flattenWafv2SingleHeader(s *wafv2.SingleHeader) interface{} { + if s == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "name": aws.StringValue(s.Name), + } + + return []interface{}{m} +} + +func flattenWafv2SingleQueryArgument(s *wafv2.SingleQueryArgument) interface{} { + if s == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "name": aws.StringValue(s.Name), + } + + return []interface{}{m} +} + +func flattenWafv2TextTransformations(l []*wafv2.TextTransformation) []interface{} { + out := make([]interface{}, len(l)) + for i, t := range l { + m := make(map[string]interface{}) + m["priority"] = int(aws.Int64Value(t.Priority)) + m["type"] = aws.StringValue(t.Type) + out[i] = m + } + return out +} + +func flattenWafv2IpSetReferenceStatement(i *wafv2.IPSetReferenceStatement) interface{} { + if i == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "arn": aws.StringValue(i.ARN), + } + + return []interface{}{m} +} + +func flattenWafv2GeoMatchStatement(g *wafv2.GeoMatchStatement) interface{} { + if g == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "country_codes": flattenStringList(g.CountryCodes), + } + + return []interface{}{m} +} + +func flattenWafv2NotStatement(a *wafv2.NotStatement) interface{} { + if a == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "statement": []interface{}{flattenWafv2Statement(a.Statement)}, + } + + return []interface{}{m} +} + +func flattenWafv2OrStatement(a *wafv2.OrStatement) interface{} { + if a == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "statement": flattenWafv2Statements(a.Statements), + } + + return []interface{}{m} +} + +func flattenWafv2RegexPatternSetReferenceStatement(r *wafv2.RegexPatternSetReferenceStatement) interface{} { + if r == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "arn": aws.StringValue(r.ARN), + "field_to_match": flattenWafv2FieldToMatch(r.FieldToMatch), + "text_transformation": flattenWafv2TextTransformations(r.TextTransformations), + } + + return []interface{}{m} +} + +func flattenWafv2SizeConstraintStatement(s *wafv2.SizeConstraintStatement) interface{} { + if s == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "comparison_operator": aws.StringValue(s.ComparisonOperator), + "field_to_match": flattenWafv2FieldToMatch(s.FieldToMatch), + "size": int(aws.Int64Value(s.Size)), + "text_transformation": flattenWafv2TextTransformations(s.TextTransformations), + } + + return []interface{}{m} +} + +func flattenWafv2SqliMatchStatement(s *wafv2.SqliMatchStatement) interface{} { + if s == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "field_to_match": flattenWafv2FieldToMatch(s.FieldToMatch), + "text_transformation": flattenWafv2TextTransformations(s.TextTransformations), + } + + return []interface{}{m} +} + +func flattenWafv2XssMatchStatement(s *wafv2.XssMatchStatement) interface{} { + if s == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "field_to_match": flattenWafv2FieldToMatch(s.FieldToMatch), + "text_transformation": flattenWafv2TextTransformations(s.TextTransformations), + } + + return []interface{}{m} +} + +func flattenWafv2VisibilityConfig(config *wafv2.VisibilityConfig) interface{} { + if config == nil { + return []interface{}{} + } + + m := map[string]interface{}{ + "cloudwatch_metrics_enabled": aws.BoolValue(config.CloudWatchMetricsEnabled), + "metric_name": aws.StringValue(config.MetricName), + "sampled_requests_enabled": aws.BoolValue(config.SampledRequestsEnabled), + } + + return []interface{}{m} +} diff --git a/awsproviderlint/README.md b/awsproviderlint/README.md index c8ed25240c3..1cc7ca7550e 100644 --- a/awsproviderlint/README.md +++ b/awsproviderlint/README.md @@ -14,13 +14,19 @@ The `awsproviderlint` tool extends the `tfproviderlint` tool and its checks. See | Check | Description | |---|---| -| [AWSAT001](passes/AWSAT001/README.md) | check for `resource.TestMatchResourceAttr()` calls against ARN attributes | +| [AWSAT001](passes/AWSAT001) | check for `resource.TestMatchResourceAttr()` calls against ARN attributes | +| [AWSAT002](passes/AWSAT002) | check for hardcoded AMI IDs | +| [AWSAT003](passes/AWSAT003) | check for hardcoded regions | +| [AWSAT004](passes/AWSAT004) | check for TestCheckResourceAttr() calls with hardcoded TypeSet state hashes | +| [AWSAT005](passes/AWSAT005) | check for hardcoded AWS partitions in ARNs | +| [AWSAT006](passes/AWSAT006) | check for hardcoded AWS partition DNS suffixes | ### AWS Resource Checks | Check | Description | |---|---| | [AWSR001](passes/AWSR001/README.md) | check for `fmt.Sprintf()` calls using `.amazonaws.com` domain suffix | +| [AWSR002](passes/AWSR002/README.md) | check for `d.Set()` of `tags` attribute that should include `IgnoreConfig()` | ## Development and Testing @@ -48,4 +54,4 @@ NOTE: Provider-specific analyzers should implement their own namespace outside ` * Add `passes/NAME/NAME_test.go` which implements `analysistest.TestData()` and `analysistest.Run()`. * Add `passes/NAME/testdata/src/a` directory with Go source files that implement passing and failing code based on `analysistest` framework. * Since the [`analysistest` package](https://godoc.org/golang.org/x/tools/go/analysis/analysistest) does not support Go Modules currently, each analyzer that implements testing must add a symlink to the top level `vendor` directory in the `testdata/src/a` directory. e.g. `ln -s ../../../../../../vendor passes/NAME/testdata/src/a/vendor`. -* Add new `Analyzer` in `main.go`. +* Add new link to new analyzer in `README.md` (this file). diff --git a/awsproviderlint/passes/AWSAT001/AWSAT001.go b/awsproviderlint/passes/AWSAT001/AWSAT001.go index 2b9ac236153..765a8809fbc 100644 --- a/awsproviderlint/passes/AWSAT001/AWSAT001.go +++ b/awsproviderlint/passes/AWSAT001/AWSAT001.go @@ -70,16 +70,16 @@ func run(pass *analysis.Pass) (interface{}, error) { } func AttributeNameAppearsArnRelated(attributeName string) bool { - if attributeName == "arn" { + if attributeName == "arn" || attributeName == "kms_key_id" { return true } - if strings.HasSuffix(attributeName, "_arn") { + if strings.HasSuffix(attributeName, "_arn") || strings.HasSuffix(attributeName, "_kms_key_id") { return true } // Handle flatmap nested attribute - if strings.HasSuffix(attributeName, ".arn") { + if strings.HasSuffix(attributeName, ".arn") || strings.HasSuffix(attributeName, ".kms_key_id") { return true } diff --git a/awsproviderlint/passes/AWSAT001/AWSAT001_test.go b/awsproviderlint/passes/AWSAT001/AWSAT001_test.go index ab6b8f4e027..7176e9a8273 100644 --- a/awsproviderlint/passes/AWSAT001/AWSAT001_test.go +++ b/awsproviderlint/passes/AWSAT001/AWSAT001_test.go @@ -33,21 +33,41 @@ func TestAttributeNameAppearsArnRelated(t *testing.T) { AttributeName: "arn", Expected: true, }, + { + Name: "equals kms_key_id", + AttributeName: "kms_key_id", + Expected: true, + }, { Name: "arn suffix", AttributeName: "some_arn", Expected: true, }, + { + Name: "kms_key_id suffix", + AttributeName: "some_kms_key_id", + Expected: true, + }, { Name: "nested attribute equals arn", AttributeName: "config_block.0.arn", Expected: true, }, + { + Name: "nested attribute equals kms_key_id", + AttributeName: "config_block.0.kms_key_id", + Expected: true, + }, { Name: "nested attribute arn suffix", AttributeName: "config_block.0.some_arn", Expected: true, }, + { + Name: "nested attribute kms_key_id suffix", + AttributeName: "config_block.0.some_kms_key_id", + Expected: true, + }, } for _, testCase := range testCases { diff --git a/awsproviderlint/passes/AWSAT001/testdata/src/a/main.go b/awsproviderlint/passes/AWSAT001/testdata/src/a/main.go index ce09ccc7a09..c68c8187ef5 100644 --- a/awsproviderlint/passes/AWSAT001/testdata/src/a/main.go +++ b/awsproviderlint/passes/AWSAT001/testdata/src/a/main.go @@ -3,7 +3,7 @@ package a import ( "regexp" - "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) const resourceName = `aws_example_thing.test` diff --git a/awsproviderlint/passes/AWSAT002/AWSAT002.go b/awsproviderlint/passes/AWSAT002/AWSAT002.go new file mode 100644 index 00000000000..4bdf05a6ec6 --- /dev/null +++ b/awsproviderlint/passes/AWSAT002/AWSAT002.go @@ -0,0 +1,59 @@ +// Package AWSAT002 defines an Analyzer that checks for +// hardcoded AMI IDs +package AWSAT002 + +import ( + "go/ast" + "go/token" + "regexp" + + "github.com/bflad/tfproviderlint/passes/commentignore" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +const Doc = `check for hardcoded AMI IDs + +The AWSAT002 analyzer reports hardcoded AMI IDs. AMI IDs are region dependent and tests will fail in any region or partition other than where the AMI was created. +` + +const analyzerName = "AWSAT002" + +var Analyzer = &analysis.Analyzer{ + Name: analyzerName, + Doc: Doc, + Requires: []*analysis.Analyzer{ + commentignore.Analyzer, + inspect.Analyzer, + }, + Run: run, +} + +func run(pass *analysis.Pass) (interface{}, error) { + ignorer := pass.ResultOf[commentignore.Analyzer].(*commentignore.Ignorer) + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + + nodeFilter := []ast.Node{ + (*ast.BasicLit)(nil), + } + re := regexp.MustCompile("ami-[0-9a-z]{8,17}") + inspect.Preorder(nodeFilter, func(n ast.Node) { + x := n.(*ast.BasicLit) + + if ignorer.ShouldIgnore(analyzerName, x) { + return + } + + if x.Kind != token.STRING { + return + } + + if !re.MatchString(x.Value) { + return + } + + pass.Reportf(x.ValuePos, "%s: AMI IDs should not be hardcoded", analyzerName) + }) + return nil, nil +} diff --git a/awsproviderlint/passes/AWSAT002/AWSAT002_test.go b/awsproviderlint/passes/AWSAT002/AWSAT002_test.go new file mode 100644 index 00000000000..57f633dd581 --- /dev/null +++ b/awsproviderlint/passes/AWSAT002/AWSAT002_test.go @@ -0,0 +1,13 @@ +package AWSAT002_test + +import ( + "testing" + + "github.com/terraform-providers/terraform-provider-aws/awsproviderlint/passes/AWSAT002" + "golang.org/x/tools/go/analysis/analysistest" +) + +func TestAWSAT002(t *testing.T) { + testdata := analysistest.TestData() + analysistest.Run(t, testdata, AWSAT002.Analyzer, "a") +} diff --git a/awsproviderlint/passes/AWSAT002/README.md b/awsproviderlint/passes/AWSAT002/README.md new file mode 100644 index 00000000000..f99a7421436 --- /dev/null +++ b/awsproviderlint/passes/AWSAT002/README.md @@ -0,0 +1,56 @@ +# AWSAT002 + +The AWSAT002 analyzer reports hardcoded AMI IDs. AMI IDs are region dependent and tests will fail in any region or partition other than where the AMI was created. + +## Flagged Code + +```go +func testAccAWSSpotFleetRequestConfig(rName string, rInt int, validUntil string) string { + return testAccAWSSpotFleetRequestConfigBase(rName, rInt) + fmt.Sprintf(` +resource "aws_spot_fleet_request" "test" { + launch_specification { + instance_type = "m1.small" + ami = "ami-516b9131" + } +} +`, validUntil) +} +``` + +## Passing Code + +```go +func testAccAWSSpotFleetRequestConfig(rName string, rInt int, validUntil string) string { + return testAccAWSSpotFleetRequestConfigBase(rName, rInt) + fmt.Sprintf(` +data "aws_ami" "amzn-ami-minimal-hvm-ebs" { + most_recent = true + owners = ["amazon"] + + filter { + name = "name" + values = ["amzn-ami-minimal-hvm-*"] + } + + filter { + name = "root-device-type" + values = ["ebs"] + } +} + +resource "aws_spot_fleet_request" "test" { + launch_specification { + instance_type = "m1.small" + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + } +} +`, validUntil) +} +``` + +## Ignoring Reports + +Singular reports can be ignored by adding the a `//lintignore:AWSAT002` Go code comment at the end of the offending line or on the line immediately proceding, e.g. + +```go +ami = "ami-516b9131" //lintignore:AWSAT002 +``` diff --git a/awsproviderlint/passes/AWSAT002/testdata/src/a/main.go b/awsproviderlint/passes/AWSAT002/testdata/src/a/main.go new file mode 100644 index 00000000000..b0aa045e896 --- /dev/null +++ b/awsproviderlint/passes/AWSAT002/testdata/src/a/main.go @@ -0,0 +1,43 @@ +package a + +import ( + "fmt" +) + +func f() { + /* Passing cases */ + fmt.Sprintf(` +data "aws_ami" "amzn-ami-minimal-hvm-ebs" { + most_recent = true + owners = ["amazon"] + + filter { + name = "name" + values = ["amzn-ami-minimal-hvm-*"] + } + + filter { + name = "root-device-type" + values = [%q] + } +} + +resource "aws_spot_fleet_request" "test" { + launch_specification { + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + } +} +`, "ebs") + + /* Comment ignored cases */ + + //lintignore:AWSAT002 + fmt.Sprintf(`ami = "%s"`, "ami-516b9131") + + fmt.Sprintf(`ami = "%s"`, "ami-516b9131") //lintignore:AWSAT002 + fmt.Sprintf(`ami = "%s"`, "amzn-ami-minimalist-ebs") //lintignore:AWSAT002 + + /* Failing cases */ + + fmt.Sprintf(`ami = "%s"`, "ami-516b9131") // want "AMI IDs should not be hardcoded" +} diff --git a/awsproviderlint/passes/AWSAT002/testdata/src/a/vendor b/awsproviderlint/passes/AWSAT002/testdata/src/a/vendor new file mode 120000 index 00000000000..ce7b6d9c07f --- /dev/null +++ b/awsproviderlint/passes/AWSAT002/testdata/src/a/vendor @@ -0,0 +1 @@ +../../../../../../vendor \ No newline at end of file diff --git a/awsproviderlint/passes/AWSAT003/AWSAT003.go b/awsproviderlint/passes/AWSAT003/AWSAT003.go new file mode 100644 index 00000000000..962f3602a6e --- /dev/null +++ b/awsproviderlint/passes/AWSAT003/AWSAT003.go @@ -0,0 +1,73 @@ +// Package AWSAT003 defines an Analyzer that checks for +// hardcoded regions +package AWSAT003 + +import ( + "go/ast" + "go/token" + "regexp" + "strings" + + "github.com/aws/aws-sdk-go/aws/endpoints" + "github.com/bflad/tfproviderlint/passes/commentignore" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +const Doc = `check for hardcoded regions + +The AWSAT003 analyzer reports hardcoded regions. Testing in non-standard +partitions with hardcoded regions (and AZs) will cause the tests to fail. +` + +const analyzerName = "AWSAT003" + +var Analyzer = &analysis.Analyzer{ + Name: analyzerName, + Doc: Doc, + Requires: []*analysis.Analyzer{ + commentignore.Analyzer, + inspect.Analyzer, + }, + Run: run, +} + +func run(pass *analysis.Pass) (interface{}, error) { + ignorer := pass.ResultOf[commentignore.Analyzer].(*commentignore.Ignorer) + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + + nodeFilter := []ast.Node{ + (*ast.BasicLit)(nil), + } + + resolver := endpoints.DefaultResolver() + partitions := resolver.(endpoints.EnumPartitions).Partitions() + var regions []string + + for _, p := range partitions { + for id := range p.Regions() { + regions = append(regions, id) + } + } + + re := regexp.MustCompile(strings.Join(regions, "|")) + inspect.Preorder(nodeFilter, func(n ast.Node) { + x := n.(*ast.BasicLit) + + if ignorer.ShouldIgnore(analyzerName, x) { + return + } + + if x.Kind != token.STRING { + return + } + + if !re.MatchString(x.Value) { + return + } + + pass.Reportf(x.ValuePos, "%s: regions should not be hardcoded, use aws_region and aws_availability_zones data sources instead", analyzerName) + }) + return nil, nil +} diff --git a/awsproviderlint/passes/AWSAT003/AWSAT003_test.go b/awsproviderlint/passes/AWSAT003/AWSAT003_test.go new file mode 100644 index 00000000000..816383f56fb --- /dev/null +++ b/awsproviderlint/passes/AWSAT003/AWSAT003_test.go @@ -0,0 +1,13 @@ +package AWSAT003_test + +import ( + "testing" + + "github.com/terraform-providers/terraform-provider-aws/awsproviderlint/passes/AWSAT003" + "golang.org/x/tools/go/analysis/analysistest" +) + +func TestAWSAT003(t *testing.T) { + testdata := analysistest.TestData() + analysistest.Run(t, testdata, AWSAT003.Analyzer, "a") +} diff --git a/awsproviderlint/passes/AWSAT003/README.md b/awsproviderlint/passes/AWSAT003/README.md new file mode 100644 index 00000000000..5060fa664ea --- /dev/null +++ b/awsproviderlint/passes/AWSAT003/README.md @@ -0,0 +1,66 @@ +# AWSAT003 + +The AWSAT003 analyzer reports hardcoded AWS regions. Tests that are hardcoded +to work in a region specific to a partition (eg, the AWS standard/commercial +partition) will fail in other partitions where the region does not exist (eg, +GovCloud). + +## Flagged Code + +The `us-west-2` region does not exist in non-standard partitions (eg, the +GovCloud partition). + +```go +fmt.Sprintf(` +resource "aws_config_configuration_aggregator" "example" { + name = %[1]q + + account_aggregation_source { + account_ids = [data.aws_caller_identity.current.account_id] + regions = ["us-west-2"] + } +} + +data "aws_caller_identity" "current" {} +`, rName) +``` + +Hardcoded regions (eg, `us-west-2`) that are part of an availability zone (AZ) +designation (eg., `us-west-2a`) are also flagged. + +```go +fmt.Sprintf(` +resource "aws_subnet" "test" { + availability_zone = "us-west-2a" + cidr_block = %q +} +`, "10.0.0.0/24") +``` + +## Passing Code + +```go +fmt.Sprintf(` +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +resource "aws_subnet" "test" { + availability_zone = data.aws_availability_zones.available.names[0] + cidr_block = %q +} +`, "10.0.0.0/24") +``` + +## Ignoring Reports + +Singular reports can be ignored by adding the a `//lintignore:AWSAT003` Go code comment at the end of the offending line or on the line immediately proceding, e.g. + +```go +fmt.Sprintf(`"af-south-1": %q,`, "525921808201") //lintignore:AWSAT003 +``` diff --git a/awsproviderlint/passes/AWSAT003/testdata/src/a/main.go b/awsproviderlint/passes/AWSAT003/testdata/src/a/main.go new file mode 100644 index 00000000000..8c7467a076d --- /dev/null +++ b/awsproviderlint/passes/AWSAT003/testdata/src/a/main.go @@ -0,0 +1,50 @@ +package a + +import ( + "fmt" +) + +func f() { + /* Passing cases */ + fmt.Sprintf(` +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +resource "aws_subnet" "test" { + availability_zone = data.aws_availability_zones.available.names[0] + cidr_block = %q +} +`, "10.0.0.0/24") + + fmt.Sprintf(` +resource "aws_config_configuration_aggregator" "example" { + name = %[1]q + + account_aggregation_source { + account_ids = [data.aws_caller_identity.current.account_id] + regions = [endpoints.UsWest2RegionID] + } +} + +data "aws_caller_identity" "current" {} +`, "rName") + + /* Comment ignored cases */ + + //lintignore:AWSAT003 + fmt.Sprintf(`"af-south-1": %q,`, "525921808201") + + fmt.Sprintf(`"af-south-1": %q,`, "525921808201") //lintignore:AWSAT003 + + /* Failing cases */ + + fmt.Println(`availability_zone = "us-west-2a"`) // want "regions should not be hardcoded" + + fmt.Sprintf(`regions = ["us-west-2"]`) // want "regions should not be hardcoded" +} diff --git a/awsproviderlint/passes/AWSAT003/testdata/src/a/vendor b/awsproviderlint/passes/AWSAT003/testdata/src/a/vendor new file mode 120000 index 00000000000..ce7b6d9c07f --- /dev/null +++ b/awsproviderlint/passes/AWSAT003/testdata/src/a/vendor @@ -0,0 +1 @@ +../../../../../../vendor \ No newline at end of file diff --git a/awsproviderlint/passes/AWSAT004/AWSAT004.go b/awsproviderlint/passes/AWSAT004/AWSAT004.go new file mode 100644 index 00000000000..6ee28f181b0 --- /dev/null +++ b/awsproviderlint/passes/AWSAT004/AWSAT004.go @@ -0,0 +1,60 @@ +// Package AWSAT004 defines an Analyzer that checks for +// TestCheckResourceAttr() calls with hardcoded TypeSet state hashes +package AWSAT004 + +import ( + "go/ast" + "regexp" + + "github.com/bflad/tfproviderlint/helper/astutils" + "github.com/bflad/tfproviderlint/passes/commentignore" + "github.com/bflad/tfproviderlint/passes/helper/resource/testcheckresourceattrcallexpr" + "golang.org/x/tools/go/analysis" +) + +const Doc = `check for TestCheckResourceAttr() calls with hardcoded TypeSet state hashes + +The AWSAT004 analyzer reports TestCheckResourceAttr() calls with hardcoded +TypeSet state hashes. Hardcoded state hashes are an unreliable way to +specifically address state values since hashes may change over time, be +inconsistent across partitions, and can be inadvertently changed by modifying +configurations. +` + +const analyzerName = "AWSAT004" + +var Analyzer = &analysis.Analyzer{ + Name: analyzerName, + Doc: Doc, + Requires: []*analysis.Analyzer{ + commentignore.Analyzer, + testcheckresourceattrcallexpr.Analyzer, + }, + Run: run, +} + +func run(pass *analysis.Pass) (interface{}, error) { + ignorer := pass.ResultOf[commentignore.Analyzer].(*commentignore.Ignorer) + callExprs := pass.ResultOf[testcheckresourceattrcallexpr.Analyzer].([]*ast.CallExpr) + + re := regexp.MustCompile(`[a-z0-9_]+\.\d{7,20}`) + for _, callExpr := range callExprs { + if ignorer.ShouldIgnore(analyzerName, callExpr) { + continue + } + + attributeName := astutils.ExprStringValue(callExpr.Args[1]) + + if attributeName == nil { + continue + } + + if !re.MatchString(*attributeName) { + continue + } + + pass.Reportf(callExpr.Args[1].Pos(), "%s: avoid hardcoded state hashes, instead use the TestCheckTypeSetElemNestedAttrs function", analyzerName) + + } + return nil, nil +} diff --git a/awsproviderlint/passes/AWSAT004/AWSAT004_test.go b/awsproviderlint/passes/AWSAT004/AWSAT004_test.go new file mode 100644 index 00000000000..3aa18c364d3 --- /dev/null +++ b/awsproviderlint/passes/AWSAT004/AWSAT004_test.go @@ -0,0 +1,13 @@ +package AWSAT004_test + +import ( + "testing" + + "github.com/terraform-providers/terraform-provider-aws/awsproviderlint/passes/AWSAT004" + "golang.org/x/tools/go/analysis/analysistest" +) + +func TestAWSAT004(t *testing.T) { + testdata := analysistest.TestData() + analysistest.Run(t, testdata, AWSAT004.Analyzer, "a") +} diff --git a/awsproviderlint/passes/AWSAT004/README.md b/awsproviderlint/passes/AWSAT004/README.md new file mode 100644 index 00000000000..379b844a37f --- /dev/null +++ b/awsproviderlint/passes/AWSAT004/README.md @@ -0,0 +1,69 @@ +# AWSAT004 + +The AWSAT004 analyzer reports TestCheckResourceAttr() calls with hardcoded +TypeSet state hashes. Hardcoded state hashes are an unreliable way to +specifically address state values since hashes may change over time, be +inconsistent across partitions, and can be inadvertently changed by modifying +configurations. + +## Flagged Code + +```go +func TestAccAWSELB_basic(t *testing.T) { + ... + resource.ParallelTest(t, resource.TestCase{ + ... + Steps: []resource.TestStep{ + { + Config: testAccAWSELBConfig, + Check: resource.ComposeTestCheckFunc( + ... + resource.TestCheckResourceAttr(resourceName, "listener.206423021.instance_port", "8000"), + resource.TestCheckResourceAttr(resourceName, "listener.206423021.instance_protocol", "http"), + resource.TestCheckResourceAttr(resourceName, "listener.206423021.lb_port", "80"), + resource.TestCheckResourceAttr(resourceName, "listener.206423021.lb_protocol", "http"), + ... + ), + }, + ... + }, + }) +} +``` + +## Passing Code + +The flagged code above can be replaced with the following passing code: + +```go +func TestAccAWSELB_basic(t *testing.T) { + ... + resource.ParallelTest(t, resource.TestCase{ + ... + Steps: []resource.TestStep{ + { + Config: testAccAWSELBConfig, + Check: resource.ComposeTestCheckFunc( + ... + tfawsresource.TestCheckTypeSetElemNestedAttrs(resourceName, "listener.*", map[string]string{ + "instance_port": "8000", + "instance_protocol": "http", + "lb_port": "80", + "lb_protocol": "http", + }), + ... + ), + }, + ... + }, + }) +} +``` + +## Ignoring Reports + +Singular reports can be ignored by adding the a `//lintignore:AWSAT004` Go code comment at the end of the offending line or on the line immediately proceding, e.g. + +```go +resource.TestCheckResourceAttr(resourceName, "listener.206423021.instance_port", "8000"), //lintignore:AWSAT004 +``` diff --git a/awsproviderlint/passes/AWSAT004/testdata/src/a/main.go b/awsproviderlint/passes/AWSAT004/testdata/src/a/main.go new file mode 100644 index 00000000000..fac6f0b1e1d --- /dev/null +++ b/awsproviderlint/passes/AWSAT004/testdata/src/a/main.go @@ -0,0 +1,23 @@ +package a + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func f() { + resourceName := "resource" + + /* Passing cases */ + resource.TestCheckResourceAttr(resourceName, "listener.*.instance_port", "8000") + + /* Comment ignored cases */ + + //lintignore:AWSAT004 + resource.TestCheckResourceAttr(resourceName, "listener.206423021.instance_port", "8000") + + resource.TestCheckResourceAttr(resourceName, "listener.206423021.instance_port", "8000") //lintignore:AWSAT004 + + /* Failing cases */ + resource.TestCheckResourceAttr(resourceName, "listener.206423021.instance_port", "8000") // want "avoid hardcoded state hashes" + resource.TestCheckResourceAttr(resourceName, "rule.3061118601.statement.#", "1") // want "avoid hardcoded state hashes" +} diff --git a/awsproviderlint/passes/AWSAT004/testdata/src/a/vendor b/awsproviderlint/passes/AWSAT004/testdata/src/a/vendor new file mode 120000 index 00000000000..ce7b6d9c07f --- /dev/null +++ b/awsproviderlint/passes/AWSAT004/testdata/src/a/vendor @@ -0,0 +1 @@ +../../../../../../vendor \ No newline at end of file diff --git a/awsproviderlint/passes/AWSAT005/AWSAT005.go b/awsproviderlint/passes/AWSAT005/AWSAT005.go new file mode 100644 index 00000000000..f3d3416d38f --- /dev/null +++ b/awsproviderlint/passes/AWSAT005/AWSAT005.go @@ -0,0 +1,68 @@ +// Package AWSAT005 defines an Analyzer that checks for +// hardcoded AWS partitions in ARNs +package AWSAT005 + +import ( + "go/ast" + "go/token" + "regexp" + "strings" + + "github.com/aws/aws-sdk-go/aws/endpoints" + "github.com/bflad/tfproviderlint/passes/commentignore" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +const Doc = `check for hardcoded AWS partitions in ARNs + +The AWSAT005 analyzer reports hardcoded AWS partitions in ARNs. For tests to +work across AWS partitions, the partitions should not be hardcoded. +` + +const analyzerName = "AWSAT005" + +var Analyzer = &analysis.Analyzer{ + Name: analyzerName, + Doc: Doc, + Requires: []*analysis.Analyzer{ + commentignore.Analyzer, + inspect.Analyzer, + }, + Run: run, +} + +func run(pass *analysis.Pass) (interface{}, error) { + ignorer := pass.ResultOf[commentignore.Analyzer].(*commentignore.Ignorer) + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + + nodeFilter := []ast.Node{ + (*ast.BasicLit)(nil), + } + + var partitions []string + for _, p := range endpoints.DefaultPartitions() { + partitions = append(partitions, p.ID()) + } + + re := regexp.MustCompile(`arn:(` + strings.Join(partitions, "|") + `):`) + inspect.Preorder(nodeFilter, func(n ast.Node) { + x := n.(*ast.BasicLit) + + if ignorer.ShouldIgnore(analyzerName, x) { + return + } + + if x.Kind != token.STRING { + return + } + + if !re.MatchString(x.Value) { + return + } + + pass.Reportf(x.ValuePos, "%s: avoid hardcoded ARN AWS partitions, use aws_partition data source", analyzerName) + }) + return nil, nil +} diff --git a/awsproviderlint/passes/AWSAT005/AWSAT005_test.go b/awsproviderlint/passes/AWSAT005/AWSAT005_test.go new file mode 100644 index 00000000000..f908c80d246 --- /dev/null +++ b/awsproviderlint/passes/AWSAT005/AWSAT005_test.go @@ -0,0 +1,13 @@ +package AWSAT005_test + +import ( + "testing" + + "github.com/terraform-providers/terraform-provider-aws/awsproviderlint/passes/AWSAT005" + "golang.org/x/tools/go/analysis/analysistest" +) + +func TestAWSAT005(t *testing.T) { + testdata := analysistest.TestData() + analysistest.Run(t, testdata, AWSAT005.Analyzer, "a") +} diff --git a/awsproviderlint/passes/AWSAT005/README.md b/awsproviderlint/passes/AWSAT005/README.md new file mode 100644 index 00000000000..8f8a11ba9c7 --- /dev/null +++ b/awsproviderlint/passes/AWSAT005/README.md @@ -0,0 +1,40 @@ +# AWSAT005 + +The AWSAT005 analyzer reports hardcoded AWS partitions in ARNs. For tests to +work across AWS partitions, the partitions should not be hardcoded. + +## Flagged Code + +```go +func testAccAWSSpotFleetRequestConfig(role string) string { + return fmt.Sprintf(` +resource "aws_iam_role_policy_attachment" "test-AmazonEKSClusterPolicy" { + policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy" + role = %q +} +`, role) +} +``` + +## Passing Code + +```go +func testAccAWSSpotFleetRequestConfig(role string) string { + return fmt.Sprintf(` +data "aws_partition" "current" {} + +resource "aws_iam_role_policy_attachment" "test-AmazonEKSClusterPolicy" { + policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/AmazonEKSClusterPolicy" + role = %q +} +`, role) +} +``` + +## Ignoring Reports + +Singular reports can be ignored by adding the a `//lintignore:AWSAT005` Go code comment at the end of the offending line or on the line immediately proceding, e.g. + +```go +policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy" //lintignore:AWSAT005 +``` diff --git a/awsproviderlint/passes/AWSAT005/testdata/src/a/main.go b/awsproviderlint/passes/AWSAT005/testdata/src/a/main.go new file mode 100644 index 00000000000..2069f325eaf --- /dev/null +++ b/awsproviderlint/passes/AWSAT005/testdata/src/a/main.go @@ -0,0 +1,30 @@ +package a + +import ( + "fmt" +) + +func f() { + /* Passing cases */ + fmt.Sprintf(` +data "aws_partition" "current" {} + +resource "aws_iam_role_policy_attachment" "test-AmazonEKSClusterPolicy" { + policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:%v" +} +`, "policy/AmazonEKSClusterPolicy") + + /* Comment ignored cases */ + + //lintignore:AWSAT005 + fmt.Sprintf(`policy_arn = "arn:aws:iam::aws:%v"`, "policy/AmazonEKSClusterPolicy") + + fmt.Sprintf(`policy_arn = "arn:aws:iam::aws:%v"`, "policy/AmazonEKSClusterPolicy") //lintignore:AWSAT005 + fmt.Sprintf(`policy_arn = "arn:aws:iam::aws:%v"`, "policy/AmazonEKSClusterPolicy") //lintignore:AWSAT005 + + /* Failing cases */ + + fmt.Sprintf(`policy_arn = "arn:aws:iam::aws:%v"`, "policy/AmazonEKSClusterPolicy") // want "avoid hardcoded ARN AWS partitions" + fmt.Sprintf(`policy_arn = "arn:aws-us-gov:iam::aws:%v"`, "policy/AmazonEKSClusterPolicy") // want "avoid hardcoded ARN AWS partitions" + +} diff --git a/awsproviderlint/passes/AWSAT005/testdata/src/a/vendor b/awsproviderlint/passes/AWSAT005/testdata/src/a/vendor new file mode 120000 index 00000000000..ce7b6d9c07f --- /dev/null +++ b/awsproviderlint/passes/AWSAT005/testdata/src/a/vendor @@ -0,0 +1 @@ +../../../../../../vendor \ No newline at end of file diff --git a/awsproviderlint/passes/AWSAT006/AWSAT006.go b/awsproviderlint/passes/AWSAT006/AWSAT006.go new file mode 100644 index 00000000000..b534548707a --- /dev/null +++ b/awsproviderlint/passes/AWSAT006/AWSAT006.go @@ -0,0 +1,69 @@ +// Package AWSAT006 defines an Analyzer that checks for +// hardcoded AWS partition DNS suffixes +package AWSAT006 + +import ( + "go/ast" + "go/token" + "regexp" + "strings" + + "github.com/aws/aws-sdk-go/aws/endpoints" + "github.com/bflad/tfproviderlint/passes/commentignore" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +const Doc = `check for hardcoded AWS partition DNS suffixes + +The AWSAT006 analyzer reports hardcoded AWS partition DNS suffixes. For tests +to work across AWS partitions, the partition DNS suffixes should not be +hardcoded. +` + +const analyzerName = "AWSAT006" + +var Analyzer = &analysis.Analyzer{ + Name: analyzerName, + Doc: Doc, + Requires: []*analysis.Analyzer{ + commentignore.Analyzer, + inspect.Analyzer, + }, + Run: run, +} + +func run(pass *analysis.Pass) (interface{}, error) { + ignorer := pass.ResultOf[commentignore.Analyzer].(*commentignore.Ignorer) + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + + nodeFilter := []ast.Node{ + (*ast.BasicLit)(nil), + } + + var suffixes []string + for _, p := range endpoints.DefaultPartitions() { + suffixes = append(suffixes, p.DNSSuffix()) + } + + re := regexp.MustCompile(strings.Join(suffixes, "|")) + inspect.Preorder(nodeFilter, func(n ast.Node) { + x := n.(*ast.BasicLit) + + if ignorer.ShouldIgnore(analyzerName, x) { + return + } + + if x.Kind != token.STRING { + return + } + + if !re.MatchString(x.Value) { + return + } + + pass.Reportf(x.ValuePos, "%s: avoid hardcoding AWS partition DNS suffixes, instead use the aws_partition data source", analyzerName) + }) + return nil, nil +} diff --git a/awsproviderlint/passes/AWSAT006/AWSAT006_test.go b/awsproviderlint/passes/AWSAT006/AWSAT006_test.go new file mode 100644 index 00000000000..16711b0dc97 --- /dev/null +++ b/awsproviderlint/passes/AWSAT006/AWSAT006_test.go @@ -0,0 +1,13 @@ +package AWSAT006_test + +import ( + "testing" + + "github.com/terraform-providers/terraform-provider-aws/awsproviderlint/passes/AWSAT006" + "golang.org/x/tools/go/analysis/analysistest" +) + +func TestAWSAT006(t *testing.T) { + testdata := analysistest.TestData() + analysistest.Run(t, testdata, AWSAT006.Analyzer, "a") +} diff --git a/awsproviderlint/passes/AWSAT006/README.md b/awsproviderlint/passes/AWSAT006/README.md new file mode 100644 index 00000000000..a9c0bedc784 --- /dev/null +++ b/awsproviderlint/passes/AWSAT006/README.md @@ -0,0 +1,68 @@ +# AWSAT006 + +The AWSAT006 analyzer reports hardcoded AWS partition DNS suffixes. For tests +to work across AWS partitions, the DNS suffixes should not be hardcoded. + +## Flagged Code + +```go +func testAccAWSMisericordiamHumilitatemPulchritudo(name string) string { + return fmt.Sprintf(` +resource "aws_iam_role" "test" { + name = "%s" + + assume_role_policy = < + +### Who are the maintainers? + +The HashiCorp Terraform AWS provider team is : + +* Mary Cutrali, Product Manager - GitHub [@maryelizbeth](https://github.com/maryelizbeth) Twitter [@marycutrali](https://twitter.com/marycutrali) +* Brian Flad, Engineering Lead GitHub [@bflad](https://github.com/bflad) +* Graham Davison, Engineer - GitHub [@gdavison](https://github.com/gdavison) +* Angie Pinilla, Engineer - GitHub [@angie44](https://github.com/angie44) +* Simon Davis, Engineering Manager - GitHub [@breathingdust](https://github.com/breathingdust) +* Kerim Satirli, Developer Advocate - GitHub [@ksatirli](https://github.com/ksatirli) + +### Why isn’t my PR merged yet? + +Unfortunately, due to the volume of issues and new pull requests we receive, we are unable to give each one the full attention that we would like. We always focus on the contributions that provide the greatest value to the most community members. + +### How do you decide what gets merged for each release? + +The number one factor we look at when deciding what issues to look at are your 👍 [reactions](https://blog.github.com/2016-03-10-add-reactions-to-pull-requests-issues-and-comments/) to the original issue/PR description as these can be [easily discovered](https://github.com/terraform-providers/terraform-provider-aws/issues?q=is%3Aopen+sort%3Areactions-%2B1-desc). Comments that further explain desired use cases or poor user experience are also heavily factored. The items with the most support are always on our radar, and we commit to keep the community updated on their status and potential timelines. + +We publish a [roadmap](../ROADMAP.md) every quarter which describes major themes or specific product areas of focus. + +We also are investing time to improve the contributing experience by improving documentation, adding more linter coverage to ensure that incoming PR's can be in as good shape as possible. This will allow us to get through them quicker. + +### How often do you release? + +We release weekly on Thursday. We release often to ensure we can bring value to the community at a frequent cadence and to ensure we are in a good place to react to AWS region launches and service announcements. + +### Backward Compatibility Promise + +Our policy is described on the Terraform website [here](https://www.terraform.io/docs/extend/best-practices/versioning.html). While we do our best to prevent breaking changes until major version releases of the provider, it is generally recommended to [pin the provider version in your configuration](https://www.terraform.io/docs/configuration/providers.html#provider-versions). + +Due to the constant release pace of AWS and the relatively infrequent major version releases of the provider, there can be cases where a minor version update may contain unexpected changes depending on your configuration or environment. These may include items such as a resource requiring additional IAM permissions to support newer functionality. We typically base these decisions on a pragmatic compromise between introducing a relatively minor one-time inconvenience for a subset of the community versus better overall user experience for the entire community. + +### AWS just announced a new region, when will I see it in the provider. + +Normally pretty quickly. We usually see the region appear within the `aws-go-sdk` within a couple days of the announcement. Depending on when it lands, we can often get it out within the current or following weekly release. Comparatively, adding support for a new region in the S3 backend can take a little longer, as it is shipped as part of Terraform Core and not via the AWS Provider. + +Please note that this new region requires a manual process to enable in your account. Once enabled in the console, it takes a few minutes for everything to work properly. + +If the region is not enabled properly, or the enablement process is still in progress, you may receive errors like these: + +``` +$ terraform apply + +Error: error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid. + status code: 403, request id: 142f947b-b2c3-11e9-9959-c11ab17bcc63 + + on main.tf line 1, in provider "aws": + 1: provider "aws" { +``` + +To use this new region before support has been added to the Terraform AWS Provider, you can disable the provider's automatic region validation via: + +```hcl +provider "aws" { + # ... potentially other configuration ... + + region = "af-south-1" + skip_region_validation = true +} + +``` + +### How can I help? + +Great question, if you have contributed before check out issues with the `help-wanted` label. These are normally enhancement issues that will have a great impact, but the maintainers are unable to develop them in the near future. If you are just getting started, take a look at issues with the `good-first-issue` label. Items with these labels will always be given priority for response. + +Check out the [Contributing Guide](CONTRIBUTING.md) for additional information. + +### How can I become a maintainer? + +This is an area under active research. Stay tuned! + + diff --git a/docs/MAINTAINING.md b/docs/MAINTAINING.md new file mode 100644 index 00000000000..f7d3852173a --- /dev/null +++ b/docs/MAINTAINING.md @@ -0,0 +1,515 @@ +# Maintaining the Terraform AWS Provider + + + +- [Pull Requests](#pull-requests) + - [Pull Request Review Process](#pull-request-review-process) + - [Dependency Updates](#dependency-updates) + - [Go Default Version Update](#go-default-version-update) + - [AWS Go SDK Updates](#aws-go-sdk-updates) + - [golangci-lint Updates](#golangci-lint-updates) + - [Terraform Plugin SDK Updates](#terraform-plugin-sdk-updates) + - [tfproviderdocs Updates](#tfproviderdocs-updates) + - [tfproviderlint Updates](#tfproviderlint-updates) + - [yaml.v2 Updates](#yaml-v2-updates) + - [Pull Request Merge Process](#pull-request-merge-process) + - [Pull Request Types to CHANGELOG](#pull-request-types-to-changelog) +- [Breaking Changes](#breaking-changes) +- [Branch Dictionary](#branch-dictionary) +- [Environment Variable Dictionary](#environment-variable-dictionary) +- [Label Dictionary](#label-dictionary) + + + +## Community Maintainers + +Members of the community who participate in any aspects of maintaining the provider must adhere to the HashiCorp [Community Guidelines](https://www.hashicorp.com/community-guidelines). + +## Triage + +Incoming issues are classified using labels. These are assigned either by automation, or manually during the triage process. We follow a two-label system where we classify by type and by the area of the provider they affect. A full listing of the labels and how they are used can be found in the [Label Dictionary](#label-dictionary). + +## Pull Requests + +### Pull Request Review Process + +Throughout the review process our first priority is to interact with contributors with kindness, empathy and in accordance with the [Guidelines](https://www.hashicorp.com/community-guidelines) and [Principles](https://www.hashicorp.com/our-principles/) of Hashicorp. + +Our contributors are often working within the provider as a hobby, or not in their main line of work so we need to give adequate time for response. By default this is two weeks, but it is worth considering taking on the work to complete the PR ourselves if the administrative effort of waiting for a response is greater than just resolving the issues ourselves (Don't wait two weeks, or add a context shift for yourself and the contributor to fix a typo). As long as we use their commits, contributions will be recorded by Github and as always ensure to thank the contributor for their work. Roadmap items are another area where we would consider taking on the work ourselves more quickly in order to meet the commitments made to our users. + +Notes for each type of pull request are (or will be) available in subsections below. + +- If you plan to be responsible for the pull request through the merge/closure process, assign it to yourself +- Add `bug`, `enhancement`, `new-data-source`, `new-resource`, or `technical-debt` labels to match expectations from change +- Perform a quick scan of open issues and ensure they are referenced in the pull request description (e.g. `Closes #1234`, `Relates #5678`). Edit the description yourself and mention this to the author: + +```markdown +This pull request appears to be related to/solve #1234, so I have edited the pull request description to denote the issue reference. +``` + +- Review the contents of the pull request and ensure the change follows the relevant section of the [Contributing Guide](https://github.com/terraform-providers/terraform-provider-aws/blob/master/docs/contributing/contribution-checklists.md) +- If the change is not acceptable, leave a long form comment about the reasoning and close the pull request +- If the change is acceptable with modifications, leave a pull request review marked using the `Request Changes` option (for maintainer pull requests with minor modification requests, giving feedback with the `Approve` option is recommended so they do not need to wait for another round of review) +- If the author is unresponsive for changes (by default we give two weeks), determine importance and level of effort to finish the pull request yourself including their commits or close the pull request +- Run relevant acceptance testing ([locally](https://github.com/terraform-providers/terraform-provider-aws/blob/master/docs/contributing/running-and-writing-acceptance-tests.md) or in TeamCity) against AWS Commercial and AWS GovCloud (US) to ensure no new failures are being introduced +- Approve the pull request with a comment outlining what steps you took that ensure the change is acceptable, e.g. acceptance testing output + +``````markdown +Looks good, thanks @username! :rocket: + +Output from acceptance testing in AWS Commercial: + +``` +--- PASS: TestAcc... +--- PASS: TestAcc... +``` + +Output from acceptance testing in AWS GovCloud (US): + +``` +--- PASS: TestAcc... +--- PASS: TestAcc... +``` +`````` + +#### Dependency Updates + +##### Go Default Version Update + +This project typically upgrades its Go version for development and testing shortly after release to get the latest and greatest Go functionality. Before beginning the update process, ensure that you review the new version release notes to look for any areas of possible friction when updating. + +Create an issue to cover the update noting down any areas of particular interest or friction. + +Ensure that the following steps are tracked within the issue and completed within the resulting pull request. + +- Update go version in `go.mod` +- Verify `make test lint` works as expected +- Verify `goreleaser build --snapshot` succeeds for all currently supported architectures +- Verify `goenv` support for the new version +- Update `docs/DEVELOPMENT.md` +- Update `.github/workflows/*.yml` +- Update `.go-version` +- Update `CHANGELOG.md` detailing the update and mention any notes practitioners need to be aware of. + +See [#9992](https://github.com/terraform-providers/terraform-provider-aws/issues/9992) / [#10206](https://github.com/terraform-providers/terraform-provider-aws/pull/10206) for a recent example. + +##### AWS Go SDK Updates + +Almost exclusively, `github.com/aws/aws-sdk-go` updates are additive in nature. It is generally safe to only scan through them before approving and merging. If you have any concerns about any of the service client updates such as suspicious code removals in the update, or deprecations introduced, run the acceptance testing for potentially affected resources before merging. + +Authentication changes: + +Occasionally, there will be changes listed in the authentication pieces of the AWS Go SDK codebase, e.g. changes to `aws/session`. The AWS Go SDK `CHANGELOG` should include a relevant description of these changes under a heading such as `SDK Enhancements` or `SDK Bug Fixes`. If they seem worthy of a callout in the Terraform AWS Provider `CHANGELOG`, then upon merging we should include a similar message prefixed with the `provider` subsystem, e.g. `* provider: ...`. + +Additionally, if a `CHANGELOG` addition seemed appropriate, this dependency and version should also be updated in the Terraform S3 Backend, which currently lives in Terraform Core. An example of this can be found with https://github.com/terraform-providers/terraform-provider-aws/pull/9305 and https://github.com/hashicorp/terraform/pull/22055. + +CloudFront changes: + +CloudFront service client updates have previously caused an issue when a new field introduced in the SDK was not included with Terraform and caused all requests to error (https://github.com/terraform-providers/terraform-provider-aws/issues/4091). As a precaution, if you see CloudFront updates, run all the CloudFront resource acceptance testing before merging (`TestAccAWSCloudFront`). + +New Regions: + +These are added to the AWS Go SDK `aws/endpoints/defaults.go` file and generally noted in the AWS Go SDK `CHANGELOG` as `aws/endpoints: Updated Regions`. Since April 2019, new regions added to AWS now require being explicitly enabled before they can be used. Examples of this can be found when `me-south-1` was announced: + +- [Terraform AWS Provider issue](https://github.com/terraform-providers/terraform-provider-aws/issues/9545) +- [Terraform AWS Provider AWS Go SDK update pull request](https://github.com/terraform-providers/terraform-provider-aws/pull/9538) +- [Terraform AWS Provider data source update pull request](https://github.com/terraform-providers/terraform-provider-aws/pull/9547) +- [Terraform S3 Backend issue](https://github.com/hashicorp/terraform/issues/22254) +- [Terraform S3 Backend pull request](https://github.com/hashicorp/terraform/pull/22253) + +Typically our process for new regions is as follows: + +- Create new (if not existing) Terraform AWS Provider issue: Support Automatic Region Validation for `XX-XXXXX-#` (Location) +- Create new (if not existing) Terraform S3 Backend issue: backend/s3: Support Automatic Region Validation for `XX-XXXXX-#` (Location) +- [Enable the new region in an AWS testing account](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable) and verify AWS Go SDK update works with the new region with `export AWS_DEFAULT_REGION=XX-XXXXX-#` with the new region and run the `TestAccDataSourceAwsRegion_` acceptance testing or by building the provider and testing a configuration like the following: + +```hcl +provider "aws" { + region = "me-south-1" +} + +data "aws_region" "current" {} + +output "region" { + value = data.aws_region.current.name +} +``` + +- Merge AWS Go SDK update in Terraform AWS Provider and close issue with the following information: + +``````markdown +Support for automatic validation of this new region has been merged and will release with version of the Terraform AWS Provider, later this week. + +--- + +Please note that this new region requires [a manual process to enable](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable). Once enabled in the console, it takes a few minutes for everything to work properly. + +If the region is not enabled properly, or the enablement process is still in progress, you can receive errors like these: + +```console +$ terraform apply + +Error: error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid. + status code: 403, request id: 142f947b-b2c3-11e9-9959-c11ab17bcc63 + + on main.tf line 1, in provider "aws": + 1: provider "aws" { +``` + +--- + +To use this new region before support has been added to Terraform AWS Provider version in use, you must disable the provider's automatic region validation via: + +```hcl +provider "aws" { + # ... potentially other configuration ... + + region = "me-south-1" + skip_region_validation = true +} +``` +`````` + +- Update the Terraform AWS Provider `CHANGELOG` with the following: + +```markdown +NOTES: + +* provider: Region validation now automatically supports the new `XX-XXXXX-#` (Location) region. For AWS operations to work in the new region, the region must be explicitly enabled as outlined in the [AWS Documentation](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable). When the region is not enabled, the Terraform AWS Provider will return errors during credential validation (e.g. `error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid`) or AWS operations will throw their own errors (e.g. `data.aws_availability_zones.available: Error fetching Availability Zones: AuthFailure: AWS was not able to validate the provided access credentials`). [GH-####] + +ENHANCEMENTS: + +* provider: Support automatic region validation for `XX-XXXXX-#` [GH-####] +``` + +- Follow the [Contributing Guide](contributing/contribution-checklists.md#new-region) to submit updates for various data sources to support the new region +- Submit the dependency update to the Terraform S3 Backend by running the following: + +```shell +go get github.com/aws/aws-sdk-go@v#.#.# +go mod tidy +go mod vendor +``` + +- Create a S3 Bucket in the new region and verify AWS Go SDK update works with new region by building the Terraform S3 Backend and testing a configuration like the following: + +```hcl +terraform { + backend "s3" { + bucket = "XXX" + key = "test" + region = "me-south-1" + } +} + +output "test" { + value = timestamp() +} +``` + +- After approval, merge AWS Go SDK update in Terraform S3 Backend and close issue with the following information: + +``````markdown +Support for automatic validation of this new region has been merged and will release with the next version of the Terraform. + +This was verified on a build of Terraform with the update: + +```hcl +terraform { + backend "s3" { + bucket = "XXX" + key = "test" + region = "me-south-1" + } +} + +output "test" { + value = timestamp() +} +``` + +Outputs: + +```console +$ terraform init +... +Terraform has been successfully initialized! +``` + +--- + +Please note that this new region requires [a manual process to enable](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable). Once enabled in the console, it takes a few minutes for everything to work properly. + +If the region is not enabled properly, or the enablement process is still in progress, you can receive errors like these: + +```console +$ terraform init + +Initializing the backend... + +Error: error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid. +``` + +--- + +To use this new region before this update is released, you must disable the Terraform S3 Backend's automatic region validation via: + +```hcl +terraform { + # ... potentially other configuration ... + + backend "s3" { + # ... other configuration ... + + region = "me-south-1" + skip_region_validation = true + } +} +``` +`````` + +- Update the Terraform S3 Backend `CHANGELOG` with the following: + +```markdown +NOTES: + +* backend/s3: Region validation now automatically supports the new `XX-XXXXX-#` (Location) region. For AWS operations to work in the new region, the region must be explicitly enabled as outlined in the [AWS Documentation](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable). When the region is not enabled, the Terraform S3 Backend will return errors during credential validation (e.g. `error validating provider credentials: error calling sts:GetCallerIdentity: InvalidClientTokenId: The security token included in the request is invalid`). [GH-####] + +ENHANCEMENTS: + +* backend/s3: Support automatic region validation for `XX-XXXXX-#` [GH-####] +``` + +##### golangci-lint Updates + +Merge if CI passes. + +##### Terraform Plugin SDK Updates + +Except for trivial changes, run the full acceptance testing suite against the pull request and verify there are no new or unexpected failures. + +##### tfproviderdocs Updates + +Merge if CI passes. + +##### tfproviderlint Updates + +Merge if CI passes. + +##### yaml.v2 Updates + +Run the acceptance testing pattern, `TestAccAWSCloudFormationStack(_dataSource)?_yaml`, and merge if passing. + +### Pull Request Merge Process + +- Add this pull request to the upcoming release milestone +- Add any linked issues that will be closed by the pull request to the same upcoming release milestone +- Merge the pull request +- Delete the branch (if the branch is on this repository) +- Determine if the pull request should have a CHANGELOG entry by reviewing the [Pull Request Types to CHANGELOG section](#pull-request-types-to-changelog). If so, update the repository `CHANGELOG.md` by directly committing to the `master` branch (e.g. editing the file in the GitHub web interface). See also the [Extending Terraform documentation](https://www.terraform.io/docs/extend/best-practices/versioning.html) for more information about the expected CHANGELOG format. +- Leave a comment on any issues closed by the pull request noting that it has been merged and when to expect the release containing it, e.g. + +```markdown +The fix for this has been merged and will release with version X.Y.Z of the Terraform AWS Provider, expected in the XXX timeframe. +``` + +### Pull Request Types to CHANGELOG + +The CHANGELOG is intended to show operator-impacting changes to the codebase for a particular version. If every change or commit to the code resulted in an entry, the CHANGELOG would become less useful for operators. The lists below are general guidelines on when a decision needs to be made to decide whether a change should have an entry. + +#### Changes that should have a CHANGELOG entry + +- New Resources and Data Sources +- New full-length documentation guides (e.g. EKS Getting Started Guide, IAM Policy Documents with Terraform) +- Resource and provider bug fixes +- Resource and provider enhancements +- Deprecations +- Removals + +#### Changes that may have a CHANGELOG entry + +- Dependency updates: If the update contains relevant bug fixes or enhancements that affect operators, those should be called out. + +#### Changes that should _not_ have a CHANGELOG entry + +- Resource and provider documentation updates +- Testing updates + +## Breaking Changes + +When breaking changes to the provider are necessary we release them in a major version. If an issue or PR necessitates a breaking change, then the following procedure should be observed: + +- Add the `breaking-change` label. +- Add the issue/PR to the next major version milestone. +- Leave a comment why this is a breaking change or otherwise only being considered for a major version update. If possible, detail any changes that might be made for the contributor to accomplish the task without a breaking change. + +## Branch Dictionary + +The following branch conventions are used: + +| Branch | Example | Description | +|--------|---------|-------------| +| `master` | `master` | Main, unreleased code branch. | +| `release/*` | `release/2.x` | Backport branches for previous major releases. | + +Additional branch naming recommendations can be found in the [Pull Request Submission and Lifecycle documentation](contributing/pullrequest-submission-and-lifecycle.md#branch-prefixes). + +## Environment Variable Dictionary + +Environment variables (beyond standard AWS Go SDK ones) used by acceptance testing. + +| Variable | Description | +|----------|-------------| +| `ACM_CERTIFICATE_ROOT_DOMAIN` | Root domain name to use with ACM Certificate testing. | +| `ACM_CERTIFICATE_MULTIPLE_ISSUED_DOMAIN` | Domain name of ACM Certificate with a multiple issued certificates. **DEPRECATED:** Should be replaced with `aws_acm_certficate` resource usage in tests. | +| `ACM_CERTIFICATE_MULTIPLE_ISSUED_MOST_RECENT_ARN` | Amazon Resource Name of most recent ACM Certificate with a multiple issued certificates. **DEPRECATED:** Should be replaced with `aws_acm_certficate` resource usage in tests. | +| `ACM_CERTIFICATE_SINGLE_ISSUED_DOMAIN` | Domain name of ACM Certificate with a single issued certificate. **DEPRECATED:** Should be replaced with `aws_acm_certficate` resource usage in tests. | +| `ACM_CERTIFICATE_SINGLE_ISSUED_MOST_RECENT_ARN` | Amazon Resource Name of most recent ACM Certificate with a single issued certificate. **DEPRECATED:** Should be replaced with `aws_acm_certficate` resource usage in tests. | +| `ADM_CLIENT_ID` | Identifier for Amazon Device Manager Client in Pinpoint testing. | +| `ADM_CLIENT_SECRET` | Secret for Amazon Device Manager Client in Pinpoint testing. | +| `APNS_BUNDLE_ID` | Identifier for Apple Push Notification Service Bundle in Pinpoint testing. | +| `APNS_CERTIFICATE` | Certificate (PEM format) for Apple Push Notification Service in Pinpoint testing. | +| `APNS_CERTIFICATE_PRIVATE_KEY` | Private key for Apple Push Notification Service in Pinpoint testing. | +| `APNS_SANDBOX_BUNDLE_ID` | Identifier for Sandbox Apple Push Notification Service Bundle in Pinpoint testing. | +| `APNS_SANDBOX_CERTIFICATE` | Certificate (PEM format) for Sandbox Apple Push Notification Service in Pinpoint testing. | +| `APNS_SANDBOX_CERTIFICATE_PRIVATE_KEY` | Private key for Sandbox Apple Push Notification Service in Pinpoint testing. | +| `APNS_SANDBOX_CREDENTIAL` | Credential contents for Sandbox Apple Push Notification Service in SNS Application Platform testing. Conflicts with `APNS_SANDBOX_CREDENTIAL_PATH`. | +| `APNS_SANDBOX_CREDENTIAL_PATH` | Path to credential for Sandbox Apple Push Notification Service in SNS Application Platform testing. Conflicts with `APNS_SANDBOX_CREDENTIAL`. | +| `APNS_SANDBOX_PRINCIPAL` | Principal contents for Sandbox Apple Push Notification Service in SNS Application Platform testing. Conflicts with `APNS_SANDBOX_PRINCIPAL_PATH`. | +| `APNS_SANDBOX_PRINCIPAL_PATH` | Path to principal for Sandbox Apple Push Notification Service in SNS Application Platform testing. Conflicts with `APNS_SANDBOX_PRINCIPAL`. | +| `APNS_SANDBOX_TEAM_ID` | Identifier for Sandbox Apple Push Notification Service Team in Pinpoint testing. | +| `APNS_SANDBOX_TOKEN_KEY` | Token key file content (.p8 format) for Sandbox Apple Push Notification Service in Pinpoint testing. | +| `APNS_SANDBOX_TOKEN_KEY_ID` | Identifier for Sandbox Apple Push Notification Service Token Key in Pinpoint testing. | +| `APNS_TEAM_ID` | Identifier for Apple Push Notification Service Team in Pinpoint testing. | +| `APNS_TOKEN_KEY` | Token key file content (.p8 format) for Apple Push Notification Service in Pinpoint testing. | +| `APNS_TOKEN_KEY_ID` | Identifier for Apple Push Notification Service Token Key in Pinpoint testing. | +| `APNS_VOIP_BUNDLE_ID` | Identifier for VOIP Apple Push Notification Service Bundle in Pinpoint testing. | +| `APNS_VOIP_CERTIFICATE` | Certificate (PEM format) for VOIP Apple Push Notification Service in Pinpoint testing. | +| `APNS_VOIP_CERTIFICATE_PRIVATE_KEY` | Private key for VOIP Apple Push Notification Service in Pinpoint testing. | +| `APNS_VOIP_TEAM_ID` | Identifier for VOIP Apple Push Notification Service Team in Pinpoint testing. | +| `APNS_VOIP_TOKEN_KEY` | Token key file content (.p8 format) for VOIP Apple Push Notification Service in Pinpoint testing. | +| `APNS_VOIP_TOKEN_KEY_ID` | Identifier for VOIP Apple Push Notification Service Token Key in Pinpoint testing. | +| `AWS_ALTERNATE_ACCESS_KEY_ID` | AWS access key ID with access to a secondary AWS account for tests requiring multiple accounts. Requires `AWS_ALTERNATE_SECRET_ACCESS_KEY`. Conflicts with `AWS_ALTERNATE_PROFILE`. | +| `AWS_ALTERNATE_SECRET_ACCESS_KEY` | AWS secret access key with access to a secondary AWS account for tests requiring multiple accounts. Requires `AWS_ALTERNATE_ACCESS_KEY_ID`. Conflicts with `AWS_ALTERNATE_PROFILE`. | +| `AWS_ALTERNATE_PROFILE` | AWS profile with access to a secondary AWS account for tests requiring multiple accounts. Conflicts with `AWS_ALTERNATE_ACCESS_KEY_ID` and `AWS_ALTERNATE_SECRET_ACCESS_KEY`. | +| `AWS_ALTERNATE_REGION` | Secondary AWS region for tests requiring multiple regions. Defaults to `us-east-1`. | +| `AWS_API_GATEWAY_DOMAIN_NAME_CERTIFICATE_ARN` | Amazon Resource Name of ACM Certificate in `us-east-1` for API Gateway Domain Name testing. | +| `AWS_API_GATEWAY_DOMAIN_NAME_CERTIFICATE_BODY` | Certificate body of publicly trusted certificate for API Gateway Domain Name testing. | +| `AWS_API_GATEWAY_DOMAIN_NAME_CERTIFICATE_CHAIN` | Certificate chain of publicly trusted certificate for API Gateway Domain Name testing. | +| `AWS_API_GATEWAY_DOMAIN_NAME_CERTIFICATE_PRIVATE_KEY` | Private key of publicly trusted certificate for API Gateway Domain Name testing. | +| `AWS_API_GATEWAY_DOMAIN_NAME_REGIONAL_CERTIFICATE_NAME_ENABLED` | Flag to enable API Gateway Domain Name regional certificate upload testing. | +| `AWS_CODEBUILD_BITBUCKET_SOURCE_LOCATION` | BitBucket source URL for CodeBuild testing. CodeBuild must have access to this repository via OAuth or Source Credentials. Defaults to `https://terraform@bitbucket.org/terraform/aws-test.git`. | +| `AWS_CODEBUILD_GITHUB_SOURCE_LOCATION` | GitHub source URL for CodeBuild testing. CodeBuild must have access to this repository via OAuth or Source Credentials. Defaults to `https://github.com/hashibot-test/aws-test.git`. | +| `AWS_COGNITO_USER_POOL_DOMAIN_CERTIFICATE_ARN` | Amazon Resource Name of ACM Certificate in `us-east-1` for Cognito User Pool Domain Name testing. | +| `AWS_COGNITO_USER_POOL_DOMAIN_ROOT_DOMAIN` | Root domain name to use with Cognito User Pool Domain testing. | +| `AWS_DEFAULT_REGION` | Primary AWS region for tests. Defaults to `us-west-2`. | +| `AWS_EC2_CLIENT_VPN_LIMIT` | Concurrency limit for Client VPN acceptance tests. [Default is 5](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/limits.html) if not specified. | +| `AWS_EC2_EIP_PUBLIC_IPV4_POOL` | Identifier for EC2 Public IPv4 Pool for EC2 EIP testing. | +| `AWS_GUARDDUTY_MEMBER_ACCOUNT_ID` | Identifier of AWS Account for GuardDuty Member testing. **DEPRECATED:** Should be replaced with standard alternate account handling for tests. | +| `AWS_GUARDDUTY_MEMBER_EMAIL` | Email address for GuardDuty Member testing. **DEPRECATED:** It may be possible to use a placeholder email address instead. | +| `DX_CONNECTION_ID` | Identifier for Direct Connect Connection testing. | +| `DX_VIRTUAL_INTERFACE_ID` | Identifier for Direct Connect Virtual Interface testing. | +| `EC2_SECURITY_GROUP_RULES_PER_GROUP_LIMIT` | EC2 Quota for Rules per Security Group. Defaults to 50. **DEPRECATED:** Can be augmented or replaced with Service Quotas lookup. | +| `GCM_API_KEY` | API Key for Google Cloud Messaging in Pinpoint and SNS Platform Application testing. | +| `GITHUB_TOKEN` | GitHub token for CodePipeline testing. | +| `MACIE_MEMBER_ACCOUNT_ID` | Identifier of AWS Account for Macie Member testing. **DEPRECATED:** Should be replaced with standard alternate account handling for tests. | +| `SERVICEQUOTAS_INCREASE_ON_CREATE_QUOTA_CODE` | Quota Code for Service Quotas testing (submits support case). | +| `SERVICEQUOTAS_INCREASE_ON_CREATE_SERVICE_CODE` | Service Code for Service Quotas testing (submits support case). | +| `SERVICEQUOTAS_INCREASE_ON_CREATE_VALUE` | Value of quota increase for Service Quotas testing (submits support case). | +| `SES_DOMAIN_IDENTITY_ROOT_DOMAIN` | Root domain name of publicly accessible and Route 53 configurable domain for SES Domain Identity testing. | +| `SWF_DOMAIN_TESTING_ENABLED` | Enables SWF Domain testing (API does not support deletions). | +| `TEST_AWS_ORGANIZATION_ACCOUNT_EMAIL_DOMAIN` | Email address for Organizations Account testing. | +| `TEST_AWS_SES_VERIFIED_EMAIL_ARN` | Verified SES Email Identity for use in Cognito User Pool testing. | +| `TF_ACC` | Enables Go tests containing `resource.Test()` and `resource.ParallelTest()`. | +| `TF_ACC_ASSUME_ROLE_ARN` | Amazon Resource Name of existing IAM Role to use for limited permissions acceptance testing. | +| `TF_TEST_CLOUDFRONT_RETAIN` | Flag to disable but dangle CloudFront Distributions during testing to reduce feedback time (must be manually destroyed afterwards) | + +## Label Dictionary + + + +| Label | Description | Automation | +|---------|-------------|----------| +| [![breaking-change][breaking-change-badge]][breaking-change]                                    | Introduces a breaking change in current functionality; breaking changes are usually deferred to the next major release. | None | +| [![bug][bug-badge]][bug] | Addresses a defect in current functionality. | None | +| [![crash][crash-badge]][crash] | Results from or addresses a Terraform crash or kernel panic. | None | +| [![dependencies][dependencies-badge]][dependencies] | Used to indicate dependency or vendoring changes. | Added by Hashibot. | +| [![documentation][documentation-badge]][documentation] | Introduces or discusses updates to documentation. | None | +| [![enhancement][enhancement-badge]][enhancement] | Requests to existing resources that expand the functionality or scope. | None | +| [![examples][examples-badge]][examples] | Introduces or discusses updates to examples. | None | +| [![good first issue][good-first-issue-badge]][good-first-issue] | Call to action for new contributors looking for a place to start. Smaller or straightforward issues. | None | +| [![hacktoberfest][hacktoberfest-badge]][hacktoberfest] | Call to action for Hacktoberfest (OSS Initiative). | None | +| [![hashibot ignore][hashibot-ignore-badge]][hashibot-ignore] | Issues or PRs labelled with this are ignored by Hashibot. | None | +| [![help wanted][help-wanted-badge]][help-wanted] | Call to action for contributors. Indicates an area of the codebase we’d like to expand/work on but don’t have the bandwidth inside the team. | None | +| [![needs-triage][needs-triage-badge]][needs-triage] | Waiting for first response or review from a maintainer. | Added to all new issues or PRs by GitHub action in `.github/workflows/issues.yml` or PRs by Hashibot in `.hashibot.hcl` unless they were submitted by a maintainer. | +| [![new-data-source][new-data-source-badge]][new-data-source] | Introduces a new data source. | None | +| [![new-resource][new-resource-badge]][new-resource] | Introduces a new resrouce. | None | +| [![proposal][proposal-badge]][proposal] | Proposes new design or functionality. | None | +| [![provider][provider-badge]][provider] | Pertains to the provider itself, rather than any interaction with AWS. | Added by Hashibot when the code change is in an area configured in `.hashibot.hcl` | +| [![question][question-badge]][question] | Includes a question about existing functionality; most questions will be re-routed to discuss.hashicorp.com. | None | +| [![regression][regression-badge]][regression] | Pertains to a degraded workflow resulting from an upstream patch or internal enhancement; usually categorized as a bug. | None | +| [![reinvent][reinvent-badge]][reinvent] | Pertains to a service or feature announced at reinvent. | None | +| ![service <*>][service-badge] | Indicates the service that is covered or introduced (i.e. service/s3) | Added by Hashibot when the code change matches a service definition in `.hashibot.hcl`. +| ![size%2F<*>][size-badge] | Managed by automation to categorize the size of a PR | Added by Hashibot to indicate the size of the PR. | +| [![stale][stale-badge]][stale] | Old or inactive issues managed by automation, if no further action taken these will get closed. | Added by a Github Action, configuration is found: `.github/workflows/stale.yml`. | +| [![technical-debt][technical-debt-badge]][technical-debt] | Addresses areas of the codebase that need refactoring or redesign. | None | +| [![tests][tests-badge]][tests] | On a PR this indicates expanded test coverage. On an Issue this proposes expanded coverage or enhancement to test infrastructure. | None | +| [![thinking][thinking-badge]][thinking] | Requires additional research by the maintainers. | None | +| [![upstream-terraform][upstream-terraform-badge]][upstream-terraform] | Addresses functionality related to the Terraform core binary. | None | +| [![upstream][upstream-badge]][upstream] | Addresses functionality related to the cloud provider. | None | +| [![waiting-response][waiting-response-badge]][waiting-response] | Maintainers are waiting on response from community or contributor. | None | + +[breaking-change-badge]: https://img.shields.io/badge/breaking--change-d93f0b +[breaking-change]: https://github.com/terraform-providers/terraform-provider-aws/labels/breaking-change +[bug-badge]: https://img.shields.io/badge/bug-f7c6c7 +[bug]: https://github.com/terraform-providers/terraform-provider-aws/labels/bug +[crash-badge]: https://img.shields.io/badge/crash-e11d21 +[crash]: https://github.com/terraform-providers/terraform-provider-aws/labels/crash +[dependencies-badge]: https://img.shields.io/badge/dependencies-fad8c7 +[dependencies]: https://github.com/terraform-providers/terraform-provider-aws/labels/dependencies +[documentation-badge]: https://img.shields.io/badge/documentation-fef2c0 +[documentation]: https://github.com/terraform-providers/terraform-provider-aws/labels/documentation +[enhancement-badge]: https://img.shields.io/badge/enhancement-d4c5f9 +[enhancement]: https://github.com/terraform-providers/terraform-provider-aws/labels/enhancement +[examples-badge]: https://img.shields.io/badge/examples-fef2c0 +[examples]: https://github.com/terraform-providers/terraform-provider-aws/labels/examples +[good-first-issue-badge]: https://img.shields.io/badge/good%20first%20issue-128A0C +[good-first-issue]: https://github.com/terraform-providers/terraform-provider-aws/labels/good%20first%20issue +[hacktoberfest-badge]: https://img.shields.io/badge/hacktoberfest-2c0fad +[hacktoberfest]: https://github.com/terraform-providers/terraform-provider-aws/labels/hacktoberfest +[hashibot-ignore-badge]: https://img.shields.io/badge/hashibot%2Fignore-2c0fad +[hashibot-ignore]: https://github.com/terraform-providers/terraform-provider-aws/labels/hashibot-ignore +[help-wanted-badge]: https://img.shields.io/badge/help%20wanted-128A0C +[help-wanted]: https://github.com/terraform-providers/terraform-provider-aws/labels/help-wanted +[needs-triage-badge]: https://img.shields.io/badge/needs--triage-e236d7 +[needs-triage]: https://github.com/terraform-providers/terraform-provider-aws/labels/needs-triage +[new-data-source-badge]: https://img.shields.io/badge/new--data--source-d4c5f9 +[new-data-source]: https://github.com/terraform-providers/terraform-provider-aws/labels/new-data-source +[new-resource-badge]: https://img.shields.io/badge/new--resource-d4c5f9 +[new-resource]: https://github.com/terraform-providers/terraform-provider-aws/labels/new-resource +[proposal-badge]: https://img.shields.io/badge/proposal-fbca04 +[proposal]: https://github.com/terraform-providers/terraform-provider-aws/labels/proposal +[provider-badge]: https://img.shields.io/badge/provider-bfd4f2 +[provider]: https://github.com/terraform-providers/terraform-provider-aws/labels/provider +[question-badge]: https://img.shields.io/badge/question-d4c5f9 +[question]: https://github.com/terraform-providers/terraform-provider-aws/labels/question +[regression-badge]: https://img.shields.io/badge/regression-e11d21 +[regression]: https://github.com/terraform-providers/terraform-provider-aws/labels/regression +[reinvent-badge]: https://img.shields.io/badge/reinvent-c5def5 +[reinvent]: https://github.com/terraform-providers/terraform-provider-aws/labels/reinvent +[service-badge]: https://img.shields.io/badge/service%2F<*>-bfd4f2 +[size-badge]: https://img.shields.io/badge/size%2F<*>-ffffff +[stale-badge]: https://img.shields.io/badge/stale-e11d21 +[stale]: https://github.com/terraform-providers/terraform-provider-aws/labels/stale +[technical-debt-badge]: https://img.shields.io/badge/technical--debt-1d76db +[technical-debt]: https://github.com/terraform-providers/terraform-provider-aws/labels/technical-debt +[tests-badge]: https://img.shields.io/badge/tests-DDDDDD +[tests]: https://github.com/terraform-providers/terraform-provider-aws/labels/tests +[thinking-badge]: https://img.shields.io/badge/thinking-bfd4f2 +[thinking]: https://github.com/terraform-providers/terraform-provider-aws/labels/thinking +[upstream-terraform-badge]: https://img.shields.io/badge/upstream--terraform-CCCCCC +[upstream-terraform]: https://github.com/terraform-providers/terraform-provider-aws/labels/upstream-terraform +[upstream-badge]: https://img.shields.io/badge/upstream-fad8c7 +[upstream]: https://github.com/terraform-providers/terraform-provider-aws/labels/upstream +[waiting-response-badge]: https://img.shields.io/badge/waiting--response-5319e7 +[waiting-response]: https://github.com/terraform-providers/terraform-provider-aws/labels/waiting-response diff --git a/docs/contributing/contribution-checklists.md b/docs/contributing/contribution-checklists.md new file mode 100644 index 00000000000..c1edaba7f9e --- /dev/null +++ b/docs/contributing/contribution-checklists.md @@ -0,0 +1,578 @@ +# Contribution Types and Checklists + +There are several different kinds of contribution, each of which has its own +standards for a speedy review. The following sections describe guidelines for +each type of contribution. + +- [Documentation Update](#documentation-update) +- [Enhancement/Bugfix to a Resource](#enhancementbugfix-to-a-resource) +- [Adding Resource Import Support](#adding-resource-import-support) +- [Adding Resource Name Generation Support](#adding-resource-name-generation-support) + - [Resource Name Generation Code Implementation](#resource-name-generation-code-implementation) + - [Resource Name Generation Testing Implementation](#resource-name-generation-testing-implementation) + - [Resource Code Generation Documentation Implementation](#resource-code-generation-documentation-implementation) +- [Adding Resource Policy Support](#adding-resource-policy-support) +- [Adding Resource Tagging Support](#adding-resource-tagging-support) + - [Adding Service to Tag Generating Code](#adding-service-to-tag-generating-code) + - [Resource Tagging Code Implementation](#resource-tagging-code-implementation) + - [Resource Tagging Acceptance Testing Implementation](#resource-tagging-acceptance-testing-implementation) + - [Resource Tagging Documentation Implementation](#resource-tagging-documentation-implementation) +- [New Resource](#new-resource) +- [New Service](#new-service) +- [New Region](#new-region) + +## Documentation Update + +The [Terraform AWS Provider's website source][website] is in this repository +along with the code and tests. Below are some common items that will get +flagged during documentation reviews: + +- [ ] __Reasoning for Change__: Documentation updates should include an explanation for why the update is needed. +- [ ] __Prefer AWS Documentation__: Documentation about AWS service features and valid argument values that are likely to update over time should link to AWS service user guides and API references where possible. +- [ ] __Large Example Configurations__: Example Terraform configuration that includes multiple resource definitions should be added to the repository `examples` directory instead of an individual resource documentation page. Each directory under `examples` should be self-contained to call `terraform apply` without special configuration. +- [ ] __Terraform Configuration Language Features__: Individual resource documentation pages and examples should refrain from highlighting particular Terraform configuration language syntax workarounds or features such as `variable`, `local`, `count`, and built-in functions. + +## Enhancement/Bugfix to a Resource + +Working on existing resources is a great way to get started as a Terraform +contributor because you can work within existing code and tests to get a feel +for what to do. + +In addition to the below checklist, please see the [Common Review +Items](pullrequest-submission-and-lifecycle.md#common-review-items) sections for more specific coding and testing +guidelines. + +- [ ] __Acceptance test coverage of new behavior__: Existing resources each + have a set of [acceptance tests][acctests] covering their functionality. + These tests should exercise all the behavior of the resource. Whether you are + adding something or fixing a bug, the idea is to have an acceptance test that + fails if your code were to be removed. Sometimes it is sufficient to + "enhance" an existing test by adding an assertion or tweaking the config + that is used, but it's often better to add a new test. You can copy/paste an + existing test and follow the conventions you see there, modifying the test + to exercise the behavior of your code. +- [ ] __Documentation updates__: If your code makes any changes that need to + be documented, you should include those doc updates in the same PR. This + includes things like new resource attributes or changes in default values. + The [Terraform website][website] source is in this repo and includes + instructions for getting a local copy of the site up and running if you'd + like to preview your changes. +- [ ] __Well-formed Code__: Do your best to follow existing conventions you + see in the codebase, and ensure your code is formatted with `go fmt`. + The PR reviewers can help out on this front, and may provide comments with + suggestions on how to improve the code. +- [ ] __Vendor additions__: Create a separate PR if you are updating the vendor + folder. This is to avoid conflicts as the vendor versions tend to be fast- + moving targets. We will plan to merge the PR with this change first. + +## Adding Resource Import Support + +Adding import support for Terraform resources will allow existing infrastructure to be managed within Terraform. This type of enhancement generally requires a small to moderate amount of code changes. + +Comprehensive code examples and information about resource import support can be found in the [Extending Terraform documentation](https://www.terraform.io/docs/extend/resources/import.html). + +In addition to the below checklist and the items noted in the Extending Terraform documentation, please see the [Common Review Items](pullrequest-submission-and-lifecycle.md#common-review-items) sections for more specific coding and testing guidelines. + +- [ ] _Resource Code Implementation_: In the resource code (e.g. `aws/resource_aws_service_thing.go`), implementation of `Importer` `State` function +- [ ] _Resource Acceptance Testing Implementation_: In the resource acceptance testing (e.g. `aws/resource_aws_service_thing_test.go`), implementation of `TestStep`s with `ImportState: true` +- [ ] _Resource Documentation Implementation_: In the resource documentation (e.g. `website/docs/r/service_thing.html.markdown`), addition of `Import` documentation section at the bottom of the page + +## Adding Resource Name Generation Support + +Terraform AWS Provider resources can use shared logic to support and test name generation, where the operator can choose between an expected naming value, a generated naming value with a prefix, or a fully generated name. + +Implementing name generation support for Terraform AWS Provider resources requires the following, each with its own section below: + +- [ ] _Resource Name Generation Code Implementation_: In the resource code (e.g. `aws/resource_aws_service_thing.go`), implementation of `name_prefix` attribute, along with handling in `Create` function. +- [ ] _Resource Name Generation Testing Implementation_: In the resource acceptance testing (e.g. `aws/resource_aws_service_thing_test.go`), implementation of new acceptance test functions and configurations to exercise new naming logic. +- [ ] _Resource Name Generation Documentation Implementation_: In the resource documentation (e.g. `website/docs/r/service_thing.html.markdown`), addition of `name_prefix` argument and update of `name` argument description. + +### Resource Name Generation Code Implementation + +- In the resource Go file (e.g. `aws/resource_aws_service_thing.go`), add the following Go import: `"github.com/terraform-providers/terraform-provider-aws/aws/internal/naming"` +- In the resource schema, add the new `name_prefix` attribute and adjust the `name` attribute to be `Optional`, `Computed`, and `ConflictsWith` the `name_prefix` attribute. Ensure to keep any existing schema fields on `name` such as `ValidateFunc`. e.g. + +```go +"name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + ConflictsWith: []string{"name_prefix"}, +}, +"name_prefix": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ConflictsWith: []string{"name"}, +}, +``` + +- In the resource `Create` function, switch any calls from `d.Get("name").(string)` to instead use the `naming.Generate()` function, e.g. + +```go +name := naming.Generate(d.Get("name").(string), d.Get("name_prefix").(string)) + +// ... in AWS Go SDK Input types, etc. use aws.String(name) +``` + +### Resource Name Generation Testing Implementation + +- In the resource testing (e.g. `aws/resource_aws_service_thing_test.go`), add the following Go import: `"github.com/terraform-providers/terraform-provider-aws/aws/internal/naming"` +- In the resource testing, implement two new tests named `_Name_Generated` and `_NamePrefix` with associated configurations, that verifies creating the resource without `name` and `name_prefix` arguments (for the former) and with only the `name_prefix` argument (for the latter). e.g. + +```go +func TestAccAWSServiceThing_Name_Generated(t *testing.T) { + var thing service.ServiceThing + resourceName := "aws_service_thing.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSServiceThingDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSServiceThingConfigNameGenerated(), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSServiceThingExists(resourceName, &thing), + naming.TestCheckResourceAttrNameGenerated(resourceName, "name"), + ), + }, + // If the resource supports import: + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAWSServiceThing_NamePrefix(t *testing.T) { + var thing service.ServiceThing + resourceName := "aws_service_thing.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSServiceThingDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSServiceThingConfigNamePrefix("tf-acc-test-prefix-"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSServiceThingExists(resourceName, &thing), + naming.TestCheckResourceAttrNameFromPrefix(resourceName, "name", "tf-acc-test-prefix-"), + ), + }, + // If the resource supports import: + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccAWSServiceThingConfigNameGenerated() string { + return fmt.Sprintf(` +resource "aws_service_thing" "test" { + # ... other configuration ... +} +`) +} + +func testAccAWSServiceThingConfigNamePrefix(namePrefix string) string { + return fmt.Sprintf(` +resource "aws_service_thing" "test" { + # ... other configuration ... + + name_prefix = %[1]q +} +`, namePrefix) +} +``` + +### Resource Code Generation Documentation Implementation + +- In the resource documentation (e.g. `website/docs/r/service_thing.html.markdown`), add the following to the arguments reference: + +```markdown +* `name_prefix` - (Optional) Creates a unique name beginning with the specified prefix. Conflicts with `name`. +``` + +- Adjust the existing `name` argument reference to ensure its denoted as `Optional`, includes a mention that it can be generated, and that it conflicts with `name_prefix`: + +```markdown +* `name` - (Optional) Name of the thing. If omitted, Terraform will assign a random, unique name. Conflicts with `name_prefix`. +``` + +## Adding Resource Policy Support + +Some AWS components support [resource-based IAM policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_identity-vs-resource.html) to control permissions. When implementing this support in the Terraform AWS Provider, we typically prefer creating a separate resource, `aws_{SERVICE}_{THING}_policy` (e.g. `aws_s3_bucket_policy`) for a few reasons: + +- Many of these policies require the Amazon Resource Name (ARN) of the resource in the policy itself. It is difficult to workaround this requirement with custom difference handling within a self-contained resource. +- Sometimes policies between two resources need to be written where they cross-reference each other resource's ARN within each policy. Without a separate resource, this introduces a configuration cycle. +- Splitting the resources allows operators to logically split their infrastructure on purely operational and security boundaries with separate configurations/modules. +- Splitting the resources prevents any separate policy API calls from needing to be permitted in the main resource in environments with restrictive IAM permissions, which can be undesirable. + +Follow the [New Resource section][#new-resource] for more information about implementing the separate resource. + +## Adding Resource Tagging Support + +AWS provides key-value metadata across many services and resources, which can be used for a variety of use cases including billing, ownership, and more. See the [AWS Tagging Strategy page](https://aws.amazon.com/answers/account-management/aws-tagging-strategies/) for more information about tagging at a high level. + +Implementing tagging support for Terraform AWS Provider resources requires the following, each with its own section below: + +- [ ] _Generated Service Tagging Code_: In the internal code generators (e.g. `aws/internal/keyvaluetags`), implementation and customization of how a service handles tagging, which is standardized for the resources. +- [ ] _Resource Tagging Code Implementation_: In the resource code (e.g. `aws/resource_aws_service_thing.go`), implementation of `tags` schema attribute, along with handling in `Create`, `Read`, and `Update` functions. +- [ ] _Resource Tagging Acceptance Testing Implementation_: In the resource acceptance testing (e.g. `aws/resource_aws_service_thing_test.go`), implementation of new acceptance test function and configurations to exercise new tagging logic. +- [ ] _Resource Tagging Documentation Implementation_: In the resource documentation (e.g. `website/docs/r/service_thing.html.markdown`), addition of `tags` argument + +See also a [full example pull request for implementing EKS tagging](https://github.com/terraform-providers/terraform-provider-aws/pull/10307). + +### Adding Service to Tag Generating Code + +This step is only necessary for the first implementation and may have been previously completed. If so, move on to the next section. + +More details about this code generation, including fixes for potential error messages in this process, can be found in the [keyvaluetags documentation](../../aws/internal/keyvaluetags/README.md). + +- Open the AWS Go SDK documentation for the service, e.g. for [`service/eks`](https://docs.aws.amazon.com/sdk-for-go/api/service/eks/). Note: there can be a delay between the AWS announcement and the updated AWS Go SDK documentation. +- Determine the "type" of tagging implementation. Some services will use a simple map style (`map[string]*string` in Go) while others will have a separate structure shape (`[]service.Tag` struct with `Key` and `Value` fields). + + - If the type is a map, add the AWS Go SDK service name (e.g. `eks`) to `mapServiceNames` in `aws/internal/keyvaluetags/generators/servicetags/main.go` + - Otherwise, if the type is a struct, add the AWS Go SDK service name (e.g. `eks`) to `sliceServiceNames` in `aws/internal/keyvaluetags/generators/servicetags/main.go`. If the struct name is not exactly `Tag`, it can be customized via the `ServiceTagType` function. If the struct key field is not exactly `Key`, it can be customized via the `ServiceTagTypeKeyField` function. If the struct value field is not exactly `Value`, it can be customized via the `ServiceTagTypeValueField` function. + +- Determine if the service API includes functionality for listing tags (usually a `ListTags` or `ListTagsForResource` API call) or updating tags (usually `TagResource` and `UntagResource` API calls). If so, add the AWS Go SDK service client information to `ServiceClientType` (along with the new required import) in `aws/internal/keyvaluetags/service_generation_customizations.go`, e.g. for EKS: + + ```go + case "eks": + funcType = reflect.TypeOf(eks.New) + ``` + + - If the service API includes functionality for listing tags, add the AWS Go SDK service name (e.g. `eks`) to `serviceNames` in `aws/internal/keyvaluetags/generators/listtags/main.go`. + - If the service API includes functionality for updating tags, add the AWS Go SDK service name (e.g. `eks`) to `serviceNames` in `aws/internal/keyvaluetags/generators/updatetags/main.go`. + +- Run `make gen` (`go generate ./...`) and ensure there are no errors via `make test` (`go test ./...`) + +### Resource Tagging Code Implementation + +- In the resource Go file (e.g. `aws/resource_aws_eks_cluster.go`), add the following Go import: `"github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags"` +- In the resource schema, add `"tags": tagsSchema(),` +- If the API supports tagging on creation (the `Input` struct accepts a `Tags` field), in the resource `Create` function, implement the logic to convert the configuration tags into the service tags, e.g. with EKS Clusters: + + ```go + input := &eks.CreateClusterInput{ + /* ... other configuration ... */ + Tags: keyvaluetags.New(d.Get("tags").(map[string]interface{})).IgnoreAws().EksTags(), + } + ``` + + If the service API does not allow passing an empty list, the logic can be adjusted similar to: + + ```go + input := &eks.CreateClusterInput{ + /* ... other configuration ... */ + } + + if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { + input.Tags = keyvaluetags.New(v).IgnoreAws().EksTags() + } + ``` + +- Otherwise if the API does not support tagging on creation (the `Input` struct does not accept a `Tags` field), in the resource `Create` function, implement the logic to convert the configuration tags into the service API call to tag a resource, e.g. with ElasticSearch Domain: + + ```go + if v := d.Get("tags").(map[string]interface{}); len(v) > 0 { + if err := keyvaluetags.ElasticsearchserviceUpdateTags(conn, d.Id(), nil, v); err != nil { + return fmt.Errorf("error adding Elasticsearch Cluster (%s) tags: %s", d.Id(), err) + } + } + ``` + +- Some EC2 resources (for example [`aws_ec2_fleet`](https://www.terraform.io/docs/providers/aws/r/ec2_fleet.html)) have a `TagsSpecification` field in the `InputStruct` instead of a `Tags` field. In these cases the `ec2TagSpecificationsFromMap()` helper function should be used, e.g.: + + ```go + input := &ec2.CreateFleetInput{ + /* ... other configuration ... */ + TagSpecifications: ec2TagSpecificationsFromMap(d.Get("tags").(map[string]interface{}), ec2.ResourceTypeFleet), + } + ``` + +- In the resource `Read` function, implement the logic to convert the service tags to save them into the Terraform state for drift detection, e.g. with EKS Clusters (which had the tags available in the DescribeCluster API call): + + ```go + // Typically declared near conn := /* ... */ + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + + if err := d.Set("tags", keyvaluetags.EksKeyValueTags(cluster.Tags).IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) + } + ``` + + If the service API does not return the tags directly from reading the resource and requires a separate API call, its possible to use the `keyvaluetags` functionality like the following, e.g. with Athena Workgroups: + + ```go + // Typically declared near conn := /* ... */ + ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig + + tags, err := keyvaluetags.AthenaListTags(conn, arn.String()) + + if err != nil { + return fmt.Errorf("error listing tags for resource (%s): %s", arn, err) + } + + if err := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil { + return fmt.Errorf("error setting tags: %s", err) + } + ``` + +- In the resource `Update` function (this may be the first functionality requiring the creation of the `Update` function), implement the logic to handle tagging updates, e.g. with EKS Clusters: + + ```go + if d.HasChange("tags") { + o, n := d.GetChange("tags") + if err := keyvaluetags.EksUpdateTags(conn, d.Get("arn").(string), o, n); err != nil { + return fmt.Errorf("error updating tags: %s", err) + } + } + ``` + +### Resource Tagging Acceptance Testing Implementation + +- In the resource testing (e.g. `aws/resource_aws_eks_cluster_test.go`), verify that existing resources without tagging are unaffected and do not have tags saved into their Terraform state. This should be done in the `_basic` acceptance test by adding a line similar to `resource.TestCheckResourceAttr(resourceName, "tags.%s", "0"),` +- In the resource testing, implement a new test named `_Tags` with associated configurations, that verifies creating the resource with tags and updating tags. e.g. EKS Clusters: + + ```go + func TestAccAWSEksCluster_Tags(t *testing.T) { + var cluster1, cluster2, cluster3 eks.Cluster + rName := acctest.RandomWithPrefix("tf-acc-test") + resourceName := "aws_eks_cluster.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t); testAccPreCheckAWSEks(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSEksClusterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSEksClusterConfigTags1(rName, "key1", "value1"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEksClusterExists(resourceName, &cluster1), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), + ), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccAWSEksClusterConfigTags2(rName, "key1", "value1updated", "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEksClusterExists(resourceName, &cluster2), + resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), + resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + { + Config: testAccAWSEksClusterConfigTags1(rName, "key2", "value2"), + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSEksClusterExists(resourceName, &cluster3), + resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), + resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), + ), + }, + }, + }) + } + + func testAccAWSEksClusterConfigTags1(rName, tagKey1, tagValue1 string) string { + return testAccAWSEksClusterConfig_Base(rName) + fmt.Sprintf(` + resource "aws_eks_cluster" "test" { + name = %[1]q + role_arn = "${aws_iam_role.test.arn}" + + tags = { + %[2]q = %[3]q + } + + vpc_config { + subnet_ids = ["${aws_subnet.test.*.id[0]}", "${aws_subnet.test.*.id[1]}"] + } + + depends_on = ["aws_iam_role_policy_attachment.test-AmazonEKSClusterPolicy"] + } + `, rName, tagKey1, tagValue1) + } + + func testAccAWSEksClusterConfigTags2(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { + return testAccAWSEksClusterConfig_Base(rName) + fmt.Sprintf(` + resource "aws_eks_cluster" "test" { + name = %[1]q + role_arn = "${aws_iam_role.test.arn}" + + tags = { + %[2]q = %[3]q + %[4]q = %[5]q + } + + vpc_config { + subnet_ids = ["${aws_subnet.test.*.id[0]}", "${aws_subnet.test.*.id[1]}"] + } + + depends_on = ["aws_iam_role_policy_attachment.test-AmazonEKSClusterPolicy"] + } + `, rName, tagKey1, tagValue1, tagKey2, tagValue2) + } + ``` + +- Verify all acceptance testing passes for the resource (e.g. `make testacc TESTARGS='-run=TestAccAWSEksCluster_'`) + +### Resource Tagging Documentation Implementation + +- In the resource documentation (e.g. `website/docs/r/eks_cluster.html.markdown`), add the following to the arguments reference: + + ```markdown + * `tags` - (Optional) Key-value mapping of resource tags + ``` + +## New Resource + +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. + +In addition to the below checklist, please see the [Common Review +Items](pullrequest-submission-and-lifecycle.md#common-review-items) sections for more specific coding and testing +guidelines. + +- [ ] __Minimal LOC__: It's difficult for both the reviewer and author to go + through long feedback cycles on a big PR with many resources. We ask 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 + approach these. +- [ ] __Resource Naming__: Resources should be named `aws__`, + using underscores (`_`) as the separator. Resources are namespaced with the + service name to allow easier searching of related resources, to align + the resource naming with the service for [Customizing Endpoints](https://www.terraform.io/docs/providers/aws/guides/custom-service-endpoints.html#available-endpoint-customizations), + and to prevent future conflicts with new AWS services/resources. + For reference: + + - `service` is the AWS short service name that matches the entry in + `endpointServiceNames` (created via the [New Service](#new-service) + section) + - `name` represents the conceptual infrastructure represented by the + create, read, update, and delete methods of the service API. It should + be a singular noun. For example, in an API that has methods such as + `CreateThing`, `DeleteThing`, `DescribeThing`, and `ModifyThing` the name + of the resource would end in `_thing`. + +- [ ] __Arguments_and_Attributes__: The HCL for arguments and attributes should + mimic the types and structs presented by the AWS API. API arguments should be + converted from `CamelCase` to `camel_case`. +- [ ] __Documentation__: Each resource gets a page in the Terraform + documentation. The [Terraform website][website] source is in this + repo and includes instructions for getting a local copy of the site up and + running if you'd like to preview your changes. For a resource, you'll want + to add a new file in the appropriate place and add a link to the sidebar for + that page. +- [ ] __Well-formed Code__: Do your best to follow existing conventions you + see in the codebase, and ensure your code is formatted with `go fmt`. + The PR reviewers can help out on this front, and may provide comments with + suggestions on how to improve the code. +- [ ] __Vendor updates__: Create a separate PR if you are adding to the vendor + folder. This is to avoid conflicts as the vendor versions tend to be fast- + moving targets. We will plan to merge the PR with this change first. + +## New Service + +Implementing a new AWS service gives Terraform the ability to manage resources in +a whole new API. It's a larger undertaking, but brings major new functionality +into Terraform. + +- [ ] __Service Client__: Before new resources are submitted, we request + a separate pull request containing just the new AWS Go SDK service client. + Doing so will pull the AWS Go SDK service code into the project at the + current version. Since the AWS Go SDK is updated frequently, these pull + requests can easily have merge conflicts or be out of date. The maintainers + prioritize reviewing and merging these quickly to prevent those situations. + + To add the AWS Go SDK service client: + + - In `aws/provider.go` Add a new service entry to `endpointServiceNames`. + This service name should match the AWS Go SDK or AWS CLI service name. + - In `aws/config.go`: Add a new import for the AWS Go SDK code. e.g. + `github.com/aws/aws-sdk-go/service/quicksight` + - In `aws/config.go`: Add a new `{SERVICE}conn` field to the `AWSClient` + struct for the service client. The service name should match the name + in `endpointServiceNames`. e.g. `quicksightconn *quicksight.QuickSight` + - In `aws/config.go`: Create the new service client in the `{SERVICE}conn` + field in the `AWSClient` instantiation within `Client()`. e.g. + `quicksightconn: quicksight.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.Endpoints["quicksight"])})),` + - In `website/allowed-subcategories.txt`: Add a name acceptable for the documentation navigation. + - In `website/docs/guides/custom-service-endpoints.html.md`: Add the service + name in the list of customizable endpoints. + - In `infrastructure/repository/labels-service.tf`: Add the new service to create a repository label. + - In `.hashibot.hcl`: Add the new service to automated issue and pull request labeling. e.g. with the `quicksight` service + + ```hcl + behavior "regexp_issue_labeler_v2" "service_labels" { + # ... other configuration ... + + label_map = { + # ... other services ... + "service/quicksight" = [ + "aws_quicksight_", + ], + # ... other services ... + } + } + + behavior "pull_request_path_labeler" "service_labels" + # ... other configuration ... + + label_map = { + # ... other services ... + "service/quicksight" = [ + "**/*_quicksight_*", + "**/quicksight_*", + ], + # ... other services ... + } + } + ``` + + - Run the following then submit the pull request: + + ```sh + go test ./aws + go mod tidy + go mod vendor + ``` + +- [ ] __Initial Resource__: Some services can be big and it can be + difficult for both reviewer & author to go through long feedback cycles + on a big PR with many resources. Often feedback items in one resource + will also need to be applied in other resources. We prefer you to submit + the necessary minimum in a single PR, ideally **just the first resource** + of the service. + +The initial resource and changes afterwards should follow the other sections +of this guide as appropriate. + +## New Region + +While region validation is automatically added with SDK updates, new regions +are generally limited in which services they support. Below are some +manually sourced values from documentation. + +- [ ] Check [Elastic Load Balancing endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/elb.html#elb_region) and add Route53 Hosted Zone ID if available to `aws/data_source_aws_elb_hosted_zone_id.go` +- [ ] Check [Amazon Simple Storage Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/s3.html#s3_region) and add Route53 Hosted Zone ID if available to `aws/hosted_zones.go` +- [ ] Check [CloudTrail Supported Regions docs](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-supported-regions.html#cloudtrail-supported-regions) and add AWS Account ID if available to `aws/data_source_aws_cloudtrail_service_account.go` +- [ ] Check [Elastic Load Balancing Access Logs docs](https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-access-logs.html#attach-bucket-policy) and add Elastic Load Balancing Account ID if available to `aws/data_source_aws_elb_service_account.go` +- [ ] Check [Redshift Database Audit Logging docs](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html#db-auditing-bucket-permissions) and add AWS Account ID if available to `aws/data_source_aws_redshift_service_account.go` +- [ ] Check [AWS Elastic Beanstalk endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/elasticbeanstalk.html#elasticbeanstalk_region) and add Route53 Hosted Zone ID if available to `aws/data_source_aws_elastic_beanstalk_hosted_zone.go` diff --git a/docs/contributing/issue-reporting-and-lifecycle.md b/docs/contributing/issue-reporting-and-lifecycle.md new file mode 100644 index 00000000000..dcd1be23dae --- /dev/null +++ b/docs/contributing/issue-reporting-and-lifecycle.md @@ -0,0 +1,77 @@ +# Issue Reporting and Lifecycle + + + +- [Issue Reporting Checklists](#issue-reporting-checklists) + - [Bug Reports](https://github.com/terraform-providers/terraform-provider-aws/issues/new?template=Bug_Report.md) + - [Feature Requests](https://github.com/terraform-providers/terraform-provider-aws/issues/new?labels=enhancement&template=Feature_Request.md) + - [Questions](https://github.com/terraform-providers/terraform-provider-aws/issues/new?labels=question&template=Question.md) +- [Issue Lifecycle](#issue-lifecycle) + + + +## Issue Reporting Checklists + +We welcome issues of all kinds including feature requests, bug reports, and +general questions. Below you'll find checklists with guidelines for well-formed +issues of each type. + +### [Bug Reports](https://github.com/terraform-providers/terraform-provider-aws/issues/new?template=Bug_Report.md) + +- [ ] __Test against latest release__: Make sure you test against the latest + released version. It is possible we already fixed the bug you're experiencing. + +- [ ] __Search for possible duplicate reports__: It's helpful to keep bug + reports consolidated to one thread, so do a quick search on existing bug + reports to check if anybody else has reported the same thing. You can [scope + searches by the label "bug"](https://github.com/terraform-providers/terraform-provider-aws/issues?q=is%3Aopen+is%3Aissue+label%3Abug) to help narrow things down. + +- [ ] __Include steps to reproduce__: Provide steps to reproduce the issue, + along with your `.tf` files, with secrets removed, so we can try to + reproduce it. Without this, it makes it much harder to fix the issue. + +- [ ] __For panics, include `crash.log`__: If you experienced a panic, please + create a [gist](https://gist.github.com) of the *entire* generated crash log + for us to look at. Double check no sensitive items were in the log. + +### [Feature Requests](https://github.com/terraform-providers/terraform-provider-aws/issues/new?labels=enhancement&template=Feature_Request.md) + +- [ ] __Search for possible duplicate requests__: It's helpful to keep requests + consolidated to one thread, so do a quick search on existing requests to + check if anybody else has reported the same thing. You can [scope searches by + the label "enhancement"](https://github.com/terraform-providers/terraform-provider-aws/issues?q=is%3Aopen+is%3Aissue+label%3Aenhancement) to help narrow things down. + +- [ ] __Include a use case description__: In addition to describing the + behavior of the feature you'd like to see added, it's helpful to also lay + out the reason why the feature would be important and how it would benefit + Terraform users. + +### [Questions](https://github.com/terraform-providers/terraform-provider-aws/issues/new?labels=question&template=Question.md) + +- [ ] __Search for answers in Terraform documentation__: We're happy to answer + questions in GitHub Issues, but it helps reduce issue churn and maintainer + workload if you work to [find answers to common questions in the + documentation](https://www.terraform.io/docs/providers/aws/index.html). Oftentimes Question issues result in documentation updates + to help future users, so if you don't find an answer, you can give us + pointers for where you'd expect to see it in the docs. + +## Issue Lifecycle + +1. The issue is reported. + +2. The issue is verified and categorized by a Terraform collaborator. + Categorization is done via GitHub labels. We generally use a two-label + system of (1) issue/PR type, and (2) section of the codebase. Type is + one of "bug", "enhancement", "documentation", or "question", and section + is usually the AWS service name. + +3. An initial triage process determines whether the issue is critical and must + be addressed immediately, or can be left open for community discussion. + +4. The issue is addressed in a pull request or commit. The issue number will be + referenced in the commit message so that the code that fixes it is clearly + linked. + +5. The issue is closed. Sometimes, valid issues will be closed because they are + tracked elsewhere or non-actionable. The issue is still indexed and + available for future viewers, or can be re-opened if necessary. diff --git a/docs/contributing/pullrequest-submission-and-lifecycle.md b/docs/contributing/pullrequest-submission-and-lifecycle.md new file mode 100644 index 00000000000..5a3fd3a007d --- /dev/null +++ b/docs/contributing/pullrequest-submission-and-lifecycle.md @@ -0,0 +1,158 @@ +# Pull Request Submission and Lifecycle + +- [Pull Request Lifecycle](#pull-request-lifecycle) +- [Branch Prefixes](#branch-prefixes) +- [Common Review Items](#common-review-items) + - [Go Coding Style](#go-coding-style) + - [Resource Contribution Guidelines](#resource-contribution-guidelines) + +We appreciate direct contributions to the provider codebase. Here's what to +expect: + +* For pull requests that follow the guidelines, we will proceed to reviewing + and merging, following the provider team's review schedule. There may be some + internal or community discussion needed before we can complete this. +* Pull requests that don't follow the guidelines will be commented with what + they're missing. The person who submits the pull request or another community + member will need to address those requests before they move forward. + +## Pull Request Lifecycle + +1. [Fork the GitHub repository](https://help.github.com/en/articles/fork-a-repo), + modify the code, and [create a pull request](https://help.github.com/en/articles/creating-a-pull-request-from-a-fork). + You are welcome to submit your pull request for commentary or review before + it is fully completed by creating a [draft pull request](https://help.github.com/en/articles/about-pull-requests#draft-pull-requests) + or adding `[WIP]` to the beginning of the pull request title. + Please include specific questions or items you'd like feedback on. + +1. Once you believe your pull request is ready to be reviewed, ensure the + pull request is not a draft pull request by [marking it ready for review](https://help.github.com/en/articles/changing-the-stage-of-a-pull-request) + or removing `[WIP]` from the pull request title if necessary, and a + maintainer will review it. Follow [the checklists below](#checklists-for-contribution) + to help ensure that your contribution can be easily reviewed and potentially + merged. + +1. One of Terraform's provider team members will look over your contribution and + either approve it or provide comments letting you know if there is anything + left to do. We do our best to keep up with the volume of PRs waiting for + review, but it may take some time depending on the complexity of the work. + +1. Once all outstanding comments and checklist items have been addressed, your + contribution will be merged! Merged PRs will be included in the next + Terraform release. The provider team takes care of updating the CHANGELOG as + they merge. + +1. In some cases, we might decide that a PR should be closed without merging. + We'll make sure to provide clear reasoning when this happens. + +## Branch Prefixes + +We try to use a common set of branch name prefixes when submitting pull requests. Prefixes give us an idea of what the branch is for. For example, `td-staticcheck-st1008` would let us know the branch was created to fix a technical debt issue, and `f-aws_emr_instance_group-refactor` would indicate a feature request for the `aws_emr_instance_group` resource that’s being refactored. These are the prefixes we currently use: + +- f = feature +- b = bug fix +- d = documentation +- t = tests +- td = technical debt +- v = "vendoring"/dependencies + +Conventions across non-AWS providers varies so when working with other providers please check the names of previously created branches and conform to their standard practices. + +## Common Review Items + +The Terraform AWS Provider follows common practices to ensure consistent and +reliable implementations across all resources in the project. While there may be +older resource and testing code that predates these guidelines, new submissions +are generally expected to adhere to these items to maintain Terraform Provider +quality. For any guidelines listed, contributors are encouraged to ask any +questions and community reviewers are encouraged to provide review suggestions +based on these guidelines to speed up the review and merge process. + +### Go Coding Style + +The following Go language resources provide common coding preferences that may be referenced during review, if not automatically handled by the project's linting tools. + +- [Effective Go](https://golang.org/doc/effective_go.html) +- [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments) + +### Resource Contribution Guidelines + +The following resource checks need to be addressed before your contribution can be merged. The exclusion of any applicable check may result in a delayed time to merge. + +- [ ] __Passes Testing__: All code and documentation changes must pass unit testing, code linting, and website link testing. Resource code changes must pass all acceptance testing for the resource. +- [ ] __Avoids API Calls Across Account, Region, and Service Boundaries__: Resources should not implement cross-account, cross-region, or cross-service API calls. +- [ ] __Avoids Optional and Required for Non-Configurable Attributes__: Resource schema definitions for read-only attributes should not include `Optional: true` or `Required: true`. +- [ ] __Avoids resource.Retry() without resource.RetryableError()__: Resource logic should only implement [`resource.Retry()`](https://godoc.org/github.com/hashicorp/terraform/helper/resource#Retry) if there is a retryable condition (e.g. `return resource.RetryableError(err)`). +- [ ] __Avoids Resource Read Function in Data Source Read Function__: Data sources should fully implement their own resource `Read` functionality including duplicating `d.Set()` calls. +- [ ] __Avoids Reading Schema Structure in Resource Code__: The resource `Schema` should not be read in resource `Create`/`Read`/`Update`/`Delete` functions to perform looping or otherwise complex attribute logic. Use [`d.Get()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.Get) and [`d.Set()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.Set) directly with individual attributes instead. +- [ ] __Avoids ResourceData.GetOkExists()__: Resource logic should avoid using [`ResourceData.GetOkExists()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.GetOkExists) as its expected functionality is not guaranteed in all scenarios. +- [ ] __Implements Read After Create and Update__: Except where API eventual consistency prohibits immediate reading of resources or updated attributes, resource `Create` and `Update` functions should return the resource `Read` function. +- [ ] __Implements Immediate Resource ID Set During Create__: Immediately after calling the API creation function, the resource ID should be set with [`d.SetId()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.SetId) before other API operations or returning the `Read` function. +- [ ] __Implements Attribute Refreshes During Read__: All attributes available in the API should have [`d.Set()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.Set) called their values in the Terraform state during the `Read` function. +- [ ] __Implements Error Checks with Non-Primitive Attribute Refreshes__: When using [`d.Set()`](https://godoc.org/github.com/hashicorp/terraform/helper/schema#ResourceData.Set) with non-primitive types (`schema.TypeList`, `schema.TypeSet`, or `schema.TypeMap`), perform error checking to [prevent issues where the code is not properly able to refresh the Terraform state](https://www.terraform.io/docs/extend/best-practices/detecting-drift.html#error-checking-aggregate-types). +- [ ] __Implements Import Acceptance Testing and Documentation__: Support for resource import (`Importer` in resource schema) must include `ImportState` acceptance testing (see also the [Acceptance Testing Guidelines](#acceptance-testing-guidelines) below) and `## Import` section in resource documentation. +- [ ] __Implements Customizable Timeouts Documentation__: Support for customizable timeouts (`Timeouts` in resource schema) must include `## Timeouts` section in resource documentation. +- [ ] __Implements State Migration When Adding New Virtual Attribute__: For new "virtual" attributes (those only in Terraform and not in the API), the schema should implement [State Migration](https://www.terraform.io/docs/extend/resources.html#state-migrations) to prevent differences for existing configurations that upgrade. +- [ ] __Uses AWS Go SDK Constants__: Many AWS services provide string constants for value enumerations, error codes, and status types. See also the "Constants" sections under each of the service packages in the [AWS Go SDK documentation](https://docs.aws.amazon.com/sdk-for-go/api/). +- [ ] __Uses AWS Go SDK Pointer Conversion Functions__: Many APIs return pointer types and these functions return the zero value for the type if the pointer is `nil`. This prevents potential panics from unchecked `*` pointer dereferences and can eliminate boilerplate `nil` checking in many cases. See also the [`aws` package in the AWS Go SDK documentation](https://docs.aws.amazon.com/sdk-for-go/api/aws/). +- [ ] __Uses AWS Go SDK Types__: Use available SDK structs instead of implementing custom types with indirection. +- [ ] __Uses TypeList and MaxItems: 1__: Configuration block attributes (e.g. `Type: schema.TypeList` or `Type: schema.TypeSet` with `Elem: &schema.Resource{...}`) that can only have one block should use `Type: schema.TypeList` and `MaxItems: 1` in the schema definition. +- [ ] __Uses Existing Validation Functions__: Schema definitions including `ValidateFunc` for attribute validation should use available [Terraform `helper/validation` package](https://godoc.org/github.com/hashicorp/terraform/helper/validation) functions. `All()`/`Any()` can be used for combining multiple validation function behaviors. +- [ ] __Uses isResourceTimeoutError() with resource.Retry()__: Resource logic implementing [`resource.Retry()`](https://godoc.org/github.com/hashicorp/terraform/helper/resource#Retry) should error check with `isResourceTimeoutError(err error)` and potentially unset the error before returning the error. For example: + + ```go + var output *kms.CreateKeyOutput + err := resource.Retry(1*time.Minute, func() *resource.RetryError { + var err error + + output, err = conn.CreateKey(input) + + /* ... */ + + return nil + }) + + if isResourceTimeoutError(err) { + output, err = conn.CreateKey(input) + } + + if err != nil { + return fmt.Errorf("error creating KMS External Key: %s", err) + } + ``` + +- [ ] __Uses resource.NotFoundError__: Custom errors for missing resources should use [`resource.NotFoundError`](https://godoc.org/github.com/hashicorp/terraform/helper/resource#NotFoundError). +- [ ] __Uses resource.UniqueId()__: API fields for concurrency protection such as `CallerReference` and `IdempotencyToken` should use [`resource.UniqueId()`](https://godoc.org/github.com/hashicorp/terraform/helper/resource#UniqueId). The implementation includes a monotonic counter which is safer for concurrent operations than solutions such as `time.Now()`. +- [ ] __Skips Exists Function__: Implementing a resource `Exists` function is extraneous as it often duplicates resource `Read` functionality. Ensure `d.SetId("")` is used to appropriately trigger resource recreation in the resource `Read` function. +- [ ] __Skips id Attribute__: The `id` attribute is implicit for all Terraform resources and does not need to be defined in the schema. + +The below are style-based items that _may_ be noted during review and are recommended for simplicity, consistency, and quality assurance: + +- [ ] __Avoids CustomizeDiff__: Usage of `CustomizeDiff` is generally discouraged. +- [ ] __Implements Error Message Context__: Returning errors from resource `Create`, `Read`, `Update`, and `Delete` functions should include additional messaging about the location or cause of the error for operators and code maintainers by wrapping with [`fmt.Errorf()`](https://godoc.org/golang.org/x/exp/errors/fmt#Errorf). + - An example `Delete` API error: `return fmt.Errorf("error deleting {SERVICE} {THING} (%s): %s", d.Id(), err)` + - An example `d.Set()` error: `return fmt.Errorf("error setting {ATTRIBUTE}: %s", err)` +- [ ] __Implements arn Attribute__: APIs that return an Amazon Resource Name (ARN) should implement `arn` as an attribute. Alternatively, the ARN can be synthesized using the AWS Go SDK [`arn.ARN`](https://docs.aws.amazon.com/sdk-for-go/api/aws/arn/#ARN) structure. For example: + + ```go + // Direct Connect Virtual Interface ARN. + // See https://docs.aws.amazon.com/directconnect/latest/UserGuide/security_iam_service-with-iam.html#security_iam_service-with-iam-id-based-policies-resources. + arn := arn.ARN{ + Partition: meta.(*AWSClient).partition, + Region: meta.(*AWSClient).region, + Service: "directconnect", + AccountID: meta.(*AWSClient).accountid, + Resource: fmt.Sprintf("dxvif/%s", d.Id()), + }.String() + d.Set("arn", arn) + ``` + + When the `arn` attribute is synthesized this way, add the resource to the [list](https://www.terraform.io/docs/providers/aws/index.html#argument-reference) of those affected by the provider's `skip_requesting_account_id` attribute. + +- [ ] __Implements Warning Logging With Resource State Removal__: If a resource is removed outside of Terraform (e.g. via different tool, API, or web UI), `d.SetId("")` and `return nil` can be used in the resource `Read` function to trigger resource recreation. When this occurs, a warning log message should be printed beforehand: `log.Printf("[WARN] {SERVICE} {THING} (%s) not found, removing from state", d.Id())` +- [ ] __Uses isAWSErr() with AWS Go SDK Error Objects__: Use the available `isAWSErr(err error, code string, message string)` helper function instead of the `awserr` package to compare error code and message contents. +- [ ] __Uses %s fmt Verb with AWS Go SDK Objects__: AWS Go SDK objects implement `String()` so using the `%v`, `%#v`, or `%+v` fmt verbs with the object are extraneous or provide unhelpful detail. +- [ ] __Uses Elem with TypeMap__: While provider schema validation does not error when the `Elem` configuration is not present with `Type: schema.TypeMap` attributes, including the explicit `Elem: &schema.Schema{Type: schema.TypeString}` is recommended. +- [ ] __Uses American English for Attribute Naming__: For any ambiguity with attribute naming, prefer American English over British English. e.g. `color` instead of `colour`. +- [ ] __Skips Timestamp Attributes__: Generally, creation and modification dates from the API should be omitted from the schema. +- [ ] __Skips Error() Call with AWS Go SDK Error Objects__: Error objects do not need to have `Error()` called. diff --git a/docs/contributing/running-and-writing-acceptance-tests.md b/docs/contributing/running-and-writing-acceptance-tests.md new file mode 100644 index 00000000000..41d2f090916 --- /dev/null +++ b/docs/contributing/running-and-writing-acceptance-tests.md @@ -0,0 +1,1040 @@ +# Running and Writing Acceptance Tests + +- [Acceptance Tests Often Cost Money to Run](#acceptance-tests-often-cost-money-to-run) +- [Running an Acceptance Test](#running-an-acceptance-test) + - [Running Cross-Account Tests](#running-cross-account-tests) + - [Running Cross-Region Tests](#running-cross-region-tests) +- [Writing an Acceptance Test](#writing-an-acceptance-test) + - [Anatomy of an Acceptance Test](#anatomy-of-an-acceptance-test) + - [Resource Acceptance Testing](#resource-acceptance-testing) + - [Test Configurations](#test-configurations) + - [Combining Test Configurations](#combining-test-configurations) + - [Base Test Configurations](#base-test-configurations) + - [Available Common Test Configurations](#available-common-test-configurations) + - [Randomized Naming](#randomized-naming) + - [Other Recommended Variables](#other-recommended-variables) + - [Basic Acceptance Tests](#basic-acceptance-tests) + - [Service Availability PreCheck](#service-availability-precheck) + - [Disappears Acceptance Tests](#disappears-acceptance-tests) + - [Per Attribute Acceptance Tests](#per-attribute-acceptance-tests) + - [Cross-Account Acceptance Tests](#cross-account-acceptance-tests) + - [Cross-Region Acceptance Tests](#cross-region-acceptance-tests) + - [Data Source Acceptance Testing](#data-source-acceptance-testing) +- [Acceptance Test Sweepers](#acceptance-test-sweepers) + - [Running Test Sweepers](#running-test-sweepers) + - [Writing Test Sweepers](#writing-test-sweepers) +- [Acceptance Test Checklist](#acceptance-test-checklist) + +Terraform includes an acceptance test harness that does most of the repetitive +work involved in testing a resource. For additional information about testing +Terraform Providers, see the [Extending Terraform documentation](https://www.terraform.io/docs/extend/testing/index.html). + +## Acceptance Tests Often Cost Money to Run + +Because acceptance tests create real resources, they often cost money to run. +Because the resources only exist for a short period of time, the total amount +of money required is usually a relatively small. Nevertheless, we don't want +financial limitations to be a barrier to contribution, so if you are unable to +pay to run acceptance tests for your contribution, mention this in your +pull request. We will happily accept "best effort" implementations of +acceptance tests and run them for you on our side. This might mean that your PR +takes a bit longer to merge, but it most definitely is not a blocker for +contributions. + +## Running an Acceptance Test + +Acceptance tests can be run using the `testacc` target in the Terraform +`Makefile`. The individual tests to run can be controlled using a regular +expression. Prior to running the tests provider configuration details such as +access keys must be made available as environment variables. + +For example, to run an acceptance test against the Amazon Web Services +provider, the following environment variables must be set: + +```sh +# Using a profile +export AWS_PROFILE=... +# Otherwise +export AWS_ACCESS_KEY_ID=... +export AWS_SECRET_ACCESS_KEY=... +export AWS_DEFAULT_REGION=... +``` + +Please note that the default region for the testing is `us-west-2` and must be +overridden via the `AWS_DEFAULT_REGION` environment variable, if necessary. This +is especially important for testing AWS GovCloud (US), which requires: + +```sh +export AWS_DEFAULT_REGION=us-gov-west-1 +``` + +Tests can then be run by specifying a regular expression defining the tests to run: + +```sh +$ make testacc TESTARGS='-run=TestAccAWSCloudWatchDashboard_update' +==> Checking that code complies with gofmt requirements... +TF_ACC=1 go test ./aws -v -run=TestAccAWSCloudWatchDashboard_update -timeout 120m +=== RUN TestAccAWSCloudWatchDashboard_update +--- PASS: TestAccAWSCloudWatchDashboard_update (26.56s) +PASS +ok github.com/terraform-providers/terraform-provider-aws/aws 26.607s +``` + +Entire resource test suites can be targeted by using the naming convention to +write the regular expression. For example, to run all tests of the +`aws_cloudwatch_dashboard` resource rather than just the update test, you can start +testing like this: + +```sh +$ make testacc TESTARGS='-run=TestAccAWSCloudWatchDashboard' +==> Checking that code complies with gofmt requirements... +TF_ACC=1 go test ./aws -v -run=TestAccAWSCloudWatchDashboard -timeout 120m +=== RUN TestAccAWSCloudWatchDashboard_importBasic +--- PASS: TestAccAWSCloudWatchDashboard_importBasic (15.06s) +=== RUN TestAccAWSCloudWatchDashboard_basic +--- PASS: TestAccAWSCloudWatchDashboard_basic (12.70s) +=== RUN TestAccAWSCloudWatchDashboard_update +--- PASS: TestAccAWSCloudWatchDashboard_update (27.81s) +PASS +ok github.com/terraform-providers/terraform-provider-aws/aws 55.619s +``` + +Running acceptance tests requires version 0.12.26 or higher of the Terraform CLI to be installed. + +Please Note: On macOS 10.14 and later (and some Linux distributions), the default user open file limit is 256. This may cause unexpected issues when running the acceptance testing since this can prevent various operations from occurring such as opening network connections to AWS. To view this limit, the `ulimit -n` command can be run. To update this limit, run `ulimit -n 1024` (or higher). + +### Running Cross-Account Tests + +Certain testing requires multiple AWS accounts. This additional setup is not typically required and the testing will return an error (shown below) if your current setup does not have the secondary AWS configuration: + +```console +$ make testacc TEST=./aws TESTARGS='-run=TestAccAWSDBInstance_DbSubnetGroupName_RamShared' +=== RUN TestAccAWSDBInstance_DbSubnetGroupName_RamShared +=== PAUSE TestAccAWSDBInstance_DbSubnetGroupName_RamShared +=== CONT TestAccAWSDBInstance_DbSubnetGroupName_RamShared + TestAccAWSDBInstance_DbSubnetGroupName_RamShared: provider_test.go:386: AWS_ALTERNATE_ACCESS_KEY_ID or AWS_ALTERNATE_PROFILE must be set for acceptance tests +--- FAIL: TestAccAWSDBInstance_DbSubnetGroupName_RamShared (2.22s) +FAIL +FAIL github.com/terraform-providers/terraform-provider-aws/aws 4.305s +FAIL +``` + +Running these acceptance tests is the same as before, except the following additional AWS credential information is required: + +```sh +# Using a profile +export AWS_ALTERNATE_PROFILE=... +# Otherwise +export AWS_ALTERNATE_ACCESS_KEY_ID=... +export AWS_ALTERNATE_SECRET_ACCESS_KEY=... +``` + +### Running Cross-Region Tests + +Certain testing requires multiple AWS regions. Additional setup is not typically required because the testing defaults the second AWS region to `us-east-1` and the third AWS region to `us-east-2`. + +Running these acceptance tests is the same as before, but if you wish to override the second and third regions: + +```sh +export AWS_ALTERNATE_REGION=... +export AWS_THIRD_REGION=... +``` + +## Writing an Acceptance Test + +Terraform has a framework for writing acceptance tests which minimises the +amount of boilerplate code necessary to use common testing patterns. This guide is meant to augment the general [Extending Terraform documentation](https://www.terraform.io/docs/extend/testing/acceptance-tests/index.html) with Terraform AWS Provider specific conventions and helpers. + +### Anatomy of an Acceptance Test + +This section describes in detail how the Terraform acceptance testing framework operates with respect to the Terraform AWS Provider. We recommend those unfamiliar with this provider, or Terraform resource testing in general, take a look here first to generally understand how we interact with AWS and the resource code to verify functionality. + +The entry point to the framework is the `resource.ParallelTest()` function. This wraps our testing to work with the standard Go testing framework, while also preventing unexpected usage of AWS by requiring the `TF_ACC=1` environment variable. This function accepts a `TestCase` parameter, which has all the details about the test itself. For example, this includes the test steps (`TestSteps`) and how to verify resource deletion in the API after all steps have been run (`CheckDestroy`). + +Each `TestStep` proceeds by applying some +Terraform configuration using the provider under test, and then verifying that +results are as expected by making assertions using the provider API. It is +common for a single test function to exercise both the creation of and updates +to a single resource. Most tests follow a similar structure. + +1. Pre-flight checks are made to ensure that sufficient provider configuration + is available to be able to proceed - for example in an acceptance test + targeting AWS, `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` must be set prior + to running acceptance tests. This is common to all tests exercising a single + provider. + +Most assertion +functions are defined out of band with the tests. This keeps the tests +readable, and allows reuse of assertion functions across different tests of the +same type of resource. The definition of a complete test looks like this: + +```go +func TestAccAWSCloudWatchDashboard_basic(t *testing.T) { + var dashboard cloudwatch.GetDashboardOutput + rInt := acctest.RandInt() + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSCloudWatchDashboardDestroy, + Steps: []resource.TestStep{ + { + Config: testAccAWSCloudWatchDashboardConfig(rInt), + Check: resource.ComposeTestCheckFunc( + testAccCheckCloudWatchDashboardExists("aws_cloudwatch_dashboard.foobar", &dashboard), + resource.TestCheckResourceAttr("aws_cloudwatch_dashboard.foobar", "dashboard_name", testAccAWSCloudWatchDashboardName(rInt)), + ), + }, + }, + }) +} +``` + +When executing the test, the following steps are taken for each `TestStep`: + +1. The Terraform configuration required for the test is applied. This is + responsible for configuring the resource under test, and any dependencies it + may have. For example, to test the `aws_cloudwatch_dashboard` resource, a valid configuration with the requisite fields is required. This results in configuration which looks like this: + + ```hcl + resource "aws_cloudwatch_dashboard" "foobar" { + dashboard_name = "terraform-test-dashboard-%d" + dashboard_body = < { + const putParams = { + TableName: process.env.TABLE_NAME, + Item: { + connectionId: event.requestContext.connectionId + } + }; + + try { + await ddb.put(putParams).promise(); + } catch (err) { + return { statusCode: 500, body: 'Failed to connect: ' + JSON.stringify(err) }; + } + + return { statusCode: 200, body: 'Connected.' }; +}; diff --git a/examples/api-gateway-websocket-chat-app/onconnect/package.json b/examples/api-gateway-websocket-chat-app/onconnect/package.json new file mode 100644 index 00000000000..c3af0703f89 --- /dev/null +++ b/examples/api-gateway-websocket-chat-app/onconnect/package.json @@ -0,0 +1,11 @@ +{ + "name": "on-connect", + "version": "1.0.0", + "description": "onconnect example for WebSockets on API Gateway", + "main": "src/app.js", + "author": "SAM CLI", + "license": "MIT", + "dependencies": { + "aws-sdk": "^2.655.0" + } +} diff --git a/examples/api-gateway-websocket-chat-app/ondisconnect/app.js b/examples/api-gateway-websocket-chat-app/ondisconnect/app.js new file mode 100644 index 00000000000..7c6c2d7d739 --- /dev/null +++ b/examples/api-gateway-websocket-chat-app/ondisconnect/app.js @@ -0,0 +1,29 @@ +// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: MIT-0 + +// https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-route-keys-connect-disconnect.html +// The $disconnect route is executed after the connection is closed. +// The connection can be closed by the server or by the client. As the connection is already closed when it is executed, +// $disconnect is a best-effort event. +// API Gateway will try its best to deliver the $disconnect event to your integration, but it cannot guarantee delivery. + +const AWS = require('aws-sdk'); + +const ddb = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10', region: process.env.AWS_REGION }); + +exports.handler = async event => { + const deleteParams = { + TableName: process.env.TABLE_NAME, + Key: { + connectionId: event.requestContext.connectionId + } + }; + + try { + await ddb.delete(deleteParams).promise(); + } catch (err) { + return { statusCode: 500, body: 'Failed to disconnect: ' + JSON.stringify(err) }; + } + + return { statusCode: 200, body: 'Disconnected.' }; +}; diff --git a/examples/api-gateway-websocket-chat-app/ondisconnect/package.json b/examples/api-gateway-websocket-chat-app/ondisconnect/package.json new file mode 100644 index 00000000000..3d3d07cdcaa --- /dev/null +++ b/examples/api-gateway-websocket-chat-app/ondisconnect/package.json @@ -0,0 +1,11 @@ +{ + "name": "on-disconnect", + "version": "1.0.0", + "description": "ondisconnect example for WebSockets on API Gateway", + "main": "src/app.js", + "author": "SAM CLI", + "license": "MIT", + "dependencies": { + "aws-sdk": "^2.655.0" + } +} diff --git a/examples/api-gateway-websocket-chat-app/sendmessage/app.js b/examples/api-gateway-websocket-chat-app/sendmessage/app.js new file mode 100644 index 00000000000..c217de88007 --- /dev/null +++ b/examples/api-gateway-websocket-chat-app/sendmessage/app.js @@ -0,0 +1,46 @@ +// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: MIT-0 + +const AWS = require('aws-sdk'); + +const ddb = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10', region: process.env.AWS_REGION }); + +const { TABLE_NAME } = process.env; + +exports.handler = async event => { + let connectionData; + + try { + connectionData = await ddb.scan({ TableName: TABLE_NAME, ProjectionExpression: 'connectionId' }).promise(); + } catch (e) { + return { statusCode: 500, body: e.stack }; + } + + const apigwManagementApi = new AWS.ApiGatewayManagementApi({ + apiVersion: '2018-11-29', + endpoint: event.requestContext.domainName + '/' + event.requestContext.stage + }); + + const postData = JSON.parse(event.body).data; + + const postCalls = connectionData.Items.map(async ({ connectionId }) => { + try { + await apigwManagementApi.postToConnection({ ConnectionId: connectionId, Data: postData }).promise(); + } catch (e) { + if (e.statusCode === 410) { + console.log(`Found stale connection, deleting ${connectionId}`); + await ddb.delete({ TableName: TABLE_NAME, Key: { connectionId } }).promise(); + } else { + throw e; + } + } + }); + + try { + await Promise.all(postCalls); + } catch (e) { + return { statusCode: 500, body: e.stack }; + } + + return { statusCode: 200, body: 'Data sent.' }; +}; diff --git a/examples/api-gateway-websocket-chat-app/sendmessage/package.json b/examples/api-gateway-websocket-chat-app/sendmessage/package.json new file mode 100644 index 00000000000..1f96ca5faef --- /dev/null +++ b/examples/api-gateway-websocket-chat-app/sendmessage/package.json @@ -0,0 +1,11 @@ +{ + "name": "send-message", + "version": "1.0.0", + "description": "sendmessage example for WebSockets on API Gateway", + "main": "src/app.js", + "author": "SAM CLI", + "license": "MIT", + "dependencies": { + "aws-sdk": "^2.655.0" + } +} diff --git a/examples/api-gateway-websocket-chat-app/terraform.template.tfvars b/examples/api-gateway-websocket-chat-app/terraform.template.tfvars new file mode 100644 index 00000000000..bb891daf459 --- /dev/null +++ b/examples/api-gateway-websocket-chat-app/terraform.template.tfvars @@ -0,0 +1 @@ +aws_region = "us-east-1" diff --git a/examples/api-gateway-websocket-chat-app/variables.tf b/examples/api-gateway-websocket-chat-app/variables.tf new file mode 100644 index 00000000000..e4f8705a6ac --- /dev/null +++ b/examples/api-gateway-websocket-chat-app/variables.tf @@ -0,0 +1,4 @@ +variable "aws_region" { + description = "AWS region" + default = "us-west-2" +} diff --git a/examples/asg/main.tf b/examples/asg/main.tf index ab6d9affc94..58db7486c4c 100644 --- a/examples/asg/main.tf +++ b/examples/asg/main.tf @@ -1,17 +1,20 @@ -# Specify the provider and access details +terraform { + required_version = ">= 0.12" +} + provider "aws" { - region = "${var.aws_region}" + region = var.aws_region } locals { - availability_zones = "${split(",", var.availability_zones)}" + availability_zones = split(",", var.availability_zones) } resource "aws_elb" "web-elb" { name = "terraform-example-elb" # The same availability zone as our instances - availability_zones = "${local.availability_zones}" + availability_zones = local.availability_zones listener { instance_port = 80 @@ -30,14 +33,14 @@ resource "aws_elb" "web-elb" { } resource "aws_autoscaling_group" "web-asg" { - availability_zones = "${local.availability_zones}" + availability_zones = local.availability_zones name = "terraform-example-asg" - max_size = "${var.asg_max}" - min_size = "${var.asg_min}" - desired_capacity = "${var.asg_desired}" + max_size = var.asg_max + min_size = var.asg_min + desired_capacity = var.asg_desired force_delete = true - launch_configuration = "${aws_launch_configuration.web-lc.name}" - load_balancers = ["${aws_elb.web-elb.name}"] + launch_configuration = aws_launch_configuration.web-lc.name + load_balancers = [aws_elb.web-elb.name] #vpc_zone_identifier = ["${split(",", var.availability_zones)}"] tag { @@ -49,13 +52,13 @@ resource "aws_autoscaling_group" "web-asg" { resource "aws_launch_configuration" "web-lc" { name = "terraform-example-lc" - image_id = "${lookup(var.aws_amis, var.aws_region)}" - instance_type = "${var.instance_type}" + image_id = var.aws_amis[var.aws_region] + instance_type = var.instance_type # Security group - security_groups = ["${aws_security_group.default.id}"] - user_data = "${file("userdata.sh")}" - key_name = "${var.key_name}" + security_groups = [aws_security_group.default.id] + user_data = file("userdata.sh") + key_name = var.key_name } # Our default security group to access diff --git a/examples/asg/outputs.tf b/examples/asg/outputs.tf index faa5864c5dd..0f5acfd9d53 100644 --- a/examples/asg/outputs.tf +++ b/examples/asg/outputs.tf @@ -1,15 +1,15 @@ output "security_group" { - value = "${aws_security_group.default.id}" + value = aws_security_group.default.id } output "launch_configuration" { - value = "${aws_launch_configuration.web-lc.id}" + value = aws_launch_configuration.web-lc.id } output "asg_name" { - value = "${aws_autoscaling_group.web-asg.id}" + value = aws_autoscaling_group.web-asg.id } output "elb_name" { - value = "${aws_elb.web-elb.dns_name}" + value = aws_elb.web-elb.dns_name } diff --git a/examples/cloudhsm/main.tf b/examples/cloudhsm/main.tf index 4e0607a1c50..cde24b44db6 100644 --- a/examples/cloudhsm/main.tf +++ b/examples/cloudhsm/main.tf @@ -1,5 +1,9 @@ +terraform { + required_version = ">= 0.12" +} + provider "aws" { - region = "${var.aws_region}" + region = var.aws_region } data "aws_availability_zones" "available" {} @@ -14,10 +18,10 @@ resource "aws_vpc" "cloudhsm_v2_vpc" { resource "aws_subnet" "cloudhsm_v2_subnets" { count = 2 - vpc_id = "${aws_vpc.cloudhsm_v2_vpc.id}" - cidr_block = "${element(var.subnets, count.index)}" + vpc_id = aws_vpc.cloudhsm_v2_vpc.id + cidr_block = element(var.subnets, count.index) map_public_ip_on_launch = false - availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}" + availability_zone = element(data.aws_availability_zones.available.names, count.index) tags = { Name = "example-aws_cloudhsm_v2_cluster" @@ -26,7 +30,7 @@ resource "aws_subnet" "cloudhsm_v2_subnets" { resource "aws_cloudhsm_v2_cluster" "cloudhsm_v2_cluster" { hsm_type = "hsm1.medium" - subnet_ids = ["${aws_subnet.cloudhsm_v2_subnets.*.id}"] + subnet_ids = aws_subnet.cloudhsm_v2_subnets.*.id tags = { Name = "example-aws_cloudhsm_v2_cluster" @@ -34,11 +38,11 @@ resource "aws_cloudhsm_v2_cluster" "cloudhsm_v2_cluster" { } resource "aws_cloudhsm_v2_hsm" "cloudhsm_v2_hsm" { - subnet_id = "${aws_subnet.cloudhsm_v2_subnets.0.id}" - cluster_id = "${aws_cloudhsm_v2_cluster.cloudhsm_v2_cluster.cluster_id}" + subnet_id = aws_subnet.cloudhsm_v2_subnets[0].id + cluster_id = aws_cloudhsm_v2_cluster.cloudhsm_v2_cluster.cluster_id } data "aws_cloudhsm_v2_cluster" "cluster" { - cluster_id = "${aws_cloudhsm_v2_cluster.cloudhsm_v2_cluster.cluster_id}" - depends_on = ["aws_cloudhsm_v2_hsm.cloudhsm_v2_hsm"] + cluster_id = aws_cloudhsm_v2_cluster.cloudhsm_v2_cluster.cluster_id + depends_on = [aws_cloudhsm_v2_hsm.cloudhsm_v2_hsm] } diff --git a/examples/cloudhsm/outputs.tf b/examples/cloudhsm/outputs.tf index a91d8997a27..a3490dc600d 100644 --- a/examples/cloudhsm/outputs.tf +++ b/examples/cloudhsm/outputs.tf @@ -1,7 +1,7 @@ output "hsm_ip_address" { - value = "${aws_cloudhsm_v2_hsm.cloudhsm_v2_hsm.ip_address}" + value = aws_cloudhsm_v2_hsm.cloudhsm_v2_hsm.ip_address } output "cluster_data_certificate" { - value = "${data.aws_cloudhsm_v2_cluster.cluster.cluster_certificates.0.cluster_csr}" + value = data.aws_cloudhsm_v2_cluster.cluster.cluster_certificates[0].cluster_csr } diff --git a/examples/cloudhsm/variables.tf b/examples/cloudhsm/variables.tf index 31cdfd980ac..74e618c20cf 100644 --- a/examples/cloudhsm/variables.tf +++ b/examples/cloudhsm/variables.tf @@ -5,5 +5,5 @@ variable "aws_region" { variable "subnets" { default = ["10.0.1.0/24", "10.0.2.0/24"] - type = "list" + type = list(string) } diff --git a/examples/cloudwatch-events/kinesis/README.md b/examples/cloudwatch-events/kinesis/README.md index 2dcb829cc04..faf3ce79b42 100644 --- a/examples/cloudwatch-events/kinesis/README.md +++ b/examples/cloudwatch-events/kinesis/README.md @@ -9,6 +9,5 @@ in the official AWS docs. ## How to run the example ``` -terraform apply \ - -var=aws_region=us-west-2 +terraform apply -var=aws_region=us-west-2 ``` diff --git a/examples/cloudwatch-events/kinesis/main.tf b/examples/cloudwatch-events/kinesis/main.tf index db8555020e1..93b171e5b86 100644 --- a/examples/cloudwatch-events/kinesis/main.tf +++ b/examples/cloudwatch-events/kinesis/main.tf @@ -1,9 +1,13 @@ +terraform { + required_version = ">= 0.12" +} + provider "aws" { - region = "${var.aws_region}" + region = var.aws_region } resource "aws_cloudwatch_event_rule" "foo" { - name = "${var.rule_name}" + name = var.rule_name event_pattern = < + export AWS_SECRET_ACCESS_KEY= + +Create docker container and push it to ECR: + + ./build_and_push.sh foo + +### Deploy model and run test prediction call + +In the directory where this README is located, run the following: + + terraform init + terraform apply + + +Go back to `amazon-sagemaker-examples/advanced_functionality/scikit_bring_your_own/container/` and make a test call to the deployed model: + + aws runtime.sagemaker invoke-endpoint --endpoint-name terraform-sagemaker-example \ + --body "`cat ./local_test/payload.csv`" --content-type "text/csv" "output.dat" + +Have a look the predicted values: + + cat output.dat + +Destroy the deployed model: + + terraform destroy diff --git a/examples/sagemaker/main.tf b/examples/sagemaker/main.tf new file mode 100644 index 00000000000..ded75b3b90e --- /dev/null +++ b/examples/sagemaker/main.tf @@ -0,0 +1,132 @@ +terraform { + required_version = ">= 0.12" +} + +provider "aws" { + region = "us-west-2" +} + +data "aws_caller_identity" "current" {} + +data "aws_region" "current" {} + +resource "aws_iam_role" "foo" { + name = "terraform-sagemaker-example" + path = "/" + assume_role_policy = data.aws_iam_policy_document.assume_role.json +} + +data "aws_iam_policy_document" "assume_role" { + statement { + actions = ["sts:AssumeRole"] + principals { + type = "Service" + identifiers = ["sagemaker.amazonaws.com"] + } + } +} + +resource "aws_iam_policy" "foo" { + name = "terraform-sagemaker-example" + description = "Allow Sagemaker to create model" + policy = data.aws_iam_policy_document.foo.json +} + +data "aws_iam_policy_document" "foo" { + statement { + effect = "Allow" + actions = [ + "sagemaker:*" + ] + resources = [ + "*" + ] + } + statement { + effect = "Allow" + actions = [ + "cloudwatch:PutMetricData", + "logs:CreateLogStream", + "logs:PutLogEvents", + "logs:CreateLogGroup", + "logs:DescribeLogStreams", + "ecr:GetAuthorizationToken", + "ecr:BatchCheckLayerAvailability", + "ecr:GetDownloadUrlForLayer", + "ecr:BatchGetImage" + ] + resources = [ + "*"] + } + statement { + effect = "Allow" + actions = [ + "s3:GetObject" + ] + resources = [ + "arn:aws:s3:::${aws_s3_bucket.foo.bucket}", + "arn:aws:s3:::${aws_s3_bucket.foo.bucket}/*" + ] + } +} + +resource "aws_iam_role_policy_attachment" "foo" { + role = aws_iam_role.foo.name + policy_arn = aws_iam_policy.foo.arn +} + +resource "random_integer" "bucket_suffix" { + min = 1 + max = 99999 +} + +resource "aws_s3_bucket" "foo" { + bucket = "terraform-sagemaker-example-${random_integer.bucket_suffix.result}" + acl = "private" + force_destroy = true +} + +resource "aws_s3_bucket_object" "object" { + bucket = aws_s3_bucket.foo.bucket + key = "model.tar.gz" + source = "model.tar.gz" +} + +resource "aws_sagemaker_model" "foo" { + name = "terraform-sagemaker-example" + execution_role_arn = aws_iam_role.foo.arn + + primary_container { + image = "${data.aws_caller_identity.current.account_id}.dkr.ecr.${data.aws_region.current.name}.amazonaws.com/foo:latest" + model_data_url = "https://s3-us-west-2.amazonaws.com/${aws_s3_bucket.foo.bucket}/model.tar.gz" + } + + tags = { + foo = "bar" + } +} + +resource "aws_sagemaker_endpoint_configuration" "foo" { + name = "terraform-sagemaker-example" + + production_variants { + variant_name = "variant-1" + model_name = aws_sagemaker_model.foo.name + initial_instance_count = 1 + instance_type = "ml.t2.medium" + initial_variant_weight = 1 + } + + tags = { + foo = "bar" + } +} + +resource "aws_sagemaker_endpoint" "foo" { + name = "terraform-sagemaker-example" + endpoint_config_name = aws_sagemaker_endpoint_configuration.foo.name + + tags = { + foo = "bar" + } +} diff --git a/examples/sagemaker/model.tar.gz b/examples/sagemaker/model.tar.gz new file mode 100644 index 00000000000..a6338d0a3fb Binary files /dev/null and b/examples/sagemaker/model.tar.gz differ diff --git a/examples/transit-gateway-cross-account-peering-attachment/main.tf b/examples/transit-gateway-cross-account-peering-attachment/main.tf index 74771de7dc5..0799f85ac0f 100644 --- a/examples/transit-gateway-cross-account-peering-attachment/main.tf +++ b/examples/transit-gateway-cross-account-peering-attachment/main.tf @@ -1,87 +1,66 @@ -// First accepts the Peering attachment. +terraform { + required_version = ">= 0.12" +} + +# First accepts the Peering attachment. provider "aws" { alias = "first" - region = "${var.aws_first_region}" - access_key = "${var.aws_first_access_key}" - secret_key = "${var.aws_first_secret_key}" + region = var.aws_first_region + access_key = var.aws_first_access_key + secret_key = var.aws_first_secret_key } -// Second creates the Peering attachment. +# Second creates the Peering attachment. provider "aws" { alias = "second" - region = "${var.aws_second_region}" - access_key = "${var.aws_second_access_key}" - secret_key = "${var.aws_second_secret_key}" + region = var.aws_second_region + access_key = var.aws_second_access_key + secret_key = var.aws_second_secret_key } data "aws_caller_identity" "first" { - provider = "aws.first" -} - -data "aws_caller_identity" "second" { - provider = "aws.second" + provider = aws.first } resource "aws_ec2_transit_gateway" "first" { - provider = "aws.first" + provider = aws.first tags = { Name = "terraform-example" } } -resource "aws_ram_resource_share" "example" { - provider = "aws.first" - - name = "terraform-example" +resource "aws_ec2_transit_gateway" "second" { + provider = aws.second tags = { Name = "terraform-example" } } -// Share the transit gateway... -resource "aws_ram_resource_association" "example" { - provider = "aws.first" - - resource_arn = "${aws_ec2_transit_gateway.first.arn}" - resource_share_arn = "${aws_ram_resource_share.example.id}" -} - -// ...with the second account. -resource "aws_ram_principal_association" "example" { - provider = "aws.first" - - principal = "${data.aws_caller_identity.second.account_id}" - resource_share_arn = "${aws_ram_resource_share.example.id}" -} - -resource "aws_ec2_transit_gateway" "second" { - provider = "aws.second" +# Create the Peering attachment in the second account... +resource "aws_ec2_transit_gateway_peering_attachment" "example" { + provider = aws.second + peer_account_id = data.aws_caller_identity.first.account_id + peer_region = var.aws_first_region + peer_transit_gateway_id = aws_ec2_transit_gateway.first.id + transit_gateway_id = aws_ec2_transit_gateway.second.id tags = { Name = "terraform-example" + Side = "Creator" } } -// Create the Peering attachment in the second account... -resource "aws_ec2_transit_gateway_peering_attachment" "example" { - provider = "aws.second" +# ...and accept it in the first account. +resource "aws_ec2_transit_gateway_peering_attachment_accepter" "example" { + provider = aws.first - peer_account_id = "${data.aws_caller_identity.first.account_id}" - peer_region = "${var.aws_first_region}" - peer_transit_gateway_id = "${aws_ec2_transit_gateway.first.id}" - transit_gateway_id = "${aws_ec2_transit_gateway.second.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_peering_attachment.example.id tags = { Name = "terraform-example" - Side = "Creator" + Side = "Acceptor" } - depends_on = ["aws_ram_principal_association.example", "aws_ram_resource_association.example"] - } - -// ...it then needs to accepted by the first account. - -// ...terraform currently doesnt have resource for Transit Gateway Peering Attachment Acceptance diff --git a/examples/transit-gateway-cross-account-vpc-attachment/main.tf b/examples/transit-gateway-cross-account-vpc-attachment/main.tf index 344ecd8f486..31a9c41210b 100644 --- a/examples/transit-gateway-cross-account-vpc-attachment/main.tf +++ b/examples/transit-gateway-cross-account-vpc-attachment/main.tf @@ -1,33 +1,37 @@ -// First account owns the transit gateway and accepts the VPC attachment. +terraform { + required_version = ">= 0.12" +} + +# First account owns the transit gateway and accepts the VPC attachment. provider "aws" { alias = "first" - region = "${var.aws_region}" - access_key = "${var.aws_first_access_key}" - secret_key = "${var.aws_first_secret_key}" + region = var.aws_region + access_key = var.aws_first_access_key + secret_key = var.aws_first_secret_key } -// Second account owns the VPC and creates the VPC attachment. +# Second account owns the VPC and creates the VPC attachment. provider "aws" { alias = "second" - region = "${var.aws_region}" - access_key = "${var.aws_second_access_key}" - secret_key = "${var.aws_second_secret_key}" + region = var.aws_region + access_key = var.aws_second_access_key + secret_key = var.aws_second_secret_key } data "aws_availability_zones" "available" { - provider = "aws.second" + provider = aws.second state = "available" } data "aws_caller_identity" "second" { - provider = "aws.second" + provider = aws.second } resource "aws_ec2_transit_gateway" "example" { - provider = "aws.first" + provider = aws.first tags = { Name = "terraform-example" @@ -35,7 +39,7 @@ resource "aws_ec2_transit_gateway" "example" { } resource "aws_ram_resource_share" "example" { - provider = "aws.first" + provider = aws.first name = "terraform-example" @@ -44,24 +48,24 @@ resource "aws_ram_resource_share" "example" { } } -// Share the transit gateway... +# Share the transit gateway... resource "aws_ram_resource_association" "example" { - provider = "aws.first" + provider = aws.first - resource_arn = "${aws_ec2_transit_gateway.example.arn}" - resource_share_arn = "${aws_ram_resource_share.example.id}" + resource_arn = aws_ec2_transit_gateway.example.arn + resource_share_arn = aws_ram_resource_share.example.id } -// ...with the second account. +# ...with the second account. resource "aws_ram_principal_association" "example" { - provider = "aws.first" + provider = aws.first - principal = "${data.aws_caller_identity.second.account_id}" - resource_share_arn = "${aws_ram_resource_share.example.id}" + principal = data.aws_caller_identity.second.account_id + resource_share_arn = aws_ram_resource_share.example.id } resource "aws_vpc" "example" { - provider = "aws.second" + provider = aws.second cidr_block = "10.0.0.0/16" @@ -71,26 +75,29 @@ resource "aws_vpc" "example" { } resource "aws_subnet" "example" { - provider = "aws.second" + provider = aws.second - availability_zone = "${data.aws_availability_zones.available.names[0]}" + availability_zone = data.aws_availability_zones.available.names[0] cidr_block = "10.0.0.0/24" - vpc_id = "${aws_vpc.example.id}" + vpc_id = aws_vpc.example.id tags = { Name = "terraform-example" } } -// Create the VPC attachment in the second account... +# Create the VPC attachment in the second account... resource "aws_ec2_transit_gateway_vpc_attachment" "example" { - provider = "aws.second" + provider = aws.second - depends_on = ["aws_ram_principal_association.example", "aws_ram_resource_association.example"] + depends_on = [ + aws_ram_principal_association.example, + aws_ram_resource_association.example, + ] - subnet_ids = ["${aws_subnet.example.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.example.id}" - vpc_id = "${aws_vpc.example.id}" + subnet_ids = [aws_subnet.example.id] + transit_gateway_id = aws_ec2_transit_gateway.example.id + vpc_id = aws_vpc.example.id tags = { Name = "terraform-example" @@ -98,11 +105,11 @@ resource "aws_ec2_transit_gateway_vpc_attachment" "example" { } } -// ...and accept it in the first account. +# ...and accept it in the first account. resource "aws_ec2_transit_gateway_vpc_attachment_accepter" "example" { - provider = "aws.first" + provider = aws.first - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.example.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.example.id tags = { Name = "terraform-example" diff --git a/examples/two-tier/main.tf b/examples/two-tier/main.tf index 348e0af4ee3..d1b8b41701d 100644 --- a/examples/two-tier/main.tf +++ b/examples/two-tier/main.tf @@ -1,6 +1,9 @@ -# Specify the provider and access details +terraform { + required_version = ">= 0.12" +} + provider "aws" { - region = "${var.aws_region}" + region = var.aws_region } # Create a VPC to launch our instances into @@ -10,19 +13,19 @@ resource "aws_vpc" "default" { # Create an internet gateway to give our subnet access to the outside world resource "aws_internet_gateway" "default" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id } # Grant the VPC internet access on its main route table resource "aws_route" "internet_access" { - route_table_id = "${aws_vpc.default.main_route_table_id}" + route_table_id = aws_vpc.default.main_route_table_id destination_cidr_block = "0.0.0.0/0" - gateway_id = "${aws_internet_gateway.default.id}" + gateway_id = aws_internet_gateway.default.id } # Create a subnet to launch our instances into resource "aws_subnet" "default" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id cidr_block = "10.0.1.0/24" map_public_ip_on_launch = true } @@ -31,7 +34,7 @@ resource "aws_subnet" "default" { resource "aws_security_group" "elb" { name = "terraform_example_elb" description = "Used in the terraform" - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id # HTTP access from anywhere ingress { @@ -55,7 +58,7 @@ resource "aws_security_group" "elb" { resource "aws_security_group" "default" { name = "terraform_example" description = "Used in the terraform" - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id # SSH access from anywhere ingress { @@ -85,9 +88,9 @@ resource "aws_security_group" "default" { resource "aws_elb" "web" { name = "terraform-example-elb" - subnets = ["${aws_subnet.default.id}"] - security_groups = ["${aws_security_group.elb.id}"] - instances = ["${aws_instance.web.id}"] + subnets = [aws_subnet.default.id] + security_groups = [aws_security_group.elb.id] + instances = [aws_instance.web.id] listener { instance_port = 80 @@ -98,17 +101,18 @@ resource "aws_elb" "web" { } resource "aws_key_pair" "auth" { - key_name = "${var.key_name}" - public_key = "${file(var.public_key_path)}" + key_name = var.key_name + public_key = file(var.public_key_path) } resource "aws_instance" "web" { # The connection block tells our provisioner how to # communicate with the resource (instance) connection { + type = "ssh" # The default username for our AMI user = "ubuntu" - host = "${self.public_ip}" + host = self.public_ip # The connection will use the local SSH agent for authentication. } @@ -116,18 +120,18 @@ resource "aws_instance" "web" { # Lookup the correct AMI based on the region # we specified - ami = "${lookup(var.aws_amis, var.aws_region)}" + ami = var.aws_amis[var.aws_region] # The name of our SSH keypair we created above. - key_name = "${aws_key_pair.auth.id}" + key_name = aws_key_pair.auth.id # Our Security group to allow HTTP and SSH access - vpc_security_group_ids = ["${aws_security_group.default.id}"] + vpc_security_group_ids = [aws_security_group.default.id] # We're going to launch into the same subnet as our ELB. In a production # environment it's more common to have a separate private subnet for # backend instances. - subnet_id = "${aws_subnet.default.id}" + subnet_id = aws_subnet.default.id # We run a remote provisioner on the instance after creating it. # In this case, we just install nginx and start it. By default, diff --git a/examples/two-tier/outputs.tf b/examples/two-tier/outputs.tf index 5977837f333..2c535bb7283 100644 --- a/examples/two-tier/outputs.tf +++ b/examples/two-tier/outputs.tf @@ -1,3 +1,3 @@ output "address" { - value = "${aws_elb.web.dns_name}" + value = aws_elb.web.dns_name } diff --git a/examples/workspaces/README.md b/examples/workspaces/README.md new file mode 100644 index 00000000000..9b6b75bbeba --- /dev/null +++ b/examples/workspaces/README.md @@ -0,0 +1,20 @@ +# AWS WorkSpaces Example + +This example demonstrates how to create a WorkSpace and WorkSpace directory using AWS WorkSpaces. + +## Note + +The AWS WorkSpaces service requires an IAM role named `workspaces_DefaultRole`. By default, this example assumes the role exists and is configured. If the role does not exist or is not configured appropriately, the example will not successfully deploy. + +The IAM resources are defined in the Terraform source file [iam.tf](./iam.tf), but are commented out. If the role does not exist in your environment, uncomment the contents of the file. The resources `aws_workspaces_directory.example` and `aws_workspaces_workspace.example` have dependencies on the IAM resources. The `depends_on` meta-arguments should also be uncommented on both. + +## Running this example + +This example can be run by calling + +```shell +terraform init +terraform apply +``` + +By default, resources are created in the `us-west-2` region. To override the region, set the variable `aws_region` to a different value. diff --git a/examples/workspaces/iam.tf b/examples/workspaces/iam.tf new file mode 100644 index 00000000000..de04b6a94a7 --- /dev/null +++ b/examples/workspaces/iam.tf @@ -0,0 +1,28 @@ +# Uncomment the resources in this file to create the IAM resources required by the AWS WorkSpaces service. +# Also uncomment the `depends_on` meta-arguments on `aws_workspaces_directory.example` and `aws_workspaces_workspace.example`. +# +# resource "aws_iam_role" "workspaces-default" { +# name = "workspaces_DefaultRole" +# assume_role_policy = "${data.aws_iam_policy_document.workspaces.json}" +# } +# +# data "aws_iam_policy_document" "workspaces" { +# statement { +# actions = ["sts:AssumeRole"] +# +# principals { +# type = "Service" +# identifiers = ["workspaces.amazonaws.com"] +# } +# } +# } +# +# resource "aws_iam_role_policy_attachment" "workspaces-default-service-access" { +# role = "${aws_iam_role.workspaces-default.name}" +# policy_arn = "arn:aws:iam::aws:policy/AmazonWorkSpacesServiceAccess" +# } +# +# resource "aws_iam_role_policy_attachment" "workspaces-default-self-service-access" { +# role = "${aws_iam_role.workspaces-default.name}" +# policy_arn = "arn:aws:iam::aws:policy/AmazonWorkSpacesSelfServiceAccess" +# } diff --git a/examples/workspaces/main.tf b/examples/workspaces/main.tf index cda2e0ed538..af5b90ea40f 100644 --- a/examples/workspaces/main.tf +++ b/examples/workspaces/main.tf @@ -1,36 +1,54 @@ -provider "aws" { - region = "us-east-1" +terraform { + required_version = ">= 0.12" } -resource "aws_vpc" "main" { - cidr_block = "10.0.0.0/16" +provider "aws" { + region = var.aws_region } -resource "aws_subnet" "private-a" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "us-east-1a" - cidr_block = "10.0.1.0/24" +resource "aws_workspaces_directory" "example" { + directory_id = aws_directory_service_directory.example.id + subnet_ids = [aws_subnet.private-a.id, aws_subnet.private-b.id] + + # Uncomment this meta-argument if you are creating the IAM resources required by the AWS WorkSpaces service. + # depends_on = [ + # "aws_iam_role.workspaces-default" + # ] } -resource "aws_subnet" "private-b" { - vpc_id = "${aws_vpc.main.id}" - availability_zone = "us-east-1b" - cidr_block = "10.0.2.0/24" +data "aws_workspaces_bundle" "value_windows" { + bundle_id = "wsb-bh8rsxt14" # Value with Windows 10 (English) } -resource "aws_directory_service_directory" "main" { - name = "tf-acctest.example.com" - password = "#S1ncerely" - size = "Small" - vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.private-a.id}", "${aws_subnet.private-b.id}"] +resource "aws_workspaces_workspace" "example" { + directory_id = aws_workspaces_directory.example.id + bundle_id = data.aws_workspaces_bundle.value_windows.id + + # Administrator is always present in a new directory. + user_name = "Administrator" + + root_volume_encryption_enabled = true + user_volume_encryption_enabled = true + volume_encryption_key = aws_kms_key.example.arn + + workspace_properties { + compute_type_name = "VALUE" + user_volume_size_gib = 10 + root_volume_size_gib = 80 + running_mode = "AUTO_STOP" + running_mode_auto_stop_timeout_in_minutes = 60 } -} -resource "aws_workspaces_directory" "main" { - directory_id = "${aws_directory_service_directory.main.id}" - subnet_ids = ["${aws_subnet.private-a.id}", "${aws_subnet.private-b.id}"] + tags = { + Department = "IT" + } + + # Uncomment this meta-argument if you are creating the IAM resources required by the AWS WorkSpaces service. + # depends_on = [ + # # The role "workspaces_DefaultRole" requires the policy arn:aws:iam::aws:policy/AmazonWorkSpacesServiceAccess + # # to create and delete the ENI that the Workspaces service creates for the Workspace + # "aws_iam_role_policy_attachment.workspaces-default-service-access", + # ] } resource "aws_workspaces_ip_group" "main" { @@ -46,3 +64,59 @@ resource "aws_workspaces_ip_group" "main" { description = "Contractors" } } + +data "aws_region" "current" {} + +data "aws_availability_zones" "available" { + state = "available" + + filter { + name = "opt-in-status" + values = ["opt-in-not-required"] + } +} + +locals { + # Workspace instances are not supported in all AZs in some regions + # We use joined and split string values here instead of lists for Terraform 0.11 compatibility + region_workspaces_az_id_strings = { + "us-east-1" = join(",", formatlist("use1-az%d", ["2", "4", "6"])) + } + + workspaces_az_id_strings = lookup( + local.region_workspaces_az_id_strings, + data.aws_region.current.name, + join(",", data.aws_availability_zones.available.zone_ids), + ) + workspaces_az_ids = split(",", local.workspaces_az_id_strings) +} + +resource "aws_vpc" "main" { + cidr_block = "10.0.0.0/16" +} + +resource "aws_subnet" "private-a" { + vpc_id = aws_vpc.main.id + availability_zone_id = local.workspaces_az_ids[0] + cidr_block = "10.0.1.0/24" +} + +resource "aws_subnet" "private-b" { + vpc_id = aws_vpc.main.id + availability_zone_id = local.workspaces_az_ids[1] + cidr_block = "10.0.2.0/24" +} + +resource "aws_directory_service_directory" "example" { + name = "workspaces.example.com" + password = "#S1ncerely" + size = "Small" + vpc_settings { + vpc_id = aws_vpc.main.id + subnet_ids = [aws_subnet.private-a.id, aws_subnet.private-b.id] + } +} + +resource "aws_kms_key" "example" { + description = "WorkSpaces example key" +} diff --git a/examples/workspaces/variables.tf b/examples/workspaces/variables.tf new file mode 100644 index 00000000000..3c91c693825 --- /dev/null +++ b/examples/workspaces/variables.tf @@ -0,0 +1,4 @@ +variable "aws_region" { + description = "The AWS region to use" + default = "us-west-2" +} diff --git a/go.mod b/go.mod index fe28e1d0016..42676918d5a 100644 --- a/go.mod +++ b/go.mod @@ -1,25 +1,25 @@ module github.com/terraform-providers/terraform-provider-aws -go 1.13 +go 1.14 require ( - github.com/aws/aws-sdk-go v1.30.21 + github.com/aws/aws-sdk-go v1.34.4 github.com/beevik/etree v1.1.0 - github.com/bflad/tfproviderdocs v0.5.3 - github.com/bflad/tfproviderlint v0.14.0 + github.com/bflad/tfproviderdocs v0.7.0 + github.com/bflad/tfproviderlint v0.18.0 github.com/client9/misspell v0.3.4 - github.com/golangci/golangci-lint v1.26.0 - github.com/hashicorp/aws-sdk-go-base v0.4.0 + github.com/golangci/golangci-lint v1.29.0 + github.com/hashicorp/aws-sdk-go-base v0.5.0 github.com/hashicorp/go-cleanhttp v0.5.1 - github.com/hashicorp/go-multierror v1.0.0 - github.com/hashicorp/go-version v1.2.0 - github.com/hashicorp/terraform-plugin-sdk v1.9.0 - github.com/hashicorp/vault v0.10.4 + github.com/hashicorp/go-multierror v1.1.0 + github.com/hashicorp/go-version v1.2.1 + github.com/hashicorp/terraform-plugin-sdk/v2 v2.0.1 github.com/jen20/awspolicyequivalence v1.1.0 github.com/katbyte/terrafmt v0.2.1-0.20200303174203-e6a3e82cb21b + github.com/keybase/go-crypto v0.0.0-20161004153544-93f5b35093ba github.com/mitchellh/copystructure v1.0.0 github.com/mitchellh/go-homedir v1.1.0 github.com/pquerna/otp v1.2.0 - golang.org/x/tools v0.0.0-20200422022333-3d57cf2e726e - gopkg.in/yaml.v2 v2.2.8 + golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed + gopkg.in/yaml.v2 v2.3.0 ) diff --git a/go.sum b/go.sum index 63b3b715bd3..d5fd6fb72ec 100644 --- a/go.sum +++ b/go.sum @@ -5,18 +5,51 @@ cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6A cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= cloud.google.com/go v0.45.1 h1:lRi0CHyU+ytlvylOlFKKq0af6JncuyoRh1J+QJBqQx0= cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3 h1:AVXDdKsrtX33oR9fbCMu/+c1o8Ofjq6Ku/MInaLVg5Y= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go v0.61.0 h1:NLQf5e1OMspfNT1RAHOB3ublr1TW3YTXO8OiWwVjK2U= +cloud.google.com/go v0.61.0/go.mod h1:XukKJg4Y7QsUu0Hxg3qQKUWR4VuWivmyMK2+rUyxAqw= +cloud.google.com/go/bigquery v1.0.1 h1:hL+ycaJpVE9M7nLoiXb/Pn10ENE2u+oddxbD8uu0ZVU= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/datastore v1.0.0 h1:Kt+gOPPp2LEPWp8CSfxhsM8ik9CcyE/gYu+0r+RnZvM= cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= +cloud.google.com/go/pubsub v1.0.1 h1:W9tAK3E57P75u0XLLR82LZyw8VpAnhmyTOxW9qzmyj8= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= +cloud.google.com/go/storage v1.0.0 h1:VV2nUM3wwLLGh9lSABFgZMjInyUbJeaRSE64WuAIQ+4= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +cloud.google.com/go/storage v1.10.0 h1:STgFzyU5/8miMl0//zKh2aQeTyeaUH3WN9bSUiJ09bA= +cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/Djarvur/go-err113 v0.0.0-20200410182137-af658d038157 h1:hY39LwQHh+1kaovmIjOrlqnXNX6tygSRfLkkK33IkZU= -github.com/Djarvur/go-err113 v0.0.0-20200410182137-af658d038157/go.mod h1:4UJr5HIiMZrwgkSPdsjy2uOQExX/WEILpIrO9UPGuXs= +github.com/Djarvur/go-err113 v0.0.0-20200511133814-5174e21577d5 h1:XTrzB+F8+SpRmbhAH8HLxhiiG6nYNwaBZjrFps1oWEk= +github.com/Djarvur/go-err113 v0.0.0-20200511133814-5174e21577d5/go.mod h1:4UJr5HIiMZrwgkSPdsjy2uOQExX/WEILpIrO9UPGuXs= +github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= +github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/OpenPeeDeeP/depguard v1.0.1 h1:VlW4R6jmBIv3/u1JNlawEvJMM4J+dPORPaZasQee8Us= github.com/OpenPeeDeeP/depguard v1.0.1/go.mod h1:xsIw86fROiiwelg+jB2uM9PiKihMMmUx/1V+TNhjQvM= github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= -github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8= github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/agext/levenshtein v1.2.2 h1:0S/Yg6LYmFJ5stwQeRp6EeOcCbj7xiqQSdNelsXvaqE= github.com/agext/levenshtein v1.2.2/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= @@ -33,68 +66,81 @@ github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0 h1:MzVXffFU github.com/apparentlymart/go-dump v0.0.0-20190214190832-042adf3cf4a0/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= github.com/apparentlymart/go-textseg v1.0.0 h1:rRmlIsPEEhUTIKQb7T++Nz/A5Q6C9IuX2wFoYVvnCs0= github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= +github.com/apparentlymart/go-textseg/v12 v12.0.0/go.mod h1:S/4uRK2UtaQttw1GenVJEynmyUenKwP++x/+DdGV/Ec= +github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI= github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/aws/aws-sdk-go v1.15.78/go.mod h1:E3/ieXAlvM0XWO57iftYVDLLvQ824smPP3ATZkfNZeM= github.com/aws/aws-sdk-go v1.25.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= -github.com/aws/aws-sdk-go v1.30.21 h1:19EO1Jr80+jLwJyITzH8c79C/6EwY5mMyasqDbBiCuc= -github.com/aws/aws-sdk-go v1.30.21/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= +github.com/aws/aws-sdk-go v1.31.9/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= +github.com/aws/aws-sdk-go v1.34.4 h1:Yx49/+ZMCD9YqIVsO3CsiMs4hnUnokd9otKvWYFjnYw= +github.com/aws/aws-sdk-go v1.34.4/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= github.com/beevik/etree v1.1.0 h1:T0xke/WvNtMoCqgzPhkX2r4rjY3GDZFi+FjpRZY2Jbs= github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/bflad/gopaniccheck v0.1.0 h1:tJftp+bv42ouERmUMWLoUn/5bi/iQZjHPznM00cP/bU= github.com/bflad/gopaniccheck v0.1.0/go.mod h1:ZCj2vSr7EqVeDaqVsWN4n2MwdROx1YL+LFo47TSWtsA= -github.com/bflad/tfproviderdocs v0.5.3 h1:0JozhslEaLujgTnV6OdljbFiT/FCponx5hruFSkizGk= -github.com/bflad/tfproviderdocs v0.5.3/go.mod h1:d0k1fQLEu1pdeORxozwuwmvauFaEmMBREQ1fw3J+pPc= -github.com/bflad/tfproviderlint v0.14.0 h1:iki5tDr4l0jp0zEL0chZylptMT5QdE09E60cziFQNZA= -github.com/bflad/tfproviderlint v0.14.0/go.mod h1:1Jtjs6DPKoyqPrbPyMiy33h0ViO2h831uzoOuikCA60= +github.com/bflad/tfproviderdocs v0.7.0 h1:5cb+zUYLqvC4ZePLWqUE/oCmOl2D2nhJTOFfcWWN0ac= +github.com/bflad/tfproviderdocs v0.7.0/go.mod h1:W6wVZPtBa6V5bpjaK1eJAoVCL/7B4Amfrld0dro+fHU= +github.com/bflad/tfproviderlint v0.18.0 h1:E4EWq051fp2zjxdUj9x6gNG27AcdyRkxip5XP03N840= +github.com/bflad/tfproviderlint v0.18.0/go.mod h1:0fdh7JywihC58Io8AZ+gpcmQtJggse0MCOXF2tMmnAQ= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= github.com/bmatcuk/doublestar v1.2.1 h1:eetYiv8DDYOZcBADY+pRvRytf3Dlz1FhnpvL2FsClBc= github.com/bmatcuk/doublestar v1.2.1/go.mod h1:wiQtGV+rzVYxB7WIlirSN++5HPtPlXEo9MEoZQC/PmE= -github.com/bombsimon/wsl/v3 v3.0.0 h1:w9f49xQatuaeTJFaNP4SpiWSR5vfT6IstPtM62JjcqA= -github.com/bombsimon/wsl/v3 v3.0.0/go.mod h1:st10JtZYLE4D5sC7b8xV4zTKZwAQjCH/Hy2Pm1FNZIc= +github.com/bombsimon/wsl/v3 v3.1.0 h1:E5SRssoBgtVFPcYWUOFJEcgaySgdtTNYzsSKDOY7ss8= +github.com/bombsimon/wsl/v3 v3.1.0/go.mod h1:st10JtZYLE4D5sC7b8xV4zTKZwAQjCH/Hy2Pm1FNZIc= github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI= github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4 h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= -github.com/coreos/etcd v3.3.10+incompatible h1:jFneRYjIvLMLhDLCzuTuU4rSJUjRplcJQ7pD7MnhC04= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= -github.com/coreos/go-semver v0.2.0 h1:3Jm3tLmsgAYcjC+4Up7hJrFBPr+n7rAqYeSw/SZazuY= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= -github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= +github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/denis-tingajkin/go-header v0.3.1 h1:ymEpSiFjeItCy1FOP+x0M2KdCELdEAHUsNa8F+hHc6w= +github.com/denis-tingajkin/go-header v0.3.1/go.mod h1:sq/2IxMhaZX+RRcgHfCRx/m0M5na0fBt4/CRe7Lrji0= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= +github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/go-critic/go-critic v0.4.1 h1:4DTQfT1wWwLg/hzxwD9bkdhDQrdJtxe6DUTadPlrIeE= -github.com/go-critic/go-critic v0.4.1/go.mod h1:7/14rZGnZbY6E38VEGk2kVhoq6itzc1E68facVDK23g= +github.com/go-critic/go-critic v0.5.0 h1:Ic2p5UCl5fX/2WX2w8nroPpPhxRNsNTMlJzsu/uqwnM= +github.com/go-critic/go-critic v0.5.0/go.mod h1:4jeRh3ZAVnRYhuWdOEvwzVqLUpxMSoAT0xZ74JsTPlo= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-lintpack/lintpack v0.5.2 h1:DI5mA3+eKdWeJ40nU4d6Wc26qmdG8RCi/btYq0TuRN0= github.com/go-lintpack/lintpack v0.5.2/go.mod h1:NwZuYi2nUHho8XEIZ6SIxihrnPoqBTDqfpXvXAN0sXM= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= @@ -108,54 +154,64 @@ github.com/go-toolsmith/astcast v1.0.0 h1:JojxlmI6STnFVG9yOImLeGREv8W2ocNUM+iOhR github.com/go-toolsmith/astcast v1.0.0/go.mod h1:mt2OdQTeAQcY4DQgPSArJjHCcOwlX+Wl/kwN+LbLGQ4= github.com/go-toolsmith/astcopy v1.0.0 h1:OMgl1b1MEpjFQ1m5ztEO06rz5CUd3oBv9RF7+DyvdG8= github.com/go-toolsmith/astcopy v1.0.0/go.mod h1:vrgyG+5Bxrnz4MZWPF+pI4R8h3qKRjjyvV/DSez4WVQ= -github.com/go-toolsmith/astequal v0.0.0-20180903214952-dcb477bfacd6 h1:aTBUNRTatDDU24gbOEKEoLiDwxtc98ga6K/iMTm6fvs= github.com/go-toolsmith/astequal v0.0.0-20180903214952-dcb477bfacd6/go.mod h1:H+xSiq0+LtiDC11+h1G32h7Of5O3CYFJ99GVbS5lDKY= github.com/go-toolsmith/astequal v1.0.0 h1:4zxD8j3JRFNyLN46lodQuqz3xdKSrur7U/sr0SDS/gQ= github.com/go-toolsmith/astequal v1.0.0/go.mod h1:H+xSiq0+LtiDC11+h1G32h7Of5O3CYFJ99GVbS5lDKY= -github.com/go-toolsmith/astfmt v0.0.0-20180903215011-8f8ee99c3086 h1:EIMuvbE9fbtQtimdLe5yeXjuC5CeKbQt8zH6GwtIrhM= github.com/go-toolsmith/astfmt v0.0.0-20180903215011-8f8ee99c3086/go.mod h1:mP93XdblcopXwlyN4X4uodxXQhldPGZbcEJIimQHrkg= github.com/go-toolsmith/astfmt v1.0.0 h1:A0vDDXt+vsvLEdbMFJAUBI/uTbRw1ffOPnxsILnFL6k= github.com/go-toolsmith/astfmt v1.0.0/go.mod h1:cnWmsOAuq4jJY6Ct5YWlVLmcmLMn1JUPuQIHCY7CJDw= github.com/go-toolsmith/astinfo v0.0.0-20180906194353-9809ff7efb21/go.mod h1:dDStQCHtmZpYOmjRP/8gHHnCCch3Zz3oEgCdZVdtweU= -github.com/go-toolsmith/astp v0.0.0-20180903215135-0af7e3c24f30 h1:zRJPftZJNLPDiOtvYbFRwjSbaJAcVOf80TeEmWGe2kQ= github.com/go-toolsmith/astp v0.0.0-20180903215135-0af7e3c24f30/go.mod h1:SV2ur98SGypH1UjcPpCatrV5hPazG6+IfNHbkDXBRrk= github.com/go-toolsmith/astp v1.0.0 h1:alXE75TXgcmupDsMK1fRAy0YUzLzqPVvBKoyWV+KPXg= github.com/go-toolsmith/astp v1.0.0/go.mod h1:RSyrtpVlfTFGDYRbrjyWP1pYu//tSFcvdYrA8meBmLI= -github.com/go-toolsmith/pkgload v0.0.0-20181119091011-e9e65178eee8 h1:vVouagbdmqTVlCIAxpyYsNNTbkKZ3V66VpKOLU/s6W4= github.com/go-toolsmith/pkgload v0.0.0-20181119091011-e9e65178eee8/go.mod h1:WoMrjiy4zvdS+Bg6z9jZH82QXwkcgCBX6nOfnmdaHks= github.com/go-toolsmith/pkgload v1.0.0 h1:4DFWWMXVfbcN5So1sBNW9+yeiMqLFGl1wFLTL5R0Tgg= github.com/go-toolsmith/pkgload v1.0.0/go.mod h1:5eFArkbO80v7Z0kdngIxsRXRMTaX4Ilcwuh3clNrQJc= github.com/go-toolsmith/strparse v1.0.0 h1:Vcw78DnpCAKlM20kSbAyO4mPfJn/lyYA4BJUDxe2Jb4= github.com/go-toolsmith/strparse v1.0.0/go.mod h1:YI2nUKP9YGZnL/L1/DLFBfixrcjslWct4wyljWhSRy8= -github.com/go-toolsmith/typep v1.0.0 h1:zKymWyA1TRYvqYrYDrfEMZULyrhcnGY3x7LDKU2XQaA= github.com/go-toolsmith/typep v1.0.0/go.mod h1:JSQCQMUPdRlMZFswiq3TGpNp1GMktqkR2Ns5AIQkATU= +github.com/go-toolsmith/typep v1.0.2 h1:8xdsa1+FSIH/RhEkgnD1j2CJOy5mNllW1Q9tRiYwvlk= +github.com/go-toolsmith/typep v1.0.2/go.mod h1:JSQCQMUPdRlMZFswiq3TGpNp1GMktqkR2Ns5AIQkATU= +github.com/go-xmlfmt/xmlfmt v0.0.0-20191208150333-d5b6f63a941b h1:khEcpUM4yFcxg4/FHQWkvVRmgijNXRfzkIDHh23ggEo= github.com/go-xmlfmt/xmlfmt v0.0.0-20191208150333-d5b6f63a941b/go.mod h1:aUCEOzzezBEjDBbFBoSiya/gduyIiWYRP6CnSFIV8AM= github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= -github.com/gofrs/flock v0.0.0-20190320160742-5135e617513b h1:ekuhfTjngPhisSjOJ0QWKpPQE8/rbknHaes6WVJj5Hw= -github.com/gofrs/flock v0.0.0-20190320160742-5135e617513b/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= +github.com/gofrs/flock v0.7.1 h1:DP+LD/t0njgoPBvT5MJLeliUIVQR03hiKR6vezdwHlc= +github.com/gofrs/flock v0.7.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1 h1:/s5zKNz0uPFCZ5hddgPdo2TK2TVrUNMn0OOX8/aZMTE= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1 h1:G5FRp8JnTd7RQH5kemVNlMeyXQAztQ3mOWV95KxsXH8= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0 h1:28o5sBqPkBsMGnC6b4MvE2TzSr5/AT4c/1fLqVGIwlk= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1 h1:qGJ6qTW+x6xX/my+8YUVl4WNpX9B7+/l2tRsHGZ7f2s= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3 h1:GV+pQPG/EUUbkh47niozDcADz6go/dUwhVzdUQHIVRw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.3.4 h1:87PNWwrRvUSnqS4dlcBU/ftvOIBep4sYuBLlh6rX2wk= github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golangci/check v0.0.0-20180506172741-cfe4005ccda2 h1:23T5iq8rbUYlhpt5DB4XJkc6BU31uODLD1o1gKvZmD0= @@ -168,12 +224,12 @@ github.com/golangci/go-misc v0.0.0-20180628070357-927a3d87b613 h1:9kfjN3AdxcbsZB github.com/golangci/go-misc v0.0.0-20180628070357-927a3d87b613/go.mod h1:SyvUF2NxV+sN8upjjeVYr5W7tyxaT1JVtvhKhOn2ii8= github.com/golangci/goconst v0.0.0-20180610141641-041c5f2b40f3 h1:pe9JHs3cHHDQgOFXJJdYkK6fLz2PWyYtP4hthoCMvs8= github.com/golangci/goconst v0.0.0-20180610141641-041c5f2b40f3/go.mod h1:JXrF4TWy4tXYn62/9x8Wm/K/dm06p8tCKwFRDPZG/1o= -github.com/golangci/gocyclo v0.0.0-20180528134321-2becd97e67ee h1:J2XAy40+7yz70uaOiMbNnluTg7gyQhtGqLQncQh+4J8= -github.com/golangci/gocyclo v0.0.0-20180528134321-2becd97e67ee/go.mod h1:ozx7R9SIwqmqf5pRP90DhR2Oay2UIjGuKheCBCNwAYU= +github.com/golangci/gocyclo v0.0.0-20180528144436-0a533e8fa43d h1:pXTK/gkVNs7Zyy7WKgLXmpQ5bHTrq5GDsp8R9Qs67g0= +github.com/golangci/gocyclo v0.0.0-20180528144436-0a533e8fa43d/go.mod h1:ozx7R9SIwqmqf5pRP90DhR2Oay2UIjGuKheCBCNwAYU= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a h1:iR3fYXUjHCR97qWS8ch1y9zPNsgXThGwjKPrYfqMPks= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a/go.mod h1:9qCChq59u/eW8im404Q2WWTrnBUQKjpNYKMbU4M7EFU= -github.com/golangci/golangci-lint v1.26.0 h1:CLLGRSA9BLMiNvsWPXHioYAdfIx9tkgdVWyA6bIdYCo= -github.com/golangci/golangci-lint v1.26.0/go.mod h1:tefbO6RcigFzvTnDC+Y51kntVGgkuCAVsC+mnfbPruc= +github.com/golangci/golangci-lint v1.29.0 h1:0ufaO3l2R1R712cFC+KT3TtwO/IOcsloKZBavRtzrBk= +github.com/golangci/golangci-lint v1.29.0/go.mod h1:Iq2GFBB9OoolSDWD81m0iJ2MR4MwDVbi4eC93fO7wh0= github.com/golangci/ineffassign v0.0.0-20190609212857-42439a7714cc h1:gLLhTLMk2/SutryVJ6D4VZCU3CUqr8YloG7FPIBWFpI= github.com/golangci/ineffassign v0.0.0-20190609212857-42439a7714cc/go.mod h1:e5tpTHCfVze+7EpLEozzMB3eafxo2KT5veNg1k6byQU= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0 h1:MfyDlzVjl1hoaPzPD4Gpb/QgoRfSBR0jdhwGyAWwMSA= @@ -190,16 +246,24 @@ github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4 h1:zwtduBRr5SSW github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4/go.mod h1:Izgrg8RkN3rCIMLGE9CyYmU9pY2Jer6DgANEnZ/L/cQ= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0 h1:pMen7vLs8nvgEYhywH3KDWJIJTeEr2ULsVWHWYHQyBs= +github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= @@ -207,95 +271,121 @@ github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/gookit/color v1.1.7 h1:WR5I/mhSHzemW2DzG54hTsUb7OzaREvkcmUG4/WST4Q= github.com/gookit/color v1.1.7/go.mod h1:R3ogXq2B9rTbXoSHJ1HyUVAZ3poOJHpd9nQmyGZsfvQ= +github.com/gookit/color v1.2.4 h1:xOYBan3Fwlrqj1M1UN2TlHOCRiek3bGzWf/vPnJ1roE= +github.com/gookit/color v1.2.4/go.mod h1:AhIE+pS6D4Ql0SQWbBeXPHw7gY0/sjHoA4s/n1KB7xg= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/gostaticanalysis/analysisutil v0.0.0-20190318220348-4088753ea4d3 h1:JVnpOZS+qxli+rgVl98ILOXVNbW+kb5wcxeGx8ShUIw= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gostaticanalysis/analysisutil v0.0.0-20190318220348-4088753ea4d3/go.mod h1:eEOZF4jCKGi+aprrirO9e7WKB3beBRtWgqGunKl6pKE= +github.com/gostaticanalysis/analysisutil v0.0.3 h1:iwp+5/UAyzQSFgQ4uR2sni99sJ8Eo9DEacKWM5pekIg= +github.com/gostaticanalysis/analysisutil v0.0.3/go.mod h1:eEOZF4jCKGi+aprrirO9e7WKB3beBRtWgqGunKl6pKE= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= -github.com/hashicorp/aws-sdk-go-base v0.4.0 h1:zH9hNUdsS+2G0zJaU85ul8D59BGnZBaKM+KMNPAHGwk= -github.com/hashicorp/aws-sdk-go-base v0.4.0/go.mod h1:eRhlz3c4nhqxFZJAahJEFL7gh6Jyj5rQmQc7F9eHFyQ= +github.com/hashicorp/aws-sdk-go-base v0.5.0 h1:fk7ID0v3PWL/KNL8FvkBPu8Sm93EPUCCmtZCiTXLySE= +github.com/hashicorp/aws-sdk-go-base v0.5.0/go.mod h1:2fRjWDv3jJBeN6mVWFHV6hFTNeFBx2gpDLQaZNxUVAY= +github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= +github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= +github.com/hashicorp/go-checkpoint v0.5.0 h1:MFYpPZCnQqQTE18jFwSII6eUQrD/oxMFp3mlgcqk5mU= +github.com/hashicorp/go-checkpoint v0.5.0/go.mod h1:7nfLNL10NsxqO4iWuW6tWW0HjZuDrwkBuEQsVcpCOgg= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-getter v1.4.0 h1:ENHNi8494porjD0ZhIrjlAHnveSFhY7hvOJrV/fsKkw= +github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320 h1:1/D3zfFHttUKaCaGKZ/dR2roBXv0vKbSCnssIldfQdI= +github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320/go.mod h1:EiZBMaudVLy8fmjf9Npq1dq9RalhveqZG5w/yz3mHWs= github.com/hashicorp/go-getter v1.4.0/go.mod h1:7qxyCd8rBfcShwsvxgIguu4KbS3l8bUCwg2Umn7RjeY= +github.com/hashicorp/go-getter v1.4.2-0.20200106182914-9813cbd4eb02 h1:l1KB3bHVdvegcIf5upQ5mjcHjs2qsWnKh4Yr9xgIuu8= +github.com/hashicorp/go-getter v1.4.2-0.20200106182914-9813cbd4eb02/go.mod h1:7qxyCd8rBfcShwsvxgIguu4KbS3l8bUCwg2Umn7RjeY= github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= -github.com/hashicorp/go-hclog v0.9.2 h1:CG6TE5H9/JXsFWJCfoIVpKFIkFe6ysEuHirp4DxCsHI= github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= github.com/hashicorp/go-hclog v0.10.0 h1:b86HUuA126IcSHyC55WjPo7KtCOVeTCKIjr+3lBhPxI= github.com/hashicorp/go-hclog v0.10.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= -github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= +github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= -github.com/hashicorp/go-plugin v1.0.1 h1:4OtAfUGbnKC6yS48p0CtMX2oFYtzFZVv6rok3cRWgnE= +github.com/hashicorp/go-multierror v1.1.0 h1:B9UzwGQJehnUY1yNrnwREHc3fGbC2xefo8g4TbElacI= +github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= github.com/hashicorp/go-plugin v1.0.1/go.mod h1:++UyYGoz3o5w9ZzAdZxtQKrWWP+iqPBn3cQptSMzBuY= +github.com/hashicorp/go-plugin v1.3.0 h1:4d/wJojzvHV1I4i/rrjVaeuyxWrLzDE1mDCyDy8fXS8= +github.com/hashicorp/go-plugin v1.3.0/go.mod h1:F9eH4LrE/ZsRdbwhfjs9k9HoDUwAHnYtXdgmf1AVNs0= +github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo= github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= +github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= +github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.1 h1:fv1ep09latC32wFoVwnqcnKJGnMSdBanPczbHAYm1BE= github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-version v1.1.0 h1:bPIoEKD27tNdebFGGxxYwcL4nepeY4j1QP23PFRGzg0= github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.2.0 h1:3vNe/fWF5CBgRIguda1meWhsZHy3m8gCJ5wx+dIzX/E= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/golang-lru v0.5.0 h1:CL2msUPvZTLb5O648aiLNJw3hnBxN2+1Jq8rCOH9wdo= +github.com/hashicorp/go-version v1.2.1 h1:zEfKbn2+PDgroKdiOzqiE8rsmLqU2uwi5PB5pBJ3TkI= +github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f h1:UdxlrJz4JOnY8W+DbLISwf2B8WXEolNRA8BGCwI9jws= github.com/hashicorp/hcl v0.0.0-20170504190234-a4b07c25de5f/go.mod h1:oZtUIOe8dh44I2q6ScRibXws4Ajl+d+nod3AaR9vL5w= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hashicorp/hcl/v2 v2.0.0 h1:efQznTz+ydmQXq3BOnRa3AXzvCeTq1P4dKj/z5GLlY8= github.com/hashicorp/hcl/v2 v2.0.0/go.mod h1:oVVDG71tEinNGYCxinCYadcmKU9bglqW9pV3txagJ90= github.com/hashicorp/hcl/v2 v2.3.0 h1:iRly8YaMwTBAKhn1Ybk7VSdzbnopghktCD031P8ggUE= github.com/hashicorp/hcl/v2 v2.3.0/go.mod h1:d+FwDBbOLvpAM3Z6J7gPj/VoAGkNe/gm352ZhjJ/Zv8= github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= +github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= +github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= +github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/hashicorp/terraform-config-inspect v0.0.0-20191115094559-17f92b0546e8 h1:+RyjwU+Gnd/aTJBPZVDNm903eXVjjqhbaR4Ypx3xYyY= github.com/hashicorp/terraform-config-inspect v0.0.0-20191115094559-17f92b0546e8/go.mod h1:p+ivJws3dpqbp1iP84+npOyAmTTOLMgCzrXd3GSdn/A= -github.com/hashicorp/terraform-json v0.3.1 h1:vRiOLck4YX4UqzljVhdQKsVLixX4L+Pgnm/q+xu6QvE= -github.com/hashicorp/terraform-json v0.3.1/go.mod h1:MdwQStcJb00ht55L/2YH0ypAO9RNtczJ1MaUlf+gJcg= -github.com/hashicorp/terraform-json v0.4.0 h1:KNh29iNxozP5adfUFBJ4/fWd0Cu3taGgjHB38JYqOF4= +github.com/hashicorp/terraform-exec v0.3.0 h1:5WLBsnv9BoEUGlHJZETROZZxw+qO3/TFQEh6JMP2uaY= +github.com/hashicorp/terraform-exec v0.3.0/go.mod h1:yKWvMPtkTaHpeAmllw+1qdHZ7E5u+pAZ+x8e2jQF6gM= github.com/hashicorp/terraform-json v0.4.0/go.mod h1:eAbqb4w0pSlRmdvl8fOyHAi/+8jnkVYN28gJkSJrLhU= -github.com/hashicorp/terraform-plugin-sdk v1.7.0 h1:B//oq0ZORG+EkVrIJy0uPGSonvmXqxSzXe8+GhknoW0= -github.com/hashicorp/terraform-plugin-sdk v1.7.0/go.mod h1:OjgQmey5VxnPej/buEhe+YqKm0KNvV3QqU4hkqHqPCY= +github.com/hashicorp/terraform-json v0.5.0 h1:7TV3/F3y7QVSuN4r9BEXqnWqrAyeOtON8f0wvREtyzs= +github.com/hashicorp/terraform-json v0.5.0/go.mod h1:eAbqb4w0pSlRmdvl8fOyHAi/+8jnkVYN28gJkSJrLhU= github.com/hashicorp/terraform-plugin-sdk v1.9.0 h1:WBHHIX/RgF6/lbfMCzx0qKl96BbQy3bexWFvDqt1bhE= github.com/hashicorp/terraform-plugin-sdk v1.9.0/go.mod h1:C/AXwmDHqbc3h6URiHpIsVKrwV4PS0Sh0+VTaeEkShw= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.0.0 h1:jPPqctLDg75CilV3IpypAz6on3MSMOiUMzXNz+Xex6E= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.0.0/go.mod h1:xOf85UtHJ0/9/EF3eKgZFlJ6feN8sDtjQRWRHhimCUw= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.0.1 h1:qG6EdnW2UrftQI4mBdIsWP4YWqYJXynZtl0shQYuU78= +github.com/hashicorp/terraform-plugin-sdk/v2 v2.0.1/go.mod h1:BRz6UtYmksQJU0eMfahQR8fcJf8tIe77gn7YVm6rGD4= github.com/hashicorp/terraform-plugin-test v1.2.0 h1:AWFdqyfnOj04sxTdaAF57QqvW7XXrT8PseUHkbKsE8I= github.com/hashicorp/terraform-plugin-test v1.2.0/go.mod h1:QIJHYz8j+xJtdtLrFTlzQVC0ocr3rf/OjIpgZLK56Hs= +github.com/hashicorp/terraform-plugin-test/v2 v2.0.0-20200724200815-faa9931ac59e h1:Q8lNGrk3SVdXEbLuUJD03jghIjykJT9pu1aReKgb858= +github.com/hashicorp/terraform-plugin-test/v2 v2.0.0-20200724200815-faa9931ac59e/go.mod h1:C6VALgUlvaif+PnHyRGKWPTdQkMJK4NQ20VJolxZLI0= +github.com/hashicorp/terraform-plugin-test/v2 v2.0.0 h1:fYGV3nZvs8KFGKuY2NPAJDMNfVSDHo+U2FGFl3bPv1s= +github.com/hashicorp/terraform-plugin-test/v2 v2.0.0/go.mod h1:C6VALgUlvaif+PnHyRGKWPTdQkMJK4NQ20VJolxZLI0= github.com/hashicorp/terraform-svchost v0.0.0-20191011084731-65d371908596 h1:hjyO2JsNZUKT1ym+FAdlBEkGPevazYsmVgIMw7dVELg= github.com/hashicorp/terraform-svchost v0.0.0-20191011084731-65d371908596/go.mod h1:kNDNcF7sN4DocDLBkQYz73HGKwN1ANB1blq4lIYLYvg= -github.com/hashicorp/vault v0.10.4 h1:4x0lHxui/ZRp/B3E0Auv1QNBJpzETqHR2kQD3mHSBJU= -github.com/hashicorp/vault v0.10.4/go.mod h1:KfSyffbKxoVyspOdlaGVjIuwLobi07qD1bAbosPMpP0= -github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb h1:b5rjCoWHc7eqmAS4/qyk21ZsHyb6Mxv/jykxvNTkU4M= github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d h1:kJCB4vdITiW1eC1vq2e6IsrXKrZit1bv/TDYFGMp4BQ= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jen20/awspolicyequivalence v1.1.0 h1:cn37D6o0lXLwqx2neCokGfaB3LLNSo5CrLMLGjY609g= github.com/jen20/awspolicyequivalence v1.1.0/go.mod h1:PV1fS2xyHhCLp83vbgSMFr2drM4GzG61wkz+k4pOG3E= +github.com/jhump/protoreflect v1.6.0 h1:h5jfMVslIg6l29nsMs0D8Wj17RDVdNYti0vDN/PZZoE= +github.com/jhump/protoreflect v1.6.0/go.mod h1:eaTn3RZAmMBcV0fifFvlm6VHNz3wSkYyXYWUh7ymB74= github.com/jingyugao/rowserrcheck v0.0.0-20191204022205-72ab7603b68a h1:GmsqmapfzSJkm28dhRoHz2tLRbJmqhU86IPgBtN3mmk= github.com/jingyugao/rowserrcheck v0.0.0-20191204022205-72ab7603b68a/go.mod h1:xRskid8CManxVta/ALEhJha/pweKBaVG6fWgc0yH25s= github.com/jirfag/go-printf-func-name v0.0.0-20191110105641-45db9963cdd3 h1:jNYPNLe3d8smommaoQlK7LOA5ESyUJJ+Wf79ZtA7Vp4= github.com/jirfag/go-printf-func-name v0.0.0-20191110105641-45db9963cdd3/go.mod h1:HEWGJkRDzjJY2sqdDwxccsGicWEf9BQOZsq2tV+xzM0= github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.3.0 h1:OS12ieG61fsCg5+qLJ+SsW9NicxNkg3b25OyT2yCeUc= github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= +github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks= github.com/jmoiron/sqlx v1.2.1-0.20190826204134-d7d95172beb5/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1 h1:6QPYqodiu3GuPL+7mfx+NwDdp2eTkp9IfEUpgAwUN0o= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= @@ -306,29 +396,25 @@ github.com/keybase/go-crypto v0.0.0-20161004153544-93f5b35093ba/go.mod h1:ghbZsc github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.4.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= -github.com/klauspost/cpuid v0.0.0-20180405133222-e7e905edc00e/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= -github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= -github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= +github.com/klauspost/compress v1.10.4/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= +github.com/klauspost/compress v1.10.5/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348 h1:MtvEpTB6LX3vkb4ax0b5D2DHbNAUsen0Gx5wZoq3lV4= github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/kyoh86/exportloopref v0.1.7 h1:u+iHuTbkbTS2D/JP7fCuZDo/t3rBVGo3Hf58Rc+lQVY= +github.com/kyoh86/exportloopref v0.1.7/go.mod h1:h1rDl2Kdj97+Kwh4gdz3ujE7XHmH51Q0lUiZ1z4NLj8= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= -github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= @@ -336,50 +422,53 @@ github.com/maratori/testpackage v1.0.1 h1:QtJ5ZjqapShm0w5DosRjg0PRlSdAdlx+W6cCKo github.com/maratori/testpackage v1.0.1/go.mod h1:ddKdw+XG0Phzhx8BFDTKgpWP4i7MpApTE5fXSKAqwDU= github.com/matoous/godox v0.0.0-20190911065817-5d6d842e92eb h1:RHba4YImhrUVQDHUCe2BNSOz4tVy2yGyXhvYDvxGgeE= github.com/matoous/godox v0.0.0-20190911065817-5d6d842e92eb/go.mod h1:1BELzlh859Sh1c6+90blK8lbYy0kwQf1bYlBhBysy1s= -github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= -github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw= +github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW10= github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= +github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= +github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mitchellh/cli v1.0.0 h1:iGBIsUe3+HZ/AD/Vd7DErOt5sU9fa8Uj7A2s1aggv1Y= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ= github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw= github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ= github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= -github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-ps v0.0.0-20190716172923-621e5597135b/go.mod h1:r1VsdOzOPt1ZSrGZWFoNhsAedKnEd6r9Np1+5blZCWk= -github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77 h1:7GoSOOW2jpsfkntVKaS2rAr1TJqfcxotyaUcuxoZSzg= +github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg= github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/go-testing-interface v1.0.0 h1:fzU/JVNcaqHQEcVFAKeR41fkiLdIPrefOvVG1VZ96U0= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/go-testing-interface v1.0.4 h1:ZU1VNC02qyufSZsjjs7+khruk2fKvbQ3TwRV/IBCeFA= +github.com/mitchellh/go-testing-interface v1.0.4/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/go-wordwrap v1.0.0 h1:6GlHJ/LTGMrIJbwgdqdl2eEH8o+Exx/0m8ir9Gns0u4= github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= -github.com/mitchellh/mapstructure v1.0.0 h1:vVpGvMXJPqSDh2VYHF7gsfQj8Ncx+Xw5Y1KHeTRY+7I= +github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= +github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= +github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.0.0/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.1 h1:FVzMWA5RllMAKIdUSC8mdWo3XtwoecrH79BY70sEEpE= github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/mozilla/tls-observatory v0.0.0-20200220173314-aae45faa4006/go.mod h1:SrKMQvPiws7F7iqYp8/TX+IhxCYhzr6N/1yb8cwHsGk= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mozilla/tls-observatory v0.0.0-20200317151703-4fa42e1c2dee/go.mod h1:SrKMQvPiws7F7iqYp8/TX+IhxCYhzr6N/1yb8cwHsGk= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/nakabonne/nestif v0.3.0 h1:+yOViDGhg8ygGrmII72nV9B/zGxY188TYpfolntsaPw= github.com/nakabonne/nestif v0.3.0/go.mod h1:dI314BppzXjJ4HsCnbo7XzrJHPszZsjnk5wEBSYHI2c= @@ -387,25 +476,26 @@ github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d h1:AREM5mwr4u1 github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d/go.mod h1:o96djdrsSGy3AWPyBgZMAGfxZNfgntdJG+11KU4QvbU= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nishanths/exhaustive v0.0.0-20200708172631-8866003e3856 h1:W3KBC2LFyfgd+wNudlfgCCsTo4q97MeNWrfz8/wSdSc= +github.com/nishanths/exhaustive v0.0.0-20200708172631-8866003e3856/go.mod h1:wBEpHwM2OdmeNpdCvRPUlkEbBuaFmcK4Wv8Q7FuGW3c= github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= -github.com/onsi/ginkgo v1.6.0 h1:Ix8l273rp3QzYgXSR+c8d1fTG7UPgYkOSELPhiY/YGw= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU= github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.9.0 h1:R1uwffexN6Pr340GtYRIdZmAiN4J+iw6WG4wog1DUXg= github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA= +github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d h1:CdDQnGF8Nq9ocOS/xlSptM1N3BbrA6/kmaep5ggwaIA= github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d/go.mod h1:3OzsM7FXDQlpCiw2j81fOmAwQLnZnLGXVKUzeKQXIAw= github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= -github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -427,33 +517,46 @@ github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/quasilyte/go-consistent v0.0.0-20190521200055-c6f3937de18c/go.mod h1:5STLWrekHfjyYwxBRVRXNOSewLJ3PWfDJd1VyTS21fI= +github.com/quasilyte/go-ruleguard v0.1.2-0.20200318202121-b00d7a75d3d8 h1:DvnesvLtRPQOvaUbfXfh0tpMHg29by0H7F2U+QIkSu8= +github.com/quasilyte/go-ruleguard v0.1.2-0.20200318202121-b00d7a75d3d8/go.mod h1:CGFX09Ci3pq9QZdj86B+VGIdNj4VyCo2iPOGS9esB/k= +github.com/quasilyte/regex/syntax v0.0.0-20200407221936-30656e2c4a95 h1:L8QM9bvf68pVdQ3bCFZMDmnt9yqcMBro1pC7F+IPYMY= +github.com/quasilyte/regex/syntax v0.0.0-20200407221936-30656e2c4a95/go.mod h1:rlzQ04UMyJXu/aOvhd8qT+hvDrFpiwqp8MRXDY9szc0= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= -github.com/ryancurrah/gomodguard v1.0.4 h1:oCreMAt9GuFXDe9jW4HBpc3GjdX3R/sUEcLAGh1zPx8= -github.com/ryancurrah/gomodguard v1.0.4/go.mod h1:9T/Cfuxs5StfsocWr4WzDL36HqnX0fVb9d5fSEaLhoE= -github.com/securego/gosec v0.0.0-20200316084457-7da9f46445fd h1:qB+l4fYZsH78xORC1aqVS0zNmgkQp4rkj2rvfxQMtzc= -github.com/securego/gosec v0.0.0-20200316084457-7da9f46445fd/go.mod h1:NurAFZsWJAEZjogSwdVPlHkOZB3DOAU7gsPP8VFZCHc= +github.com/rogpeppe/go-internal v1.6.0/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/ryancurrah/gomodguard v1.1.0 h1:DWbye9KyMgytn8uYpuHkwf0RHqAYO6Ay/D0TbCpPtVU= +github.com/ryancurrah/gomodguard v1.1.0/go.mod h1:4O8tr7hBODaGE6VIhfJDHcwzh5GUccKSJBU0UMXJFVM= +github.com/ryanrolds/sqlclosecheck v0.3.0 h1:AZx+Bixh8zdUBxUA1NxbxVAS78vTPq4rCb8OUZI9xFw= +github.com/ryanrolds/sqlclosecheck v0.3.0/go.mod h1:1gREqxyTGR3lVtpngyFo3hZAgk0KCtEdgEkHwDbigdA= +github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/securego/gosec/v2 v2.3.0 h1:y/9mCF2WPDbSDpL3QDWZD3HHGrSYw0QSHnCqTfs4JPE= +github.com/securego/gosec/v2 v2.3.0/go.mod h1:UzeVyUXbxukhLeHKV3VVqo7HdoQR9MrRfFmZYotn8ME= github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c h1:W65qqJCIOVP4jpqPQ0YvHYKwcMEMVWIzWC5iNQQfBTU= +github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c/go.mod h1:/PevMnwAxekIXwN8qQyfc5gl2NlkB3CQlkizAbOkeBs= github.com/shirou/gopsutil v0.0.0-20190901111213-e4ec7b275ada/go.mod h1:WWnYX4lzhCH5h/3YBfyVA3VbLYjlMZZAQcW9ojMexNc= github.com/shirou/w32 v0.0.0-20160930032740-bb4de0191aa4/go.mod h1:qsXQc7+bwAM3Q1u/4XEfrquwF8Lw7D7y5cD8CuHnfIc= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e h1:MZM7FHLqUHYI0Y/mQAt3d2aYa0SiNms/hFqC9qJYolM= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041 h1:llrF3Fs4018ePo4+G/HV/uQUqEI1HMDjCeOf2V6puPc= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= -github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= -github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= -github.com/sourcegraph/go-diff v0.5.1 h1:gO6i5zugwzo1RVTvgvfwCOSVegNuvnNi6bAD1QCmkHs= -github.com/sourcegraph/go-diff v0.5.1/go.mod h1:j2dHj3m8aZgQO8lMTcTnBcXkRRRqi34cd2MNlA9u1mE= +github.com/sonatard/noctx v0.0.1 h1:VC1Qhl6Oxx9vvWo3UDgrGXYCeKCe3Wbw7qAWL6FrmTY= +github.com/sonatard/noctx v0.0.1/go.mod h1:9D2D/EoULe8Yy2joDHJj7bv3sZoq9AaSb8B4lqBjiZI= +github.com/sourcegraph/go-diff v0.5.3 h1:lhIKJ2nXLZZ+AfbHpYxTn0pXpNTTui0DX7DO3xeb1Zs= +github.com/sourcegraph/go-diff v0.5.3/go.mod h1:v9JDtjCE4HHHCZGId75rg8gkKKa98RVjBcBGsVmMmak= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc= @@ -461,35 +564,33 @@ github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTd github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/cobra v0.0.5 h1:f0B+LkLX6DtmRH1isoNA9VTtNUK9K8xYd28JNNfOv/s= -github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= +github.com/spf13/cobra v1.0.0 h1:6m/oheQuQ13N9ks4hubMG6BnvwOeaJrqSPLahSnczz8= +github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= -github.com/spf13/viper v1.6.1 h1:VPZzIkznI1YhVMRi6vNFLHSwhnhReBfgTxIPccpfdZk= -github.com/spf13/viper v1.6.1/go.mod h1:t3iDnF5Jlj76alVNuyFBk5oUMCvsrkbvZK0WQdfDi5k= +github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= +github.com/spf13/viper v1.7.0 h1:xVKxvI7ouOI5I+U9s2eeiUfMaWBVoXA3AWskkrqK0VM= +github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48= -github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tdakkota/asciicheck v0.0.0-20200416190851-d7f85be797a2 h1:Xr9gkxfOP0KQWXKNqmwe8vEeSUiUj4Rlee9CMVX2ZUQ= github.com/tdakkota/asciicheck v0.0.0-20200416190851-d7f85be797a2/go.mod h1:yHp0ai0Z9gUljN3o0xMhYJnH/IcvkdTBOX2fmJ93JEM= -github.com/tetafro/godot v0.3.3 h1:uJjg8N+Ee10rAnaqJGet1WeI0YW4fiX9pKbwqnsqH6k= -github.com/tetafro/godot v0.3.3/go.mod h1:pT6/T8+h6//L/LwQcFc4C0xpfy1euZwzS1sHdrFCms0= +github.com/tetafro/godot v0.4.2 h1:Dib7un+rYJFUi8vN0Bk6EHheKy6fv6ZzFURHw75g6m8= +github.com/tetafro/godot v0.4.2/go.mod h1:/7NLHhv08H1+8DNj0MElpAACw1ajsCuf3TKNQxA5S+0= github.com/timakin/bodyclose v0.0.0-20190930140734-f7f2e9bca95e h1:RumXZ56IrCj4CL+g1b9OL/oH0QnsF976bC8xQFYUD5Q= github.com/timakin/bodyclose v0.0.0-20190930140734-f7f2e9bca95e/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= @@ -497,8 +598,9 @@ github.com/tommy-muehle/go-mnd v1.3.1-0.20200224220436-e6f9a994e8fa h1:RC4maTWLK github.com/tommy-muehle/go-mnd v1.3.1-0.20200224220436-e6f9a994e8fa/go.mod h1:dSUh0FtTP8VhvkL1S+gUR1OKd9ZnSaozuI6r3m6wOig= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= -github.com/ulikunitz/xz v0.5.5 h1:pFrO0lVpTBXLpYw+pnLj6TbvHuyjXMfjGeCwSqCVwok= github.com/ulikunitz/xz v0.5.5/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= +github.com/ulikunitz/xz v0.5.7 h1:YvTNdFzX6+W5m9msiYg/zpkSURPPtOlzbqYjrFn7Yt4= +github.com/ulikunitz/xz v0.5.7/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= github.com/ultraware/funlen v0.0.2 h1:Av96YVBwwNSe4MLR7iI/BIa3VyI7/djnto/pK3Uxbdo= github.com/ultraware/funlen v0.0.2/go.mod h1:Dp4UiAus7Wdb9KUZsYWZEWiRzGuM2kXM1lPbfaF6xhA= github.com/ultraware/whitespace v0.0.4 h1:If7Va4cM03mpgrNH9k49/VOicWpGoG70XPBFFODYDsg= @@ -506,8 +608,8 @@ github.com/ultraware/whitespace v0.0.4/go.mod h1:aVMh/gQve5Maj9hQ/hg+F75lr/X5A89 github.com/uudashr/gocognit v1.0.1 h1:MoG2fZ0b/Eo7NXoIwCVFLG5JED3qgQz5/NEE+rOsjPs= github.com/uudashr/gocognit v1.0.1/go.mod h1:j44Ayx2KW4+oB6SWMv8KsmHzZrOInQav7D3cQMJ5JUM= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasthttp v1.2.0/go.mod h1:4vX61m6KN+xDduDNwXrhIAVZaZaZiQ1luJk8LWSxF3s= -github.com/valyala/quicktemplate v1.2.0/go.mod h1:EH+4AkTd43SvgIbQHYu59/cJyxDoOVRUAfrukLPuGJ4= +github.com/valyala/fasthttp v1.12.0/go.mod h1:229t1eWu9UXTPmoUkbpN/fctKPBY4IJoFXQnxHGXy6E= +github.com/valyala/quicktemplate v1.5.1/go.mod h1:v7yYWpBEiutDyNfVaph6oC/yKwejzVyTX/2cwwHxyok= github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio= github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= github.com/vmihailenco/msgpack v4.0.1+incompatible h1:RMF1enSPeKTlXrXdOcqjFUElywVZjjC6pqse21bKbEU= @@ -516,9 +618,8 @@ github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/zclconf/go-cty v0.0.0-20190430221426-d36a6f0dbffd/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/zclconf/go-cty v1.0.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= -github.com/zclconf/go-cty v1.1.0 h1:uJwc9HiBOCpoKIObTQaLR+tsEXx1HBHnOsOOpcdhZgw= github.com/zclconf/go-cty v1.1.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= github.com/zclconf/go-cty v1.2.0/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= github.com/zclconf/go-cty v1.2.1 h1:vGMsygfmeCl4Xb6OA5U5XVAaQZ69FvoG7X2jUtQujb8= @@ -527,45 +628,67 @@ github.com/zclconf/go-cty-yaml v1.0.1 h1:up11wlgAaDvlAGENcFDnZgkn0qUJurso7k6EpUR github.com/zclconf/go-cty-yaml v1.0.1/go.mod h1:IP3Ylp0wQpYm50IHK8OZWKMu6sPJIUgKa8XhiVHura0= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0 h1:C9hSCOW830chIVkdja34wa6Ky+IzWllkUinR+BtRZd4= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.4 h1:LYy1Hy3MJdrCdMwwzxA/dRok4ejH+RwNGbuoD9fCjto= +go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734 h1:p/H982KKEjUnLJkM3tt/LemDnOc1GiZL5FCVlORJ5zo= golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b h1:Wh+f8QHJXR411sJR8/vRBTZ7YapZaRvUcLFFJhusH0k= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee h1:WG0RUwxtNT4qqaXX3DPA8zHFNm/D9xaBpxzHt1WcA/E= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180530234432-1e491301e022/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180911220305-26e67e76b6c3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd h1:HuTn7WObtcDo9uEEU7rEqL0jYthdXAmZ6PP+meazmaU= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -573,34 +696,43 @@ golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190923162816-aa69164e4478 h1:l5EDrHhldLYb3ZRHDUhXF7Om7MvYXnkV9/iQNo1lX6g= -golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191009170851-d66e71096ffb h1:TR699M2v0qoKTOHxeLgp6zPqaQNs74f01a/ob9W0qko= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191009170851-d66e71096ffb/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2 h1:CCH4IOTTfewWjGOlSp+zGcjutRKlBEZQ6wTn8ozI/nI= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200301022130-244492dfa37a h1:GuSPYbZzB5/dcLNCwLQLsg3obCJtX9IJhpXkvY7kzk0= golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200707034311-ab3426394381 h1:VXak5I6aEWmAXeQjA+QSZzlgNrpq9mjcfDemuexIKsU= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421 h1:Wo7BWFiOk0QRFMLYMqJGFMd9CgUAcGx7V+qEg/h5IBI= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -611,27 +743,40 @@ golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190502175342-a43fa875dd82 h1:vsphBvatvfbhlb4PO1BYSr9dzugGxJ/SQHoNufZJq1w= golang.org/x/sys v0.0.0-20190502175342-a43fa875dd82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191008105621-543471e840be h1:QAcqgptGM8IQBC9K/RC4o+O9YmqEm0diQn9QmZw/0mU= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 h1:uYVVQ9WP/Ds2ROhcaGPeIdVq0RIXVLwsHlnvJ+cT1So= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121 h1:rITEj+UZHYC927n8GT97eC3zrpzXdb/voyeOuVKS46o= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 h1:z99zHgr7hKfrUcX/KsoJk5FJfjTceCKIp96+biqP4To= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/time v0.0.0-20181108054448-85acf8d2951c h1:fqgJT0MGcGpPgpWU7VRdRjuArfcOvC4AoJmILihzhDg= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 h1:SvFZT6jyqRaOeXpc5h/JSfZenJ2O330aBsf7JfSUXmQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -646,72 +791,141 @@ golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190322203728-c1a832b0ad89/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262 h1:qsl9y/CJx34tuA7QCPNp86JNJe4spst6Ff8MjvPUdPg= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190521203540-521d6ed310dd h1:7E3PabyysDSEjnaANKBgums/hyvMI/HoHQ50qZEzTrg= golang.org/x/tools v0.0.0-20190521203540-521d6ed310dd/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190719005602-e377ae9d6386/go.mod h1:jcCCGcm9btYwXyDqrUWc6MKQKKGJCWEQ3AfLSRIbEuI= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190910044552-dd2b5c81c578/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117220505-0cba7a3a9ee9/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200214201135-548b770e2dfa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200216192241-b320d3a0f5a2 h1:0sfSpGSa544Fwnbot3Oxq/U6SXqjty6Jy/3wRhVS7ig= -golang.org/x/tools v0.0.0-20200216192241-b320d3a0f5a2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200228224639-71482053b885/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200321224714-0d839f3cf2ed/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= golang.org/x/tools v0.0.0-20200324003944-a576cf524670/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200331202046-9d5940d49312/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200414032229-332987a829c3/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200422022333-3d57cf2e726e h1:3Dzrrxi54Io7Aoyb0PYLsI47K2TxkRQg+cqUn+m04do= golang.org/x/tools v0.0.0-20200422022333-3d57cf2e726e/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200519015757-0d0afa43d58a/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200625211823-6506e20df31f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200626171337-aa94e735be7f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200710042808-f1c4188a97a1/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed h1:+qzWo37K31KxduIYaBeMqJ8MUOyTayOQKpH9aDPLMSY= +golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898 h1:/atklqdjdhuosWIl6AIbOeHJjicWYPqR9bpxqxYG2pA= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0 h1:jbyannxz0XFD3zdjgrSUsaJbgpH4eTrkdhRChkHPfO8= google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.29.0 h1:BaiDisFir8O4IJxvAabCGGkQ6yCJegNQqSVoYUNAnbk= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1 h1:QzqyMA1tlu6CgqCDUtU9V+ZKhLFT2dkJuANu5QaxI3I= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6 h1:lMO5rYAqUxkmaj76jAkRUvt5JZgFymx/+Q5Mzfivuhc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20170818010345-ee236bd376b0/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19 h1:Lj2SnHtxkRGJDqnGaSjo+CCdIieEnwVazbOXILwQemk= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20200310143817-43be25429f5a h1:lRlI5zu6AFy3iU/F8YWyNrAmn/tPCnhiTxfwhWb76eU= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200310143817-43be25429f5a/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200711021454-869866162049 h1:YFTFpQhgvrLrmxtiIncJxFXeCyq84ixuKWVCaCAi9Oc= +google.golang.org/genproto v0.0.0-20200711021454-869866162049/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/grpc v1.8.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.0 h1:G+97AoqBnmZIT91cLG/EkCoK9NSelj64P8bOHHNmGn0= google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.23.0 h1:AzbTB6ux+okLTzP8Ru1Xs41C303zdcfEht7MQnYJt5A= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.1 h1:zvIju4sqAGvwKspUQOhwnpcqSbzi7/H6QomNNjTL4sk= google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0 h1:M5a8xTlYTxwMn5ZFkwhRabsygDY5G8TYLyQDBxJNAxE= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -725,22 +939,25 @@ gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= -gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo= gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4 h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +mvdan.cc/gofumpt v0.0.0-20200709182408-4fd085cb6d5f h1:gi7cb8HTDZ6q8VqsUpkdoFi3vxwHMneQ6+Q5Ap5hjPE= +mvdan.cc/gofumpt v0.0.0-20200709182408-4fd085cb6d5f/go.mod h1:9VQ397fNXEnF84t90W4r4TRCQK+pg9f8ugVfyj+S26w= mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed h1:WX1yoOaKQfddO/mLzdV4wptyWgoH/6hwLs7QHTixo0I= mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed/go.mod h1:Xkxe497xwlCKkIaQYRfC7CSLworTXY9RMqwhhCm+8Nc= mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b h1:DxJ5nJdkhDlLok9K6qO+5290kphDJbHOQO1DFFFTeBo= @@ -748,5 +965,7 @@ mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b/go.mod h1:2odslEg/xrtNQqCYg2/jC mvdan.cc/unparam v0.0.0-20190720180237-d51796306d8f h1:Cq7MalBHYACRd6EesksG1Q8EoIAKOsiZviGKbOLIej4= mvdan.cc/unparam v0.0.0-20190720180237-d51796306d8f/go.mod h1:4G1h5nDURzA3bwVMZIVpwbkw+04kSxk3rAtzlimaUJw= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4 h1:JPJh2pk3+X4lXAkZIk2RuE/7/FoK9maXw+TNPJhVS/c= sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= diff --git a/infrastructure/repository/labels-service.tf b/infrastructure/repository/labels-service.tf index 079baf5d5cb..74182d9f0ad 100644 --- a/infrastructure/repository/labels-service.tf +++ b/infrastructure/repository/labels-service.tf @@ -38,6 +38,7 @@ variable "service_labels" { "cloudwatch", "cloudwatchevents", "cloudwatchlogs", + "codeartifact", "codebuild", "codecommit", "codedeploy", @@ -45,6 +46,7 @@ variable "service_labels" { "codegurureviewer", "codepipeline", "codestar", + "codestarconnections", "codestarnotifications", "cognito", "comprehend", @@ -53,11 +55,13 @@ variable "service_labels" { "configservice", "connect", "costandusagereportservice", + "costexplorer", "databasemigrationservice", "dataexchange", "datapipeline", "datasync", "dax", + "detective", "devicefarm", "directconnect", "directoryservice", @@ -98,6 +102,7 @@ variable "service_labels" { "iotanalytics", "iotevents", "iotsecuretunneling", + "iotsitewise", "iotthingsgraph", "kafka", "kendra", @@ -171,8 +176,11 @@ variable "service_labels" { "sts", "support", "swf", + "synthetics", + "textract", "transcribeservice", "transfer", + "translate", "waf", "wafv2", "workdocs", diff --git a/infrastructure/repository/labels-workflow.tf b/infrastructure/repository/labels-workflow.tf index 8a470950147..ce5108359e6 100644 --- a/infrastructure/repository/labels-workflow.tf +++ b/infrastructure/repository/labels-workflow.tf @@ -1,8 +1,10 @@ variable "workflow_labels" { default = { + "examples" = "fef2c0", "hacktoberfest" = "2c0fad", "needs-triage" = "e236d7", "terraform-plugin-sdk-migration" = "fad8c7", + "terraform-plugin-sdk-v1" = "fad8c7", } description = "Name-color mapping of workflow issues" type = map(string) diff --git a/infrastructure/repository/main.tf b/infrastructure/repository/main.tf index f2768d87538..b7beea61bb9 100644 --- a/infrastructure/repository/main.tf +++ b/infrastructure/repository/main.tf @@ -4,7 +4,7 @@ terraform { } required_providers { - github = "2.1.0" + github = "2.9.2" } required_version = "~> 0.12.24" diff --git a/main.go b/main.go index cbd7fc33185..42d1bc3c66f 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,7 @@ package main import ( - "github.com/hashicorp/terraform-plugin-sdk/plugin" + "github.com/hashicorp/terraform-plugin-sdk/v2/plugin" "github.com/terraform-providers/terraform-provider-aws/aws" ) diff --git a/renovate.json b/renovate.json index 58a4d8ad9e2..47bd80d6184 100644 --- a/renovate.json +++ b/renovate.json @@ -6,9 +6,7 @@ "ignoreDeps": [ "github.com/go-toolsmith/pkgload", "github.com/gogo/protobuf", - "github.com/golang/snappy", "github.com/hashicorp/go-hclog", - "github.com/hashicorp/vault", "github.com/mattn/go-isatty", "github.com/mitchellh/go-testing-interface", "golang.org/x/tools", diff --git a/scripts/markdown-link-check.sh b/scripts/markdown-link-check.sh index d21308ac184..37ebd88a9c7 100755 --- a/scripts/markdown-link-check.sh +++ b/scripts/markdown-link-check.sh @@ -22,7 +22,15 @@ docker run --rm -i -t \ -w /github/workspace \ --entrypoint /usr/bin/find \ markdown-link-check \ - website -type f -name "*.md" -or -name "*.markdown" -exec /src/markdown-link-check --config .markdownlinkcheck.json --quiet --verbose {} \; \ + docs -type f -name "*.md" -exec /src/markdown-link-check --config .markdownlinkcheck.json --quiet --verbose {} \; \ + | tee -a "${output_file}" + +docker run --rm -i -t \ + -v $(pwd):/github/workspace:ro \ + -w /github/workspace \ + --entrypoint /usr/bin/find \ + markdown-link-check \ + website \( -type f -name "*.md" -or -name "*.markdown" \) -exec /src/markdown-link-check --config .markdownlinkcheck.json --quiet --verbose {} \; \ | tee -a "${output_file}" touch "${error_file}" diff --git a/scripts/validate-terraform-file.sh b/scripts/validate-terraform-file.sh new file mode 100755 index 00000000000..7106f72f71a --- /dev/null +++ b/scripts/validate-terraform-file.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash + +set -eo pipefail + +# This script accepts the filename and an array of options for tflint. +# To call it, e.g. +# rules=( +# "--enable-rule=terraform_deprecated_interpolation" +# "--enable-rule=terraform_deprecated_index" +# ) +# ./scripts/validate-terraform-file.sh "$filename" "${rules[@]}" + +filename=$1 +shift +rules=( "$@" ) + +exit_code=0 + +block_number=0 + +while IFS= read -r block ; do + ((block_number+=1)) + start_line=$(echo "$block" | jq '.start_line') + end_line=$(echo "$block" | jq '.end_line') + text=$(echo "$block" | jq --raw-output '.text') + + td=$(mktemp -d) + tf="$td/main.tf" + + echo "$text" > "$tf" + + # We need to capture the output and error code here. We don't want to exit on the first error + set +e + tflint_output=$(tflint "${rules[@]}" "$tf" 2>&1) + tflint_exitcode=$? + set -e + + if [ $tflint_exitcode -ne 0 ]; then + echo "ERROR: File \"$filename\", block #$block_number (lines $start_line-$end_line):" + echo "$tflint_output" + echo + exit_code=1 + fi +done < <( terrafmt blocks --json "$filename" | jq --compact-output '.blocks[]?' ) + +exit $exit_code diff --git a/staticcheck.conf b/staticcheck.conf index 0f022090118..6f10b6ed746 100644 --- a/staticcheck.conf +++ b/staticcheck.conf @@ -1,5 +1,6 @@ checks = [ "all", + "-S1039", "-SA1019", "-ST1000", "-ST1003", diff --git a/vendor/cloud.google.com/go/.gitignore b/vendor/cloud.google.com/go/.gitignore new file mode 100644 index 00000000000..ee9694b8780 --- /dev/null +++ b/vendor/cloud.google.com/go/.gitignore @@ -0,0 +1,11 @@ +# Editors +.idea +.vscode +*.swp + +# Test files +*.test +coverage.txt + +# Other +.DS_Store diff --git a/vendor/cloud.google.com/go/CHANGES.md b/vendor/cloud.google.com/go/CHANGES.md new file mode 100644 index 00000000000..3e9fca4a749 --- /dev/null +++ b/vendor/cloud.google.com/go/CHANGES.md @@ -0,0 +1,1566 @@ +# Changes + +## v0.61.0 + +### Changes + +- all: + - Update all direct dependencies. +- dashboard: + - Start generating client for apiv1. +- policytroubleshooter: + - Start generating client for apiv1. +- profiler: + - Disable OpenCensus Telemetry for requests made by the profiler package by default. You can re-enable it using `profiler.Config.EnableOCTelemetry`. +- Various updates to autogenerated clients. + +## v0.60.0 + +### Changes + +- all: + - Refactored examples to reduce module dependencies. + - Update sub-modules to use cloud.google.com/go v0.59.0. +- internal: + - Start generating client for gaming apiv1beta. +- Various updates to autogenerated clients. + +## v0.59.0 + +### Announcements + +goolgeapis/google-cloud-go has moved its source of truth to GitHub and is no longer a mirror. This means that our +contributing process has changed a bit. We will now be conducting all code reviews on GitHub which means we now accept +pull requests! If you have a version of the codebase previously checked out you may wish to update your git remote to +point to GitHub. + +### Changes + +- all: + - Remove dependency on honnef.co/go/tools. + - Update our contributing instructions now that we use GitHub for reviews. + - Remove some un-inclusive terminology. +- compute/metadata: + - Pass cancelable context to DNS lookup. +- .github: + - Update templates issue/PR templates. +- internal: + - Bump several clients to GA. + - Fix GoDoc badge source. + - Several automation changes related to the move to GitHub. + - Start generating a client for asset v1p5beta1. +- Various updates to autogenerated clients. + +## v0.58.0 + +### Deprecation notice + +- `cloud.google.com/go/monitoring/apiv3` has been deprecated due to breaking + changes in the API. Please migrate to `cloud.google.com/go/monitoring/apiv3/v2`. + +### Changes + +- all: + - The remaining uses of gtransport.Dial have been removed. + - The `genproto` dependency has been updated to a version that makes use of + new `protoreflect` library. For more information on these protobuf changes + please see the following post from the official Go blog: + https://blog.golang.org/protobuf-apiv2. +- internal: + - Started generation of datastore admin v1 client. + - Updated protofuf version used for generation to 3.12.X. + - Update the release levels for several APIs. + - Generate clients with protoc-gen-go@v1.4.1. +- monitoring: + - Re-enable generation of monitoring/apiv3 under v2 directory (see deprecation + notice above). +- profiler: + - Fixed flakiness in tests. +- Various updates to autogenerated clients. + +## v0.57.0 + +- all: + - Update module dependency `google.golang.org/api` to `v0.21.0`. +- errorreporting: + - Add exported SetGoogleClientInfo wrappers to manual file. +- expr/v1alpha1: + - Deprecate client. This client will be removed in a future release. +- internal: + - Fix possible data race in TestTracer. + - Pin versions of tools used for generation. + - Correct the release levels for BigQuery APIs. + - Start generation osconfig v1. +- longrunning: + - Add exported SetGoogleClientInfo wrappers to manual file. +- monitoring: + - Stop generation of monitoring/apiv3 because of incoming breaking change. +- trace: + - Add exported SetGoogleClientInfo wrappers to manual file. +- Various updates to autogenerated clients. + +## v0.56.0 + +- secretmanager: + - add IAM helper +- profiler: + - try all us-west1 zones for integration tests +- internal: + - add config to generate webrisk v1 + - add repo and commit to buildcop invocation + - add recaptchaenterprise v1 generation config + - update microgenerator to v0.12.5 + - add datacatalog client + - start generating security center settings v1beta + - start generating osconfig agentendpoint v1 + - setup generation for bigquery/connection/v1beta1 +- all: + - increase continous testing timeout to 45m + - various updates to autogenerated clients. + +## v0.55.0 + +- Various updates to autogenerated clients. + +## v0.54.0 + +- all: + - remove unused golang.org/x/exp from mod file + - update godoc.org links to pkg.go.dev +- compute/metadata: + - use defaultClient when http.Client is nil + - remove subscribeClient +- iam: + - add support for v3 policy and IAM conditions +- Various updates to autogenerated clients. + +## v0.53.0 + +- all: most clients now use transport/grpc.DialPool rather than Dial (see #1777 for outliers). + - Connection pooling now does not use the deprecated (and soon to be removed) gRPC load balancer API. +- profiler: remove symbolization (drops support for go1.10) +- Various updates to autogenerated clients. + +## v0.52.0 + +- internal/gapicgen: multiple improvements related to library generation. +- compute/metadata: unset ResponseHeaderTimeout in defaultClient +- docs: fix link to KMS in README.md +- Various updates to autogenerated clients. + +## v0.51.0 + +- secretmanager: + - add IAM helper for generic resource IAM handle +- cloudbuild: + - migrate to microgen in a major version +- Various updates to autogenerated clients. + +## v0.50.0 + +- profiler: + - Support disabling CPU profile collection. + - Log when a profile creation attempt begins. +- compute/metadata: + - Fix panic on malformed URLs. + - InstanceName returns actual instance name. +- Various updates to autogenerated clients. + +## v0.49.0 + +- functions/metadata: + - Handle string resources in JSON unmarshaller. +- Various updates to autogenerated clients. + +## v0.48.0 + +- Various updates to autogenerated clients + +## v0.47.0 + +This release drops support for Go 1.9 and Go 1.10: we continue to officially +support Go 1.11, Go 1.12, and Go 1.13. + +- Various updates to autogenerated clients. +- Add cloudbuild/apiv1 client. + +## v0.46.3 + +This is an empty release that was created solely to aid in storage's module +carve-out. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository. + +## v0.46.2 + +This is an empty release that was created solely to aid in spanner's module +carve-out. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository. + +## v0.46.1 + +This is an empty release that was created solely to aid in firestore's module +carve-out. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository. + +## v0.46.0 + +- spanner: + - Retry "Session not found" for read-only transactions. + - Retry aborted PDMLs. +- spanner/spannertest: + - Fix a bug that was causing 0X-prefixed number to be parsed incorrectly. +- storage: + - Add HMACKeyOptions. + - Remove *REGIONAL from StorageClass documentation. Using MULTI_REGIONAL, + DURABLE_REDUCED_AVAILABILITY, and REGIONAL are no longer best practice + StorageClasses but they are still acceptable values. +- trace: + - Remove cloud.google.com/go/trace. Package cloud.google.com/go/trace has been + marked OBSOLETE for several years: it is now no longer provided. If you + relied on this package, please vendor it or switch to using + https://cloud.google.com/trace/docs/setup/go (which obsoleted it). + +## v0.45.1 + +This is an empty release that was created solely to aid in pubsub's module +carve-out. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository. + +## v0.45.0 + +- compute/metadata: + - Add Email method. +- storage: + - Fix duplicated retry logic. + - Add ReaderObjectAttrs.StartOffset. + - Support reading last N bytes of a file when a negative range is given, such + as `obj.NewRangeReader(ctx, -10, -1)`. + - Add HMACKey listing functionality. +- spanner/spannertest: + - Support primary keys with no columns. + - Fix MinInt64 parsing. + - Implement deletion of key ranges. + - Handle reads during a read-write transaction. + - Handle returning DATE values. +- pubsub: + - Fix Ack/Modack request size calculation. +- logging: + - Add auto-detection of monitored resources on GAE Standard. + +## v0.44.3 + +This is an empty release that was created solely to aid in bigtable's module +carve-out. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository. + +## v0.44.2 + +This is an empty release that was created solely to aid in bigquery's module +carve-out. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository. + +## v0.44.1 + +This is an empty release that was created solely to aid in datastore's module +carve-out. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository. + +## v0.44.0 + +- datastore: + - Interface elements whose underlying types are supported, are now supported. + - Reduce time to initial retry from 1s to 100ms. +- firestore: + - Add Increment transformation. +- storage: + - Allow emulator with STORAGE_EMULATOR_HOST. + - Add methods for HMAC key management. +- pubsub: + - Add PublishCount and PublishLatency measurements. + - Add DefaultPublishViews and DefaultSubscribeViews for convenience of + importing all views. + - Add add Subscription.PushConfig.AuthenticationMethod. +- spanner: + - Allow emulator usage with SPANNER_EMULATOR_HOST. + - Add cloud.google.com/go/spanner/spannertest, a spanner emulator. + - Add cloud.google.com/go/spanner/spansql which contains types and a parser + for the Cloud Spanner SQL dialect. +- asset: + - Add apiv1p2beta1 client. + +## v0.43.0 + +This is an empty release that was created solely to aid in logging's module +carve-out. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository. + +## v0.42.0 + +- bigtable: + - Add an admin method to update an instance and clusters. + - Fix bttest regex matching behavior for alternations (things like `|a`). + - Expose BlockAllFilter filter. +- bigquery: + - Add Routines API support. +- storage: + - Add read-only Bucket.LocationType. +- logging: + - Add TraceSampled to Entry. + - Fix to properly extract {Trace, Span}Id from X-Cloud-Trace-Context. +- pubsub: + - Add Cloud Key Management to TopicConfig. + - Change ExpirationPolicy to optional.Duration. +- automl: + - Add apiv1beta1 client. +- iam: + - Fix compilation problem with iam/credentials/apiv1. + +## v0.41.0 + +- bigtable: + - Check results from PredicateFilter in bttest, which fixes certain false matches. +- profiler: + - debugLog checks user defined logging options before logging. +- spanner: + - PartitionedUpdates respect query parameters. + - StartInstance allows specifying cloud API access scopes. +- bigquery: + - Use empty slice instead of nil for ValueSaver, fixing an issue with zero-length, repeated, nested fields causing panics. +- firestore: + - Return same number of snapshots as doc refs (in the form of duplicate records) during GetAll. +- replay: + - Change references to IPv4 addresses to localhost, making replay compatible with IPv6. + +## v0.40.0 + +- all: + - Update to protobuf-golang v1.3.1. +- datastore: + - Attempt to decode GAE-encoded keys if initial decoding attempt fails. + - Support integer time conversion. +- pubsub: + - Add PublishSettings.BundlerByteLimit. If users receive pubsub.ErrOverflow, + this value should be adjusted higher. + - Use IPv6 compatible target in testutil. +- bigtable: + - Fix Latin-1 regexp filters in bttest, allowing \C. + - Expose PassAllFilter. +- profiler: + - Add log messages for slow path in start. + - Fix start to allow retry until success. +- firestore: + - Add admin client. +- containeranalysis: + - Add apiv1 client. +- grafeas: + - Add apiv1 client. + +## 0.39.0 + +- bigtable: + - Implement DeleteInstance in bttest. + - Return an error on invalid ReadRowsRequest.RowRange key ranges in bttest. +- bigquery: + - Move RequirePartitionFilter outside of TimePartioning. + - Expose models API. +- firestore: + - Allow array values in create and update calls. + - Add CollectionGroup method. +- pubsub: + - Add ExpirationPolicy to Subscription. +- storage: + - Add V4 signing. +- rpcreplay: + - Match streams by first sent request. This further improves rpcreplay's + ability to distinguish streams. +- httpreplay: + - Set up Man-In-The-Middle config only once. This should improve proxy + creation when multiple proxies are used in a single process. + - Remove error on empty Content-Type, allowing requests with no Content-Type + header but a non-empty body. +- all: + - Fix an edge case bug in auto-generated library pagination by properly + propagating pagetoken. + +## 0.38.0 + +This update includes a substantial reduction in our transitive dependency list +by way of updating to opencensus@v0.21.0. + +- spanner: + - Error implements GRPCStatus, allowing status.Convert. +- bigtable: + - Fix a bug in bttest that prevents single column queries returning results + that match other filters. + - Remove verbose retry logging. +- logging: + - Ensure RequestUrl has proper UTF-8, removing the need for users to wrap and + rune replace manually. +- recaptchaenterprise: + - Add v1beta1 client. +- phishingprotection: + - Add v1beta1 client. + +## 0.37.4 + +This patch releases re-builds the go.sum. This was not possible in the +previous release. + +- firestore: + - Add sentinel value DetectProjectID for auto-detecting project ID. + - Add OpenCensus tracing for public methods. + - Marked stable. All future changes come with a backwards compatibility + guarantee. + - Removed firestore/apiv1beta1. All users relying on this low-level library + should migrate to firestore/apiv1. Note that most users should use the + high-level firestore package instead. +- pubsub: + - Allow large messages in synchronous pull case. + - Cap bundler byte limit. This should prevent OOM conditions when there are + a very large number of message publishes occurring. +- storage: + - Add ETag to BucketAttrs and ObjectAttrs. +- datastore: + - Removed some non-sensical OpenCensus traces. +- webrisk: + - Add v1 client. +- asset: + - Add v1 client. +- cloudtasks: + - Add v2 client. + +## 0.37.3 + +This patch release removes github.com/golang/lint from the transitive +dependency list, resolving `go get -u` problems. + +Note: this release intentionally has a broken go.sum. Please use v0.37.4. + +## 0.37.2 + +This patch release is mostly intended to bring in v0.3.0 of +google.golang.org/api, which fixes a GCF deployment issue. + +Note: we had to-date accidentally marked Redis as stable. In this release, we've +fixed it by downgrading its documentation to alpha, as it is in other languages +and docs. + +- all: + - Document context in generated libraries. + +## 0.37.1 + +Small go.mod version bumps to bring in v0.2.0 of google.golang.org/api, which +introduces a new oauth2 url. + +## 0.37.0 + +- spanner: + - Add BatchDML method. + - Reduced initial time between retries. +- bigquery: + - Produce better error messages for InferSchema. + - Add logical type control for avro loads. + - Add support for the GEOGRAPHY type. +- datastore: + - Add sentinel value DetectProjectID for auto-detecting project ID. + - Allow flatten tag on struct pointers. + - Fixed a bug that caused queries to panic with invalid queries. Instead they + will now return an error. +- profiler: + - Add ability to override GCE zone and instance. +- pubsub: + - BEHAVIOR CHANGE: Refactor error code retry logic. RPCs should now more + consistently retry specific error codes based on whether they're idempotent + or non-idempotent. +- httpreplay: Fixed a bug when a non-GET request had a zero-length body causing + the Content-Length header to be dropped. +- iot: + - Add new apiv1 client. +- securitycenter: + - Add new apiv1 client. +- cloudscheduler: + - Add new apiv1 client. + +## 0.36.0 + +- spanner: + - Reduce minimum retry backoff from 1s to 100ms. This makes time between + retries much faster and should improve latency. +- storage: + - Add support for Bucket Policy Only. +- kms: + - Add ResourceIAM helper method. + - Deprecate KeyRingIAM and CryptoKeyIAM. Please use ResourceIAM. +- firestore: + - Switch from v1beta1 API to v1 API. + - Allow emulator with FIRESTORE_EMULATOR_HOST. +- bigquery: + - Add NumLongTermBytes to Table. + - Add TotalBytesProcessedAccuracy to QueryStatistics. +- irm: + - Add new v1alpha2 client. +- talent: + - Add new v4beta1 client. +- rpcreplay: + - Fix connection to work with grpc >= 1.17. + - It is now required for an actual gRPC server to be running for Dial to + succeed. + +## 0.35.1 + +- spanner: + - Adds OpenCensus views back to public API. + +## v0.35.0 + +- all: + - Add go.mod and go.sum. + - Switch usage of gax-go to gax-go/v2. +- bigquery: + - Fix bug where time partitioning could not be removed from a table. + - Fix panic that occurred with empty query parameters. +- bttest: + - Fix bug where deleted rows were returned by ReadRows. +- bigtable/emulator: + - Configure max message size to 256 MiB. +- firestore: + - Allow non-transactional queries in transactions. + - Allow StartAt/EndBefore on direct children at any depth. + - QuerySnapshotIterator.Stop may be called in an error state. + - Fix bug the prevented reset of transaction write state in between retries. +- functions/metadata: + - Make Metadata.Resource a pointer. +- logging: + - Make SpanID available in logging.Entry. +- metadata: + - Wrap !200 error code in a typed err. +- profiler: + - Add function to check if function name is within a particular file in the + profile. + - Set parent field in create profile request. + - Return kubernetes client to start cluster, so client can be used to poll + cluster. + - Add function for checking if filename is in profile. +- pubsub: + - Fix bug where messages expired without an initial modack in + synchronous=true mode. + - Receive does not retry ResourceExhausted errors. +- spanner: + - client.Close now cancels existing requests and should be much faster for + large amounts of sessions. + - Correctly allow MinOpened sessions to be spun up. + +## v0.34.0 + +- functions/metadata: + - Switch to using JSON in context. + - Make Resource a value. +- vision: Fix ProductSearch return type. +- datastore: Add an example for how to handle MultiError. + +## v0.33.1 + +- compute: Removes an erroneously added go.mod. +- logging: Populate source location in fromLogEntry. + +## v0.33.0 + +- bttest: + - Add support for apply_label_transformer. +- expr: + - Add expr library. +- firestore: + - Support retrieval of missing documents. +- kms: + - Add IAM methods. +- pubsub: + - Clarify extension documentation. +- scheduler: + - Add v1beta1 client. +- vision: + - Add product search helper. + - Add new product search client. + +## v0.32.0 + +Note: This release is the last to support Go 1.6 and 1.8. + +- bigquery: + - Add support for removing an expiration. + - Ignore NeverExpire in Table.Create. + - Validate table expiration time. +- cbt: + - Add note about not supporting arbitrary bytes. +- datastore: + - Align key checks. +- firestore: + - Return an error when using Start/End without providing values. +- pubsub: + - Add pstest Close method. + - Clarify MaxExtension documentation. +- securitycenter: + - Add v1beta1 client. +- spanner: + - Allow nil in mutations. + - Improve doc of SessionPoolConfig.MaxOpened. + - Increase session deletion timeout from 5s to 15s. + +## v0.31.0 + +- bigtable: + - Group mutations across multiple requests. +- bigquery: + - Link to bigquery troubleshooting errors page in bigquery.Error comment. +- cbt: + - Fix go generate command. + - Document usage of both maxage + maxversions. +- datastore: + - Passing nil keys results in ErrInvalidKey. +- firestore: + - Clarify what Document.DataTo does with untouched struct fields. +- profile: + - Validate service name in agent. +- pubsub: + - Fix deadlock with pstest and ctx.Cancel. + - Fix a possible deadlock in pstest. +- trace: + - Update doc URL with new fragment. + +Special thanks to @fastest963 for going above and beyond helping us to debug +hard-to-reproduce Pub/Sub issues. + +## v0.30.0 + +- spanner: DML support added. See https://godoc.org/cloud.google.com/go/spanner#hdr-DML_and_Partitioned_DML for more information. +- bigtable: bttest supports row sample filter. +- functions: metadata package added for accessing Cloud Functions resource metadata. + +## v0.29.0 + +- bigtable: + - Add retry to all idempotent RPCs. + - cbt supports complex GC policies. + - Emulator supports arbitrary bytes in regex filters. +- firestore: Add ArrayUnion and ArrayRemove. +- logging: Add the ContextFunc option to supply the context used for + asynchronous RPCs. +- profiler: Ignore NotDefinedError when fetching the instance name +- pubsub: + - BEHAVIOR CHANGE: Receive doesn't retry if an RPC returns codes.Cancelled. + - BEHAVIOR CHANGE: Receive retries on Unavailable intead of returning. + - Fix deadlock. + - Restore Ack/Nack/Modacks metrics. + - Improve context handling in iterator. + - Implement synchronous mode for Receive. + - pstest: add Pull. +- spanner: Add a metric for the number of sessions currently opened. +- storage: + - Canceling the context releases all resources. + - Add additional RetentionPolicy attributes. +- vision/apiv1: Add LocalizeObjects method. + +## v0.28.0 + +- bigtable: + - Emulator returns Unimplemented for snapshot RPCs. +- bigquery: + - Support zero-length repeated, nested fields. +- cloud assets: + - Add v1beta client. +- datastore: + - Don't nil out transaction ID on retry. +- firestore: + - BREAKING CHANGE: When watching a query with Query.Snapshots, QuerySnapshotIterator.Next + returns a QuerySnapshot which contains read time, result size, change list and the DocumentIterator + (previously, QuerySnapshotIterator.Next returned just the DocumentIterator). See: https://godoc.org/cloud.google.com/go/firestore#Query.Snapshots. + - Add array-contains operator. +- IAM: + - Add iam/credentials/apiv1 client. +- pubsub: + - Canceling the context passed to Subscription.Receive causes Receive to return when + processing finishes on all messages currently in progress, even if new messages are arriving. +- redis: + - Add redis/apiv1 client. +- storage: + - Add Reader.Attrs. + - Deprecate several Reader getter methods: please use Reader.Attrs for these instead. + - Add ObjectHandle.Bucket and ObjectHandle.Object methods. + +## v0.27.0 + +- bigquery: + - Allow modification of encryption configuration and partitioning options to a table via the Update call. + - Add a SchemaFromJSON function that converts a JSON table schema. +- bigtable: + - Restore cbt count functionality. +- containeranalysis: + - Add v1beta client. +- spanner: + - Fix a case where an iterator might not be closed correctly. +- storage: + - Add ServiceAccount method https://godoc.org/cloud.google.com/go/storage#Client.ServiceAccount. + - Add a method to Reader that returns the parsed value of the Last-Modified header. + +## v0.26.0 + +- bigquery: + - Support filtering listed jobs by min/max creation time. + - Support data clustering (https://godoc.org/cloud.google.com/go/bigquery#Clustering). + - Include job creator email in Job struct. +- bigtable: + - Add `RowSampleFilter`. + - emulator: BREAKING BEHAVIOR CHANGE: Regexps in row, family, column and value filters + must match the entire target string to succeed. Previously, the emulator was + succeeding on partial matches. + NOTE: As of this release, this change only affects the emulator when run + from this repo (bigtable/cmd/emulator/cbtemulator.go). The version launched + from `gcloud` will be updated in a subsequent `gcloud` release. +- dataproc: Add apiv1beta2 client. +- datastore: Save non-nil pointer fields on omitempty. +- logging: populate Entry.Trace from the HTTP X-Cloud-Trace-Context header. +- logging/logadmin: Support writer_identity and include_children. +- pubsub: + - Support labels on topics and subscriptions. + - Support message storage policy for topics. + - Use the distribution of ack times to determine when to extend ack deadlines. + The only user-visible effect of this change should be that programs that + call only `Subscription.Receive` need no IAM permissions other than `Pub/Sub + Subscriber`. +- storage: + - Support predefined ACLs. + - Support additional ACL fields other than Entity and Role. + - Support bucket websites. + - Support bucket logging. + + +## v0.25.0 + +- Added [Code of Conduct](https://github.com/googleapis/google-cloud-go/blob/master/CODE_OF_CONDUCT.md) +- bigtable: + - cbt: Support a GC policy of "never". +- errorreporting: + - Support User. + - Close now calls Flush. + - Use OnError (previously ignored). + - Pass through the RPC error as-is to OnError. +- httpreplay: A tool for recording and replaying HTTP requests + (for the bigquery and storage clients in this repo). +- kms: v1 client added +- logging: add SourceLocation to Entry. +- storage: improve CRC checking on read. + +## v0.24.0 + +- bigquery: Support for the NUMERIC type. +- bigtable: + - cbt: Optionally specify columns for read/lookup + - Support instance-level administration. +- oslogin: New client for the OS Login API. +- pubsub: + - The package is now stable. There will be no further breaking changes. + - Internal changes to improve Subscription.Receive behavior. +- storage: Support updating bucket lifecycle config. +- spanner: Support struct-typed parameter bindings. +- texttospeech: New client for the Text-to-Speech API. + +## v0.23.0 + +- bigquery: Add DDL stats to query statistics. +- bigtable: + - cbt: Add cells-per-column limit for row lookup. + - cbt: Make it possible to combine read filters. +- dlp: v2beta2 client removed. Use the v2 client instead. +- firestore, spanner: Fix compilation errors due to protobuf changes. + +## v0.22.0 + +- bigtable: + - cbt: Support cells per column limit for row read. + - bttest: Correctly handle empty RowSet. + - Fix ReadModifyWrite operation in emulator. + - Fix API path in GetCluster. + +- bigquery: + - BEHAVIOR CHANGE: Retry on 503 status code. + - Add dataset.DeleteWithContents. + - Add SchemaUpdateOptions for query jobs. + - Add Timeline to QueryStatistics. + - Add more stats to ExplainQueryStage. + - Support Parquet data format. + +- datastore: + - Support omitempty for times. + +- dlp: + - **BREAKING CHANGE:** Remove v1beta1 client. Please migrate to the v2 client, + which is now out of beta. + - Add v2 client. + +- firestore: + - BEHAVIOR CHANGE: Treat set({}, MergeAll) as valid. + +- iam: + - Support JWT signing via SignJwt callopt. + +- profiler: + - BEHAVIOR CHANGE: PollForSerialOutput returns an error when context.Done. + - BEHAVIOR CHANGE: Increase the initial backoff to 1 minute. + - Avoid returning empty serial port output. + +- pubsub: + - BEHAVIOR CHANGE: Don't backoff during next retryable error once stream is healthy. + - BEHAVIOR CHANGE: Don't backoff on EOF. + - pstest: Support Acknowledge and ModifyAckDeadline RPCs. + +- redis: + - Add v1 beta Redis client. + +- spanner: + - Support SessionLabels. + +- speech: + - Add api v1 beta1 client. + +- storage: + - BEHAVIOR CHANGE: Retry reads when retryable error occurs. + - Fix delete of object in requester-pays bucket. + - Support KMS integration. + +## v0.21.0 + +- bigquery: + - Add OpenCensus tracing. + +- firestore: + - **BREAKING CHANGE:** If a document does not exist, return a DocumentSnapshot + whose Exists method returns false. DocumentRef.Get and Transaction.Get + return the non-nil DocumentSnapshot in addition to a NotFound error. + **DocumentRef.GetAll and Transaction.GetAll return a non-nil + DocumentSnapshot instead of nil.** + - Add DocumentIterator.Stop. **Call Stop whenever you are done with a + DocumentIterator.** + - Added Query.Snapshots and DocumentRef.Snapshots, which provide realtime + notification of updates. See https://cloud.google.com/firestore/docs/query-data/listen. + - Canceling an RPC now always returns a grpc.Status with codes.Canceled. + +- spanner: + - Add `CommitTimestamp`, which supports inserting the commit timestamp of a + transaction into a column. + +## v0.20.0 + +- bigquery: Support SchemaUpdateOptions for load jobs. + +- bigtable: + - Add SampleRowKeys. + - cbt: Support union, intersection GCPolicy. + - Retry admin RPCS. + - Add trace spans to retries. + +- datastore: Add OpenCensus tracing. + +- firestore: + - Fix queries involving Null and NaN. + - Allow Timestamp protobuffers for time values. + +- logging: Add a WriteTimeout option. + +- spanner: Support Batch API. + +- storage: Add OpenCensus tracing. + +## v0.19.0 + +- bigquery: + - Support customer-managed encryption keys. + +- bigtable: + - Improved emulator support. + - Support GetCluster. + +- datastore: + - Add general mutations. + - Support pointer struct fields. + - Support transaction options. + +- firestore: + - Add Transaction.GetAll. + - Support document cursors. + +- logging: + - Support concurrent RPCs to the service. + - Support per-entry resources. + +- profiler: + - Add config options to disable heap and thread profiling. + - Read the project ID from $GOOGLE_CLOUD_PROJECT when it's set. + +- pubsub: + - BEHAVIOR CHANGE: Release flow control after ack/nack (instead of after the + callback returns). + - Add SubscriptionInProject. + - Add OpenCensus instrumentation for streaming pull. + +- storage: + - Support CORS. + +## v0.18.0 + +- bigquery: + - Marked stable. + - Schema inference of nullable fields supported. + - Added TimePartitioning to QueryConfig. + +- firestore: Data provided to DocumentRef.Set with a Merge option can contain + Delete sentinels. + +- logging: Clients can accept parent resources other than projects. + +- pubsub: + - pubsub/pstest: A lighweight fake for pubsub. Experimental; feedback welcome. + - Support updating more subscription metadata: AckDeadline, + RetainAckedMessages and RetentionDuration. + +- oslogin/apiv1beta: New client for the Cloud OS Login API. + +- rpcreplay: A package for recording and replaying gRPC traffic. + +- spanner: + - Add a ReadWithOptions that supports a row limit, as well as an index. + - Support query plan and execution statistics. + - Added [OpenCensus](http://opencensus.io) support. + +- storage: Clarify checksum validation for gzipped files (it is not validated + when the file is served uncompressed). + + +## v0.17.0 + +- firestore BREAKING CHANGES: + - Remove UpdateMap and UpdateStruct; rename UpdatePaths to Update. + Change + `docref.UpdateMap(ctx, map[string]interface{}{"a.b", 1})` + to + `docref.Update(ctx, []firestore.Update{{Path: "a.b", Value: 1}})` + + Change + `docref.UpdateStruct(ctx, []string{"Field"}, aStruct)` + to + `docref.Update(ctx, []firestore.Update{{Path: "Field", Value: aStruct.Field}})` + - Rename MergePaths to Merge; require args to be FieldPaths + - A value stored as an integer can be read into a floating-point field, and vice versa. +- bigtable/cmd/cbt: + - Support deleting a column. + - Add regex option for row read. +- spanner: Mark stable. +- storage: + - Add Reader.ContentEncoding method. + - Fix handling of SignedURL headers. +- bigquery: + - If Uploader.Put is called with no rows, it returns nil without making a + call. + - Schema inference supports the "nullable" option in struct tags for + non-required fields. + - TimePartitioning supports "Field". + + +## v0.16.0 + +- Other bigquery changes: + - `JobIterator.Next` returns `*Job`; removed `JobInfo` (BREAKING CHANGE). + - UseStandardSQL is deprecated; set UseLegacySQL to true if you need + Legacy SQL. + - Uploader.Put will generate a random insert ID if you do not provide one. + - Support time partitioning for load jobs. + - Support dry-run queries. + - A `Job` remembers its last retrieved status. + - Support retrieving job configuration. + - Support labels for jobs and tables. + - Support dataset access lists. + - Improve support for external data sources, including data from Bigtable and + Google Sheets, and tables with external data. + - Support updating a table's view configuration. + - Fix uploading civil times with nanoseconds. + +- storage: + - Support PubSub notifications. + - Support Requester Pays buckets. + +- profiler: Support goroutine and mutex profile types. + +## v0.15.0 + +- firestore: beta release. See the + [announcement](https://firebase.googleblog.com/2017/10/introducing-cloud-firestore.html). + +- errorreporting: The existing package has been redesigned. + +- errors: This package has been removed. Use errorreporting. + + +## v0.14.0 + +- bigquery BREAKING CHANGES: + - Standard SQL is the default for queries and views. + - `Table.Create` takes `TableMetadata` as a second argument, instead of + options. + - `Dataset.Create` takes `DatasetMetadata` as a second argument. + - `DatasetMetadata` field `ID` renamed to `FullID` + - `TableMetadata` field `ID` renamed to `FullID` + +- Other bigquery changes: + - The client will append a random suffix to a provided job ID if you set + `AddJobIDSuffix` to true in a job config. + - Listing jobs is supported. + - Better retry logic. + +- vision, language, speech: clients are now stable + +- monitoring: client is now beta + +- profiler: + - Rename InstanceName to Instance, ZoneName to Zone + - Auto-detect service name and version on AppEngine. + +## v0.13.0 + +- bigquery: UseLegacySQL options for CreateTable and QueryConfig. Use these + options to continue using Legacy SQL after the client switches its default + to Standard SQL. + +- bigquery: Support for updating dataset labels. + +- bigquery: Set DatasetIterator.ProjectID to list datasets in a project other + than the client's. DatasetsInProject is no longer needed and is deprecated. + +- bigtable: Fail ListInstances when any zones fail. + +- spanner: support decoding of slices of basic types (e.g. []string, []int64, + etc.) + +- logging/logadmin: UpdateSink no longer creates a sink if it is missing + (actually a change to the underlying service, not the client) + +- profiler: Service and ServiceVersion replace Target in Config. + +## v0.12.0 + +- pubsub: Subscription.Receive now uses streaming pull. + +- pubsub: add Client.TopicInProject to access topics in a different project + than the client. + +- errors: renamed errorreporting. The errors package will be removed shortly. + +- datastore: improved retry behavior. + +- bigquery: support updates to dataset metadata, with etags. + +- bigquery: add etag support to Table.Update (BREAKING: etag argument added). + +- bigquery: generate all job IDs on the client. + +- storage: support bucket lifecycle configurations. + + +## v0.11.0 + +- Clients for spanner, pubsub and video are now in beta. + +- New client for DLP. + +- spanner: performance and testing improvements. + +- storage: requester-pays buckets are supported. + +- storage, profiler, bigtable, bigquery: bug fixes and other minor improvements. + +- pubsub: bug fixes and other minor improvements + +## v0.10.0 + +- pubsub: Subscription.ModifyPushConfig replaced with Subscription.Update. + +- pubsub: Subscription.Receive now runs concurrently for higher throughput. + +- vision: cloud.google.com/go/vision is deprecated. Use +cloud.google.com/go/vision/apiv1 instead. + +- translation: now stable. + +- trace: several changes to the surface. See the link below. + +### Code changes required from v0.9.0 + +- pubsub: Replace + + ``` + sub.ModifyPushConfig(ctx, pubsub.PushConfig{Endpoint: "https://example.com/push"}) + ``` + + with + + ``` + sub.Update(ctx, pubsub.SubscriptionConfigToUpdate{ + PushConfig: &pubsub.PushConfig{Endpoint: "https://example.com/push"}, + }) + ``` + +- trace: traceGRPCServerInterceptor will be provided from *trace.Client. +Given an initialized `*trace.Client` named `tc`, instead of + + ``` + s := grpc.NewServer(grpc.UnaryInterceptor(trace.GRPCServerInterceptor(tc))) + ``` + + write + + ``` + s := grpc.NewServer(grpc.UnaryInterceptor(tc.GRPCServerInterceptor())) + ``` + +- trace trace.GRPCClientInterceptor will also provided from *trace.Client. +Instead of + + ``` + conn, err := grpc.Dial(srv.Addr, grpc.WithUnaryInterceptor(trace.GRPCClientInterceptor())) + ``` + + write + + ``` + conn, err := grpc.Dial(srv.Addr, grpc.WithUnaryInterceptor(tc.GRPCClientInterceptor())) + ``` + +- trace: We removed the deprecated `trace.EnableGRPCTracing`. Use the gRPC +interceptor as a dial option as shown below when initializing Cloud package +clients: + + ``` + c, err := pubsub.NewClient(ctx, "project-id", option.WithGRPCDialOption(grpc.WithUnaryInterceptor(tc.GRPCClientInterceptor()))) + if err != nil { + ... + } + ``` + + +## v0.9.0 + +- Breaking changes to some autogenerated clients. +- rpcreplay package added. + +## v0.8.0 + +- profiler package added. +- storage: + - Retry Objects.Insert call. + - Add ProgressFunc to WRiter. +- pubsub: breaking changes: + - Publish is now asynchronous ([announcement](https://groups.google.com/d/topic/google-api-go-announce/aaqRDIQ3rvU/discussion)). + - Subscription.Pull replaced by Subscription.Receive, which takes a callback ([announcement](https://groups.google.com/d/topic/google-api-go-announce/8pt6oetAdKc/discussion)). + - Message.Done replaced with Message.Ack and Message.Nack. + +## v0.7.0 + +- Release of a client library for Spanner. See +the +[blog +post](https://cloudplatform.googleblog.com/2017/02/introducing-Cloud-Spanner-a-global-database-service-for-mission-critical-applications.html). +Note that although the Spanner service is beta, the Go client library is alpha. + +## v0.6.0 + +- Beta release of BigQuery, DataStore, Logging and Storage. See the +[blog post](https://cloudplatform.googleblog.com/2016/12/announcing-new-google-cloud-client.html). + +- bigquery: + - struct support. Read a row directly into a struct with +`RowIterator.Next`, and upload a row directly from a struct with `Uploader.Put`. +You can also use field tags. See the [package documentation][cloud-bigquery-ref] +for details. + + - The `ValueList` type was removed. It is no longer necessary. Instead of + ```go + var v ValueList + ... it.Next(&v) .. + ``` + use + + ```go + var v []Value + ... it.Next(&v) ... + ``` + + - Previously, repeatedly calling `RowIterator.Next` on the same `[]Value` or + `ValueList` would append to the slice. Now each call resets the size to zero first. + + - Schema inference will infer the SQL type BYTES for a struct field of + type []byte. Previously it inferred STRING. + + - The types `uint`, `uint64` and `uintptr` are no longer supported in schema + inference. BigQuery's integer type is INT64, and those types may hold values + that are not correctly represented in a 64-bit signed integer. + +## v0.5.0 + +- bigquery: + - The SQL types DATE, TIME and DATETIME are now supported. They correspond to + the `Date`, `Time` and `DateTime` types in the new `cloud.google.com/go/civil` + package. + - Support for query parameters. + - Support deleting a dataset. + - Values from INTEGER columns will now be returned as int64, not int. This + will avoid errors arising from large values on 32-bit systems. +- datastore: + - Nested Go structs encoded as Entity values, instead of a +flattened list of the embedded struct's fields. This means that you may now have twice-nested slices, eg. + ```go + type State struct { + Cities []struct{ + Populations []int + } + } + ``` + See [the announcement](https://groups.google.com/forum/#!topic/google-api-go-announce/79jtrdeuJAg) for +more details. + - Contexts no longer hold namespaces; instead you must set a key's namespace + explicitly. Also, key functions have been changed and renamed. + - The WithNamespace function has been removed. To specify a namespace in a Query, use the Query.Namespace method: + ```go + q := datastore.NewQuery("Kind").Namespace("ns") + ``` + - All the fields of Key are exported. That means you can construct any Key with a struct literal: + ```go + k := &Key{Kind: "Kind", ID: 37, Namespace: "ns"} + ``` + - As a result of the above, the Key methods Kind, ID, d.Name, Parent, SetParent and Namespace have been removed. + - `NewIncompleteKey` has been removed, replaced by `IncompleteKey`. Replace + ```go + NewIncompleteKey(ctx, kind, parent) + ``` + with + ```go + IncompleteKey(kind, parent) + ``` + and if you do use namespaces, make sure you set the namespace on the returned key. + - `NewKey` has been removed, replaced by `NameKey` and `IDKey`. Replace + ```go + NewKey(ctx, kind, name, 0, parent) + NewKey(ctx, kind, "", id, parent) + ``` + with + ```go + NameKey(kind, name, parent) + IDKey(kind, id, parent) + ``` + and if you do use namespaces, make sure you set the namespace on the returned key. + - The `Done` variable has been removed. Replace `datastore.Done` with `iterator.Done`, from the package `google.golang.org/api/iterator`. + - The `Client.Close` method will have a return type of error. It will return the result of closing the underlying gRPC connection. + - See [the announcement](https://groups.google.com/forum/#!topic/google-api-go-announce/hqXtM_4Ix-0) for +more details. + +## v0.4.0 + +- bigquery: + -`NewGCSReference` is now a function, not a method on `Client`. + - `Table.LoaderFrom` now accepts a `ReaderSource`, enabling + loading data into a table from a file or any `io.Reader`. + * Client.Table and Client.OpenTable have been removed. + Replace + ```go + client.OpenTable("project", "dataset", "table") + ``` + with + ```go + client.DatasetInProject("project", "dataset").Table("table") + ``` + + * Client.CreateTable has been removed. + Replace + ```go + client.CreateTable(ctx, "project", "dataset", "table") + ``` + with + ```go + client.DatasetInProject("project", "dataset").Table("table").Create(ctx) + ``` + + * Dataset.ListTables have been replaced with Dataset.Tables. + Replace + ```go + tables, err := ds.ListTables(ctx) + ``` + with + ```go + it := ds.Tables(ctx) + for { + table, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + // TODO: Handle error. + } + // TODO: use table. + } + ``` + + * Client.Read has been replaced with Job.Read, Table.Read and Query.Read. + Replace + ```go + it, err := client.Read(ctx, job) + ``` + with + ```go + it, err := job.Read(ctx) + ``` + and similarly for reading from tables or queries. + + * The iterator returned from the Read methods is now named RowIterator. Its + behavior is closer to the other iterators in these libraries. It no longer + supports the Schema method; see the next item. + Replace + ```go + for it.Next(ctx) { + var vals ValueList + if err := it.Get(&vals); err != nil { + // TODO: Handle error. + } + // TODO: use vals. + } + if err := it.Err(); err != nil { + // TODO: Handle error. + } + ``` + with + ``` + for { + var vals ValueList + err := it.Next(&vals) + if err == iterator.Done { + break + } + if err != nil { + // TODO: Handle error. + } + // TODO: use vals. + } + ``` + Instead of the `RecordsPerRequest(n)` option, write + ```go + it.PageInfo().MaxSize = n + ``` + Instead of the `StartIndex(i)` option, write + ```go + it.StartIndex = i + ``` + + * ValueLoader.Load now takes a Schema in addition to a slice of Values. + Replace + ```go + func (vl *myValueLoader) Load(v []bigquery.Value) + ``` + with + ```go + func (vl *myValueLoader) Load(v []bigquery.Value, s bigquery.Schema) + ``` + + + * Table.Patch is replace by Table.Update. + Replace + ```go + p := table.Patch() + p.Description("new description") + metadata, err := p.Apply(ctx) + ``` + with + ```go + metadata, err := table.Update(ctx, bigquery.TableMetadataToUpdate{ + Description: "new description", + }) + ``` + + * Client.Copy is replaced by separate methods for each of its four functions. + All options have been replaced by struct fields. + + * To load data from Google Cloud Storage into a table, use Table.LoaderFrom. + + Replace + ```go + client.Copy(ctx, table, gcsRef) + ``` + with + ```go + table.LoaderFrom(gcsRef).Run(ctx) + ``` + Instead of passing options to Copy, set fields on the Loader: + ```go + loader := table.LoaderFrom(gcsRef) + loader.WriteDisposition = bigquery.WriteTruncate + ``` + + * To extract data from a table into Google Cloud Storage, use + Table.ExtractorTo. Set fields on the returned Extractor instead of + passing options. + + Replace + ```go + client.Copy(ctx, gcsRef, table) + ``` + with + ```go + table.ExtractorTo(gcsRef).Run(ctx) + ``` + + * To copy data into a table from one or more other tables, use + Table.CopierFrom. Set fields on the returned Copier instead of passing options. + + Replace + ```go + client.Copy(ctx, dstTable, srcTable) + ``` + with + ```go + dst.Table.CopierFrom(srcTable).Run(ctx) + ``` + + * To start a query job, create a Query and call its Run method. Set fields + on the query instead of passing options. + + Replace + ```go + client.Copy(ctx, table, query) + ``` + with + ```go + query.Run(ctx) + ``` + + * Table.NewUploader has been renamed to Table.Uploader. Instead of options, + configure an Uploader by setting its fields. + Replace + ```go + u := table.NewUploader(bigquery.UploadIgnoreUnknownValues()) + ``` + with + ```go + u := table.NewUploader(bigquery.UploadIgnoreUnknownValues()) + u.IgnoreUnknownValues = true + ``` + +- pubsub: remove `pubsub.Done`. Use `iterator.Done` instead, where `iterator` is the package +`google.golang.org/api/iterator`. + +## v0.3.0 + +- storage: + * AdminClient replaced by methods on Client. + Replace + ```go + adminClient.CreateBucket(ctx, bucketName, attrs) + ``` + with + ```go + client.Bucket(bucketName).Create(ctx, projectID, attrs) + ``` + + * BucketHandle.List replaced by BucketHandle.Objects. + Replace + ```go + for query != nil { + objs, err := bucket.List(d.ctx, query) + if err != nil { ... } + query = objs.Next + for _, obj := range objs.Results { + fmt.Println(obj) + } + } + ``` + with + ```go + iter := bucket.Objects(d.ctx, query) + for { + obj, err := iter.Next() + if err == iterator.Done { + break + } + if err != nil { ... } + fmt.Println(obj) + } + ``` + (The `iterator` package is at `google.golang.org/api/iterator`.) + + Replace `Query.Cursor` with `ObjectIterator.PageInfo().Token`. + + Replace `Query.MaxResults` with `ObjectIterator.PageInfo().MaxSize`. + + + * ObjectHandle.CopyTo replaced by ObjectHandle.CopierFrom. + Replace + ```go + attrs, err := src.CopyTo(ctx, dst, nil) + ``` + with + ```go + attrs, err := dst.CopierFrom(src).Run(ctx) + ``` + + Replace + ```go + attrs, err := src.CopyTo(ctx, dst, &storage.ObjectAttrs{ContextType: "text/html"}) + ``` + with + ```go + c := dst.CopierFrom(src) + c.ContextType = "text/html" + attrs, err := c.Run(ctx) + ``` + + * ObjectHandle.ComposeFrom replaced by ObjectHandle.ComposerFrom. + Replace + ```go + attrs, err := dst.ComposeFrom(ctx, []*storage.ObjectHandle{src1, src2}, nil) + ``` + with + ```go + attrs, err := dst.ComposerFrom(src1, src2).Run(ctx) + ``` + + * ObjectHandle.Update's ObjectAttrs argument replaced by ObjectAttrsToUpdate. + Replace + ```go + attrs, err := obj.Update(ctx, &storage.ObjectAttrs{ContextType: "text/html"}) + ``` + with + ```go + attrs, err := obj.Update(ctx, storage.ObjectAttrsToUpdate{ContextType: "text/html"}) + ``` + + * ObjectHandle.WithConditions replaced by ObjectHandle.If. + Replace + ```go + obj.WithConditions(storage.Generation(gen), storage.IfMetaGenerationMatch(mgen)) + ``` + with + ```go + obj.Generation(gen).If(storage.Conditions{MetagenerationMatch: mgen}) + ``` + + Replace + ```go + obj.WithConditions(storage.IfGenerationMatch(0)) + ``` + with + ```go + obj.If(storage.Conditions{DoesNotExist: true}) + ``` + + * `storage.Done` replaced by `iterator.Done` (from package `google.golang.org/api/iterator`). + +- Package preview/logging deleted. Use logging instead. + +## v0.2.0 + +- Logging client replaced with preview version (see below). + +- New clients for some of Google's Machine Learning APIs: Vision, Speech, and +Natural Language. + +- Preview version of a new [Stackdriver Logging][cloud-logging] client in +[`cloud.google.com/go/preview/logging`](https://godoc.org/cloud.google.com/go/preview/logging). +This client uses gRPC as its transport layer, and supports log reading, sinks +and metrics. It will replace the current client at `cloud.google.com/go/logging` shortly. + diff --git a/vendor/cloud.google.com/go/CODE_OF_CONDUCT.md b/vendor/cloud.google.com/go/CODE_OF_CONDUCT.md new file mode 100644 index 00000000000..8fd1bc9c22b --- /dev/null +++ b/vendor/cloud.google.com/go/CODE_OF_CONDUCT.md @@ -0,0 +1,44 @@ +# Contributor Code of Conduct + +As contributors and maintainers of this project, +and in the interest of fostering an open and welcoming community, +we pledge to respect all people who contribute through reporting issues, +posting feature requests, updating documentation, +submitting pull requests or patches, and other activities. + +We are committed to making participation in this project +a harassment-free experience for everyone, +regardless of level of experience, gender, gender identity and expression, +sexual orientation, disability, personal appearance, +body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, +such as physical or electronic +addresses, without explicit permission +* Other unethical or unprofessional conduct. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct. +By adopting this Code of Conduct, +project maintainers commit themselves to fairly and consistently +applying these principles to every aspect of managing this project. +Project maintainers who do not follow or enforce the Code of Conduct +may be permanently removed from the project team. + +This code of conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior +may be reported by opening an issue +or contacting one or more of the project maintainers. + +This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, +available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) + diff --git a/vendor/cloud.google.com/go/CONTRIBUTING.md b/vendor/cloud.google.com/go/CONTRIBUTING.md new file mode 100644 index 00000000000..109ca5c43c2 --- /dev/null +++ b/vendor/cloud.google.com/go/CONTRIBUTING.md @@ -0,0 +1,250 @@ +# Contributing + +1. [File an issue](https://github.com/googleapis/google-cloud-go/issues/new/choose). + The issue will be used to discuss the bug or feature and should be created + before sending a CL. + +1. [Install Go](https://golang.org/dl/). + 1. Ensure that your `GOBIN` directory (by default `$(go env GOPATH)/bin`) + is in your `PATH`. + 1. Check it's working by running `go version`. + * If it doesn't work, check the install location, usually + `/usr/local/go`, is on your `PATH`. + +1. Sign one of the +[contributor license agreements](#contributor-license-agreements) below. + +1. Clone the repo: + `git clone https://github.com/googleapis/google-cloud-go` + +1. Change into the checked out source: + `cd google-cloud-go` + +1. Fork the repo. + +1. Set your fork as a remote: + `git remote add fork git@github.com:GITHUB_USERNAME/google-cloud-go.git` + +1. Make changes (see [Formatting](#formatting) and [Style](#style)), commit to + your fork. + + Commit messages should follow the + [Go project style](https://github.com/golang/go/wiki/CommitMessage). For example: + ``` + functions: add gophers codelab + ``` + +1. Send a pull request with your changes. + +1. A maintainer will review the pull request and make comments. + + Prefer adding additional commits over amending and force-pushing since it can + be difficult to follow code reviews when the commit history changes. + + Commits will be squashed when they're merged. + +## Integration Tests + +In addition to the unit tests, you may run the integration test suite. These +directions describe setting up your environment to run integration tests for +_all_ packages: note that many of these instructions may be redundant if you +intend only to run integration tests on a single package. + +#### GCP Setup + +To run the integrations tests, creation and configuration of two projects in +the Google Developers Console is required: one specifically for Firestore +integration tests, and another for all other integration tests. We'll refer to +these projects as "general project" and "Firestore project". + +After creating each project, you must [create a service account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount) +for each project. Ensure the project-level **Owner** +[IAM role](console.cloud.google.com/iam-admin/iam/project) role is added to +each service account. During the creation of the service account, you should +download the JSON credential file for use later. + +Next, ensure the following APIs are enabled in the general project: + +- BigQuery API +- BigQuery Data Transfer API +- Cloud Dataproc API +- Cloud Dataproc Control API Private +- Cloud Datastore API +- Cloud Firestore API +- Cloud Key Management Service (KMS) API +- Cloud Natural Language API +- Cloud OS Login API +- Cloud Pub/Sub API +- Cloud Resource Manager API +- Cloud Spanner API +- Cloud Speech API +- Cloud Translation API +- Cloud Video Intelligence API +- Cloud Vision API +- Compute Engine API +- Compute Engine Instance Group Manager API +- Container Registry API +- Firebase Rules API +- Google Cloud APIs +- Google Cloud Deployment Manager V2 API +- Google Cloud SQL +- Google Cloud Storage +- Google Cloud Storage JSON API +- Google Compute Engine Instance Group Updater API +- Google Compute Engine Instance Groups API +- Kubernetes Engine API +- Stackdriver Error Reporting API + +Next, create a Datastore database in the general project, and a Firestore +database in the Firestore project. + +Finally, in the general project, create an API key for the translate API: + +- Go to GCP Developer Console. +- Navigate to APIs & Services > Credentials. +- Click Create Credentials > API Key. +- Save this key for use in `GCLOUD_TESTS_API_KEY` as described below. + +#### Local Setup + +Once the two projects are created and configured, set the following environment +variables: + +- `GCLOUD_TESTS_GOLANG_PROJECT_ID`: Developers Console project's ID (e.g. +bamboo-shift-455) for the general project. +- `GCLOUD_TESTS_GOLANG_KEY`: The path to the JSON key file of the general +project's service account. +- `GCLOUD_TESTS_GOLANG_FIRESTORE_PROJECT_ID`: Developers Console project's ID +(e.g. doorway-cliff-677) for the Firestore project. +- `GCLOUD_TESTS_GOLANG_FIRESTORE_KEY`: The path to the JSON key file of the +Firestore project's service account. +- `GCLOUD_TESTS_GOLANG_KEYRING`: The full name of the keyring for the tests, +in the form +"projects/P/locations/L/keyRings/R". The creation of this is described below. +- `GCLOUD_TESTS_API_KEY`: API key for using the Translate API. +- `GCLOUD_TESTS_GOLANG_ZONE`: Compute Engine zone. + +Install the [gcloud command-line tool][gcloudcli] to your machine and use it to +create some resources used in integration tests. + +From the project's root directory: + +``` sh +# Sets the default project in your env. +$ gcloud config set project $GCLOUD_TESTS_GOLANG_PROJECT_ID + +# Authenticates the gcloud tool with your account. +$ gcloud auth login + +# Create the indexes used in the datastore integration tests. +$ gcloud datastore indexes create datastore/testdata/index.yaml + +# Creates a Google Cloud storage bucket with the same name as your test project, +# and with the Stackdriver Logging service account as owner, for the sink +# integration tests in logging. +$ gsutil mb gs://$GCLOUD_TESTS_GOLANG_PROJECT_ID +$ gsutil acl ch -g cloud-logs@google.com:O gs://$GCLOUD_TESTS_GOLANG_PROJECT_ID + +# Creates a PubSub topic for integration tests of storage notifications. +$ gcloud beta pubsub topics create go-storage-notification-test +# Next, go to the Pub/Sub dashboard in GCP console. Authorize the user +# "service-@gs-project-accounts.iam.gserviceaccount.com" +# as a publisher to that topic. + +# Creates a Spanner instance for the spanner integration tests. +$ gcloud beta spanner instances create go-integration-test --config regional-us-central1 --nodes 10 --description 'Instance for go client test' +# NOTE: Spanner instances are priced by the node-hour, so you may want to +# delete the instance after testing with 'gcloud beta spanner instances delete'. + +$ export MY_KEYRING=some-keyring-name +$ export MY_LOCATION=global +# Creates a KMS keyring, in the same location as the default location for your +# project's buckets. +$ gcloud kms keyrings create $MY_KEYRING --location $MY_LOCATION +# Creates two keys in the keyring, named key1 and key2. +$ gcloud kms keys create key1 --keyring $MY_KEYRING --location $MY_LOCATION --purpose encryption +$ gcloud kms keys create key2 --keyring $MY_KEYRING --location $MY_LOCATION --purpose encryption +# Sets the GCLOUD_TESTS_GOLANG_KEYRING environment variable. +$ export GCLOUD_TESTS_GOLANG_KEYRING=projects/$GCLOUD_TESTS_GOLANG_PROJECT_ID/locations/$MY_LOCATION/keyRings/$MY_KEYRING +# Authorizes Google Cloud Storage to encrypt and decrypt using key1. +gsutil kms authorize -p $GCLOUD_TESTS_GOLANG_PROJECT_ID -k $GCLOUD_TESTS_GOLANG_KEYRING/cryptoKeys/key1 +``` + +#### Running + +Once you've done the necessary setup, you can run the integration tests by +running: + +``` sh +$ go test -v cloud.google.com/go/... +``` + +#### Replay + +Some packages can record the RPCs during integration tests to a file for +subsequent replay. To record, pass the `-record` flag to `go test`. The +recording will be saved to the _package_`.replay` file. To replay integration +tests from a saved recording, the replay file must be present, the `-short` +flag must be passed to `go test`, and the `GCLOUD_TESTS_GOLANG_ENABLE_REPLAY` +environment variable must have a non-empty value. + +## Contributor License Agreements + +Before we can accept your pull requests you'll need to sign a Contributor +License Agreement (CLA): + +- **If you are an individual writing original source code** and **you own the +intellectual property**, then you'll need to sign an [individual CLA][indvcla]. +- **If you work for a company that wants to allow you to contribute your +work**, then you'll need to sign a [corporate CLA][corpcla]. + +You can sign these electronically (just scroll to the bottom). After that, +we'll be able to accept your pull requests. + +## Contributor Code of Conduct + +As contributors and maintainers of this project, +and in the interest of fostering an open and welcoming community, +we pledge to respect all people who contribute through reporting issues, +posting feature requests, updating documentation, +submitting pull requests or patches, and other activities. + +We are committed to making participation in this project +a harassment-free experience for everyone, +regardless of level of experience, gender, gender identity and expression, +sexual orientation, disability, personal appearance, +body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, +such as physical or electronic +addresses, without explicit permission +* Other unethical or unprofessional conduct. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct. +By adopting this Code of Conduct, +project maintainers commit themselves to fairly and consistently +applying these principles to every aspect of managing this project. +Project maintainers who do not follow or enforce the Code of Conduct +may be permanently removed from the project team. + +This code of conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior +may be reported by opening an issue +or contacting one or more of the project maintainers. + +This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, +available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) + +[gcloudcli]: https://developers.google.com/cloud/sdk/gcloud/ +[indvcla]: https://developers.google.com/open-source/cla/individual +[corpcla]: https://developers.google.com/open-source/cla/corporate diff --git a/vendor/cloud.google.com/go/README.md b/vendor/cloud.google.com/go/README.md new file mode 100644 index 00000000000..b115812c269 --- /dev/null +++ b/vendor/cloud.google.com/go/README.md @@ -0,0 +1,178 @@ +# Google Cloud Client Libraries for Go + +[![GoDoc](https://godoc.org/cloud.google.com/go?status.svg)](https://pkg.go.dev/cloud.google.com/go) + +Go packages for [Google Cloud Platform](https://cloud.google.com) services. + +``` go +import "cloud.google.com/go" +``` + +To install the packages on your system, *do not clone the repo*. Instead: + +1. Change to your project directory: + + ``` + cd /my/cloud/project + ``` +1. Get the package you want to use. Some products have their own module, so it's + best to `go get` the package(s) you want to use: + + ``` + $ go get cloud.google.com/go/firestore # Replace with the package you want to use. + ``` + +**NOTE:** Some of these packages are under development, and may occasionally +make backwards-incompatible changes. + +**NOTE:** Github repo is a mirror of [https://code.googlesource.com/gocloud](https://code.googlesource.com/gocloud). + +## Supported APIs + +Google API | Status | Package +------------------------------------------------|--------------|----------------------------------------------------------- +[Asset][cloud-asset] | stable | [`cloud.google.com/go/asset/apiv1`](https://pkg.go.dev/cloud.google.com/go/asset/v1beta) +[Automl][cloud-automl] | stable | [`cloud.google.com/go/automl/apiv1`](https://pkg.go.dev/cloud.google.com/go/automl/apiv1) +[BigQuery][cloud-bigquery] | stable | [`cloud.google.com/go/bigquery`](https://pkg.go.dev/cloud.google.com/go/bigquery) +[Bigtable][cloud-bigtable] | stable | [`cloud.google.com/go/bigtable`](https://pkg.go.dev/cloud.google.com/go/bigtable) +[Cloudbuild][cloud-build] | stable | [`cloud.google.com/go/cloudbuild/apiv1`](https://pkg.go.dev/cloud.google.com/go/cloudbuild/apiv1) +[Cloudtasks][cloud-tasks] | stable | [`cloud.google.com/go/cloudtasks/apiv2`](https://pkg.go.dev/cloud.google.com/go/cloudtasks/apiv2) +[Container][cloud-container] | stable | [`cloud.google.com/go/container/apiv1`](https://pkg.go.dev/cloud.google.com/go/container/apiv1) +[ContainerAnalysis][cloud-containeranalysis] | beta | [`cloud.google.com/go/containeranalysis/apiv1`](https://pkg.go.dev/cloud.google.com/go/containeranalysis/apiv1) +[Dataproc][cloud-dataproc] | stable | [`cloud.google.com/go/dataproc/apiv1`](https://pkg.go.dev/cloud.google.com/go/dataproc/apiv1) +[Datastore][cloud-datastore] | stable | [`cloud.google.com/go/datastore`](https://pkg.go.dev/cloud.google.com/go/datastore) +[Debugger][cloud-debugger] | stable | [`cloud.google.com/go/debugger/apiv2`](https://pkg.go.dev/cloud.google.com/go/debugger/apiv2) +[Dialogflow][cloud-dialogflow] | stable | [`cloud.google.com/go/dialogflow/apiv2`](https://pkg.go.dev/cloud.google.com/go/dialogflow/apiv2) +[Data Loss Prevention][cloud-dlp] | stable | [`cloud.google.com/go/dlp/apiv2`](https://pkg.go.dev/cloud.google.com/go/dlp/apiv2) +[ErrorReporting][cloud-errors] | alpha | [`cloud.google.com/go/errorreporting`](https://pkg.go.dev/cloud.google.com/go/errorreporting) +[Firestore][cloud-firestore] | stable | [`cloud.google.com/go/firestore`](https://pkg.go.dev/cloud.google.com/go/firestore) +[IAM][cloud-iam] | stable | [`cloud.google.com/go/iam`](https://pkg.go.dev/cloud.google.com/go/iam) +[IoT][cloud-iot] | stable | [`cloud.google.com/go/iot/apiv1`](https://pkg.go.dev/cloud.google.com/go/iot/apiv1) +[IRM][cloud-irm] | alpha | [`cloud.google.com/go/irm/apiv1alpha2`](https://pkg.go.dev/cloud.google.com/go/irm/apiv1alpha2) +[KMS][cloud-kms] | stable | [`cloud.google.com/go/kms/apiv1`](https://pkg.go.dev/cloud.google.com/go/kms/apiv1) +[Natural Language][cloud-natural-language] | stable | [`cloud.google.com/go/language/apiv1`](https://pkg.go.dev/cloud.google.com/go/language/apiv1) +[Logging][cloud-logging] | stable | [`cloud.google.com/go/logging`](https://pkg.go.dev/cloud.google.com/go/logging) +[Memorystore][cloud-memorystore] | alpha | [`cloud.google.com/go/redis/apiv1`](https://pkg.go.dev/cloud.google.com/go/redis/apiv1) +[Monitoring][cloud-monitoring] | stable | [`cloud.google.com/go/monitoring/apiv3`](https://pkg.go.dev/cloud.google.com/go/monitoring/apiv3) +[OS Login][cloud-oslogin] | stable | [`cloud.google.com/go/oslogin/apiv1`](https://pkg.go.dev/cloud.google.com/go/oslogin/apiv1) +[Pub/Sub][cloud-pubsub] | stable | [`cloud.google.com/go/pubsub`](https://pkg.go.dev/cloud.google.com/go/pubsub) +[Phishing Protection][cloud-phishingprotection] | alpha | [`cloud.google.com/go/phishingprotection/apiv1beta1`](https://pkg.go.dev/cloud.google.com/go/phishingprotection/apiv1beta1) +[reCAPTCHA Enterprise][cloud-recaptcha] | alpha | [`cloud.google.com/go/recaptchaenterprise/apiv1beta1`](https://pkg.go.dev/cloud.google.com/go/recaptchaenterprise/apiv1beta1) +[Recommender][cloud-recommender] | beta | [`cloud.google.com/go/recommender/apiv1beta1`](https://pkg.go.dev/cloud.google.com/go/recommender/apiv1beta1) +[Scheduler][cloud-scheduler] | stable | [`cloud.google.com/go/scheduler/apiv1`](https://pkg.go.dev/cloud.google.com/go/scheduler/apiv1) +[Securitycenter][cloud-securitycenter] | stable | [`cloud.google.com/go/securitycenter/apiv1`](https://pkg.go.dev/cloud.google.com/go/securitycenter/apiv1) +[Spanner][cloud-spanner] | stable | [`cloud.google.com/go/spanner`](https://pkg.go.dev/cloud.google.com/go/spanner) +[Speech][cloud-speech] | stable | [`cloud.google.com/go/speech/apiv1`](https://pkg.go.dev/cloud.google.com/go/speech/apiv1) +[Storage][cloud-storage] | stable | [`cloud.google.com/go/storage`](https://pkg.go.dev/cloud.google.com/go/storage) +[Talent][cloud-talent] | alpha | [`cloud.google.com/go/talent/apiv4beta1`](https://pkg.go.dev/cloud.google.com/go/talent/apiv4beta1) +[Text To Speech][cloud-texttospeech] | stable | [`cloud.google.com/go/texttospeech/apiv1`](https://pkg.go.dev/cloud.google.com/go/texttospeech/apiv1) +[Trace][cloud-trace] | stable | [`cloud.google.com/go/trace/apiv2`](https://pkg.go.dev/cloud.google.com/go/trace/apiv2) +[Translate][cloud-translate] | stable | [`cloud.google.com/go/translate`](https://pkg.go.dev/cloud.google.com/go/translate) +[Video Intelligence][cloud-video] | beta | [`cloud.google.com/go/videointelligence/apiv1beta2`](https://pkg.go.dev/cloud.google.com/go/videointelligence/apiv1beta2) +[Vision][cloud-vision] | stable | [`cloud.google.com/go/vision/apiv1`](https://pkg.go.dev/cloud.google.com/go/vision/apiv1) +[Webrisk][cloud-webrisk] | alpha | [`cloud.google.com/go/webrisk/apiv1beta1`](https://pkg.go.dev/cloud.google.com/go/webrisk/apiv1beta1) + +> **Alpha status**: the API is still being actively developed. As a +> result, it might change in backward-incompatible ways and is not recommended +> for production use. +> +> **Beta status**: the API is largely complete, but still has outstanding +> features and bugs to be addressed. There may be minor backwards-incompatible +> changes where necessary. +> +> **Stable status**: the API is mature and ready for production use. We will +> continue addressing bugs and feature requests. + +Documentation and examples are available at [pkg.go.dev/cloud.google.com/go](https://pkg.go.dev/cloud.google.com/go) + +## Go Versions Supported + +We support the two most recent major versions of Go. If Google App Engine uses +an older version, we support that as well. + +## Authorization + +By default, each API will use [Google Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials) +for authorization credentials used in calling the API endpoints. This will allow your +application to run in many environments without requiring explicit configuration. + +[snip]:# (auth) +```go +client, err := storage.NewClient(ctx) +``` + +To authorize using a +[JSON key file](https://cloud.google.com/iam/docs/managing-service-account-keys), +pass +[`option.WithCredentialsFile`](https://pkg.go.dev/google.golang.org/api/option#WithCredentialsFile) +to the `NewClient` function of the desired package. For example: + +[snip]:# (auth-JSON) +```go +client, err := storage.NewClient(ctx, option.WithCredentialsFile("path/to/keyfile.json")) +``` + +You can exert more control over authorization by using the +[`golang.org/x/oauth2`](https://pkg.go.dev/golang.org/x/oauth2) package to +create an `oauth2.TokenSource`. Then pass +[`option.WithTokenSource`](https://pkg.go.dev/google.golang.org/api/option#WithTokenSource) +to the `NewClient` function: +[snip]:# (auth-ts) +```go +tokenSource := ... +client, err := storage.NewClient(ctx, option.WithTokenSource(tokenSource)) +``` + +## Contributing + +Contributions are welcome. Please, see the +[CONTRIBUTING](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/CONTRIBUTING.md) +document for details. + +Please note that this project is released with a Contributor Code of Conduct. +By participating in this project you agree to abide by its terms. +See [Contributor Code of Conduct](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/CONTRIBUTING.md#contributor-code-of-conduct) +for more information. + +[cloud-asset]: https://cloud.google.com/security-command-center/docs/how-to-asset-inventory +[cloud-automl]: https://cloud.google.com/automl +[cloud-build]: https://cloud.google.com/cloud-build/ +[cloud-bigquery]: https://cloud.google.com/bigquery/ +[cloud-bigtable]: https://cloud.google.com/bigtable/ +[cloud-container]: https://cloud.google.com/containers/ +[cloud-containeranalysis]: https://cloud.google.com/container-registry/docs/container-analysis +[cloud-dataproc]: https://cloud.google.com/dataproc/ +[cloud-datastore]: https://cloud.google.com/datastore/ +[cloud-dialogflow]: https://cloud.google.com/dialogflow-enterprise/ +[cloud-debugger]: https://cloud.google.com/debugger/ +[cloud-dlp]: https://cloud.google.com/dlp/ +[cloud-errors]: https://cloud.google.com/error-reporting/ +[cloud-firestore]: https://cloud.google.com/firestore/ +[cloud-iam]: https://cloud.google.com/iam/ +[cloud-iot]: https://cloud.google.com/iot-core/ +[cloud-irm]: https://cloud.google.com/incident-response/docs/concepts +[cloud-kms]: https://cloud.google.com/kms/ +[cloud-pubsub]: https://cloud.google.com/pubsub/ +[cloud-storage]: https://cloud.google.com/storage/ +[cloud-language]: https://cloud.google.com/natural-language +[cloud-logging]: https://cloud.google.com/logging/ +[cloud-natural-language]: https://cloud.google.com/natural-language/ +[cloud-memorystore]: https://cloud.google.com/memorystore/ +[cloud-monitoring]: https://cloud.google.com/monitoring/ +[cloud-oslogin]: https://cloud.google.com/compute/docs/oslogin/rest +[cloud-phishingprotection]: https://cloud.google.com/phishing-protection/ +[cloud-securitycenter]: https://cloud.google.com/security-command-center/ +[cloud-scheduler]: https://cloud.google.com/scheduler +[cloud-spanner]: https://cloud.google.com/spanner/ +[cloud-speech]: https://cloud.google.com/speech +[cloud-talent]: https://cloud.google.com/solutions/talent-solution/ +[cloud-tasks]: https://cloud.google.com/tasks/ +[cloud-texttospeech]: https://cloud.google.com/texttospeech/ +[cloud-talent]: https://cloud.google.com/solutions/talent-solution/ +[cloud-trace]: https://cloud.google.com/trace/ +[cloud-translate]: https://cloud.google.com/translate +[cloud-recaptcha]: https://cloud.google.com/recaptcha-enterprise/ +[cloud-recommender]: https://cloud.google.com/recommendations/ +[cloud-video]: https://cloud.google.com/video-intelligence/ +[cloud-vision]: https://cloud.google.com/vision +[cloud-webrisk]: https://cloud.google.com/web-risk/ diff --git a/vendor/cloud.google.com/go/RELEASING.md b/vendor/cloud.google.com/go/RELEASING.md new file mode 100644 index 00000000000..c8c7f933527 --- /dev/null +++ b/vendor/cloud.google.com/go/RELEASING.md @@ -0,0 +1,128 @@ +# Setup from scratch + +1. [Install Go](https://golang.org/dl/). + 1. Ensure that your `GOBIN` directory (by default `$(go env GOPATH)/bin`) + is in your `PATH`. + 1. Check it's working by running `go version`. + * If it doesn't work, check the install location, usually + `/usr/local/go`, is on your `PATH`. + +1. Sign one of the +[contributor license agreements](#contributor-license-agreements) below. + +1. Clone the repo: + `git clone https://github.com/googleapis/google-cloud-go` + +1. Change into the checked out source: + `cd google-cloud-go` + +1. Fork the repo and add your fork as a secondary remote (this is necessary in + order to create PRs). + +# Which module to release? + +The Go client libraries have several modules. Each module does not strictly +correspond to a single library - they correspond to trees of directories. If a +file needs to be released, you must release the closest ancestor module. + +To see all modules: + +``` +$ cat `find . -name go.mod` | grep module +module cloud.google.com/go +module cloud.google.com/go/bigtable +module cloud.google.com/go/firestore +module cloud.google.com/go/bigquery +module cloud.google.com/go/storage +module cloud.google.com/go/datastore +module cloud.google.com/go/pubsub +module cloud.google.com/go/spanner +module cloud.google.com/go/logging +``` + +The `cloud.google.com/go` is the repository root module. Each other module is +a submodule. + +So, if you need to release a change in `bigtable/bttest/inmem.go`, the closest +ancestor module is `cloud.google.com/go/bigtable` - so you should release a new +version of the `cloud.google.com/go/bigtable` submodule. + +If you need to release a change in `asset/apiv1/asset_client.go`, the closest +ancestor module is `cloud.google.com/go` - so you should release a new version +of the `cloud.google.com/go` repository root module. Note: releasing +`cloud.google.com/go` has no impact on any of the submodules, and vice-versa. +They are released entirely independently. + +# Test failures + +If there are any test failures in the Kokoro build, releases are blocked until +the failures have been resolved. + +# How to release `cloud.google.com/go` + +1. Check for failures in the + [continuous Kokoro build](http://go/google-cloud-go-continuous). If there are any + failures in the most recent build, address them before proceeding with the + release. +1. Navigate to `~/code/gocloud/` and switch to master. +1. `git pull` +1. Run `git tag -l | grep -v beta | grep -v alpha` to see all existing releases. + The current latest tag `$CV` is the largest tag. It should look something + like `vX.Y.Z` (note: ignore all `LIB/vX.Y.Z` tags - these are tags for a + specific library, not the module root). We'll call the current version `$CV` + and the new version `$NV`. +1. On master, run `git log $CV...` to list all the changes since the last + release. NOTE: You must manually visually parse out changes to submodules [1] + (the `git log` is going to show you things in submodules, which are not going + to be part of your release). +1. Edit `CHANGES.md` to include a summary of the changes. +1. `cd internal/version && go generate && cd -` +1. Commit the changes, push to your fork, and create a PR. +1. Wait for the PR to be reviewed and merged. Once it's merged, and without + merging any other PRs in the meantime: + a. Switch to master. + b. `git pull` + c. Tag the repo with the next version: `git tag $NV`. + d. Push the tag to origin: + `git push origin $NV` +2. Update [the releases page](https://github.com/googleapis/google-cloud-go/releases) + with the new release, copying the contents of `CHANGES.md`. + +# How to release a submodule + +We have several submodules, including `cloud.google.com/go/logging`, +`cloud.google.com/go/datastore`, and so on. + +To release a submodule: + +(these instructions assume we're releasing `cloud.google.com/go/datastore` - adjust accordingly) + +1. Check for failures in the + [continuous Kokoro build](http://go/google-cloud-go-continuous). If there are any + failures in the most recent build, address them before proceeding with the + release. (This applies even if the failures are in a different submodule from the one + being released.) +1. Navigate to `~/code/gocloud/` and switch to master. +1. `git pull` +1. Run `git tag -l | grep datastore | grep -v beta | grep -v alpha` to see all + existing releases. The current latest tag `$CV` is the largest tag. It + should look something like `datastore/vX.Y.Z`. We'll call the current version + `$CV` and the new version `$NV`. +1. On master, run `git log $CV.. -- datastore/` to list all the changes to the + submodule directory since the last release. +1. Edit `datastore/CHANGES.md` to include a summary of the changes. +1. `cd internal/version && go generate && cd -` +1. Commit the changes, push to your fork, and create a PR. +1. Wait for the PR to be reviewed and merged. Once it's merged, and without + merging any other PRs in the meantime: + a. Switch to master. + b. `git pull` + c. Tag the repo with the next version: `git tag $NV`. + d. Push the tag to origin: + `git push origin $NV` +1. Update [the releases page](https://github.com/googleapis/google-cloud-go/releases) + with the new release, copying the contents of `datastore/CHANGES.md`. + +# Appendix + +1: This should get better as submodule tooling matures. diff --git a/vendor/cloud.google.com/go/compute/metadata/metadata.go b/vendor/cloud.google.com/go/compute/metadata/metadata.go index 4ff4e2f1ca6..6b13424fd97 100644 --- a/vendor/cloud.google.com/go/compute/metadata/metadata.go +++ b/vendor/cloud.google.com/go/compute/metadata/metadata.go @@ -61,25 +61,14 @@ var ( instID = &cachedValue{k: "instance/id", trim: true} ) -var ( - defaultClient = &Client{hc: &http.Client{ - Transport: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 2 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - ResponseHeaderTimeout: 2 * time.Second, - }, - }} - subscribeClient = &Client{hc: &http.Client{ - Transport: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 2 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - }, - }} -) +var defaultClient = &Client{hc: &http.Client{ + Transport: &http.Transport{ + Dial: (&net.Dialer{ + Timeout: 2 * time.Second, + KeepAlive: 30 * time.Second, + }).Dial, + }, +}} // NotDefinedError is returned when requested metadata is not defined. // @@ -151,7 +140,7 @@ func testOnGCE() bool { }() go func() { - addrs, err := net.LookupHost("metadata.google.internal") + addrs, err := net.DefaultResolver.LookupHost(ctx, "metadata.google.internal") if err != nil || len(addrs) == 0 { resc <- false return @@ -206,10 +195,9 @@ func systemInfoSuggestsGCE() bool { return name == "Google" || name == "Google Compute Engine" } -// Subscribe calls Client.Subscribe on a client designed for subscribing (one with no -// ResponseHeaderTimeout). +// Subscribe calls Client.Subscribe on the default client. func Subscribe(suffix string, fn func(v string, ok bool) error) error { - return subscribeClient.Subscribe(suffix, fn) + return defaultClient.Subscribe(suffix, fn) } // Get calls Client.Get on the default client. @@ -280,9 +268,14 @@ type Client struct { hc *http.Client } -// NewClient returns a Client that can be used to fetch metadata. All HTTP requests -// will use the given http.Client instead of the default client. +// NewClient returns a Client that can be used to fetch metadata. +// Returns the client that uses the specified http.Client for HTTP requests. +// If nil is specified, returns the default client. func NewClient(c *http.Client) *Client { + if c == nil { + return defaultClient + } + return &Client{hc: c} } @@ -304,7 +297,10 @@ func (c *Client) getETag(suffix string) (value, etag string, err error) { host = metadataIP } u := "http://" + host + "/computeMetadata/v1/" + suffix - req, _ := http.NewRequest("GET", u, nil) + req, err := http.NewRequest("GET", u, nil) + if err != nil { + return "", "", err + } req.Header.Set("Metadata-Flavor", "Google") req.Header.Set("User-Agent", userAgent) res, err := c.hc.Do(req) @@ -407,11 +403,7 @@ func (c *Client) InstanceTags() ([]string, error) { // InstanceName returns the current VM's instance ID string. func (c *Client) InstanceName() (string, error) { - host, err := c.Hostname() - if err != nil { - return "", err - } - return strings.Split(host, ".")[0], nil + return c.getTrimmed("instance/name") } // Zone returns the current VM's zone, such as "us-central1-b". diff --git a/vendor/cloud.google.com/go/doc.go b/vendor/cloud.google.com/go/doc.go new file mode 100644 index 00000000000..237d84561ce --- /dev/null +++ b/vendor/cloud.google.com/go/doc.go @@ -0,0 +1,100 @@ +// Copyright 2014 Google LLC +// +// 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 cloud is the root of the packages used to access Google Cloud +Services. See https://godoc.org/cloud.google.com/go for a full list +of sub-packages. + + +Client Options + +All clients in sub-packages are configurable via client options. These options are +described here: https://godoc.org/google.golang.org/api/option. + + +Authentication and Authorization + +All the clients in sub-packages support authentication via Google Application Default +Credentials (see https://cloud.google.com/docs/authentication/production), or +by providing a JSON key file for a Service Account. See the authentication examples +in this package for details. + + +Timeouts and Cancellation + +By default, all requests in sub-packages will run indefinitely, retrying on transient +errors when correctness allows. To set timeouts or arrange for cancellation, use +contexts. See the examples for details. + +Do not attempt to control the initial connection (dialing) of a service by setting a +timeout on the context passed to NewClient. Dialing is non-blocking, so timeouts +would be ineffective and would only interfere with credential refreshing, which uses +the same context. + + +Connection Pooling + +Connection pooling differs in clients based on their transport. Cloud +clients either rely on HTTP or gRPC transports to communicate +with Google Cloud. + +Cloud clients that use HTTP (bigquery, compute, storage, and translate) rely on the +underlying HTTP transport to cache connections for later re-use. These are cached to +the default http.MaxIdleConns and http.MaxIdleConnsPerHost settings in +http.DefaultTransport. + +For gRPC clients (all others in this repo), connection pooling is configurable. Users +of cloud client libraries may specify option.WithGRPCConnectionPool(n) as a client +option to NewClient calls. This configures the underlying gRPC connections to be +pooled and addressed in a round robin fashion. + + +Using the Libraries with Docker + +Minimal docker images like Alpine lack CA certificates. This causes RPCs to appear to +hang, because gRPC retries indefinitely. See https://github.com/googleapis/google-cloud-go/issues/928 +for more information. + + +Debugging + +To see gRPC logs, set the environment variable GRPC_GO_LOG_SEVERITY_LEVEL. See +https://godoc.org/google.golang.org/grpc/grpclog for more information. + +For HTTP logging, set the GODEBUG environment variable to "http2debug=1" or "http2debug=2". + + +Client Stability + +Clients in this repository are considered alpha or beta unless otherwise +marked as stable in the README.md. Semver is not used to communicate stability +of clients. + +Alpha and beta clients may change or go away without notice. + +Clients marked stable will maintain compatibility with future versions for as +long as we can reasonably sustain. Incompatible changes might be made in some +situations, including: + +- Security bugs may prompt backwards-incompatible changes. + +- Situations in which components are no longer feasible to maintain without +making breaking changes, including removal. + +- Parts of the client surface may be outright unstable and subject to change. +These parts of the surface will be labeled with the note, "It is EXPERIMENTAL +and subject to change or removal without notice." +*/ +package cloud // import "cloud.google.com/go" diff --git a/vendor/cloud.google.com/go/go.mod b/vendor/cloud.google.com/go/go.mod new file mode 100644 index 00000000000..5bdc67a97f7 --- /dev/null +++ b/vendor/cloud.google.com/go/go.mod @@ -0,0 +1,24 @@ +module cloud.google.com/go + +go 1.11 + +require ( + cloud.google.com/go/storage v1.10.0 + github.com/golang/mock v1.4.3 + github.com/golang/protobuf v1.4.2 + github.com/google/go-cmp v0.5.0 + github.com/google/martian/v3 v3.0.0 + github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99 + github.com/googleapis/gax-go/v2 v2.0.5 + github.com/jstemmer/go-junit-report v0.9.1 + go.opencensus.io v0.22.4 + golang.org/x/lint v0.0.0-20200302205851-738671d3881b + golang.org/x/net v0.0.0-20200707034311-ab3426394381 + golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d + golang.org/x/text v0.3.3 + golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed + google.golang.org/api v0.29.0 + google.golang.org/genproto v0.0.0-20200711021454-869866162049 + google.golang.org/grpc v1.30.0 + google.golang.org/protobuf v1.25.0 // indirect +) diff --git a/vendor/cloud.google.com/go/go.sum b/vendor/cloud.google.com/go/go.sum new file mode 100644 index 00000000000..3736901a512 --- /dev/null +++ b/vendor/cloud.google.com/go/go.sum @@ -0,0 +1,484 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go/bigquery v1.0.1 h1:hL+ycaJpVE9M7nLoiXb/Pn10ENE2u+oddxbD8uu0ZVU= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0 h1:sAbMqjY1PEQKZBWfbu6Y6bsupJ9c4QdHnzg/VvYTLcE= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0 h1:xE3CPsOgttP4ACBePh79zTKALtXwn/Edhcr16R5hMWU= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0 h1:a/O/bK/vWrYGOTFtH8di4rBxMZnmkjy+Y5LxpDwo+dA= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/datastore v1.0.0 h1:Kt+gOPPp2LEPWp8CSfxhsM8ik9CcyE/gYu+0r+RnZvM= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0 h1:/May9ojXjRkPBNVrq+oWLqmWCkr4OU5uRY29bu0mRyQ= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/pubsub v1.0.1 h1:W9tAK3E57P75u0XLLR82LZyw8VpAnhmyTOxW9qzmyj8= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0 h1:9/vpR43S4aJaROxqQHQ3nH9lfyKKV0dC3vOmnw8ebQQ= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0 h1:Lpy6hKgdcl7a3WGSfJIFmxmcdjSpP6OmBEfcOv1Y680= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1 h1:ukjixP1wl0LpnZ6LWtZJ0mX5tBmjp1f8Sqer8Z2OMUU= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= +cloud.google.com/go/storage v1.0.0 h1:VV2nUM3wwLLGh9lSABFgZMjInyUbJeaRSE64WuAIQ+4= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0 h1:RPUcBvDeYgQFMfQu1eBMq6piD1SXmLH+vK3qjewZPus= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0 h1:UDpwYIwla4jHGzZJaEJYx1tOejbgSoNqsAfHAUYe2r8= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0 h1:86K1Gel7BQ9/WmNWn7dTKMvTLFzwtBe5FNqYbi9X35g= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +cloud.google.com/go/storage v1.10.0 h1:STgFzyU5/8miMl0//zKh2aQeTyeaUH3WN9bSUiJ09bA= +cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e h1:fY5BOSpyZCqRo5OhCuC+XN+r/bBCmeuuJtjz+bCNIf8= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0 h1:28o5sBqPkBsMGnC6b4MvE2TzSr5/AT4c/1fLqVGIwlk= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1 h1:qGJ6qTW+x6xX/my+8YUVl4WNpX9B7+/l2tRsHGZ7f2s= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0 h1:Rd1kQnQu0Hq3qvJppYSG0HtP+f5LPPUiDswTLiEegLg= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3 h1:GV+pQPG/EUUbkh47niozDcADz6go/dUwhVzdUQHIVRw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0 h1:oOuy+ugB+P/kBdUnG5QaMXSIyJ1q38wWSojYCb3z5VQ= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1 h1:ZFgWrT+bLgsYPirOnRfKLYJLvssAegOj/hgyMFdJZe0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c h1:964Od4U6p2jUkFxvCydnIczKteheJEzHRToSGK3Bnlw= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0 h1:pMen7vLs8nvgEYhywH3KDWJIJTeEr2ULsVWHWYHQyBs= +github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57 h1:eqyIo2HjKhKe/mJzTG8n4VqvLXIOEG+SLdDqX7xGtkY= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f h1:Jnx61latede7zDD3DiiP4gmNz33uK0U5HDUaF0a/HVQ= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99 h1:Ak8CrdlwwXwAZxzS66vgPt4U8yUZX7JwLvVR58FN5jM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/googleapis/gax-go/v2 v2.0.4 h1:hU4mGcQI4DaAYW+IbTun+2qEZVFxK0ySjQLTbS0VQKc= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/hashicorp/golang-lru v0.5.0 h1:CL2msUPvZTLb5O648aiLNJw3hnBxN2+1Jq8rCOH9wdo= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6 h1:UDMh68UUwekSh5iP2OMhRRZJiiBccgV7axzUG8vi56c= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024 h1:rBMNdlhTLzJjJSDIjNEXX1Pz3Hmwmz91v+zycvx9PJc= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1 h1:6QPYqodiu3GuPL+7mfx+NwDdp2eTkp9IfEUpgAwUN0o= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.opencensus.io v0.21.0 h1:mU6zScU4U1YAFPHEHYk+3JC4SY7JxgkqS10ZOSyksNg= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0 h1:C9hSCOW830chIVkdja34wa6Ky+IzWllkUinR+BtRZd4= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3 h1:8sGtKOrtQqkN1bp2AtX+misvLIlOmsEsNd+9NIcPEm8= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.4 h1:LYy1Hy3MJdrCdMwwzxA/dRok4ejH+RwNGbuoD9fCjto= +go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4 h1:c2HOrn5iMezYjSlGPncknSEr/8x5LELb/ilJbXi9DEA= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522 h1:OeRHuibLsmZkFj773W4LcfAGsSxJgfPONhr8cmO+eLA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979 h1:Agxu5KLo8o7Bb634SVDnhIfpTvxmzUwhbYAzBvXt6h4= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 h1:QE6XYQK6naiK1EPAe1g/ILLxN5RBoH5xkJk3CqlMI/Y= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f h1:hX65Cu3JDlGH3uEdK7I99Ii+9kjD6mvnnpfLdEAH0x4= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422 h1:QzoH/1pFpZguR8NrRHLcO6jKqfv2zpuSqZLgdm7ZmjI= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac h1:8R1esu+8QioDxo4E4mX6bFztO+dMTM49DNAaWfO5OeY= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367 h1:0IiAsCRByjO2QjX7ZPkw5oU9x+n1YqRL802rjC0c3Aw= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b h1:Wh+f8QHJXR411sJR8/vRBTZ7YapZaRvUcLFFJhusH0k= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee h1:WG0RUwxtNT4qqaXX3DPA8zHFNm/D9xaBpxzHt1WcA/E= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c h1:uOCk1iQW6Vc18bnC13MfzScl+wdKBmM9Y9kU7Z83/lw= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5 h1:WQ8q63x+f/zpC8Ac1s9wLElVoHhm32p6tudrU72n1QA= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f h1:QBjCr1Fz5kw158VqdE9JfI9cJnl/ymnJWAdMuinqL7Y= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344 h1:vGXIOMxbNfDTk/aXCmfdLgkrSV+Z2tcbze+pEc3v5W4= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200707034311-ab3426394381 h1:VXak5I6aEWmAXeQjA+QSZzlgNrpq9mjcfDemuexIKsU= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421 h1:Wo7BWFiOk0QRFMLYMqJGFMd9CgUAcGx7V+qEg/h5IBI= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6 h1:bjcUS9ztw9kFmmIxJInhon/0Is3p+EHBKNgquIzo1OI= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a h1:WXEvlFVvvGxCJLG6REjsT03iWnKLEWinaScsxF2Vm2o= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208 h1:qwRHBd0NqMbJxfbotnDhm2ByMI1Shq4Y6oRJo21SGJA= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b h1:ag/x1USPSsqHud38I9BAC88qdNLDHHtQ4mlgQIZPPNA= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0 h1:HyfiK1WMnHj5FXFXatD+Qs1A/xC2Run6RzeW1SyHxpc= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae h1:/WDfKMnPU+m5M4xB+6x4kaepxRw6jWvR5iDRdvjHgy8= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e h1:hq86ru83GdWTlfQFZGO4nZJTU4Bs2wfHl8oFHRaXsfc= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25 h1:OKbAoGs4fGM5cPLlVQLZGYkFC8OnOfgo6tt0Smf9XhM= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121 h1:rITEj+UZHYC927n8GT97eC3zrpzXdb/voyeOuVKS46o= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2 h1:z99zHgr7hKfrUcX/KsoJk5FJfjTceCKIp96+biqP4To= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c h1:fqgJT0MGcGpPgpWU7VRdRjuArfcOvC4AoJmILihzhDg= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 h1:SvFZT6jyqRaOeXpc5h/JSfZenJ2O330aBsf7JfSUXmQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138 h1:H3uGjxCR/6Ds0Mjgyp7LMK81+LvmbvWWEnJhzk1Pi9E= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c h1:97SnQk1GYRXJgvwZ8fadnxDOWfKvkNQHH3CtZntPSrM= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0 h1:Dh6fw+p6FyRl5x/FvNswO1ji0lIGzm3KP8Y9VkS9PTE= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff h1:On1qIo75ByTwFJ4/W2bIqHcwJ9XAqtSWUs8GwRrIhtc= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d h1:lzLdP95xJmMpwQ6LUHwrc5V7js93hTiY7gkznu0BgmY= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88 h1:4j84u0sokprDu3IdSYHJMmou+YSLflMz8p7yAx/QI4g= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed h1:+qzWo37K31KxduIYaBeMqJ8MUOyTayOQKpH9aDPLMSY= +golang.org/x/tools v0.0.0-20200713011307-fd294ab11aed/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0 h1:VGGbLNyPF7dvYHhcUGYBBGCRDDK0RRJAI6KCvo0CL+E= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0 h1:jbyannxz0XFD3zdjgrSUsaJbgpH4eTrkdhRChkHPfO8= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0 h1:yzlyyDW/J0w8yNFJIhiAJy4kq74S+1DOLdawELNxFMA= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0 h1:0q95w+VuFtv4PAx4PZVQdBMmYbaCHbnfKaEiDIcVyag= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0 h1:J1Pl9P2lnmYFSJvgs70DKELqHNh8CNWXPbud4njEE2s= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0 h1:cG03eaksBzhfSIk7JRGctfp3lanklcOM/mTGvow7BbQ= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.29.0 h1:BaiDisFir8O4IJxvAabCGGkQ6yCJegNQqSVoYUNAnbk= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0 h1:KxkO13IPW4Lslp2bz+KHP2E3gtFlrIGNThxkZQ3g+4c= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1 h1:QzqyMA1tlu6CgqCDUtU9V+ZKhLFT2dkJuANu5QaxI3I= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6 h1:lMO5rYAqUxkmaj76jAkRUvt5JZgFymx/+Q5Mzfivuhc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19 h1:Lj2SnHtxkRGJDqnGaSjo+CCdIieEnwVazbOXILwQemk= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873 h1:nfPFGzJkUDX6uBmpN/pSw7MbOAWegH5QDQuoXFHedLg= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64 h1:iKtrH9Y8mcbADOP0YFaEMth7OfuHY9xHOwNj4znpM1A= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51 h1:Ex1mq5jaJof+kRnYi3SlYJ8KKa9Ao3NHyIT5XJ1gF6U= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84 h1:pSLkPbrjnPyLDYUO2VM9mDLqo2V6CFBY84lFSZAfoi4= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380 h1:xriR1EgvKfkKxIoU2uUvrMVl+H26359loFFUleSMXFo= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200711021454-869866162049 h1:YFTFpQhgvrLrmxtiIncJxFXeCyq84ixuKWVCaCAi9Oc= +google.golang.org/genproto v0.0.0-20200711021454-869866162049/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/grpc v1.19.0 h1:cfg4PD8YEdSFnm7qLV4++93WcmhH2nIUhMjhdCvl3j8= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1 h1:Hz2g2wirWK7H0qIIhGIqRGTuMwTE8HEKFnDZZ7lm9NU= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.1 h1:j6XxA85m/6txkUCHvzlV5f+HBNl/1r5cZ2A/3IEFOO8= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0 h1:rRYRFMVgRv6E0D70Skyfsr28tDXIuuPZyWGMPdMcnXg= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1 h1:zvIju4sqAGvwKspUQOhwnpcqSbzi7/H6QomNNjTL4sk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1 h1:EC2SB8S04d2r73uptxphDSUG+kTKVgjRPF+N3xpxRB4= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0 h1:M5a8xTlYTxwMn5ZFkwhRabsygDY5G8TYLyQDBxJNAxE= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0 h1:qdOKuR/EIArgaWNjetjgTzgVTAZ+S/WXVrq9HW9zimw= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0 h1:cJv5/xdbk1NnMPR1VP9+HU6gupuG9MLBoH1r6RHZ2MY= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc h1:TnonUr8u3himcMY0vSh23jFOXA+cnucl1gB6EQTReBI= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0 h1:UhZDfRO8JRQru4/+LlLE0BRKGF8L+PICnvYZmx/fEGA= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a h1:/8zB6iBfHCl1qAnEAWwGPNrUvapuy6CPla1VM0k8hQw= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a h1:LJwr7TCTghdatWv40WobzlKXc9c4s8oGa7QKJUtHhWA= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3 h1:sXmLre5bzIR6ypkjXCDI3jHPssRhc8KD/Ome589sc3U= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +rsc.io/binaryregexp v0.2.0 h1:HfqmD5MEmC0zvwBuF187nq9mdnXjXsSivRiXN7SmRkE= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/quote/v3 v3.1.0 h1:9JKUTTIUgS6kzR9mK1YuGKv6Nl+DijDNIc0ghT58FaY= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0 h1:7uVkIFmeBqHfdjD+gZwtXXI+RODJ2Wc4O7MPEh/QiW4= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/vendor/cloud.google.com/go/iam/iam.go b/vendor/cloud.google.com/go/iam/iam.go index 5232cb6730f..0a06ea2e84d 100644 --- a/vendor/cloud.google.com/go/iam/iam.go +++ b/vendor/cloud.google.com/go/iam/iam.go @@ -38,6 +38,7 @@ type client interface { Get(ctx context.Context, resource string) (*pb.Policy, error) Set(ctx context.Context, resource string, p *pb.Policy) error Test(ctx context.Context, resource string, perms []string) ([]string, error) + GetWithVersion(ctx context.Context, resource string, requestedPolicyVersion int32) (*pb.Policy, error) } // grpcClient implements client for the standard gRPC-based IAMPolicy service. @@ -57,13 +58,22 @@ var withRetry = gax.WithRetry(func() gax.Retryer { }) func (g *grpcClient) Get(ctx context.Context, resource string) (*pb.Policy, error) { + return g.GetWithVersion(ctx, resource, 1) +} + +func (g *grpcClient) GetWithVersion(ctx context.Context, resource string, requestedPolicyVersion int32) (*pb.Policy, error) { var proto *pb.Policy md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource)) ctx = insertMetadata(ctx, md) err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error { var err error - proto, err = g.c.GetIamPolicy(ctx, &pb.GetIamPolicyRequest{Resource: resource}) + proto, err = g.c.GetIamPolicy(ctx, &pb.GetIamPolicyRequest{ + Resource: resource, + Options: &pb.GetPolicyOptions{ + RequestedPolicyVersion: requestedPolicyVersion, + }, + }) return err }, withRetry) if err != nil { @@ -110,11 +120,18 @@ type Handle struct { resource string } +// A Handle3 provides IAM operations for a resource. It is similar to a Handle, but provides access to newer IAM features (e.g., conditions). +type Handle3 struct { + c client + resource string + version int32 +} + // InternalNewHandle is for use by the Google Cloud Libraries only. // // InternalNewHandle returns a Handle for resource. // The conn parameter refers to a server that must support the IAMPolicy service. -func InternalNewHandle(conn *grpc.ClientConn, resource string) *Handle { +func InternalNewHandle(conn grpc.ClientConnInterface, resource string) *Handle { return InternalNewHandleGRPCClient(pb.NewIAMPolicyClient(conn), resource) } @@ -137,6 +154,17 @@ func InternalNewHandleClient(c client, resource string) *Handle { } } +// V3 returns a Handle3, which is like Handle except it sets +// requestedPolicyVersion to 3 when retrieving a policy and policy.version to 3 +// when storing a policy. +func (h *Handle) V3() *Handle3 { + return &Handle3{ + c: h.c, + resource: h.resource, + version: 3, + } +} + // Policy retrieves the IAM policy for the resource. func (h *Handle) Policy(ctx context.Context) (*Policy, error) { proto, err := h.c.Get(ctx, h.resource) @@ -313,3 +341,47 @@ func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { } return metadata.NewOutgoingContext(ctx, out) } + +// A Policy3 is a list of Bindings representing roles granted to members. +// +// The zero Policy3 is a valid policy with no bindings. +// +// It is similar to a Policy, except a Policy3 provides direct access to the +// list of Bindings. +// +// The policy version is always set to 3. +type Policy3 struct { + etag []byte + Bindings []*pb.Binding +} + +// Policy retrieves the IAM policy for the resource. +// +// requestedPolicyVersion is always set to 3. +func (h *Handle3) Policy(ctx context.Context) (*Policy3, error) { + proto, err := h.c.GetWithVersion(ctx, h.resource, h.version) + if err != nil { + return nil, err + } + return &Policy3{ + Bindings: proto.Bindings, + etag: proto.Etag, + }, nil +} + +// SetPolicy replaces the resource's current policy with the supplied Policy. +// +// If policy was created from a prior call to Get, then the modification will +// only succeed if the policy has not changed since the Get. +func (h *Handle3) SetPolicy(ctx context.Context, policy *Policy3) error { + return h.c.Set(ctx, h.resource, &pb.Policy{ + Bindings: policy.Bindings, + Etag: policy.etag, + Version: h.version, + }) +} + +// TestPermissions returns the subset of permissions that the caller has on the resource. +func (h *Handle3) TestPermissions(ctx context.Context, permissions []string) ([]string, error) { + return h.c.Test(ctx, h.resource, permissions) +} diff --git a/vendor/cloud.google.com/go/internal/.repo-metadata-full.json b/vendor/cloud.google.com/go/internal/.repo-metadata-full.json new file mode 100644 index 00000000000..77368c01099 --- /dev/null +++ b/vendor/cloud.google.com/go/internal/.repo-metadata-full.json @@ -0,0 +1,770 @@ +{ + "cloud.google.com/go/asset/apiv1": { + "distribution_name": "cloud.google.com/go/asset/apiv1", + "description": "Cloud Asset API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/asset/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/asset/apiv1beta1": { + "distribution_name": "cloud.google.com/go/asset/apiv1beta1", + "description": "Cloud Asset API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/asset/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/asset/apiv1p2beta1": { + "distribution_name": "cloud.google.com/go/asset/apiv1p2beta1", + "description": "Cloud Asset API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/asset/apiv1p2beta1", + "release_level": "beta" + }, + "cloud.google.com/go/asset/apiv1p5beta1": { + "distribution_name": "cloud.google.com/go/asset/apiv1p5beta1", + "description": "Cloud Asset API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/asset/apiv1p5beta1", + "release_level": "beta" + }, + "cloud.google.com/go/automl/apiv1": { + "distribution_name": "cloud.google.com/go/automl/apiv1", + "description": "Cloud AutoML API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/automl/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/automl/apiv1beta1": { + "distribution_name": "cloud.google.com/go/automl/apiv1beta1", + "description": "Cloud AutoML API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/automl/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/bigquery": { + "distribution_name": "cloud.google.com/go/bigquery", + "description": "BigQuery", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/bigquery", + "release_level": "ga" + }, + "cloud.google.com/go/bigquery/connection/apiv1": { + "distribution_name": "cloud.google.com/go/bigquery/connection/apiv1", + "description": "BigQuery Connection API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/bigquery/connection/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/bigquery/connection/apiv1beta1": { + "distribution_name": "cloud.google.com/go/bigquery/connection/apiv1beta1", + "description": "BigQuery Connection API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/bigquery/connection/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/bigquery/datatransfer/apiv1": { + "distribution_name": "cloud.google.com/go/bigquery/datatransfer/apiv1", + "description": "BigQuery Data Transfer API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/bigquery/datatransfer/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/bigquery/reservation/apiv1": { + "distribution_name": "cloud.google.com/go/bigquery/reservation/apiv1", + "description": "BigQuery Reservation API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/bigquery/reservation/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/bigquery/reservation/apiv1beta1": { + "distribution_name": "cloud.google.com/go/bigquery/reservation/apiv1beta1", + "description": "BigQuery Reservation API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/bigquery/reservation/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/bigquery/storage/apiv1": { + "distribution_name": "cloud.google.com/go/bigquery/storage/apiv1", + "description": "BigQuery Storage API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/bigquery/storage/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/bigquery/storage/apiv1alpha2": { + "distribution_name": "cloud.google.com/go/bigquery/storage/apiv1alpha2", + "description": "BigQuery Storage API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/bigquery/storage/apiv1alpha2", + "release_level": "alpha" + }, + "cloud.google.com/go/bigquery/storage/apiv1beta1": { + "distribution_name": "cloud.google.com/go/bigquery/storage/apiv1beta1", + "description": "BigQuery Storage API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/bigquery/storage/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/bigquery/storage/apiv1beta2": { + "distribution_name": "cloud.google.com/go/bigquery/storage/apiv1beta2", + "description": "BigQuery Storage API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/bigquery/storage/apiv1beta2", + "release_level": "beta" + }, + "cloud.google.com/go/bigtable": { + "distribution_name": "cloud.google.com/go/bigtable", + "description": "Cloud BigTable", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/bigtable", + "release_level": "ga" + }, + "cloud.google.com/go/billing/apiv1": { + "distribution_name": "cloud.google.com/go/billing/apiv1", + "description": "Cloud Billing API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/billing/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/cloudbuild/apiv1/v2": { + "distribution_name": "cloud.google.com/go/cloudbuild/apiv1/v2", + "description": "Cloud Build API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/cloudbuild/apiv1/v2", + "release_level": "ga" + }, + "cloud.google.com/go/cloudtasks/apiv2": { + "distribution_name": "cloud.google.com/go/cloudtasks/apiv2", + "description": "Cloud Tasks API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/cloudtasks/apiv2", + "release_level": "ga" + }, + "cloud.google.com/go/cloudtasks/apiv2beta2": { + "distribution_name": "cloud.google.com/go/cloudtasks/apiv2beta2", + "description": "Cloud Tasks API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/cloudtasks/apiv2beta2", + "release_level": "beta" + }, + "cloud.google.com/go/cloudtasks/apiv2beta3": { + "distribution_name": "cloud.google.com/go/cloudtasks/apiv2beta3", + "description": "Cloud Tasks API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/cloudtasks/apiv2beta3", + "release_level": "beta" + }, + "cloud.google.com/go/container/apiv1": { + "distribution_name": "cloud.google.com/go/container/apiv1", + "description": "Kubernetes Engine API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/container/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/containeranalysis/apiv1beta1": { + "distribution_name": "cloud.google.com/go/containeranalysis/apiv1beta1", + "description": "Container Analysis API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/containeranalysis/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/datacatalog/apiv1": { + "distribution_name": "cloud.google.com/go/datacatalog/apiv1", + "description": "Google Cloud Data Catalog API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/datacatalog/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/datacatalog/apiv1beta1": { + "distribution_name": "cloud.google.com/go/datacatalog/apiv1beta1", + "description": "Google Cloud Data Catalog API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/datacatalog/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/dataproc/apiv1": { + "distribution_name": "cloud.google.com/go/dataproc/apiv1", + "description": "Cloud Dataproc API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/dataproc/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/dataproc/apiv1beta2": { + "distribution_name": "cloud.google.com/go/dataproc/apiv1beta2", + "description": "Cloud Dataproc API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/dataproc/apiv1beta2", + "release_level": "beta" + }, + "cloud.google.com/go/datastore": { + "distribution_name": "cloud.google.com/go/datastore", + "description": "Cloud Datastore", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/datastore", + "release_level": "ga" + }, + "cloud.google.com/go/datastore/admin/apiv1": { + "distribution_name": "cloud.google.com/go/datastore/admin/apiv1", + "description": "Cloud Datastore API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/datastore/admin/apiv1", + "release_level": "alpha" + }, + "cloud.google.com/go/debugger/apiv2": { + "distribution_name": "cloud.google.com/go/debugger/apiv2", + "description": "Stackdriver Debugger API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/debugger/apiv2", + "release_level": "ga" + }, + "cloud.google.com/go/dialogflow/apiv2": { + "distribution_name": "cloud.google.com/go/dialogflow/apiv2", + "description": "Dialogflow API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/dialogflow/apiv2", + "release_level": "ga" + }, + "cloud.google.com/go/dlp/apiv2": { + "distribution_name": "cloud.google.com/go/dlp/apiv2", + "description": "Cloud Data Loss Prevention (DLP) API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/dlp/apiv2", + "release_level": "ga" + }, + "cloud.google.com/go/errorreporting": { + "distribution_name": "cloud.google.com/go/errorreporting", + "description": "Stackdriver Error Reporting API", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/errorreporting", + "release_level": "beta" + }, + "cloud.google.com/go/errorreporting/apiv1beta1": { + "distribution_name": "cloud.google.com/go/errorreporting/apiv1beta1", + "description": "Stackdriver Error Reporting API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/errorreporting/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/firestore": { + "distribution_name": "cloud.google.com/go/firestore", + "description": "Cloud Firestore API", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/firestore", + "release_level": "ga" + }, + "cloud.google.com/go/firestore/apiv1": { + "distribution_name": "cloud.google.com/go/firestore/apiv1", + "description": "Cloud Firestore API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/firestore/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/firestore/apiv1/admin": { + "distribution_name": "cloud.google.com/go/firestore/apiv1/admin", + "description": "Google Cloud Firestore Admin API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/firestore/apiv1/admin", + "release_level": "ga" + }, + "cloud.google.com/go/gaming/apiv1beta": { + "distribution_name": "cloud.google.com/go/gaming/apiv1beta", + "description": "", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/gaming/apiv1beta", + "release_level": "beta" + }, + "cloud.google.com/go/iam": { + "distribution_name": "cloud.google.com/go/iam", + "description": "Cloud IAM", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/iam", + "release_level": "ga" + }, + "cloud.google.com/go/iam/credentials/apiv1": { + "distribution_name": "cloud.google.com/go/iam/credentials/apiv1", + "description": "IAM Service Account Credentials API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/iam/credentials/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/iot/apiv1": { + "distribution_name": "cloud.google.com/go/iot/apiv1", + "description": "Cloud IoT API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/iot/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/kms/apiv1": { + "distribution_name": "cloud.google.com/go/kms/apiv1", + "description": "Cloud Key Management Service (KMS) API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/kms/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/language/apiv1": { + "distribution_name": "cloud.google.com/go/language/apiv1", + "description": "Cloud Natural Language API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/language/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/language/apiv1beta2": { + "distribution_name": "cloud.google.com/go/language/apiv1beta2", + "description": "Cloud Natural Language API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/language/apiv1beta2", + "release_level": "beta" + }, + "cloud.google.com/go/logging": { + "distribution_name": "cloud.google.com/go/logging", + "description": "Stackdriver Logging API", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/logging", + "release_level": "ga" + }, + "cloud.google.com/go/logging/apiv2": { + "distribution_name": "cloud.google.com/go/logging/apiv2", + "description": "Cloud Logging API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/logging/apiv2", + "release_level": "ga" + }, + "cloud.google.com/go/longrunning/autogen": { + "distribution_name": "cloud.google.com/go/longrunning/autogen", + "description": "Long Running Operations API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/longrunning/autogen", + "release_level": "alpha" + }, + "cloud.google.com/go/memcache/apiv1beta2": { + "distribution_name": "cloud.google.com/go/memcache/apiv1beta2", + "description": "Cloud Memorystore for Memcached API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/memcache/apiv1beta2", + "release_level": "beta" + }, + "cloud.google.com/go/monitoring/apiv3/v2": { + "distribution_name": "cloud.google.com/go/monitoring/apiv3/v2", + "description": "Cloud Monitoring API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/monitoring/apiv3/v2", + "release_level": "ga" + }, + "cloud.google.com/go/monitoring/dashboard/apiv1": { + "distribution_name": "cloud.google.com/go/monitoring/dashboard/apiv1", + "description": "", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/monitoring/dashboard/apiv1", + "release_level": "beta" + }, + "cloud.google.com/go/osconfig/agentendpoint/apiv1": { + "distribution_name": "cloud.google.com/go/osconfig/agentendpoint/apiv1", + "description": "Cloud OS Config API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/osconfig/agentendpoint/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/osconfig/agentendpoint/apiv1beta": { + "distribution_name": "cloud.google.com/go/osconfig/agentendpoint/apiv1beta", + "description": "Cloud OS Config API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/osconfig/agentendpoint/apiv1beta", + "release_level": "beta" + }, + "cloud.google.com/go/osconfig/apiv1": { + "distribution_name": "cloud.google.com/go/osconfig/apiv1", + "description": "Cloud OS Config API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/osconfig/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/osconfig/apiv1beta": { + "distribution_name": "cloud.google.com/go/osconfig/apiv1beta", + "description": "Cloud OS Config API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/osconfig/apiv1beta", + "release_level": "beta" + }, + "cloud.google.com/go/oslogin/apiv1": { + "distribution_name": "cloud.google.com/go/oslogin/apiv1", + "description": "Cloud OS Login API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/oslogin/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/oslogin/apiv1beta": { + "distribution_name": "cloud.google.com/go/oslogin/apiv1beta", + "description": "Cloud OS Login API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/oslogin/apiv1beta", + "release_level": "beta" + }, + "cloud.google.com/go/phishingprotection/apiv1beta1": { + "distribution_name": "cloud.google.com/go/phishingprotection/apiv1beta1", + "description": "Phishing Protection API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/phishingprotection/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/policytroubleshooter/apiv1": { + "distribution_name": "cloud.google.com/go/policytroubleshooter/apiv1", + "description": "Policy Troubleshooter API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/policytroubleshooter/apiv1", + "release_level": "beta" + }, + "cloud.google.com/go/pubsub": { + "distribution_name": "cloud.google.com/go/pubsub", + "description": "Cloud PubSub", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/pubsub", + "release_level": "ga" + }, + "cloud.google.com/go/pubsub/apiv1": { + "distribution_name": "cloud.google.com/go/pubsub/apiv1", + "description": "Cloud Pub/Sub API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/pubsub/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/recaptchaenterprise/apiv1": { + "distribution_name": "cloud.google.com/go/recaptchaenterprise/apiv1", + "description": "reCAPTCHA Enterprise API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/recaptchaenterprise/apiv1", + "release_level": "beta" + }, + "cloud.google.com/go/recaptchaenterprise/apiv1beta1": { + "distribution_name": "cloud.google.com/go/recaptchaenterprise/apiv1beta1", + "description": "reCAPTCHA Enterprise API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/recaptchaenterprise/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/recommender/apiv1": { + "distribution_name": "cloud.google.com/go/recommender/apiv1", + "description": "Recommender API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/recommender/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/recommender/apiv1beta1": { + "distribution_name": "cloud.google.com/go/recommender/apiv1beta1", + "description": "Recommender API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/recommender/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/redis/apiv1": { + "distribution_name": "cloud.google.com/go/redis/apiv1", + "description": "Google Cloud Memorystore for Redis API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/redis/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/redis/apiv1beta1": { + "distribution_name": "cloud.google.com/go/redis/apiv1beta1", + "description": "Google Cloud Memorystore for Redis API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/redis/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/rpcreplay": { + "distribution_name": "cloud.google.com/go/rpcreplay", + "description": "RPC Replay", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/rpcreplay", + "release_level": "ga" + }, + "cloud.google.com/go/scheduler/apiv1": { + "distribution_name": "cloud.google.com/go/scheduler/apiv1", + "description": "Cloud Scheduler API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/scheduler/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/scheduler/apiv1beta1": { + "distribution_name": "cloud.google.com/go/scheduler/apiv1beta1", + "description": "Cloud Scheduler API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/scheduler/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/secretmanager/apiv1": { + "distribution_name": "cloud.google.com/go/secretmanager/apiv1", + "description": "Secret Manager API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/secretmanager/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/secretmanager/apiv1beta1": { + "distribution_name": "cloud.google.com/go/secretmanager/apiv1beta1", + "description": "Secret Manager API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/secretmanager/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/securitycenter/apiv1": { + "distribution_name": "cloud.google.com/go/securitycenter/apiv1", + "description": "Security Command Center API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/securitycenter/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/securitycenter/apiv1beta1": { + "distribution_name": "cloud.google.com/go/securitycenter/apiv1beta1", + "description": "Cloud Security Command Center API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/securitycenter/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/securitycenter/apiv1p1beta1": { + "distribution_name": "cloud.google.com/go/securitycenter/apiv1p1beta1", + "description": "Security Command Center API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/securitycenter/apiv1p1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/securitycenter/settings/apiv1beta1": { + "distribution_name": "cloud.google.com/go/securitycenter/settings/apiv1beta1", + "description": "Cloud Security Command Center API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/securitycenter/settings/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/servicedirectory/apiv1beta1": { + "distribution_name": "cloud.google.com/go/servicedirectory/apiv1beta1", + "description": "Service Directory API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/servicedirectory/apiv1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/spanner": { + "distribution_name": "cloud.google.com/go/spanner", + "description": "Cloud Spanner", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/spanner", + "release_level": "ga" + }, + "cloud.google.com/go/spanner/admin/database/apiv1": { + "distribution_name": "cloud.google.com/go/spanner/admin/database/apiv1", + "description": "Cloud Spanner Database Admin API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/spanner/admin/database/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/spanner/admin/instance/apiv1": { + "distribution_name": "cloud.google.com/go/spanner/admin/instance/apiv1", + "description": "Cloud Spanner Instance Admin API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/spanner/admin/instance/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/spanner/apiv1": { + "distribution_name": "cloud.google.com/go/spanner/apiv1", + "description": "Cloud Spanner API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/spanner/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/speech/apiv1": { + "distribution_name": "cloud.google.com/go/speech/apiv1", + "description": "Cloud Speech-to-Text API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/speech/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/speech/apiv1p1beta1": { + "distribution_name": "cloud.google.com/go/speech/apiv1p1beta1", + "description": "Cloud Speech-to-Text API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/speech/apiv1p1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/storage": { + "distribution_name": "cloud.google.com/go/storage", + "description": "Cloud Storage (GCS)", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/storage", + "release_level": "ga" + }, + "cloud.google.com/go/talent/apiv4beta1": { + "distribution_name": "cloud.google.com/go/talent/apiv4beta1", + "description": "Cloud Talent Solution API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/talent/apiv4beta1", + "release_level": "beta" + }, + "cloud.google.com/go/texttospeech/apiv1": { + "distribution_name": "cloud.google.com/go/texttospeech/apiv1", + "description": "Cloud Text-to-Speech API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/texttospeech/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/trace": { + "distribution_name": "cloud.google.com/go/trace", + "description": "Stackdriver Trace", + "language": "Go", + "client_library_type": "manual", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/trace", + "release_level": "ga" + }, + "cloud.google.com/go/trace/apiv1": { + "distribution_name": "cloud.google.com/go/trace/apiv1", + "description": "Stackdriver Trace API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/trace/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/trace/apiv2": { + "distribution_name": "cloud.google.com/go/trace/apiv2", + "description": "Stackdriver Trace API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/trace/apiv2", + "release_level": "ga" + }, + "cloud.google.com/go/translate/apiv3": { + "distribution_name": "cloud.google.com/go/translate/apiv3", + "description": "Cloud Translation API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/translate/apiv3", + "release_level": "ga" + }, + "cloud.google.com/go/videointelligence/apiv1": { + "distribution_name": "cloud.google.com/go/videointelligence/apiv1", + "description": "Cloud Video Intelligence API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/videointelligence/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/videointelligence/apiv1beta2": { + "distribution_name": "cloud.google.com/go/videointelligence/apiv1beta2", + "description": "Google Cloud Video Intelligence API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/videointelligence/apiv1beta2", + "release_level": "beta" + }, + "cloud.google.com/go/vision/apiv1": { + "distribution_name": "cloud.google.com/go/vision/apiv1", + "description": "Cloud Vision API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/vision/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/vision/apiv1p1beta1": { + "distribution_name": "cloud.google.com/go/vision/apiv1p1beta1", + "description": "Cloud Vision API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/vision/apiv1p1beta1", + "release_level": "beta" + }, + "cloud.google.com/go/webrisk/apiv1": { + "distribution_name": "cloud.google.com/go/webrisk/apiv1", + "description": "Web Risk API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/webrisk/apiv1", + "release_level": "ga" + }, + "cloud.google.com/go/webrisk/apiv1beta1": { + "distribution_name": "cloud.google.com/go/webrisk/apiv1beta1", + "description": "Web Risk API", + "language": "Go", + "client_library_type": "generated", + "docs_url": "https://pkg.go.dev/cloud.google.com/go/webrisk/apiv1beta1", + "release_level": "beta" + } +} diff --git a/vendor/cloud.google.com/go/internal/README.md b/vendor/cloud.google.com/go/internal/README.md new file mode 100644 index 00000000000..8857c8f6fea --- /dev/null +++ b/vendor/cloud.google.com/go/internal/README.md @@ -0,0 +1,18 @@ +# Internal + +This directory contains internal code for cloud.google.com/go packages. + +## .repo-metadata-full.json + +`.repo-metadata-full.json` contains metadata about the packages in this repo. It +is generated by `internal/gapicgen/generator`. It's processed by external tools +to build lists of all of the packages. + +Don't make breaking changes to the format without consulting with the external +tools. + +One day, we may want to create individual `.repo-metadata.json` files next to +each package, which is the pattern followed by some other languages. External +tools would then talk to pkg.go.dev or some other service to get the overall +list of packages and use the `.repo-metadata.json` files to get the additional +metadata required. For now, `.repo-metadata-full.json` includes everything. \ No newline at end of file diff --git a/vendor/cloud.google.com/go/internal/version/version.go b/vendor/cloud.google.com/go/internal/version/version.go index d291921b18f..3328019a3af 100644 --- a/vendor/cloud.google.com/go/internal/version/version.go +++ b/vendor/cloud.google.com/go/internal/version/version.go @@ -26,7 +26,7 @@ import ( // Repo is the current version of the client libraries in this // repo. It should be a date in YYYYMMDD format. -const Repo = "20190802" +const Repo = "20200706" // Go returns the Go runtime version. The returned string // has no whitespace. diff --git a/vendor/cloud.google.com/go/storage/CHANGES.md b/vendor/cloud.google.com/go/storage/CHANGES.md new file mode 100644 index 00000000000..f6d57be5085 --- /dev/null +++ b/vendor/cloud.google.com/go/storage/CHANGES.md @@ -0,0 +1,83 @@ +# Changes + +## v1.10.0 +- Bump dependency on google.golang.org/api to capture changes to retry logic + which will make retries on writes more resilient. +- Improve documentation for Writer.ChunkSize. +- Fix a bug in lifecycle to allow callers to clear lifecycle rules on a bucket. + +## v1.9.0 +- Add retry for transient network errors on most operations (with the exception + of writes). +- Bump dependency for google.golang.org/api to capture a change in the default + HTTP transport which will improve performance for reads under heavy load. +- Add CRC32C checksum validation option to Composer. + +## v1.8.0 +- Add support for V4 signed post policies. + +## v1.7.0 +- V4 signed URL support: + - Add support for bucket-bound domains and virtual hosted style URLs. + - Add support for query parameters in the signature. + - Fix text encoding to align with standards. +- Add the object name to query parameters for write calls. +- Fix retry behavior when reading files with Content-Encoding gzip. +- Fix response header in reader. +- New code examples: + - Error handling for `ObjectHandle` preconditions. + - Existence checks for buckets and objects. + +## v1.6.0 + +- Updated option handling: + - Don't drop custom scopes (#1756) + - Don't drop port in provided endpoint (#1737) + +## v1.5.0 + +- Honor WithEndpoint client option for reads as well as writes. +- Add archive storage class to docs. +- Make fixes to storage benchwrapper. + +## v1.4.0 + +- When listing objects in a bucket, allow callers to specify which attributes + are queried. This allows for performance optimization. + +## v1.3.0 + +- Use `storage.googleapis.com/storage/v1` by default for GCS requests + instead of `www.googleapis.com/storage/v1`. + +## v1.2.1 + +- Fixed a bug where UniformBucketLevelAccess and BucketPolicyOnly were not + being sent in all cases. + +## v1.2.0 + +- Add support for UniformBucketLevelAccess. This configures access checks + to use only bucket-level IAM policies. + See: https://godoc.org/cloud.google.com/go/storage#UniformBucketLevelAccess. +- Fix userAgent to use correct version. + +## v1.1.2 + +- Fix memory leak in BucketIterator and ObjectIterator. + +## v1.1.1 + +- Send BucketPolicyOnly even when it's disabled. + +## v1.1.0 + +- Performance improvements for ObjectIterator and BucketIterator. +- Fix Bucket.ObjectIterator size calculation checks. +- Added HMACKeyOptions to all the methods which allows for options such as + UserProject to be set per invocation and optionally be used. + +## v1.0.0 + +This is the first tag to carve out storage as its own module. See: +https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository. diff --git a/vendor/cloud.google.com/go/storage/LICENSE b/vendor/cloud.google.com/go/storage/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/vendor/cloud.google.com/go/storage/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/cloud.google.com/go/storage/bucket.go b/vendor/cloud.google.com/go/storage/bucket.go index 07c470d3e0d..478482645fa 100644 --- a/vendor/cloud.google.com/go/storage/bucket.go +++ b/vendor/cloud.google.com/go/storage/bucket.go @@ -232,10 +232,18 @@ type BucketAttrs struct { // ACL is the list of access control rules on the bucket. ACL []ACLRule - // BucketPolicyOnly configures access checks to use only bucket-level IAM - // policies. + // BucketPolicyOnly is an alias for UniformBucketLevelAccess. Use of + // UniformBucketLevelAccess is recommended above the use of this field. + // Setting BucketPolicyOnly.Enabled OR UniformBucketLevelAccess.Enabled to + // true, will enable UniformBucketLevelAccess. BucketPolicyOnly BucketPolicyOnly + // UniformBucketLevelAccess configures access checks to use only bucket-level IAM + // policies and ignore any ACL rules for the bucket. + // See https://cloud.google.com/storage/docs/uniform-bucket-level-access + // for more information. + UniformBucketLevelAccess UniformBucketLevelAccess + // DefaultObjectACL is the list of access controls to // apply to new objects when no object ACL is provided. DefaultObjectACL []ACLRule @@ -267,14 +275,10 @@ type BucketAttrs struct { // StorageClass is the default storage class of the bucket. This defines // how objects in the bucket are stored and determines the SLA - // and the cost of storage. Typical values are "MULTI_REGIONAL", - // "REGIONAL", "NEARLINE", "COLDLINE", "STANDARD" and - // "DURABLE_REDUCED_AVAILABILITY". Defaults to "STANDARD", which - // is equivalent to "MULTI_REGIONAL" or "REGIONAL" depending on - // the bucket's location settings. - // - // "DURABLE_REDUCED_AVAILABILITY", "MULTI_REGIONAL" and "REGIONAL" - // are considered legacy storage classes. + // and the cost of storage. Typical values are "STANDARD", "NEARLINE", + // "COLDLINE" and "ARCHIVE". Defaults to "STANDARD". + // See https://cloud.google.com/storage/docs/storage-classes for all + // valid values. StorageClass string // Created is the creation time of the bucket. @@ -327,8 +331,8 @@ type BucketAttrs struct { LocationType string } -// BucketPolicyOnly configures access checks to use only bucket-level IAM -// policies. +// BucketPolicyOnly is an alias for UniformBucketLevelAccess. +// Use of UniformBucketLevelAccess is preferred above BucketPolicyOnly. type BucketPolicyOnly struct { // Enabled specifies whether access checks use only bucket-level IAM // policies. Enabled may be disabled until the locked time. @@ -338,6 +342,17 @@ type BucketPolicyOnly struct { LockedTime time.Time } +// UniformBucketLevelAccess configures access checks to use only bucket-level IAM +// policies. +type UniformBucketLevelAccess struct { + // Enabled specifies whether access checks use only bucket-level IAM + // policies. Enabled may be disabled until the locked time. + Enabled bool + // LockedTime specifies the deadline for changing Enabled from true to + // false. + LockedTime time.Time +} + // Lifecycle is the lifecycle configuration for objects in the bucket. type Lifecycle struct { Rules []LifecycleRule @@ -446,8 +461,7 @@ type LifecycleCondition struct { // MatchesStorageClasses is the condition matching the object's storage // class. // - // Values include "MULTI_REGIONAL", "REGIONAL", "NEARLINE", "COLDLINE", - // "STANDARD", and "DURABLE_REDUCED_AVAILABILITY". + // Values include "STANDARD", "NEARLINE", "COLDLINE" and "ARCHIVE". MatchesStorageClasses []string // NumNewerVersions is the condition matching objects with a number of newer versions. @@ -495,26 +509,27 @@ func newBucket(b *raw.Bucket) (*BucketAttrs, error) { return nil, err } return &BucketAttrs{ - Name: b.Name, - Location: b.Location, - MetaGeneration: b.Metageneration, - DefaultEventBasedHold: b.DefaultEventBasedHold, - StorageClass: b.StorageClass, - Created: convertTime(b.TimeCreated), - VersioningEnabled: b.Versioning != nil && b.Versioning.Enabled, - ACL: toBucketACLRules(b.Acl), - DefaultObjectACL: toObjectACLRules(b.DefaultObjectAcl), - Labels: b.Labels, - RequesterPays: b.Billing != nil && b.Billing.RequesterPays, - Lifecycle: toLifecycle(b.Lifecycle), - RetentionPolicy: rp, - CORS: toCORS(b.Cors), - Encryption: toBucketEncryption(b.Encryption), - Logging: toBucketLogging(b.Logging), - Website: toBucketWebsite(b.Website), - BucketPolicyOnly: toBucketPolicyOnly(b.IamConfiguration), - Etag: b.Etag, - LocationType: b.LocationType, + Name: b.Name, + Location: b.Location, + MetaGeneration: b.Metageneration, + DefaultEventBasedHold: b.DefaultEventBasedHold, + StorageClass: b.StorageClass, + Created: convertTime(b.TimeCreated), + VersioningEnabled: b.Versioning != nil && b.Versioning.Enabled, + ACL: toBucketACLRules(b.Acl), + DefaultObjectACL: toObjectACLRules(b.DefaultObjectAcl), + Labels: b.Labels, + RequesterPays: b.Billing != nil && b.Billing.RequesterPays, + Lifecycle: toLifecycle(b.Lifecycle), + RetentionPolicy: rp, + CORS: toCORS(b.Cors), + Encryption: toBucketEncryption(b.Encryption), + Logging: toBucketLogging(b.Logging), + Website: toBucketWebsite(b.Website), + BucketPolicyOnly: toBucketPolicyOnly(b.IamConfiguration), + UniformBucketLevelAccess: toUniformBucketLevelAccess(b.IamConfiguration), + Etag: b.Etag, + LocationType: b.LocationType, }, nil } @@ -540,9 +555,9 @@ func (b *BucketAttrs) toRawBucket() *raw.Bucket { bb = &raw.BucketBilling{RequesterPays: true} } var bktIAM *raw.BucketIamConfiguration - if b.BucketPolicyOnly.Enabled { + if b.UniformBucketLevelAccess.Enabled || b.BucketPolicyOnly.Enabled { bktIAM = &raw.BucketIamConfiguration{ - BucketPolicyOnly: &raw.BucketIamConfigurationBucketPolicyOnly{ + UniformBucketLevelAccess: &raw.BucketIamConfigurationUniformBucketLevelAccess{ Enabled: true, }, } @@ -609,10 +624,20 @@ type BucketAttrsToUpdate struct { // newly created objects in this bucket. DefaultEventBasedHold optional.Bool - // BucketPolicyOnly configures access checks to use only bucket-level IAM - // policies. + // BucketPolicyOnly is an alias for UniformBucketLevelAccess. Use of + // UniformBucketLevelAccess is recommended above the use of this field. + // Setting BucketPolicyOnly.Enabled OR UniformBucketLevelAccess.Enabled to + // true, will enable UniformBucketLevelAccess. If both BucketPolicyOnly and + // UniformBucketLevelAccess are set, the value of UniformBucketLevelAccess + // will take precedence. BucketPolicyOnly *BucketPolicyOnly + // UniformBucketLevelAccess configures access checks to use only bucket-level IAM + // policies and ignore any ACL rules for the bucket. + // See https://cloud.google.com/storage/docs/uniform-bucket-level-access + // for more information. + UniformBucketLevelAccess *UniformBucketLevelAccess + // If set, updates the retention policy of the bucket. Using // RetentionPolicy.RetentionPeriod = 0 will delete the existing policy. // @@ -701,8 +726,17 @@ func (ua *BucketAttrsToUpdate) toRawBucket() *raw.Bucket { } if ua.BucketPolicyOnly != nil { rb.IamConfiguration = &raw.BucketIamConfiguration{ - BucketPolicyOnly: &raw.BucketIamConfigurationBucketPolicyOnly{ - Enabled: ua.BucketPolicyOnly.Enabled, + UniformBucketLevelAccess: &raw.BucketIamConfigurationUniformBucketLevelAccess{ + Enabled: ua.BucketPolicyOnly.Enabled, + ForceSendFields: []string{"Enabled"}, + }, + } + } + if ua.UniformBucketLevelAccess != nil { + rb.IamConfiguration = &raw.BucketIamConfiguration{ + UniformBucketLevelAccess: &raw.BucketIamConfigurationUniformBucketLevelAccess{ + Enabled: ua.UniformBucketLevelAccess.Enabled, + ForceSendFields: []string{"Enabled"}, }, } } @@ -716,6 +750,7 @@ func (ua *BucketAttrsToUpdate) toRawBucket() *raw.Bucket { } if ua.Lifecycle != nil { rb.Lifecycle = toRawLifecycle(*ua.Lifecycle) + rb.ForceSendFields = append(rb.ForceSendFields, "Lifecycle") } if ua.Logging != nil { if *ua.Logging == (BucketLogging{}) { @@ -902,7 +937,7 @@ func toCORS(rc []*raw.BucketCors) []CORS { func toRawLifecycle(l Lifecycle) *raw.BucketLifecycle { var rl raw.BucketLifecycle if len(l.Rules) == 0 { - return nil + rl.ForceSendFields = []string{"Rule"} } for _, r := range l.Rules { rr := &raw.BucketLifecycleRule{ @@ -952,12 +987,11 @@ func toLifecycle(rl *raw.BucketLifecycle) Lifecycle { }, } - switch { - case rr.Condition.IsLive == nil: + if rr.Condition.IsLive == nil { r.Condition.Liveness = LiveAndArchived - case *rr.Condition.IsLive == true: + } else if *rr.Condition.IsLive { r.Condition.Liveness = Live - case *rr.Condition.IsLive == false: + } else { r.Condition.Liveness = Archived } @@ -1041,8 +1075,26 @@ func toBucketPolicyOnly(b *raw.BucketIamConfiguration) BucketPolicyOnly { } } +func toUniformBucketLevelAccess(b *raw.BucketIamConfiguration) UniformBucketLevelAccess { + if b == nil || b.UniformBucketLevelAccess == nil || !b.UniformBucketLevelAccess.Enabled { + return UniformBucketLevelAccess{} + } + lt, err := time.Parse(time.RFC3339, b.UniformBucketLevelAccess.LockedTime) + if err != nil { + return UniformBucketLevelAccess{ + Enabled: true, + } + } + return UniformBucketLevelAccess{ + Enabled: true, + LockedTime: lt, + } +} + // Objects returns an iterator over the objects in the bucket that match the Query q. // If q is nil, no filtering is done. +// +// Note: The returned iterator is not safe for concurrent operations without explicit synchronization. func (b *BucketHandle) Objects(ctx context.Context, q *Query) *ObjectIterator { it := &ObjectIterator{ ctx: ctx, @@ -1059,6 +1111,8 @@ func (b *BucketHandle) Objects(ctx context.Context, q *Query) *ObjectIterator { } // An ObjectIterator is an iterator over ObjectAttrs. +// +// Note: This iterator is not safe for concurrent operations without explicit synchronization. type ObjectIterator struct { ctx context.Context bucket *BucketHandle @@ -1069,6 +1123,8 @@ type ObjectIterator struct { } // PageInfo supports pagination. See the google.golang.org/api/iterator package for details. +// +// Note: This method is not safe for concurrent operations without explicit synchronization. func (it *ObjectIterator) PageInfo() *iterator.PageInfo { return it.pageInfo } // Next returns the next result. Its second return value is iterator.Done if @@ -1078,6 +1134,8 @@ func (it *ObjectIterator) PageInfo() *iterator.PageInfo { return it.pageInfo } // If Query.Delimiter is non-empty, some of the ObjectAttrs returned by Next will // have a non-empty Prefix field, and a zero value for all other fields. These // represent prefixes. +// +// Note: This method is not safe for concurrent operations without explicit synchronization. func (it *ObjectIterator) Next() (*ObjectAttrs, error) { if err := it.nextFunc(); err != nil { return nil, err @@ -1094,6 +1152,9 @@ func (it *ObjectIterator) fetch(pageSize int, pageToken string) (string, error) req.Delimiter(it.query.Delimiter) req.Prefix(it.query.Prefix) req.Versions(it.query.Versions) + if len(it.query.fieldSelection) > 0 { + req.Fields("nextPageToken", googleapi.Field(it.query.fieldSelection)) + } req.PageToken(pageToken) if it.bucket.userProject != "" { req.UserProject(it.bucket.userProject) @@ -1126,6 +1187,8 @@ func (it *ObjectIterator) fetch(pageSize int, pageToken string) (string, error) // optionally set the iterator's Prefix field to restrict the list to buckets // whose names begin with the prefix. By default, all buckets in the project // are returned. +// +// Note: The returned iterator is not safe for concurrent operations without explicit synchronization. func (c *Client) Buckets(ctx context.Context, projectID string) *BucketIterator { it := &BucketIterator{ ctx: ctx, @@ -1136,10 +1199,13 @@ func (c *Client) Buckets(ctx context.Context, projectID string) *BucketIterator it.fetch, func() int { return len(it.buckets) }, func() interface{} { b := it.buckets; it.buckets = nil; return b }) + return it } // A BucketIterator is an iterator over BucketAttrs. +// +// Note: This iterator is not safe for concurrent operations without explicit synchronization. type BucketIterator struct { // Prefix restricts the iterator to buckets whose names begin with it. Prefix string @@ -1155,6 +1221,8 @@ type BucketIterator struct { // Next returns the next result. Its second return value is iterator.Done if // there are no more results. Once Next returns iterator.Done, all subsequent // calls will return iterator.Done. +// +// Note: This method is not safe for concurrent operations without explicit synchronization. func (it *BucketIterator) Next() (*BucketAttrs, error) { if err := it.nextFunc(); err != nil { return nil, err @@ -1165,6 +1233,8 @@ func (it *BucketIterator) Next() (*BucketAttrs, error) { } // PageInfo supports pagination. See the google.golang.org/api/iterator package for details. +// +// Note: This method is not safe for concurrent operations without explicit synchronization. func (it *BucketIterator) PageInfo() *iterator.PageInfo { return it.pageInfo } func (it *BucketIterator) fetch(pageSize int, pageToken string) (token string, err error) { diff --git a/vendor/cloud.google.com/go/storage/copy.go b/vendor/cloud.google.com/go/storage/copy.go index 52162e72d10..61983df5ada 100644 --- a/vendor/cloud.google.com/go/storage/copy.go +++ b/vendor/cloud.google.com/go/storage/copy.go @@ -166,6 +166,13 @@ type Composer struct { // or zero-valued attributes are ignored. ObjectAttrs + // SendCRC specifies whether to transmit a CRC32C field. It should be set + // to true in addition to setting the Composer's CRC32C field, because zero + // is a valid CRC and normally a zero would not be transmitted. + // If a CRC32C is sent, and the data in the destination object does not match + // the checksum, the compose will be rejected. + SendCRC32C bool + dst *ObjectHandle srcs []*ObjectHandle } @@ -186,6 +193,9 @@ func (c *Composer) Run(ctx context.Context) (attrs *ObjectAttrs, err error) { // Compose requires a non-empty Destination, so we always set it, // even if the caller-provided ObjectAttrs is the zero value. req.Destination = c.ObjectAttrs.toRawObject(c.dst.bucket) + if c.SendCRC32C { + req.Destination.Crc32c = encodeUint32(c.ObjectAttrs.CRC32C) + } for _, src := range c.srcs { if err := src.validate(); err != nil { return nil, err diff --git a/vendor/cloud.google.com/go/storage/doc.go b/vendor/cloud.google.com/go/storage/doc.go index 88f6459046c..614ea11a590 100644 --- a/vendor/cloud.google.com/go/storage/doc.go +++ b/vendor/cloud.google.com/go/storage/doc.go @@ -117,6 +117,33 @@ Objects also have attributes, which you can fetch with Attrs: fmt.Printf("object %s has size %d and can be read using %s\n", objAttrs.Name, objAttrs.Size, objAttrs.MediaLink) +Listing objects + +Listing objects in a bucket is done with the Bucket.Objects method: + + query := &storage.Query{Prefix: ""} + + var names []string + it := bkt.Objects(ctx, query) + for { + attrs, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + log.Fatal(err) + } + names = append(names, attrs.Name) + } + +If only a subset of object attributes is needed when listing, specifying this +subset using Query.SetAttrSelection may speed up the listing process: + + query := &storage.Query{Prefix: ""} + query.SetAttrSelection([]string{"Name"}) + + // ... as before + ACLs Both objects and buckets have ACLs (Access Control Lists). An ACL is a list of @@ -164,6 +191,21 @@ SignedURL for details. } fmt.Println(url) +Post Policy V4 Signed Request + +A type of signed request that allows uploads through HTML forms directly to Cloud Storage with +temporary permission. Conditions can be applied to restrict how the HTML form is used and exercised +by a user. + +For more information, please see https://cloud.google.com/storage/docs/xml-api/post-object as well +as the documentation of GenerateSignedPostPolicyV4. + + pv4, err := storage.GenerateSignedPostPolicyV4(bucketName, objectName, opts) + if err != nil { + // TODO: Handle error. + } + fmt.Printf("URL: %s\nFields; %v\n", pv4.URL, pv4.Fields) + Errors Errors returned by this client are often of the type [`googleapi.Error`](https://godoc.org/google.golang.org/api/googleapi#Error). diff --git a/vendor/cloud.google.com/go/storage/go.mod b/vendor/cloud.google.com/go/storage/go.mod new file mode 100644 index 00000000000..2eb6df3cbde --- /dev/null +++ b/vendor/cloud.google.com/go/storage/go.mod @@ -0,0 +1,18 @@ +module cloud.google.com/go/storage + +go 1.11 + +require ( + cloud.google.com/go v0.57.0 + cloud.google.com/go/bigquery v1.8.0 // indirect + github.com/golang/protobuf v1.4.2 + github.com/google/go-cmp v0.4.1 + github.com/googleapis/gax-go/v2 v2.0.5 + golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2 // indirect + golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d + golang.org/x/sys v0.0.0-20200523222454-059865788121 // indirect + golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2 // indirect + google.golang.org/api v0.28.0 + google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790 + google.golang.org/grpc v1.29.1 +) diff --git a/vendor/cloud.google.com/go/storage/go.sum b/vendor/cloud.google.com/go/storage/go.sum new file mode 100644 index 00000000000..5d3fca5f832 --- /dev/null +++ b/vendor/cloud.google.com/go/storage/go.sum @@ -0,0 +1,450 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3 h1:AVXDdKsrtX33oR9fbCMu/+c1o8Ofjq6Ku/MInaLVg5Y= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0 h1:GGslhk/BU052LPlnI1vpp3fcbUs+hQ3E+Doti/3/vF8= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0 h1:MZQCQQaRwOrAcuKjiHWHrgKykt4fZyuwF2dtiG3fGW8= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0 h1:3ithwDMr7/3vpAMXiH+ZQnYbuIsh+OPhUPMFC9enmn0= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0 h1:WRz29PgAsVEyPSDHyk+0fpEkwEFyfhHn+JbksT6gIL4= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0 h1:EpMNVUorLiZIELdMZbCYX/ByTFCdoYopYAGxaGVz9ms= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go/bigquery v1.0.1 h1:hL+ycaJpVE9M7nLoiXb/Pn10ENE2u+oddxbD8uu0ZVU= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0 h1:sAbMqjY1PEQKZBWfbu6Y6bsupJ9c4QdHnzg/VvYTLcE= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0 h1:xE3CPsOgttP4ACBePh79zTKALtXwn/Edhcr16R5hMWU= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0 h1:K2NyuHRuv15ku6eUpe0DQk5ZykPMnSOnvuVf6IHcjaE= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0 h1:a/O/bK/vWrYGOTFtH8di4rBxMZnmkjy+Y5LxpDwo+dA= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0 h1:PQcPefKFdaIzjQFbiyOgAqyx8q5djaE7x9Sqe712DPA= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/datastore v1.0.0 h1:Kt+gOPPp2LEPWp8CSfxhsM8ik9CcyE/gYu+0r+RnZvM= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0 h1:/May9ojXjRkPBNVrq+oWLqmWCkr4OU5uRY29bu0mRyQ= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/pubsub v1.0.1 h1:W9tAK3E57P75u0XLLR82LZyw8VpAnhmyTOxW9qzmyj8= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0 h1:9/vpR43S4aJaROxqQHQ3nH9lfyKKV0dC3vOmnw8ebQQ= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0 h1:Lpy6hKgdcl7a3WGSfJIFmxmcdjSpP6OmBEfcOv1Y680= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1 h1:ukjixP1wl0LpnZ6LWtZJ0mX5tBmjp1f8Sqer8Z2OMUU= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7 h1:5ZkaAPbicIKTF2I64qf5Fh8Aa83Q/dnOafMYV0OMwjA= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4 h1:87PNWwrRvUSnqS4dlcBU/ftvOIBep4sYuBLlh6rX2wk= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5 h1:F768QJ1E9tib+q5Sc8MkdJi1RxLTbRcTf8LJV56aRls= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0 h1:oOuy+ugB+P/kBdUnG5QaMXSIyJ1q38wWSojYCb3z5VQ= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1 h1:ZFgWrT+bLgsYPirOnRfKLYJLvssAegOj/hgyMFdJZe0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1 h1:/exdXoGamhu5ONeUJH0deniYLWYvQwW66yvlfiiKTu0= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024 h1:rBMNdlhTLzJjJSDIjNEXX1Pz3Hmwmz91v+zycvx9PJc= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1 h1:6QPYqodiu3GuPL+7mfx+NwDdp2eTkp9IfEUpgAwUN0o= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0 h1:C9hSCOW830chIVkdja34wa6Ky+IzWllkUinR+BtRZd4= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2 h1:75k/FF0Q2YM8QYo07VPddOLBslDt1MZOdEslOHvmzAs= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3 h1:8sGtKOrtQqkN1bp2AtX+misvLIlOmsEsNd+9NIcPEm8= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979 h1:Agxu5KLo8o7Bb634SVDnhIfpTvxmzUwhbYAzBvXt6h4= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299 h1:zQpM52jfKHG6II1ISZY1ZcpygvuSFZpLwfluuF89XOg= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a h1:7Wlg8L54In96HTWOaI4sreLJ6qfyGuvSau5el3fK41Y= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd h1:zkO/Lhoka23X63N9OSzpSeROEUQ5ODw47tM3YWjygbs= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6 h1:QE6XYQK6naiK1EPAe1g/ILLxN5RBoH5xkJk3CqlMI/Y= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac h1:8R1esu+8QioDxo4E4mX6bFztO+dMTM49DNAaWfO5OeY= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f h1:J5lckAjkw6qYlOZNj90mLYNTEKDvWeuc1yieZ8qUzUE= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367 h1:0IiAsCRByjO2QjX7ZPkw5oU9x+n1YqRL802rjC0c3Aw= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b h1:Wh+f8QHJXR411sJR8/vRBTZ7YapZaRvUcLFFJhusH0k= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee h1:WG0RUwxtNT4qqaXX3DPA8zHFNm/D9xaBpxzHt1WcA/E= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa h1:F+8P+gmewFQYRk6JoLQLwjBCTu3mcIURZfNkVweuRKA= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2 h1:CCH4IOTTfewWjGOlSp+zGcjutRKlBEZQ6wTn8ozI/nI= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b h1:0mm1VjtFUOIlE1SbDlwjYaDxZVDP2S5ou6y0gSgXHu8= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a h1:GuSPYbZzB5/dcLNCwLQLsg3obCJtX9IJhpXkvY7kzk0= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e h1:3G+cUijn7XD+S4eJFddp53Pv7+slrESplyjG25HgL+k= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5 h1:WQ8q63x+f/zpC8Ac1s9wLElVoHhm32p6tudrU72n1QA= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2 h1:eDrdRpKgkcCqKZQwyZRyeFZgfqt37SL7Kv3tok06cKE= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a h1:WXEvlFVvvGxCJLG6REjsT03iWnKLEWinaScsxF2Vm2o= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0 h1:HyfiK1WMnHj5FXFXatD+Qs1A/xC2Run6RzeW1SyHxpc= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1 h1:gZpLHxUX5BdYLA08Lj4YCJNN/jk7KtquiArPoeX0WvA= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82 h1:ywK/j/KkyTHcdyYSZNXGjMwgmDSfjglYZ3vStQ/gSCU= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5 h1:LfCXLvNmTYH9kEmVgqbnsWfruoXZIrh4YBgqVHtDvw0= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4 h1:sfkvUWPNGwSV+8/fNqctR5lS2AqCSqYwXdrjCxp/dXo= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae h1:/WDfKMnPU+m5M4xB+6x4kaepxRw6jWvR5iDRdvjHgy8= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 h1:uYVVQ9WP/Ds2ROhcaGPeIdVq0RIXVLwsHlnvJ+cT1So= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d h1:nc5K6ox/4lTFbMVSL9WRR81ixkcwXThoiF6yf+R9scA= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e h1:hq86ru83GdWTlfQFZGO4nZJTU4Bs2wfHl8oFHRaXsfc= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121 h1:rITEj+UZHYC927n8GT97eC3zrpzXdb/voyeOuVKS46o= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff h1:On1qIo75ByTwFJ4/W2bIqHcwJ9XAqtSWUs8GwRrIhtc= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c h1:2EA2K0k9bcvvEDlqD8xdlOhCOqq+O/p9Voqi4x9W1YU= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a h1:7YaEqUc1tUg0yDwvdX+3U5bwrBg7u3FFAZ5D8gUs4/c= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74 h1:KW20qMcLRWuIgjdCpHFJbVZA7zsDKtFXPNcm7/eI5ZA= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56 h1:DFtSed2q3HtNuVazwVDZ4nSRS/JrZEig0gz2BY4VNrg= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d h1:7M9AXzLrJWWGdDYtBblPHBTnHtaN6KKQ98OYb35mLlY= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb h1:iKlO7ROJc6SttHKlxzwGytRtBUqX4VARrNTgP2YLX5M= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d h1:3K34ovZAOnVaUPxanr0j4ghTZTPTA0CnXvjCl+5lZqk= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4 h1:kDtqNkeBrZb8B+atrj50B5XLHpzXXqcCdZPP/ApQ5NY= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d h1:lzLdP95xJmMpwQ6LUHwrc5V7js93hTiY7gkznu0BgmY= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2 h1:FD4wDsP+CQUqh2V12OBOt90pLHVToe58P++fUu3ggV4= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0 h1:jbyannxz0XFD3zdjgrSUsaJbgpH4eTrkdhRChkHPfO8= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0 h1:yzlyyDW/J0w8yNFJIhiAJy4kq74S+1DOLdawELNxFMA= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0 h1:0q95w+VuFtv4PAx4PZVQdBMmYbaCHbnfKaEiDIcVyag= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0 h1:GwFK8+l5/gdsOYKz5p6M4UK+QT8OvmHWZPJCnf+5DjA= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0 h1:jz2KixHX7EcCPiQrySzPdnYT7DbINAypCqKZ1Z7GM40= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0 h1:J1Pl9P2lnmYFSJvgs70DKELqHNh8CNWXPbud4njEE2s= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0 h1:cG03eaksBzhfSIk7JRGctfp3lanklcOM/mTGvow7BbQ= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0 h1:jMF5hhVfMkTZwHW1SDpKq5CkgWLXOb31Foaca9Zr3oM= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1 h1:QzqyMA1tlu6CgqCDUtU9V+ZKhLFT2dkJuANu5QaxI3I= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6 h1:lMO5rYAqUxkmaj76jAkRUvt5JZgFymx/+Q5Mzfivuhc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51 h1:Ex1mq5jaJof+kRnYi3SlYJ8KKa9Ao3NHyIT5XJ1gF6U= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba h1:pRj9OXZbwNtbtZtOB4dLwfK4u+EVRMvP+e9zKkg2grM= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150 h1:VPpdpQkGvFicX9yo4G5oxZPi9ALBnEOZblPSa/Wa2m4= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90 h1:7THRSvPuzF1bql5kyFzX0JM0vpGhwuhskgJrJsbZ80Y= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce h1:1mbrb1tUU+Zmt5C94IGKADBTJZjZXAd+BubWi7r9EiI= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383 h1:Vo0fD5w0fUKriWlZLyrim2GXbumyN0D6euW79T9PgEE= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171 h1:xes2Q2k+d/+YNXVw0FpZkIDJiaux4OVrRKXRAzH6A0U= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672 h1:jiDSspVssiikoRPFHT6pYrL+CL6/yIc3b9AuHO/4xik= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940 h1:MRHtG0U6SnaUb+s+LhNE1qt1FQ1wlhqr5E4usBKC0uA= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84 h1:pSLkPbrjnPyLDYUO2VM9mDLqo2V6CFBY84lFSZAfoi4= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790 h1:FGjyjrQGURdc98leD1P65IdQD9Zlr4McvRcqIlV6OSs= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.1 h1:j6XxA85m/6txkUCHvzlV5f+HBNl/1r5cZ2A/3IEFOO8= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0 h1:2dTRdpdFEEhJYQD8EMLB61nnrzSCTbG38PhqdhvOltg= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0 h1:rRYRFMVgRv6E0D70Skyfsr28tDXIuuPZyWGMPdMcnXg= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1 h1:zvIju4sqAGvwKspUQOhwnpcqSbzi7/H6QomNNjTL4sk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0 h1:bO/TA4OxCOummhSf10siHuG7vJOiwh7SpRpFZDkOgl4= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1 h1:EC2SB8S04d2r73uptxphDSUG+kTKVgjRPF+N3xpxRB4= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0 h1:qdOKuR/EIArgaWNjetjgTzgVTAZ+S/WXVrq9HW9zimw= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0 h1:cJv5/xdbk1NnMPR1VP9+HU6gupuG9MLBoH1r6RHZ2MY= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc h1:TnonUr8u3himcMY0vSh23jFOXA+cnucl1gB6EQTReBI= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0 h1:UhZDfRO8JRQru4/+LlLE0BRKGF8L+PICnvYZmx/fEGA= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3 h1:sXmLre5bzIR6ypkjXCDI3jHPssRhc8KD/Ome589sc3U= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4 h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/vendor/cloud.google.com/go/storage/go110.go b/vendor/cloud.google.com/go/storage/go110.go index 206813f0cea..c1273d59ade 100644 --- a/vendor/cloud.google.com/go/storage/go110.go +++ b/vendor/cloud.google.com/go/storage/go110.go @@ -16,7 +16,12 @@ package storage -import "google.golang.org/api/googleapi" +import ( + "net/url" + "strings" + + "google.golang.org/api/googleapi" +) func shouldRetry(err error) bool { switch e := err.(type) { @@ -24,6 +29,17 @@ func shouldRetry(err error) bool { // Retry on 429 and 5xx, according to // https://cloud.google.com/storage/docs/exponential-backoff. return e.Code == 429 || (e.Code >= 500 && e.Code < 600) + case *url.Error: + // Retry socket-level errors ECONNREFUSED and ENETUNREACH (from syscall). + // Unfortunately the error type is unexported, so we resort to string + // matching. + retriable := []string{"connection refused", "connection reset"} + for _, s := range retriable { + if strings.Contains(e.Error(), s) { + return true + } + } + return false case interface{ Temporary() bool }: return e.Temporary() default: diff --git a/vendor/cloud.google.com/go/storage/go_mod_tidy_hack.go b/vendor/cloud.google.com/go/storage/go_mod_tidy_hack.go new file mode 100644 index 00000000000..7df7a1d7155 --- /dev/null +++ b/vendor/cloud.google.com/go/storage/go_mod_tidy_hack.go @@ -0,0 +1,22 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file, and the cloud.google.com/go import, won't actually become part of +// the resultant binary. +// +build modhack + +package storage + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "cloud.google.com/go" diff --git a/vendor/cloud.google.com/go/storage/hmac.go b/vendor/cloud.google.com/go/storage/hmac.go index 4a5c1b5121f..7d8185f37b8 100644 --- a/vendor/cloud.google.com/go/storage/hmac.go +++ b/vendor/cloud.google.com/go/storage/hmac.go @@ -25,6 +25,8 @@ import ( ) // HMACState is the state of the HMAC key. +// +// This type is EXPERIMENTAL and subject to change or removal without notice. type HMACState string const ( @@ -105,9 +107,21 @@ func (c *Client) HMACKeyHandle(projectID, accessID string) *HMACKeyHandle { // Get invokes an RPC to retrieve the HMAC key referenced by the // HMACKeyHandle's accessID. // +// Options such as UserProjectForHMACKeys can be used to set the +// userProject to be billed against for operations. +// // This method is EXPERIMENTAL and subject to change or removal without notice. -func (hkh *HMACKeyHandle) Get(ctx context.Context) (*HMACKey, error) { +func (hkh *HMACKeyHandle) Get(ctx context.Context, opts ...HMACKeyOption) (*HMACKey, error) { call := hkh.raw.Get(hkh.projectID, hkh.accessID) + + desc := new(hmacKeyDesc) + for _, opt := range opts { + opt.withHMACKeyDesc(desc) + } + if desc.userProjectID != "" { + call = call.UserProject(desc.userProjectID) + } + setClientHeader(call.Header()) var metadata *raw.HmacKeyMetadata @@ -131,8 +145,15 @@ func (hkh *HMACKeyHandle) Get(ctx context.Context) (*HMACKey, error) { // After deletion, a key cannot be used to authenticate requests. // // This method is EXPERIMENTAL and subject to change or removal without notice. -func (hkh *HMACKeyHandle) Delete(ctx context.Context) error { +func (hkh *HMACKeyHandle) Delete(ctx context.Context, opts ...HMACKeyOption) error { delCall := hkh.raw.Delete(hkh.projectID, hkh.accessID) + desc := new(hmacKeyDesc) + for _, opt := range opts { + opt.withHMACKeyDesc(desc) + } + if desc.userProjectID != "" { + delCall = delCall.UserProject(desc.userProjectID) + } setClientHeader(delCall.Header()) return runWithRetry(ctx, func() error { @@ -173,7 +194,7 @@ func pbHmacKeyToHMACKey(pb *raw.HmacKey, updatedTimeCanBeNil bool) (*HMACKey, er // CreateHMACKey invokes an RPC for Google Cloud Storage to create a new HMACKey. // // This method is EXPERIMENTAL and subject to change or removal without notice. -func (c *Client) CreateHMACKey(ctx context.Context, projectID, serviceAccountEmail string) (*HMACKey, error) { +func (c *Client) CreateHMACKey(ctx context.Context, projectID, serviceAccountEmail string, opts ...HMACKeyOption) (*HMACKey, error) { if projectID == "" { return nil, errors.New("storage: expecting a non-blank projectID") } @@ -183,6 +204,14 @@ func (c *Client) CreateHMACKey(ctx context.Context, projectID, serviceAccountEma svc := raw.NewProjectsHmacKeysService(c.raw) call := svc.Create(projectID, serviceAccountEmail) + desc := new(hmacKeyDesc) + for _, opt := range opts { + opt.withHMACKeyDesc(desc) + } + if desc.userProjectID != "" { + call = call.UserProject(desc.userProjectID) + } + setClientHeader(call.Header()) var hkPb *raw.HmacKey @@ -212,7 +241,7 @@ type HMACKeyAttrsToUpdate struct { // Update mutates the HMACKey referred to by accessID. // // This method is EXPERIMENTAL and subject to change or removal without notice. -func (h *HMACKeyHandle) Update(ctx context.Context, au HMACKeyAttrsToUpdate) (*HMACKey, error) { +func (h *HMACKeyHandle) Update(ctx context.Context, au HMACKeyAttrsToUpdate, opts ...HMACKeyOption) (*HMACKey, error) { if au.State != Active && au.State != Inactive { return nil, fmt.Errorf("storage: invalid state %q for update, must be either %q or %q", au.State, Active, Inactive) } @@ -221,6 +250,14 @@ func (h *HMACKeyHandle) Update(ctx context.Context, au HMACKeyAttrsToUpdate) (*H Etag: au.Etag, State: string(au.State), }) + + desc := new(hmacKeyDesc) + for _, opt := range opts { + opt.withHMACKeyDesc(desc) + } + if desc.userProjectID != "" { + call = call.UserProject(desc.userProjectID) + } setClientHeader(call.Header()) var metadata *raw.HmacKeyMetadata @@ -241,6 +278,8 @@ func (h *HMACKeyHandle) Update(ctx context.Context, au HMACKeyAttrsToUpdate) (*H // An HMACKeysIterator is an iterator over HMACKeys. // +// Note: This iterator is not safe for concurrent operations without explicit synchronization. +// // This type is EXPERIMENTAL and subject to change or removal without notice. type HMACKeysIterator struct { ctx context.Context @@ -250,18 +289,25 @@ type HMACKeysIterator struct { pageInfo *iterator.PageInfo nextFunc func() error index int + desc hmacKeyDesc } // ListHMACKeys returns an iterator for listing HMACKeys. // +// Note: This iterator is not safe for concurrent operations without explicit synchronization. +// // This method is EXPERIMENTAL and subject to change or removal without notice. -func (c *Client) ListHMACKeys(ctx context.Context, projectID string) *HMACKeysIterator { +func (c *Client) ListHMACKeys(ctx context.Context, projectID string, opts ...HMACKeyOption) *HMACKeysIterator { it := &HMACKeysIterator{ ctx: ctx, raw: raw.NewProjectsHmacKeysService(c.raw), projectID: projectID, } + for _, opt := range opts { + opt.withHMACKeyDesc(&it.desc) + } + it.pageInfo, it.nextFunc = iterator.NewPageInfo( it.fetch, func() int { return len(it.hmacKeys) - it.index }, @@ -278,6 +324,8 @@ func (c *Client) ListHMACKeys(ctx context.Context, projectID string) *HMACKeysIt // there are no more results. Once Next returns iterator.Done, all subsequent // calls will return iterator.Done. // +// Note: This iterator is not safe for concurrent operations without explicit synchronization. +// // This method is EXPERIMENTAL and subject to change or removal without notice. func (it *HMACKeysIterator) Next() (*HMACKey, error) { if err := it.nextFunc(); err != nil { @@ -292,16 +340,26 @@ func (it *HMACKeysIterator) Next() (*HMACKey, error) { // PageInfo supports pagination. See the google.golang.org/api/iterator package for details. // +// Note: This iterator is not safe for concurrent operations without explicit synchronization. +// // This method is EXPERIMENTAL and subject to change or removal without notice. func (it *HMACKeysIterator) PageInfo() *iterator.PageInfo { return it.pageInfo } func (it *HMACKeysIterator) fetch(pageSize int, pageToken string) (token string, err error) { call := it.raw.List(it.projectID) setClientHeader(call.Header()) - call = call.PageToken(pageToken) - // By default we'll also show deleted keys and then - // let users filter on their own. - call = call.ShowDeletedKeys(true) + if pageToken != "" { + call = call.PageToken(pageToken) + } + if it.desc.showDeletedKeys { + call = call.ShowDeletedKeys(true) + } + if it.desc.userProjectID != "" { + call = call.UserProject(it.desc.userProjectID) + } + if it.desc.forServiceAccountEmail != "" { + call = call.ServiceAccountEmail(it.desc.forServiceAccountEmail) + } if pageSize > 0 { call = call.MaxResults(int64(pageSize)) } @@ -328,3 +386,56 @@ func (it *HMACKeysIterator) fetch(pageSize int, pageToken string) (token string, } return resp.NextPageToken, nil } + +type hmacKeyDesc struct { + forServiceAccountEmail string + showDeletedKeys bool + userProjectID string +} + +// HMACKeyOption configures the behavior of HMACKey related methods and actions. +// +// This interface is EXPERIMENTAL and subject to change or removal without notice. +type HMACKeyOption interface { + withHMACKeyDesc(*hmacKeyDesc) +} + +type hmacKeyDescFunc func(*hmacKeyDesc) + +func (hkdf hmacKeyDescFunc) withHMACKeyDesc(hkd *hmacKeyDesc) { + hkdf(hkd) +} + +// ForHMACKeyServiceAccountEmail returns HMAC Keys that are +// associated with the email address of a service account in the project. +// +// Only one service account email can be used as a filter, so if multiple +// of these options are applied, the last email to be set will be used. +// +// This option is EXPERIMENTAL and subject to change or removal without notice. +func ForHMACKeyServiceAccountEmail(serviceAccountEmail string) HMACKeyOption { + return hmacKeyDescFunc(func(hkd *hmacKeyDesc) { + hkd.forServiceAccountEmail = serviceAccountEmail + }) +} + +// ShowDeletedHMACKeys will also list keys whose state is "DELETED". +// +// This option is EXPERIMENTAL and subject to change or removal without notice. +func ShowDeletedHMACKeys() HMACKeyOption { + return hmacKeyDescFunc(func(hkd *hmacKeyDesc) { + hkd.showDeletedKeys = true + }) +} + +// UserProjectForHMACKeys will bill the request against userProjectID +// if userProjectID is non-empty. +// +// Note: This is a noop right now and only provided for API compatibility. +// +// This option is EXPERIMENTAL and subject to change or removal without notice. +func UserProjectForHMACKeys(userProjectID string) HMACKeyOption { + return hmacKeyDescFunc(func(hkd *hmacKeyDesc) { + hkd.userProjectID = userProjectID + }) +} diff --git a/vendor/cloud.google.com/go/storage/iam.go b/vendor/cloud.google.com/go/storage/iam.go index 9d936067129..5caefb059d5 100644 --- a/vendor/cloud.google.com/go/storage/iam.go +++ b/vendor/cloud.google.com/go/storage/iam.go @@ -21,6 +21,7 @@ import ( "cloud.google.com/go/internal/trace" raw "google.golang.org/api/storage/v1" iampb "google.golang.org/genproto/googleapis/iam/v1" + "google.golang.org/genproto/googleapis/type/expr" ) // IAM provides access to IAM access control for the bucket. @@ -38,10 +39,14 @@ type iamClient struct { } func (c *iamClient) Get(ctx context.Context, resource string) (p *iampb.Policy, err error) { + return c.GetWithVersion(ctx, resource, 1) +} + +func (c *iamClient) GetWithVersion(ctx context.Context, resource string, requestedPolicyVersion int32) (p *iampb.Policy, err error) { ctx = trace.StartSpan(ctx, "cloud.google.com/go/storage.IAM.Get") defer func() { trace.EndSpan(ctx, err) }() - call := c.raw.Buckets.GetIamPolicy(resource) + call := c.raw.Buckets.GetIamPolicy(resource).OptionsRequestedPolicyVersion(int64(requestedPolicyVersion)) setClientHeader(call.Header()) if c.userProject != "" { call.UserProject(c.userProject) @@ -97,6 +102,7 @@ func iamToStoragePolicy(ip *iampb.Policy) *raw.Policy { return &raw.Policy{ Bindings: iamToStorageBindings(ip.Bindings), Etag: string(ip.Etag), + Version: int64(ip.Version), } } @@ -104,13 +110,26 @@ func iamToStorageBindings(ibs []*iampb.Binding) []*raw.PolicyBindings { var rbs []*raw.PolicyBindings for _, ib := range ibs { rbs = append(rbs, &raw.PolicyBindings{ - Role: ib.Role, - Members: ib.Members, + Role: ib.Role, + Members: ib.Members, + Condition: iamToStorageCondition(ib.Condition), }) } return rbs } +func iamToStorageCondition(exprpb *expr.Expr) *raw.Expr { + if exprpb == nil { + return nil + } + return &raw.Expr{ + Expression: exprpb.Expression, + Description: exprpb.Description, + Location: exprpb.Location, + Title: exprpb.Title, + } +} + func iamFromStoragePolicy(rp *raw.Policy) *iampb.Policy { return &iampb.Policy{ Bindings: iamFromStorageBindings(rp.Bindings), @@ -122,9 +141,22 @@ func iamFromStorageBindings(rbs []*raw.PolicyBindings) []*iampb.Binding { var ibs []*iampb.Binding for _, rb := range rbs { ibs = append(ibs, &iampb.Binding{ - Role: rb.Role, - Members: rb.Members, + Role: rb.Role, + Members: rb.Members, + Condition: iamFromStorageCondition(rb.Condition), }) } return ibs } + +func iamFromStorageCondition(rawexpr *raw.Expr) *expr.Expr { + if rawexpr == nil { + return nil + } + return &expr.Expr{ + Expression: rawexpr.Expression, + Description: rawexpr.Description, + Location: rawexpr.Location, + Title: rawexpr.Title, + } +} diff --git a/vendor/cloud.google.com/go/storage/post_policy_v4.go b/vendor/cloud.google.com/go/storage/post_policy_v4.go new file mode 100644 index 00000000000..b9df7db9581 --- /dev/null +++ b/vendor/cloud.google.com/go/storage/post_policy_v4.go @@ -0,0 +1,377 @@ +// Copyright 2020 Google LLC +// +// 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 storage + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/url" + "strings" + "time" +) + +// PostPolicyV4Options are used to construct a signed post policy. +// Please see https://cloud.google.com/storage/docs/xml-api/post-object +// for reference about the fields. +type PostPolicyV4Options struct { + // GoogleAccessID represents the authorizer of the signed URL generation. + // It is typically the Google service account client email address from + // the Google Developers Console in the form of "xxx@developer.gserviceaccount.com". + // Required. + GoogleAccessID string + + // PrivateKey is the Google service account private key. It is obtainable + // from the Google Developers Console. + // At https://console.developers.google.com/project//apiui/credential, + // create a service account client ID or reuse one of your existing service account + // credentials. Click on the "Generate new P12 key" to generate and download + // a new private key. Once you download the P12 file, use the following command + // to convert it into a PEM file. + // + // $ openssl pkcs12 -in key.p12 -passin pass:notasecret -out key.pem -nodes + // + // Provide the contents of the PEM file as a byte slice. + // Exactly one of PrivateKey or SignBytes must be non-nil. + PrivateKey []byte + + // SignBytes is a function for implementing custom signing. For example, if + // your application is running on Google App Engine, you can use + // appengine's internal signing function: + // ctx := appengine.NewContext(request) + // acc, _ := appengine.ServiceAccount(ctx) + // url, err := SignedURL("bucket", "object", &SignedURLOptions{ + // GoogleAccessID: acc, + // SignBytes: func(b []byte) ([]byte, error) { + // _, signedBytes, err := appengine.SignBytes(ctx, b) + // return signedBytes, err + // }, + // // etc. + // }) + // + // Exactly one of PrivateKey or SignBytes must be non-nil. + SignBytes func(hashBytes []byte) (signature []byte, err error) + + // Expires is the expiration time on the signed URL. + // It must be a time in the future. + // Required. + Expires time.Time + + // Style provides options for the type of URL to use. Options are + // PathStyle (default), BucketBoundHostname, and VirtualHostedStyle. See + // https://cloud.google.com/storage/docs/request-endpoints for details. + // Optional. + Style URLStyle + + // Insecure when set indicates that the generated URL's scheme + // will use "http" instead of "https" (default). + // Optional. + Insecure bool + + // Fields specifies the attributes of a PostPolicyV4 request. + // When Fields is non-nil, its attributes must match those that will + // passed into field Conditions. + // Optional. + Fields *PolicyV4Fields + + // The conditions that the uploaded file will be expected to conform to. + // When used, the failure of an upload to satisfy a condition will result in + // a 4XX status code, back with the message describing the problem. + // Optional. + Conditions []PostPolicyV4Condition +} + +// PolicyV4Fields describes the attributes for a PostPolicyV4 request. +type PolicyV4Fields struct { + // ACL specifies the access control permissions for the object. + // Optional. + ACL string + // CacheControl specifies the caching directives for the object. + // Optional. + CacheControl string + // ContentType specifies the media type of the object. + // Optional. + ContentType string + // ContentDisposition specifies how the file will be served back to requesters. + // Optional. + ContentDisposition string + // ContentEncoding specifies the decompressive transcoding that the object. + // This field is complementary to ContentType in that the file could be + // compressed but ContentType specifies the file's original media type. + // Optional. + ContentEncoding string + // Metadata specifies custom metadata for the object. + // If any key doesn't begin with "x-goog-meta-", an error will be returned. + // Optional. + Metadata map[string]string + // StatusCodeOnSuccess when set, specifies the status code that Cloud Storage + // will serve back on successful upload of the object. + // Optional. + StatusCodeOnSuccess int + // RedirectToURLOnSuccess when set, specifies the URL that Cloud Storage + // will serve back on successful upload of the object. + // Optional. + RedirectToURLOnSuccess string +} + +// PostPolicyV4 describes the URL and respective form fields for a generated PostPolicyV4 request. +type PostPolicyV4 struct { + // URL is the generated URL that the file upload will be made to. + URL string + // Fields specifies the generated key-values that the file uploader + // must include in their multipart upload form. + Fields map[string]string +} + +// PostPolicyV4Condition describes the constraints that the subsequent +// object upload's multipart form fields will be expected to conform to. +type PostPolicyV4Condition interface { + isEmpty() bool + json.Marshaler +} + +type startsWith struct { + key, value string +} + +func (sw *startsWith) MarshalJSON() ([]byte, error) { + return json.Marshal([]string{"starts-with", sw.key, sw.value}) +} +func (sw *startsWith) isEmpty() bool { + return sw.value == "" +} + +// ConditionStartsWith checks that an attributes starts with value. +// An empty value will cause this condition to be ignored. +func ConditionStartsWith(key, value string) PostPolicyV4Condition { + return &startsWith{key, value} +} + +type contentLengthRangeCondition struct { + start, end uint64 +} + +func (clr *contentLengthRangeCondition) MarshalJSON() ([]byte, error) { + return json.Marshal([]interface{}{"content-length-range", clr.start, clr.end}) +} +func (clr *contentLengthRangeCondition) isEmpty() bool { + return clr.start == 0 && clr.end == 0 +} + +type singleValueCondition struct { + name, value string +} + +func (svc *singleValueCondition) MarshalJSON() ([]byte, error) { + return json.Marshal(map[string]string{svc.name: svc.value}) +} +func (svc *singleValueCondition) isEmpty() bool { + return svc.value == "" +} + +// ConditionContentLengthRange constraints the limits that the +// multipart upload's range header will be expected to be within. +func ConditionContentLengthRange(start, end uint64) PostPolicyV4Condition { + return &contentLengthRangeCondition{start, end} +} + +func conditionRedirectToURLOnSuccess(redirectURL string) PostPolicyV4Condition { + return &singleValueCondition{"success_action_redirect", redirectURL} +} + +func conditionStatusCodeOnSuccess(statusCode int) PostPolicyV4Condition { + svc := &singleValueCondition{name: "success_action_status"} + if statusCode > 0 { + svc.value = fmt.Sprintf("%d", statusCode) + } + return svc +} + +// GenerateSignedPostPolicyV4 generates a PostPolicyV4 value from bucket, object and opts. +// The generated URL and fields will then allow an unauthenticated client to perform multipart uploads. +func GenerateSignedPostPolicyV4(bucket, object string, opts *PostPolicyV4Options) (*PostPolicyV4, error) { + if bucket == "" { + return nil, errors.New("storage: bucket must be non-empty") + } + if object == "" { + return nil, errors.New("storage: object must be non-empty") + } + now := utcNow() + if err := validatePostPolicyV4Options(opts, now); err != nil { + return nil, err + } + + var signingFn func(hashedBytes []byte) ([]byte, error) + switch { + case opts.SignBytes != nil: + signingFn = opts.SignBytes + + case len(opts.PrivateKey) != 0: + parsedRSAPrivKey, err := parseKey(opts.PrivateKey) + if err != nil { + return nil, err + } + signingFn = func(hashedBytes []byte) ([]byte, error) { + return rsa.SignPKCS1v15(rand.Reader, parsedRSAPrivKey, crypto.SHA256, hashedBytes) + } + + default: + return nil, errors.New("storage: exactly one of PrivateKey or SignedBytes must be set") + } + + var descFields PolicyV4Fields + if opts.Fields != nil { + descFields = *opts.Fields + } + + if err := validateMetadata(descFields.Metadata); err != nil { + return nil, err + } + + // Build the policy. + conds := make([]PostPolicyV4Condition, len(opts.Conditions)) + copy(conds, opts.Conditions) + conds = append(conds, + conditionRedirectToURLOnSuccess(descFields.RedirectToURLOnSuccess), + conditionStatusCodeOnSuccess(descFields.StatusCodeOnSuccess), + &singleValueCondition{"acl", descFields.ACL}, + &singleValueCondition{"cache-control", descFields.CacheControl}, + ) + + YYYYMMDD := now.Format(yearMonthDay) + policyFields := map[string]string{ + "key": object, + "x-goog-date": now.Format(iso8601), + "x-goog-credential": opts.GoogleAccessID + "/" + YYYYMMDD + "/auto/storage/goog4_request", + "x-goog-algorithm": "GOOG4-RSA-SHA256", + "success_action_redirect": descFields.RedirectToURLOnSuccess, + "acl": descFields.ACL, + } + for key, value := range descFields.Metadata { + conds = append(conds, &singleValueCondition{key, value}) + policyFields[key] = value + } + + // Following from the order expected by the conformance test cases, + // hence manually inserting these fields in a specific order. + conds = append(conds, + &singleValueCondition{"bucket", bucket}, + &singleValueCondition{"key", object}, + &singleValueCondition{"x-goog-date", now.Format(iso8601)}, + &singleValueCondition{ + name: "x-goog-credential", + value: opts.GoogleAccessID + "/" + YYYYMMDD + "/auto/storage/goog4_request", + }, + &singleValueCondition{"x-goog-algorithm", "GOOG4-RSA-SHA256"}, + ) + + nonEmptyConds := make([]PostPolicyV4Condition, 0, len(opts.Conditions)) + for _, cond := range conds { + if cond == nil || !cond.isEmpty() { + nonEmptyConds = append(nonEmptyConds, cond) + } + } + condsAsJSON, err := json.Marshal(map[string]interface{}{ + "conditions": nonEmptyConds, + "expiration": opts.Expires.Format(time.RFC3339), + }) + if err != nil { + return nil, fmt.Errorf("storage: PostPolicyV4 JSON serialization failed: %v", err) + } + + b64Policy := base64.StdEncoding.EncodeToString(condsAsJSON) + shaSum := sha256.Sum256([]byte(b64Policy)) + signature, err := signingFn(shaSum[:]) + if err != nil { + return nil, err + } + + policyFields["policy"] = b64Policy + policyFields["x-goog-signature"] = fmt.Sprintf("%x", signature) + + // Construct the URL. + scheme := "https" + if opts.Insecure { + scheme = "http" + } + path := opts.Style.path(bucket, "") + "/" + u := &url.URL{ + Path: path, + RawPath: pathEncodeV4(path), + Host: opts.Style.host(bucket), + Scheme: scheme, + } + + if descFields.StatusCodeOnSuccess > 0 { + policyFields["success_action_status"] = fmt.Sprintf("%d", descFields.StatusCodeOnSuccess) + } + + // Clear out fields with blanks values. + for key, value := range policyFields { + if value == "" { + delete(policyFields, key) + } + } + pp4 := &PostPolicyV4{ + Fields: policyFields, + URL: u.String(), + } + return pp4, nil +} + +// validatePostPolicyV4Options checks that: +// * GoogleAccessID is set +// * either but not both PrivateKey and SignBytes are set or nil, but not both +// * Expires, the deadline is not in the past +// * if Style is not set, it'll use PathStyle +func validatePostPolicyV4Options(opts *PostPolicyV4Options, now time.Time) error { + if opts == nil || opts.GoogleAccessID == "" { + return errors.New("storage: missing required GoogleAccessID") + } + if privBlank, signBlank := len(opts.PrivateKey) == 0, opts.SignBytes == nil; privBlank == signBlank { + return errors.New("storage: exactly one of PrivateKey or SignedBytes must be set") + } + if opts.Expires.Before(now) { + return errors.New("storage: expecting Expires to be in the future") + } + if opts.Style == nil { + opts.Style = PathStyle() + } + return nil +} + +// validateMetadata ensures that all keys passed in have a prefix of "x-goog-meta-", +// otherwise it will return an error. +func validateMetadata(hdrs map[string]string) (err error) { + if len(hdrs) == 0 { + return nil + } + + badKeys := make([]string, 0, len(hdrs)) + for key := range hdrs { + if !strings.HasPrefix(key, "x-goog-meta-") { + badKeys = append(badKeys, key) + } + } + if len(badKeys) != 0 { + err = errors.New("storage: expected metadata to begin with x-goog-meta-, got " + strings.Join(badKeys, ", ")) + } + return +} diff --git a/vendor/cloud.google.com/go/storage/reader.go b/vendor/cloud.google.com/go/storage/reader.go index 5c83651bd9b..d64f5ec778c 100644 --- a/vendor/cloud.google.com/go/storage/reader.go +++ b/vendor/cloud.google.com/go/storage/reader.go @@ -86,6 +86,11 @@ func (o *ObjectHandle) NewReader(ctx context.Context) (*Reader, error) { // until the end. If offset is negative, the object is read abs(offset) bytes // from the end, and length must also be negative to indicate all remaining // bytes will be read. +// +// If the object's metadata property "Content-Encoding" is set to "gzip" or satisfies +// decompressive transcoding per https://cloud.google.com/storage/docs/transcoding +// that file will be served back whole, regardless of the requested range as +// Google Cloud Storage dictates. func (o *ObjectHandle) NewRangeReader(ctx context.Context, offset, length int64) (r *Reader, err error) { ctx = trace.StartSpan(ctx, "cloud.google.com/go/storage.Object.NewRangeReader") defer func() { trace.EndSpan(ctx, err) }() @@ -160,10 +165,25 @@ func (o *ObjectHandle) NewRangeReader(ctx context.Context, offset, length int64) Body: string(body), } } - if start > 0 && length != 0 && res.StatusCode != http.StatusPartialContent { + + partialContentNotSatisfied := + !decompressiveTranscoding(res) && + start > 0 && length != 0 && + res.StatusCode != http.StatusPartialContent + + if partialContentNotSatisfied { res.Body.Close() return errors.New("storage: partial request not satisfied") } + + // With "Content-Encoding": "gzip" aka decompressive transcoding, GCS serves + // back the whole file regardless of the range count passed in as per: + // https://cloud.google.com/storage/docs/transcoding#range, + // thus we have to manually move the body forward by seen bytes. + if decompressiveTranscoding(res) && seen > 0 { + _, _ = io.CopyN(ioutil.Discard, res.Body, seen) + } + // If a generation hasn't been specified, and this is the first response we get, let's record the // generation. In future requests we'll use this generation as a precondition to avoid data races. if gen < 0 && res.Header.Get("X-Goog-Generation") != "" { @@ -232,7 +252,7 @@ func (o *ObjectHandle) NewRangeReader(ctx context.Context, offset, length int64) body = emptyBody } var metaGen int64 - if res.Header.Get("X-Goog-Generation") != "" { + if res.Header.Get("X-Goog-Metageneration") != "" { metaGen, err = strconv.ParseInt(res.Header.Get("X-Goog-Metageneration"), 10, 64) if err != nil { return nil, err @@ -268,6 +288,18 @@ func (o *ObjectHandle) NewRangeReader(ctx context.Context, offset, length int64) }, nil } +// decompressiveTranscoding returns true if the request was served decompressed +// and different than its original storage form. This happens when the "Content-Encoding" +// header is "gzip". +// See: +// * https://cloud.google.com/storage/docs/transcoding#transcoding_and_gzip +// * https://github.com/googleapis/google-cloud-go/issues/1800 +func decompressiveTranscoding(res *http.Response) bool { + // Decompressive Transcoding. + return res.Header.Get("Content-Encoding") == "gzip" || + res.Header.Get("X-Goog-Stored-Content-Encoding") == "gzip" +} + func uncompressedByServer(res *http.Response) bool { // If the data is stored as gzip but is not encoded as gzip, then it // was uncompressed by the server. diff --git a/vendor/cloud.google.com/go/storage/storage.go b/vendor/cloud.google.com/go/storage/storage.go index d35bd7568e7..20d9518a42d 100644 --- a/vendor/cloud.google.com/go/storage/storage.go +++ b/vendor/cloud.google.com/go/storage/storage.go @@ -47,14 +47,19 @@ import ( htransport "google.golang.org/api/transport/http" ) +// Methods which can be used in signed URLs. +var signedURLMethods = map[string]bool{"DELETE": true, "GET": true, "HEAD": true, "POST": true, "PUT": true} + var ( // ErrBucketNotExist indicates that the bucket does not exist. ErrBucketNotExist = errors.New("storage: bucket doesn't exist") // ErrObjectNotExist indicates that the object does not exist. ErrObjectNotExist = errors.New("storage: object doesn't exist") + // errMethodNotValid indicates that given HTTP method is not valid. + errMethodNotValid = fmt.Errorf("storage: HTTP method should be one of %v", reflect.ValueOf(signedURLMethods).MapKeys()) ) -const userAgent = "gcloud-golang-storage/20151204" +var userAgent = fmt.Sprintf("gcloud-golang-storage/%s", version.Repo) const ( // ScopeFullControl grants permissions to manage your @@ -94,30 +99,44 @@ type Client struct { // NewClient creates a new Google Cloud Storage client. // The default scope is ScopeFullControl. To use a different scope, like ScopeReadOnly, use option.WithScopes. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - o := []option.ClientOption{ - option.WithScopes(ScopeFullControl), - option.WithUserAgent(userAgent), + var host, readHost, scheme string + + if host = os.Getenv("STORAGE_EMULATOR_HOST"); host == "" { + scheme = "https" + readHost = "storage.googleapis.com" + + // Prepend default options to avoid overriding options passed by the user. + opts = append([]option.ClientOption{option.WithScopes(ScopeFullControl), option.WithUserAgent(userAgent)}, opts...) + } else { + scheme = "http" + readHost = host + + opts = append([]option.ClientOption{option.WithoutAuthentication()}, opts...) } - opts = append(o, opts...) + hc, ep, err := htransport.NewClient(ctx, opts...) if err != nil { return nil, fmt.Errorf("dialing: %v", err) } - rawService, err := raw.New(hc) + rawService, err := raw.NewService(ctx, option.WithHTTPClient(hc)) if err != nil { return nil, fmt.Errorf("storage client: %v", err) } - if ep != "" { - rawService.BasePath = ep - } - scheme := "https" - var host, readHost string - if host = os.Getenv("STORAGE_EMULATOR_HOST"); host != "" { - scheme = "http" - readHost = host + if ep == "" { + // Override the default value for BasePath from the raw client. + // TODO: remove when the raw client uses this endpoint as its default (~end of 2020) + rawService.BasePath = "https://storage.googleapis.com/storage/v1/" } else { - readHost = "storage.googleapis.com" + // If the endpoint has been set explicitly, use this for the BasePath + // as well as readHost + rawService.BasePath = ep + u, err := url.Parse(ep) + if err != nil { + return nil, fmt.Errorf("supplied endpoint %v is not valid: %v", ep, err) + } + readHost = u.Host } + return &Client{ hc: hc, raw: rawService, @@ -151,6 +170,80 @@ const ( SigningSchemeV4 ) +// URLStyle determines the style to use for the signed URL. pathStyle is the +// default. All non-default options work with V4 scheme only. See +// https://cloud.google.com/storage/docs/request-endpoints for details. +type URLStyle interface { + // host should return the host portion of the signed URL, not including + // the scheme (e.g. storage.googleapis.com). + host(bucket string) string + + // path should return the path portion of the signed URL, which may include + // both the bucket and object name or only the object name depending on the + // style. + path(bucket, object string) string +} + +type pathStyle struct{} + +type virtualHostedStyle struct{} + +type bucketBoundHostname struct { + hostname string +} + +func (s pathStyle) host(bucket string) string { + return "storage.googleapis.com" +} + +func (s virtualHostedStyle) host(bucket string) string { + return bucket + ".storage.googleapis.com" +} + +func (s bucketBoundHostname) host(bucket string) string { + return s.hostname +} + +func (s pathStyle) path(bucket, object string) string { + p := bucket + if object != "" { + p += "/" + object + } + return p +} + +func (s virtualHostedStyle) path(bucket, object string) string { + return object +} + +func (s bucketBoundHostname) path(bucket, object string) string { + return object +} + +// PathStyle is the default style, and will generate a URL of the form +// "storage.googleapis.com//". +func PathStyle() URLStyle { + return pathStyle{} +} + +// VirtualHostedStyle generates a URL relative to the bucket's virtual +// hostname, e.g. ".storage.googleapis.com/". +func VirtualHostedStyle() URLStyle { + return virtualHostedStyle{} +} + +// BucketBoundHostname generates a URL with a custom hostname tied to a +// specific GCS bucket. The desired hostname should be passed in using the +// hostname argument. Generated urls will be of the form +// "/". See +// https://cloud.google.com/storage/docs/request-endpoints#cname and +// https://cloud.google.com/load-balancing/docs/https/adding-backend-buckets-to-load-balancers +// for details. Note that for CNAMEs, only HTTP is supported, so Insecure must +// be set to true. +func BucketBoundHostname(hostname string) URLStyle { + return bucketBoundHostname{hostname: hostname} +} + // SignedURLOptions allows you to restrict the access to the signed URL. type SignedURLOptions struct { // GoogleAccessID represents the authorizer of the signed URL generation. @@ -207,16 +300,37 @@ type SignedURLOptions struct { ContentType string // Headers is a list of extension headers the client must provide - // in order to use the generated signed URL. + // in order to use the generated signed URL. Each must be a string of the + // form "key:values", with multiple values separated by a semicolon. // Optional. Headers []string + // QueryParameters is a map of additional query parameters. When + // SigningScheme is V4, this is used in computing the signature, and the + // client must use the same query parameters when using the generated signed + // URL. + // Optional. + QueryParameters url.Values + // MD5 is the base64 encoded MD5 checksum of the file. // If provided, the client should provide the exact value on the request // header in order to use the signed URL. // Optional. MD5 string + // Style provides options for the type of URL to use. Options are + // PathStyle (default), BucketBoundHostname, and VirtualHostedStyle. See + // https://cloud.google.com/storage/docs/request-endpoints for details. + // Only supported for V4 signing. + // Optional. + Style URLStyle + + // Insecure determines whether the signed URL should use HTTPS (default) or + // HTTP. + // Only supported for V4 signing. + // Optional. + Insecure bool + // Scheme determines the version of URL signing to use. Default is // SigningSchemeV2. Scheme SigningScheme @@ -368,8 +482,9 @@ func validateOptions(opts *SignedURLOptions, now time.Time) error { if (opts.PrivateKey == nil) == (opts.SignBytes == nil) { return errors.New("storage: exactly one of PrivateKey or SignedBytes must be set") } - if opts.Method == "" { - return errors.New("storage: missing required method option") + opts.Method = strings.ToUpper(opts.Method) + if _, ok := signedURLMethods[opts.Method]; !ok { + return errMethodNotValid } if opts.Expires.IsZero() { return errors.New("storage: missing required expires option") @@ -380,6 +495,12 @@ func validateOptions(opts *SignedURLOptions, now time.Time) error { return errors.New("storage: invalid MD5 checksum") } } + if opts.Style == nil { + opts.Style = PathStyle() + } + if _, ok := opts.Style.(pathStyle); !ok && opts.Scheme == SigningSchemeV2 { + return errors.New("storage: only path-style URLs are permitted with SigningSchemeV2") + } if opts.Scheme == SigningSchemeV4 { cutoff := now.Add(604801 * time.Second) // 7 days + 1 second if !opts.Expires.Before(cutoff) { @@ -411,19 +532,33 @@ func extractHeaderNames(kvs []string) []string { return res } +// pathEncodeV4 creates an encoded string that matches the v4 signature spec. +// Following the spec precisely is necessary in order to ensure that the URL +// and signing string are correctly formed, and Go's url.PathEncode and +// url.QueryEncode don't generate an exact match without some additional logic. +func pathEncodeV4(path string) string { + segments := strings.Split(path, "/") + var encodedSegments []string + for _, s := range segments { + encodedSegments = append(encodedSegments, url.QueryEscape(s)) + } + encodedStr := strings.Join(encodedSegments, "/") + encodedStr = strings.Replace(encodedStr, "+", "%20", -1) + return encodedStr +} + // signedURLV4 creates a signed URL using the sigV4 algorithm. func signedURLV4(bucket, name string, opts *SignedURLOptions, now time.Time) (string, error) { buf := &bytes.Buffer{} fmt.Fprintf(buf, "%s\n", opts.Method) - u := &url.URL{Path: bucket} - if name != "" { - u.Path += "/" + name - } + + u := &url.URL{Path: opts.Style.path(bucket, name)} + u.RawPath = pathEncodeV4(u.Path) // Note: we have to add a / here because GCS does so auto-magically, despite - // Go's EscapedPath not doing so (and we have to exactly match their + // our encoding not doing so (and we have to exactly match their // canonical query). - fmt.Fprintf(buf, "/%s\n", u.EscapedPath()) + fmt.Fprintf(buf, "/%s\n", u.RawPath) headerNames := append(extractHeaderNames(opts.Headers), "host") if opts.ContentType != "" { @@ -443,23 +578,55 @@ func signedURLV4(bucket, name string, opts *SignedURLOptions, now time.Time) (st "X-Goog-Expires": {fmt.Sprintf("%d", int(opts.Expires.Sub(now).Seconds()))}, "X-Goog-SignedHeaders": {signedHeaders}, } + // Add user-supplied query parameters to the canonical query string. For V4, + // it's necessary to include these. + for k, v := range opts.QueryParameters { + canonicalQueryString[k] = append(canonicalQueryString[k], v...) + } + fmt.Fprintf(buf, "%s\n", canonicalQueryString.Encode()) - u.Host = "storage.googleapis.com" + // Fill in the hostname based on the desired URL style. + u.Host = opts.Style.host(bucket) + + // Fill in the URL scheme. + if opts.Insecure { + u.Scheme = "http" + } else { + u.Scheme = "https" + } var headersWithValue []string headersWithValue = append(headersWithValue, "host:"+u.Host) headersWithValue = append(headersWithValue, opts.Headers...) if opts.ContentType != "" { - headersWithValue = append(headersWithValue, "content-type:"+strings.TrimSpace(opts.ContentType)) + headersWithValue = append(headersWithValue, "content-type:"+opts.ContentType) } if opts.MD5 != "" { - headersWithValue = append(headersWithValue, "content-md5:"+strings.TrimSpace(opts.MD5)) + headersWithValue = append(headersWithValue, "content-md5:"+opts.MD5) + } + // Trim extra whitespace from headers and replace with a single space. + var trimmedHeaders []string + for _, h := range headersWithValue { + trimmedHeaders = append(trimmedHeaders, strings.Join(strings.Fields(h), " ")) } - canonicalHeaders := strings.Join(sortHeadersByKey(headersWithValue), "\n") + canonicalHeaders := strings.Join(sortHeadersByKey(trimmedHeaders), "\n") fmt.Fprintf(buf, "%s\n\n", canonicalHeaders) fmt.Fprintf(buf, "%s\n", signedHeaders) - fmt.Fprint(buf, "UNSIGNED-PAYLOAD") + + // If the user provides a value for X-Goog-Content-SHA256, we must use + // that value in the request string. If not, we use UNSIGNED-PAYLOAD. + sha256Header := false + for _, h := range trimmedHeaders { + if strings.HasPrefix(strings.ToLower(h), "x-goog-content-sha256") && strings.Contains(h, ":") { + sha256Header = true + fmt.Fprintf(buf, "%s", strings.SplitN(h, ":", 2)[1]) + break + } + } + if !sha256Header { + fmt.Fprint(buf, "UNSIGNED-PAYLOAD") + } sum := sha256.Sum256(buf.Bytes()) hexDigest := hex.EncodeToString(sum[:]) @@ -491,7 +658,6 @@ func signedURLV4(bucket, name string, opts *SignedURLOptions, now time.Time) (st } signature := hex.EncodeToString(b) canonicalQueryString.Set("X-Goog-Signature", string(signature)) - u.Scheme = "https" u.RawQuery = canonicalQueryString.Encode() return u.String(), nil } @@ -964,11 +1130,11 @@ type ObjectAttrs struct { // data is rejected if its MD5 hash does not match this field. MD5 []byte - // CRC32C is the CRC32 checksum of the object's content using - // the Castagnoli93 polynomial. This field is read-only, except when - // used from a Writer. If set on a Writer and Writer.SendCRC32C - // is true, the uploaded data is rejected if its CRC32c hash does not - // match this field. + // CRC32C is the CRC32 checksum of the object's content using the Castagnoli93 + // polynomial. This field is read-only, except when used from a Writer or + // Composer. In those cases, if the SendCRC32C field in the Writer or Composer + // is set to is true, the uploaded data is rejected if its CRC32C hash does + // not match this field. CRC32C uint32 // MediaLink is an URL to the object's content. This field is read-only. @@ -989,13 +1155,12 @@ type ObjectAttrs struct { // of a particular object. This field is read-only. Metageneration int64 - // StorageClass is the storage class of the object. - // This value defines how objects in the bucket are stored and - // determines the SLA and the cost of storage. Typical values are - // "MULTI_REGIONAL", "REGIONAL", "NEARLINE", "COLDLINE", "STANDARD" - // and "DURABLE_REDUCED_AVAILABILITY". - // It defaults to "STANDARD", which is equivalent to "MULTI_REGIONAL" - // or "REGIONAL" depending on the bucket's location settings. + // StorageClass is the storage class of the object. This defines + // how objects are stored and determines the SLA and the cost of storage. + // Typical values are "STANDARD", "NEARLINE", "COLDLINE" and "ARCHIVE". + // Defaults to "STANDARD". + // See https://cloud.google.com/storage/docs/storage-classes for all + // valid values. StorageClass string // Created is the time the object was created. This field is read-only. @@ -1127,6 +1292,78 @@ type Query struct { // Versions indicates whether multiple versions of the same // object will be included in the results. Versions bool + + // fieldSelection is used to select only specific fields to be returned by + // the query. It's used internally and is populated for the user by + // calling Query.SetAttrSelection + fieldSelection string +} + +// attrToFieldMap maps the field names of ObjectAttrs to the underlying field +// names in the API call. Only the ObjectAttrs field names are visible to users +// because they are already part of the public API of the package. +var attrToFieldMap = map[string]string{ + "Bucket": "bucket", + "Name": "name", + "ContentType": "contentType", + "ContentLanguage": "contentLanguage", + "CacheControl": "cacheControl", + "EventBasedHold": "eventBasedHold", + "TemporaryHold": "temporaryHold", + "RetentionExpirationTime": "retentionExpirationTime", + "ACL": "acl", + "Owner": "owner", + "ContentEncoding": "contentEncoding", + "ContentDisposition": "contentDisposition", + "Size": "size", + "MD5": "md5Hash", + "CRC32C": "crc32c", + "MediaLink": "mediaLink", + "Metadata": "metadata", + "Generation": "generation", + "Metageneration": "metageneration", + "StorageClass": "storageClass", + "CustomerKeySHA256": "customerEncryption", + "KMSKeyName": "kmsKeyName", + "Created": "timeCreated", + "Deleted": "timeDeleted", + "Updated": "updated", + "Etag": "etag", +} + +// SetAttrSelection makes the query populate only specific attributes of +// objects. When iterating over objects, if you only need each object's name +// and size, pass []string{"Name", "Size"} to this method. Only these fields +// will be fetched for each object across the network; the other fields of +// ObjectAttr will remain at their default values. This is a performance +// optimization; for more information, see +// https://cloud.google.com/storage/docs/json_api/v1/how-tos/performance +func (q *Query) SetAttrSelection(attrs []string) error { + fieldSet := make(map[string]bool) + + for _, attr := range attrs { + field, ok := attrToFieldMap[attr] + if !ok { + return fmt.Errorf("storage: attr %v is not valid", attr) + } + fieldSet[field] = true + } + + if len(fieldSet) > 0 { + var b bytes.Buffer + b.WriteString("items(") + first := true + for field := range fieldSet { + if !first { + b.WriteString(",") + } + first = false + b.WriteString(field) + } + b.WriteString(")") + q.fieldSelection = b.String() + } + return nil } // Conditions constrain methods to act on specific generations of diff --git a/vendor/cloud.google.com/go/storage/writer.go b/vendor/cloud.google.com/go/storage/writer.go index a1165921287..1843a814155 100644 --- a/vendor/cloud.google.com/go/storage/writer.go +++ b/vendor/cloud.google.com/go/storage/writer.go @@ -45,12 +45,20 @@ type Writer struct { // Writer will attempt to send to the server in a single request. Objects // smaller than the size will be sent in a single request, while larger // objects will be split over multiple requests. The size will be rounded up - // to the nearest multiple of 256K. If zero, chunking will be disabled and - // the object will be uploaded in a single request. + // to the nearest multiple of 256K. // - // ChunkSize will default to a reasonable value. If you perform many concurrent - // writes of small objects, you may wish set ChunkSize to a value that matches - // your objects' sizes to avoid consuming large amounts of memory. + // ChunkSize will default to a reasonable value. If you perform many + // concurrent writes of small objects (under ~8MB), you may wish set ChunkSize + // to a value that matches your objects' sizes to avoid consuming large + // amounts of memory. See + // https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload#size + // for more information about performance trade-offs related to ChunkSize. + // + // If ChunkSize is set to zero, chunking will be disabled and the object will + // be uploaded in a single request without the use of a buffer. This will + // further reduce memory used during uploads, but will also prevent the writer + // from retrying in case of a transient error from the server, since a buffer + // is required in order to retry the failed request. // // ChunkSize must be set before the first Write call. ChunkSize int @@ -123,7 +131,8 @@ func (w *Writer) open() error { call := w.o.c.raw.Objects.Insert(w.o.bucket, rawObj). Media(pr, mediaOpts...). Projection("full"). - Context(w.ctx) + Context(w.ctx). + Name(w.o.object) if w.ProgressFunc != nil { call.ProgressUpdater(func(n, _ int64) { w.ProgressFunc(n) }) @@ -149,14 +158,10 @@ func (w *Writer) open() error { } setClientHeader(call.Header()) - // The internals that perform call.Do automatically retry - // uploading chunks, hence no need to add retries here. - // See issue https://github.com/googleapis/google-cloud-go/issues/1507. - // - // However, since this whole call's internals involve making the initial - // resumable upload session, the first HTTP request is not retried. - // TODO: Follow-up with google.golang.org/gensupport to solve - // https://github.com/googleapis/google-api-go-client/issues/392. + // The internals that perform call.Do automatically retry both the initial + // call to set up the upload as well as calls to upload individual chunks + // for a resumable upload (as long as the chunk size is non-zero). Hence + // there is no need to add retries here. resp, err = call.Do() } if err != nil { @@ -177,6 +182,9 @@ func (w *Writer) open() error { // error even though the write failed (or will fail). Always // use the error returned from Writer.Close to determine if // the upload was successful. +// +// Writes will be retried on transient errors from the server, unless +// Writer.ChunkSize has been set to zero. func (w *Writer) Write(p []byte) (n int, err error) { w.mu.Lock() werr := w.err diff --git a/vendor/cloud.google.com/go/tools.go b/vendor/cloud.google.com/go/tools.go new file mode 100644 index 00000000000..da5ca585d48 --- /dev/null +++ b/vendor/cloud.google.com/go/tools.go @@ -0,0 +1,31 @@ +// +build tools + +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This package exists to cause `go mod` and `go get` to believe these tools +// are dependencies, even though they are not runtime dependencies of any +// package (these are tools used by our CI builds). This means they will appear +// in our `go.mod` file, but will not be a part of the build. Also, since the +// build target is something non-existent, these should not be included in any +// binaries. + +package cloud + +import ( + _ "github.com/golang/protobuf/protoc-gen-go" + _ "github.com/jstemmer/go-junit-report" + _ "golang.org/x/lint/golint" + _ "golang.org/x/tools/cmd/goimports" +) diff --git a/vendor/github.com/Djarvur/go-err113/README.adoc b/vendor/github.com/Djarvur/go-err113/README.adoc index b4c1f437542..b26af403862 100644 --- a/vendor/github.com/Djarvur/go-err113/README.adoc +++ b/vendor/github.com/Djarvur/go-err113/README.adoc @@ -23,7 +23,7 @@ So, `err113` reports every `==` and `!=` comparison for exact `error` type varia Also, any call of `errors.New()` and `fmt.Errorf()` methods are reported except the calls used to initialise package-level variables and the `fmt.Errorf()` calls wrapping the other errors. -Note: non-standard packages, like `github.com/pkg/errors` are ignored complitely. +Note: non-standard packages, like `github.com/pkg/errors` are ignored completely. == Install @@ -71,3 +71,5 @@ Flags: == Thanks To link:https://github.com/quasilyte[Iskander (Alex) Sharipov] for the really useful advices. + +To link:https://github.com/jackwhelpton[Jack Whelpton] for the bugfix provided. \ No newline at end of file diff --git a/vendor/github.com/Djarvur/go-err113/comparison.go b/vendor/github.com/Djarvur/go-err113/comparison.go index 7e7777df68b..777d7523d19 100644 --- a/vendor/github.com/Djarvur/go-err113/comparison.go +++ b/vendor/github.com/Djarvur/go-err113/comparison.go @@ -99,5 +99,5 @@ func asImportedName(ex ast.Expr, info *types.Info) (string, bool) { return "", false } - return ep.Imported().Name(), true + return ep.Imported().Path(), true } diff --git a/vendor/github.com/Masterminds/semver/.travis.yml b/vendor/github.com/Masterminds/semver/.travis.yml new file mode 100644 index 00000000000..096369d44d9 --- /dev/null +++ b/vendor/github.com/Masterminds/semver/.travis.yml @@ -0,0 +1,29 @@ +language: go + +go: + - 1.6.x + - 1.7.x + - 1.8.x + - 1.9.x + - 1.10.x + - 1.11.x + - 1.12.x + - tip + +# Setting sudo access to false will let Travis CI use containers rather than +# VMs to run the tests. For more details see: +# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/ +# - http://docs.travis-ci.com/user/workers/standard-infrastructure/ +sudo: false + +script: + - make setup + - make test + +notifications: + webhooks: + urls: + - https://webhooks.gitter.im/e/06e3328629952dabe3e0 + on_success: change # options: [always|never|change] default: always + on_failure: always # options: [always|never|change] default: always + on_start: never # options: [always|never|change] default: always diff --git a/vendor/github.com/Masterminds/semver/CHANGELOG.md b/vendor/github.com/Masterminds/semver/CHANGELOG.md new file mode 100644 index 00000000000..e405c9a84d9 --- /dev/null +++ b/vendor/github.com/Masterminds/semver/CHANGELOG.md @@ -0,0 +1,109 @@ +# 1.5.0 (2019-09-11) + +## Added + +- #103: Add basic fuzzing for `NewVersion()` (thanks @jesse-c) + +## Changed + +- #82: Clarify wildcard meaning in range constraints and update tests for it (thanks @greysteil) +- #83: Clarify caret operator range for pre-1.0.0 dependencies (thanks @greysteil) +- #72: Adding docs comment pointing to vert for a cli +- #71: Update the docs on pre-release comparator handling +- #89: Test with new go versions (thanks @thedevsaddam) +- #87: Added $ to ValidPrerelease for better validation (thanks @jeremycarroll) + +## Fixed + +- #78: Fix unchecked error in example code (thanks @ravron) +- #70: Fix the handling of pre-releases and the 0.0.0 release edge case +- #97: Fixed copyright file for proper display on GitHub +- #107: Fix handling prerelease when sorting alphanum and num +- #109: Fixed where Validate sometimes returns wrong message on error + +# 1.4.2 (2018-04-10) + +## Changed +- #72: Updated the docs to point to vert for a console appliaction +- #71: Update the docs on pre-release comparator handling + +## Fixed +- #70: Fix the handling of pre-releases and the 0.0.0 release edge case + +# 1.4.1 (2018-04-02) + +## Fixed +- Fixed #64: Fix pre-release precedence issue (thanks @uudashr) + +# 1.4.0 (2017-10-04) + +## Changed +- #61: Update NewVersion to parse ints with a 64bit int size (thanks @zknill) + +# 1.3.1 (2017-07-10) + +## Fixed +- Fixed #57: number comparisons in prerelease sometimes inaccurate + +# 1.3.0 (2017-05-02) + +## Added +- #45: Added json (un)marshaling support (thanks @mh-cbon) +- Stability marker. See https://masterminds.github.io/stability/ + +## Fixed +- #51: Fix handling of single digit tilde constraint (thanks @dgodd) + +## Changed +- #55: The godoc icon moved from png to svg + +# 1.2.3 (2017-04-03) + +## Fixed +- #46: Fixed 0.x.x and 0.0.x in constraints being treated as * + +# Release 1.2.2 (2016-12-13) + +## Fixed +- #34: Fixed issue where hyphen range was not working with pre-release parsing. + +# Release 1.2.1 (2016-11-28) + +## Fixed +- #24: Fixed edge case issue where constraint "> 0" does not handle "0.0.1-alpha" + properly. + +# Release 1.2.0 (2016-11-04) + +## Added +- #20: Added MustParse function for versions (thanks @adamreese) +- #15: Added increment methods on versions (thanks @mh-cbon) + +## Fixed +- Issue #21: Per the SemVer spec (section 9) a pre-release is unstable and + might not satisfy the intended compatibility. The change here ignores pre-releases + on constraint checks (e.g., ~ or ^) when a pre-release is not part of the + constraint. For example, `^1.2.3` will ignore pre-releases while + `^1.2.3-alpha` will include them. + +# Release 1.1.1 (2016-06-30) + +## Changed +- Issue #9: Speed up version comparison performance (thanks @sdboyer) +- Issue #8: Added benchmarks (thanks @sdboyer) +- Updated Go Report Card URL to new location +- Updated Readme to add code snippet formatting (thanks @mh-cbon) +- Updating tagging to v[SemVer] structure for compatibility with other tools. + +# Release 1.1.0 (2016-03-11) + +- Issue #2: Implemented validation to provide reasons a versions failed a + constraint. + +# Release 1.0.1 (2015-12-31) + +- Fixed #1: * constraint failing on valid versions. + +# Release 1.0.0 (2015-10-20) + +- Initial release diff --git a/vendor/github.com/Masterminds/semver/LICENSE.txt b/vendor/github.com/Masterminds/semver/LICENSE.txt new file mode 100644 index 00000000000..9ff7da9c48b --- /dev/null +++ b/vendor/github.com/Masterminds/semver/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (C) 2014-2019, Matt Butcher and Matt Farina + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/Masterminds/semver/Makefile b/vendor/github.com/Masterminds/semver/Makefile new file mode 100644 index 00000000000..a7a1b4e36de --- /dev/null +++ b/vendor/github.com/Masterminds/semver/Makefile @@ -0,0 +1,36 @@ +.PHONY: setup +setup: + go get -u gopkg.in/alecthomas/gometalinter.v1 + gometalinter.v1 --install + +.PHONY: test +test: validate lint + @echo "==> Running tests" + go test -v + +.PHONY: validate +validate: + @echo "==> Running static validations" + @gometalinter.v1 \ + --disable-all \ + --enable deadcode \ + --severity deadcode:error \ + --enable gofmt \ + --enable gosimple \ + --enable ineffassign \ + --enable misspell \ + --enable vet \ + --tests \ + --vendor \ + --deadline 60s \ + ./... || exit_code=1 + +.PHONY: lint +lint: + @echo "==> Running linters" + @gometalinter.v1 \ + --disable-all \ + --enable golint \ + --vendor \ + --deadline 60s \ + ./... || : diff --git a/vendor/github.com/Masterminds/semver/README.md b/vendor/github.com/Masterminds/semver/README.md new file mode 100644 index 00000000000..1b52d2f4362 --- /dev/null +++ b/vendor/github.com/Masterminds/semver/README.md @@ -0,0 +1,194 @@ +# SemVer + +The `semver` package provides the ability to work with [Semantic Versions](http://semver.org) in Go. Specifically it provides the ability to: + +* Parse semantic versions +* Sort semantic versions +* Check if a semantic version fits within a set of constraints +* Optionally work with a `v` prefix + +[![Stability: +Active](https://masterminds.github.io/stability/active.svg)](https://masterminds.github.io/stability/active.html) +[![Build Status](https://travis-ci.org/Masterminds/semver.svg)](https://travis-ci.org/Masterminds/semver) [![Build status](https://ci.appveyor.com/api/projects/status/jfk66lib7hb985k8/branch/master?svg=true&passingText=windows%20build%20passing&failingText=windows%20build%20failing)](https://ci.appveyor.com/project/mattfarina/semver/branch/master) [![GoDoc](https://godoc.org/github.com/Masterminds/semver?status.svg)](https://godoc.org/github.com/Masterminds/semver) [![Go Report Card](https://goreportcard.com/badge/github.com/Masterminds/semver)](https://goreportcard.com/report/github.com/Masterminds/semver) + +If you are looking for a command line tool for version comparisons please see +[vert](https://github.com/Masterminds/vert) which uses this library. + +## Parsing Semantic Versions + +To parse a semantic version use the `NewVersion` function. For example, + +```go + v, err := semver.NewVersion("1.2.3-beta.1+build345") +``` + +If there is an error the version wasn't parseable. The version object has methods +to get the parts of the version, compare it to other versions, convert the +version back into a string, and get the original string. For more details +please see the [documentation](https://godoc.org/github.com/Masterminds/semver). + +## Sorting Semantic Versions + +A set of versions can be sorted using the [`sort`](https://golang.org/pkg/sort/) +package from the standard library. For example, + +```go + raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} + vs := make([]*semver.Version, len(raw)) + for i, r := range raw { + v, err := semver.NewVersion(r) + if err != nil { + t.Errorf("Error parsing version: %s", err) + } + + vs[i] = v + } + + sort.Sort(semver.Collection(vs)) +``` + +## Checking Version Constraints + +Checking a version against version constraints is one of the most featureful +parts of the package. + +```go + c, err := semver.NewConstraint(">= 1.2.3") + if err != nil { + // Handle constraint not being parseable. + } + + v, _ := semver.NewVersion("1.3") + if err != nil { + // Handle version not being parseable. + } + // Check if the version meets the constraints. The a variable will be true. + a := c.Check(v) +``` + +## Basic Comparisons + +There are two elements to the comparisons. First, a comparison string is a list +of comma separated and comparisons. These are then separated by || separated or +comparisons. For example, `">= 1.2, < 3.0.0 || >= 4.2.3"` is looking for a +comparison that's greater than or equal to 1.2 and less than 3.0.0 or is +greater than or equal to 4.2.3. + +The basic comparisons are: + +* `=`: equal (aliased to no operator) +* `!=`: not equal +* `>`: greater than +* `<`: less than +* `>=`: greater than or equal to +* `<=`: less than or equal to + +## Working With Pre-release Versions + +Pre-releases, for those not familiar with them, are used for software releases +prior to stable or generally available releases. Examples of pre-releases include +development, alpha, beta, and release candidate releases. A pre-release may be +a version such as `1.2.3-beta.1` while the stable release would be `1.2.3`. In the +order of precidence, pre-releases come before their associated releases. In this +example `1.2.3-beta.1 < 1.2.3`. + +According to the Semantic Version specification pre-releases may not be +API compliant with their release counterpart. It says, + +> A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version. + +SemVer comparisons without a pre-release comparator will skip pre-release versions. +For example, `>=1.2.3` will skip pre-releases when looking at a list of releases +while `>=1.2.3-0` will evaluate and find pre-releases. + +The reason for the `0` as a pre-release version in the example comparison is +because pre-releases can only contain ASCII alphanumerics and hyphens (along with +`.` separators), per the spec. Sorting happens in ASCII sort order, again per the spec. The lowest character is a `0` in ASCII sort order (see an [ASCII Table](http://www.asciitable.com/)) + +Understanding ASCII sort ordering is important because A-Z comes before a-z. That +means `>=1.2.3-BETA` will return `1.2.3-alpha`. What you might expect from case +sensitivity doesn't apply here. This is due to ASCII sort ordering which is what +the spec specifies. + +## Hyphen Range Comparisons + +There are multiple methods to handle ranges and the first is hyphens ranges. +These look like: + +* `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5` +* `2.3.4 - 4.5` which is equivalent to `>= 2.3.4, <= 4.5` + +## Wildcards In Comparisons + +The `x`, `X`, and `*` characters can be used as a wildcard character. This works +for all comparison operators. When used on the `=` operator it falls +back to the pack level comparison (see tilde below). For example, + +* `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` +* `>= 1.2.x` is equivalent to `>= 1.2.0` +* `<= 2.x` is equivalent to `< 3` +* `*` is equivalent to `>= 0.0.0` + +## Tilde Range Comparisons (Patch) + +The tilde (`~`) comparison operator is for patch level ranges when a minor +version is specified and major level changes when the minor number is missing. +For example, + +* `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0` +* `~1` is equivalent to `>= 1, < 2` +* `~2.3` is equivalent to `>= 2.3, < 2.4` +* `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` +* `~1.x` is equivalent to `>= 1, < 2` + +## Caret Range Comparisons (Major) + +The caret (`^`) comparison operator is for major level changes. This is useful +when comparisons of API versions as a major change is API breaking. For example, + +* `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` +* `^0.0.1` is equivalent to `>= 0.0.1, < 1.0.0` +* `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` +* `^2.3` is equivalent to `>= 2.3, < 3` +* `^2.x` is equivalent to `>= 2.0.0, < 3` + +# Validation + +In addition to testing a version against a constraint, a version can be validated +against a constraint. When validation fails a slice of errors containing why a +version didn't meet the constraint is returned. For example, + +```go + c, err := semver.NewConstraint("<= 1.2.3, >= 1.4") + if err != nil { + // Handle constraint not being parseable. + } + + v, _ := semver.NewVersion("1.3") + if err != nil { + // Handle version not being parseable. + } + + // Validate a version against a constraint. + a, msgs := c.Validate(v) + // a is false + for _, m := range msgs { + fmt.Println(m) + + // Loops over the errors which would read + // "1.3 is greater than 1.2.3" + // "1.3 is less than 1.4" + } +``` + +# Fuzzing + + [dvyukov/go-fuzz](https://github.com/dvyukov/go-fuzz) is used for fuzzing. + +1. `go-fuzz-build` +2. `go-fuzz -workdir=fuzz` + +# Contribute + +If you find an issue or want to contribute please file an [issue](https://github.com/Masterminds/semver/issues) +or [create a pull request](https://github.com/Masterminds/semver/pulls). diff --git a/vendor/github.com/Masterminds/semver/appveyor.yml b/vendor/github.com/Masterminds/semver/appveyor.yml new file mode 100644 index 00000000000..b2778df15a4 --- /dev/null +++ b/vendor/github.com/Masterminds/semver/appveyor.yml @@ -0,0 +1,44 @@ +version: build-{build}.{branch} + +clone_folder: C:\gopath\src\github.com\Masterminds\semver +shallow_clone: true + +environment: + GOPATH: C:\gopath + +platform: + - x64 + +install: + - go version + - go env + - go get -u gopkg.in/alecthomas/gometalinter.v1 + - set PATH=%PATH%;%GOPATH%\bin + - gometalinter.v1.exe --install + +build_script: + - go install -v ./... + +test_script: + - "gometalinter.v1 \ + --disable-all \ + --enable deadcode \ + --severity deadcode:error \ + --enable gofmt \ + --enable gosimple \ + --enable ineffassign \ + --enable misspell \ + --enable vet \ + --tests \ + --vendor \ + --deadline 60s \ + ./... || exit_code=1" + - "gometalinter.v1 \ + --disable-all \ + --enable golint \ + --vendor \ + --deadline 60s \ + ./... || :" + - go test -v + +deploy: off diff --git a/vendor/github.com/Masterminds/semver/collection.go b/vendor/github.com/Masterminds/semver/collection.go new file mode 100644 index 00000000000..a78235895fd --- /dev/null +++ b/vendor/github.com/Masterminds/semver/collection.go @@ -0,0 +1,24 @@ +package semver + +// Collection is a collection of Version instances and implements the sort +// interface. See the sort package for more details. +// https://golang.org/pkg/sort/ +type Collection []*Version + +// Len returns the length of a collection. The number of Version instances +// on the slice. +func (c Collection) Len() int { + return len(c) +} + +// Less is needed for the sort interface to compare two Version objects on the +// slice. If checks if one is less than the other. +func (c Collection) Less(i, j int) bool { + return c[i].LessThan(c[j]) +} + +// Swap is needed for the sort interface to replace the Version objects +// at two different positions in the slice. +func (c Collection) Swap(i, j int) { + c[i], c[j] = c[j], c[i] +} diff --git a/vendor/github.com/Masterminds/semver/constraints.go b/vendor/github.com/Masterminds/semver/constraints.go new file mode 100644 index 00000000000..b94b93413f3 --- /dev/null +++ b/vendor/github.com/Masterminds/semver/constraints.go @@ -0,0 +1,423 @@ +package semver + +import ( + "errors" + "fmt" + "regexp" + "strings" +) + +// Constraints is one or more constraint that a semantic version can be +// checked against. +type Constraints struct { + constraints [][]*constraint +} + +// NewConstraint returns a Constraints instance that a Version instance can +// be checked against. If there is a parse error it will be returned. +func NewConstraint(c string) (*Constraints, error) { + + // Rewrite - ranges into a comparison operation. + c = rewriteRange(c) + + ors := strings.Split(c, "||") + or := make([][]*constraint, len(ors)) + for k, v := range ors { + cs := strings.Split(v, ",") + result := make([]*constraint, len(cs)) + for i, s := range cs { + pc, err := parseConstraint(s) + if err != nil { + return nil, err + } + + result[i] = pc + } + or[k] = result + } + + o := &Constraints{constraints: or} + return o, nil +} + +// Check tests if a version satisfies the constraints. +func (cs Constraints) Check(v *Version) bool { + // loop over the ORs and check the inner ANDs + for _, o := range cs.constraints { + joy := true + for _, c := range o { + if !c.check(v) { + joy = false + break + } + } + + if joy { + return true + } + } + + return false +} + +// Validate checks if a version satisfies a constraint. If not a slice of +// reasons for the failure are returned in addition to a bool. +func (cs Constraints) Validate(v *Version) (bool, []error) { + // loop over the ORs and check the inner ANDs + var e []error + + // Capture the prerelease message only once. When it happens the first time + // this var is marked + var prerelesase bool + for _, o := range cs.constraints { + joy := true + for _, c := range o { + // Before running the check handle the case there the version is + // a prerelease and the check is not searching for prereleases. + if c.con.pre == "" && v.pre != "" { + if !prerelesase { + em := fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) + e = append(e, em) + prerelesase = true + } + joy = false + + } else { + + if !c.check(v) { + em := fmt.Errorf(c.msg, v, c.orig) + e = append(e, em) + joy = false + } + } + } + + if joy { + return true, []error{} + } + } + + return false, e +} + +var constraintOps map[string]cfunc +var constraintMsg map[string]string +var constraintRegex *regexp.Regexp + +func init() { + constraintOps = map[string]cfunc{ + "": constraintTildeOrEqual, + "=": constraintTildeOrEqual, + "!=": constraintNotEqual, + ">": constraintGreaterThan, + "<": constraintLessThan, + ">=": constraintGreaterThanEqual, + "=>": constraintGreaterThanEqual, + "<=": constraintLessThanEqual, + "=<": constraintLessThanEqual, + "~": constraintTilde, + "~>": constraintTilde, + "^": constraintCaret, + } + + constraintMsg = map[string]string{ + "": "%s is not equal to %s", + "=": "%s is not equal to %s", + "!=": "%s is equal to %s", + ">": "%s is less than or equal to %s", + "<": "%s is greater than or equal to %s", + ">=": "%s is less than %s", + "=>": "%s is less than %s", + "<=": "%s is greater than %s", + "=<": "%s is greater than %s", + "~": "%s does not have same major and minor version as %s", + "~>": "%s does not have same major and minor version as %s", + "^": "%s does not have same major version as %s", + } + + ops := make([]string, 0, len(constraintOps)) + for k := range constraintOps { + ops = append(ops, regexp.QuoteMeta(k)) + } + + constraintRegex = regexp.MustCompile(fmt.Sprintf( + `^\s*(%s)\s*(%s)\s*$`, + strings.Join(ops, "|"), + cvRegex)) + + constraintRangeRegex = regexp.MustCompile(fmt.Sprintf( + `\s*(%s)\s+-\s+(%s)\s*`, + cvRegex, cvRegex)) +} + +// An individual constraint +type constraint struct { + // The callback function for the restraint. It performs the logic for + // the constraint. + function cfunc + + msg string + + // The version used in the constraint check. For example, if a constraint + // is '<= 2.0.0' the con a version instance representing 2.0.0. + con *Version + + // The original parsed version (e.g., 4.x from != 4.x) + orig string + + // When an x is used as part of the version (e.g., 1.x) + minorDirty bool + dirty bool + patchDirty bool +} + +// Check if a version meets the constraint +func (c *constraint) check(v *Version) bool { + return c.function(v, c) +} + +type cfunc func(v *Version, c *constraint) bool + +func parseConstraint(c string) (*constraint, error) { + m := constraintRegex.FindStringSubmatch(c) + if m == nil { + return nil, fmt.Errorf("improper constraint: %s", c) + } + + ver := m[2] + orig := ver + minorDirty := false + patchDirty := false + dirty := false + if isX(m[3]) { + ver = "0.0.0" + dirty = true + } else if isX(strings.TrimPrefix(m[4], ".")) || m[4] == "" { + minorDirty = true + dirty = true + ver = fmt.Sprintf("%s.0.0%s", m[3], m[6]) + } else if isX(strings.TrimPrefix(m[5], ".")) { + dirty = true + patchDirty = true + ver = fmt.Sprintf("%s%s.0%s", m[3], m[4], m[6]) + } + + con, err := NewVersion(ver) + if err != nil { + + // The constraintRegex should catch any regex parsing errors. So, + // we should never get here. + return nil, errors.New("constraint Parser Error") + } + + cs := &constraint{ + function: constraintOps[m[1]], + msg: constraintMsg[m[1]], + con: con, + orig: orig, + minorDirty: minorDirty, + patchDirty: patchDirty, + dirty: dirty, + } + return cs, nil +} + +// Constraint functions +func constraintNotEqual(v *Version, c *constraint) bool { + if c.dirty { + + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false + } + + if c.con.Major() != v.Major() { + return true + } + if c.con.Minor() != v.Minor() && !c.minorDirty { + return true + } else if c.minorDirty { + return false + } + + return false + } + + return !v.Equal(c.con) +} + +func constraintGreaterThan(v *Version, c *constraint) bool { + + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false + } + + return v.Compare(c.con) == 1 +} + +func constraintLessThan(v *Version, c *constraint) bool { + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false + } + + if !c.dirty { + return v.Compare(c.con) < 0 + } + + if v.Major() > c.con.Major() { + return false + } else if v.Minor() > c.con.Minor() && !c.minorDirty { + return false + } + + return true +} + +func constraintGreaterThanEqual(v *Version, c *constraint) bool { + + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false + } + + return v.Compare(c.con) >= 0 +} + +func constraintLessThanEqual(v *Version, c *constraint) bool { + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false + } + + if !c.dirty { + return v.Compare(c.con) <= 0 + } + + if v.Major() > c.con.Major() { + return false + } else if v.Minor() > c.con.Minor() && !c.minorDirty { + return false + } + + return true +} + +// ~*, ~>* --> >= 0.0.0 (any) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0, <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0, <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0, <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3, <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0, <1.3.0 +func constraintTilde(v *Version, c *constraint) bool { + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false + } + + if v.LessThan(c.con) { + return false + } + + // ~0.0.0 is a special case where all constraints are accepted. It's + // equivalent to >= 0.0.0. + if c.con.Major() == 0 && c.con.Minor() == 0 && c.con.Patch() == 0 && + !c.minorDirty && !c.patchDirty { + return true + } + + if v.Major() != c.con.Major() { + return false + } + + if v.Minor() != c.con.Minor() && !c.minorDirty { + return false + } + + return true +} + +// When there is a .x (dirty) status it automatically opts in to ~. Otherwise +// it's a straight = +func constraintTildeOrEqual(v *Version, c *constraint) bool { + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false + } + + if c.dirty { + c.msg = constraintMsg["~"] + return constraintTilde(v, c) + } + + return v.Equal(c.con) +} + +// ^* --> (any) +// ^2, ^2.x, ^2.x.x --> >=2.0.0, <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0, <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0, <2.0.0 +// ^1.2.3 --> >=1.2.3, <2.0.0 +// ^1.2.0 --> >=1.2.0, <2.0.0 +func constraintCaret(v *Version, c *constraint) bool { + // If there is a pre-release on the version but the constraint isn't looking + // for them assume that pre-releases are not compatible. See issue 21 for + // more details. + if v.Prerelease() != "" && c.con.Prerelease() == "" { + return false + } + + if v.LessThan(c.con) { + return false + } + + if v.Major() != c.con.Major() { + return false + } + + return true +} + +var constraintRangeRegex *regexp.Regexp + +const cvRegex string = `v?([0-9|x|X|\*]+)(\.[0-9|x|X|\*]+)?(\.[0-9|x|X|\*]+)?` + + `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + + `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + +func isX(x string) bool { + switch x { + case "x", "*", "X": + return true + default: + return false + } +} + +func rewriteRange(i string) string { + m := constraintRangeRegex.FindAllStringSubmatch(i, -1) + if m == nil { + return i + } + o := i + for _, v := range m { + t := fmt.Sprintf(">= %s, <= %s", v[1], v[11]) + o = strings.Replace(o, v[0], t, 1) + } + + return o +} diff --git a/vendor/github.com/Masterminds/semver/doc.go b/vendor/github.com/Masterminds/semver/doc.go new file mode 100644 index 00000000000..6a6c24c6d6e --- /dev/null +++ b/vendor/github.com/Masterminds/semver/doc.go @@ -0,0 +1,115 @@ +/* +Package semver provides the ability to work with Semantic Versions (http://semver.org) in Go. + +Specifically it provides the ability to: + + * Parse semantic versions + * Sort semantic versions + * Check if a semantic version fits within a set of constraints + * Optionally work with a `v` prefix + +Parsing Semantic Versions + +To parse a semantic version use the `NewVersion` function. For example, + + v, err := semver.NewVersion("1.2.3-beta.1+build345") + +If there is an error the version wasn't parseable. The version object has methods +to get the parts of the version, compare it to other versions, convert the +version back into a string, and get the original string. For more details +please see the documentation at https://godoc.org/github.com/Masterminds/semver. + +Sorting Semantic Versions + +A set of versions can be sorted using the `sort` package from the standard library. +For example, + + raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} + vs := make([]*semver.Version, len(raw)) + for i, r := range raw { + v, err := semver.NewVersion(r) + if err != nil { + t.Errorf("Error parsing version: %s", err) + } + + vs[i] = v + } + + sort.Sort(semver.Collection(vs)) + +Checking Version Constraints + +Checking a version against version constraints is one of the most featureful +parts of the package. + + c, err := semver.NewConstraint(">= 1.2.3") + if err != nil { + // Handle constraint not being parseable. + } + + v, err := semver.NewVersion("1.3") + if err != nil { + // Handle version not being parseable. + } + // Check if the version meets the constraints. The a variable will be true. + a := c.Check(v) + +Basic Comparisons + +There are two elements to the comparisons. First, a comparison string is a list +of comma separated and comparisons. These are then separated by || separated or +comparisons. For example, `">= 1.2, < 3.0.0 || >= 4.2.3"` is looking for a +comparison that's greater than or equal to 1.2 and less than 3.0.0 or is +greater than or equal to 4.2.3. + +The basic comparisons are: + + * `=`: equal (aliased to no operator) + * `!=`: not equal + * `>`: greater than + * `<`: less than + * `>=`: greater than or equal to + * `<=`: less than or equal to + +Hyphen Range Comparisons + +There are multiple methods to handle ranges and the first is hyphens ranges. +These look like: + + * `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5` + * `2.3.4 - 4.5` which is equivalent to `>= 2.3.4, <= 4.5` + +Wildcards In Comparisons + +The `x`, `X`, and `*` characters can be used as a wildcard character. This works +for all comparison operators. When used on the `=` operator it falls +back to the pack level comparison (see tilde below). For example, + + * `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` + * `>= 1.2.x` is equivalent to `>= 1.2.0` + * `<= 2.x` is equivalent to `<= 3` + * `*` is equivalent to `>= 0.0.0` + +Tilde Range Comparisons (Patch) + +The tilde (`~`) comparison operator is for patch level ranges when a minor +version is specified and major level changes when the minor number is missing. +For example, + + * `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0` + * `~1` is equivalent to `>= 1, < 2` + * `~2.3` is equivalent to `>= 2.3, < 2.4` + * `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` + * `~1.x` is equivalent to `>= 1, < 2` + +Caret Range Comparisons (Major) + +The caret (`^`) comparison operator is for major level changes. This is useful +when comparisons of API versions as a major change is API breaking. For example, + + * `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` + * `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` + * `^2.3` is equivalent to `>= 2.3, < 3` + * `^2.x` is equivalent to `>= 2.0.0, < 3` +*/ +package semver diff --git a/vendor/github.com/Masterminds/semver/version.go b/vendor/github.com/Masterminds/semver/version.go new file mode 100644 index 00000000000..400d4f93412 --- /dev/null +++ b/vendor/github.com/Masterminds/semver/version.go @@ -0,0 +1,425 @@ +package semver + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "regexp" + "strconv" + "strings" +) + +// The compiled version of the regex created at init() is cached here so it +// only needs to be created once. +var versionRegex *regexp.Regexp +var validPrereleaseRegex *regexp.Regexp + +var ( + // ErrInvalidSemVer is returned a version is found to be invalid when + // being parsed. + ErrInvalidSemVer = errors.New("Invalid Semantic Version") + + // ErrInvalidMetadata is returned when the metadata is an invalid format + ErrInvalidMetadata = errors.New("Invalid Metadata string") + + // ErrInvalidPrerelease is returned when the pre-release is an invalid format + ErrInvalidPrerelease = errors.New("Invalid Prerelease string") +) + +// SemVerRegex is the regular expression used to parse a semantic version. +const SemVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` + + `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + + `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + +// ValidPrerelease is the regular expression which validates +// both prerelease and metadata values. +const ValidPrerelease string = `^([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*)$` + +// Version represents a single semantic version. +type Version struct { + major, minor, patch int64 + pre string + metadata string + original string +} + +func init() { + versionRegex = regexp.MustCompile("^" + SemVerRegex + "$") + validPrereleaseRegex = regexp.MustCompile(ValidPrerelease) +} + +// NewVersion parses a given version and returns an instance of Version or +// an error if unable to parse the version. +func NewVersion(v string) (*Version, error) { + m := versionRegex.FindStringSubmatch(v) + if m == nil { + return nil, ErrInvalidSemVer + } + + sv := &Version{ + metadata: m[8], + pre: m[5], + original: v, + } + + var temp int64 + temp, err := strconv.ParseInt(m[1], 10, 64) + if err != nil { + return nil, fmt.Errorf("Error parsing version segment: %s", err) + } + sv.major = temp + + if m[2] != "" { + temp, err = strconv.ParseInt(strings.TrimPrefix(m[2], "."), 10, 64) + if err != nil { + return nil, fmt.Errorf("Error parsing version segment: %s", err) + } + sv.minor = temp + } else { + sv.minor = 0 + } + + if m[3] != "" { + temp, err = strconv.ParseInt(strings.TrimPrefix(m[3], "."), 10, 64) + if err != nil { + return nil, fmt.Errorf("Error parsing version segment: %s", err) + } + sv.patch = temp + } else { + sv.patch = 0 + } + + return sv, nil +} + +// MustParse parses a given version and panics on error. +func MustParse(v string) *Version { + sv, err := NewVersion(v) + if err != nil { + panic(err) + } + return sv +} + +// String converts a Version object to a string. +// Note, if the original version contained a leading v this version will not. +// See the Original() method to retrieve the original value. Semantic Versions +// don't contain a leading v per the spec. Instead it's optional on +// implementation. +func (v *Version) String() string { + var buf bytes.Buffer + + fmt.Fprintf(&buf, "%d.%d.%d", v.major, v.minor, v.patch) + if v.pre != "" { + fmt.Fprintf(&buf, "-%s", v.pre) + } + if v.metadata != "" { + fmt.Fprintf(&buf, "+%s", v.metadata) + } + + return buf.String() +} + +// Original returns the original value passed in to be parsed. +func (v *Version) Original() string { + return v.original +} + +// Major returns the major version. +func (v *Version) Major() int64 { + return v.major +} + +// Minor returns the minor version. +func (v *Version) Minor() int64 { + return v.minor +} + +// Patch returns the patch version. +func (v *Version) Patch() int64 { + return v.patch +} + +// Prerelease returns the pre-release version. +func (v *Version) Prerelease() string { + return v.pre +} + +// Metadata returns the metadata on the version. +func (v *Version) Metadata() string { + return v.metadata +} + +// originalVPrefix returns the original 'v' prefix if any. +func (v *Version) originalVPrefix() string { + + // Note, only lowercase v is supported as a prefix by the parser. + if v.original != "" && v.original[:1] == "v" { + return v.original[:1] + } + return "" +} + +// IncPatch produces the next patch version. +// If the current version does not have prerelease/metadata information, +// it unsets metadata and prerelease values, increments patch number. +// If the current version has any of prerelease or metadata information, +// it unsets both values and keeps curent patch value +func (v Version) IncPatch() Version { + vNext := v + // according to http://semver.org/#spec-item-9 + // Pre-release versions have a lower precedence than the associated normal version. + // according to http://semver.org/#spec-item-10 + // Build metadata SHOULD be ignored when determining version precedence. + if v.pre != "" { + vNext.metadata = "" + vNext.pre = "" + } else { + vNext.metadata = "" + vNext.pre = "" + vNext.patch = v.patch + 1 + } + vNext.original = v.originalVPrefix() + "" + vNext.String() + return vNext +} + +// IncMinor produces the next minor version. +// Sets patch to 0. +// Increments minor number. +// Unsets metadata. +// Unsets prerelease status. +func (v Version) IncMinor() Version { + vNext := v + vNext.metadata = "" + vNext.pre = "" + vNext.patch = 0 + vNext.minor = v.minor + 1 + vNext.original = v.originalVPrefix() + "" + vNext.String() + return vNext +} + +// IncMajor produces the next major version. +// Sets patch to 0. +// Sets minor to 0. +// Increments major number. +// Unsets metadata. +// Unsets prerelease status. +func (v Version) IncMajor() Version { + vNext := v + vNext.metadata = "" + vNext.pre = "" + vNext.patch = 0 + vNext.minor = 0 + vNext.major = v.major + 1 + vNext.original = v.originalVPrefix() + "" + vNext.String() + return vNext +} + +// SetPrerelease defines the prerelease value. +// Value must not include the required 'hypen' prefix. +func (v Version) SetPrerelease(prerelease string) (Version, error) { + vNext := v + if len(prerelease) > 0 && !validPrereleaseRegex.MatchString(prerelease) { + return vNext, ErrInvalidPrerelease + } + vNext.pre = prerelease + vNext.original = v.originalVPrefix() + "" + vNext.String() + return vNext, nil +} + +// SetMetadata defines metadata value. +// Value must not include the required 'plus' prefix. +func (v Version) SetMetadata(metadata string) (Version, error) { + vNext := v + if len(metadata) > 0 && !validPrereleaseRegex.MatchString(metadata) { + return vNext, ErrInvalidMetadata + } + vNext.metadata = metadata + vNext.original = v.originalVPrefix() + "" + vNext.String() + return vNext, nil +} + +// LessThan tests if one version is less than another one. +func (v *Version) LessThan(o *Version) bool { + return v.Compare(o) < 0 +} + +// GreaterThan tests if one version is greater than another one. +func (v *Version) GreaterThan(o *Version) bool { + return v.Compare(o) > 0 +} + +// Equal tests if two versions are equal to each other. +// Note, versions can be equal with different metadata since metadata +// is not considered part of the comparable version. +func (v *Version) Equal(o *Version) bool { + return v.Compare(o) == 0 +} + +// Compare compares this version to another one. It returns -1, 0, or 1 if +// the version smaller, equal, or larger than the other version. +// +// Versions are compared by X.Y.Z. Build metadata is ignored. Prerelease is +// lower than the version without a prerelease. +func (v *Version) Compare(o *Version) int { + // Compare the major, minor, and patch version for differences. If a + // difference is found return the comparison. + if d := compareSegment(v.Major(), o.Major()); d != 0 { + return d + } + if d := compareSegment(v.Minor(), o.Minor()); d != 0 { + return d + } + if d := compareSegment(v.Patch(), o.Patch()); d != 0 { + return d + } + + // At this point the major, minor, and patch versions are the same. + ps := v.pre + po := o.Prerelease() + + if ps == "" && po == "" { + return 0 + } + if ps == "" { + return 1 + } + if po == "" { + return -1 + } + + return comparePrerelease(ps, po) +} + +// UnmarshalJSON implements JSON.Unmarshaler interface. +func (v *Version) UnmarshalJSON(b []byte) error { + var s string + if err := json.Unmarshal(b, &s); err != nil { + return err + } + temp, err := NewVersion(s) + if err != nil { + return err + } + v.major = temp.major + v.minor = temp.minor + v.patch = temp.patch + v.pre = temp.pre + v.metadata = temp.metadata + v.original = temp.original + temp = nil + return nil +} + +// MarshalJSON implements JSON.Marshaler interface. +func (v *Version) MarshalJSON() ([]byte, error) { + return json.Marshal(v.String()) +} + +func compareSegment(v, o int64) int { + if v < o { + return -1 + } + if v > o { + return 1 + } + + return 0 +} + +func comparePrerelease(v, o string) int { + + // split the prelease versions by their part. The separator, per the spec, + // is a . + sparts := strings.Split(v, ".") + oparts := strings.Split(o, ".") + + // Find the longer length of the parts to know how many loop iterations to + // go through. + slen := len(sparts) + olen := len(oparts) + + l := slen + if olen > slen { + l = olen + } + + // Iterate over each part of the prereleases to compare the differences. + for i := 0; i < l; i++ { + // Since the lentgh of the parts can be different we need to create + // a placeholder. This is to avoid out of bounds issues. + stemp := "" + if i < slen { + stemp = sparts[i] + } + + otemp := "" + if i < olen { + otemp = oparts[i] + } + + d := comparePrePart(stemp, otemp) + if d != 0 { + return d + } + } + + // Reaching here means two versions are of equal value but have different + // metadata (the part following a +). They are not identical in string form + // but the version comparison finds them to be equal. + return 0 +} + +func comparePrePart(s, o string) int { + // Fastpath if they are equal + if s == o { + return 0 + } + + // When s or o are empty we can use the other in an attempt to determine + // the response. + if s == "" { + if o != "" { + return -1 + } + return 1 + } + + if o == "" { + if s != "" { + return 1 + } + return -1 + } + + // When comparing strings "99" is greater than "103". To handle + // cases like this we need to detect numbers and compare them. According + // to the semver spec, numbers are always positive. If there is a - at the + // start like -99 this is to be evaluated as an alphanum. numbers always + // have precedence over alphanum. Parsing as Uints because negative numbers + // are ignored. + + oi, n1 := strconv.ParseUint(o, 10, 64) + si, n2 := strconv.ParseUint(s, 10, 64) + + // The case where both are strings compare the strings + if n1 != nil && n2 != nil { + if s > o { + return 1 + } + return -1 + } else if n1 != nil { + // o is a string and s is a number + return -1 + } else if n2 != nil { + // s is a string and o is a number + return 1 + } + // Both are numbers + if si > oi { + return 1 + } + return -1 + +} diff --git a/vendor/github.com/Masterminds/semver/version_fuzz.go b/vendor/github.com/Masterminds/semver/version_fuzz.go new file mode 100644 index 00000000000..b42bcd62b95 --- /dev/null +++ b/vendor/github.com/Masterminds/semver/version_fuzz.go @@ -0,0 +1,10 @@ +// +build gofuzz + +package semver + +func Fuzz(data []byte) int { + if _, err := NewVersion(string(data)); err != nil { + return 0 + } + return 1 +} 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 2def23fa1d1..3b809e8478c 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/config.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/config.go @@ -43,7 +43,7 @@ type Config struct { // An optional endpoint URL (hostname only or fully qualified URI) // that overrides the default generated endpoint for a client. Set this - // to `""` to use the default generated endpoint. + // to `nil` or the value to `""` to use the default generated endpoint. // // Note: You must still provide a `Region` value when specifying an // endpoint for a client. @@ -138,7 +138,7 @@ type Config struct { // `ExpectContinueTimeout` for information on adjusting the continue wait // timeout. https://golang.org/pkg/net/http/#Transport // - // You should use this flag to disble 100-Continue if you experience issues + // You should use this flag to disable 100-Continue if you experience issues // with proxies or third party S3 compatible services. S3Disable100Continue *bool @@ -183,7 +183,7 @@ type Config struct { // // Example: // sess := session.Must(session.NewSession(aws.NewConfig() - // .WithEC2MetadataDiableTimeoutOverride(true))) + // .WithEC2MetadataDisableTimeoutOverride(true))) // // svc := s3.New(sess) // @@ -194,7 +194,7 @@ type Config struct { // both IPv4 and IPv6 addressing. // // Setting this for a service which does not support dual stack will fail - // to make requets. It is not recommended to set this value on the session + // to make requests. It is not recommended to set this value on the session // as it will apply to all service clients created with the session. Even // services which don't support dual stack endpoints. // @@ -238,6 +238,7 @@ type Config struct { // EnableEndpointDiscovery will allow for endpoint discovery on operations that // have the definition in its model. By default, endpoint discovery is off. + // To use EndpointDiscovery, Endpoint should be unset or set to an empty string. // // Example: // sess := session.Must(session.NewSession(&aws.Config{ diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go index aa902d70837..d95a5eb5408 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go @@ -225,6 +225,8 @@ var ValidateEndpointHandler = request.NamedHandler{Name: "core.ValidateEndpointH if r.ClientInfo.SigningRegion == "" && aws.StringValue(r.Config.Region) == "" { r.Error = aws.ErrMissingRegion } else if r.ClientInfo.Endpoint == "" { + // Was any endpoint provided by the user, or one was derived by the + // SDK's endpoint resolver? r.Error = aws.ErrMissingEndpoint } }} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go index e1551495812..22b5c5d9f32 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go @@ -17,8 +17,9 @@ var ( ErrSharedCredentialsHomeNotFound = awserr.New("UserHomeNotFound", "user home directory not found.", nil) ) -// A SharedCredentialsProvider retrieves credentials from the current user's home -// directory, and keeps track if those credentials are expired. +// A SharedCredentialsProvider retrieves access key pair (access key ID, +// secret access key, and session token if present) credentials from the current +// user's home directory, and keeps track if those credentials are expired. // // Profile ini file example: $HOME/.aws/credentials type SharedCredentialsProvider struct { diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go index 6feb262b2f7..cefe2a76d4d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go @@ -52,9 +52,21 @@ type WebIdentityRoleProvider struct { credentials.Expiry PolicyArns []*sts.PolicyDescriptorType - client stsiface.STSAPI + // Duration the STS credentials will be valid for. Truncated to seconds. + // If unset, the assumed role will use AssumeRoleWithWebIdentity's default + // expiry duration. See + // https://docs.aws.amazon.com/sdk-for-go/api/service/sts/#STS.AssumeRoleWithWebIdentity + // for more information. + Duration time.Duration + + // The amount of time the credentials will be refreshed before they expire. + // This is useful refresh credentials before they expire to reduce risk of + // using credentials as they expire. If unset, will default to no expiry + // window. ExpiryWindow time.Duration + client stsiface.STSAPI + tokenFetcher TokenFetcher roleARN string roleSessionName string @@ -107,11 +119,18 @@ func (p *WebIdentityRoleProvider) RetrieveWithContext(ctx credentials.Context) ( // uses unix time in nanoseconds to uniquely identify sessions. sessionName = strconv.FormatInt(now().UnixNano(), 10) } + + var duration *int64 + if p.Duration != 0 { + duration = aws.Int64(int64(p.Duration / time.Second)) + } + req, resp := p.client.AssumeRoleWithWebIdentityRequest(&sts.AssumeRoleWithWebIdentityInput{ PolicyArns: p.PolicyArns, RoleArn: &p.roleARN, RoleSessionName: &sessionName, WebIdentityToken: aws.String(string(b)), + DurationSeconds: duration, }) req.SetContext(ctx) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go index b8b2940d744..dc7e051e0c0 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go @@ -41,7 +41,7 @@ const ( enableTokenProviderHandlerName = "enableTokenProviderHandler" // TTL constants - defaultTTL = 21600 * time.Second + defaultTTL = 21600 * time.Second ttlExpirationWindow = 30 * time.Second ) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go index 343a2106f81..654fb1ad52d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go @@ -93,7 +93,7 @@ func decodeV3Endpoints(modelDef modelDefinition, opts DecodeModelOptions) (Resol } func custAddS3DualStack(p *partition) { - if p.ID != "aws" { + if !(p.ID == "aws" || p.ID == "aws-cn" || p.ID == "aws-us-gov") { return } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go index 9b50e10b4bd..b7be4901ce7 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 @@ -25,12 +25,12 @@ const ( ApSoutheast1RegionID = "ap-southeast-1" // Asia Pacific (Singapore). ApSoutheast2RegionID = "ap-southeast-2" // Asia Pacific (Sydney). CaCentral1RegionID = "ca-central-1" // Canada (Central). - EuCentral1RegionID = "eu-central-1" // EU (Frankfurt). - EuNorth1RegionID = "eu-north-1" // EU (Stockholm). + EuCentral1RegionID = "eu-central-1" // Europe (Frankfurt). + EuNorth1RegionID = "eu-north-1" // Europe (Stockholm). EuSouth1RegionID = "eu-south-1" // Europe (Milan). - EuWest1RegionID = "eu-west-1" // EU (Ireland). - EuWest2RegionID = "eu-west-2" // EU (London). - EuWest3RegionID = "eu-west-3" // EU (Paris). + EuWest1RegionID = "eu-west-1" // Europe (Ireland). + EuWest2RegionID = "eu-west-2" // Europe (London). + EuWest3RegionID = "eu-west-3" // Europe (Paris). MeSouth1RegionID = "me-south-1" // Middle East (Bahrain). SaEast1RegionID = "sa-east-1" // South America (Sao Paulo). UsEast1RegionID = "us-east-1" // US East (N. Virginia). @@ -48,7 +48,7 @@ const ( // AWS GovCloud (US) partition's regions. const ( UsGovEast1RegionID = "us-gov-east-1" // AWS GovCloud (US-East). - UsGovWest1RegionID = "us-gov-west-1" // AWS GovCloud (US). + UsGovWest1RegionID = "us-gov-west-1" // AWS GovCloud (US-West). ) // AWS ISO (US) partition's regions. @@ -134,22 +134,22 @@ var awsPartition = partition{ Description: "Canada (Central)", }, "eu-central-1": region{ - Description: "EU (Frankfurt)", + Description: "Europe (Frankfurt)", }, "eu-north-1": region{ - Description: "EU (Stockholm)", + Description: "Europe (Stockholm)", }, "eu-south-1": region{ Description: "Europe (Milan)", }, "eu-west-1": region{ - Description: "EU (Ireland)", + Description: "Europe (Ireland)", }, "eu-west-2": region{ - Description: "EU (London)", + Description: "Europe (London)", }, "eu-west-3": region{ - Description: "EU (Paris)", + Description: "Europe (Paris)", }, "me-south-1": region{ Description: "Middle East (Bahrain)", @@ -194,12 +194,42 @@ var awsPartition = partition{ "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "me-south-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips-ca-central-1": endpoint{ + Hostname: "access-analyzer-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "fips-us-east-1": endpoint{ + Hostname: "access-analyzer-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "access-analyzer-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "access-analyzer-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "access-analyzer-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "acm": service{ @@ -312,6 +342,29 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "api.detective": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + 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-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "api.ecr": service{ Endpoints: endpoints{ @@ -399,6 +452,30 @@ var awsPartition = partition{ Region: "eu-west-3", }, }, + "fips-dkr-us-east-1": endpoint{ + Hostname: "ecr-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-dkr-us-east-2": endpoint{ + Hostname: "ecr-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-dkr-us-west-1": endpoint{ + Hostname: "ecr-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-dkr-us-west-2": endpoint{ + Hostname: "ecr-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, "fips-us-east-1": endpoint{ Hostname: "ecr-fips.us-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -639,6 +716,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{}, @@ -661,11 +739,17 @@ var awsPartition = partition{ "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -724,6 +808,7 @@ var awsPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ + "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, @@ -731,8 +816,12 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, @@ -774,6 +863,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -855,6 +945,7 @@ var awsPartition = partition{ "cloud9": service{ Endpoints: endpoints{ + "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, @@ -863,10 +954,15 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -969,6 +1065,7 @@ var awsPartition = partition{ }, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -978,6 +1075,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1053,6 +1151,21 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "codeartifact": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "codebuild": service{ Endpoints: endpoints{ @@ -1505,6 +1618,7 @@ var awsPartition = partition{ "datasync": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1514,6 +1628,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1631,8 +1746,10 @@ var awsPartition = partition{ "discovery": service{ Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, + "us-east-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -1753,6 +1870,7 @@ var awsPartition = partition{ "ds": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1762,6 +1880,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1984,6 +2103,50 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "eks": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, + Endpoints: endpoints{ + "af-south-1": endpoint{}, + "ap-east-1": endpoint{}, + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "fips-us-east-1": endpoint{ + Hostname: "fips.eks.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "fips.eks.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "fips.eks.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "elasticache": service{ Endpoints: endpoints{ @@ -2067,6 +2230,7 @@ var awsPartition = partition{ "elasticfilesystem": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -2076,9 +2240,16 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, + "fips-af-south-1": endpoint{ + Hostname: "elasticfilesystem-fips.af-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "af-south-1", + }, + }, "fips-ap-east-1": endpoint{ Hostname: "elasticfilesystem-fips.ap-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -2133,6 +2304,12 @@ var awsPartition = partition{ Region: "eu-north-1", }, }, + "fips-eu-south-1": endpoint{ + Hostname: "elasticfilesystem-fips.eu-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-south-1", + }, + }, "fips-eu-west-1": endpoint{ Hostname: "elasticfilesystem-fips.eu-west-1.amazonaws.com", CredentialScope: credentialScope{ @@ -2425,6 +2602,7 @@ var awsPartition = partition{ "firehose": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -2434,6 +2612,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2474,6 +2653,7 @@ var awsPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ + "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, @@ -2575,11 +2755,12 @@ var awsPartition = partition{ Region: "us-west-2", }, }, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "forecast": service{ @@ -2618,12 +2799,15 @@ var awsPartition = partition{ "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, @@ -2778,9 +2962,21 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, - "me-south-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, + "fips-us-east-2": endpoint{ + Hostname: "groundstation-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "groundstation-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, }, }, "guardduty": service{ @@ -2789,6 +2985,7 @@ var awsPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -2798,6 +2995,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2839,6 +3037,12 @@ var awsPartition = partition{ "us-east-1": endpoint{}, }, }, + "honeycode": service{ + + Endpoints: endpoints{ + "us-west-2": endpoint{}, + }, + }, "iam": service{ PartitionEndpoint: "aws-global", IsRegionalized: boxedFalse, @@ -2945,6 +3149,7 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "us-east-1": endpoint{}, @@ -3219,8 +3424,11 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, @@ -3279,6 +3487,7 @@ var awsPartition = partition{ "license-manager": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -3288,6 +3497,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -3358,12 +3568,36 @@ var awsPartition = partition{ "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "me-south-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips-us-east-1": endpoint{ + Hostname: "logs-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "logs-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "logs-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "logs-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "machinelearning": service{ @@ -3373,16 +3607,81 @@ var awsPartition = partition{ "us-east-1": endpoint{}, }, }, - "managedblockchain": service{ + "macie": service{ Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - }, - }, + "fips-us-east-1": endpoint{ + Hostname: "macie-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "macie-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "macie2": service{ + + Endpoints: endpoints{ + "ap-east-1": endpoint{}, + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "fips-us-east-1": endpoint{ + Hostname: "macie2-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "macie2-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "macie2-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "macie2-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "managedblockchain": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-southeast-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + }, + }, "marketplacecommerceanalytics": service{ Endpoints: endpoints{ @@ -3420,14 +3719,45 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips-ca-central-1": endpoint{ + Hostname: "mediaconvert-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "fips-us-east-1": endpoint{ + Hostname: "mediaconvert-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "mediaconvert-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "mediaconvert-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "mediaconvert-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "medialive": service{ @@ -3514,8 +3844,10 @@ var awsPartition = partition{ "mgh": service{ Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, + "us-east-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -3532,6 +3864,7 @@ var awsPartition = partition{ }, }, Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, @@ -3652,6 +3985,12 @@ var awsPartition = partition{ "neptune": service{ Endpoints: endpoints{ + "ap-east-1": endpoint{ + Hostname: "rds.ap-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-east-1", + }, + }, "ap-northeast-1": endpoint{ Hostname: "rds.ap-northeast-1.amazonaws.com", CredentialScope: credentialScope{ @@ -3724,6 +4063,12 @@ var awsPartition = partition{ Region: "me-south-1", }, }, + "sa-east-1": endpoint{ + Hostname: "rds.sa-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "sa-east-1", + }, + }, "us-east-1": endpoint{ Hostname: "rds.us-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -3736,6 +4081,12 @@ var awsPartition = partition{ Region: "us-east-2", }, }, + "us-west-1": endpoint{ + Hostname: "rds.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, "us-west-2": endpoint{ Hostname: "rds.us-west-2.amazonaws.com", CredentialScope: credentialScope{ @@ -3771,6 +4122,12 @@ var awsPartition = partition{ Region: "eu-central-1", }, }, + "eu-north-1": endpoint{ + Hostname: "oidc.eu-north-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-north-1", + }, + }, "eu-west-1": endpoint{ Hostname: "oidc.eu-west-1.amazonaws.com", CredentialScope: credentialScope{ @@ -3859,22 +4216,56 @@ var awsPartition = partition{ "outposts": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "me-south-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips-ca-central-1": endpoint{ + Hostname: "outposts-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "fips-us-east-1": endpoint{ + Hostname: "outposts-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "outposts-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "outposts-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "outposts-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "pinpoint": service{ @@ -3884,6 +4275,7 @@ var awsPartition = partition{ }, }, Endpoints: endpoints{ + "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, @@ -4049,6 +4441,7 @@ var awsPartition = partition{ "ram": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4058,6 +4451,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4192,10 +4586,34 @@ var awsPartition = partition{ "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "rekognition-fips.us-east-1": endpoint{ + Hostname: "rekognition-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "rekognition-fips.us-east-2": endpoint{ + Hostname: "rekognition-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "rekognition-fips.us-west-1": endpoint{ + Hostname: "rekognition-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "rekognition-fips.us-west-2": endpoint{ + Hostname: "rekognition-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "resource-groups": service{ @@ -4283,6 +4701,7 @@ var awsPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4292,6 +4711,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4310,6 +4730,7 @@ var awsPartition = partition{ }, }, Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, @@ -4604,10 +5025,22 @@ var awsPartition = partition{ "schemas": service{ Endpoints: endpoints{ + "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -4632,6 +5065,7 @@ var awsPartition = partition{ "secretsmanager": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4641,6 +5075,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4679,6 +5114,7 @@ var awsPartition = partition{ "securityhub": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4688,15 +5124,40 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "me-south-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips-us-east-1": endpoint{ + Hostname: "securityhub-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "securityhub-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "securityhub-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "securityhub-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "serverlessrepo": service{ @@ -4763,6 +5224,7 @@ var awsPartition = partition{ "servicecatalog": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4772,6 +5234,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4830,6 +5293,31 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "servicequotas": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "ap-east-1": endpoint{}, + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "session.qldb": service{ Endpoints: endpoints{ @@ -4845,20 +5333,21 @@ var awsPartition = partition{ }, }, "shield": service{ - IsRegionalized: boxedFalse, + PartitionEndpoint: "aws-global", + IsRegionalized: boxedFalse, Defaults: endpoint{ SSLCommonName: "shield.us-east-1.amazonaws.com", Protocols: []string{"https"}, }, Endpoints: endpoints{ - "fips-us-east-1": endpoint{ - Hostname: "shield-fips.us-east-1.amazonaws.com", + "aws-global": endpoint{ + Hostname: "shield.us-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-1", }, }, - "us-east-1": endpoint{ - Hostname: "shield.us-east-1.amazonaws.com", + "fips-aws-global": endpoint{ + Hostname: "shield-fips.us-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-1", }, @@ -5254,6 +5743,7 @@ var awsPartition = partition{ "storagegateway": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -5263,15 +5753,22 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "me-south-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips": endpoint{ + Hostname: "storagegateway-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "streams.dynamodb": service{ @@ -5947,6 +6444,13 @@ var awscnPartition = partition{ }, }, Services: services{ + "access-analyzer": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "acm": service{ Endpoints: endpoints{ @@ -6016,6 +6520,15 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "autoscaling-plans": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "backup": service{ Endpoints: endpoints{ @@ -6030,6 +6543,32 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "budgets": service{ + PartitionEndpoint: "aws-cn-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-cn-global": endpoint{ + Hostname: "budgets.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, + "ce": service{ + PartitionEndpoint: "aws-cn-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-cn-global": endpoint{ + Hostname: "ce.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, "cloudformation": service{ Endpoints: endpoints{ @@ -6092,6 +6631,12 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "cur": service{ + + Endpoints: endpoints{ + "cn-northwest-1": endpoint{}, + }, + }, "dax": service{ Endpoints: endpoints{ @@ -6155,6 +6700,15 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "eks": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "elasticache": service{ Endpoints: endpoints{ @@ -6310,6 +6864,13 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "kinesisanalytics": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "kms": service{ Endpoints: endpoints{ @@ -6369,6 +6930,25 @@ var awscnPartition = partition{ }, }, }, + "organizations": service{ + PartitionEndpoint: "aws-cn-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-cn-global": endpoint{ + Hostname: "organizations.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + "fips-aws-cn-global": endpoint{ + Hostname: "organizations.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, "polly": service{ Endpoints: endpoints{ @@ -6389,6 +6969,19 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "route53": service{ + PartitionEndpoint: "aws-cn-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-cn-global": endpoint{ + Hostname: "route53.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, "runtime.sagemaker": service{ Endpoints: endpoints{ @@ -6400,6 +6993,9 @@ var awscnPartition = partition{ Defaults: endpoint{ Protocols: []string{"http", "https"}, SignatureVersions: []string{"s3v4"}, + + HasDualStack: boxedTrue, + DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", }, Endpoints: endpoints{ "cn-north-1": endpoint{}, @@ -6410,6 +7006,9 @@ var awscnPartition = partition{ Defaults: endpoint{ Protocols: []string{"https"}, SignatureVersions: []string{"s3v4"}, + + HasDualStack: boxedTrue, + DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", }, Endpoints: endpoints{ "cn-north-1": endpoint{ @@ -6458,13 +7057,20 @@ var awscnPartition = partition{ "snowball": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, "fips-cn-north-1": endpoint{ Hostname: "snowball-fips.cn-north-1.amazonaws.com.cn", CredentialScope: credentialScope{ Region: "cn-north-1", }, }, + "fips-cn-northwest-1": endpoint{ + Hostname: "snowball-fips.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, }, }, "sns": service{ @@ -6612,15 +7218,25 @@ var awsusgovPartition = partition{ Description: "AWS GovCloud (US-East)", }, "us-gov-west-1": region{ - Description: "AWS GovCloud (US)", + Description: "AWS GovCloud (US-West)", }, }, Services: services{ "access-analyzer": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, - "us-gov-west-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "access-analyzer.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "access-analyzer.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "acm": service{ @@ -6654,6 +7270,18 @@ var awsusgovPartition = partition{ "api.ecr": service{ Endpoints: endpoints{ + "fips-dkr-us-gov-east-1": endpoint{ + Hostname: "ecr-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-dkr-us-gov-west-1": endpoint{ + Hostname: "ecr-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "fips-us-gov-east-1": endpoint{ Hostname: "ecr-fips.us-gov-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -6684,6 +7312,18 @@ var awsusgovPartition = partition{ Endpoints: endpoints{ "us-gov-west-1": endpoint{}, + "us-gov-west-1-fips": endpoint{ + Hostname: "api-fips.sagemaker.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "us-gov-west-1-fips-secondary": endpoint{ + Hostname: "api.sagemaker.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "apigateway": service{ @@ -6745,7 +7385,9 @@ var awsusgovPartition = partition{ "autoscaling": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, + "us-gov-east-1": endpoint{ + Protocols: []string{"http", "https"}, + }, "us-gov-west-1": endpoint{ Protocols: []string{"http", "https"}, }, @@ -6760,6 +7402,13 @@ var awsusgovPartition = partition{ "us-gov-west-1": endpoint{}, }, }, + "backup": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, "batch": service{ Endpoints: endpoints{ @@ -6788,8 +7437,18 @@ var awsusgovPartition = partition{ "cloudformation": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, - "us-gov-west-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "cloudformation.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "cloudformation.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "cloudhsm": service{ @@ -6812,8 +7471,18 @@ var awsusgovPartition = partition{ "cloudtrail": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, - "us-gov-west-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "cloudtrail.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "cloudtrail.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "codebuild": service{ @@ -6867,11 +7536,29 @@ var awsusgovPartition = partition{ }, }, }, - "codepipeline": service{ + "codepipeline": service{ + + Endpoints: endpoints{ + "fips-us-gov-west-1": endpoint{ + Hostname: "codepipeline-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "us-gov-west-1": endpoint{}, + }, + }, + "cognito-identity": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, + "cognito-idp": service{ Endpoints: endpoints{ "fips-us-gov-west-1": endpoint{ - Hostname: "codepipeline-fips.us-gov-west-1.amazonaws.com", + Hostname: "cognito-idp-fips.us-gov-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-gov-west-1", }, @@ -6896,6 +7583,12 @@ var awsusgovPartition = partition{ "comprehendmedical": service{ Endpoints: endpoints{ + "fips-us-gov-west-1": endpoint{ + Hostname: "comprehendmedical-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-west-1": endpoint{}, }, }, @@ -6955,6 +7648,17 @@ var awsusgovPartition = partition{ "us-gov-west-1": endpoint{}, }, }, + "docdb": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{ + Hostname: "rds.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + }, + }, "ds": service{ Endpoints: endpoints{ @@ -7040,11 +7744,20 @@ var awsusgovPartition = partition{ "us-gov-west-1": endpoint{}, }, }, + "eks": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, "elasticache": service{ Endpoints: endpoints{ "fips": endpoint{ - Hostname: "elasticache-fips.us-gov-west-1.amazonaws.com", + Hostname: "elasticache.us-gov-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-gov-west-1", }, @@ -7092,6 +7805,18 @@ var awsusgovPartition = partition{ "elasticloadbalancing": service{ Endpoints: endpoints{ + "fips-us-gov-east-1": endpoint{ + Hostname: "elasticloadbalancing-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-us-gov-west-1": endpoint{ + Hostname: "elasticloadbalancing-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{ Protocols: []string{"http", "https"}, @@ -7101,6 +7826,18 @@ var awsusgovPartition = partition{ "elasticmapreduce": service{ Endpoints: endpoints{ + "fips-us-gov-east-1": endpoint{ + Hostname: "elasticmapreduce.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-us-gov-west-1": endpoint{ + Hostname: "elasticmapreduce.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{ Protocols: []string{"https"}, @@ -7135,8 +7872,18 @@ var awsusgovPartition = partition{ "events": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, - "us-gov-west-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "events.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "events.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "firehose": service{ @@ -7201,7 +7948,12 @@ var awsusgovPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, + "us-gov-west-1": endpoint{ + Hostname: "greengrass.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "guardduty": service{ @@ -7211,6 +7963,12 @@ var awsusgovPartition = partition{ }, Endpoints: endpoints{ "us-gov-west-1": endpoint{}, + "us-gov-west-1-fips": endpoint{ + Hostname: "guardduty.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "health": service{ @@ -7230,6 +7988,12 @@ var awsusgovPartition = partition{ Region: "us-gov-west-1", }, }, + "iam-govcloud-fips": endpoint{ + Hostname: "iam.us-gov.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "inspector": service{ @@ -7267,8 +8031,34 @@ var awsusgovPartition = partition{ "us-gov-west-1": endpoint{}, }, }, + "kafka": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, "kinesis": service{ + Endpoints: endpoints{ + "fips-us-gov-east-1": endpoint{ + Hostname: "kinesis-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-us-gov-west-1": endpoint{ + Hostname: "kinesis-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "kinesisanalytics": service{ + Endpoints: endpoints{ "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, @@ -7328,14 +8118,29 @@ var awsusgovPartition = partition{ "logs": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, - "us-gov-west-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "logs.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "logs.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "mediaconvert": service{ Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, + "us-gov-west-1": endpoint{ + Hostname: "mediaconvert.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "metering.marketplace": service{ @@ -7396,13 +8201,29 @@ var awsusgovPartition = partition{ Region: "us-gov-west-1", }, }, + "fips-aws-us-gov-global": endpoint{ + Hostname: "organizations.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "outposts": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, - "us-gov-west-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "outposts.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "outposts.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "pinpoint": service{ @@ -7437,6 +8258,18 @@ var awsusgovPartition = partition{ "rds": service{ Endpoints: endpoints{ + "rds.us-gov-east-1": endpoint{ + Hostname: "rds.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "rds.us-gov-west-1": endpoint{ + Hostname: "rds.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, @@ -7461,6 +8294,12 @@ var awsusgovPartition = partition{ "rekognition": service{ Endpoints: endpoints{ + "rekognition-fips.us-gov-west-1": endpoint{ + Hostname: "rekognition-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-west-1": endpoint{}, }, }, @@ -7512,6 +8351,9 @@ var awsusgovPartition = partition{ "s3": service{ Defaults: endpoint{ SignatureVersions: []string{"s3", "s3v4"}, + + HasDualStack: boxedTrue, + DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", }, Endpoints: endpoints{ "fips-us-gov-west-1": endpoint{ @@ -7534,6 +8376,9 @@ var awsusgovPartition = partition{ Defaults: endpoint{ Protocols: []string{"https"}, SignatureVersions: []string{"s3v4"}, + + HasDualStack: boxedTrue, + DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", }, Endpoints: endpoints{ "us-gov-east-1": endpoint{ @@ -7588,6 +8433,18 @@ var awsusgovPartition = partition{ "securityhub": service{ Endpoints: endpoints{ + "fips-us-gov-east-1": endpoint{ + Hostname: "securityhub-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-us-gov-west-1": endpoint{ + Hostname: "securityhub-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, @@ -7598,10 +8455,18 @@ var awsusgovPartition = partition{ }, Endpoints: endpoints{ "us-gov-east-1": endpoint{ + Hostname: "serverlessrepo.us-gov-east-1.amazonaws.com", Protocols: []string{"https"}, + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, }, "us-gov-west-1": endpoint{ + Hostname: "serverlessrepo.us-gov-west-1.amazonaws.com", Protocols: []string{"https"}, + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, }, }, }, @@ -7665,25 +8530,67 @@ var awsusgovPartition = partition{ "sns": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "sns.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, "us-gov-west-1": endpoint{ + Hostname: "sns.us-gov-west-1.amazonaws.com", Protocols: []string{"http", "https"}, + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, }, }, }, "sqs": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "sqs.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, "us-gov-west-1": endpoint{ + Hostname: "sqs.us-gov-west-1.amazonaws.com", SSLCommonName: "{region}.queue.{dnsSuffix}", Protocols: []string{"http", "https"}, + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, }, }, }, "ssm": service{ Endpoints: endpoints{ + "fips-us-gov-east-1": endpoint{ + Hostname: "ssm.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-us-gov-west-1": endpoint{ + Hostname: "ssm.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "ssm-facade-fips-us-gov-east-1": endpoint{ + Hostname: "ssm-facade.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "ssm-facade-fips-us-gov-west-1": endpoint{ + Hostname: "ssm-facade.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, @@ -7710,6 +8617,12 @@ var awsusgovPartition = partition{ "storagegateway": service{ Endpoints: endpoints{ + "fips": endpoint{ + Hostname: "storagegateway-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, @@ -7741,7 +8654,19 @@ var awsusgovPartition = partition{ Endpoints: endpoints{ "us-gov-east-1": endpoint{}, + "us-gov-east-1-fips": endpoint{ + Hostname: "sts.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, "us-gov-west-1": endpoint{}, + "us-gov-west-1-fips": endpoint{ + Hostname: "sts.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "support": service{ @@ -7754,6 +8679,12 @@ var awsusgovPartition = partition{ Region: "us-gov-west-1", }, }, + "fips-us-gov-west-1": endpoint{ + Hostname: "support.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "swf": service{ @@ -8028,6 +8959,12 @@ var awsisoPartition = partition{ }, }, }, + "es": service{ + + Endpoints: endpoints{ + "us-iso-east-1": endpoint{}, + }, + }, "events": service{ Endpoints: endpoints{ @@ -8204,6 +9141,20 @@ var awsisoPartition = partition{ "us-iso-east-1": endpoint{}, }, }, + "transcribe": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "us-iso-east-1": endpoint{}, + }, + }, + "transcribestreaming": service{ + + Endpoints: endpoints{ + "us-iso-east-1": endpoint{}, + }, + }, "workspaces": service{ Endpoints: endpoints{ @@ -8387,6 +9338,12 @@ var awsisobPartition = partition{ "us-isob-east-1": endpoint{}, }, }, + "lambda": service{ + + Endpoints: endpoints{ + "us-isob-east-1": endpoint{}, + }, + }, "license-manager": service{ Endpoints: endpoints{ diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go index eb2ac83c992..773613722f4 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go @@ -7,6 +7,8 @@ import ( "strings" ) +var regionValidationRegex = regexp.MustCompile(`^[[:alnum:]]([[:alnum:]\-]*[[:alnum:]])?$`) + type partitions []partition func (ps partitions) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { @@ -124,7 +126,7 @@ func (p partition) EndpointFor(service, region string, opts ...func(*Options)) ( defs := []endpoint{p.Defaults, s.Defaults} - return e.resolve(service, p.ID, region, p.DNSSuffix, defs, opt), nil + return e.resolve(service, p.ID, region, p.DNSSuffix, defs, opt) } func serviceList(ss services) []string { @@ -233,7 +235,7 @@ func getByPriority(s []string, p []string, def string) string { return s[0] } -func (e endpoint) resolve(service, partitionID, region, dnsSuffix string, defs []endpoint, opts Options) ResolvedEndpoint { +func (e endpoint) resolve(service, partitionID, region, dnsSuffix string, defs []endpoint, opts Options) (ResolvedEndpoint, error) { var merged endpoint for _, def := range defs { merged.mergeIn(def) @@ -260,6 +262,10 @@ func (e endpoint) resolve(service, partitionID, region, dnsSuffix string, defs [ region = signingRegion } + if !validateInputRegion(region) { + return ResolvedEndpoint{}, fmt.Errorf("invalid region identifier format provided") + } + u := strings.Replace(hostname, "{service}", service, 1) u = strings.Replace(u, "{region}", region, 1) u = strings.Replace(u, "{dnsSuffix}", dnsSuffix, 1) @@ -274,7 +280,7 @@ func (e endpoint) resolve(service, partitionID, region, dnsSuffix string, defs [ SigningName: signingName, SigningNameDerived: signingNameDerived, SigningMethod: getByPriority(e.SignatureVersions, signerPriority, defaultSigner), - } + }, nil } func getEndpointScheme(protocols []string, disableSSL bool) string { @@ -339,3 +345,7 @@ const ( boxedFalse boxedTrue ) + +func validateInputRegion(region string) bool { + return regionValidationRegex.MatchString(region) +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go index d9b37f4d32a..2ba3c56c11f 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go @@ -9,7 +9,8 @@ func isErrConnectionReset(err error) bool { return false } - if strings.Contains(err.Error(), "connection reset") || + if strings.Contains(err.Error(), "use of closed network connection") || + strings.Contains(err.Error(), "connection reset") || strings.Contains(err.Error(), "broken pipe") { return true } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/types.go b/vendor/github.com/aws/aws-sdk-go/aws/types.go index d542ef01bc8..98751ee84f2 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/types.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/types.go @@ -239,3 +239,26 @@ func (es errors) Error() string { return strings.Join(parts, "\n") } + +// CopySeekableBody copies the seekable body to an io.Writer +func CopySeekableBody(dst io.Writer, src io.ReadSeeker) (int64, error) { + curPos, err := src.Seek(0, sdkio.SeekCurrent) + if err != nil { + return 0, err + } + + // copy errors may be assumed to be from the body. + n, err := io.Copy(dst, src) + if err != nil { + return n, err + } + + // seek back to the first position after reading to reset + // the body for transmission. + _, err = src.Seek(curPos, sdkio.SeekStart) + if err != nil { + return n, err + } + + return n, nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/aws/aws-sdk-go/aws/version.go index 354ef69292d..e0ec21b76fe 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/version.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/version.go @@ -5,4 +5,4 @@ package aws const SDKName = "aws-sdk-go" // SDKVersion is the version of this SDK -const SDKVersion = "1.30.21" +const SDKVersion = "1.34.4" diff --git a/vendor/github.com/aws/aws-sdk-go/private/checksum/content_md5.go b/vendor/github.com/aws/aws-sdk-go/private/checksum/content_md5.go new file mode 100644 index 00000000000..e045f38d837 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/checksum/content_md5.go @@ -0,0 +1,53 @@ +package checksum + +import ( + "crypto/md5" + "encoding/base64" + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/request" +) + +const contentMD5Header = "Content-Md5" + +// AddBodyContentMD5Handler computes and sets the HTTP Content-MD5 header for requests that +// require it. +func AddBodyContentMD5Handler(r *request.Request) { + // if Content-MD5 header is already present, return + if v := r.HTTPRequest.Header.Get(contentMD5Header); len(v) != 0 { + return + } + + // if S3DisableContentMD5Validation flag is set, return + if aws.BoolValue(r.Config.S3DisableContentMD5Validation) { + return + } + + // if request is presigned, return + if r.IsPresigned() { + return + } + + // if body is not seekable, return + if !aws.IsReaderSeekable(r.Body) { + if r.Config.Logger != nil { + r.Config.Logger.Log(fmt.Sprintf( + "Unable to compute Content-MD5 for unseekable body, S3.%s", + r.Operation.Name)) + } + return + } + + h := md5.New() + + if _, err := aws.CopySeekableBody(h, r.Body); err != nil { + r.Error = awserr.New("ContentMD5", "failed to compute body MD5", err) + return + } + + // encode the md5 checksum in base64 and set the request header. + v := base64.StdEncoding.EncodeToString(h.Sum(nil)) + r.HTTPRequest.Header.Set(contentMD5Header, v) +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go index bb8ea5da165..0e4aa42f3e4 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go @@ -69,10 +69,23 @@ func (r *EventReader) ReadEvent() (event interface{}, err error) { case ErrorMessageType: return nil, r.unmarshalErrorMessage(msg) default: - return nil, fmt.Errorf("unknown eventstream message type, %v", typ) + return nil, &UnknownMessageTypeError{ + Type: typ, Message: msg.Clone(), + } } } +// UnknownMessageTypeError provides an error when a message is received from +// the stream, but the reader is unable to determine what kind of message it is. +type UnknownMessageTypeError struct { + Type string + Message eventstream.Message +} + +func (e *UnknownMessageTypeError) Error() string { + return "unknown eventstream message type, " + e.Type +} + func (r *EventReader) unmarshalEventMessage( msg eventstream.Message, ) (event interface{}, err error) { diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go index 3b44dde2f32..f6f8c5674ed 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go @@ -52,6 +52,15 @@ func (hs *Headers) Del(name string) { } } +// Clone returns a deep copy of the headers +func (hs Headers) Clone() Headers { + o := make(Headers, 0, len(hs)) + for _, h := range hs { + o.Set(h.Name, h.Value) + } + return o +} + func decodeHeaders(r io.Reader) (Headers, error) { hs := Headers{} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go index 25c9783cde6..f7427da039e 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go @@ -57,6 +57,20 @@ func (m *Message) rawMessage() (rawMessage, error) { return raw, nil } +// Clone returns a deep copy of the message. +func (m Message) Clone() Message { + var payload []byte + if m.Payload != nil { + payload = make([]byte, len(m.Payload)) + copy(payload, m.Payload) + } + + return Message{ + Headers: m.Headers.Clone(), + Payload: payload, + } +} + type messagePrelude struct { Length uint32 HeadersLen uint32 diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go index 5e9499699ba..8b2c9bbeba0 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "io" + "math/big" "reflect" "strings" "time" @@ -15,6 +16,8 @@ import ( "github.com/aws/aws-sdk-go/private/protocol" ) +var millisecondsFloat = new(big.Float).SetInt64(1e3) + // UnmarshalJSONError unmarshal's the reader's JSON document into the passed in // type. The value to unmarshal the json document into must be a pointer to the // type. @@ -39,7 +42,9 @@ func UnmarshalJSONError(v interface{}, stream io.Reader) error { func UnmarshalJSON(v interface{}, stream io.Reader) error { var out interface{} - err := json.NewDecoder(stream).Decode(&out) + decoder := json.NewDecoder(stream) + decoder.UseNumber() + err := decoder.Decode(&out) if err == io.EOF { return nil } else if err != nil { @@ -54,7 +59,9 @@ func UnmarshalJSON(v interface{}, stream io.Reader) error { func UnmarshalJSONCaseInsensitive(v interface{}, stream io.Reader) error { var out interface{} - err := json.NewDecoder(stream).Decode(&out) + decoder := json.NewDecoder(stream) + decoder.UseNumber() + err := decoder.Decode(&out) if err == io.EOF { return nil } else if err != nil { @@ -254,16 +261,31 @@ func (u unmarshaler) unmarshalScalar(value reflect.Value, data interface{}, tag default: return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) } - case float64: + case json.Number: switch value.Interface().(type) { case *int64: - di := int64(d) + // Retain the old behavior where we would just truncate the float64 + // calling d.Int64() here could cause an invalid syntax error due to the usage of strconv.ParseInt + f, err := d.Float64() + if err != nil { + return err + } + di := int64(f) value.Set(reflect.ValueOf(&di)) case *float64: - value.Set(reflect.ValueOf(&d)) + f, err := d.Float64() + if err != nil { + return err + } + value.Set(reflect.ValueOf(&f)) case *time.Time: - // Time unmarshaled from a float64 can only be epoch seconds - t := time.Unix(int64(d), 0).UTC() + float, ok := new(big.Float).SetString(d.String()) + if !ok { + return fmt.Errorf("unsupported float time representation: %v", d.String()) + } + float = float.Mul(float, millisecondsFloat) + ms, _ := float.Int64() + t := time.Unix(0, ms*1e6).UTC() value.Set(reflect.ValueOf(&t)) default: return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go index 05d4ff51925..d2f6dae5321 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go @@ -56,7 +56,8 @@ func FormatTime(name string, t time.Time) string { case ISO8601TimeFormatName: return t.Format(ISO8601OutputTimeFormat) case UnixTimeFormatName: - return strconv.FormatInt(t.Unix(), 10) + ms := t.UnixNano() / int64(time.Millisecond) + return strconv.FormatFloat(float64(ms)/1e3, 'f', -1, 64) default: panic("unknown timestamp format name, " + name) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/accessanalyzer/api.go b/vendor/github.com/aws/aws-sdk-go/service/accessanalyzer/api.go index 16ad2d2e603..8ae4e0cfebd 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/accessanalyzer/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/accessanalyzer/api.go @@ -4878,6 +4878,16 @@ const ( AnalyzerStatusFailed = "FAILED" ) +// AnalyzerStatus_Values returns all elements of the AnalyzerStatus enum +func AnalyzerStatus_Values() []string { + return []string{ + AnalyzerStatusActive, + AnalyzerStatusCreating, + AnalyzerStatusDisabled, + AnalyzerStatusFailed, + } +} + const ( // FindingSourceTypeBucketAcl is a FindingSourceType enum value FindingSourceTypeBucketAcl = "BUCKET_ACL" @@ -4889,6 +4899,15 @@ const ( FindingSourceTypeS3AccessPoint = "S3_ACCESS_POINT" ) +// FindingSourceType_Values returns all elements of the FindingSourceType enum +func FindingSourceType_Values() []string { + return []string{ + FindingSourceTypeBucketAcl, + FindingSourceTypePolicy, + FindingSourceTypeS3AccessPoint, + } +} + const ( // FindingStatusActive is a FindingStatus enum value FindingStatusActive = "ACTIVE" @@ -4900,6 +4919,15 @@ const ( FindingStatusResolved = "RESOLVED" ) +// FindingStatus_Values returns all elements of the FindingStatus enum +func FindingStatus_Values() []string { + return []string{ + FindingStatusActive, + FindingStatusArchived, + FindingStatusResolved, + } +} + const ( // FindingStatusUpdateActive is a FindingStatusUpdate enum value FindingStatusUpdateActive = "ACTIVE" @@ -4908,6 +4936,14 @@ const ( FindingStatusUpdateArchived = "ARCHIVED" ) +// FindingStatusUpdate_Values returns all elements of the FindingStatusUpdate enum +func FindingStatusUpdate_Values() []string { + return []string{ + FindingStatusUpdateActive, + FindingStatusUpdateArchived, + } +} + const ( // OrderByAsc is a OrderBy enum value OrderByAsc = "ASC" @@ -4916,6 +4952,14 @@ const ( OrderByDesc = "DESC" ) +// OrderBy_Values returns all elements of the OrderBy enum +func OrderBy_Values() []string { + return []string{ + OrderByAsc, + OrderByDesc, + } +} + const ( // ReasonCodeAwsServiceAccessDisabled is a ReasonCode enum value ReasonCodeAwsServiceAccessDisabled = "AWS_SERVICE_ACCESS_DISABLED" @@ -4930,6 +4974,16 @@ const ( ReasonCodeServiceLinkedRoleCreationFailed = "SERVICE_LINKED_ROLE_CREATION_FAILED" ) +// ReasonCode_Values returns all elements of the ReasonCode enum +func ReasonCode_Values() []string { + return []string{ + ReasonCodeAwsServiceAccessDisabled, + ReasonCodeDelegatedAdministratorDeregistered, + ReasonCodeOrganizationDeleted, + ReasonCodeServiceLinkedRoleCreationFailed, + } +} + const ( // ResourceTypeAwsIamRole is a ResourceType enum value ResourceTypeAwsIamRole = "AWS::IAM::Role" @@ -4950,6 +5004,18 @@ const ( ResourceTypeAwsSqsQueue = "AWS::SQS::Queue" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeAwsIamRole, + ResourceTypeAwsKmsKey, + ResourceTypeAwsLambdaFunction, + ResourceTypeAwsLambdaLayerVersion, + ResourceTypeAwsS3Bucket, + ResourceTypeAwsSqsQueue, + } +} + const ( // TypeAccount is a Type enum value TypeAccount = "ACCOUNT" @@ -4958,6 +5024,14 @@ const ( TypeOrganization = "ORGANIZATION" ) +// Type_Values returns all elements of the Type enum +func Type_Values() []string { + return []string{ + TypeAccount, + TypeOrganization, + } +} + const ( // ValidationExceptionReasonCannotParse is a ValidationExceptionReason enum value ValidationExceptionReasonCannotParse = "cannotParse" @@ -4971,3 +5045,13 @@ const ( // ValidationExceptionReasonUnknownOperation is a ValidationExceptionReason enum value ValidationExceptionReasonUnknownOperation = "unknownOperation" ) + +// ValidationExceptionReason_Values returns all elements of the ValidationExceptionReason enum +func ValidationExceptionReason_Values() []string { + return []string{ + ValidationExceptionReasonCannotParse, + ValidationExceptionReasonFieldValidationFailed, + ValidationExceptionReasonOther, + ValidationExceptionReasonUnknownOperation, + } +} 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 f643d683a69..51c26a35f10 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 @@ -4142,6 +4142,19 @@ const ( CertificateStatusFailed = "FAILED" ) +// CertificateStatus_Values returns all elements of the CertificateStatus enum +func CertificateStatus_Values() []string { + return []string{ + CertificateStatusPendingValidation, + CertificateStatusIssued, + CertificateStatusInactive, + CertificateStatusExpired, + CertificateStatusValidationTimedOut, + CertificateStatusRevoked, + CertificateStatusFailed, + } +} + const ( // CertificateTransparencyLoggingPreferenceEnabled is a CertificateTransparencyLoggingPreference enum value CertificateTransparencyLoggingPreferenceEnabled = "ENABLED" @@ -4150,6 +4163,14 @@ const ( CertificateTransparencyLoggingPreferenceDisabled = "DISABLED" ) +// CertificateTransparencyLoggingPreference_Values returns all elements of the CertificateTransparencyLoggingPreference enum +func CertificateTransparencyLoggingPreference_Values() []string { + return []string{ + CertificateTransparencyLoggingPreferenceEnabled, + CertificateTransparencyLoggingPreferenceDisabled, + } +} + const ( // CertificateTypeImported is a CertificateType enum value CertificateTypeImported = "IMPORTED" @@ -4161,6 +4182,15 @@ const ( CertificateTypePrivate = "PRIVATE" ) +// CertificateType_Values returns all elements of the CertificateType enum +func CertificateType_Values() []string { + return []string{ + CertificateTypeImported, + CertificateTypeAmazonIssued, + CertificateTypePrivate, + } +} + const ( // DomainStatusPendingValidation is a DomainStatus enum value DomainStatusPendingValidation = "PENDING_VALIDATION" @@ -4172,6 +4202,15 @@ const ( DomainStatusFailed = "FAILED" ) +// DomainStatus_Values returns all elements of the DomainStatus enum +func DomainStatus_Values() []string { + return []string{ + DomainStatusPendingValidation, + DomainStatusSuccess, + DomainStatusFailed, + } +} + const ( // ExtendedKeyUsageNameTlsWebServerAuthentication is a ExtendedKeyUsageName enum value ExtendedKeyUsageNameTlsWebServerAuthentication = "TLS_WEB_SERVER_AUTHENTICATION" @@ -4210,6 +4249,24 @@ const ( ExtendedKeyUsageNameCustom = "CUSTOM" ) +// ExtendedKeyUsageName_Values returns all elements of the ExtendedKeyUsageName enum +func ExtendedKeyUsageName_Values() []string { + return []string{ + ExtendedKeyUsageNameTlsWebServerAuthentication, + ExtendedKeyUsageNameTlsWebClientAuthentication, + ExtendedKeyUsageNameCodeSigning, + ExtendedKeyUsageNameEmailProtection, + ExtendedKeyUsageNameTimeStamping, + ExtendedKeyUsageNameOcspSigning, + ExtendedKeyUsageNameIpsecEndSystem, + ExtendedKeyUsageNameIpsecTunnel, + ExtendedKeyUsageNameIpsecUser, + ExtendedKeyUsageNameAny, + ExtendedKeyUsageNameNone, + ExtendedKeyUsageNameCustom, + } +} + const ( // FailureReasonNoAvailableContacts is a FailureReason enum value FailureReasonNoAvailableContacts = "NO_AVAILABLE_CONTACTS" @@ -4260,6 +4317,28 @@ const ( FailureReasonOther = "OTHER" ) +// FailureReason_Values returns all elements of the FailureReason enum +func FailureReason_Values() []string { + return []string{ + FailureReasonNoAvailableContacts, + FailureReasonAdditionalVerificationRequired, + FailureReasonDomainNotAllowed, + FailureReasonInvalidPublicDomain, + FailureReasonDomainValidationDenied, + FailureReasonCaaError, + FailureReasonPcaLimitExceeded, + FailureReasonPcaInvalidArn, + FailureReasonPcaInvalidState, + FailureReasonPcaRequestFailed, + FailureReasonPcaNameConstraintsValidation, + FailureReasonPcaResourceNotFound, + FailureReasonPcaInvalidArgs, + FailureReasonPcaInvalidDuration, + FailureReasonPcaAccessDenied, + FailureReasonOther, + } +} + const ( // KeyAlgorithmRsa2048 is a KeyAlgorithm enum value KeyAlgorithmRsa2048 = "RSA_2048" @@ -4280,6 +4359,18 @@ const ( KeyAlgorithmEcSecp521r1 = "EC_secp521r1" ) +// KeyAlgorithm_Values returns all elements of the KeyAlgorithm enum +func KeyAlgorithm_Values() []string { + return []string{ + KeyAlgorithmRsa2048, + KeyAlgorithmRsa1024, + KeyAlgorithmRsa4096, + KeyAlgorithmEcPrime256v1, + KeyAlgorithmEcSecp384r1, + KeyAlgorithmEcSecp521r1, + } +} + const ( // KeyUsageNameDigitalSignature is a KeyUsageName enum value KeyUsageNameDigitalSignature = "DIGITAL_SIGNATURE" @@ -4315,11 +4406,35 @@ const ( KeyUsageNameCustom = "CUSTOM" ) +// KeyUsageName_Values returns all elements of the KeyUsageName enum +func KeyUsageName_Values() []string { + return []string{ + KeyUsageNameDigitalSignature, + KeyUsageNameNonRepudiation, + KeyUsageNameKeyEncipherment, + KeyUsageNameDataEncipherment, + KeyUsageNameKeyAgreement, + KeyUsageNameCertificateSigning, + KeyUsageNameCrlSigning, + KeyUsageNameEncipherOnly, + KeyUsageNameDecipherOnly, + KeyUsageNameAny, + KeyUsageNameCustom, + } +} + const ( // RecordTypeCname is a RecordType enum value RecordTypeCname = "CNAME" ) +// RecordType_Values returns all elements of the RecordType enum +func RecordType_Values() []string { + return []string{ + RecordTypeCname, + } +} + const ( // RenewalEligibilityEligible is a RenewalEligibility enum value RenewalEligibilityEligible = "ELIGIBLE" @@ -4328,6 +4443,14 @@ const ( RenewalEligibilityIneligible = "INELIGIBLE" ) +// RenewalEligibility_Values returns all elements of the RenewalEligibility enum +func RenewalEligibility_Values() []string { + return []string{ + RenewalEligibilityEligible, + RenewalEligibilityIneligible, + } +} + const ( // RenewalStatusPendingAutoRenewal is a RenewalStatus enum value RenewalStatusPendingAutoRenewal = "PENDING_AUTO_RENEWAL" @@ -4342,6 +4465,16 @@ const ( RenewalStatusFailed = "FAILED" ) +// RenewalStatus_Values returns all elements of the RenewalStatus enum +func RenewalStatus_Values() []string { + return []string{ + RenewalStatusPendingAutoRenewal, + RenewalStatusPendingValidation, + RenewalStatusSuccess, + RenewalStatusFailed, + } +} + const ( // RevocationReasonUnspecified is a RevocationReason enum value RevocationReasonUnspecified = "UNSPECIFIED" @@ -4374,6 +4507,22 @@ const ( RevocationReasonAACompromise = "A_A_COMPROMISE" ) +// RevocationReason_Values returns all elements of the RevocationReason enum +func RevocationReason_Values() []string { + return []string{ + RevocationReasonUnspecified, + RevocationReasonKeyCompromise, + RevocationReasonCaCompromise, + RevocationReasonAffiliationChanged, + RevocationReasonSuperceded, + RevocationReasonCessationOfOperation, + RevocationReasonCertificateHold, + RevocationReasonRemoveFromCrl, + RevocationReasonPrivilegeWithdrawn, + RevocationReasonAACompromise, + } +} + const ( // ValidationMethodEmail is a ValidationMethod enum value ValidationMethodEmail = "EMAIL" @@ -4381,3 +4530,11 @@ const ( // ValidationMethodDns is a ValidationMethod enum value ValidationMethodDns = "DNS" ) + +// ValidationMethod_Values returns all elements of the ValidationMethod enum +func ValidationMethod_Values() []string { + return []string{ + ValidationMethodEmail, + ValidationMethodDns, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/acmpca/api.go b/vendor/github.com/aws/aws-sdk-go/service/acmpca/api.go index 22cca109ef4..dc6eabe52f4 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/acmpca/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/acmpca/api.go @@ -5882,6 +5882,15 @@ const ( ActionTypeListPermissions = "ListPermissions" ) +// ActionType_Values returns all elements of the ActionType enum +func ActionType_Values() []string { + return []string{ + ActionTypeIssueCertificate, + ActionTypeGetCertificate, + ActionTypeListPermissions, + } +} + const ( // AuditReportResponseFormatJson is a AuditReportResponseFormat enum value AuditReportResponseFormatJson = "JSON" @@ -5890,6 +5899,14 @@ const ( AuditReportResponseFormatCsv = "CSV" ) +// AuditReportResponseFormat_Values returns all elements of the AuditReportResponseFormat enum +func AuditReportResponseFormat_Values() []string { + return []string{ + AuditReportResponseFormatJson, + AuditReportResponseFormatCsv, + } +} + const ( // AuditReportStatusCreating is a AuditReportStatus enum value AuditReportStatusCreating = "CREATING" @@ -5901,6 +5918,15 @@ const ( AuditReportStatusFailed = "FAILED" ) +// AuditReportStatus_Values returns all elements of the AuditReportStatus enum +func AuditReportStatus_Values() []string { + return []string{ + AuditReportStatusCreating, + AuditReportStatusSuccess, + AuditReportStatusFailed, + } +} + const ( // CertificateAuthorityStatusCreating is a CertificateAuthorityStatus enum value CertificateAuthorityStatusCreating = "CREATING" @@ -5924,6 +5950,19 @@ const ( CertificateAuthorityStatusFailed = "FAILED" ) +// CertificateAuthorityStatus_Values returns all elements of the CertificateAuthorityStatus enum +func CertificateAuthorityStatus_Values() []string { + return []string{ + CertificateAuthorityStatusCreating, + CertificateAuthorityStatusPendingCertificate, + CertificateAuthorityStatusActive, + CertificateAuthorityStatusDeleted, + CertificateAuthorityStatusDisabled, + CertificateAuthorityStatusExpired, + CertificateAuthorityStatusFailed, + } +} + const ( // CertificateAuthorityTypeRoot is a CertificateAuthorityType enum value CertificateAuthorityTypeRoot = "ROOT" @@ -5932,6 +5971,14 @@ const ( CertificateAuthorityTypeSubordinate = "SUBORDINATE" ) +// CertificateAuthorityType_Values returns all elements of the CertificateAuthorityType enum +func CertificateAuthorityType_Values() []string { + return []string{ + CertificateAuthorityTypeRoot, + CertificateAuthorityTypeSubordinate, + } +} + const ( // FailureReasonRequestTimedOut is a FailureReason enum value FailureReasonRequestTimedOut = "REQUEST_TIMED_OUT" @@ -5943,6 +5990,15 @@ const ( FailureReasonOther = "OTHER" ) +// FailureReason_Values returns all elements of the FailureReason enum +func FailureReason_Values() []string { + return []string{ + FailureReasonRequestTimedOut, + FailureReasonUnsupportedAlgorithm, + FailureReasonOther, + } +} + const ( // KeyAlgorithmRsa2048 is a KeyAlgorithm enum value KeyAlgorithmRsa2048 = "RSA_2048" @@ -5957,6 +6013,16 @@ const ( KeyAlgorithmEcSecp384r1 = "EC_secp384r1" ) +// KeyAlgorithm_Values returns all elements of the KeyAlgorithm enum +func KeyAlgorithm_Values() []string { + return []string{ + KeyAlgorithmRsa2048, + KeyAlgorithmRsa4096, + KeyAlgorithmEcPrime256v1, + KeyAlgorithmEcSecp384r1, + } +} + const ( // RevocationReasonUnspecified is a RevocationReason enum value RevocationReasonUnspecified = "UNSPECIFIED" @@ -5983,6 +6049,20 @@ const ( RevocationReasonAACompromise = "A_A_COMPROMISE" ) +// RevocationReason_Values returns all elements of the RevocationReason enum +func RevocationReason_Values() []string { + return []string{ + RevocationReasonUnspecified, + RevocationReasonKeyCompromise, + RevocationReasonCertificateAuthorityCompromise, + RevocationReasonAffiliationChanged, + RevocationReasonSuperseded, + RevocationReasonCessationOfOperation, + RevocationReasonPrivilegeWithdrawn, + RevocationReasonAACompromise, + } +} + const ( // SigningAlgorithmSha256withecdsa is a SigningAlgorithm enum value SigningAlgorithmSha256withecdsa = "SHA256WITHECDSA" @@ -6003,6 +6083,18 @@ const ( SigningAlgorithmSha512withrsa = "SHA512WITHRSA" ) +// SigningAlgorithm_Values returns all elements of the SigningAlgorithm enum +func SigningAlgorithm_Values() []string { + return []string{ + SigningAlgorithmSha256withecdsa, + SigningAlgorithmSha384withecdsa, + SigningAlgorithmSha512withecdsa, + SigningAlgorithmSha256withrsa, + SigningAlgorithmSha384withrsa, + SigningAlgorithmSha512withrsa, + } +} + const ( // ValidityPeriodTypeEndDate is a ValidityPeriodType enum value ValidityPeriodTypeEndDate = "END_DATE" @@ -6019,3 +6111,14 @@ const ( // ValidityPeriodTypeYears is a ValidityPeriodType enum value ValidityPeriodTypeYears = "YEARS" ) + +// ValidityPeriodType_Values returns all elements of the ValidityPeriodType enum +func ValidityPeriodType_Values() []string { + return []string{ + ValidityPeriodTypeEndDate, + ValidityPeriodTypeAbsolute, + ValidityPeriodTypeDays, + ValidityPeriodTypeMonths, + ValidityPeriodTypeYears, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/amplify/api.go b/vendor/github.com/aws/aws-sdk-go/service/amplify/api.go index 76a70164f40..b89dddfb021 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/amplify/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/amplify/api.go @@ -57,7 +57,7 @@ func (c *Amplify) CreateAppRequest(input *CreateAppInput) (req *request.Request, // CreateApp API operation for AWS Amplify. // -// Creates a new Amplify App. +// Creates a new Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -68,22 +68,19 @@ func (c *Amplify) CreateAppRequest(input *CreateAppInput) (req *request.Request, // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // * DependentServiceFailureException -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/CreateApp func (c *Amplify) CreateApp(input *CreateAppInput) (*CreateAppOutput, error) { @@ -151,7 +148,7 @@ func (c *Amplify) CreateBackendEnvironmentRequest(input *CreateBackendEnvironmen // CreateBackendEnvironment API operation for AWS Amplify. // -// Creates a new backend environment for an Amplify App. +// Creates a new backend environment for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -162,21 +159,19 @@ func (c *Amplify) CreateBackendEnvironmentRequest(input *CreateBackendEnvironmen // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/CreateBackendEnvironment func (c *Amplify) CreateBackendEnvironment(input *CreateBackendEnvironmentInput) (*CreateBackendEnvironmentOutput, error) { @@ -244,7 +239,7 @@ func (c *Amplify) CreateBranchRequest(input *CreateBranchInput) (req *request.Re // CreateBranch API operation for AWS Amplify. // -// Creates a new Branch for an Amplify App. +// Creates a new branch for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -255,25 +250,22 @@ func (c *Amplify) CreateBranchRequest(input *CreateBranchInput) (req *request.Re // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // * DependentServiceFailureException -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/CreateBranch func (c *Amplify) CreateBranch(input *CreateBranchInput) (*CreateBranchOutput, error) { @@ -341,7 +333,8 @@ func (c *Amplify) CreateDeploymentRequest(input *CreateDeploymentInput) (req *re // CreateDeployment API operation for AWS Amplify. // -// Create a deployment for manual deploy apps. (Apps are not connected to repository) +// Creates a deployment for a manually deployed Amplify app. Manually deployed +// apps are not connected to a repository. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -352,18 +345,16 @@ func (c *Amplify) CreateDeploymentRequest(input *CreateDeploymentInput) (req *re // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/CreateDeployment func (c *Amplify) CreateDeployment(input *CreateDeploymentInput) (*CreateDeploymentOutput, error) { @@ -431,7 +422,8 @@ func (c *Amplify) CreateDomainAssociationRequest(input *CreateDomainAssociationI // CreateDomainAssociation API operation for AWS Amplify. // -// Create a new DomainAssociation on an App +// Creates a new domain association for an Amplify app. This action associates +// a custom domain with the Amplify app // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -442,25 +434,22 @@ func (c *Amplify) CreateDomainAssociationRequest(input *CreateDomainAssociationI // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // * DependentServiceFailureException -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/CreateDomainAssociation func (c *Amplify) CreateDomainAssociation(input *CreateDomainAssociationInput) (*CreateDomainAssociationOutput, error) { @@ -528,7 +517,7 @@ func (c *Amplify) CreateWebhookRequest(input *CreateWebhookInput) (req *request. // CreateWebhook API operation for AWS Amplify. // -// Create a new webhook on an App. +// Creates a new webhook on an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -539,25 +528,22 @@ func (c *Amplify) CreateWebhookRequest(input *CreateWebhookInput) (req *request. // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // * DependentServiceFailureException -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/CreateWebhook func (c *Amplify) CreateWebhook(input *CreateWebhookInput) (*CreateWebhookOutput, error) { @@ -625,7 +611,7 @@ func (c *Amplify) DeleteAppRequest(input *DeleteAppInput) (req *request.Request, // DeleteApp API operation for AWS Amplify. // -// Delete an existing Amplify App by appId. +// Deletes an existing Amplify app specified by an app 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 @@ -636,21 +622,19 @@ func (c *Amplify) DeleteAppRequest(input *DeleteAppInput) (req *request.Request, // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * DependentServiceFailureException -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/DeleteApp func (c *Amplify) DeleteApp(input *DeleteAppInput) (*DeleteAppOutput, error) { @@ -718,7 +702,7 @@ func (c *Amplify) DeleteBackendEnvironmentRequest(input *DeleteBackendEnvironmen // DeleteBackendEnvironment API operation for AWS Amplify. // -// Delete backend environment for an Amplify App. +// Deletes a backend environment for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -729,21 +713,19 @@ func (c *Amplify) DeleteBackendEnvironmentRequest(input *DeleteBackendEnvironmen // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * DependentServiceFailureException -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/DeleteBackendEnvironment func (c *Amplify) DeleteBackendEnvironment(input *DeleteBackendEnvironmentInput) (*DeleteBackendEnvironmentOutput, error) { @@ -811,7 +793,7 @@ func (c *Amplify) DeleteBranchRequest(input *DeleteBranchInput) (req *request.Re // DeleteBranch API operation for AWS Amplify. // -// Deletes a branch for an Amplify App. +// Deletes a branch for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -822,21 +804,19 @@ func (c *Amplify) DeleteBranchRequest(input *DeleteBranchInput) (req *request.Re // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * DependentServiceFailureException -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/DeleteBranch func (c *Amplify) DeleteBranch(input *DeleteBranchInput) (*DeleteBranchOutput, error) { @@ -904,7 +884,7 @@ func (c *Amplify) DeleteDomainAssociationRequest(input *DeleteDomainAssociationI // DeleteDomainAssociation API operation for AWS Amplify. // -// Deletes a DomainAssociation. +// Deletes a domain association for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -915,21 +895,19 @@ func (c *Amplify) DeleteDomainAssociationRequest(input *DeleteDomainAssociationI // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * DependentServiceFailureException -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/DeleteDomainAssociation func (c *Amplify) DeleteDomainAssociation(input *DeleteDomainAssociationInput) (*DeleteDomainAssociationOutput, error) { @@ -997,7 +975,7 @@ func (c *Amplify) DeleteJobRequest(input *DeleteJobInput) (req *request.Request, // DeleteJob API operation for AWS Amplify. // -// Delete a job, for an Amplify branch, part of Amplify App. +// Deletes a job for a branch of an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1008,21 +986,19 @@ func (c *Amplify) DeleteJobRequest(input *DeleteJobInput) (req *request.Request, // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/DeleteJob func (c *Amplify) DeleteJob(input *DeleteJobInput) (*DeleteJobOutput, error) { @@ -1101,21 +1077,19 @@ func (c *Amplify) DeleteWebhookRequest(input *DeleteWebhookInput) (req *request. // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/DeleteWebhook func (c *Amplify) DeleteWebhook(input *DeleteWebhookInput) (*DeleteWebhookOutput, error) { @@ -1183,7 +1157,8 @@ func (c *Amplify) GenerateAccessLogsRequest(input *GenerateAccessLogsInput) (req // GenerateAccessLogs API operation for AWS Amplify. // -// Retrieve website access logs for a specific time range via a pre-signed URL. +// Returns the website access logs for a specific time range using a presigned +// URL. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1194,17 +1169,16 @@ func (c *Amplify) GenerateAccessLogsRequest(input *GenerateAccessLogsInput) (req // // Returned Error Types: // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/GenerateAccessLogs func (c *Amplify) GenerateAccessLogs(input *GenerateAccessLogsInput) (*GenerateAccessLogsOutput, error) { @@ -1272,7 +1246,7 @@ func (c *Amplify) GetAppRequest(input *GetAppInput) (req *request.Request, outpu // GetApp API operation for AWS Amplify. // -// Retrieves an existing Amplify App by appId. +// Returns an existing Amplify app by appID. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1283,17 +1257,16 @@ func (c *Amplify) GetAppRequest(input *GetAppInput) (req *request.Request, outpu // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/GetApp func (c *Amplify) GetApp(input *GetAppInput) (*GetAppOutput, error) { @@ -1361,7 +1334,7 @@ func (c *Amplify) GetArtifactUrlRequest(input *GetArtifactUrlInput) (req *reques // GetArtifactUrl API operation for AWS Amplify. // -// Retrieves artifact info that corresponds to a artifactId. +// Returns the artifact info that corresponds to an artifact 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 @@ -1372,21 +1345,19 @@ func (c *Amplify) GetArtifactUrlRequest(input *GetArtifactUrlInput) (req *reques // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/GetArtifactUrl func (c *Amplify) GetArtifactUrl(input *GetArtifactUrlInput) (*GetArtifactUrlOutput, error) { @@ -1454,7 +1425,7 @@ func (c *Amplify) GetBackendEnvironmentRequest(input *GetBackendEnvironmentInput // GetBackendEnvironment API operation for AWS Amplify. // -// Retrieves a backend environment for an Amplify App. +// Returns a backend environment for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1465,17 +1436,16 @@ func (c *Amplify) GetBackendEnvironmentRequest(input *GetBackendEnvironmentInput // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/GetBackendEnvironment func (c *Amplify) GetBackendEnvironment(input *GetBackendEnvironmentInput) (*GetBackendEnvironmentOutput, error) { @@ -1543,7 +1513,7 @@ func (c *Amplify) GetBranchRequest(input *GetBranchInput) (req *request.Request, // GetBranch API operation for AWS Amplify. // -// Retrieves a branch for an Amplify App. +// Returns a branch for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1554,17 +1524,16 @@ func (c *Amplify) GetBranchRequest(input *GetBranchInput) (req *request.Request, // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/GetBranch func (c *Amplify) GetBranch(input *GetBranchInput) (*GetBranchOutput, error) { @@ -1632,7 +1601,7 @@ func (c *Amplify) GetDomainAssociationRequest(input *GetDomainAssociationInput) // GetDomainAssociation API operation for AWS Amplify. // -// Retrieves domain info that corresponds to an appId and domainName. +// Returns the domain information for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1643,17 +1612,16 @@ func (c *Amplify) GetDomainAssociationRequest(input *GetDomainAssociationInput) // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/GetDomainAssociation func (c *Amplify) GetDomainAssociation(input *GetDomainAssociationInput) (*GetDomainAssociationOutput, error) { @@ -1721,7 +1689,7 @@ func (c *Amplify) GetJobRequest(input *GetJobInput) (req *request.Request, outpu // GetJob API operation for AWS Amplify. // -// Get a job for a branch, part of an Amplify App. +// Returns a job for a branch of an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1732,21 +1700,19 @@ func (c *Amplify) GetJobRequest(input *GetJobInput) (req *request.Request, outpu // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/GetJob func (c *Amplify) GetJob(input *GetJobInput) (*GetJobOutput, error) { @@ -1814,7 +1780,7 @@ func (c *Amplify) GetWebhookRequest(input *GetWebhookInput) (req *request.Reques // GetWebhook API operation for AWS Amplify. // -// Retrieves webhook info that corresponds to a webhookId. +// Returns the webhook information that corresponds to a specified webhook 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 @@ -1825,21 +1791,19 @@ func (c *Amplify) GetWebhookRequest(input *GetWebhookInput) (req *request.Reques // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/GetWebhook func (c *Amplify) GetWebhook(input *GetWebhookInput) (*GetWebhookOutput, error) { @@ -1907,7 +1871,7 @@ func (c *Amplify) ListAppsRequest(input *ListAppsInput) (req *request.Request, o // ListApps API operation for AWS Amplify. // -// Lists existing Amplify Apps. +// Returns a list of the existing Amplify apps. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1918,14 +1882,13 @@ func (c *Amplify) ListAppsRequest(input *ListAppsInput) (req *request.Request, o // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/ListApps func (c *Amplify) ListApps(input *ListAppsInput) (*ListAppsOutput, error) { @@ -1993,7 +1956,7 @@ func (c *Amplify) ListArtifactsRequest(input *ListArtifactsInput) (req *request. // ListArtifacts API operation for AWS Amplify. // -// List artifacts with an app, a branch, a job and an artifact type. +// Returns a list of artifacts for a specified app, branch, and 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 @@ -2004,18 +1967,16 @@ func (c *Amplify) ListArtifactsRequest(input *ListArtifactsInput) (req *request. // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/ListArtifacts func (c *Amplify) ListArtifacts(input *ListArtifactsInput) (*ListArtifactsOutput, error) { @@ -2083,7 +2044,7 @@ func (c *Amplify) ListBackendEnvironmentsRequest(input *ListBackendEnvironmentsI // ListBackendEnvironments API operation for AWS Amplify. // -// Lists backend environments for an Amplify App. +// Lists the backend environments for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2094,14 +2055,13 @@ func (c *Amplify) ListBackendEnvironmentsRequest(input *ListBackendEnvironmentsI // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/ListBackendEnvironments func (c *Amplify) ListBackendEnvironments(input *ListBackendEnvironmentsInput) (*ListBackendEnvironmentsOutput, error) { @@ -2169,7 +2129,7 @@ func (c *Amplify) ListBranchesRequest(input *ListBranchesInput) (req *request.Re // ListBranches API operation for AWS Amplify. // -// Lists branches for an Amplify App. +// Lists the branches of an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2180,14 +2140,13 @@ func (c *Amplify) ListBranchesRequest(input *ListBranchesInput) (req *request.Re // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/ListBranches func (c *Amplify) ListBranches(input *ListBranchesInput) (*ListBranchesOutput, error) { @@ -2255,7 +2214,7 @@ func (c *Amplify) ListDomainAssociationsRequest(input *ListDomainAssociationsInp // ListDomainAssociations API operation for AWS Amplify. // -// List domains with an app +// Returns the domain associations for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2266,14 +2225,13 @@ func (c *Amplify) ListDomainAssociationsRequest(input *ListDomainAssociationsInp // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/ListDomainAssociations func (c *Amplify) ListDomainAssociations(input *ListDomainAssociationsInput) (*ListDomainAssociationsOutput, error) { @@ -2341,7 +2299,7 @@ func (c *Amplify) ListJobsRequest(input *ListJobsInput) (req *request.Request, o // ListJobs API operation for AWS Amplify. // -// List Jobs for a branch, part of an Amplify App. +// Lists the jobs for a branch of an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2352,18 +2310,16 @@ func (c *Amplify) ListJobsRequest(input *ListJobsInput) (req *request.Request, o // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/ListJobs func (c *Amplify) ListJobs(input *ListJobsInput) (*ListJobsOutput, error) { @@ -2431,7 +2387,7 @@ func (c *Amplify) ListTagsForResourceRequest(input *ListTagsForResourceInput) (r // ListTagsForResource API operation for AWS Amplify. // -// List tags for resource. +// Returns a list of tags for a specified Amazon Resource Name (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 @@ -2442,14 +2398,13 @@ func (c *Amplify) ListTagsForResourceRequest(input *ListTagsForResourceInput) (r // // Returned Error Types: // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * ResourceNotFoundException -// Exception thrown when an operation fails due to non-existent resource. +// An operation failed due to a non-existent resource. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/ListTagsForResource func (c *Amplify) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { @@ -2517,7 +2472,7 @@ func (c *Amplify) ListWebhooksRequest(input *ListWebhooksInput) (req *request.Re // ListWebhooks API operation for AWS Amplify. // -// List webhooks with an app. +// Returns a list of webhooks for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2528,18 +2483,16 @@ func (c *Amplify) ListWebhooksRequest(input *ListWebhooksInput) (req *request.Re // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/ListWebhooks func (c *Amplify) ListWebhooks(input *ListWebhooksInput) (*ListWebhooksOutput, error) { @@ -2607,7 +2560,8 @@ func (c *Amplify) StartDeploymentRequest(input *StartDeploymentInput) (req *requ // StartDeployment API operation for AWS Amplify. // -// Start a deployment for manual deploy apps. (Apps are not connected to repository) +// Starts a deployment for a manually deployed app. Manually deployed apps are +// not connected to a repository. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2618,21 +2572,19 @@ func (c *Amplify) StartDeploymentRequest(input *StartDeploymentInput) (req *requ // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/StartDeployment func (c *Amplify) StartDeployment(input *StartDeploymentInput) (*StartDeploymentOutput, error) { @@ -2700,7 +2652,7 @@ func (c *Amplify) StartJobRequest(input *StartJobInput) (req *request.Request, o // StartJob API operation for AWS Amplify. // -// Starts a new job for a branch, part of an Amplify App. +// Starts a new job for a branch of an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2711,21 +2663,19 @@ func (c *Amplify) StartJobRequest(input *StartJobInput) (req *request.Request, o // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/StartJob func (c *Amplify) StartJob(input *StartJobInput) (*StartJobOutput, error) { @@ -2793,7 +2743,7 @@ func (c *Amplify) StopJobRequest(input *StopJobInput) (req *request.Request, out // StopJob API operation for AWS Amplify. // -// Stop a job that is in progress, for an Amplify branch, part of Amplify App. +// Stops a job that is in progress for a branch of an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2804,21 +2754,19 @@ func (c *Amplify) StopJobRequest(input *StopJobInput) (req *request.Request, out // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * LimitExceededException -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/StopJob func (c *Amplify) StopJob(input *StopJobInput) (*StopJobOutput, error) { @@ -2887,7 +2835,7 @@ func (c *Amplify) TagResourceRequest(input *TagResourceInput) (req *request.Requ // TagResource API operation for AWS Amplify. // -// Tag resource with tag key and value. +// Tags the resource with a tag key and value. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2898,14 +2846,13 @@ func (c *Amplify) TagResourceRequest(input *TagResourceInput) (req *request.Requ // // Returned Error Types: // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * ResourceNotFoundException -// Exception thrown when an operation fails due to non-existent resource. +// An operation failed due to a non-existent resource. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/TagResource func (c *Amplify) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { @@ -2974,7 +2921,7 @@ func (c *Amplify) UntagResourceRequest(input *UntagResourceInput) (req *request. // UntagResource API operation for AWS Amplify. // -// Untag resource with resourceArn. +// Untags a resource with a specified Amazon Resource Name (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 @@ -2985,14 +2932,13 @@ func (c *Amplify) UntagResourceRequest(input *UntagResourceInput) (req *request. // // Returned Error Types: // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * ResourceNotFoundException -// Exception thrown when an operation fails due to non-existent resource. +// An operation failed due to a non-existent resource. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/UntagResource func (c *Amplify) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { @@ -3060,7 +3006,7 @@ func (c *Amplify) UpdateAppRequest(input *UpdateAppInput) (req *request.Request, // UpdateApp API operation for AWS Amplify. // -// Updates an existing Amplify App. +// Updates an existing Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3071,17 +3017,16 @@ func (c *Amplify) UpdateAppRequest(input *UpdateAppInput) (req *request.Request, // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/UpdateApp func (c *Amplify) UpdateApp(input *UpdateAppInput) (*UpdateAppOutput, error) { @@ -3149,7 +3094,7 @@ func (c *Amplify) UpdateBranchRequest(input *UpdateBranchInput) (req *request.Re // UpdateBranch API operation for AWS Amplify. // -// Updates a branch for an Amplify App. +// Updates a branch for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3160,21 +3105,19 @@ func (c *Amplify) UpdateBranchRequest(input *UpdateBranchInput) (req *request.Re // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * DependentServiceFailureException -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/UpdateBranch func (c *Amplify) UpdateBranch(input *UpdateBranchInput) (*UpdateBranchOutput, error) { @@ -3242,7 +3185,7 @@ func (c *Amplify) UpdateDomainAssociationRequest(input *UpdateDomainAssociationI // UpdateDomainAssociation API operation for AWS Amplify. // -// Create a new DomainAssociation on an App +// Creates a new domain association for an Amplify app. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3253,21 +3196,19 @@ func (c *Amplify) UpdateDomainAssociationRequest(input *UpdateDomainAssociationI // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * DependentServiceFailureException -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/UpdateDomainAssociation func (c *Amplify) UpdateDomainAssociation(input *UpdateDomainAssociationInput) (*UpdateDomainAssociationOutput, error) { @@ -3335,7 +3276,7 @@ func (c *Amplify) UpdateWebhookRequest(input *UpdateWebhookInput) (req *request. // UpdateWebhook API operation for AWS Amplify. // -// Update a webhook. +// Updates a webhook. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3346,21 +3287,19 @@ func (c *Amplify) UpdateWebhookRequest(input *UpdateWebhookInput) (req *request. // // Returned Error Types: // * BadRequestException -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. // // * UnauthorizedException -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. // // * NotFoundException -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. // // * InternalFailureException -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. // // * DependentServiceFailureException -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. // // See also, https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/UpdateWebhook func (c *Amplify) UpdateWebhook(input *UpdateWebhookInput) (*UpdateWebhookOutput, error) { @@ -3384,94 +3323,100 @@ func (c *Amplify) UpdateWebhookWithContext(ctx aws.Context, input *UpdateWebhook return out, req.Send() } -// Amplify App represents different branches of a repository for building, deploying, -// and hosting. +// Represents the different branches of a repository for building, deploying, +// and hosting an Amplify app. type App struct { _ struct{} `type:"structure"` - // ARN for the Amplify App. + // The Amazon Resource Name (ARN) of the Amplify app. // // AppArn is a required field AppArn *string `locationName:"appArn" type:"string" required:"true"` - // Unique Id for the Amplify App. + // The unique ID of the Amplify app. // // AppId is a required field AppId *string `locationName:"appId" min:"1" type:"string" required:"true"` - // Automated branch creation config for the Amplify App. + // Describes the automated branch creation configuration for the Amplify app. AutoBranchCreationConfig *AutoBranchCreationConfig `locationName:"autoBranchCreationConfig" type:"structure"` - // Automated branch creation glob patterns for the Amplify App. + // Describes the automated branch creation glob patterns for the Amplify app. AutoBranchCreationPatterns []*string `locationName:"autoBranchCreationPatterns" type:"list"` - // Basic Authorization credentials for branches for the Amplify App. - BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string"` + // The basic authorization credentials for branches for the Amplify app. + BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string" sensitive:"true"` - // BuildSpec content for Amplify App. + // Describes the content of the build specification (build spec) for the Amplify + // app. BuildSpec *string `locationName:"buildSpec" min:"1" type:"string"` - // Create date / time for the Amplify App. + // Creates a date and time for the Amplify app. // // CreateTime is a required field CreateTime *time.Time `locationName:"createTime" type:"timestamp" required:"true"` - // Custom redirect / rewrite rules for the Amplify App. + // Describes the custom redirect and rewrite rules for the Amplify app. CustomRules []*CustomRule `locationName:"customRules" type:"list"` - // Default domain for the Amplify App. + // The default domain for the Amplify app. // // DefaultDomain is a required field DefaultDomain *string `locationName:"defaultDomain" min:"1" type:"string" required:"true"` - // Description for the Amplify App. + // The description for the Amplify app. // // Description is a required field Description *string `locationName:"description" type:"string" required:"true"` - // Enables automated branch creation for the Amplify App. + // Enables automated branch creation for the Amplify app. EnableAutoBranchCreation *bool `locationName:"enableAutoBranchCreation" type:"boolean"` - // Enables Basic Authorization for branches for the Amplify App. + // Enables basic authorization for the Amplify app's branches. // // EnableBasicAuth is a required field EnableBasicAuth *bool `locationName:"enableBasicAuth" type:"boolean" required:"true"` - // Enables auto-building of branches for the Amplify App. + // Enables the auto-building of branches for the Amplify app. // // EnableBranchAutoBuild is a required field EnableBranchAutoBuild *bool `locationName:"enableBranchAutoBuild" type:"boolean" required:"true"` - // Environment Variables for the Amplify App. + // Automatically disconnect a branch in the Amplify Console when you delete + // a branch from your Git repository. + EnableBranchAutoDeletion *bool `locationName:"enableBranchAutoDeletion" type:"boolean"` + + // The environment variables for the Amplify app. // // EnvironmentVariables is a required field EnvironmentVariables map[string]*string `locationName:"environmentVariables" type:"map" required:"true"` - // IAM service role ARN for the Amplify App. + // The AWS Identity and Access Management (IAM) service role for the Amazon + // Resource Name (ARN) of the Amplify app. IamServiceRoleArn *string `locationName:"iamServiceRoleArn" min:"1" type:"string"` - // Name for the Amplify App. + // The name for the Amplify app. // // Name is a required field Name *string `locationName:"name" min:"1" type:"string" required:"true"` - // Platform for the Amplify App. + // The platform for the Amplify app. // // Platform is a required field Platform *string `locationName:"platform" type:"string" required:"true" enum:"Platform"` - // Structure with Production Branch information. + // Describes the information about a production branch of the Amplify app. ProductionBranch *ProductionBranch `locationName:"productionBranch" type:"structure"` - // Repository for the Amplify App. + // The repository for the Amplify app. // // Repository is a required field Repository *string `locationName:"repository" type:"string" required:"true"` - // Tag for Amplify App. + // The tag for the Amplify app. Tags map[string]*string `locationName:"tags" min:"1" type:"map"` - // Update date / time for the Amplify App. + // Updates the date and time for the Amplify app. // // UpdateTime is a required field UpdateTime *time.Time `locationName:"updateTime" type:"timestamp" required:"true"` @@ -3565,6 +3510,12 @@ func (s *App) SetEnableBranchAutoBuild(v bool) *App { return s } +// SetEnableBranchAutoDeletion sets the EnableBranchAutoDeletion field's value. +func (s *App) SetEnableBranchAutoDeletion(v bool) *App { + s.EnableBranchAutoDeletion = &v + return s +} + // SetEnvironmentVariables sets the EnvironmentVariables field's value. func (s *App) SetEnvironmentVariables(v map[string]*string) *App { s.EnvironmentVariables = v @@ -3613,16 +3564,16 @@ func (s *App) SetUpdateTime(v time.Time) *App { return s } -// Structure for artifact. +// Describes an artifact. type Artifact struct { _ struct{} `type:"structure"` - // File name for the artifact. + // The file name for the artifact. // // ArtifactFileName is a required field ArtifactFileName *string `locationName:"artifactFileName" type:"string" required:"true"` - // Unique Id for a artifact. + // The unique ID for the artifact. // // ArtifactId is a required field ArtifactId *string `locationName:"artifactId" type:"string" required:"true"` @@ -3650,35 +3601,35 @@ func (s *Artifact) SetArtifactId(v string) *Artifact { return s } -// Structure with auto branch creation config. +// Describes the automated branch creation configuration. type AutoBranchCreationConfig struct { _ struct{} `type:"structure"` - // Basic Authorization credentials for the auto created branch. - BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string"` + // The basic authorization credentials for the autocreated branch. + BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string" sensitive:"true"` - // BuildSpec for the auto created branch. + // The build specification (build spec) for the autocreated branch. BuildSpec *string `locationName:"buildSpec" min:"1" type:"string"` - // Enables auto building for the auto created branch. + // Enables auto building for the autocreated branch. EnableAutoBuild *bool `locationName:"enableAutoBuild" type:"boolean"` - // Enables Basic Auth for the auto created branch. + // Enables basic authorization for the autocreated branch. EnableBasicAuth *bool `locationName:"enableBasicAuth" type:"boolean"` - // Enables Pull Request Preview for auto created branch. + // Enables pull request preview for the autocreated branch. EnablePullRequestPreview *bool `locationName:"enablePullRequestPreview" type:"boolean"` - // Environment Variables for the auto created branch. + // The environment variables for the autocreated branch. EnvironmentVariables map[string]*string `locationName:"environmentVariables" type:"map"` - // Framework for the auto created branch. + // The framework for the autocreated branch. Framework *string `locationName:"framework" type:"string"` - // The Amplify Environment name for the pull request. + // The Amplify environment name for the pull request. PullRequestEnvironmentName *string `locationName:"pullRequestEnvironmentName" type:"string"` - // Stage for the auto created branch. + // Describes the current stage for the autocreated branch. Stage *string `locationName:"stage" type:"string" enum:"Stage"` } @@ -3759,33 +3710,35 @@ func (s *AutoBranchCreationConfig) SetStage(v string) *AutoBranchCreationConfig return s } -// Backend environment for an Amplify App. +// Describes the backend environment for an Amplify app. type BackendEnvironment struct { _ struct{} `type:"structure"` - // Arn for a backend environment, part of an Amplify App. + // The Amazon Resource Name (ARN) for a backend environment that is part of + // an Amplify app. // // BackendEnvironmentArn is a required field BackendEnvironmentArn *string `locationName:"backendEnvironmentArn" min:"1" type:"string" required:"true"` - // Creation date and time for a backend environment, part of an Amplify App. + // The creation date and time for a backend environment that is part of an Amplify + // app. // // CreateTime is a required field CreateTime *time.Time `locationName:"createTime" type:"timestamp" required:"true"` - // Name of deployment artifacts. + // The name of deployment artifacts. DeploymentArtifacts *string `locationName:"deploymentArtifacts" min:"1" type:"string"` - // Name for a backend environment, part of an Amplify App. + // The name for a backend environment that is part of an Amplify app. // // EnvironmentName is a required field EnvironmentName *string `locationName:"environmentName" min:"1" type:"string" required:"true"` - // CloudFormation stack name of backend environment. + // The AWS CloudFormation stack name of a backend environment. StackName *string `locationName:"stackName" min:"1" type:"string"` - // Last updated date and time for a backend environment, part of an Amplify - // App. + // The last updated date and time for a backend environment that is part of + // an Amplify app. // // UpdateTime is a required field UpdateTime *time.Time `locationName:"updateTime" type:"timestamp" required:"true"` @@ -3837,7 +3790,7 @@ func (s *BackendEnvironment) SetUpdateTime(v time.Time) *BackendEnvironment { return s } -// Exception thrown when a request contains unexpected data. +// A request contains unexpected data. type BadRequestException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -3893,48 +3846,50 @@ func (s *BadRequestException) RequestID() string { return s.RespMetadata.RequestID } -// Branch for an Amplify App, which maps to a 3rd party repository branch. +// The branch for an Amplify app, which maps to a third-party repository branch. type Branch struct { _ struct{} `type:"structure"` - // Id of the active job for a branch, part of an Amplify App. + // The ID of the active job for a branch of an Amplify app. // // ActiveJobId is a required field ActiveJobId *string `locationName:"activeJobId" type:"string" required:"true"` - // List of custom resources that are linked to this branch. + // A list of custom resources that are linked to this branch. AssociatedResources []*string `locationName:"associatedResources" type:"list"` - // ARN for a Backend Environment, part of an Amplify App. + // The Amazon Resource Name (ARN) for a backend environment that is part of + // an Amplify app. BackendEnvironmentArn *string `locationName:"backendEnvironmentArn" min:"1" type:"string"` - // Basic Authorization credentials for a branch, part of an Amplify App. - BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string"` + // The basic authorization credentials for a branch of an Amplify app. + BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string" sensitive:"true"` - // ARN for a branch, part of an Amplify App. + // The Amazon Resource Name (ARN) for a branch that is part of an Amplify app. // // BranchArn is a required field BranchArn *string `locationName:"branchArn" type:"string" required:"true"` - // Name for a branch, part of an Amplify App. + // The name for the branch that is part of an Amplify app. // // BranchName is a required field BranchName *string `locationName:"branchName" min:"1" type:"string" required:"true"` - // BuildSpec content for branch for Amplify App. + // The build specification (build spec) content for the branch of an Amplify + // app. BuildSpec *string `locationName:"buildSpec" min:"1" type:"string"` - // Creation date and time for a branch, part of an Amplify App. + // The creation date and time for a branch that is part of an Amplify app. // // CreateTime is a required field CreateTime *time.Time `locationName:"createTime" type:"timestamp" required:"true"` - // Custom domains for a branch, part of an Amplify App. + // The custom domains for a branch of an Amplify app. // // CustomDomains is a required field CustomDomains []*string `locationName:"customDomains" type:"list" required:"true"` - // Description for a branch, part of an Amplify App. + // The description for the branch that is part of an Amplify app. // // Description is a required field Description *string `locationName:"description" type:"string" required:"true"` @@ -3942,69 +3897,69 @@ type Branch struct { // The destination branch if the branch is a pull request branch. DestinationBranch *string `locationName:"destinationBranch" min:"1" type:"string"` - // Display name for a branch, will use as the default domain prefix. + // The display name for the branch. This is used as the default domain prefix. // // DisplayName is a required field DisplayName *string `locationName:"displayName" type:"string" required:"true"` - // Enables auto-building on push for a branch, part of an Amplify App. + // Enables auto-building on push for a branch of an Amplify app. // // EnableAutoBuild is a required field EnableAutoBuild *bool `locationName:"enableAutoBuild" type:"boolean" required:"true"` - // Enables Basic Authorization for a branch, part of an Amplify App. + // Enables basic authorization for a branch of an Amplify app. // // EnableBasicAuth is a required field EnableBasicAuth *bool `locationName:"enableBasicAuth" type:"boolean" required:"true"` - // Enables notifications for a branch, part of an Amplify App. + // Enables notifications for a branch that is part of an Amplify app. // // EnableNotification is a required field EnableNotification *bool `locationName:"enableNotification" type:"boolean" required:"true"` - // Enables Pull Request Preview for this branch. + // Enables pull request preview for the branch. // // EnablePullRequestPreview is a required field EnablePullRequestPreview *bool `locationName:"enablePullRequestPreview" type:"boolean" required:"true"` - // Environment Variables specific to a branch, part of an Amplify App. + // The environment variables specific to a branch of an Amplify app. // // EnvironmentVariables is a required field EnvironmentVariables map[string]*string `locationName:"environmentVariables" type:"map" required:"true"` - // Framework for a branch, part of an Amplify App. + // The framework for a branch of an Amplify app. // // Framework is a required field Framework *string `locationName:"framework" type:"string" required:"true"` - // The Amplify Environment name for the pull request. + // The Amplify environment name for the pull request. PullRequestEnvironmentName *string `locationName:"pullRequestEnvironmentName" type:"string"` // The source branch if the branch is a pull request branch. SourceBranch *string `locationName:"sourceBranch" min:"1" type:"string"` - // Stage for a branch, part of an Amplify App. + // The current stage for the branch that is part of an Amplify app. // // Stage is a required field Stage *string `locationName:"stage" type:"string" required:"true" enum:"Stage"` - // Tag for branch for Amplify App. + // The tag for the branch of an Amplify app. Tags map[string]*string `locationName:"tags" min:"1" type:"map"` - // Thumbnail URL for the branch. + // The thumbnail URL for the branch of an Amplify app. ThumbnailUrl *string `locationName:"thumbnailUrl" min:"1" type:"string"` - // Total number of Jobs part of an Amplify App. + // The total number of jobs that are part of an Amplify app. // // TotalNumberOfJobs is a required field TotalNumberOfJobs *string `locationName:"totalNumberOfJobs" type:"string" required:"true"` - // The content TTL for the website in seconds. + // The content Time to Live (TTL) for the website in seconds. // // Ttl is a required field Ttl *string `locationName:"ttl" type:"string" required:"true"` - // Last updated date and time for a branch, part of an Amplify App. + // The last updated date and time for a branch that is part of an Amplify app. // // UpdateTime is a required field UpdateTime *time.Time `locationName:"updateTime" type:"timestamp" required:"true"` @@ -4176,64 +4131,71 @@ func (s *Branch) SetUpdateTime(v time.Time) *Branch { return s } -// Request structure used to create Apps in Amplify. +// The request structure used to create apps in Amplify. type CreateAppInput struct { _ struct{} `type:"structure"` - // Personal Access token for 3rd party source control system for an Amplify - // App, used to create webhook and read-only deploy key. Token is not stored. - AccessToken *string `locationName:"accessToken" min:"1" type:"string"` + // The personal access token for a third-party source control system for an + // Amplify app. The personal access token is used to create a webhook and a + // read-only deploy key. The token is not stored. + AccessToken *string `locationName:"accessToken" min:"1" type:"string" sensitive:"true"` - // Automated branch creation config for the Amplify App. + // The automated branch creation configuration for the Amplify app. AutoBranchCreationConfig *AutoBranchCreationConfig `locationName:"autoBranchCreationConfig" type:"structure"` - // Automated branch creation glob patterns for the Amplify App. + // The automated branch creation glob patterns for the Amplify app. AutoBranchCreationPatterns []*string `locationName:"autoBranchCreationPatterns" type:"list"` - // Credentials for Basic Authorization for an Amplify App. - BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string"` + // The credentials for basic authorization for an Amplify app. + BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string" sensitive:"true"` - // BuildSpec for an Amplify App + // The build specification (build spec) for an Amplify app. BuildSpec *string `locationName:"buildSpec" min:"1" type:"string"` - // Custom rewrite / redirect rules for an Amplify App. + // The custom rewrite and redirect rules for an Amplify app. CustomRules []*CustomRule `locationName:"customRules" type:"list"` - // Description for an Amplify App + // The description for an Amplify app. Description *string `locationName:"description" type:"string"` - // Enables automated branch creation for the Amplify App. + // Enables automated branch creation for the Amplify app. EnableAutoBranchCreation *bool `locationName:"enableAutoBranchCreation" type:"boolean"` - // Enable Basic Authorization for an Amplify App, this will apply to all branches - // part of this App. + // Enables basic authorization for an Amplify app. This will apply to all branches + // that are part of this app. EnableBasicAuth *bool `locationName:"enableBasicAuth" type:"boolean"` - // Enable the auto building of branches for an Amplify App. + // Enables the auto building of branches for an Amplify app. EnableBranchAutoBuild *bool `locationName:"enableBranchAutoBuild" type:"boolean"` - // Environment variables map for an Amplify App. + // Automatically disconnects a branch in the Amplify Console when you delete + // a branch from your Git repository. + EnableBranchAutoDeletion *bool `locationName:"enableBranchAutoDeletion" type:"boolean"` + + // The environment variables map for an Amplify app. EnvironmentVariables map[string]*string `locationName:"environmentVariables" type:"map"` - // AWS IAM service role for an Amplify App + // The AWS Identity and Access Management (IAM) service role for an Amplify + // app. IamServiceRoleArn *string `locationName:"iamServiceRoleArn" min:"1" type:"string"` - // Name for the Amplify App + // The name for the Amplify app. // // Name is a required field Name *string `locationName:"name" min:"1" type:"string" required:"true"` - // OAuth token for 3rd party source control system for an Amplify App, used - // to create webhook and read-only deploy key. OAuth token is not stored. - OauthToken *string `locationName:"oauthToken" type:"string"` + // The OAuth token for a third-party source control system for an Amplify app. + // The OAuth token is used to create a webhook and a read-only deploy key. The + // OAuth token is not stored. + OauthToken *string `locationName:"oauthToken" type:"string" sensitive:"true"` - // Platform / framework for an Amplify App + // The platform or framework for an Amplify app. Platform *string `locationName:"platform" type:"string" enum:"Platform"` - // Repository for an Amplify App + // The repository for an Amplify app. Repository *string `locationName:"repository" type:"string"` - // Tag for an Amplify App + // The tag for an Amplify app. Tags map[string]*string `locationName:"tags" min:"1" type:"map"` } @@ -4350,6 +4312,12 @@ func (s *CreateAppInput) SetEnableBranchAutoBuild(v bool) *CreateAppInput { return s } +// SetEnableBranchAutoDeletion sets the EnableBranchAutoDeletion field's value. +func (s *CreateAppInput) SetEnableBranchAutoDeletion(v bool) *CreateAppInput { + s.EnableBranchAutoDeletion = &v + return s +} + // SetEnvironmentVariables sets the EnvironmentVariables field's value. func (s *CreateAppInput) SetEnvironmentVariables(v map[string]*string) *CreateAppInput { s.EnvironmentVariables = v @@ -4395,8 +4363,8 @@ func (s *CreateAppInput) SetTags(v map[string]*string) *CreateAppInput { type CreateAppOutput struct { _ struct{} `type:"structure"` - // Amplify App represents different branches of a repository for building, deploying, - // and hosting. + // Represents the different branches of a repository for building, deploying, + // and hosting an Amplify app. // // App is a required field App *App `locationName:"app" type:"structure" required:"true"` @@ -4418,24 +4386,24 @@ func (s *CreateAppOutput) SetApp(v *App) *CreateAppOutput { return s } -// Request structure for a backend environment create request. +// The request structure for the backend environment create request. type CreateBackendEnvironmentInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name of deployment artifacts. + // The name of deployment artifacts. DeploymentArtifacts *string `locationName:"deploymentArtifacts" min:"1" type:"string"` - // Name for the backend environment. + // The name for the backend environment. // // EnvironmentName is a required field EnvironmentName *string `locationName:"environmentName" min:"1" type:"string" required:"true"` - // CloudFormation stack name of backend environment. + // The AWS CloudFormation stack name of a backend environment. StackName *string `locationName:"stackName" min:"1" type:"string"` } @@ -4501,11 +4469,11 @@ func (s *CreateBackendEnvironmentInput) SetStackName(v string) *CreateBackendEnv return s } -// Result structure for create backend environment. +// The result structure for the create backend environment request. type CreateBackendEnvironmentOutput struct { _ struct{} `type:"structure"` - // Backend environment structure for an amplify App. + // Describes the backend environment for an Amplify app. // // BackendEnvironment is a required field BackendEnvironment *BackendEnvironment `locationName:"backendEnvironment" type:"structure" required:"true"` @@ -4527,63 +4495,64 @@ func (s *CreateBackendEnvironmentOutput) SetBackendEnvironment(v *BackendEnviron return s } -// Request structure for a branch create request. +// The request structure for the create branch request. type CreateBranchInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // ARN for a Backend Environment, part of an Amplify App. + // The Amazon Resource Name (ARN) for a backend environment that is part of + // an Amplify app. BackendEnvironmentArn *string `locationName:"backendEnvironmentArn" min:"1" type:"string"` - // Basic Authorization credentials for the branch. - BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string"` + // The basic authorization credentials for the branch. + BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string" sensitive:"true"` - // Name for the branch. + // The name for the branch. // // BranchName is a required field BranchName *string `locationName:"branchName" min:"1" type:"string" required:"true"` - // BuildSpec for the branch. + // The build specification (build spec) for the branch. BuildSpec *string `locationName:"buildSpec" min:"1" type:"string"` - // Description for the branch. + // The description for the branch. Description *string `locationName:"description" type:"string"` - // Display name for a branch, will use as the default domain prefix. + // The display name for a branch. This is used as the default domain prefix. DisplayName *string `locationName:"displayName" type:"string"` // Enables auto building for the branch. EnableAutoBuild *bool `locationName:"enableAutoBuild" type:"boolean"` - // Enables Basic Auth for the branch. + // Enables basic authorization for the branch. EnableBasicAuth *bool `locationName:"enableBasicAuth" type:"boolean"` // Enables notifications for the branch. EnableNotification *bool `locationName:"enableNotification" type:"boolean"` - // Enables Pull Request Preview for this branch. + // Enables pull request preview for this branch. EnablePullRequestPreview *bool `locationName:"enablePullRequestPreview" type:"boolean"` - // Environment Variables for the branch. + // The environment variables for the branch. EnvironmentVariables map[string]*string `locationName:"environmentVariables" type:"map"` - // Framework for the branch. + // The framework for the branch. Framework *string `locationName:"framework" type:"string"` - // The Amplify Environment name for the pull request. + // The Amplify environment name for the pull request. PullRequestEnvironmentName *string `locationName:"pullRequestEnvironmentName" type:"string"` - // Stage for the branch. + // Describes the current stage for the branch. Stage *string `locationName:"stage" type:"string" enum:"Stage"` - // Tag for the branch. + // The tag for the branch. Tags map[string]*string `locationName:"tags" min:"1" type:"map"` - // The content TTL for the website in seconds. + // The content Time To Live (TTL) for the website in seconds. Ttl *string `locationName:"ttl" type:"string"` } @@ -4730,11 +4699,12 @@ func (s *CreateBranchInput) SetTtl(v string) *CreateBranchInput { return s } -// Result structure for create branch request. +// The result structure for create branch request. type CreateBranchOutput struct { _ struct{} `type:"structure"` - // Branch structure for an Amplify App. + // Describes the branch for an Amplify app, which maps to a third-party repository + // branch. // // Branch is a required field Branch *Branch `locationName:"branch" type:"structure" required:"true"` @@ -4756,24 +4726,24 @@ func (s *CreateBranchOutput) SetBranch(v *Branch) *CreateBranchOutput { return s } -// Request structure for create a new deployment. +// The request structure for the create a new deployment request. type CreateDeploymentInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for the branch, for the Job. + // The name for the branch, for the job. // // BranchName is a required field BranchName *string `location:"uri" locationName:"branchName" min:"1" type:"string" required:"true"` - // Optional file map that contains file name as the key and file content md5 - // hash as the value. If this argument is provided, the service will generate - // different upload url per file. Otherwise, the service will only generate - // a single upload url for the zipped files. + // An optional file map that contains the file name as the key and the file + // content md5 hash as the value. If this argument is provided, the service + // will generate a unique upload URL per file. Otherwise, the service will only + // generate a single upload URL for the zipped files. FileMap map[string]*string `locationName:"fileMap" type:"map"` } @@ -4827,20 +4797,21 @@ func (s *CreateDeploymentInput) SetFileMap(v map[string]*string) *CreateDeployme return s } -// Result structure for create a new deployment. +// The result structure for the create a new deployment request. type CreateDeploymentOutput struct { _ struct{} `type:"structure"` - // When the fileMap argument is provided in the request, the fileUploadUrls - // will contain a map of file names to upload url. + // When the fileMap argument is provided in the request, fileUploadUrls will + // contain a map of file names to upload URLs. // // FileUploadUrls is a required field FileUploadUrls map[string]*string `locationName:"fileUploadUrls" type:"map" required:"true"` - // The jobId for this deployment, will supply to start deployment api. + // The job ID for this deployment. will supply to start deployment api. JobId *string `locationName:"jobId" type:"string"` - // When the fileMap argument is NOT provided. This zipUploadUrl will be returned. + // When the fileMap argument is not provided in the request, this zipUploadUrl + // is returned. // // ZipUploadUrl is a required field ZipUploadUrl *string `locationName:"zipUploadUrl" type:"string" required:"true"` @@ -4874,24 +4845,31 @@ func (s *CreateDeploymentOutput) SetZipUploadUrl(v string) *CreateDeploymentOutp return s } -// Request structure for create Domain Association request. +// The request structure for the create domain association request. type CreateDomainAssociationInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Domain name for the Domain Association. + // Sets the branch patterns for automatic subdomain creation. + AutoSubDomainCreationPatterns []*string `locationName:"autoSubDomainCreationPatterns" type:"list"` + + // The required AWS Identity and Access Management (IAM) service role for the + // Amazon Resource Name (ARN) for automatically creating subdomains. + AutoSubDomainIAMRole *string `locationName:"autoSubDomainIAMRole" type:"string"` + + // The domain name for the domain association. // // DomainName is a required field DomainName *string `locationName:"domainName" type:"string" required:"true"` - // Enables automated creation of Subdomains for branches. (Currently not supported) + // Enables the automated creation of subdomains for branches. EnableAutoSubDomain *bool `locationName:"enableAutoSubDomain" type:"boolean"` - // Setting structure for the Subdomain. + // The setting for the subdomain. // // SubDomainSettings is a required field SubDomainSettings []*SubDomainSetting `locationName:"subDomainSettings" type:"list" required:"true"` @@ -4945,6 +4923,18 @@ func (s *CreateDomainAssociationInput) SetAppId(v string) *CreateDomainAssociati return s } +// SetAutoSubDomainCreationPatterns sets the AutoSubDomainCreationPatterns field's value. +func (s *CreateDomainAssociationInput) SetAutoSubDomainCreationPatterns(v []*string) *CreateDomainAssociationInput { + s.AutoSubDomainCreationPatterns = v + return s +} + +// SetAutoSubDomainIAMRole sets the AutoSubDomainIAMRole field's value. +func (s *CreateDomainAssociationInput) SetAutoSubDomainIAMRole(v string) *CreateDomainAssociationInput { + s.AutoSubDomainIAMRole = &v + return s +} + // SetDomainName sets the DomainName field's value. func (s *CreateDomainAssociationInput) SetDomainName(v string) *CreateDomainAssociationInput { s.DomainName = &v @@ -4963,11 +4953,12 @@ func (s *CreateDomainAssociationInput) SetSubDomainSettings(v []*SubDomainSettin return s } -// Result structure for the create Domain Association request. +// The result structure for the create domain association request. type CreateDomainAssociationOutput struct { _ struct{} `type:"structure"` - // Domain Association structure. + // Describes the structure of a domain association, which associates a custom + // domain with an Amplify app. // // DomainAssociation is a required field DomainAssociation *DomainAssociation `locationName:"domainAssociation" type:"structure" required:"true"` @@ -4989,21 +4980,21 @@ func (s *CreateDomainAssociationOutput) SetDomainAssociation(v *DomainAssociatio return s } -// Request structure for create webhook request. +// The request structure for the create webhook request. type CreateWebhookInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for a branch, part of an Amplify App. + // The name for a branch that is part of an Amplify app. // // BranchName is a required field BranchName *string `locationName:"branchName" min:"1" type:"string" required:"true"` - // Description for a webhook. + // The description for a webhook. Description *string `locationName:"description" type:"string"` } @@ -5057,11 +5048,11 @@ func (s *CreateWebhookInput) SetDescription(v string) *CreateWebhookInput { return s } -// Result structure for the create webhook request. +// The result structure for the create webhook request. type CreateWebhookOutput struct { _ struct{} `type:"structure"` - // Webhook structure. + // Describes a webhook that connects repository events to an Amplify app. // // Webhook is a required field Webhook *Webhook `locationName:"webhook" type:"structure" required:"true"` @@ -5083,11 +5074,11 @@ func (s *CreateWebhookOutput) SetWebhook(v *Webhook) *CreateWebhookOutput { return s } -// Custom rewrite / redirect rule. +// Describes a custom rewrite or redirect rule. type CustomRule struct { _ struct{} `type:"structure"` - // The condition for a URL rewrite or redirect rule, e.g. country code. + // The condition for a URL rewrite or redirect rule, such as a country code. Condition *string `locationName:"condition" min:"1" type:"string"` // The source pattern for a URL rewrite or redirect rule. @@ -5166,11 +5157,11 @@ func (s *CustomRule) SetTarget(v string) *CustomRule { return s } -// Request structure for an Amplify App delete request. +// Describes the request structure for the delete app request. type DeleteAppInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` @@ -5208,12 +5199,12 @@ func (s *DeleteAppInput) SetAppId(v string) *DeleteAppInput { return s } -// Result structure for an Amplify App delete request. +// The result structure for the delete app request. type DeleteAppOutput struct { _ struct{} `type:"structure"` - // Amplify App represents different branches of a repository for building, deploying, - // and hosting. + // Represents the different branches of a repository for building, deploying, + // and hosting an Amplify app. // // App is a required field App *App `locationName:"app" type:"structure" required:"true"` @@ -5235,16 +5226,16 @@ func (s *DeleteAppOutput) SetApp(v *App) *DeleteAppOutput { return s } -// Request structure for delete backend environment request. +// The request structure for the delete backend environment request. type DeleteBackendEnvironmentInput struct { _ struct{} `type:"structure"` - // Unique Id of an Amplify App. + // The unique ID of an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name of a backend environment of an Amplify App. + // The name of a backend environment of an Amplify app. // // EnvironmentName is a required field EnvironmentName *string `location:"uri" locationName:"environmentName" min:"1" type:"string" required:"true"` @@ -5294,11 +5285,11 @@ func (s *DeleteBackendEnvironmentInput) SetEnvironmentName(v string) *DeleteBack return s } -// Result structure of a delete backend environment result. +// The result structure of the delete backend environment result. type DeleteBackendEnvironmentOutput struct { _ struct{} `type:"structure"` - // Backend environment structure for an Amplify App. + // Describes the backend environment for an Amplify app. // // BackendEnvironment is a required field BackendEnvironment *BackendEnvironment `locationName:"backendEnvironment" type:"structure" required:"true"` @@ -5320,16 +5311,16 @@ func (s *DeleteBackendEnvironmentOutput) SetBackendEnvironment(v *BackendEnviron return s } -// Request structure for delete branch request. +// The request structure for the delete branch request. type DeleteBranchInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for the branch. + // The name for the branch. // // BranchName is a required field BranchName *string `location:"uri" locationName:"branchName" min:"1" type:"string" required:"true"` @@ -5379,11 +5370,11 @@ func (s *DeleteBranchInput) SetBranchName(v string) *DeleteBranchInput { return s } -// Result structure for delete branch request. +// The result structure for the delete branch request. type DeleteBranchOutput struct { _ struct{} `type:"structure"` - // Branch structure for an Amplify App. + // The branch for an Amplify app, which maps to a third-party repository branch. // // Branch is a required field Branch *Branch `locationName:"branch" type:"structure" required:"true"` @@ -5405,16 +5396,16 @@ func (s *DeleteBranchOutput) SetBranch(v *Branch) *DeleteBranchOutput { return s } -// Request structure for the delete Domain Association request. +// The request structure for the delete domain association request. type DeleteDomainAssociationInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique id for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name of the domain. + // The name of the domain. // // DomainName is a required field DomainName *string `location:"uri" locationName:"domainName" type:"string" required:"true"` @@ -5467,8 +5458,8 @@ func (s *DeleteDomainAssociationInput) SetDomainName(v string) *DeleteDomainAsso type DeleteDomainAssociationOutput struct { _ struct{} `type:"structure"` - // Structure for Domain Association, which associates a custom domain with an - // Amplify App. + // Describes a domain association that associates a custom domain with an Amplify + // app. // // DomainAssociation is a required field DomainAssociation *DomainAssociation `locationName:"domainAssociation" type:"structure" required:"true"` @@ -5490,21 +5481,21 @@ func (s *DeleteDomainAssociationOutput) SetDomainAssociation(v *DomainAssociatio return s } -// Request structure for delete job request. +// The request structure for the delete job request. type DeleteJobInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for the branch, for the Job. + // The name for the branch, for the job. // // BranchName is a required field BranchName *string `location:"uri" locationName:"branchName" min:"1" type:"string" required:"true"` - // Unique Id for the Job. + // The unique ID for the job. // // JobId is a required field JobId *string `location:"uri" locationName:"jobId" type:"string" required:"true"` @@ -5566,11 +5557,11 @@ func (s *DeleteJobInput) SetJobId(v string) *DeleteJobInput { return s } -// Result structure for the delete job request. +// The result structure for the delete job request. type DeleteJobOutput struct { _ struct{} `type:"structure"` - // Structure for the summary of a Job. + // Describes the summary for an execution job for an Amplify app. // // JobSummary is a required field JobSummary *JobSummary `locationName:"jobSummary" type:"structure" required:"true"` @@ -5592,11 +5583,11 @@ func (s *DeleteJobOutput) SetJobSummary(v *JobSummary) *DeleteJobOutput { return s } -// Request structure for the delete webhook request. +// The request structure for the delete webhook request. type DeleteWebhookInput struct { _ struct{} `type:"structure"` - // Unique Id for a webhook. + // The unique ID for a webhook. // // WebhookId is a required field WebhookId *string `location:"uri" locationName:"webhookId" type:"string" required:"true"` @@ -5634,11 +5625,11 @@ func (s *DeleteWebhookInput) SetWebhookId(v string) *DeleteWebhookInput { return s } -// Result structure for the delete webhook request. +// The result structure for the delete webhook request. type DeleteWebhookOutput struct { _ struct{} `type:"structure"` - // Webhook structure. + // Describes a webhook that connects repository events to an Amplify app. // // Webhook is a required field Webhook *Webhook `locationName:"webhook" type:"structure" required:"true"` @@ -5660,8 +5651,7 @@ func (s *DeleteWebhookOutput) SetWebhook(v *Webhook) *DeleteWebhookOutput { return s } -// Exception thrown when an operation fails due to a dependent service throwing -// an exception. +// An operation failed because a dependent service threw an exception. type DependentServiceFailureException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -5717,40 +5707,47 @@ func (s *DependentServiceFailureException) RequestID() string { return s.RespMetadata.RequestID } -// Structure for Domain Association, which associates a custom domain with an -// Amplify App. +// Describes a domain association that associates a custom domain with an Amplify +// app. type DomainAssociation struct { _ struct{} `type:"structure"` - // DNS Record for certificate verification. + // Sets branch patterns for automatic subdomain creation. + AutoSubDomainCreationPatterns []*string `locationName:"autoSubDomainCreationPatterns" type:"list"` + + // The required AWS Identity and Access Management (IAM) service role for the + // Amazon Resource Name (ARN) for automatically creating subdomains. + AutoSubDomainIAMRole *string `locationName:"autoSubDomainIAMRole" type:"string"` + + // The DNS record for certificate verification. CertificateVerificationDNSRecord *string `locationName:"certificateVerificationDNSRecord" type:"string"` - // ARN for the Domain Association. + // The Amazon Resource Name (ARN) for the domain association. // // DomainAssociationArn is a required field DomainAssociationArn *string `locationName:"domainAssociationArn" type:"string" required:"true"` - // Name of the domain. + // The name of the domain. // // DomainName is a required field DomainName *string `locationName:"domainName" type:"string" required:"true"` - // Status fo the Domain Association. + // The current status of the domain association. // // DomainStatus is a required field DomainStatus *string `locationName:"domainStatus" type:"string" required:"true" enum:"DomainStatus"` - // Enables automated creation of Subdomains for branches. (Currently not supported) + // Enables the automated creation of subdomains for branches. // // EnableAutoSubDomain is a required field EnableAutoSubDomain *bool `locationName:"enableAutoSubDomain" type:"boolean" required:"true"` - // Reason for the current status of the Domain Association. + // The reason for the current status of the domain association. // // StatusReason is a required field StatusReason *string `locationName:"statusReason" type:"string" required:"true"` - // Subdomains for the Domain Association. + // The subdomains for the domain association. // // SubDomains is a required field SubDomains []*SubDomain `locationName:"subDomains" type:"list" required:"true"` @@ -5766,6 +5763,18 @@ func (s DomainAssociation) GoString() string { return s.String() } +// SetAutoSubDomainCreationPatterns sets the AutoSubDomainCreationPatterns field's value. +func (s *DomainAssociation) SetAutoSubDomainCreationPatterns(v []*string) *DomainAssociation { + s.AutoSubDomainCreationPatterns = v + return s +} + +// SetAutoSubDomainIAMRole sets the AutoSubDomainIAMRole field's value. +func (s *DomainAssociation) SetAutoSubDomainIAMRole(v string) *DomainAssociation { + s.AutoSubDomainIAMRole = &v + return s +} + // SetCertificateVerificationDNSRecord sets the CertificateVerificationDNSRecord field's value. func (s *DomainAssociation) SetCertificateVerificationDNSRecord(v string) *DomainAssociation { s.CertificateVerificationDNSRecord = &v @@ -5808,24 +5817,26 @@ func (s *DomainAssociation) SetSubDomains(v []*SubDomain) *DomainAssociation { return s } -// Request structure for the generate access logs request. +// The request structure for the generate access logs request. type GenerateAccessLogsInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name of the domain. + // The name of the domain. // // DomainName is a required field DomainName *string `locationName:"domainName" type:"string" required:"true"` - // The time at which the logs should end, inclusive. + // The time at which the logs should end. The time range specified is inclusive + // of the end time. EndTime *time.Time `locationName:"endTime" type:"timestamp"` - // The time at which the logs should start, inclusive. + // The time at which the logs should start. The time range specified is inclusive + // of the start time. StartTime *time.Time `locationName:"startTime" type:"timestamp"` } @@ -5882,11 +5893,11 @@ func (s *GenerateAccessLogsInput) SetStartTime(v time.Time) *GenerateAccessLogsI return s } -// Result structure for the generate access logs request. +// The result structure for the generate access logs request. type GenerateAccessLogsOutput struct { _ struct{} `type:"structure"` - // Pre-signed URL for the requested access logs. + // The pre-signed URL for the requested access logs. LogUrl *string `locationName:"logUrl" type:"string"` } @@ -5906,11 +5917,11 @@ func (s *GenerateAccessLogsOutput) SetLogUrl(v string) *GenerateAccessLogsOutput return s } -// Request structure for get App request. +// The request structure for the get app request. type GetAppInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` @@ -5951,8 +5962,8 @@ func (s *GetAppInput) SetAppId(v string) *GetAppInput { type GetAppOutput struct { _ struct{} `type:"structure"` - // Amplify App represents different branches of a repository for building, deploying, - // and hosting. + // Represents the different branches of a repository for building, deploying, + // and hosting an Amplify app. // // App is a required field App *App `locationName:"app" type:"structure" required:"true"` @@ -5974,11 +5985,11 @@ func (s *GetAppOutput) SetApp(v *App) *GetAppOutput { return s } -// Request structure for the get artifact request. +// Returns the request structure for the get artifact request. type GetArtifactUrlInput struct { _ struct{} `type:"structure"` - // Unique Id for a artifact. + // The unique ID for an artifact. // // ArtifactId is a required field ArtifactId *string `location:"uri" locationName:"artifactId" type:"string" required:"true"` @@ -6016,16 +6027,16 @@ func (s *GetArtifactUrlInput) SetArtifactId(v string) *GetArtifactUrlInput { return s } -// Result structure for the get artifact request. +// Returns the result structure for the get artifact request. type GetArtifactUrlOutput struct { _ struct{} `type:"structure"` - // Unique Id for a artifact. + // The unique ID for an artifact. // // ArtifactId is a required field ArtifactId *string `locationName:"artifactId" type:"string" required:"true"` - // Presigned url for the artifact. + // The presigned URL for the artifact. // // ArtifactUrl is a required field ArtifactUrl *string `locationName:"artifactUrl" type:"string" required:"true"` @@ -6053,16 +6064,16 @@ func (s *GetArtifactUrlOutput) SetArtifactUrl(v string) *GetArtifactUrlOutput { return s } -// Request structure for get backend environment request. +// The request structure for the get backend environment request. type GetBackendEnvironmentInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique id for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for the backend environment. + // The name for the backend environment. // // EnvironmentName is a required field EnvironmentName *string `location:"uri" locationName:"environmentName" min:"1" type:"string" required:"true"` @@ -6112,11 +6123,11 @@ func (s *GetBackendEnvironmentInput) SetEnvironmentName(v string) *GetBackendEnv return s } -// Result structure for get backend environment result. +// The result structure for the get backend environment result. type GetBackendEnvironmentOutput struct { _ struct{} `type:"structure"` - // Backend environment structure for an an Amplify App. + // Describes the backend environment for an Amplify app. // // BackendEnvironment is a required field BackendEnvironment *BackendEnvironment `locationName:"backendEnvironment" type:"structure" required:"true"` @@ -6138,16 +6149,16 @@ func (s *GetBackendEnvironmentOutput) SetBackendEnvironment(v *BackendEnvironmen return s } -// Request structure for get branch request. +// The request structure for the get branch request. type GetBranchInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for the branch. + // The name for the branch. // // BranchName is a required field BranchName *string `location:"uri" locationName:"branchName" min:"1" type:"string" required:"true"` @@ -6200,7 +6211,7 @@ func (s *GetBranchInput) SetBranchName(v string) *GetBranchInput { type GetBranchOutput struct { _ struct{} `type:"structure"` - // Branch for an Amplify App, which maps to a 3rd party repository branch. + // The branch for an Amplify app, which maps to a third-party repository branch. // // Branch is a required field Branch *Branch `locationName:"branch" type:"structure" required:"true"` @@ -6222,16 +6233,16 @@ func (s *GetBranchOutput) SetBranch(v *Branch) *GetBranchOutput { return s } -// Request structure for the get Domain Association request. +// The request structure for the get domain association request. type GetDomainAssociationInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique id for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name of the domain. + // The name of the domain. // // DomainName is a required field DomainName *string `location:"uri" locationName:"domainName" type:"string" required:"true"` @@ -6281,11 +6292,12 @@ func (s *GetDomainAssociationInput) SetDomainName(v string) *GetDomainAssociatio return s } -// Result structure for the get Domain Association request. +// The result structure for the get domain association request. type GetDomainAssociationOutput struct { _ struct{} `type:"structure"` - // Domain Association structure. + // Describes the structure of a domain association, which associates a custom + // domain with an Amplify app. // // DomainAssociation is a required field DomainAssociation *DomainAssociation `locationName:"domainAssociation" type:"structure" required:"true"` @@ -6307,21 +6319,21 @@ func (s *GetDomainAssociationOutput) SetDomainAssociation(v *DomainAssociation) return s } -// Request structure for get job request. +// The request structure for the get job request. type GetJobInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for the branch, for the Job. + // The branch name for the job. // // BranchName is a required field BranchName *string `location:"uri" locationName:"branchName" min:"1" type:"string" required:"true"` - // Unique Id for the Job. + // The unique ID for the job. // // JobId is a required field JobId *string `location:"uri" locationName:"jobId" type:"string" required:"true"` @@ -6386,7 +6398,7 @@ func (s *GetJobInput) SetJobId(v string) *GetJobInput { type GetJobOutput struct { _ struct{} `type:"structure"` - // Structure for an execution job for an Amplify App. + // Describes an execution job for an Amplify app. // // Job is a required field Job *Job `locationName:"job" type:"structure" required:"true"` @@ -6408,11 +6420,11 @@ func (s *GetJobOutput) SetJob(v *Job) *GetJobOutput { return s } -// Request structure for the get webhook request. +// The request structure for the get webhook request. type GetWebhookInput struct { _ struct{} `type:"structure"` - // Unique Id for a webhook. + // The unique ID for a webhook. // // WebhookId is a required field WebhookId *string `location:"uri" locationName:"webhookId" type:"string" required:"true"` @@ -6450,11 +6462,11 @@ func (s *GetWebhookInput) SetWebhookId(v string) *GetWebhookInput { return s } -// Result structure for the get webhook request. +// The result structure for the get webhook request. type GetWebhookOutput struct { _ struct{} `type:"structure"` - // Webhook structure. + // Describes the structure of a webhook. // // Webhook is a required field Webhook *Webhook `locationName:"webhook" type:"structure" required:"true"` @@ -6476,8 +6488,7 @@ func (s *GetWebhookOutput) SetWebhook(v *Webhook) *GetWebhookOutput { return s } -// Exception thrown when the service fails to perform an operation due to an -// internal issue. +// The service failed to perform an operation due to an internal issue. type InternalFailureException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -6533,16 +6544,16 @@ func (s *InternalFailureException) RequestID() string { return s.RespMetadata.RequestID } -// Structure for an execution job for an Amplify App. +// Describes an execution job for an Amplify app. type Job struct { _ struct{} `type:"structure"` - // Execution steps for an execution job, for an Amplify App. + // The execution steps for an execution job, for an Amplify app. // // Steps is a required field Steps []*Step `locationName:"steps" type:"list" required:"true"` - // Summary for an execution job for an Amplify App. + // Describes the summary for an execution job for an Amplify app. // // Summary is a required field Summary *JobSummary `locationName:"summary" type:"structure" required:"true"` @@ -6570,51 +6581,52 @@ func (s *Job) SetSummary(v *JobSummary) *Job { return s } -// Structure for the summary of a Job. +// Describes the summary for an execution job for an Amplify app. type JobSummary struct { _ struct{} `type:"structure"` - // Commit Id from 3rd party repository provider for the Job. + // The commit ID from a third-party repository provider for the job. // // CommitId is a required field CommitId *string `locationName:"commitId" type:"string" required:"true"` - // Commit message from 3rd party repository provider for the Job. + // The commit message from a third-party repository provider for the job. // // CommitMessage is a required field CommitMessage *string `locationName:"commitMessage" type:"string" required:"true"` - // Commit date / time for the Job. + // The commit date and time for the job. // // CommitTime is a required field CommitTime *time.Time `locationName:"commitTime" type:"timestamp" required:"true"` - // End date / time for the Job. + // The end date and time for the job. EndTime *time.Time `locationName:"endTime" type:"timestamp"` - // Arn for the Job. + // The Amazon Resource Name (ARN) for the job. // // JobArn is a required field JobArn *string `locationName:"jobArn" type:"string" required:"true"` - // Unique Id for the Job. + // The unique ID for the job. // // JobId is a required field JobId *string `locationName:"jobId" type:"string" required:"true"` - // Type for the Job. \n "RELEASE": Manually released from source by using StartJob - // API. "RETRY": Manually retried by using StartJob API. "WEB_HOOK": Automatically - // triggered by WebHooks. + // The type for the job. If the value is RELEASE, the job was manually released + // from its source by using the StartJob API. If the value is RETRY, the job + // was manually retried using the StartJob API. If the value is WEB_HOOK, the + // job was automatically triggered by webhooks. // // JobType is a required field JobType *string `locationName:"jobType" type:"string" required:"true" enum:"JobType"` - // Start date / time for the Job. + // The start date and time for the job. // // StartTime is a required field StartTime *time.Time `locationName:"startTime" type:"timestamp" required:"true"` - // Status for the Job. + // The current status for the job. // // Status is a required field Status *string `locationName:"status" type:"string" required:"true" enum:"JobStatus"` @@ -6684,8 +6696,7 @@ func (s *JobSummary) SetStatus(v string) *JobSummary { return s } -// Exception thrown when a resource could not be created because of service -// limits. +// A resource could not be created because service quotas were exceeded. type LimitExceededException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -6741,15 +6752,15 @@ func (s *LimitExceededException) RequestID() string { return s.RespMetadata.RequestID } -// Request structure for an Amplify App list request. +// The request structure for the list apps request. type ListAppsInput struct { _ struct{} `type:"structure"` - // Maximum number of records to list in a single response. + // The maximum number of records to list in a single response. MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` - // Pagination token. If non-null pagination token is returned in a result, then - // pass its value in another request to fetch more entries. + // A pagination token. If non-null, the pagination token is returned in a result. + // Pass its value in another request to retrieve more entries. NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } @@ -6788,18 +6799,18 @@ func (s *ListAppsInput) SetNextToken(v string) *ListAppsInput { return s } -// Result structure for an Amplify App list request. +// The result structure for an Amplify app list request. type ListAppsOutput struct { _ struct{} `type:"structure"` - // List of Amplify Apps. + // A list of Amplify apps. // // Apps is a required field Apps []*App `locationName:"apps" type:"list" required:"true"` - // Pagination token. Set to null to start listing Apps from start. If non-null - // pagination token is returned in a result, then pass its value in here to - // list more projects. + // A pagination token. Set to null to start listing apps from start. If non-null, + // the pagination token is returned in a result. Pass its value in here to list + // more projects. NextToken *string `locationName:"nextToken" type:"string"` } @@ -6825,31 +6836,31 @@ func (s *ListAppsOutput) SetNextToken(v string) *ListAppsOutput { return s } -// Request structure for the list artifacts request. +// Describes the request structure for the list artifacts request. type ListArtifactsInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for a branch, part of an Amplify App. + // The name of a branch that is part of an Amplify app. // // BranchName is a required field BranchName *string `location:"uri" locationName:"branchName" min:"1" type:"string" required:"true"` - // Unique Id for an Job. + // The unique ID for a job. // // JobId is a required field JobId *string `location:"uri" locationName:"jobId" type:"string" required:"true"` - // Maximum number of records to list in a single response. + // The maximum number of records to list in a single response. MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` - // Pagination token. Set to null to start listing artifacts from start. If non-null - // pagination token is returned in a result, then pass its value in here to - // list more artifacts. + // A pagination token. Set to null to start listing artifacts from start. If + // a non-null pagination token is returned in a result, pass its value in here + // to list more artifacts. NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } @@ -6924,17 +6935,17 @@ func (s *ListArtifactsInput) SetNextToken(v string) *ListArtifactsInput { return s } -// Result structure for the list artifacts request. +// The result structure for the list artifacts request. type ListArtifactsOutput struct { _ struct{} `type:"structure"` - // List of artifacts. + // A list of artifacts. // // Artifacts is a required field Artifacts []*Artifact `locationName:"artifacts" type:"list" required:"true"` - // Pagination token. If non-null pagination token is returned in a result, then - // pass its value in another request to fetch more entries. + // A pagination token. If a non-null pagination token is returned in a result, + // pass its value in another request to retrieve more entries. NextToken *string `locationName:"nextToken" type:"string"` } @@ -6960,24 +6971,24 @@ func (s *ListArtifactsOutput) SetNextToken(v string) *ListArtifactsOutput { return s } -// Request structure for list backend environments request. +// The request structure for the list backend environments request. type ListBackendEnvironmentsInput struct { _ struct{} `type:"structure"` - // Unique Id for an amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name of the backend environment - EnvironmentName *string `locationName:"environmentName" min:"1" type:"string"` + // The name of the backend environment + EnvironmentName *string `location:"querystring" locationName:"environmentName" min:"1" type:"string"` - // Maximum number of records to list in a single response. + // The maximum number of records to list in a single response. MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` - // Pagination token. Set to null to start listing backen environments from start. - // If a non-null pagination token is returned in a result, then pass its value - // in here to list more backend environments. + // A pagination token. Set to null to start listing backend environments from + // the start. If a non-null pagination token is returned in a result, pass its + // value in here to list more backend environments. NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } @@ -7037,17 +7048,17 @@ func (s *ListBackendEnvironmentsInput) SetNextToken(v string) *ListBackendEnviro return s } -// Result structure for list backend environments result. +// The result structure for the list backend environments result. type ListBackendEnvironmentsOutput struct { _ struct{} `type:"structure"` - // List of backend environments for an Amplify App. + // The list of backend environments for an Amplify app. // // BackendEnvironments is a required field BackendEnvironments []*BackendEnvironment `locationName:"backendEnvironments" type:"list" required:"true"` - // Pagination token. If non-null pagination token is returned in a result, then - // pass its value in another request to fetch more entries. + // A pagination token. If a non-null pagination token is returned in a result, + // pass its value in another request to retrieve more entries. NextToken *string `locationName:"nextToken" type:"string"` } @@ -7073,20 +7084,20 @@ func (s *ListBackendEnvironmentsOutput) SetNextToken(v string) *ListBackendEnvir return s } -// Request structure for list branches request. +// The request structure for the list branches request. type ListBranchesInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Maximum number of records to list in a single response. + // The maximum number of records to list in a single response. MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` - // Pagination token. Set to null to start listing branches from start. If a - // non-null pagination token is returned in a result, then pass its value in + // A pagination token. Set to null to start listing branches from the start. + // If a non-null pagination token is returned in a result, pass its value in // here to list more branches. NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } @@ -7138,17 +7149,17 @@ func (s *ListBranchesInput) SetNextToken(v string) *ListBranchesInput { return s } -// Result structure for list branches request. +// The result structure for the list branches request. type ListBranchesOutput struct { _ struct{} `type:"structure"` - // List of branches for an Amplify App. + // A list of branches for an Amplify app. // // Branches is a required field Branches []*Branch `locationName:"branches" type:"list" required:"true"` - // Pagination token. If non-null pagination token is returned in a result, then - // pass its value in another request to fetch more entries. + // A pagination token. If a non-null pagination token is returned in a result, + // pass its value in another request to retrieve more entries. NextToken *string `locationName:"nextToken" type:"string"` } @@ -7174,21 +7185,21 @@ func (s *ListBranchesOutput) SetNextToken(v string) *ListBranchesOutput { return s } -// Request structure for the list Domain Associations request. +// The request structure for the list domain associations request. type ListDomainAssociationsInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Maximum number of records to list in a single response. + // The maximum number of records to list in a single response. MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` - // Pagination token. Set to null to start listing Apps from start. If non-null - // pagination token is returned in a result, then pass its value in here to - // list more projects. + // A pagination token. Set to null to start listing apps from the start. If + // non-null, a pagination token is returned in a result. Pass its value in here + // to list more projects. NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } @@ -7239,17 +7250,17 @@ func (s *ListDomainAssociationsInput) SetNextToken(v string) *ListDomainAssociat return s } -// Result structure for the list Domain Association request. +// The result structure for the list domain association request. type ListDomainAssociationsOutput struct { _ struct{} `type:"structure"` - // List of Domain Associations. + // A list of domain associations. // // DomainAssociations is a required field DomainAssociations []*DomainAssociation `locationName:"domainAssociations" type:"list" required:"true"` - // Pagination token. If non-null pagination token is returned in a result, then - // pass its value in another request to fetch more entries. + // A pagination token. If non-null, a pagination token is returned in a result. + // Pass its value in another request to retrieve more entries. NextToken *string `locationName:"nextToken" type:"string"` } @@ -7275,26 +7286,26 @@ func (s *ListDomainAssociationsOutput) SetNextToken(v string) *ListDomainAssocia return s } -// Request structure for list job request. +// The request structure for the list jobs request. type ListJobsInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for a branch. + // The name for a branch. // // BranchName is a required field BranchName *string `location:"uri" locationName:"branchName" min:"1" type:"string" required:"true"` - // Maximum number of records to list in a single response. + // The maximum number of records to list in a single response. MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` - // Pagination token. Set to null to start listing steps from start. If a non-null - // pagination token is returned in a result, then pass its value in here to - // list more steps. + // A pagination token. Set to null to start listing steps from the start. If + // a non-null pagination token is returned in a result, pass its value in here + // to list more steps. NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } @@ -7357,17 +7368,17 @@ func (s *ListJobsInput) SetNextToken(v string) *ListJobsInput { return s } -// Maximum number of records to list in a single response. +// The maximum number of records to list in a single response. type ListJobsOutput struct { _ struct{} `type:"structure"` - // Result structure for list job result request. + // The result structure for the list job result request. // // JobSummaries is a required field JobSummaries []*JobSummary `locationName:"jobSummaries" type:"list" required:"true"` - // Pagination token. If non-null pagination token is returned in a result, then - // pass its value in another request to fetch more entries. + // A pagination token. If non-null the pagination token is returned in a result. + // Pass its value in another request to retrieve more entries. NextToken *string `locationName:"nextToken" type:"string"` } @@ -7393,11 +7404,11 @@ func (s *ListJobsOutput) SetNextToken(v string) *ListJobsOutput { return s } -// Request structure used to list tags for resource. +// The request structure to use to list tags for a resource. type ListTagsForResourceInput struct { _ struct{} `type:"structure"` - // Resource arn used to list tags. + // The Amazon Resource Name (ARN) to use to list tags. // // ResourceArn is a required field ResourceArn *string `location:"uri" locationName:"resourceArn" type:"string" required:"true"` @@ -7435,11 +7446,11 @@ func (s *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResource return s } -// Response for list tags. +// The response for the list tags for resource request. type ListTagsForResourceOutput struct { _ struct{} `type:"structure"` - // Tags result for response. + // A list of tags for the specified The Amazon Resource Name (ARN). Tags map[string]*string `locationName:"tags" min:"1" type:"map"` } @@ -7459,21 +7470,21 @@ func (s *ListTagsForResourceOutput) SetTags(v map[string]*string) *ListTagsForRe return s } -// Request structure for the list webhooks request. +// The request structure for the list webhooks request. type ListWebhooksInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Maximum number of records to list in a single response. + // The maximum number of records to list in a single response. MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` - // Pagination token. Set to null to start listing webhooks from start. If non-null - // pagination token is returned in a result, then pass its value in here to - // list more webhooks. + // A pagination token. Set to null to start listing webhooks from the start. + // If non-null,the pagination token is returned in a result. Pass its value + // in here to list more webhooks. NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } @@ -7524,15 +7535,15 @@ func (s *ListWebhooksInput) SetNextToken(v string) *ListWebhooksInput { return s } -// Result structure for the list webhooks request. +// The result structure for the list webhooks request. type ListWebhooksOutput struct { _ struct{} `type:"structure"` - // Pagination token. If non-null pagination token is returned in a result, then - // pass its value in another request to fetch more entries. + // A pagination token. If non-null, the pagination token is returned in a result. + // Pass its value in another request to retrieve more entries. NextToken *string `locationName:"nextToken" type:"string"` - // List of webhooks. + // A list of webhooks. // // Webhooks is a required field Webhooks []*Webhook `locationName:"webhooks" type:"list" required:"true"` @@ -7560,7 +7571,7 @@ func (s *ListWebhooksOutput) SetWebhooks(v []*Webhook) *ListWebhooksOutput { return s } -// Exception thrown when an entity has not been found during an operation. +// An entity was not found during an operation. type NotFoundException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -7616,20 +7627,20 @@ func (s *NotFoundException) RequestID() string { return s.RespMetadata.RequestID } -// Structure with Production Branch information. +// Describes the information about a production branch for an Amplify app. type ProductionBranch struct { _ struct{} `type:"structure"` - // Branch Name for Production Branch. + // The branch name for the production branch. BranchName *string `locationName:"branchName" min:"1" type:"string"` - // Last Deploy Time of Production Branch. + // The last deploy time of the production branch. LastDeployTime *time.Time `locationName:"lastDeployTime" type:"timestamp"` - // Status of Production Branch. + // The status of the production branch. Status *string `locationName:"status" min:"3" type:"string"` - // Thumbnail URL for Production Branch. + // The thumbnail URL for the production branch. ThumbnailUrl *string `locationName:"thumbnailUrl" min:"1" type:"string"` } @@ -7667,7 +7678,7 @@ func (s *ProductionBranch) SetThumbnailUrl(v string) *ProductionBranch { return s } -// Exception thrown when an operation fails due to non-existent resource. +// An operation failed due to a non-existent resource. type ResourceNotFoundException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -7725,26 +7736,26 @@ func (s *ResourceNotFoundException) RequestID() string { return s.RespMetadata.RequestID } -// Request structure for start a deployment. +// The request structure for the start a deployment request. type StartDeploymentInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for the branch, for the Job. + // The name for the branch, for the job. // // BranchName is a required field BranchName *string `location:"uri" locationName:"branchName" min:"1" type:"string" required:"true"` - // The job id for this deployment, generated by create deployment request. + // The job ID for this deployment, generated by the create deployment request. JobId *string `locationName:"jobId" type:"string"` - // The sourceUrl for this deployment, used when calling start deployment without - // create deployment. SourceUrl can be any HTTP GET url that is public accessible - // and downloads a single zip. + // The source URL for this deployment, used when calling start deployment without + // create deployment. The source URL can be any HTTP GET URL that is publicly + // accessible and downloads a single .zip file. SourceUrl *string `locationName:"sourceUrl" type:"string"` } @@ -7804,11 +7815,11 @@ func (s *StartDeploymentInput) SetSourceUrl(v string) *StartDeploymentInput { return s } -// Result structure for start a deployment. +// The result structure for the start a deployment request. type StartDeploymentOutput struct { _ struct{} `type:"structure"` - // Summary for the Job. + // The summary for the job. // // JobSummary is a required field JobSummary *JobSummary `locationName:"jobSummary" type:"structure" required:"true"` @@ -7830,39 +7841,40 @@ func (s *StartDeploymentOutput) SetJobSummary(v *JobSummary) *StartDeploymentOut return s } -// Request structure for Start job request. +// The request structure for the start job request. type StartJobInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for the branch, for the Job. + // The branch name for the job. // // BranchName is a required field BranchName *string `location:"uri" locationName:"branchName" min:"1" type:"string" required:"true"` - // Commit Id from 3rd party repository provider for the Job. + // The commit ID from a third-party repository provider for the job. CommitId *string `locationName:"commitId" type:"string"` - // Commit message from 3rd party repository provider for the Job. + // The commit message from a third-party repository provider for the job. CommitMessage *string `locationName:"commitMessage" type:"string"` - // Commit date / time for the Job. + // The commit date and time for the job. CommitTime *time.Time `locationName:"commitTime" type:"timestamp"` - // Unique Id for an existing job. Required for "RETRY" JobType. + // The unique ID for an existing job. This is required if the value of jobType + // is RETRY. JobId *string `locationName:"jobId" type:"string"` - // Descriptive reason for starting this job. + // A descriptive reason for starting this job. JobReason *string `locationName:"jobReason" type:"string"` - // Type for the Job. Available JobTypes are: \n "RELEASE": Start a new job with - // the latest change from the specified branch. Only available for apps that - // have connected to a repository. "RETRY": Retry an existing job. JobId is - // required for this type of job. + // Describes the type for the job. The job type RELEASE starts a new job with + // the latest change from the specified branch. This value is available only + // for apps that are connected to a repository. The job type RETRY retries an + // existing job. If the job type value is RETRY, the jobId is also required. // // JobType is a required field JobType *string `locationName:"jobType" type:"string" required:"true" enum:"JobType"` @@ -7951,11 +7963,11 @@ func (s *StartJobInput) SetJobType(v string) *StartJobInput { return s } -// Result structure for run job request. +// The result structure for the run job request. type StartJobOutput struct { _ struct{} `type:"structure"` - // Summary for the Job. + // The summary for the job. // // JobSummary is a required field JobSummary *JobSummary `locationName:"jobSummary" type:"structure" required:"true"` @@ -7977,49 +7989,49 @@ func (s *StartJobOutput) SetJobSummary(v *JobSummary) *StartJobOutput { return s } -// Structure for an execution step for an execution job, for an Amplify App. +// Describes an execution step, for an execution job, for an Amplify app. type Step struct { _ struct{} `type:"structure"` - // URL to the artifact for the execution step. + // The URL to the artifact for the execution step. ArtifactsUrl *string `locationName:"artifactsUrl" type:"string"` - // The context for current step, will include build image if step is build. + // The context for the current step. Includes a build image if the step is build. Context *string `locationName:"context" type:"string"` - // End date/ time of the execution step. + // The end date and time of the execution step. // // EndTime is a required field EndTime *time.Time `locationName:"endTime" type:"timestamp" required:"true"` - // URL to the logs for the execution step. + // The URL to the logs for the execution step. LogUrl *string `locationName:"logUrl" type:"string"` - // List of screenshot URLs for the execution step, if relevant. + // The list of screenshot URLs for the execution step, if relevant. Screenshots map[string]*string `locationName:"screenshots" type:"map"` - // Start date/ time of the execution step. + // The start date and time of the execution step. // // StartTime is a required field StartTime *time.Time `locationName:"startTime" type:"timestamp" required:"true"` - // Status of the execution step. + // The status of the execution step. // // Status is a required field Status *string `locationName:"status" type:"string" required:"true" enum:"JobStatus"` - // The reason for current step status. + // The reason for the current step status. StatusReason *string `locationName:"statusReason" type:"string"` - // Name of the execution step. + // The name of the execution step. // // StepName is a required field StepName *string `locationName:"stepName" type:"string" required:"true"` - // URL to the test artifact for the execution step. + // The URL to the test artifact for the execution step. TestArtifactsUrl *string `locationName:"testArtifactsUrl" type:"string"` - // URL to the test config for the execution step. + // The URL to the test configuration for the execution step. TestConfigUrl *string `locationName:"testConfigUrl" type:"string"` } @@ -8099,21 +8111,21 @@ func (s *Step) SetTestConfigUrl(v string) *Step { return s } -// Request structure for stop job request. +// The request structure for the stop job request. type StopJobInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name for the branch, for the Job. + // The name for the branch, for the job. // // BranchName is a required field BranchName *string `location:"uri" locationName:"branchName" min:"1" type:"string" required:"true"` - // Unique Id for the Job. + // The unique id for the job. // // JobId is a required field JobId *string `location:"uri" locationName:"jobId" type:"string" required:"true"` @@ -8175,11 +8187,11 @@ func (s *StopJobInput) SetJobId(v string) *StopJobInput { return s } -// Result structure for the stop job request. +// The result structure for the stop job request. type StopJobOutput struct { _ struct{} `type:"structure"` - // Summary for the Job. + // The summary for the job. // // JobSummary is a required field JobSummary *JobSummary `locationName:"jobSummary" type:"structure" required:"true"` @@ -8201,21 +8213,21 @@ func (s *StopJobOutput) SetJobSummary(v *JobSummary) *StopJobOutput { return s } -// Subdomain for the Domain Association. +// The subdomain for the domain association. type SubDomain struct { _ struct{} `type:"structure"` - // DNS record for the Subdomain. + // The DNS record for the subdomain. // // DnsRecord is a required field DnsRecord *string `locationName:"dnsRecord" type:"string" required:"true"` - // Setting structure for the Subdomain. + // Describes the settings for the subdomain. // // SubDomainSetting is a required field SubDomainSetting *SubDomainSetting `locationName:"subDomainSetting" type:"structure" required:"true"` - // Verified status of the Subdomain + // The verified status of the subdomain // // Verified is a required field Verified *bool `locationName:"verified" type:"boolean" required:"true"` @@ -8249,16 +8261,16 @@ func (s *SubDomain) SetVerified(v bool) *SubDomain { return s } -// Setting for the Subdomain. +// Describes the settings for the subdomain. type SubDomainSetting struct { _ struct{} `type:"structure"` - // Branch name setting for the Subdomain. + // The branch name setting for the subdomain. // // BranchName is a required field BranchName *string `locationName:"branchName" min:"1" type:"string" required:"true"` - // Prefix setting for the Subdomain. + // The prefix setting for the subdomain. // // Prefix is a required field Prefix *string `locationName:"prefix" type:"string" required:"true"` @@ -8305,16 +8317,16 @@ func (s *SubDomainSetting) SetPrefix(v string) *SubDomainSetting { return s } -// Request structure used to tag resource. +// The request structure to tag a resource with a tag key and value. type TagResourceInput struct { _ struct{} `type:"structure"` - // Resource arn used to tag resource. + // The Amazon Resource Name (ARN) to use to tag a resource. // // ResourceArn is a required field ResourceArn *string `location:"uri" locationName:"resourceArn" type:"string" required:"true"` - // Tags used to tag resource. + // The tags used to tag the resource. // // Tags is a required field Tags map[string]*string `locationName:"tags" min:"1" type:"map" required:"true"` @@ -8364,7 +8376,7 @@ func (s *TagResourceInput) SetTags(v map[string]*string) *TagResourceInput { return s } -// Response for tag resource. +// The response for the tag resource request. type TagResourceOutput struct { _ struct{} `type:"structure"` } @@ -8379,7 +8391,7 @@ func (s TagResourceOutput) GoString() string { return s.String() } -// Exception thrown when an operation fails due to a lack of access. +// An operation failed due to a lack of access. type UnauthorizedException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -8435,16 +8447,16 @@ func (s *UnauthorizedException) RequestID() string { return s.RespMetadata.RequestID } -// Request structure used to untag resource. +// The request structure for the untag resource request. type UntagResourceInput struct { _ struct{} `type:"structure"` - // Resource arn used to untag resource. + // The Amazon Resource Name (ARN) to use to untag a resource. // // ResourceArn is a required field ResourceArn *string `location:"uri" locationName:"resourceArn" type:"string" required:"true"` - // Tag keys used to untag resource. + // The tag keys to use to untag a resource. // // TagKeys is a required field TagKeys []*string `location:"querystring" locationName:"tagKeys" min:"1" type:"list" required:"true"` @@ -8494,7 +8506,7 @@ func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { return s } -// Response for untag resource. +// The response for the untag resource request. type UntagResourceOutput struct { _ struct{} `type:"structure"` } @@ -8509,63 +8521,70 @@ func (s UntagResourceOutput) GoString() string { return s.String() } -// Request structure for update App request. +// The request structure for the update app request. type UpdateAppInput struct { _ struct{} `type:"structure"` - // Personal Access token for 3rd party source control system for an Amplify - // App, used to create webhook and read-only deploy key. Token is not stored. - AccessToken *string `locationName:"accessToken" min:"1" type:"string"` + // The personal access token for a third-party source control system for an + // Amplify app. The token is used to create webhook and a read-only deploy key. + // The token is not stored. + AccessToken *string `locationName:"accessToken" min:"1" type:"string" sensitive:"true"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Automated branch creation branchConfig for the Amplify App. + // The automated branch creation configuration for the Amplify app. AutoBranchCreationConfig *AutoBranchCreationConfig `locationName:"autoBranchCreationConfig" type:"structure"` - // Automated branch creation glob patterns for the Amplify App. + // Describes the automated branch creation glob patterns for the Amplify app. AutoBranchCreationPatterns []*string `locationName:"autoBranchCreationPatterns" type:"list"` - // Basic Authorization credentials for an Amplify App. - BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string"` + // The basic authorization credentials for an Amplify app. + BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string" sensitive:"true"` - // BuildSpec for an Amplify App. + // The build specification (build spec) for an Amplify app. BuildSpec *string `locationName:"buildSpec" min:"1" type:"string"` - // Custom redirect / rewrite rules for an Amplify App. + // The custom redirect and rewrite rules for an Amplify app. CustomRules []*CustomRule `locationName:"customRules" type:"list"` - // Description for an Amplify App. + // The description for an Amplify app. Description *string `locationName:"description" type:"string"` - // Enables automated branch creation for the Amplify App. + // Enables automated branch creation for the Amplify app. EnableAutoBranchCreation *bool `locationName:"enableAutoBranchCreation" type:"boolean"` - // Enables Basic Authorization for an Amplify App. + // Enables basic authorization for an Amplify app. EnableBasicAuth *bool `locationName:"enableBasicAuth" type:"boolean"` - // Enables branch auto-building for an Amplify App. + // Enables branch auto-building for an Amplify app. EnableBranchAutoBuild *bool `locationName:"enableBranchAutoBuild" type:"boolean"` - // Environment Variables for an Amplify App. + // Automatically disconnects a branch in the Amplify Console when you delete + // a branch from your Git repository. + EnableBranchAutoDeletion *bool `locationName:"enableBranchAutoDeletion" type:"boolean"` + + // The environment variables for an Amplify app. EnvironmentVariables map[string]*string `locationName:"environmentVariables" type:"map"` - // IAM service role for an Amplify App. + // The AWS Identity and Access Management (IAM) service role for an Amplify + // app. IamServiceRoleArn *string `locationName:"iamServiceRoleArn" min:"1" type:"string"` - // Name for an Amplify App. + // The name for an Amplify app. Name *string `locationName:"name" min:"1" type:"string"` - // OAuth token for 3rd party source control system for an Amplify App, used - // to create webhook and read-only deploy key. OAuth token is not stored. - OauthToken *string `locationName:"oauthToken" type:"string"` + // The OAuth token for a third-party source control system for an Amplify app. + // The token is used to create a webhook and a read-only deploy key. The OAuth + // token is not stored. + OauthToken *string `locationName:"oauthToken" type:"string" sensitive:"true"` - // Platform for an Amplify App. + // The platform for an Amplify app. Platform *string `locationName:"platform" type:"string" enum:"Platform"` - // Repository for an Amplify App + // The name of the repository for an Amplify app Repository *string `locationName:"repository" type:"string"` } @@ -8688,6 +8707,12 @@ func (s *UpdateAppInput) SetEnableBranchAutoBuild(v bool) *UpdateAppInput { return s } +// SetEnableBranchAutoDeletion sets the EnableBranchAutoDeletion field's value. +func (s *UpdateAppInput) SetEnableBranchAutoDeletion(v bool) *UpdateAppInput { + s.EnableBranchAutoDeletion = &v + return s +} + // SetEnvironmentVariables sets the EnvironmentVariables field's value. func (s *UpdateAppInput) SetEnvironmentVariables(v map[string]*string) *UpdateAppInput { s.EnvironmentVariables = v @@ -8724,11 +8749,11 @@ func (s *UpdateAppInput) SetRepository(v string) *UpdateAppInput { return s } -// Result structure for an Amplify App update request. +// The result structure for an Amplify app update request. type UpdateAppOutput struct { _ struct{} `type:"structure"` - // App structure for the updated App. + // Represents the updated Amplify app. // // App is a required field App *App `locationName:"app" type:"structure" required:"true"` @@ -8750,60 +8775,61 @@ func (s *UpdateAppOutput) SetApp(v *App) *UpdateAppOutput { return s } -// Request structure for update branch request. +// The request structure for the update branch request. type UpdateBranchInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // ARN for a Backend Environment, part of an Amplify App. + // The Amazon Resource Name (ARN) for a backend environment that is part of + // an Amplify app. BackendEnvironmentArn *string `locationName:"backendEnvironmentArn" min:"1" type:"string"` - // Basic Authorization credentials for the branch. - BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string"` + // The basic authorization credentials for the branch. + BasicAuthCredentials *string `locationName:"basicAuthCredentials" type:"string" sensitive:"true"` - // Name for the branch. + // The name for the branch. // // BranchName is a required field BranchName *string `location:"uri" locationName:"branchName" min:"1" type:"string" required:"true"` - // BuildSpec for the branch. + // The build specification (build spec) for the branch. BuildSpec *string `locationName:"buildSpec" min:"1" type:"string"` - // Description for the branch. + // The description for the branch. Description *string `locationName:"description" type:"string"` - // Display name for a branch, will use as the default domain prefix. + // The display name for a branch. This is used as the default domain prefix. DisplayName *string `locationName:"displayName" type:"string"` // Enables auto building for the branch. EnableAutoBuild *bool `locationName:"enableAutoBuild" type:"boolean"` - // Enables Basic Auth for the branch. + // Enables basic authorization for the branch. EnableBasicAuth *bool `locationName:"enableBasicAuth" type:"boolean"` // Enables notifications for the branch. EnableNotification *bool `locationName:"enableNotification" type:"boolean"` - // Enables Pull Request Preview for this branch. + // Enables pull request preview for this branch. EnablePullRequestPreview *bool `locationName:"enablePullRequestPreview" type:"boolean"` - // Environment Variables for the branch. + // The environment variables for the branch. EnvironmentVariables map[string]*string `locationName:"environmentVariables" type:"map"` - // Framework for the branch. + // The framework for the branch. Framework *string `locationName:"framework" type:"string"` - // The Amplify Environment name for the pull request. + // The Amplify environment name for the pull request. PullRequestEnvironmentName *string `locationName:"pullRequestEnvironmentName" type:"string"` - // Stage for the branch. + // Describes the current stage for the branch. Stage *string `locationName:"stage" type:"string" enum:"Stage"` - // The content TTL for the website in seconds. + // The content Time to Live (TTL) for the website in seconds. Ttl *string `locationName:"ttl" type:"string"` } @@ -8941,11 +8967,11 @@ func (s *UpdateBranchInput) SetTtl(v string) *UpdateBranchInput { return s } -// Result structure for update branch request. +// The result structure for the update branch request. type UpdateBranchOutput struct { _ struct{} `type:"structure"` - // Branch structure for an Amplify App. + // The branch for an Amplify app, which maps to a third-party repository branch. // // Branch is a required field Branch *Branch `locationName:"branch" type:"structure" required:"true"` @@ -8967,24 +8993,31 @@ func (s *UpdateBranchOutput) SetBranch(v *Branch) *UpdateBranchOutput { return s } -// Request structure for update Domain Association request. +// The request structure for the update domain association request. type UpdateDomainAssociationInput struct { _ struct{} `type:"structure"` - // Unique Id for an Amplify App. + // The unique ID for an Amplify app. // // AppId is a required field AppId *string `location:"uri" locationName:"appId" min:"1" type:"string" required:"true"` - // Name of the domain. + // Sets the branch patterns for automatic subdomain creation. + AutoSubDomainCreationPatterns []*string `locationName:"autoSubDomainCreationPatterns" type:"list"` + + // The required AWS Identity and Access Management (IAM) service role for the + // Amazon Resource Name (ARN) for automatically creating subdomains. + AutoSubDomainIAMRole *string `locationName:"autoSubDomainIAMRole" type:"string"` + + // The name of the domain. // // DomainName is a required field DomainName *string `location:"uri" locationName:"domainName" type:"string" required:"true"` - // Enables automated creation of Subdomains for branches. (Currently not supported) + // Enables the automated creation of subdomains for branches. EnableAutoSubDomain *bool `locationName:"enableAutoSubDomain" type:"boolean"` - // Setting structure for the Subdomain. + // Describes the settings for the subdomain. // // SubDomainSettings is a required field SubDomainSettings []*SubDomainSetting `locationName:"subDomainSettings" type:"list" required:"true"` @@ -9041,6 +9074,18 @@ func (s *UpdateDomainAssociationInput) SetAppId(v string) *UpdateDomainAssociati return s } +// SetAutoSubDomainCreationPatterns sets the AutoSubDomainCreationPatterns field's value. +func (s *UpdateDomainAssociationInput) SetAutoSubDomainCreationPatterns(v []*string) *UpdateDomainAssociationInput { + s.AutoSubDomainCreationPatterns = v + return s +} + +// SetAutoSubDomainIAMRole sets the AutoSubDomainIAMRole field's value. +func (s *UpdateDomainAssociationInput) SetAutoSubDomainIAMRole(v string) *UpdateDomainAssociationInput { + s.AutoSubDomainIAMRole = &v + return s +} + // SetDomainName sets the DomainName field's value. func (s *UpdateDomainAssociationInput) SetDomainName(v string) *UpdateDomainAssociationInput { s.DomainName = &v @@ -9059,11 +9104,12 @@ func (s *UpdateDomainAssociationInput) SetSubDomainSettings(v []*SubDomainSettin return s } -// Result structure for the update Domain Association request. +// The result structure for the update domain association request. type UpdateDomainAssociationOutput struct { _ struct{} `type:"structure"` - // Domain Association structure. + // Describes a domain association, which associates a custom domain with an + // Amplify app. // // DomainAssociation is a required field DomainAssociation *DomainAssociation `locationName:"domainAssociation" type:"structure" required:"true"` @@ -9085,17 +9131,17 @@ func (s *UpdateDomainAssociationOutput) SetDomainAssociation(v *DomainAssociatio return s } -// Request structure for update webhook request. +// The request structure for the update webhook request. type UpdateWebhookInput struct { _ struct{} `type:"structure"` - // Name for a branch, part of an Amplify App. + // The name for a branch that is part of an Amplify app. BranchName *string `locationName:"branchName" min:"1" type:"string"` - // Description for a webhook. + // The description for a webhook. Description *string `locationName:"description" type:"string"` - // Unique Id for a webhook. + // The unique ID for a webhook. // // WebhookId is a required field WebhookId *string `location:"uri" locationName:"webhookId" type:"string" required:"true"` @@ -9148,11 +9194,11 @@ func (s *UpdateWebhookInput) SetWebhookId(v string) *UpdateWebhookInput { return s } -// Result structure for the update webhook request. +// The result structure for the update webhook request. type UpdateWebhookOutput struct { _ struct{} `type:"structure"` - // Webhook structure. + // Describes a webhook that connects repository events to an Amplify app. // // Webhook is a required field Webhook *Webhook `locationName:"webhook" type:"structure" required:"true"` @@ -9174,41 +9220,41 @@ func (s *UpdateWebhookOutput) SetWebhook(v *Webhook) *UpdateWebhookOutput { return s } -// Structure for webhook, which associates a webhook with an Amplify App. +// Describes a webhook that connects repository events to an Amplify app. type Webhook struct { _ struct{} `type:"structure"` - // Name for a branch, part of an Amplify App. + // The name for a branch that is part of an Amplify app. // // BranchName is a required field BranchName *string `locationName:"branchName" min:"1" type:"string" required:"true"` - // Create date / time for a webhook. + // The create date and time for a webhook. // // CreateTime is a required field CreateTime *time.Time `locationName:"createTime" type:"timestamp" required:"true"` - // Description for a webhook. + // The description for a webhook. // // Description is a required field Description *string `locationName:"description" type:"string" required:"true"` - // Update date / time for a webhook. + // Updates the date and time for a webhook. // // UpdateTime is a required field UpdateTime *time.Time `locationName:"updateTime" type:"timestamp" required:"true"` - // ARN for the webhook. + // The Amazon Resource Name (ARN) for the webhook. // // WebhookArn is a required field WebhookArn *string `locationName:"webhookArn" type:"string" required:"true"` - // Id of the webhook. + // The ID of the webhook. // // WebhookId is a required field WebhookId *string `locationName:"webhookId" type:"string" required:"true"` - // Url of the webhook. + // The URL of the webhook. // // WebhookUrl is a required field WebhookUrl *string `locationName:"webhookUrl" type:"string" required:"true"` @@ -9292,6 +9338,20 @@ const ( DomainStatusUpdating = "UPDATING" ) +// DomainStatus_Values returns all elements of the DomainStatus enum +func DomainStatus_Values() []string { + return []string{ + DomainStatusPendingVerification, + DomainStatusInProgress, + DomainStatusAvailable, + DomainStatusPendingDeployment, + DomainStatusFailed, + DomainStatusCreating, + DomainStatusRequestingCertificate, + DomainStatusUpdating, + } +} + const ( // JobStatusPending is a JobStatus enum value JobStatusPending = "PENDING" @@ -9315,6 +9375,19 @@ const ( JobStatusCancelled = "CANCELLED" ) +// JobStatus_Values returns all elements of the JobStatus enum +func JobStatus_Values() []string { + return []string{ + JobStatusPending, + JobStatusProvisioning, + JobStatusRunning, + JobStatusFailed, + JobStatusSucceed, + JobStatusCancelling, + JobStatusCancelled, + } +} + const ( // JobTypeRelease is a JobType enum value JobTypeRelease = "RELEASE" @@ -9329,11 +9402,28 @@ const ( JobTypeWebHook = "WEB_HOOK" ) +// JobType_Values returns all elements of the JobType enum +func JobType_Values() []string { + return []string{ + JobTypeRelease, + JobTypeRetry, + JobTypeManual, + JobTypeWebHook, + } +} + const ( // PlatformWeb is a Platform enum value PlatformWeb = "WEB" ) +// Platform_Values returns all elements of the Platform enum +func Platform_Values() []string { + return []string{ + PlatformWeb, + } +} + const ( // StageProduction is a Stage enum value StageProduction = "PRODUCTION" @@ -9350,3 +9440,14 @@ const ( // StagePullRequest is a Stage enum value StagePullRequest = "PULL_REQUEST" ) + +// Stage_Values returns all elements of the Stage enum +func Stage_Values() []string { + return []string{ + StageProduction, + StageBeta, + StageDevelopment, + StageExperimental, + StagePullRequest, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/amplify/doc.go b/vendor/github.com/aws/aws-sdk-go/service/amplify/doc.go index d00cb08ebab..e1395d3fd2f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/amplify/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/amplify/doc.go @@ -3,8 +3,13 @@ // Package amplify provides the client and types for making API // requests to AWS Amplify. // -// Amplify is a fully managed continuous deployment and hosting service for -// modern web apps. +// Amplify enables developers to develop and deploy cloud-powered mobile and +// web apps. The Amplify Console provides a continuous delivery and hosting +// service for web applications. For more information, see the Amplify Console +// User Guide (https://docs.aws.amazon.com/amplify/latest/userguide/welcome.html). +// The Amplify Framework is a comprehensive set of SDKs, libraries, tools, and +// documentation for client app development. For more information, see the Amplify +// Framework. (https://docs.amplify.aws/) // // See https://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25 for more information on this service. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/amplify/errors.go b/vendor/github.com/aws/aws-sdk-go/service/amplify/errors.go index 4e406d9ce46..f79cee8392f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/amplify/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/amplify/errors.go @@ -11,46 +11,43 @@ const ( // ErrCodeBadRequestException for service response error code // "BadRequestException". // - // Exception thrown when a request contains unexpected data. + // A request contains unexpected data. ErrCodeBadRequestException = "BadRequestException" // ErrCodeDependentServiceFailureException for service response error code // "DependentServiceFailureException". // - // Exception thrown when an operation fails due to a dependent service throwing - // an exception. + // An operation failed because a dependent service threw an exception. ErrCodeDependentServiceFailureException = "DependentServiceFailureException" // ErrCodeInternalFailureException for service response error code // "InternalFailureException". // - // Exception thrown when the service fails to perform an operation due to an - // internal issue. + // The service failed to perform an operation due to an internal issue. ErrCodeInternalFailureException = "InternalFailureException" // ErrCodeLimitExceededException for service response error code // "LimitExceededException". // - // Exception thrown when a resource could not be created because of service - // limits. + // A resource could not be created because service quotas were exceeded. ErrCodeLimitExceededException = "LimitExceededException" // ErrCodeNotFoundException for service response error code // "NotFoundException". // - // Exception thrown when an entity has not been found during an operation. + // An entity was not found during an operation. ErrCodeNotFoundException = "NotFoundException" // ErrCodeResourceNotFoundException for service response error code // "ResourceNotFoundException". // - // Exception thrown when an operation fails due to non-existent resource. + // An operation failed due to a non-existent resource. ErrCodeResourceNotFoundException = "ResourceNotFoundException" // ErrCodeUnauthorizedException for service response error code // "UnauthorizedException". // - // Exception thrown when an operation fails due to a lack of access. + // An operation failed due to a lack of access. ErrCodeUnauthorizedException = "UnauthorizedException" ) 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 15969f19078..835db5e32e9 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 @@ -19847,7 +19847,7 @@ type ImportRestApiInput struct { // [Required] The POST request body containing external API definitions. Currently, // only OpenAPI definition JSON/YAML files are supported. The maximum size of - // the API definition file is 2MB. + // the API definition file is 6MB. // // Body is a required field Body []byte `locationName:"body" type:"blob" required:"true"` @@ -19936,9 +19936,10 @@ type Integration struct { // Method requestParameters. CacheKeyParameters []*string `locationName:"cacheKeyParameters" type:"list"` - // An API-specific tag group of related cached parameters. To be valid values - // for cacheKeyParameters, these parameters must also be specified for Method - // requestParameters. + // Specifies a group of related cached parameters. By default, API Gateway uses + // the resource ID as the cacheNamespace. You can specify the same cacheNamespace + // across resources to return the same cached data for requests to different + // resources. CacheNamespace *string `locationName:"cacheNamespace" type:"string"` // The (id (https://docs.aws.amazon.com/apigateway/api-reference/resource/vpc-link/#id)) @@ -20043,6 +20044,9 @@ type Integration struct { // milliseconds or 29 seconds. TimeoutInMillis *int64 `locationName:"timeoutInMillis" type:"integer"` + // Specifies the TLS configuration for an integration. + TlsConfig *TlsConfig `locationName:"tlsConfig" type:"structure"` + // Specifies an API method integration type. The valid value is one of the following: // // * AWS: for integrating the API method request with an AWS service action, @@ -20178,6 +20182,12 @@ func (s *Integration) SetTimeoutInMillis(v int64) *Integration { return s } +// SetTlsConfig sets the TlsConfig field's value. +func (s *Integration) SetTlsConfig(v *TlsConfig) *Integration { + s.TlsConfig = v + return s +} + // SetType sets the Type field's value. func (s *Integration) SetType(v string) *Integration { s.Type = &v @@ -21192,10 +21202,15 @@ func (s *PutGatewayResponseInput) SetStatusCode(v string) *PutGatewayResponseInp type PutIntegrationInput struct { _ struct{} `type:"structure"` - // An API-specific tag group of related cached parameters. + // A list of request parameters whose values API Gateway caches. To be valid + // values for cacheKeyParameters, these parameters must also be specified for + // Method requestParameters. CacheKeyParameters []*string `locationName:"cacheKeyParameters" type:"list"` - // A list of request parameters whose values are to be cached. + // Specifies a group of related cached parameters. By default, API Gateway uses + // the resource ID as the cacheNamespace. You can specify the same cacheNamespace + // across resources to return the same cached data for requests to different + // resources. CacheNamespace *string `locationName:"cacheNamespace" type:"string"` // The (id (https://docs.aws.amazon.com/apigateway/api-reference/resource/vpc-link/#id)) @@ -21280,6 +21295,8 @@ type PutIntegrationInput struct { // milliseconds or 29 seconds. TimeoutInMillis *int64 `locationName:"timeoutInMillis" type:"integer"` + TlsConfig *TlsConfig `locationName:"tlsConfig" type:"structure"` + // [Required] Specifies a put integration input's type. // // Type is a required field @@ -21434,6 +21451,12 @@ func (s *PutIntegrationInput) SetTimeoutInMillis(v int64) *PutIntegrationInput { return s } +// SetTlsConfig sets the TlsConfig field's value. +func (s *PutIntegrationInput) SetTlsConfig(v *TlsConfig) *PutIntegrationInput { + s.TlsConfig = v + return s +} + // SetType sets the Type field's value. func (s *PutIntegrationInput) SetType(v string) *PutIntegrationInput { s.Type = &v @@ -21900,7 +21923,7 @@ type PutRestApiInput struct { // [Required] The PUT request body containing external API definitions. Currently, // only OpenAPI definition JSON/YAML files are supported. The maximum size of - // the API definition file is 2MB. + // the API definition file is 6MB. // // Body is a required field Body []byte `locationName:"body" type:"blob" required:"true"` @@ -23178,6 +23201,36 @@ func (s *ThrottleSettings) SetRateLimit(v float64) *ThrottleSettings { return s } +type TlsConfig struct { + _ struct{} `type:"structure"` + + // Specifies whether or not API Gateway skips verification that the certificate + // for an integration endpoint is issued by a supported certificate authority + // (https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-supported-certificate-authorities-for-http-endpoints.html). + // This isn’t recommended, but it enables you to use certificates that are + // signed by private certificate authorities, or certificates that are self-signed. + // If enabled, API Gateway still performs basic certificate validation, which + // includes checking the certificate's expiration date, hostname, and presence + // of a root certificate authority. Supported only for HTTP and HTTP_PROXY integrations. + InsecureSkipVerification *bool `locationName:"insecureSkipVerification" type:"boolean"` +} + +// String returns the string representation +func (s TlsConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TlsConfig) GoString() string { + return s.String() +} + +// SetInsecureSkipVerification sets the InsecureSkipVerification field's value. +func (s *TlsConfig) SetInsecureSkipVerification(v bool) *TlsConfig { + s.InsecureSkipVerification = &v + return s +} + // The request has reached its throttling limit. Retry after the specified time // period. type TooManyRequestsException struct { @@ -25403,11 +25456,26 @@ const ( ApiKeySourceTypeAuthorizer = "AUTHORIZER" ) +// ApiKeySourceType_Values returns all elements of the ApiKeySourceType enum +func ApiKeySourceType_Values() []string { + return []string{ + ApiKeySourceTypeHeader, + ApiKeySourceTypeAuthorizer, + } +} + const ( // ApiKeysFormatCsv is a ApiKeysFormat enum value ApiKeysFormatCsv = "csv" ) +// ApiKeysFormat_Values returns all elements of the ApiKeysFormat enum +func ApiKeysFormat_Values() []string { + return []string{ + ApiKeysFormatCsv, + } +} + // The authorizer type. Valid values are TOKEN for a Lambda function using a // single authorization token submitted in a custom header, REQUEST for a Lambda // function using incoming request parameters, and COGNITO_USER_POOLS for using @@ -25423,6 +25491,15 @@ const ( AuthorizerTypeCognitoUserPools = "COGNITO_USER_POOLS" ) +// AuthorizerType_Values returns all elements of the AuthorizerType enum +func AuthorizerType_Values() []string { + return []string{ + AuthorizerTypeToken, + AuthorizerTypeRequest, + AuthorizerTypeCognitoUserPools, + } +} + // Returns the size of the CacheCluster. const ( // CacheClusterSize05 is a CacheClusterSize enum value @@ -25450,6 +25527,20 @@ const ( CacheClusterSize237 = "237" ) +// CacheClusterSize_Values returns all elements of the CacheClusterSize enum +func CacheClusterSize_Values() []string { + return []string{ + CacheClusterSize05, + CacheClusterSize16, + CacheClusterSize61, + CacheClusterSize135, + CacheClusterSize284, + CacheClusterSize582, + CacheClusterSize118, + CacheClusterSize237, + } +} + // Returns the status of the CacheCluster. const ( // CacheClusterStatusCreateInProgress is a CacheClusterStatus enum value @@ -25468,6 +25559,17 @@ const ( CacheClusterStatusFlushInProgress = "FLUSH_IN_PROGRESS" ) +// CacheClusterStatus_Values returns all elements of the CacheClusterStatus enum +func CacheClusterStatus_Values() []string { + return []string{ + CacheClusterStatusCreateInProgress, + CacheClusterStatusAvailable, + CacheClusterStatusDeleteInProgress, + CacheClusterStatusNotAvailable, + CacheClusterStatusFlushInProgress, + } +} + const ( // ConnectionTypeInternet is a ConnectionType enum value ConnectionTypeInternet = "INTERNET" @@ -25476,6 +25578,14 @@ const ( ConnectionTypeVpcLink = "VPC_LINK" ) +// ConnectionType_Values returns all elements of the ConnectionType enum +func ConnectionType_Values() []string { + return []string{ + ConnectionTypeInternet, + ConnectionTypeVpcLink, + } +} + const ( // ContentHandlingStrategyConvertToBinary is a ContentHandlingStrategy enum value ContentHandlingStrategyConvertToBinary = "CONVERT_TO_BINARY" @@ -25484,6 +25594,14 @@ const ( ContentHandlingStrategyConvertToText = "CONVERT_TO_TEXT" ) +// ContentHandlingStrategy_Values returns all elements of the ContentHandlingStrategy enum +func ContentHandlingStrategy_Values() []string { + return []string{ + ContentHandlingStrategyConvertToBinary, + ContentHandlingStrategyConvertToText, + } +} + const ( // DocumentationPartTypeApi is a DocumentationPartType enum value DocumentationPartTypeApi = "API" @@ -25522,6 +25640,24 @@ const ( DocumentationPartTypeResponseBody = "RESPONSE_BODY" ) +// DocumentationPartType_Values returns all elements of the DocumentationPartType enum +func DocumentationPartType_Values() []string { + return []string{ + DocumentationPartTypeApi, + DocumentationPartTypeAuthorizer, + DocumentationPartTypeModel, + DocumentationPartTypeResource, + DocumentationPartTypeMethod, + DocumentationPartTypePathParameter, + DocumentationPartTypeQueryParameter, + DocumentationPartTypeRequestHeader, + DocumentationPartTypeRequestBody, + DocumentationPartTypeResponse, + DocumentationPartTypeResponseHeader, + DocumentationPartTypeResponseBody, + } +} + const ( // DomainNameStatusAvailable is a DomainNameStatus enum value DomainNameStatusAvailable = "AVAILABLE" @@ -25533,6 +25669,15 @@ const ( DomainNameStatusPending = "PENDING" ) +// DomainNameStatus_Values returns all elements of the DomainNameStatus enum +func DomainNameStatus_Values() []string { + return []string{ + DomainNameStatusAvailable, + DomainNameStatusUpdating, + DomainNameStatusPending, + } +} + // The endpoint type. The valid values are EDGE for edge-optimized API setup, // most suitable for mobile applications; REGIONAL for regional API endpoint // setup, most suitable for calling from AWS Region; and PRIVATE for private @@ -25548,6 +25693,15 @@ const ( EndpointTypePrivate = "PRIVATE" ) +// EndpointType_Values returns all elements of the EndpointType enum +func EndpointType_Values() []string { + return []string{ + EndpointTypeRegional, + EndpointTypeEdge, + EndpointTypePrivate, + } +} + const ( // GatewayResponseTypeDefault4xx is a GatewayResponseType enum value GatewayResponseTypeDefault4xx = "DEFAULT_4XX" @@ -25610,6 +25764,32 @@ const ( GatewayResponseTypeQuotaExceeded = "QUOTA_EXCEEDED" ) +// GatewayResponseType_Values returns all elements of the GatewayResponseType enum +func GatewayResponseType_Values() []string { + return []string{ + GatewayResponseTypeDefault4xx, + GatewayResponseTypeDefault5xx, + GatewayResponseTypeResourceNotFound, + GatewayResponseTypeUnauthorized, + GatewayResponseTypeInvalidApiKey, + GatewayResponseTypeAccessDenied, + GatewayResponseTypeAuthorizerFailure, + GatewayResponseTypeAuthorizerConfigurationError, + GatewayResponseTypeInvalidSignature, + GatewayResponseTypeExpiredToken, + GatewayResponseTypeMissingAuthenticationToken, + GatewayResponseTypeIntegrationFailure, + GatewayResponseTypeIntegrationTimeout, + GatewayResponseTypeApiConfigurationError, + GatewayResponseTypeUnsupportedMediaType, + GatewayResponseTypeBadRequestParameters, + GatewayResponseTypeBadRequestBody, + GatewayResponseTypeRequestTooLarge, + GatewayResponseTypeThrottled, + GatewayResponseTypeQuotaExceeded, + } +} + // The integration type. The valid value is HTTP for integrating an API method // with an HTTP backend; AWS with any AWS service endpoints; MOCK for testing // without actually invoking the backend; HTTP_PROXY for integrating with the @@ -25631,6 +25811,17 @@ const ( IntegrationTypeAwsProxy = "AWS_PROXY" ) +// IntegrationType_Values returns all elements of the IntegrationType enum +func IntegrationType_Values() []string { + return []string{ + IntegrationTypeHttp, + IntegrationTypeAws, + IntegrationTypeMock, + IntegrationTypeHttpProxy, + IntegrationTypeAwsProxy, + } +} + const ( // LocationStatusTypeDocumented is a LocationStatusType enum value LocationStatusTypeDocumented = "DOCUMENTED" @@ -25639,6 +25830,14 @@ const ( LocationStatusTypeUndocumented = "UNDOCUMENTED" ) +// LocationStatusType_Values returns all elements of the LocationStatusType enum +func LocationStatusType_Values() []string { + return []string{ + LocationStatusTypeDocumented, + LocationStatusTypeUndocumented, + } +} + const ( // OpAdd is a Op enum value OpAdd = "add" @@ -25659,6 +25858,18 @@ const ( OpTest = "test" ) +// Op_Values returns all elements of the Op enum +func Op_Values() []string { + return []string{ + OpAdd, + OpRemove, + OpReplace, + OpMove, + OpCopy, + OpTest, + } +} + const ( // PutModeMerge is a PutMode enum value PutModeMerge = "merge" @@ -25667,6 +25878,14 @@ const ( PutModeOverwrite = "overwrite" ) +// PutMode_Values returns all elements of the PutMode enum +func PutMode_Values() []string { + return []string{ + PutModeMerge, + PutModeOverwrite, + } +} + const ( // QuotaPeriodTypeDay is a QuotaPeriodType enum value QuotaPeriodTypeDay = "DAY" @@ -25678,6 +25897,15 @@ const ( QuotaPeriodTypeMonth = "MONTH" ) +// QuotaPeriodType_Values returns all elements of the QuotaPeriodType enum +func QuotaPeriodType_Values() []string { + return []string{ + QuotaPeriodTypeDay, + QuotaPeriodTypeWeek, + QuotaPeriodTypeMonth, + } +} + const ( // SecurityPolicyTls10 is a SecurityPolicy enum value SecurityPolicyTls10 = "TLS_1_0" @@ -25686,6 +25914,14 @@ const ( SecurityPolicyTls12 = "TLS_1_2" ) +// SecurityPolicy_Values returns all elements of the SecurityPolicy enum +func SecurityPolicy_Values() []string { + return []string{ + SecurityPolicyTls10, + SecurityPolicyTls12, + } +} + const ( // UnauthorizedCacheControlHeaderStrategyFailWith403 is a UnauthorizedCacheControlHeaderStrategy enum value UnauthorizedCacheControlHeaderStrategyFailWith403 = "FAIL_WITH_403" @@ -25697,6 +25933,15 @@ const ( UnauthorizedCacheControlHeaderStrategySucceedWithoutResponseHeader = "SUCCEED_WITHOUT_RESPONSE_HEADER" ) +// UnauthorizedCacheControlHeaderStrategy_Values returns all elements of the UnauthorizedCacheControlHeaderStrategy enum +func UnauthorizedCacheControlHeaderStrategy_Values() []string { + return []string{ + UnauthorizedCacheControlHeaderStrategyFailWith403, + UnauthorizedCacheControlHeaderStrategySucceedWithResponseHeader, + UnauthorizedCacheControlHeaderStrategySucceedWithoutResponseHeader, + } +} + const ( // VpcLinkStatusAvailable is a VpcLinkStatus enum value VpcLinkStatusAvailable = "AVAILABLE" @@ -25710,3 +25955,13 @@ const ( // VpcLinkStatusFailed is a VpcLinkStatus enum value VpcLinkStatusFailed = "FAILED" ) + +// VpcLinkStatus_Values returns all elements of the VpcLinkStatus enum +func VpcLinkStatus_Values() []string { + return []string{ + VpcLinkStatusAvailable, + VpcLinkStatusPending, + VpcLinkStatusDeleting, + VpcLinkStatusFailed, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/apigatewayv2/api.go b/vendor/github.com/aws/aws-sdk-go/service/apigatewayv2/api.go index f191a64b8a1..6077267c78e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/apigatewayv2/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/apigatewayv2/api.go @@ -18128,6 +18128,16 @@ const ( AuthorizationTypeJwt = "JWT" ) +// AuthorizationType_Values returns all elements of the AuthorizationType enum +func AuthorizationType_Values() []string { + return []string{ + AuthorizationTypeNone, + AuthorizationTypeAwsIam, + AuthorizationTypeCustom, + AuthorizationTypeJwt, + } +} + // The authorizer type. For WebSocket APIs, specify REQUEST for a Lambda function // using incoming request parameters. For HTTP APIs, specify JWT to use JSON // Web Tokens. @@ -18139,6 +18149,14 @@ const ( AuthorizerTypeJwt = "JWT" ) +// AuthorizerType_Values returns all elements of the AuthorizerType enum +func AuthorizerType_Values() []string { + return []string{ + AuthorizerTypeRequest, + AuthorizerTypeJwt, + } +} + // Represents a connection type. const ( // ConnectionTypeInternet is a ConnectionType enum value @@ -18148,6 +18166,14 @@ const ( ConnectionTypeVpcLink = "VPC_LINK" ) +// ConnectionType_Values returns all elements of the ConnectionType enum +func ConnectionType_Values() []string { + return []string{ + ConnectionTypeInternet, + ConnectionTypeVpcLink, + } +} + // Specifies how to handle response payload content type conversions. Supported // only for WebSocket APIs. const ( @@ -18158,6 +18184,14 @@ const ( ContentHandlingStrategyConvertToText = "CONVERT_TO_TEXT" ) +// ContentHandlingStrategy_Values returns all elements of the ContentHandlingStrategy enum +func ContentHandlingStrategy_Values() []string { + return []string{ + ContentHandlingStrategyConvertToBinary, + ContentHandlingStrategyConvertToText, + } +} + // Represents a deployment status. const ( // DeploymentStatusPending is a DeploymentStatus enum value @@ -18170,6 +18204,15 @@ const ( DeploymentStatusDeployed = "DEPLOYED" ) +// DeploymentStatus_Values returns all elements of the DeploymentStatus enum +func DeploymentStatus_Values() []string { + return []string{ + DeploymentStatusPending, + DeploymentStatusFailed, + DeploymentStatusDeployed, + } +} + // The status of the domain name migration. The valid values are AVAILABLE and // UPDATING. If the status is UPDATING, the domain cannot be modified further // until the existing operation is complete. If it is AVAILABLE, the domain @@ -18182,6 +18225,14 @@ const ( DomainNameStatusUpdating = "UPDATING" ) +// DomainNameStatus_Values returns all elements of the DomainNameStatus enum +func DomainNameStatus_Values() []string { + return []string{ + DomainNameStatusAvailable, + DomainNameStatusUpdating, + } +} + // Represents an endpoint type. const ( // EndpointTypeRegional is a EndpointType enum value @@ -18191,6 +18242,14 @@ const ( EndpointTypeEdge = "EDGE" ) +// EndpointType_Values returns all elements of the EndpointType enum +func EndpointType_Values() []string { + return []string{ + EndpointTypeRegional, + EndpointTypeEdge, + } +} + // Represents an API method integration type. const ( // IntegrationTypeAws is a IntegrationType enum value @@ -18209,6 +18268,17 @@ const ( IntegrationTypeAwsProxy = "AWS_PROXY" ) +// IntegrationType_Values returns all elements of the IntegrationType enum +func IntegrationType_Values() []string { + return []string{ + IntegrationTypeAws, + IntegrationTypeHttp, + IntegrationTypeMock, + IntegrationTypeHttpProxy, + IntegrationTypeAwsProxy, + } +} + // The logging level. const ( // LoggingLevelError is a LoggingLevel enum value @@ -18221,6 +18291,15 @@ const ( LoggingLevelOff = "OFF" ) +// LoggingLevel_Values returns all elements of the LoggingLevel enum +func LoggingLevel_Values() []string { + return []string{ + LoggingLevelError, + LoggingLevelInfo, + LoggingLevelOff, + } +} + // Represents passthrough behavior for an integration response. Supported only // for WebSocket APIs. const ( @@ -18234,6 +18313,15 @@ const ( PassthroughBehaviorWhenNoTemplates = "WHEN_NO_TEMPLATES" ) +// PassthroughBehavior_Values returns all elements of the PassthroughBehavior enum +func PassthroughBehavior_Values() []string { + return []string{ + PassthroughBehaviorWhenNoMatch, + PassthroughBehaviorNever, + PassthroughBehaviorWhenNoTemplates, + } +} + // Represents a protocol type. const ( // ProtocolTypeWebsocket is a ProtocolType enum value @@ -18243,6 +18331,14 @@ const ( ProtocolTypeHttp = "HTTP" ) +// ProtocolType_Values returns all elements of the ProtocolType enum +func ProtocolType_Values() []string { + return []string{ + ProtocolTypeWebsocket, + ProtocolTypeHttp, + } +} + // The Transport Layer Security (TLS) version of the security policy for this // domain name. The valid values are TLS_1_0 and TLS_1_2. const ( @@ -18253,6 +18349,14 @@ const ( SecurityPolicyTls12 = "TLS_1_2" ) +// SecurityPolicy_Values returns all elements of the SecurityPolicy enum +func SecurityPolicy_Values() []string { + return []string{ + SecurityPolicyTls10, + SecurityPolicyTls12, + } +} + // The status of the VPC link. const ( // VpcLinkStatusPending is a VpcLinkStatus enum value @@ -18271,8 +18375,26 @@ const ( VpcLinkStatusInactive = "INACTIVE" ) +// VpcLinkStatus_Values returns all elements of the VpcLinkStatus enum +func VpcLinkStatus_Values() []string { + return []string{ + VpcLinkStatusPending, + VpcLinkStatusAvailable, + VpcLinkStatusDeleting, + VpcLinkStatusFailed, + VpcLinkStatusInactive, + } +} + // The version of the VPC link. const ( // VpcLinkVersionV2 is a VpcLinkVersion enum value VpcLinkVersionV2 = "V2" ) + +// VpcLinkVersion_Values returns all elements of the VpcLinkVersion enum +func VpcLinkVersion_Values() []string { + return []string{ + VpcLinkVersionV2, + } +} 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 a4cce2c0b42..df23d218c7f 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 @@ -998,6 +998,14 @@ func (c *ApplicationAutoScaling) PutScalingPolicyRequest(input *PutScalingPolicy // uses the policy with the highest calculated capacity (200% of 10 = 20) and // scales out to 30. // +// We recommend caution, however, when using target tracking scaling policies +// with step scaling policies because conflicts between these policies can cause +// undesirable behavior. For example, if the step scaling policy initiates a +// scale-in activity before the target tracking policy is ready to scale in, +// the scale-in activity will not be blocked. After the scale-in activity completes, +// the target tracking policy could instruct the scalable target to scale out +// again. +// // For more information, see Target Tracking Scaling Policies (https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html) // and Step Scaling Policies (https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html) // in the Application Auto Scaling User Guide. @@ -3267,7 +3275,9 @@ type PredefinedMetricSpecification struct { // a resource label unless the metric type is ALBRequestCountPerTarget and there // is a target group attached to the Spot Fleet request or ECS service. // - // The format is app///targetgroup//, + // Elastic Load Balancing sends data about your load balancers to Amazon CloudWatch. + // CloudWatch collects the data and specifies the format to use to access the + // data. The format is app///targetgroup//, // where: // // * app// is the final portion of @@ -3275,6 +3285,12 @@ type PredefinedMetricSpecification struct { // // * targetgroup// is the final portion // of the target group ARN. + // + // To find the ARN for an Application Load Balancer, use the DescribeLoadBalancers + // (https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeLoadBalancers.html) + // API operation. To find the ARN for the target group, use the DescribeTargetGroups + // (https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeTargetGroups.html) + // API operation. ResourceLabel *string `min:"1" type:"string"` } @@ -3332,7 +3348,7 @@ type PutScalingPolicyInput struct { // TargetTrackingScaling—Not supported for Amazon EMR // // StepScaling—Not supported for DynamoDB, Amazon Comprehend, Lambda, or Amazon - // Keyspaces for Apache Cassandra. + // Keyspaces (for Apache Cassandra). // // For more information, see Target Tracking Scaling Policies (https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html) // and Step Scaling Policies (https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html) @@ -3846,8 +3862,10 @@ type RegisterScalableTargetInput struct { // the minimum capacity limit in response to changing demand. // // This parameter is required if you are registering a scalable target. For - // Lambda provisioned concurrency, the minimum value allowed is 0. For all other - // resources, the minimum value allowed is 1. + // certain resources, the minimum value allowed is 0. This includes Lambda provisioned + // concurrency, Spot Fleet, ECS services, Aurora DB clusters, EMR clusters, + // and custom resources. For all other resources, the minimum value allowed + // is 1. MinCapacity *int64 `type:"integer"` // The identifier of the resource that is associated with the scalable target. @@ -4084,12 +4102,12 @@ type ScalableTarget struct { // CreationTime is a required field CreationTime *time.Time `type:"timestamp" required:"true"` - // The maximum value to scale to in response to a scale-out event. + // The maximum value to scale to in response to a scale-out activity. // // MaxCapacity is a required field MaxCapacity *int64 `type:"integer" required:"true"` - // The minimum value to scale to in response to a scale-in event. + // The minimum value to scale to in response to a scale-in activity. // // MinCapacity is a required field MinCapacity *int64 `type:"integer" required:"true"` @@ -5062,27 +5080,27 @@ type StepScalingPolicyConfiguration struct { // AdjustmentType is required if you are adding a new step scaling policy configuration. AdjustmentType *string `type:"string" enum:"AdjustmentType"` - // The amount of time, in seconds, after a scaling activity completes where - // previous trigger-related scaling activities can influence future scaling - // events. - // - // For scale-out policies, while the cooldown period is in effect, the capacity - // that has been added by the previous scale-out action that initiated the cooldown - // is calculated as part of the desired capacity for the next scale out. The - // intention is to continuously (but not excessively) scale out. For example, - // an alarm triggers a step scaling policy to scale out an Amazon ECS service - // by 2 tasks, the scaling activity completes successfully, and a cooldown period - // of 5 minutes starts. During the cooldown period, if the alarm triggers the - // same policy again but at a more aggressive step adjustment to scale out the - // service by 3 tasks, the 2 tasks that were added in the previous scale-out - // action are considered part of that capacity and only 1 additional task is - // added to the desired count. - // - // For scale-in policies, the cooldown period is used to block subsequent scale-in - // requests until it has expired. The intention is to scale in conservatively - // to protect your application's availability. However, if another alarm triggers - // a scale-out policy during the cooldown period after a scale-in, Application - // Auto Scaling scales out your scalable target immediately. + // The amount of time, in seconds, to wait for a previous scaling activity to + // take effect. + // + // With scale-out policies, the intention is to continuously (but not excessively) + // scale out. After Application Auto Scaling successfully scales out using a + // step scaling policy, it starts to calculate the cooldown time. While the + // cooldown period is in effect, capacity added by the initiating scale-out + // activity is calculated as part of the desired capacity for the next scale-out + // activity. For example, when an alarm triggers a step scaling policy to increase + // the capacity by 2, the scaling activity completes successfully, and a cooldown + // period starts. If the alarm triggers again during the cooldown period but + // at a more aggressive step adjustment of 3, the previous increase of 2 is + // considered part of the current capacity. Therefore, only 1 is added to the + // capacity. + // + // With scale-in policies, the intention is to scale in conservatively to protect + // your application’s availability, so scale-in activities are blocked until + // the cooldown period has expired. However, if another alarm triggers a scale-out + // activity during the cooldown period after a scale-in activity, Application + // Auto Scaling scales out the target immediately. In this case, the cooldown + // period for the scale-in activity stops and doesn't complete. // // Application Auto Scaling provides a default value of 300 for the following // scalable targets: @@ -5267,13 +5285,14 @@ type TargetTrackingScalingPolicyConfiguration struct { PredefinedMetricSpecification *PredefinedMetricSpecification `type:"structure"` // The amount of time, in seconds, after a scale-in activity completes before - // another scale in activity can start. + // another scale-in activity can start. // - // The cooldown period is used to block subsequent scale-in requests until it - // has expired. The intention is to scale in conservatively to protect your - // application's availability. However, if another alarm triggers a scale-out - // policy during the cooldown period after a scale-in, Application Auto Scaling - // scales out your scalable target immediately. + // With the scale-in cooldown period, the intention is to scale in conservatively + // to protect your application’s availability, so scale-in activities are + // blocked until the cooldown period has expired. However, if another alarm + // triggers a scale-out activity during the scale-in cooldown period, Application + // Auto Scaling scales out the target immediately. In this case, the scale-in + // cooldown period stops and doesn't complete. // // Application Auto Scaling provides a default value of 300 for the following // scalable targets: @@ -5305,13 +5324,15 @@ type TargetTrackingScalingPolicyConfiguration struct { // * Amazon Keyspaces tables ScaleInCooldown *int64 `type:"integer"` - // The amount of time, in seconds, after a scale-out activity completes before - // another scale-out activity can start. + // The amount of time, in seconds, to wait for a previous scale-out activity + // to take effect. // - // While the cooldown period is in effect, the capacity that has been added - // by the previous scale-out action that initiated the cooldown is calculated - // as part of the desired capacity for the next scale out. The intention is - // to continuously (but not excessively) scale out. + // With the scale-out cooldown period, the intention is to continuously (but + // not excessively) scale out. After Application Auto Scaling successfully scales + // out using a target tracking scaling policy, it starts to calculate the cooldown + // time. While the scale-out cooldown period is in effect, the capacity added + // by the initiating scale-out activity is calculated as part of the desired + // capacity for the next scale-out activity. // // Application Auto Scaling provides a default value of 300 for the following // scalable targets: @@ -5487,6 +5508,15 @@ const ( AdjustmentTypeExactCapacity = "ExactCapacity" ) +// AdjustmentType_Values returns all elements of the AdjustmentType enum +func AdjustmentType_Values() []string { + return []string{ + AdjustmentTypeChangeInCapacity, + AdjustmentTypePercentChangeInCapacity, + AdjustmentTypeExactCapacity, + } +} + const ( // MetricAggregationTypeAverage is a MetricAggregationType enum value MetricAggregationTypeAverage = "Average" @@ -5498,6 +5528,15 @@ const ( MetricAggregationTypeMaximum = "Maximum" ) +// MetricAggregationType_Values returns all elements of the MetricAggregationType enum +func MetricAggregationType_Values() []string { + return []string{ + MetricAggregationTypeAverage, + MetricAggregationTypeMinimum, + MetricAggregationTypeMaximum, + } +} + const ( // MetricStatisticAverage is a MetricStatistic enum value MetricStatisticAverage = "Average" @@ -5515,6 +5554,17 @@ const ( MetricStatisticSum = "Sum" ) +// MetricStatistic_Values returns all elements of the MetricStatistic enum +func MetricStatistic_Values() []string { + return []string{ + MetricStatisticAverage, + MetricStatisticMinimum, + MetricStatisticMaximum, + MetricStatisticSampleCount, + MetricStatisticSum, + } +} + const ( // MetricTypeDynamoDbreadCapacityUtilization is a MetricType enum value MetricTypeDynamoDbreadCapacityUtilization = "DynamoDBReadCapacityUtilization" @@ -5565,6 +5615,28 @@ const ( MetricTypeCassandraWriteCapacityUtilization = "CassandraWriteCapacityUtilization" ) +// MetricType_Values returns all elements of the MetricType enum +func MetricType_Values() []string { + return []string{ + MetricTypeDynamoDbreadCapacityUtilization, + MetricTypeDynamoDbwriteCapacityUtilization, + MetricTypeAlbrequestCountPerTarget, + MetricTypeRdsreaderAverageCpuutilization, + MetricTypeRdsreaderAverageDatabaseConnections, + MetricTypeEc2spotFleetRequestAverageCpuutilization, + MetricTypeEc2spotFleetRequestAverageNetworkIn, + MetricTypeEc2spotFleetRequestAverageNetworkOut, + MetricTypeSageMakerVariantInvocationsPerInstance, + MetricTypeEcsserviceAverageCpuutilization, + MetricTypeEcsserviceAverageMemoryUtilization, + MetricTypeAppStreamAverageCapacityUtilization, + MetricTypeComprehendInferenceUtilization, + MetricTypeLambdaProvisionedConcurrencyUtilization, + MetricTypeCassandraReadCapacityUtilization, + MetricTypeCassandraWriteCapacityUtilization, + } +} + const ( // PolicyTypeStepScaling is a PolicyType enum value PolicyTypeStepScaling = "StepScaling" @@ -5573,6 +5645,14 @@ const ( PolicyTypeTargetTrackingScaling = "TargetTrackingScaling" ) +// PolicyType_Values returns all elements of the PolicyType enum +func PolicyType_Values() []string { + return []string{ + PolicyTypeStepScaling, + PolicyTypeTargetTrackingScaling, + } +} + const ( // ScalableDimensionEcsServiceDesiredCount is a ScalableDimension enum value ScalableDimensionEcsServiceDesiredCount = "ecs:service:DesiredCount" @@ -5620,6 +5700,27 @@ const ( ScalableDimensionCassandraTableWriteCapacityUnits = "cassandra:table:WriteCapacityUnits" ) +// ScalableDimension_Values returns all elements of the ScalableDimension enum +func ScalableDimension_Values() []string { + return []string{ + ScalableDimensionEcsServiceDesiredCount, + ScalableDimensionEc2SpotFleetRequestTargetCapacity, + ScalableDimensionElasticmapreduceInstancegroupInstanceCount, + ScalableDimensionAppstreamFleetDesiredCapacity, + ScalableDimensionDynamodbTableReadCapacityUnits, + ScalableDimensionDynamodbTableWriteCapacityUnits, + ScalableDimensionDynamodbIndexReadCapacityUnits, + ScalableDimensionDynamodbIndexWriteCapacityUnits, + ScalableDimensionRdsClusterReadReplicaCount, + ScalableDimensionSagemakerVariantDesiredInstanceCount, + ScalableDimensionCustomResourceResourceTypeProperty, + ScalableDimensionComprehendDocumentClassifierEndpointDesiredInferenceUnits, + ScalableDimensionLambdaFunctionProvisionedConcurrency, + ScalableDimensionCassandraTableReadCapacityUnits, + ScalableDimensionCassandraTableWriteCapacityUnits, + } +} + const ( // ScalingActivityStatusCodePending is a ScalingActivityStatusCode enum value ScalingActivityStatusCodePending = "Pending" @@ -5640,6 +5741,18 @@ const ( ScalingActivityStatusCodeFailed = "Failed" ) +// ScalingActivityStatusCode_Values returns all elements of the ScalingActivityStatusCode enum +func ScalingActivityStatusCode_Values() []string { + return []string{ + ScalingActivityStatusCodePending, + ScalingActivityStatusCodeInProgress, + ScalingActivityStatusCodeSuccessful, + ScalingActivityStatusCodeOverridden, + ScalingActivityStatusCodeUnfulfilled, + ScalingActivityStatusCodeFailed, + } +} + const ( // ServiceNamespaceEcs is a ServiceNamespace enum value ServiceNamespaceEcs = "ecs" @@ -5674,3 +5787,20 @@ const ( // ServiceNamespaceCassandra is a ServiceNamespace enum value ServiceNamespaceCassandra = "cassandra" ) + +// ServiceNamespace_Values returns all elements of the ServiceNamespace enum +func ServiceNamespace_Values() []string { + return []string{ + ServiceNamespaceEcs, + ServiceNamespaceElasticmapreduce, + ServiceNamespaceEc2, + ServiceNamespaceAppstream, + ServiceNamespaceDynamodb, + ServiceNamespaceRds, + ServiceNamespaceSagemaker, + ServiceNamespaceCustomResource, + ServiceNamespaceComprehend, + ServiceNamespaceLambda, + ServiceNamespaceCassandra, + } +} 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 index 88feeb8edb1..8bc83b04ef5 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/applicationautoscaling/doc.go @@ -26,7 +26,7 @@ // // * AWS Lambda function provisioned concurrency // -// * Amazon Keyspaces for Apache Cassandra tables +// * Amazon Keyspaces (for Apache Cassandra) tables // // API Summary // diff --git a/vendor/github.com/aws/aws-sdk-go/service/applicationinsights/api.go b/vendor/github.com/aws/aws-sdk-go/service/applicationinsights/api.go index ba09f52950e..3c330256374 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/applicationinsights/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/applicationinsights/api.go @@ -6393,6 +6393,15 @@ const ( CloudWatchEventSourceHealth = "HEALTH" ) +// CloudWatchEventSource_Values returns all elements of the CloudWatchEventSource enum +func CloudWatchEventSource_Values() []string { + return []string{ + CloudWatchEventSourceEc2, + CloudWatchEventSourceCodeDeploy, + CloudWatchEventSourceHealth, + } +} + const ( // ConfigurationEventResourceTypeCloudwatchAlarm is a ConfigurationEventResourceType enum value ConfigurationEventResourceTypeCloudwatchAlarm = "CLOUDWATCH_ALARM" @@ -6404,6 +6413,15 @@ const ( ConfigurationEventResourceTypeSsmAssociation = "SSM_ASSOCIATION" ) +// ConfigurationEventResourceType_Values returns all elements of the ConfigurationEventResourceType enum +func ConfigurationEventResourceType_Values() []string { + return []string{ + ConfigurationEventResourceTypeCloudwatchAlarm, + ConfigurationEventResourceTypeCloudformation, + ConfigurationEventResourceTypeSsmAssociation, + } +} + const ( // ConfigurationEventStatusInfo is a ConfigurationEventStatus enum value ConfigurationEventStatusInfo = "INFO" @@ -6415,11 +6433,27 @@ const ( ConfigurationEventStatusError = "ERROR" ) +// ConfigurationEventStatus_Values returns all elements of the ConfigurationEventStatus enum +func ConfigurationEventStatus_Values() []string { + return []string{ + ConfigurationEventStatusInfo, + ConfigurationEventStatusWarn, + ConfigurationEventStatusError, + } +} + const ( // FeedbackKeyInsightsFeedback is a FeedbackKey enum value FeedbackKeyInsightsFeedback = "INSIGHTS_FEEDBACK" ) +// FeedbackKey_Values returns all elements of the FeedbackKey enum +func FeedbackKey_Values() []string { + return []string{ + FeedbackKeyInsightsFeedback, + } +} + const ( // FeedbackValueNotSpecified is a FeedbackValue enum value FeedbackValueNotSpecified = "NOT_SPECIFIED" @@ -6431,6 +6465,15 @@ const ( FeedbackValueNotUseful = "NOT_USEFUL" ) +// FeedbackValue_Values returns all elements of the FeedbackValue enum +func FeedbackValue_Values() []string { + return []string{ + FeedbackValueNotSpecified, + FeedbackValueUseful, + FeedbackValueNotUseful, + } +} + const ( // LogFilterError is a LogFilter enum value LogFilterError = "ERROR" @@ -6442,6 +6485,15 @@ const ( LogFilterInfo = "INFO" ) +// LogFilter_Values returns all elements of the LogFilter enum +func LogFilter_Values() []string { + return []string{ + LogFilterError, + LogFilterWarn, + LogFilterInfo, + } +} + const ( // SeverityLevelLow is a SeverityLevel enum value SeverityLevelLow = "Low" @@ -6453,6 +6505,15 @@ const ( SeverityLevelHigh = "High" ) +// SeverityLevel_Values returns all elements of the SeverityLevel enum +func SeverityLevel_Values() []string { + return []string{ + SeverityLevelLow, + SeverityLevelMedium, + SeverityLevelHigh, + } +} + const ( // StatusIgnore is a Status enum value StatusIgnore = "IGNORE" @@ -6464,6 +6525,15 @@ const ( StatusPending = "PENDING" ) +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusIgnore, + StatusResolved, + StatusPending, + } +} + const ( // TierDefault is a Tier enum value TierDefault = "DEFAULT" @@ -6480,3 +6550,14 @@ const ( // TierSqlServer is a Tier enum value TierSqlServer = "SQL_SERVER" ) + +// Tier_Values returns all elements of the Tier enum +func Tier_Values() []string { + return []string{ + TierDefault, + TierDotNetCore, + TierDotNetWorker, + TierDotNetWeb, + TierSqlServer, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/appmesh/api.go b/vendor/github.com/aws/aws-sdk-go/service/appmesh/api.go index 18cb1a9452a..8f436c9ae13 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/appmesh/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/appmesh/api.go @@ -13,6 +13,119 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restjson" ) +const opCreateGatewayRoute = "CreateGatewayRoute" + +// CreateGatewayRouteRequest generates a "aws/request.Request" representing the +// client's request for the CreateGatewayRoute operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateGatewayRoute for more information on using the CreateGatewayRoute +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateGatewayRouteRequest method. +// req, resp := client.CreateGatewayRouteRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateGatewayRoute +func (c *AppMesh) CreateGatewayRouteRequest(input *CreateGatewayRouteInput) (req *request.Request, output *CreateGatewayRouteOutput) { + op := &request.Operation{ + Name: opCreateGatewayRoute, + HTTPMethod: "PUT", + HTTPPath: "/v20190125/meshes/{meshName}/virtualGateway/{virtualGatewayName}/gatewayRoutes", + } + + if input == nil { + input = &CreateGatewayRouteInput{} + } + + output = &CreateGatewayRouteOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateGatewayRoute API operation for AWS App Mesh. +// +// Creates a gateway route. +// +// A gateway route is attached to a virtual gateway and routes traffic to an +// existing virtual service. If a route matches a request, it can distribute +// traffic to a target virtual service. +// +// For more information about gateway routes, see Gateway routes (https://docs.aws.amazon.com/app-mesh/latest/userguide/gateway-routes.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS App Mesh's +// API operation CreateGatewayRoute for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request syntax was malformed. Check your request syntax and try again. +// +// * ConflictException +// The request contains a client token that was used for a previous update resource +// call with different specifications. Try the request again with a new client +// token. +// +// * ForbiddenException +// You don't have permissions to perform this action. +// +// * InternalServerErrorException +// The request processing has failed because of an unknown error, exception, +// or failure. +// +// * LimitExceededException +// You have exceeded a service limit for your account. For more information, +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) +// in the AWS App Mesh User Guide. +// +// * NotFoundException +// The specified resource doesn't exist. Check your request syntax and try again. +// +// * ServiceUnavailableException +// The request has failed due to a temporary failure of the service. +// +// * TooManyRequestsException +// The maximum request rate permitted by the App Mesh APIs has been exceeded +// for your account. For best results, use an increasing or variable sleep interval +// between requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateGatewayRoute +func (c *AppMesh) CreateGatewayRoute(input *CreateGatewayRouteInput) (*CreateGatewayRouteOutput, error) { + req, out := c.CreateGatewayRouteRequest(input) + return out, req.Send() +} + +// CreateGatewayRouteWithContext is the same as CreateGatewayRoute with the addition of +// the ability to pass a context and additional request options. +// +// See CreateGatewayRoute for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) CreateGatewayRouteWithContext(ctx aws.Context, input *CreateGatewayRouteInput, opts ...request.Option) (*CreateGatewayRouteOutput, error) { + req, out := c.CreateGatewayRouteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateMesh = "CreateMesh" // CreateMeshRequest generates a "aws/request.Request" representing the @@ -57,12 +170,14 @@ func (c *AppMesh) CreateMeshRequest(input *CreateMeshInput) (req *request.Reques // CreateMesh API operation for AWS App Mesh. // -// Creates a service mesh. A service mesh is a logical boundary for network -// traffic between the services that reside within it. +// Creates a service mesh. // -// After you create your service mesh, you can create virtual services, virtual -// nodes, virtual routers, and routes to distribute traffic between the applications -// in your mesh. +// A service mesh is a logical boundary for network traffic between services +// that are represented by resources within the mesh. After you create your +// service mesh, you can create virtual services, virtual nodes, virtual routers, +// and routes to distribute traffic between the applications in your mesh. +// +// For more information about service meshes, see Service meshes (https://docs.aws.amazon.com/app-mesh/latest/userguide/meshes.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 @@ -89,7 +204,7 @@ func (c *AppMesh) CreateMeshRequest(input *CreateMeshInput) (req *request.Reques // // * LimitExceededException // You have exceeded a service limit for your account. For more information, -// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service_limits.html) +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) // in the AWS App Mesh User Guide. // // * NotFoundException @@ -171,13 +286,8 @@ func (c *AppMesh) CreateRouteRequest(input *CreateRouteInput) (req *request.Requ // // Creates a route that is associated with a virtual router. // -// You can use the prefix parameter in your route specification for path-based -// routing of requests. For example, if your virtual service name is my-service.local -// and you want the route to match requests to my-service.local/metrics, your -// prefix should be /metrics. -// -// If your route matches a request, you can distribute traffic to one or more -// target virtual nodes with relative weighting. +// You can route several different protocols and define a retry policy for a +// route. Traffic can be routed to one or more virtual nodes. // // For more information about routes, see Routes (https://docs.aws.amazon.com/app-mesh/latest/userguide/routes.html). // @@ -206,7 +316,7 @@ func (c *AppMesh) CreateRouteRequest(input *CreateRouteInput) (req *request.Requ // // * LimitExceededException // You have exceeded a service limit for your account. For more information, -// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service_limits.html) +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) // in the AWS App Mesh User Guide. // // * NotFoundException @@ -242,6 +352,121 @@ func (c *AppMesh) CreateRouteWithContext(ctx aws.Context, input *CreateRouteInpu return out, req.Send() } +const opCreateVirtualGateway = "CreateVirtualGateway" + +// CreateVirtualGatewayRequest generates a "aws/request.Request" representing the +// client's request for the CreateVirtualGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateVirtualGateway for more information on using the CreateVirtualGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateVirtualGatewayRequest method. +// req, resp := client.CreateVirtualGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateVirtualGateway +func (c *AppMesh) CreateVirtualGatewayRequest(input *CreateVirtualGatewayInput) (req *request.Request, output *CreateVirtualGatewayOutput) { + op := &request.Operation{ + Name: opCreateVirtualGateway, + HTTPMethod: "PUT", + HTTPPath: "/v20190125/meshes/{meshName}/virtualGateways", + } + + if input == nil { + input = &CreateVirtualGatewayInput{} + } + + output = &CreateVirtualGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateVirtualGateway API operation for AWS App Mesh. +// +// Creates a virtual gateway. +// +// A virtual gateway allows resources outside your mesh to communicate to resources +// that are inside your mesh. The virtual gateway represents an Envoy proxy +// running in an Amazon ECS task, in a Kubernetes service, or on an Amazon EC2 +// instance. Unlike a virtual node, which represents an Envoy running with an +// application, a virtual gateway represents Envoy deployed by itself. +// +// For more information about virtual gateways, see Virtual gateways (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_gateways.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS App Mesh's +// API operation CreateVirtualGateway for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request syntax was malformed. Check your request syntax and try again. +// +// * ConflictException +// The request contains a client token that was used for a previous update resource +// call with different specifications. Try the request again with a new client +// token. +// +// * ForbiddenException +// You don't have permissions to perform this action. +// +// * InternalServerErrorException +// The request processing has failed because of an unknown error, exception, +// or failure. +// +// * LimitExceededException +// You have exceeded a service limit for your account. For more information, +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) +// in the AWS App Mesh User Guide. +// +// * NotFoundException +// The specified resource doesn't exist. Check your request syntax and try again. +// +// * ServiceUnavailableException +// The request has failed due to a temporary failure of the service. +// +// * TooManyRequestsException +// The maximum request rate permitted by the App Mesh APIs has been exceeded +// for your account. For best results, use an increasing or variable sleep interval +// between requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/CreateVirtualGateway +func (c *AppMesh) CreateVirtualGateway(input *CreateVirtualGatewayInput) (*CreateVirtualGatewayOutput, error) { + req, out := c.CreateVirtualGatewayRequest(input) + return out, req.Send() +} + +// CreateVirtualGatewayWithContext is the same as CreateVirtualGateway with the addition of +// the ability to pass a context and additional request options. +// +// See CreateVirtualGateway for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) CreateVirtualGatewayWithContext(ctx aws.Context, input *CreateVirtualGatewayInput, opts ...request.Option) (*CreateVirtualGatewayOutput, error) { + req, out := c.CreateVirtualGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateVirtualNode = "CreateVirtualNode" // CreateVirtualNodeRequest generates a "aws/request.Request" representing the @@ -290,11 +515,13 @@ func (c *AppMesh) CreateVirtualNodeRequest(input *CreateVirtualNodeInput) (req * // // A virtual node acts as a logical pointer to a particular task group, such // as an Amazon ECS service or a Kubernetes deployment. When you create a virtual -// node, you can specify the service discovery information for your task group. +// node, you can specify the service discovery information for your task group, +// and whether the proxy running in a task group will communicate with other +// proxies using Transport Layer Security (TLS). // -// Any inbound traffic that your virtual node expects should be specified as -// a listener. Any outbound traffic that your virtual node expects to reach -// should be specified as a backend. +// You define a listener for any inbound traffic that your virtual node expects. +// Any virtual service that your virtual node expects to communicate to is specified +// as a backend. // // The response metadata for your new virtual node contains the arn that is // associated with the virtual node. Set this value (either the full ARN or @@ -307,7 +534,7 @@ func (c *AppMesh) CreateVirtualNodeRequest(input *CreateVirtualNodeInput) (req * // override the node.cluster value that is set by APPMESH_VIRTUAL_NODE_NAME // with the APPMESH_VIRTUAL_NODE_CLUSTER environment variable. // -// For more information about virtual nodes, see Virtual Nodes (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_nodes.html). +// For more information about virtual nodes, see Virtual nodes (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_nodes.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 @@ -334,7 +561,7 @@ func (c *AppMesh) CreateVirtualNodeRequest(input *CreateVirtualNodeInput) (req * // // * LimitExceededException // You have exceeded a service limit for your account. For more information, -// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service_limits.html) +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) // in the AWS App Mesh User Guide. // // * NotFoundException @@ -416,14 +643,13 @@ func (c *AppMesh) CreateVirtualRouterRequest(input *CreateVirtualRouterInput) (r // // Creates a virtual router within a service mesh. // -// Any inbound traffic that your virtual router expects should be specified -// as a listener. -// +// Specify a listener for any inbound traffic that your virtual router receives. +// Create a virtual router for each protocol and port that you need to route. // Virtual routers handle traffic for one or more virtual services within your // mesh. After you create your virtual router, create and associate routes for // your virtual router that direct incoming requests to different virtual nodes. // -// For more information about virtual routers, see Virtual Routers (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_routers.html). +// For more information about virtual routers, see Virtual routers (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_routers.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 @@ -450,7 +676,7 @@ func (c *AppMesh) CreateVirtualRouterRequest(input *CreateVirtualRouterInput) (r // // * LimitExceededException // You have exceeded a service limit for your account. For more information, -// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service_limits.html) +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) // in the AWS App Mesh User Guide. // // * NotFoundException @@ -538,7 +764,7 @@ func (c *AppMesh) CreateVirtualServiceRequest(input *CreateVirtualServiceInput) // are routed to the virtual node or virtual router that is specified as the // provider for the virtual service. // -// For more information about virtual services, see Virtual Services (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_services.html). +// For more information about virtual services, see Virtual services (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_services.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 @@ -565,7 +791,7 @@ func (c *AppMesh) CreateVirtualServiceRequest(input *CreateVirtualServiceInput) // // * LimitExceededException // You have exceeded a service limit for your account. For more information, -// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service_limits.html) +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) // in the AWS App Mesh User Guide. // // * NotFoundException @@ -601,6 +827,107 @@ func (c *AppMesh) CreateVirtualServiceWithContext(ctx aws.Context, input *Create return out, req.Send() } +const opDeleteGatewayRoute = "DeleteGatewayRoute" + +// DeleteGatewayRouteRequest generates a "aws/request.Request" representing the +// client's request for the DeleteGatewayRoute operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteGatewayRoute for more information on using the DeleteGatewayRoute +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteGatewayRouteRequest method. +// req, resp := client.DeleteGatewayRouteRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteGatewayRoute +func (c *AppMesh) DeleteGatewayRouteRequest(input *DeleteGatewayRouteInput) (req *request.Request, output *DeleteGatewayRouteOutput) { + op := &request.Operation{ + Name: opDeleteGatewayRoute, + HTTPMethod: "DELETE", + HTTPPath: "/v20190125/meshes/{meshName}/virtualGateway/{virtualGatewayName}/gatewayRoutes/{gatewayRouteName}", + } + + if input == nil { + input = &DeleteGatewayRouteInput{} + } + + output = &DeleteGatewayRouteOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteGatewayRoute API operation for AWS App Mesh. +// +// Deletes an existing gateway route. +// +// Returns awserr.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 App Mesh's +// API operation DeleteGatewayRoute for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request syntax was malformed. Check your request syntax and try again. +// +// * ForbiddenException +// You don't have permissions to perform this action. +// +// * InternalServerErrorException +// The request processing has failed because of an unknown error, exception, +// or failure. +// +// * NotFoundException +// The specified resource doesn't exist. Check your request syntax and try again. +// +// * ResourceInUseException +// You can't delete the specified resource because it's in use or required by +// another resource. +// +// * ServiceUnavailableException +// The request has failed due to a temporary failure of the service. +// +// * TooManyRequestsException +// The maximum request rate permitted by the App Mesh APIs has been exceeded +// for your account. For best results, use an increasing or variable sleep interval +// between requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteGatewayRoute +func (c *AppMesh) DeleteGatewayRoute(input *DeleteGatewayRouteInput) (*DeleteGatewayRouteOutput, error) { + req, out := c.DeleteGatewayRouteRequest(input) + return out, req.Send() +} + +// DeleteGatewayRouteWithContext is the same as DeleteGatewayRoute with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteGatewayRoute for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) DeleteGatewayRouteWithContext(ctx aws.Context, input *DeleteGatewayRouteInput, opts ...request.Option) (*DeleteGatewayRouteOutput, error) { + req, out := c.DeleteGatewayRouteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteMesh = "DeleteMesh" // DeleteMeshRequest generates a "aws/request.Request" representing the @@ -806,9 +1133,111 @@ func (c *AppMesh) DeleteRouteWithContext(ctx aws.Context, input *DeleteRouteInpu return out, req.Send() } -const opDeleteVirtualNode = "DeleteVirtualNode" +const opDeleteVirtualGateway = "DeleteVirtualGateway" -// DeleteVirtualNodeRequest generates a "aws/request.Request" representing the +// DeleteVirtualGatewayRequest generates a "aws/request.Request" representing the +// client's request for the DeleteVirtualGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteVirtualGateway for more information on using the DeleteVirtualGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteVirtualGatewayRequest method. +// req, resp := client.DeleteVirtualGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteVirtualGateway +func (c *AppMesh) DeleteVirtualGatewayRequest(input *DeleteVirtualGatewayInput) (req *request.Request, output *DeleteVirtualGatewayOutput) { + op := &request.Operation{ + Name: opDeleteVirtualGateway, + HTTPMethod: "DELETE", + HTTPPath: "/v20190125/meshes/{meshName}/virtualGateways/{virtualGatewayName}", + } + + if input == nil { + input = &DeleteVirtualGatewayInput{} + } + + output = &DeleteVirtualGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteVirtualGateway API operation for AWS App Mesh. +// +// Deletes an existing virtual gateway. You cannot delete a virtual gateway +// if any gateway routes are associated to it. +// +// Returns awserr.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 App Mesh's +// API operation DeleteVirtualGateway for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request syntax was malformed. Check your request syntax and try again. +// +// * ForbiddenException +// You don't have permissions to perform this action. +// +// * InternalServerErrorException +// The request processing has failed because of an unknown error, exception, +// or failure. +// +// * NotFoundException +// The specified resource doesn't exist. Check your request syntax and try again. +// +// * ResourceInUseException +// You can't delete the specified resource because it's in use or required by +// another resource. +// +// * ServiceUnavailableException +// The request has failed due to a temporary failure of the service. +// +// * TooManyRequestsException +// The maximum request rate permitted by the App Mesh APIs has been exceeded +// for your account. For best results, use an increasing or variable sleep interval +// between requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DeleteVirtualGateway +func (c *AppMesh) DeleteVirtualGateway(input *DeleteVirtualGatewayInput) (*DeleteVirtualGatewayOutput, error) { + req, out := c.DeleteVirtualGatewayRequest(input) + return out, req.Send() +} + +// DeleteVirtualGatewayWithContext is the same as DeleteVirtualGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteVirtualGateway for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) DeleteVirtualGatewayWithContext(ctx aws.Context, input *DeleteVirtualGatewayInput, opts ...request.Option) (*DeleteVirtualGatewayOutput, error) { + req, out := c.DeleteVirtualGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteVirtualNode = "DeleteVirtualNode" + +// DeleteVirtualNodeRequest generates a "aws/request.Request" representing the // client's request for the DeleteVirtualNode operation. The "output" return // value will be populated with the request's response once the request completes // successfully. @@ -1081,6 +1510,10 @@ func (c *AppMesh) DeleteVirtualServiceRequest(input *DeleteVirtualServiceInput) // * NotFoundException // The specified resource doesn't exist. Check your request syntax and try again. // +// * ResourceInUseException +// You can't delete the specified resource because it's in use or required by +// another resource. +// // * ServiceUnavailableException // The request has failed due to a temporary failure of the service. // @@ -1111,6 +1544,103 @@ func (c *AppMesh) DeleteVirtualServiceWithContext(ctx aws.Context, input *Delete return out, req.Send() } +const opDescribeGatewayRoute = "DescribeGatewayRoute" + +// DescribeGatewayRouteRequest generates a "aws/request.Request" representing the +// client's request for the DescribeGatewayRoute operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeGatewayRoute for more information on using the DescribeGatewayRoute +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeGatewayRouteRequest method. +// req, resp := client.DescribeGatewayRouteRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeGatewayRoute +func (c *AppMesh) DescribeGatewayRouteRequest(input *DescribeGatewayRouteInput) (req *request.Request, output *DescribeGatewayRouteOutput) { + op := &request.Operation{ + Name: opDescribeGatewayRoute, + HTTPMethod: "GET", + HTTPPath: "/v20190125/meshes/{meshName}/virtualGateway/{virtualGatewayName}/gatewayRoutes/{gatewayRouteName}", + } + + if input == nil { + input = &DescribeGatewayRouteInput{} + } + + output = &DescribeGatewayRouteOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeGatewayRoute API operation for AWS App Mesh. +// +// Describes an existing gateway route. +// +// Returns awserr.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 App Mesh's +// API operation DescribeGatewayRoute for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request syntax was malformed. Check your request syntax and try again. +// +// * ForbiddenException +// You don't have permissions to perform this action. +// +// * InternalServerErrorException +// The request processing has failed because of an unknown error, exception, +// or failure. +// +// * NotFoundException +// The specified resource doesn't exist. Check your request syntax and try again. +// +// * ServiceUnavailableException +// The request has failed due to a temporary failure of the service. +// +// * TooManyRequestsException +// The maximum request rate permitted by the App Mesh APIs has been exceeded +// for your account. For best results, use an increasing or variable sleep interval +// between requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeGatewayRoute +func (c *AppMesh) DescribeGatewayRoute(input *DescribeGatewayRouteInput) (*DescribeGatewayRouteOutput, error) { + req, out := c.DescribeGatewayRouteRequest(input) + return out, req.Send() +} + +// DescribeGatewayRouteWithContext is the same as DescribeGatewayRoute with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeGatewayRoute for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) DescribeGatewayRouteWithContext(ctx aws.Context, input *DescribeGatewayRouteInput, opts ...request.Option) (*DescribeGatewayRouteOutput, error) { + req, out := c.DescribeGatewayRouteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeMesh = "DescribeMesh" // DescribeMeshRequest generates a "aws/request.Request" representing the @@ -1305,6 +1835,103 @@ func (c *AppMesh) DescribeRouteWithContext(ctx aws.Context, input *DescribeRoute return out, req.Send() } +const opDescribeVirtualGateway = "DescribeVirtualGateway" + +// DescribeVirtualGatewayRequest generates a "aws/request.Request" representing the +// client's request for the DescribeVirtualGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeVirtualGateway for more information on using the DescribeVirtualGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeVirtualGatewayRequest method. +// req, resp := client.DescribeVirtualGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeVirtualGateway +func (c *AppMesh) DescribeVirtualGatewayRequest(input *DescribeVirtualGatewayInput) (req *request.Request, output *DescribeVirtualGatewayOutput) { + op := &request.Operation{ + Name: opDescribeVirtualGateway, + HTTPMethod: "GET", + HTTPPath: "/v20190125/meshes/{meshName}/virtualGateways/{virtualGatewayName}", + } + + if input == nil { + input = &DescribeVirtualGatewayInput{} + } + + output = &DescribeVirtualGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeVirtualGateway API operation for AWS App Mesh. +// +// Describes an existing virtual gateway. +// +// Returns awserr.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 App Mesh's +// API operation DescribeVirtualGateway for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request syntax was malformed. Check your request syntax and try again. +// +// * ForbiddenException +// You don't have permissions to perform this action. +// +// * InternalServerErrorException +// The request processing has failed because of an unknown error, exception, +// or failure. +// +// * NotFoundException +// The specified resource doesn't exist. Check your request syntax and try again. +// +// * ServiceUnavailableException +// The request has failed due to a temporary failure of the service. +// +// * TooManyRequestsException +// The maximum request rate permitted by the App Mesh APIs has been exceeded +// for your account. For best results, use an increasing or variable sleep interval +// between requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/DescribeVirtualGateway +func (c *AppMesh) DescribeVirtualGateway(input *DescribeVirtualGatewayInput) (*DescribeVirtualGatewayOutput, error) { + req, out := c.DescribeVirtualGatewayRequest(input) + return out, req.Send() +} + +// DescribeVirtualGatewayWithContext is the same as DescribeVirtualGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeVirtualGateway for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) DescribeVirtualGatewayWithContext(ctx aws.Context, input *DescribeVirtualGatewayInput, opts ...request.Option) (*DescribeVirtualGatewayOutput, error) { + req, out := c.DescribeVirtualGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeVirtualNode = "DescribeVirtualNode" // DescribeVirtualNodeRequest generates a "aws/request.Request" representing the @@ -1596,37 +2223,37 @@ func (c *AppMesh) DescribeVirtualServiceWithContext(ctx aws.Context, input *Desc return out, req.Send() } -const opListMeshes = "ListMeshes" +const opListGatewayRoutes = "ListGatewayRoutes" -// ListMeshesRequest generates a "aws/request.Request" representing the -// client's request for the ListMeshes operation. The "output" return +// ListGatewayRoutesRequest generates a "aws/request.Request" representing the +// client's request for the ListGatewayRoutes operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListMeshes for more information on using the ListMeshes +// See ListGatewayRoutes for more information on using the ListGatewayRoutes // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListMeshesRequest method. -// req, resp := client.ListMeshesRequest(params) +// // Example sending a request using the ListGatewayRoutesRequest method. +// req, resp := client.ListGatewayRoutesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListMeshes -func (c *AppMesh) ListMeshesRequest(input *ListMeshesInput) (req *request.Request, output *ListMeshesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListGatewayRoutes +func (c *AppMesh) ListGatewayRoutesRequest(input *ListGatewayRoutesInput) (req *request.Request, output *ListGatewayRoutesOutput) { op := &request.Operation{ - Name: opListMeshes, + Name: opListGatewayRoutes, HTTPMethod: "GET", - HTTPPath: "/v20190125/meshes", + HTTPPath: "/v20190125/meshes/{meshName}/virtualGateway/{virtualGatewayName}/gatewayRoutes", Paginator: &request.Paginator{ InputTokens: []string{"nextToken"}, OutputTokens: []string{"nextToken"}, @@ -1636,24 +2263,25 @@ func (c *AppMesh) ListMeshesRequest(input *ListMeshesInput) (req *request.Reques } if input == nil { - input = &ListMeshesInput{} + input = &ListGatewayRoutesInput{} } - output = &ListMeshesOutput{} + output = &ListGatewayRoutesOutput{} req = c.newRequest(op, input, output) return } -// ListMeshes API operation for AWS App Mesh. +// ListGatewayRoutes API operation for AWS App Mesh. // -// Returns a list of existing service meshes. +// Returns a list of existing gateway routes that are associated to a virtual +// gateway. // // Returns awserr.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 App Mesh's -// API operation ListMeshes for usage and error information. +// API operation ListGatewayRoutes for usage and error information. // // Returned Error Types: // * BadRequestException @@ -1677,22 +2305,177 @@ func (c *AppMesh) ListMeshesRequest(input *ListMeshesInput) (req *request.Reques // for your account. For best results, use an increasing or variable sleep interval // between requests. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListMeshes -func (c *AppMesh) ListMeshes(input *ListMeshesInput) (*ListMeshesOutput, error) { - req, out := c.ListMeshesRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListGatewayRoutes +func (c *AppMesh) ListGatewayRoutes(input *ListGatewayRoutesInput) (*ListGatewayRoutesOutput, error) { + req, out := c.ListGatewayRoutesRequest(input) return out, req.Send() } -// ListMeshesWithContext is the same as ListMeshes with the addition of +// ListGatewayRoutesWithContext is the same as ListGatewayRoutes with the addition of // the ability to pass a context and additional request options. // -// See ListMeshes for details on how to use this API operation. +// See ListGatewayRoutes for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *AppMesh) ListMeshesWithContext(ctx aws.Context, input *ListMeshesInput, opts ...request.Option) (*ListMeshesOutput, error) { +func (c *AppMesh) ListGatewayRoutesWithContext(ctx aws.Context, input *ListGatewayRoutesInput, opts ...request.Option) (*ListGatewayRoutesOutput, error) { + req, out := c.ListGatewayRoutesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListGatewayRoutesPages iterates over the pages of a ListGatewayRoutes operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListGatewayRoutes 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 ListGatewayRoutes operation. +// pageNum := 0 +// err := client.ListGatewayRoutesPages(params, +// func(page *appmesh.ListGatewayRoutesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *AppMesh) ListGatewayRoutesPages(input *ListGatewayRoutesInput, fn func(*ListGatewayRoutesOutput, bool) bool) error { + return c.ListGatewayRoutesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListGatewayRoutesPagesWithContext same as ListGatewayRoutesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) ListGatewayRoutesPagesWithContext(ctx aws.Context, input *ListGatewayRoutesInput, fn func(*ListGatewayRoutesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListGatewayRoutesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListGatewayRoutesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListGatewayRoutesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListMeshes = "ListMeshes" + +// ListMeshesRequest generates a "aws/request.Request" representing the +// client's request for the ListMeshes operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListMeshes for more information on using the ListMeshes +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListMeshesRequest method. +// req, resp := client.ListMeshesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListMeshes +func (c *AppMesh) ListMeshesRequest(input *ListMeshesInput) (req *request.Request, output *ListMeshesOutput) { + op := &request.Operation{ + Name: opListMeshes, + HTTPMethod: "GET", + HTTPPath: "/v20190125/meshes", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "limit", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListMeshesInput{} + } + + output = &ListMeshesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListMeshes API operation for AWS App Mesh. +// +// Returns a list of existing service meshes. +// +// Returns awserr.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 App Mesh's +// API operation ListMeshes for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request syntax was malformed. Check your request syntax and try again. +// +// * ForbiddenException +// You don't have permissions to perform this action. +// +// * InternalServerErrorException +// The request processing has failed because of an unknown error, exception, +// or failure. +// +// * NotFoundException +// The specified resource doesn't exist. Check your request syntax and try again. +// +// * ServiceUnavailableException +// The request has failed due to a temporary failure of the service. +// +// * TooManyRequestsException +// The maximum request rate permitted by the App Mesh APIs has been exceeded +// for your account. For best results, use an increasing or variable sleep interval +// between requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListMeshes +func (c *AppMesh) ListMeshes(input *ListMeshesInput) (*ListMeshesOutput, error) { + req, out := c.ListMeshesRequest(input) + return out, req.Send() +} + +// ListMeshesWithContext is the same as ListMeshes with the addition of +// the ability to pass a context and additional request options. +// +// See ListMeshes for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) ListMeshesWithContext(ctx aws.Context, input *ListMeshesInput, opts ...request.Option) (*ListMeshesOutput, error) { req, out := c.ListMeshesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) @@ -2061,37 +2844,37 @@ func (c *AppMesh) ListTagsForResourcePagesWithContext(ctx aws.Context, input *Li return p.Err() } -const opListVirtualNodes = "ListVirtualNodes" +const opListVirtualGateways = "ListVirtualGateways" -// ListVirtualNodesRequest generates a "aws/request.Request" representing the -// client's request for the ListVirtualNodes operation. The "output" return +// ListVirtualGatewaysRequest generates a "aws/request.Request" representing the +// client's request for the ListVirtualGateways operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListVirtualNodes for more information on using the ListVirtualNodes +// See ListVirtualGateways for more information on using the ListVirtualGateways // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListVirtualNodesRequest method. -// req, resp := client.ListVirtualNodesRequest(params) +// // Example sending a request using the ListVirtualGatewaysRequest method. +// req, resp := client.ListVirtualGatewaysRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualNodes -func (c *AppMesh) ListVirtualNodesRequest(input *ListVirtualNodesInput) (req *request.Request, output *ListVirtualNodesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualGateways +func (c *AppMesh) ListVirtualGatewaysRequest(input *ListVirtualGatewaysInput) (req *request.Request, output *ListVirtualGatewaysOutput) { op := &request.Operation{ - Name: opListVirtualNodes, + Name: opListVirtualGateways, HTTPMethod: "GET", - HTTPPath: "/v20190125/meshes/{meshName}/virtualNodes", + HTTPPath: "/v20190125/meshes/{meshName}/virtualGateways", Paginator: &request.Paginator{ InputTokens: []string{"nextToken"}, OutputTokens: []string{"nextToken"}, @@ -2101,24 +2884,24 @@ func (c *AppMesh) ListVirtualNodesRequest(input *ListVirtualNodesInput) (req *re } if input == nil { - input = &ListVirtualNodesInput{} + input = &ListVirtualGatewaysInput{} } - output = &ListVirtualNodesOutput{} + output = &ListVirtualGatewaysOutput{} req = c.newRequest(op, input, output) return } -// ListVirtualNodes API operation for AWS App Mesh. +// ListVirtualGateways API operation for AWS App Mesh. // -// Returns a list of existing virtual nodes. +// Returns a list of existing virtual gateways in a service mesh. // // Returns awserr.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 App Mesh's -// API operation ListVirtualNodes for usage and error information. +// API operation ListVirtualGateways for usage and error information. // // Returned Error Types: // * BadRequestException @@ -2142,65 +2925,65 @@ func (c *AppMesh) ListVirtualNodesRequest(input *ListVirtualNodesInput) (req *re // for your account. For best results, use an increasing or variable sleep interval // between requests. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualNodes -func (c *AppMesh) ListVirtualNodes(input *ListVirtualNodesInput) (*ListVirtualNodesOutput, error) { - req, out := c.ListVirtualNodesRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualGateways +func (c *AppMesh) ListVirtualGateways(input *ListVirtualGatewaysInput) (*ListVirtualGatewaysOutput, error) { + req, out := c.ListVirtualGatewaysRequest(input) return out, req.Send() } -// ListVirtualNodesWithContext is the same as ListVirtualNodes with the addition of +// ListVirtualGatewaysWithContext is the same as ListVirtualGateways with the addition of // the ability to pass a context and additional request options. // -// See ListVirtualNodes for details on how to use this API operation. +// See ListVirtualGateways for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *AppMesh) ListVirtualNodesWithContext(ctx aws.Context, input *ListVirtualNodesInput, opts ...request.Option) (*ListVirtualNodesOutput, error) { - req, out := c.ListVirtualNodesRequest(input) +func (c *AppMesh) ListVirtualGatewaysWithContext(ctx aws.Context, input *ListVirtualGatewaysInput, opts ...request.Option) (*ListVirtualGatewaysOutput, error) { + req, out := c.ListVirtualGatewaysRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListVirtualNodesPages iterates over the pages of a ListVirtualNodes operation, +// ListVirtualGatewaysPages iterates over the pages of a ListVirtualGateways operation, // calling the "fn" function with the response data for each page. To stop // iterating, return false from the fn function. // -// See ListVirtualNodes method for more information on how to use this operation. +// See ListVirtualGateways 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 ListVirtualNodes operation. +// // Example iterating over at most 3 pages of a ListVirtualGateways operation. // pageNum := 0 -// err := client.ListVirtualNodesPages(params, -// func(page *appmesh.ListVirtualNodesOutput, lastPage bool) bool { +// err := client.ListVirtualGatewaysPages(params, +// func(page *appmesh.ListVirtualGatewaysOutput, lastPage bool) bool { // pageNum++ // fmt.Println(page) // return pageNum <= 3 // }) // -func (c *AppMesh) ListVirtualNodesPages(input *ListVirtualNodesInput, fn func(*ListVirtualNodesOutput, bool) bool) error { - return c.ListVirtualNodesPagesWithContext(aws.BackgroundContext(), input, fn) +func (c *AppMesh) ListVirtualGatewaysPages(input *ListVirtualGatewaysInput, fn func(*ListVirtualGatewaysOutput, bool) bool) error { + return c.ListVirtualGatewaysPagesWithContext(aws.BackgroundContext(), input, fn) } -// ListVirtualNodesPagesWithContext same as ListVirtualNodesPages except +// ListVirtualGatewaysPagesWithContext same as ListVirtualGatewaysPages except // it takes a Context and allows setting request options on the pages. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *AppMesh) ListVirtualNodesPagesWithContext(ctx aws.Context, input *ListVirtualNodesInput, fn func(*ListVirtualNodesOutput, bool) bool, opts ...request.Option) error { +func (c *AppMesh) ListVirtualGatewaysPagesWithContext(ctx aws.Context, input *ListVirtualGatewaysInput, fn func(*ListVirtualGatewaysOutput, bool) bool, opts ...request.Option) error { p := request.Pagination{ NewRequest: func() (*request.Request, error) { - var inCpy *ListVirtualNodesInput + var inCpy *ListVirtualGatewaysInput if input != nil { tmp := *input inCpy = &tmp } - req, _ := c.ListVirtualNodesRequest(inCpy) + req, _ := c.ListVirtualGatewaysRequest(inCpy) req.SetContext(ctx) req.ApplyOptions(opts...) return req, nil @@ -2208,7 +2991,7 @@ func (c *AppMesh) ListVirtualNodesPagesWithContext(ctx aws.Context, input *ListV } for p.Next() { - if !fn(p.Page().(*ListVirtualNodesOutput), !p.HasNextPage()) { + if !fn(p.Page().(*ListVirtualGatewaysOutput), !p.HasNextPage()) { break } } @@ -2216,37 +2999,37 @@ func (c *AppMesh) ListVirtualNodesPagesWithContext(ctx aws.Context, input *ListV return p.Err() } -const opListVirtualRouters = "ListVirtualRouters" +const opListVirtualNodes = "ListVirtualNodes" -// ListVirtualRoutersRequest generates a "aws/request.Request" representing the -// client's request for the ListVirtualRouters operation. The "output" return +// ListVirtualNodesRequest generates a "aws/request.Request" representing the +// client's request for the ListVirtualNodes operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListVirtualRouters for more information on using the ListVirtualRouters +// See ListVirtualNodes for more information on using the ListVirtualNodes // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListVirtualRoutersRequest method. -// req, resp := client.ListVirtualRoutersRequest(params) +// // Example sending a request using the ListVirtualNodesRequest method. +// req, resp := client.ListVirtualNodesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualRouters -func (c *AppMesh) ListVirtualRoutersRequest(input *ListVirtualRoutersInput) (req *request.Request, output *ListVirtualRoutersOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualNodes +func (c *AppMesh) ListVirtualNodesRequest(input *ListVirtualNodesInput) (req *request.Request, output *ListVirtualNodesOutput) { op := &request.Operation{ - Name: opListVirtualRouters, + Name: opListVirtualNodes, HTTPMethod: "GET", - HTTPPath: "/v20190125/meshes/{meshName}/virtualRouters", + HTTPPath: "/v20190125/meshes/{meshName}/virtualNodes", Paginator: &request.Paginator{ InputTokens: []string{"nextToken"}, OutputTokens: []string{"nextToken"}, @@ -2256,24 +3039,24 @@ func (c *AppMesh) ListVirtualRoutersRequest(input *ListVirtualRoutersInput) (req } if input == nil { - input = &ListVirtualRoutersInput{} + input = &ListVirtualNodesInput{} } - output = &ListVirtualRoutersOutput{} + output = &ListVirtualNodesOutput{} req = c.newRequest(op, input, output) return } -// ListVirtualRouters API operation for AWS App Mesh. +// ListVirtualNodes API operation for AWS App Mesh. // -// Returns a list of existing virtual routers in a service mesh. +// Returns a list of existing virtual nodes. // // Returns awserr.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 App Mesh's -// API operation ListVirtualRouters for usage and error information. +// API operation ListVirtualNodes for usage and error information. // // Returned Error Types: // * BadRequestException @@ -2297,65 +3080,65 @@ func (c *AppMesh) ListVirtualRoutersRequest(input *ListVirtualRoutersInput) (req // for your account. For best results, use an increasing or variable sleep interval // between requests. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualRouters -func (c *AppMesh) ListVirtualRouters(input *ListVirtualRoutersInput) (*ListVirtualRoutersOutput, error) { - req, out := c.ListVirtualRoutersRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualNodes +func (c *AppMesh) ListVirtualNodes(input *ListVirtualNodesInput) (*ListVirtualNodesOutput, error) { + req, out := c.ListVirtualNodesRequest(input) return out, req.Send() } -// ListVirtualRoutersWithContext is the same as ListVirtualRouters with the addition of +// ListVirtualNodesWithContext is the same as ListVirtualNodes with the addition of // the ability to pass a context and additional request options. // -// See ListVirtualRouters for details on how to use this API operation. +// See ListVirtualNodes for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *AppMesh) ListVirtualRoutersWithContext(ctx aws.Context, input *ListVirtualRoutersInput, opts ...request.Option) (*ListVirtualRoutersOutput, error) { - req, out := c.ListVirtualRoutersRequest(input) +func (c *AppMesh) ListVirtualNodesWithContext(ctx aws.Context, input *ListVirtualNodesInput, opts ...request.Option) (*ListVirtualNodesOutput, error) { + req, out := c.ListVirtualNodesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListVirtualRoutersPages iterates over the pages of a ListVirtualRouters operation, +// ListVirtualNodesPages iterates over the pages of a ListVirtualNodes operation, // calling the "fn" function with the response data for each page. To stop // iterating, return false from the fn function. // -// See ListVirtualRouters method for more information on how to use this operation. +// See ListVirtualNodes 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 ListVirtualRouters operation. +// // Example iterating over at most 3 pages of a ListVirtualNodes operation. // pageNum := 0 -// err := client.ListVirtualRoutersPages(params, -// func(page *appmesh.ListVirtualRoutersOutput, lastPage bool) bool { +// err := client.ListVirtualNodesPages(params, +// func(page *appmesh.ListVirtualNodesOutput, lastPage bool) bool { // pageNum++ // fmt.Println(page) // return pageNum <= 3 // }) // -func (c *AppMesh) ListVirtualRoutersPages(input *ListVirtualRoutersInput, fn func(*ListVirtualRoutersOutput, bool) bool) error { - return c.ListVirtualRoutersPagesWithContext(aws.BackgroundContext(), input, fn) +func (c *AppMesh) ListVirtualNodesPages(input *ListVirtualNodesInput, fn func(*ListVirtualNodesOutput, bool) bool) error { + return c.ListVirtualNodesPagesWithContext(aws.BackgroundContext(), input, fn) } -// ListVirtualRoutersPagesWithContext same as ListVirtualRoutersPages except +// ListVirtualNodesPagesWithContext same as ListVirtualNodesPages except // it takes a Context and allows setting request options on the pages. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *AppMesh) ListVirtualRoutersPagesWithContext(ctx aws.Context, input *ListVirtualRoutersInput, fn func(*ListVirtualRoutersOutput, bool) bool, opts ...request.Option) error { +func (c *AppMesh) ListVirtualNodesPagesWithContext(ctx aws.Context, input *ListVirtualNodesInput, fn func(*ListVirtualNodesOutput, bool) bool, opts ...request.Option) error { p := request.Pagination{ NewRequest: func() (*request.Request, error) { - var inCpy *ListVirtualRoutersInput + var inCpy *ListVirtualNodesInput if input != nil { tmp := *input inCpy = &tmp } - req, _ := c.ListVirtualRoutersRequest(inCpy) + req, _ := c.ListVirtualNodesRequest(inCpy) req.SetContext(ctx) req.ApplyOptions(opts...) return req, nil @@ -2363,7 +3146,7 @@ func (c *AppMesh) ListVirtualRoutersPagesWithContext(ctx aws.Context, input *Lis } for p.Next() { - if !fn(p.Page().(*ListVirtualRoutersOutput), !p.HasNextPage()) { + if !fn(p.Page().(*ListVirtualNodesOutput), !p.HasNextPage()) { break } } @@ -2371,25 +3154,180 @@ func (c *AppMesh) ListVirtualRoutersPagesWithContext(ctx aws.Context, input *Lis return p.Err() } -const opListVirtualServices = "ListVirtualServices" +const opListVirtualRouters = "ListVirtualRouters" -// ListVirtualServicesRequest generates a "aws/request.Request" representing the -// client's request for the ListVirtualServices operation. The "output" return +// ListVirtualRoutersRequest generates a "aws/request.Request" representing the +// client's request for the ListVirtualRouters operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListVirtualServices for more information on using the ListVirtualServices +// See ListVirtualRouters for more information on using the ListVirtualRouters // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListVirtualServicesRequest method. -// req, resp := client.ListVirtualServicesRequest(params) +// // Example sending a request using the ListVirtualRoutersRequest method. +// req, resp := client.ListVirtualRoutersRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualRouters +func (c *AppMesh) ListVirtualRoutersRequest(input *ListVirtualRoutersInput) (req *request.Request, output *ListVirtualRoutersOutput) { + op := &request.Operation{ + Name: opListVirtualRouters, + HTTPMethod: "GET", + HTTPPath: "/v20190125/meshes/{meshName}/virtualRouters", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "limit", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListVirtualRoutersInput{} + } + + output = &ListVirtualRoutersOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListVirtualRouters API operation for AWS App Mesh. +// +// Returns a list of existing virtual routers in a service mesh. +// +// Returns awserr.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 App Mesh's +// API operation ListVirtualRouters for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request syntax was malformed. Check your request syntax and try again. +// +// * ForbiddenException +// You don't have permissions to perform this action. +// +// * InternalServerErrorException +// The request processing has failed because of an unknown error, exception, +// or failure. +// +// * NotFoundException +// The specified resource doesn't exist. Check your request syntax and try again. +// +// * ServiceUnavailableException +// The request has failed due to a temporary failure of the service. +// +// * TooManyRequestsException +// The maximum request rate permitted by the App Mesh APIs has been exceeded +// for your account. For best results, use an increasing or variable sleep interval +// between requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/ListVirtualRouters +func (c *AppMesh) ListVirtualRouters(input *ListVirtualRoutersInput) (*ListVirtualRoutersOutput, error) { + req, out := c.ListVirtualRoutersRequest(input) + return out, req.Send() +} + +// ListVirtualRoutersWithContext is the same as ListVirtualRouters with the addition of +// the ability to pass a context and additional request options. +// +// See ListVirtualRouters for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) ListVirtualRoutersWithContext(ctx aws.Context, input *ListVirtualRoutersInput, opts ...request.Option) (*ListVirtualRoutersOutput, error) { + req, out := c.ListVirtualRoutersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListVirtualRoutersPages iterates over the pages of a ListVirtualRouters operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListVirtualRouters 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 ListVirtualRouters operation. +// pageNum := 0 +// err := client.ListVirtualRoutersPages(params, +// func(page *appmesh.ListVirtualRoutersOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *AppMesh) ListVirtualRoutersPages(input *ListVirtualRoutersInput, fn func(*ListVirtualRoutersOutput, bool) bool) error { + return c.ListVirtualRoutersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListVirtualRoutersPagesWithContext same as ListVirtualRoutersPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) ListVirtualRoutersPagesWithContext(ctx aws.Context, input *ListVirtualRoutersInput, fn func(*ListVirtualRoutersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListVirtualRoutersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListVirtualRoutersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListVirtualRoutersOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListVirtualServices = "ListVirtualServices" + +// ListVirtualServicesRequest generates a "aws/request.Request" representing the +// client's request for the ListVirtualServices operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListVirtualServices for more information on using the ListVirtualServices +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListVirtualServicesRequest method. +// req, resp := client.ListVirtualServicesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled @@ -2730,6 +3668,114 @@ func (c *AppMesh) UntagResourceWithContext(ctx aws.Context, input *UntagResource return out, req.Send() } +const opUpdateGatewayRoute = "UpdateGatewayRoute" + +// UpdateGatewayRouteRequest generates a "aws/request.Request" representing the +// client's request for the UpdateGatewayRoute operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateGatewayRoute for more information on using the UpdateGatewayRoute +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateGatewayRouteRequest method. +// req, resp := client.UpdateGatewayRouteRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateGatewayRoute +func (c *AppMesh) UpdateGatewayRouteRequest(input *UpdateGatewayRouteInput) (req *request.Request, output *UpdateGatewayRouteOutput) { + op := &request.Operation{ + Name: opUpdateGatewayRoute, + HTTPMethod: "PUT", + HTTPPath: "/v20190125/meshes/{meshName}/virtualGateway/{virtualGatewayName}/gatewayRoutes/{gatewayRouteName}", + } + + if input == nil { + input = &UpdateGatewayRouteInput{} + } + + output = &UpdateGatewayRouteOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateGatewayRoute API operation for AWS App Mesh. +// +// Updates an existing gateway route that is associated to a specified virtual +// gateway in a service mesh. +// +// Returns awserr.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 App Mesh's +// API operation UpdateGatewayRoute for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request syntax was malformed. Check your request syntax and try again. +// +// * ConflictException +// The request contains a client token that was used for a previous update resource +// call with different specifications. Try the request again with a new client +// token. +// +// * ForbiddenException +// You don't have permissions to perform this action. +// +// * InternalServerErrorException +// The request processing has failed because of an unknown error, exception, +// or failure. +// +// * LimitExceededException +// You have exceeded a service limit for your account. For more information, +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) +// in the AWS App Mesh User Guide. +// +// * NotFoundException +// The specified resource doesn't exist. Check your request syntax and try again. +// +// * ServiceUnavailableException +// The request has failed due to a temporary failure of the service. +// +// * TooManyRequestsException +// The maximum request rate permitted by the App Mesh APIs has been exceeded +// for your account. For best results, use an increasing or variable sleep interval +// between requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateGatewayRoute +func (c *AppMesh) UpdateGatewayRoute(input *UpdateGatewayRouteInput) (*UpdateGatewayRouteOutput, error) { + req, out := c.UpdateGatewayRouteRequest(input) + return out, req.Send() +} + +// UpdateGatewayRouteWithContext is the same as UpdateGatewayRoute with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateGatewayRoute for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) UpdateGatewayRouteWithContext(ctx aws.Context, input *UpdateGatewayRouteInput, opts ...request.Option) (*UpdateGatewayRouteOutput, error) { + req, out := c.UpdateGatewayRouteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opUpdateMesh = "UpdateMesh" // UpdateMeshRequest generates a "aws/request.Request" representing the @@ -2903,7 +3949,7 @@ func (c *AppMesh) UpdateRouteRequest(input *UpdateRouteInput) (req *request.Requ // // * LimitExceededException // You have exceeded a service limit for your account. For more information, -// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service_limits.html) +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) // in the AWS App Mesh User Guide. // // * NotFoundException @@ -2939,58 +3985,58 @@ func (c *AppMesh) UpdateRouteWithContext(ctx aws.Context, input *UpdateRouteInpu return out, req.Send() } -const opUpdateVirtualNode = "UpdateVirtualNode" +const opUpdateVirtualGateway = "UpdateVirtualGateway" -// UpdateVirtualNodeRequest generates a "aws/request.Request" representing the -// client's request for the UpdateVirtualNode operation. The "output" return +// UpdateVirtualGatewayRequest generates a "aws/request.Request" representing the +// client's request for the UpdateVirtualGateway operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateVirtualNode for more information on using the UpdateVirtualNode +// See UpdateVirtualGateway for more information on using the UpdateVirtualGateway // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateVirtualNodeRequest method. -// req, resp := client.UpdateVirtualNodeRequest(params) +// // Example sending a request using the UpdateVirtualGatewayRequest method. +// req, resp := client.UpdateVirtualGatewayRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualNode -func (c *AppMesh) UpdateVirtualNodeRequest(input *UpdateVirtualNodeInput) (req *request.Request, output *UpdateVirtualNodeOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualGateway +func (c *AppMesh) UpdateVirtualGatewayRequest(input *UpdateVirtualGatewayInput) (req *request.Request, output *UpdateVirtualGatewayOutput) { op := &request.Operation{ - Name: opUpdateVirtualNode, + Name: opUpdateVirtualGateway, HTTPMethod: "PUT", - HTTPPath: "/v20190125/meshes/{meshName}/virtualNodes/{virtualNodeName}", + HTTPPath: "/v20190125/meshes/{meshName}/virtualGateways/{virtualGatewayName}", } if input == nil { - input = &UpdateVirtualNodeInput{} + input = &UpdateVirtualGatewayInput{} } - output = &UpdateVirtualNodeOutput{} + output = &UpdateVirtualGatewayOutput{} req = c.newRequest(op, input, output) return } -// UpdateVirtualNode API operation for AWS App Mesh. +// UpdateVirtualGateway API operation for AWS App Mesh. // -// Updates an existing virtual node in a specified service mesh. +// Updates an existing virtual gateway in a specified service mesh. // // Returns awserr.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 App Mesh's -// API operation UpdateVirtualNode for usage and error information. +// API operation UpdateVirtualGateway for usage and error information. // // Returned Error Types: // * BadRequestException @@ -3010,7 +4056,7 @@ func (c *AppMesh) UpdateVirtualNodeRequest(input *UpdateVirtualNodeInput) (req * // // * LimitExceededException // You have exceeded a service limit for your account. For more information, -// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service_limits.html) +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) // in the AWS App Mesh User Guide. // // * NotFoundException @@ -3024,8 +4070,115 @@ func (c *AppMesh) UpdateVirtualNodeRequest(input *UpdateVirtualNodeInput) (req * // for your account. For best results, use an increasing or variable sleep interval // between requests. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualNode -func (c *AppMesh) UpdateVirtualNode(input *UpdateVirtualNodeInput) (*UpdateVirtualNodeOutput, error) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualGateway +func (c *AppMesh) UpdateVirtualGateway(input *UpdateVirtualGatewayInput) (*UpdateVirtualGatewayOutput, error) { + req, out := c.UpdateVirtualGatewayRequest(input) + return out, req.Send() +} + +// UpdateVirtualGatewayWithContext is the same as UpdateVirtualGateway with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateVirtualGateway for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *AppMesh) UpdateVirtualGatewayWithContext(ctx aws.Context, input *UpdateVirtualGatewayInput, opts ...request.Option) (*UpdateVirtualGatewayOutput, error) { + req, out := c.UpdateVirtualGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateVirtualNode = "UpdateVirtualNode" + +// UpdateVirtualNodeRequest generates a "aws/request.Request" representing the +// client's request for the UpdateVirtualNode operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateVirtualNode for more information on using the UpdateVirtualNode +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateVirtualNodeRequest method. +// req, resp := client.UpdateVirtualNodeRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualNode +func (c *AppMesh) UpdateVirtualNodeRequest(input *UpdateVirtualNodeInput) (req *request.Request, output *UpdateVirtualNodeOutput) { + op := &request.Operation{ + Name: opUpdateVirtualNode, + HTTPMethod: "PUT", + HTTPPath: "/v20190125/meshes/{meshName}/virtualNodes/{virtualNodeName}", + } + + if input == nil { + input = &UpdateVirtualNodeInput{} + } + + output = &UpdateVirtualNodeOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateVirtualNode API operation for AWS App Mesh. +// +// Updates an existing virtual node in a specified service mesh. +// +// Returns awserr.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 App Mesh's +// API operation UpdateVirtualNode for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request syntax was malformed. Check your request syntax and try again. +// +// * ConflictException +// The request contains a client token that was used for a previous update resource +// call with different specifications. Try the request again with a new client +// token. +// +// * ForbiddenException +// You don't have permissions to perform this action. +// +// * InternalServerErrorException +// The request processing has failed because of an unknown error, exception, +// or failure. +// +// * LimitExceededException +// You have exceeded a service limit for your account. For more information, +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) +// in the AWS App Mesh User Guide. +// +// * NotFoundException +// The specified resource doesn't exist. Check your request syntax and try again. +// +// * ServiceUnavailableException +// The request has failed due to a temporary failure of the service. +// +// * TooManyRequestsException +// The maximum request rate permitted by the App Mesh APIs has been exceeded +// for your account. For best results, use an increasing or variable sleep interval +// between requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualNode +func (c *AppMesh) UpdateVirtualNode(input *UpdateVirtualNodeInput) (*UpdateVirtualNodeOutput, error) { req, out := c.UpdateVirtualNodeRequest(input) return out, req.Send() } @@ -3117,7 +4270,7 @@ func (c *AppMesh) UpdateVirtualRouterRequest(input *UpdateVirtualRouterInput) (r // // * LimitExceededException // You have exceeded a service limit for your account. For more information, -// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service_limits.html) +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) // in the AWS App Mesh User Guide. // // * NotFoundException @@ -3224,7 +4377,7 @@ func (c *AppMesh) UpdateVirtualServiceRequest(input *UpdateVirtualServiceInput) // // * LimitExceededException // You have exceeded a service limit for your account. For more information, -// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service_limits.html) +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) // in the AWS App Mesh User Guide. // // * NotFoundException @@ -3721,6 +4874,157 @@ func (s *ConflictException) RequestID() string { return s.RespMetadata.RequestID } +type CreateGatewayRouteInput struct { + _ struct{} `type:"structure"` + + ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` + + // GatewayRouteName is a required field + GatewayRouteName *string `locationName:"gatewayRouteName" min:"1" type:"string" required:"true"` + + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + + // An object that represents a gateway route specification. Specify one gateway + // route type. + // + // Spec is a required field + Spec *GatewayRouteSpec `locationName:"spec" type:"structure" required:"true"` + + Tags []*TagRef `locationName:"tags" type:"list"` + + // VirtualGatewayName is a required field + VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateGatewayRouteInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateGatewayRouteInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateGatewayRouteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateGatewayRouteInput"} + if s.GatewayRouteName == nil { + invalidParams.Add(request.NewErrParamRequired("GatewayRouteName")) + } + if s.GatewayRouteName != nil && len(*s.GatewayRouteName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GatewayRouteName", 1)) + } + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.Spec == nil { + invalidParams.Add(request.NewErrParamRequired("Spec")) + } + if s.VirtualGatewayName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName")) + } + if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1)) + } + if s.Spec != nil { + if err := s.Spec.Validate(); err != nil { + invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) + } + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientToken sets the ClientToken field's value. +func (s *CreateGatewayRouteInput) SetClientToken(v string) *CreateGatewayRouteInput { + s.ClientToken = &v + return s +} + +// SetGatewayRouteName sets the GatewayRouteName field's value. +func (s *CreateGatewayRouteInput) SetGatewayRouteName(v string) *CreateGatewayRouteInput { + s.GatewayRouteName = &v + return s +} + +// SetMeshName sets the MeshName field's value. +func (s *CreateGatewayRouteInput) SetMeshName(v string) *CreateGatewayRouteInput { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *CreateGatewayRouteInput) SetMeshOwner(v string) *CreateGatewayRouteInput { + s.MeshOwner = &v + return s +} + +// SetSpec sets the Spec field's value. +func (s *CreateGatewayRouteInput) SetSpec(v *GatewayRouteSpec) *CreateGatewayRouteInput { + s.Spec = v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateGatewayRouteInput) SetTags(v []*TagRef) *CreateGatewayRouteInput { + s.Tags = v + return s +} + +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *CreateGatewayRouteInput) SetVirtualGatewayName(v string) *CreateGatewayRouteInput { + s.VirtualGatewayName = &v + return s +} + +type CreateGatewayRouteOutput struct { + _ struct{} `type:"structure" payload:"GatewayRoute"` + + // An object that represents a gateway route returned by a describe operation. + // + // GatewayRoute is a required field + GatewayRoute *GatewayRouteData `locationName:"gatewayRoute" type:"structure" required:"true"` +} + +// String returns the string representation +func (s CreateGatewayRouteOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateGatewayRouteOutput) GoString() string { + return s.String() +} + +// SetGatewayRoute sets the GatewayRoute field's value. +func (s *CreateGatewayRouteOutput) SetGatewayRoute(v *GatewayRouteData) *CreateGatewayRouteOutput { + s.GatewayRoute = v + return s +} + type CreateMeshInput struct { _ struct{} `type:"structure"` @@ -3975,7 +5279,7 @@ func (s *CreateRouteOutput) SetRoute(v *RouteData) *CreateRouteOutput { return s } -type CreateVirtualNodeInput struct { +type CreateVirtualGatewayInput struct { _ struct{} `type:"structure"` ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` @@ -3985,30 +5289,30 @@ type CreateVirtualNodeInput struct { MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - // An object that represents the specification of a virtual node. + // An object that represents the specification of a service mesh resource. // // Spec is a required field - Spec *VirtualNodeSpec `locationName:"spec" type:"structure" required:"true"` + Spec *VirtualGatewaySpec `locationName:"spec" type:"structure" required:"true"` Tags []*TagRef `locationName:"tags" type:"list"` - // VirtualNodeName is a required field - VirtualNodeName *string `locationName:"virtualNodeName" min:"1" type:"string" required:"true"` + // VirtualGatewayName is a required field + VirtualGatewayName *string `locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s CreateVirtualNodeInput) String() string { +func (s CreateVirtualGatewayInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateVirtualNodeInput) GoString() string { +func (s CreateVirtualGatewayInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateVirtualNodeInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateVirtualNodeInput"} +func (s *CreateVirtualGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateVirtualGatewayInput"} if s.MeshName == nil { invalidParams.Add(request.NewErrParamRequired("MeshName")) } @@ -4021,11 +5325,11 @@ func (s *CreateVirtualNodeInput) Validate() error { if s.Spec == nil { invalidParams.Add(request.NewErrParamRequired("Spec")) } - if s.VirtualNodeName == nil { - invalidParams.Add(request.NewErrParamRequired("VirtualNodeName")) + if s.VirtualGatewayName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName")) } - if s.VirtualNodeName != nil && len(*s.VirtualNodeName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VirtualNodeName", 1)) + if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1)) } if s.Spec != nil { if err := s.Spec.Validate(); err != nil { @@ -4050,67 +5354,67 @@ func (s *CreateVirtualNodeInput) Validate() error { } // SetClientToken sets the ClientToken field's value. -func (s *CreateVirtualNodeInput) SetClientToken(v string) *CreateVirtualNodeInput { +func (s *CreateVirtualGatewayInput) SetClientToken(v string) *CreateVirtualGatewayInput { s.ClientToken = &v return s } // SetMeshName sets the MeshName field's value. -func (s *CreateVirtualNodeInput) SetMeshName(v string) *CreateVirtualNodeInput { +func (s *CreateVirtualGatewayInput) SetMeshName(v string) *CreateVirtualGatewayInput { s.MeshName = &v return s } // SetMeshOwner sets the MeshOwner field's value. -func (s *CreateVirtualNodeInput) SetMeshOwner(v string) *CreateVirtualNodeInput { +func (s *CreateVirtualGatewayInput) SetMeshOwner(v string) *CreateVirtualGatewayInput { s.MeshOwner = &v return s } // SetSpec sets the Spec field's value. -func (s *CreateVirtualNodeInput) SetSpec(v *VirtualNodeSpec) *CreateVirtualNodeInput { +func (s *CreateVirtualGatewayInput) SetSpec(v *VirtualGatewaySpec) *CreateVirtualGatewayInput { s.Spec = v return s } // SetTags sets the Tags field's value. -func (s *CreateVirtualNodeInput) SetTags(v []*TagRef) *CreateVirtualNodeInput { +func (s *CreateVirtualGatewayInput) SetTags(v []*TagRef) *CreateVirtualGatewayInput { s.Tags = v return s } -// SetVirtualNodeName sets the VirtualNodeName field's value. -func (s *CreateVirtualNodeInput) SetVirtualNodeName(v string) *CreateVirtualNodeInput { - s.VirtualNodeName = &v +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *CreateVirtualGatewayInput) SetVirtualGatewayName(v string) *CreateVirtualGatewayInput { + s.VirtualGatewayName = &v return s } -type CreateVirtualNodeOutput struct { - _ struct{} `type:"structure" payload:"VirtualNode"` +type CreateVirtualGatewayOutput struct { + _ struct{} `type:"structure" payload:"VirtualGateway"` - // An object that represents a virtual node returned by a describe operation. + // An object that represents a virtual gateway returned by a describe operation. // - // VirtualNode is a required field - VirtualNode *VirtualNodeData `locationName:"virtualNode" type:"structure" required:"true"` + // VirtualGateway is a required field + VirtualGateway *VirtualGatewayData `locationName:"virtualGateway" type:"structure" required:"true"` } // String returns the string representation -func (s CreateVirtualNodeOutput) String() string { +func (s CreateVirtualGatewayOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateVirtualNodeOutput) GoString() string { +func (s CreateVirtualGatewayOutput) GoString() string { return s.String() } -// SetVirtualNode sets the VirtualNode field's value. -func (s *CreateVirtualNodeOutput) SetVirtualNode(v *VirtualNodeData) *CreateVirtualNodeOutput { - s.VirtualNode = v +// SetVirtualGateway sets the VirtualGateway field's value. +func (s *CreateVirtualGatewayOutput) SetVirtualGateway(v *VirtualGatewayData) *CreateVirtualGatewayOutput { + s.VirtualGateway = v return s } -type CreateVirtualRouterInput struct { +type CreateVirtualNodeInput struct { _ struct{} `type:"structure"` ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` @@ -4120,24 +5424,159 @@ type CreateVirtualRouterInput struct { MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - // An object that represents the specification of a virtual router. + // An object that represents the specification of a virtual node. // // Spec is a required field - Spec *VirtualRouterSpec `locationName:"spec" type:"structure" required:"true"` + Spec *VirtualNodeSpec `locationName:"spec" type:"structure" required:"true"` Tags []*TagRef `locationName:"tags" type:"list"` - // VirtualRouterName is a required field - VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"` + // VirtualNodeName is a required field + VirtualNodeName *string `locationName:"virtualNodeName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s CreateVirtualRouterInput) String() string { +func (s CreateVirtualNodeInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateVirtualRouterInput) GoString() string { +func (s CreateVirtualNodeInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateVirtualNodeInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateVirtualNodeInput"} + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.Spec == nil { + invalidParams.Add(request.NewErrParamRequired("Spec")) + } + if s.VirtualNodeName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualNodeName")) + } + if s.VirtualNodeName != nil && len(*s.VirtualNodeName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualNodeName", 1)) + } + if s.Spec != nil { + if err := s.Spec.Validate(); err != nil { + invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) + } + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientToken sets the ClientToken field's value. +func (s *CreateVirtualNodeInput) SetClientToken(v string) *CreateVirtualNodeInput { + s.ClientToken = &v + return s +} + +// SetMeshName sets the MeshName field's value. +func (s *CreateVirtualNodeInput) SetMeshName(v string) *CreateVirtualNodeInput { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *CreateVirtualNodeInput) SetMeshOwner(v string) *CreateVirtualNodeInput { + s.MeshOwner = &v + return s +} + +// SetSpec sets the Spec field's value. +func (s *CreateVirtualNodeInput) SetSpec(v *VirtualNodeSpec) *CreateVirtualNodeInput { + s.Spec = v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateVirtualNodeInput) SetTags(v []*TagRef) *CreateVirtualNodeInput { + s.Tags = v + return s +} + +// SetVirtualNodeName sets the VirtualNodeName field's value. +func (s *CreateVirtualNodeInput) SetVirtualNodeName(v string) *CreateVirtualNodeInput { + s.VirtualNodeName = &v + return s +} + +type CreateVirtualNodeOutput struct { + _ struct{} `type:"structure" payload:"VirtualNode"` + + // An object that represents a virtual node returned by a describe operation. + // + // VirtualNode is a required field + VirtualNode *VirtualNodeData `locationName:"virtualNode" type:"structure" required:"true"` +} + +// String returns the string representation +func (s CreateVirtualNodeOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateVirtualNodeOutput) GoString() string { + return s.String() +} + +// SetVirtualNode sets the VirtualNode field's value. +func (s *CreateVirtualNodeOutput) SetVirtualNode(v *VirtualNodeData) *CreateVirtualNodeOutput { + s.VirtualNode = v + return s +} + +type CreateVirtualRouterInput struct { + _ struct{} `type:"structure"` + + ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` + + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + + // An object that represents the specification of a virtual router. + // + // Spec is a required field + Spec *VirtualRouterSpec `locationName:"spec" type:"structure" required:"true"` + + Tags []*TagRef `locationName:"tags" type:"list"` + + // VirtualRouterName is a required field + VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateVirtualRouterInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateVirtualRouterInput) GoString() string { return s.String() } @@ -4377,6 +5816,111 @@ func (s *CreateVirtualServiceOutput) SetVirtualService(v *VirtualServiceData) *C return s } +type DeleteGatewayRouteInput struct { + _ struct{} `type:"structure"` + + // GatewayRouteName is a required field + GatewayRouteName *string `location:"uri" locationName:"gatewayRouteName" min:"1" type:"string" required:"true"` + + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + + // VirtualGatewayName is a required field + VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteGatewayRouteInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteGatewayRouteInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteGatewayRouteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteGatewayRouteInput"} + if s.GatewayRouteName == nil { + invalidParams.Add(request.NewErrParamRequired("GatewayRouteName")) + } + if s.GatewayRouteName != nil && len(*s.GatewayRouteName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GatewayRouteName", 1)) + } + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.VirtualGatewayName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName")) + } + if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGatewayRouteName sets the GatewayRouteName field's value. +func (s *DeleteGatewayRouteInput) SetGatewayRouteName(v string) *DeleteGatewayRouteInput { + s.GatewayRouteName = &v + return s +} + +// SetMeshName sets the MeshName field's value. +func (s *DeleteGatewayRouteInput) SetMeshName(v string) *DeleteGatewayRouteInput { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *DeleteGatewayRouteInput) SetMeshOwner(v string) *DeleteGatewayRouteInput { + s.MeshOwner = &v + return s +} + +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *DeleteGatewayRouteInput) SetVirtualGatewayName(v string) *DeleteGatewayRouteInput { + s.VirtualGatewayName = &v + return s +} + +type DeleteGatewayRouteOutput struct { + _ struct{} `type:"structure" payload:"GatewayRoute"` + + // An object that represents a gateway route returned by a describe operation. + // + // GatewayRoute is a required field + GatewayRoute *GatewayRouteData `locationName:"gatewayRoute" type:"structure" required:"true"` +} + +// String returns the string representation +func (s DeleteGatewayRouteOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteGatewayRouteOutput) GoString() string { + return s.String() +} + +// SetGatewayRoute sets the GatewayRoute field's value. +func (s *DeleteGatewayRouteOutput) SetGatewayRoute(v *GatewayRouteData) *DeleteGatewayRouteOutput { + s.GatewayRoute = v + return s +} + type DeleteMeshInput struct { _ struct{} `type:"structure"` @@ -4546,7 +6090,7 @@ func (s *DeleteRouteOutput) SetRoute(v *RouteData) *DeleteRouteOutput { return s } -type DeleteVirtualNodeInput struct { +type DeleteVirtualGatewayInput struct { _ struct{} `type:"structure"` // MeshName is a required field @@ -4554,23 +6098,23 @@ type DeleteVirtualNodeInput struct { MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - // VirtualNodeName is a required field - VirtualNodeName *string `location:"uri" locationName:"virtualNodeName" min:"1" type:"string" required:"true"` + // VirtualGatewayName is a required field + VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DeleteVirtualNodeInput) String() string { +func (s DeleteVirtualGatewayInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteVirtualNodeInput) GoString() string { +func (s DeleteVirtualGatewayInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteVirtualNodeInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteVirtualNodeInput"} +func (s *DeleteVirtualGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteVirtualGatewayInput"} if s.MeshName == nil { invalidParams.Add(request.NewErrParamRequired("MeshName")) } @@ -4580,11 +6124,11 @@ func (s *DeleteVirtualNodeInput) Validate() error { if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) } - if s.VirtualNodeName == nil { - invalidParams.Add(request.NewErrParamRequired("VirtualNodeName")) + if s.VirtualGatewayName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName")) } - if s.VirtualNodeName != nil && len(*s.VirtualNodeName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VirtualNodeName", 1)) + if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1)) } if invalidParams.Len() > 0 { @@ -4594,49 +6138,49 @@ func (s *DeleteVirtualNodeInput) Validate() error { } // SetMeshName sets the MeshName field's value. -func (s *DeleteVirtualNodeInput) SetMeshName(v string) *DeleteVirtualNodeInput { +func (s *DeleteVirtualGatewayInput) SetMeshName(v string) *DeleteVirtualGatewayInput { s.MeshName = &v return s } // SetMeshOwner sets the MeshOwner field's value. -func (s *DeleteVirtualNodeInput) SetMeshOwner(v string) *DeleteVirtualNodeInput { +func (s *DeleteVirtualGatewayInput) SetMeshOwner(v string) *DeleteVirtualGatewayInput { s.MeshOwner = &v return s } -// SetVirtualNodeName sets the VirtualNodeName field's value. -func (s *DeleteVirtualNodeInput) SetVirtualNodeName(v string) *DeleteVirtualNodeInput { - s.VirtualNodeName = &v +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *DeleteVirtualGatewayInput) SetVirtualGatewayName(v string) *DeleteVirtualGatewayInput { + s.VirtualGatewayName = &v return s } -type DeleteVirtualNodeOutput struct { - _ struct{} `type:"structure" payload:"VirtualNode"` +type DeleteVirtualGatewayOutput struct { + _ struct{} `type:"structure" payload:"VirtualGateway"` - // An object that represents a virtual node returned by a describe operation. + // An object that represents a virtual gateway returned by a describe operation. // - // VirtualNode is a required field - VirtualNode *VirtualNodeData `locationName:"virtualNode" type:"structure" required:"true"` + // VirtualGateway is a required field + VirtualGateway *VirtualGatewayData `locationName:"virtualGateway" type:"structure" required:"true"` } // String returns the string representation -func (s DeleteVirtualNodeOutput) String() string { +func (s DeleteVirtualGatewayOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteVirtualNodeOutput) GoString() string { +func (s DeleteVirtualGatewayOutput) GoString() string { return s.String() } -// SetVirtualNode sets the VirtualNode field's value. -func (s *DeleteVirtualNodeOutput) SetVirtualNode(v *VirtualNodeData) *DeleteVirtualNodeOutput { - s.VirtualNode = v +// SetVirtualGateway sets the VirtualGateway field's value. +func (s *DeleteVirtualGatewayOutput) SetVirtualGateway(v *VirtualGatewayData) *DeleteVirtualGatewayOutput { + s.VirtualGateway = v return s } -type DeleteVirtualRouterInput struct { +type DeleteVirtualNodeInput struct { _ struct{} `type:"structure"` // MeshName is a required field @@ -4644,23 +6188,23 @@ type DeleteVirtualRouterInput struct { MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - // VirtualRouterName is a required field - VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"` + // VirtualNodeName is a required field + VirtualNodeName *string `location:"uri" locationName:"virtualNodeName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DeleteVirtualRouterInput) String() string { +func (s DeleteVirtualNodeInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteVirtualRouterInput) GoString() string { +func (s DeleteVirtualNodeInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteVirtualRouterInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteVirtualRouterInput"} +func (s *DeleteVirtualNodeInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteVirtualNodeInput"} if s.MeshName == nil { invalidParams.Add(request.NewErrParamRequired("MeshName")) } @@ -4670,11 +6214,11 @@ func (s *DeleteVirtualRouterInput) Validate() error { if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) } - if s.VirtualRouterName == nil { - invalidParams.Add(request.NewErrParamRequired("VirtualRouterName")) + if s.VirtualNodeName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualNodeName")) } - if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1)) + if s.VirtualNodeName != nil && len(*s.VirtualNodeName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualNodeName", 1)) } if invalidParams.Len() > 0 { @@ -4684,13 +6228,103 @@ func (s *DeleteVirtualRouterInput) Validate() error { } // SetMeshName sets the MeshName field's value. -func (s *DeleteVirtualRouterInput) SetMeshName(v string) *DeleteVirtualRouterInput { +func (s *DeleteVirtualNodeInput) SetMeshName(v string) *DeleteVirtualNodeInput { s.MeshName = &v return s } // SetMeshOwner sets the MeshOwner field's value. -func (s *DeleteVirtualRouterInput) SetMeshOwner(v string) *DeleteVirtualRouterInput { +func (s *DeleteVirtualNodeInput) SetMeshOwner(v string) *DeleteVirtualNodeInput { + s.MeshOwner = &v + return s +} + +// SetVirtualNodeName sets the VirtualNodeName field's value. +func (s *DeleteVirtualNodeInput) SetVirtualNodeName(v string) *DeleteVirtualNodeInput { + s.VirtualNodeName = &v + return s +} + +type DeleteVirtualNodeOutput struct { + _ struct{} `type:"structure" payload:"VirtualNode"` + + // An object that represents a virtual node returned by a describe operation. + // + // VirtualNode is a required field + VirtualNode *VirtualNodeData `locationName:"virtualNode" type:"structure" required:"true"` +} + +// String returns the string representation +func (s DeleteVirtualNodeOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteVirtualNodeOutput) GoString() string { + return s.String() +} + +// SetVirtualNode sets the VirtualNode field's value. +func (s *DeleteVirtualNodeOutput) SetVirtualNode(v *VirtualNodeData) *DeleteVirtualNodeOutput { + s.VirtualNode = v + return s +} + +type DeleteVirtualRouterInput struct { + _ struct{} `type:"structure"` + + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + + // VirtualRouterName is a required field + VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteVirtualRouterInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteVirtualRouterInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteVirtualRouterInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteVirtualRouterInput"} + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.VirtualRouterName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualRouterName")) + } + if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMeshName sets the MeshName field's value. +func (s *DeleteVirtualRouterInput) SetMeshName(v string) *DeleteVirtualRouterInput { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *DeleteVirtualRouterInput) SetMeshOwner(v string) *DeleteVirtualRouterInput { s.MeshOwner = &v return s } @@ -4816,6 +6450,111 @@ func (s *DeleteVirtualServiceOutput) SetVirtualService(v *VirtualServiceData) *D return s } +type DescribeGatewayRouteInput struct { + _ struct{} `type:"structure"` + + // GatewayRouteName is a required field + GatewayRouteName *string `location:"uri" locationName:"gatewayRouteName" min:"1" type:"string" required:"true"` + + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + + // VirtualGatewayName is a required field + VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeGatewayRouteInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeGatewayRouteInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeGatewayRouteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeGatewayRouteInput"} + if s.GatewayRouteName == nil { + invalidParams.Add(request.NewErrParamRequired("GatewayRouteName")) + } + if s.GatewayRouteName != nil && len(*s.GatewayRouteName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GatewayRouteName", 1)) + } + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.VirtualGatewayName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName")) + } + if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGatewayRouteName sets the GatewayRouteName field's value. +func (s *DescribeGatewayRouteInput) SetGatewayRouteName(v string) *DescribeGatewayRouteInput { + s.GatewayRouteName = &v + return s +} + +// SetMeshName sets the MeshName field's value. +func (s *DescribeGatewayRouteInput) SetMeshName(v string) *DescribeGatewayRouteInput { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *DescribeGatewayRouteInput) SetMeshOwner(v string) *DescribeGatewayRouteInput { + s.MeshOwner = &v + return s +} + +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *DescribeGatewayRouteInput) SetVirtualGatewayName(v string) *DescribeGatewayRouteInput { + s.VirtualGatewayName = &v + return s +} + +type DescribeGatewayRouteOutput struct { + _ struct{} `type:"structure" payload:"GatewayRoute"` + + // An object that represents a gateway route returned by a describe operation. + // + // GatewayRoute is a required field + GatewayRoute *GatewayRouteData `locationName:"gatewayRoute" type:"structure" required:"true"` +} + +// String returns the string representation +func (s DescribeGatewayRouteOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeGatewayRouteOutput) GoString() string { + return s.String() +} + +// SetGatewayRoute sets the GatewayRoute field's value. +func (s *DescribeGatewayRouteOutput) SetGatewayRoute(v *GatewayRouteData) *DescribeGatewayRouteOutput { + s.GatewayRoute = v + return s +} + type DescribeMeshInput struct { _ struct{} `type:"structure"` @@ -4996,6 +6735,96 @@ func (s *DescribeRouteOutput) SetRoute(v *RouteData) *DescribeRouteOutput { return s } +type DescribeVirtualGatewayInput struct { + _ struct{} `type:"structure"` + + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + + // VirtualGatewayName is a required field + VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeVirtualGatewayInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeVirtualGatewayInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeVirtualGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeVirtualGatewayInput"} + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.VirtualGatewayName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName")) + } + if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMeshName sets the MeshName field's value. +func (s *DescribeVirtualGatewayInput) SetMeshName(v string) *DescribeVirtualGatewayInput { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *DescribeVirtualGatewayInput) SetMeshOwner(v string) *DescribeVirtualGatewayInput { + s.MeshOwner = &v + return s +} + +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *DescribeVirtualGatewayInput) SetVirtualGatewayName(v string) *DescribeVirtualGatewayInput { + s.VirtualGatewayName = &v + return s +} + +type DescribeVirtualGatewayOutput struct { + _ struct{} `type:"structure" payload:"VirtualGateway"` + + // An object that represents a virtual gateway returned by a describe operation. + // + // VirtualGateway is a required field + VirtualGateway *VirtualGatewayData `locationName:"virtualGateway" type:"structure" required:"true"` +} + +// String returns the string representation +func (s DescribeVirtualGatewayOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeVirtualGatewayOutput) GoString() string { + return s.String() +} + +// SetVirtualGateway sets the VirtualGateway field's value. +func (s *DescribeVirtualGatewayOutput) SetVirtualGateway(v *VirtualGatewayData) *DescribeVirtualGatewayOutput { + s.VirtualGateway = v + return s +} + type DescribeVirtualNodeInput struct { _ struct{} `type:"structure"` @@ -5468,144 +7297,219 @@ func (s *ForbiddenException) RequestID() string { return s.RespMetadata.RequestID } -// An object that represents a retry policy. Specify at least one value for -// at least one of the types of RetryEvents, a value for maxRetries, and a value -// for perRetryTimeout. -type GrpcRetryPolicy struct { +// An object that represents a gateway route returned by a describe operation. +type GatewayRouteData struct { _ struct{} `type:"structure"` - GrpcRetryEvents []*string `locationName:"grpcRetryEvents" min:"1" type:"list"` + // GatewayRouteName is a required field + GatewayRouteName *string `locationName:"gatewayRouteName" min:"1" type:"string" required:"true"` - HttpRetryEvents []*string `locationName:"httpRetryEvents" min:"1" type:"list"` + // MeshName is a required field + MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` - // MaxRetries is a required field - MaxRetries *int64 `locationName:"maxRetries" type:"long" required:"true"` + // An object that represents metadata for a resource. + // + // Metadata is a required field + Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"` - // An object that represents a duration of time. + // An object that represents a gateway route specification. Specify one gateway + // route type. // - // PerRetryTimeout is a required field - PerRetryTimeout *Duration `locationName:"perRetryTimeout" type:"structure" required:"true"` + // Spec is a required field + Spec *GatewayRouteSpec `locationName:"spec" type:"structure" required:"true"` - TcpRetryEvents []*string `locationName:"tcpRetryEvents" min:"1" type:"list"` + // An object that represents the current status of a gateway route. + // + // Status is a required field + Status *GatewayRouteStatus `locationName:"status" type:"structure" required:"true"` + + // VirtualGatewayName is a required field + VirtualGatewayName *string `locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s GrpcRetryPolicy) String() string { +func (s GatewayRouteData) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GrpcRetryPolicy) GoString() string { +func (s GatewayRouteData) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GrpcRetryPolicy) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GrpcRetryPolicy"} - if s.GrpcRetryEvents != nil && len(s.GrpcRetryEvents) < 1 { - invalidParams.Add(request.NewErrParamMinLen("GrpcRetryEvents", 1)) - } - if s.HttpRetryEvents != nil && len(s.HttpRetryEvents) < 1 { - invalidParams.Add(request.NewErrParamMinLen("HttpRetryEvents", 1)) - } - if s.MaxRetries == nil { - invalidParams.Add(request.NewErrParamRequired("MaxRetries")) - } - if s.PerRetryTimeout == nil { - invalidParams.Add(request.NewErrParamRequired("PerRetryTimeout")) - } - if s.TcpRetryEvents != nil && len(s.TcpRetryEvents) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TcpRetryEvents", 1)) - } +// SetGatewayRouteName sets the GatewayRouteName field's value. +func (s *GatewayRouteData) SetGatewayRouteName(v string) *GatewayRouteData { + s.GatewayRouteName = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetMeshName sets the MeshName field's value. +func (s *GatewayRouteData) SetMeshName(v string) *GatewayRouteData { + s.MeshName = &v + return s } -// SetGrpcRetryEvents sets the GrpcRetryEvents field's value. -func (s *GrpcRetryPolicy) SetGrpcRetryEvents(v []*string) *GrpcRetryPolicy { - s.GrpcRetryEvents = v +// SetMetadata sets the Metadata field's value. +func (s *GatewayRouteData) SetMetadata(v *ResourceMetadata) *GatewayRouteData { + s.Metadata = v return s } -// SetHttpRetryEvents sets the HttpRetryEvents field's value. -func (s *GrpcRetryPolicy) SetHttpRetryEvents(v []*string) *GrpcRetryPolicy { - s.HttpRetryEvents = v +// SetSpec sets the Spec field's value. +func (s *GatewayRouteData) SetSpec(v *GatewayRouteSpec) *GatewayRouteData { + s.Spec = v return s } -// SetMaxRetries sets the MaxRetries field's value. -func (s *GrpcRetryPolicy) SetMaxRetries(v int64) *GrpcRetryPolicy { - s.MaxRetries = &v +// SetStatus sets the Status field's value. +func (s *GatewayRouteData) SetStatus(v *GatewayRouteStatus) *GatewayRouteData { + s.Status = v return s } -// SetPerRetryTimeout sets the PerRetryTimeout field's value. -func (s *GrpcRetryPolicy) SetPerRetryTimeout(v *Duration) *GrpcRetryPolicy { - s.PerRetryTimeout = v +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *GatewayRouteData) SetVirtualGatewayName(v string) *GatewayRouteData { + s.VirtualGatewayName = &v return s } -// SetTcpRetryEvents sets the TcpRetryEvents field's value. -func (s *GrpcRetryPolicy) SetTcpRetryEvents(v []*string) *GrpcRetryPolicy { - s.TcpRetryEvents = v +// An object that represents a gateway route returned by a list operation. +type GatewayRouteRef struct { + _ struct{} `type:"structure"` + + // Arn is a required field + Arn *string `locationName:"arn" type:"string" required:"true"` + + // CreatedAt is a required field + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"` + + // GatewayRouteName is a required field + GatewayRouteName *string `locationName:"gatewayRouteName" min:"1" type:"string" required:"true"` + + // LastUpdatedAt is a required field + LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"` + + // MeshName is a required field + MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` + + // MeshOwner is a required field + MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"` + + // ResourceOwner is a required field + ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"` + + // Version is a required field + Version *int64 `locationName:"version" type:"long" required:"true"` + + // VirtualGatewayName is a required field + VirtualGatewayName *string `locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GatewayRouteRef) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GatewayRouteRef) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *GatewayRouteRef) SetArn(v string) *GatewayRouteRef { + s.Arn = &v return s } -// An object that represents a gRPC route type. -type GrpcRoute struct { +// SetCreatedAt sets the CreatedAt field's value. +func (s *GatewayRouteRef) SetCreatedAt(v time.Time) *GatewayRouteRef { + s.CreatedAt = &v + return s +} + +// SetGatewayRouteName sets the GatewayRouteName field's value. +func (s *GatewayRouteRef) SetGatewayRouteName(v string) *GatewayRouteRef { + s.GatewayRouteName = &v + return s +} + +// SetLastUpdatedAt sets the LastUpdatedAt field's value. +func (s *GatewayRouteRef) SetLastUpdatedAt(v time.Time) *GatewayRouteRef { + s.LastUpdatedAt = &v + return s +} + +// SetMeshName sets the MeshName field's value. +func (s *GatewayRouteRef) SetMeshName(v string) *GatewayRouteRef { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *GatewayRouteRef) SetMeshOwner(v string) *GatewayRouteRef { + s.MeshOwner = &v + return s +} + +// SetResourceOwner sets the ResourceOwner field's value. +func (s *GatewayRouteRef) SetResourceOwner(v string) *GatewayRouteRef { + s.ResourceOwner = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *GatewayRouteRef) SetVersion(v int64) *GatewayRouteRef { + s.Version = &v + return s +} + +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *GatewayRouteRef) SetVirtualGatewayName(v string) *GatewayRouteRef { + s.VirtualGatewayName = &v + return s +} + +// An object that represents a gateway route specification. Specify one gateway +// route type. +type GatewayRouteSpec struct { _ struct{} `type:"structure"` - // An object that represents the action to take if a match is determined. - // - // Action is a required field - Action *GrpcRouteAction `locationName:"action" type:"structure" required:"true"` + // An object that represents a gRPC gateway route. + GrpcRoute *GrpcGatewayRoute `locationName:"grpcRoute" type:"structure"` - // An object that represents the criteria for determining a request match. - // - // Match is a required field - Match *GrpcRouteMatch `locationName:"match" type:"structure" required:"true"` + // An object that represents an HTTP gateway route. + Http2Route *HttpGatewayRoute `locationName:"http2Route" type:"structure"` - // An object that represents a retry policy. Specify at least one value for - // at least one of the types of RetryEvents, a value for maxRetries, and a value - // for perRetryTimeout. - RetryPolicy *GrpcRetryPolicy `locationName:"retryPolicy" type:"structure"` + // An object that represents an HTTP gateway route. + HttpRoute *HttpGatewayRoute `locationName:"httpRoute" type:"structure"` } // String returns the string representation -func (s GrpcRoute) String() string { +func (s GatewayRouteSpec) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GrpcRoute) GoString() string { +func (s GatewayRouteSpec) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GrpcRoute) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GrpcRoute"} - if s.Action == nil { - invalidParams.Add(request.NewErrParamRequired("Action")) - } - if s.Match == nil { - invalidParams.Add(request.NewErrParamRequired("Match")) - } - if s.Action != nil { - if err := s.Action.Validate(); err != nil { - invalidParams.AddNested("Action", err.(request.ErrInvalidParams)) +func (s *GatewayRouteSpec) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GatewayRouteSpec"} + if s.GrpcRoute != nil { + if err := s.GrpcRoute.Validate(); err != nil { + invalidParams.AddNested("GrpcRoute", err.(request.ErrInvalidParams)) } } - if s.Match != nil { - if err := s.Match.Validate(); err != nil { - invalidParams.AddNested("Match", err.(request.ErrInvalidParams)) + if s.Http2Route != nil { + if err := s.Http2Route.Validate(); err != nil { + invalidParams.AddNested("Http2Route", err.(request.ErrInvalidParams)) } } - if s.RetryPolicy != nil { - if err := s.RetryPolicy.Validate(); err != nil { - invalidParams.AddNested("RetryPolicy", err.(request.ErrInvalidParams)) + if s.HttpRoute != nil { + if err := s.HttpRoute.Validate(); err != nil { + invalidParams.AddNested("HttpRoute", err.(request.ErrInvalidParams)) } } @@ -5615,59 +7519,77 @@ func (s *GrpcRoute) Validate() error { return nil } -// SetAction sets the Action field's value. -func (s *GrpcRoute) SetAction(v *GrpcRouteAction) *GrpcRoute { - s.Action = v +// SetGrpcRoute sets the GrpcRoute field's value. +func (s *GatewayRouteSpec) SetGrpcRoute(v *GrpcGatewayRoute) *GatewayRouteSpec { + s.GrpcRoute = v return s } -// SetMatch sets the Match field's value. -func (s *GrpcRoute) SetMatch(v *GrpcRouteMatch) *GrpcRoute { - s.Match = v +// SetHttp2Route sets the Http2Route field's value. +func (s *GatewayRouteSpec) SetHttp2Route(v *HttpGatewayRoute) *GatewayRouteSpec { + s.Http2Route = v return s } -// SetRetryPolicy sets the RetryPolicy field's value. -func (s *GrpcRoute) SetRetryPolicy(v *GrpcRetryPolicy) *GrpcRoute { - s.RetryPolicy = v +// SetHttpRoute sets the HttpRoute field's value. +func (s *GatewayRouteSpec) SetHttpRoute(v *HttpGatewayRoute) *GatewayRouteSpec { + s.HttpRoute = v return s } -// An object that represents the action to take if a match is determined. -type GrpcRouteAction struct { +// An object that represents the current status of a gateway route. +type GatewayRouteStatus struct { _ struct{} `type:"structure"` - // WeightedTargets is a required field - WeightedTargets []*WeightedTarget `locationName:"weightedTargets" min:"1" type:"list" required:"true"` + // Status is a required field + Status *string `locationName:"status" type:"string" required:"true" enum:"GatewayRouteStatusCode"` } // String returns the string representation -func (s GrpcRouteAction) String() string { +func (s GatewayRouteStatus) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GrpcRouteAction) GoString() string { +func (s GatewayRouteStatus) GoString() string { + return s.String() +} + +// SetStatus sets the Status field's value. +func (s *GatewayRouteStatus) SetStatus(v string) *GatewayRouteStatus { + s.Status = &v + return s +} + +// An object that represents a gateway route target. +type GatewayRouteTarget struct { + _ struct{} `type:"structure"` + + // An object that represents the virtual service that traffic is routed to. + // + // VirtualService is a required field + VirtualService *GatewayRouteVirtualService `locationName:"virtualService" type:"structure" required:"true"` +} + +// String returns the string representation +func (s GatewayRouteTarget) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GatewayRouteTarget) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GrpcRouteAction) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GrpcRouteAction"} - if s.WeightedTargets == nil { - invalidParams.Add(request.NewErrParamRequired("WeightedTargets")) +func (s *GatewayRouteTarget) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GatewayRouteTarget"} + if s.VirtualService == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualService")) } - if s.WeightedTargets != nil && len(s.WeightedTargets) < 1 { - invalidParams.Add(request.NewErrParamMinLen("WeightedTargets", 1)) - } - if s.WeightedTargets != nil { - for i, v := range s.WeightedTargets { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "WeightedTargets", i), err.(request.ErrInvalidParams)) - } + if s.VirtualService != nil { + if err := s.VirtualService.Validate(); err != nil { + invalidParams.AddNested("VirtualService", err.(request.ErrInvalidParams)) } } @@ -5677,51 +7599,38 @@ func (s *GrpcRouteAction) Validate() error { return nil } -// SetWeightedTargets sets the WeightedTargets field's value. -func (s *GrpcRouteAction) SetWeightedTargets(v []*WeightedTarget) *GrpcRouteAction { - s.WeightedTargets = v +// SetVirtualService sets the VirtualService field's value. +func (s *GatewayRouteTarget) SetVirtualService(v *GatewayRouteVirtualService) *GatewayRouteTarget { + s.VirtualService = v return s } -// An object that represents the criteria for determining a request match. -type GrpcRouteMatch struct { +// An object that represents the virtual service that traffic is routed to. +type GatewayRouteVirtualService struct { _ struct{} `type:"structure"` - Metadata []*GrpcRouteMetadata `locationName:"metadata" min:"1" type:"list"` - - MethodName *string `locationName:"methodName" min:"1" type:"string"` - - ServiceName *string `locationName:"serviceName" type:"string"` + // VirtualServiceName is a required field + VirtualServiceName *string `locationName:"virtualServiceName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s GrpcRouteMatch) String() string { +func (s GatewayRouteVirtualService) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GrpcRouteMatch) GoString() string { +func (s GatewayRouteVirtualService) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GrpcRouteMatch) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GrpcRouteMatch"} - if s.Metadata != nil && len(s.Metadata) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Metadata", 1)) - } - if s.MethodName != nil && len(*s.MethodName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MethodName", 1)) +func (s *GatewayRouteVirtualService) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GatewayRouteVirtualService"} + if s.VirtualServiceName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualServiceName")) } - if s.Metadata != nil { - for i, v := range s.Metadata { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Metadata", i), err.(request.ErrInvalidParams)) - } - } + if s.VirtualServiceName != nil && len(*s.VirtualServiceName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualServiceName", 1)) } if invalidParams.Len() > 0 { @@ -5730,59 +7639,49 @@ func (s *GrpcRouteMatch) Validate() error { return nil } -// SetMetadata sets the Metadata field's value. -func (s *GrpcRouteMatch) SetMetadata(v []*GrpcRouteMetadata) *GrpcRouteMatch { - s.Metadata = v +// SetVirtualServiceName sets the VirtualServiceName field's value. +func (s *GatewayRouteVirtualService) SetVirtualServiceName(v string) *GatewayRouteVirtualService { + s.VirtualServiceName = &v return s } -// SetMethodName sets the MethodName field's value. -func (s *GrpcRouteMatch) SetMethodName(v string) *GrpcRouteMatch { - s.MethodName = &v - return s -} - -// SetServiceName sets the ServiceName field's value. -func (s *GrpcRouteMatch) SetServiceName(v string) *GrpcRouteMatch { - s.ServiceName = &v - return s -} - -// An object that represents the match metadata for the route. -type GrpcRouteMetadata struct { +// An object that represents a gRPC gateway route. +type GrpcGatewayRoute struct { _ struct{} `type:"structure"` - Invert *bool `locationName:"invert" type:"boolean"` - - // An object that represents the match method. Specify one of the match values. - Match *GrpcRouteMetadataMatchMethod `locationName:"match" type:"structure"` + // An object that represents the action to take if a match is determined. + // + // Action is a required field + Action *GrpcGatewayRouteAction `locationName:"action" type:"structure" required:"true"` - // Name is a required field - Name *string `locationName:"name" min:"1" type:"string" required:"true"` + // An object that represents the criteria for determining a request match. + // + // Match is a required field + Match *GrpcGatewayRouteMatch `locationName:"match" type:"structure" required:"true"` } // String returns the string representation -func (s GrpcRouteMetadata) String() string { +func (s GrpcGatewayRoute) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GrpcRouteMetadata) GoString() string { +func (s GrpcGatewayRoute) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GrpcRouteMetadata) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GrpcRouteMetadata"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) +func (s *GrpcGatewayRoute) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GrpcGatewayRoute"} + if s.Action == nil { + invalidParams.Add(request.NewErrParamRequired("Action")) } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + if s.Match == nil { + invalidParams.Add(request.NewErrParamRequired("Match")) } - if s.Match != nil { - if err := s.Match.Validate(); err != nil { - invalidParams.AddNested("Match", err.(request.ErrInvalidParams)) + if s.Action != nil { + if err := s.Action.Validate(); err != nil { + invalidParams.AddNested("Action", err.(request.ErrInvalidParams)) } } @@ -5792,71 +7691,47 @@ func (s *GrpcRouteMetadata) Validate() error { return nil } -// SetInvert sets the Invert field's value. -func (s *GrpcRouteMetadata) SetInvert(v bool) *GrpcRouteMetadata { - s.Invert = &v +// SetAction sets the Action field's value. +func (s *GrpcGatewayRoute) SetAction(v *GrpcGatewayRouteAction) *GrpcGatewayRoute { + s.Action = v return s } // SetMatch sets the Match field's value. -func (s *GrpcRouteMetadata) SetMatch(v *GrpcRouteMetadataMatchMethod) *GrpcRouteMetadata { +func (s *GrpcGatewayRoute) SetMatch(v *GrpcGatewayRouteMatch) *GrpcGatewayRoute { s.Match = v return s } -// SetName sets the Name field's value. -func (s *GrpcRouteMetadata) SetName(v string) *GrpcRouteMetadata { - s.Name = &v - return s -} - -// An object that represents the match method. Specify one of the match values. -type GrpcRouteMetadataMatchMethod struct { +// An object that represents the action to take if a match is determined. +type GrpcGatewayRouteAction struct { _ struct{} `type:"structure"` - Exact *string `locationName:"exact" min:"1" type:"string"` - - Prefix *string `locationName:"prefix" min:"1" type:"string"` - - // An object that represents the range of values to match on. The first character - // of the range is included in the range, though the last character is not. - // For example, if the range specified were 1-100, only values 1-99 would be - // matched. - Range *MatchRange `locationName:"range" type:"structure"` - - Regex *string `locationName:"regex" min:"1" type:"string"` - - Suffix *string `locationName:"suffix" min:"1" type:"string"` + // An object that represents a gateway route target. + // + // Target is a required field + Target *GatewayRouteTarget `locationName:"target" type:"structure" required:"true"` } // String returns the string representation -func (s GrpcRouteMetadataMatchMethod) String() string { +func (s GrpcGatewayRouteAction) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GrpcRouteMetadataMatchMethod) GoString() string { +func (s GrpcGatewayRouteAction) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GrpcRouteMetadataMatchMethod) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GrpcRouteMetadataMatchMethod"} - if s.Exact != nil && len(*s.Exact) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Exact", 1)) - } - if s.Prefix != nil && len(*s.Prefix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Prefix", 1)) - } - if s.Regex != nil && len(*s.Regex) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Regex", 1)) - } - if s.Suffix != nil && len(*s.Suffix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Suffix", 1)) - } - if s.Range != nil { - if err := s.Range.Validate(); err != nil { - invalidParams.AddNested("Range", err.(request.ErrInvalidParams)) +func (s *GrpcGatewayRouteAction) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GrpcGatewayRouteAction"} + if s.Target == nil { + invalidParams.Add(request.NewErrParamRequired("Target")) + } + if s.Target != nil { + if err := s.Target.Validate(); err != nil { + invalidParams.AddNested("Target", err.(request.ErrInvalidParams)) } } @@ -5866,85 +7741,83 @@ func (s *GrpcRouteMetadataMatchMethod) Validate() error { return nil } -// SetExact sets the Exact field's value. -func (s *GrpcRouteMetadataMatchMethod) SetExact(v string) *GrpcRouteMetadataMatchMethod { - s.Exact = &v +// SetTarget sets the Target field's value. +func (s *GrpcGatewayRouteAction) SetTarget(v *GatewayRouteTarget) *GrpcGatewayRouteAction { + s.Target = v return s } -// SetPrefix sets the Prefix field's value. -func (s *GrpcRouteMetadataMatchMethod) SetPrefix(v string) *GrpcRouteMetadataMatchMethod { - s.Prefix = &v - return s +// An object that represents the criteria for determining a request match. +type GrpcGatewayRouteMatch struct { + _ struct{} `type:"structure"` + + ServiceName *string `locationName:"serviceName" type:"string"` } -// SetRange sets the Range field's value. -func (s *GrpcRouteMetadataMatchMethod) SetRange(v *MatchRange) *GrpcRouteMetadataMatchMethod { - s.Range = v - return s +// String returns the string representation +func (s GrpcGatewayRouteMatch) String() string { + return awsutil.Prettify(s) } -// SetRegex sets the Regex field's value. -func (s *GrpcRouteMetadataMatchMethod) SetRegex(v string) *GrpcRouteMetadataMatchMethod { - s.Regex = &v - return s +// GoString returns the string representation +func (s GrpcGatewayRouteMatch) GoString() string { + return s.String() } -// SetSuffix sets the Suffix field's value. -func (s *GrpcRouteMetadataMatchMethod) SetSuffix(v string) *GrpcRouteMetadataMatchMethod { - s.Suffix = &v +// SetServiceName sets the ServiceName field's value. +func (s *GrpcGatewayRouteMatch) SetServiceName(v string) *GrpcGatewayRouteMatch { + s.ServiceName = &v return s } -// An object that represents the method and value to match with the header value -// sent in a request. Specify one match method. -type HeaderMatchMethod struct { +// An object that represents a retry policy. Specify at least one value for +// at least one of the types of RetryEvents, a value for maxRetries, and a value +// for perRetryTimeout. +type GrpcRetryPolicy struct { _ struct{} `type:"structure"` - Exact *string `locationName:"exact" min:"1" type:"string"` + GrpcRetryEvents []*string `locationName:"grpcRetryEvents" min:"1" type:"list"` - Prefix *string `locationName:"prefix" min:"1" type:"string"` + HttpRetryEvents []*string `locationName:"httpRetryEvents" min:"1" type:"list"` - // An object that represents the range of values to match on. The first character - // of the range is included in the range, though the last character is not. - // For example, if the range specified were 1-100, only values 1-99 would be - // matched. - Range *MatchRange `locationName:"range" type:"structure"` + // MaxRetries is a required field + MaxRetries *int64 `locationName:"maxRetries" type:"long" required:"true"` - Regex *string `locationName:"regex" min:"1" type:"string"` + // An object that represents a duration of time. + // + // PerRetryTimeout is a required field + PerRetryTimeout *Duration `locationName:"perRetryTimeout" type:"structure" required:"true"` - Suffix *string `locationName:"suffix" min:"1" type:"string"` + TcpRetryEvents []*string `locationName:"tcpRetryEvents" min:"1" type:"list"` } // String returns the string representation -func (s HeaderMatchMethod) String() string { +func (s GrpcRetryPolicy) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s HeaderMatchMethod) GoString() string { +func (s GrpcRetryPolicy) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *HeaderMatchMethod) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HeaderMatchMethod"} - if s.Exact != nil && len(*s.Exact) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Exact", 1)) +func (s *GrpcRetryPolicy) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GrpcRetryPolicy"} + if s.GrpcRetryEvents != nil && len(s.GrpcRetryEvents) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GrpcRetryEvents", 1)) } - if s.Prefix != nil && len(*s.Prefix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Prefix", 1)) + if s.HttpRetryEvents != nil && len(s.HttpRetryEvents) < 1 { + invalidParams.Add(request.NewErrParamMinLen("HttpRetryEvents", 1)) } - if s.Regex != nil && len(*s.Regex) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Regex", 1)) + if s.MaxRetries == nil { + invalidParams.Add(request.NewErrParamRequired("MaxRetries")) } - if s.Suffix != nil && len(*s.Suffix) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Suffix", 1)) + if s.PerRetryTimeout == nil { + invalidParams.Add(request.NewErrParamRequired("PerRetryTimeout")) } - if s.Range != nil { - if err := s.Range.Validate(); err != nil { - invalidParams.AddNested("Range", err.(request.ErrInvalidParams)) - } + if s.TcpRetryEvents != nil && len(s.TcpRetryEvents) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TcpRetryEvents", 1)) } if invalidParams.Len() > 0 { @@ -5953,102 +7826,92 @@ func (s *HeaderMatchMethod) Validate() error { return nil } -// SetExact sets the Exact field's value. -func (s *HeaderMatchMethod) SetExact(v string) *HeaderMatchMethod { - s.Exact = &v +// SetGrpcRetryEvents sets the GrpcRetryEvents field's value. +func (s *GrpcRetryPolicy) SetGrpcRetryEvents(v []*string) *GrpcRetryPolicy { + s.GrpcRetryEvents = v return s } -// SetPrefix sets the Prefix field's value. -func (s *HeaderMatchMethod) SetPrefix(v string) *HeaderMatchMethod { - s.Prefix = &v +// SetHttpRetryEvents sets the HttpRetryEvents field's value. +func (s *GrpcRetryPolicy) SetHttpRetryEvents(v []*string) *GrpcRetryPolicy { + s.HttpRetryEvents = v return s } -// SetRange sets the Range field's value. -func (s *HeaderMatchMethod) SetRange(v *MatchRange) *HeaderMatchMethod { - s.Range = v +// SetMaxRetries sets the MaxRetries field's value. +func (s *GrpcRetryPolicy) SetMaxRetries(v int64) *GrpcRetryPolicy { + s.MaxRetries = &v return s } -// SetRegex sets the Regex field's value. -func (s *HeaderMatchMethod) SetRegex(v string) *HeaderMatchMethod { - s.Regex = &v +// SetPerRetryTimeout sets the PerRetryTimeout field's value. +func (s *GrpcRetryPolicy) SetPerRetryTimeout(v *Duration) *GrpcRetryPolicy { + s.PerRetryTimeout = v return s } -// SetSuffix sets the Suffix field's value. -func (s *HeaderMatchMethod) SetSuffix(v string) *HeaderMatchMethod { - s.Suffix = &v +// SetTcpRetryEvents sets the TcpRetryEvents field's value. +func (s *GrpcRetryPolicy) SetTcpRetryEvents(v []*string) *GrpcRetryPolicy { + s.TcpRetryEvents = v return s } -// An object that represents the health check policy for a virtual node's listener. -type HealthCheckPolicy struct { +// An object that represents a gRPC route type. +type GrpcRoute struct { _ struct{} `type:"structure"` - // HealthyThreshold is a required field - HealthyThreshold *int64 `locationName:"healthyThreshold" min:"2" type:"integer" required:"true"` - - // IntervalMillis is a required field - IntervalMillis *int64 `locationName:"intervalMillis" min:"5000" type:"long" required:"true"` - - Path *string `locationName:"path" type:"string"` - - Port *int64 `locationName:"port" min:"1" type:"integer"` + // An object that represents the action to take if a match is determined. + // + // Action is a required field + Action *GrpcRouteAction `locationName:"action" type:"structure" required:"true"` - // Protocol is a required field - Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"PortProtocol"` + // An object that represents the criteria for determining a request match. + // + // Match is a required field + Match *GrpcRouteMatch `locationName:"match" type:"structure" required:"true"` - // TimeoutMillis is a required field - TimeoutMillis *int64 `locationName:"timeoutMillis" min:"2000" type:"long" required:"true"` + // An object that represents a retry policy. Specify at least one value for + // at least one of the types of RetryEvents, a value for maxRetries, and a value + // for perRetryTimeout. + RetryPolicy *GrpcRetryPolicy `locationName:"retryPolicy" type:"structure"` - // UnhealthyThreshold is a required field - UnhealthyThreshold *int64 `locationName:"unhealthyThreshold" min:"2" type:"integer" required:"true"` + // An object that represents types of timeouts. + Timeout *GrpcTimeout `locationName:"timeout" type:"structure"` } // String returns the string representation -func (s HealthCheckPolicy) String() string { +func (s GrpcRoute) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s HealthCheckPolicy) GoString() string { +func (s GrpcRoute) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *HealthCheckPolicy) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HealthCheckPolicy"} - if s.HealthyThreshold == nil { - invalidParams.Add(request.NewErrParamRequired("HealthyThreshold")) +func (s *GrpcRoute) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GrpcRoute"} + if s.Action == nil { + invalidParams.Add(request.NewErrParamRequired("Action")) } - if s.HealthyThreshold != nil && *s.HealthyThreshold < 2 { - invalidParams.Add(request.NewErrParamMinValue("HealthyThreshold", 2)) + if s.Match == nil { + invalidParams.Add(request.NewErrParamRequired("Match")) } - if s.IntervalMillis == nil { - invalidParams.Add(request.NewErrParamRequired("IntervalMillis")) + if s.Action != nil { + if err := s.Action.Validate(); err != nil { + invalidParams.AddNested("Action", err.(request.ErrInvalidParams)) + } } - if s.IntervalMillis != nil && *s.IntervalMillis < 5000 { - invalidParams.Add(request.NewErrParamMinValue("IntervalMillis", 5000)) - } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) - } - if s.Protocol == nil { - invalidParams.Add(request.NewErrParamRequired("Protocol")) - } - if s.TimeoutMillis == nil { - invalidParams.Add(request.NewErrParamRequired("TimeoutMillis")) - } - if s.TimeoutMillis != nil && *s.TimeoutMillis < 2000 { - invalidParams.Add(request.NewErrParamMinValue("TimeoutMillis", 2000)) - } - if s.UnhealthyThreshold == nil { - invalidParams.Add(request.NewErrParamRequired("UnhealthyThreshold")) + if s.Match != nil { + if err := s.Match.Validate(); err != nil { + invalidParams.AddNested("Match", err.(request.ErrInvalidParams)) + } } - if s.UnhealthyThreshold != nil && *s.UnhealthyThreshold < 2 { - invalidParams.Add(request.NewErrParamMinValue("UnhealthyThreshold", 2)) + if s.RetryPolicy != nil { + if err := s.RetryPolicy.Validate(); err != nil { + invalidParams.AddNested("RetryPolicy", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -6057,91 +7920,119 @@ func (s *HealthCheckPolicy) Validate() error { return nil } -// SetHealthyThreshold sets the HealthyThreshold field's value. -func (s *HealthCheckPolicy) SetHealthyThreshold(v int64) *HealthCheckPolicy { - s.HealthyThreshold = &v +// SetAction sets the Action field's value. +func (s *GrpcRoute) SetAction(v *GrpcRouteAction) *GrpcRoute { + s.Action = v return s } -// SetIntervalMillis sets the IntervalMillis field's value. -func (s *HealthCheckPolicy) SetIntervalMillis(v int64) *HealthCheckPolicy { - s.IntervalMillis = &v +// SetMatch sets the Match field's value. +func (s *GrpcRoute) SetMatch(v *GrpcRouteMatch) *GrpcRoute { + s.Match = v return s } -// SetPath sets the Path field's value. -func (s *HealthCheckPolicy) SetPath(v string) *HealthCheckPolicy { - s.Path = &v +// SetRetryPolicy sets the RetryPolicy field's value. +func (s *GrpcRoute) SetRetryPolicy(v *GrpcRetryPolicy) *GrpcRoute { + s.RetryPolicy = v return s } -// SetPort sets the Port field's value. -func (s *HealthCheckPolicy) SetPort(v int64) *HealthCheckPolicy { - s.Port = &v +// SetTimeout sets the Timeout field's value. +func (s *GrpcRoute) SetTimeout(v *GrpcTimeout) *GrpcRoute { + s.Timeout = v return s } -// SetProtocol sets the Protocol field's value. -func (s *HealthCheckPolicy) SetProtocol(v string) *HealthCheckPolicy { - s.Protocol = &v - return s +// An object that represents the action to take if a match is determined. +type GrpcRouteAction struct { + _ struct{} `type:"structure"` + + // WeightedTargets is a required field + WeightedTargets []*WeightedTarget `locationName:"weightedTargets" min:"1" type:"list" required:"true"` } -// SetTimeoutMillis sets the TimeoutMillis field's value. -func (s *HealthCheckPolicy) SetTimeoutMillis(v int64) *HealthCheckPolicy { - s.TimeoutMillis = &v - return s +// String returns the string representation +func (s GrpcRouteAction) String() string { + return awsutil.Prettify(s) } -// SetUnhealthyThreshold sets the UnhealthyThreshold field's value. -func (s *HealthCheckPolicy) SetUnhealthyThreshold(v int64) *HealthCheckPolicy { - s.UnhealthyThreshold = &v +// GoString returns the string representation +func (s GrpcRouteAction) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GrpcRouteAction) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GrpcRouteAction"} + if s.WeightedTargets == nil { + invalidParams.Add(request.NewErrParamRequired("WeightedTargets")) + } + if s.WeightedTargets != nil && len(s.WeightedTargets) < 1 { + invalidParams.Add(request.NewErrParamMinLen("WeightedTargets", 1)) + } + if s.WeightedTargets != nil { + for i, v := range s.WeightedTargets { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "WeightedTargets", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetWeightedTargets sets the WeightedTargets field's value. +func (s *GrpcRouteAction) SetWeightedTargets(v []*WeightedTarget) *GrpcRouteAction { + s.WeightedTargets = v return s } -// An object that represents a retry policy. Specify at least one value for -// at least one of the types of RetryEvents, a value for maxRetries, and a value -// for perRetryTimeout. -type HttpRetryPolicy struct { +// An object that represents the criteria for determining a request match. +type GrpcRouteMatch struct { _ struct{} `type:"structure"` - HttpRetryEvents []*string `locationName:"httpRetryEvents" min:"1" type:"list"` - - // MaxRetries is a required field - MaxRetries *int64 `locationName:"maxRetries" type:"long" required:"true"` + Metadata []*GrpcRouteMetadata `locationName:"metadata" min:"1" type:"list"` - // An object that represents a duration of time. - // - // PerRetryTimeout is a required field - PerRetryTimeout *Duration `locationName:"perRetryTimeout" type:"structure" required:"true"` + MethodName *string `locationName:"methodName" min:"1" type:"string"` - TcpRetryEvents []*string `locationName:"tcpRetryEvents" min:"1" type:"list"` + ServiceName *string `locationName:"serviceName" type:"string"` } // String returns the string representation -func (s HttpRetryPolicy) String() string { +func (s GrpcRouteMatch) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s HttpRetryPolicy) GoString() string { +func (s GrpcRouteMatch) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *HttpRetryPolicy) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HttpRetryPolicy"} - if s.HttpRetryEvents != nil && len(s.HttpRetryEvents) < 1 { - invalidParams.Add(request.NewErrParamMinLen("HttpRetryEvents", 1)) - } - if s.MaxRetries == nil { - invalidParams.Add(request.NewErrParamRequired("MaxRetries")) +func (s *GrpcRouteMatch) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GrpcRouteMatch"} + if s.Metadata != nil && len(s.Metadata) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Metadata", 1)) } - if s.PerRetryTimeout == nil { - invalidParams.Add(request.NewErrParamRequired("PerRetryTimeout")) + if s.MethodName != nil && len(*s.MethodName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MethodName", 1)) } - if s.TcpRetryEvents != nil && len(s.TcpRetryEvents) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TcpRetryEvents", 1)) + if s.Metadata != nil { + for i, v := range s.Metadata { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Metadata", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -6150,85 +8041,61 @@ func (s *HttpRetryPolicy) Validate() error { return nil } -// SetHttpRetryEvents sets the HttpRetryEvents field's value. -func (s *HttpRetryPolicy) SetHttpRetryEvents(v []*string) *HttpRetryPolicy { - s.HttpRetryEvents = v - return s -} - -// SetMaxRetries sets the MaxRetries field's value. -func (s *HttpRetryPolicy) SetMaxRetries(v int64) *HttpRetryPolicy { - s.MaxRetries = &v +// SetMetadata sets the Metadata field's value. +func (s *GrpcRouteMatch) SetMetadata(v []*GrpcRouteMetadata) *GrpcRouteMatch { + s.Metadata = v return s } -// SetPerRetryTimeout sets the PerRetryTimeout field's value. -func (s *HttpRetryPolicy) SetPerRetryTimeout(v *Duration) *HttpRetryPolicy { - s.PerRetryTimeout = v +// SetMethodName sets the MethodName field's value. +func (s *GrpcRouteMatch) SetMethodName(v string) *GrpcRouteMatch { + s.MethodName = &v return s } -// SetTcpRetryEvents sets the TcpRetryEvents field's value. -func (s *HttpRetryPolicy) SetTcpRetryEvents(v []*string) *HttpRetryPolicy { - s.TcpRetryEvents = v +// SetServiceName sets the ServiceName field's value. +func (s *GrpcRouteMatch) SetServiceName(v string) *GrpcRouteMatch { + s.ServiceName = &v return s } -// An object that represents an HTTP or HTTP/2 route type. -type HttpRoute struct { +// An object that represents the match metadata for the route. +type GrpcRouteMetadata struct { _ struct{} `type:"structure"` - // An object that represents the action to take if a match is determined. - // - // Action is a required field - Action *HttpRouteAction `locationName:"action" type:"structure" required:"true"` + Invert *bool `locationName:"invert" type:"boolean"` - // An object that represents the requirements for a route to match HTTP requests - // for a virtual router. - // - // Match is a required field - Match *HttpRouteMatch `locationName:"match" type:"structure" required:"true"` + // An object that represents the match method. Specify one of the match values. + Match *GrpcRouteMetadataMatchMethod `locationName:"match" type:"structure"` - // An object that represents a retry policy. Specify at least one value for - // at least one of the types of RetryEvents, a value for maxRetries, and a value - // for perRetryTimeout. - RetryPolicy *HttpRetryPolicy `locationName:"retryPolicy" type:"structure"` + // Name is a required field + Name *string `locationName:"name" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s HttpRoute) String() string { +func (s GrpcRouteMetadata) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s HttpRoute) GoString() string { +func (s GrpcRouteMetadata) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *HttpRoute) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HttpRoute"} - if s.Action == nil { - invalidParams.Add(request.NewErrParamRequired("Action")) - } - if s.Match == nil { - invalidParams.Add(request.NewErrParamRequired("Match")) +func (s *GrpcRouteMetadata) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GrpcRouteMetadata"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) } - if s.Action != nil { - if err := s.Action.Validate(); err != nil { - invalidParams.AddNested("Action", err.(request.ErrInvalidParams)) - } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } if s.Match != nil { if err := s.Match.Validate(); err != nil { invalidParams.AddNested("Match", err.(request.ErrInvalidParams)) } } - if s.RetryPolicy != nil { - if err := s.RetryPolicy.Validate(); err != nil { - invalidParams.AddNested("RetryPolicy", err.(request.ErrInvalidParams)) - } - } if invalidParams.Len() > 0 { return invalidParams @@ -6236,59 +8103,71 @@ func (s *HttpRoute) Validate() error { return nil } -// SetAction sets the Action field's value. -func (s *HttpRoute) SetAction(v *HttpRouteAction) *HttpRoute { - s.Action = v +// SetInvert sets the Invert field's value. +func (s *GrpcRouteMetadata) SetInvert(v bool) *GrpcRouteMetadata { + s.Invert = &v return s } // SetMatch sets the Match field's value. -func (s *HttpRoute) SetMatch(v *HttpRouteMatch) *HttpRoute { +func (s *GrpcRouteMetadata) SetMatch(v *GrpcRouteMetadataMatchMethod) *GrpcRouteMetadata { s.Match = v return s } -// SetRetryPolicy sets the RetryPolicy field's value. -func (s *HttpRoute) SetRetryPolicy(v *HttpRetryPolicy) *HttpRoute { - s.RetryPolicy = v +// SetName sets the Name field's value. +func (s *GrpcRouteMetadata) SetName(v string) *GrpcRouteMetadata { + s.Name = &v return s } -// An object that represents the action to take if a match is determined. -type HttpRouteAction struct { +// An object that represents the match method. Specify one of the match values. +type GrpcRouteMetadataMatchMethod struct { _ struct{} `type:"structure"` - // WeightedTargets is a required field - WeightedTargets []*WeightedTarget `locationName:"weightedTargets" min:"1" type:"list" required:"true"` + Exact *string `locationName:"exact" min:"1" type:"string"` + + Prefix *string `locationName:"prefix" min:"1" type:"string"` + + // An object that represents the range of values to match on. The first character + // of the range is included in the range, though the last character is not. + // For example, if the range specified were 1-100, only values 1-99 would be + // matched. + Range *MatchRange `locationName:"range" type:"structure"` + + Regex *string `locationName:"regex" min:"1" type:"string"` + + Suffix *string `locationName:"suffix" min:"1" type:"string"` } // String returns the string representation -func (s HttpRouteAction) String() string { +func (s GrpcRouteMetadataMatchMethod) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s HttpRouteAction) GoString() string { +func (s GrpcRouteMetadataMatchMethod) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *HttpRouteAction) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HttpRouteAction"} - if s.WeightedTargets == nil { - invalidParams.Add(request.NewErrParamRequired("WeightedTargets")) +func (s *GrpcRouteMetadataMatchMethod) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GrpcRouteMetadataMatchMethod"} + if s.Exact != nil && len(*s.Exact) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Exact", 1)) } - if s.WeightedTargets != nil && len(s.WeightedTargets) < 1 { - invalidParams.Add(request.NewErrParamMinLen("WeightedTargets", 1)) + if s.Prefix != nil && len(*s.Prefix) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Prefix", 1)) } - if s.WeightedTargets != nil { - for i, v := range s.WeightedTargets { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "WeightedTargets", i), err.(request.ErrInvalidParams)) - } + if s.Regex != nil && len(*s.Regex) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Regex", 1)) + } + if s.Suffix != nil && len(*s.Suffix) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Suffix", 1)) + } + if s.Range != nil { + if err := s.Range.Validate(); err != nil { + invalidParams.AddNested("Range", err.(request.ErrInvalidParams)) } } @@ -6298,117 +8177,117 @@ func (s *HttpRouteAction) Validate() error { return nil } -// SetWeightedTargets sets the WeightedTargets field's value. -func (s *HttpRouteAction) SetWeightedTargets(v []*WeightedTarget) *HttpRouteAction { - s.WeightedTargets = v +// SetExact sets the Exact field's value. +func (s *GrpcRouteMetadataMatchMethod) SetExact(v string) *GrpcRouteMetadataMatchMethod { + s.Exact = &v return s } -// An object that represents the HTTP header in the request. -type HttpRouteHeader struct { - _ struct{} `type:"structure"` +// SetPrefix sets the Prefix field's value. +func (s *GrpcRouteMetadataMatchMethod) SetPrefix(v string) *GrpcRouteMetadataMatchMethod { + s.Prefix = &v + return s +} - Invert *bool `locationName:"invert" type:"boolean"` +// SetRange sets the Range field's value. +func (s *GrpcRouteMetadataMatchMethod) SetRange(v *MatchRange) *GrpcRouteMetadataMatchMethod { + s.Range = v + return s +} - // An object that represents the method and value to match with the header value - // sent in a request. Specify one match method. - Match *HeaderMatchMethod `locationName:"match" type:"structure"` +// SetRegex sets the Regex field's value. +func (s *GrpcRouteMetadataMatchMethod) SetRegex(v string) *GrpcRouteMetadataMatchMethod { + s.Regex = &v + return s +} - // Name is a required field - Name *string `locationName:"name" min:"1" type:"string" required:"true"` +// SetSuffix sets the Suffix field's value. +func (s *GrpcRouteMetadataMatchMethod) SetSuffix(v string) *GrpcRouteMetadataMatchMethod { + s.Suffix = &v + return s +} + +// An object that represents types of timeouts. +type GrpcTimeout struct { + _ struct{} `type:"structure"` + + // An object that represents a duration of time. + Idle *Duration `locationName:"idle" type:"structure"` + + // An object that represents a duration of time. + PerRequest *Duration `locationName:"perRequest" type:"structure"` } // String returns the string representation -func (s HttpRouteHeader) String() string { +func (s GrpcTimeout) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s HttpRouteHeader) GoString() string { +func (s GrpcTimeout) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *HttpRouteHeader) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HttpRouteHeader"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.Match != nil { - if err := s.Match.Validate(); err != nil { - invalidParams.AddNested("Match", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInvert sets the Invert field's value. -func (s *HttpRouteHeader) SetInvert(v bool) *HttpRouteHeader { - s.Invert = &v - return s -} - -// SetMatch sets the Match field's value. -func (s *HttpRouteHeader) SetMatch(v *HeaderMatchMethod) *HttpRouteHeader { - s.Match = v +// SetIdle sets the Idle field's value. +func (s *GrpcTimeout) SetIdle(v *Duration) *GrpcTimeout { + s.Idle = v return s } -// SetName sets the Name field's value. -func (s *HttpRouteHeader) SetName(v string) *HttpRouteHeader { - s.Name = &v +// SetPerRequest sets the PerRequest field's value. +func (s *GrpcTimeout) SetPerRequest(v *Duration) *GrpcTimeout { + s.PerRequest = v return s } -// An object that represents the requirements for a route to match HTTP requests -// for a virtual router. -type HttpRouteMatch struct { +// An object that represents the method and value to match with the header value +// sent in a request. Specify one match method. +type HeaderMatchMethod struct { _ struct{} `type:"structure"` - Headers []*HttpRouteHeader `locationName:"headers" min:"1" type:"list"` + Exact *string `locationName:"exact" min:"1" type:"string"` - Method *string `locationName:"method" type:"string" enum:"HttpMethod"` + Prefix *string `locationName:"prefix" min:"1" type:"string"` - // Prefix is a required field - Prefix *string `locationName:"prefix" type:"string" required:"true"` + // An object that represents the range of values to match on. The first character + // of the range is included in the range, though the last character is not. + // For example, if the range specified were 1-100, only values 1-99 would be + // matched. + Range *MatchRange `locationName:"range" type:"structure"` - Scheme *string `locationName:"scheme" type:"string" enum:"HttpScheme"` + Regex *string `locationName:"regex" min:"1" type:"string"` + + Suffix *string `locationName:"suffix" min:"1" type:"string"` } // String returns the string representation -func (s HttpRouteMatch) String() string { +func (s HeaderMatchMethod) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s HttpRouteMatch) GoString() string { +func (s HeaderMatchMethod) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *HttpRouteMatch) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HttpRouteMatch"} - if s.Headers != nil && len(s.Headers) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Headers", 1)) +func (s *HeaderMatchMethod) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HeaderMatchMethod"} + if s.Exact != nil && len(*s.Exact) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Exact", 1)) } - if s.Prefix == nil { - invalidParams.Add(request.NewErrParamRequired("Prefix")) + if s.Prefix != nil && len(*s.Prefix) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Prefix", 1)) } - if s.Headers != nil { - for i, v := range s.Headers { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Headers", i), err.(request.ErrInvalidParams)) - } + if s.Regex != nil && len(*s.Regex) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Regex", 1)) + } + if s.Suffix != nil && len(*s.Suffix) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Suffix", 1)) + } + if s.Range != nil { + if err := s.Range.Validate(); err != nil { + invalidParams.AddNested("Range", err.(request.ErrInvalidParams)) } } @@ -6418,168 +8297,195 @@ func (s *HttpRouteMatch) Validate() error { return nil } -// SetHeaders sets the Headers field's value. -func (s *HttpRouteMatch) SetHeaders(v []*HttpRouteHeader) *HttpRouteMatch { - s.Headers = v - return s -} - -// SetMethod sets the Method field's value. -func (s *HttpRouteMatch) SetMethod(v string) *HttpRouteMatch { - s.Method = &v +// SetExact sets the Exact field's value. +func (s *HeaderMatchMethod) SetExact(v string) *HeaderMatchMethod { + s.Exact = &v return s } // SetPrefix sets the Prefix field's value. -func (s *HttpRouteMatch) SetPrefix(v string) *HttpRouteMatch { +func (s *HeaderMatchMethod) SetPrefix(v string) *HeaderMatchMethod { s.Prefix = &v return s } -// SetScheme sets the Scheme field's value. -func (s *HttpRouteMatch) SetScheme(v string) *HttpRouteMatch { - s.Scheme = &v +// SetRange sets the Range field's value. +func (s *HeaderMatchMethod) SetRange(v *MatchRange) *HeaderMatchMethod { + s.Range = v return s } -// The request processing has failed because of an unknown error, exception, -// or failure. -type InternalServerErrorException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` +// SetRegex sets the Regex field's value. +func (s *HeaderMatchMethod) SetRegex(v string) *HeaderMatchMethod { + s.Regex = &v + return s } -// String returns the string representation -func (s InternalServerErrorException) String() string { - return awsutil.Prettify(s) +// SetSuffix sets the Suffix field's value. +func (s *HeaderMatchMethod) SetSuffix(v string) *HeaderMatchMethod { + s.Suffix = &v + return s } -// GoString returns the string representation -func (s InternalServerErrorException) GoString() string { - return s.String() -} +// An object that represents the health check policy for a virtual node's listener. +type HealthCheckPolicy struct { + _ struct{} `type:"structure"` -func newErrorInternalServerErrorException(v protocol.ResponseMetadata) error { - return &InternalServerErrorException{ - RespMetadata: v, - } -} + // HealthyThreshold is a required field + HealthyThreshold *int64 `locationName:"healthyThreshold" min:"2" type:"integer" required:"true"` -// Code returns the exception type name. -func (s *InternalServerErrorException) Code() string { - return "InternalServerErrorException" -} + // IntervalMillis is a required field + IntervalMillis *int64 `locationName:"intervalMillis" min:"5000" type:"long" required:"true"` -// Message returns the exception's message. -func (s *InternalServerErrorException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} + Path *string `locationName:"path" type:"string"` -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InternalServerErrorException) OrigErr() error { - return nil -} + Port *int64 `locationName:"port" min:"1" type:"integer"` -func (s *InternalServerErrorException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) + // Protocol is a required field + Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"PortProtocol"` + + // TimeoutMillis is a required field + TimeoutMillis *int64 `locationName:"timeoutMillis" min:"2000" type:"long" required:"true"` + + // UnhealthyThreshold is a required field + UnhealthyThreshold *int64 `locationName:"unhealthyThreshold" min:"2" type:"integer" required:"true"` } -// Status code returns the HTTP status code for the request's response error. -func (s *InternalServerErrorException) StatusCode() int { - return s.RespMetadata.StatusCode +// String returns the string representation +func (s HealthCheckPolicy) String() string { + return awsutil.Prettify(s) } -// RequestID returns the service's response RequestID for request. -func (s *InternalServerErrorException) RequestID() string { - return s.RespMetadata.RequestID +// GoString returns the string representation +func (s HealthCheckPolicy) GoString() string { + return s.String() } -// You have exceeded a service limit for your account. For more information, -// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service_limits.html) -// in the AWS App Mesh User Guide. -type LimitExceededException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} - -// String returns the string representation -func (s LimitExceededException) String() string { - return awsutil.Prettify(s) -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *HealthCheckPolicy) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HealthCheckPolicy"} + if s.HealthyThreshold == nil { + invalidParams.Add(request.NewErrParamRequired("HealthyThreshold")) + } + if s.HealthyThreshold != nil && *s.HealthyThreshold < 2 { + invalidParams.Add(request.NewErrParamMinValue("HealthyThreshold", 2)) + } + if s.IntervalMillis == nil { + invalidParams.Add(request.NewErrParamRequired("IntervalMillis")) + } + if s.IntervalMillis != nil && *s.IntervalMillis < 5000 { + invalidParams.Add(request.NewErrParamMinValue("IntervalMillis", 5000)) + } + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + } + if s.Protocol == nil { + invalidParams.Add(request.NewErrParamRequired("Protocol")) + } + if s.TimeoutMillis == nil { + invalidParams.Add(request.NewErrParamRequired("TimeoutMillis")) + } + if s.TimeoutMillis != nil && *s.TimeoutMillis < 2000 { + invalidParams.Add(request.NewErrParamMinValue("TimeoutMillis", 2000)) + } + if s.UnhealthyThreshold == nil { + invalidParams.Add(request.NewErrParamRequired("UnhealthyThreshold")) + } + if s.UnhealthyThreshold != nil && *s.UnhealthyThreshold < 2 { + invalidParams.Add(request.NewErrParamMinValue("UnhealthyThreshold", 2)) + } -// GoString returns the string representation -func (s LimitExceededException) GoString() string { - return s.String() + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -func newErrorLimitExceededException(v protocol.ResponseMetadata) error { - return &LimitExceededException{ - RespMetadata: v, - } +// SetHealthyThreshold sets the HealthyThreshold field's value. +func (s *HealthCheckPolicy) SetHealthyThreshold(v int64) *HealthCheckPolicy { + s.HealthyThreshold = &v + return s } -// Code returns the exception type name. -func (s *LimitExceededException) Code() string { - return "LimitExceededException" +// SetIntervalMillis sets the IntervalMillis field's value. +func (s *HealthCheckPolicy) SetIntervalMillis(v int64) *HealthCheckPolicy { + s.IntervalMillis = &v + return s } -// Message returns the exception's message. -func (s *LimitExceededException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" +// SetPath sets the Path field's value. +func (s *HealthCheckPolicy) SetPath(v string) *HealthCheckPolicy { + s.Path = &v + return s } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *LimitExceededException) OrigErr() error { - return nil +// SetPort sets the Port field's value. +func (s *HealthCheckPolicy) SetPort(v int64) *HealthCheckPolicy { + s.Port = &v + return s } -func (s *LimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +// SetProtocol sets the Protocol field's value. +func (s *HealthCheckPolicy) SetProtocol(v string) *HealthCheckPolicy { + s.Protocol = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *LimitExceededException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetTimeoutMillis sets the TimeoutMillis field's value. +func (s *HealthCheckPolicy) SetTimeoutMillis(v int64) *HealthCheckPolicy { + s.TimeoutMillis = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *LimitExceededException) RequestID() string { - return s.RespMetadata.RequestID +// SetUnhealthyThreshold sets the UnhealthyThreshold field's value. +func (s *HealthCheckPolicy) SetUnhealthyThreshold(v int64) *HealthCheckPolicy { + s.UnhealthyThreshold = &v + return s } -type ListMeshesInput struct { +// An object that represents an HTTP gateway route. +type HttpGatewayRoute struct { _ struct{} `type:"structure"` - Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` + // An object that represents the action to take if a match is determined. + // + // Action is a required field + Action *HttpGatewayRouteAction `locationName:"action" type:"structure" required:"true"` - NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` + // An object that represents the criteria for determining a request match. + // + // Match is a required field + Match *HttpGatewayRouteMatch `locationName:"match" type:"structure" required:"true"` } // String returns the string representation -func (s ListMeshesInput) String() string { +func (s HttpGatewayRoute) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListMeshesInput) GoString() string { +func (s HttpGatewayRoute) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListMeshesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListMeshesInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) +func (s *HttpGatewayRoute) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpGatewayRoute"} + if s.Action == nil { + invalidParams.Add(request.NewErrParamRequired("Action")) + } + if s.Match == nil { + invalidParams.Add(request.NewErrParamRequired("Match")) + } + if s.Action != nil { + if err := s.Action.Validate(); err != nil { + invalidParams.AddNested("Action", err.(request.ErrInvalidParams)) + } + } + if s.Match != nil { + if err := s.Match.Validate(); err != nil { + invalidParams.AddNested("Match", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -6588,95 +8494,85 @@ func (s *ListMeshesInput) Validate() error { return nil } -// SetLimit sets the Limit field's value. -func (s *ListMeshesInput) SetLimit(v int64) *ListMeshesInput { - s.Limit = &v +// SetAction sets the Action field's value. +func (s *HttpGatewayRoute) SetAction(v *HttpGatewayRouteAction) *HttpGatewayRoute { + s.Action = v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListMeshesInput) SetNextToken(v string) *ListMeshesInput { - s.NextToken = &v +// SetMatch sets the Match field's value. +func (s *HttpGatewayRoute) SetMatch(v *HttpGatewayRouteMatch) *HttpGatewayRoute { + s.Match = v return s } -type ListMeshesOutput struct { +// An object that represents the action to take if a match is determined. +type HttpGatewayRouteAction struct { _ struct{} `type:"structure"` - // Meshes is a required field - Meshes []*MeshRef `locationName:"meshes" type:"list" required:"true"` - - NextToken *string `locationName:"nextToken" type:"string"` + // An object that represents a gateway route target. + // + // Target is a required field + Target *GatewayRouteTarget `locationName:"target" type:"structure" required:"true"` } // String returns the string representation -func (s ListMeshesOutput) String() string { +func (s HttpGatewayRouteAction) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListMeshesOutput) GoString() string { +func (s HttpGatewayRouteAction) GoString() string { return s.String() } -// SetMeshes sets the Meshes field's value. -func (s *ListMeshesOutput) SetMeshes(v []*MeshRef) *ListMeshesOutput { - s.Meshes = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *HttpGatewayRouteAction) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpGatewayRouteAction"} + if s.Target == nil { + invalidParams.Add(request.NewErrParamRequired("Target")) + } + if s.Target != nil { + if err := s.Target.Validate(); err != nil { + invalidParams.AddNested("Target", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetNextToken sets the NextToken field's value. -func (s *ListMeshesOutput) SetNextToken(v string) *ListMeshesOutput { - s.NextToken = &v +// SetTarget sets the Target field's value. +func (s *HttpGatewayRouteAction) SetTarget(v *GatewayRouteTarget) *HttpGatewayRouteAction { + s.Target = v return s } -type ListRoutesInput struct { +// An object that represents the criteria for determining a request match. +type HttpGatewayRouteMatch struct { _ struct{} `type:"structure"` - Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` - - // MeshName is a required field - MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` - - MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - - NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` - - // VirtualRouterName is a required field - VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"` + // Prefix is a required field + Prefix *string `locationName:"prefix" type:"string" required:"true"` } // String returns the string representation -func (s ListRoutesInput) String() string { +func (s HttpGatewayRouteMatch) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListRoutesInput) GoString() string { +func (s HttpGatewayRouteMatch) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListRoutesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListRoutesInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.MeshName == nil { - invalidParams.Add(request.NewErrParamRequired("MeshName")) - } - if s.MeshName != nil && len(*s.MeshName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) - } - if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { - invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) - } - if s.VirtualRouterName == nil { - invalidParams.Add(request.NewErrParamRequired("VirtualRouterName")) - } - if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1)) +func (s *HttpGatewayRouteMatch) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpGatewayRouteMatch"} + if s.Prefix == nil { + invalidParams.Add(request.NewErrParamRequired("Prefix")) } if invalidParams.Len() > 0 { @@ -6685,96 +8581,144 @@ func (s *ListRoutesInput) Validate() error { return nil } -// SetLimit sets the Limit field's value. -func (s *ListRoutesInput) SetLimit(v int64) *ListRoutesInput { - s.Limit = &v - return s -} - -// SetMeshName sets the MeshName field's value. -func (s *ListRoutesInput) SetMeshName(v string) *ListRoutesInput { - s.MeshName = &v - return s -} - -// SetMeshOwner sets the MeshOwner field's value. -func (s *ListRoutesInput) SetMeshOwner(v string) *ListRoutesInput { - s.MeshOwner = &v +// SetPrefix sets the Prefix field's value. +func (s *HttpGatewayRouteMatch) SetPrefix(v string) *HttpGatewayRouteMatch { + s.Prefix = &v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListRoutesInput) SetNextToken(v string) *ListRoutesInput { - s.NextToken = &v - return s -} +// An object that represents a retry policy. Specify at least one value for +// at least one of the types of RetryEvents, a value for maxRetries, and a value +// for perRetryTimeout. +type HttpRetryPolicy struct { + _ struct{} `type:"structure"` -// SetVirtualRouterName sets the VirtualRouterName field's value. -func (s *ListRoutesInput) SetVirtualRouterName(v string) *ListRoutesInput { - s.VirtualRouterName = &v - return s -} + HttpRetryEvents []*string `locationName:"httpRetryEvents" min:"1" type:"list"` -type ListRoutesOutput struct { - _ struct{} `type:"structure"` + // MaxRetries is a required field + MaxRetries *int64 `locationName:"maxRetries" type:"long" required:"true"` - NextToken *string `locationName:"nextToken" type:"string"` + // An object that represents a duration of time. + // + // PerRetryTimeout is a required field + PerRetryTimeout *Duration `locationName:"perRetryTimeout" type:"structure" required:"true"` - // Routes is a required field - Routes []*RouteRef `locationName:"routes" type:"list" required:"true"` + TcpRetryEvents []*string `locationName:"tcpRetryEvents" min:"1" type:"list"` } // String returns the string representation -func (s ListRoutesOutput) String() string { +func (s HttpRetryPolicy) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListRoutesOutput) GoString() string { +func (s HttpRetryPolicy) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListRoutesOutput) SetNextToken(v string) *ListRoutesOutput { - s.NextToken = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *HttpRetryPolicy) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpRetryPolicy"} + if s.HttpRetryEvents != nil && len(s.HttpRetryEvents) < 1 { + invalidParams.Add(request.NewErrParamMinLen("HttpRetryEvents", 1)) + } + if s.MaxRetries == nil { + invalidParams.Add(request.NewErrParamRequired("MaxRetries")) + } + if s.PerRetryTimeout == nil { + invalidParams.Add(request.NewErrParamRequired("PerRetryTimeout")) + } + if s.TcpRetryEvents != nil && len(s.TcpRetryEvents) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TcpRetryEvents", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetHttpRetryEvents sets the HttpRetryEvents field's value. +func (s *HttpRetryPolicy) SetHttpRetryEvents(v []*string) *HttpRetryPolicy { + s.HttpRetryEvents = v return s } -// SetRoutes sets the Routes field's value. -func (s *ListRoutesOutput) SetRoutes(v []*RouteRef) *ListRoutesOutput { - s.Routes = v +// SetMaxRetries sets the MaxRetries field's value. +func (s *HttpRetryPolicy) SetMaxRetries(v int64) *HttpRetryPolicy { + s.MaxRetries = &v return s } -type ListTagsForResourceInput struct { +// SetPerRetryTimeout sets the PerRetryTimeout field's value. +func (s *HttpRetryPolicy) SetPerRetryTimeout(v *Duration) *HttpRetryPolicy { + s.PerRetryTimeout = v + return s +} + +// SetTcpRetryEvents sets the TcpRetryEvents field's value. +func (s *HttpRetryPolicy) SetTcpRetryEvents(v []*string) *HttpRetryPolicy { + s.TcpRetryEvents = v + return s +} + +// An object that represents an HTTP or HTTP/2 route type. +type HttpRoute struct { _ struct{} `type:"structure"` - Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` + // An object that represents the action to take if a match is determined. + // + // Action is a required field + Action *HttpRouteAction `locationName:"action" type:"structure" required:"true"` - NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` + // An object that represents the requirements for a route to match HTTP requests + // for a virtual router. + // + // Match is a required field + Match *HttpRouteMatch `locationName:"match" type:"structure" required:"true"` - // ResourceArn is a required field - ResourceArn *string `location:"querystring" locationName:"resourceArn" type:"string" required:"true"` + // An object that represents a retry policy. Specify at least one value for + // at least one of the types of RetryEvents, a value for maxRetries, and a value + // for perRetryTimeout. + RetryPolicy *HttpRetryPolicy `locationName:"retryPolicy" type:"structure"` + + // An object that represents types of timeouts. + Timeout *HttpTimeout `locationName:"timeout" type:"structure"` } // String returns the string representation -func (s ListTagsForResourceInput) String() string { +func (s HttpRoute) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListTagsForResourceInput) GoString() string { +func (s HttpRoute) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListTagsForResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) +func (s *HttpRoute) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpRoute"} + if s.Action == nil { + invalidParams.Add(request.NewErrParamRequired("Action")) } - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + if s.Match == nil { + invalidParams.Add(request.NewErrParamRequired("Match")) + } + if s.Action != nil { + if err := s.Action.Validate(); err != nil { + invalidParams.AddNested("Action", err.(request.ErrInvalidParams)) + } + } + if s.Match != nil { + if err := s.Match.Validate(); err != nil { + invalidParams.AddNested("Match", err.(request.ErrInvalidParams)) + } + } + if s.RetryPolicy != nil { + if err := s.RetryPolicy.Validate(); err != nil { + invalidParams.AddNested("RetryPolicy", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -6783,92 +8727,117 @@ func (s *ListTagsForResourceInput) Validate() error { return nil } -// SetLimit sets the Limit field's value. -func (s *ListTagsForResourceInput) SetLimit(v int64) *ListTagsForResourceInput { - s.Limit = &v +// SetAction sets the Action field's value. +func (s *HttpRoute) SetAction(v *HttpRouteAction) *HttpRoute { + s.Action = v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListTagsForResourceInput) SetNextToken(v string) *ListTagsForResourceInput { - s.NextToken = &v +// SetMatch sets the Match field's value. +func (s *HttpRoute) SetMatch(v *HttpRouteMatch) *HttpRoute { + s.Match = v return s } -// SetResourceArn sets the ResourceArn field's value. -func (s *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResourceInput { - s.ResourceArn = &v +// SetRetryPolicy sets the RetryPolicy field's value. +func (s *HttpRoute) SetRetryPolicy(v *HttpRetryPolicy) *HttpRoute { + s.RetryPolicy = v return s } -type ListTagsForResourceOutput struct { - _ struct{} `type:"structure"` +// SetTimeout sets the Timeout field's value. +func (s *HttpRoute) SetTimeout(v *HttpTimeout) *HttpRoute { + s.Timeout = v + return s +} - NextToken *string `locationName:"nextToken" type:"string"` +// An object that represents the action to take if a match is determined. +type HttpRouteAction struct { + _ struct{} `type:"structure"` - // Tags is a required field - Tags []*TagRef `locationName:"tags" type:"list" required:"true"` + // WeightedTargets is a required field + WeightedTargets []*WeightedTarget `locationName:"weightedTargets" min:"1" type:"list" required:"true"` } // String returns the string representation -func (s ListTagsForResourceOutput) String() string { +func (s HttpRouteAction) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListTagsForResourceOutput) GoString() string { +func (s HttpRouteAction) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListTagsForResourceOutput) SetNextToken(v string) *ListTagsForResourceOutput { - s.NextToken = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *HttpRouteAction) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpRouteAction"} + if s.WeightedTargets == nil { + invalidParams.Add(request.NewErrParamRequired("WeightedTargets")) + } + if s.WeightedTargets != nil && len(s.WeightedTargets) < 1 { + invalidParams.Add(request.NewErrParamMinLen("WeightedTargets", 1)) + } + if s.WeightedTargets != nil { + for i, v := range s.WeightedTargets { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "WeightedTargets", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetTags sets the Tags field's value. -func (s *ListTagsForResourceOutput) SetTags(v []*TagRef) *ListTagsForResourceOutput { - s.Tags = v +// SetWeightedTargets sets the WeightedTargets field's value. +func (s *HttpRouteAction) SetWeightedTargets(v []*WeightedTarget) *HttpRouteAction { + s.WeightedTargets = v return s } -type ListVirtualNodesInput struct { +// An object that represents the HTTP header in the request. +type HttpRouteHeader struct { _ struct{} `type:"structure"` - Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` - - // MeshName is a required field - MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + Invert *bool `locationName:"invert" type:"boolean"` - MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + // An object that represents the method and value to match with the header value + // sent in a request. Specify one match method. + Match *HeaderMatchMethod `locationName:"match" type:"structure"` - NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` + // Name is a required field + Name *string `locationName:"name" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s ListVirtualNodesInput) String() string { +func (s HttpRouteHeader) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListVirtualNodesInput) GoString() string { +func (s HttpRouteHeader) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListVirtualNodesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListVirtualNodesInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.MeshName == nil { - invalidParams.Add(request.NewErrParamRequired("MeshName")) +func (s *HttpRouteHeader) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpRouteHeader"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) } - if s.MeshName != nil && len(*s.MeshName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } - if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { - invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + if s.Match != nil { + if err := s.Match.Validate(); err != nil { + invalidParams.AddNested("Match", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -6877,162 +8846,248 @@ func (s *ListVirtualNodesInput) Validate() error { return nil } -// SetLimit sets the Limit field's value. -func (s *ListVirtualNodesInput) SetLimit(v int64) *ListVirtualNodesInput { - s.Limit = &v - return s -} - -// SetMeshName sets the MeshName field's value. -func (s *ListVirtualNodesInput) SetMeshName(v string) *ListVirtualNodesInput { - s.MeshName = &v +// SetInvert sets the Invert field's value. +func (s *HttpRouteHeader) SetInvert(v bool) *HttpRouteHeader { + s.Invert = &v return s } -// SetMeshOwner sets the MeshOwner field's value. -func (s *ListVirtualNodesInput) SetMeshOwner(v string) *ListVirtualNodesInput { - s.MeshOwner = &v +// SetMatch sets the Match field's value. +func (s *HttpRouteHeader) SetMatch(v *HeaderMatchMethod) *HttpRouteHeader { + s.Match = v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListVirtualNodesInput) SetNextToken(v string) *ListVirtualNodesInput { - s.NextToken = &v +// SetName sets the Name field's value. +func (s *HttpRouteHeader) SetName(v string) *HttpRouteHeader { + s.Name = &v return s } -type ListVirtualNodesOutput struct { +// An object that represents the requirements for a route to match HTTP requests +// for a virtual router. +type HttpRouteMatch struct { _ struct{} `type:"structure"` - NextToken *string `locationName:"nextToken" type:"string"` + Headers []*HttpRouteHeader `locationName:"headers" min:"1" type:"list"` - // VirtualNodes is a required field - VirtualNodes []*VirtualNodeRef `locationName:"virtualNodes" type:"list" required:"true"` + Method *string `locationName:"method" type:"string" enum:"HttpMethod"` + + // Prefix is a required field + Prefix *string `locationName:"prefix" type:"string" required:"true"` + + Scheme *string `locationName:"scheme" type:"string" enum:"HttpScheme"` } // String returns the string representation -func (s ListVirtualNodesOutput) String() string { +func (s HttpRouteMatch) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListVirtualNodesOutput) GoString() string { +func (s HttpRouteMatch) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListVirtualNodesOutput) SetNextToken(v string) *ListVirtualNodesOutput { - s.NextToken = &v - return s -} - -// SetVirtualNodes sets the VirtualNodes field's value. -func (s *ListVirtualNodesOutput) SetVirtualNodes(v []*VirtualNodeRef) *ListVirtualNodesOutput { - s.VirtualNodes = v +// Validate inspects the fields of the type to determine if they are valid. +func (s *HttpRouteMatch) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpRouteMatch"} + if s.Headers != nil && len(s.Headers) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Headers", 1)) + } + if s.Prefix == nil { + invalidParams.Add(request.NewErrParamRequired("Prefix")) + } + if s.Headers != nil { + for i, v := range s.Headers { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Headers", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetHeaders sets the Headers field's value. +func (s *HttpRouteMatch) SetHeaders(v []*HttpRouteHeader) *HttpRouteMatch { + s.Headers = v return s } -type ListVirtualRoutersInput struct { +// SetMethod sets the Method field's value. +func (s *HttpRouteMatch) SetMethod(v string) *HttpRouteMatch { + s.Method = &v + return s +} + +// SetPrefix sets the Prefix field's value. +func (s *HttpRouteMatch) SetPrefix(v string) *HttpRouteMatch { + s.Prefix = &v + return s +} + +// SetScheme sets the Scheme field's value. +func (s *HttpRouteMatch) SetScheme(v string) *HttpRouteMatch { + s.Scheme = &v + return s +} + +// An object that represents types of timeouts. +type HttpTimeout struct { _ struct{} `type:"structure"` - Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` + // An object that represents a duration of time. + Idle *Duration `locationName:"idle" type:"structure"` - // MeshName is a required field - MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + // An object that represents a duration of time. + PerRequest *Duration `locationName:"perRequest" type:"structure"` +} - MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` +// String returns the string representation +func (s HttpTimeout) String() string { + return awsutil.Prettify(s) +} - NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` +// GoString returns the string representation +func (s HttpTimeout) GoString() string { + return s.String() +} + +// SetIdle sets the Idle field's value. +func (s *HttpTimeout) SetIdle(v *Duration) *HttpTimeout { + s.Idle = v + return s +} + +// SetPerRequest sets the PerRequest field's value. +func (s *HttpTimeout) SetPerRequest(v *Duration) *HttpTimeout { + s.PerRequest = v + return s +} + +// The request processing has failed because of an unknown error, exception, +// or failure. +type InternalServerErrorException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` } // String returns the string representation -func (s ListVirtualRoutersInput) String() string { +func (s InternalServerErrorException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListVirtualRoutersInput) GoString() string { +func (s InternalServerErrorException) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListVirtualRoutersInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListVirtualRoutersInput"} - if s.Limit != nil && *s.Limit < 1 { - invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) - } - if s.MeshName == nil { - invalidParams.Add(request.NewErrParamRequired("MeshName")) - } - if s.MeshName != nil && len(*s.MeshName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) - } - if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { - invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) +func newErrorInternalServerErrorException(v protocol.ResponseMetadata) error { + return &InternalServerErrorException{ + RespMetadata: v, } +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// Code returns the exception type name. +func (s *InternalServerErrorException) Code() string { + return "InternalServerErrorException" } -// SetLimit sets the Limit field's value. -func (s *ListVirtualRoutersInput) SetLimit(v int64) *ListVirtualRoutersInput { - s.Limit = &v - return s +// Message returns the exception's message. +func (s *InternalServerErrorException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" } -// SetMeshName sets the MeshName field's value. -func (s *ListVirtualRoutersInput) SetMeshName(v string) *ListVirtualRoutersInput { - s.MeshName = &v - return s +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InternalServerErrorException) OrigErr() error { + return nil } -// SetMeshOwner sets the MeshOwner field's value. -func (s *ListVirtualRoutersInput) SetMeshOwner(v string) *ListVirtualRoutersInput { - s.MeshOwner = &v - return s +func (s *InternalServerErrorException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) } -// SetNextToken sets the NextToken field's value. -func (s *ListVirtualRoutersInput) SetNextToken(v string) *ListVirtualRoutersInput { - s.NextToken = &v - return s +// Status code returns the HTTP status code for the request's response error. +func (s *InternalServerErrorException) StatusCode() int { + return s.RespMetadata.StatusCode } -type ListVirtualRoutersOutput struct { - _ struct{} `type:"structure"` +// RequestID returns the service's response RequestID for request. +func (s *InternalServerErrorException) RequestID() string { + return s.RespMetadata.RequestID +} - NextToken *string `locationName:"nextToken" type:"string"` +// You have exceeded a service limit for your account. For more information, +// see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) +// in the AWS App Mesh User Guide. +type LimitExceededException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // VirtualRouters is a required field - VirtualRouters []*VirtualRouterRef `locationName:"virtualRouters" type:"list" required:"true"` + Message_ *string `locationName:"message" type:"string"` } // String returns the string representation -func (s ListVirtualRoutersOutput) String() string { +func (s LimitExceededException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListVirtualRoutersOutput) GoString() string { +func (s LimitExceededException) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListVirtualRoutersOutput) SetNextToken(v string) *ListVirtualRoutersOutput { - s.NextToken = &v - return s +func newErrorLimitExceededException(v protocol.ResponseMetadata) error { + return &LimitExceededException{ + RespMetadata: v, + } } -// SetVirtualRouters sets the VirtualRouters field's value. -func (s *ListVirtualRoutersOutput) SetVirtualRouters(v []*VirtualRouterRef) *ListVirtualRoutersOutput { - s.VirtualRouters = v - return s +// Code returns the exception type name. +func (s *LimitExceededException) Code() string { + return "LimitExceededException" } -type ListVirtualServicesInput struct { +// Message returns the exception's message. +func (s *LimitExceededException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *LimitExceededException) OrigErr() error { + return nil +} + +func (s *LimitExceededException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *LimitExceededException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *LimitExceededException) RequestID() string { + return s.RespMetadata.RequestID +} + +type ListGatewayRoutesInput struct { _ struct{} `type:"structure"` Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` @@ -7043,21 +9098,24 @@ type ListVirtualServicesInput struct { MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` + + // VirtualGatewayName is a required field + VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s ListVirtualServicesInput) String() string { +func (s ListGatewayRoutesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListVirtualServicesInput) GoString() string { +func (s ListGatewayRoutesInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListVirtualServicesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListVirtualServicesInput"} +func (s *ListGatewayRoutesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListGatewayRoutesInput"} if s.Limit != nil && *s.Limit < 1 { invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) } @@ -7070,6 +9128,12 @@ func (s *ListVirtualServicesInput) Validate() error { if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) } + if s.VirtualGatewayName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName")) + } + if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -7078,107 +9142,89 @@ func (s *ListVirtualServicesInput) Validate() error { } // SetLimit sets the Limit field's value. -func (s *ListVirtualServicesInput) SetLimit(v int64) *ListVirtualServicesInput { +func (s *ListGatewayRoutesInput) SetLimit(v int64) *ListGatewayRoutesInput { s.Limit = &v return s } // SetMeshName sets the MeshName field's value. -func (s *ListVirtualServicesInput) SetMeshName(v string) *ListVirtualServicesInput { +func (s *ListGatewayRoutesInput) SetMeshName(v string) *ListGatewayRoutesInput { s.MeshName = &v return s } // SetMeshOwner sets the MeshOwner field's value. -func (s *ListVirtualServicesInput) SetMeshOwner(v string) *ListVirtualServicesInput { +func (s *ListGatewayRoutesInput) SetMeshOwner(v string) *ListGatewayRoutesInput { s.MeshOwner = &v return s } // SetNextToken sets the NextToken field's value. -func (s *ListVirtualServicesInput) SetNextToken(v string) *ListVirtualServicesInput { +func (s *ListGatewayRoutesInput) SetNextToken(v string) *ListGatewayRoutesInput { s.NextToken = &v return s } -type ListVirtualServicesOutput struct { +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *ListGatewayRoutesInput) SetVirtualGatewayName(v string) *ListGatewayRoutesInput { + s.VirtualGatewayName = &v + return s +} + +type ListGatewayRoutesOutput struct { _ struct{} `type:"structure"` - NextToken *string `locationName:"nextToken" type:"string"` + // GatewayRoutes is a required field + GatewayRoutes []*GatewayRouteRef `locationName:"gatewayRoutes" type:"list" required:"true"` - // VirtualServices is a required field - VirtualServices []*VirtualServiceRef `locationName:"virtualServices" type:"list" required:"true"` + NextToken *string `locationName:"nextToken" type:"string"` } // String returns the string representation -func (s ListVirtualServicesOutput) String() string { +func (s ListGatewayRoutesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListVirtualServicesOutput) GoString() string { +func (s ListGatewayRoutesOutput) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListVirtualServicesOutput) SetNextToken(v string) *ListVirtualServicesOutput { - s.NextToken = &v +// SetGatewayRoutes sets the GatewayRoutes field's value. +func (s *ListGatewayRoutesOutput) SetGatewayRoutes(v []*GatewayRouteRef) *ListGatewayRoutesOutput { + s.GatewayRoutes = v return s } -// SetVirtualServices sets the VirtualServices field's value. -func (s *ListVirtualServicesOutput) SetVirtualServices(v []*VirtualServiceRef) *ListVirtualServicesOutput { - s.VirtualServices = v +// SetNextToken sets the NextToken field's value. +func (s *ListGatewayRoutesOutput) SetNextToken(v string) *ListGatewayRoutesOutput { + s.NextToken = &v return s } -// An object that represents a listener for a virtual node. -type Listener struct { +type ListMeshesInput struct { _ struct{} `type:"structure"` - // An object that represents the health check policy for a virtual node's listener. - HealthCheck *HealthCheckPolicy `locationName:"healthCheck" type:"structure"` - - // An object that represents a port mapping. - // - // PortMapping is a required field - PortMapping *PortMapping `locationName:"portMapping" type:"structure" required:"true"` + Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` - // An object that represents the Transport Layer Security (TLS) properties for - // a listener. - Tls *ListenerTls `locationName:"tls" type:"structure"` + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } // String returns the string representation -func (s Listener) String() string { +func (s ListMeshesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Listener) GoString() string { +func (s ListMeshesInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *Listener) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Listener"} - if s.PortMapping == nil { - invalidParams.Add(request.NewErrParamRequired("PortMapping")) - } - if s.HealthCheck != nil { - if err := s.HealthCheck.Validate(); err != nil { - invalidParams.AddNested("HealthCheck", err.(request.ErrInvalidParams)) - } - } - if s.PortMapping != nil { - if err := s.PortMapping.Validate(); err != nil { - invalidParams.AddNested("PortMapping", err.(request.ErrInvalidParams)) - } - } - if s.Tls != nil { - if err := s.Tls.Validate(); err != nil { - invalidParams.AddNested("Tls", err.(request.ErrInvalidParams)) - } +func (s *ListMeshesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListMeshesInput"} + if s.Limit != nil && *s.Limit < 1 { + invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) } if invalidParams.Len() > 0 { @@ -7187,104 +9233,95 @@ func (s *Listener) Validate() error { return nil } -// SetHealthCheck sets the HealthCheck field's value. -func (s *Listener) SetHealthCheck(v *HealthCheckPolicy) *Listener { - s.HealthCheck = v - return s -} - -// SetPortMapping sets the PortMapping field's value. -func (s *Listener) SetPortMapping(v *PortMapping) *Listener { - s.PortMapping = v +// SetLimit sets the Limit field's value. +func (s *ListMeshesInput) SetLimit(v int64) *ListMeshesInput { + s.Limit = &v return s } -// SetTls sets the Tls field's value. -func (s *Listener) SetTls(v *ListenerTls) *Listener { - s.Tls = v +// SetNextToken sets the NextToken field's value. +func (s *ListMeshesInput) SetNextToken(v string) *ListMeshesInput { + s.NextToken = &v return s } -// An object that represents the Transport Layer Security (TLS) properties for -// a listener. -type ListenerTls struct { +type ListMeshesOutput struct { _ struct{} `type:"structure"` - // An object that represents a listener's Transport Layer Security (TLS) certificate. - // - // Certificate is a required field - Certificate *ListenerTlsCertificate `locationName:"certificate" type:"structure" required:"true"` + // Meshes is a required field + Meshes []*MeshRef `locationName:"meshes" type:"list" required:"true"` - // Mode is a required field - Mode *string `locationName:"mode" type:"string" required:"true" enum:"ListenerTlsMode"` + NextToken *string `locationName:"nextToken" type:"string"` } // String returns the string representation -func (s ListenerTls) String() string { +func (s ListMeshesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListenerTls) GoString() string { +func (s ListMeshesOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListenerTls) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListenerTls"} - if s.Certificate == nil { - invalidParams.Add(request.NewErrParamRequired("Certificate")) - } - if s.Mode == nil { - invalidParams.Add(request.NewErrParamRequired("Mode")) - } - if s.Certificate != nil { - if err := s.Certificate.Validate(); err != nil { - invalidParams.AddNested("Certificate", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCertificate sets the Certificate field's value. -func (s *ListenerTls) SetCertificate(v *ListenerTlsCertificate) *ListenerTls { - s.Certificate = v +// SetMeshes sets the Meshes field's value. +func (s *ListMeshesOutput) SetMeshes(v []*MeshRef) *ListMeshesOutput { + s.Meshes = v return s } -// SetMode sets the Mode field's value. -func (s *ListenerTls) SetMode(v string) *ListenerTls { - s.Mode = &v +// SetNextToken sets the NextToken field's value. +func (s *ListMeshesOutput) SetNextToken(v string) *ListMeshesOutput { + s.NextToken = &v return s } -// An object that represents an AWS Certicate Manager (ACM) certificate. -type ListenerTlsAcmCertificate struct { +type ListRoutesInput struct { _ struct{} `type:"structure"` - // CertificateArn is a required field - CertificateArn *string `locationName:"certificateArn" type:"string" required:"true"` + Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` + + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` + + // VirtualRouterName is a required field + VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s ListenerTlsAcmCertificate) String() string { +func (s ListRoutesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListenerTlsAcmCertificate) GoString() string { +func (s ListRoutesInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListenerTlsAcmCertificate) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListenerTlsAcmCertificate"} - if s.CertificateArn == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateArn")) +func (s *ListRoutesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListRoutesInput"} + if s.Limit != nil && *s.Limit < 1 { + invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) + } + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.VirtualRouterName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualRouterName")) + } + if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1)) } if invalidParams.Len() > 0 { @@ -7293,104 +9330,96 @@ func (s *ListenerTlsAcmCertificate) Validate() error { return nil } -// SetCertificateArn sets the CertificateArn field's value. -func (s *ListenerTlsAcmCertificate) SetCertificateArn(v string) *ListenerTlsAcmCertificate { - s.CertificateArn = &v +// SetLimit sets the Limit field's value. +func (s *ListRoutesInput) SetLimit(v int64) *ListRoutesInput { + s.Limit = &v return s } -// An object that represents a listener's Transport Layer Security (TLS) certificate. -type ListenerTlsCertificate struct { +// SetMeshName sets the MeshName field's value. +func (s *ListRoutesInput) SetMeshName(v string) *ListRoutesInput { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *ListRoutesInput) SetMeshOwner(v string) *ListRoutesInput { + s.MeshOwner = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListRoutesInput) SetNextToken(v string) *ListRoutesInput { + s.NextToken = &v + return s +} + +// SetVirtualRouterName sets the VirtualRouterName field's value. +func (s *ListRoutesInput) SetVirtualRouterName(v string) *ListRoutesInput { + s.VirtualRouterName = &v + return s +} + +type ListRoutesOutput struct { _ struct{} `type:"structure"` - // An object that represents an AWS Certicate Manager (ACM) certificate. - Acm *ListenerTlsAcmCertificate `locationName:"acm" type:"structure"` + NextToken *string `locationName:"nextToken" type:"string"` - // An object that represents a local file certificate. The certificate must - // meet specific requirements and you must have proxy authorization enabled. - // For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual-node-tls.html#virtual-node-tls-prerequisites). - File *ListenerTlsFileCertificate `locationName:"file" type:"structure"` + // Routes is a required field + Routes []*RouteRef `locationName:"routes" type:"list" required:"true"` } // String returns the string representation -func (s ListenerTlsCertificate) String() string { +func (s ListRoutesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListenerTlsCertificate) GoString() string { +func (s ListRoutesOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListenerTlsCertificate) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListenerTlsCertificate"} - if s.Acm != nil { - if err := s.Acm.Validate(); err != nil { - invalidParams.AddNested("Acm", err.(request.ErrInvalidParams)) - } - } - if s.File != nil { - if err := s.File.Validate(); err != nil { - invalidParams.AddNested("File", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAcm sets the Acm field's value. -func (s *ListenerTlsCertificate) SetAcm(v *ListenerTlsAcmCertificate) *ListenerTlsCertificate { - s.Acm = v +// SetNextToken sets the NextToken field's value. +func (s *ListRoutesOutput) SetNextToken(v string) *ListRoutesOutput { + s.NextToken = &v return s } -// SetFile sets the File field's value. -func (s *ListenerTlsCertificate) SetFile(v *ListenerTlsFileCertificate) *ListenerTlsCertificate { - s.File = v +// SetRoutes sets the Routes field's value. +func (s *ListRoutesOutput) SetRoutes(v []*RouteRef) *ListRoutesOutput { + s.Routes = v return s } -// An object that represents a local file certificate. The certificate must -// meet specific requirements and you must have proxy authorization enabled. -// For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual-node-tls.html#virtual-node-tls-prerequisites). -type ListenerTlsFileCertificate struct { +type ListTagsForResourceInput struct { _ struct{} `type:"structure"` - // CertificateChain is a required field - CertificateChain *string `locationName:"certificateChain" min:"1" type:"string" required:"true"` + Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` - // PrivateKey is a required field - PrivateKey *string `locationName:"privateKey" min:"1" type:"string" required:"true"` + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` + + // ResourceArn is a required field + ResourceArn *string `location:"querystring" locationName:"resourceArn" type:"string" required:"true"` } // String returns the string representation -func (s ListenerTlsFileCertificate) String() string { +func (s ListTagsForResourceInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListenerTlsFileCertificate) GoString() string { +func (s ListTagsForResourceInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListenerTlsFileCertificate) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListenerTlsFileCertificate"} - if s.CertificateChain == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateChain")) - } - if s.CertificateChain != nil && len(*s.CertificateChain) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CertificateChain", 1)) - } - if s.PrivateKey == nil { - invalidParams.Add(request.NewErrParamRequired("PrivateKey")) +func (s *ListTagsForResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} + if s.Limit != nil && *s.Limit < 1 { + invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) } - if s.PrivateKey != nil && len(*s.PrivateKey) < 1 { - invalidParams.Add(request.NewErrParamMinLen("PrivateKey", 1)) + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) } if invalidParams.Len() > 0 { @@ -7399,89 +9428,92 @@ func (s *ListenerTlsFileCertificate) Validate() error { return nil } -// SetCertificateChain sets the CertificateChain field's value. -func (s *ListenerTlsFileCertificate) SetCertificateChain(v string) *ListenerTlsFileCertificate { - s.CertificateChain = &v +// SetLimit sets the Limit field's value. +func (s *ListTagsForResourceInput) SetLimit(v int64) *ListTagsForResourceInput { + s.Limit = &v return s } -// SetPrivateKey sets the PrivateKey field's value. -func (s *ListenerTlsFileCertificate) SetPrivateKey(v string) *ListenerTlsFileCertificate { - s.PrivateKey = &v +// SetNextToken sets the NextToken field's value. +func (s *ListTagsForResourceInput) SetNextToken(v string) *ListTagsForResourceInput { + s.NextToken = &v return s } -// An object that represents the logging information for a virtual node. -type Logging struct { +// SetResourceArn sets the ResourceArn field's value. +func (s *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResourceInput { + s.ResourceArn = &v + return s +} + +type ListTagsForResourceOutput struct { _ struct{} `type:"structure"` - // An object that represents the access logging information for a virtual node. - AccessLog *AccessLog `locationName:"accessLog" type:"structure"` + NextToken *string `locationName:"nextToken" type:"string"` + + // Tags is a required field + Tags []*TagRef `locationName:"tags" type:"list" required:"true"` } // String returns the string representation -func (s Logging) String() string { +func (s ListTagsForResourceOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Logging) GoString() string { +func (s ListTagsForResourceOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *Logging) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Logging"} - if s.AccessLog != nil { - if err := s.AccessLog.Validate(); err != nil { - invalidParams.AddNested("AccessLog", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetNextToken sets the NextToken field's value. +func (s *ListTagsForResourceOutput) SetNextToken(v string) *ListTagsForResourceOutput { + s.NextToken = &v + return s } -// SetAccessLog sets the AccessLog field's value. -func (s *Logging) SetAccessLog(v *AccessLog) *Logging { - s.AccessLog = v +// SetTags sets the Tags field's value. +func (s *ListTagsForResourceOutput) SetTags(v []*TagRef) *ListTagsForResourceOutput { + s.Tags = v return s } -// An object that represents the range of values to match on. The first character -// of the range is included in the range, though the last character is not. -// For example, if the range specified were 1-100, only values 1-99 would be -// matched. -type MatchRange struct { +type ListVirtualGatewaysInput struct { _ struct{} `type:"structure"` - // End is a required field - End *int64 `locationName:"end" type:"long" required:"true"` + Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` - // Start is a required field - Start *int64 `locationName:"start" type:"long" required:"true"` + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } // String returns the string representation -func (s MatchRange) String() string { +func (s ListVirtualGatewaysInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s MatchRange) GoString() string { +func (s ListVirtualGatewaysInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *MatchRange) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "MatchRange"} - if s.End == nil { - invalidParams.Add(request.NewErrParamRequired("End")) +func (s *ListVirtualGatewaysInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListVirtualGatewaysInput"} + if s.Limit != nil && *s.Limit < 1 { + invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) } - if s.Start == nil { - invalidParams.Add(request.NewErrParamRequired("Start")) + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) } if invalidParams.Len() > 0 { @@ -7490,276 +9522,2520 @@ func (s *MatchRange) Validate() error { return nil } -// SetEnd sets the End field's value. -func (s *MatchRange) SetEnd(v int64) *MatchRange { - s.End = &v +// SetLimit sets the Limit field's value. +func (s *ListVirtualGatewaysInput) SetLimit(v int64) *ListVirtualGatewaysInput { + s.Limit = &v return s } -// SetStart sets the Start field's value. -func (s *MatchRange) SetStart(v int64) *MatchRange { - s.Start = &v +// SetMeshName sets the MeshName field's value. +func (s *ListVirtualGatewaysInput) SetMeshName(v string) *ListVirtualGatewaysInput { + s.MeshName = &v return s } -// An object that represents a service mesh returned by a describe operation. -type MeshData struct { - _ struct{} `type:"structure"` +// SetMeshOwner sets the MeshOwner field's value. +func (s *ListVirtualGatewaysInput) SetMeshOwner(v string) *ListVirtualGatewaysInput { + s.MeshOwner = &v + return s +} - // MeshName is a required field - MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` +// SetNextToken sets the NextToken field's value. +func (s *ListVirtualGatewaysInput) SetNextToken(v string) *ListVirtualGatewaysInput { + s.NextToken = &v + return s +} - // An object that represents metadata for a resource. - // - // Metadata is a required field - Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"` +type ListVirtualGatewaysOutput struct { + _ struct{} `type:"structure"` - // An object that represents the specification of a service mesh. - // - // Spec is a required field - Spec *MeshSpec `locationName:"spec" type:"structure" required:"true"` + NextToken *string `locationName:"nextToken" type:"string"` - // An object that represents the status of a service mesh. - // - // Status is a required field - Status *MeshStatus `locationName:"status" type:"structure" required:"true"` + // VirtualGateways is a required field + VirtualGateways []*VirtualGatewayRef `locationName:"virtualGateways" type:"list" required:"true"` } // String returns the string representation -func (s MeshData) String() string { +func (s ListVirtualGatewaysOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s MeshData) GoString() string { +func (s ListVirtualGatewaysOutput) GoString() string { return s.String() } -// SetMeshName sets the MeshName field's value. -func (s *MeshData) SetMeshName(v string) *MeshData { - s.MeshName = &v - return s -} - -// SetMetadata sets the Metadata field's value. -func (s *MeshData) SetMetadata(v *ResourceMetadata) *MeshData { - s.Metadata = v - return s -} - -// SetSpec sets the Spec field's value. -func (s *MeshData) SetSpec(v *MeshSpec) *MeshData { - s.Spec = v +// SetNextToken sets the NextToken field's value. +func (s *ListVirtualGatewaysOutput) SetNextToken(v string) *ListVirtualGatewaysOutput { + s.NextToken = &v return s } -// SetStatus sets the Status field's value. -func (s *MeshData) SetStatus(v *MeshStatus) *MeshData { - s.Status = v +// SetVirtualGateways sets the VirtualGateways field's value. +func (s *ListVirtualGatewaysOutput) SetVirtualGateways(v []*VirtualGatewayRef) *ListVirtualGatewaysOutput { + s.VirtualGateways = v return s } -// An object that represents a service mesh returned by a list operation. -type MeshRef struct { +type ListVirtualNodesInput struct { _ struct{} `type:"structure"` - // Arn is a required field - Arn *string `locationName:"arn" type:"string" required:"true"` + Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` // MeshName is a required field - MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` - // MeshOwner is a required field - MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"` + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - // ResourceOwner is a required field - ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"` + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } // String returns the string representation -func (s MeshRef) String() string { +func (s ListVirtualNodesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s MeshRef) GoString() string { +func (s ListVirtualNodesInput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *MeshRef) SetArn(v string) *MeshRef { - s.Arn = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListVirtualNodesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListVirtualNodesInput"} + if s.Limit != nil && *s.Limit < 1 { + invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) + } + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLimit sets the Limit field's value. +func (s *ListVirtualNodesInput) SetLimit(v int64) *ListVirtualNodesInput { + s.Limit = &v return s } // SetMeshName sets the MeshName field's value. -func (s *MeshRef) SetMeshName(v string) *MeshRef { +func (s *ListVirtualNodesInput) SetMeshName(v string) *ListVirtualNodesInput { s.MeshName = &v return s } // SetMeshOwner sets the MeshOwner field's value. -func (s *MeshRef) SetMeshOwner(v string) *MeshRef { +func (s *ListVirtualNodesInput) SetMeshOwner(v string) *ListVirtualNodesInput { s.MeshOwner = &v return s } -// SetResourceOwner sets the ResourceOwner field's value. -func (s *MeshRef) SetResourceOwner(v string) *MeshRef { - s.ResourceOwner = &v +// SetNextToken sets the NextToken field's value. +func (s *ListVirtualNodesInput) SetNextToken(v string) *ListVirtualNodesInput { + s.NextToken = &v return s } -// An object that represents the specification of a service mesh. -type MeshSpec struct { +type ListVirtualNodesOutput struct { _ struct{} `type:"structure"` - // An object that represents the egress filter rules for a service mesh. - EgressFilter *EgressFilter `locationName:"egressFilter" type:"structure"` + NextToken *string `locationName:"nextToken" type:"string"` + + // VirtualNodes is a required field + VirtualNodes []*VirtualNodeRef `locationName:"virtualNodes" type:"list" required:"true"` } // String returns the string representation -func (s MeshSpec) String() string { +func (s ListVirtualNodesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s MeshSpec) GoString() string { +func (s ListVirtualNodesOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *MeshSpec) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "MeshSpec"} - if s.EgressFilter != nil { - if err := s.EgressFilter.Validate(); err != nil { - invalidParams.AddNested("EgressFilter", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetNextToken sets the NextToken field's value. +func (s *ListVirtualNodesOutput) SetNextToken(v string) *ListVirtualNodesOutput { + s.NextToken = &v + return s } -// SetEgressFilter sets the EgressFilter field's value. -func (s *MeshSpec) SetEgressFilter(v *EgressFilter) *MeshSpec { - s.EgressFilter = v +// SetVirtualNodes sets the VirtualNodes field's value. +func (s *ListVirtualNodesOutput) SetVirtualNodes(v []*VirtualNodeRef) *ListVirtualNodesOutput { + s.VirtualNodes = v return s } -// An object that represents the status of a service mesh. -type MeshStatus struct { +type ListVirtualRoutersInput struct { _ struct{} `type:"structure"` - Status *string `locationName:"status" type:"string" enum:"MeshStatusCode"` -} - -// String returns the string representation -func (s MeshStatus) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s MeshStatus) GoString() string { - return s.String() -} + Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` -// SetStatus sets the Status field's value. -func (s *MeshStatus) SetStatus(v string) *MeshStatus { - s.Status = &v - return s -} + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` -// The specified resource doesn't exist. Check your request syntax and try again. -type NotFoundException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - Message_ *string `locationName:"message" type:"string"` + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } // String returns the string representation -func (s NotFoundException) String() string { +func (s ListVirtualRoutersInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s NotFoundException) GoString() string { +func (s ListVirtualRoutersInput) GoString() string { return s.String() } -func newErrorNotFoundException(v protocol.ResponseMetadata) error { - return &NotFoundException{ - RespMetadata: v, - } +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListVirtualRoutersInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListVirtualRoutersInput"} + if s.Limit != nil && *s.Limit < 1 { + invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) + } + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLimit sets the Limit field's value. +func (s *ListVirtualRoutersInput) SetLimit(v int64) *ListVirtualRoutersInput { + s.Limit = &v + return s +} + +// SetMeshName sets the MeshName field's value. +func (s *ListVirtualRoutersInput) SetMeshName(v string) *ListVirtualRoutersInput { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *ListVirtualRoutersInput) SetMeshOwner(v string) *ListVirtualRoutersInput { + s.MeshOwner = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListVirtualRoutersInput) SetNextToken(v string) *ListVirtualRoutersInput { + s.NextToken = &v + return s +} + +type ListVirtualRoutersOutput struct { + _ struct{} `type:"structure"` + + NextToken *string `locationName:"nextToken" type:"string"` + + // VirtualRouters is a required field + VirtualRouters []*VirtualRouterRef `locationName:"virtualRouters" type:"list" required:"true"` +} + +// String returns the string representation +func (s ListVirtualRoutersOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListVirtualRoutersOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListVirtualRoutersOutput) SetNextToken(v string) *ListVirtualRoutersOutput { + s.NextToken = &v + return s +} + +// SetVirtualRouters sets the VirtualRouters field's value. +func (s *ListVirtualRoutersOutput) SetVirtualRouters(v []*VirtualRouterRef) *ListVirtualRoutersOutput { + s.VirtualRouters = v + return s +} + +type ListVirtualServicesInput struct { + _ struct{} `type:"structure"` + + Limit *int64 `location:"querystring" locationName:"limit" min:"1" type:"integer"` + + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s ListVirtualServicesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListVirtualServicesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListVirtualServicesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListVirtualServicesInput"} + if s.Limit != nil && *s.Limit < 1 { + invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) + } + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLimit sets the Limit field's value. +func (s *ListVirtualServicesInput) SetLimit(v int64) *ListVirtualServicesInput { + s.Limit = &v + return s +} + +// SetMeshName sets the MeshName field's value. +func (s *ListVirtualServicesInput) SetMeshName(v string) *ListVirtualServicesInput { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *ListVirtualServicesInput) SetMeshOwner(v string) *ListVirtualServicesInput { + s.MeshOwner = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListVirtualServicesInput) SetNextToken(v string) *ListVirtualServicesInput { + s.NextToken = &v + return s +} + +type ListVirtualServicesOutput struct { + _ struct{} `type:"structure"` + + NextToken *string `locationName:"nextToken" type:"string"` + + // VirtualServices is a required field + VirtualServices []*VirtualServiceRef `locationName:"virtualServices" type:"list" required:"true"` +} + +// String returns the string representation +func (s ListVirtualServicesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListVirtualServicesOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListVirtualServicesOutput) SetNextToken(v string) *ListVirtualServicesOutput { + s.NextToken = &v + return s +} + +// SetVirtualServices sets the VirtualServices field's value. +func (s *ListVirtualServicesOutput) SetVirtualServices(v []*VirtualServiceRef) *ListVirtualServicesOutput { + s.VirtualServices = v + return s +} + +// An object that represents a listener for a virtual node. +type Listener struct { + _ struct{} `type:"structure"` + + // An object that represents the health check policy for a virtual node's listener. + HealthCheck *HealthCheckPolicy `locationName:"healthCheck" type:"structure"` + + // An object that represents a port mapping. + // + // PortMapping is a required field + PortMapping *PortMapping `locationName:"portMapping" type:"structure" required:"true"` + + // An object that represents timeouts for different protocols. + Timeout *ListenerTimeout `locationName:"timeout" type:"structure"` + + // An object that represents the Transport Layer Security (TLS) properties for + // a listener. + Tls *ListenerTls `locationName:"tls" type:"structure"` +} + +// String returns the string representation +func (s Listener) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Listener) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Listener) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Listener"} + if s.PortMapping == nil { + invalidParams.Add(request.NewErrParamRequired("PortMapping")) + } + if s.HealthCheck != nil { + if err := s.HealthCheck.Validate(); err != nil { + invalidParams.AddNested("HealthCheck", err.(request.ErrInvalidParams)) + } + } + if s.PortMapping != nil { + if err := s.PortMapping.Validate(); err != nil { + invalidParams.AddNested("PortMapping", err.(request.ErrInvalidParams)) + } + } + if s.Tls != nil { + if err := s.Tls.Validate(); err != nil { + invalidParams.AddNested("Tls", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetHealthCheck sets the HealthCheck field's value. +func (s *Listener) SetHealthCheck(v *HealthCheckPolicy) *Listener { + s.HealthCheck = v + return s +} + +// SetPortMapping sets the PortMapping field's value. +func (s *Listener) SetPortMapping(v *PortMapping) *Listener { + s.PortMapping = v + return s +} + +// SetTimeout sets the Timeout field's value. +func (s *Listener) SetTimeout(v *ListenerTimeout) *Listener { + s.Timeout = v + return s +} + +// SetTls sets the Tls field's value. +func (s *Listener) SetTls(v *ListenerTls) *Listener { + s.Tls = v + return s +} + +// An object that represents timeouts for different protocols. +type ListenerTimeout struct { + _ struct{} `type:"structure"` + + // An object that represents types of timeouts. + Grpc *GrpcTimeout `locationName:"grpc" type:"structure"` + + // An object that represents types of timeouts. + Http *HttpTimeout `locationName:"http" type:"structure"` + + // An object that represents types of timeouts. + Http2 *HttpTimeout `locationName:"http2" type:"structure"` + + // An object that represents types of timeouts. + Tcp *TcpTimeout `locationName:"tcp" type:"structure"` +} + +// String returns the string representation +func (s ListenerTimeout) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListenerTimeout) GoString() string { + return s.String() +} + +// SetGrpc sets the Grpc field's value. +func (s *ListenerTimeout) SetGrpc(v *GrpcTimeout) *ListenerTimeout { + s.Grpc = v + return s +} + +// SetHttp sets the Http field's value. +func (s *ListenerTimeout) SetHttp(v *HttpTimeout) *ListenerTimeout { + s.Http = v + return s +} + +// SetHttp2 sets the Http2 field's value. +func (s *ListenerTimeout) SetHttp2(v *HttpTimeout) *ListenerTimeout { + s.Http2 = v + return s +} + +// SetTcp sets the Tcp field's value. +func (s *ListenerTimeout) SetTcp(v *TcpTimeout) *ListenerTimeout { + s.Tcp = v + return s +} + +// An object that represents the Transport Layer Security (TLS) properties for +// a listener. +type ListenerTls struct { + _ struct{} `type:"structure"` + + // An object that represents a listener's Transport Layer Security (TLS) certificate. + // + // Certificate is a required field + Certificate *ListenerTlsCertificate `locationName:"certificate" type:"structure" required:"true"` + + // Mode is a required field + Mode *string `locationName:"mode" type:"string" required:"true" enum:"ListenerTlsMode"` +} + +// String returns the string representation +func (s ListenerTls) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListenerTls) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListenerTls) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListenerTls"} + if s.Certificate == nil { + invalidParams.Add(request.NewErrParamRequired("Certificate")) + } + if s.Mode == nil { + invalidParams.Add(request.NewErrParamRequired("Mode")) + } + if s.Certificate != nil { + if err := s.Certificate.Validate(); err != nil { + invalidParams.AddNested("Certificate", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCertificate sets the Certificate field's value. +func (s *ListenerTls) SetCertificate(v *ListenerTlsCertificate) *ListenerTls { + s.Certificate = v + return s +} + +// SetMode sets the Mode field's value. +func (s *ListenerTls) SetMode(v string) *ListenerTls { + s.Mode = &v + return s +} + +// An object that represents an AWS Certicate Manager (ACM) certificate. +type ListenerTlsAcmCertificate struct { + _ struct{} `type:"structure"` + + // CertificateArn is a required field + CertificateArn *string `locationName:"certificateArn" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListenerTlsAcmCertificate) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListenerTlsAcmCertificate) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListenerTlsAcmCertificate) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListenerTlsAcmCertificate"} + if s.CertificateArn == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateArn")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCertificateArn sets the CertificateArn field's value. +func (s *ListenerTlsAcmCertificate) SetCertificateArn(v string) *ListenerTlsAcmCertificate { + s.CertificateArn = &v + return s +} + +// An object that represents a listener's Transport Layer Security (TLS) certificate. +type ListenerTlsCertificate struct { + _ struct{} `type:"structure"` + + // An object that represents an AWS Certicate Manager (ACM) certificate. + Acm *ListenerTlsAcmCertificate `locationName:"acm" type:"structure"` + + // An object that represents a local file certificate. The certificate must + // meet specific requirements and you must have proxy authorization enabled. + // For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html#virtual-node-tls-prerequisites). + File *ListenerTlsFileCertificate `locationName:"file" type:"structure"` +} + +// String returns the string representation +func (s ListenerTlsCertificate) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListenerTlsCertificate) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListenerTlsCertificate) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListenerTlsCertificate"} + if s.Acm != nil { + if err := s.Acm.Validate(); err != nil { + invalidParams.AddNested("Acm", err.(request.ErrInvalidParams)) + } + } + if s.File != nil { + if err := s.File.Validate(); err != nil { + invalidParams.AddNested("File", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAcm sets the Acm field's value. +func (s *ListenerTlsCertificate) SetAcm(v *ListenerTlsAcmCertificate) *ListenerTlsCertificate { + s.Acm = v + return s +} + +// SetFile sets the File field's value. +func (s *ListenerTlsCertificate) SetFile(v *ListenerTlsFileCertificate) *ListenerTlsCertificate { + s.File = v + return s +} + +// An object that represents a local file certificate. The certificate must +// meet specific requirements and you must have proxy authorization enabled. +// For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html#virtual-node-tls-prerequisites). +type ListenerTlsFileCertificate struct { + _ struct{} `type:"structure"` + + // CertificateChain is a required field + CertificateChain *string `locationName:"certificateChain" min:"1" type:"string" required:"true"` + + // PrivateKey is a required field + PrivateKey *string `locationName:"privateKey" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListenerTlsFileCertificate) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListenerTlsFileCertificate) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListenerTlsFileCertificate) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListenerTlsFileCertificate"} + if s.CertificateChain == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateChain")) + } + if s.CertificateChain != nil && len(*s.CertificateChain) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CertificateChain", 1)) + } + if s.PrivateKey == nil { + invalidParams.Add(request.NewErrParamRequired("PrivateKey")) + } + if s.PrivateKey != nil && len(*s.PrivateKey) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PrivateKey", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCertificateChain sets the CertificateChain field's value. +func (s *ListenerTlsFileCertificate) SetCertificateChain(v string) *ListenerTlsFileCertificate { + s.CertificateChain = &v + return s +} + +// SetPrivateKey sets the PrivateKey field's value. +func (s *ListenerTlsFileCertificate) SetPrivateKey(v string) *ListenerTlsFileCertificate { + s.PrivateKey = &v + return s +} + +// An object that represents the logging information for a virtual node. +type Logging struct { + _ struct{} `type:"structure"` + + // An object that represents the access logging information for a virtual node. + AccessLog *AccessLog `locationName:"accessLog" type:"structure"` +} + +// String returns the string representation +func (s Logging) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Logging) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Logging) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Logging"} + if s.AccessLog != nil { + if err := s.AccessLog.Validate(); err != nil { + invalidParams.AddNested("AccessLog", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAccessLog sets the AccessLog field's value. +func (s *Logging) SetAccessLog(v *AccessLog) *Logging { + s.AccessLog = v + return s +} + +// An object that represents the range of values to match on. The first character +// of the range is included in the range, though the last character is not. +// For example, if the range specified were 1-100, only values 1-99 would be +// matched. +type MatchRange struct { + _ struct{} `type:"structure"` + + // End is a required field + End *int64 `locationName:"end" type:"long" required:"true"` + + // Start is a required field + Start *int64 `locationName:"start" type:"long" required:"true"` +} + +// String returns the string representation +func (s MatchRange) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MatchRange) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *MatchRange) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "MatchRange"} + if s.End == nil { + invalidParams.Add(request.NewErrParamRequired("End")) + } + if s.Start == nil { + invalidParams.Add(request.NewErrParamRequired("Start")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetEnd sets the End field's value. +func (s *MatchRange) SetEnd(v int64) *MatchRange { + s.End = &v + return s +} + +// SetStart sets the Start field's value. +func (s *MatchRange) SetStart(v int64) *MatchRange { + s.Start = &v + return s +} + +// An object that represents a service mesh returned by a describe operation. +type MeshData struct { + _ struct{} `type:"structure"` + + // MeshName is a required field + MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` + + // An object that represents metadata for a resource. + // + // Metadata is a required field + Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"` + + // An object that represents the specification of a service mesh. + // + // Spec is a required field + Spec *MeshSpec `locationName:"spec" type:"structure" required:"true"` + + // An object that represents the status of a service mesh. + // + // Status is a required field + Status *MeshStatus `locationName:"status" type:"structure" required:"true"` +} + +// String returns the string representation +func (s MeshData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MeshData) GoString() string { + return s.String() +} + +// SetMeshName sets the MeshName field's value. +func (s *MeshData) SetMeshName(v string) *MeshData { + s.MeshName = &v + return s +} + +// SetMetadata sets the Metadata field's value. +func (s *MeshData) SetMetadata(v *ResourceMetadata) *MeshData { + s.Metadata = v + return s +} + +// SetSpec sets the Spec field's value. +func (s *MeshData) SetSpec(v *MeshSpec) *MeshData { + s.Spec = v + return s +} + +// SetStatus sets the Status field's value. +func (s *MeshData) SetStatus(v *MeshStatus) *MeshData { + s.Status = v + return s +} + +// An object that represents a service mesh returned by a list operation. +type MeshRef struct { + _ struct{} `type:"structure"` + + // Arn is a required field + Arn *string `locationName:"arn" type:"string" required:"true"` + + // CreatedAt is a required field + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"` + + // LastUpdatedAt is a required field + LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"` + + // MeshName is a required field + MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` + + // MeshOwner is a required field + MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"` + + // ResourceOwner is a required field + ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"` + + // Version is a required field + Version *int64 `locationName:"version" type:"long" required:"true"` +} + +// String returns the string representation +func (s MeshRef) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MeshRef) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *MeshRef) SetArn(v string) *MeshRef { + s.Arn = &v + return s +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *MeshRef) SetCreatedAt(v time.Time) *MeshRef { + s.CreatedAt = &v + return s +} + +// SetLastUpdatedAt sets the LastUpdatedAt field's value. +func (s *MeshRef) SetLastUpdatedAt(v time.Time) *MeshRef { + s.LastUpdatedAt = &v + return s +} + +// SetMeshName sets the MeshName field's value. +func (s *MeshRef) SetMeshName(v string) *MeshRef { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *MeshRef) SetMeshOwner(v string) *MeshRef { + s.MeshOwner = &v + return s +} + +// SetResourceOwner sets the ResourceOwner field's value. +func (s *MeshRef) SetResourceOwner(v string) *MeshRef { + s.ResourceOwner = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *MeshRef) SetVersion(v int64) *MeshRef { + s.Version = &v + return s +} + +// An object that represents the specification of a service mesh. +type MeshSpec struct { + _ struct{} `type:"structure"` + + // An object that represents the egress filter rules for a service mesh. + EgressFilter *EgressFilter `locationName:"egressFilter" type:"structure"` +} + +// String returns the string representation +func (s MeshSpec) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MeshSpec) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *MeshSpec) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "MeshSpec"} + if s.EgressFilter != nil { + if err := s.EgressFilter.Validate(); err != nil { + invalidParams.AddNested("EgressFilter", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetEgressFilter sets the EgressFilter field's value. +func (s *MeshSpec) SetEgressFilter(v *EgressFilter) *MeshSpec { + s.EgressFilter = v + return s +} + +// An object that represents the status of a service mesh. +type MeshStatus struct { + _ struct{} `type:"structure"` + + Status *string `locationName:"status" type:"string" enum:"MeshStatusCode"` +} + +// String returns the string representation +func (s MeshStatus) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MeshStatus) GoString() string { + return s.String() +} + +// SetStatus sets the Status field's value. +func (s *MeshStatus) SetStatus(v string) *MeshStatus { + s.Status = &v + return s +} + +// The specified resource doesn't exist. Check your request syntax and try again. +type NotFoundException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s NotFoundException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s NotFoundException) GoString() string { + return s.String() +} + +func newErrorNotFoundException(v protocol.ResponseMetadata) error { + return &NotFoundException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *NotFoundException) Code() string { + return "NotFoundException" +} + +// Message returns the exception's message. +func (s *NotFoundException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *NotFoundException) OrigErr() error { + return nil +} + +func (s *NotFoundException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *NotFoundException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *NotFoundException) RequestID() string { + return s.RespMetadata.RequestID +} + +// An object that represents a port mapping. +type PortMapping struct { + _ struct{} `type:"structure"` + + // Port is a required field + Port *int64 `locationName:"port" min:"1" type:"integer" required:"true"` + + // Protocol is a required field + Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"PortProtocol"` +} + +// String returns the string representation +func (s PortMapping) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PortMapping) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PortMapping) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PortMapping"} + if s.Port == nil { + invalidParams.Add(request.NewErrParamRequired("Port")) + } + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + } + if s.Protocol == nil { + invalidParams.Add(request.NewErrParamRequired("Protocol")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetPort sets the Port field's value. +func (s *PortMapping) SetPort(v int64) *PortMapping { + s.Port = &v + return s +} + +// SetProtocol sets the Protocol field's value. +func (s *PortMapping) SetProtocol(v string) *PortMapping { + s.Protocol = &v + return s +} + +// You can't delete the specified resource because it's in use or required by +// another resource. +type ResourceInUseException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ResourceInUseException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResourceInUseException) GoString() string { + return s.String() +} + +func newErrorResourceInUseException(v protocol.ResponseMetadata) error { + return &ResourceInUseException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ResourceInUseException) Code() string { + return "ResourceInUseException" +} + +// Message returns the exception's message. +func (s *ResourceInUseException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ResourceInUseException) OrigErr() error { + return nil +} + +func (s *ResourceInUseException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ResourceInUseException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ResourceInUseException) RequestID() string { + return s.RespMetadata.RequestID +} + +// An object that represents metadata for a resource. +type ResourceMetadata struct { + _ struct{} `type:"structure"` + + // Arn is a required field + Arn *string `locationName:"arn" type:"string" required:"true"` + + // CreatedAt is a required field + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"` + + // LastUpdatedAt is a required field + LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"` + + // MeshOwner is a required field + MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"` + + // ResourceOwner is a required field + ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"` + + // Uid is a required field + Uid *string `locationName:"uid" type:"string" required:"true"` + + // Version is a required field + Version *int64 `locationName:"version" type:"long" required:"true"` +} + +// String returns the string representation +func (s ResourceMetadata) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResourceMetadata) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *ResourceMetadata) SetArn(v string) *ResourceMetadata { + s.Arn = &v + return s +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *ResourceMetadata) SetCreatedAt(v time.Time) *ResourceMetadata { + s.CreatedAt = &v + return s +} + +// SetLastUpdatedAt sets the LastUpdatedAt field's value. +func (s *ResourceMetadata) SetLastUpdatedAt(v time.Time) *ResourceMetadata { + s.LastUpdatedAt = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *ResourceMetadata) SetMeshOwner(v string) *ResourceMetadata { + s.MeshOwner = &v + return s +} + +// SetResourceOwner sets the ResourceOwner field's value. +func (s *ResourceMetadata) SetResourceOwner(v string) *ResourceMetadata { + s.ResourceOwner = &v + return s +} + +// SetUid sets the Uid field's value. +func (s *ResourceMetadata) SetUid(v string) *ResourceMetadata { + s.Uid = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *ResourceMetadata) SetVersion(v int64) *ResourceMetadata { + s.Version = &v + return s +} + +// An object that represents a route returned by a describe operation. +type RouteData struct { + _ struct{} `type:"structure"` + + // MeshName is a required field + MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` + + // An object that represents metadata for a resource. + // + // Metadata is a required field + Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"` + + // RouteName is a required field + RouteName *string `locationName:"routeName" min:"1" type:"string" required:"true"` + + // An object that represents a route specification. Specify one route type. + // + // Spec is a required field + Spec *RouteSpec `locationName:"spec" type:"structure" required:"true"` + + // An object that represents the current status of a route. + // + // Status is a required field + Status *RouteStatus `locationName:"status" type:"structure" required:"true"` + + // VirtualRouterName is a required field + VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s RouteData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RouteData) GoString() string { + return s.String() +} + +// SetMeshName sets the MeshName field's value. +func (s *RouteData) SetMeshName(v string) *RouteData { + s.MeshName = &v + return s +} + +// SetMetadata sets the Metadata field's value. +func (s *RouteData) SetMetadata(v *ResourceMetadata) *RouteData { + s.Metadata = v + return s +} + +// SetRouteName sets the RouteName field's value. +func (s *RouteData) SetRouteName(v string) *RouteData { + s.RouteName = &v + return s +} + +// SetSpec sets the Spec field's value. +func (s *RouteData) SetSpec(v *RouteSpec) *RouteData { + s.Spec = v + return s +} + +// SetStatus sets the Status field's value. +func (s *RouteData) SetStatus(v *RouteStatus) *RouteData { + s.Status = v + return s +} + +// SetVirtualRouterName sets the VirtualRouterName field's value. +func (s *RouteData) SetVirtualRouterName(v string) *RouteData { + s.VirtualRouterName = &v + return s +} + +// An object that represents a route returned by a list operation. +type RouteRef struct { + _ struct{} `type:"structure"` + + // Arn is a required field + Arn *string `locationName:"arn" type:"string" required:"true"` + + // CreatedAt is a required field + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"` + + // LastUpdatedAt is a required field + LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"` + + // MeshName is a required field + MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` + + // MeshOwner is a required field + MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"` + + // ResourceOwner is a required field + ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"` + + // RouteName is a required field + RouteName *string `locationName:"routeName" min:"1" type:"string" required:"true"` + + // Version is a required field + Version *int64 `locationName:"version" type:"long" required:"true"` + + // VirtualRouterName is a required field + VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s RouteRef) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RouteRef) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *RouteRef) SetArn(v string) *RouteRef { + s.Arn = &v + return s +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *RouteRef) SetCreatedAt(v time.Time) *RouteRef { + s.CreatedAt = &v + return s +} + +// SetLastUpdatedAt sets the LastUpdatedAt field's value. +func (s *RouteRef) SetLastUpdatedAt(v time.Time) *RouteRef { + s.LastUpdatedAt = &v + return s +} + +// SetMeshName sets the MeshName field's value. +func (s *RouteRef) SetMeshName(v string) *RouteRef { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *RouteRef) SetMeshOwner(v string) *RouteRef { + s.MeshOwner = &v + return s +} + +// SetResourceOwner sets the ResourceOwner field's value. +func (s *RouteRef) SetResourceOwner(v string) *RouteRef { + s.ResourceOwner = &v + return s +} + +// SetRouteName sets the RouteName field's value. +func (s *RouteRef) SetRouteName(v string) *RouteRef { + s.RouteName = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *RouteRef) SetVersion(v int64) *RouteRef { + s.Version = &v + return s +} + +// SetVirtualRouterName sets the VirtualRouterName field's value. +func (s *RouteRef) SetVirtualRouterName(v string) *RouteRef { + s.VirtualRouterName = &v + return s +} + +// An object that represents a route specification. Specify one route type. +type RouteSpec struct { + _ struct{} `type:"structure"` + + // An object that represents a gRPC route type. + GrpcRoute *GrpcRoute `locationName:"grpcRoute" type:"structure"` + + // An object that represents an HTTP or HTTP/2 route type. + Http2Route *HttpRoute `locationName:"http2Route" type:"structure"` + + // An object that represents an HTTP or HTTP/2 route type. + HttpRoute *HttpRoute `locationName:"httpRoute" type:"structure"` + + Priority *int64 `locationName:"priority" type:"integer"` + + // An object that represents a TCP route type. + TcpRoute *TcpRoute `locationName:"tcpRoute" type:"structure"` +} + +// String returns the string representation +func (s RouteSpec) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RouteSpec) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RouteSpec) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RouteSpec"} + if s.GrpcRoute != nil { + if err := s.GrpcRoute.Validate(); err != nil { + invalidParams.AddNested("GrpcRoute", err.(request.ErrInvalidParams)) + } + } + if s.Http2Route != nil { + if err := s.Http2Route.Validate(); err != nil { + invalidParams.AddNested("Http2Route", err.(request.ErrInvalidParams)) + } + } + if s.HttpRoute != nil { + if err := s.HttpRoute.Validate(); err != nil { + invalidParams.AddNested("HttpRoute", err.(request.ErrInvalidParams)) + } + } + if s.TcpRoute != nil { + if err := s.TcpRoute.Validate(); err != nil { + invalidParams.AddNested("TcpRoute", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGrpcRoute sets the GrpcRoute field's value. +func (s *RouteSpec) SetGrpcRoute(v *GrpcRoute) *RouteSpec { + s.GrpcRoute = v + return s +} + +// SetHttp2Route sets the Http2Route field's value. +func (s *RouteSpec) SetHttp2Route(v *HttpRoute) *RouteSpec { + s.Http2Route = v + return s +} + +// SetHttpRoute sets the HttpRoute field's value. +func (s *RouteSpec) SetHttpRoute(v *HttpRoute) *RouteSpec { + s.HttpRoute = v + return s +} + +// SetPriority sets the Priority field's value. +func (s *RouteSpec) SetPriority(v int64) *RouteSpec { + s.Priority = &v + return s +} + +// SetTcpRoute sets the TcpRoute field's value. +func (s *RouteSpec) SetTcpRoute(v *TcpRoute) *RouteSpec { + s.TcpRoute = v + return s +} + +// An object that represents the current status of a route. +type RouteStatus struct { + _ struct{} `type:"structure"` + + // Status is a required field + Status *string `locationName:"status" type:"string" required:"true" enum:"RouteStatusCode"` +} + +// String returns the string representation +func (s RouteStatus) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RouteStatus) GoString() string { + return s.String() +} + +// SetStatus sets the Status field's value. +func (s *RouteStatus) SetStatus(v string) *RouteStatus { + s.Status = &v + return s +} + +// An object that represents the service discovery information for a virtual +// node. +type ServiceDiscovery struct { + _ struct{} `type:"structure"` + + // An object that represents the AWS Cloud Map service discovery information + // for your virtual node. + AwsCloudMap *AwsCloudMapServiceDiscovery `locationName:"awsCloudMap" type:"structure"` + + // An object that represents the DNS service discovery information for your + // virtual node. + Dns *DnsServiceDiscovery `locationName:"dns" type:"structure"` +} + +// String returns the string representation +func (s ServiceDiscovery) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ServiceDiscovery) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ServiceDiscovery) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ServiceDiscovery"} + if s.AwsCloudMap != nil { + if err := s.AwsCloudMap.Validate(); err != nil { + invalidParams.AddNested("AwsCloudMap", err.(request.ErrInvalidParams)) + } + } + if s.Dns != nil { + if err := s.Dns.Validate(); err != nil { + invalidParams.AddNested("Dns", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsCloudMap sets the AwsCloudMap field's value. +func (s *ServiceDiscovery) SetAwsCloudMap(v *AwsCloudMapServiceDiscovery) *ServiceDiscovery { + s.AwsCloudMap = v + return s +} + +// SetDns sets the Dns field's value. +func (s *ServiceDiscovery) SetDns(v *DnsServiceDiscovery) *ServiceDiscovery { + s.Dns = v + return s +} + +// The request has failed due to a temporary failure of the service. +type ServiceUnavailableException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ServiceUnavailableException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ServiceUnavailableException) GoString() string { + return s.String() +} + +func newErrorServiceUnavailableException(v protocol.ResponseMetadata) error { + return &ServiceUnavailableException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ServiceUnavailableException) Code() string { + return "ServiceUnavailableException" +} + +// Message returns the exception's message. +func (s *ServiceUnavailableException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ServiceUnavailableException) OrigErr() error { + return nil +} + +func (s *ServiceUnavailableException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ServiceUnavailableException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ServiceUnavailableException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Optional metadata that you apply to a resource to assist with categorization +// and organization. Each tag consists of a key and an optional value, both +// of which you define. Tag keys can have a maximum character length of 128 +// characters, and tag values can have a maximum length of 256 characters. +type TagRef struct { + _ struct{} `type:"structure"` + + // Key is a required field + Key *string `locationName:"key" min:"1" type:"string" required:"true"` + + Value *string `locationName:"value" type:"string"` +} + +// String returns the string representation +func (s TagRef) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagRef) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagRef) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagRef"} + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKey sets the Key field's value. +func (s *TagRef) SetKey(v string) *TagRef { + s.Key = &v + return s +} + +// SetValue sets the Value field's value. +func (s *TagRef) SetValue(v string) *TagRef { + s.Value = &v + return s +} + +type TagResourceInput struct { + _ struct{} `type:"structure"` + + // ResourceArn is a required field + ResourceArn *string `location:"querystring" locationName:"resourceArn" type:"string" required:"true"` + + // Tags is a required field + Tags []*TagRef `locationName:"tags" type:"list" required:"true"` +} + +// String returns the string representation +func (s TagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *TagResourceInput) SetTags(v []*TagRef) *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() +} + +// An object that represents a TCP route type. +type TcpRoute struct { + _ struct{} `type:"structure"` + + // An object that represents the action to take if a match is determined. + // + // Action is a required field + Action *TcpRouteAction `locationName:"action" type:"structure" required:"true"` + + // An object that represents types of timeouts. + Timeout *TcpTimeout `locationName:"timeout" type:"structure"` +} + +// String returns the string representation +func (s TcpRoute) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TcpRoute) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TcpRoute) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TcpRoute"} + if s.Action == nil { + invalidParams.Add(request.NewErrParamRequired("Action")) + } + if s.Action != nil { + if err := s.Action.Validate(); err != nil { + invalidParams.AddNested("Action", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAction sets the Action field's value. +func (s *TcpRoute) SetAction(v *TcpRouteAction) *TcpRoute { + s.Action = v + return s +} + +// SetTimeout sets the Timeout field's value. +func (s *TcpRoute) SetTimeout(v *TcpTimeout) *TcpRoute { + s.Timeout = v + return s +} + +// An object that represents the action to take if a match is determined. +type TcpRouteAction struct { + _ struct{} `type:"structure"` + + // WeightedTargets is a required field + WeightedTargets []*WeightedTarget `locationName:"weightedTargets" min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s TcpRouteAction) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TcpRouteAction) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TcpRouteAction) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TcpRouteAction"} + if s.WeightedTargets == nil { + invalidParams.Add(request.NewErrParamRequired("WeightedTargets")) + } + if s.WeightedTargets != nil && len(s.WeightedTargets) < 1 { + invalidParams.Add(request.NewErrParamMinLen("WeightedTargets", 1)) + } + if s.WeightedTargets != nil { + for i, v := range s.WeightedTargets { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "WeightedTargets", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetWeightedTargets sets the WeightedTargets field's value. +func (s *TcpRouteAction) SetWeightedTargets(v []*WeightedTarget) *TcpRouteAction { + s.WeightedTargets = v + return s +} + +// An object that represents types of timeouts. +type TcpTimeout struct { + _ struct{} `type:"structure"` + + // An object that represents a duration of time. + Idle *Duration `locationName:"idle" type:"structure"` +} + +// String returns the string representation +func (s TcpTimeout) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TcpTimeout) GoString() string { + return s.String() +} + +// SetIdle sets the Idle field's value. +func (s *TcpTimeout) SetIdle(v *Duration) *TcpTimeout { + s.Idle = v + return s +} + +// An object that represents a Transport Layer Security (TLS) validation context. +type TlsValidationContext struct { + _ struct{} `type:"structure"` + + // An object that represents a Transport Layer Security (TLS) validation context + // trust. + // + // Trust is a required field + Trust *TlsValidationContextTrust `locationName:"trust" type:"structure" required:"true"` +} + +// String returns the string representation +func (s TlsValidationContext) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TlsValidationContext) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TlsValidationContext) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TlsValidationContext"} + if s.Trust == nil { + invalidParams.Add(request.NewErrParamRequired("Trust")) + } + if s.Trust != nil { + if err := s.Trust.Validate(); err != nil { + invalidParams.AddNested("Trust", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetTrust sets the Trust field's value. +func (s *TlsValidationContext) SetTrust(v *TlsValidationContextTrust) *TlsValidationContext { + s.Trust = v + return s +} + +// An object that represents a TLS validation context trust for an AWS Certicate +// Manager (ACM) certificate. +type TlsValidationContextAcmTrust struct { + _ struct{} `type:"structure"` + + // CertificateAuthorityArns is a required field + CertificateAuthorityArns []*string `locationName:"certificateAuthorityArns" min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s TlsValidationContextAcmTrust) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TlsValidationContextAcmTrust) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TlsValidationContextAcmTrust) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TlsValidationContextAcmTrust"} + if s.CertificateAuthorityArns == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateAuthorityArns")) + } + if s.CertificateAuthorityArns != nil && len(s.CertificateAuthorityArns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CertificateAuthorityArns", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCertificateAuthorityArns sets the CertificateAuthorityArns field's value. +func (s *TlsValidationContextAcmTrust) SetCertificateAuthorityArns(v []*string) *TlsValidationContextAcmTrust { + s.CertificateAuthorityArns = v + return s +} + +// An object that represents a Transport Layer Security (TLS) validation context +// trust for a local file. +type TlsValidationContextFileTrust struct { + _ struct{} `type:"structure"` + + // CertificateChain is a required field + CertificateChain *string `locationName:"certificateChain" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s TlsValidationContextFileTrust) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TlsValidationContextFileTrust) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TlsValidationContextFileTrust) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TlsValidationContextFileTrust"} + if s.CertificateChain == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateChain")) + } + if s.CertificateChain != nil && len(*s.CertificateChain) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CertificateChain", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCertificateChain sets the CertificateChain field's value. +func (s *TlsValidationContextFileTrust) SetCertificateChain(v string) *TlsValidationContextFileTrust { + s.CertificateChain = &v + return s +} + +// An object that represents a Transport Layer Security (TLS) validation context +// trust. +type TlsValidationContextTrust struct { + _ struct{} `type:"structure"` + + // An object that represents a TLS validation context trust for an AWS Certicate + // Manager (ACM) certificate. + Acm *TlsValidationContextAcmTrust `locationName:"acm" type:"structure"` + + // An object that represents a Transport Layer Security (TLS) validation context + // trust for a local file. + File *TlsValidationContextFileTrust `locationName:"file" type:"structure"` +} + +// String returns the string representation +func (s TlsValidationContextTrust) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TlsValidationContextTrust) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TlsValidationContextTrust) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TlsValidationContextTrust"} + if s.Acm != nil { + if err := s.Acm.Validate(); err != nil { + invalidParams.AddNested("Acm", err.(request.ErrInvalidParams)) + } + } + if s.File != nil { + if err := s.File.Validate(); err != nil { + invalidParams.AddNested("File", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAcm sets the Acm field's value. +func (s *TlsValidationContextTrust) SetAcm(v *TlsValidationContextAcmTrust) *TlsValidationContextTrust { + s.Acm = v + return s +} + +// SetFile sets the File field's value. +func (s *TlsValidationContextTrust) SetFile(v *TlsValidationContextFileTrust) *TlsValidationContextTrust { + s.File = v + return s +} + +// The maximum request rate permitted by the App Mesh APIs has been exceeded +// for your account. For best results, use an increasing or variable sleep interval +// between requests. +type TooManyRequestsException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s TooManyRequestsException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TooManyRequestsException) GoString() string { + return s.String() +} + +func newErrorTooManyRequestsException(v protocol.ResponseMetadata) error { + return &TooManyRequestsException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *TooManyRequestsException) Code() string { + return "TooManyRequestsException" +} + +// Message returns the exception's message. +func (s *TooManyRequestsException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *TooManyRequestsException) OrigErr() error { + return nil +} + +func (s *TooManyRequestsException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *TooManyRequestsException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *TooManyRequestsException) RequestID() string { + return s.RespMetadata.RequestID +} + +// The request exceeds the maximum allowed number of tags allowed per resource. +// The current limit is 50 user tags per resource. You must reduce the number +// of tags in the request. None of the tags in this request were applied. +type TooManyTagsException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s TooManyTagsException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TooManyTagsException) GoString() string { + return s.String() +} + +func newErrorTooManyTagsException(v protocol.ResponseMetadata) error { + return &TooManyTagsException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *TooManyTagsException) Code() string { + return "TooManyTagsException" +} + +// Message returns the exception's message. +func (s *TooManyTagsException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *TooManyTagsException) OrigErr() error { + return nil +} + +func (s *TooManyTagsException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *TooManyTagsException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *TooManyTagsException) RequestID() string { + return s.RespMetadata.RequestID +} + +type UntagResourceInput struct { + _ struct{} `type:"structure"` + + // ResourceArn is a required field + ResourceArn *string `location:"querystring" locationName:"resourceArn" type:"string" required:"true"` + + // TagKeys is a required field + TagKeys []*string `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.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTagKeys sets the TagKeys field's value. +func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { + s.TagKeys = v + return s +} + +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 UpdateGatewayRouteInput struct { + _ struct{} `type:"structure"` + + ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` + + // GatewayRouteName is a required field + GatewayRouteName *string `location:"uri" locationName:"gatewayRouteName" min:"1" type:"string" required:"true"` + + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + + // An object that represents a gateway route specification. Specify one gateway + // route type. + // + // Spec is a required field + Spec *GatewayRouteSpec `locationName:"spec" type:"structure" required:"true"` + + // VirtualGatewayName is a required field + VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s UpdateGatewayRouteInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateGatewayRouteInput) GoString() string { + return s.String() } -// Code returns the exception type name. -func (s *NotFoundException) Code() string { - return "NotFoundException" -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateGatewayRouteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateGatewayRouteInput"} + if s.GatewayRouteName == nil { + invalidParams.Add(request.NewErrParamRequired("GatewayRouteName")) + } + if s.GatewayRouteName != nil && len(*s.GatewayRouteName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GatewayRouteName", 1)) + } + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.Spec == nil { + invalidParams.Add(request.NewErrParamRequired("Spec")) + } + if s.VirtualGatewayName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName")) + } + if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1)) + } + if s.Spec != nil { + if err := s.Spec.Validate(); err != nil { + invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) + } + } -// Message returns the exception's message. -func (s *NotFoundException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if invalidParams.Len() > 0 { + return invalidParams } - return "" + return nil } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *NotFoundException) OrigErr() error { +// SetClientToken sets the ClientToken field's value. +func (s *UpdateGatewayRouteInput) SetClientToken(v string) *UpdateGatewayRouteInput { + s.ClientToken = &v + return s +} + +// SetGatewayRouteName sets the GatewayRouteName field's value. +func (s *UpdateGatewayRouteInput) SetGatewayRouteName(v string) *UpdateGatewayRouteInput { + s.GatewayRouteName = &v + return s +} + +// SetMeshName sets the MeshName field's value. +func (s *UpdateGatewayRouteInput) SetMeshName(v string) *UpdateGatewayRouteInput { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *UpdateGatewayRouteInput) SetMeshOwner(v string) *UpdateGatewayRouteInput { + s.MeshOwner = &v + return s +} + +// SetSpec sets the Spec field's value. +func (s *UpdateGatewayRouteInput) SetSpec(v *GatewayRouteSpec) *UpdateGatewayRouteInput { + s.Spec = v + return s +} + +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *UpdateGatewayRouteInput) SetVirtualGatewayName(v string) *UpdateGatewayRouteInput { + s.VirtualGatewayName = &v + return s +} + +type UpdateGatewayRouteOutput struct { + _ struct{} `type:"structure" payload:"GatewayRoute"` + + // An object that represents a gateway route returned by a describe operation. + // + // GatewayRoute is a required field + GatewayRoute *GatewayRouteData `locationName:"gatewayRoute" type:"structure" required:"true"` +} + +// String returns the string representation +func (s UpdateGatewayRouteOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateGatewayRouteOutput) GoString() string { + return s.String() +} + +// SetGatewayRoute sets the GatewayRoute field's value. +func (s *UpdateGatewayRouteOutput) SetGatewayRoute(v *GatewayRouteData) *UpdateGatewayRouteOutput { + s.GatewayRoute = v + return s +} + +type UpdateMeshInput struct { + _ struct{} `type:"structure"` + + ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` + + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + // An object that represents the specification of a service mesh. + Spec *MeshSpec `locationName:"spec" type:"structure"` +} + +// String returns the string representation +func (s UpdateMeshInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateMeshInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateMeshInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateMeshInput"} + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.Spec != nil { + if err := s.Spec.Validate(); err != nil { + invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } return nil } -func (s *NotFoundException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +// SetClientToken sets the ClientToken field's value. +func (s *UpdateMeshInput) SetClientToken(v string) *UpdateMeshInput { + s.ClientToken = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *NotFoundException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetMeshName sets the MeshName field's value. +func (s *UpdateMeshInput) SetMeshName(v string) *UpdateMeshInput { + s.MeshName = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *NotFoundException) RequestID() string { - return s.RespMetadata.RequestID +// SetSpec sets the Spec field's value. +func (s *UpdateMeshInput) SetSpec(v *MeshSpec) *UpdateMeshInput { + s.Spec = v + return s } -// An object that represents a port mapping. -type PortMapping struct { +type UpdateMeshOutput struct { + _ struct{} `type:"structure" payload:"Mesh"` + + // An object that represents a service mesh returned by a describe operation. + // + // Mesh is a required field + Mesh *MeshData `locationName:"mesh" type:"structure" required:"true"` +} + +// String returns the string representation +func (s UpdateMeshOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateMeshOutput) GoString() string { + return s.String() +} + +// SetMesh sets the Mesh field's value. +func (s *UpdateMeshOutput) SetMesh(v *MeshData) *UpdateMeshOutput { + s.Mesh = v + return s +} + +type UpdateRouteInput struct { _ struct{} `type:"structure"` - // Port is a required field - Port *int64 `locationName:"port" min:"1" type:"integer" required:"true"` + ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` - // Protocol is a required field - Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"PortProtocol"` + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + + // RouteName is a required field + RouteName *string `location:"uri" locationName:"routeName" min:"1" type:"string" required:"true"` + + // An object that represents a route specification. Specify one route type. + // + // Spec is a required field + Spec *RouteSpec `locationName:"spec" type:"structure" required:"true"` + + // VirtualRouterName is a required field + VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s PortMapping) String() string { +func (s UpdateRouteInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PortMapping) GoString() string { +func (s UpdateRouteInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PortMapping) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PortMapping"} - if s.Port == nil { - invalidParams.Add(request.NewErrParamRequired("Port")) +func (s *UpdateRouteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateRouteInput"} + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) } - if s.Protocol == nil { - invalidParams.Add(request.NewErrParamRequired("Protocol")) + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.RouteName == nil { + invalidParams.Add(request.NewErrParamRequired("RouteName")) + } + if s.RouteName != nil && len(*s.RouteName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RouteName", 1)) + } + if s.Spec == nil { + invalidParams.Add(request.NewErrParamRequired("Spec")) + } + if s.VirtualRouterName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualRouterName")) + } + if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1)) + } + if s.Spec != nil { + if err := s.Spec.Validate(); err != nil { + invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -7768,347 +12044,471 @@ func (s *PortMapping) Validate() error { return nil } -// SetPort sets the Port field's value. -func (s *PortMapping) SetPort(v int64) *PortMapping { - s.Port = &v +// SetClientToken sets the ClientToken field's value. +func (s *UpdateRouteInput) SetClientToken(v string) *UpdateRouteInput { + s.ClientToken = &v + return s +} + +// SetMeshName sets the MeshName field's value. +func (s *UpdateRouteInput) SetMeshName(v string) *UpdateRouteInput { + s.MeshName = &v + return s +} + +// SetMeshOwner sets the MeshOwner field's value. +func (s *UpdateRouteInput) SetMeshOwner(v string) *UpdateRouteInput { + s.MeshOwner = &v + return s +} + +// SetRouteName sets the RouteName field's value. +func (s *UpdateRouteInput) SetRouteName(v string) *UpdateRouteInput { + s.RouteName = &v + return s +} + +// SetSpec sets the Spec field's value. +func (s *UpdateRouteInput) SetSpec(v *RouteSpec) *UpdateRouteInput { + s.Spec = v return s } -// SetProtocol sets the Protocol field's value. -func (s *PortMapping) SetProtocol(v string) *PortMapping { - s.Protocol = &v +// SetVirtualRouterName sets the VirtualRouterName field's value. +func (s *UpdateRouteInput) SetVirtualRouterName(v string) *UpdateRouteInput { + s.VirtualRouterName = &v return s } -// You can't delete the specified resource because it's in use or required by -// another resource. -type ResourceInUseException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +type UpdateRouteOutput struct { + _ struct{} `type:"structure" payload:"Route"` - Message_ *string `locationName:"message" type:"string"` + // An object that represents a route returned by a describe operation. + // + // Route is a required field + Route *RouteData `locationName:"route" type:"structure" required:"true"` } // String returns the string representation -func (s ResourceInUseException) String() string { +func (s UpdateRouteOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ResourceInUseException) GoString() string { +func (s UpdateRouteOutput) GoString() string { return s.String() } -func newErrorResourceInUseException(v protocol.ResponseMetadata) error { - return &ResourceInUseException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ResourceInUseException) Code() string { - return "ResourceInUseException" -} - -// Message returns the exception's message. -func (s *ResourceInUseException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ResourceInUseException) OrigErr() error { - return nil -} - -func (s *ResourceInUseException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ResourceInUseException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *ResourceInUseException) RequestID() string { - return s.RespMetadata.RequestID +// SetRoute sets the Route field's value. +func (s *UpdateRouteOutput) SetRoute(v *RouteData) *UpdateRouteOutput { + s.Route = v + return s } -// An object that represents metadata for a resource. -type ResourceMetadata struct { +type UpdateVirtualGatewayInput struct { _ struct{} `type:"structure"` - // Arn is a required field - Arn *string `locationName:"arn" type:"string" required:"true"` - - // CreatedAt is a required field - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"` - - // LastUpdatedAt is a required field - LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"` + ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` - // MeshOwner is a required field - MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"` + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` - // ResourceOwner is a required field - ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"` + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - // Uid is a required field - Uid *string `locationName:"uid" type:"string" required:"true"` + // An object that represents the specification of a service mesh resource. + // + // Spec is a required field + Spec *VirtualGatewaySpec `locationName:"spec" type:"structure" required:"true"` - // Version is a required field - Version *int64 `locationName:"version" type:"long" required:"true"` + // VirtualGatewayName is a required field + VirtualGatewayName *string `location:"uri" locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s ResourceMetadata) String() string { +func (s UpdateVirtualGatewayInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ResourceMetadata) GoString() string { +func (s UpdateVirtualGatewayInput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *ResourceMetadata) SetArn(v string) *ResourceMetadata { - s.Arn = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateVirtualGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateVirtualGatewayInput"} + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.Spec == nil { + invalidParams.Add(request.NewErrParamRequired("Spec")) + } + if s.VirtualGatewayName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualGatewayName")) + } + if s.VirtualGatewayName != nil && len(*s.VirtualGatewayName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualGatewayName", 1)) + } + if s.Spec != nil { + if err := s.Spec.Validate(); err != nil { + invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetCreatedAt sets the CreatedAt field's value. -func (s *ResourceMetadata) SetCreatedAt(v time.Time) *ResourceMetadata { - s.CreatedAt = &v +// SetClientToken sets the ClientToken field's value. +func (s *UpdateVirtualGatewayInput) SetClientToken(v string) *UpdateVirtualGatewayInput { + s.ClientToken = &v return s } -// SetLastUpdatedAt sets the LastUpdatedAt field's value. -func (s *ResourceMetadata) SetLastUpdatedAt(v time.Time) *ResourceMetadata { - s.LastUpdatedAt = &v +// SetMeshName sets the MeshName field's value. +func (s *UpdateVirtualGatewayInput) SetMeshName(v string) *UpdateVirtualGatewayInput { + s.MeshName = &v return s } // SetMeshOwner sets the MeshOwner field's value. -func (s *ResourceMetadata) SetMeshOwner(v string) *ResourceMetadata { +func (s *UpdateVirtualGatewayInput) SetMeshOwner(v string) *UpdateVirtualGatewayInput { s.MeshOwner = &v return s } -// SetResourceOwner sets the ResourceOwner field's value. -func (s *ResourceMetadata) SetResourceOwner(v string) *ResourceMetadata { - s.ResourceOwner = &v +// SetSpec sets the Spec field's value. +func (s *UpdateVirtualGatewayInput) SetSpec(v *VirtualGatewaySpec) *UpdateVirtualGatewayInput { + s.Spec = v return s } -// SetUid sets the Uid field's value. -func (s *ResourceMetadata) SetUid(v string) *ResourceMetadata { - s.Uid = &v +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *UpdateVirtualGatewayInput) SetVirtualGatewayName(v string) *UpdateVirtualGatewayInput { + s.VirtualGatewayName = &v return s } -// SetVersion sets the Version field's value. -func (s *ResourceMetadata) SetVersion(v int64) *ResourceMetadata { - s.Version = &v +type UpdateVirtualGatewayOutput struct { + _ struct{} `type:"structure" payload:"VirtualGateway"` + + // An object that represents a virtual gateway returned by a describe operation. + // + // VirtualGateway is a required field + VirtualGateway *VirtualGatewayData `locationName:"virtualGateway" type:"structure" required:"true"` +} + +// String returns the string representation +func (s UpdateVirtualGatewayOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateVirtualGatewayOutput) GoString() string { + return s.String() +} + +// SetVirtualGateway sets the VirtualGateway field's value. +func (s *UpdateVirtualGatewayOutput) SetVirtualGateway(v *VirtualGatewayData) *UpdateVirtualGatewayOutput { + s.VirtualGateway = v return s } -// An object that represents a route returned by a describe operation. -type RouteData struct { +type UpdateVirtualNodeInput struct { _ struct{} `type:"structure"` - // MeshName is a required field - MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` + ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` - // An object that represents metadata for a resource. - // - // Metadata is a required field - Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"` + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` - // RouteName is a required field - RouteName *string `locationName:"routeName" min:"1" type:"string" required:"true"` + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - // An object that represents a route specification. Specify one route type. + // An object that represents the specification of a virtual node. // // Spec is a required field - Spec *RouteSpec `locationName:"spec" type:"structure" required:"true"` - - // An object that represents the current status of a route. - // - // Status is a required field - Status *RouteStatus `locationName:"status" type:"structure" required:"true"` + Spec *VirtualNodeSpec `locationName:"spec" type:"structure" required:"true"` - // VirtualRouterName is a required field - VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"` + // VirtualNodeName is a required field + VirtualNodeName *string `location:"uri" locationName:"virtualNodeName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s RouteData) String() string { +func (s UpdateVirtualNodeInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RouteData) GoString() string { +func (s UpdateVirtualNodeInput) GoString() string { return s.String() } -// SetMeshName sets the MeshName field's value. -func (s *RouteData) SetMeshName(v string) *RouteData { - s.MeshName = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateVirtualNodeInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateVirtualNodeInput"} + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.Spec == nil { + invalidParams.Add(request.NewErrParamRequired("Spec")) + } + if s.VirtualNodeName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualNodeName")) + } + if s.VirtualNodeName != nil && len(*s.VirtualNodeName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualNodeName", 1)) + } + if s.Spec != nil { + if err := s.Spec.Validate(); err != nil { + invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientToken sets the ClientToken field's value. +func (s *UpdateVirtualNodeInput) SetClientToken(v string) *UpdateVirtualNodeInput { + s.ClientToken = &v return s } -// SetMetadata sets the Metadata field's value. -func (s *RouteData) SetMetadata(v *ResourceMetadata) *RouteData { - s.Metadata = v +// SetMeshName sets the MeshName field's value. +func (s *UpdateVirtualNodeInput) SetMeshName(v string) *UpdateVirtualNodeInput { + s.MeshName = &v return s } -// SetRouteName sets the RouteName field's value. -func (s *RouteData) SetRouteName(v string) *RouteData { - s.RouteName = &v +// SetMeshOwner sets the MeshOwner field's value. +func (s *UpdateVirtualNodeInput) SetMeshOwner(v string) *UpdateVirtualNodeInput { + s.MeshOwner = &v return s } // SetSpec sets the Spec field's value. -func (s *RouteData) SetSpec(v *RouteSpec) *RouteData { +func (s *UpdateVirtualNodeInput) SetSpec(v *VirtualNodeSpec) *UpdateVirtualNodeInput { s.Spec = v return s } -// SetStatus sets the Status field's value. -func (s *RouteData) SetStatus(v *RouteStatus) *RouteData { - s.Status = v +// SetVirtualNodeName sets the VirtualNodeName field's value. +func (s *UpdateVirtualNodeInput) SetVirtualNodeName(v string) *UpdateVirtualNodeInput { + s.VirtualNodeName = &v return s } -// SetVirtualRouterName sets the VirtualRouterName field's value. -func (s *RouteData) SetVirtualRouterName(v string) *RouteData { - s.VirtualRouterName = &v +type UpdateVirtualNodeOutput struct { + _ struct{} `type:"structure" payload:"VirtualNode"` + + // An object that represents a virtual node returned by a describe operation. + // + // VirtualNode is a required field + VirtualNode *VirtualNodeData `locationName:"virtualNode" type:"structure" required:"true"` +} + +// String returns the string representation +func (s UpdateVirtualNodeOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateVirtualNodeOutput) GoString() string { + return s.String() +} + +// SetVirtualNode sets the VirtualNode field's value. +func (s *UpdateVirtualNodeOutput) SetVirtualNode(v *VirtualNodeData) *UpdateVirtualNodeOutput { + s.VirtualNode = v return s } -// An object that represents a route returned by a list operation. -type RouteRef struct { +type UpdateVirtualRouterInput struct { _ struct{} `type:"structure"` - // Arn is a required field - Arn *string `locationName:"arn" type:"string" required:"true"` + ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` // MeshName is a required field - MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` - - // MeshOwner is a required field - MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"` + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` - // ResourceOwner is a required field - ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"` + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - // RouteName is a required field - RouteName *string `locationName:"routeName" min:"1" type:"string" required:"true"` + // An object that represents the specification of a virtual router. + // + // Spec is a required field + Spec *VirtualRouterSpec `locationName:"spec" type:"structure" required:"true"` // VirtualRouterName is a required field - VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"` + VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s RouteRef) String() string { +func (s UpdateVirtualRouterInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RouteRef) GoString() string { +func (s UpdateVirtualRouterInput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *RouteRef) SetArn(v string) *RouteRef { - s.Arn = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateVirtualRouterInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateVirtualRouterInput"} + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) + } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) + } + if s.Spec == nil { + invalidParams.Add(request.NewErrParamRequired("Spec")) + } + if s.VirtualRouterName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualRouterName")) + } + if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1)) + } + if s.Spec != nil { + if err := s.Spec.Validate(); err != nil { + invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientToken sets the ClientToken field's value. +func (s *UpdateVirtualRouterInput) SetClientToken(v string) *UpdateVirtualRouterInput { + s.ClientToken = &v return s } // SetMeshName sets the MeshName field's value. -func (s *RouteRef) SetMeshName(v string) *RouteRef { +func (s *UpdateVirtualRouterInput) SetMeshName(v string) *UpdateVirtualRouterInput { s.MeshName = &v return s } // SetMeshOwner sets the MeshOwner field's value. -func (s *RouteRef) SetMeshOwner(v string) *RouteRef { +func (s *UpdateVirtualRouterInput) SetMeshOwner(v string) *UpdateVirtualRouterInput { s.MeshOwner = &v return s } -// SetResourceOwner sets the ResourceOwner field's value. -func (s *RouteRef) SetResourceOwner(v string) *RouteRef { - s.ResourceOwner = &v +// SetSpec sets the Spec field's value. +func (s *UpdateVirtualRouterInput) SetSpec(v *VirtualRouterSpec) *UpdateVirtualRouterInput { + s.Spec = v return s } -// SetRouteName sets the RouteName field's value. -func (s *RouteRef) SetRouteName(v string) *RouteRef { - s.RouteName = &v +// SetVirtualRouterName sets the VirtualRouterName field's value. +func (s *UpdateVirtualRouterInput) SetVirtualRouterName(v string) *UpdateVirtualRouterInput { + s.VirtualRouterName = &v return s } -// SetVirtualRouterName sets the VirtualRouterName field's value. -func (s *RouteRef) SetVirtualRouterName(v string) *RouteRef { - s.VirtualRouterName = &v +type UpdateVirtualRouterOutput struct { + _ struct{} `type:"structure" payload:"VirtualRouter"` + + // An object that represents a virtual router returned by a describe operation. + // + // VirtualRouter is a required field + VirtualRouter *VirtualRouterData `locationName:"virtualRouter" type:"structure" required:"true"` +} + +// String returns the string representation +func (s UpdateVirtualRouterOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateVirtualRouterOutput) GoString() string { + return s.String() +} + +// SetVirtualRouter sets the VirtualRouter field's value. +func (s *UpdateVirtualRouterOutput) SetVirtualRouter(v *VirtualRouterData) *UpdateVirtualRouterOutput { + s.VirtualRouter = v return s } -// An object that represents a route specification. Specify one route type. -type RouteSpec struct { +type UpdateVirtualServiceInput struct { _ struct{} `type:"structure"` - // An object that represents a gRPC route type. - GrpcRoute *GrpcRoute `locationName:"grpcRoute" type:"structure"` + ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` - // An object that represents an HTTP or HTTP/2 route type. - Http2Route *HttpRoute `locationName:"http2Route" type:"structure"` + // MeshName is a required field + MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` - // An object that represents an HTTP or HTTP/2 route type. - HttpRoute *HttpRoute `locationName:"httpRoute" type:"structure"` + MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - Priority *int64 `locationName:"priority" type:"integer"` + // An object that represents the specification of a virtual service. + // + // Spec is a required field + Spec *VirtualServiceSpec `locationName:"spec" type:"structure" required:"true"` - // An object that represents a TCP route type. - TcpRoute *TcpRoute `locationName:"tcpRoute" type:"structure"` + // VirtualServiceName is a required field + VirtualServiceName *string `location:"uri" locationName:"virtualServiceName" type:"string" required:"true"` } // String returns the string representation -func (s RouteSpec) String() string { +func (s UpdateVirtualServiceInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RouteSpec) GoString() string { +func (s UpdateVirtualServiceInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *RouteSpec) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RouteSpec"} - if s.GrpcRoute != nil { - if err := s.GrpcRoute.Validate(); err != nil { - invalidParams.AddNested("GrpcRoute", err.(request.ErrInvalidParams)) - } +func (s *UpdateVirtualServiceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateVirtualServiceInput"} + if s.MeshName == nil { + invalidParams.Add(request.NewErrParamRequired("MeshName")) } - if s.Http2Route != nil { - if err := s.Http2Route.Validate(); err != nil { - invalidParams.AddNested("Http2Route", err.(request.ErrInvalidParams)) - } + if s.MeshName != nil && len(*s.MeshName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) } - if s.HttpRoute != nil { - if err := s.HttpRoute.Validate(); err != nil { - invalidParams.AddNested("HttpRoute", err.(request.ErrInvalidParams)) - } + if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) } - if s.TcpRoute != nil { - if err := s.TcpRoute.Validate(); err != nil { - invalidParams.AddNested("TcpRoute", err.(request.ErrInvalidParams)) + if s.Spec == nil { + invalidParams.Add(request.NewErrParamRequired("Spec")) + } + if s.VirtualServiceName == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualServiceName")) + } + if s.VirtualServiceName != nil && len(*s.VirtualServiceName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VirtualServiceName", 1)) + } + if s.Spec != nil { + if err := s.Spec.Validate(); err != nil { + invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) } } @@ -8118,95 +12518,85 @@ func (s *RouteSpec) Validate() error { return nil } -// SetGrpcRoute sets the GrpcRoute field's value. -func (s *RouteSpec) SetGrpcRoute(v *GrpcRoute) *RouteSpec { - s.GrpcRoute = v +// SetClientToken sets the ClientToken field's value. +func (s *UpdateVirtualServiceInput) SetClientToken(v string) *UpdateVirtualServiceInput { + s.ClientToken = &v return s } -// SetHttp2Route sets the Http2Route field's value. -func (s *RouteSpec) SetHttp2Route(v *HttpRoute) *RouteSpec { - s.Http2Route = v +// SetMeshName sets the MeshName field's value. +func (s *UpdateVirtualServiceInput) SetMeshName(v string) *UpdateVirtualServiceInput { + s.MeshName = &v return s } -// SetHttpRoute sets the HttpRoute field's value. -func (s *RouteSpec) SetHttpRoute(v *HttpRoute) *RouteSpec { - s.HttpRoute = v +// SetMeshOwner sets the MeshOwner field's value. +func (s *UpdateVirtualServiceInput) SetMeshOwner(v string) *UpdateVirtualServiceInput { + s.MeshOwner = &v return s } -// SetPriority sets the Priority field's value. -func (s *RouteSpec) SetPriority(v int64) *RouteSpec { - s.Priority = &v +// SetSpec sets the Spec field's value. +func (s *UpdateVirtualServiceInput) SetSpec(v *VirtualServiceSpec) *UpdateVirtualServiceInput { + s.Spec = v return s } -// SetTcpRoute sets the TcpRoute field's value. -func (s *RouteSpec) SetTcpRoute(v *TcpRoute) *RouteSpec { - s.TcpRoute = v +// SetVirtualServiceName sets the VirtualServiceName field's value. +func (s *UpdateVirtualServiceInput) SetVirtualServiceName(v string) *UpdateVirtualServiceInput { + s.VirtualServiceName = &v return s } -// An object that represents the current status of a route. -type RouteStatus struct { - _ struct{} `type:"structure"` +type UpdateVirtualServiceOutput struct { + _ struct{} `type:"structure" payload:"VirtualService"` - // Status is a required field - Status *string `locationName:"status" type:"string" required:"true" enum:"RouteStatusCode"` + // An object that represents a virtual service returned by a describe operation. + // + // VirtualService is a required field + VirtualService *VirtualServiceData `locationName:"virtualService" type:"structure" required:"true"` } // String returns the string representation -func (s RouteStatus) String() string { +func (s UpdateVirtualServiceOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RouteStatus) GoString() string { +func (s UpdateVirtualServiceOutput) GoString() string { return s.String() } -// SetStatus sets the Status field's value. -func (s *RouteStatus) SetStatus(v string) *RouteStatus { - s.Status = &v +// SetVirtualService sets the VirtualService field's value. +func (s *UpdateVirtualServiceOutput) SetVirtualService(v *VirtualServiceData) *UpdateVirtualServiceOutput { + s.VirtualService = v return s } -// An object that represents the service discovery information for a virtual -// node. -type ServiceDiscovery struct { +// The access log configuration for a virtual gateway. +type VirtualGatewayAccessLog struct { _ struct{} `type:"structure"` - // An object that represents the AWS Cloud Map service discovery information - // for your virtual node. - AwsCloudMap *AwsCloudMapServiceDiscovery `locationName:"awsCloudMap" type:"structure"` - - // An object that represents the DNS service discovery information for your - // virtual node. - Dns *DnsServiceDiscovery `locationName:"dns" type:"structure"` + // An object that represents an access log file. + File *VirtualGatewayFileAccessLog `locationName:"file" type:"structure"` } // String returns the string representation -func (s ServiceDiscovery) String() string { +func (s VirtualGatewayAccessLog) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ServiceDiscovery) GoString() string { +func (s VirtualGatewayAccessLog) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ServiceDiscovery) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ServiceDiscovery"} - if s.AwsCloudMap != nil { - if err := s.AwsCloudMap.Validate(); err != nil { - invalidParams.AddNested("AwsCloudMap", err.(request.ErrInvalidParams)) - } - } - if s.Dns != nil { - if err := s.Dns.Validate(); err != nil { - invalidParams.AddNested("Dns", err.(request.ErrInvalidParams)) +func (s *VirtualGatewayAccessLog) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayAccessLog"} + if s.File != nil { + if err := s.File.Validate(); err != nil { + invalidParams.AddNested("File", err.(request.ErrInvalidParams)) } } @@ -8216,105 +12606,76 @@ func (s *ServiceDiscovery) Validate() error { return nil } -// SetAwsCloudMap sets the AwsCloudMap field's value. -func (s *ServiceDiscovery) SetAwsCloudMap(v *AwsCloudMapServiceDiscovery) *ServiceDiscovery { - s.AwsCloudMap = v - return s -} - -// SetDns sets the Dns field's value. -func (s *ServiceDiscovery) SetDns(v *DnsServiceDiscovery) *ServiceDiscovery { - s.Dns = v +// SetFile sets the File field's value. +func (s *VirtualGatewayAccessLog) SetFile(v *VirtualGatewayFileAccessLog) *VirtualGatewayAccessLog { + s.File = v return s } -// The request has failed due to a temporary failure of the service. -type ServiceUnavailableException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +// An object that represents the default properties for a backend. +type VirtualGatewayBackendDefaults struct { + _ struct{} `type:"structure"` - Message_ *string `locationName:"message" type:"string"` + // An object that represents a client policy. + ClientPolicy *VirtualGatewayClientPolicy `locationName:"clientPolicy" type:"structure"` } // String returns the string representation -func (s ServiceUnavailableException) String() string { +func (s VirtualGatewayBackendDefaults) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ServiceUnavailableException) GoString() string { +func (s VirtualGatewayBackendDefaults) GoString() string { return s.String() } -func newErrorServiceUnavailableException(v protocol.ResponseMetadata) error { - return &ServiceUnavailableException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *VirtualGatewayBackendDefaults) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayBackendDefaults"} + if s.ClientPolicy != nil { + if err := s.ClientPolicy.Validate(); err != nil { + invalidParams.AddNested("ClientPolicy", err.(request.ErrInvalidParams)) + } } -} - -// Code returns the exception type name. -func (s *ServiceUnavailableException) Code() string { - return "ServiceUnavailableException" -} -// Message returns the exception's message. -func (s *ServiceUnavailableException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if invalidParams.Len() > 0 { + return invalidParams } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ServiceUnavailableException) OrigErr() error { return nil } -func (s *ServiceUnavailableException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ServiceUnavailableException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *ServiceUnavailableException) RequestID() string { - return s.RespMetadata.RequestID +// SetClientPolicy sets the ClientPolicy field's value. +func (s *VirtualGatewayBackendDefaults) SetClientPolicy(v *VirtualGatewayClientPolicy) *VirtualGatewayBackendDefaults { + s.ClientPolicy = v + return s } -// Optional metadata that you apply to a resource to assist with categorization -// and organization. Each tag consists of a key and an optional value, both -// of which you define. Tag keys can have a maximum character length of 128 -// characters, and tag values can have a maximum length of 256 characters. -type TagRef struct { +// An object that represents a client policy. +type VirtualGatewayClientPolicy struct { _ struct{} `type:"structure"` - // Key is a required field - Key *string `locationName:"key" min:"1" type:"string" required:"true"` - - Value *string `locationName:"value" type:"string"` + // An object that represents a Transport Layer Security (TLS) client policy. + Tls *VirtualGatewayClientPolicyTls `locationName:"tls" type:"structure"` } // String returns the string representation -func (s TagRef) String() string { +func (s VirtualGatewayClientPolicy) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TagRef) GoString() string { +func (s VirtualGatewayClientPolicy) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *TagRef) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TagRef"} - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) +func (s *VirtualGatewayClientPolicy) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayClientPolicy"} + if s.Tls != nil { + if err := s.Tls.Validate(); err != nil { + invalidParams.AddNested("Tls", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -8323,55 +12684,45 @@ func (s *TagRef) Validate() error { return nil } -// SetKey sets the Key field's value. -func (s *TagRef) SetKey(v string) *TagRef { - s.Key = &v - return s -} - -// SetValue sets the Value field's value. -func (s *TagRef) SetValue(v string) *TagRef { - s.Value = &v +// SetTls sets the Tls field's value. +func (s *VirtualGatewayClientPolicy) SetTls(v *VirtualGatewayClientPolicyTls) *VirtualGatewayClientPolicy { + s.Tls = v return s } -type TagResourceInput struct { +// An object that represents a Transport Layer Security (TLS) client policy. +type VirtualGatewayClientPolicyTls struct { _ struct{} `type:"structure"` - // ResourceArn is a required field - ResourceArn *string `location:"querystring" locationName:"resourceArn" type:"string" required:"true"` + Enforce *bool `locationName:"enforce" type:"boolean"` - // Tags is a required field - Tags []*TagRef `locationName:"tags" type:"list" required:"true"` + Ports []*int64 `locationName:"ports" type:"list"` + + // An object that represents a Transport Layer Security (TLS) validation context. + // + // Validation is a required field + Validation *VirtualGatewayTlsValidationContext `locationName:"validation" type:"structure" required:"true"` } // String returns the string representation -func (s TagResourceInput) String() string { +func (s VirtualGatewayClientPolicyTls) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TagResourceInput) GoString() string { +func (s VirtualGatewayClientPolicyTls) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *TagResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"} - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) - } - if s.Tags == nil { - invalidParams.Add(request.NewErrParamRequired("Tags")) +func (s *VirtualGatewayClientPolicyTls) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayClientPolicyTls"} + if s.Validation == nil { + invalidParams.Add(request.NewErrParamRequired("Validation")) } - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } + if s.Validation != nil { + if err := s.Validation.Validate(); err != nil { + invalidParams.AddNested("Validation", err.(request.ErrInvalidParams)) } } @@ -8381,112 +12732,116 @@ func (s *TagResourceInput) Validate() error { return nil } -// SetResourceArn sets the ResourceArn field's value. -func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput { - s.ResourceArn = &v +// SetEnforce sets the Enforce field's value. +func (s *VirtualGatewayClientPolicyTls) SetEnforce(v bool) *VirtualGatewayClientPolicyTls { + s.Enforce = &v return s } -// SetTags sets the Tags field's value. -func (s *TagResourceInput) SetTags(v []*TagRef) *TagResourceInput { - s.Tags = v +// SetPorts sets the Ports field's value. +func (s *VirtualGatewayClientPolicyTls) SetPorts(v []*int64) *VirtualGatewayClientPolicyTls { + s.Ports = v return s } -type TagResourceOutput struct { - _ struct{} `type:"structure"` +// SetValidation sets the Validation field's value. +func (s *VirtualGatewayClientPolicyTls) SetValidation(v *VirtualGatewayTlsValidationContext) *VirtualGatewayClientPolicyTls { + s.Validation = v + return s } -// String returns the string representation -func (s TagResourceOutput) String() string { - return awsutil.Prettify(s) -} +// An object that represents a virtual gateway returned by a describe operation. +type VirtualGatewayData struct { + _ struct{} `type:"structure"` -// GoString returns the string representation -func (s TagResourceOutput) GoString() string { - return s.String() -} + // MeshName is a required field + MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` -// An object that represents a TCP route type. -type TcpRoute struct { - _ struct{} `type:"structure"` + // An object that represents metadata for a resource. + // + // Metadata is a required field + Metadata *ResourceMetadata `locationName:"metadata" type:"structure" required:"true"` - // An object that represents the action to take if a match is determined. + // An object that represents the specification of a service mesh resource. // - // Action is a required field - Action *TcpRouteAction `locationName:"action" type:"structure" required:"true"` + // Spec is a required field + Spec *VirtualGatewaySpec `locationName:"spec" type:"structure" required:"true"` + + // An object that represents the status of the mesh resource. + // + // Status is a required field + Status *VirtualGatewayStatus `locationName:"status" type:"structure" required:"true"` + + // VirtualGatewayName is a required field + VirtualGatewayName *string `locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s TcpRoute) String() string { +func (s VirtualGatewayData) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TcpRoute) GoString() string { +func (s VirtualGatewayData) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *TcpRoute) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TcpRoute"} - if s.Action == nil { - invalidParams.Add(request.NewErrParamRequired("Action")) - } - if s.Action != nil { - if err := s.Action.Validate(); err != nil { - invalidParams.AddNested("Action", err.(request.ErrInvalidParams)) - } - } +// SetMeshName sets the MeshName field's value. +func (s *VirtualGatewayData) SetMeshName(v string) *VirtualGatewayData { + s.MeshName = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetMetadata sets the Metadata field's value. +func (s *VirtualGatewayData) SetMetadata(v *ResourceMetadata) *VirtualGatewayData { + s.Metadata = v + return s } -// SetAction sets the Action field's value. -func (s *TcpRoute) SetAction(v *TcpRouteAction) *TcpRoute { - s.Action = v +// SetSpec sets the Spec field's value. +func (s *VirtualGatewayData) SetSpec(v *VirtualGatewaySpec) *VirtualGatewayData { + s.Spec = v return s } -// An object that represents the action to take if a match is determined. -type TcpRouteAction struct { +// SetStatus sets the Status field's value. +func (s *VirtualGatewayData) SetStatus(v *VirtualGatewayStatus) *VirtualGatewayData { + s.Status = v + return s +} + +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *VirtualGatewayData) SetVirtualGatewayName(v string) *VirtualGatewayData { + s.VirtualGatewayName = &v + return s +} + +// An object that represents an access log file. +type VirtualGatewayFileAccessLog struct { _ struct{} `type:"structure"` - // WeightedTargets is a required field - WeightedTargets []*WeightedTarget `locationName:"weightedTargets" min:"1" type:"list" required:"true"` + // Path is a required field + Path *string `locationName:"path" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s TcpRouteAction) String() string { +func (s VirtualGatewayFileAccessLog) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TcpRouteAction) GoString() string { +func (s VirtualGatewayFileAccessLog) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *TcpRouteAction) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TcpRouteAction"} - if s.WeightedTargets == nil { - invalidParams.Add(request.NewErrParamRequired("WeightedTargets")) - } - if s.WeightedTargets != nil && len(s.WeightedTargets) < 1 { - invalidParams.Add(request.NewErrParamMinLen("WeightedTargets", 1)) +func (s *VirtualGatewayFileAccessLog) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayFileAccessLog"} + if s.Path == nil { + invalidParams.Add(request.NewErrParamRequired("Path")) } - if s.WeightedTargets != nil { - for i, v := range s.WeightedTargets { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "WeightedTargets", i), err.(request.ErrInvalidParams)) - } - } + if s.Path != nil && len(*s.Path) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Path", 1)) } if invalidParams.Len() > 0 { @@ -8495,43 +12850,79 @@ func (s *TcpRouteAction) Validate() error { return nil } -// SetWeightedTargets sets the WeightedTargets field's value. -func (s *TcpRouteAction) SetWeightedTargets(v []*WeightedTarget) *TcpRouteAction { - s.WeightedTargets = v +// SetPath sets the Path field's value. +func (s *VirtualGatewayFileAccessLog) SetPath(v string) *VirtualGatewayFileAccessLog { + s.Path = &v return s } -// An object that represents a Transport Layer Security (TLS) validation context. -type TlsValidationContext struct { - _ struct{} `type:"structure"` +// An object that represents the health check policy for a virtual gateway's +// listener. +type VirtualGatewayHealthCheckPolicy struct { + _ struct{} `type:"structure"` + + // HealthyThreshold is a required field + HealthyThreshold *int64 `locationName:"healthyThreshold" min:"2" type:"integer" required:"true"` + + // IntervalMillis is a required field + IntervalMillis *int64 `locationName:"intervalMillis" min:"5000" type:"long" required:"true"` + + Path *string `locationName:"path" type:"string"` + + Port *int64 `locationName:"port" min:"1" type:"integer"` + + // Protocol is a required field + Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"VirtualGatewayPortProtocol"` + + // TimeoutMillis is a required field + TimeoutMillis *int64 `locationName:"timeoutMillis" min:"2000" type:"long" required:"true"` - // An object that represents a Transport Layer Security (TLS) validation context - // trust. - // - // Trust is a required field - Trust *TlsValidationContextTrust `locationName:"trust" type:"structure" required:"true"` + // UnhealthyThreshold is a required field + UnhealthyThreshold *int64 `locationName:"unhealthyThreshold" min:"2" type:"integer" required:"true"` } // String returns the string representation -func (s TlsValidationContext) String() string { +func (s VirtualGatewayHealthCheckPolicy) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TlsValidationContext) GoString() string { +func (s VirtualGatewayHealthCheckPolicy) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *TlsValidationContext) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TlsValidationContext"} - if s.Trust == nil { - invalidParams.Add(request.NewErrParamRequired("Trust")) +func (s *VirtualGatewayHealthCheckPolicy) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayHealthCheckPolicy"} + if s.HealthyThreshold == nil { + invalidParams.Add(request.NewErrParamRequired("HealthyThreshold")) } - if s.Trust != nil { - if err := s.Trust.Validate(); err != nil { - invalidParams.AddNested("Trust", err.(request.ErrInvalidParams)) - } + if s.HealthyThreshold != nil && *s.HealthyThreshold < 2 { + invalidParams.Add(request.NewErrParamMinValue("HealthyThreshold", 2)) + } + if s.IntervalMillis == nil { + invalidParams.Add(request.NewErrParamRequired("IntervalMillis")) + } + if s.IntervalMillis != nil && *s.IntervalMillis < 5000 { + invalidParams.Add(request.NewErrParamMinValue("IntervalMillis", 5000)) + } + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + } + if s.Protocol == nil { + invalidParams.Add(request.NewErrParamRequired("Protocol")) + } + if s.TimeoutMillis == nil { + invalidParams.Add(request.NewErrParamRequired("TimeoutMillis")) + } + if s.TimeoutMillis != nil && *s.TimeoutMillis < 2000 { + invalidParams.Add(request.NewErrParamMinValue("TimeoutMillis", 2000)) + } + if s.UnhealthyThreshold == nil { + invalidParams.Add(request.NewErrParamRequired("UnhealthyThreshold")) + } + if s.UnhealthyThreshold != nil && *s.UnhealthyThreshold < 2 { + invalidParams.Add(request.NewErrParamMinValue("UnhealthyThreshold", 2)) } if invalidParams.Len() > 0 { @@ -8540,80 +12931,96 @@ func (s *TlsValidationContext) Validate() error { return nil } -// SetTrust sets the Trust field's value. -func (s *TlsValidationContext) SetTrust(v *TlsValidationContextTrust) *TlsValidationContext { - s.Trust = v +// SetHealthyThreshold sets the HealthyThreshold field's value. +func (s *VirtualGatewayHealthCheckPolicy) SetHealthyThreshold(v int64) *VirtualGatewayHealthCheckPolicy { + s.HealthyThreshold = &v return s } -// An object that represents a TLS validation context trust for an AWS Certicate -// Manager (ACM) certificate. -type TlsValidationContextAcmTrust struct { - _ struct{} `type:"structure"` - - // CertificateAuthorityArns is a required field - CertificateAuthorityArns []*string `locationName:"certificateAuthorityArns" min:"1" type:"list" required:"true"` +// SetIntervalMillis sets the IntervalMillis field's value. +func (s *VirtualGatewayHealthCheckPolicy) SetIntervalMillis(v int64) *VirtualGatewayHealthCheckPolicy { + s.IntervalMillis = &v + return s } -// String returns the string representation -func (s TlsValidationContextAcmTrust) String() string { - return awsutil.Prettify(s) +// SetPath sets the Path field's value. +func (s *VirtualGatewayHealthCheckPolicy) SetPath(v string) *VirtualGatewayHealthCheckPolicy { + s.Path = &v + return s } -// GoString returns the string representation -func (s TlsValidationContextAcmTrust) GoString() string { - return s.String() +// SetPort sets the Port field's value. +func (s *VirtualGatewayHealthCheckPolicy) SetPort(v int64) *VirtualGatewayHealthCheckPolicy { + s.Port = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *TlsValidationContextAcmTrust) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TlsValidationContextAcmTrust"} - if s.CertificateAuthorityArns == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateAuthorityArns")) - } - if s.CertificateAuthorityArns != nil && len(s.CertificateAuthorityArns) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CertificateAuthorityArns", 1)) - } +// SetProtocol sets the Protocol field's value. +func (s *VirtualGatewayHealthCheckPolicy) SetProtocol(v string) *VirtualGatewayHealthCheckPolicy { + s.Protocol = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetTimeoutMillis sets the TimeoutMillis field's value. +func (s *VirtualGatewayHealthCheckPolicy) SetTimeoutMillis(v int64) *VirtualGatewayHealthCheckPolicy { + s.TimeoutMillis = &v + return s } -// SetCertificateAuthorityArns sets the CertificateAuthorityArns field's value. -func (s *TlsValidationContextAcmTrust) SetCertificateAuthorityArns(v []*string) *TlsValidationContextAcmTrust { - s.CertificateAuthorityArns = v +// SetUnhealthyThreshold sets the UnhealthyThreshold field's value. +func (s *VirtualGatewayHealthCheckPolicy) SetUnhealthyThreshold(v int64) *VirtualGatewayHealthCheckPolicy { + s.UnhealthyThreshold = &v return s } -// An object that represents a Transport Layer Security (TLS) validation context -// trust for a local file. -type TlsValidationContextFileTrust struct { +// An object that represents a listener for a virtual gateway. +type VirtualGatewayListener struct { _ struct{} `type:"structure"` - // CertificateChain is a required field - CertificateChain *string `locationName:"certificateChain" min:"1" type:"string" required:"true"` + // An object that represents the health check policy for a virtual gateway's + // listener. + HealthCheck *VirtualGatewayHealthCheckPolicy `locationName:"healthCheck" type:"structure"` + + // An object that represents a port mapping. + // + // PortMapping is a required field + PortMapping *VirtualGatewayPortMapping `locationName:"portMapping" type:"structure" required:"true"` + + // An object that represents the Transport Layer Security (TLS) properties for + // a listener. + Tls *VirtualGatewayListenerTls `locationName:"tls" type:"structure"` } // String returns the string representation -func (s TlsValidationContextFileTrust) String() string { +func (s VirtualGatewayListener) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TlsValidationContextFileTrust) GoString() string { +func (s VirtualGatewayListener) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *TlsValidationContextFileTrust) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TlsValidationContextFileTrust"} - if s.CertificateChain == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateChain")) +func (s *VirtualGatewayListener) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListener"} + if s.PortMapping == nil { + invalidParams.Add(request.NewErrParamRequired("PortMapping")) } - if s.CertificateChain != nil && len(*s.CertificateChain) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CertificateChain", 1)) + if s.HealthCheck != nil { + if err := s.HealthCheck.Validate(); err != nil { + invalidParams.AddNested("HealthCheck", err.(request.ErrInvalidParams)) + } + } + if s.PortMapping != nil { + if err := s.PortMapping.Validate(); err != nil { + invalidParams.AddNested("PortMapping", err.(request.ErrInvalidParams)) + } + } + if s.Tls != nil { + if err := s.Tls.Validate(); err != nil { + invalidParams.AddNested("Tls", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -8622,47 +13029,60 @@ func (s *TlsValidationContextFileTrust) Validate() error { return nil } -// SetCertificateChain sets the CertificateChain field's value. -func (s *TlsValidationContextFileTrust) SetCertificateChain(v string) *TlsValidationContextFileTrust { - s.CertificateChain = &v +// SetHealthCheck sets the HealthCheck field's value. +func (s *VirtualGatewayListener) SetHealthCheck(v *VirtualGatewayHealthCheckPolicy) *VirtualGatewayListener { + s.HealthCheck = v return s } -// An object that represents a Transport Layer Security (TLS) validation context -// trust. -type TlsValidationContextTrust struct { +// SetPortMapping sets the PortMapping field's value. +func (s *VirtualGatewayListener) SetPortMapping(v *VirtualGatewayPortMapping) *VirtualGatewayListener { + s.PortMapping = v + return s +} + +// SetTls sets the Tls field's value. +func (s *VirtualGatewayListener) SetTls(v *VirtualGatewayListenerTls) *VirtualGatewayListener { + s.Tls = v + return s +} + +// An object that represents the Transport Layer Security (TLS) properties for +// a listener. +type VirtualGatewayListenerTls struct { _ struct{} `type:"structure"` - // An object that represents a TLS validation context trust for an AWS Certicate - // Manager (ACM) certificate. - Acm *TlsValidationContextAcmTrust `locationName:"acm" type:"structure"` + // An object that represents a listener's Transport Layer Security (TLS) certificate. + // + // Certificate is a required field + Certificate *VirtualGatewayListenerTlsCertificate `locationName:"certificate" type:"structure" required:"true"` - // An object that represents a Transport Layer Security (TLS) validation context - // trust for a local file. - File *TlsValidationContextFileTrust `locationName:"file" type:"structure"` + // Mode is a required field + Mode *string `locationName:"mode" type:"string" required:"true" enum:"VirtualGatewayListenerTlsMode"` } // String returns the string representation -func (s TlsValidationContextTrust) String() string { +func (s VirtualGatewayListenerTls) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TlsValidationContextTrust) GoString() string { +func (s VirtualGatewayListenerTls) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *TlsValidationContextTrust) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TlsValidationContextTrust"} - if s.Acm != nil { - if err := s.Acm.Validate(); err != nil { - invalidParams.AddNested("Acm", err.(request.ErrInvalidParams)) - } +func (s *VirtualGatewayListenerTls) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListenerTls"} + if s.Certificate == nil { + invalidParams.Add(request.NewErrParamRequired("Certificate")) } - if s.File != nil { - if err := s.File.Validate(); err != nil { - invalidParams.AddNested("File", err.(request.ErrInvalidParams)) + if s.Mode == nil { + invalidParams.Add(request.NewErrParamRequired("Mode")) + } + if s.Certificate != nil { + if err := s.Certificate.Validate(); err != nil { + invalidParams.AddNested("Certificate", err.(request.ErrInvalidParams)) } } @@ -8672,162 +13092,147 @@ func (s *TlsValidationContextTrust) Validate() error { return nil } -// SetAcm sets the Acm field's value. -func (s *TlsValidationContextTrust) SetAcm(v *TlsValidationContextAcmTrust) *TlsValidationContextTrust { - s.Acm = v +// SetCertificate sets the Certificate field's value. +func (s *VirtualGatewayListenerTls) SetCertificate(v *VirtualGatewayListenerTlsCertificate) *VirtualGatewayListenerTls { + s.Certificate = v return s } -// SetFile sets the File field's value. -func (s *TlsValidationContextTrust) SetFile(v *TlsValidationContextFileTrust) *TlsValidationContextTrust { - s.File = v +// SetMode sets the Mode field's value. +func (s *VirtualGatewayListenerTls) SetMode(v string) *VirtualGatewayListenerTls { + s.Mode = &v return s } -// The maximum request rate permitted by the App Mesh APIs has been exceeded -// for your account. For best results, use an increasing or variable sleep interval -// between requests. -type TooManyRequestsException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +// An object that represents an AWS Certicate Manager (ACM) certificate. +type VirtualGatewayListenerTlsAcmCertificate struct { + _ struct{} `type:"structure"` - Message_ *string `locationName:"message" type:"string"` + // CertificateArn is a required field + CertificateArn *string `locationName:"certificateArn" type:"string" required:"true"` } // String returns the string representation -func (s TooManyRequestsException) String() string { +func (s VirtualGatewayListenerTlsAcmCertificate) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TooManyRequestsException) GoString() string { +func (s VirtualGatewayListenerTlsAcmCertificate) GoString() string { return s.String() } -func newErrorTooManyRequestsException(v protocol.ResponseMetadata) error { - return &TooManyRequestsException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *VirtualGatewayListenerTlsAcmCertificate) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListenerTlsAcmCertificate"} + if s.CertificateArn == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateArn")) } -} - -// Code returns the exception type name. -func (s *TooManyRequestsException) Code() string { - return "TooManyRequestsException" -} -// Message returns the exception's message. -func (s *TooManyRequestsException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if invalidParams.Len() > 0 { + return invalidParams } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *TooManyRequestsException) OrigErr() error { return nil } -func (s *TooManyRequestsException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *TooManyRequestsException) StatusCode() int { - return s.RespMetadata.StatusCode -} - -// RequestID returns the service's response RequestID for request. -func (s *TooManyRequestsException) RequestID() string { - return s.RespMetadata.RequestID +// SetCertificateArn sets the CertificateArn field's value. +func (s *VirtualGatewayListenerTlsAcmCertificate) SetCertificateArn(v string) *VirtualGatewayListenerTlsAcmCertificate { + s.CertificateArn = &v + return s } -// The request exceeds the maximum allowed number of tags allowed per resource. -// The current limit is 50 user tags per resource. You must reduce the number -// of tags in the request. None of the tags in this request were applied. -type TooManyTagsException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` +// An object that represents a listener's Transport Layer Security (TLS) certificate. +type VirtualGatewayListenerTlsCertificate struct { + _ struct{} `type:"structure"` + + // An object that represents an AWS Certicate Manager (ACM) certificate. + Acm *VirtualGatewayListenerTlsAcmCertificate `locationName:"acm" type:"structure"` + + // An object that represents a local file certificate. The certificate must + // meet specific requirements and you must have proxy authorization enabled. + // For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html#virtual-node-tls-prerequisites). + File *VirtualGatewayListenerTlsFileCertificate `locationName:"file" type:"structure"` } // String returns the string representation -func (s TooManyTagsException) String() string { +func (s VirtualGatewayListenerTlsCertificate) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TooManyTagsException) GoString() string { +func (s VirtualGatewayListenerTlsCertificate) GoString() string { return s.String() } -func newErrorTooManyTagsException(v protocol.ResponseMetadata) error { - return &TooManyTagsException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *VirtualGatewayListenerTlsCertificate) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListenerTlsCertificate"} + if s.Acm != nil { + if err := s.Acm.Validate(); err != nil { + invalidParams.AddNested("Acm", err.(request.ErrInvalidParams)) + } } -} - -// Code returns the exception type name. -func (s *TooManyTagsException) Code() string { - return "TooManyTagsException" -} - -// Message returns the exception's message. -func (s *TooManyTagsException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if s.File != nil { + if err := s.File.Validate(); err != nil { + invalidParams.AddNested("File", err.(request.ErrInvalidParams)) + } } - return "" -} -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *TooManyTagsException) OrigErr() error { + if invalidParams.Len() > 0 { + return invalidParams + } return nil } -func (s *TooManyTagsException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *TooManyTagsException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetAcm sets the Acm field's value. +func (s *VirtualGatewayListenerTlsCertificate) SetAcm(v *VirtualGatewayListenerTlsAcmCertificate) *VirtualGatewayListenerTlsCertificate { + s.Acm = v + return s } -// RequestID returns the service's response RequestID for request. -func (s *TooManyTagsException) RequestID() string { - return s.RespMetadata.RequestID +// SetFile sets the File field's value. +func (s *VirtualGatewayListenerTlsCertificate) SetFile(v *VirtualGatewayListenerTlsFileCertificate) *VirtualGatewayListenerTlsCertificate { + s.File = v + return s } -type UntagResourceInput struct { +// An object that represents a local file certificate. The certificate must +// meet specific requirements and you must have proxy authorization enabled. +// For more information, see Transport Layer Security (TLS) (https://docs.aws.amazon.com/app-mesh/latest/userguide/tls.html#virtual-node-tls-prerequisites). +type VirtualGatewayListenerTlsFileCertificate struct { _ struct{} `type:"structure"` - // ResourceArn is a required field - ResourceArn *string `location:"querystring" locationName:"resourceArn" type:"string" required:"true"` + // CertificateChain is a required field + CertificateChain *string `locationName:"certificateChain" min:"1" type:"string" required:"true"` - // TagKeys is a required field - TagKeys []*string `locationName:"tagKeys" type:"list" required:"true"` + // PrivateKey is a required field + PrivateKey *string `locationName:"privateKey" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s UntagResourceInput) String() string { +func (s VirtualGatewayListenerTlsFileCertificate) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UntagResourceInput) GoString() string { +func (s VirtualGatewayListenerTlsFileCertificate) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UntagResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"} - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) +func (s *VirtualGatewayListenerTlsFileCertificate) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayListenerTlsFileCertificate"} + if s.CertificateChain == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateChain")) } - if s.TagKeys == nil { - invalidParams.Add(request.NewErrParamRequired("TagKeys")) + if s.CertificateChain != nil && len(*s.CertificateChain) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CertificateChain", 1)) + } + if s.PrivateKey == nil { + invalidParams.Add(request.NewErrParamRequired("PrivateKey")) + } + if s.PrivateKey != nil && len(*s.PrivateKey) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PrivateKey", 1)) } if invalidParams.Len() > 0 { @@ -8836,67 +13241,89 @@ func (s *UntagResourceInput) Validate() error { return nil } -// SetResourceArn sets the ResourceArn field's value. -func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { - s.ResourceArn = &v +// SetCertificateChain sets the CertificateChain field's value. +func (s *VirtualGatewayListenerTlsFileCertificate) SetCertificateChain(v string) *VirtualGatewayListenerTlsFileCertificate { + s.CertificateChain = &v return s } -// SetTagKeys sets the TagKeys field's value. -func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { - s.TagKeys = v +// SetPrivateKey sets the PrivateKey field's value. +func (s *VirtualGatewayListenerTlsFileCertificate) SetPrivateKey(v string) *VirtualGatewayListenerTlsFileCertificate { + s.PrivateKey = &v return s } -type UntagResourceOutput struct { +// An object that represents logging information. +type VirtualGatewayLogging struct { _ struct{} `type:"structure"` + + // The access log configuration for a virtual gateway. + AccessLog *VirtualGatewayAccessLog `locationName:"accessLog" type:"structure"` } // String returns the string representation -func (s UntagResourceOutput) String() string { +func (s VirtualGatewayLogging) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UntagResourceOutput) GoString() string { +func (s VirtualGatewayLogging) GoString() string { return s.String() } -type UpdateMeshInput struct { - _ struct{} `type:"structure"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *VirtualGatewayLogging) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayLogging"} + if s.AccessLog != nil { + if err := s.AccessLog.Validate(); err != nil { + invalidParams.AddNested("AccessLog", err.(request.ErrInvalidParams)) + } + } - ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - // MeshName is a required field - MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` +// SetAccessLog sets the AccessLog field's value. +func (s *VirtualGatewayLogging) SetAccessLog(v *VirtualGatewayAccessLog) *VirtualGatewayLogging { + s.AccessLog = v + return s +} - // An object that represents the specification of a service mesh. - Spec *MeshSpec `locationName:"spec" type:"structure"` +// An object that represents a port mapping. +type VirtualGatewayPortMapping struct { + _ struct{} `type:"structure"` + + // Port is a required field + Port *int64 `locationName:"port" min:"1" type:"integer" required:"true"` + + // Protocol is a required field + Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"VirtualGatewayPortProtocol"` } // String returns the string representation -func (s UpdateMeshInput) String() string { +func (s VirtualGatewayPortMapping) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateMeshInput) GoString() string { +func (s VirtualGatewayPortMapping) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateMeshInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateMeshInput"} - if s.MeshName == nil { - invalidParams.Add(request.NewErrParamRequired("MeshName")) +func (s *VirtualGatewayPortMapping) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayPortMapping"} + if s.Port == nil { + invalidParams.Add(request.NewErrParamRequired("Port")) } - if s.MeshName != nil && len(*s.MeshName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) } - if s.Spec != nil { - if err := s.Spec.Validate(); err != nil { - invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) - } + if s.Protocol == nil { + invalidParams.Add(request.NewErrParamRequired("Protocol")) } if invalidParams.Len() > 0 { @@ -8905,234 +13332,153 @@ func (s *UpdateMeshInput) Validate() error { return nil } -// SetClientToken sets the ClientToken field's value. -func (s *UpdateMeshInput) SetClientToken(v string) *UpdateMeshInput { - s.ClientToken = &v - return s -} - -// SetMeshName sets the MeshName field's value. -func (s *UpdateMeshInput) SetMeshName(v string) *UpdateMeshInput { - s.MeshName = &v +// SetPort sets the Port field's value. +func (s *VirtualGatewayPortMapping) SetPort(v int64) *VirtualGatewayPortMapping { + s.Port = &v return s } -// SetSpec sets the Spec field's value. -func (s *UpdateMeshInput) SetSpec(v *MeshSpec) *UpdateMeshInput { - s.Spec = v +// SetProtocol sets the Protocol field's value. +func (s *VirtualGatewayPortMapping) SetProtocol(v string) *VirtualGatewayPortMapping { + s.Protocol = &v return s } -type UpdateMeshOutput struct { - _ struct{} `type:"structure" payload:"Mesh"` - - // An object that represents a service mesh returned by a describe operation. - // - // Mesh is a required field - Mesh *MeshData `locationName:"mesh" type:"structure" required:"true"` -} - -// String returns the string representation -func (s UpdateMeshOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateMeshOutput) GoString() string { - return s.String() -} +// An object that represents a virtual gateway returned by a list operation. +type VirtualGatewayRef struct { + _ struct{} `type:"structure"` -// SetMesh sets the Mesh field's value. -func (s *UpdateMeshOutput) SetMesh(v *MeshData) *UpdateMeshOutput { - s.Mesh = v - return s -} + // Arn is a required field + Arn *string `locationName:"arn" type:"string" required:"true"` -type UpdateRouteInput struct { - _ struct{} `type:"structure"` + // CreatedAt is a required field + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"` - ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` + // LastUpdatedAt is a required field + LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"` // MeshName is a required field - MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` - MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + // MeshOwner is a required field + MeshOwner *string `locationName:"meshOwner" min:"12" type:"string" required:"true"` - // RouteName is a required field - RouteName *string `location:"uri" locationName:"routeName" min:"1" type:"string" required:"true"` + // ResourceOwner is a required field + ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"` - // An object that represents a route specification. Specify one route type. - // - // Spec is a required field - Spec *RouteSpec `locationName:"spec" type:"structure" required:"true"` + // Version is a required field + Version *int64 `locationName:"version" type:"long" required:"true"` - // VirtualRouterName is a required field - VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"` + // VirtualGatewayName is a required field + VirtualGatewayName *string `locationName:"virtualGatewayName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s UpdateRouteInput) String() string { +func (s VirtualGatewayRef) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateRouteInput) GoString() string { +func (s VirtualGatewayRef) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateRouteInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateRouteInput"} - if s.MeshName == nil { - invalidParams.Add(request.NewErrParamRequired("MeshName")) - } - if s.MeshName != nil && len(*s.MeshName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) - } - if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { - invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) - } - if s.RouteName == nil { - invalidParams.Add(request.NewErrParamRequired("RouteName")) - } - if s.RouteName != nil && len(*s.RouteName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("RouteName", 1)) - } - if s.Spec == nil { - invalidParams.Add(request.NewErrParamRequired("Spec")) - } - if s.VirtualRouterName == nil { - invalidParams.Add(request.NewErrParamRequired("VirtualRouterName")) - } - if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1)) - } - if s.Spec != nil { - if err := s.Spec.Validate(); err != nil { - invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) - } - } +// SetArn sets the Arn field's value. +func (s *VirtualGatewayRef) SetArn(v string) *VirtualGatewayRef { + s.Arn = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCreatedAt sets the CreatedAt field's value. +func (s *VirtualGatewayRef) SetCreatedAt(v time.Time) *VirtualGatewayRef { + s.CreatedAt = &v + return s } -// SetClientToken sets the ClientToken field's value. -func (s *UpdateRouteInput) SetClientToken(v string) *UpdateRouteInput { - s.ClientToken = &v +// SetLastUpdatedAt sets the LastUpdatedAt field's value. +func (s *VirtualGatewayRef) SetLastUpdatedAt(v time.Time) *VirtualGatewayRef { + s.LastUpdatedAt = &v return s } // SetMeshName sets the MeshName field's value. -func (s *UpdateRouteInput) SetMeshName(v string) *UpdateRouteInput { +func (s *VirtualGatewayRef) SetMeshName(v string) *VirtualGatewayRef { s.MeshName = &v return s } // SetMeshOwner sets the MeshOwner field's value. -func (s *UpdateRouteInput) SetMeshOwner(v string) *UpdateRouteInput { +func (s *VirtualGatewayRef) SetMeshOwner(v string) *VirtualGatewayRef { s.MeshOwner = &v return s } -// SetRouteName sets the RouteName field's value. -func (s *UpdateRouteInput) SetRouteName(v string) *UpdateRouteInput { - s.RouteName = &v - return s -} - -// SetSpec sets the Spec field's value. -func (s *UpdateRouteInput) SetSpec(v *RouteSpec) *UpdateRouteInput { - s.Spec = v +// SetResourceOwner sets the ResourceOwner field's value. +func (s *VirtualGatewayRef) SetResourceOwner(v string) *VirtualGatewayRef { + s.ResourceOwner = &v return s } -// SetVirtualRouterName sets the VirtualRouterName field's value. -func (s *UpdateRouteInput) SetVirtualRouterName(v string) *UpdateRouteInput { - s.VirtualRouterName = &v +// SetVersion sets the Version field's value. +func (s *VirtualGatewayRef) SetVersion(v int64) *VirtualGatewayRef { + s.Version = &v return s } -type UpdateRouteOutput struct { - _ struct{} `type:"structure" payload:"Route"` - - // An object that represents a route returned by a describe operation. - // - // Route is a required field - Route *RouteData `locationName:"route" type:"structure" required:"true"` -} - -// String returns the string representation -func (s UpdateRouteOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateRouteOutput) GoString() string { - return s.String() -} - -// SetRoute sets the Route field's value. -func (s *UpdateRouteOutput) SetRoute(v *RouteData) *UpdateRouteOutput { - s.Route = v +// SetVirtualGatewayName sets the VirtualGatewayName field's value. +func (s *VirtualGatewayRef) SetVirtualGatewayName(v string) *VirtualGatewayRef { + s.VirtualGatewayName = &v return s } -type UpdateVirtualNodeInput struct { +// An object that represents the specification of a service mesh resource. +type VirtualGatewaySpec struct { _ struct{} `type:"structure"` - ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` - - // MeshName is a required field - MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` - - MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` + // An object that represents the default properties for a backend. + BackendDefaults *VirtualGatewayBackendDefaults `locationName:"backendDefaults" type:"structure"` - // An object that represents the specification of a virtual node. - // - // Spec is a required field - Spec *VirtualNodeSpec `locationName:"spec" type:"structure" required:"true"` + // Listeners is a required field + Listeners []*VirtualGatewayListener `locationName:"listeners" type:"list" required:"true"` - // VirtualNodeName is a required field - VirtualNodeName *string `location:"uri" locationName:"virtualNodeName" min:"1" type:"string" required:"true"` + // An object that represents logging information. + Logging *VirtualGatewayLogging `locationName:"logging" type:"structure"` } // String returns the string representation -func (s UpdateVirtualNodeInput) String() string { +func (s VirtualGatewaySpec) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateVirtualNodeInput) GoString() string { +func (s VirtualGatewaySpec) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateVirtualNodeInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateVirtualNodeInput"} - if s.MeshName == nil { - invalidParams.Add(request.NewErrParamRequired("MeshName")) - } - if s.MeshName != nil && len(*s.MeshName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) - } - if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { - invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) +func (s *VirtualGatewaySpec) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewaySpec"} + if s.Listeners == nil { + invalidParams.Add(request.NewErrParamRequired("Listeners")) } - if s.Spec == nil { - invalidParams.Add(request.NewErrParamRequired("Spec")) - } - if s.VirtualNodeName == nil { - invalidParams.Add(request.NewErrParamRequired("VirtualNodeName")) + if s.BackendDefaults != nil { + if err := s.BackendDefaults.Validate(); err != nil { + invalidParams.AddNested("BackendDefaults", err.(request.ErrInvalidParams)) + } } - if s.VirtualNodeName != nil && len(*s.VirtualNodeName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VirtualNodeName", 1)) + if s.Listeners != nil { + for i, v := range s.Listeners { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Listeners", i), err.(request.ErrInvalidParams)) + } + } } - if s.Spec != nil { - if err := s.Spec.Validate(); err != nil { - invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) + if s.Logging != nil { + if err := s.Logging.Validate(); err != nil { + invalidParams.AddNested("Logging", err.(request.ErrInvalidParams)) } } @@ -9142,114 +13488,78 @@ func (s *UpdateVirtualNodeInput) Validate() error { return nil } -// SetClientToken sets the ClientToken field's value. -func (s *UpdateVirtualNodeInput) SetClientToken(v string) *UpdateVirtualNodeInput { - s.ClientToken = &v - return s -} - -// SetMeshName sets the MeshName field's value. -func (s *UpdateVirtualNodeInput) SetMeshName(v string) *UpdateVirtualNodeInput { - s.MeshName = &v - return s -} - -// SetMeshOwner sets the MeshOwner field's value. -func (s *UpdateVirtualNodeInput) SetMeshOwner(v string) *UpdateVirtualNodeInput { - s.MeshOwner = &v +// SetBackendDefaults sets the BackendDefaults field's value. +func (s *VirtualGatewaySpec) SetBackendDefaults(v *VirtualGatewayBackendDefaults) *VirtualGatewaySpec { + s.BackendDefaults = v return s } -// SetSpec sets the Spec field's value. -func (s *UpdateVirtualNodeInput) SetSpec(v *VirtualNodeSpec) *UpdateVirtualNodeInput { - s.Spec = v +// SetListeners sets the Listeners field's value. +func (s *VirtualGatewaySpec) SetListeners(v []*VirtualGatewayListener) *VirtualGatewaySpec { + s.Listeners = v return s } -// SetVirtualNodeName sets the VirtualNodeName field's value. -func (s *UpdateVirtualNodeInput) SetVirtualNodeName(v string) *UpdateVirtualNodeInput { - s.VirtualNodeName = &v +// SetLogging sets the Logging field's value. +func (s *VirtualGatewaySpec) SetLogging(v *VirtualGatewayLogging) *VirtualGatewaySpec { + s.Logging = v return s } -type UpdateVirtualNodeOutput struct { - _ struct{} `type:"structure" payload:"VirtualNode"` +// An object that represents the status of the mesh resource. +type VirtualGatewayStatus struct { + _ struct{} `type:"structure"` - // An object that represents a virtual node returned by a describe operation. - // - // VirtualNode is a required field - VirtualNode *VirtualNodeData `locationName:"virtualNode" type:"structure" required:"true"` + // Status is a required field + Status *string `locationName:"status" type:"string" required:"true" enum:"VirtualGatewayStatusCode"` } // String returns the string representation -func (s UpdateVirtualNodeOutput) String() string { +func (s VirtualGatewayStatus) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateVirtualNodeOutput) GoString() string { +func (s VirtualGatewayStatus) GoString() string { return s.String() } -// SetVirtualNode sets the VirtualNode field's value. -func (s *UpdateVirtualNodeOutput) SetVirtualNode(v *VirtualNodeData) *UpdateVirtualNodeOutput { - s.VirtualNode = v +// SetStatus sets the Status field's value. +func (s *VirtualGatewayStatus) SetStatus(v string) *VirtualGatewayStatus { + s.Status = &v return s } -type UpdateVirtualRouterInput struct { +// An object that represents a Transport Layer Security (TLS) validation context. +type VirtualGatewayTlsValidationContext struct { _ struct{} `type:"structure"` - ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` - - // MeshName is a required field - MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` - - MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` - - // An object that represents the specification of a virtual router. + // An object that represents a Transport Layer Security (TLS) validation context + // trust. // - // Spec is a required field - Spec *VirtualRouterSpec `locationName:"spec" type:"structure" required:"true"` - - // VirtualRouterName is a required field - VirtualRouterName *string `location:"uri" locationName:"virtualRouterName" min:"1" type:"string" required:"true"` + // Trust is a required field + Trust *VirtualGatewayTlsValidationContextTrust `locationName:"trust" type:"structure" required:"true"` } // String returns the string representation -func (s UpdateVirtualRouterInput) String() string { +func (s VirtualGatewayTlsValidationContext) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateVirtualRouterInput) GoString() string { +func (s VirtualGatewayTlsValidationContext) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateVirtualRouterInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateVirtualRouterInput"} - if s.MeshName == nil { - invalidParams.Add(request.NewErrParamRequired("MeshName")) - } - if s.MeshName != nil && len(*s.MeshName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) - } - if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { - invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) - } - if s.Spec == nil { - invalidParams.Add(request.NewErrParamRequired("Spec")) - } - if s.VirtualRouterName == nil { - invalidParams.Add(request.NewErrParamRequired("VirtualRouterName")) - } - if s.VirtualRouterName != nil && len(*s.VirtualRouterName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VirtualRouterName", 1)) +func (s *VirtualGatewayTlsValidationContext) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayTlsValidationContext"} + if s.Trust == nil { + invalidParams.Add(request.NewErrParamRequired("Trust")) } - if s.Spec != nil { - if err := s.Spec.Validate(); err != nil { - invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) + if s.Trust != nil { + if err := s.Trust.Validate(); err != nil { + invalidParams.AddNested("Trust", err.(request.ErrInvalidParams)) } } @@ -9259,115 +13569,80 @@ func (s *UpdateVirtualRouterInput) Validate() error { return nil } -// SetClientToken sets the ClientToken field's value. -func (s *UpdateVirtualRouterInput) SetClientToken(v string) *UpdateVirtualRouterInput { - s.ClientToken = &v - return s -} - -// SetMeshName sets the MeshName field's value. -func (s *UpdateVirtualRouterInput) SetMeshName(v string) *UpdateVirtualRouterInput { - s.MeshName = &v - return s -} - -// SetMeshOwner sets the MeshOwner field's value. -func (s *UpdateVirtualRouterInput) SetMeshOwner(v string) *UpdateVirtualRouterInput { - s.MeshOwner = &v - return s -} - -// SetSpec sets the Spec field's value. -func (s *UpdateVirtualRouterInput) SetSpec(v *VirtualRouterSpec) *UpdateVirtualRouterInput { - s.Spec = v - return s -} - -// SetVirtualRouterName sets the VirtualRouterName field's value. -func (s *UpdateVirtualRouterInput) SetVirtualRouterName(v string) *UpdateVirtualRouterInput { - s.VirtualRouterName = &v +// SetTrust sets the Trust field's value. +func (s *VirtualGatewayTlsValidationContext) SetTrust(v *VirtualGatewayTlsValidationContextTrust) *VirtualGatewayTlsValidationContext { + s.Trust = v return s } -type UpdateVirtualRouterOutput struct { - _ struct{} `type:"structure" payload:"VirtualRouter"` +// An object that represents a TLS validation context trust for an AWS Certicate +// Manager (ACM) certificate. +type VirtualGatewayTlsValidationContextAcmTrust struct { + _ struct{} `type:"structure"` - // An object that represents a virtual router returned by a describe operation. - // - // VirtualRouter is a required field - VirtualRouter *VirtualRouterData `locationName:"virtualRouter" type:"structure" required:"true"` + // CertificateAuthorityArns is a required field + CertificateAuthorityArns []*string `locationName:"certificateAuthorityArns" min:"1" type:"list" required:"true"` } // String returns the string representation -func (s UpdateVirtualRouterOutput) String() string { +func (s VirtualGatewayTlsValidationContextAcmTrust) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateVirtualRouterOutput) GoString() string { +func (s VirtualGatewayTlsValidationContextAcmTrust) GoString() string { return s.String() } -// SetVirtualRouter sets the VirtualRouter field's value. -func (s *UpdateVirtualRouterOutput) SetVirtualRouter(v *VirtualRouterData) *UpdateVirtualRouterOutput { - s.VirtualRouter = v - return s -} - -type UpdateVirtualServiceInput struct { - _ struct{} `type:"structure"` - - ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *VirtualGatewayTlsValidationContextAcmTrust) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayTlsValidationContextAcmTrust"} + if s.CertificateAuthorityArns == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateAuthorityArns")) + } + if s.CertificateAuthorityArns != nil && len(s.CertificateAuthorityArns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CertificateAuthorityArns", 1)) + } - // MeshName is a required field - MeshName *string `location:"uri" locationName:"meshName" min:"1" type:"string" required:"true"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - MeshOwner *string `location:"querystring" locationName:"meshOwner" min:"12" type:"string"` +// SetCertificateAuthorityArns sets the CertificateAuthorityArns field's value. +func (s *VirtualGatewayTlsValidationContextAcmTrust) SetCertificateAuthorityArns(v []*string) *VirtualGatewayTlsValidationContextAcmTrust { + s.CertificateAuthorityArns = v + return s +} - // An object that represents the specification of a virtual service. - // - // Spec is a required field - Spec *VirtualServiceSpec `locationName:"spec" type:"structure" required:"true"` +// An object that represents a Transport Layer Security (TLS) validation context +// trust for a local file. +type VirtualGatewayTlsValidationContextFileTrust struct { + _ struct{} `type:"structure"` - // VirtualServiceName is a required field - VirtualServiceName *string `location:"uri" locationName:"virtualServiceName" type:"string" required:"true"` + // CertificateChain is a required field + CertificateChain *string `locationName:"certificateChain" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s UpdateVirtualServiceInput) String() string { +func (s VirtualGatewayTlsValidationContextFileTrust) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateVirtualServiceInput) GoString() string { +func (s VirtualGatewayTlsValidationContextFileTrust) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateVirtualServiceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateVirtualServiceInput"} - if s.MeshName == nil { - invalidParams.Add(request.NewErrParamRequired("MeshName")) - } - if s.MeshName != nil && len(*s.MeshName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MeshName", 1)) - } - if s.MeshOwner != nil && len(*s.MeshOwner) < 12 { - invalidParams.Add(request.NewErrParamMinLen("MeshOwner", 12)) - } - if s.Spec == nil { - invalidParams.Add(request.NewErrParamRequired("Spec")) - } - if s.VirtualServiceName == nil { - invalidParams.Add(request.NewErrParamRequired("VirtualServiceName")) - } - if s.VirtualServiceName != nil && len(*s.VirtualServiceName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VirtualServiceName", 1)) +func (s *VirtualGatewayTlsValidationContextFileTrust) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayTlsValidationContextFileTrust"} + if s.CertificateChain == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateChain")) } - if s.Spec != nil { - if err := s.Spec.Validate(); err != nil { - invalidParams.AddNested("Spec", err.(request.ErrInvalidParams)) - } + if s.CertificateChain != nil && len(*s.CertificateChain) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CertificateChain", 1)) } if invalidParams.Len() > 0 { @@ -9376,58 +13651,65 @@ func (s *UpdateVirtualServiceInput) Validate() error { return nil } -// SetClientToken sets the ClientToken field's value. -func (s *UpdateVirtualServiceInput) SetClientToken(v string) *UpdateVirtualServiceInput { - s.ClientToken = &v - return s -} - -// SetMeshName sets the MeshName field's value. -func (s *UpdateVirtualServiceInput) SetMeshName(v string) *UpdateVirtualServiceInput { - s.MeshName = &v - return s -} - -// SetMeshOwner sets the MeshOwner field's value. -func (s *UpdateVirtualServiceInput) SetMeshOwner(v string) *UpdateVirtualServiceInput { - s.MeshOwner = &v - return s -} - -// SetSpec sets the Spec field's value. -func (s *UpdateVirtualServiceInput) SetSpec(v *VirtualServiceSpec) *UpdateVirtualServiceInput { - s.Spec = v +// SetCertificateChain sets the CertificateChain field's value. +func (s *VirtualGatewayTlsValidationContextFileTrust) SetCertificateChain(v string) *VirtualGatewayTlsValidationContextFileTrust { + s.CertificateChain = &v return s } -// SetVirtualServiceName sets the VirtualServiceName field's value. -func (s *UpdateVirtualServiceInput) SetVirtualServiceName(v string) *UpdateVirtualServiceInput { - s.VirtualServiceName = &v - return s -} +// An object that represents a Transport Layer Security (TLS) validation context +// trust. +type VirtualGatewayTlsValidationContextTrust struct { + _ struct{} `type:"structure"` -type UpdateVirtualServiceOutput struct { - _ struct{} `type:"structure" payload:"VirtualService"` + // An object that represents a TLS validation context trust for an AWS Certicate + // Manager (ACM) certificate. + Acm *VirtualGatewayTlsValidationContextAcmTrust `locationName:"acm" type:"structure"` - // An object that represents a virtual service returned by a describe operation. - // - // VirtualService is a required field - VirtualService *VirtualServiceData `locationName:"virtualService" type:"structure" required:"true"` + // An object that represents a Transport Layer Security (TLS) validation context + // trust for a local file. + File *VirtualGatewayTlsValidationContextFileTrust `locationName:"file" type:"structure"` } // String returns the string representation -func (s UpdateVirtualServiceOutput) String() string { +func (s VirtualGatewayTlsValidationContextTrust) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateVirtualServiceOutput) GoString() string { +func (s VirtualGatewayTlsValidationContextTrust) GoString() string { return s.String() } -// SetVirtualService sets the VirtualService field's value. -func (s *UpdateVirtualServiceOutput) SetVirtualService(v *VirtualServiceData) *UpdateVirtualServiceOutput { - s.VirtualService = v +// Validate inspects the fields of the type to determine if they are valid. +func (s *VirtualGatewayTlsValidationContextTrust) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VirtualGatewayTlsValidationContextTrust"} + if s.Acm != nil { + if err := s.Acm.Validate(); err != nil { + invalidParams.AddNested("Acm", err.(request.ErrInvalidParams)) + } + } + if s.File != nil { + if err := s.File.Validate(); err != nil { + invalidParams.AddNested("File", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAcm sets the Acm field's value. +func (s *VirtualGatewayTlsValidationContextTrust) SetAcm(v *VirtualGatewayTlsValidationContextAcmTrust) *VirtualGatewayTlsValidationContextTrust { + s.Acm = v + return s +} + +// SetFile sets the File field's value. +func (s *VirtualGatewayTlsValidationContextTrust) SetFile(v *VirtualGatewayTlsValidationContextFileTrust) *VirtualGatewayTlsValidationContextTrust { + s.File = v return s } @@ -9504,6 +13786,12 @@ type VirtualNodeRef struct { // Arn is a required field Arn *string `locationName:"arn" type:"string" required:"true"` + // CreatedAt is a required field + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"` + + // LastUpdatedAt is a required field + LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"` + // MeshName is a required field MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` @@ -9513,6 +13801,9 @@ type VirtualNodeRef struct { // ResourceOwner is a required field ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"` + // Version is a required field + Version *int64 `locationName:"version" type:"long" required:"true"` + // VirtualNodeName is a required field VirtualNodeName *string `locationName:"virtualNodeName" min:"1" type:"string" required:"true"` } @@ -9533,6 +13824,18 @@ func (s *VirtualNodeRef) SetArn(v string) *VirtualNodeRef { return s } +// SetCreatedAt sets the CreatedAt field's value. +func (s *VirtualNodeRef) SetCreatedAt(v time.Time) *VirtualNodeRef { + s.CreatedAt = &v + return s +} + +// SetLastUpdatedAt sets the LastUpdatedAt field's value. +func (s *VirtualNodeRef) SetLastUpdatedAt(v time.Time) *VirtualNodeRef { + s.LastUpdatedAt = &v + return s +} + // SetMeshName sets the MeshName field's value. func (s *VirtualNodeRef) SetMeshName(v string) *VirtualNodeRef { s.MeshName = &v @@ -9551,6 +13854,12 @@ func (s *VirtualNodeRef) SetResourceOwner(v string) *VirtualNodeRef { return s } +// SetVersion sets the Version field's value. +func (s *VirtualNodeRef) SetVersion(v int64) *VirtualNodeRef { + s.Version = &v + return s +} + // SetVirtualNodeName sets the VirtualNodeName field's value. func (s *VirtualNodeRef) SetVirtualNodeName(v string) *VirtualNodeRef { s.VirtualNodeName = &v @@ -9842,6 +14151,12 @@ type VirtualRouterRef struct { // Arn is a required field Arn *string `locationName:"arn" type:"string" required:"true"` + // CreatedAt is a required field + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"` + + // LastUpdatedAt is a required field + LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"` + // MeshName is a required field MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` @@ -9851,6 +14166,9 @@ type VirtualRouterRef struct { // ResourceOwner is a required field ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"` + // Version is a required field + Version *int64 `locationName:"version" type:"long" required:"true"` + // VirtualRouterName is a required field VirtualRouterName *string `locationName:"virtualRouterName" min:"1" type:"string" required:"true"` } @@ -9871,6 +14189,18 @@ func (s *VirtualRouterRef) SetArn(v string) *VirtualRouterRef { return s } +// SetCreatedAt sets the CreatedAt field's value. +func (s *VirtualRouterRef) SetCreatedAt(v time.Time) *VirtualRouterRef { + s.CreatedAt = &v + return s +} + +// SetLastUpdatedAt sets the LastUpdatedAt field's value. +func (s *VirtualRouterRef) SetLastUpdatedAt(v time.Time) *VirtualRouterRef { + s.LastUpdatedAt = &v + return s +} + // SetMeshName sets the MeshName field's value. func (s *VirtualRouterRef) SetMeshName(v string) *VirtualRouterRef { s.MeshName = &v @@ -9889,6 +14219,12 @@ func (s *VirtualRouterRef) SetResourceOwner(v string) *VirtualRouterRef { return s } +// SetVersion sets the Version field's value. +func (s *VirtualRouterRef) SetVersion(v int64) *VirtualRouterRef { + s.Version = &v + return s +} + // SetVirtualRouterName sets the VirtualRouterName field's value. func (s *VirtualRouterRef) SetVirtualRouterName(v string) *VirtualRouterRef { s.VirtualRouterName = &v @@ -10182,6 +14518,12 @@ type VirtualServiceRef struct { // Arn is a required field Arn *string `locationName:"arn" type:"string" required:"true"` + // CreatedAt is a required field + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" required:"true"` + + // LastUpdatedAt is a required field + LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp" required:"true"` + // MeshName is a required field MeshName *string `locationName:"meshName" min:"1" type:"string" required:"true"` @@ -10191,6 +14533,9 @@ type VirtualServiceRef struct { // ResourceOwner is a required field ResourceOwner *string `locationName:"resourceOwner" min:"12" type:"string" required:"true"` + // Version is a required field + Version *int64 `locationName:"version" type:"long" required:"true"` + // VirtualServiceName is a required field VirtualServiceName *string `locationName:"virtualServiceName" type:"string" required:"true"` } @@ -10211,6 +14556,18 @@ func (s *VirtualServiceRef) SetArn(v string) *VirtualServiceRef { return s } +// SetCreatedAt sets the CreatedAt field's value. +func (s *VirtualServiceRef) SetCreatedAt(v time.Time) *VirtualServiceRef { + s.CreatedAt = &v + return s +} + +// SetLastUpdatedAt sets the LastUpdatedAt field's value. +func (s *VirtualServiceRef) SetLastUpdatedAt(v time.Time) *VirtualServiceRef { + s.LastUpdatedAt = &v + return s +} + // SetMeshName sets the MeshName field's value. func (s *VirtualServiceRef) SetMeshName(v string) *VirtualServiceRef { s.MeshName = &v @@ -10229,6 +14586,12 @@ func (s *VirtualServiceRef) SetResourceOwner(v string) *VirtualServiceRef { return s } +// SetVersion sets the Version field's value. +func (s *VirtualServiceRef) SetVersion(v int64) *VirtualServiceRef { + s.Version = &v + return s +} + // SetVirtualServiceName sets the VirtualServiceName field's value. func (s *VirtualServiceRef) SetVirtualServiceName(v string) *VirtualServiceRef { s.VirtualServiceName = &v @@ -10362,6 +14725,14 @@ const ( DurationUnitS = "s" ) +// DurationUnit_Values returns all elements of the DurationUnit enum +func DurationUnit_Values() []string { + return []string{ + DurationUnitMs, + DurationUnitS, + } +} + const ( // EgressFilterTypeAllowAll is a EgressFilterType enum value EgressFilterTypeAllowAll = "ALLOW_ALL" @@ -10370,6 +14741,34 @@ const ( EgressFilterTypeDropAll = "DROP_ALL" ) +// EgressFilterType_Values returns all elements of the EgressFilterType enum +func EgressFilterType_Values() []string { + return []string{ + EgressFilterTypeAllowAll, + EgressFilterTypeDropAll, + } +} + +const ( + // GatewayRouteStatusCodeActive is a GatewayRouteStatusCode enum value + GatewayRouteStatusCodeActive = "ACTIVE" + + // GatewayRouteStatusCodeDeleted is a GatewayRouteStatusCode enum value + GatewayRouteStatusCodeDeleted = "DELETED" + + // GatewayRouteStatusCodeInactive is a GatewayRouteStatusCode enum value + GatewayRouteStatusCodeInactive = "INACTIVE" +) + +// GatewayRouteStatusCode_Values returns all elements of the GatewayRouteStatusCode enum +func GatewayRouteStatusCode_Values() []string { + return []string{ + GatewayRouteStatusCodeActive, + GatewayRouteStatusCodeDeleted, + GatewayRouteStatusCodeInactive, + } +} + const ( // GrpcRetryPolicyEventCancelled is a GrpcRetryPolicyEvent enum value GrpcRetryPolicyEventCancelled = "cancelled" @@ -10387,6 +14786,17 @@ const ( GrpcRetryPolicyEventUnavailable = "unavailable" ) +// GrpcRetryPolicyEvent_Values returns all elements of the GrpcRetryPolicyEvent enum +func GrpcRetryPolicyEvent_Values() []string { + return []string{ + GrpcRetryPolicyEventCancelled, + GrpcRetryPolicyEventDeadlineExceeded, + GrpcRetryPolicyEventInternal, + GrpcRetryPolicyEventResourceExhausted, + GrpcRetryPolicyEventUnavailable, + } +} + const ( // HttpMethodConnect is a HttpMethod enum value HttpMethodConnect = "CONNECT" @@ -10416,6 +14826,21 @@ const ( HttpMethodTrace = "TRACE" ) +// HttpMethod_Values returns all elements of the HttpMethod enum +func HttpMethod_Values() []string { + return []string{ + HttpMethodConnect, + HttpMethodDelete, + HttpMethodGet, + HttpMethodHead, + HttpMethodOptions, + HttpMethodPatch, + HttpMethodPost, + HttpMethodPut, + HttpMethodTrace, + } +} + const ( // HttpSchemeHttp is a HttpScheme enum value HttpSchemeHttp = "http" @@ -10424,6 +14849,14 @@ const ( HttpSchemeHttps = "https" ) +// HttpScheme_Values returns all elements of the HttpScheme enum +func HttpScheme_Values() []string { + return []string{ + HttpSchemeHttp, + HttpSchemeHttps, + } +} + const ( // ListenerTlsModeDisabled is a ListenerTlsMode enum value ListenerTlsModeDisabled = "DISABLED" @@ -10435,6 +14868,15 @@ const ( ListenerTlsModeStrict = "STRICT" ) +// ListenerTlsMode_Values returns all elements of the ListenerTlsMode enum +func ListenerTlsMode_Values() []string { + return []string{ + ListenerTlsModeDisabled, + ListenerTlsModePermissive, + ListenerTlsModeStrict, + } +} + const ( // MeshStatusCodeActive is a MeshStatusCode enum value MeshStatusCodeActive = "ACTIVE" @@ -10446,6 +14888,15 @@ const ( MeshStatusCodeInactive = "INACTIVE" ) +// MeshStatusCode_Values returns all elements of the MeshStatusCode enum +func MeshStatusCode_Values() []string { + return []string{ + MeshStatusCodeActive, + MeshStatusCodeDeleted, + MeshStatusCodeInactive, + } +} + const ( // PortProtocolGrpc is a PortProtocol enum value PortProtocolGrpc = "grpc" @@ -10460,6 +14911,16 @@ const ( PortProtocolTcp = "tcp" ) +// PortProtocol_Values returns all elements of the PortProtocol enum +func PortProtocol_Values() []string { + return []string{ + PortProtocolGrpc, + PortProtocolHttp, + PortProtocolHttp2, + PortProtocolTcp, + } +} + const ( // RouteStatusCodeActive is a RouteStatusCode enum value RouteStatusCodeActive = "ACTIVE" @@ -10471,11 +14932,87 @@ const ( RouteStatusCodeInactive = "INACTIVE" ) +// RouteStatusCode_Values returns all elements of the RouteStatusCode enum +func RouteStatusCode_Values() []string { + return []string{ + RouteStatusCodeActive, + RouteStatusCodeDeleted, + RouteStatusCodeInactive, + } +} + const ( // TcpRetryPolicyEventConnectionError is a TcpRetryPolicyEvent enum value TcpRetryPolicyEventConnectionError = "connection-error" ) +// TcpRetryPolicyEvent_Values returns all elements of the TcpRetryPolicyEvent enum +func TcpRetryPolicyEvent_Values() []string { + return []string{ + TcpRetryPolicyEventConnectionError, + } +} + +const ( + // VirtualGatewayListenerTlsModeDisabled is a VirtualGatewayListenerTlsMode enum value + VirtualGatewayListenerTlsModeDisabled = "DISABLED" + + // VirtualGatewayListenerTlsModePermissive is a VirtualGatewayListenerTlsMode enum value + VirtualGatewayListenerTlsModePermissive = "PERMISSIVE" + + // VirtualGatewayListenerTlsModeStrict is a VirtualGatewayListenerTlsMode enum value + VirtualGatewayListenerTlsModeStrict = "STRICT" +) + +// VirtualGatewayListenerTlsMode_Values returns all elements of the VirtualGatewayListenerTlsMode enum +func VirtualGatewayListenerTlsMode_Values() []string { + return []string{ + VirtualGatewayListenerTlsModeDisabled, + VirtualGatewayListenerTlsModePermissive, + VirtualGatewayListenerTlsModeStrict, + } +} + +const ( + // VirtualGatewayPortProtocolGrpc is a VirtualGatewayPortProtocol enum value + VirtualGatewayPortProtocolGrpc = "grpc" + + // VirtualGatewayPortProtocolHttp is a VirtualGatewayPortProtocol enum value + VirtualGatewayPortProtocolHttp = "http" + + // VirtualGatewayPortProtocolHttp2 is a VirtualGatewayPortProtocol enum value + VirtualGatewayPortProtocolHttp2 = "http2" +) + +// VirtualGatewayPortProtocol_Values returns all elements of the VirtualGatewayPortProtocol enum +func VirtualGatewayPortProtocol_Values() []string { + return []string{ + VirtualGatewayPortProtocolGrpc, + VirtualGatewayPortProtocolHttp, + VirtualGatewayPortProtocolHttp2, + } +} + +const ( + // VirtualGatewayStatusCodeActive is a VirtualGatewayStatusCode enum value + VirtualGatewayStatusCodeActive = "ACTIVE" + + // VirtualGatewayStatusCodeDeleted is a VirtualGatewayStatusCode enum value + VirtualGatewayStatusCodeDeleted = "DELETED" + + // VirtualGatewayStatusCodeInactive is a VirtualGatewayStatusCode enum value + VirtualGatewayStatusCodeInactive = "INACTIVE" +) + +// VirtualGatewayStatusCode_Values returns all elements of the VirtualGatewayStatusCode enum +func VirtualGatewayStatusCode_Values() []string { + return []string{ + VirtualGatewayStatusCodeActive, + VirtualGatewayStatusCodeDeleted, + VirtualGatewayStatusCodeInactive, + } +} + const ( // VirtualNodeStatusCodeActive is a VirtualNodeStatusCode enum value VirtualNodeStatusCodeActive = "ACTIVE" @@ -10487,6 +15024,15 @@ const ( VirtualNodeStatusCodeInactive = "INACTIVE" ) +// VirtualNodeStatusCode_Values returns all elements of the VirtualNodeStatusCode enum +func VirtualNodeStatusCode_Values() []string { + return []string{ + VirtualNodeStatusCodeActive, + VirtualNodeStatusCodeDeleted, + VirtualNodeStatusCodeInactive, + } +} + const ( // VirtualRouterStatusCodeActive is a VirtualRouterStatusCode enum value VirtualRouterStatusCodeActive = "ACTIVE" @@ -10498,6 +15044,15 @@ const ( VirtualRouterStatusCodeInactive = "INACTIVE" ) +// VirtualRouterStatusCode_Values returns all elements of the VirtualRouterStatusCode enum +func VirtualRouterStatusCode_Values() []string { + return []string{ + VirtualRouterStatusCodeActive, + VirtualRouterStatusCodeDeleted, + VirtualRouterStatusCodeInactive, + } +} + const ( // VirtualServiceStatusCodeActive is a VirtualServiceStatusCode enum value VirtualServiceStatusCodeActive = "ACTIVE" @@ -10508,3 +15063,12 @@ const ( // VirtualServiceStatusCodeInactive is a VirtualServiceStatusCode enum value VirtualServiceStatusCodeInactive = "INACTIVE" ) + +// VirtualServiceStatusCode_Values returns all elements of the VirtualServiceStatusCode enum +func VirtualServiceStatusCode_Values() []string { + return []string{ + VirtualServiceStatusCodeActive, + VirtualServiceStatusCodeDeleted, + VirtualServiceStatusCodeInactive, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/appmesh/doc.go b/vendor/github.com/aws/aws-sdk-go/service/appmesh/doc.go index 09a02953834..66f3509f3e4 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/appmesh/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/appmesh/doc.go @@ -14,7 +14,7 @@ // // App Mesh supports microservice applications that use service discovery naming // for their components. For more information about service discovery on Amazon -// ECS, see Service Discovery (http://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-discovery.html) +// ECS, see Service Discovery (https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-discovery.html) // in the Amazon Elastic Container Service Developer Guide. Kubernetes kube-dns // and coredns are supported. For more information, see DNS for Services and // Pods (https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/) diff --git a/vendor/github.com/aws/aws-sdk-go/service/appmesh/errors.go b/vendor/github.com/aws/aws-sdk-go/service/appmesh/errors.go index 9e60da8d1d0..96973b8dae2 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/appmesh/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/appmesh/errors.go @@ -39,7 +39,7 @@ const ( // "LimitExceededException". // // You have exceeded a service limit for your account. For more information, - // see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service_limits.html) + // see Service Limits (https://docs.aws.amazon.com/app-mesh/latest/userguide/service-quotas.html) // in the AWS App Mesh User Guide. ErrCodeLimitExceededException = "LimitExceededException" diff --git a/vendor/github.com/aws/aws-sdk-go/service/appstream/api.go b/vendor/github.com/aws/aws-sdk-go/service/appstream/api.go index 7d4306f2f07..0335bb7e0ed 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/appstream/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/appstream/api.go @@ -11664,6 +11664,13 @@ const ( AccessEndpointTypeStreaming = "STREAMING" ) +// AccessEndpointType_Values returns all elements of the AccessEndpointType enum +func AccessEndpointType_Values() []string { + return []string{ + AccessEndpointTypeStreaming, + } +} + const ( // ActionClipboardCopyFromLocalDevice is a Action enum value ActionClipboardCopyFromLocalDevice = "CLIPBOARD_COPY_FROM_LOCAL_DEVICE" @@ -11681,6 +11688,17 @@ const ( ActionPrintingToLocalDevice = "PRINTING_TO_LOCAL_DEVICE" ) +// Action_Values returns all elements of the Action enum +func Action_Values() []string { + return []string{ + ActionClipboardCopyFromLocalDevice, + ActionClipboardCopyToLocalDevice, + ActionFileUpload, + ActionFileDownload, + ActionPrintingToLocalDevice, + } +} + const ( // AuthenticationTypeApi is a AuthenticationType enum value AuthenticationTypeApi = "API" @@ -11692,6 +11710,15 @@ const ( AuthenticationTypeUserpool = "USERPOOL" ) +// AuthenticationType_Values returns all elements of the AuthenticationType enum +func AuthenticationType_Values() []string { + return []string{ + AuthenticationTypeApi, + AuthenticationTypeSaml, + AuthenticationTypeUserpool, + } +} + // The fleet attribute. const ( // FleetAttributeVpcConfiguration is a FleetAttribute enum value @@ -11707,6 +11734,16 @@ const ( FleetAttributeIamRoleArn = "IAM_ROLE_ARN" ) +// FleetAttribute_Values returns all elements of the FleetAttribute enum +func FleetAttribute_Values() []string { + return []string{ + FleetAttributeVpcConfiguration, + FleetAttributeVpcConfigurationSecurityGroupIds, + FleetAttributeDomainJoinInfo, + FleetAttributeIamRoleArn, + } +} + const ( // FleetErrorCodeIamServiceRoleMissingEniDescribeAction is a FleetErrorCode enum value FleetErrorCodeIamServiceRoleMissingEniDescribeAction = "IAM_SERVICE_ROLE_MISSING_ENI_DESCRIBE_ACTION" @@ -11793,6 +11830,40 @@ const ( FleetErrorCodeDomainJoinInternalServiceError = "DOMAIN_JOIN_INTERNAL_SERVICE_ERROR" ) +// FleetErrorCode_Values returns all elements of the FleetErrorCode enum +func FleetErrorCode_Values() []string { + return []string{ + FleetErrorCodeIamServiceRoleMissingEniDescribeAction, + FleetErrorCodeIamServiceRoleMissingEniCreateAction, + FleetErrorCodeIamServiceRoleMissingEniDeleteAction, + FleetErrorCodeNetworkInterfaceLimitExceeded, + FleetErrorCodeInternalServiceError, + FleetErrorCodeIamServiceRoleIsMissing, + FleetErrorCodeMachineRoleIsMissing, + FleetErrorCodeStsDisabledInRegion, + FleetErrorCodeSubnetHasInsufficientIpAddresses, + FleetErrorCodeIamServiceRoleMissingDescribeSubnetAction, + FleetErrorCodeSubnetNotFound, + FleetErrorCodeImageNotFound, + FleetErrorCodeInvalidSubnetConfiguration, + FleetErrorCodeSecurityGroupsNotFound, + FleetErrorCodeIgwNotAttached, + FleetErrorCodeIamServiceRoleMissingDescribeSecurityGroupsAction, + FleetErrorCodeDomainJoinErrorFileNotFound, + FleetErrorCodeDomainJoinErrorAccessDenied, + FleetErrorCodeDomainJoinErrorLogonFailure, + FleetErrorCodeDomainJoinErrorInvalidParameter, + FleetErrorCodeDomainJoinErrorMoreData, + FleetErrorCodeDomainJoinErrorNoSuchDomain, + FleetErrorCodeDomainJoinErrorNotSupported, + FleetErrorCodeDomainJoinNerrInvalidWorkgroupName, + FleetErrorCodeDomainJoinNerrWorkstationNotStarted, + FleetErrorCodeDomainJoinErrorDsMachineAccountQuotaExceeded, + FleetErrorCodeDomainJoinNerrPasswordExpired, + FleetErrorCodeDomainJoinInternalServiceError, + } +} + const ( // FleetStateStarting is a FleetState enum value FleetStateStarting = "STARTING" @@ -11807,6 +11878,16 @@ const ( FleetStateStopped = "STOPPED" ) +// FleetState_Values returns all elements of the FleetState enum +func FleetState_Values() []string { + return []string{ + FleetStateStarting, + FleetStateRunning, + FleetStateStopping, + FleetStateStopped, + } +} + const ( // FleetTypeAlwaysOn is a FleetType enum value FleetTypeAlwaysOn = "ALWAYS_ON" @@ -11815,6 +11896,14 @@ const ( FleetTypeOnDemand = "ON_DEMAND" ) +// FleetType_Values returns all elements of the FleetType enum +func FleetType_Values() []string { + return []string{ + FleetTypeAlwaysOn, + FleetTypeOnDemand, + } +} + const ( // ImageBuilderStatePending is a ImageBuilderState enum value ImageBuilderStatePending = "PENDING" @@ -11844,6 +11933,21 @@ const ( ImageBuilderStateFailed = "FAILED" ) +// ImageBuilderState_Values returns all elements of the ImageBuilderState enum +func ImageBuilderState_Values() []string { + return []string{ + ImageBuilderStatePending, + ImageBuilderStateUpdatingAgent, + ImageBuilderStateRunning, + ImageBuilderStateStopping, + ImageBuilderStateStopped, + ImageBuilderStateRebooting, + ImageBuilderStateSnapshotting, + ImageBuilderStateDeleting, + ImageBuilderStateFailed, + } +} + const ( // ImageBuilderStateChangeReasonCodeInternalError is a ImageBuilderStateChangeReasonCode enum value ImageBuilderStateChangeReasonCodeInternalError = "INTERNAL_ERROR" @@ -11852,6 +11956,14 @@ const ( ImageBuilderStateChangeReasonCodeImageUnavailable = "IMAGE_UNAVAILABLE" ) +// ImageBuilderStateChangeReasonCode_Values returns all elements of the ImageBuilderStateChangeReasonCode enum +func ImageBuilderStateChangeReasonCode_Values() []string { + return []string{ + ImageBuilderStateChangeReasonCodeInternalError, + ImageBuilderStateChangeReasonCodeImageUnavailable, + } +} + const ( // ImageStatePending is a ImageState enum value ImageStatePending = "PENDING" @@ -11869,6 +11981,17 @@ const ( ImageStateDeleting = "DELETING" ) +// ImageState_Values returns all elements of the ImageState enum +func ImageState_Values() []string { + return []string{ + ImageStatePending, + ImageStateAvailable, + ImageStateFailed, + ImageStateCopying, + ImageStateDeleting, + } +} + const ( // ImageStateChangeReasonCodeInternalError is a ImageStateChangeReasonCode enum value ImageStateChangeReasonCodeInternalError = "INTERNAL_ERROR" @@ -11880,6 +12003,15 @@ const ( ImageStateChangeReasonCodeImageCopyFailure = "IMAGE_COPY_FAILURE" ) +// ImageStateChangeReasonCode_Values returns all elements of the ImageStateChangeReasonCode enum +func ImageStateChangeReasonCode_Values() []string { + return []string{ + ImageStateChangeReasonCodeInternalError, + ImageStateChangeReasonCodeImageBuilderNotAvailable, + ImageStateChangeReasonCodeImageCopyFailure, + } +} + const ( // MessageActionSuppress is a MessageAction enum value MessageActionSuppress = "SUPPRESS" @@ -11888,6 +12020,14 @@ const ( MessageActionResend = "RESEND" ) +// MessageAction_Values returns all elements of the MessageAction enum +func MessageAction_Values() []string { + return []string{ + MessageActionSuppress, + MessageActionResend, + } +} + const ( // PermissionEnabled is a Permission enum value PermissionEnabled = "ENABLED" @@ -11896,6 +12036,14 @@ const ( PermissionDisabled = "DISABLED" ) +// Permission_Values returns all elements of the Permission enum +func Permission_Values() []string { + return []string{ + PermissionEnabled, + PermissionDisabled, + } +} + const ( // PlatformTypeWindows is a PlatformType enum value PlatformTypeWindows = "WINDOWS" @@ -11907,6 +12055,15 @@ const ( PlatformTypeWindowsServer2019 = "WINDOWS_SERVER_2019" ) +// PlatformType_Values returns all elements of the PlatformType enum +func PlatformType_Values() []string { + return []string{ + PlatformTypeWindows, + PlatformTypeWindowsServer2016, + PlatformTypeWindowsServer2019, + } +} + const ( // SessionConnectionStateConnected is a SessionConnectionState enum value SessionConnectionStateConnected = "CONNECTED" @@ -11915,6 +12072,14 @@ const ( SessionConnectionStateNotConnected = "NOT_CONNECTED" ) +// SessionConnectionState_Values returns all elements of the SessionConnectionState enum +func SessionConnectionState_Values() []string { + return []string{ + SessionConnectionStateConnected, + SessionConnectionStateNotConnected, + } +} + // Possible values for the state of a streaming session. const ( // SessionStateActive is a SessionState enum value @@ -11927,6 +12092,15 @@ const ( SessionStateExpired = "EXPIRED" ) +// SessionState_Values returns all elements of the SessionState enum +func SessionState_Values() []string { + return []string{ + SessionStateActive, + SessionStatePending, + SessionStateExpired, + } +} + const ( // StackAttributeStorageConnectors is a StackAttribute enum value StackAttributeStorageConnectors = "STORAGE_CONNECTORS" @@ -11962,6 +12136,23 @@ const ( StackAttributeAccessEndpoints = "ACCESS_ENDPOINTS" ) +// StackAttribute_Values returns all elements of the StackAttribute enum +func StackAttribute_Values() []string { + return []string{ + StackAttributeStorageConnectors, + StackAttributeStorageConnectorHomefolders, + StackAttributeStorageConnectorGoogleDrive, + StackAttributeStorageConnectorOneDrive, + StackAttributeRedirectUrl, + StackAttributeFeedbackUrl, + StackAttributeThemeName, + StackAttributeUserSettings, + StackAttributeEmbedHostDomains, + StackAttributeIamRoleArn, + StackAttributeAccessEndpoints, + } +} + const ( // StackErrorCodeStorageConnectorError is a StackErrorCode enum value StackErrorCodeStorageConnectorError = "STORAGE_CONNECTOR_ERROR" @@ -11970,6 +12161,14 @@ const ( StackErrorCodeInternalServiceError = "INTERNAL_SERVICE_ERROR" ) +// StackErrorCode_Values returns all elements of the StackErrorCode enum +func StackErrorCode_Values() []string { + return []string{ + StackErrorCodeStorageConnectorError, + StackErrorCodeInternalServiceError, + } +} + // The type of storage connector. const ( // StorageConnectorTypeHomefolders is a StorageConnectorType enum value @@ -11982,6 +12181,15 @@ const ( StorageConnectorTypeOneDrive = "ONE_DRIVE" ) +// StorageConnectorType_Values returns all elements of the StorageConnectorType enum +func StorageConnectorType_Values() []string { + return []string{ + StorageConnectorTypeHomefolders, + StorageConnectorTypeGoogleDrive, + StorageConnectorTypeOneDrive, + } +} + const ( // UsageReportExecutionErrorCodeResourceNotFound is a UsageReportExecutionErrorCode enum value UsageReportExecutionErrorCodeResourceNotFound = "RESOURCE_NOT_FOUND" @@ -11993,11 +12201,27 @@ const ( UsageReportExecutionErrorCodeInternalServiceError = "INTERNAL_SERVICE_ERROR" ) +// UsageReportExecutionErrorCode_Values returns all elements of the UsageReportExecutionErrorCode enum +func UsageReportExecutionErrorCode_Values() []string { + return []string{ + UsageReportExecutionErrorCodeResourceNotFound, + UsageReportExecutionErrorCodeAccessDenied, + UsageReportExecutionErrorCodeInternalServiceError, + } +} + const ( // UsageReportScheduleDaily is a UsageReportSchedule enum value UsageReportScheduleDaily = "DAILY" ) +// UsageReportSchedule_Values returns all elements of the UsageReportSchedule enum +func UsageReportSchedule_Values() []string { + return []string{ + UsageReportScheduleDaily, + } +} + const ( // UserStackAssociationErrorCodeStackNotFound is a UserStackAssociationErrorCode enum value UserStackAssociationErrorCodeStackNotFound = "STACK_NOT_FOUND" @@ -12009,6 +12233,15 @@ const ( UserStackAssociationErrorCodeInternalError = "INTERNAL_ERROR" ) +// UserStackAssociationErrorCode_Values returns all elements of the UserStackAssociationErrorCode enum +func UserStackAssociationErrorCode_Values() []string { + return []string{ + UserStackAssociationErrorCodeStackNotFound, + UserStackAssociationErrorCodeUserNameNotFound, + UserStackAssociationErrorCodeInternalError, + } +} + const ( // VisibilityTypePublic is a VisibilityType enum value VisibilityTypePublic = "PUBLIC" @@ -12019,3 +12252,12 @@ const ( // VisibilityTypeShared is a VisibilityType enum value VisibilityTypeShared = "SHARED" ) + +// VisibilityType_Values returns all elements of the VisibilityType enum +func VisibilityType_Values() []string { + return []string{ + VisibilityTypePublic, + VisibilityTypePrivate, + VisibilityTypeShared, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/appsync/api.go b/vendor/github.com/aws/aws-sdk-go/service/appsync/api.go index 8215648e8d8..1c3c2fce829 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/appsync/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/appsync/api.go @@ -3990,7 +3990,29 @@ type ApiCache struct { // Valid values are between 1 and 3600 seconds. Ttl *int64 `locationName:"ttl" type:"long"` - // The cache instance type. + // The cache instance type. Valid values are + // + // * SMALL + // + // * MEDIUM + // + // * LARGE + // + // * XLARGE + // + // * LARGE_2X + // + // * LARGE_4X + // + // * LARGE_8X (not available in all regions) + // + // * LARGE_12X + // + // Historically, instance types were identified by an EC2-style value. As of + // July 2020, this is deprecated, and the generic identifiers above should be + // used. + // + // The following legacy instance types are avaible, but their use is discouraged: // // * T2_SMALL: A t2.small instance type. // @@ -4449,8 +4471,8 @@ type CachingConfig struct { // The caching keys for a resolver that has caching enabled. // - // Valid values are entries from the $context.identity and $context.arguments - // maps. + // Valid values are entries from the $context.arguments, $context.source, and + // $context.identity maps. CachingKeys []*string `locationName:"cachingKeys" type:"list"` // The TTL in seconds for a resolver that has caching enabled. @@ -4633,7 +4655,29 @@ type CreateApiCacheInput struct { // Ttl is a required field Ttl *int64 `locationName:"ttl" type:"long" required:"true"` - // The cache instance type. + // The cache instance type. Valid values are + // + // * SMALL + // + // * MEDIUM + // + // * LARGE + // + // * XLARGE + // + // * LARGE_2X + // + // * LARGE_4X + // + // * LARGE_8X (not available in all regions) + // + // * LARGE_12X + // + // Historically, instance types were identified by an EC2-style value. As of + // July 2020, this is deprecated, and the generic identifiers above should be + // used. + // + // The following legacy instance types are avaible, but their use is discouraged: // // * T2_SMALL: A t2.small instance type. // @@ -5041,9 +5085,7 @@ type CreateFunctionInput struct { // The Function request mapping template. Functions support only the 2018-05-29 // version of the request mapping template. - // - // RequestMappingTemplate is a required field - RequestMappingTemplate *string `locationName:"requestMappingTemplate" min:"1" type:"string" required:"true"` + RequestMappingTemplate *string `locationName:"requestMappingTemplate" min:"1" type:"string"` // The Function response mapping template. ResponseMappingTemplate *string `locationName:"responseMappingTemplate" min:"1" type:"string"` @@ -5083,9 +5125,6 @@ func (s *CreateFunctionInput) Validate() error { if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } - if s.RequestMappingTemplate == nil { - invalidParams.Add(request.NewErrParamRequired("RequestMappingTemplate")) - } if s.RequestMappingTemplate != nil && len(*s.RequestMappingTemplate) < 1 { invalidParams.Add(request.NewErrParamMinLen("RequestMappingTemplate", 1)) } @@ -5360,8 +5399,10 @@ type CreateResolverInput struct { // into a format that a data source can understand. Mapping templates are written // in Apache Velocity Template Language (VTL). // - // RequestMappingTemplate is a required field - RequestMappingTemplate *string `locationName:"requestMappingTemplate" min:"1" type:"string" required:"true"` + // VTL request mapping templates are optional when using a Lambda data source. + // For all other data sources, VTL request and response mapping templates are + // required. + RequestMappingTemplate *string `locationName:"requestMappingTemplate" min:"1" type:"string"` // The mapping template to be used for responses from the data source. ResponseMappingTemplate *string `locationName:"responseMappingTemplate" min:"1" type:"string"` @@ -5403,9 +5444,6 @@ func (s *CreateResolverInput) Validate() error { if s.FieldName != nil && len(*s.FieldName) < 1 { invalidParams.Add(request.NewErrParamMinLen("FieldName", 1)) } - if s.RequestMappingTemplate == nil { - invalidParams.Add(request.NewErrParamRequired("RequestMappingTemplate")) - } if s.RequestMappingTemplate != nil && len(*s.RequestMappingTemplate) < 1 { invalidParams.Add(request.NewErrParamMinLen("RequestMappingTemplate", 1)) } @@ -8585,7 +8623,7 @@ type RdsHttpEndpointConfig struct { // Logical database name. DatabaseName *string `locationName:"databaseName" type:"string"` - // Amazon RDS cluster identifier. + // Amazon RDS cluster ARN. DbClusterIdentifier *string `locationName:"dbClusterIdentifier" type:"string"` // Logical schema name. @@ -9204,7 +9242,29 @@ type UpdateApiCacheInput struct { // Ttl is a required field Ttl *int64 `locationName:"ttl" type:"long" required:"true"` - // The cache instance type. + // The cache instance type. Valid values are + // + // * SMALL + // + // * MEDIUM + // + // * LARGE + // + // * XLARGE + // + // * LARGE_2X + // + // * LARGE_4X + // + // * LARGE_8X (not available in all regions) + // + // * LARGE_12X + // + // Historically, instance types were identified by an EC2-style value. As of + // July 2020, this is deprecated, and the generic identifiers above should be + // used. + // + // The following legacy instance types are avaible, but their use is discouraged: // // * T2_SMALL: A t2.small instance type. // @@ -9619,9 +9679,7 @@ type UpdateFunctionInput struct { // The Function request mapping template. Functions support only the 2018-05-29 // version of the request mapping template. - // - // RequestMappingTemplate is a required field - RequestMappingTemplate *string `locationName:"requestMappingTemplate" min:"1" type:"string" required:"true"` + RequestMappingTemplate *string `locationName:"requestMappingTemplate" min:"1" type:"string"` // The Function request mapping template. ResponseMappingTemplate *string `locationName:"responseMappingTemplate" min:"1" type:"string"` @@ -9667,9 +9725,6 @@ func (s *UpdateFunctionInput) Validate() error { if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } - if s.RequestMappingTemplate == nil { - invalidParams.Add(request.NewErrParamRequired("RequestMappingTemplate")) - } if s.RequestMappingTemplate != nil && len(*s.RequestMappingTemplate) < 1 { invalidParams.Add(request.NewErrParamMinLen("RequestMappingTemplate", 1)) } @@ -9946,8 +10001,14 @@ type UpdateResolverInput struct { // The new request mapping template. // - // RequestMappingTemplate is a required field - RequestMappingTemplate *string `locationName:"requestMappingTemplate" min:"1" type:"string" required:"true"` + // A resolver uses a request mapping template to convert a GraphQL expression + // into a format that a data source can understand. Mapping templates are written + // in Apache Velocity Template Language (VTL). + // + // VTL request mapping templates are optional when using a Lambda data source. + // For all other data sources, VTL request and response mapping templates are + // required. + RequestMappingTemplate *string `locationName:"requestMappingTemplate" min:"1" type:"string"` // The new response mapping template. ResponseMappingTemplate *string `locationName:"responseMappingTemplate" min:"1" type:"string"` @@ -9989,9 +10050,6 @@ func (s *UpdateResolverInput) Validate() error { if s.FieldName != nil && len(*s.FieldName) < 1 { invalidParams.Add(request.NewErrParamMinLen("FieldName", 1)) } - if s.RequestMappingTemplate == nil { - invalidParams.Add(request.NewErrParamRequired("RequestMappingTemplate")) - } if s.RequestMappingTemplate != nil && len(*s.RequestMappingTemplate) < 1 { invalidParams.Add(request.NewErrParamMinLen("RequestMappingTemplate", 1)) } @@ -10294,6 +10352,17 @@ const ( ApiCacheStatusFailed = "FAILED" ) +// ApiCacheStatus_Values returns all elements of the ApiCacheStatus enum +func ApiCacheStatus_Values() []string { + return []string{ + ApiCacheStatusAvailable, + ApiCacheStatusCreating, + ApiCacheStatusDeleting, + ApiCacheStatusModifying, + ApiCacheStatusFailed, + } +} + const ( // ApiCacheTypeT2Small is a ApiCacheType enum value ApiCacheTypeT2Small = "T2_SMALL" @@ -10315,8 +10384,53 @@ const ( // ApiCacheTypeR48xlarge is a ApiCacheType enum value ApiCacheTypeR48xlarge = "R4_8XLARGE" + + // ApiCacheTypeSmall is a ApiCacheType enum value + ApiCacheTypeSmall = "SMALL" + + // ApiCacheTypeMedium is a ApiCacheType enum value + ApiCacheTypeMedium = "MEDIUM" + + // ApiCacheTypeLarge is a ApiCacheType enum value + ApiCacheTypeLarge = "LARGE" + + // ApiCacheTypeXlarge is a ApiCacheType enum value + ApiCacheTypeXlarge = "XLARGE" + + // ApiCacheTypeLarge2x is a ApiCacheType enum value + ApiCacheTypeLarge2x = "LARGE_2X" + + // ApiCacheTypeLarge4x is a ApiCacheType enum value + ApiCacheTypeLarge4x = "LARGE_4X" + + // ApiCacheTypeLarge8x is a ApiCacheType enum value + ApiCacheTypeLarge8x = "LARGE_8X" + + // ApiCacheTypeLarge12x is a ApiCacheType enum value + ApiCacheTypeLarge12x = "LARGE_12X" ) +// ApiCacheType_Values returns all elements of the ApiCacheType enum +func ApiCacheType_Values() []string { + return []string{ + ApiCacheTypeT2Small, + ApiCacheTypeT2Medium, + ApiCacheTypeR4Large, + ApiCacheTypeR4Xlarge, + ApiCacheTypeR42xlarge, + ApiCacheTypeR44xlarge, + ApiCacheTypeR48xlarge, + ApiCacheTypeSmall, + ApiCacheTypeMedium, + ApiCacheTypeLarge, + ApiCacheTypeXlarge, + ApiCacheTypeLarge2x, + ApiCacheTypeLarge4x, + ApiCacheTypeLarge8x, + ApiCacheTypeLarge12x, + } +} + const ( // ApiCachingBehaviorFullRequestCaching is a ApiCachingBehavior enum value ApiCachingBehaviorFullRequestCaching = "FULL_REQUEST_CACHING" @@ -10325,6 +10439,14 @@ const ( ApiCachingBehaviorPerResolverCaching = "PER_RESOLVER_CACHING" ) +// ApiCachingBehavior_Values returns all elements of the ApiCachingBehavior enum +func ApiCachingBehavior_Values() []string { + return []string{ + ApiCachingBehaviorFullRequestCaching, + ApiCachingBehaviorPerResolverCaching, + } +} + const ( // AuthenticationTypeApiKey is a AuthenticationType enum value AuthenticationTypeApiKey = "API_KEY" @@ -10339,11 +10461,28 @@ const ( AuthenticationTypeOpenidConnect = "OPENID_CONNECT" ) +// AuthenticationType_Values returns all elements of the AuthenticationType enum +func AuthenticationType_Values() []string { + return []string{ + AuthenticationTypeApiKey, + AuthenticationTypeAwsIam, + AuthenticationTypeAmazonCognitoUserPools, + AuthenticationTypeOpenidConnect, + } +} + const ( // AuthorizationTypeAwsIam is a AuthorizationType enum value AuthorizationTypeAwsIam = "AWS_IAM" ) +// AuthorizationType_Values returns all elements of the AuthorizationType enum +func AuthorizationType_Values() []string { + return []string{ + AuthorizationTypeAwsIam, + } +} + const ( // ConflictDetectionTypeVersion is a ConflictDetectionType enum value ConflictDetectionTypeVersion = "VERSION" @@ -10352,6 +10491,14 @@ const ( ConflictDetectionTypeNone = "NONE" ) +// ConflictDetectionType_Values returns all elements of the ConflictDetectionType enum +func ConflictDetectionType_Values() []string { + return []string{ + ConflictDetectionTypeVersion, + ConflictDetectionTypeNone, + } +} + const ( // ConflictHandlerTypeOptimisticConcurrency is a ConflictHandlerType enum value ConflictHandlerTypeOptimisticConcurrency = "OPTIMISTIC_CONCURRENCY" @@ -10366,6 +10513,16 @@ const ( ConflictHandlerTypeNone = "NONE" ) +// ConflictHandlerType_Values returns all elements of the ConflictHandlerType enum +func ConflictHandlerType_Values() []string { + return []string{ + ConflictHandlerTypeOptimisticConcurrency, + ConflictHandlerTypeLambda, + ConflictHandlerTypeAutomerge, + ConflictHandlerTypeNone, + } +} + const ( // DataSourceTypeAwsLambda is a DataSourceType enum value DataSourceTypeAwsLambda = "AWS_LAMBDA" @@ -10386,6 +10543,18 @@ const ( DataSourceTypeRelationalDatabase = "RELATIONAL_DATABASE" ) +// DataSourceType_Values returns all elements of the DataSourceType enum +func DataSourceType_Values() []string { + return []string{ + DataSourceTypeAwsLambda, + DataSourceTypeAmazonDynamodb, + DataSourceTypeAmazonElasticsearch, + DataSourceTypeNone, + DataSourceTypeHttp, + DataSourceTypeRelationalDatabase, + } +} + const ( // DefaultActionAllow is a DefaultAction enum value DefaultActionAllow = "ALLOW" @@ -10394,6 +10563,14 @@ const ( DefaultActionDeny = "DENY" ) +// DefaultAction_Values returns all elements of the DefaultAction enum +func DefaultAction_Values() []string { + return []string{ + DefaultActionAllow, + DefaultActionDeny, + } +} + const ( // FieldLogLevelNone is a FieldLogLevel enum value FieldLogLevelNone = "NONE" @@ -10405,6 +10582,15 @@ const ( FieldLogLevelAll = "ALL" ) +// FieldLogLevel_Values returns all elements of the FieldLogLevel enum +func FieldLogLevel_Values() []string { + return []string{ + FieldLogLevelNone, + FieldLogLevelError, + FieldLogLevelAll, + } +} + const ( // OutputTypeSdl is a OutputType enum value OutputTypeSdl = "SDL" @@ -10413,11 +10599,26 @@ const ( OutputTypeJson = "JSON" ) +// OutputType_Values returns all elements of the OutputType enum +func OutputType_Values() []string { + return []string{ + OutputTypeSdl, + OutputTypeJson, + } +} + const ( // RelationalDatabaseSourceTypeRdsHttpEndpoint is a RelationalDatabaseSourceType enum value RelationalDatabaseSourceTypeRdsHttpEndpoint = "RDS_HTTP_ENDPOINT" ) +// RelationalDatabaseSourceType_Values returns all elements of the RelationalDatabaseSourceType enum +func RelationalDatabaseSourceType_Values() []string { + return []string{ + RelationalDatabaseSourceTypeRdsHttpEndpoint, + } +} + const ( // ResolverKindUnit is a ResolverKind enum value ResolverKindUnit = "UNIT" @@ -10426,6 +10627,14 @@ const ( ResolverKindPipeline = "PIPELINE" ) +// ResolverKind_Values returns all elements of the ResolverKind enum +func ResolverKind_Values() []string { + return []string{ + ResolverKindUnit, + ResolverKindPipeline, + } +} + const ( // SchemaStatusProcessing is a SchemaStatus enum value SchemaStatusProcessing = "PROCESSING" @@ -10446,6 +10655,18 @@ const ( SchemaStatusNotApplicable = "NOT_APPLICABLE" ) +// SchemaStatus_Values returns all elements of the SchemaStatus enum +func SchemaStatus_Values() []string { + return []string{ + SchemaStatusProcessing, + SchemaStatusActive, + SchemaStatusDeleting, + SchemaStatusFailed, + SchemaStatusSuccess, + SchemaStatusNotApplicable, + } +} + const ( // TypeDefinitionFormatSdl is a TypeDefinitionFormat enum value TypeDefinitionFormatSdl = "SDL" @@ -10453,3 +10674,11 @@ const ( // TypeDefinitionFormatJson is a TypeDefinitionFormat enum value TypeDefinitionFormatJson = "JSON" ) + +// TypeDefinitionFormat_Values returns all elements of the TypeDefinitionFormat enum +func TypeDefinitionFormat_Values() []string { + return []string{ + TypeDefinitionFormatSdl, + TypeDefinitionFormatJson, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/athena/api.go b/vendor/github.com/aws/aws-sdk-go/service/athena/api.go index ca2043b0144..7e5303a78b0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/athena/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/athena/api.go @@ -194,6 +194,92 @@ func (c *Athena) BatchGetQueryExecutionWithContext(ctx aws.Context, input *Batch return out, req.Send() } +const opCreateDataCatalog = "CreateDataCatalog" + +// CreateDataCatalogRequest generates a "aws/request.Request" representing the +// client's request for the CreateDataCatalog operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateDataCatalog for more information on using the CreateDataCatalog +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateDataCatalogRequest method. +// req, resp := client.CreateDataCatalogRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/CreateDataCatalog +func (c *Athena) CreateDataCatalogRequest(input *CreateDataCatalogInput) (req *request.Request, output *CreateDataCatalogOutput) { + op := &request.Operation{ + Name: opCreateDataCatalog, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateDataCatalogInput{} + } + + output = &CreateDataCatalogOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// CreateDataCatalog API operation for Amazon Athena. +// +// Creates (registers) a data catalog with the specified name and properties. +// Catalogs created are visible to all users of the same 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. +// +// See the AWS API reference guide for Amazon Athena's +// API operation CreateDataCatalog for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// Indicates a platform issue, which may be due to a transient condition or +// outage. +// +// * InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter may be missing or out of range. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/CreateDataCatalog +func (c *Athena) CreateDataCatalog(input *CreateDataCatalogInput) (*CreateDataCatalogOutput, error) { + req, out := c.CreateDataCatalogRequest(input) + return out, req.Send() +} + +// CreateDataCatalogWithContext is the same as CreateDataCatalog with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDataCatalog for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Athena) CreateDataCatalogWithContext(ctx aws.Context, input *CreateDataCatalogInput, opts ...request.Option) (*CreateDataCatalogOutput, error) { + req, out := c.CreateDataCatalogRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateNamedQuery = "CreateNamedQuery" // CreateNamedQueryRequest generates a "aws/request.Request" representing the @@ -368,6 +454,91 @@ func (c *Athena) CreateWorkGroupWithContext(ctx aws.Context, input *CreateWorkGr return out, req.Send() } +const opDeleteDataCatalog = "DeleteDataCatalog" + +// DeleteDataCatalogRequest generates a "aws/request.Request" representing the +// client's request for the DeleteDataCatalog operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteDataCatalog for more information on using the DeleteDataCatalog +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteDataCatalogRequest method. +// req, resp := client.DeleteDataCatalogRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/DeleteDataCatalog +func (c *Athena) DeleteDataCatalogRequest(input *DeleteDataCatalogInput) (req *request.Request, output *DeleteDataCatalogOutput) { + op := &request.Operation{ + Name: opDeleteDataCatalog, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteDataCatalogInput{} + } + + output = &DeleteDataCatalogOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteDataCatalog API operation for Amazon Athena. +// +// Deletes a data catalog. +// +// Returns awserr.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 Athena's +// API operation DeleteDataCatalog for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// Indicates a platform issue, which may be due to a transient condition or +// outage. +// +// * InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter may be missing or out of range. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/DeleteDataCatalog +func (c *Athena) DeleteDataCatalog(input *DeleteDataCatalogInput) (*DeleteDataCatalogOutput, error) { + req, out := c.DeleteDataCatalogRequest(input) + return out, req.Send() +} + +// DeleteDataCatalogWithContext is the same as DeleteDataCatalog with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDataCatalog for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Athena) DeleteDataCatalogWithContext(ctx aws.Context, input *DeleteDataCatalogInput, opts ...request.Option) (*DeleteDataCatalogOutput, error) { + req, out := c.DeleteDataCatalogRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteNamedQuery = "DeleteNamedQuery" // DeleteNamedQueryRequest generates a "aws/request.Request" representing the @@ -544,6 +715,181 @@ func (c *Athena) DeleteWorkGroupWithContext(ctx aws.Context, input *DeleteWorkGr return out, req.Send() } +const opGetDataCatalog = "GetDataCatalog" + +// GetDataCatalogRequest generates a "aws/request.Request" representing the +// client's request for the GetDataCatalog operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetDataCatalog for more information on using the GetDataCatalog +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetDataCatalogRequest method. +// req, resp := client.GetDataCatalogRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/GetDataCatalog +func (c *Athena) GetDataCatalogRequest(input *GetDataCatalogInput) (req *request.Request, output *GetDataCatalogOutput) { + op := &request.Operation{ + Name: opGetDataCatalog, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetDataCatalogInput{} + } + + output = &GetDataCatalogOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetDataCatalog API operation for Amazon Athena. +// +// Returns the specified data catalog. +// +// Returns awserr.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 Athena's +// API operation GetDataCatalog for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// Indicates a platform issue, which may be due to a transient condition or +// outage. +// +// * InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter may be missing or out of range. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/GetDataCatalog +func (c *Athena) GetDataCatalog(input *GetDataCatalogInput) (*GetDataCatalogOutput, error) { + req, out := c.GetDataCatalogRequest(input) + return out, req.Send() +} + +// GetDataCatalogWithContext is the same as GetDataCatalog with the addition of +// the ability to pass a context and additional request options. +// +// See GetDataCatalog for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Athena) GetDataCatalogWithContext(ctx aws.Context, input *GetDataCatalogInput, opts ...request.Option) (*GetDataCatalogOutput, error) { + req, out := c.GetDataCatalogRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetDatabase = "GetDatabase" + +// GetDatabaseRequest generates a "aws/request.Request" representing the +// client's request for the GetDatabase operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetDatabase for more information on using the GetDatabase +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetDatabaseRequest method. +// req, resp := client.GetDatabaseRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/GetDatabase +func (c *Athena) GetDatabaseRequest(input *GetDatabaseInput) (req *request.Request, output *GetDatabaseOutput) { + op := &request.Operation{ + Name: opGetDatabase, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetDatabaseInput{} + } + + output = &GetDatabaseOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetDatabase API operation for Amazon Athena. +// +// Returns a database object for the specfied database and data catalog. +// +// Returns awserr.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 Athena's +// API operation GetDatabase for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// Indicates a platform issue, which may be due to a transient condition or +// outage. +// +// * InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter may be missing or out of range. +// +// * MetadataException +// An exception that Athena received when it called a custom metastore. Occurs +// if the error is not caused by user input (InvalidRequestException) or from +// the Athena platform (InternalServerException). For example, if a user-created +// Lambda function is missing permissions, the Lambda 4XX exception is returned +// in a MetadataException. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/GetDatabase +func (c *Athena) GetDatabase(input *GetDatabaseInput) (*GetDatabaseOutput, error) { + req, out := c.GetDatabaseRequest(input) + return out, req.Send() +} + +// GetDatabaseWithContext is the same as GetDatabase with the addition of +// the ability to pass a context and additional request options. +// +// See GetDatabase for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Athena) GetDatabaseWithContext(ctx aws.Context, input *GetDatabaseInput, opts ...request.Option) (*GetDatabaseOutput, error) { + req, out := c.GetDatabaseRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetNamedQuery = "GetNamedQuery" // GetNamedQueryRequest generates a "aws/request.Request" representing the @@ -871,7 +1217,98 @@ func (c *Athena) GetQueryResultsPagesWithContext(ctx aws.Context, input *GetQuer return p.Err() } -const opGetWorkGroup = "GetWorkGroup" +const opGetTableMetadata = "GetTableMetadata" + +// GetTableMetadataRequest generates a "aws/request.Request" representing the +// client's request for the GetTableMetadata operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetTableMetadata for more information on using the GetTableMetadata +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetTableMetadataRequest method. +// req, resp := client.GetTableMetadataRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/GetTableMetadata +func (c *Athena) GetTableMetadataRequest(input *GetTableMetadataInput) (req *request.Request, output *GetTableMetadataOutput) { + op := &request.Operation{ + Name: opGetTableMetadata, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetTableMetadataInput{} + } + + output = &GetTableMetadataOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetTableMetadata API operation for Amazon Athena. +// +// Returns table metadata for the specified catalog, database, and table. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Athena's +// API operation GetTableMetadata for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// Indicates a platform issue, which may be due to a transient condition or +// outage. +// +// * InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter may be missing or out of range. +// +// * MetadataException +// An exception that Athena received when it called a custom metastore. Occurs +// if the error is not caused by user input (InvalidRequestException) or from +// the Athena platform (InternalServerException). For example, if a user-created +// Lambda function is missing permissions, the Lambda 4XX exception is returned +// in a MetadataException. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/GetTableMetadata +func (c *Athena) GetTableMetadata(input *GetTableMetadataInput) (*GetTableMetadataOutput, error) { + req, out := c.GetTableMetadataRequest(input) + return out, req.Send() +} + +// GetTableMetadataWithContext is the same as GetTableMetadata with the addition of +// the ability to pass a context and additional request options. +// +// See GetTableMetadata for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Athena) GetTableMetadataWithContext(ctx aws.Context, input *GetTableMetadataInput, opts ...request.Option) (*GetTableMetadataOutput, error) { + req, out := c.GetTableMetadataRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetWorkGroup = "GetWorkGroup" // GetWorkGroupRequest generates a "aws/request.Request" representing the // client's request for the GetWorkGroup operation. The "output" return @@ -955,35 +1392,35 @@ func (c *Athena) GetWorkGroupWithContext(ctx aws.Context, input *GetWorkGroupInp return out, req.Send() } -const opListNamedQueries = "ListNamedQueries" +const opListDataCatalogs = "ListDataCatalogs" -// ListNamedQueriesRequest generates a "aws/request.Request" representing the -// client's request for the ListNamedQueries operation. The "output" return +// ListDataCatalogsRequest generates a "aws/request.Request" representing the +// client's request for the ListDataCatalogs operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListNamedQueries for more information on using the ListNamedQueries +// See ListDataCatalogs for more information on using the ListDataCatalogs // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListNamedQueriesRequest method. -// req, resp := client.ListNamedQueriesRequest(params) +// // Example sending a request using the ListDataCatalogsRequest method. +// req, resp := client.ListDataCatalogsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListNamedQueries -func (c *Athena) ListNamedQueriesRequest(input *ListNamedQueriesInput) (req *request.Request, output *ListNamedQueriesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListDataCatalogs +func (c *Athena) ListDataCatalogsRequest(input *ListDataCatalogsInput) (req *request.Request, output *ListDataCatalogsOutput) { op := &request.Operation{ - Name: opListNamedQueries, + Name: opListDataCatalogs, HTTPMethod: "POST", HTTPPath: "/", Paginator: &request.Paginator{ @@ -995,30 +1432,24 @@ func (c *Athena) ListNamedQueriesRequest(input *ListNamedQueriesInput) (req *req } if input == nil { - input = &ListNamedQueriesInput{} + input = &ListDataCatalogsInput{} } - output = &ListNamedQueriesOutput{} + output = &ListDataCatalogsOutput{} req = c.newRequest(op, input, output) return } -// ListNamedQueries API operation for Amazon Athena. -// -// Provides a list of available query IDs only for queries saved in the specified -// workgroup. Requires that you have access to the workgroup. If a workgroup -// is not specified, lists the saved queries for the primary workgroup. +// ListDataCatalogs API operation for Amazon Athena. // -// For code samples using the AWS SDK for Java, see Examples and Code Samples -// (http://docs.aws.amazon.com/athena/latest/ug/code-samples.html) in the Amazon -// Athena User Guide. +// Lists the data catalogs in 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. // // See the AWS API reference guide for Amazon Athena's -// API operation ListNamedQueries for usage and error information. +// API operation ListDataCatalogs for usage and error information. // // Returned Error Types: // * InternalServerException @@ -1029,65 +1460,65 @@ func (c *Athena) ListNamedQueriesRequest(input *ListNamedQueriesInput) (req *req // Indicates that something is wrong with the input to the request. For example, // a required parameter may be missing or out of range. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListNamedQueries -func (c *Athena) ListNamedQueries(input *ListNamedQueriesInput) (*ListNamedQueriesOutput, error) { - req, out := c.ListNamedQueriesRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListDataCatalogs +func (c *Athena) ListDataCatalogs(input *ListDataCatalogsInput) (*ListDataCatalogsOutput, error) { + req, out := c.ListDataCatalogsRequest(input) return out, req.Send() } -// ListNamedQueriesWithContext is the same as ListNamedQueries with the addition of +// ListDataCatalogsWithContext is the same as ListDataCatalogs with the addition of // the ability to pass a context and additional request options. // -// See ListNamedQueries for details on how to use this API operation. +// See ListDataCatalogs for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *Athena) ListNamedQueriesWithContext(ctx aws.Context, input *ListNamedQueriesInput, opts ...request.Option) (*ListNamedQueriesOutput, error) { - req, out := c.ListNamedQueriesRequest(input) +func (c *Athena) ListDataCatalogsWithContext(ctx aws.Context, input *ListDataCatalogsInput, opts ...request.Option) (*ListDataCatalogsOutput, error) { + req, out := c.ListDataCatalogsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListNamedQueriesPages iterates over the pages of a ListNamedQueries operation, +// ListDataCatalogsPages iterates over the pages of a ListDataCatalogs operation, // calling the "fn" function with the response data for each page. To stop // iterating, return false from the fn function. // -// See ListNamedQueries method for more information on how to use this operation. +// See ListDataCatalogs 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 ListNamedQueries operation. +// // Example iterating over at most 3 pages of a ListDataCatalogs operation. // pageNum := 0 -// err := client.ListNamedQueriesPages(params, -// func(page *athena.ListNamedQueriesOutput, lastPage bool) bool { +// err := client.ListDataCatalogsPages(params, +// func(page *athena.ListDataCatalogsOutput, lastPage bool) bool { // pageNum++ // fmt.Println(page) // return pageNum <= 3 // }) // -func (c *Athena) ListNamedQueriesPages(input *ListNamedQueriesInput, fn func(*ListNamedQueriesOutput, bool) bool) error { - return c.ListNamedQueriesPagesWithContext(aws.BackgroundContext(), input, fn) +func (c *Athena) ListDataCatalogsPages(input *ListDataCatalogsInput, fn func(*ListDataCatalogsOutput, bool) bool) error { + return c.ListDataCatalogsPagesWithContext(aws.BackgroundContext(), input, fn) } -// ListNamedQueriesPagesWithContext same as ListNamedQueriesPages except +// ListDataCatalogsPagesWithContext same as ListDataCatalogsPages except // it takes a Context and allows setting request options on the pages. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *Athena) ListNamedQueriesPagesWithContext(ctx aws.Context, input *ListNamedQueriesInput, fn func(*ListNamedQueriesOutput, bool) bool, opts ...request.Option) error { +func (c *Athena) ListDataCatalogsPagesWithContext(ctx aws.Context, input *ListDataCatalogsInput, fn func(*ListDataCatalogsOutput, bool) bool, opts ...request.Option) error { p := request.Pagination{ NewRequest: func() (*request.Request, error) { - var inCpy *ListNamedQueriesInput + var inCpy *ListDataCatalogsInput if input != nil { tmp := *input inCpy = &tmp } - req, _ := c.ListNamedQueriesRequest(inCpy) + req, _ := c.ListDataCatalogsRequest(inCpy) req.SetContext(ctx) req.ApplyOptions(opts...) return req, nil @@ -1095,7 +1526,7 @@ func (c *Athena) ListNamedQueriesPagesWithContext(ctx aws.Context, input *ListNa } for p.Next() { - if !fn(p.Page().(*ListNamedQueriesOutput), !p.HasNextPage()) { + if !fn(p.Page().(*ListDataCatalogsOutput), !p.HasNextPage()) { break } } @@ -1103,35 +1534,35 @@ func (c *Athena) ListNamedQueriesPagesWithContext(ctx aws.Context, input *ListNa return p.Err() } -const opListQueryExecutions = "ListQueryExecutions" +const opListDatabases = "ListDatabases" -// ListQueryExecutionsRequest generates a "aws/request.Request" representing the -// client's request for the ListQueryExecutions operation. The "output" return +// ListDatabasesRequest generates a "aws/request.Request" representing the +// client's request for the ListDatabases operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListQueryExecutions for more information on using the ListQueryExecutions +// See ListDatabases for more information on using the ListDatabases // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListQueryExecutionsRequest method. -// req, resp := client.ListQueryExecutionsRequest(params) +// // Example sending a request using the ListDatabasesRequest method. +// req, resp := client.ListDatabasesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListQueryExecutions -func (c *Athena) ListQueryExecutionsRequest(input *ListQueryExecutionsInput) (req *request.Request, output *ListQueryExecutionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListDatabases +func (c *Athena) ListDatabasesRequest(input *ListDatabasesInput) (req *request.Request, output *ListDatabasesOutput) { op := &request.Operation{ - Name: opListQueryExecutions, + Name: opListDatabases, HTTPMethod: "POST", HTTPPath: "/", Paginator: &request.Paginator{ @@ -1143,31 +1574,24 @@ func (c *Athena) ListQueryExecutionsRequest(input *ListQueryExecutionsInput) (re } if input == nil { - input = &ListQueryExecutionsInput{} + input = &ListDatabasesInput{} } - output = &ListQueryExecutionsOutput{} + output = &ListDatabasesOutput{} req = c.newRequest(op, input, output) return } -// ListQueryExecutions API operation for Amazon Athena. -// -// Provides a list of available query execution IDs for the queries in the specified -// workgroup. If a workgroup is not specified, returns a list of query execution -// IDs for the primary workgroup. Requires you to have access to the workgroup -// in which the queries ran. +// ListDatabases API operation for Amazon Athena. // -// For code samples using the AWS SDK for Java, see Examples and Code Samples -// (http://docs.aws.amazon.com/athena/latest/ug/code-samples.html) in the Amazon -// Athena User Guide. +// Lists the databases in the specified data catalog. // // Returns awserr.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 Athena's -// API operation ListQueryExecutions for usage and error information. +// API operation ListDatabases for usage and error information. // // Returned Error Types: // * InternalServerException @@ -1178,65 +1602,72 @@ func (c *Athena) ListQueryExecutionsRequest(input *ListQueryExecutionsInput) (re // Indicates that something is wrong with the input to the request. For example, // a required parameter may be missing or out of range. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListQueryExecutions -func (c *Athena) ListQueryExecutions(input *ListQueryExecutionsInput) (*ListQueryExecutionsOutput, error) { - req, out := c.ListQueryExecutionsRequest(input) +// * MetadataException +// An exception that Athena received when it called a custom metastore. Occurs +// if the error is not caused by user input (InvalidRequestException) or from +// the Athena platform (InternalServerException). For example, if a user-created +// Lambda function is missing permissions, the Lambda 4XX exception is returned +// in a MetadataException. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListDatabases +func (c *Athena) ListDatabases(input *ListDatabasesInput) (*ListDatabasesOutput, error) { + req, out := c.ListDatabasesRequest(input) return out, req.Send() } -// ListQueryExecutionsWithContext is the same as ListQueryExecutions with the addition of +// ListDatabasesWithContext is the same as ListDatabases with the addition of // the ability to pass a context and additional request options. // -// See ListQueryExecutions for details on how to use this API operation. +// See ListDatabases for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *Athena) ListQueryExecutionsWithContext(ctx aws.Context, input *ListQueryExecutionsInput, opts ...request.Option) (*ListQueryExecutionsOutput, error) { - req, out := c.ListQueryExecutionsRequest(input) +func (c *Athena) ListDatabasesWithContext(ctx aws.Context, input *ListDatabasesInput, opts ...request.Option) (*ListDatabasesOutput, error) { + req, out := c.ListDatabasesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListQueryExecutionsPages iterates over the pages of a ListQueryExecutions operation, +// ListDatabasesPages iterates over the pages of a ListDatabases operation, // calling the "fn" function with the response data for each page. To stop // iterating, return false from the fn function. // -// See ListQueryExecutions method for more information on how to use this operation. +// See ListDatabases 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 ListQueryExecutions operation. +// // Example iterating over at most 3 pages of a ListDatabases operation. // pageNum := 0 -// err := client.ListQueryExecutionsPages(params, -// func(page *athena.ListQueryExecutionsOutput, lastPage bool) bool { +// err := client.ListDatabasesPages(params, +// func(page *athena.ListDatabasesOutput, lastPage bool) bool { // pageNum++ // fmt.Println(page) // return pageNum <= 3 // }) // -func (c *Athena) ListQueryExecutionsPages(input *ListQueryExecutionsInput, fn func(*ListQueryExecutionsOutput, bool) bool) error { - return c.ListQueryExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +func (c *Athena) ListDatabasesPages(input *ListDatabasesInput, fn func(*ListDatabasesOutput, bool) bool) error { + return c.ListDatabasesPagesWithContext(aws.BackgroundContext(), input, fn) } -// ListQueryExecutionsPagesWithContext same as ListQueryExecutionsPages except +// ListDatabasesPagesWithContext same as ListDatabasesPages except // it takes a Context and allows setting request options on the pages. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *Athena) ListQueryExecutionsPagesWithContext(ctx aws.Context, input *ListQueryExecutionsInput, fn func(*ListQueryExecutionsOutput, bool) bool, opts ...request.Option) error { +func (c *Athena) ListDatabasesPagesWithContext(ctx aws.Context, input *ListDatabasesInput, fn func(*ListDatabasesOutput, bool) bool, opts ...request.Option) error { p := request.Pagination{ NewRequest: func() (*request.Request, error) { - var inCpy *ListQueryExecutionsInput + var inCpy *ListDatabasesInput if input != nil { tmp := *input inCpy = &tmp } - req, _ := c.ListQueryExecutionsRequest(inCpy) + req, _ := c.ListDatabasesRequest(inCpy) req.SetContext(ctx) req.ApplyOptions(opts...) return req, nil @@ -1244,7 +1675,7 @@ func (c *Athena) ListQueryExecutionsPagesWithContext(ctx aws.Context, input *Lis } for p.Next() { - if !fn(p.Page().(*ListQueryExecutionsOutput), !p.HasNextPage()) { + if !fn(p.Page().(*ListDatabasesOutput), !p.HasNextPage()) { break } } @@ -1252,58 +1683,70 @@ func (c *Athena) ListQueryExecutionsPagesWithContext(ctx aws.Context, input *Lis return p.Err() } -const opListTagsForResource = "ListTagsForResource" +const opListNamedQueries = "ListNamedQueries" -// ListTagsForResourceRequest generates a "aws/request.Request" representing the -// client's request for the ListTagsForResource operation. The "output" return +// ListNamedQueriesRequest generates a "aws/request.Request" representing the +// client's request for the ListNamedQueries operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListTagsForResource for more information on using the ListTagsForResource +// See ListNamedQueries for more information on using the ListNamedQueries // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListTagsForResourceRequest method. -// req, resp := client.ListTagsForResourceRequest(params) +// // Example sending a request using the ListNamedQueriesRequest method. +// req, resp := client.ListNamedQueriesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListTagsForResource -func (c *Athena) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListNamedQueries +func (c *Athena) ListNamedQueriesRequest(input *ListNamedQueriesInput) (req *request.Request, output *ListNamedQueriesOutput) { op := &request.Operation{ - Name: opListTagsForResource, + Name: opListNamedQueries, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { - input = &ListTagsForResourceInput{} + input = &ListNamedQueriesInput{} } - output = &ListTagsForResourceOutput{} + output = &ListNamedQueriesOutput{} req = c.newRequest(op, input, output) return } -// ListTagsForResource API operation for Amazon Athena. +// ListNamedQueries API operation for Amazon Athena. +// +// Provides a list of available query IDs only for queries saved in the specified +// workgroup. Requires that you have access to the specified workgroup. If a +// workgroup is not specified, lists the saved queries for the primary workgroup. // -// Lists the tags associated with this workgroup. +// For code samples using the AWS SDK for Java, see Examples and Code Samples +// (http://docs.aws.amazon.com/athena/latest/ug/code-samples.html) in the Amazon +// Athena 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 Athena's -// API operation ListTagsForResource for usage and error information. +// API operation ListNamedQueries for usage and error information. // // Returned Error Types: // * InternalServerException @@ -1314,42 +1757,534 @@ func (c *Athena) ListTagsForResourceRequest(input *ListTagsForResourceInput) (re // Indicates that something is wrong with the input to the request. For example, // a required parameter may be missing or out of range. // -// * ResourceNotFoundException -// A resource, such as a workgroup, was not found. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListTagsForResource -func (c *Athena) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { - req, out := c.ListTagsForResourceRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListNamedQueries +func (c *Athena) ListNamedQueries(input *ListNamedQueriesInput) (*ListNamedQueriesOutput, error) { + req, out := c.ListNamedQueriesRequest(input) return out, req.Send() } -// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of +// ListNamedQueriesWithContext is the same as ListNamedQueries 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. +// See ListNamedQueries for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *Athena) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { - req, out := c.ListTagsForResourceRequest(input) +func (c *Athena) ListNamedQueriesWithContext(ctx aws.Context, input *ListNamedQueriesInput, opts ...request.Option) (*ListNamedQueriesOutput, error) { + req, out := c.ListNamedQueriesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opListWorkGroups = "ListWorkGroups" +// ListNamedQueriesPages iterates over the pages of a ListNamedQueries operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListNamedQueries 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 ListNamedQueries operation. +// pageNum := 0 +// err := client.ListNamedQueriesPages(params, +// func(page *athena.ListNamedQueriesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Athena) ListNamedQueriesPages(input *ListNamedQueriesInput, fn func(*ListNamedQueriesOutput, bool) bool) error { + return c.ListNamedQueriesPagesWithContext(aws.BackgroundContext(), input, fn) +} -// ListWorkGroupsRequest generates a "aws/request.Request" representing the -// client's request for the ListWorkGroups operation. The "output" return +// ListNamedQueriesPagesWithContext same as ListNamedQueriesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Athena) ListNamedQueriesPagesWithContext(ctx aws.Context, input *ListNamedQueriesInput, fn func(*ListNamedQueriesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListNamedQueriesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListNamedQueriesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListNamedQueriesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListQueryExecutions = "ListQueryExecutions" + +// ListQueryExecutionsRequest generates a "aws/request.Request" representing the +// client's request for the ListQueryExecutions operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListWorkGroups for more information on using the ListWorkGroups +// See ListQueryExecutions for more information on using the ListQueryExecutions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListQueryExecutionsRequest method. +// req, resp := client.ListQueryExecutionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListQueryExecutions +func (c *Athena) ListQueryExecutionsRequest(input *ListQueryExecutionsInput) (req *request.Request, output *ListQueryExecutionsOutput) { + op := &request.Operation{ + Name: opListQueryExecutions, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListQueryExecutionsInput{} + } + + output = &ListQueryExecutionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListQueryExecutions API operation for Amazon Athena. +// +// Provides a list of available query execution IDs for the queries in the specified +// workgroup. If a workgroup is not specified, returns a list of query execution +// IDs for the primary workgroup. Requires you to have access to the workgroup +// in which the queries ran. +// +// For code samples using the AWS SDK for Java, see Examples and Code Samples +// (http://docs.aws.amazon.com/athena/latest/ug/code-samples.html) in the Amazon +// Athena 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 Athena's +// API operation ListQueryExecutions for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// Indicates a platform issue, which may be due to a transient condition or +// outage. +// +// * InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter may be missing or out of range. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListQueryExecutions +func (c *Athena) ListQueryExecutions(input *ListQueryExecutionsInput) (*ListQueryExecutionsOutput, error) { + req, out := c.ListQueryExecutionsRequest(input) + return out, req.Send() +} + +// ListQueryExecutionsWithContext is the same as ListQueryExecutions with the addition of +// the ability to pass a context and additional request options. +// +// See ListQueryExecutions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Athena) ListQueryExecutionsWithContext(ctx aws.Context, input *ListQueryExecutionsInput, opts ...request.Option) (*ListQueryExecutionsOutput, error) { + req, out := c.ListQueryExecutionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListQueryExecutionsPages iterates over the pages of a ListQueryExecutions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListQueryExecutions 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 ListQueryExecutions operation. +// pageNum := 0 +// err := client.ListQueryExecutionsPages(params, +// func(page *athena.ListQueryExecutionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Athena) ListQueryExecutionsPages(input *ListQueryExecutionsInput, fn func(*ListQueryExecutionsOutput, bool) bool) error { + return c.ListQueryExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListQueryExecutionsPagesWithContext same as ListQueryExecutionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Athena) ListQueryExecutionsPagesWithContext(ctx aws.Context, input *ListQueryExecutionsInput, fn func(*ListQueryExecutionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListQueryExecutionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListQueryExecutionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListQueryExecutionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListTableMetadata = "ListTableMetadata" + +// ListTableMetadataRequest generates a "aws/request.Request" representing the +// client's request for the ListTableMetadata operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListTableMetadata for more information on using the ListTableMetadata +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListTableMetadataRequest method. +// req, resp := client.ListTableMetadataRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListTableMetadata +func (c *Athena) ListTableMetadataRequest(input *ListTableMetadataInput) (req *request.Request, output *ListTableMetadataOutput) { + op := &request.Operation{ + Name: opListTableMetadata, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListTableMetadataInput{} + } + + output = &ListTableMetadataOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListTableMetadata API operation for Amazon Athena. +// +// Lists the metadata for the tables in the specified data catalog database. +// +// Returns awserr.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 Athena's +// API operation ListTableMetadata for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// Indicates a platform issue, which may be due to a transient condition or +// outage. +// +// * InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter may be missing or out of range. +// +// * MetadataException +// An exception that Athena received when it called a custom metastore. Occurs +// if the error is not caused by user input (InvalidRequestException) or from +// the Athena platform (InternalServerException). For example, if a user-created +// Lambda function is missing permissions, the Lambda 4XX exception is returned +// in a MetadataException. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListTableMetadata +func (c *Athena) ListTableMetadata(input *ListTableMetadataInput) (*ListTableMetadataOutput, error) { + req, out := c.ListTableMetadataRequest(input) + return out, req.Send() +} + +// ListTableMetadataWithContext is the same as ListTableMetadata with the addition of +// the ability to pass a context and additional request options. +// +// See ListTableMetadata for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Athena) ListTableMetadataWithContext(ctx aws.Context, input *ListTableMetadataInput, opts ...request.Option) (*ListTableMetadataOutput, error) { + req, out := c.ListTableMetadataRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListTableMetadataPages iterates over the pages of a ListTableMetadata operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListTableMetadata 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 ListTableMetadata operation. +// pageNum := 0 +// err := client.ListTableMetadataPages(params, +// func(page *athena.ListTableMetadataOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Athena) ListTableMetadataPages(input *ListTableMetadataInput, fn func(*ListTableMetadataOutput, bool) bool) error { + return c.ListTableMetadataPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTableMetadataPagesWithContext same as ListTableMetadataPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Athena) ListTableMetadataPagesWithContext(ctx aws.Context, input *ListTableMetadataInput, fn func(*ListTableMetadataOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTableMetadataInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTableMetadataRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListTableMetadataOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListTagsForResource = "ListTagsForResource" + +// ListTagsForResourceRequest generates a "aws/request.Request" representing the +// client's request for the ListTagsForResource operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListTagsForResource for more information on using the ListTagsForResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListTagsForResourceRequest method. +// req, resp := client.ListTagsForResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListTagsForResource +func (c *Athena) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { + op := &request.Operation{ + Name: opListTagsForResource, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListTagsForResourceInput{} + } + + output = &ListTagsForResourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListTagsForResource API operation for Amazon Athena. +// +// Lists the tags associated with an Athena workgroup or data catalog 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 Amazon Athena's +// API operation ListTagsForResource for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// Indicates a platform issue, which may be due to a transient condition or +// outage. +// +// * InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter may be missing or out of range. +// +// * ResourceNotFoundException +// A resource, such as a workgroup, was not found. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/ListTagsForResource +func (c *Athena) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + 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 *Athena) 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() +} + +// ListTagsForResourcePages iterates over the pages of a ListTagsForResource operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListTagsForResource 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 ListTagsForResource operation. +// pageNum := 0 +// err := client.ListTagsForResourcePages(params, +// func(page *athena.ListTagsForResourceOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Athena) ListTagsForResourcePages(input *ListTagsForResourceInput, fn func(*ListTagsForResourceOutput, bool) bool) error { + return c.ListTagsForResourcePagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTagsForResourcePagesWithContext same as ListTagsForResourcePages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Athena) ListTagsForResourcePagesWithContext(ctx aws.Context, input *ListTagsForResourceInput, fn func(*ListTagsForResourceOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTagsForResourceInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTagsForResourceRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListTagsForResourceOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListWorkGroups = "ListWorkGroups" + +// ListWorkGroupsRequest generates a "aws/request.Request" representing the +// client's request for the ListWorkGroups operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListWorkGroups for more information on using the ListWorkGroups // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration @@ -1526,11 +2461,10 @@ func (c *Athena) StartQueryExecutionRequest(input *StartQueryExecutionInput) (re // StartQueryExecution API operation for Amazon Athena. // // Runs the SQL query statements contained in the Query. Requires you to have -// access to the workgroup in which the query ran. -// -// For code samples using the AWS SDK for Java, see Examples and Code Samples -// (http://docs.aws.amazon.com/athena/latest/ug/code-samples.html) in the Amazon -// Athena User Guide. +// access to the workgroup in which the query ran. Running queries against an +// external catalog requires GetDataCatalog permission to the catalog. For code +// samples using the AWS SDK for Java, see Examples and Code Samples (http://docs.aws.amazon.com/athena/latest/ug/code-samples.html) +// in the Amazon Athena 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 @@ -1708,19 +2642,18 @@ func (c *Athena) TagResourceRequest(input *TagResourceInput) (req *request.Reque // TagResource API operation for Amazon Athena. // -// Adds one or more tags to the resource, such as a workgroup. A tag is a label -// that you assign to an AWS Athena resource (a workgroup). Each tag consists -// of a key and an optional value, both of which you define. Tags enable you -// to categorize resources (workgroups) in Athena, for example, by purpose, -// owner, or environment. Use a consistent set of tag keys to make it easier -// to search and filter workgroups in your account. For best practices, see -// AWS Tagging Strategies (https://aws.amazon.com/answers/account-management/aws-tagging-strategies/). -// The key length is from 1 (minimum) to 128 (maximum) Unicode characters in -// UTF-8. The tag value length is from 0 (minimum) to 256 (maximum) Unicode -// characters in UTF-8. You can use letters and numbers representable in UTF-8, -// and the following characters: + - = . _ : / @. Tag keys and values are case-sensitive. -// Tag keys must be unique per resource. If you specify more than one, separate -// them by commas. +// Adds one or more tags to an Athena resource. A tag is a label that you assign +// to a resource. In Athena, a resource can be a workgroup or data catalog. +// Each tag consists of a key and an optional value, both of which you define. +// For example, you can use tags to categorize Athena workgroups or data catalogs +// by purpose, owner, or environment. Use a consistent set of tag keys to make +// it easier to search and filter workgroups or data catalogs in your account. +// For best practices, see Tagging Best Practices (https://aws.amazon.com/answers/account-management/aws-tagging-strategies/). +// Tag keys can be from 1 to 128 UTF-8 Unicode characters, and tag values can +// be from 0 to 256 UTF-8 Unicode characters. Tags can use letters and numbers +// representable in UTF-8, and the following characters: + - = . _ : / @. Tag +// keys and values are case-sensitive. Tag keys must be unique per resource. +// If you specify more than one tag, separate them by commas. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1773,51 +2706,137 @@ const opUntagResource = "UntagResource" // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UntagResource for more information on using the UntagResource +// See UntagResource for more information on using the UntagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UntagResourceRequest method. +// req, resp := client.UntagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/UntagResource +func (c *Athena) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { + op := &request.Operation{ + Name: opUntagResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UntagResourceInput{} + } + + output = &UntagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UntagResource API operation for Amazon Athena. +// +// Removes one or more tags from a data catalog or workgroup 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 Amazon Athena's +// API operation UntagResource for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// Indicates a platform issue, which may be due to a transient condition or +// outage. +// +// * InvalidRequestException +// Indicates that something is wrong with the input to the request. For example, +// a required parameter may be missing or out of range. +// +// * ResourceNotFoundException +// A resource, such as a workgroup, was not found. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/UntagResource +func (c *Athena) 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 *Athena) 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 opUpdateDataCatalog = "UpdateDataCatalog" + +// UpdateDataCatalogRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDataCatalog operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDataCatalog for more information on using the UpdateDataCatalog // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UntagResourceRequest method. -// req, resp := client.UntagResourceRequest(params) +// // Example sending a request using the UpdateDataCatalogRequest method. +// req, resp := client.UpdateDataCatalogRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/UntagResource -func (c *Athena) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/UpdateDataCatalog +func (c *Athena) UpdateDataCatalogRequest(input *UpdateDataCatalogInput) (req *request.Request, output *UpdateDataCatalogOutput) { op := &request.Operation{ - Name: opUntagResource, + Name: opUpdateDataCatalog, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UntagResourceInput{} + input = &UpdateDataCatalogInput{} } - output = &UntagResourceOutput{} + output = &UpdateDataCatalogOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// UntagResource API operation for Amazon Athena. +// UpdateDataCatalog API operation for Amazon Athena. // -// Removes one or more tags from the workgroup resource. Takes as an input a -// list of TagKey Strings separated by commas, and removes their tags at the -// same time. +// Updates the data catalog that has the specified 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 Athena's -// API operation UntagResource for usage and error information. +// API operation UpdateDataCatalog for usage and error information. // // Returned Error Types: // * InternalServerException @@ -1828,26 +2847,23 @@ func (c *Athena) UntagResourceRequest(input *UntagResourceInput) (req *request.R // Indicates that something is wrong with the input to the request. For example, // a required parameter may be missing or out of range. // -// * ResourceNotFoundException -// A resource, such as a workgroup, was not found. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/UntagResource -func (c *Athena) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { - req, out := c.UntagResourceRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/athena-2017-05-18/UpdateDataCatalog +func (c *Athena) UpdateDataCatalog(input *UpdateDataCatalogInput) (*UpdateDataCatalogOutput, error) { + req, out := c.UpdateDataCatalogRequest(input) return out, req.Send() } -// UntagResourceWithContext is the same as UntagResource with the addition of +// UpdateDataCatalogWithContext is the same as UpdateDataCatalog 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. +// See UpdateDataCatalog for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *Athena) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) { - req, out := c.UntagResourceRequest(input) +func (c *Athena) UpdateDataCatalogWithContext(ctx aws.Context, input *UpdateDataCatalogInput, opts ...request.Option) (*UpdateDataCatalogOutput, error) { + req, out := c.UpdateDataCatalogRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() @@ -2085,6 +3101,50 @@ func (s *BatchGetQueryExecutionOutput) SetUnprocessedQueryExecutionIds(v []*Unpr return s } +// Contains metadata for a column in a table. +type Column struct { + _ struct{} `type:"structure"` + + // Optional information about the column. + Comment *string `type:"string"` + + // The name of the column. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // The data type of the column. + Type *string `type:"string"` +} + +// String returns the string representation +func (s Column) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Column) GoString() string { + return s.String() +} + +// SetComment sets the Comment field's value. +func (s *Column) SetComment(v string) *Column { + s.Comment = &v + return s +} + +// SetName sets the Name field's value. +func (s *Column) SetName(v string) *Column { + s.Name = &v + return s +} + +// SetType sets the Type field's value. +func (s *Column) SetType(v string) *Column { + s.Type = &v + return s +} + // Information about the columns in a query execution result. type ColumnInfo struct { _ struct{} `type:"structure"` @@ -2196,6 +3256,132 @@ func (s *ColumnInfo) SetType(v string) *ColumnInfo { return s } +type CreateDataCatalogInput struct { + _ struct{} `type:"structure"` + + // A description of the data catalog to be created. + Description *string `min:"1" type:"string"` + + // The name of the data catalog to create. The catalog name must be unique for + // the AWS account and can use a maximum of 128 alphanumeric, underscore, at + // sign, or hyphen characters. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // Specifies the Lambda function or functions to use for creating the data catalog. + // This is a mapping whose values depend on the catalog type. + // + // * For the HIVE data catalog type, use the following syntax. The metadata-function + // parameter is required. The sdk-version parameter is optional and defaults + // to the currently supported version. metadata-function=lambda_arn, sdk-version=version_number + // + // * For the LAMBDA data catalog type, use one of the following sets of required + // parameters, but not both. If you have one Lambda function that processes + // metadata and another for reading the actual data, use the following syntax. + // Both parameters are required. metadata-function=lambda_arn, record-function=lambda_arn + // If you have a composite Lambda function that processes both metadata and + // data, use the following syntax to specify your Lambda function. function=lambda_arn + // + // * The GLUE type has no parameters. + Parameters map[string]*string `type:"map"` + + // A list of comma separated tags to add to the data catalog that is created. + Tags []*Tag `type:"list"` + + // The type of data catalog to create: LAMBDA for a federated catalog, GLUE + // for AWS Glue Catalog, or HIVE for an external hive metastore. + // + // Type is a required field + Type *string `type:"string" required:"true" enum:"DataCatalogType"` +} + +// String returns the string representation +func (s CreateDataCatalogInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDataCatalogInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateDataCatalogInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDataCatalogInput"} + if s.Description != nil && len(*s.Description) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Description", 1)) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *CreateDataCatalogInput) SetDescription(v string) *CreateDataCatalogInput { + s.Description = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateDataCatalogInput) SetName(v string) *CreateDataCatalogInput { + s.Name = &v + return s +} + +// SetParameters sets the Parameters field's value. +func (s *CreateDataCatalogInput) SetParameters(v map[string]*string) *CreateDataCatalogInput { + s.Parameters = v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateDataCatalogInput) SetTags(v []*Tag) *CreateDataCatalogInput { + s.Tags = v + return s +} + +// SetType sets the Type field's value. +func (s *CreateDataCatalogInput) SetType(v string) *CreateDataCatalogInput { + s.Type = &v + return s +} + +type CreateDataCatalogOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s CreateDataCatalogOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDataCatalogOutput) GoString() string { + return s.String() +} + type CreateNamedQueryInput struct { _ struct{} `type:"structure"` @@ -2354,8 +3540,7 @@ type CreateWorkGroupInput struct { // Name is a required field Name *string `type:"string" required:"true"` - // One or more tags, separated by commas, that you want to attach to the workgroup - // as you create it. + // A list of comma separated tags to add to the workgroup that is created. Tags []*Tag `type:"list"` } @@ -2397,68 +3582,273 @@ func (s *CreateWorkGroupInput) Validate() error { return nil } -// SetConfiguration sets the Configuration field's value. -func (s *CreateWorkGroupInput) SetConfiguration(v *WorkGroupConfiguration) *CreateWorkGroupInput { - s.Configuration = v - return s +// SetConfiguration sets the Configuration field's value. +func (s *CreateWorkGroupInput) SetConfiguration(v *WorkGroupConfiguration) *CreateWorkGroupInput { + s.Configuration = v + return s +} + +// SetDescription sets the Description field's value. +func (s *CreateWorkGroupInput) SetDescription(v string) *CreateWorkGroupInput { + s.Description = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateWorkGroupInput) SetName(v string) *CreateWorkGroupInput { + s.Name = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateWorkGroupInput) SetTags(v []*Tag) *CreateWorkGroupInput { + s.Tags = v + return s +} + +type CreateWorkGroupOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s CreateWorkGroupOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateWorkGroupOutput) GoString() string { + return s.String() +} + +// Contains information about a data catalog in an AWS account. +type DataCatalog struct { + _ struct{} `type:"structure"` + + // An optional description of the data catalog. + Description *string `min:"1" type:"string"` + + // The name of the data catalog. The catalog name must be unique for the AWS + // account and can use a maximum of 128 alphanumeric, underscore, at sign, or + // hyphen characters. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // Specifies the Lambda function or functions to use for the data catalog. This + // is a mapping whose values depend on the catalog type. + // + // * For the HIVE data catalog type, use the following syntax. The metadata-function + // parameter is required. The sdk-version parameter is optional and defaults + // to the currently supported version. metadata-function=lambda_arn, sdk-version=version_number + // + // * For the LAMBDA data catalog type, use one of the following sets of required + // parameters, but not both. If you have one Lambda function that processes + // metadata and another for reading the actual data, use the following syntax. + // Both parameters are required. metadata-function=lambda_arn, record-function=lambda_arn + // If you have a composite Lambda function that processes both metadata and + // data, use the following syntax to specify your Lambda function. function=lambda_arn + // + // * The GLUE type has no parameters. + Parameters map[string]*string `type:"map"` + + // The type of data catalog: LAMBDA for a federated catalog, GLUE for AWS Glue + // Catalog, or HIVE for an external hive metastore. + // + // Type is a required field + Type *string `type:"string" required:"true" enum:"DataCatalogType"` +} + +// String returns the string representation +func (s DataCatalog) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DataCatalog) GoString() string { + return s.String() +} + +// SetDescription sets the Description field's value. +func (s *DataCatalog) SetDescription(v string) *DataCatalog { + s.Description = &v + return s +} + +// SetName sets the Name field's value. +func (s *DataCatalog) SetName(v string) *DataCatalog { + s.Name = &v + return s +} + +// SetParameters sets the Parameters field's value. +func (s *DataCatalog) SetParameters(v map[string]*string) *DataCatalog { + s.Parameters = v + return s +} + +// SetType sets the Type field's value. +func (s *DataCatalog) SetType(v string) *DataCatalog { + s.Type = &v + return s +} + +// The summary information for the data catalog, which includes its name and +// type. +type DataCatalogSummary struct { + _ struct{} `type:"structure"` + + // The name of the data catalog. + CatalogName *string `min:"1" type:"string"` + + // The data catalog type. + Type *string `type:"string" enum:"DataCatalogType"` +} + +// String returns the string representation +func (s DataCatalogSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DataCatalogSummary) GoString() string { + return s.String() +} + +// SetCatalogName sets the CatalogName field's value. +func (s *DataCatalogSummary) SetCatalogName(v string) *DataCatalogSummary { + s.CatalogName = &v + return s +} + +// SetType sets the Type field's value. +func (s *DataCatalogSummary) SetType(v string) *DataCatalogSummary { + s.Type = &v + return s +} + +// Contains metadata information for a database in a data catalog. +type Database struct { + _ struct{} `type:"structure"` + + // An optional description of the database. + Description *string `min:"1" type:"string"` + + // The name of the database. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // A set of custom key/value pairs. + Parameters map[string]*string `type:"map"` +} + +// String returns the string representation +func (s Database) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Database) GoString() string { + return s.String() } // SetDescription sets the Description field's value. -func (s *CreateWorkGroupInput) SetDescription(v string) *CreateWorkGroupInput { +func (s *Database) SetDescription(v string) *Database { s.Description = &v return s } // SetName sets the Name field's value. -func (s *CreateWorkGroupInput) SetName(v string) *CreateWorkGroupInput { +func (s *Database) SetName(v string) *Database { s.Name = &v return s } -// SetTags sets the Tags field's value. -func (s *CreateWorkGroupInput) SetTags(v []*Tag) *CreateWorkGroupInput { - s.Tags = v +// SetParameters sets the Parameters field's value. +func (s *Database) SetParameters(v map[string]*string) *Database { + s.Parameters = v return s } -type CreateWorkGroupOutput struct { +// A piece of data (a field in the table). +type Datum struct { _ struct{} `type:"structure"` + + // The value of the datum. + VarCharValue *string `type:"string"` } // String returns the string representation -func (s CreateWorkGroupOutput) String() string { +func (s Datum) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateWorkGroupOutput) GoString() string { +func (s Datum) GoString() string { return s.String() } -// A piece of data (a field in the table). -type Datum struct { +// SetVarCharValue sets the VarCharValue field's value. +func (s *Datum) SetVarCharValue(v string) *Datum { + s.VarCharValue = &v + return s +} + +type DeleteDataCatalogInput struct { _ struct{} `type:"structure"` - // The value of the datum. - VarCharValue *string `type:"string"` + // The name of the data catalog to delete. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s Datum) String() string { +func (s DeleteDataCatalogInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Datum) GoString() string { +func (s DeleteDataCatalogInput) GoString() string { return s.String() } -// SetVarCharValue sets the VarCharValue field's value. -func (s *Datum) SetVarCharValue(v string) *Datum { - s.VarCharValue = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteDataCatalogInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDataCatalogInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *DeleteDataCatalogInput) SetName(v string) *DeleteDataCatalogInput { + s.Name = &v return s } +type DeleteDataCatalogOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteDataCatalogOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDataCatalogOutput) GoString() string { + return s.String() +} + type DeleteNamedQueryInput struct { _ struct{} `type:"structure"` @@ -2613,6 +4003,151 @@ func (s *EncryptionConfiguration) SetKmsKey(v string) *EncryptionConfiguration { return s } +type GetDataCatalogInput struct { + _ struct{} `type:"structure"` + + // The name of the data catalog to return. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetDataCatalogInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDataCatalogInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetDataCatalogInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDataCatalogInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *GetDataCatalogInput) SetName(v string) *GetDataCatalogInput { + s.Name = &v + return s +} + +type GetDataCatalogOutput struct { + _ struct{} `type:"structure"` + + // The data catalog returned. + DataCatalog *DataCatalog `type:"structure"` +} + +// String returns the string representation +func (s GetDataCatalogOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDataCatalogOutput) GoString() string { + return s.String() +} + +// SetDataCatalog sets the DataCatalog field's value. +func (s *GetDataCatalogOutput) SetDataCatalog(v *DataCatalog) *GetDataCatalogOutput { + s.DataCatalog = v + return s +} + +type GetDatabaseInput struct { + _ struct{} `type:"structure"` + + // The name of the data catalog that contains the database to return. + // + // CatalogName is a required field + CatalogName *string `min:"1" type:"string" required:"true"` + + // The name of the database to return. + // + // DatabaseName is a required field + DatabaseName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetDatabaseInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDatabaseInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetDatabaseInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDatabaseInput"} + if s.CatalogName == nil { + invalidParams.Add(request.NewErrParamRequired("CatalogName")) + } + if s.CatalogName != nil && len(*s.CatalogName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogName", 1)) + } + if s.DatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("DatabaseName")) + } + if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCatalogName sets the CatalogName field's value. +func (s *GetDatabaseInput) SetCatalogName(v string) *GetDatabaseInput { + s.CatalogName = &v + return s +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *GetDatabaseInput) SetDatabaseName(v string) *GetDatabaseInput { + s.DatabaseName = &v + return s +} + +type GetDatabaseOutput struct { + _ struct{} `type:"structure"` + + // The database returned. + Database *Database `type:"structure"` +} + +// String returns the string representation +func (s GetDatabaseOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDatabaseOutput) GoString() string { + return s.String() +} + +// SetDatabase sets the Database field's value. +func (s *GetDatabaseOutput) SetDatabase(v *Database) *GetDatabaseOutput { + s.Database = v + return s +} + type GetNamedQueryInput struct { _ struct{} `type:"structure"` @@ -2741,8 +4276,10 @@ type GetQueryResultsInput struct { // The maximum number of results (rows) to return in this request. MaxResults *int64 `min:"1" type:"integer"` - // The token that specifies where to start pagination if a previous request - // was truncated. + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. NextToken *string `min:"1" type:"string"` // The unique ID of the query execution. @@ -2767,11 +4304,131 @@ func (s *GetQueryResultsInput) Validate() error { 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 s.NextToken != nil && len(*s.NextToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) + } + if s.QueryExecutionId == nil { + invalidParams.Add(request.NewErrParamRequired("QueryExecutionId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetQueryResultsInput) SetMaxResults(v int64) *GetQueryResultsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetQueryResultsInput) SetNextToken(v string) *GetQueryResultsInput { + s.NextToken = &v + return s +} + +// SetQueryExecutionId sets the QueryExecutionId field's value. +func (s *GetQueryResultsInput) SetQueryExecutionId(v string) *GetQueryResultsInput { + s.QueryExecutionId = &v + return s +} + +type GetQueryResultsOutput struct { + _ struct{} `type:"structure"` + + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. + NextToken *string `min:"1" type:"string"` + + // The results of the query execution. + ResultSet *ResultSet `type:"structure"` + + // The number of rows inserted with a CREATE TABLE AS SELECT statement. + UpdateCount *int64 `type:"long"` +} + +// String returns the string representation +func (s GetQueryResultsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetQueryResultsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *GetQueryResultsOutput) SetNextToken(v string) *GetQueryResultsOutput { + s.NextToken = &v + return s +} + +// SetResultSet sets the ResultSet field's value. +func (s *GetQueryResultsOutput) SetResultSet(v *ResultSet) *GetQueryResultsOutput { + s.ResultSet = v + return s +} + +// SetUpdateCount sets the UpdateCount field's value. +func (s *GetQueryResultsOutput) SetUpdateCount(v int64) *GetQueryResultsOutput { + s.UpdateCount = &v + return s +} + +type GetTableMetadataInput struct { + _ struct{} `type:"structure"` + + // The name of the data catalog that contains the database and table metadata + // to return. + // + // CatalogName is a required field + CatalogName *string `min:"1" type:"string" required:"true"` + + // The name of the database that contains the table metadata to return. + // + // DatabaseName is a required field + DatabaseName *string `min:"1" type:"string" required:"true"` + + // The name of the table for which metadata is returned. + // + // TableName is a required field + TableName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetTableMetadataInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetTableMetadataInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetTableMetadataInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetTableMetadataInput"} + if s.CatalogName == nil { + invalidParams.Add(request.NewErrParamRequired("CatalogName")) + } + if s.CatalogName != nil && len(*s.CatalogName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogName", 1)) } - if s.QueryExecutionId == nil { - invalidParams.Add(request.NewErrParamRequired("QueryExecutionId")) + if s.DatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("DatabaseName")) + } + if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) + } + if s.TableName == nil { + invalidParams.Add(request.NewErrParamRequired("TableName")) + } + if s.TableName != nil && len(*s.TableName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TableName", 1)) } if invalidParams.Len() > 0 { @@ -2780,62 +4437,44 @@ func (s *GetQueryResultsInput) Validate() error { return nil } -// SetMaxResults sets the MaxResults field's value. -func (s *GetQueryResultsInput) SetMaxResults(v int64) *GetQueryResultsInput { - s.MaxResults = &v +// SetCatalogName sets the CatalogName field's value. +func (s *GetTableMetadataInput) SetCatalogName(v string) *GetTableMetadataInput { + s.CatalogName = &v return s } -// SetNextToken sets the NextToken field's value. -func (s *GetQueryResultsInput) SetNextToken(v string) *GetQueryResultsInput { - s.NextToken = &v +// SetDatabaseName sets the DatabaseName field's value. +func (s *GetTableMetadataInput) SetDatabaseName(v string) *GetTableMetadataInput { + s.DatabaseName = &v return s } -// SetQueryExecutionId sets the QueryExecutionId field's value. -func (s *GetQueryResultsInput) SetQueryExecutionId(v string) *GetQueryResultsInput { - s.QueryExecutionId = &v +// SetTableName sets the TableName field's value. +func (s *GetTableMetadataInput) SetTableName(v string) *GetTableMetadataInput { + s.TableName = &v return s } -type GetQueryResultsOutput struct { +type GetTableMetadataOutput struct { _ struct{} `type:"structure"` - // A token to be used by the next request if this request is truncated. - NextToken *string `min:"1" type:"string"` - - // The results of the query execution. - ResultSet *ResultSet `type:"structure"` - - // The number of rows inserted with a CREATE TABLE AS SELECT statement. - UpdateCount *int64 `type:"long"` + // An object that contains table metadata. + TableMetadata *TableMetadata `type:"structure"` } // String returns the string representation -func (s GetQueryResultsOutput) String() string { +func (s GetTableMetadataOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetQueryResultsOutput) GoString() string { +func (s GetTableMetadataOutput) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *GetQueryResultsOutput) SetNextToken(v string) *GetQueryResultsOutput { - s.NextToken = &v - return s -} - -// SetResultSet sets the ResultSet field's value. -func (s *GetQueryResultsOutput) SetResultSet(v *ResultSet) *GetQueryResultsOutput { - s.ResultSet = v - return s -} - -// SetUpdateCount sets the UpdateCount field's value. -func (s *GetQueryResultsOutput) SetUpdateCount(v int64) *GetQueryResultsOutput { - s.UpdateCount = &v +// SetTableMetadata sets the TableMetadata field's value. +func (s *GetTableMetadataOutput) SetTableMetadata(v *TableMetadata) *GetTableMetadataOutput { + s.TableMetadata = v return s } @@ -3018,19 +4657,210 @@ func (s *InvalidRequestException) RequestID() string { return s.RespMetadata.RequestID } +type ListDataCatalogsInput struct { + _ struct{} `type:"structure"` + + // Specifies the maximum number of data catalogs to return. + MaxResults *int64 `min:"2" type:"integer"` + + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListDataCatalogsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListDataCatalogsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListDataCatalogsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDataCatalogsInput"} + if s.MaxResults != nil && *s.MaxResults < 2 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 2)) + } + 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 *ListDataCatalogsInput) SetMaxResults(v int64) *ListDataCatalogsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDataCatalogsInput) SetNextToken(v string) *ListDataCatalogsInput { + s.NextToken = &v + return s +} + +type ListDataCatalogsOutput struct { + _ struct{} `type:"structure"` + + // A summary list of data catalogs. + DataCatalogsSummary []*DataCatalogSummary `type:"list"` + + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListDataCatalogsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListDataCatalogsOutput) GoString() string { + return s.String() +} + +// SetDataCatalogsSummary sets the DataCatalogsSummary field's value. +func (s *ListDataCatalogsOutput) SetDataCatalogsSummary(v []*DataCatalogSummary) *ListDataCatalogsOutput { + s.DataCatalogsSummary = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDataCatalogsOutput) SetNextToken(v string) *ListDataCatalogsOutput { + s.NextToken = &v + return s +} + +type ListDatabasesInput struct { + _ struct{} `type:"structure"` + + // The name of the data catalog that contains the databases to return. + // + // CatalogName is a required field + CatalogName *string `min:"1" type:"string" required:"true"` + + // Specifies the maximum number of results to return. + MaxResults *int64 `min:"1" type:"integer"` + + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListDatabasesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListDatabasesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListDatabasesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDatabasesInput"} + if s.CatalogName == nil { + invalidParams.Add(request.NewErrParamRequired("CatalogName")) + } + if s.CatalogName != nil && len(*s.CatalogName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogName", 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 +} + +// SetCatalogName sets the CatalogName field's value. +func (s *ListDatabasesInput) SetCatalogName(v string) *ListDatabasesInput { + s.CatalogName = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListDatabasesInput) SetMaxResults(v int64) *ListDatabasesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDatabasesInput) SetNextToken(v string) *ListDatabasesInput { + s.NextToken = &v + return s +} + +type ListDatabasesOutput struct { + _ struct{} `type:"structure"` + + // A list of databases from a data catalog. + DatabaseList []*Database `type:"list"` + + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListDatabasesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListDatabasesOutput) GoString() string { + return s.String() +} + +// SetDatabaseList sets the DatabaseList field's value. +func (s *ListDatabasesOutput) SetDatabaseList(v []*Database) *ListDatabasesOutput { + s.DatabaseList = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDatabasesOutput) SetNextToken(v string) *ListDatabasesOutput { + s.NextToken = &v + return s +} + type ListNamedQueriesInput struct { _ struct{} `type:"structure"` // The maximum number of queries to return in this request. MaxResults *int64 `type:"integer"` - // The token that specifies where to start pagination if a previous request - // was truncated. + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. NextToken *string `min:"1" type:"string"` - // The name of the workgroup from which the named queries are returned. If a - // workgroup is not specified, the saved queries for the primary workgroup are - // returned. + // The name of the workgroup from which the named queries are being returned. + // If a workgroup is not specified, the saved queries for the primary workgroup + // are returned. WorkGroup *string `type:"string"` } @@ -3081,7 +4911,10 @@ type ListNamedQueriesOutput struct { // The list of unique query IDs. NamedQueryIds []*string `min:"1" type:"list"` - // A token to be used by the next request if this request is truncated. + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. NextToken *string `min:"1" type:"string"` } @@ -3102,40 +4935,157 @@ func (s *ListNamedQueriesOutput) SetNamedQueryIds(v []*string) *ListNamedQueries } // SetNextToken sets the NextToken field's value. -func (s *ListNamedQueriesOutput) SetNextToken(v string) *ListNamedQueriesOutput { +func (s *ListNamedQueriesOutput) SetNextToken(v string) *ListNamedQueriesOutput { + s.NextToken = &v + return s +} + +type ListQueryExecutionsInput struct { + _ struct{} `type:"structure"` + + // The maximum number of query executions to return in this request. + MaxResults *int64 `type:"integer"` + + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. + NextToken *string `min:"1" type:"string"` + + // The name of the workgroup from which queries are being returned. If a workgroup + // is not specified, a list of available query execution IDs for the queries + // in the primary workgroup is returned. + WorkGroup *string `type:"string"` +} + +// String returns the string representation +func (s ListQueryExecutionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListQueryExecutionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListQueryExecutionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListQueryExecutionsInput"} + 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 *ListQueryExecutionsInput) SetMaxResults(v int64) *ListQueryExecutionsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListQueryExecutionsInput) SetNextToken(v string) *ListQueryExecutionsInput { + s.NextToken = &v + return s +} + +// SetWorkGroup sets the WorkGroup field's value. +func (s *ListQueryExecutionsInput) SetWorkGroup(v string) *ListQueryExecutionsInput { + s.WorkGroup = &v + return s +} + +type ListQueryExecutionsOutput struct { + _ struct{} `type:"structure"` + + // A token to be used by the next request if this request is truncated. + NextToken *string `min:"1" type:"string"` + + // The unique IDs of each query execution as an array of strings. + QueryExecutionIds []*string `min:"1" type:"list"` +} + +// String returns the string representation +func (s ListQueryExecutionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListQueryExecutionsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListQueryExecutionsOutput) SetNextToken(v string) *ListQueryExecutionsOutput { s.NextToken = &v return s } -type ListQueryExecutionsInput struct { +// SetQueryExecutionIds sets the QueryExecutionIds field's value. +func (s *ListQueryExecutionsOutput) SetQueryExecutionIds(v []*string) *ListQueryExecutionsOutput { + s.QueryExecutionIds = v + return s +} + +type ListTableMetadataInput struct { _ struct{} `type:"structure"` - // The maximum number of query executions to return in this request. - MaxResults *int64 `type:"integer"` + // The name of the data catalog for which table metadata should be returned. + // + // CatalogName is a required field + CatalogName *string `min:"1" type:"string" required:"true"` - // The token that specifies where to start pagination if a previous request - // was truncated. - NextToken *string `min:"1" type:"string"` + // The name of the database for which table metadata should be returned. + // + // DatabaseName is a required field + DatabaseName *string `min:"1" type:"string" required:"true"` - // The name of the workgroup from which queries are returned. If a workgroup - // is not specified, a list of available query execution IDs for the queries - // in the primary workgroup is returned. - WorkGroup *string `type:"string"` + // A regex filter that pattern-matches table names. If no expression is supplied, + // metadata for all tables are listed. + Expression *string `type:"string"` + + // Specifies the maximum number of results to return. + MaxResults *int64 `min:"1" type:"integer"` + + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. + NextToken *string `min:"1" type:"string"` } // String returns the string representation -func (s ListQueryExecutionsInput) String() string { +func (s ListTableMetadataInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListQueryExecutionsInput) GoString() string { +func (s ListTableMetadataInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListQueryExecutionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListQueryExecutionsInput"} +func (s *ListTableMetadataInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTableMetadataInput"} + if s.CatalogName == nil { + invalidParams.Add(request.NewErrParamRequired("CatalogName")) + } + if s.CatalogName != nil && len(*s.CatalogName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogName", 1)) + } + if s.DatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("DatabaseName")) + } + if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 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)) } @@ -3146,53 +5096,68 @@ func (s *ListQueryExecutionsInput) Validate() error { return nil } +// SetCatalogName sets the CatalogName field's value. +func (s *ListTableMetadataInput) SetCatalogName(v string) *ListTableMetadataInput { + s.CatalogName = &v + return s +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *ListTableMetadataInput) SetDatabaseName(v string) *ListTableMetadataInput { + s.DatabaseName = &v + return s +} + +// SetExpression sets the Expression field's value. +func (s *ListTableMetadataInput) SetExpression(v string) *ListTableMetadataInput { + s.Expression = &v + return s +} + // SetMaxResults sets the MaxResults field's value. -func (s *ListQueryExecutionsInput) SetMaxResults(v int64) *ListQueryExecutionsInput { +func (s *ListTableMetadataInput) SetMaxResults(v int64) *ListTableMetadataInput { s.MaxResults = &v return s } // SetNextToken sets the NextToken field's value. -func (s *ListQueryExecutionsInput) SetNextToken(v string) *ListQueryExecutionsInput { +func (s *ListTableMetadataInput) SetNextToken(v string) *ListTableMetadataInput { s.NextToken = &v return s } -// SetWorkGroup sets the WorkGroup field's value. -func (s *ListQueryExecutionsInput) SetWorkGroup(v string) *ListQueryExecutionsInput { - s.WorkGroup = &v - return s -} - -type ListQueryExecutionsOutput struct { +type ListTableMetadataOutput struct { _ struct{} `type:"structure"` - // A token to be used by the next request if this request is truncated. + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. NextToken *string `min:"1" type:"string"` - // The unique IDs of each query execution as an array of strings. - QueryExecutionIds []*string `min:"1" type:"list"` + // A list of table metadata. + TableMetadataList []*TableMetadata `type:"list"` } // String returns the string representation -func (s ListQueryExecutionsOutput) String() string { +func (s ListTableMetadataOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListQueryExecutionsOutput) GoString() string { +func (s ListTableMetadataOutput) GoString() string { return s.String() } // SetNextToken sets the NextToken field's value. -func (s *ListQueryExecutionsOutput) SetNextToken(v string) *ListQueryExecutionsOutput { +func (s *ListTableMetadataOutput) SetNextToken(v string) *ListTableMetadataOutput { s.NextToken = &v return s } -// SetQueryExecutionIds sets the QueryExecutionIds field's value. -func (s *ListQueryExecutionsOutput) SetQueryExecutionIds(v []*string) *ListQueryExecutionsOutput { - s.QueryExecutionIds = v +// SetTableMetadataList sets the TableMetadataList field's value. +func (s *ListTableMetadataOutput) SetTableMetadataList(v []*TableMetadata) *ListTableMetadataOutput { + s.TableMetadataList = v return s } @@ -3200,15 +5165,15 @@ type ListTagsForResourceInput struct { _ struct{} `type:"structure"` // The maximum number of results to be returned per request that lists the tags - // for the workgroup resource. + // for the resource. MaxResults *int64 `min:"75" type:"integer"` // The token for the next set of results, or null if there are no additional - // results for this request, where the request lists the tags for the workgroup - // resource with the specified ARN. + // results for this request, where the request lists the tags for the resource + // with the specified ARN. NextToken *string `min:"1" type:"string"` - // Lists the tags for the workgroup resource with the specified ARN. + // Lists the tags for the resource with the specified ARN. // // ResourceARN is a required field ResourceARN *string `min:"1" type:"string" required:"true"` @@ -3270,7 +5235,7 @@ type ListTagsForResourceOutput struct { // A token to be used by the next request if this request is truncated. NextToken *string `min:"1" type:"string"` - // The list of tags associated with this workgroup. + // The list of tags associated with the specified resource. Tags []*Tag `type:"list"` } @@ -3302,7 +5267,10 @@ type ListWorkGroupsInput struct { // The maximum number of workgroups to return in this request. MaxResults *int64 `min:"1" type:"integer"` - // A token to be used by the next request if this request is truncated. + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. NextToken *string `min:"1" type:"string"` } @@ -3347,7 +5315,10 @@ func (s *ListWorkGroupsInput) SetNextToken(v string) *ListWorkGroupsInput { type ListWorkGroupsOutput struct { _ struct{} `type:"structure"` - // A token to be used by the next request if this request is truncated. + // A token generated by the Athena service that specifies where to continue + // pagination if a previous request was truncated. To obtain the next set of + // pages, pass in the NextToken from the response object of the previous page + // call. NextToken *string `min:"1" type:"string"` // The list of workgroups, including their names, descriptions, creation times, @@ -3377,6 +5348,66 @@ func (s *ListWorkGroupsOutput) SetWorkGroups(v []*WorkGroupSummary) *ListWorkGro return s } +// An exception that Athena received when it called a custom metastore. Occurs +// if the error is not caused by user input (InvalidRequestException) or from +// the Athena platform (InternalServerException). For example, if a user-created +// Lambda function is missing permissions, the Lambda 4XX exception is returned +// in a MetadataException. +type MetadataException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s MetadataException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MetadataException) GoString() string { + return s.String() +} + +func newErrorMetadataException(v protocol.ResponseMetadata) error { + return &MetadataException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *MetadataException) Code() string { + return "MetadataException" +} + +// Message returns the exception's message. +func (s *MetadataException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *MetadataException) OrigErr() error { + return nil +} + +func (s *MetadataException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *MetadataException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *MetadataException) RequestID() string { + return s.RespMetadata.RequestID +} + // A query, where QueryString is the list of SQL query statements that comprise // the query. type NamedQuery struct { @@ -3550,11 +5581,14 @@ func (s *QueryExecution) SetWorkGroup(v string) *QueryExecution { return s } -// The database in which the query execution occurs. +// The database and data catalog context in which the query execution occurs. type QueryExecutionContext struct { _ struct{} `type:"structure"` - // The name of the database. + // The name of the data catalog used in the query execution. + Catalog *string `min:"1" type:"string"` + + // The name of the database used in the query execution. Database *string `min:"1" type:"string"` } @@ -3571,6 +5605,9 @@ func (s QueryExecutionContext) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *QueryExecutionContext) Validate() error { invalidParams := request.ErrInvalidParams{Context: "QueryExecutionContext"} + if s.Catalog != nil && len(*s.Catalog) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Catalog", 1)) + } if s.Database != nil && len(*s.Database) < 1 { invalidParams.Add(request.NewErrParamMinLen("Database", 1)) } @@ -3581,6 +5618,12 @@ func (s *QueryExecutionContext) Validate() error { return nil } +// SetCatalog sets the Catalog field's value. +func (s *QueryExecutionContext) SetCatalog(v string) *QueryExecutionContext { + s.Catalog = &v + return s +} + // SetDatabase sets the Database field's value. func (s *QueryExecutionContext) SetDatabase(v string) *QueryExecutionContext { s.Database = &v @@ -3693,6 +5736,10 @@ type QueryExecutionStatus struct { // indicates that the query completed without errors. FAILED indicates that // the query experienced an error and did not complete processing. CANCELLED // indicates that a user input interrupted query execution. + // + // Athena automatically retries your queries in cases of certain transient errors. + // As a result, you may see the query state transition from RUNNING or FAILED + // to QUEUED. State *string `type:"string" enum:"QueryExecutionState"` // Further detail about the status of the query. @@ -3944,7 +5991,7 @@ func (s *ResultConfigurationUpdates) SetRemoveOutputLocation(v bool) *ResultConf } // The metadata and rows that comprise a query result set. The metadata describes -// the column structure and data types. +// the column structure and data types. To return a ResultSet object, use GetQueryResults. type ResultSet struct { _ struct{} `type:"structure"` @@ -3979,7 +6026,7 @@ func (s *ResultSet) SetRows(v []*Row) *ResultSet { } // The metadata that describes the column structure and data types of a table -// of query results. +// of query results. To return a ResultSetMetadata object, use GetQueryResults. type ResultSetMetadata struct { _ struct{} `type:"structure"` @@ -4188,16 +6235,97 @@ func (s StopQueryExecutionOutput) GoString() string { return s.String() } -// A tag that you can add to a resource. A tag is a label that you assign to -// an AWS Athena resource (a workgroup). Each tag consists of a key and an optional -// value, both of which you define. Tags enable you to categorize workgroups -// in Athena, for example, by purpose, owner, or environment. Use a consistent -// set of tag keys to make it easier to search and filter workgroups in your -// account. The maximum tag key length is 128 Unicode characters in UTF-8. The -// maximum tag value length is 256 Unicode characters in UTF-8. You can use -// letters and numbers representable in UTF-8, and the following characters: -// + - = . _ : / @. Tag keys and values are case-sensitive. Tag keys must be -// unique per resource. +// Contains metadata for a table. +type TableMetadata struct { + _ struct{} `type:"structure"` + + // A list of the columns in the table. + Columns []*Column `type:"list"` + + // The time that the table was created. + CreateTime *time.Time `type:"timestamp"` + + // The last time the table was accessed. + LastAccessTime *time.Time `type:"timestamp"` + + // The name of the table. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // A set of custom key/value pairs for table properties. + Parameters map[string]*string `type:"map"` + + // A list of the partition keys in the table. + PartitionKeys []*Column `type:"list"` + + // The type of table. In Athena, only EXTERNAL_TABLE is supported. + TableType *string `type:"string"` +} + +// String returns the string representation +func (s TableMetadata) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TableMetadata) GoString() string { + return s.String() +} + +// SetColumns sets the Columns field's value. +func (s *TableMetadata) SetColumns(v []*Column) *TableMetadata { + s.Columns = v + return s +} + +// SetCreateTime sets the CreateTime field's value. +func (s *TableMetadata) SetCreateTime(v time.Time) *TableMetadata { + s.CreateTime = &v + return s +} + +// SetLastAccessTime sets the LastAccessTime field's value. +func (s *TableMetadata) SetLastAccessTime(v time.Time) *TableMetadata { + s.LastAccessTime = &v + return s +} + +// SetName sets the Name field's value. +func (s *TableMetadata) SetName(v string) *TableMetadata { + s.Name = &v + return s +} + +// SetParameters sets the Parameters field's value. +func (s *TableMetadata) SetParameters(v map[string]*string) *TableMetadata { + s.Parameters = v + return s +} + +// SetPartitionKeys sets the PartitionKeys field's value. +func (s *TableMetadata) SetPartitionKeys(v []*Column) *TableMetadata { + s.PartitionKeys = v + return s +} + +// SetTableType sets the TableType field's value. +func (s *TableMetadata) SetTableType(v string) *TableMetadata { + s.TableType = &v + return s +} + +// A label that you assign to a resource. In Athena, a resource can be a workgroup +// or data catalog. Each tag consists of a key and an optional value, both of +// which you define. For example, you can use tags to categorize Athena workgroups +// or data catalogs by purpose, owner, or environment. Use a consistent set +// of tag keys to make it easier to search and filter workgroups or data catalogs +// in your account. For best practices, see Tagging Best Practices (https://aws.amazon.com/answers/account-management/aws-tagging-strategies/). +// Tag keys can be from 1 to 128 UTF-8 Unicode characters, and tag values can +// be from 0 to 256 UTF-8 Unicode characters. Tags can use letters and numbers +// representable in UTF-8, and the following characters: + - = . _ : / @. Tag +// keys and values are case-sensitive. Tag keys must be unique per resource. +// If you specify more than one tag, separate them by commas. type Tag struct { _ struct{} `type:"structure"` @@ -4251,14 +6379,14 @@ func (s *Tag) SetValue(v string) *Tag { type TagResourceInput struct { _ struct{} `type:"structure"` - // Requests that one or more tags are added to the resource (such as a workgroup) - // for the specified ARN. + // Specifies the ARN of the Athena resource (workgroup or data catalog) to which + // tags are to be added. // // ResourceARN is a required field ResourceARN *string `min:"1" type:"string" required:"true"` - // One or more tags, separated by commas, to be added to the resource, such - // as a workgroup. + // A collection of one or more tags, separated by commas, to be added to an + // Athena workgroup or data catalog resource. // // Tags is a required field Tags []*Tag `type:"list" required:"true"` @@ -4479,13 +6607,13 @@ func (s *UnprocessedQueryExecutionId) SetQueryExecutionId(v string) *Unprocessed type UntagResourceInput struct { _ struct{} `type:"structure"` - // Removes one or more tags from the workgroup resource for the specified ARN. + // Specifies the ARN of the resource from which tags are to be removed. // // ResourceARN is a required field ResourceARN *string `min:"1" type:"string" required:"true"` - // Removes the tags associated with one or more tag keys from the workgroup - // resource. + // A comma-separated list of one or more tag keys whose tags are to be removed + // from the specified resource. // // TagKeys is a required field TagKeys []*string `type:"list" required:"true"` @@ -4546,6 +6674,113 @@ func (s UntagResourceOutput) GoString() string { return s.String() } +type UpdateDataCatalogInput struct { + _ struct{} `type:"structure"` + + // New or modified text that describes the data catalog. + Description *string `min:"1" type:"string"` + + // The name of the data catalog to update. The catalog name must be unique for + // the AWS account and can use a maximum of 128 alphanumeric, underscore, at + // sign, or hyphen characters. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // Specifies the Lambda function or functions to use for updating the data catalog. + // This is a mapping whose values depend on the catalog type. + // + // * For the HIVE data catalog type, use the following syntax. The metadata-function + // parameter is required. The sdk-version parameter is optional and defaults + // to the currently supported version. metadata-function=lambda_arn, sdk-version=version_number + // + // * For the LAMBDA data catalog type, use one of the following sets of required + // parameters, but not both. If you have one Lambda function that processes + // metadata and another for reading the actual data, use the following syntax. + // Both parameters are required. metadata-function=lambda_arn, record-function=lambda_arn + // If you have a composite Lambda function that processes both metadata and + // data, use the following syntax to specify your Lambda function. function=lambda_arn + // + // * The GLUE type has no parameters. + Parameters map[string]*string `type:"map"` + + // Specifies the type of data catalog to update. Specify LAMBDA for a federated + // catalog, GLUE for AWS Glue Catalog, or HIVE for an external hive metastore. + // + // Type is a required field + Type *string `type:"string" required:"true" enum:"DataCatalogType"` +} + +// String returns the string representation +func (s UpdateDataCatalogInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateDataCatalogInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateDataCatalogInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateDataCatalogInput"} + if s.Description != nil && len(*s.Description) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Description", 1)) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *UpdateDataCatalogInput) SetDescription(v string) *UpdateDataCatalogInput { + s.Description = &v + return s +} + +// SetName sets the Name field's value. +func (s *UpdateDataCatalogInput) SetName(v string) *UpdateDataCatalogInput { + s.Name = &v + return s +} + +// SetParameters sets the Parameters field's value. +func (s *UpdateDataCatalogInput) SetParameters(v map[string]*string) *UpdateDataCatalogInput { + s.Parameters = v + return s +} + +// SetType sets the Type field's value. +func (s *UpdateDataCatalogInput) SetType(v string) *UpdateDataCatalogInput { + s.Type = &v + return s +} + +type UpdateDataCatalogOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UpdateDataCatalogOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateDataCatalogOutput) GoString() string { + return s.String() +} + type UpdateWorkGroupInput struct { _ struct{} `type:"structure"` @@ -4971,6 +7206,35 @@ const ( ColumnNullableUnknown = "UNKNOWN" ) +// ColumnNullable_Values returns all elements of the ColumnNullable enum +func ColumnNullable_Values() []string { + return []string{ + ColumnNullableNotNull, + ColumnNullableNullable, + ColumnNullableUnknown, + } +} + +const ( + // DataCatalogTypeLambda is a DataCatalogType enum value + DataCatalogTypeLambda = "LAMBDA" + + // DataCatalogTypeGlue is a DataCatalogType enum value + DataCatalogTypeGlue = "GLUE" + + // DataCatalogTypeHive is a DataCatalogType enum value + DataCatalogTypeHive = "HIVE" +) + +// DataCatalogType_Values returns all elements of the DataCatalogType enum +func DataCatalogType_Values() []string { + return []string{ + DataCatalogTypeLambda, + DataCatalogTypeGlue, + DataCatalogTypeHive, + } +} + const ( // EncryptionOptionSseS3 is a EncryptionOption enum value EncryptionOptionSseS3 = "SSE_S3" @@ -4982,6 +7246,15 @@ const ( EncryptionOptionCseKms = "CSE_KMS" ) +// EncryptionOption_Values returns all elements of the EncryptionOption enum +func EncryptionOption_Values() []string { + return []string{ + EncryptionOptionSseS3, + EncryptionOptionSseKms, + EncryptionOptionCseKms, + } +} + const ( // QueryExecutionStateQueued is a QueryExecutionState enum value QueryExecutionStateQueued = "QUEUED" @@ -4999,6 +7272,17 @@ const ( QueryExecutionStateCancelled = "CANCELLED" ) +// QueryExecutionState_Values returns all elements of the QueryExecutionState enum +func QueryExecutionState_Values() []string { + return []string{ + QueryExecutionStateQueued, + QueryExecutionStateRunning, + QueryExecutionStateSucceeded, + QueryExecutionStateFailed, + QueryExecutionStateCancelled, + } +} + const ( // StatementTypeDdl is a StatementType enum value StatementTypeDdl = "DDL" @@ -5010,6 +7294,15 @@ const ( StatementTypeUtility = "UTILITY" ) +// StatementType_Values returns all elements of the StatementType enum +func StatementType_Values() []string { + return []string{ + StatementTypeDdl, + StatementTypeDml, + StatementTypeUtility, + } +} + // The reason for the query throttling, for example, when it exceeds the concurrent // query limit. const ( @@ -5017,6 +7310,13 @@ const ( ThrottleReasonConcurrentQueryLimitExceeded = "CONCURRENT_QUERY_LIMIT_EXCEEDED" ) +// ThrottleReason_Values returns all elements of the ThrottleReason enum +func ThrottleReason_Values() []string { + return []string{ + ThrottleReasonConcurrentQueryLimitExceeded, + } +} + const ( // WorkGroupStateEnabled is a WorkGroupState enum value WorkGroupStateEnabled = "ENABLED" @@ -5024,3 +7324,11 @@ const ( // WorkGroupStateDisabled is a WorkGroupState enum value WorkGroupStateDisabled = "DISABLED" ) + +// WorkGroupState_Values returns all elements of the WorkGroupState enum +func WorkGroupState_Values() []string { + return []string{ + WorkGroupStateEnabled, + WorkGroupStateDisabled, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/athena/errors.go b/vendor/github.com/aws/aws-sdk-go/service/athena/errors.go index 5da82bf6a0e..a0939ed6d5e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/athena/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/athena/errors.go @@ -22,6 +22,16 @@ const ( // a required parameter may be missing or out of range. ErrCodeInvalidRequestException = "InvalidRequestException" + // ErrCodeMetadataException for service response error code + // "MetadataException". + // + // An exception that Athena received when it called a custom metastore. Occurs + // if the error is not caused by user input (InvalidRequestException) or from + // the Athena platform (InternalServerException). For example, if a user-created + // Lambda function is missing permissions, the Lambda 4XX exception is returned + // in a MetadataException. + ErrCodeMetadataException = "MetadataException" + // ErrCodeResourceNotFoundException for service response error code // "ResourceNotFoundException". // @@ -38,6 +48,7 @@ const ( var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "InternalServerException": newErrorInternalServerException, "InvalidRequestException": newErrorInvalidRequestException, + "MetadataException": newErrorMetadataException, "ResourceNotFoundException": newErrorResourceNotFoundException, "TooManyRequestsException": newErrorTooManyRequestsException, } 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 d80c2f819d9..bea102a8869 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 @@ -158,8 +158,9 @@ func (c *AutoScaling) AttachLoadBalancerTargetGroupsRequest(input *AttachLoadBal // // Attaches one or more target groups to the specified Auto Scaling group. // -// To describe the target groups for an Auto Scaling group, use DescribeLoadBalancerTargetGroups. -// To detach the target group from the Auto Scaling group, use DetachLoadBalancerTargetGroups. +// To describe the target groups for an Auto Scaling group, call the DescribeLoadBalancerTargetGroups +// API. To detach the target group from the Auto Scaling group, call the DetachLoadBalancerTargetGroups +// API. // // With Application Load Balancers and Network Load Balancers, instances are // registered as targets with a target group. With Classic Load Balancers, instances @@ -249,14 +250,17 @@ func (c *AutoScaling) AttachLoadBalancersRequest(input *AttachLoadBalancersInput // AttachLoadBalancers API operation for Auto Scaling. // -// Attaches one or more Classic Load Balancers to the specified Auto Scaling -// group. // -// To attach an Application Load Balancer or a Network Load Balancer instead, -// see AttachLoadBalancerTargetGroups. +// To attach an Application Load Balancer or a Network Load Balancer, use the +// AttachLoadBalancerTargetGroups API operation instead. +// +// Attaches one or more Classic Load Balancers to the specified Auto Scaling +// group. Amazon EC2 Auto Scaling registers the running instances with these +// Classic Load Balancers. // -// To describe the load balancers for an Auto Scaling group, use DescribeLoadBalancers. -// To detach the load balancer from the Auto Scaling group, use DetachLoadBalancers. +// To describe the load balancers for an Auto Scaling group, call the DescribeLoadBalancers +// API. To detach the load balancer from the Auto Scaling group, call the DetachLoadBalancers +// API. // // For more information, see Attaching a Load Balancer to Your Auto Scaling // Group (https://docs.aws.amazon.com/autoscaling/ec2/userguide/attach-load-balancer-asg.html) @@ -442,7 +446,8 @@ func (c *AutoScaling) BatchPutScheduledUpdateGroupActionRequest(input *BatchPutS // * ErrCodeLimitExceededFault "LimitExceeded" // You have already reached a limit for your Amazon EC2 Auto Scaling resources // (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). -// For more information, see DescribeAccountLimits. +// For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) +// in the Amazon EC2 Auto Scaling API Reference. // // * ErrCodeResourceContentionFault "ResourceContention" // You already have a pending update to an Amazon EC2 Auto Scaling resource @@ -470,6 +475,101 @@ func (c *AutoScaling) BatchPutScheduledUpdateGroupActionWithContext(ctx aws.Cont return out, req.Send() } +const opCancelInstanceRefresh = "CancelInstanceRefresh" + +// CancelInstanceRefreshRequest generates a "aws/request.Request" representing the +// client's request for the CancelInstanceRefresh operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CancelInstanceRefresh for more information on using the CancelInstanceRefresh +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CancelInstanceRefreshRequest method. +// req, resp := client.CancelInstanceRefreshRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/CancelInstanceRefresh +func (c *AutoScaling) CancelInstanceRefreshRequest(input *CancelInstanceRefreshInput) (req *request.Request, output *CancelInstanceRefreshOutput) { + op := &request.Operation{ + Name: opCancelInstanceRefresh, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CancelInstanceRefreshInput{} + } + + output = &CancelInstanceRefreshOutput{} + req = c.newRequest(op, input, output) + return +} + +// CancelInstanceRefresh API operation for Auto Scaling. +// +// Cancels an instance refresh operation in progress. Cancellation does not +// roll back any replacements that have already been completed, but it prevents +// new replacements from being started. +// +// For more information, see Replacing Auto Scaling Instances Based on an Instance +// Refresh (https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-instance-refresh.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Auto Scaling's +// API operation CancelInstanceRefresh for usage and error information. +// +// Returned Error Codes: +// * ErrCodeLimitExceededFault "LimitExceeded" +// You have already reached a limit for your Amazon EC2 Auto Scaling resources +// (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). +// For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) +// in the Amazon EC2 Auto Scaling API Reference. +// +// * ErrCodeResourceContentionFault "ResourceContention" +// You already have a pending update to an Amazon EC2 Auto Scaling resource +// (for example, an Auto Scaling group, instance, or load balancer). +// +// * ErrCodeActiveInstanceRefreshNotFoundFault "ActiveInstanceRefreshNotFound" +// The request failed because an active instance refresh for the specified Auto +// Scaling group was not found. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/CancelInstanceRefresh +func (c *AutoScaling) CancelInstanceRefresh(input *CancelInstanceRefreshInput) (*CancelInstanceRefreshOutput, error) { + req, out := c.CancelInstanceRefreshRequest(input) + return out, req.Send() +} + +// CancelInstanceRefreshWithContext is the same as CancelInstanceRefresh with the addition of +// the ability to pass a context and additional request options. +// +// See CancelInstanceRefresh for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) CancelInstanceRefreshWithContext(ctx aws.Context, input *CancelInstanceRefreshInput, opts ...request.Option) (*CancelInstanceRefreshOutput, error) { + req, out := c.CancelInstanceRefreshRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCompleteLifecycleAction = "CompleteLifecycleAction" // CompleteLifecycleActionRequest generates a "aws/request.Request" representing the @@ -622,11 +722,23 @@ func (c *AutoScaling) CreateAutoScalingGroupRequest(input *CreateAutoScalingGrou // Creates an Auto Scaling group with the specified name and attributes. // // If you exceed your maximum limit of Auto Scaling groups, the call fails. -// For information about viewing this limit, see DescribeAccountLimits. For -// information about updating this limit, see Amazon EC2 Auto Scaling Service -// Quotas (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-account-limits.html) +// To query this limit, call the DescribeAccountLimits API. For information +// about updating this limit, see Amazon EC2 Auto Scaling Service Quotas (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-account-limits.html) +// in the Amazon EC2 Auto Scaling User Guide. +// +// For introductory exercises for creating an Auto Scaling group, see Getting +// Started with Amazon EC2 Auto Scaling (https://docs.aws.amazon.com/autoscaling/ec2/userguide/GettingStartedTutorial.html) +// and Tutorial: Set Up a Scaled and Load-Balanced Application (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-register-lbs-with-asg.html) +// in the Amazon EC2 Auto Scaling User Guide. For more information, see Auto +// Scaling Groups (https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html) // in the Amazon EC2 Auto Scaling User Guide. // +// Every Auto Scaling group has three size parameters (DesiredCapacity, MaxSize, +// and MinSize). Usually, you set these sizes based on a specific number of +// instances. However, if you configure a mixed instances policy that defines +// weights for the instance types, you must specify these sizes with the same +// units that you use for weighting 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 // the error. @@ -642,7 +754,8 @@ func (c *AutoScaling) CreateAutoScalingGroupRequest(input *CreateAutoScalingGrou // * ErrCodeLimitExceededFault "LimitExceeded" // You have already reached a limit for your Amazon EC2 Auto Scaling resources // (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). -// For more information, see DescribeAccountLimits. +// For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) +// in the Amazon EC2 Auto Scaling API Reference. // // * ErrCodeResourceContentionFault "ResourceContention" // You already have a pending update to an Amazon EC2 Auto Scaling resource @@ -721,9 +834,8 @@ func (c *AutoScaling) CreateLaunchConfigurationRequest(input *CreateLaunchConfig // Creates a launch configuration. // // If you exceed your maximum limit of launch configurations, the call fails. -// For information about viewing this limit, see DescribeAccountLimits. For -// information about updating this limit, see Amazon EC2 Auto Scaling Service -// Quotas (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-account-limits.html) +// To query this limit, call the DescribeAccountLimits API. For information +// about updating this limit, see Amazon EC2 Auto Scaling Service Quotas (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-account-limits.html) // in the Amazon EC2 Auto Scaling User Guide. // // For more information, see Launch Configurations (https://docs.aws.amazon.com/autoscaling/ec2/userguide/LaunchConfiguration.html) @@ -744,7 +856,8 @@ func (c *AutoScaling) CreateLaunchConfigurationRequest(input *CreateLaunchConfig // * ErrCodeLimitExceededFault "LimitExceeded" // You have already reached a limit for your Amazon EC2 Auto Scaling resources // (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). -// For more information, see DescribeAccountLimits. +// For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) +// in the Amazon EC2 Auto Scaling API Reference. // // * ErrCodeResourceContentionFault "ResourceContention" // You already have a pending update to an Amazon EC2 Auto Scaling resource @@ -836,7 +949,8 @@ func (c *AutoScaling) CreateOrUpdateTagsRequest(input *CreateOrUpdateTagsInput) // * ErrCodeLimitExceededFault "LimitExceeded" // You have already reached a limit for your Amazon EC2 Auto Scaling resources // (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). -// For more information, see DescribeAccountLimits. +// For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) +// in the Amazon EC2 Auto Scaling API Reference. // // * ErrCodeAlreadyExistsFault "AlreadyExists" // You already have an Auto Scaling group or launch configuration with this @@ -925,13 +1039,13 @@ func (c *AutoScaling) DeleteAutoScalingGroupRequest(input *DeleteAutoScalingGrou // alarm actions, and any alarm that no longer has an associated action. // // To remove instances from the Auto Scaling group before deleting it, call -// DetachInstances with the list of instances and the option to decrement the -// desired capacity. This ensures that Amazon EC2 Auto Scaling does not launch -// replacement instances. +// the DetachInstances API with the list of instances and the option to decrement +// the desired capacity. This ensures that Amazon EC2 Auto Scaling does not +// launch replacement instances. // -// To terminate all instances before deleting the Auto Scaling group, call UpdateAutoScalingGroup -// and set the minimum size and desired capacity of the Auto Scaling group to -// zero. +// To terminate all instances before deleting the Auto Scaling group, call the +// UpdateAutoScalingGroup API and set the minimum size and desired capacity +// of the Auto Scaling group to zero. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1612,7 +1726,17 @@ func (c *AutoScaling) DescribeAdjustmentTypesRequest(input *DescribeAdjustmentTy // DescribeAdjustmentTypes API operation for Auto Scaling. // -// Describes the policy adjustment types for use with PutScalingPolicy. +// Describes the available adjustment types for Amazon EC2 Auto Scaling scaling +// policies. These settings apply to step scaling policies and simple scaling +// policies; they do not apply to target tracking scaling policies. +// +// The following adjustment types are supported: +// +// * ChangeInCapacity +// +// * ExactCapacity +// +// * PercentChangeInCapacity // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2010,6 +2134,110 @@ func (c *AutoScaling) DescribeAutoScalingNotificationTypesWithContext(ctx aws.Co return out, req.Send() } +const opDescribeInstanceRefreshes = "DescribeInstanceRefreshes" + +// DescribeInstanceRefreshesRequest generates a "aws/request.Request" representing the +// client's request for the DescribeInstanceRefreshes operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeInstanceRefreshes for more information on using the DescribeInstanceRefreshes +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeInstanceRefreshesRequest method. +// req, resp := client.DescribeInstanceRefreshesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeInstanceRefreshes +func (c *AutoScaling) DescribeInstanceRefreshesRequest(input *DescribeInstanceRefreshesInput) (req *request.Request, output *DescribeInstanceRefreshesOutput) { + op := &request.Operation{ + Name: opDescribeInstanceRefreshes, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeInstanceRefreshesInput{} + } + + output = &DescribeInstanceRefreshesOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeInstanceRefreshes API operation for Auto Scaling. +// +// Describes one or more instance refreshes. +// +// You can determine the status of a request by looking at the Status parameter. +// The following are the possible statuses: +// +// * Pending - The request was created, but the operation has not started. +// +// * InProgress - The operation is in progress. +// +// * Successful - The operation completed successfully. +// +// * Failed - The operation failed to complete. You can troubleshoot using +// the status reason and the scaling activities. +// +// * Cancelling - An ongoing operation is being cancelled. Cancellation does +// not roll back any replacements that have already been completed, but it +// prevents new replacements from being started. +// +// * Cancelled - The operation is cancelled. +// +// For more information, see Replacing Auto Scaling Instances Based on an Instance +// Refresh (https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-instance-refresh.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Auto Scaling's +// API operation DescribeInstanceRefreshes for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidNextToken "InvalidNextToken" +// The NextToken value is not valid. +// +// * ErrCodeResourceContentionFault "ResourceContention" +// You already have a pending update to an Amazon EC2 Auto Scaling resource +// (for example, an Auto Scaling group, instance, or load balancer). +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeInstanceRefreshes +func (c *AutoScaling) DescribeInstanceRefreshes(input *DescribeInstanceRefreshesInput) (*DescribeInstanceRefreshesOutput, error) { + req, out := c.DescribeInstanceRefreshesRequest(input) + return out, req.Send() +} + +// DescribeInstanceRefreshesWithContext is the same as DescribeInstanceRefreshes with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInstanceRefreshes for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeInstanceRefreshesWithContext(ctx aws.Context, input *DescribeInstanceRefreshesInput, opts ...request.Option) (*DescribeInstanceRefreshesOutput, error) { + req, out := c.DescribeInstanceRefreshesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeLaunchConfigurations = "DescribeLaunchConfigurations" // DescribeLaunchConfigurationsRequest generates a "aws/request.Request" representing the @@ -2444,8 +2672,8 @@ func (c *AutoScaling) DescribeLoadBalancersRequest(input *DescribeLoadBalancersI // Describes the load balancers for the specified Auto Scaling group. // // This operation describes only Classic Load Balancers. If you have Application -// Load Balancers or Network Load Balancers, use DescribeLoadBalancerTargetGroups -// instead. +// Load Balancers or Network Load Balancers, use the DescribeLoadBalancerTargetGroups +// API instead. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2528,7 +2756,7 @@ func (c *AutoScaling) DescribeMetricCollectionTypesRequest(input *DescribeMetric // Describes the available CloudWatch metrics for Amazon EC2 Auto Scaling. // // The GroupStandbyInstances metric is not returned by default. You must explicitly -// request this metric when calling EnableMetricsCollection. +// request this metric when calling the EnableMetricsCollection 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 @@ -3035,7 +3263,8 @@ func (c *AutoScaling) DescribeScalingProcessTypesRequest(input *DescribeScalingP // DescribeScalingProcessTypes API operation for Auto Scaling. // -// Describes the scaling process types for use with ResumeProcesses and SuspendProcesses. +// Describes the scaling process types for use with the ResumeProcesses and +// SuspendProcesses APIs. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3123,7 +3352,7 @@ func (c *AutoScaling) DescribeScheduledActionsRequest(input *DescribeScheduledAc // // Describes the actions scheduled for your Auto Scaling group that haven't // run or that have not reached their end time. To describe the actions that -// have already run, use DescribeScalingActivities. +// have already run, call the DescribeScalingActivities 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 @@ -3275,6 +3504,9 @@ func (c *AutoScaling) DescribeTagsRequest(input *DescribeTagsInput) (req *reques // a particular tag only if it matches all the filters. If there's no match, // no special message is returned. // +// For more information, see Tagging Auto Scaling Groups and Instances (https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html) +// in the Amazon EC2 Auto Scaling 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. @@ -3673,13 +3905,13 @@ func (c *AutoScaling) DetachLoadBalancersRequest(input *DetachLoadBalancersInput // group. // // This operation detaches only Classic Load Balancers. If you have Application -// Load Balancers or Network Load Balancers, use DetachLoadBalancerTargetGroups -// instead. +// Load Balancers or Network Load Balancers, use the DetachLoadBalancerTargetGroups +// API instead. // // When you detach a load balancer, it enters the Removing state while deregistering // the instances in the group. When all instances are deregistered, then you -// can no longer describe the load balancer using DescribeLoadBalancers. The -// instances remain running. +// can no longer describe the load balancer using the DescribeLoadBalancers +// API call. The instances remain running. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4017,7 +4249,8 @@ func (c *AutoScaling) ExecutePolicyRequest(input *ExecutePolicyInput) (req *requ // ExecutePolicy API operation for Auto Scaling. // -// Executes the specified policy. +// Executes the specified policy. This can be useful for testing the design +// of your scaling 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 @@ -4209,10 +4442,11 @@ func (c *AutoScaling) PutLifecycleHookRequest(input *PutLifecycleHookInput) (req // launch or terminate. // // If you need more time, record the lifecycle action heartbeat to keep the -// instance in a pending state using RecordLifecycleActionHeartbeat. +// instance in a pending state using the RecordLifecycleActionHeartbeat API +// call. // // If you finish before the timeout period ends, complete the lifecycle action -// using CompleteLifecycleAction. +// using the CompleteLifecycleAction API call. // // For more information, see Amazon EC2 Auto Scaling Lifecycle Hooks (https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html) // in the Amazon EC2 Auto Scaling User Guide. @@ -4220,8 +4454,9 @@ func (c *AutoScaling) PutLifecycleHookRequest(input *PutLifecycleHookInput) (req // If you exceed your maximum limit of lifecycle hooks, which by default is // 50 per Auto Scaling group, the call fails. // -// You can view the lifecycle hooks for an Auto Scaling group using DescribeLifecycleHooks. -// If you are no longer using a lifecycle hook, you can delete it using DeleteLifecycleHook. +// You can view the lifecycle hooks for an Auto Scaling group using the DescribeLifecycleHooks +// API call. If you are no longer using a lifecycle hook, you can delete it +// by calling the DeleteLifecycleHook 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 @@ -4234,7 +4469,8 @@ func (c *AutoScaling) PutLifecycleHookRequest(input *PutLifecycleHookInput) (req // * ErrCodeLimitExceededFault "LimitExceeded" // You have already reached a limit for your Amazon EC2 Auto Scaling resources // (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). -// For more information, see DescribeAccountLimits. +// For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) +// in the Amazon EC2 Auto Scaling API Reference. // // * ErrCodeResourceContentionFault "ResourceContention" // You already have a pending update to an Amazon EC2 Auto Scaling resource @@ -4328,7 +4564,8 @@ func (c *AutoScaling) PutNotificationConfigurationRequest(input *PutNotification // * ErrCodeLimitExceededFault "LimitExceeded" // You have already reached a limit for your Amazon EC2 Auto Scaling resources // (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). -// For more information, see DescribeAccountLimits. +// For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) +// in the Amazon EC2 Auto Scaling API Reference. // // * ErrCodeResourceContentionFault "ResourceContention" // You already have a pending update to an Amazon EC2 Auto Scaling resource @@ -4406,7 +4643,8 @@ func (c *AutoScaling) PutScalingPolicyRequest(input *PutScalingPolicyInput) (req // Creates or updates a scaling policy for an Auto Scaling group. // // For more information about using scaling policies to scale your Auto Scaling -// group automatically, see Dynamic Scaling (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scale-based-on-demand.html) +// group, see Target Tracking Scaling Policies (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-target-tracking.html) +// and Step and Simple Scaling Policies (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html) // in the Amazon EC2 Auto Scaling User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -4420,7 +4658,8 @@ func (c *AutoScaling) PutScalingPolicyRequest(input *PutScalingPolicyInput) (req // * ErrCodeLimitExceededFault "LimitExceeded" // You have already reached a limit for your Amazon EC2 Auto Scaling resources // (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). -// For more information, see DescribeAccountLimits. +// For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) +// in the Amazon EC2 Auto Scaling API Reference. // // * ErrCodeResourceContentionFault "ResourceContention" // You already have a pending update to an Amazon EC2 Auto Scaling resource @@ -4518,7 +4757,8 @@ func (c *AutoScaling) PutScheduledUpdateGroupActionRequest(input *PutScheduledUp // * ErrCodeLimitExceededFault "LimitExceeded" // You have already reached a limit for your Amazon EC2 Auto Scaling resources // (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). -// For more information, see DescribeAccountLimits. +// For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) +// in the Amazon EC2 Auto Scaling API Reference. // // * ErrCodeResourceContentionFault "ResourceContention" // You already have a pending update to an Amazon EC2 Auto Scaling resource @@ -4593,7 +4833,7 @@ func (c *AutoScaling) RecordLifecycleActionHeartbeatRequest(input *RecordLifecyc // // Records a heartbeat for the lifecycle action associated with the specified // token or instance. This extends the timeout by the length of time defined -// using PutLifecycleHook. +// using the PutLifecycleHook API call. // // This step is a part of the procedure for adding a lifecycle hook to an Auto // Scaling group: @@ -4786,8 +5026,11 @@ func (c *AutoScaling) SetDesiredCapacityRequest(input *SetDesiredCapacityInput) // // Sets the size of the specified Auto Scaling group. // -// For more information about desired capacity, see What Is Amazon EC2 Auto -// Scaling? (https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html) +// If a scale-in activity occurs as a result of a new DesiredCapacity value +// that is lower than the current size of the group, the Auto Scaling group +// uses its termination policy to determine which instances to terminate. +// +// For more information, see Manual Scaling (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-manual-scaling.html) // in the Amazon EC2 Auto Scaling User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -4974,7 +5217,8 @@ func (c *AutoScaling) SetInstanceProtectionRequest(input *SetInstanceProtectionI // * ErrCodeLimitExceededFault "LimitExceeded" // You have already reached a limit for your Amazon EC2 Auto Scaling resources // (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). -// For more information, see DescribeAccountLimits. +// For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) +// in the Amazon EC2 Auto Scaling API Reference. // // * ErrCodeResourceContentionFault "ResourceContention" // You already have a pending update to an Amazon EC2 Auto Scaling resource @@ -5002,6 +5246,107 @@ func (c *AutoScaling) SetInstanceProtectionWithContext(ctx aws.Context, input *S return out, req.Send() } +const opStartInstanceRefresh = "StartInstanceRefresh" + +// StartInstanceRefreshRequest generates a "aws/request.Request" representing the +// client's request for the StartInstanceRefresh operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See StartInstanceRefresh for more information on using the StartInstanceRefresh +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the StartInstanceRefreshRequest method. +// req, resp := client.StartInstanceRefreshRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/StartInstanceRefresh +func (c *AutoScaling) StartInstanceRefreshRequest(input *StartInstanceRefreshInput) (req *request.Request, output *StartInstanceRefreshOutput) { + op := &request.Operation{ + Name: opStartInstanceRefresh, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &StartInstanceRefreshInput{} + } + + output = &StartInstanceRefreshOutput{} + req = c.newRequest(op, input, output) + return +} + +// StartInstanceRefresh API operation for Auto Scaling. +// +// Starts a new instance refresh operation, which triggers a rolling replacement +// of all previously launched instances in the Auto Scaling group with a new +// group of instances. +// +// If successful, this call creates a new instance refresh request with a unique +// ID that you can use to track its progress. To query its status, call the +// DescribeInstanceRefreshes API. To describe the instance refreshes that have +// already run, call the DescribeInstanceRefreshes API. To cancel an instance +// refresh operation in progress, use the CancelInstanceRefresh API. +// +// For more information, see Replacing Auto Scaling Instances Based on an Instance +// Refresh (https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-instance-refresh.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Auto Scaling's +// API operation StartInstanceRefresh for usage and error information. +// +// Returned Error Codes: +// * ErrCodeLimitExceededFault "LimitExceeded" +// You have already reached a limit for your Amazon EC2 Auto Scaling resources +// (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). +// For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) +// in the Amazon EC2 Auto Scaling API Reference. +// +// * ErrCodeResourceContentionFault "ResourceContention" +// You already have a pending update to an Amazon EC2 Auto Scaling resource +// (for example, an Auto Scaling group, instance, or load balancer). +// +// * ErrCodeInstanceRefreshInProgressFault "InstanceRefreshInProgress" +// The request failed because an active instance refresh operation already exists +// for the specified Auto Scaling group. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/StartInstanceRefresh +func (c *AutoScaling) StartInstanceRefresh(input *StartInstanceRefreshInput) (*StartInstanceRefreshOutput, error) { + req, out := c.StartInstanceRefreshRequest(input) + return out, req.Send() +} + +// StartInstanceRefreshWithContext is the same as StartInstanceRefresh with the addition of +// the ability to pass a context and additional request options. +// +// See StartInstanceRefresh for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) StartInstanceRefreshWithContext(ctx aws.Context, input *StartInstanceRefreshInput, opts ...request.Option) (*StartInstanceRefreshOutput, error) { + req, out := c.StartInstanceRefreshRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opSuspendProcesses = "SuspendProcesses" // SuspendProcessesRequest generates a "aws/request.Request" representing the @@ -5051,13 +5396,12 @@ func (c *AutoScaling) SuspendProcessesRequest(input *ScalingProcessQuery) (req * // the specified Auto Scaling group. // // If you suspend either the Launch or Terminate process types, it can prevent -// other process types from functioning properly. -// -// To resume processes that have been suspended, use ResumeProcesses. -// -// For more information, see Suspending and Resuming Scaling Processes (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html) +// other process types from functioning properly. For more information, see +// Suspending and Resuming Scaling Processes (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html) // in the Amazon EC2 Auto Scaling User Guide. // +// To resume processes that have been suspended, call the ResumeProcesses 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. @@ -5140,7 +5484,9 @@ func (c *AutoScaling) TerminateInstanceInAutoScalingGroupRequest(input *Terminat // TerminateInstanceInAutoScalingGroup API operation for Auto Scaling. // // Terminates the specified instance and optionally adjusts the desired group -// size. This call simply makes a termination request. The instance is not terminated +// size. +// +// This call simply makes a termination request. The instance is not terminated // immediately. When an instance is terminated, the instance status changes // to terminated. You can't connect to or start an instance after you've terminated // it. @@ -5260,7 +5606,7 @@ func (c *AutoScaling) UpdateAutoScalingGroupRequest(input *UpdateAutoScalingGrou // // Note the following about changing DesiredCapacity, MaxSize, or MinSize: // -// * If a scale-in event occurs as a result of a new DesiredCapacity value +// * If a scale-in activity occurs as a result of a new DesiredCapacity value // that is lower than the current size of the group, the Auto Scaling group // uses its termination policy to determine which instances to terminate. // @@ -5273,9 +5619,10 @@ func (c *AutoScaling) UpdateAutoScalingGroupRequest(input *UpdateAutoScalingGrou // of the group, this sets the group's DesiredCapacity to the new MaxSize // value. // -// To see which parameters have been set, use DescribeAutoScalingGroups. You -// can also view the scaling policies for an Auto Scaling group using DescribePolicies. -// If the group has scaling policies, you can update them using PutScalingPolicy. +// To see which parameters have been set, call the DescribeAutoScalingGroups +// API. To view the scaling policies for an Auto Scaling group, call the DescribePolicies +// API. If the group has scaling policies, you can update them by calling the +// PutScalingPolicy 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 @@ -5876,17 +6223,23 @@ type BlockDeviceMapping struct { // DeviceName is a required field DeviceName *string `min:"1" type:"string" required:"true"` - // The information about the Amazon EBS volume. + // Parameters used to automatically set up EBS volumes when an instance is launched. + // + // You can specify either VirtualName or Ebs, but not both. Ebs *Ebs `type:"structure"` - // Suppresses a device mapping. + // Setting this value to true suppresses the specified device included in the + // block device mapping of the AMI. // - // If this parameter is true for the root device, the instance might fail the - // EC2 health check. In that case, Amazon EC2 Auto Scaling launches a replacement - // instance. + // If NoDevice is true for the root device, instances might fail the EC2 health + // check. In that case, Amazon EC2 Auto Scaling launches replacement instances. + // + // If you specify NoDevice, you cannot specify Ebs. NoDevice *bool `type:"boolean"` // The name of the virtual device (for example, ephemeral0). + // + // You can specify either VirtualName or Ebs, but not both. VirtualName *string `min:"1" type:"string"` } @@ -5948,58 +6301,122 @@ func (s *BlockDeviceMapping) SetVirtualName(v string) *BlockDeviceMapping { return s } -type CompleteLifecycleActionInput struct { +type CancelInstanceRefreshInput struct { _ struct{} `type:"structure"` // The name of the Auto Scaling group. // // AutoScalingGroupName is a required field AutoScalingGroupName *string `min:"1" type:"string" required:"true"` - - // The ID of the instance. - InstanceId *string `min:"1" type:"string"` - - // The action for the group to take. This parameter can be either CONTINUE or - // ABANDON. - // - // LifecycleActionResult is a required field - LifecycleActionResult *string `type:"string" required:"true"` - - // A universally unique identifier (UUID) that identifies a specific lifecycle - // action associated with an instance. Amazon EC2 Auto Scaling sends this token - // to the notification target you specified when you created the lifecycle hook. - LifecycleActionToken *string `min:"36" type:"string"` - - // The name of the lifecycle hook. - // - // LifecycleHookName is a required field - LifecycleHookName *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s CompleteLifecycleActionInput) String() string { +func (s CancelInstanceRefreshInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CompleteLifecycleActionInput) GoString() string { +func (s CancelInstanceRefreshInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CompleteLifecycleActionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CompleteLifecycleActionInput"} +func (s *CancelInstanceRefreshInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CancelInstanceRefreshInput"} if s.AutoScalingGroupName == nil { invalidParams.Add(request.NewErrParamRequired("AutoScalingGroupName")) } if s.AutoScalingGroupName != nil && len(*s.AutoScalingGroupName) < 1 { invalidParams.Add(request.NewErrParamMinLen("AutoScalingGroupName", 1)) } - if s.InstanceId != nil && len(*s.InstanceId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("InstanceId", 1)) - } - if s.LifecycleActionResult == nil { - invalidParams.Add(request.NewErrParamRequired("LifecycleActionResult")) + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAutoScalingGroupName sets the AutoScalingGroupName field's value. +func (s *CancelInstanceRefreshInput) SetAutoScalingGroupName(v string) *CancelInstanceRefreshInput { + s.AutoScalingGroupName = &v + return s +} + +type CancelInstanceRefreshOutput struct { + _ struct{} `type:"structure"` + + // The instance refresh ID. + InstanceRefreshId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s CancelInstanceRefreshOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CancelInstanceRefreshOutput) GoString() string { + return s.String() +} + +// SetInstanceRefreshId sets the InstanceRefreshId field's value. +func (s *CancelInstanceRefreshOutput) SetInstanceRefreshId(v string) *CancelInstanceRefreshOutput { + s.InstanceRefreshId = &v + return s +} + +type CompleteLifecycleActionInput struct { + _ struct{} `type:"structure"` + + // The name of the Auto Scaling group. + // + // AutoScalingGroupName is a required field + AutoScalingGroupName *string `min:"1" type:"string" required:"true"` + + // The ID of the instance. + InstanceId *string `min:"1" type:"string"` + + // The action for the group to take. This parameter can be either CONTINUE or + // ABANDON. + // + // LifecycleActionResult is a required field + LifecycleActionResult *string `type:"string" required:"true"` + + // A universally unique identifier (UUID) that identifies a specific lifecycle + // action associated with an instance. Amazon EC2 Auto Scaling sends this token + // to the notification target you specified when you created the lifecycle hook. + LifecycleActionToken *string `min:"36" type:"string"` + + // The name of the lifecycle hook. + // + // LifecycleHookName is a required field + LifecycleHookName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CompleteLifecycleActionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CompleteLifecycleActionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CompleteLifecycleActionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CompleteLifecycleActionInput"} + if s.AutoScalingGroupName == nil { + invalidParams.Add(request.NewErrParamRequired("AutoScalingGroupName")) + } + if s.AutoScalingGroupName != nil && len(*s.AutoScalingGroupName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AutoScalingGroupName", 1)) + } + if s.InstanceId != nil && len(*s.InstanceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("InstanceId", 1)) + } + if s.LifecycleActionResult == nil { + invalidParams.Add(request.NewErrParamRequired("LifecycleActionResult")) } if s.LifecycleActionToken != nil && len(*s.LifecycleActionToken) < 36 { invalidParams.Add(request.NewErrParamMinLen("LifecycleActionToken", 36)) @@ -6080,15 +6497,19 @@ type CreateAutoScalingGroupInput struct { // The amount of time, in seconds, after a scaling activity completes before // another scaling activity can start. The default value is 300. // - // For more information, see Scaling Cooldowns (https://docs.aws.amazon.com/autoscaling/ec2/userguide/Cooldown.html) + // This setting applies when using simple scaling policies, but not when using + // other scaling policies or scheduled scaling. For more information, see Scaling + // Cooldowns for Amazon EC2 Auto Scaling (https://docs.aws.amazon.com/autoscaling/ec2/userguide/Cooldown.html) // in the Amazon EC2 Auto Scaling User Guide. DefaultCooldown *int64 `type:"integer"` - // The number of Amazon EC2 instances that the Auto Scaling group attempts to - // maintain. This number must be greater than or equal to the minimum size of - // the group and less than or equal to the maximum size of the group. If you - // do not specify a desired capacity, the default is the minimum size of the - // group. + // The desired capacity is the initial capacity of the Auto Scaling group at + // the time of its creation and the capacity it attempts to maintain. It can + // scale beyond this capacity if you configure automatic scaling. + // + // This number must be greater than or equal to the minimum size of the group + // and less than or equal to the maximum size of the group. If you do not specify + // a desired capacity, the default is the minimum size of the group. DesiredCapacity *int64 `type:"integer"` // The amount of time, in seconds, that Amazon EC2 Auto Scaling waits before @@ -6099,7 +6520,7 @@ type CreateAutoScalingGroupInput struct { // For more information, see Health Check Grace Period (https://docs.aws.amazon.com/autoscaling/ec2/userguide/healthcheck.html#health-check-grace-period) // in the Amazon EC2 Auto Scaling User Guide. // - // Conditional: This parameter is required if you are adding an ELB health check. + // Required if you are adding an ELB health check. HealthCheckGracePeriod *int64 `type:"integer"` // The service to use for the health checks. The valid values are EC2 and ELB. @@ -6112,33 +6533,38 @@ type CreateAutoScalingGroupInput struct { HealthCheckType *string `min:"1" type:"string"` // The ID of the instance used to create a launch configuration for the group. + // To get the instance ID, use the Amazon EC2 DescribeInstances (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) + // API operation. // // When you specify an ID of an instance, Amazon EC2 Auto Scaling creates a // new launch configuration and associates it with the group. This launch configuration // derives its attributes from the specified instance, except for the block // device mapping. // - // For more information, see Create an Auto Scaling Group Using an EC2 Instance - // (https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-asg-from-instance.html) - // in the Amazon EC2 Auto Scaling User Guide. - // // You must specify one of the following parameters in your request: LaunchConfigurationName, // LaunchTemplate, InstanceId, or MixedInstancesPolicy. InstanceId *string `min:"1" type:"string"` - // The name of the launch configuration. + // The name of the launch configuration to use when an instance is launched. + // To get the launch configuration name, use the DescribeLaunchConfigurations + // API operation. New launch configurations can be created with the CreateLaunchConfiguration + // API. // - // If you do not specify LaunchConfigurationName, you must specify one of the - // following parameters: InstanceId, LaunchTemplate, or MixedInstancesPolicy. + // You must specify one of the following parameters in your request: LaunchConfigurationName, + // LaunchTemplate, InstanceId, or MixedInstancesPolicy. LaunchConfigurationName *string `min:"1" type:"string"` - // The launch template to use to launch instances. + // Parameters used to specify the launch template and version to use when an + // instance is launched. // // For more information, see LaunchTemplateSpecification (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_LaunchTemplateSpecification.html) // in the Amazon EC2 Auto Scaling API Reference. // - // If you do not specify LaunchTemplate, you must specify one of the following - // parameters: InstanceId, LaunchConfigurationName, or MixedInstancesPolicy. + // You can alternatively associate a launch template to the Auto Scaling group + // by using the MixedInstancesPolicy parameter. + // + // You must specify one of the following parameters in your request: LaunchConfigurationName, + // LaunchTemplate, InstanceId, or MixedInstancesPolicy. LaunchTemplate *LaunchTemplateSpecification `type:"structure"` // One or more lifecycle hooks. @@ -6154,16 +6580,27 @@ type CreateAutoScalingGroupInput struct { LoadBalancerNames []*string `type:"list"` // The maximum amount of time, in seconds, that an instance can be in service. + // The default is null. + // + // This parameter is optional, but if you specify a value for it, you must specify + // a value of at least 604,800 seconds (7 days). To clear a previously set value, + // specify a new value of 0. // // For more information, see Replacing Auto Scaling Instances Based on Maximum // Instance Lifetime (https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-max-instance-lifetime.html) // in the Amazon EC2 Auto Scaling User Guide. // - // Valid Range: Minimum value of 604800. + // Valid Range: Minimum value of 0. MaxInstanceLifetime *int64 `type:"integer"` // The maximum size of the group. // + // With a mixed instances policy that uses instance weighting, Amazon EC2 Auto + // Scaling may need to go above MaxSize to meet your capacity requirements. + // In this event, Amazon EC2 Auto Scaling will never go above MaxSize by more + // than your largest instance weight (weights that define how many units each + // instance contributes to the desired capacity of the group). + // // MaxSize is a required field MaxSize *int64 `type:"integer" required:"true"` @@ -6214,7 +6651,14 @@ type CreateAutoScalingGroupInput struct { // in the Amazon EC2 Auto Scaling User Guide. ServiceLinkedRoleARN *string `min:"1" type:"string"` - // One or more tags. + // One or more tags. You can tag your Auto Scaling group and propagate the tags + // to the Amazon EC2 instances it launches. + // + // Tags are not propagated to Amazon EBS volumes. To add tags to Amazon EBS + // volumes, specify the tags in a launch template but use caution. If the launch + // template specifies an instance tag with a key that is also specified for + // the Auto Scaling group, Amazon EC2 Auto Scaling overrides the value of that + // instance tag with the value specified by the Auto Scaling group. // // For more information, see Tagging Auto Scaling Groups and Instances (https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html) // in the Amazon EC2 Auto Scaling User Guide. @@ -6597,6 +7041,11 @@ type CreateLaunchConfigurationInput struct { // LaunchConfigurationName is a required field LaunchConfigurationName *string `min:"1" type:"string" required:"true"` + // The metadata options for the instances. For more information, see Instance + // Metadata and User Data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) + // in the Amazon EC2 User Guide for Linux Instances. + MetadataOptions *InstanceMetadataOptions `type:"structure"` + // The tenancy of the instance. An instance with dedicated tenancy runs on isolated, // single-tenant hardware and can only be launched into a VPC. // @@ -6704,6 +7153,11 @@ func (s *CreateLaunchConfigurationInput) Validate() error { } } } + if s.MetadataOptions != nil { + if err := s.MetadataOptions.Validate(); err != nil { + invalidParams.AddNested("MetadataOptions", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -6789,6 +7243,12 @@ func (s *CreateLaunchConfigurationInput) SetLaunchConfigurationName(v string) *C return s } +// SetMetadataOptions sets the MetadataOptions field's value. +func (s *CreateLaunchConfigurationInput) SetMetadataOptions(v *InstanceMetadataOptions) *CreateLaunchConfigurationInput { + s.MetadataOptions = v + return s +} + // SetPlacementTenancy sets the PlacementTenancy field's value. func (s *CreateLaunchConfigurationInput) SetPlacementTenancy(v string) *CreateLaunchConfigurationInput { s.PlacementTenancy = &v @@ -7780,6 +8240,111 @@ func (s *DescribeAutoScalingNotificationTypesOutput) SetAutoScalingNotificationT return s } +type DescribeInstanceRefreshesInput struct { + _ struct{} `type:"structure"` + + // The name of the Auto Scaling group. + // + // AutoScalingGroupName is a required field + AutoScalingGroupName *string `min:"1" type:"string" required:"true"` + + // One or more instance refresh IDs. + InstanceRefreshIds []*string `type:"list"` + + // The maximum number of items to return with this call. The default value is + // 50 and the maximum value is 100. + MaxRecords *int64 `type:"integer"` + + // The token for the next set of items to return. (You received this token from + // a previous call.) + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeInstanceRefreshesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeInstanceRefreshesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeInstanceRefreshesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeInstanceRefreshesInput"} + if s.AutoScalingGroupName == nil { + invalidParams.Add(request.NewErrParamRequired("AutoScalingGroupName")) + } + if s.AutoScalingGroupName != nil && len(*s.AutoScalingGroupName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AutoScalingGroupName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAutoScalingGroupName sets the AutoScalingGroupName field's value. +func (s *DescribeInstanceRefreshesInput) SetAutoScalingGroupName(v string) *DescribeInstanceRefreshesInput { + s.AutoScalingGroupName = &v + return s +} + +// SetInstanceRefreshIds sets the InstanceRefreshIds field's value. +func (s *DescribeInstanceRefreshesInput) SetInstanceRefreshIds(v []*string) *DescribeInstanceRefreshesInput { + s.InstanceRefreshIds = v + return s +} + +// SetMaxRecords sets the MaxRecords field's value. +func (s *DescribeInstanceRefreshesInput) SetMaxRecords(v int64) *DescribeInstanceRefreshesInput { + s.MaxRecords = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeInstanceRefreshesInput) SetNextToken(v string) *DescribeInstanceRefreshesInput { + s.NextToken = &v + return s +} + +type DescribeInstanceRefreshesOutput struct { + _ struct{} `type:"structure"` + + // The instance refreshes for the specified group. + InstanceRefreshes []*InstanceRefresh `type:"list"` + + // A string that indicates that the response contains more items than can be + // returned in a single response. To receive additional items, specify this + // string for the NextToken value when requesting the next set of items. This + // value is null when there are no more items to return. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeInstanceRefreshesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeInstanceRefreshesOutput) GoString() string { + return s.String() +} + +// SetInstanceRefreshes sets the InstanceRefreshes field's value. +func (s *DescribeInstanceRefreshesOutput) SetInstanceRefreshes(v []*InstanceRefresh) *DescribeInstanceRefreshesOutput { + s.InstanceRefreshes = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeInstanceRefreshesOutput) SetNextToken(v string) *DescribeInstanceRefreshesOutput { + s.NextToken = &v + return s +} + type DescribeLaunchConfigurationsInput struct { _ struct{} `type:"structure"` @@ -9022,8 +9587,7 @@ type DisableMetricsCollectionInput struct { // AutoScalingGroupName is a required field AutoScalingGroupName *string `min:"1" type:"string" required:"true"` - // One or more of the following metrics. If you omit this parameter, all metrics - // are disabled. + // Specifies one or more of the following metrics: // // * GroupMinSize // @@ -9040,6 +9604,18 @@ type DisableMetricsCollectionInput struct { // * GroupTerminatingInstances // // * GroupTotalInstances + // + // * GroupInServiceCapacity + // + // * GroupPendingCapacity + // + // * GroupStandbyCapacity + // + // * GroupTerminatingCapacity + // + // * GroupTotalCapacity + // + // If you omit this parameter, all metrics are disabled. Metrics []*string `type:"list"` } @@ -9095,7 +9671,8 @@ func (s DisableMetricsCollectionOutput) GoString() string { return s.String() } -// Describes an Amazon EBS volume. Used in combination with BlockDeviceMapping. +// Describes information used to set up an Amazon EBS volume specified in a +// block device mapping. type Ebs struct { _ struct{} `type:"structure"` @@ -9133,15 +9710,13 @@ type Ebs struct { // see Amazon EBS Volume Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) // in the Amazon EC2 User Guide for Linux Instances. // - // Conditional: This parameter is required when the volume type is io1. (Not - // used with standard, gp2, st1, or sc1 volumes.) + // Required when the volume type is io1. (Not used with standard, gp2, st1, + // or sc1 volumes.) Iops *int64 `min:"100" type:"integer"` // The snapshot ID of the volume to use. // - // Conditional: This parameter is optional if you specify a volume size. If - // you specify both SnapshotId and VolumeSize, VolumeSize must be equal or greater - // than the size of the snapshot. + // You must specify either a VolumeSize or a SnapshotId. SnapshotId *string `min:"1" type:"string"` // The volume size, in Gibibytes (GiB). @@ -9153,7 +9728,9 @@ type Ebs struct { // Default: If you create a volume from a snapshot and you don't specify a volume // size, the default is the snapshot size. // - // At least one of VolumeSize or SnapshotId is required. + // You must specify either a VolumeSize or a SnapshotId. If you specify both + // SnapshotId and VolumeSize, the volume size must be equal or greater than + // the size of the snapshot. VolumeSize *int64 `min:"1" type:"integer"` // The volume type, which can be standard for Magnetic, io1 for Provisioned @@ -9247,8 +9824,8 @@ type EnableMetricsCollectionInput struct { // Granularity is a required field Granularity *string `min:"1" type:"string" required:"true"` - // One or more of the following metrics. If you omit this parameter, all metrics - // are enabled. + // Specifies which group-level metrics to start collecting. You can specify + // one or more of the following metrics: // // * GroupMinSize // @@ -9265,6 +9842,20 @@ type EnableMetricsCollectionInput struct { // * GroupTerminatingInstances // // * GroupTotalInstances + // + // The instance weighting feature supports the following additional metrics: + // + // * GroupInServiceCapacity + // + // * GroupPendingCapacity + // + // * GroupStandbyCapacity + // + // * GroupTerminatingCapacity + // + // * GroupTotalCapacity + // + // If you omit this parameter, all metrics are enabled. Metrics []*string `type:"list"` } @@ -9356,6 +9947,16 @@ type EnabledMetric struct { // * GroupTerminatingInstances // // * GroupTotalInstances + // + // * GroupInServiceCapacity + // + // * GroupPendingCapacity + // + // * GroupStandbyCapacity + // + // * GroupTerminatingCapacity + // + // * GroupTotalCapacity Metric *string `min:"1" type:"string"` } @@ -9477,16 +10078,14 @@ type ExecutePolicyInput struct { // The breach threshold for the alarm. // - // Conditional: This parameter is required if the policy type is StepScaling - // and not supported otherwise. + // Required if the policy type is StepScaling and not supported otherwise. BreachThreshold *float64 `type:"double"` // Indicates whether Amazon EC2 Auto Scaling waits for the cooldown period to // complete before executing the policy. // - // This parameter is not supported if the policy type is StepScaling or TargetTrackingScaling. - // - // For more information, see Scaling Cooldowns (https://docs.aws.amazon.com/autoscaling/ec2/userguide/Cooldown.html) + // Valid only if the policy type is SimpleScaling. For more information, see + // Scaling Cooldowns for Amazon EC2 Auto Scaling (https://docs.aws.amazon.com/autoscaling/ec2/userguide/Cooldown.html) // in the Amazon EC2 Auto Scaling User Guide. HonorCooldown *bool `type:"boolean"` @@ -9499,8 +10098,7 @@ type ExecutePolicyInput struct { // If you specify a metric value that doesn't correspond to a step adjustment // for the policy, the call returns an error. // - // Conditional: This parameter is required if the policy type is StepScaling - // and not supported otherwise. + // Required if the policy type is StepScaling and not supported otherwise. MetricValue *float64 `type:"double"` // The name or ARN of the policy. @@ -9699,15 +10297,19 @@ func (s *FailedScheduledUpdateGroupActionRequest) SetScheduledActionName(v strin return s } -// Describes a filter. +// Describes a filter that is used to return a more specific list of results +// when describing tags. +// +// For more information, see Tagging Auto Scaling Groups and Instances (https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html) +// in the Amazon EC2 Auto Scaling User Guide. type Filter struct { _ struct{} `type:"structure"` - // The name of the filter. The valid values are: "auto-scaling-group", "key", - // "value", and "propagate-at-launch". + // The name of the filter. The valid values are: auto-scaling-group, key, value, + // and propagate-at-launch. Name *string `type:"string"` - // The value of the filter. + // One or more filter values. Filter values are case-sensitive. Values []*string `type:"list"` } @@ -9755,8 +10357,7 @@ type Group struct { // CreatedTime is a required field CreatedTime *time.Time `type:"timestamp" required:"true"` - // The amount of time, in seconds, after a scaling activity completes before - // another scaling activity can start. + // The duration of the default cooldown period, in seconds. // // DefaultCooldown is a required field DefaultCooldown *int64 `type:"integer" required:"true"` @@ -9795,7 +10396,7 @@ type Group struct { // The maximum amount of time, in seconds, that an instance can be in service. // - // Valid Range: Minimum value of 604800. + // Valid Range: Minimum value of 0. MaxInstanceLifetime *int64 `type:"integer"` // The maximum size of the group. @@ -9822,7 +10423,8 @@ type Group struct { // group uses to call other AWS services on your behalf. ServiceLinkedRoleARN *string `min:"1" type:"string"` - // The current state of the group when DeleteAutoScalingGroup is in progress. + // The current state of the group when the DeleteAutoScalingGroup operation + // is in progress. Status *string `min:"1" type:"string"` // The suspended processes associated with the group. @@ -10246,6 +10848,84 @@ func (s *InstanceDetails) SetWeightedCapacity(v string) *InstanceDetails { return s } +// The metadata options for the instances. For more information, see Instance +// Metadata and User Data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) +// in the Amazon EC2 User Guide for Linux Instances. +type InstanceMetadataOptions struct { + _ struct{} `type:"structure"` + + // This parameter enables or disables the HTTP metadata endpoint on your instances. + // If the parameter is not specified, the default state is enabled. + // + // If you specify a value of disabled, you will not be able to access your instance + // metadata. + HttpEndpoint *string `type:"string" enum:"InstanceMetadataEndpointState"` + + // The desired HTTP PUT response hop limit for instance metadata requests. The + // larger the number, the further instance metadata requests can travel. + // + // Default: 1 + // + // Possible values: Integers from 1 to 64 + HttpPutResponseHopLimit *int64 `min:"1" type:"integer"` + + // The state of token usage for your instance metadata requests. If the parameter + // is not specified in the request, the default state is optional. + // + // If the state is optional, you can choose to retrieve instance metadata with + // or without a signed token header on your request. If you retrieve the IAM + // role credentials without a token, the version 1.0 role credentials are returned. + // If you retrieve the IAM role credentials using a valid signed token, the + // version 2.0 role credentials are returned. + // + // If the state is required, you must send a signed token header with any instance + // metadata retrieval requests. In this state, retrieving the IAM role credentials + // always returns the version 2.0 credentials; the version 1.0 credentials are + // not available. + HttpTokens *string `type:"string" enum:"InstanceMetadataHttpTokensState"` +} + +// String returns the string representation +func (s InstanceMetadataOptions) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InstanceMetadataOptions) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *InstanceMetadataOptions) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InstanceMetadataOptions"} + if s.HttpPutResponseHopLimit != nil && *s.HttpPutResponseHopLimit < 1 { + invalidParams.Add(request.NewErrParamMinValue("HttpPutResponseHopLimit", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetHttpEndpoint sets the HttpEndpoint field's value. +func (s *InstanceMetadataOptions) SetHttpEndpoint(v string) *InstanceMetadataOptions { + s.HttpEndpoint = &v + return s +} + +// SetHttpPutResponseHopLimit sets the HttpPutResponseHopLimit field's value. +func (s *InstanceMetadataOptions) SetHttpPutResponseHopLimit(v int64) *InstanceMetadataOptions { + s.HttpPutResponseHopLimit = &v + return s +} + +// SetHttpTokens sets the HttpTokens field's value. +func (s *InstanceMetadataOptions) SetHttpTokens(v string) *InstanceMetadataOptions { + s.HttpTokens = &v + return s +} + // Describes whether detailed monitoring is enabled for the Auto Scaling instances. type InstanceMonitoring struct { _ struct{} `type:"structure"` @@ -10270,7 +10950,114 @@ func (s *InstanceMonitoring) SetEnabled(v bool) *InstanceMonitoring { return s } -// Describes an instances distribution for an Auto Scaling group with MixedInstancesPolicy. +// Describes an instance refresh for an Auto Scaling group. +type InstanceRefresh struct { + _ struct{} `type:"structure"` + + // The name of the Auto Scaling group. + AutoScalingGroupName *string `min:"1" type:"string"` + + // The date and time at which the instance refresh ended. + EndTime *time.Time `type:"timestamp"` + + // The instance refresh ID. + InstanceRefreshId *string `min:"1" type:"string"` + + // The number of instances remaining to update before the instance refresh is + // complete. + InstancesToUpdate *int64 `type:"integer"` + + // The percentage of the instance refresh that is complete. For each instance + // replacement, Amazon EC2 Auto Scaling tracks the instance's health status + // and warm-up time. When the instance's health status changes to healthy and + // the specified warm-up time passes, the instance is considered updated and + // added to the percentage complete. + PercentageComplete *int64 `type:"integer"` + + // The date and time at which the instance refresh began. + StartTime *time.Time `type:"timestamp"` + + // The current status for the instance refresh operation: + // + // * Pending - The request was created, but the operation has not started. + // + // * InProgress - The operation is in progress. + // + // * Successful - The operation completed successfully. + // + // * Failed - The operation failed to complete. You can troubleshoot using + // the status reason and the scaling activities. + // + // * Cancelling - An ongoing operation is being cancelled. Cancellation does + // not roll back any replacements that have already been completed, but it + // prevents new replacements from being started. + // + // * Cancelled - The operation is cancelled. + Status *string `type:"string" enum:"InstanceRefreshStatus"` + + // Provides more details about the current status of the instance refresh. + StatusReason *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s InstanceRefresh) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InstanceRefresh) GoString() string { + return s.String() +} + +// SetAutoScalingGroupName sets the AutoScalingGroupName field's value. +func (s *InstanceRefresh) SetAutoScalingGroupName(v string) *InstanceRefresh { + s.AutoScalingGroupName = &v + return s +} + +// SetEndTime sets the EndTime field's value. +func (s *InstanceRefresh) SetEndTime(v time.Time) *InstanceRefresh { + s.EndTime = &v + return s +} + +// SetInstanceRefreshId sets the InstanceRefreshId field's value. +func (s *InstanceRefresh) SetInstanceRefreshId(v string) *InstanceRefresh { + s.InstanceRefreshId = &v + return s +} + +// SetInstancesToUpdate sets the InstancesToUpdate field's value. +func (s *InstanceRefresh) SetInstancesToUpdate(v int64) *InstanceRefresh { + s.InstancesToUpdate = &v + return s +} + +// SetPercentageComplete sets the PercentageComplete field's value. +func (s *InstanceRefresh) SetPercentageComplete(v int64) *InstanceRefresh { + s.PercentageComplete = &v + return s +} + +// SetStartTime sets the StartTime field's value. +func (s *InstanceRefresh) SetStartTime(v time.Time) *InstanceRefresh { + s.StartTime = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *InstanceRefresh) SetStatus(v string) *InstanceRefresh { + s.Status = &v + return s +} + +// SetStatusReason sets the StatusReason field's value. +func (s *InstanceRefresh) SetStatusReason(v string) *InstanceRefresh { + s.StatusReason = &v + return s +} + +// Describes an instances distribution for an Auto Scaling group with a MixedInstancesPolicy. // // The instances distribution specifies the distribution of On-Demand Instances // and Spot Instances, the maximum price to pay for Spot Instances, and how @@ -10501,6 +11288,11 @@ type LaunchConfiguration struct { // LaunchConfigurationName is a required field LaunchConfigurationName *string `min:"1" type:"string" required:"true"` + // The metadata options for the instances. For more information, see Instance + // Metadata and User Data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) + // in the Amazon EC2 User Guide for Linux Instances. + MetadataOptions *InstanceMetadataOptions `type:"structure"` + // The tenancy of the instance, either default or dedicated. An instance with // dedicated tenancy runs on isolated, single-tenant hardware and can only be // launched into a VPC. @@ -10629,6 +11421,12 @@ func (s *LaunchConfiguration) SetLaunchConfigurationName(v string) *LaunchConfig return s } +// SetMetadataOptions sets the MetadataOptions field's value. +func (s *LaunchConfiguration) SetMetadataOptions(v *InstanceMetadataOptions) *LaunchConfiguration { + s.MetadataOptions = v + return s +} + // SetPlacementTenancy sets the PlacementTenancy field's value. func (s *LaunchConfiguration) SetPlacementTenancy(v string) *LaunchConfiguration { s.PlacementTenancy = &v @@ -10676,9 +11474,12 @@ type LaunchTemplate struct { // or launch template name in the request. LaunchTemplateSpecification *LaunchTemplateSpecification `type:"structure"` - // An optional setting. Any parameters that you specify override the same parameters - // in the launch template. Currently, the only supported override is instance - // type. You can specify between 1 and 20 instance types. + // Any parameters that you specify override the same parameters in the launch + // template. Currently, the only supported override is instance type. You can + // specify between 1 and 20 instance types. + // + // If not provided, Amazon EC2 Auto Scaling will use the instance type specified + // in the launch template to launch instances. Overrides []*LaunchTemplateOverrides `type:"list"` } @@ -10729,11 +11530,16 @@ func (s *LaunchTemplate) SetOverrides(v []*LaunchTemplateOverrides) *LaunchTempl return s } -// Describes an override for a launch template. +// Describes an override for a launch template. Currently, the only supported +// override is instance type. +// +// The maximum number of instance type overrides that can be associated with +// an Auto Scaling group is 20. type LaunchTemplateOverrides struct { _ struct{} `type:"structure"` - // The instance type. + // The instance type. You must use an instance type that is supported in your + // requested Region and Availability Zones. // // For information about available instance types, see Available Instance Types // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes) @@ -10792,7 +11598,8 @@ func (s *LaunchTemplateOverrides) SetWeightedCapacity(v string) *LaunchTemplateO return s } -// Describes a launch template and the launch template version. +// Describes the Amazon EC2 launch template and the launch template version +// that can be used by an Auto Scaling group to configure Amazon EC2 instances. // // The launch template that is specified must be configured for use with an // Auto Scaling group. For more information, see Creating a Launch Template @@ -10801,19 +11608,34 @@ func (s *LaunchTemplateOverrides) SetWeightedCapacity(v string) *LaunchTemplateO type LaunchTemplateSpecification struct { _ struct{} `type:"structure"` - // The ID of the launch template. You must specify either a template ID or a - // template name. + // The ID of the launch template. To get the template ID, use the Amazon EC2 + // DescribeLaunchTemplates (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeLaunchTemplates.html) + // API operation. New launch templates can be created using the Amazon EC2 CreateLaunchTemplate + // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateLaunchTemplate.html) + // API. + // + // You must specify either a template ID or a template name. LaunchTemplateId *string `min:"1" type:"string"` - // The name of the launch template. You must specify either a template name - // or a template ID. + // The name of the launch template. To get the template name, use the Amazon + // EC2 DescribeLaunchTemplates (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeLaunchTemplates.html) + // API operation. New launch templates can be created using the Amazon EC2 CreateLaunchTemplate + // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateLaunchTemplate.html) + // API. + // + // You must specify either a template ID or a template name. LaunchTemplateName *string `min:"3" type:"string"` - // The version number, $Latest, or $Default. If the value is $Latest, Amazon - // EC2 Auto Scaling selects the latest version of the launch template when launching - // instances. If the value is $Default, Amazon EC2 Auto Scaling selects the - // default version of the launch template when launching instances. The default - // value is $Default. + // The version number, $Latest, or $Default. To get the version number, use + // the Amazon EC2 DescribeLaunchTemplateVersions (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeLaunchTemplateVersions.html) + // API operation. New launch template versions can be created using the Amazon + // EC2 CreateLaunchTemplateVersion (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateLaunchTemplateVersion.html) + // API. + // + // If the value is $Latest, Amazon EC2 Auto Scaling selects the latest version + // of the launch template when launching instances. If the value is $Default, + // Amazon EC2 Auto Scaling selects the default version of the launch template + // when launching instances. The default value is $Default. Version *string `min:"1" type:"string"` } @@ -10866,7 +11688,6 @@ func (s *LaunchTemplateSpecification) SetVersion(v string) *LaunchTemplateSpecif // Describes a lifecycle hook, which tells Amazon EC2 Auto Scaling that you // want to perform an action whenever it launches instances or terminates instances. -// Used in response to DescribeLifecycleHooks. type LifecycleHook struct { _ struct{} `type:"structure"` @@ -10977,7 +11798,8 @@ func (s *LifecycleHook) SetRoleARN(v string) *LifecycleHook { return s } -// Describes a lifecycle hook. Used in combination with CreateAutoScalingGroup. +// Describes information used to specify a lifecycle hook for an Auto Scaling +// group. // // A lifecycle hook tells Amazon EC2 Auto Scaling to perform an action on an // instance when the instance launches (before it is put into service) or as @@ -10998,18 +11820,12 @@ func (s *LifecycleHook) SetRoleARN(v string) *LifecycleHook { // launch or terminate. // // If you need more time, record the lifecycle action heartbeat to keep the -// instance in a pending state using RecordLifecycleActionHeartbeat. +// instance in a pending state. // -// If you finish before the timeout period ends, complete the lifecycle action -// using CompleteLifecycleAction. +// If you finish before the timeout period ends, complete the lifecycle action. // // For more information, see Amazon EC2 Auto Scaling Lifecycle Hooks (https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html) // in the Amazon EC2 Auto Scaling User Guide. -// -// You can view the lifecycle hooks for an Auto Scaling group using DescribeLifecycleHooks. -// You can modify an existing lifecycle hook or create new lifecycle hooks using -// PutLifecycleHook. If you are no longer using a lifecycle hook, you can delete -// it using DeleteLifecycleHook. type LifecycleHookSpecification struct { _ struct{} `type:"structure"` @@ -11268,6 +12084,16 @@ type MetricCollectionType struct { // * GroupTerminatingInstances // // * GroupTotalInstances + // + // * GroupInServiceCapacity + // + // * GroupPendingCapacity + // + // * GroupStandbyCapacity + // + // * GroupTerminatingCapacity + // + // * GroupTotalCapacity Metric *string `min:"1" type:"string"` } @@ -11374,7 +12200,8 @@ func (s *MetricGranularityType) SetGranularity(v string) *MetricGranularityType // You can create a mixed instances policy for a new Auto Scaling group, or // you can create it for an existing group by updating the group to specify // MixedInstancesPolicy as the top-level parameter instead of a launch configuration -// or template. For more information, see CreateAutoScalingGroup and UpdateAutoScalingGroup. +// or launch template. For more information, see CreateAutoScalingGroup and +// UpdateAutoScalingGroup. type MixedInstancesPolicy struct { _ struct{} `type:"structure"` @@ -11386,7 +12213,7 @@ type MixedInstancesPolicy struct { // The launch template and instance types (overrides). // - // This parameter must be specified when creating a mixed instances policy. + // Required when creating a mixed instances policy. LaunchTemplate *LaunchTemplate `type:"structure"` } @@ -11506,7 +12333,9 @@ type PredefinedMetricSpecification struct { // a resource label unless the metric type is ALBRequestCountPerTarget and there // is a target group attached to the Auto Scaling group. // - // The format is app/load-balancer-name/load-balancer-id/targetgroup/target-group-name/target-group-id + // Elastic Load Balancing sends data about your load balancers to Amazon CloudWatch. + // CloudWatch collects the data and specifies the format to use to access the + // data. The format is app/load-balancer-name/load-balancer-id/targetgroup/target-group-name/target-group-id // , where // // * app/load-balancer-name/load-balancer-id is the final portion of the @@ -11514,6 +12343,12 @@ type PredefinedMetricSpecification struct { // // * targetgroup/target-group-name/target-group-id is the final portion of // the target group ARN. + // + // To find the ARN for an Application Load Balancer, use the DescribeLoadBalancers + // (https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeLoadBalancers.html) + // API operation. To find the ARN for the target group, use the DescribeTargetGroups + // (https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeTargetGroups.html) + // API operation. ResourceLabel *string `min:"1" type:"string"` } @@ -11576,6 +12411,8 @@ type ProcessType struct { // // * HealthCheck // + // * InstanceRefresh + // // * ReplaceUnhealthy // // * ScheduledActions @@ -11619,7 +12456,7 @@ type PutLifecycleHookInput struct { // // If the lifecycle hook times out, Amazon EC2 Auto Scaling performs the action // that you specified in the DefaultResult parameter. You can prevent the lifecycle - // hook from timing out by calling RecordLifecycleActionHeartbeat. + // hook from timing out by calling the RecordLifecycleActionHeartbeat API. HeartbeatTimeout *int64 `type:"integer"` // The name of the lifecycle hook. @@ -11634,8 +12471,7 @@ type PutLifecycleHookInput struct { // // * autoscaling:EC2_INSTANCE_TERMINATING // - // Conditional: This parameter is required for new lifecycle hooks, but optional - // when updating existing hooks. + // Required for new lifecycle hooks, but optional when updating existing hooks. LifecycleTransition *string `type:"string"` // Additional information that you want to include any time Amazon EC2 Auto @@ -11661,8 +12497,7 @@ type PutLifecycleHookInput struct { // the specified notification target, for example, an Amazon SNS topic or an // Amazon SQS queue. // - // Conditional: This parameter is required for new lifecycle hooks, but optional - // when updating existing hooks. + // Required for new lifecycle hooks, but optional when updating existing hooks. RoleARN *string `min:"1" type:"string"` } @@ -11774,8 +12609,9 @@ type PutNotificationConfigurationInput struct { // AutoScalingGroupName is a required field AutoScalingGroupName *string `min:"1" type:"string" required:"true"` - // The type of event that causes the notification to be sent. For more information - // about notification types supported by Amazon EC2 Auto Scaling, see DescribeAutoScalingNotificationTypes. + // The type of event that causes the notification to be sent. To query the notification + // types supported by Amazon EC2 Auto Scaling, call the DescribeAutoScalingNotificationTypes + // API. // // NotificationTypes is a required field NotificationTypes []*string `type:"list" required:"true"` @@ -11857,11 +12693,11 @@ func (s PutNotificationConfigurationOutput) GoString() string { type PutScalingPolicyInput struct { _ struct{} `type:"structure"` - // Specifies whether the ScalingAdjustment parameter is an absolute number or - // a percentage of the current capacity. The valid values are ChangeInCapacity, - // ExactCapacity, and PercentChangeInCapacity. + // Specifies how the scaling adjustment is interpreted (for example, an absolute + // number or a percentage). The valid values are ChangeInCapacity, ExactCapacity, + // and PercentChangeInCapacity. // - // Valid only if the policy type is StepScaling or SimpleScaling. For more information, + // Required if the policy type is StepScaling or SimpleScaling. For more information, // see Scaling Adjustment Types (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html#as-scaling-adjustment) // in the Amazon EC2 Auto Scaling User Guide. AdjustmentType *string `min:"1" type:"string"` @@ -11871,12 +12707,12 @@ type PutScalingPolicyInput struct { // AutoScalingGroupName is a required field AutoScalingGroupName *string `min:"1" type:"string" required:"true"` - // The amount of time, in seconds, after a scaling activity completes before - // any further dynamic scaling activities can start. If this parameter is not - // specified, the default cooldown period for the group applies. + // The duration of the policy's cooldown period, in seconds. When a cooldown + // period is specified here, it overrides the default cooldown period defined + // for the Auto Scaling group. // // Valid only if the policy type is SimpleScaling. For more information, see - // Scaling Cooldowns (https://docs.aws.amazon.com/autoscaling/ec2/userguide/Cooldown.html) + // Scaling Cooldowns for Amazon EC2 Auto Scaling (https://docs.aws.amazon.com/autoscaling/ec2/userguide/Cooldown.html) // in the Amazon EC2 Auto Scaling User Guide. Cooldown *int64 `type:"integer"` @@ -11887,10 +12723,10 @@ type PutScalingPolicyInput struct { Enabled *bool `type:"boolean"` // The estimated time, in seconds, until a newly launched instance can contribute - // to the CloudWatch metrics. The default is to use the value specified for - // the default cooldown period for the group. + // to the CloudWatch metrics. If not provided, the default is to use the value + // from the default cooldown period for the Auto Scaling group. // - // Valid only if the policy type is StepScaling or TargetTrackingScaling. + // Valid only if the policy type is TargetTrackingScaling or StepScaling. EstimatedInstanceWarmup *int64 `type:"integer"` // The aggregation type for the CloudWatch metrics. The valid values are Minimum, @@ -11900,19 +12736,19 @@ type PutScalingPolicyInput struct { // Valid only if the policy type is StepScaling. MetricAggregationType *string `min:"1" type:"string"` - // The minimum number of instances to scale. If the value of AdjustmentType - // is PercentChangeInCapacity, the scaling policy changes the DesiredCapacity - // of the Auto Scaling group by at least this many instances. Otherwise, the - // error is ValidationError. + // The minimum value to scale by when the adjustment type is PercentChangeInCapacity. + // For example, suppose that you create a step scaling policy to scale out an + // Auto Scaling group by 25 percent and you specify a MinAdjustmentMagnitude + // of 2. If the group has 4 instances and the scaling policy is performed, 25 + // percent of 4 is 1. However, because you specified a MinAdjustmentMagnitude + // of 2, Amazon EC2 Auto Scaling scales out the group by 2 instances. // - // This property replaces the MinAdjustmentStep property. For example, suppose - // that you create a step scaling policy to scale out an Auto Scaling group - // by 25 percent and you specify a MinAdjustmentMagnitude of 2. If the group - // has 4 instances and the scaling policy is performed, 25 percent of 4 is 1. - // However, because you specified a MinAdjustmentMagnitude of 2, Amazon EC2 - // Auto Scaling scales out the group by 2 instances. + // Valid only if the policy type is StepScaling or SimpleScaling. For more information, + // see Scaling Adjustment Types (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html#as-scaling-adjustment) + // in the Amazon EC2 Auto Scaling User Guide. // - // Valid only if the policy type is SimpleScaling or StepScaling. + // Some Auto Scaling groups use instance weights. In this case, set the MinAdjustmentMagnitude + // to a value that is at least as large as your largest instance weight. MinAdjustmentMagnitude *int64 `type:"integer"` // Available for backward compatibility. Use MinAdjustmentMagnitude instead. @@ -11923,36 +12759,50 @@ type PutScalingPolicyInput struct { // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` - // The policy type. The valid values are SimpleScaling, StepScaling, and TargetTrackingScaling. - // If the policy type is null, the value is treated as SimpleScaling. + // One of the following policy types: + // + // * TargetTrackingScaling + // + // * StepScaling + // + // * SimpleScaling (default) PolicyType *string `min:"1" type:"string"` - // The amount by which a simple scaling policy scales the Auto Scaling group - // in response to an alarm breach. The adjustment is based on the value that - // you specified in the AdjustmentType parameter (either an absolute number - // or a percentage). A positive value adds to the current capacity and a negative - // value subtracts from the current capacity. For exact capacity, you must specify - // a positive value. + // The amount by which to scale, based on the specified adjustment type. A positive + // value adds to the current capacity while a negative number removes from the + // current capacity. For exact capacity, you must specify a positive value. // - // Conditional: If you specify SimpleScaling for the policy type, you must specify - // this parameter. (Not used with any other policy type.) + // Required if the policy type is SimpleScaling. (Not used with any other policy + // type.) ScalingAdjustment *int64 `type:"integer"` // A set of adjustments that enable you to scale based on the size of the alarm // breach. // - // Conditional: If you specify StepScaling for the policy type, you must specify - // this parameter. (Not used with any other policy type.) + // Required if the policy type is StepScaling. (Not used with any other policy + // type.) StepAdjustments []*StepAdjustment `type:"list"` // A target tracking scaling policy. Includes support for predefined or customized // metrics. // + // The following predefined metrics are available: + // + // * ASGAverageCPUUtilization + // + // * ASGAverageNetworkIn + // + // * ASGAverageNetworkOut + // + // * ALBRequestCountPerTarget + // + // If you specify ALBRequestCountPerTarget for the metric, you must specify + // the ResourceLabel parameter with the PredefinedMetricSpecification. + // // For more information, see TargetTrackingConfiguration (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_TargetTrackingConfiguration.html) // in the Amazon EC2 Auto Scaling API Reference. // - // Conditional: If you specify TargetTrackingScaling for the policy type, you - // must specify this parameter. (Not used with any other policy type.) + // Required if the policy type is TargetTrackingScaling. TargetTrackingConfiguration *TargetTrackingConfiguration `type:"structure"` } @@ -12131,17 +12981,19 @@ type PutScheduledUpdateGroupActionInput struct { // AutoScalingGroupName is a required field AutoScalingGroupName *string `min:"1" type:"string" required:"true"` - // The number of EC2 instances that should be running in the Auto Scaling group. + // The desired capacity is the initial capacity of the Auto Scaling group after + // the scheduled action runs and the capacity it attempts to maintain. It can + // scale beyond this capacity if you add more scaling conditions. DesiredCapacity *int64 `type:"integer"` // The date and time for the recurring schedule to end. Amazon EC2 Auto Scaling // does not perform the action after this time. EndTime *time.Time `type:"timestamp"` - // The maximum number of instances in the Auto Scaling group. + // The maximum size of the Auto Scaling group. MaxSize *int64 `type:"integer"` - // The minimum number of instances in the Auto Scaling group. + // The minimum size of the Auto Scaling group. MinSize *int64 `type:"integer"` // The recurring schedule for this action, in Unix cron syntax format. This @@ -12375,6 +13227,45 @@ func (s RecordLifecycleActionHeartbeatOutput) GoString() string { return s.String() } +// Describes information used to start an instance refresh. +type RefreshPreferences struct { + _ struct{} `type:"structure"` + + // The number of seconds until a newly launched instance is configured and ready + // to use. During this time, Amazon EC2 Auto Scaling does not immediately move + // on to the next replacement. The default is to use the value for the health + // check grace period defined for the group. + InstanceWarmup *int64 `type:"integer"` + + // The amount of capacity in the Auto Scaling group that must remain healthy + // during an instance refresh to allow the operation to continue, as a percentage + // of the desired capacity of the Auto Scaling group (rounded up to the nearest + // integer). The default is 90. + MinHealthyPercentage *int64 `type:"integer"` +} + +// String returns the string representation +func (s RefreshPreferences) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RefreshPreferences) GoString() string { + return s.String() +} + +// SetInstanceWarmup sets the InstanceWarmup field's value. +func (s *RefreshPreferences) SetInstanceWarmup(v int64) *RefreshPreferences { + s.InstanceWarmup = &v + return s +} + +// SetMinHealthyPercentage sets the MinHealthyPercentage field's value. +func (s *RefreshPreferences) SetMinHealthyPercentage(v int64) *RefreshPreferences { + s.MinHealthyPercentage = &v + return s +} + type ResumeProcessesOutput struct { _ struct{} `type:"structure"` } @@ -12393,8 +13284,9 @@ func (s ResumeProcessesOutput) GoString() string { type ScalingPolicy struct { _ struct{} `type:"structure"` - // The adjustment type, which specifies how ScalingAdjustment is interpreted. - // The valid values are ChangeInCapacity, ExactCapacity, and PercentChangeInCapacity. + // Specifies how the scaling adjustment is interpreted (for example, an absolute + // number or a percentage). The valid values are ChangeInCapacity, ExactCapacity, + // and PercentChangeInCapacity. AdjustmentType *string `min:"1" type:"string"` // The CloudWatch alarms related to the policy. @@ -12403,8 +13295,7 @@ type ScalingPolicy struct { // The name of the Auto Scaling group. AutoScalingGroupName *string `min:"1" type:"string"` - // The amount of time, in seconds, after a scaling activity completes before - // any further dynamic scaling activities can start. + // The duration of the policy's cooldown period, in seconds. Cooldown *int64 `type:"integer"` // Indicates whether the policy is enabled (true) or disabled (false). @@ -12418,10 +13309,7 @@ type ScalingPolicy struct { // Maximum, and Average. MetricAggregationType *string `min:"1" type:"string"` - // The minimum number of instances to scale. If the value of AdjustmentType - // is PercentChangeInCapacity, the scaling policy changes the DesiredCapacity - // of the Auto Scaling group by at least this many instances. Otherwise, the - // error is ValidationError. + // The minimum value to scale by when the adjustment type is PercentChangeInCapacity. MinAdjustmentMagnitude *int64 `type:"integer"` // Available for backward compatibility. Use MinAdjustmentMagnitude instead. @@ -12433,7 +13321,17 @@ type ScalingPolicy struct { // The name of the scaling policy. PolicyName *string `min:"1" type:"string"` - // The policy type. The valid values are SimpleScaling, StepScaling, and TargetTrackingScaling. + // One of the following policy types: + // + // * TargetTrackingScaling + // + // * StepScaling + // + // * SimpleScaling (default) + // + // For more information, see Target Tracking Scaling Policies (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-target-tracking.html) + // and Step and Simple Scaling Policies (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html) + // in the Amazon EC2 Auto Scaling User Guide. PolicyType *string `min:"1" type:"string"` // The amount by which to scale, based on the specified adjustment type. A positive @@ -12557,24 +13455,27 @@ type ScalingProcessQuery struct { // AutoScalingGroupName is a required field AutoScalingGroupName *string `min:"1" type:"string" required:"true"` - // One or more of the following processes. If you omit this parameter, all processes - // are specified. + // One or more of the following processes: // // * Launch // // * Terminate // - // * HealthCheck + // * AddToLoadBalancer // - // * ReplaceUnhealthy + // * AlarmNotification // // * AZRebalance // - // * AlarmNotification + // * HealthCheck + // + // * InstanceRefresh + // + // * ReplaceUnhealthy // // * ScheduledActions // - // * AddToLoadBalancer + // If you omit this parameter, all processes are specified. ScalingProcesses []*string `type:"list"` } @@ -12616,24 +13517,25 @@ func (s *ScalingProcessQuery) SetScalingProcesses(v []*string) *ScalingProcessQu return s } -// Describes a scheduled scaling action. Used in response to DescribeScheduledActions. +// Describes a scheduled scaling action. type ScheduledUpdateGroupAction struct { _ struct{} `type:"structure"` // The name of the Auto Scaling group. AutoScalingGroupName *string `min:"1" type:"string"` - // The number of instances you prefer to maintain in the group. + // The desired capacity is the initial capacity of the Auto Scaling group after + // the scheduled action runs and the capacity it attempts to maintain. DesiredCapacity *int64 `type:"integer"` // The date and time in UTC for the recurring schedule to end. For example, // "2019-06-01T00:00:00Z". EndTime *time.Time `type:"timestamp"` - // The maximum number of instances in the Auto Scaling group. + // The maximum size of the Auto Scaling group. MaxSize *int64 `type:"integer"` - // The minimum number of instances in the Auto Scaling group. + // The minimum size of the Auto Scaling group. MinSize *int64 `type:"integer"` // The recurring schedule for the action, in Unix cron syntax format. @@ -12725,25 +13627,26 @@ func (s *ScheduledUpdateGroupAction) SetTime(v time.Time) *ScheduledUpdateGroupA return s } -// Describes one or more scheduled scaling action updates for a specified Auto -// Scaling group. Used in combination with BatchPutScheduledUpdateGroupAction. +// Describes information used for one or more scheduled scaling action updates +// in a BatchPutScheduledUpdateGroupAction operation. // // When updating a scheduled scaling action, all optional parameters are left // unchanged if not specified. type ScheduledUpdateGroupActionRequest struct { _ struct{} `type:"structure"` - // The number of EC2 instances that should be running in the group. + // The desired capacity is the initial capacity of the Auto Scaling group after + // the scheduled action runs and the capacity it attempts to maintain. DesiredCapacity *int64 `type:"integer"` // The date and time for the recurring schedule to end. Amazon EC2 Auto Scaling // does not perform the action after this time. EndTime *time.Time `type:"timestamp"` - // The maximum number of instances in the Auto Scaling group. + // The maximum size of the Auto Scaling group. MaxSize *int64 `type:"integer"` - // The minimum number of instances in the Auto Scaling group. + // The minimum size of the Auto Scaling group. MinSize *int64 `type:"integer"` // The recurring schedule for the action, in Unix cron syntax format. This format @@ -12851,7 +13754,8 @@ type SetDesiredCapacityInput struct { // AutoScalingGroupName is a required field AutoScalingGroupName *string `min:"1" type:"string" required:"true"` - // The number of EC2 instances that should be running in the Auto Scaling group. + // The desired capacity is the initial capacity of the Auto Scaling group after + // this operation completes and the capacity it attempts to maintain. // // DesiredCapacity is a required field DesiredCapacity *int64 `type:"integer" required:"true"` @@ -12944,7 +13848,9 @@ type SetInstanceHealthInput struct { // Set this to False, to have the call not respect the grace period associated // with the group. // - // For more information about the health check grace period, see CreateAutoScalingGroup. + // For more information about the health check grace period, see CreateAutoScalingGroup + // (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_CreateAutoScalingGroup.html) + // in the Amazon EC2 Auto Scaling API Reference. ShouldRespectGracePeriod *bool `type:"boolean"` } @@ -13096,9 +14002,103 @@ func (s SetInstanceProtectionOutput) GoString() string { return s.String() } -// Describes an adjustment based on the difference between the value of the -// aggregated CloudWatch metric and the breach threshold that you've defined -// for the alarm. Used in combination with PutScalingPolicy. +type StartInstanceRefreshInput struct { + _ struct{} `type:"structure"` + + // The name of the Auto Scaling group. + // + // AutoScalingGroupName is a required field + AutoScalingGroupName *string `min:"1" type:"string" required:"true"` + + // Set of preferences associated with the instance refresh request. + // + // If not provided, the default values are used. For MinHealthyPercentage, the + // default value is 90. For InstanceWarmup, the default is to use the value + // specified for the health check grace period for the Auto Scaling group. + // + // For more information, see RefreshPreferences (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_RefreshPreferences.html) + // in the Amazon EC2 Auto Scaling API Reference. + Preferences *RefreshPreferences `type:"structure"` + + // The strategy to use for the instance refresh. The only valid value is Rolling. + // + // A rolling update is an update that is applied to all instances in an Auto + // Scaling group until all instances have been updated. A rolling update can + // fail due to failed health checks or if instances are on standby or are protected + // from scale in. If the rolling update process fails, any instances that were + // already replaced are not rolled back to their previous configuration. + Strategy *string `type:"string" enum:"RefreshStrategy"` +} + +// String returns the string representation +func (s StartInstanceRefreshInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StartInstanceRefreshInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StartInstanceRefreshInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StartInstanceRefreshInput"} + if s.AutoScalingGroupName == nil { + invalidParams.Add(request.NewErrParamRequired("AutoScalingGroupName")) + } + if s.AutoScalingGroupName != nil && len(*s.AutoScalingGroupName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AutoScalingGroupName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAutoScalingGroupName sets the AutoScalingGroupName field's value. +func (s *StartInstanceRefreshInput) SetAutoScalingGroupName(v string) *StartInstanceRefreshInput { + s.AutoScalingGroupName = &v + return s +} + +// SetPreferences sets the Preferences field's value. +func (s *StartInstanceRefreshInput) SetPreferences(v *RefreshPreferences) *StartInstanceRefreshInput { + s.Preferences = v + return s +} + +// SetStrategy sets the Strategy field's value. +func (s *StartInstanceRefreshInput) SetStrategy(v string) *StartInstanceRefreshInput { + s.Strategy = &v + return s +} + +type StartInstanceRefreshOutput struct { + _ struct{} `type:"structure"` + + // A unique ID for tracking the progress of the request. + InstanceRefreshId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s StartInstanceRefreshOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StartInstanceRefreshOutput) GoString() string { + return s.String() +} + +// SetInstanceRefreshId sets the InstanceRefreshId field's value. +func (s *StartInstanceRefreshOutput) SetInstanceRefreshId(v string) *StartInstanceRefreshOutput { + s.InstanceRefreshId = &v + return s +} + +// Describes information used to create a step adjustment for a step scaling +// policy. // // For the following examples, suppose that you have an alarm with a breach // threshold of 50: @@ -13124,6 +14124,9 @@ func (s SetInstanceProtectionOutput) GoString() string { // with a null upper bound. // // * The upper and lower bound can't be null in the same step adjustment. +// +// For more information, see Step Adjustments (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html#as-scaling-steps) +// in the Amazon EC2 Auto Scaling User Guide. type StepAdjustment struct { _ struct{} `type:"structure"` @@ -13207,8 +14210,10 @@ func (s SuspendProcessesOutput) GoString() string { return s.String() } -// Describes an automatic scaling process that has been suspended. For more -// information, see ProcessType. +// Describes an automatic scaling process that has been suspended. +// +// For more information, see Scaling Processes (https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html#process-types) +// in the Amazon EC2 Auto Scaling User Guide. type SuspendedProcess struct { _ struct{} `type:"structure"` @@ -13554,16 +14559,17 @@ type UpdateAutoScalingGroupInput struct { AvailabilityZones []*string `min:"1" type:"list"` // The amount of time, in seconds, after a scaling activity completes before - // another scaling activity can start. The default value is 300. This cooldown - // period is not used when a scaling-specific cooldown is specified. + // another scaling activity can start. The default value is 300. // - // Cooldown periods are not supported for target tracking scaling policies, - // step scaling policies, or scheduled scaling. For more information, see Scaling - // Cooldowns (https://docs.aws.amazon.com/autoscaling/ec2/userguide/Cooldown.html) + // This setting applies when using simple scaling policies, but not when using + // other scaling policies or scheduled scaling. For more information, see Scaling + // Cooldowns for Amazon EC2 Auto Scaling (https://docs.aws.amazon.com/autoscaling/ec2/userguide/Cooldown.html) // in the Amazon EC2 Auto Scaling User Guide. DefaultCooldown *int64 `type:"integer"` - // The number of EC2 instances that should be running in the Auto Scaling group. + // The desired capacity is the initial capacity of the Auto Scaling group after + // this operation completes and the capacity it attempts to maintain. + // // This number must be greater than or equal to the minimum size of the group // and less than or equal to the maximum size of the group. DesiredCapacity *int64 `type:"integer"` @@ -13575,7 +14581,7 @@ type UpdateAutoScalingGroupInput struct { // For more information, see Health Check Grace Period (https://docs.aws.amazon.com/autoscaling/ec2/userguide/healthcheck.html#health-check-grace-period) // in the Amazon EC2 Auto Scaling User Guide. // - // Conditional: This parameter is required if you are adding an ELB health check. + // Required if you are adding an ELB health check. HealthCheckGracePeriod *int64 `type:"integer"` // The service to use for the health checks. The valid values are EC2 and ELB. @@ -13597,15 +14603,26 @@ type UpdateAutoScalingGroupInput struct { LaunchTemplate *LaunchTemplateSpecification `type:"structure"` // The maximum amount of time, in seconds, that an instance can be in service. + // The default is null. + // + // This parameter is optional, but if you specify a value for it, you must specify + // a value of at least 604,800 seconds (7 days). To clear a previously set value, + // specify a new value of 0. // // For more information, see Replacing Auto Scaling Instances Based on Maximum // Instance Lifetime (https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-max-instance-lifetime.html) // in the Amazon EC2 Auto Scaling User Guide. // - // Valid Range: Minimum value of 604800. + // Valid Range: Minimum value of 0. MaxInstanceLifetime *int64 `type:"integer"` // The maximum size of the Auto Scaling group. + // + // With a mixed instances policy that uses instance weighting, Amazon EC2 Auto + // Scaling may need to go above MaxSize to meet your capacity requirements. + // In this event, Amazon EC2 Auto Scaling will never go above MaxSize by more + // than your largest instance weight (weights that define how many units each + // instance contributes to the desired capacity of the group). MaxSize *int64 `type:"integer"` // The minimum size of the Auto Scaling group. @@ -13829,6 +14846,70 @@ func (s UpdateAutoScalingGroupOutput) GoString() string { return s.String() } +const ( + // InstanceMetadataEndpointStateDisabled is a InstanceMetadataEndpointState enum value + InstanceMetadataEndpointStateDisabled = "disabled" + + // InstanceMetadataEndpointStateEnabled is a InstanceMetadataEndpointState enum value + InstanceMetadataEndpointStateEnabled = "enabled" +) + +// InstanceMetadataEndpointState_Values returns all elements of the InstanceMetadataEndpointState enum +func InstanceMetadataEndpointState_Values() []string { + return []string{ + InstanceMetadataEndpointStateDisabled, + InstanceMetadataEndpointStateEnabled, + } +} + +const ( + // InstanceMetadataHttpTokensStateOptional is a InstanceMetadataHttpTokensState enum value + InstanceMetadataHttpTokensStateOptional = "optional" + + // InstanceMetadataHttpTokensStateRequired is a InstanceMetadataHttpTokensState enum value + InstanceMetadataHttpTokensStateRequired = "required" +) + +// InstanceMetadataHttpTokensState_Values returns all elements of the InstanceMetadataHttpTokensState enum +func InstanceMetadataHttpTokensState_Values() []string { + return []string{ + InstanceMetadataHttpTokensStateOptional, + InstanceMetadataHttpTokensStateRequired, + } +} + +const ( + // InstanceRefreshStatusPending is a InstanceRefreshStatus enum value + InstanceRefreshStatusPending = "Pending" + + // InstanceRefreshStatusInProgress is a InstanceRefreshStatus enum value + InstanceRefreshStatusInProgress = "InProgress" + + // InstanceRefreshStatusSuccessful is a InstanceRefreshStatus enum value + InstanceRefreshStatusSuccessful = "Successful" + + // InstanceRefreshStatusFailed is a InstanceRefreshStatus enum value + InstanceRefreshStatusFailed = "Failed" + + // InstanceRefreshStatusCancelling is a InstanceRefreshStatus enum value + InstanceRefreshStatusCancelling = "Cancelling" + + // InstanceRefreshStatusCancelled is a InstanceRefreshStatus enum value + InstanceRefreshStatusCancelled = "Cancelled" +) + +// InstanceRefreshStatus_Values returns all elements of the InstanceRefreshStatus enum +func InstanceRefreshStatus_Values() []string { + return []string{ + InstanceRefreshStatusPending, + InstanceRefreshStatusInProgress, + InstanceRefreshStatusSuccessful, + InstanceRefreshStatusFailed, + InstanceRefreshStatusCancelling, + InstanceRefreshStatusCancelled, + } +} + const ( // LifecycleStatePending is a LifecycleState enum value LifecycleStatePending = "Pending" @@ -13870,6 +14951,25 @@ const ( LifecycleStateStandby = "Standby" ) +// LifecycleState_Values returns all elements of the LifecycleState enum +func LifecycleState_Values() []string { + return []string{ + LifecycleStatePending, + LifecycleStatePendingWait, + LifecycleStatePendingProceed, + LifecycleStateQuarantined, + LifecycleStateInService, + LifecycleStateTerminating, + LifecycleStateTerminatingWait, + LifecycleStateTerminatingProceed, + LifecycleStateTerminated, + LifecycleStateDetaching, + LifecycleStateDetached, + LifecycleStateEnteringStandby, + LifecycleStateStandby, + } +} + const ( // MetricStatisticAverage is a MetricStatistic enum value MetricStatisticAverage = "Average" @@ -13887,6 +14987,17 @@ const ( MetricStatisticSum = "Sum" ) +// MetricStatistic_Values returns all elements of the MetricStatistic enum +func MetricStatistic_Values() []string { + return []string{ + MetricStatisticAverage, + MetricStatisticMinimum, + MetricStatisticMaximum, + MetricStatisticSampleCount, + MetricStatisticSum, + } +} + const ( // MetricTypeAsgaverageCpuutilization is a MetricType enum value MetricTypeAsgaverageCpuutilization = "ASGAverageCPUUtilization" @@ -13901,6 +15012,28 @@ const ( MetricTypeAlbrequestCountPerTarget = "ALBRequestCountPerTarget" ) +// MetricType_Values returns all elements of the MetricType enum +func MetricType_Values() []string { + return []string{ + MetricTypeAsgaverageCpuutilization, + MetricTypeAsgaverageNetworkIn, + MetricTypeAsgaverageNetworkOut, + MetricTypeAlbrequestCountPerTarget, + } +} + +const ( + // RefreshStrategyRolling is a RefreshStrategy enum value + RefreshStrategyRolling = "Rolling" +) + +// RefreshStrategy_Values returns all elements of the RefreshStrategy enum +func RefreshStrategy_Values() []string { + return []string{ + RefreshStrategyRolling, + } +} + const ( // ScalingActivityStatusCodePendingSpotBidPlacement is a ScalingActivityStatusCode enum value ScalingActivityStatusCodePendingSpotBidPlacement = "PendingSpotBidPlacement" @@ -13938,3 +15071,21 @@ const ( // ScalingActivityStatusCodeCancelled is a ScalingActivityStatusCode enum value ScalingActivityStatusCodeCancelled = "Cancelled" ) + +// ScalingActivityStatusCode_Values returns all elements of the ScalingActivityStatusCode enum +func ScalingActivityStatusCode_Values() []string { + return []string{ + ScalingActivityStatusCodePendingSpotBidPlacement, + ScalingActivityStatusCodeWaitingForSpotInstanceRequestId, + ScalingActivityStatusCodeWaitingForSpotInstanceId, + ScalingActivityStatusCodeWaitingForInstanceId, + ScalingActivityStatusCodePreInService, + ScalingActivityStatusCodeInProgress, + ScalingActivityStatusCodeWaitingForElbconnectionDraining, + ScalingActivityStatusCodeMidLifecycleAction, + ScalingActivityStatusCodeWaitingForInstanceWarmup, + ScalingActivityStatusCodeSuccessful, + ScalingActivityStatusCodeFailed, + ScalingActivityStatusCodeCancelled, + } +} 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 2e65ee3d93f..85e907df74f 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 @@ -4,6 +4,13 @@ package autoscaling const ( + // ErrCodeActiveInstanceRefreshNotFoundFault for service response error code + // "ActiveInstanceRefreshNotFound". + // + // The request failed because an active instance refresh for the specified Auto + // Scaling group was not found. + ErrCodeActiveInstanceRefreshNotFoundFault = "ActiveInstanceRefreshNotFound" + // ErrCodeAlreadyExistsFault for service response error code // "AlreadyExists". // @@ -11,6 +18,13 @@ const ( // name. ErrCodeAlreadyExistsFault = "AlreadyExists" + // ErrCodeInstanceRefreshInProgressFault for service response error code + // "InstanceRefreshInProgress". + // + // The request failed because an active instance refresh operation already exists + // for the specified Auto Scaling group. + ErrCodeInstanceRefreshInProgressFault = "InstanceRefreshInProgress" + // ErrCodeInvalidNextToken for service response error code // "InvalidNextToken". // @@ -22,7 +36,8 @@ const ( // // You have already reached a limit for your Amazon EC2 Auto Scaling resources // (for example, Auto Scaling groups, launch configurations, or lifecycle hooks). - // For more information, see DescribeAccountLimits. + // For more information, see DescribeAccountLimits (https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeAccountLimits.html) + // in the Amazon EC2 Auto Scaling API Reference. ErrCodeLimitExceededFault = "LimitExceeded" // ErrCodeResourceContentionFault for service response error code diff --git a/vendor/github.com/aws/aws-sdk-go/service/autoscalingplans/api.go b/vendor/github.com/aws/aws-sdk-go/service/autoscalingplans/api.go index 128cfeb8f35..da115a42b19 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/autoscalingplans/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/autoscalingplans/api.go @@ -2946,6 +2946,16 @@ const ( ForecastDataTypeScheduledActionMaxCapacity = "ScheduledActionMaxCapacity" ) +// ForecastDataType_Values returns all elements of the ForecastDataType enum +func ForecastDataType_Values() []string { + return []string{ + ForecastDataTypeCapacityForecast, + ForecastDataTypeLoadForecast, + ForecastDataTypeScheduledActionMinCapacity, + ForecastDataTypeScheduledActionMaxCapacity, + } +} + const ( // LoadMetricTypeAsgtotalCpuutilization is a LoadMetricType enum value LoadMetricTypeAsgtotalCpuutilization = "ASGTotalCPUUtilization" @@ -2960,6 +2970,16 @@ const ( LoadMetricTypeAlbtargetGroupRequestCount = "ALBTargetGroupRequestCount" ) +// LoadMetricType_Values returns all elements of the LoadMetricType enum +func LoadMetricType_Values() []string { + return []string{ + LoadMetricTypeAsgtotalCpuutilization, + LoadMetricTypeAsgtotalNetworkIn, + LoadMetricTypeAsgtotalNetworkOut, + LoadMetricTypeAlbtargetGroupRequestCount, + } +} + const ( // MetricStatisticAverage is a MetricStatistic enum value MetricStatisticAverage = "Average" @@ -2977,11 +2997,29 @@ const ( MetricStatisticSum = "Sum" ) +// MetricStatistic_Values returns all elements of the MetricStatistic enum +func MetricStatistic_Values() []string { + return []string{ + MetricStatisticAverage, + MetricStatisticMinimum, + MetricStatisticMaximum, + MetricStatisticSampleCount, + MetricStatisticSum, + } +} + const ( // PolicyTypeTargetTrackingScaling is a PolicyType enum value PolicyTypeTargetTrackingScaling = "TargetTrackingScaling" ) +// PolicyType_Values returns all elements of the PolicyType enum +func PolicyType_Values() []string { + return []string{ + PolicyTypeTargetTrackingScaling, + } +} + const ( // PredictiveScalingMaxCapacityBehaviorSetForecastCapacityToMaxCapacity is a PredictiveScalingMaxCapacityBehavior enum value PredictiveScalingMaxCapacityBehaviorSetForecastCapacityToMaxCapacity = "SetForecastCapacityToMaxCapacity" @@ -2993,6 +3031,15 @@ const ( PredictiveScalingMaxCapacityBehaviorSetMaxCapacityAboveForecastCapacity = "SetMaxCapacityAboveForecastCapacity" ) +// PredictiveScalingMaxCapacityBehavior_Values returns all elements of the PredictiveScalingMaxCapacityBehavior enum +func PredictiveScalingMaxCapacityBehavior_Values() []string { + return []string{ + PredictiveScalingMaxCapacityBehaviorSetForecastCapacityToMaxCapacity, + PredictiveScalingMaxCapacityBehaviorSetMaxCapacityToForecastCapacity, + PredictiveScalingMaxCapacityBehaviorSetMaxCapacityAboveForecastCapacity, + } +} + const ( // PredictiveScalingModeForecastAndScale is a PredictiveScalingMode enum value PredictiveScalingModeForecastAndScale = "ForecastAndScale" @@ -3001,6 +3048,14 @@ const ( PredictiveScalingModeForecastOnly = "ForecastOnly" ) +// PredictiveScalingMode_Values returns all elements of the PredictiveScalingMode enum +func PredictiveScalingMode_Values() []string { + return []string{ + PredictiveScalingModeForecastAndScale, + PredictiveScalingModeForecastOnly, + } +} + const ( // ScalableDimensionAutoscalingAutoScalingGroupDesiredCapacity is a ScalableDimension enum value ScalableDimensionAutoscalingAutoScalingGroupDesiredCapacity = "autoscaling:autoScalingGroup:DesiredCapacity" @@ -3027,6 +3082,20 @@ const ( ScalableDimensionDynamodbIndexWriteCapacityUnits = "dynamodb:index:WriteCapacityUnits" ) +// ScalableDimension_Values returns all elements of the ScalableDimension enum +func ScalableDimension_Values() []string { + return []string{ + ScalableDimensionAutoscalingAutoScalingGroupDesiredCapacity, + ScalableDimensionEcsServiceDesiredCount, + ScalableDimensionEc2SpotFleetRequestTargetCapacity, + ScalableDimensionRdsClusterReadReplicaCount, + ScalableDimensionDynamodbTableReadCapacityUnits, + ScalableDimensionDynamodbTableWriteCapacityUnits, + ScalableDimensionDynamodbIndexReadCapacityUnits, + ScalableDimensionDynamodbIndexWriteCapacityUnits, + } +} + const ( // ScalingMetricTypeAsgaverageCpuutilization is a ScalingMetricType enum value ScalingMetricTypeAsgaverageCpuutilization = "ASGAverageCPUUtilization" @@ -3068,6 +3137,25 @@ const ( ScalingMetricTypeEc2spotFleetRequestAverageNetworkOut = "EC2SpotFleetRequestAverageNetworkOut" ) +// ScalingMetricType_Values returns all elements of the ScalingMetricType enum +func ScalingMetricType_Values() []string { + return []string{ + ScalingMetricTypeAsgaverageCpuutilization, + ScalingMetricTypeAsgaverageNetworkIn, + ScalingMetricTypeAsgaverageNetworkOut, + ScalingMetricTypeDynamoDbreadCapacityUtilization, + ScalingMetricTypeDynamoDbwriteCapacityUtilization, + ScalingMetricTypeEcsserviceAverageCpuutilization, + ScalingMetricTypeEcsserviceAverageMemoryUtilization, + ScalingMetricTypeAlbrequestCountPerTarget, + ScalingMetricTypeRdsreaderAverageCpuutilization, + ScalingMetricTypeRdsreaderAverageDatabaseConnections, + ScalingMetricTypeEc2spotFleetRequestAverageCpuutilization, + ScalingMetricTypeEc2spotFleetRequestAverageNetworkIn, + ScalingMetricTypeEc2spotFleetRequestAverageNetworkOut, + } +} + const ( // ScalingPlanStatusCodeActive is a ScalingPlanStatusCode enum value ScalingPlanStatusCodeActive = "Active" @@ -3094,6 +3182,20 @@ const ( ScalingPlanStatusCodeUpdateFailed = "UpdateFailed" ) +// ScalingPlanStatusCode_Values returns all elements of the ScalingPlanStatusCode enum +func ScalingPlanStatusCode_Values() []string { + return []string{ + ScalingPlanStatusCodeActive, + ScalingPlanStatusCodeActiveWithProblems, + ScalingPlanStatusCodeCreationInProgress, + ScalingPlanStatusCodeCreationFailed, + ScalingPlanStatusCodeDeletionInProgress, + ScalingPlanStatusCodeDeletionFailed, + ScalingPlanStatusCodeUpdateInProgress, + ScalingPlanStatusCodeUpdateFailed, + } +} + const ( // ScalingPolicyUpdateBehaviorKeepExternalPolicies is a ScalingPolicyUpdateBehavior enum value ScalingPolicyUpdateBehaviorKeepExternalPolicies = "KeepExternalPolicies" @@ -3102,6 +3204,14 @@ const ( ScalingPolicyUpdateBehaviorReplaceExternalPolicies = "ReplaceExternalPolicies" ) +// ScalingPolicyUpdateBehavior_Values returns all elements of the ScalingPolicyUpdateBehavior enum +func ScalingPolicyUpdateBehavior_Values() []string { + return []string{ + ScalingPolicyUpdateBehaviorKeepExternalPolicies, + ScalingPolicyUpdateBehaviorReplaceExternalPolicies, + } +} + const ( // ScalingStatusCodeInactive is a ScalingStatusCode enum value ScalingStatusCodeInactive = "Inactive" @@ -3113,6 +3223,15 @@ const ( ScalingStatusCodeActive = "Active" ) +// ScalingStatusCode_Values returns all elements of the ScalingStatusCode enum +func ScalingStatusCode_Values() []string { + return []string{ + ScalingStatusCodeInactive, + ScalingStatusCodePartiallyActive, + ScalingStatusCodeActive, + } +} + const ( // ServiceNamespaceAutoscaling is a ServiceNamespace enum value ServiceNamespaceAutoscaling = "autoscaling" @@ -3129,3 +3248,14 @@ const ( // ServiceNamespaceDynamodb is a ServiceNamespace enum value ServiceNamespaceDynamodb = "dynamodb" ) + +// ServiceNamespace_Values returns all elements of the ServiceNamespace enum +func ServiceNamespace_Values() []string { + return []string{ + ServiceNamespaceAutoscaling, + ServiceNamespaceEcs, + ServiceNamespaceEc2, + ServiceNamespaceRds, + ServiceNamespaceDynamodb, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/backup/api.go b/vendor/github.com/aws/aws-sdk-go/service/backup/api.go index 8804a28f688..f9bd26b3672 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/backup/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/backup/api.go @@ -1193,7 +1193,7 @@ func (c *Backup) DescribeProtectedResourceRequest(input *DescribeProtectedResour // DescribeProtectedResource API operation for AWS Backup. // // Returns information about a saved resource, including the last time it was -// backed-up, its Amazon Resource Name (ARN), and the AWS service type of the +// backed up, its Amazon Resource Name (ARN), and the AWS service type of the // saved resource. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1329,6 +1329,89 @@ func (c *Backup) DescribeRecoveryPointWithContext(ctx aws.Context, input *Descri return out, req.Send() } +const opDescribeRegionSettings = "DescribeRegionSettings" + +// DescribeRegionSettingsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeRegionSettings operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeRegionSettings for more information on using the DescribeRegionSettings +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeRegionSettingsRequest method. +// req, resp := client.DescribeRegionSettingsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/backup-2018-11-15/DescribeRegionSettings +func (c *Backup) DescribeRegionSettingsRequest(input *DescribeRegionSettingsInput) (req *request.Request, output *DescribeRegionSettingsOutput) { + op := &request.Operation{ + Name: opDescribeRegionSettings, + HTTPMethod: "GET", + HTTPPath: "/account-settings", + } + + if input == nil { + input = &DescribeRegionSettingsInput{} + } + + output = &DescribeRegionSettingsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeRegionSettings API operation for AWS Backup. +// +// Returns the current service opt-in settings for the Region. If the service +// has a value set to true, AWS Backup attempts to protect that service's resources +// in this Region, when included in an on-demand backup or scheduled backup +// plan. If the value is set to false for a service, AWS Backup does not attempt +// to protect that service's resources in this Region. +// +// Returns awserr.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 Backup's +// API operation DescribeRegionSettings for usage and error information. +// +// Returned Error Types: +// * ServiceUnavailableException +// The request failed due to a temporary failure of the server. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/backup-2018-11-15/DescribeRegionSettings +func (c *Backup) DescribeRegionSettings(input *DescribeRegionSettingsInput) (*DescribeRegionSettingsOutput, error) { + req, out := c.DescribeRegionSettingsRequest(input) + return out, req.Send() +} + +// DescribeRegionSettingsWithContext is the same as DescribeRegionSettings with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRegionSettings for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Backup) DescribeRegionSettingsWithContext(ctx aws.Context, input *DescribeRegionSettingsInput, opts ...request.Option) (*DescribeRegionSettingsOutput, error) { + req, out := c.DescribeRegionSettingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeRestoreJob = "DescribeRestoreJob" // DescribeRestoreJobRequest generates a "aws/request.Request" representing the @@ -2285,10 +2368,6 @@ func (c *Backup) ListBackupJobsRequest(input *ListBackupJobsInput) (req *request // Indicates that something is wrong with a parameter's value. For example, // the value is out of range. // -// * InvalidRequestException -// Indicates that something is wrong with the input to the request. For example, -// a parameter is of the wrong type. -// // * ServiceUnavailableException // The request failed due to a temporary failure of the server. // @@ -3889,6 +3968,8 @@ func (c *Backup) ListTagsRequest(input *ListTagsInput) (req *request.Request, ou // Returns a list of key-value pairs assigned to a target recovery point, backup // plan, or backup vault. // +// ListTags are currently only supported with Amazon EFS backups. +// // Returns awserr.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. @@ -4915,6 +4996,97 @@ func (c *Backup) UpdateRecoveryPointLifecycleWithContext(ctx aws.Context, input return out, req.Send() } +const opUpdateRegionSettings = "UpdateRegionSettings" + +// UpdateRegionSettingsRequest generates a "aws/request.Request" representing the +// client's request for the UpdateRegionSettings operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateRegionSettings for more information on using the UpdateRegionSettings +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateRegionSettingsRequest method. +// req, resp := client.UpdateRegionSettingsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/backup-2018-11-15/UpdateRegionSettings +func (c *Backup) UpdateRegionSettingsRequest(input *UpdateRegionSettingsInput) (req *request.Request, output *UpdateRegionSettingsOutput) { + op := &request.Operation{ + Name: opUpdateRegionSettings, + HTTPMethod: "PUT", + HTTPPath: "/account-settings", + } + + if input == nil { + input = &UpdateRegionSettingsInput{} + } + + output = &UpdateRegionSettingsOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UpdateRegionSettings API operation for AWS Backup. +// +// Updates the current service opt-in settings for the Region. If the service +// has a value set to true, AWS Backup attempts to protect that service's resources +// in this Region, when included in an on-demand backup or scheduled backup +// plan. If the value is set to false for a service, AWS Backup does not attempt +// to protect that service's resources in this Region. +// +// Returns awserr.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 Backup's +// API operation UpdateRegionSettings for usage and error information. +// +// Returned Error Types: +// * ServiceUnavailableException +// The request failed due to a temporary failure of the server. +// +// * MissingParameterValueException +// Indicates that a required parameter is missing. +// +// * InvalidParameterValueException +// Indicates that something is wrong with a parameter's value. For example, +// the value is out of range. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/backup-2018-11-15/UpdateRegionSettings +func (c *Backup) UpdateRegionSettings(input *UpdateRegionSettingsInput) (*UpdateRegionSettingsOutput, error) { + req, out := c.UpdateRegionSettingsRequest(input) + return out, req.Send() +} + +// UpdateRegionSettingsWithContext is the same as UpdateRegionSettings with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRegionSettings for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Backup) UpdateRegionSettingsWithContext(ctx aws.Context, input *UpdateRegionSettingsInput, opts ...request.Option) (*UpdateRegionSettingsOutput, error) { + req, out := c.UpdateRegionSettingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + // The required resource already exists. type AlreadyExistsException struct { _ struct{} `type:"structure"` @@ -5157,16 +5329,19 @@ func (s *CopyAction) SetLifecycle(v *Lifecycle) *CopyAction { type CopyJob struct { _ struct{} `type:"structure"` + // The account ID that owns the copy job. + AccountId *string `type:"string"` + // The size, in bytes, of a copy job. BackupSizeInBytes *int64 `type:"long"` - // The date and time a job to create a copy job is completed, in Unix format - // and Coordinated Universal Time (UTC). The value of CompletionDate is accurate - // to milliseconds. For example, the value 1516925490.087 represents Friday, - // January 26, 2018 12:11:30.087 AM. + // The date and time a copy job is completed, in Unix format and Coordinated + // Universal Time (UTC). The value of CompletionDate is accurate to milliseconds. + // For example, the value 1516925490.087 represents Friday, January 26, 2018 + // 12:11:30.087 AM. CompletionDate *time.Time `type:"timestamp"` - // Uniquely identifies a request to AWS Backup to copy a resource. + // Uniquely identifies a copy job. CopyJobId *string `type:"string"` // Contains information about the backup plan and rule that AWS Backup used @@ -5191,9 +5366,9 @@ type CopyJob struct { // arn:aws:iam::123456789012:role/S3Access. IamRoleArn *string `type:"string"` - // The type of AWS resource to be copied; for example, an Amazon Elastic Block - // Store (Amazon EBS) volume or an Amazon Relational Database Service (Amazon - // RDS) database. + // The AWS resource to be copied; for example, an Amazon Elastic Block Store + // (Amazon EBS) volume or an Amazon Relational Database Service (Amazon RDS) + // database. ResourceArn *string `type:"string"` // The type of AWS resource to be copied; for example, an Amazon Elastic Block @@ -5208,10 +5383,10 @@ type CopyJob struct { // An ARN that uniquely identifies a source recovery point; for example, arn:aws:backup:us-east-1:123456789012:recovery-point:1EB3B5E7-9EB0-435A-A80B-108B488B0D45. SourceRecoveryPointArn *string `type:"string"` - // The current state of a resource recovery point. + // The current state of a copy job. State *string `type:"string" enum:"CopyJobState"` - // A detailed message explaining the status of the job that to copy a resource. + // A detailed message explaining the status of the job to copy a resource. StatusMessage *string `type:"string"` } @@ -5225,6 +5400,12 @@ func (s CopyJob) GoString() string { return s.String() } +// SetAccountId sets the AccountId field's value. +func (s *CopyJob) SetAccountId(v string) *CopyJob { + s.AccountId = &v + return s +} + // SetBackupSizeInBytes sets the BackupSizeInBytes field's value. func (s *CopyJob) SetBackupSizeInBytes(v int64) *CopyJob { s.BackupSizeInBytes = &v @@ -5393,7 +5574,7 @@ type CreateBackupPlanOutput struct { CreationDate *time.Time `type:"timestamp"` // Unique, randomly generated, Unicode, UTF-8 encoded strings that are at most - // 1024 bytes long. They cannot be edited. + // 1,024 bytes long. They cannot be edited. VersionId *string `type:"string"` } @@ -5722,7 +5903,7 @@ type DeleteBackupPlanOutput struct { BackupPlanId *string `type:"string"` // The date and time a backup plan is deleted, in Unix format and Coordinated - // Universal Time (UTC). The value of CreationDate is accurate to milliseconds. + // Universal Time (UTC). The value of DeletionDate is accurate to milliseconds. // For example, the value 1516925490.087 represents Friday, January 26, 2018 // 12:11:30.087 AM. DeletionDate *time.Time `type:"timestamp"` @@ -5902,7 +6083,7 @@ type DeleteBackupVaultInput struct { // The name of a logical container where backups are stored. Backup vaults are // identified by names that are unique to the account used to create them and - // theAWS Region where they are created. They consist of lowercase letters, + // the AWS Region where they are created. They consist of lowercase letters, // numbers, and hyphens. // // BackupVaultName is a required field @@ -6196,6 +6377,9 @@ func (s *DescribeBackupJobInput) SetBackupJobId(v string) *DescribeBackupJobInpu type DescribeBackupJobOutput struct { _ struct{} `type:"structure"` + // Returns the account ID that owns the backup job. + AccountId *string `type:"string"` + // Uniquely identifies a request to AWS Backup to back up a resource. BackupJobId *string `type:"string"` @@ -6217,8 +6401,8 @@ type DescribeBackupJobOutput struct { BytesTransferred *int64 `type:"long"` // The date and time that a job to create a backup job is completed, in Unix - // format and Coordinated Universal Time (UTC). The value of CreationDate is - // accurate to milliseconds. For example, the value 1516925490.087 represents + // format and Coordinated Universal Time (UTC). The value of CompletionDate + // is accurate to milliseconds. For example, the value 1516925490.087 represents // Friday, January 26, 2018 12:11:30.087 AM. CompletionDate *time.Time `type:"timestamp"` @@ -6254,7 +6438,7 @@ type DescribeBackupJobOutput struct { // on the resource type. ResourceArn *string `type:"string"` - // The type of AWS resource to be backed-up; for example, an Amazon Elastic + // The type of AWS resource to be backed up; for example, an Amazon Elastic // Block Store (Amazon EBS) volume or an Amazon Relational Database Service // (Amazon RDS) database. ResourceType *string `type:"string"` @@ -6285,6 +6469,12 @@ func (s DescribeBackupJobOutput) GoString() string { return s.String() } +// SetAccountId sets the AccountId field's value. +func (s *DescribeBackupJobOutput) SetAccountId(v string) *DescribeBackupJobOutput { + s.AccountId = &v + return s +} + // SetBackupJobId sets the BackupJobId field's value. func (s *DescribeBackupJobOutput) SetBackupJobId(v string) *DescribeBackupJobOutput { s.BackupJobId = &v @@ -6511,7 +6701,7 @@ func (s *DescribeBackupVaultOutput) SetNumberOfRecoveryPoints(v int64) *Describe type DescribeCopyJobInput struct { _ struct{} `type:"structure"` - // Uniquely identifies a request to AWS Backup to copy a resource. + // Uniquely identifies a copy job. // // CopyJobId is a required field CopyJobId *string `location:"uri" locationName:"copyJobId" type:"string" required:"true"` @@ -6922,6 +7112,43 @@ func (s *DescribeRecoveryPointOutput) SetStorageClass(v string) *DescribeRecover return s } +type DescribeRegionSettingsInput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DescribeRegionSettingsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeRegionSettingsInput) GoString() string { + return s.String() +} + +type DescribeRegionSettingsOutput struct { + _ struct{} `type:"structure"` + + // Returns a list of all services along with the opt-in preferences in the region. + ResourceTypeOptInPreference map[string]*bool `type:"map"` +} + +// String returns the string representation +func (s DescribeRegionSettingsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeRegionSettingsOutput) GoString() string { + return s.String() +} + +// SetResourceTypeOptInPreference sets the ResourceTypeOptInPreference field's value. +func (s *DescribeRegionSettingsOutput) SetResourceTypeOptInPreference(v map[string]*bool) *DescribeRegionSettingsOutput { + s.ResourceTypeOptInPreference = v + return s +} + type DescribeRestoreJobInput struct { _ struct{} `type:"structure"` @@ -6966,6 +7193,9 @@ func (s *DescribeRestoreJobInput) SetRestoreJobId(v string) *DescribeRestoreJobI type DescribeRestoreJobOutput struct { _ struct{} `type:"structure"` + // Returns the account ID that owns the restore job. + AccountId *string `type:"string"` + // The size, in bytes, of the restored resource. BackupSizeInBytes *int64 `type:"long"` @@ -7001,6 +7231,9 @@ type DescribeRestoreJobOutput struct { // An ARN that uniquely identifies a recovery point; for example, arn:aws:backup:us-east-1:123456789012:recovery-point:1EB3B5E7-9EB0-435A-A80B-108B488B0D45. RecoveryPointArn *string `type:"string"` + // Returns metadata associated with a restore job listed by resource type. + ResourceType *string `type:"string"` + // Uniquely identifies the job that restores a recovery point. RestoreJobId *string `type:"string"` @@ -7008,7 +7241,7 @@ type DescribeRestoreJobOutput struct { // to restore a recovery point. Status *string `type:"string" enum:"RestoreJobStatus"` - // A detailed message explaining the status of a job to restore a recovery point. + // A message showing the status of a job to restore a recovery point. StatusMessage *string `type:"string"` } @@ -7022,6 +7255,12 @@ func (s DescribeRestoreJobOutput) GoString() string { return s.String() } +// SetAccountId sets the AccountId field's value. +func (s *DescribeRestoreJobOutput) SetAccountId(v string) *DescribeRestoreJobOutput { + s.AccountId = &v + return s +} + // SetBackupSizeInBytes sets the BackupSizeInBytes field's value. func (s *DescribeRestoreJobOutput) SetBackupSizeInBytes(v int64) *DescribeRestoreJobOutput { s.BackupSizeInBytes = &v @@ -7070,6 +7309,12 @@ func (s *DescribeRestoreJobOutput) SetRecoveryPointArn(v string) *DescribeRestor return s } +// SetResourceType sets the ResourceType field's value. +func (s *DescribeRestoreJobOutput) SetResourceType(v string) *DescribeRestoreJobOutput { + s.ResourceType = &v + return s +} + // SetRestoreJobId sets the RestoreJobId field's value. func (s *DescribeRestoreJobOutput) SetRestoreJobId(v string) *DescribeRestoreJobOutput { s.RestoreJobId = &v @@ -7358,7 +7603,7 @@ type GetBackupPlanOutput struct { CreatorRequestId *string `type:"string"` // The date and time that a backup plan is deleted, in Unix format and Coordinated - // Universal Time (UTC). The value of CreationDate is accurate to milliseconds. + // Universal Time (UTC). The value of DeletionDate is accurate to milliseconds. // For example, the value 1516925490.087 represents Friday, January 26, 2018 // 12:11:30.087 AM. DeletionDate *time.Time `type:"timestamp"` @@ -7869,15 +8114,17 @@ type GetSupportedResourceTypesOutput struct { // Contains a string with the supported AWS resource types: // + // * DynamoDB for Amazon DynamoDB + // // * EBS for Amazon Elastic Block Store // - // * Storage Gateway for AWS Storage Gateway + // * EC2 for Amazon Elastic Compute Cloud // - // * RDS for Amazon Relational Database Service + // * EFS for Amazon Elastic File System // - // * DDB for Amazon DynamoDB + // * RDS for Amazon Relational Database Service // - // * EFS for Amazon Elastic File System + // * Storage Gateway for AWS Storage Gateway ResourceTypes []*string `type:"list"` } @@ -8027,6 +8274,9 @@ func (s *InvalidRequestException) RequestID() string { type Job struct { _ struct{} `type:"structure"` + // The account ID that owns the backup job. + AccountId *string `type:"string"` + // Uniquely identifies a request to AWS Backup to back up a resource. BackupJobId *string `type:"string"` @@ -8085,7 +8335,7 @@ type Job struct { // on the resource type. ResourceArn *string `type:"string"` - // The type of AWS resource to be backed-up; for example, an Amazon Elastic + // The type of AWS resource to be backed up; for example, an Amazon Elastic // Block Store (Amazon EBS) volume or an Amazon Relational Database Service // (Amazon RDS) database. ResourceType *string `type:"string"` @@ -8116,6 +8366,12 @@ func (s Job) GoString() string { return s.String() } +// SetAccountId sets the AccountId field's value. +func (s *Job) SetAccountId(v string) *Job { + s.AccountId = &v + return s +} + // SetBackupJobId sets the BackupJobId field's value. func (s *Job) SetBackupJobId(v string) *Job { s.BackupJobId = &v @@ -8326,6 +8582,10 @@ func (s *LimitExceededException) RequestID() string { type ListBackupJobsInput struct { _ struct{} `type:"structure"` + // The account ID to list the jobs from. Returns only backup jobs associated + // with the specified account ID. + ByAccountId *string `location:"querystring" locationName:"accountId" type:"string"` + // Returns only backup jobs that will be stored in the specified backup vault. // Backup vaults are identified by names that are unique to the account used // to create them and the AWS Region where they are created. They consist of @@ -8348,6 +8608,8 @@ type ListBackupJobsInput struct { // // * EBS for Amazon Elastic Block Store // + // * EC2 for Amazon Elastic Compute Cloud + // // * EFS for Amazon Elastic File System // // * RDS for Amazon Relational Database Service @@ -8391,6 +8653,12 @@ func (s *ListBackupJobsInput) Validate() error { return nil } +// SetByAccountId sets the ByAccountId field's value. +func (s *ListBackupJobsInput) SetByAccountId(v string) *ListBackupJobsInput { + s.ByAccountId = &v + return s +} + // SetByBackupVaultName sets the ByBackupVaultName field's value. func (s *ListBackupJobsInput) SetByBackupVaultName(v string) *ListBackupJobsInput { s.ByBackupVaultName = &v @@ -8942,6 +9210,10 @@ func (s *ListBackupVaultsOutput) SetNextToken(v string) *ListBackupVaultsOutput type ListCopyJobsInput struct { _ struct{} `type:"structure"` + // The account ID to list the jobs from. Returns only copy jobs associated with + // the specified account ID. + ByAccountId *string `location:"querystring" locationName:"accountId" type:"string"` + // Returns only copy jobs that were created after the specified date. ByCreatedAfter *time.Time `location:"querystring" locationName:"createdAfter" type:"timestamp"` @@ -8962,6 +9234,8 @@ type ListCopyJobsInput struct { // // * EBS for Amazon Elastic Block Store // + // * EC2 for Amazon Elastic Compute Cloud + // // * EFS for Amazon Elastic File System // // * RDS for Amazon Relational Database Service @@ -9005,6 +9279,12 @@ func (s *ListCopyJobsInput) Validate() error { return nil } +// SetByAccountId sets the ByAccountId field's value. +func (s *ListCopyJobsInput) SetByAccountId(v string) *ListCopyJobsInput { + s.ByAccountId = &v + return s +} + // SetByCreatedAfter sets the ByCreatedAfter field's value. func (s *ListCopyJobsInput) SetByCreatedAfter(v time.Time) *ListCopyJobsInput { s.ByCreatedAfter = &v @@ -9429,6 +9709,19 @@ func (s *ListRecoveryPointsByResourceOutput) SetRecoveryPoints(v []*RecoveryPoin type ListRestoreJobsInput struct { _ struct{} `type:"structure"` + // The account ID to list the jobs from. Returns only restore jobs associated + // with the specified account ID. + ByAccountId *string `location:"querystring" locationName:"accountId" type:"string"` + + // Returns only restore jobs that were created after the specified date. + ByCreatedAfter *time.Time `location:"querystring" locationName:"createdAfter" type:"timestamp"` + + // Returns only restore jobs that were created before the specified date. + ByCreatedBefore *time.Time `location:"querystring" locationName:"createdBefore" type:"timestamp"` + + // Returns only restore jobs associated with the specified job status. + ByStatus *string `location:"querystring" locationName:"status" type:"string" enum:"RestoreJobStatus"` + // The maximum number of items to be returned. MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` @@ -9462,6 +9755,30 @@ func (s *ListRestoreJobsInput) Validate() error { return nil } +// SetByAccountId sets the ByAccountId field's value. +func (s *ListRestoreJobsInput) SetByAccountId(v string) *ListRestoreJobsInput { + s.ByAccountId = &v + return s +} + +// SetByCreatedAfter sets the ByCreatedAfter field's value. +func (s *ListRestoreJobsInput) SetByCreatedAfter(v time.Time) *ListRestoreJobsInput { + s.ByCreatedAfter = &v + return s +} + +// SetByCreatedBefore sets the ByCreatedBefore field's value. +func (s *ListRestoreJobsInput) SetByCreatedBefore(v time.Time) *ListRestoreJobsInput { + s.ByCreatedBefore = &v + return s +} + +// SetByStatus sets the ByStatus field's value. +func (s *ListRestoreJobsInput) SetByStatus(v string) *ListRestoreJobsInput { + s.ByStatus = &v + return s +} + // SetMaxResults sets the MaxResults field's value. func (s *ListRestoreJobsInput) SetMaxResults(v int64) *ListRestoreJobsInput { s.MaxResults = &v @@ -9723,7 +10040,7 @@ func (s *Plan) SetRules(v []*Rule) *Plan { type PlanInput struct { _ struct{} `type:"structure"` - // The display name of a backup plan. + // The optional display name of a backup plan. // // BackupPlanName is a required field BackupPlanName *string `type:"string" required:"true"` @@ -10505,6 +10822,9 @@ func (s *ResourceNotFoundException) RequestID() string { type RestoreJobsListMember struct { _ struct{} `type:"structure"` + // The account ID that owns the restore job. + AccountId *string `type:"string"` + // The size, in bytes, of the restored resource. BackupSizeInBytes *int64 `type:"long"` @@ -10539,6 +10859,11 @@ type RestoreJobsListMember struct { // An ARN that uniquely identifies a recovery point; for example, arn:aws:backup:us-east-1:123456789012:recovery-point:1EB3B5E7-9EB0-435A-A80B-108B488B0D45. RecoveryPointArn *string `type:"string"` + // The resource type of the listed restore jobs; for example, an Amazon Elastic + // Block Store (Amazon EBS) volume or an Amazon Relational Database Service + // (Amazon RDS) database. + ResourceType *string `type:"string"` + // Uniquely identifies the job that restores a recovery point. RestoreJobId *string `type:"string"` @@ -10561,6 +10886,12 @@ func (s RestoreJobsListMember) GoString() string { return s.String() } +// SetAccountId sets the AccountId field's value. +func (s *RestoreJobsListMember) SetAccountId(v string) *RestoreJobsListMember { + s.AccountId = &v + return s +} + // SetBackupSizeInBytes sets the BackupSizeInBytes field's value. func (s *RestoreJobsListMember) SetBackupSizeInBytes(v int64) *RestoreJobsListMember { s.BackupSizeInBytes = &v @@ -10609,6 +10940,12 @@ func (s *RestoreJobsListMember) SetRecoveryPointArn(v string) *RestoreJobsListMe return s } +// SetResourceType sets the ResourceType field's value. +func (s *RestoreJobsListMember) SetResourceType(v string) *RestoreJobsListMember { + s.ResourceType = &v + return s +} + // SetRestoreJobId sets the RestoreJobId field's value. func (s *RestoreJobsListMember) SetRestoreJobId(v string) *RestoreJobsListMember { s.RestoreJobId = &v @@ -10632,7 +10969,7 @@ type Rule struct { _ struct{} `type:"structure"` // A value in minutes after a backup job is successfully started before it must - // be completed or it is canceled by AWS Backup. This value is optional. + // be completed or it will be canceled by AWS Backup. This value is optional. CompletionWindowMinutes *int64 `type:"long"` // An array of CopyAction objects, which contains the details of the copy operation. @@ -10665,8 +11002,8 @@ type Rule struct { // A CRON expression specifying when AWS Backup initiates a backup job. ScheduleExpression *string `type:"string"` - // An optional value that specifies a period of time in minutes after a backup - // is scheduled before a job is canceled if it doesn't start successfully. + // A value in minutes after a backup is scheduled before a job will be canceled + // if it doesn't start successfully. This value is optional. StartWindowMinutes *int64 `type:"long"` // The name of a logical container where backups are stored. Backup vaults are @@ -10746,8 +11083,8 @@ func (s *Rule) SetTargetBackupVaultName(v string) *Rule { type RuleInput struct { _ struct{} `type:"structure"` - // The amount of time AWS Backup attempts a backup before canceling the job - // and returning an error. + // A value in minutes after a backup job is successfully started before it must + // be completed or it will be canceled by AWS Backup. This value is optional. CompletionWindowMinutes *int64 `type:"long"` // An array of CopyAction objects, which contains the details of the copy operation. @@ -10759,16 +11096,16 @@ type RuleInput struct { // // Backups transitioned to cold storage must be stored in cold storage for a // minimum of 90 days. Therefore, the “expire after days” setting must be - // 90 days greater than the “transition to cold after days”. The “transition - // to cold after days” setting cannot be changed after a backup has been transitioned - // to cold. + // 90 days greater than the “transition to cold after days” setting. The + // “transition to cold after days” setting cannot be changed after a backup + // has been transitioned to cold. Lifecycle *Lifecycle `type:"structure"` // To help organize your resources, you can assign your own metadata to the // resources that you create. Each tag is a key-value pair. RecoveryPointTags map[string]*string `type:"map" sensitive:"true"` - // >An optional display name for a backup rule. + // An optional display name for a backup rule. // // RuleName is a required field RuleName *string `type:"string" required:"true"` @@ -10776,7 +11113,8 @@ type RuleInput struct { // A CRON expression specifying when AWS Backup initiates a backup job. ScheduleExpression *string `type:"string"` - // The amount of time in minutes before beginning a backup. + // A value in minutes after a backup is scheduled before a job will be canceled + // if it doesn't start successfully. This value is optional. StartWindowMinutes *int64 `type:"long"` // The name of a logical container where backups are stored. Backup vaults are @@ -11104,8 +11442,8 @@ type StartBackupJobInput struct { // BackupVaultName is a required field BackupVaultName *string `type:"string" required:"true"` - // The amount of time AWS Backup attempts a backup before canceling the job - // and returning an error. + // A value in minutes after a backup job is successfully started before it must + // be completed or it will be canceled by AWS Backup. This value is optional. CompleteWindowMinutes *int64 `type:"long"` // Specifies the IAM role ARN used to create the target recovery point; for @@ -11139,7 +11477,8 @@ type StartBackupJobInput struct { // ResourceArn is a required field ResourceArn *string `type:"string" required:"true"` - // The amount of time in minutes before beginning a backup. + // A value in minutes after a backup is scheduled before a job will be canceled + // if it doesn't start successfully. This value is optional. StartWindowMinutes *int64 `type:"long"` } @@ -11302,7 +11641,7 @@ type StartCopyJobInput struct { // The name of a logical source container where backups are stored. Backup vaults // are identified by names that are unique to the account used to create them // and the AWS Region where they are created. They consist of lowercase letters, - // numbers, and hyphens. > + // numbers, and hyphens. // // SourceBackupVaultName is a required field SourceBackupVaultName *string `type:"string" required:"true"` @@ -11379,13 +11718,13 @@ func (s *StartCopyJobInput) SetSourceBackupVaultName(v string) *StartCopyJobInpu type StartCopyJobOutput struct { _ struct{} `type:"structure"` - // Uniquely identifies a request to AWS Backup to copy a resource. + // Uniquely identifies a copy job. CopyJobId *string `type:"string"` - // The date and time that a backup job is started, in Unix format and Coordinated + // The date and time that a copy job is started, in Unix format and Coordinated // Universal Time (UTC). The value of CreationDate is accurate to milliseconds. // For example, the value 1516925490.087 represents Friday, January 26, 2018 - // 12:11:30.087 AM. > + // 12:11:30.087 AM. CreationDate *time.Time `type:"timestamp"` } @@ -11427,11 +11766,11 @@ type StartRestoreJobInput struct { // A set of metadata key-value pairs. Contains information, such as a resource // name, required to restore a recovery point. // - // You can get configuration metadata about a resource at the time it was backed-up - // by calling GetRecoveryPointRestoreMetadata. However, values in addition to - // those provided by GetRecoveryPointRestoreMetadata might be required to restore - // a resource. For example, you might need to provide a new resource name if - // the original already exists. + // You can get configuration metadata about a resource at the time it was backed + // up by calling GetRecoveryPointRestoreMetadata. However, values in addition + // to those provided by GetRecoveryPointRestoreMetadata might be required to + // restore a resource. For example, you might need to provide a new resource + // name if the original already exists. // // You need to specify specific metadata to restore an Amazon Elastic File System // (Amazon EFS) instance: @@ -11463,15 +11802,17 @@ type StartRestoreJobInput struct { // Starts a job to restore a recovery point for one of the following resources: // + // * DynamoDB for Amazon DynamoDB + // // * EBS for Amazon Elastic Block Store // - // * Storage Gateway for AWS Storage Gateway + // * EC2 for Amazon Elastic Compute Cloud // - // * RDS for Amazon Relational Database Service + // * EFS for Amazon Elastic File System // - // * DDB for Amazon DynamoDB + // * RDS for Amazon Relational Database Service // - // * EFS for Amazon Elastic File System + // * Storage Gateway for AWS Storage Gateway ResourceType *string `type:"string"` } @@ -12008,6 +12349,43 @@ func (s *UpdateRecoveryPointLifecycleOutput) SetRecoveryPointArn(v string) *Upda return s } +type UpdateRegionSettingsInput struct { + _ struct{} `type:"structure"` + + // Updates the list of services along with the opt-in preferences for the region. + ResourceTypeOptInPreference map[string]*bool `type:"map"` +} + +// String returns the string representation +func (s UpdateRegionSettingsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateRegionSettingsInput) GoString() string { + return s.String() +} + +// SetResourceTypeOptInPreference sets the ResourceTypeOptInPreference field's value. +func (s *UpdateRegionSettingsInput) SetResourceTypeOptInPreference(v map[string]*bool) *UpdateRegionSettingsInput { + s.ResourceTypeOptInPreference = v + return s +} + +type UpdateRegionSettingsOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UpdateRegionSettingsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateRegionSettingsOutput) GoString() string { + return s.String() +} + // Contains metadata about a backup vault. type VaultListMember struct { _ struct{} `type:"structure"` @@ -12091,6 +12469,13 @@ const ( ConditionTypeStringequals = "STRINGEQUALS" ) +// ConditionType_Values returns all elements of the ConditionType enum +func ConditionType_Values() []string { + return []string{ + ConditionTypeStringequals, + } +} + const ( // CopyJobStateCreated is a CopyJobState enum value CopyJobStateCreated = "CREATED" @@ -12105,6 +12490,16 @@ const ( CopyJobStateFailed = "FAILED" ) +// CopyJobState_Values returns all elements of the CopyJobState enum +func CopyJobState_Values() []string { + return []string{ + CopyJobStateCreated, + CopyJobStateRunning, + CopyJobStateCompleted, + CopyJobStateFailed, + } +} + const ( // JobStateCreated is a JobState enum value JobStateCreated = "CREATED" @@ -12131,6 +12526,20 @@ const ( JobStateExpired = "EXPIRED" ) +// JobState_Values returns all elements of the JobState enum +func JobState_Values() []string { + return []string{ + JobStateCreated, + JobStatePending, + JobStateRunning, + JobStateAborting, + JobStateAborted, + JobStateCompleted, + JobStateFailed, + JobStateExpired, + } +} + const ( // RecoveryPointStatusCompleted is a RecoveryPointStatus enum value RecoveryPointStatusCompleted = "COMPLETED" @@ -12145,6 +12554,16 @@ const ( RecoveryPointStatusExpired = "EXPIRED" ) +// RecoveryPointStatus_Values returns all elements of the RecoveryPointStatus enum +func RecoveryPointStatus_Values() []string { + return []string{ + RecoveryPointStatusCompleted, + RecoveryPointStatusPartial, + RecoveryPointStatusDeleting, + RecoveryPointStatusExpired, + } +} + const ( // RestoreJobStatusPending is a RestoreJobStatus enum value RestoreJobStatusPending = "PENDING" @@ -12162,6 +12581,17 @@ const ( RestoreJobStatusFailed = "FAILED" ) +// RestoreJobStatus_Values returns all elements of the RestoreJobStatus enum +func RestoreJobStatus_Values() []string { + return []string{ + RestoreJobStatusPending, + RestoreJobStatusRunning, + RestoreJobStatusCompleted, + RestoreJobStatusAborted, + RestoreJobStatusFailed, + } +} + const ( // StorageClassWarm is a StorageClass enum value StorageClassWarm = "WARM" @@ -12173,6 +12603,15 @@ const ( StorageClassDeleted = "DELETED" ) +// StorageClass_Values returns all elements of the StorageClass enum +func StorageClass_Values() []string { + return []string{ + StorageClassWarm, + StorageClassCold, + StorageClassDeleted, + } +} + const ( // VaultEventBackupJobStarted is a VaultEvent enum value VaultEventBackupJobStarted = "BACKUP_JOB_STARTED" @@ -12219,3 +12658,24 @@ const ( // VaultEventBackupPlanModified is a VaultEvent enum value VaultEventBackupPlanModified = "BACKUP_PLAN_MODIFIED" ) + +// VaultEvent_Values returns all elements of the VaultEvent enum +func VaultEvent_Values() []string { + return []string{ + VaultEventBackupJobStarted, + VaultEventBackupJobCompleted, + VaultEventBackupJobSuccessful, + VaultEventBackupJobFailed, + VaultEventBackupJobExpired, + VaultEventRestoreJobStarted, + VaultEventRestoreJobCompleted, + VaultEventRestoreJobSuccessful, + VaultEventRestoreJobFailed, + VaultEventCopyJobStarted, + VaultEventCopyJobSuccessful, + VaultEventCopyJobFailed, + VaultEventRecoveryPointModified, + VaultEventBackupPlanCreated, + VaultEventBackupPlanModified, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/batch/api.go b/vendor/github.com/aws/aws-sdk-go/service/batch/api.go index 025c323950d..32cfab98d83 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/batch/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/batch/api.go @@ -6180,6 +6180,14 @@ const ( ArrayJobDependencySequential = "SEQUENTIAL" ) +// ArrayJobDependency_Values returns all elements of the ArrayJobDependency enum +func ArrayJobDependency_Values() []string { + return []string{ + ArrayJobDependencyNToN, + ArrayJobDependencySequential, + } +} + const ( // CEStateEnabled is a CEState enum value CEStateEnabled = "ENABLED" @@ -6188,6 +6196,14 @@ const ( CEStateDisabled = "DISABLED" ) +// CEState_Values returns all elements of the CEState enum +func CEState_Values() []string { + return []string{ + CEStateEnabled, + CEStateDisabled, + } +} + const ( // CEStatusCreating is a CEStatus enum value CEStatusCreating = "CREATING" @@ -6208,6 +6224,18 @@ const ( CEStatusInvalid = "INVALID" ) +// CEStatus_Values returns all elements of the CEStatus enum +func CEStatus_Values() []string { + return []string{ + CEStatusCreating, + CEStatusUpdating, + CEStatusDeleting, + CEStatusDeleted, + CEStatusValid, + CEStatusInvalid, + } +} + const ( // CETypeManaged is a CEType enum value CETypeManaged = "MANAGED" @@ -6216,6 +6244,14 @@ const ( CETypeUnmanaged = "UNMANAGED" ) +// CEType_Values returns all elements of the CEType enum +func CEType_Values() []string { + return []string{ + CETypeManaged, + CETypeUnmanaged, + } +} + const ( // CRAllocationStrategyBestFit is a CRAllocationStrategy enum value CRAllocationStrategyBestFit = "BEST_FIT" @@ -6227,6 +6263,15 @@ const ( CRAllocationStrategySpotCapacityOptimized = "SPOT_CAPACITY_OPTIMIZED" ) +// CRAllocationStrategy_Values returns all elements of the CRAllocationStrategy enum +func CRAllocationStrategy_Values() []string { + return []string{ + CRAllocationStrategyBestFit, + CRAllocationStrategyBestFitProgressive, + CRAllocationStrategySpotCapacityOptimized, + } +} + const ( // CRTypeEc2 is a CRType enum value CRTypeEc2 = "EC2" @@ -6235,6 +6280,14 @@ const ( CRTypeSpot = "SPOT" ) +// CRType_Values returns all elements of the CRType enum +func CRType_Values() []string { + return []string{ + CRTypeEc2, + CRTypeSpot, + } +} + const ( // DeviceCgroupPermissionRead is a DeviceCgroupPermission enum value DeviceCgroupPermissionRead = "READ" @@ -6246,6 +6299,15 @@ const ( DeviceCgroupPermissionMknod = "MKNOD" ) +// DeviceCgroupPermission_Values returns all elements of the DeviceCgroupPermission enum +func DeviceCgroupPermission_Values() []string { + return []string{ + DeviceCgroupPermissionRead, + DeviceCgroupPermissionWrite, + DeviceCgroupPermissionMknod, + } +} + const ( // JQStateEnabled is a JQState enum value JQStateEnabled = "ENABLED" @@ -6254,6 +6316,14 @@ const ( JQStateDisabled = "DISABLED" ) +// JQState_Values returns all elements of the JQState enum +func JQState_Values() []string { + return []string{ + JQStateEnabled, + JQStateDisabled, + } +} + const ( // JQStatusCreating is a JQStatus enum value JQStatusCreating = "CREATING" @@ -6274,6 +6344,18 @@ const ( JQStatusInvalid = "INVALID" ) +// JQStatus_Values returns all elements of the JQStatus enum +func JQStatus_Values() []string { + return []string{ + JQStatusCreating, + JQStatusUpdating, + JQStatusDeleting, + JQStatusDeleted, + JQStatusValid, + JQStatusInvalid, + } +} + const ( // JobDefinitionTypeContainer is a JobDefinitionType enum value JobDefinitionTypeContainer = "container" @@ -6282,6 +6364,14 @@ const ( JobDefinitionTypeMultinode = "multinode" ) +// JobDefinitionType_Values returns all elements of the JobDefinitionType enum +func JobDefinitionType_Values() []string { + return []string{ + JobDefinitionTypeContainer, + JobDefinitionTypeMultinode, + } +} + const ( // JobStatusSubmitted is a JobStatus enum value JobStatusSubmitted = "SUBMITTED" @@ -6305,7 +6395,27 @@ const ( JobStatusFailed = "FAILED" ) +// JobStatus_Values returns all elements of the JobStatus enum +func JobStatus_Values() []string { + return []string{ + JobStatusSubmitted, + JobStatusPending, + JobStatusRunnable, + JobStatusStarting, + JobStatusRunning, + JobStatusSucceeded, + JobStatusFailed, + } +} + const ( // ResourceTypeGpu is a ResourceType enum value ResourceTypeGpu = "GPU" ) + +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeGpu, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/budgets/api.go b/vendor/github.com/aws/aws-sdk-go/service/budgets/api.go index 0673e50561e..9e2944a0a09 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/budgets/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/budgets/api.go @@ -4210,6 +4210,18 @@ const ( BudgetTypeSavingsPlansCoverage = "SAVINGS_PLANS_COVERAGE" ) +// BudgetType_Values returns all elements of the BudgetType enum +func BudgetType_Values() []string { + return []string{ + BudgetTypeUsage, + BudgetTypeCost, + BudgetTypeRiUtilization, + BudgetTypeRiCoverage, + BudgetTypeSavingsPlansUtilization, + BudgetTypeSavingsPlansCoverage, + } +} + // The comparison operator of a notification. Currently the service supports // the following operators: // @@ -4225,6 +4237,15 @@ const ( ComparisonOperatorEqualTo = "EQUAL_TO" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorGreaterThan, + ComparisonOperatorLessThan, + ComparisonOperatorEqualTo, + } +} + const ( // NotificationStateOk is a NotificationState enum value NotificationStateOk = "OK" @@ -4233,6 +4254,14 @@ const ( NotificationStateAlarm = "ALARM" ) +// NotificationState_Values returns all elements of the NotificationState enum +func NotificationState_Values() []string { + return []string{ + NotificationStateOk, + NotificationStateAlarm, + } +} + // The type of a notification. It must be ACTUAL or FORECASTED. const ( // NotificationTypeActual is a NotificationType enum value @@ -4242,6 +4271,14 @@ const ( NotificationTypeForecasted = "FORECASTED" ) +// NotificationType_Values returns all elements of the NotificationType enum +func NotificationType_Values() []string { + return []string{ + NotificationTypeActual, + NotificationTypeForecasted, + } +} + // The subscription type of the subscriber. It can be SMS or EMAIL. const ( // SubscriptionTypeSns is a SubscriptionType enum value @@ -4251,6 +4288,14 @@ const ( SubscriptionTypeEmail = "EMAIL" ) +// SubscriptionType_Values returns all elements of the SubscriptionType enum +func SubscriptionType_Values() []string { + return []string{ + SubscriptionTypeSns, + SubscriptionTypeEmail, + } +} + // The type of threshold for a notification. It can be PERCENTAGE or ABSOLUTE_VALUE. const ( // ThresholdTypePercentage is a ThresholdType enum value @@ -4260,6 +4305,14 @@ const ( ThresholdTypeAbsoluteValue = "ABSOLUTE_VALUE" ) +// ThresholdType_Values returns all elements of the ThresholdType enum +func ThresholdType_Values() []string { + return []string{ + ThresholdTypePercentage, + ThresholdTypeAbsoluteValue, + } +} + // The time unit of the budget, such as MONTHLY or QUARTERLY. const ( // TimeUnitDaily is a TimeUnit enum value @@ -4274,3 +4327,13 @@ const ( // TimeUnitAnnually is a TimeUnit enum value TimeUnitAnnually = "ANNUALLY" ) + +// TimeUnit_Values returns all elements of the TimeUnit enum +func TimeUnit_Values() []string { + return []string{ + TimeUnitDaily, + TimeUnitMonthly, + TimeUnitQuarterly, + TimeUnitAnnually, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloud9/api.go b/vendor/github.com/aws/aws-sdk-go/service/cloud9/api.go index fd1fea5ce78..df2c680ef50 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloud9/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloud9/api.go @@ -1063,6 +1063,9 @@ func (c *Cloud9) TagResourceRequest(input *TagResourceInput) (req *request.Reque // * BadRequestException // The target request is invalid. // +// * ConcurrentAccessException +// A concurrent access issue occurred. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/cloud9-2017-09-23/TagResource func (c *Cloud9) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { req, out := c.TagResourceRequest(input) @@ -1149,6 +1152,9 @@ func (c *Cloud9) UntagResourceRequest(input *UntagResourceInput) (req *request.R // * BadRequestException // The target request is invalid. // +// * ConcurrentAccessException +// A concurrent access issue occurred. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/cloud9-2017-09-23/UntagResource func (c *Cloud9) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { req, out := c.UntagResourceRequest(input) @@ -1423,6 +1429,62 @@ func (s *BadRequestException) RequestID() string { return s.RespMetadata.RequestID } +// A concurrent access issue occurred. +type ConcurrentAccessException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ConcurrentAccessException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ConcurrentAccessException) GoString() string { + return s.String() +} + +func newErrorConcurrentAccessException(v protocol.ResponseMetadata) error { + return &ConcurrentAccessException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ConcurrentAccessException) Code() string { + return "ConcurrentAccessException" +} + +// Message returns the exception's message. +func (s *ConcurrentAccessException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ConcurrentAccessException) OrigErr() error { + return nil +} + +func (s *ConcurrentAccessException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ConcurrentAccessException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ConcurrentAccessException) RequestID() string { + return s.RespMetadata.RequestID +} + // A conflict occurred. type ConflictException struct { _ struct{} `type:"structure"` @@ -1493,6 +1555,9 @@ type CreateEnvironmentEC2Input struct { // in the Amazon EC2 API Reference. ClientRequestToken *string `locationName:"clientRequestToken" type:"string"` + // The connection type used for connecting to an Amazon EC2 environment. + ConnectionType *string `locationName:"connectionType" type:"string" enum:"ConnectionType"` + // The description of the environment to create. Description *string `locationName:"description" type:"string" sensitive:"true"` @@ -1579,6 +1644,12 @@ func (s *CreateEnvironmentEC2Input) SetClientRequestToken(v string) *CreateEnvir return s } +// SetConnectionType sets the ConnectionType field's value. +func (s *CreateEnvironmentEC2Input) SetConnectionType(v string) *CreateEnvironmentEC2Input { + s.ConnectionType = &v + return s +} + // SetDescription sets the Description field's value. func (s *CreateEnvironmentEC2Input) SetDescription(v string) *CreateEnvironmentEC2Input { s.Description = &v @@ -2117,6 +2188,9 @@ type Environment struct { // The Amazon Resource Name (ARN) of the environment. Arn *string `locationName:"arn" type:"string"` + // The connection type used for connecting to an Amazon EC2 environment. + ConnectionType *string `locationName:"connectionType" type:"string" enum:"ConnectionType"` + // The description for the environment. Description *string `locationName:"description" type:"string" sensitive:"true"` @@ -2157,6 +2231,12 @@ func (s *Environment) SetArn(v string) *Environment { return s } +// SetConnectionType sets the ConnectionType field's value. +func (s *Environment) SetConnectionType(v string) *Environment { + s.ConnectionType = &v + return s +} + // SetDescription sets the Description field's value. func (s *Environment) SetDescription(v string) *Environment { s.Description = &v @@ -3104,6 +3184,22 @@ func (s UpdateEnvironmentOutput) GoString() string { return s.String() } +const ( + // ConnectionTypeConnectSsh is a ConnectionType enum value + ConnectionTypeConnectSsh = "CONNECT_SSH" + + // ConnectionTypeConnectSsm is a ConnectionType enum value + ConnectionTypeConnectSsm = "CONNECT_SSM" +) + +// ConnectionType_Values returns all elements of the ConnectionType enum +func ConnectionType_Values() []string { + return []string{ + ConnectionTypeConnectSsh, + ConnectionTypeConnectSsm, + } +} + const ( // EnvironmentLifecycleStatusCreating is a EnvironmentLifecycleStatus enum value EnvironmentLifecycleStatusCreating = "CREATING" @@ -3121,6 +3217,17 @@ const ( EnvironmentLifecycleStatusDeleteFailed = "DELETE_FAILED" ) +// EnvironmentLifecycleStatus_Values returns all elements of the EnvironmentLifecycleStatus enum +func EnvironmentLifecycleStatus_Values() []string { + return []string{ + EnvironmentLifecycleStatusCreating, + EnvironmentLifecycleStatusCreated, + EnvironmentLifecycleStatusCreateFailed, + EnvironmentLifecycleStatusDeleting, + EnvironmentLifecycleStatusDeleteFailed, + } +} + const ( // EnvironmentStatusError is a EnvironmentStatus enum value EnvironmentStatusError = "error" @@ -3144,6 +3251,19 @@ const ( EnvironmentStatusDeleting = "deleting" ) +// EnvironmentStatus_Values returns all elements of the EnvironmentStatus enum +func EnvironmentStatus_Values() []string { + return []string{ + EnvironmentStatusError, + EnvironmentStatusCreating, + EnvironmentStatusConnecting, + EnvironmentStatusReady, + EnvironmentStatusStopping, + EnvironmentStatusStopped, + EnvironmentStatusDeleting, + } +} + const ( // EnvironmentTypeSsh is a EnvironmentType enum value EnvironmentTypeSsh = "ssh" @@ -3152,6 +3272,14 @@ const ( EnvironmentTypeEc2 = "ec2" ) +// EnvironmentType_Values returns all elements of the EnvironmentType enum +func EnvironmentType_Values() []string { + return []string{ + EnvironmentTypeSsh, + EnvironmentTypeEc2, + } +} + const ( // MemberPermissionsReadWrite is a MemberPermissions enum value MemberPermissionsReadWrite = "read-write" @@ -3160,6 +3288,14 @@ const ( MemberPermissionsReadOnly = "read-only" ) +// MemberPermissions_Values returns all elements of the MemberPermissions enum +func MemberPermissions_Values() []string { + return []string{ + MemberPermissionsReadWrite, + MemberPermissionsReadOnly, + } +} + const ( // PermissionsOwner is a Permissions enum value PermissionsOwner = "owner" @@ -3170,3 +3306,12 @@ const ( // PermissionsReadOnly is a Permissions enum value PermissionsReadOnly = "read-only" ) + +// Permissions_Values returns all elements of the Permissions enum +func Permissions_Values() []string { + return []string{ + PermissionsOwner, + PermissionsReadWrite, + PermissionsReadOnly, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloud9/errors.go b/vendor/github.com/aws/aws-sdk-go/service/cloud9/errors.go index 0318a99b302..308ab4f0b0d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloud9/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloud9/errors.go @@ -14,6 +14,12 @@ const ( // The target request is invalid. ErrCodeBadRequestException = "BadRequestException" + // ErrCodeConcurrentAccessException for service response error code + // "ConcurrentAccessException". + // + // A concurrent access issue occurred. + ErrCodeConcurrentAccessException = "ConcurrentAccessException" + // ErrCodeConflictException for service response error code // "ConflictException". // @@ -53,6 +59,7 @@ const ( var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "BadRequestException": newErrorBadRequestException, + "ConcurrentAccessException": newErrorConcurrentAccessException, "ConflictException": newErrorConflictException, "ForbiddenException": newErrorForbiddenException, "InternalServerErrorException": newErrorInternalServerErrorException, 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 d92ee2227bc..f8b384c0a65 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 @@ -1055,6 +1055,12 @@ func (c *CloudFormation) DescribeAccountLimitsRequest(input *DescribeAccountLimi Name: opDescribeAccountLimits, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "", + TruncationToken: "", + }, } if input == nil { @@ -1101,6 +1107,58 @@ func (c *CloudFormation) DescribeAccountLimitsWithContext(ctx aws.Context, input return out, req.Send() } +// DescribeAccountLimitsPages iterates over the pages of a DescribeAccountLimits operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeAccountLimits 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 DescribeAccountLimits operation. +// pageNum := 0 +// err := client.DescribeAccountLimitsPages(params, +// func(page *cloudformation.DescribeAccountLimitsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CloudFormation) DescribeAccountLimitsPages(input *DescribeAccountLimitsInput, fn func(*DescribeAccountLimitsOutput, bool) bool) error { + return c.DescribeAccountLimitsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAccountLimitsPagesWithContext same as DescribeAccountLimitsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeAccountLimitsPagesWithContext(ctx aws.Context, input *DescribeAccountLimitsInput, fn func(*DescribeAccountLimitsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAccountLimitsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAccountLimitsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeAccountLimitsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeChangeSet = "DescribeChangeSet" // DescribeChangeSetRequest generates a "aws/request.Request" representing the @@ -3038,6 +3096,12 @@ func (c *CloudFormation) ListChangeSetsRequest(input *ListChangeSetsInput) (req Name: opListChangeSets, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "", + TruncationToken: "", + }, } if input == nil { @@ -3083,6 +3147,58 @@ func (c *CloudFormation) ListChangeSetsWithContext(ctx aws.Context, input *ListC return out, req.Send() } +// ListChangeSetsPages iterates over the pages of a ListChangeSets operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListChangeSets 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 ListChangeSets operation. +// pageNum := 0 +// err := client.ListChangeSetsPages(params, +// func(page *cloudformation.ListChangeSetsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CloudFormation) ListChangeSetsPages(input *ListChangeSetsInput, fn func(*ListChangeSetsOutput, bool) bool) error { + return c.ListChangeSetsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListChangeSetsPagesWithContext same as ListChangeSetsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListChangeSetsPagesWithContext(ctx aws.Context, input *ListChangeSetsInput, fn func(*ListChangeSetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListChangeSetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListChangeSetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListChangeSetsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListExports = "ListExports" // ListExportsRequest generates a "aws/request.Request" representing the @@ -3389,6 +3505,12 @@ func (c *CloudFormation) ListStackInstancesRequest(input *ListStackInstancesInpu Name: opListStackInstances, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3404,7 +3526,7 @@ func (c *CloudFormation) ListStackInstancesRequest(input *ListStackInstancesInpu // // Returns summary information about stack instances that are associated with // the specified stack set. You can filter for stack instances that are associated -// with a specific AWS account name or Region. +// with a specific AWS account name or Region, or that have a specific status. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3439,6 +3561,58 @@ func (c *CloudFormation) ListStackInstancesWithContext(ctx aws.Context, input *L return out, req.Send() } +// ListStackInstancesPages iterates over the pages of a ListStackInstances operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListStackInstances 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 ListStackInstances operation. +// pageNum := 0 +// err := client.ListStackInstancesPages(params, +// func(page *cloudformation.ListStackInstancesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CloudFormation) ListStackInstancesPages(input *ListStackInstancesInput, fn func(*ListStackInstancesOutput, bool) bool) error { + return c.ListStackInstancesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListStackInstancesPagesWithContext same as ListStackInstancesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListStackInstancesPagesWithContext(ctx aws.Context, input *ListStackInstancesInput, fn func(*ListStackInstancesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListStackInstancesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListStackInstancesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListStackInstancesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListStackResources = "ListStackResources" // ListStackResourcesRequest generates a "aws/request.Request" representing the @@ -3605,6 +3779,12 @@ func (c *CloudFormation) ListStackSetOperationResultsRequest(input *ListStackSet Name: opListStackSetOperationResults, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3656,6 +3836,58 @@ func (c *CloudFormation) ListStackSetOperationResultsWithContext(ctx aws.Context return out, req.Send() } +// ListStackSetOperationResultsPages iterates over the pages of a ListStackSetOperationResults operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListStackSetOperationResults 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 ListStackSetOperationResults operation. +// pageNum := 0 +// err := client.ListStackSetOperationResultsPages(params, +// func(page *cloudformation.ListStackSetOperationResultsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CloudFormation) ListStackSetOperationResultsPages(input *ListStackSetOperationResultsInput, fn func(*ListStackSetOperationResultsOutput, bool) bool) error { + return c.ListStackSetOperationResultsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListStackSetOperationResultsPagesWithContext same as ListStackSetOperationResultsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListStackSetOperationResultsPagesWithContext(ctx aws.Context, input *ListStackSetOperationResultsInput, fn func(*ListStackSetOperationResultsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListStackSetOperationResultsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListStackSetOperationResultsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListStackSetOperationResultsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListStackSetOperations = "ListStackSetOperations" // ListStackSetOperationsRequest generates a "aws/request.Request" representing the @@ -3687,6 +3919,12 @@ func (c *CloudFormation) ListStackSetOperationsRequest(input *ListStackSetOperat Name: opListStackSetOperations, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3735,6 +3973,58 @@ func (c *CloudFormation) ListStackSetOperationsWithContext(ctx aws.Context, inpu return out, req.Send() } +// ListStackSetOperationsPages iterates over the pages of a ListStackSetOperations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListStackSetOperations 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 ListStackSetOperations operation. +// pageNum := 0 +// err := client.ListStackSetOperationsPages(params, +// func(page *cloudformation.ListStackSetOperationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CloudFormation) ListStackSetOperationsPages(input *ListStackSetOperationsInput, fn func(*ListStackSetOperationsOutput, bool) bool) error { + return c.ListStackSetOperationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListStackSetOperationsPagesWithContext same as ListStackSetOperationsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListStackSetOperationsPagesWithContext(ctx aws.Context, input *ListStackSetOperationsInput, fn func(*ListStackSetOperationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListStackSetOperationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListStackSetOperationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListStackSetOperationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListStackSets = "ListStackSets" // ListStackSetsRequest generates a "aws/request.Request" representing the @@ -3766,6 +4056,12 @@ func (c *CloudFormation) ListStackSetsRequest(input *ListStackSetsInput) (req *r Name: opListStackSets, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3810,6 +4106,58 @@ func (c *CloudFormation) ListStackSetsWithContext(ctx aws.Context, input *ListSt return out, req.Send() } +// ListStackSetsPages iterates over the pages of a ListStackSets operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListStackSets 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 ListStackSets operation. +// pageNum := 0 +// err := client.ListStackSetsPages(params, +// func(page *cloudformation.ListStackSetsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CloudFormation) ListStackSetsPages(input *ListStackSetsInput, fn func(*ListStackSetsOutput, bool) bool) error { + return c.ListStackSetsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListStackSetsPagesWithContext same as ListStackSetsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListStackSetsPagesWithContext(ctx aws.Context, input *ListStackSetsInput, fn func(*ListStackSetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListStackSetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListStackSetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListStackSetsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListStacks = "ListStacks" // ListStacksRequest generates a "aws/request.Request" representing the @@ -8851,6 +9199,9 @@ type DescribeTypeOutput struct { // role to provide your resource type with the appropriate credentials. ExecutionRoleArn *string `min:"1" type:"string"` + // Whether the specified type version is set as the default version. + IsDefaultVersion *bool `type:"boolean"` + // When the specified type version was registered. LastUpdated *time.Time `type:"timestamp"` @@ -8952,6 +9303,12 @@ func (s *DescribeTypeOutput) SetExecutionRoleArn(v string) *DescribeTypeOutput { return s } +// SetIsDefaultVersion sets the IsDefaultVersion field's value. +func (s *DescribeTypeOutput) SetIsDefaultVersion(v bool) *DescribeTypeOutput { + s.IsDefaultVersion = &v + return s +} + // SetLastUpdated sets the LastUpdated field's value. func (s *DescribeTypeOutput) SetLastUpdated(v time.Time) *DescribeTypeOutput { s.LastUpdated = &v @@ -10220,6 +10577,9 @@ func (s *ListImportsOutput) SetNextToken(v string) *ListImportsOutput { type ListStackInstancesInput struct { _ struct{} `type:"structure"` + // The status that stack instances are filtered by. + Filters []*StackInstanceFilter `type:"list"` + // The maximum number of results to be returned with a single call. If the number // of available results exceeds this maximum, the response includes a NextToken // value that you can assign to the NextToken request parameter to get the next @@ -10268,6 +10628,16 @@ func (s *ListStackInstancesInput) Validate() error { if s.StackSetName == nil { invalidParams.Add(request.NewErrParamRequired("StackSetName")) } + if s.Filters != nil { + for i, v := range s.Filters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -10275,6 +10645,12 @@ func (s *ListStackInstancesInput) Validate() error { return nil } +// SetFilters sets the Filters field's value. +func (s *ListStackInstancesInput) SetFilters(v []*StackInstanceFilter) *ListStackInstancesInput { + s.Filters = v + return s +} + // SetMaxResults sets the MaxResults field's value. func (s *ListStackInstancesInput) SetMaxResults(v int64) *ListStackInstancesInput { s.MaxResults = &v @@ -11798,12 +12174,15 @@ type RegisterTypeInput struct { // if the request is submitted multiple times. ClientRequestToken *string `min:"1" type:"string"` - // The Amazon Resource Name (ARN) of the IAM execution role to use to register - // the type. If your resource type calls AWS APIs in any of its handlers, you - // must create an IAM execution role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) + // The Amazon Resource Name (ARN) of the IAM role for CloudFormation to assume + // when invoking the resource provider. If your resource type calls AWS APIs + // in any of its handlers, you must create an IAM execution role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) // that includes the necessary permissions to call those AWS APIs, and provision - // that execution role in your account. CloudFormation then assumes that execution - // role to provide your resource type with the appropriate credentials. + // that execution role in your account. When CloudFormation needs to invoke + // the resource provider handler, CloudFormation assumes this execution role + // to create a temporary session token, which it then passes to the resource + // provider handler, thereby supplying your resource provider with the appropriate + // credentials. ExecutionRoleArn *string `min:"1" type:"string"` // Specifies logging configuration information for a type. @@ -12259,6 +12638,9 @@ type ResourceToImport struct { ResourceIdentifier map[string]*string `min:"1" type:"map" required:"true"` // The type of resource to import into your stack, such as AWS::S3::Bucket. + // For a list of supported resource types, see Resources that support import + // operations (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import-supported-resources.html) + // in the AWS CloudFormation User Guide. // // ResourceType is a required field ResourceType *string `min:"1" type:"string" required:"true"` @@ -13276,7 +13658,8 @@ type StackInstance struct { // which drift detection has not yet been performed. LastDriftCheckTimestamp *time.Time `type:"timestamp"` - // Reserved for internal use. No data returned. + // [Service-managed permissions] The organization root ID or organizational + // unit (OU) IDs that you specified for DeploymentTargets (https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html). OrganizationalUnitId *string `type:"string"` // A list of parameters from the stack set template whose values have been overridden @@ -13289,6 +13672,9 @@ type StackInstance struct { // The ID of the stack instance. StackId *string `type:"string"` + // The detailed status of the stack instance. + StackInstanceStatus *StackInstanceComprehensiveStatus `type:"structure"` + // The name or unique ID of the stack set that the stack instance is associated // with. StackSetId *string `type:"string"` @@ -13367,6 +13753,12 @@ func (s *StackInstance) SetStackId(v string) *StackInstance { return s } +// SetStackInstanceStatus sets the StackInstanceStatus field's value. +func (s *StackInstance) SetStackInstanceStatus(v *StackInstanceComprehensiveStatus) *StackInstance { + s.StackInstanceStatus = v + return s +} + // SetStackSetId sets the StackSetId field's value. func (s *StackInstance) SetStackSetId(v string) *StackInstance { s.StackSetId = &v @@ -13385,6 +13777,97 @@ func (s *StackInstance) SetStatusReason(v string) *StackInstance { return s } +// The detailed status of the stack instance. +type StackInstanceComprehensiveStatus struct { + _ struct{} `type:"structure"` + + // * CANCELLED: The operation in the specified account and Region has been + // cancelled. This is either because a user has stopped the stack set operation, + // or because the failure tolerance of the stack set operation has been exceeded. + // + // * FAILED: The operation in the specified account and Region failed. If + // the stack set operation fails in enough accounts within a Region, the + // failure tolerance for the stack set operation as a whole might be exceeded. + // + // * INOPERABLE: A DeleteStackInstances operation has failed and left the + // stack in an unstable state. Stacks in this state are excluded from further + // UpdateStackSet operations. You might need to perform a DeleteStackInstances + // operation, with RetainStacks set to true, to delete the stack instance, + // and then delete the stack manually. + // + // * PENDING: The operation in the specified account and Region has yet to + // start. + // + // * RUNNING: The operation in the specified account and Region is currently + // in progress. + // + // * SUCCEEDED: The operation in the specified account and Region completed + // successfully. + DetailedStatus *string `type:"string" enum:"StackInstanceDetailedStatus"` +} + +// String returns the string representation +func (s StackInstanceComprehensiveStatus) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StackInstanceComprehensiveStatus) GoString() string { + return s.String() +} + +// SetDetailedStatus sets the DetailedStatus field's value. +func (s *StackInstanceComprehensiveStatus) SetDetailedStatus(v string) *StackInstanceComprehensiveStatus { + s.DetailedStatus = &v + return s +} + +// The status that stack instances are filtered by. +type StackInstanceFilter struct { + _ struct{} `type:"structure"` + + // The type of filter to apply. + Name *string `type:"string" enum:"StackInstanceFilterName"` + + // The status to filter by. + Values *string `min:"6" type:"string"` +} + +// String returns the string representation +func (s StackInstanceFilter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StackInstanceFilter) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StackInstanceFilter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StackInstanceFilter"} + if s.Values != nil && len(*s.Values) < 6 { + invalidParams.Add(request.NewErrParamMinLen("Values", 6)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *StackInstanceFilter) SetName(v string) *StackInstanceFilter { + s.Name = &v + return s +} + +// SetValues sets the Values field's value. +func (s *StackInstanceFilter) SetValues(v string) *StackInstanceFilter { + s.Values = &v + return s +} + // The structure that contains summary information about a stack instance. type StackInstanceSummary struct { _ struct{} `type:"structure"` @@ -13415,7 +13898,8 @@ type StackInstanceSummary struct { // which drift detection has not yet been performed. LastDriftCheckTimestamp *time.Time `type:"timestamp"` - // Reserved for internal use. No data returned. + // [Service-managed permissions] The organization root ID or organizational + // unit (OU) IDs that you specified for DeploymentTargets (https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html). OrganizationalUnitId *string `type:"string"` // The name of the AWS Region that the stack instance is associated with. @@ -13424,6 +13908,9 @@ type StackInstanceSummary struct { // The ID of the stack instance. StackId *string `type:"string"` + // The detailed status of the stack instance. + StackInstanceStatus *StackInstanceComprehensiveStatus `type:"structure"` + // The name or unique ID of the stack set that the stack instance is associated // with. StackSetId *string `type:"string"` @@ -13495,6 +13982,12 @@ func (s *StackInstanceSummary) SetStackId(v string) *StackInstanceSummary { return s } +// SetStackInstanceStatus sets the StackInstanceStatus field's value. +func (s *StackInstanceSummary) SetStackInstanceStatus(v *StackInstanceComprehensiveStatus) *StackInstanceSummary { + s.StackInstanceStatus = v + return s +} + // SetStackSetId sets the StackSetId field's value. func (s *StackInstanceSummary) SetStackSetId(v string) *StackInstanceSummary { s.StackSetId = &v @@ -14148,7 +14641,8 @@ type StackSet struct { // groups can include in their stack sets. ExecutionRoleName *string `min:"1" type:"string"` - // Reserved for internal use. No data returned. + // [Service-managed permissions] The organization root ID or organizational + // unit (OU) IDs that you specified for DeploymentTargets (https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html). OrganizationalUnitIds []*string `type:"list"` // A list of input parameters for a stack set. @@ -14638,8 +15132,8 @@ type StackSetOperationPreferences struct { FailureTolerancePercentage *int64 `type:"integer"` // The maximum number of accounts in which to perform this operation at one - // time. This is dependent on the value of FailureToleranceCount—MaxConcurrentCount - // is at most one more than the FailureToleranceCount . + // time. This is dependent on the value of FailureToleranceCount. MaxConcurrentCount + // is at most one more than the FailureToleranceCount. // // Note that this setting lets you specify the maximum for operations. For large // deployments, under certain circumstances the actual number of accounts acted @@ -14738,7 +15232,8 @@ type StackSetOperationResultSummary struct { // before proceeding with stack set operations in an account AccountGateResult *AccountGateResult `type:"structure"` - // Reserved for internal use. No data returned. + // [Service-managed permissions] The organization root ID or organizational + // unit (OU) IDs that you specified for DeploymentTargets (https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_DeploymentTargets.html). OrganizationalUnitId *string `type:"string"` // The name of the AWS Region for this operation result. @@ -15424,6 +15919,9 @@ type TypeVersionSummary struct { // The description of the type version. Description *string `min:"1" type:"string"` + // Whether the specified type version is set as the default version. + IsDefaultVersion *bool `type:"boolean"` + // When the version was registered. TimeCreated *time.Time `type:"timestamp"` @@ -15461,6 +15959,12 @@ func (s *TypeVersionSummary) SetDescription(v string) *TypeVersionSummary { return s } +// SetIsDefaultVersion sets the IsDefaultVersion field's value. +func (s *TypeVersionSummary) SetIsDefaultVersion(v bool) *TypeVersionSummary { + s.IsDefaultVersion = &v + return s +} + // SetTimeCreated sets the TimeCreated field's value. func (s *TypeVersionSummary) SetTimeCreated(v time.Time) *TypeVersionSummary { s.TimeCreated = &v @@ -16650,6 +17154,15 @@ const ( AccountGateStatusSkipped = "SKIPPED" ) +// AccountGateStatus_Values returns all elements of the AccountGateStatus enum +func AccountGateStatus_Values() []string { + return []string{ + AccountGateStatusSucceeded, + AccountGateStatusFailed, + AccountGateStatusSkipped, + } +} + const ( // CapabilityCapabilityIam is a Capability enum value CapabilityCapabilityIam = "CAPABILITY_IAM" @@ -16661,6 +17174,15 @@ const ( CapabilityCapabilityAutoExpand = "CAPABILITY_AUTO_EXPAND" ) +// Capability_Values returns all elements of the Capability enum +func Capability_Values() []string { + return []string{ + CapabilityCapabilityIam, + CapabilityCapabilityNamedIam, + CapabilityCapabilityAutoExpand, + } +} + const ( // ChangeActionAdd is a ChangeAction enum value ChangeActionAdd = "Add" @@ -16675,6 +17197,16 @@ const ( ChangeActionImport = "Import" ) +// ChangeAction_Values returns all elements of the ChangeAction enum +func ChangeAction_Values() []string { + return []string{ + ChangeActionAdd, + ChangeActionModify, + ChangeActionRemove, + ChangeActionImport, + } +} + const ( // ChangeSetStatusCreatePending is a ChangeSetStatus enum value ChangeSetStatusCreatePending = "CREATE_PENDING" @@ -16692,6 +17224,17 @@ const ( ChangeSetStatusFailed = "FAILED" ) +// ChangeSetStatus_Values returns all elements of the ChangeSetStatus enum +func ChangeSetStatus_Values() []string { + return []string{ + ChangeSetStatusCreatePending, + ChangeSetStatusCreateInProgress, + ChangeSetStatusCreateComplete, + ChangeSetStatusDeleteComplete, + ChangeSetStatusFailed, + } +} + const ( // ChangeSetTypeCreate is a ChangeSetType enum value ChangeSetTypeCreate = "CREATE" @@ -16703,6 +17246,15 @@ const ( ChangeSetTypeImport = "IMPORT" ) +// ChangeSetType_Values returns all elements of the ChangeSetType enum +func ChangeSetType_Values() []string { + return []string{ + ChangeSetTypeCreate, + ChangeSetTypeUpdate, + ChangeSetTypeImport, + } +} + const ( // ChangeSourceResourceReference is a ChangeSource enum value ChangeSourceResourceReference = "ResourceReference" @@ -16720,11 +17272,29 @@ const ( ChangeSourceAutomatic = "Automatic" ) +// ChangeSource_Values returns all elements of the ChangeSource enum +func ChangeSource_Values() []string { + return []string{ + ChangeSourceResourceReference, + ChangeSourceParameterReference, + ChangeSourceResourceAttribute, + ChangeSourceDirectModification, + ChangeSourceAutomatic, + } +} + const ( // ChangeTypeResource is a ChangeType enum value ChangeTypeResource = "Resource" ) +// ChangeType_Values returns all elements of the ChangeType enum +func ChangeType_Values() []string { + return []string{ + ChangeTypeResource, + } +} + const ( // DeprecatedStatusLive is a DeprecatedStatus enum value DeprecatedStatusLive = "LIVE" @@ -16733,6 +17303,14 @@ const ( DeprecatedStatusDeprecated = "DEPRECATED" ) +// DeprecatedStatus_Values returns all elements of the DeprecatedStatus enum +func DeprecatedStatus_Values() []string { + return []string{ + DeprecatedStatusLive, + DeprecatedStatusDeprecated, + } +} + const ( // DifferenceTypeAdd is a DifferenceType enum value DifferenceTypeAdd = "ADD" @@ -16744,6 +17322,15 @@ const ( DifferenceTypeNotEqual = "NOT_EQUAL" ) +// DifferenceType_Values returns all elements of the DifferenceType enum +func DifferenceType_Values() []string { + return []string{ + DifferenceTypeAdd, + DifferenceTypeRemove, + DifferenceTypeNotEqual, + } +} + const ( // EvaluationTypeStatic is a EvaluationType enum value EvaluationTypeStatic = "Static" @@ -16752,6 +17339,14 @@ const ( EvaluationTypeDynamic = "Dynamic" ) +// EvaluationType_Values returns all elements of the EvaluationType enum +func EvaluationType_Values() []string { + return []string{ + EvaluationTypeStatic, + EvaluationTypeDynamic, + } +} + const ( // ExecutionStatusUnavailable is a ExecutionStatus enum value ExecutionStatusUnavailable = "UNAVAILABLE" @@ -16772,6 +17367,18 @@ const ( ExecutionStatusObsolete = "OBSOLETE" ) +// ExecutionStatus_Values returns all elements of the ExecutionStatus enum +func ExecutionStatus_Values() []string { + return []string{ + ExecutionStatusUnavailable, + ExecutionStatusAvailable, + ExecutionStatusExecuteInProgress, + ExecutionStatusExecuteComplete, + ExecutionStatusExecuteFailed, + ExecutionStatusObsolete, + } +} + const ( // HandlerErrorCodeNotUpdatable is a HandlerErrorCode enum value HandlerErrorCodeNotUpdatable = "NotUpdatable" @@ -16816,6 +17423,26 @@ const ( HandlerErrorCodeInternalFailure = "InternalFailure" ) +// HandlerErrorCode_Values returns all elements of the HandlerErrorCode enum +func HandlerErrorCode_Values() []string { + return []string{ + HandlerErrorCodeNotUpdatable, + HandlerErrorCodeInvalidRequest, + HandlerErrorCodeAccessDenied, + HandlerErrorCodeInvalidCredentials, + HandlerErrorCodeAlreadyExists, + HandlerErrorCodeNotFound, + HandlerErrorCodeResourceConflict, + HandlerErrorCodeThrottling, + HandlerErrorCodeServiceLimitExceeded, + HandlerErrorCodeNotStabilized, + HandlerErrorCodeGeneralServiceException, + HandlerErrorCodeServiceInternalError, + HandlerErrorCodeNetworkFailure, + HandlerErrorCodeInternalFailure, + } +} + const ( // OnFailureDoNothing is a OnFailure enum value OnFailureDoNothing = "DO_NOTHING" @@ -16827,6 +17454,15 @@ const ( OnFailureDelete = "DELETE" ) +// OnFailure_Values returns all elements of the OnFailure enum +func OnFailure_Values() []string { + return []string{ + OnFailureDoNothing, + OnFailureRollback, + OnFailureDelete, + } +} + const ( // OperationStatusPending is a OperationStatus enum value OperationStatusPending = "PENDING" @@ -16841,6 +17477,16 @@ const ( OperationStatusFailed = "FAILED" ) +// OperationStatus_Values returns all elements of the OperationStatus enum +func OperationStatus_Values() []string { + return []string{ + OperationStatusPending, + OperationStatusInProgress, + OperationStatusSuccess, + OperationStatusFailed, + } +} + const ( // PermissionModelsServiceManaged is a PermissionModels enum value PermissionModelsServiceManaged = "SERVICE_MANAGED" @@ -16849,6 +17495,14 @@ const ( PermissionModelsSelfManaged = "SELF_MANAGED" ) +// PermissionModels_Values returns all elements of the PermissionModels enum +func PermissionModels_Values() []string { + return []string{ + PermissionModelsServiceManaged, + PermissionModelsSelfManaged, + } +} + const ( // ProvisioningTypeNonProvisionable is a ProvisioningType enum value ProvisioningTypeNonProvisionable = "NON_PROVISIONABLE" @@ -16860,6 +17514,15 @@ const ( ProvisioningTypeFullyMutable = "FULLY_MUTABLE" ) +// ProvisioningType_Values returns all elements of the ProvisioningType enum +func ProvisioningType_Values() []string { + return []string{ + ProvisioningTypeNonProvisionable, + ProvisioningTypeImmutable, + ProvisioningTypeFullyMutable, + } +} + const ( // RegistrationStatusComplete is a RegistrationStatus enum value RegistrationStatusComplete = "COMPLETE" @@ -16871,11 +17534,27 @@ const ( RegistrationStatusFailed = "FAILED" ) +// RegistrationStatus_Values returns all elements of the RegistrationStatus enum +func RegistrationStatus_Values() []string { + return []string{ + RegistrationStatusComplete, + RegistrationStatusInProgress, + RegistrationStatusFailed, + } +} + const ( // RegistryTypeResource is a RegistryType enum value RegistryTypeResource = "RESOURCE" ) +// RegistryType_Values returns all elements of the RegistryType enum +func RegistryType_Values() []string { + return []string{ + RegistryTypeResource, + } +} + const ( // ReplacementTrue is a Replacement enum value ReplacementTrue = "True" @@ -16887,6 +17566,15 @@ const ( ReplacementConditional = "Conditional" ) +// Replacement_Values returns all elements of the Replacement enum +func Replacement_Values() []string { + return []string{ + ReplacementTrue, + ReplacementFalse, + ReplacementConditional, + } +} + const ( // RequiresRecreationNever is a RequiresRecreation enum value RequiresRecreationNever = "Never" @@ -16898,6 +17586,15 @@ const ( RequiresRecreationAlways = "Always" ) +// RequiresRecreation_Values returns all elements of the RequiresRecreation enum +func RequiresRecreation_Values() []string { + return []string{ + RequiresRecreationNever, + RequiresRecreationConditionally, + RequiresRecreationAlways, + } +} + const ( // ResourceAttributeProperties is a ResourceAttribute enum value ResourceAttributeProperties = "Properties" @@ -16918,6 +17615,18 @@ const ( ResourceAttributeTags = "Tags" ) +// ResourceAttribute_Values returns all elements of the ResourceAttribute enum +func ResourceAttribute_Values() []string { + return []string{ + ResourceAttributeProperties, + ResourceAttributeMetadata, + ResourceAttributeCreationPolicy, + ResourceAttributeUpdatePolicy, + ResourceAttributeDeletionPolicy, + ResourceAttributeTags, + } +} + const ( // ResourceSignalStatusSuccess is a ResourceSignalStatus enum value ResourceSignalStatusSuccess = "SUCCESS" @@ -16926,6 +17635,14 @@ const ( ResourceSignalStatusFailure = "FAILURE" ) +// ResourceSignalStatus_Values returns all elements of the ResourceSignalStatus enum +func ResourceSignalStatus_Values() []string { + return []string{ + ResourceSignalStatusSuccess, + ResourceSignalStatusFailure, + } +} + const ( // ResourceStatusCreateInProgress is a ResourceStatus enum value ResourceStatusCreateInProgress = "CREATE_IN_PROGRESS" @@ -16976,6 +17693,28 @@ const ( ResourceStatusImportRollbackComplete = "IMPORT_ROLLBACK_COMPLETE" ) +// ResourceStatus_Values returns all elements of the ResourceStatus enum +func ResourceStatus_Values() []string { + return []string{ + ResourceStatusCreateInProgress, + ResourceStatusCreateFailed, + ResourceStatusCreateComplete, + ResourceStatusDeleteInProgress, + ResourceStatusDeleteFailed, + ResourceStatusDeleteComplete, + ResourceStatusDeleteSkipped, + ResourceStatusUpdateInProgress, + ResourceStatusUpdateFailed, + ResourceStatusUpdateComplete, + ResourceStatusImportFailed, + ResourceStatusImportComplete, + ResourceStatusImportInProgress, + ResourceStatusImportRollbackInProgress, + ResourceStatusImportRollbackFailed, + ResourceStatusImportRollbackComplete, + } +} + const ( // StackDriftDetectionStatusDetectionInProgress is a StackDriftDetectionStatus enum value StackDriftDetectionStatusDetectionInProgress = "DETECTION_IN_PROGRESS" @@ -16987,6 +17726,15 @@ const ( StackDriftDetectionStatusDetectionComplete = "DETECTION_COMPLETE" ) +// StackDriftDetectionStatus_Values returns all elements of the StackDriftDetectionStatus enum +func StackDriftDetectionStatus_Values() []string { + return []string{ + StackDriftDetectionStatusDetectionInProgress, + StackDriftDetectionStatusDetectionFailed, + StackDriftDetectionStatusDetectionComplete, + } +} + const ( // StackDriftStatusDrifted is a StackDriftStatus enum value StackDriftStatusDrifted = "DRIFTED" @@ -17001,6 +17749,60 @@ const ( StackDriftStatusNotChecked = "NOT_CHECKED" ) +// StackDriftStatus_Values returns all elements of the StackDriftStatus enum +func StackDriftStatus_Values() []string { + return []string{ + StackDriftStatusDrifted, + StackDriftStatusInSync, + StackDriftStatusUnknown, + StackDriftStatusNotChecked, + } +} + +const ( + // StackInstanceDetailedStatusPending is a StackInstanceDetailedStatus enum value + StackInstanceDetailedStatusPending = "PENDING" + + // StackInstanceDetailedStatusRunning is a StackInstanceDetailedStatus enum value + StackInstanceDetailedStatusRunning = "RUNNING" + + // StackInstanceDetailedStatusSucceeded is a StackInstanceDetailedStatus enum value + StackInstanceDetailedStatusSucceeded = "SUCCEEDED" + + // StackInstanceDetailedStatusFailed is a StackInstanceDetailedStatus enum value + StackInstanceDetailedStatusFailed = "FAILED" + + // StackInstanceDetailedStatusCancelled is a StackInstanceDetailedStatus enum value + StackInstanceDetailedStatusCancelled = "CANCELLED" + + // StackInstanceDetailedStatusInoperable is a StackInstanceDetailedStatus enum value + StackInstanceDetailedStatusInoperable = "INOPERABLE" +) + +// StackInstanceDetailedStatus_Values returns all elements of the StackInstanceDetailedStatus enum +func StackInstanceDetailedStatus_Values() []string { + return []string{ + StackInstanceDetailedStatusPending, + StackInstanceDetailedStatusRunning, + StackInstanceDetailedStatusSucceeded, + StackInstanceDetailedStatusFailed, + StackInstanceDetailedStatusCancelled, + StackInstanceDetailedStatusInoperable, + } +} + +const ( + // StackInstanceFilterNameDetailedStatus is a StackInstanceFilterName enum value + StackInstanceFilterNameDetailedStatus = "DETAILED_STATUS" +) + +// StackInstanceFilterName_Values returns all elements of the StackInstanceFilterName enum +func StackInstanceFilterName_Values() []string { + return []string{ + StackInstanceFilterNameDetailedStatus, + } +} + const ( // StackInstanceStatusCurrent is a StackInstanceStatus enum value StackInstanceStatusCurrent = "CURRENT" @@ -17012,6 +17814,15 @@ const ( StackInstanceStatusInoperable = "INOPERABLE" ) +// StackInstanceStatus_Values returns all elements of the StackInstanceStatus enum +func StackInstanceStatus_Values() []string { + return []string{ + StackInstanceStatusCurrent, + StackInstanceStatusOutdated, + StackInstanceStatusInoperable, + } +} + const ( // StackResourceDriftStatusInSync is a StackResourceDriftStatus enum value StackResourceDriftStatusInSync = "IN_SYNC" @@ -17026,6 +17837,16 @@ const ( StackResourceDriftStatusNotChecked = "NOT_CHECKED" ) +// StackResourceDriftStatus_Values returns all elements of the StackResourceDriftStatus enum +func StackResourceDriftStatus_Values() []string { + return []string{ + StackResourceDriftStatusInSync, + StackResourceDriftStatusModified, + StackResourceDriftStatusDeleted, + StackResourceDriftStatusNotChecked, + } +} + const ( // StackSetDriftDetectionStatusCompleted is a StackSetDriftDetectionStatus enum value StackSetDriftDetectionStatusCompleted = "COMPLETED" @@ -17043,6 +17864,17 @@ const ( StackSetDriftDetectionStatusStopped = "STOPPED" ) +// StackSetDriftDetectionStatus_Values returns all elements of the StackSetDriftDetectionStatus enum +func StackSetDriftDetectionStatus_Values() []string { + return []string{ + StackSetDriftDetectionStatusCompleted, + StackSetDriftDetectionStatusFailed, + StackSetDriftDetectionStatusPartialSuccess, + StackSetDriftDetectionStatusInProgress, + StackSetDriftDetectionStatusStopped, + } +} + const ( // StackSetDriftStatusDrifted is a StackSetDriftStatus enum value StackSetDriftStatusDrifted = "DRIFTED" @@ -17054,6 +17886,15 @@ const ( StackSetDriftStatusNotChecked = "NOT_CHECKED" ) +// StackSetDriftStatus_Values returns all elements of the StackSetDriftStatus enum +func StackSetDriftStatus_Values() []string { + return []string{ + StackSetDriftStatusDrifted, + StackSetDriftStatusInSync, + StackSetDriftStatusNotChecked, + } +} + const ( // StackSetOperationActionCreate is a StackSetOperationAction enum value StackSetOperationActionCreate = "CREATE" @@ -17068,6 +17909,16 @@ const ( StackSetOperationActionDetectDrift = "DETECT_DRIFT" ) +// StackSetOperationAction_Values returns all elements of the StackSetOperationAction enum +func StackSetOperationAction_Values() []string { + return []string{ + StackSetOperationActionCreate, + StackSetOperationActionUpdate, + StackSetOperationActionDelete, + StackSetOperationActionDetectDrift, + } +} + const ( // StackSetOperationResultStatusPending is a StackSetOperationResultStatus enum value StackSetOperationResultStatusPending = "PENDING" @@ -17085,6 +17936,17 @@ const ( StackSetOperationResultStatusCancelled = "CANCELLED" ) +// StackSetOperationResultStatus_Values returns all elements of the StackSetOperationResultStatus enum +func StackSetOperationResultStatus_Values() []string { + return []string{ + StackSetOperationResultStatusPending, + StackSetOperationResultStatusRunning, + StackSetOperationResultStatusSucceeded, + StackSetOperationResultStatusFailed, + StackSetOperationResultStatusCancelled, + } +} + const ( // StackSetOperationStatusRunning is a StackSetOperationStatus enum value StackSetOperationStatusRunning = "RUNNING" @@ -17105,6 +17967,18 @@ const ( StackSetOperationStatusQueued = "QUEUED" ) +// StackSetOperationStatus_Values returns all elements of the StackSetOperationStatus enum +func StackSetOperationStatus_Values() []string { + return []string{ + StackSetOperationStatusRunning, + StackSetOperationStatusSucceeded, + StackSetOperationStatusFailed, + StackSetOperationStatusStopping, + StackSetOperationStatusStopped, + StackSetOperationStatusQueued, + } +} + const ( // StackSetStatusActive is a StackSetStatus enum value StackSetStatusActive = "ACTIVE" @@ -17113,6 +17987,14 @@ const ( StackSetStatusDeleted = "DELETED" ) +// StackSetStatus_Values returns all elements of the StackSetStatus enum +func StackSetStatus_Values() []string { + return []string{ + StackSetStatusActive, + StackSetStatusDeleted, + } +} + const ( // StackStatusCreateInProgress is a StackStatus enum value StackStatusCreateInProgress = "CREATE_IN_PROGRESS" @@ -17181,6 +18063,34 @@ const ( StackStatusImportRollbackComplete = "IMPORT_ROLLBACK_COMPLETE" ) +// StackStatus_Values returns all elements of the StackStatus enum +func StackStatus_Values() []string { + return []string{ + StackStatusCreateInProgress, + StackStatusCreateFailed, + StackStatusCreateComplete, + StackStatusRollbackInProgress, + StackStatusRollbackFailed, + StackStatusRollbackComplete, + StackStatusDeleteInProgress, + StackStatusDeleteFailed, + StackStatusDeleteComplete, + StackStatusUpdateInProgress, + StackStatusUpdateCompleteCleanupInProgress, + StackStatusUpdateComplete, + StackStatusUpdateRollbackInProgress, + StackStatusUpdateRollbackFailed, + StackStatusUpdateRollbackCompleteCleanupInProgress, + StackStatusUpdateRollbackComplete, + StackStatusReviewInProgress, + StackStatusImportInProgress, + StackStatusImportComplete, + StackStatusImportRollbackInProgress, + StackStatusImportRollbackFailed, + StackStatusImportRollbackComplete, + } +} + const ( // TemplateStageOriginal is a TemplateStage enum value TemplateStageOriginal = "Original" @@ -17189,6 +18099,14 @@ const ( TemplateStageProcessed = "Processed" ) +// TemplateStage_Values returns all elements of the TemplateStage enum +func TemplateStage_Values() []string { + return []string{ + TemplateStageOriginal, + TemplateStageProcessed, + } +} + const ( // VisibilityPublic is a Visibility enum value VisibilityPublic = "PUBLIC" @@ -17196,3 +18114,11 @@ const ( // VisibilityPrivate is a Visibility enum value VisibilityPrivate = "PRIVATE" ) + +// Visibility_Values returns all elements of the Visibility enum +func Visibility_Values() []string { + return []string{ + VisibilityPublic, + VisibilityPrivate, + } +} 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 0dbdc6c2353..183720d485a 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 @@ -349,6 +349,72 @@ func (c *CloudFormation) WaitUntilStackImportCompleteWithContext(ctx aws.Context return w.WaitWithContext(ctx) } +// WaitUntilStackRollbackComplete uses the AWS CloudFormation API operation +// DescribeStacks to wait for a condition to be met before returning. +// If the condition is not met within the max attempt window, an error will +// be returned. +func (c *CloudFormation) WaitUntilStackRollbackComplete(input *DescribeStacksInput) error { + return c.WaitUntilStackRollbackCompleteWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilStackRollbackCompleteWithContext is an extended version of WaitUntilStackRollbackComplete. +// 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) WaitUntilStackRollbackCompleteWithContext(ctx aws.Context, input *DescribeStacksInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilStackRollbackComplete", + MaxAttempts: 120, + Delay: request.ConstantWaiterDelay(30 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Stacks[].StackStatus", + Expected: "UPDATE_ROLLBACK_COMPLETE", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", + Expected: "UPDATE_FAILED", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", + Expected: "UPDATE_ROLLBACK_FAILED", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathAnyWaiterMatch, Argument: "Stacks[].StackStatus", + Expected: "DELETE_FAILED", + }, + { + 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...) + + return w.WaitWithContext(ctx) +} + // WaitUntilStackUpdateComplete uses the AWS CloudFormation API operation // DescribeStacks to wait for a condition to be met before returning. // If the condition is not met within the max attempt window, an error will 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 316965c88ba..c20e519f03a 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 @@ -13,7 +13,138 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restxml" ) -const opCreateCloudFrontOriginAccessIdentity = "CreateCloudFrontOriginAccessIdentity2019_03_26" +const opCreateCachePolicy = "CreateCachePolicy2020_05_31" + +// CreateCachePolicyRequest generates a "aws/request.Request" representing the +// client's request for the CreateCachePolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateCachePolicy for more information on using the CreateCachePolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateCachePolicyRequest method. +// req, resp := client.CreateCachePolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateCachePolicy +func (c *CloudFront) CreateCachePolicyRequest(input *CreateCachePolicyInput) (req *request.Request, output *CreateCachePolicyOutput) { + op := &request.Operation{ + Name: opCreateCachePolicy, + HTTPMethod: "POST", + HTTPPath: "/2020-05-31/cache-policy", + } + + if input == nil { + input = &CreateCachePolicyInput{} + } + + output = &CreateCachePolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateCachePolicy API operation for Amazon CloudFront. +// +// Creates a cache policy. +// +// After you create a cache policy, you can attach it to one or more cache behaviors. +// When it’s attached to a cache behavior, the cache policy determines the +// following: +// +// * The values that CloudFront includes in the cache key. These values can +// include HTTP headers, cookies, and URL query strings. CloudFront uses +// the cache key to find an object in its cache that it can return to the +// viewer. +// +// * The default, minimum, and maximum time to live (TTL) values that you +// want objects to stay in the CloudFront cache. +// +// The headers, cookies, and query strings that are included in the cache key +// are automatically included in requests that CloudFront sends to the origin. +// CloudFront sends a request when it can’t find an object in its cache that +// matches the request’s cache key. If you want to send values to the origin +// but not include them in the cache key, use CreateOriginRequestPolicy. +// +// For more information about cache policies, see Controlling the cache key +// (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html) +// in the Amazon CloudFront Developer Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon CloudFront's +// API operation CreateCachePolicy for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodeInconsistentQuantities "InconsistentQuantities" +// The value of Quantity and the size of Items don't match. +// +// * ErrCodeInvalidArgument "InvalidArgument" +// An argument is invalid. +// +// * ErrCodeCachePolicyAlreadyExists "CachePolicyAlreadyExists" +// A cache policy with this name already exists. You must provide a unique name. +// To modify an existing cache policy, use UpdateCachePolicy. +// +// * ErrCodeTooManyCachePolicies "TooManyCachePolicies" +// You have reached the maximum number of cache policies for this AWS account. +// For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeTooManyHeadersInCachePolicy "TooManyHeadersInCachePolicy" +// The number of headers in the cache policy exceeds the maximum. For more information, +// see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeTooManyCookiesInCachePolicy "TooManyCookiesInCachePolicy" +// The number of cookies in the cache policy exceeds the maximum. For more information, +// see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeTooManyQueryStringsInCachePolicy "TooManyQueryStringsInCachePolicy" +// The number of query strings in the cache policy exceeds the maximum. For +// more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateCachePolicy +func (c *CloudFront) CreateCachePolicy(input *CreateCachePolicyInput) (*CreateCachePolicyOutput, error) { + req, out := c.CreateCachePolicyRequest(input) + return out, req.Send() +} + +// CreateCachePolicyWithContext is the same as CreateCachePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCachePolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) CreateCachePolicyWithContext(ctx aws.Context, input *CreateCachePolicyInput, opts ...request.Option) (*CreateCachePolicyOutput, error) { + req, out := c.CreateCachePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateCloudFrontOriginAccessIdentity = "CreateCloudFrontOriginAccessIdentity2020_05_31" // CreateCloudFrontOriginAccessIdentityRequest generates a "aws/request.Request" representing the // client's request for the CreateCloudFrontOriginAccessIdentity operation. The "output" return @@ -38,12 +169,12 @@ const opCreateCloudFrontOriginAccessIdentity = "CreateCloudFrontOriginAccessIden // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateCloudFrontOriginAccessIdentity +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateCloudFrontOriginAccessIdentity func (c *CloudFront) CreateCloudFrontOriginAccessIdentityRequest(input *CreateCloudFrontOriginAccessIdentityInput) (req *request.Request, output *CreateCloudFrontOriginAccessIdentityOutput) { op := &request.Operation{ Name: opCreateCloudFrontOriginAccessIdentity, HTTPMethod: "POST", - HTTPPath: "/2019-03-26/origin-access-identity/cloudfront", + HTTPPath: "/2020-05-31/origin-access-identity/cloudfront", } if input == nil { @@ -87,12 +218,12 @@ func (c *CloudFront) CreateCloudFrontOriginAccessIdentityRequest(input *CreateCl // access identities allowed. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items don't match. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateCloudFrontOriginAccessIdentity +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateCloudFrontOriginAccessIdentity func (c *CloudFront) CreateCloudFrontOriginAccessIdentity(input *CreateCloudFrontOriginAccessIdentityInput) (*CreateCloudFrontOriginAccessIdentityOutput, error) { req, out := c.CreateCloudFrontOriginAccessIdentityRequest(input) return out, req.Send() @@ -114,7 +245,7 @@ func (c *CloudFront) CreateCloudFrontOriginAccessIdentityWithContext(ctx aws.Con return out, req.Send() } -const opCreateDistribution = "CreateDistribution2019_03_26" +const opCreateDistribution = "CreateDistribution2020_05_31" // CreateDistributionRequest generates a "aws/request.Request" representing the // client's request for the CreateDistribution operation. The "output" return @@ -139,12 +270,12 @@ const opCreateDistribution = "CreateDistribution2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateDistribution func (c *CloudFront) CreateDistributionRequest(input *CreateDistributionInput) (req *request.Request, output *CreateDistributionOutput) { op := &request.Operation{ Name: opCreateDistribution, HTTPMethod: "POST", - HTTPPath: "/2019-03-26/distribution", + HTTPPath: "/2020-05-31/distribution", } if input == nil { @@ -234,7 +365,7 @@ func (c *CloudFront) CreateDistributionRequest(input *CreateDistributionInput) ( // A response code is not valid. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInvalidRequiredProtocol "InvalidRequiredProtocol" // This operation requires the HTTPS protocol. Ensure that you specify the HTTPS @@ -308,6 +439,10 @@ func (c *CloudFront) CreateDistributionRequest(input *CreateDistributionInput) ( // Processing your request would cause the maximum number of distributions with // Lambda function associations per owner to be exceeded. // +// * ErrCodeTooManyDistributionsWithSingleFunctionARN "TooManyDistributionsWithSingleFunctionARN" +// The maximum number of distributions have been associated with the specified +// Lambda function. +// // * ErrCodeTooManyLambdaFunctionAssociations "TooManyLambdaFunctionAssociations" // Your request contains more Lambda function associations than are allowed // per distribution. @@ -332,7 +467,23 @@ func (c *CloudFront) CreateDistributionRequest(input *CreateDistributionInput) ( // The maximum number of distributions have been associated with the specified // configuration for field-level encryption. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateDistribution +// * ErrCodeNoSuchCachePolicy "NoSuchCachePolicy" +// The cache policy does not exist. +// +// * ErrCodeTooManyDistributionsAssociatedToCachePolicy "TooManyDistributionsAssociatedToCachePolicy" +// The maximum number of distributions have been associated with the specified +// cache policy. For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeNoSuchOriginRequestPolicy "NoSuchOriginRequestPolicy" +// The origin request policy does not exist. +// +// * ErrCodeTooManyDistributionsAssociatedToOriginRequestPolicy "TooManyDistributionsAssociatedToOriginRequestPolicy" +// The maximum number of distributions have been associated with the specified +// origin request policy. For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateDistribution func (c *CloudFront) CreateDistribution(input *CreateDistributionInput) (*CreateDistributionOutput, error) { req, out := c.CreateDistributionRequest(input) return out, req.Send() @@ -354,7 +505,7 @@ func (c *CloudFront) CreateDistributionWithContext(ctx aws.Context, input *Creat return out, req.Send() } -const opCreateDistributionWithTags = "CreateDistributionWithTags2019_03_26" +const opCreateDistributionWithTags = "CreateDistributionWithTags2020_05_31" // CreateDistributionWithTagsRequest generates a "aws/request.Request" representing the // client's request for the CreateDistributionWithTags operation. The "output" return @@ -379,12 +530,12 @@ const opCreateDistributionWithTags = "CreateDistributionWithTags2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateDistributionWithTags +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateDistributionWithTags func (c *CloudFront) CreateDistributionWithTagsRequest(input *CreateDistributionWithTagsInput) (req *request.Request, output *CreateDistributionWithTagsOutput) { op := &request.Operation{ Name: opCreateDistributionWithTags, HTTPMethod: "POST", - HTTPPath: "/2019-03-26/distribution?WithTags", + HTTPPath: "/2020-05-31/distribution?WithTags", } if input == nil { @@ -462,7 +613,7 @@ func (c *CloudFront) CreateDistributionWithTagsRequest(input *CreateDistribution // A response code is not valid. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInvalidRequiredProtocol "InvalidRequiredProtocol" // This operation requires the HTTPS protocol. Ensure that you specify the HTTPS @@ -539,6 +690,10 @@ func (c *CloudFront) CreateDistributionWithTagsRequest(input *CreateDistribution // Processing your request would cause the maximum number of distributions with // Lambda function associations per owner to be exceeded. // +// * ErrCodeTooManyDistributionsWithSingleFunctionARN "TooManyDistributionsWithSingleFunctionARN" +// The maximum number of distributions have been associated with the specified +// Lambda function. +// // * ErrCodeTooManyLambdaFunctionAssociations "TooManyLambdaFunctionAssociations" // Your request contains more Lambda function associations than are allowed // per distribution. @@ -563,7 +718,23 @@ func (c *CloudFront) CreateDistributionWithTagsRequest(input *CreateDistribution // The maximum number of distributions have been associated with the specified // configuration for field-level encryption. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateDistributionWithTags +// * ErrCodeNoSuchCachePolicy "NoSuchCachePolicy" +// The cache policy does not exist. +// +// * ErrCodeTooManyDistributionsAssociatedToCachePolicy "TooManyDistributionsAssociatedToCachePolicy" +// The maximum number of distributions have been associated with the specified +// cache policy. For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeNoSuchOriginRequestPolicy "NoSuchOriginRequestPolicy" +// The origin request policy does not exist. +// +// * ErrCodeTooManyDistributionsAssociatedToOriginRequestPolicy "TooManyDistributionsAssociatedToOriginRequestPolicy" +// The maximum number of distributions have been associated with the specified +// origin request policy. For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateDistributionWithTags func (c *CloudFront) CreateDistributionWithTags(input *CreateDistributionWithTagsInput) (*CreateDistributionWithTagsOutput, error) { req, out := c.CreateDistributionWithTagsRequest(input) return out, req.Send() @@ -585,7 +756,7 @@ func (c *CloudFront) CreateDistributionWithTagsWithContext(ctx aws.Context, inpu return out, req.Send() } -const opCreateFieldLevelEncryptionConfig = "CreateFieldLevelEncryptionConfig2019_03_26" +const opCreateFieldLevelEncryptionConfig = "CreateFieldLevelEncryptionConfig2020_05_31" // CreateFieldLevelEncryptionConfigRequest generates a "aws/request.Request" representing the // client's request for the CreateFieldLevelEncryptionConfig operation. The "output" return @@ -610,12 +781,12 @@ const opCreateFieldLevelEncryptionConfig = "CreateFieldLevelEncryptionConfig2019 // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateFieldLevelEncryptionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateFieldLevelEncryptionConfig func (c *CloudFront) CreateFieldLevelEncryptionConfigRequest(input *CreateFieldLevelEncryptionConfigInput) (req *request.Request, output *CreateFieldLevelEncryptionConfigOutput) { op := &request.Operation{ Name: opCreateFieldLevelEncryptionConfig, HTTPMethod: "POST", - HTTPPath: "/2019-03-26/field-level-encryption", + HTTPPath: "/2020-05-31/field-level-encryption", } if input == nil { @@ -643,7 +814,7 @@ func (c *CloudFront) CreateFieldLevelEncryptionConfigRequest(input *CreateFieldL // The value of Quantity and the size of Items don't match. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeNoSuchFieldLevelEncryptionProfile "NoSuchFieldLevelEncryptionProfile" // The specified profile for field-level encryption doesn't exist. @@ -666,7 +837,7 @@ func (c *CloudFront) CreateFieldLevelEncryptionConfigRequest(input *CreateFieldL // * ErrCodeQueryArgProfileEmpty "QueryArgProfileEmpty" // No profile specified for the field-level encryption query argument. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateFieldLevelEncryptionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateFieldLevelEncryptionConfig func (c *CloudFront) CreateFieldLevelEncryptionConfig(input *CreateFieldLevelEncryptionConfigInput) (*CreateFieldLevelEncryptionConfigOutput, error) { req, out := c.CreateFieldLevelEncryptionConfigRequest(input) return out, req.Send() @@ -688,7 +859,7 @@ func (c *CloudFront) CreateFieldLevelEncryptionConfigWithContext(ctx aws.Context return out, req.Send() } -const opCreateFieldLevelEncryptionProfile = "CreateFieldLevelEncryptionProfile2019_03_26" +const opCreateFieldLevelEncryptionProfile = "CreateFieldLevelEncryptionProfile2020_05_31" // CreateFieldLevelEncryptionProfileRequest generates a "aws/request.Request" representing the // client's request for the CreateFieldLevelEncryptionProfile operation. The "output" return @@ -713,12 +884,12 @@ const opCreateFieldLevelEncryptionProfile = "CreateFieldLevelEncryptionProfile20 // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateFieldLevelEncryptionProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateFieldLevelEncryptionProfile func (c *CloudFront) CreateFieldLevelEncryptionProfileRequest(input *CreateFieldLevelEncryptionProfileInput) (req *request.Request, output *CreateFieldLevelEncryptionProfileOutput) { op := &request.Operation{ Name: opCreateFieldLevelEncryptionProfile, HTTPMethod: "POST", - HTTPPath: "/2019-03-26/field-level-encryption-profile", + HTTPPath: "/2020-05-31/field-level-encryption-profile", } if input == nil { @@ -746,7 +917,7 @@ func (c *CloudFront) CreateFieldLevelEncryptionProfileRequest(input *CreateField // The value of Quantity and the size of Items don't match. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeNoSuchPublicKey "NoSuchPublicKey" // The specified public key doesn't exist. @@ -768,7 +939,7 @@ func (c *CloudFront) CreateFieldLevelEncryptionProfileRequest(input *CreateField // The maximum number of field patterns for field-level encryption have been // created. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateFieldLevelEncryptionProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateFieldLevelEncryptionProfile func (c *CloudFront) CreateFieldLevelEncryptionProfile(input *CreateFieldLevelEncryptionProfileInput) (*CreateFieldLevelEncryptionProfileOutput, error) { req, out := c.CreateFieldLevelEncryptionProfileRequest(input) return out, req.Send() @@ -790,7 +961,7 @@ func (c *CloudFront) CreateFieldLevelEncryptionProfileWithContext(ctx aws.Contex return out, req.Send() } -const opCreateInvalidation = "CreateInvalidation2019_03_26" +const opCreateInvalidation = "CreateInvalidation2020_05_31" // CreateInvalidationRequest generates a "aws/request.Request" representing the // client's request for the CreateInvalidation operation. The "output" return @@ -815,12 +986,12 @@ const opCreateInvalidation = "CreateInvalidation2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateInvalidation +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateInvalidation func (c *CloudFront) CreateInvalidationRequest(input *CreateInvalidationInput) (req *request.Request, output *CreateInvalidationOutput) { op := &request.Operation{ Name: opCreateInvalidation, HTTPMethod: "POST", - HTTPPath: "/2019-03-26/distribution/{DistributionId}/invalidation", + HTTPPath: "/2020-05-31/distribution/{DistributionId}/invalidation", } if input == nil { @@ -852,7 +1023,7 @@ func (c *CloudFront) CreateInvalidationRequest(input *CreateInvalidationInput) ( // header is set. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeNoSuchDistribution "NoSuchDistribution" // The specified distribution does not exist. @@ -867,7 +1038,7 @@ func (c *CloudFront) CreateInvalidationRequest(input *CreateInvalidationInput) ( // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items don't match. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateInvalidation +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateInvalidation func (c *CloudFront) CreateInvalidation(input *CreateInvalidationInput) (*CreateInvalidationOutput, error) { req, out := c.CreateInvalidationRequest(input) return out, req.Send() @@ -889,7 +1060,141 @@ func (c *CloudFront) CreateInvalidationWithContext(ctx aws.Context, input *Creat return out, req.Send() } -const opCreatePublicKey = "CreatePublicKey2019_03_26" +const opCreateOriginRequestPolicy = "CreateOriginRequestPolicy2020_05_31" + +// CreateOriginRequestPolicyRequest generates a "aws/request.Request" representing the +// client's request for the CreateOriginRequestPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateOriginRequestPolicy for more information on using the CreateOriginRequestPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateOriginRequestPolicyRequest method. +// req, resp := client.CreateOriginRequestPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateOriginRequestPolicy +func (c *CloudFront) CreateOriginRequestPolicyRequest(input *CreateOriginRequestPolicyInput) (req *request.Request, output *CreateOriginRequestPolicyOutput) { + op := &request.Operation{ + Name: opCreateOriginRequestPolicy, + HTTPMethod: "POST", + HTTPPath: "/2020-05-31/origin-request-policy", + } + + if input == nil { + input = &CreateOriginRequestPolicyInput{} + } + + output = &CreateOriginRequestPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateOriginRequestPolicy API operation for Amazon CloudFront. +// +// Creates an origin request policy. +// +// After you create an origin request policy, you can attach it to one or more +// cache behaviors. When it’s attached to a cache behavior, the origin request +// policy determines the values that CloudFront includes in requests that it +// sends to the origin. Each request that CloudFront sends to the origin includes +// the following: +// +// * The request body and the URL path (without the domain name) from the +// viewer request. +// +// * The headers that CloudFront automatically includes in every origin request, +// including Host, User-Agent, and X-Amz-Cf-Id. +// +// * All HTTP headers, cookies, and URL query strings that are specified +// in the cache policy or the origin request policy. These can include items +// from the viewer request and, in the case of headers, additional ones that +// are added by CloudFront. +// +// CloudFront sends a request when it can’t find a valid object in its cache +// that matches the request. If you want to send values to the origin and also +// include them in the cache key, use CreateCachePolicy. +// +// For more information about origin request policies, see Controlling origin +// requests (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html) +// in the Amazon CloudFront Developer Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon CloudFront's +// API operation CreateOriginRequestPolicy for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodeInconsistentQuantities "InconsistentQuantities" +// The value of Quantity and the size of Items don't match. +// +// * ErrCodeInvalidArgument "InvalidArgument" +// An argument is invalid. +// +// * ErrCodeOriginRequestPolicyAlreadyExists "OriginRequestPolicyAlreadyExists" +// An origin request policy with this name already exists. You must provide +// a unique name. To modify an existing origin request policy, use UpdateOriginRequestPolicy. +// +// * ErrCodeTooManyOriginRequestPolicies "TooManyOriginRequestPolicies" +// You have reached the maximum number of origin request policies for this AWS +// account. For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeTooManyHeadersInOriginRequestPolicy "TooManyHeadersInOriginRequestPolicy" +// The number of headers in the origin request policy exceeds the maximum. For +// more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeTooManyCookiesInOriginRequestPolicy "TooManyCookiesInOriginRequestPolicy" +// The number of cookies in the origin request policy exceeds the maximum. For +// more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeTooManyQueryStringsInOriginRequestPolicy "TooManyQueryStringsInOriginRequestPolicy" +// The number of query strings in the origin request policy exceeds the maximum. +// For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateOriginRequestPolicy +func (c *CloudFront) CreateOriginRequestPolicy(input *CreateOriginRequestPolicyInput) (*CreateOriginRequestPolicyOutput, error) { + req, out := c.CreateOriginRequestPolicyRequest(input) + return out, req.Send() +} + +// CreateOriginRequestPolicyWithContext is the same as CreateOriginRequestPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See CreateOriginRequestPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) CreateOriginRequestPolicyWithContext(ctx aws.Context, input *CreateOriginRequestPolicyInput, opts ...request.Option) (*CreateOriginRequestPolicyOutput, error) { + req, out := c.CreateOriginRequestPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreatePublicKey = "CreatePublicKey2020_05_31" // CreatePublicKeyRequest generates a "aws/request.Request" representing the // client's request for the CreatePublicKey operation. The "output" return @@ -914,12 +1219,12 @@ const opCreatePublicKey = "CreatePublicKey2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreatePublicKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreatePublicKey func (c *CloudFront) CreatePublicKeyRequest(input *CreatePublicKeyInput) (req *request.Request, output *CreatePublicKeyOutput) { op := &request.Operation{ Name: opCreatePublicKey, HTTPMethod: "POST", - HTTPPath: "/2019-03-26/public-key", + HTTPPath: "/2020-05-31/public-key", } if input == nil { @@ -948,13 +1253,13 @@ func (c *CloudFront) CreatePublicKeyRequest(input *CreatePublicKeyInput) (req *r // The specified public key already exists. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeTooManyPublicKeys "TooManyPublicKeys" // The maximum number of public keys for field-level encryption have been created. // To create a new public key, delete one of the existing keys. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreatePublicKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreatePublicKey func (c *CloudFront) CreatePublicKey(input *CreatePublicKeyInput) (*CreatePublicKeyOutput, error) { req, out := c.CreatePublicKeyRequest(input) return out, req.Send() @@ -976,7 +1281,7 @@ func (c *CloudFront) CreatePublicKeyWithContext(ctx aws.Context, input *CreatePu return out, req.Send() } -const opCreateStreamingDistribution = "CreateStreamingDistribution2019_03_26" +const opCreateStreamingDistribution = "CreateStreamingDistribution2020_05_31" // CreateStreamingDistributionRequest generates a "aws/request.Request" representing the // client's request for the CreateStreamingDistribution operation. The "output" return @@ -1001,12 +1306,12 @@ const opCreateStreamingDistribution = "CreateStreamingDistribution2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateStreamingDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateStreamingDistribution func (c *CloudFront) CreateStreamingDistributionRequest(input *CreateStreamingDistributionInput) (req *request.Request, output *CreateStreamingDistributionOutput) { op := &request.Operation{ Name: opCreateStreamingDistribution, HTTPMethod: "POST", - HTTPPath: "/2019-03-26/streaming-distribution", + HTTPPath: "/2020-05-31/streaming-distribution", } if input == nil { @@ -1092,12 +1397,12 @@ func (c *CloudFront) CreateStreamingDistributionRequest(input *CreateStreamingDi // distributions allowed. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items don't match. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateStreamingDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateStreamingDistribution func (c *CloudFront) CreateStreamingDistribution(input *CreateStreamingDistributionInput) (*CreateStreamingDistributionOutput, error) { req, out := c.CreateStreamingDistributionRequest(input) return out, req.Send() @@ -1119,7 +1424,7 @@ func (c *CloudFront) CreateStreamingDistributionWithContext(ctx aws.Context, inp return out, req.Send() } -const opCreateStreamingDistributionWithTags = "CreateStreamingDistributionWithTags2019_03_26" +const opCreateStreamingDistributionWithTags = "CreateStreamingDistributionWithTags2020_05_31" // CreateStreamingDistributionWithTagsRequest generates a "aws/request.Request" representing the // client's request for the CreateStreamingDistributionWithTags operation. The "output" return @@ -1144,12 +1449,12 @@ const opCreateStreamingDistributionWithTags = "CreateStreamingDistributionWithTa // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateStreamingDistributionWithTags +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateStreamingDistributionWithTags func (c *CloudFront) CreateStreamingDistributionWithTagsRequest(input *CreateStreamingDistributionWithTagsInput) (req *request.Request, output *CreateStreamingDistributionWithTagsOutput) { op := &request.Operation{ Name: opCreateStreamingDistributionWithTags, HTTPMethod: "POST", - HTTPPath: "/2019-03-26/streaming-distribution?WithTags", + HTTPPath: "/2020-05-31/streaming-distribution?WithTags", } if input == nil { @@ -1208,7 +1513,7 @@ func (c *CloudFront) CreateStreamingDistributionWithTagsRequest(input *CreateStr // distributions allowed. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items don't match. @@ -1216,7 +1521,7 @@ func (c *CloudFront) CreateStreamingDistributionWithTagsRequest(input *CreateStr // * ErrCodeInvalidTagging "InvalidTagging" // The tagging specified is not valid. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/CreateStreamingDistributionWithTags +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/CreateStreamingDistributionWithTags func (c *CloudFront) CreateStreamingDistributionWithTags(input *CreateStreamingDistributionWithTagsInput) (*CreateStreamingDistributionWithTagsOutput, error) { req, out := c.CreateStreamingDistributionWithTagsRequest(input) return out, req.Send() @@ -1238,7 +1543,111 @@ func (c *CloudFront) CreateStreamingDistributionWithTagsWithContext(ctx aws.Cont return out, req.Send() } -const opDeleteCloudFrontOriginAccessIdentity = "DeleteCloudFrontOriginAccessIdentity2019_03_26" +const opDeleteCachePolicy = "DeleteCachePolicy2020_05_31" + +// DeleteCachePolicyRequest generates a "aws/request.Request" representing the +// client's request for the DeleteCachePolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteCachePolicy for more information on using the DeleteCachePolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteCachePolicyRequest method. +// req, resp := client.DeleteCachePolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteCachePolicy +func (c *CloudFront) DeleteCachePolicyRequest(input *DeleteCachePolicyInput) (req *request.Request, output *DeleteCachePolicyOutput) { + op := &request.Operation{ + Name: opDeleteCachePolicy, + HTTPMethod: "DELETE", + HTTPPath: "/2020-05-31/cache-policy/{Id}", + } + + if input == nil { + input = &DeleteCachePolicyInput{} + } + + output = &DeleteCachePolicyOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteCachePolicy API operation for Amazon CloudFront. +// +// Deletes a cache policy. +// +// You cannot delete a cache policy if it’s attached to a cache behavior. +// First update your distributions to remove the cache policy from all cache +// behaviors, then delete the cache policy. +// +// To delete a cache policy, you must provide the policy’s identifier and +// version. To get these values, you can use ListCachePolicies or GetCachePolicy. +// +// Returns awserr.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 CloudFront's +// API operation DeleteCachePolicy for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" +// The If-Match version is missing or not valid. +// +// * ErrCodeNoSuchCachePolicy "NoSuchCachePolicy" +// The cache policy does not exist. +// +// * ErrCodePreconditionFailed "PreconditionFailed" +// The precondition given in one or more of the request header fields evaluated +// to false. +// +// * ErrCodeIllegalDelete "IllegalDelete" +// You cannot delete a managed policy. +// +// * ErrCodeCachePolicyInUse "CachePolicyInUse" +// Cannot delete the cache policy because it is attached to one or more cache +// behaviors. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteCachePolicy +func (c *CloudFront) DeleteCachePolicy(input *DeleteCachePolicyInput) (*DeleteCachePolicyOutput, error) { + req, out := c.DeleteCachePolicyRequest(input) + return out, req.Send() +} + +// DeleteCachePolicyWithContext is the same as DeleteCachePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCachePolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DeleteCachePolicyWithContext(ctx aws.Context, input *DeleteCachePolicyInput, opts ...request.Option) (*DeleteCachePolicyOutput, error) { + req, out := c.DeleteCachePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteCloudFrontOriginAccessIdentity = "DeleteCloudFrontOriginAccessIdentity2020_05_31" // DeleteCloudFrontOriginAccessIdentityRequest generates a "aws/request.Request" representing the // client's request for the DeleteCloudFrontOriginAccessIdentity operation. The "output" return @@ -1263,12 +1672,12 @@ const opDeleteCloudFrontOriginAccessIdentity = "DeleteCloudFrontOriginAccessIden // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeleteCloudFrontOriginAccessIdentity +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteCloudFrontOriginAccessIdentity func (c *CloudFront) DeleteCloudFrontOriginAccessIdentityRequest(input *DeleteCloudFrontOriginAccessIdentityInput) (req *request.Request, output *DeleteCloudFrontOriginAccessIdentityOutput) { op := &request.Operation{ Name: opDeleteCloudFrontOriginAccessIdentity, HTTPMethod: "DELETE", - HTTPPath: "/2019-03-26/origin-access-identity/cloudfront/{Id}", + HTTPPath: "/2020-05-31/origin-access-identity/cloudfront/{Id}", } if input == nil { @@ -1297,19 +1706,19 @@ func (c *CloudFront) DeleteCloudFrontOriginAccessIdentityRequest(input *DeleteCl // Access denied. // // * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// The If-Match version is missing or not valid. // // * ErrCodeNoSuchCloudFrontOriginAccessIdentity "NoSuchCloudFrontOriginAccessIdentity" // The specified origin access identity does not exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // // * ErrCodeOriginAccessIdentityInUse "CloudFrontOriginAccessIdentityInUse" // The Origin Access Identity specified is already in use. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeleteCloudFrontOriginAccessIdentity +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteCloudFrontOriginAccessIdentity func (c *CloudFront) DeleteCloudFrontOriginAccessIdentity(input *DeleteCloudFrontOriginAccessIdentityInput) (*DeleteCloudFrontOriginAccessIdentityOutput, error) { req, out := c.DeleteCloudFrontOriginAccessIdentityRequest(input) return out, req.Send() @@ -1331,7 +1740,7 @@ func (c *CloudFront) DeleteCloudFrontOriginAccessIdentityWithContext(ctx aws.Con return out, req.Send() } -const opDeleteDistribution = "DeleteDistribution2019_03_26" +const opDeleteDistribution = "DeleteDistribution2020_05_31" // DeleteDistributionRequest generates a "aws/request.Request" representing the // client's request for the DeleteDistribution operation. The "output" return @@ -1356,12 +1765,12 @@ const opDeleteDistribution = "DeleteDistribution2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeleteDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteDistribution func (c *CloudFront) DeleteDistributionRequest(input *DeleteDistributionInput) (req *request.Request, output *DeleteDistributionOutput) { op := &request.Operation{ Name: opDeleteDistribution, HTTPMethod: "DELETE", - HTTPPath: "/2019-03-26/distribution/{Id}", + HTTPPath: "/2020-05-31/distribution/{Id}", } if input == nil { @@ -1394,16 +1803,16 @@ func (c *CloudFront) DeleteDistributionRequest(input *DeleteDistributionInput) ( // distribution before you can delete it. // // * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// The If-Match version is missing or not valid. // // * ErrCodeNoSuchDistribution "NoSuchDistribution" // The specified distribution does not exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeleteDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteDistribution func (c *CloudFront) DeleteDistribution(input *DeleteDistributionInput) (*DeleteDistributionOutput, error) { req, out := c.DeleteDistributionRequest(input) return out, req.Send() @@ -1425,7 +1834,7 @@ func (c *CloudFront) DeleteDistributionWithContext(ctx aws.Context, input *Delet return out, req.Send() } -const opDeleteFieldLevelEncryptionConfig = "DeleteFieldLevelEncryptionConfig2019_03_26" +const opDeleteFieldLevelEncryptionConfig = "DeleteFieldLevelEncryptionConfig2020_05_31" // DeleteFieldLevelEncryptionConfigRequest generates a "aws/request.Request" representing the // client's request for the DeleteFieldLevelEncryptionConfig operation. The "output" return @@ -1450,12 +1859,12 @@ const opDeleteFieldLevelEncryptionConfig = "DeleteFieldLevelEncryptionConfig2019 // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeleteFieldLevelEncryptionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteFieldLevelEncryptionConfig func (c *CloudFront) DeleteFieldLevelEncryptionConfigRequest(input *DeleteFieldLevelEncryptionConfigInput) (req *request.Request, output *DeleteFieldLevelEncryptionConfigOutput) { op := &request.Operation{ Name: opDeleteFieldLevelEncryptionConfig, HTTPMethod: "DELETE", - HTTPPath: "/2019-03-26/field-level-encryption/{Id}", + HTTPPath: "/2020-05-31/field-level-encryption/{Id}", } if input == nil { @@ -1484,19 +1893,19 @@ func (c *CloudFront) DeleteFieldLevelEncryptionConfigRequest(input *DeleteFieldL // Access denied. // // * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// The If-Match version is missing or not valid. // // * ErrCodeNoSuchFieldLevelEncryptionConfig "NoSuchFieldLevelEncryptionConfig" // The specified configuration for field-level encryption doesn't exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // // * ErrCodeFieldLevelEncryptionConfigInUse "FieldLevelEncryptionConfigInUse" // The specified configuration for field-level encryption is in use. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeleteFieldLevelEncryptionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteFieldLevelEncryptionConfig func (c *CloudFront) DeleteFieldLevelEncryptionConfig(input *DeleteFieldLevelEncryptionConfigInput) (*DeleteFieldLevelEncryptionConfigOutput, error) { req, out := c.DeleteFieldLevelEncryptionConfigRequest(input) return out, req.Send() @@ -1518,7 +1927,7 @@ func (c *CloudFront) DeleteFieldLevelEncryptionConfigWithContext(ctx aws.Context return out, req.Send() } -const opDeleteFieldLevelEncryptionProfile = "DeleteFieldLevelEncryptionProfile2019_03_26" +const opDeleteFieldLevelEncryptionProfile = "DeleteFieldLevelEncryptionProfile2020_05_31" // DeleteFieldLevelEncryptionProfileRequest generates a "aws/request.Request" representing the // client's request for the DeleteFieldLevelEncryptionProfile operation. The "output" return @@ -1543,12 +1952,12 @@ const opDeleteFieldLevelEncryptionProfile = "DeleteFieldLevelEncryptionProfile20 // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeleteFieldLevelEncryptionProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteFieldLevelEncryptionProfile func (c *CloudFront) DeleteFieldLevelEncryptionProfileRequest(input *DeleteFieldLevelEncryptionProfileInput) (req *request.Request, output *DeleteFieldLevelEncryptionProfileOutput) { op := &request.Operation{ Name: opDeleteFieldLevelEncryptionProfile, HTTPMethod: "DELETE", - HTTPPath: "/2019-03-26/field-level-encryption-profile/{Id}", + HTTPPath: "/2020-05-31/field-level-encryption-profile/{Id}", } if input == nil { @@ -1577,19 +1986,19 @@ func (c *CloudFront) DeleteFieldLevelEncryptionProfileRequest(input *DeleteField // Access denied. // // * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// The If-Match version is missing or not valid. // // * ErrCodeNoSuchFieldLevelEncryptionProfile "NoSuchFieldLevelEncryptionProfile" // The specified profile for field-level encryption doesn't exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // // * ErrCodeFieldLevelEncryptionProfileInUse "FieldLevelEncryptionProfileInUse" // The specified profile for field-level encryption is in use. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeleteFieldLevelEncryptionProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteFieldLevelEncryptionProfile func (c *CloudFront) DeleteFieldLevelEncryptionProfile(input *DeleteFieldLevelEncryptionProfileInput) (*DeleteFieldLevelEncryptionProfileOutput, error) { req, out := c.DeleteFieldLevelEncryptionProfileRequest(input) return out, req.Send() @@ -1611,130 +2020,235 @@ func (c *CloudFront) DeleteFieldLevelEncryptionProfileWithContext(ctx aws.Contex return out, req.Send() } -const opDeletePublicKey = "DeletePublicKey2019_03_26" +const opDeleteOriginRequestPolicy = "DeleteOriginRequestPolicy2020_05_31" -// DeletePublicKeyRequest generates a "aws/request.Request" representing the -// client's request for the DeletePublicKey operation. The "output" return +// DeleteOriginRequestPolicyRequest generates a "aws/request.Request" representing the +// client's request for the DeleteOriginRequestPolicy operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeletePublicKey for more information on using the DeletePublicKey +// See DeleteOriginRequestPolicy for more information on using the DeleteOriginRequestPolicy // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeletePublicKeyRequest method. -// req, resp := client.DeletePublicKeyRequest(params) +// // Example sending a request using the DeleteOriginRequestPolicyRequest method. +// req, resp := client.DeleteOriginRequestPolicyRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeletePublicKey -func (c *CloudFront) DeletePublicKeyRequest(input *DeletePublicKeyInput) (req *request.Request, output *DeletePublicKeyOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteOriginRequestPolicy +func (c *CloudFront) DeleteOriginRequestPolicyRequest(input *DeleteOriginRequestPolicyInput) (req *request.Request, output *DeleteOriginRequestPolicyOutput) { op := &request.Operation{ - Name: opDeletePublicKey, + Name: opDeleteOriginRequestPolicy, HTTPMethod: "DELETE", - HTTPPath: "/2019-03-26/public-key/{Id}", + HTTPPath: "/2020-05-31/origin-request-policy/{Id}", } if input == nil { - input = &DeletePublicKeyInput{} + input = &DeleteOriginRequestPolicyInput{} } - output = &DeletePublicKeyOutput{} + output = &DeleteOriginRequestPolicyOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) return } -// DeletePublicKey API operation for Amazon CloudFront. +// DeleteOriginRequestPolicy API operation for Amazon CloudFront. // -// Remove a public key you previously added to CloudFront. +// Deletes an origin request policy. +// +// You cannot delete an origin request policy if it’s attached to any cache +// behaviors. First update your distributions to remove the origin request policy +// from all cache behaviors, then delete the origin request policy. +// +// To delete an origin request policy, you must provide the policy’s identifier +// and version. To get the identifier, you can use ListOriginRequestPolicies +// or GetOriginRequestPolicy. // // Returns awserr.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 CloudFront's -// API operation DeletePublicKey for usage and error information. +// API operation DeleteOriginRequestPolicy for usage and error information. // // Returned Error Codes: // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// * ErrCodePublicKeyInUse "PublicKeyInUse" -// The specified public key is in use. -// // * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// The If-Match version is missing or not valid. // -// * ErrCodeNoSuchPublicKey "NoSuchPublicKey" -// The specified public key doesn't exist. +// * ErrCodeNoSuchOriginRequestPolicy "NoSuchOriginRequestPolicy" +// The origin request policy does not exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeletePublicKey -func (c *CloudFront) DeletePublicKey(input *DeletePublicKeyInput) (*DeletePublicKeyOutput, error) { - req, out := c.DeletePublicKeyRequest(input) +// * ErrCodeIllegalDelete "IllegalDelete" +// You cannot delete a managed policy. +// +// * ErrCodeOriginRequestPolicyInUse "OriginRequestPolicyInUse" +// Cannot delete the origin request policy because it is attached to one or +// more cache behaviors. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteOriginRequestPolicy +func (c *CloudFront) DeleteOriginRequestPolicy(input *DeleteOriginRequestPolicyInput) (*DeleteOriginRequestPolicyOutput, error) { + req, out := c.DeleteOriginRequestPolicyRequest(input) return out, req.Send() } -// DeletePublicKeyWithContext is the same as DeletePublicKey with the addition of +// DeleteOriginRequestPolicyWithContext is the same as DeleteOriginRequestPolicy with the addition of // the ability to pass a context and additional request options. // -// See DeletePublicKey for details on how to use this API operation. +// See DeleteOriginRequestPolicy for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) DeletePublicKeyWithContext(ctx aws.Context, input *DeletePublicKeyInput, opts ...request.Option) (*DeletePublicKeyOutput, error) { - req, out := c.DeletePublicKeyRequest(input) +func (c *CloudFront) DeleteOriginRequestPolicyWithContext(ctx aws.Context, input *DeleteOriginRequestPolicyInput, opts ...request.Option) (*DeleteOriginRequestPolicyOutput, error) { + req, out := c.DeleteOriginRequestPolicyRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDeleteStreamingDistribution = "DeleteStreamingDistribution2019_03_26" +const opDeletePublicKey = "DeletePublicKey2020_05_31" -// DeleteStreamingDistributionRequest generates a "aws/request.Request" representing the -// client's request for the DeleteStreamingDistribution operation. The "output" return +// DeletePublicKeyRequest generates a "aws/request.Request" representing the +// client's request for the DeletePublicKey operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteStreamingDistribution for more information on using the DeleteStreamingDistribution +// See DeletePublicKey for more information on using the DeletePublicKey // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteStreamingDistributionRequest method. -// req, resp := client.DeleteStreamingDistributionRequest(params) +// // Example sending a request using the DeletePublicKeyRequest method. +// req, resp := client.DeletePublicKeyRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeleteStreamingDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeletePublicKey +func (c *CloudFront) DeletePublicKeyRequest(input *DeletePublicKeyInput) (req *request.Request, output *DeletePublicKeyOutput) { + op := &request.Operation{ + Name: opDeletePublicKey, + HTTPMethod: "DELETE", + HTTPPath: "/2020-05-31/public-key/{Id}", + } + + if input == nil { + input = &DeletePublicKeyInput{} + } + + output = &DeletePublicKeyOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeletePublicKey API operation for Amazon CloudFront. +// +// Remove a public key you previously added to CloudFront. +// +// Returns awserr.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 CloudFront's +// API operation DeletePublicKey for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodePublicKeyInUse "PublicKeyInUse" +// The specified public key is in use. +// +// * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" +// The If-Match version is missing or not valid. +// +// * ErrCodeNoSuchPublicKey "NoSuchPublicKey" +// The specified public key doesn't exist. +// +// * ErrCodePreconditionFailed "PreconditionFailed" +// The precondition given in one or more of the request header fields evaluated +// to false. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeletePublicKey +func (c *CloudFront) DeletePublicKey(input *DeletePublicKeyInput) (*DeletePublicKeyOutput, error) { + req, out := c.DeletePublicKeyRequest(input) + return out, req.Send() +} + +// DeletePublicKeyWithContext is the same as DeletePublicKey with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePublicKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DeletePublicKeyWithContext(ctx aws.Context, input *DeletePublicKeyInput, opts ...request.Option) (*DeletePublicKeyOutput, error) { + req, out := c.DeletePublicKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteStreamingDistribution = "DeleteStreamingDistribution2020_05_31" + +// DeleteStreamingDistributionRequest generates a "aws/request.Request" representing the +// client's request for the DeleteStreamingDistribution operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteStreamingDistribution for more information on using the DeleteStreamingDistribution +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteStreamingDistributionRequest method. +// req, resp := client.DeleteStreamingDistributionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteStreamingDistribution func (c *CloudFront) DeleteStreamingDistributionRequest(input *DeleteStreamingDistributionInput) (req *request.Request, output *DeleteStreamingDistributionOutput) { op := &request.Operation{ Name: opDeleteStreamingDistribution, HTTPMethod: "DELETE", - HTTPPath: "/2019-03-26/streaming-distribution/{Id}", + HTTPPath: "/2020-05-31/streaming-distribution/{Id}", } if input == nil { @@ -1802,16 +2316,16 @@ func (c *CloudFront) DeleteStreamingDistributionRequest(input *DeleteStreamingDi // distribution before you can delete it. // // * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// The If-Match version is missing or not valid. // // * ErrCodeNoSuchStreamingDistribution "NoSuchStreamingDistribution" // The specified streaming distribution does not exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/DeleteStreamingDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/DeleteStreamingDistribution func (c *CloudFront) DeleteStreamingDistribution(input *DeleteStreamingDistributionInput) (*DeleteStreamingDistributionOutput, error) { req, out := c.DeleteStreamingDistributionRequest(input) return out, req.Send() @@ -1833,7 +2347,187 @@ func (c *CloudFront) DeleteStreamingDistributionWithContext(ctx aws.Context, inp return out, req.Send() } -const opGetCloudFrontOriginAccessIdentity = "GetCloudFrontOriginAccessIdentity2019_03_26" +const opGetCachePolicy = "GetCachePolicy2020_05_31" + +// GetCachePolicyRequest generates a "aws/request.Request" representing the +// client's request for the GetCachePolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetCachePolicy for more information on using the GetCachePolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetCachePolicyRequest method. +// req, resp := client.GetCachePolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetCachePolicy +func (c *CloudFront) GetCachePolicyRequest(input *GetCachePolicyInput) (req *request.Request, output *GetCachePolicyOutput) { + op := &request.Operation{ + Name: opGetCachePolicy, + HTTPMethod: "GET", + HTTPPath: "/2020-05-31/cache-policy/{Id}", + } + + if input == nil { + input = &GetCachePolicyInput{} + } + + output = &GetCachePolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetCachePolicy API operation for Amazon CloudFront. +// +// Gets a cache policy, including the following metadata: +// +// * The policy’s identifier. +// +// * The date and time when the policy was last modified. +// +// To get a cache policy, you must provide the policy’s identifier. If the +// cache policy is attached to a distribution’s cache behavior, you can get +// the policy’s identifier using ListDistributions or GetDistribution. If +// the cache policy is not attached to a cache behavior, you can get the identifier +// using ListCachePolicies. +// +// Returns awserr.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 CloudFront's +// API operation GetCachePolicy for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodeNoSuchCachePolicy "NoSuchCachePolicy" +// The cache policy does not exist. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetCachePolicy +func (c *CloudFront) GetCachePolicy(input *GetCachePolicyInput) (*GetCachePolicyOutput, error) { + req, out := c.GetCachePolicyRequest(input) + return out, req.Send() +} + +// GetCachePolicyWithContext is the same as GetCachePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetCachePolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) GetCachePolicyWithContext(ctx aws.Context, input *GetCachePolicyInput, opts ...request.Option) (*GetCachePolicyOutput, error) { + req, out := c.GetCachePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetCachePolicyConfig = "GetCachePolicyConfig2020_05_31" + +// GetCachePolicyConfigRequest generates a "aws/request.Request" representing the +// client's request for the GetCachePolicyConfig operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetCachePolicyConfig for more information on using the GetCachePolicyConfig +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetCachePolicyConfigRequest method. +// req, resp := client.GetCachePolicyConfigRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetCachePolicyConfig +func (c *CloudFront) GetCachePolicyConfigRequest(input *GetCachePolicyConfigInput) (req *request.Request, output *GetCachePolicyConfigOutput) { + op := &request.Operation{ + Name: opGetCachePolicyConfig, + HTTPMethod: "GET", + HTTPPath: "/2020-05-31/cache-policy/{Id}/config", + } + + if input == nil { + input = &GetCachePolicyConfigInput{} + } + + output = &GetCachePolicyConfigOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetCachePolicyConfig API operation for Amazon CloudFront. +// +// Gets a cache policy configuration. +// +// To get a cache policy configuration, you must provide the policy’s identifier. +// If the cache policy is attached to a distribution’s cache behavior, you +// can get the policy’s identifier using ListDistributions or GetDistribution. +// If the cache policy is not attached to a cache behavior, you can get the +// identifier using ListCachePolicies. +// +// Returns awserr.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 CloudFront's +// API operation GetCachePolicyConfig for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodeNoSuchCachePolicy "NoSuchCachePolicy" +// The cache policy does not exist. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetCachePolicyConfig +func (c *CloudFront) GetCachePolicyConfig(input *GetCachePolicyConfigInput) (*GetCachePolicyConfigOutput, error) { + req, out := c.GetCachePolicyConfigRequest(input) + return out, req.Send() +} + +// GetCachePolicyConfigWithContext is the same as GetCachePolicyConfig with the addition of +// the ability to pass a context and additional request options. +// +// See GetCachePolicyConfig for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) GetCachePolicyConfigWithContext(ctx aws.Context, input *GetCachePolicyConfigInput, opts ...request.Option) (*GetCachePolicyConfigOutput, error) { + req, out := c.GetCachePolicyConfigRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetCloudFrontOriginAccessIdentity = "GetCloudFrontOriginAccessIdentity2020_05_31" // GetCloudFrontOriginAccessIdentityRequest generates a "aws/request.Request" representing the // client's request for the GetCloudFrontOriginAccessIdentity operation. The "output" return @@ -1858,12 +2552,12 @@ const opGetCloudFrontOriginAccessIdentity = "GetCloudFrontOriginAccessIdentity20 // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetCloudFrontOriginAccessIdentity +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetCloudFrontOriginAccessIdentity func (c *CloudFront) GetCloudFrontOriginAccessIdentityRequest(input *GetCloudFrontOriginAccessIdentityInput) (req *request.Request, output *GetCloudFrontOriginAccessIdentityOutput) { op := &request.Operation{ Name: opGetCloudFrontOriginAccessIdentity, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/origin-access-identity/cloudfront/{Id}", + HTTPPath: "/2020-05-31/origin-access-identity/cloudfront/{Id}", } if input == nil { @@ -1893,7 +2587,7 @@ func (c *CloudFront) GetCloudFrontOriginAccessIdentityRequest(input *GetCloudFro // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetCloudFrontOriginAccessIdentity +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetCloudFrontOriginAccessIdentity func (c *CloudFront) GetCloudFrontOriginAccessIdentity(input *GetCloudFrontOriginAccessIdentityInput) (*GetCloudFrontOriginAccessIdentityOutput, error) { req, out := c.GetCloudFrontOriginAccessIdentityRequest(input) return out, req.Send() @@ -1915,7 +2609,7 @@ func (c *CloudFront) GetCloudFrontOriginAccessIdentityWithContext(ctx aws.Contex return out, req.Send() } -const opGetCloudFrontOriginAccessIdentityConfig = "GetCloudFrontOriginAccessIdentityConfig2019_03_26" +const opGetCloudFrontOriginAccessIdentityConfig = "GetCloudFrontOriginAccessIdentityConfig2020_05_31" // GetCloudFrontOriginAccessIdentityConfigRequest generates a "aws/request.Request" representing the // client's request for the GetCloudFrontOriginAccessIdentityConfig operation. The "output" return @@ -1940,12 +2634,12 @@ const opGetCloudFrontOriginAccessIdentityConfig = "GetCloudFrontOriginAccessIden // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetCloudFrontOriginAccessIdentityConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetCloudFrontOriginAccessIdentityConfig func (c *CloudFront) GetCloudFrontOriginAccessIdentityConfigRequest(input *GetCloudFrontOriginAccessIdentityConfigInput) (req *request.Request, output *GetCloudFrontOriginAccessIdentityConfigOutput) { op := &request.Operation{ Name: opGetCloudFrontOriginAccessIdentityConfig, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/origin-access-identity/cloudfront/{Id}/config", + HTTPPath: "/2020-05-31/origin-access-identity/cloudfront/{Id}/config", } if input == nil { @@ -1975,7 +2669,7 @@ func (c *CloudFront) GetCloudFrontOriginAccessIdentityConfigRequest(input *GetCl // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetCloudFrontOriginAccessIdentityConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetCloudFrontOriginAccessIdentityConfig func (c *CloudFront) GetCloudFrontOriginAccessIdentityConfig(input *GetCloudFrontOriginAccessIdentityConfigInput) (*GetCloudFrontOriginAccessIdentityConfigOutput, error) { req, out := c.GetCloudFrontOriginAccessIdentityConfigRequest(input) return out, req.Send() @@ -1997,7 +2691,7 @@ func (c *CloudFront) GetCloudFrontOriginAccessIdentityConfigWithContext(ctx aws. return out, req.Send() } -const opGetDistribution = "GetDistribution2019_03_26" +const opGetDistribution = "GetDistribution2020_05_31" // GetDistributionRequest generates a "aws/request.Request" representing the // client's request for the GetDistribution operation. The "output" return @@ -2022,12 +2716,12 @@ const opGetDistribution = "GetDistribution2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetDistribution func (c *CloudFront) GetDistributionRequest(input *GetDistributionInput) (req *request.Request, output *GetDistributionOutput) { op := &request.Operation{ Name: opGetDistribution, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/distribution/{Id}", + HTTPPath: "/2020-05-31/distribution/{Id}", } if input == nil { @@ -2057,7 +2751,7 @@ func (c *CloudFront) GetDistributionRequest(input *GetDistributionInput) (req *r // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetDistribution func (c *CloudFront) GetDistribution(input *GetDistributionInput) (*GetDistributionOutput, error) { req, out := c.GetDistributionRequest(input) return out, req.Send() @@ -2079,7 +2773,7 @@ func (c *CloudFront) GetDistributionWithContext(ctx aws.Context, input *GetDistr return out, req.Send() } -const opGetDistributionConfig = "GetDistributionConfig2019_03_26" +const opGetDistributionConfig = "GetDistributionConfig2020_05_31" // GetDistributionConfigRequest generates a "aws/request.Request" representing the // client's request for the GetDistributionConfig operation. The "output" return @@ -2104,12 +2798,12 @@ const opGetDistributionConfig = "GetDistributionConfig2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetDistributionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetDistributionConfig func (c *CloudFront) GetDistributionConfigRequest(input *GetDistributionConfigInput) (req *request.Request, output *GetDistributionConfigOutput) { op := &request.Operation{ Name: opGetDistributionConfig, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/distribution/{Id}/config", + HTTPPath: "/2020-05-31/distribution/{Id}/config", } if input == nil { @@ -2139,7 +2833,7 @@ func (c *CloudFront) GetDistributionConfigRequest(input *GetDistributionConfigIn // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetDistributionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetDistributionConfig func (c *CloudFront) GetDistributionConfig(input *GetDistributionConfigInput) (*GetDistributionConfigOutput, error) { req, out := c.GetDistributionConfigRequest(input) return out, req.Send() @@ -2161,7 +2855,7 @@ func (c *CloudFront) GetDistributionConfigWithContext(ctx aws.Context, input *Ge return out, req.Send() } -const opGetFieldLevelEncryption = "GetFieldLevelEncryption2019_03_26" +const opGetFieldLevelEncryption = "GetFieldLevelEncryption2020_05_31" // GetFieldLevelEncryptionRequest generates a "aws/request.Request" representing the // client's request for the GetFieldLevelEncryption operation. The "output" return @@ -2186,12 +2880,12 @@ const opGetFieldLevelEncryption = "GetFieldLevelEncryption2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetFieldLevelEncryption +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetFieldLevelEncryption func (c *CloudFront) GetFieldLevelEncryptionRequest(input *GetFieldLevelEncryptionInput) (req *request.Request, output *GetFieldLevelEncryptionOutput) { op := &request.Operation{ Name: opGetFieldLevelEncryption, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/field-level-encryption/{Id}", + HTTPPath: "/2020-05-31/field-level-encryption/{Id}", } if input == nil { @@ -2221,7 +2915,7 @@ func (c *CloudFront) GetFieldLevelEncryptionRequest(input *GetFieldLevelEncrypti // * ErrCodeNoSuchFieldLevelEncryptionConfig "NoSuchFieldLevelEncryptionConfig" // The specified configuration for field-level encryption doesn't exist. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetFieldLevelEncryption +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetFieldLevelEncryption func (c *CloudFront) GetFieldLevelEncryption(input *GetFieldLevelEncryptionInput) (*GetFieldLevelEncryptionOutput, error) { req, out := c.GetFieldLevelEncryptionRequest(input) return out, req.Send() @@ -2243,7 +2937,7 @@ func (c *CloudFront) GetFieldLevelEncryptionWithContext(ctx aws.Context, input * return out, req.Send() } -const opGetFieldLevelEncryptionConfig = "GetFieldLevelEncryptionConfig2019_03_26" +const opGetFieldLevelEncryptionConfig = "GetFieldLevelEncryptionConfig2020_05_31" // GetFieldLevelEncryptionConfigRequest generates a "aws/request.Request" representing the // client's request for the GetFieldLevelEncryptionConfig operation. The "output" return @@ -2268,12 +2962,12 @@ const opGetFieldLevelEncryptionConfig = "GetFieldLevelEncryptionConfig2019_03_26 // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetFieldLevelEncryptionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetFieldLevelEncryptionConfig func (c *CloudFront) GetFieldLevelEncryptionConfigRequest(input *GetFieldLevelEncryptionConfigInput) (req *request.Request, output *GetFieldLevelEncryptionConfigOutput) { op := &request.Operation{ Name: opGetFieldLevelEncryptionConfig, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/field-level-encryption/{Id}/config", + HTTPPath: "/2020-05-31/field-level-encryption/{Id}/config", } if input == nil { @@ -2303,7 +2997,7 @@ func (c *CloudFront) GetFieldLevelEncryptionConfigRequest(input *GetFieldLevelEn // * ErrCodeNoSuchFieldLevelEncryptionConfig "NoSuchFieldLevelEncryptionConfig" // The specified configuration for field-level encryption doesn't exist. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetFieldLevelEncryptionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetFieldLevelEncryptionConfig func (c *CloudFront) GetFieldLevelEncryptionConfig(input *GetFieldLevelEncryptionConfigInput) (*GetFieldLevelEncryptionConfigOutput, error) { req, out := c.GetFieldLevelEncryptionConfigRequest(input) return out, req.Send() @@ -2325,7 +3019,7 @@ func (c *CloudFront) GetFieldLevelEncryptionConfigWithContext(ctx aws.Context, i return out, req.Send() } -const opGetFieldLevelEncryptionProfile = "GetFieldLevelEncryptionProfile2019_03_26" +const opGetFieldLevelEncryptionProfile = "GetFieldLevelEncryptionProfile2020_05_31" // GetFieldLevelEncryptionProfileRequest generates a "aws/request.Request" representing the // client's request for the GetFieldLevelEncryptionProfile operation. The "output" return @@ -2350,12 +3044,12 @@ const opGetFieldLevelEncryptionProfile = "GetFieldLevelEncryptionProfile2019_03_ // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetFieldLevelEncryptionProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetFieldLevelEncryptionProfile func (c *CloudFront) GetFieldLevelEncryptionProfileRequest(input *GetFieldLevelEncryptionProfileInput) (req *request.Request, output *GetFieldLevelEncryptionProfileOutput) { op := &request.Operation{ Name: opGetFieldLevelEncryptionProfile, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/field-level-encryption-profile/{Id}", + HTTPPath: "/2020-05-31/field-level-encryption-profile/{Id}", } if input == nil { @@ -2385,7 +3079,7 @@ func (c *CloudFront) GetFieldLevelEncryptionProfileRequest(input *GetFieldLevelE // * ErrCodeNoSuchFieldLevelEncryptionProfile "NoSuchFieldLevelEncryptionProfile" // The specified profile for field-level encryption doesn't exist. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetFieldLevelEncryptionProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetFieldLevelEncryptionProfile func (c *CloudFront) GetFieldLevelEncryptionProfile(input *GetFieldLevelEncryptionProfileInput) (*GetFieldLevelEncryptionProfileOutput, error) { req, out := c.GetFieldLevelEncryptionProfileRequest(input) return out, req.Send() @@ -2407,7 +3101,7 @@ func (c *CloudFront) GetFieldLevelEncryptionProfileWithContext(ctx aws.Context, return out, req.Send() } -const opGetFieldLevelEncryptionProfileConfig = "GetFieldLevelEncryptionProfileConfig2019_03_26" +const opGetFieldLevelEncryptionProfileConfig = "GetFieldLevelEncryptionProfileConfig2020_05_31" // GetFieldLevelEncryptionProfileConfigRequest generates a "aws/request.Request" representing the // client's request for the GetFieldLevelEncryptionProfileConfig operation. The "output" return @@ -2432,12 +3126,12 @@ const opGetFieldLevelEncryptionProfileConfig = "GetFieldLevelEncryptionProfileCo // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetFieldLevelEncryptionProfileConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetFieldLevelEncryptionProfileConfig func (c *CloudFront) GetFieldLevelEncryptionProfileConfigRequest(input *GetFieldLevelEncryptionProfileConfigInput) (req *request.Request, output *GetFieldLevelEncryptionProfileConfigOutput) { op := &request.Operation{ Name: opGetFieldLevelEncryptionProfileConfig, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/field-level-encryption-profile/{Id}/config", + HTTPPath: "/2020-05-31/field-level-encryption-profile/{Id}/config", } if input == nil { @@ -2467,7 +3161,7 @@ func (c *CloudFront) GetFieldLevelEncryptionProfileConfigRequest(input *GetField // * ErrCodeNoSuchFieldLevelEncryptionProfile "NoSuchFieldLevelEncryptionProfile" // The specified profile for field-level encryption doesn't exist. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetFieldLevelEncryptionProfileConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetFieldLevelEncryptionProfileConfig func (c *CloudFront) GetFieldLevelEncryptionProfileConfig(input *GetFieldLevelEncryptionProfileConfigInput) (*GetFieldLevelEncryptionProfileConfigOutput, error) { req, out := c.GetFieldLevelEncryptionProfileConfigRequest(input) return out, req.Send() @@ -2489,7 +3183,7 @@ func (c *CloudFront) GetFieldLevelEncryptionProfileConfigWithContext(ctx aws.Con return out, req.Send() } -const opGetInvalidation = "GetInvalidation2019_03_26" +const opGetInvalidation = "GetInvalidation2020_05_31" // GetInvalidationRequest generates a "aws/request.Request" representing the // client's request for the GetInvalidation operation. The "output" return @@ -2514,12 +3208,12 @@ const opGetInvalidation = "GetInvalidation2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetInvalidation +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetInvalidation func (c *CloudFront) GetInvalidationRequest(input *GetInvalidationInput) (req *request.Request, output *GetInvalidationOutput) { op := &request.Operation{ Name: opGetInvalidation, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/distribution/{DistributionId}/invalidation/{Id}", + HTTPPath: "/2020-05-31/distribution/{DistributionId}/invalidation/{Id}", } if input == nil { @@ -2552,7 +3246,7 @@ func (c *CloudFront) GetInvalidationRequest(input *GetInvalidationInput) (req *r // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetInvalidation +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetInvalidation func (c *CloudFront) GetInvalidation(input *GetInvalidationInput) (*GetInvalidationOutput, error) { req, out := c.GetInvalidationRequest(input) return out, req.Send() @@ -2574,181 +3268,361 @@ func (c *CloudFront) GetInvalidationWithContext(ctx aws.Context, input *GetInval return out, req.Send() } -const opGetPublicKey = "GetPublicKey2019_03_26" +const opGetOriginRequestPolicy = "GetOriginRequestPolicy2020_05_31" -// GetPublicKeyRequest generates a "aws/request.Request" representing the -// client's request for the GetPublicKey operation. The "output" return +// GetOriginRequestPolicyRequest generates a "aws/request.Request" representing the +// client's request for the GetOriginRequestPolicy operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetPublicKey for more information on using the GetPublicKey +// See GetOriginRequestPolicy for more information on using the GetOriginRequestPolicy // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetPublicKeyRequest method. -// req, resp := client.GetPublicKeyRequest(params) +// // Example sending a request using the GetOriginRequestPolicyRequest method. +// req, resp := client.GetOriginRequestPolicyRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetPublicKey -func (c *CloudFront) GetPublicKeyRequest(input *GetPublicKeyInput) (req *request.Request, output *GetPublicKeyOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetOriginRequestPolicy +func (c *CloudFront) GetOriginRequestPolicyRequest(input *GetOriginRequestPolicyInput) (req *request.Request, output *GetOriginRequestPolicyOutput) { op := &request.Operation{ - Name: opGetPublicKey, + Name: opGetOriginRequestPolicy, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/public-key/{Id}", + HTTPPath: "/2020-05-31/origin-request-policy/{Id}", } if input == nil { - input = &GetPublicKeyInput{} + input = &GetOriginRequestPolicyInput{} } - output = &GetPublicKeyOutput{} + output = &GetOriginRequestPolicyOutput{} req = c.newRequest(op, input, output) return } -// GetPublicKey API operation for Amazon CloudFront. +// GetOriginRequestPolicy API operation for Amazon CloudFront. // -// Get the public key information. +// Gets an origin request policy, including the following metadata: +// +// * The policy’s identifier. +// +// * The date and time when the policy was last modified. +// +// To get an origin request policy, you must provide the policy’s identifier. +// If the origin request policy is attached to a distribution’s cache behavior, +// you can get the policy’s identifier using ListDistributions or GetDistribution. +// If the origin request policy is not attached to a cache behavior, you can +// get the identifier using ListOriginRequestPolicies. // // Returns awserr.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 CloudFront's -// API operation GetPublicKey for usage and error information. +// API operation GetOriginRequestPolicy for usage and error information. // // Returned Error Codes: // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// * ErrCodeNoSuchPublicKey "NoSuchPublicKey" -// The specified public key doesn't exist. +// * ErrCodeNoSuchOriginRequestPolicy "NoSuchOriginRequestPolicy" +// The origin request policy does not exist. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetPublicKey -func (c *CloudFront) GetPublicKey(input *GetPublicKeyInput) (*GetPublicKeyOutput, error) { - req, out := c.GetPublicKeyRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetOriginRequestPolicy +func (c *CloudFront) GetOriginRequestPolicy(input *GetOriginRequestPolicyInput) (*GetOriginRequestPolicyOutput, error) { + req, out := c.GetOriginRequestPolicyRequest(input) return out, req.Send() } -// GetPublicKeyWithContext is the same as GetPublicKey with the addition of +// GetOriginRequestPolicyWithContext is the same as GetOriginRequestPolicy with the addition of // the ability to pass a context and additional request options. // -// See GetPublicKey for details on how to use this API operation. +// See GetOriginRequestPolicy for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) GetPublicKeyWithContext(ctx aws.Context, input *GetPublicKeyInput, opts ...request.Option) (*GetPublicKeyOutput, error) { - req, out := c.GetPublicKeyRequest(input) +func (c *CloudFront) GetOriginRequestPolicyWithContext(ctx aws.Context, input *GetOriginRequestPolicyInput, opts ...request.Option) (*GetOriginRequestPolicyOutput, error) { + req, out := c.GetOriginRequestPolicyRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetPublicKeyConfig = "GetPublicKeyConfig2019_03_26" +const opGetOriginRequestPolicyConfig = "GetOriginRequestPolicyConfig2020_05_31" -// GetPublicKeyConfigRequest generates a "aws/request.Request" representing the -// client's request for the GetPublicKeyConfig operation. The "output" return +// GetOriginRequestPolicyConfigRequest generates a "aws/request.Request" representing the +// client's request for the GetOriginRequestPolicyConfig operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetPublicKeyConfig for more information on using the GetPublicKeyConfig +// See GetOriginRequestPolicyConfig for more information on using the GetOriginRequestPolicyConfig // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetPublicKeyConfigRequest method. -// req, resp := client.GetPublicKeyConfigRequest(params) +// // Example sending a request using the GetOriginRequestPolicyConfigRequest method. +// req, resp := client.GetOriginRequestPolicyConfigRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetPublicKeyConfig -func (c *CloudFront) GetPublicKeyConfigRequest(input *GetPublicKeyConfigInput) (req *request.Request, output *GetPublicKeyConfigOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetOriginRequestPolicyConfig +func (c *CloudFront) GetOriginRequestPolicyConfigRequest(input *GetOriginRequestPolicyConfigInput) (req *request.Request, output *GetOriginRequestPolicyConfigOutput) { op := &request.Operation{ - Name: opGetPublicKeyConfig, + Name: opGetOriginRequestPolicyConfig, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/public-key/{Id}/config", + HTTPPath: "/2020-05-31/origin-request-policy/{Id}/config", } if input == nil { - input = &GetPublicKeyConfigInput{} + input = &GetOriginRequestPolicyConfigInput{} } - output = &GetPublicKeyConfigOutput{} + output = &GetOriginRequestPolicyConfigOutput{} req = c.newRequest(op, input, output) return } -// GetPublicKeyConfig API operation for Amazon CloudFront. +// GetOriginRequestPolicyConfig API operation for Amazon CloudFront. // -// Return public key configuration informaation +// Gets an origin request policy configuration. +// +// To get an origin request policy configuration, you must provide the policy’s +// identifier. If the origin request policy is attached to a distribution’s +// cache behavior, you can get the policy’s identifier using ListDistributions +// or GetDistribution. If the origin request policy is not attached to a cache +// behavior, you can get the identifier using ListOriginRequestPolicies. // // Returns awserr.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 CloudFront's -// API operation GetPublicKeyConfig for usage and error information. +// API operation GetOriginRequestPolicyConfig for usage and error information. // // Returned Error Codes: // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// * ErrCodeNoSuchPublicKey "NoSuchPublicKey" -// The specified public key doesn't exist. +// * ErrCodeNoSuchOriginRequestPolicy "NoSuchOriginRequestPolicy" +// The origin request policy does not exist. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetPublicKeyConfig -func (c *CloudFront) GetPublicKeyConfig(input *GetPublicKeyConfigInput) (*GetPublicKeyConfigOutput, error) { - req, out := c.GetPublicKeyConfigRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetOriginRequestPolicyConfig +func (c *CloudFront) GetOriginRequestPolicyConfig(input *GetOriginRequestPolicyConfigInput) (*GetOriginRequestPolicyConfigOutput, error) { + req, out := c.GetOriginRequestPolicyConfigRequest(input) return out, req.Send() } -// GetPublicKeyConfigWithContext is the same as GetPublicKeyConfig with the addition of +// GetOriginRequestPolicyConfigWithContext is the same as GetOriginRequestPolicyConfig with the addition of // the ability to pass a context and additional request options. // -// See GetPublicKeyConfig for details on how to use this API operation. +// See GetOriginRequestPolicyConfig for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) GetPublicKeyConfigWithContext(ctx aws.Context, input *GetPublicKeyConfigInput, opts ...request.Option) (*GetPublicKeyConfigOutput, error) { - req, out := c.GetPublicKeyConfigRequest(input) +func (c *CloudFront) GetOriginRequestPolicyConfigWithContext(ctx aws.Context, input *GetOriginRequestPolicyConfigInput, opts ...request.Option) (*GetOriginRequestPolicyConfigOutput, error) { + req, out := c.GetOriginRequestPolicyConfigRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetStreamingDistribution = "GetStreamingDistribution2019_03_26" +const opGetPublicKey = "GetPublicKey2020_05_31" -// GetStreamingDistributionRequest generates a "aws/request.Request" representing the -// client's request for the GetStreamingDistribution operation. The "output" return +// GetPublicKeyRequest generates a "aws/request.Request" representing the +// client's request for the GetPublicKey operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetStreamingDistribution for more information on using the GetStreamingDistribution +// See GetPublicKey for more information on using the GetPublicKey +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetPublicKeyRequest method. +// req, resp := client.GetPublicKeyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetPublicKey +func (c *CloudFront) GetPublicKeyRequest(input *GetPublicKeyInput) (req *request.Request, output *GetPublicKeyOutput) { + op := &request.Operation{ + Name: opGetPublicKey, + HTTPMethod: "GET", + HTTPPath: "/2020-05-31/public-key/{Id}", + } + + if input == nil { + input = &GetPublicKeyInput{} + } + + output = &GetPublicKeyOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetPublicKey API operation for Amazon CloudFront. +// +// Get the public key information. +// +// Returns awserr.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 CloudFront's +// API operation GetPublicKey for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodeNoSuchPublicKey "NoSuchPublicKey" +// The specified public key doesn't exist. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetPublicKey +func (c *CloudFront) GetPublicKey(input *GetPublicKeyInput) (*GetPublicKeyOutput, error) { + req, out := c.GetPublicKeyRequest(input) + return out, req.Send() +} + +// GetPublicKeyWithContext is the same as GetPublicKey with the addition of +// the ability to pass a context and additional request options. +// +// See GetPublicKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) GetPublicKeyWithContext(ctx aws.Context, input *GetPublicKeyInput, opts ...request.Option) (*GetPublicKeyOutput, error) { + req, out := c.GetPublicKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetPublicKeyConfig = "GetPublicKeyConfig2020_05_31" + +// GetPublicKeyConfigRequest generates a "aws/request.Request" representing the +// client's request for the GetPublicKeyConfig operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetPublicKeyConfig for more information on using the GetPublicKeyConfig +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetPublicKeyConfigRequest method. +// req, resp := client.GetPublicKeyConfigRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetPublicKeyConfig +func (c *CloudFront) GetPublicKeyConfigRequest(input *GetPublicKeyConfigInput) (req *request.Request, output *GetPublicKeyConfigOutput) { + op := &request.Operation{ + Name: opGetPublicKeyConfig, + HTTPMethod: "GET", + HTTPPath: "/2020-05-31/public-key/{Id}/config", + } + + if input == nil { + input = &GetPublicKeyConfigInput{} + } + + output = &GetPublicKeyConfigOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetPublicKeyConfig API operation for Amazon CloudFront. +// +// Return public key configuration informaation +// +// Returns awserr.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 CloudFront's +// API operation GetPublicKeyConfig for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodeNoSuchPublicKey "NoSuchPublicKey" +// The specified public key doesn't exist. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetPublicKeyConfig +func (c *CloudFront) GetPublicKeyConfig(input *GetPublicKeyConfigInput) (*GetPublicKeyConfigOutput, error) { + req, out := c.GetPublicKeyConfigRequest(input) + return out, req.Send() +} + +// GetPublicKeyConfigWithContext is the same as GetPublicKeyConfig with the addition of +// the ability to pass a context and additional request options. +// +// See GetPublicKeyConfig for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) GetPublicKeyConfigWithContext(ctx aws.Context, input *GetPublicKeyConfigInput, opts ...request.Option) (*GetPublicKeyConfigOutput, error) { + req, out := c.GetPublicKeyConfigRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetStreamingDistribution = "GetStreamingDistribution2020_05_31" + +// GetStreamingDistributionRequest generates a "aws/request.Request" representing the +// client's request for the GetStreamingDistribution operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetStreamingDistribution for more information on using the GetStreamingDistribution // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration @@ -2763,12 +3637,12 @@ const opGetStreamingDistribution = "GetStreamingDistribution2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetStreamingDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetStreamingDistribution func (c *CloudFront) GetStreamingDistributionRequest(input *GetStreamingDistributionInput) (req *request.Request, output *GetStreamingDistributionOutput) { op := &request.Operation{ Name: opGetStreamingDistribution, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/streaming-distribution/{Id}", + HTTPPath: "/2020-05-31/streaming-distribution/{Id}", } if input == nil { @@ -2799,7 +3673,7 @@ func (c *CloudFront) GetStreamingDistributionRequest(input *GetStreamingDistribu // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetStreamingDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetStreamingDistribution func (c *CloudFront) GetStreamingDistribution(input *GetStreamingDistributionInput) (*GetStreamingDistributionOutput, error) { req, out := c.GetStreamingDistributionRequest(input) return out, req.Send() @@ -2821,7 +3695,7 @@ func (c *CloudFront) GetStreamingDistributionWithContext(ctx aws.Context, input return out, req.Send() } -const opGetStreamingDistributionConfig = "GetStreamingDistributionConfig2019_03_26" +const opGetStreamingDistributionConfig = "GetStreamingDistributionConfig2020_05_31" // GetStreamingDistributionConfigRequest generates a "aws/request.Request" representing the // client's request for the GetStreamingDistributionConfig operation. The "output" return @@ -2846,12 +3720,12 @@ const opGetStreamingDistributionConfig = "GetStreamingDistributionConfig2019_03_ // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetStreamingDistributionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetStreamingDistributionConfig func (c *CloudFront) GetStreamingDistributionConfigRequest(input *GetStreamingDistributionConfigInput) (req *request.Request, output *GetStreamingDistributionConfigOutput) { op := &request.Operation{ Name: opGetStreamingDistributionConfig, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/streaming-distribution/{Id}/config", + HTTPPath: "/2020-05-31/streaming-distribution/{Id}/config", } if input == nil { @@ -2881,7 +3755,7 @@ func (c *CloudFront) GetStreamingDistributionConfigRequest(input *GetStreamingDi // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/GetStreamingDistributionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/GetStreamingDistributionConfig func (c *CloudFront) GetStreamingDistributionConfig(input *GetStreamingDistributionConfigInput) (*GetStreamingDistributionConfigOutput, error) { req, out := c.GetStreamingDistributionConfigRequest(input) return out, req.Send() @@ -2903,7 +3777,101 @@ func (c *CloudFront) GetStreamingDistributionConfigWithContext(ctx aws.Context, return out, req.Send() } -const opListCloudFrontOriginAccessIdentities = "ListCloudFrontOriginAccessIdentities2019_03_26" +const opListCachePolicies = "ListCachePolicies2020_05_31" + +// ListCachePoliciesRequest generates a "aws/request.Request" representing the +// client's request for the ListCachePolicies operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListCachePolicies for more information on using the ListCachePolicies +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListCachePoliciesRequest method. +// req, resp := client.ListCachePoliciesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListCachePolicies +func (c *CloudFront) ListCachePoliciesRequest(input *ListCachePoliciesInput) (req *request.Request, output *ListCachePoliciesOutput) { + op := &request.Operation{ + Name: opListCachePolicies, + HTTPMethod: "GET", + HTTPPath: "/2020-05-31/cache-policy", + } + + if input == nil { + input = &ListCachePoliciesInput{} + } + + output = &ListCachePoliciesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListCachePolicies API operation for Amazon CloudFront. +// +// Gets a list of cache policies. +// +// You can optionally apply a filter to return only the managed policies created +// by AWS, or only the custom policies created in your AWS account. +// +// You can optionally specify the maximum number of items to receive in the +// response. If the total number of items in the list exceeds the maximum that +// you specify, or the default maximum, the response is paginated. To get the +// next page of items, send a subsequent request that specifies the NextMarker +// value from the current response as the Marker value in the subsequent 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 Amazon CloudFront's +// API operation ListCachePolicies for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodeNoSuchCachePolicy "NoSuchCachePolicy" +// The cache policy does not exist. +// +// * ErrCodeInvalidArgument "InvalidArgument" +// An argument is invalid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListCachePolicies +func (c *CloudFront) ListCachePolicies(input *ListCachePoliciesInput) (*ListCachePoliciesOutput, error) { + req, out := c.ListCachePoliciesRequest(input) + return out, req.Send() +} + +// ListCachePoliciesWithContext is the same as ListCachePolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListCachePolicies for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListCachePoliciesWithContext(ctx aws.Context, input *ListCachePoliciesInput, opts ...request.Option) (*ListCachePoliciesOutput, error) { + req, out := c.ListCachePoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListCloudFrontOriginAccessIdentities = "ListCloudFrontOriginAccessIdentities2020_05_31" // ListCloudFrontOriginAccessIdentitiesRequest generates a "aws/request.Request" representing the // client's request for the ListCloudFrontOriginAccessIdentities operation. The "output" return @@ -2928,12 +3896,12 @@ const opListCloudFrontOriginAccessIdentities = "ListCloudFrontOriginAccessIdenti // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListCloudFrontOriginAccessIdentities +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListCloudFrontOriginAccessIdentities func (c *CloudFront) ListCloudFrontOriginAccessIdentitiesRequest(input *ListCloudFrontOriginAccessIdentitiesInput) (req *request.Request, output *ListCloudFrontOriginAccessIdentitiesOutput) { op := &request.Operation{ Name: opListCloudFrontOriginAccessIdentities, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/origin-access-identity/cloudfront", + HTTPPath: "/2020-05-31/origin-access-identity/cloudfront", Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"CloudFrontOriginAccessIdentityList.NextMarker"}, @@ -2964,9 +3932,9 @@ func (c *CloudFront) ListCloudFrontOriginAccessIdentitiesRequest(input *ListClou // // Returned Error Codes: // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListCloudFrontOriginAccessIdentities +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListCloudFrontOriginAccessIdentities func (c *CloudFront) ListCloudFrontOriginAccessIdentities(input *ListCloudFrontOriginAccessIdentitiesInput) (*ListCloudFrontOriginAccessIdentitiesOutput, error) { req, out := c.ListCloudFrontOriginAccessIdentitiesRequest(input) return out, req.Send() @@ -3040,7 +4008,7 @@ func (c *CloudFront) ListCloudFrontOriginAccessIdentitiesPagesWithContext(ctx aw return p.Err() } -const opListDistributions = "ListDistributions2019_03_26" +const opListDistributions = "ListDistributions2020_05_31" // ListDistributionsRequest generates a "aws/request.Request" representing the // client's request for the ListDistributions operation. The "output" return @@ -3065,12 +4033,12 @@ const opListDistributions = "ListDistributions2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListDistributions +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListDistributions func (c *CloudFront) ListDistributionsRequest(input *ListDistributionsInput) (req *request.Request, output *ListDistributionsOutput) { op := &request.Operation{ Name: opListDistributions, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/distribution", + HTTPPath: "/2020-05-31/distribution", Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"DistributionList.NextMarker"}, @@ -3101,9 +4069,9 @@ func (c *CloudFront) ListDistributionsRequest(input *ListDistributionsInput) (re // // Returned Error Codes: // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListDistributions +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListDistributions func (c *CloudFront) ListDistributions(input *ListDistributionsInput) (*ListDistributionsOutput, error) { req, out := c.ListDistributionsRequest(input) return out, req.Send() @@ -3177,134 +4145,318 @@ func (c *CloudFront) ListDistributionsPagesWithContext(ctx aws.Context, input *L return p.Err() } -const opListDistributionsByWebACLId = "ListDistributionsByWebACLId2019_03_26" +const opListDistributionsByCachePolicyId = "ListDistributionsByCachePolicyId2020_05_31" -// ListDistributionsByWebACLIdRequest generates a "aws/request.Request" representing the -// client's request for the ListDistributionsByWebACLId operation. The "output" return +// ListDistributionsByCachePolicyIdRequest generates a "aws/request.Request" representing the +// client's request for the ListDistributionsByCachePolicyId operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListDistributionsByWebACLId for more information on using the ListDistributionsByWebACLId +// See ListDistributionsByCachePolicyId for more information on using the ListDistributionsByCachePolicyId // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListDistributionsByWebACLIdRequest method. -// req, resp := client.ListDistributionsByWebACLIdRequest(params) +// // Example sending a request using the ListDistributionsByCachePolicyIdRequest method. +// req, resp := client.ListDistributionsByCachePolicyIdRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListDistributionsByWebACLId -func (c *CloudFront) ListDistributionsByWebACLIdRequest(input *ListDistributionsByWebACLIdInput) (req *request.Request, output *ListDistributionsByWebACLIdOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListDistributionsByCachePolicyId +func (c *CloudFront) ListDistributionsByCachePolicyIdRequest(input *ListDistributionsByCachePolicyIdInput) (req *request.Request, output *ListDistributionsByCachePolicyIdOutput) { op := &request.Operation{ - Name: opListDistributionsByWebACLId, + Name: opListDistributionsByCachePolicyId, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/distributionsByWebACLId/{WebACLId}", + HTTPPath: "/2020-05-31/distributionsByCachePolicyId/{CachePolicyId}", } if input == nil { - input = &ListDistributionsByWebACLIdInput{} + input = &ListDistributionsByCachePolicyIdInput{} } - output = &ListDistributionsByWebACLIdOutput{} + output = &ListDistributionsByCachePolicyIdOutput{} req = c.newRequest(op, input, output) return } -// ListDistributionsByWebACLId API operation for Amazon CloudFront. +// ListDistributionsByCachePolicyId API operation for Amazon CloudFront. // -// List the distributions that are associated with a specified AWS WAF web ACL. +// Gets a list of distribution IDs for distributions that have a cache behavior +// that’s associated with the specified cache policy. +// +// You can optionally specify the maximum number of items to receive in the +// response. If the total number of items in the list exceeds the maximum that +// you specify, or the default maximum, the response is paginated. To get the +// next page of items, send a subsequent request that specifies the NextMarker +// value from the current response as the Marker value in the subsequent 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 Amazon CloudFront's -// API operation ListDistributionsByWebACLId for usage and error information. +// API operation ListDistributionsByCachePolicyId for usage and error information. // // Returned Error Codes: +// * ErrCodeNoSuchCachePolicy "NoSuchCachePolicy" +// The cache policy does not exist. +// // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // -// * ErrCodeInvalidWebACLId "InvalidWebACLId" -// A web ACL ID specified is not valid. To specify a web ACL created using the -// latest version of AWS WAF, use the ACL ARN, for example arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a. -// To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example -// 473e64fd-f30b-4765-81a0-62ad96dd167a. +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListDistributionsByWebACLId -func (c *CloudFront) ListDistributionsByWebACLId(input *ListDistributionsByWebACLIdInput) (*ListDistributionsByWebACLIdOutput, error) { - req, out := c.ListDistributionsByWebACLIdRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListDistributionsByCachePolicyId +func (c *CloudFront) ListDistributionsByCachePolicyId(input *ListDistributionsByCachePolicyIdInput) (*ListDistributionsByCachePolicyIdOutput, error) { + req, out := c.ListDistributionsByCachePolicyIdRequest(input) return out, req.Send() } -// ListDistributionsByWebACLIdWithContext is the same as ListDistributionsByWebACLId with the addition of +// ListDistributionsByCachePolicyIdWithContext is the same as ListDistributionsByCachePolicyId 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. +// See ListDistributionsByCachePolicyId for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *CloudFront) ListDistributionsByCachePolicyIdWithContext(ctx aws.Context, input *ListDistributionsByCachePolicyIdInput, opts ...request.Option) (*ListDistributionsByCachePolicyIdOutput, error) { + req, out := c.ListDistributionsByCachePolicyIdRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opListFieldLevelEncryptionConfigs = "ListFieldLevelEncryptionConfigs2019_03_26" +const opListDistributionsByOriginRequestPolicyId = "ListDistributionsByOriginRequestPolicyId2020_05_31" -// ListFieldLevelEncryptionConfigsRequest generates a "aws/request.Request" representing the -// client's request for the ListFieldLevelEncryptionConfigs operation. The "output" return +// ListDistributionsByOriginRequestPolicyIdRequest generates a "aws/request.Request" representing the +// client's request for the ListDistributionsByOriginRequestPolicyId operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListFieldLevelEncryptionConfigs for more information on using the ListFieldLevelEncryptionConfigs +// See ListDistributionsByOriginRequestPolicyId for more information on using the ListDistributionsByOriginRequestPolicyId // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListFieldLevelEncryptionConfigsRequest method. -// req, resp := client.ListFieldLevelEncryptionConfigsRequest(params) +// // Example sending a request using the ListDistributionsByOriginRequestPolicyIdRequest method. +// req, resp := client.ListDistributionsByOriginRequestPolicyIdRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListFieldLevelEncryptionConfigs -func (c *CloudFront) ListFieldLevelEncryptionConfigsRequest(input *ListFieldLevelEncryptionConfigsInput) (req *request.Request, output *ListFieldLevelEncryptionConfigsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListDistributionsByOriginRequestPolicyId +func (c *CloudFront) ListDistributionsByOriginRequestPolicyIdRequest(input *ListDistributionsByOriginRequestPolicyIdInput) (req *request.Request, output *ListDistributionsByOriginRequestPolicyIdOutput) { op := &request.Operation{ - Name: opListFieldLevelEncryptionConfigs, + Name: opListDistributionsByOriginRequestPolicyId, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/field-level-encryption", + HTTPPath: "/2020-05-31/distributionsByOriginRequestPolicyId/{OriginRequestPolicyId}", } if input == nil { - input = &ListFieldLevelEncryptionConfigsInput{} + input = &ListDistributionsByOriginRequestPolicyIdInput{} } - output = &ListFieldLevelEncryptionConfigsOutput{} + output = &ListDistributionsByOriginRequestPolicyIdOutput{} req = c.newRequest(op, input, output) return } -// ListFieldLevelEncryptionConfigs API operation for Amazon CloudFront. +// ListDistributionsByOriginRequestPolicyId API operation for Amazon CloudFront. +// +// Gets a list of distribution IDs for distributions that have a cache behavior +// that’s associated with the specified origin request policy. +// +// You can optionally specify the maximum number of items to receive in the +// response. If the total number of items in the list exceeds the maximum that +// you specify, or the default maximum, the response is paginated. To get the +// next page of items, send a subsequent request that specifies the NextMarker +// value from the current response as the Marker value in the subsequent 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 Amazon CloudFront's +// API operation ListDistributionsByOriginRequestPolicyId for usage and error information. +// +// Returned Error Codes: +// * ErrCodeNoSuchOriginRequestPolicy "NoSuchOriginRequestPolicy" +// The origin request policy does not exist. +// +// * ErrCodeInvalidArgument "InvalidArgument" +// An argument is invalid. +// +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListDistributionsByOriginRequestPolicyId +func (c *CloudFront) ListDistributionsByOriginRequestPolicyId(input *ListDistributionsByOriginRequestPolicyIdInput) (*ListDistributionsByOriginRequestPolicyIdOutput, error) { + req, out := c.ListDistributionsByOriginRequestPolicyIdRequest(input) + return out, req.Send() +} + +// ListDistributionsByOriginRequestPolicyIdWithContext is the same as ListDistributionsByOriginRequestPolicyId with the addition of +// the ability to pass a context and additional request options. +// +// See ListDistributionsByOriginRequestPolicyId for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListDistributionsByOriginRequestPolicyIdWithContext(ctx aws.Context, input *ListDistributionsByOriginRequestPolicyIdInput, opts ...request.Option) (*ListDistributionsByOriginRequestPolicyIdOutput, error) { + req, out := c.ListDistributionsByOriginRequestPolicyIdRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListDistributionsByWebACLId = "ListDistributionsByWebACLId2020_05_31" + +// ListDistributionsByWebACLIdRequest generates a "aws/request.Request" representing the +// client's request for the ListDistributionsByWebACLId operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListDistributionsByWebACLId for more information on using the ListDistributionsByWebACLId +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListDistributionsByWebACLIdRequest method. +// req, resp := client.ListDistributionsByWebACLIdRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListDistributionsByWebACLId +func (c *CloudFront) ListDistributionsByWebACLIdRequest(input *ListDistributionsByWebACLIdInput) (req *request.Request, output *ListDistributionsByWebACLIdOutput) { + op := &request.Operation{ + Name: opListDistributionsByWebACLId, + HTTPMethod: "GET", + HTTPPath: "/2020-05-31/distributionsByWebACLId/{WebACLId}", + } + + if input == nil { + input = &ListDistributionsByWebACLIdInput{} + } + + output = &ListDistributionsByWebACLIdOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListDistributionsByWebACLId API operation for Amazon CloudFront. +// +// List the distributions that are associated with a specified AWS WAF 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 Amazon CloudFront's +// API operation ListDistributionsByWebACLId for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidArgument "InvalidArgument" +// An argument is invalid. +// +// * ErrCodeInvalidWebACLId "InvalidWebACLId" +// A web ACL ID specified is not valid. To specify a web ACL created using the +// latest version of AWS WAF, use the ACL ARN, for example arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a. +// To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example +// 473e64fd-f30b-4765-81a0-62ad96dd167a. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListDistributionsByWebACLId +func (c *CloudFront) ListDistributionsByWebACLId(input *ListDistributionsByWebACLIdInput) (*ListDistributionsByWebACLIdOutput, error) { + req, out := c.ListDistributionsByWebACLIdRequest(input) + return out, req.Send() +} + +// 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 opListFieldLevelEncryptionConfigs = "ListFieldLevelEncryptionConfigs2020_05_31" + +// ListFieldLevelEncryptionConfigsRequest generates a "aws/request.Request" representing the +// client's request for the ListFieldLevelEncryptionConfigs operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListFieldLevelEncryptionConfigs for more information on using the ListFieldLevelEncryptionConfigs +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListFieldLevelEncryptionConfigsRequest method. +// req, resp := client.ListFieldLevelEncryptionConfigsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListFieldLevelEncryptionConfigs +func (c *CloudFront) ListFieldLevelEncryptionConfigsRequest(input *ListFieldLevelEncryptionConfigsInput) (req *request.Request, output *ListFieldLevelEncryptionConfigsOutput) { + op := &request.Operation{ + Name: opListFieldLevelEncryptionConfigs, + HTTPMethod: "GET", + HTTPPath: "/2020-05-31/field-level-encryption", + } + + if input == nil { + input = &ListFieldLevelEncryptionConfigsInput{} + } + + output = &ListFieldLevelEncryptionConfigsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListFieldLevelEncryptionConfigs API operation for Amazon CloudFront. // // List all field-level encryption configurations that have been created in // CloudFront for this account. @@ -3318,9 +4470,9 @@ func (c *CloudFront) ListFieldLevelEncryptionConfigsRequest(input *ListFieldLeve // // Returned Error Codes: // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListFieldLevelEncryptionConfigs +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListFieldLevelEncryptionConfigs func (c *CloudFront) ListFieldLevelEncryptionConfigs(input *ListFieldLevelEncryptionConfigsInput) (*ListFieldLevelEncryptionConfigsOutput, error) { req, out := c.ListFieldLevelEncryptionConfigsRequest(input) return out, req.Send() @@ -3342,7 +4494,7 @@ func (c *CloudFront) ListFieldLevelEncryptionConfigsWithContext(ctx aws.Context, return out, req.Send() } -const opListFieldLevelEncryptionProfiles = "ListFieldLevelEncryptionProfiles2019_03_26" +const opListFieldLevelEncryptionProfiles = "ListFieldLevelEncryptionProfiles2020_05_31" // ListFieldLevelEncryptionProfilesRequest generates a "aws/request.Request" representing the // client's request for the ListFieldLevelEncryptionProfiles operation. The "output" return @@ -3367,12 +4519,12 @@ const opListFieldLevelEncryptionProfiles = "ListFieldLevelEncryptionProfiles2019 // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListFieldLevelEncryptionProfiles +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListFieldLevelEncryptionProfiles func (c *CloudFront) ListFieldLevelEncryptionProfilesRequest(input *ListFieldLevelEncryptionProfilesInput) (req *request.Request, output *ListFieldLevelEncryptionProfilesOutput) { op := &request.Operation{ Name: opListFieldLevelEncryptionProfiles, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/field-level-encryption-profile", + HTTPPath: "/2020-05-31/field-level-encryption-profile", } if input == nil { @@ -3398,9 +4550,9 @@ func (c *CloudFront) ListFieldLevelEncryptionProfilesRequest(input *ListFieldLev // // Returned Error Codes: // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListFieldLevelEncryptionProfiles +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListFieldLevelEncryptionProfiles func (c *CloudFront) ListFieldLevelEncryptionProfiles(input *ListFieldLevelEncryptionProfilesInput) (*ListFieldLevelEncryptionProfilesOutput, error) { req, out := c.ListFieldLevelEncryptionProfilesRequest(input) return out, req.Send() @@ -3422,7 +4574,7 @@ func (c *CloudFront) ListFieldLevelEncryptionProfilesWithContext(ctx aws.Context return out, req.Send() } -const opListInvalidations = "ListInvalidations2019_03_26" +const opListInvalidations = "ListInvalidations2020_05_31" // ListInvalidationsRequest generates a "aws/request.Request" representing the // client's request for the ListInvalidations operation. The "output" return @@ -3447,12 +4599,12 @@ const opListInvalidations = "ListInvalidations2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListInvalidations +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListInvalidations func (c *CloudFront) ListInvalidationsRequest(input *ListInvalidationsInput) (req *request.Request, output *ListInvalidationsOutput) { op := &request.Operation{ Name: opListInvalidations, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/distribution/{DistributionId}/invalidation", + HTTPPath: "/2020-05-31/distribution/{DistributionId}/invalidation", Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"InvalidationList.NextMarker"}, @@ -3483,7 +4635,7 @@ func (c *CloudFront) ListInvalidationsRequest(input *ListInvalidationsInput) (re // // Returned Error Codes: // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeNoSuchDistribution "NoSuchDistribution" // The specified distribution does not exist. @@ -3491,7 +4643,7 @@ func (c *CloudFront) ListInvalidationsRequest(input *ListInvalidationsInput) (re // * ErrCodeAccessDenied "AccessDenied" // Access denied. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListInvalidations +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListInvalidations func (c *CloudFront) ListInvalidations(input *ListInvalidationsInput) (*ListInvalidationsOutput, error) { req, out := c.ListInvalidationsRequest(input) return out, req.Send() @@ -3565,7 +4717,101 @@ func (c *CloudFront) ListInvalidationsPagesWithContext(ctx aws.Context, input *L return p.Err() } -const opListPublicKeys = "ListPublicKeys2019_03_26" +const opListOriginRequestPolicies = "ListOriginRequestPolicies2020_05_31" + +// ListOriginRequestPoliciesRequest generates a "aws/request.Request" representing the +// client's request for the ListOriginRequestPolicies operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListOriginRequestPolicies for more information on using the ListOriginRequestPolicies +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListOriginRequestPoliciesRequest method. +// req, resp := client.ListOriginRequestPoliciesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListOriginRequestPolicies +func (c *CloudFront) ListOriginRequestPoliciesRequest(input *ListOriginRequestPoliciesInput) (req *request.Request, output *ListOriginRequestPoliciesOutput) { + op := &request.Operation{ + Name: opListOriginRequestPolicies, + HTTPMethod: "GET", + HTTPPath: "/2020-05-31/origin-request-policy", + } + + if input == nil { + input = &ListOriginRequestPoliciesInput{} + } + + output = &ListOriginRequestPoliciesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListOriginRequestPolicies API operation for Amazon CloudFront. +// +// Gets a list of origin request policies. +// +// You can optionally apply a filter to return only the managed policies created +// by AWS, or only the custom policies created in your AWS account. +// +// You can optionally specify the maximum number of items to receive in the +// response. If the total number of items in the list exceeds the maximum that +// you specify, or the default maximum, the response is paginated. To get the +// next page of items, send a subsequent request that specifies the NextMarker +// value from the current response as the Marker value in the subsequent 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 Amazon CloudFront's +// API operation ListOriginRequestPolicies for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodeNoSuchOriginRequestPolicy "NoSuchOriginRequestPolicy" +// The origin request policy does not exist. +// +// * ErrCodeInvalidArgument "InvalidArgument" +// An argument is invalid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListOriginRequestPolicies +func (c *CloudFront) ListOriginRequestPolicies(input *ListOriginRequestPoliciesInput) (*ListOriginRequestPoliciesOutput, error) { + req, out := c.ListOriginRequestPoliciesRequest(input) + return out, req.Send() +} + +// ListOriginRequestPoliciesWithContext is the same as ListOriginRequestPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListOriginRequestPolicies for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListOriginRequestPoliciesWithContext(ctx aws.Context, input *ListOriginRequestPoliciesInput, opts ...request.Option) (*ListOriginRequestPoliciesOutput, error) { + req, out := c.ListOriginRequestPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListPublicKeys = "ListPublicKeys2020_05_31" // ListPublicKeysRequest generates a "aws/request.Request" representing the // client's request for the ListPublicKeys operation. The "output" return @@ -3590,12 +4836,12 @@ const opListPublicKeys = "ListPublicKeys2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListPublicKeys +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListPublicKeys func (c *CloudFront) ListPublicKeysRequest(input *ListPublicKeysInput) (req *request.Request, output *ListPublicKeysOutput) { op := &request.Operation{ Name: opListPublicKeys, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/public-key", + HTTPPath: "/2020-05-31/public-key", } if input == nil { @@ -3620,9 +4866,9 @@ func (c *CloudFront) ListPublicKeysRequest(input *ListPublicKeysInput) (req *req // // Returned Error Codes: // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListPublicKeys +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListPublicKeys func (c *CloudFront) ListPublicKeys(input *ListPublicKeysInput) (*ListPublicKeysOutput, error) { req, out := c.ListPublicKeysRequest(input) return out, req.Send() @@ -3644,7 +4890,7 @@ func (c *CloudFront) ListPublicKeysWithContext(ctx aws.Context, input *ListPubli return out, req.Send() } -const opListStreamingDistributions = "ListStreamingDistributions2019_03_26" +const opListStreamingDistributions = "ListStreamingDistributions2020_05_31" // ListStreamingDistributionsRequest generates a "aws/request.Request" representing the // client's request for the ListStreamingDistributions operation. The "output" return @@ -3669,12 +4915,12 @@ const opListStreamingDistributions = "ListStreamingDistributions2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListStreamingDistributions +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListStreamingDistributions func (c *CloudFront) ListStreamingDistributionsRequest(input *ListStreamingDistributionsInput) (req *request.Request, output *ListStreamingDistributionsOutput) { op := &request.Operation{ Name: opListStreamingDistributions, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/streaming-distribution", + HTTPPath: "/2020-05-31/streaming-distribution", Paginator: &request.Paginator{ InputTokens: []string{"Marker"}, OutputTokens: []string{"StreamingDistributionList.NextMarker"}, @@ -3705,9 +4951,9 @@ func (c *CloudFront) ListStreamingDistributionsRequest(input *ListStreamingDistr // // Returned Error Codes: // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListStreamingDistributions +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListStreamingDistributions func (c *CloudFront) ListStreamingDistributions(input *ListStreamingDistributionsInput) (*ListStreamingDistributionsOutput, error) { req, out := c.ListStreamingDistributionsRequest(input) return out, req.Send() @@ -3781,7 +5027,7 @@ func (c *CloudFront) ListStreamingDistributionsPagesWithContext(ctx aws.Context, return p.Err() } -const opListTagsForResource = "ListTagsForResource2019_03_26" +const opListTagsForResource = "ListTagsForResource2020_05_31" // ListTagsForResourceRequest generates a "aws/request.Request" representing the // client's request for the ListTagsForResource operation. The "output" return @@ -3806,12 +5052,12 @@ const opListTagsForResource = "ListTagsForResource2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListTagsForResource +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListTagsForResource func (c *CloudFront) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { op := &request.Operation{ Name: opListTagsForResource, HTTPMethod: "GET", - HTTPPath: "/2019-03-26/tagging", + HTTPPath: "/2020-05-31/tagging", } if input == nil { @@ -3839,7 +5085,7 @@ func (c *CloudFront) ListTagsForResourceRequest(input *ListTagsForResourceInput) // Access denied. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInvalidTagging "InvalidTagging" // The tagging specified is not valid. @@ -3847,7 +5093,7 @@ func (c *CloudFront) ListTagsForResourceRequest(input *ListTagsForResourceInput) // * ErrCodeNoSuchResource "NoSuchResource" // A resource that was specified is not valid. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/ListTagsForResource +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ListTagsForResource func (c *CloudFront) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { req, out := c.ListTagsForResourceRequest(input) return out, req.Send() @@ -3869,7 +5115,7 @@ func (c *CloudFront) ListTagsForResourceWithContext(ctx aws.Context, input *List return out, req.Send() } -const opTagResource = "TagResource2019_03_26" +const opTagResource = "TagResource2020_05_31" // TagResourceRequest generates a "aws/request.Request" representing the // client's request for the TagResource operation. The "output" return @@ -3894,12 +5140,12 @@ const opTagResource = "TagResource2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/TagResource +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/TagResource func (c *CloudFront) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { op := &request.Operation{ Name: opTagResource, HTTPMethod: "POST", - HTTPPath: "/2019-03-26/tagging?Operation=Tag", + HTTPPath: "/2020-05-31/tagging?Operation=Tag", } if input == nil { @@ -3928,7 +5174,7 @@ func (c *CloudFront) TagResourceRequest(input *TagResourceInput) (req *request.R // Access denied. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInvalidTagging "InvalidTagging" // The tagging specified is not valid. @@ -3936,7 +5182,7 @@ func (c *CloudFront) TagResourceRequest(input *TagResourceInput) (req *request.R // * ErrCodeNoSuchResource "NoSuchResource" // A resource that was specified is not valid. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/TagResource +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/TagResource func (c *CloudFront) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { req, out := c.TagResourceRequest(input) return out, req.Send() @@ -3958,7 +5204,7 @@ func (c *CloudFront) TagResourceWithContext(ctx aws.Context, input *TagResourceI return out, req.Send() } -const opUntagResource = "UntagResource2019_03_26" +const opUntagResource = "UntagResource2020_05_31" // UntagResourceRequest generates a "aws/request.Request" representing the // client's request for the UntagResource operation. The "output" return @@ -3983,12 +5229,12 @@ const opUntagResource = "UntagResource2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UntagResource +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UntagResource func (c *CloudFront) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { op := &request.Operation{ Name: opUntagResource, HTTPMethod: "POST", - HTTPPath: "/2019-03-26/tagging?Operation=Untag", + HTTPPath: "/2020-05-31/tagging?Operation=Untag", } if input == nil { @@ -4017,7 +5263,7 @@ func (c *CloudFront) UntagResourceRequest(input *UntagResourceInput) (req *reque // Access denied. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInvalidTagging "InvalidTagging" // The tagging specified is not valid. @@ -4025,7 +5271,7 @@ func (c *CloudFront) UntagResourceRequest(input *UntagResourceInput) (req *reque // * ErrCodeNoSuchResource "NoSuchResource" // A resource that was specified is not valid. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UntagResource +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UntagResource func (c *CloudFront) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { req, out := c.UntagResourceRequest(input) return out, req.Send() @@ -4047,119 +5293,248 @@ func (c *CloudFront) UntagResourceWithContext(ctx aws.Context, input *UntagResou return out, req.Send() } -const opUpdateCloudFrontOriginAccessIdentity = "UpdateCloudFrontOriginAccessIdentity2019_03_26" +const opUpdateCachePolicy = "UpdateCachePolicy2020_05_31" -// UpdateCloudFrontOriginAccessIdentityRequest generates a "aws/request.Request" representing the -// client's request for the UpdateCloudFrontOriginAccessIdentity operation. The "output" return +// UpdateCachePolicyRequest generates a "aws/request.Request" representing the +// client's request for the UpdateCachePolicy operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateCloudFrontOriginAccessIdentity for more information on using the UpdateCloudFrontOriginAccessIdentity +// See UpdateCachePolicy for more information on using the UpdateCachePolicy // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateCloudFrontOriginAccessIdentityRequest method. -// req, resp := client.UpdateCloudFrontOriginAccessIdentityRequest(params) +// // Example sending a request using the UpdateCachePolicyRequest method. +// req, resp := client.UpdateCachePolicyRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateCloudFrontOriginAccessIdentity -func (c *CloudFront) UpdateCloudFrontOriginAccessIdentityRequest(input *UpdateCloudFrontOriginAccessIdentityInput) (req *request.Request, output *UpdateCloudFrontOriginAccessIdentityOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateCachePolicy +func (c *CloudFront) UpdateCachePolicyRequest(input *UpdateCachePolicyInput) (req *request.Request, output *UpdateCachePolicyOutput) { op := &request.Operation{ - Name: opUpdateCloudFrontOriginAccessIdentity, + Name: opUpdateCachePolicy, HTTPMethod: "PUT", - HTTPPath: "/2019-03-26/origin-access-identity/cloudfront/{Id}/config", + HTTPPath: "/2020-05-31/cache-policy/{Id}", } if input == nil { - input = &UpdateCloudFrontOriginAccessIdentityInput{} + input = &UpdateCachePolicyInput{} } - output = &UpdateCloudFrontOriginAccessIdentityOutput{} + output = &UpdateCachePolicyOutput{} req = c.newRequest(op, input, output) return } -// UpdateCloudFrontOriginAccessIdentity API operation for Amazon CloudFront. +// UpdateCachePolicy API operation for Amazon CloudFront. // -// Update an origin access identity. +// Updates a cache policy configuration. +// +// When you update a cache policy configuration, all the fields are updated +// with the values provided in the request. You cannot update some fields independent +// of others. To update a cache policy configuration: +// +// Use GetCachePolicyConfig to get the current configuration. +// +// Locally modify the fields in the cache policy configuration that you want +// to update. +// +// Call UpdateCachePolicy by providing the entire cache policy configuration, +// including the fields that you modified and those that you didn’t. // // Returns awserr.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 CloudFront's -// API operation UpdateCloudFrontOriginAccessIdentity for usage and error information. +// API operation UpdateCachePolicy for usage and error information. // // Returned Error Codes: // * ErrCodeAccessDenied "AccessDenied" // Access denied. // // * ErrCodeIllegalUpdate "IllegalUpdate" -// Origin and CallerReference cannot be updated. +// The update contains modifications that are not allowed. // -// * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// * ErrCodeInconsistentQuantities "InconsistentQuantities" +// The value of Quantity and the size of Items don't match. // -// * ErrCodeMissingBody "MissingBody" -// This operation requires a body. Ensure that the body is present and the Content-Type -// header is set. +// * ErrCodeInvalidArgument "InvalidArgument" +// An argument is invalid. // -// * ErrCodeNoSuchCloudFrontOriginAccessIdentity "NoSuchCloudFrontOriginAccessIdentity" -// The specified origin access identity does not exist. +// * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" +// The If-Match version is missing or not valid. +// +// * ErrCodeNoSuchCachePolicy "NoSuchCachePolicy" +// The cache policy does not exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // -// * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// * ErrCodeCachePolicyAlreadyExists "CachePolicyAlreadyExists" +// A cache policy with this name already exists. You must provide a unique name. +// To modify an existing cache policy, use UpdateCachePolicy. // -// * ErrCodeInconsistentQuantities "InconsistentQuantities" -// The value of Quantity and the size of Items don't match. +// * ErrCodeTooManyHeadersInCachePolicy "TooManyHeadersInCachePolicy" +// The number of headers in the cache policy exceeds the maximum. For more information, +// see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateCloudFrontOriginAccessIdentity -func (c *CloudFront) UpdateCloudFrontOriginAccessIdentity(input *UpdateCloudFrontOriginAccessIdentityInput) (*UpdateCloudFrontOriginAccessIdentityOutput, error) { - req, out := c.UpdateCloudFrontOriginAccessIdentityRequest(input) +// * ErrCodeTooManyCookiesInCachePolicy "TooManyCookiesInCachePolicy" +// The number of cookies in the cache policy exceeds the maximum. For more information, +// see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeTooManyQueryStringsInCachePolicy "TooManyQueryStringsInCachePolicy" +// The number of query strings in the cache policy exceeds the maximum. For +// more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateCachePolicy +func (c *CloudFront) UpdateCachePolicy(input *UpdateCachePolicyInput) (*UpdateCachePolicyOutput, error) { + req, out := c.UpdateCachePolicyRequest(input) return out, req.Send() } -// UpdateCloudFrontOriginAccessIdentityWithContext is the same as UpdateCloudFrontOriginAccessIdentity with the addition of +// UpdateCachePolicyWithContext is the same as UpdateCachePolicy 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. +// See UpdateCachePolicy for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *CloudFront) UpdateCachePolicyWithContext(ctx aws.Context, input *UpdateCachePolicyInput, opts ...request.Option) (*UpdateCachePolicyOutput, error) { + req, out := c.UpdateCachePolicyRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateDistribution = "UpdateDistribution2019_03_26" +const opUpdateCloudFrontOriginAccessIdentity = "UpdateCloudFrontOriginAccessIdentity2020_05_31" -// UpdateDistributionRequest generates a "aws/request.Request" representing the -// client's request for the UpdateDistribution operation. The "output" return +// UpdateCloudFrontOriginAccessIdentityRequest generates a "aws/request.Request" representing the +// client's request for the UpdateCloudFrontOriginAccessIdentity operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateDistribution for more information on using the UpdateDistribution +// See UpdateCloudFrontOriginAccessIdentity for more information on using the UpdateCloudFrontOriginAccessIdentity +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateCloudFrontOriginAccessIdentityRequest method. +// req, resp := client.UpdateCloudFrontOriginAccessIdentityRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateCloudFrontOriginAccessIdentity +func (c *CloudFront) UpdateCloudFrontOriginAccessIdentityRequest(input *UpdateCloudFrontOriginAccessIdentityInput) (req *request.Request, output *UpdateCloudFrontOriginAccessIdentityOutput) { + op := &request.Operation{ + Name: opUpdateCloudFrontOriginAccessIdentity, + HTTPMethod: "PUT", + HTTPPath: "/2020-05-31/origin-access-identity/cloudfront/{Id}/config", + } + + if input == nil { + input = &UpdateCloudFrontOriginAccessIdentityInput{} + } + + output = &UpdateCloudFrontOriginAccessIdentityOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateCloudFrontOriginAccessIdentity API operation for Amazon CloudFront. +// +// Update an origin access identity. +// +// Returns awserr.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 CloudFront's +// API operation UpdateCloudFrontOriginAccessIdentity for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodeIllegalUpdate "IllegalUpdate" +// The update contains modifications that are not allowed. +// +// * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" +// The If-Match version is missing or not valid. +// +// * ErrCodeMissingBody "MissingBody" +// This operation requires a body. Ensure that the body is present and the Content-Type +// header is set. +// +// * ErrCodeNoSuchCloudFrontOriginAccessIdentity "NoSuchCloudFrontOriginAccessIdentity" +// The specified origin access identity does not exist. +// +// * ErrCodePreconditionFailed "PreconditionFailed" +// The precondition given in one or more of the request header fields evaluated +// to false. +// +// * ErrCodeInvalidArgument "InvalidArgument" +// An argument is invalid. +// +// * ErrCodeInconsistentQuantities "InconsistentQuantities" +// The value of Quantity and the size of Items don't match. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateCloudFrontOriginAccessIdentity +func (c *CloudFront) UpdateCloudFrontOriginAccessIdentity(input *UpdateCloudFrontOriginAccessIdentityInput) (*UpdateCloudFrontOriginAccessIdentityOutput, error) { + req, out := c.UpdateCloudFrontOriginAccessIdentityRequest(input) + return out, req.Send() +} + +// 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 = "UpdateDistribution2020_05_31" + +// UpdateDistributionRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDistribution operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDistribution for more information on using the UpdateDistribution // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration @@ -4174,12 +5549,12 @@ const opUpdateDistribution = "UpdateDistribution2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateDistribution func (c *CloudFront) UpdateDistributionRequest(input *UpdateDistributionInput) (req *request.Request, output *UpdateDistributionOutput) { op := &request.Operation{ Name: opUpdateDistribution, HTTPMethod: "PUT", - HTTPPath: "/2019-03-26/distribution/{Id}/config", + HTTPPath: "/2020-05-31/distribution/{Id}/config", } if input == nil { @@ -4273,10 +5648,10 @@ func (c *CloudFront) UpdateDistributionRequest(input *UpdateDistributionInput) ( // The CNAME specified is already defined for CloudFront. // // * ErrCodeIllegalUpdate "IllegalUpdate" -// Origin and CallerReference cannot be updated. +// The update contains modifications that are not allowed. // // * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// The If-Match version is missing or not valid. // // * ErrCodeMissingBody "MissingBody" // This operation requires a body. Ensure that the body is present and the Content-Type @@ -4286,7 +5661,7 @@ func (c *CloudFront) UpdateDistributionRequest(input *UpdateDistributionInput) ( // The specified distribution does not exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // // * ErrCodeTooManyDistributionCNAMEs "TooManyDistributionCNAMEs" @@ -4306,7 +5681,7 @@ func (c *CloudFront) UpdateDistributionRequest(input *UpdateDistributionInput) ( // A response code is not valid. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInvalidOriginAccessIdentity "InvalidOriginAccessIdentity" // The origin access identity is not valid or doesn't exist. @@ -4391,6 +5766,10 @@ func (c *CloudFront) UpdateDistributionRequest(input *UpdateDistributionInput) ( // Processing your request would cause the maximum number of distributions with // Lambda function associations per owner to be exceeded. // +// * ErrCodeTooManyDistributionsWithSingleFunctionARN "TooManyDistributionsWithSingleFunctionARN" +// The maximum number of distributions have been associated with the specified +// Lambda function. +// // * ErrCodeTooManyLambdaFunctionAssociations "TooManyLambdaFunctionAssociations" // Your request contains more Lambda function associations than are allowed // per distribution. @@ -4415,7 +5794,23 @@ func (c *CloudFront) UpdateDistributionRequest(input *UpdateDistributionInput) ( // The maximum number of distributions have been associated with the specified // configuration for field-level encryption. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateDistribution +// * ErrCodeNoSuchCachePolicy "NoSuchCachePolicy" +// The cache policy does not exist. +// +// * ErrCodeTooManyDistributionsAssociatedToCachePolicy "TooManyDistributionsAssociatedToCachePolicy" +// The maximum number of distributions have been associated with the specified +// cache policy. For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeNoSuchOriginRequestPolicy "NoSuchOriginRequestPolicy" +// The origin request policy does not exist. +// +// * ErrCodeTooManyDistributionsAssociatedToOriginRequestPolicy "TooManyDistributionsAssociatedToOriginRequestPolicy" +// The maximum number of distributions have been associated with the specified +// origin request policy. For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateDistribution func (c *CloudFront) UpdateDistribution(input *UpdateDistributionInput) (*UpdateDistributionOutput, error) { req, out := c.UpdateDistributionRequest(input) return out, req.Send() @@ -4437,7 +5832,7 @@ func (c *CloudFront) UpdateDistributionWithContext(ctx aws.Context, input *Updat return out, req.Send() } -const opUpdateFieldLevelEncryptionConfig = "UpdateFieldLevelEncryptionConfig2019_03_26" +const opUpdateFieldLevelEncryptionConfig = "UpdateFieldLevelEncryptionConfig2020_05_31" // UpdateFieldLevelEncryptionConfigRequest generates a "aws/request.Request" representing the // client's request for the UpdateFieldLevelEncryptionConfig operation. The "output" return @@ -4462,12 +5857,12 @@ const opUpdateFieldLevelEncryptionConfig = "UpdateFieldLevelEncryptionConfig2019 // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateFieldLevelEncryptionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateFieldLevelEncryptionConfig func (c *CloudFront) UpdateFieldLevelEncryptionConfigRequest(input *UpdateFieldLevelEncryptionConfigInput) (req *request.Request, output *UpdateFieldLevelEncryptionConfigOutput) { op := &request.Operation{ Name: opUpdateFieldLevelEncryptionConfig, HTTPMethod: "PUT", - HTTPPath: "/2019-03-26/field-level-encryption/{Id}/config", + HTTPPath: "/2020-05-31/field-level-encryption/{Id}/config", } if input == nil { @@ -4495,16 +5890,16 @@ func (c *CloudFront) UpdateFieldLevelEncryptionConfigRequest(input *UpdateFieldL // Access denied. // // * ErrCodeIllegalUpdate "IllegalUpdate" -// Origin and CallerReference cannot be updated. +// The update contains modifications that are not allowed. // // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items don't match. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// The If-Match version is missing or not valid. // // * ErrCodeNoSuchFieldLevelEncryptionProfile "NoSuchFieldLevelEncryptionProfile" // The specified profile for field-level encryption doesn't exist. @@ -4513,7 +5908,7 @@ func (c *CloudFront) UpdateFieldLevelEncryptionConfigRequest(input *UpdateFieldL // The specified configuration for field-level encryption doesn't exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // // * ErrCodeTooManyFieldLevelEncryptionQueryArgProfiles "TooManyFieldLevelEncryptionQueryArgProfiles" @@ -4527,7 +5922,7 @@ func (c *CloudFront) UpdateFieldLevelEncryptionConfigRequest(input *UpdateFieldL // * ErrCodeQueryArgProfileEmpty "QueryArgProfileEmpty" // No profile specified for the field-level encryption query argument. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateFieldLevelEncryptionConfig +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateFieldLevelEncryptionConfig func (c *CloudFront) UpdateFieldLevelEncryptionConfig(input *UpdateFieldLevelEncryptionConfigInput) (*UpdateFieldLevelEncryptionConfigOutput, error) { req, out := c.UpdateFieldLevelEncryptionConfigRequest(input) return out, req.Send() @@ -4549,7 +5944,7 @@ func (c *CloudFront) UpdateFieldLevelEncryptionConfigWithContext(ctx aws.Context return out, req.Send() } -const opUpdateFieldLevelEncryptionProfile = "UpdateFieldLevelEncryptionProfile2019_03_26" +const opUpdateFieldLevelEncryptionProfile = "UpdateFieldLevelEncryptionProfile2020_05_31" // UpdateFieldLevelEncryptionProfileRequest generates a "aws/request.Request" representing the // client's request for the UpdateFieldLevelEncryptionProfile operation. The "output" return @@ -4574,12 +5969,12 @@ const opUpdateFieldLevelEncryptionProfile = "UpdateFieldLevelEncryptionProfile20 // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateFieldLevelEncryptionProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateFieldLevelEncryptionProfile func (c *CloudFront) UpdateFieldLevelEncryptionProfileRequest(input *UpdateFieldLevelEncryptionProfileInput) (req *request.Request, output *UpdateFieldLevelEncryptionProfileOutput) { op := &request.Operation{ Name: opUpdateFieldLevelEncryptionProfile, HTTPMethod: "PUT", - HTTPPath: "/2019-03-26/field-level-encryption-profile/{Id}/config", + HTTPPath: "/2020-05-31/field-level-encryption-profile/{Id}/config", } if input == nil { @@ -4610,16 +6005,16 @@ func (c *CloudFront) UpdateFieldLevelEncryptionProfileRequest(input *UpdateField // The specified profile for field-level encryption already exists. // // * ErrCodeIllegalUpdate "IllegalUpdate" -// Origin and CallerReference cannot be updated. +// The update contains modifications that are not allowed. // // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items don't match. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// The If-Match version is missing or not valid. // // * ErrCodeNoSuchPublicKey "NoSuchPublicKey" // The specified public key doesn't exist. @@ -4628,7 +6023,7 @@ func (c *CloudFront) UpdateFieldLevelEncryptionProfileRequest(input *UpdateField // The specified profile for field-level encryption doesn't exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // // * ErrCodeFieldLevelEncryptionProfileSizeExceeded "FieldLevelEncryptionProfileSizeExceeded" @@ -4642,7 +6037,7 @@ func (c *CloudFront) UpdateFieldLevelEncryptionProfileRequest(input *UpdateField // The maximum number of field patterns for field-level encryption have been // created. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateFieldLevelEncryptionProfile +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateFieldLevelEncryptionProfile func (c *CloudFront) UpdateFieldLevelEncryptionProfile(input *UpdateFieldLevelEncryptionProfileInput) (*UpdateFieldLevelEncryptionProfileOutput, error) { req, out := c.UpdateFieldLevelEncryptionProfileRequest(input) return out, req.Send() @@ -4664,7 +6059,137 @@ func (c *CloudFront) UpdateFieldLevelEncryptionProfileWithContext(ctx aws.Contex return out, req.Send() } -const opUpdatePublicKey = "UpdatePublicKey2019_03_26" +const opUpdateOriginRequestPolicy = "UpdateOriginRequestPolicy2020_05_31" + +// UpdateOriginRequestPolicyRequest generates a "aws/request.Request" representing the +// client's request for the UpdateOriginRequestPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateOriginRequestPolicy for more information on using the UpdateOriginRequestPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateOriginRequestPolicyRequest method. +// req, resp := client.UpdateOriginRequestPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateOriginRequestPolicy +func (c *CloudFront) UpdateOriginRequestPolicyRequest(input *UpdateOriginRequestPolicyInput) (req *request.Request, output *UpdateOriginRequestPolicyOutput) { + op := &request.Operation{ + Name: opUpdateOriginRequestPolicy, + HTTPMethod: "PUT", + HTTPPath: "/2020-05-31/origin-request-policy/{Id}", + } + + if input == nil { + input = &UpdateOriginRequestPolicyInput{} + } + + output = &UpdateOriginRequestPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateOriginRequestPolicy API operation for Amazon CloudFront. +// +// Updates an origin request policy configuration. +// +// When you update an origin request policy configuration, all the fields are +// updated with the values provided in the request. You cannot update some fields +// independent of others. To update an origin request policy configuration: +// +// Use GetOriginRequestPolicyConfig to get the current configuration. +// +// Locally modify the fields in the origin request policy configuration that +// you want to update. +// +// Call UpdateOriginRequestPolicy by providing the entire origin request policy +// configuration, including the fields that you modified and those that you +// didn’t. +// +// Returns awserr.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 CloudFront's +// API operation UpdateOriginRequestPolicy for usage and error information. +// +// Returned Error Codes: +// * ErrCodeAccessDenied "AccessDenied" +// Access denied. +// +// * ErrCodeIllegalUpdate "IllegalUpdate" +// The update contains modifications that are not allowed. +// +// * ErrCodeInconsistentQuantities "InconsistentQuantities" +// The value of Quantity and the size of Items don't match. +// +// * ErrCodeInvalidArgument "InvalidArgument" +// An argument is invalid. +// +// * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" +// The If-Match version is missing or not valid. +// +// * ErrCodeNoSuchOriginRequestPolicy "NoSuchOriginRequestPolicy" +// The origin request policy does not exist. +// +// * ErrCodePreconditionFailed "PreconditionFailed" +// The precondition given in one or more of the request header fields evaluated +// to false. +// +// * ErrCodeOriginRequestPolicyAlreadyExists "OriginRequestPolicyAlreadyExists" +// An origin request policy with this name already exists. You must provide +// a unique name. To modify an existing origin request policy, use UpdateOriginRequestPolicy. +// +// * ErrCodeTooManyHeadersInOriginRequestPolicy "TooManyHeadersInOriginRequestPolicy" +// The number of headers in the origin request policy exceeds the maximum. For +// more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeTooManyCookiesInOriginRequestPolicy "TooManyCookiesInOriginRequestPolicy" +// The number of cookies in the origin request policy exceeds the maximum. For +// more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// * ErrCodeTooManyQueryStringsInOriginRequestPolicy "TooManyQueryStringsInOriginRequestPolicy" +// The number of query strings in the origin request policy exceeds the maximum. +// For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// (formerly known as limits) in the Amazon CloudFront Developer Guide. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateOriginRequestPolicy +func (c *CloudFront) UpdateOriginRequestPolicy(input *UpdateOriginRequestPolicyInput) (*UpdateOriginRequestPolicyOutput, error) { + req, out := c.UpdateOriginRequestPolicyRequest(input) + return out, req.Send() +} + +// UpdateOriginRequestPolicyWithContext is the same as UpdateOriginRequestPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateOriginRequestPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) UpdateOriginRequestPolicyWithContext(ctx aws.Context, input *UpdateOriginRequestPolicyInput, opts ...request.Option) (*UpdateOriginRequestPolicyOutput, error) { + req, out := c.UpdateOriginRequestPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdatePublicKey = "UpdatePublicKey2020_05_31" // UpdatePublicKeyRequest generates a "aws/request.Request" representing the // client's request for the UpdatePublicKey operation. The "output" return @@ -4689,12 +6214,12 @@ const opUpdatePublicKey = "UpdatePublicKey2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdatePublicKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdatePublicKey func (c *CloudFront) UpdatePublicKeyRequest(input *UpdatePublicKeyInput) (req *request.Request, output *UpdatePublicKeyOutput) { op := &request.Operation{ Name: opUpdatePublicKey, HTTPMethod: "PUT", - HTTPPath: "/2019-03-26/public-key/{Id}/config", + HTTPPath: "/2020-05-31/public-key/{Id}/config", } if input == nil { @@ -4726,22 +6251,22 @@ func (c *CloudFront) UpdatePublicKeyRequest(input *UpdatePublicKeyInput) (req *r // You can't change the value of a public key. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// The If-Match version is missing or not valid. // // * ErrCodeIllegalUpdate "IllegalUpdate" -// Origin and CallerReference cannot be updated. +// The update contains modifications that are not allowed. // // * ErrCodeNoSuchPublicKey "NoSuchPublicKey" // The specified public key doesn't exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdatePublicKey +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdatePublicKey func (c *CloudFront) UpdatePublicKey(input *UpdatePublicKeyInput) (*UpdatePublicKeyOutput, error) { req, out := c.UpdatePublicKeyRequest(input) return out, req.Send() @@ -4763,7 +6288,7 @@ func (c *CloudFront) UpdatePublicKeyWithContext(ctx aws.Context, input *UpdatePu return out, req.Send() } -const opUpdateStreamingDistribution = "UpdateStreamingDistribution2019_03_26" +const opUpdateStreamingDistribution = "UpdateStreamingDistribution2020_05_31" // UpdateStreamingDistributionRequest generates a "aws/request.Request" representing the // client's request for the UpdateStreamingDistribution operation. The "output" return @@ -4788,12 +6313,12 @@ const opUpdateStreamingDistribution = "UpdateStreamingDistribution2019_03_26" // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateStreamingDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateStreamingDistribution func (c *CloudFront) UpdateStreamingDistributionRequest(input *UpdateStreamingDistributionInput) (req *request.Request, output *UpdateStreamingDistributionOutput) { op := &request.Operation{ Name: opUpdateStreamingDistribution, HTTPMethod: "PUT", - HTTPPath: "/2019-03-26/streaming-distribution/{Id}/config", + HTTPPath: "/2020-05-31/streaming-distribution/{Id}/config", } if input == nil { @@ -4824,10 +6349,10 @@ func (c *CloudFront) UpdateStreamingDistributionRequest(input *UpdateStreamingDi // The CNAME specified is already defined for CloudFront. // // * ErrCodeIllegalUpdate "IllegalUpdate" -// Origin and CallerReference cannot be updated. +// The update contains modifications that are not allowed. // // * ErrCodeInvalidIfMatchVersion "InvalidIfMatchVersion" -// The If-Match version is missing or not valid for the distribution. +// The If-Match version is missing or not valid. // // * ErrCodeMissingBody "MissingBody" // This operation requires a body. Ensure that the body is present and the Content-Type @@ -4837,14 +6362,14 @@ func (c *CloudFront) UpdateStreamingDistributionRequest(input *UpdateStreamingDi // The specified streaming distribution does not exist. // // * ErrCodePreconditionFailed "PreconditionFailed" -// The precondition given in one or more of the request-header fields evaluated +// The precondition given in one or more of the request header fields evaluated // to false. // // * ErrCodeTooManyStreamingDistributionCNAMEs "TooManyStreamingDistributionCNAMEs" // Your request contains more CNAMEs than are allowed per distribution. // // * ErrCodeInvalidArgument "InvalidArgument" -// The argument is invalid. +// An argument is invalid. // // * ErrCodeInvalidOriginAccessIdentity "InvalidOriginAccessIdentity" // The origin access identity is not valid or doesn't exist. @@ -4858,7 +6383,7 @@ func (c *CloudFront) UpdateStreamingDistributionRequest(input *UpdateStreamingDi // * ErrCodeInconsistentQuantities "InconsistentQuantities" // The value of Quantity and the size of Items don't match. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateStreamingDistribution +// See also, https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/UpdateStreamingDistribution func (c *CloudFront) UpdateStreamingDistribution(input *UpdateStreamingDistributionInput) (*UpdateStreamingDistributionOutput, error) { req, out := c.UpdateStreamingDistributionRequest(input) return out, req.Send() @@ -5147,19 +6672,19 @@ func (s *AllowedMethods) SetQuantity(v int64) *AllowedMethods { // A complex type that describes how CloudFront processes requests. // // You must create at least as many cache behaviors (including the default cache -// behavior) as you have origins if you want CloudFront to distribute objects -// from all of the origins. Each cache behavior specifies the one origin from -// which you want CloudFront to get objects. If you have two origins and only -// the default cache behavior, the default cache behavior will cause CloudFront +// behavior) as you have origins if you want CloudFront to serve objects from +// all of the origins. Each cache behavior specifies the one origin from which +// you want CloudFront to get objects. If you have two origins and only the +// default cache behavior, the default cache behavior will cause CloudFront // to get objects from one of the origins, but the other origin is never used. // -// For the current limit on the number of cache behaviors that you can add to -// a distribution, see Amazon CloudFront Limits (https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_cloudfront) -// in the AWS General Reference. +// For the current quota (formerly known as limit) on the number of cache behaviors +// that you can add to a distribution, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) +// in the Amazon CloudFront Developer Guide. // -// If you don't want to specify any cache behaviors, include only an empty CacheBehaviors -// element. Don't include an empty CacheBehavior element, or CloudFront returns -// a MalformedXML error. +// If you don’t want to specify any cache behaviors, include only an empty +// CacheBehaviors element. Don’t include an empty CacheBehavior element because +// this is invalid. // // To delete all cache behaviors in an existing distribution, update the distribution // configuration and include only an empty CacheBehaviors element. @@ -5168,7 +6693,7 @@ func (s *AllowedMethods) SetQuantity(v int64) *AllowedMethods { // configuration and specify all of the cache behaviors that you want to include // in the updated distribution. // -// For more information about cache behaviors, see Cache Behaviors (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesCacheBehavior) +// For more information about cache behaviors, see Cache Behavior Settings (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesCacheBehavior) // in the Amazon CloudFront Developer Guide. type CacheBehavior struct { _ struct{} `type:"structure"` @@ -5190,12 +6715,24 @@ type CacheBehavior struct { // to delete objects from your origin. AllowedMethods *AllowedMethods `type:"structure"` + // The unique identifier of the cache policy that is attached to this cache + // behavior. For more information, see Creating cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // or Using the managed cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html) + // in the Amazon CloudFront Developer Guide. + CachePolicyId *string `type:"string"` + // Whether you want CloudFront to automatically compress certain files for this // cache behavior. If so, specify true; if not, specify false. For more information, // see Serving Compressed Files (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html) // in the Amazon CloudFront Developer Guide. Compress *bool `type:"boolean"` + // This field is deprecated. We recommend that you use the DefaultTTL field + // in a cache policy instead of this field. For more information, see Creating + // cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // or Using the managed cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html) + // in the Amazon CloudFront Developer Guide. + // // The default amount of time that you want objects to stay in CloudFront caches // before CloudFront forwards another request to your origin to determine whether // the object has been updated. The value that you specify applies only when @@ -5203,23 +6740,46 @@ type CacheBehavior struct { // s-maxage, and Expires to objects. For more information, see Managing How // Long Content Stays in an Edge Cache (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) // in the Amazon CloudFront Developer Guide. - DefaultTTL *int64 `type:"long"` + // + // Deprecated: DefaultTTL has been deprecated + DefaultTTL *int64 `deprecated:"true" type:"long"` // The value of ID for the field-level encryption configuration that you want - // CloudFront to use for encrypting specific fields of data for a cache behavior - // or for the default cache behavior in your distribution. + // CloudFront to use for encrypting specific fields of data for this cache behavior. FieldLevelEncryptionId *string `type:"string"` + // This field is deprecated. We recommend that you use a cache policy or an + // origin request policy instead of this field. For more information, see Working + // with policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/working-with-policies.html) + // in the Amazon CloudFront Developer Guide. + // + // If you want to include values in the cache key, use a cache policy. For more + // information, see Creating cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // or Using the managed cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html) + // in the Amazon CloudFront Developer Guide. + // + // If you want to send values to the origin but not include them in the cache + // key, use an origin request policy. For more information, see Creating origin + // request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) + // or Using the managed origin request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-origin-request-policies.html) + // in the Amazon CloudFront Developer Guide. + // // A complex type that specifies how CloudFront handles query strings, cookies, // and HTTP headers. // - // ForwardedValues is a required field - ForwardedValues *ForwardedValues `type:"structure" required:"true"` + // Deprecated: ForwardedValues has been deprecated + ForwardedValues *ForwardedValues `deprecated:"true" type:"structure"` // A complex type that contains zero or more Lambda function associations for // a cache behavior. LambdaFunctionAssociations *LambdaFunctionAssociations `type:"structure"` + // This field is deprecated. We recommend that you use the MaxTTL field in a + // cache policy instead of this field. For more information, see Creating cache + // policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // or Using the managed cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html) + // in the Amazon CloudFront Developer Guide. + // // The maximum amount of time that you want objects to stay in CloudFront caches // before CloudFront forwards another request to your origin to determine whether // the object has been updated. The value that you specify applies only when @@ -5227,8 +6787,16 @@ type CacheBehavior struct { // s-maxage, and Expires to objects. For more information, see Managing How // Long Content Stays in an Edge Cache (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) // in the Amazon CloudFront Developer Guide. - MaxTTL *int64 `type:"long"` + // + // Deprecated: MaxTTL has been deprecated + MaxTTL *int64 `deprecated:"true" type:"long"` + // This field is deprecated. We recommend that you use the MinTTL field in a + // cache policy instead of this field. For more information, see Creating cache + // policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // or Using the managed cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html) + // in the Amazon CloudFront Developer Guide. + // // The minimum amount of time that you want objects to stay in CloudFront caches // before CloudFront forwards another request to your origin to determine whether // the object has been updated. For more information, see Managing How Long @@ -5239,8 +6807,15 @@ type CacheBehavior struct { // headers to your origin (under Headers, if you specify 1 for Quantity and // * for Name). // - // MinTTL is a required field - MinTTL *int64 `type:"long" required:"true"` + // Deprecated: MinTTL has been deprecated + MinTTL *int64 `deprecated:"true" type:"long"` + + // The unique identifier of the origin request policy that is attached to this + // cache behavior. For more information, see Creating origin request policies + // (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) + // or Using the managed origin request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-origin-request-policies.html) + // in the Amazon CloudFront Developer Guide. + OriginRequestPolicyId *string `type:"string"` // The pattern (for example, images/*.jpg) that specifies which requests to // apply the behavior to. When CloudFront receives a viewer request, the requested @@ -5269,8 +6844,7 @@ type CacheBehavior struct { SmoothStreaming *bool `type:"boolean"` // The value of ID for the origin that you want CloudFront to route requests - // to when a request matches the path pattern either for a cache behavior or - // for the default cache behavior in your distribution. + // to when they match this cache behavior. // // TargetOriginId is a required field TargetOriginId *string `type:"string" required:"true"` @@ -5281,14 +6855,15 @@ type CacheBehavior struct { // If you want to require signed URLs in requests for objects in the target // origin that match the PathPattern for this cache behavior, specify true for // Enabled, and specify the applicable values for Quantity and Items. For more - // information, see Serving Private Content through CloudFront (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html) + // information, see Serving Private Content with Signed URLs and Signed Cookies + // (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html) // in the Amazon CloudFront Developer Guide. // - // If you don't want to require signed URLs in requests for objects that match + // If you don’t want to require signed URLs in requests for objects that match // PathPattern, specify false for Enabled and 0 for Quantity. Omit Items. // // To add, change, or remove one or more trusted signers, change Enabled to - // true (if it's currently false), change Quantity as applicable, and specify + // true (if it’s currently false), change Quantity as applicable, and specify // all of the trusted signers that you want to include in the updated distribution. // // TrustedSigners is a required field @@ -5307,18 +6882,17 @@ type CacheBehavior struct { // * https-only: If a viewer sends an HTTP request, CloudFront returns an // HTTP status code of 403 (Forbidden). // - // For more information about requiring the HTTPS protocol, see Using an HTTPS - // Connection to Access Your Objects (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html) + // For more information about requiring the HTTPS protocol, see Requiring HTTPS + // Between Viewers and CloudFront (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-https-viewers-to-cloudfront.html) // in the Amazon CloudFront Developer Guide. // // The only way to guarantee that viewers retrieve an object that was fetched // from the origin using HTTPS is never to use any other protocol to fetch the // object. If you have recently changed from HTTP to HTTPS, we recommend that - // you clear your objects' cache because cached objects are protocol agnostic. + // you clear your objects’ cache because cached objects are protocol agnostic. // That means that an edge location will return an object from the cache regardless // of whether the current request protocol matches the protocol used previously. - // For more information, see Managing How Long Content Stays in an Edge Cache - // (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) + // For more information, see Managing Cache Expiration (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) // in the Amazon CloudFront Developer Guide. // // ViewerProtocolPolicy is a required field @@ -5338,12 +6912,6 @@ func (s CacheBehavior) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *CacheBehavior) Validate() error { invalidParams := request.ErrInvalidParams{Context: "CacheBehavior"} - if s.ForwardedValues == nil { - invalidParams.Add(request.NewErrParamRequired("ForwardedValues")) - } - if s.MinTTL == nil { - invalidParams.Add(request.NewErrParamRequired("MinTTL")) - } if s.PathPattern == nil { invalidParams.Add(request.NewErrParamRequired("PathPattern")) } @@ -5389,6 +6957,12 @@ func (s *CacheBehavior) SetAllowedMethods(v *AllowedMethods) *CacheBehavior { return s } +// SetCachePolicyId sets the CachePolicyId field's value. +func (s *CacheBehavior) SetCachePolicyId(v string) *CacheBehavior { + s.CachePolicyId = &v + return s +} + // SetCompress sets the Compress field's value. func (s *CacheBehavior) SetCompress(v bool) *CacheBehavior { s.Compress = &v @@ -5431,6 +7005,12 @@ func (s *CacheBehavior) SetMinTTL(v int64) *CacheBehavior { return s } +// SetOriginRequestPolicyId sets the OriginRequestPolicyId field's value. +func (s *CacheBehavior) SetOriginRequestPolicyId(v string) *CacheBehavior { + s.OriginRequestPolicyId = &v + return s +} + // SetPathPattern sets the PathPattern field's value. func (s *CacheBehavior) SetPathPattern(v string) *CacheBehavior { s.PathPattern = &v @@ -5520,107 +7100,162 @@ func (s *CacheBehaviors) SetQuantity(v int64) *CacheBehaviors { return s } -// A complex type that controls whether CloudFront caches the response to requests -// using the specified HTTP methods. There are two choices: +// A cache policy. // -// * CloudFront caches responses to GET and HEAD requests. +// When it’s attached to a cache behavior, the cache policy determines the +// following: // -// * CloudFront caches responses to GET, HEAD, and OPTIONS requests. +// * The values that CloudFront includes in the cache key. These values can +// include HTTP headers, cookies, and URL query strings. CloudFront uses +// the cache key to find an object in its cache that it can return to the +// viewer. // -// 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. -type CachedMethods struct { +// * The default, minimum, and maximum time to live (TTL) values that you +// want objects to stay in the CloudFront cache. +// +// The headers, cookies, and query strings that are included in the cache key +// are automatically included in requests that CloudFront sends to the origin. +// CloudFront sends a request when it can’t find a valid object in its cache +// that matches the request’s cache key. If you want to send values to the +// origin but not include them in the cache key, use OriginRequestPolicy. +type CachePolicy struct { _ struct{} `type:"structure"` - // A complex type that contains the HTTP methods that you want CloudFront to - // cache responses to. + // The cache policy configuration. // - // Items is a required field - Items []*string `locationNameList:"Method" type:"list" required:"true"` + // CachePolicyConfig is a required field + CachePolicyConfig *CachePolicyConfig `type:"structure" required:"true"` - // The number of HTTP methods for which you want CloudFront to cache responses. - // Valid values are 2 (for caching responses to GET and HEAD requests) and 3 - // (for caching responses to GET, HEAD, and OPTIONS requests). + // The unique identifier for the cache policy. // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // Id is a required field + Id *string `type:"string" required:"true"` + + // The date and time when the cache policy was last modified. + // + // LastModifiedTime is a required field + LastModifiedTime *time.Time `type:"timestamp" required:"true"` } // String returns the string representation -func (s CachedMethods) String() string { +func (s CachePolicy) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CachedMethods) GoString() string { +func (s CachePolicy) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *CachedMethods) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CachedMethods"} - if s.Items == nil { - invalidParams.Add(request.NewErrParamRequired("Items")) - } - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCachePolicyConfig sets the CachePolicyConfig field's value. +func (s *CachePolicy) SetCachePolicyConfig(v *CachePolicyConfig) *CachePolicy { + s.CachePolicyConfig = v + return s } -// SetItems sets the Items field's value. -func (s *CachedMethods) SetItems(v []*string) *CachedMethods { - s.Items = v +// SetId sets the Id field's value. +func (s *CachePolicy) SetId(v string) *CachePolicy { + s.Id = &v return s } -// SetQuantity sets the Quantity field's value. -func (s *CachedMethods) SetQuantity(v int64) *CachedMethods { - s.Quantity = &v +// SetLastModifiedTime sets the LastModifiedTime field's value. +func (s *CachePolicy) SetLastModifiedTime(v time.Time) *CachePolicy { + s.LastModifiedTime = &v return s } -// A field-level encryption content type profile. -type ContentTypeProfile struct { +// A cache policy configuration. +// +// This configuration determines the following: +// +// * The values that CloudFront includes in the cache key. These values can +// include HTTP headers, cookies, and URL query strings. CloudFront uses +// the cache key to find an object in its cache that it can return to the +// viewer. +// +// * The default, minimum, and maximum time to live (TTL) values that you +// want objects to stay in the CloudFront cache. +// +// The headers, cookies, and query strings that are included in the cache key +// are automatically included in requests that CloudFront sends to the origin. +// CloudFront sends a request when it can’t find a valid object in its cache +// that matches the request’s cache key. If you want to send values to the +// origin but not include them in the cache key, use OriginRequestPolicy. +type CachePolicyConfig struct { _ struct{} `type:"structure"` - // The content type for a field-level encryption content type-profile mapping. + // A comment to describe the cache policy. + Comment *string `type:"string"` + + // The default amount of time, in seconds, that you want objects to stay in + // the CloudFront cache before CloudFront sends another request to the origin + // to see if the object has been updated. CloudFront uses this value as the + // object’s time to live (TTL) only when the origin does not send Cache-Control + // or Expires headers with the object. For more information, see Managing How + // Long Content Stays in an Edge Cache (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) + // in the Amazon CloudFront Developer Guide. // - // ContentType is a required field - ContentType *string `type:"string" required:"true"` + // The default value for this field is 86400 seconds (one day). If the value + // of MinTTL is more than 86400 seconds, then the default value for this field + // is the same as the value of MinTTL. + DefaultTTL *int64 `type:"long"` - // The format for a field-level encryption content type-profile mapping. + // The maximum amount of time, in seconds, that objects stay in the CloudFront + // cache before CloudFront sends another request to the origin to see if the + // object has been updated. CloudFront uses this value only when the origin + // sends Cache-Control or Expires headers with the object. For more information, + // see Managing How Long Content Stays in an Edge Cache (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) + // in the Amazon CloudFront Developer Guide. // - // Format is a required field - Format *string `type:"string" required:"true" enum:"Format"` + // The default value for this field is 31536000 seconds (one year). If the value + // of MinTTL or DefaultTTL is more than 31536000 seconds, then the default value + // for this field is the same as the value of DefaultTTL. + MaxTTL *int64 `type:"long"` - // The profile ID for a field-level encryption content type-profile mapping. - ProfileId *string `type:"string"` + // The minimum amount of time, in seconds, that you want objects to stay in + // the CloudFront cache before CloudFront sends another request to the origin + // to see if the object has been updated. For more information, see Managing + // How Long Content Stays in an Edge Cache (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) + // in the Amazon CloudFront Developer Guide. + // + // MinTTL is a required field + MinTTL *int64 `type:"long" required:"true"` + + // A unique name to identify the cache policy. + // + // Name is a required field + Name *string `type:"string" required:"true"` + + // The HTTP headers, cookies, and URL query strings to include in the cache + // key. The values included in the cache key are automatically included in requests + // that CloudFront sends to the origin. + ParametersInCacheKeyAndForwardedToOrigin *ParametersInCacheKeyAndForwardedToOrigin `type:"structure"` } // String returns the string representation -func (s ContentTypeProfile) String() string { +func (s CachePolicyConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ContentTypeProfile) GoString() string { +func (s CachePolicyConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ContentTypeProfile) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ContentTypeProfile"} - if s.ContentType == nil { - invalidParams.Add(request.NewErrParamRequired("ContentType")) +func (s *CachePolicyConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CachePolicyConfig"} + if s.MinTTL == nil { + invalidParams.Add(request.NewErrParamRequired("MinTTL")) } - if s.Format == nil { - invalidParams.Add(request.NewErrParamRequired("Format")) + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.ParametersInCacheKeyAndForwardedToOrigin != nil { + if err := s.ParametersInCacheKeyAndForwardedToOrigin.Validate(); err != nil { + invalidParams.AddNested("ParametersInCacheKeyAndForwardedToOrigin", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -5629,60 +7264,95 @@ func (s *ContentTypeProfile) Validate() error { return nil } -// SetContentType sets the ContentType field's value. -func (s *ContentTypeProfile) SetContentType(v string) *ContentTypeProfile { - s.ContentType = &v +// SetComment sets the Comment field's value. +func (s *CachePolicyConfig) SetComment(v string) *CachePolicyConfig { + s.Comment = &v return s } -// SetFormat sets the Format field's value. -func (s *ContentTypeProfile) SetFormat(v string) *ContentTypeProfile { - s.Format = &v +// SetDefaultTTL sets the DefaultTTL field's value. +func (s *CachePolicyConfig) SetDefaultTTL(v int64) *CachePolicyConfig { + s.DefaultTTL = &v return s } -// SetProfileId sets the ProfileId field's value. -func (s *ContentTypeProfile) SetProfileId(v string) *ContentTypeProfile { - s.ProfileId = &v +// SetMaxTTL sets the MaxTTL field's value. +func (s *CachePolicyConfig) SetMaxTTL(v int64) *CachePolicyConfig { + s.MaxTTL = &v return s } -// The configuration for a field-level encryption content type-profile mapping. -type ContentTypeProfileConfig struct { - _ struct{} `type:"structure"` +// SetMinTTL sets the MinTTL field's value. +func (s *CachePolicyConfig) SetMinTTL(v int64) *CachePolicyConfig { + s.MinTTL = &v + return s +} - // The configuration for a field-level encryption content type-profile. - ContentTypeProfiles *ContentTypeProfiles `type:"structure"` +// SetName sets the Name field's value. +func (s *CachePolicyConfig) SetName(v string) *CachePolicyConfig { + s.Name = &v + return s +} - // The setting in a field-level encryption content type-profile mapping that - // specifies what to do when an unknown content type is provided for the profile. - // If true, content is forwarded without being encrypted when the content type - // is unknown. If false (the default), an error is returned when the content - // type is unknown. +// SetParametersInCacheKeyAndForwardedToOrigin sets the ParametersInCacheKeyAndForwardedToOrigin field's value. +func (s *CachePolicyConfig) SetParametersInCacheKeyAndForwardedToOrigin(v *ParametersInCacheKeyAndForwardedToOrigin) *CachePolicyConfig { + s.ParametersInCacheKeyAndForwardedToOrigin = v + return s +} + +// An object that determines whether any cookies in viewer requests (and if +// so, which cookies) are included in the cache key and automatically included +// in requests that CloudFront sends to the origin. +type CachePolicyCookiesConfig struct { + _ struct{} `type:"structure"` + + // Determines whether any cookies in viewer requests are included in the cache + // key and automatically included in requests that CloudFront sends to the origin. + // Valid values are: // - // ForwardWhenContentTypeIsUnknown is a required field - ForwardWhenContentTypeIsUnknown *bool `type:"boolean" required:"true"` + // * none – Cookies in viewer requests are not included in the cache key + // and are not automatically included in requests that CloudFront sends to + // the origin. Even when this field is set to none, any cookies that are + // listed in an OriginRequestPolicy are included in origin requests. + // + // * whitelist – The cookies in viewer requests that are listed in the + // CookieNames type are included in the cache key and automatically included + // in requests that CloudFront sends to the origin. + // + // * allExcept – All cookies in viewer requests that are not listed in + // the CookieNames type are included in the cache key and automatically included + // in requests that CloudFront sends to the origin. + // + // * all – All cookies in viewer requests are included in the cache key + // and are automatically included in requests that CloudFront sends to the + // origin. + // + // CookieBehavior is a required field + CookieBehavior *string `type:"string" required:"true" enum:"CachePolicyCookieBehavior"` + + // Contains a list of cookie names. + Cookies *CookieNames `type:"structure"` } // String returns the string representation -func (s ContentTypeProfileConfig) String() string { +func (s CachePolicyCookiesConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ContentTypeProfileConfig) GoString() string { +func (s CachePolicyCookiesConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ContentTypeProfileConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ContentTypeProfileConfig"} - if s.ForwardWhenContentTypeIsUnknown == nil { - invalidParams.Add(request.NewErrParamRequired("ForwardWhenContentTypeIsUnknown")) +func (s *CachePolicyCookiesConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CachePolicyCookiesConfig"} + if s.CookieBehavior == nil { + invalidParams.Add(request.NewErrParamRequired("CookieBehavior")) } - if s.ContentTypeProfiles != nil { - if err := s.ContentTypeProfiles.Validate(); err != nil { - invalidParams.AddNested("ContentTypeProfiles", err.(request.ErrInvalidParams)) + if s.Cookies != nil { + if err := s.Cookies.Validate(); err != nil { + invalidParams.AddNested("Cookies", err.(request.ErrInvalidParams)) } } @@ -5692,55 +7362,62 @@ func (s *ContentTypeProfileConfig) Validate() error { return nil } -// SetContentTypeProfiles sets the ContentTypeProfiles field's value. -func (s *ContentTypeProfileConfig) SetContentTypeProfiles(v *ContentTypeProfiles) *ContentTypeProfileConfig { - s.ContentTypeProfiles = v +// SetCookieBehavior sets the CookieBehavior field's value. +func (s *CachePolicyCookiesConfig) SetCookieBehavior(v string) *CachePolicyCookiesConfig { + s.CookieBehavior = &v return s } -// SetForwardWhenContentTypeIsUnknown sets the ForwardWhenContentTypeIsUnknown field's value. -func (s *ContentTypeProfileConfig) SetForwardWhenContentTypeIsUnknown(v bool) *ContentTypeProfileConfig { - s.ForwardWhenContentTypeIsUnknown = &v +// SetCookies sets the Cookies field's value. +func (s *CachePolicyCookiesConfig) SetCookies(v *CookieNames) *CachePolicyCookiesConfig { + s.Cookies = v return s } -// Field-level encryption content type-profile. -type ContentTypeProfiles struct { +// An object that determines whether any HTTP headers (and if so, which headers) +// are included in the cache key and automatically included in requests that +// CloudFront sends to the origin. +type CachePolicyHeadersConfig struct { _ struct{} `type:"structure"` - // Items in a field-level encryption content type-profile mapping. - Items []*ContentTypeProfile `locationNameList:"ContentTypeProfile" type:"list"` - - // The number of field-level encryption content type-profile mappings. + // Determines whether any HTTP headers are included in the cache key and automatically + // included in requests that CloudFront sends to the origin. Valid values are: // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // * none – HTTP headers are not included in the cache key and are not + // automatically included in requests that CloudFront sends to the origin. + // Even when this field is set to none, any headers that are listed in an + // OriginRequestPolicy are included in origin requests. + // + // * whitelist – The HTTP headers that are listed in the Headers type are + // included in the cache key and are automatically included in requests that + // CloudFront sends to the origin. + // + // HeaderBehavior is a required field + HeaderBehavior *string `type:"string" required:"true" enum:"CachePolicyHeaderBehavior"` + + // Contains a list of HTTP header names. + Headers *Headers `type:"structure"` } // String returns the string representation -func (s ContentTypeProfiles) String() string { +func (s CachePolicyHeadersConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ContentTypeProfiles) GoString() string { +func (s CachePolicyHeadersConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ContentTypeProfiles) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ContentTypeProfiles"} - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) +func (s *CachePolicyHeadersConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CachePolicyHeadersConfig"} + if s.HeaderBehavior == nil { + invalidParams.Add(request.NewErrParamRequired("HeaderBehavior")) } - if s.Items != nil { - for i, v := range s.Items { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) - } + if s.Headers != nil { + if err := s.Headers.Validate(); err != nil { + invalidParams.AddNested("Headers", err.(request.ErrInvalidParams)) } } @@ -5750,131 +7427,134 @@ func (s *ContentTypeProfiles) Validate() error { return nil } -// SetItems sets the Items field's value. -func (s *ContentTypeProfiles) SetItems(v []*ContentTypeProfile) *ContentTypeProfiles { - s.Items = v +// SetHeaderBehavior sets the HeaderBehavior field's value. +func (s *CachePolicyHeadersConfig) SetHeaderBehavior(v string) *CachePolicyHeadersConfig { + s.HeaderBehavior = &v return s } -// SetQuantity sets the Quantity field's value. -func (s *ContentTypeProfiles) SetQuantity(v int64) *ContentTypeProfiles { - s.Quantity = &v +// SetHeaders sets the Headers field's value. +func (s *CachePolicyHeadersConfig) SetHeaders(v *Headers) *CachePolicyHeadersConfig { + s.Headers = v return s } -// A complex type that specifies whether you want CloudFront to forward cookies -// to the origin and, if so, which ones. For more information about forwarding -// cookies to the origin, see Caching Content Based on Request Headers (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html) -// in the Amazon CloudFront Developer Guide. -type CookieNames struct { +// A list of cache policies. +type CachePolicyList struct { _ struct{} `type:"structure"` - // A complex type that contains one Name element for each cookie that you want - // CloudFront to forward to the origin for this cache behavior. It must contain - // the same number of items that is specified in the Quantity field. - // - // When you set Forward = whitelist (in the CookiePreferences object), this - // field must contain at least one item. - Items []*string `locationNameList:"Name" type:"list"` + // Contains the cache policies in the list. + Items []*CachePolicySummary `locationNameList:"CachePolicySummary" type:"list"` - // The number of different cookies that you want CloudFront to forward to the - // origin for this cache behavior. The value must equal the number of items - // that are in the Items field. + // The maximum number of cache policies requested. // - // When you set Forward = whitelist (in the CookiePreferences object), this - // value must be 1 or higher. + // MaxItems is a required field + MaxItems *int64 `type:"integer" required:"true"` + + // If there are more items in the list than are in this response, this element + // is present. It contains the value that you should use in the Marker field + // of a subsequent request to continue listing cache policies where you left + // off. + NextMarker *string `type:"string"` + + // The total number of cache policies returned in the response. // // Quantity is a required field Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s CookieNames) String() string { +func (s CachePolicyList) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CookieNames) GoString() string { +func (s CachePolicyList) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *CookieNames) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CookieNames"} - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) - } +// SetItems sets the Items field's value. +func (s *CachePolicyList) SetItems(v []*CachePolicySummary) *CachePolicyList { + s.Items = v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetMaxItems sets the MaxItems field's value. +func (s *CachePolicyList) SetMaxItems(v int64) *CachePolicyList { + s.MaxItems = &v + return s } -// SetItems sets the Items field's value. -func (s *CookieNames) SetItems(v []*string) *CookieNames { - s.Items = v +// SetNextMarker sets the NextMarker field's value. +func (s *CachePolicyList) SetNextMarker(v string) *CachePolicyList { + s.NextMarker = &v return s } // SetQuantity sets the Quantity field's value. -func (s *CookieNames) SetQuantity(v int64) *CookieNames { +func (s *CachePolicyList) SetQuantity(v int64) *CachePolicyList { s.Quantity = &v return s } -// A complex type that specifies whether you want CloudFront to forward cookies -// to the origin and, if so, which ones. For more information about forwarding -// cookies to the origin, see Caching Content Based on Cookies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Cookies.html) -// in the Amazon CloudFront Developer Guide. -type CookiePreference struct { +// An object that determines whether any URL query strings in viewer requests +// (and if so, which query strings) are included in the cache key and automatically +// included in requests that CloudFront sends to the origin. +type CachePolicyQueryStringsConfig struct { _ struct{} `type:"structure"` - // Specifies which cookies to forward to the origin for this cache behavior: - // all, none, or the list of cookies specified in the WhitelistedNames complex - // type. + // Determines whether any URL query strings in viewer requests are included + // in the cache key and automatically included in requests that CloudFront sends + // to the origin. Valid values are: // - // Amazon S3 doesn't process cookies. When the cache behavior is forwarding - // requests to an Amazon S3 origin, specify none for the Forward element. + // * none – Query strings in viewer requests are not included in the cache + // key and are not automatically included in requests that CloudFront sends + // to the origin. Even when this field is set to none, any query strings + // that are listed in an OriginRequestPolicy are included in origin requests. // - // Forward is a required field - Forward *string `type:"string" required:"true" enum:"ItemSelection"` - - // Required if you specify whitelist for the value of Forward. A complex type - // that specifies how many different cookies you want CloudFront to forward - // to the origin for this cache behavior and, if you want to forward selected - // cookies, the names of those cookies. + // * whitelist – The query strings in viewer requests that are listed in + // the QueryStringNames type are included in the cache key and automatically + // included in requests that CloudFront sends to the origin. // - // If you specify all or none for the value of Forward, omit WhitelistedNames. - // If you change the value of Forward from whitelist to all or none and you - // don't delete the WhitelistedNames element and its child elements, CloudFront - // deletes them automatically. + // * allExcept – All query strings in viewer requests that are not listed + // in the QueryStringNames type are included in the cache key and automatically + // included in requests that CloudFront sends to the origin. // - // For the current limit on the number of cookie names that you can whitelist - // for each cache behavior, see CloudFront Limits (https://docs.aws.amazon.com/general/latest/gr/xrefaws_service_limits.html#limits_cloudfront) - // in the AWS General Reference. - WhitelistedNames *CookieNames `type:"structure"` + // * all – All query strings in viewer requests are included in the cache + // key and are automatically included in requests that CloudFront sends to + // the origin. + // + // QueryStringBehavior is a required field + QueryStringBehavior *string `type:"string" required:"true" enum:"CachePolicyQueryStringBehavior"` + + // Contains the specific query strings in viewer requests that either are or + // are not included in the cache key and automatically included in requests + // that CloudFront sends to the origin. The behavior depends on whether the + // QueryStringBehavior field in the CachePolicyQueryStringsConfig type is set + // to whitelist (the listed query strings are included) or allExcept (the listed + // query strings are not included, but all other query strings are). + QueryStrings *QueryStringNames `type:"structure"` } // String returns the string representation -func (s CookiePreference) String() string { +func (s CachePolicyQueryStringsConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CookiePreference) GoString() string { +func (s CachePolicyQueryStringsConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CookiePreference) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CookiePreference"} - if s.Forward == nil { - invalidParams.Add(request.NewErrParamRequired("Forward")) - } - if s.WhitelistedNames != nil { - if err := s.WhitelistedNames.Validate(); err != nil { - invalidParams.AddNested("WhitelistedNames", err.(request.ErrInvalidParams)) +func (s *CachePolicyQueryStringsConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CachePolicyQueryStringsConfig"} + if s.QueryStringBehavior == nil { + invalidParams.Add(request.NewErrParamRequired("QueryStringBehavior")) + } + if s.QueryStrings != nil { + if err := s.QueryStrings.Validate(); err != nil { + invalidParams.AddNested("QueryStrings", err.(request.ErrInvalidParams)) } } @@ -5884,140 +7564,157 @@ func (s *CookiePreference) Validate() error { return nil } -// SetForward sets the Forward field's value. -func (s *CookiePreference) SetForward(v string) *CookiePreference { - s.Forward = &v +// SetQueryStringBehavior sets the QueryStringBehavior field's value. +func (s *CachePolicyQueryStringsConfig) SetQueryStringBehavior(v string) *CachePolicyQueryStringsConfig { + s.QueryStringBehavior = &v return s } -// SetWhitelistedNames sets the WhitelistedNames field's value. -func (s *CookiePreference) SetWhitelistedNames(v *CookieNames) *CookiePreference { - s.WhitelistedNames = v +// SetQueryStrings sets the QueryStrings field's value. +func (s *CachePolicyQueryStringsConfig) SetQueryStrings(v *QueryStringNames) *CachePolicyQueryStringsConfig { + s.QueryStrings = v return s } -// The request to create a new origin access identity (OAI). An origin access -// identity is a special CloudFront user that you can associate with Amazon -// S3 origins, so that you can secure all or just some of your Amazon S3 content. -// For more information, see Restricting Access to Amazon S3 Content by Using -// an Origin Access Identity (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html) -// in the Amazon CloudFront Developer Guide. -type CreateCloudFrontOriginAccessIdentityInput struct { - _ struct{} `locationName:"CreateCloudFrontOriginAccessIdentityRequest" type:"structure" payload:"CloudFrontOriginAccessIdentityConfig"` +// Contains a cache policy. +type CachePolicySummary struct { + _ struct{} `type:"structure"` - // The current configuration information for the identity. + // The cache policy. // - // CloudFrontOriginAccessIdentityConfig is a required field - CloudFrontOriginAccessIdentityConfig *OriginAccessIdentityConfig `locationName:"CloudFrontOriginAccessIdentityConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + // CachePolicy is a required field + CachePolicy *CachePolicy `type:"structure" required:"true"` + + // The type of cache policy, either managed (created by AWS) or custom (created + // in this AWS account). + // + // Type is a required field + Type *string `type:"string" required:"true" enum:"CachePolicyType"` } // String returns the string representation -func (s CreateCloudFrontOriginAccessIdentityInput) String() string { +func (s CachePolicySummary) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateCloudFrontOriginAccessIdentityInput) GoString() string { +func (s CachePolicySummary) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateCloudFrontOriginAccessIdentityInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateCloudFrontOriginAccessIdentityInput"} - if s.CloudFrontOriginAccessIdentityConfig == nil { - invalidParams.Add(request.NewErrParamRequired("CloudFrontOriginAccessIdentityConfig")) - } - if s.CloudFrontOriginAccessIdentityConfig != nil { - if err := s.CloudFrontOriginAccessIdentityConfig.Validate(); err != nil { - invalidParams.AddNested("CloudFrontOriginAccessIdentityConfig", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCachePolicy sets the CachePolicy field's value. +func (s *CachePolicySummary) SetCachePolicy(v *CachePolicy) *CachePolicySummary { + s.CachePolicy = v + return s } -// SetCloudFrontOriginAccessIdentityConfig sets the CloudFrontOriginAccessIdentityConfig field's value. -func (s *CreateCloudFrontOriginAccessIdentityInput) SetCloudFrontOriginAccessIdentityConfig(v *OriginAccessIdentityConfig) *CreateCloudFrontOriginAccessIdentityInput { - s.CloudFrontOriginAccessIdentityConfig = v +// SetType sets the Type field's value. +func (s *CachePolicySummary) SetType(v string) *CachePolicySummary { + s.Type = &v return s } -// The returned result of the corresponding request. -type CreateCloudFrontOriginAccessIdentityOutput struct { - _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentity"` - - // The origin access identity's information. - CloudFrontOriginAccessIdentity *OriginAccessIdentity `type:"structure"` +// A complex type that controls whether CloudFront caches the response to requests +// using the specified HTTP methods. There are two choices: +// +// * CloudFront caches responses to GET and HEAD requests. +// +// * CloudFront caches responses to GET, HEAD, and OPTIONS requests. +// +// 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. +type CachedMethods struct { + _ struct{} `type:"structure"` - // The current version of the origin access identity created. - ETag *string `location:"header" locationName:"ETag" type:"string"` + // A complex type that contains the HTTP methods that you want CloudFront to + // cache responses to. + // + // Items is a required field + Items []*string `locationNameList:"Method" type:"list" required:"true"` - // The fully qualified URI of the new origin access identity just created. For - // example: https://cloudfront.amazonaws.com/2010-11-01/origin-access-identity/cloudfront/E74FTE3AJFJ256A. - Location *string `location:"header" locationName:"Location" type:"string"` + // The number of HTTP methods for which you want CloudFront to cache responses. + // Valid values are 2 (for caching responses to GET and HEAD requests) and 3 + // (for caching responses to GET, HEAD, and OPTIONS requests). + // + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s CreateCloudFrontOriginAccessIdentityOutput) String() string { +func (s CachedMethods) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateCloudFrontOriginAccessIdentityOutput) GoString() string { +func (s CachedMethods) GoString() string { return s.String() } -// SetCloudFrontOriginAccessIdentity sets the CloudFrontOriginAccessIdentity field's value. -func (s *CreateCloudFrontOriginAccessIdentityOutput) SetCloudFrontOriginAccessIdentity(v *OriginAccessIdentity) *CreateCloudFrontOriginAccessIdentityOutput { - s.CloudFrontOriginAccessIdentity = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *CachedMethods) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CachedMethods"} + if s.Items == nil { + invalidParams.Add(request.NewErrParamRequired("Items")) + } + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetETag sets the ETag field's value. -func (s *CreateCloudFrontOriginAccessIdentityOutput) SetETag(v string) *CreateCloudFrontOriginAccessIdentityOutput { - s.ETag = &v +// SetItems sets the Items field's value. +func (s *CachedMethods) SetItems(v []*string) *CachedMethods { + s.Items = v return s } -// SetLocation sets the Location field's value. -func (s *CreateCloudFrontOriginAccessIdentityOutput) SetLocation(v string) *CreateCloudFrontOriginAccessIdentityOutput { - s.Location = &v +// SetQuantity sets the Quantity field's value. +func (s *CachedMethods) SetQuantity(v int64) *CachedMethods { + s.Quantity = &v return s } -// The request to create a new distribution. -type CreateDistributionInput struct { - _ struct{} `locationName:"CreateDistributionRequest" type:"structure" payload:"DistributionConfig"` +// A field-level encryption content type profile. +type ContentTypeProfile struct { + _ struct{} `type:"structure"` - // The distribution's configuration information. + // The content type for a field-level encryption content type-profile mapping. // - // DistributionConfig is a required field - DistributionConfig *DistributionConfig `locationName:"DistributionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + // ContentType is a required field + ContentType *string `type:"string" required:"true"` + + // The format for a field-level encryption content type-profile mapping. + // + // Format is a required field + Format *string `type:"string" required:"true" enum:"Format"` + + // The profile ID for a field-level encryption content type-profile mapping. + ProfileId *string `type:"string"` } // String returns the string representation -func (s CreateDistributionInput) String() string { +func (s ContentTypeProfile) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDistributionInput) GoString() string { +func (s ContentTypeProfile) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDistributionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDistributionInput"} - if s.DistributionConfig == nil { - invalidParams.Add(request.NewErrParamRequired("DistributionConfig")) +func (s *ContentTypeProfile) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ContentTypeProfile"} + if s.ContentType == nil { + invalidParams.Add(request.NewErrParamRequired("ContentType")) } - if s.DistributionConfig != nil { - if err := s.DistributionConfig.Validate(); err != nil { - invalidParams.AddNested("DistributionConfig", err.(request.ErrInvalidParams)) - } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) } if invalidParams.Len() > 0 { @@ -6026,84 +7723,118 @@ func (s *CreateDistributionInput) Validate() error { return nil } -// SetDistributionConfig sets the DistributionConfig field's value. -func (s *CreateDistributionInput) SetDistributionConfig(v *DistributionConfig) *CreateDistributionInput { - s.DistributionConfig = v +// SetContentType sets the ContentType field's value. +func (s *ContentTypeProfile) SetContentType(v string) *ContentTypeProfile { + s.ContentType = &v return s } -// The returned result of the corresponding request. -type CreateDistributionOutput struct { - _ struct{} `type:"structure" payload:"Distribution"` +// SetFormat sets the Format field's value. +func (s *ContentTypeProfile) SetFormat(v string) *ContentTypeProfile { + s.Format = &v + return s +} - // The distribution's information. - Distribution *Distribution `type:"structure"` +// SetProfileId sets the ProfileId field's value. +func (s *ContentTypeProfile) SetProfileId(v string) *ContentTypeProfile { + s.ProfileId = &v + return s +} - // The current version of the distribution created. - ETag *string `location:"header" locationName:"ETag" type:"string"` +// The configuration for a field-level encryption content type-profile mapping. +type ContentTypeProfileConfig struct { + _ struct{} `type:"structure"` - // The fully qualified URI of the new distribution resource just created. For - // example: https://cloudfront.amazonaws.com/2010-11-01/distribution/EDFDVBD632BHDS5. - Location *string `location:"header" locationName:"Location" type:"string"` + // The configuration for a field-level encryption content type-profile. + ContentTypeProfiles *ContentTypeProfiles `type:"structure"` + + // The setting in a field-level encryption content type-profile mapping that + // specifies what to do when an unknown content type is provided for the profile. + // If true, content is forwarded without being encrypted when the content type + // is unknown. If false (the default), an error is returned when the content + // type is unknown. + // + // ForwardWhenContentTypeIsUnknown is a required field + ForwardWhenContentTypeIsUnknown *bool `type:"boolean" required:"true"` } // String returns the string representation -func (s CreateDistributionOutput) String() string { +func (s ContentTypeProfileConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDistributionOutput) GoString() string { +func (s ContentTypeProfileConfig) GoString() string { return s.String() } -// SetDistribution sets the Distribution field's value. -func (s *CreateDistributionOutput) SetDistribution(v *Distribution) *CreateDistributionOutput { - s.Distribution = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *ContentTypeProfileConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ContentTypeProfileConfig"} + if s.ForwardWhenContentTypeIsUnknown == nil { + invalidParams.Add(request.NewErrParamRequired("ForwardWhenContentTypeIsUnknown")) + } + if s.ContentTypeProfiles != nil { + if err := s.ContentTypeProfiles.Validate(); err != nil { + invalidParams.AddNested("ContentTypeProfiles", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetETag sets the ETag field's value. -func (s *CreateDistributionOutput) SetETag(v string) *CreateDistributionOutput { - s.ETag = &v +// SetContentTypeProfiles sets the ContentTypeProfiles field's value. +func (s *ContentTypeProfileConfig) SetContentTypeProfiles(v *ContentTypeProfiles) *ContentTypeProfileConfig { + s.ContentTypeProfiles = v return s } -// SetLocation sets the Location field's value. -func (s *CreateDistributionOutput) SetLocation(v string) *CreateDistributionOutput { - s.Location = &v +// SetForwardWhenContentTypeIsUnknown sets the ForwardWhenContentTypeIsUnknown field's value. +func (s *ContentTypeProfileConfig) SetForwardWhenContentTypeIsUnknown(v bool) *ContentTypeProfileConfig { + s.ForwardWhenContentTypeIsUnknown = &v return s } -// The request to create a new distribution with tags. -type CreateDistributionWithTagsInput struct { - _ struct{} `locationName:"CreateDistributionWithTagsRequest" type:"structure" payload:"DistributionConfigWithTags"` +// Field-level encryption content type-profile. +type ContentTypeProfiles struct { + _ struct{} `type:"structure"` - // The distribution's configuration information. + // Items in a field-level encryption content type-profile mapping. + Items []*ContentTypeProfile `locationNameList:"ContentTypeProfile" type:"list"` + + // The number of field-level encryption content type-profile mappings. // - // DistributionConfigWithTags is a required field - DistributionConfigWithTags *DistributionConfigWithTags `locationName:"DistributionConfigWithTags" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s CreateDistributionWithTagsInput) String() string { +func (s ContentTypeProfiles) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDistributionWithTagsInput) GoString() string { +func (s ContentTypeProfiles) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDistributionWithTagsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDistributionWithTagsInput"} - if s.DistributionConfigWithTags == nil { - invalidParams.Add(request.NewErrParamRequired("DistributionConfigWithTags")) +func (s *ContentTypeProfiles) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ContentTypeProfiles"} + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) } - if s.DistributionConfigWithTags != nil { - if err := s.DistributionConfigWithTags.Validate(); err != nil { - invalidParams.AddNested("DistributionConfigWithTags", err.(request.ErrInvalidParams)) + if s.Items != nil { + for i, v := range s.Items { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) + } } } @@ -6113,83 +7844,151 @@ func (s *CreateDistributionWithTagsInput) Validate() error { return nil } -// SetDistributionConfigWithTags sets the DistributionConfigWithTags field's value. -func (s *CreateDistributionWithTagsInput) SetDistributionConfigWithTags(v *DistributionConfigWithTags) *CreateDistributionWithTagsInput { - s.DistributionConfigWithTags = v +// SetItems sets the Items field's value. +func (s *ContentTypeProfiles) SetItems(v []*ContentTypeProfile) *ContentTypeProfiles { + s.Items = v return s } -// The returned result of the corresponding request. -type CreateDistributionWithTagsOutput struct { - _ struct{} `type:"structure" payload:"Distribution"` +// SetQuantity sets the Quantity field's value. +func (s *ContentTypeProfiles) SetQuantity(v int64) *ContentTypeProfiles { + s.Quantity = &v + return s +} - // The distribution's information. - Distribution *Distribution `type:"structure"` +// Contains a list of cookie names. +type CookieNames struct { + _ struct{} `type:"structure"` - // The current version of the distribution created. - ETag *string `location:"header" locationName:"ETag" type:"string"` + // A list of cookie names. + Items []*string `locationNameList:"Name" type:"list"` - // The fully qualified URI of the new distribution resource just created. For - // example: https://cloudfront.amazonaws.com/2010-11-01/distribution/EDFDVBD632BHDS5. - Location *string `location:"header" locationName:"Location" type:"string"` + // The number of cookie names in the Items list. + // + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s CreateDistributionWithTagsOutput) String() string { +func (s CookieNames) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDistributionWithTagsOutput) GoString() string { +func (s CookieNames) GoString() string { return s.String() } -// SetDistribution sets the Distribution field's value. -func (s *CreateDistributionWithTagsOutput) SetDistribution(v *Distribution) *CreateDistributionWithTagsOutput { - s.Distribution = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *CookieNames) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CookieNames"} + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetETag sets the ETag field's value. -func (s *CreateDistributionWithTagsOutput) SetETag(v string) *CreateDistributionWithTagsOutput { - s.ETag = &v +// SetItems sets the Items field's value. +func (s *CookieNames) SetItems(v []*string) *CookieNames { + s.Items = v return s } -// SetLocation sets the Location field's value. -func (s *CreateDistributionWithTagsOutput) SetLocation(v string) *CreateDistributionWithTagsOutput { - s.Location = &v +// SetQuantity sets the Quantity field's value. +func (s *CookieNames) SetQuantity(v int64) *CookieNames { + s.Quantity = &v return s } -type CreateFieldLevelEncryptionConfigInput struct { - _ struct{} `locationName:"CreateFieldLevelEncryptionConfigRequest" type:"structure" payload:"FieldLevelEncryptionConfig"` +// This field is deprecated. We recommend that you use a cache policy or an +// origin request policy instead of this field. +// +// If you want to include cookies in the cache key, use CookiesConfig in a cache +// policy. See CreateCachePolicy. +// +// If you want to send cookies to the origin but not include them in the cache +// key, use CookiesConfig in an origin request policy. See CreateOriginRequestPolicy. +// +// A complex type that specifies whether you want CloudFront to forward cookies +// to the origin and, if so, which ones. For more information about forwarding +// cookies to the origin, see Caching Content Based on Cookies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Cookies.html) +// in the Amazon CloudFront Developer Guide. +type CookiePreference struct { + _ struct{} `type:"structure"` - // The request to create a new field-level encryption configuration. + // This field is deprecated. We recommend that you use a cache policy or an + // origin request policy instead of this field. // - // FieldLevelEncryptionConfig is a required field - FieldLevelEncryptionConfig *FieldLevelEncryptionConfig `locationName:"FieldLevelEncryptionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + // If you want to include cookies in the cache key, use a cache policy. For + // more information, see Creating cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // in the Amazon CloudFront Developer Guide. + // + // If you want to send cookies to the origin but not include them in the cache + // key, use origin request policy. For more information, see Creating origin + // request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) + // in the Amazon CloudFront Developer Guide. + // + // Specifies which cookies to forward to the origin for this cache behavior: + // all, none, or the list of cookies specified in the WhitelistedNames complex + // type. + // + // Amazon S3 doesn't process cookies. When the cache behavior is forwarding + // requests to an Amazon S3 origin, specify none for the Forward element. + // + // Forward is a required field + Forward *string `type:"string" required:"true" enum:"ItemSelection"` + + // This field is deprecated. We recommend that you use a cache policy or an + // origin request policy instead of this field. + // + // If you want to include cookies in the cache key, use a cache policy. For + // more information, see Creating cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // in the Amazon CloudFront Developer Guide. + // + // If you want to send cookies to the origin but not include them in the cache + // key, use an origin request policy. For more information, see Creating origin + // request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) + // in the Amazon CloudFront Developer Guide. + // + // Required if you specify whitelist for the value of Forward. A complex type + // that specifies how many different cookies you want CloudFront to forward + // to the origin for this cache behavior and, if you want to forward selected + // cookies, the names of those cookies. + // + // If you specify all or none for the value of Forward, omit WhitelistedNames. + // If you change the value of Forward from whitelist to all or none and you + // don't delete the WhitelistedNames element and its child elements, CloudFront + // deletes them automatically. + // + // For the current limit on the number of cookie names that you can whitelist + // for each cache behavior, see CloudFront Limits (https://docs.aws.amazon.com/general/latest/gr/xrefaws_service_limits.html#limits_cloudfront) + // in the AWS General Reference. + WhitelistedNames *CookieNames `type:"structure"` } // String returns the string representation -func (s CreateFieldLevelEncryptionConfigInput) String() string { +func (s CookiePreference) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateFieldLevelEncryptionConfigInput) GoString() string { +func (s CookiePreference) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateFieldLevelEncryptionConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateFieldLevelEncryptionConfigInput"} - if s.FieldLevelEncryptionConfig == nil { - invalidParams.Add(request.NewErrParamRequired("FieldLevelEncryptionConfig")) +func (s *CookiePreference) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CookiePreference"} + if s.Forward == nil { + invalidParams.Add(request.NewErrParamRequired("Forward")) } - if s.FieldLevelEncryptionConfig != nil { - if err := s.FieldLevelEncryptionConfig.Validate(); err != nil { - invalidParams.AddNested("FieldLevelEncryptionConfig", err.(request.ErrInvalidParams)) + if s.WhitelistedNames != nil { + if err := s.WhitelistedNames.Validate(); err != nil { + invalidParams.AddNested("WhitelistedNames", err.(request.ErrInvalidParams)) } } @@ -6199,83 +7998,136 @@ func (s *CreateFieldLevelEncryptionConfigInput) Validate() error { return nil } -// SetFieldLevelEncryptionConfig sets the FieldLevelEncryptionConfig field's value. -func (s *CreateFieldLevelEncryptionConfigInput) SetFieldLevelEncryptionConfig(v *FieldLevelEncryptionConfig) *CreateFieldLevelEncryptionConfigInput { - s.FieldLevelEncryptionConfig = v +// SetForward sets the Forward field's value. +func (s *CookiePreference) SetForward(v string) *CookiePreference { + s.Forward = &v return s } -type CreateFieldLevelEncryptionConfigOutput struct { - _ struct{} `type:"structure" payload:"FieldLevelEncryption"` +// SetWhitelistedNames sets the WhitelistedNames field's value. +func (s *CookiePreference) SetWhitelistedNames(v *CookieNames) *CookiePreference { + s.WhitelistedNames = v + return s +} - // The current version of the field level encryption configuration. For example: - // E2QWRUHAPOMQZL. - ETag *string `location:"header" locationName:"ETag" type:"string"` +type CreateCachePolicyInput struct { + _ struct{} `locationName:"CreateCachePolicyRequest" type:"structure" payload:"CachePolicyConfig"` - // Returned when you create a new field-level encryption configuration. - FieldLevelEncryption *FieldLevelEncryption `type:"structure"` + // A cache policy configuration. + // + // CachePolicyConfig is a required field + CachePolicyConfig *CachePolicyConfig `locationName:"CachePolicyConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` +} + +// String returns the string representation +func (s CreateCachePolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateCachePolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateCachePolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateCachePolicyInput"} + if s.CachePolicyConfig == nil { + invalidParams.Add(request.NewErrParamRequired("CachePolicyConfig")) + } + if s.CachePolicyConfig != nil { + if err := s.CachePolicyConfig.Validate(); err != nil { + invalidParams.AddNested("CachePolicyConfig", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCachePolicyConfig sets the CachePolicyConfig field's value. +func (s *CreateCachePolicyInput) SetCachePolicyConfig(v *CachePolicyConfig) *CreateCachePolicyInput { + s.CachePolicyConfig = v + return s +} + +type CreateCachePolicyOutput struct { + _ struct{} `type:"structure" payload:"CachePolicy"` + + // A cache policy. + CachePolicy *CachePolicy `type:"structure"` + + // The current version of the cache policy. + ETag *string `location:"header" locationName:"ETag" type:"string"` - // The fully qualified URI of the new configuration resource just created. For - // example: https://cloudfront.amazonaws.com/2010-11-01/field-level-encryption-config/EDFDVBD632BHDS5. + // The fully qualified URI of the cache policy just created. Location *string `location:"header" locationName:"Location" type:"string"` } // String returns the string representation -func (s CreateFieldLevelEncryptionConfigOutput) String() string { +func (s CreateCachePolicyOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateFieldLevelEncryptionConfigOutput) GoString() string { +func (s CreateCachePolicyOutput) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *CreateFieldLevelEncryptionConfigOutput) SetETag(v string) *CreateFieldLevelEncryptionConfigOutput { - s.ETag = &v +// SetCachePolicy sets the CachePolicy field's value. +func (s *CreateCachePolicyOutput) SetCachePolicy(v *CachePolicy) *CreateCachePolicyOutput { + s.CachePolicy = v return s } -// SetFieldLevelEncryption sets the FieldLevelEncryption field's value. -func (s *CreateFieldLevelEncryptionConfigOutput) SetFieldLevelEncryption(v *FieldLevelEncryption) *CreateFieldLevelEncryptionConfigOutput { - s.FieldLevelEncryption = v +// SetETag sets the ETag field's value. +func (s *CreateCachePolicyOutput) SetETag(v string) *CreateCachePolicyOutput { + s.ETag = &v return s } // SetLocation sets the Location field's value. -func (s *CreateFieldLevelEncryptionConfigOutput) SetLocation(v string) *CreateFieldLevelEncryptionConfigOutput { +func (s *CreateCachePolicyOutput) SetLocation(v string) *CreateCachePolicyOutput { s.Location = &v return s } -type CreateFieldLevelEncryptionProfileInput struct { - _ struct{} `locationName:"CreateFieldLevelEncryptionProfileRequest" type:"structure" payload:"FieldLevelEncryptionProfileConfig"` +// The request to create a new origin access identity (OAI). An origin access +// identity is a special CloudFront user that you can associate with Amazon +// S3 origins, so that you can secure all or just some of your Amazon S3 content. +// For more information, see Restricting Access to Amazon S3 Content by Using +// an Origin Access Identity (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html) +// in the Amazon CloudFront Developer Guide. +type CreateCloudFrontOriginAccessIdentityInput struct { + _ struct{} `locationName:"CreateCloudFrontOriginAccessIdentityRequest" type:"structure" payload:"CloudFrontOriginAccessIdentityConfig"` - // The request to create a field-level encryption profile. + // The current configuration information for the identity. // - // FieldLevelEncryptionProfileConfig is a required field - FieldLevelEncryptionProfileConfig *FieldLevelEncryptionProfileConfig `locationName:"FieldLevelEncryptionProfileConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + // CloudFrontOriginAccessIdentityConfig is a required field + CloudFrontOriginAccessIdentityConfig *OriginAccessIdentityConfig `locationName:"CloudFrontOriginAccessIdentityConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation -func (s CreateFieldLevelEncryptionProfileInput) String() string { +func (s CreateCloudFrontOriginAccessIdentityInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateFieldLevelEncryptionProfileInput) GoString() string { +func (s CreateCloudFrontOriginAccessIdentityInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateFieldLevelEncryptionProfileInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateFieldLevelEncryptionProfileInput"} - if s.FieldLevelEncryptionProfileConfig == nil { - invalidParams.Add(request.NewErrParamRequired("FieldLevelEncryptionProfileConfig")) +func (s *CreateCloudFrontOriginAccessIdentityInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateCloudFrontOriginAccessIdentityInput"} + if s.CloudFrontOriginAccessIdentityConfig == nil { + invalidParams.Add(request.NewErrParamRequired("CloudFrontOriginAccessIdentityConfig")) } - if s.FieldLevelEncryptionProfileConfig != nil { - if err := s.FieldLevelEncryptionProfileConfig.Validate(); err != nil { - invalidParams.AddNested("FieldLevelEncryptionProfileConfig", err.(request.ErrInvalidParams)) + if s.CloudFrontOriginAccessIdentityConfig != nil { + if err := s.CloudFrontOriginAccessIdentityConfig.Validate(); err != nil { + invalidParams.AddNested("CloudFrontOriginAccessIdentityConfig", err.(request.ErrInvalidParams)) } } @@ -6285,94 +8137,83 @@ func (s *CreateFieldLevelEncryptionProfileInput) Validate() error { return nil } -// SetFieldLevelEncryptionProfileConfig sets the FieldLevelEncryptionProfileConfig field's value. -func (s *CreateFieldLevelEncryptionProfileInput) SetFieldLevelEncryptionProfileConfig(v *FieldLevelEncryptionProfileConfig) *CreateFieldLevelEncryptionProfileInput { - s.FieldLevelEncryptionProfileConfig = v +// SetCloudFrontOriginAccessIdentityConfig sets the CloudFrontOriginAccessIdentityConfig field's value. +func (s *CreateCloudFrontOriginAccessIdentityInput) SetCloudFrontOriginAccessIdentityConfig(v *OriginAccessIdentityConfig) *CreateCloudFrontOriginAccessIdentityInput { + s.CloudFrontOriginAccessIdentityConfig = v return s } -type CreateFieldLevelEncryptionProfileOutput struct { - _ struct{} `type:"structure" payload:"FieldLevelEncryptionProfile"` +// The returned result of the corresponding request. +type CreateCloudFrontOriginAccessIdentityOutput struct { + _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentity"` - // The current version of the field level encryption profile. For example: E2QWRUHAPOMQZL. - ETag *string `location:"header" locationName:"ETag" type:"string"` + // The origin access identity's information. + CloudFrontOriginAccessIdentity *OriginAccessIdentity `type:"structure"` - // Returned when you create a new field-level encryption profile. - FieldLevelEncryptionProfile *FieldLevelEncryptionProfile `type:"structure"` + // The current version of the origin access identity created. + ETag *string `location:"header" locationName:"ETag" type:"string"` - // The fully qualified URI of the new profile resource just created. For example: - // https://cloudfront.amazonaws.com/2010-11-01/field-level-encryption-profile/EDFDVBD632BHDS5. + // The fully qualified URI of the new origin access identity just created. Location *string `location:"header" locationName:"Location" type:"string"` } // String returns the string representation -func (s CreateFieldLevelEncryptionProfileOutput) String() string { +func (s CreateCloudFrontOriginAccessIdentityOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateFieldLevelEncryptionProfileOutput) GoString() string { +func (s CreateCloudFrontOriginAccessIdentityOutput) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *CreateFieldLevelEncryptionProfileOutput) SetETag(v string) *CreateFieldLevelEncryptionProfileOutput { - s.ETag = &v +// SetCloudFrontOriginAccessIdentity sets the CloudFrontOriginAccessIdentity field's value. +func (s *CreateCloudFrontOriginAccessIdentityOutput) SetCloudFrontOriginAccessIdentity(v *OriginAccessIdentity) *CreateCloudFrontOriginAccessIdentityOutput { + s.CloudFrontOriginAccessIdentity = v return s } -// SetFieldLevelEncryptionProfile sets the FieldLevelEncryptionProfile field's value. -func (s *CreateFieldLevelEncryptionProfileOutput) SetFieldLevelEncryptionProfile(v *FieldLevelEncryptionProfile) *CreateFieldLevelEncryptionProfileOutput { - s.FieldLevelEncryptionProfile = v +// SetETag sets the ETag field's value. +func (s *CreateCloudFrontOriginAccessIdentityOutput) SetETag(v string) *CreateCloudFrontOriginAccessIdentityOutput { + s.ETag = &v return s } // SetLocation sets the Location field's value. -func (s *CreateFieldLevelEncryptionProfileOutput) SetLocation(v string) *CreateFieldLevelEncryptionProfileOutput { +func (s *CreateCloudFrontOriginAccessIdentityOutput) SetLocation(v string) *CreateCloudFrontOriginAccessIdentityOutput { s.Location = &v return s } -// The request to create an invalidation. -type CreateInvalidationInput struct { - _ struct{} `locationName:"CreateInvalidationRequest" type:"structure" payload:"InvalidationBatch"` - - // The distribution's id. - // - // DistributionId is a required field - DistributionId *string `location:"uri" locationName:"DistributionId" type:"string" required:"true"` +// The request to create a new distribution. +type CreateDistributionInput struct { + _ struct{} `locationName:"CreateDistributionRequest" type:"structure" payload:"DistributionConfig"` - // The batch information for the invalidation. + // The distribution's configuration information. // - // InvalidationBatch is a required field - InvalidationBatch *InvalidationBatch `locationName:"InvalidationBatch" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + // DistributionConfig is a required field + DistributionConfig *DistributionConfig `locationName:"DistributionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation -func (s CreateInvalidationInput) String() string { +func (s CreateDistributionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateInvalidationInput) GoString() string { +func (s CreateDistributionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateInvalidationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateInvalidationInput"} - if s.DistributionId == nil { - invalidParams.Add(request.NewErrParamRequired("DistributionId")) - } - if s.DistributionId != nil && len(*s.DistributionId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DistributionId", 1)) - } - if s.InvalidationBatch == nil { - invalidParams.Add(request.NewErrParamRequired("InvalidationBatch")) +func (s *CreateDistributionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDistributionInput"} + if s.DistributionConfig == nil { + invalidParams.Add(request.NewErrParamRequired("DistributionConfig")) } - if s.InvalidationBatch != nil { - if err := s.InvalidationBatch.Validate(); err != nil { - invalidParams.AddNested("InvalidationBatch", err.(request.ErrInvalidParams)) + if s.DistributionConfig != nil { + if err := s.DistributionConfig.Validate(); err != nil { + invalidParams.AddNested("DistributionConfig", err.(request.ErrInvalidParams)) } } @@ -6382,80 +8223,83 @@ func (s *CreateInvalidationInput) Validate() error { return nil } -// SetDistributionId sets the DistributionId field's value. -func (s *CreateInvalidationInput) SetDistributionId(v string) *CreateInvalidationInput { - s.DistributionId = &v - return s -} - -// SetInvalidationBatch sets the InvalidationBatch field's value. -func (s *CreateInvalidationInput) SetInvalidationBatch(v *InvalidationBatch) *CreateInvalidationInput { - s.InvalidationBatch = v +// SetDistributionConfig sets the DistributionConfig field's value. +func (s *CreateDistributionInput) SetDistributionConfig(v *DistributionConfig) *CreateDistributionInput { + s.DistributionConfig = v return s } // The returned result of the corresponding request. -type CreateInvalidationOutput struct { - _ struct{} `type:"structure" payload:"Invalidation"` +type CreateDistributionOutput struct { + _ struct{} `type:"structure" payload:"Distribution"` - // The invalidation's information. - Invalidation *Invalidation `type:"structure"` + // The distribution's information. + Distribution *Distribution `type:"structure"` - // The fully qualified URI of the distribution and invalidation batch request, - // including the Invalidation ID. + // The current version of the distribution created. + ETag *string `location:"header" locationName:"ETag" type:"string"` + + // The fully qualified URI of the new distribution resource just created. Location *string `location:"header" locationName:"Location" type:"string"` } // String returns the string representation -func (s CreateInvalidationOutput) String() string { +func (s CreateDistributionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateInvalidationOutput) GoString() string { +func (s CreateDistributionOutput) GoString() string { return s.String() } -// SetInvalidation sets the Invalidation field's value. -func (s *CreateInvalidationOutput) SetInvalidation(v *Invalidation) *CreateInvalidationOutput { - s.Invalidation = v +// SetDistribution sets the Distribution field's value. +func (s *CreateDistributionOutput) SetDistribution(v *Distribution) *CreateDistributionOutput { + s.Distribution = v + return s +} + +// SetETag sets the ETag field's value. +func (s *CreateDistributionOutput) SetETag(v string) *CreateDistributionOutput { + s.ETag = &v return s } // SetLocation sets the Location field's value. -func (s *CreateInvalidationOutput) SetLocation(v string) *CreateInvalidationOutput { +func (s *CreateDistributionOutput) SetLocation(v string) *CreateDistributionOutput { s.Location = &v return s } -type CreatePublicKeyInput struct { - _ struct{} `locationName:"CreatePublicKeyRequest" type:"structure" payload:"PublicKeyConfig"` +// The request to create a new distribution with tags. +type CreateDistributionWithTagsInput struct { + _ struct{} `locationName:"CreateDistributionWithTagsRequest" type:"structure" payload:"DistributionConfigWithTags"` - // The request to add a public key to CloudFront. + // The distribution's configuration information. // - // PublicKeyConfig is a required field - PublicKeyConfig *PublicKeyConfig `locationName:"PublicKeyConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + // DistributionConfigWithTags is a required field + DistributionConfigWithTags *DistributionConfigWithTags `locationName:"DistributionConfigWithTags" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation -func (s CreatePublicKeyInput) String() string { +func (s CreateDistributionWithTagsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreatePublicKeyInput) GoString() string { +func (s CreateDistributionWithTagsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreatePublicKeyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreatePublicKeyInput"} - if s.PublicKeyConfig == nil { - invalidParams.Add(request.NewErrParamRequired("PublicKeyConfig")) +func (s *CreateDistributionWithTagsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDistributionWithTagsInput"} + if s.DistributionConfigWithTags == nil { + invalidParams.Add(request.NewErrParamRequired("DistributionConfigWithTags")) } - if s.PublicKeyConfig != nil { - if err := s.PublicKeyConfig.Validate(); err != nil { - invalidParams.AddNested("PublicKeyConfig", err.(request.ErrInvalidParams)) + if s.DistributionConfigWithTags != nil { + if err := s.DistributionConfigWithTags.Validate(); err != nil { + invalidParams.AddNested("DistributionConfigWithTags", err.(request.ErrInvalidParams)) } } @@ -6465,83 +8309,82 @@ func (s *CreatePublicKeyInput) Validate() error { return nil } -// SetPublicKeyConfig sets the PublicKeyConfig field's value. -func (s *CreatePublicKeyInput) SetPublicKeyConfig(v *PublicKeyConfig) *CreatePublicKeyInput { - s.PublicKeyConfig = v +// SetDistributionConfigWithTags sets the DistributionConfigWithTags field's value. +func (s *CreateDistributionWithTagsInput) SetDistributionConfigWithTags(v *DistributionConfigWithTags) *CreateDistributionWithTagsInput { + s.DistributionConfigWithTags = v return s } -type CreatePublicKeyOutput struct { - _ struct{} `type:"structure" payload:"PublicKey"` +// The returned result of the corresponding request. +type CreateDistributionWithTagsOutput struct { + _ struct{} `type:"structure" payload:"Distribution"` - // The current version of the public key. For example: E2QWRUHAPOMQZL. + // The distribution's information. + Distribution *Distribution `type:"structure"` + + // The current version of the distribution created. ETag *string `location:"header" locationName:"ETag" type:"string"` - // The fully qualified URI of the new public key resource just created. For - // example: https://cloudfront.amazonaws.com/2010-11-01/cloudfront-public-key/EDFDVBD632BHDS5. + // The fully qualified URI of the new distribution resource just created. Location *string `location:"header" locationName:"Location" type:"string"` - - // Returned when you add a public key. - PublicKey *PublicKey `type:"structure"` } // String returns the string representation -func (s CreatePublicKeyOutput) String() string { +func (s CreateDistributionWithTagsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreatePublicKeyOutput) GoString() string { +func (s CreateDistributionWithTagsOutput) GoString() string { return s.String() } +// SetDistribution sets the Distribution field's value. +func (s *CreateDistributionWithTagsOutput) SetDistribution(v *Distribution) *CreateDistributionWithTagsOutput { + s.Distribution = v + return s +} + // SetETag sets the ETag field's value. -func (s *CreatePublicKeyOutput) SetETag(v string) *CreatePublicKeyOutput { +func (s *CreateDistributionWithTagsOutput) SetETag(v string) *CreateDistributionWithTagsOutput { s.ETag = &v return s } // SetLocation sets the Location field's value. -func (s *CreatePublicKeyOutput) SetLocation(v string) *CreatePublicKeyOutput { +func (s *CreateDistributionWithTagsOutput) SetLocation(v string) *CreateDistributionWithTagsOutput { s.Location = &v return s } -// SetPublicKey sets the PublicKey field's value. -func (s *CreatePublicKeyOutput) SetPublicKey(v *PublicKey) *CreatePublicKeyOutput { - s.PublicKey = v - return s -} - -// The request to create a new streaming distribution. -type CreateStreamingDistributionInput struct { - _ struct{} `locationName:"CreateStreamingDistributionRequest" type:"structure" payload:"StreamingDistributionConfig"` +type CreateFieldLevelEncryptionConfigInput struct { + _ struct{} `locationName:"CreateFieldLevelEncryptionConfigRequest" type:"structure" payload:"FieldLevelEncryptionConfig"` - // The streaming distribution's configuration information. + // The request to create a new field-level encryption configuration. // - // StreamingDistributionConfig is a required field - StreamingDistributionConfig *StreamingDistributionConfig `locationName:"StreamingDistributionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + // FieldLevelEncryptionConfig is a required field + FieldLevelEncryptionConfig *FieldLevelEncryptionConfig `locationName:"FieldLevelEncryptionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation -func (s CreateStreamingDistributionInput) String() string { +func (s CreateFieldLevelEncryptionConfigInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateStreamingDistributionInput) GoString() string { +func (s CreateFieldLevelEncryptionConfigInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateStreamingDistributionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateStreamingDistributionInput"} - if s.StreamingDistributionConfig == nil { - invalidParams.Add(request.NewErrParamRequired("StreamingDistributionConfig")) +func (s *CreateFieldLevelEncryptionConfigInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateFieldLevelEncryptionConfigInput"} + if s.FieldLevelEncryptionConfig == nil { + invalidParams.Add(request.NewErrParamRequired("FieldLevelEncryptionConfig")) } - if s.StreamingDistributionConfig != nil { - if err := s.StreamingDistributionConfig.Validate(); err != nil { - invalidParams.AddNested("StreamingDistributionConfig", err.(request.ErrInvalidParams)) + if s.FieldLevelEncryptionConfig != nil { + if err := s.FieldLevelEncryptionConfig.Validate(); err != nil { + invalidParams.AddNested("FieldLevelEncryptionConfig", err.(request.ErrInvalidParams)) } } @@ -6551,84 +8394,82 @@ func (s *CreateStreamingDistributionInput) Validate() error { return nil } -// SetStreamingDistributionConfig sets the StreamingDistributionConfig field's value. -func (s *CreateStreamingDistributionInput) SetStreamingDistributionConfig(v *StreamingDistributionConfig) *CreateStreamingDistributionInput { - s.StreamingDistributionConfig = v +// SetFieldLevelEncryptionConfig sets the FieldLevelEncryptionConfig field's value. +func (s *CreateFieldLevelEncryptionConfigInput) SetFieldLevelEncryptionConfig(v *FieldLevelEncryptionConfig) *CreateFieldLevelEncryptionConfigInput { + s.FieldLevelEncryptionConfig = v return s } -// The returned result of the corresponding request. -type CreateStreamingDistributionOutput struct { - _ struct{} `type:"structure" payload:"StreamingDistribution"` +type CreateFieldLevelEncryptionConfigOutput struct { + _ struct{} `type:"structure" payload:"FieldLevelEncryption"` - // The current version of the streaming distribution created. + // The current version of the field level encryption configuration. For example: + // E2QWRUHAPOMQZL. ETag *string `location:"header" locationName:"ETag" type:"string"` - // The fully qualified URI of the new streaming distribution resource just created. - // For example: https://cloudfront.amazonaws.com/2010-11-01/streaming-distribution/EGTXBD79H29TRA8. - Location *string `location:"header" locationName:"Location" type:"string"` + // Returned when you create a new field-level encryption configuration. + FieldLevelEncryption *FieldLevelEncryption `type:"structure"` - // The streaming distribution's information. - StreamingDistribution *StreamingDistribution `type:"structure"` + // The fully qualified URI of the new configuration resource just created. + Location *string `location:"header" locationName:"Location" type:"string"` } // String returns the string representation -func (s CreateStreamingDistributionOutput) String() string { +func (s CreateFieldLevelEncryptionConfigOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateStreamingDistributionOutput) GoString() string { +func (s CreateFieldLevelEncryptionConfigOutput) GoString() string { return s.String() } // SetETag sets the ETag field's value. -func (s *CreateStreamingDistributionOutput) SetETag(v string) *CreateStreamingDistributionOutput { +func (s *CreateFieldLevelEncryptionConfigOutput) SetETag(v string) *CreateFieldLevelEncryptionConfigOutput { s.ETag = &v return s } -// SetLocation sets the Location field's value. -func (s *CreateStreamingDistributionOutput) SetLocation(v string) *CreateStreamingDistributionOutput { - s.Location = &v +// SetFieldLevelEncryption sets the FieldLevelEncryption field's value. +func (s *CreateFieldLevelEncryptionConfigOutput) SetFieldLevelEncryption(v *FieldLevelEncryption) *CreateFieldLevelEncryptionConfigOutput { + s.FieldLevelEncryption = v return s } -// SetStreamingDistribution sets the StreamingDistribution field's value. -func (s *CreateStreamingDistributionOutput) SetStreamingDistribution(v *StreamingDistribution) *CreateStreamingDistributionOutput { - s.StreamingDistribution = v +// SetLocation sets the Location field's value. +func (s *CreateFieldLevelEncryptionConfigOutput) SetLocation(v string) *CreateFieldLevelEncryptionConfigOutput { + s.Location = &v return s } -// The request to create a new streaming distribution with tags. -type CreateStreamingDistributionWithTagsInput struct { - _ struct{} `locationName:"CreateStreamingDistributionWithTagsRequest" type:"structure" payload:"StreamingDistributionConfigWithTags"` +type CreateFieldLevelEncryptionProfileInput struct { + _ struct{} `locationName:"CreateFieldLevelEncryptionProfileRequest" type:"structure" payload:"FieldLevelEncryptionProfileConfig"` - // The streaming distribution's configuration information. + // The request to create a field-level encryption profile. // - // StreamingDistributionConfigWithTags is a required field - StreamingDistributionConfigWithTags *StreamingDistributionConfigWithTags `locationName:"StreamingDistributionConfigWithTags" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + // FieldLevelEncryptionProfileConfig is a required field + FieldLevelEncryptionProfileConfig *FieldLevelEncryptionProfileConfig `locationName:"FieldLevelEncryptionProfileConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation -func (s CreateStreamingDistributionWithTagsInput) String() string { +func (s CreateFieldLevelEncryptionProfileInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateStreamingDistributionWithTagsInput) GoString() string { +func (s CreateFieldLevelEncryptionProfileInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateStreamingDistributionWithTagsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateStreamingDistributionWithTagsInput"} - if s.StreamingDistributionConfigWithTags == nil { - invalidParams.Add(request.NewErrParamRequired("StreamingDistributionConfigWithTags")) +func (s *CreateFieldLevelEncryptionProfileInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateFieldLevelEncryptionProfileInput"} + if s.FieldLevelEncryptionProfileConfig == nil { + invalidParams.Add(request.NewErrParamRequired("FieldLevelEncryptionProfileConfig")) } - if s.StreamingDistributionConfigWithTags != nil { - if err := s.StreamingDistributionConfigWithTags.Validate(); err != nil { - invalidParams.AddNested("StreamingDistributionConfigWithTags", err.(request.ErrInvalidParams)) + if s.FieldLevelEncryptionProfileConfig != nil { + if err := s.FieldLevelEncryptionProfileConfig.Validate(); err != nil { + invalidParams.AddNested("FieldLevelEncryptionProfileConfig", err.(request.ErrInvalidParams)) } } @@ -6638,144 +8479,94 @@ func (s *CreateStreamingDistributionWithTagsInput) Validate() error { return nil } -// SetStreamingDistributionConfigWithTags sets the StreamingDistributionConfigWithTags field's value. -func (s *CreateStreamingDistributionWithTagsInput) SetStreamingDistributionConfigWithTags(v *StreamingDistributionConfigWithTags) *CreateStreamingDistributionWithTagsInput { - s.StreamingDistributionConfigWithTags = v +// SetFieldLevelEncryptionProfileConfig sets the FieldLevelEncryptionProfileConfig field's value. +func (s *CreateFieldLevelEncryptionProfileInput) SetFieldLevelEncryptionProfileConfig(v *FieldLevelEncryptionProfileConfig) *CreateFieldLevelEncryptionProfileInput { + s.FieldLevelEncryptionProfileConfig = v return s } -// The returned result of the corresponding request. -type CreateStreamingDistributionWithTagsOutput struct { - _ struct{} `type:"structure" payload:"StreamingDistribution"` +type CreateFieldLevelEncryptionProfileOutput struct { + _ struct{} `type:"structure" payload:"FieldLevelEncryptionProfile"` - // The current version of the distribution created. + // The current version of the field level encryption profile. For example: E2QWRUHAPOMQZL. ETag *string `location:"header" locationName:"ETag" type:"string"` - // The fully qualified URI of the new streaming distribution resource just created. - // For example:https://cloudfront.amazonaws.com/2010-11-01/streaming-distribution/EGTXBD79H29TRA8. - Location *string `location:"header" locationName:"Location" type:"string"` + // Returned when you create a new field-level encryption profile. + FieldLevelEncryptionProfile *FieldLevelEncryptionProfile `type:"structure"` - // The streaming distribution's information. - StreamingDistribution *StreamingDistribution `type:"structure"` + // The fully qualified URI of the new profile resource just created. + Location *string `location:"header" locationName:"Location" type:"string"` } // String returns the string representation -func (s CreateStreamingDistributionWithTagsOutput) String() string { +func (s CreateFieldLevelEncryptionProfileOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateStreamingDistributionWithTagsOutput) GoString() string { +func (s CreateFieldLevelEncryptionProfileOutput) GoString() string { return s.String() } // SetETag sets the ETag field's value. -func (s *CreateStreamingDistributionWithTagsOutput) SetETag(v string) *CreateStreamingDistributionWithTagsOutput { +func (s *CreateFieldLevelEncryptionProfileOutput) SetETag(v string) *CreateFieldLevelEncryptionProfileOutput { s.ETag = &v return s } -// SetLocation sets the Location field's value. -func (s *CreateStreamingDistributionWithTagsOutput) SetLocation(v string) *CreateStreamingDistributionWithTagsOutput { - s.Location = &v +// SetFieldLevelEncryptionProfile sets the FieldLevelEncryptionProfile field's value. +func (s *CreateFieldLevelEncryptionProfileOutput) SetFieldLevelEncryptionProfile(v *FieldLevelEncryptionProfile) *CreateFieldLevelEncryptionProfileOutput { + s.FieldLevelEncryptionProfile = v return s } -// SetStreamingDistribution sets the StreamingDistribution field's value. -func (s *CreateStreamingDistributionWithTagsOutput) SetStreamingDistribution(v *StreamingDistribution) *CreateStreamingDistributionWithTagsOutput { - s.StreamingDistribution = v +// SetLocation sets the Location field's value. +func (s *CreateFieldLevelEncryptionProfileOutput) SetLocation(v string) *CreateFieldLevelEncryptionProfileOutput { + s.Location = &v return s } -// A complex type that controls: -// -// * Whether CloudFront replaces HTTP status codes in the 4xx and 5xx range -// with custom error messages before returning the response to the viewer. -// -// * How long CloudFront caches HTTP status codes in the 4xx and 5xx range. -// -// For more information about custom error pages, see Customizing Error Responses -// (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html) -// in the Amazon CloudFront Developer Guide. -type CustomErrorResponse struct { - _ struct{} `type:"structure"` +// The request to create an invalidation. +type CreateInvalidationInput struct { + _ struct{} `locationName:"CreateInvalidationRequest" type:"structure" payload:"InvalidationBatch"` - // The minimum amount of time, in seconds, that you want CloudFront to cache - // the HTTP status code specified in ErrorCode. When this time period has elapsed, - // CloudFront queries your origin to see whether the problem that caused the - // error has been resolved and the requested object is now available. - // - // For more information, see Customizing Error Responses (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html) - // in the Amazon CloudFront Developer Guide. - ErrorCachingMinTTL *int64 `type:"long"` - - // The HTTP status code for which you want to specify a custom error page and/or - // a caching duration. - // - // ErrorCode is a required field - ErrorCode *int64 `type:"integer" required:"true"` - - // The HTTP status code that you want CloudFront to return to the viewer along - // with the custom error page. There are a variety of reasons that you might - // want CloudFront to return a status code different from the status code that - // your origin returned to CloudFront, for example: - // - // * Some Internet devices (some firewalls and corporate proxies, for example) - // intercept HTTP 4xx and 5xx and prevent the response from being returned - // to the viewer. If you substitute 200, the response typically won't be - // intercepted. - // - // * If you don't care about distinguishing among different client errors - // or server errors, you can specify 400 or 500 as the ResponseCode for all - // 4xx or 5xx errors. - // - // * You might want to return a 200 status code (OK) and static website so - // your customers don't know that your website is down. + // The distribution's id. // - // If you specify a value for ResponseCode, you must also specify a value for - // ResponsePagePath. - ResponseCode *string `type:"string"` + // DistributionId is a required field + DistributionId *string `location:"uri" locationName:"DistributionId" type:"string" required:"true"` - // The path to the custom error page that you want CloudFront to return to a - // viewer when your origin returns the HTTP status code specified by ErrorCode, - // for example, /4xx-errors/403-forbidden.html. If you want to store your objects - // and your custom error pages in different locations, your distribution must - // include a cache behavior for which the following is true: - // - // * The value of PathPattern matches the path to your custom error messages. - // For example, suppose you saved custom error pages for 4xx errors in an - // Amazon S3 bucket in a directory named /4xx-errors. Your distribution must - // include a cache behavior for which the path pattern routes requests for - // your custom error pages to that location, for example, /4xx-errors/*. - // - // * The value of TargetOriginId specifies the value of the ID element for - // the origin that contains your custom error pages. - // - // If you specify a value for ResponsePagePath, you must also specify a value - // for ResponseCode. + // The batch information for the invalidation. // - // We recommend that you store custom error pages in an Amazon S3 bucket. If - // you store custom error pages on an HTTP server and the server starts to return - // 5xx errors, CloudFront can't get the files that you want to return to viewers - // because the origin server is unavailable. - ResponsePagePath *string `type:"string"` + // InvalidationBatch is a required field + InvalidationBatch *InvalidationBatch `locationName:"InvalidationBatch" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation -func (s CustomErrorResponse) String() string { +func (s CreateInvalidationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CustomErrorResponse) GoString() string { +func (s CreateInvalidationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CustomErrorResponse) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CustomErrorResponse"} - if s.ErrorCode == nil { - invalidParams.Add(request.NewErrParamRequired("ErrorCode")) +func (s *CreateInvalidationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateInvalidationInput"} + if s.DistributionId == nil { + invalidParams.Add(request.NewErrParamRequired("DistributionId")) + } + if s.DistributionId != nil && len(*s.DistributionId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DistributionId", 1)) + } + if s.InvalidationBatch == nil { + invalidParams.Add(request.NewErrParamRequired("InvalidationBatch")) + } + if s.InvalidationBatch != nil { + if err := s.InvalidationBatch.Validate(); err != nil { + invalidParams.AddNested("InvalidationBatch", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -6784,79 +8575,80 @@ func (s *CustomErrorResponse) Validate() error { return nil } -// SetErrorCachingMinTTL sets the ErrorCachingMinTTL field's value. -func (s *CustomErrorResponse) SetErrorCachingMinTTL(v int64) *CustomErrorResponse { - s.ErrorCachingMinTTL = &v +// SetDistributionId sets the DistributionId field's value. +func (s *CreateInvalidationInput) SetDistributionId(v string) *CreateInvalidationInput { + s.DistributionId = &v return s } -// SetErrorCode sets the ErrorCode field's value. -func (s *CustomErrorResponse) SetErrorCode(v int64) *CustomErrorResponse { - s.ErrorCode = &v +// SetInvalidationBatch sets the InvalidationBatch field's value. +func (s *CreateInvalidationInput) SetInvalidationBatch(v *InvalidationBatch) *CreateInvalidationInput { + s.InvalidationBatch = v return s } -// SetResponseCode sets the ResponseCode field's value. -func (s *CustomErrorResponse) SetResponseCode(v string) *CustomErrorResponse { - s.ResponseCode = &v - return s +// The returned result of the corresponding request. +type CreateInvalidationOutput struct { + _ struct{} `type:"structure" payload:"Invalidation"` + + // The invalidation's information. + Invalidation *Invalidation `type:"structure"` + + // The fully qualified URI of the distribution and invalidation batch request, + // including the Invalidation ID. + Location *string `location:"header" locationName:"Location" type:"string"` } -// SetResponsePagePath sets the ResponsePagePath field's value. -func (s *CustomErrorResponse) SetResponsePagePath(v string) *CustomErrorResponse { - s.ResponsePagePath = &v +// String returns the string representation +func (s CreateInvalidationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateInvalidationOutput) GoString() string { + return s.String() +} + +// SetInvalidation sets the Invalidation field's value. +func (s *CreateInvalidationOutput) SetInvalidation(v *Invalidation) *CreateInvalidationOutput { + s.Invalidation = v return s } -// A complex type that controls: -// -// * Whether CloudFront replaces HTTP status codes in the 4xx and 5xx range -// with custom error messages before returning the response to the viewer. -// -// * How long CloudFront caches HTTP status codes in the 4xx and 5xx range. -// -// For more information about custom error pages, see Customizing Error Responses -// (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html) -// in the Amazon CloudFront Developer Guide. -type CustomErrorResponses struct { - _ struct{} `type:"structure"` +// SetLocation sets the Location field's value. +func (s *CreateInvalidationOutput) SetLocation(v string) *CreateInvalidationOutput { + s.Location = &v + return s +} - // A complex type that contains a CustomErrorResponse element for each HTTP - // status code for which you want to specify a custom error page and/or a caching - // duration. - Items []*CustomErrorResponse `locationNameList:"CustomErrorResponse" type:"list"` +type CreateOriginRequestPolicyInput struct { + _ struct{} `locationName:"CreateOriginRequestPolicyRequest" type:"structure" payload:"OriginRequestPolicyConfig"` - // The number of HTTP status codes for which you want to specify a custom error - // page and/or a caching duration. If Quantity is 0, you can omit Items. + // An origin request policy configuration. // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // OriginRequestPolicyConfig is a required field + OriginRequestPolicyConfig *OriginRequestPolicyConfig `locationName:"OriginRequestPolicyConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation -func (s CustomErrorResponses) String() string { +func (s CreateOriginRequestPolicyInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CustomErrorResponses) GoString() string { +func (s CreateOriginRequestPolicyInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CustomErrorResponses) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CustomErrorResponses"} - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) - } - if s.Items != nil { - for i, v := range s.Items { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) - } +func (s *CreateOriginRequestPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateOriginRequestPolicyInput"} + if s.OriginRequestPolicyConfig == nil { + invalidParams.Add(request.NewErrParamRequired("OriginRequestPolicyConfig")) + } + if s.OriginRequestPolicyConfig != nil { + if err := s.OriginRequestPolicyConfig.Validate(); err != nil { + invalidParams.AddNested("OriginRequestPolicyConfig", err.(request.ErrInvalidParams)) } } @@ -6866,145 +8658,81 @@ func (s *CustomErrorResponses) Validate() error { return nil } -// SetItems sets the Items field's value. -func (s *CustomErrorResponses) SetItems(v []*CustomErrorResponse) *CustomErrorResponses { - s.Items = v +// SetOriginRequestPolicyConfig sets the OriginRequestPolicyConfig field's value. +func (s *CreateOriginRequestPolicyInput) SetOriginRequestPolicyConfig(v *OriginRequestPolicyConfig) *CreateOriginRequestPolicyInput { + s.OriginRequestPolicyConfig = v return s } -// SetQuantity sets the Quantity field's value. -func (s *CustomErrorResponses) SetQuantity(v int64) *CustomErrorResponses { - s.Quantity = &v - return s -} +type CreateOriginRequestPolicyOutput struct { + _ struct{} `type:"structure" payload:"OriginRequestPolicy"` -// A complex type that contains the list of Custom Headers for each origin. -type CustomHeaders struct { - _ struct{} `type:"structure"` + // The current version of the origin request policy. + ETag *string `location:"header" locationName:"ETag" type:"string"` - // Optional: A list that contains one OriginCustomHeader element for each custom - // header that you want CloudFront to forward to the origin. If Quantity is - // 0, omit Items. - Items []*OriginCustomHeader `locationNameList:"OriginCustomHeader" type:"list"` + // The fully qualified URI of the origin request policy just created. + Location *string `location:"header" locationName:"Location" type:"string"` - // The number of custom headers, if any, for this distribution. - // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // An origin request policy. + OriginRequestPolicy *OriginRequestPolicy `type:"structure"` } // String returns the string representation -func (s CustomHeaders) String() string { +func (s CreateOriginRequestPolicyOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CustomHeaders) GoString() string { +func (s CreateOriginRequestPolicyOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *CustomHeaders) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CustomHeaders"} - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) - } - if s.Items != nil { - for i, v := range s.Items { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetETag sets the ETag field's value. +func (s *CreateOriginRequestPolicyOutput) SetETag(v string) *CreateOriginRequestPolicyOutput { + s.ETag = &v + return s } -// SetItems sets the Items field's value. -func (s *CustomHeaders) SetItems(v []*OriginCustomHeader) *CustomHeaders { - s.Items = v +// SetLocation sets the Location field's value. +func (s *CreateOriginRequestPolicyOutput) SetLocation(v string) *CreateOriginRequestPolicyOutput { + s.Location = &v return s } -// SetQuantity sets the Quantity field's value. -func (s *CustomHeaders) SetQuantity(v int64) *CustomHeaders { - s.Quantity = &v +// SetOriginRequestPolicy sets the OriginRequestPolicy field's value. +func (s *CreateOriginRequestPolicyOutput) SetOriginRequestPolicy(v *OriginRequestPolicy) *CreateOriginRequestPolicyOutput { + s.OriginRequestPolicy = v return s } -// A custom origin or an Amazon S3 bucket configured as a website endpoint. -type CustomOriginConfig struct { - _ struct{} `type:"structure"` - - // The HTTP port the custom origin listens on. - // - // HTTPPort is a required field - HTTPPort *int64 `type:"integer" required:"true"` - - // The HTTPS port the custom origin listens on. - // - // 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"` +type CreatePublicKeyInput struct { + _ struct{} `locationName:"CreatePublicKeyRequest" type:"structure" payload:"PublicKeyConfig"` - // 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. + // The request to add a public key to CloudFront. // - // 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"` + // PublicKeyConfig is a required field + PublicKeyConfig *PublicKeyConfig `locationName:"PublicKeyConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation -func (s CustomOriginConfig) String() string { +func (s CreatePublicKeyInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CustomOriginConfig) GoString() string { +func (s CreatePublicKeyInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CustomOriginConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CustomOriginConfig"} - if s.HTTPPort == nil { - invalidParams.Add(request.NewErrParamRequired("HTTPPort")) +func (s *CreatePublicKeyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreatePublicKeyInput"} + if s.PublicKeyConfig == nil { + invalidParams.Add(request.NewErrParamRequired("PublicKeyConfig")) } - if s.HTTPSPort == nil { - invalidParams.Add(request.NewErrParamRequired("HTTPSPort")) - } - if s.OriginProtocolPolicy == nil { - invalidParams.Add(request.NewErrParamRequired("OriginProtocolPolicy")) - } - if s.OriginSslProtocols != nil { - if err := s.OriginSslProtocols.Validate(); err != nil { - invalidParams.AddNested("OriginSslProtocols", err.(request.ErrInvalidParams)) + if s.PublicKeyConfig != nil { + if err := s.PublicKeyConfig.Validate(); err != nil { + invalidParams.AddNested("PublicKeyConfig", err.(request.ErrInvalidParams)) } } @@ -7014,227 +8742,82 @@ func (s *CustomOriginConfig) Validate() error { return nil } -// SetHTTPPort sets the HTTPPort field's value. -func (s *CustomOriginConfig) SetHTTPPort(v int64) *CustomOriginConfig { - s.HTTPPort = &v +// SetPublicKeyConfig sets the PublicKeyConfig field's value. +func (s *CreatePublicKeyInput) SetPublicKeyConfig(v *PublicKeyConfig) *CreatePublicKeyInput { + s.PublicKeyConfig = v return s } -// SetHTTPSPort sets the HTTPSPort field's value. -func (s *CustomOriginConfig) SetHTTPSPort(v int64) *CustomOriginConfig { - s.HTTPSPort = &v - return s +type CreatePublicKeyOutput struct { + _ struct{} `type:"structure" payload:"PublicKey"` + + // The current version of the public key. For example: E2QWRUHAPOMQZL. + ETag *string `location:"header" locationName:"ETag" type:"string"` + + // The fully qualified URI of the new public key resource just created. + Location *string `location:"header" locationName:"Location" type:"string"` + + // Returned when you add a public key. + PublicKey *PublicKey `type:"structure"` } -// SetOriginKeepaliveTimeout sets the OriginKeepaliveTimeout field's value. -func (s *CustomOriginConfig) SetOriginKeepaliveTimeout(v int64) *CustomOriginConfig { - s.OriginKeepaliveTimeout = &v - return s +// String returns the string representation +func (s CreatePublicKeyOutput) String() string { + return awsutil.Prettify(s) } -// SetOriginProtocolPolicy sets the OriginProtocolPolicy field's value. -func (s *CustomOriginConfig) SetOriginProtocolPolicy(v string) *CustomOriginConfig { - s.OriginProtocolPolicy = &v - return s +// GoString returns the string representation +func (s CreatePublicKeyOutput) GoString() string { + return s.String() } -// SetOriginReadTimeout sets the OriginReadTimeout field's value. -func (s *CustomOriginConfig) SetOriginReadTimeout(v int64) *CustomOriginConfig { - s.OriginReadTimeout = &v +// SetETag sets the ETag field's value. +func (s *CreatePublicKeyOutput) SetETag(v string) *CreatePublicKeyOutput { + s.ETag = &v return s } -// SetOriginSslProtocols sets the OriginSslProtocols field's value. -func (s *CustomOriginConfig) SetOriginSslProtocols(v *OriginSslProtocols) *CustomOriginConfig { - s.OriginSslProtocols = v +// SetLocation sets the Location field's value. +func (s *CreatePublicKeyOutput) SetLocation(v string) *CreatePublicKeyOutput { + s.Location = &v return s } -// A complex type that describes the default cache behavior if you don't 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. -type DefaultCacheBehavior struct { - _ struct{} `type:"structure"` - - // A complex type that controls which HTTP methods CloudFront processes and - // forwards to your Amazon S3 bucket or your custom origin. There are three - // choices: - // - // * CloudFront forwards only GET and HEAD requests. - // - // * CloudFront forwards only GET, HEAD, and OPTIONS requests. - // - // * CloudFront forwards GET, HEAD, OPTIONS, PUT, PATCH, POST, and DELETE - // requests. - // - // If you pick the third choice, you may need to restrict access to your Amazon - // 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. - AllowedMethods *AllowedMethods `type:"structure"` - - // Whether you want CloudFront to automatically compress certain files for this - // cache behavior. If so, specify true; if not, specify false. For more information, - // see Serving Compressed Files (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html) - // in the Amazon CloudFront Developer Guide. - Compress *bool `type:"boolean"` - - // The default amount of time that you want objects to stay in CloudFront caches - // before CloudFront forwards another request to your origin to determine whether - // the object has been updated. The value that you specify applies only when - // your origin does not add HTTP headers such as Cache-Control max-age, Cache-Control - // s-maxage, and Expires to objects. For more information, see Managing How - // Long Content Stays in an Edge Cache (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) - // in the Amazon CloudFront Developer Guide. - DefaultTTL *int64 `type:"long"` - - // The value of ID for the field-level encryption configuration that you want - // CloudFront to use for encrypting specific fields of data for a cache behavior - // or for the default cache behavior in your distribution. - FieldLevelEncryptionId *string `type:"string"` - - // A complex type that specifies how CloudFront handles query strings, cookies, - // and HTTP headers. - // - // ForwardedValues is a required field - ForwardedValues *ForwardedValues `type:"structure" required:"true"` - - // A complex type that contains zero or more Lambda function associations for - // a cache behavior. - LambdaFunctionAssociations *LambdaFunctionAssociations `type:"structure"` - - // The maximum amount of time that you want objects to stay in CloudFront caches - // before CloudFront forwards another request to your origin to determine whether - // the object has been updated. The value that you specify applies only when - // your origin adds HTTP headers such as Cache-Control max-age, Cache-Control - // s-maxage, and Expires to objects. For more information, see Managing How - // Long Content Stays in an Edge Cache (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) - // in the Amazon CloudFront Developer Guide. - MaxTTL *int64 `type:"long"` - - // The minimum amount of time that you want objects to stay in CloudFront caches - // before CloudFront forwards another request to your origin to determine whether - // the object has been updated. For more information, see Managing How Long - // Content Stays in an Edge Cache (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) - // in the Amazon CloudFront Developer Guide. - // - // You must specify 0 for MinTTL if you configure CloudFront to forward all - // headers to your origin (under Headers, if you specify 1 for Quantity and - // * for Name). - // - // MinTTL is a required field - MinTTL *int64 `type:"long" required:"true"` - - // Indicates whether you want to distribute media files in the Microsoft Smooth - // Streaming format using the origin that is associated with this cache behavior. - // If so, specify true; if not, specify false. If you specify true for SmoothStreaming, - // you can still distribute other content using this cache behavior if the content - // matches the value of PathPattern. - SmoothStreaming *bool `type:"boolean"` - - // The value of ID for the origin that you want CloudFront to route requests - // to when a request matches the path pattern either for a cache behavior or - // for the default cache behavior in your distribution. - // - // TargetOriginId is a required field - TargetOriginId *string `type:"string" required:"true"` +// SetPublicKey sets the PublicKey field's value. +func (s *CreatePublicKeyOutput) SetPublicKey(v *PublicKey) *CreatePublicKeyOutput { + s.PublicKey = v + return s +} - // A complex type that specifies the AWS accounts, if any, that you want to - // allow to create signed URLs for private content. - // - // If you want to require signed URLs in requests for objects in the target - // origin that match the PathPattern for this cache behavior, specify true for - // Enabled, and specify the applicable values for Quantity and Items. For more - // information, see Serving Private Content through CloudFront (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html) - // in the Amazon CloudFront Developer Guide. - // - // If you don't want to require signed URLs in requests for objects that match - // PathPattern, specify false for Enabled and 0 for Quantity. Omit Items. - // - // To add, change, or remove one or more trusted signers, change Enabled to - // true (if it's currently false), change Quantity as applicable, and specify - // all of the trusted signers that you want to include in the updated distribution. - // - // TrustedSigners is a required field - TrustedSigners *TrustedSigners `type:"structure" required:"true"` +// The request to create a new streaming distribution. +type CreateStreamingDistributionInput struct { + _ struct{} `locationName:"CreateStreamingDistributionRequest" type:"structure" payload:"StreamingDistributionConfig"` - // The protocol that viewers can use to access the files in the origin specified - // by TargetOriginId when a request matches the path pattern in PathPattern. - // You can specify the following options: - // - // * allow-all: Viewers can use HTTP or HTTPS. - // - // * redirect-to-https: If a viewer submits an HTTP request, CloudFront returns - // an HTTP status code of 301 (Moved Permanently) to the viewer along with - // the HTTPS URL. The viewer then resubmits the request using the new URL. - // - // * https-only: If a viewer sends an HTTP request, CloudFront returns an - // HTTP status code of 403 (Forbidden). - // - // For more information about requiring the HTTPS protocol, see Using an HTTPS - // Connection to Access Your Objects (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html) - // in the Amazon CloudFront Developer Guide. - // - // The only way to guarantee that viewers retrieve an object that was fetched - // from the origin using HTTPS is never to use any other protocol to fetch the - // object. If you have recently changed from HTTP to HTTPS, we recommend that - // you clear your objects' cache because cached objects are protocol agnostic. - // That means that an edge location will return an object from the cache regardless - // of whether the current request protocol matches the protocol used previously. - // For more information, see Managing How Long Content Stays in an Edge Cache - // (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) - // in the Amazon CloudFront Developer Guide. + // The streaming distribution's configuration information. // - // ViewerProtocolPolicy is a required field - ViewerProtocolPolicy *string `type:"string" required:"true" enum:"ViewerProtocolPolicy"` + // StreamingDistributionConfig is a required field + StreamingDistributionConfig *StreamingDistributionConfig `locationName:"StreamingDistributionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation -func (s DefaultCacheBehavior) String() string { +func (s CreateStreamingDistributionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DefaultCacheBehavior) GoString() string { +func (s CreateStreamingDistributionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DefaultCacheBehavior) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DefaultCacheBehavior"} - if s.ForwardedValues == nil { - invalidParams.Add(request.NewErrParamRequired("ForwardedValues")) - } - if s.MinTTL == nil { - invalidParams.Add(request.NewErrParamRequired("MinTTL")) - } - if s.TargetOriginId == nil { - invalidParams.Add(request.NewErrParamRequired("TargetOriginId")) - } - if s.TrustedSigners == nil { - invalidParams.Add(request.NewErrParamRequired("TrustedSigners")) - } - if s.ViewerProtocolPolicy == nil { - invalidParams.Add(request.NewErrParamRequired("ViewerProtocolPolicy")) - } - if s.AllowedMethods != nil { - if err := s.AllowedMethods.Validate(); err != nil { - invalidParams.AddNested("AllowedMethods", err.(request.ErrInvalidParams)) - } - } - if s.ForwardedValues != nil { - if err := s.ForwardedValues.Validate(); err != nil { - invalidParams.AddNested("ForwardedValues", err.(request.ErrInvalidParams)) - } - } - if s.LambdaFunctionAssociations != nil { - if err := s.LambdaFunctionAssociations.Validate(); err != nil { - invalidParams.AddNested("LambdaFunctionAssociations", err.(request.ErrInvalidParams)) - } +func (s *CreateStreamingDistributionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateStreamingDistributionInput"} + if s.StreamingDistributionConfig == nil { + invalidParams.Add(request.NewErrParamRequired("StreamingDistributionConfig")) } - if s.TrustedSigners != nil { - if err := s.TrustedSigners.Validate(); err != nil { - invalidParams.AddNested("TrustedSigners", err.(request.ErrInvalidParams)) + if s.StreamingDistributionConfig != nil { + if err := s.StreamingDistributionConfig.Validate(); err != nil { + invalidParams.AddNested("StreamingDistributionConfig", err.(request.ErrInvalidParams)) } } @@ -7244,110 +8827,84 @@ func (s *DefaultCacheBehavior) Validate() error { return nil } -// SetAllowedMethods sets the AllowedMethods field's value. -func (s *DefaultCacheBehavior) SetAllowedMethods(v *AllowedMethods) *DefaultCacheBehavior { - s.AllowedMethods = v +// SetStreamingDistributionConfig sets the StreamingDistributionConfig field's value. +func (s *CreateStreamingDistributionInput) SetStreamingDistributionConfig(v *StreamingDistributionConfig) *CreateStreamingDistributionInput { + s.StreamingDistributionConfig = v return s } -// SetCompress sets the Compress field's value. -func (s *DefaultCacheBehavior) SetCompress(v bool) *DefaultCacheBehavior { - s.Compress = &v - return s +// The returned result of the corresponding request. +type CreateStreamingDistributionOutput struct { + _ struct{} `type:"structure" payload:"StreamingDistribution"` + + // The current version of the streaming distribution created. + ETag *string `location:"header" locationName:"ETag" type:"string"` + + // The fully qualified URI of the new streaming distribution resource just created. + Location *string `location:"header" locationName:"Location" type:"string"` + + // The streaming distribution's information. + StreamingDistribution *StreamingDistribution `type:"structure"` } -// SetDefaultTTL sets the DefaultTTL field's value. -func (s *DefaultCacheBehavior) SetDefaultTTL(v int64) *DefaultCacheBehavior { - s.DefaultTTL = &v - return s +// String returns the string representation +func (s CreateStreamingDistributionOutput) String() string { + return awsutil.Prettify(s) } -// SetFieldLevelEncryptionId sets the FieldLevelEncryptionId field's value. -func (s *DefaultCacheBehavior) SetFieldLevelEncryptionId(v string) *DefaultCacheBehavior { - s.FieldLevelEncryptionId = &v - return s -} - -// SetForwardedValues sets the ForwardedValues field's value. -func (s *DefaultCacheBehavior) SetForwardedValues(v *ForwardedValues) *DefaultCacheBehavior { - s.ForwardedValues = v - return s -} - -// SetLambdaFunctionAssociations sets the LambdaFunctionAssociations field's value. -func (s *DefaultCacheBehavior) SetLambdaFunctionAssociations(v *LambdaFunctionAssociations) *DefaultCacheBehavior { - s.LambdaFunctionAssociations = v - return s -} - -// SetMaxTTL sets the MaxTTL field's value. -func (s *DefaultCacheBehavior) SetMaxTTL(v int64) *DefaultCacheBehavior { - s.MaxTTL = &v - return s -} - -// SetMinTTL sets the MinTTL field's value. -func (s *DefaultCacheBehavior) SetMinTTL(v int64) *DefaultCacheBehavior { - s.MinTTL = &v - return s -} - -// SetSmoothStreaming sets the SmoothStreaming field's value. -func (s *DefaultCacheBehavior) SetSmoothStreaming(v bool) *DefaultCacheBehavior { - s.SmoothStreaming = &v - return s +// GoString returns the string representation +func (s CreateStreamingDistributionOutput) GoString() string { + return s.String() } -// SetTargetOriginId sets the TargetOriginId field's value. -func (s *DefaultCacheBehavior) SetTargetOriginId(v string) *DefaultCacheBehavior { - s.TargetOriginId = &v +// SetETag sets the ETag field's value. +func (s *CreateStreamingDistributionOutput) SetETag(v string) *CreateStreamingDistributionOutput { + s.ETag = &v return s } -// SetTrustedSigners sets the TrustedSigners field's value. -func (s *DefaultCacheBehavior) SetTrustedSigners(v *TrustedSigners) *DefaultCacheBehavior { - s.TrustedSigners = v +// SetLocation sets the Location field's value. +func (s *CreateStreamingDistributionOutput) SetLocation(v string) *CreateStreamingDistributionOutput { + s.Location = &v return s } -// SetViewerProtocolPolicy sets the ViewerProtocolPolicy field's value. -func (s *DefaultCacheBehavior) SetViewerProtocolPolicy(v string) *DefaultCacheBehavior { - s.ViewerProtocolPolicy = &v +// SetStreamingDistribution sets the StreamingDistribution field's value. +func (s *CreateStreamingDistributionOutput) SetStreamingDistribution(v *StreamingDistribution) *CreateStreamingDistributionOutput { + s.StreamingDistribution = v return s } -// Deletes a origin access identity. -type DeleteCloudFrontOriginAccessIdentityInput struct { - _ struct{} `locationName:"DeleteCloudFrontOriginAccessIdentityRequest" type:"structure"` +// The request to create a new streaming distribution with tags. +type CreateStreamingDistributionWithTagsInput struct { + _ struct{} `locationName:"CreateStreamingDistributionWithTagsRequest" type:"structure" payload:"StreamingDistributionConfigWithTags"` - // The origin access identity's ID. + // The streaming distribution's configuration information. // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // The value of the ETag header you received from a previous GET or PUT request. - // For example: E2QWRUHAPOMQZL. - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` + // StreamingDistributionConfigWithTags is a required field + StreamingDistributionConfigWithTags *StreamingDistributionConfigWithTags `locationName:"StreamingDistributionConfigWithTags" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation -func (s DeleteCloudFrontOriginAccessIdentityInput) String() string { +func (s CreateStreamingDistributionWithTagsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteCloudFrontOriginAccessIdentityInput) GoString() string { +func (s CreateStreamingDistributionWithTagsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteCloudFrontOriginAccessIdentityInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteCloudFrontOriginAccessIdentityInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) +func (s *CreateStreamingDistributionWithTagsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateStreamingDistributionWithTagsInput"} + if s.StreamingDistributionConfigWithTags == nil { + invalidParams.Add(request.NewErrParamRequired("StreamingDistributionConfigWithTags")) } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + if s.StreamingDistributionConfigWithTags != nil { + if err := s.StreamingDistributionConfigWithTags.Validate(); err != nil { + invalidParams.AddNested("StreamingDistributionConfigWithTags", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -7356,98 +8913,143 @@ func (s *DeleteCloudFrontOriginAccessIdentityInput) Validate() error { return nil } -// SetId sets the Id field's value. -func (s *DeleteCloudFrontOriginAccessIdentityInput) SetId(v string) *DeleteCloudFrontOriginAccessIdentityInput { - s.Id = &v +// SetStreamingDistributionConfigWithTags sets the StreamingDistributionConfigWithTags field's value. +func (s *CreateStreamingDistributionWithTagsInput) SetStreamingDistributionConfigWithTags(v *StreamingDistributionConfigWithTags) *CreateStreamingDistributionWithTagsInput { + s.StreamingDistributionConfigWithTags = v return s } -// SetIfMatch sets the IfMatch field's value. -func (s *DeleteCloudFrontOriginAccessIdentityInput) SetIfMatch(v string) *DeleteCloudFrontOriginAccessIdentityInput { - s.IfMatch = &v - return s -} +// The returned result of the corresponding request. +type CreateStreamingDistributionWithTagsOutput struct { + _ struct{} `type:"structure" payload:"StreamingDistribution"` -type DeleteCloudFrontOriginAccessIdentityOutput struct { - _ struct{} `type:"structure"` + // The current version of the distribution created. + ETag *string `location:"header" locationName:"ETag" type:"string"` + + // The fully qualified URI of the new streaming distribution resource just created. + Location *string `location:"header" locationName:"Location" type:"string"` + + // The streaming distribution's information. + StreamingDistribution *StreamingDistribution `type:"structure"` } // String returns the string representation -func (s DeleteCloudFrontOriginAccessIdentityOutput) String() string { +func (s CreateStreamingDistributionWithTagsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteCloudFrontOriginAccessIdentityOutput) GoString() string { +func (s CreateStreamingDistributionWithTagsOutput) GoString() string { return s.String() } -// This action deletes a web distribution. To delete a web distribution using -// the CloudFront API, perform the following steps. -// -// To delete a web distribution using the CloudFront API: -// -// Disable the web distribution -// -// Submit a GET Distribution Config request to get the current configuration -// and the Etag header for the distribution. -// -// Update the XML document that was returned in the response to your GET Distribution -// Config request to change the value of Enabled to false. -// -// Submit a PUT Distribution Config request to update the configuration for -// your distribution. In the request body, include the XML document that you -// updated in Step 3. Set the value of the HTTP If-Match header to the value -// of the ETag header that CloudFront returned when you submitted the GET Distribution -// Config request in Step 2. -// -// Review the response to the PUT Distribution Config request to confirm that -// the distribution was successfully disabled. -// -// Submit a GET Distribution request to confirm that your changes have propagated. -// When propagation is complete, the value of Status is Deployed. +// SetETag sets the ETag field's value. +func (s *CreateStreamingDistributionWithTagsOutput) SetETag(v string) *CreateStreamingDistributionWithTagsOutput { + s.ETag = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *CreateStreamingDistributionWithTagsOutput) SetLocation(v string) *CreateStreamingDistributionWithTagsOutput { + s.Location = &v + return s +} + +// SetStreamingDistribution sets the StreamingDistribution field's value. +func (s *CreateStreamingDistributionWithTagsOutput) SetStreamingDistribution(v *StreamingDistribution) *CreateStreamingDistributionWithTagsOutput { + s.StreamingDistribution = v + return s +} + +// A complex type that controls: // -// Submit a DELETE Distribution request. Set the value of the HTTP If-Match -// header to the value of the ETag header that CloudFront returned when you -// submitted the GET Distribution Config request in Step 6. +// * Whether CloudFront replaces HTTP status codes in the 4xx and 5xx range +// with custom error messages before returning the response to the viewer. // -// Review the response to your DELETE Distribution request to confirm that the -// distribution was successfully deleted. +// * How long CloudFront caches HTTP status codes in the 4xx and 5xx range. // -// For information about deleting a distribution using the CloudFront console, -// see Deleting a Distribution (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/HowToDeleteDistribution.html) +// For more information about custom error pages, see Customizing Error Responses +// (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html) // in the Amazon CloudFront Developer Guide. -type DeleteDistributionInput struct { - _ struct{} `locationName:"DeleteDistributionRequest" type:"structure"` +type CustomErrorResponse struct { + _ struct{} `type:"structure"` - // The distribution ID. + // The minimum amount of time, in seconds, that you want CloudFront to cache + // the HTTP status code specified in ErrorCode. When this time period has elapsed, + // CloudFront queries your origin to see whether the problem that caused the + // error has been resolved and the requested object is now available. // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + // For more information, see Customizing Error Responses (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html) + // in the Amazon CloudFront Developer Guide. + ErrorCachingMinTTL *int64 `type:"long"` - // The value of the ETag header that you received when you disabled the distribution. - // For example: E2QWRUHAPOMQZL. - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` + // The HTTP status code for which you want to specify a custom error page and/or + // a caching duration. + // + // ErrorCode is a required field + ErrorCode *int64 `type:"integer" required:"true"` + + // The HTTP status code that you want CloudFront to return to the viewer along + // with the custom error page. There are a variety of reasons that you might + // want CloudFront to return a status code different from the status code that + // your origin returned to CloudFront, for example: + // + // * Some Internet devices (some firewalls and corporate proxies, for example) + // intercept HTTP 4xx and 5xx and prevent the response from being returned + // to the viewer. If you substitute 200, the response typically won't be + // intercepted. + // + // * If you don't care about distinguishing among different client errors + // or server errors, you can specify 400 or 500 as the ResponseCode for all + // 4xx or 5xx errors. + // + // * You might want to return a 200 status code (OK) and static website so + // your customers don't know that your website is down. + // + // If you specify a value for ResponseCode, you must also specify a value for + // ResponsePagePath. + ResponseCode *string `type:"string"` + + // The path to the custom error page that you want CloudFront to return to a + // viewer when your origin returns the HTTP status code specified by ErrorCode, + // for example, /4xx-errors/403-forbidden.html. If you want to store your objects + // and your custom error pages in different locations, your distribution must + // include a cache behavior for which the following is true: + // + // * The value of PathPattern matches the path to your custom error messages. + // For example, suppose you saved custom error pages for 4xx errors in an + // Amazon S3 bucket in a directory named /4xx-errors. Your distribution must + // include a cache behavior for which the path pattern routes requests for + // your custom error pages to that location, for example, /4xx-errors/*. + // + // * The value of TargetOriginId specifies the value of the ID element for + // the origin that contains your custom error pages. + // + // If you specify a value for ResponsePagePath, you must also specify a value + // for ResponseCode. + // + // We recommend that you store custom error pages in an Amazon S3 bucket. If + // you store custom error pages on an HTTP server and the server starts to return + // 5xx errors, CloudFront can't get the files that you want to return to viewers + // because the origin server is unavailable. + ResponsePagePath *string `type:"string"` } // String returns the string representation -func (s DeleteDistributionInput) String() string { +func (s CustomErrorResponse) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDistributionInput) GoString() string { +func (s CustomErrorResponse) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDistributionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDistributionInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) +func (s *CustomErrorResponse) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CustomErrorResponse"} + if s.ErrorCode == nil { + invalidParams.Add(request.NewErrParamRequired("ErrorCode")) } if invalidParams.Len() > 0 { @@ -7456,63 +9058,80 @@ func (s *DeleteDistributionInput) Validate() error { return nil } -// SetId sets the Id field's value. -func (s *DeleteDistributionInput) SetId(v string) *DeleteDistributionInput { - s.Id = &v +// SetErrorCachingMinTTL sets the ErrorCachingMinTTL field's value. +func (s *CustomErrorResponse) SetErrorCachingMinTTL(v int64) *CustomErrorResponse { + s.ErrorCachingMinTTL = &v return s } -// SetIfMatch sets the IfMatch field's value. -func (s *DeleteDistributionInput) SetIfMatch(v string) *DeleteDistributionInput { - s.IfMatch = &v +// SetErrorCode sets the ErrorCode field's value. +func (s *CustomErrorResponse) SetErrorCode(v int64) *CustomErrorResponse { + s.ErrorCode = &v return s } -type DeleteDistributionOutput struct { - _ struct{} `type:"structure"` +// SetResponseCode sets the ResponseCode field's value. +func (s *CustomErrorResponse) SetResponseCode(v string) *CustomErrorResponse { + s.ResponseCode = &v + return s } -// String returns the string representation -func (s DeleteDistributionOutput) String() string { - return awsutil.Prettify(s) +// SetResponsePagePath sets the ResponsePagePath field's value. +func (s *CustomErrorResponse) SetResponsePagePath(v string) *CustomErrorResponse { + s.ResponsePagePath = &v + return s } -// GoString returns the string representation -func (s DeleteDistributionOutput) GoString() string { - return s.String() -} +// A complex type that controls: +// +// * Whether CloudFront replaces HTTP status codes in the 4xx and 5xx range +// with custom error messages before returning the response to the viewer. +// +// * How long CloudFront caches HTTP status codes in the 4xx and 5xx range. +// +// For more information about custom error pages, see Customizing Error Responses +// (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html) +// in the Amazon CloudFront Developer Guide. +type CustomErrorResponses struct { + _ struct{} `type:"structure"` -type DeleteFieldLevelEncryptionConfigInput struct { - _ struct{} `locationName:"DeleteFieldLevelEncryptionConfigRequest" type:"structure"` + // A complex type that contains a CustomErrorResponse element for each HTTP + // status code for which you want to specify a custom error page and/or a caching + // duration. + Items []*CustomErrorResponse `locationNameList:"CustomErrorResponse" type:"list"` - // The ID of the configuration you want to delete from CloudFront. + // The number of HTTP status codes for which you want to specify a custom error + // page and/or a caching duration. If Quantity is 0, you can omit Items. // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // The value of the ETag header that you received when retrieving the configuration - // identity to delete. For example: E2QWRUHAPOMQZL. - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s DeleteFieldLevelEncryptionConfigInput) String() string { +func (s CustomErrorResponses) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteFieldLevelEncryptionConfigInput) GoString() string { +func (s CustomErrorResponses) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteFieldLevelEncryptionConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteFieldLevelEncryptionConfigInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) +func (s *CustomErrorResponses) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CustomErrorResponses"} + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + if s.Items != nil { + for i, v := range s.Items { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -7521,63 +9140,58 @@ func (s *DeleteFieldLevelEncryptionConfigInput) Validate() error { return nil } -// SetId sets the Id field's value. -func (s *DeleteFieldLevelEncryptionConfigInput) SetId(v string) *DeleteFieldLevelEncryptionConfigInput { - s.Id = &v +// SetItems sets the Items field's value. +func (s *CustomErrorResponses) SetItems(v []*CustomErrorResponse) *CustomErrorResponses { + s.Items = v return s } -// SetIfMatch sets the IfMatch field's value. -func (s *DeleteFieldLevelEncryptionConfigInput) SetIfMatch(v string) *DeleteFieldLevelEncryptionConfigInput { - s.IfMatch = &v +// SetQuantity sets the Quantity field's value. +func (s *CustomErrorResponses) SetQuantity(v int64) *CustomErrorResponses { + s.Quantity = &v return s } -type DeleteFieldLevelEncryptionConfigOutput struct { +// A complex type that contains the list of Custom Headers for each origin. +type CustomHeaders struct { _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteFieldLevelEncryptionConfigOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteFieldLevelEncryptionConfigOutput) GoString() string { - return s.String() -} -type DeleteFieldLevelEncryptionProfileInput struct { - _ struct{} `locationName:"DeleteFieldLevelEncryptionProfileRequest" type:"structure"` + // Optional: A list that contains one OriginCustomHeader element for each custom + // header that you want CloudFront to forward to the origin. If Quantity is + // 0, omit Items. + Items []*OriginCustomHeader `locationNameList:"OriginCustomHeader" type:"list"` - // Request the ID of the profile you want to delete from CloudFront. + // The number of custom headers, if any, for this distribution. // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // The value of the ETag header that you received when retrieving the profile - // to delete. For example: E2QWRUHAPOMQZL. - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s DeleteFieldLevelEncryptionProfileInput) String() string { +func (s CustomHeaders) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteFieldLevelEncryptionProfileInput) GoString() string { +func (s CustomHeaders) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteFieldLevelEncryptionProfileInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteFieldLevelEncryptionProfileInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) +func (s *CustomHeaders) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CustomHeaders"} + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + if s.Items != nil { + for i, v := range s.Items { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -7586,63 +9200,102 @@ func (s *DeleteFieldLevelEncryptionProfileInput) Validate() error { return nil } -// SetId sets the Id field's value. -func (s *DeleteFieldLevelEncryptionProfileInput) SetId(v string) *DeleteFieldLevelEncryptionProfileInput { - s.Id = &v +// SetItems sets the Items field's value. +func (s *CustomHeaders) SetItems(v []*OriginCustomHeader) *CustomHeaders { + s.Items = v return s } -// SetIfMatch sets the IfMatch field's value. -func (s *DeleteFieldLevelEncryptionProfileInput) SetIfMatch(v string) *DeleteFieldLevelEncryptionProfileInput { - s.IfMatch = &v +// SetQuantity sets the Quantity field's value. +func (s *CustomHeaders) SetQuantity(v int64) *CustomHeaders { + s.Quantity = &v return s } -type DeleteFieldLevelEncryptionProfileOutput struct { +// A custom origin. A custom origin is any origin that is not an Amazon S3 bucket, +// with one exception. An Amazon S3 bucket that is configured with static website +// hosting (https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html) +// is a custom origin. +type CustomOriginConfig struct { _ struct{} `type:"structure"` -} -// String returns the string representation -func (s DeleteFieldLevelEncryptionProfileOutput) String() string { - return awsutil.Prettify(s) -} + // The HTTP port that CloudFront uses to connect to the origin. Specify the + // HTTP port that the origin listens on. + // + // HTTPPort is a required field + HTTPPort *int64 `type:"integer" required:"true"` -// GoString returns the string representation -func (s DeleteFieldLevelEncryptionProfileOutput) GoString() string { - return s.String() -} + // The HTTPS port that CloudFront uses to connect to the origin. Specify the + // HTTPS port that the origin listens on. + // + // HTTPSPort is a required field + HTTPSPort *int64 `type:"integer" required:"true"` -type DeletePublicKeyInput struct { - _ struct{} `locationName:"DeletePublicKeyRequest" type:"structure"` + // Specifies how long, in seconds, CloudFront persists its connection to the + // origin. The minimum timeout is 1 second, the maximum is 60 seconds, and the + // default (if you don’t specify otherwise) is 5 seconds. + // + // For more information, see Origin Keep-alive Timeout (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginKeepaliveTimeout) + // in the Amazon CloudFront Developer Guide. + OriginKeepaliveTimeout *int64 `type:"integer"` - // The ID of the public key you want to remove from CloudFront. + // Specifies the protocol (HTTP or HTTPS) that CloudFront uses to connect to + // the origin. Valid values are: // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + // * http-only – CloudFront always uses HTTP to connect to the origin. + // + // * match-viewer – CloudFront connects to the origin using the same protocol + // that the viewer used to connect to CloudFront. + // + // * https-only – CloudFront always uses HTTPS to connect to the origin. + // + // OriginProtocolPolicy is a required field + OriginProtocolPolicy *string `type:"string" required:"true" enum:"OriginProtocolPolicy"` - // The value of the ETag header that you received when retrieving the public - // key identity to delete. For example: E2QWRUHAPOMQZL. - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` + // Specifies how long, in seconds, CloudFront waits for a response from the + // origin. This is also known as the origin response timeout. The minimum timeout + // is 1 second, the maximum is 60 seconds, and the default (if you don’t specify + // otherwise) is 30 seconds. + // + // For more information, see Origin Response Timeout (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginResponseTimeout) + // in the Amazon CloudFront Developer Guide. + OriginReadTimeout *int64 `type:"integer"` + + // Specifies the minimum SSL/TLS protocol that CloudFront uses when connecting + // to your origin over HTTPS. Valid values include SSLv3, TLSv1, TLSv1.1, and + // TLSv1.2. + // + // For more information, see Minimum Origin SSL Protocol (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginSSLProtocols) + // in the Amazon CloudFront Developer Guide. + OriginSslProtocols *OriginSslProtocols `type:"structure"` } // String returns the string representation -func (s DeletePublicKeyInput) String() string { +func (s CustomOriginConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeletePublicKeyInput) GoString() string { +func (s CustomOriginConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeletePublicKeyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeletePublicKeyInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) +func (s *CustomOriginConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CustomOriginConfig"} + if s.HTTPPort == nil { + invalidParams.Add(request.NewErrParamRequired("HTTPPort")) } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + if s.HTTPSPort == nil { + invalidParams.Add(request.NewErrParamRequired("HTTPSPort")) + } + if s.OriginProtocolPolicy == nil { + invalidParams.Add(request.NewErrParamRequired("OriginProtocolPolicy")) + } + if s.OriginSslProtocols != nil { + if err := s.OriginSslProtocols.Validate(); err != nil { + invalidParams.AddNested("OriginSslProtocols", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -7651,64 +9304,2013 @@ func (s *DeletePublicKeyInput) Validate() error { return nil } -// SetId sets the Id field's value. -func (s *DeletePublicKeyInput) SetId(v string) *DeletePublicKeyInput { - s.Id = &v +// SetHTTPPort sets the HTTPPort field's value. +func (s *CustomOriginConfig) SetHTTPPort(v int64) *CustomOriginConfig { + s.HTTPPort = &v return s } -// SetIfMatch sets the IfMatch field's value. -func (s *DeletePublicKeyInput) SetIfMatch(v string) *DeletePublicKeyInput { - s.IfMatch = &v +// SetHTTPSPort sets the HTTPSPort field's value. +func (s *CustomOriginConfig) SetHTTPSPort(v int64) *CustomOriginConfig { + s.HTTPSPort = &v return s } -type DeletePublicKeyOutput struct { - _ struct{} `type:"structure"` +// SetOriginKeepaliveTimeout sets the OriginKeepaliveTimeout field's value. +func (s *CustomOriginConfig) SetOriginKeepaliveTimeout(v int64) *CustomOriginConfig { + s.OriginKeepaliveTimeout = &v + return s } -// String returns the string representation -func (s DeletePublicKeyOutput) String() string { - return awsutil.Prettify(s) +// SetOriginProtocolPolicy sets the OriginProtocolPolicy field's value. +func (s *CustomOriginConfig) SetOriginProtocolPolicy(v string) *CustomOriginConfig { + s.OriginProtocolPolicy = &v + return s } -// GoString returns the string representation -func (s DeletePublicKeyOutput) GoString() string { - return s.String() +// SetOriginReadTimeout sets the OriginReadTimeout field's value. +func (s *CustomOriginConfig) SetOriginReadTimeout(v int64) *CustomOriginConfig { + s.OriginReadTimeout = &v + return s } -// The request to delete a streaming distribution. -type DeleteStreamingDistributionInput struct { - _ struct{} `locationName:"DeleteStreamingDistributionRequest" type:"structure"` - - // The distribution ID. +// SetOriginSslProtocols sets the OriginSslProtocols field's value. +func (s *CustomOriginConfig) SetOriginSslProtocols(v *OriginSslProtocols) *CustomOriginConfig { + s.OriginSslProtocols = v + return s +} + +// A complex type that describes the default cache behavior if you don’t specify +// a CacheBehavior element or if request URLs don’t match any of the values +// of PathPattern in CacheBehavior elements. You must create exactly one default +// cache behavior. +type DefaultCacheBehavior struct { + _ struct{} `type:"structure"` + + // A complex type that controls which HTTP methods CloudFront processes and + // forwards to your Amazon S3 bucket or your custom origin. There are three + // choices: + // + // * CloudFront forwards only GET and HEAD requests. + // + // * CloudFront forwards only GET, HEAD, and OPTIONS requests. + // + // * CloudFront forwards GET, HEAD, OPTIONS, PUT, PATCH, POST, and DELETE + // requests. + // + // If you pick the third choice, you may need to restrict access to your Amazon + // 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. + AllowedMethods *AllowedMethods `type:"structure"` + + // The unique identifier of the cache policy that is attached to the default + // cache behavior. For more information, see Creating cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // or Using the managed cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html) + // in the Amazon CloudFront Developer Guide. + CachePolicyId *string `type:"string"` + + // Whether you want CloudFront to automatically compress certain files for this + // cache behavior. If so, specify true; if not, specify false. For more information, + // see Serving Compressed Files (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html) + // in the Amazon CloudFront Developer Guide. + Compress *bool `type:"boolean"` + + // This field is deprecated. We recommend that you use the DefaultTTL field + // in a cache policy instead of this field. For more information, see Creating + // cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // or Using the managed cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html) + // in the Amazon CloudFront Developer Guide. + // + // The default amount of time that you want objects to stay in CloudFront caches + // before CloudFront forwards another request to your origin to determine whether + // the object has been updated. The value that you specify applies only when + // your origin does not add HTTP headers such as Cache-Control max-age, Cache-Control + // s-maxage, and Expires to objects. For more information, see Managing How + // Long Content Stays in an Edge Cache (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) + // in the Amazon CloudFront Developer Guide. + // + // Deprecated: DefaultTTL has been deprecated + DefaultTTL *int64 `deprecated:"true" type:"long"` + + // The value of ID for the field-level encryption configuration that you want + // CloudFront to use for encrypting specific fields of data for the default + // cache behavior. + FieldLevelEncryptionId *string `type:"string"` + + // This field is deprecated. We recommend that you use a cache policy or an + // origin request policy instead of this field. For more information, see Working + // with policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/working-with-policies.html) + // in the Amazon CloudFront Developer Guide. + // + // If you want to include values in the cache key, use a cache policy. For more + // information, see Creating cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // or Using the managed cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html) + // in the Amazon CloudFront Developer Guide. + // + // If you want to send values to the origin but not include them in the cache + // key, use an origin request policy. For more information, see Creating origin + // request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) + // or Using the managed origin request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-origin-request-policies.html) + // in the Amazon CloudFront Developer Guide. + // + // A complex type that specifies how CloudFront handles query strings, cookies, + // and HTTP headers. + // + // Deprecated: ForwardedValues has been deprecated + ForwardedValues *ForwardedValues `deprecated:"true" type:"structure"` + + // A complex type that contains zero or more Lambda function associations for + // a cache behavior. + LambdaFunctionAssociations *LambdaFunctionAssociations `type:"structure"` + + // This field is deprecated. We recommend that you use the MaxTTL field in a + // cache policy instead of this field. For more information, see Creating cache + // policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // or Using the managed cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html) + // in the Amazon CloudFront Developer Guide. + // + // The maximum amount of time that you want objects to stay in CloudFront caches + // before CloudFront forwards another request to your origin to determine whether + // the object has been updated. The value that you specify applies only when + // your origin adds HTTP headers such as Cache-Control max-age, Cache-Control + // s-maxage, and Expires to objects. For more information, see Managing How + // Long Content Stays in an Edge Cache (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) + // in the Amazon CloudFront Developer Guide. + // + // Deprecated: MaxTTL has been deprecated + MaxTTL *int64 `deprecated:"true" type:"long"` + + // This field is deprecated. We recommend that you use the MinTTL field in a + // cache policy instead of this field. For more information, see Creating cache + // policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // or Using the managed cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html) + // in the Amazon CloudFront Developer Guide. + // + // The minimum amount of time that you want objects to stay in CloudFront caches + // before CloudFront forwards another request to your origin to determine whether + // the object has been updated. For more information, see Managing How Long + // Content Stays in an Edge Cache (Expiration) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) + // in the Amazon CloudFront Developer Guide. + // + // You must specify 0 for MinTTL if you configure CloudFront to forward all + // headers to your origin (under Headers, if you specify 1 for Quantity and + // * for Name). + // + // Deprecated: MinTTL has been deprecated + MinTTL *int64 `deprecated:"true" type:"long"` + + // The unique identifier of the origin request policy that is attached to the + // default cache behavior. For more information, see Creating origin request + // policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) + // or Using the managed origin request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-origin-request-policies.html) + // in the Amazon CloudFront Developer Guide. + OriginRequestPolicyId *string `type:"string"` + + // Indicates whether you want to distribute media files in the Microsoft Smooth + // Streaming format using the origin that is associated with this cache behavior. + // If so, specify true; if not, specify false. If you specify true for SmoothStreaming, + // you can still distribute other content using this cache behavior if the content + // matches the value of PathPattern. + SmoothStreaming *bool `type:"boolean"` + + // The value of ID for the origin that you want CloudFront to route requests + // to when they use the default cache behavior. + // + // TargetOriginId is a required field + TargetOriginId *string `type:"string" required:"true"` + + // A complex type that specifies the AWS accounts, if any, that you want to + // allow to create signed URLs for private content. + // + // If you want to require signed URLs in requests for objects in the target + // origin that match the PathPattern for this cache behavior, specify true for + // Enabled, and specify the applicable values for Quantity and Items. For more + // information, see Serving Private Content with Signed URLs and Signed Cookies + // (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html) + // in the Amazon CloudFront Developer Guide. + // + // If you don’t want to require signed URLs in requests for objects that match + // PathPattern, specify false for Enabled and 0 for Quantity. Omit Items. + // + // To add, change, or remove one or more trusted signers, change Enabled to + // true (if it’s currently false), change Quantity as applicable, and specify + // all of the trusted signers that you want to include in the updated distribution. + // + // TrustedSigners is a required field + TrustedSigners *TrustedSigners `type:"structure" required:"true"` + + // The protocol that viewers can use to access the files in the origin specified + // by TargetOriginId when a request matches the path pattern in PathPattern. + // You can specify the following options: + // + // * allow-all: Viewers can use HTTP or HTTPS. + // + // * redirect-to-https: If a viewer submits an HTTP request, CloudFront returns + // an HTTP status code of 301 (Moved Permanently) to the viewer along with + // the HTTPS URL. The viewer then resubmits the request using the new URL. + // + // * https-only: If a viewer sends an HTTP request, CloudFront returns an + // HTTP status code of 403 (Forbidden). + // + // For more information about requiring the HTTPS protocol, see Requiring HTTPS + // Between Viewers and CloudFront (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-https-viewers-to-cloudfront.html) + // in the Amazon CloudFront Developer Guide. + // + // The only way to guarantee that viewers retrieve an object that was fetched + // from the origin using HTTPS is never to use any other protocol to fetch the + // object. If you have recently changed from HTTP to HTTPS, we recommend that + // you clear your objects’ cache because cached objects are protocol agnostic. + // That means that an edge location will return an object from the cache regardless + // of whether the current request protocol matches the protocol used previously. + // For more information, see Managing Cache Expiration (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) + // in the Amazon CloudFront Developer Guide. + // + // ViewerProtocolPolicy is a required field + ViewerProtocolPolicy *string `type:"string" required:"true" enum:"ViewerProtocolPolicy"` +} + +// String returns the string representation +func (s DefaultCacheBehavior) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DefaultCacheBehavior) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DefaultCacheBehavior) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DefaultCacheBehavior"} + if s.TargetOriginId == nil { + invalidParams.Add(request.NewErrParamRequired("TargetOriginId")) + } + if s.TrustedSigners == nil { + invalidParams.Add(request.NewErrParamRequired("TrustedSigners")) + } + if s.ViewerProtocolPolicy == nil { + invalidParams.Add(request.NewErrParamRequired("ViewerProtocolPolicy")) + } + if s.AllowedMethods != nil { + if err := s.AllowedMethods.Validate(); err != nil { + invalidParams.AddNested("AllowedMethods", err.(request.ErrInvalidParams)) + } + } + if s.ForwardedValues != nil { + if err := s.ForwardedValues.Validate(); err != nil { + invalidParams.AddNested("ForwardedValues", err.(request.ErrInvalidParams)) + } + } + if s.LambdaFunctionAssociations != nil { + if err := s.LambdaFunctionAssociations.Validate(); err != nil { + invalidParams.AddNested("LambdaFunctionAssociations", err.(request.ErrInvalidParams)) + } + } + if s.TrustedSigners != nil { + if err := s.TrustedSigners.Validate(); err != nil { + invalidParams.AddNested("TrustedSigners", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAllowedMethods sets the AllowedMethods field's value. +func (s *DefaultCacheBehavior) SetAllowedMethods(v *AllowedMethods) *DefaultCacheBehavior { + s.AllowedMethods = v + return s +} + +// SetCachePolicyId sets the CachePolicyId field's value. +func (s *DefaultCacheBehavior) SetCachePolicyId(v string) *DefaultCacheBehavior { + s.CachePolicyId = &v + return s +} + +// SetCompress sets the Compress field's value. +func (s *DefaultCacheBehavior) SetCompress(v bool) *DefaultCacheBehavior { + s.Compress = &v + return s +} + +// SetDefaultTTL sets the DefaultTTL field's value. +func (s *DefaultCacheBehavior) SetDefaultTTL(v int64) *DefaultCacheBehavior { + s.DefaultTTL = &v + return s +} + +// SetFieldLevelEncryptionId sets the FieldLevelEncryptionId field's value. +func (s *DefaultCacheBehavior) SetFieldLevelEncryptionId(v string) *DefaultCacheBehavior { + s.FieldLevelEncryptionId = &v + return s +} + +// SetForwardedValues sets the ForwardedValues field's value. +func (s *DefaultCacheBehavior) SetForwardedValues(v *ForwardedValues) *DefaultCacheBehavior { + s.ForwardedValues = v + return s +} + +// SetLambdaFunctionAssociations sets the LambdaFunctionAssociations field's value. +func (s *DefaultCacheBehavior) SetLambdaFunctionAssociations(v *LambdaFunctionAssociations) *DefaultCacheBehavior { + s.LambdaFunctionAssociations = v + return s +} + +// SetMaxTTL sets the MaxTTL field's value. +func (s *DefaultCacheBehavior) SetMaxTTL(v int64) *DefaultCacheBehavior { + s.MaxTTL = &v + return s +} + +// SetMinTTL sets the MinTTL field's value. +func (s *DefaultCacheBehavior) SetMinTTL(v int64) *DefaultCacheBehavior { + s.MinTTL = &v + return s +} + +// SetOriginRequestPolicyId sets the OriginRequestPolicyId field's value. +func (s *DefaultCacheBehavior) SetOriginRequestPolicyId(v string) *DefaultCacheBehavior { + s.OriginRequestPolicyId = &v + return s +} + +// SetSmoothStreaming sets the SmoothStreaming field's value. +func (s *DefaultCacheBehavior) SetSmoothStreaming(v bool) *DefaultCacheBehavior { + s.SmoothStreaming = &v + return s +} + +// SetTargetOriginId sets the TargetOriginId field's value. +func (s *DefaultCacheBehavior) SetTargetOriginId(v string) *DefaultCacheBehavior { + s.TargetOriginId = &v + return s +} + +// SetTrustedSigners sets the TrustedSigners field's value. +func (s *DefaultCacheBehavior) SetTrustedSigners(v *TrustedSigners) *DefaultCacheBehavior { + s.TrustedSigners = v + return s +} + +// SetViewerProtocolPolicy sets the ViewerProtocolPolicy field's value. +func (s *DefaultCacheBehavior) SetViewerProtocolPolicy(v string) *DefaultCacheBehavior { + s.ViewerProtocolPolicy = &v + return s +} + +type DeleteCachePolicyInput struct { + _ struct{} `locationName:"DeleteCachePolicyRequest" type:"structure"` + + // The unique identifier for the cache policy that you are deleting. To get + // the identifier, you can use ListCachePolicies. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + + // The version of the cache policy that you are deleting. The version is the + // cache policy’s ETag value, which you can get using ListCachePolicies, GetCachePolicy, + // or GetCachePolicyConfig. + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` +} + +// String returns the string representation +func (s DeleteCachePolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCachePolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteCachePolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteCachePolicyInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *DeleteCachePolicyInput) SetId(v string) *DeleteCachePolicyInput { + s.Id = &v + return s +} + +// SetIfMatch sets the IfMatch field's value. +func (s *DeleteCachePolicyInput) SetIfMatch(v string) *DeleteCachePolicyInput { + s.IfMatch = &v + return s +} + +type DeleteCachePolicyOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteCachePolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCachePolicyOutput) GoString() string { + return s.String() +} + +// Deletes a origin access identity. +type DeleteCloudFrontOriginAccessIdentityInput struct { + _ struct{} `locationName:"DeleteCloudFrontOriginAccessIdentityRequest" type:"structure"` + + // The origin access identity's ID. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + + // The value of the ETag header you received from a previous GET or PUT request. + // For example: E2QWRUHAPOMQZL. + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` +} + +// String returns the string representation +func (s DeleteCloudFrontOriginAccessIdentityInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCloudFrontOriginAccessIdentityInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteCloudFrontOriginAccessIdentityInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteCloudFrontOriginAccessIdentityInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *DeleteCloudFrontOriginAccessIdentityInput) SetId(v string) *DeleteCloudFrontOriginAccessIdentityInput { + s.Id = &v + return s +} + +// SetIfMatch sets the IfMatch field's value. +func (s *DeleteCloudFrontOriginAccessIdentityInput) SetIfMatch(v string) *DeleteCloudFrontOriginAccessIdentityInput { + s.IfMatch = &v + return s +} + +type DeleteCloudFrontOriginAccessIdentityOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteCloudFrontOriginAccessIdentityOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCloudFrontOriginAccessIdentityOutput) GoString() string { + return s.String() +} + +// This action deletes a web distribution. To delete a web distribution using +// the CloudFront API, perform the following steps. +// +// To delete a web distribution using the CloudFront API: +// +// Disable the web distribution +// +// Submit a GET Distribution Config request to get the current configuration +// and the Etag header for the distribution. +// +// Update the XML document that was returned in the response to your GET Distribution +// Config request to change the value of Enabled to false. +// +// Submit a PUT Distribution Config request to update the configuration for +// your distribution. In the request body, include the XML document that you +// updated in Step 3. Set the value of the HTTP If-Match header to the value +// of the ETag header that CloudFront returned when you submitted the GET Distribution +// Config request in Step 2. +// +// Review the response to the PUT Distribution Config request to confirm that +// the distribution was successfully disabled. +// +// Submit a GET Distribution request to confirm that your changes have propagated. +// When propagation is complete, the value of Status is Deployed. +// +// Submit a DELETE Distribution request. Set the value of the HTTP If-Match +// header to the value of the ETag header that CloudFront returned when you +// submitted the GET Distribution Config request in Step 6. +// +// Review the response to your DELETE Distribution request to confirm that the +// distribution was successfully deleted. +// +// For information about deleting a distribution using the CloudFront console, +// see Deleting a Distribution (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/HowToDeleteDistribution.html) +// in the Amazon CloudFront Developer Guide. +type DeleteDistributionInput struct { + _ struct{} `locationName:"DeleteDistributionRequest" type:"structure"` + + // The distribution ID. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + + // The value of the ETag header that you received when you disabled the distribution. + // For example: E2QWRUHAPOMQZL. + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` +} + +// String returns the string representation +func (s DeleteDistributionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDistributionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteDistributionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDistributionInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *DeleteDistributionInput) SetId(v string) *DeleteDistributionInput { + s.Id = &v + return s +} + +// SetIfMatch sets the IfMatch field's value. +func (s *DeleteDistributionInput) SetIfMatch(v string) *DeleteDistributionInput { + s.IfMatch = &v + return s +} + +type DeleteDistributionOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteDistributionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDistributionOutput) GoString() string { + return s.String() +} + +type DeleteFieldLevelEncryptionConfigInput struct { + _ struct{} `locationName:"DeleteFieldLevelEncryptionConfigRequest" type:"structure"` + + // The ID of the configuration you want to delete from CloudFront. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + + // The value of the ETag header that you received when retrieving the configuration + // identity to delete. For example: E2QWRUHAPOMQZL. + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` +} + +// String returns the string representation +func (s DeleteFieldLevelEncryptionConfigInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteFieldLevelEncryptionConfigInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteFieldLevelEncryptionConfigInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteFieldLevelEncryptionConfigInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *DeleteFieldLevelEncryptionConfigInput) SetId(v string) *DeleteFieldLevelEncryptionConfigInput { + s.Id = &v + return s +} + +// SetIfMatch sets the IfMatch field's value. +func (s *DeleteFieldLevelEncryptionConfigInput) SetIfMatch(v string) *DeleteFieldLevelEncryptionConfigInput { + s.IfMatch = &v + return s +} + +type DeleteFieldLevelEncryptionConfigOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteFieldLevelEncryptionConfigOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteFieldLevelEncryptionConfigOutput) GoString() string { + return s.String() +} + +type DeleteFieldLevelEncryptionProfileInput struct { + _ struct{} `locationName:"DeleteFieldLevelEncryptionProfileRequest" type:"structure"` + + // Request the ID of the profile you want to delete from CloudFront. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + + // The value of the ETag header that you received when retrieving the profile + // to delete. For example: E2QWRUHAPOMQZL. + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` +} + +// String returns the string representation +func (s DeleteFieldLevelEncryptionProfileInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteFieldLevelEncryptionProfileInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteFieldLevelEncryptionProfileInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteFieldLevelEncryptionProfileInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *DeleteFieldLevelEncryptionProfileInput) SetId(v string) *DeleteFieldLevelEncryptionProfileInput { + s.Id = &v + return s +} + +// SetIfMatch sets the IfMatch field's value. +func (s *DeleteFieldLevelEncryptionProfileInput) SetIfMatch(v string) *DeleteFieldLevelEncryptionProfileInput { + s.IfMatch = &v + return s +} + +type DeleteFieldLevelEncryptionProfileOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteFieldLevelEncryptionProfileOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteFieldLevelEncryptionProfileOutput) GoString() string { + return s.String() +} + +type DeleteOriginRequestPolicyInput struct { + _ struct{} `locationName:"DeleteOriginRequestPolicyRequest" type:"structure"` + + // The unique identifier for the origin request policy that you are deleting. + // To get the identifier, you can use ListOriginRequestPolicies. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + + // The version of the origin request policy that you are deleting. The version + // is the origin request policy’s ETag value, which you can get using ListOriginRequestPolicies, + // GetOriginRequestPolicy, or GetOriginRequestPolicyConfig. + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` +} + +// String returns the string representation +func (s DeleteOriginRequestPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteOriginRequestPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteOriginRequestPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteOriginRequestPolicyInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *DeleteOriginRequestPolicyInput) SetId(v string) *DeleteOriginRequestPolicyInput { + s.Id = &v + return s +} + +// SetIfMatch sets the IfMatch field's value. +func (s *DeleteOriginRequestPolicyInput) SetIfMatch(v string) *DeleteOriginRequestPolicyInput { + s.IfMatch = &v + return s +} + +type DeleteOriginRequestPolicyOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteOriginRequestPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteOriginRequestPolicyOutput) GoString() string { + return s.String() +} + +type DeletePublicKeyInput struct { + _ struct{} `locationName:"DeletePublicKeyRequest" type:"structure"` + + // The ID of the public key you want to remove from CloudFront. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + + // The value of the ETag header that you received when retrieving the public + // key identity to delete. For example: E2QWRUHAPOMQZL. + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` +} + +// String returns the string representation +func (s DeletePublicKeyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeletePublicKeyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeletePublicKeyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeletePublicKeyInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *DeletePublicKeyInput) SetId(v string) *DeletePublicKeyInput { + s.Id = &v + return s +} + +// SetIfMatch sets the IfMatch field's value. +func (s *DeletePublicKeyInput) SetIfMatch(v string) *DeletePublicKeyInput { + s.IfMatch = &v + return s +} + +type DeletePublicKeyOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeletePublicKeyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeletePublicKeyOutput) GoString() string { + return s.String() +} + +// The request to delete a streaming distribution. +type DeleteStreamingDistributionInput struct { + _ struct{} `locationName:"DeleteStreamingDistributionRequest" type:"structure"` + + // The distribution ID. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + + // The value of the ETag header that you received when you disabled the streaming + // distribution. For example: E2QWRUHAPOMQZL. + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` +} + +// String returns the string representation +func (s DeleteStreamingDistributionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteStreamingDistributionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteStreamingDistributionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteStreamingDistributionInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *DeleteStreamingDistributionInput) SetId(v string) *DeleteStreamingDistributionInput { + s.Id = &v + return s +} + +// SetIfMatch sets the IfMatch field's value. +func (s *DeleteStreamingDistributionInput) SetIfMatch(v string) *DeleteStreamingDistributionInput { + s.IfMatch = &v + return s +} + +type DeleteStreamingDistributionOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteStreamingDistributionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteStreamingDistributionOutput) GoString() string { + return s.String() +} + +// A distribution tells CloudFront where you want content to be delivered from, +// and the details about how to track and manage content delivery. +type Distribution struct { + _ struct{} `type:"structure"` + + // The ARN (Amazon Resource Name) for the distribution. For example: arn:aws:cloudfront::123456789012:distribution/EDFDVBD632BHDS5, + // where 123456789012 is your AWS account ID. + // + // ARN is a required field + ARN *string `type:"string" required:"true"` + + // CloudFront automatically adds this element to the response only if you've + // set up the distribution to serve private content with signed URLs. The element + // lists the key pair IDs that CloudFront is aware of for each trusted signer. + // The Signer child element lists the AWS account number of the trusted signer + // (or an empty Self element if the signer is you). The Signer element also + // includes the IDs of any active key pairs associated with the trusted signer's + // AWS account. If no KeyPairId element appears for a Signer, that signer can't + // create working signed URLs. + // + // ActiveTrustedSigners is a required field + ActiveTrustedSigners *ActiveTrustedSigners `type:"structure" required:"true"` + + // AWS services in China customers must file for an Internet Content Provider + // (ICP) recordal if they want to serve content publicly on an alternate domain + // name, also known as a CNAME, that they've added to CloudFront. AliasICPRecordal + // provides the ICP recordal status for CNAMEs associated with distributions. + // + // For more information about ICP recordals, see Signup, Accounts, and Credentials + // (https://docs.amazonaws.cn/en_us/aws/latest/userguide/accounts-and-credentials.html) + // in Getting Started with AWS services in China. + AliasICPRecordals []*AliasICPRecordal `locationNameList:"AliasICPRecordal" type:"list"` + + // The current configuration information for the distribution. Send a GET request + // to the /CloudFront API version/distribution ID/config resource. + // + // DistributionConfig is a required field + DistributionConfig *DistributionConfig `type:"structure" required:"true"` + + // The domain name corresponding to the distribution, for example, d111111abcdef8.cloudfront.net. + // + // DomainName is a required field + DomainName *string `type:"string" required:"true"` + + // The identifier for the distribution. For example: EDFDVBD632BHDS5. + // + // Id is a required field + Id *string `type:"string" required:"true"` + + // The number of invalidation batches currently in progress. + // + // InProgressInvalidationBatches is a required field + InProgressInvalidationBatches *int64 `type:"integer" required:"true"` + + // The date and time the distribution was last modified. + // + // LastModifiedTime is a required field + LastModifiedTime *time.Time `type:"timestamp" required:"true"` + + // This response element indicates the current status of the distribution. When + // the status is Deployed, the distribution's information is fully propagated + // to all CloudFront edge locations. + // + // Status is a required field + Status *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s Distribution) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Distribution) GoString() string { + return s.String() +} + +// SetARN sets the ARN field's value. +func (s *Distribution) SetARN(v string) *Distribution { + s.ARN = &v + return s +} + +// SetActiveTrustedSigners sets the ActiveTrustedSigners field's value. +func (s *Distribution) SetActiveTrustedSigners(v *ActiveTrustedSigners) *Distribution { + s.ActiveTrustedSigners = v + return s +} + +// SetAliasICPRecordals sets the AliasICPRecordals field's value. +func (s *Distribution) SetAliasICPRecordals(v []*AliasICPRecordal) *Distribution { + s.AliasICPRecordals = v + return s +} + +// SetDistributionConfig sets the DistributionConfig field's value. +func (s *Distribution) SetDistributionConfig(v *DistributionConfig) *Distribution { + s.DistributionConfig = v + return s +} + +// SetDomainName sets the DomainName field's value. +func (s *Distribution) SetDomainName(v string) *Distribution { + s.DomainName = &v + return s +} + +// SetId sets the Id field's value. +func (s *Distribution) SetId(v string) *Distribution { + s.Id = &v + return s +} + +// SetInProgressInvalidationBatches sets the InProgressInvalidationBatches field's value. +func (s *Distribution) SetInProgressInvalidationBatches(v int64) *Distribution { + s.InProgressInvalidationBatches = &v + return s +} + +// SetLastModifiedTime sets the LastModifiedTime field's value. +func (s *Distribution) SetLastModifiedTime(v time.Time) *Distribution { + s.LastModifiedTime = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *Distribution) SetStatus(v string) *Distribution { + s.Status = &v + return s +} + +// A distribution configuration. +type DistributionConfig struct { + _ struct{} `type:"structure"` + + // A complex type that contains information about CNAMEs (alternate domain names), + // if any, for this distribution. + Aliases *Aliases `type:"structure"` + + // A complex type that contains zero or more CacheBehavior elements. + CacheBehaviors *CacheBehaviors `type:"structure"` + + // A unique value (for example, a date-time stamp) that ensures that the request + // can't be replayed. + // + // If the value of CallerReference is new (regardless of the content of the + // DistributionConfig object), CloudFront creates a new distribution. + // + // If CallerReference is a value that you already sent in a previous request + // to create a distribution, CloudFront returns a DistributionAlreadyExists + // error. + // + // CallerReference is a required field + CallerReference *string `type:"string" required:"true"` + + // Any comments you want to include about the distribution. + // + // If you don't want to specify a comment, include an empty Comment element. + // + // To delete an existing comment, update the distribution configuration and + // include an empty Comment element. + // + // To add or change a comment, update the distribution configuration and specify + // the new comment. + // + // Comment is a required field + Comment *string `type:"string" required:"true" sensitive:"true"` + + // A complex type that controls the following: + // + // * Whether CloudFront replaces HTTP status codes in the 4xx and 5xx range + // with custom error messages before returning the response to the viewer. + // + // * How long CloudFront caches HTTP status codes in the 4xx and 5xx range. + // + // For more information about custom error pages, see Customizing Error Responses + // (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html) + // in the Amazon CloudFront Developer Guide. + CustomErrorResponses *CustomErrorResponses `type:"structure"` + + // A complex type that describes the default cache behavior if you don't 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. + // + // DefaultCacheBehavior is a required field + DefaultCacheBehavior *DefaultCacheBehavior `type:"structure" required:"true"` + + // The object that you want CloudFront to request from your origin (for example, + // index.html) when a viewer requests the root URL for your distribution (http://www.example.com) + // instead of an object in your distribution (http://www.example.com/product-description.html). + // Specifying a default root object avoids exposing the contents of your distribution. + // + // Specify only the object name, for example, index.html. Don't add a / before + // the object name. + // + // If you don't want to specify a default root object when you create a distribution, + // include an empty DefaultRootObject element. + // + // To delete the default root object from an existing distribution, update the + // distribution configuration and include an empty DefaultRootObject element. + // + // To replace the default root object, update the distribution configuration + // and specify the new object. + // + // For more information about the default root object, see Creating a Default + // Root Object (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/DefaultRootObject.html) + // in the Amazon CloudFront Developer Guide. + DefaultRootObject *string `type:"string"` + + // From this field, you can enable or disable the selected distribution. + // + // Enabled is a required field + Enabled *bool `type:"boolean" required:"true"` + + // (Optional) Specify the maximum HTTP version that you want viewers to use + // to communicate with CloudFront. The default value for new web distributions + // is http2. Viewers that don't support HTTP/2 automatically use an earlier + // HTTP version. + // + // For viewers and CloudFront to use HTTP/2, viewers must support TLS 1.2 or + // later, and must support Server Name Identification (SNI). + // + // In general, configuring CloudFront to communicate with viewers using HTTP/2 + // reduces latency. You can improve performance by optimizing for HTTP/2. For + // more information, do an Internet search for "http/2 optimization." + HttpVersion *string `type:"string" enum:"HttpVersion"` + + // If you want CloudFront to respond to IPv6 DNS requests with an IPv6 address + // for your distribution, specify true. If you specify false, CloudFront responds + // to IPv6 DNS requests with the DNS response code NOERROR and with no IP addresses. + // This allows viewers to submit a second request, for an IPv4 address for your + // distribution. + // + // In general, you should enable IPv6 if you have users on IPv6 networks who + // want to access your content. However, if you're using signed URLs or signed + // cookies to restrict access to your content, and if you're using a custom + // policy that includes the IpAddress parameter to restrict the IP addresses + // that can access your content, don't enable IPv6. If you want to restrict + // access to some content by IP address and not restrict access to other content + // (or restrict access but not by IP address), you can create two distributions. + // For more information, see Creating a Signed URL Using a Custom Policy (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html) + // in the Amazon CloudFront Developer Guide. + // + // If you're using an Amazon Route 53 alias resource record set to route traffic + // to your CloudFront distribution, you need to create a second alias resource + // record set when both of the following are true: + // + // * You enable IPv6 for the distribution + // + // * You're using alternate domain names in the URLs for your objects + // + // For more information, see Routing Traffic to an Amazon CloudFront Web Distribution + // by Using Your Domain Name (https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-cloudfront-distribution.html) + // in the Amazon Route 53 Developer Guide. + // + // If you created a CNAME resource record set, either with Amazon Route 53 or + // with another DNS service, you don't need to make any changes. A CNAME record + // will route traffic to your distribution regardless of the IP address format + // of the viewer request. + IsIPV6Enabled *bool `type:"boolean"` + + // A complex type that controls whether access logs are written for the distribution. + // + // For more information about logging, see Access Logs (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html) + // in the Amazon CloudFront Developer Guide. + Logging *LoggingConfig `type:"structure"` + + // A complex type that contains information about origin groups for this distribution. + OriginGroups *OriginGroups `type:"structure"` + + // A complex type that contains information about origins for this distribution. + // + // Origins is a required field + Origins *Origins `type:"structure" required:"true"` + + // The price class that corresponds with the maximum price that you want to + // pay for CloudFront service. If you specify PriceClass_All, CloudFront responds + // to requests for your objects from all CloudFront edge locations. + // + // If you specify a price class other than PriceClass_All, CloudFront serves + // your objects from the CloudFront edge location that has the lowest latency + // among the edge locations in your price class. Viewers who are in or near + // regions that are excluded from your specified price class may encounter slower + // performance. + // + // For more information about price classes, see Choosing the Price Class for + // a CloudFront Distribution (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PriceClass.html) + // in the Amazon CloudFront Developer Guide. For information about CloudFront + // pricing, including how price classes (such as Price Class 100) map to CloudFront + // regions, see Amazon CloudFront Pricing (http://aws.amazon.com/cloudfront/pricing/). + // For price class information, scroll down to see the table at the bottom of + // the page. + PriceClass *string `type:"string" enum:"PriceClass"` + + // A complex type that identifies ways in which you want to restrict distribution + // of your content. + Restrictions *Restrictions `type:"structure"` + + // A complex type that determines the distribution’s SSL/TLS configuration + // for communicating with viewers. + ViewerCertificate *ViewerCertificate `type:"structure"` + + // A unique identifier that specifies the AWS WAF web ACL, if any, to associate + // with this distribution. To specify a web ACL created using the latest version + // of AWS WAF, use the ACL ARN, for example arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a. + // To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example + // 473e64fd-f30b-4765-81a0-62ad96dd167a. + // + // AWS WAF is a web application firewall that lets you monitor the HTTP and + // HTTPS requests that are forwarded to CloudFront, and lets you control access + // to your content. Based on conditions that you specify, such as the IP addresses + // that requests originate from or the values of query strings, CloudFront responds + // to requests either with the requested content or with an HTTP 403 status + // code (Forbidden). You can also configure CloudFront to return a custom error + // page when a request is blocked. For more information about AWS WAF, see the + // AWS WAF Developer Guide (https://docs.aws.amazon.com/waf/latest/developerguide/what-is-aws-waf.html). + WebACLId *string `type:"string"` +} + +// String returns the string representation +func (s DistributionConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DistributionConfig) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DistributionConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DistributionConfig"} + if s.CallerReference == nil { + invalidParams.Add(request.NewErrParamRequired("CallerReference")) + } + if s.Comment == nil { + invalidParams.Add(request.NewErrParamRequired("Comment")) + } + if s.DefaultCacheBehavior == nil { + invalidParams.Add(request.NewErrParamRequired("DefaultCacheBehavior")) + } + if s.Enabled == nil { + invalidParams.Add(request.NewErrParamRequired("Enabled")) + } + if s.Origins == nil { + invalidParams.Add(request.NewErrParamRequired("Origins")) + } + if s.Aliases != nil { + if err := s.Aliases.Validate(); err != nil { + invalidParams.AddNested("Aliases", err.(request.ErrInvalidParams)) + } + } + if s.CacheBehaviors != nil { + if err := s.CacheBehaviors.Validate(); err != nil { + invalidParams.AddNested("CacheBehaviors", err.(request.ErrInvalidParams)) + } + } + if s.CustomErrorResponses != nil { + if err := s.CustomErrorResponses.Validate(); err != nil { + invalidParams.AddNested("CustomErrorResponses", err.(request.ErrInvalidParams)) + } + } + if s.DefaultCacheBehavior != nil { + if err := s.DefaultCacheBehavior.Validate(); err != nil { + invalidParams.AddNested("DefaultCacheBehavior", err.(request.ErrInvalidParams)) + } + } + if s.Logging != nil { + if err := s.Logging.Validate(); err != nil { + invalidParams.AddNested("Logging", err.(request.ErrInvalidParams)) + } + } + if s.OriginGroups != nil { + if err := s.OriginGroups.Validate(); err != nil { + invalidParams.AddNested("OriginGroups", err.(request.ErrInvalidParams)) + } + } + if s.Origins != nil { + if err := s.Origins.Validate(); err != nil { + invalidParams.AddNested("Origins", err.(request.ErrInvalidParams)) + } + } + if s.Restrictions != nil { + if err := s.Restrictions.Validate(); err != nil { + invalidParams.AddNested("Restrictions", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAliases sets the Aliases field's value. +func (s *DistributionConfig) SetAliases(v *Aliases) *DistributionConfig { + s.Aliases = v + return s +} + +// SetCacheBehaviors sets the CacheBehaviors field's value. +func (s *DistributionConfig) SetCacheBehaviors(v *CacheBehaviors) *DistributionConfig { + s.CacheBehaviors = v + return s +} + +// SetCallerReference sets the CallerReference field's value. +func (s *DistributionConfig) SetCallerReference(v string) *DistributionConfig { + s.CallerReference = &v + return s +} + +// SetComment sets the Comment field's value. +func (s *DistributionConfig) SetComment(v string) *DistributionConfig { + s.Comment = &v + return s +} + +// SetCustomErrorResponses sets the CustomErrorResponses field's value. +func (s *DistributionConfig) SetCustomErrorResponses(v *CustomErrorResponses) *DistributionConfig { + s.CustomErrorResponses = v + return s +} + +// SetDefaultCacheBehavior sets the DefaultCacheBehavior field's value. +func (s *DistributionConfig) SetDefaultCacheBehavior(v *DefaultCacheBehavior) *DistributionConfig { + s.DefaultCacheBehavior = v + return s +} + +// SetDefaultRootObject sets the DefaultRootObject field's value. +func (s *DistributionConfig) SetDefaultRootObject(v string) *DistributionConfig { + s.DefaultRootObject = &v + return s +} + +// SetEnabled sets the Enabled field's value. +func (s *DistributionConfig) SetEnabled(v bool) *DistributionConfig { + s.Enabled = &v + return s +} + +// SetHttpVersion sets the HttpVersion field's value. +func (s *DistributionConfig) SetHttpVersion(v string) *DistributionConfig { + s.HttpVersion = &v + return s +} + +// SetIsIPV6Enabled sets the IsIPV6Enabled field's value. +func (s *DistributionConfig) SetIsIPV6Enabled(v bool) *DistributionConfig { + s.IsIPV6Enabled = &v + return s +} + +// SetLogging sets the Logging field's value. +func (s *DistributionConfig) SetLogging(v *LoggingConfig) *DistributionConfig { + s.Logging = v + return s +} + +// SetOriginGroups sets the OriginGroups field's value. +func (s *DistributionConfig) SetOriginGroups(v *OriginGroups) *DistributionConfig { + s.OriginGroups = v + return s +} + +// SetOrigins sets the Origins field's value. +func (s *DistributionConfig) SetOrigins(v *Origins) *DistributionConfig { + s.Origins = v + return s +} + +// SetPriceClass sets the PriceClass field's value. +func (s *DistributionConfig) SetPriceClass(v string) *DistributionConfig { + s.PriceClass = &v + return s +} + +// SetRestrictions sets the Restrictions field's value. +func (s *DistributionConfig) SetRestrictions(v *Restrictions) *DistributionConfig { + s.Restrictions = v + return s +} + +// SetViewerCertificate sets the ViewerCertificate field's value. +func (s *DistributionConfig) SetViewerCertificate(v *ViewerCertificate) *DistributionConfig { + s.ViewerCertificate = v + return s +} + +// SetWebACLId sets the WebACLId field's value. +func (s *DistributionConfig) SetWebACLId(v string) *DistributionConfig { + s.WebACLId = &v + return s +} + +// A distribution Configuration and a list of tags to be associated with the +// distribution. +type DistributionConfigWithTags struct { + _ struct{} `type:"structure"` + + // A distribution configuration. + // + // DistributionConfig is a required field + DistributionConfig *DistributionConfig `type:"structure" required:"true"` + + // A complex type that contains zero or more Tag elements. + // + // Tags is a required field + Tags *Tags `type:"structure" required:"true"` +} + +// String returns the string representation +func (s DistributionConfigWithTags) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DistributionConfigWithTags) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DistributionConfigWithTags) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DistributionConfigWithTags"} + if s.DistributionConfig == nil { + invalidParams.Add(request.NewErrParamRequired("DistributionConfig")) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + if s.DistributionConfig != nil { + if err := s.DistributionConfig.Validate(); err != nil { + invalidParams.AddNested("DistributionConfig", err.(request.ErrInvalidParams)) + } + } + if s.Tags != nil { + if err := s.Tags.Validate(); err != nil { + invalidParams.AddNested("Tags", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDistributionConfig sets the DistributionConfig field's value. +func (s *DistributionConfigWithTags) SetDistributionConfig(v *DistributionConfig) *DistributionConfigWithTags { + s.DistributionConfig = v + return s +} + +// SetTags sets the Tags field's value. +func (s *DistributionConfigWithTags) SetTags(v *Tags) *DistributionConfigWithTags { + s.Tags = v + return s +} + +// A list of distribution IDs. +type DistributionIdList struct { + _ struct{} `type:"structure"` + + // A flag that indicates whether more distribution IDs remain to be listed. + // If your results were truncated, you can make a subsequent request using the + // Marker request field to retrieve more distribution IDs in the list. + // + // IsTruncated is a required field + IsTruncated *bool `type:"boolean" required:"true"` + + // Contains the distribution IDs in the list. + Items []*string `locationNameList:"DistributionId" type:"list"` + + // The value provided in the Marker request field. + // + // Marker is a required field + Marker *string `type:"string" required:"true"` + + // The maximum number of distribution IDs requested. + // + // MaxItems is a required field + MaxItems *int64 `type:"integer" required:"true"` + + // Contains the value that you should use in the Marker field of a subsequent + // request to continue listing distribution IDs where you left off. + NextMarker *string `type:"string"` + + // The total number of distribution IDs returned in the response. + // + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` +} + +// String returns the string representation +func (s DistributionIdList) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DistributionIdList) GoString() string { + return s.String() +} + +// SetIsTruncated sets the IsTruncated field's value. +func (s *DistributionIdList) SetIsTruncated(v bool) *DistributionIdList { + s.IsTruncated = &v + return s +} + +// SetItems sets the Items field's value. +func (s *DistributionIdList) SetItems(v []*string) *DistributionIdList { + s.Items = v + return s +} + +// SetMarker sets the Marker field's value. +func (s *DistributionIdList) SetMarker(v string) *DistributionIdList { + s.Marker = &v + return s +} + +// SetMaxItems sets the MaxItems field's value. +func (s *DistributionIdList) SetMaxItems(v int64) *DistributionIdList { + s.MaxItems = &v + return s +} + +// SetNextMarker sets the NextMarker field's value. +func (s *DistributionIdList) SetNextMarker(v string) *DistributionIdList { + s.NextMarker = &v + return s +} + +// SetQuantity sets the Quantity field's value. +func (s *DistributionIdList) SetQuantity(v int64) *DistributionIdList { + s.Quantity = &v + return s +} + +// A distribution list. +type DistributionList struct { + _ struct{} `type:"structure"` + + // A flag that indicates whether more distributions remain to be listed. If + // your results were truncated, you can make a follow-up pagination request + // using the Marker request parameter to retrieve more distributions in the + // list. + // + // IsTruncated is a required field + IsTruncated *bool `type:"boolean" required:"true"` + + // A complex type that contains one DistributionSummary element for each distribution + // that was created by the current AWS account. + Items []*DistributionSummary `locationNameList:"DistributionSummary" type:"list"` + + // The value you provided for the Marker request parameter. + // + // Marker is a required field + Marker *string `type:"string" required:"true"` + + // The value you provided for the MaxItems request parameter. + // + // MaxItems is a required field + MaxItems *int64 `type:"integer" required:"true"` + + // If IsTruncated is true, this element is present and contains the value you + // can use for the Marker request parameter to continue listing your distributions + // where they left off. + NextMarker *string `type:"string"` + + // The number of distributions that were created by the current AWS account. + // + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` +} + +// String returns the string representation +func (s DistributionList) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DistributionList) GoString() string { + return s.String() +} + +// SetIsTruncated sets the IsTruncated field's value. +func (s *DistributionList) SetIsTruncated(v bool) *DistributionList { + s.IsTruncated = &v + return s +} + +// SetItems sets the Items field's value. +func (s *DistributionList) SetItems(v []*DistributionSummary) *DistributionList { + s.Items = v + return s +} + +// SetMarker sets the Marker field's value. +func (s *DistributionList) SetMarker(v string) *DistributionList { + s.Marker = &v + return s +} + +// SetMaxItems sets the MaxItems field's value. +func (s *DistributionList) SetMaxItems(v int64) *DistributionList { + s.MaxItems = &v + return s +} + +// SetNextMarker sets the NextMarker field's value. +func (s *DistributionList) SetNextMarker(v string) *DistributionList { + s.NextMarker = &v + return s +} + +// SetQuantity sets the Quantity field's value. +func (s *DistributionList) SetQuantity(v int64) *DistributionList { + s.Quantity = &v + return s +} + +// A summary of the information about a CloudFront distribution. +type DistributionSummary struct { + _ struct{} `type:"structure"` + + // The ARN (Amazon Resource Name) for the distribution. For example: arn:aws:cloudfront::123456789012:distribution/EDFDVBD632BHDS5, + // where 123456789012 is your AWS account ID. + // + // ARN is a required field + ARN *string `type:"string" required:"true"` + + // AWS services in China customers must file for an Internet Content Provider + // (ICP) recordal if they want to serve content publicly on an alternate domain + // name, also known as a CNAME, that they've added to CloudFront. AliasICPRecordal + // provides the ICP recordal status for CNAMEs associated with distributions. + // + // For more information about ICP recordals, see Signup, Accounts, and Credentials + // (https://docs.amazonaws.cn/en_us/aws/latest/userguide/accounts-and-credentials.html) + // in Getting Started with AWS services in China. + AliasICPRecordals []*AliasICPRecordal `locationNameList:"AliasICPRecordal" type:"list"` + + // A complex type that contains information about CNAMEs (alternate domain names), + // if any, for this distribution. + // + // Aliases is a required field + Aliases *Aliases `type:"structure" required:"true"` + + // A complex type that contains zero or more CacheBehavior elements. + // + // CacheBehaviors is a required field + CacheBehaviors *CacheBehaviors `type:"structure" required:"true"` + + // The comment originally specified when this distribution was created. + // + // Comment is a required field + Comment *string `type:"string" required:"true"` + + // A complex type that contains zero or more CustomErrorResponses elements. + // + // CustomErrorResponses is a required field + CustomErrorResponses *CustomErrorResponses `type:"structure" required:"true"` + + // A complex type that describes the default cache behavior if you don't 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. + // + // DefaultCacheBehavior is a required field + DefaultCacheBehavior *DefaultCacheBehavior `type:"structure" required:"true"` + + // The domain name that corresponds to the distribution, for example, d111111abcdef8.cloudfront.net. + // + // DomainName is a required field + DomainName *string `type:"string" required:"true"` + + // Whether the distribution is enabled to accept user requests for content. + // + // Enabled is a required field + Enabled *bool `type:"boolean" required:"true"` + + // Specify the maximum HTTP version that you want viewers to use to communicate + // with CloudFront. The default value for new web distributions is http2. Viewers + // that don't support HTTP/2 will automatically use an earlier version. + // + // HttpVersion is a required field + HttpVersion *string `type:"string" required:"true" enum:"HttpVersion"` + + // The identifier for the distribution. For example: EDFDVBD632BHDS5. + // + // Id is a required field + Id *string `type:"string" required:"true"` + + // Whether CloudFront responds to IPv6 DNS requests with an IPv6 address for + // your distribution. + // + // IsIPV6Enabled is a required field + IsIPV6Enabled *bool `type:"boolean" required:"true"` + + // The date and time the distribution was last modified. + // + // LastModifiedTime is a required field + LastModifiedTime *time.Time `type:"timestamp" required:"true"` + + // A complex type that contains information about origin groups for this distribution. + OriginGroups *OriginGroups `type:"structure"` + + // A complex type that contains information about origins for this distribution. + // + // Origins is a required field + Origins *Origins `type:"structure" required:"true"` + + // A complex type that contains information about price class for this streaming + // distribution. + // + // PriceClass is a required field + PriceClass *string `type:"string" required:"true" enum:"PriceClass"` + + // A complex type that identifies ways in which you want to restrict distribution + // of your content. + // + // Restrictions is a required field + Restrictions *Restrictions `type:"structure" required:"true"` + + // The current status of the distribution. When the status is Deployed, the + // distribution's information is propagated to all CloudFront edge locations. + // + // Status is a required field + Status *string `type:"string" required:"true"` + + // A complex type that determines the distribution’s SSL/TLS configuration + // for communicating with viewers. + // + // ViewerCertificate is a required field + ViewerCertificate *ViewerCertificate `type:"structure" required:"true"` + + // The Web ACL Id (if any) associated with the distribution. + // + // WebACLId is a required field + WebACLId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s DistributionSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DistributionSummary) GoString() string { + return s.String() +} + +// SetARN sets the ARN field's value. +func (s *DistributionSummary) SetARN(v string) *DistributionSummary { + s.ARN = &v + return s +} + +// SetAliasICPRecordals sets the AliasICPRecordals field's value. +func (s *DistributionSummary) SetAliasICPRecordals(v []*AliasICPRecordal) *DistributionSummary { + s.AliasICPRecordals = v + return s +} + +// SetAliases sets the Aliases field's value. +func (s *DistributionSummary) SetAliases(v *Aliases) *DistributionSummary { + s.Aliases = v + return s +} + +// SetCacheBehaviors sets the CacheBehaviors field's value. +func (s *DistributionSummary) SetCacheBehaviors(v *CacheBehaviors) *DistributionSummary { + s.CacheBehaviors = v + return s +} + +// SetComment sets the Comment field's value. +func (s *DistributionSummary) SetComment(v string) *DistributionSummary { + s.Comment = &v + return s +} + +// SetCustomErrorResponses sets the CustomErrorResponses field's value. +func (s *DistributionSummary) SetCustomErrorResponses(v *CustomErrorResponses) *DistributionSummary { + s.CustomErrorResponses = v + return s +} + +// SetDefaultCacheBehavior sets the DefaultCacheBehavior field's value. +func (s *DistributionSummary) SetDefaultCacheBehavior(v *DefaultCacheBehavior) *DistributionSummary { + s.DefaultCacheBehavior = v + return s +} + +// SetDomainName sets the DomainName field's value. +func (s *DistributionSummary) SetDomainName(v string) *DistributionSummary { + s.DomainName = &v + return s +} + +// SetEnabled sets the Enabled field's value. +func (s *DistributionSummary) SetEnabled(v bool) *DistributionSummary { + s.Enabled = &v + return s +} + +// SetHttpVersion sets the HttpVersion field's value. +func (s *DistributionSummary) SetHttpVersion(v string) *DistributionSummary { + s.HttpVersion = &v + return s +} + +// SetId sets the Id field's value. +func (s *DistributionSummary) SetId(v string) *DistributionSummary { + s.Id = &v + return s +} + +// SetIsIPV6Enabled sets the IsIPV6Enabled field's value. +func (s *DistributionSummary) SetIsIPV6Enabled(v bool) *DistributionSummary { + s.IsIPV6Enabled = &v + return s +} + +// SetLastModifiedTime sets the LastModifiedTime field's value. +func (s *DistributionSummary) SetLastModifiedTime(v time.Time) *DistributionSummary { + s.LastModifiedTime = &v + return s +} + +// SetOriginGroups sets the OriginGroups field's value. +func (s *DistributionSummary) SetOriginGroups(v *OriginGroups) *DistributionSummary { + s.OriginGroups = v + return s +} + +// SetOrigins sets the Origins field's value. +func (s *DistributionSummary) SetOrigins(v *Origins) *DistributionSummary { + s.Origins = v + return s +} + +// SetPriceClass sets the PriceClass field's value. +func (s *DistributionSummary) SetPriceClass(v string) *DistributionSummary { + s.PriceClass = &v + return s +} + +// SetRestrictions sets the Restrictions field's value. +func (s *DistributionSummary) SetRestrictions(v *Restrictions) *DistributionSummary { + s.Restrictions = v + return s +} + +// SetStatus sets the Status field's value. +func (s *DistributionSummary) SetStatus(v string) *DistributionSummary { + s.Status = &v + return s +} + +// SetViewerCertificate sets the ViewerCertificate field's value. +func (s *DistributionSummary) SetViewerCertificate(v *ViewerCertificate) *DistributionSummary { + s.ViewerCertificate = v + return s +} + +// SetWebACLId sets the WebACLId field's value. +func (s *DistributionSummary) SetWebACLId(v string) *DistributionSummary { + s.WebACLId = &v + return s +} + +// Complex data type for field-level encryption profiles that includes all of +// the encryption entities. +type EncryptionEntities struct { + _ struct{} `type:"structure"` + + // An array of field patterns in a field-level encryption content type-profile + // mapping. + Items []*EncryptionEntity `locationNameList:"EncryptionEntity" type:"list"` + + // Number of field pattern items in a field-level encryption content type-profile + // mapping. + // + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` +} + +// String returns the string representation +func (s EncryptionEntities) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EncryptionEntities) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *EncryptionEntities) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "EncryptionEntities"} + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) + } + if s.Items != nil { + for i, v := range s.Items { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetItems sets the Items field's value. +func (s *EncryptionEntities) SetItems(v []*EncryptionEntity) *EncryptionEntities { + s.Items = v + return s +} + +// SetQuantity sets the Quantity field's value. +func (s *EncryptionEntities) SetQuantity(v int64) *EncryptionEntities { + s.Quantity = &v + return s +} + +// Complex data type for field-level encryption profiles that includes the encryption +// key and field pattern specifications. +type EncryptionEntity struct { + _ struct{} `type:"structure"` + + // Field patterns in a field-level encryption content type profile specify the + // fields that you want to be encrypted. You can provide the full field name, + // or any beginning characters followed by a wildcard (*). You can't overlap + // field patterns. For example, you can't have both ABC* and AB*. Note that + // field patterns are case-sensitive. // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + // FieldPatterns is a required field + FieldPatterns *FieldPatterns `type:"structure" required:"true"` - // The value of the ETag header that you received when you disabled the streaming - // distribution. For example: E2QWRUHAPOMQZL. - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` + // The provider associated with the public key being used for encryption. This + // value must also be provided with the private key for applications to be able + // to decrypt data. + // + // ProviderId is a required field + ProviderId *string `type:"string" required:"true"` + + // The public key associated with a set of field-level encryption patterns, + // to be used when encrypting the fields that match the patterns. + // + // PublicKeyId is a required field + PublicKeyId *string `type:"string" required:"true"` } // String returns the string representation -func (s DeleteStreamingDistributionInput) String() string { +func (s EncryptionEntity) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteStreamingDistributionInput) GoString() string { +func (s EncryptionEntity) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteStreamingDistributionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteStreamingDistributionInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) +func (s *EncryptionEntity) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "EncryptionEntity"} + if s.FieldPatterns == nil { + invalidParams.Add(request.NewErrParamRequired("FieldPatterns")) } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + if s.ProviderId == nil { + invalidParams.Add(request.NewErrParamRequired("ProviderId")) + } + if s.PublicKeyId == nil { + invalidParams.Add(request.NewErrParamRequired("PublicKeyId")) + } + if s.FieldPatterns != nil { + if err := s.FieldPatterns.Validate(); err != nil { + invalidParams.AddNested("FieldPatterns", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -7717,417 +11319,314 @@ func (s *DeleteStreamingDistributionInput) Validate() error { return nil } -// SetId sets the Id field's value. -func (s *DeleteStreamingDistributionInput) SetId(v string) *DeleteStreamingDistributionInput { - s.Id = &v +// SetFieldPatterns sets the FieldPatterns field's value. +func (s *EncryptionEntity) SetFieldPatterns(v *FieldPatterns) *EncryptionEntity { + s.FieldPatterns = v return s } -// SetIfMatch sets the IfMatch field's value. -func (s *DeleteStreamingDistributionInput) SetIfMatch(v string) *DeleteStreamingDistributionInput { - s.IfMatch = &v +// SetProviderId sets the ProviderId field's value. +func (s *EncryptionEntity) SetProviderId(v string) *EncryptionEntity { + s.ProviderId = &v return s } -type DeleteStreamingDistributionOutput struct { +// SetPublicKeyId sets the PublicKeyId field's value. +func (s *EncryptionEntity) SetPublicKeyId(v string) *EncryptionEntity { + s.PublicKeyId = &v + return s +} + +// A complex data type that includes the profile configurations and other options +// specified for field-level encryption. +type FieldLevelEncryption struct { _ struct{} `type:"structure"` + + // A complex data type that includes the profile configurations specified for + // field-level encryption. + // + // FieldLevelEncryptionConfig is a required field + FieldLevelEncryptionConfig *FieldLevelEncryptionConfig `type:"structure" required:"true"` + + // The configuration ID for a field-level encryption configuration which includes + // a set of profiles that specify certain selected data fields to be encrypted + // by specific public keys. + // + // Id is a required field + Id *string `type:"string" required:"true"` + + // The last time the field-level encryption configuration was changed. + // + // LastModifiedTime is a required field + LastModifiedTime *time.Time `type:"timestamp" required:"true"` } // String returns the string representation -func (s DeleteStreamingDistributionOutput) String() string { +func (s FieldLevelEncryption) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteStreamingDistributionOutput) GoString() string { +func (s FieldLevelEncryption) GoString() string { return s.String() } -// A distribution tells CloudFront where you want content to be delivered from, -// and the details about how to track and manage content delivery. -type Distribution struct { +// SetFieldLevelEncryptionConfig sets the FieldLevelEncryptionConfig field's value. +func (s *FieldLevelEncryption) SetFieldLevelEncryptionConfig(v *FieldLevelEncryptionConfig) *FieldLevelEncryption { + s.FieldLevelEncryptionConfig = v + return s +} + +// SetId sets the Id field's value. +func (s *FieldLevelEncryption) SetId(v string) *FieldLevelEncryption { + s.Id = &v + return s +} + +// SetLastModifiedTime sets the LastModifiedTime field's value. +func (s *FieldLevelEncryption) SetLastModifiedTime(v time.Time) *FieldLevelEncryption { + s.LastModifiedTime = &v + return s +} + +// A complex data type that includes the profile configurations specified for +// field-level encryption. +type FieldLevelEncryptionConfig struct { _ struct{} `type:"structure"` - // The ARN (Amazon Resource Name) for the distribution. For example: arn:aws:cloudfront::123456789012:distribution/EDFDVBD632BHDS5, - // where 123456789012 is your AWS account ID. + // A unique number that ensures the request can't be replayed. // - // ARN is a required field - ARN *string `type:"string" required:"true"` + // CallerReference is a required field + CallerReference *string `type:"string" required:"true"` - // CloudFront automatically adds this element to the response only if you've - // set up the distribution to serve private content with signed URLs. The element - // lists the key pair IDs that CloudFront is aware of for each trusted signer. - // The Signer child element lists the AWS account number of the trusted signer - // (or an empty Self element if the signer is you). The Signer element also - // includes the IDs of any active key pairs associated with the trusted signer's - // AWS account. If no KeyPairId element appears for a Signer, that signer can't - // create working signed URLs. - // - // ActiveTrustedSigners is a required field - ActiveTrustedSigners *ActiveTrustedSigners `type:"structure" required:"true"` + // An optional comment about the configuration. + Comment *string `type:"string"` - // AWS services in China customers must file for an Internet Content Provider - // (ICP) recordal if they want to serve content publicly on an alternate domain - // name, also known as a CNAME, that they've added to CloudFront. AliasICPRecordal - // provides the ICP recordal status for CNAMEs associated with distributions. - // - // For more information about ICP recordals, see Signup, Accounts, and Credentials - // (https://docs.amazonaws.cn/en_us/aws/latest/userguide/accounts-and-credentials.html) - // in Getting Started with AWS services in China. - AliasICPRecordals []*AliasICPRecordal `locationNameList:"AliasICPRecordal" type:"list"` + // A complex data type that specifies when to forward content if a content type + // isn't recognized and profiles to use as by default in a request if a query + // argument doesn't specify a profile to use. + ContentTypeProfileConfig *ContentTypeProfileConfig `type:"structure"` - // The current configuration information for the distribution. Send a GET request - // to the /CloudFront API version/distribution ID/config resource. - // - // DistributionConfig is a required field - DistributionConfig *DistributionConfig `type:"structure" required:"true"` + // A complex data type that specifies when to forward content if a profile isn't + // found and the profile that can be provided as a query argument in a request. + QueryArgProfileConfig *QueryArgProfileConfig `type:"structure"` +} - // The domain name corresponding to the distribution, for example, d111111abcdef8.cloudfront.net. - // - // DomainName is a required field - DomainName *string `type:"string" required:"true"` +// String returns the string representation +func (s FieldLevelEncryptionConfig) String() string { + return awsutil.Prettify(s) +} - // The identifier for the distribution. For example: EDFDVBD632BHDS5. - // - // Id is a required field - Id *string `type:"string" required:"true"` +// GoString returns the string representation +func (s FieldLevelEncryptionConfig) GoString() string { + return s.String() +} - // The number of invalidation batches currently in progress. - // - // InProgressInvalidationBatches is a required field - InProgressInvalidationBatches *int64 `type:"integer" required:"true"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *FieldLevelEncryptionConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "FieldLevelEncryptionConfig"} + if s.CallerReference == nil { + invalidParams.Add(request.NewErrParamRequired("CallerReference")) + } + if s.ContentTypeProfileConfig != nil { + if err := s.ContentTypeProfileConfig.Validate(); err != nil { + invalidParams.AddNested("ContentTypeProfileConfig", err.(request.ErrInvalidParams)) + } + } + if s.QueryArgProfileConfig != nil { + if err := s.QueryArgProfileConfig.Validate(); err != nil { + invalidParams.AddNested("QueryArgProfileConfig", err.(request.ErrInvalidParams)) + } + } - // The date and time the distribution was last modified. + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCallerReference sets the CallerReference field's value. +func (s *FieldLevelEncryptionConfig) SetCallerReference(v string) *FieldLevelEncryptionConfig { + s.CallerReference = &v + return s +} + +// SetComment sets the Comment field's value. +func (s *FieldLevelEncryptionConfig) SetComment(v string) *FieldLevelEncryptionConfig { + s.Comment = &v + return s +} + +// SetContentTypeProfileConfig sets the ContentTypeProfileConfig field's value. +func (s *FieldLevelEncryptionConfig) SetContentTypeProfileConfig(v *ContentTypeProfileConfig) *FieldLevelEncryptionConfig { + s.ContentTypeProfileConfig = v + return s +} + +// SetQueryArgProfileConfig sets the QueryArgProfileConfig field's value. +func (s *FieldLevelEncryptionConfig) SetQueryArgProfileConfig(v *QueryArgProfileConfig) *FieldLevelEncryptionConfig { + s.QueryArgProfileConfig = v + return s +} + +// List of field-level encrpytion configurations. +type FieldLevelEncryptionList struct { + _ struct{} `type:"structure"` + + // An array of field-level encryption items. + Items []*FieldLevelEncryptionSummary `locationNameList:"FieldLevelEncryptionSummary" type:"list"` + + // The maximum number of elements you want in the response body. // - // LastModifiedTime is a required field - LastModifiedTime *time.Time `type:"timestamp" required:"true"` + // MaxItems is a required field + MaxItems *int64 `type:"integer" required:"true"` - // This response element indicates the current status of the distribution. When - // the status is Deployed, the distribution's information is fully propagated - // to all CloudFront edge locations. + // If there are more elements to be listed, this element is present and contains + // the value that you can use for the Marker request parameter to continue listing + // your configurations where you left off. + NextMarker *string `type:"string"` + + // The number of field-level encryption items. // - // Status is a required field - Status *string `type:"string" required:"true"` + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s Distribution) String() string { +func (s FieldLevelEncryptionList) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Distribution) GoString() string { +func (s FieldLevelEncryptionList) GoString() string { return s.String() } -// SetARN sets the ARN field's value. -func (s *Distribution) SetARN(v string) *Distribution { - s.ARN = &v +// SetItems sets the Items field's value. +func (s *FieldLevelEncryptionList) SetItems(v []*FieldLevelEncryptionSummary) *FieldLevelEncryptionList { + s.Items = v return s } -// SetActiveTrustedSigners sets the ActiveTrustedSigners field's value. -func (s *Distribution) SetActiveTrustedSigners(v *ActiveTrustedSigners) *Distribution { - s.ActiveTrustedSigners = v +// SetMaxItems sets the MaxItems field's value. +func (s *FieldLevelEncryptionList) SetMaxItems(v int64) *FieldLevelEncryptionList { + s.MaxItems = &v return s } -// SetAliasICPRecordals sets the AliasICPRecordals field's value. -func (s *Distribution) SetAliasICPRecordals(v []*AliasICPRecordal) *Distribution { - s.AliasICPRecordals = v +// SetNextMarker sets the NextMarker field's value. +func (s *FieldLevelEncryptionList) SetNextMarker(v string) *FieldLevelEncryptionList { + s.NextMarker = &v return s } -// SetDistributionConfig sets the DistributionConfig field's value. -func (s *Distribution) SetDistributionConfig(v *DistributionConfig) *Distribution { - s.DistributionConfig = v +// SetQuantity sets the Quantity field's value. +func (s *FieldLevelEncryptionList) SetQuantity(v int64) *FieldLevelEncryptionList { + s.Quantity = &v return s } -// SetDomainName sets the DomainName field's value. -func (s *Distribution) SetDomainName(v string) *Distribution { - s.DomainName = &v - return s +// A complex data type for field-level encryption profiles. +type FieldLevelEncryptionProfile struct { + _ struct{} `type:"structure"` + + // A complex data type that includes the profile name and the encryption entities + // for the field-level encryption profile. + // + // FieldLevelEncryptionProfileConfig is a required field + FieldLevelEncryptionProfileConfig *FieldLevelEncryptionProfileConfig `type:"structure" required:"true"` + + // The ID for a field-level encryption profile configuration which includes + // a set of profiles that specify certain selected data fields to be encrypted + // by specific public keys. + // + // Id is a required field + Id *string `type:"string" required:"true"` + + // The last time the field-level encryption profile was updated. + // + // LastModifiedTime is a required field + LastModifiedTime *time.Time `type:"timestamp" required:"true"` } -// SetId sets the Id field's value. -func (s *Distribution) SetId(v string) *Distribution { - s.Id = &v - return s +// String returns the string representation +func (s FieldLevelEncryptionProfile) String() string { + return awsutil.Prettify(s) } -// SetInProgressInvalidationBatches sets the InProgressInvalidationBatches field's value. -func (s *Distribution) SetInProgressInvalidationBatches(v int64) *Distribution { - s.InProgressInvalidationBatches = &v +// GoString returns the string representation +func (s FieldLevelEncryptionProfile) GoString() string { + return s.String() +} + +// SetFieldLevelEncryptionProfileConfig sets the FieldLevelEncryptionProfileConfig field's value. +func (s *FieldLevelEncryptionProfile) SetFieldLevelEncryptionProfileConfig(v *FieldLevelEncryptionProfileConfig) *FieldLevelEncryptionProfile { + s.FieldLevelEncryptionProfileConfig = v return s } -// SetLastModifiedTime sets the LastModifiedTime field's value. -func (s *Distribution) SetLastModifiedTime(v time.Time) *Distribution { - s.LastModifiedTime = &v +// SetId sets the Id field's value. +func (s *FieldLevelEncryptionProfile) SetId(v string) *FieldLevelEncryptionProfile { + s.Id = &v return s } -// SetStatus sets the Status field's value. -func (s *Distribution) SetStatus(v string) *Distribution { - s.Status = &v +// SetLastModifiedTime sets the LastModifiedTime field's value. +func (s *FieldLevelEncryptionProfile) SetLastModifiedTime(v time.Time) *FieldLevelEncryptionProfile { + s.LastModifiedTime = &v return s } -// A distribution configuration. -type DistributionConfig struct { +// A complex data type of profiles for the field-level encryption. +type FieldLevelEncryptionProfileConfig struct { _ struct{} `type:"structure"` - // A complex type that contains information about CNAMEs (alternate domain names), - // if any, for this distribution. - Aliases *Aliases `type:"structure"` - - // A complex type that contains zero or more CacheBehavior elements. - CacheBehaviors *CacheBehaviors `type:"structure"` - - // A unique value (for example, a date-time stamp) that ensures that the request - // can't be replayed. - // - // If the value of CallerReference is new (regardless of the content of the - // DistributionConfig object), CloudFront creates a new distribution. - // - // If CallerReference is a value that you already sent in a previous request - // to create a distribution, CloudFront returns a DistributionAlreadyExists - // error. + // A unique number that ensures that the request can't be replayed. // // CallerReference is a required field CallerReference *string `type:"string" required:"true"` - // Any comments you want to include about the distribution. - // - // If you don't want to specify a comment, include an empty Comment element. - // - // To delete an existing comment, update the distribution configuration and - // include an empty Comment element. - // - // To add or change a comment, update the distribution configuration and specify - // the new comment. - // - // Comment is a required field - Comment *string `type:"string" required:"true" sensitive:"true"` - - // A complex type that controls the following: - // - // * Whether CloudFront replaces HTTP status codes in the 4xx and 5xx range - // with custom error messages before returning the response to the viewer. - // - // * How long CloudFront caches HTTP status codes in the 4xx and 5xx range. - // - // For more information about custom error pages, see Customizing Error Responses - // (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-error-pages.html) - // in the Amazon CloudFront Developer Guide. - CustomErrorResponses *CustomErrorResponses `type:"structure"` - - // A complex type that describes the default cache behavior if you don't 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. - // - // DefaultCacheBehavior is a required field - DefaultCacheBehavior *DefaultCacheBehavior `type:"structure" required:"true"` - - // The object that you want CloudFront to request from your origin (for example, - // index.html) when a viewer requests the root URL for your distribution (http://www.example.com) - // instead of an object in your distribution (http://www.example.com/product-description.html). - // Specifying a default root object avoids exposing the contents of your distribution. - // - // Specify only the object name, for example, index.html. Don't add a / before - // the object name. - // - // If you don't want to specify a default root object when you create a distribution, - // include an empty DefaultRootObject element. - // - // To delete the default root object from an existing distribution, update the - // distribution configuration and include an empty DefaultRootObject element. - // - // To replace the default root object, update the distribution configuration - // and specify the new object. - // - // For more information about the default root object, see Creating a Default - // Root Object (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/DefaultRootObject.html) - // in the Amazon CloudFront Developer Guide. - DefaultRootObject *string `type:"string"` - - // From this field, you can enable or disable the selected distribution. - // - // Enabled is a required field - Enabled *bool `type:"boolean" required:"true"` - - // (Optional) Specify the maximum HTTP version that you want viewers to use - // to communicate with CloudFront. The default value for new web distributions - // is http2. Viewers that don't support HTTP/2 automatically use an earlier - // HTTP version. - // - // For viewers and CloudFront to use HTTP/2, viewers must support TLS 1.2 or - // later, and must support Server Name Identification (SNI). - // - // In general, configuring CloudFront to communicate with viewers using HTTP/2 - // reduces latency. You can improve performance by optimizing for HTTP/2. For - // more information, do an Internet search for "http/2 optimization." - HttpVersion *string `type:"string" enum:"HttpVersion"` - - // If you want CloudFront to respond to IPv6 DNS requests with an IPv6 address - // for your distribution, specify true. If you specify false, CloudFront responds - // to IPv6 DNS requests with the DNS response code NOERROR and with no IP addresses. - // This allows viewers to submit a second request, for an IPv4 address for your - // distribution. - // - // In general, you should enable IPv6 if you have users on IPv6 networks who - // want to access your content. However, if you're using signed URLs or signed - // cookies to restrict access to your content, and if you're using a custom - // policy that includes the IpAddress parameter to restrict the IP addresses - // that can access your content, don't enable IPv6. If you want to restrict - // access to some content by IP address and not restrict access to other content - // (or restrict access but not by IP address), you can create two distributions. - // For more information, see Creating a Signed URL Using a Custom Policy (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-custom-policy.html) - // in the Amazon CloudFront Developer Guide. - // - // If you're using an Amazon Route 53 alias resource record set to route traffic - // to your CloudFront distribution, you need to create a second alias resource - // record set when both of the following are true: - // - // * You enable IPv6 for the distribution - // - // * You're using alternate domain names in the URLs for your objects - // - // For more information, see Routing Traffic to an Amazon CloudFront Web Distribution - // by Using Your Domain Name (https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-cloudfront-distribution.html) - // in the Amazon Route 53 Developer Guide. - // - // If you created a CNAME resource record set, either with Amazon Route 53 or - // with another DNS service, you don't need to make any changes. A CNAME record - // will route traffic to your distribution regardless of the IP address format - // of the viewer request. - IsIPV6Enabled *bool `type:"boolean"` - - // A complex type that controls whether access logs are written for the distribution. - // - // For more information about logging, see Access Logs (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html) - // in the Amazon CloudFront Developer Guide. - Logging *LoggingConfig `type:"structure"` - - // A complex type that contains information about origin groups for this distribution. - OriginGroups *OriginGroups `type:"structure"` - - // A complex type that contains information about origins for this distribution. - // - // Origins is a required field - Origins *Origins `type:"structure" required:"true"` - - // The price class that corresponds with the maximum price that you want to - // pay for CloudFront service. If you specify PriceClass_All, CloudFront responds - // to requests for your objects from all CloudFront edge locations. - // - // If you specify a price class other than PriceClass_All, CloudFront serves - // your objects from the CloudFront edge location that has the lowest latency - // among the edge locations in your price class. Viewers who are in or near - // regions that are excluded from your specified price class may encounter slower - // performance. - // - // For more information about price classes, see Choosing the Price Class for - // a CloudFront Distribution (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PriceClass.html) - // in the Amazon CloudFront Developer Guide. For information about CloudFront - // pricing, including how price classes (such as Price Class 100) map to CloudFront - // regions, see Amazon CloudFront Pricing (http://aws.amazon.com/cloudfront/pricing/). - // For price class information, scroll down to see the table at the bottom of - // the page. - PriceClass *string `type:"string" enum:"PriceClass"` - - // A complex type that identifies ways in which you want to restrict distribution - // of your content. - Restrictions *Restrictions `type:"structure"` + // An optional comment for the field-level encryption profile. + Comment *string `type:"string"` - // A complex type that determines the distribution’s SSL/TLS configuration - // for communicating with viewers. - ViewerCertificate *ViewerCertificate `type:"structure"` + // A complex data type of encryption entities for the field-level encryption + // profile that include the public key ID, provider, and field patterns for + // specifying which fields to encrypt with this key. + // + // EncryptionEntities is a required field + EncryptionEntities *EncryptionEntities `type:"structure" required:"true"` - // A unique identifier that specifies the AWS WAF web ACL, if any, to associate - // with this distribution. To specify a web ACL created using the latest version - // of AWS WAF, use the ACL ARN, for example arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a. - // To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example - // 473e64fd-f30b-4765-81a0-62ad96dd167a. + // Profile name for the field-level encryption profile. // - // AWS WAF is a web application firewall that lets you monitor the HTTP and - // HTTPS requests that are forwarded to CloudFront, and lets you control access - // to your content. Based on conditions that you specify, such as the IP addresses - // that requests originate from or the values of query strings, CloudFront responds - // to requests either with the requested content or with an HTTP 403 status - // code (Forbidden). You can also configure CloudFront to return a custom error - // page when a request is blocked. For more information about AWS WAF, see the - // AWS WAF Developer Guide (https://docs.aws.amazon.com/waf/latest/developerguide/what-is-aws-waf.html). - WebACLId *string `type:"string"` + // Name is a required field + Name *string `type:"string" required:"true"` } // String returns the string representation -func (s DistributionConfig) String() string { +func (s FieldLevelEncryptionProfileConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DistributionConfig) GoString() string { +func (s FieldLevelEncryptionProfileConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DistributionConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DistributionConfig"} +func (s *FieldLevelEncryptionProfileConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "FieldLevelEncryptionProfileConfig"} if s.CallerReference == nil { invalidParams.Add(request.NewErrParamRequired("CallerReference")) } - if s.Comment == nil { - invalidParams.Add(request.NewErrParamRequired("Comment")) - } - if s.DefaultCacheBehavior == nil { - invalidParams.Add(request.NewErrParamRequired("DefaultCacheBehavior")) - } - if s.Enabled == nil { - invalidParams.Add(request.NewErrParamRequired("Enabled")) - } - if s.Origins == nil { - invalidParams.Add(request.NewErrParamRequired("Origins")) - } - if s.Aliases != nil { - if err := s.Aliases.Validate(); err != nil { - invalidParams.AddNested("Aliases", err.(request.ErrInvalidParams)) - } - } - if s.CacheBehaviors != nil { - if err := s.CacheBehaviors.Validate(); err != nil { - invalidParams.AddNested("CacheBehaviors", err.(request.ErrInvalidParams)) - } - } - if s.CustomErrorResponses != nil { - if err := s.CustomErrorResponses.Validate(); err != nil { - invalidParams.AddNested("CustomErrorResponses", err.(request.ErrInvalidParams)) - } - } - if s.DefaultCacheBehavior != nil { - if err := s.DefaultCacheBehavior.Validate(); err != nil { - invalidParams.AddNested("DefaultCacheBehavior", err.(request.ErrInvalidParams)) - } - } - if s.Logging != nil { - if err := s.Logging.Validate(); err != nil { - invalidParams.AddNested("Logging", err.(request.ErrInvalidParams)) - } - } - if s.OriginGroups != nil { - if err := s.OriginGroups.Validate(); err != nil { - invalidParams.AddNested("OriginGroups", err.(request.ErrInvalidParams)) - } + if s.EncryptionEntities == nil { + invalidParams.Add(request.NewErrParamRequired("EncryptionEntities")) } - if s.Origins != nil { - if err := s.Origins.Validate(); err != nil { - invalidParams.AddNested("Origins", err.(request.ErrInvalidParams)) - } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) } - if s.Restrictions != nil { - if err := s.Restrictions.Validate(); err != nil { - invalidParams.AddNested("Restrictions", err.(request.ErrInvalidParams)) + if s.EncryptionEntities != nil { + if err := s.EncryptionEntities.Validate(); err != nil { + invalidParams.AddNested("EncryptionEntities", err.(request.ErrInvalidParams)) } } @@ -8137,545 +11636,644 @@ func (s *DistributionConfig) Validate() error { return nil } -// SetAliases sets the Aliases field's value. -func (s *DistributionConfig) SetAliases(v *Aliases) *DistributionConfig { - s.Aliases = v - return s -} - -// SetCacheBehaviors sets the CacheBehaviors field's value. -func (s *DistributionConfig) SetCacheBehaviors(v *CacheBehaviors) *DistributionConfig { - s.CacheBehaviors = v - return s -} - // SetCallerReference sets the CallerReference field's value. -func (s *DistributionConfig) SetCallerReference(v string) *DistributionConfig { +func (s *FieldLevelEncryptionProfileConfig) SetCallerReference(v string) *FieldLevelEncryptionProfileConfig { s.CallerReference = &v return s } // SetComment sets the Comment field's value. -func (s *DistributionConfig) SetComment(v string) *DistributionConfig { +func (s *FieldLevelEncryptionProfileConfig) SetComment(v string) *FieldLevelEncryptionProfileConfig { s.Comment = &v return s } -// SetCustomErrorResponses sets the CustomErrorResponses field's value. -func (s *DistributionConfig) SetCustomErrorResponses(v *CustomErrorResponses) *DistributionConfig { - s.CustomErrorResponses = v +// SetEncryptionEntities sets the EncryptionEntities field's value. +func (s *FieldLevelEncryptionProfileConfig) SetEncryptionEntities(v *EncryptionEntities) *FieldLevelEncryptionProfileConfig { + s.EncryptionEntities = v return s } -// SetDefaultCacheBehavior sets the DefaultCacheBehavior field's value. -func (s *DistributionConfig) SetDefaultCacheBehavior(v *DefaultCacheBehavior) *DistributionConfig { - s.DefaultCacheBehavior = v +// SetName sets the Name field's value. +func (s *FieldLevelEncryptionProfileConfig) SetName(v string) *FieldLevelEncryptionProfileConfig { + s.Name = &v return s } -// SetDefaultRootObject sets the DefaultRootObject field's value. -func (s *DistributionConfig) SetDefaultRootObject(v string) *DistributionConfig { - s.DefaultRootObject = &v - return s +// List of field-level encryption profiles. +type FieldLevelEncryptionProfileList struct { + _ struct{} `type:"structure"` + + // The field-level encryption profile items. + Items []*FieldLevelEncryptionProfileSummary `locationNameList:"FieldLevelEncryptionProfileSummary" type:"list"` + + // The maximum number of field-level encryption profiles you want in the response + // body. + // + // MaxItems is a required field + MaxItems *int64 `type:"integer" required:"true"` + + // If there are more elements to be listed, this element is present and contains + // the value that you can use for the Marker request parameter to continue listing + // your profiles where you left off. + NextMarker *string `type:"string"` + + // The number of field-level encryption profiles. + // + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } -// SetEnabled sets the Enabled field's value. -func (s *DistributionConfig) SetEnabled(v bool) *DistributionConfig { - s.Enabled = &v - return s +// String returns the string representation +func (s FieldLevelEncryptionProfileList) String() string { + return awsutil.Prettify(s) } -// SetHttpVersion sets the HttpVersion field's value. -func (s *DistributionConfig) SetHttpVersion(v string) *DistributionConfig { - s.HttpVersion = &v +// GoString returns the string representation +func (s FieldLevelEncryptionProfileList) GoString() string { + return s.String() +} + +// SetItems sets the Items field's value. +func (s *FieldLevelEncryptionProfileList) SetItems(v []*FieldLevelEncryptionProfileSummary) *FieldLevelEncryptionProfileList { + s.Items = v return s } -// SetIsIPV6Enabled sets the IsIPV6Enabled field's value. -func (s *DistributionConfig) SetIsIPV6Enabled(v bool) *DistributionConfig { - s.IsIPV6Enabled = &v +// SetMaxItems sets the MaxItems field's value. +func (s *FieldLevelEncryptionProfileList) SetMaxItems(v int64) *FieldLevelEncryptionProfileList { + s.MaxItems = &v return s } -// SetLogging sets the Logging field's value. -func (s *DistributionConfig) SetLogging(v *LoggingConfig) *DistributionConfig { - s.Logging = v +// SetNextMarker sets the NextMarker field's value. +func (s *FieldLevelEncryptionProfileList) SetNextMarker(v string) *FieldLevelEncryptionProfileList { + s.NextMarker = &v return s } -// SetOriginGroups sets the OriginGroups field's value. -func (s *DistributionConfig) SetOriginGroups(v *OriginGroups) *DistributionConfig { - s.OriginGroups = v +// SetQuantity sets the Quantity field's value. +func (s *FieldLevelEncryptionProfileList) SetQuantity(v int64) *FieldLevelEncryptionProfileList { + s.Quantity = &v return s } -// SetOrigins sets the Origins field's value. -func (s *DistributionConfig) SetOrigins(v *Origins) *DistributionConfig { - s.Origins = v +// The field-level encryption profile summary. +type FieldLevelEncryptionProfileSummary struct { + _ struct{} `type:"structure"` + + // An optional comment for the field-level encryption profile summary. + Comment *string `type:"string"` + + // A complex data type of encryption entities for the field-level encryption + // profile that include the public key ID, provider, and field patterns for + // specifying which fields to encrypt with this key. + // + // EncryptionEntities is a required field + EncryptionEntities *EncryptionEntities `type:"structure" required:"true"` + + // ID for the field-level encryption profile summary. + // + // Id is a required field + Id *string `type:"string" required:"true"` + + // The time when the the field-level encryption profile summary was last updated. + // + // LastModifiedTime is a required field + LastModifiedTime *time.Time `type:"timestamp" required:"true"` + + // Name for the field-level encryption profile summary. + // + // Name is a required field + Name *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s FieldLevelEncryptionProfileSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FieldLevelEncryptionProfileSummary) GoString() string { + return s.String() +} + +// SetComment sets the Comment field's value. +func (s *FieldLevelEncryptionProfileSummary) SetComment(v string) *FieldLevelEncryptionProfileSummary { + s.Comment = &v return s } -// SetPriceClass sets the PriceClass field's value. -func (s *DistributionConfig) SetPriceClass(v string) *DistributionConfig { - s.PriceClass = &v +// SetEncryptionEntities sets the EncryptionEntities field's value. +func (s *FieldLevelEncryptionProfileSummary) SetEncryptionEntities(v *EncryptionEntities) *FieldLevelEncryptionProfileSummary { + s.EncryptionEntities = v return s } -// SetRestrictions sets the Restrictions field's value. -func (s *DistributionConfig) SetRestrictions(v *Restrictions) *DistributionConfig { - s.Restrictions = v +// SetId sets the Id field's value. +func (s *FieldLevelEncryptionProfileSummary) SetId(v string) *FieldLevelEncryptionProfileSummary { + s.Id = &v return s } -// SetViewerCertificate sets the ViewerCertificate field's value. -func (s *DistributionConfig) SetViewerCertificate(v *ViewerCertificate) *DistributionConfig { - s.ViewerCertificate = v +// SetLastModifiedTime sets the LastModifiedTime field's value. +func (s *FieldLevelEncryptionProfileSummary) SetLastModifiedTime(v time.Time) *FieldLevelEncryptionProfileSummary { + s.LastModifiedTime = &v return s } -// SetWebACLId sets the WebACLId field's value. -func (s *DistributionConfig) SetWebACLId(v string) *DistributionConfig { - s.WebACLId = &v +// SetName sets the Name field's value. +func (s *FieldLevelEncryptionProfileSummary) SetName(v string) *FieldLevelEncryptionProfileSummary { + s.Name = &v return s } -// A distribution Configuration and a list of tags to be associated with the -// distribution. -type DistributionConfigWithTags struct { +// A summary of a field-level encryption item. +type FieldLevelEncryptionSummary struct { _ struct{} `type:"structure"` - // A distribution configuration. + // An optional comment about the field-level encryption item. + Comment *string `type:"string"` + + // A summary of a content type-profile mapping. + ContentTypeProfileConfig *ContentTypeProfileConfig `type:"structure"` + + // The unique ID of a field-level encryption item. // - // DistributionConfig is a required field - DistributionConfig *DistributionConfig `type:"structure" required:"true"` + // Id is a required field + Id *string `type:"string" required:"true"` - // A complex type that contains zero or more Tag elements. + // The last time that the summary of field-level encryption items was modified. // - // Tags is a required field - Tags *Tags `type:"structure" required:"true"` + // LastModifiedTime is a required field + LastModifiedTime *time.Time `type:"timestamp" required:"true"` + + // A summary of a query argument-profile mapping. + QueryArgProfileConfig *QueryArgProfileConfig `type:"structure"` } // String returns the string representation -func (s DistributionConfigWithTags) String() string { +func (s FieldLevelEncryptionSummary) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DistributionConfigWithTags) GoString() string { +func (s FieldLevelEncryptionSummary) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DistributionConfigWithTags) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DistributionConfigWithTags"} - if s.DistributionConfig == nil { - invalidParams.Add(request.NewErrParamRequired("DistributionConfig")) - } - if s.Tags == nil { - invalidParams.Add(request.NewErrParamRequired("Tags")) - } - if s.DistributionConfig != nil { - if err := s.DistributionConfig.Validate(); err != nil { - invalidParams.AddNested("DistributionConfig", err.(request.ErrInvalidParams)) - } - } - if s.Tags != nil { - if err := s.Tags.Validate(); err != nil { - invalidParams.AddNested("Tags", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetComment sets the Comment field's value. +func (s *FieldLevelEncryptionSummary) SetComment(v string) *FieldLevelEncryptionSummary { + s.Comment = &v + return s } -// SetDistributionConfig sets the DistributionConfig field's value. -func (s *DistributionConfigWithTags) SetDistributionConfig(v *DistributionConfig) *DistributionConfigWithTags { - s.DistributionConfig = v +// SetContentTypeProfileConfig sets the ContentTypeProfileConfig field's value. +func (s *FieldLevelEncryptionSummary) SetContentTypeProfileConfig(v *ContentTypeProfileConfig) *FieldLevelEncryptionSummary { + s.ContentTypeProfileConfig = v return s } -// SetTags sets the Tags field's value. -func (s *DistributionConfigWithTags) SetTags(v *Tags) *DistributionConfigWithTags { - s.Tags = v +// SetId sets the Id field's value. +func (s *FieldLevelEncryptionSummary) SetId(v string) *FieldLevelEncryptionSummary { + s.Id = &v return s } -// A distribution list. -type DistributionList struct { - _ struct{} `type:"structure"` - - // A flag that indicates whether more distributions remain to be listed. If - // your results were truncated, you can make a follow-up pagination request - // using the Marker request parameter to retrieve more distributions in the - // list. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // A complex type that contains one DistributionSummary element for each distribution - // that was created by the current AWS account. - Items []*DistributionSummary `locationNameList:"DistributionSummary" type:"list"` +// SetLastModifiedTime sets the LastModifiedTime field's value. +func (s *FieldLevelEncryptionSummary) SetLastModifiedTime(v time.Time) *FieldLevelEncryptionSummary { + s.LastModifiedTime = &v + return s +} - // The value you provided for the Marker request parameter. - // - // Marker is a required field - Marker *string `type:"string" required:"true"` +// SetQueryArgProfileConfig sets the QueryArgProfileConfig field's value. +func (s *FieldLevelEncryptionSummary) SetQueryArgProfileConfig(v *QueryArgProfileConfig) *FieldLevelEncryptionSummary { + s.QueryArgProfileConfig = v + return s +} - // The value you provided for the MaxItems request parameter. - // - // MaxItems is a required field - MaxItems *int64 `type:"integer" required:"true"` +// A complex data type that includes the field patterns to match for field-level +// encryption. +type FieldPatterns struct { + _ struct{} `type:"structure"` - // If IsTruncated is true, this element is present and contains the value you - // can use for the Marker request parameter to continue listing your distributions - // where they left off. - NextMarker *string `type:"string"` + // An array of the field-level encryption field patterns. + Items []*string `locationNameList:"FieldPattern" type:"list"` - // The number of distributions that were created by the current AWS account. + // The number of field-level encryption field patterns. // // Quantity is a required field Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s DistributionList) String() string { +func (s FieldPatterns) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DistributionList) GoString() string { +func (s FieldPatterns) GoString() string { return s.String() } -// SetIsTruncated sets the IsTruncated field's value. -func (s *DistributionList) SetIsTruncated(v bool) *DistributionList { - s.IsTruncated = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *FieldPatterns) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "FieldPatterns"} + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } // SetItems sets the Items field's value. -func (s *DistributionList) SetItems(v []*DistributionSummary) *DistributionList { +func (s *FieldPatterns) SetItems(v []*string) *FieldPatterns { s.Items = v return s } -// SetMarker sets the Marker field's value. -func (s *DistributionList) SetMarker(v string) *DistributionList { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *DistributionList) SetMaxItems(v int64) *DistributionList { - s.MaxItems = &v - return s -} - -// SetNextMarker sets the NextMarker field's value. -func (s *DistributionList) SetNextMarker(v string) *DistributionList { - s.NextMarker = &v - return s -} - // SetQuantity sets the Quantity field's value. -func (s *DistributionList) SetQuantity(v int64) *DistributionList { +func (s *FieldPatterns) SetQuantity(v int64) *FieldPatterns { s.Quantity = &v return s } -// A summary of the information about a CloudFront distribution. -type DistributionSummary struct { +// This field is deprecated. We recommend that you use a cache policy or an +// origin request policy instead of this field. +// +// If you want to include values in the cache key, use a cache policy. For more +// information, see Creating cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) +// in the Amazon CloudFront Developer Guide. +// +// If you want to send values to the origin but not include them in the cache +// key, use an origin request policy. For more information, see Creating origin +// request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) +// in the Amazon CloudFront Developer Guide. +// +// A complex type that specifies how CloudFront handles query strings, cookies, +// and HTTP headers. +type ForwardedValues struct { _ struct{} `type:"structure"` - // The ARN (Amazon Resource Name) for the distribution. For example: arn:aws:cloudfront::123456789012:distribution/EDFDVBD632BHDS5, - // where 123456789012 is your AWS account ID. - // - // ARN is a required field - ARN *string `type:"string" required:"true"` - - // AWS services in China customers must file for an Internet Content Provider - // (ICP) recordal if they want to serve content publicly on an alternate domain - // name, also known as a CNAME, that they've added to CloudFront. AliasICPRecordal - // provides the ICP recordal status for CNAMEs associated with distributions. + // This field is deprecated. We recommend that you use a cache policy or an + // origin request policy instead of this field. // - // For more information about ICP recordals, see Signup, Accounts, and Credentials - // (https://docs.amazonaws.cn/en_us/aws/latest/userguide/accounts-and-credentials.html) - // in Getting Started with AWS services in China. - AliasICPRecordals []*AliasICPRecordal `locationNameList:"AliasICPRecordal" type:"list"` - - // A complex type that contains information about CNAMEs (alternate domain names), - // if any, for this distribution. + // If you want to include cookies in the cache key, use a cache policy. For + // more information, see Creating cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // in the Amazon CloudFront Developer Guide. // - // Aliases is a required field - Aliases *Aliases `type:"structure" required:"true"` - - // A complex type that contains zero or more CacheBehavior elements. + // If you want to send cookies to the origin but not include them in the cache + // key, use an origin request policy. For more information, see Creating origin + // request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) + // in the Amazon CloudFront Developer Guide. // - // CacheBehaviors is a required field - CacheBehaviors *CacheBehaviors `type:"structure" required:"true"` - - // The comment originally specified when this distribution was created. + // A complex type that specifies whether you want CloudFront to forward cookies + // to the origin and, if so, which ones. For more information about forwarding + // cookies to the origin, see How CloudFront Forwards, Caches, and Logs Cookies + // (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Cookies.html) + // in the Amazon CloudFront Developer Guide. // - // Comment is a required field - Comment *string `type:"string" required:"true"` + // Cookies is a required field + Cookies *CookiePreference `type:"structure" required:"true"` - // A complex type that contains zero or more CustomErrorResponses elements. + // This field is deprecated. We recommend that you use a cache policy or an + // origin request policy instead of this field. // - // CustomErrorResponses is a required field - CustomErrorResponses *CustomErrorResponses `type:"structure" required:"true"` - - // A complex type that describes the default cache behavior if you don't 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. + // If you want to include headers in the cache key, use a cache policy. For + // more information, see Creating cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // in the Amazon CloudFront Developer Guide. // - // DefaultCacheBehavior is a required field - DefaultCacheBehavior *DefaultCacheBehavior `type:"structure" required:"true"` - - // The domain name that corresponds to the distribution, for example, d111111abcdef8.cloudfront.net. + // If you want to send headers to the origin but not include them in the cache + // key, use an origin request policy. For more information, see Creating origin + // request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) + // in the Amazon CloudFront Developer Guide. // - // DomainName is a required field - DomainName *string `type:"string" required:"true"` - - // Whether the distribution is enabled to accept user requests for content. + // A complex type that specifies the Headers, if any, that you want CloudFront + // to forward to the origin for this cache behavior (whitelisted headers). For + // the headers that you specify, CloudFront also caches separate versions of + // a specified object that is based on the header values in viewer requests. // - // Enabled is a required field - Enabled *bool `type:"boolean" required:"true"` + // For more information, see Caching Content Based on Request Headers (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html) + // in the Amazon CloudFront Developer Guide. + Headers *Headers `type:"structure"` - // Specify the maximum HTTP version that you want viewers to use to communicate - // with CloudFront. The default value for new web distributions is http2. Viewers - // that don't support HTTP/2 will automatically use an earlier version. + // This field is deprecated. We recommend that you use a cache policy or an + // origin request policy instead of this field. // - // HttpVersion is a required field - HttpVersion *string `type:"string" required:"true" enum:"HttpVersion"` - - // The identifier for the distribution. For example: EDFDVBD632BHDS5. + // If you want to include query strings in the cache key, use a cache policy. + // For more information, see Creating cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // in the Amazon CloudFront Developer Guide. // - // Id is a required field - Id *string `type:"string" required:"true"` - - // Whether CloudFront responds to IPv6 DNS requests with an IPv6 address for - // your distribution. + // If you want to send query strings to the origin but not include them in the + // cache key, use an origin request policy. For more information, see Creating + // origin request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) + // in the Amazon CloudFront Developer Guide. // - // IsIPV6Enabled is a required field - IsIPV6Enabled *bool `type:"boolean" required:"true"` - - // The date and time the distribution was last modified. + // Indicates whether you want CloudFront to forward query strings to the origin + // that is associated with this cache behavior and cache based on the query + // string parameters. CloudFront behavior depends on the value of QueryString + // and on the values that you specify for QueryStringCacheKeys, if any: // - // LastModifiedTime is a required field - LastModifiedTime *time.Time `type:"timestamp" required:"true"` - - // A complex type that contains information about origin groups for this distribution. - OriginGroups *OriginGroups `type:"structure"` - - // A complex type that contains information about origins for this distribution. + // If you specify true for QueryString and you don't specify any values for + // QueryStringCacheKeys, CloudFront forwards all query string parameters to + // the origin and caches based on all query string parameters. Depending on + // how many query string parameters and values you have, this can adversely + // affect performance because CloudFront must forward more requests to the origin. // - // Origins is a required field - Origins *Origins `type:"structure" required:"true"` - - // A complex type that contains information about price class for this streaming - // distribution. + // If you specify true for QueryString and you specify one or more values for + // QueryStringCacheKeys, CloudFront forwards all query string parameters to + // the origin, but it only caches based on the query string parameters that + // you specify. // - // PriceClass is a required field - PriceClass *string `type:"string" required:"true" enum:"PriceClass"` - - // A complex type that identifies ways in which you want to restrict distribution - // of your content. + // If you specify false for QueryString, CloudFront doesn't forward any query + // string parameters to the origin, and doesn't cache based on query string + // parameters. // - // Restrictions is a required field - Restrictions *Restrictions `type:"structure" required:"true"` - - // The current status of the distribution. When the status is Deployed, the - // distribution's information is propagated to all CloudFront edge locations. + // For more information, see Configuring CloudFront to Cache Based on Query + // String Parameters (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/QueryStringParameters.html) + // in the Amazon CloudFront Developer Guide. // - // Status is a required field - Status *string `type:"string" required:"true"` + // QueryString is a required field + QueryString *bool `type:"boolean" required:"true"` - // A complex type that determines the distribution’s SSL/TLS configuration - // for communicating with viewers. + // This field is deprecated. We recommend that you use a cache policy or an + // origin request policy instead of this field. // - // ViewerCertificate is a required field - ViewerCertificate *ViewerCertificate `type:"structure" required:"true"` - - // The Web ACL Id (if any) associated with the distribution. + // If you want to include query strings in the cache key, use a cache policy. + // For more information, see Creating cache policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) + // in the Amazon CloudFront Developer Guide. // - // WebACLId is a required field - WebACLId *string `type:"string" required:"true"` + // If you want to send query strings to the origin but not include them in the + // cache key, use an origin request policy. For more information, see Creating + // origin request policies (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) + // in the Amazon CloudFront Developer Guide. + // + // A complex type that contains information about the query string parameters + // that you want CloudFront to use for caching for this cache behavior. + QueryStringCacheKeys *QueryStringCacheKeys `type:"structure"` } // String returns the string representation -func (s DistributionSummary) String() string { +func (s ForwardedValues) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DistributionSummary) GoString() string { +func (s ForwardedValues) GoString() string { return s.String() } -// SetARN sets the ARN field's value. -func (s *DistributionSummary) SetARN(v string) *DistributionSummary { - s.ARN = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *ForwardedValues) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ForwardedValues"} + if s.Cookies == nil { + invalidParams.Add(request.NewErrParamRequired("Cookies")) + } + if s.QueryString == nil { + invalidParams.Add(request.NewErrParamRequired("QueryString")) + } + if s.Cookies != nil { + if err := s.Cookies.Validate(); err != nil { + invalidParams.AddNested("Cookies", err.(request.ErrInvalidParams)) + } + } + if s.Headers != nil { + if err := s.Headers.Validate(); err != nil { + invalidParams.AddNested("Headers", err.(request.ErrInvalidParams)) + } + } + if s.QueryStringCacheKeys != nil { + if err := s.QueryStringCacheKeys.Validate(); err != nil { + invalidParams.AddNested("QueryStringCacheKeys", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetAliasICPRecordals sets the AliasICPRecordals field's value. -func (s *DistributionSummary) SetAliasICPRecordals(v []*AliasICPRecordal) *DistributionSummary { - s.AliasICPRecordals = v +// SetCookies sets the Cookies field's value. +func (s *ForwardedValues) SetCookies(v *CookiePreference) *ForwardedValues { + s.Cookies = v return s } -// SetAliases sets the Aliases field's value. -func (s *DistributionSummary) SetAliases(v *Aliases) *DistributionSummary { - s.Aliases = v +// SetHeaders sets the Headers field's value. +func (s *ForwardedValues) SetHeaders(v *Headers) *ForwardedValues { + s.Headers = v return s } -// SetCacheBehaviors sets the CacheBehaviors field's value. -func (s *DistributionSummary) SetCacheBehaviors(v *CacheBehaviors) *DistributionSummary { - s.CacheBehaviors = v +// SetQueryString sets the QueryString field's value. +func (s *ForwardedValues) SetQueryString(v bool) *ForwardedValues { + s.QueryString = &v return s } -// SetComment sets the Comment field's value. -func (s *DistributionSummary) SetComment(v string) *DistributionSummary { - s.Comment = &v +// SetQueryStringCacheKeys sets the QueryStringCacheKeys field's value. +func (s *ForwardedValues) SetQueryStringCacheKeys(v *QueryStringCacheKeys) *ForwardedValues { + s.QueryStringCacheKeys = v return s } -// SetCustomErrorResponses sets the CustomErrorResponses field's value. -func (s *DistributionSummary) SetCustomErrorResponses(v *CustomErrorResponses) *DistributionSummary { - s.CustomErrorResponses = v - return s +// A complex type that controls the countries in which your content is distributed. +// CloudFront determines the location of your users using MaxMind GeoIP databases. +type GeoRestriction struct { + _ struct{} `type:"structure"` + + // A complex type that contains a Location element for each country in which + // you want CloudFront either to distribute your content (whitelist) or not + // distribute your content (blacklist). + // + // The Location element is a two-letter, uppercase country code for a country + // that you want to include in your blacklist or whitelist. Include one Location + // element for each country. + // + // CloudFront and MaxMind both use ISO 3166 country codes. For the current list + // of countries and the corresponding codes, see ISO 3166-1-alpha-2 code on + // the International Organization for Standardization website. You can also + // refer to the country list on the CloudFront console, which includes both + // country names and codes. + Items []*string `locationNameList:"Location" type:"list"` + + // When geo restriction is enabled, this is the number of countries in your + // whitelist or blacklist. Otherwise, when it is not enabled, Quantity is 0, + // and you can omit Items. + // + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` + + // The method that you want to use to restrict distribution of your content + // by country: + // + // * none: No geo restriction is enabled, meaning access to content is not + // restricted by client geo location. + // + // * blacklist: The Location elements specify the countries in which you + // don't want CloudFront to distribute your content. + // + // * whitelist: The Location elements specify the countries in which you + // want CloudFront to distribute your content. + // + // RestrictionType is a required field + RestrictionType *string `type:"string" required:"true" enum:"GeoRestrictionType"` } -// SetDefaultCacheBehavior sets the DefaultCacheBehavior field's value. -func (s *DistributionSummary) SetDefaultCacheBehavior(v *DefaultCacheBehavior) *DistributionSummary { - s.DefaultCacheBehavior = v - return s +// String returns the string representation +func (s GeoRestriction) String() string { + return awsutil.Prettify(s) } -// SetDomainName sets the DomainName field's value. -func (s *DistributionSummary) SetDomainName(v string) *DistributionSummary { - s.DomainName = &v - return s +// GoString returns the string representation +func (s GeoRestriction) GoString() string { + return s.String() } -// SetEnabled sets the Enabled field's value. -func (s *DistributionSummary) SetEnabled(v bool) *DistributionSummary { - s.Enabled = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *GeoRestriction) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GeoRestriction"} + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) + } + if s.RestrictionType == nil { + invalidParams.Add(request.NewErrParamRequired("RestrictionType")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetHttpVersion sets the HttpVersion field's value. -func (s *DistributionSummary) SetHttpVersion(v string) *DistributionSummary { - s.HttpVersion = &v +// SetItems sets the Items field's value. +func (s *GeoRestriction) SetItems(v []*string) *GeoRestriction { + s.Items = v return s } -// SetId sets the Id field's value. -func (s *DistributionSummary) SetId(v string) *DistributionSummary { - s.Id = &v +// SetQuantity sets the Quantity field's value. +func (s *GeoRestriction) SetQuantity(v int64) *GeoRestriction { + s.Quantity = &v return s } -// SetIsIPV6Enabled sets the IsIPV6Enabled field's value. -func (s *DistributionSummary) SetIsIPV6Enabled(v bool) *DistributionSummary { - s.IsIPV6Enabled = &v +// SetRestrictionType sets the RestrictionType field's value. +func (s *GeoRestriction) SetRestrictionType(v string) *GeoRestriction { + s.RestrictionType = &v return s } -// SetLastModifiedTime sets the LastModifiedTime field's value. -func (s *DistributionSummary) SetLastModifiedTime(v time.Time) *DistributionSummary { - s.LastModifiedTime = &v - return s +type GetCachePolicyConfigInput struct { + _ struct{} `locationName:"GetCachePolicyConfigRequest" type:"structure"` + + // The unique identifier for the cache policy. If the cache policy is attached + // to a distribution’s cache behavior, you can get the policy’s identifier + // using ListDistributions or GetDistribution. If the cache policy is not attached + // to a cache behavior, you can get the identifier using ListCachePolicies. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } -// SetOriginGroups sets the OriginGroups field's value. -func (s *DistributionSummary) SetOriginGroups(v *OriginGroups) *DistributionSummary { - s.OriginGroups = v - return s +// String returns the string representation +func (s GetCachePolicyConfigInput) String() string { + return awsutil.Prettify(s) } -// SetOrigins sets the Origins field's value. -func (s *DistributionSummary) SetOrigins(v *Origins) *DistributionSummary { - s.Origins = v - return s +// GoString returns the string representation +func (s GetCachePolicyConfigInput) GoString() string { + return s.String() } -// SetPriceClass sets the PriceClass field's value. -func (s *DistributionSummary) SetPriceClass(v string) *DistributionSummary { - s.PriceClass = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetCachePolicyConfigInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetCachePolicyConfigInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetRestrictions sets the Restrictions field's value. -func (s *DistributionSummary) SetRestrictions(v *Restrictions) *DistributionSummary { - s.Restrictions = v +// SetId sets the Id field's value. +func (s *GetCachePolicyConfigInput) SetId(v string) *GetCachePolicyConfigInput { + s.Id = &v return s } -// SetStatus sets the Status field's value. -func (s *DistributionSummary) SetStatus(v string) *DistributionSummary { - s.Status = &v - return s +type GetCachePolicyConfigOutput struct { + _ struct{} `type:"structure" payload:"CachePolicyConfig"` + + // The cache policy configuration. + CachePolicyConfig *CachePolicyConfig `type:"structure"` + + // The current version of the cache policy. + ETag *string `location:"header" locationName:"ETag" type:"string"` } -// SetViewerCertificate sets the ViewerCertificate field's value. -func (s *DistributionSummary) SetViewerCertificate(v *ViewerCertificate) *DistributionSummary { - s.ViewerCertificate = v +// String returns the string representation +func (s GetCachePolicyConfigOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCachePolicyConfigOutput) GoString() string { + return s.String() +} + +// SetCachePolicyConfig sets the CachePolicyConfig field's value. +func (s *GetCachePolicyConfigOutput) SetCachePolicyConfig(v *CachePolicyConfig) *GetCachePolicyConfigOutput { + s.CachePolicyConfig = v return s } -// SetWebACLId sets the WebACLId field's value. -func (s *DistributionSummary) SetWebACLId(v string) *DistributionSummary { - s.WebACLId = &v +// SetETag sets the ETag field's value. +func (s *GetCachePolicyConfigOutput) SetETag(v string) *GetCachePolicyConfigOutput { + s.ETag = &v return s } -// Complex data type for field-level encryption profiles that includes all of -// the encryption entities. -type EncryptionEntities struct { - _ struct{} `type:"structure"` - - // An array of field patterns in a field-level encryption content type-profile - // mapping. - Items []*EncryptionEntity `locationNameList:"EncryptionEntity" type:"list"` +type GetCachePolicyInput struct { + _ struct{} `locationName:"GetCachePolicyRequest" type:"structure"` - // Number of field pattern items in a field-level encryption content type-profile - // mapping. + // The unique identifier for the cache policy. If the cache policy is attached + // to a distribution’s cache behavior, you can get the policy’s identifier + // using ListDistributions or GetDistribution. If the cache policy is not attached + // to a cache behavior, you can get the identifier using ListCachePolicies. // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s EncryptionEntities) String() string { +func (s GetCachePolicyInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s EncryptionEntities) GoString() string { +func (s GetCachePolicyInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *EncryptionEntities) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "EncryptionEntities"} - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) +func (s *GetCachePolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetCachePolicyInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) } - if s.Items != nil { - for i, v := range s.Items { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) - } - } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) } if invalidParams.Len() > 0 { @@ -8684,72 +12282,73 @@ func (s *EncryptionEntities) Validate() error { return nil } -// SetItems sets the Items field's value. -func (s *EncryptionEntities) SetItems(v []*EncryptionEntity) *EncryptionEntities { - s.Items = v +// SetId sets the Id field's value. +func (s *GetCachePolicyInput) SetId(v string) *GetCachePolicyInput { + s.Id = &v return s } -// SetQuantity sets the Quantity field's value. -func (s *EncryptionEntities) SetQuantity(v int64) *EncryptionEntities { - s.Quantity = &v - return s +type GetCachePolicyOutput struct { + _ struct{} `type:"structure" payload:"CachePolicy"` + + // The cache policy. + CachePolicy *CachePolicy `type:"structure"` + + // The current version of the cache policy. + ETag *string `location:"header" locationName:"ETag" type:"string"` } -// Complex data type for field-level encryption profiles that includes the encryption -// key and field pattern specifications. -type EncryptionEntity struct { - _ struct{} `type:"structure"` +// String returns the string representation +func (s GetCachePolicyOutput) String() string { + return awsutil.Prettify(s) +} - // Field patterns in a field-level encryption content type profile specify the - // fields that you want to be encrypted. You can provide the full field name, - // or any beginning characters followed by a wildcard (*). You can't overlap - // field patterns. For example, you can't have both ABC* and AB*. Note that - // field patterns are case-sensitive. - // - // FieldPatterns is a required field - FieldPatterns *FieldPatterns `type:"structure" required:"true"` +// GoString returns the string representation +func (s GetCachePolicyOutput) GoString() string { + return s.String() +} - // The provider associated with the public key being used for encryption. This - // value must also be provided with the private key for applications to be able - // to decrypt data. - // - // ProviderId is a required field - ProviderId *string `type:"string" required:"true"` +// SetCachePolicy sets the CachePolicy field's value. +func (s *GetCachePolicyOutput) SetCachePolicy(v *CachePolicy) *GetCachePolicyOutput { + s.CachePolicy = v + return s +} - // The public key associated with a set of field-level encryption patterns, - // to be used when encrypting the fields that match the patterns. +// SetETag sets the ETag field's value. +func (s *GetCachePolicyOutput) SetETag(v string) *GetCachePolicyOutput { + s.ETag = &v + return s +} + +// The origin access identity's configuration information. For more information, +// see CloudFrontOriginAccessIdentityConfig (https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CloudFrontOriginAccessIdentityConfig.html). +type GetCloudFrontOriginAccessIdentityConfigInput struct { + _ struct{} `locationName:"GetCloudFrontOriginAccessIdentityConfigRequest" type:"structure"` + + // The identity's ID. // - // PublicKeyId is a required field - PublicKeyId *string `type:"string" required:"true"` + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s EncryptionEntity) String() string { +func (s GetCloudFrontOriginAccessIdentityConfigInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s EncryptionEntity) GoString() string { +func (s GetCloudFrontOriginAccessIdentityConfigInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *EncryptionEntity) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "EncryptionEntity"} - if s.FieldPatterns == nil { - invalidParams.Add(request.NewErrParamRequired("FieldPatterns")) - } - if s.ProviderId == nil { - invalidParams.Add(request.NewErrParamRequired("ProviderId")) - } - if s.PublicKeyId == nil { - invalidParams.Add(request.NewErrParamRequired("PublicKeyId")) +func (s *GetCloudFrontOriginAccessIdentityConfigInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetCloudFrontOriginAccessIdentityConfigInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) } - if s.FieldPatterns != nil { - if err := s.FieldPatterns.Validate(); err != nil { - invalidParams.AddNested("FieldPatterns", err.(request.ErrInvalidParams)) - } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) } if invalidParams.Len() > 0 { @@ -8758,124 +12357,150 @@ func (s *EncryptionEntity) Validate() error { return nil } -// SetFieldPatterns sets the FieldPatterns field's value. -func (s *EncryptionEntity) SetFieldPatterns(v *FieldPatterns) *EncryptionEntity { - s.FieldPatterns = v +// SetId sets the Id field's value. +func (s *GetCloudFrontOriginAccessIdentityConfigInput) SetId(v string) *GetCloudFrontOriginAccessIdentityConfigInput { + s.Id = &v return s } -// SetProviderId sets the ProviderId field's value. -func (s *EncryptionEntity) SetProviderId(v string) *EncryptionEntity { - s.ProviderId = &v - return s +// The returned result of the corresponding request. +type GetCloudFrontOriginAccessIdentityConfigOutput struct { + _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentityConfig"` + + // The origin access identity's configuration information. + CloudFrontOriginAccessIdentityConfig *OriginAccessIdentityConfig `type:"structure"` + + // The current version of the configuration. For example: E2QWRUHAPOMQZL. + ETag *string `location:"header" locationName:"ETag" type:"string"` } -// SetPublicKeyId sets the PublicKeyId field's value. -func (s *EncryptionEntity) SetPublicKeyId(v string) *EncryptionEntity { - s.PublicKeyId = &v +// String returns the string representation +func (s GetCloudFrontOriginAccessIdentityConfigOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCloudFrontOriginAccessIdentityConfigOutput) GoString() string { + return s.String() +} + +// SetCloudFrontOriginAccessIdentityConfig sets the CloudFrontOriginAccessIdentityConfig field's value. +func (s *GetCloudFrontOriginAccessIdentityConfigOutput) SetCloudFrontOriginAccessIdentityConfig(v *OriginAccessIdentityConfig) *GetCloudFrontOriginAccessIdentityConfigOutput { + s.CloudFrontOriginAccessIdentityConfig = v return s } -// A complex data type that includes the profile configurations and other options -// specified for field-level encryption. -type FieldLevelEncryption struct { - _ struct{} `type:"structure"` +// SetETag sets the ETag field's value. +func (s *GetCloudFrontOriginAccessIdentityConfigOutput) SetETag(v string) *GetCloudFrontOriginAccessIdentityConfigOutput { + s.ETag = &v + return s +} - // A complex data type that includes the profile configurations specified for - // field-level encryption. - // - // FieldLevelEncryptionConfig is a required field - FieldLevelEncryptionConfig *FieldLevelEncryptionConfig `type:"structure" required:"true"` +// The request to get an origin access identity's information. +type GetCloudFrontOriginAccessIdentityInput struct { + _ struct{} `locationName:"GetCloudFrontOriginAccessIdentityRequest" type:"structure"` - // The configuration ID for a field-level encryption configuration which includes - // a set of profiles that specify certain selected data fields to be encrypted - // by specific public keys. + // The identity's ID. // // Id is a required field - Id *string `type:"string" required:"true"` - - // The last time the field-level encryption configuration was changed. - // - // LastModifiedTime is a required field - LastModifiedTime *time.Time `type:"timestamp" required:"true"` + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s FieldLevelEncryption) String() string { +func (s GetCloudFrontOriginAccessIdentityInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FieldLevelEncryption) GoString() string { +func (s GetCloudFrontOriginAccessIdentityInput) GoString() string { return s.String() } -// SetFieldLevelEncryptionConfig sets the FieldLevelEncryptionConfig field's value. -func (s *FieldLevelEncryption) SetFieldLevelEncryptionConfig(v *FieldLevelEncryptionConfig) *FieldLevelEncryption { - s.FieldLevelEncryptionConfig = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetCloudFrontOriginAccessIdentityInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetCloudFrontOriginAccessIdentityInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } // SetId sets the Id field's value. -func (s *FieldLevelEncryption) SetId(v string) *FieldLevelEncryption { +func (s *GetCloudFrontOriginAccessIdentityInput) SetId(v string) *GetCloudFrontOriginAccessIdentityInput { s.Id = &v return s } -// SetLastModifiedTime sets the LastModifiedTime field's value. -func (s *FieldLevelEncryption) SetLastModifiedTime(v time.Time) *FieldLevelEncryption { - s.LastModifiedTime = &v - return s +// The returned result of the corresponding request. +type GetCloudFrontOriginAccessIdentityOutput struct { + _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentity"` + + // The origin access identity's information. + CloudFrontOriginAccessIdentity *OriginAccessIdentity `type:"structure"` + + // The current version of the origin access identity's information. For example: + // E2QWRUHAPOMQZL. + ETag *string `location:"header" locationName:"ETag" type:"string"` } -// A complex data type that includes the profile configurations specified for -// field-level encryption. -type FieldLevelEncryptionConfig struct { - _ struct{} `type:"structure"` +// String returns the string representation +func (s GetCloudFrontOriginAccessIdentityOutput) String() string { + return awsutil.Prettify(s) +} - // A unique number that ensures the request can't be replayed. - // - // CallerReference is a required field - CallerReference *string `type:"string" required:"true"` +// GoString returns the string representation +func (s GetCloudFrontOriginAccessIdentityOutput) GoString() string { + return s.String() +} - // An optional comment about the configuration. - Comment *string `type:"string"` +// SetCloudFrontOriginAccessIdentity sets the CloudFrontOriginAccessIdentity field's value. +func (s *GetCloudFrontOriginAccessIdentityOutput) SetCloudFrontOriginAccessIdentity(v *OriginAccessIdentity) *GetCloudFrontOriginAccessIdentityOutput { + s.CloudFrontOriginAccessIdentity = v + return s +} - // A complex data type that specifies when to forward content if a content type - // isn't recognized and profiles to use as by default in a request if a query - // argument doesn't specify a profile to use. - ContentTypeProfileConfig *ContentTypeProfileConfig `type:"structure"` +// SetETag sets the ETag field's value. +func (s *GetCloudFrontOriginAccessIdentityOutput) SetETag(v string) *GetCloudFrontOriginAccessIdentityOutput { + s.ETag = &v + return s +} - // A complex data type that specifies when to forward content if a profile isn't - // found and the profile that can be provided as a query argument in a request. - QueryArgProfileConfig *QueryArgProfileConfig `type:"structure"` +// The request to get a distribution configuration. +type GetDistributionConfigInput struct { + _ struct{} `locationName:"GetDistributionConfigRequest" type:"structure"` + + // The distribution's ID. If the ID is empty, an empty distribution configuration + // is returned. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s FieldLevelEncryptionConfig) String() string { +func (s GetDistributionConfigInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FieldLevelEncryptionConfig) GoString() string { +func (s GetDistributionConfigInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *FieldLevelEncryptionConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "FieldLevelEncryptionConfig"} - if s.CallerReference == nil { - invalidParams.Add(request.NewErrParamRequired("CallerReference")) - } - if s.ContentTypeProfileConfig != nil { - if err := s.ContentTypeProfileConfig.Validate(); err != nil { - invalidParams.AddNested("ContentTypeProfileConfig", err.(request.ErrInvalidParams)) - } +func (s *GetDistributionConfigInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDistributionConfigInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) } - if s.QueryArgProfileConfig != nil { - if err := s.QueryArgProfileConfig.Validate(); err != nil { - invalidParams.AddNested("QueryArgProfileConfig", err.(request.ErrInvalidParams)) - } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) } if invalidParams.Len() > 0 { @@ -8884,189 +12509,148 @@ func (s *FieldLevelEncryptionConfig) Validate() error { return nil } -// SetCallerReference sets the CallerReference field's value. -func (s *FieldLevelEncryptionConfig) SetCallerReference(v string) *FieldLevelEncryptionConfig { - s.CallerReference = &v +// SetId sets the Id field's value. +func (s *GetDistributionConfigInput) SetId(v string) *GetDistributionConfigInput { + s.Id = &v return s } -// SetComment sets the Comment field's value. -func (s *FieldLevelEncryptionConfig) SetComment(v string) *FieldLevelEncryptionConfig { - s.Comment = &v - return s -} +// The returned result of the corresponding request. +type GetDistributionConfigOutput struct { + _ struct{} `type:"structure" payload:"DistributionConfig"` -// SetContentTypeProfileConfig sets the ContentTypeProfileConfig field's value. -func (s *FieldLevelEncryptionConfig) SetContentTypeProfileConfig(v *ContentTypeProfileConfig) *FieldLevelEncryptionConfig { - s.ContentTypeProfileConfig = v - return s + // The distribution's configuration information. + DistributionConfig *DistributionConfig `type:"structure"` + + // The current version of the configuration. For example: E2QWRUHAPOMQZL. + ETag *string `location:"header" locationName:"ETag" type:"string"` } -// SetQueryArgProfileConfig sets the QueryArgProfileConfig field's value. -func (s *FieldLevelEncryptionConfig) SetQueryArgProfileConfig(v *QueryArgProfileConfig) *FieldLevelEncryptionConfig { - s.QueryArgProfileConfig = v - return s +// String returns the string representation +func (s GetDistributionConfigOutput) String() string { + return awsutil.Prettify(s) } -// List of field-level encrpytion configurations. -type FieldLevelEncryptionList struct { - _ struct{} `type:"structure"` +// GoString returns the string representation +func (s GetDistributionConfigOutput) GoString() string { + return s.String() +} - // An array of field-level encryption items. - Items []*FieldLevelEncryptionSummary `locationNameList:"FieldLevelEncryptionSummary" type:"list"` +// SetDistributionConfig sets the DistributionConfig field's value. +func (s *GetDistributionConfigOutput) SetDistributionConfig(v *DistributionConfig) *GetDistributionConfigOutput { + s.DistributionConfig = v + return s +} - // The maximum number of elements you want in the response body. - // - // MaxItems is a required field - MaxItems *int64 `type:"integer" required:"true"` +// SetETag sets the ETag field's value. +func (s *GetDistributionConfigOutput) SetETag(v string) *GetDistributionConfigOutput { + s.ETag = &v + return s +} - // If there are more elements to be listed, this element is present and contains - // the value that you can use for the Marker request parameter to continue listing - // your configurations where you left off. - NextMarker *string `type:"string"` +// The request to get a distribution's information. +type GetDistributionInput struct { + _ struct{} `locationName:"GetDistributionRequest" type:"structure"` - // The number of field-level encryption items. + // The distribution's ID. If the ID is empty, an empty distribution configuration + // is returned. // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s FieldLevelEncryptionList) String() string { +func (s GetDistributionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FieldLevelEncryptionList) GoString() string { +func (s GetDistributionInput) GoString() string { return s.String() } -// SetItems sets the Items field's value. -func (s *FieldLevelEncryptionList) SetItems(v []*FieldLevelEncryptionSummary) *FieldLevelEncryptionList { - s.Items = v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *FieldLevelEncryptionList) SetMaxItems(v int64) *FieldLevelEncryptionList { - s.MaxItems = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetDistributionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDistributionInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } -// SetNextMarker sets the NextMarker field's value. -func (s *FieldLevelEncryptionList) SetNextMarker(v string) *FieldLevelEncryptionList { - s.NextMarker = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetQuantity sets the Quantity field's value. -func (s *FieldLevelEncryptionList) SetQuantity(v int64) *FieldLevelEncryptionList { - s.Quantity = &v +// SetId sets the Id field's value. +func (s *GetDistributionInput) SetId(v string) *GetDistributionInput { + s.Id = &v return s } -// A complex data type for field-level encryption profiles. -type FieldLevelEncryptionProfile struct { - _ struct{} `type:"structure"` - - // A complex data type that includes the profile name and the encryption entities - // for the field-level encryption profile. - // - // FieldLevelEncryptionProfileConfig is a required field - FieldLevelEncryptionProfileConfig *FieldLevelEncryptionProfileConfig `type:"structure" required:"true"` +// The returned result of the corresponding request. +type GetDistributionOutput struct { + _ struct{} `type:"structure" payload:"Distribution"` - // The ID for a field-level encryption profile configuration which includes - // a set of profiles that specify certain selected data fields to be encrypted - // by specific public keys. - // - // Id is a required field - Id *string `type:"string" required:"true"` + // The distribution's information. + Distribution *Distribution `type:"structure"` - // The last time the field-level encryption profile was updated. - // - // LastModifiedTime is a required field - LastModifiedTime *time.Time `type:"timestamp" required:"true"` + // The current version of the distribution's information. For example: E2QWRUHAPOMQZL. + ETag *string `location:"header" locationName:"ETag" type:"string"` } // String returns the string representation -func (s FieldLevelEncryptionProfile) String() string { +func (s GetDistributionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FieldLevelEncryptionProfile) GoString() string { +func (s GetDistributionOutput) GoString() string { return s.String() } -// SetFieldLevelEncryptionProfileConfig sets the FieldLevelEncryptionProfileConfig field's value. -func (s *FieldLevelEncryptionProfile) SetFieldLevelEncryptionProfileConfig(v *FieldLevelEncryptionProfileConfig) *FieldLevelEncryptionProfile { - s.FieldLevelEncryptionProfileConfig = v - return s -} - -// SetId sets the Id field's value. -func (s *FieldLevelEncryptionProfile) SetId(v string) *FieldLevelEncryptionProfile { - s.Id = &v +// SetDistribution sets the Distribution field's value. +func (s *GetDistributionOutput) SetDistribution(v *Distribution) *GetDistributionOutput { + s.Distribution = v return s } -// SetLastModifiedTime sets the LastModifiedTime field's value. -func (s *FieldLevelEncryptionProfile) SetLastModifiedTime(v time.Time) *FieldLevelEncryptionProfile { - s.LastModifiedTime = &v +// SetETag sets the ETag field's value. +func (s *GetDistributionOutput) SetETag(v string) *GetDistributionOutput { + s.ETag = &v return s } -// A complex data type of profiles for the field-level encryption. -type FieldLevelEncryptionProfileConfig struct { - _ struct{} `type:"structure"` - - // A unique number that ensures that the request can't be replayed. - // - // CallerReference is a required field - CallerReference *string `type:"string" required:"true"` - - // An optional comment for the field-level encryption profile. - Comment *string `type:"string"` - - // A complex data type of encryption entities for the field-level encryption - // profile that include the public key ID, provider, and field patterns for - // specifying which fields to encrypt with this key. - // - // EncryptionEntities is a required field - EncryptionEntities *EncryptionEntities `type:"structure" required:"true"` +type GetFieldLevelEncryptionConfigInput struct { + _ struct{} `locationName:"GetFieldLevelEncryptionConfigRequest" type:"structure"` - // Profile name for the field-level encryption profile. + // Request the ID for the field-level encryption configuration information. // - // Name is a required field - Name *string `type:"string" required:"true"` + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s FieldLevelEncryptionProfileConfig) String() string { +func (s GetFieldLevelEncryptionConfigInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FieldLevelEncryptionProfileConfig) GoString() string { +func (s GetFieldLevelEncryptionConfigInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *FieldLevelEncryptionProfileConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "FieldLevelEncryptionProfileConfig"} - if s.CallerReference == nil { - invalidParams.Add(request.NewErrParamRequired("CallerReference")) - } - if s.EncryptionEntities == nil { - invalidParams.Add(request.NewErrParamRequired("EncryptionEntities")) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) +func (s *GetFieldLevelEncryptionConfigInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetFieldLevelEncryptionConfigInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) } - if s.EncryptionEntities != nil { - if err := s.EncryptionEntities.Validate(); err != nil { - invalidParams.AddNested("EncryptionEntities", err.(request.ErrInvalidParams)) - } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) } if invalidParams.Len() > 0 { @@ -9075,359 +12659,305 @@ func (s *FieldLevelEncryptionProfileConfig) Validate() error { return nil } -// SetCallerReference sets the CallerReference field's value. -func (s *FieldLevelEncryptionProfileConfig) SetCallerReference(v string) *FieldLevelEncryptionProfileConfig { - s.CallerReference = &v +// SetId sets the Id field's value. +func (s *GetFieldLevelEncryptionConfigInput) SetId(v string) *GetFieldLevelEncryptionConfigInput { + s.Id = &v return s } -// SetComment sets the Comment field's value. -func (s *FieldLevelEncryptionProfileConfig) SetComment(v string) *FieldLevelEncryptionProfileConfig { - s.Comment = &v - return s +type GetFieldLevelEncryptionConfigOutput struct { + _ struct{} `type:"structure" payload:"FieldLevelEncryptionConfig"` + + // The current version of the field level encryption configuration. For example: + // E2QWRUHAPOMQZL. + ETag *string `location:"header" locationName:"ETag" type:"string"` + + // Return the field-level encryption configuration information. + FieldLevelEncryptionConfig *FieldLevelEncryptionConfig `type:"structure"` +} + +// String returns the string representation +func (s GetFieldLevelEncryptionConfigOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetFieldLevelEncryptionConfigOutput) GoString() string { + return s.String() } -// SetEncryptionEntities sets the EncryptionEntities field's value. -func (s *FieldLevelEncryptionProfileConfig) SetEncryptionEntities(v *EncryptionEntities) *FieldLevelEncryptionProfileConfig { - s.EncryptionEntities = v +// SetETag sets the ETag field's value. +func (s *GetFieldLevelEncryptionConfigOutput) SetETag(v string) *GetFieldLevelEncryptionConfigOutput { + s.ETag = &v return s } -// SetName sets the Name field's value. -func (s *FieldLevelEncryptionProfileConfig) SetName(v string) *FieldLevelEncryptionProfileConfig { - s.Name = &v +// SetFieldLevelEncryptionConfig sets the FieldLevelEncryptionConfig field's value. +func (s *GetFieldLevelEncryptionConfigOutput) SetFieldLevelEncryptionConfig(v *FieldLevelEncryptionConfig) *GetFieldLevelEncryptionConfigOutput { + s.FieldLevelEncryptionConfig = v return s } -// List of field-level encryption profiles. -type FieldLevelEncryptionProfileList struct { - _ struct{} `type:"structure"` - - // The field-level encryption profile items. - Items []*FieldLevelEncryptionProfileSummary `locationNameList:"FieldLevelEncryptionProfileSummary" type:"list"` - - // The maximum number of field-level encryption profiles you want in the response - // body. - // - // MaxItems is a required field - MaxItems *int64 `type:"integer" required:"true"` - - // If there are more elements to be listed, this element is present and contains - // the value that you can use for the Marker request parameter to continue listing - // your profiles where you left off. - NextMarker *string `type:"string"` +type GetFieldLevelEncryptionInput struct { + _ struct{} `locationName:"GetFieldLevelEncryptionRequest" type:"structure"` - // The number of field-level encryption profiles. + // Request the ID for the field-level encryption configuration information. // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s FieldLevelEncryptionProfileList) String() string { +func (s GetFieldLevelEncryptionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FieldLevelEncryptionProfileList) GoString() string { +func (s GetFieldLevelEncryptionInput) GoString() string { return s.String() } -// SetItems sets the Items field's value. -func (s *FieldLevelEncryptionProfileList) SetItems(v []*FieldLevelEncryptionProfileSummary) *FieldLevelEncryptionProfileList { - s.Items = v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetFieldLevelEncryptionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetFieldLevelEncryptionInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } -// SetMaxItems sets the MaxItems field's value. -func (s *FieldLevelEncryptionProfileList) SetMaxItems(v int64) *FieldLevelEncryptionProfileList { - s.MaxItems = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetNextMarker sets the NextMarker field's value. -func (s *FieldLevelEncryptionProfileList) SetNextMarker(v string) *FieldLevelEncryptionProfileList { - s.NextMarker = &v +// SetId sets the Id field's value. +func (s *GetFieldLevelEncryptionInput) SetId(v string) *GetFieldLevelEncryptionInput { + s.Id = &v return s } -// SetQuantity sets the Quantity field's value. -func (s *FieldLevelEncryptionProfileList) SetQuantity(v int64) *FieldLevelEncryptionProfileList { - s.Quantity = &v - return s +type GetFieldLevelEncryptionOutput struct { + _ struct{} `type:"structure" payload:"FieldLevelEncryption"` + + // The current version of the field level encryption configuration. For example: + // E2QWRUHAPOMQZL. + ETag *string `location:"header" locationName:"ETag" type:"string"` + + // Return the field-level encryption configuration information. + FieldLevelEncryption *FieldLevelEncryption `type:"structure"` } -// The field-level encryption profile summary. -type FieldLevelEncryptionProfileSummary struct { - _ struct{} `type:"structure"` +// String returns the string representation +func (s GetFieldLevelEncryptionOutput) String() string { + return awsutil.Prettify(s) +} - // An optional comment for the field-level encryption profile summary. - Comment *string `type:"string"` +// GoString returns the string representation +func (s GetFieldLevelEncryptionOutput) GoString() string { + return s.String() +} - // A complex data type of encryption entities for the field-level encryption - // profile that include the public key ID, provider, and field patterns for - // specifying which fields to encrypt with this key. - // - // EncryptionEntities is a required field - EncryptionEntities *EncryptionEntities `type:"structure" required:"true"` +// SetETag sets the ETag field's value. +func (s *GetFieldLevelEncryptionOutput) SetETag(v string) *GetFieldLevelEncryptionOutput { + s.ETag = &v + return s +} - // ID for the field-level encryption profile summary. - // - // Id is a required field - Id *string `type:"string" required:"true"` +// SetFieldLevelEncryption sets the FieldLevelEncryption field's value. +func (s *GetFieldLevelEncryptionOutput) SetFieldLevelEncryption(v *FieldLevelEncryption) *GetFieldLevelEncryptionOutput { + s.FieldLevelEncryption = v + return s +} - // The time when the the field-level encryption profile summary was last updated. - // - // LastModifiedTime is a required field - LastModifiedTime *time.Time `type:"timestamp" required:"true"` +type GetFieldLevelEncryptionProfileConfigInput struct { + _ struct{} `locationName:"GetFieldLevelEncryptionProfileConfigRequest" type:"structure"` - // Name for the field-level encryption profile summary. + // Get the ID for the field-level encryption profile configuration information. // - // Name is a required field - Name *string `type:"string" required:"true"` + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s FieldLevelEncryptionProfileSummary) String() string { +func (s GetFieldLevelEncryptionProfileConfigInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FieldLevelEncryptionProfileSummary) GoString() string { +func (s GetFieldLevelEncryptionProfileConfigInput) GoString() string { return s.String() } -// SetComment sets the Comment field's value. -func (s *FieldLevelEncryptionProfileSummary) SetComment(v string) *FieldLevelEncryptionProfileSummary { - s.Comment = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetFieldLevelEncryptionProfileConfigInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetFieldLevelEncryptionProfileConfigInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } -// SetEncryptionEntities sets the EncryptionEntities field's value. -func (s *FieldLevelEncryptionProfileSummary) SetEncryptionEntities(v *EncryptionEntities) *FieldLevelEncryptionProfileSummary { - s.EncryptionEntities = v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } // SetId sets the Id field's value. -func (s *FieldLevelEncryptionProfileSummary) SetId(v string) *FieldLevelEncryptionProfileSummary { +func (s *GetFieldLevelEncryptionProfileConfigInput) SetId(v string) *GetFieldLevelEncryptionProfileConfigInput { s.Id = &v return s } -// SetLastModifiedTime sets the LastModifiedTime field's value. -func (s *FieldLevelEncryptionProfileSummary) SetLastModifiedTime(v time.Time) *FieldLevelEncryptionProfileSummary { - s.LastModifiedTime = &v - return s +type GetFieldLevelEncryptionProfileConfigOutput struct { + _ struct{} `type:"structure" payload:"FieldLevelEncryptionProfileConfig"` + + // The current version of the field-level encryption profile configuration result. + // For example: E2QWRUHAPOMQZL. + ETag *string `location:"header" locationName:"ETag" type:"string"` + + // Return the field-level encryption profile configuration information. + FieldLevelEncryptionProfileConfig *FieldLevelEncryptionProfileConfig `type:"structure"` } -// SetName sets the Name field's value. -func (s *FieldLevelEncryptionProfileSummary) SetName(v string) *FieldLevelEncryptionProfileSummary { - s.Name = &v - return s +// String returns the string representation +func (s GetFieldLevelEncryptionProfileConfigOutput) String() string { + return awsutil.Prettify(s) } -// A summary of a field-level encryption item. -type FieldLevelEncryptionSummary struct { - _ struct{} `type:"structure"` +// GoString returns the string representation +func (s GetFieldLevelEncryptionProfileConfigOutput) GoString() string { + return s.String() +} - // An optional comment about the field-level encryption item. - Comment *string `type:"string"` +// SetETag sets the ETag field's value. +func (s *GetFieldLevelEncryptionProfileConfigOutput) SetETag(v string) *GetFieldLevelEncryptionProfileConfigOutput { + s.ETag = &v + return s +} - // A summary of a content type-profile mapping. - ContentTypeProfileConfig *ContentTypeProfileConfig `type:"structure"` +// SetFieldLevelEncryptionProfileConfig sets the FieldLevelEncryptionProfileConfig field's value. +func (s *GetFieldLevelEncryptionProfileConfigOutput) SetFieldLevelEncryptionProfileConfig(v *FieldLevelEncryptionProfileConfig) *GetFieldLevelEncryptionProfileConfigOutput { + s.FieldLevelEncryptionProfileConfig = v + return s +} - // The unique ID of a field-level encryption item. - // - // Id is a required field - Id *string `type:"string" required:"true"` +type GetFieldLevelEncryptionProfileInput struct { + _ struct{} `locationName:"GetFieldLevelEncryptionProfileRequest" type:"structure"` - // The last time that the summary of field-level encryption items was modified. + // Get the ID for the field-level encryption profile information. // - // LastModifiedTime is a required field - LastModifiedTime *time.Time `type:"timestamp" required:"true"` - - // A summary of a query argument-profile mapping. - QueryArgProfileConfig *QueryArgProfileConfig `type:"structure"` + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s FieldLevelEncryptionSummary) String() string { +func (s GetFieldLevelEncryptionProfileInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FieldLevelEncryptionSummary) GoString() string { +func (s GetFieldLevelEncryptionProfileInput) GoString() string { return s.String() } -// SetComment sets the Comment field's value. -func (s *FieldLevelEncryptionSummary) SetComment(v string) *FieldLevelEncryptionSummary { - s.Comment = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetFieldLevelEncryptionProfileInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetFieldLevelEncryptionProfileInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } -// SetContentTypeProfileConfig sets the ContentTypeProfileConfig field's value. -func (s *FieldLevelEncryptionSummary) SetContentTypeProfileConfig(v *ContentTypeProfileConfig) *FieldLevelEncryptionSummary { - s.ContentTypeProfileConfig = v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } // SetId sets the Id field's value. -func (s *FieldLevelEncryptionSummary) SetId(v string) *FieldLevelEncryptionSummary { +func (s *GetFieldLevelEncryptionProfileInput) SetId(v string) *GetFieldLevelEncryptionProfileInput { s.Id = &v return s } -// SetLastModifiedTime sets the LastModifiedTime field's value. -func (s *FieldLevelEncryptionSummary) SetLastModifiedTime(v time.Time) *FieldLevelEncryptionSummary { - s.LastModifiedTime = &v - return s -} - -// SetQueryArgProfileConfig sets the QueryArgProfileConfig field's value. -func (s *FieldLevelEncryptionSummary) SetQueryArgProfileConfig(v *QueryArgProfileConfig) *FieldLevelEncryptionSummary { - s.QueryArgProfileConfig = v - return s -} - -// A complex data type that includes the field patterns to match for field-level -// encryption. -type FieldPatterns struct { - _ struct{} `type:"structure"` +type GetFieldLevelEncryptionProfileOutput struct { + _ struct{} `type:"structure" payload:"FieldLevelEncryptionProfile"` - // An array of the field-level encryption field patterns. - Items []*string `locationNameList:"FieldPattern" type:"list"` + // The current version of the field level encryption profile. For example: E2QWRUHAPOMQZL. + ETag *string `location:"header" locationName:"ETag" type:"string"` - // The number of field-level encryption field patterns. - // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // Return the field-level encryption profile information. + FieldLevelEncryptionProfile *FieldLevelEncryptionProfile `type:"structure"` } // String returns the string representation -func (s FieldPatterns) String() string { +func (s GetFieldLevelEncryptionProfileOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FieldPatterns) GoString() string { +func (s GetFieldLevelEncryptionProfileOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *FieldPatterns) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "FieldPatterns"} - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetItems sets the Items field's value. -func (s *FieldPatterns) SetItems(v []*string) *FieldPatterns { - s.Items = v +// SetETag sets the ETag field's value. +func (s *GetFieldLevelEncryptionProfileOutput) SetETag(v string) *GetFieldLevelEncryptionProfileOutput { + s.ETag = &v return s } -// SetQuantity sets the Quantity field's value. -func (s *FieldPatterns) SetQuantity(v int64) *FieldPatterns { - s.Quantity = &v +// SetFieldLevelEncryptionProfile sets the FieldLevelEncryptionProfile field's value. +func (s *GetFieldLevelEncryptionProfileOutput) SetFieldLevelEncryptionProfile(v *FieldLevelEncryptionProfile) *GetFieldLevelEncryptionProfileOutput { + s.FieldLevelEncryptionProfile = v return s } -// A complex type that specifies how CloudFront handles query strings, cookies, -// and HTTP headers. -type ForwardedValues struct { - _ struct{} `type:"structure"` - - // A complex type that specifies whether you want CloudFront to forward cookies - // to the origin and, if so, which ones. For more information about forwarding - // cookies to the origin, see How CloudFront Forwards, Caches, and Logs Cookies - // (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Cookies.html) - // in the Amazon CloudFront Developer Guide. - // - // Cookies is a required field - Cookies *CookiePreference `type:"structure" required:"true"` +// The request to get an invalidation's information. +type GetInvalidationInput struct { + _ struct{} `locationName:"GetInvalidationRequest" type:"structure"` - // A complex type that specifies the Headers, if any, that you want CloudFront - // to forward to the origin for this cache behavior (whitelisted headers). For - // the headers that you specify, CloudFront also caches separate versions of - // a specified object that is based on the header values in viewer requests. + // The distribution's ID. // - // For more information, see Caching Content Based on Request Headers (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html) - // in the Amazon CloudFront Developer Guide. - Headers *Headers `type:"structure"` + // DistributionId is a required field + DistributionId *string `location:"uri" locationName:"DistributionId" type:"string" required:"true"` - // Indicates whether you want CloudFront to forward query strings to the origin - // that is associated with this cache behavior and cache based on the query - // string parameters. CloudFront behavior depends on the value of QueryString - // and on the values that you specify for QueryStringCacheKeys, if any: - // - // If you specify true for QueryString and you don't specify any values for - // QueryStringCacheKeys, CloudFront forwards all query string parameters to - // the origin and caches based on all query string parameters. Depending on - // how many query string parameters and values you have, this can adversely - // affect performance because CloudFront must forward more requests to the origin. - // - // If you specify true for QueryString and you specify one or more values for - // QueryStringCacheKeys, CloudFront forwards all query string parameters to - // the origin, but it only caches based on the query string parameters that - // you specify. - // - // If you specify false for QueryString, CloudFront doesn't forward any query - // string parameters to the origin, and doesn't cache based on query string - // parameters. - // - // For more information, see Configuring CloudFront to Cache Based on Query - // String Parameters (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/QueryStringParameters.html) - // in the Amazon CloudFront Developer Guide. + // The identifier for the invalidation request, for example, IDFDVBD632BHDS5. // - // QueryString is a required field - QueryString *bool `type:"boolean" required:"true"` - - // A complex type that contains information about the query string parameters - // that you want CloudFront to use for caching for this cache behavior. - QueryStringCacheKeys *QueryStringCacheKeys `type:"structure"` + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s ForwardedValues) String() string { +func (s GetInvalidationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ForwardedValues) GoString() string { +func (s GetInvalidationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ForwardedValues) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ForwardedValues"} - if s.Cookies == nil { - invalidParams.Add(request.NewErrParamRequired("Cookies")) - } - if s.QueryString == nil { - invalidParams.Add(request.NewErrParamRequired("QueryString")) +func (s *GetInvalidationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetInvalidationInput"} + if s.DistributionId == nil { + invalidParams.Add(request.NewErrParamRequired("DistributionId")) } - if s.Cookies != nil { - if err := s.Cookies.Validate(); err != nil { - invalidParams.AddNested("Cookies", err.(request.ErrInvalidParams)) - } + if s.DistributionId != nil && len(*s.DistributionId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DistributionId", 1)) } - if s.Headers != nil { - if err := s.Headers.Validate(); err != nil { - invalidParams.AddNested("Headers", err.(request.ErrInvalidParams)) - } + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) } - if s.QueryStringCacheKeys != nil { - if err := s.QueryStringCacheKeys.Validate(); err != nil { - invalidParams.AddNested("QueryStringCacheKeys", err.(request.ErrInvalidParams)) - } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) } if invalidParams.Len() > 0 { @@ -9436,91 +12966,74 @@ func (s *ForwardedValues) Validate() error { return nil } -// SetCookies sets the Cookies field's value. -func (s *ForwardedValues) SetCookies(v *CookiePreference) *ForwardedValues { - s.Cookies = v +// SetDistributionId sets the DistributionId field's value. +func (s *GetInvalidationInput) SetDistributionId(v string) *GetInvalidationInput { + s.DistributionId = &v return s } -// SetHeaders sets the Headers field's value. -func (s *ForwardedValues) SetHeaders(v *Headers) *ForwardedValues { - s.Headers = v +// SetId sets the Id field's value. +func (s *GetInvalidationInput) SetId(v string) *GetInvalidationInput { + s.Id = &v return s } -// SetQueryString sets the QueryString field's value. -func (s *ForwardedValues) SetQueryString(v bool) *ForwardedValues { - s.QueryString = &v - return s +// The returned result of the corresponding request. +type GetInvalidationOutput struct { + _ struct{} `type:"structure" payload:"Invalidation"` + + // The invalidation's information. For more information, see Invalidation Complex + // Type (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/InvalidationDatatype.html). + Invalidation *Invalidation `type:"structure"` } -// SetQueryStringCacheKeys sets the QueryStringCacheKeys field's value. -func (s *ForwardedValues) SetQueryStringCacheKeys(v *QueryStringCacheKeys) *ForwardedValues { - s.QueryStringCacheKeys = v - return s +// String returns the string representation +func (s GetInvalidationOutput) String() string { + return awsutil.Prettify(s) } -// A complex type that controls the countries in which your content is distributed. -// CloudFront determines the location of your users using MaxMind GeoIP databases. -type GeoRestriction struct { - _ struct{} `type:"structure"` +// GoString returns the string representation +func (s GetInvalidationOutput) GoString() string { + return s.String() +} - // A complex type that contains a Location element for each country in which - // you want CloudFront either to distribute your content (whitelist) or not - // distribute your content (blacklist). - // - // The Location element is a two-letter, uppercase country code for a country - // that you want to include in your blacklist or whitelist. Include one Location - // element for each country. - // - // CloudFront and MaxMind both use ISO 3166 country codes. For the current list - // of countries and the corresponding codes, see ISO 3166-1-alpha-2 code on - // the International Organization for Standardization website. You can also - // refer to the country list on the CloudFront console, which includes both - // country names and codes. - Items []*string `locationNameList:"Location" type:"list"` +// SetInvalidation sets the Invalidation field's value. +func (s *GetInvalidationOutput) SetInvalidation(v *Invalidation) *GetInvalidationOutput { + s.Invalidation = v + return s +} - // When geo restriction is enabled, this is the number of countries in your - // whitelist or blacklist. Otherwise, when it is not enabled, Quantity is 0, - // and you can omit Items. - // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` +type GetOriginRequestPolicyConfigInput struct { + _ struct{} `locationName:"GetOriginRequestPolicyConfigRequest" type:"structure"` - // The method that you want to use to restrict distribution of your content - // by country: - // - // * none: No geo restriction is enabled, meaning access to content is not - // restricted by client geo location. - // - // * blacklist: The Location elements specify the countries in which you - // don't want CloudFront to distribute your content. - // - // * whitelist: The Location elements specify the countries in which you - // want CloudFront to distribute your content. + // The unique identifier for the origin request policy. If the origin request + // policy is attached to a distribution’s cache behavior, you can get the + // policy’s identifier using ListDistributions or GetDistribution. If the + // origin request policy is not attached to a cache behavior, you can get the + // identifier using ListOriginRequestPolicies. // - // RestrictionType is a required field - RestrictionType *string `type:"string" required:"true" enum:"GeoRestrictionType"` + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s GeoRestriction) String() string { +func (s GetOriginRequestPolicyConfigInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GeoRestriction) GoString() string { +func (s GetOriginRequestPolicyConfigInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GeoRestriction) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GeoRestriction"} - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) +func (s *GetOriginRequestPolicyConfigInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetOriginRequestPolicyConfigInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) } - if s.RestrictionType == nil { - invalidParams.Add(request.NewErrParamRequired("RestrictionType")) + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) } if invalidParams.Len() > 0 { @@ -9529,48 +13042,70 @@ func (s *GeoRestriction) Validate() error { return nil } -// SetItems sets the Items field's value. -func (s *GeoRestriction) SetItems(v []*string) *GeoRestriction { - s.Items = v +// SetId sets the Id field's value. +func (s *GetOriginRequestPolicyConfigInput) SetId(v string) *GetOriginRequestPolicyConfigInput { + s.Id = &v return s } -// SetQuantity sets the Quantity field's value. -func (s *GeoRestriction) SetQuantity(v int64) *GeoRestriction { - s.Quantity = &v +type GetOriginRequestPolicyConfigOutput struct { + _ struct{} `type:"structure" payload:"OriginRequestPolicyConfig"` + + // The current version of the origin request policy. + ETag *string `location:"header" locationName:"ETag" type:"string"` + + // The origin request policy configuration. + OriginRequestPolicyConfig *OriginRequestPolicyConfig `type:"structure"` +} + +// String returns the string representation +func (s GetOriginRequestPolicyConfigOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetOriginRequestPolicyConfigOutput) GoString() string { + return s.String() +} + +// SetETag sets the ETag field's value. +func (s *GetOriginRequestPolicyConfigOutput) SetETag(v string) *GetOriginRequestPolicyConfigOutput { + s.ETag = &v return s } -// SetRestrictionType sets the RestrictionType field's value. -func (s *GeoRestriction) SetRestrictionType(v string) *GeoRestriction { - s.RestrictionType = &v +// SetOriginRequestPolicyConfig sets the OriginRequestPolicyConfig field's value. +func (s *GetOriginRequestPolicyConfigOutput) SetOriginRequestPolicyConfig(v *OriginRequestPolicyConfig) *GetOriginRequestPolicyConfigOutput { + s.OriginRequestPolicyConfig = v return s } -// The origin access identity's configuration information. For more information, -// see CloudFrontOriginAccessIdentityConfig (https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CloudFrontOriginAccessIdentityConfig.html). -type GetCloudFrontOriginAccessIdentityConfigInput struct { - _ struct{} `locationName:"GetCloudFrontOriginAccessIdentityConfigRequest" type:"structure"` +type GetOriginRequestPolicyInput struct { + _ struct{} `locationName:"GetOriginRequestPolicyRequest" type:"structure"` - // The identity's ID. + // The unique identifier for the origin request policy. If the origin request + // policy is attached to a distribution’s cache behavior, you can get the + // policy’s identifier using ListDistributions or GetDistribution. If the + // origin request policy is not attached to a cache behavior, you can get the + // identifier using ListOriginRequestPolicies. // // Id is a required field Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s GetCloudFrontOriginAccessIdentityConfigInput) String() string { +func (s GetOriginRequestPolicyInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetCloudFrontOriginAccessIdentityConfigInput) GoString() string { +func (s GetOriginRequestPolicyInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetCloudFrontOriginAccessIdentityConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetCloudFrontOriginAccessIdentityConfigInput"} +func (s *GetOriginRequestPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetOriginRequestPolicyInput"} if s.Id == nil { invalidParams.Add(request.NewErrParamRequired("Id")) } @@ -9585,67 +13120,65 @@ func (s *GetCloudFrontOriginAccessIdentityConfigInput) Validate() error { } // SetId sets the Id field's value. -func (s *GetCloudFrontOriginAccessIdentityConfigInput) SetId(v string) *GetCloudFrontOriginAccessIdentityConfigInput { +func (s *GetOriginRequestPolicyInput) SetId(v string) *GetOriginRequestPolicyInput { s.Id = &v return s } -// The returned result of the corresponding request. -type GetCloudFrontOriginAccessIdentityConfigOutput struct { - _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentityConfig"` - - // The origin access identity's configuration information. - CloudFrontOriginAccessIdentityConfig *OriginAccessIdentityConfig `type:"structure"` +type GetOriginRequestPolicyOutput struct { + _ struct{} `type:"structure" payload:"OriginRequestPolicy"` - // The current version of the configuration. For example: E2QWRUHAPOMQZL. + // The current version of the origin request policy. ETag *string `location:"header" locationName:"ETag" type:"string"` + + // The origin request policy. + OriginRequestPolicy *OriginRequestPolicy `type:"structure"` } // String returns the string representation -func (s GetCloudFrontOriginAccessIdentityConfigOutput) String() string { +func (s GetOriginRequestPolicyOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetCloudFrontOriginAccessIdentityConfigOutput) GoString() string { +func (s GetOriginRequestPolicyOutput) GoString() string { return s.String() } -// SetCloudFrontOriginAccessIdentityConfig sets the CloudFrontOriginAccessIdentityConfig field's value. -func (s *GetCloudFrontOriginAccessIdentityConfigOutput) SetCloudFrontOriginAccessIdentityConfig(v *OriginAccessIdentityConfig) *GetCloudFrontOriginAccessIdentityConfigOutput { - s.CloudFrontOriginAccessIdentityConfig = v +// SetETag sets the ETag field's value. +func (s *GetOriginRequestPolicyOutput) SetETag(v string) *GetOriginRequestPolicyOutput { + s.ETag = &v return s } -// SetETag sets the ETag field's value. -func (s *GetCloudFrontOriginAccessIdentityConfigOutput) SetETag(v string) *GetCloudFrontOriginAccessIdentityConfigOutput { - s.ETag = &v +// SetOriginRequestPolicy sets the OriginRequestPolicy field's value. +func (s *GetOriginRequestPolicyOutput) SetOriginRequestPolicy(v *OriginRequestPolicy) *GetOriginRequestPolicyOutput { + s.OriginRequestPolicy = v return s } -// The request to get an origin access identity's information. -type GetCloudFrontOriginAccessIdentityInput struct { - _ struct{} `locationName:"GetCloudFrontOriginAccessIdentityRequest" type:"structure"` +type GetPublicKeyConfigInput struct { + _ struct{} `locationName:"GetPublicKeyConfigRequest" type:"structure"` - // The identity's ID. + // Request the ID for the public key configuration. // // Id is a required field Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s GetCloudFrontOriginAccessIdentityInput) String() string { +func (s GetPublicKeyConfigInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetCloudFrontOriginAccessIdentityInput) GoString() string { +func (s GetPublicKeyConfigInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetCloudFrontOriginAccessIdentityInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetCloudFrontOriginAccessIdentityInput"} +func (s *GetPublicKeyConfigInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetPublicKeyConfigInput"} if s.Id == nil { invalidParams.Add(request.NewErrParamRequired("Id")) } @@ -9660,69 +13193,65 @@ func (s *GetCloudFrontOriginAccessIdentityInput) Validate() error { } // SetId sets the Id field's value. -func (s *GetCloudFrontOriginAccessIdentityInput) SetId(v string) *GetCloudFrontOriginAccessIdentityInput { +func (s *GetPublicKeyConfigInput) SetId(v string) *GetPublicKeyConfigInput { s.Id = &v return s } -// The returned result of the corresponding request. -type GetCloudFrontOriginAccessIdentityOutput struct { - _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentity"` - - // The origin access identity's information. - CloudFrontOriginAccessIdentity *OriginAccessIdentity `type:"structure"` +type GetPublicKeyConfigOutput struct { + _ struct{} `type:"structure" payload:"PublicKeyConfig"` - // The current version of the origin access identity's information. For example: - // E2QWRUHAPOMQZL. + // The current version of the public key configuration. For example: E2QWRUHAPOMQZL. ETag *string `location:"header" locationName:"ETag" type:"string"` + + // Return the result for the public key configuration. + PublicKeyConfig *PublicKeyConfig `type:"structure"` } // String returns the string representation -func (s GetCloudFrontOriginAccessIdentityOutput) String() string { +func (s GetPublicKeyConfigOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetCloudFrontOriginAccessIdentityOutput) GoString() string { +func (s GetPublicKeyConfigOutput) GoString() string { return s.String() } -// SetCloudFrontOriginAccessIdentity sets the CloudFrontOriginAccessIdentity field's value. -func (s *GetCloudFrontOriginAccessIdentityOutput) SetCloudFrontOriginAccessIdentity(v *OriginAccessIdentity) *GetCloudFrontOriginAccessIdentityOutput { - s.CloudFrontOriginAccessIdentity = v +// SetETag sets the ETag field's value. +func (s *GetPublicKeyConfigOutput) SetETag(v string) *GetPublicKeyConfigOutput { + s.ETag = &v return s } -// SetETag sets the ETag field's value. -func (s *GetCloudFrontOriginAccessIdentityOutput) SetETag(v string) *GetCloudFrontOriginAccessIdentityOutput { - s.ETag = &v +// SetPublicKeyConfig sets the PublicKeyConfig field's value. +func (s *GetPublicKeyConfigOutput) SetPublicKeyConfig(v *PublicKeyConfig) *GetPublicKeyConfigOutput { + s.PublicKeyConfig = v return s } -// The request to get a distribution configuration. -type GetDistributionConfigInput struct { - _ struct{} `locationName:"GetDistributionConfigRequest" type:"structure"` +type GetPublicKeyInput struct { + _ struct{} `locationName:"GetPublicKeyRequest" type:"structure"` - // The distribution's ID. If the ID is empty, an empty distribution configuration - // is returned. + // Request the ID for the public key. // // Id is a required field Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s GetDistributionConfigInput) String() string { +func (s GetPublicKeyInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDistributionConfigInput) GoString() string { +func (s GetPublicKeyInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetDistributionConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDistributionConfigInput"} +func (s *GetPublicKeyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetPublicKeyInput"} if s.Id == nil { invalidParams.Add(request.NewErrParamRequired("Id")) } @@ -9737,68 +13266,66 @@ func (s *GetDistributionConfigInput) Validate() error { } // SetId sets the Id field's value. -func (s *GetDistributionConfigInput) SetId(v string) *GetDistributionConfigInput { +func (s *GetPublicKeyInput) SetId(v string) *GetPublicKeyInput { s.Id = &v return s } -// The returned result of the corresponding request. -type GetDistributionConfigOutput struct { - _ struct{} `type:"structure" payload:"DistributionConfig"` - - // The distribution's configuration information. - DistributionConfig *DistributionConfig `type:"structure"` +type GetPublicKeyOutput struct { + _ struct{} `type:"structure" payload:"PublicKey"` - // The current version of the configuration. For example: E2QWRUHAPOMQZL. + // The current version of the public key. For example: E2QWRUHAPOMQZL. ETag *string `location:"header" locationName:"ETag" type:"string"` + + // Return the public key. + PublicKey *PublicKey `type:"structure"` } // String returns the string representation -func (s GetDistributionConfigOutput) String() string { +func (s GetPublicKeyOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDistributionConfigOutput) GoString() string { +func (s GetPublicKeyOutput) GoString() string { return s.String() } -// SetDistributionConfig sets the DistributionConfig field's value. -func (s *GetDistributionConfigOutput) SetDistributionConfig(v *DistributionConfig) *GetDistributionConfigOutput { - s.DistributionConfig = v +// SetETag sets the ETag field's value. +func (s *GetPublicKeyOutput) SetETag(v string) *GetPublicKeyOutput { + s.ETag = &v return s } -// SetETag sets the ETag field's value. -func (s *GetDistributionConfigOutput) SetETag(v string) *GetDistributionConfigOutput { - s.ETag = &v +// SetPublicKey sets the PublicKey field's value. +func (s *GetPublicKeyOutput) SetPublicKey(v *PublicKey) *GetPublicKeyOutput { + s.PublicKey = v return s } -// The request to get a distribution's information. -type GetDistributionInput struct { - _ struct{} `locationName:"GetDistributionRequest" type:"structure"` +// To request to get a streaming distribution configuration. +type GetStreamingDistributionConfigInput struct { + _ struct{} `locationName:"GetStreamingDistributionConfigRequest" type:"structure"` - // The distribution's ID. If the ID is empty, an empty distribution configuration - // is returned. + // The streaming distribution's ID. // // Id is a required field Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s GetDistributionInput) String() string { +func (s GetStreamingDistributionConfigInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDistributionInput) GoString() string { +func (s GetStreamingDistributionConfigInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetDistributionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDistributionInput"} +func (s *GetStreamingDistributionConfigInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetStreamingDistributionConfigInput"} if s.Id == nil { invalidParams.Add(request.NewErrParamRequired("Id")) } @@ -9813,66 +13340,67 @@ func (s *GetDistributionInput) Validate() error { } // SetId sets the Id field's value. -func (s *GetDistributionInput) SetId(v string) *GetDistributionInput { +func (s *GetStreamingDistributionConfigInput) SetId(v string) *GetStreamingDistributionConfigInput { s.Id = &v return s } // The returned result of the corresponding request. -type GetDistributionOutput struct { - _ struct{} `type:"structure" payload:"Distribution"` - - // The distribution's information. - Distribution *Distribution `type:"structure"` +type GetStreamingDistributionConfigOutput struct { + _ struct{} `type:"structure" payload:"StreamingDistributionConfig"` - // The current version of the distribution's information. For example: E2QWRUHAPOMQZL. + // The current version of the configuration. For example: E2QWRUHAPOMQZL. ETag *string `location:"header" locationName:"ETag" type:"string"` + + // The streaming distribution's configuration information. + StreamingDistributionConfig *StreamingDistributionConfig `type:"structure"` } // String returns the string representation -func (s GetDistributionOutput) String() string { +func (s GetStreamingDistributionConfigOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDistributionOutput) GoString() string { +func (s GetStreamingDistributionConfigOutput) GoString() string { return s.String() } -// SetDistribution sets the Distribution field's value. -func (s *GetDistributionOutput) SetDistribution(v *Distribution) *GetDistributionOutput { - s.Distribution = v +// SetETag sets the ETag field's value. +func (s *GetStreamingDistributionConfigOutput) SetETag(v string) *GetStreamingDistributionConfigOutput { + s.ETag = &v return s } -// SetETag sets the ETag field's value. -func (s *GetDistributionOutput) SetETag(v string) *GetDistributionOutput { - s.ETag = &v +// SetStreamingDistributionConfig sets the StreamingDistributionConfig field's value. +func (s *GetStreamingDistributionConfigOutput) SetStreamingDistributionConfig(v *StreamingDistributionConfig) *GetStreamingDistributionConfigOutput { + s.StreamingDistributionConfig = v return s } -type GetFieldLevelEncryptionConfigInput struct { - _ struct{} `locationName:"GetFieldLevelEncryptionConfigRequest" type:"structure"` +// The request to get a streaming distribution's information. +type GetStreamingDistributionInput struct { + _ struct{} `locationName:"GetStreamingDistributionRequest" type:"structure"` - // Request the ID for the field-level encryption configuration information. + // The streaming distribution's ID. // // Id is a required field Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` } // String returns the string representation -func (s GetFieldLevelEncryptionConfigInput) String() string { +func (s GetStreamingDistributionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetFieldLevelEncryptionConfigInput) GoString() string { +func (s GetStreamingDistributionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetFieldLevelEncryptionConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetFieldLevelEncryptionConfigInput"} +func (s *GetStreamingDistributionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetStreamingDistributionInput"} if s.Id == nil { invalidParams.Add(request.NewErrParamRequired("Id")) } @@ -9887,71 +13415,73 @@ func (s *GetFieldLevelEncryptionConfigInput) Validate() error { } // SetId sets the Id field's value. -func (s *GetFieldLevelEncryptionConfigInput) SetId(v string) *GetFieldLevelEncryptionConfigInput { +func (s *GetStreamingDistributionInput) SetId(v string) *GetStreamingDistributionInput { s.Id = &v return s } -type GetFieldLevelEncryptionConfigOutput struct { - _ struct{} `type:"structure" payload:"FieldLevelEncryptionConfig"` +// The returned result of the corresponding request. +type GetStreamingDistributionOutput struct { + _ struct{} `type:"structure" payload:"StreamingDistribution"` - // The current version of the field level encryption configuration. For example: + // The current version of the streaming distribution's information. For example: // E2QWRUHAPOMQZL. ETag *string `location:"header" locationName:"ETag" type:"string"` - // Return the field-level encryption configuration information. - FieldLevelEncryptionConfig *FieldLevelEncryptionConfig `type:"structure"` + // The streaming distribution's information. + StreamingDistribution *StreamingDistribution `type:"structure"` } // String returns the string representation -func (s GetFieldLevelEncryptionConfigOutput) String() string { +func (s GetStreamingDistributionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetFieldLevelEncryptionConfigOutput) GoString() string { +func (s GetStreamingDistributionOutput) GoString() string { return s.String() } // SetETag sets the ETag field's value. -func (s *GetFieldLevelEncryptionConfigOutput) SetETag(v string) *GetFieldLevelEncryptionConfigOutput { +func (s *GetStreamingDistributionOutput) SetETag(v string) *GetStreamingDistributionOutput { s.ETag = &v return s } -// SetFieldLevelEncryptionConfig sets the FieldLevelEncryptionConfig field's value. -func (s *GetFieldLevelEncryptionConfigOutput) SetFieldLevelEncryptionConfig(v *FieldLevelEncryptionConfig) *GetFieldLevelEncryptionConfigOutput { - s.FieldLevelEncryptionConfig = v +// SetStreamingDistribution sets the StreamingDistribution field's value. +func (s *GetStreamingDistributionOutput) SetStreamingDistribution(v *StreamingDistribution) *GetStreamingDistributionOutput { + s.StreamingDistribution = v return s } -type GetFieldLevelEncryptionInput struct { - _ struct{} `locationName:"GetFieldLevelEncryptionRequest" type:"structure"` +// Contains a list of HTTP header names. +type Headers struct { + _ struct{} `type:"structure"` - // Request the ID for the field-level encryption configuration information. + // A list of HTTP header names. + Items []*string `locationNameList:"Name" type:"list"` + + // The number of header names in the Items list. // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s GetFieldLevelEncryptionInput) String() string { +func (s Headers) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetFieldLevelEncryptionInput) GoString() string { +func (s Headers) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetFieldLevelEncryptionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetFieldLevelEncryptionInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) +func (s *Headers) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Headers"} + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) } if invalidParams.Len() > 0 { @@ -9960,72 +13490,133 @@ func (s *GetFieldLevelEncryptionInput) Validate() error { return nil } -// SetId sets the Id field's value. -func (s *GetFieldLevelEncryptionInput) SetId(v string) *GetFieldLevelEncryptionInput { - s.Id = &v +// SetItems sets the Items field's value. +func (s *Headers) SetItems(v []*string) *Headers { + s.Items = v return s } -type GetFieldLevelEncryptionOutput struct { - _ struct{} `type:"structure" payload:"FieldLevelEncryption"` +// SetQuantity sets the Quantity field's value. +func (s *Headers) SetQuantity(v int64) *Headers { + s.Quantity = &v + return s +} - // The current version of the field level encryption configuration. For example: - // E2QWRUHAPOMQZL. - ETag *string `location:"header" locationName:"ETag" type:"string"` +// An invalidation. +type Invalidation struct { + _ struct{} `type:"structure"` + + // The date and time the invalidation request was first made. + // + // CreateTime is a required field + CreateTime *time.Time `type:"timestamp" required:"true"` + + // The identifier for the invalidation request. For example: IDFDVBD632BHDS5. + // + // Id is a required field + Id *string `type:"string" required:"true"` + + // The current invalidation information for the batch request. + // + // InvalidationBatch is a required field + InvalidationBatch *InvalidationBatch `type:"structure" required:"true"` - // Return the field-level encryption configuration information. - FieldLevelEncryption *FieldLevelEncryption `type:"structure"` + // The status of the invalidation request. When the invalidation batch is finished, + // the status is Completed. + // + // Status is a required field + Status *string `type:"string" required:"true"` } // String returns the string representation -func (s GetFieldLevelEncryptionOutput) String() string { +func (s Invalidation) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetFieldLevelEncryptionOutput) GoString() string { +func (s Invalidation) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *GetFieldLevelEncryptionOutput) SetETag(v string) *GetFieldLevelEncryptionOutput { - s.ETag = &v +// SetCreateTime sets the CreateTime field's value. +func (s *Invalidation) SetCreateTime(v time.Time) *Invalidation { + s.CreateTime = &v return s } -// SetFieldLevelEncryption sets the FieldLevelEncryption field's value. -func (s *GetFieldLevelEncryptionOutput) SetFieldLevelEncryption(v *FieldLevelEncryption) *GetFieldLevelEncryptionOutput { - s.FieldLevelEncryption = v +// SetId sets the Id field's value. +func (s *Invalidation) SetId(v string) *Invalidation { + s.Id = &v return s } -type GetFieldLevelEncryptionProfileConfigInput struct { - _ struct{} `locationName:"GetFieldLevelEncryptionProfileConfigRequest" type:"structure"` +// SetInvalidationBatch sets the InvalidationBatch field's value. +func (s *Invalidation) SetInvalidationBatch(v *InvalidationBatch) *Invalidation { + s.InvalidationBatch = v + return s +} - // Get the ID for the field-level encryption profile configuration information. +// SetStatus sets the Status field's value. +func (s *Invalidation) SetStatus(v string) *Invalidation { + s.Status = &v + return s +} + +// An invalidation batch. +type InvalidationBatch struct { + _ struct{} `type:"structure"` + + // A value that you specify to uniquely identify an invalidation request. CloudFront + // uses the value to prevent you from accidentally resubmitting an identical + // request. Whenever you create a new invalidation request, you must specify + // a new value for CallerReference and change other values in the request as + // applicable. One way to ensure that the value of CallerReference is unique + // is to use a timestamp, for example, 20120301090000. // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + // If you make a second invalidation request with the same value for CallerReference, + // and if the rest of the request is the same, CloudFront doesn't create a new + // invalidation request. Instead, CloudFront returns information about the invalidation + // request that you previously created with the same CallerReference. + // + // If CallerReference is a value you already sent in a previous invalidation + // batch request but the content of any Path is different from the original + // request, CloudFront returns an InvalidationBatchAlreadyExists error. + // + // CallerReference is a required field + CallerReference *string `type:"string" required:"true"` + + // A complex type that contains information about the objects that you want + // to invalidate. For more information, see Specifying the Objects to Invalidate + // (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#invalidation-specifying-objects) + // in the Amazon CloudFront Developer Guide. + // + // Paths is a required field + Paths *Paths `type:"structure" required:"true"` } // String returns the string representation -func (s GetFieldLevelEncryptionProfileConfigInput) String() string { +func (s InvalidationBatch) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetFieldLevelEncryptionProfileConfigInput) GoString() string { +func (s InvalidationBatch) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetFieldLevelEncryptionProfileConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetFieldLevelEncryptionProfileConfigInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) +func (s *InvalidationBatch) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InvalidationBatch"} + if s.CallerReference == nil { + invalidParams.Add(request.NewErrParamRequired("CallerReference")) } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + if s.Paths == nil { + invalidParams.Add(request.NewErrParamRequired("Paths")) + } + if s.Paths != nil { + if err := s.Paths.Validate(); err != nil { + invalidParams.AddNested("Paths", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -10034,157 +13625,253 @@ func (s *GetFieldLevelEncryptionProfileConfigInput) Validate() error { return nil } -// SetId sets the Id field's value. -func (s *GetFieldLevelEncryptionProfileConfigInput) SetId(v string) *GetFieldLevelEncryptionProfileConfigInput { - s.Id = &v +// SetCallerReference sets the CallerReference field's value. +func (s *InvalidationBatch) SetCallerReference(v string) *InvalidationBatch { + s.CallerReference = &v return s } -type GetFieldLevelEncryptionProfileConfigOutput struct { - _ struct{} `type:"structure" payload:"FieldLevelEncryptionProfileConfig"` +// SetPaths sets the Paths field's value. +func (s *InvalidationBatch) SetPaths(v *Paths) *InvalidationBatch { + s.Paths = v + return s +} - // The current version of the field-level encryption profile configuration result. - // For example: E2QWRUHAPOMQZL. - ETag *string `location:"header" locationName:"ETag" type:"string"` +// The InvalidationList complex type describes the list of invalidation objects. +// For more information about invalidation, see Invalidating Objects (Web Distributions +// Only) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html) +// in the Amazon CloudFront Developer Guide. +type InvalidationList struct { + _ struct{} `type:"structure"` - // Return the field-level encryption profile configuration information. - FieldLevelEncryptionProfileConfig *FieldLevelEncryptionProfileConfig `type:"structure"` + // A flag that indicates whether more invalidation batch requests remain to + // be listed. If your results were truncated, you can make a follow-up pagination + // request using the Marker request parameter to retrieve more invalidation + // batches in the list. + // + // IsTruncated is a required field + IsTruncated *bool `type:"boolean" required:"true"` + + // A complex type that contains one InvalidationSummary element for each invalidation + // batch created by the current AWS account. + Items []*InvalidationSummary `locationNameList:"InvalidationSummary" type:"list"` + + // The value that you provided for the Marker request parameter. + // + // Marker is a required field + Marker *string `type:"string" required:"true"` + + // The value that you provided for the MaxItems request parameter. + // + // MaxItems is a required field + MaxItems *int64 `type:"integer" required:"true"` + + // If IsTruncated is true, this element is present and contains the value that + // you can use for the Marker request parameter to continue listing your invalidation + // batches where they left off. + NextMarker *string `type:"string"` + + // The number of invalidation batches that were created by the current AWS account. + // + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s GetFieldLevelEncryptionProfileConfigOutput) String() string { +func (s InvalidationList) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetFieldLevelEncryptionProfileConfigOutput) GoString() string { +func (s InvalidationList) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *GetFieldLevelEncryptionProfileConfigOutput) SetETag(v string) *GetFieldLevelEncryptionProfileConfigOutput { - s.ETag = &v +// SetIsTruncated sets the IsTruncated field's value. +func (s *InvalidationList) SetIsTruncated(v bool) *InvalidationList { + s.IsTruncated = &v return s } -// SetFieldLevelEncryptionProfileConfig sets the FieldLevelEncryptionProfileConfig field's value. -func (s *GetFieldLevelEncryptionProfileConfigOutput) SetFieldLevelEncryptionProfileConfig(v *FieldLevelEncryptionProfileConfig) *GetFieldLevelEncryptionProfileConfigOutput { - s.FieldLevelEncryptionProfileConfig = v +// SetItems sets the Items field's value. +func (s *InvalidationList) SetItems(v []*InvalidationSummary) *InvalidationList { + s.Items = v return s } -type GetFieldLevelEncryptionProfileInput struct { - _ struct{} `locationName:"GetFieldLevelEncryptionProfileRequest" type:"structure"` +// SetMarker sets the Marker field's value. +func (s *InvalidationList) SetMarker(v string) *InvalidationList { + s.Marker = &v + return s +} - // Get the ID for the field-level encryption profile information. +// SetMaxItems sets the MaxItems field's value. +func (s *InvalidationList) SetMaxItems(v int64) *InvalidationList { + s.MaxItems = &v + return s +} + +// SetNextMarker sets the NextMarker field's value. +func (s *InvalidationList) SetNextMarker(v string) *InvalidationList { + s.NextMarker = &v + return s +} + +// SetQuantity sets the Quantity field's value. +func (s *InvalidationList) SetQuantity(v int64) *InvalidationList { + s.Quantity = &v + return s +} + +// A summary of an invalidation request. +type InvalidationSummary struct { + _ struct{} `type:"structure"` + + // The time that an invalidation request was created. + // + // CreateTime is a required field + CreateTime *time.Time `type:"timestamp" required:"true"` + + // The unique ID for an invalidation request. // // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + Id *string `type:"string" required:"true"` + + // The status of an invalidation request. + // + // Status is a required field + Status *string `type:"string" required:"true"` } // String returns the string representation -func (s GetFieldLevelEncryptionProfileInput) String() string { +func (s InvalidationSummary) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetFieldLevelEncryptionProfileInput) GoString() string { +func (s InvalidationSummary) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetFieldLevelEncryptionProfileInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetFieldLevelEncryptionProfileInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCreateTime sets the CreateTime field's value. +func (s *InvalidationSummary) SetCreateTime(v time.Time) *InvalidationSummary { + s.CreateTime = &v + return s } // SetId sets the Id field's value. -func (s *GetFieldLevelEncryptionProfileInput) SetId(v string) *GetFieldLevelEncryptionProfileInput { +func (s *InvalidationSummary) SetId(v string) *InvalidationSummary { s.Id = &v return s } -type GetFieldLevelEncryptionProfileOutput struct { - _ struct{} `type:"structure" payload:"FieldLevelEncryptionProfile"` +// SetStatus sets the Status field's value. +func (s *InvalidationSummary) SetStatus(v string) *InvalidationSummary { + s.Status = &v + return s +} - // The current version of the field level encryption profile. For example: E2QWRUHAPOMQZL. - ETag *string `location:"header" locationName:"ETag" type:"string"` +// A complex type that lists the active CloudFront key pairs, if any, that are +// associated with AwsAccountNumber. +// +// For more information, see ActiveTrustedSigners (https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ActiveTrustedSigners.html). +type KeyPairIds struct { + _ struct{} `type:"structure"` - // Return the field-level encryption profile information. - FieldLevelEncryptionProfile *FieldLevelEncryptionProfile `type:"structure"` + // A complex type that lists the active CloudFront key pairs, if any, that are + // associated with AwsAccountNumber. + // + // For more information, see ActiveTrustedSigners (https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ActiveTrustedSigners.html). + Items []*string `locationNameList:"KeyPairId" type:"list"` + + // The number of active CloudFront key pairs for AwsAccountNumber. + // + // For more information, see ActiveTrustedSigners (https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ActiveTrustedSigners.html). + // + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s GetFieldLevelEncryptionProfileOutput) String() string { +func (s KeyPairIds) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetFieldLevelEncryptionProfileOutput) GoString() string { +func (s KeyPairIds) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *GetFieldLevelEncryptionProfileOutput) SetETag(v string) *GetFieldLevelEncryptionProfileOutput { - s.ETag = &v +// SetItems sets the Items field's value. +func (s *KeyPairIds) SetItems(v []*string) *KeyPairIds { + s.Items = v return s } -// SetFieldLevelEncryptionProfile sets the FieldLevelEncryptionProfile field's value. -func (s *GetFieldLevelEncryptionProfileOutput) SetFieldLevelEncryptionProfile(v *FieldLevelEncryptionProfile) *GetFieldLevelEncryptionProfileOutput { - s.FieldLevelEncryptionProfile = v +// SetQuantity sets the Quantity field's value. +func (s *KeyPairIds) SetQuantity(v int64) *KeyPairIds { + s.Quantity = &v return s } -// The request to get an invalidation's information. -type GetInvalidationInput struct { - _ struct{} `locationName:"GetInvalidationRequest" type:"structure"` +// A complex type that contains a Lambda function association. +type LambdaFunctionAssociation struct { + _ struct{} `type:"structure"` - // The distribution's ID. + // Specifies the event type that triggers a Lambda function invocation. You + // can specify the following values: // - // DistributionId is a required field - DistributionId *string `location:"uri" locationName:"DistributionId" type:"string" required:"true"` + // * viewer-request: The function executes when CloudFront receives a request + // from a viewer and before it checks to see whether the requested object + // is in the edge cache. + // + // * origin-request: The function executes only when CloudFront sends a request + // to your origin. When the requested object is in the edge cache, the function + // doesn't execute. + // + // * origin-response: The function executes after CloudFront receives a response + // from the origin and before it caches the object in the response. When + // the requested object is in the edge cache, the function doesn't execute. + // + // * viewer-response: The function executes before CloudFront returns the + // requested object to the viewer. The function executes regardless of whether + // the object was already in the edge cache. If the origin returns an HTTP + // status code other than HTTP 200 (OK), the function doesn't execute. + // + // EventType is a required field + EventType *string `type:"string" required:"true" enum:"EventType"` - // The identifier for the invalidation request, for example, IDFDVBD632BHDS5. + // A flag that allows a Lambda function to have read access to the body content. + // For more information, see Accessing the Request Body by Choosing the Include + // Body Option (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-include-body-access.html) + // in the Amazon CloudFront Developer Guide. + IncludeBody *bool `type:"boolean"` + + // The ARN of the Lambda function. You must specify the ARN of a function version; + // you can't specify a Lambda alias or $LATEST. // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + // LambdaFunctionARN is a required field + LambdaFunctionARN *string `type:"string" required:"true"` } // String returns the string representation -func (s GetInvalidationInput) String() string { +func (s LambdaFunctionAssociation) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetInvalidationInput) GoString() string { +func (s LambdaFunctionAssociation) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetInvalidationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInvalidationInput"} - if s.DistributionId == nil { - invalidParams.Add(request.NewErrParamRequired("DistributionId")) - } - if s.DistributionId != nil && len(*s.DistributionId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DistributionId", 1)) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) +func (s *LambdaFunctionAssociation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LambdaFunctionAssociation"} + if s.EventType == nil { + invalidParams.Add(request.NewErrParamRequired("EventType")) } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + if s.LambdaFunctionARN == nil { + invalidParams.Add(request.NewErrParamRequired("LambdaFunctionARN")) } if invalidParams.Len() > 0 { @@ -10193,70 +13880,73 @@ func (s *GetInvalidationInput) Validate() error { return nil } -// SetDistributionId sets the DistributionId field's value. -func (s *GetInvalidationInput) SetDistributionId(v string) *GetInvalidationInput { - s.DistributionId = &v +// SetEventType sets the EventType field's value. +func (s *LambdaFunctionAssociation) SetEventType(v string) *LambdaFunctionAssociation { + s.EventType = &v return s } -// SetId sets the Id field's value. -func (s *GetInvalidationInput) SetId(v string) *GetInvalidationInput { - s.Id = &v +// SetIncludeBody sets the IncludeBody field's value. +func (s *LambdaFunctionAssociation) SetIncludeBody(v bool) *LambdaFunctionAssociation { + s.IncludeBody = &v return s } -// The returned result of the corresponding request. -type GetInvalidationOutput struct { - _ struct{} `type:"structure" payload:"Invalidation"` - - // The invalidation's information. For more information, see Invalidation Complex - // Type (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/InvalidationDatatype.html). - Invalidation *Invalidation `type:"structure"` -} - -// String returns the string representation -func (s GetInvalidationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInvalidationOutput) GoString() string { - return s.String() -} - -// SetInvalidation sets the Invalidation field's value. -func (s *GetInvalidationOutput) SetInvalidation(v *Invalidation) *GetInvalidationOutput { - s.Invalidation = v +// SetLambdaFunctionARN sets the LambdaFunctionARN field's value. +func (s *LambdaFunctionAssociation) SetLambdaFunctionARN(v string) *LambdaFunctionAssociation { + s.LambdaFunctionARN = &v return s } -type GetPublicKeyConfigInput struct { - _ struct{} `locationName:"GetPublicKeyConfigRequest" type:"structure"` +// A complex type that specifies a list of Lambda functions associations for +// a cache behavior. +// +// If you want to invoke one or more Lambda functions triggered by requests +// that match the PathPattern of the cache behavior, specify the applicable +// values for Quantity and Items. Note that there can be up to 4 LambdaFunctionAssociation +// items in this list (one for each possible value of EventType) and each EventType +// can be associated with the Lambda function only once. +// +// If you don't want to invoke any Lambda functions for the requests that match +// PathPattern, specify 0 for Quantity and omit Items. +type LambdaFunctionAssociations struct { + _ struct{} `type:"structure"` - // Request the ID for the public key configuration. + // Optional: A complex type that contains LambdaFunctionAssociation items for + // this cache behavior. If Quantity is 0, you can omit Items. + Items []*LambdaFunctionAssociation `locationNameList:"LambdaFunctionAssociation" type:"list"` + + // The number of Lambda function associations for this cache behavior. // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s GetPublicKeyConfigInput) String() string { +func (s LambdaFunctionAssociations) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetPublicKeyConfigInput) GoString() string { +func (s LambdaFunctionAssociations) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetPublicKeyConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetPublicKeyConfigInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) +func (s *LambdaFunctionAssociations) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LambdaFunctionAssociations"} + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + if s.Items != nil { + for i, v := range s.Items { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -10265,220 +13955,188 @@ func (s *GetPublicKeyConfigInput) Validate() error { return nil } -// SetId sets the Id field's value. -func (s *GetPublicKeyConfigInput) SetId(v string) *GetPublicKeyConfigInput { - s.Id = &v +// SetItems sets the Items field's value. +func (s *LambdaFunctionAssociations) SetItems(v []*LambdaFunctionAssociation) *LambdaFunctionAssociations { + s.Items = v return s } -type GetPublicKeyConfigOutput struct { - _ struct{} `type:"structure" payload:"PublicKeyConfig"` - - // The current version of the public key configuration. For example: E2QWRUHAPOMQZL. - ETag *string `location:"header" locationName:"ETag" type:"string"` - - // Return the result for the public key configuration. - PublicKeyConfig *PublicKeyConfig `type:"structure"` -} - -// String returns the string representation -func (s GetPublicKeyConfigOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetPublicKeyConfigOutput) GoString() string { - return s.String() -} - -// SetETag sets the ETag field's value. -func (s *GetPublicKeyConfigOutput) SetETag(v string) *GetPublicKeyConfigOutput { - s.ETag = &v +// SetQuantity sets the Quantity field's value. +func (s *LambdaFunctionAssociations) SetQuantity(v int64) *LambdaFunctionAssociations { + s.Quantity = &v return s } -// SetPublicKeyConfig sets the PublicKeyConfig field's value. -func (s *GetPublicKeyConfigOutput) SetPublicKeyConfig(v *PublicKeyConfig) *GetPublicKeyConfigOutput { - s.PublicKeyConfig = v - return s -} +type ListCachePoliciesInput struct { + _ struct{} `locationName:"ListCachePoliciesRequest" type:"structure"` -type GetPublicKeyInput struct { - _ struct{} `locationName:"GetPublicKeyRequest" type:"structure"` + // Use this field when paginating results to indicate where to begin in your + // list of cache policies. The response includes cache policies in the list + // that occur after the marker. To get the next page of the list, set this field’s + // value to the value of NextMarker from the current page’s response. + Marker *string `location:"querystring" locationName:"Marker" type:"string"` - // Request the ID for the public key. + // The maximum number of cache policies that you want in the response. + MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` + + // A filter to return only the specified kinds of cache policies. Valid values + // are: // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + // * managed – Returns only the managed policies created by AWS. + // + // * custom – Returns only the custom policies created in your AWS account. + Type *string `location:"querystring" locationName:"Type" type:"string" enum:"CachePolicyType"` } // String returns the string representation -func (s GetPublicKeyInput) String() string { +func (s ListCachePoliciesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetPublicKeyInput) GoString() string { +func (s ListCachePoliciesInput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetPublicKeyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetPublicKeyInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetMarker sets the Marker field's value. +func (s *ListCachePoliciesInput) SetMarker(v string) *ListCachePoliciesInput { + s.Marker = &v + return s } -// SetId sets the Id field's value. -func (s *GetPublicKeyInput) SetId(v string) *GetPublicKeyInput { - s.Id = &v +// SetMaxItems sets the MaxItems field's value. +func (s *ListCachePoliciesInput) SetMaxItems(v int64) *ListCachePoliciesInput { + s.MaxItems = &v return s } -type GetPublicKeyOutput struct { - _ struct{} `type:"structure" payload:"PublicKey"` +// SetType sets the Type field's value. +func (s *ListCachePoliciesInput) SetType(v string) *ListCachePoliciesInput { + s.Type = &v + return s +} - // The current version of the public key. For example: E2QWRUHAPOMQZL. - ETag *string `location:"header" locationName:"ETag" type:"string"` +type ListCachePoliciesOutput struct { + _ struct{} `type:"structure" payload:"CachePolicyList"` - // Return the public key. - PublicKey *PublicKey `type:"structure"` + // A list of cache policies. + CachePolicyList *CachePolicyList `type:"structure"` } // String returns the string representation -func (s GetPublicKeyOutput) String() string { +func (s ListCachePoliciesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetPublicKeyOutput) GoString() string { +func (s ListCachePoliciesOutput) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *GetPublicKeyOutput) SetETag(v string) *GetPublicKeyOutput { - s.ETag = &v +// SetCachePolicyList sets the CachePolicyList field's value. +func (s *ListCachePoliciesOutput) SetCachePolicyList(v *CachePolicyList) *ListCachePoliciesOutput { + s.CachePolicyList = v return s } -// SetPublicKey sets the PublicKey field's value. -func (s *GetPublicKeyOutput) SetPublicKey(v *PublicKey) *GetPublicKeyOutput { - s.PublicKey = v - return s -} +// The request to list origin access identities. +type ListCloudFrontOriginAccessIdentitiesInput struct { + _ struct{} `locationName:"ListCloudFrontOriginAccessIdentitiesRequest" type:"structure"` -// To request to get a streaming distribution configuration. -type GetStreamingDistributionConfigInput struct { - _ struct{} `locationName:"GetStreamingDistributionConfigRequest" type:"structure"` + // Use this when paginating results to indicate where to begin in your list + // of origin access identities. The results include identities in the list that + // occur after the marker. To get the next page of results, set the Marker to + // the value of the NextMarker from the current page's response (which is also + // the ID of the last identity on that page). + Marker *string `location:"querystring" locationName:"Marker" type:"string"` - // The streaming distribution's ID. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + // The maximum number of origin access identities you want in the response body. + MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` } // String returns the string representation -func (s GetStreamingDistributionConfigInput) String() string { +func (s ListCloudFrontOriginAccessIdentitiesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetStreamingDistributionConfigInput) GoString() string { +func (s ListCloudFrontOriginAccessIdentitiesInput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetStreamingDistributionConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetStreamingDistributionConfigInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetMarker sets the Marker field's value. +func (s *ListCloudFrontOriginAccessIdentitiesInput) SetMarker(v string) *ListCloudFrontOriginAccessIdentitiesInput { + s.Marker = &v + return s } -// SetId sets the Id field's value. -func (s *GetStreamingDistributionConfigInput) SetId(v string) *GetStreamingDistributionConfigInput { - s.Id = &v +// SetMaxItems sets the MaxItems field's value. +func (s *ListCloudFrontOriginAccessIdentitiesInput) SetMaxItems(v int64) *ListCloudFrontOriginAccessIdentitiesInput { + s.MaxItems = &v return s } // The returned result of the corresponding request. -type GetStreamingDistributionConfigOutput struct { - _ struct{} `type:"structure" payload:"StreamingDistributionConfig"` - - // The current version of the configuration. For example: E2QWRUHAPOMQZL. - ETag *string `location:"header" locationName:"ETag" type:"string"` +type ListCloudFrontOriginAccessIdentitiesOutput struct { + _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentityList"` - // The streaming distribution's configuration information. - StreamingDistributionConfig *StreamingDistributionConfig `type:"structure"` + // The CloudFrontOriginAccessIdentityList type. + CloudFrontOriginAccessIdentityList *OriginAccessIdentityList `type:"structure"` } // String returns the string representation -func (s GetStreamingDistributionConfigOutput) String() string { +func (s ListCloudFrontOriginAccessIdentitiesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetStreamingDistributionConfigOutput) GoString() string { +func (s ListCloudFrontOriginAccessIdentitiesOutput) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *GetStreamingDistributionConfigOutput) SetETag(v string) *GetStreamingDistributionConfigOutput { - s.ETag = &v - return s -} - -// SetStreamingDistributionConfig sets the StreamingDistributionConfig field's value. -func (s *GetStreamingDistributionConfigOutput) SetStreamingDistributionConfig(v *StreamingDistributionConfig) *GetStreamingDistributionConfigOutput { - s.StreamingDistributionConfig = v +// SetCloudFrontOriginAccessIdentityList sets the CloudFrontOriginAccessIdentityList field's value. +func (s *ListCloudFrontOriginAccessIdentitiesOutput) SetCloudFrontOriginAccessIdentityList(v *OriginAccessIdentityList) *ListCloudFrontOriginAccessIdentitiesOutput { + s.CloudFrontOriginAccessIdentityList = v return s } -// The request to get a streaming distribution's information. -type GetStreamingDistributionInput struct { - _ struct{} `locationName:"GetStreamingDistributionRequest" type:"structure"` +type ListDistributionsByCachePolicyIdInput struct { + _ struct{} `locationName:"ListDistributionsByCachePolicyIdRequest" type:"structure"` - // The streaming distribution's ID. + // The ID of the cache policy whose associated distribution IDs you want to + // list. // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + // CachePolicyId is a required field + CachePolicyId *string `location:"uri" locationName:"CachePolicyId" type:"string" required:"true"` + + // Use this field when paginating results to indicate where to begin in your + // list of distribution IDs. The response includes distribution IDs in the list + // that occur after the marker. To get the next page of the list, set this field’s + // value to the value of NextMarker from the current page’s response. + Marker *string `location:"querystring" locationName:"Marker" type:"string"` + + // The maximum number of distribution IDs that you want in the response. + MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` } // String returns the string representation -func (s GetStreamingDistributionInput) String() string { +func (s ListDistributionsByCachePolicyIdInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetStreamingDistributionInput) GoString() string { +func (s ListDistributionsByCachePolicyIdInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetStreamingDistributionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetStreamingDistributionInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) +func (s *ListDistributionsByCachePolicyIdInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDistributionsByCachePolicyIdInput"} + if s.CachePolicyId == nil { + invalidParams.Add(request.NewErrParamRequired("CachePolicyId")) } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + if s.CachePolicyId != nil && len(*s.CachePolicyId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CachePolicyId", 1)) } if invalidParams.Len() > 0 { @@ -10487,110 +14145,84 @@ func (s *GetStreamingDistributionInput) Validate() error { return nil } -// SetId sets the Id field's value. -func (s *GetStreamingDistributionInput) SetId(v string) *GetStreamingDistributionInput { - s.Id = &v +// SetCachePolicyId sets the CachePolicyId field's value. +func (s *ListDistributionsByCachePolicyIdInput) SetCachePolicyId(v string) *ListDistributionsByCachePolicyIdInput { + s.CachePolicyId = &v return s } -// The returned result of the corresponding request. -type GetStreamingDistributionOutput struct { - _ struct{} `type:"structure" payload:"StreamingDistribution"` +// SetMarker sets the Marker field's value. +func (s *ListDistributionsByCachePolicyIdInput) SetMarker(v string) *ListDistributionsByCachePolicyIdInput { + s.Marker = &v + return s +} - // The current version of the streaming distribution's information. For example: - // E2QWRUHAPOMQZL. - ETag *string `location:"header" locationName:"ETag" type:"string"` +// SetMaxItems sets the MaxItems field's value. +func (s *ListDistributionsByCachePolicyIdInput) SetMaxItems(v int64) *ListDistributionsByCachePolicyIdInput { + s.MaxItems = &v + return s +} - // The streaming distribution's information. - StreamingDistribution *StreamingDistribution `type:"structure"` +type ListDistributionsByCachePolicyIdOutput struct { + _ struct{} `type:"structure" payload:"DistributionIdList"` + + // A list of distribution IDs. + DistributionIdList *DistributionIdList `type:"structure"` } // String returns the string representation -func (s GetStreamingDistributionOutput) String() string { +func (s ListDistributionsByCachePolicyIdOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetStreamingDistributionOutput) GoString() string { +func (s ListDistributionsByCachePolicyIdOutput) GoString() string { return s.String() } -// SetETag sets the ETag field's value. -func (s *GetStreamingDistributionOutput) SetETag(v string) *GetStreamingDistributionOutput { - s.ETag = &v +// SetDistributionIdList sets the DistributionIdList field's value. +func (s *ListDistributionsByCachePolicyIdOutput) SetDistributionIdList(v *DistributionIdList) *ListDistributionsByCachePolicyIdOutput { + s.DistributionIdList = v return s } -// SetStreamingDistribution sets the StreamingDistribution field's value. -func (s *GetStreamingDistributionOutput) SetStreamingDistribution(v *StreamingDistribution) *GetStreamingDistributionOutput { - s.StreamingDistribution = v - return s -} +type ListDistributionsByOriginRequestPolicyIdInput struct { + _ struct{} `locationName:"ListDistributionsByOriginRequestPolicyIdRequest" type:"structure"` -// A complex type that specifies the request headers, if any, that you want -// CloudFront to base caching on for this cache behavior. -// -// For the headers that you specify, CloudFront caches separate versions of -// a specified object based on the header values in viewer requests. For example, -// suppose viewer requests for logo.jpg contain a custom product header that -// has a value of either acme or apex, and you configure CloudFront to cache -// your content based on values in the product header. CloudFront forwards the -// product header to the origin and caches the response from the origin once -// for each header value. For more information about caching based on header -// values, see How CloudFront Forwards and Caches Headers (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html) -// in the Amazon CloudFront Developer Guide. -type Headers struct { - _ struct{} `type:"structure"` + // Use this field when paginating results to indicate where to begin in your + // list of distribution IDs. The response includes distribution IDs in the list + // that occur after the marker. To get the next page of the list, set this field’s + // value to the value of NextMarker from the current page’s response. + Marker *string `location:"querystring" locationName:"Marker" type:"string"` - // A list that contains one Name element for each header that you want CloudFront - // to use for caching in this cache behavior. If Quantity is 0, omit Items. - Items []*string `locationNameList:"Name" type:"list"` + // The maximum number of distribution IDs that you want in the response. + MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` - // The number of different headers that you want CloudFront to base caching - // on for this cache behavior. You can configure each cache behavior in a web - // distribution to do one of the following: + // The ID of the origin request policy whose associated distribution IDs you + // want to list. // - // * Forward all headers to your origin: Specify 1 for Quantity and * for - // Name. CloudFront doesn't cache the objects that are associated with this - // cache behavior. Instead, CloudFront sends every request to the origin. - // - // * Forward a whitelist of headers you specify: Specify the number of headers - // that you want CloudFront to base caching on. Then specify the header names - // in Name elements. CloudFront caches your objects based on the values in - // the specified headers. - // - // * Forward only the default headers: Specify 0 for Quantity and omit Items. - // In this configuration, CloudFront doesn't cache based on the values in - // the request headers. - // - // Regardless of which option you choose, CloudFront forwards headers to your - // origin based on whether the origin is an S3 bucket or a custom origin. See - // the following documentation: - // - // * S3 bucket: See HTTP Request Headers That CloudFront Removes or Updates - // (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorS3Origin.html#request-s3-removed-headers) - // - // * Custom origin: See HTTP Request Headers and CloudFront Behavior (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#request-custom-headers-behavior) - // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // OriginRequestPolicyId is a required field + OriginRequestPolicyId *string `location:"uri" locationName:"OriginRequestPolicyId" type:"string" required:"true"` } // String returns the string representation -func (s Headers) String() string { +func (s ListDistributionsByOriginRequestPolicyIdInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Headers) GoString() string { +func (s ListDistributionsByOriginRequestPolicyIdInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *Headers) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Headers"} - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) +func (s *ListDistributionsByOriginRequestPolicyIdInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDistributionsByOriginRequestPolicyIdInput"} + if s.OriginRequestPolicyId == nil { + invalidParams.Add(request.NewErrParamRequired("OriginRequestPolicyId")) + } + if s.OriginRequestPolicyId != nil && len(*s.OriginRequestPolicyId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("OriginRequestPolicyId", 1)) } if invalidParams.Len() > 0 { @@ -10599,133 +14231,89 @@ func (s *Headers) Validate() error { return nil } -// SetItems sets the Items field's value. -func (s *Headers) SetItems(v []*string) *Headers { - s.Items = v +// SetMarker sets the Marker field's value. +func (s *ListDistributionsByOriginRequestPolicyIdInput) SetMarker(v string) *ListDistributionsByOriginRequestPolicyIdInput { + s.Marker = &v return s } -// SetQuantity sets the Quantity field's value. -func (s *Headers) SetQuantity(v int64) *Headers { - s.Quantity = &v +// SetMaxItems sets the MaxItems field's value. +func (s *ListDistributionsByOriginRequestPolicyIdInput) SetMaxItems(v int64) *ListDistributionsByOriginRequestPolicyIdInput { + s.MaxItems = &v return s } -// An invalidation. -type Invalidation struct { - _ struct{} `type:"structure"` - - // The date and time the invalidation request was first made. - // - // CreateTime is a required field - CreateTime *time.Time `type:"timestamp" required:"true"` - - // The identifier for the invalidation request. For example: IDFDVBD632BHDS5. - // - // Id is a required field - Id *string `type:"string" required:"true"` +// SetOriginRequestPolicyId sets the OriginRequestPolicyId field's value. +func (s *ListDistributionsByOriginRequestPolicyIdInput) SetOriginRequestPolicyId(v string) *ListDistributionsByOriginRequestPolicyIdInput { + s.OriginRequestPolicyId = &v + return s +} - // The current invalidation information for the batch request. - // - // InvalidationBatch is a required field - InvalidationBatch *InvalidationBatch `type:"structure" required:"true"` +type ListDistributionsByOriginRequestPolicyIdOutput struct { + _ struct{} `type:"structure" payload:"DistributionIdList"` - // The status of the invalidation request. When the invalidation batch is finished, - // the status is Completed. - // - // Status is a required field - Status *string `type:"string" required:"true"` + // A list of distribution IDs. + DistributionIdList *DistributionIdList `type:"structure"` } // String returns the string representation -func (s Invalidation) String() string { +func (s ListDistributionsByOriginRequestPolicyIdOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Invalidation) GoString() string { +func (s ListDistributionsByOriginRequestPolicyIdOutput) GoString() string { return s.String() } -// SetCreateTime sets the CreateTime field's value. -func (s *Invalidation) SetCreateTime(v time.Time) *Invalidation { - s.CreateTime = &v - return s -} - -// SetId sets the Id field's value. -func (s *Invalidation) SetId(v string) *Invalidation { - s.Id = &v - return s -} - -// SetInvalidationBatch sets the InvalidationBatch field's value. -func (s *Invalidation) SetInvalidationBatch(v *InvalidationBatch) *Invalidation { - s.InvalidationBatch = v +// SetDistributionIdList sets the DistributionIdList field's value. +func (s *ListDistributionsByOriginRequestPolicyIdOutput) SetDistributionIdList(v *DistributionIdList) *ListDistributionsByOriginRequestPolicyIdOutput { + s.DistributionIdList = v return s } -// SetStatus sets the Status field's value. -func (s *Invalidation) SetStatus(v string) *Invalidation { - s.Status = &v - return s -} +// The request to list distributions that are associated with a specified AWS +// WAF web ACL. +type ListDistributionsByWebACLIdInput struct { + _ struct{} `locationName:"ListDistributionsByWebACLIdRequest" type:"structure"` -// An invalidation batch. -type InvalidationBatch struct { - _ struct{} `type:"structure"` + // Use Marker and MaxItems to control pagination of results. If you have more + // than MaxItems distributions that satisfy the request, the response includes + // a NextMarker element. To get the next page of results, submit another request. + // For the value of Marker, specify the value of NextMarker from the last response. + // (For the first request, omit Marker.) + Marker *string `location:"querystring" locationName:"Marker" type:"string"` - // A value that you specify to uniquely identify an invalidation request. CloudFront - // uses the value to prevent you from accidentally resubmitting an identical - // request. Whenever you create a new invalidation request, you must specify - // a new value for CallerReference and change other values in the request as - // applicable. One way to ensure that the value of CallerReference is unique - // is to use a timestamp, for example, 20120301090000. - // - // If you make a second invalidation request with the same value for CallerReference, - // and if the rest of the request is the same, CloudFront doesn't create a new - // invalidation request. Instead, CloudFront returns information about the invalidation - // request that you previously created with the same CallerReference. - // - // If CallerReference is a value you already sent in a previous invalidation - // batch request but the content of any Path is different from the original - // request, CloudFront returns an InvalidationBatchAlreadyExists error. - // - // CallerReference is a required field - CallerReference *string `type:"string" required:"true"` + // The maximum number of distributions that you want CloudFront to return in + // the response body. The maximum and default values are both 100. + MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` - // A complex type that contains information about the objects that you want - // to invalidate. For more information, see Specifying the Objects to Invalidate - // (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#invalidation-specifying-objects) - // in the Amazon CloudFront Developer Guide. + // The ID of the AWS WAF web ACL that you want to list the associated distributions. + // If you specify "null" for the ID, the request returns a list of the distributions + // that aren't associated with a web ACL. // - // Paths is a required field - Paths *Paths `type:"structure" required:"true"` + // WebACLId is a required field + WebACLId *string `location:"uri" locationName:"WebACLId" type:"string" required:"true"` } // String returns the string representation -func (s InvalidationBatch) String() string { +func (s ListDistributionsByWebACLIdInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InvalidationBatch) GoString() string { +func (s ListDistributionsByWebACLIdInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *InvalidationBatch) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InvalidationBatch"} - if s.CallerReference == nil { - invalidParams.Add(request.NewErrParamRequired("CallerReference")) - } - if s.Paths == nil { - invalidParams.Add(request.NewErrParamRequired("Paths")) +func (s *ListDistributionsByWebACLIdInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDistributionsByWebACLIdInput"} + if s.WebACLId == nil { + invalidParams.Add(request.NewErrParamRequired("WebACLId")) } - if s.Paths != nil { - if err := s.Paths.Validate(); err != nil { - invalidParams.AddNested("Paths", err.(request.ErrInvalidParams)) - } + if s.WebACLId != nil && len(*s.WebACLId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("WebACLId", 1)) } if invalidParams.Len() > 0 { @@ -10734,253 +14322,273 @@ func (s *InvalidationBatch) Validate() error { return nil } -// SetCallerReference sets the CallerReference field's value. -func (s *InvalidationBatch) SetCallerReference(v string) *InvalidationBatch { - s.CallerReference = &v +// SetMarker sets the Marker field's value. +func (s *ListDistributionsByWebACLIdInput) SetMarker(v string) *ListDistributionsByWebACLIdInput { + s.Marker = &v return s } -// SetPaths sets the Paths field's value. -func (s *InvalidationBatch) SetPaths(v *Paths) *InvalidationBatch { - s.Paths = v +// SetMaxItems sets the MaxItems field's value. +func (s *ListDistributionsByWebACLIdInput) SetMaxItems(v int64) *ListDistributionsByWebACLIdInput { + s.MaxItems = &v return s } -// The InvalidationList complex type describes the list of invalidation objects. -// For more information about invalidation, see Invalidating Objects (Web Distributions -// Only) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html) -// in the Amazon CloudFront Developer Guide. -type InvalidationList struct { - _ struct{} `type:"structure"` +// SetWebACLId sets the WebACLId field's value. +func (s *ListDistributionsByWebACLIdInput) SetWebACLId(v string) *ListDistributionsByWebACLIdInput { + s.WebACLId = &v + return s +} - // A flag that indicates whether more invalidation batch requests remain to - // be listed. If your results were truncated, you can make a follow-up pagination - // request using the Marker request parameter to retrieve more invalidation - // batches in the list. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` +// The response to a request to list the distributions that are associated with +// a specified AWS WAF web ACL. +type ListDistributionsByWebACLIdOutput struct { + _ struct{} `type:"structure" payload:"DistributionList"` - // A complex type that contains one InvalidationSummary element for each invalidation - // batch created by the current AWS account. - Items []*InvalidationSummary `locationNameList:"InvalidationSummary" type:"list"` + // The DistributionList type. + DistributionList *DistributionList `type:"structure"` +} - // The value that you provided for the Marker request parameter. - // - // Marker is a required field - Marker *string `type:"string" required:"true"` +// String returns the string representation +func (s ListDistributionsByWebACLIdOutput) String() string { + return awsutil.Prettify(s) +} - // The value that you provided for the MaxItems request parameter. - // - // MaxItems is a required field - MaxItems *int64 `type:"integer" required:"true"` +// GoString returns the string representation +func (s ListDistributionsByWebACLIdOutput) GoString() string { + return s.String() +} - // If IsTruncated is true, this element is present and contains the value that - // you can use for the Marker request parameter to continue listing your invalidation - // batches where they left off. - NextMarker *string `type:"string"` +// SetDistributionList sets the DistributionList field's value. +func (s *ListDistributionsByWebACLIdOutput) SetDistributionList(v *DistributionList) *ListDistributionsByWebACLIdOutput { + s.DistributionList = v + return s +} - // The number of invalidation batches that were created by the current AWS account. - // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` +// The request to list your distributions. +type ListDistributionsInput struct { + _ struct{} `locationName:"ListDistributionsRequest" type:"structure"` + + // Use this when paginating results to indicate where to begin in your list + // of distributions. The results include distributions in the list that occur + // after the marker. To get the next page of results, set the Marker to the + // value of the NextMarker from the current page's response (which is also the + // ID of the last distribution on that page). + Marker *string `location:"querystring" locationName:"Marker" type:"string"` + + // The maximum number of distributions you want in the response body. + MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` } // String returns the string representation -func (s InvalidationList) String() string { +func (s ListDistributionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InvalidationList) GoString() string { +func (s ListDistributionsInput) GoString() string { return s.String() } -// SetIsTruncated sets the IsTruncated field's value. -func (s *InvalidationList) SetIsTruncated(v bool) *InvalidationList { - s.IsTruncated = &v +// SetMarker sets the Marker field's value. +func (s *ListDistributionsInput) SetMarker(v string) *ListDistributionsInput { + s.Marker = &v return s } -// SetItems sets the Items field's value. -func (s *InvalidationList) SetItems(v []*InvalidationSummary) *InvalidationList { - s.Items = v +// SetMaxItems sets the MaxItems field's value. +func (s *ListDistributionsInput) SetMaxItems(v int64) *ListDistributionsInput { + s.MaxItems = &v + return s +} + +// The returned result of the corresponding request. +type ListDistributionsOutput struct { + _ struct{} `type:"structure" payload:"DistributionList"` + + // The DistributionList type. + DistributionList *DistributionList `type:"structure"` +} + +// String returns the string representation +func (s ListDistributionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListDistributionsOutput) GoString() string { + return s.String() +} + +// SetDistributionList sets the DistributionList field's value. +func (s *ListDistributionsOutput) SetDistributionList(v *DistributionList) *ListDistributionsOutput { + s.DistributionList = v return s } +type ListFieldLevelEncryptionConfigsInput struct { + _ struct{} `locationName:"ListFieldLevelEncryptionConfigsRequest" type:"structure"` + + // Use this when paginating results to indicate where to begin in your list + // of configurations. The results include configurations in the list that occur + // after the marker. To get the next page of results, set the Marker to the + // value of the NextMarker from the current page's response (which is also the + // ID of the last configuration on that page). + Marker *string `location:"querystring" locationName:"Marker" type:"string"` + + // The maximum number of field-level encryption configurations you want in the + // response body. + MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` +} + +// String returns the string representation +func (s ListFieldLevelEncryptionConfigsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListFieldLevelEncryptionConfigsInput) GoString() string { + return s.String() +} + // SetMarker sets the Marker field's value. -func (s *InvalidationList) SetMarker(v string) *InvalidationList { +func (s *ListFieldLevelEncryptionConfigsInput) SetMarker(v string) *ListFieldLevelEncryptionConfigsInput { s.Marker = &v return s } // SetMaxItems sets the MaxItems field's value. -func (s *InvalidationList) SetMaxItems(v int64) *InvalidationList { +func (s *ListFieldLevelEncryptionConfigsInput) SetMaxItems(v int64) *ListFieldLevelEncryptionConfigsInput { s.MaxItems = &v return s } -// SetNextMarker sets the NextMarker field's value. -func (s *InvalidationList) SetNextMarker(v string) *InvalidationList { - s.NextMarker = &v - return s +type ListFieldLevelEncryptionConfigsOutput struct { + _ struct{} `type:"structure" payload:"FieldLevelEncryptionList"` + + // Returns a list of all field-level encryption configurations that have been + // created in CloudFront for this account. + FieldLevelEncryptionList *FieldLevelEncryptionList `type:"structure"` } -// SetQuantity sets the Quantity field's value. -func (s *InvalidationList) SetQuantity(v int64) *InvalidationList { - s.Quantity = &v - return s +// String returns the string representation +func (s ListFieldLevelEncryptionConfigsOutput) String() string { + return awsutil.Prettify(s) } -// A summary of an invalidation request. -type InvalidationSummary struct { - _ struct{} `type:"structure"` +// GoString returns the string representation +func (s ListFieldLevelEncryptionConfigsOutput) GoString() string { + return s.String() +} - // The time that an invalidation request was created. - // - // CreateTime is a required field - CreateTime *time.Time `type:"timestamp" required:"true"` +// SetFieldLevelEncryptionList sets the FieldLevelEncryptionList field's value. +func (s *ListFieldLevelEncryptionConfigsOutput) SetFieldLevelEncryptionList(v *FieldLevelEncryptionList) *ListFieldLevelEncryptionConfigsOutput { + s.FieldLevelEncryptionList = v + return s +} - // The unique ID for an invalidation request. - // - // Id is a required field - Id *string `type:"string" required:"true"` +type ListFieldLevelEncryptionProfilesInput struct { + _ struct{} `locationName:"ListFieldLevelEncryptionProfilesRequest" type:"structure"` - // The status of an invalidation request. - // - // Status is a required field - Status *string `type:"string" required:"true"` + // Use this when paginating results to indicate where to begin in your list + // of profiles. The results include profiles in the list that occur after the + // marker. To get the next page of results, set the Marker to the value of the + // NextMarker from the current page's response (which is also the ID of the + // last profile on that page). + Marker *string `location:"querystring" locationName:"Marker" type:"string"` + + // The maximum number of field-level encryption profiles you want in the response + // body. + MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` } // String returns the string representation -func (s InvalidationSummary) String() string { +func (s ListFieldLevelEncryptionProfilesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InvalidationSummary) GoString() string { +func (s ListFieldLevelEncryptionProfilesInput) GoString() string { return s.String() } -// SetCreateTime sets the CreateTime field's value. -func (s *InvalidationSummary) SetCreateTime(v time.Time) *InvalidationSummary { - s.CreateTime = &v - return s -} - -// SetId sets the Id field's value. -func (s *InvalidationSummary) SetId(v string) *InvalidationSummary { - s.Id = &v +// SetMarker sets the Marker field's value. +func (s *ListFieldLevelEncryptionProfilesInput) SetMarker(v string) *ListFieldLevelEncryptionProfilesInput { + s.Marker = &v return s } -// SetStatus sets the Status field's value. -func (s *InvalidationSummary) SetStatus(v string) *InvalidationSummary { - s.Status = &v +// SetMaxItems sets the MaxItems field's value. +func (s *ListFieldLevelEncryptionProfilesInput) SetMaxItems(v int64) *ListFieldLevelEncryptionProfilesInput { + s.MaxItems = &v return s } -// A complex type that lists the active CloudFront key pairs, if any, that are -// associated with AwsAccountNumber. -// -// For more information, see ActiveTrustedSigners (https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ActiveTrustedSigners.html). -type KeyPairIds struct { - _ struct{} `type:"structure"` - - // A complex type that lists the active CloudFront key pairs, if any, that are - // associated with AwsAccountNumber. - // - // For more information, see ActiveTrustedSigners (https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ActiveTrustedSigners.html). - Items []*string `locationNameList:"KeyPairId" type:"list"` +type ListFieldLevelEncryptionProfilesOutput struct { + _ struct{} `type:"structure" payload:"FieldLevelEncryptionProfileList"` - // The number of active CloudFront key pairs for AwsAccountNumber. - // - // For more information, see ActiveTrustedSigners (https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_ActiveTrustedSigners.html). - // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // Returns a list of the field-level encryption profiles that have been created + // in CloudFront for this account. + FieldLevelEncryptionProfileList *FieldLevelEncryptionProfileList `type:"structure"` } // String returns the string representation -func (s KeyPairIds) String() string { +func (s ListFieldLevelEncryptionProfilesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s KeyPairIds) GoString() string { +func (s ListFieldLevelEncryptionProfilesOutput) GoString() string { return s.String() } -// SetItems sets the Items field's value. -func (s *KeyPairIds) SetItems(v []*string) *KeyPairIds { - s.Items = v - return s -} - -// SetQuantity sets the Quantity field's value. -func (s *KeyPairIds) SetQuantity(v int64) *KeyPairIds { - s.Quantity = &v +// SetFieldLevelEncryptionProfileList sets the FieldLevelEncryptionProfileList field's value. +func (s *ListFieldLevelEncryptionProfilesOutput) SetFieldLevelEncryptionProfileList(v *FieldLevelEncryptionProfileList) *ListFieldLevelEncryptionProfilesOutput { + s.FieldLevelEncryptionProfileList = v return s } -// A complex type that contains a Lambda function association. -type LambdaFunctionAssociation struct { - _ struct{} `type:"structure"` +// The request to list invalidations. +type ListInvalidationsInput struct { + _ struct{} `locationName:"ListInvalidationsRequest" type:"structure"` - // Specifies the event type that triggers a Lambda function invocation. You - // can specify the following values: - // - // * viewer-request: The function executes when CloudFront receives a request - // from a viewer and before it checks to see whether the requested object - // is in the edge cache. - // - // * origin-request: The function executes only when CloudFront forwards - // a request to your origin. When the requested object is in the edge cache, - // the function doesn't execute. - // - // * origin-response: The function executes after CloudFront receives a response - // from the origin and before it caches the object in the response. When - // the requested object is in the edge cache, the function doesn't execute. - // - // * viewer-response: The function executes before CloudFront returns the - // requested object to the viewer. The function executes regardless of whether - // the object was already in the edge cache. If the origin returns an HTTP - // status code other than HTTP 200 (OK), the function doesn't execute. + // The distribution's ID. // - // EventType is a required field - EventType *string `type:"string" required:"true" enum:"EventType"` + // DistributionId is a required field + DistributionId *string `location:"uri" locationName:"DistributionId" type:"string" required:"true"` - // A flag that allows a Lambda function to have read access to the body content. - // For more information, see Accessing the Request Body by Choosing the Include - // Body Option (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-include-body-access.html) - // in the Amazon CloudFront Developer Guide. - IncludeBody *bool `type:"boolean"` + // Use this parameter when paginating results to indicate where to begin in + // your list of invalidation batches. Because the results are returned in decreasing + // order from most recent to oldest, the most recent results are on the first + // page, the second page will contain earlier results, and so on. To get the + // next page of results, set Marker to the value of the NextMarker from the + // current page's response. This value is the same as the ID of the last invalidation + // batch on that page. + Marker *string `location:"querystring" locationName:"Marker" type:"string"` - // The ARN of the Lambda function. You must specify the ARN of a function version; - // you can't specify a Lambda alias or $LATEST. - // - // LambdaFunctionARN is a required field - LambdaFunctionARN *string `type:"string" required:"true"` + // The maximum number of invalidation batches that you want in the response + // body. + MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` } // String returns the string representation -func (s LambdaFunctionAssociation) String() string { +func (s ListInvalidationsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s LambdaFunctionAssociation) GoString() string { +func (s ListInvalidationsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *LambdaFunctionAssociation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LambdaFunctionAssociation"} - if s.EventType == nil { - invalidParams.Add(request.NewErrParamRequired("EventType")) +func (s *ListInvalidationsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListInvalidationsInput"} + if s.DistributionId == nil { + invalidParams.Add(request.NewErrParamRequired("DistributionId")) } - if s.LambdaFunctionARN == nil { - invalidParams.Add(request.NewErrParamRequired("LambdaFunctionARN")) + if s.DistributionId != nil && len(*s.DistributionId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DistributionId", 1)) } if invalidParams.Len() > 0 { @@ -10989,471 +14597,516 @@ func (s *LambdaFunctionAssociation) Validate() error { return nil } -// SetEventType sets the EventType field's value. -func (s *LambdaFunctionAssociation) SetEventType(v string) *LambdaFunctionAssociation { - s.EventType = &v +// SetDistributionId sets the DistributionId field's value. +func (s *ListInvalidationsInput) SetDistributionId(v string) *ListInvalidationsInput { + s.DistributionId = &v return s } -// SetIncludeBody sets the IncludeBody field's value. -func (s *LambdaFunctionAssociation) SetIncludeBody(v bool) *LambdaFunctionAssociation { - s.IncludeBody = &v +// SetMarker sets the Marker field's value. +func (s *ListInvalidationsInput) SetMarker(v string) *ListInvalidationsInput { + s.Marker = &v return s } -// SetLambdaFunctionARN sets the LambdaFunctionARN field's value. -func (s *LambdaFunctionAssociation) SetLambdaFunctionARN(v string) *LambdaFunctionAssociation { - s.LambdaFunctionARN = &v +// SetMaxItems sets the MaxItems field's value. +func (s *ListInvalidationsInput) SetMaxItems(v int64) *ListInvalidationsInput { + s.MaxItems = &v return s } -// A complex type that specifies a list of Lambda functions associations for -// a cache behavior. -// -// If you want to invoke one or more Lambda functions triggered by requests -// that match the PathPattern of the cache behavior, specify the applicable -// values for Quantity and Items. Note that there can be up to 4 LambdaFunctionAssociation -// items in this list (one for each possible value of EventType) and each EventType -// can be associated with the Lambda function only once. -// -// If you don't want to invoke any Lambda functions for the requests that match -// PathPattern, specify 0 for Quantity and omit Items. -type LambdaFunctionAssociations struct { - _ struct{} `type:"structure"` - - // Optional: A complex type that contains LambdaFunctionAssociation items for - // this cache behavior. If Quantity is 0, you can omit Items. - Items []*LambdaFunctionAssociation `locationNameList:"LambdaFunctionAssociation" type:"list"` +// The returned result of the corresponding request. +type ListInvalidationsOutput struct { + _ struct{} `type:"structure" payload:"InvalidationList"` - // The number of Lambda function associations for this cache behavior. - // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // Information about invalidation batches. + InvalidationList *InvalidationList `type:"structure"` } // String returns the string representation -func (s LambdaFunctionAssociations) String() string { +func (s ListInvalidationsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s LambdaFunctionAssociations) GoString() string { +func (s ListInvalidationsOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *LambdaFunctionAssociations) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LambdaFunctionAssociations"} - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) - } - if s.Items != nil { - for i, v := range s.Items { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetItems sets the Items field's value. -func (s *LambdaFunctionAssociations) SetItems(v []*LambdaFunctionAssociation) *LambdaFunctionAssociations { - s.Items = v - return s -} - -// SetQuantity sets the Quantity field's value. -func (s *LambdaFunctionAssociations) SetQuantity(v int64) *LambdaFunctionAssociations { - s.Quantity = &v +// SetInvalidationList sets the InvalidationList field's value. +func (s *ListInvalidationsOutput) SetInvalidationList(v *InvalidationList) *ListInvalidationsOutput { + s.InvalidationList = v return s } -// The request to list origin access identities. -type ListCloudFrontOriginAccessIdentitiesInput struct { - _ struct{} `locationName:"ListCloudFrontOriginAccessIdentitiesRequest" type:"structure"` +type ListOriginRequestPoliciesInput struct { + _ struct{} `locationName:"ListOriginRequestPoliciesRequest" type:"structure"` - // Use this when paginating results to indicate where to begin in your list - // of origin access identities. The results include identities in the list that - // occur after the marker. To get the next page of results, set the Marker to - // the value of the NextMarker from the current page's response (which is also - // the ID of the last identity on that page). + // Use this field when paginating results to indicate where to begin in your + // list of origin request policies. The response includes origin request policies + // in the list that occur after the marker. To get the next page of the list, + // set this field’s value to the value of NextMarker from the current page’s + // response. Marker *string `location:"querystring" locationName:"Marker" type:"string"` - // The maximum number of origin access identities you want in the response body. + // The maximum number of origin request policies that you want in the response. MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` + + // A filter to return only the specified kinds of origin request policies. Valid + // values are: + // + // * managed – Returns only the managed policies created by AWS. + // + // * custom – Returns only the custom policies created in your AWS account. + Type *string `location:"querystring" locationName:"Type" type:"string" enum:"OriginRequestPolicyType"` } // String returns the string representation -func (s ListCloudFrontOriginAccessIdentitiesInput) String() string { +func (s ListOriginRequestPoliciesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListCloudFrontOriginAccessIdentitiesInput) GoString() string { +func (s ListOriginRequestPoliciesInput) GoString() string { return s.String() } // SetMarker sets the Marker field's value. -func (s *ListCloudFrontOriginAccessIdentitiesInput) SetMarker(v string) *ListCloudFrontOriginAccessIdentitiesInput { +func (s *ListOriginRequestPoliciesInput) SetMarker(v string) *ListOriginRequestPoliciesInput { s.Marker = &v return s } // SetMaxItems sets the MaxItems field's value. -func (s *ListCloudFrontOriginAccessIdentitiesInput) SetMaxItems(v int64) *ListCloudFrontOriginAccessIdentitiesInput { +func (s *ListOriginRequestPoliciesInput) SetMaxItems(v int64) *ListOriginRequestPoliciesInput { s.MaxItems = &v return s } -// The returned result of the corresponding request. -type ListCloudFrontOriginAccessIdentitiesOutput struct { - _ struct{} `type:"structure" payload:"CloudFrontOriginAccessIdentityList"` +// SetType sets the Type field's value. +func (s *ListOriginRequestPoliciesInput) SetType(v string) *ListOriginRequestPoliciesInput { + s.Type = &v + return s +} - // The CloudFrontOriginAccessIdentityList type. - CloudFrontOriginAccessIdentityList *OriginAccessIdentityList `type:"structure"` +type ListOriginRequestPoliciesOutput struct { + _ struct{} `type:"structure" payload:"OriginRequestPolicyList"` + + // A list of origin request policies. + OriginRequestPolicyList *OriginRequestPolicyList `type:"structure"` } // String returns the string representation -func (s ListCloudFrontOriginAccessIdentitiesOutput) String() string { +func (s ListOriginRequestPoliciesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListCloudFrontOriginAccessIdentitiesOutput) GoString() string { +func (s ListOriginRequestPoliciesOutput) GoString() string { return s.String() } -// SetCloudFrontOriginAccessIdentityList sets the CloudFrontOriginAccessIdentityList field's value. -func (s *ListCloudFrontOriginAccessIdentitiesOutput) SetCloudFrontOriginAccessIdentityList(v *OriginAccessIdentityList) *ListCloudFrontOriginAccessIdentitiesOutput { - s.CloudFrontOriginAccessIdentityList = v +// SetOriginRequestPolicyList sets the OriginRequestPolicyList field's value. +func (s *ListOriginRequestPoliciesOutput) SetOriginRequestPolicyList(v *OriginRequestPolicyList) *ListOriginRequestPoliciesOutput { + s.OriginRequestPolicyList = v return s } -// The request to list distributions that are associated with a specified AWS -// WAF web ACL. -type ListDistributionsByWebACLIdInput struct { - _ struct{} `locationName:"ListDistributionsByWebACLIdRequest" type:"structure"` +type ListPublicKeysInput struct { + _ struct{} `locationName:"ListPublicKeysRequest" type:"structure"` - // Use Marker and MaxItems to control pagination of results. If you have more - // than MaxItems distributions that satisfy the request, the response includes - // a NextMarker element. To get the next page of results, submit another request. - // For the value of Marker, specify the value of NextMarker from the last response. - // (For the first request, omit Marker.) + // Use this when paginating results to indicate where to begin in your list + // of public keys. The results include public keys in the list that occur after + // the marker. To get the next page of results, set the Marker to the value + // of the NextMarker from the current page's response (which is also the ID + // of the last public key on that page). Marker *string `location:"querystring" locationName:"Marker" type:"string"` - // The maximum number of distributions that you want CloudFront to return in - // the response body. The maximum and default values are both 100. + // The maximum number of public keys you want in the response body. MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` - - // The ID of the AWS WAF web ACL that you want to list the associated distributions. - // If you specify "null" for the ID, the request returns a list of the distributions - // that aren't associated with a web ACL. - // - // WebACLId is a required field - WebACLId *string `location:"uri" locationName:"WebACLId" type:"string" required:"true"` } // String returns the string representation -func (s ListDistributionsByWebACLIdInput) String() string { +func (s ListPublicKeysInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDistributionsByWebACLIdInput) GoString() string { +func (s ListPublicKeysInput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListDistributionsByWebACLIdInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListDistributionsByWebACLIdInput"} - 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 -} - // SetMarker sets the Marker field's value. -func (s *ListDistributionsByWebACLIdInput) SetMarker(v string) *ListDistributionsByWebACLIdInput { +func (s *ListPublicKeysInput) SetMarker(v string) *ListPublicKeysInput { s.Marker = &v return s } // SetMaxItems sets the MaxItems field's value. -func (s *ListDistributionsByWebACLIdInput) SetMaxItems(v int64) *ListDistributionsByWebACLIdInput { +func (s *ListPublicKeysInput) SetMaxItems(v int64) *ListPublicKeysInput { s.MaxItems = &v return s -} - -// SetWebACLId sets the WebACLId field's value. -func (s *ListDistributionsByWebACLIdInput) SetWebACLId(v string) *ListDistributionsByWebACLIdInput { - s.WebACLId = &v - return s -} - -// The response to a request to list the distributions that are associated with -// a specified AWS WAF web ACL. -type ListDistributionsByWebACLIdOutput struct { - _ struct{} `type:"structure" payload:"DistributionList"` +} - // The DistributionList type. - DistributionList *DistributionList `type:"structure"` +type ListPublicKeysOutput struct { + _ struct{} `type:"structure" payload:"PublicKeyList"` + + // Returns a list of all public keys that have been added to CloudFront for + // this account. + PublicKeyList *PublicKeyList `type:"structure"` } // String returns the string representation -func (s ListDistributionsByWebACLIdOutput) String() string { +func (s ListPublicKeysOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDistributionsByWebACLIdOutput) GoString() string { +func (s ListPublicKeysOutput) GoString() string { return s.String() } -// SetDistributionList sets the DistributionList field's value. -func (s *ListDistributionsByWebACLIdOutput) SetDistributionList(v *DistributionList) *ListDistributionsByWebACLIdOutput { - s.DistributionList = v +// SetPublicKeyList sets the PublicKeyList field's value. +func (s *ListPublicKeysOutput) SetPublicKeyList(v *PublicKeyList) *ListPublicKeysOutput { + s.PublicKeyList = v return s } -// The request to list your distributions. -type ListDistributionsInput struct { - _ struct{} `locationName:"ListDistributionsRequest" type:"structure"` +// The request to list your streaming distributions. +type ListStreamingDistributionsInput struct { + _ struct{} `locationName:"ListStreamingDistributionsRequest" type:"structure"` - // Use this when paginating results to indicate where to begin in your list - // of distributions. The results include distributions in the list that occur - // after the marker. To get the next page of results, set the Marker to the - // value of the NextMarker from the current page's response (which is also the - // ID of the last distribution on that page). + // The value that you provided for the Marker request parameter. Marker *string `location:"querystring" locationName:"Marker" type:"string"` - // The maximum number of distributions you want in the response body. + // The value that you provided for the MaxItems request parameter. MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` } // String returns the string representation -func (s ListDistributionsInput) String() string { +func (s ListStreamingDistributionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDistributionsInput) GoString() string { +func (s ListStreamingDistributionsInput) GoString() string { return s.String() } // SetMarker sets the Marker field's value. -func (s *ListDistributionsInput) SetMarker(v string) *ListDistributionsInput { +func (s *ListStreamingDistributionsInput) SetMarker(v string) *ListStreamingDistributionsInput { s.Marker = &v return s } // SetMaxItems sets the MaxItems field's value. -func (s *ListDistributionsInput) SetMaxItems(v int64) *ListDistributionsInput { +func (s *ListStreamingDistributionsInput) SetMaxItems(v int64) *ListStreamingDistributionsInput { s.MaxItems = &v return s } // The returned result of the corresponding request. -type ListDistributionsOutput struct { - _ struct{} `type:"structure" payload:"DistributionList"` +type ListStreamingDistributionsOutput struct { + _ struct{} `type:"structure" payload:"StreamingDistributionList"` - // The DistributionList type. - DistributionList *DistributionList `type:"structure"` + // The StreamingDistributionList type. + StreamingDistributionList *StreamingDistributionList `type:"structure"` } // String returns the string representation -func (s ListDistributionsOutput) String() string { +func (s ListStreamingDistributionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDistributionsOutput) GoString() string { +func (s ListStreamingDistributionsOutput) GoString() string { return s.String() } -// SetDistributionList sets the DistributionList field's value. -func (s *ListDistributionsOutput) SetDistributionList(v *DistributionList) *ListDistributionsOutput { - s.DistributionList = v +// SetStreamingDistributionList sets the StreamingDistributionList field's value. +func (s *ListStreamingDistributionsOutput) SetStreamingDistributionList(v *StreamingDistributionList) *ListStreamingDistributionsOutput { + s.StreamingDistributionList = v return s } -type ListFieldLevelEncryptionConfigsInput struct { - _ struct{} `locationName:"ListFieldLevelEncryptionConfigsRequest" type:"structure"` - - // Use this when paginating results to indicate where to begin in your list - // of configurations. The results include configurations in the list that occur - // after the marker. To get the next page of results, set the Marker to the - // value of the NextMarker from the current page's response (which is also the - // ID of the last configuration on that page). - Marker *string `location:"querystring" locationName:"Marker" type:"string"` +// The request to list tags for a CloudFront resource. +type ListTagsForResourceInput struct { + _ struct{} `locationName:"ListTagsForResourceRequest" type:"structure"` - // The maximum number of field-level encryption configurations you want in the - // response body. - MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` + // An ARN of a CloudFront resource. + // + // Resource is a required field + Resource *string `location:"querystring" locationName:"Resource" type:"string" required:"true"` } // String returns the string representation -func (s ListFieldLevelEncryptionConfigsInput) String() string { +func (s ListTagsForResourceInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListFieldLevelEncryptionConfigsInput) GoString() string { +func (s ListTagsForResourceInput) GoString() string { return s.String() } -// SetMarker sets the Marker field's value. -func (s *ListFieldLevelEncryptionConfigsInput) SetMarker(v string) *ListFieldLevelEncryptionConfigsInput { - s.Marker = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTagsForResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} + if s.Resource == nil { + invalidParams.Add(request.NewErrParamRequired("Resource")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetMaxItems sets the MaxItems field's value. -func (s *ListFieldLevelEncryptionConfigsInput) SetMaxItems(v int64) *ListFieldLevelEncryptionConfigsInput { - s.MaxItems = &v +// SetResource sets the Resource field's value. +func (s *ListTagsForResourceInput) SetResource(v string) *ListTagsForResourceInput { + s.Resource = &v return s } -type ListFieldLevelEncryptionConfigsOutput struct { - _ struct{} `type:"structure" payload:"FieldLevelEncryptionList"` +// The returned result of the corresponding request. +type ListTagsForResourceOutput struct { + _ struct{} `type:"structure" payload:"Tags"` - // Returns a list of all field-level encryption configurations that have been - // created in CloudFront for this account. - FieldLevelEncryptionList *FieldLevelEncryptionList `type:"structure"` + // A complex type that contains zero or more Tag elements. + // + // Tags is a required field + Tags *Tags `type:"structure" required:"true"` } // String returns the string representation -func (s ListFieldLevelEncryptionConfigsOutput) String() string { +func (s ListTagsForResourceOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListFieldLevelEncryptionConfigsOutput) GoString() string { +func (s ListTagsForResourceOutput) GoString() string { return s.String() } -// SetFieldLevelEncryptionList sets the FieldLevelEncryptionList field's value. -func (s *ListFieldLevelEncryptionConfigsOutput) SetFieldLevelEncryptionList(v *FieldLevelEncryptionList) *ListFieldLevelEncryptionConfigsOutput { - s.FieldLevelEncryptionList = v +// SetTags sets the Tags field's value. +func (s *ListTagsForResourceOutput) SetTags(v *Tags) *ListTagsForResourceOutput { + s.Tags = v return s } -type ListFieldLevelEncryptionProfilesInput struct { - _ struct{} `locationName:"ListFieldLevelEncryptionProfilesRequest" type:"structure"` +// A complex type that controls whether access logs are written for the distribution. +type LoggingConfig struct { + _ struct{} `type:"structure"` - // Use this when paginating results to indicate where to begin in your list - // of profiles. The results include profiles in the list that occur after the - // marker. To get the next page of results, set the Marker to the value of the - // NextMarker from the current page's response (which is also the ID of the - // last profile on that page). - Marker *string `location:"querystring" locationName:"Marker" type:"string"` + // The Amazon S3 bucket to store the access logs in, for example, myawslogbucket.s3.amazonaws.com. + // + // Bucket is a required field + Bucket *string `type:"string" required:"true"` - // The maximum number of field-level encryption profiles you want in the response - // body. - MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` + // Specifies whether you want CloudFront to save access logs to an Amazon S3 + // bucket. If you don't 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. If you specify + // false for Enabled but you specify values for Bucket, prefix, and IncludeCookies, + // the values are automatically deleted. + // + // Enabled is a required field + Enabled *bool `type:"boolean" required:"true"` + + // Specifies whether you want CloudFront to include cookies in access logs, + // specify true for IncludeCookies. If you choose to include cookies in logs, + // CloudFront logs all cookies regardless of how you configure the cache behaviors + // for this distribution. If you don't want to include cookies when you create + // a distribution or if you want to disable include cookies for an existing + // distribution, specify false for IncludeCookies. + // + // IncludeCookies is a required field + IncludeCookies *bool `type:"boolean" required:"true"` + + // An optional string that you want CloudFront to prefix to the access log filenames + // for this distribution, for example, myprefix/. If you want to enable logging, + // but you don't want to specify a prefix, you still must include an empty Prefix + // element in the Logging element. + // + // Prefix is a required field + Prefix *string `type:"string" required:"true"` } // String returns the string representation -func (s ListFieldLevelEncryptionProfilesInput) String() string { +func (s LoggingConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListFieldLevelEncryptionProfilesInput) GoString() string { +func (s LoggingConfig) GoString() string { return s.String() } -// SetMarker sets the Marker field's value. -func (s *ListFieldLevelEncryptionProfilesInput) SetMarker(v string) *ListFieldLevelEncryptionProfilesInput { - s.Marker = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *LoggingConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LoggingConfig"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) + } + if s.Enabled == nil { + invalidParams.Add(request.NewErrParamRequired("Enabled")) + } + if s.IncludeCookies == nil { + invalidParams.Add(request.NewErrParamRequired("IncludeCookies")) + } + if s.Prefix == nil { + invalidParams.Add(request.NewErrParamRequired("Prefix")) + } -// SetMaxItems sets the MaxItems field's value. -func (s *ListFieldLevelEncryptionProfilesInput) SetMaxItems(v int64) *ListFieldLevelEncryptionProfilesInput { - s.MaxItems = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -type ListFieldLevelEncryptionProfilesOutput struct { - _ struct{} `type:"structure" payload:"FieldLevelEncryptionProfileList"` - - // Returns a list of the field-level encryption profiles that have been created - // in CloudFront for this account. - FieldLevelEncryptionProfileList *FieldLevelEncryptionProfileList `type:"structure"` +// SetBucket sets the Bucket field's value. +func (s *LoggingConfig) SetBucket(v string) *LoggingConfig { + s.Bucket = &v + return s } -// String returns the string representation -func (s ListFieldLevelEncryptionProfilesOutput) String() string { - return awsutil.Prettify(s) +// SetEnabled sets the Enabled field's value. +func (s *LoggingConfig) SetEnabled(v bool) *LoggingConfig { + s.Enabled = &v + return s } -// GoString returns the string representation -func (s ListFieldLevelEncryptionProfilesOutput) GoString() string { - return s.String() +// SetIncludeCookies sets the IncludeCookies field's value. +func (s *LoggingConfig) SetIncludeCookies(v bool) *LoggingConfig { + s.IncludeCookies = &v + return s } -// SetFieldLevelEncryptionProfileList sets the FieldLevelEncryptionProfileList field's value. -func (s *ListFieldLevelEncryptionProfilesOutput) SetFieldLevelEncryptionProfileList(v *FieldLevelEncryptionProfileList) *ListFieldLevelEncryptionProfilesOutput { - s.FieldLevelEncryptionProfileList = v +// SetPrefix sets the Prefix field's value. +func (s *LoggingConfig) SetPrefix(v string) *LoggingConfig { + s.Prefix = &v return s } -// The request to list invalidations. -type ListInvalidationsInput struct { - _ struct{} `locationName:"ListInvalidationsRequest" type:"structure"` +// An origin. +// +// An origin is the location where content is stored, and from which CloudFront +// gets content to serve to viewers. To specify an origin: +// +// * Use the S3OriginConfig type to specify an Amazon S3 bucket that is not +// configured with static website hosting. +// +// * Use the CustomOriginConfig type to specify various other kinds of content +// containers or HTTP servers, including: An Amazon S3 bucket that is configured +// with static website hosting An Elastic Load Balancing load balancer An +// AWS Elemental MediaPackage origin An AWS Elemental MediaStore container +// Any other HTTP server, running on an Amazon EC2 instance or any other +// kind of host +// +// For the current maximum number of origins that you can specify per distribution, +// see General Quotas on Web Distributions (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html#limits-web-distributions) +// in the Amazon CloudFront Developer Guide (quotas were formerly referred to +// as limits). +type Origin struct { + _ struct{} `type:"structure"` + + // The number of times that CloudFront attempts to connect to the origin. The + // minimum number is 1, the maximum is 3, and the default (if you don’t specify + // otherwise) is 3. + // + // For a custom origin (including an Amazon S3 bucket that’s configured with + // static website hosting), this value also specifies the number of times that + // CloudFront attempts to get a response from the origin, in the case of an + // Origin Response Timeout (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginResponseTimeout). + // + // For more information, see Origin Connection Attempts (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-attempts) + // in the Amazon CloudFront Developer Guide. + ConnectionAttempts *int64 `type:"integer"` + + // The number of seconds that CloudFront waits when trying to establish a connection + // to the origin. The minimum timeout is 1 second, the maximum is 10 seconds, + // and the default (if you don’t specify otherwise) is 10 seconds. + // + // For more information, see Origin Connection Timeout (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-timeout) + // in the Amazon CloudFront Developer Guide. + ConnectionTimeout *int64 `type:"integer"` + + // A list of HTTP header names and values that CloudFront adds to requests it + // sends to the origin. + // + // For more information, see Adding Custom Headers to Origin Requests (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/add-origin-custom-headers.html) + // in the Amazon CloudFront Developer Guide. + CustomHeaders *CustomHeaders `type:"structure"` + + // Use this type to specify an origin that is a content container or HTTP server, + // including an Amazon S3 bucket that is configured with static website hosting. + // To specify an Amazon S3 bucket that is not configured with static website + // hosting, use the S3OriginConfig type instead. + CustomOriginConfig *CustomOriginConfig `type:"structure"` + + // The domain name for the origin. + // + // For more information, see Origin Domain Name (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName) + // in the Amazon CloudFront Developer Guide. + // + // DomainName is a required field + DomainName *string `type:"string" required:"true"` - // The distribution's ID. + // A unique identifier for the origin. This value must be unique within the + // distribution. // - // DistributionId is a required field - DistributionId *string `location:"uri" locationName:"DistributionId" type:"string" required:"true"` + // Use this value to specify the TargetOriginId in a CacheBehavior or DefaultCacheBehavior. + // + // Id is a required field + Id *string `type:"string" required:"true"` - // Use this parameter when paginating results to indicate where to begin in - // your list of invalidation batches. Because the results are returned in decreasing - // order from most recent to oldest, the most recent results are on the first - // page, the second page will contain earlier results, and so on. To get the - // next page of results, set Marker to the value of the NextMarker from the - // current page's response. This value is the same as the ID of the last invalidation - // batch on that page. - Marker *string `location:"querystring" locationName:"Marker" type:"string"` + // An optional path that CloudFront appends to the origin domain name when CloudFront + // requests content from the origin. + // + // For more information, see Origin Path (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginPath) + // in the Amazon CloudFront Developer Guide. + OriginPath *string `type:"string"` - // The maximum number of invalidation batches that you want in the response - // body. - MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` + // Use this type to specify an origin that is an Amazon S3 bucket that is not + // configured with static website hosting. To specify any other type of origin, + // including an Amazon S3 bucket that is configured with static website hosting, + // use the CustomOriginConfig type instead. + S3OriginConfig *S3OriginConfig `type:"structure"` } // String returns the string representation -func (s ListInvalidationsInput) String() string { +func (s Origin) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListInvalidationsInput) GoString() string { +func (s Origin) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListInvalidationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListInvalidationsInput"} - if s.DistributionId == nil { - invalidParams.Add(request.NewErrParamRequired("DistributionId")) +func (s *Origin) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Origin"} + if s.DomainName == nil { + invalidParams.Add(request.NewErrParamRequired("DomainName")) } - if s.DistributionId != nil && len(*s.DistributionId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DistributionId", 1)) + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.CustomHeaders != nil { + if err := s.CustomHeaders.Validate(); err != nil { + invalidParams.AddNested("CustomHeaders", err.(request.ErrInvalidParams)) + } + } + if s.CustomOriginConfig != nil { + if err := s.CustomOriginConfig.Validate(); err != nil { + invalidParams.AddNested("CustomOriginConfig", err.(request.ErrInvalidParams)) + } + } + if s.S3OriginConfig != nil { + if err := s.S3OriginConfig.Validate(); err != nil { + invalidParams.AddNested("S3OriginConfig", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -11462,292 +15115,351 @@ func (s *ListInvalidationsInput) Validate() error { return nil } -// SetDistributionId sets the DistributionId field's value. -func (s *ListInvalidationsInput) SetDistributionId(v string) *ListInvalidationsInput { - s.DistributionId = &v +// SetConnectionAttempts sets the ConnectionAttempts field's value. +func (s *Origin) SetConnectionAttempts(v int64) *Origin { + s.ConnectionAttempts = &v return s } -// SetMarker sets the Marker field's value. -func (s *ListInvalidationsInput) SetMarker(v string) *ListInvalidationsInput { - s.Marker = &v +// SetConnectionTimeout sets the ConnectionTimeout field's value. +func (s *Origin) SetConnectionTimeout(v int64) *Origin { + s.ConnectionTimeout = &v return s } -// SetMaxItems sets the MaxItems field's value. -func (s *ListInvalidationsInput) SetMaxItems(v int64) *ListInvalidationsInput { - s.MaxItems = &v +// SetCustomHeaders sets the CustomHeaders field's value. +func (s *Origin) SetCustomHeaders(v *CustomHeaders) *Origin { + s.CustomHeaders = v return s } -// The returned result of the corresponding request. -type ListInvalidationsOutput struct { - _ struct{} `type:"structure" payload:"InvalidationList"` +// SetCustomOriginConfig sets the CustomOriginConfig field's value. +func (s *Origin) SetCustomOriginConfig(v *CustomOriginConfig) *Origin { + s.CustomOriginConfig = v + return s +} - // Information about invalidation batches. - InvalidationList *InvalidationList `type:"structure"` +// SetDomainName sets the DomainName field's value. +func (s *Origin) SetDomainName(v string) *Origin { + s.DomainName = &v + return s +} + +// SetId sets the Id field's value. +func (s *Origin) SetId(v string) *Origin { + s.Id = &v + return s +} + +// SetOriginPath sets the OriginPath field's value. +func (s *Origin) SetOriginPath(v string) *Origin { + s.OriginPath = &v + return s +} + +// SetS3OriginConfig sets the S3OriginConfig field's value. +func (s *Origin) SetS3OriginConfig(v *S3OriginConfig) *Origin { + s.S3OriginConfig = v + return s +} + +// CloudFront origin access identity. +type OriginAccessIdentity struct { + _ struct{} `type:"structure"` + + // The current configuration information for the identity. + CloudFrontOriginAccessIdentityConfig *OriginAccessIdentityConfig `type:"structure"` + + // The ID for the origin access identity, for example, E74FTE3AJFJ256A. + // + // Id is a required field + Id *string `type:"string" required:"true"` + + // The Amazon S3 canonical user ID for the origin access identity, used when + // giving the origin access identity read permission to an object in Amazon + // S3. + // + // S3CanonicalUserId is a required field + S3CanonicalUserId *string `type:"string" required:"true"` } // String returns the string representation -func (s ListInvalidationsOutput) String() string { +func (s OriginAccessIdentity) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListInvalidationsOutput) GoString() string { +func (s OriginAccessIdentity) GoString() string { return s.String() } -// SetInvalidationList sets the InvalidationList field's value. -func (s *ListInvalidationsOutput) SetInvalidationList(v *InvalidationList) *ListInvalidationsOutput { - s.InvalidationList = v +// SetCloudFrontOriginAccessIdentityConfig sets the CloudFrontOriginAccessIdentityConfig field's value. +func (s *OriginAccessIdentity) SetCloudFrontOriginAccessIdentityConfig(v *OriginAccessIdentityConfig) *OriginAccessIdentity { + s.CloudFrontOriginAccessIdentityConfig = v return s } -type ListPublicKeysInput struct { - _ struct{} `locationName:"ListPublicKeysRequest" type:"structure"` +// SetId sets the Id field's value. +func (s *OriginAccessIdentity) SetId(v string) *OriginAccessIdentity { + s.Id = &v + return s +} - // Use this when paginating results to indicate where to begin in your list - // of public keys. The results include public keys in the list that occur after - // the marker. To get the next page of results, set the Marker to the value - // of the NextMarker from the current page's response (which is also the ID - // of the last public key on that page). - Marker *string `location:"querystring" locationName:"Marker" type:"string"` +// SetS3CanonicalUserId sets the S3CanonicalUserId field's value. +func (s *OriginAccessIdentity) SetS3CanonicalUserId(v string) *OriginAccessIdentity { + s.S3CanonicalUserId = &v + return s +} - // The maximum number of public keys you want in the response body. - MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` +// Origin access identity configuration. Send a GET request to the /CloudFront +// API version/CloudFront/identity ID/config resource. +type OriginAccessIdentityConfig struct { + _ struct{} `type:"structure"` + + // A unique value (for example, a date-time stamp) that ensures that the request + // can't be replayed. + // + // If the value of CallerReference is new (regardless of the content of the + // CloudFrontOriginAccessIdentityConfig object), a new origin access identity + // is created. + // + // If the CallerReference is a value already sent in a previous identity request, + // and the content of the CloudFrontOriginAccessIdentityConfig is identical + // to the original request (ignoring white space), the response includes the + // same information returned to the original request. + // + // If the CallerReference is a value you already sent in a previous request + // to create an identity, but the content of the CloudFrontOriginAccessIdentityConfig + // is different from the original request, CloudFront returns a CloudFrontOriginAccessIdentityAlreadyExists + // error. + // + // CallerReference is a required field + CallerReference *string `type:"string" required:"true"` + + // Any comments you want to include about the origin access identity. + // + // Comment is a required field + Comment *string `type:"string" required:"true"` } // String returns the string representation -func (s ListPublicKeysInput) String() string { +func (s OriginAccessIdentityConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListPublicKeysInput) GoString() string { +func (s OriginAccessIdentityConfig) GoString() string { return s.String() } -// SetMarker sets the Marker field's value. -func (s *ListPublicKeysInput) SetMarker(v string) *ListPublicKeysInput { - s.Marker = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *OriginAccessIdentityConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OriginAccessIdentityConfig"} + if s.CallerReference == nil { + invalidParams.Add(request.NewErrParamRequired("CallerReference")) + } + if s.Comment == nil { + invalidParams.Add(request.NewErrParamRequired("Comment")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCallerReference sets the CallerReference field's value. +func (s *OriginAccessIdentityConfig) SetCallerReference(v string) *OriginAccessIdentityConfig { + s.CallerReference = &v return s } -// SetMaxItems sets the MaxItems field's value. -func (s *ListPublicKeysInput) SetMaxItems(v int64) *ListPublicKeysInput { - s.MaxItems = &v +// SetComment sets the Comment field's value. +func (s *OriginAccessIdentityConfig) SetComment(v string) *OriginAccessIdentityConfig { + s.Comment = &v return s } -type ListPublicKeysOutput struct { - _ struct{} `type:"structure" payload:"PublicKeyList"` +// Lists the origin access identities for CloudFront.Send a GET request to the +// /CloudFront API version/origin-access-identity/cloudfront resource. The response +// includes a CloudFrontOriginAccessIdentityList element with zero or more CloudFrontOriginAccessIdentitySummary +// 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. +type OriginAccessIdentityList struct { + _ struct{} `type:"structure"` - // Returns a list of all public keys that have been added to CloudFront for - // this account. - PublicKeyList *PublicKeyList `type:"structure"` + // A flag that indicates whether more origin access identities remain to be + // listed. If your results were truncated, you can make a follow-up pagination + // request using the Marker request parameter to retrieve more items in the + // list. + // + // IsTruncated is a required field + IsTruncated *bool `type:"boolean" required:"true"` + + // A complex type that contains one CloudFrontOriginAccessIdentitySummary element + // for each origin access identity that was created by the current AWS account. + Items []*OriginAccessIdentitySummary `locationNameList:"CloudFrontOriginAccessIdentitySummary" type:"list"` + + // Use this when paginating results to indicate where to begin in your list + // of origin access identities. The results include identities in the list that + // occur after the marker. To get the next page of results, set the Marker to + // the value of the NextMarker from the current page's response (which is also + // the ID of the last identity on that page). + // + // Marker is a required field + Marker *string `type:"string" required:"true"` + + // The maximum number of origin access identities you want in the response body. + // + // MaxItems is a required field + MaxItems *int64 `type:"integer" required:"true"` + + // If IsTruncated is true, this element is present and contains the value you + // can use for the Marker request parameter to continue listing your origin + // access identities where they left off. + NextMarker *string `type:"string"` + + // The number of CloudFront origin access identities that were created by the + // current AWS account. + // + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s ListPublicKeysOutput) String() string { +func (s OriginAccessIdentityList) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListPublicKeysOutput) GoString() string { +func (s OriginAccessIdentityList) GoString() string { return s.String() } -// SetPublicKeyList sets the PublicKeyList field's value. -func (s *ListPublicKeysOutput) SetPublicKeyList(v *PublicKeyList) *ListPublicKeysOutput { - s.PublicKeyList = v +// SetIsTruncated sets the IsTruncated field's value. +func (s *OriginAccessIdentityList) SetIsTruncated(v bool) *OriginAccessIdentityList { + s.IsTruncated = &v return s } -// The request to list your streaming distributions. -type ListStreamingDistributionsInput struct { - _ struct{} `locationName:"ListStreamingDistributionsRequest" type:"structure"` - - // The value that you provided for the Marker request parameter. - Marker *string `location:"querystring" locationName:"Marker" type:"string"` - - // The value that you provided for the MaxItems request parameter. - MaxItems *int64 `location:"querystring" locationName:"MaxItems" type:"integer"` -} - -// String returns the string representation -func (s ListStreamingDistributionsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListStreamingDistributionsInput) GoString() string { - return s.String() +// SetItems sets the Items field's value. +func (s *OriginAccessIdentityList) SetItems(v []*OriginAccessIdentitySummary) *OriginAccessIdentityList { + s.Items = v + return s } // SetMarker sets the Marker field's value. -func (s *ListStreamingDistributionsInput) SetMarker(v string) *ListStreamingDistributionsInput { +func (s *OriginAccessIdentityList) SetMarker(v string) *OriginAccessIdentityList { s.Marker = &v return s } // SetMaxItems sets the MaxItems field's value. -func (s *ListStreamingDistributionsInput) SetMaxItems(v int64) *ListStreamingDistributionsInput { +func (s *OriginAccessIdentityList) SetMaxItems(v int64) *OriginAccessIdentityList { s.MaxItems = &v return s } -// The returned result of the corresponding request. -type ListStreamingDistributionsOutput struct { - _ struct{} `type:"structure" payload:"StreamingDistributionList"` - - // The StreamingDistributionList type. - StreamingDistributionList *StreamingDistributionList `type:"structure"` +// SetNextMarker sets the NextMarker field's value. +func (s *OriginAccessIdentityList) SetNextMarker(v string) *OriginAccessIdentityList { + s.NextMarker = &v + return s } -// String returns the string representation -func (s ListStreamingDistributionsOutput) String() string { - return awsutil.Prettify(s) +// SetQuantity sets the Quantity field's value. +func (s *OriginAccessIdentityList) SetQuantity(v int64) *OriginAccessIdentityList { + s.Quantity = &v + return s } -// GoString returns the string representation -func (s ListStreamingDistributionsOutput) GoString() string { - return s.String() -} +// Summary of the information about a CloudFront origin access identity. +type OriginAccessIdentitySummary struct { + _ struct{} `type:"structure"` -// SetStreamingDistributionList sets the StreamingDistributionList field's value. -func (s *ListStreamingDistributionsOutput) SetStreamingDistributionList(v *StreamingDistributionList) *ListStreamingDistributionsOutput { - s.StreamingDistributionList = v - return s -} + // The comment for this origin access identity, as originally specified when + // created. + // + // Comment is a required field + Comment *string `type:"string" required:"true"` -// The request to list tags for a CloudFront resource. -type ListTagsForResourceInput struct { - _ struct{} `locationName:"ListTagsForResourceRequest" type:"structure"` + // The ID for the origin access identity. For example: E74FTE3AJFJ256A. + // + // Id is a required field + Id *string `type:"string" required:"true"` - // An ARN of a CloudFront resource. + // The Amazon S3 canonical user ID for the origin access identity, which you + // use when giving the origin access identity read permission to an object in + // Amazon S3. // - // Resource is a required field - Resource *string `location:"querystring" locationName:"Resource" type:"string" required:"true"` + // S3CanonicalUserId is a required field + S3CanonicalUserId *string `type:"string" required:"true"` } // String returns the string representation -func (s ListTagsForResourceInput) String() string { +func (s OriginAccessIdentitySummary) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListTagsForResourceInput) GoString() string { +func (s OriginAccessIdentitySummary) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTagsForResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} - 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 *ListTagsForResourceInput) SetResource(v string) *ListTagsForResourceInput { - s.Resource = &v +// SetComment sets the Comment field's value. +func (s *OriginAccessIdentitySummary) SetComment(v string) *OriginAccessIdentitySummary { + s.Comment = &v return s } -// The returned result of the corresponding request. -type ListTagsForResourceOutput struct { - _ struct{} `type:"structure" payload:"Tags"` - - // A complex type that contains zero or more Tag elements. - // - // Tags is a required field - Tags *Tags `type:"structure" required:"true"` -} - -// String returns the string representation -func (s ListTagsForResourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTagsForResourceOutput) GoString() string { - return s.String() +// SetId sets the Id field's value. +func (s *OriginAccessIdentitySummary) SetId(v string) *OriginAccessIdentitySummary { + s.Id = &v + return s } -// SetTags sets the Tags field's value. -func (s *ListTagsForResourceOutput) SetTags(v *Tags) *ListTagsForResourceOutput { - s.Tags = v +// SetS3CanonicalUserId sets the S3CanonicalUserId field's value. +func (s *OriginAccessIdentitySummary) SetS3CanonicalUserId(v string) *OriginAccessIdentitySummary { + s.S3CanonicalUserId = &v return s } -// A complex type that controls whether access logs are written for the distribution. -type LoggingConfig struct { +// A complex type that contains HeaderName and HeaderValue elements, if any, +// for this distribution. +type OriginCustomHeader struct { _ struct{} `type:"structure"` - // The Amazon S3 bucket to store the access logs in, for example, myawslogbucket.s3.amazonaws.com. - // - // Bucket is a required field - Bucket *string `type:"string" required:"true"` - - // Specifies whether you want CloudFront to save access logs to an Amazon S3 - // bucket. If you don't 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. If you specify - // false for Enabled but you specify values for Bucket, prefix, and IncludeCookies, - // the values are automatically deleted. - // - // Enabled is a required field - Enabled *bool `type:"boolean" required:"true"` - - // Specifies whether you want CloudFront to include cookies in access logs, - // specify true for IncludeCookies. If you choose to include cookies in logs, - // CloudFront logs all cookies regardless of how you configure the cache behaviors - // for this distribution. If you don't want to include cookies when you create - // a distribution or if you want to disable include cookies for an existing - // distribution, specify false for IncludeCookies. + // The name of a header that you want CloudFront to send to your origin. For + // more information, see Adding Custom Headers to Origin Requests (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/forward-custom-headers.html) + // in the Amazon CloudFront Developer Guide. // - // IncludeCookies is a required field - IncludeCookies *bool `type:"boolean" required:"true"` + // HeaderName is a required field + HeaderName *string `type:"string" required:"true"` - // An optional string that you want CloudFront to prefix to the access log filenames - // for this distribution, for example, myprefix/. If you want to enable logging, - // but you don't want to specify a prefix, you still must include an empty Prefix - // element in the Logging element. + // The value for the header that you specified in the HeaderName field. // - // Prefix is a required field - Prefix *string `type:"string" required:"true"` + // HeaderValue is a required field + HeaderValue *string `type:"string" required:"true"` } // String returns the string representation -func (s LoggingConfig) String() string { +func (s OriginCustomHeader) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s LoggingConfig) GoString() string { +func (s OriginCustomHeader) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *LoggingConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LoggingConfig"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Enabled == nil { - invalidParams.Add(request.NewErrParamRequired("Enabled")) - } - if s.IncludeCookies == nil { - invalidParams.Add(request.NewErrParamRequired("IncludeCookies")) +func (s *OriginCustomHeader) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OriginCustomHeader"} + if s.HeaderName == nil { + invalidParams.Add(request.NewErrParamRequired("HeaderName")) } - if s.Prefix == nil { - invalidParams.Add(request.NewErrParamRequired("Prefix")) + if s.HeaderValue == nil { + invalidParams.Add(request.NewErrParamRequired("HeaderValue")) } if invalidParams.Len() > 0 { @@ -11756,155 +15468,74 @@ func (s *LoggingConfig) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *LoggingConfig) SetBucket(v string) *LoggingConfig { - s.Bucket = &v - return s -} - -// SetEnabled sets the Enabled field's value. -func (s *LoggingConfig) SetEnabled(v bool) *LoggingConfig { - s.Enabled = &v - return s -} - -// SetIncludeCookies sets the IncludeCookies field's value. -func (s *LoggingConfig) SetIncludeCookies(v bool) *LoggingConfig { - s.IncludeCookies = &v +// SetHeaderName sets the HeaderName field's value. +func (s *OriginCustomHeader) SetHeaderName(v string) *OriginCustomHeader { + s.HeaderName = &v return s } -// SetPrefix sets the Prefix field's value. -func (s *LoggingConfig) SetPrefix(v string) *LoggingConfig { - s.Prefix = &v +// SetHeaderValue sets the HeaderValue field's value. +func (s *OriginCustomHeader) SetHeaderValue(v string) *OriginCustomHeader { + s.HeaderValue = &v return s } -// A complex type that describes the Amazon S3 bucket, HTTP server (for example, -// a web server), Amazon MediaStore, or other server from which CloudFront gets -// your files. This can also be an origin group, if you've created an origin -// group. You must specify at least one origin or origin group. -// -// For the current limit on the number of origins or origin groups that you -// can specify for a distribution, see Amazon CloudFront Limits (https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_cloudfront) -// in the AWS General Reference. -type Origin struct { +// An origin group includes two origins (a primary origin and a second origin +// to failover to) and a failover criteria that you specify. You create an origin +// group to support origin failover in CloudFront. When you create or update +// a distribution, you can specifiy the origin group instead of a single origin, +// and CloudFront will failover from the primary origin to the second origin +// under the failover conditions that you've chosen. +type OriginGroup struct { _ struct{} `type:"structure"` - // A complex type that contains names and values for the custom headers that - // you want. - CustomHeaders *CustomHeaders `type:"structure"` - - // A complex type that contains information about a custom origin. If the origin - // is an Amazon S3 bucket, use the S3OriginConfig element instead. - CustomOriginConfig *CustomOriginConfig `type:"structure"` - - // Amazon S3 origins: The DNS name of the Amazon S3 bucket from which you want - // CloudFront to get objects for this origin, for example, myawsbucket.s3.amazonaws.com. - // If you set up your bucket to be configured as a website endpoint, enter the - // Amazon S3 static website hosting endpoint for the bucket. - // - // For more information about specifying this value for different types of origins, - // see Origin Domain Name (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesDomainName) - // in the Amazon CloudFront Developer Guide. - // - // Constraints for Amazon S3 origins: - // - // * If you configured Amazon S3 Transfer Acceleration for your bucket, don't - // specify the s3-accelerate endpoint for DomainName. - // - // * The bucket name must be between 3 and 63 characters long (inclusive). - // - // * The bucket name must contain only lowercase characters, numbers, periods, - // underscores, and dashes. - // - // * The bucket name must not contain adjacent periods. - // - // Custom Origins: The DNS domain name for the HTTP server from which you want - // CloudFront to get objects for this origin, for example, www.example.com. - // - // Constraints for custom origins: - // - // * DomainName must be a valid DNS name that contains only a-z, A-Z, 0-9, - // dot (.), hyphen (-), or underscore (_) characters. - // - // * The name cannot exceed 128 characters. - // - // DomainName is a required field - DomainName *string `type:"string" required:"true"` - - // A unique identifier for the origin or origin group. The value of Id must - // be unique within the distribution. + // A complex type that contains information about the failover criteria for + // an origin group. // - // When you specify the value of TargetOriginId for the default cache behavior - // or for another cache behavior, you indicate the origin to which you want - // the cache behavior to route requests by specifying the value of the Id element - // for that origin. When a request matches the path pattern for that cache behavior, - // CloudFront routes the request to the specified origin. For more information, - // see Cache Behavior Settings (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesCacheBehavior) - // in the Amazon CloudFront Developer Guide. + // FailoverCriteria is a required field + FailoverCriteria *OriginGroupFailoverCriteria `type:"structure" required:"true"` + + // The origin group's ID. // // Id is a required field Id *string `type:"string" required:"true"` - // An optional element that causes CloudFront to request your content from a - // directory in your Amazon S3 bucket or your custom origin. When you include - // the OriginPath element, specify the directory name, beginning with a /. CloudFront - // appends the directory name to the value of DomainName, for example, example.com/production. - // Do not include a / at the end of the directory name. - // - // For example, suppose you've specified the following values for your distribution: - // - // * DomainName: An Amazon S3 bucket named myawsbucket. - // - // * OriginPath: /production - // - // * CNAME: example.com - // - // When a user enters example.com/index.html in a browser, CloudFront sends - // a request to Amazon S3 for myawsbucket/production/index.html. + // A complex type that contains information about the origins in an origin group. // - // When a user enters example.com/acme/index.html in a browser, CloudFront sends - // a request to Amazon S3 for myawsbucket/production/acme/index.html. - OriginPath *string `type:"string"` - - // A complex type that contains information about the Amazon S3 origin. If the - // origin is a custom origin, use the CustomOriginConfig element instead. - S3OriginConfig *S3OriginConfig `type:"structure"` + // Members is a required field + Members *OriginGroupMembers `type:"structure" required:"true"` } // String returns the string representation -func (s Origin) String() string { +func (s OriginGroup) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Origin) GoString() string { +func (s OriginGroup) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *Origin) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Origin"} - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) +func (s *OriginGroup) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OriginGroup"} + if s.FailoverCriteria == nil { + invalidParams.Add(request.NewErrParamRequired("FailoverCriteria")) } if s.Id == nil { invalidParams.Add(request.NewErrParamRequired("Id")) } - if s.CustomHeaders != nil { - if err := s.CustomHeaders.Validate(); err != nil { - invalidParams.AddNested("CustomHeaders", err.(request.ErrInvalidParams)) - } + if s.Members == nil { + invalidParams.Add(request.NewErrParamRequired("Members")) } - if s.CustomOriginConfig != nil { - if err := s.CustomOriginConfig.Validate(); err != nil { - invalidParams.AddNested("CustomOriginConfig", err.(request.ErrInvalidParams)) + if s.FailoverCriteria != nil { + if err := s.FailoverCriteria.Validate(); err != nil { + invalidParams.AddNested("FailoverCriteria", err.(request.ErrInvalidParams)) } } - if s.S3OriginConfig != nil { - if err := s.S3OriginConfig.Validate(); err != nil { - invalidParams.AddNested("S3OriginConfig", err.(request.ErrInvalidParams)) + if s.Members != nil { + if err := s.Members.Validate(); err != nil { + invalidParams.AddNested("Members", err.(request.ErrInvalidParams)) } } @@ -11914,139 +15545,96 @@ func (s *Origin) Validate() error { return nil } -// SetCustomHeaders sets the CustomHeaders field's value. -func (s *Origin) SetCustomHeaders(v *CustomHeaders) *Origin { - s.CustomHeaders = v - return s -} - -// SetCustomOriginConfig sets the CustomOriginConfig field's value. -func (s *Origin) SetCustomOriginConfig(v *CustomOriginConfig) *Origin { - s.CustomOriginConfig = v - return s -} - -// SetDomainName sets the DomainName field's value. -func (s *Origin) SetDomainName(v string) *Origin { - s.DomainName = &v +// SetFailoverCriteria sets the FailoverCriteria field's value. +func (s *OriginGroup) SetFailoverCriteria(v *OriginGroupFailoverCriteria) *OriginGroup { + s.FailoverCriteria = v return s } // SetId sets the Id field's value. -func (s *Origin) SetId(v string) *Origin { +func (s *OriginGroup) SetId(v string) *OriginGroup { s.Id = &v return s } -// SetOriginPath sets the OriginPath field's value. -func (s *Origin) SetOriginPath(v string) *Origin { - s.OriginPath = &v - return s -} - -// SetS3OriginConfig sets the S3OriginConfig field's value. -func (s *Origin) SetS3OriginConfig(v *S3OriginConfig) *Origin { - s.S3OriginConfig = v +// SetMembers sets the Members field's value. +func (s *OriginGroup) SetMembers(v *OriginGroupMembers) *OriginGroup { + s.Members = v return s } -// CloudFront origin access identity. -type OriginAccessIdentity struct { +// A complex data type that includes information about the failover criteria +// for an origin group, including the status codes for which CloudFront will +// failover from the primary origin to the second origin. +type OriginGroupFailoverCriteria struct { _ struct{} `type:"structure"` - // The current configuration information for the identity. - CloudFrontOriginAccessIdentityConfig *OriginAccessIdentityConfig `type:"structure"` - - // The ID for the origin access identity, for example, E74FTE3AJFJ256A. - // - // Id is a required field - Id *string `type:"string" required:"true"` - - // The Amazon S3 canonical user ID for the origin access identity, used when - // giving the origin access identity read permission to an object in Amazon - // S3. + // The status codes that, when returned from the primary origin, will trigger + // CloudFront to failover to the second origin. // - // S3CanonicalUserId is a required field - S3CanonicalUserId *string `type:"string" required:"true"` + // StatusCodes is a required field + StatusCodes *StatusCodes `type:"structure" required:"true"` } // String returns the string representation -func (s OriginAccessIdentity) String() string { +func (s OriginGroupFailoverCriteria) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s OriginAccessIdentity) GoString() string { +func (s OriginGroupFailoverCriteria) GoString() string { return s.String() } -// SetCloudFrontOriginAccessIdentityConfig sets the CloudFrontOriginAccessIdentityConfig field's value. -func (s *OriginAccessIdentity) SetCloudFrontOriginAccessIdentityConfig(v *OriginAccessIdentityConfig) *OriginAccessIdentity { - s.CloudFrontOriginAccessIdentityConfig = v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *OriginGroupFailoverCriteria) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OriginGroupFailoverCriteria"} + if s.StatusCodes == nil { + invalidParams.Add(request.NewErrParamRequired("StatusCodes")) + } + if s.StatusCodes != nil { + if err := s.StatusCodes.Validate(); err != nil { + invalidParams.AddNested("StatusCodes", err.(request.ErrInvalidParams)) + } + } -// SetId sets the Id field's value. -func (s *OriginAccessIdentity) SetId(v string) *OriginAccessIdentity { - s.Id = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetS3CanonicalUserId sets the S3CanonicalUserId field's value. -func (s *OriginAccessIdentity) SetS3CanonicalUserId(v string) *OriginAccessIdentity { - s.S3CanonicalUserId = &v +// SetStatusCodes sets the StatusCodes field's value. +func (s *OriginGroupFailoverCriteria) SetStatusCodes(v *StatusCodes) *OriginGroupFailoverCriteria { + s.StatusCodes = v return s } -// Origin access identity configuration. Send a GET request to the /CloudFront -// API version/CloudFront/identity ID/config resource. -type OriginAccessIdentityConfig struct { +// An origin in an origin group. +type OriginGroupMember struct { _ struct{} `type:"structure"` - // A unique value (for example, a date-time stamp) that ensures that the request - // can't be replayed. - // - // If the value of CallerReference is new (regardless of the content of the - // CloudFrontOriginAccessIdentityConfig object), a new origin access identity - // is created. - // - // If the CallerReference is a value already sent in a previous identity request, - // and the content of the CloudFrontOriginAccessIdentityConfig is identical - // to the original request (ignoring white space), the response includes the - // same information returned to the original request. - // - // If the CallerReference is a value you already sent in a previous request - // to create an identity, but the content of the CloudFrontOriginAccessIdentityConfig - // is different from the original request, CloudFront returns a CloudFrontOriginAccessIdentityAlreadyExists - // error. - // - // CallerReference is a required field - CallerReference *string `type:"string" required:"true"` - - // Any comments you want to include about the origin access identity. + // The ID for an origin in an origin group. // - // Comment is a required field - Comment *string `type:"string" required:"true"` + // OriginId is a required field + OriginId *string `type:"string" required:"true"` } // String returns the string representation -func (s OriginAccessIdentityConfig) String() string { +func (s OriginGroupMember) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s OriginAccessIdentityConfig) GoString() string { +func (s OriginGroupMember) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *OriginAccessIdentityConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "OriginAccessIdentityConfig"} - if s.CallerReference == nil { - invalidParams.Add(request.NewErrParamRequired("CallerReference")) - } - if s.Comment == nil { - invalidParams.Add(request.NewErrParamRequired("Comment")) +func (s *OriginGroupMember) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OriginGroupMember"} + if s.OriginId == nil { + invalidParams.Add(request.NewErrParamRequired("OriginId")) } if invalidParams.Len() > 0 { @@ -12055,275 +15643,289 @@ func (s *OriginAccessIdentityConfig) Validate() error { return nil } -// SetCallerReference sets the CallerReference field's value. -func (s *OriginAccessIdentityConfig) SetCallerReference(v string) *OriginAccessIdentityConfig { - s.CallerReference = &v - return s -} - -// SetComment sets the Comment field's value. -func (s *OriginAccessIdentityConfig) SetComment(v string) *OriginAccessIdentityConfig { - s.Comment = &v +// SetOriginId sets the OriginId field's value. +func (s *OriginGroupMember) SetOriginId(v string) *OriginGroupMember { + s.OriginId = &v return s } -// Lists the origin access identities for CloudFront.Send a GET request to the -// /CloudFront API version/origin-access-identity/cloudfront resource. The response -// includes a CloudFrontOriginAccessIdentityList element with zero or more CloudFrontOriginAccessIdentitySummary -// 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. -type OriginAccessIdentityList struct { +// A complex data type for the origins included in an origin group. +type OriginGroupMembers struct { _ struct{} `type:"structure"` - // A flag that indicates whether more origin access identities remain to be - // listed. If your results were truncated, you can make a follow-up pagination - // request using the Marker request parameter to retrieve more items in the - // list. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // A complex type that contains one CloudFrontOriginAccessIdentitySummary element - // for each origin access identity that was created by the current AWS account. - Items []*OriginAccessIdentitySummary `locationNameList:"CloudFrontOriginAccessIdentitySummary" type:"list"` - - // Use this when paginating results to indicate where to begin in your list - // of origin access identities. The results include identities in the list that - // occur after the marker. To get the next page of results, set the Marker to - // the value of the NextMarker from the current page's response (which is also - // the ID of the last identity on that page). - // - // Marker is a required field - Marker *string `type:"string" required:"true"` - - // The maximum number of origin access identities you want in the response body. + // Items (origins) in an origin group. // - // MaxItems is a required field - MaxItems *int64 `type:"integer" required:"true"` - - // If IsTruncated is true, this element is present and contains the value you - // can use for the Marker request parameter to continue listing your origin - // access identities where they left off. - NextMarker *string `type:"string"` + // Items is a required field + Items []*OriginGroupMember `locationNameList:"OriginGroupMember" min:"2" type:"list" required:"true"` - // The number of CloudFront origin access identities that were created by the - // current AWS account. + // The number of origins in an origin group. // // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` -} - -// String returns the string representation -func (s OriginAccessIdentityList) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s OriginAccessIdentityList) GoString() string { - return s.String() -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *OriginAccessIdentityList) SetIsTruncated(v bool) *OriginAccessIdentityList { - s.IsTruncated = &v - return s + Quantity *int64 `type:"integer" required:"true"` } -// SetItems sets the Items field's value. -func (s *OriginAccessIdentityList) SetItems(v []*OriginAccessIdentitySummary) *OriginAccessIdentityList { - s.Items = v - return s +// String returns the string representation +func (s OriginGroupMembers) String() string { + return awsutil.Prettify(s) } -// SetMarker sets the Marker field's value. -func (s *OriginAccessIdentityList) SetMarker(v string) *OriginAccessIdentityList { - s.Marker = &v - return s +// GoString returns the string representation +func (s OriginGroupMembers) GoString() string { + return s.String() } -// SetMaxItems sets the MaxItems field's value. -func (s *OriginAccessIdentityList) SetMaxItems(v int64) *OriginAccessIdentityList { - s.MaxItems = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *OriginGroupMembers) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OriginGroupMembers"} + if s.Items == nil { + invalidParams.Add(request.NewErrParamRequired("Items")) + } + if s.Items != nil && len(s.Items) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Items", 2)) + } + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) + } + if s.Items != nil { + for i, v := range s.Items { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetNextMarker sets the NextMarker field's value. -func (s *OriginAccessIdentityList) SetNextMarker(v string) *OriginAccessIdentityList { - s.NextMarker = &v +// SetItems sets the Items field's value. +func (s *OriginGroupMembers) SetItems(v []*OriginGroupMember) *OriginGroupMembers { + s.Items = v return s } // SetQuantity sets the Quantity field's value. -func (s *OriginAccessIdentityList) SetQuantity(v int64) *OriginAccessIdentityList { +func (s *OriginGroupMembers) SetQuantity(v int64) *OriginGroupMembers { s.Quantity = &v return s } -// Summary of the information about a CloudFront origin access identity. -type OriginAccessIdentitySummary struct { +// A complex data type for the origin groups specified for a distribution. +type OriginGroups struct { _ struct{} `type:"structure"` - // The comment for this origin access identity, as originally specified when - // created. - // - // Comment is a required field - Comment *string `type:"string" required:"true"` - - // The ID for the origin access identity. For example: E74FTE3AJFJ256A. - // - // Id is a required field - Id *string `type:"string" required:"true"` + // The items (origin groups) in a distribution. + Items []*OriginGroup `locationNameList:"OriginGroup" type:"list"` - // The Amazon S3 canonical user ID for the origin access identity, which you - // use when giving the origin access identity read permission to an object in - // Amazon S3. + // The number of origin groups. // - // S3CanonicalUserId is a required field - S3CanonicalUserId *string `type:"string" required:"true"` + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s OriginAccessIdentitySummary) String() string { +func (s OriginGroups) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s OriginAccessIdentitySummary) GoString() string { +func (s OriginGroups) GoString() string { return s.String() } -// SetComment sets the Comment field's value. -func (s *OriginAccessIdentitySummary) SetComment(v string) *OriginAccessIdentitySummary { - s.Comment = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *OriginGroups) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OriginGroups"} + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) + } + if s.Items != nil { + for i, v := range s.Items { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetId sets the Id field's value. -func (s *OriginAccessIdentitySummary) SetId(v string) *OriginAccessIdentitySummary { - s.Id = &v +// SetItems sets the Items field's value. +func (s *OriginGroups) SetItems(v []*OriginGroup) *OriginGroups { + s.Items = v return s } -// SetS3CanonicalUserId sets the S3CanonicalUserId field's value. -func (s *OriginAccessIdentitySummary) SetS3CanonicalUserId(v string) *OriginAccessIdentitySummary { - s.S3CanonicalUserId = &v +// SetQuantity sets the Quantity field's value. +func (s *OriginGroups) SetQuantity(v int64) *OriginGroups { + s.Quantity = &v return s } -// A complex type that contains HeaderName and HeaderValue elements, if any, -// for this distribution. -type OriginCustomHeader struct { +// An origin request policy. +// +// When it’s attached to a cache behavior, the origin request policy determines +// the values that CloudFront includes in requests that it sends to the origin. +// Each request that CloudFront sends to the origin includes the following: +// +// * The request body and the URL path (without the domain name) from the +// viewer request. +// +// * The headers that CloudFront automatically includes in every origin request, +// including Host, User-Agent, and X-Amz-Cf-Id. +// +// * All HTTP headers, cookies, and URL query strings that are specified +// in the cache policy or the origin request policy. These can include items +// from the viewer request and, in the case of headers, additional ones that +// are added by CloudFront. +// +// CloudFront sends a request when it can’t find an object in its cache that +// matches the request. If you want to send values to the origin and also include +// them in the cache key, use CreateCachePolicy. +type OriginRequestPolicy struct { _ struct{} `type:"structure"` - // The name of a header that you want CloudFront to forward to your origin. - // For more information, see Forwarding Custom Headers to Your Origin (Web Distributions - // Only) (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/forward-custom-headers.html) - // in the Amazon CloudFront Developer Guide. + // The unique identifier for the origin request policy. // - // HeaderName is a required field - HeaderName *string `type:"string" required:"true"` + // Id is a required field + Id *string `type:"string" required:"true"` - // The value for the header that you specified in the HeaderName field. + // The date and time when the origin request policy was last modified. // - // HeaderValue is a required field - HeaderValue *string `type:"string" required:"true"` + // LastModifiedTime is a required field + LastModifiedTime *time.Time `type:"timestamp" required:"true"` + + // The origin request policy configuration. + // + // OriginRequestPolicyConfig is a required field + OriginRequestPolicyConfig *OriginRequestPolicyConfig `type:"structure" required:"true"` } // String returns the string representation -func (s OriginCustomHeader) String() string { +func (s OriginRequestPolicy) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s OriginCustomHeader) GoString() string { +func (s OriginRequestPolicy) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *OriginCustomHeader) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "OriginCustomHeader"} - if s.HeaderName == nil { - invalidParams.Add(request.NewErrParamRequired("HeaderName")) - } - if s.HeaderValue == nil { - invalidParams.Add(request.NewErrParamRequired("HeaderValue")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetId sets the Id field's value. +func (s *OriginRequestPolicy) SetId(v string) *OriginRequestPolicy { + s.Id = &v + return s } -// SetHeaderName sets the HeaderName field's value. -func (s *OriginCustomHeader) SetHeaderName(v string) *OriginCustomHeader { - s.HeaderName = &v +// SetLastModifiedTime sets the LastModifiedTime field's value. +func (s *OriginRequestPolicy) SetLastModifiedTime(v time.Time) *OriginRequestPolicy { + s.LastModifiedTime = &v return s } -// SetHeaderValue sets the HeaderValue field's value. -func (s *OriginCustomHeader) SetHeaderValue(v string) *OriginCustomHeader { - s.HeaderValue = &v +// SetOriginRequestPolicyConfig sets the OriginRequestPolicyConfig field's value. +func (s *OriginRequestPolicy) SetOriginRequestPolicyConfig(v *OriginRequestPolicyConfig) *OriginRequestPolicy { + s.OriginRequestPolicyConfig = v return s } -// An origin group includes two origins (a primary origin and a second origin -// to failover to) and a failover criteria that you specify. You create an origin -// group to support origin failover in CloudFront. When you create or update -// a distribution, you can specifiy the origin group instead of a single origin, -// and CloudFront will failover from the primary origin to the second origin -// under the failover conditions that you've chosen. -type OriginGroup struct { +// An origin request policy configuration. +// +// This configuration determines the values that CloudFront includes in requests +// that it sends to the origin. Each request that CloudFront sends to the origin +// includes the following: +// +// * The request body and the URL path (without the domain name) from the +// viewer request. +// +// * The headers that CloudFront automatically includes in every origin request, +// including Host, User-Agent, and X-Amz-Cf-Id. +// +// * All HTTP headers, cookies, and URL query strings that are specified +// in the cache policy or the origin request policy. These can include items +// from the viewer request and, in the case of headers, additional ones that +// are added by CloudFront. +// +// CloudFront sends a request when it can’t find an object in its cache that +// matches the request. If you want to send values to the origin and also include +// them in the cache key, use CreateCachePolicy. +type OriginRequestPolicyConfig struct { _ struct{} `type:"structure"` - // A complex type that contains information about the failover criteria for - // an origin group. + // A comment to describe the origin request policy. + Comment *string `type:"string"` + + // The cookies from viewer requests to include in origin requests. // - // FailoverCriteria is a required field - FailoverCriteria *OriginGroupFailoverCriteria `type:"structure" required:"true"` + // CookiesConfig is a required field + CookiesConfig *OriginRequestPolicyCookiesConfig `type:"structure" required:"true"` - // The origin group's ID. + // The HTTP headers to include in origin requests. These can include headers + // from viewer requests and additional headers added by CloudFront. // - // Id is a required field - Id *string `type:"string" required:"true"` + // HeadersConfig is a required field + HeadersConfig *OriginRequestPolicyHeadersConfig `type:"structure" required:"true"` - // A complex type that contains information about the origins in an origin group. + // A unique name to identify the origin request policy. // - // Members is a required field - Members *OriginGroupMembers `type:"structure" required:"true"` + // Name is a required field + Name *string `type:"string" required:"true"` + + // The URL query strings from viewer requests to include in origin requests. + // + // QueryStringsConfig is a required field + QueryStringsConfig *OriginRequestPolicyQueryStringsConfig `type:"structure" required:"true"` } // String returns the string representation -func (s OriginGroup) String() string { +func (s OriginRequestPolicyConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s OriginGroup) GoString() string { +func (s OriginRequestPolicyConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *OriginGroup) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "OriginGroup"} - if s.FailoverCriteria == nil { - invalidParams.Add(request.NewErrParamRequired("FailoverCriteria")) +func (s *OriginRequestPolicyConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OriginRequestPolicyConfig"} + if s.CookiesConfig == nil { + invalidParams.Add(request.NewErrParamRequired("CookiesConfig")) } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) + if s.HeadersConfig == nil { + invalidParams.Add(request.NewErrParamRequired("HeadersConfig")) } - if s.Members == nil { - invalidParams.Add(request.NewErrParamRequired("Members")) + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) } - if s.FailoverCriteria != nil { - if err := s.FailoverCriteria.Validate(); err != nil { - invalidParams.AddNested("FailoverCriteria", err.(request.ErrInvalidParams)) + if s.QueryStringsConfig == nil { + invalidParams.Add(request.NewErrParamRequired("QueryStringsConfig")) + } + if s.CookiesConfig != nil { + if err := s.CookiesConfig.Validate(); err != nil { + invalidParams.AddNested("CookiesConfig", err.(request.ErrInvalidParams)) } } - if s.Members != nil { - if err := s.Members.Validate(); err != nil { - invalidParams.AddNested("Members", err.(request.ErrInvalidParams)) + if s.HeadersConfig != nil { + if err := s.HeadersConfig.Validate(); err != nil { + invalidParams.AddNested("HeadersConfig", err.(request.ErrInvalidParams)) + } + } + if s.QueryStringsConfig != nil { + if err := s.QueryStringsConfig.Validate(); err != nil { + invalidParams.AddNested("QueryStringsConfig", err.(request.ErrInvalidParams)) } } @@ -12333,56 +15935,82 @@ func (s *OriginGroup) Validate() error { return nil } -// SetFailoverCriteria sets the FailoverCriteria field's value. -func (s *OriginGroup) SetFailoverCriteria(v *OriginGroupFailoverCriteria) *OriginGroup { - s.FailoverCriteria = v +// SetComment sets the Comment field's value. +func (s *OriginRequestPolicyConfig) SetComment(v string) *OriginRequestPolicyConfig { + s.Comment = &v return s } -// SetId sets the Id field's value. -func (s *OriginGroup) SetId(v string) *OriginGroup { - s.Id = &v +// SetCookiesConfig sets the CookiesConfig field's value. +func (s *OriginRequestPolicyConfig) SetCookiesConfig(v *OriginRequestPolicyCookiesConfig) *OriginRequestPolicyConfig { + s.CookiesConfig = v return s } -// SetMembers sets the Members field's value. -func (s *OriginGroup) SetMembers(v *OriginGroupMembers) *OriginGroup { - s.Members = v +// SetHeadersConfig sets the HeadersConfig field's value. +func (s *OriginRequestPolicyConfig) SetHeadersConfig(v *OriginRequestPolicyHeadersConfig) *OriginRequestPolicyConfig { + s.HeadersConfig = v return s } -// A complex data type that includes information about the failover criteria -// for an origin group, including the status codes for which CloudFront will -// failover from the primary origin to the second origin. -type OriginGroupFailoverCriteria struct { +// SetName sets the Name field's value. +func (s *OriginRequestPolicyConfig) SetName(v string) *OriginRequestPolicyConfig { + s.Name = &v + return s +} + +// SetQueryStringsConfig sets the QueryStringsConfig field's value. +func (s *OriginRequestPolicyConfig) SetQueryStringsConfig(v *OriginRequestPolicyQueryStringsConfig) *OriginRequestPolicyConfig { + s.QueryStringsConfig = v + return s +} + +// An object that determines whether any cookies in viewer requests (and if +// so, which cookies) are included in requests that CloudFront sends to the +// origin. +type OriginRequestPolicyCookiesConfig struct { _ struct{} `type:"structure"` - // The status codes that, when returned from the primary origin, will trigger - // CloudFront to failover to the second origin. + // Determines whether cookies in viewer requests are included in requests that + // CloudFront sends to the origin. Valid values are: // - // StatusCodes is a required field - StatusCodes *StatusCodes `type:"structure" required:"true"` + // * none – Cookies in viewer requests are not included in requests that + // CloudFront sends to the origin. Even when this field is set to none, any + // cookies that are listed in a CachePolicy are included in origin requests. + // + // * whitelist – The cookies in viewer requests that are listed in the + // CookieNames type are included in requests that CloudFront sends to the + // origin. + // + // * all – All cookies in viewer requests are included in requests that + // CloudFront sends to the origin. + // + // CookieBehavior is a required field + CookieBehavior *string `type:"string" required:"true" enum:"OriginRequestPolicyCookieBehavior"` + + // Contains a list of cookie names. + Cookies *CookieNames `type:"structure"` } // String returns the string representation -func (s OriginGroupFailoverCriteria) String() string { +func (s OriginRequestPolicyCookiesConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s OriginGroupFailoverCriteria) GoString() string { +func (s OriginRequestPolicyCookiesConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *OriginGroupFailoverCriteria) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "OriginGroupFailoverCriteria"} - if s.StatusCodes == nil { - invalidParams.Add(request.NewErrParamRequired("StatusCodes")) +func (s *OriginRequestPolicyCookiesConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OriginRequestPolicyCookiesConfig"} + if s.CookieBehavior == nil { + invalidParams.Add(request.NewErrParamRequired("CookieBehavior")) } - if s.StatusCodes != nil { - if err := s.StatusCodes.Validate(); err != nil { - invalidParams.AddNested("StatusCodes", err.(request.ErrInvalidParams)) + if s.Cookies != nil { + if err := s.Cookies.Validate(); err != nil { + invalidParams.AddNested("Cookies", err.(request.ErrInvalidParams)) } } @@ -12392,37 +16020,68 @@ func (s *OriginGroupFailoverCriteria) Validate() error { return nil } -// SetStatusCodes sets the StatusCodes field's value. -func (s *OriginGroupFailoverCriteria) SetStatusCodes(v *StatusCodes) *OriginGroupFailoverCriteria { - s.StatusCodes = v +// SetCookieBehavior sets the CookieBehavior field's value. +func (s *OriginRequestPolicyCookiesConfig) SetCookieBehavior(v string) *OriginRequestPolicyCookiesConfig { + s.CookieBehavior = &v return s } -// An origin in an origin group. -type OriginGroupMember struct { +// SetCookies sets the Cookies field's value. +func (s *OriginRequestPolicyCookiesConfig) SetCookies(v *CookieNames) *OriginRequestPolicyCookiesConfig { + s.Cookies = v + return s +} + +// An object that determines whether any HTTP headers (and if so, which headers) +// are included in requests that CloudFront sends to the origin. +type OriginRequestPolicyHeadersConfig struct { _ struct{} `type:"structure"` - // The ID for an origin in an origin group. + // Determines whether any HTTP headers are included in requests that CloudFront + // sends to the origin. Valid values are: // - // OriginId is a required field - OriginId *string `type:"string" required:"true"` + // * none – HTTP headers are not included in requests that CloudFront sends + // to the origin. Even when this field is set to none, any headers that are + // listed in a CachePolicy are included in origin requests. + // + // * whitelist – The HTTP headers that are listed in the Headers type are + // included in requests that CloudFront sends to the origin. + // + // * allViewer – All HTTP headers in viewer requests are included in requests + // that CloudFront sends to the origin. + // + // * allViewerAndWhitelistCloudFront – All HTTP headers in viewer requests + // and the additional CloudFront headers that are listed in the Headers type + // are included in requests that CloudFront sends to the origin. The additional + // headers are added by CloudFront. + // + // HeaderBehavior is a required field + HeaderBehavior *string `type:"string" required:"true" enum:"OriginRequestPolicyHeaderBehavior"` + + // Contains a list of HTTP header names. + Headers *Headers `type:"structure"` } // String returns the string representation -func (s OriginGroupMember) String() string { +func (s OriginRequestPolicyHeadersConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s OriginGroupMember) GoString() string { +func (s OriginRequestPolicyHeadersConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *OriginGroupMember) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "OriginGroupMember"} - if s.OriginId == nil { - invalidParams.Add(request.NewErrParamRequired("OriginId")) +func (s *OriginRequestPolicyHeadersConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OriginRequestPolicyHeadersConfig"} + if s.HeaderBehavior == nil { + invalidParams.Add(request.NewErrParamRequired("HeaderBehavior")) + } + if s.Headers != nil { + if err := s.Headers.Validate(); err != nil { + invalidParams.AddNested("Headers", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -12431,115 +16090,124 @@ func (s *OriginGroupMember) Validate() error { return nil } -// SetOriginId sets the OriginId field's value. -func (s *OriginGroupMember) SetOriginId(v string) *OriginGroupMember { - s.OriginId = &v +// SetHeaderBehavior sets the HeaderBehavior field's value. +func (s *OriginRequestPolicyHeadersConfig) SetHeaderBehavior(v string) *OriginRequestPolicyHeadersConfig { + s.HeaderBehavior = &v return s } -// A complex data type for the origins included in an origin group. -type OriginGroupMembers struct { +// SetHeaders sets the Headers field's value. +func (s *OriginRequestPolicyHeadersConfig) SetHeaders(v *Headers) *OriginRequestPolicyHeadersConfig { + s.Headers = v + return s +} + +// A list of origin request policies. +type OriginRequestPolicyList struct { _ struct{} `type:"structure"` - // Items (origins) in an origin group. + // Contains the origin request policies in the list. + Items []*OriginRequestPolicySummary `locationNameList:"OriginRequestPolicySummary" type:"list"` + + // The maximum number of origin request policies requested. // - // Items is a required field - Items []*OriginGroupMember `locationNameList:"OriginGroupMember" min:"2" type:"list" required:"true"` + // MaxItems is a required field + MaxItems *int64 `type:"integer" required:"true"` - // The number of origins in an origin group. + // If there are more items in the list than are in this response, this element + // is present. It contains the value that you should use in the Marker field + // of a subsequent request to continue listing origin request policies where + // you left off. + NextMarker *string `type:"string"` + + // The total number of origin request policies returned in the response. // // Quantity is a required field Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s OriginGroupMembers) String() string { +func (s OriginRequestPolicyList) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s OriginGroupMembers) GoString() string { +func (s OriginRequestPolicyList) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *OriginGroupMembers) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "OriginGroupMembers"} - if s.Items == nil { - invalidParams.Add(request.NewErrParamRequired("Items")) - } - if s.Items != nil && len(s.Items) < 2 { - invalidParams.Add(request.NewErrParamMinLen("Items", 2)) - } - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) - } - if s.Items != nil { - for i, v := range s.Items { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) - } - } - } +// SetItems sets the Items field's value. +func (s *OriginRequestPolicyList) SetItems(v []*OriginRequestPolicySummary) *OriginRequestPolicyList { + s.Items = v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetMaxItems sets the MaxItems field's value. +func (s *OriginRequestPolicyList) SetMaxItems(v int64) *OriginRequestPolicyList { + s.MaxItems = &v + return s } -// SetItems sets the Items field's value. -func (s *OriginGroupMembers) SetItems(v []*OriginGroupMember) *OriginGroupMembers { - s.Items = v +// SetNextMarker sets the NextMarker field's value. +func (s *OriginRequestPolicyList) SetNextMarker(v string) *OriginRequestPolicyList { + s.NextMarker = &v return s } // SetQuantity sets the Quantity field's value. -func (s *OriginGroupMembers) SetQuantity(v int64) *OriginGroupMembers { +func (s *OriginRequestPolicyList) SetQuantity(v int64) *OriginRequestPolicyList { s.Quantity = &v return s } -// A complex data type for the origin groups specified for a distribution. -type OriginGroups struct { +// An object that determines whether any URL query strings in viewer requests +// (and if so, which query strings) are included in requests that CloudFront +// sends to the origin. +type OriginRequestPolicyQueryStringsConfig struct { _ struct{} `type:"structure"` - // The items (origin groups) in a distribution. - Items []*OriginGroup `locationNameList:"OriginGroup" type:"list"` - - // The number of origin groups. + // Determines whether any URL query strings in viewer requests are included + // in requests that CloudFront sends to the origin. Valid values are: // - // Quantity is a required field - Quantity *int64 `type:"integer" required:"true"` + // * none – Query strings in viewer requests are not included in requests + // that CloudFront sends to the origin. Even when this field is set to none, + // any query strings that are listed in a CachePolicy are included in origin + // requests. + // + // * whitelist – The query strings in viewer requests that are listed in + // the QueryStringNames type are included in requests that CloudFront sends + // to the origin. + // + // * all – All query strings in viewer requests are included in requests + // that CloudFront sends to the origin. + // + // QueryStringBehavior is a required field + QueryStringBehavior *string `type:"string" required:"true" enum:"OriginRequestPolicyQueryStringBehavior"` + + // Contains a list of the query strings in viewer requests that are included + // in requests that CloudFront sends to the origin. + QueryStrings *QueryStringNames `type:"structure"` } // String returns the string representation -func (s OriginGroups) String() string { +func (s OriginRequestPolicyQueryStringsConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s OriginGroups) GoString() string { +func (s OriginRequestPolicyQueryStringsConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *OriginGroups) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "OriginGroups"} - if s.Quantity == nil { - invalidParams.Add(request.NewErrParamRequired("Quantity")) - } - if s.Items != nil { - for i, v := range s.Items { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Items", i), err.(request.ErrInvalidParams)) - } +func (s *OriginRequestPolicyQueryStringsConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OriginRequestPolicyQueryStringsConfig"} + if s.QueryStringBehavior == nil { + invalidParams.Add(request.NewErrParamRequired("QueryStringBehavior")) + } + if s.QueryStrings != nil { + if err := s.QueryStrings.Validate(); err != nil { + invalidParams.AddNested("QueryStrings", err.(request.ErrInvalidParams)) } } @@ -12549,15 +16217,53 @@ func (s *OriginGroups) Validate() error { return nil } -// SetItems sets the Items field's value. -func (s *OriginGroups) SetItems(v []*OriginGroup) *OriginGroups { - s.Items = v +// SetQueryStringBehavior sets the QueryStringBehavior field's value. +func (s *OriginRequestPolicyQueryStringsConfig) SetQueryStringBehavior(v string) *OriginRequestPolicyQueryStringsConfig { + s.QueryStringBehavior = &v return s } -// SetQuantity sets the Quantity field's value. -func (s *OriginGroups) SetQuantity(v int64) *OriginGroups { - s.Quantity = &v +// SetQueryStrings sets the QueryStrings field's value. +func (s *OriginRequestPolicyQueryStringsConfig) SetQueryStrings(v *QueryStringNames) *OriginRequestPolicyQueryStringsConfig { + s.QueryStrings = v + return s +} + +// Contains an origin request policy. +type OriginRequestPolicySummary struct { + _ struct{} `type:"structure"` + + // The origin request policy. + // + // OriginRequestPolicy is a required field + OriginRequestPolicy *OriginRequestPolicy `type:"structure" required:"true"` + + // The type of origin request policy, either managed (created by AWS) or custom + // (created in this AWS account). + // + // Type is a required field + Type *string `type:"string" required:"true" enum:"OriginRequestPolicyType"` +} + +// String returns the string representation +func (s OriginRequestPolicySummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OriginRequestPolicySummary) GoString() string { + return s.String() +} + +// SetOriginRequestPolicy sets the OriginRequestPolicy field's value. +func (s *OriginRequestPolicySummary) SetOriginRequestPolicy(v *OriginRequestPolicy) *OriginRequestPolicySummary { + s.OriginRequestPolicy = v + return s +} + +// SetType sets the Type field's value. +func (s *OriginRequestPolicySummary) SetType(v string) *OriginRequestPolicySummary { + s.Type = &v return s } @@ -12683,6 +16389,144 @@ func (s *Origins) SetQuantity(v int64) *Origins { return s } +// This object determines the values that CloudFront includes in the cache key. +// These values can include HTTP headers, cookies, and URL query strings. CloudFront +// uses the cache key to find an object in its cache that it can return to the +// viewer. +// +// The headers, cookies, and query strings that are included in the cache key +// are automatically included in requests that CloudFront sends to the origin. +// CloudFront sends a request when it can’t find an object in its cache that +// matches the request’s cache key. If you want to send values to the origin +// but not include them in the cache key, use CreateOriginRequestPolicy. +type ParametersInCacheKeyAndForwardedToOrigin struct { + _ struct{} `type:"structure"` + + // An object that determines whether any cookies in viewer requests (and if + // so, which cookies) are included in the cache key and automatically included + // in requests that CloudFront sends to the origin. + // + // CookiesConfig is a required field + CookiesConfig *CachePolicyCookiesConfig `type:"structure" required:"true"` + + // A flag that determines whether the Accept-Encoding HTTP header is included + // in the cache key and included in requests that CloudFront sends to the origin. + // + // If this field is true and the viewer request includes the Accept-Encoding + // header, then CloudFront normalizes the value of the viewer’s Accept-Encoding + // header to one of the following: + // + // * Accept-Encoding: gzip (if gzip is in the viewer’s Accept-Encoding + // header) + // + // * Accept-Encoding: identity (if gzip is not in the viewer’s Accept-Encoding + // header) + // + // CloudFront includes the normalized header in the cache key and includes it + // in requests that CloudFront sends to the origin. + // + // If this field is false, then CloudFront treats the Accept-Encoding header + // the same as any other HTTP header in the viewer request. By default, it’s + // not included in the cache key and it’s not included in origin requests. + // You can manually add Accept-Encoding to the headers whitelist like any other + // HTTP header. + // + // When this field is true, you should not whitelist the Accept-Encoding header + // in the cache policy or in an origin request policy attached to the same cache + // behavior. + // + // For more information, see Cache compressed objects (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects) + // in the Amazon CloudFront Developer Guide. + // + // EnableAcceptEncodingGzip is a required field + EnableAcceptEncodingGzip *bool `type:"boolean" required:"true"` + + // An object that determines whether any HTTP headers (and if so, which headers) + // are included in the cache key and automatically included in requests that + // CloudFront sends to the origin. + // + // HeadersConfig is a required field + HeadersConfig *CachePolicyHeadersConfig `type:"structure" required:"true"` + + // An object that determines whether any URL query strings in viewer requests + // (and if so, which query strings) are included in the cache key and automatically + // included in requests that CloudFront sends to the origin. + // + // QueryStringsConfig is a required field + QueryStringsConfig *CachePolicyQueryStringsConfig `type:"structure" required:"true"` +} + +// String returns the string representation +func (s ParametersInCacheKeyAndForwardedToOrigin) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ParametersInCacheKeyAndForwardedToOrigin) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ParametersInCacheKeyAndForwardedToOrigin) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ParametersInCacheKeyAndForwardedToOrigin"} + if s.CookiesConfig == nil { + invalidParams.Add(request.NewErrParamRequired("CookiesConfig")) + } + if s.EnableAcceptEncodingGzip == nil { + invalidParams.Add(request.NewErrParamRequired("EnableAcceptEncodingGzip")) + } + if s.HeadersConfig == nil { + invalidParams.Add(request.NewErrParamRequired("HeadersConfig")) + } + if s.QueryStringsConfig == nil { + invalidParams.Add(request.NewErrParamRequired("QueryStringsConfig")) + } + if s.CookiesConfig != nil { + if err := s.CookiesConfig.Validate(); err != nil { + invalidParams.AddNested("CookiesConfig", err.(request.ErrInvalidParams)) + } + } + if s.HeadersConfig != nil { + if err := s.HeadersConfig.Validate(); err != nil { + invalidParams.AddNested("HeadersConfig", err.(request.ErrInvalidParams)) + } + } + if s.QueryStringsConfig != nil { + if err := s.QueryStringsConfig.Validate(); err != nil { + invalidParams.AddNested("QueryStringsConfig", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCookiesConfig sets the CookiesConfig field's value. +func (s *ParametersInCacheKeyAndForwardedToOrigin) SetCookiesConfig(v *CachePolicyCookiesConfig) *ParametersInCacheKeyAndForwardedToOrigin { + s.CookiesConfig = v + return s +} + +// SetEnableAcceptEncodingGzip sets the EnableAcceptEncodingGzip field's value. +func (s *ParametersInCacheKeyAndForwardedToOrigin) SetEnableAcceptEncodingGzip(v bool) *ParametersInCacheKeyAndForwardedToOrigin { + s.EnableAcceptEncodingGzip = &v + return s +} + +// SetHeadersConfig sets the HeadersConfig field's value. +func (s *ParametersInCacheKeyAndForwardedToOrigin) SetHeadersConfig(v *CachePolicyHeadersConfig) *ParametersInCacheKeyAndForwardedToOrigin { + s.HeadersConfig = v + return s +} + +// SetQueryStringsConfig sets the QueryStringsConfig field's value. +func (s *ParametersInCacheKeyAndForwardedToOrigin) SetQueryStringsConfig(v *CachePolicyQueryStringsConfig) *ParametersInCacheKeyAndForwardedToOrigin { + s.QueryStringsConfig = v + return s +} + // A complex type that contains information about the objects that you want // to invalidate. For more information, see Specifying the Objects to Invalidate // (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#invalidation-specifying-objects) @@ -13158,35 +17002,92 @@ func (s *QueryArgProfiles) SetQuantity(v int64) *QueryArgProfiles { return s } +// This field is deprecated. We recommend that you use a cache policy or an +// origin request policy instead of this field. +// +// If you want to include query strings in the cache key, use QueryStringsConfig +// in a cache policy. See CreateCachePolicy. +// +// If you want to send query strings to the origin but not include them in the +// cache key, use QueryStringsConfig in an origin request policy. See CreateOriginRequestPolicy. +// // A complex type that contains information about the query string parameters // that you want CloudFront to use for caching for a cache behavior. type QueryStringCacheKeys struct { _ struct{} `type:"structure"` - // A list that contains the query string parameters that you want CloudFront - // to use as a basis for caching for a cache behavior. If Quantity is 0, you - // can omit Items. + // A list that contains the query string parameters that you want CloudFront + // to use as a basis for caching for a cache behavior. If Quantity is 0, you + // can omit Items. + Items []*string `locationNameList:"Name" type:"list"` + + // The number of whitelisted query string parameters for a cache behavior. + // + // Quantity is a required field + Quantity *int64 `type:"integer" required:"true"` +} + +// String returns the string representation +func (s QueryStringCacheKeys) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s QueryStringCacheKeys) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *QueryStringCacheKeys) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "QueryStringCacheKeys"} + if s.Quantity == nil { + invalidParams.Add(request.NewErrParamRequired("Quantity")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetItems sets the Items field's value. +func (s *QueryStringCacheKeys) SetItems(v []*string) *QueryStringCacheKeys { + s.Items = v + return s +} + +// SetQuantity sets the Quantity field's value. +func (s *QueryStringCacheKeys) SetQuantity(v int64) *QueryStringCacheKeys { + s.Quantity = &v + return s +} + +// Contains a list of query string names. +type QueryStringNames struct { + _ struct{} `type:"structure"` + + // A list of query string names. Items []*string `locationNameList:"Name" type:"list"` - // The number of whitelisted query string parameters for a cache behavior. + // The number of query string names in the Items list. // // Quantity is a required field Quantity *int64 `type:"integer" required:"true"` } // String returns the string representation -func (s QueryStringCacheKeys) String() string { +func (s QueryStringNames) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s QueryStringCacheKeys) GoString() string { +func (s QueryStringNames) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *QueryStringCacheKeys) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "QueryStringCacheKeys"} +func (s *QueryStringNames) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "QueryStringNames"} if s.Quantity == nil { invalidParams.Add(request.NewErrParamRequired("Quantity")) } @@ -13198,13 +17099,13 @@ func (s *QueryStringCacheKeys) Validate() error { } // SetItems sets the Items field's value. -func (s *QueryStringCacheKeys) SetItems(v []*string) *QueryStringCacheKeys { +func (s *QueryStringNames) SetItems(v []*string) *QueryStringNames { s.Items = v return s } // SetQuantity sets the Quantity field's value. -func (s *QueryStringCacheKeys) SetQuantity(v int64) *QueryStringCacheKeys { +func (s *QueryStringNames) SetQuantity(v int64) *QueryStringNames { s.Quantity = &v return s } @@ -13326,7 +17227,8 @@ 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. +// origin is a custom origin or an S3 bucket that is configured as a website +// endpoint, use the CustomOriginConfig element instead. type S3OriginConfig struct { _ struct{} `type:"structure"` @@ -14222,7 +18124,7 @@ type TagResourceInput struct { // A complex type that contains zero or more Tag elements. // // Tags is a required field - Tags *Tags `locationName:"Tags" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + Tags *Tags `locationName:"Tags" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation @@ -14420,7 +18322,7 @@ type UntagResourceInput struct { // A complex type that contains zero or more Tag key elements. // // TagKeys is a required field - TagKeys *TagKeys `locationName:"TagKeys" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + TagKeys *TagKeys `locationName:"TagKeys" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation @@ -14475,6 +18377,110 @@ func (s UntagResourceOutput) GoString() string { return s.String() } +type UpdateCachePolicyInput struct { + _ struct{} `locationName:"UpdateCachePolicyRequest" type:"structure" payload:"CachePolicyConfig"` + + // A cache policy configuration. + // + // CachePolicyConfig is a required field + CachePolicyConfig *CachePolicyConfig `locationName:"CachePolicyConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` + + // The unique identifier for the cache policy that you are updating. The identifier + // is returned in a cache behavior’s CachePolicyId field in the response to + // GetDistributionConfig. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + + // The version of the cache policy that you are updating. The version is returned + // in the cache policy’s ETag field in the response to GetCachePolicyConfig. + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` +} + +// String returns the string representation +func (s UpdateCachePolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateCachePolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateCachePolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateCachePolicyInput"} + if s.CachePolicyConfig == nil { + invalidParams.Add(request.NewErrParamRequired("CachePolicyConfig")) + } + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + if s.CachePolicyConfig != nil { + if err := s.CachePolicyConfig.Validate(); err != nil { + invalidParams.AddNested("CachePolicyConfig", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCachePolicyConfig sets the CachePolicyConfig field's value. +func (s *UpdateCachePolicyInput) SetCachePolicyConfig(v *CachePolicyConfig) *UpdateCachePolicyInput { + s.CachePolicyConfig = v + return s +} + +// SetId sets the Id field's value. +func (s *UpdateCachePolicyInput) SetId(v string) *UpdateCachePolicyInput { + s.Id = &v + return s +} + +// SetIfMatch sets the IfMatch field's value. +func (s *UpdateCachePolicyInput) SetIfMatch(v string) *UpdateCachePolicyInput { + s.IfMatch = &v + return s +} + +type UpdateCachePolicyOutput struct { + _ struct{} `type:"structure" payload:"CachePolicy"` + + // A cache policy. + CachePolicy *CachePolicy `type:"structure"` + + // The current version of the cache policy. + ETag *string `location:"header" locationName:"ETag" type:"string"` +} + +// String returns the string representation +func (s UpdateCachePolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateCachePolicyOutput) GoString() string { + return s.String() +} + +// SetCachePolicy sets the CachePolicy field's value. +func (s *UpdateCachePolicyOutput) SetCachePolicy(v *CachePolicy) *UpdateCachePolicyOutput { + s.CachePolicy = v + return s +} + +// SetETag sets the ETag field's value. +func (s *UpdateCachePolicyOutput) SetETag(v string) *UpdateCachePolicyOutput { + s.ETag = &v + return s +} + // The request to update an origin access identity. type UpdateCloudFrontOriginAccessIdentityInput struct { _ struct{} `locationName:"UpdateCloudFrontOriginAccessIdentityRequest" type:"structure" payload:"CloudFrontOriginAccessIdentityConfig"` @@ -14482,7 +18488,7 @@ type UpdateCloudFrontOriginAccessIdentityInput struct { // The identity's configuration information. // // CloudFrontOriginAccessIdentityConfig is a required field - CloudFrontOriginAccessIdentityConfig *OriginAccessIdentityConfig `locationName:"CloudFrontOriginAccessIdentityConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + CloudFrontOriginAccessIdentityConfig *OriginAccessIdentityConfig `locationName:"CloudFrontOriginAccessIdentityConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` // The identity's id. // @@ -14586,7 +18592,7 @@ type UpdateDistributionInput struct { // The distribution's configuration information. // // DistributionConfig is a required field - DistributionConfig *DistributionConfig `locationName:"DistributionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + DistributionConfig *DistributionConfig `locationName:"DistributionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` // The distribution's id. // @@ -14689,7 +18695,7 @@ type UpdateFieldLevelEncryptionConfigInput struct { // Request to update a field-level encryption configuration. // // FieldLevelEncryptionConfig is a required field - FieldLevelEncryptionConfig *FieldLevelEncryptionConfig `locationName:"FieldLevelEncryptionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + FieldLevelEncryptionConfig *FieldLevelEncryptionConfig `locationName:"FieldLevelEncryptionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` // The ID of the configuration you want to update. // @@ -14792,7 +18798,7 @@ type UpdateFieldLevelEncryptionProfileInput struct { // Request to update a field-level encryption profile. // // FieldLevelEncryptionProfileConfig is a required field - FieldLevelEncryptionProfileConfig *FieldLevelEncryptionProfileConfig `locationName:"FieldLevelEncryptionProfileConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + FieldLevelEncryptionProfileConfig *FieldLevelEncryptionProfileConfig `locationName:"FieldLevelEncryptionProfileConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` // The ID of the field-level encryption profile request. // @@ -14888,6 +18894,111 @@ func (s *UpdateFieldLevelEncryptionProfileOutput) SetFieldLevelEncryptionProfile return s } +type UpdateOriginRequestPolicyInput struct { + _ struct{} `locationName:"UpdateOriginRequestPolicyRequest" type:"structure" payload:"OriginRequestPolicyConfig"` + + // The unique identifier for the origin request policy that you are updating. + // The identifier is returned in a cache behavior’s OriginRequestPolicyId + // field in the response to GetDistributionConfig. + // + // Id is a required field + Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` + + // The version of the origin request policy that you are updating. The version + // is returned in the origin request policy’s ETag field in the response to + // GetOriginRequestPolicyConfig. + IfMatch *string `location:"header" locationName:"If-Match" type:"string"` + + // An origin request policy configuration. + // + // OriginRequestPolicyConfig is a required field + OriginRequestPolicyConfig *OriginRequestPolicyConfig `locationName:"OriginRequestPolicyConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` +} + +// String returns the string representation +func (s UpdateOriginRequestPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateOriginRequestPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateOriginRequestPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateOriginRequestPolicyInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + if s.OriginRequestPolicyConfig == nil { + invalidParams.Add(request.NewErrParamRequired("OriginRequestPolicyConfig")) + } + if s.OriginRequestPolicyConfig != nil { + if err := s.OriginRequestPolicyConfig.Validate(); err != nil { + invalidParams.AddNested("OriginRequestPolicyConfig", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *UpdateOriginRequestPolicyInput) SetId(v string) *UpdateOriginRequestPolicyInput { + s.Id = &v + return s +} + +// SetIfMatch sets the IfMatch field's value. +func (s *UpdateOriginRequestPolicyInput) SetIfMatch(v string) *UpdateOriginRequestPolicyInput { + s.IfMatch = &v + return s +} + +// SetOriginRequestPolicyConfig sets the OriginRequestPolicyConfig field's value. +func (s *UpdateOriginRequestPolicyInput) SetOriginRequestPolicyConfig(v *OriginRequestPolicyConfig) *UpdateOriginRequestPolicyInput { + s.OriginRequestPolicyConfig = v + return s +} + +type UpdateOriginRequestPolicyOutput struct { + _ struct{} `type:"structure" payload:"OriginRequestPolicy"` + + // The current version of the origin request policy. + ETag *string `location:"header" locationName:"ETag" type:"string"` + + // An origin request policy. + OriginRequestPolicy *OriginRequestPolicy `type:"structure"` +} + +// String returns the string representation +func (s UpdateOriginRequestPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateOriginRequestPolicyOutput) GoString() string { + return s.String() +} + +// SetETag sets the ETag field's value. +func (s *UpdateOriginRequestPolicyOutput) SetETag(v string) *UpdateOriginRequestPolicyOutput { + s.ETag = &v + return s +} + +// SetOriginRequestPolicy sets the OriginRequestPolicy field's value. +func (s *UpdateOriginRequestPolicyOutput) SetOriginRequestPolicy(v *OriginRequestPolicy) *UpdateOriginRequestPolicyOutput { + s.OriginRequestPolicy = v + return s +} + type UpdatePublicKeyInput struct { _ struct{} `locationName:"UpdatePublicKeyRequest" type:"structure" payload:"PublicKeyConfig"` @@ -14903,7 +19014,7 @@ type UpdatePublicKeyInput struct { // Request to update public key information. // // PublicKeyConfig is a required field - PublicKeyConfig *PublicKeyConfig `locationName:"PublicKeyConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + PublicKeyConfig *PublicKeyConfig `locationName:"PublicKeyConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation @@ -15006,7 +19117,7 @@ type UpdateStreamingDistributionInput struct { // The streaming distribution's configuration information. // // StreamingDistributionConfig is a required field - StreamingDistributionConfig *StreamingDistributionConfig `locationName:"StreamingDistributionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` + StreamingDistributionConfig *StreamingDistributionConfig `locationName:"StreamingDistributionConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2020-05-31/"` } // String returns the string representation @@ -15109,10 +19220,10 @@ func (s *UpdateStreamingDistributionOutput) SetStreamingDistribution(v *Streamin // viewers that support server name indication (SNI) (https://en.wikipedia.org/wiki/Server_Name_Indication) // (recommended), or all viewers including those that don’t support SNI. // To accept HTTPS connections from only viewers that support SNI, set SSLSupportMethod -// to sni-only. This is recommended. Most browsers and clients released after -// 2010 support SNI. To accept HTTPS connections from all viewers, including -// those that don’t support SNI, set SSLSupportMethod to vip. This is not -// recommended, and results in additional monthly charges from CloudFront. +// to sni-only. This is recommended. Most browsers and clients support SNI. +// To accept HTTPS connections from all viewers, including those that don’t +// support SNI, set SSLSupportMethod to vip. This is not recommended, and +// results in additional monthly charges from CloudFront. // // * The minimum SSL/TLS protocol version that the distribution can use to // communicate with viewers. To specify a minimum version, choose a value @@ -15207,9 +19318,6 @@ type ViewerCertificate struct { // // On the CloudFront console, this setting is called Security Policy. // - // We recommend that you specify TLSv1.2_2018 unless your viewers are using - // browsers or devices that don’t support TLSv1.2. - // // When you’re using SNI only (you set SSLSupportMethod to sni-only), you // must specify TLSv1 or higher. // @@ -15223,8 +19331,7 @@ type ViewerCertificate struct { // // * sni-only – The distribution accepts HTTPS connections from only viewers // that support server name indication (SNI) (https://en.wikipedia.org/wiki/Server_Name_Indication). - // This is recommended. Most browsers and clients released after 2010 support - // SNI. + // This is recommended. Most browsers and clients support SNI. // // * vip – The distribution accepts HTTPS connections from all viewers // including those that don’t support SNI. This is not recommended, and @@ -15287,6 +19394,86 @@ func (s *ViewerCertificate) SetSSLSupportMethod(v string) *ViewerCertificate { return s } +const ( + // CachePolicyCookieBehaviorNone is a CachePolicyCookieBehavior enum value + CachePolicyCookieBehaviorNone = "none" + + // CachePolicyCookieBehaviorWhitelist is a CachePolicyCookieBehavior enum value + CachePolicyCookieBehaviorWhitelist = "whitelist" + + // CachePolicyCookieBehaviorAllExcept is a CachePolicyCookieBehavior enum value + CachePolicyCookieBehaviorAllExcept = "allExcept" + + // CachePolicyCookieBehaviorAll is a CachePolicyCookieBehavior enum value + CachePolicyCookieBehaviorAll = "all" +) + +// CachePolicyCookieBehavior_Values returns all elements of the CachePolicyCookieBehavior enum +func CachePolicyCookieBehavior_Values() []string { + return []string{ + CachePolicyCookieBehaviorNone, + CachePolicyCookieBehaviorWhitelist, + CachePolicyCookieBehaviorAllExcept, + CachePolicyCookieBehaviorAll, + } +} + +const ( + // CachePolicyHeaderBehaviorNone is a CachePolicyHeaderBehavior enum value + CachePolicyHeaderBehaviorNone = "none" + + // CachePolicyHeaderBehaviorWhitelist is a CachePolicyHeaderBehavior enum value + CachePolicyHeaderBehaviorWhitelist = "whitelist" +) + +// CachePolicyHeaderBehavior_Values returns all elements of the CachePolicyHeaderBehavior enum +func CachePolicyHeaderBehavior_Values() []string { + return []string{ + CachePolicyHeaderBehaviorNone, + CachePolicyHeaderBehaviorWhitelist, + } +} + +const ( + // CachePolicyQueryStringBehaviorNone is a CachePolicyQueryStringBehavior enum value + CachePolicyQueryStringBehaviorNone = "none" + + // CachePolicyQueryStringBehaviorWhitelist is a CachePolicyQueryStringBehavior enum value + CachePolicyQueryStringBehaviorWhitelist = "whitelist" + + // CachePolicyQueryStringBehaviorAllExcept is a CachePolicyQueryStringBehavior enum value + CachePolicyQueryStringBehaviorAllExcept = "allExcept" + + // CachePolicyQueryStringBehaviorAll is a CachePolicyQueryStringBehavior enum value + CachePolicyQueryStringBehaviorAll = "all" +) + +// CachePolicyQueryStringBehavior_Values returns all elements of the CachePolicyQueryStringBehavior enum +func CachePolicyQueryStringBehavior_Values() []string { + return []string{ + CachePolicyQueryStringBehaviorNone, + CachePolicyQueryStringBehaviorWhitelist, + CachePolicyQueryStringBehaviorAllExcept, + CachePolicyQueryStringBehaviorAll, + } +} + +const ( + // CachePolicyTypeManaged is a CachePolicyType enum value + CachePolicyTypeManaged = "managed" + + // CachePolicyTypeCustom is a CachePolicyType enum value + CachePolicyTypeCustom = "custom" +) + +// CachePolicyType_Values returns all elements of the CachePolicyType enum +func CachePolicyType_Values() []string { + return []string{ + CachePolicyTypeManaged, + CachePolicyTypeCustom, + } +} + const ( // CertificateSourceCloudfront is a CertificateSource enum value CertificateSourceCloudfront = "cloudfront" @@ -15298,6 +19485,15 @@ const ( CertificateSourceAcm = "acm" ) +// CertificateSource_Values returns all elements of the CertificateSource enum +func CertificateSource_Values() []string { + return []string{ + CertificateSourceCloudfront, + CertificateSourceIam, + CertificateSourceAcm, + } +} + const ( // EventTypeViewerRequest is a EventType enum value EventTypeViewerRequest = "viewer-request" @@ -15312,11 +19508,28 @@ const ( EventTypeOriginResponse = "origin-response" ) +// EventType_Values returns all elements of the EventType enum +func EventType_Values() []string { + return []string{ + EventTypeViewerRequest, + EventTypeViewerResponse, + EventTypeOriginRequest, + EventTypeOriginResponse, + } +} + const ( // FormatUrlencoded is a Format enum value FormatUrlencoded = "URLEncoded" ) +// Format_Values returns all elements of the Format enum +func Format_Values() []string { + return []string{ + FormatUrlencoded, + } +} + const ( // GeoRestrictionTypeBlacklist is a GeoRestrictionType enum value GeoRestrictionTypeBlacklist = "blacklist" @@ -15328,6 +19541,15 @@ const ( GeoRestrictionTypeNone = "none" ) +// GeoRestrictionType_Values returns all elements of the GeoRestrictionType enum +func GeoRestrictionType_Values() []string { + return []string{ + GeoRestrictionTypeBlacklist, + GeoRestrictionTypeWhitelist, + GeoRestrictionTypeNone, + } +} + const ( // HttpVersionHttp11 is a HttpVersion enum value HttpVersionHttp11 = "http1.1" @@ -15336,6 +19558,14 @@ const ( HttpVersionHttp2 = "http2" ) +// HttpVersion_Values returns all elements of the HttpVersion enum +func HttpVersion_Values() []string { + return []string{ + HttpVersionHttp11, + HttpVersionHttp2, + } +} + const ( // ICPRecordalStatusApproved is a ICPRecordalStatus enum value ICPRecordalStatusApproved = "APPROVED" @@ -15347,6 +19577,15 @@ const ( ICPRecordalStatusPending = "PENDING" ) +// ICPRecordalStatus_Values returns all elements of the ICPRecordalStatus enum +func ICPRecordalStatus_Values() []string { + return []string{ + ICPRecordalStatusApproved, + ICPRecordalStatusSuspended, + ICPRecordalStatusPending, + } +} + const ( // ItemSelectionNone is a ItemSelection enum value ItemSelectionNone = "none" @@ -15358,6 +19597,15 @@ const ( ItemSelectionAll = "all" ) +// ItemSelection_Values returns all elements of the ItemSelection enum +func ItemSelection_Values() []string { + return []string{ + ItemSelectionNone, + ItemSelectionWhitelist, + ItemSelectionAll, + } +} + const ( // MethodGet is a Method enum value MethodGet = "GET" @@ -15381,6 +19629,19 @@ const ( MethodDelete = "DELETE" ) +// Method_Values returns all elements of the Method enum +func Method_Values() []string { + return []string{ + MethodGet, + MethodHead, + MethodPost, + MethodPut, + MethodPatch, + MethodOptions, + MethodDelete, + } +} + const ( // MinimumProtocolVersionSslv3 is a MinimumProtocolVersion enum value MinimumProtocolVersionSslv3 = "SSLv3" @@ -15396,8 +19657,23 @@ const ( // MinimumProtocolVersionTlsv122018 is a MinimumProtocolVersion enum value MinimumProtocolVersionTlsv122018 = "TLSv1.2_2018" + + // MinimumProtocolVersionTlsv122019 is a MinimumProtocolVersion enum value + MinimumProtocolVersionTlsv122019 = "TLSv1.2_2019" ) +// MinimumProtocolVersion_Values returns all elements of the MinimumProtocolVersion enum +func MinimumProtocolVersion_Values() []string { + return []string{ + MinimumProtocolVersionSslv3, + MinimumProtocolVersionTlsv1, + MinimumProtocolVersionTlsv12016, + MinimumProtocolVersionTlsv112016, + MinimumProtocolVersionTlsv122018, + MinimumProtocolVersionTlsv122019, + } +} + const ( // OriginProtocolPolicyHttpOnly is a OriginProtocolPolicy enum value OriginProtocolPolicyHttpOnly = "http-only" @@ -15409,6 +19685,95 @@ const ( OriginProtocolPolicyHttpsOnly = "https-only" ) +// OriginProtocolPolicy_Values returns all elements of the OriginProtocolPolicy enum +func OriginProtocolPolicy_Values() []string { + return []string{ + OriginProtocolPolicyHttpOnly, + OriginProtocolPolicyMatchViewer, + OriginProtocolPolicyHttpsOnly, + } +} + +const ( + // OriginRequestPolicyCookieBehaviorNone is a OriginRequestPolicyCookieBehavior enum value + OriginRequestPolicyCookieBehaviorNone = "none" + + // OriginRequestPolicyCookieBehaviorWhitelist is a OriginRequestPolicyCookieBehavior enum value + OriginRequestPolicyCookieBehaviorWhitelist = "whitelist" + + // OriginRequestPolicyCookieBehaviorAll is a OriginRequestPolicyCookieBehavior enum value + OriginRequestPolicyCookieBehaviorAll = "all" +) + +// OriginRequestPolicyCookieBehavior_Values returns all elements of the OriginRequestPolicyCookieBehavior enum +func OriginRequestPolicyCookieBehavior_Values() []string { + return []string{ + OriginRequestPolicyCookieBehaviorNone, + OriginRequestPolicyCookieBehaviorWhitelist, + OriginRequestPolicyCookieBehaviorAll, + } +} + +const ( + // OriginRequestPolicyHeaderBehaviorNone is a OriginRequestPolicyHeaderBehavior enum value + OriginRequestPolicyHeaderBehaviorNone = "none" + + // OriginRequestPolicyHeaderBehaviorWhitelist is a OriginRequestPolicyHeaderBehavior enum value + OriginRequestPolicyHeaderBehaviorWhitelist = "whitelist" + + // OriginRequestPolicyHeaderBehaviorAllViewer is a OriginRequestPolicyHeaderBehavior enum value + OriginRequestPolicyHeaderBehaviorAllViewer = "allViewer" + + // OriginRequestPolicyHeaderBehaviorAllViewerAndWhitelistCloudFront is a OriginRequestPolicyHeaderBehavior enum value + OriginRequestPolicyHeaderBehaviorAllViewerAndWhitelistCloudFront = "allViewerAndWhitelistCloudFront" +) + +// OriginRequestPolicyHeaderBehavior_Values returns all elements of the OriginRequestPolicyHeaderBehavior enum +func OriginRequestPolicyHeaderBehavior_Values() []string { + return []string{ + OriginRequestPolicyHeaderBehaviorNone, + OriginRequestPolicyHeaderBehaviorWhitelist, + OriginRequestPolicyHeaderBehaviorAllViewer, + OriginRequestPolicyHeaderBehaviorAllViewerAndWhitelistCloudFront, + } +} + +const ( + // OriginRequestPolicyQueryStringBehaviorNone is a OriginRequestPolicyQueryStringBehavior enum value + OriginRequestPolicyQueryStringBehaviorNone = "none" + + // OriginRequestPolicyQueryStringBehaviorWhitelist is a OriginRequestPolicyQueryStringBehavior enum value + OriginRequestPolicyQueryStringBehaviorWhitelist = "whitelist" + + // OriginRequestPolicyQueryStringBehaviorAll is a OriginRequestPolicyQueryStringBehavior enum value + OriginRequestPolicyQueryStringBehaviorAll = "all" +) + +// OriginRequestPolicyQueryStringBehavior_Values returns all elements of the OriginRequestPolicyQueryStringBehavior enum +func OriginRequestPolicyQueryStringBehavior_Values() []string { + return []string{ + OriginRequestPolicyQueryStringBehaviorNone, + OriginRequestPolicyQueryStringBehaviorWhitelist, + OriginRequestPolicyQueryStringBehaviorAll, + } +} + +const ( + // OriginRequestPolicyTypeManaged is a OriginRequestPolicyType enum value + OriginRequestPolicyTypeManaged = "managed" + + // OriginRequestPolicyTypeCustom is a OriginRequestPolicyType enum value + OriginRequestPolicyTypeCustom = "custom" +) + +// OriginRequestPolicyType_Values returns all elements of the OriginRequestPolicyType enum +func OriginRequestPolicyType_Values() []string { + return []string{ + OriginRequestPolicyTypeManaged, + OriginRequestPolicyTypeCustom, + } +} + const ( // PriceClassPriceClass100 is a PriceClass enum value PriceClassPriceClass100 = "PriceClass_100" @@ -15420,6 +19785,15 @@ const ( PriceClassPriceClassAll = "PriceClass_All" ) +// PriceClass_Values returns all elements of the PriceClass enum +func PriceClass_Values() []string { + return []string{ + PriceClassPriceClass100, + PriceClassPriceClass200, + PriceClassPriceClassAll, + } +} + const ( // SSLSupportMethodSniOnly is a SSLSupportMethod enum value SSLSupportMethodSniOnly = "sni-only" @@ -15428,6 +19802,14 @@ const ( SSLSupportMethodVip = "vip" ) +// SSLSupportMethod_Values returns all elements of the SSLSupportMethod enum +func SSLSupportMethod_Values() []string { + return []string{ + SSLSupportMethodSniOnly, + SSLSupportMethodVip, + } +} + const ( // SslProtocolSslv3 is a SslProtocol enum value SslProtocolSslv3 = "SSLv3" @@ -15442,6 +19824,16 @@ const ( SslProtocolTlsv12 = "TLSv1.2" ) +// SslProtocol_Values returns all elements of the SslProtocol enum +func SslProtocol_Values() []string { + return []string{ + SslProtocolSslv3, + SslProtocolTlsv1, + SslProtocolTlsv11, + SslProtocolTlsv12, + } +} + const ( // ViewerProtocolPolicyAllowAll is a ViewerProtocolPolicy enum value ViewerProtocolPolicyAllowAll = "allow-all" @@ -15452,3 +19844,12 @@ const ( // ViewerProtocolPolicyRedirectToHttps is a ViewerProtocolPolicy enum value ViewerProtocolPolicyRedirectToHttps = "redirect-to-https" ) + +// ViewerProtocolPolicy_Values returns all elements of the ViewerProtocolPolicy enum +func ViewerProtocolPolicy_Values() []string { + return []string{ + ViewerProtocolPolicyAllowAll, + ViewerProtocolPolicyHttpsOnly, + ViewerProtocolPolicyRedirectToHttps, + } +} 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 index fb197f85b21..c9f335dd4da 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudfront/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudfront/doc.go @@ -8,7 +8,7 @@ // errors. For detailed information about CloudFront features, see the Amazon // CloudFront Developer Guide. // -// See https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26 for more information on this service. +// See https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31 for more information on this service. // // See cloudfront package documentation for more information. // https://docs.aws.amazon.com/sdk-for-go/api/service/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 827ff5f7eba..533ff29608d 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 @@ -22,6 +22,20 @@ const ( // The CNAME specified is already defined for CloudFront. ErrCodeCNAMEAlreadyExists = "CNAMEAlreadyExists" + // ErrCodeCachePolicyAlreadyExists for service response error code + // "CachePolicyAlreadyExists". + // + // A cache policy with this name already exists. You must provide a unique name. + // To modify an existing cache policy, use UpdateCachePolicy. + ErrCodeCachePolicyAlreadyExists = "CachePolicyAlreadyExists" + + // ErrCodeCachePolicyInUse for service response error code + // "CachePolicyInUse". + // + // Cannot delete the cache policy because it is attached to one or more cache + // behaviors. + ErrCodeCachePolicyInUse = "CachePolicyInUse" + // ErrCodeCannotChangeImmutablePublicKeyFields for service response error code // "CannotChangeImmutablePublicKeyFields". // @@ -72,6 +86,12 @@ const ( // The maximum size of a profile for field-level encryption was exceeded. ErrCodeFieldLevelEncryptionProfileSizeExceeded = "FieldLevelEncryptionProfileSizeExceeded" + // ErrCodeIllegalDelete for service response error code + // "IllegalDelete". + // + // You cannot delete a managed policy. + ErrCodeIllegalDelete = "IllegalDelete" + // ErrCodeIllegalFieldLevelEncryptionConfigAssociationWithCacheBehavior for service response error code // "IllegalFieldLevelEncryptionConfigAssociationWithCacheBehavior". // @@ -82,7 +102,7 @@ const ( // ErrCodeIllegalUpdate for service response error code // "IllegalUpdate". // - // Origin and CallerReference cannot be updated. + // The update contains modifications that are not allowed. ErrCodeIllegalUpdate = "IllegalUpdate" // ErrCodeInconsistentQuantities for service response error code @@ -94,7 +114,7 @@ const ( // ErrCodeInvalidArgument for service response error code // "InvalidArgument". // - // The argument is invalid. + // An argument is invalid. ErrCodeInvalidArgument = "InvalidArgument" // ErrCodeInvalidDefaultRootObject for service response error code @@ -133,7 +153,7 @@ const ( // ErrCodeInvalidIfMatchVersion for service response error code // "InvalidIfMatchVersion". // - // The If-Match version is missing or not valid for the distribution. + // The If-Match version is missing or not valid. ErrCodeInvalidIfMatchVersion = "InvalidIfMatchVersion" // ErrCodeInvalidLambdaFunctionAssociation for service response error code @@ -247,6 +267,12 @@ const ( // header is set. ErrCodeMissingBody = "MissingBody" + // ErrCodeNoSuchCachePolicy for service response error code + // "NoSuchCachePolicy". + // + // The cache policy does not exist. + ErrCodeNoSuchCachePolicy = "NoSuchCachePolicy" + // ErrCodeNoSuchCloudFrontOriginAccessIdentity for service response error code // "NoSuchCloudFrontOriginAccessIdentity". // @@ -283,6 +309,12 @@ const ( // No origin exists with the specified Origin Id. ErrCodeNoSuchOrigin = "NoSuchOrigin" + // ErrCodeNoSuchOriginRequestPolicy for service response error code + // "NoSuchOriginRequestPolicy". + // + // The origin request policy does not exist. + ErrCodeNoSuchOriginRequestPolicy = "NoSuchOriginRequestPolicy" + // ErrCodeNoSuchPublicKey for service response error code // "NoSuchPublicKey". // @@ -316,10 +348,24 @@ const ( // The Origin Access Identity specified is already in use. ErrCodeOriginAccessIdentityInUse = "CloudFrontOriginAccessIdentityInUse" + // ErrCodeOriginRequestPolicyAlreadyExists for service response error code + // "OriginRequestPolicyAlreadyExists". + // + // An origin request policy with this name already exists. You must provide + // a unique name. To modify an existing origin request policy, use UpdateOriginRequestPolicy. + ErrCodeOriginRequestPolicyAlreadyExists = "OriginRequestPolicyAlreadyExists" + + // ErrCodeOriginRequestPolicyInUse for service response error code + // "OriginRequestPolicyInUse". + // + // Cannot delete the origin request policy because it is attached to one or + // more cache behaviors. + ErrCodeOriginRequestPolicyInUse = "OriginRequestPolicyInUse" + // ErrCodePreconditionFailed for service response error code // "PreconditionFailed". // - // The precondition given in one or more of the request-header fields evaluated + // The precondition given in one or more of the request header fields evaluated // to false. ErrCodePreconditionFailed = "PreconditionFailed" @@ -361,6 +407,14 @@ const ( // You cannot create more cache behaviors for the distribution. ErrCodeTooManyCacheBehaviors = "TooManyCacheBehaviors" + // ErrCodeTooManyCachePolicies for service response error code + // "TooManyCachePolicies". + // + // You have reached the maximum number of cache policies for this AWS account. + // For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) + // (formerly known as limits) in the Amazon CloudFront Developer Guide. + ErrCodeTooManyCachePolicies = "TooManyCachePolicies" + // ErrCodeTooManyCertificates for service response error code // "TooManyCertificates". // @@ -381,6 +435,22 @@ const ( // per cache behavior. ErrCodeTooManyCookieNamesInWhiteList = "TooManyCookieNamesInWhiteList" + // ErrCodeTooManyCookiesInCachePolicy for service response error code + // "TooManyCookiesInCachePolicy". + // + // The number of cookies in the cache policy exceeds the maximum. For more information, + // see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) + // (formerly known as limits) in the Amazon CloudFront Developer Guide. + ErrCodeTooManyCookiesInCachePolicy = "TooManyCookiesInCachePolicy" + + // ErrCodeTooManyCookiesInOriginRequestPolicy for service response error code + // "TooManyCookiesInOriginRequestPolicy". + // + // The number of cookies in the origin request policy exceeds the maximum. For + // more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) + // (formerly known as limits) in the Amazon CloudFront Developer Guide. + ErrCodeTooManyCookiesInOriginRequestPolicy = "TooManyCookiesInOriginRequestPolicy" + // ErrCodeTooManyDistributionCNAMEs for service response error code // "TooManyDistributionCNAMEs". // @@ -394,6 +464,14 @@ const ( // allowed. ErrCodeTooManyDistributions = "TooManyDistributions" + // ErrCodeTooManyDistributionsAssociatedToCachePolicy for service response error code + // "TooManyDistributionsAssociatedToCachePolicy". + // + // The maximum number of distributions have been associated with the specified + // cache policy. For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) + // (formerly known as limits) in the Amazon CloudFront Developer Guide. + ErrCodeTooManyDistributionsAssociatedToCachePolicy = "TooManyDistributionsAssociatedToCachePolicy" + // ErrCodeTooManyDistributionsAssociatedToFieldLevelEncryptionConfig for service response error code // "TooManyDistributionsAssociatedToFieldLevelEncryptionConfig". // @@ -401,6 +479,14 @@ const ( // configuration for field-level encryption. ErrCodeTooManyDistributionsAssociatedToFieldLevelEncryptionConfig = "TooManyDistributionsAssociatedToFieldLevelEncryptionConfig" + // ErrCodeTooManyDistributionsAssociatedToOriginRequestPolicy for service response error code + // "TooManyDistributionsAssociatedToOriginRequestPolicy". + // + // The maximum number of distributions have been associated with the specified + // origin request policy. For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) + // (formerly known as limits) in the Amazon CloudFront Developer Guide. + ErrCodeTooManyDistributionsAssociatedToOriginRequestPolicy = "TooManyDistributionsAssociatedToOriginRequestPolicy" + // ErrCodeTooManyDistributionsWithLambdaAssociations for service response error code // "TooManyDistributionsWithLambdaAssociations". // @@ -408,6 +494,13 @@ const ( // Lambda function associations per owner to be exceeded. ErrCodeTooManyDistributionsWithLambdaAssociations = "TooManyDistributionsWithLambdaAssociations" + // ErrCodeTooManyDistributionsWithSingleFunctionARN for service response error code + // "TooManyDistributionsWithSingleFunctionARN". + // + // The maximum number of distributions have been associated with the specified + // Lambda function. + ErrCodeTooManyDistributionsWithSingleFunctionARN = "TooManyDistributionsWithSingleFunctionARN" + // ErrCodeTooManyFieldLevelEncryptionConfigs for service response error code // "TooManyFieldLevelEncryptionConfigs". // @@ -449,12 +542,28 @@ const ( // been created. ErrCodeTooManyFieldLevelEncryptionQueryArgProfiles = "TooManyFieldLevelEncryptionQueryArgProfiles" + // ErrCodeTooManyHeadersInCachePolicy for service response error code + // "TooManyHeadersInCachePolicy". + // + // The number of headers in the cache policy exceeds the maximum. For more information, + // see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) + // (formerly known as limits) in the Amazon CloudFront Developer Guide. + ErrCodeTooManyHeadersInCachePolicy = "TooManyHeadersInCachePolicy" + // ErrCodeTooManyHeadersInForwardedValues for service response error code // "TooManyHeadersInForwardedValues". // // Your request contains too many headers in forwarded values. ErrCodeTooManyHeadersInForwardedValues = "TooManyHeadersInForwardedValues" + // ErrCodeTooManyHeadersInOriginRequestPolicy for service response error code + // "TooManyHeadersInOriginRequestPolicy". + // + // The number of headers in the origin request policy exceeds the maximum. For + // more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) + // (formerly known as limits) in the Amazon CloudFront Developer Guide. + ErrCodeTooManyHeadersInOriginRequestPolicy = "TooManyHeadersInOriginRequestPolicy" + // ErrCodeTooManyInvalidationsInProgress for service response error code // "TooManyInvalidationsInProgress". // @@ -482,6 +591,14 @@ const ( // groups allowed. ErrCodeTooManyOriginGroupsPerDistribution = "TooManyOriginGroupsPerDistribution" + // ErrCodeTooManyOriginRequestPolicies for service response error code + // "TooManyOriginRequestPolicies". + // + // You have reached the maximum number of origin request policies for this AWS + // account. For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) + // (formerly known as limits) in the Amazon CloudFront Developer Guide. + ErrCodeTooManyOriginRequestPolicies = "TooManyOriginRequestPolicies" + // ErrCodeTooManyOrigins for service response error code // "TooManyOrigins". // @@ -501,6 +618,22 @@ const ( // Your request contains too many query string parameters. ErrCodeTooManyQueryStringParameters = "TooManyQueryStringParameters" + // ErrCodeTooManyQueryStringsInCachePolicy for service response error code + // "TooManyQueryStringsInCachePolicy". + // + // The number of query strings in the cache policy exceeds the maximum. For + // more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) + // (formerly known as limits) in the Amazon CloudFront Developer Guide. + ErrCodeTooManyQueryStringsInCachePolicy = "TooManyQueryStringsInCachePolicy" + + // ErrCodeTooManyQueryStringsInOriginRequestPolicy for service response error code + // "TooManyQueryStringsInOriginRequestPolicy". + // + // The number of query strings in the origin request policy exceeds the maximum. + // For more information, see Quotas (https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html) + // (formerly known as limits) in the Amazon CloudFront Developer Guide. + ErrCodeTooManyQueryStringsInOriginRequestPolicy = "TooManyQueryStringsInOriginRequestPolicy" + // ErrCodeTooManyStreamingDistributionCNAMEs for service response error code // "TooManyStreamingDistributionCNAMEs". // 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 be2ca42f187..28338550858 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 @@ -63,7 +63,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, SigningRegion: signingRegion, PartitionID: partitionID, Endpoint: endpoint, - APIVersion: "2019-03-26", + APIVersion: "2020-05-31", }, handlers, ), diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudhsmv2/api.go b/vendor/github.com/aws/aws-sdk-go/service/cloudhsmv2/api.go index 56b3c461c6d..7d3fdaac015 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudhsmv2/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudhsmv2/api.go @@ -85,6 +85,8 @@ func (c *CloudHSMV2) CopyBackupToRegionRequest(input *CopyBackupToRegionInput) ( // The request was rejected because an error occurred. // // * CloudHsmTagException +// The request was rejected because of a tagging failure. Verify the tag conditions +// in all applicable policies, and then retry the request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/cloudhsmv2-2017-04-28/CopyBackupToRegion func (c *CloudHSMV2) CopyBackupToRegion(input *CopyBackupToRegionInput) (*CopyBackupToRegionOutput, error) { @@ -180,6 +182,8 @@ func (c *CloudHSMV2) CreateClusterRequest(input *CreateClusterInput) (req *reque // The request was rejected because an error occurred. // // * CloudHsmTagException +// The request was rejected because of a tagging failure. Verify the tag conditions +// in all applicable policies, and then retry the request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/cloudhsmv2-2017-04-28/CreateCluster func (c *CloudHSMV2) CreateCluster(input *CreateClusterInput) (*CreateClusterOutput, error) { @@ -466,6 +470,8 @@ func (c *CloudHSMV2) DeleteClusterRequest(input *DeleteClusterInput) (req *reque // The request was rejected because an error occurred. // // * CloudHsmTagException +// The request was rejected because of a tagging failure. Verify the tag conditions +// in all applicable policies, and then retry the request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/cloudhsmv2-2017-04-28/DeleteCluster func (c *CloudHSMV2) DeleteCluster(input *DeleteClusterInput) (*DeleteClusterOutput, error) { @@ -670,6 +676,8 @@ func (c *CloudHSMV2) DescribeBackupsRequest(input *DescribeBackupsInput) (req *r // The request was rejected because an error occurred. // // * CloudHsmTagException +// The request was rejected because of a tagging failure. Verify the tag conditions +// in all applicable policies, and then retry the request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/cloudhsmv2-2017-04-28/DescribeBackups func (c *CloudHSMV2) DescribeBackups(input *DescribeBackupsInput) (*DescribeBackupsOutput, error) { @@ -827,6 +835,8 @@ func (c *CloudHSMV2) DescribeClustersRequest(input *DescribeClustersInput) (req // The request was rejected because an error occurred. // // * CloudHsmTagException +// The request was rejected because of a tagging failure. Verify the tag conditions +// in all applicable policies, and then retry the request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/cloudhsmv2-2017-04-28/DescribeClusters func (c *CloudHSMV2) DescribeClusters(input *DescribeClustersInput) (*DescribeClustersOutput, error) { @@ -1082,6 +1092,8 @@ func (c *CloudHSMV2) ListTagsRequest(input *ListTagsInput) (req *request.Request // The request was rejected because an error occurred. // // * CloudHsmTagException +// The request was rejected because of a tagging failure. Verify the tag conditions +// in all applicable policies, and then retry the request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/cloudhsmv2-2017-04-28/ListTags func (c *CloudHSMV2) ListTags(input *ListTagsInput) (*ListTagsOutput, error) { @@ -1324,6 +1336,8 @@ func (c *CloudHSMV2) TagResourceRequest(input *TagResourceInput) (req *request.R // The request was rejected because an error occurred. // // * CloudHsmTagException +// The request was rejected because of a tagging failure. Verify the tag conditions +// in all applicable policies, and then retry the request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/cloudhsmv2-2017-04-28/TagResource func (c *CloudHSMV2) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { @@ -1420,6 +1434,8 @@ func (c *CloudHSMV2) UntagResourceRequest(input *UntagResourceInput) (req *reque // The request was rejected because an error occurred. // // * CloudHsmTagException +// The request was rejected because of a tagging failure. Verify the tag conditions +// in all applicable policies, and then retry the request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/cloudhsmv2-2017-04-28/UntagResource func (c *CloudHSMV2) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { @@ -1476,13 +1492,14 @@ type Backup struct { SourceBackup *string `type:"string"` // The identifier (ID) of the cluster containing the source backup from which - // the new backup was copied. . + // the new backup was copied. SourceCluster *string `type:"string"` - // The AWS region that contains the source backup from which the new backup + // The AWS Region that contains the source backup from which the new backup // was copied. SourceRegion *string `type:"string"` + // The list of tags for the backup. TagList []*Tag `min:"1" type:"list"` } @@ -1900,6 +1917,8 @@ func (s *CloudHsmServiceException) RequestID() string { return s.RespMetadata.RequestID } +// The request was rejected because of a tagging failure. Verify the tag conditions +// in all applicable policies, and then retry the request. type CloudHsmTagException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -1997,6 +2016,7 @@ type Cluster struct { // zone. SubnetMapping map[string]*string `type:"map"` + // The list of tags for the cluster. TagList []*Tag `min:"1" type:"list"` // The identifier (ID) of the virtual private cloud (VPC) that contains the @@ -2111,6 +2131,10 @@ type CopyBackupToRegionInput struct { // DestinationRegion is a required field DestinationRegion *string `type:"string" required:"true"` + // Tags to apply to the destination backup during creation. If you specify tags, + // only these tags will be applied to the destination backup. If you do not + // specify tags, the service copies tags from the source backup to the destination + // backup. TagList []*Tag `min:"1" type:"list"` } @@ -2226,6 +2250,7 @@ type CreateClusterInput struct { // SubnetIds is a required field SubnetIds []*string `min:"1" type:"list" required:"true"` + // Tags to apply to the CloudHSM cluster during creation. TagList []*Tag `min:"1" type:"list"` } @@ -3451,6 +3476,13 @@ const ( BackupPolicyDefault = "DEFAULT" ) +// BackupPolicy_Values returns all elements of the BackupPolicy enum +func BackupPolicy_Values() []string { + return []string{ + BackupPolicyDefault, + } +} + const ( // BackupStateCreateInProgress is a BackupState enum value BackupStateCreateInProgress = "CREATE_IN_PROGRESS" @@ -3465,6 +3497,16 @@ const ( BackupStatePendingDeletion = "PENDING_DELETION" ) +// BackupState_Values returns all elements of the BackupState enum +func BackupState_Values() []string { + return []string{ + BackupStateCreateInProgress, + BackupStateReady, + BackupStateDeleted, + BackupStatePendingDeletion, + } +} + const ( // ClusterStateCreateInProgress is a ClusterState enum value ClusterStateCreateInProgress = "CREATE_IN_PROGRESS" @@ -3494,6 +3536,21 @@ const ( ClusterStateDegraded = "DEGRADED" ) +// ClusterState_Values returns all elements of the ClusterState enum +func ClusterState_Values() []string { + return []string{ + ClusterStateCreateInProgress, + ClusterStateUninitialized, + ClusterStateInitializeInProgress, + ClusterStateInitialized, + ClusterStateActive, + ClusterStateUpdateInProgress, + ClusterStateDeleteInProgress, + ClusterStateDeleted, + ClusterStateDegraded, + } +} + const ( // HsmStateCreateInProgress is a HsmState enum value HsmStateCreateInProgress = "CREATE_IN_PROGRESS" @@ -3510,3 +3567,14 @@ const ( // HsmStateDeleted is a HsmState enum value HsmStateDeleted = "DELETED" ) + +// HsmState_Values returns all elements of the HsmState enum +func HsmState_Values() []string { + return []string{ + HsmStateCreateInProgress, + HsmStateActive, + HsmStateDegraded, + HsmStateDeleteInProgress, + HsmStateDeleted, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudhsmv2/errors.go b/vendor/github.com/aws/aws-sdk-go/service/cloudhsmv2/errors.go index a99c421f3f4..9f72ea42eaf 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudhsmv2/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudhsmv2/errors.go @@ -42,6 +42,9 @@ const ( // ErrCodeCloudHsmTagException for service response error code // "CloudHsmTagException". + // + // The request was rejected because of a tagging failure. Verify the tag conditions + // in all applicable policies, and then retry the request. ErrCodeCloudHsmTagException = "CloudHsmTagException" ) diff --git a/vendor/github.com/aws/aws-sdk-go/service/cloudsearch/api.go b/vendor/github.com/aws/aws-sdk-go/service/cloudsearch/api.go index a39be361ffd..7cb304fd405 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cloudsearch/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cloudsearch/api.go @@ -6625,6 +6625,16 @@ const ( AlgorithmicStemmingFull = "full" ) +// AlgorithmicStemming_Values returns all elements of the AlgorithmicStemming enum +func AlgorithmicStemming_Values() []string { + return []string{ + AlgorithmicStemmingNone, + AlgorithmicStemmingMinimal, + AlgorithmicStemmingLight, + AlgorithmicStemmingFull, + } +} + // An IETF RFC 4646 (http://tools.ietf.org/html/rfc4646) language code or mul // for multiple languages. const ( @@ -6734,6 +6744,47 @@ const ( AnalysisSchemeLanguageZhHant = "zh-Hant" ) +// AnalysisSchemeLanguage_Values returns all elements of the AnalysisSchemeLanguage enum +func AnalysisSchemeLanguage_Values() []string { + return []string{ + AnalysisSchemeLanguageAr, + AnalysisSchemeLanguageBg, + AnalysisSchemeLanguageCa, + AnalysisSchemeLanguageCs, + AnalysisSchemeLanguageDa, + AnalysisSchemeLanguageDe, + AnalysisSchemeLanguageEl, + AnalysisSchemeLanguageEn, + AnalysisSchemeLanguageEs, + AnalysisSchemeLanguageEu, + AnalysisSchemeLanguageFa, + AnalysisSchemeLanguageFi, + AnalysisSchemeLanguageFr, + AnalysisSchemeLanguageGa, + AnalysisSchemeLanguageGl, + AnalysisSchemeLanguageHe, + AnalysisSchemeLanguageHi, + AnalysisSchemeLanguageHu, + AnalysisSchemeLanguageHy, + AnalysisSchemeLanguageId, + AnalysisSchemeLanguageIt, + AnalysisSchemeLanguageJa, + AnalysisSchemeLanguageKo, + AnalysisSchemeLanguageLv, + AnalysisSchemeLanguageMul, + AnalysisSchemeLanguageNl, + AnalysisSchemeLanguageNo, + AnalysisSchemeLanguagePt, + AnalysisSchemeLanguageRo, + AnalysisSchemeLanguageRu, + AnalysisSchemeLanguageSv, + AnalysisSchemeLanguageTh, + AnalysisSchemeLanguageTr, + AnalysisSchemeLanguageZhHans, + AnalysisSchemeLanguageZhHant, + } +} + // The type of field. The valid options for a field depend on the field type. // For more information about the supported field types, see Configuring Index // Fields (http://docs.aws.amazon.com/cloudsearch/latest/developerguide/configuring-index-fields.html) @@ -6773,6 +6824,23 @@ const ( IndexFieldTypeDateArray = "date-array" ) +// IndexFieldType_Values returns all elements of the IndexFieldType enum +func IndexFieldType_Values() []string { + return []string{ + IndexFieldTypeInt, + IndexFieldTypeDouble, + IndexFieldTypeLiteral, + IndexFieldTypeText, + IndexFieldTypeDate, + IndexFieldTypeLatlon, + IndexFieldTypeIntArray, + IndexFieldTypeDoubleArray, + IndexFieldTypeLiteralArray, + IndexFieldTypeTextArray, + IndexFieldTypeDateArray, + } +} + // The state of processing a change to an option. One of: // // * RequiresIndexDocuments: The option's latest value will not be deployed @@ -6799,6 +6867,16 @@ const ( OptionStateFailedToValidate = "FailedToValidate" ) +// OptionState_Values returns all elements of the OptionState enum +func OptionState_Values() []string { + return []string{ + OptionStateRequiresIndexDocuments, + OptionStateProcessing, + OptionStateActive, + OptionStateFailedToValidate, + } +} + // The instance type (such as search.m1.small) on which an index partition is // hosted. const ( @@ -6827,6 +6905,20 @@ const ( PartitionInstanceTypeSearchM32xlarge = "search.m3.2xlarge" ) +// PartitionInstanceType_Values returns all elements of the PartitionInstanceType enum +func PartitionInstanceType_Values() []string { + return []string{ + PartitionInstanceTypeSearchM1Small, + PartitionInstanceTypeSearchM1Large, + PartitionInstanceTypeSearchM2Xlarge, + PartitionInstanceTypeSearchM22xlarge, + PartitionInstanceTypeSearchM3Medium, + PartitionInstanceTypeSearchM3Large, + PartitionInstanceTypeSearchM3Xlarge, + PartitionInstanceTypeSearchM32xlarge, + } +} + const ( // SuggesterFuzzyMatchingNone is a SuggesterFuzzyMatching enum value SuggesterFuzzyMatchingNone = "none" @@ -6838,6 +6930,15 @@ const ( SuggesterFuzzyMatchingHigh = "high" ) +// SuggesterFuzzyMatching_Values returns all elements of the SuggesterFuzzyMatching enum +func SuggesterFuzzyMatching_Values() []string { + return []string{ + SuggesterFuzzyMatchingNone, + SuggesterFuzzyMatchingLow, + SuggesterFuzzyMatchingHigh, + } +} + // The minimum required TLS version. const ( // TLSSecurityPolicyPolicyMinTls10201907 is a TLSSecurityPolicy enum value @@ -6846,3 +6947,11 @@ const ( // TLSSecurityPolicyPolicyMinTls12201907 is a TLSSecurityPolicy enum value TLSSecurityPolicyPolicyMinTls12201907 = "Policy-Min-TLS-1-2-2019-07" ) + +// TLSSecurityPolicy_Values returns all elements of the TLSSecurityPolicy enum +func TLSSecurityPolicy_Values() []string { + return []string{ + TLSSecurityPolicyPolicyMinTls10201907, + TLSSecurityPolicyPolicyMinTls12201907, + } +} 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 3dcad2dafde..5c1a5889e42 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 @@ -7845,11 +7845,25 @@ const ( EventCategoryInsight = "insight" ) +// EventCategory_Values returns all elements of the EventCategory enum +func EventCategory_Values() []string { + return []string{ + EventCategoryInsight, + } +} + const ( // InsightTypeApiCallRateInsight is a InsightType enum value InsightTypeApiCallRateInsight = "ApiCallRateInsight" ) +// InsightType_Values returns all elements of the InsightType enum +func InsightType_Values() []string { + return []string{ + InsightTypeApiCallRateInsight, + } +} + const ( // LookupAttributeKeyEventId is a LookupAttributeKey enum value LookupAttributeKeyEventId = "EventId" @@ -7876,6 +7890,20 @@ const ( LookupAttributeKeyAccessKeyId = "AccessKeyId" ) +// LookupAttributeKey_Values returns all elements of the LookupAttributeKey enum +func LookupAttributeKey_Values() []string { + return []string{ + LookupAttributeKeyEventId, + LookupAttributeKeyEventName, + LookupAttributeKeyReadOnly, + LookupAttributeKeyUsername, + LookupAttributeKeyResourceType, + LookupAttributeKeyResourceName, + LookupAttributeKeyEventSource, + LookupAttributeKeyAccessKeyId, + } +} + const ( // ReadWriteTypeReadOnly is a ReadWriteType enum value ReadWriteTypeReadOnly = "ReadOnly" @@ -7886,3 +7914,12 @@ const ( // ReadWriteTypeAll is a ReadWriteType enum value ReadWriteTypeAll = "All" ) + +// ReadWriteType_Values returns all elements of the ReadWriteType enum +func ReadWriteType_Values() []string { + return []string{ + ReadWriteTypeReadOnly, + ReadWriteTypeWriteOnly, + ReadWriteTypeAll, + } +} 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 635d88c5b8e..7a2d4b2d189 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 @@ -246,7 +246,7 @@ func (c *CloudWatch) DeleteDashboardsRequest(input *DeleteDashboardsInput) (req // DeleteDashboards API operation for Amazon CloudWatch. // -// Deletes all dashboards that you specify. You may specify up to 100 dashboards +// Deletes all dashboards that you specify. You can specify up to 100 dashboards // to delete. If there is an error during this call, no dashboards are deleted. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -335,8 +335,7 @@ func (c *CloudWatch) DeleteInsightRulesRequest(input *DeleteInsightRulesInput) ( // Permanently deletes the specified Contributor Insights rules. // // If you create a rule, delete it, and then re-create it with the same name, -// historical data from the first time the rule was created may or may not be -// available. +// historical data from the first time the rule was created might not be available. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1420,7 +1419,7 @@ func (c *CloudWatch) GetInsightRuleReportRequest(input *GetInsightRuleReportInpu // point. // // * MaxContributorValue -- the value of the top contributor for each data -// point. The identity of the contributor may change for each data point +// point. The identity of the contributor might change for each data point // in the graph. If this rule aggregates by COUNT, the top contributor for // each data point is the contributor with the most occurrences in that period. // If the rule aggregates by SUM, the top contributor is the contributor @@ -1569,9 +1568,9 @@ func (c *CloudWatch) GetMetricDataRequest(input *GetMetricDataInput) (req *reque // If you omit Unit in your request, all data that was collected with any unit // is returned, along with the corresponding units that were specified when // the data was reported to CloudWatch. If you specify a unit, the operation -// returns only data data that was collected with that unit specified. If you -// specify a unit that does not match the data collected, the results of the -// operation are null. CloudWatch does not perform unit conversions. +// returns only data that was collected with that unit specified. If you specify +// a unit that does not match the data collected, the results of the operation +// are null. CloudWatch does not perform unit conversions. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2091,9 +2090,13 @@ func (c *CloudWatch) ListMetricsRequest(input *ListMetricsInput) (req *request.R // Up to 500 results are returned for any one call. To retrieve additional results, // use the returned token with subsequent calls. // -// After you create a metric, allow up to fifteen minutes before the metric -// appears. Statistics about the metric, however, are available sooner using -// GetMetricData (https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html) +// After you create a metric, allow up to 15 minutes before the metric appears. +// You can see statistics about the metric sooner by using GetMetricData (https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html) +// or GetMetricStatistics (https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html). +// +// ListMetrics doesn't return information about metrics if those metrics haven't +// reported data in the past two weeks. To retrieve those metrics, use GetMetricData +// (https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html) // or GetMetricStatistics (https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -2630,8 +2633,7 @@ func (c *CloudWatch) PutInsightRuleRequest(input *PutInsightRuleInput) (req *req // Analyze High-Cardinality Data (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html). // // If you create a rule, delete it, and then re-create it with the same name, -// historical data from the first time the rule was created may or may not be -// available. +// historical data from the first time the rule was created might not be available. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2982,8 +2984,8 @@ func (c *CloudWatch) SetAlarmStateRequest(input *SetAlarmStateInput) (req *reque // DescribeAlarmHistory (https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarmHistory.html). // // If you use SetAlarmState on a composite alarm, the composite alarm is not -// guaranteed to return to its actual state. It will return to its actual state -// only once any of its children alarms change state. It is also re-evaluated +// guaranteed to return to its actual state. It returns to its actual state +// only once any of its children alarms change state. It is also reevaluated // if you update its configuration. // // If an alarm triggers EC2 Auto Scaling policies or application Auto Scaling @@ -3076,7 +3078,7 @@ func (c *CloudWatch) TagResourceRequest(input *TagResourceInput) (req *request.R // Contributor Insights rules. // // Tags can help you organize and categorize your resources. You can also use -// them to scope user permissions, by granting a user permission to access or +// them to scope user permissions by granting a user permission to access or // change only resources with certain tag values. // // Tags don't have any semantic meaning to AWS and are interpreted strictly @@ -4321,8 +4323,8 @@ type DescribeAlarmsInput struct { // is not returned. // // If you specify ChildrenOfAlarmName, you cannot specify any other parameters - // in the request except for MaxRecords and NextToken. If you do so, you will - // receive a validation error. + // in the request except for MaxRecords and NextToken. If you do so, you receive + // a validation error. // // Only the Alarm Name, ARN, StateValue (OK/ALARM/INSUFFICIENT_DATA), and StateUpdatedTimestamp // information are returned by this operation when you use this parameter. To @@ -4344,8 +4346,8 @@ type DescribeAlarmsInput struct { // alarm that you specify in ParentsOfAlarmName is not returned. // // If you specify ParentsOfAlarmName, you cannot specify any other parameters - // in the request except for MaxRecords and NextToken. If you do so, you will - // receive a validation error. + // in the request except for MaxRecords and NextToken. If you do so, you receive + // a validation error. // // Only the Alarm Name and ARN are returned by this operation when you use this // parameter. To get complete information about these alarms, perform another @@ -4624,7 +4626,7 @@ type DescribeInsightRulesInput struct { _ struct{} `type:"structure"` // This parameter is not currently used. Reserved for future use. If it is used - // in the future, the maximum value may be different. + // in the future, the maximum value might be different. MaxResults *int64 `min:"1" type:"integer"` // Reserved for future use. @@ -4698,16 +4700,20 @@ func (s *DescribeInsightRulesOutput) SetNextToken(v string) *DescribeInsightRule return s } -// Expands the identity of a metric. +// A dimension is a name/value pair that is part of the identity of a metric. +// You can assign up to 10 dimensions to a metric. Because dimensions are part +// of the unique identifier for a metric, whenever you add a unique name/value +// pair to one of your metrics, you are creating a new variation of that metric. type Dimension struct { _ struct{} `type:"structure"` - // The name of the dimension. + // The name of the dimension. Dimension names cannot contain blank spaces or + // non-ASCII characters. // // Name is a required field Name *string `min:"1" type:"string" required:"true"` - // The value representing the dimension measurement. + // The value of the dimension. // // Value is a required field Value *string `min:"1" type:"string" required:"true"` @@ -5142,7 +5148,7 @@ type GetInsightRuleReportInput struct { // point. // // * MaxContributorValue -- the value of the top contributor for each data - // point. The identity of the contributor may change for each data point + // point. The identity of the contributor might change for each data point // in the graph. If this rule aggregates by COUNT, the top contributor for // each data point is the contributor with the most occurrences in that period. // If the rule aggregates by SUM, the top contributor is the contributor @@ -5496,7 +5502,7 @@ type GetMetricDataOutput struct { _ struct{} `type:"structure"` // Contains a message about this GetMetricData operation, if the operation results - // in such a message. An example of a message that may be returned is Maximum + // in such a message. An example of a message that might be returned is Maximum // number of allowed metrics exceeded. If there is a message, as much of the // operation as possible is still executed. // @@ -5640,9 +5646,9 @@ type GetMetricStatisticsInput struct { // The unit for a given metric. If you omit Unit, all data that was collected // with any unit is returned, along with the corresponding units that were specified // when the data was reported to CloudWatch. If you specify a unit, the operation - // returns only data data that was collected with that unit specified. If you - // specify a unit that does not match the data collected, the results of the - // operation are null. CloudWatch does not perform unit conversions. + // returns only data that was collected with that unit specified. If you specify + // a unit that does not match the data collected, the results of the operation + // are null. CloudWatch does not perform unit conversions. Unit *string `type:"string" enum:"StandardUnit"` } @@ -5880,7 +5886,7 @@ func (s *GetMetricWidgetImageInput) SetOutputFormat(v string) *GetMetricWidgetIm type GetMetricWidgetImageOutput struct { _ struct{} `type:"structure"` - // The image of the graph, in the output format specified. + // The image of the graph, in the output format specified. The output is base64-encoded. // // MetricWidgetImage is automatically base64 encoded/decoded by the SDK. MetricWidgetImage []byte `type:"blob"` @@ -6263,6 +6269,15 @@ type ListMetricsInput struct { // The token returned by a previous call to indicate that there is more data // available. NextToken *string `type:"string"` + + // To filter the results to show only metrics that have had data points published + // in the past three hours, specify this parameter with a value of PT3H. This + // is the only valid value for this parameter. + // + // The results that are returned are an approximation of the value you specify. + // There is a low probability that the returned results include metrics with + // last published data as much as 40 minutes more than the specified time interval. + RecentlyActive *string `type:"string" enum:"RecentlyActive"` } // String returns the string representation @@ -6325,10 +6340,16 @@ func (s *ListMetricsInput) SetNextToken(v string) *ListMetricsInput { return s } +// SetRecentlyActive sets the RecentlyActive field's value. +func (s *ListMetricsInput) SetRecentlyActive(v string) *ListMetricsInput { + s.RecentlyActive = &v + return s +} + type ListMetricsOutput struct { _ struct{} `type:"structure"` - // The metrics. + // The metrics that match your request. Metrics []*Metric `type:"list"` // The token that marks the start of the next batch of returned results. @@ -6366,7 +6387,7 @@ type ListTagsForResourceInput struct { // // The ARN format of a Contributor Insights rule is arn:aws:cloudwatch:Region:account-id:insight-rule:insight-rule-name // - // For more information on ARN format, see Resource Types Defined by Amazon + // For more information about ARN format, see Resource Types Defined by Amazon // CloudWatch (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncloudwatch.html#amazoncloudwatch-resources-for-iam-policies) // in the Amazon Web Services General Reference. // @@ -7251,9 +7272,9 @@ type MetricStat struct { // In a Get operation, if you omit Unit then all data that was collected with // any unit is returned, along with the corresponding units that were specified // when the data was reported to CloudWatch. If you specify a unit, the operation - // returns only data data that was collected with that unit specified. If you - // specify a unit that does not match the data collected, the results of the - // operation are null. CloudWatch does not perform unit conversions. + // returns only data that was collected with that unit specified. If you specify + // a unit that does not match the data collected, the results of the operation + // are null. CloudWatch does not perform unit conversions. Unit *string `type:"string" enum:"StandardUnit"` } @@ -7512,8 +7533,7 @@ type PutCompositeAlarmInput struct { // The description for the composite alarm. AlarmDescription *string `type:"string"` - // The name for the composite alarm. This name must be unique within your AWS - // account. + // The name for the composite alarm. This name must be unique within the Region. // // AlarmName is a required field AlarmName *string `min:"1" type:"string" required:"true"` @@ -7767,7 +7787,7 @@ type PutDashboardOutput struct { // // If this result includes only warning messages, then the input was valid enough // for the dashboard to be created or modified, but some elements of the dashboard - // may not render. + // might not render. // // If this result includes error messages, the input was not valid and the operation // failed. @@ -7928,7 +7948,7 @@ type PutMetricAlarmInput struct { // The description for the alarm. AlarmDescription *string `type:"string"` - // The name for the alarm. This name must be unique within your AWS account. + // The name for the alarm. This name must be unique within the Region. // // AlarmName is a required field AlarmName *string `min:"1" type:"string" required:"true"` @@ -8045,7 +8065,7 @@ type PutMetricAlarmInput struct { // a metric that does not have sub-minute resolution, the alarm still attempts // to gather data at the period rate that you specify. In this case, it does // not receive data for the attempts that do not correspond to a one-minute - // data resolution, and the alarm may often lapse into INSUFFICENT_DATA status. + // data resolution, and the alarm might often lapse into INSUFFICENT_DATA status. // Specifying 10 or 30 also sets this alarm as a high-resolution alarm, which // has a higher charge than other alarms. For more information about pricing, // see Amazon CloudWatch Pricing (https://aws.amazon.com/cloudwatch/pricing/). @@ -8064,7 +8084,7 @@ type PutMetricAlarmInput struct { // as many as 50 tags with an alarm. // // Tags can help you organize and categorize your resources. You can also use - // them to scope user permissions, by granting a user permission to access or + // them to scope user permissions by granting a user permission to access or // change only resources with certain tag values. Tags []*Tag `type:"list"` @@ -8098,12 +8118,12 @@ type PutMetricAlarmInput struct { // Percent, are aggregated separately. // // If you don't specify Unit, CloudWatch retrieves all unit types that have - // been published for the metric and attempts to evaluate the alarm. Usually - // metrics are published with only one unit, so the alarm will work as intended. + // been published for the metric and attempts to evaluate the alarm. Usually, + // metrics are published with only one unit, so the alarm works as intended. // // However, if the metric is published with multiple types of units and you - // don't specify a unit, the alarm's behavior is not defined and will behave - // un-predictably. + // don't specify a unit, the alarm's behavior is not defined and it behaves + // predictably. // // We recommend omitting Unit so that you don't inadvertently specify an incorrect // unit that is not published for this metric. Doing so causes the alarm to @@ -8485,8 +8505,7 @@ func (s *Range) SetStartTime(v time.Time) *Range { type SetAlarmStateInput struct { _ struct{} `type:"structure"` - // The name for the alarm. This name must be unique within the AWS account. - // The maximum length is 255 characters. + // The name of the alarm. // // AlarmName is a required field AlarmName *string `min:"1" type:"string" required:"true"` @@ -8726,7 +8745,7 @@ type TagResourceInput struct { // // The ARN format of a Contributor Insights rule is arn:aws:cloudwatch:Region:account-id:insight-rule:insight-rule-name // - // For more information on ARN format, see Resource Types Defined by Amazon + // For more information about ARN format, see Resource Types Defined by Amazon // CloudWatch (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncloudwatch.html#amazoncloudwatch-resources-for-iam-policies) // in the Amazon Web Services General Reference. // @@ -8813,7 +8832,7 @@ type UntagResourceInput struct { // // The ARN format of a Contributor Insights rule is arn:aws:cloudwatch:Region:account-id:insight-rule:insight-rule-name // - // For more information on ARN format, see Resource Types Defined by Amazon + // For more information about ARN format, see Resource Types Defined by Amazon // CloudWatch (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncloudwatch.html#amazoncloudwatch-resources-for-iam-policies) // in the Amazon Web Services General Reference. // @@ -8889,6 +8908,14 @@ const ( AlarmTypeMetricAlarm = "MetricAlarm" ) +// AlarmType_Values returns all elements of the AlarmType enum +func AlarmType_Values() []string { + return []string{ + AlarmTypeCompositeAlarm, + AlarmTypeMetricAlarm, + } +} + const ( // AnomalyDetectorStateValuePendingTraining is a AnomalyDetectorStateValue enum value AnomalyDetectorStateValuePendingTraining = "PENDING_TRAINING" @@ -8900,6 +8927,15 @@ const ( AnomalyDetectorStateValueTrained = "TRAINED" ) +// AnomalyDetectorStateValue_Values returns all elements of the AnomalyDetectorStateValue enum +func AnomalyDetectorStateValue_Values() []string { + return []string{ + AnomalyDetectorStateValuePendingTraining, + AnomalyDetectorStateValueTrainedInsufficientData, + AnomalyDetectorStateValueTrained, + } +} + const ( // ComparisonOperatorGreaterThanOrEqualToThreshold is a ComparisonOperator enum value ComparisonOperatorGreaterThanOrEqualToThreshold = "GreaterThanOrEqualToThreshold" @@ -8923,6 +8959,19 @@ const ( ComparisonOperatorGreaterThanUpperThreshold = "GreaterThanUpperThreshold" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorGreaterThanOrEqualToThreshold, + ComparisonOperatorGreaterThanThreshold, + ComparisonOperatorLessThanThreshold, + ComparisonOperatorLessThanOrEqualToThreshold, + ComparisonOperatorLessThanLowerOrGreaterThanUpperThreshold, + ComparisonOperatorLessThanLowerThreshold, + ComparisonOperatorGreaterThanUpperThreshold, + } +} + const ( // HistoryItemTypeConfigurationUpdate is a HistoryItemType enum value HistoryItemTypeConfigurationUpdate = "ConfigurationUpdate" @@ -8934,6 +8983,27 @@ const ( HistoryItemTypeAction = "Action" ) +// HistoryItemType_Values returns all elements of the HistoryItemType enum +func HistoryItemType_Values() []string { + return []string{ + HistoryItemTypeConfigurationUpdate, + HistoryItemTypeStateUpdate, + HistoryItemTypeAction, + } +} + +const ( + // RecentlyActivePt3h is a RecentlyActive enum value + RecentlyActivePt3h = "PT3H" +) + +// RecentlyActive_Values returns all elements of the RecentlyActive enum +func RecentlyActive_Values() []string { + return []string{ + RecentlyActivePt3h, + } +} + const ( // ScanByTimestampDescending is a ScanBy enum value ScanByTimestampDescending = "TimestampDescending" @@ -8942,6 +9012,14 @@ const ( ScanByTimestampAscending = "TimestampAscending" ) +// ScanBy_Values returns all elements of the ScanBy enum +func ScanBy_Values() []string { + return []string{ + ScanByTimestampDescending, + ScanByTimestampAscending, + } +} + const ( // StandardUnitSeconds is a StandardUnit enum value StandardUnitSeconds = "Seconds" @@ -9025,6 +9103,39 @@ const ( StandardUnitNone = "None" ) +// StandardUnit_Values returns all elements of the StandardUnit enum +func StandardUnit_Values() []string { + return []string{ + StandardUnitSeconds, + StandardUnitMicroseconds, + StandardUnitMilliseconds, + StandardUnitBytes, + StandardUnitKilobytes, + StandardUnitMegabytes, + StandardUnitGigabytes, + StandardUnitTerabytes, + StandardUnitBits, + StandardUnitKilobits, + StandardUnitMegabits, + StandardUnitGigabits, + StandardUnitTerabits, + StandardUnitPercent, + StandardUnitCount, + StandardUnitBytesSecond, + StandardUnitKilobytesSecond, + StandardUnitMegabytesSecond, + StandardUnitGigabytesSecond, + StandardUnitTerabytesSecond, + StandardUnitBitsSecond, + StandardUnitKilobitsSecond, + StandardUnitMegabitsSecond, + StandardUnitGigabitsSecond, + StandardUnitTerabitsSecond, + StandardUnitCountSecond, + StandardUnitNone, + } +} + const ( // StateValueOk is a StateValue enum value StateValueOk = "OK" @@ -9036,6 +9147,15 @@ const ( StateValueInsufficientData = "INSUFFICIENT_DATA" ) +// StateValue_Values returns all elements of the StateValue enum +func StateValue_Values() []string { + return []string{ + StateValueOk, + StateValueAlarm, + StateValueInsufficientData, + } +} + const ( // StatisticSampleCount is a Statistic enum value StatisticSampleCount = "SampleCount" @@ -9053,6 +9173,17 @@ const ( StatisticMaximum = "Maximum" ) +// Statistic_Values returns all elements of the Statistic enum +func Statistic_Values() []string { + return []string{ + StatisticSampleCount, + StatisticAverage, + StatisticSum, + StatisticMinimum, + StatisticMaximum, + } +} + const ( // StatusCodeComplete is a StatusCode enum value StatusCodeComplete = "Complete" @@ -9063,3 +9194,12 @@ const ( // StatusCodePartialData is a StatusCode enum value StatusCodePartialData = "PartialData" ) + +// StatusCode_Values returns all elements of the StatusCode enum +func StatusCode_Values() []string { + return []string{ + StatusCodeComplete, + StatusCodeInternalError, + StatusCodePartialData, + } +} 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 2069fda2168..570b5a51be3 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 @@ -81,6 +81,9 @@ func (c *CloudWatchEvents) ActivateEventSourceRequest(input *ActivateEventSource // * InternalException // This exception occurs due to unexpected causes. // +// * OperationDisabledException +// The operation you are attempting is not available in this region. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/ActivateEventSource func (c *CloudWatchEvents) ActivateEventSource(input *ActivateEventSourceInput) (*ActivateEventSourceOutput, error) { req, out := c.ActivateEventSourceRequest(input) @@ -178,6 +181,9 @@ func (c *CloudWatchEvents) CreateEventBusRequest(input *CreateEventBusInput) (re // * LimitExceededException // You tried to create more rules or add more targets to a rule than is allowed. // +// * OperationDisabledException +// The operation you are attempting is not available in this region. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/CreateEventBus func (c *CloudWatchEvents) CreateEventBus(input *CreateEventBusInput) (*CreateEventBusOutput, error) { req, out := c.CreateEventBusRequest(input) @@ -290,6 +296,9 @@ func (c *CloudWatchEvents) CreatePartnerEventSourceRequest(input *CreatePartnerE // * LimitExceededException // You tried to create more rules or add more targets to a rule than is allowed. // +// * OperationDisabledException +// The operation you are attempting is not available in this region. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/CreatePartnerEventSource func (c *CloudWatchEvents) CreatePartnerEventSource(input *CreatePartnerEventSourceInput) (*CreatePartnerEventSourceOutput, error) { req, out := c.CreatePartnerEventSourceRequest(input) @@ -385,6 +394,9 @@ func (c *CloudWatchEvents) DeactivateEventSourceRequest(input *DeactivateEventSo // * InternalException // This exception occurs due to unexpected causes. // +// * OperationDisabledException +// The operation you are attempting is not available in this region. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/DeactivateEventSource func (c *CloudWatchEvents) DeactivateEventSource(input *DeactivateEventSourceInput) (*DeactivateEventSourceOutput, error) { req, out := c.DeactivateEventSourceRequest(input) @@ -557,6 +569,9 @@ func (c *CloudWatchEvents) DeletePartnerEventSourceRequest(input *DeletePartnerE // * ConcurrentModificationException // There is concurrent modification on a rule or target. // +// * OperationDisabledException +// The operation you are attempting is not available in this region. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/DeletePartnerEventSource func (c *CloudWatchEvents) DeletePartnerEventSource(input *DeletePartnerEventSourceInput) (*DeletePartnerEventSourceOutput, error) { req, out := c.DeletePartnerEventSourceRequest(input) @@ -835,6 +850,9 @@ func (c *CloudWatchEvents) DescribeEventSourceRequest(input *DescribeEventSource // * InternalException // This exception occurs due to unexpected causes. // +// * OperationDisabledException +// The operation you are attempting is not available in this region. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/DescribeEventSource func (c *CloudWatchEvents) DescribeEventSource(input *DescribeEventSourceInput) (*DescribeEventSourceOutput, error) { req, out := c.DescribeEventSourceRequest(input) @@ -920,6 +938,9 @@ func (c *CloudWatchEvents) DescribePartnerEventSourceRequest(input *DescribePart // * InternalException // This exception occurs due to unexpected causes. // +// * OperationDisabledException +// The operation you are attempting is not available in this region. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/DescribePartnerEventSource func (c *CloudWatchEvents) DescribePartnerEventSource(input *DescribePartnerEventSourceInput) (*DescribePartnerEventSourceOutput, error) { req, out := c.DescribePartnerEventSourceRequest(input) @@ -1362,6 +1383,9 @@ func (c *CloudWatchEvents) ListEventSourcesRequest(input *ListEventSourcesInput) // * InternalException // This exception occurs due to unexpected causes. // +// * OperationDisabledException +// The operation you are attempting is not available in this region. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/ListEventSources func (c *CloudWatchEvents) ListEventSources(input *ListEventSourcesInput) (*ListEventSourcesOutput, error) { req, out := c.ListEventSourcesRequest(input) @@ -1446,6 +1470,9 @@ func (c *CloudWatchEvents) ListPartnerEventSourceAccountsRequest(input *ListPart // * InternalException // This exception occurs due to unexpected causes. // +// * OperationDisabledException +// The operation you are attempting is not available in this region. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/ListPartnerEventSourceAccounts func (c *CloudWatchEvents) ListPartnerEventSourceAccounts(input *ListPartnerEventSourceAccountsInput) (*ListPartnerEventSourceAccountsOutput, error) { req, out := c.ListPartnerEventSourceAccountsRequest(input) @@ -1526,6 +1553,9 @@ func (c *CloudWatchEvents) ListPartnerEventSourcesRequest(input *ListPartnerEven // * InternalException // This exception occurs due to unexpected causes. // +// * OperationDisabledException +// The operation you are attempting is not available in this region. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/ListPartnerEventSources func (c *CloudWatchEvents) ListPartnerEventSources(input *ListPartnerEventSourcesInput) (*ListPartnerEventSourcesOutput, error) { req, out := c.ListPartnerEventSourcesRequest(input) @@ -2020,6 +2050,9 @@ func (c *CloudWatchEvents) PutPartnerEventsRequest(input *PutPartnerEventsInput) // * InternalException // This exception occurs due to unexpected causes. // +// * OperationDisabledException +// The operation you are attempting is not available in this region. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/events-2015-10-07/PutPartnerEvents func (c *CloudWatchEvents) PutPartnerEvents(input *PutPartnerEventsInput) (*PutPartnerEventsOutput, error) { req, out := c.PutPartnerEventsRequest(input) @@ -2088,8 +2121,9 @@ func (c *CloudWatchEvents) PutPermissionRequest(input *PutPermissionInput) (req // PutPermission API operation for Amazon CloudWatch Events. // // Running PutPermission permits the specified AWS account or AWS organization -// to put events to the specified event bus. CloudWatch Events rules in your -// account are triggered by these events arriving to an event bus in your account. +// to put events to the specified event bus. Amazon EventBridge (CloudWatch +// Events) rules in your account are triggered by these events arriving to an +// event bus in your account. // // For another account to send events to your account, that external account // must have an EventBridge rule with your account's event bus as a target. @@ -2383,6 +2417,8 @@ func (c *CloudWatchEvents) PutTargetsRequest(input *PutTargetsInput) (req *reque // // * The default event bus of another AWS account // +// * Amazon API Gateway REST APIs +// // Creating rules with built-in targets is supported only in the AWS Management // Console. The built-in targets are EC2 CreateSnapshot API call, EC2 RebootInstances // API call, EC2 StopInstances API call, and EC2 TerminateInstances API call. @@ -2393,12 +2429,13 @@ func (c *CloudWatchEvents) PutTargetsRequest(input *PutTargetsInput) (req *reque // on multiple EC2 instances with one rule, you can use the RunCommandParameters // field. // -// To be able to make API calls against the resources that you own, Amazon CloudWatch -// Events needs the appropriate permissions. For AWS Lambda and Amazon SNS resources, -// EventBridge relies on resource-based policies. For EC2 instances, Kinesis -// data streams, and AWS Step Functions state machines, EventBridge relies on -// IAM roles that you specify in the RoleARN argument in PutTargets. For more -// information, see Authentication and Access Control (https://docs.aws.amazon.com/eventbridge/latest/userguide/auth-and-access-control-eventbridge.html) +// To be able to make API calls against the resources that you own, Amazon EventBridge +// (CloudWatch Events) needs the appropriate permissions. For AWS Lambda and +// Amazon SNS resources, EventBridge relies on resource-based policies. For +// EC2 instances, Kinesis data streams, AWS Step Functions state machines and +// API Gateway REST APIs, EventBridge relies on IAM roles that you specify in +// the RoleARN argument in PutTargets. For more information, see Authentication +// and Access Control (https://docs.aws.amazon.com/eventbridge/latest/userguide/auth-and-access-control-eventbridge.html) // in the Amazon EventBridge User Guide. // // If another AWS account is in the same region and has granted you permission @@ -2408,7 +2445,8 @@ func (c *CloudWatchEvents) PutTargetsRequest(input *PutTargetsInput) (req *reque // you run PutTargets. If your account sends events to another account, your // account is charged for each sent event. Each event sent to another account // is charged as a custom event. The account receiving the event is not charged. -// For more information, see Amazon CloudWatch Pricing (https://aws.amazon.com/cloudwatch/pricing/). +// For more information, see Amazon EventBridge (CloudWatch Events) Pricing +// (https://aws.amazon.com/eventbridge/pricing/). // // Input, InputPath, and InputTransformer are not available with PutTarget if // the target is an event bus of a different AWS account. @@ -2936,8 +2974,8 @@ func (c *CloudWatchEvents) UntagResourceRequest(input *UntagResourceInput) (req // UntagResource API operation for Amazon CloudWatch Events. // -// Removes one or more tags from the specified EventBridge resource. In CloudWatch -// Events, rules and event buses can be tagged. +// Removes one or more tags from the specified EventBridge resource. In Amazon +// EventBridge (CloudWatch Events, rules and event buses can be tagged. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4611,6 +4649,52 @@ func (s *EventSource) SetState(v string) *EventSource { return s } +// These are custom parameter to be used when the target is an API Gateway REST +// APIs. +type HttpParameters struct { + _ struct{} `type:"structure"` + + // The headers that need to be sent as part of request invoking the API Gateway + // REST API. + HeaderParameters map[string]*string `type:"map"` + + // The path parameter values to be used to populate API Gateway REST API path + // wildcards ("*"). + PathParameterValues []*string `type:"list"` + + // The query string keys/values that need to be sent as part of request invoking + // the API Gateway REST API. + QueryStringParameters map[string]*string `type:"map"` +} + +// String returns the string representation +func (s HttpParameters) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s HttpParameters) GoString() string { + return s.String() +} + +// SetHeaderParameters sets the HeaderParameters field's value. +func (s *HttpParameters) SetHeaderParameters(v map[string]*string) *HttpParameters { + s.HeaderParameters = v + return s +} + +// SetPathParameterValues sets the PathParameterValues field's value. +func (s *HttpParameters) SetPathParameterValues(v []*string) *HttpParameters { + s.PathParameterValues = v + return s +} + +// SetQueryStringParameters sets the QueryStringParameters field's value. +func (s *HttpParameters) SetQueryStringParameters(v map[string]*string) *HttpParameters { + s.QueryStringParameters = v + return s +} + // Contains the parameters needed for you to provide custom input to a target // based on one or more pieces of data extracted from the event. type InputTransformer struct { @@ -5863,6 +5947,62 @@ func (s *NetworkConfiguration) SetAwsvpcConfiguration(v *AwsVpcConfiguration) *N return s } +// The operation you are attempting is not available in this region. +type OperationDisabledException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s OperationDisabledException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OperationDisabledException) GoString() string { + return s.String() +} + +func newErrorOperationDisabledException(v protocol.ResponseMetadata) error { + return &OperationDisabledException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *OperationDisabledException) Code() string { + return "OperationDisabledException" +} + +// Message returns the exception's message. +func (s *OperationDisabledException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *OperationDisabledException) OrigErr() error { + return nil +} + +func (s *OperationDisabledException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *OperationDisabledException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *OperationDisabledException) RequestID() string { + return s.RespMetadata.RequestID +} + // A partner event source is created by an SaaS partner. If a customer creates // a partner event bus that matches this event source, that AWS account can // receive events from the partner's applications or services. @@ -7611,6 +7751,14 @@ type Target struct { // in the Amazon EC2 Container Service Developer Guide. EcsParameters *EcsParameters `type:"structure"` + // Contains the HTTP parameters to use when the target is a API Gateway REST + // endpoint. + // + // If you specify an API Gateway REST API as a target, you can use this parameter + // to specify headers, path parameter, query string keys/values as part of your + // target invoking request. + HttpParameters *HttpParameters `type:"structure"` + // The ID of the target. // // Id is a required field @@ -7729,6 +7877,12 @@ func (s *Target) SetEcsParameters(v *EcsParameters) *Target { return s } +// SetHttpParameters sets the HttpParameters field's value. +func (s *Target) SetHttpParameters(v *HttpParameters) *Target { + s.HttpParameters = v + return s +} + // SetId sets the Id field's value. func (s *Target) SetId(v string) *Target { s.Id = &v @@ -7930,6 +8084,14 @@ const ( AssignPublicIpDisabled = "DISABLED" ) +// AssignPublicIp_Values returns all elements of the AssignPublicIp enum +func AssignPublicIp_Values() []string { + return []string{ + AssignPublicIpEnabled, + AssignPublicIpDisabled, + } +} + const ( // EventSourceStatePending is a EventSourceState enum value EventSourceStatePending = "PENDING" @@ -7941,6 +8103,15 @@ const ( EventSourceStateDeleted = "DELETED" ) +// EventSourceState_Values returns all elements of the EventSourceState enum +func EventSourceState_Values() []string { + return []string{ + EventSourceStatePending, + EventSourceStateActive, + EventSourceStateDeleted, + } +} + const ( // LaunchTypeEc2 is a LaunchType enum value LaunchTypeEc2 = "EC2" @@ -7949,6 +8120,14 @@ const ( LaunchTypeFargate = "FARGATE" ) +// LaunchType_Values returns all elements of the LaunchType enum +func LaunchType_Values() []string { + return []string{ + LaunchTypeEc2, + LaunchTypeFargate, + } +} + const ( // RuleStateEnabled is a RuleState enum value RuleStateEnabled = "ENABLED" @@ -7956,3 +8135,11 @@ const ( // RuleStateDisabled is a RuleState enum value RuleStateDisabled = "DISABLED" ) + +// RuleState_Values returns all elements of the RuleState enum +func RuleState_Values() []string { + return []string{ + RuleStateEnabled, + RuleStateDisabled, + } +} 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 059007e401b..9de2a8c22a6 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 @@ -49,6 +49,12 @@ const ( // or UntagResource. ErrCodeManagedRuleException = "ManagedRuleException" + // ErrCodeOperationDisabledException for service response error code + // "OperationDisabledException". + // + // The operation you are attempting is not available in this region. + ErrCodeOperationDisabledException = "OperationDisabledException" + // ErrCodePolicyLengthExceededException for service response error code // "PolicyLengthExceededException". // @@ -75,6 +81,7 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "InvalidStateException": newErrorInvalidStateException, "LimitExceededException": newErrorLimitExceededException, "ManagedRuleException": newErrorManagedRuleException, + "OperationDisabledException": newErrorOperationDisabledException, "PolicyLengthExceededException": newErrorPolicyLengthExceededException, "ResourceAlreadyExistsException": newErrorResourceAlreadyExistsException, "ResourceNotFoundException": newErrorResourceNotFoundException, 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 b629ace9dd1..f8a8ce658b8 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 @@ -258,9 +258,10 @@ func (c *CloudWatchLogs) CreateExportTaskRequest(input *CreateExportTaskInput) ( // // This is an asynchronous call. If all the required information is provided, // this operation initiates an export task and responds with the ID of the task. -// After the task has started, you can use DescribeExportTasks to get the status -// of the export task. Each account can only have one active (RUNNING or PENDING) -// export task at a time. To cancel an export task, use CancelExportTask. +// After the task has started, you can use DescribeExportTasks (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeExportTasks.html) +// to get the status of the export task. Each account can only have one active +// (RUNNING or PENDING) export task at a time. To cancel an export task, use +// CancelExportTask (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CancelExportTask.html). // // You can export logs from multiple log groups or multiple time ranges to the // same S3 bucket. To separate out log data for each export task, you can specify @@ -896,6 +897,89 @@ func (c *CloudWatchLogs) DeleteMetricFilterWithContext(ctx aws.Context, input *D return out, req.Send() } +const opDeleteQueryDefinition = "DeleteQueryDefinition" + +// DeleteQueryDefinitionRequest generates a "aws/request.Request" representing the +// client's request for the DeleteQueryDefinition operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteQueryDefinition for more information on using the DeleteQueryDefinition +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteQueryDefinitionRequest method. +// req, resp := client.DeleteQueryDefinitionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteQueryDefinition +func (c *CloudWatchLogs) DeleteQueryDefinitionRequest(input *DeleteQueryDefinitionInput) (req *request.Request, output *DeleteQueryDefinitionOutput) { + op := &request.Operation{ + Name: opDeleteQueryDefinition, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteQueryDefinitionInput{} + } + + output = &DeleteQueryDefinitionOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteQueryDefinition API operation for Amazon CloudWatch Logs. +// +// Returns awserr.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 CloudWatch Logs's +// API operation DeleteQueryDefinition for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// A parameter is specified incorrectly. +// +// * ResourceNotFoundException +// The specified resource does not exist. +// +// * ServiceUnavailableException +// The service cannot complete the request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DeleteQueryDefinition +func (c *CloudWatchLogs) DeleteQueryDefinition(input *DeleteQueryDefinitionInput) (*DeleteQueryDefinitionOutput, error) { + req, out := c.DeleteQueryDefinitionRequest(input) + return out, req.Send() +} + +// DeleteQueryDefinitionWithContext is the same as DeleteQueryDefinition with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteQueryDefinition for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DeleteQueryDefinitionWithContext(ctx aws.Context, input *DeleteQueryDefinitionInput, opts ...request.Option) (*DeleteQueryDefinitionOutput, error) { + req, out := c.DeleteQueryDefinitionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteResourcePolicy = "DeleteResourcePolicy" // DeleteResourcePolicyRequest generates a "aws/request.Request" representing the @@ -1914,6 +1998,86 @@ func (c *CloudWatchLogs) DescribeQueriesWithContext(ctx aws.Context, input *Desc return out, req.Send() } +const opDescribeQueryDefinitions = "DescribeQueryDefinitions" + +// DescribeQueryDefinitionsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeQueryDefinitions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeQueryDefinitions for more information on using the DescribeQueryDefinitions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeQueryDefinitionsRequest method. +// req, resp := client.DescribeQueryDefinitionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeQueryDefinitions +func (c *CloudWatchLogs) DescribeQueryDefinitionsRequest(input *DescribeQueryDefinitionsInput) (req *request.Request, output *DescribeQueryDefinitionsOutput) { + op := &request.Operation{ + Name: opDescribeQueryDefinitions, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeQueryDefinitionsInput{} + } + + output = &DescribeQueryDefinitionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeQueryDefinitions API operation for Amazon CloudWatch Logs. +// +// Returns awserr.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 CloudWatch Logs's +// API operation DescribeQueryDefinitions for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// A parameter is specified incorrectly. +// +// * ServiceUnavailableException +// The service cannot complete the request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/DescribeQueryDefinitions +func (c *CloudWatchLogs) DescribeQueryDefinitions(input *DescribeQueryDefinitionsInput) (*DescribeQueryDefinitionsOutput, error) { + req, out := c.DescribeQueryDefinitionsRequest(input) + return out, req.Send() +} + +// DescribeQueryDefinitionsWithContext is the same as DescribeQueryDefinitions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeQueryDefinitions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeQueryDefinitionsWithContext(ctx aws.Context, input *DescribeQueryDefinitionsInput, opts ...request.Option) (*DescribeQueryDefinitionsOutput, error) { + req, out := c.DescribeQueryDefinitionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeResourcePolicies = "DescribeResourcePolicies" // DescribeResourcePoliciesRequest generates a "aws/request.Request" representing the @@ -2589,7 +2753,9 @@ func (c *CloudWatchLogs) GetLogGroupFieldsRequest(input *GetLogGroupFieldsInput) // The search is limited to a time period that you specify. // // In the results, fields that start with @ are fields generated by CloudWatch -// Logs. For example, @timestamp is the timestamp of each log event. +// Logs. For example, @timestamp is the timestamp of each log event. For more +// information about the fields that are generated by CloudWatch logs, see Supported +// Logs and Discovered Fields (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_AnalyzeLogData-discoverable-fields.html). // // The response results are sorted by the frequency percentage, starting with // the highest percentage. @@ -2777,9 +2943,11 @@ func (c *CloudWatchLogs) GetQueryResultsRequest(input *GetQueryResultsInput) (re // // Only the fields requested in the query are returned, along with a @ptr field // which is the identifier for the log record. You can use the value of @ptr -// in a operation to get the full log record. +// in a GetLogRecord (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogRecord.html) +// operation to get the full log record. // -// GetQueryResults does not start a query execution. To run a query, use . +// GetQueryResults does not start a query execution. To run a query, use StartQuery +// (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartQuery.html). // // If the value of the Status field in the output is Running, this operation // returns only partial results. If you see a value of Scheduled or Running @@ -2955,12 +3123,13 @@ func (c *CloudWatchLogs) PutDestinationRequest(input *PutDestinationInput) (req // // A destination encapsulates a physical resource (such as an Amazon Kinesis // stream) and enables you to subscribe to a real-time stream of log events -// for a different account, ingested using PutLogEvents. +// for a different account, ingested using PutLogEvents (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html). // // Through an access policy, a destination controls what is written to it. By // default, PutDestination does not set any access policy with the destination, -// which means a cross-account user cannot call PutSubscriptionFilter against -// this destination. To enable this, the destination owner must call PutDestinationPolicy +// which means a cross-account user cannot call PutSubscriptionFilter (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutSubscriptionFilter.html) +// against this destination. To enable this, the destination owner must call +// PutDestinationPolicy (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutDestinationPolicy.html) // after PutDestination. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -3269,7 +3438,7 @@ func (c *CloudWatchLogs) PutMetricFilterRequest(input *PutMetricFilterInput) (re // // Creates or updates a metric filter and associates it with the specified log // group. Metric filters allow you to configure rules to extract metric data -// from log events ingested through PutLogEvents. +// from log events ingested through PutLogEvents (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html). // // The maximum number of metric filters that can be associated with a log group // is 100. @@ -3319,6 +3488,89 @@ func (c *CloudWatchLogs) PutMetricFilterWithContext(ctx aws.Context, input *PutM return out, req.Send() } +const opPutQueryDefinition = "PutQueryDefinition" + +// PutQueryDefinitionRequest generates a "aws/request.Request" representing the +// client's request for the PutQueryDefinition operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutQueryDefinition for more information on using the PutQueryDefinition +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutQueryDefinitionRequest method. +// req, resp := client.PutQueryDefinitionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutQueryDefinition +func (c *CloudWatchLogs) PutQueryDefinitionRequest(input *PutQueryDefinitionInput) (req *request.Request, output *PutQueryDefinitionOutput) { + op := &request.Operation{ + Name: opPutQueryDefinition, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &PutQueryDefinitionInput{} + } + + output = &PutQueryDefinitionOutput{} + req = c.newRequest(op, input, output) + return +} + +// PutQueryDefinition API operation for Amazon CloudWatch Logs. +// +// Returns awserr.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 CloudWatch Logs's +// API operation PutQueryDefinition for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// A parameter is specified incorrectly. +// +// * ResourceNotFoundException +// The specified resource does not exist. +// +// * ServiceUnavailableException +// The service cannot complete the request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/PutQueryDefinition +func (c *CloudWatchLogs) PutQueryDefinition(input *PutQueryDefinitionInput) (*PutQueryDefinitionOutput, error) { + req, out := c.PutQueryDefinitionRequest(input) + return out, req.Send() +} + +// PutQueryDefinitionWithContext is the same as PutQueryDefinition with the addition of +// the ability to pass a context and additional request options. +// +// See PutQueryDefinition for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) PutQueryDefinitionWithContext(ctx aws.Context, input *PutQueryDefinitionInput, opts ...request.Option) (*PutQueryDefinitionOutput, error) { + req, out := c.PutQueryDefinitionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opPutResourcePolicy = "PutResourcePolicy" // PutResourcePolicyRequest generates a "aws/request.Request" representing the @@ -3544,8 +3796,9 @@ func (c *CloudWatchLogs) PutSubscriptionFilterRequest(input *PutSubscriptionFilt // // Creates or updates a subscription filter and associates it with the specified // log group. Subscription filters allow you to subscribe to a real-time stream -// of log events ingested through PutLogEvents and have them delivered to a -// specific destination. Currently, the supported destinations are: +// of log events ingested through PutLogEvents (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html) +// and have them delivered to a specific destination. Currently, the supported +// destinations are: // // * An Amazon Kinesis stream belonging to the same account as the subscription // filter, for same-account delivery. @@ -3672,7 +3925,7 @@ func (c *CloudWatchLogs) StartQueryRequest(input *StartQueryInput) (req *request // Returned Error Types: // * MalformedQueryException // The query string is not valid. Details about this error are displayed in -// a QueryCompileError object. For more information, see . +// a QueryCompileError object. For more information, see QueryCompileError (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_QueryCompileError.html)"/>. // // For more information about valid query syntax, see CloudWatch Logs Insights // Query Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html). @@ -3845,11 +4098,11 @@ func (c *CloudWatchLogs) TagLogGroupRequest(input *TagLogGroupInput) (req *reque // // Adds or updates the specified tags for the specified log group. // -// To list the tags for a log group, use ListTagsLogGroup. To remove tags, use -// UntagLogGroup. +// To list the tags for a log group, use ListTagsLogGroup (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListTagsLogGroup.html). +// To remove tags, use UntagLogGroup (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_UntagLogGroup.html). // // For more information about tags, see Tag Log Groups in Amazon CloudWatch -// Logs (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/log-group-tagging.html) +// Logs (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html#log-group-tagging) // in the Amazon CloudWatch Logs User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -4019,8 +4272,8 @@ func (c *CloudWatchLogs) UntagLogGroupRequest(input *UntagLogGroupInput) (req *r // // Removes the specified tags from the specified log group. // -// To list the tags for a log group, use ListTagsLogGroup. To add tags, use -// UntagLogGroup. +// To list the tags for a log group, use ListTagsLogGroup (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_ListTagsLogGroup.html). +// To add tags, use TagLogGroup (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_TagLogGroup.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 @@ -4793,6 +5046,64 @@ func (s DeleteMetricFilterOutput) GoString() string { return s.String() } +type DeleteQueryDefinitionInput struct { + _ struct{} `type:"structure"` + + // QueryDefinitionId is a required field + QueryDefinitionId *string `locationName:"queryDefinitionId" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteQueryDefinitionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteQueryDefinitionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteQueryDefinitionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteQueryDefinitionInput"} + if s.QueryDefinitionId == nil { + invalidParams.Add(request.NewErrParamRequired("QueryDefinitionId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetQueryDefinitionId sets the QueryDefinitionId field's value. +func (s *DeleteQueryDefinitionInput) SetQueryDefinitionId(v string) *DeleteQueryDefinitionInput { + s.QueryDefinitionId = &v + return s +} + +type DeleteQueryDefinitionOutput struct { + _ struct{} `type:"structure"` + + Success *bool `locationName:"success" type:"boolean"` +} + +// String returns the string representation +func (s DeleteQueryDefinitionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteQueryDefinitionOutput) GoString() string { + return s.String() +} + +// SetSuccess sets the Success field's value. +func (s *DeleteQueryDefinitionOutput) SetSuccess(v bool) *DeleteQueryDefinitionOutput { + s.Success = &v + return s +} + type DeleteResourcePolicyInput struct { _ struct{} `type:"structure"` @@ -5631,6 +5942,97 @@ func (s *DescribeQueriesOutput) SetQueries(v []*QueryInfo) *DescribeQueriesOutpu return s } +type DescribeQueryDefinitionsInput struct { + _ struct{} `type:"structure"` + + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` + + // The token for the next set of items to return. The token expires after 24 + // hours. + NextToken *string `locationName:"nextToken" min:"1" type:"string"` + + QueryDefinitionNamePrefix *string `locationName:"queryDefinitionNamePrefix" min:"1" type:"string"` +} + +// String returns the string representation +func (s DescribeQueryDefinitionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeQueryDefinitionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeQueryDefinitionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeQueryDefinitionsInput"} + 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 s.QueryDefinitionNamePrefix != nil && len(*s.QueryDefinitionNamePrefix) < 1 { + invalidParams.Add(request.NewErrParamMinLen("QueryDefinitionNamePrefix", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeQueryDefinitionsInput) SetMaxResults(v int64) *DescribeQueryDefinitionsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeQueryDefinitionsInput) SetNextToken(v string) *DescribeQueryDefinitionsInput { + s.NextToken = &v + return s +} + +// SetQueryDefinitionNamePrefix sets the QueryDefinitionNamePrefix field's value. +func (s *DescribeQueryDefinitionsInput) SetQueryDefinitionNamePrefix(v string) *DescribeQueryDefinitionsInput { + s.QueryDefinitionNamePrefix = &v + return s +} + +type DescribeQueryDefinitionsOutput struct { + _ struct{} `type:"structure"` + + // The token for the next set of items to return. The token expires after 24 + // hours. + NextToken *string `locationName:"nextToken" min:"1" type:"string"` + + QueryDefinitions []*QueryDefinition `locationName:"queryDefinitions" type:"list"` +} + +// String returns the string representation +func (s DescribeQueryDefinitionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeQueryDefinitionsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeQueryDefinitionsOutput) SetNextToken(v string) *DescribeQueryDefinitionsOutput { + s.NextToken = &v + return s +} + +// SetQueryDefinitions sets the QueryDefinitions field's value. +func (s *DescribeQueryDefinitionsOutput) SetQueryDefinitions(v []*QueryDefinition) *DescribeQueryDefinitionsOutput { + s.QueryDefinitions = v + return s +} + type DescribeResourcePoliciesInput struct { _ struct{} `type:"structure"` @@ -7344,7 +7746,7 @@ func (s *LogStream) SetUploadSequenceToken(v string) *LogStream { } // The query string is not valid. Details about this error are displayed in -// a QueryCompileError object. For more information, see . +// a QueryCompileError object. For more information, see QueryCompileError (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_QueryCompileError.html)"/>. // // For more information about valid query syntax, see CloudWatch Logs Insights // Query Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html). @@ -7528,7 +7930,9 @@ type MetricTransformation struct { // MetricName is a required field MetricName *string `locationName:"metricName" type:"string" required:"true"` - // The namespace of the CloudWatch metric. + // A custom namespace to contain your metric in CloudWatch. Use namespaces to + // group together metrics that are similar. For more information, see Namespaces + // (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Namespace). // // MetricNamespace is a required field MetricNamespace *string `locationName:"metricNamespace" type:"string" required:"true"` @@ -7885,9 +8289,9 @@ type PutLogEventsInput struct { // The sequence token obtained from the response of the previous PutLogEvents // call. An upload in a newly created log stream does not require a sequence - // token. You can also get the sequence token using DescribeLogStreams. If you - // call PutLogEvents twice within a narrow time period using the same value - // for sequenceToken, both calls may be successful, or one may be rejected. + // token. You can also get the sequence token using DescribeLogStreams (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogStreams.html). + // If you call PutLogEvents twice within a narrow time period using the same + // value for sequenceToken, both calls may be successful, or one may be rejected. SequenceToken *string `locationName:"sequenceToken" min:"1" type:"string"` } @@ -8111,6 +8515,98 @@ func (s PutMetricFilterOutput) GoString() string { return s.String() } +type PutQueryDefinitionInput struct { + _ struct{} `type:"structure"` + + LogGroupNames []*string `locationName:"logGroupNames" type:"list"` + + // Name is a required field + Name *string `locationName:"name" min:"1" type:"string" required:"true"` + + QueryDefinitionId *string `locationName:"queryDefinitionId" type:"string"` + + // QueryString is a required field + QueryString *string `locationName:"queryString" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s PutQueryDefinitionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutQueryDefinitionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutQueryDefinitionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutQueryDefinitionInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.QueryString == nil { + invalidParams.Add(request.NewErrParamRequired("QueryString")) + } + if s.QueryString != nil && len(*s.QueryString) < 1 { + invalidParams.Add(request.NewErrParamMinLen("QueryString", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLogGroupNames sets the LogGroupNames field's value. +func (s *PutQueryDefinitionInput) SetLogGroupNames(v []*string) *PutQueryDefinitionInput { + s.LogGroupNames = v + return s +} + +// SetName sets the Name field's value. +func (s *PutQueryDefinitionInput) SetName(v string) *PutQueryDefinitionInput { + s.Name = &v + return s +} + +// SetQueryDefinitionId sets the QueryDefinitionId field's value. +func (s *PutQueryDefinitionInput) SetQueryDefinitionId(v string) *PutQueryDefinitionInput { + s.QueryDefinitionId = &v + return s +} + +// SetQueryString sets the QueryString field's value. +func (s *PutQueryDefinitionInput) SetQueryString(v string) *PutQueryDefinitionInput { + s.QueryString = &v + return s +} + +type PutQueryDefinitionOutput struct { + _ struct{} `type:"structure"` + + QueryDefinitionId *string `locationName:"queryDefinitionId" type:"string"` +} + +// String returns the string representation +func (s PutQueryDefinitionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutQueryDefinitionOutput) GoString() string { + return s.String() +} + +// SetQueryDefinitionId sets the QueryDefinitionId field's value. +func (s *PutQueryDefinitionOutput) SetQueryDefinitionId(v string) *PutQueryDefinitionOutput { + s.QueryDefinitionId = &v + return s +} + type PutResourcePolicyInput struct { _ struct{} `type:"structure"` @@ -8290,7 +8786,8 @@ type PutSubscriptionFilterInput struct { // A name for the subscription filter. If you are updating an existing filter, // you must specify the correct name in filterName. Otherwise, the call fails // because you cannot associate a second filter with a log group. To find the - // name of the filter currently associated with a log group, use DescribeSubscriptionFilters. + // name of the filter currently associated with a log group, use DescribeSubscriptionFilters + // (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeSubscriptionFilters.html). // // FilterName is a required field FilterName *string `locationName:"filterName" min:"1" type:"string" required:"true"` @@ -8472,6 +8969,60 @@ func (s *QueryCompileErrorLocation) SetStartCharOffset(v int64) *QueryCompileErr return s } +type QueryDefinition struct { + _ struct{} `type:"structure"` + + LastModified *int64 `locationName:"lastModified" type:"long"` + + LogGroupNames []*string `locationName:"logGroupNames" type:"list"` + + Name *string `locationName:"name" min:"1" type:"string"` + + QueryDefinitionId *string `locationName:"queryDefinitionId" type:"string"` + + QueryString *string `locationName:"queryString" min:"1" type:"string"` +} + +// String returns the string representation +func (s QueryDefinition) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s QueryDefinition) GoString() string { + return s.String() +} + +// SetLastModified sets the LastModified field's value. +func (s *QueryDefinition) SetLastModified(v int64) *QueryDefinition { + s.LastModified = &v + return s +} + +// SetLogGroupNames sets the LogGroupNames field's value. +func (s *QueryDefinition) SetLogGroupNames(v []*string) *QueryDefinition { + s.LogGroupNames = v + return s +} + +// SetName sets the Name field's value. +func (s *QueryDefinition) SetName(v string) *QueryDefinition { + s.Name = &v + return s +} + +// SetQueryDefinitionId sets the QueryDefinitionId field's value. +func (s *QueryDefinition) SetQueryDefinitionId(v string) *QueryDefinition { + s.QueryDefinitionId = &v + return s +} + +// SetQueryString sets the QueryString field's value. +func (s *QueryDefinition) SetQueryString(v string) *QueryDefinition { + s.QueryString = &v + return s +} + // Information about one CloudWatch Logs Insights query that matches the request // in a DescribeQueries operation. type QueryInfo struct { @@ -8778,6 +9329,9 @@ func (s *ResourcePolicy) SetPolicyName(v string) *ResourcePolicy { // Contains one field from one log event returned by a CloudWatch Logs Insights // query, along with the value of that field. +// +// For more information about the fields that are generated by CloudWatch logs, +// see Supported Logs and Discovered Fields (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_AnalyzeLogData-discoverable-fields.html). type ResultField struct { _ struct{} `type:"structure"` @@ -9469,6 +10023,14 @@ const ( DistributionByLogStream = "ByLogStream" ) +// Distribution_Values returns all elements of the Distribution enum +func Distribution_Values() []string { + return []string{ + DistributionRandom, + DistributionByLogStream, + } +} + const ( // ExportTaskStatusCodeCancelled is a ExportTaskStatusCode enum value ExportTaskStatusCodeCancelled = "CANCELLED" @@ -9489,6 +10051,18 @@ const ( ExportTaskStatusCodeRunning = "RUNNING" ) +// ExportTaskStatusCode_Values returns all elements of the ExportTaskStatusCode enum +func ExportTaskStatusCode_Values() []string { + return []string{ + ExportTaskStatusCodeCancelled, + ExportTaskStatusCodeCompleted, + ExportTaskStatusCodeFailed, + ExportTaskStatusCodePending, + ExportTaskStatusCodePendingCancel, + ExportTaskStatusCodeRunning, + } +} + const ( // OrderByLogStreamName is a OrderBy enum value OrderByLogStreamName = "LogStreamName" @@ -9497,6 +10071,14 @@ const ( OrderByLastEventTime = "LastEventTime" ) +// OrderBy_Values returns all elements of the OrderBy enum +func OrderBy_Values() []string { + return []string{ + OrderByLogStreamName, + OrderByLastEventTime, + } +} + const ( // QueryStatusScheduled is a QueryStatus enum value QueryStatusScheduled = "Scheduled" @@ -9513,3 +10095,14 @@ const ( // QueryStatusCancelled is a QueryStatus enum value QueryStatusCancelled = "Cancelled" ) + +// QueryStatus_Values returns all elements of the QueryStatus enum +func QueryStatus_Values() []string { + return []string{ + QueryStatusScheduled, + QueryStatusRunning, + QueryStatusComplete, + QueryStatusFailed, + QueryStatusCancelled, + } +} 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 c6e23336d00..39c9cd5eafe 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 @@ -43,7 +43,7 @@ const ( // "MalformedQueryException". // // The query string is not valid. Details about this error are displayed in - // a QueryCompileError object. For more information, see . + // a QueryCompileError object. For more information, see QueryCompileError (https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_QueryCompileError.html)"/>. // // For more information about valid query syntax, see CloudWatch Logs Insights // Query Syntax (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_QuerySyntax.html). diff --git a/vendor/github.com/aws/aws-sdk-go/service/codeartifact/api.go b/vendor/github.com/aws/aws-sdk-go/service/codeartifact/api.go new file mode 100644 index 00000000000..32dee23aba5 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/codeartifact/api.go @@ -0,0 +1,9587 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package codeartifact + +import ( + "fmt" + "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" +) + +const opAssociateExternalConnection = "AssociateExternalConnection" + +// AssociateExternalConnectionRequest generates a "aws/request.Request" representing the +// client's request for the AssociateExternalConnection operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See AssociateExternalConnection for more information on using the AssociateExternalConnection +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the AssociateExternalConnectionRequest method. +// req, resp := client.AssociateExternalConnectionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/AssociateExternalConnection +func (c *CodeArtifact) AssociateExternalConnectionRequest(input *AssociateExternalConnectionInput) (req *request.Request, output *AssociateExternalConnectionOutput) { + op := &request.Operation{ + Name: opAssociateExternalConnection, + HTTPMethod: "POST", + HTTPPath: "/v1/repository/external-connection", + } + + if input == nil { + input = &AssociateExternalConnectionInput{} + } + + output = &AssociateExternalConnectionOutput{} + req = c.newRequest(op, input, output) + return +} + +// AssociateExternalConnection API operation for CodeArtifact. +// +// Adds an existing external connection to a repository. One external connection +// is allowed per repository. +// +// A repository can have one or more upstream repositories, or an external connection. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for CodeArtifact's +// API operation AssociateExternalConnection for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ServiceQuotaExceededException +// The operation did not succeed because it would have exceeded a service limit +// for your account. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/AssociateExternalConnection +func (c *CodeArtifact) AssociateExternalConnection(input *AssociateExternalConnectionInput) (*AssociateExternalConnectionOutput, error) { + req, out := c.AssociateExternalConnectionRequest(input) + return out, req.Send() +} + +// AssociateExternalConnectionWithContext is the same as AssociateExternalConnection with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateExternalConnection for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) AssociateExternalConnectionWithContext(ctx aws.Context, input *AssociateExternalConnectionInput, opts ...request.Option) (*AssociateExternalConnectionOutput, error) { + req, out := c.AssociateExternalConnectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCopyPackageVersions = "CopyPackageVersions" + +// CopyPackageVersionsRequest generates a "aws/request.Request" representing the +// client's request for the CopyPackageVersions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CopyPackageVersions for more information on using the CopyPackageVersions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CopyPackageVersionsRequest method. +// req, resp := client.CopyPackageVersionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/CopyPackageVersions +func (c *CodeArtifact) CopyPackageVersionsRequest(input *CopyPackageVersionsInput) (req *request.Request, output *CopyPackageVersionsOutput) { + op := &request.Operation{ + Name: opCopyPackageVersions, + HTTPMethod: "POST", + HTTPPath: "/v1/package/versions/copy", + } + + if input == nil { + input = &CopyPackageVersionsInput{} + } + + output = &CopyPackageVersionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// CopyPackageVersions API operation for CodeArtifact. +// +// Copies package versions from one repository to another repository in the +// same domain. +// +// You must specify versions or versionRevisions. You cannot specify both. +// +// Returns awserr.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 CodeArtifact's +// API operation CopyPackageVersions for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ServiceQuotaExceededException +// The operation did not succeed because it would have exceeded a service limit +// for your account. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/CopyPackageVersions +func (c *CodeArtifact) CopyPackageVersions(input *CopyPackageVersionsInput) (*CopyPackageVersionsOutput, error) { + req, out := c.CopyPackageVersionsRequest(input) + return out, req.Send() +} + +// CopyPackageVersionsWithContext is the same as CopyPackageVersions with the addition of +// the ability to pass a context and additional request options. +// +// See CopyPackageVersions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) CopyPackageVersionsWithContext(ctx aws.Context, input *CopyPackageVersionsInput, opts ...request.Option) (*CopyPackageVersionsOutput, error) { + req, out := c.CopyPackageVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateDomain = "CreateDomain" + +// CreateDomainRequest generates a "aws/request.Request" representing the +// client's request for the CreateDomain operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateDomain for more information on using the CreateDomain +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateDomainRequest method. +// req, resp := client.CreateDomainRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/CreateDomain +func (c *CodeArtifact) CreateDomainRequest(input *CreateDomainInput) (req *request.Request, output *CreateDomainOutput) { + op := &request.Operation{ + Name: opCreateDomain, + HTTPMethod: "POST", + HTTPPath: "/v1/domain", + } + + if input == nil { + input = &CreateDomainInput{} + } + + output = &CreateDomainOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateDomain API operation for CodeArtifact. +// +// Creates a domain. CodeArtifact domains make it easier to manage multiple +// repositories across an organization. You can use a domain to apply permissions +// across many repositories owned by different AWS accounts. An asset is stored +// only once in a domain, even if it's in multiple repositories. +// +// Although you can have multiple domains, we recommend a single production +// domain that contains all published artifacts so that your development teams +// can find and share packages. You can use a second pre-production domain to +// test changes to the production domain configuration. +// +// Returns awserr.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 CodeArtifact's +// API operation CreateDomain for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ServiceQuotaExceededException +// The operation did not succeed because it would have exceeded a service limit +// for your account. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/CreateDomain +func (c *CodeArtifact) CreateDomain(input *CreateDomainInput) (*CreateDomainOutput, error) { + req, out := c.CreateDomainRequest(input) + 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 *CodeArtifact) 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 opCreateRepository = "CreateRepository" + +// CreateRepositoryRequest generates a "aws/request.Request" representing the +// client's request for the CreateRepository operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateRepository for more information on using the CreateRepository +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateRepositoryRequest method. +// req, resp := client.CreateRepositoryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/CreateRepository +func (c *CodeArtifact) CreateRepositoryRequest(input *CreateRepositoryInput) (req *request.Request, output *CreateRepositoryOutput) { + op := &request.Operation{ + Name: opCreateRepository, + HTTPMethod: "POST", + HTTPPath: "/v1/repository", + } + + if input == nil { + input = &CreateRepositoryInput{} + } + + output = &CreateRepositoryOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateRepository API operation for CodeArtifact. +// +// Creates a repository. +// +// Returns awserr.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 CodeArtifact's +// API operation CreateRepository for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ServiceQuotaExceededException +// The operation did not succeed because it would have exceeded a service limit +// for your account. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/CreateRepository +func (c *CodeArtifact) CreateRepository(input *CreateRepositoryInput) (*CreateRepositoryOutput, error) { + req, out := c.CreateRepositoryRequest(input) + 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 *CodeArtifact) 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 opDeleteDomain = "DeleteDomain" + +// DeleteDomainRequest generates a "aws/request.Request" representing the +// client's request for the DeleteDomain operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteDomain for more information on using the DeleteDomain +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteDomainRequest method. +// req, resp := client.DeleteDomainRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DeleteDomain +func (c *CodeArtifact) DeleteDomainRequest(input *DeleteDomainInput) (req *request.Request, output *DeleteDomainOutput) { + op := &request.Operation{ + Name: opDeleteDomain, + HTTPMethod: "DELETE", + HTTPPath: "/v1/domain", + } + + if input == nil { + input = &DeleteDomainInput{} + } + + output = &DeleteDomainOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteDomain API operation for CodeArtifact. +// +// Deletes a domain. You cannot delete a domain that contains repositories. +// If you want to delete a domain with repositories, first delete its repositories. +// +// Returns awserr.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 CodeArtifact's +// API operation DeleteDomain for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DeleteDomain +func (c *CodeArtifact) DeleteDomain(input *DeleteDomainInput) (*DeleteDomainOutput, error) { + req, out := c.DeleteDomainRequest(input) + 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 *CodeArtifact) 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 opDeleteDomainPermissionsPolicy = "DeleteDomainPermissionsPolicy" + +// DeleteDomainPermissionsPolicyRequest generates a "aws/request.Request" representing the +// client's request for the DeleteDomainPermissionsPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteDomainPermissionsPolicy for more information on using the DeleteDomainPermissionsPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteDomainPermissionsPolicyRequest method. +// req, resp := client.DeleteDomainPermissionsPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DeleteDomainPermissionsPolicy +func (c *CodeArtifact) DeleteDomainPermissionsPolicyRequest(input *DeleteDomainPermissionsPolicyInput) (req *request.Request, output *DeleteDomainPermissionsPolicyOutput) { + op := &request.Operation{ + Name: opDeleteDomainPermissionsPolicy, + HTTPMethod: "DELETE", + HTTPPath: "/v1/domain/permissions/policy", + } + + if input == nil { + input = &DeleteDomainPermissionsPolicyInput{} + } + + output = &DeleteDomainPermissionsPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteDomainPermissionsPolicy API operation for CodeArtifact. +// +// Deletes the resource policy set on a domain. +// +// Returns awserr.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 CodeArtifact's +// API operation DeleteDomainPermissionsPolicy for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DeleteDomainPermissionsPolicy +func (c *CodeArtifact) DeleteDomainPermissionsPolicy(input *DeleteDomainPermissionsPolicyInput) (*DeleteDomainPermissionsPolicyOutput, error) { + req, out := c.DeleteDomainPermissionsPolicyRequest(input) + return out, req.Send() +} + +// DeleteDomainPermissionsPolicyWithContext is the same as DeleteDomainPermissionsPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDomainPermissionsPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) DeleteDomainPermissionsPolicyWithContext(ctx aws.Context, input *DeleteDomainPermissionsPolicyInput, opts ...request.Option) (*DeleteDomainPermissionsPolicyOutput, error) { + req, out := c.DeleteDomainPermissionsPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeletePackageVersions = "DeletePackageVersions" + +// DeletePackageVersionsRequest generates a "aws/request.Request" representing the +// client's request for the DeletePackageVersions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeletePackageVersions for more information on using the DeletePackageVersions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeletePackageVersionsRequest method. +// req, resp := client.DeletePackageVersionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DeletePackageVersions +func (c *CodeArtifact) DeletePackageVersionsRequest(input *DeletePackageVersionsInput) (req *request.Request, output *DeletePackageVersionsOutput) { + op := &request.Operation{ + Name: opDeletePackageVersions, + HTTPMethod: "POST", + HTTPPath: "/v1/package/versions/delete", + } + + if input == nil { + input = &DeletePackageVersionsInput{} + } + + output = &DeletePackageVersionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeletePackageVersions API operation for CodeArtifact. +// +// Deletes one or more versions of a package. A deleted package version cannot +// be restored in your repository. If you want to remove a package version from +// your repository and be able to restore it later, set its status to Archived. +// Archived packages cannot be downloaded from a repository and don't show up +// with list package APIs (for example, ListackageVersions (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListPackageVersions.html) +// ), but you can restore them using UpdatePackageVersionsStatus (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_UpdatePackageVersionsStatus.html) . +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for CodeArtifact's +// API operation DeletePackageVersions for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DeletePackageVersions +func (c *CodeArtifact) DeletePackageVersions(input *DeletePackageVersionsInput) (*DeletePackageVersionsOutput, error) { + req, out := c.DeletePackageVersionsRequest(input) + return out, req.Send() +} + +// DeletePackageVersionsWithContext is the same as DeletePackageVersions with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePackageVersions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) DeletePackageVersionsWithContext(ctx aws.Context, input *DeletePackageVersionsInput, opts ...request.Option) (*DeletePackageVersionsOutput, error) { + req, out := c.DeletePackageVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteRepository = "DeleteRepository" + +// DeleteRepositoryRequest generates a "aws/request.Request" representing the +// client's request for the DeleteRepository operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteRepository for more information on using the DeleteRepository +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteRepositoryRequest method. +// req, resp := client.DeleteRepositoryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DeleteRepository +func (c *CodeArtifact) DeleteRepositoryRequest(input *DeleteRepositoryInput) (req *request.Request, output *DeleteRepositoryOutput) { + op := &request.Operation{ + Name: opDeleteRepository, + HTTPMethod: "DELETE", + HTTPPath: "/v1/repository", + } + + if input == nil { + input = &DeleteRepositoryInput{} + } + + output = &DeleteRepositoryOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteRepository API operation for CodeArtifact. +// +// Deletes a repository. +// +// Returns awserr.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 CodeArtifact's +// API operation DeleteRepository for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DeleteRepository +func (c *CodeArtifact) DeleteRepository(input *DeleteRepositoryInput) (*DeleteRepositoryOutput, error) { + req, out := c.DeleteRepositoryRequest(input) + 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 *CodeArtifact) 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 opDeleteRepositoryPermissionsPolicy = "DeleteRepositoryPermissionsPolicy" + +// DeleteRepositoryPermissionsPolicyRequest generates a "aws/request.Request" representing the +// client's request for the DeleteRepositoryPermissionsPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteRepositoryPermissionsPolicy for more information on using the DeleteRepositoryPermissionsPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteRepositoryPermissionsPolicyRequest method. +// req, resp := client.DeleteRepositoryPermissionsPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DeleteRepositoryPermissionsPolicy +func (c *CodeArtifact) DeleteRepositoryPermissionsPolicyRequest(input *DeleteRepositoryPermissionsPolicyInput) (req *request.Request, output *DeleteRepositoryPermissionsPolicyOutput) { + op := &request.Operation{ + Name: opDeleteRepositoryPermissionsPolicy, + HTTPMethod: "DELETE", + HTTPPath: "/v1/repository/permissions/policies", + } + + if input == nil { + input = &DeleteRepositoryPermissionsPolicyInput{} + } + + output = &DeleteRepositoryPermissionsPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteRepositoryPermissionsPolicy API operation for CodeArtifact. +// +// Deletes the resource policy that is set on a repository. After a resource +// policy is deleted, the permissions allowed and denied by the deleted policy +// are removed. The effect of deleting a resource policy might not be immediate. +// +// Use DeleteRepositoryPermissionsPolicy with caution. After a policy is deleted, +// AWS users, roles, and accounts lose permissions to perform the repository +// actions granted by the deleted 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. +// +// See the AWS API reference guide for CodeArtifact's +// API operation DeleteRepositoryPermissionsPolicy for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DeleteRepositoryPermissionsPolicy +func (c *CodeArtifact) DeleteRepositoryPermissionsPolicy(input *DeleteRepositoryPermissionsPolicyInput) (*DeleteRepositoryPermissionsPolicyOutput, error) { + req, out := c.DeleteRepositoryPermissionsPolicyRequest(input) + return out, req.Send() +} + +// DeleteRepositoryPermissionsPolicyWithContext is the same as DeleteRepositoryPermissionsPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteRepositoryPermissionsPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) DeleteRepositoryPermissionsPolicyWithContext(ctx aws.Context, input *DeleteRepositoryPermissionsPolicyInput, opts ...request.Option) (*DeleteRepositoryPermissionsPolicyOutput, error) { + req, out := c.DeleteRepositoryPermissionsPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDescribeDomain = "DescribeDomain" + +// DescribeDomainRequest generates a "aws/request.Request" representing the +// client's request for the DescribeDomain operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeDomain for more information on using the DescribeDomain +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeDomainRequest method. +// req, resp := client.DescribeDomainRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DescribeDomain +func (c *CodeArtifact) DescribeDomainRequest(input *DescribeDomainInput) (req *request.Request, output *DescribeDomainOutput) { + op := &request.Operation{ + Name: opDescribeDomain, + HTTPMethod: "GET", + HTTPPath: "/v1/domain", + } + + if input == nil { + input = &DescribeDomainInput{} + } + + output = &DescribeDomainOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeDomain API operation for CodeArtifact. +// +// Returns a DomainDescription (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_DomainDescription.html) +// object that contains information about the requested domain. +// +// Returns awserr.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 CodeArtifact's +// API operation DescribeDomain for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DescribeDomain +func (c *CodeArtifact) DescribeDomain(input *DescribeDomainInput) (*DescribeDomainOutput, error) { + req, out := c.DescribeDomainRequest(input) + return out, req.Send() +} + +// DescribeDomainWithContext is the same as DescribeDomain with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeDomain for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) DescribeDomainWithContext(ctx aws.Context, input *DescribeDomainInput, opts ...request.Option) (*DescribeDomainOutput, error) { + req, out := c.DescribeDomainRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDescribePackageVersion = "DescribePackageVersion" + +// DescribePackageVersionRequest generates a "aws/request.Request" representing the +// client's request for the DescribePackageVersion operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribePackageVersion for more information on using the DescribePackageVersion +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribePackageVersionRequest method. +// req, resp := client.DescribePackageVersionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DescribePackageVersion +func (c *CodeArtifact) DescribePackageVersionRequest(input *DescribePackageVersionInput) (req *request.Request, output *DescribePackageVersionOutput) { + op := &request.Operation{ + Name: opDescribePackageVersion, + HTTPMethod: "GET", + HTTPPath: "/v1/package/version", + } + + if input == nil { + input = &DescribePackageVersionInput{} + } + + output = &DescribePackageVersionOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribePackageVersion API operation for CodeArtifact. +// +// Returns a PackageVersionDescription (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageVersionDescription.html) +// object that contains information about the requested package version. +// +// Returns awserr.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 CodeArtifact's +// API operation DescribePackageVersion for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DescribePackageVersion +func (c *CodeArtifact) DescribePackageVersion(input *DescribePackageVersionInput) (*DescribePackageVersionOutput, error) { + req, out := c.DescribePackageVersionRequest(input) + return out, req.Send() +} + +// DescribePackageVersionWithContext is the same as DescribePackageVersion with the addition of +// the ability to pass a context and additional request options. +// +// See DescribePackageVersion for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) DescribePackageVersionWithContext(ctx aws.Context, input *DescribePackageVersionInput, opts ...request.Option) (*DescribePackageVersionOutput, error) { + req, out := c.DescribePackageVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDescribeRepository = "DescribeRepository" + +// DescribeRepositoryRequest generates a "aws/request.Request" representing the +// client's request for the DescribeRepository operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeRepository for more information on using the DescribeRepository +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeRepositoryRequest method. +// req, resp := client.DescribeRepositoryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DescribeRepository +func (c *CodeArtifact) DescribeRepositoryRequest(input *DescribeRepositoryInput) (req *request.Request, output *DescribeRepositoryOutput) { + op := &request.Operation{ + Name: opDescribeRepository, + HTTPMethod: "GET", + HTTPPath: "/v1/repository", + } + + if input == nil { + input = &DescribeRepositoryInput{} + } + + output = &DescribeRepositoryOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeRepository API operation for CodeArtifact. +// +// Returns a RepositoryDescription object that contains detailed information +// about the requested repository. +// +// Returns awserr.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 CodeArtifact's +// API operation DescribeRepository for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DescribeRepository +func (c *CodeArtifact) DescribeRepository(input *DescribeRepositoryInput) (*DescribeRepositoryOutput, error) { + req, out := c.DescribeRepositoryRequest(input) + return out, req.Send() +} + +// DescribeRepositoryWithContext is the same as DescribeRepository with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRepository for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) DescribeRepositoryWithContext(ctx aws.Context, input *DescribeRepositoryInput, opts ...request.Option) (*DescribeRepositoryOutput, error) { + req, out := c.DescribeRepositoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDisassociateExternalConnection = "DisassociateExternalConnection" + +// DisassociateExternalConnectionRequest generates a "aws/request.Request" representing the +// client's request for the DisassociateExternalConnection operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DisassociateExternalConnection for more information on using the DisassociateExternalConnection +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DisassociateExternalConnectionRequest method. +// req, resp := client.DisassociateExternalConnectionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DisassociateExternalConnection +func (c *CodeArtifact) DisassociateExternalConnectionRequest(input *DisassociateExternalConnectionInput) (req *request.Request, output *DisassociateExternalConnectionOutput) { + op := &request.Operation{ + Name: opDisassociateExternalConnection, + HTTPMethod: "DELETE", + HTTPPath: "/v1/repository/external-connection", + } + + if input == nil { + input = &DisassociateExternalConnectionInput{} + } + + output = &DisassociateExternalConnectionOutput{} + req = c.newRequest(op, input, output) + return +} + +// DisassociateExternalConnection API operation for CodeArtifact. +// +// Removes an existing external connection from a repository. +// +// Returns awserr.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 CodeArtifact's +// API operation DisassociateExternalConnection for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ServiceQuotaExceededException +// The operation did not succeed because it would have exceeded a service limit +// for your account. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DisassociateExternalConnection +func (c *CodeArtifact) DisassociateExternalConnection(input *DisassociateExternalConnectionInput) (*DisassociateExternalConnectionOutput, error) { + req, out := c.DisassociateExternalConnectionRequest(input) + return out, req.Send() +} + +// DisassociateExternalConnectionWithContext is the same as DisassociateExternalConnection with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateExternalConnection for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) DisassociateExternalConnectionWithContext(ctx aws.Context, input *DisassociateExternalConnectionInput, opts ...request.Option) (*DisassociateExternalConnectionOutput, error) { + req, out := c.DisassociateExternalConnectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDisposePackageVersions = "DisposePackageVersions" + +// DisposePackageVersionsRequest generates a "aws/request.Request" representing the +// client's request for the DisposePackageVersions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DisposePackageVersions for more information on using the DisposePackageVersions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DisposePackageVersionsRequest method. +// req, resp := client.DisposePackageVersionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DisposePackageVersions +func (c *CodeArtifact) DisposePackageVersionsRequest(input *DisposePackageVersionsInput) (req *request.Request, output *DisposePackageVersionsOutput) { + op := &request.Operation{ + Name: opDisposePackageVersions, + HTTPMethod: "POST", + HTTPPath: "/v1/package/versions/dispose", + } + + if input == nil { + input = &DisposePackageVersionsInput{} + } + + output = &DisposePackageVersionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DisposePackageVersions API operation for CodeArtifact. +// +// Deletes the assets in package versions and sets the package versions' status +// to Disposed. A disposed package version cannot be restored in your repository +// because its assets are deleted. +// +// To view all disposed package versions in a repository, use ListackageVersions +// (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListPackageVersions.html) +// and set the status (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListPackageVersions.html#API_ListPackageVersions_RequestSyntax) +// parameter to Disposed. +// +// To view information about a disposed package version, use ListPackageVersions +// (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListPackageVersions.html) +// and set the status (https://docs.aws.amazon.com/API_ListPackageVersions.html#codeartifact-ListPackageVersions-response-status) +// parameter to Disposed. +// +// Returns awserr.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 CodeArtifact's +// API operation DisposePackageVersions for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/DisposePackageVersions +func (c *CodeArtifact) DisposePackageVersions(input *DisposePackageVersionsInput) (*DisposePackageVersionsOutput, error) { + req, out := c.DisposePackageVersionsRequest(input) + return out, req.Send() +} + +// DisposePackageVersionsWithContext is the same as DisposePackageVersions with the addition of +// the ability to pass a context and additional request options. +// +// See DisposePackageVersions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) DisposePackageVersionsWithContext(ctx aws.Context, input *DisposePackageVersionsInput, opts ...request.Option) (*DisposePackageVersionsOutput, error) { + req, out := c.DisposePackageVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetAuthorizationToken = "GetAuthorizationToken" + +// GetAuthorizationTokenRequest generates a "aws/request.Request" representing the +// client's request for the GetAuthorizationToken operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetAuthorizationToken for more information on using the GetAuthorizationToken +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetAuthorizationTokenRequest method. +// req, resp := client.GetAuthorizationTokenRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetAuthorizationToken +func (c *CodeArtifact) GetAuthorizationTokenRequest(input *GetAuthorizationTokenInput) (req *request.Request, output *GetAuthorizationTokenOutput) { + op := &request.Operation{ + Name: opGetAuthorizationToken, + HTTPMethod: "POST", + HTTPPath: "/v1/authorization-token", + } + + if input == nil { + input = &GetAuthorizationTokenInput{} + } + + output = &GetAuthorizationTokenOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetAuthorizationToken API operation for CodeArtifact. +// +// Generates a temporary authentication token for accessing repositories in +// the domain. This API requires the codeartifact:GetAuthorizationToken and +// sts:GetServiceBearerToken permissions. +// +// CodeArtifact authorization tokens are valid for a period of 12 hours when +// created with the login command. You can call login periodically to refresh +// the token. When you create an authorization token with the GetAuthorizationToken +// API, you can set a custom authorization period, up to a maximum of 12 hours, +// with the durationSeconds parameter. +// +// The authorization period begins after login or GetAuthorizationToken is called. +// If login or GetAuthorizationToken is called while assuming a role, the token +// lifetime is independent of the maximum session duration of the role. For +// example, if you call sts assume-role and specify a session duration of 15 +// minutes, then generate a CodeArtifact authorization token, the token will +// be valid for the full authorization period even though this is longer than +// the 15-minute session duration. +// +// See Using IAM Roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) +// for more information on controlling session duration. +// +// Returns awserr.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 CodeArtifact's +// API operation GetAuthorizationToken for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetAuthorizationToken +func (c *CodeArtifact) GetAuthorizationToken(input *GetAuthorizationTokenInput) (*GetAuthorizationTokenOutput, error) { + req, out := c.GetAuthorizationTokenRequest(input) + 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 *CodeArtifact) 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 opGetDomainPermissionsPolicy = "GetDomainPermissionsPolicy" + +// GetDomainPermissionsPolicyRequest generates a "aws/request.Request" representing the +// client's request for the GetDomainPermissionsPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetDomainPermissionsPolicy for more information on using the GetDomainPermissionsPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetDomainPermissionsPolicyRequest method. +// req, resp := client.GetDomainPermissionsPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetDomainPermissionsPolicy +func (c *CodeArtifact) GetDomainPermissionsPolicyRequest(input *GetDomainPermissionsPolicyInput) (req *request.Request, output *GetDomainPermissionsPolicyOutput) { + op := &request.Operation{ + Name: opGetDomainPermissionsPolicy, + HTTPMethod: "GET", + HTTPPath: "/v1/domain/permissions/policy", + } + + if input == nil { + input = &GetDomainPermissionsPolicyInput{} + } + + output = &GetDomainPermissionsPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetDomainPermissionsPolicy API operation for CodeArtifact. +// +// Returns the resource policy attached to the specified domain. +// +// The policy is a resource-based policy, not an identity-based policy. For +// more information, see Identity-based policies and resource-based policies +// (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_identity-vs-resource.html) +// in the AWS Identity and Access Management 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 CodeArtifact's +// API operation GetDomainPermissionsPolicy for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetDomainPermissionsPolicy +func (c *CodeArtifact) GetDomainPermissionsPolicy(input *GetDomainPermissionsPolicyInput) (*GetDomainPermissionsPolicyOutput, error) { + req, out := c.GetDomainPermissionsPolicyRequest(input) + return out, req.Send() +} + +// GetDomainPermissionsPolicyWithContext is the same as GetDomainPermissionsPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetDomainPermissionsPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) GetDomainPermissionsPolicyWithContext(ctx aws.Context, input *GetDomainPermissionsPolicyInput, opts ...request.Option) (*GetDomainPermissionsPolicyOutput, error) { + req, out := c.GetDomainPermissionsPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetPackageVersionAsset = "GetPackageVersionAsset" + +// GetPackageVersionAssetRequest generates a "aws/request.Request" representing the +// client's request for the GetPackageVersionAsset operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetPackageVersionAsset for more information on using the GetPackageVersionAsset +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetPackageVersionAssetRequest method. +// req, resp := client.GetPackageVersionAssetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetPackageVersionAsset +func (c *CodeArtifact) GetPackageVersionAssetRequest(input *GetPackageVersionAssetInput) (req *request.Request, output *GetPackageVersionAssetOutput) { + op := &request.Operation{ + Name: opGetPackageVersionAsset, + HTTPMethod: "GET", + HTTPPath: "/v1/package/version/asset", + } + + if input == nil { + input = &GetPackageVersionAssetInput{} + } + + output = &GetPackageVersionAssetOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetPackageVersionAsset API operation for CodeArtifact. +// +// Returns an asset (or file) that is in a package. For example, for a Maven +// package version, use GetPackageVersionAsset to download a JAR file, a POM +// file, or any other assets in the package version. +// +// Returns awserr.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 CodeArtifact's +// API operation GetPackageVersionAsset for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetPackageVersionAsset +func (c *CodeArtifact) GetPackageVersionAsset(input *GetPackageVersionAssetInput) (*GetPackageVersionAssetOutput, error) { + req, out := c.GetPackageVersionAssetRequest(input) + return out, req.Send() +} + +// GetPackageVersionAssetWithContext is the same as GetPackageVersionAsset with the addition of +// the ability to pass a context and additional request options. +// +// See GetPackageVersionAsset for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) GetPackageVersionAssetWithContext(ctx aws.Context, input *GetPackageVersionAssetInput, opts ...request.Option) (*GetPackageVersionAssetOutput, error) { + req, out := c.GetPackageVersionAssetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetPackageVersionReadme = "GetPackageVersionReadme" + +// GetPackageVersionReadmeRequest generates a "aws/request.Request" representing the +// client's request for the GetPackageVersionReadme operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetPackageVersionReadme for more information on using the GetPackageVersionReadme +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetPackageVersionReadmeRequest method. +// req, resp := client.GetPackageVersionReadmeRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetPackageVersionReadme +func (c *CodeArtifact) GetPackageVersionReadmeRequest(input *GetPackageVersionReadmeInput) (req *request.Request, output *GetPackageVersionReadmeOutput) { + op := &request.Operation{ + Name: opGetPackageVersionReadme, + HTTPMethod: "GET", + HTTPPath: "/v1/package/version/readme", + } + + if input == nil { + input = &GetPackageVersionReadmeInput{} + } + + output = &GetPackageVersionReadmeOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetPackageVersionReadme API operation for CodeArtifact. +// +// Gets the readme file or descriptive text for a package version. For packages +// that do not contain a readme file, CodeArtifact extracts a description from +// a metadata file. For example, from the element in the pom.xml +// file of a Maven package. +// +// The returned text might contain formatting. For example, it might contain +// formatting for Markdown or reStructuredText. +// +// Returns awserr.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 CodeArtifact's +// API operation GetPackageVersionReadme for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetPackageVersionReadme +func (c *CodeArtifact) GetPackageVersionReadme(input *GetPackageVersionReadmeInput) (*GetPackageVersionReadmeOutput, error) { + req, out := c.GetPackageVersionReadmeRequest(input) + return out, req.Send() +} + +// GetPackageVersionReadmeWithContext is the same as GetPackageVersionReadme with the addition of +// the ability to pass a context and additional request options. +// +// See GetPackageVersionReadme for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) GetPackageVersionReadmeWithContext(ctx aws.Context, input *GetPackageVersionReadmeInput, opts ...request.Option) (*GetPackageVersionReadmeOutput, error) { + req, out := c.GetPackageVersionReadmeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetRepositoryEndpoint = "GetRepositoryEndpoint" + +// GetRepositoryEndpointRequest generates a "aws/request.Request" representing the +// client's request for the GetRepositoryEndpoint operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetRepositoryEndpoint for more information on using the GetRepositoryEndpoint +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetRepositoryEndpointRequest method. +// req, resp := client.GetRepositoryEndpointRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetRepositoryEndpoint +func (c *CodeArtifact) GetRepositoryEndpointRequest(input *GetRepositoryEndpointInput) (req *request.Request, output *GetRepositoryEndpointOutput) { + op := &request.Operation{ + Name: opGetRepositoryEndpoint, + HTTPMethod: "GET", + HTTPPath: "/v1/repository/endpoint", + } + + if input == nil { + input = &GetRepositoryEndpointInput{} + } + + output = &GetRepositoryEndpointOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetRepositoryEndpoint API operation for CodeArtifact. +// +// Returns the endpoint of a repository for a specific package format. A repository +// has one endpoint for each package format: +// +// * npm +// +// * pypi +// +// * maven +// +// Returns awserr.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 CodeArtifact's +// API operation GetRepositoryEndpoint for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetRepositoryEndpoint +func (c *CodeArtifact) GetRepositoryEndpoint(input *GetRepositoryEndpointInput) (*GetRepositoryEndpointOutput, error) { + req, out := c.GetRepositoryEndpointRequest(input) + return out, req.Send() +} + +// GetRepositoryEndpointWithContext is the same as GetRepositoryEndpoint with the addition of +// the ability to pass a context and additional request options. +// +// See GetRepositoryEndpoint for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) GetRepositoryEndpointWithContext(ctx aws.Context, input *GetRepositoryEndpointInput, opts ...request.Option) (*GetRepositoryEndpointOutput, error) { + req, out := c.GetRepositoryEndpointRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetRepositoryPermissionsPolicy = "GetRepositoryPermissionsPolicy" + +// GetRepositoryPermissionsPolicyRequest generates a "aws/request.Request" representing the +// client's request for the GetRepositoryPermissionsPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetRepositoryPermissionsPolicy for more information on using the GetRepositoryPermissionsPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetRepositoryPermissionsPolicyRequest method. +// req, resp := client.GetRepositoryPermissionsPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetRepositoryPermissionsPolicy +func (c *CodeArtifact) GetRepositoryPermissionsPolicyRequest(input *GetRepositoryPermissionsPolicyInput) (req *request.Request, output *GetRepositoryPermissionsPolicyOutput) { + op := &request.Operation{ + Name: opGetRepositoryPermissionsPolicy, + HTTPMethod: "GET", + HTTPPath: "/v1/repository/permissions/policy", + } + + if input == nil { + input = &GetRepositoryPermissionsPolicyInput{} + } + + output = &GetRepositoryPermissionsPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetRepositoryPermissionsPolicy API operation for CodeArtifact. +// +// Returns the resource policy that is set on a repository. +// +// Returns awserr.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 CodeArtifact's +// API operation GetRepositoryPermissionsPolicy for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/GetRepositoryPermissionsPolicy +func (c *CodeArtifact) GetRepositoryPermissionsPolicy(input *GetRepositoryPermissionsPolicyInput) (*GetRepositoryPermissionsPolicyOutput, error) { + req, out := c.GetRepositoryPermissionsPolicyRequest(input) + return out, req.Send() +} + +// GetRepositoryPermissionsPolicyWithContext is the same as GetRepositoryPermissionsPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetRepositoryPermissionsPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) GetRepositoryPermissionsPolicyWithContext(ctx aws.Context, input *GetRepositoryPermissionsPolicyInput, opts ...request.Option) (*GetRepositoryPermissionsPolicyOutput, error) { + req, out := c.GetRepositoryPermissionsPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListDomains = "ListDomains" + +// ListDomainsRequest generates a "aws/request.Request" representing the +// client's request for the ListDomains operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListDomains for more information on using the ListDomains +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListDomainsRequest method. +// req, resp := client.ListDomainsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListDomains +func (c *CodeArtifact) ListDomainsRequest(input *ListDomainsInput) (req *request.Request, output *ListDomainsOutput) { + op := &request.Operation{ + Name: opListDomains, + HTTPMethod: "POST", + HTTPPath: "/v1/domains", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListDomainsInput{} + } + + output = &ListDomainsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListDomains API operation for CodeArtifact. +// +// Returns a list of DomainSummary (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageVersionDescription.html) +// objects for all domains owned by the AWS account that makes this call. Each +// returned DomainSummary object contains information about a domain. +// +// Returns awserr.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 CodeArtifact's +// API operation ListDomains for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListDomains +func (c *CodeArtifact) ListDomains(input *ListDomainsInput) (*ListDomainsOutput, error) { + req, out := c.ListDomainsRequest(input) + 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 *CodeArtifact) 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, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListDomains 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 ListDomains operation. +// pageNum := 0 +// err := client.ListDomainsPages(params, +// func(page *codeartifact.ListDomainsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeArtifact) 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 *CodeArtifact) 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 + }, + } + + for p.Next() { + if !fn(p.Page().(*ListDomainsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListPackageVersionAssets = "ListPackageVersionAssets" + +// ListPackageVersionAssetsRequest generates a "aws/request.Request" representing the +// client's request for the ListPackageVersionAssets operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListPackageVersionAssets for more information on using the ListPackageVersionAssets +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListPackageVersionAssetsRequest method. +// req, resp := client.ListPackageVersionAssetsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListPackageVersionAssets +func (c *CodeArtifact) ListPackageVersionAssetsRequest(input *ListPackageVersionAssetsInput) (req *request.Request, output *ListPackageVersionAssetsOutput) { + op := &request.Operation{ + Name: opListPackageVersionAssets, + HTTPMethod: "POST", + HTTPPath: "/v1/package/version/assets", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListPackageVersionAssetsInput{} + } + + output = &ListPackageVersionAssetsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListPackageVersionAssets API operation for CodeArtifact. +// +// Returns a list of AssetSummary (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_AssetSummary.html) +// objects for assets in a package version. +// +// Returns awserr.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 CodeArtifact's +// API operation ListPackageVersionAssets for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListPackageVersionAssets +func (c *CodeArtifact) ListPackageVersionAssets(input *ListPackageVersionAssetsInput) (*ListPackageVersionAssetsOutput, error) { + req, out := c.ListPackageVersionAssetsRequest(input) + return out, req.Send() +} + +// ListPackageVersionAssetsWithContext is the same as ListPackageVersionAssets with the addition of +// the ability to pass a context and additional request options. +// +// See ListPackageVersionAssets for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) ListPackageVersionAssetsWithContext(ctx aws.Context, input *ListPackageVersionAssetsInput, opts ...request.Option) (*ListPackageVersionAssetsOutput, error) { + req, out := c.ListPackageVersionAssetsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListPackageVersionAssetsPages iterates over the pages of a ListPackageVersionAssets operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListPackageVersionAssets 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 ListPackageVersionAssets operation. +// pageNum := 0 +// err := client.ListPackageVersionAssetsPages(params, +// func(page *codeartifact.ListPackageVersionAssetsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeArtifact) ListPackageVersionAssetsPages(input *ListPackageVersionAssetsInput, fn func(*ListPackageVersionAssetsOutput, bool) bool) error { + return c.ListPackageVersionAssetsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPackageVersionAssetsPagesWithContext same as ListPackageVersionAssetsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) ListPackageVersionAssetsPagesWithContext(ctx aws.Context, input *ListPackageVersionAssetsInput, fn func(*ListPackageVersionAssetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPackageVersionAssetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPackageVersionAssetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListPackageVersionAssetsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListPackageVersionDependencies = "ListPackageVersionDependencies" + +// ListPackageVersionDependenciesRequest generates a "aws/request.Request" representing the +// client's request for the ListPackageVersionDependencies operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListPackageVersionDependencies for more information on using the ListPackageVersionDependencies +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListPackageVersionDependenciesRequest method. +// req, resp := client.ListPackageVersionDependenciesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListPackageVersionDependencies +func (c *CodeArtifact) ListPackageVersionDependenciesRequest(input *ListPackageVersionDependenciesInput) (req *request.Request, output *ListPackageVersionDependenciesOutput) { + op := &request.Operation{ + Name: opListPackageVersionDependencies, + HTTPMethod: "POST", + HTTPPath: "/v1/package/version/dependencies", + } + + if input == nil { + input = &ListPackageVersionDependenciesInput{} + } + + output = &ListPackageVersionDependenciesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListPackageVersionDependencies API operation for CodeArtifact. +// +// Returns the direct dependencies for a package version. The dependencies are +// returned as PackageDependency (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageDependency.html) +// objects. CodeArtifact extracts the dependencies for a package version from +// the metadata file for the package format (for example, the package.json file +// for npm packages and the pom.xml file for Maven). Any package version dependencies +// that are not listed in the configuration file are not returned. +// +// Returns awserr.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 CodeArtifact's +// API operation ListPackageVersionDependencies for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListPackageVersionDependencies +func (c *CodeArtifact) ListPackageVersionDependencies(input *ListPackageVersionDependenciesInput) (*ListPackageVersionDependenciesOutput, error) { + req, out := c.ListPackageVersionDependenciesRequest(input) + return out, req.Send() +} + +// ListPackageVersionDependenciesWithContext is the same as ListPackageVersionDependencies with the addition of +// the ability to pass a context and additional request options. +// +// See ListPackageVersionDependencies for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) ListPackageVersionDependenciesWithContext(ctx aws.Context, input *ListPackageVersionDependenciesInput, opts ...request.Option) (*ListPackageVersionDependenciesOutput, error) { + req, out := c.ListPackageVersionDependenciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListPackageVersions = "ListPackageVersions" + +// ListPackageVersionsRequest generates a "aws/request.Request" representing the +// client's request for the ListPackageVersions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListPackageVersions for more information on using the ListPackageVersions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListPackageVersionsRequest method. +// req, resp := client.ListPackageVersionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListPackageVersions +func (c *CodeArtifact) ListPackageVersionsRequest(input *ListPackageVersionsInput) (req *request.Request, output *ListPackageVersionsOutput) { + op := &request.Operation{ + Name: opListPackageVersions, + HTTPMethod: "POST", + HTTPPath: "/v1/package/versions", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListPackageVersionsInput{} + } + + output = &ListPackageVersionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListPackageVersions API operation for CodeArtifact. +// +// Returns a list of PackageVersionSummary (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageVersionSummary.html) +// objects for package versions in a repository that match the request parameters. +// +// Returns awserr.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 CodeArtifact's +// API operation ListPackageVersions for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListPackageVersions +func (c *CodeArtifact) ListPackageVersions(input *ListPackageVersionsInput) (*ListPackageVersionsOutput, error) { + req, out := c.ListPackageVersionsRequest(input) + return out, req.Send() +} + +// ListPackageVersionsWithContext is the same as ListPackageVersions with the addition of +// the ability to pass a context and additional request options. +// +// See ListPackageVersions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) ListPackageVersionsWithContext(ctx aws.Context, input *ListPackageVersionsInput, opts ...request.Option) (*ListPackageVersionsOutput, error) { + req, out := c.ListPackageVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListPackageVersionsPages iterates over the pages of a ListPackageVersions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListPackageVersions 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 ListPackageVersions operation. +// pageNum := 0 +// err := client.ListPackageVersionsPages(params, +// func(page *codeartifact.ListPackageVersionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeArtifact) ListPackageVersionsPages(input *ListPackageVersionsInput, fn func(*ListPackageVersionsOutput, bool) bool) error { + return c.ListPackageVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPackageVersionsPagesWithContext same as ListPackageVersionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) ListPackageVersionsPagesWithContext(ctx aws.Context, input *ListPackageVersionsInput, fn func(*ListPackageVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPackageVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPackageVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListPackageVersionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListPackages = "ListPackages" + +// ListPackagesRequest generates a "aws/request.Request" representing the +// client's request for the ListPackages operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListPackages for more information on using the ListPackages +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListPackagesRequest method. +// req, resp := client.ListPackagesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListPackages +func (c *CodeArtifact) ListPackagesRequest(input *ListPackagesInput) (req *request.Request, output *ListPackagesOutput) { + op := &request.Operation{ + Name: opListPackages, + HTTPMethod: "POST", + HTTPPath: "/v1/packages", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListPackagesInput{} + } + + output = &ListPackagesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListPackages API operation for CodeArtifact. +// +// Returns a list of PackageSummary (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageSummary.html) +// objects for packages in a repository that match the request parameters. +// +// Returns awserr.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 CodeArtifact's +// API operation ListPackages for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListPackages +func (c *CodeArtifact) ListPackages(input *ListPackagesInput) (*ListPackagesOutput, error) { + req, out := c.ListPackagesRequest(input) + return out, req.Send() +} + +// ListPackagesWithContext is the same as ListPackages with the addition of +// the ability to pass a context and additional request options. +// +// See ListPackages for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) ListPackagesWithContext(ctx aws.Context, input *ListPackagesInput, opts ...request.Option) (*ListPackagesOutput, error) { + req, out := c.ListPackagesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListPackagesPages iterates over the pages of a ListPackages operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListPackages 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 ListPackages operation. +// pageNum := 0 +// err := client.ListPackagesPages(params, +// func(page *codeartifact.ListPackagesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeArtifact) ListPackagesPages(input *ListPackagesInput, fn func(*ListPackagesOutput, bool) bool) error { + return c.ListPackagesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPackagesPagesWithContext same as ListPackagesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) ListPackagesPagesWithContext(ctx aws.Context, input *ListPackagesInput, fn func(*ListPackagesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPackagesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPackagesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListPackagesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListRepositories = "ListRepositories" + +// ListRepositoriesRequest generates a "aws/request.Request" representing the +// client's request for the ListRepositories operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListRepositories for more information on using the ListRepositories +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListRepositoriesRequest method. +// req, resp := client.ListRepositoriesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListRepositories +func (c *CodeArtifact) ListRepositoriesRequest(input *ListRepositoriesInput) (req *request.Request, output *ListRepositoriesOutput) { + op := &request.Operation{ + Name: opListRepositories, + HTTPMethod: "POST", + HTTPPath: "/v1/repositories", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListRepositoriesInput{} + } + + output = &ListRepositoriesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListRepositories API operation for CodeArtifact. +// +// Returns a list of RepositorySummary (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_RepositorySummary.html) +// objects. Each RepositorySummary contains information about a repository in +// the specified AWS account and that matches the input parameters. +// +// Returns awserr.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 CodeArtifact's +// API operation ListRepositories for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListRepositories +func (c *CodeArtifact) ListRepositories(input *ListRepositoriesInput) (*ListRepositoriesOutput, error) { + req, out := c.ListRepositoriesRequest(input) + 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 *CodeArtifact) 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, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListRepositories 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 ListRepositories operation. +// pageNum := 0 +// err := client.ListRepositoriesPages(params, +// func(page *codeartifact.ListRepositoriesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeArtifact) 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 *CodeArtifact) 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 + }, + } + + for p.Next() { + if !fn(p.Page().(*ListRepositoriesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListRepositoriesInDomain = "ListRepositoriesInDomain" + +// ListRepositoriesInDomainRequest generates a "aws/request.Request" representing the +// client's request for the ListRepositoriesInDomain operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListRepositoriesInDomain for more information on using the ListRepositoriesInDomain +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListRepositoriesInDomainRequest method. +// req, resp := client.ListRepositoriesInDomainRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListRepositoriesInDomain +func (c *CodeArtifact) ListRepositoriesInDomainRequest(input *ListRepositoriesInDomainInput) (req *request.Request, output *ListRepositoriesInDomainOutput) { + op := &request.Operation{ + Name: opListRepositoriesInDomain, + HTTPMethod: "POST", + HTTPPath: "/v1/domain/repositories", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListRepositoriesInDomainInput{} + } + + output = &ListRepositoriesInDomainOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListRepositoriesInDomain API operation for CodeArtifact. +// +// Returns a list of RepositorySummary (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_RepositorySummary.html) +// objects. Each RepositorySummary contains information about a repository in +// the specified domain and that matches the input parameters. +// +// Returns awserr.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 CodeArtifact's +// API operation ListRepositoriesInDomain for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/ListRepositoriesInDomain +func (c *CodeArtifact) ListRepositoriesInDomain(input *ListRepositoriesInDomainInput) (*ListRepositoriesInDomainOutput, error) { + req, out := c.ListRepositoriesInDomainRequest(input) + return out, req.Send() +} + +// ListRepositoriesInDomainWithContext is the same as ListRepositoriesInDomain with the addition of +// the ability to pass a context and additional request options. +// +// See ListRepositoriesInDomain for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) ListRepositoriesInDomainWithContext(ctx aws.Context, input *ListRepositoriesInDomainInput, opts ...request.Option) (*ListRepositoriesInDomainOutput, error) { + req, out := c.ListRepositoriesInDomainRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListRepositoriesInDomainPages iterates over the pages of a ListRepositoriesInDomain operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListRepositoriesInDomain 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 ListRepositoriesInDomain operation. +// pageNum := 0 +// err := client.ListRepositoriesInDomainPages(params, +// func(page *codeartifact.ListRepositoriesInDomainOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeArtifact) ListRepositoriesInDomainPages(input *ListRepositoriesInDomainInput, fn func(*ListRepositoriesInDomainOutput, bool) bool) error { + return c.ListRepositoriesInDomainPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListRepositoriesInDomainPagesWithContext same as ListRepositoriesInDomainPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) ListRepositoriesInDomainPagesWithContext(ctx aws.Context, input *ListRepositoriesInDomainInput, fn func(*ListRepositoriesInDomainOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListRepositoriesInDomainInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListRepositoriesInDomainRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListRepositoriesInDomainOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opPutDomainPermissionsPolicy = "PutDomainPermissionsPolicy" + +// PutDomainPermissionsPolicyRequest generates a "aws/request.Request" representing the +// client's request for the PutDomainPermissionsPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutDomainPermissionsPolicy for more information on using the PutDomainPermissionsPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutDomainPermissionsPolicyRequest method. +// req, resp := client.PutDomainPermissionsPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/PutDomainPermissionsPolicy +func (c *CodeArtifact) PutDomainPermissionsPolicyRequest(input *PutDomainPermissionsPolicyInput) (req *request.Request, output *PutDomainPermissionsPolicyOutput) { + op := &request.Operation{ + Name: opPutDomainPermissionsPolicy, + HTTPMethod: "PUT", + HTTPPath: "/v1/domain/permissions/policy", + } + + if input == nil { + input = &PutDomainPermissionsPolicyInput{} + } + + output = &PutDomainPermissionsPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// PutDomainPermissionsPolicy API operation for CodeArtifact. +// +// Sets a resource policy on a domain that specifies permissions to access it. +// +// Returns awserr.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 CodeArtifact's +// API operation PutDomainPermissionsPolicy for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ServiceQuotaExceededException +// The operation did not succeed because it would have exceeded a service limit +// for your account. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/PutDomainPermissionsPolicy +func (c *CodeArtifact) PutDomainPermissionsPolicy(input *PutDomainPermissionsPolicyInput) (*PutDomainPermissionsPolicyOutput, error) { + req, out := c.PutDomainPermissionsPolicyRequest(input) + return out, req.Send() +} + +// PutDomainPermissionsPolicyWithContext is the same as PutDomainPermissionsPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutDomainPermissionsPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) PutDomainPermissionsPolicyWithContext(ctx aws.Context, input *PutDomainPermissionsPolicyInput, opts ...request.Option) (*PutDomainPermissionsPolicyOutput, error) { + req, out := c.PutDomainPermissionsPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opPutRepositoryPermissionsPolicy = "PutRepositoryPermissionsPolicy" + +// PutRepositoryPermissionsPolicyRequest generates a "aws/request.Request" representing the +// client's request for the PutRepositoryPermissionsPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutRepositoryPermissionsPolicy for more information on using the PutRepositoryPermissionsPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutRepositoryPermissionsPolicyRequest method. +// req, resp := client.PutRepositoryPermissionsPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/PutRepositoryPermissionsPolicy +func (c *CodeArtifact) PutRepositoryPermissionsPolicyRequest(input *PutRepositoryPermissionsPolicyInput) (req *request.Request, output *PutRepositoryPermissionsPolicyOutput) { + op := &request.Operation{ + Name: opPutRepositoryPermissionsPolicy, + HTTPMethod: "PUT", + HTTPPath: "/v1/repository/permissions/policy", + } + + if input == nil { + input = &PutRepositoryPermissionsPolicyInput{} + } + + output = &PutRepositoryPermissionsPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// PutRepositoryPermissionsPolicy API operation for CodeArtifact. +// +// Sets the resource policy on a repository that specifies permissions to access +// it. +// +// Returns awserr.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 CodeArtifact's +// API operation PutRepositoryPermissionsPolicy for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ServiceQuotaExceededException +// The operation did not succeed because it would have exceeded a service limit +// for your account. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/PutRepositoryPermissionsPolicy +func (c *CodeArtifact) PutRepositoryPermissionsPolicy(input *PutRepositoryPermissionsPolicyInput) (*PutRepositoryPermissionsPolicyOutput, error) { + req, out := c.PutRepositoryPermissionsPolicyRequest(input) + return out, req.Send() +} + +// PutRepositoryPermissionsPolicyWithContext is the same as PutRepositoryPermissionsPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutRepositoryPermissionsPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) PutRepositoryPermissionsPolicyWithContext(ctx aws.Context, input *PutRepositoryPermissionsPolicyInput, opts ...request.Option) (*PutRepositoryPermissionsPolicyOutput, error) { + req, out := c.PutRepositoryPermissionsPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdatePackageVersionsStatus = "UpdatePackageVersionsStatus" + +// UpdatePackageVersionsStatusRequest generates a "aws/request.Request" representing the +// client's request for the UpdatePackageVersionsStatus operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdatePackageVersionsStatus for more information on using the UpdatePackageVersionsStatus +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdatePackageVersionsStatusRequest method. +// req, resp := client.UpdatePackageVersionsStatusRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/UpdatePackageVersionsStatus +func (c *CodeArtifact) UpdatePackageVersionsStatusRequest(input *UpdatePackageVersionsStatusInput) (req *request.Request, output *UpdatePackageVersionsStatusOutput) { + op := &request.Operation{ + Name: opUpdatePackageVersionsStatus, + HTTPMethod: "POST", + HTTPPath: "/v1/package/versions/update_status", + } + + if input == nil { + input = &UpdatePackageVersionsStatusInput{} + } + + output = &UpdatePackageVersionsStatusOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdatePackageVersionsStatus API operation for CodeArtifact. +// +// Updates the status of one or more versions of a package. +// +// Returns awserr.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 CodeArtifact's +// API operation UpdatePackageVersionsStatus for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/UpdatePackageVersionsStatus +func (c *CodeArtifact) UpdatePackageVersionsStatus(input *UpdatePackageVersionsStatusInput) (*UpdatePackageVersionsStatusOutput, error) { + req, out := c.UpdatePackageVersionsStatusRequest(input) + return out, req.Send() +} + +// UpdatePackageVersionsStatusWithContext is the same as UpdatePackageVersionsStatus with the addition of +// the ability to pass a context and additional request options. +// +// See UpdatePackageVersionsStatus for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) UpdatePackageVersionsStatusWithContext(ctx aws.Context, input *UpdatePackageVersionsStatusInput, opts ...request.Option) (*UpdatePackageVersionsStatusOutput, error) { + req, out := c.UpdatePackageVersionsStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateRepository = "UpdateRepository" + +// UpdateRepositoryRequest generates a "aws/request.Request" representing the +// client's request for the UpdateRepository operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateRepository for more information on using the UpdateRepository +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateRepositoryRequest method. +// req, resp := client.UpdateRepositoryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/UpdateRepository +func (c *CodeArtifact) UpdateRepositoryRequest(input *UpdateRepositoryInput) (req *request.Request, output *UpdateRepositoryOutput) { + op := &request.Operation{ + Name: opUpdateRepository, + HTTPMethod: "PUT", + HTTPPath: "/v1/repository", + } + + if input == nil { + input = &UpdateRepositoryInput{} + } + + output = &UpdateRepositoryOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateRepository API operation for CodeArtifact. +// +// Update the properties of a repository. +// +// Returns awserr.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 CodeArtifact's +// API operation UpdateRepository for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// The operation did not succeed because of an unauthorized access attempt. +// +// * ConflictException +// The operation did not succeed because prerequisites are not met. +// +// * InternalServerException +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +// +// * ResourceNotFoundException +// The operation did not succeed because the resource requested is not found +// in the service. +// +// * ServiceQuotaExceededException +// The operation did not succeed because it would have exceeded a service limit +// for your account. +// +// * ThrottlingException +// The operation did not succeed because too many requests are sent to the service. +// +// * ValidationException +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22/UpdateRepository +func (c *CodeArtifact) UpdateRepository(input *UpdateRepositoryInput) (*UpdateRepositoryOutput, error) { + req, out := c.UpdateRepositoryRequest(input) + return out, req.Send() +} + +// UpdateRepositoryWithContext is the same as UpdateRepository with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRepository for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *CodeArtifact) UpdateRepositoryWithContext(ctx aws.Context, input *UpdateRepositoryInput, opts ...request.Option) (*UpdateRepositoryOutput, error) { + req, out := c.UpdateRepositoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// The operation did not succeed because of an unauthorized access attempt. +type AccessDeniedException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s AccessDeniedException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccessDeniedException) GoString() string { + return s.String() +} + +func newErrorAccessDeniedException(v protocol.ResponseMetadata) error { + return &AccessDeniedException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *AccessDeniedException) Code() string { + return "AccessDeniedException" +} + +// Message returns the exception's message. +func (s *AccessDeniedException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *AccessDeniedException) OrigErr() error { + return nil +} + +func (s *AccessDeniedException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *AccessDeniedException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *AccessDeniedException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Contains details about a package version asset. +type AssetSummary struct { + _ struct{} `type:"structure"` + + // The hashes of the asset. + Hashes map[string]*string `locationName:"hashes" type:"map"` + + // The name of the asset. + // + // Name is a required field + Name *string `locationName:"name" min:"1" type:"string" required:"true"` + + // The size of the asset. + Size *int64 `locationName:"size" type:"long"` +} + +// String returns the string representation +func (s AssetSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssetSummary) GoString() string { + return s.String() +} + +// SetHashes sets the Hashes field's value. +func (s *AssetSummary) SetHashes(v map[string]*string) *AssetSummary { + s.Hashes = v + return s +} + +// SetName sets the Name field's value. +func (s *AssetSummary) SetName(v string) *AssetSummary { + s.Name = &v + return s +} + +// SetSize sets the Size field's value. +func (s *AssetSummary) SetSize(v int64) *AssetSummary { + s.Size = &v + return s +} + +type AssociateExternalConnectionInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the repository. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The name of the external connection to add to the repository. The following + // values are supported: + // + // * public:npmjs - for the npm public repository. + // + // * public:pypi - for the Python Package Index. + // + // * public:maven-central - for Maven Central. + // + // * public:maven-googleandroid - for the Google Android repository. + // + // * public:maven-gradleplugins - for the Gradle plugins repository. + // + // * public:maven-commonsware - for the CommonsWare Android repository. + // + // ExternalConnection is a required field + ExternalConnection *string `location:"querystring" locationName:"external-connection" type:"string" required:"true"` + + // The name of the repository to which the external connection is added. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s AssociateExternalConnectionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateExternalConnectionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AssociateExternalConnectionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AssociateExternalConnectionInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.ExternalConnection == nil { + invalidParams.Add(request.NewErrParamRequired("ExternalConnection")) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *AssociateExternalConnectionInput) SetDomain(v string) *AssociateExternalConnectionInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *AssociateExternalConnectionInput) SetDomainOwner(v string) *AssociateExternalConnectionInput { + s.DomainOwner = &v + return s +} + +// SetExternalConnection sets the ExternalConnection field's value. +func (s *AssociateExternalConnectionInput) SetExternalConnection(v string) *AssociateExternalConnectionInput { + s.ExternalConnection = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *AssociateExternalConnectionInput) SetRepository(v string) *AssociateExternalConnectionInput { + s.Repository = &v + return s +} + +type AssociateExternalConnectionOutput struct { + _ struct{} `type:"structure"` + + // Information about the connected repository after processing the request. + Repository *RepositoryDescription `locationName:"repository" type:"structure"` +} + +// String returns the string representation +func (s AssociateExternalConnectionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateExternalConnectionOutput) GoString() string { + return s.String() +} + +// SetRepository sets the Repository field's value. +func (s *AssociateExternalConnectionOutput) SetRepository(v *RepositoryDescription) *AssociateExternalConnectionOutput { + s.Repository = v + return s +} + +// The operation did not succeed because prerequisites are not met. +type ConflictException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` + + // The ID of the resource. + ResourceId *string `locationName:"resourceId" type:"string"` + + // The type of AWS resource. + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` +} + +// String returns the string representation +func (s ConflictException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ConflictException) GoString() string { + return s.String() +} + +func newErrorConflictException(v protocol.ResponseMetadata) error { + return &ConflictException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ConflictException) Code() string { + return "ConflictException" +} + +// Message returns the exception's message. +func (s *ConflictException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ConflictException) OrigErr() error { + return nil +} + +func (s *ConflictException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ConflictException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ConflictException) RequestID() string { + return s.RespMetadata.RequestID +} + +type CopyPackageVersionsInput struct { + _ struct{} `type:"structure"` + + // Set to true to overwrite a package version that already exists in the destination + // repository. If set to false and the package version already exists in the + // destination repository, the package version is returned in the failedVersions + // field of the response with an ALREADY_EXISTS error code. + AllowOverwrite *bool `locationName:"allowOverwrite" type:"boolean"` + + // The name of the repository into which package versions are copied. + // + // DestinationRepository is a required field + DestinationRepository *string `location:"querystring" locationName:"destination-repository" min:"2" type:"string" required:"true"` + + // The name of the domain that contains the source and destination repositories. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The format of the package that is copied. The valid package types are: + // + // * npm: A Node Package Manager (npm) package. + // + // * pypi: A Python Package Index (PyPI) package. + // + // * maven: A Maven package that contains compiled code in a distributable + // format, such as a JAR file. + // + // Format is a required field + Format *string `location:"querystring" locationName:"format" type:"string" required:"true" enum:"PackageFormat"` + + // Set to true to copy packages from repositories that are upstream from the + // source repository to the destination repository. The default setting is false. + // For more information, see Working with upstream repositories (https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html). + IncludeFromUpstream *bool `locationName:"includeFromUpstream" type:"boolean"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `location:"querystring" locationName:"namespace" min:"1" type:"string"` + + // The name of the package that is copied. + // + // Package is a required field + Package *string `location:"querystring" locationName:"package" min:"1" type:"string" required:"true"` + + // The name of the repository that contains the package versions to copy. + // + // SourceRepository is a required field + SourceRepository *string `location:"querystring" locationName:"source-repository" min:"2" type:"string" required:"true"` + + // A list of key-value pairs. The keys are package versions and the values are + // package version revisions. A CopyPackageVersion operation succeeds if the + // specified versions in the source repository match the specified package version + // revision. + // + // You must specify versions or versionRevisions. You cannot specify both. + VersionRevisions map[string]*string `locationName:"versionRevisions" type:"map"` + + // The versions of the package to copy. + // + // You must specify versions or versionRevisions. You cannot specify both. + Versions []*string `locationName:"versions" type:"list"` +} + +// String returns the string representation +func (s CopyPackageVersionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CopyPackageVersionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CopyPackageVersionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CopyPackageVersionsInput"} + if s.DestinationRepository == nil { + invalidParams.Add(request.NewErrParamRequired("DestinationRepository")) + } + if s.DestinationRepository != nil && len(*s.DestinationRepository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("DestinationRepository", 2)) + } + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.Package == nil { + invalidParams.Add(request.NewErrParamRequired("Package")) + } + if s.Package != nil && len(*s.Package) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Package", 1)) + } + if s.SourceRepository == nil { + invalidParams.Add(request.NewErrParamRequired("SourceRepository")) + } + if s.SourceRepository != nil && len(*s.SourceRepository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("SourceRepository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAllowOverwrite sets the AllowOverwrite field's value. +func (s *CopyPackageVersionsInput) SetAllowOverwrite(v bool) *CopyPackageVersionsInput { + s.AllowOverwrite = &v + return s +} + +// SetDestinationRepository sets the DestinationRepository field's value. +func (s *CopyPackageVersionsInput) SetDestinationRepository(v string) *CopyPackageVersionsInput { + s.DestinationRepository = &v + return s +} + +// SetDomain sets the Domain field's value. +func (s *CopyPackageVersionsInput) SetDomain(v string) *CopyPackageVersionsInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *CopyPackageVersionsInput) SetDomainOwner(v string) *CopyPackageVersionsInput { + s.DomainOwner = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *CopyPackageVersionsInput) SetFormat(v string) *CopyPackageVersionsInput { + s.Format = &v + return s +} + +// SetIncludeFromUpstream sets the IncludeFromUpstream field's value. +func (s *CopyPackageVersionsInput) SetIncludeFromUpstream(v bool) *CopyPackageVersionsInput { + s.IncludeFromUpstream = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *CopyPackageVersionsInput) SetNamespace(v string) *CopyPackageVersionsInput { + s.Namespace = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *CopyPackageVersionsInput) SetPackage(v string) *CopyPackageVersionsInput { + s.Package = &v + return s +} + +// SetSourceRepository sets the SourceRepository field's value. +func (s *CopyPackageVersionsInput) SetSourceRepository(v string) *CopyPackageVersionsInput { + s.SourceRepository = &v + return s +} + +// SetVersionRevisions sets the VersionRevisions field's value. +func (s *CopyPackageVersionsInput) SetVersionRevisions(v map[string]*string) *CopyPackageVersionsInput { + s.VersionRevisions = v + return s +} + +// SetVersions sets the Versions field's value. +func (s *CopyPackageVersionsInput) SetVersions(v []*string) *CopyPackageVersionsInput { + s.Versions = v + return s +} + +type CopyPackageVersionsOutput struct { + _ struct{} `type:"structure"` + + // A map of package versions that failed to copy and their error codes. The + // possible error codes are in the PackageVersionError data type. They are: + // + // * ALREADY_EXISTS + // + // * MISMATCHED_REVISION + // + // * MISMATCHED_STATUS + // + // * NOT_ALLOWED + // + // * NOT_FOUND + // + // * SKIPPED + FailedVersions map[string]*PackageVersionError `locationName:"failedVersions" type:"map"` + + // A list of the package versions that were successfully copied to your repository. + SuccessfulVersions map[string]*SuccessfulPackageVersionInfo `locationName:"successfulVersions" type:"map"` +} + +// String returns the string representation +func (s CopyPackageVersionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CopyPackageVersionsOutput) GoString() string { + return s.String() +} + +// SetFailedVersions sets the FailedVersions field's value. +func (s *CopyPackageVersionsOutput) SetFailedVersions(v map[string]*PackageVersionError) *CopyPackageVersionsOutput { + s.FailedVersions = v + return s +} + +// SetSuccessfulVersions sets the SuccessfulVersions field's value. +func (s *CopyPackageVersionsOutput) SetSuccessfulVersions(v map[string]*SuccessfulPackageVersionInfo) *CopyPackageVersionsOutput { + s.SuccessfulVersions = v + return s +} + +type CreateDomainInput struct { + _ struct{} `type:"structure"` + + // The name of the domain to create. All domain names in an AWS Region that + // are in the same AWS account must be unique. The domain name is used as the + // prefix in DNS hostnames. Do not use sensitive information in a domain name + // because it is publicly discoverable. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The encryption key for the domain. This is used to encrypt content stored + // in a domain. An encryption key can be a key ID, a key Amazon Resource Name + // (ARN), a key alias, or a key alias ARN. To specify an encryptionKey, your + // IAM role must have kms:DescribeKey and kms:CreateGrant permissions on the + // encryption key that is used. For more information, see DescribeKey (https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestSyntax) + // in the AWS Key Management Service API Reference and AWS KMS API Permissions + // Reference (https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html) + // in the AWS Key Management Service Developer Guide. + // + // CodeArtifact supports only symmetric CMKs. Do not associate an asymmetric + // CMK with your domain. For more information, see Using symmetric and asymmetric + // keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) + // in the AWS Key Management Service Developer Guide. + EncryptionKey *string `locationName:"encryptionKey" min:"1" type:"string"` +} + +// String returns the string representation +func (s CreateDomainInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDomainInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateDomainInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDomainInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.EncryptionKey != nil && len(*s.EncryptionKey) < 1 { + invalidParams.Add(request.NewErrParamMinLen("EncryptionKey", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *CreateDomainInput) SetDomain(v string) *CreateDomainInput { + s.Domain = &v + return s +} + +// SetEncryptionKey sets the EncryptionKey field's value. +func (s *CreateDomainInput) SetEncryptionKey(v string) *CreateDomainInput { + s.EncryptionKey = &v + return s +} + +type CreateDomainOutput struct { + _ struct{} `type:"structure"` + + // Contains information about the created domain after processing the request. + Domain *DomainDescription `locationName:"domain" type:"structure"` +} + +// String returns the string representation +func (s CreateDomainOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDomainOutput) GoString() string { + return s.String() +} + +// SetDomain sets the Domain field's value. +func (s *CreateDomainOutput) SetDomain(v *DomainDescription) *CreateDomainOutput { + s.Domain = v + return s +} + +type CreateRepositoryInput struct { + _ struct{} `type:"structure"` + + // A description of the created repository. + Description *string `locationName:"description" type:"string"` + + // The domain that contains the created repository. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The name of the repository to create. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` + + // A list of upstream repositories to associate with the repository. The order + // of the upstream repositories in the list determines their priority order + // when AWS CodeArtifact looks for a requested package version. For more information, + // see Working with upstream repositories (https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html). + Upstreams []*UpstreamRepository `locationName:"upstreams" type:"list"` +} + +// String returns the string representation +func (s CreateRepositoryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateRepositoryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateRepositoryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateRepositoryInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + if s.Upstreams != nil { + for i, v := range s.Upstreams { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Upstreams", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *CreateRepositoryInput) SetDescription(v string) *CreateRepositoryInput { + s.Description = &v + return s +} + +// SetDomain sets the Domain field's value. +func (s *CreateRepositoryInput) SetDomain(v string) *CreateRepositoryInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *CreateRepositoryInput) SetDomainOwner(v string) *CreateRepositoryInput { + s.DomainOwner = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *CreateRepositoryInput) SetRepository(v string) *CreateRepositoryInput { + s.Repository = &v + return s +} + +// SetUpstreams sets the Upstreams field's value. +func (s *CreateRepositoryInput) SetUpstreams(v []*UpstreamRepository) *CreateRepositoryInput { + s.Upstreams = v + return s +} + +type CreateRepositoryOutput struct { + _ struct{} `type:"structure"` + + // Information about the created repository after processing the request. + Repository *RepositoryDescription `locationName:"repository" type:"structure"` +} + +// String returns the string representation +func (s CreateRepositoryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateRepositoryOutput) GoString() string { + return s.String() +} + +// SetRepository sets the Repository field's value. +func (s *CreateRepositoryOutput) SetRepository(v *RepositoryDescription) *CreateRepositoryOutput { + s.Repository = v + return s +} + +type DeleteDomainInput struct { + _ struct{} `type:"structure"` + + // The name of the domain to delete. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` +} + +// String returns the string representation +func (s DeleteDomainInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDomainInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteDomainInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDomainInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *DeleteDomainInput) SetDomain(v string) *DeleteDomainInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *DeleteDomainInput) SetDomainOwner(v string) *DeleteDomainInput { + s.DomainOwner = &v + return s +} + +type DeleteDomainOutput struct { + _ struct{} `type:"structure"` + + // Contains information about the deleted domain after processing the request. + Domain *DomainDescription `locationName:"domain" type:"structure"` +} + +// String returns the string representation +func (s DeleteDomainOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDomainOutput) GoString() string { + return s.String() +} + +// SetDomain sets the Domain field's value. +func (s *DeleteDomainOutput) SetDomain(v *DomainDescription) *DeleteDomainOutput { + s.Domain = v + return s +} + +type DeleteDomainPermissionsPolicyInput struct { + _ struct{} `type:"structure"` + + // The name of the domain associated with the resource policy to be deleted. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The current revision of the resource policy to be deleted. This revision + // is used for optimistic locking, which prevents others from overwriting your + // changes to the domain's resource policy. + PolicyRevision *string `location:"querystring" locationName:"policy-revision" min:"1" type:"string"` +} + +// String returns the string representation +func (s DeleteDomainPermissionsPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDomainPermissionsPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteDomainPermissionsPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDomainPermissionsPolicyInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.PolicyRevision != nil && len(*s.PolicyRevision) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PolicyRevision", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *DeleteDomainPermissionsPolicyInput) SetDomain(v string) *DeleteDomainPermissionsPolicyInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *DeleteDomainPermissionsPolicyInput) SetDomainOwner(v string) *DeleteDomainPermissionsPolicyInput { + s.DomainOwner = &v + return s +} + +// SetPolicyRevision sets the PolicyRevision field's value. +func (s *DeleteDomainPermissionsPolicyInput) SetPolicyRevision(v string) *DeleteDomainPermissionsPolicyInput { + s.PolicyRevision = &v + return s +} + +type DeleteDomainPermissionsPolicyOutput struct { + _ struct{} `type:"structure"` + + // Information about the deleted resource policy after processing the request. + Policy *ResourcePolicy `locationName:"policy" type:"structure"` +} + +// String returns the string representation +func (s DeleteDomainPermissionsPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDomainPermissionsPolicyOutput) GoString() string { + return s.String() +} + +// SetPolicy sets the Policy field's value. +func (s *DeleteDomainPermissionsPolicyOutput) SetPolicy(v *ResourcePolicy) *DeleteDomainPermissionsPolicyOutput { + s.Policy = v + return s +} + +type DeletePackageVersionsInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the package to delete. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The expected status of the package version to delete. Valid values are: + // + // * Published + // + // * Unfinished + // + // * Unlisted + // + // * Archived + // + // * Disposed + ExpectedStatus *string `locationName:"expectedStatus" type:"string" enum:"PackageVersionStatus"` + + // The format of the package versions to delete. The valid values are: + // + // * npm + // + // * pypi + // + // * maven + // + // Format is a required field + Format *string `location:"querystring" locationName:"format" type:"string" required:"true" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `location:"querystring" locationName:"namespace" min:"1" type:"string"` + + // The name of the package with the versions to delete. + // + // Package is a required field + Package *string `location:"querystring" locationName:"package" min:"1" type:"string" required:"true"` + + // The name of the repository that contains the package versions to delete. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` + + // An array of strings that specify the versions of the package to delete. + // + // Versions is a required field + Versions []*string `locationName:"versions" type:"list" required:"true"` +} + +// String returns the string representation +func (s DeletePackageVersionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeletePackageVersionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeletePackageVersionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeletePackageVersionsInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.Package == nil { + invalidParams.Add(request.NewErrParamRequired("Package")) + } + if s.Package != nil && len(*s.Package) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Package", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + if s.Versions == nil { + invalidParams.Add(request.NewErrParamRequired("Versions")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *DeletePackageVersionsInput) SetDomain(v string) *DeletePackageVersionsInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *DeletePackageVersionsInput) SetDomainOwner(v string) *DeletePackageVersionsInput { + s.DomainOwner = &v + return s +} + +// SetExpectedStatus sets the ExpectedStatus field's value. +func (s *DeletePackageVersionsInput) SetExpectedStatus(v string) *DeletePackageVersionsInput { + s.ExpectedStatus = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *DeletePackageVersionsInput) SetFormat(v string) *DeletePackageVersionsInput { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *DeletePackageVersionsInput) SetNamespace(v string) *DeletePackageVersionsInput { + s.Namespace = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *DeletePackageVersionsInput) SetPackage(v string) *DeletePackageVersionsInput { + s.Package = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *DeletePackageVersionsInput) SetRepository(v string) *DeletePackageVersionsInput { + s.Repository = &v + return s +} + +// SetVersions sets the Versions field's value. +func (s *DeletePackageVersionsInput) SetVersions(v []*string) *DeletePackageVersionsInput { + s.Versions = v + return s +} + +type DeletePackageVersionsOutput struct { + _ struct{} `type:"structure"` + + // A PackageVersionError object that contains a map of errors codes for the + // deleted package that failed. The possible error codes are: + // + // * ALREADY_EXISTS + // + // * MISMATCHED_REVISION + // + // * MISMATCHED_STATUS + // + // * NOT_ALLOWED + // + // * NOT_FOUND + // + // * SKIPPED + FailedVersions map[string]*PackageVersionError `locationName:"failedVersions" type:"map"` + + // A list of the package versions that were successfully deleted. + SuccessfulVersions map[string]*SuccessfulPackageVersionInfo `locationName:"successfulVersions" type:"map"` +} + +// String returns the string representation +func (s DeletePackageVersionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeletePackageVersionsOutput) GoString() string { + return s.String() +} + +// SetFailedVersions sets the FailedVersions field's value. +func (s *DeletePackageVersionsOutput) SetFailedVersions(v map[string]*PackageVersionError) *DeletePackageVersionsOutput { + s.FailedVersions = v + return s +} + +// SetSuccessfulVersions sets the SuccessfulVersions field's value. +func (s *DeletePackageVersionsOutput) SetSuccessfulVersions(v map[string]*SuccessfulPackageVersionInfo) *DeletePackageVersionsOutput { + s.SuccessfulVersions = v + return s +} + +type DeleteRepositoryInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the repository to delete. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The name of the repository to delete. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteRepositoryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRepositoryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteRepositoryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteRepositoryInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *DeleteRepositoryInput) SetDomain(v string) *DeleteRepositoryInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *DeleteRepositoryInput) SetDomainOwner(v string) *DeleteRepositoryInput { + s.DomainOwner = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *DeleteRepositoryInput) SetRepository(v string) *DeleteRepositoryInput { + s.Repository = &v + return s +} + +type DeleteRepositoryOutput struct { + _ struct{} `type:"structure"` + + // Information about the deleted repository after processing the request. + Repository *RepositoryDescription `locationName:"repository" type:"structure"` +} + +// String returns the string representation +func (s DeleteRepositoryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRepositoryOutput) GoString() string { + return s.String() +} + +// SetRepository sets the Repository field's value. +func (s *DeleteRepositoryOutput) SetRepository(v *RepositoryDescription) *DeleteRepositoryOutput { + s.Repository = v + return s +} + +type DeleteRepositoryPermissionsPolicyInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the repository associated with the resource + // policy to be deleted. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The revision of the repository's resource policy to be deleted. This revision + // is used for optimistic locking, which prevents others from accidentally overwriting + // your changes to the repository's resource policy. + PolicyRevision *string `location:"querystring" locationName:"policy-revision" min:"1" type:"string"` + + // The name of the repository that is associated with the resource policy to + // be deleted + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteRepositoryPermissionsPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRepositoryPermissionsPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteRepositoryPermissionsPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteRepositoryPermissionsPolicyInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.PolicyRevision != nil && len(*s.PolicyRevision) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PolicyRevision", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *DeleteRepositoryPermissionsPolicyInput) SetDomain(v string) *DeleteRepositoryPermissionsPolicyInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *DeleteRepositoryPermissionsPolicyInput) SetDomainOwner(v string) *DeleteRepositoryPermissionsPolicyInput { + s.DomainOwner = &v + return s +} + +// SetPolicyRevision sets the PolicyRevision field's value. +func (s *DeleteRepositoryPermissionsPolicyInput) SetPolicyRevision(v string) *DeleteRepositoryPermissionsPolicyInput { + s.PolicyRevision = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *DeleteRepositoryPermissionsPolicyInput) SetRepository(v string) *DeleteRepositoryPermissionsPolicyInput { + s.Repository = &v + return s +} + +type DeleteRepositoryPermissionsPolicyOutput struct { + _ struct{} `type:"structure"` + + // Information about the deleted policy after processing the request. + Policy *ResourcePolicy `locationName:"policy" type:"structure"` +} + +// String returns the string representation +func (s DeleteRepositoryPermissionsPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRepositoryPermissionsPolicyOutput) GoString() string { + return s.String() +} + +// SetPolicy sets the Policy field's value. +func (s *DeleteRepositoryPermissionsPolicyOutput) SetPolicy(v *ResourcePolicy) *DeleteRepositoryPermissionsPolicyOutput { + s.Policy = v + return s +} + +type DescribeDomainInput struct { + _ struct{} `type:"structure"` + + // A string that specifies the name of the requested domain. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` +} + +// String returns the string representation +func (s DescribeDomainInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeDomainInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeDomainInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeDomainInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *DescribeDomainInput) SetDomain(v string) *DescribeDomainInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *DescribeDomainInput) SetDomainOwner(v string) *DescribeDomainInput { + s.DomainOwner = &v + return s +} + +type DescribeDomainOutput struct { + _ struct{} `type:"structure"` + + // Information about a domain. A domain is a container for repositories. When + // you create a domain, it is empty until you add one or more repositories. + Domain *DomainDescription `locationName:"domain" type:"structure"` +} + +// String returns the string representation +func (s DescribeDomainOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeDomainOutput) GoString() string { + return s.String() +} + +// SetDomain sets the Domain field's value. +func (s *DescribeDomainOutput) SetDomain(v *DomainDescription) *DescribeDomainOutput { + s.Domain = v + return s +} + +type DescribePackageVersionInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the repository that contains the package + // version. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // A format that specifies the type of the requested package version. The valid + // values are: + // + // * npm + // + // * pypi + // + // * maven + // + // Format is a required field + Format *string `location:"querystring" locationName:"format" type:"string" required:"true" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `location:"querystring" locationName:"namespace" min:"1" type:"string"` + + // The name of the requested package version. + // + // Package is a required field + Package *string `location:"querystring" locationName:"package" min:"1" type:"string" required:"true"` + + // A string that contains the package version (for example, 3.5.2). + // + // PackageVersion is a required field + PackageVersion *string `location:"querystring" locationName:"version" min:"1" type:"string" required:"true"` + + // The name of the repository that contains the package version. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribePackageVersionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribePackageVersionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribePackageVersionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribePackageVersionInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.Package == nil { + invalidParams.Add(request.NewErrParamRequired("Package")) + } + if s.Package != nil && len(*s.Package) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Package", 1)) + } + if s.PackageVersion == nil { + invalidParams.Add(request.NewErrParamRequired("PackageVersion")) + } + if s.PackageVersion != nil && len(*s.PackageVersion) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PackageVersion", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *DescribePackageVersionInput) SetDomain(v string) *DescribePackageVersionInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *DescribePackageVersionInput) SetDomainOwner(v string) *DescribePackageVersionInput { + s.DomainOwner = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *DescribePackageVersionInput) SetFormat(v string) *DescribePackageVersionInput { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *DescribePackageVersionInput) SetNamespace(v string) *DescribePackageVersionInput { + s.Namespace = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *DescribePackageVersionInput) SetPackage(v string) *DescribePackageVersionInput { + s.Package = &v + return s +} + +// SetPackageVersion sets the PackageVersion field's value. +func (s *DescribePackageVersionInput) SetPackageVersion(v string) *DescribePackageVersionInput { + s.PackageVersion = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *DescribePackageVersionInput) SetRepository(v string) *DescribePackageVersionInput { + s.Repository = &v + return s +} + +type DescribePackageVersionOutput struct { + _ struct{} `type:"structure"` + + // A PackageVersionDescription (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageVersionDescription.html) + // object that contains information about the requested package version. + // + // PackageVersion is a required field + PackageVersion *PackageVersionDescription `locationName:"packageVersion" type:"structure" required:"true"` +} + +// String returns the string representation +func (s DescribePackageVersionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribePackageVersionOutput) GoString() string { + return s.String() +} + +// SetPackageVersion sets the PackageVersion field's value. +func (s *DescribePackageVersionOutput) SetPackageVersion(v *PackageVersionDescription) *DescribePackageVersionOutput { + s.PackageVersion = v + return s +} + +type DescribeRepositoryInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the repository to describe. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // A string that specifies the name of the requested repository. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeRepositoryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeRepositoryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeRepositoryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeRepositoryInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *DescribeRepositoryInput) SetDomain(v string) *DescribeRepositoryInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *DescribeRepositoryInput) SetDomainOwner(v string) *DescribeRepositoryInput { + s.DomainOwner = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *DescribeRepositoryInput) SetRepository(v string) *DescribeRepositoryInput { + s.Repository = &v + return s +} + +type DescribeRepositoryOutput struct { + _ struct{} `type:"structure"` + + // A RepositoryDescription object that contains the requested repository information. + Repository *RepositoryDescription `locationName:"repository" type:"structure"` +} + +// String returns the string representation +func (s DescribeRepositoryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeRepositoryOutput) GoString() string { + return s.String() +} + +// SetRepository sets the Repository field's value. +func (s *DescribeRepositoryOutput) SetRepository(v *RepositoryDescription) *DescribeRepositoryOutput { + s.Repository = v + return s +} + +type DisassociateExternalConnectionInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the repository from which to remove + // the external repository. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The name of the external connection to be removed from the repository. + // + // ExternalConnection is a required field + ExternalConnection *string `location:"querystring" locationName:"external-connection" type:"string" required:"true"` + + // The name of the repository from which the external connection will be removed. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s DisassociateExternalConnectionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisassociateExternalConnectionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DisassociateExternalConnectionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DisassociateExternalConnectionInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.ExternalConnection == nil { + invalidParams.Add(request.NewErrParamRequired("ExternalConnection")) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *DisassociateExternalConnectionInput) SetDomain(v string) *DisassociateExternalConnectionInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *DisassociateExternalConnectionInput) SetDomainOwner(v string) *DisassociateExternalConnectionInput { + s.DomainOwner = &v + return s +} + +// SetExternalConnection sets the ExternalConnection field's value. +func (s *DisassociateExternalConnectionInput) SetExternalConnection(v string) *DisassociateExternalConnectionInput { + s.ExternalConnection = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *DisassociateExternalConnectionInput) SetRepository(v string) *DisassociateExternalConnectionInput { + s.Repository = &v + return s +} + +type DisassociateExternalConnectionOutput struct { + _ struct{} `type:"structure"` + + // The repository associated with the removed external connection. + Repository *RepositoryDescription `locationName:"repository" type:"structure"` +} + +// String returns the string representation +func (s DisassociateExternalConnectionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisassociateExternalConnectionOutput) GoString() string { + return s.String() +} + +// SetRepository sets the Repository field's value. +func (s *DisassociateExternalConnectionOutput) SetRepository(v *RepositoryDescription) *DisassociateExternalConnectionOutput { + s.Repository = v + return s +} + +type DisposePackageVersionsInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the repository you want to dispose. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The expected status of the package version to dispose. Valid values are: + // + // * Published + // + // * Unfinished + // + // * Unlisted + // + // * Archived + // + // * Disposed + ExpectedStatus *string `locationName:"expectedStatus" type:"string" enum:"PackageVersionStatus"` + + // A format that specifies the type of package versions you want to dispose. + // The valid values are: + // + // * npm + // + // * pypi + // + // * maven + // + // Format is a required field + Format *string `location:"querystring" locationName:"format" type:"string" required:"true" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `location:"querystring" locationName:"namespace" min:"1" type:"string"` + + // The name of the package with the versions you want to dispose. + // + // Package is a required field + Package *string `location:"querystring" locationName:"package" min:"1" type:"string" required:"true"` + + // The name of the repository that contains the package versions you want to + // dispose. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` + + // The revisions of the package versions you want to dispose. + VersionRevisions map[string]*string `locationName:"versionRevisions" type:"map"` + + // The versions of the package you want to dispose. + // + // Versions is a required field + Versions []*string `locationName:"versions" type:"list" required:"true"` +} + +// String returns the string representation +func (s DisposePackageVersionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisposePackageVersionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DisposePackageVersionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DisposePackageVersionsInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.Package == nil { + invalidParams.Add(request.NewErrParamRequired("Package")) + } + if s.Package != nil && len(*s.Package) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Package", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + if s.Versions == nil { + invalidParams.Add(request.NewErrParamRequired("Versions")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *DisposePackageVersionsInput) SetDomain(v string) *DisposePackageVersionsInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *DisposePackageVersionsInput) SetDomainOwner(v string) *DisposePackageVersionsInput { + s.DomainOwner = &v + return s +} + +// SetExpectedStatus sets the ExpectedStatus field's value. +func (s *DisposePackageVersionsInput) SetExpectedStatus(v string) *DisposePackageVersionsInput { + s.ExpectedStatus = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *DisposePackageVersionsInput) SetFormat(v string) *DisposePackageVersionsInput { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *DisposePackageVersionsInput) SetNamespace(v string) *DisposePackageVersionsInput { + s.Namespace = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *DisposePackageVersionsInput) SetPackage(v string) *DisposePackageVersionsInput { + s.Package = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *DisposePackageVersionsInput) SetRepository(v string) *DisposePackageVersionsInput { + s.Repository = &v + return s +} + +// SetVersionRevisions sets the VersionRevisions field's value. +func (s *DisposePackageVersionsInput) SetVersionRevisions(v map[string]*string) *DisposePackageVersionsInput { + s.VersionRevisions = v + return s +} + +// SetVersions sets the Versions field's value. +func (s *DisposePackageVersionsInput) SetVersions(v []*string) *DisposePackageVersionsInput { + s.Versions = v + return s +} + +type DisposePackageVersionsOutput struct { + _ struct{} `type:"structure"` + + // A PackageVersionError object that contains a map of errors codes for the + // disposed package versions that failed. The possible error codes are: + // + // * ALREADY_EXISTS + // + // * MISMATCHED_REVISION + // + // * MISMATCHED_STATUS + // + // * NOT_ALLOWED + // + // * NOT_FOUND + // + // * SKIPPED + FailedVersions map[string]*PackageVersionError `locationName:"failedVersions" type:"map"` + + // A list of the package versions that were successfully disposed. + SuccessfulVersions map[string]*SuccessfulPackageVersionInfo `locationName:"successfulVersions" type:"map"` +} + +// String returns the string representation +func (s DisposePackageVersionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisposePackageVersionsOutput) GoString() string { + return s.String() +} + +// SetFailedVersions sets the FailedVersions field's value. +func (s *DisposePackageVersionsOutput) SetFailedVersions(v map[string]*PackageVersionError) *DisposePackageVersionsOutput { + s.FailedVersions = v + return s +} + +// SetSuccessfulVersions sets the SuccessfulVersions field's value. +func (s *DisposePackageVersionsOutput) SetSuccessfulVersions(v map[string]*SuccessfulPackageVersionInfo) *DisposePackageVersionsOutput { + s.SuccessfulVersions = v + return s +} + +// Information about a domain. A domain is a container for repositories. When +// you create a domain, it is empty until you add one or more repositories. +type DomainDescription struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the domain. + Arn *string `locationName:"arn" min:"1" type:"string"` + + // The total size of all assets in the domain. + AssetSizeBytes *int64 `locationName:"assetSizeBytes" type:"long"` + + // A timestamp that represents the date and time the domain was created. + CreatedTime *time.Time `locationName:"createdTime" type:"timestamp"` + + // The ARN of an AWS Key Management Service (AWS KMS) key associated with a + // domain. + EncryptionKey *string `locationName:"encryptionKey" min:"1" type:"string"` + + // The name of the domain. + Name *string `locationName:"name" min:"2" type:"string"` + + // The AWS account ID that owns the domain. + Owner *string `locationName:"owner" min:"12" type:"string"` + + // The number of repositories in the domain. + RepositoryCount *int64 `locationName:"repositoryCount" type:"integer"` + + // The current status of a domain. The valid values are + // + // * Active + // + // * Deleted + Status *string `locationName:"status" type:"string" enum:"DomainStatus"` +} + +// String returns the string representation +func (s DomainDescription) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DomainDescription) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *DomainDescription) SetArn(v string) *DomainDescription { + s.Arn = &v + return s +} + +// SetAssetSizeBytes sets the AssetSizeBytes field's value. +func (s *DomainDescription) SetAssetSizeBytes(v int64) *DomainDescription { + s.AssetSizeBytes = &v + return s +} + +// SetCreatedTime sets the CreatedTime field's value. +func (s *DomainDescription) SetCreatedTime(v time.Time) *DomainDescription { + s.CreatedTime = &v + return s +} + +// SetEncryptionKey sets the EncryptionKey field's value. +func (s *DomainDescription) SetEncryptionKey(v string) *DomainDescription { + s.EncryptionKey = &v + return s +} + +// SetName sets the Name field's value. +func (s *DomainDescription) SetName(v string) *DomainDescription { + s.Name = &v + return s +} + +// SetOwner sets the Owner field's value. +func (s *DomainDescription) SetOwner(v string) *DomainDescription { + s.Owner = &v + return s +} + +// SetRepositoryCount sets the RepositoryCount field's value. +func (s *DomainDescription) SetRepositoryCount(v int64) *DomainDescription { + s.RepositoryCount = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *DomainDescription) SetStatus(v string) *DomainDescription { + s.Status = &v + return s +} + +// Information about a domain, including its name, Amazon Resource Name (ARN), +// and status. The ListDomains (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListDomains.html) +// operation returns a list of DomainSummary objects. +type DomainSummary struct { + _ struct{} `type:"structure"` + + // The ARN of the domain. + Arn *string `locationName:"arn" min:"1" type:"string"` + + // A timestamp that contains the date and time the domain was created. + CreatedTime *time.Time `locationName:"createdTime" type:"timestamp"` + + // The key used to encrypt the domain. + EncryptionKey *string `locationName:"encryptionKey" min:"1" type:"string"` + + // The name of the domain. + Name *string `locationName:"name" min:"2" type:"string"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + Owner *string `locationName:"owner" min:"12" type:"string"` + + // A string that contains the status of the domain. The valid values are: + // + // * Active + // + // * Deleted + Status *string `locationName:"status" type:"string" enum:"DomainStatus"` +} + +// String returns the string representation +func (s DomainSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DomainSummary) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *DomainSummary) SetArn(v string) *DomainSummary { + s.Arn = &v + return s +} + +// SetCreatedTime sets the CreatedTime field's value. +func (s *DomainSummary) SetCreatedTime(v time.Time) *DomainSummary { + s.CreatedTime = &v + return s +} + +// SetEncryptionKey sets the EncryptionKey field's value. +func (s *DomainSummary) SetEncryptionKey(v string) *DomainSummary { + s.EncryptionKey = &v + return s +} + +// SetName sets the Name field's value. +func (s *DomainSummary) SetName(v string) *DomainSummary { + s.Name = &v + return s +} + +// SetOwner sets the Owner field's value. +func (s *DomainSummary) SetOwner(v string) *DomainSummary { + s.Owner = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *DomainSummary) SetStatus(v string) *DomainSummary { + s.Status = &v + return s +} + +type GetAuthorizationTokenInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that is in scope for the generated authorization token. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The time, in seconds, that the generated authorization token is valid. + DurationSeconds *int64 `location:"querystring" locationName:"duration" type:"long"` +} + +// String returns the string representation +func (s GetAuthorizationTokenInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetAuthorizationTokenInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetAuthorizationTokenInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetAuthorizationTokenInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *GetAuthorizationTokenInput) SetDomain(v string) *GetAuthorizationTokenInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *GetAuthorizationTokenInput) SetDomainOwner(v string) *GetAuthorizationTokenInput { + s.DomainOwner = &v + return s +} + +// SetDurationSeconds sets the DurationSeconds field's value. +func (s *GetAuthorizationTokenInput) SetDurationSeconds(v int64) *GetAuthorizationTokenInput { + s.DurationSeconds = &v + return s +} + +type GetAuthorizationTokenOutput struct { + _ struct{} `type:"structure"` + + // The returned authentication token. + AuthorizationToken *string `locationName:"authorizationToken" type:"string"` + + // A timestamp that specifies the date and time the authorization token expires. + Expiration *time.Time `locationName:"expiration" type:"timestamp"` +} + +// String returns the string representation +func (s GetAuthorizationTokenOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetAuthorizationTokenOutput) GoString() string { + return s.String() +} + +// SetAuthorizationToken sets the AuthorizationToken field's value. +func (s *GetAuthorizationTokenOutput) SetAuthorizationToken(v string) *GetAuthorizationTokenOutput { + s.AuthorizationToken = &v + return s +} + +// SetExpiration sets the Expiration field's value. +func (s *GetAuthorizationTokenOutput) SetExpiration(v time.Time) *GetAuthorizationTokenOutput { + s.Expiration = &v + return s +} + +type GetDomainPermissionsPolicyInput struct { + _ struct{} `type:"structure"` + + // The name of the domain to which the resource policy is attached. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` +} + +// String returns the string representation +func (s GetDomainPermissionsPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDomainPermissionsPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetDomainPermissionsPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDomainPermissionsPolicyInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *GetDomainPermissionsPolicyInput) SetDomain(v string) *GetDomainPermissionsPolicyInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *GetDomainPermissionsPolicyInput) SetDomainOwner(v string) *GetDomainPermissionsPolicyInput { + s.DomainOwner = &v + return s +} + +type GetDomainPermissionsPolicyOutput struct { + _ struct{} `type:"structure"` + + // The returned resource policy. + Policy *ResourcePolicy `locationName:"policy" type:"structure"` +} + +// String returns the string representation +func (s GetDomainPermissionsPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDomainPermissionsPolicyOutput) GoString() string { + return s.String() +} + +// SetPolicy sets the Policy field's value. +func (s *GetDomainPermissionsPolicyOutput) SetPolicy(v *ResourcePolicy) *GetDomainPermissionsPolicyOutput { + s.Policy = v + return s +} + +type GetPackageVersionAssetInput struct { + _ struct{} `type:"structure"` + + // The name of the requested asset. + // + // Asset is a required field + Asset *string `location:"querystring" locationName:"asset" min:"1" type:"string" required:"true"` + + // The domain that contains the repository that contains the package version + // with the requested asset. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // A format that specifies the type of the package version with the requested + // asset file. The valid values are: + // + // * npm + // + // * pypi + // + // * maven + // + // Format is a required field + Format *string `location:"querystring" locationName:"format" type:"string" required:"true" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `location:"querystring" locationName:"namespace" min:"1" type:"string"` + + // The name of the package that contains the requested asset. + // + // Package is a required field + Package *string `location:"querystring" locationName:"package" min:"1" type:"string" required:"true"` + + // A string that contains the package version (for example, 3.5.2). + // + // PackageVersion is a required field + PackageVersion *string `location:"querystring" locationName:"version" min:"1" type:"string" required:"true"` + + // The name of the package version revision that contains the requested asset. + PackageVersionRevision *string `location:"querystring" locationName:"revision" min:"1" type:"string"` + + // The repository that contains the package version with the requested asset. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetPackageVersionAssetInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetPackageVersionAssetInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetPackageVersionAssetInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetPackageVersionAssetInput"} + if s.Asset == nil { + invalidParams.Add(request.NewErrParamRequired("Asset")) + } + if s.Asset != nil && len(*s.Asset) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Asset", 1)) + } + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.Package == nil { + invalidParams.Add(request.NewErrParamRequired("Package")) + } + if s.Package != nil && len(*s.Package) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Package", 1)) + } + if s.PackageVersion == nil { + invalidParams.Add(request.NewErrParamRequired("PackageVersion")) + } + if s.PackageVersion != nil && len(*s.PackageVersion) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PackageVersion", 1)) + } + if s.PackageVersionRevision != nil && len(*s.PackageVersionRevision) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PackageVersionRevision", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAsset sets the Asset field's value. +func (s *GetPackageVersionAssetInput) SetAsset(v string) *GetPackageVersionAssetInput { + s.Asset = &v + return s +} + +// SetDomain sets the Domain field's value. +func (s *GetPackageVersionAssetInput) SetDomain(v string) *GetPackageVersionAssetInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *GetPackageVersionAssetInput) SetDomainOwner(v string) *GetPackageVersionAssetInput { + s.DomainOwner = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *GetPackageVersionAssetInput) SetFormat(v string) *GetPackageVersionAssetInput { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *GetPackageVersionAssetInput) SetNamespace(v string) *GetPackageVersionAssetInput { + s.Namespace = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *GetPackageVersionAssetInput) SetPackage(v string) *GetPackageVersionAssetInput { + s.Package = &v + return s +} + +// SetPackageVersion sets the PackageVersion field's value. +func (s *GetPackageVersionAssetInput) SetPackageVersion(v string) *GetPackageVersionAssetInput { + s.PackageVersion = &v + return s +} + +// SetPackageVersionRevision sets the PackageVersionRevision field's value. +func (s *GetPackageVersionAssetInput) SetPackageVersionRevision(v string) *GetPackageVersionAssetInput { + s.PackageVersionRevision = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *GetPackageVersionAssetInput) SetRepository(v string) *GetPackageVersionAssetInput { + s.Repository = &v + return s +} + +type GetPackageVersionAssetOutput struct { + _ struct{} `type:"structure" payload:"Asset"` + + // The binary file, or asset, that is downloaded. + Asset io.ReadCloser `locationName:"asset" type:"blob"` + + // The name of the asset that is downloaded. + AssetName *string `location:"header" locationName:"X-AssetName" min:"1" type:"string"` + + // A string that contains the package version (for example, 3.5.2). + PackageVersion *string `location:"header" locationName:"X-PackageVersion" min:"1" type:"string"` + + // The name of the package version revision that contains the downloaded asset. + PackageVersionRevision *string `location:"header" locationName:"X-PackageVersionRevision" min:"1" type:"string"` +} + +// String returns the string representation +func (s GetPackageVersionAssetOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetPackageVersionAssetOutput) GoString() string { + return s.String() +} + +// SetAsset sets the Asset field's value. +func (s *GetPackageVersionAssetOutput) SetAsset(v io.ReadCloser) *GetPackageVersionAssetOutput { + s.Asset = v + return s +} + +// SetAssetName sets the AssetName field's value. +func (s *GetPackageVersionAssetOutput) SetAssetName(v string) *GetPackageVersionAssetOutput { + s.AssetName = &v + return s +} + +// SetPackageVersion sets the PackageVersion field's value. +func (s *GetPackageVersionAssetOutput) SetPackageVersion(v string) *GetPackageVersionAssetOutput { + s.PackageVersion = &v + return s +} + +// SetPackageVersionRevision sets the PackageVersionRevision field's value. +func (s *GetPackageVersionAssetOutput) SetPackageVersionRevision(v string) *GetPackageVersionAssetOutput { + s.PackageVersionRevision = &v + return s +} + +type GetPackageVersionReadmeInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the repository that contains the package + // version with the requested readme file. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // A format that specifies the type of the package version with the requested + // readme file. The valid values are: + // + // * npm + // + // * pypi + // + // * maven + // + // Format is a required field + Format *string `location:"querystring" locationName:"format" type:"string" required:"true" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `location:"querystring" locationName:"namespace" min:"1" type:"string"` + + // The name of the package version that contains the requested readme file. + // + // Package is a required field + Package *string `location:"querystring" locationName:"package" min:"1" type:"string" required:"true"` + + // A string that contains the package version (for example, 3.5.2). + // + // PackageVersion is a required field + PackageVersion *string `location:"querystring" locationName:"version" min:"1" type:"string" required:"true"` + + // The repository that contains the package with the requested readme file. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetPackageVersionReadmeInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetPackageVersionReadmeInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetPackageVersionReadmeInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetPackageVersionReadmeInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.Package == nil { + invalidParams.Add(request.NewErrParamRequired("Package")) + } + if s.Package != nil && len(*s.Package) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Package", 1)) + } + if s.PackageVersion == nil { + invalidParams.Add(request.NewErrParamRequired("PackageVersion")) + } + if s.PackageVersion != nil && len(*s.PackageVersion) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PackageVersion", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *GetPackageVersionReadmeInput) SetDomain(v string) *GetPackageVersionReadmeInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *GetPackageVersionReadmeInput) SetDomainOwner(v string) *GetPackageVersionReadmeInput { + s.DomainOwner = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *GetPackageVersionReadmeInput) SetFormat(v string) *GetPackageVersionReadmeInput { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *GetPackageVersionReadmeInput) SetNamespace(v string) *GetPackageVersionReadmeInput { + s.Namespace = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *GetPackageVersionReadmeInput) SetPackage(v string) *GetPackageVersionReadmeInput { + s.Package = &v + return s +} + +// SetPackageVersion sets the PackageVersion field's value. +func (s *GetPackageVersionReadmeInput) SetPackageVersion(v string) *GetPackageVersionReadmeInput { + s.PackageVersion = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *GetPackageVersionReadmeInput) SetRepository(v string) *GetPackageVersionReadmeInput { + s.Repository = &v + return s +} + +type GetPackageVersionReadmeOutput struct { + _ struct{} `type:"structure"` + + // The format of the package with the requested readme file. Valid format types + // are: + // + // * npm + // + // * pypi + // + // * maven + Format *string `locationName:"format" type:"string" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `locationName:"namespace" min:"1" type:"string"` + + // The name of the package that contains the returned readme file. + Package *string `locationName:"package" min:"1" type:"string"` + + // The text of the returned readme file. + Readme *string `locationName:"readme" type:"string"` + + // The version of the package with the requested readme file. + Version *string `locationName:"version" min:"1" type:"string"` + + // The current revision associated with the package version. + VersionRevision *string `locationName:"versionRevision" min:"1" type:"string"` +} + +// String returns the string representation +func (s GetPackageVersionReadmeOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetPackageVersionReadmeOutput) GoString() string { + return s.String() +} + +// SetFormat sets the Format field's value. +func (s *GetPackageVersionReadmeOutput) SetFormat(v string) *GetPackageVersionReadmeOutput { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *GetPackageVersionReadmeOutput) SetNamespace(v string) *GetPackageVersionReadmeOutput { + s.Namespace = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *GetPackageVersionReadmeOutput) SetPackage(v string) *GetPackageVersionReadmeOutput { + s.Package = &v + return s +} + +// SetReadme sets the Readme field's value. +func (s *GetPackageVersionReadmeOutput) SetReadme(v string) *GetPackageVersionReadmeOutput { + s.Readme = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *GetPackageVersionReadmeOutput) SetVersion(v string) *GetPackageVersionReadmeOutput { + s.Version = &v + return s +} + +// SetVersionRevision sets the VersionRevision field's value. +func (s *GetPackageVersionReadmeOutput) SetVersionRevision(v string) *GetPackageVersionReadmeOutput { + s.VersionRevision = &v + return s +} + +type GetRepositoryEndpointInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the repository. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain that + // contains the repository. It does not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // Returns which endpoint of a repository to return. A repository has one endpoint + // for each package format: + // + // * npm + // + // * pypi + // + // * maven + // + // Format is a required field + Format *string `location:"querystring" locationName:"format" type:"string" required:"true" enum:"PackageFormat"` + + // The name of the repository. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetRepositoryEndpointInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetRepositoryEndpointInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetRepositoryEndpointInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetRepositoryEndpointInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *GetRepositoryEndpointInput) SetDomain(v string) *GetRepositoryEndpointInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *GetRepositoryEndpointInput) SetDomainOwner(v string) *GetRepositoryEndpointInput { + s.DomainOwner = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *GetRepositoryEndpointInput) SetFormat(v string) *GetRepositoryEndpointInput { + s.Format = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *GetRepositoryEndpointInput) SetRepository(v string) *GetRepositoryEndpointInput { + s.Repository = &v + return s +} + +type GetRepositoryEndpointOutput struct { + _ struct{} `type:"structure"` + + // A string that specifies the URL of the returned endpoint. + RepositoryEndpoint *string `locationName:"repositoryEndpoint" type:"string"` +} + +// String returns the string representation +func (s GetRepositoryEndpointOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetRepositoryEndpointOutput) GoString() string { + return s.String() +} + +// SetRepositoryEndpoint sets the RepositoryEndpoint field's value. +func (s *GetRepositoryEndpointOutput) SetRepositoryEndpoint(v string) *GetRepositoryEndpointOutput { + s.RepositoryEndpoint = &v + return s +} + +type GetRepositoryPermissionsPolicyInput struct { + _ struct{} `type:"structure"` + + // The name of the domain containing the repository whose associated resource + // policy is to be retrieved. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The name of the repository whose associated resource policy is to be retrieved. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetRepositoryPermissionsPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetRepositoryPermissionsPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetRepositoryPermissionsPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetRepositoryPermissionsPolicyInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *GetRepositoryPermissionsPolicyInput) SetDomain(v string) *GetRepositoryPermissionsPolicyInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *GetRepositoryPermissionsPolicyInput) SetDomainOwner(v string) *GetRepositoryPermissionsPolicyInput { + s.DomainOwner = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *GetRepositoryPermissionsPolicyInput) SetRepository(v string) *GetRepositoryPermissionsPolicyInput { + s.Repository = &v + return s +} + +type GetRepositoryPermissionsPolicyOutput struct { + _ struct{} `type:"structure"` + + // The returned resource policy. + Policy *ResourcePolicy `locationName:"policy" type:"structure"` +} + +// String returns the string representation +func (s GetRepositoryPermissionsPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetRepositoryPermissionsPolicyOutput) GoString() string { + return s.String() +} + +// SetPolicy sets the Policy field's value. +func (s *GetRepositoryPermissionsPolicyOutput) SetPolicy(v *ResourcePolicy) *GetRepositoryPermissionsPolicyOutput { + s.Policy = v + return s +} + +// The operation did not succeed because of an error that occurred inside AWS +// CodeArtifact. +type InternalServerException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s InternalServerException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InternalServerException) GoString() string { + return s.String() +} + +func newErrorInternalServerException(v protocol.ResponseMetadata) error { + return &InternalServerException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InternalServerException) Code() string { + return "InternalServerException" +} + +// Message returns the exception's message. +func (s *InternalServerException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InternalServerException) OrigErr() error { + return nil +} + +func (s *InternalServerException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InternalServerException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InternalServerException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Details of the license data. +type LicenseInfo struct { + _ struct{} `type:"structure"` + + // Name of the license. + Name *string `locationName:"name" type:"string"` + + // The URL for license data. + Url *string `locationName:"url" type:"string"` +} + +// String returns the string representation +func (s LicenseInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s LicenseInfo) GoString() string { + return s.String() +} + +// SetName sets the Name field's value. +func (s *LicenseInfo) SetName(v string) *LicenseInfo { + s.Name = &v + return s +} + +// SetUrl sets the Url field's value. +func (s *LicenseInfo) SetUrl(v string) *LicenseInfo { + s.Url = &v + return s +} + +type ListDomainsInput struct { + _ struct{} `type:"structure"` + + // The maximum number of results to return per page. + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` + + // The token for the next set of results. Use the value returned in the previous + // response in the next request to retrieve the next set of results. + NextToken *string `locationName:"nextToken" min:"1" type:"string"` +} + +// String returns the string representation +func (s ListDomainsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListDomainsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListDomainsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDomainsInput"} + 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 *ListDomainsInput) SetMaxResults(v int64) *ListDomainsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDomainsInput) SetNextToken(v string) *ListDomainsInput { + s.NextToken = &v + return s +} + +type ListDomainsOutput struct { + _ struct{} `type:"structure"` + + // The returned list of DomainSummary (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_DomainSummary.html) + // objects. + Domains []*DomainSummary `locationName:"domains" type:"list"` + + // The token for the next set of results. Use the value returned in the previous + // response in the next request to retrieve the next set of results. + NextToken *string `locationName:"nextToken" min:"1" type:"string"` +} + +// String returns the string representation +func (s ListDomainsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListDomainsOutput) GoString() string { + return s.String() +} + +// SetDomains sets the Domains field's value. +func (s *ListDomainsOutput) SetDomains(v []*DomainSummary) *ListDomainsOutput { + s.Domains = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDomainsOutput) SetNextToken(v string) *ListDomainsOutput { + s.NextToken = &v + return s +} + +type ListPackageVersionAssetsInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the repository associated with the package + // version assets. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The format of the package that contains the returned package version assets. + // The valid package types are: + // + // * npm: A Node Package Manager (npm) package. + // + // * pypi: A Python Package Index (PyPI) package. + // + // * maven: A Maven package that contains compiled code in a distributable + // format, such as a JAR file. + // + // Format is a required field + Format *string `location:"querystring" locationName:"format" type:"string" required:"true" enum:"PackageFormat"` + + // The maximum number of results to return per page. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `location:"querystring" locationName:"namespace" min:"1" type:"string"` + + // The token for the next set of results. Use the value returned in the previous + // response in the next request to retrieve the next set of results. + NextToken *string `location:"querystring" locationName:"next-token" min:"1" type:"string"` + + // The name of the package that contains the returned package version assets. + // + // Package is a required field + Package *string `location:"querystring" locationName:"package" min:"1" type:"string" required:"true"` + + // A string that contains the package version (for example, 3.5.2). + // + // PackageVersion is a required field + PackageVersion *string `location:"querystring" locationName:"version" min:"1" type:"string" required:"true"` + + // The name of the repository that contains the package that contains the returned + // package version assets. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListPackageVersionAssetsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListPackageVersionAssetsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListPackageVersionAssetsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListPackageVersionAssetsInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.NextToken != nil && len(*s.NextToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) + } + if s.Package == nil { + invalidParams.Add(request.NewErrParamRequired("Package")) + } + if s.Package != nil && len(*s.Package) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Package", 1)) + } + if s.PackageVersion == nil { + invalidParams.Add(request.NewErrParamRequired("PackageVersion")) + } + if s.PackageVersion != nil && len(*s.PackageVersion) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PackageVersion", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *ListPackageVersionAssetsInput) SetDomain(v string) *ListPackageVersionAssetsInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *ListPackageVersionAssetsInput) SetDomainOwner(v string) *ListPackageVersionAssetsInput { + s.DomainOwner = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *ListPackageVersionAssetsInput) SetFormat(v string) *ListPackageVersionAssetsInput { + s.Format = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListPackageVersionAssetsInput) SetMaxResults(v int64) *ListPackageVersionAssetsInput { + s.MaxResults = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *ListPackageVersionAssetsInput) SetNamespace(v string) *ListPackageVersionAssetsInput { + s.Namespace = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListPackageVersionAssetsInput) SetNextToken(v string) *ListPackageVersionAssetsInput { + s.NextToken = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *ListPackageVersionAssetsInput) SetPackage(v string) *ListPackageVersionAssetsInput { + s.Package = &v + return s +} + +// SetPackageVersion sets the PackageVersion field's value. +func (s *ListPackageVersionAssetsInput) SetPackageVersion(v string) *ListPackageVersionAssetsInput { + s.PackageVersion = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *ListPackageVersionAssetsInput) SetRepository(v string) *ListPackageVersionAssetsInput { + s.Repository = &v + return s +} + +type ListPackageVersionAssetsOutput struct { + _ struct{} `type:"structure"` + + // The returned list of AssetSummary (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_AssetSummary.html) + // objects. + Assets []*AssetSummary `locationName:"assets" type:"list"` + + // The format of the package that contains the returned package version assets. + Format *string `locationName:"format" type:"string" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `locationName:"namespace" min:"1" type:"string"` + + // If there are additional results, this is the token for the next set of results. + NextToken *string `locationName:"nextToken" min:"1" type:"string"` + + // The name of the package that contains the returned package version assets. + Package *string `locationName:"package" min:"1" type:"string"` + + // The version of the package associated with the returned assets. + Version *string `locationName:"version" min:"1" type:"string"` + + // The current revision associated with the package version. + VersionRevision *string `locationName:"versionRevision" min:"1" type:"string"` +} + +// String returns the string representation +func (s ListPackageVersionAssetsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListPackageVersionAssetsOutput) GoString() string { + return s.String() +} + +// SetAssets sets the Assets field's value. +func (s *ListPackageVersionAssetsOutput) SetAssets(v []*AssetSummary) *ListPackageVersionAssetsOutput { + s.Assets = v + return s +} + +// SetFormat sets the Format field's value. +func (s *ListPackageVersionAssetsOutput) SetFormat(v string) *ListPackageVersionAssetsOutput { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *ListPackageVersionAssetsOutput) SetNamespace(v string) *ListPackageVersionAssetsOutput { + s.Namespace = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListPackageVersionAssetsOutput) SetNextToken(v string) *ListPackageVersionAssetsOutput { + s.NextToken = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *ListPackageVersionAssetsOutput) SetPackage(v string) *ListPackageVersionAssetsOutput { + s.Package = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *ListPackageVersionAssetsOutput) SetVersion(v string) *ListPackageVersionAssetsOutput { + s.Version = &v + return s +} + +// SetVersionRevision sets the VersionRevision field's value. +func (s *ListPackageVersionAssetsOutput) SetVersionRevision(v string) *ListPackageVersionAssetsOutput { + s.VersionRevision = &v + return s +} + +type ListPackageVersionDependenciesInput struct { + _ struct{} `type:"structure"` + + // The domain that contains the repository that contains the requested package + // version dependencies. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The format of the package with the requested dependencies. The valid package + // types are: + // + // * npm: A Node Package Manager (npm) package. + // + // * pypi: A Python Package Index (PyPI) package. + // + // * maven: A Maven package that contains compiled code in a distributable + // format, such as a JAR file. + // + // Format is a required field + Format *string `location:"querystring" locationName:"format" type:"string" required:"true" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `location:"querystring" locationName:"namespace" min:"1" type:"string"` + + // The token for the next set of results. Use the value returned in the previous + // response in the next request to retrieve the next set of results. + NextToken *string `location:"querystring" locationName:"next-token" min:"1" type:"string"` + + // The name of the package versions' package. + // + // Package is a required field + Package *string `location:"querystring" locationName:"package" min:"1" type:"string" required:"true"` + + // A string that contains the package version (for example, 3.5.2). + // + // PackageVersion is a required field + PackageVersion *string `location:"querystring" locationName:"version" min:"1" type:"string" required:"true"` + + // The name of the repository that contains the requested package version. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListPackageVersionDependenciesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListPackageVersionDependenciesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListPackageVersionDependenciesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListPackageVersionDependenciesInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.NextToken != nil && len(*s.NextToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) + } + if s.Package == nil { + invalidParams.Add(request.NewErrParamRequired("Package")) + } + if s.Package != nil && len(*s.Package) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Package", 1)) + } + if s.PackageVersion == nil { + invalidParams.Add(request.NewErrParamRequired("PackageVersion")) + } + if s.PackageVersion != nil && len(*s.PackageVersion) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PackageVersion", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *ListPackageVersionDependenciesInput) SetDomain(v string) *ListPackageVersionDependenciesInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *ListPackageVersionDependenciesInput) SetDomainOwner(v string) *ListPackageVersionDependenciesInput { + s.DomainOwner = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *ListPackageVersionDependenciesInput) SetFormat(v string) *ListPackageVersionDependenciesInput { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *ListPackageVersionDependenciesInput) SetNamespace(v string) *ListPackageVersionDependenciesInput { + s.Namespace = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListPackageVersionDependenciesInput) SetNextToken(v string) *ListPackageVersionDependenciesInput { + s.NextToken = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *ListPackageVersionDependenciesInput) SetPackage(v string) *ListPackageVersionDependenciesInput { + s.Package = &v + return s +} + +// SetPackageVersion sets the PackageVersion field's value. +func (s *ListPackageVersionDependenciesInput) SetPackageVersion(v string) *ListPackageVersionDependenciesInput { + s.PackageVersion = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *ListPackageVersionDependenciesInput) SetRepository(v string) *ListPackageVersionDependenciesInput { + s.Repository = &v + return s +} + +type ListPackageVersionDependenciesOutput struct { + _ struct{} `type:"structure"` + + // The returned list of PackageDependency (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageDependency.html) + // objects. + Dependencies []*PackageDependency `locationName:"dependencies" type:"list"` + + // A format that specifies the type of the package that contains the returned + // dependencies. The valid values are: + // + // * npm + // + // * pypi + // + // * maven + Format *string `locationName:"format" type:"string" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `locationName:"namespace" min:"1" type:"string"` + + // The token for the next set of results. Use the value returned in the previous + // response in the next request to retrieve the next set of results. + NextToken *string `locationName:"nextToken" min:"1" type:"string"` + + // The name of the package that contains the returned package versions dependencies. + Package *string `locationName:"package" min:"1" type:"string"` + + // The version of the package that is specified in the request. + Version *string `locationName:"version" min:"1" type:"string"` + + // The current revision associated with the package version. + VersionRevision *string `locationName:"versionRevision" min:"1" type:"string"` +} + +// String returns the string representation +func (s ListPackageVersionDependenciesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListPackageVersionDependenciesOutput) GoString() string { + return s.String() +} + +// SetDependencies sets the Dependencies field's value. +func (s *ListPackageVersionDependenciesOutput) SetDependencies(v []*PackageDependency) *ListPackageVersionDependenciesOutput { + s.Dependencies = v + return s +} + +// SetFormat sets the Format field's value. +func (s *ListPackageVersionDependenciesOutput) SetFormat(v string) *ListPackageVersionDependenciesOutput { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *ListPackageVersionDependenciesOutput) SetNamespace(v string) *ListPackageVersionDependenciesOutput { + s.Namespace = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListPackageVersionDependenciesOutput) SetNextToken(v string) *ListPackageVersionDependenciesOutput { + s.NextToken = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *ListPackageVersionDependenciesOutput) SetPackage(v string) *ListPackageVersionDependenciesOutput { + s.Package = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *ListPackageVersionDependenciesOutput) SetVersion(v string) *ListPackageVersionDependenciesOutput { + s.Version = &v + return s +} + +// SetVersionRevision sets the VersionRevision field's value. +func (s *ListPackageVersionDependenciesOutput) SetVersionRevision(v string) *ListPackageVersionDependenciesOutput { + s.VersionRevision = &v + return s +} + +type ListPackageVersionsInput struct { + _ struct{} `type:"structure"` + + // The name of the domain that contains the repository that contains the returned + // package versions. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The format of the returned packages. The valid package types are: + // + // * npm: A Node Package Manager (npm) package. + // + // * pypi: A Python Package Index (PyPI) package. + // + // * maven: A Maven package that contains compiled code in a distributable + // format, such as a JAR file. + // + // Format is a required field + Format *string `location:"querystring" locationName:"format" type:"string" required:"true" enum:"PackageFormat"` + + // The maximum number of results to return per page. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `location:"querystring" locationName:"namespace" min:"1" type:"string"` + + // The token for the next set of results. Use the value returned in the previous + // response in the next request to retrieve the next set of results. + NextToken *string `location:"querystring" locationName:"next-token" min:"1" type:"string"` + + // The name of the package for which you want to return a list of package versions. + // + // Package is a required field + Package *string `location:"querystring" locationName:"package" min:"1" type:"string" required:"true"` + + // The name of the repository that contains the package. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` + + // How to sort the returned list of package versions. + SortBy *string `location:"querystring" locationName:"sortBy" type:"string" enum:"PackageVersionSortType"` + + // A string that specifies the status of the package versions to include in + // the returned list. It can be one of the following: + // + // * Published + // + // * Unfinished + // + // * Unlisted + // + // * Archived + // + // * Disposed + Status *string `location:"querystring" locationName:"status" type:"string" enum:"PackageVersionStatus"` +} + +// String returns the string representation +func (s ListPackageVersionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListPackageVersionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListPackageVersionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListPackageVersionsInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.NextToken != nil && len(*s.NextToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) + } + if s.Package == nil { + invalidParams.Add(request.NewErrParamRequired("Package")) + } + if s.Package != nil && len(*s.Package) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Package", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *ListPackageVersionsInput) SetDomain(v string) *ListPackageVersionsInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *ListPackageVersionsInput) SetDomainOwner(v string) *ListPackageVersionsInput { + s.DomainOwner = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *ListPackageVersionsInput) SetFormat(v string) *ListPackageVersionsInput { + s.Format = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListPackageVersionsInput) SetMaxResults(v int64) *ListPackageVersionsInput { + s.MaxResults = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *ListPackageVersionsInput) SetNamespace(v string) *ListPackageVersionsInput { + s.Namespace = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListPackageVersionsInput) SetNextToken(v string) *ListPackageVersionsInput { + s.NextToken = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *ListPackageVersionsInput) SetPackage(v string) *ListPackageVersionsInput { + s.Package = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *ListPackageVersionsInput) SetRepository(v string) *ListPackageVersionsInput { + s.Repository = &v + return s +} + +// SetSortBy sets the SortBy field's value. +func (s *ListPackageVersionsInput) SetSortBy(v string) *ListPackageVersionsInput { + s.SortBy = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *ListPackageVersionsInput) SetStatus(v string) *ListPackageVersionsInput { + s.Status = &v + return s +} + +type ListPackageVersionsOutput struct { + _ struct{} `type:"structure"` + + // The default package version to display. This depends on the package format: + // + // * For Maven and PyPI packages, it's the most recently published package + // version. + // + // * For npm packages, it's the version referenced by the latest tag. If + // the latest tag is not set, it's the most recently published package version. + DefaultDisplayVersion *string `locationName:"defaultDisplayVersion" min:"1" type:"string"` + + // A format of the package. Valid package format values are: + // + // * npm + // + // * pypi + // + // * maven + Format *string `locationName:"format" type:"string" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `locationName:"namespace" min:"1" type:"string"` + + // If there are additional results, this is the token for the next set of results. + NextToken *string `locationName:"nextToken" min:"1" type:"string"` + + // The name of the package. + Package *string `locationName:"package" min:"1" type:"string"` + + // The returned list of PackageVersionSummary (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageVersionSummary.html) + // objects. + Versions []*PackageVersionSummary `locationName:"versions" type:"list"` +} + +// String returns the string representation +func (s ListPackageVersionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListPackageVersionsOutput) GoString() string { + return s.String() +} + +// SetDefaultDisplayVersion sets the DefaultDisplayVersion field's value. +func (s *ListPackageVersionsOutput) SetDefaultDisplayVersion(v string) *ListPackageVersionsOutput { + s.DefaultDisplayVersion = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *ListPackageVersionsOutput) SetFormat(v string) *ListPackageVersionsOutput { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *ListPackageVersionsOutput) SetNamespace(v string) *ListPackageVersionsOutput { + s.Namespace = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListPackageVersionsOutput) SetNextToken(v string) *ListPackageVersionsOutput { + s.NextToken = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *ListPackageVersionsOutput) SetPackage(v string) *ListPackageVersionsOutput { + s.Package = &v + return s +} + +// SetVersions sets the Versions field's value. +func (s *ListPackageVersionsOutput) SetVersions(v []*PackageVersionSummary) *ListPackageVersionsOutput { + s.Versions = v + return s +} + +type ListPackagesInput struct { + _ struct{} `type:"structure"` + + // The domain that contains the repository that contains the requested list + // of packages. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The format of the packages. The valid package types are: + // + // * npm: A Node Package Manager (npm) package. + // + // * pypi: A Python Package Index (PyPI) package. + // + // * maven: A Maven package that contains compiled code in a distributable + // format, such as a JAR file. + Format *string `location:"querystring" locationName:"format" type:"string" enum:"PackageFormat"` + + // The maximum number of results to return per page. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `location:"querystring" locationName:"namespace" min:"1" type:"string"` + + // The token for the next set of results. Use the value returned in the previous + // response in the next request to retrieve the next set of results. + NextToken *string `location:"querystring" locationName:"next-token" min:"1" type:"string"` + + // A prefix used to filter returned repositories. Only repositories with names + // that start with repositoryPrefix are returned. + PackagePrefix *string `location:"querystring" locationName:"package-prefix" min:"1" type:"string"` + + // The name of the repository from which packages are to be listed. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListPackagesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListPackagesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListPackagesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListPackagesInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.NextToken != nil && len(*s.NextToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) + } + if s.PackagePrefix != nil && len(*s.PackagePrefix) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PackagePrefix", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *ListPackagesInput) SetDomain(v string) *ListPackagesInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *ListPackagesInput) SetDomainOwner(v string) *ListPackagesInput { + s.DomainOwner = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *ListPackagesInput) SetFormat(v string) *ListPackagesInput { + s.Format = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListPackagesInput) SetMaxResults(v int64) *ListPackagesInput { + s.MaxResults = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *ListPackagesInput) SetNamespace(v string) *ListPackagesInput { + s.Namespace = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListPackagesInput) SetNextToken(v string) *ListPackagesInput { + s.NextToken = &v + return s +} + +// SetPackagePrefix sets the PackagePrefix field's value. +func (s *ListPackagesInput) SetPackagePrefix(v string) *ListPackagesInput { + s.PackagePrefix = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *ListPackagesInput) SetRepository(v string) *ListPackagesInput { + s.Repository = &v + return s +} + +type ListPackagesOutput struct { + _ struct{} `type:"structure"` + + // If there are additional results, this is the token for the next set of results. + NextToken *string `locationName:"nextToken" min:"1" type:"string"` + + // The list of returned PackageSummary (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageSummary.html) + // objects. + Packages []*PackageSummary `locationName:"packages" type:"list"` +} + +// String returns the string representation +func (s ListPackagesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListPackagesOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListPackagesOutput) SetNextToken(v string) *ListPackagesOutput { + s.NextToken = &v + return s +} + +// SetPackages sets the Packages field's value. +func (s *ListPackagesOutput) SetPackages(v []*PackageSummary) *ListPackagesOutput { + s.Packages = v + return s +} + +type ListRepositoriesInDomainInput struct { + _ struct{} `type:"structure"` + + // Filter the list of repositories to only include those that are managed by + // the AWS account ID. + AdministratorAccount *string `location:"querystring" locationName:"administrator-account" min:"12" type:"string"` + + // The name of the domain that contains the returned list of repositories. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The maximum number of results to return per page. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + + // The token for the next set of results. Use the value returned in the previous + // response in the next request to retrieve the next set of results. + NextToken *string `location:"querystring" locationName:"next-token" min:"1" type:"string"` + + // A prefix used to filter returned repositories. Only repositories with names + // that start with repositoryPrefix are returned. + RepositoryPrefix *string `location:"querystring" locationName:"repository-prefix" min:"2" type:"string"` +} + +// String returns the string representation +func (s ListRepositoriesInDomainInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListRepositoriesInDomainInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListRepositoriesInDomainInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListRepositoriesInDomainInput"} + if s.AdministratorAccount != nil && len(*s.AdministratorAccount) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AdministratorAccount", 12)) + } + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + 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 s.RepositoryPrefix != nil && len(*s.RepositoryPrefix) < 2 { + invalidParams.Add(request.NewErrParamMinLen("RepositoryPrefix", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAdministratorAccount sets the AdministratorAccount field's value. +func (s *ListRepositoriesInDomainInput) SetAdministratorAccount(v string) *ListRepositoriesInDomainInput { + s.AdministratorAccount = &v + return s +} + +// SetDomain sets the Domain field's value. +func (s *ListRepositoriesInDomainInput) SetDomain(v string) *ListRepositoriesInDomainInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *ListRepositoriesInDomainInput) SetDomainOwner(v string) *ListRepositoriesInDomainInput { + s.DomainOwner = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListRepositoriesInDomainInput) SetMaxResults(v int64) *ListRepositoriesInDomainInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListRepositoriesInDomainInput) SetNextToken(v string) *ListRepositoriesInDomainInput { + s.NextToken = &v + return s +} + +// SetRepositoryPrefix sets the RepositoryPrefix field's value. +func (s *ListRepositoriesInDomainInput) SetRepositoryPrefix(v string) *ListRepositoriesInDomainInput { + s.RepositoryPrefix = &v + return s +} + +type ListRepositoriesInDomainOutput struct { + _ struct{} `type:"structure"` + + // If there are additional results, this is the token for the next set of results. + NextToken *string `locationName:"nextToken" min:"1" type:"string"` + + // The returned list of repositories. + Repositories []*RepositorySummary `locationName:"repositories" type:"list"` +} + +// String returns the string representation +func (s ListRepositoriesInDomainOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListRepositoriesInDomainOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListRepositoriesInDomainOutput) SetNextToken(v string) *ListRepositoriesInDomainOutput { + s.NextToken = &v + return s +} + +// SetRepositories sets the Repositories field's value. +func (s *ListRepositoriesInDomainOutput) SetRepositories(v []*RepositorySummary) *ListRepositoriesInDomainOutput { + s.Repositories = v + return s +} + +type ListRepositoriesInput struct { + _ struct{} `type:"structure"` + + // The maximum number of results to return per page. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + + // The token for the next set of results. Use the value returned in the previous + // response in the next request to retrieve the next set of results. + NextToken *string `location:"querystring" locationName:"next-token" min:"1" type:"string"` + + // A prefix used to filter returned repositories. Only repositories with names + // that start with repositoryPrefix are returned. + RepositoryPrefix *string `location:"querystring" locationName:"repository-prefix" min:"2" type:"string"` +} + +// String returns the string representation +func (s ListRepositoriesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListRepositoriesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListRepositoriesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListRepositoriesInput"} + 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 s.RepositoryPrefix != nil && len(*s.RepositoryPrefix) < 2 { + invalidParams.Add(request.NewErrParamMinLen("RepositoryPrefix", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListRepositoriesInput) SetMaxResults(v int64) *ListRepositoriesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListRepositoriesInput) SetNextToken(v string) *ListRepositoriesInput { + s.NextToken = &v + return s +} + +// SetRepositoryPrefix sets the RepositoryPrefix field's value. +func (s *ListRepositoriesInput) SetRepositoryPrefix(v string) *ListRepositoriesInput { + s.RepositoryPrefix = &v + return s +} + +type ListRepositoriesOutput struct { + _ struct{} `type:"structure"` + + // If there are additional results, this is the token for the next set of results. + NextToken *string `locationName:"nextToken" min:"1" type:"string"` + + // The returned list of RepositorySummary (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_RepositorySummary.html) + // objects. + Repositories []*RepositorySummary `locationName:"repositories" type:"list"` +} + +// String returns the string representation +func (s ListRepositoriesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListRepositoriesOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListRepositoriesOutput) SetNextToken(v string) *ListRepositoriesOutput { + s.NextToken = &v + return s +} + +// SetRepositories sets the Repositories field's value. +func (s *ListRepositoriesOutput) SetRepositories(v []*RepositorySummary) *ListRepositoriesOutput { + s.Repositories = v + return s +} + +// Details about a package dependency. +type PackageDependency struct { + _ struct{} `type:"structure"` + + // The type of a package dependency. The possible values depend on the package + // type. Example types are compile, runtime, and test for Maven packages, and + // dev, prod, and optional for npm packages. + DependencyType *string `locationName:"dependencyType" type:"string"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `locationName:"namespace" min:"1" type:"string"` + + // The name of the package that this package depends on. + Package *string `locationName:"package" min:"1" type:"string"` + + // The required version, or version range, of the package that this package + // depends on. The version format is specific to the package type. For example, + // the following are possible valid required versions: 1.2.3, ^2.3.4, or 4.x. + VersionRequirement *string `locationName:"versionRequirement" type:"string"` +} + +// String returns the string representation +func (s PackageDependency) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PackageDependency) GoString() string { + return s.String() +} + +// SetDependencyType sets the DependencyType field's value. +func (s *PackageDependency) SetDependencyType(v string) *PackageDependency { + s.DependencyType = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *PackageDependency) SetNamespace(v string) *PackageDependency { + s.Namespace = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *PackageDependency) SetPackage(v string) *PackageDependency { + s.Package = &v + return s +} + +// SetVersionRequirement sets the VersionRequirement field's value. +func (s *PackageDependency) SetVersionRequirement(v string) *PackageDependency { + s.VersionRequirement = &v + return s +} + +// Details about a package, including its format, namespace, and name. The ListPackages +// (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListPackages.html) +// operation returns a list of PackageSummary objects. +type PackageSummary struct { + _ struct{} `type:"structure"` + + // The format of the package. Valid values are: + // + // * npm + // + // * pypi + // + // * maven + Format *string `locationName:"format" type:"string" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `locationName:"namespace" min:"1" type:"string"` + + // The name of the package. + Package *string `locationName:"package" min:"1" type:"string"` +} + +// String returns the string representation +func (s PackageSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PackageSummary) GoString() string { + return s.String() +} + +// SetFormat sets the Format field's value. +func (s *PackageSummary) SetFormat(v string) *PackageSummary { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *PackageSummary) SetNamespace(v string) *PackageSummary { + s.Namespace = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *PackageSummary) SetPackage(v string) *PackageSummary { + s.Package = &v + return s +} + +// Details about a package version. +type PackageVersionDescription struct { + _ struct{} `type:"structure"` + + // The name of the package that is displayed. The displayName varies depending + // on the package version's format. For example, if an npm package is named + // ui, is in the namespace vue, and has the format npm, then the displayName + // is @vue/ui. + DisplayName *string `locationName:"displayName" min:"1" type:"string"` + + // The format of the package version. The valid package formats are: + // + // * npm: A Node Package Manager (npm) package. + // + // * pypi: A Python Package Index (PyPI) package. + // + // * maven: A Maven package that contains compiled code in a distributable + // format, such as a JAR file. + Format *string `locationName:"format" type:"string" enum:"PackageFormat"` + + // The homepage associated with the package. + HomePage *string `locationName:"homePage" type:"string"` + + // Information about licenses associated with the package version. + Licenses []*LicenseInfo `locationName:"licenses" type:"list"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `locationName:"namespace" min:"1" type:"string"` + + // The name of the requested package. + PackageName *string `locationName:"packageName" min:"1" type:"string"` + + // A timestamp that contains the date and time the package version was published. + PublishedTime *time.Time `locationName:"publishedTime" type:"timestamp"` + + // The revision of the package version. + Revision *string `locationName:"revision" min:"1" type:"string"` + + // The repository for the source code in the package version, or the source + // code used to build it. + SourceCodeRepository *string `locationName:"sourceCodeRepository" type:"string"` + + // A string that contains the status of the package version. It can be one of + // the following: + // + // * Published + // + // * Unfinished + // + // * Unlisted + // + // * Archived + // + // * Disposed + Status *string `locationName:"status" type:"string" enum:"PackageVersionStatus"` + + // A summary of the package version. The summary is extracted from the package. + // The information in and detail level of the summary depends on the package + // version's format. + Summary *string `locationName:"summary" type:"string"` + + // The version of the package. + Version *string `locationName:"version" min:"1" type:"string"` +} + +// String returns the string representation +func (s PackageVersionDescription) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PackageVersionDescription) GoString() string { + return s.String() +} + +// SetDisplayName sets the DisplayName field's value. +func (s *PackageVersionDescription) SetDisplayName(v string) *PackageVersionDescription { + s.DisplayName = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *PackageVersionDescription) SetFormat(v string) *PackageVersionDescription { + s.Format = &v + return s +} + +// SetHomePage sets the HomePage field's value. +func (s *PackageVersionDescription) SetHomePage(v string) *PackageVersionDescription { + s.HomePage = &v + return s +} + +// SetLicenses sets the Licenses field's value. +func (s *PackageVersionDescription) SetLicenses(v []*LicenseInfo) *PackageVersionDescription { + s.Licenses = v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *PackageVersionDescription) SetNamespace(v string) *PackageVersionDescription { + s.Namespace = &v + return s +} + +// SetPackageName sets the PackageName field's value. +func (s *PackageVersionDescription) SetPackageName(v string) *PackageVersionDescription { + s.PackageName = &v + return s +} + +// SetPublishedTime sets the PublishedTime field's value. +func (s *PackageVersionDescription) SetPublishedTime(v time.Time) *PackageVersionDescription { + s.PublishedTime = &v + return s +} + +// SetRevision sets the Revision field's value. +func (s *PackageVersionDescription) SetRevision(v string) *PackageVersionDescription { + s.Revision = &v + return s +} + +// SetSourceCodeRepository sets the SourceCodeRepository field's value. +func (s *PackageVersionDescription) SetSourceCodeRepository(v string) *PackageVersionDescription { + s.SourceCodeRepository = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *PackageVersionDescription) SetStatus(v string) *PackageVersionDescription { + s.Status = &v + return s +} + +// SetSummary sets the Summary field's value. +func (s *PackageVersionDescription) SetSummary(v string) *PackageVersionDescription { + s.Summary = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *PackageVersionDescription) SetVersion(v string) *PackageVersionDescription { + s.Version = &v + return s +} + +// An error associated with package. +type PackageVersionError struct { + _ struct{} `type:"structure"` + + // The error code associated with the error. Valid error codes are: + // + // * ALREADY_EXISTS + // + // * MISMATCHED_REVISION + // + // * MISMATCHED_STATUS + // + // * NOT_ALLOWED + // + // * NOT_FOUND + // + // * SKIPPED + ErrorCode *string `locationName:"errorCode" type:"string" enum:"PackageVersionErrorCode"` + + // The error message associated with the error. + ErrorMessage *string `locationName:"errorMessage" type:"string"` +} + +// String returns the string representation +func (s PackageVersionError) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PackageVersionError) GoString() string { + return s.String() +} + +// SetErrorCode sets the ErrorCode field's value. +func (s *PackageVersionError) SetErrorCode(v string) *PackageVersionError { + s.ErrorCode = &v + return s +} + +// SetErrorMessage sets the ErrorMessage field's value. +func (s *PackageVersionError) SetErrorMessage(v string) *PackageVersionError { + s.ErrorMessage = &v + return s +} + +// Details about a package version, including its status, version, and revision. +// The ListPackageVersions (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListPackageVersions.html) +// operation returns a list of PackageVersionSummary objects. +type PackageVersionSummary struct { + _ struct{} `type:"structure"` + + // The revision associated with a package version. + Revision *string `locationName:"revision" min:"1" type:"string"` + + // A string that contains the status of the package version. It can be one of + // the following: + // + // * Published + // + // * Unfinished + // + // * Unlisted + // + // * Archived + // + // * Disposed + // + // Status is a required field + Status *string `locationName:"status" type:"string" required:"true" enum:"PackageVersionStatus"` + + // Information about a package version. + // + // Version is a required field + Version *string `locationName:"version" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s PackageVersionSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PackageVersionSummary) GoString() string { + return s.String() +} + +// SetRevision sets the Revision field's value. +func (s *PackageVersionSummary) SetRevision(v string) *PackageVersionSummary { + s.Revision = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *PackageVersionSummary) SetStatus(v string) *PackageVersionSummary { + s.Status = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *PackageVersionSummary) SetVersion(v string) *PackageVersionSummary { + s.Version = &v + return s +} + +type PutDomainPermissionsPolicyInput struct { + _ struct{} `type:"structure"` + + // The name of the domain on which to set the resource policy. + // + // Domain is a required field + Domain *string `locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `locationName:"domainOwner" min:"12" type:"string"` + + // A valid displayable JSON Aspen policy string to be set as the access control + // resource policy on the provided domain. + // + // PolicyDocument is a required field + PolicyDocument *string `locationName:"policyDocument" min:"1" type:"string" required:"true"` + + // The current revision of the resource policy to be set. This revision is used + // for optimistic locking, which prevents others from overwriting your changes + // to the domain's resource policy. + PolicyRevision *string `locationName:"policyRevision" min:"1" type:"string"` +} + +// String returns the string representation +func (s PutDomainPermissionsPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutDomainPermissionsPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutDomainPermissionsPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutDomainPermissionsPolicyInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.PolicyDocument == nil { + invalidParams.Add(request.NewErrParamRequired("PolicyDocument")) + } + if s.PolicyDocument != nil && len(*s.PolicyDocument) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PolicyDocument", 1)) + } + if s.PolicyRevision != nil && len(*s.PolicyRevision) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PolicyRevision", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *PutDomainPermissionsPolicyInput) SetDomain(v string) *PutDomainPermissionsPolicyInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *PutDomainPermissionsPolicyInput) SetDomainOwner(v string) *PutDomainPermissionsPolicyInput { + s.DomainOwner = &v + return s +} + +// SetPolicyDocument sets the PolicyDocument field's value. +func (s *PutDomainPermissionsPolicyInput) SetPolicyDocument(v string) *PutDomainPermissionsPolicyInput { + s.PolicyDocument = &v + return s +} + +// SetPolicyRevision sets the PolicyRevision field's value. +func (s *PutDomainPermissionsPolicyInput) SetPolicyRevision(v string) *PutDomainPermissionsPolicyInput { + s.PolicyRevision = &v + return s +} + +type PutDomainPermissionsPolicyOutput struct { + _ struct{} `type:"structure"` + + // The resource policy that was set after processing the request. + Policy *ResourcePolicy `locationName:"policy" type:"structure"` +} + +// String returns the string representation +func (s PutDomainPermissionsPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutDomainPermissionsPolicyOutput) GoString() string { + return s.String() +} + +// SetPolicy sets the Policy field's value. +func (s *PutDomainPermissionsPolicyOutput) SetPolicy(v *ResourcePolicy) *PutDomainPermissionsPolicyOutput { + s.Policy = v + return s +} + +type PutRepositoryPermissionsPolicyInput struct { + _ struct{} `type:"structure"` + + // The name of the domain containing the repository to set the resource policy + // on. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // A valid displayable JSON Aspen policy string to be set as the access control + // resource policy on the provided repository. + // + // PolicyDocument is a required field + PolicyDocument *string `locationName:"policyDocument" min:"1" type:"string" required:"true"` + + // Sets the revision of the resource policy that specifies permissions to access + // the repository. This revision is used for optimistic locking, which prevents + // others from overwriting your changes to the repository's resource policy. + PolicyRevision *string `locationName:"policyRevision" min:"1" type:"string"` + + // The name of the repository to set the resource policy on. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s PutRepositoryPermissionsPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutRepositoryPermissionsPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutRepositoryPermissionsPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutRepositoryPermissionsPolicyInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.PolicyDocument == nil { + invalidParams.Add(request.NewErrParamRequired("PolicyDocument")) + } + if s.PolicyDocument != nil && len(*s.PolicyDocument) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PolicyDocument", 1)) + } + if s.PolicyRevision != nil && len(*s.PolicyRevision) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PolicyRevision", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *PutRepositoryPermissionsPolicyInput) SetDomain(v string) *PutRepositoryPermissionsPolicyInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *PutRepositoryPermissionsPolicyInput) SetDomainOwner(v string) *PutRepositoryPermissionsPolicyInput { + s.DomainOwner = &v + return s +} + +// SetPolicyDocument sets the PolicyDocument field's value. +func (s *PutRepositoryPermissionsPolicyInput) SetPolicyDocument(v string) *PutRepositoryPermissionsPolicyInput { + s.PolicyDocument = &v + return s +} + +// SetPolicyRevision sets the PolicyRevision field's value. +func (s *PutRepositoryPermissionsPolicyInput) SetPolicyRevision(v string) *PutRepositoryPermissionsPolicyInput { + s.PolicyRevision = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *PutRepositoryPermissionsPolicyInput) SetRepository(v string) *PutRepositoryPermissionsPolicyInput { + s.Repository = &v + return s +} + +type PutRepositoryPermissionsPolicyOutput struct { + _ struct{} `type:"structure"` + + // The resource policy that was set after processing the request. + Policy *ResourcePolicy `locationName:"policy" type:"structure"` +} + +// String returns the string representation +func (s PutRepositoryPermissionsPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutRepositoryPermissionsPolicyOutput) GoString() string { + return s.String() +} + +// SetPolicy sets the Policy field's value. +func (s *PutRepositoryPermissionsPolicyOutput) SetPolicy(v *ResourcePolicy) *PutRepositoryPermissionsPolicyOutput { + s.Policy = v + return s +} + +// The details of a repository stored in AWS CodeArtifact. A CodeArtifact repository +// contains a set of package versions, each of which maps to a set of assets. +// Repositories are polyglot—a single repository can contain packages of any +// supported type. Each repository exposes endpoints for fetching and publishing +// packages using tools like the npm CLI, the Maven CLI (mvn), and pip. You +// can create up to 100 repositories per AWS account. +type RepositoryDescription struct { + _ struct{} `type:"structure"` + + // The 12-digit account number of the AWS account that manages the repository. + AdministratorAccount *string `locationName:"administratorAccount" min:"12" type:"string"` + + // The Amazon Resource Name (ARN) of the repository. + Arn *string `locationName:"arn" min:"1" type:"string"` + + // A text description of the repository. + Description *string `locationName:"description" type:"string"` + + // The name of the domain that contains the repository. + DomainName *string `locationName:"domainName" min:"2" type:"string"` + + // The 12-digit account number of the AWS account that owns the domain that + // contains the repository. It does not include dashes or spaces. + DomainOwner *string `locationName:"domainOwner" min:"12" type:"string"` + + // An array of external connections associated with the repository. + ExternalConnections []*RepositoryExternalConnectionInfo `locationName:"externalConnections" type:"list"` + + // The name of the repository. + Name *string `locationName:"name" min:"2" type:"string"` + + // A list of upstream repositories to associate with the repository. The order + // of the upstream repositories in the list determines their priority order + // when AWS CodeArtifact looks for a requested package version. For more information, + // see Working with upstream repositories (https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html). + Upstreams []*UpstreamRepositoryInfo `locationName:"upstreams" type:"list"` +} + +// String returns the string representation +func (s RepositoryDescription) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RepositoryDescription) GoString() string { + return s.String() +} + +// SetAdministratorAccount sets the AdministratorAccount field's value. +func (s *RepositoryDescription) SetAdministratorAccount(v string) *RepositoryDescription { + s.AdministratorAccount = &v + return s +} + +// SetArn sets the Arn field's value. +func (s *RepositoryDescription) SetArn(v string) *RepositoryDescription { + s.Arn = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *RepositoryDescription) SetDescription(v string) *RepositoryDescription { + s.Description = &v + return s +} + +// SetDomainName sets the DomainName field's value. +func (s *RepositoryDescription) SetDomainName(v string) *RepositoryDescription { + s.DomainName = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *RepositoryDescription) SetDomainOwner(v string) *RepositoryDescription { + s.DomainOwner = &v + return s +} + +// SetExternalConnections sets the ExternalConnections field's value. +func (s *RepositoryDescription) SetExternalConnections(v []*RepositoryExternalConnectionInfo) *RepositoryDescription { + s.ExternalConnections = v + return s +} + +// SetName sets the Name field's value. +func (s *RepositoryDescription) SetName(v string) *RepositoryDescription { + s.Name = &v + return s +} + +// SetUpstreams sets the Upstreams field's value. +func (s *RepositoryDescription) SetUpstreams(v []*UpstreamRepositoryInfo) *RepositoryDescription { + s.Upstreams = v + return s +} + +// Contains information about the external connection of a repository. +type RepositoryExternalConnectionInfo struct { + _ struct{} `type:"structure"` + + // The name of the external connection associated with a repository. + ExternalConnectionName *string `locationName:"externalConnectionName" type:"string"` + + // The package format associated with a repository's external connection. The + // valid package formats are: + // + // * npm: A Node Package Manager (npm) package. + // + // * pypi: A Python Package Index (PyPI) package. + // + // * maven: A Maven package that contains compiled code in a distributable + // format, such as a JAR file. + PackageFormat *string `locationName:"packageFormat" type:"string" enum:"PackageFormat"` + + // The status of the external connection of a repository. There is one valid + // value, Available. + Status *string `locationName:"status" type:"string" enum:"ExternalConnectionStatus"` +} + +// String returns the string representation +func (s RepositoryExternalConnectionInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RepositoryExternalConnectionInfo) GoString() string { + return s.String() +} + +// SetExternalConnectionName sets the ExternalConnectionName field's value. +func (s *RepositoryExternalConnectionInfo) SetExternalConnectionName(v string) *RepositoryExternalConnectionInfo { + s.ExternalConnectionName = &v + return s +} + +// SetPackageFormat sets the PackageFormat field's value. +func (s *RepositoryExternalConnectionInfo) SetPackageFormat(v string) *RepositoryExternalConnectionInfo { + s.PackageFormat = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *RepositoryExternalConnectionInfo) SetStatus(v string) *RepositoryExternalConnectionInfo { + s.Status = &v + return s +} + +// Details about a repository, including its Amazon Resource Name (ARN), description, +// and domain information. The ListRepositories (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_ListRepositories.html) +// operation returns a list of RepositorySummary objects. +type RepositorySummary struct { + _ struct{} `type:"structure"` + + // The AWS account ID that manages the repository. + AdministratorAccount *string `locationName:"administratorAccount" min:"12" type:"string"` + + // The ARN of the repository. + Arn *string `locationName:"arn" min:"1" type:"string"` + + // The description of the repository. + Description *string `locationName:"description" type:"string"` + + // The name of the domain that contains the repository. + DomainName *string `locationName:"domainName" min:"2" type:"string"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `locationName:"domainOwner" min:"12" type:"string"` + + // The name of the repository. + Name *string `locationName:"name" min:"2" type:"string"` +} + +// String returns the string representation +func (s RepositorySummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RepositorySummary) GoString() string { + return s.String() +} + +// SetAdministratorAccount sets the AdministratorAccount field's value. +func (s *RepositorySummary) SetAdministratorAccount(v string) *RepositorySummary { + s.AdministratorAccount = &v + return s +} + +// SetArn sets the Arn field's value. +func (s *RepositorySummary) SetArn(v string) *RepositorySummary { + s.Arn = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *RepositorySummary) SetDescription(v string) *RepositorySummary { + s.Description = &v + return s +} + +// SetDomainName sets the DomainName field's value. +func (s *RepositorySummary) SetDomainName(v string) *RepositorySummary { + s.DomainName = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *RepositorySummary) SetDomainOwner(v string) *RepositorySummary { + s.DomainOwner = &v + return s +} + +// SetName sets the Name field's value. +func (s *RepositorySummary) SetName(v string) *RepositorySummary { + s.Name = &v + return s +} + +// The operation did not succeed because the resource requested is not found +// in the service. +type ResourceNotFoundException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` + + // The ID of the resource. + ResourceId *string `locationName:"resourceId" type:"string"` + + // The type of AWS resource. + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` +} + +// String returns the string representation +func (s ResourceNotFoundException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResourceNotFoundException) GoString() string { + return s.String() +} + +func newErrorResourceNotFoundException(v protocol.ResponseMetadata) error { + return &ResourceNotFoundException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ResourceNotFoundException) Code() string { + return "ResourceNotFoundException" +} + +// Message returns the exception's message. +func (s *ResourceNotFoundException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ResourceNotFoundException) OrigErr() error { + return nil +} + +func (s *ResourceNotFoundException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ResourceNotFoundException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ResourceNotFoundException) RequestID() string { + return s.RespMetadata.RequestID +} + +// An AWS CodeArtifact resource policy that contains a resource ARN, document +// details, and a revision. +type ResourcePolicy struct { + _ struct{} `type:"structure"` + + // The resource policy formatted in JSON. + Document *string `locationName:"document" min:"1" type:"string"` + + // The ARN of the resource associated with the resource policy + ResourceArn *string `locationName:"resourceArn" min:"1" type:"string"` + + // The current revision of the resource policy. + Revision *string `locationName:"revision" min:"1" type:"string"` +} + +// String returns the string representation +func (s ResourcePolicy) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResourcePolicy) GoString() string { + return s.String() +} + +// SetDocument sets the Document field's value. +func (s *ResourcePolicy) SetDocument(v string) *ResourcePolicy { + s.Document = &v + return s +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *ResourcePolicy) SetResourceArn(v string) *ResourcePolicy { + s.ResourceArn = &v + return s +} + +// SetRevision sets the Revision field's value. +func (s *ResourcePolicy) SetRevision(v string) *ResourcePolicy { + s.Revision = &v + return s +} + +// The operation did not succeed because it would have exceeded a service limit +// for your account. +type ServiceQuotaExceededException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` + + // The ID of the resource. + ResourceId *string `locationName:"resourceId" type:"string"` + + // The type of AWS resource. + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` +} + +// String returns the string representation +func (s ServiceQuotaExceededException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ServiceQuotaExceededException) GoString() string { + return s.String() +} + +func newErrorServiceQuotaExceededException(v protocol.ResponseMetadata) error { + return &ServiceQuotaExceededException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ServiceQuotaExceededException) Code() string { + return "ServiceQuotaExceededException" +} + +// Message returns the exception's message. +func (s *ServiceQuotaExceededException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ServiceQuotaExceededException) OrigErr() error { + return nil +} + +func (s *ServiceQuotaExceededException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ServiceQuotaExceededException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ServiceQuotaExceededException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Contains the revision and status of a package version. +type SuccessfulPackageVersionInfo struct { + _ struct{} `type:"structure"` + + // The revision of a package version. + Revision *string `locationName:"revision" type:"string"` + + // The status of a package version. Valid statuses are: + // + // * Published + // + // * Unfinished + // + // * Unlisted + // + // * Archived + // + // * Disposed + Status *string `locationName:"status" type:"string" enum:"PackageVersionStatus"` +} + +// String returns the string representation +func (s SuccessfulPackageVersionInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SuccessfulPackageVersionInfo) GoString() string { + return s.String() +} + +// SetRevision sets the Revision field's value. +func (s *SuccessfulPackageVersionInfo) SetRevision(v string) *SuccessfulPackageVersionInfo { + s.Revision = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *SuccessfulPackageVersionInfo) SetStatus(v string) *SuccessfulPackageVersionInfo { + s.Status = &v + return s +} + +// The operation did not succeed because too many requests are sent to the service. +type ThrottlingException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` + + // The time period, in seconds, to wait before retrying the request. + RetryAfterSeconds *int64 `location:"header" locationName:"Retry-After" type:"integer"` +} + +// String returns the string representation +func (s ThrottlingException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ThrottlingException) GoString() string { + return s.String() +} + +func newErrorThrottlingException(v protocol.ResponseMetadata) error { + return &ThrottlingException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ThrottlingException) Code() string { + return "ThrottlingException" +} + +// Message returns the exception's message. +func (s *ThrottlingException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ThrottlingException) OrigErr() error { + return nil +} + +func (s *ThrottlingException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ThrottlingException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ThrottlingException) RequestID() string { + return s.RespMetadata.RequestID +} + +type UpdatePackageVersionsStatusInput struct { + _ struct{} `type:"structure"` + + // The domain that contains the repository that contains the package versions + // with a status to be updated. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The package version’s expected status before it is updated. If expectedStatus + // is provided, the package version's status is updated only if its status at + // the time UpdatePackageVersionsStatus is called matches expectedStatus. + ExpectedStatus *string `locationName:"expectedStatus" type:"string" enum:"PackageVersionStatus"` + + // A format that specifies the type of the package with the statuses to update. + // The valid values are: + // + // * npm + // + // * pypi + // + // * maven + // + // Format is a required field + Format *string `location:"querystring" locationName:"format" type:"string" required:"true" enum:"PackageFormat"` + + // The namespace of the package. The package component that specifies its namespace + // depends on its type. For example: + // + // * The namespace of a Maven package is its groupId. + // + // * The namespace of an npm package is its scope. + // + // * A Python package does not contain a corresponding component, so Python + // packages do not have a namespace. + Namespace *string `location:"querystring" locationName:"namespace" min:"1" type:"string"` + + // The name of the package with the version statuses to update. + // + // Package is a required field + Package *string `location:"querystring" locationName:"package" min:"1" type:"string" required:"true"` + + // The repository that contains the package versions with the status you want + // to update. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` + + // The status you want to change the package version status to. + // + // TargetStatus is a required field + TargetStatus *string `locationName:"targetStatus" type:"string" required:"true" enum:"PackageVersionStatus"` + + // A map of package versions and package version revisions. The map key is the + // package version (for example, 3.5.2), and the map value is the package version + // revision. + VersionRevisions map[string]*string `locationName:"versionRevisions" type:"map"` + + // An array of strings that specify the versions of the package with the statuses + // to update. + // + // Versions is a required field + Versions []*string `locationName:"versions" type:"list" required:"true"` +} + +// String returns the string representation +func (s UpdatePackageVersionsStatusInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdatePackageVersionsStatusInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdatePackageVersionsStatusInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdatePackageVersionsStatusInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Format == nil { + invalidParams.Add(request.NewErrParamRequired("Format")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.Package == nil { + invalidParams.Add(request.NewErrParamRequired("Package")) + } + if s.Package != nil && len(*s.Package) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Package", 1)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + if s.TargetStatus == nil { + invalidParams.Add(request.NewErrParamRequired("TargetStatus")) + } + if s.Versions == nil { + invalidParams.Add(request.NewErrParamRequired("Versions")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *UpdatePackageVersionsStatusInput) SetDomain(v string) *UpdatePackageVersionsStatusInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *UpdatePackageVersionsStatusInput) SetDomainOwner(v string) *UpdatePackageVersionsStatusInput { + s.DomainOwner = &v + return s +} + +// SetExpectedStatus sets the ExpectedStatus field's value. +func (s *UpdatePackageVersionsStatusInput) SetExpectedStatus(v string) *UpdatePackageVersionsStatusInput { + s.ExpectedStatus = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *UpdatePackageVersionsStatusInput) SetFormat(v string) *UpdatePackageVersionsStatusInput { + s.Format = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *UpdatePackageVersionsStatusInput) SetNamespace(v string) *UpdatePackageVersionsStatusInput { + s.Namespace = &v + return s +} + +// SetPackage sets the Package field's value. +func (s *UpdatePackageVersionsStatusInput) SetPackage(v string) *UpdatePackageVersionsStatusInput { + s.Package = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *UpdatePackageVersionsStatusInput) SetRepository(v string) *UpdatePackageVersionsStatusInput { + s.Repository = &v + return s +} + +// SetTargetStatus sets the TargetStatus field's value. +func (s *UpdatePackageVersionsStatusInput) SetTargetStatus(v string) *UpdatePackageVersionsStatusInput { + s.TargetStatus = &v + return s +} + +// SetVersionRevisions sets the VersionRevisions field's value. +func (s *UpdatePackageVersionsStatusInput) SetVersionRevisions(v map[string]*string) *UpdatePackageVersionsStatusInput { + s.VersionRevisions = v + return s +} + +// SetVersions sets the Versions field's value. +func (s *UpdatePackageVersionsStatusInput) SetVersions(v []*string) *UpdatePackageVersionsStatusInput { + s.Versions = v + return s +} + +type UpdatePackageVersionsStatusOutput struct { + _ struct{} `type:"structure"` + + // A list of SuccessfulPackageVersionInfo objects, one for each package version + // with a status that successfully updated. + FailedVersions map[string]*PackageVersionError `locationName:"failedVersions" type:"map"` + + // A list of PackageVersionError objects, one for each package version with + // a status that failed to update. + SuccessfulVersions map[string]*SuccessfulPackageVersionInfo `locationName:"successfulVersions" type:"map"` +} + +// String returns the string representation +func (s UpdatePackageVersionsStatusOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdatePackageVersionsStatusOutput) GoString() string { + return s.String() +} + +// SetFailedVersions sets the FailedVersions field's value. +func (s *UpdatePackageVersionsStatusOutput) SetFailedVersions(v map[string]*PackageVersionError) *UpdatePackageVersionsStatusOutput { + s.FailedVersions = v + return s +} + +// SetSuccessfulVersions sets the SuccessfulVersions field's value. +func (s *UpdatePackageVersionsStatusOutput) SetSuccessfulVersions(v map[string]*SuccessfulPackageVersionInfo) *UpdatePackageVersionsStatusOutput { + s.SuccessfulVersions = v + return s +} + +type UpdateRepositoryInput struct { + _ struct{} `type:"structure"` + + // An updated repository description. + Description *string `locationName:"description" type:"string"` + + // The name of the domain associated with the repository to update. + // + // Domain is a required field + Domain *string `location:"querystring" locationName:"domain" min:"2" type:"string" required:"true"` + + // The 12-digit account number of the AWS account that owns the domain. It does + // not include dashes or spaces. + DomainOwner *string `location:"querystring" locationName:"domain-owner" min:"12" type:"string"` + + // The name of the repository to update. + // + // Repository is a required field + Repository *string `location:"querystring" locationName:"repository" min:"2" type:"string" required:"true"` + + // A list of upstream repositories to associate with the repository. The order + // of the upstream repositories in the list determines their priority order + // when AWS CodeArtifact looks for a requested package version. For more information, + // see Working with upstream repositories (https://docs.aws.amazon.com/codeartifact/latest/ug/repos-upstream.html). + Upstreams []*UpstreamRepository `locationName:"upstreams" type:"list"` +} + +// String returns the string representation +func (s UpdateRepositoryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateRepositoryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateRepositoryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateRepositoryInput"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 2)) + } + if s.DomainOwner != nil && len(*s.DomainOwner) < 12 { + invalidParams.Add(request.NewErrParamMinLen("DomainOwner", 12)) + } + if s.Repository == nil { + invalidParams.Add(request.NewErrParamRequired("Repository")) + } + if s.Repository != nil && len(*s.Repository) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Repository", 2)) + } + if s.Upstreams != nil { + for i, v := range s.Upstreams { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Upstreams", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *UpdateRepositoryInput) SetDescription(v string) *UpdateRepositoryInput { + s.Description = &v + return s +} + +// SetDomain sets the Domain field's value. +func (s *UpdateRepositoryInput) SetDomain(v string) *UpdateRepositoryInput { + s.Domain = &v + return s +} + +// SetDomainOwner sets the DomainOwner field's value. +func (s *UpdateRepositoryInput) SetDomainOwner(v string) *UpdateRepositoryInput { + s.DomainOwner = &v + return s +} + +// SetRepository sets the Repository field's value. +func (s *UpdateRepositoryInput) SetRepository(v string) *UpdateRepositoryInput { + s.Repository = &v + return s +} + +// SetUpstreams sets the Upstreams field's value. +func (s *UpdateRepositoryInput) SetUpstreams(v []*UpstreamRepository) *UpdateRepositoryInput { + s.Upstreams = v + return s +} + +type UpdateRepositoryOutput struct { + _ struct{} `type:"structure"` + + // The updated repository. + Repository *RepositoryDescription `locationName:"repository" type:"structure"` +} + +// String returns the string representation +func (s UpdateRepositoryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateRepositoryOutput) GoString() string { + return s.String() +} + +// SetRepository sets the Repository field's value. +func (s *UpdateRepositoryOutput) SetRepository(v *RepositoryDescription) *UpdateRepositoryOutput { + s.Repository = v + return s +} + +// Information about an upstream repository. A list of UpstreamRepository objects +// is an input parameter to CreateRepository (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_CreateRepository.html) +// and UpdateRepository (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_UpdateRepository.html). +type UpstreamRepository struct { + _ struct{} `type:"structure"` + + // The name of an upstream repository. + // + // RepositoryName is a required field + RepositoryName *string `locationName:"repositoryName" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s UpstreamRepository) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpstreamRepository) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpstreamRepository) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpstreamRepository"} + if s.RepositoryName == nil { + invalidParams.Add(request.NewErrParamRequired("RepositoryName")) + } + if s.RepositoryName != nil && len(*s.RepositoryName) < 2 { + invalidParams.Add(request.NewErrParamMinLen("RepositoryName", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetRepositoryName sets the RepositoryName field's value. +func (s *UpstreamRepository) SetRepositoryName(v string) *UpstreamRepository { + s.RepositoryName = &v + return s +} + +// Information about an upstream repository. +type UpstreamRepositoryInfo struct { + _ struct{} `type:"structure"` + + // The name of an upstream repository. + RepositoryName *string `locationName:"repositoryName" min:"2" type:"string"` +} + +// String returns the string representation +func (s UpstreamRepositoryInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpstreamRepositoryInfo) GoString() string { + return s.String() +} + +// SetRepositoryName sets the RepositoryName field's value. +func (s *UpstreamRepositoryInfo) SetRepositoryName(v string) *UpstreamRepositoryInfo { + s.RepositoryName = &v + return s +} + +// The operation did not succeed because a parameter in the request was sent +// with an invalid value. +type ValidationException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` + + Reason *string `locationName:"reason" type:"string" enum:"ValidationExceptionReason"` +} + +// String returns the string representation +func (s ValidationException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationException) GoString() string { + return s.String() +} + +func newErrorValidationException(v protocol.ResponseMetadata) error { + return &ValidationException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ValidationException) Code() string { + return "ValidationException" +} + +// Message returns the exception's message. +func (s *ValidationException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ValidationException) OrigErr() error { + return nil +} + +func (s *ValidationException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ValidationException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ValidationException) RequestID() string { + return s.RespMetadata.RequestID +} + +const ( + // DomainStatusActive is a DomainStatus enum value + DomainStatusActive = "Active" + + // DomainStatusDeleted is a DomainStatus enum value + DomainStatusDeleted = "Deleted" +) + +// DomainStatus_Values returns all elements of the DomainStatus enum +func DomainStatus_Values() []string { + return []string{ + DomainStatusActive, + DomainStatusDeleted, + } +} + +const ( + // ExternalConnectionStatusAvailable is a ExternalConnectionStatus enum value + ExternalConnectionStatusAvailable = "Available" +) + +// ExternalConnectionStatus_Values returns all elements of the ExternalConnectionStatus enum +func ExternalConnectionStatus_Values() []string { + return []string{ + ExternalConnectionStatusAvailable, + } +} + +const ( + // HashAlgorithmMd5 is a HashAlgorithm enum value + HashAlgorithmMd5 = "MD5" + + // HashAlgorithmSha1 is a HashAlgorithm enum value + HashAlgorithmSha1 = "SHA-1" + + // HashAlgorithmSha256 is a HashAlgorithm enum value + HashAlgorithmSha256 = "SHA-256" + + // HashAlgorithmSha512 is a HashAlgorithm enum value + HashAlgorithmSha512 = "SHA-512" +) + +// HashAlgorithm_Values returns all elements of the HashAlgorithm enum +func HashAlgorithm_Values() []string { + return []string{ + HashAlgorithmMd5, + HashAlgorithmSha1, + HashAlgorithmSha256, + HashAlgorithmSha512, + } +} + +const ( + // PackageFormatNpm is a PackageFormat enum value + PackageFormatNpm = "npm" + + // PackageFormatPypi is a PackageFormat enum value + PackageFormatPypi = "pypi" + + // PackageFormatMaven is a PackageFormat enum value + PackageFormatMaven = "maven" +) + +// PackageFormat_Values returns all elements of the PackageFormat enum +func PackageFormat_Values() []string { + return []string{ + PackageFormatNpm, + PackageFormatPypi, + PackageFormatMaven, + } +} + +const ( + // PackageVersionErrorCodeAlreadyExists is a PackageVersionErrorCode enum value + PackageVersionErrorCodeAlreadyExists = "ALREADY_EXISTS" + + // PackageVersionErrorCodeMismatchedRevision is a PackageVersionErrorCode enum value + PackageVersionErrorCodeMismatchedRevision = "MISMATCHED_REVISION" + + // PackageVersionErrorCodeMismatchedStatus is a PackageVersionErrorCode enum value + PackageVersionErrorCodeMismatchedStatus = "MISMATCHED_STATUS" + + // PackageVersionErrorCodeNotAllowed is a PackageVersionErrorCode enum value + PackageVersionErrorCodeNotAllowed = "NOT_ALLOWED" + + // PackageVersionErrorCodeNotFound is a PackageVersionErrorCode enum value + PackageVersionErrorCodeNotFound = "NOT_FOUND" + + // PackageVersionErrorCodeSkipped is a PackageVersionErrorCode enum value + PackageVersionErrorCodeSkipped = "SKIPPED" +) + +// PackageVersionErrorCode_Values returns all elements of the PackageVersionErrorCode enum +func PackageVersionErrorCode_Values() []string { + return []string{ + PackageVersionErrorCodeAlreadyExists, + PackageVersionErrorCodeMismatchedRevision, + PackageVersionErrorCodeMismatchedStatus, + PackageVersionErrorCodeNotAllowed, + PackageVersionErrorCodeNotFound, + PackageVersionErrorCodeSkipped, + } +} + +const ( + // PackageVersionSortTypePublishedTime is a PackageVersionSortType enum value + PackageVersionSortTypePublishedTime = "PUBLISHED_TIME" +) + +// PackageVersionSortType_Values returns all elements of the PackageVersionSortType enum +func PackageVersionSortType_Values() []string { + return []string{ + PackageVersionSortTypePublishedTime, + } +} + +const ( + // PackageVersionStatusPublished is a PackageVersionStatus enum value + PackageVersionStatusPublished = "Published" + + // PackageVersionStatusUnfinished is a PackageVersionStatus enum value + PackageVersionStatusUnfinished = "Unfinished" + + // PackageVersionStatusUnlisted is a PackageVersionStatus enum value + PackageVersionStatusUnlisted = "Unlisted" + + // PackageVersionStatusArchived is a PackageVersionStatus enum value + PackageVersionStatusArchived = "Archived" + + // PackageVersionStatusDisposed is a PackageVersionStatus enum value + PackageVersionStatusDisposed = "Disposed" + + // PackageVersionStatusDeleted is a PackageVersionStatus enum value + PackageVersionStatusDeleted = "Deleted" +) + +// PackageVersionStatus_Values returns all elements of the PackageVersionStatus enum +func PackageVersionStatus_Values() []string { + return []string{ + PackageVersionStatusPublished, + PackageVersionStatusUnfinished, + PackageVersionStatusUnlisted, + PackageVersionStatusArchived, + PackageVersionStatusDisposed, + PackageVersionStatusDeleted, + } +} + +const ( + // ResourceTypeDomain is a ResourceType enum value + ResourceTypeDomain = "domain" + + // ResourceTypeRepository is a ResourceType enum value + ResourceTypeRepository = "repository" + + // ResourceTypePackage is a ResourceType enum value + ResourceTypePackage = "package" + + // ResourceTypePackageVersion is a ResourceType enum value + ResourceTypePackageVersion = "package-version" + + // ResourceTypeAsset is a ResourceType enum value + ResourceTypeAsset = "asset" +) + +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeDomain, + ResourceTypeRepository, + ResourceTypePackage, + ResourceTypePackageVersion, + ResourceTypeAsset, + } +} + +const ( + // ValidationExceptionReasonCannotParse is a ValidationExceptionReason enum value + ValidationExceptionReasonCannotParse = "CANNOT_PARSE" + + // ValidationExceptionReasonEncryptionKeyError is a ValidationExceptionReason enum value + ValidationExceptionReasonEncryptionKeyError = "ENCRYPTION_KEY_ERROR" + + // ValidationExceptionReasonFieldValidationFailed is a ValidationExceptionReason enum value + ValidationExceptionReasonFieldValidationFailed = "FIELD_VALIDATION_FAILED" + + // ValidationExceptionReasonUnknownOperation is a ValidationExceptionReason enum value + ValidationExceptionReasonUnknownOperation = "UNKNOWN_OPERATION" + + // ValidationExceptionReasonOther is a ValidationExceptionReason enum value + ValidationExceptionReasonOther = "OTHER" +) + +// ValidationExceptionReason_Values returns all elements of the ValidationExceptionReason enum +func ValidationExceptionReason_Values() []string { + return []string{ + ValidationExceptionReasonCannotParse, + ValidationExceptionReasonEncryptionKeyError, + ValidationExceptionReasonFieldValidationFailed, + ValidationExceptionReasonUnknownOperation, + ValidationExceptionReasonOther, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/codeartifact/doc.go b/vendor/github.com/aws/aws-sdk-go/service/codeartifact/doc.go new file mode 100644 index 00000000000..6540dc7e9c6 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/codeartifact/doc.go @@ -0,0 +1,179 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package codeartifact provides the client and types for making API +// requests to CodeArtifact. +// +// AWS CodeArtifact is a fully managed artifact repository compatible with language-native +// package managers and build tools such as npm, Apache Maven, and pip. You +// can use CodeArtifact to share packages with development teams and pull packages. +// Packages can be pulled from both public and CodeArtifact repositories. You +// can also create an upstream relationship between a CodeArtifact repository +// and another repository, which effectively merges their contents from the +// point of view of a package manager client. +// +// AWS CodeArtifact Components +// +// Use the information in this guide to help you work with the following CodeArtifact +// components: +// +// * Repository: A CodeArtifact repository contains a set of package versions +// (https://docs.aws.amazon.com/codeartifact/latest/ug/welcome.html#welcome-concepts-package-version), +// each of which maps to a set of assets, or files. Repositories are polyglot, +// so a single repository can contain packages of any supported type. Each +// repository exposes endpoints for fetching and publishing packages using +// tools like the npm CLI, the Maven CLI ( mvn ), and pip . You can create +// up to 100 repositories per AWS account. +// +// * Domain: Repositories are aggregated into a higher-level entity known +// as a domain. All package assets and metadata are stored in the domain, +// but are consumed through repositories. A given package asset, such as +// a Maven JAR file, is stored once per domain, no matter how many repositories +// it's present in. All of the assets and metadata in a domain are encrypted +// with the same customer master key (CMK) stored in AWS Key Management Service +// (AWS KMS). Each repository is a member of a single domain and can't be +// moved to a different domain. The domain allows organizational policy to +// be applied across multiple repositories, such as which accounts can access +// repositories in the domain, and which public repositories can be used +// as sources of packages. Although an organization can have multiple domains, +// we recommend a single production domain that contains all published artifacts +// so that teams can find and share packages across their organization. +// +// * Package: A package is a bundle of software and the metadata required +// to resolve dependencies and install the software. CodeArtifact supports +// npm (https://docs.aws.amazon.com/codeartifact/latest/ug/using-npm.html), +// PyPI (https://docs.aws.amazon.com/codeartifact/latest/ug/using-python.html), +// and Maven (https://docs.aws.amazon.com/codeartifact/latest/ug/using-maven) +// package formats. In CodeArtifact, a package consists of: A name (for example, +// webpack is the name of a popular npm package) An optional namespace (for +// example, @types in @types/node) A set of versions (for example, 1.0.0, +// 1.0.1, 1.0.2, etc.) Package-level metadata (for example, npm tags) +// +// * Package version: A version of a package, such as @types/node 12.6.9. +// The version number format and semantics vary for different package formats. +// For example, npm package versions must conform to the Semantic Versioning +// specification (https://semver.org/). In CodeArtifact, a package version +// consists of the version identifier, metadata at the package version level, +// and a set of assets. +// +// * Upstream repository: One repository is upstream of another when the +// package versions in it can be accessed from the repository endpoint of +// the downstream repository, effectively merging the contents of the two +// repositories from the point of view of a client. CodeArtifact allows creating +// an upstream relationship between two repositories. +// +// * Asset: An individual file stored in CodeArtifact associated with a package +// version, such as an npm .tgz file or Maven POM and JAR files. +// +// CodeArtifact supports these operations: +// +// * AssociateExternalConnection: Adds an existing external connection to +// a repository. +// +// * CopyPackageVersions: Copies package versions from one repository to +// another repository in the same domain. +// +// * CreateDomain: Creates a domain +// +// * CreateRepository: Creates a CodeArtifact repository in a domain. +// +// * DeleteDomain: Deletes a domain. You cannot delete a domain that contains +// repositories. +// +// * DeleteDomainPermissionsPolicy: Deletes the resource policy that is set +// on a domain. +// +// * DeletePackageVersions: Deletes versions of a package. After a package +// has been deleted, it can be republished, but its assets and metadata cannot +// be restored because they have been permanently removed from storage. +// +// * DeleteRepository: Deletes a repository. +// +// * DeleteRepositoryPermissionsPolicy: Deletes the resource policy that +// is set on a repository. +// +// * DescribeDomain: Returns a DomainDescription object that contains information +// about the requested domain. +// +// * DescribePackageVersion: Returns a PackageVersionDescription (https://docs.aws.amazon.com/codeartifact/latest/APIReference/API_PackageVersionDescription.html) +// object that contains details about a package version. +// +// * DescribeRepository: Returns a RepositoryDescription object that contains +// detailed information about the requested repository. +// +// * DisposePackageVersions: Disposes versions of a package. A package version +// with the status Disposed cannot be restored because they have been permanently +// removed from storage. +// +// * DisassociateExternalConnection: Removes an existing external connection +// from a repository. +// +// * GetAuthorizationToken: Generates a temporary authorization token for +// accessing repositories in the domain. The token expires the authorization +// period has passed. The default authorization period is 12 hours and can +// be customized to any length with a maximum of 12 hours. +// +// * GetDomainPermissionsPolicy: Returns the policy of a resource that is +// attached to the specified domain. +// +// * GetPackageVersionAsset: Returns the contents of an asset that is in +// a package version. +// +// * GetPackageVersionReadme: Gets the readme file or descriptive text for +// a package version. +// +// * GetRepositoryEndpoint: Returns the endpoint of a repository for a specific +// package format. A repository has one endpoint for each package format: +// npm pypi maven +// +// * GetRepositoryPermissionsPolicy: Returns the resource policy that is +// set on a repository. +// +// * ListDomains: Returns a list of DomainSummary objects. Each returned +// DomainSummary object contains information about a domain. +// +// * ListPackages: Lists the packages in a repository. +// +// * ListPackageVersionAssets: Lists the assets for a given package version. +// +// * ListPackageVersionDependencies: Returns a list of the direct dependencies +// for a package version. +// +// * ListPackageVersions: Returns a list of package versions for a specified +// package in a repository. +// +// * ListRepositories: Returns a list of repositories owned by the AWS account +// that called this method. +// +// * ListRepositoriesInDomain: Returns a list of the repositories in a domain. +// +// * PutDomainPermissionsPolicy: Attaches a resource policy to a domain. +// +// * PutRepositoryPermissionsPolicy: Sets the resource policy on a repository +// that specifies permissions to access it. +// +// * UpdatePackageVersionsStatus: Updates the status of one or more versions +// of a package. +// +// * UpdateRepository: Updates the properties of a repository. +// +// See https://docs.aws.amazon.com/goto/WebAPI/codeartifact-2018-09-22 for more information on this service. +// +// See codeartifact package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/codeartifact/ +// +// Using the Client +// +// To contact CodeArtifact with the SDK use the New function to create +// a new service client. With that client you can make API requests to the service. +// These clients are safe to use concurrently. +// +// See the SDK's documentation for more information on how to use the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws.Config documentation for more information on configuring SDK clients. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the CodeArtifact client CodeArtifact for more +// information on creating client for this service. +// https://docs.aws.amazon.com/sdk-for-go/api/service/codeartifact/#New +package codeartifact diff --git a/vendor/github.com/aws/aws-sdk-go/service/codeartifact/errors.go b/vendor/github.com/aws/aws-sdk-go/service/codeartifact/errors.go new file mode 100644 index 00000000000..0faee781ff4 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/codeartifact/errors.go @@ -0,0 +1,66 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package codeartifact + +import ( + "github.com/aws/aws-sdk-go/private/protocol" +) + +const ( + + // ErrCodeAccessDeniedException for service response error code + // "AccessDeniedException". + // + // The operation did not succeed because of an unauthorized access attempt. + ErrCodeAccessDeniedException = "AccessDeniedException" + + // ErrCodeConflictException for service response error code + // "ConflictException". + // + // The operation did not succeed because prerequisites are not met. + ErrCodeConflictException = "ConflictException" + + // ErrCodeInternalServerException for service response error code + // "InternalServerException". + // + // The operation did not succeed because of an error that occurred inside AWS + // CodeArtifact. + ErrCodeInternalServerException = "InternalServerException" + + // ErrCodeResourceNotFoundException for service response error code + // "ResourceNotFoundException". + // + // The operation did not succeed because the resource requested is not found + // in the service. + ErrCodeResourceNotFoundException = "ResourceNotFoundException" + + // ErrCodeServiceQuotaExceededException for service response error code + // "ServiceQuotaExceededException". + // + // The operation did not succeed because it would have exceeded a service limit + // for your account. + ErrCodeServiceQuotaExceededException = "ServiceQuotaExceededException" + + // ErrCodeThrottlingException for service response error code + // "ThrottlingException". + // + // The operation did not succeed because too many requests are sent to the service. + ErrCodeThrottlingException = "ThrottlingException" + + // ErrCodeValidationException for service response error code + // "ValidationException". + // + // The operation did not succeed because a parameter in the request was sent + // with an invalid value. + ErrCodeValidationException = "ValidationException" +) + +var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ + "AccessDeniedException": newErrorAccessDeniedException, + "ConflictException": newErrorConflictException, + "InternalServerException": newErrorInternalServerException, + "ResourceNotFoundException": newErrorResourceNotFoundException, + "ServiceQuotaExceededException": newErrorServiceQuotaExceededException, + "ThrottlingException": newErrorThrottlingException, + "ValidationException": newErrorValidationException, +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/codeartifact/service.go b/vendor/github.com/aws/aws-sdk-go/service/codeartifact/service.go new file mode 100644 index 00000000000..3375d0c9f1f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/codeartifact/service.go @@ -0,0 +1,104 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package codeartifact + +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" + "github.com/aws/aws-sdk-go/private/protocol/restjson" +) + +// CodeArtifact provides the API operation methods for making requests to +// CodeArtifact. See this package's package overview docs +// for details on the service. +// +// CodeArtifact methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. +type CodeArtifact 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 = "codeartifact" // Name of service. + EndpointsID = ServiceName // ID to lookup a service endpoint with. + ServiceID = "codeartifact" // ServiceID is a unique identifier of a specific service. +) + +// New creates a new instance of the CodeArtifact 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: +// mySession := session.Must(session.NewSession()) +// +// // Create a CodeArtifact client from just a session. +// svc := codeartifact.New(mySession) +// +// // Create a CodeArtifact client with additional configuration +// svc := codeartifact.New(mySession, aws.NewConfig().WithRegion("us-west-2")) +func New(p client.ConfigProvider, cfgs ...*aws.Config) *CodeArtifact { + c := p.ClientConfig(EndpointsID, cfgs...) + if c.SigningNameDerived || len(c.SigningName) == 0 { + c.SigningName = "codeartifact" + } + return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) +} + +// newClient creates, initializes and returns a new service client instance. +func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *CodeArtifact { + svc := &CodeArtifact{ + Client: client.New( + cfg, + metadata.ClientInfo{ + ServiceName: ServiceName, + ServiceID: ServiceID, + SigningName: signingName, + SigningRegion: signingRegion, + PartitionID: partitionID, + Endpoint: endpoint, + APIVersion: "2018-09-22", + }, + handlers, + ), + } + + // Handlers + svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) + svc.Handlers.Build.PushBackNamed(restjson.BuildHandler) + svc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler) + svc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler) + svc.Handlers.UnmarshalError.PushBackNamed( + protocol.NewUnmarshalErrorHandler(restjson.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(), + ) + + // Run custom client initialization if present + if initClient != nil { + initClient(svc.Client) + } + + return svc +} + +// newRequest creates a new request for a CodeArtifact operation and runs any +// custom request initialization. +func (c *CodeArtifact) 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/codebuild/api.go b/vendor/github.com/aws/aws-sdk-go/service/codebuild/api.go index 48ec22795e9..5d32f44fdc6 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 @@ -92,6 +92,85 @@ func (c *CodeBuild) BatchDeleteBuildsWithContext(ctx aws.Context, input *BatchDe return out, req.Send() } +const opBatchGetBuildBatches = "BatchGetBuildBatches" + +// BatchGetBuildBatchesRequest generates a "aws/request.Request" representing the +// client's request for the BatchGetBuildBatches operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See BatchGetBuildBatches for more information on using the BatchGetBuildBatches +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the BatchGetBuildBatchesRequest method. +// req, resp := client.BatchGetBuildBatchesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetBuildBatches +func (c *CodeBuild) BatchGetBuildBatchesRequest(input *BatchGetBuildBatchesInput) (req *request.Request, output *BatchGetBuildBatchesOutput) { + op := &request.Operation{ + Name: opBatchGetBuildBatches, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &BatchGetBuildBatchesInput{} + } + + output = &BatchGetBuildBatchesOutput{} + req = c.newRequest(op, input, output) + return +} + +// BatchGetBuildBatches API operation for AWS CodeBuild. +// +// Retrieves information about one or more batch builds. +// +// Returns awserr.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 CodeBuild's +// API operation BatchGetBuildBatches for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input value that was provided is not valid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/BatchGetBuildBatches +func (c *CodeBuild) BatchGetBuildBatches(input *BatchGetBuildBatchesInput) (*BatchGetBuildBatchesOutput, error) { + req, out := c.BatchGetBuildBatchesRequest(input) + return out, req.Send() +} + +// BatchGetBuildBatchesWithContext is the same as BatchGetBuildBatches with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetBuildBatches for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) BatchGetBuildBatchesWithContext(ctx aws.Context, input *BatchGetBuildBatchesInput, opts ...request.Option) (*BatchGetBuildBatchesOutput, error) { + req, out := c.BatchGetBuildBatchesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opBatchGetBuilds = "BatchGetBuilds" // BatchGetBuildsRequest generates a "aws/request.Request" representing the @@ -680,6 +759,85 @@ func (c *CodeBuild) CreateWebhookWithContext(ctx aws.Context, input *CreateWebho return out, req.Send() } +const opDeleteBuildBatch = "DeleteBuildBatch" + +// DeleteBuildBatchRequest generates a "aws/request.Request" representing the +// client's request for the DeleteBuildBatch operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteBuildBatch for more information on using the DeleteBuildBatch +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteBuildBatchRequest method. +// req, resp := client.DeleteBuildBatchRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteBuildBatch +func (c *CodeBuild) DeleteBuildBatchRequest(input *DeleteBuildBatchInput) (req *request.Request, output *DeleteBuildBatchOutput) { + op := &request.Operation{ + Name: opDeleteBuildBatch, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteBuildBatchInput{} + } + + output = &DeleteBuildBatchOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteBuildBatch API operation for AWS CodeBuild. +// +// Deletes a batch build. +// +// Returns awserr.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 CodeBuild's +// API operation DeleteBuildBatch for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input value that was provided is not valid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DeleteBuildBatch +func (c *CodeBuild) DeleteBuildBatch(input *DeleteBuildBatchInput) (*DeleteBuildBatchOutput, error) { + req, out := c.DeleteBuildBatchRequest(input) + return out, req.Send() +} + +// DeleteBuildBatchWithContext is the same as DeleteBuildBatch with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBuildBatch for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DeleteBuildBatchWithContext(ctx aws.Context, input *DeleteBuildBatchInput, opts ...request.Option) (*DeleteBuildBatchOutput, error) { + req, out := c.DeleteBuildBatchRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteProject = "DeleteProject" // DeleteProjectRequest generates a "aws/request.Request" representing the @@ -1174,6 +1332,143 @@ func (c *CodeBuild) DeleteWebhookWithContext(ctx aws.Context, input *DeleteWebho return out, req.Send() } +const opDescribeCodeCoverages = "DescribeCodeCoverages" + +// DescribeCodeCoveragesRequest generates a "aws/request.Request" representing the +// client's request for the DescribeCodeCoverages operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeCodeCoverages for more information on using the DescribeCodeCoverages +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeCodeCoveragesRequest method. +// req, resp := client.DescribeCodeCoveragesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DescribeCodeCoverages +func (c *CodeBuild) DescribeCodeCoveragesRequest(input *DescribeCodeCoveragesInput) (req *request.Request, output *DescribeCodeCoveragesOutput) { + op := &request.Operation{ + Name: opDescribeCodeCoverages, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeCodeCoveragesInput{} + } + + output = &DescribeCodeCoveragesOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeCodeCoverages API operation for AWS CodeBuild. +// +// Retrieves one or more code coverage reports. +// +// Returns awserr.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 CodeBuild's +// API operation DescribeCodeCoverages for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input value that was provided is not valid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/DescribeCodeCoverages +func (c *CodeBuild) DescribeCodeCoverages(input *DescribeCodeCoveragesInput) (*DescribeCodeCoveragesOutput, error) { + req, out := c.DescribeCodeCoveragesRequest(input) + return out, req.Send() +} + +// DescribeCodeCoveragesWithContext is the same as DescribeCodeCoverages with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCodeCoverages for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeCodeCoveragesWithContext(ctx aws.Context, input *DescribeCodeCoveragesInput, opts ...request.Option) (*DescribeCodeCoveragesOutput, error) { + req, out := c.DescribeCodeCoveragesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeCodeCoveragesPages iterates over the pages of a DescribeCodeCoverages operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeCodeCoverages 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 DescribeCodeCoverages operation. +// pageNum := 0 +// err := client.DescribeCodeCoveragesPages(params, +// func(page *codebuild.DescribeCodeCoveragesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeBuild) DescribeCodeCoveragesPages(input *DescribeCodeCoveragesInput, fn func(*DescribeCodeCoveragesOutput, bool) bool) error { + return c.DescribeCodeCoveragesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCodeCoveragesPagesWithContext same as DescribeCodeCoveragesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeCodeCoveragesPagesWithContext(ctx aws.Context, input *DescribeCodeCoveragesInput, fn func(*DescribeCodeCoveragesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCodeCoveragesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCodeCoveragesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeCodeCoveragesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeTestCases = "DescribeTestCases" // DescribeTestCasesRequest generates a "aws/request.Request" representing the @@ -1205,6 +1500,12 @@ func (c *CodeBuild) DescribeTestCasesRequest(input *DescribeTestCasesInput) (req Name: opDescribeTestCases, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -1256,6 +1557,58 @@ func (c *CodeBuild) DescribeTestCasesWithContext(ctx aws.Context, input *Describ return out, req.Send() } +// DescribeTestCasesPages iterates over the pages of a DescribeTestCases operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeTestCases 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 DescribeTestCases operation. +// pageNum := 0 +// err := client.DescribeTestCasesPages(params, +// func(page *codebuild.DescribeTestCasesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeBuild) DescribeTestCasesPages(input *DescribeTestCasesInput, fn func(*DescribeTestCasesOutput, bool) bool) error { + return c.DescribeTestCasesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeTestCasesPagesWithContext same as DescribeTestCasesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeTestCasesPagesWithContext(ctx aws.Context, input *DescribeTestCasesInput, fn func(*DescribeTestCasesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeTestCasesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeTestCasesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeTestCasesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetResourcePolicy = "GetResourcePolicy" // GetResourcePolicyRequest generates a "aws/request.Request" representing the @@ -1508,96 +1861,431 @@ func (c *CodeBuild) InvalidateProjectCacheWithContext(ctx aws.Context, input *In return out, req.Send() } -const opListBuilds = "ListBuilds" +const opListBuildBatches = "ListBuildBatches" -// ListBuildsRequest generates a "aws/request.Request" representing the -// client's request for the ListBuilds operation. The "output" return +// ListBuildBatchesRequest generates a "aws/request.Request" representing the +// client's request for the ListBuildBatches operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListBuilds for more information on using the ListBuilds +// See ListBuildBatches for more information on using the ListBuildBatches // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListBuildsRequest method. -// req, resp := client.ListBuildsRequest(params) +// // Example sending a request using the ListBuildBatchesRequest method. +// req, resp := client.ListBuildBatchesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuilds -func (c *CodeBuild) ListBuildsRequest(input *ListBuildsInput) (req *request.Request, output *ListBuildsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildBatches +func (c *CodeBuild) ListBuildBatchesRequest(input *ListBuildBatchesInput) (req *request.Request, output *ListBuildBatchesOutput) { op := &request.Operation{ - Name: opListBuilds, + Name: opListBuildBatches, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { - input = &ListBuildsInput{} + input = &ListBuildBatchesInput{} } - output = &ListBuildsOutput{} + output = &ListBuildBatchesOutput{} req = c.newRequest(op, input, output) return } -// ListBuilds API operation for AWS CodeBuild. +// ListBuildBatches API operation for AWS CodeBuild. // -// Gets a list of build IDs, with each build ID representing a single build. +// Retrieves the identifiers of your build batches in the current region. // // Returns awserr.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 CodeBuild's -// API operation ListBuilds for usage and error information. +// API operation ListBuildBatches for usage and error information. // // Returned Error Types: // * InvalidInputException // The input value that was provided is not valid. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildBatches +func (c *CodeBuild) ListBuildBatches(input *ListBuildBatchesInput) (*ListBuildBatchesOutput, error) { + req, out := c.ListBuildBatchesRequest(input) return out, req.Send() } -// ListBuildsWithContext is the same as ListBuilds with the addition of +// ListBuildBatchesWithContext is the same as ListBuildBatches 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. +// See ListBuildBatches for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *CodeBuild) ListBuildBatchesWithContext(ctx aws.Context, input *ListBuildBatchesInput, opts ...request.Option) (*ListBuildBatchesOutput, error) { + req, out := c.ListBuildBatchesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opListBuildsForProject = "ListBuildsForProject" +// ListBuildBatchesPages iterates over the pages of a ListBuildBatches operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListBuildBatches 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 ListBuildBatches operation. +// pageNum := 0 +// err := client.ListBuildBatchesPages(params, +// func(page *codebuild.ListBuildBatchesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeBuild) ListBuildBatchesPages(input *ListBuildBatchesInput, fn func(*ListBuildBatchesOutput, bool) bool) error { + return c.ListBuildBatchesPagesWithContext(aws.BackgroundContext(), input, fn) +} -// ListBuildsForProjectRequest generates a "aws/request.Request" representing the -// client's request for the ListBuildsForProject operation. The "output" return +// ListBuildBatchesPagesWithContext same as ListBuildBatchesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListBuildBatchesPagesWithContext(ctx aws.Context, input *ListBuildBatchesInput, fn func(*ListBuildBatchesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListBuildBatchesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListBuildBatchesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListBuildBatchesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListBuildBatchesForProject = "ListBuildBatchesForProject" + +// ListBuildBatchesForProjectRequest generates a "aws/request.Request" representing the +// client's request for the ListBuildBatchesForProject operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListBuildsForProject for more information on using the ListBuildsForProject +// See ListBuildBatchesForProject for more information on using the ListBuildBatchesForProject +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListBuildBatchesForProjectRequest method. +// req, resp := client.ListBuildBatchesForProjectRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildBatchesForProject +func (c *CodeBuild) ListBuildBatchesForProjectRequest(input *ListBuildBatchesForProjectInput) (req *request.Request, output *ListBuildBatchesForProjectOutput) { + op := &request.Operation{ + Name: opListBuildBatchesForProject, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListBuildBatchesForProjectInput{} + } + + output = &ListBuildBatchesForProjectOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListBuildBatchesForProject API operation for AWS CodeBuild. +// +// Retrieves the identifiers of the build batches for a specific 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 CodeBuild's +// API operation ListBuildBatchesForProject for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input value that was provided is not valid. +// +// * ResourceNotFoundException +// The specified AWS resource cannot be found. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuildBatchesForProject +func (c *CodeBuild) ListBuildBatchesForProject(input *ListBuildBatchesForProjectInput) (*ListBuildBatchesForProjectOutput, error) { + req, out := c.ListBuildBatchesForProjectRequest(input) + return out, req.Send() +} + +// ListBuildBatchesForProjectWithContext is the same as ListBuildBatchesForProject with the addition of +// the ability to pass a context and additional request options. +// +// See ListBuildBatchesForProject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListBuildBatchesForProjectWithContext(ctx aws.Context, input *ListBuildBatchesForProjectInput, opts ...request.Option) (*ListBuildBatchesForProjectOutput, error) { + req, out := c.ListBuildBatchesForProjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListBuildBatchesForProjectPages iterates over the pages of a ListBuildBatchesForProject operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListBuildBatchesForProject 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 ListBuildBatchesForProject operation. +// pageNum := 0 +// err := client.ListBuildBatchesForProjectPages(params, +// func(page *codebuild.ListBuildBatchesForProjectOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeBuild) ListBuildBatchesForProjectPages(input *ListBuildBatchesForProjectInput, fn func(*ListBuildBatchesForProjectOutput, bool) bool) error { + return c.ListBuildBatchesForProjectPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListBuildBatchesForProjectPagesWithContext same as ListBuildBatchesForProjectPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListBuildBatchesForProjectPagesWithContext(ctx aws.Context, input *ListBuildBatchesForProjectInput, fn func(*ListBuildBatchesForProjectOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListBuildBatchesForProjectInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListBuildBatchesForProjectRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListBuildBatchesForProjectOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListBuilds = "ListBuilds" + +// ListBuildsRequest generates a "aws/request.Request" representing the +// client's request for the ListBuilds operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListBuilds for more information on using the ListBuilds +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListBuildsRequest method. +// req, resp := client.ListBuildsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListBuilds +func (c *CodeBuild) ListBuildsRequest(input *ListBuildsInput) (req *request.Request, output *ListBuildsOutput) { + op := &request.Operation{ + Name: opListBuilds, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListBuildsInput{} + } + + output = &ListBuildsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListBuilds API operation for AWS CodeBuild. +// +// Gets a list of build IDs, with each build ID representing a single build. +// +// Returns awserr.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 CodeBuild's +// API operation ListBuilds for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input value that was provided is not valid. +// +// See also, 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) + 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() +} + +// ListBuildsPages iterates over the pages of a ListBuilds operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListBuilds 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 ListBuilds operation. +// pageNum := 0 +// err := client.ListBuildsPages(params, +// func(page *codebuild.ListBuildsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeBuild) ListBuildsPages(input *ListBuildsInput, fn func(*ListBuildsOutput, bool) bool) error { + return c.ListBuildsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListBuildsPagesWithContext same as ListBuildsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListBuildsPagesWithContext(ctx aws.Context, input *ListBuildsInput, fn func(*ListBuildsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListBuildsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListBuildsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListBuildsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListBuildsForProject = "ListBuildsForProject" + +// ListBuildsForProjectRequest generates a "aws/request.Request" representing the +// client's request for the ListBuildsForProject operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListBuildsForProject for more information on using the ListBuildsForProject // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration @@ -1618,6 +2306,12 @@ func (c *CodeBuild) ListBuildsForProjectRequest(input *ListBuildsForProjectInput Name: opListBuildsForProject, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, } if input == nil { @@ -1670,6 +2364,58 @@ func (c *CodeBuild) ListBuildsForProjectWithContext(ctx aws.Context, input *List return out, req.Send() } +// ListBuildsForProjectPages iterates over the pages of a ListBuildsForProject operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListBuildsForProject 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 ListBuildsForProject operation. +// pageNum := 0 +// err := client.ListBuildsForProjectPages(params, +// func(page *codebuild.ListBuildsForProjectOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeBuild) ListBuildsForProjectPages(input *ListBuildsForProjectInput, fn func(*ListBuildsForProjectOutput, bool) bool) error { + return c.ListBuildsForProjectPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListBuildsForProjectPagesWithContext same as ListBuildsForProjectPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListBuildsForProjectPagesWithContext(ctx aws.Context, input *ListBuildsForProjectInput, fn func(*ListBuildsForProjectOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListBuildsForProjectInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListBuildsForProjectRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListBuildsForProjectOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListCuratedEnvironmentImages = "ListCuratedEnvironmentImages" // ListCuratedEnvironmentImagesRequest generates a "aws/request.Request" representing the @@ -1775,6 +2521,12 @@ func (c *CodeBuild) ListProjectsRequest(input *ListProjectsInput) (req *request. Name: opListProjects, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, } if input == nil { @@ -1824,6 +2576,58 @@ func (c *CodeBuild) ListProjectsWithContext(ctx aws.Context, input *ListProjects 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 *codebuild.ListProjectsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeBuild) 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 *CodeBuild) 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 + }, + } + + for p.Next() { + if !fn(p.Page().(*ListProjectsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListReportGroups = "ListReportGroups" // ListReportGroupsRequest generates a "aws/request.Request" representing the @@ -1855,6 +2659,12 @@ func (c *CodeBuild) ListReportGroupsRequest(input *ListReportGroupsInput) (req * Name: opListReportGroups, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -1903,6 +2713,58 @@ func (c *CodeBuild) ListReportGroupsWithContext(ctx aws.Context, input *ListRepo return out, req.Send() } +// ListReportGroupsPages iterates over the pages of a ListReportGroups operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListReportGroups 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 ListReportGroups operation. +// pageNum := 0 +// err := client.ListReportGroupsPages(params, +// func(page *codebuild.ListReportGroupsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeBuild) ListReportGroupsPages(input *ListReportGroupsInput, fn func(*ListReportGroupsOutput, bool) bool) error { + return c.ListReportGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListReportGroupsPagesWithContext same as ListReportGroupsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListReportGroupsPagesWithContext(ctx aws.Context, input *ListReportGroupsInput, fn func(*ListReportGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListReportGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListReportGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListReportGroupsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListReports = "ListReports" // ListReportsRequest generates a "aws/request.Request" representing the @@ -1934,6 +2796,12 @@ func (c *CodeBuild) ListReportsRequest(input *ListReportsInput) (req *request.Re Name: opListReports, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -1982,25 +2850,77 @@ func (c *CodeBuild) ListReportsWithContext(ctx aws.Context, input *ListReportsIn return out, req.Send() } -const opListReportsForReportGroup = "ListReportsForReportGroup" - -// ListReportsForReportGroupRequest generates a "aws/request.Request" representing the -// client's request for the ListReportsForReportGroup operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. +// ListReportsPages iterates over the pages of a ListReports operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. // -// See ListReportsForReportGroup for more information on using the ListReportsForReportGroup -// API call, and error handling. +// See ListReports method for more information on how to use this operation. // -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// Note: This operation can generate multiple requests to a service. // +// // Example iterating over at most 3 pages of a ListReports operation. +// pageNum := 0 +// err := client.ListReportsPages(params, +// func(page *codebuild.ListReportsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) // -// // Example sending a request using the ListReportsForReportGroupRequest method. -// req, resp := client.ListReportsForReportGroupRequest(params) +func (c *CodeBuild) ListReportsPages(input *ListReportsInput, fn func(*ListReportsOutput, bool) bool) error { + return c.ListReportsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListReportsPagesWithContext same as ListReportsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListReportsPagesWithContext(ctx aws.Context, input *ListReportsInput, fn func(*ListReportsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListReportsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListReportsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListReportsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListReportsForReportGroup = "ListReportsForReportGroup" + +// ListReportsForReportGroupRequest generates a "aws/request.Request" representing the +// client's request for the ListReportsForReportGroup operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListReportsForReportGroup for more information on using the ListReportsForReportGroup +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListReportsForReportGroupRequest method. +// req, resp := client.ListReportsForReportGroupRequest(params) // // err := req.Send() // if err == nil { // resp is now filled @@ -2013,6 +2933,12 @@ func (c *CodeBuild) ListReportsForReportGroupRequest(input *ListReportsForReport Name: opListReportsForReportGroup, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -2064,6 +2990,58 @@ func (c *CodeBuild) ListReportsForReportGroupWithContext(ctx aws.Context, input return out, req.Send() } +// ListReportsForReportGroupPages iterates over the pages of a ListReportsForReportGroup operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListReportsForReportGroup 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 ListReportsForReportGroup operation. +// pageNum := 0 +// err := client.ListReportsForReportGroupPages(params, +// func(page *codebuild.ListReportsForReportGroupOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeBuild) ListReportsForReportGroupPages(input *ListReportsForReportGroupInput, fn func(*ListReportsForReportGroupOutput, bool) bool) error { + return c.ListReportsForReportGroupPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListReportsForReportGroupPagesWithContext same as ListReportsForReportGroupPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListReportsForReportGroupPagesWithContext(ctx aws.Context, input *ListReportsForReportGroupInput, fn func(*ListReportsForReportGroupOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListReportsForReportGroupInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListReportsForReportGroupRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListReportsForReportGroupOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListSharedProjects = "ListSharedProjects" // ListSharedProjectsRequest generates a "aws/request.Request" representing the @@ -2095,6 +3073,12 @@ func (c *CodeBuild) ListSharedProjectsRequest(input *ListSharedProjectsInput) (r Name: opListSharedProjects, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -2143,6 +3127,58 @@ func (c *CodeBuild) ListSharedProjectsWithContext(ctx aws.Context, input *ListSh return out, req.Send() } +// ListSharedProjectsPages iterates over the pages of a ListSharedProjects operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListSharedProjects 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 ListSharedProjects operation. +// pageNum := 0 +// err := client.ListSharedProjectsPages(params, +// func(page *codebuild.ListSharedProjectsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeBuild) ListSharedProjectsPages(input *ListSharedProjectsInput, fn func(*ListSharedProjectsOutput, bool) bool) error { + return c.ListSharedProjectsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSharedProjectsPagesWithContext same as ListSharedProjectsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListSharedProjectsPagesWithContext(ctx aws.Context, input *ListSharedProjectsInput, fn func(*ListSharedProjectsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSharedProjectsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSharedProjectsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListSharedProjectsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListSharedReportGroups = "ListSharedReportGroups" // ListSharedReportGroupsRequest generates a "aws/request.Request" representing the @@ -2174,6 +3210,12 @@ func (c *CodeBuild) ListSharedReportGroupsRequest(input *ListSharedReportGroupsI Name: opListSharedReportGroups, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -2222,6 +3264,58 @@ func (c *CodeBuild) ListSharedReportGroupsWithContext(ctx aws.Context, input *Li return out, req.Send() } +// ListSharedReportGroupsPages iterates over the pages of a ListSharedReportGroups operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListSharedReportGroups 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 ListSharedReportGroups operation. +// pageNum := 0 +// err := client.ListSharedReportGroupsPages(params, +// func(page *codebuild.ListSharedReportGroupsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeBuild) ListSharedReportGroupsPages(input *ListSharedReportGroupsInput, fn func(*ListSharedReportGroupsOutput, bool) bool) error { + return c.ListSharedReportGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSharedReportGroupsPagesWithContext same as ListSharedReportGroupsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListSharedReportGroupsPagesWithContext(ctx aws.Context, input *ListSharedReportGroupsInput, fn func(*ListSharedReportGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSharedReportGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSharedReportGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListSharedReportGroupsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListSourceCredentials = "ListSourceCredentials" // ListSourceCredentialsRequest generates a "aws/request.Request" representing the @@ -2274,6 +3368,11 @@ func (c *CodeBuild) ListSourceCredentialsRequest(input *ListSourceCredentialsInp // // See the AWS API reference guide for AWS CodeBuild's // API operation ListSourceCredentials for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input value that was provided is not valid. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/ListSourceCredentials func (c *CodeBuild) ListSourceCredentials(input *ListSourceCredentialsInput) (*ListSourceCredentialsOutput, error) { req, out := c.ListSourceCredentialsRequest(input) @@ -2378,58 +3477,58 @@ func (c *CodeBuild) PutResourcePolicyWithContext(ctx aws.Context, input *PutReso return out, req.Send() } -const opStartBuild = "StartBuild" +const opRetryBuild = "RetryBuild" -// StartBuildRequest generates a "aws/request.Request" representing the -// client's request for the StartBuild operation. The "output" return +// RetryBuildRequest generates a "aws/request.Request" representing the +// client's request for the RetryBuild operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See StartBuild for more information on using the StartBuild +// See RetryBuild for more information on using the RetryBuild // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the StartBuildRequest method. -// req, resp := client.StartBuildRequest(params) +// // Example sending a request using the RetryBuildRequest method. +// req, resp := client.RetryBuildRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StartBuild -func (c *CodeBuild) StartBuildRequest(input *StartBuildInput) (req *request.Request, output *StartBuildOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/RetryBuild +func (c *CodeBuild) RetryBuildRequest(input *RetryBuildInput) (req *request.Request, output *RetryBuildOutput) { op := &request.Operation{ - Name: opStartBuild, + Name: opRetryBuild, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &StartBuildInput{} + input = &RetryBuildInput{} } - output = &StartBuildOutput{} + output = &RetryBuildOutput{} req = c.newRequest(op, input, output) return } -// StartBuild API operation for AWS CodeBuild. +// RetryBuild API operation for AWS CodeBuild. // -// Starts running a build. +// Restarts a build. // // Returns awserr.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 CodeBuild's -// API operation StartBuild for usage and error information. +// API operation RetryBuild for usage and error information. // // Returned Error Types: // * InvalidInputException @@ -2441,80 +3540,80 @@ func (c *CodeBuild) StartBuildRequest(input *StartBuildInput) (req *request.Requ // * AccountLimitExceededException // An AWS service limit was exceeded for the calling AWS account. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/RetryBuild +func (c *CodeBuild) RetryBuild(input *RetryBuildInput) (*RetryBuildOutput, error) { + req, out := c.RetryBuildRequest(input) return out, req.Send() } -// StartBuildWithContext is the same as StartBuild with the addition of +// RetryBuildWithContext is the same as RetryBuild 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. +// See RetryBuild for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *CodeBuild) RetryBuildWithContext(ctx aws.Context, input *RetryBuildInput, opts ...request.Option) (*RetryBuildOutput, error) { + req, out := c.RetryBuildRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opStopBuild = "StopBuild" +const opRetryBuildBatch = "RetryBuildBatch" -// StopBuildRequest generates a "aws/request.Request" representing the -// client's request for the StopBuild operation. The "output" return +// RetryBuildBatchRequest generates a "aws/request.Request" representing the +// client's request for the RetryBuildBatch operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See StopBuild for more information on using the StopBuild +// See RetryBuildBatch for more information on using the RetryBuildBatch // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the StopBuildRequest method. -// req, resp := client.StopBuildRequest(params) +// // Example sending a request using the RetryBuildBatchRequest method. +// req, resp := client.RetryBuildBatchRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StopBuild -func (c *CodeBuild) StopBuildRequest(input *StopBuildInput) (req *request.Request, output *StopBuildOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/RetryBuildBatch +func (c *CodeBuild) RetryBuildBatchRequest(input *RetryBuildBatchInput) (req *request.Request, output *RetryBuildBatchOutput) { op := &request.Operation{ - Name: opStopBuild, + Name: opRetryBuildBatch, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &StopBuildInput{} + input = &RetryBuildBatchInput{} } - output = &StopBuildOutput{} + output = &RetryBuildBatchOutput{} req = c.newRequest(op, input, output) return } -// StopBuild API operation for AWS CodeBuild. +// RetryBuildBatch API operation for AWS CodeBuild. // -// Attempts to stop running a build. +// Restarts a batch build. // // Returns awserr.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 CodeBuild's -// API operation StopBuild for usage and error information. +// API operation RetryBuildBatch for usage and error information. // // Returned Error Types: // * InvalidInputException @@ -2523,80 +3622,80 @@ func (c *CodeBuild) StopBuildRequest(input *StopBuildInput) (req *request.Reques // * ResourceNotFoundException // The specified AWS resource cannot be found. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/RetryBuildBatch +func (c *CodeBuild) RetryBuildBatch(input *RetryBuildBatchInput) (*RetryBuildBatchOutput, error) { + req, out := c.RetryBuildBatchRequest(input) return out, req.Send() } -// StopBuildWithContext is the same as StopBuild with the addition of +// RetryBuildBatchWithContext is the same as RetryBuildBatch 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. +// See RetryBuildBatch for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *CodeBuild) RetryBuildBatchWithContext(ctx aws.Context, input *RetryBuildBatchInput, opts ...request.Option) (*RetryBuildBatchOutput, error) { + req, out := c.RetryBuildBatchRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateProject = "UpdateProject" +const opStartBuild = "StartBuild" -// UpdateProjectRequest generates a "aws/request.Request" representing the -// client's request for the UpdateProject operation. The "output" return +// StartBuildRequest generates a "aws/request.Request" representing the +// client's request for the StartBuild operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateProject for more information on using the UpdateProject +// See StartBuild for more information on using the StartBuild // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateProjectRequest method. -// req, resp := client.UpdateProjectRequest(params) +// // Example sending a request using the StartBuildRequest method. +// req, resp := client.StartBuildRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateProject -func (c *CodeBuild) UpdateProjectRequest(input *UpdateProjectInput) (req *request.Request, output *UpdateProjectOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StartBuild +func (c *CodeBuild) StartBuildRequest(input *StartBuildInput) (req *request.Request, output *StartBuildOutput) { op := &request.Operation{ - Name: opUpdateProject, + Name: opStartBuild, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateProjectInput{} + input = &StartBuildInput{} } - output = &UpdateProjectOutput{} + output = &StartBuildOutput{} req = c.newRequest(op, input, output) return } -// UpdateProject API operation for AWS CodeBuild. +// StartBuild API operation for AWS CodeBuild. // -// Changes the settings of a build project. +// Starts running a build. // // Returns awserr.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 CodeBuild's -// API operation UpdateProject for usage and error information. +// API operation StartBuild for usage and error information. // // Returned Error Types: // * InvalidInputException @@ -2605,80 +3704,83 @@ func (c *CodeBuild) UpdateProjectRequest(input *UpdateProjectInput) (req *reques // * ResourceNotFoundException // The specified AWS resource cannot be found. // -// See also, 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) +// * AccountLimitExceededException +// An AWS service limit was exceeded for the calling AWS account. +// +// See also, 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) return out, req.Send() } -// UpdateProjectWithContext is the same as UpdateProject with the addition of +// StartBuildWithContext is the same as StartBuild 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. +// 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) UpdateProjectWithContext(ctx aws.Context, input *UpdateProjectInput, opts ...request.Option) (*UpdateProjectOutput, error) { - req, out := c.UpdateProjectRequest(input) +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 opUpdateReportGroup = "UpdateReportGroup" +const opStartBuildBatch = "StartBuildBatch" -// UpdateReportGroupRequest generates a "aws/request.Request" representing the -// client's request for the UpdateReportGroup operation. The "output" return +// StartBuildBatchRequest generates a "aws/request.Request" representing the +// client's request for the StartBuildBatch operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateReportGroup for more information on using the UpdateReportGroup +// See StartBuildBatch for more information on using the StartBuildBatch // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateReportGroupRequest method. -// req, resp := client.UpdateReportGroupRequest(params) +// // Example sending a request using the StartBuildBatchRequest method. +// req, resp := client.StartBuildBatchRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateReportGroup -func (c *CodeBuild) UpdateReportGroupRequest(input *UpdateReportGroupInput) (req *request.Request, output *UpdateReportGroupOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StartBuildBatch +func (c *CodeBuild) StartBuildBatchRequest(input *StartBuildBatchInput) (req *request.Request, output *StartBuildBatchOutput) { op := &request.Operation{ - Name: opUpdateReportGroup, + Name: opStartBuildBatch, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateReportGroupInput{} + input = &StartBuildBatchInput{} } - output = &UpdateReportGroupOutput{} + output = &StartBuildBatchOutput{} req = c.newRequest(op, input, output) return } -// UpdateReportGroup API operation for AWS CodeBuild. +// StartBuildBatch API operation for AWS CodeBuild. // -// Updates a report group. +// Starts a batch build for 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 CodeBuild's -// API operation UpdateReportGroup for usage and error information. +// API operation StartBuildBatch for usage and error information. // // Returned Error Types: // * InvalidInputException @@ -2687,82 +3789,80 @@ func (c *CodeBuild) UpdateReportGroupRequest(input *UpdateReportGroupInput) (req // * ResourceNotFoundException // The specified AWS resource cannot be found. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateReportGroup -func (c *CodeBuild) UpdateReportGroup(input *UpdateReportGroupInput) (*UpdateReportGroupOutput, error) { - req, out := c.UpdateReportGroupRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StartBuildBatch +func (c *CodeBuild) StartBuildBatch(input *StartBuildBatchInput) (*StartBuildBatchOutput, error) { + req, out := c.StartBuildBatchRequest(input) return out, req.Send() } -// UpdateReportGroupWithContext is the same as UpdateReportGroup with the addition of +// StartBuildBatchWithContext is the same as StartBuildBatch with the addition of // the ability to pass a context and additional request options. // -// See UpdateReportGroup for details on how to use this API operation. +// See StartBuildBatch for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) UpdateReportGroupWithContext(ctx aws.Context, input *UpdateReportGroupInput, opts ...request.Option) (*UpdateReportGroupOutput, error) { - req, out := c.UpdateReportGroupRequest(input) +func (c *CodeBuild) StartBuildBatchWithContext(ctx aws.Context, input *StartBuildBatchInput, opts ...request.Option) (*StartBuildBatchOutput, error) { + req, out := c.StartBuildBatchRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateWebhook = "UpdateWebhook" +const opStopBuild = "StopBuild" -// UpdateWebhookRequest generates a "aws/request.Request" representing the -// client's request for the UpdateWebhook operation. The "output" return +// StopBuildRequest generates a "aws/request.Request" representing the +// client's request for the StopBuild operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateWebhook for more information on using the UpdateWebhook +// See StopBuild for more information on using the StopBuild // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateWebhookRequest method. -// req, resp := client.UpdateWebhookRequest(params) +// // Example sending a request using the StopBuildRequest method. +// req, resp := client.StopBuildRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateWebhook -func (c *CodeBuild) UpdateWebhookRequest(input *UpdateWebhookInput) (req *request.Request, output *UpdateWebhookOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StopBuild +func (c *CodeBuild) StopBuildRequest(input *StopBuildInput) (req *request.Request, output *StopBuildOutput) { op := &request.Operation{ - Name: opUpdateWebhook, + Name: opStopBuild, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateWebhookInput{} + input = &StopBuildInput{} } - output = &UpdateWebhookOutput{} + output = &StopBuildOutput{} req = c.newRequest(op, input, output) return } -// UpdateWebhook API operation for AWS CodeBuild. -// -// Updates the webhook associated with an AWS CodeBuild build project. +// StopBuild API operation for AWS CodeBuild. // -// If you use Bitbucket for your repository, rotateSecret is ignored. +// Attempts to stop running a build. // // Returns awserr.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 CodeBuild's -// API operation UpdateWebhook for usage and error information. +// API operation StopBuild for usage and error information. // // Returned Error Types: // * InvalidInputException @@ -2771,335 +3871,2228 @@ func (c *CodeBuild) UpdateWebhookRequest(input *UpdateWebhookInput) (req *reques // * ResourceNotFoundException // The specified AWS resource cannot be found. // -// * OAuthProviderException -// There was a problem with the underlying OAuth provider. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateWebhook -func (c *CodeBuild) UpdateWebhook(input *UpdateWebhookInput) (*UpdateWebhookOutput, error) { - req, out := c.UpdateWebhookRequest(input) +// See also, 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) return out, req.Send() } -// UpdateWebhookWithContext is the same as UpdateWebhook with the addition of +// StopBuildWithContext is the same as StopBuild with the addition of // the ability to pass a context and additional request options. // -// See UpdateWebhook for details on how to use this API operation. +// 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) UpdateWebhookWithContext(ctx aws.Context, input *UpdateWebhookInput, opts ...request.Option) (*UpdateWebhookOutput, error) { - req, out := c.UpdateWebhookRequest(input) +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() } -// An AWS service limit was exceeded for the calling AWS account. -type AccountLimitExceededException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"message" type:"string"` -} +const opStopBuildBatch = "StopBuildBatch" + +// StopBuildBatchRequest generates a "aws/request.Request" representing the +// client's request for the StopBuildBatch operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See StopBuildBatch for more information on using the StopBuildBatch +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the StopBuildBatchRequest method. +// req, resp := client.StopBuildBatchRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StopBuildBatch +func (c *CodeBuild) StopBuildBatchRequest(input *StopBuildBatchInput) (req *request.Request, output *StopBuildBatchOutput) { + op := &request.Operation{ + Name: opStopBuildBatch, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &StopBuildBatchInput{} + } + + output = &StopBuildBatchOutput{} + req = c.newRequest(op, input, output) + return +} + +// StopBuildBatch API operation for AWS CodeBuild. +// +// Stops a running batch build. +// +// Returns awserr.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 CodeBuild's +// API operation StopBuildBatch for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input value that was provided is not valid. +// +// * ResourceNotFoundException +// The specified AWS resource cannot be found. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/StopBuildBatch +func (c *CodeBuild) StopBuildBatch(input *StopBuildBatchInput) (*StopBuildBatchOutput, error) { + req, out := c.StopBuildBatchRequest(input) + return out, req.Send() +} + +// StopBuildBatchWithContext is the same as StopBuildBatch with the addition of +// the ability to pass a context and additional request options. +// +// See StopBuildBatch for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) StopBuildBatchWithContext(ctx aws.Context, input *StopBuildBatchInput, opts ...request.Option) (*StopBuildBatchOutput, error) { + req, out := c.StopBuildBatchRequest(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 will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateProject for more information on using the UpdateProject +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateProjectRequest method. +// req, resp := client.UpdateProjectRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateProject +func (c *CodeBuild) 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 CodeBuild. +// +// Changes the settings of a build 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 CodeBuild's +// API operation UpdateProject for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input value that was provided is not valid. +// +// * ResourceNotFoundException +// The specified AWS resource cannot be found. +// +// See also, 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) + 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() +} + +const opUpdateReportGroup = "UpdateReportGroup" + +// UpdateReportGroupRequest generates a "aws/request.Request" representing the +// client's request for the UpdateReportGroup operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateReportGroup for more information on using the UpdateReportGroup +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateReportGroupRequest method. +// req, resp := client.UpdateReportGroupRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateReportGroup +func (c *CodeBuild) UpdateReportGroupRequest(input *UpdateReportGroupInput) (req *request.Request, output *UpdateReportGroupOutput) { + op := &request.Operation{ + Name: opUpdateReportGroup, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateReportGroupInput{} + } + + output = &UpdateReportGroupOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateReportGroup API operation for AWS CodeBuild. +// +// Updates a report group. +// +// Returns awserr.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 CodeBuild's +// API operation UpdateReportGroup for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input value that was provided is not valid. +// +// * ResourceNotFoundException +// The specified AWS resource cannot be found. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateReportGroup +func (c *CodeBuild) UpdateReportGroup(input *UpdateReportGroupInput) (*UpdateReportGroupOutput, error) { + req, out := c.UpdateReportGroupRequest(input) + return out, req.Send() +} + +// UpdateReportGroupWithContext is the same as UpdateReportGroup with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateReportGroup for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) UpdateReportGroupWithContext(ctx aws.Context, input *UpdateReportGroupInput, opts ...request.Option) (*UpdateReportGroupOutput, error) { + req, out := c.UpdateReportGroupRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateWebhook = "UpdateWebhook" + +// UpdateWebhookRequest generates a "aws/request.Request" representing the +// client's request for the UpdateWebhook operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateWebhook for more information on using the UpdateWebhook +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateWebhookRequest method. +// req, resp := client.UpdateWebhookRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateWebhook +func (c *CodeBuild) UpdateWebhookRequest(input *UpdateWebhookInput) (req *request.Request, output *UpdateWebhookOutput) { + op := &request.Operation{ + Name: opUpdateWebhook, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateWebhookInput{} + } + + output = &UpdateWebhookOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateWebhook API operation for AWS CodeBuild. +// +// Updates the webhook associated with an AWS CodeBuild build project. +// +// If you use Bitbucket for your repository, rotateSecret is ignored. +// +// Returns awserr.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 CodeBuild's +// API operation UpdateWebhook for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input value that was provided is not valid. +// +// * ResourceNotFoundException +// The specified AWS resource cannot be found. +// +// * OAuthProviderException +// There was a problem with the underlying OAuth provider. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codebuild-2016-10-06/UpdateWebhook +func (c *CodeBuild) UpdateWebhook(input *UpdateWebhookInput) (*UpdateWebhookOutput, error) { + req, out := c.UpdateWebhookRequest(input) + return out, req.Send() +} + +// UpdateWebhookWithContext is the same as UpdateWebhook with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateWebhook for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) UpdateWebhookWithContext(ctx aws.Context, input *UpdateWebhookInput, opts ...request.Option) (*UpdateWebhookOutput, error) { + req, out := c.UpdateWebhookRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// An AWS service limit was exceeded for the calling AWS account. +type AccountLimitExceededException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s AccountLimitExceededException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccountLimitExceededException) GoString() string { + return s.String() +} + +func newErrorAccountLimitExceededException(v protocol.ResponseMetadata) error { + return &AccountLimitExceededException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *AccountLimitExceededException) Code() string { + return "AccountLimitExceededException" +} + +// Message returns the exception's message. +func (s *AccountLimitExceededException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *AccountLimitExceededException) OrigErr() error { + return nil +} + +func (s *AccountLimitExceededException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *AccountLimitExceededException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *AccountLimitExceededException) RequestID() string { + return s.RespMetadata.RequestID +} + +type BatchDeleteBuildsInput struct { + _ struct{} `type:"structure"` + + // The IDs of the builds to delete. + // + // Ids is a required field + Ids []*string `locationName:"ids" min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s BatchDeleteBuildsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchDeleteBuildsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *BatchDeleteBuildsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "BatchDeleteBuildsInput"} + if s.Ids == nil { + invalidParams.Add(request.NewErrParamRequired("Ids")) + } + if s.Ids != nil && len(s.Ids) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Ids", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIds sets the Ids field's value. +func (s *BatchDeleteBuildsInput) SetIds(v []*string) *BatchDeleteBuildsInput { + s.Ids = v + return s +} + +type BatchDeleteBuildsOutput struct { + _ struct{} `type:"structure"` + + // The IDs of the builds that were successfully deleted. + BuildsDeleted []*string `locationName:"buildsDeleted" min:"1" type:"list"` + + // Information about any builds that could not be successfully deleted. + BuildsNotDeleted []*BuildNotDeleted `locationName:"buildsNotDeleted" type:"list"` +} + +// String returns the string representation +func (s BatchDeleteBuildsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchDeleteBuildsOutput) GoString() string { + return s.String() +} + +// SetBuildsDeleted sets the BuildsDeleted field's value. +func (s *BatchDeleteBuildsOutput) SetBuildsDeleted(v []*string) *BatchDeleteBuildsOutput { + s.BuildsDeleted = v + return s +} + +// SetBuildsNotDeleted sets the BuildsNotDeleted field's value. +func (s *BatchDeleteBuildsOutput) SetBuildsNotDeleted(v []*BuildNotDeleted) *BatchDeleteBuildsOutput { + s.BuildsNotDeleted = v + return s +} + +type BatchGetBuildBatchesInput struct { + _ struct{} `type:"structure"` + + // An array that contains the batch build identifiers to retrieve. + // + // Ids is a required field + Ids []*string `locationName:"ids" type:"list" required:"true"` +} + +// String returns the string representation +func (s BatchGetBuildBatchesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchGetBuildBatchesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *BatchGetBuildBatchesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "BatchGetBuildBatchesInput"} + if s.Ids == nil { + invalidParams.Add(request.NewErrParamRequired("Ids")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIds sets the Ids field's value. +func (s *BatchGetBuildBatchesInput) SetIds(v []*string) *BatchGetBuildBatchesInput { + s.Ids = v + return s +} + +type BatchGetBuildBatchesOutput struct { + _ struct{} `type:"structure"` + + // An array of BuildBatch objects that represent the retrieved batch builds. + BuildBatches []*BuildBatch `locationName:"buildBatches" type:"list"` + + // An array that contains the identifiers of any batch builds that are not found. + BuildBatchesNotFound []*string `locationName:"buildBatchesNotFound" type:"list"` +} + +// String returns the string representation +func (s BatchGetBuildBatchesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchGetBuildBatchesOutput) GoString() string { + return s.String() +} + +// SetBuildBatches sets the BuildBatches field's value. +func (s *BatchGetBuildBatchesOutput) SetBuildBatches(v []*BuildBatch) *BatchGetBuildBatchesOutput { + s.BuildBatches = v + return s +} + +// SetBuildBatchesNotFound sets the BuildBatchesNotFound field's value. +func (s *BatchGetBuildBatchesOutput) SetBuildBatchesNotFound(v []*string) *BatchGetBuildBatchesOutput { + s.BuildBatchesNotFound = v + return s +} + +type BatchGetBuildsInput struct { + _ struct{} `type:"structure"` + + // The IDs of the builds. + // + // Ids is a required field + Ids []*string `locationName:"ids" min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s BatchGetBuildsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchGetBuildsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *BatchGetBuildsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "BatchGetBuildsInput"} + if s.Ids == nil { + invalidParams.Add(request.NewErrParamRequired("Ids")) + } + if s.Ids != nil && len(s.Ids) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Ids", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIds sets the Ids field's value. +func (s *BatchGetBuildsInput) SetIds(v []*string) *BatchGetBuildsInput { + s.Ids = v + return s +} + +type BatchGetBuildsOutput struct { + _ struct{} `type:"structure"` + + // Information about the requested builds. + Builds []*Build `locationName:"builds" type:"list"` + + // The IDs of builds for which information could not be found. + BuildsNotFound []*string `locationName:"buildsNotFound" min:"1" type:"list"` +} + +// String returns the string representation +func (s BatchGetBuildsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchGetBuildsOutput) GoString() string { + return s.String() +} + +// SetBuilds sets the Builds field's value. +func (s *BatchGetBuildsOutput) SetBuilds(v []*Build) *BatchGetBuildsOutput { + s.Builds = v + return s +} + +// SetBuildsNotFound sets the BuildsNotFound field's value. +func (s *BatchGetBuildsOutput) SetBuildsNotFound(v []*string) *BatchGetBuildsOutput { + s.BuildsNotFound = v + return s +} + +type BatchGetProjectsInput struct { + _ struct{} `type:"structure"` + + // The names or ARNs of the build projects. To get information about a project + // shared with your AWS account, its ARN must be specified. You cannot specify + // a shared project using its name. + // + // Names is a required field + Names []*string `locationName:"names" min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s BatchGetProjectsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchGetProjectsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *BatchGetProjectsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "BatchGetProjectsInput"} + if s.Names == nil { + invalidParams.Add(request.NewErrParamRequired("Names")) + } + if s.Names != nil && len(s.Names) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Names", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetNames sets the Names field's value. +func (s *BatchGetProjectsInput) SetNames(v []*string) *BatchGetProjectsInput { + s.Names = v + return s +} + +type BatchGetProjectsOutput struct { + _ struct{} `type:"structure"` + + // Information about the requested build projects. + Projects []*Project `locationName:"projects" type:"list"` + + // The names of build projects for which information could not be found. + ProjectsNotFound []*string `locationName:"projectsNotFound" min:"1" type:"list"` +} + +// String returns the string representation +func (s BatchGetProjectsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchGetProjectsOutput) GoString() string { + return s.String() +} + +// SetProjects sets the Projects field's value. +func (s *BatchGetProjectsOutput) SetProjects(v []*Project) *BatchGetProjectsOutput { + s.Projects = v + return s +} + +// SetProjectsNotFound sets the ProjectsNotFound field's value. +func (s *BatchGetProjectsOutput) SetProjectsNotFound(v []*string) *BatchGetProjectsOutput { + s.ProjectsNotFound = v + return s +} + +type BatchGetReportGroupsInput struct { + _ struct{} `type:"structure"` + + // An array of report group ARNs that identify the report groups to return. + // + // ReportGroupArns is a required field + ReportGroupArns []*string `locationName:"reportGroupArns" min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s BatchGetReportGroupsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchGetReportGroupsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *BatchGetReportGroupsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "BatchGetReportGroupsInput"} + if s.ReportGroupArns == nil { + invalidParams.Add(request.NewErrParamRequired("ReportGroupArns")) + } + if s.ReportGroupArns != nil && len(s.ReportGroupArns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ReportGroupArns", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetReportGroupArns sets the ReportGroupArns field's value. +func (s *BatchGetReportGroupsInput) SetReportGroupArns(v []*string) *BatchGetReportGroupsInput { + s.ReportGroupArns = v + return s +} + +type BatchGetReportGroupsOutput struct { + _ struct{} `type:"structure"` + + // The array of report groups returned by BatchGetReportGroups. + ReportGroups []*ReportGroup `locationName:"reportGroups" min:"1" type:"list"` + + // An array of ARNs passed to BatchGetReportGroups that are not associated with + // a ReportGroup. + ReportGroupsNotFound []*string `locationName:"reportGroupsNotFound" min:"1" type:"list"` +} + +// String returns the string representation +func (s BatchGetReportGroupsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchGetReportGroupsOutput) GoString() string { + return s.String() +} + +// SetReportGroups sets the ReportGroups field's value. +func (s *BatchGetReportGroupsOutput) SetReportGroups(v []*ReportGroup) *BatchGetReportGroupsOutput { + s.ReportGroups = v + return s +} + +// SetReportGroupsNotFound sets the ReportGroupsNotFound field's value. +func (s *BatchGetReportGroupsOutput) SetReportGroupsNotFound(v []*string) *BatchGetReportGroupsOutput { + s.ReportGroupsNotFound = v + return s +} + +type BatchGetReportsInput struct { + _ struct{} `type:"structure"` + + // An array of ARNs that identify the Report objects to return. + // + // ReportArns is a required field + ReportArns []*string `locationName:"reportArns" min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s BatchGetReportsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchGetReportsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *BatchGetReportsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "BatchGetReportsInput"} + if s.ReportArns == nil { + invalidParams.Add(request.NewErrParamRequired("ReportArns")) + } + if s.ReportArns != nil && len(s.ReportArns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ReportArns", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetReportArns sets the ReportArns field's value. +func (s *BatchGetReportsInput) SetReportArns(v []*string) *BatchGetReportsInput { + s.ReportArns = v + return s +} + +type BatchGetReportsOutput struct { + _ struct{} `type:"structure"` + + // The array of Report objects returned by BatchGetReports. + Reports []*Report `locationName:"reports" min:"1" type:"list"` + + // An array of ARNs passed to BatchGetReportGroups that are not associated with + // a Report. + ReportsNotFound []*string `locationName:"reportsNotFound" min:"1" type:"list"` +} + +// String returns the string representation +func (s BatchGetReportsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchGetReportsOutput) GoString() string { + return s.String() +} + +// SetReports sets the Reports field's value. +func (s *BatchGetReportsOutput) SetReports(v []*Report) *BatchGetReportsOutput { + s.Reports = v + return s +} + +// SetReportsNotFound sets the ReportsNotFound field's value. +func (s *BatchGetReportsOutput) SetReportsNotFound(v []*string) *BatchGetReportsOutput { + s.ReportsNotFound = v + return s +} + +// Specifies restrictions for the batch build. +type BatchRestrictions struct { + _ struct{} `type:"structure"` + + // An array of strings that specify the compute types that are allowed for the + // batch build. See Build environment compute types (https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-compute-types.html) + // in the AWS CodeBuild User Guide for these values. + ComputeTypesAllowed []*string `locationName:"computeTypesAllowed" type:"list"` + + // Specifies the maximum number of builds allowed. + MaximumBuildsAllowed *int64 `locationName:"maximumBuildsAllowed" type:"integer"` +} + +// String returns the string representation +func (s BatchRestrictions) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchRestrictions) GoString() string { + return s.String() +} + +// SetComputeTypesAllowed sets the ComputeTypesAllowed field's value. +func (s *BatchRestrictions) SetComputeTypesAllowed(v []*string) *BatchRestrictions { + s.ComputeTypesAllowed = v + return s +} + +// SetMaximumBuildsAllowed sets the MaximumBuildsAllowed field's value. +func (s *BatchRestrictions) SetMaximumBuildsAllowed(v int64) *BatchRestrictions { + s.MaximumBuildsAllowed = &v + return s +} + +// Information about a build. +type Build struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the build. + Arn *string `locationName:"arn" min:"1" type:"string"` + + // Information about the output artifacts for the build. + Artifacts *BuildArtifacts `locationName:"artifacts" type:"structure"` + + // The ARN of the batch build that this build is a member of, if applicable. + BuildBatchArn *string `locationName:"buildBatchArn" type:"string"` + + // Whether the build is complete. True if complete; otherwise, false. + BuildComplete *bool `locationName:"buildComplete" type:"boolean"` + + // The number of the build. For each project, the buildNumber of its first build + // is 1. The buildNumber of each subsequent build is incremented by 1. If a + // build is deleted, the buildNumber of other builds does not change. + BuildNumber *int64 `locationName:"buildNumber" type:"long"` + + // The current status of the build. Valid values include: + // + // * FAILED: The build failed. + // + // * FAULT: The build faulted. + // + // * IN_PROGRESS: The build is still in progress. + // + // * STOPPED: The build stopped. + // + // * SUCCEEDED: The build succeeded. + // + // * TIMED_OUT: The build timed out. + BuildStatus *string `locationName:"buildStatus" type:"string" enum:"StatusType"` + + // Information about the cache for the build. + Cache *ProjectCache `locationName:"cache" type:"structure"` + + // The current build phase. + CurrentPhase *string `locationName:"currentPhase" type:"string"` + + // Contains information about the debug session for this build. + DebugSession *DebugSession `locationName:"debugSession" type:"structure"` + + // The AWS Key Management Service (AWS KMS) customer master key (CMK) to be + // used for encrypting the build output artifacts. + // + // You can use a cross-account KMS key to encrypt the build output artifacts + // if your service role has permission to that key. + // + // You can specify either the Amazon Resource Name (ARN) of the CMK or, if available, + // the CMK's alias (using the format alias/alias-name ). + EncryptionKey *string `locationName:"encryptionKey" min:"1" type:"string"` + + // When the build process ended, expressed in Unix time format. + EndTime *time.Time `locationName:"endTime" type:"timestamp"` + + // Information about the build environment for this build. + Environment *ProjectEnvironment `locationName:"environment" type:"structure"` + + // A list of exported environment variables for this build. + ExportedEnvironmentVariables []*ExportedEnvironmentVariable `locationName:"exportedEnvironmentVariables" type:"list"` + + // An array of ProjectFileSystemLocation objects for a CodeBuild build project. + // A ProjectFileSystemLocation object specifies the identifier, location, mountOptions, + // mountPoint, and type of a file system created using Amazon Elastic File System. + FileSystemLocations []*ProjectFileSystemLocation `locationName:"fileSystemLocations" type:"list"` + + // The unique ID for the build. + Id *string `locationName:"id" min:"1" type:"string"` + + // The entity that started the build. Valid values include: + // + // * If AWS CodePipeline started the build, the pipeline's name (for example, + // codepipeline/my-demo-pipeline). + // + // * If an AWS Identity and Access Management (IAM) user started the build, + // the user's name (for example, MyUserName). + // + // * If the Jenkins plugin for AWS CodeBuild started the build, the string + // CodeBuild-Jenkins-Plugin. + Initiator *string `locationName:"initiator" type:"string"` + + // Information about the build's logs in Amazon CloudWatch Logs. + Logs *LogsLocation `locationName:"logs" type:"structure"` + + // Describes a network interface. + NetworkInterface *NetworkInterface `locationName:"networkInterface" type:"structure"` + + // Information about all previous build phases that are complete and information + // about any current build phase that is not yet complete. + Phases []*BuildPhase `locationName:"phases" type:"list"` + + // The name of the AWS CodeBuild project. + ProjectName *string `locationName:"projectName" min:"1" type:"string"` + + // The number of minutes a build is allowed to be queued before it times out. + QueuedTimeoutInMinutes *int64 `locationName:"queuedTimeoutInMinutes" type:"integer"` + + // An array of the ARNs associated with this build's reports. + ReportArns []*string `locationName:"reportArns" type:"list"` + + // An identifier for the version of this build's source code. + // + // * For AWS CodeCommit, GitHub, GitHub Enterprise, and BitBucket, the commit + // ID. + // + // * For AWS CodePipeline, the source revision provided by AWS CodePipeline. + // + // * For Amazon Simple Storage Service (Amazon S3), this does not apply. + ResolvedSourceVersion *string `locationName:"resolvedSourceVersion" min:"1" type:"string"` + + // An array of ProjectArtifacts objects. + SecondaryArtifacts []*BuildArtifacts `locationName:"secondaryArtifacts" type:"list"` + + // An array of ProjectSourceVersion objects. Each ProjectSourceVersion must + // be one of: + // + // * For AWS CodeCommit: the commit ID, branch, or Git tag to use. + // + // * For GitHub: the commit ID, pull request ID, branch name, or tag name + // that corresponds to the version of the source code you want to build. + // If a pull request ID is specified, it must use the format pr/pull-request-ID + // (for example, pr/25). If a branch name is specified, the branch's HEAD + // commit ID is used. If not specified, the default branch's HEAD commit + // ID is used. + // + // * For Bitbucket: the commit ID, branch name, or tag name that corresponds + // to the version of the source code you want to build. If a branch name + // is specified, the branch's HEAD commit ID is used. If not specified, the + // default branch's HEAD commit ID is used. + // + // * For Amazon Simple Storage Service (Amazon S3): the version ID of the + // object that represents the build input ZIP file to use. + SecondarySourceVersions []*ProjectSourceVersion `locationName:"secondarySourceVersions" type:"list"` + + // An array of ProjectSource objects. + SecondarySources []*ProjectSource `locationName:"secondarySources" type:"list"` + + // The name of a service role used for this build. + ServiceRole *string `locationName:"serviceRole" min:"1" type:"string"` + + // Information about the source code to be built. + Source *ProjectSource `locationName:"source" type:"structure"` + + // Any version identifier for the version of the source code to be built. If + // sourceVersion is specified at the project level, then this sourceVersion + // (at the build level) takes precedence. + // + // For more information, see Source Version Sample with CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/sample-source-version.html) + // in the AWS CodeBuild User Guide. + SourceVersion *string `locationName:"sourceVersion" min:"1" type:"string"` + + // When the build process started, expressed in Unix time format. + StartTime *time.Time `locationName:"startTime" type:"timestamp"` + + // How long, in minutes, for AWS CodeBuild to wait before timing out this build + // if it does not get marked as completed. + TimeoutInMinutes *int64 `locationName:"timeoutInMinutes" type:"integer"` + + // If your AWS CodeBuild project accesses resources in an Amazon VPC, you provide + // this parameter that identifies the VPC ID and the list of security group + // IDs and subnet IDs. The security groups and subnets must belong to the same + // VPC. You must provide at least one security group and one subnet ID. + VpcConfig *VpcConfig `locationName:"vpcConfig" type:"structure"` +} + +// String returns the string representation +func (s Build) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Build) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Build) SetArn(v string) *Build { + s.Arn = &v + return s +} + +// SetArtifacts sets the Artifacts field's value. +func (s *Build) SetArtifacts(v *BuildArtifacts) *Build { + s.Artifacts = v + return s +} + +// SetBuildBatchArn sets the BuildBatchArn field's value. +func (s *Build) SetBuildBatchArn(v string) *Build { + s.BuildBatchArn = &v + return s +} + +// SetBuildComplete sets the BuildComplete field's value. +func (s *Build) SetBuildComplete(v bool) *Build { + s.BuildComplete = &v + return s +} + +// SetBuildNumber sets the BuildNumber field's value. +func (s *Build) SetBuildNumber(v int64) *Build { + s.BuildNumber = &v + return s +} + +// SetBuildStatus sets the BuildStatus field's value. +func (s *Build) SetBuildStatus(v string) *Build { + s.BuildStatus = &v + return s +} + +// SetCache sets the Cache field's value. +func (s *Build) SetCache(v *ProjectCache) *Build { + s.Cache = v + return s +} + +// SetCurrentPhase sets the CurrentPhase field's value. +func (s *Build) SetCurrentPhase(v string) *Build { + s.CurrentPhase = &v + return s +} + +// SetDebugSession sets the DebugSession field's value. +func (s *Build) SetDebugSession(v *DebugSession) *Build { + s.DebugSession = v + return s +} + +// SetEncryptionKey sets the EncryptionKey field's value. +func (s *Build) SetEncryptionKey(v string) *Build { + s.EncryptionKey = &v + return s +} + +// SetEndTime sets the EndTime field's value. +func (s *Build) SetEndTime(v time.Time) *Build { + s.EndTime = &v + return s +} + +// SetEnvironment sets the Environment field's value. +func (s *Build) SetEnvironment(v *ProjectEnvironment) *Build { + s.Environment = v + return s +} + +// SetExportedEnvironmentVariables sets the ExportedEnvironmentVariables field's value. +func (s *Build) SetExportedEnvironmentVariables(v []*ExportedEnvironmentVariable) *Build { + s.ExportedEnvironmentVariables = v + return s +} + +// SetFileSystemLocations sets the FileSystemLocations field's value. +func (s *Build) SetFileSystemLocations(v []*ProjectFileSystemLocation) *Build { + s.FileSystemLocations = v + return s +} + +// SetId sets the Id field's value. +func (s *Build) SetId(v string) *Build { + s.Id = &v + return s +} + +// SetInitiator sets the Initiator field's value. +func (s *Build) SetInitiator(v string) *Build { + s.Initiator = &v + return s +} + +// SetLogs sets the Logs field's value. +func (s *Build) SetLogs(v *LogsLocation) *Build { + s.Logs = v + return s +} + +// SetNetworkInterface sets the NetworkInterface field's value. +func (s *Build) SetNetworkInterface(v *NetworkInterface) *Build { + s.NetworkInterface = v + return s +} + +// SetPhases sets the Phases field's value. +func (s *Build) SetPhases(v []*BuildPhase) *Build { + s.Phases = v + return s +} + +// SetProjectName sets the ProjectName field's value. +func (s *Build) SetProjectName(v string) *Build { + s.ProjectName = &v + return s +} + +// SetQueuedTimeoutInMinutes sets the QueuedTimeoutInMinutes field's value. +func (s *Build) SetQueuedTimeoutInMinutes(v int64) *Build { + s.QueuedTimeoutInMinutes = &v + return s +} + +// SetReportArns sets the ReportArns field's value. +func (s *Build) SetReportArns(v []*string) *Build { + s.ReportArns = v + return s +} + +// SetResolvedSourceVersion sets the ResolvedSourceVersion field's value. +func (s *Build) SetResolvedSourceVersion(v string) *Build { + s.ResolvedSourceVersion = &v + return s +} + +// SetSecondaryArtifacts sets the SecondaryArtifacts field's value. +func (s *Build) SetSecondaryArtifacts(v []*BuildArtifacts) *Build { + s.SecondaryArtifacts = v + return s +} + +// SetSecondarySourceVersions sets the SecondarySourceVersions field's value. +func (s *Build) SetSecondarySourceVersions(v []*ProjectSourceVersion) *Build { + s.SecondarySourceVersions = v + return s +} + +// SetSecondarySources sets the SecondarySources field's value. +func (s *Build) SetSecondarySources(v []*ProjectSource) *Build { + s.SecondarySources = v + return s +} + +// SetServiceRole sets the ServiceRole field's value. +func (s *Build) SetServiceRole(v string) *Build { + s.ServiceRole = &v + return s +} + +// SetSource sets the Source field's value. +func (s *Build) SetSource(v *ProjectSource) *Build { + s.Source = v + return s +} + +// SetSourceVersion sets the SourceVersion field's value. +func (s *Build) SetSourceVersion(v string) *Build { + s.SourceVersion = &v + return s +} + +// SetStartTime sets the StartTime field's value. +func (s *Build) SetStartTime(v time.Time) *Build { + s.StartTime = &v + return s +} + +// SetTimeoutInMinutes sets the TimeoutInMinutes field's value. +func (s *Build) SetTimeoutInMinutes(v int64) *Build { + s.TimeoutInMinutes = &v + return s +} + +// SetVpcConfig sets the VpcConfig field's value. +func (s *Build) SetVpcConfig(v *VpcConfig) *Build { + s.VpcConfig = v + return s +} + +// Information about build output artifacts. +type BuildArtifacts struct { + _ struct{} `type:"structure"` + + // An identifier for this artifact definition. + ArtifactIdentifier *string `locationName:"artifactIdentifier" type:"string"` + + // Information that tells you if encryption for build artifacts is disabled. + EncryptionDisabled *bool `locationName:"encryptionDisabled" type:"boolean"` + + // Information about the location of the build artifacts. + Location *string `locationName:"location" type:"string"` + + // The MD5 hash of the build artifact. + // + // You can use this hash along with a checksum tool to confirm file integrity + // and authenticity. + // + // This value is available only if the build project's packaging value is set + // to ZIP. + Md5sum *string `locationName:"md5sum" type:"string"` + + // If this flag is set, a name specified in the buildspec file overrides the + // artifact name. The name specified in a buildspec file is calculated at build + // time and uses the Shell Command Language. For example, you can append a date + // and time to your artifact name so that it is always unique. + OverrideArtifactName *bool `locationName:"overrideArtifactName" type:"boolean"` + + // The SHA-256 hash of the build artifact. + // + // You can use this hash along with a checksum tool to confirm file integrity + // and authenticity. + // + // This value is available only if the build project's packaging value is set + // to ZIP. + Sha256sum *string `locationName:"sha256sum" type:"string"` +} + +// String returns the string representation +func (s BuildArtifacts) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BuildArtifacts) GoString() string { + return s.String() +} + +// SetArtifactIdentifier sets the ArtifactIdentifier field's value. +func (s *BuildArtifacts) SetArtifactIdentifier(v string) *BuildArtifacts { + s.ArtifactIdentifier = &v + return s +} + +// SetEncryptionDisabled sets the EncryptionDisabled field's value. +func (s *BuildArtifacts) SetEncryptionDisabled(v bool) *BuildArtifacts { + s.EncryptionDisabled = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *BuildArtifacts) SetLocation(v string) *BuildArtifacts { + s.Location = &v + return s +} + +// SetMd5sum sets the Md5sum field's value. +func (s *BuildArtifacts) SetMd5sum(v string) *BuildArtifacts { + s.Md5sum = &v + return s +} + +// SetOverrideArtifactName sets the OverrideArtifactName field's value. +func (s *BuildArtifacts) SetOverrideArtifactName(v bool) *BuildArtifacts { + s.OverrideArtifactName = &v + return s +} + +// SetSha256sum sets the Sha256sum field's value. +func (s *BuildArtifacts) SetSha256sum(v string) *BuildArtifacts { + s.Sha256sum = &v + return s +} + +// Contains information about a batch build. +type BuildBatch struct { + _ struct{} `type:"structure"` + + // The ARN of the batch build. + Arn *string `locationName:"arn" min:"1" type:"string"` + + // A BuildArtifacts object the defines the build artifacts for this batch build. + Artifacts *BuildArtifacts `locationName:"artifacts" type:"structure"` + + // Contains configuration information about a batch build project. + BuildBatchConfig *ProjectBuildBatchConfig `locationName:"buildBatchConfig" type:"structure"` + + // The number of the batch build. For each project, the buildBatchNumber of + // its first batch build is 1. The buildBatchNumber of each subsequent batch + // build is incremented by 1. If a batch build is deleted, the buildBatchNumber + // of other batch builds does not change. + BuildBatchNumber *int64 `locationName:"buildBatchNumber" type:"long"` + + // The status of the batch build. + BuildBatchStatus *string `locationName:"buildBatchStatus" type:"string" enum:"StatusType"` + + // An array of BuildGroup objects that define the build groups for the batch + // build. + BuildGroups []*BuildGroup `locationName:"buildGroups" type:"list"` + + // Specifies the maximum amount of time, in minutes, that the build in a batch + // must be completed in. + BuildTimeoutInMinutes *int64 `locationName:"buildTimeoutInMinutes" type:"integer"` + + // Information about the cache for the build project. + Cache *ProjectCache `locationName:"cache" type:"structure"` + + // Indicates if the batch build is complete. + Complete *bool `locationName:"complete" type:"boolean"` + + // The current phase of the batch build. + CurrentPhase *string `locationName:"currentPhase" type:"string"` + + // The AWS Key Management Service (AWS KMS) customer master key (CMK) to be + // used for encrypting the batch build output artifacts. + // + // You can use a cross-account KMS key to encrypt the build output artifacts + // if your service role has permission to that key. + // + // You can specify either the Amazon Resource Name (ARN) of the CMK or, if available, + // the CMK's alias (using the format alias/alias-name ). + EncryptionKey *string `locationName:"encryptionKey" min:"1" type:"string"` + + // The date and time that the batch build ended. + EndTime *time.Time `locationName:"endTime" type:"timestamp"` + + // Information about the build environment of the build project. + Environment *ProjectEnvironment `locationName:"environment" type:"structure"` + + // An array of ProjectFileSystemLocation objects for the batch build project. + // A ProjectFileSystemLocation object specifies the identifier, location, mountOptions, + // mountPoint, and type of a file system created using Amazon Elastic File System. + FileSystemLocations []*ProjectFileSystemLocation `locationName:"fileSystemLocations" type:"list"` + + // The identifier of the batch build. + Id *string `locationName:"id" min:"1" type:"string"` + + // The entity that started the batch build. Valid values include: + // + // * If AWS CodePipeline started the build, the pipeline's name (for example, + // codepipeline/my-demo-pipeline). + // + // * If an AWS Identity and Access Management (IAM) user started the build, + // the user's name. + // + // * If the Jenkins plugin for AWS CodeBuild started the build, the string + // CodeBuild-Jenkins-Plugin. + Initiator *string `locationName:"initiator" type:"string"` + + // Information about logs for a build project. These can be logs in Amazon CloudWatch + // Logs, built in a specified S3 bucket, or both. + LogConfig *LogsConfig `locationName:"logConfig" type:"structure"` + + // An array of BuildBatchPhase objects the specify the phases of the batch build. + Phases []*BuildBatchPhase `locationName:"phases" type:"list"` + + // The name of the batch build project. + ProjectName *string `locationName:"projectName" min:"1" type:"string"` + + // Specifies the amount of time, in minutes, that the batch build is allowed + // to be queued before it times out. + QueuedTimeoutInMinutes *int64 `locationName:"queuedTimeoutInMinutes" type:"integer"` + + // The identifier of the resolved version of this batch build's source code. + // + // * For AWS CodeCommit, GitHub, GitHub Enterprise, and BitBucket, the commit + // ID. + // + // * For AWS CodePipeline, the source revision provided by AWS CodePipeline. + // + // * For Amazon Simple Storage Service (Amazon S3), this does not apply. + ResolvedSourceVersion *string `locationName:"resolvedSourceVersion" min:"1" type:"string"` + + // An array of BuildArtifacts objects the define the build artifacts for this + // batch build. + SecondaryArtifacts []*BuildArtifacts `locationName:"secondaryArtifacts" type:"list"` + + // An array of ProjectSourceVersion objects. Each ProjectSourceVersion must + // be one of: + // + // * For AWS CodeCommit: the commit ID, branch, or Git tag to use. + // + // * For GitHub: the commit ID, pull request ID, branch name, or tag name + // that corresponds to the version of the source code you want to build. + // If a pull request ID is specified, it must use the format pr/pull-request-ID + // (for example, pr/25). If a branch name is specified, the branch's HEAD + // commit ID is used. If not specified, the default branch's HEAD commit + // ID is used. + // + // * For Bitbucket: the commit ID, branch name, or tag name that corresponds + // to the version of the source code you want to build. If a branch name + // is specified, the branch's HEAD commit ID is used. If not specified, the + // default branch's HEAD commit ID is used. + // + // * For Amazon Simple Storage Service (Amazon S3): the version ID of the + // object that represents the build input ZIP file to use. + SecondarySourceVersions []*ProjectSourceVersion `locationName:"secondarySourceVersions" type:"list"` + + // An array of ProjectSource objects that define the sources for the batch build. + SecondarySources []*ProjectSource `locationName:"secondarySources" type:"list"` + + // The name of a service role used for builds in the batch. + ServiceRole *string `locationName:"serviceRole" min:"1" type:"string"` + + // Information about the build input source code for the build project. + Source *ProjectSource `locationName:"source" type:"structure"` + + // The identifier of the version of the source code to be built. + SourceVersion *string `locationName:"sourceVersion" min:"1" type:"string"` + + // The date and time that the batch build started. + StartTime *time.Time `locationName:"startTime" type:"timestamp"` + + // Information about the VPC configuration that AWS CodeBuild accesses. + VpcConfig *VpcConfig `locationName:"vpcConfig" type:"structure"` +} // String returns the string representation -func (s AccountLimitExceededException) String() string { +func (s BuildBatch) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AccountLimitExceededException) GoString() string { +func (s BuildBatch) GoString() string { return s.String() } -func newErrorAccountLimitExceededException(v protocol.ResponseMetadata) error { - return &AccountLimitExceededException{ - RespMetadata: v, - } +// SetArn sets the Arn field's value. +func (s *BuildBatch) SetArn(v string) *BuildBatch { + s.Arn = &v + return s } -// Code returns the exception type name. -func (s *AccountLimitExceededException) Code() string { - return "AccountLimitExceededException" +// SetArtifacts sets the Artifacts field's value. +func (s *BuildBatch) SetArtifacts(v *BuildArtifacts) *BuildBatch { + s.Artifacts = v + return s } -// Message returns the exception's message. -func (s *AccountLimitExceededException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" +// SetBuildBatchConfig sets the BuildBatchConfig field's value. +func (s *BuildBatch) SetBuildBatchConfig(v *ProjectBuildBatchConfig) *BuildBatch { + s.BuildBatchConfig = v + return s } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *AccountLimitExceededException) OrigErr() error { - return nil +// SetBuildBatchNumber sets the BuildBatchNumber field's value. +func (s *BuildBatch) SetBuildBatchNumber(v int64) *BuildBatch { + s.BuildBatchNumber = &v + return s } -func (s *AccountLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +// SetBuildBatchStatus sets the BuildBatchStatus field's value. +func (s *BuildBatch) SetBuildBatchStatus(v string) *BuildBatch { + s.BuildBatchStatus = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *AccountLimitExceededException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetBuildGroups sets the BuildGroups field's value. +func (s *BuildBatch) SetBuildGroups(v []*BuildGroup) *BuildBatch { + s.BuildGroups = v + return s } -// RequestID returns the service's response RequestID for request. -func (s *AccountLimitExceededException) RequestID() string { - return s.RespMetadata.RequestID +// SetBuildTimeoutInMinutes sets the BuildTimeoutInMinutes field's value. +func (s *BuildBatch) SetBuildTimeoutInMinutes(v int64) *BuildBatch { + s.BuildTimeoutInMinutes = &v + return s +} + +// SetCache sets the Cache field's value. +func (s *BuildBatch) SetCache(v *ProjectCache) *BuildBatch { + s.Cache = v + return s +} + +// SetComplete sets the Complete field's value. +func (s *BuildBatch) SetComplete(v bool) *BuildBatch { + s.Complete = &v + return s +} + +// SetCurrentPhase sets the CurrentPhase field's value. +func (s *BuildBatch) SetCurrentPhase(v string) *BuildBatch { + s.CurrentPhase = &v + return s +} + +// SetEncryptionKey sets the EncryptionKey field's value. +func (s *BuildBatch) SetEncryptionKey(v string) *BuildBatch { + s.EncryptionKey = &v + return s +} + +// SetEndTime sets the EndTime field's value. +func (s *BuildBatch) SetEndTime(v time.Time) *BuildBatch { + s.EndTime = &v + return s +} + +// SetEnvironment sets the Environment field's value. +func (s *BuildBatch) SetEnvironment(v *ProjectEnvironment) *BuildBatch { + s.Environment = v + return s +} + +// SetFileSystemLocations sets the FileSystemLocations field's value. +func (s *BuildBatch) SetFileSystemLocations(v []*ProjectFileSystemLocation) *BuildBatch { + s.FileSystemLocations = v + return s +} + +// SetId sets the Id field's value. +func (s *BuildBatch) SetId(v string) *BuildBatch { + s.Id = &v + return s +} + +// SetInitiator sets the Initiator field's value. +func (s *BuildBatch) SetInitiator(v string) *BuildBatch { + s.Initiator = &v + return s +} + +// SetLogConfig sets the LogConfig field's value. +func (s *BuildBatch) SetLogConfig(v *LogsConfig) *BuildBatch { + s.LogConfig = v + return s +} + +// SetPhases sets the Phases field's value. +func (s *BuildBatch) SetPhases(v []*BuildBatchPhase) *BuildBatch { + s.Phases = v + return s +} + +// SetProjectName sets the ProjectName field's value. +func (s *BuildBatch) SetProjectName(v string) *BuildBatch { + s.ProjectName = &v + return s +} + +// SetQueuedTimeoutInMinutes sets the QueuedTimeoutInMinutes field's value. +func (s *BuildBatch) SetQueuedTimeoutInMinutes(v int64) *BuildBatch { + s.QueuedTimeoutInMinutes = &v + return s +} + +// SetResolvedSourceVersion sets the ResolvedSourceVersion field's value. +func (s *BuildBatch) SetResolvedSourceVersion(v string) *BuildBatch { + s.ResolvedSourceVersion = &v + return s +} + +// SetSecondaryArtifacts sets the SecondaryArtifacts field's value. +func (s *BuildBatch) SetSecondaryArtifacts(v []*BuildArtifacts) *BuildBatch { + s.SecondaryArtifacts = v + return s +} + +// SetSecondarySourceVersions sets the SecondarySourceVersions field's value. +func (s *BuildBatch) SetSecondarySourceVersions(v []*ProjectSourceVersion) *BuildBatch { + s.SecondarySourceVersions = v + return s +} + +// SetSecondarySources sets the SecondarySources field's value. +func (s *BuildBatch) SetSecondarySources(v []*ProjectSource) *BuildBatch { + s.SecondarySources = v + return s } -type BatchDeleteBuildsInput struct { - _ struct{} `type:"structure"` +// SetServiceRole sets the ServiceRole field's value. +func (s *BuildBatch) SetServiceRole(v string) *BuildBatch { + s.ServiceRole = &v + return s +} + +// SetSource sets the Source field's value. +func (s *BuildBatch) SetSource(v *ProjectSource) *BuildBatch { + s.Source = v + return s +} + +// SetSourceVersion sets the SourceVersion field's value. +func (s *BuildBatch) SetSourceVersion(v string) *BuildBatch { + s.SourceVersion = &v + return s +} + +// SetStartTime sets the StartTime field's value. +func (s *BuildBatch) SetStartTime(v time.Time) *BuildBatch { + s.StartTime = &v + return s +} + +// SetVpcConfig sets the VpcConfig field's value. +func (s *BuildBatch) SetVpcConfig(v *VpcConfig) *BuildBatch { + s.VpcConfig = v + return s +} + +// Specifies filters when retrieving batch builds. +type BuildBatchFilter struct { + _ struct{} `type:"structure"` + + // The status of the batch builds to retrieve. Only batch builds that have this + // status will be retrieved. + Status *string `locationName:"status" type:"string" enum:"StatusType"` +} + +// String returns the string representation +func (s BuildBatchFilter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BuildBatchFilter) GoString() string { + return s.String() +} + +// SetStatus sets the Status field's value. +func (s *BuildBatchFilter) SetStatus(v string) *BuildBatchFilter { + s.Status = &v + return s +} + +// Contains information about a stage for a batch build. +type BuildBatchPhase struct { + _ struct{} `type:"structure"` + + // Additional information about the batch build phase. Especially to help troubleshoot + // a failed btach build. + Contexts []*PhaseContext `locationName:"contexts" type:"list"` + + // How long, in seconds, between the starting and ending times of the batch + // build's phase. + DurationInSeconds *int64 `locationName:"durationInSeconds" type:"long"` + + // When the batch build phase ended, expressed in Unix time format. + EndTime *time.Time `locationName:"endTime" type:"timestamp"` + + // The current status of the batch build phase. Valid values include: + // + // FAILED + // + // The build phase failed. + // + // FAULT + // + // The build phase faulted. + // + // IN_PROGRESS + // + // The build phase is still in progress. + // + // QUEUED + // + // The build has been submitted and is queued behind other submitted builds. + // + // STOPPED + // + // The build phase stopped. + // + // SUCCEEDED + // + // The build phase succeeded. + // + // TIMED_OUT + // + // The build phase timed out. + PhaseStatus *string `locationName:"phaseStatus" type:"string" enum:"StatusType"` + + // The name of the batch build phase. Valid values include: + // + // COMBINE_ARTIFACTS + // + // Build output artifacts are being combined and uploaded to the output location. + // + // DOWNLOAD_BATCHSPEC + // + // The batch build specification is being downloaded. + // + // FAILED + // + // One or more of the builds failed. + // + // IN_PROGRESS + // + // The batch build is in progress. + // + // STOPPED + // + // The batch build was stopped. + // + // SUBMITTED + // + // The btach build has been submitted. + // + // SUCCEEDED + // + // The batch build succeeded. + PhaseType *string `locationName:"phaseType" type:"string" enum:"BuildBatchPhaseType"` + + // When the batch build phase started, expressed in Unix time format. + StartTime *time.Time `locationName:"startTime" type:"timestamp"` +} + +// String returns the string representation +func (s BuildBatchPhase) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BuildBatchPhase) GoString() string { + return s.String() +} + +// SetContexts sets the Contexts field's value. +func (s *BuildBatchPhase) SetContexts(v []*PhaseContext) *BuildBatchPhase { + s.Contexts = v + return s +} + +// SetDurationInSeconds sets the DurationInSeconds field's value. +func (s *BuildBatchPhase) SetDurationInSeconds(v int64) *BuildBatchPhase { + s.DurationInSeconds = &v + return s +} + +// SetEndTime sets the EndTime field's value. +func (s *BuildBatchPhase) SetEndTime(v time.Time) *BuildBatchPhase { + s.EndTime = &v + return s +} + +// SetPhaseStatus sets the PhaseStatus field's value. +func (s *BuildBatchPhase) SetPhaseStatus(v string) *BuildBatchPhase { + s.PhaseStatus = &v + return s +} + +// SetPhaseType sets the PhaseType field's value. +func (s *BuildBatchPhase) SetPhaseType(v string) *BuildBatchPhase { + s.PhaseType = &v + return s +} + +// SetStartTime sets the StartTime field's value. +func (s *BuildBatchPhase) SetStartTime(v time.Time) *BuildBatchPhase { + s.StartTime = &v + return s +} + +// Contains information about a batch build build group. Build groups are used +// to combine builds that can run in parallel, while still being able to set +// dependencies on other build groups. +type BuildGroup struct { + _ struct{} `type:"structure"` + + // A BuildSummary object that contains a summary of the current build group. + CurrentBuildSummary *BuildSummary `locationName:"currentBuildSummary" type:"structure"` + + // An array of strings that contain the identifiers of the build groups that + // this build group depends on. + DependsOn []*string `locationName:"dependsOn" type:"list"` + + // Contains the identifier of the build group. + Identifier *string `locationName:"identifier" type:"string"` + + // Specifies if failures in this build group can be ignored. + IgnoreFailure *bool `locationName:"ignoreFailure" type:"boolean"` - // The IDs of the builds to delete. - // - // Ids is a required field - Ids []*string `locationName:"ids" min:"1" type:"list" required:"true"` + // An array of BuildSummary objects that contain summaries of previous build + // groups. + PriorBuildSummaryList []*BuildSummary `locationName:"priorBuildSummaryList" type:"list"` } // String returns the string representation -func (s BatchDeleteBuildsInput) String() string { +func (s BuildGroup) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BatchDeleteBuildsInput) GoString() string { +func (s BuildGroup) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *BatchDeleteBuildsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "BatchDeleteBuildsInput"} - if s.Ids == nil { - invalidParams.Add(request.NewErrParamRequired("Ids")) - } - if s.Ids != nil && len(s.Ids) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Ids", 1)) - } +// SetCurrentBuildSummary sets the CurrentBuildSummary field's value. +func (s *BuildGroup) SetCurrentBuildSummary(v *BuildSummary) *BuildGroup { + s.CurrentBuildSummary = v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetDependsOn sets the DependsOn field's value. +func (s *BuildGroup) SetDependsOn(v []*string) *BuildGroup { + s.DependsOn = v + return s } -// SetIds sets the Ids field's value. -func (s *BatchDeleteBuildsInput) SetIds(v []*string) *BatchDeleteBuildsInput { - s.Ids = v +// SetIdentifier sets the Identifier field's value. +func (s *BuildGroup) SetIdentifier(v string) *BuildGroup { + s.Identifier = &v return s } -type BatchDeleteBuildsOutput struct { +// SetIgnoreFailure sets the IgnoreFailure field's value. +func (s *BuildGroup) SetIgnoreFailure(v bool) *BuildGroup { + s.IgnoreFailure = &v + return s +} + +// SetPriorBuildSummaryList sets the PriorBuildSummaryList field's value. +func (s *BuildGroup) SetPriorBuildSummaryList(v []*BuildSummary) *BuildGroup { + s.PriorBuildSummaryList = v + return s +} + +// Information about a build that could not be successfully deleted. +type BuildNotDeleted struct { _ struct{} `type:"structure"` - // The IDs of the builds that were successfully deleted. - BuildsDeleted []*string `locationName:"buildsDeleted" min:"1" type:"list"` + // The ID of the build that could not be successfully deleted. + Id *string `locationName:"id" min:"1" type:"string"` - // Information about any builds that could not be successfully deleted. - BuildsNotDeleted []*BuildNotDeleted `locationName:"buildsNotDeleted" type:"list"` + // Additional information about the build that could not be successfully deleted. + StatusCode *string `locationName:"statusCode" type:"string"` } // String returns the string representation -func (s BatchDeleteBuildsOutput) String() string { +func (s BuildNotDeleted) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BatchDeleteBuildsOutput) GoString() string { +func (s BuildNotDeleted) GoString() string { return s.String() } -// SetBuildsDeleted sets the BuildsDeleted field's value. -func (s *BatchDeleteBuildsOutput) SetBuildsDeleted(v []*string) *BatchDeleteBuildsOutput { - s.BuildsDeleted = v +// SetId sets the Id field's value. +func (s *BuildNotDeleted) SetId(v string) *BuildNotDeleted { + s.Id = &v return s } -// SetBuildsNotDeleted sets the BuildsNotDeleted field's value. -func (s *BatchDeleteBuildsOutput) SetBuildsNotDeleted(v []*BuildNotDeleted) *BatchDeleteBuildsOutput { - s.BuildsNotDeleted = v +// SetStatusCode sets the StatusCode field's value. +func (s *BuildNotDeleted) SetStatusCode(v string) *BuildNotDeleted { + s.StatusCode = &v return s } -type BatchGetBuildsInput struct { +// Information about a stage for a build. +type BuildPhase struct { _ struct{} `type:"structure"` - // The IDs of the builds. + // Additional information about a build phase, especially to help troubleshoot + // a failed build. + Contexts []*PhaseContext `locationName:"contexts" type:"list"` + + // How long, in seconds, between the starting and ending times of the build's + // phase. + DurationInSeconds *int64 `locationName:"durationInSeconds" type:"long"` + + // When the build phase ended, expressed in Unix time format. + EndTime *time.Time `locationName:"endTime" type:"timestamp"` + + // The current status of the build phase. Valid values include: // - // Ids is a required field - Ids []*string `locationName:"ids" min:"1" type:"list" required:"true"` + // FAILED + // + // The build phase failed. + // + // FAULT + // + // The build phase faulted. + // + // IN_PROGRESS + // + // The build phase is still in progress. + // + // QUEUED + // + // The build has been submitted and is queued behind other submitted builds. + // + // STOPPED + // + // The build phase stopped. + // + // SUCCEEDED + // + // The build phase succeeded. + // + // TIMED_OUT + // + // The build phase timed out. + PhaseStatus *string `locationName:"phaseStatus" type:"string" enum:"StatusType"` + + // The name of the build phase. Valid values include: + // + // * BUILD: Core build activities typically occur in this build phase. + // + // * COMPLETED: The build has been completed. + // + // * DOWNLOAD_SOURCE: Source code is being downloaded in this build phase. + // + // * FINALIZING: The build process is completing in this build phase. + // + // * INSTALL: Installation activities typically occur in this build phase. + // + // * POST_BUILD: Post-build activities typically occur in this build phase. + // + // * PRE_BUILD: Pre-build activities typically occur in this build phase. + // + // * PROVISIONING: The build environment is being set up. + // + // * QUEUED: The build has been submitted and is queued behind other submitted + // builds. + // + // * SUBMITTED: The build has been submitted. + // + // * UPLOAD_ARTIFACTS: Build output artifacts are being uploaded to the output + // location. + PhaseType *string `locationName:"phaseType" type:"string" enum:"BuildPhaseType"` + + // When the build phase started, expressed in Unix time format. + StartTime *time.Time `locationName:"startTime" type:"timestamp"` } // String returns the string representation -func (s BatchGetBuildsInput) String() string { +func (s BuildPhase) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BatchGetBuildsInput) GoString() string { +func (s BuildPhase) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *BatchGetBuildsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "BatchGetBuildsInput"} - if s.Ids == nil { - invalidParams.Add(request.NewErrParamRequired("Ids")) - } - if s.Ids != nil && len(s.Ids) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Ids", 1)) - } +// SetContexts sets the Contexts field's value. +func (s *BuildPhase) SetContexts(v []*PhaseContext) *BuildPhase { + s.Contexts = v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetDurationInSeconds sets the DurationInSeconds field's value. +func (s *BuildPhase) SetDurationInSeconds(v int64) *BuildPhase { + s.DurationInSeconds = &v + return s } -// SetIds sets the Ids field's value. -func (s *BatchGetBuildsInput) SetIds(v []*string) *BatchGetBuildsInput { - s.Ids = v +// SetEndTime sets the EndTime field's value. +func (s *BuildPhase) SetEndTime(v time.Time) *BuildPhase { + s.EndTime = &v return s } -type BatchGetBuildsOutput struct { +// SetPhaseStatus sets the PhaseStatus field's value. +func (s *BuildPhase) SetPhaseStatus(v string) *BuildPhase { + s.PhaseStatus = &v + return s +} + +// SetPhaseType sets the PhaseType field's value. +func (s *BuildPhase) SetPhaseType(v string) *BuildPhase { + s.PhaseType = &v + return s +} + +// SetStartTime sets the StartTime field's value. +func (s *BuildPhase) SetStartTime(v time.Time) *BuildPhase { + s.StartTime = &v + return s +} + +// Contains information that defines how the AWS CodeBuild build project reports +// the build status to the source provider. +type BuildStatusConfig struct { _ struct{} `type:"structure"` - // Information about the requested builds. - Builds []*Build `locationName:"builds" type:"list"` + // Specifies the context of the build status CodeBuild sends to the source provider. + // The usage of this parameter depends on the source provider. + // + // Bitbucket + // + // This parameter is used for the name parameter in the Bitbucket commit status. + // For more information, see build (https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/commit/%7Bnode%7D/statuses/build) + // in the Bitbucket API documentation. + // + // GitHub/GitHub Enterprise Server + // + // This parameter is used for the context parameter in the GitHub commit status. + // For more information, see Create a commit status (https://developer.github.com/v3/repos/statuses/#create-a-commit-status) + // in the GitHub developer guide. + Context *string `locationName:"context" type:"string"` - // The IDs of builds for which information could not be found. - BuildsNotFound []*string `locationName:"buildsNotFound" min:"1" type:"list"` + // Specifies the target url of the build status CodeBuild sends to the source + // provider. The usage of this parameter depends on the source provider. + // + // Bitbucket + // + // This parameter is used for the url parameter in the Bitbucket commit status. + // For more information, see build (https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/commit/%7Bnode%7D/statuses/build) + // in the Bitbucket API documentation. + // + // GitHub/GitHub Enterprise Server + // + // This parameter is used for the target_url parameter in the GitHub commit + // status. For more information, see Create a commit status (https://developer.github.com/v3/repos/statuses/#create-a-commit-status) + // in the GitHub developer guide. + TargetUrl *string `locationName:"targetUrl" type:"string"` } // String returns the string representation -func (s BatchGetBuildsOutput) String() string { +func (s BuildStatusConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BatchGetBuildsOutput) GoString() string { +func (s BuildStatusConfig) GoString() string { return s.String() } -// SetBuilds sets the Builds field's value. -func (s *BatchGetBuildsOutput) SetBuilds(v []*Build) *BatchGetBuildsOutput { - s.Builds = v +// SetContext sets the Context field's value. +func (s *BuildStatusConfig) SetContext(v string) *BuildStatusConfig { + s.Context = &v return s } -// SetBuildsNotFound sets the BuildsNotFound field's value. -func (s *BatchGetBuildsOutput) SetBuildsNotFound(v []*string) *BatchGetBuildsOutput { - s.BuildsNotFound = v +// SetTargetUrl sets the TargetUrl field's value. +func (s *BuildStatusConfig) SetTargetUrl(v string) *BuildStatusConfig { + s.TargetUrl = &v return s } -type BatchGetProjectsInput struct { +// Contains summary information about a batch build group. +type BuildSummary struct { _ struct{} `type:"structure"` - // The names or ARNs of the build projects. To get information about a project - // shared with your AWS account, its ARN must be specified. You cannot specify - // a shared project using its name. + // The batch build ARN. + Arn *string `locationName:"arn" type:"string"` + + // The status of the build group. // - // Names is a required field - Names []*string `locationName:"names" min:"1" type:"list" required:"true"` + // FAILED + // + // The build group failed. + // + // FAULT + // + // The build group faulted. + // + // IN_PROGRESS + // + // The build group is still in progress. + // + // STOPPED + // + // The build group stopped. + // + // SUCCEEDED + // + // The build group succeeded. + // + // TIMED_OUT + // + // The build group timed out. + BuildStatus *string `locationName:"buildStatus" type:"string" enum:"StatusType"` + + // A ResolvedArtifact object that represents the primary build artifacts for + // the build group. + PrimaryArtifact *ResolvedArtifact `locationName:"primaryArtifact" type:"structure"` + + // When the build was started, expressed in Unix time format. + RequestedOn *time.Time `locationName:"requestedOn" type:"timestamp"` + + // An array of ResolvedArtifact objects that represents the secondary build + // artifacts for the build group. + SecondaryArtifacts []*ResolvedArtifact `locationName:"secondaryArtifacts" type:"list"` } // String returns the string representation -func (s BatchGetProjectsInput) String() string { +func (s BuildSummary) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BatchGetProjectsInput) GoString() string { +func (s BuildSummary) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *BatchGetProjectsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "BatchGetProjectsInput"} - if s.Names == nil { - invalidParams.Add(request.NewErrParamRequired("Names")) - } - if s.Names != nil && len(s.Names) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Names", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetNames sets the Names field's value. -func (s *BatchGetProjectsInput) SetNames(v []*string) *BatchGetProjectsInput { - s.Names = v +// SetArn sets the Arn field's value. +func (s *BuildSummary) SetArn(v string) *BuildSummary { + s.Arn = &v return s } -type BatchGetProjectsOutput struct { - _ struct{} `type:"structure"` - - // Information about the requested build projects. - Projects []*Project `locationName:"projects" type:"list"` - - // The names of build projects for which information could not be found. - ProjectsNotFound []*string `locationName:"projectsNotFound" min:"1" type:"list"` -} - -// String returns the string representation -func (s BatchGetProjectsOutput) String() string { - return awsutil.Prettify(s) +// SetBuildStatus sets the BuildStatus field's value. +func (s *BuildSummary) SetBuildStatus(v string) *BuildSummary { + s.BuildStatus = &v + return s } -// GoString returns the string representation -func (s BatchGetProjectsOutput) GoString() string { - return s.String() +// SetPrimaryArtifact sets the PrimaryArtifact field's value. +func (s *BuildSummary) SetPrimaryArtifact(v *ResolvedArtifact) *BuildSummary { + s.PrimaryArtifact = v + return s } -// SetProjects sets the Projects field's value. -func (s *BatchGetProjectsOutput) SetProjects(v []*Project) *BatchGetProjectsOutput { - s.Projects = v +// SetRequestedOn sets the RequestedOn field's value. +func (s *BuildSummary) SetRequestedOn(v time.Time) *BuildSummary { + s.RequestedOn = &v return s } -// SetProjectsNotFound sets the ProjectsNotFound field's value. -func (s *BatchGetProjectsOutput) SetProjectsNotFound(v []*string) *BatchGetProjectsOutput { - s.ProjectsNotFound = v +// SetSecondaryArtifacts sets the SecondaryArtifacts field's value. +func (s *BuildSummary) SetSecondaryArtifacts(v []*ResolvedArtifact) *BuildSummary { + s.SecondaryArtifacts = v return s } -type BatchGetReportGroupsInput struct { +// Information about Amazon CloudWatch Logs for a build project. +type CloudWatchLogsConfig struct { _ struct{} `type:"structure"` - // An array of report group ARNs that identify the report groups to return. + // The group name of the logs in Amazon CloudWatch Logs. For more information, + // see Working with Log Groups and Log Streams (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html). + GroupName *string `locationName:"groupName" type:"string"` + + // The current status of the logs in Amazon CloudWatch Logs for a build project. + // Valid values are: // - // ReportGroupArns is a required field - ReportGroupArns []*string `locationName:"reportGroupArns" min:"1" type:"list" required:"true"` + // * ENABLED: Amazon CloudWatch Logs are enabled for this build project. + // + // * DISABLED: Amazon CloudWatch Logs are not enabled for this build project. + // + // Status is a required field + Status *string `locationName:"status" type:"string" required:"true" enum:"LogsConfigStatusType"` + + // The prefix of the stream name of the Amazon CloudWatch Logs. For more information, + // see Working with Log Groups and Log Streams (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html). + StreamName *string `locationName:"streamName" type:"string"` } // String returns the string representation -func (s BatchGetReportGroupsInput) String() string { +func (s CloudWatchLogsConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BatchGetReportGroupsInput) GoString() string { +func (s CloudWatchLogsConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *BatchGetReportGroupsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "BatchGetReportGroupsInput"} - if s.ReportGroupArns == nil { - invalidParams.Add(request.NewErrParamRequired("ReportGroupArns")) - } - if s.ReportGroupArns != nil && len(s.ReportGroupArns) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ReportGroupArns", 1)) +func (s *CloudWatchLogsConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CloudWatchLogsConfig"} + if s.Status == nil { + invalidParams.Add(request.NewErrParamRequired("Status")) } if invalidParams.Len() > 0 { @@ -3108,157 +6101,232 @@ func (s *BatchGetReportGroupsInput) Validate() error { return nil } -// SetReportGroupArns sets the ReportGroupArns field's value. -func (s *BatchGetReportGroupsInput) SetReportGroupArns(v []*string) *BatchGetReportGroupsInput { - s.ReportGroupArns = v +// SetGroupName sets the GroupName field's value. +func (s *CloudWatchLogsConfig) SetGroupName(v string) *CloudWatchLogsConfig { + s.GroupName = &v return s } -type BatchGetReportGroupsOutput struct { +// SetStatus sets the Status field's value. +func (s *CloudWatchLogsConfig) SetStatus(v string) *CloudWatchLogsConfig { + s.Status = &v + return s +} + +// SetStreamName sets the StreamName field's value. +func (s *CloudWatchLogsConfig) SetStreamName(v string) *CloudWatchLogsConfig { + s.StreamName = &v + return s +} + +// Contains code coverage report information. +// +// Line coverage measures how many statements your tests cover. A statement +// is a single instruction, not including comments, conditionals, etc. +// +// Branch coverage determines if your tests cover every possible branch of a +// control structure, such as an if or case statement. +type CodeCoverage struct { _ struct{} `type:"structure"` - // The array of report groups returned by BatchGetReportGroups. - ReportGroups []*ReportGroup `locationName:"reportGroups" min:"1" type:"list"` + // The percentage of branches that are covered by your tests. + BranchCoveragePercentage *float64 `locationName:"branchCoveragePercentage" type:"double"` - // An array of ARNs passed to BatchGetReportGroups that are not associated with - // a ReportGroup. - ReportGroupsNotFound []*string `locationName:"reportGroupsNotFound" min:"1" type:"list"` + // The number of conditional branches that are covered by your tests. + BranchesCovered *int64 `locationName:"branchesCovered" type:"integer"` + + // The number of conditional branches that are not covered by your tests. + BranchesMissed *int64 `locationName:"branchesMissed" type:"integer"` + + // The date and time that the tests were run. + Expired *time.Time `locationName:"expired" type:"timestamp"` + + // The path of the test report file. + FilePath *string `locationName:"filePath" min:"1" type:"string"` + + // The identifier of the code coverage report. + Id *string `locationName:"id" min:"1" type:"string"` + + // The percentage of lines that are covered by your tests. + LineCoveragePercentage *float64 `locationName:"lineCoveragePercentage" type:"double"` + + // The number of lines that are covered by your tests. + LinesCovered *int64 `locationName:"linesCovered" type:"integer"` + + // The number of lines that are not covered by your tests. + LinesMissed *int64 `locationName:"linesMissed" type:"integer"` + + // The ARN of the report. + ReportARN *string `locationName:"reportARN" min:"1" type:"string"` } // String returns the string representation -func (s BatchGetReportGroupsOutput) String() string { +func (s CodeCoverage) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BatchGetReportGroupsOutput) GoString() string { +func (s CodeCoverage) GoString() string { return s.String() } -// SetReportGroups sets the ReportGroups field's value. -func (s *BatchGetReportGroupsOutput) SetReportGroups(v []*ReportGroup) *BatchGetReportGroupsOutput { - s.ReportGroups = v +// SetBranchCoveragePercentage sets the BranchCoveragePercentage field's value. +func (s *CodeCoverage) SetBranchCoveragePercentage(v float64) *CodeCoverage { + s.BranchCoveragePercentage = &v return s } -// SetReportGroupsNotFound sets the ReportGroupsNotFound field's value. -func (s *BatchGetReportGroupsOutput) SetReportGroupsNotFound(v []*string) *BatchGetReportGroupsOutput { - s.ReportGroupsNotFound = v +// SetBranchesCovered sets the BranchesCovered field's value. +func (s *CodeCoverage) SetBranchesCovered(v int64) *CodeCoverage { + s.BranchesCovered = &v return s } -type BatchGetReportsInput struct { - _ struct{} `type:"structure"` +// SetBranchesMissed sets the BranchesMissed field's value. +func (s *CodeCoverage) SetBranchesMissed(v int64) *CodeCoverage { + s.BranchesMissed = &v + return s +} - // An array of ARNs that identify the Report objects to return. - // - // ReportArns is a required field - ReportArns []*string `locationName:"reportArns" min:"1" type:"list" required:"true"` +// SetExpired sets the Expired field's value. +func (s *CodeCoverage) SetExpired(v time.Time) *CodeCoverage { + s.Expired = &v + return s } -// String returns the string representation -func (s BatchGetReportsInput) String() string { - return awsutil.Prettify(s) +// SetFilePath sets the FilePath field's value. +func (s *CodeCoverage) SetFilePath(v string) *CodeCoverage { + s.FilePath = &v + return s } -// GoString returns the string representation -func (s BatchGetReportsInput) GoString() string { - return s.String() +// SetId sets the Id field's value. +func (s *CodeCoverage) SetId(v string) *CodeCoverage { + s.Id = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *BatchGetReportsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "BatchGetReportsInput"} - if s.ReportArns == nil { - invalidParams.Add(request.NewErrParamRequired("ReportArns")) - } - if s.ReportArns != nil && len(s.ReportArns) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ReportArns", 1)) - } +// SetLineCoveragePercentage sets the LineCoveragePercentage field's value. +func (s *CodeCoverage) SetLineCoveragePercentage(v float64) *CodeCoverage { + s.LineCoveragePercentage = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetLinesCovered sets the LinesCovered field's value. +func (s *CodeCoverage) SetLinesCovered(v int64) *CodeCoverage { + s.LinesCovered = &v + return s } -// SetReportArns sets the ReportArns field's value. -func (s *BatchGetReportsInput) SetReportArns(v []*string) *BatchGetReportsInput { - s.ReportArns = v +// SetLinesMissed sets the LinesMissed field's value. +func (s *CodeCoverage) SetLinesMissed(v int64) *CodeCoverage { + s.LinesMissed = &v return s } -type BatchGetReportsOutput struct { +// SetReportARN sets the ReportARN field's value. +func (s *CodeCoverage) SetReportARN(v string) *CodeCoverage { + s.ReportARN = &v + return s +} + +// Contains a summary of a code coverage report. +// +// Line coverage measures how many statements your tests cover. A statement +// is a single instruction, not including comments, conditionals, etc. +// +// Branch coverage determines if your tests cover every possible branch of a +// control structure, such as an if or case statement. +type CodeCoverageReportSummary struct { _ struct{} `type:"structure"` - // The array of Report objects returned by BatchGetReports. - Reports []*Report `locationName:"reports" min:"1" type:"list"` + // The percentage of branches that are covered by your tests. + BranchCoveragePercentage *float64 `locationName:"branchCoveragePercentage" type:"double"` - // An array of ARNs passed to BatchGetReportGroups that are not associated with - // a Report. - ReportsNotFound []*string `locationName:"reportsNotFound" min:"1" type:"list"` + // The number of conditional branches that are covered by your tests. + BranchesCovered *int64 `locationName:"branchesCovered" type:"integer"` + + // The number of conditional branches that are not covered by your tests. + BranchesMissed *int64 `locationName:"branchesMissed" type:"integer"` + + // The percentage of lines that are covered by your tests. + LineCoveragePercentage *float64 `locationName:"lineCoveragePercentage" type:"double"` + + // The number of lines that are covered by your tests. + LinesCovered *int64 `locationName:"linesCovered" type:"integer"` + + // The number of lines that are not covered by your tests. + LinesMissed *int64 `locationName:"linesMissed" type:"integer"` } // String returns the string representation -func (s BatchGetReportsOutput) String() string { +func (s CodeCoverageReportSummary) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BatchGetReportsOutput) GoString() string { +func (s CodeCoverageReportSummary) GoString() string { return s.String() } -// SetReports sets the Reports field's value. -func (s *BatchGetReportsOutput) SetReports(v []*Report) *BatchGetReportsOutput { - s.Reports = v +// SetBranchCoveragePercentage sets the BranchCoveragePercentage field's value. +func (s *CodeCoverageReportSummary) SetBranchCoveragePercentage(v float64) *CodeCoverageReportSummary { + s.BranchCoveragePercentage = &v return s } -// SetReportsNotFound sets the ReportsNotFound field's value. -func (s *BatchGetReportsOutput) SetReportsNotFound(v []*string) *BatchGetReportsOutput { - s.ReportsNotFound = v +// SetBranchesCovered sets the BranchesCovered field's value. +func (s *CodeCoverageReportSummary) SetBranchesCovered(v int64) *CodeCoverageReportSummary { + s.BranchesCovered = &v return s } -// Information about a build. -type Build struct { - _ struct{} `type:"structure"` +// SetBranchesMissed sets the BranchesMissed field's value. +func (s *CodeCoverageReportSummary) SetBranchesMissed(v int64) *CodeCoverageReportSummary { + s.BranchesMissed = &v + return s +} - // The Amazon Resource Name (ARN) of the build. - Arn *string `locationName:"arn" min:"1" type:"string"` +// SetLineCoveragePercentage sets the LineCoveragePercentage field's value. +func (s *CodeCoverageReportSummary) SetLineCoveragePercentage(v float64) *CodeCoverageReportSummary { + s.LineCoveragePercentage = &v + return s +} - // Information about the output artifacts for the build. - Artifacts *BuildArtifacts `locationName:"artifacts" type:"structure"` +// SetLinesCovered sets the LinesCovered field's value. +func (s *CodeCoverageReportSummary) SetLinesCovered(v int64) *CodeCoverageReportSummary { + s.LinesCovered = &v + return s +} - // Whether the build is complete. True if complete; otherwise, false. - BuildComplete *bool `locationName:"buildComplete" type:"boolean"` +// SetLinesMissed sets the LinesMissed field's value. +func (s *CodeCoverageReportSummary) SetLinesMissed(v int64) *CodeCoverageReportSummary { + s.LinesMissed = &v + return s +} - // The number of the build. For each project, the buildNumber of its first build - // is 1. The buildNumber of each subsequent build is incremented by 1. If a - // build is deleted, the buildNumber of other builds does not change. - BuildNumber *int64 `locationName:"buildNumber" type:"long"` +type CreateProjectInput struct { + _ struct{} `type:"structure"` - // The current status of the build. Valid values include: - // - // * FAILED: The build failed. - // - // * FAULT: The build faulted. - // - // * IN_PROGRESS: The build is still in progress. - // - // * STOPPED: The build stopped. - // - // * SUCCEEDED: The build succeeded. + // Information about the build output artifacts for the build project. // - // * TIMED_OUT: The build timed out. - BuildStatus *string `locationName:"buildStatus" type:"string" enum:"StatusType"` + // Artifacts is a required field + Artifacts *ProjectArtifacts `locationName:"artifacts" type:"structure" required:"true"` - // Information about the cache for the build. + // Set this to true to generate a publicly accessible URL for your project's + // build badge. + BadgeEnabled *bool `locationName:"badgeEnabled" type:"boolean"` + + // A ProjectBuildBatchConfig object that defines the batch build options for + // the project. + BuildBatchConfig *ProjectBuildBatchConfig `locationName:"buildBatchConfig" type:"structure"` + + // Stores recently used information so that it can be quickly accessed at a + // later time. Cache *ProjectCache `locationName:"cache" type:"structure"` - // The current build phase. - CurrentPhase *string `locationName:"currentPhase" type:"string"` + // A description that makes the build project easy to identify. + Description *string `locationName:"description" type:"string"` // The AWS Key Management Service (AWS KMS) customer master key (CMK) to be // used for encrypting the build output artifacts. @@ -3270,76 +6338,60 @@ type Build struct { // the CMK's alias (using the format alias/alias-name ). EncryptionKey *string `locationName:"encryptionKey" min:"1" type:"string"` - // When the build process ended, expressed in Unix time format. - EndTime *time.Time `locationName:"endTime" type:"timestamp"` - - // Information about the build environment for this build. - Environment *ProjectEnvironment `locationName:"environment" type:"structure"` - - // A list of exported environment variables for this build. - ExportedEnvironmentVariables []*ExportedEnvironmentVariable `locationName:"exportedEnvironmentVariables" type:"list"` + // Information about the build environment for the build project. + // + // Environment is a required field + Environment *ProjectEnvironment `locationName:"environment" type:"structure" required:"true"` // An array of ProjectFileSystemLocation objects for a CodeBuild build project. // A ProjectFileSystemLocation object specifies the identifier, location, mountOptions, // mountPoint, and type of a file system created using Amazon Elastic File System. FileSystemLocations []*ProjectFileSystemLocation `locationName:"fileSystemLocations" type:"list"` - // The unique ID for the build. - Id *string `locationName:"id" min:"1" type:"string"` + // Information about logs for the build project. These can be logs in Amazon + // CloudWatch Logs, logs uploaded to a specified S3 bucket, or both. + LogsConfig *LogsConfig `locationName:"logsConfig" type:"structure"` - // The entity that started the build. Valid values include: - // - // * If AWS CodePipeline started the build, the pipeline's name (for example, - // codepipeline/my-demo-pipeline). - // - // * If an AWS Identity and Access Management (IAM) user started the build, - // the user's name (for example, MyUserName). + // The name of the build project. // - // * If the Jenkins plugin for AWS CodeBuild started the build, the string - // CodeBuild-Jenkins-Plugin. - Initiator *string `locationName:"initiator" type:"string"` - - // Information about the build's logs in Amazon CloudWatch Logs. - Logs *LogsLocation `locationName:"logs" type:"structure"` - - // Describes a network interface. - NetworkInterface *NetworkInterface `locationName:"networkInterface" type:"structure"` - - // Information about all previous build phases that are complete and information - // about any current build phase that is not yet complete. - Phases []*BuildPhase `locationName:"phases" type:"list"` - - // The name of the AWS CodeBuild project. - ProjectName *string `locationName:"projectName" min:"1" type:"string"` + // Name is a required field + Name *string `locationName:"name" min:"2" type:"string" required:"true"` // The number of minutes a build is allowed to be queued before it times out. - QueuedTimeoutInMinutes *int64 `locationName:"queuedTimeoutInMinutes" type:"integer"` + QueuedTimeoutInMinutes *int64 `locationName:"queuedTimeoutInMinutes" min:"5" type:"integer"` + + // An array of ProjectArtifacts objects. + SecondaryArtifacts []*ProjectArtifacts `locationName:"secondaryArtifacts" type:"list"` - // An array of the ARNs associated with this build's reports. - ReportArns []*string `locationName:"reportArns" type:"list"` + // An array of ProjectSourceVersion objects. If secondarySourceVersions is specified + // at the build level, then they take precedence over these secondarySourceVersions + // (at the project level). + SecondarySourceVersions []*ProjectSourceVersion `locationName:"secondarySourceVersions" type:"list"` - // An identifier for the version of this build's source code. - // - // * For AWS CodeCommit, GitHub, GitHub Enterprise, and BitBucket, the commit - // ID. - // - // * For AWS CodePipeline, the source revision provided by AWS CodePipeline. + // An array of ProjectSource objects. + SecondarySources []*ProjectSource `locationName:"secondarySources" type:"list"` + + // The ARN of the AWS Identity and Access Management (IAM) role that enables + // AWS CodeBuild to interact with dependent AWS services on behalf of the AWS + // account. // - // * For Amazon Simple Storage Service (Amazon S3), this does not apply. - ResolvedSourceVersion *string `locationName:"resolvedSourceVersion" min:"1" type:"string"` + // ServiceRole is a required field + ServiceRole *string `locationName:"serviceRole" min:"1" type:"string" required:"true"` - // An array of ProjectArtifacts objects. - SecondaryArtifacts []*BuildArtifacts `locationName:"secondaryArtifacts" type:"list"` + // Information about the build input source code for the build project. + // + // Source is a required field + Source *ProjectSource `locationName:"source" type:"structure" required:"true"` - // An array of ProjectSourceVersion objects. Each ProjectSourceVersion must - // be one of: + // A version of the build input to be built for this project. If not specified, + // the latest version is used. If specified, it must be one of: // // * For AWS CodeCommit: the commit ID, branch, or Git tag to use. // // * For GitHub: the commit ID, pull request ID, branch name, or tag name // that corresponds to the version of the source code you want to build. // If a pull request ID is specified, it must use the format pr/pull-request-ID - // (for example, pr/25). If a branch name is specified, the branch's HEAD + // (for example pr/25). If a branch name is specified, the branch's HEAD // commit ID is used. If not specified, the default branch's HEAD commit // ID is used. // @@ -3350,494 +6402,776 @@ type Build struct { // // * For Amazon Simple Storage Service (Amazon S3): the version ID of the // object that represents the build input ZIP file to use. - SecondarySourceVersions []*ProjectSourceVersion `locationName:"secondarySourceVersions" type:"list"` - - // An array of ProjectSource objects. - SecondarySources []*ProjectSource `locationName:"secondarySources" type:"list"` - - // The name of a service role used for this build. - ServiceRole *string `locationName:"serviceRole" min:"1" type:"string"` - - // Information about the source code to be built. - Source *ProjectSource `locationName:"source" type:"structure"` - - // Any version identifier for the version of the source code to be built. If - // sourceVersion is specified at the project level, then this sourceVersion - // (at the build level) takes precedence. + // + // If sourceVersion is specified at the build level, then that version takes + // precedence over this sourceVersion (at the project level). // // For more information, see Source Version Sample with CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/sample-source-version.html) // in the AWS CodeBuild User Guide. - SourceVersion *string `locationName:"sourceVersion" min:"1" type:"string"` + SourceVersion *string `locationName:"sourceVersion" type:"string"` - // When the build process started, expressed in Unix time format. - StartTime *time.Time `locationName:"startTime" type:"timestamp"` + // A list of tag key and value pairs associated with this build project. + // + // These tags are available for use by AWS services that support AWS CodeBuild + // build project tags. + Tags []*Tag `locationName:"tags" type:"list"` - // How long, in minutes, for AWS CodeBuild to wait before timing out this build - // if it does not get marked as completed. - TimeoutInMinutes *int64 `locationName:"timeoutInMinutes" type:"integer"` + // How long, in minutes, from 5 to 480 (8 hours), for AWS CodeBuild to wait + // before it times out any build that has not been marked as completed. The + // default is 60 minutes. + TimeoutInMinutes *int64 `locationName:"timeoutInMinutes" min:"5" type:"integer"` - // If your AWS CodeBuild project accesses resources in an Amazon VPC, you provide - // this parameter that identifies the VPC ID and the list of security group - // IDs and subnet IDs. The security groups and subnets must belong to the same - // VPC. You must provide at least one security group and one subnet ID. + // VpcConfig enables AWS CodeBuild to access resources in an Amazon VPC. VpcConfig *VpcConfig `locationName:"vpcConfig" type:"structure"` } -// String returns the string representation -func (s Build) String() string { - return awsutil.Prettify(s) +// 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.Artifacts == nil { + invalidParams.Add(request.NewErrParamRequired("Artifacts")) + } + if s.EncryptionKey != nil && len(*s.EncryptionKey) < 1 { + invalidParams.Add(request.NewErrParamMinLen("EncryptionKey", 1)) + } + if s.Environment == nil { + invalidParams.Add(request.NewErrParamRequired("Environment")) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Name", 2)) + } + if s.QueuedTimeoutInMinutes != nil && *s.QueuedTimeoutInMinutes < 5 { + invalidParams.Add(request.NewErrParamMinValue("QueuedTimeoutInMinutes", 5)) + } + if s.ServiceRole == nil { + invalidParams.Add(request.NewErrParamRequired("ServiceRole")) + } + if s.ServiceRole != nil && len(*s.ServiceRole) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ServiceRole", 1)) + } + if s.Source == nil { + invalidParams.Add(request.NewErrParamRequired("Source")) + } + if s.TimeoutInMinutes != nil && *s.TimeoutInMinutes < 5 { + invalidParams.Add(request.NewErrParamMinValue("TimeoutInMinutes", 5)) + } + if s.Artifacts != nil { + if err := s.Artifacts.Validate(); err != nil { + invalidParams.AddNested("Artifacts", err.(request.ErrInvalidParams)) + } + } + if s.BuildBatchConfig != nil { + if err := s.BuildBatchConfig.Validate(); err != nil { + invalidParams.AddNested("BuildBatchConfig", err.(request.ErrInvalidParams)) + } + } + if s.Cache != nil { + if err := s.Cache.Validate(); err != nil { + invalidParams.AddNested("Cache", err.(request.ErrInvalidParams)) + } + } + if s.Environment != nil { + if err := s.Environment.Validate(); err != nil { + invalidParams.AddNested("Environment", err.(request.ErrInvalidParams)) + } + } + if s.LogsConfig != nil { + if err := s.LogsConfig.Validate(); err != nil { + invalidParams.AddNested("LogsConfig", err.(request.ErrInvalidParams)) + } + } + if s.SecondaryArtifacts != nil { + for i, v := range s.SecondaryArtifacts { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "SecondaryArtifacts", i), err.(request.ErrInvalidParams)) + } + } + } + if s.SecondarySourceVersions != nil { + for i, v := range s.SecondarySourceVersions { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "SecondarySourceVersions", i), err.(request.ErrInvalidParams)) + } + } + } + if s.SecondarySources != nil { + for i, v := range s.SecondarySources { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "SecondarySources", i), err.(request.ErrInvalidParams)) + } + } + } + if s.Source != nil { + if err := s.Source.Validate(); err != nil { + invalidParams.AddNested("Source", err.(request.ErrInvalidParams)) + } + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + if s.VpcConfig != nil { + if err := s.VpcConfig.Validate(); err != nil { + invalidParams.AddNested("VpcConfig", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArtifacts sets the Artifacts field's value. +func (s *CreateProjectInput) SetArtifacts(v *ProjectArtifacts) *CreateProjectInput { + s.Artifacts = v + return s +} + +// SetBadgeEnabled sets the BadgeEnabled field's value. +func (s *CreateProjectInput) SetBadgeEnabled(v bool) *CreateProjectInput { + s.BadgeEnabled = &v + return s +} + +// SetBuildBatchConfig sets the BuildBatchConfig field's value. +func (s *CreateProjectInput) SetBuildBatchConfig(v *ProjectBuildBatchConfig) *CreateProjectInput { + s.BuildBatchConfig = v + return s +} + +// SetCache sets the Cache field's value. +func (s *CreateProjectInput) SetCache(v *ProjectCache) *CreateProjectInput { + s.Cache = v + return s +} + +// SetDescription sets the Description field's value. +func (s *CreateProjectInput) SetDescription(v string) *CreateProjectInput { + s.Description = &v + return s +} + +// SetEncryptionKey sets the EncryptionKey field's value. +func (s *CreateProjectInput) SetEncryptionKey(v string) *CreateProjectInput { + s.EncryptionKey = &v + return s +} + +// SetEnvironment sets the Environment field's value. +func (s *CreateProjectInput) SetEnvironment(v *ProjectEnvironment) *CreateProjectInput { + s.Environment = v + return s +} + +// SetFileSystemLocations sets the FileSystemLocations field's value. +func (s *CreateProjectInput) SetFileSystemLocations(v []*ProjectFileSystemLocation) *CreateProjectInput { + s.FileSystemLocations = v + return s +} + +// SetLogsConfig sets the LogsConfig field's value. +func (s *CreateProjectInput) SetLogsConfig(v *LogsConfig) *CreateProjectInput { + s.LogsConfig = v + return s +} + +// SetName sets the Name field's value. +func (s *CreateProjectInput) SetName(v string) *CreateProjectInput { + s.Name = &v + return s +} + +// SetQueuedTimeoutInMinutes sets the QueuedTimeoutInMinutes field's value. +func (s *CreateProjectInput) SetQueuedTimeoutInMinutes(v int64) *CreateProjectInput { + s.QueuedTimeoutInMinutes = &v + return s +} + +// SetSecondaryArtifacts sets the SecondaryArtifacts field's value. +func (s *CreateProjectInput) SetSecondaryArtifacts(v []*ProjectArtifacts) *CreateProjectInput { + s.SecondaryArtifacts = v + return s } -// GoString returns the string representation -func (s Build) GoString() string { - return s.String() +// SetSecondarySourceVersions sets the SecondarySourceVersions field's value. +func (s *CreateProjectInput) SetSecondarySourceVersions(v []*ProjectSourceVersion) *CreateProjectInput { + s.SecondarySourceVersions = v + return s } -// SetArn sets the Arn field's value. -func (s *Build) SetArn(v string) *Build { - s.Arn = &v +// SetSecondarySources sets the SecondarySources field's value. +func (s *CreateProjectInput) SetSecondarySources(v []*ProjectSource) *CreateProjectInput { + s.SecondarySources = v return s } -// SetArtifacts sets the Artifacts field's value. -func (s *Build) SetArtifacts(v *BuildArtifacts) *Build { - s.Artifacts = v +// SetServiceRole sets the ServiceRole field's value. +func (s *CreateProjectInput) SetServiceRole(v string) *CreateProjectInput { + s.ServiceRole = &v return s } -// SetBuildComplete sets the BuildComplete field's value. -func (s *Build) SetBuildComplete(v bool) *Build { - s.BuildComplete = &v +// SetSource sets the Source field's value. +func (s *CreateProjectInput) SetSource(v *ProjectSource) *CreateProjectInput { + s.Source = v return s } -// SetBuildNumber sets the BuildNumber field's value. -func (s *Build) SetBuildNumber(v int64) *Build { - s.BuildNumber = &v +// SetSourceVersion sets the SourceVersion field's value. +func (s *CreateProjectInput) SetSourceVersion(v string) *CreateProjectInput { + s.SourceVersion = &v return s } -// SetBuildStatus sets the BuildStatus field's value. -func (s *Build) SetBuildStatus(v string) *Build { - s.BuildStatus = &v +// SetTags sets the Tags field's value. +func (s *CreateProjectInput) SetTags(v []*Tag) *CreateProjectInput { + s.Tags = v return s } -// SetCache sets the Cache field's value. -func (s *Build) SetCache(v *ProjectCache) *Build { - s.Cache = v +// SetTimeoutInMinutes sets the TimeoutInMinutes field's value. +func (s *CreateProjectInput) SetTimeoutInMinutes(v int64) *CreateProjectInput { + s.TimeoutInMinutes = &v return s } -// SetCurrentPhase sets the CurrentPhase field's value. -func (s *Build) SetCurrentPhase(v string) *Build { - s.CurrentPhase = &v +// SetVpcConfig sets the VpcConfig field's value. +func (s *CreateProjectInput) SetVpcConfig(v *VpcConfig) *CreateProjectInput { + s.VpcConfig = v return s } -// SetEncryptionKey sets the EncryptionKey field's value. -func (s *Build) SetEncryptionKey(v string) *Build { - s.EncryptionKey = &v - return s +type CreateProjectOutput struct { + _ struct{} `type:"structure"` + + // Information about the build project that was created. + Project *Project `locationName:"project" type:"structure"` } -// SetEndTime sets the EndTime field's value. -func (s *Build) SetEndTime(v time.Time) *Build { - s.EndTime = &v - return s +// String returns the string representation +func (s CreateProjectOutput) String() string { + return awsutil.Prettify(s) } -// SetEnvironment sets the Environment field's value. -func (s *Build) SetEnvironment(v *ProjectEnvironment) *Build { - s.Environment = v - return s +// GoString returns the string representation +func (s CreateProjectOutput) GoString() string { + return s.String() } -// SetExportedEnvironmentVariables sets the ExportedEnvironmentVariables field's value. -func (s *Build) SetExportedEnvironmentVariables(v []*ExportedEnvironmentVariable) *Build { - s.ExportedEnvironmentVariables = v +// SetProject sets the Project field's value. +func (s *CreateProjectOutput) SetProject(v *Project) *CreateProjectOutput { + s.Project = v return s } -// SetFileSystemLocations sets the FileSystemLocations field's value. -func (s *Build) SetFileSystemLocations(v []*ProjectFileSystemLocation) *Build { - s.FileSystemLocations = v - return s +type CreateReportGroupInput struct { + _ struct{} `type:"structure"` + + // A ReportExportConfig object that contains information about where the report + // group test results are exported. + // + // ExportConfig is a required field + ExportConfig *ReportExportConfig `locationName:"exportConfig" type:"structure" required:"true"` + + // The name of the report group. + // + // Name is a required field + Name *string `locationName:"name" min:"2" type:"string" required:"true"` + + // A list of tag key and value pairs associated with this report group. + // + // These tags are available for use by AWS services that support AWS CodeBuild + // report group tags. + Tags []*Tag `locationName:"tags" type:"list"` + + // The type of report group. + // + // Type is a required field + Type *string `locationName:"type" type:"string" required:"true" enum:"ReportType"` } -// SetId sets the Id field's value. -func (s *Build) SetId(v string) *Build { - s.Id = &v - return s +// String returns the string representation +func (s CreateReportGroupInput) String() string { + return awsutil.Prettify(s) } -// SetInitiator sets the Initiator field's value. -func (s *Build) SetInitiator(v string) *Build { - s.Initiator = &v - return s +// GoString returns the string representation +func (s CreateReportGroupInput) GoString() string { + return s.String() } -// SetLogs sets the Logs field's value. -func (s *Build) SetLogs(v *LogsLocation) *Build { - s.Logs = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateReportGroupInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateReportGroupInput"} + if s.ExportConfig == nil { + invalidParams.Add(request.NewErrParamRequired("ExportConfig")) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 2 { + invalidParams.Add(request.NewErrParamMinLen("Name", 2)) + } + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + if s.ExportConfig != nil { + if err := s.ExportConfig.Validate(); err != nil { + invalidParams.AddNested("ExportConfig", err.(request.ErrInvalidParams)) + } + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetNetworkInterface sets the NetworkInterface field's value. -func (s *Build) SetNetworkInterface(v *NetworkInterface) *Build { - s.NetworkInterface = v +// SetExportConfig sets the ExportConfig field's value. +func (s *CreateReportGroupInput) SetExportConfig(v *ReportExportConfig) *CreateReportGroupInput { + s.ExportConfig = v return s } -// SetPhases sets the Phases field's value. -func (s *Build) SetPhases(v []*BuildPhase) *Build { - s.Phases = v +// SetName sets the Name field's value. +func (s *CreateReportGroupInput) SetName(v string) *CreateReportGroupInput { + s.Name = &v return s } -// SetProjectName sets the ProjectName field's value. -func (s *Build) SetProjectName(v string) *Build { - s.ProjectName = &v +// SetTags sets the Tags field's value. +func (s *CreateReportGroupInput) SetTags(v []*Tag) *CreateReportGroupInput { + s.Tags = v return s } -// SetQueuedTimeoutInMinutes sets the QueuedTimeoutInMinutes field's value. -func (s *Build) SetQueuedTimeoutInMinutes(v int64) *Build { - s.QueuedTimeoutInMinutes = &v +// SetType sets the Type field's value. +func (s *CreateReportGroupInput) SetType(v string) *CreateReportGroupInput { + s.Type = &v return s } -// SetReportArns sets the ReportArns field's value. -func (s *Build) SetReportArns(v []*string) *Build { - s.ReportArns = v - return s +type CreateReportGroupOutput struct { + _ struct{} `type:"structure"` + + // Information about the report group that was created. + ReportGroup *ReportGroup `locationName:"reportGroup" type:"structure"` } -// SetResolvedSourceVersion sets the ResolvedSourceVersion field's value. -func (s *Build) SetResolvedSourceVersion(v string) *Build { - s.ResolvedSourceVersion = &v +// String returns the string representation +func (s CreateReportGroupOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateReportGroupOutput) GoString() string { + return s.String() +} + +// SetReportGroup sets the ReportGroup field's value. +func (s *CreateReportGroupOutput) SetReportGroup(v *ReportGroup) *CreateReportGroupOutput { + s.ReportGroup = v return s } -// SetSecondaryArtifacts sets the SecondaryArtifacts field's value. -func (s *Build) SetSecondaryArtifacts(v []*BuildArtifacts) *Build { - s.SecondaryArtifacts = v - return s +type CreateWebhookInput struct { + _ struct{} `type:"structure"` + + // A regular expression used to determine which repository branches are built + // when a webhook is triggered. If the name of a branch matches the regular + // expression, then it is built. If branchFilter is empty, then all branches + // are built. + // + // It is recommended that you use filterGroups instead of branchFilter. + BranchFilter *string `locationName:"branchFilter" type:"string"` + + // Specifies the type of build this webhook will trigger. + BuildType *string `locationName:"buildType" type:"string" enum:"WebhookBuildType"` + + // An array of arrays of WebhookFilter objects used to determine which webhooks + // are triggered. At least one WebhookFilter in the array must specify EVENT + // as its type. + // + // For a build to be triggered, at least one filter group in the filterGroups + // array must pass. For a filter group to pass, each of its filters must pass. + FilterGroups [][]*WebhookFilter `locationName:"filterGroups" type:"list"` + + // The name of the AWS CodeBuild project. + // + // ProjectName is a required field + ProjectName *string `locationName:"projectName" min:"2" type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateWebhookInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateWebhookInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateWebhookInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateWebhookInput"} + if s.ProjectName == nil { + invalidParams.Add(request.NewErrParamRequired("ProjectName")) + } + if s.ProjectName != nil && len(*s.ProjectName) < 2 { + invalidParams.Add(request.NewErrParamMinLen("ProjectName", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetSecondarySourceVersions sets the SecondarySourceVersions field's value. -func (s *Build) SetSecondarySourceVersions(v []*ProjectSourceVersion) *Build { - s.SecondarySourceVersions = v +// SetBranchFilter sets the BranchFilter field's value. +func (s *CreateWebhookInput) SetBranchFilter(v string) *CreateWebhookInput { + s.BranchFilter = &v return s } -// SetSecondarySources sets the SecondarySources field's value. -func (s *Build) SetSecondarySources(v []*ProjectSource) *Build { - s.SecondarySources = v +// SetBuildType sets the BuildType field's value. +func (s *CreateWebhookInput) SetBuildType(v string) *CreateWebhookInput { + s.BuildType = &v return s } -// SetServiceRole sets the ServiceRole field's value. -func (s *Build) SetServiceRole(v string) *Build { - s.ServiceRole = &v +// SetFilterGroups sets the FilterGroups field's value. +func (s *CreateWebhookInput) SetFilterGroups(v [][]*WebhookFilter) *CreateWebhookInput { + s.FilterGroups = v return s } -// SetSource sets the Source field's value. -func (s *Build) SetSource(v *ProjectSource) *Build { - s.Source = v +// SetProjectName sets the ProjectName field's value. +func (s *CreateWebhookInput) SetProjectName(v string) *CreateWebhookInput { + s.ProjectName = &v return s } -// SetSourceVersion sets the SourceVersion field's value. -func (s *Build) SetSourceVersion(v string) *Build { - s.SourceVersion = &v - return s +type CreateWebhookOutput struct { + _ struct{} `type:"structure"` + + // Information about a webhook that connects repository events to a build project + // in AWS CodeBuild. + Webhook *Webhook `locationName:"webhook" type:"structure"` } -// SetStartTime sets the StartTime field's value. -func (s *Build) SetStartTime(v time.Time) *Build { - s.StartTime = &v - return s +// String returns the string representation +func (s CreateWebhookOutput) String() string { + return awsutil.Prettify(s) } -// SetTimeoutInMinutes sets the TimeoutInMinutes field's value. -func (s *Build) SetTimeoutInMinutes(v int64) *Build { - s.TimeoutInMinutes = &v - return s +// GoString returns the string representation +func (s CreateWebhookOutput) GoString() string { + return s.String() } -// SetVpcConfig sets the VpcConfig field's value. -func (s *Build) SetVpcConfig(v *VpcConfig) *Build { - s.VpcConfig = v +// SetWebhook sets the Webhook field's value. +func (s *CreateWebhookOutput) SetWebhook(v *Webhook) *CreateWebhookOutput { + s.Webhook = v return s } -// Information about build output artifacts. -type BuildArtifacts struct { +// Contains information about the debug session for a build. For more information, +// see Viewing a running build in Session Manager (https://docs.aws.amazon.com/codebuild/latest/userguide/session-manager.html). +type DebugSession struct { _ struct{} `type:"structure"` - // An identifier for this artifact definition. - ArtifactIdentifier *string `locationName:"artifactIdentifier" type:"string"` - - // Information that tells you if encryption for build artifacts is disabled. - EncryptionDisabled *bool `locationName:"encryptionDisabled" type:"boolean"` - - // Information about the location of the build artifacts. - Location *string `locationName:"location" type:"string"` - - // The MD5 hash of the build artifact. - // - // You can use this hash along with a checksum tool to confirm file integrity - // and authenticity. - // - // This value is available only if the build project's packaging value is set - // to ZIP. - Md5sum *string `locationName:"md5sum" type:"string"` - - // If this flag is set, a name specified in the buildspec file overrides the - // artifact name. The name specified in a buildspec file is calculated at build - // time and uses the Shell Command Language. For example, you can append a date - // and time to your artifact name so that it is always unique. - OverrideArtifactName *bool `locationName:"overrideArtifactName" type:"boolean"` + // Specifies if session debugging is enabled for this build. + SessionEnabled *bool `locationName:"sessionEnabled" type:"boolean"` - // The SHA-256 hash of the build artifact. - // - // You can use this hash along with a checksum tool to confirm file integrity - // and authenticity. - // - // This value is available only if the build project's packaging value is set - // to ZIP. - Sha256sum *string `locationName:"sha256sum" type:"string"` + // Contains the identifier of the Session Manager session used for the build. + // To work with the paused build, you open this session to examine, control, + // and resume the build. + SessionTarget *string `locationName:"sessionTarget" min:"1" type:"string"` } // String returns the string representation -func (s BuildArtifacts) String() string { +func (s DebugSession) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BuildArtifacts) GoString() string { +func (s DebugSession) GoString() string { return s.String() } -// SetArtifactIdentifier sets the ArtifactIdentifier field's value. -func (s *BuildArtifacts) SetArtifactIdentifier(v string) *BuildArtifacts { - s.ArtifactIdentifier = &v +// SetSessionEnabled sets the SessionEnabled field's value. +func (s *DebugSession) SetSessionEnabled(v bool) *DebugSession { + s.SessionEnabled = &v return s } -// SetEncryptionDisabled sets the EncryptionDisabled field's value. -func (s *BuildArtifacts) SetEncryptionDisabled(v bool) *BuildArtifacts { - s.EncryptionDisabled = &v +// SetSessionTarget sets the SessionTarget field's value. +func (s *DebugSession) SetSessionTarget(v string) *DebugSession { + s.SessionTarget = &v return s } -// SetLocation sets the Location field's value. -func (s *BuildArtifacts) SetLocation(v string) *BuildArtifacts { - s.Location = &v - return s +type DeleteBuildBatchInput struct { + _ struct{} `type:"structure"` + + // The identifier of the batch build to delete. + // + // Id is a required field + Id *string `locationName:"id" min:"1" type:"string" required:"true"` } -// SetMd5sum sets the Md5sum field's value. -func (s *BuildArtifacts) SetMd5sum(v string) *BuildArtifacts { - s.Md5sum = &v - return s +// String returns the string representation +func (s DeleteBuildBatchInput) String() string { + return awsutil.Prettify(s) } -// SetOverrideArtifactName sets the OverrideArtifactName field's value. -func (s *BuildArtifacts) SetOverrideArtifactName(v bool) *BuildArtifacts { - s.OverrideArtifactName = &v - return s +// GoString returns the string representation +func (s DeleteBuildBatchInput) GoString() string { + return s.String() } -// SetSha256sum sets the Sha256sum field's value. -func (s *BuildArtifacts) SetSha256sum(v string) *BuildArtifacts { - s.Sha256sum = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteBuildBatchInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteBuildBatchInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *DeleteBuildBatchInput) SetId(v string) *DeleteBuildBatchInput { + s.Id = &v return s } -// Information about a build that could not be successfully deleted. -type BuildNotDeleted struct { +type DeleteBuildBatchOutput struct { _ struct{} `type:"structure"` - // The ID of the build that could not be successfully deleted. - Id *string `locationName:"id" min:"1" type:"string"` + // An array of strings that contain the identifiers of the builds that were + // deleted. + BuildsDeleted []*string `locationName:"buildsDeleted" min:"1" type:"list"` - // Additional information about the build that could not be successfully deleted. + // An array of BuildNotDeleted objects that specify the builds that could not + // be deleted. + BuildsNotDeleted []*BuildNotDeleted `locationName:"buildsNotDeleted" type:"list"` + + // The status code. StatusCode *string `locationName:"statusCode" type:"string"` } // String returns the string representation -func (s BuildNotDeleted) String() string { +func (s DeleteBuildBatchOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BuildNotDeleted) GoString() string { +func (s DeleteBuildBatchOutput) GoString() string { return s.String() } -// SetId sets the Id field's value. -func (s *BuildNotDeleted) SetId(v string) *BuildNotDeleted { - s.Id = &v +// SetBuildsDeleted sets the BuildsDeleted field's value. +func (s *DeleteBuildBatchOutput) SetBuildsDeleted(v []*string) *DeleteBuildBatchOutput { + s.BuildsDeleted = v + return s +} + +// SetBuildsNotDeleted sets the BuildsNotDeleted field's value. +func (s *DeleteBuildBatchOutput) SetBuildsNotDeleted(v []*BuildNotDeleted) *DeleteBuildBatchOutput { + s.BuildsNotDeleted = v return s } // SetStatusCode sets the StatusCode field's value. -func (s *BuildNotDeleted) SetStatusCode(v string) *BuildNotDeleted { +func (s *DeleteBuildBatchOutput) SetStatusCode(v string) *DeleteBuildBatchOutput { s.StatusCode = &v return s } -// Information about a stage for a build. -type BuildPhase struct { +type DeleteProjectInput struct { _ struct{} `type:"structure"` - // Additional information about a build phase, especially to help troubleshoot - // a failed build. - Contexts []*PhaseContext `locationName:"contexts" type:"list"` + // The name of the build project. + // + // Name is a required field + Name *string `locationName:"name" min:"1" type:"string" required:"true"` +} - // How long, in seconds, between the starting and ending times of the build's - // phase. - DurationInSeconds *int64 `locationName:"durationInSeconds" type:"long"` +// String returns the string representation +func (s DeleteProjectInput) String() string { + return awsutil.Prettify(s) +} - // When the build phase ended, expressed in Unix time format. - EndTime *time.Time `locationName:"endTime" type:"timestamp"` +// GoString returns the string representation +func (s DeleteProjectInput) GoString() string { + return s.String() +} - // The current status of the build phase. Valid values include: - // - // * FAILED: The build phase failed. - // - // * FAULT: The build phase faulted. - // - // * IN_PROGRESS: The build phase is still in progress. - // - // * QUEUED: The build has been submitted and is queued behind other submitted - // builds. - // - // * STOPPED: The build phase stopped. - // - // * SUCCEEDED: The build phase succeeded. - // - // * TIMED_OUT: The build phase timed out. - PhaseStatus *string `locationName:"phaseStatus" type:"string" enum:"StatusType"` +// 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.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } - // The name of the build phase. Valid values include: - // - // * BUILD: Core build activities typically occur in this build phase. - // - // * COMPLETED: The build has been completed. - // - // * DOWNLOAD_SOURCE: Source code is being downloaded in this build phase. - // - // * FINALIZING: The build process is completing in this build phase. - // - // * INSTALL: Installation activities typically occur in this build phase. - // - // * POST_BUILD: Post-build activities typically occur in this build phase. - // - // * PRE_BUILD: Pre-build activities typically occur in this build phase. - // - // * PROVISIONING: The build environment is being set up. - // - // * QUEUED: The build has been submitted and is queued behind other submitted - // builds. - // - // * SUBMITTED: The build has been submitted. - // - // * UPLOAD_ARTIFACTS: Build output artifacts are being uploaded to the output - // location. - PhaseType *string `locationName:"phaseType" type:"string" enum:"BuildPhaseType"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *DeleteProjectInput) SetName(v string) *DeleteProjectInput { + s.Name = &v + return s +} + +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() +} - // When the build phase started, expressed in Unix time format. - StartTime *time.Time `locationName:"startTime" type:"timestamp"` +type DeleteReportGroupInput struct { + _ struct{} `type:"structure"` + + // The ARN of the report group to delete. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s BuildPhase) String() string { +func (s DeleteReportGroupInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s BuildPhase) GoString() string { +func (s DeleteReportGroupInput) GoString() string { return s.String() } -// SetContexts sets the Contexts field's value. -func (s *BuildPhase) SetContexts(v []*PhaseContext) *BuildPhase { - s.Contexts = v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteReportGroupInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteReportGroupInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 1)) + } -// SetDurationInSeconds sets the DurationInSeconds field's value. -func (s *BuildPhase) SetDurationInSeconds(v int64) *BuildPhase { - s.DurationInSeconds = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetEndTime sets the EndTime field's value. -func (s *BuildPhase) SetEndTime(v time.Time) *BuildPhase { - s.EndTime = &v +// SetArn sets the Arn field's value. +func (s *DeleteReportGroupInput) SetArn(v string) *DeleteReportGroupInput { + s.Arn = &v return s } -// SetPhaseStatus sets the PhaseStatus field's value. -func (s *BuildPhase) SetPhaseStatus(v string) *BuildPhase { - s.PhaseStatus = &v - return s +type DeleteReportGroupOutput struct { + _ struct{} `type:"structure"` } -// SetPhaseType sets the PhaseType field's value. -func (s *BuildPhase) SetPhaseType(v string) *BuildPhase { - s.PhaseType = &v - return s +// String returns the string representation +func (s DeleteReportGroupOutput) String() string { + return awsutil.Prettify(s) } -// SetStartTime sets the StartTime field's value. -func (s *BuildPhase) SetStartTime(v time.Time) *BuildPhase { - s.StartTime = &v - return s +// GoString returns the string representation +func (s DeleteReportGroupOutput) GoString() string { + return s.String() } -// Information about Amazon CloudWatch Logs for a build project. -type CloudWatchLogsConfig struct { +type DeleteReportInput struct { _ struct{} `type:"structure"` - // The group name of the logs in Amazon CloudWatch Logs. For more information, - // see Working with Log Groups and Log Streams (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html). - GroupName *string `locationName:"groupName" type:"string"` - - // The current status of the logs in Amazon CloudWatch Logs for a build project. - // Valid values are: - // - // * ENABLED: Amazon CloudWatch Logs are enabled for this build project. - // - // * DISABLED: Amazon CloudWatch Logs are not enabled for this build project. + // The ARN of the report to delete. // - // Status is a required field - Status *string `locationName:"status" type:"string" required:"true" enum:"LogsConfigStatusType"` - - // The prefix of the stream name of the Amazon CloudWatch Logs. For more information, - // see Working with Log Groups and Log Streams (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html). - StreamName *string `locationName:"streamName" type:"string"` + // Arn is a required field + Arn *string `locationName:"arn" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s CloudWatchLogsConfig) String() string { +func (s DeleteReportInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CloudWatchLogsConfig) GoString() string { +func (s DeleteReportInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CloudWatchLogsConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CloudWatchLogsConfig"} - if s.Status == nil { - invalidParams.Add(request.NewErrParamRequired("Status")) +func (s *DeleteReportInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteReportInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.Arn != nil && len(*s.Arn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 1)) } if invalidParams.Len() > 0 { @@ -3846,252 +7180,108 @@ func (s *CloudWatchLogsConfig) Validate() error { return nil } -// SetGroupName sets the GroupName field's value. -func (s *CloudWatchLogsConfig) SetGroupName(v string) *CloudWatchLogsConfig { - s.GroupName = &v +// SetArn sets the Arn field's value. +func (s *DeleteReportInput) SetArn(v string) *DeleteReportInput { + s.Arn = &v return s } -// SetStatus sets the Status field's value. -func (s *CloudWatchLogsConfig) SetStatus(v string) *CloudWatchLogsConfig { - s.Status = &v - return s +type DeleteReportOutput struct { + _ struct{} `type:"structure"` } -// SetStreamName sets the StreamName field's value. -func (s *CloudWatchLogsConfig) SetStreamName(v string) *CloudWatchLogsConfig { - s.StreamName = &v - return s +// String returns the string representation +func (s DeleteReportOutput) String() string { + return awsutil.Prettify(s) } -type CreateProjectInput struct { - _ struct{} `type:"structure"` - - // Information about the build output artifacts for the build project. - // - // Artifacts is a required field - Artifacts *ProjectArtifacts `locationName:"artifacts" type:"structure" required:"true"` - - // Set this to true to generate a publicly accessible URL for your project's - // build badge. - BadgeEnabled *bool `locationName:"badgeEnabled" type:"boolean"` - - // Stores recently used information so that it can be quickly accessed at a - // later time. - Cache *ProjectCache `locationName:"cache" type:"structure"` - - // A description that makes the build project easy to identify. - Description *string `locationName:"description" type:"string"` - - // The AWS Key Management Service (AWS KMS) customer master key (CMK) to be - // used for encrypting the build output artifacts. - // - // You can use a cross-account KMS key to encrypt the build output artifacts - // if your service role has permission to that key. - // - // You can specify either the Amazon Resource Name (ARN) of the CMK or, if available, - // the CMK's alias (using the format alias/alias-name ). - EncryptionKey *string `locationName:"encryptionKey" min:"1" type:"string"` - - // Information about the build environment for the build project. - // - // Environment is a required field - Environment *ProjectEnvironment `locationName:"environment" type:"structure" required:"true"` - - // An array of ProjectFileSystemLocation objects for a CodeBuild build project. - // A ProjectFileSystemLocation object specifies the identifier, location, mountOptions, - // mountPoint, and type of a file system created using Amazon Elastic File System. - FileSystemLocations []*ProjectFileSystemLocation `locationName:"fileSystemLocations" type:"list"` +// GoString returns the string representation +func (s DeleteReportOutput) GoString() string { + return s.String() +} - // Information about logs for the build project. These can be logs in Amazon - // CloudWatch Logs, logs uploaded to a specified S3 bucket, or both. - LogsConfig *LogsConfig `locationName:"logsConfig" type:"structure"` +type DeleteResourcePolicyInput struct { + _ struct{} `type:"structure"` - // The name of the build project. + // The ARN of the resource that is associated with the resource policy. // - // Name is a required field - Name *string `locationName:"name" min:"2" type:"string" required:"true"` - - // The number of minutes a build is allowed to be queued before it times out. - QueuedTimeoutInMinutes *int64 `locationName:"queuedTimeoutInMinutes" min:"5" type:"integer"` + // ResourceArn is a required field + ResourceArn *string `locationName:"resourceArn" min:"1" type:"string" required:"true"` +} - // An array of ProjectArtifacts objects. - SecondaryArtifacts []*ProjectArtifacts `locationName:"secondaryArtifacts" type:"list"` +// String returns the string representation +func (s DeleteResourcePolicyInput) String() string { + return awsutil.Prettify(s) +} - // An array of ProjectSourceVersion objects. If secondarySourceVersions is specified - // at the build level, then they take precedence over these secondarySourceVersions - // (at the project level). - SecondarySourceVersions []*ProjectSourceVersion `locationName:"secondarySourceVersions" type:"list"` +// GoString returns the string representation +func (s DeleteResourcePolicyInput) GoString() string { + return s.String() +} - // An array of ProjectSource objects. - SecondarySources []*ProjectSource `locationName:"secondarySources" type:"list"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteResourcePolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteResourcePolicyInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } - // The ARN of the AWS Identity and Access Management (IAM) role that enables - // AWS CodeBuild to interact with dependent AWS services on behalf of the AWS - // account. - // - // ServiceRole is a required field - ServiceRole *string `locationName:"serviceRole" min:"1" type:"string" required:"true"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - // Information about the build input source code for the build project. - // - // Source is a required field - Source *ProjectSource `locationName:"source" type:"structure" required:"true"` +// SetResourceArn sets the ResourceArn field's value. +func (s *DeleteResourcePolicyInput) SetResourceArn(v string) *DeleteResourcePolicyInput { + s.ResourceArn = &v + return s +} - // A version of the build input to be built for this project. If not specified, - // the latest version is used. If specified, it must be one of: - // - // * For AWS CodeCommit: the commit ID, branch, or Git tag to use. - // - // * For GitHub: the commit ID, pull request ID, branch name, or tag name - // that corresponds to the version of the source code you want to build. - // If a pull request ID is specified, it must use the format pr/pull-request-ID - // (for example pr/25). If a branch name is specified, the branch's HEAD - // commit ID is used. If not specified, the default branch's HEAD commit - // ID is used. - // - // * For Bitbucket: the commit ID, branch name, or tag name that corresponds - // to the version of the source code you want to build. If a branch name - // is specified, the branch's HEAD commit ID is used. If not specified, the - // default branch's HEAD commit ID is used. - // - // * For Amazon Simple Storage Service (Amazon S3): the version ID of the - // object that represents the build input ZIP file to use. - // - // If sourceVersion is specified at the build level, then that version takes - // precedence over this sourceVersion (at the project level). - // - // For more information, see Source Version Sample with CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/sample-source-version.html) - // in the AWS CodeBuild User Guide. - SourceVersion *string `locationName:"sourceVersion" type:"string"` +type DeleteResourcePolicyOutput struct { + _ struct{} `type:"structure"` +} - // A set of tags for this build project. - // - // These tags are available for use by AWS services that support AWS CodeBuild - // build project tags. - Tags []*Tag `locationName:"tags" type:"list"` +// String returns the string representation +func (s DeleteResourcePolicyOutput) String() string { + return awsutil.Prettify(s) +} - // How long, in minutes, from 5 to 480 (8 hours), for AWS CodeBuild to wait - // before it times out any build that has not been marked as completed. The - // default is 60 minutes. - TimeoutInMinutes *int64 `locationName:"timeoutInMinutes" min:"5" type:"integer"` +// GoString returns the string representation +func (s DeleteResourcePolicyOutput) GoString() string { + return s.String() +} - // VpcConfig enables AWS CodeBuild to access resources in an Amazon VPC. - VpcConfig *VpcConfig `locationName:"vpcConfig" type:"structure"` +type DeleteSourceCredentialsInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the token. + // + // Arn is a required field + Arn *string `locationName:"arn" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s CreateProjectInput) String() string { +func (s DeleteSourceCredentialsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateProjectInput) GoString() string { +func (s DeleteSourceCredentialsInput) 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.Artifacts == nil { - invalidParams.Add(request.NewErrParamRequired("Artifacts")) - } - if s.EncryptionKey != nil && len(*s.EncryptionKey) < 1 { - invalidParams.Add(request.NewErrParamMinLen("EncryptionKey", 1)) - } - if s.Environment == nil { - invalidParams.Add(request.NewErrParamRequired("Environment")) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 2 { - invalidParams.Add(request.NewErrParamMinLen("Name", 2)) - } - if s.QueuedTimeoutInMinutes != nil && *s.QueuedTimeoutInMinutes < 5 { - invalidParams.Add(request.NewErrParamMinValue("QueuedTimeoutInMinutes", 5)) - } - if s.ServiceRole == nil { - invalidParams.Add(request.NewErrParamRequired("ServiceRole")) - } - if s.ServiceRole != nil && len(*s.ServiceRole) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ServiceRole", 1)) - } - if s.Source == nil { - invalidParams.Add(request.NewErrParamRequired("Source")) - } - if s.TimeoutInMinutes != nil && *s.TimeoutInMinutes < 5 { - invalidParams.Add(request.NewErrParamMinValue("TimeoutInMinutes", 5)) - } - if s.Artifacts != nil { - if err := s.Artifacts.Validate(); err != nil { - invalidParams.AddNested("Artifacts", err.(request.ErrInvalidParams)) - } - } - if s.Cache != nil { - if err := s.Cache.Validate(); err != nil { - invalidParams.AddNested("Cache", err.(request.ErrInvalidParams)) - } - } - if s.Environment != nil { - if err := s.Environment.Validate(); err != nil { - invalidParams.AddNested("Environment", err.(request.ErrInvalidParams)) - } - } - if s.LogsConfig != nil { - if err := s.LogsConfig.Validate(); err != nil { - invalidParams.AddNested("LogsConfig", err.(request.ErrInvalidParams)) - } - } - if s.SecondaryArtifacts != nil { - for i, v := range s.SecondaryArtifacts { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "SecondaryArtifacts", i), err.(request.ErrInvalidParams)) - } - } - } - if s.SecondarySourceVersions != nil { - for i, v := range s.SecondarySourceVersions { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "SecondarySourceVersions", i), err.(request.ErrInvalidParams)) - } - } - } - if s.SecondarySources != nil { - for i, v := range s.SecondarySources { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "SecondarySources", i), err.(request.ErrInvalidParams)) - } - } - } - if s.Source != nil { - if err := s.Source.Validate(); err != nil { - invalidParams.AddNested("Source", err.(request.ErrInvalidParams)) - } - } - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } +func (s *DeleteSourceCredentialsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteSourceCredentialsInput"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) } - if s.VpcConfig != nil { - if err := s.VpcConfig.Validate(); err != nil { - invalidParams.AddNested("VpcConfig", err.(request.ErrInvalidParams)) - } + if s.Arn != nil && len(*s.Arn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Arn", 1)) } if invalidParams.Len() > 0 { @@ -4100,192 +7290,275 @@ func (s *CreateProjectInput) Validate() error { return nil } -// SetArtifacts sets the Artifacts field's value. -func (s *CreateProjectInput) SetArtifacts(v *ProjectArtifacts) *CreateProjectInput { - s.Artifacts = v +// SetArn sets the Arn field's value. +func (s *DeleteSourceCredentialsInput) SetArn(v string) *DeleteSourceCredentialsInput { + s.Arn = &v return s } -// SetBadgeEnabled sets the BadgeEnabled field's value. -func (s *CreateProjectInput) SetBadgeEnabled(v bool) *CreateProjectInput { - s.BadgeEnabled = &v - return s +type DeleteSourceCredentialsOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the token. + Arn *string `locationName:"arn" min:"1" type:"string"` } -// SetCache sets the Cache field's value. -func (s *CreateProjectInput) SetCache(v *ProjectCache) *CreateProjectInput { - s.Cache = v - return s +// String returns the string representation +func (s DeleteSourceCredentialsOutput) String() string { + return awsutil.Prettify(s) } -// SetDescription sets the Description field's value. -func (s *CreateProjectInput) SetDescription(v string) *CreateProjectInput { - s.Description = &v - return s +// GoString returns the string representation +func (s DeleteSourceCredentialsOutput) GoString() string { + return s.String() } -// SetEncryptionKey sets the EncryptionKey field's value. -func (s *CreateProjectInput) SetEncryptionKey(v string) *CreateProjectInput { - s.EncryptionKey = &v +// SetArn sets the Arn field's value. +func (s *DeleteSourceCredentialsOutput) SetArn(v string) *DeleteSourceCredentialsOutput { + s.Arn = &v return s } -// SetEnvironment sets the Environment field's value. -func (s *CreateProjectInput) SetEnvironment(v *ProjectEnvironment) *CreateProjectInput { - s.Environment = v - return s +type DeleteWebhookInput struct { + _ struct{} `type:"structure"` + + // The name of the AWS CodeBuild project. + // + // ProjectName is a required field + ProjectName *string `locationName:"projectName" min:"2" type:"string" required:"true"` } -// SetFileSystemLocations sets the FileSystemLocations field's value. -func (s *CreateProjectInput) SetFileSystemLocations(v []*ProjectFileSystemLocation) *CreateProjectInput { - s.FileSystemLocations = v - return s +// String returns the string representation +func (s DeleteWebhookInput) String() string { + return awsutil.Prettify(s) } -// SetLogsConfig sets the LogsConfig field's value. -func (s *CreateProjectInput) SetLogsConfig(v *LogsConfig) *CreateProjectInput { - s.LogsConfig = v - return s +// GoString returns the string representation +func (s DeleteWebhookInput) GoString() string { + return s.String() } -// SetName sets the Name field's value. -func (s *CreateProjectInput) SetName(v string) *CreateProjectInput { - s.Name = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteWebhookInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteWebhookInput"} + if s.ProjectName == nil { + invalidParams.Add(request.NewErrParamRequired("ProjectName")) + } + if s.ProjectName != nil && len(*s.ProjectName) < 2 { + invalidParams.Add(request.NewErrParamMinLen("ProjectName", 2)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetQueuedTimeoutInMinutes sets the QueuedTimeoutInMinutes field's value. -func (s *CreateProjectInput) SetQueuedTimeoutInMinutes(v int64) *CreateProjectInput { - s.QueuedTimeoutInMinutes = &v +// SetProjectName sets the ProjectName field's value. +func (s *DeleteWebhookInput) SetProjectName(v string) *DeleteWebhookInput { + s.ProjectName = &v return s } -// SetSecondaryArtifacts sets the SecondaryArtifacts field's value. -func (s *CreateProjectInput) SetSecondaryArtifacts(v []*ProjectArtifacts) *CreateProjectInput { - s.SecondaryArtifacts = v - return s -} +type DeleteWebhookOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteWebhookOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteWebhookOutput) GoString() string { + return s.String() +} + +type DescribeCodeCoveragesInput struct { + _ struct{} `type:"structure"` + + // The maximum line coverage percentage to report. + MaxLineCoveragePercentage *float64 `locationName:"maxLineCoveragePercentage" type:"double"` + + // The maximum number of results to return. + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` + + // The minimum line coverage percentage to report. + MinLineCoveragePercentage *float64 `locationName:"minLineCoveragePercentage" type:"double"` + + // The nextToken value returned from a previous call to DescribeCodeCoverages. + // This specifies the next item to return. To return the beginning of the list, + // exclude this parameter. + NextToken *string `locationName:"nextToken" type:"string"` + + // The ARN of the report for which test cases are returned. + // + // ReportArn is a required field + ReportArn *string `locationName:"reportArn" min:"1" type:"string" required:"true"` + + // Specifies how the results are sorted. Possible values are: + // + // FILE_PATH + // + // The results are sorted by file path. + // + // LINE_COVERAGE_PERCENTAGE + // + // The results are sorted by the percentage of lines that are covered. + SortBy *string `locationName:"sortBy" type:"string" enum:"ReportCodeCoverageSortByType"` + + // Specifies if the results are sorted in ascending or descending order. + SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` +} + +// String returns the string representation +func (s DescribeCodeCoveragesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCodeCoveragesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeCodeCoveragesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeCodeCoveragesInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.ReportArn == nil { + invalidParams.Add(request.NewErrParamRequired("ReportArn")) + } + if s.ReportArn != nil && len(*s.ReportArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ReportArn", 1)) + } -// SetSecondarySourceVersions sets the SecondarySourceVersions field's value. -func (s *CreateProjectInput) SetSecondarySourceVersions(v []*ProjectSourceVersion) *CreateProjectInput { - s.SecondarySourceVersions = v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetSecondarySources sets the SecondarySources field's value. -func (s *CreateProjectInput) SetSecondarySources(v []*ProjectSource) *CreateProjectInput { - s.SecondarySources = v +// SetMaxLineCoveragePercentage sets the MaxLineCoveragePercentage field's value. +func (s *DescribeCodeCoveragesInput) SetMaxLineCoveragePercentage(v float64) *DescribeCodeCoveragesInput { + s.MaxLineCoveragePercentage = &v return s } -// SetServiceRole sets the ServiceRole field's value. -func (s *CreateProjectInput) SetServiceRole(v string) *CreateProjectInput { - s.ServiceRole = &v +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeCodeCoveragesInput) SetMaxResults(v int64) *DescribeCodeCoveragesInput { + s.MaxResults = &v return s } -// SetSource sets the Source field's value. -func (s *CreateProjectInput) SetSource(v *ProjectSource) *CreateProjectInput { - s.Source = v +// SetMinLineCoveragePercentage sets the MinLineCoveragePercentage field's value. +func (s *DescribeCodeCoveragesInput) SetMinLineCoveragePercentage(v float64) *DescribeCodeCoveragesInput { + s.MinLineCoveragePercentage = &v return s } -// SetSourceVersion sets the SourceVersion field's value. -func (s *CreateProjectInput) SetSourceVersion(v string) *CreateProjectInput { - s.SourceVersion = &v +// SetNextToken sets the NextToken field's value. +func (s *DescribeCodeCoveragesInput) SetNextToken(v string) *DescribeCodeCoveragesInput { + s.NextToken = &v return s } -// SetTags sets the Tags field's value. -func (s *CreateProjectInput) SetTags(v []*Tag) *CreateProjectInput { - s.Tags = v +// SetReportArn sets the ReportArn field's value. +func (s *DescribeCodeCoveragesInput) SetReportArn(v string) *DescribeCodeCoveragesInput { + s.ReportArn = &v return s } -// SetTimeoutInMinutes sets the TimeoutInMinutes field's value. -func (s *CreateProjectInput) SetTimeoutInMinutes(v int64) *CreateProjectInput { - s.TimeoutInMinutes = &v +// SetSortBy sets the SortBy field's value. +func (s *DescribeCodeCoveragesInput) SetSortBy(v string) *DescribeCodeCoveragesInput { + s.SortBy = &v return s } -// SetVpcConfig sets the VpcConfig field's value. -func (s *CreateProjectInput) SetVpcConfig(v *VpcConfig) *CreateProjectInput { - s.VpcConfig = v +// SetSortOrder sets the SortOrder field's value. +func (s *DescribeCodeCoveragesInput) SetSortOrder(v string) *DescribeCodeCoveragesInput { + s.SortOrder = &v return s } -type CreateProjectOutput struct { +type DescribeCodeCoveragesOutput struct { _ struct{} `type:"structure"` - // Information about the build project that was created. - Project *Project `locationName:"project" type:"structure"` + // An array of CodeCoverage objects that contain the results. + CodeCoverages []*CodeCoverage `locationName:"codeCoverages" type:"list"` + + // If there are more items to return, this contains a token that is passed to + // a subsequent call to DescribeCodeCoverages to retrieve the next set of items. + NextToken *string `locationName:"nextToken" type:"string"` } // String returns the string representation -func (s CreateProjectOutput) String() string { +func (s DescribeCodeCoveragesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateProjectOutput) GoString() string { +func (s DescribeCodeCoveragesOutput) GoString() string { return s.String() } -// SetProject sets the Project field's value. -func (s *CreateProjectOutput) SetProject(v *Project) *CreateProjectOutput { - s.Project = v +// SetCodeCoverages sets the CodeCoverages field's value. +func (s *DescribeCodeCoveragesOutput) SetCodeCoverages(v []*CodeCoverage) *DescribeCodeCoveragesOutput { + s.CodeCoverages = v return s } -type CreateReportGroupInput struct { +// SetNextToken sets the NextToken field's value. +func (s *DescribeCodeCoveragesOutput) SetNextToken(v string) *DescribeCodeCoveragesOutput { + s.NextToken = &v + return s +} + +type DescribeTestCasesInput struct { _ struct{} `type:"structure"` - // A ReportExportConfig object that contains information about where the report - // group test results are exported. - // - // ExportConfig is a required field - ExportConfig *ReportExportConfig `locationName:"exportConfig" type:"structure" required:"true"` + // A TestCaseFilter object used to filter the returned reports. + Filter *TestCaseFilter `locationName:"filter" type:"structure"` - // The name of the report group. - // - // Name is a required field - Name *string `locationName:"name" min:"2" type:"string" required:"true"` + // The maximum number of paginated test cases returned per response. Use nextToken + // to iterate pages in the list of returned TestCase objects. The default value + // is 100. + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` - // The type of report group. + // During a previous call, the maximum number of items that can be returned + // is the value specified in maxResults. If there more items in the list, then + // a unique string called a nextToken is returned. To get the next batch of + // items in the list, call this operation again, adding the next token to the + // call. To get all of the items in the list, keep calling this operation with + // each subsequent next token that is returned, until no more next tokens are + // returned. + NextToken *string `locationName:"nextToken" type:"string"` + + // The ARN of the report for which test cases are returned. // - // Type is a required field - Type *string `locationName:"type" type:"string" required:"true" enum:"ReportType"` + // ReportArn is a required field + ReportArn *string `locationName:"reportArn" type:"string" required:"true"` } // String returns the string representation -func (s CreateReportGroupInput) String() string { +func (s DescribeTestCasesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateReportGroupInput) GoString() string { +func (s DescribeTestCasesInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateReportGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateReportGroupInput"} - if s.ExportConfig == nil { - invalidParams.Add(request.NewErrParamRequired("ExportConfig")) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 2 { - invalidParams.Add(request.NewErrParamMinLen("Name", 2)) - } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) +func (s *DescribeTestCasesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeTestCasesInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } - if s.ExportConfig != nil { - if err := s.ExportConfig.Validate(); err != nil { - invalidParams.AddNested("ExportConfig", err.(request.ErrInvalidParams)) - } + if s.ReportArn == nil { + invalidParams.Add(request.NewErrParamRequired("ReportArn")) } if invalidParams.Len() > 0 { @@ -4294,168 +7567,235 @@ func (s *CreateReportGroupInput) Validate() error { return nil } -// SetExportConfig sets the ExportConfig field's value. -func (s *CreateReportGroupInput) SetExportConfig(v *ReportExportConfig) *CreateReportGroupInput { - s.ExportConfig = v +// SetFilter sets the Filter field's value. +func (s *DescribeTestCasesInput) SetFilter(v *TestCaseFilter) *DescribeTestCasesInput { + s.Filter = v return s } -// SetName sets the Name field's value. -func (s *CreateReportGroupInput) SetName(v string) *CreateReportGroupInput { - s.Name = &v +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeTestCasesInput) SetMaxResults(v int64) *DescribeTestCasesInput { + s.MaxResults = &v return s } -// SetType sets the Type field's value. -func (s *CreateReportGroupInput) SetType(v string) *CreateReportGroupInput { - s.Type = &v +// SetNextToken sets the NextToken field's value. +func (s *DescribeTestCasesInput) SetNextToken(v string) *DescribeTestCasesInput { + s.NextToken = &v return s } -type CreateReportGroupOutput struct { +// SetReportArn sets the ReportArn field's value. +func (s *DescribeTestCasesInput) SetReportArn(v string) *DescribeTestCasesInput { + s.ReportArn = &v + return s +} + +type DescribeTestCasesOutput struct { _ struct{} `type:"structure"` - // Information about the report group that was created. - ReportGroup *ReportGroup `locationName:"reportGroup" type:"structure"` + // During a previous call, the maximum number of items that can be returned + // is the value specified in maxResults. If there more items in the list, then + // a unique string called a nextToken is returned. To get the next batch of + // items in the list, call this operation again, adding the next token to the + // call. To get all of the items in the list, keep calling this operation with + // each subsequent next token that is returned, until no more next tokens are + // returned. + NextToken *string `locationName:"nextToken" type:"string"` + + // The returned list of test cases. + TestCases []*TestCase `locationName:"testCases" type:"list"` } // String returns the string representation -func (s CreateReportGroupOutput) String() string { +func (s DescribeTestCasesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateReportGroupOutput) GoString() string { +func (s DescribeTestCasesOutput) GoString() string { return s.String() } -// SetReportGroup sets the ReportGroup field's value. -func (s *CreateReportGroupOutput) SetReportGroup(v *ReportGroup) *CreateReportGroupOutput { - s.ReportGroup = v +// SetNextToken sets the NextToken field's value. +func (s *DescribeTestCasesOutput) SetNextToken(v string) *DescribeTestCasesOutput { + s.NextToken = &v return s } -type CreateWebhookInput struct { +// SetTestCases sets the TestCases field's value. +func (s *DescribeTestCasesOutput) SetTestCases(v []*TestCase) *DescribeTestCasesOutput { + s.TestCases = v + return s +} + +// Information about a Docker image that is managed by AWS CodeBuild. +type EnvironmentImage struct { _ struct{} `type:"structure"` - // A regular expression used to determine which repository branches are built - // when a webhook is triggered. If the name of a branch matches the regular - // expression, then it is built. If branchFilter is empty, then all branches - // are built. - // - // It is recommended that you use filterGroups instead of branchFilter. - BranchFilter *string `locationName:"branchFilter" type:"string"` + // The description of the Docker image. + Description *string `locationName:"description" type:"string"` - // An array of arrays of WebhookFilter objects used to determine which webhooks - // are triggered. At least one WebhookFilter in the array must specify EVENT - // as its type. - // - // For a build to be triggered, at least one filter group in the filterGroups - // array must pass. For a filter group to pass, each of its filters must pass. - FilterGroups [][]*WebhookFilter `locationName:"filterGroups" type:"list"` + // The name of the Docker image. + Name *string `locationName:"name" type:"string"` - // The name of the AWS CodeBuild project. - // - // ProjectName is a required field - ProjectName *string `locationName:"projectName" min:"2" type:"string" required:"true"` + // A list of environment image versions. + Versions []*string `locationName:"versions" type:"list"` } // String returns the string representation -func (s CreateWebhookInput) String() string { +func (s EnvironmentImage) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateWebhookInput) GoString() string { +func (s EnvironmentImage) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateWebhookInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateWebhookInput"} - if s.ProjectName == nil { - invalidParams.Add(request.NewErrParamRequired("ProjectName")) - } - if s.ProjectName != nil && len(*s.ProjectName) < 2 { - invalidParams.Add(request.NewErrParamMinLen("ProjectName", 2)) - } +// SetDescription sets the Description field's value. +func (s *EnvironmentImage) SetDescription(v string) *EnvironmentImage { + s.Description = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetName sets the Name field's value. +func (s *EnvironmentImage) SetName(v string) *EnvironmentImage { + s.Name = &v + return s +} + +// SetVersions sets the Versions field's value. +func (s *EnvironmentImage) SetVersions(v []*string) *EnvironmentImage { + s.Versions = v + return s +} + +// A set of Docker images that are related by programming language and are managed +// by AWS CodeBuild. +type EnvironmentLanguage struct { + _ struct{} `type:"structure"` + + // The list of Docker images that are related by the specified programming language. + Images []*EnvironmentImage `locationName:"images" type:"list"` + + // The programming language for the Docker images. + Language *string `locationName:"language" type:"string" enum:"LanguageType"` +} + +// String returns the string representation +func (s EnvironmentLanguage) String() string { + return awsutil.Prettify(s) } -// SetBranchFilter sets the BranchFilter field's value. -func (s *CreateWebhookInput) SetBranchFilter(v string) *CreateWebhookInput { - s.BranchFilter = &v - return s +// GoString returns the string representation +func (s EnvironmentLanguage) GoString() string { + return s.String() } -// SetFilterGroups sets the FilterGroups field's value. -func (s *CreateWebhookInput) SetFilterGroups(v [][]*WebhookFilter) *CreateWebhookInput { - s.FilterGroups = v +// SetImages sets the Images field's value. +func (s *EnvironmentLanguage) SetImages(v []*EnvironmentImage) *EnvironmentLanguage { + s.Images = v return s } -// SetProjectName sets the ProjectName field's value. -func (s *CreateWebhookInput) SetProjectName(v string) *CreateWebhookInput { - s.ProjectName = &v +// SetLanguage sets the Language field's value. +func (s *EnvironmentLanguage) SetLanguage(v string) *EnvironmentLanguage { + s.Language = &v return s } -type CreateWebhookOutput struct { +// A set of Docker images that are related by platform and are managed by AWS +// CodeBuild. +type EnvironmentPlatform struct { _ struct{} `type:"structure"` - // Information about a webhook that connects repository events to a build project - // in AWS CodeBuild. - Webhook *Webhook `locationName:"webhook" type:"structure"` + // The list of programming languages that are available for the specified platform. + Languages []*EnvironmentLanguage `locationName:"languages" type:"list"` + + // The platform's name. + Platform *string `locationName:"platform" type:"string" enum:"PlatformType"` } // String returns the string representation -func (s CreateWebhookOutput) String() string { +func (s EnvironmentPlatform) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateWebhookOutput) GoString() string { +func (s EnvironmentPlatform) GoString() string { return s.String() } -// SetWebhook sets the Webhook field's value. -func (s *CreateWebhookOutput) SetWebhook(v *Webhook) *CreateWebhookOutput { - s.Webhook = v +// SetLanguages sets the Languages field's value. +func (s *EnvironmentPlatform) SetLanguages(v []*EnvironmentLanguage) *EnvironmentPlatform { + s.Languages = v return s } -type DeleteProjectInput struct { +// SetPlatform sets the Platform field's value. +func (s *EnvironmentPlatform) SetPlatform(v string) *EnvironmentPlatform { + s.Platform = &v + return s +} + +// Information about an environment variable for a build project or a build. +type EnvironmentVariable struct { _ struct{} `type:"structure"` - // The name of the build project. + // The name or key of the environment variable. // // Name is a required field Name *string `locationName:"name" min:"1" type:"string" required:"true"` + + // The type of environment variable. Valid values include: + // + // * PARAMETER_STORE: An environment variable stored in Amazon EC2 Systems + // Manager Parameter Store. To learn how to specify a parameter store environment + // variable, see parameter store reference-key in the buildspec file (https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#parameter-store-build-spec). + // + // * PLAINTEXT: An environment variable in plain text format. This is the + // default value. + // + // * SECRETS_MANAGER: An environment variable stored in AWS Secrets Manager. + // To learn how to specify a secrets manager environment variable, see secrets + // manager reference-key in the buildspec file (https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#secrets-manager-build-spec). + Type *string `locationName:"type" type:"string" enum:"EnvironmentVariableType"` + + // The value of the environment variable. + // + // We strongly discourage the use of PLAINTEXT environment variables to store + // sensitive values, especially AWS secret key IDs and secret access keys. PLAINTEXT + // environment variables can be displayed in plain text using the AWS CodeBuild + // console and the AWS Command Line Interface (AWS CLI). For sensitive values, + // we recommend you use an environment variable of type PARAMETER_STORE or SECRETS_MANAGER. + // + // Value is a required field + Value *string `locationName:"value" type:"string" required:"true"` } // String returns the string representation -func (s DeleteProjectInput) String() string { +func (s EnvironmentVariable) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteProjectInput) GoString() string { +func (s EnvironmentVariable) 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"} +func (s *EnvironmentVariable) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "EnvironmentVariable"} if s.Name == nil { invalidParams.Add(request.NewErrParamRequired("Name")) } if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } + if s.Value == nil { + invalidParams.Add(request.NewErrParamRequired("Value")) + } if invalidParams.Len() > 0 { return invalidParams @@ -4464,52 +7804,88 @@ func (s *DeleteProjectInput) Validate() error { } // SetName sets the Name field's value. -func (s *DeleteProjectInput) SetName(v string) *DeleteProjectInput { +func (s *EnvironmentVariable) SetName(v string) *EnvironmentVariable { s.Name = &v return s } -type DeleteProjectOutput struct { +// SetType sets the Type field's value. +func (s *EnvironmentVariable) SetType(v string) *EnvironmentVariable { + s.Type = &v + return s +} + +// SetValue sets the Value field's value. +func (s *EnvironmentVariable) SetValue(v string) *EnvironmentVariable { + s.Value = &v + return s +} + +// Information about an exported environment variable. +type ExportedEnvironmentVariable struct { _ struct{} `type:"structure"` + + // The name of this exported environment variable. + Name *string `locationName:"name" min:"1" type:"string"` + + // The value assigned to this exported environment variable. + // + // During a build, the value of a variable is available starting with the install + // phase. It can be updated between the start of the install phase and the end + // of the post_build phase. After the post_build phase ends, the value of exported + // variables cannot change. + Value *string `locationName:"value" type:"string"` } // String returns the string representation -func (s DeleteProjectOutput) String() string { +func (s ExportedEnvironmentVariable) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteProjectOutput) GoString() string { +func (s ExportedEnvironmentVariable) GoString() string { return s.String() } -type DeleteReportGroupInput struct { +// SetName sets the Name field's value. +func (s *ExportedEnvironmentVariable) SetName(v string) *ExportedEnvironmentVariable { + s.Name = &v + return s +} + +// SetValue sets the Value field's value. +func (s *ExportedEnvironmentVariable) SetValue(v string) *ExportedEnvironmentVariable { + s.Value = &v + return s +} + +type GetResourcePolicyInput struct { _ struct{} `type:"structure"` - // The ARN of the report group to delete. + // The ARN of the resource that is associated with the resource policy. // - // Arn is a required field - Arn *string `locationName:"arn" min:"1" type:"string" required:"true"` + // ResourceArn is a required field + ResourceArn *string `locationName:"resourceArn" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DeleteReportGroupInput) String() string { +func (s GetResourcePolicyInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteReportGroupInput) GoString() string { +func (s GetResourcePolicyInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteReportGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteReportGroupInput"} - if s.Arn == nil { - invalidParams.Add(request.NewErrParamRequired("Arn")) +func (s *GetResourcePolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetResourcePolicyInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) } - if s.Arn != nil && len(*s.Arn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Arn", 1)) + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) } if invalidParams.Len() > 0 { @@ -4518,53 +7894,61 @@ func (s *DeleteReportGroupInput) Validate() error { return nil } -// SetArn sets the Arn field's value. -func (s *DeleteReportGroupInput) SetArn(v string) *DeleteReportGroupInput { - s.Arn = &v +// SetResourceArn sets the ResourceArn field's value. +func (s *GetResourcePolicyInput) SetResourceArn(v string) *GetResourcePolicyInput { + s.ResourceArn = &v return s } -type DeleteReportGroupOutput struct { +type GetResourcePolicyOutput struct { _ struct{} `type:"structure"` + + // The resource policy for the resource identified by the input ARN parameter. + Policy *string `locationName:"policy" min:"1" type:"string"` } // String returns the string representation -func (s DeleteReportGroupOutput) String() string { +func (s GetResourcePolicyOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteReportGroupOutput) GoString() string { +func (s GetResourcePolicyOutput) GoString() string { return s.String() } -type DeleteReportInput struct { +// SetPolicy sets the Policy field's value. +func (s *GetResourcePolicyOutput) SetPolicy(v string) *GetResourcePolicyOutput { + s.Policy = &v + return s +} + +// Information about the Git submodules configuration for an AWS CodeBuild build +// project. +type GitSubmodulesConfig struct { _ struct{} `type:"structure"` - // The ARN of the report to delete. + // Set to true to fetch Git submodules for your AWS CodeBuild build project. // - // Arn is a required field - Arn *string `locationName:"arn" min:"1" type:"string" required:"true"` + // FetchSubmodules is a required field + FetchSubmodules *bool `locationName:"fetchSubmodules" type:"boolean" required:"true"` } // String returns the string representation -func (s DeleteReportInput) String() string { +func (s GitSubmodulesConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteReportInput) GoString() string { +func (s GitSubmodulesConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteReportInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteReportInput"} - if s.Arn == nil { - invalidParams.Add(request.NewErrParamRequired("Arn")) - } - if s.Arn != nil && len(*s.Arn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Arn", 1)) +func (s *GitSubmodulesConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GitSubmodulesConfig"} + if s.FetchSubmodules == nil { + invalidParams.Add(request.NewErrParamRequired("FetchSubmodules")) } if invalidParams.Len() > 0 { @@ -4573,53 +7957,70 @@ func (s *DeleteReportInput) Validate() error { return nil } -// SetArn sets the Arn field's value. -func (s *DeleteReportInput) SetArn(v string) *DeleteReportInput { - s.Arn = &v +// SetFetchSubmodules sets the FetchSubmodules field's value. +func (s *GitSubmodulesConfig) SetFetchSubmodules(v bool) *GitSubmodulesConfig { + s.FetchSubmodules = &v return s } -type DeleteReportOutput struct { +type ImportSourceCredentialsInput struct { _ struct{} `type:"structure"` -} -// String returns the string representation -func (s DeleteReportOutput) String() string { - return awsutil.Prettify(s) -} + // The type of authentication used to connect to a GitHub, GitHub Enterprise, + // or Bitbucket repository. An OAUTH connection is not supported by the API + // and must be created using the AWS CodeBuild console. + // + // AuthType is a required field + AuthType *string `locationName:"authType" type:"string" required:"true" enum:"AuthType"` -// GoString returns the string representation -func (s DeleteReportOutput) GoString() string { - return s.String() -} + // The source provider used for this project. + // + // ServerType is a required field + ServerType *string `locationName:"serverType" type:"string" required:"true" enum:"ServerType"` -type DeleteResourcePolicyInput struct { - _ struct{} `type:"structure"` + // Set to false to prevent overwriting the repository source credentials. Set + // to true to overwrite the repository source credentials. The default value + // is true. + ShouldOverwrite *bool `locationName:"shouldOverwrite" type:"boolean"` - // The ARN of the resource that is associated with the resource policy. + // For GitHub or GitHub Enterprise, this is the personal access token. For Bitbucket, + // this is the app password. // - // ResourceArn is a required field - ResourceArn *string `locationName:"resourceArn" min:"1" type:"string" required:"true"` + // Token is a required field + Token *string `locationName:"token" min:"1" type:"string" required:"true" sensitive:"true"` + + // The Bitbucket username when the authType is BASIC_AUTH. This parameter is + // not valid for other types of source providers or connections. + Username *string `locationName:"username" min:"1" type:"string"` } // String returns the string representation -func (s DeleteResourcePolicyInput) String() string { +func (s ImportSourceCredentialsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteResourcePolicyInput) GoString() string { +func (s ImportSourceCredentialsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteResourcePolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteResourcePolicyInput"} - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) +func (s *ImportSourceCredentialsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ImportSourceCredentialsInput"} + if s.AuthType == nil { + invalidParams.Add(request.NewErrParamRequired("AuthType")) + } + if s.ServerType == nil { + invalidParams.Add(request.NewErrParamRequired("ServerType")) } - if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + if s.Token == nil { + invalidParams.Add(request.NewErrParamRequired("Token")) + } + if s.Token != nil && len(*s.Token) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Token", 1)) + } + if s.Username != nil && len(*s.Username) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Username", 1)) } if invalidParams.Len() > 0 { @@ -4628,117 +8029,142 @@ func (s *DeleteResourcePolicyInput) Validate() error { return nil } -// SetResourceArn sets the ResourceArn field's value. -func (s *DeleteResourcePolicyInput) SetResourceArn(v string) *DeleteResourcePolicyInput { - s.ResourceArn = &v +// SetAuthType sets the AuthType field's value. +func (s *ImportSourceCredentialsInput) SetAuthType(v string) *ImportSourceCredentialsInput { + s.AuthType = &v return s } -type DeleteResourcePolicyOutput struct { - _ struct{} `type:"structure"` +// SetServerType sets the ServerType field's value. +func (s *ImportSourceCredentialsInput) SetServerType(v string) *ImportSourceCredentialsInput { + s.ServerType = &v + return s } -// String returns the string representation -func (s DeleteResourcePolicyOutput) String() string { - return awsutil.Prettify(s) +// SetShouldOverwrite sets the ShouldOverwrite field's value. +func (s *ImportSourceCredentialsInput) SetShouldOverwrite(v bool) *ImportSourceCredentialsInput { + s.ShouldOverwrite = &v + return s } -// GoString returns the string representation -func (s DeleteResourcePolicyOutput) GoString() string { - return s.String() +// SetToken sets the Token field's value. +func (s *ImportSourceCredentialsInput) SetToken(v string) *ImportSourceCredentialsInput { + s.Token = &v + return s } -type DeleteSourceCredentialsInput struct { +// SetUsername sets the Username field's value. +func (s *ImportSourceCredentialsInput) SetUsername(v string) *ImportSourceCredentialsInput { + s.Username = &v + return s +} + +type ImportSourceCredentialsOutput struct { _ struct{} `type:"structure"` // The Amazon Resource Name (ARN) of the token. - // - // Arn is a required field - Arn *string `locationName:"arn" min:"1" type:"string" required:"true"` + Arn *string `locationName:"arn" min:"1" type:"string"` } // String returns the string representation -func (s DeleteSourceCredentialsInput) String() string { +func (s ImportSourceCredentialsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteSourceCredentialsInput) GoString() string { +func (s ImportSourceCredentialsOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteSourceCredentialsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteSourceCredentialsInput"} - if s.Arn == nil { - invalidParams.Add(request.NewErrParamRequired("Arn")) - } - if s.Arn != nil && len(*s.Arn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Arn", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - // SetArn sets the Arn field's value. -func (s *DeleteSourceCredentialsInput) SetArn(v string) *DeleteSourceCredentialsInput { +func (s *ImportSourceCredentialsOutput) SetArn(v string) *ImportSourceCredentialsOutput { s.Arn = &v return s } -type DeleteSourceCredentialsOutput struct { - _ struct{} `type:"structure"` +// The input value that was provided is not valid. +type InvalidInputException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // The Amazon Resource Name (ARN) of the token. - Arn *string `locationName:"arn" min:"1" type:"string"` + Message_ *string `locationName:"message" type:"string"` } // String returns the string representation -func (s DeleteSourceCredentialsOutput) String() string { +func (s InvalidInputException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteSourceCredentialsOutput) GoString() string { +func (s InvalidInputException) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *DeleteSourceCredentialsOutput) SetArn(v string) *DeleteSourceCredentialsOutput { - s.Arn = &v - return s +func newErrorInvalidInputException(v protocol.ResponseMetadata) error { + return &InvalidInputException{ + RespMetadata: v, + } } -type DeleteWebhookInput struct { +// Code returns the exception type name. +func (s *InvalidInputException) Code() string { + return "InvalidInputException" +} + +// Message returns the exception's message. +func (s *InvalidInputException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidInputException) OrigErr() error { + return nil +} + +func (s *InvalidInputException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidInputException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidInputException) RequestID() string { + return s.RespMetadata.RequestID +} + +type InvalidateProjectCacheInput struct { _ struct{} `type:"structure"` - // The name of the AWS CodeBuild project. + // The name of the AWS CodeBuild build project that the cache is reset for. // // ProjectName is a required field - ProjectName *string `locationName:"projectName" min:"2" type:"string" required:"true"` + ProjectName *string `locationName:"projectName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DeleteWebhookInput) String() string { +func (s InvalidateProjectCacheInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteWebhookInput) GoString() string { +func (s InvalidateProjectCacheInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteWebhookInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteWebhookInput"} +func (s *InvalidateProjectCacheInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InvalidateProjectCacheInput"} if s.ProjectName == nil { invalidParams.Add(request.NewErrParamRequired("ProjectName")) } - if s.ProjectName != nil && len(*s.ProjectName) < 2 { - invalidParams.Add(request.NewErrParamMinLen("ProjectName", 2)) + if s.ProjectName != nil && len(*s.ProjectName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ProjectName", 1)) } if invalidParams.Len() > 0 { @@ -4748,69 +8174,69 @@ func (s *DeleteWebhookInput) Validate() error { } // SetProjectName sets the ProjectName field's value. -func (s *DeleteWebhookInput) SetProjectName(v string) *DeleteWebhookInput { +func (s *InvalidateProjectCacheInput) SetProjectName(v string) *InvalidateProjectCacheInput { s.ProjectName = &v return s } -type DeleteWebhookOutput struct { +type InvalidateProjectCacheOutput struct { _ struct{} `type:"structure"` } // String returns the string representation -func (s DeleteWebhookOutput) String() string { +func (s InvalidateProjectCacheOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteWebhookOutput) GoString() string { +func (s InvalidateProjectCacheOutput) GoString() string { return s.String() } -type DescribeTestCasesInput struct { +type ListBuildBatchesForProjectInput struct { _ struct{} `type:"structure"` - // A TestCaseFilter object used to filter the returned reports. - Filter *TestCaseFilter `locationName:"filter" type:"structure"` + // A BuildBatchFilter object that specifies the filters for the search. + Filter *BuildBatchFilter `locationName:"filter" type:"structure"` - // The maximum number of paginated test cases returned per response. Use nextToken - // to iterate pages in the list of returned TestCase objects. The default value - // is 100. + // The maximum number of results to return. MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` - // During a previous call, the maximum number of items that can be returned - // is the value specified in maxResults. If there more items in the list, then - // a unique string called a nextToken is returned. To get the next batch of - // items in the list, call this operation again, adding the next token to the - // call. To get all of the items in the list, keep calling this operation with - // each subsequent next token that is returned, until no more next tokens are - // returned. + // The nextToken value returned from a previous call to ListBuildBatchesForProject. + // This specifies the next item to return. To return the beginning of the list, + // exclude this parameter. NextToken *string `locationName:"nextToken" type:"string"` - // The ARN of the report for which test cases are returned. + // The name of the project. + ProjectName *string `locationName:"projectName" min:"1" type:"string"` + + // Specifies the sort order of the returned items. Valid values include: // - // ReportArn is a required field - ReportArn *string `locationName:"reportArn" type:"string" required:"true"` + // * ASCENDING: List the batch build identifiers in ascending order by identifier. + // + // * DESCENDING: List the batch build identifiers in descending order by + // identifier. + SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` } // String returns the string representation -func (s DescribeTestCasesInput) String() string { +func (s ListBuildBatchesForProjectInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeTestCasesInput) GoString() string { +func (s ListBuildBatchesForProjectInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeTestCasesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeTestCasesInput"} +func (s *ListBuildBatchesForProjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListBuildBatchesForProjectInput"} if s.MaxResults != nil && *s.MaxResults < 1 { invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } - if s.ReportArn == nil { - invalidParams.Add(request.NewErrParamRequired("ReportArn")) + if s.ProjectName != nil && len(*s.ProjectName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ProjectName", 1)) } if invalidParams.Len() > 0 { @@ -4820,230 +8246,214 @@ func (s *DescribeTestCasesInput) Validate() error { } // SetFilter sets the Filter field's value. -func (s *DescribeTestCasesInput) SetFilter(v *TestCaseFilter) *DescribeTestCasesInput { +func (s *ListBuildBatchesForProjectInput) SetFilter(v *BuildBatchFilter) *ListBuildBatchesForProjectInput { s.Filter = v return s } // SetMaxResults sets the MaxResults field's value. -func (s *DescribeTestCasesInput) SetMaxResults(v int64) *DescribeTestCasesInput { +func (s *ListBuildBatchesForProjectInput) SetMaxResults(v int64) *ListBuildBatchesForProjectInput { s.MaxResults = &v return s } // SetNextToken sets the NextToken field's value. -func (s *DescribeTestCasesInput) SetNextToken(v string) *DescribeTestCasesInput { +func (s *ListBuildBatchesForProjectInput) SetNextToken(v string) *ListBuildBatchesForProjectInput { s.NextToken = &v return s } -// SetReportArn sets the ReportArn field's value. -func (s *DescribeTestCasesInput) SetReportArn(v string) *DescribeTestCasesInput { - s.ReportArn = &v - return s -} - -type DescribeTestCasesOutput struct { - _ struct{} `type:"structure"` - - // During a previous call, the maximum number of items that can be returned - // is the value specified in maxResults. If there more items in the list, then - // a unique string called a nextToken is returned. To get the next batch of - // items in the list, call this operation again, adding the next token to the - // call. To get all of the items in the list, keep calling this operation with - // each subsequent next token that is returned, until no more next tokens are - // returned. - NextToken *string `locationName:"nextToken" type:"string"` - - // The returned list of test cases. - TestCases []*TestCase `locationName:"testCases" type:"list"` -} - -// String returns the string representation -func (s DescribeTestCasesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DescribeTestCasesOutput) GoString() string { - return s.String() -} - -// SetNextToken sets the NextToken field's value. -func (s *DescribeTestCasesOutput) SetNextToken(v string) *DescribeTestCasesOutput { - s.NextToken = &v +// SetProjectName sets the ProjectName field's value. +func (s *ListBuildBatchesForProjectInput) SetProjectName(v string) *ListBuildBatchesForProjectInput { + s.ProjectName = &v return s } -// SetTestCases sets the TestCases field's value. -func (s *DescribeTestCasesOutput) SetTestCases(v []*TestCase) *DescribeTestCasesOutput { - s.TestCases = v +// SetSortOrder sets the SortOrder field's value. +func (s *ListBuildBatchesForProjectInput) SetSortOrder(v string) *ListBuildBatchesForProjectInput { + s.SortOrder = &v return s } -// Information about a Docker image that is managed by AWS CodeBuild. -type EnvironmentImage struct { +type ListBuildBatchesForProjectOutput struct { _ struct{} `type:"structure"` - // The description of the Docker image. - Description *string `locationName:"description" type:"string"` - - // The name of the Docker image. - Name *string `locationName:"name" type:"string"` + // An array of strings that contains the batch build identifiers. + Ids []*string `locationName:"ids" type:"list"` - // A list of environment image versions. - Versions []*string `locationName:"versions" type:"list"` + // If there are more items to return, this contains a token that is passed to + // a subsequent call to ListBuildBatchesForProject to retrieve the next set + // of items. + NextToken *string `locationName:"nextToken" type:"string"` } // String returns the string representation -func (s EnvironmentImage) String() string { +func (s ListBuildBatchesForProjectOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s EnvironmentImage) GoString() string { +func (s ListBuildBatchesForProjectOutput) GoString() string { return s.String() } -// SetDescription sets the Description field's value. -func (s *EnvironmentImage) SetDescription(v string) *EnvironmentImage { - s.Description = &v - return s -} - -// SetName sets the Name field's value. -func (s *EnvironmentImage) SetName(v string) *EnvironmentImage { - s.Name = &v +// SetIds sets the Ids field's value. +func (s *ListBuildBatchesForProjectOutput) SetIds(v []*string) *ListBuildBatchesForProjectOutput { + s.Ids = v return s } -// SetVersions sets the Versions field's value. -func (s *EnvironmentImage) SetVersions(v []*string) *EnvironmentImage { - s.Versions = v +// SetNextToken sets the NextToken field's value. +func (s *ListBuildBatchesForProjectOutput) SetNextToken(v string) *ListBuildBatchesForProjectOutput { + s.NextToken = &v return s } - -// A set of Docker images that are related by programming language and are managed -// by AWS CodeBuild. -type EnvironmentLanguage struct { + +type ListBuildBatchesInput struct { _ struct{} `type:"structure"` - // The list of Docker images that are related by the specified programming language. - Images []*EnvironmentImage `locationName:"images" type:"list"` + // A BuildBatchFilter object that specifies the filters for the search. + Filter *BuildBatchFilter `locationName:"filter" type:"structure"` - // The programming language for the Docker images. - Language *string `locationName:"language" type:"string" enum:"LanguageType"` + // The maximum number of results to return. + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` + + // The nextToken value returned from a previous call to ListBuildBatches. This + // specifies the next item to return. To return the beginning of the list, exclude + // this parameter. + NextToken *string `locationName:"nextToken" type:"string"` + + // Specifies the sort order of the returned items. Valid values include: + // + // * ASCENDING: List the batch build identifiers in ascending order by identifier. + // + // * DESCENDING: List the batch build identifiers in descending order by + // identifier. + SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` } // String returns the string representation -func (s EnvironmentLanguage) String() string { +func (s ListBuildBatchesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s EnvironmentLanguage) GoString() string { +func (s ListBuildBatchesInput) GoString() string { return s.String() } -// SetImages sets the Images field's value. -func (s *EnvironmentLanguage) SetImages(v []*EnvironmentImage) *EnvironmentLanguage { - s.Images = v +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListBuildBatchesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListBuildBatchesInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetFilter sets the Filter field's value. +func (s *ListBuildBatchesInput) SetFilter(v *BuildBatchFilter) *ListBuildBatchesInput { + s.Filter = v return s } -// SetLanguage sets the Language field's value. -func (s *EnvironmentLanguage) SetLanguage(v string) *EnvironmentLanguage { - s.Language = &v +// SetMaxResults sets the MaxResults field's value. +func (s *ListBuildBatchesInput) SetMaxResults(v int64) *ListBuildBatchesInput { + s.MaxResults = &v return s } -// A set of Docker images that are related by platform and are managed by AWS -// CodeBuild. -type EnvironmentPlatform struct { +// SetNextToken sets the NextToken field's value. +func (s *ListBuildBatchesInput) SetNextToken(v string) *ListBuildBatchesInput { + s.NextToken = &v + return s +} + +// SetSortOrder sets the SortOrder field's value. +func (s *ListBuildBatchesInput) SetSortOrder(v string) *ListBuildBatchesInput { + s.SortOrder = &v + return s +} + +type ListBuildBatchesOutput struct { _ struct{} `type:"structure"` - // The list of programming languages that are available for the specified platform. - Languages []*EnvironmentLanguage `locationName:"languages" type:"list"` + // An array of strings that contains the batch build identifiers. + Ids []*string `locationName:"ids" type:"list"` - // The platform's name. - Platform *string `locationName:"platform" type:"string" enum:"PlatformType"` + // If there are more items to return, this contains a token that is passed to + // a subsequent call to ListBuildBatches to retrieve the next set of items. + NextToken *string `locationName:"nextToken" type:"string"` } // String returns the string representation -func (s EnvironmentPlatform) String() string { +func (s ListBuildBatchesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s EnvironmentPlatform) GoString() string { +func (s ListBuildBatchesOutput) GoString() string { return s.String() } -// SetLanguages sets the Languages field's value. -func (s *EnvironmentPlatform) SetLanguages(v []*EnvironmentLanguage) *EnvironmentPlatform { - s.Languages = v +// SetIds sets the Ids field's value. +func (s *ListBuildBatchesOutput) SetIds(v []*string) *ListBuildBatchesOutput { + s.Ids = v return s } -// SetPlatform sets the Platform field's value. -func (s *EnvironmentPlatform) SetPlatform(v string) *EnvironmentPlatform { - s.Platform = &v +// SetNextToken sets the NextToken field's value. +func (s *ListBuildBatchesOutput) SetNextToken(v string) *ListBuildBatchesOutput { + s.NextToken = &v return s } -// Information about an environment variable for a build project or a build. -type EnvironmentVariable struct { +type ListBuildsForProjectInput struct { _ struct{} `type:"structure"` - // The name or key of the environment variable. - // - // Name is a required field - Name *string `locationName:"name" min:"1" type:"string" required:"true"` + // During a previous call, if there are more than 100 items in the list, only + // the first 100 items are returned, along with a unique string called a nextToken. + // To get the next batch of items in the list, call this operation again, adding + // the next token to the call. To get all of the items in the list, keep calling + // this operation with each subsequent next token that is returned, until no + // more next tokens are returned. + NextToken *string `locationName:"nextToken" type:"string"` - // The type of environment variable. Valid values include: - // - // * PARAMETER_STORE: An environment variable stored in Amazon EC2 Systems - // Manager Parameter Store. - // - // * PLAINTEXT: An environment variable in plain text format. This is the - // default value. + // The name of the AWS CodeBuild project. // - // * SECRETS_MANAGER: An environment variable stored in AWS Secrets Manager. - Type *string `locationName:"type" type:"string" enum:"EnvironmentVariableType"` + // ProjectName is a required field + ProjectName *string `locationName:"projectName" min:"1" type:"string" required:"true"` - // The value of the environment variable. + // The order to list build IDs. Valid values include: // - // We strongly discourage the use of PLAINTEXT environment variables to store - // sensitive values, especially AWS secret key IDs and secret access keys. PLAINTEXT - // environment variables can be displayed in plain text using the AWS CodeBuild - // console and the AWS Command Line Interface (AWS CLI). For sensitive values, - // we recommend you use an environment variable of type PARAMETER_STORE or SECRETS_MANAGER. + // * ASCENDING: List the build IDs in ascending order by build ID. // - // Value is a required field - Value *string `locationName:"value" type:"string" required:"true"` + // * DESCENDING: List the build IDs in descending order by build ID. + SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` } // String returns the string representation -func (s EnvironmentVariable) String() string { +func (s ListBuildsForProjectInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s EnvironmentVariable) GoString() string { +func (s ListBuildsForProjectInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *EnvironmentVariable) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "EnvironmentVariable"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) +func (s *ListBuildsForProjectInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListBuildsForProjectInput"} + if s.ProjectName == nil { + invalidParams.Add(request.NewErrParamRequired("ProjectName")) } - if s.Value == nil { - invalidParams.Add(request.NewErrParamRequired("Value")) + if s.ProjectName != nil && len(*s.ProjectName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ProjectName", 1)) } if invalidParams.Len() > 0 { @@ -5052,224 +8462,223 @@ func (s *EnvironmentVariable) Validate() error { return nil } -// SetName sets the Name field's value. -func (s *EnvironmentVariable) SetName(v string) *EnvironmentVariable { - s.Name = &v +// SetNextToken sets the NextToken field's value. +func (s *ListBuildsForProjectInput) SetNextToken(v string) *ListBuildsForProjectInput { + s.NextToken = &v return s } -// SetType sets the Type field's value. -func (s *EnvironmentVariable) SetType(v string) *EnvironmentVariable { - s.Type = &v +// SetProjectName sets the ProjectName field's value. +func (s *ListBuildsForProjectInput) SetProjectName(v string) *ListBuildsForProjectInput { + s.ProjectName = &v return s } -// SetValue sets the Value field's value. -func (s *EnvironmentVariable) SetValue(v string) *EnvironmentVariable { - s.Value = &v +// SetSortOrder sets the SortOrder field's value. +func (s *ListBuildsForProjectInput) SetSortOrder(v string) *ListBuildsForProjectInput { + s.SortOrder = &v return s } -// Information about an exported environment variable. -type ExportedEnvironmentVariable struct { +type ListBuildsForProjectOutput struct { _ struct{} `type:"structure"` - // The name of this exported environment variable. - Name *string `locationName:"name" min:"1" type:"string"` + // A list of build IDs for the specified build project, with each build ID representing + // a single build. + Ids []*string `locationName:"ids" min:"1" type:"list"` - // The value assigned to this exported environment variable. - // - // During a build, the value of a variable is available starting with the install - // phase. It can be updated between the start of the install phase and the end - // of the post_build phase. After the post_build phase ends, the value of exported - // variables cannot change. - Value *string `locationName:"value" type:"string"` + // If there are more than 100 items in the list, only the first 100 items are + // returned, along with a unique string called a nextToken. To get the next + // batch of items in the list, call this operation again, adding the next token + // to the call. + NextToken *string `locationName:"nextToken" type:"string"` } // String returns the string representation -func (s ExportedEnvironmentVariable) String() string { +func (s ListBuildsForProjectOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ExportedEnvironmentVariable) GoString() string { +func (s ListBuildsForProjectOutput) GoString() string { return s.String() } -// SetName sets the Name field's value. -func (s *ExportedEnvironmentVariable) SetName(v string) *ExportedEnvironmentVariable { - s.Name = &v +// SetIds sets the Ids field's value. +func (s *ListBuildsForProjectOutput) SetIds(v []*string) *ListBuildsForProjectOutput { + s.Ids = v return s } -// SetValue sets the Value field's value. -func (s *ExportedEnvironmentVariable) SetValue(v string) *ExportedEnvironmentVariable { - s.Value = &v +// SetNextToken sets the NextToken field's value. +func (s *ListBuildsForProjectOutput) SetNextToken(v string) *ListBuildsForProjectOutput { + s.NextToken = &v return s } -type GetResourcePolicyInput struct { +type ListBuildsInput struct { _ struct{} `type:"structure"` - // The ARN of the resource that is associated with the resource policy. + // During a previous call, if there are more than 100 items in the list, only + // the first 100 items are returned, along with a unique string called a nextToken. + // To get the next batch of items in the list, call this operation again, adding + // the next token to the call. To get all of the items in the list, keep calling + // this operation with each subsequent next token that is returned, until no + // more next tokens are returned. + NextToken *string `locationName:"nextToken" type:"string"` + + // The order to list build IDs. Valid values include: // - // ResourceArn is a required field - ResourceArn *string `locationName:"resourceArn" min:"1" type:"string" required:"true"` + // * ASCENDING: List the build IDs in ascending order by build ID. + // + // * DESCENDING: List the build IDs in descending order by build ID. + SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` } // String returns the string representation -func (s GetResourcePolicyInput) String() string { +func (s ListBuildsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetResourcePolicyInput) GoString() string { +func (s ListBuildsInput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetResourcePolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetResourcePolicyInput"} - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) - } - if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) - } +// SetNextToken sets the NextToken field's value. +func (s *ListBuildsInput) SetNextToken(v string) *ListBuildsInput { + s.NextToken = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetSortOrder sets the SortOrder field's value. +func (s *ListBuildsInput) SetSortOrder(v string) *ListBuildsInput { + s.SortOrder = &v + return s } -// SetResourceArn sets the ResourceArn field's value. -func (s *GetResourcePolicyInput) SetResourceArn(v string) *GetResourcePolicyInput { - s.ResourceArn = &v +type ListBuildsOutput struct { + _ struct{} `type:"structure"` + + // A list of build IDs, with each build ID representing a single build. + Ids []*string `locationName:"ids" min:"1" type:"list"` + + // If there are more than 100 items in the list, only the first 100 items are + // returned, along with a unique string called a nextToken. To get the next + // batch of items in the list, call this operation again, adding the next token + // to the call. + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s ListBuildsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListBuildsOutput) GoString() string { + return s.String() +} + +// SetIds sets the Ids field's value. +func (s *ListBuildsOutput) SetIds(v []*string) *ListBuildsOutput { + s.Ids = v return s } -type GetResourcePolicyOutput struct { +// SetNextToken sets the NextToken field's value. +func (s *ListBuildsOutput) SetNextToken(v string) *ListBuildsOutput { + s.NextToken = &v + return s +} + +type ListCuratedEnvironmentImagesInput struct { _ struct{} `type:"structure"` - - // The resource policy for the resource identified by the input ARN parameter. - Policy *string `locationName:"policy" min:"1" type:"string"` } // String returns the string representation -func (s GetResourcePolicyOutput) String() string { +func (s ListCuratedEnvironmentImagesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetResourcePolicyOutput) GoString() string { +func (s ListCuratedEnvironmentImagesInput) GoString() string { return s.String() } -// SetPolicy sets the Policy field's value. -func (s *GetResourcePolicyOutput) SetPolicy(v string) *GetResourcePolicyOutput { - s.Policy = &v - return s -} - -// Information about the Git submodules configuration for an AWS CodeBuild build -// project. -type GitSubmodulesConfig struct { +type ListCuratedEnvironmentImagesOutput struct { _ struct{} `type:"structure"` - // Set to true to fetch Git submodules for your AWS CodeBuild build project. - // - // FetchSubmodules is a required field - FetchSubmodules *bool `locationName:"fetchSubmodules" type:"boolean" required:"true"` + // Information about supported platforms for Docker images that are managed + // by AWS CodeBuild. + Platforms []*EnvironmentPlatform `locationName:"platforms" type:"list"` } // String returns the string representation -func (s GitSubmodulesConfig) String() string { +func (s ListCuratedEnvironmentImagesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GitSubmodulesConfig) GoString() string { +func (s ListCuratedEnvironmentImagesOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GitSubmodulesConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GitSubmodulesConfig"} - if s.FetchSubmodules == nil { - invalidParams.Add(request.NewErrParamRequired("FetchSubmodules")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetFetchSubmodules sets the FetchSubmodules field's value. -func (s *GitSubmodulesConfig) SetFetchSubmodules(v bool) *GitSubmodulesConfig { - s.FetchSubmodules = &v +// SetPlatforms sets the Platforms field's value. +func (s *ListCuratedEnvironmentImagesOutput) SetPlatforms(v []*EnvironmentPlatform) *ListCuratedEnvironmentImagesOutput { + s.Platforms = v return s } -type ImportSourceCredentialsInput struct { +type ListProjectsInput struct { _ struct{} `type:"structure"` - // The type of authentication used to connect to a GitHub, GitHub Enterprise, - // or Bitbucket repository. An OAUTH connection is not supported by the API - // and must be created using the AWS CodeBuild console. - // - // AuthType is a required field - AuthType *string `locationName:"authType" type:"string" required:"true" enum:"AuthType"` + // During a previous call, if there are more than 100 items in the list, only + // the first 100 items are returned, along with a unique string called a nextToken. + // To get the next batch of items in the list, call this operation again, adding + // the next token to the call. To get all of the items in the list, keep calling + // this operation with each subsequent next token that is returned, until no + // more next tokens are returned. + NextToken *string `locationName:"nextToken" min:"1" type:"string"` - // The source provider used for this project. + // The criterion to be used to list build project names. Valid values include: // - // ServerType is a required field - ServerType *string `locationName:"serverType" type:"string" required:"true" enum:"ServerType"` - - // Set to false to prevent overwriting the repository source credentials. Set - // to true to overwrite the repository source credentials. The default value - // is true. - ShouldOverwrite *bool `locationName:"shouldOverwrite" type:"boolean"` - - // For GitHub or GitHub Enterprise, this is the personal access token. For Bitbucket, - // this is the app password. + // * CREATED_TIME: List based on when each build project was created. // - // Token is a required field - Token *string `locationName:"token" min:"1" type:"string" required:"true" sensitive:"true"` + // * LAST_MODIFIED_TIME: List based on when information about each build + // project was last changed. + // + // * NAME: List based on each build project's name. + // + // Use sortOrder to specify in what order to list the build project names based + // on the preceding criteria. + SortBy *string `locationName:"sortBy" type:"string" enum:"ProjectSortByType"` - // The Bitbucket username when the authType is BASIC_AUTH. This parameter is - // not valid for other types of source providers or connections. - Username *string `locationName:"username" min:"1" type:"string"` + // The order in which to list build projects. Valid values include: + // + // * ASCENDING: List in ascending order. + // + // * DESCENDING: List in descending order. + // + // Use sortBy to specify the criterion to be used to list build project names. + SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` } // String returns the string representation -func (s ImportSourceCredentialsInput) String() string { +func (s ListProjectsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ImportSourceCredentialsInput) GoString() string { +func (s ListProjectsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ImportSourceCredentialsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ImportSourceCredentialsInput"} - if s.AuthType == nil { - invalidParams.Add(request.NewErrParamRequired("AuthType")) - } - if s.ServerType == nil { - invalidParams.Add(request.NewErrParamRequired("ServerType")) - } - if s.Token == nil { - invalidParams.Add(request.NewErrParamRequired("Token")) - } - if s.Token != nil && len(*s.Token) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Token", 1)) - } - if s.Username != nil && len(*s.Username) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Username", 1)) +func (s *ListProjectsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListProjectsInput"} + if s.NextToken != nil && len(*s.NextToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) } if invalidParams.Len() > 0 { @@ -5278,212 +8687,224 @@ func (s *ImportSourceCredentialsInput) Validate() error { return nil } -// SetAuthType sets the AuthType field's value. -func (s *ImportSourceCredentialsInput) SetAuthType(v string) *ImportSourceCredentialsInput { - s.AuthType = &v - return s -} - -// SetServerType sets the ServerType field's value. -func (s *ImportSourceCredentialsInput) SetServerType(v string) *ImportSourceCredentialsInput { - s.ServerType = &v - return s -} - -// SetShouldOverwrite sets the ShouldOverwrite field's value. -func (s *ImportSourceCredentialsInput) SetShouldOverwrite(v bool) *ImportSourceCredentialsInput { - s.ShouldOverwrite = &v +// SetNextToken sets the NextToken field's value. +func (s *ListProjectsInput) SetNextToken(v string) *ListProjectsInput { + s.NextToken = &v return s } -// SetToken sets the Token field's value. -func (s *ImportSourceCredentialsInput) SetToken(v string) *ImportSourceCredentialsInput { - s.Token = &v +// SetSortBy sets the SortBy field's value. +func (s *ListProjectsInput) SetSortBy(v string) *ListProjectsInput { + s.SortBy = &v return s } -// SetUsername sets the Username field's value. -func (s *ImportSourceCredentialsInput) SetUsername(v string) *ImportSourceCredentialsInput { - s.Username = &v +// SetSortOrder sets the SortOrder field's value. +func (s *ListProjectsInput) SetSortOrder(v string) *ListProjectsInput { + s.SortOrder = &v return s } -type ImportSourceCredentialsOutput struct { +type ListProjectsOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the token. - Arn *string `locationName:"arn" min:"1" type:"string"` + // If there are more than 100 items in the list, only the first 100 items are + // returned, along with a unique string called a nextToken. To get the next + // batch of items in the list, call this operation again, adding the next token + // to the call. + NextToken *string `locationName:"nextToken" type:"string"` + + // The list of build project names, with each build project name representing + // a single build project. + Projects []*string `locationName:"projects" min:"1" type:"list"` } // String returns the string representation -func (s ImportSourceCredentialsOutput) String() string { +func (s ListProjectsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ImportSourceCredentialsOutput) GoString() string { +func (s ListProjectsOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *ImportSourceCredentialsOutput) SetArn(v string) *ImportSourceCredentialsOutput { - s.Arn = &v +// SetNextToken sets the NextToken field's value. +func (s *ListProjectsOutput) SetNextToken(v string) *ListProjectsOutput { + s.NextToken = &v return s } -// The input value that was provided is not valid. -type InvalidInputException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +// SetProjects sets the Projects field's value. +func (s *ListProjectsOutput) SetProjects(v []*string) *ListProjectsOutput { + s.Projects = v + return s +} - Message_ *string `locationName:"message" type:"string"` +type ListReportGroupsInput struct { + _ struct{} `type:"structure"` + + // The maximum number of paginated report groups returned per response. Use + // nextToken to iterate pages in the list of returned ReportGroup objects. The + // default value is 100. + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` + + // During a previous call, the maximum number of items that can be returned + // is the value specified in maxResults. If there more items in the list, then + // a unique string called a nextToken is returned. To get the next batch of + // items in the list, call this operation again, adding the next token to the + // call. To get all of the items in the list, keep calling this operation with + // each subsequent next token that is returned, until no more next tokens are + // returned. + NextToken *string `locationName:"nextToken" type:"string"` + + // The criterion to be used to list build report groups. Valid values include: + // + // * CREATED_TIME: List based on when each report group was created. + // + // * LAST_MODIFIED_TIME: List based on when each report group was last changed. + // + // * NAME: List based on each report group's name. + SortBy *string `locationName:"sortBy" type:"string" enum:"ReportGroupSortByType"` + + // Used to specify the order to sort the list of returned report groups. Valid + // values are ASCENDING and DESCENDING. + SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` } // String returns the string representation -func (s InvalidInputException) String() string { +func (s ListReportGroupsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InvalidInputException) GoString() string { +func (s ListReportGroupsInput) GoString() string { return s.String() } -func newErrorInvalidInputException(v protocol.ResponseMetadata) error { - return &InvalidInputException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListReportGroupsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListReportGroupsInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } -} - -// Code returns the exception type name. -func (s *InvalidInputException) Code() string { - return "InvalidInputException" -} -// Message returns the exception's message. -func (s *InvalidInputException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if invalidParams.Len() > 0 { + return invalidParams } - return "" + return nil } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidInputException) OrigErr() error { - return nil +// SetMaxResults sets the MaxResults field's value. +func (s *ListReportGroupsInput) SetMaxResults(v int64) *ListReportGroupsInput { + s.MaxResults = &v + return s } -func (s *InvalidInputException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +// SetNextToken sets the NextToken field's value. +func (s *ListReportGroupsInput) SetNextToken(v string) *ListReportGroupsInput { + s.NextToken = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidInputException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetSortBy sets the SortBy field's value. +func (s *ListReportGroupsInput) SetSortBy(v string) *ListReportGroupsInput { + s.SortBy = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *InvalidInputException) RequestID() string { - return s.RespMetadata.RequestID +// SetSortOrder sets the SortOrder field's value. +func (s *ListReportGroupsInput) SetSortOrder(v string) *ListReportGroupsInput { + s.SortOrder = &v + return s } -type InvalidateProjectCacheInput struct { +type ListReportGroupsOutput struct { _ struct{} `type:"structure"` - // The name of the AWS CodeBuild build project that the cache is reset for. - // - // ProjectName is a required field - ProjectName *string `locationName:"projectName" min:"1" type:"string" required:"true"` + // During a previous call, the maximum number of items that can be returned + // is the value specified in maxResults. If there more items in the list, then + // a unique string called a nextToken is returned. To get the next batch of + // items in the list, call this operation again, adding the next token to the + // call. To get all of the items in the list, keep calling this operation with + // each subsequent next token that is returned, until no more next tokens are + // returned. + NextToken *string `locationName:"nextToken" type:"string"` + + // The list of ARNs for the report groups in the current AWS account. + ReportGroups []*string `locationName:"reportGroups" min:"1" type:"list"` } // String returns the string representation -func (s InvalidateProjectCacheInput) String() string { +func (s ListReportGroupsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InvalidateProjectCacheInput) GoString() string { +func (s ListReportGroupsOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *InvalidateProjectCacheInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InvalidateProjectCacheInput"} - if s.ProjectName == nil { - invalidParams.Add(request.NewErrParamRequired("ProjectName")) - } - if s.ProjectName != nil && len(*s.ProjectName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ProjectName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetNextToken sets the NextToken field's value. +func (s *ListReportGroupsOutput) SetNextToken(v string) *ListReportGroupsOutput { + s.NextToken = &v + return s } -// SetProjectName sets the ProjectName field's value. -func (s *InvalidateProjectCacheInput) SetProjectName(v string) *InvalidateProjectCacheInput { - s.ProjectName = &v +// SetReportGroups sets the ReportGroups field's value. +func (s *ListReportGroupsOutput) SetReportGroups(v []*string) *ListReportGroupsOutput { + s.ReportGroups = v return s } -type InvalidateProjectCacheOutput struct { +type ListReportsForReportGroupInput struct { _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s InvalidateProjectCacheOutput) String() string { - return awsutil.Prettify(s) -} -// GoString returns the string representation -func (s InvalidateProjectCacheOutput) GoString() string { - return s.String() -} + // A ReportFilter object used to filter the returned reports. + Filter *ReportFilter `locationName:"filter" type:"structure"` -type ListBuildsForProjectInput struct { - _ struct{} `type:"structure"` + // The maximum number of paginated reports in this report group returned per + // response. Use nextToken to iterate pages in the list of returned Report objects. + // The default value is 100. + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` - // During a previous call, if there are more than 100 items in the list, only - // the first 100 items are returned, along with a unique string called a nextToken. - // To get the next batch of items in the list, call this operation again, adding - // the next token to the call. To get all of the items in the list, keep calling - // this operation with each subsequent next token that is returned, until no - // more next tokens are returned. + // During a previous call, the maximum number of items that can be returned + // is the value specified in maxResults. If there more items in the list, then + // a unique string called a nextToken is returned. To get the next batch of + // items in the list, call this operation again, adding the next token to the + // call. To get all of the items in the list, keep calling this operation with + // each subsequent next token that is returned, until no more next tokens are + // returned. NextToken *string `locationName:"nextToken" type:"string"` - // The name of the AWS CodeBuild project. + // The ARN of the report group for which you want to return report ARNs. // - // ProjectName is a required field - ProjectName *string `locationName:"projectName" min:"1" type:"string" required:"true"` + // ReportGroupArn is a required field + ReportGroupArn *string `locationName:"reportGroupArn" type:"string" required:"true"` - // The order to list build IDs. Valid values include: - // - // * ASCENDING: List the build IDs in ascending order by build ID. - // - // * DESCENDING: List the build IDs in descending order by build ID. + // Use to specify whether the results are returned in ascending or descending + // order. SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` } // String returns the string representation -func (s ListBuildsForProjectInput) String() string { +func (s ListReportsForReportGroupInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListBuildsForProjectInput) GoString() string { +func (s ListReportsForReportGroupInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListBuildsForProjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListBuildsForProjectInput"} - if s.ProjectName == nil { - invalidParams.Add(request.NewErrParamRequired("ProjectName")) +func (s *ListReportsForReportGroupInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListReportsForReportGroupInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } - if s.ProjectName != nil && len(*s.ProjectName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ProjectName", 1)) + if s.ReportGroupArn == nil { + invalidParams.Add(request.NewErrParamRequired("ReportGroupArn")) } if invalidParams.Len() > 0 { @@ -5492,221 +8913,239 @@ func (s *ListBuildsForProjectInput) Validate() error { return nil } +// SetFilter sets the Filter field's value. +func (s *ListReportsForReportGroupInput) SetFilter(v *ReportFilter) *ListReportsForReportGroupInput { + s.Filter = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListReportsForReportGroupInput) SetMaxResults(v int64) *ListReportsForReportGroupInput { + s.MaxResults = &v + return s +} + // SetNextToken sets the NextToken field's value. -func (s *ListBuildsForProjectInput) SetNextToken(v string) *ListBuildsForProjectInput { +func (s *ListReportsForReportGroupInput) SetNextToken(v string) *ListReportsForReportGroupInput { s.NextToken = &v return s } -// SetProjectName sets the ProjectName field's value. -func (s *ListBuildsForProjectInput) SetProjectName(v string) *ListBuildsForProjectInput { - s.ProjectName = &v +// SetReportGroupArn sets the ReportGroupArn field's value. +func (s *ListReportsForReportGroupInput) SetReportGroupArn(v string) *ListReportsForReportGroupInput { + s.ReportGroupArn = &v return s } // SetSortOrder sets the SortOrder field's value. -func (s *ListBuildsForProjectInput) SetSortOrder(v string) *ListBuildsForProjectInput { +func (s *ListReportsForReportGroupInput) SetSortOrder(v string) *ListReportsForReportGroupInput { s.SortOrder = &v return s } -type ListBuildsForProjectOutput struct { +type ListReportsForReportGroupOutput struct { _ struct{} `type:"structure"` - // A list of build IDs for the specified build project, with each build ID representing - // a single build. - Ids []*string `locationName:"ids" min:"1" type:"list"` - - // If there are more than 100 items in the list, only the first 100 items are - // returned, along with a unique string called a nextToken. To get the next - // batch of items in the list, call this operation again, adding the next token - // to the call. + // During a previous call, the maximum number of items that can be returned + // is the value specified in maxResults. If there more items in the list, then + // a unique string called a nextToken is returned. To get the next batch of + // items in the list, call this operation again, adding the next token to the + // call. To get all of the items in the list, keep calling this operation with + // each subsequent next token that is returned, until no more next tokens are + // returned. NextToken *string `locationName:"nextToken" type:"string"` + + // The list of report ARNs. + Reports []*string `locationName:"reports" min:"1" type:"list"` } // String returns the string representation -func (s ListBuildsForProjectOutput) String() string { +func (s ListReportsForReportGroupOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListBuildsForProjectOutput) GoString() string { +func (s ListReportsForReportGroupOutput) GoString() string { return s.String() } -// SetIds sets the Ids field's value. -func (s *ListBuildsForProjectOutput) SetIds(v []*string) *ListBuildsForProjectOutput { - s.Ids = v +// SetNextToken sets the NextToken field's value. +func (s *ListReportsForReportGroupOutput) SetNextToken(v string) *ListReportsForReportGroupOutput { + s.NextToken = &v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListBuildsForProjectOutput) SetNextToken(v string) *ListBuildsForProjectOutput { - s.NextToken = &v +// SetReports sets the Reports field's value. +func (s *ListReportsForReportGroupOutput) SetReports(v []*string) *ListReportsForReportGroupOutput { + s.Reports = v return s } -type ListBuildsInput struct { +type ListReportsInput struct { _ struct{} `type:"structure"` - // During a previous call, if there are more than 100 items in the list, only - // the first 100 items are returned, along with a unique string called a nextToken. - // To get the next batch of items in the list, call this operation again, adding - // the next token to the call. To get all of the items in the list, keep calling - // this operation with each subsequent next token that is returned, until no - // more next tokens are returned. + // A ReportFilter object used to filter the returned reports. + Filter *ReportFilter `locationName:"filter" type:"structure"` + + // The maximum number of paginated reports returned per response. Use nextToken + // to iterate pages in the list of returned Report objects. The default value + // is 100. + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` + + // During a previous call, the maximum number of items that can be returned + // is the value specified in maxResults. If there more items in the list, then + // a unique string called a nextToken is returned. To get the next batch of + // items in the list, call this operation again, adding the next token to the + // call. To get all of the items in the list, keep calling this operation with + // each subsequent next token that is returned, until no more next tokens are + // returned. NextToken *string `locationName:"nextToken" type:"string"` - // The order to list build IDs. Valid values include: + // Specifies the sort order for the list of returned reports. Valid values are: // - // * ASCENDING: List the build IDs in ascending order by build ID. + // * ASCENDING: return reports in chronological order based on their creation + // date. // - // * DESCENDING: List the build IDs in descending order by build ID. + // * DESCENDING: return reports in the reverse chronological order based + // on their creation date. SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` } // String returns the string representation -func (s ListBuildsInput) String() string { +func (s ListReportsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListBuildsInput) GoString() string { +func (s ListReportsInput) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListBuildsInput) SetNextToken(v string) *ListBuildsInput { - s.NextToken = &v - return s -} - -// SetSortOrder sets the SortOrder field's value. -func (s *ListBuildsInput) SetSortOrder(v string) *ListBuildsInput { - s.SortOrder = &v - return s -} - -type ListBuildsOutput struct { - _ struct{} `type:"structure"` - - // A list of build IDs, with each build ID representing a single build. - Ids []*string `locationName:"ids" min:"1" type:"list"` - - // If there are more than 100 items in the list, only the first 100 items are - // returned, along with a unique string called a nextToken. To get the next - // batch of items in the list, call this operation again, adding the next token - // to the call. - NextToken *string `locationName:"nextToken" type:"string"` -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListReportsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListReportsInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } -// String returns the string representation -func (s ListBuildsOutput) String() string { - return awsutil.Prettify(s) + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// GoString returns the string representation -func (s ListBuildsOutput) GoString() string { - return s.String() +// SetFilter sets the Filter field's value. +func (s *ListReportsInput) SetFilter(v *ReportFilter) *ListReportsInput { + s.Filter = v + return s } - -// SetIds sets the Ids field's value. -func (s *ListBuildsOutput) SetIds(v []*string) *ListBuildsOutput { - s.Ids = v + +// SetMaxResults sets the MaxResults field's value. +func (s *ListReportsInput) SetMaxResults(v int64) *ListReportsInput { + s.MaxResults = &v return s } // SetNextToken sets the NextToken field's value. -func (s *ListBuildsOutput) SetNextToken(v string) *ListBuildsOutput { +func (s *ListReportsInput) SetNextToken(v string) *ListReportsInput { s.NextToken = &v return s } -type ListCuratedEnvironmentImagesInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s ListCuratedEnvironmentImagesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListCuratedEnvironmentImagesInput) GoString() string { - return s.String() +// SetSortOrder sets the SortOrder field's value. +func (s *ListReportsInput) SetSortOrder(v string) *ListReportsInput { + s.SortOrder = &v + return s } -type ListCuratedEnvironmentImagesOutput struct { +type ListReportsOutput struct { _ struct{} `type:"structure"` - // Information about supported platforms for Docker images that are managed - // by AWS CodeBuild. - Platforms []*EnvironmentPlatform `locationName:"platforms" type:"list"` + // During a previous call, the maximum number of items that can be returned + // is the value specified in maxResults. If there more items in the list, then + // a unique string called a nextToken is returned. To get the next batch of + // items in the list, call this operation again, adding the next token to the + // call. To get all of the items in the list, keep calling this operation with + // each subsequent next token that is returned, until no more next tokens are + // returned. + NextToken *string `locationName:"nextToken" type:"string"` + + // The list of returned ARNs for the reports in the current AWS account. + Reports []*string `locationName:"reports" min:"1" type:"list"` } // String returns the string representation -func (s ListCuratedEnvironmentImagesOutput) String() string { +func (s ListReportsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListCuratedEnvironmentImagesOutput) GoString() string { +func (s ListReportsOutput) GoString() string { return s.String() } -// SetPlatforms sets the Platforms field's value. -func (s *ListCuratedEnvironmentImagesOutput) SetPlatforms(v []*EnvironmentPlatform) *ListCuratedEnvironmentImagesOutput { - s.Platforms = v +// SetNextToken sets the NextToken field's value. +func (s *ListReportsOutput) SetNextToken(v string) *ListReportsOutput { + s.NextToken = &v return s } -type ListProjectsInput struct { +// SetReports sets the Reports field's value. +func (s *ListReportsOutput) SetReports(v []*string) *ListReportsOutput { + s.Reports = v + return s +} + +type ListSharedProjectsInput struct { _ struct{} `type:"structure"` - // During a previous call, if there are more than 100 items in the list, only - // the first 100 items are returned, along with a unique string called a nextToken. - // To get the next batch of items in the list, call this operation again, adding - // the next token to the call. To get all of the items in the list, keep calling - // this operation with each subsequent next token that is returned, until no - // more next tokens are returned. + // The maximum number of paginated shared build projects returned per response. + // Use nextToken to iterate pages in the list of returned Project objects. The + // default value is 100. + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` + + // During a previous call, the maximum number of items that can be returned + // is the value specified in maxResults. If there more items in the list, then + // a unique string called a nextToken is returned. To get the next batch of + // items in the list, call this operation again, adding the next token to the + // call. To get all of the items in the list, keep calling this operation with + // each subsequent next token that is returned, until no more next tokens are + // returned. NextToken *string `locationName:"nextToken" min:"1" type:"string"` - // The criterion to be used to list build project names. Valid values include: - // - // * CREATED_TIME: List based on when each build project was created. - // - // * LAST_MODIFIED_TIME: List based on when information about each build - // project was last changed. + // The criterion to be used to list build projects shared with the current AWS + // account or user. Valid values include: // - // * NAME: List based on each build project's name. + // * ARN: List based on the ARN. // - // Use sortOrder to specify in what order to list the build project names based - // on the preceding criteria. - SortBy *string `locationName:"sortBy" type:"string" enum:"ProjectSortByType"` + // * MODIFIED_TIME: List based on when information about the shared project + // was last changed. + SortBy *string `locationName:"sortBy" type:"string" enum:"SharedResourceSortByType"` - // The order in which to list build projects. Valid values include: + // The order in which to list shared build projects. Valid values include: // // * ASCENDING: List in ascending order. // // * DESCENDING: List in descending order. - // - // Use sortBy to specify the criterion to be used to list build project names. SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` } // String returns the string representation -func (s ListProjectsInput) String() string { +func (s ListSharedProjectsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListProjectsInput) GoString() string { +func (s ListSharedProjectsInput) 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"} +func (s *ListSharedProjectsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListSharedProjectsInput"} + 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)) } @@ -5717,66 +9156,75 @@ func (s *ListProjectsInput) Validate() error { return nil } +// SetMaxResults sets the MaxResults field's value. +func (s *ListSharedProjectsInput) SetMaxResults(v int64) *ListSharedProjectsInput { + s.MaxResults = &v + return s +} + // SetNextToken sets the NextToken field's value. -func (s *ListProjectsInput) SetNextToken(v string) *ListProjectsInput { +func (s *ListSharedProjectsInput) SetNextToken(v string) *ListSharedProjectsInput { s.NextToken = &v return s } // SetSortBy sets the SortBy field's value. -func (s *ListProjectsInput) SetSortBy(v string) *ListProjectsInput { +func (s *ListSharedProjectsInput) SetSortBy(v string) *ListSharedProjectsInput { s.SortBy = &v return s } // SetSortOrder sets the SortOrder field's value. -func (s *ListProjectsInput) SetSortOrder(v string) *ListProjectsInput { +func (s *ListSharedProjectsInput) SetSortOrder(v string) *ListSharedProjectsInput { s.SortOrder = &v return s } -type ListProjectsOutput struct { +type ListSharedProjectsOutput struct { _ struct{} `type:"structure"` - // If there are more than 100 items in the list, only the first 100 items are - // returned, along with a unique string called a nextToken. To get the next - // batch of items in the list, call this operation again, adding the next token - // to the call. + // During a previous call, the maximum number of items that can be returned + // is the value specified in maxResults. If there more items in the list, then + // a unique string called a nextToken is returned. To get the next batch of + // items in the list, call this operation again, adding the next token to the + // call. To get all of the items in the list, keep calling this operation with + // each subsequent next token that is returned, until no more next tokens are + // returned. NextToken *string `locationName:"nextToken" type:"string"` - // The list of build project names, with each build project name representing - // a single build project. + // The list of ARNs for the build projects shared with the current AWS account + // or user. Projects []*string `locationName:"projects" min:"1" type:"list"` } // String returns the string representation -func (s ListProjectsOutput) String() string { +func (s ListSharedProjectsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListProjectsOutput) GoString() string { +func (s ListSharedProjectsOutput) GoString() string { return s.String() } // SetNextToken sets the NextToken field's value. -func (s *ListProjectsOutput) SetNextToken(v string) *ListProjectsOutput { +func (s *ListSharedProjectsOutput) SetNextToken(v string) *ListSharedProjectsOutput { s.NextToken = &v return s } // SetProjects sets the Projects field's value. -func (s *ListProjectsOutput) SetProjects(v []*string) *ListProjectsOutput { +func (s *ListSharedProjectsOutput) SetProjects(v []*string) *ListSharedProjectsOutput { s.Projects = v return s } -type ListReportGroupsInput struct { +type ListSharedReportGroupsInput struct { _ struct{} `type:"structure"` - // The maximum number of paginated report groups returned per response. Use - // nextToken to iterate pages in the list of returned ReportGroup objects. The - // default value is 100. + // The maximum number of paginated shared report groups per response. Use nextToken + // to iterate pages in the list of returned ReportGroup objects. The default + // value is 100. MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` // During a previous call, the maximum number of items that can be returned @@ -5788,33 +9236,36 @@ type ListReportGroupsInput struct { // returned. NextToken *string `locationName:"nextToken" type:"string"` - // The criterion to be used to list build report groups. Valid values include: - // - // * CREATED_TIME: List based on when each report group was created. + // The criterion to be used to list report groups shared with the current AWS + // account or user. Valid values include: // - // * LAST_MODIFIED_TIME: List based on when each report group was last changed. + // * ARN: List based on the ARN. // - // * NAME: List based on each report group's name. - SortBy *string `locationName:"sortBy" type:"string" enum:"ReportGroupSortByType"` + // * MODIFIED_TIME: List based on when information about the shared report + // group was last changed. + SortBy *string `locationName:"sortBy" type:"string" enum:"SharedResourceSortByType"` - // Used to specify the order to sort the list of returned report groups. Valid - // values are ASCENDING and DESCENDING. + // The order in which to list shared report groups. Valid values include: + // + // * ASCENDING: List in ascending order. + // + // * DESCENDING: List in descending order. SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` } // String returns the string representation -func (s ListReportGroupsInput) String() string { +func (s ListSharedReportGroupsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListReportGroupsInput) GoString() string { +func (s ListSharedReportGroupsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListReportGroupsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListReportGroupsInput"} +func (s *ListSharedReportGroupsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListSharedReportGroupsInput"} if s.MaxResults != nil && *s.MaxResults < 1 { invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } @@ -5826,30 +9277,30 @@ func (s *ListReportGroupsInput) Validate() error { } // SetMaxResults sets the MaxResults field's value. -func (s *ListReportGroupsInput) SetMaxResults(v int64) *ListReportGroupsInput { +func (s *ListSharedReportGroupsInput) SetMaxResults(v int64) *ListSharedReportGroupsInput { s.MaxResults = &v return s } // SetNextToken sets the NextToken field's value. -func (s *ListReportGroupsInput) SetNextToken(v string) *ListReportGroupsInput { +func (s *ListSharedReportGroupsInput) SetNextToken(v string) *ListSharedReportGroupsInput { s.NextToken = &v return s } // SetSortBy sets the SortBy field's value. -func (s *ListReportGroupsInput) SetSortBy(v string) *ListReportGroupsInput { +func (s *ListSharedReportGroupsInput) SetSortBy(v string) *ListSharedReportGroupsInput { s.SortBy = &v return s } // SetSortOrder sets the SortOrder field's value. -func (s *ListReportGroupsInput) SetSortOrder(v string) *ListReportGroupsInput { +func (s *ListSharedReportGroupsInput) SetSortOrder(v string) *ListSharedReportGroupsInput { s.SortOrder = &v return s } -type ListReportGroupsOutput struct { +type ListSharedReportGroupsOutput struct { _ struct{} `type:"structure"` // During a previous call, the maximum number of items that can be returned @@ -5861,80 +9312,108 @@ type ListReportGroupsOutput struct { // returned. NextToken *string `locationName:"nextToken" type:"string"` - // The list of ARNs for the report groups in the current AWS account. + // The list of ARNs for the report groups shared with the current AWS account + // or user. ReportGroups []*string `locationName:"reportGroups" min:"1" type:"list"` } // String returns the string representation -func (s ListReportGroupsOutput) String() string { +func (s ListSharedReportGroupsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListReportGroupsOutput) GoString() string { +func (s ListSharedReportGroupsOutput) GoString() string { return s.String() } // SetNextToken sets the NextToken field's value. -func (s *ListReportGroupsOutput) SetNextToken(v string) *ListReportGroupsOutput { +func (s *ListSharedReportGroupsOutput) SetNextToken(v string) *ListSharedReportGroupsOutput { s.NextToken = &v return s } // SetReportGroups sets the ReportGroups field's value. -func (s *ListReportGroupsOutput) SetReportGroups(v []*string) *ListReportGroupsOutput { +func (s *ListSharedReportGroupsOutput) SetReportGroups(v []*string) *ListSharedReportGroupsOutput { s.ReportGroups = v return s } -type ListReportsForReportGroupInput struct { +type ListSourceCredentialsInput struct { _ struct{} `type:"structure"` +} - // A ReportFilter object used to filter the returned reports. - Filter *ReportFilter `locationName:"filter" type:"structure"` +// String returns the string representation +func (s ListSourceCredentialsInput) String() string { + return awsutil.Prettify(s) +} - // The maximum number of paginated reports in this report group returned per - // response. Use nextToken to iterate pages in the list of returned Report objects. - // The default value is 100. - MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` +// GoString returns the string representation +func (s ListSourceCredentialsInput) GoString() string { + return s.String() +} - // During a previous call, the maximum number of items that can be returned - // is the value specified in maxResults. If there more items in the list, then - // a unique string called a nextToken is returned. To get the next batch of - // items in the list, call this operation again, adding the next token to the - // call. To get all of the items in the list, keep calling this operation with - // each subsequent next token that is returned, until no more next tokens are - // returned. - NextToken *string `locationName:"nextToken" type:"string"` +type ListSourceCredentialsOutput struct { + _ struct{} `type:"structure"` - // The ARN of the report group for which you want to return report ARNs. - // - // ReportGroupArn is a required field - ReportGroupArn *string `locationName:"reportGroupArn" type:"string" required:"true"` + // A list of SourceCredentialsInfo objects. Each SourceCredentialsInfo object + // includes the authentication type, token ARN, and type of source provider + // for one set of credentials. + SourceCredentialsInfos []*SourceCredentialsInfo `locationName:"sourceCredentialsInfos" type:"list"` +} + +// String returns the string representation +func (s ListSourceCredentialsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListSourceCredentialsOutput) GoString() string { + return s.String() +} + +// SetSourceCredentialsInfos sets the SourceCredentialsInfos field's value. +func (s *ListSourceCredentialsOutput) SetSourceCredentialsInfos(v []*SourceCredentialsInfo) *ListSourceCredentialsOutput { + s.SourceCredentialsInfos = v + return s +} + +// Information about logs for a build project. These can be logs in Amazon CloudWatch +// Logs, built in a specified S3 bucket, or both. +type LogsConfig struct { + _ struct{} `type:"structure"` + + // Information about Amazon CloudWatch Logs for a build project. Amazon CloudWatch + // Logs are enabled by default. + CloudWatchLogs *CloudWatchLogsConfig `locationName:"cloudWatchLogs" type:"structure"` - // Use to specify whether the results are returned in ascending or descending - // order. - SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` + // Information about logs built to an S3 bucket for a build project. S3 logs + // are not enabled by default. + S3Logs *S3LogsConfig `locationName:"s3Logs" type:"structure"` } // String returns the string representation -func (s ListReportsForReportGroupInput) String() string { +func (s LogsConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListReportsForReportGroupInput) GoString() string { +func (s LogsConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListReportsForReportGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListReportsForReportGroupInput"} - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) +func (s *LogsConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LogsConfig"} + if s.CloudWatchLogs != nil { + if err := s.CloudWatchLogs.Validate(); err != nil { + invalidParams.AddNested("CloudWatchLogs", err.(request.ErrInvalidParams)) + } } - if s.ReportGroupArn == nil { - invalidParams.Add(request.NewErrParamRequired("ReportGroupArn")) + if s.S3Logs != nil { + if err := s.S3Logs.Validate(); err != nil { + invalidParams.AddNested("S3Logs", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -5943,507 +9422,645 @@ func (s *ListReportsForReportGroupInput) Validate() error { return nil } -// SetFilter sets the Filter field's value. -func (s *ListReportsForReportGroupInput) SetFilter(v *ReportFilter) *ListReportsForReportGroupInput { - s.Filter = v +// SetCloudWatchLogs sets the CloudWatchLogs field's value. +func (s *LogsConfig) SetCloudWatchLogs(v *CloudWatchLogsConfig) *LogsConfig { + s.CloudWatchLogs = v return s } -// SetMaxResults sets the MaxResults field's value. -func (s *ListReportsForReportGroupInput) SetMaxResults(v int64) *ListReportsForReportGroupInput { - s.MaxResults = &v +// SetS3Logs sets the S3Logs field's value. +func (s *LogsConfig) SetS3Logs(v *S3LogsConfig) *LogsConfig { + s.S3Logs = v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListReportsForReportGroupInput) SetNextToken(v string) *ListReportsForReportGroupInput { - s.NextToken = &v - return s -} +// Information about build logs in Amazon CloudWatch Logs. +type LogsLocation struct { + _ struct{} `type:"structure"` -// SetReportGroupArn sets the ReportGroupArn field's value. -func (s *ListReportsForReportGroupInput) SetReportGroupArn(v string) *ListReportsForReportGroupInput { - s.ReportGroupArn = &v - return s -} + // Information about Amazon CloudWatch Logs for a build project. + CloudWatchLogs *CloudWatchLogsConfig `locationName:"cloudWatchLogs" type:"structure"` -// SetSortOrder sets the SortOrder field's value. -func (s *ListReportsForReportGroupInput) SetSortOrder(v string) *ListReportsForReportGroupInput { - s.SortOrder = &v - return s -} + // The ARN of Amazon CloudWatch Logs for a build project. Its format is arn:${Partition}:logs:${Region}:${Account}:log-group:${LogGroupName}:log-stream:${LogStreamName}. + // For more information, see Resources Defined by Amazon CloudWatch Logs (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncloudwatchlogs.html#amazoncloudwatchlogs-resources-for-iam-policies). + CloudWatchLogsArn *string `locationName:"cloudWatchLogsArn" type:"string"` -type ListReportsForReportGroupOutput struct { - _ struct{} `type:"structure"` + // The URL to an individual build log in Amazon CloudWatch Logs. + DeepLink *string `locationName:"deepLink" type:"string"` - // During a previous call, the maximum number of items that can be returned - // is the value specified in maxResults. If there more items in the list, then - // a unique string called a nextToken is returned. To get the next batch of - // items in the list, call this operation again, adding the next token to the - // call. To get all of the items in the list, keep calling this operation with - // each subsequent next token that is returned, until no more next tokens are - // returned. - NextToken *string `locationName:"nextToken" type:"string"` + // The name of the Amazon CloudWatch Logs group for the build logs. + GroupName *string `locationName:"groupName" type:"string"` - // The list of returned report group ARNs. - Reports []*string `locationName:"reports" min:"1" type:"list"` + // The URL to a build log in an S3 bucket. + S3DeepLink *string `locationName:"s3DeepLink" type:"string"` + + // Information about S3 logs for a build project. + S3Logs *S3LogsConfig `locationName:"s3Logs" type:"structure"` + + // The ARN of S3 logs for a build project. Its format is arn:${Partition}:s3:::${BucketName}/${ObjectName}. + // For more information, see Resources Defined by Amazon S3 (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazons3.html#amazons3-resources-for-iam-policies). + S3LogsArn *string `locationName:"s3LogsArn" type:"string"` + + // The name of the Amazon CloudWatch Logs stream for the build logs. + StreamName *string `locationName:"streamName" type:"string"` } // String returns the string representation -func (s ListReportsForReportGroupOutput) String() string { +func (s LogsLocation) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListReportsForReportGroupOutput) GoString() string { +func (s LogsLocation) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListReportsForReportGroupOutput) SetNextToken(v string) *ListReportsForReportGroupOutput { - s.NextToken = &v +// SetCloudWatchLogs sets the CloudWatchLogs field's value. +func (s *LogsLocation) SetCloudWatchLogs(v *CloudWatchLogsConfig) *LogsLocation { + s.CloudWatchLogs = v return s } -// SetReports sets the Reports field's value. -func (s *ListReportsForReportGroupOutput) SetReports(v []*string) *ListReportsForReportGroupOutput { - s.Reports = v +// SetCloudWatchLogsArn sets the CloudWatchLogsArn field's value. +func (s *LogsLocation) SetCloudWatchLogsArn(v string) *LogsLocation { + s.CloudWatchLogsArn = &v return s } -type ListReportsInput struct { - _ struct{} `type:"structure"` - - // A ReportFilter object used to filter the returned reports. - Filter *ReportFilter `locationName:"filter" type:"structure"` - - // The maximum number of paginated reports returned per response. Use nextToken - // to iterate pages in the list of returned Report objects. The default value - // is 100. - MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` - - // During a previous call, the maximum number of items that can be returned - // is the value specified in maxResults. If there more items in the list, then - // a unique string called a nextToken is returned. To get the next batch of - // items in the list, call this operation again, adding the next token to the - // call. To get all of the items in the list, keep calling this operation with - // each subsequent next token that is returned, until no more next tokens are - // returned. - NextToken *string `locationName:"nextToken" type:"string"` - - // Specifies the sort order for the list of returned reports. Valid values are: - // - // * ASCENDING: return reports in chronological order based on their creation - // date. - // - // * DESCENDING: return reports in the reverse chronological order based - // on their creation date. - SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` -} - -// String returns the string representation -func (s ListReportsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListReportsInput) GoString() string { - return s.String() +// SetDeepLink sets the DeepLink field's value. +func (s *LogsLocation) SetDeepLink(v string) *LogsLocation { + s.DeepLink = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListReportsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListReportsInput"} - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetGroupName sets the GroupName field's value. +func (s *LogsLocation) SetGroupName(v string) *LogsLocation { + s.GroupName = &v + return s } -// SetFilter sets the Filter field's value. -func (s *ListReportsInput) SetFilter(v *ReportFilter) *ListReportsInput { - s.Filter = v +// SetS3DeepLink sets the S3DeepLink field's value. +func (s *LogsLocation) SetS3DeepLink(v string) *LogsLocation { + s.S3DeepLink = &v return s } -// SetMaxResults sets the MaxResults field's value. -func (s *ListReportsInput) SetMaxResults(v int64) *ListReportsInput { - s.MaxResults = &v +// SetS3Logs sets the S3Logs field's value. +func (s *LogsLocation) SetS3Logs(v *S3LogsConfig) *LogsLocation { + s.S3Logs = v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListReportsInput) SetNextToken(v string) *ListReportsInput { - s.NextToken = &v +// SetS3LogsArn sets the S3LogsArn field's value. +func (s *LogsLocation) SetS3LogsArn(v string) *LogsLocation { + s.S3LogsArn = &v return s } -// SetSortOrder sets the SortOrder field's value. -func (s *ListReportsInput) SetSortOrder(v string) *ListReportsInput { - s.SortOrder = &v +// SetStreamName sets the StreamName field's value. +func (s *LogsLocation) SetStreamName(v string) *LogsLocation { + s.StreamName = &v return s } -type ListReportsOutput struct { +// Describes a network interface. +type NetworkInterface struct { _ struct{} `type:"structure"` - // During a previous call, the maximum number of items that can be returned - // is the value specified in maxResults. If there more items in the list, then - // a unique string called a nextToken is returned. To get the next batch of - // items in the list, call this operation again, adding the next token to the - // call. To get all of the items in the list, keep calling this operation with - // each subsequent next token that is returned, until no more next tokens are - // returned. - NextToken *string `locationName:"nextToken" type:"string"` + // The ID of the network interface. + NetworkInterfaceId *string `locationName:"networkInterfaceId" min:"1" type:"string"` - // The list of returned ARNs for the reports in the current AWS account. - Reports []*string `locationName:"reports" min:"1" type:"list"` + // The ID of the subnet. + SubnetId *string `locationName:"subnetId" min:"1" type:"string"` } // String returns the string representation -func (s ListReportsOutput) String() string { +func (s NetworkInterface) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListReportsOutput) GoString() string { +func (s NetworkInterface) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListReportsOutput) SetNextToken(v string) *ListReportsOutput { - s.NextToken = &v +// SetNetworkInterfaceId sets the NetworkInterfaceId field's value. +func (s *NetworkInterface) SetNetworkInterfaceId(v string) *NetworkInterface { + s.NetworkInterfaceId = &v return s } -// SetReports sets the Reports field's value. -func (s *ListReportsOutput) SetReports(v []*string) *ListReportsOutput { - s.Reports = v +// SetSubnetId sets the SubnetId field's value. +func (s *NetworkInterface) SetSubnetId(v string) *NetworkInterface { + s.SubnetId = &v return s } -type ListSharedProjectsInput struct { - _ struct{} `type:"structure"` - - // The maximum number of paginated shared build projects returned per response. - // Use nextToken to iterate pages in the list of returned Project objects. The - // default value is 100. - MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` - - // During a previous call, the maximum number of items that can be returned - // is the value specified in maxResults. If there more items in the list, then - // a unique string called a nextToken is returned. To get the next batch of - // items in the list, call this operation again, adding the next token to the - // call. To get all of the items in the list, keep calling this operation with - // each subsequent next token that is returned, until no more next tokens are - // returned. - NextToken *string `locationName:"nextToken" min:"1" type:"string"` - - // The criterion to be used to list build projects shared with the current AWS - // account or user. Valid values include: - // - // * ARN: List based on the ARN. - // - // * MODIFIED_TIME: List based on when information about the shared project - // was last changed. - SortBy *string `locationName:"sortBy" type:"string" enum:"SharedResourceSortByType"` +// There was a problem with the underlying OAuth provider. +type OAuthProviderException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // The order in which to list shared build projects. Valid values include: - // - // * ASCENDING: List in ascending order. - // - // * DESCENDING: List in descending order. - SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` + Message_ *string `locationName:"message" type:"string"` } // String returns the string representation -func (s ListSharedProjectsInput) String() string { +func (s OAuthProviderException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListSharedProjectsInput) GoString() string { +func (s OAuthProviderException) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListSharedProjectsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListSharedProjectsInput"} - 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)) +func newErrorOAuthProviderException(v protocol.ResponseMetadata) error { + return &OAuthProviderException{ + RespMetadata: v, } +} - if invalidParams.Len() > 0 { - return invalidParams +// Code returns the exception type name. +func (s *OAuthProviderException) Code() string { + return "OAuthProviderException" +} + +// Message returns the exception's message. +func (s *OAuthProviderException) Message() string { + if s.Message_ != nil { + return *s.Message_ } - return nil + return "" } -// SetMaxResults sets the MaxResults field's value. -func (s *ListSharedProjectsInput) SetMaxResults(v int64) *ListSharedProjectsInput { - s.MaxResults = &v - return s +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *OAuthProviderException) OrigErr() error { + return nil } -// SetNextToken sets the NextToken field's value. -func (s *ListSharedProjectsInput) SetNextToken(v string) *ListSharedProjectsInput { - s.NextToken = &v - return s +func (s *OAuthProviderException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) } -// SetSortBy sets the SortBy field's value. -func (s *ListSharedProjectsInput) SetSortBy(v string) *ListSharedProjectsInput { - s.SortBy = &v - return s +// Status code returns the HTTP status code for the request's response error. +func (s *OAuthProviderException) StatusCode() int { + return s.RespMetadata.StatusCode } -// SetSortOrder sets the SortOrder field's value. -func (s *ListSharedProjectsInput) SetSortOrder(v string) *ListSharedProjectsInput { - s.SortOrder = &v - return s +// RequestID returns the service's response RequestID for request. +func (s *OAuthProviderException) RequestID() string { + return s.RespMetadata.RequestID } -type ListSharedProjectsOutput struct { +// Additional information about a build phase that has an error. You can use +// this information for troubleshooting. +type PhaseContext struct { _ struct{} `type:"structure"` - // During a previous call, the maximum number of items that can be returned - // is the value specified in maxResults. If there more items in the list, then - // a unique string called a nextToken is returned. To get the next batch of - // items in the list, call this operation again, adding the next token to the - // call. To get all of the items in the list, keep calling this operation with - // each subsequent next token that is returned, until no more next tokens are - // returned. - NextToken *string `locationName:"nextToken" type:"string"` + // An explanation of the build phase's context. This might include a command + // ID and an exit code. + Message *string `locationName:"message" type:"string"` - // The list of ARNs for the build projects shared with the current AWS account - // or user. - Projects []*string `locationName:"projects" min:"1" type:"list"` + // The status code for the context of the build phase. + StatusCode *string `locationName:"statusCode" type:"string"` } // String returns the string representation -func (s ListSharedProjectsOutput) String() string { +func (s PhaseContext) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListSharedProjectsOutput) GoString() string { +func (s PhaseContext) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListSharedProjectsOutput) SetNextToken(v string) *ListSharedProjectsOutput { - s.NextToken = &v +// SetMessage sets the Message field's value. +func (s *PhaseContext) SetMessage(v string) *PhaseContext { + s.Message = &v return s } -// SetProjects sets the Projects field's value. -func (s *ListSharedProjectsOutput) SetProjects(v []*string) *ListSharedProjectsOutput { - s.Projects = v +// SetStatusCode sets the StatusCode field's value. +func (s *PhaseContext) SetStatusCode(v string) *PhaseContext { + s.StatusCode = &v return s } -type ListSharedReportGroupsInput struct { +// Information about a build project. +type Project struct { _ struct{} `type:"structure"` - // The maximum number of paginated shared report groups per response. Use nextToken - // to iterate pages in the list of returned ReportGroup objects. The default - // value is 100. - MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` + // The Amazon Resource Name (ARN) of the build project. + Arn *string `locationName:"arn" type:"string"` - // During a previous call, the maximum number of items that can be returned - // is the value specified in maxResults. If there more items in the list, then - // a unique string called a nextToken is returned. To get the next batch of - // items in the list, call this operation again, adding the next token to the - // call. To get all of the items in the list, keep calling this operation with - // each subsequent next token that is returned, until no more next tokens are - // returned. - NextToken *string `locationName:"nextToken" type:"string"` + // Information about the build output artifacts for the build project. + Artifacts *ProjectArtifacts `locationName:"artifacts" type:"structure"` - // The criterion to be used to list report groups shared with the current AWS - // account or user. Valid values include: + // Information about the build badge for the build project. + Badge *ProjectBadge `locationName:"badge" type:"structure"` + + // A ProjectBuildBatchConfig object that defines the batch build options for + // the project. + BuildBatchConfig *ProjectBuildBatchConfig `locationName:"buildBatchConfig" type:"structure"` + + // Information about the cache for the build project. + Cache *ProjectCache `locationName:"cache" type:"structure"` + + // When the build project was created, expressed in Unix time format. + Created *time.Time `locationName:"created" type:"timestamp"` + + // A description that makes the build project easy to identify. + Description *string `locationName:"description" type:"string"` + + // The AWS Key Management Service (AWS KMS) customer master key (CMK) to be + // used for encrypting the build output artifacts. // - // * ARN: List based on the ARN. + // You can use a cross-account KMS key to encrypt the build output artifacts + // if your service role has permission to that key. // - // * MODIFIED_TIME: List based on when information about the shared report - // group was last changed. - SortBy *string `locationName:"sortBy" type:"string" enum:"SharedResourceSortByType"` + // You can specify either the Amazon Resource Name (ARN) of the CMK or, if available, + // the CMK's alias (using the format alias/alias-name ). + EncryptionKey *string `locationName:"encryptionKey" min:"1" type:"string"` - // The order in which to list shared report groups. Valid values include: + // Information about the build environment for this build project. + Environment *ProjectEnvironment `locationName:"environment" type:"structure"` + + // An array of ProjectFileSystemLocation objects for a CodeBuild build project. + // A ProjectFileSystemLocation object specifies the identifier, location, mountOptions, + // mountPoint, and type of a file system created using Amazon Elastic File System. + FileSystemLocations []*ProjectFileSystemLocation `locationName:"fileSystemLocations" type:"list"` + + // When the build project's settings were last modified, expressed in Unix time + // format. + LastModified *time.Time `locationName:"lastModified" type:"timestamp"` + + // Information about logs for the build project. A project can create logs in + // Amazon CloudWatch Logs, an S3 bucket, or both. + LogsConfig *LogsConfig `locationName:"logsConfig" type:"structure"` + + // The name of the build project. + Name *string `locationName:"name" min:"2" type:"string"` + + // The number of minutes a build is allowed to be queued before it times out. + QueuedTimeoutInMinutes *int64 `locationName:"queuedTimeoutInMinutes" min:"5" type:"integer"` + + // An array of ProjectArtifacts objects. + SecondaryArtifacts []*ProjectArtifacts `locationName:"secondaryArtifacts" type:"list"` + + // An array of ProjectSourceVersion objects. If secondarySourceVersions is specified + // at the build level, then they take over these secondarySourceVersions (at + // the project level). + SecondarySourceVersions []*ProjectSourceVersion `locationName:"secondarySourceVersions" type:"list"` + + // An array of ProjectSource objects. + SecondarySources []*ProjectSource `locationName:"secondarySources" type:"list"` + + // The ARN of the AWS Identity and Access Management (IAM) role that enables + // AWS CodeBuild to interact with dependent AWS services on behalf of the AWS + // account. + ServiceRole *string `locationName:"serviceRole" min:"1" type:"string"` + + // Information about the build input source code for this build project. + Source *ProjectSource `locationName:"source" type:"structure"` + + // A version of the build input to be built for this project. If not specified, + // the latest version is used. If specified, it must be one of: // - // * ASCENDING: List in ascending order. + // * For AWS CodeCommit: the commit ID, branch, or Git tag to use. // - // * DESCENDING: List in descending order. - SortOrder *string `locationName:"sortOrder" type:"string" enum:"SortOrderType"` + // * For GitHub: the commit ID, pull request ID, branch name, or tag name + // that corresponds to the version of the source code you want to build. + // If a pull request ID is specified, it must use the format pr/pull-request-ID + // (for example pr/25). If a branch name is specified, the branch's HEAD + // commit ID is used. If not specified, the default branch's HEAD commit + // ID is used. + // + // * For Bitbucket: the commit ID, branch name, or tag name that corresponds + // to the version of the source code you want to build. If a branch name + // is specified, the branch's HEAD commit ID is used. If not specified, the + // default branch's HEAD commit ID is used. + // + // * For Amazon Simple Storage Service (Amazon S3): the version ID of the + // object that represents the build input ZIP file to use. + // + // If sourceVersion is specified at the build level, then that version takes + // precedence over this sourceVersion (at the project level). + // + // For more information, see Source Version Sample with CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/sample-source-version.html) + // in the AWS CodeBuild User Guide. + SourceVersion *string `locationName:"sourceVersion" type:"string"` + + // A list of tag key and value pairs associated with this build project. + // + // These tags are available for use by AWS services that support AWS CodeBuild + // build project tags. + Tags []*Tag `locationName:"tags" type:"list"` + + // How long, in minutes, from 5 to 480 (8 hours), for AWS CodeBuild to wait + // before timing out any related build that did not get marked as completed. + // The default is 60 minutes. + TimeoutInMinutes *int64 `locationName:"timeoutInMinutes" min:"5" type:"integer"` + + // Information about the VPC configuration that AWS CodeBuild accesses. + VpcConfig *VpcConfig `locationName:"vpcConfig" type:"structure"` + + // Information about a webhook that connects repository events to a build project + // in AWS CodeBuild. + Webhook *Webhook `locationName:"webhook" type:"structure"` } // String returns the string representation -func (s ListSharedReportGroupsInput) String() string { +func (s Project) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListSharedReportGroupsInput) GoString() string { +func (s Project) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListSharedReportGroupsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListSharedReportGroupsInput"} - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) - } +// SetArn sets the Arn field's value. +func (s *Project) SetArn(v string) *Project { + s.Arn = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetArtifacts sets the Artifacts field's value. +func (s *Project) SetArtifacts(v *ProjectArtifacts) *Project { + s.Artifacts = v + return s +} + +// SetBadge sets the Badge field's value. +func (s *Project) SetBadge(v *ProjectBadge) *Project { + s.Badge = v + return s +} + +// SetBuildBatchConfig sets the BuildBatchConfig field's value. +func (s *Project) SetBuildBatchConfig(v *ProjectBuildBatchConfig) *Project { + s.BuildBatchConfig = v + return s } -// SetMaxResults sets the MaxResults field's value. -func (s *ListSharedReportGroupsInput) SetMaxResults(v int64) *ListSharedReportGroupsInput { - s.MaxResults = &v +// SetCache sets the Cache field's value. +func (s *Project) SetCache(v *ProjectCache) *Project { + s.Cache = v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListSharedReportGroupsInput) SetNextToken(v string) *ListSharedReportGroupsInput { - s.NextToken = &v +// SetCreated sets the Created field's value. +func (s *Project) SetCreated(v time.Time) *Project { + s.Created = &v return s } -// SetSortBy sets the SortBy field's value. -func (s *ListSharedReportGroupsInput) SetSortBy(v string) *ListSharedReportGroupsInput { - s.SortBy = &v +// SetDescription sets the Description field's value. +func (s *Project) SetDescription(v string) *Project { + s.Description = &v return s } -// SetSortOrder sets the SortOrder field's value. -func (s *ListSharedReportGroupsInput) SetSortOrder(v string) *ListSharedReportGroupsInput { - s.SortOrder = &v +// SetEncryptionKey sets the EncryptionKey field's value. +func (s *Project) SetEncryptionKey(v string) *Project { + s.EncryptionKey = &v return s } -type ListSharedReportGroupsOutput struct { - _ struct{} `type:"structure"` +// SetEnvironment sets the Environment field's value. +func (s *Project) SetEnvironment(v *ProjectEnvironment) *Project { + s.Environment = v + return s +} - // During a previous call, the maximum number of items that can be returned - // is the value specified in maxResults. If there more items in the list, then - // a unique string called a nextToken is returned. To get the next batch of - // items in the list, call this operation again, adding the next token to the - // call. To get all of the items in the list, keep calling this operation with - // each subsequent next token that is returned, until no more next tokens are - // returned. - NextToken *string `locationName:"nextToken" type:"string"` +// SetFileSystemLocations sets the FileSystemLocations field's value. +func (s *Project) SetFileSystemLocations(v []*ProjectFileSystemLocation) *Project { + s.FileSystemLocations = v + return s +} - // The list of ARNs for the report groups shared with the current AWS account - // or user. - ReportGroups []*string `locationName:"reportGroups" min:"1" type:"list"` +// SetLastModified sets the LastModified field's value. +func (s *Project) SetLastModified(v time.Time) *Project { + s.LastModified = &v + return s } -// String returns the string representation -func (s ListSharedReportGroupsOutput) String() string { - return awsutil.Prettify(s) +// SetLogsConfig sets the LogsConfig field's value. +func (s *Project) SetLogsConfig(v *LogsConfig) *Project { + s.LogsConfig = v + return s } -// GoString returns the string representation -func (s ListSharedReportGroupsOutput) GoString() string { - return s.String() +// SetName sets the Name field's value. +func (s *Project) SetName(v string) *Project { + s.Name = &v + return s } -// SetNextToken sets the NextToken field's value. -func (s *ListSharedReportGroupsOutput) SetNextToken(v string) *ListSharedReportGroupsOutput { - s.NextToken = &v +// SetQueuedTimeoutInMinutes sets the QueuedTimeoutInMinutes field's value. +func (s *Project) SetQueuedTimeoutInMinutes(v int64) *Project { + s.QueuedTimeoutInMinutes = &v return s } -// SetReportGroups sets the ReportGroups field's value. -func (s *ListSharedReportGroupsOutput) SetReportGroups(v []*string) *ListSharedReportGroupsOutput { - s.ReportGroups = v +// SetSecondaryArtifacts sets the SecondaryArtifacts field's value. +func (s *Project) SetSecondaryArtifacts(v []*ProjectArtifacts) *Project { + s.SecondaryArtifacts = v return s } -type ListSourceCredentialsInput struct { - _ struct{} `type:"structure"` +// SetSecondarySourceVersions sets the SecondarySourceVersions field's value. +func (s *Project) SetSecondarySourceVersions(v []*ProjectSourceVersion) *Project { + s.SecondarySourceVersions = v + return s } -// String returns the string representation -func (s ListSourceCredentialsInput) String() string { - return awsutil.Prettify(s) +// SetSecondarySources sets the SecondarySources field's value. +func (s *Project) SetSecondarySources(v []*ProjectSource) *Project { + s.SecondarySources = v + return s } -// GoString returns the string representation -func (s ListSourceCredentialsInput) GoString() string { - return s.String() +// SetServiceRole sets the ServiceRole field's value. +func (s *Project) SetServiceRole(v string) *Project { + s.ServiceRole = &v + return s } -type ListSourceCredentialsOutput struct { - _ struct{} `type:"structure"` +// SetSource sets the Source field's value. +func (s *Project) SetSource(v *ProjectSource) *Project { + s.Source = v + return s +} - // A list of SourceCredentialsInfo objects. Each SourceCredentialsInfo object - // includes the authentication type, token ARN, and type of source provider - // for one set of credentials. - SourceCredentialsInfos []*SourceCredentialsInfo `locationName:"sourceCredentialsInfos" type:"list"` +// SetSourceVersion sets the SourceVersion field's value. +func (s *Project) SetSourceVersion(v string) *Project { + s.SourceVersion = &v + return s } -// String returns the string representation -func (s ListSourceCredentialsOutput) String() string { - return awsutil.Prettify(s) +// SetTags sets the Tags field's value. +func (s *Project) SetTags(v []*Tag) *Project { + s.Tags = v + return s } -// GoString returns the string representation -func (s ListSourceCredentialsOutput) GoString() string { - return s.String() +// SetTimeoutInMinutes sets the TimeoutInMinutes field's value. +func (s *Project) SetTimeoutInMinutes(v int64) *Project { + s.TimeoutInMinutes = &v + return s } -// SetSourceCredentialsInfos sets the SourceCredentialsInfos field's value. -func (s *ListSourceCredentialsOutput) SetSourceCredentialsInfos(v []*SourceCredentialsInfo) *ListSourceCredentialsOutput { - s.SourceCredentialsInfos = v +// SetVpcConfig sets the VpcConfig field's value. +func (s *Project) SetVpcConfig(v *VpcConfig) *Project { + s.VpcConfig = v return s } -// Information about logs for a build project. These can be logs in Amazon CloudWatch -// Logs, built in a specified S3 bucket, or both. -type LogsConfig struct { +// SetWebhook sets the Webhook field's value. +func (s *Project) SetWebhook(v *Webhook) *Project { + s.Webhook = v + return s +} + +// Information about the build output artifacts for the build project. +type ProjectArtifacts struct { _ struct{} `type:"structure"` - // Information about Amazon CloudWatch Logs for a build project. Amazon CloudWatch - // Logs are enabled by default. - CloudWatchLogs *CloudWatchLogsConfig `locationName:"cloudWatchLogs" type:"structure"` + // An identifier for this artifact definition. + ArtifactIdentifier *string `locationName:"artifactIdentifier" type:"string"` - // Information about logs built to an S3 bucket for a build project. S3 logs - // are not enabled by default. - S3Logs *S3LogsConfig `locationName:"s3Logs" type:"structure"` + // Set to true if you do not want your output artifacts encrypted. This option + // is valid only if your artifacts type is Amazon Simple Storage Service (Amazon + // S3). If this is set with another artifacts type, an invalidInputException + // is thrown. + EncryptionDisabled *bool `locationName:"encryptionDisabled" type:"boolean"` + + // Information about the build output artifact location: + // + // * If type is set to CODEPIPELINE, AWS CodePipeline ignores this value + // if specified. This is because AWS CodePipeline manages its build output + // locations instead of AWS CodeBuild. + // + // * If type is set to NO_ARTIFACTS, this value is ignored if specified, + // because no build output is produced. + // + // * If type is set to S3, this is the name of the output bucket. + Location *string `locationName:"location" type:"string"` + + // Along with path and namespaceType, the pattern that AWS CodeBuild uses to + // name and store the output artifact: + // + // * If type is set to CODEPIPELINE, AWS CodePipeline ignores this value + // if specified. This is because AWS CodePipeline manages its build output + // names instead of AWS CodeBuild. + // + // * If type is set to NO_ARTIFACTS, this value is ignored if specified, + // because no build output is produced. + // + // * If type is set to S3, this is the name of the output artifact object. + // If you set the name to be a forward slash ("/"), the artifact is stored + // in the root of the output bucket. + // + // For example: + // + // * If path is set to MyArtifacts, namespaceType is set to BUILD_ID, and + // name is set to MyArtifact.zip, then the output artifact is stored in MyArtifacts/build-ID/MyArtifact.zip. + // + // * If path is empty, namespaceType is set to NONE, and name is set to "/", + // the output artifact is stored in the root of the output bucket. + // + // * If path is set to MyArtifacts, namespaceType is set to BUILD_ID, and + // name is set to "/", the output artifact is stored in MyArtifacts/build-ID . + Name *string `locationName:"name" type:"string"` + + // Along with path and name, the pattern that AWS CodeBuild uses to determine + // the name and location to store the output artifact: + // + // * If type is set to CODEPIPELINE, AWS CodePipeline ignores this value + // if specified. This is because AWS CodePipeline manages its build output + // names instead of AWS CodeBuild. + // + // * If type is set to NO_ARTIFACTS, this value is ignored if specified, + // because no build output is produced. + // + // * If type is set to S3, valid values include: BUILD_ID: Include the build + // ID in the location of the build output artifact. NONE: Do not include + // the build ID. This is the default if namespaceType is not specified. + // + // For example, if path is set to MyArtifacts, namespaceType is set to BUILD_ID, + // and name is set to MyArtifact.zip, the output artifact is stored in MyArtifacts/build-ID/MyArtifact.zip. + NamespaceType *string `locationName:"namespaceType" type:"string" enum:"ArtifactNamespace"` + + // If this flag is set, a name specified in the buildspec file overrides the + // artifact name. The name specified in a buildspec file is calculated at build + // time and uses the Shell Command Language. For example, you can append a date + // and time to your artifact name so that it is always unique. + OverrideArtifactName *bool `locationName:"overrideArtifactName" type:"boolean"` + + // The type of build output artifact to create: + // + // * If type is set to CODEPIPELINE, AWS CodePipeline ignores this value + // if specified. This is because AWS CodePipeline manages its build output + // artifacts instead of AWS CodeBuild. + // + // * If type is set to NO_ARTIFACTS, this value is ignored if specified, + // because no build output is produced. + // + // * If type is set to S3, valid values include: NONE: AWS CodeBuild creates + // in the output bucket a folder that contains the build output. This is + // the default if packaging is not specified. ZIP: AWS CodeBuild creates + // in the output bucket a ZIP file that contains the build output. + Packaging *string `locationName:"packaging" type:"string" enum:"ArtifactPackaging"` + + // Along with namespaceType and name, the pattern that AWS CodeBuild uses to + // name and store the output artifact: + // + // * If type is set to CODEPIPELINE, AWS CodePipeline ignores this value + // if specified. This is because AWS CodePipeline manages its build output + // names instead of AWS CodeBuild. + // + // * If type is set to NO_ARTIFACTS, this value is ignored if specified, + // because no build output is produced. + // + // * If type is set to S3, this is the path to the output artifact. If path + // is not specified, path is not used. + // + // For example, if path is set to MyArtifacts, namespaceType is set to NONE, + // and name is set to MyArtifact.zip, the output artifact is stored in the output + // bucket at MyArtifacts/MyArtifact.zip. + Path *string `locationName:"path" type:"string"` + + // The type of build output artifact. Valid values include: + // + // * CODEPIPELINE: The build project has build output generated through AWS + // CodePipeline. The CODEPIPELINE type is not supported for secondaryArtifacts. + // + // * NO_ARTIFACTS: The build project does not produce any build output. + // + // * S3: The build project stores build output in Amazon Simple Storage Service + // (Amazon S3). + // + // Type is a required field + Type *string `locationName:"type" type:"string" required:"true" enum:"ArtifactsType"` } // String returns the string representation -func (s LogsConfig) String() string { +func (s ProjectArtifacts) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s LogsConfig) GoString() string { +func (s ProjectArtifacts) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *LogsConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LogsConfig"} - if s.CloudWatchLogs != nil { - if err := s.CloudWatchLogs.Validate(); err != nil { - invalidParams.AddNested("CloudWatchLogs", err.(request.ErrInvalidParams)) - } - } - if s.S3Logs != nil { - if err := s.S3Logs.Validate(); err != nil { - invalidParams.AddNested("S3Logs", err.(request.ErrInvalidParams)) - } +func (s *ProjectArtifacts) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ProjectArtifacts"} + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) } if invalidParams.Len() > 0 { @@ -6452,636 +10069,692 @@ func (s *LogsConfig) Validate() error { return nil } -// SetCloudWatchLogs sets the CloudWatchLogs field's value. -func (s *LogsConfig) SetCloudWatchLogs(v *CloudWatchLogsConfig) *LogsConfig { - s.CloudWatchLogs = v - return s -} - -// SetS3Logs sets the S3Logs field's value. -func (s *LogsConfig) SetS3Logs(v *S3LogsConfig) *LogsConfig { - s.S3Logs = v +// SetArtifactIdentifier sets the ArtifactIdentifier field's value. +func (s *ProjectArtifacts) SetArtifactIdentifier(v string) *ProjectArtifacts { + s.ArtifactIdentifier = &v return s } -// Information about build logs in Amazon CloudWatch Logs. -type LogsLocation struct { - _ struct{} `type:"structure"` - - // Information about Amazon CloudWatch Logs for a build project. - CloudWatchLogs *CloudWatchLogsConfig `locationName:"cloudWatchLogs" type:"structure"` - - // The ARN of Amazon CloudWatch Logs for a build project. Its format is arn:${Partition}:logs:${Region}:${Account}:log-group:${LogGroupName}:log-stream:${LogStreamName}. - // For more information, see Resources Defined by Amazon CloudWatch Logs (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazoncloudwatchlogs.html#amazoncloudwatchlogs-resources-for-iam-policies). - CloudWatchLogsArn *string `locationName:"cloudWatchLogsArn" type:"string"` - - // The URL to an individual build log in Amazon CloudWatch Logs. - DeepLink *string `locationName:"deepLink" type:"string"` - - // The name of the Amazon CloudWatch Logs group for the build logs. - GroupName *string `locationName:"groupName" type:"string"` - - // The URL to a build log in an S3 bucket. - S3DeepLink *string `locationName:"s3DeepLink" type:"string"` - - // Information about S3 logs for a build project. - S3Logs *S3LogsConfig `locationName:"s3Logs" type:"structure"` - - // The ARN of S3 logs for a build project. Its format is arn:${Partition}:s3:::${BucketName}/${ObjectName}. - // For more information, see Resources Defined by Amazon S3 (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazons3.html#amazons3-resources-for-iam-policies). - S3LogsArn *string `locationName:"s3LogsArn" type:"string"` - - // The name of the Amazon CloudWatch Logs stream for the build logs. - StreamName *string `locationName:"streamName" type:"string"` -} - -// String returns the string representation -func (s LogsLocation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LogsLocation) GoString() string { - return s.String() -} - -// SetCloudWatchLogs sets the CloudWatchLogs field's value. -func (s *LogsLocation) SetCloudWatchLogs(v *CloudWatchLogsConfig) *LogsLocation { - s.CloudWatchLogs = v +// SetEncryptionDisabled sets the EncryptionDisabled field's value. +func (s *ProjectArtifacts) SetEncryptionDisabled(v bool) *ProjectArtifacts { + s.EncryptionDisabled = &v return s } -// SetCloudWatchLogsArn sets the CloudWatchLogsArn field's value. -func (s *LogsLocation) SetCloudWatchLogsArn(v string) *LogsLocation { - s.CloudWatchLogsArn = &v +// SetLocation sets the Location field's value. +func (s *ProjectArtifacts) SetLocation(v string) *ProjectArtifacts { + s.Location = &v return s } -// SetDeepLink sets the DeepLink field's value. -func (s *LogsLocation) SetDeepLink(v string) *LogsLocation { - s.DeepLink = &v +// SetName sets the Name field's value. +func (s *ProjectArtifacts) SetName(v string) *ProjectArtifacts { + s.Name = &v return s } -// SetGroupName sets the GroupName field's value. -func (s *LogsLocation) SetGroupName(v string) *LogsLocation { - s.GroupName = &v +// SetNamespaceType sets the NamespaceType field's value. +func (s *ProjectArtifacts) SetNamespaceType(v string) *ProjectArtifacts { + s.NamespaceType = &v return s } -// SetS3DeepLink sets the S3DeepLink field's value. -func (s *LogsLocation) SetS3DeepLink(v string) *LogsLocation { - s.S3DeepLink = &v +// SetOverrideArtifactName sets the OverrideArtifactName field's value. +func (s *ProjectArtifacts) SetOverrideArtifactName(v bool) *ProjectArtifacts { + s.OverrideArtifactName = &v return s } -// SetS3Logs sets the S3Logs field's value. -func (s *LogsLocation) SetS3Logs(v *S3LogsConfig) *LogsLocation { - s.S3Logs = v +// SetPackaging sets the Packaging field's value. +func (s *ProjectArtifacts) SetPackaging(v string) *ProjectArtifacts { + s.Packaging = &v return s } -// SetS3LogsArn sets the S3LogsArn field's value. -func (s *LogsLocation) SetS3LogsArn(v string) *LogsLocation { - s.S3LogsArn = &v +// SetPath sets the Path field's value. +func (s *ProjectArtifacts) SetPath(v string) *ProjectArtifacts { + s.Path = &v return s } -// SetStreamName sets the StreamName field's value. -func (s *LogsLocation) SetStreamName(v string) *LogsLocation { - s.StreamName = &v +// SetType sets the Type field's value. +func (s *ProjectArtifacts) SetType(v string) *ProjectArtifacts { + s.Type = &v return s } -// Describes a network interface. -type NetworkInterface struct { +// Information about the build badge for the build project. +type ProjectBadge struct { _ struct{} `type:"structure"` - // The ID of the network interface. - NetworkInterfaceId *string `locationName:"networkInterfaceId" min:"1" type:"string"` + // Set this to true to generate a publicly accessible URL for your project's + // build badge. + BadgeEnabled *bool `locationName:"badgeEnabled" type:"boolean"` - // The ID of the subnet. - SubnetId *string `locationName:"subnetId" min:"1" type:"string"` + // The publicly-accessible URL through which you can access the build badge + // for your project. + // + // The publicly accessible URL through which you can access the build badge + // for your project. + BadgeRequestUrl *string `locationName:"badgeRequestUrl" type:"string"` } // String returns the string representation -func (s NetworkInterface) String() string { +func (s ProjectBadge) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s NetworkInterface) GoString() string { +func (s ProjectBadge) GoString() string { return s.String() } -// SetNetworkInterfaceId sets the NetworkInterfaceId field's value. -func (s *NetworkInterface) SetNetworkInterfaceId(v string) *NetworkInterface { - s.NetworkInterfaceId = &v +// SetBadgeEnabled sets the BadgeEnabled field's value. +func (s *ProjectBadge) SetBadgeEnabled(v bool) *ProjectBadge { + s.BadgeEnabled = &v return s } -// SetSubnetId sets the SubnetId field's value. -func (s *NetworkInterface) SetSubnetId(v string) *NetworkInterface { - s.SubnetId = &v +// SetBadgeRequestUrl sets the BadgeRequestUrl field's value. +func (s *ProjectBadge) SetBadgeRequestUrl(v string) *ProjectBadge { + s.BadgeRequestUrl = &v return s } -// There was a problem with the underlying OAuth provider. -type OAuthProviderException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +// Contains configuration information about a batch build project. +type ProjectBuildBatchConfig struct { + _ struct{} `type:"structure"` - Message_ *string `locationName:"message" type:"string"` + // Specifies if the build artifacts for the batch build should be combined into + // a single artifact location. + CombineArtifacts *bool `locationName:"combineArtifacts" type:"boolean"` + + // A BatchRestrictions object that specifies the restrictions for the batch + // build. + Restrictions *BatchRestrictions `locationName:"restrictions" type:"structure"` + + // Specifies the service role ARN for the batch build project. + ServiceRole *string `locationName:"serviceRole" min:"1" type:"string"` + + // Specifies the maximum amount of time, in minutes, that the batch build must + // be completed in. + TimeoutInMins *int64 `locationName:"timeoutInMins" type:"integer"` } // String returns the string representation -func (s OAuthProviderException) String() string { +func (s ProjectBuildBatchConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s OAuthProviderException) GoString() string { +func (s ProjectBuildBatchConfig) GoString() string { return s.String() } -func newErrorOAuthProviderException(v protocol.ResponseMetadata) error { - return &OAuthProviderException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *ProjectBuildBatchConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ProjectBuildBatchConfig"} + if s.ServiceRole != nil && len(*s.ServiceRole) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ServiceRole", 1)) } -} - -// Code returns the exception type name. -func (s *OAuthProviderException) Code() string { - return "OAuthProviderException" -} -// Message returns the exception's message. -func (s *OAuthProviderException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if invalidParams.Len() > 0 { + return invalidParams } - return "" + return nil } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *OAuthProviderException) OrigErr() error { - return nil +// SetCombineArtifacts sets the CombineArtifacts field's value. +func (s *ProjectBuildBatchConfig) SetCombineArtifacts(v bool) *ProjectBuildBatchConfig { + s.CombineArtifacts = &v + return s } -func (s *OAuthProviderException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +// SetRestrictions sets the Restrictions field's value. +func (s *ProjectBuildBatchConfig) SetRestrictions(v *BatchRestrictions) *ProjectBuildBatchConfig { + s.Restrictions = v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *OAuthProviderException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetServiceRole sets the ServiceRole field's value. +func (s *ProjectBuildBatchConfig) SetServiceRole(v string) *ProjectBuildBatchConfig { + s.ServiceRole = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *OAuthProviderException) RequestID() string { - return s.RespMetadata.RequestID +// SetTimeoutInMins sets the TimeoutInMins field's value. +func (s *ProjectBuildBatchConfig) SetTimeoutInMins(v int64) *ProjectBuildBatchConfig { + s.TimeoutInMins = &v + return s } -// Additional information about a build phase that has an error. You can use -// this information for troubleshooting. -type PhaseContext struct { +// Information about the cache for the build project. +type ProjectCache struct { _ struct{} `type:"structure"` - // An explanation of the build phase's context. This might include a command - // ID and an exit code. - Message *string `locationName:"message" type:"string"` + // Information about the cache location: + // + // * NO_CACHE or LOCAL: This value is ignored. + // + // * S3: This is the S3 bucket name/prefix. + Location *string `locationName:"location" type:"string"` - // The status code for the context of the build phase. - StatusCode *string `locationName:"statusCode" type:"string"` + // If you use a LOCAL cache, the local cache mode. You can use one or more local + // cache modes at the same time. + // + // * LOCAL_SOURCE_CACHE mode caches Git metadata for primary and secondary + // sources. After the cache is created, subsequent builds pull only the change + // between commits. This mode is a good choice for projects with a clean + // working directory and a source that is a large Git repository. If you + // choose this option and your project does not use a Git repository (GitHub, + // GitHub Enterprise, or Bitbucket), the option is ignored. + // + // * LOCAL_DOCKER_LAYER_CACHE mode caches existing Docker layers. This mode + // is a good choice for projects that build or pull large Docker images. + // It can prevent the performance issues caused by pulling large Docker images + // down from the network. You can use a Docker layer cache in the Linux environment + // only. The privileged flag must be set so that your project has the required + // Docker permissions. You should consider the security implications before + // you use a Docker layer cache. + // + // * LOCAL_CUSTOM_CACHE mode caches directories you specify in the buildspec + // file. This mode is a good choice if your build scenario is not suited + // to one of the other three local cache modes. If you use a custom cache: + // Only directories can be specified for caching. You cannot specify individual + // files. Symlinks are used to reference cached directories. Cached directories + // are linked to your build before it downloads its project sources. Cached + // items are overridden if a source item has the same name. Directories are + // specified using cache paths in the buildspec file. + Modes []*string `locationName:"modes" type:"list"` + + // The type of cache used by the build project. Valid values include: + // + // * NO_CACHE: The build project does not use any cache. + // + // * S3: The build project reads and writes from and to S3. + // + // * LOCAL: The build project stores a cache locally on a build host that + // is only available to that build host. + // + // Type is a required field + Type *string `locationName:"type" type:"string" required:"true" enum:"CacheType"` } // String returns the string representation -func (s PhaseContext) String() string { +func (s ProjectCache) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PhaseContext) GoString() string { +func (s ProjectCache) GoString() string { return s.String() } -// SetMessage sets the Message field's value. -func (s *PhaseContext) SetMessage(v string) *PhaseContext { - s.Message = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *ProjectCache) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ProjectCache"} + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetStatusCode sets the StatusCode field's value. -func (s *PhaseContext) SetStatusCode(v string) *PhaseContext { - s.StatusCode = &v +// SetLocation sets the Location field's value. +func (s *ProjectCache) SetLocation(v string) *ProjectCache { + s.Location = &v return s } -// Information about a build project. -type Project struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the build project. - Arn *string `locationName:"arn" type:"string"` - - // Information about the build output artifacts for the build project. - Artifacts *ProjectArtifacts `locationName:"artifacts" type:"structure"` - - // Information about the build badge for the build project. - Badge *ProjectBadge `locationName:"badge" type:"structure"` +// SetModes sets the Modes field's value. +func (s *ProjectCache) SetModes(v []*string) *ProjectCache { + s.Modes = v + return s +} - // Information about the cache for the build project. - Cache *ProjectCache `locationName:"cache" type:"structure"` +// SetType sets the Type field's value. +func (s *ProjectCache) SetType(v string) *ProjectCache { + s.Type = &v + return s +} - // When the build project was created, expressed in Unix time format. - Created *time.Time `locationName:"created" type:"timestamp"` +// Information about the build environment of the build project. +type ProjectEnvironment struct { + _ struct{} `type:"structure"` - // A description that makes the build project easy to identify. - Description *string `locationName:"description" type:"string"` + // The certificate to use with this build project. + Certificate *string `locationName:"certificate" type:"string"` - // The AWS Key Management Service (AWS KMS) customer master key (CMK) to be - // used for encrypting the build output artifacts. + // Information about the compute resources the build project uses. Available + // values include: // - // You can use a cross-account KMS key to encrypt the build output artifacts - // if your service role has permission to that key. + // * BUILD_GENERAL1_SMALL: Use up to 3 GB memory and 2 vCPUs for builds. // - // You can specify either the Amazon Resource Name (ARN) of the CMK or, if available, - // the CMK's alias (using the format alias/alias-name ). - EncryptionKey *string `locationName:"encryptionKey" min:"1" type:"string"` - - // Information about the build environment for this build project. - Environment *ProjectEnvironment `locationName:"environment" type:"structure"` - - // An array of ProjectFileSystemLocation objects for a CodeBuild build project. - // A ProjectFileSystemLocation object specifies the identifier, location, mountOptions, - // mountPoint, and type of a file system created using Amazon Elastic File System. - FileSystemLocations []*ProjectFileSystemLocation `locationName:"fileSystemLocations" type:"list"` - - // When the build project's settings were last modified, expressed in Unix time - // format. - LastModified *time.Time `locationName:"lastModified" type:"timestamp"` - - // Information about logs for the build project. A project can create logs in - // Amazon CloudWatch Logs, an S3 bucket, or both. - LogsConfig *LogsConfig `locationName:"logsConfig" type:"structure"` - - // The name of the build project. - Name *string `locationName:"name" min:"2" type:"string"` - - // The number of minutes a build is allowed to be queued before it times out. - QueuedTimeoutInMinutes *int64 `locationName:"queuedTimeoutInMinutes" min:"5" type:"integer"` - - // An array of ProjectArtifacts objects. - SecondaryArtifacts []*ProjectArtifacts `locationName:"secondaryArtifacts" type:"list"` - - // An array of ProjectSourceVersion objects. If secondarySourceVersions is specified - // at the build level, then they take over these secondarySourceVersions (at - // the project level). - SecondarySourceVersions []*ProjectSourceVersion `locationName:"secondarySourceVersions" type:"list"` + // * BUILD_GENERAL1_MEDIUM: Use up to 7 GB memory and 4 vCPUs for builds. + // + // * BUILD_GENERAL1_LARGE: Use up to 16 GB memory and 8 vCPUs for builds, + // depending on your environment type. + // + // * BUILD_GENERAL1_2XLARGE: Use up to 145 GB memory, 72 vCPUs, and 824 GB + // of SSD storage for builds. This compute type supports Docker images up + // to 100 GB uncompressed. + // + // If you use BUILD_GENERAL1_LARGE: + // + // * For environment type LINUX_CONTAINER, you can use up to 15 GB memory + // and 8 vCPUs for builds. + // + // * For environment type LINUX_GPU_CONTAINER, you can use up to 255 GB memory, + // 32 vCPUs, and 4 NVIDIA Tesla V100 GPUs for builds. + // + // * For environment type ARM_CONTAINER, you can use up to 16 GB memory and + // 8 vCPUs on ARM-based processors for builds. + // + // For more information, see Build Environment Compute Types (https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-compute-types.html) + // in the AWS CodeBuild User Guide. + // + // ComputeType is a required field + ComputeType *string `locationName:"computeType" type:"string" required:"true" enum:"ComputeType"` - // An array of ProjectSource objects. - SecondarySources []*ProjectSource `locationName:"secondarySources" type:"list"` + // A set of environment variables to make available to builds for this build + // project. + EnvironmentVariables []*EnvironmentVariable `locationName:"environmentVariables" type:"list"` - // The ARN of the AWS Identity and Access Management (IAM) role that enables - // AWS CodeBuild to interact with dependent AWS services on behalf of the AWS - // account. - ServiceRole *string `locationName:"serviceRole" min:"1" type:"string"` + // The image tag or image digest that identifies the Docker image to use for + // this build project. Use the following formats: + // + // * For an image tag: registry/repository:tag. For example, to specify an + // image with the tag "latest," use registry/repository:latest. + // + // * For an image digest: registry/repository@digest. For example, to specify + // an image with the digest "sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf," + // use registry/repository@sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf. + // + // Image is a required field + Image *string `locationName:"image" min:"1" type:"string" required:"true"` - // Information about the build input source code for this build project. - Source *ProjectSource `locationName:"source" type:"structure"` + // The type of credentials AWS CodeBuild uses to pull images in your build. + // There are two valid values: + // + // * CODEBUILD specifies that AWS CodeBuild uses its own credentials. This + // requires that you modify your ECR repository policy to trust AWS CodeBuild's + // service principal. + // + // * SERVICE_ROLE specifies that AWS CodeBuild uses your build project's + // service role. + // + // When you use a cross-account or private registry image, you must use SERVICE_ROLE + // credentials. When you use an AWS CodeBuild curated image, you must use CODEBUILD + // credentials. + ImagePullCredentialsType *string `locationName:"imagePullCredentialsType" type:"string" enum:"ImagePullCredentialsType"` - // A version of the build input to be built for this project. If not specified, - // the latest version is used. If specified, it must be one of: + // Enables running the Docker daemon inside a Docker container. Set to true + // only if the build project is used to build Docker images. Otherwise, a build + // that attempts to interact with the Docker daemon fails. The default setting + // is false. // - // * For AWS CodeCommit: the commit ID, branch, or Git tag to use. + // You can initialize the Docker daemon during the install phase of your build + // by adding one of the following sets of commands to the install phase of your + // buildspec file: // - // * For GitHub: the commit ID, pull request ID, branch name, or tag name - // that corresponds to the version of the source code you want to build. - // If a pull request ID is specified, it must use the format pr/pull-request-ID - // (for example pr/25). If a branch name is specified, the branch's HEAD - // commit ID is used. If not specified, the default branch's HEAD commit - // ID is used. + // If the operating system's base image is Ubuntu Linux: // - // * For Bitbucket: the commit ID, branch name, or tag name that corresponds - // to the version of the source code you want to build. If a branch name - // is specified, the branch's HEAD commit ID is used. If not specified, the - // default branch's HEAD commit ID is used. + // - nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://0.0.0.0:2375 + // --storage-driver=overlay& // - // * For Amazon Simple Storage Service (Amazon S3): the version ID of the - // object that represents the build input ZIP file to use. + // - timeout 15 sh -c "until docker info; do echo .; sleep 1; done" // - // If sourceVersion is specified at the build level, then that version takes - // precedence over this sourceVersion (at the project level). + // If the operating system's base image is Alpine Linux and the previous command + // does not work, add the -t argument to timeout: // - // For more information, see Source Version Sample with CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/sample-source-version.html) - // in the AWS CodeBuild User Guide. - SourceVersion *string `locationName:"sourceVersion" type:"string"` - - // The tags for this build project. + // - nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://0.0.0.0:2375 + // --storage-driver=overlay& // - // These tags are available for use by AWS services that support AWS CodeBuild - // build project tags. - Tags []*Tag `locationName:"tags" type:"list"` - - // How long, in minutes, from 5 to 480 (8 hours), for AWS CodeBuild to wait - // before timing out any related build that did not get marked as completed. - // The default is 60 minutes. - TimeoutInMinutes *int64 `locationName:"timeoutInMinutes" min:"5" type:"integer"` + // - timeout -t 15 sh -c "until docker info; do echo .; sleep 1; done" + PrivilegedMode *bool `locationName:"privilegedMode" type:"boolean"` - // Information about the VPC configuration that AWS CodeBuild accesses. - VpcConfig *VpcConfig `locationName:"vpcConfig" type:"structure"` + // The credentials for access to a private registry. + RegistryCredential *RegistryCredential `locationName:"registryCredential" type:"structure"` - // Information about a webhook that connects repository events to a build project - // in AWS CodeBuild. - Webhook *Webhook `locationName:"webhook" type:"structure"` + // The type of build environment to use for related builds. + // + // * The environment type ARM_CONTAINER is available only in regions US East + // (N. Virginia), US East (Ohio), US West (Oregon), EU (Ireland), Asia Pacific + // (Mumbai), Asia Pacific (Tokyo), Asia Pacific (Sydney), and EU (Frankfurt). + // + // * The environment type LINUX_CONTAINER with compute type build.general1.2xlarge + // is available only in regions US East (N. Virginia), US East (Ohio), US + // West (Oregon), Canada (Central), EU (Ireland), EU (London), EU (Frankfurt), + // Asia Pacific (Tokyo), Asia Pacific (Seoul), Asia Pacific (Singapore), + // Asia Pacific (Sydney), China (Beijing), and China (Ningxia). + // + // * The environment type LINUX_GPU_CONTAINER is available only in regions + // US East (N. Virginia), US East (Ohio), US West (Oregon), Canada (Central), + // EU (Ireland), EU (London), EU (Frankfurt), Asia Pacific (Tokyo), Asia + // Pacific (Seoul), Asia Pacific (Singapore), Asia Pacific (Sydney) , China + // (Beijing), and China (Ningxia). + // + // Type is a required field + Type *string `locationName:"type" type:"string" required:"true" enum:"EnvironmentType"` } // String returns the string representation -func (s Project) String() string { +func (s ProjectEnvironment) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Project) GoString() string { +func (s ProjectEnvironment) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *Project) SetArn(v string) *Project { - s.Arn = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *ProjectEnvironment) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ProjectEnvironment"} + if s.ComputeType == nil { + invalidParams.Add(request.NewErrParamRequired("ComputeType")) + } + if s.Image == nil { + invalidParams.Add(request.NewErrParamRequired("Image")) + } + if s.Image != nil && len(*s.Image) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Image", 1)) + } + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + if s.EnvironmentVariables != nil { + for i, v := range s.EnvironmentVariables { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "EnvironmentVariables", i), err.(request.ErrInvalidParams)) + } + } + } + if s.RegistryCredential != nil { + if err := s.RegistryCredential.Validate(); err != nil { + invalidParams.AddNested("RegistryCredential", err.(request.ErrInvalidParams)) + } + } -// SetArtifacts sets the Artifacts field's value. -func (s *Project) SetArtifacts(v *ProjectArtifacts) *Project { - s.Artifacts = v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetBadge sets the Badge field's value. -func (s *Project) SetBadge(v *ProjectBadge) *Project { - s.Badge = v +// SetCertificate sets the Certificate field's value. +func (s *ProjectEnvironment) SetCertificate(v string) *ProjectEnvironment { + s.Certificate = &v return s } -// SetCache sets the Cache field's value. -func (s *Project) SetCache(v *ProjectCache) *Project { - s.Cache = v +// SetComputeType sets the ComputeType field's value. +func (s *ProjectEnvironment) SetComputeType(v string) *ProjectEnvironment { + s.ComputeType = &v return s } -// SetCreated sets the Created field's value. -func (s *Project) SetCreated(v time.Time) *Project { - s.Created = &v +// SetEnvironmentVariables sets the EnvironmentVariables field's value. +func (s *ProjectEnvironment) SetEnvironmentVariables(v []*EnvironmentVariable) *ProjectEnvironment { + s.EnvironmentVariables = v return s } -// SetDescription sets the Description field's value. -func (s *Project) SetDescription(v string) *Project { - s.Description = &v +// SetImage sets the Image field's value. +func (s *ProjectEnvironment) SetImage(v string) *ProjectEnvironment { + s.Image = &v return s } -// SetEncryptionKey sets the EncryptionKey field's value. -func (s *Project) SetEncryptionKey(v string) *Project { - s.EncryptionKey = &v +// SetImagePullCredentialsType sets the ImagePullCredentialsType field's value. +func (s *ProjectEnvironment) SetImagePullCredentialsType(v string) *ProjectEnvironment { + s.ImagePullCredentialsType = &v return s } -// SetEnvironment sets the Environment field's value. -func (s *Project) SetEnvironment(v *ProjectEnvironment) *Project { - s.Environment = v +// SetPrivilegedMode sets the PrivilegedMode field's value. +func (s *ProjectEnvironment) SetPrivilegedMode(v bool) *ProjectEnvironment { + s.PrivilegedMode = &v return s } -// SetFileSystemLocations sets the FileSystemLocations field's value. -func (s *Project) SetFileSystemLocations(v []*ProjectFileSystemLocation) *Project { - s.FileSystemLocations = v +// SetRegistryCredential sets the RegistryCredential field's value. +func (s *ProjectEnvironment) SetRegistryCredential(v *RegistryCredential) *ProjectEnvironment { + s.RegistryCredential = v return s } -// SetLastModified sets the LastModified field's value. -func (s *Project) SetLastModified(v time.Time) *Project { - s.LastModified = &v +// SetType sets the Type field's value. +func (s *ProjectEnvironment) SetType(v string) *ProjectEnvironment { + s.Type = &v return s } -// SetLogsConfig sets the LogsConfig field's value. -func (s *Project) SetLogsConfig(v *LogsConfig) *Project { - s.LogsConfig = v - return s -} +// Information about a file system created by Amazon Elastic File System (EFS). +// For more information, see What Is Amazon Elastic File System? (https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html) +type ProjectFileSystemLocation struct { + _ struct{} `type:"structure"` -// SetName sets the Name field's value. -func (s *Project) SetName(v string) *Project { - s.Name = &v - return s -} + // The name used to access a file system created by Amazon EFS. CodeBuild creates + // an environment variable by appending the identifier in all capital letters + // to CODEBUILD_. For example, if you specify my-efs for identifier, a new environment + // variable is create named CODEBUILD_MY-EFS. + // + // The identifier is used to mount your file system. + Identifier *string `locationName:"identifier" type:"string"` -// SetQueuedTimeoutInMinutes sets the QueuedTimeoutInMinutes field's value. -func (s *Project) SetQueuedTimeoutInMinutes(v int64) *Project { - s.QueuedTimeoutInMinutes = &v - return s -} + // A string that specifies the location of the file system created by Amazon + // EFS. Its format is efs-dns-name:/directory-path. You can find the DNS name + // of file system when you view it in the AWS EFS console. The directory path + // is a path to a directory in the file system that CodeBuild mounts. For example, + // if the DNS name of a file system is fs-abcd1234.efs.us-west-2.amazonaws.com, + // and its mount directory is my-efs-mount-directory, then the location is fs-abcd1234.efs.us-west-2.amazonaws.com:/my-efs-mount-directory. + // + // The directory path in the format efs-dns-name:/directory-path is optional. + // If you do not specify a directory path, the location is only the DNS name + // and CodeBuild mounts the entire file system. + Location *string `locationName:"location" type:"string"` -// SetSecondaryArtifacts sets the SecondaryArtifacts field's value. -func (s *Project) SetSecondaryArtifacts(v []*ProjectArtifacts) *Project { - s.SecondaryArtifacts = v - return s -} + // The mount options for a file system created by AWS EFS. The default mount + // options used by CodeBuild are nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2. + // For more information, see Recommended NFS Mount Options (https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-nfs-mount-settings.html). + MountOptions *string `locationName:"mountOptions" type:"string"` -// SetSecondarySourceVersions sets the SecondarySourceVersions field's value. -func (s *Project) SetSecondarySourceVersions(v []*ProjectSourceVersion) *Project { - s.SecondarySourceVersions = v - return s -} + // The location in the container where you mount the file system. + MountPoint *string `locationName:"mountPoint" type:"string"` -// SetSecondarySources sets the SecondarySources field's value. -func (s *Project) SetSecondarySources(v []*ProjectSource) *Project { - s.SecondarySources = v - return s + // The type of the file system. The one supported type is EFS. + Type *string `locationName:"type" type:"string" enum:"FileSystemType"` } -// SetServiceRole sets the ServiceRole field's value. -func (s *Project) SetServiceRole(v string) *Project { - s.ServiceRole = &v - return s +// String returns the string representation +func (s ProjectFileSystemLocation) String() string { + return awsutil.Prettify(s) } -// SetSource sets the Source field's value. -func (s *Project) SetSource(v *ProjectSource) *Project { - s.Source = v - return s +// GoString returns the string representation +func (s ProjectFileSystemLocation) GoString() string { + return s.String() } -// SetSourceVersion sets the SourceVersion field's value. -func (s *Project) SetSourceVersion(v string) *Project { - s.SourceVersion = &v +// SetIdentifier sets the Identifier field's value. +func (s *ProjectFileSystemLocation) SetIdentifier(v string) *ProjectFileSystemLocation { + s.Identifier = &v return s } -// SetTags sets the Tags field's value. -func (s *Project) SetTags(v []*Tag) *Project { - s.Tags = v +// SetLocation sets the Location field's value. +func (s *ProjectFileSystemLocation) SetLocation(v string) *ProjectFileSystemLocation { + s.Location = &v return s } -// SetTimeoutInMinutes sets the TimeoutInMinutes field's value. -func (s *Project) SetTimeoutInMinutes(v int64) *Project { - s.TimeoutInMinutes = &v +// SetMountOptions sets the MountOptions field's value. +func (s *ProjectFileSystemLocation) SetMountOptions(v string) *ProjectFileSystemLocation { + s.MountOptions = &v return s } -// SetVpcConfig sets the VpcConfig field's value. -func (s *Project) SetVpcConfig(v *VpcConfig) *Project { - s.VpcConfig = v +// SetMountPoint sets the MountPoint field's value. +func (s *ProjectFileSystemLocation) SetMountPoint(v string) *ProjectFileSystemLocation { + s.MountPoint = &v return s } -// SetWebhook sets the Webhook field's value. -func (s *Project) SetWebhook(v *Webhook) *Project { - s.Webhook = v +// SetType sets the Type field's value. +func (s *ProjectFileSystemLocation) SetType(v string) *ProjectFileSystemLocation { + s.Type = &v return s } -// Information about the build output artifacts for the build project. -type ProjectArtifacts struct { +// Information about the build input source code for the build project. +type ProjectSource struct { _ struct{} `type:"structure"` - // An identifier for this artifact definition. - ArtifactIdentifier *string `locationName:"artifactIdentifier" type:"string"` + // Information about the authorization settings for AWS CodeBuild to access + // the source code to be built. + // + // This information is for the AWS CodeBuild console's use only. Your code should + // not get or set this information directly. + Auth *SourceAuth `locationName:"auth" type:"structure"` - // Set to true if you do not want your output artifacts encrypted. This option - // is valid only if your artifacts type is Amazon Simple Storage Service (Amazon - // S3). If this is set with another artifacts type, an invalidInputException - // is thrown. - EncryptionDisabled *bool `locationName:"encryptionDisabled" type:"boolean"` + // Contains information that defines how the build project reports the build + // status to the source provider. This option is only used when the source provider + // is GITHUB, GITHUB_ENTERPRISE, or BITBUCKET. + BuildStatusConfig *BuildStatusConfig `locationName:"buildStatusConfig" type:"structure"` - // Information about the build output artifact location: - // - // * If type is set to CODEPIPELINE, AWS CodePipeline ignores this value - // if specified. This is because AWS CodePipeline manages its build output - // locations instead of AWS CodeBuild. - // - // * If type is set to NO_ARTIFACTS, this value is ignored if specified, - // because no build output is produced. + // The buildspec file declaration to use for the builds in this build project. // - // * If type is set to S3, this is the name of the output bucket. - Location *string `locationName:"location" type:"string"` + // If this value is set, it can be either an inline buildspec definition, the + // path to an alternate buildspec file relative to the value of the built-in + // CODEBUILD_SRC_DIR environment variable, or the path to an S3 bucket. The + // bucket must be in the same AWS Region as the build project. Specify the buildspec + // file using its ARN (for example, arn:aws:s3:::my-codebuild-sample2/buildspec.yml). + // If this value is not provided or is set to an empty string, the source code + // must contain a buildspec file in its root directory. For more information, + // see Buildspec File Name and Storage Location (https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec-ref-name-storage). + Buildspec *string `locationName:"buildspec" type:"string"` - // Along with path and namespaceType, the pattern that AWS CodeBuild uses to - // name and store the output artifact: - // - // * If type is set to CODEPIPELINE, AWS CodePipeline ignores this value - // if specified. This is because AWS CodePipeline manages its build output - // names instead of AWS CodeBuild. - // - // * If type is set to NO_ARTIFACTS, this value is ignored if specified, - // because no build output is produced. - // - // * If type is set to S3, this is the name of the output artifact object. - // If you set the name to be a forward slash ("/"), the artifact is stored - // in the root of the output bucket. - // - // For example: - // - // * If path is set to MyArtifacts, namespaceType is set to BUILD_ID, and - // name is set to MyArtifact.zip, then the output artifact is stored in MyArtifacts/build-ID/MyArtifact.zip. - // - // * If path is empty, namespaceType is set to NONE, and name is set to "/", - // the output artifact is stored in the root of the output bucket. - // - // * If path is set to MyArtifacts, namespaceType is set to BUILD_ID, and - // name is set to "/", the output artifact is stored in MyArtifacts/build-ID . - Name *string `locationName:"name" type:"string"` + // Information about the Git clone depth for the build project. + GitCloneDepth *int64 `locationName:"gitCloneDepth" type:"integer"` - // Along with path and name, the pattern that AWS CodeBuild uses to determine - // the name and location to store the output artifact: - // - // * If type is set to CODEPIPELINE, AWS CodePipeline ignores this value - // if specified. This is because AWS CodePipeline manages its build output - // names instead of AWS CodeBuild. + // Information about the Git submodules configuration for the build project. + GitSubmodulesConfig *GitSubmodulesConfig `locationName:"gitSubmodulesConfig" type:"structure"` + + // Enable this flag to ignore SSL warnings while connecting to the project source + // code. + InsecureSsl *bool `locationName:"insecureSsl" type:"boolean"` + + // Information about the location of the source code to be built. Valid values + // include: // - // * If type is set to NO_ARTIFACTS, this value is ignored if specified, - // because no build output is produced. + // * For source code settings that are specified in the source action of + // a pipeline in AWS CodePipeline, location should not be specified. If it + // is specified, AWS CodePipeline ignores it. This is because AWS CodePipeline + // uses the settings in a pipeline's source action instead of this value. // - // * If type is set to S3, valid values include: BUILD_ID: Include the build - // ID in the location of the build output artifact. NONE: Do not include - // the build ID. This is the default if namespaceType is not specified. + // * For source code in an AWS CodeCommit repository, the HTTPS clone URL + // to the repository that contains the source code and the buildspec file + // (for example, https://git-codecommit.region-ID.amazonaws.com/v1/repos/repo-name + // ). // - // For example, if path is set to MyArtifacts, namespaceType is set to BUILD_ID, - // and name is set to MyArtifact.zip, the output artifact is stored in MyArtifacts/build-ID/MyArtifact.zip. - NamespaceType *string `locationName:"namespaceType" type:"string" enum:"ArtifactNamespace"` - - // If this flag is set, a name specified in the buildspec file overrides the - // artifact name. The name specified in a buildspec file is calculated at build - // time and uses the Shell Command Language. For example, you can append a date - // and time to your artifact name so that it is always unique. - OverrideArtifactName *bool `locationName:"overrideArtifactName" type:"boolean"` - - // The type of build output artifact to create: + // * For source code in an Amazon Simple Storage Service (Amazon S3) input + // bucket, one of the following. The path to the ZIP file that contains the + // source code (for example, bucket-name/path/to/object-name.zip). The path + // to the folder that contains the source code (for example, bucket-name/path/to/source-code/folder/). // - // * If type is set to CODEPIPELINE, AWS CodePipeline ignores this value - // if specified. This is because AWS CodePipeline manages its build output - // artifacts instead of AWS CodeBuild. + // * For source code in a GitHub repository, the HTTPS clone URL to the repository + // that contains the source and the buildspec file. You must connect your + // AWS account to your GitHub account. Use the AWS CodeBuild console to start + // creating a build project. When you use the console to connect (or reconnect) + // with GitHub, on the GitHub Authorize application page, for Organization + // access, choose Request access next to each repository you want to allow + // AWS CodeBuild to have access to, and then choose Authorize application. + // (After you have connected to your GitHub account, you do not need to finish + // creating the build project. You can leave the AWS CodeBuild console.) + // To instruct AWS CodeBuild to use this connection, in the source object, + // set the auth object's type value to OAUTH. // - // * If type is set to NO_ARTIFACTS, this value is ignored if specified, - // because no build output is produced. + // * For source code in a Bitbucket repository, the HTTPS clone URL to the + // repository that contains the source and the buildspec file. You must connect + // your AWS account to your Bitbucket account. Use the AWS CodeBuild console + // to start creating a build project. When you use the console to connect + // (or reconnect) with Bitbucket, on the Bitbucket Confirm access to your + // account page, choose Grant access. (After you have connected to your Bitbucket + // account, you do not need to finish creating the build project. You can + // leave the AWS CodeBuild console.) To instruct AWS CodeBuild to use this + // connection, in the source object, set the auth object's type value to + // OAUTH. + Location *string `locationName:"location" type:"string"` + + // Set to true to report the status of a build's start and finish to your source + // provider. This option is valid only when your source provider is GitHub, + // GitHub Enterprise, or Bitbucket. If this is set and you use a different source + // provider, an invalidInputException is thrown. // - // * If type is set to S3, valid values include: NONE: AWS CodeBuild creates - // in the output bucket a folder that contains the build output. This is - // the default if packaging is not specified. ZIP: AWS CodeBuild creates - // in the output bucket a ZIP file that contains the build output. - Packaging *string `locationName:"packaging" type:"string" enum:"ArtifactPackaging"` + // The status of a build triggered by a webhook is always reported to your source + // provider. + ReportBuildStatus *bool `locationName:"reportBuildStatus" type:"boolean"` - // Along with namespaceType and name, the pattern that AWS CodeBuild uses to - // name and store the output artifact: + // An identifier for this project source. + SourceIdentifier *string `locationName:"sourceIdentifier" type:"string"` + + // The type of repository that contains the source code to be built. Valid values + // include: // - // * If type is set to CODEPIPELINE, AWS CodePipeline ignores this value - // if specified. This is because AWS CodePipeline manages its build output - // names instead of AWS CodeBuild. + // * BITBUCKET: The source code is in a Bitbucket repository. // - // * If type is set to NO_ARTIFACTS, this value is ignored if specified, - // because no build output is produced. + // * CODECOMMIT: The source code is in an AWS CodeCommit repository. // - // * If type is set to S3, this is the path to the output artifact. If path - // is not specified, path is not used. + // * CODEPIPELINE: The source code settings are specified in the source action + // of a pipeline in AWS CodePipeline. // - // For example, if path is set to MyArtifacts, namespaceType is set to NONE, - // and name is set to MyArtifact.zip, the output artifact is stored in the output - // bucket at MyArtifacts/MyArtifact.zip. - Path *string `locationName:"path" type:"string"` - - // The type of build output artifact. Valid values include: + // * GITHUB: The source code is in a GitHub or GitHub Enterprise Cloud repository. // - // * CODEPIPELINE: The build project has build output generated through AWS - // CodePipeline. The CODEPIPELINE type is not supported for secondaryArtifacts. + // * GITHUB_ENTERPRISE: The source code is in a GitHub Enterprise Server + // repository. // - // * NO_ARTIFACTS: The build project does not produce any build output. + // * NO_SOURCE: The project does not have input source code. // - // * S3: The build project stores build output in Amazon Simple Storage Service - // (Amazon S3). + // * S3: The source code is in an Amazon Simple Storage Service (Amazon S3) + // input bucket. // // Type is a required field - Type *string `locationName:"type" type:"string" required:"true" enum:"ArtifactsType"` + Type *string `locationName:"type" type:"string" required:"true" enum:"SourceType"` } // String returns the string representation -func (s ProjectArtifacts) String() string { +func (s ProjectSource) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ProjectArtifacts) GoString() string { +func (s ProjectSource) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ProjectArtifacts) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ProjectArtifacts"} +func (s *ProjectSource) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ProjectSource"} if s.Type == nil { invalidParams.Add(request.NewErrParamRequired("Type")) } + if s.Auth != nil { + if err := s.Auth.Validate(); err != nil { + invalidParams.AddNested("Auth", err.(request.ErrInvalidParams)) + } + } + if s.GitSubmodulesConfig != nil { + if err := s.GitSubmodulesConfig.Validate(); err != nil { + invalidParams.AddNested("GitSubmodulesConfig", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -7089,165 +10762,182 @@ func (s *ProjectArtifacts) Validate() error { return nil } -// SetArtifactIdentifier sets the ArtifactIdentifier field's value. -func (s *ProjectArtifacts) SetArtifactIdentifier(v string) *ProjectArtifacts { - s.ArtifactIdentifier = &v +// SetAuth sets the Auth field's value. +func (s *ProjectSource) SetAuth(v *SourceAuth) *ProjectSource { + s.Auth = v return s } -// SetEncryptionDisabled sets the EncryptionDisabled field's value. -func (s *ProjectArtifacts) SetEncryptionDisabled(v bool) *ProjectArtifacts { - s.EncryptionDisabled = &v +// SetBuildStatusConfig sets the BuildStatusConfig field's value. +func (s *ProjectSource) SetBuildStatusConfig(v *BuildStatusConfig) *ProjectSource { + s.BuildStatusConfig = v return s } -// SetLocation sets the Location field's value. -func (s *ProjectArtifacts) SetLocation(v string) *ProjectArtifacts { - s.Location = &v +// SetBuildspec sets the Buildspec field's value. +func (s *ProjectSource) SetBuildspec(v string) *ProjectSource { + s.Buildspec = &v return s } -// SetName sets the Name field's value. -func (s *ProjectArtifacts) SetName(v string) *ProjectArtifacts { - s.Name = &v +// SetGitCloneDepth sets the GitCloneDepth field's value. +func (s *ProjectSource) SetGitCloneDepth(v int64) *ProjectSource { + s.GitCloneDepth = &v return s } -// SetNamespaceType sets the NamespaceType field's value. -func (s *ProjectArtifacts) SetNamespaceType(v string) *ProjectArtifacts { - s.NamespaceType = &v +// SetGitSubmodulesConfig sets the GitSubmodulesConfig field's value. +func (s *ProjectSource) SetGitSubmodulesConfig(v *GitSubmodulesConfig) *ProjectSource { + s.GitSubmodulesConfig = v return s } -// SetOverrideArtifactName sets the OverrideArtifactName field's value. -func (s *ProjectArtifacts) SetOverrideArtifactName(v bool) *ProjectArtifacts { - s.OverrideArtifactName = &v +// SetInsecureSsl sets the InsecureSsl field's value. +func (s *ProjectSource) SetInsecureSsl(v bool) *ProjectSource { + s.InsecureSsl = &v return s } -// SetPackaging sets the Packaging field's value. -func (s *ProjectArtifacts) SetPackaging(v string) *ProjectArtifacts { - s.Packaging = &v +// SetLocation sets the Location field's value. +func (s *ProjectSource) SetLocation(v string) *ProjectSource { + s.Location = &v return s } -// SetPath sets the Path field's value. -func (s *ProjectArtifacts) SetPath(v string) *ProjectArtifacts { - s.Path = &v +// SetReportBuildStatus sets the ReportBuildStatus field's value. +func (s *ProjectSource) SetReportBuildStatus(v bool) *ProjectSource { + s.ReportBuildStatus = &v + return s +} + +// SetSourceIdentifier sets the SourceIdentifier field's value. +func (s *ProjectSource) SetSourceIdentifier(v string) *ProjectSource { + s.SourceIdentifier = &v return s } // SetType sets the Type field's value. -func (s *ProjectArtifacts) SetType(v string) *ProjectArtifacts { +func (s *ProjectSource) SetType(v string) *ProjectSource { s.Type = &v return s } -// Information about the build badge for the build project. -type ProjectBadge struct { +// A source identifier and its corresponding version. +type ProjectSourceVersion struct { _ struct{} `type:"structure"` - // Set this to true to generate a publicly accessible URL for your project's - // build badge. - BadgeEnabled *bool `locationName:"badgeEnabled" type:"boolean"` + // An identifier for a source in the build project. + // + // SourceIdentifier is a required field + SourceIdentifier *string `locationName:"sourceIdentifier" type:"string" required:"true"` - // The publicly-accessible URL through which you can access the build badge - // for your project. + // The source version for the corresponding source identifier. If specified, + // must be one of: // - // The publicly accessible URL through which you can access the build badge - // for your project. - BadgeRequestUrl *string `locationName:"badgeRequestUrl" type:"string"` + // * For AWS CodeCommit: the commit ID, branch, or Git tag to use. + // + // * For GitHub: the commit ID, pull request ID, branch name, or tag name + // that corresponds to the version of the source code you want to build. + // If a pull request ID is specified, it must use the format pr/pull-request-ID + // (for example, pr/25). If a branch name is specified, the branch's HEAD + // commit ID is used. If not specified, the default branch's HEAD commit + // ID is used. + // + // * For Bitbucket: the commit ID, branch name, or tag name that corresponds + // to the version of the source code you want to build. If a branch name + // is specified, the branch's HEAD commit ID is used. If not specified, the + // default branch's HEAD commit ID is used. + // + // * For Amazon Simple Storage Service (Amazon S3): the version ID of the + // object that represents the build input ZIP file to use. + // + // For more information, see Source Version Sample with CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/sample-source-version.html) + // in the AWS CodeBuild User Guide. + // + // SourceVersion is a required field + SourceVersion *string `locationName:"sourceVersion" type:"string" required:"true"` } // String returns the string representation -func (s ProjectBadge) String() string { +func (s ProjectSourceVersion) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ProjectBadge) GoString() string { +func (s ProjectSourceVersion) GoString() string { return s.String() } -// SetBadgeEnabled sets the BadgeEnabled field's value. -func (s *ProjectBadge) SetBadgeEnabled(v bool) *ProjectBadge { - s.BadgeEnabled = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *ProjectSourceVersion) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ProjectSourceVersion"} + if s.SourceIdentifier == nil { + invalidParams.Add(request.NewErrParamRequired("SourceIdentifier")) + } + if s.SourceVersion == nil { + invalidParams.Add(request.NewErrParamRequired("SourceVersion")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetBadgeRequestUrl sets the BadgeRequestUrl field's value. -func (s *ProjectBadge) SetBadgeRequestUrl(v string) *ProjectBadge { - s.BadgeRequestUrl = &v +// SetSourceIdentifier sets the SourceIdentifier field's value. +func (s *ProjectSourceVersion) SetSourceIdentifier(v string) *ProjectSourceVersion { + s.SourceIdentifier = &v return s } -// Information about the cache for the build project. -type ProjectCache struct { - _ struct{} `type:"structure"` +// SetSourceVersion sets the SourceVersion field's value. +func (s *ProjectSourceVersion) SetSourceVersion(v string) *ProjectSourceVersion { + s.SourceVersion = &v + return s +} - // Information about the cache location: - // - // * NO_CACHE or LOCAL: This value is ignored. - // - // * S3: This is the S3 bucket name/prefix. - Location *string `locationName:"location" type:"string"` +type PutResourcePolicyInput struct { + _ struct{} `type:"structure"` - // If you use a LOCAL cache, the local cache mode. You can use one or more local - // cache modes at the same time. - // - // * LOCAL_SOURCE_CACHE mode caches Git metadata for primary and secondary - // sources. After the cache is created, subsequent builds pull only the change - // between commits. This mode is a good choice for projects with a clean - // working directory and a source that is a large Git repository. If you - // choose this option and your project does not use a Git repository (GitHub, - // GitHub Enterprise, or Bitbucket), the option is ignored. - // - // * LOCAL_DOCKER_LAYER_CACHE mode caches existing Docker layers. This mode - // is a good choice for projects that build or pull large Docker images. - // It can prevent the performance issues caused by pulling large Docker images - // down from the network. You can use a Docker layer cache in the Linux environment - // only. The privileged flag must be set so that your project has the required - // Docker permissions. You should consider the security implications before - // you use a Docker layer cache. + // A JSON-formatted resource policy. For more information, see Sharing a Project + // (https://docs.aws.amazon.com/codebuild/latest/userguide/project-sharing.html#project-sharing-share) + // and Sharing a Report Group (https://docs.aws.amazon.com/codebuild/latest/userguide/report-groups-sharing.html#report-groups-sharing-share) + // in the AWS CodeBuild User Guide. // - // * LOCAL_CUSTOM_CACHE mode caches directories you specify in the buildspec - // file. This mode is a good choice if your build scenario is not suited - // to one of the other three local cache modes. If you use a custom cache: - // Only directories can be specified for caching. You cannot specify individual - // files. Symlinks are used to reference cached directories. Cached directories - // are linked to your build before it downloads its project sources. Cached - // items are overridden if a source item has the same name. Directories are - // specified using cache paths in the buildspec file. - Modes []*string `locationName:"modes" type:"list"` + // Policy is a required field + Policy *string `locationName:"policy" min:"1" type:"string" required:"true"` - // The type of cache used by the build project. Valid values include: - // - // * NO_CACHE: The build project does not use any cache. - // - // * S3: The build project reads and writes from and to S3. - // - // * LOCAL: The build project stores a cache locally on a build host that - // is only available to that build host. + // The ARN of the Project or ReportGroup resource you want to associate with + // a resource policy. // - // Type is a required field - Type *string `locationName:"type" type:"string" required:"true" enum:"CacheType"` + // ResourceArn is a required field + ResourceArn *string `locationName:"resourceArn" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s ProjectCache) String() string { +func (s PutResourcePolicyInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ProjectCache) GoString() string { +func (s PutResourcePolicyInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ProjectCache) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ProjectCache"} - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) +func (s *PutResourcePolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutResourcePolicyInput"} + if s.Policy == nil { + invalidParams.Add(request.NewErrParamRequired("Policy")) + } + if s.Policy != nil && len(*s.Policy) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) + } + 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 { @@ -7256,183 +10946,91 @@ func (s *ProjectCache) Validate() error { return nil } -// SetLocation sets the Location field's value. -func (s *ProjectCache) SetLocation(v string) *ProjectCache { - s.Location = &v - return s -} - -// SetModes sets the Modes field's value. -func (s *ProjectCache) SetModes(v []*string) *ProjectCache { - s.Modes = v +// SetPolicy sets the Policy field's value. +func (s *PutResourcePolicyInput) SetPolicy(v string) *PutResourcePolicyInput { + s.Policy = &v return s } -// SetType sets the Type field's value. -func (s *ProjectCache) SetType(v string) *ProjectCache { - s.Type = &v +// SetResourceArn sets the ResourceArn field's value. +func (s *PutResourcePolicyInput) SetResourceArn(v string) *PutResourcePolicyInput { + s.ResourceArn = &v return s } -// Information about the build environment of the build project. -type ProjectEnvironment struct { +type PutResourcePolicyOutput struct { _ struct{} `type:"structure"` - // The certificate to use with this build project. - Certificate *string `locationName:"certificate" type:"string"` + // The ARN of the Project or ReportGroup resource that is associated with a + // resource policy. + ResourceArn *string `locationName:"resourceArn" min:"1" type:"string"` +} - // Information about the compute resources the build project uses. Available - // values include: - // - // * BUILD_GENERAL1_SMALL: Use up to 3 GB memory and 2 vCPUs for builds. - // - // * BUILD_GENERAL1_MEDIUM: Use up to 7 GB memory and 4 vCPUs for builds. - // - // * BUILD_GENERAL1_LARGE: Use up to 16 GB memory and 8 vCPUs for builds, - // depending on your environment type. - // - // * BUILD_GENERAL1_2XLARGE: Use up to 145 GB memory, 72 vCPUs, and 824 GB - // of SSD storage for builds. This compute type supports Docker images up - // to 100 GB uncompressed. - // - // If you use BUILD_GENERAL1_LARGE: - // - // * For environment type LINUX_CONTAINER, you can use up to 15 GB memory - // and 8 vCPUs for builds. - // - // * For environment type LINUX_GPU_CONTAINER, you can use up to 255 GB memory, - // 32 vCPUs, and 4 NVIDIA Tesla V100 GPUs for builds. - // - // * For environment type ARM_CONTAINER, you can use up to 16 GB memory and - // 8 vCPUs on ARM-based processors for builds. - // - // For more information, see Build Environment Compute Types (https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-compute-types.html) - // in the AWS CodeBuild User Guide. - // - // ComputeType is a required field - ComputeType *string `locationName:"computeType" type:"string" required:"true" enum:"ComputeType"` +// String returns the string representation +func (s PutResourcePolicyOutput) String() string { + return awsutil.Prettify(s) +} - // A set of environment variables to make available to builds for this build - // project. - EnvironmentVariables []*EnvironmentVariable `locationName:"environmentVariables" type:"list"` +// GoString returns the string representation +func (s PutResourcePolicyOutput) GoString() string { + return s.String() +} - // The image tag or image digest that identifies the Docker image to use for - // this build project. Use the following formats: - // - // * For an image tag: registry/repository:tag. For example, to specify an - // image with the tag "latest," use registry/repository:latest. - // - // * For an image digest: registry/repository@digest. For example, to specify - // an image with the digest "sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf," - // use registry/repository@sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf. - // - // Image is a required field - Image *string `locationName:"image" min:"1" type:"string" required:"true"` +// SetResourceArn sets the ResourceArn field's value. +func (s *PutResourcePolicyOutput) SetResourceArn(v string) *PutResourcePolicyOutput { + s.ResourceArn = &v + return s +} - // The type of credentials AWS CodeBuild uses to pull images in your build. - // There are two valid values: - // - // * CODEBUILD specifies that AWS CodeBuild uses its own credentials. This - // requires that you modify your ECR repository policy to trust AWS CodeBuild's - // service principal. - // - // * SERVICE_ROLE specifies that AWS CodeBuild uses your build project's - // service role. - // - // When you use a cross-account or private registry image, you must use SERVICE_ROLE - // credentials. When you use an AWS CodeBuild curated image, you must use CODEBUILD - // credentials. - ImagePullCredentialsType *string `locationName:"imagePullCredentialsType" type:"string" enum:"ImagePullCredentialsType"` +// Information about credentials that provide access to a private Docker registry. +// When this is set: +// +// * imagePullCredentialsType must be set to SERVICE_ROLE. +// +// * images cannot be curated or an Amazon ECR image. +// +// For more information, see Private Registry with AWS Secrets Manager Sample +// for AWS CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/sample-private-registry.html). +type RegistryCredential struct { + _ struct{} `type:"structure"` - // Enables running the Docker daemon inside a Docker container. Set to true - // only if the build project is used to build Docker images. Otherwise, a build - // that attempts to interact with the Docker daemon fails. The default setting - // is false. - // - // You can initialize the Docker daemon during the install phase of your build - // by adding one of the following sets of commands to the install phase of your - // buildspec file: - // - // If the operating system's base image is Ubuntu Linux: - // - // - nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://0.0.0.0:2375 - // --storage-driver=overlay& - // - // - timeout 15 sh -c "until docker info; do echo .; sleep 1; done" - // - // If the operating system's base image is Alpine Linux and the previous command - // does not work, add the -t argument to timeout: + // The Amazon Resource Name (ARN) or name of credentials created using AWS Secrets + // Manager. // - // - nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://0.0.0.0:2375 - // --storage-driver=overlay& + // The credential can use the name of the credentials only if they exist in + // your current AWS Region. // - // - timeout -t 15 sh -c "until docker info; do echo .; sleep 1; done" - PrivilegedMode *bool `locationName:"privilegedMode" type:"boolean"` - - // The credentials for access to a private registry. - RegistryCredential *RegistryCredential `locationName:"registryCredential" type:"structure"` + // Credential is a required field + Credential *string `locationName:"credential" min:"1" type:"string" required:"true"` - // The type of build environment to use for related builds. - // - // * The environment type ARM_CONTAINER is available only in regions US East - // (N. Virginia), US East (Ohio), US West (Oregon), EU (Ireland), Asia Pacific - // (Mumbai), Asia Pacific (Tokyo), Asia Pacific (Sydney), and EU (Frankfurt). - // - // * The environment type LINUX_CONTAINER with compute type build.general1.2xlarge - // is available only in regions US East (N. Virginia), US East (N. Virginia), - // US West (Oregon), Canada (Central), EU (Ireland), EU (London), EU (Frankfurt), - // Asia Pacific (Tokyo), Asia Pacific (Seoul), Asia Pacific (Singapore), - // Asia Pacific (Sydney), China (Beijing), and China (Ningxia). - // - // * The environment type LINUX_GPU_CONTAINER is available only in regions - // US East (N. Virginia), US East (N. Virginia), US West (Oregon), Canada - // (Central), EU (Ireland), EU (London), EU (Frankfurt), Asia Pacific (Tokyo), - // Asia Pacific (Seoul), Asia Pacific (Singapore), Asia Pacific (Sydney) - // , China (Beijing), and China (Ningxia). + // The service that created the credentials to access a private Docker registry. + // The valid value, SECRETS_MANAGER, is for AWS Secrets Manager. // - // Type is a required field - Type *string `locationName:"type" type:"string" required:"true" enum:"EnvironmentType"` + // CredentialProvider is a required field + CredentialProvider *string `locationName:"credentialProvider" type:"string" required:"true" enum:"CredentialProviderType"` } // String returns the string representation -func (s ProjectEnvironment) String() string { +func (s RegistryCredential) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ProjectEnvironment) GoString() string { +func (s RegistryCredential) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ProjectEnvironment) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ProjectEnvironment"} - if s.ComputeType == nil { - invalidParams.Add(request.NewErrParamRequired("ComputeType")) - } - if s.Image == nil { - invalidParams.Add(request.NewErrParamRequired("Image")) - } - if s.Image != nil && len(*s.Image) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Image", 1)) - } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - if s.EnvironmentVariables != nil { - for i, v := range s.EnvironmentVariables { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "EnvironmentVariables", i), err.(request.ErrInvalidParams)) - } - } +func (s *RegistryCredential) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RegistryCredential"} + if s.Credential == nil { + invalidParams.Add(request.NewErrParamRequired("Credential")) } - if s.RegistryCredential != nil { - if err := s.RegistryCredential.Validate(); err != nil { - invalidParams.AddNested("RegistryCredential", err.(request.ErrInvalidParams)) - } + if s.Credential != nil && len(*s.Credential) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Credential", 1)) + } + if s.CredentialProvider == nil { + invalidParams.Add(request.NewErrParamRequired("CredentialProvider")) } if invalidParams.Len() > 0 { @@ -7441,265 +11039,188 @@ func (s *ProjectEnvironment) Validate() error { return nil } -// SetCertificate sets the Certificate field's value. -func (s *ProjectEnvironment) SetCertificate(v string) *ProjectEnvironment { - s.Certificate = &v +// SetCredential sets the Credential field's value. +func (s *RegistryCredential) SetCredential(v string) *RegistryCredential { + s.Credential = &v return s } -// SetComputeType sets the ComputeType field's value. -func (s *ProjectEnvironment) SetComputeType(v string) *ProjectEnvironment { - s.ComputeType = &v +// SetCredentialProvider sets the CredentialProvider field's value. +func (s *RegistryCredential) SetCredentialProvider(v string) *RegistryCredential { + s.CredentialProvider = &v return s } -// SetEnvironmentVariables sets the EnvironmentVariables field's value. -func (s *ProjectEnvironment) SetEnvironmentVariables(v []*EnvironmentVariable) *ProjectEnvironment { - s.EnvironmentVariables = v - return s -} +// Information about the results from running a series of test cases during +// the run of a build project. The test cases are specified in the buildspec +// for the build project using one or more paths to the test case files. You +// can specify any type of tests you want, such as unit tests, integration tests, +// and functional tests. +type Report struct { + _ struct{} `type:"structure"` -// SetImage sets the Image field's value. -func (s *ProjectEnvironment) SetImage(v string) *ProjectEnvironment { - s.Image = &v - return s -} + // The ARN of the report run. + Arn *string `locationName:"arn" min:"1" type:"string"` -// SetImagePullCredentialsType sets the ImagePullCredentialsType field's value. -func (s *ProjectEnvironment) SetImagePullCredentialsType(v string) *ProjectEnvironment { - s.ImagePullCredentialsType = &v - return s -} + // A CodeCoverageReportSummary object that contains a code coverage summary + // for this report. + CodeCoverageSummary *CodeCoverageReportSummary `locationName:"codeCoverageSummary" type:"structure"` -// SetPrivilegedMode sets the PrivilegedMode field's value. -func (s *ProjectEnvironment) SetPrivilegedMode(v bool) *ProjectEnvironment { - s.PrivilegedMode = &v - return s -} + // The date and time this report run occurred. + Created *time.Time `locationName:"created" type:"timestamp"` -// SetRegistryCredential sets the RegistryCredential field's value. -func (s *ProjectEnvironment) SetRegistryCredential(v *RegistryCredential) *ProjectEnvironment { - s.RegistryCredential = v - return s -} + // The ARN of the build run that generated this report. + ExecutionId *string `locationName:"executionId" type:"string"` -// SetType sets the Type field's value. -func (s *ProjectEnvironment) SetType(v string) *ProjectEnvironment { - s.Type = &v - return s -} + // The date and time a report expires. A report expires 30 days after it is + // created. An expired report is not available to view in CodeBuild. + Expired *time.Time `locationName:"expired" type:"timestamp"` -// Information about a file system created by Amazon Elastic File System (EFS). -// For more information, see What Is Amazon Elastic File System? (https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html) -type ProjectFileSystemLocation struct { - _ struct{} `type:"structure"` + // Information about where the raw data used to generate this report was exported. + ExportConfig *ReportExportConfig `locationName:"exportConfig" type:"structure"` - // The name used to access a file system created by Amazon EFS. CodeBuild creates - // an environment variable by appending the identifier in all capital letters - // to CODEBUILD_. For example, if you specify my-efs for identifier, a new environment - // variable is create named CODEBUILD_MY-EFS. - // - // The identifier is used to mount your file system. - Identifier *string `locationName:"identifier" type:"string"` + // The name of the report that was run. + Name *string `locationName:"name" type:"string"` - // A string that specifies the location of the file system created by Amazon - // EFS. Its format is efs-dns-name:/directory-path. You can find the DNS name - // of file system when you view it in the AWS EFS console. The directory path - // is a path to a directory in the file system that CodeBuild mounts. For example, - // if the DNS name of a file system is fs-abcd1234.efs.us-west-2.amazonaws.com, - // and its mount directory is my-efs-mount-directory, then the location is fs-abcd1234.efs.us-west-2.amazonaws.com:/my-efs-mount-directory. - // - // The directory path in the format efs-dns-name:/directory-path is optional. - // If you do not specify a directory path, the location is only the DNS name - // and CodeBuild mounts the entire file system. - Location *string `locationName:"location" type:"string"` + // The ARN of the report group associated with this report. + ReportGroupArn *string `locationName:"reportGroupArn" min:"1" type:"string"` - // The mount options for a file system created by AWS EFS. The default mount - // options used by CodeBuild are nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2. - // For more information, see Recommended NFS Mount Options (https://docs.aws.amazon.com/efs/latest/ug/mounting-fs-nfs-mount-settings.html). - MountOptions *string `locationName:"mountOptions" type:"string"` + // The status of this report. + Status *string `locationName:"status" type:"string" enum:"ReportStatusType"` - // The location in the container where you mount the file system. - MountPoint *string `locationName:"mountPoint" type:"string"` + // A TestReportSummary object that contains information about this test report. + TestSummary *TestReportSummary `locationName:"testSummary" type:"structure"` - // The type of the file system. The one supported type is EFS. - Type *string `locationName:"type" type:"string" enum:"FileSystemType"` + // A boolean that specifies if this report run is truncated. The list of test + // cases is truncated after the maximum number of test cases is reached. + Truncated *bool `locationName:"truncated" type:"boolean"` + + // The type of the report that was run. + // + // CODE_COVERAGE + // + // A code coverage report. + // + // TEST + // + // A test report. + Type *string `locationName:"type" type:"string" enum:"ReportType"` } // String returns the string representation -func (s ProjectFileSystemLocation) String() string { +func (s Report) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ProjectFileSystemLocation) GoString() string { +func (s Report) GoString() string { return s.String() } -// SetIdentifier sets the Identifier field's value. -func (s *ProjectFileSystemLocation) SetIdentifier(v string) *ProjectFileSystemLocation { - s.Identifier = &v +// SetArn sets the Arn field's value. +func (s *Report) SetArn(v string) *Report { + s.Arn = &v return s } -// SetLocation sets the Location field's value. -func (s *ProjectFileSystemLocation) SetLocation(v string) *ProjectFileSystemLocation { - s.Location = &v +// SetCodeCoverageSummary sets the CodeCoverageSummary field's value. +func (s *Report) SetCodeCoverageSummary(v *CodeCoverageReportSummary) *Report { + s.CodeCoverageSummary = v return s } -// SetMountOptions sets the MountOptions field's value. -func (s *ProjectFileSystemLocation) SetMountOptions(v string) *ProjectFileSystemLocation { - s.MountOptions = &v +// SetCreated sets the Created field's value. +func (s *Report) SetCreated(v time.Time) *Report { + s.Created = &v return s } -// SetMountPoint sets the MountPoint field's value. -func (s *ProjectFileSystemLocation) SetMountPoint(v string) *ProjectFileSystemLocation { - s.MountPoint = &v +// SetExecutionId sets the ExecutionId field's value. +func (s *Report) SetExecutionId(v string) *Report { + s.ExecutionId = &v return s } -// SetType sets the Type field's value. -func (s *ProjectFileSystemLocation) SetType(v string) *ProjectFileSystemLocation { - s.Type = &v +// SetExpired sets the Expired field's value. +func (s *Report) SetExpired(v time.Time) *Report { + s.Expired = &v return s } -// Information about the build input source code for the build project. -type ProjectSource struct { - _ struct{} `type:"structure"` - - // Information about the authorization settings for AWS CodeBuild to access - // the source code to be built. - // - // This information is for the AWS CodeBuild console's use only. Your code should - // not get or set this information directly. - Auth *SourceAuth `locationName:"auth" type:"structure"` - - // The buildspec file declaration to use for the builds in this build project. - // - // If this value is set, it can be either an inline buildspec definition, the - // path to an alternate buildspec file relative to the value of the built-in - // CODEBUILD_SRC_DIR environment variable, or the path to an S3 bucket. The - // bucket must be in the same AWS Region as the build project. Specify the buildspec - // file using its ARN (for example, arn:aws:s3:::my-codebuild-sample2/buildspec.yml). - // If this value is not provided or is set to an empty string, the source code - // must contain a buildspec file in its root directory. For more information, - // see Buildspec File Name and Storage Location (https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec-ref-name-storage). - Buildspec *string `locationName:"buildspec" type:"string"` +// SetExportConfig sets the ExportConfig field's value. +func (s *Report) SetExportConfig(v *ReportExportConfig) *Report { + s.ExportConfig = v + return s +} - // Information about the Git clone depth for the build project. - GitCloneDepth *int64 `locationName:"gitCloneDepth" type:"integer"` +// SetName sets the Name field's value. +func (s *Report) SetName(v string) *Report { + s.Name = &v + return s +} - // Information about the Git submodules configuration for the build project. - GitSubmodulesConfig *GitSubmodulesConfig `locationName:"gitSubmodulesConfig" type:"structure"` +// SetReportGroupArn sets the ReportGroupArn field's value. +func (s *Report) SetReportGroupArn(v string) *Report { + s.ReportGroupArn = &v + return s +} - // Enable this flag to ignore SSL warnings while connecting to the project source - // code. - InsecureSsl *bool `locationName:"insecureSsl" type:"boolean"` +// SetStatus sets the Status field's value. +func (s *Report) SetStatus(v string) *Report { + s.Status = &v + return s +} - // Information about the location of the source code to be built. Valid values - // include: - // - // * For source code settings that are specified in the source action of - // a pipeline in AWS CodePipeline, location should not be specified. If it - // is specified, AWS CodePipeline ignores it. This is because AWS CodePipeline - // uses the settings in a pipeline's source action instead of this value. - // - // * For source code in an AWS CodeCommit repository, the HTTPS clone URL - // to the repository that contains the source code and the buildspec file - // (for example, https://git-codecommit.region-ID.amazonaws.com/v1/repos/repo-name - // ). - // - // * For source code in an Amazon Simple Storage Service (Amazon S3) input - // bucket, one of the following. The path to the ZIP file that contains the - // source code (for example, bucket-name/path/to/object-name.zip). The path - // to the folder that contains the source code (for example, bucket-name/path/to/source-code/folder/). - // - // * For source code in a GitHub repository, the HTTPS clone URL to the repository - // that contains the source and the buildspec file. You must connect your - // AWS account to your GitHub account. Use the AWS CodeBuild console to start - // creating a build project. When you use the console to connect (or reconnect) - // with GitHub, on the GitHub Authorize application page, for Organization - // access, choose Request access next to each repository you want to allow - // AWS CodeBuild to have access to, and then choose Authorize application. - // (After you have connected to your GitHub account, you do not need to finish - // creating the build project. You can leave the AWS CodeBuild console.) - // To instruct AWS CodeBuild to use this connection, in the source object, - // set the auth object's type value to OAUTH. - // - // * For source code in a Bitbucket repository, the HTTPS clone URL to the - // repository that contains the source and the buildspec file. You must connect - // your AWS account to your Bitbucket account. Use the AWS CodeBuild console - // to start creating a build project. When you use the console to connect - // (or reconnect) with Bitbucket, on the Bitbucket Confirm access to your - // account page, choose Grant access. (After you have connected to your Bitbucket - // account, you do not need to finish creating the build project. You can - // leave the AWS CodeBuild console.) To instruct AWS CodeBuild to use this - // connection, in the source object, set the auth object's type value to - // OAUTH. - Location *string `locationName:"location" type:"string"` +// SetTestSummary sets the TestSummary field's value. +func (s *Report) SetTestSummary(v *TestReportSummary) *Report { + s.TestSummary = v + return s +} - // Set to true to report the status of a build's start and finish to your source - // provider. This option is valid only when your source provider is GitHub, - // GitHub Enterprise, or Bitbucket. If this is set and you use a different source - // provider, an invalidInputException is thrown. - // - // The status of a build triggered by a webhook is always reported to your source - // provider. - ReportBuildStatus *bool `locationName:"reportBuildStatus" type:"boolean"` +// SetTruncated sets the Truncated field's value. +func (s *Report) SetTruncated(v bool) *Report { + s.Truncated = &v + return s +} - // An identifier for this project source. - SourceIdentifier *string `locationName:"sourceIdentifier" type:"string"` +// SetType sets the Type field's value. +func (s *Report) SetType(v string) *Report { + s.Type = &v + return s +} - // The type of repository that contains the source code to be built. Valid values - // include: - // - // * BITBUCKET: The source code is in a Bitbucket repository. - // - // * CODECOMMIT: The source code is in an AWS CodeCommit repository. - // - // * CODEPIPELINE: The source code settings are specified in the source action - // of a pipeline in AWS CodePipeline. - // - // * GITHUB: The source code is in a GitHub repository. - // - // * GITHUB_ENTERPRISE: The source code is in a GitHub Enterprise repository. - // - // * NO_SOURCE: The project does not have input source code. +// Information about the location where the run of a report is exported. +type ReportExportConfig struct { + _ struct{} `type:"structure"` + + // The export configuration type. Valid values are: // - // * S3: The source code is in an Amazon Simple Storage Service (Amazon S3) - // input bucket. + // * S3: The report results are exported to an S3 bucket. // - // Type is a required field - Type *string `locationName:"type" type:"string" required:"true" enum:"SourceType"` + // * NO_EXPORT: The report results are not exported. + ExportConfigType *string `locationName:"exportConfigType" type:"string" enum:"ReportExportConfigType"` + + // A S3ReportExportConfig object that contains information about the S3 bucket + // where the run of a report is exported. + S3Destination *S3ReportExportConfig `locationName:"s3Destination" type:"structure"` } // String returns the string representation -func (s ProjectSource) String() string { +func (s ReportExportConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ProjectSource) GoString() string { +func (s ReportExportConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ProjectSource) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ProjectSource"} - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - if s.Auth != nil { - if err := s.Auth.Validate(); err != nil { - invalidParams.AddNested("Auth", err.(request.ErrInvalidParams)) - } - } - if s.GitSubmodulesConfig != nil { - if err := s.GitSubmodulesConfig.Validate(); err != nil { - invalidParams.AddNested("GitSubmodulesConfig", err.(request.ErrInvalidParams)) +func (s *ReportExportConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ReportExportConfig"} + if s.S3Destination != nil { + if err := s.S3Destination.Validate(); err != nil { + invalidParams.AddNested("S3Destination", err.(request.ErrInvalidParams)) } } @@ -7709,269 +11230,317 @@ func (s *ProjectSource) Validate() error { return nil } -// SetAuth sets the Auth field's value. -func (s *ProjectSource) SetAuth(v *SourceAuth) *ProjectSource { - s.Auth = v +// SetExportConfigType sets the ExportConfigType field's value. +func (s *ReportExportConfig) SetExportConfigType(v string) *ReportExportConfig { + s.ExportConfigType = &v return s } -// SetBuildspec sets the Buildspec field's value. -func (s *ProjectSource) SetBuildspec(v string) *ProjectSource { - s.Buildspec = &v +// SetS3Destination sets the S3Destination field's value. +func (s *ReportExportConfig) SetS3Destination(v *S3ReportExportConfig) *ReportExportConfig { + s.S3Destination = v return s } -// SetGitCloneDepth sets the GitCloneDepth field's value. -func (s *ProjectSource) SetGitCloneDepth(v int64) *ProjectSource { - s.GitCloneDepth = &v +// A filter used to return reports with the status specified by the input status +// parameter. +type ReportFilter struct { + _ struct{} `type:"structure"` + + // The status used to filter reports. You can filter using one status only. + Status *string `locationName:"status" type:"string" enum:"ReportStatusType"` +} + +// String returns the string representation +func (s ReportFilter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ReportFilter) GoString() string { + return s.String() +} + +// SetStatus sets the Status field's value. +func (s *ReportFilter) SetStatus(v string) *ReportFilter { + s.Status = &v return s } -// SetGitSubmodulesConfig sets the GitSubmodulesConfig field's value. -func (s *ProjectSource) SetGitSubmodulesConfig(v *GitSubmodulesConfig) *ProjectSource { - s.GitSubmodulesConfig = v +// A series of reports. Each report contains information about the results from +// running a series of test cases. You specify the test cases for a report group +// in the buildspec for a build project using one or more paths to the test +// case files. +type ReportGroup struct { + _ struct{} `type:"structure"` + + // The ARN of a ReportGroup. + Arn *string `locationName:"arn" min:"1" type:"string"` + + // The date and time this ReportGroup was created. + Created *time.Time `locationName:"created" type:"timestamp"` + + // Information about the destination where the raw data of this ReportGroup + // is exported. + ExportConfig *ReportExportConfig `locationName:"exportConfig" type:"structure"` + + // The date and time this ReportGroup was last modified. + LastModified *time.Time `locationName:"lastModified" type:"timestamp"` + + // The name of a ReportGroup. + Name *string `locationName:"name" min:"2" type:"string"` + + // A list of tag key and value pairs associated with this report group. + // + // These tags are available for use by AWS services that support AWS CodeBuild + // report group tags. + Tags []*Tag `locationName:"tags" type:"list"` + + // The type of the ReportGroup. The one valid value is TEST. + Type *string `locationName:"type" type:"string" enum:"ReportType"` +} + +// String returns the string representation +func (s ReportGroup) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ReportGroup) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *ReportGroup) SetArn(v string) *ReportGroup { + s.Arn = &v return s } -// SetInsecureSsl sets the InsecureSsl field's value. -func (s *ProjectSource) SetInsecureSsl(v bool) *ProjectSource { - s.InsecureSsl = &v +// SetCreated sets the Created field's value. +func (s *ReportGroup) SetCreated(v time.Time) *ReportGroup { + s.Created = &v return s } -// SetLocation sets the Location field's value. -func (s *ProjectSource) SetLocation(v string) *ProjectSource { - s.Location = &v +// SetExportConfig sets the ExportConfig field's value. +func (s *ReportGroup) SetExportConfig(v *ReportExportConfig) *ReportGroup { + s.ExportConfig = v return s } -// SetReportBuildStatus sets the ReportBuildStatus field's value. -func (s *ProjectSource) SetReportBuildStatus(v bool) *ProjectSource { - s.ReportBuildStatus = &v +// SetLastModified sets the LastModified field's value. +func (s *ReportGroup) SetLastModified(v time.Time) *ReportGroup { + s.LastModified = &v return s } -// SetSourceIdentifier sets the SourceIdentifier field's value. -func (s *ProjectSource) SetSourceIdentifier(v string) *ProjectSource { - s.SourceIdentifier = &v +// SetName sets the Name field's value. +func (s *ReportGroup) SetName(v string) *ReportGroup { + s.Name = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *ReportGroup) SetTags(v []*Tag) *ReportGroup { + s.Tags = v return s } // SetType sets the Type field's value. -func (s *ProjectSource) SetType(v string) *ProjectSource { +func (s *ReportGroup) SetType(v string) *ReportGroup { s.Type = &v return s } -// A source identifier and its corresponding version. -type ProjectSourceVersion struct { +// Represents a resolved build artifact. A resolve artifact is an artifact that +// is built and deployed to the destination, such as Amazon Simple Storage Service +// (Amazon S3). +type ResolvedArtifact struct { _ struct{} `type:"structure"` - // An identifier for a source in the build project. - // - // SourceIdentifier is a required field - SourceIdentifier *string `locationName:"sourceIdentifier" type:"string" required:"true"` + // The identifier of the artifact. + Identifier *string `locationName:"identifier" type:"string"` - // The source version for the corresponding source identifier. If specified, - // must be one of: - // - // * For AWS CodeCommit: the commit ID, branch, or Git tag to use. - // - // * For GitHub: the commit ID, pull request ID, branch name, or tag name - // that corresponds to the version of the source code you want to build. - // If a pull request ID is specified, it must use the format pr/pull-request-ID - // (for example, pr/25). If a branch name is specified, the branch's HEAD - // commit ID is used. If not specified, the default branch's HEAD commit - // ID is used. - // - // * For Bitbucket: the commit ID, branch name, or tag name that corresponds - // to the version of the source code you want to build. If a branch name - // is specified, the branch's HEAD commit ID is used. If not specified, the - // default branch's HEAD commit ID is used. - // - // * For Amazon Simple Storage Service (Amazon S3): the version ID of the - // object that represents the build input ZIP file to use. - // - // For more information, see Source Version Sample with CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/sample-source-version.html) - // in the AWS CodeBuild User Guide. - // - // SourceVersion is a required field - SourceVersion *string `locationName:"sourceVersion" type:"string" required:"true"` + // The location of the artifact. + Location *string `locationName:"location" type:"string"` + + // Specifies the type of artifact. + Type *string `locationName:"type" type:"string" enum:"ArtifactsType"` } // String returns the string representation -func (s ProjectSourceVersion) String() string { +func (s ResolvedArtifact) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ProjectSourceVersion) GoString() string { +func (s ResolvedArtifact) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ProjectSourceVersion) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ProjectSourceVersion"} - if s.SourceIdentifier == nil { - invalidParams.Add(request.NewErrParamRequired("SourceIdentifier")) - } - if s.SourceVersion == nil { - invalidParams.Add(request.NewErrParamRequired("SourceVersion")) +// SetIdentifier sets the Identifier field's value. +func (s *ResolvedArtifact) SetIdentifier(v string) *ResolvedArtifact { + s.Identifier = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *ResolvedArtifact) SetLocation(v string) *ResolvedArtifact { + s.Location = &v + return s +} + +// SetType sets the Type field's value. +func (s *ResolvedArtifact) SetType(v string) *ResolvedArtifact { + s.Type = &v + return s +} + +// The specified AWS resource cannot be created, because an AWS resource with +// the same settings already exists. +type ResourceAlreadyExistsException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ResourceAlreadyExistsException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResourceAlreadyExistsException) GoString() string { + return s.String() +} + +func newErrorResourceAlreadyExistsException(v protocol.ResponseMetadata) error { + return &ResourceAlreadyExistsException{ + RespMetadata: v, } +} - if invalidParams.Len() > 0 { - return invalidParams +// Code returns the exception type name. +func (s *ResourceAlreadyExistsException) Code() string { + return "ResourceAlreadyExistsException" +} + +// Message returns the exception's message. +func (s *ResourceAlreadyExistsException) Message() string { + if s.Message_ != nil { + return *s.Message_ } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ResourceAlreadyExistsException) OrigErr() error { return nil } -// SetSourceIdentifier sets the SourceIdentifier field's value. -func (s *ProjectSourceVersion) SetSourceIdentifier(v string) *ProjectSourceVersion { - s.SourceIdentifier = &v - return s +func (s *ResourceAlreadyExistsException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) } -// SetSourceVersion sets the SourceVersion field's value. -func (s *ProjectSourceVersion) SetSourceVersion(v string) *ProjectSourceVersion { - s.SourceVersion = &v - return s +// Status code returns the HTTP status code for the request's response error. +func (s *ResourceAlreadyExistsException) StatusCode() int { + return s.RespMetadata.StatusCode } -type PutResourcePolicyInput struct { - _ struct{} `type:"structure"` +// RequestID returns the service's response RequestID for request. +func (s *ResourceAlreadyExistsException) RequestID() string { + return s.RespMetadata.RequestID +} - // A JSON-formatted resource policy. For more information, see Sharing a Project - // (https://docs.aws.amazon.com/codebuild/latest/userguide/project-sharing.html#project-sharing-share) - // and Sharing a Report Group (https://docs.aws.amazon.com/codebuild/latest/userguide/report-groups-sharing.html#report-groups-sharing-share) - // in the AWS CodeBuild User Guide. - // - // Policy is a required field - Policy *string `locationName:"policy" min:"1" type:"string" required:"true"` +// The specified AWS resource cannot be found. +type ResourceNotFoundException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // The ARN of the Project or ReportGroup resource you want to associate with - // a resource policy. - // - // ResourceArn is a required field - ResourceArn *string `locationName:"resourceArn" min:"1" type:"string" required:"true"` + Message_ *string `locationName:"message" type:"string"` } // String returns the string representation -func (s PutResourcePolicyInput) String() string { +func (s ResourceNotFoundException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PutResourcePolicyInput) GoString() string { +func (s ResourceNotFoundException) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutResourcePolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutResourcePolicyInput"} - if s.Policy == nil { - invalidParams.Add(request.NewErrParamRequired("Policy")) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - 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 +func newErrorResourceNotFoundException(v protocol.ResponseMetadata) error { + return &ResourceNotFoundException{ + RespMetadata: v, } - return nil } -// SetPolicy sets the Policy field's value. -func (s *PutResourcePolicyInput) SetPolicy(v string) *PutResourcePolicyInput { - s.Policy = &v - return s +// Code returns the exception type name. +func (s *ResourceNotFoundException) Code() string { + return "ResourceNotFoundException" } -// SetResourceArn sets the ResourceArn field's value. -func (s *PutResourcePolicyInput) SetResourceArn(v string) *PutResourcePolicyInput { - s.ResourceArn = &v - return s +// Message returns the exception's message. +func (s *ResourceNotFoundException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" } -type PutResourcePolicyOutput struct { - _ struct{} `type:"structure"` - - // The ARN of the Project or ReportGroup resource that is associated with a - // resource policy. - ResourceArn *string `locationName:"resourceArn" min:"1" type:"string"` +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ResourceNotFoundException) OrigErr() error { + return nil } -// String returns the string representation -func (s PutResourcePolicyOutput) String() string { - return awsutil.Prettify(s) +func (s *ResourceNotFoundException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) } -// GoString returns the string representation -func (s PutResourcePolicyOutput) GoString() string { - return s.String() +// Status code returns the HTTP status code for the request's response error. +func (s *ResourceNotFoundException) StatusCode() int { + return s.RespMetadata.StatusCode } -// SetResourceArn sets the ResourceArn field's value. -func (s *PutResourcePolicyOutput) SetResourceArn(v string) *PutResourcePolicyOutput { - s.ResourceArn = &v - return s +// RequestID returns the service's response RequestID for request. +func (s *ResourceNotFoundException) RequestID() string { + return s.RespMetadata.RequestID } -// Information about credentials that provide access to a private Docker registry. -// When this is set: -// -// * imagePullCredentialsType must be set to SERVICE_ROLE. -// -// * images cannot be curated or an Amazon ECR image. -// -// For more information, see Private Registry with AWS Secrets Manager Sample -// for AWS CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/sample-private-registry.html). -type RegistryCredential struct { +type RetryBuildBatchInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) or name of credentials created using AWS Secrets - // Manager. - // - // The credential can use the name of the credentials only if they exist in - // your current AWS Region. - // - // Credential is a required field - Credential *string `locationName:"credential" min:"1" type:"string" required:"true"` + // Specifies the identifier of the batch build to restart. + Id *string `locationName:"id" min:"1" type:"string"` - // The service that created the credentials to access a private Docker registry. - // The valid value, SECRETS_MANAGER, is for AWS Secrets Manager. - // - // CredentialProvider is a required field - CredentialProvider *string `locationName:"credentialProvider" type:"string" required:"true" enum:"CredentialProviderType"` + // A unique, case sensitive identifier you provide to ensure the idempotency + // of the RetryBuildBatch request. The token is included in the RetryBuildBatch + // request and is valid for five minutes. If you repeat the RetryBuildBatch + // request with the same token, but change a parameter, AWS CodeBuild returns + // a parameter mismatch error. + IdempotencyToken *string `locationName:"idempotencyToken" type:"string"` + + // Specifies the type of retry to perform. + RetryType *string `locationName:"retryType" type:"string" enum:"RetryBuildBatchType"` } // String returns the string representation -func (s RegistryCredential) String() string { +func (s RetryBuildBatchInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RegistryCredential) GoString() string { +func (s RetryBuildBatchInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *RegistryCredential) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RegistryCredential"} - if s.Credential == nil { - invalidParams.Add(request.NewErrParamRequired("Credential")) - } - if s.Credential != nil && len(*s.Credential) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Credential", 1)) - } - if s.CredentialProvider == nil { - invalidParams.Add(request.NewErrParamRequired("CredentialProvider")) +func (s *RetryBuildBatchInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RetryBuildBatchInput"} + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) } if invalidParams.Len() > 0 { @@ -7980,171 +11549,157 @@ func (s *RegistryCredential) Validate() error { return nil } -// SetCredential sets the Credential field's value. -func (s *RegistryCredential) SetCredential(v string) *RegistryCredential { - s.Credential = &v +// SetId sets the Id field's value. +func (s *RetryBuildBatchInput) SetId(v string) *RetryBuildBatchInput { + s.Id = &v return s } -// SetCredentialProvider sets the CredentialProvider field's value. -func (s *RegistryCredential) SetCredentialProvider(v string) *RegistryCredential { - s.CredentialProvider = &v +// SetIdempotencyToken sets the IdempotencyToken field's value. +func (s *RetryBuildBatchInput) SetIdempotencyToken(v string) *RetryBuildBatchInput { + s.IdempotencyToken = &v return s } -// Information about the results from running a series of test cases during -// the run of a build project. The test cases are specified in the buildspec -// for the build project using one or more paths to the test case files. You -// can specify any type of tests you want, such as unit tests, integration tests, -// and functional tests. -type Report struct { - _ struct{} `type:"structure"` - - // The ARN of the report run. - Arn *string `locationName:"arn" min:"1" type:"string"` - - // The date and time this report run occurred. - Created *time.Time `locationName:"created" type:"timestamp"` - - // The ARN of the build run that generated this report. - ExecutionId *string `locationName:"executionId" type:"string"` - - // The date and time a report expires. A report expires 30 days after it is - // created. An expired report is not available to view in CodeBuild. - Expired *time.Time `locationName:"expired" type:"timestamp"` - - // Information about where the raw data used to generate this report was exported. - ExportConfig *ReportExportConfig `locationName:"exportConfig" type:"structure"` - - // The name of the report that was run. - Name *string `locationName:"name" type:"string"` - - // The ARN of the report group associated with this report. - ReportGroupArn *string `locationName:"reportGroupArn" min:"1" type:"string"` - - // The status of this report. - Status *string `locationName:"status" type:"string" enum:"ReportStatusType"` - - // A TestReportSummary object that contains information about this test report. - TestSummary *TestReportSummary `locationName:"testSummary" type:"structure"` +// SetRetryType sets the RetryType field's value. +func (s *RetryBuildBatchInput) SetRetryType(v string) *RetryBuildBatchInput { + s.RetryType = &v + return s +} - // A boolean that specifies if this report run is truncated. The list of test - // cases is truncated after the maximum number of test cases is reached. - Truncated *bool `locationName:"truncated" type:"boolean"` +type RetryBuildBatchOutput struct { + _ struct{} `type:"structure"` - // The type of the report that was run. - Type *string `locationName:"type" type:"string" enum:"ReportType"` + // Contains information about a batch build. + BuildBatch *BuildBatch `locationName:"buildBatch" type:"structure"` } // String returns the string representation -func (s Report) String() string { +func (s RetryBuildBatchOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Report) GoString() string { +func (s RetryBuildBatchOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *Report) SetArn(v string) *Report { - s.Arn = &v +// SetBuildBatch sets the BuildBatch field's value. +func (s *RetryBuildBatchOutput) SetBuildBatch(v *BuildBatch) *RetryBuildBatchOutput { + s.BuildBatch = v return s } -// SetCreated sets the Created field's value. -func (s *Report) SetCreated(v time.Time) *Report { - s.Created = &v - return s +type RetryBuildInput struct { + _ struct{} `type:"structure"` + + // Specifies the identifier of the build to restart. + Id *string `locationName:"id" min:"1" type:"string"` + + // A unique, case sensitive identifier you provide to ensure the idempotency + // of the RetryBuild request. The token is included in the RetryBuild request + // and is valid for five minutes. If you repeat the RetryBuild request with + // the same token, but change a parameter, AWS CodeBuild returns a parameter + // mismatch error. + IdempotencyToken *string `locationName:"idempotencyToken" type:"string"` } -// SetExecutionId sets the ExecutionId field's value. -func (s *Report) SetExecutionId(v string) *Report { - s.ExecutionId = &v - return s +// String returns the string representation +func (s RetryBuildInput) String() string { + return awsutil.Prettify(s) } -// SetExpired sets the Expired field's value. -func (s *Report) SetExpired(v time.Time) *Report { - s.Expired = &v - return s +// GoString returns the string representation +func (s RetryBuildInput) GoString() string { + return s.String() } -// SetExportConfig sets the ExportConfig field's value. -func (s *Report) SetExportConfig(v *ReportExportConfig) *Report { - s.ExportConfig = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *RetryBuildInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RetryBuildInput"} + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetName sets the Name field's value. -func (s *Report) SetName(v string) *Report { - s.Name = &v +// SetId sets the Id field's value. +func (s *RetryBuildInput) SetId(v string) *RetryBuildInput { + s.Id = &v return s } -// SetReportGroupArn sets the ReportGroupArn field's value. -func (s *Report) SetReportGroupArn(v string) *Report { - s.ReportGroupArn = &v +// SetIdempotencyToken sets the IdempotencyToken field's value. +func (s *RetryBuildInput) SetIdempotencyToken(v string) *RetryBuildInput { + s.IdempotencyToken = &v return s } -// SetStatus sets the Status field's value. -func (s *Report) SetStatus(v string) *Report { - s.Status = &v - return s +type RetryBuildOutput struct { + _ struct{} `type:"structure"` + + // Information about a build. + Build *Build `locationName:"build" type:"structure"` } -// SetTestSummary sets the TestSummary field's value. -func (s *Report) SetTestSummary(v *TestReportSummary) *Report { - s.TestSummary = v - return s +// String returns the string representation +func (s RetryBuildOutput) String() string { + return awsutil.Prettify(s) } -// SetTruncated sets the Truncated field's value. -func (s *Report) SetTruncated(v bool) *Report { - s.Truncated = &v - return s +// GoString returns the string representation +func (s RetryBuildOutput) GoString() string { + return s.String() } -// SetType sets the Type field's value. -func (s *Report) SetType(v string) *Report { - s.Type = &v +// SetBuild sets the Build field's value. +func (s *RetryBuildOutput) SetBuild(v *Build) *RetryBuildOutput { + s.Build = v return s } -// Information about the location where the run of a report is exported. -type ReportExportConfig struct { +// Information about S3 logs for a build project. +type S3LogsConfig struct { _ struct{} `type:"structure"` - // The export configuration type. Valid values are: + // Set to true if you do not want your S3 build log output encrypted. By default + // S3 build logs are encrypted. + EncryptionDisabled *bool `locationName:"encryptionDisabled" type:"boolean"` + + // The ARN of an S3 bucket and the path prefix for S3 logs. If your Amazon S3 + // bucket name is my-bucket, and your path prefix is build-log, then acceptable + // formats are my-bucket/build-log or arn:aws:s3:::my-bucket/build-log. + Location *string `locationName:"location" type:"string"` + + // The current status of the S3 build logs. Valid values are: // - // * S3: The report results are exported to an S3 bucket. + // * ENABLED: S3 build logs are enabled for this build project. // - // * NO_EXPORT: The report results are not exported. - ExportConfigType *string `locationName:"exportConfigType" type:"string" enum:"ReportExportConfigType"` - - // A S3ReportExportConfig object that contains information about the S3 bucket - // where the run of a report is exported. - S3Destination *S3ReportExportConfig `locationName:"s3Destination" type:"structure"` + // * DISABLED: S3 build logs are not enabled for this build project. + // + // Status is a required field + Status *string `locationName:"status" type:"string" required:"true" enum:"LogsConfigStatusType"` } // String returns the string representation -func (s ReportExportConfig) String() string { +func (s S3LogsConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ReportExportConfig) GoString() string { +func (s S3LogsConfig) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ReportExportConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ReportExportConfig"} - if s.S3Destination != nil { - if err := s.S3Destination.Validate(); err != nil { - invalidParams.AddNested("S3Destination", err.(request.ErrInvalidParams)) - } +func (s *S3LogsConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "S3LogsConfig"} + if s.Status == nil { + invalidParams.Add(request.NewErrParamRequired("Status")) } if invalidParams.Len() > 0 { @@ -8153,267 +11708,509 @@ func (s *ReportExportConfig) Validate() error { return nil } -// SetExportConfigType sets the ExportConfigType field's value. -func (s *ReportExportConfig) SetExportConfigType(v string) *ReportExportConfig { - s.ExportConfigType = &v +// SetEncryptionDisabled sets the EncryptionDisabled field's value. +func (s *S3LogsConfig) SetEncryptionDisabled(v bool) *S3LogsConfig { + s.EncryptionDisabled = &v return s } -// SetS3Destination sets the S3Destination field's value. -func (s *ReportExportConfig) SetS3Destination(v *S3ReportExportConfig) *ReportExportConfig { - s.S3Destination = v +// SetLocation sets the Location field's value. +func (s *S3LogsConfig) SetLocation(v string) *S3LogsConfig { + s.Location = &v return s } -// A filter used to return reports with the status specified by the input status -// parameter. -type ReportFilter struct { +// SetStatus sets the Status field's value. +func (s *S3LogsConfig) SetStatus(v string) *S3LogsConfig { + s.Status = &v + return s +} + +// Information about the S3 bucket where the raw data of a report are exported. +type S3ReportExportConfig struct { _ struct{} `type:"structure"` - // The status used to filter reports. You can filter using one status only. - Status *string `locationName:"status" type:"string" enum:"ReportStatusType"` + // The name of the S3 bucket where the raw data of a report are exported. + Bucket *string `locationName:"bucket" min:"1" type:"string"` + + // A boolean value that specifies if the results of a report are encrypted. + EncryptionDisabled *bool `locationName:"encryptionDisabled" type:"boolean"` + + // The encryption key for the report's encrypted raw data. + EncryptionKey *string `locationName:"encryptionKey" min:"1" type:"string"` + + // The type of build output artifact to create. Valid values include: + // + // * NONE: AWS CodeBuild creates the raw data in the output bucket. This + // is the default if packaging is not specified. + // + // * ZIP: AWS CodeBuild creates a ZIP file with the raw data in the output + // bucket. + Packaging *string `locationName:"packaging" type:"string" enum:"ReportPackagingType"` + + // The path to the exported report's raw data results. + Path *string `locationName:"path" type:"string"` } // String returns the string representation -func (s ReportFilter) String() string { +func (s S3ReportExportConfig) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ReportFilter) GoString() string { +func (s S3ReportExportConfig) GoString() string { return s.String() } -// SetStatus sets the Status field's value. -func (s *ReportFilter) SetStatus(v string) *ReportFilter { - s.Status = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *S3ReportExportConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "S3ReportExportConfig"} + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) + } + if s.EncryptionKey != nil && len(*s.EncryptionKey) < 1 { + invalidParams.Add(request.NewErrParamMinLen("EncryptionKey", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBucket sets the Bucket field's value. +func (s *S3ReportExportConfig) SetBucket(v string) *S3ReportExportConfig { + s.Bucket = &v return s } -// A series of reports. Each report contains information about the results from -// running a series of test cases. You specify the test cases for a report group -// in the buildspec for a build project using one or more paths to the test -// case files. -type ReportGroup struct { - _ struct{} `type:"structure"` +// SetEncryptionDisabled sets the EncryptionDisabled field's value. +func (s *S3ReportExportConfig) SetEncryptionDisabled(v bool) *S3ReportExportConfig { + s.EncryptionDisabled = &v + return s +} - // The ARN of a ReportGroup. - Arn *string `locationName:"arn" min:"1" type:"string"` +// SetEncryptionKey sets the EncryptionKey field's value. +func (s *S3ReportExportConfig) SetEncryptionKey(v string) *S3ReportExportConfig { + s.EncryptionKey = &v + return s +} - // The date and time this ReportGroup was created. - Created *time.Time `locationName:"created" type:"timestamp"` +// SetPackaging sets the Packaging field's value. +func (s *S3ReportExportConfig) SetPackaging(v string) *S3ReportExportConfig { + s.Packaging = &v + return s +} - // Information about the destination where the raw data of this ReportGroup - // is exported. - ExportConfig *ReportExportConfig `locationName:"exportConfig" type:"structure"` +// SetPath sets the Path field's value. +func (s *S3ReportExportConfig) SetPath(v string) *S3ReportExportConfig { + s.Path = &v + return s +} - // The date and time this ReportGroup was last modified. - LastModified *time.Time `locationName:"lastModified" type:"timestamp"` +// Information about the authorization settings for AWS CodeBuild to access +// the source code to be built. +// +// This information is for the AWS CodeBuild console's use only. Your code should +// not get or set this information directly. +type SourceAuth struct { + _ struct{} `type:"structure"` - // The name of a ReportGroup. - Name *string `locationName:"name" min:"2" type:"string"` + // The resource value that applies to the specified authorization type. + Resource *string `locationName:"resource" type:"string"` - // The type of the ReportGroup. The one valid value is TEST. - Type *string `locationName:"type" type:"string" enum:"ReportType"` + // + // This data type is deprecated and is no longer accurate or used. + // + // The authorization type to use. The only valid value is OAUTH, which represents + // the OAuth authorization type. + // + // Type is a required field + Type *string `locationName:"type" type:"string" required:"true" enum:"SourceAuthType"` } // String returns the string representation -func (s ReportGroup) String() string { +func (s SourceAuth) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ReportGroup) GoString() string { +func (s SourceAuth) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *ReportGroup) SetArn(v string) *ReportGroup { - s.Arn = &v - return s -} - -// SetCreated sets the Created field's value. -func (s *ReportGroup) SetCreated(v time.Time) *ReportGroup { - s.Created = &v - return s -} - -// SetExportConfig sets the ExportConfig field's value. -func (s *ReportGroup) SetExportConfig(v *ReportExportConfig) *ReportGroup { - s.ExportConfig = v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *SourceAuth) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SourceAuth"} + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } -// SetLastModified sets the LastModified field's value. -func (s *ReportGroup) SetLastModified(v time.Time) *ReportGroup { - s.LastModified = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetName sets the Name field's value. -func (s *ReportGroup) SetName(v string) *ReportGroup { - s.Name = &v +// SetResource sets the Resource field's value. +func (s *SourceAuth) SetResource(v string) *SourceAuth { + s.Resource = &v return s } // SetType sets the Type field's value. -func (s *ReportGroup) SetType(v string) *ReportGroup { +func (s *SourceAuth) SetType(v string) *SourceAuth { s.Type = &v return s } -// The specified AWS resource cannot be created, because an AWS resource with -// the same settings already exists. -type ResourceAlreadyExistsException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +// Information about the credentials for a GitHub, GitHub Enterprise, or Bitbucket +// repository. +type SourceCredentialsInfo struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the token. + Arn *string `locationName:"arn" min:"1" type:"string"` - Message_ *string `locationName:"message" type:"string"` + // The type of authentication used by the credentials. Valid options are OAUTH, + // BASIC_AUTH, or PERSONAL_ACCESS_TOKEN. + AuthType *string `locationName:"authType" type:"string" enum:"AuthType"` + + // The type of source provider. The valid options are GITHUB, GITHUB_ENTERPRISE, + // or BITBUCKET. + ServerType *string `locationName:"serverType" type:"string" enum:"ServerType"` } // String returns the string representation -func (s ResourceAlreadyExistsException) String() string { +func (s SourceCredentialsInfo) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ResourceAlreadyExistsException) GoString() string { +func (s SourceCredentialsInfo) GoString() string { return s.String() } -func newErrorResourceAlreadyExistsException(v protocol.ResponseMetadata) error { - return &ResourceAlreadyExistsException{ - RespMetadata: v, - } +// SetArn sets the Arn field's value. +func (s *SourceCredentialsInfo) SetArn(v string) *SourceCredentialsInfo { + s.Arn = &v + return s } -// Code returns the exception type name. -func (s *ResourceAlreadyExistsException) Code() string { - return "ResourceAlreadyExistsException" +// SetAuthType sets the AuthType field's value. +func (s *SourceCredentialsInfo) SetAuthType(v string) *SourceCredentialsInfo { + s.AuthType = &v + return s } -// Message returns the exception's message. -func (s *ResourceAlreadyExistsException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" +// SetServerType sets the ServerType field's value. +func (s *SourceCredentialsInfo) SetServerType(v string) *SourceCredentialsInfo { + s.ServerType = &v + return s } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ResourceAlreadyExistsException) OrigErr() error { - return nil -} +type StartBuildBatchInput struct { + _ struct{} `type:"structure"` -func (s *ResourceAlreadyExistsException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} + // An array of ProjectArtifacts objects that contains information about the + // build output artifact overrides for the build project. + ArtifactsOverride *ProjectArtifacts `locationName:"artifactsOverride" type:"structure"` -// Status code returns the HTTP status code for the request's response error. -func (s *ResourceAlreadyExistsException) StatusCode() int { - return s.RespMetadata.StatusCode -} + // A BuildBatchConfigOverride object that contains batch build configuration + // overrides. + BuildBatchConfigOverride *ProjectBuildBatchConfig `locationName:"buildBatchConfigOverride" type:"structure"` -// RequestID returns the service's response RequestID for request. -func (s *ResourceAlreadyExistsException) RequestID() string { - return s.RespMetadata.RequestID -} + // Overrides the build timeout specified in the batch build project. + BuildTimeoutInMinutesOverride *int64 `locationName:"buildTimeoutInMinutesOverride" min:"5" type:"integer"` -// The specified AWS resource cannot be found. -type ResourceNotFoundException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + // A buildspec file declaration that overrides, for this build only, the latest + // one already defined in the build project. + // + // If this value is set, it can be either an inline buildspec definition, the + // path to an alternate buildspec file relative to the value of the built-in + // CODEBUILD_SRC_DIR environment variable, or the path to an S3 bucket. The + // bucket must be in the same AWS Region as the build project. Specify the buildspec + // file using its ARN (for example, arn:aws:s3:::my-codebuild-sample2/buildspec.yml). + // If this value is not provided or is set to an empty string, the source code + // must contain a buildspec file in its root directory. For more information, + // see Buildspec File Name and Storage Location (https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec-ref-name-storage). + BuildspecOverride *string `locationName:"buildspecOverride" type:"string"` - Message_ *string `locationName:"message" type:"string"` -} + // A ProjectCache object that specifies cache overrides. + CacheOverride *ProjectCache `locationName:"cacheOverride" type:"structure"` -// String returns the string representation -func (s ResourceNotFoundException) String() string { - return awsutil.Prettify(s) -} + // The name of a certificate for this batch build that overrides the one specified + // in the batch build project. + CertificateOverride *string `locationName:"certificateOverride" type:"string"` -// GoString returns the string representation -func (s ResourceNotFoundException) GoString() string { - return s.String() -} + // The name of a compute type for this batch build that overrides the one specified + // in the batch build project. + ComputeTypeOverride *string `locationName:"computeTypeOverride" type:"string" enum:"ComputeType"` -func newErrorResourceNotFoundException(v protocol.ResponseMetadata) error { - return &ResourceNotFoundException{ - RespMetadata: v, - } -} + // The AWS Key Management Service (AWS KMS) customer master key (CMK) that overrides + // the one specified in the batch build project. The CMK key encrypts the build + // output artifacts. + // + // You can use a cross-account KMS key to encrypt the build output artifacts + // if your service role has permission to that key. + // + // You can specify either the Amazon Resource Name (ARN) of the CMK or, if available, + // the CMK's alias (using the format alias/alias-name ). + EncryptionKeyOverride *string `locationName:"encryptionKeyOverride" min:"1" type:"string"` -// Code returns the exception type name. -func (s *ResourceNotFoundException) Code() string { - return "ResourceNotFoundException" -} + // A container type for this batch build that overrides the one specified in + // the batch build project. + EnvironmentTypeOverride *string `locationName:"environmentTypeOverride" type:"string" enum:"EnvironmentType"` -// Message returns the exception's message. -func (s *ResourceNotFoundException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} + // An array of EnvironmentVariable objects that override, or add to, the environment + // variables defined in the batch build project. + EnvironmentVariablesOverride []*EnvironmentVariable `locationName:"environmentVariablesOverride" type:"list"` -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ResourceNotFoundException) OrigErr() error { - return nil -} + // The user-defined depth of history, with a minimum value of 0, that overrides, + // for this batch build only, any previous depth of history defined in the batch + // build project. + GitCloneDepthOverride *int64 `locationName:"gitCloneDepthOverride" type:"integer"` -func (s *ResourceNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", s.Code(), s.Message()) -} + // A GitSubmodulesConfig object that overrides the Git submodules configuration + // for this batch build. + GitSubmodulesConfigOverride *GitSubmodulesConfig `locationName:"gitSubmodulesConfigOverride" type:"structure"` -// Status code returns the HTTP status code for the request's response error. -func (s *ResourceNotFoundException) StatusCode() int { - return s.RespMetadata.StatusCode -} + // A unique, case sensitive identifier you provide to ensure the idempotency + // of the StartBuildBatch request. The token is included in the StartBuildBatch + // request and is valid for five minutes. If you repeat the StartBuildBatch + // request with the same token, but change a parameter, AWS CodeBuild returns + // a parameter mismatch error. + IdempotencyToken *string `locationName:"idempotencyToken" type:"string"` -// RequestID returns the service's response RequestID for request. -func (s *ResourceNotFoundException) RequestID() string { - return s.RespMetadata.RequestID -} + // The name of an image for this batch build that overrides the one specified + // in the batch build project. + ImageOverride *string `locationName:"imageOverride" min:"1" type:"string"` -// Information about S3 logs for a build project. -type S3LogsConfig struct { - _ struct{} `type:"structure"` + // The type of credentials AWS CodeBuild uses to pull images in your batch build. + // There are two valid values: + // + // CODEBUILD + // + // Specifies that AWS CodeBuild uses its own credentials. This requires that + // you modify your ECR repository policy to trust AWS CodeBuild's service principal. + // + // SERVICE_ROLE + // + // Specifies that AWS CodeBuild uses your build project's service role. + // + // When using a cross-account or private registry image, you must use SERVICE_ROLE + // credentials. When using an AWS CodeBuild curated image, you must use CODEBUILD + // credentials. + ImagePullCredentialsTypeOverride *string `locationName:"imagePullCredentialsTypeOverride" type:"string" enum:"ImagePullCredentialsType"` - // Set to true if you do not want your S3 build log output encrypted. By default - // S3 build logs are encrypted. - EncryptionDisabled *bool `locationName:"encryptionDisabled" type:"boolean"` + // Enable this flag to override the insecure SSL setting that is specified in + // the batch build project. The insecure SSL setting determines whether to ignore + // SSL warnings while connecting to the project source code. This override applies + // only if the build's source is GitHub Enterprise. + InsecureSslOverride *bool `locationName:"insecureSslOverride" type:"boolean"` - // The ARN of an S3 bucket and the path prefix for S3 logs. If your Amazon S3 - // bucket name is my-bucket, and your path prefix is build-log, then acceptable - // formats are my-bucket/build-log or arn:aws:s3:::my-bucket/build-log. - Location *string `locationName:"location" type:"string"` + // A LogsConfig object that override the log settings defined in the batch build + // project. + LogsConfigOverride *LogsConfig `locationName:"logsConfigOverride" type:"structure"` - // The current status of the S3 build logs. Valid values are: + // Enable this flag to override privileged mode in the batch build project. + PrivilegedModeOverride *bool `locationName:"privilegedModeOverride" type:"boolean"` + + // The name of the project. // - // * ENABLED: S3 build logs are enabled for this build project. + // ProjectName is a required field + ProjectName *string `locationName:"projectName" min:"1" type:"string" required:"true"` + + // The number of minutes a batch build is allowed to be queued before it times + // out. + QueuedTimeoutInMinutesOverride *int64 `locationName:"queuedTimeoutInMinutesOverride" min:"5" type:"integer"` + + // A RegistryCredential object that overrides credentials for access to a private + // registry. + RegistryCredentialOverride *RegistryCredential `locationName:"registryCredentialOverride" type:"structure"` + + // Set to true to report to your source provider the status of a batch build's + // start and completion. If you use this option with a source provider other + // than GitHub, GitHub Enterprise, or Bitbucket, an invalidInputException is + // thrown. // - // * DISABLED: S3 build logs are not enabled for this build project. + // The status of a build triggered by a webhook is always reported to your source + // provider. + ReportBuildBatchStatusOverride *bool `locationName:"reportBuildBatchStatusOverride" type:"boolean"` + + // An array of ProjectArtifacts objects that override the secondary artifacts + // defined in the batch build project. + SecondaryArtifactsOverride []*ProjectArtifacts `locationName:"secondaryArtifactsOverride" type:"list"` + + // An array of ProjectSource objects that override the secondary sources defined + // in the batch build project. + SecondarySourcesOverride []*ProjectSource `locationName:"secondarySourcesOverride" type:"list"` + + // An array of ProjectSourceVersion objects that override the secondary source + // versions in the batch build project. + SecondarySourcesVersionOverride []*ProjectSourceVersion `locationName:"secondarySourcesVersionOverride" type:"list"` + + // The name of a service role for this batch build that overrides the one specified + // in the batch build project. + ServiceRoleOverride *string `locationName:"serviceRoleOverride" min:"1" type:"string"` + + // A SourceAuth object that overrides the one defined in the batch build project. + // This override applies only if the build project's source is BitBucket or + // GitHub. + SourceAuthOverride *SourceAuth `locationName:"sourceAuthOverride" type:"structure"` + + // A location that overrides, for this batch build, the source location defined + // in the batch build project. + SourceLocationOverride *string `locationName:"sourceLocationOverride" type:"string"` + + // The source input type that overrides the source input defined in the batch + // build project. + SourceTypeOverride *string `locationName:"sourceTypeOverride" type:"string" enum:"SourceType"` + + // The version of the batch build input to be built, for this build only. If + // not specified, the latest version is used. If specified, the contents depends + // on the source provider: // - // Status is a required field - Status *string `locationName:"status" type:"string" required:"true" enum:"LogsConfigStatusType"` + // AWS CodeCommit + // + // The commit ID, branch, or Git tag to use. + // + // GitHub + // + // The commit ID, pull request ID, branch name, or tag name that corresponds + // to the version of the source code you want to build. If a pull request ID + // is specified, it must use the format pr/pull-request-ID (for example pr/25). + // If a branch name is specified, the branch's HEAD commit ID is used. If not + // specified, the default branch's HEAD commit ID is used. + // + // Bitbucket + // + // The commit ID, branch name, or tag name that corresponds to the version of + // the source code you want to build. If a branch name is specified, the branch's + // HEAD commit ID is used. If not specified, the default branch's HEAD commit + // ID is used. + // + // Amazon Simple Storage Service (Amazon S3) + // + // The version ID of the object that represents the build input ZIP file to + // use. + // + // If sourceVersion is specified at the project level, then this sourceVersion + // (at the build level) takes precedence. + // + // For more information, see Source Version Sample with CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/sample-source-version.html) + // in the AWS CodeBuild User Guide. + SourceVersion *string `locationName:"sourceVersion" type:"string"` } // String returns the string representation -func (s S3LogsConfig) String() string { +func (s StartBuildBatchInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s S3LogsConfig) GoString() string { +func (s StartBuildBatchInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *S3LogsConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "S3LogsConfig"} - if s.Status == nil { - invalidParams.Add(request.NewErrParamRequired("Status")) +func (s *StartBuildBatchInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StartBuildBatchInput"} + if s.BuildTimeoutInMinutesOverride != nil && *s.BuildTimeoutInMinutesOverride < 5 { + invalidParams.Add(request.NewErrParamMinValue("BuildTimeoutInMinutesOverride", 5)) + } + if s.EncryptionKeyOverride != nil && len(*s.EncryptionKeyOverride) < 1 { + invalidParams.Add(request.NewErrParamMinLen("EncryptionKeyOverride", 1)) + } + if s.ImageOverride != nil && len(*s.ImageOverride) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ImageOverride", 1)) + } + if s.ProjectName == nil { + invalidParams.Add(request.NewErrParamRequired("ProjectName")) + } + if s.ProjectName != nil && len(*s.ProjectName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ProjectName", 1)) + } + if s.QueuedTimeoutInMinutesOverride != nil && *s.QueuedTimeoutInMinutesOverride < 5 { + invalidParams.Add(request.NewErrParamMinValue("QueuedTimeoutInMinutesOverride", 5)) + } + if s.ServiceRoleOverride != nil && len(*s.ServiceRoleOverride) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ServiceRoleOverride", 1)) + } + if s.ArtifactsOverride != nil { + if err := s.ArtifactsOverride.Validate(); err != nil { + invalidParams.AddNested("ArtifactsOverride", err.(request.ErrInvalidParams)) + } + } + if s.BuildBatchConfigOverride != nil { + if err := s.BuildBatchConfigOverride.Validate(); err != nil { + invalidParams.AddNested("BuildBatchConfigOverride", err.(request.ErrInvalidParams)) + } + } + if s.CacheOverride != nil { + if err := s.CacheOverride.Validate(); err != nil { + invalidParams.AddNested("CacheOverride", err.(request.ErrInvalidParams)) + } + } + if s.EnvironmentVariablesOverride != nil { + for i, v := range s.EnvironmentVariablesOverride { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "EnvironmentVariablesOverride", i), err.(request.ErrInvalidParams)) + } + } + } + if s.GitSubmodulesConfigOverride != nil { + if err := s.GitSubmodulesConfigOverride.Validate(); err != nil { + invalidParams.AddNested("GitSubmodulesConfigOverride", err.(request.ErrInvalidParams)) + } + } + if s.LogsConfigOverride != nil { + if err := s.LogsConfigOverride.Validate(); err != nil { + invalidParams.AddNested("LogsConfigOverride", err.(request.ErrInvalidParams)) + } + } + if s.RegistryCredentialOverride != nil { + if err := s.RegistryCredentialOverride.Validate(); err != nil { + invalidParams.AddNested("RegistryCredentialOverride", err.(request.ErrInvalidParams)) + } + } + if s.SecondaryArtifactsOverride != nil { + for i, v := range s.SecondaryArtifactsOverride { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "SecondaryArtifactsOverride", i), err.(request.ErrInvalidParams)) + } + } + } + if s.SecondarySourcesOverride != nil { + for i, v := range s.SecondarySourcesOverride { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "SecondarySourcesOverride", i), err.(request.ErrInvalidParams)) + } + } + } + if s.SecondarySourcesVersionOverride != nil { + for i, v := range s.SecondarySourcesVersionOverride { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "SecondarySourcesVersionOverride", i), err.(request.ErrInvalidParams)) + } + } + } + if s.SourceAuthOverride != nil { + if err := s.SourceAuthOverride.Validate(); err != nil { + invalidParams.AddNested("SourceAuthOverride", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -8422,204 +12219,206 @@ func (s *S3LogsConfig) Validate() error { return nil } -// SetEncryptionDisabled sets the EncryptionDisabled field's value. -func (s *S3LogsConfig) SetEncryptionDisabled(v bool) *S3LogsConfig { - s.EncryptionDisabled = &v +// SetArtifactsOverride sets the ArtifactsOverride field's value. +func (s *StartBuildBatchInput) SetArtifactsOverride(v *ProjectArtifacts) *StartBuildBatchInput { + s.ArtifactsOverride = v return s } -// SetLocation sets the Location field's value. -func (s *S3LogsConfig) SetLocation(v string) *S3LogsConfig { - s.Location = &v +// SetBuildBatchConfigOverride sets the BuildBatchConfigOverride field's value. +func (s *StartBuildBatchInput) SetBuildBatchConfigOverride(v *ProjectBuildBatchConfig) *StartBuildBatchInput { + s.BuildBatchConfigOverride = v return s } -// SetStatus sets the Status field's value. -func (s *S3LogsConfig) SetStatus(v string) *S3LogsConfig { - s.Status = &v +// SetBuildTimeoutInMinutesOverride sets the BuildTimeoutInMinutesOverride field's value. +func (s *StartBuildBatchInput) SetBuildTimeoutInMinutesOverride(v int64) *StartBuildBatchInput { + s.BuildTimeoutInMinutesOverride = &v return s } -// Information about the S3 bucket where the raw data of a report are exported. -type S3ReportExportConfig struct { - _ struct{} `type:"structure"` - - // The name of the S3 bucket where the raw data of a report are exported. - Bucket *string `locationName:"bucket" min:"1" type:"string"` - - // A boolean value that specifies if the results of a report are encrypted. - EncryptionDisabled *bool `locationName:"encryptionDisabled" type:"boolean"` - - // The encryption key for the report's encrypted raw data. - EncryptionKey *string `locationName:"encryptionKey" min:"1" type:"string"` - - // The type of build output artifact to create. Valid values include: - // - // * NONE: AWS CodeBuild creates the raw data in the output bucket. This - // is the default if packaging is not specified. - // - // * ZIP: AWS CodeBuild creates a ZIP file with the raw data in the output - // bucket. - Packaging *string `locationName:"packaging" type:"string" enum:"ReportPackagingType"` +// SetBuildspecOverride sets the BuildspecOverride field's value. +func (s *StartBuildBatchInput) SetBuildspecOverride(v string) *StartBuildBatchInput { + s.BuildspecOverride = &v + return s +} - // The path to the exported report's raw data results. - Path *string `locationName:"path" type:"string"` +// SetCacheOverride sets the CacheOverride field's value. +func (s *StartBuildBatchInput) SetCacheOverride(v *ProjectCache) *StartBuildBatchInput { + s.CacheOverride = v + return s } -// String returns the string representation -func (s S3ReportExportConfig) String() string { - return awsutil.Prettify(s) +// SetCertificateOverride sets the CertificateOverride field's value. +func (s *StartBuildBatchInput) SetCertificateOverride(v string) *StartBuildBatchInput { + s.CertificateOverride = &v + return s } -// GoString returns the string representation -func (s S3ReportExportConfig) GoString() string { - return s.String() +// SetComputeTypeOverride sets the ComputeTypeOverride field's value. +func (s *StartBuildBatchInput) SetComputeTypeOverride(v string) *StartBuildBatchInput { + s.ComputeTypeOverride = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *S3ReportExportConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "S3ReportExportConfig"} - if s.Bucket != nil && len(*s.Bucket) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) - } - if s.EncryptionKey != nil && len(*s.EncryptionKey) < 1 { - invalidParams.Add(request.NewErrParamMinLen("EncryptionKey", 1)) - } +// SetEncryptionKeyOverride sets the EncryptionKeyOverride field's value. +func (s *StartBuildBatchInput) SetEncryptionKeyOverride(v string) *StartBuildBatchInput { + s.EncryptionKeyOverride = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetEnvironmentTypeOverride sets the EnvironmentTypeOverride field's value. +func (s *StartBuildBatchInput) SetEnvironmentTypeOverride(v string) *StartBuildBatchInput { + s.EnvironmentTypeOverride = &v + return s } -// SetBucket sets the Bucket field's value. -func (s *S3ReportExportConfig) SetBucket(v string) *S3ReportExportConfig { - s.Bucket = &v +// SetEnvironmentVariablesOverride sets the EnvironmentVariablesOverride field's value. +func (s *StartBuildBatchInput) SetEnvironmentVariablesOverride(v []*EnvironmentVariable) *StartBuildBatchInput { + s.EnvironmentVariablesOverride = v return s } -// SetEncryptionDisabled sets the EncryptionDisabled field's value. -func (s *S3ReportExportConfig) SetEncryptionDisabled(v bool) *S3ReportExportConfig { - s.EncryptionDisabled = &v +// SetGitCloneDepthOverride sets the GitCloneDepthOverride field's value. +func (s *StartBuildBatchInput) SetGitCloneDepthOverride(v int64) *StartBuildBatchInput { + s.GitCloneDepthOverride = &v return s } -// SetEncryptionKey sets the EncryptionKey field's value. -func (s *S3ReportExportConfig) SetEncryptionKey(v string) *S3ReportExportConfig { - s.EncryptionKey = &v +// SetGitSubmodulesConfigOverride sets the GitSubmodulesConfigOverride field's value. +func (s *StartBuildBatchInput) SetGitSubmodulesConfigOverride(v *GitSubmodulesConfig) *StartBuildBatchInput { + s.GitSubmodulesConfigOverride = v return s } -// SetPackaging sets the Packaging field's value. -func (s *S3ReportExportConfig) SetPackaging(v string) *S3ReportExportConfig { - s.Packaging = &v +// SetIdempotencyToken sets the IdempotencyToken field's value. +func (s *StartBuildBatchInput) SetIdempotencyToken(v string) *StartBuildBatchInput { + s.IdempotencyToken = &v return s } -// SetPath sets the Path field's value. -func (s *S3ReportExportConfig) SetPath(v string) *S3ReportExportConfig { - s.Path = &v +// SetImageOverride sets the ImageOverride field's value. +func (s *StartBuildBatchInput) SetImageOverride(v string) *StartBuildBatchInput { + s.ImageOverride = &v return s } -// Information about the authorization settings for AWS CodeBuild to access -// the source code to be built. -// -// This information is for the AWS CodeBuild console's use only. Your code should -// not get or set this information directly. -type SourceAuth struct { - _ struct{} `type:"structure"` +// SetImagePullCredentialsTypeOverride sets the ImagePullCredentialsTypeOverride field's value. +func (s *StartBuildBatchInput) SetImagePullCredentialsTypeOverride(v string) *StartBuildBatchInput { + s.ImagePullCredentialsTypeOverride = &v + return s +} - // The resource value that applies to the specified authorization type. - Resource *string `locationName:"resource" type:"string"` +// SetInsecureSslOverride sets the InsecureSslOverride field's value. +func (s *StartBuildBatchInput) SetInsecureSslOverride(v bool) *StartBuildBatchInput { + s.InsecureSslOverride = &v + return s +} - // - // This data type is deprecated and is no longer accurate or used. - // - // The authorization type to use. The only valid value is OAUTH, which represents - // the OAuth authorization type. - // - // Type is a required field - Type *string `locationName:"type" type:"string" required:"true" enum:"SourceAuthType"` +// SetLogsConfigOverride sets the LogsConfigOverride field's value. +func (s *StartBuildBatchInput) SetLogsConfigOverride(v *LogsConfig) *StartBuildBatchInput { + s.LogsConfigOverride = v + return s } -// String returns the string representation -func (s SourceAuth) String() string { - return awsutil.Prettify(s) +// SetPrivilegedModeOverride sets the PrivilegedModeOverride field's value. +func (s *StartBuildBatchInput) SetPrivilegedModeOverride(v bool) *StartBuildBatchInput { + s.PrivilegedModeOverride = &v + return s } -// GoString returns the string representation -func (s SourceAuth) GoString() string { - return s.String() +// SetProjectName sets the ProjectName field's value. +func (s *StartBuildBatchInput) SetProjectName(v string) *StartBuildBatchInput { + s.ProjectName = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *SourceAuth) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SourceAuth"} - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } +// SetQueuedTimeoutInMinutesOverride sets the QueuedTimeoutInMinutesOverride field's value. +func (s *StartBuildBatchInput) SetQueuedTimeoutInMinutesOverride(v int64) *StartBuildBatchInput { + s.QueuedTimeoutInMinutesOverride = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetRegistryCredentialOverride sets the RegistryCredentialOverride field's value. +func (s *StartBuildBatchInput) SetRegistryCredentialOverride(v *RegistryCredential) *StartBuildBatchInput { + s.RegistryCredentialOverride = v + return s } -// SetResource sets the Resource field's value. -func (s *SourceAuth) SetResource(v string) *SourceAuth { - s.Resource = &v +// SetReportBuildBatchStatusOverride sets the ReportBuildBatchStatusOverride field's value. +func (s *StartBuildBatchInput) SetReportBuildBatchStatusOverride(v bool) *StartBuildBatchInput { + s.ReportBuildBatchStatusOverride = &v return s } -// SetType sets the Type field's value. -func (s *SourceAuth) SetType(v string) *SourceAuth { - s.Type = &v +// SetSecondaryArtifactsOverride sets the SecondaryArtifactsOverride field's value. +func (s *StartBuildBatchInput) SetSecondaryArtifactsOverride(v []*ProjectArtifacts) *StartBuildBatchInput { + s.SecondaryArtifactsOverride = v return s } -// Information about the credentials for a GitHub, GitHub Enterprise, or Bitbucket -// repository. -type SourceCredentialsInfo struct { - _ struct{} `type:"structure"` +// SetSecondarySourcesOverride sets the SecondarySourcesOverride field's value. +func (s *StartBuildBatchInput) SetSecondarySourcesOverride(v []*ProjectSource) *StartBuildBatchInput { + s.SecondarySourcesOverride = v + return s +} - // The Amazon Resource Name (ARN) of the token. - Arn *string `locationName:"arn" min:"1" type:"string"` +// SetSecondarySourcesVersionOverride sets the SecondarySourcesVersionOverride field's value. +func (s *StartBuildBatchInput) SetSecondarySourcesVersionOverride(v []*ProjectSourceVersion) *StartBuildBatchInput { + s.SecondarySourcesVersionOverride = v + return s +} - // The type of authentication used by the credentials. Valid options are OAUTH, - // BASIC_AUTH, or PERSONAL_ACCESS_TOKEN. - AuthType *string `locationName:"authType" type:"string" enum:"AuthType"` +// SetServiceRoleOverride sets the ServiceRoleOverride field's value. +func (s *StartBuildBatchInput) SetServiceRoleOverride(v string) *StartBuildBatchInput { + s.ServiceRoleOverride = &v + return s +} - // The type of source provider. The valid options are GITHUB, GITHUB_ENTERPRISE, - // or BITBUCKET. - ServerType *string `locationName:"serverType" type:"string" enum:"ServerType"` +// SetSourceAuthOverride sets the SourceAuthOverride field's value. +func (s *StartBuildBatchInput) SetSourceAuthOverride(v *SourceAuth) *StartBuildBatchInput { + s.SourceAuthOverride = v + return s } -// String returns the string representation -func (s SourceCredentialsInfo) String() string { - return awsutil.Prettify(s) +// SetSourceLocationOverride sets the SourceLocationOverride field's value. +func (s *StartBuildBatchInput) SetSourceLocationOverride(v string) *StartBuildBatchInput { + s.SourceLocationOverride = &v + return s } -// GoString returns the string representation -func (s SourceCredentialsInfo) GoString() string { - return s.String() +// SetSourceTypeOverride sets the SourceTypeOverride field's value. +func (s *StartBuildBatchInput) SetSourceTypeOverride(v string) *StartBuildBatchInput { + s.SourceTypeOverride = &v + return s } -// SetArn sets the Arn field's value. -func (s *SourceCredentialsInfo) SetArn(v string) *SourceCredentialsInfo { - s.Arn = &v +// SetSourceVersion sets the SourceVersion field's value. +func (s *StartBuildBatchInput) SetSourceVersion(v string) *StartBuildBatchInput { + s.SourceVersion = &v return s } -// SetAuthType sets the AuthType field's value. -func (s *SourceCredentialsInfo) SetAuthType(v string) *SourceCredentialsInfo { - s.AuthType = &v - return s +type StartBuildBatchOutput struct { + _ struct{} `type:"structure"` + + // A BuildBatch object that contains information about the batch build. + BuildBatch *BuildBatch `locationName:"buildBatch" type:"structure"` +} + +// String returns the string representation +func (s StartBuildBatchOutput) String() string { + return awsutil.Prettify(s) } -// SetServerType sets the ServerType field's value. -func (s *SourceCredentialsInfo) SetServerType(v string) *SourceCredentialsInfo { - s.ServerType = &v +// GoString returns the string representation +func (s StartBuildBatchOutput) GoString() string { + return s.String() +} + +// SetBuildBatch sets the BuildBatch field's value. +func (s *StartBuildBatchOutput) SetBuildBatch(v *BuildBatch) *StartBuildBatchOutput { + s.BuildBatch = v return s } @@ -8630,6 +12429,11 @@ type StartBuildInput struct { // ones already defined in the build project. ArtifactsOverride *ProjectArtifacts `locationName:"artifactsOverride" type:"structure"` + // Contains information that defines how the build project reports the build + // status to the source provider. This option is only used when the source provider + // is GITHUB, GITHUB_ENTERPRISE, or BITBUCKET. + BuildStatusConfigOverride *BuildStatusConfig `locationName:"buildStatusConfigOverride" type:"structure"` + // A buildspec file declaration that overrides, for this build only, the latest // one already defined in the build project. // @@ -8655,6 +12459,10 @@ type StartBuildInput struct { // in the build project. ComputeTypeOverride *string `locationName:"computeTypeOverride" type:"string" enum:"ComputeType"` + // Specifies if session debugging is enabled for this build. For more information, + // see Viewing a running build in Session Manager (https://docs.aws.amazon.com/codebuild/latest/userguide/session-manager.html). + DebugSessionEnabled *bool `locationName:"debugSessionEnabled" type:"boolean"` + // The AWS Key Management Service (AWS KMS) customer master key (CMK) that overrides // the one specified in the build project. The CMK key encrypts the build output // artifacts. @@ -8684,7 +12492,7 @@ type StartBuildInput struct { // A unique, case sensitive identifier you provide to ensure the idempotency // of the StartBuild request. The token is included in the StartBuild request - // and is valid for 12 hours. If you repeat the StartBuild request with the + // and is valid for 5 minutes. If you repeat the StartBuild request with the // same token, but change a parameter, AWS CodeBuild returns a parameter mismatch // error. IdempotencyToken *string `locationName:"idempotencyToken" type:"string"` @@ -8696,12 +12504,14 @@ type StartBuildInput struct { // The type of credentials AWS CodeBuild uses to pull images in your build. // There are two valid values: // - // * CODEBUILD specifies that AWS CodeBuild uses its own credentials. This - // requires that you modify your ECR repository policy to trust AWS CodeBuild's - // service principal. + // CODEBUILD // - // * SERVICE_ROLE specifies that AWS CodeBuild uses your build project's - // service role. + // Specifies that AWS CodeBuild uses its own credentials. This requires that + // you modify your ECR repository policy to trust AWS CodeBuild's service principal. + // + // SERVICE_ROLE + // + // Specifies that AWS CodeBuild uses your build project's service role. // // When using a cross-account or private registry image, you must use SERVICE_ROLE // credentials. When using an AWS CodeBuild curated image, you must use CODEBUILD @@ -8767,25 +12577,33 @@ type StartBuildInput struct { // in the build project. SourceTypeOverride *string `locationName:"sourceTypeOverride" type:"string" enum:"SourceType"` - // A version of the build input to be built, for this build only. If not specified, - // the latest version is used. If specified, must be one of: + // The version of the build input to be built, for this build only. If not specified, + // the latest version is used. If specified, the contents depends on the source + // provider: // - // * For AWS CodeCommit: the commit ID, branch, or Git tag to use. + // AWS CodeCommit // - // * For GitHub: the commit ID, pull request ID, branch name, or tag name - // that corresponds to the version of the source code you want to build. - // If a pull request ID is specified, it must use the format pr/pull-request-ID - // (for example pr/25). If a branch name is specified, the branch's HEAD - // commit ID is used. If not specified, the default branch's HEAD commit - // ID is used. + // The commit ID, branch, or Git tag to use. // - // * For Bitbucket: the commit ID, branch name, or tag name that corresponds - // to the version of the source code you want to build. If a branch name - // is specified, the branch's HEAD commit ID is used. If not specified, the - // default branch's HEAD commit ID is used. + // GitHub // - // * For Amazon Simple Storage Service (Amazon S3): the version ID of the - // object that represents the build input ZIP file to use. + // The commit ID, pull request ID, branch name, or tag name that corresponds + // to the version of the source code you want to build. If a pull request ID + // is specified, it must use the format pr/pull-request-ID (for example pr/25). + // If a branch name is specified, the branch's HEAD commit ID is used. If not + // specified, the default branch's HEAD commit ID is used. + // + // Bitbucket + // + // The commit ID, branch name, or tag name that corresponds to the version of + // the source code you want to build. If a branch name is specified, the branch's + // HEAD commit ID is used. If not specified, the default branch's HEAD commit + // ID is used. + // + // Amazon Simple Storage Service (Amazon S3) + // + // The version ID of the object that represents the build input ZIP file to + // use. // // If sourceVersion is specified at the project level, then this sourceVersion // (at the build level) takes precedence. @@ -8916,6 +12734,12 @@ func (s *StartBuildInput) SetArtifactsOverride(v *ProjectArtifacts) *StartBuildI return s } +// SetBuildStatusConfigOverride sets the BuildStatusConfigOverride field's value. +func (s *StartBuildInput) SetBuildStatusConfigOverride(v *BuildStatusConfig) *StartBuildInput { + s.BuildStatusConfigOverride = v + return s +} + // SetBuildspecOverride sets the BuildspecOverride field's value. func (s *StartBuildInput) SetBuildspecOverride(v string) *StartBuildInput { s.BuildspecOverride = &v @@ -8940,6 +12764,12 @@ func (s *StartBuildInput) SetComputeTypeOverride(v string) *StartBuildInput { return s } +// SetDebugSessionEnabled sets the DebugSessionEnabled field's value. +func (s *StartBuildInput) SetDebugSessionEnabled(v bool) *StartBuildInput { + s.DebugSessionEnabled = &v + return s +} + // SetEncryptionKeyOverride sets the EncryptionKeyOverride field's value. func (s *StartBuildInput) SetEncryptionKeyOverride(v string) *StartBuildInput { s.EncryptionKeyOverride = &v @@ -9107,6 +12937,70 @@ func (s *StartBuildOutput) SetBuild(v *Build) *StartBuildOutput { return s } +type StopBuildBatchInput struct { + _ struct{} `type:"structure"` + + // The identifier of the batch build to stop. + // + // Id is a required field + Id *string `locationName:"id" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s StopBuildBatchInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopBuildBatchInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StopBuildBatchInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StopBuildBatchInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *StopBuildBatchInput) SetId(v string) *StopBuildBatchInput { + s.Id = &v + return s +} + +type StopBuildBatchOutput struct { + _ struct{} `type:"structure"` + + // Contains information about a batch build. + BuildBatch *BuildBatch `locationName:"buildBatch" type:"structure"` +} + +// String returns the string representation +func (s StopBuildBatchOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopBuildBatchOutput) GoString() string { + return s.String() +} + +// SetBuildBatch sets the BuildBatch field's value. +func (s *StopBuildBatchOutput) SetBuildBatch(v *BuildBatch) *StopBuildBatchOutput { + s.BuildBatch = v + return s +} + type StopBuildInput struct { _ struct{} `type:"structure"` @@ -9181,7 +13075,7 @@ type Tag struct { Key *string `locationName:"key" min:"1" type:"string"` // The tag's value. - Value *string `locationName:"value" min:"1" type:"string"` + Value *string `locationName:"value" type:"string"` } // String returns the string representation @@ -9200,9 +13094,6 @@ func (s *Tag) Validate() error { if s.Key != nil && len(*s.Key) < 1 { invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } - if s.Value != nil && len(*s.Value) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Value", 1)) - } if invalidParams.Len() > 0 { return invalidParams @@ -9400,6 +13291,9 @@ type UpdateProjectInput struct { // build badge. BadgeEnabled *bool `locationName:"badgeEnabled" type:"boolean"` + // Contains configuration information about a batch build project. + BuildBatchConfig *ProjectBuildBatchConfig `locationName:"buildBatchConfig" type:"structure"` + // Stores recently used information so that it can be quickly accessed at a // later time. Cache *ProjectCache `locationName:"cache" type:"structure"` @@ -9486,7 +13380,7 @@ type UpdateProjectInput struct { // in the AWS CodeBuild User Guide. SourceVersion *string `locationName:"sourceVersion" type:"string"` - // The replacement set of tags for this build project. + // An updated list of tag key and value pairs associated with this build project. // // These tags are available for use by AWS services that support AWS CodeBuild // build project tags. @@ -9536,6 +13430,11 @@ func (s *UpdateProjectInput) Validate() error { invalidParams.AddNested("Artifacts", err.(request.ErrInvalidParams)) } } + if s.BuildBatchConfig != nil { + if err := s.BuildBatchConfig.Validate(); err != nil { + invalidParams.AddNested("BuildBatchConfig", err.(request.ErrInvalidParams)) + } + } if s.Cache != nil { if err := s.Cache.Validate(); err != nil { invalidParams.AddNested("Cache", err.(request.ErrInvalidParams)) @@ -9620,6 +13519,12 @@ func (s *UpdateProjectInput) SetBadgeEnabled(v bool) *UpdateProjectInput { return s } +// SetBuildBatchConfig sets the BuildBatchConfig field's value. +func (s *UpdateProjectInput) SetBuildBatchConfig(v *ProjectBuildBatchConfig) *UpdateProjectInput { + s.BuildBatchConfig = v + return s +} + // SetCache sets the Cache field's value. func (s *UpdateProjectInput) SetCache(v *ProjectCache) *UpdateProjectInput { s.Cache = v @@ -9759,6 +13664,12 @@ type UpdateReportGroupInput struct { // // * NO_EXPORT: The report results are not exported. ExportConfig *ReportExportConfig `locationName:"exportConfig" type:"structure"` + + // An updated list of tag key and value pairs associated with this report group. + // + // These tags are available for use by AWS services that support AWS CodeBuild + // report group tags. + Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation @@ -9785,6 +13696,16 @@ func (s *UpdateReportGroupInput) Validate() error { invalidParams.AddNested("ExportConfig", err.(request.ErrInvalidParams)) } } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -9804,6 +13725,12 @@ func (s *UpdateReportGroupInput) SetExportConfig(v *ReportExportConfig) *UpdateR return s } +// SetTags sets the Tags field's value. +func (s *UpdateReportGroupInput) SetTags(v []*Tag) *UpdateReportGroupInput { + s.Tags = v + return s +} + type UpdateReportGroupOutput struct { _ struct{} `type:"structure"` @@ -9838,6 +13765,9 @@ type UpdateWebhookInput struct { // It is recommended that you use filterGroups instead of branchFilter. BranchFilter *string `locationName:"branchFilter" type:"string"` + // Specifies the type of build this webhook will trigger. + BuildType *string `locationName:"buildType" type:"string" enum:"WebhookBuildType"` + // An array of arrays of WebhookFilter objects used to determine if a webhook // event can trigger a build. A filter group must contain at least one EVENT // WebhookFilter. @@ -9886,6 +13816,12 @@ func (s *UpdateWebhookInput) SetBranchFilter(v string) *UpdateWebhookInput { return s } +// SetBuildType sets the BuildType field's value. +func (s *UpdateWebhookInput) SetBuildType(v string) *UpdateWebhookInput { + s.BuildType = &v + return s +} + // SetFilterGroups sets the FilterGroups field's value. func (s *UpdateWebhookInput) SetFilterGroups(v [][]*WebhookFilter) *UpdateWebhookInput { s.FilterGroups = v @@ -9996,6 +13932,9 @@ type Webhook struct { // It is recommended that you use filterGroups instead of branchFilter. BranchFilter *string `locationName:"branchFilter" type:"string"` + // Specifies the type of build this webhook will trigger. + BuildType *string `locationName:"buildType" type:"string" enum:"WebhookBuildType"` + // An array of arrays of WebhookFilter objects used to determine which webhooks // are triggered. At least one WebhookFilter in the array must specify EVENT // as its type. @@ -10036,6 +13975,12 @@ func (s *Webhook) SetBranchFilter(v string) *Webhook { return s } +// SetBuildType sets the BuildType field's value. +func (s *Webhook) SetBuildType(v string) *Webhook { + s.BuildType = &v + return s +} + // SetFilterGroups sets the FilterGroups field's value. func (s *Webhook) SetFilterGroups(v [][]*WebhookFilter) *Webhook { s.FilterGroups = v @@ -10089,16 +14034,16 @@ type WebhookFilter struct { // Pattern is a required field Pattern *string `locationName:"pattern" type:"string" required:"true"` - // The type of webhook filter. There are five webhook filter types: EVENT, ACTOR_ACCOUNT_ID, - // HEAD_REF, BASE_REF, and FILE_PATH. + // The type of webhook filter. There are six webhook filter types: EVENT, ACTOR_ACCOUNT_ID, + // HEAD_REF, BASE_REF, FILE_PATH, and COMMIT_MESSAGE. // // EVENT // // A webhook event triggers a build when the provided pattern matches one of - // four event types: PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, and PULL_REQUEST_REOPENED. - // The EVENT patterns are specified as a comma-separated string. For example, - // PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED filters all push, pull request - // created, and pull request updated events. + // five event types: PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_REOPENED, + // and PULL_REQUEST_MERGED. The EVENT patterns are specified as a comma-separated + // string. For example, PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED filters + // all push, pull request created, and pull request updated events. // // The PULL_REQUEST_REOPENED works with GitHub and GitHub Enterprise only. // @@ -10127,7 +14072,18 @@ type WebhookFilter struct { // A webhook triggers a build when the path of a changed file matches the regular // expression pattern. // - // Works with GitHub and GitHub Enterprise push events only. + // Works with GitHub and Bitbucket events push and pull requests events. Also + // works with GitHub Enterprise push events, but does not work with GitHub Enterprise + // pull request events. + // + // COMMIT_MESSAGE + // + // A webhook triggers a build when the head commit message matches the regular + // expression pattern. + // + // Works with GitHub and Bitbucket events push and pull requests events. Also + // works with GitHub Enterprise push events, but does not work with GitHub Enterprise + // pull request events. // // Type is a required field Type *string `locationName:"type" type:"string" required:"true" enum:"WebhookFilterType"` @@ -10169,6 +14125,14 @@ const ( ArtifactNamespaceBuildId = "BUILD_ID" ) +// ArtifactNamespace_Values returns all elements of the ArtifactNamespace enum +func ArtifactNamespace_Values() []string { + return []string{ + ArtifactNamespaceNone, + ArtifactNamespaceBuildId, + } +} + const ( // ArtifactPackagingNone is a ArtifactPackaging enum value ArtifactPackagingNone = "NONE" @@ -10177,6 +14141,14 @@ const ( ArtifactPackagingZip = "ZIP" ) +// ArtifactPackaging_Values returns all elements of the ArtifactPackaging enum +func ArtifactPackaging_Values() []string { + return []string{ + ArtifactPackagingNone, + ArtifactPackagingZip, + } +} + const ( // ArtifactsTypeCodepipeline is a ArtifactsType enum value ArtifactsTypeCodepipeline = "CODEPIPELINE" @@ -10188,6 +14160,15 @@ const ( ArtifactsTypeNoArtifacts = "NO_ARTIFACTS" ) +// ArtifactsType_Values returns all elements of the ArtifactsType enum +func ArtifactsType_Values() []string { + return []string{ + ArtifactsTypeCodepipeline, + ArtifactsTypeS3, + ArtifactsTypeNoArtifacts, + } +} + const ( // AuthTypeOauth is a AuthType enum value AuthTypeOauth = "OAUTH" @@ -10199,6 +14180,51 @@ const ( AuthTypePersonalAccessToken = "PERSONAL_ACCESS_TOKEN" ) +// AuthType_Values returns all elements of the AuthType enum +func AuthType_Values() []string { + return []string{ + AuthTypeOauth, + AuthTypeBasicAuth, + AuthTypePersonalAccessToken, + } +} + +const ( + // BuildBatchPhaseTypeSubmitted is a BuildBatchPhaseType enum value + BuildBatchPhaseTypeSubmitted = "SUBMITTED" + + // BuildBatchPhaseTypeDownloadBatchspec is a BuildBatchPhaseType enum value + BuildBatchPhaseTypeDownloadBatchspec = "DOWNLOAD_BATCHSPEC" + + // BuildBatchPhaseTypeInProgress is a BuildBatchPhaseType enum value + BuildBatchPhaseTypeInProgress = "IN_PROGRESS" + + // BuildBatchPhaseTypeCombineArtifacts is a BuildBatchPhaseType enum value + BuildBatchPhaseTypeCombineArtifacts = "COMBINE_ARTIFACTS" + + // BuildBatchPhaseTypeSucceeded is a BuildBatchPhaseType enum value + BuildBatchPhaseTypeSucceeded = "SUCCEEDED" + + // BuildBatchPhaseTypeFailed is a BuildBatchPhaseType enum value + BuildBatchPhaseTypeFailed = "FAILED" + + // BuildBatchPhaseTypeStopped is a BuildBatchPhaseType enum value + BuildBatchPhaseTypeStopped = "STOPPED" +) + +// BuildBatchPhaseType_Values returns all elements of the BuildBatchPhaseType enum +func BuildBatchPhaseType_Values() []string { + return []string{ + BuildBatchPhaseTypeSubmitted, + BuildBatchPhaseTypeDownloadBatchspec, + BuildBatchPhaseTypeInProgress, + BuildBatchPhaseTypeCombineArtifacts, + BuildBatchPhaseTypeSucceeded, + BuildBatchPhaseTypeFailed, + BuildBatchPhaseTypeStopped, + } +} + const ( // BuildPhaseTypeSubmitted is a BuildPhaseType enum value BuildPhaseTypeSubmitted = "SUBMITTED" @@ -10234,6 +14260,23 @@ const ( BuildPhaseTypeCompleted = "COMPLETED" ) +// BuildPhaseType_Values returns all elements of the BuildPhaseType enum +func BuildPhaseType_Values() []string { + return []string{ + BuildPhaseTypeSubmitted, + BuildPhaseTypeQueued, + BuildPhaseTypeProvisioning, + BuildPhaseTypeDownloadSource, + BuildPhaseTypeInstall, + BuildPhaseTypePreBuild, + BuildPhaseTypeBuild, + BuildPhaseTypePostBuild, + BuildPhaseTypeUploadArtifacts, + BuildPhaseTypeFinalizing, + BuildPhaseTypeCompleted, + } +} + const ( // CacheModeLocalDockerLayerCache is a CacheMode enum value CacheModeLocalDockerLayerCache = "LOCAL_DOCKER_LAYER_CACHE" @@ -10245,6 +14288,15 @@ const ( CacheModeLocalCustomCache = "LOCAL_CUSTOM_CACHE" ) +// CacheMode_Values returns all elements of the CacheMode enum +func CacheMode_Values() []string { + return []string{ + CacheModeLocalDockerLayerCache, + CacheModeLocalSourceCache, + CacheModeLocalCustomCache, + } +} + const ( // CacheTypeNoCache is a CacheType enum value CacheTypeNoCache = "NO_CACHE" @@ -10256,6 +14308,15 @@ const ( CacheTypeLocal = "LOCAL" ) +// CacheType_Values returns all elements of the CacheType enum +func CacheType_Values() []string { + return []string{ + CacheTypeNoCache, + CacheTypeS3, + CacheTypeLocal, + } +} + const ( // ComputeTypeBuildGeneral1Small is a ComputeType enum value ComputeTypeBuildGeneral1Small = "BUILD_GENERAL1_SMALL" @@ -10270,11 +14331,28 @@ const ( ComputeTypeBuildGeneral12xlarge = "BUILD_GENERAL1_2XLARGE" ) +// ComputeType_Values returns all elements of the ComputeType enum +func ComputeType_Values() []string { + return []string{ + ComputeTypeBuildGeneral1Small, + ComputeTypeBuildGeneral1Medium, + ComputeTypeBuildGeneral1Large, + ComputeTypeBuildGeneral12xlarge, + } +} + const ( // CredentialProviderTypeSecretsManager is a CredentialProviderType enum value CredentialProviderTypeSecretsManager = "SECRETS_MANAGER" ) +// CredentialProviderType_Values returns all elements of the CredentialProviderType enum +func CredentialProviderType_Values() []string { + return []string{ + CredentialProviderTypeSecretsManager, + } +} + const ( // EnvironmentTypeWindowsContainer is a EnvironmentType enum value EnvironmentTypeWindowsContainer = "WINDOWS_CONTAINER" @@ -10287,8 +14365,22 @@ const ( // EnvironmentTypeArmContainer is a EnvironmentType enum value EnvironmentTypeArmContainer = "ARM_CONTAINER" + + // EnvironmentTypeWindowsServer2019Container is a EnvironmentType enum value + EnvironmentTypeWindowsServer2019Container = "WINDOWS_SERVER_2019_CONTAINER" ) +// EnvironmentType_Values returns all elements of the EnvironmentType enum +func EnvironmentType_Values() []string { + return []string{ + EnvironmentTypeWindowsContainer, + EnvironmentTypeLinuxContainer, + EnvironmentTypeLinuxGpuContainer, + EnvironmentTypeArmContainer, + EnvironmentTypeWindowsServer2019Container, + } +} + const ( // EnvironmentVariableTypePlaintext is a EnvironmentVariableType enum value EnvironmentVariableTypePlaintext = "PLAINTEXT" @@ -10300,11 +14392,27 @@ const ( EnvironmentVariableTypeSecretsManager = "SECRETS_MANAGER" ) +// EnvironmentVariableType_Values returns all elements of the EnvironmentVariableType enum +func EnvironmentVariableType_Values() []string { + return []string{ + EnvironmentVariableTypePlaintext, + EnvironmentVariableTypeParameterStore, + EnvironmentVariableTypeSecretsManager, + } +} + const ( // FileSystemTypeEfs is a FileSystemType enum value FileSystemTypeEfs = "EFS" ) +// FileSystemType_Values returns all elements of the FileSystemType enum +func FileSystemType_Values() []string { + return []string{ + FileSystemTypeEfs, + } +} + const ( // ImagePullCredentialsTypeCodebuild is a ImagePullCredentialsType enum value ImagePullCredentialsTypeCodebuild = "CODEBUILD" @@ -10313,6 +14421,14 @@ const ( ImagePullCredentialsTypeServiceRole = "SERVICE_ROLE" ) +// ImagePullCredentialsType_Values returns all elements of the ImagePullCredentialsType enum +func ImagePullCredentialsType_Values() []string { + return []string{ + ImagePullCredentialsTypeCodebuild, + ImagePullCredentialsTypeServiceRole, + } +} + const ( // LanguageTypeJava is a LanguageType enum value LanguageTypeJava = "JAVA" @@ -10345,6 +14461,22 @@ const ( LanguageTypePhp = "PHP" ) +// LanguageType_Values returns all elements of the LanguageType enum +func LanguageType_Values() []string { + return []string{ + LanguageTypeJava, + LanguageTypePython, + LanguageTypeNodeJs, + LanguageTypeRuby, + LanguageTypeGolang, + LanguageTypeDocker, + LanguageTypeAndroid, + LanguageTypeDotnet, + LanguageTypeBase, + LanguageTypePhp, + } +} + const ( // LogsConfigStatusTypeEnabled is a LogsConfigStatusType enum value LogsConfigStatusTypeEnabled = "ENABLED" @@ -10353,6 +14485,14 @@ const ( LogsConfigStatusTypeDisabled = "DISABLED" ) +// LogsConfigStatusType_Values returns all elements of the LogsConfigStatusType enum +func LogsConfigStatusType_Values() []string { + return []string{ + LogsConfigStatusTypeEnabled, + LogsConfigStatusTypeDisabled, + } +} + const ( // PlatformTypeDebian is a PlatformType enum value PlatformTypeDebian = "DEBIAN" @@ -10367,6 +14507,16 @@ const ( PlatformTypeWindowsServer = "WINDOWS_SERVER" ) +// PlatformType_Values returns all elements of the PlatformType enum +func PlatformType_Values() []string { + return []string{ + PlatformTypeDebian, + PlatformTypeAmazonLinux, + PlatformTypeUbuntu, + PlatformTypeWindowsServer, + } +} + const ( // ProjectSortByTypeName is a ProjectSortByType enum value ProjectSortByTypeName = "NAME" @@ -10378,6 +14528,31 @@ const ( ProjectSortByTypeLastModifiedTime = "LAST_MODIFIED_TIME" ) +// ProjectSortByType_Values returns all elements of the ProjectSortByType enum +func ProjectSortByType_Values() []string { + return []string{ + ProjectSortByTypeName, + ProjectSortByTypeCreatedTime, + ProjectSortByTypeLastModifiedTime, + } +} + +const ( + // ReportCodeCoverageSortByTypeLineCoveragePercentage is a ReportCodeCoverageSortByType enum value + ReportCodeCoverageSortByTypeLineCoveragePercentage = "LINE_COVERAGE_PERCENTAGE" + + // ReportCodeCoverageSortByTypeFilePath is a ReportCodeCoverageSortByType enum value + ReportCodeCoverageSortByTypeFilePath = "FILE_PATH" +) + +// ReportCodeCoverageSortByType_Values returns all elements of the ReportCodeCoverageSortByType enum +func ReportCodeCoverageSortByType_Values() []string { + return []string{ + ReportCodeCoverageSortByTypeLineCoveragePercentage, + ReportCodeCoverageSortByTypeFilePath, + } +} + const ( // ReportExportConfigTypeS3 is a ReportExportConfigType enum value ReportExportConfigTypeS3 = "S3" @@ -10386,6 +14561,14 @@ const ( ReportExportConfigTypeNoExport = "NO_EXPORT" ) +// ReportExportConfigType_Values returns all elements of the ReportExportConfigType enum +func ReportExportConfigType_Values() []string { + return []string{ + ReportExportConfigTypeS3, + ReportExportConfigTypeNoExport, + } +} + const ( // ReportGroupSortByTypeName is a ReportGroupSortByType enum value ReportGroupSortByTypeName = "NAME" @@ -10397,6 +14580,15 @@ const ( ReportGroupSortByTypeLastModifiedTime = "LAST_MODIFIED_TIME" ) +// ReportGroupSortByType_Values returns all elements of the ReportGroupSortByType enum +func ReportGroupSortByType_Values() []string { + return []string{ + ReportGroupSortByTypeName, + ReportGroupSortByTypeCreatedTime, + ReportGroupSortByTypeLastModifiedTime, + } +} + const ( // ReportPackagingTypeZip is a ReportPackagingType enum value ReportPackagingTypeZip = "ZIP" @@ -10405,6 +14597,14 @@ const ( ReportPackagingTypeNone = "NONE" ) +// ReportPackagingType_Values returns all elements of the ReportPackagingType enum +func ReportPackagingType_Values() []string { + return []string{ + ReportPackagingTypeZip, + ReportPackagingTypeNone, + } +} + const ( // ReportStatusTypeGenerating is a ReportStatusType enum value ReportStatusTypeGenerating = "GENERATING" @@ -10422,11 +14622,49 @@ const ( ReportStatusTypeDeleting = "DELETING" ) +// ReportStatusType_Values returns all elements of the ReportStatusType enum +func ReportStatusType_Values() []string { + return []string{ + ReportStatusTypeGenerating, + ReportStatusTypeSucceeded, + ReportStatusTypeFailed, + ReportStatusTypeIncomplete, + ReportStatusTypeDeleting, + } +} + const ( // ReportTypeTest is a ReportType enum value ReportTypeTest = "TEST" + + // ReportTypeCodeCoverage is a ReportType enum value + ReportTypeCodeCoverage = "CODE_COVERAGE" +) + +// ReportType_Values returns all elements of the ReportType enum +func ReportType_Values() []string { + return []string{ + ReportTypeTest, + ReportTypeCodeCoverage, + } +} + +const ( + // RetryBuildBatchTypeRetryAllBuilds is a RetryBuildBatchType enum value + RetryBuildBatchTypeRetryAllBuilds = "RETRY_ALL_BUILDS" + + // RetryBuildBatchTypeRetryFailedBuilds is a RetryBuildBatchType enum value + RetryBuildBatchTypeRetryFailedBuilds = "RETRY_FAILED_BUILDS" ) +// RetryBuildBatchType_Values returns all elements of the RetryBuildBatchType enum +func RetryBuildBatchType_Values() []string { + return []string{ + RetryBuildBatchTypeRetryAllBuilds, + RetryBuildBatchTypeRetryFailedBuilds, + } +} + const ( // ServerTypeGithub is a ServerType enum value ServerTypeGithub = "GITHUB" @@ -10438,6 +14676,15 @@ const ( ServerTypeGithubEnterprise = "GITHUB_ENTERPRISE" ) +// ServerType_Values returns all elements of the ServerType enum +func ServerType_Values() []string { + return []string{ + ServerTypeGithub, + ServerTypeBitbucket, + ServerTypeGithubEnterprise, + } +} + const ( // SharedResourceSortByTypeArn is a SharedResourceSortByType enum value SharedResourceSortByTypeArn = "ARN" @@ -10446,6 +14693,14 @@ const ( SharedResourceSortByTypeModifiedTime = "MODIFIED_TIME" ) +// SharedResourceSortByType_Values returns all elements of the SharedResourceSortByType enum +func SharedResourceSortByType_Values() []string { + return []string{ + SharedResourceSortByTypeArn, + SharedResourceSortByTypeModifiedTime, + } +} + const ( // SortOrderTypeAscending is a SortOrderType enum value SortOrderTypeAscending = "ASCENDING" @@ -10454,11 +14709,26 @@ const ( SortOrderTypeDescending = "DESCENDING" ) +// SortOrderType_Values returns all elements of the SortOrderType enum +func SortOrderType_Values() []string { + return []string{ + SortOrderTypeAscending, + SortOrderTypeDescending, + } +} + const ( // SourceAuthTypeOauth is a SourceAuthType enum value SourceAuthTypeOauth = "OAUTH" ) +// SourceAuthType_Values returns all elements of the SourceAuthType enum +func SourceAuthType_Values() []string { + return []string{ + SourceAuthTypeOauth, + } +} + const ( // SourceTypeCodecommit is a SourceType enum value SourceTypeCodecommit = "CODECOMMIT" @@ -10482,6 +14752,19 @@ const ( SourceTypeNoSource = "NO_SOURCE" ) +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeCodecommit, + SourceTypeCodepipeline, + SourceTypeGithub, + SourceTypeS3, + SourceTypeBitbucket, + SourceTypeGithubEnterprise, + SourceTypeNoSource, + } +} + const ( // StatusTypeSucceeded is a StatusType enum value StatusTypeSucceeded = "SUCCEEDED" @@ -10502,6 +14785,34 @@ const ( StatusTypeStopped = "STOPPED" ) +// StatusType_Values returns all elements of the StatusType enum +func StatusType_Values() []string { + return []string{ + StatusTypeSucceeded, + StatusTypeFailed, + StatusTypeFault, + StatusTypeTimedOut, + StatusTypeInProgress, + StatusTypeStopped, + } +} + +const ( + // WebhookBuildTypeBuild is a WebhookBuildType enum value + WebhookBuildTypeBuild = "BUILD" + + // WebhookBuildTypeBuildBatch is a WebhookBuildType enum value + WebhookBuildTypeBuildBatch = "BUILD_BATCH" +) + +// WebhookBuildType_Values returns all elements of the WebhookBuildType enum +func WebhookBuildType_Values() []string { + return []string{ + WebhookBuildTypeBuild, + WebhookBuildTypeBuildBatch, + } +} + const ( // WebhookFilterTypeEvent is a WebhookFilterType enum value WebhookFilterTypeEvent = "EVENT" @@ -10517,4 +14828,19 @@ const ( // WebhookFilterTypeFilePath is a WebhookFilterType enum value WebhookFilterTypeFilePath = "FILE_PATH" + + // WebhookFilterTypeCommitMessage is a WebhookFilterType enum value + WebhookFilterTypeCommitMessage = "COMMIT_MESSAGE" ) + +// WebhookFilterType_Values returns all elements of the WebhookFilterType enum +func WebhookFilterType_Values() []string { + return []string{ + WebhookFilterTypeEvent, + WebhookFilterTypeBaseRef, + WebhookFilterTypeHeadRef, + WebhookFilterTypeActorAccountId, + WebhookFilterTypeFilePath, + WebhookFilterTypeCommitMessage, + } +} 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 e79a77db563..a8d53f46244 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 @@ -922,7 +922,8 @@ func (c *CodeCommit) CreateBranchRequest(input *CreateBranchInput) (req *request // A branch name is required, but was not specified. // // * BranchNameExistsException -// The specified branch name already exists. +// Cannot create the branch with the specified name because the commit conflicts +// with an existing branch with the same name. Branch names must be unique. // // * InvalidBranchNameException // The specified reference name is not valid. @@ -3531,6 +3532,10 @@ func (c *CodeCommit) GetCommentRequest(input *GetCommentInput) (req *request.Req // // Returns the content of a comment made on a change, file, or commit in a repository. // +// Reaction counts might include numbers from user identities who were deleted +// after the reaction was made. For a count of reactions from active identities, +// use GetCommentReactions. +// // Returns awserr.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. @@ -3543,6 +3548,10 @@ func (c *CodeCommit) GetCommentRequest(input *GetCommentInput) (req *request.Req // No comment exists with the provided ID. Verify that you have used the correct // ID, and then try again. // +// * CommentDeletedException +// This comment has already been deleted. You cannot edit or delete a deleted +// comment. +// // * CommentIdRequiredException // The comment ID is missing or null. A comment ID is required. // @@ -3550,9 +3559,20 @@ func (c *CodeCommit) GetCommentRequest(input *GetCommentInput) (req *request.Req // The comment ID is not in a valid format. Make sure that you have provided // the full comment ID. // -// * CommentDeletedException -// This comment has already been deleted. You cannot edit or delete a deleted -// comment. +// * EncryptionIntegrityChecksFailedException +// An encryption integrity check failed. +// +// * EncryptionKeyAccessDeniedException +// An encryption key could not be accessed. +// +// * EncryptionKeyDisabledException +// The encryption key is disabled. +// +// * EncryptionKeyNotFoundException +// No encryption key was found. +// +// * EncryptionKeyUnavailableException +// The encryption key is not available. // // See also, https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/GetComment func (c *CodeCommit) GetComment(input *GetCommentInput) (*GetCommentOutput, error) { @@ -3576,6 +3596,165 @@ func (c *CodeCommit) GetCommentWithContext(ctx aws.Context, input *GetCommentInp return out, req.Send() } +const opGetCommentReactions = "GetCommentReactions" + +// GetCommentReactionsRequest generates a "aws/request.Request" representing the +// client's request for the GetCommentReactions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetCommentReactions for more information on using the GetCommentReactions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetCommentReactionsRequest method. +// req, resp := client.GetCommentReactionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/GetCommentReactions +func (c *CodeCommit) GetCommentReactionsRequest(input *GetCommentReactionsInput) (req *request.Request, output *GetCommentReactionsOutput) { + op := &request.Operation{ + Name: opGetCommentReactions, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetCommentReactionsInput{} + } + + output = &GetCommentReactionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetCommentReactions API operation for AWS CodeCommit. +// +// Returns information about reactions to a specified comment ID. Reactions +// from users who have been deleted will not be included in the count. +// +// Returns awserr.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 CodeCommit's +// API operation GetCommentReactions for usage and error information. +// +// Returned Error Types: +// * CommentDoesNotExistException +// No comment exists with the provided ID. Verify that you have used the correct +// ID, and then try again. +// +// * CommentIdRequiredException +// The comment ID is missing or null. A comment ID is required. +// +// * InvalidCommentIdException +// The comment ID is not in a valid format. Make sure that you have provided +// the full comment ID. +// +// * InvalidReactionUserArnException +// The Amazon Resource Name (ARN) of the user or identity is not valid. +// +// * InvalidMaxResultsException +// The specified number of maximum results is not valid. +// +// * InvalidContinuationTokenException +// The specified continuation token is not valid. +// +// * CommentDeletedException +// This comment has already been deleted. You cannot edit or delete a deleted +// comment. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/GetCommentReactions +func (c *CodeCommit) GetCommentReactions(input *GetCommentReactionsInput) (*GetCommentReactionsOutput, error) { + req, out := c.GetCommentReactionsRequest(input) + return out, req.Send() +} + +// GetCommentReactionsWithContext is the same as GetCommentReactions with the addition of +// the ability to pass a context and additional request options. +// +// See GetCommentReactions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) GetCommentReactionsWithContext(ctx aws.Context, input *GetCommentReactionsInput, opts ...request.Option) (*GetCommentReactionsOutput, error) { + req, out := c.GetCommentReactionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetCommentReactionsPages iterates over the pages of a GetCommentReactions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetCommentReactions 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 GetCommentReactions operation. +// pageNum := 0 +// err := client.GetCommentReactionsPages(params, +// func(page *codecommit.GetCommentReactionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *CodeCommit) GetCommentReactionsPages(input *GetCommentReactionsInput, fn func(*GetCommentReactionsOutput, bool) bool) error { + return c.GetCommentReactionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetCommentReactionsPagesWithContext same as GetCommentReactionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) GetCommentReactionsPagesWithContext(ctx aws.Context, input *GetCommentReactionsInput, fn func(*GetCommentReactionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetCommentReactionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetCommentReactionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetCommentReactionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetCommentsForComparedCommit = "GetCommentsForComparedCommit" // GetCommentsForComparedCommitRequest generates a "aws/request.Request" representing the @@ -3628,6 +3807,10 @@ func (c *CodeCommit) GetCommentsForComparedCommitRequest(input *GetCommentsForCo // // Returns information about comments made on the comparison between two commits. // +// Reaction counts might include numbers from user identities who were deleted +// after the reaction was made. For a count of reactions from active identities, +// use GetCommentReactions. +// // Returns awserr.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. @@ -3806,6 +3989,10 @@ func (c *CodeCommit) GetCommentsForPullRequestRequest(input *GetCommentsForPullR // // Returns comments made on a pull request. // +// Reaction counts might include numbers from user identities who were deleted +// after the reaction was made. For a count of reactions from active identities, +// use GetCommentReactions. +// // Returns awserr.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. @@ -7986,6 +8173,10 @@ func (c *CodeCommit) PostCommentForComparedCommitRequest(input *PostCommentForCo // * InvalidCommitIdException // The specified commit ID is not valid. // +// * BeforeCommitIdAndAfterCommitIdAreSameException +// The before commit ID and the after commit ID are the same, which is not valid. +// The before commit ID and the after commit ID must be different commit IDs. +// // * EncryptionIntegrityChecksFailedException // An encryption integrity check failed. // @@ -8001,10 +8192,6 @@ func (c *CodeCommit) PostCommentForComparedCommitRequest(input *PostCommentForCo // * EncryptionKeyUnavailableException // The encryption key is not available. // -// * BeforeCommitIdAndAfterCommitIdAreSameException -// The before commit ID and the after commit ID are the same, which is not valid. -// The before commit ID and the after commit ID must be different commit IDs. -// // * CommitDoesNotExistException // The specified commit does not exist or no commit was specified, and the specified // repository has no default branch. @@ -8015,6 +8202,9 @@ func (c *CodeCommit) PostCommentForComparedCommitRequest(input *PostCommentForCo // * PathDoesNotExistException // The specified path does not exist. // +// * PathRequiredException +// The folderPath for a location cannot be null. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/PostCommentForComparedCommit func (c *CodeCommit) PostCommentForComparedCommit(input *PostCommentForComparedCommitInput) (*PostCommentForComparedCommitOutput, error) { req, out := c.PostCommentForComparedCommitRequest(input) @@ -8163,6 +8353,10 @@ func (c *CodeCommit) PostCommentForPullRequestRequest(input *PostCommentForPullR // * InvalidCommitIdException // The specified commit ID is not valid. // +// * BeforeCommitIdAndAfterCommitIdAreSameException +// The before commit ID and the after commit ID are the same, which is not valid. +// The before commit ID and the after commit ID must be different commit IDs. +// // * EncryptionIntegrityChecksFailedException // An encryption integrity check failed. // @@ -8191,10 +8385,6 @@ func (c *CodeCommit) PostCommentForPullRequestRequest(input *PostCommentForPullR // * PathRequiredException // The folderPath for a location cannot be null. // -// * BeforeCommitIdAndAfterCommitIdAreSameException -// The before commit ID and the after commit ID are the same, which is not valid. -// The before commit ID and the after commit ID must be different commit IDs. -// // See also, https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/PostCommentForPullRequest func (c *CodeCommit) PostCommentForPullRequest(input *PostCommentForPullRequestInput) (*PostCommentForPullRequestOutput, error) { req, out := c.PostCommentForPullRequestRequest(input) @@ -8326,6 +8516,111 @@ func (c *CodeCommit) PostCommentReplyWithContext(ctx aws.Context, input *PostCom return out, req.Send() } +const opPutCommentReaction = "PutCommentReaction" + +// PutCommentReactionRequest generates a "aws/request.Request" representing the +// client's request for the PutCommentReaction operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutCommentReaction for more information on using the PutCommentReaction +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutCommentReactionRequest method. +// req, resp := client.PutCommentReactionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/PutCommentReaction +func (c *CodeCommit) PutCommentReactionRequest(input *PutCommentReactionInput) (req *request.Request, output *PutCommentReactionOutput) { + op := &request.Operation{ + Name: opPutCommentReaction, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &PutCommentReactionInput{} + } + + output = &PutCommentReactionOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// PutCommentReaction API operation for AWS CodeCommit. +// +// Adds or updates a reaction to a specified comment for the user whose identity +// is used to make the request. You can only add or update a reaction for yourself. +// You cannot add, modify, or delete a reaction for another user. +// +// Returns awserr.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 CodeCommit's +// API operation PutCommentReaction for usage and error information. +// +// Returned Error Types: +// * CommentDoesNotExistException +// No comment exists with the provided ID. Verify that you have used the correct +// ID, and then try again. +// +// * CommentIdRequiredException +// The comment ID is missing or null. A comment ID is required. +// +// * InvalidCommentIdException +// The comment ID is not in a valid format. Make sure that you have provided +// the full comment ID. +// +// * InvalidReactionValueException +// The value of the reaction is not valid. For more information, see the AWS +// CodeCommit User Guide (https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html). +// +// * ReactionValueRequiredException +// A reaction value is required. +// +// * ReactionLimitExceededException +// The number of reactions has been exceeded. Reactions are limited to one reaction +// per user for each individual comment ID. +// +// * CommentDeletedException +// This comment has already been deleted. You cannot edit or delete a deleted +// comment. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/PutCommentReaction +func (c *CodeCommit) PutCommentReaction(input *PutCommentReactionInput) (*PutCommentReactionOutput, error) { + req, out := c.PutCommentReactionRequest(input) + return out, req.Send() +} + +// PutCommentReactionWithContext is the same as PutCommentReaction with the addition of +// the ability to pass a context and additional request options. +// +// See PutCommentReaction for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) PutCommentReactionWithContext(ctx aws.Context, input *PutCommentReactionInput, opts ...request.Option) (*PutCommentReactionOutput, error) { + req, out := c.PutCommentReactionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opPutFile = "PutFile" // PutFileRequest generates a "aws/request.Request" representing the @@ -12500,7 +12795,8 @@ func (s *BranchInfo) SetCommitId(v string) *BranchInfo { return s } -// The specified branch name already exists. +// Cannot create the branch with the specified name because the commit conflicts +// with an existing branch with the same name. Branch names must be unique. type BranchNameExistsException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -12851,6 +13147,10 @@ type Comment struct { // The Amazon Resource Name (ARN) of the person who posted the comment. AuthorArn *string `locationName:"authorArn" type:"string"` + // The emoji reactions to a comment, if any, submitted by the user whose credentials + // are associated with the call to the API. + CallerReactions []*string `locationName:"callerReactions" type:"list"` + // A unique, client-generated idempotency token that, when provided in a request, // ensures the request cannot be repeated with a changed parameter. If a request // is received with the same parameters and a token is included, the request @@ -12874,6 +13174,10 @@ type Comment struct { // The date and time the comment was most recently modified, in timestamp format. LastModifiedDate *time.Time `locationName:"lastModifiedDate" type:"timestamp"` + + // A string to integer map that represents the number of individual users who + // have responded to a comment with the specified reactions. + ReactionCounts map[string]*int64 `locationName:"reactionCounts" type:"map"` } // String returns the string representation @@ -12892,6 +13196,12 @@ func (s *Comment) SetAuthorArn(v string) *Comment { return s } +// SetCallerReactions sets the CallerReactions field's value. +func (s *Comment) SetCallerReactions(v []*string) *Comment { + s.CallerReactions = v + return s +} + // SetClientRequestToken sets the ClientRequestToken field's value. func (s *Comment) SetClientRequestToken(v string) *Comment { s.ClientRequestToken = &v @@ -12934,6 +13244,12 @@ func (s *Comment) SetLastModifiedDate(v time.Time) *Comment { return s } +// SetReactionCounts sets the ReactionCounts field's value. +func (s *Comment) SetReactionCounts(v map[string]*int64) *Comment { + s.ReactionCounts = v + return s +} + // The comment is empty. You must provide some content for a comment. The content // cannot be null. type CommentContentRequiredException struct { @@ -14246,7 +14562,7 @@ type CreateApprovalRuleTemplateInput struct { // Amazon Resource Name (ARN) of the IAM user or role. // // For more information about IAM ARNs, wildcards, and formats, see IAM Identifiers - // (https://docs.aws.amazon.com/iam/latest/UserGuide/reference_identifiers.html) + // (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) // in the IAM User Guide. // // ApprovalRuleTemplateContent is a required field @@ -14678,7 +14994,7 @@ type CreatePullRequestApprovalRuleInput struct { // Amazon Resource Name (ARN) of the IAM user or role. // // For more information about IAM ARNs, wildcards, and formats, see IAM Identifiers - // (https://docs.aws.amazon.com/iam/latest/UserGuide/reference_identifiers.html) + // (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) // in the IAM User Guide. // // ApprovalRuleContent is a required field @@ -17908,16 +18224,119 @@ func (s *GetCommentOutput) SetComment(v *Comment) *GetCommentOutput { return s } -type GetCommentsForComparedCommitInput struct { +type GetCommentReactionsInput struct { _ struct{} `type:"structure"` - // To establish the directionality of the comparison, the full commit ID of - // the after commit. + // The ID of the comment for which you want to get reactions information. // - // AfterCommitId is a required field - AfterCommitId *string `locationName:"afterCommitId" type:"string" required:"true"` + // CommentId is a required field + CommentId *string `locationName:"commentId" type:"string" required:"true"` - // To establish the directionality of the comparison, the full commit ID of + // A non-zero, non-negative integer used to limit the number of returned results. + // The default is the same as the allowed maximum, 1,000. + MaxResults *int64 `locationName:"maxResults" type:"integer"` + + // An enumeration token that, when provided in a request, returns the next batch + // of the results. + NextToken *string `locationName:"nextToken" type:"string"` + + // Optional. The Amazon Resource Name (ARN) of the user or identity for which + // you want to get reaction information. + ReactionUserArn *string `locationName:"reactionUserArn" type:"string"` +} + +// String returns the string representation +func (s GetCommentReactionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCommentReactionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetCommentReactionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetCommentReactionsInput"} + if s.CommentId == nil { + invalidParams.Add(request.NewErrParamRequired("CommentId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCommentId sets the CommentId field's value. +func (s *GetCommentReactionsInput) SetCommentId(v string) *GetCommentReactionsInput { + s.CommentId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetCommentReactionsInput) SetMaxResults(v int64) *GetCommentReactionsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetCommentReactionsInput) SetNextToken(v string) *GetCommentReactionsInput { + s.NextToken = &v + return s +} + +// SetReactionUserArn sets the ReactionUserArn field's value. +func (s *GetCommentReactionsInput) SetReactionUserArn(v string) *GetCommentReactionsInput { + s.ReactionUserArn = &v + return s +} + +type GetCommentReactionsOutput struct { + _ struct{} `type:"structure"` + + // An enumeration token that can be used in a request to return the next batch + // of the results. + NextToken *string `locationName:"nextToken" type:"string"` + + // An array of reactions to the specified comment. + // + // ReactionsForComment is a required field + ReactionsForComment []*ReactionForComment `locationName:"reactionsForComment" type:"list" required:"true"` +} + +// String returns the string representation +func (s GetCommentReactionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCommentReactionsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *GetCommentReactionsOutput) SetNextToken(v string) *GetCommentReactionsOutput { + s.NextToken = &v + return s +} + +// SetReactionsForComment sets the ReactionsForComment field's value. +func (s *GetCommentReactionsOutput) SetReactionsForComment(v []*ReactionForComment) *GetCommentReactionsOutput { + s.ReactionsForComment = v + return s +} + +type GetCommentsForComparedCommitInput struct { + _ struct{} `type:"structure"` + + // To establish the directionality of the comparison, the full commit ID of + // the after commit. + // + // AfterCommitId is a required field + AfterCommitId *string `locationName:"afterCommitId" type:"string" required:"true"` + + // To establish the directionality of the comparison, the full commit ID of // the before commit. BeforeCommitId *string `locationName:"beforeCommitId" type:"string"` @@ -21720,6 +22139,119 @@ func (s *InvalidPullRequestStatusUpdateException) RequestID() string { return s.RespMetadata.RequestID } +// The Amazon Resource Name (ARN) of the user or identity is not valid. +type InvalidReactionUserArnException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s InvalidReactionUserArnException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InvalidReactionUserArnException) GoString() string { + return s.String() +} + +func newErrorInvalidReactionUserArnException(v protocol.ResponseMetadata) error { + return &InvalidReactionUserArnException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidReactionUserArnException) Code() string { + return "InvalidReactionUserArnException" +} + +// Message returns the exception's message. +func (s *InvalidReactionUserArnException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidReactionUserArnException) OrigErr() error { + return nil +} + +func (s *InvalidReactionUserArnException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidReactionUserArnException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidReactionUserArnException) RequestID() string { + return s.RespMetadata.RequestID +} + +// The value of the reaction is not valid. For more information, see the AWS +// CodeCommit User Guide (https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html). +type InvalidReactionValueException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s InvalidReactionValueException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InvalidReactionValueException) GoString() string { + return s.String() +} + +func newErrorInvalidReactionValueException(v protocol.ResponseMetadata) error { + return &InvalidReactionValueException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidReactionValueException) Code() string { + return "InvalidReactionValueException" +} + +// Message returns the exception's message. +func (s *InvalidReactionValueException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidReactionValueException) OrigErr() error { + return nil +} + +func (s *InvalidReactionValueException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidReactionValueException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidReactionValueException) RequestID() string { + return s.RespMetadata.RequestID +} + // The specified reference name format is not valid. Reference names must conform // to the Git references format (for example, refs/heads/master). For more information, // see Git Internals - Git References (https://git-scm.com/book/en/v2/Git-Internals-Git-References) @@ -27815,6 +28347,75 @@ func (s *PullRequestTarget) SetSourceReference(v string) *PullRequestTarget { return s } +type PutCommentReactionInput struct { + _ struct{} `type:"structure"` + + // The ID of the comment to which you want to add or update a reaction. + // + // CommentId is a required field + CommentId *string `locationName:"commentId" type:"string" required:"true"` + + // The emoji reaction you want to add or update. To remove a reaction, provide + // a value of blank or null. You can also provide the value of none. For information + // about emoji reaction values supported in AWS CodeCommit, see the AWS CodeCommit + // User Guide (https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-commit-comment.html#emoji-reaction-table). + // + // ReactionValue is a required field + ReactionValue *string `locationName:"reactionValue" type:"string" required:"true"` +} + +// String returns the string representation +func (s PutCommentReactionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutCommentReactionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutCommentReactionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutCommentReactionInput"} + if s.CommentId == nil { + invalidParams.Add(request.NewErrParamRequired("CommentId")) + } + if s.ReactionValue == nil { + invalidParams.Add(request.NewErrParamRequired("ReactionValue")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCommentId sets the CommentId field's value. +func (s *PutCommentReactionInput) SetCommentId(v string) *PutCommentReactionInput { + s.CommentId = &v + return s +} + +// SetReactionValue sets the ReactionValue field's value. +func (s *PutCommentReactionInput) SetReactionValue(v string) *PutCommentReactionInput { + s.ReactionValue = &v + return s +} + +type PutCommentReactionOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s PutCommentReactionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutCommentReactionOutput) GoString() string { + return s.String() +} + // Information about a file added or updated as part of a commit. type PutFileEntry struct { _ struct{} `type:"structure"` @@ -28231,6 +28832,209 @@ func (s *PutRepositoryTriggersOutput) SetConfigurationId(v string) *PutRepositor return s } +// Information about the reaction values provided by users on a comment. +type ReactionForComment struct { + _ struct{} `type:"structure"` + + // The reaction for a specified comment. + Reaction *ReactionValueFormats `locationName:"reaction" type:"structure"` + + // The Amazon Resource Names (ARNs) of users who have provided reactions to + // the comment. + ReactionUsers []*string `locationName:"reactionUsers" type:"list"` + + // A numerical count of users who reacted with the specified emoji whose identities + // have been subsequently deleted from IAM. While these IAM users or roles no + // longer exist, the reactions might still appear in total reaction counts. + ReactionsFromDeletedUsersCount *int64 `locationName:"reactionsFromDeletedUsersCount" type:"integer"` +} + +// String returns the string representation +func (s ReactionForComment) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ReactionForComment) GoString() string { + return s.String() +} + +// SetReaction sets the Reaction field's value. +func (s *ReactionForComment) SetReaction(v *ReactionValueFormats) *ReactionForComment { + s.Reaction = v + return s +} + +// SetReactionUsers sets the ReactionUsers field's value. +func (s *ReactionForComment) SetReactionUsers(v []*string) *ReactionForComment { + s.ReactionUsers = v + return s +} + +// SetReactionsFromDeletedUsersCount sets the ReactionsFromDeletedUsersCount field's value. +func (s *ReactionForComment) SetReactionsFromDeletedUsersCount(v int64) *ReactionForComment { + s.ReactionsFromDeletedUsersCount = &v + return s +} + +// The number of reactions has been exceeded. Reactions are limited to one reaction +// per user for each individual comment ID. +type ReactionLimitExceededException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ReactionLimitExceededException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ReactionLimitExceededException) GoString() string { + return s.String() +} + +func newErrorReactionLimitExceededException(v protocol.ResponseMetadata) error { + return &ReactionLimitExceededException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ReactionLimitExceededException) Code() string { + return "ReactionLimitExceededException" +} + +// Message returns the exception's message. +func (s *ReactionLimitExceededException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ReactionLimitExceededException) OrigErr() error { + return nil +} + +func (s *ReactionLimitExceededException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ReactionLimitExceededException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ReactionLimitExceededException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Information about the values for reactions to a comment. AWS CodeCommit supports +// a limited set of reactions. +type ReactionValueFormats struct { + _ struct{} `type:"structure"` + + // The Emoji Version 1.0 graphic of the reaction. These graphics are interpreted + // slightly differently on different operating systems. + Emoji *string `locationName:"emoji" type:"string"` + + // The emoji short code for the reaction. Short codes are interpreted slightly + // differently on different operating systems. + ShortCode *string `locationName:"shortCode" type:"string"` + + // The Unicode codepoint for the reaction. + Unicode *string `locationName:"unicode" type:"string"` +} + +// String returns the string representation +func (s ReactionValueFormats) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ReactionValueFormats) GoString() string { + return s.String() +} + +// SetEmoji sets the Emoji field's value. +func (s *ReactionValueFormats) SetEmoji(v string) *ReactionValueFormats { + s.Emoji = &v + return s +} + +// SetShortCode sets the ShortCode field's value. +func (s *ReactionValueFormats) SetShortCode(v string) *ReactionValueFormats { + s.ShortCode = &v + return s +} + +// SetUnicode sets the Unicode field's value. +func (s *ReactionValueFormats) SetUnicode(v string) *ReactionValueFormats { + s.Unicode = &v + return s +} + +// A reaction value is required. +type ReactionValueRequiredException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ReactionValueRequiredException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ReactionValueRequiredException) GoString() string { + return s.String() +} + +func newErrorReactionValueRequiredException(v protocol.ResponseMetadata) error { + return &ReactionValueRequiredException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ReactionValueRequiredException) Code() string { + return "ReactionValueRequiredException" +} + +// Message returns the exception's message. +func (s *ReactionValueRequiredException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ReactionValueRequiredException) OrigErr() error { + return nil +} + +func (s *ReactionValueRequiredException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ReactionValueRequiredException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ReactionValueRequiredException) RequestID() string { + return s.RespMetadata.RequestID +} + // The specified reference does not exist. You must provide a full commit ID. type ReferenceDoesNotExistException struct { _ struct{} `type:"structure"` @@ -31378,7 +32182,7 @@ type UpdatePullRequestApprovalRuleContentInput struct { // Amazon Resource Name (ARN) of the IAM user or role. // // For more information about IAM ARNs, wildcards, and formats, see IAM Identifiers - // (https://docs.aws.amazon.com/iam/latest/UserGuide/reference_identifiers.html) + // (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) // in the IAM User Guide. // // NewRuleContent is a required field @@ -31977,6 +32781,14 @@ const ( ApprovalStateRevoke = "REVOKE" ) +// ApprovalState_Values returns all elements of the ApprovalState enum +func ApprovalState_Values() []string { + return []string{ + ApprovalStateApprove, + ApprovalStateRevoke, + } +} + const ( // ChangeTypeEnumA is a ChangeTypeEnum enum value ChangeTypeEnumA = "A" @@ -31988,6 +32800,15 @@ const ( ChangeTypeEnumD = "D" ) +// ChangeTypeEnum_Values returns all elements of the ChangeTypeEnum enum +func ChangeTypeEnum_Values() []string { + return []string{ + ChangeTypeEnumA, + ChangeTypeEnumM, + ChangeTypeEnumD, + } +} + const ( // ConflictDetailLevelTypeEnumFileLevel is a ConflictDetailLevelTypeEnum enum value ConflictDetailLevelTypeEnumFileLevel = "FILE_LEVEL" @@ -31996,6 +32817,14 @@ const ( ConflictDetailLevelTypeEnumLineLevel = "LINE_LEVEL" ) +// ConflictDetailLevelTypeEnum_Values returns all elements of the ConflictDetailLevelTypeEnum enum +func ConflictDetailLevelTypeEnum_Values() []string { + return []string{ + ConflictDetailLevelTypeEnumFileLevel, + ConflictDetailLevelTypeEnumLineLevel, + } +} + const ( // ConflictResolutionStrategyTypeEnumNone is a ConflictResolutionStrategyTypeEnum enum value ConflictResolutionStrategyTypeEnumNone = "NONE" @@ -32010,6 +32839,16 @@ const ( ConflictResolutionStrategyTypeEnumAutomerge = "AUTOMERGE" ) +// ConflictResolutionStrategyTypeEnum_Values returns all elements of the ConflictResolutionStrategyTypeEnum enum +func ConflictResolutionStrategyTypeEnum_Values() []string { + return []string{ + ConflictResolutionStrategyTypeEnumNone, + ConflictResolutionStrategyTypeEnumAcceptSource, + ConflictResolutionStrategyTypeEnumAcceptDestination, + ConflictResolutionStrategyTypeEnumAutomerge, + } +} + const ( // FileModeTypeEnumExecutable is a FileModeTypeEnum enum value FileModeTypeEnumExecutable = "EXECUTABLE" @@ -32021,6 +32860,15 @@ const ( FileModeTypeEnumSymlink = "SYMLINK" ) +// FileModeTypeEnum_Values returns all elements of the FileModeTypeEnum enum +func FileModeTypeEnum_Values() []string { + return []string{ + FileModeTypeEnumExecutable, + FileModeTypeEnumNormal, + FileModeTypeEnumSymlink, + } +} + const ( // MergeOptionTypeEnumFastForwardMerge is a MergeOptionTypeEnum enum value MergeOptionTypeEnumFastForwardMerge = "FAST_FORWARD_MERGE" @@ -32032,6 +32880,15 @@ const ( MergeOptionTypeEnumThreeWayMerge = "THREE_WAY_MERGE" ) +// MergeOptionTypeEnum_Values returns all elements of the MergeOptionTypeEnum enum +func MergeOptionTypeEnum_Values() []string { + return []string{ + MergeOptionTypeEnumFastForwardMerge, + MergeOptionTypeEnumSquashMerge, + MergeOptionTypeEnumThreeWayMerge, + } +} + const ( // ObjectTypeEnumFile is a ObjectTypeEnum enum value ObjectTypeEnumFile = "FILE" @@ -32046,6 +32903,16 @@ const ( ObjectTypeEnumSymbolicLink = "SYMBOLIC_LINK" ) +// ObjectTypeEnum_Values returns all elements of the ObjectTypeEnum enum +func ObjectTypeEnum_Values() []string { + return []string{ + ObjectTypeEnumFile, + ObjectTypeEnumDirectory, + ObjectTypeEnumGitLink, + ObjectTypeEnumSymbolicLink, + } +} + const ( // OrderEnumAscending is a OrderEnum enum value OrderEnumAscending = "ascending" @@ -32054,6 +32921,14 @@ const ( OrderEnumDescending = "descending" ) +// OrderEnum_Values returns all elements of the OrderEnum enum +func OrderEnum_Values() []string { + return []string{ + OrderEnumAscending, + OrderEnumDescending, + } +} + const ( // OverrideStatusOverride is a OverrideStatus enum value OverrideStatusOverride = "OVERRIDE" @@ -32062,6 +32937,14 @@ const ( OverrideStatusRevoke = "REVOKE" ) +// OverrideStatus_Values returns all elements of the OverrideStatus enum +func OverrideStatus_Values() []string { + return []string{ + OverrideStatusOverride, + OverrideStatusRevoke, + } +} + const ( // PullRequestEventTypePullRequestCreated is a PullRequestEventType enum value PullRequestEventTypePullRequestCreated = "PULL_REQUEST_CREATED" @@ -32091,6 +32974,21 @@ const ( PullRequestEventTypePullRequestApprovalStateChanged = "PULL_REQUEST_APPROVAL_STATE_CHANGED" ) +// PullRequestEventType_Values returns all elements of the PullRequestEventType enum +func PullRequestEventType_Values() []string { + return []string{ + PullRequestEventTypePullRequestCreated, + PullRequestEventTypePullRequestStatusChanged, + PullRequestEventTypePullRequestSourceReferenceUpdated, + PullRequestEventTypePullRequestMergeStateChanged, + PullRequestEventTypePullRequestApprovalRuleCreated, + PullRequestEventTypePullRequestApprovalRuleUpdated, + PullRequestEventTypePullRequestApprovalRuleDeleted, + PullRequestEventTypePullRequestApprovalRuleOverridden, + PullRequestEventTypePullRequestApprovalStateChanged, + } +} + const ( // PullRequestStatusEnumOpen is a PullRequestStatusEnum enum value PullRequestStatusEnumOpen = "OPEN" @@ -32099,6 +32997,14 @@ const ( PullRequestStatusEnumClosed = "CLOSED" ) +// PullRequestStatusEnum_Values returns all elements of the PullRequestStatusEnum enum +func PullRequestStatusEnum_Values() []string { + return []string{ + PullRequestStatusEnumOpen, + PullRequestStatusEnumClosed, + } +} + const ( // RelativeFileVersionEnumBefore is a RelativeFileVersionEnum enum value RelativeFileVersionEnumBefore = "BEFORE" @@ -32107,6 +33013,14 @@ const ( RelativeFileVersionEnumAfter = "AFTER" ) +// RelativeFileVersionEnum_Values returns all elements of the RelativeFileVersionEnum enum +func RelativeFileVersionEnum_Values() []string { + return []string{ + RelativeFileVersionEnumBefore, + RelativeFileVersionEnumAfter, + } +} + const ( // ReplacementTypeEnumKeepBase is a ReplacementTypeEnum enum value ReplacementTypeEnumKeepBase = "KEEP_BASE" @@ -32121,6 +33035,16 @@ const ( ReplacementTypeEnumUseNewContent = "USE_NEW_CONTENT" ) +// ReplacementTypeEnum_Values returns all elements of the ReplacementTypeEnum enum +func ReplacementTypeEnum_Values() []string { + return []string{ + ReplacementTypeEnumKeepBase, + ReplacementTypeEnumKeepSource, + ReplacementTypeEnumKeepDestination, + ReplacementTypeEnumUseNewContent, + } +} + const ( // RepositoryTriggerEventEnumAll is a RepositoryTriggerEventEnum enum value RepositoryTriggerEventEnumAll = "all" @@ -32135,6 +33059,16 @@ const ( RepositoryTriggerEventEnumDeleteReference = "deleteReference" ) +// RepositoryTriggerEventEnum_Values returns all elements of the RepositoryTriggerEventEnum enum +func RepositoryTriggerEventEnum_Values() []string { + return []string{ + RepositoryTriggerEventEnumAll, + RepositoryTriggerEventEnumUpdateReference, + RepositoryTriggerEventEnumCreateReference, + RepositoryTriggerEventEnumDeleteReference, + } +} + const ( // SortByEnumRepositoryName is a SortByEnum enum value SortByEnumRepositoryName = "repositoryName" @@ -32142,3 +33076,11 @@ const ( // SortByEnumLastModifiedDate is a SortByEnum enum value SortByEnumLastModifiedDate = "lastModifiedDate" ) + +// SortByEnum_Values returns all elements of the SortByEnum enum +func SortByEnum_Values() []string { + return []string{ + SortByEnumRepositoryName, + SortByEnumLastModifiedDate, + } +} 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 index 2025f901bd5..87186d5eddd 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codecommit/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codecommit/doc.go @@ -224,6 +224,9 @@ // // * GetComment, which returns information about a comment on a commit. // +// * GetCommentReactions, which returns information about emoji reactions +// to comments. +// // * GetCommentsForComparedCommit, which returns information about comments // on the comparison between two commit specifiers in a repository. // @@ -232,6 +235,9 @@ // // * PostCommentReply, which creates a reply to a comment. // +// * PutCommentReaction, which creates or updates an emoji reaction to a +// comment. +// // * UpdateComment, which updates the content of a comment on a commit in // a repository. // 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 030dd1c47bf..44aa82763a5 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 @@ -117,7 +117,8 @@ const ( // ErrCodeBranchNameExistsException for service response error code // "BranchNameExistsException". // - // The specified branch name already exists. + // Cannot create the branch with the specified name because the commit conflicts + // with an existing branch with the same name. Branch names must be unique. ErrCodeBranchNameExistsException = "BranchNameExistsException" // ErrCodeBranchNameIsTagNameException for service response error code @@ -636,6 +637,19 @@ const ( // OPEN to CLOSED. ErrCodeInvalidPullRequestStatusUpdateException = "InvalidPullRequestStatusUpdateException" + // ErrCodeInvalidReactionUserArnException for service response error code + // "InvalidReactionUserArnException". + // + // The Amazon Resource Name (ARN) of the user or identity is not valid. + ErrCodeInvalidReactionUserArnException = "InvalidReactionUserArnException" + + // ErrCodeInvalidReactionValueException for service response error code + // "InvalidReactionValueException". + // + // The value of the reaction is not valid. For more information, see the AWS + // CodeCommit User Guide (https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html). + ErrCodeInvalidReactionValueException = "InvalidReactionValueException" + // ErrCodeInvalidReferenceNameException for service response error code // "InvalidReferenceNameException". // @@ -1023,6 +1037,19 @@ const ( // reference both a file and a folder. ErrCodePutFileEntryConflictException = "PutFileEntryConflictException" + // ErrCodeReactionLimitExceededException for service response error code + // "ReactionLimitExceededException". + // + // The number of reactions has been exceeded. Reactions are limited to one reaction + // per user for each individual comment ID. + ErrCodeReactionLimitExceededException = "ReactionLimitExceededException" + + // ErrCodeReactionValueRequiredException for service response error code + // "ReactionValueRequiredException". + // + // A reaction value is required. + ErrCodeReactionValueRequiredException = "ReactionValueRequiredException" + // ErrCodeReferenceDoesNotExistException for service response error code // "ReferenceDoesNotExistException". // @@ -1337,6 +1364,8 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "InvalidPullRequestIdException": newErrorInvalidPullRequestIdException, "InvalidPullRequestStatusException": newErrorInvalidPullRequestStatusException, "InvalidPullRequestStatusUpdateException": newErrorInvalidPullRequestStatusUpdateException, + "InvalidReactionUserArnException": newErrorInvalidReactionUserArnException, + "InvalidReactionValueException": newErrorInvalidReactionValueException, "InvalidReferenceNameException": newErrorInvalidReferenceNameException, "InvalidRelativeFileVersionEnumException": newErrorInvalidRelativeFileVersionEnumException, "InvalidReplacementContentException": newErrorInvalidReplacementContentException, @@ -1393,6 +1422,8 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "PullRequestIdRequiredException": newErrorPullRequestIdRequiredException, "PullRequestStatusRequiredException": newErrorPullRequestStatusRequiredException, "PutFileEntryConflictException": newErrorPutFileEntryConflictException, + "ReactionLimitExceededException": newErrorReactionLimitExceededException, + "ReactionValueRequiredException": newErrorReactionValueRequiredException, "ReferenceDoesNotExistException": newErrorReferenceDoesNotExistException, "ReferenceNameRequiredException": newErrorReferenceNameRequiredException, "ReferenceTypeNotSupportedException": newErrorReferenceTypeNotSupportedException, 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 33832844aa3..9cbd7b88dd4 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 @@ -252,7 +252,7 @@ func (c *CodeDeploy) BatchGetApplicationsRequest(input *BatchGetApplicationsInpu // BatchGetApplications API operation for AWS CodeDeploy. // // Gets information about one or more applications. The maximum number of applications -// that can be returned is 25. +// that can be returned is 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 @@ -477,7 +477,8 @@ func (c *CodeDeploy) BatchGetDeploymentInstancesRequest(input *BatchGetDeploymen // The maximum number of names or IDs allowed for this request (100) was exceeded. // // * InvalidComputePlatformException -// The computePlatform is invalid. The computePlatform should be Lambda or Server. +// The computePlatform is invalid. The computePlatform should be Lambda, Server, +// or ECS. // // See also, https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/BatchGetDeploymentInstances // @@ -554,7 +555,8 @@ func (c *CodeDeploy) BatchGetDeploymentTargetsRequest(input *BatchGetDeploymentT // BatchGetDeploymentInstances. The maximum number of targets that can be returned // is 25. // -// The type of targets returned depends on the deployment's compute platform: +// The type of targets returned depends on the deployment's compute platform +// or deployment method: // // * EC2/On-premises: Information about EC2 instance targets. // @@ -562,6 +564,9 @@ func (c *CodeDeploy) BatchGetDeploymentTargetsRequest(input *BatchGetDeploymentT // // * Amazon ECS: Information about Amazon ECS service targets. // +// * CloudFormation: Information about targets of blue/green deployments +// initiated by a CloudFormation stack update. +// // Returns awserr.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. @@ -597,6 +602,9 @@ func (c *CodeDeploy) BatchGetDeploymentTargetsRequest(input *BatchGetDeploymentT // must have exactly one item. This exception does not apply to EC2/On-premises // deployments. // +// * InstanceDoesNotExistException +// The specified instance does not exist in the deployment group. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/BatchGetDeploymentTargets func (c *CodeDeploy) BatchGetDeploymentTargets(input *BatchGetDeploymentTargetsInput) (*BatchGetDeploymentTargetsOutput, error) { req, out := c.BatchGetDeploymentTargetsRequest(input) @@ -965,7 +973,8 @@ func (c *CodeDeploy) CreateApplicationRequest(input *CreateApplicationInput) (re // More applications were attempted to be created than are allowed. // // * InvalidComputePlatformException -// The computePlatform is invalid. The computePlatform should be Lambda or Server. +// The computePlatform is invalid. The computePlatform should be Lambda, Server, +// or ECS. // // * InvalidTagsToAddException // The specified tags are not valid. @@ -1133,6 +1142,10 @@ func (c *CodeDeploy) CreateDeploymentRequest(input *CreateDeploymentInput) (req // * InvalidGitHubAccountTokenException // The GitHub token is not valid. // +// * InvalidTrafficRoutingConfigurationException +// The configuration that specifies how traffic is routed during a deployment +// is invalid. +// // See also, 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) @@ -1217,7 +1230,7 @@ func (c *CodeDeploy) CreateDeploymentConfigRequest(input *CreateDeploymentConfig // // * DeploymentConfigAlreadyExistsException // A deployment configuration with the specified name with the IAM user or AWS -// account already exists . +// account already exists. // // * InvalidMinimumHealthyHostValueException // The minimum healthy instance value was specified in an invalid format. @@ -1226,7 +1239,8 @@ func (c *CodeDeploy) CreateDeploymentConfigRequest(input *CreateDeploymentConfig // The deployment configurations limit was exceeded. // // * InvalidComputePlatformException -// The computePlatform is invalid. The computePlatform should be Lambda or Server. +// The computePlatform is invalid. The computePlatform should be Lambda, Server, +// or ECS. // // * InvalidTrafficRoutingConfigurationException // The configuration that specifies how traffic is routed during a deployment @@ -1427,6 +1441,10 @@ func (c *CodeDeploy) CreateDeploymentGroupRequest(input *CreateDeploymentGroupIn // * InvalidTagsToAddException // The specified tags are not valid. // +// * InvalidTrafficRoutingConfigurationException +// The configuration that specifies how traffic is routed during a deployment +// is invalid. +// // See also, 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) @@ -1813,6 +1831,81 @@ func (c *CodeDeploy) DeleteGitHubAccountTokenWithContext(ctx aws.Context, input return out, req.Send() } +const opDeleteResourcesByExternalId = "DeleteResourcesByExternalId" + +// DeleteResourcesByExternalIdRequest generates a "aws/request.Request" representing the +// client's request for the DeleteResourcesByExternalId operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteResourcesByExternalId for more information on using the DeleteResourcesByExternalId +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteResourcesByExternalIdRequest method. +// req, resp := client.DeleteResourcesByExternalIdRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/DeleteResourcesByExternalId +func (c *CodeDeploy) DeleteResourcesByExternalIdRequest(input *DeleteResourcesByExternalIdInput) (req *request.Request, output *DeleteResourcesByExternalIdOutput) { + op := &request.Operation{ + Name: opDeleteResourcesByExternalId, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteResourcesByExternalIdInput{} + } + + output = &DeleteResourcesByExternalIdOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteResourcesByExternalId API operation for AWS CodeDeploy. +// +// Deletes resources linked to an external 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 +// the error. +// +// See the AWS API reference guide for AWS CodeDeploy's +// API operation DeleteResourcesByExternalId for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/DeleteResourcesByExternalId +func (c *CodeDeploy) DeleteResourcesByExternalId(input *DeleteResourcesByExternalIdInput) (*DeleteResourcesByExternalIdOutput, error) { + req, out := c.DeleteResourcesByExternalIdRequest(input) + return out, req.Send() +} + +// DeleteResourcesByExternalIdWithContext is the same as DeleteResourcesByExternalId with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteResourcesByExternalId for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DeleteResourcesByExternalIdWithContext(ctx aws.Context, input *DeleteResourcesByExternalIdInput, opts ...request.Option) (*DeleteResourcesByExternalIdOutput, error) { + req, out := c.DeleteResourcesByExternalIdRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeregisterOnPremisesInstance = "DeregisterOnPremisesInstance" // DeregisterOnPremisesInstanceRequest generates a "aws/request.Request" representing the @@ -2229,7 +2322,8 @@ func (c *CodeDeploy) GetDeploymentConfigRequest(input *GetDeploymentConfigInput) // The deployment configuration does not exist with the IAM user or AWS account. // // * InvalidComputePlatformException -// The computePlatform is invalid. The computePlatform should be Lambda or Server. +// The computePlatform is invalid. The computePlatform should be Lambda, Server, +// or ECS. // // See also, https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/GetDeploymentConfig func (c *CodeDeploy) GetDeploymentConfig(input *GetDeploymentConfigInput) (*GetDeploymentConfigOutput, error) { @@ -2428,7 +2522,8 @@ func (c *CodeDeploy) GetDeploymentInstanceRequest(input *GetDeploymentInstanceIn // The on-premises instance name was specified in an invalid format. // // * InvalidComputePlatformException -// The computePlatform is invalid. The computePlatform should be Lambda or Server. +// The computePlatform is invalid. The computePlatform should be Lambda, Server, +// or ECS. // // See also, https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/GetDeploymentInstance // @@ -3328,7 +3423,8 @@ func (c *CodeDeploy) ListDeploymentInstancesRequest(input *ListDeploymentInstanc // The target filter name is invalid. // // * InvalidComputePlatformException -// The computePlatform is invalid. The computePlatform should be Lambda or Server. +// The computePlatform is invalid. The computePlatform should be Lambda, Server, +// or ECS. // // See also, https://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/ListDeploymentInstances // @@ -3603,6 +3699,12 @@ func (c *CodeDeploy) ListDeploymentsRequest(input *ListDeploymentsInput) (req *r // * InvalidNextTokenException // The next token was specified in an invalid format. // +// * InvalidExternalIdException +// The external ID was specified in an invalid format. +// +// * InvalidInputException +// The input was specified in an invalid format. +// // See also, 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) @@ -3895,8 +3997,9 @@ func (c *CodeDeploy) ListTagsForResourceRequest(input *ListTagsForResourceInput) // ListTagsForResource API operation for AWS CodeDeploy. // -// Returns a list of tags for the resource identified by a specified ARN. Tags -// are used to organize and categorize your CodeDeploy resources. +// Returns a list of tags for the resource identified by a specified Amazon +// Resource Name (ARN). Tags are used to organize and categorize your CodeDeploy +// resources. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3982,9 +4085,15 @@ func (c *CodeDeploy) PutLifecycleEventHookExecutionStatusRequest(input *PutLifec // PutLifecycleEventHookExecutionStatus API operation for AWS CodeDeploy. // -// Sets the result of a Lambda validation function. The function validates one -// or both lifecycle events (BeforeAllowTraffic and AfterAllowTraffic) and returns -// Succeeded or Failed. +// Sets the result of a Lambda validation function. The function validates lifecycle +// hooks during a deployment that uses the AWS Lambda or Amazon ECS compute +// platform. For AWS Lambda deployments, the available lifecycle hooks are BeforeAllowTraffic +// and AfterAllowTraffic. For Amazon ECS deployments, the available lifecycle +// hooks are BeforeInstall, AfterInstall, AfterAllowTestTraffic, BeforeAllowTraffic, +// and AfterAllowTraffic. Lambda validation functions return Succeeded or Failed. +// For more information, see AppSpec 'hooks' Section for an AWS Lambda Deployment +// (https://docs.aws.amazon.com/codedeploy/latest/userguide/reference-appspec-file-structure-hooks.html#appspec-hooks-lambda) +// and AppSpec 'hooks' Section for an Amazon ECS Deployment (https://docs.aws.amazon.com/codedeploy/latest/userguide/reference-appspec-file-structure-hooks.html#appspec-hooks-ecs). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4520,6 +4629,9 @@ func (c *CodeDeploy) StopDeploymentRequest(input *StopDeploymentInput) (req *req // * InvalidDeploymentIdException // At least one of the deployment IDs was specified in an invalid format. // +// * UnsupportedActionForDeploymentTypeException +// A call was submitted that is not supported for the specified deployment type. +// // See also, 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) @@ -4691,7 +4803,7 @@ func (c *CodeDeploy) UntagResourceRequest(input *UntagResourceInput) (req *reque // UntagResource API operation for AWS CodeDeploy. // // Disassociates a resource from a list of tags. The resource is identified -// by the ResourceArn input parameter. The tags are identfied by the list of +// by the ResourceArn input parameter. The tags are identified by the list of // keys in the TagKeys input parameter. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -5006,6 +5118,10 @@ func (c *CodeDeploy) UpdateDeploymentGroupRequest(input *UpdateDeploymentGroupIn // The Amazon ECS service is associated with more than one deployment groups. // An Amazon ECS service can be associated with only one deployment group. // +// * InvalidTrafficRoutingConfigurationException +// The configuration that specifies how traffic is routed during a deployment +// is invalid. +// // See also, 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) @@ -5803,7 +5919,7 @@ type BatchGetApplicationsInput struct { _ struct{} `type:"structure"` // A list of application names separated by spaces. The maximum number of application - // names you can specify is 25. + // names you can specify is 100. // // ApplicationNames is a required field ApplicationNames []*string `locationName:"applicationNames" type:"list" required:"true"` @@ -6058,6 +6174,9 @@ type BatchGetDeploymentTargetsInput struct { // * For deployments that use the Amazon ECS compute platform, the target // IDs are pairs of Amazon ECS clusters and services specified using the // format :. Their target type is ecsTarget. + // + // * For deployments that are deployed with AWS CloudFormation, the target + // IDs are CloudFormation stack IDs. Their target type is cloudFormationTarget. TargetIds []*string `locationName:"targetIds" type:"list"` } @@ -6096,6 +6215,9 @@ type BatchGetDeploymentTargetsOutput struct { // function. // // * Amazon ECS: The target object is an Amazon ECS service. + // + // * CloudFormation: The target object is an AWS CloudFormation blue/green + // deployment. DeploymentTargets []*DeploymentTarget `locationName:"deploymentTargets" type:"list"` } @@ -6448,6 +6570,89 @@ func (s *BucketNameFilterRequiredException) RequestID() string { return s.RespMetadata.RequestID } +// Information about the target to be updated by an AWS CloudFormation blue/green +// deployment. This target type is used for all deployments initiated by a CloudFormation +// stack update. +type CloudFormationTarget struct { + _ struct{} `type:"structure"` + + // The unique ID of an AWS CloudFormation blue/green deployment. + DeploymentId *string `locationName:"deploymentId" type:"string"` + + // The date and time when the target application was updated by an AWS CloudFormation + // blue/green deployment. + LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp"` + + // The lifecycle events of the AWS CloudFormation blue/green deployment to this + // target application. + LifecycleEvents []*LifecycleEvent `locationName:"lifecycleEvents" type:"list"` + + // The resource type for the AWS CloudFormation blue/green deployment. + ResourceType *string `locationName:"resourceType" type:"string"` + + // The status of an AWS CloudFormation blue/green deployment's target application. + Status *string `locationName:"status" type:"string" enum:"TargetStatus"` + + // The unique ID of a deployment target that has a type of CloudFormationTarget. + TargetId *string `locationName:"targetId" type:"string"` + + // The percentage of production traffic that the target version of an AWS CloudFormation + // blue/green deployment receives. + TargetVersionWeight *float64 `locationName:"targetVersionWeight" type:"double"` +} + +// String returns the string representation +func (s CloudFormationTarget) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CloudFormationTarget) GoString() string { + return s.String() +} + +// SetDeploymentId sets the DeploymentId field's value. +func (s *CloudFormationTarget) SetDeploymentId(v string) *CloudFormationTarget { + s.DeploymentId = &v + return s +} + +// SetLastUpdatedAt sets the LastUpdatedAt field's value. +func (s *CloudFormationTarget) SetLastUpdatedAt(v time.Time) *CloudFormationTarget { + s.LastUpdatedAt = &v + return s +} + +// SetLifecycleEvents sets the LifecycleEvents field's value. +func (s *CloudFormationTarget) SetLifecycleEvents(v []*LifecycleEvent) *CloudFormationTarget { + s.LifecycleEvents = v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *CloudFormationTarget) SetResourceType(v string) *CloudFormationTarget { + s.ResourceType = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CloudFormationTarget) SetStatus(v string) *CloudFormationTarget { + s.Status = &v + return s +} + +// SetTargetId sets the TargetId field's value. +func (s *CloudFormationTarget) SetTargetId(v string) *CloudFormationTarget { + s.TargetId = &v + return s +} + +// SetTargetVersionWeight sets the TargetVersionWeight field's value. +func (s *CloudFormationTarget) SetTargetVersionWeight(v float64) *CloudFormationTarget { + s.TargetVersionWeight = &v + return s +} + type ContinueDeploymentInput struct { _ struct{} `type:"structure"` @@ -6455,9 +6660,9 @@ type ContinueDeploymentInput struct { // traffic to the replacement environment. DeploymentId *string `locationName:"deploymentId" type:"string"` - // The status of the deployment's waiting period. READY_WAIT indicates the deployment - // is ready to start shifting traffic. TERMINATION_WAIT indicates the traffic - // is shifted, but the original target is not terminated. + // The status of the deployment's waiting period. READY_WAIT indicates that + // the deployment is ready to start shifting traffic. TERMINATION_WAIT indicates + // that the traffic is shifted, but the original target is not terminated. DeploymentWaitType *string `locationName:"deploymentWaitType" type:"string" enum:"DeploymentWaitType"` } @@ -6608,7 +6813,7 @@ type CreateDeploymentConfigInput struct { // * FLEET_PERCENT: The value parameter represents the minimum number of // healthy instances as a percentage of the total number of instances in // the deployment. If you specify FLEET_PERCENT, at the start of the deployment, - // AWS CodeDeploy converts the percentage to the equivalent number of instance + // AWS CodeDeploy converts the percentage to the equivalent number of instances // and rounds up fractional instances. // // The value parameter takes an integer. @@ -6729,7 +6934,7 @@ type CreateDeploymentGroupInput struct { // group. // // For more information about the predefined deployment configurations in AWS - // CodeDeploy, see Working with Deployment Groups in AWS CodeDeploy (https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-configurations.html) + // CodeDeploy, see Working with Deployment Configurations in CodeDeploy (https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-configurations.html) // in the AWS CodeDeploy User Guide. DeploymentConfigName *string `locationName:"deploymentConfigName" min:"1" type:"string"` @@ -6771,8 +6976,8 @@ type CreateDeploymentGroupInput struct { // Cannot be used in the same call as onPremisesInstanceTagFilters. OnPremisesTagSet *OnPremisesTagSet `locationName:"onPremisesTagSet" type:"structure"` - // A service role ARN that allows AWS CodeDeploy to act on the user's behalf - // when interacting with AWS services. + // A service role Amazon Resource Name (ARN) that allows AWS CodeDeploy to act + // on the user's behalf when interacting with AWS services. // // ServiceRoleArn is a required field ServiceRoleArn *string `locationName:"serviceRoleArn" type:"string" required:"true"` @@ -7400,6 +7605,44 @@ func (s *DeleteGitHubAccountTokenOutput) SetTokenName(v string) *DeleteGitHubAcc return s } +type DeleteResourcesByExternalIdInput struct { + _ struct{} `type:"structure"` + + // The unique ID of an external resource (for example, a CloudFormation stack + // ID) that is linked to one or more CodeDeploy resources. + ExternalId *string `locationName:"externalId" type:"string"` +} + +// String returns the string representation +func (s DeleteResourcesByExternalIdInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteResourcesByExternalIdInput) GoString() string { + return s.String() +} + +// SetExternalId sets the ExternalId field's value. +func (s *DeleteResourcesByExternalIdInput) SetExternalId(v string) *DeleteResourcesByExternalIdInput { + s.ExternalId = &v + return s +} + +type DeleteResourcesByExternalIdOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteResourcesByExternalIdOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteResourcesByExternalIdOutput) GoString() string { + return s.String() +} + // The deployment is already complete. type DeploymentAlreadyCompletedException struct { _ struct{} `type:"structure"` @@ -7457,7 +7700,7 @@ func (s *DeploymentAlreadyCompletedException) RequestID() string { } // A deployment configuration with the specified name with the IAM user or AWS -// account already exists . +// account already exists. type DeploymentConfigAlreadyExistsException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -7644,8 +7887,8 @@ type DeploymentConfigInfo struct { // Information about the number or percentage of minimum healthy instance. MinimumHealthyHosts *MinimumHealthyHosts `locationName:"minimumHealthyHosts" type:"structure"` - // The configuration that specifies how the deployment traffic is routed. Only - // deployments with a Lambda compute platform can specify this. + // The configuration that specifies how the deployment traffic is routed. Used + // for deployments with a Lambda or ECS compute platform only. TrafficRoutingConfig *TrafficRoutingConfig `locationName:"trafficRoutingConfig" type:"structure"` } @@ -8426,6 +8669,10 @@ type DeploymentInfo struct { // Information about any error associated with this deployment. ErrorInformation *ErrorInformation `locationName:"errorInformation" type:"structure"` + // The unique ID for an external resource (for example, a CloudFormation stack + // ID) that is linked to this deployment. + ExternalId *string `locationName:"externalId" type:"string"` + // Information about how AWS CodeDeploy handles files that already exist in // a deployment target location but weren't part of the previous successful // deployment. @@ -8611,6 +8858,12 @@ func (s *DeploymentInfo) SetErrorInformation(v *ErrorInformation) *DeploymentInf return s } +// SetExternalId sets the ExternalId field's value. +func (s *DeploymentInfo) SetExternalId(v string) *DeploymentInfo { + s.ExternalId = &v + return s +} + // SetFileExistsBehavior sets the FileExistsBehavior field's value. func (s *DeploymentInfo) SetFileExistsBehavior(v string) *DeploymentInfo { s.FileExistsBehavior = &v @@ -8936,7 +9189,7 @@ type DeploymentReadyOption struct { // The number of minutes to wait before the status of a blue/green deployment // is changed to Stopped if rerouting is not started manually. Applies only - // to the STOP_DEPLOYMENT option for actionOnTimeout + // to the STOP_DEPLOYMENT option for actionOnTimeout. WaitTimeInMinutes *int64 `locationName:"waitTimeInMinutes" type:"integer"` } @@ -9000,7 +9253,13 @@ func (s *DeploymentStyle) SetDeploymentType(v string) *DeploymentStyle { type DeploymentTarget struct { _ struct{} `type:"structure"` - // The deployment type that is specific to the deployment's compute platform. + // Information about the target to be updated by an AWS CloudFormation blue/green + // deployment. This target type is used for all deployments initiated by a CloudFormation + // stack update. + CloudFormationTarget *CloudFormationTarget `locationName:"cloudFormationTarget" type:"structure"` + + // The deployment type that is specific to the deployment's compute platform + // or deployments initiated by a CloudFormation stack update. DeploymentTargetType *string `locationName:"deploymentTargetType" type:"string" enum:"DeploymentTargetType"` // Information about the target for a deployment that uses the Amazon ECS compute @@ -9026,6 +9285,12 @@ func (s DeploymentTarget) GoString() string { return s.String() } +// SetCloudFormationTarget sets the CloudFormationTarget field's value. +func (s *DeploymentTarget) SetCloudFormationTarget(v *CloudFormationTarget) *DeploymentTarget { + s.CloudFormationTarget = v + return s +} + // SetDeploymentTargetType sets the DeploymentTargetType field's value. func (s *DeploymentTarget) SetDeploymentTargetType(v string) *DeploymentTarget { s.DeploymentTargetType = &v @@ -9580,7 +9845,7 @@ type ECSTarget struct { // The status an Amazon ECS deployment's target ECS application. Status *string `locationName:"status" type:"string" enum:"TargetStatus"` - // The ARN of the target. + // The Amazon Resource Name (ARN) of the target. TargetArn *string `locationName:"targetArn" type:"string"` // The unique ID of a deployment target that has a type of ecsTarget. @@ -10404,7 +10669,7 @@ type GetDeploymentTargetOutput struct { _ struct{} `type:"structure"` // A deployment target that contains information about a deployment such as - // its status, lifecyle events, and when it was last updated. It also contains + // its status, lifecycle events, and when it was last updated. It also contains // metadata about the deployment target. The deployment target metadata depends // on the deployment target's type (instanceTarget, lambdaTarget, or ecsTarget). DeploymentTarget *DeploymentTarget `locationName:"deploymentTarget" type:"structure"` @@ -11335,7 +11600,7 @@ type InstanceSummary struct { // * GREEN: The instance is part of the replacement environment. InstanceType *string `locationName:"instanceType" type:"string" enum:"InstanceType"` - // A timestamp that indicaties when the instance information was last updated. + // A timestamp that indicates when the instance information was last updated. LastUpdatedAt *time.Time `locationName:"lastUpdatedAt" type:"timestamp"` // A list of lifecycle events for this instance. @@ -11424,7 +11689,7 @@ type InstanceTarget struct { // The status an EC2/On-premises deployment's target instance. Status *string `locationName:"status" type:"string" enum:"TargetStatus"` - // The ARN of the target. + // The Amazon Resource Name (ARN) of the target. TargetArn *string `locationName:"targetArn" type:"string"` // The unique ID of a deployment target that has a type of instanceTarget. @@ -11889,7 +12154,8 @@ func (s *InvalidBucketNameFilterException) RequestID() string { return s.RespMetadata.RequestID } -// The computePlatform is invalid. The computePlatform should be Lambda or Server. +// The computePlatform is invalid. The computePlatform should be Lambda, Server, +// or ECS. type InvalidComputePlatformException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -12621,6 +12887,62 @@ func (s *InvalidECSServiceException) RequestID() string { return s.RespMetadata.RequestID } +// The external ID was specified in an invalid format. +type InvalidExternalIdException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s InvalidExternalIdException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InvalidExternalIdException) GoString() string { + return s.String() +} + +func newErrorInvalidExternalIdException(v protocol.ResponseMetadata) error { + return &InvalidExternalIdException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidExternalIdException) Code() string { + return "InvalidExternalIdException" +} + +// Message returns the exception's message. +func (s *InvalidExternalIdException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidExternalIdException) OrigErr() error { + return nil +} + +func (s *InvalidExternalIdException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidExternalIdException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidExternalIdException) RequestID() string { + return s.RespMetadata.RequestID +} + // An invalid fileExistsBehavior option was specified to determine how AWS CodeDeploy // handles files or directories that already exist in a deployment target location, // but weren't part of the previous successful deployment. Valid values include @@ -14499,8 +14821,9 @@ type LambdaFunctionInfo struct { // The version of a Lambda function that production traffic points to. CurrentVersion *string `locationName:"currentVersion" type:"string"` - // The alias of a Lambda function. For more information, see Introduction to - // AWS Lambda Aliases (https://docs.aws.amazon.com/lambda/latest/dg/aliases-intro.html). + // The alias of a Lambda function. For more information, see AWS Lambda Function + // Aliases (https://docs.aws.amazon.com/lambda/latest/dg/aliases-intro.html) + // in the AWS Lambda Developer Guide. FunctionAlias *string `locationName:"functionAlias" type:"string"` // The name of a Lambda function. @@ -14574,7 +14897,7 @@ type LambdaTarget struct { // The status an AWS Lambda deployment's target Lambda function. Status *string `locationName:"status" type:"string" enum:"TargetStatus"` - // The ARN of the target. + // The Amazon Resource Name (ARN) of the target. TargetArn *string `locationName:"targetArn" type:"string"` // The unique ID of a deployment target that has a type of lambdaTarget. @@ -14883,7 +15206,7 @@ type ListApplicationRevisionsInput struct { ApplicationName *string `locationName:"applicationName" min:"1" type:"string" required:"true"` // Whether to list revisions based on whether the revision is the target revision - // of an deployment group: + // of a deployment group: // // * include: List revisions that are target revisions of a deployment group. // @@ -15469,6 +15792,10 @@ type ListDeploymentsInput struct { // If it is not specified, then applicationName must not be specified. DeploymentGroupName *string `locationName:"deploymentGroupName" min:"1" type:"string"` + // The unique ID of an external resource for returning deployments linked to + // the external resource. + ExternalId *string `locationName:"externalId" type:"string"` + // A subset of deployments to list by status: // // * Created: Include created deployments in the resulting list. @@ -15533,6 +15860,12 @@ func (s *ListDeploymentsInput) SetDeploymentGroupName(v string) *ListDeployments return s } +// SetExternalId sets the ExternalId field's value. +func (s *ListDeploymentsInput) SetExternalId(v string) *ListDeploymentsInput { + s.ExternalId = &v + return s +} + // SetIncludeOnlyStatuses sets the IncludeOnlyStatuses field's value. func (s *ListDeploymentsInput) SetIncludeOnlyStatuses(v []*string) *ListDeploymentsInput { s.IncludeOnlyStatuses = v @@ -15870,16 +16203,16 @@ type MinimumHealthyHosts struct { // The minimum healthy instance type: // - // * HOST_COUNT: The minimum number of healthy instance as an absolute value. + // * HOST_COUNT: The minimum number of healthy instances as an absolute value. // - // * FLEET_PERCENT: The minimum number of healthy instance as a percentage - // of the total number of instance in the deployment. + // * FLEET_PERCENT: The minimum number of healthy instances as a percentage + // of the total number of instances in the deployment. // - // In an example of nine instance, if a HOST_COUNT of six is specified, deploy + // In an example of nine instances, if a HOST_COUNT of six is specified, deploy // to up to three instances at a time. The deployment is successful if six or // more instances are deployed to successfully. Otherwise, the deployment fails. - // If a FLEET_PERCENT of 40 is specified, deploy to up to five instance at a - // time. The deployment is successful if four or more instance are deployed + // If a FLEET_PERCENT of 40 is specified, deploy to up to five instances at + // a time. The deployment is successful if four or more instances are deployed // to successfully. Otherwise, the deployment fails. // // In a call to the GetDeploymentConfig, CodeDeployDefault.OneAtATime returns @@ -16609,6 +16942,10 @@ type RevisionLocation struct { // // * String: A YAML-formatted or JSON-formatted string (AWS Lambda deployments // only). + // + // * AppSpecContent: An AppSpecContent object that contains the contents + // of an AppSpec file for an AWS Lambda or Amazon ECS deployment. The content + // is formatted as JSON or YAML stored as a RawString. RevisionType *string `locationName:"revisionType" type:"string" enum:"RevisionLocationType"` // Information about the location of a revision stored in Amazon S3. @@ -17520,8 +17857,9 @@ func (s *ThrottlingException) RequestID() string { } // A configuration that shifts traffic from one version of a Lambda function -// to another in two increments. The original and target Lambda function versions -// are specified in the deployment's AppSpec file. +// or ECS task set to another in two increments. The original and target Lambda +// function versions or ECS task sets are specified in the deployment's AppSpec +// file. type TimeBasedCanary struct { _ struct{} `type:"structure"` @@ -17557,9 +17895,9 @@ func (s *TimeBasedCanary) SetCanaryPercentage(v int64) *TimeBasedCanary { } // A configuration that shifts traffic from one version of a Lambda function -// to another in equal increments, with an equal number of minutes between each -// increment. The original and target Lambda function versions are specified -// in the deployment's AppSpec file. +// or ECS task set to another in equal increments, with an equal number of minutes +// between each increment. The original and target Lambda function versions +// or ECS task sets are specified in the deployment's AppSpec file. type TimeBasedLinear struct { _ struct{} `type:"structure"` @@ -17636,9 +17974,9 @@ func (s *TimeRange) SetStart(v time.Time) *TimeRange { type TrafficRoute struct { _ struct{} `type:"structure"` - // The ARN of one listener. The listener identifies the route between a target - // group and a load balancer. This is an array of strings with a maximum size - // of one. + // The Amazon Resource Name (ARN) of one listener. The listener identifies the + // route between a target group and a load balancer. This is an array of strings + // with a maximum size of one. ListenerArns []*string `locationName:"listenerArns" type:"list"` } @@ -17659,23 +17997,25 @@ func (s *TrafficRoute) SetListenerArns(v []*string) *TrafficRoute { } // The configuration that specifies how traffic is shifted from one version -// of a Lambda function to another version during an AWS Lambda deployment. +// of a Lambda function to another version during an AWS Lambda deployment, +// or from one Amazon ECS task set to another during an Amazon ECS deployment. type TrafficRoutingConfig struct { _ struct{} `type:"structure"` // A configuration that shifts traffic from one version of a Lambda function - // to another in two increments. The original and target Lambda function versions - // are specified in the deployment's AppSpec file. + // or ECS task set to another in two increments. The original and target Lambda + // function versions or ECS task sets are specified in the deployment's AppSpec + // file. TimeBasedCanary *TimeBasedCanary `locationName:"timeBasedCanary" type:"structure"` // A configuration that shifts traffic from one version of a Lambda function - // to another in equal increments, with an equal number of minutes between each - // increment. The original and target Lambda function versions are specified - // in the deployment's AppSpec file. + // or ECS task set to another in equal increments, with an equal number of minutes + // between each increment. The original and target Lambda function versions + // or ECS task sets are specified in the deployment's AppSpec file. TimeBasedLinear *TimeBasedLinear `locationName:"timeBasedLinear" type:"structure"` // The type of traffic shifting (TimeBasedCanary or TimeBasedLinear) used by - // a deployment configuration . + // a deployment configuration. Type *string `locationName:"type" type:"string" enum:"TrafficRoutingType"` } @@ -17717,8 +18057,9 @@ type TriggerConfig struct { // The name of the notification trigger. TriggerName *string `locationName:"triggerName" type:"string"` - // The ARN of the Amazon Simple Notification Service topic through which notifications - // about deployment or instance events are sent. + // The Amazon Resource Name (ARN) of the Amazon Simple Notification Service + // topic through which notifications about deployment or instance events are + // sent. TriggerTargetArn *string `locationName:"triggerTargetArn" type:"string"` } @@ -17865,8 +18206,8 @@ func (s *UnsupportedActionForDeploymentTypeException) RequestID() string { type UntagResourceInput struct { _ struct{} `type:"structure"` - // The ARN that specifies from which resource to disassociate the tags with - // the keys in the TagKeys input paramter. + // The Amazon Resource Name (ARN) that specifies from which resource to disassociate + // the tags with the keys in the TagKeys input parameter. // // ResourceArn is a required field ResourceArn *string `min:"1" type:"string" required:"true"` @@ -18069,7 +18410,7 @@ type UpdateDeploymentGroupInput struct { ServiceRoleArn *string `locationName:"serviceRoleArn" type:"string"` // Information about triggers to change when the deployment group is updated. - // For examples, see Modify Triggers in an AWS CodeDeploy Deployment Group (https://docs.aws.amazon.com/codedeploy/latest/userguide/how-to-notify-edit.html) + // For examples, see Edit a Trigger in a CodeDeploy Deployment Group (https://docs.aws.amazon.com/codedeploy/latest/userguide/how-to-notify-edit.html) // in the AWS CodeDeploy User Guide. TriggerConfigurations []*TriggerConfig `locationName:"triggerConfigurations" type:"list"` } @@ -18253,6 +18594,15 @@ const ( ApplicationRevisionSortByLastUsedTime = "lastUsedTime" ) +// ApplicationRevisionSortBy_Values returns all elements of the ApplicationRevisionSortBy enum +func ApplicationRevisionSortBy_Values() []string { + return []string{ + ApplicationRevisionSortByRegisterTime, + ApplicationRevisionSortByFirstUsedTime, + ApplicationRevisionSortByLastUsedTime, + } +} + const ( // AutoRollbackEventDeploymentFailure is a AutoRollbackEvent enum value AutoRollbackEventDeploymentFailure = "DEPLOYMENT_FAILURE" @@ -18264,6 +18614,15 @@ const ( AutoRollbackEventDeploymentStopOnRequest = "DEPLOYMENT_STOP_ON_REQUEST" ) +// AutoRollbackEvent_Values returns all elements of the AutoRollbackEvent enum +func AutoRollbackEvent_Values() []string { + return []string{ + AutoRollbackEventDeploymentFailure, + AutoRollbackEventDeploymentStopOnAlarm, + AutoRollbackEventDeploymentStopOnRequest, + } +} + const ( // BundleTypeTar is a BundleType enum value BundleTypeTar = "tar" @@ -18281,6 +18640,17 @@ const ( BundleTypeJson = "JSON" ) +// BundleType_Values returns all elements of the BundleType enum +func BundleType_Values() []string { + return []string{ + BundleTypeTar, + BundleTypeTgz, + BundleTypeZip, + BundleTypeYaml, + BundleTypeJson, + } +} + const ( // ComputePlatformServer is a ComputePlatform enum value ComputePlatformServer = "Server" @@ -18292,6 +18662,15 @@ const ( ComputePlatformEcs = "ECS" ) +// ComputePlatform_Values returns all elements of the ComputePlatform enum +func ComputePlatform_Values() []string { + return []string{ + ComputePlatformServer, + ComputePlatformLambda, + ComputePlatformEcs, + } +} + const ( // DeploymentCreatorUser is a DeploymentCreator enum value DeploymentCreatorUser = "user" @@ -18301,8 +18680,29 @@ const ( // DeploymentCreatorCodeDeployRollback is a DeploymentCreator enum value DeploymentCreatorCodeDeployRollback = "codeDeployRollback" + + // DeploymentCreatorCodeDeploy is a DeploymentCreator enum value + DeploymentCreatorCodeDeploy = "CodeDeploy" + + // DeploymentCreatorCloudFormation is a DeploymentCreator enum value + DeploymentCreatorCloudFormation = "CloudFormation" + + // DeploymentCreatorCloudFormationRollback is a DeploymentCreator enum value + DeploymentCreatorCloudFormationRollback = "CloudFormationRollback" ) +// DeploymentCreator_Values returns all elements of the DeploymentCreator enum +func DeploymentCreator_Values() []string { + return []string{ + DeploymentCreatorUser, + DeploymentCreatorAutoscaling, + DeploymentCreatorCodeDeployRollback, + DeploymentCreatorCodeDeploy, + DeploymentCreatorCloudFormation, + DeploymentCreatorCloudFormationRollback, + } +} + const ( // DeploymentOptionWithTrafficControl is a DeploymentOption enum value DeploymentOptionWithTrafficControl = "WITH_TRAFFIC_CONTROL" @@ -18311,6 +18711,14 @@ const ( DeploymentOptionWithoutTrafficControl = "WITHOUT_TRAFFIC_CONTROL" ) +// DeploymentOption_Values returns all elements of the DeploymentOption enum +func DeploymentOption_Values() []string { + return []string{ + DeploymentOptionWithTrafficControl, + DeploymentOptionWithoutTrafficControl, + } +} + const ( // DeploymentReadyActionContinueDeployment is a DeploymentReadyAction enum value DeploymentReadyActionContinueDeployment = "CONTINUE_DEPLOYMENT" @@ -18319,6 +18727,14 @@ const ( DeploymentReadyActionStopDeployment = "STOP_DEPLOYMENT" ) +// DeploymentReadyAction_Values returns all elements of the DeploymentReadyAction enum +func DeploymentReadyAction_Values() []string { + return []string{ + DeploymentReadyActionContinueDeployment, + DeploymentReadyActionStopDeployment, + } +} + const ( // DeploymentStatusCreated is a DeploymentStatus enum value DeploymentStatusCreated = "Created" @@ -18329,6 +18745,9 @@ const ( // DeploymentStatusInProgress is a DeploymentStatus enum value DeploymentStatusInProgress = "InProgress" + // DeploymentStatusBaking is a DeploymentStatus enum value + DeploymentStatusBaking = "Baking" + // DeploymentStatusSucceeded is a DeploymentStatus enum value DeploymentStatusSucceeded = "Succeeded" @@ -18342,6 +18761,20 @@ const ( DeploymentStatusReady = "Ready" ) +// DeploymentStatus_Values returns all elements of the DeploymentStatus enum +func DeploymentStatus_Values() []string { + return []string{ + DeploymentStatusCreated, + DeploymentStatusQueued, + DeploymentStatusInProgress, + DeploymentStatusBaking, + DeploymentStatusSucceeded, + DeploymentStatusFailed, + DeploymentStatusStopped, + DeploymentStatusReady, + } +} + const ( // DeploymentTargetTypeInstanceTarget is a DeploymentTargetType enum value DeploymentTargetTypeInstanceTarget = "InstanceTarget" @@ -18351,8 +18784,21 @@ const ( // DeploymentTargetTypeEcstarget is a DeploymentTargetType enum value DeploymentTargetTypeEcstarget = "ECSTarget" + + // DeploymentTargetTypeCloudFormationTarget is a DeploymentTargetType enum value + DeploymentTargetTypeCloudFormationTarget = "CloudFormationTarget" ) +// DeploymentTargetType_Values returns all elements of the DeploymentTargetType enum +func DeploymentTargetType_Values() []string { + return []string{ + DeploymentTargetTypeInstanceTarget, + DeploymentTargetTypeLambdaTarget, + DeploymentTargetTypeEcstarget, + DeploymentTargetTypeCloudFormationTarget, + } +} + const ( // DeploymentTypeInPlace is a DeploymentType enum value DeploymentTypeInPlace = "IN_PLACE" @@ -18361,6 +18807,14 @@ const ( DeploymentTypeBlueGreen = "BLUE_GREEN" ) +// DeploymentType_Values returns all elements of the DeploymentType enum +func DeploymentType_Values() []string { + return []string{ + DeploymentTypeInPlace, + DeploymentTypeBlueGreen, + } +} + const ( // DeploymentWaitTypeReadyWait is a DeploymentWaitType enum value DeploymentWaitTypeReadyWait = "READY_WAIT" @@ -18369,6 +18823,14 @@ const ( DeploymentWaitTypeTerminationWait = "TERMINATION_WAIT" ) +// DeploymentWaitType_Values returns all elements of the DeploymentWaitType enum +func DeploymentWaitType_Values() []string { + return []string{ + DeploymentWaitTypeReadyWait, + DeploymentWaitTypeTerminationWait, + } +} + const ( // EC2TagFilterTypeKeyOnly is a EC2TagFilterType enum value EC2TagFilterTypeKeyOnly = "KEY_ONLY" @@ -18380,6 +18842,15 @@ const ( EC2TagFilterTypeKeyAndValue = "KEY_AND_VALUE" ) +// EC2TagFilterType_Values returns all elements of the EC2TagFilterType enum +func EC2TagFilterType_Values() []string { + return []string{ + EC2TagFilterTypeKeyOnly, + EC2TagFilterTypeValueOnly, + EC2TagFilterTypeKeyAndValue, + } +} + const ( // ErrorCodeAgentIssue is a ErrorCode enum value ErrorCodeAgentIssue = "AGENT_ISSUE" @@ -18479,8 +18950,51 @@ const ( // ErrorCodeTimeout is a ErrorCode enum value ErrorCodeTimeout = "TIMEOUT" + + // ErrorCodeCloudformationStackFailure is a ErrorCode enum value + ErrorCodeCloudformationStackFailure = "CLOUDFORMATION_STACK_FAILURE" ) +// ErrorCode_Values returns all elements of the ErrorCode enum +func ErrorCode_Values() []string { + return []string{ + ErrorCodeAgentIssue, + ErrorCodeAlarmActive, + ErrorCodeApplicationMissing, + ErrorCodeAutoscalingValidationError, + ErrorCodeAutoScalingConfiguration, + ErrorCodeAutoScalingIamRolePermissions, + ErrorCodeCodedeployResourceCannotBeFound, + ErrorCodeCustomerApplicationUnhealthy, + ErrorCodeDeploymentGroupMissing, + ErrorCodeEcsUpdateError, + ErrorCodeElasticLoadBalancingInvalid, + ErrorCodeElbInvalidInstance, + ErrorCodeHealthConstraints, + ErrorCodeHealthConstraintsInvalid, + ErrorCodeHookExecutionFailure, + ErrorCodeIamRoleMissing, + ErrorCodeIamRolePermissions, + ErrorCodeInternalError, + ErrorCodeInvalidEcsService, + ErrorCodeInvalidLambdaConfiguration, + ErrorCodeInvalidLambdaFunction, + ErrorCodeInvalidRevision, + ErrorCodeManualStop, + ErrorCodeMissingBlueGreenDeploymentConfiguration, + ErrorCodeMissingElbInformation, + ErrorCodeMissingGithubToken, + ErrorCodeNoEc2Subscription, + ErrorCodeNoInstances, + ErrorCodeOverMaxInstances, + ErrorCodeResourceLimitExceeded, + ErrorCodeRevisionMissing, + ErrorCodeThrottled, + ErrorCodeTimeout, + ErrorCodeCloudformationStackFailure, + } +} + const ( // FileExistsBehaviorDisallow is a FileExistsBehavior enum value FileExistsBehaviorDisallow = "DISALLOW" @@ -18492,6 +19006,15 @@ const ( FileExistsBehaviorRetain = "RETAIN" ) +// FileExistsBehavior_Values returns all elements of the FileExistsBehavior enum +func FileExistsBehavior_Values() []string { + return []string{ + FileExistsBehaviorDisallow, + FileExistsBehaviorOverwrite, + FileExistsBehaviorRetain, + } +} + const ( // GreenFleetProvisioningActionDiscoverExisting is a GreenFleetProvisioningAction enum value GreenFleetProvisioningActionDiscoverExisting = "DISCOVER_EXISTING" @@ -18500,6 +19023,14 @@ const ( GreenFleetProvisioningActionCopyAutoScalingGroup = "COPY_AUTO_SCALING_GROUP" ) +// GreenFleetProvisioningAction_Values returns all elements of the GreenFleetProvisioningAction enum +func GreenFleetProvisioningAction_Values() []string { + return []string{ + GreenFleetProvisioningActionDiscoverExisting, + GreenFleetProvisioningActionCopyAutoScalingGroup, + } +} + const ( // InstanceActionTerminate is a InstanceAction enum value InstanceActionTerminate = "TERMINATE" @@ -18508,6 +19039,14 @@ const ( InstanceActionKeepAlive = "KEEP_ALIVE" ) +// InstanceAction_Values returns all elements of the InstanceAction enum +func InstanceAction_Values() []string { + return []string{ + InstanceActionTerminate, + InstanceActionKeepAlive, + } +} + const ( // InstanceStatusPending is a InstanceStatus enum value InstanceStatusPending = "Pending" @@ -18531,6 +19070,19 @@ const ( InstanceStatusReady = "Ready" ) +// InstanceStatus_Values returns all elements of the InstanceStatus enum +func InstanceStatus_Values() []string { + return []string{ + InstanceStatusPending, + InstanceStatusInProgress, + InstanceStatusSucceeded, + InstanceStatusFailed, + InstanceStatusSkipped, + InstanceStatusUnknown, + InstanceStatusReady, + } +} + const ( // InstanceTypeBlue is a InstanceType enum value InstanceTypeBlue = "Blue" @@ -18539,6 +19091,14 @@ const ( InstanceTypeGreen = "Green" ) +// InstanceType_Values returns all elements of the InstanceType enum +func InstanceType_Values() []string { + return []string{ + InstanceTypeBlue, + InstanceTypeGreen, + } +} + const ( // LifecycleErrorCodeSuccess is a LifecycleErrorCode enum value LifecycleErrorCodeSuccess = "Success" @@ -18559,6 +19119,18 @@ const ( LifecycleErrorCodeUnknownError = "UnknownError" ) +// LifecycleErrorCode_Values returns all elements of the LifecycleErrorCode enum +func LifecycleErrorCode_Values() []string { + return []string{ + LifecycleErrorCodeSuccess, + LifecycleErrorCodeScriptMissing, + LifecycleErrorCodeScriptNotExecutable, + LifecycleErrorCodeScriptTimedOut, + LifecycleErrorCodeScriptFailed, + LifecycleErrorCodeUnknownError, + } +} + const ( // LifecycleEventStatusPending is a LifecycleEventStatus enum value LifecycleEventStatusPending = "Pending" @@ -18579,6 +19151,18 @@ const ( LifecycleEventStatusUnknown = "Unknown" ) +// LifecycleEventStatus_Values returns all elements of the LifecycleEventStatus enum +func LifecycleEventStatus_Values() []string { + return []string{ + LifecycleEventStatusPending, + LifecycleEventStatusInProgress, + LifecycleEventStatusSucceeded, + LifecycleEventStatusFailed, + LifecycleEventStatusSkipped, + LifecycleEventStatusUnknown, + } +} + const ( // ListStateFilterActionInclude is a ListStateFilterAction enum value ListStateFilterActionInclude = "include" @@ -18590,6 +19174,15 @@ const ( ListStateFilterActionIgnore = "ignore" ) +// ListStateFilterAction_Values returns all elements of the ListStateFilterAction enum +func ListStateFilterAction_Values() []string { + return []string{ + ListStateFilterActionInclude, + ListStateFilterActionExclude, + ListStateFilterActionIgnore, + } +} + const ( // MinimumHealthyHostsTypeHostCount is a MinimumHealthyHostsType enum value MinimumHealthyHostsTypeHostCount = "HOST_COUNT" @@ -18598,6 +19191,14 @@ const ( MinimumHealthyHostsTypeFleetPercent = "FLEET_PERCENT" ) +// MinimumHealthyHostsType_Values returns all elements of the MinimumHealthyHostsType enum +func MinimumHealthyHostsType_Values() []string { + return []string{ + MinimumHealthyHostsTypeHostCount, + MinimumHealthyHostsTypeFleetPercent, + } +} + const ( // RegistrationStatusRegistered is a RegistrationStatus enum value RegistrationStatusRegistered = "Registered" @@ -18606,6 +19207,14 @@ const ( RegistrationStatusDeregistered = "Deregistered" ) +// RegistrationStatus_Values returns all elements of the RegistrationStatus enum +func RegistrationStatus_Values() []string { + return []string{ + RegistrationStatusRegistered, + RegistrationStatusDeregistered, + } +} + const ( // RevisionLocationTypeS3 is a RevisionLocationType enum value RevisionLocationTypeS3 = "S3" @@ -18620,6 +19229,16 @@ const ( RevisionLocationTypeAppSpecContent = "AppSpecContent" ) +// RevisionLocationType_Values returns all elements of the RevisionLocationType enum +func RevisionLocationType_Values() []string { + return []string{ + RevisionLocationTypeS3, + RevisionLocationTypeGitHub, + RevisionLocationTypeString, + RevisionLocationTypeAppSpecContent, + } +} + const ( // SortOrderAscending is a SortOrder enum value SortOrderAscending = "ascending" @@ -18628,6 +19247,14 @@ const ( SortOrderDescending = "descending" ) +// SortOrder_Values returns all elements of the SortOrder enum +func SortOrder_Values() []string { + return []string{ + SortOrderAscending, + SortOrderDescending, + } +} + const ( // StopStatusPending is a StopStatus enum value StopStatusPending = "Pending" @@ -18636,6 +19263,14 @@ const ( StopStatusSucceeded = "Succeeded" ) +// StopStatus_Values returns all elements of the StopStatus enum +func StopStatus_Values() []string { + return []string{ + StopStatusPending, + StopStatusSucceeded, + } +} + const ( // TagFilterTypeKeyOnly is a TagFilterType enum value TagFilterTypeKeyOnly = "KEY_ONLY" @@ -18647,6 +19282,15 @@ const ( TagFilterTypeKeyAndValue = "KEY_AND_VALUE" ) +// TagFilterType_Values returns all elements of the TagFilterType enum +func TagFilterType_Values() []string { + return []string{ + TagFilterTypeKeyOnly, + TagFilterTypeValueOnly, + TagFilterTypeKeyAndValue, + } +} + const ( // TargetFilterNameTargetStatus is a TargetFilterName enum value TargetFilterNameTargetStatus = "TargetStatus" @@ -18655,6 +19299,14 @@ const ( TargetFilterNameServerInstanceLabel = "ServerInstanceLabel" ) +// TargetFilterName_Values returns all elements of the TargetFilterName enum +func TargetFilterName_Values() []string { + return []string{ + TargetFilterNameTargetStatus, + TargetFilterNameServerInstanceLabel, + } +} + const ( // TargetLabelBlue is a TargetLabel enum value TargetLabelBlue = "Blue" @@ -18663,6 +19315,14 @@ const ( TargetLabelGreen = "Green" ) +// TargetLabel_Values returns all elements of the TargetLabel enum +func TargetLabel_Values() []string { + return []string{ + TargetLabelBlue, + TargetLabelGreen, + } +} + const ( // TargetStatusPending is a TargetStatus enum value TargetStatusPending = "Pending" @@ -18686,6 +19346,19 @@ const ( TargetStatusReady = "Ready" ) +// TargetStatus_Values returns all elements of the TargetStatus enum +func TargetStatus_Values() []string { + return []string{ + TargetStatusPending, + TargetStatusInProgress, + TargetStatusSucceeded, + TargetStatusFailed, + TargetStatusSkipped, + TargetStatusUnknown, + TargetStatusReady, + } +} + const ( // TrafficRoutingTypeTimeBasedCanary is a TrafficRoutingType enum value TrafficRoutingTypeTimeBasedCanary = "TimeBasedCanary" @@ -18697,6 +19370,15 @@ const ( TrafficRoutingTypeAllAtOnce = "AllAtOnce" ) +// TrafficRoutingType_Values returns all elements of the TrafficRoutingType enum +func TrafficRoutingType_Values() []string { + return []string{ + TrafficRoutingTypeTimeBasedCanary, + TrafficRoutingTypeTimeBasedLinear, + TrafficRoutingTypeAllAtOnce, + } +} + const ( // TriggerEventTypeDeploymentStart is a TriggerEventType enum value TriggerEventTypeDeploymentStart = "DeploymentStart" @@ -18728,3 +19410,19 @@ const ( // TriggerEventTypeInstanceReady is a TriggerEventType enum value TriggerEventTypeInstanceReady = "InstanceReady" ) + +// TriggerEventType_Values returns all elements of the TriggerEventType enum +func TriggerEventType_Values() []string { + return []string{ + TriggerEventTypeDeploymentStart, + TriggerEventTypeDeploymentSuccess, + TriggerEventTypeDeploymentFailure, + TriggerEventTypeDeploymentStop, + TriggerEventTypeDeploymentRollback, + TriggerEventTypeDeploymentReady, + TriggerEventTypeInstanceStart, + TriggerEventTypeInstanceSuccess, + TriggerEventTypeInstanceFailure, + TriggerEventTypeInstanceReady, + } +} 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 89a7dac6881..11057d7b21e 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 @@ -68,7 +68,7 @@ const ( // "DeploymentConfigAlreadyExistsException". // // A deployment configuration with the specified name with the IAM user or AWS - // account already exists . + // account already exists. ErrCodeDeploymentConfigAlreadyExistsException = "DeploymentConfigAlreadyExistsException" // ErrCodeDeploymentConfigDoesNotExistException for service response error code @@ -318,7 +318,8 @@ const ( // ErrCodeInvalidComputePlatformException for service response error code // "InvalidComputePlatformException". // - // The computePlatform is invalid. The computePlatform should be Lambda or Server. + // The computePlatform is invalid. The computePlatform should be Lambda, Server, + // or ECS. ErrCodeInvalidComputePlatformException = "InvalidComputePlatformException" // ErrCodeInvalidDeployedStateFilterException for service response error code @@ -397,6 +398,12 @@ const ( // The Amazon ECS service identifier is not valid. ErrCodeInvalidECSServiceException = "InvalidECSServiceException" + // ErrCodeInvalidExternalIdException for service response error code + // "InvalidExternalIdException". + // + // The external ID was specified in an invalid format. + ErrCodeInvalidExternalIdException = "InvalidExternalIdException" + // ErrCodeInvalidFileExistsBehaviorException for service response error code // "InvalidFileExistsBehaviorException". // @@ -772,6 +779,7 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "InvalidEC2TagCombinationException": newErrorInvalidEC2TagCombinationException, "InvalidEC2TagException": newErrorInvalidEC2TagException, "InvalidECSServiceException": newErrorInvalidECSServiceException, + "InvalidExternalIdException": newErrorInvalidExternalIdException, "InvalidFileExistsBehaviorException": newErrorInvalidFileExistsBehaviorException, "InvalidGitHubAccountTokenException": newErrorInvalidGitHubAccountTokenException, "InvalidGitHubAccountTokenNameException": newErrorInvalidGitHubAccountTokenNameException, 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 0c40af453e0..9d13004e466 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 @@ -12747,6 +12747,18 @@ const ( ActionCategoryApproval = "Approval" ) +// ActionCategory_Values returns all elements of the ActionCategory enum +func ActionCategory_Values() []string { + return []string{ + ActionCategorySource, + ActionCategoryBuild, + ActionCategoryDeploy, + ActionCategoryTest, + ActionCategoryInvoke, + ActionCategoryApproval, + } +} + const ( // ActionConfigurationPropertyTypeString is a ActionConfigurationPropertyType enum value ActionConfigurationPropertyTypeString = "String" @@ -12758,6 +12770,15 @@ const ( ActionConfigurationPropertyTypeBoolean = "Boolean" ) +// ActionConfigurationPropertyType_Values returns all elements of the ActionConfigurationPropertyType enum +func ActionConfigurationPropertyType_Values() []string { + return []string{ + ActionConfigurationPropertyTypeString, + ActionConfigurationPropertyTypeNumber, + ActionConfigurationPropertyTypeBoolean, + } +} + const ( // ActionExecutionStatusInProgress is a ActionExecutionStatus enum value ActionExecutionStatusInProgress = "InProgress" @@ -12772,6 +12793,16 @@ const ( ActionExecutionStatusFailed = "Failed" ) +// ActionExecutionStatus_Values returns all elements of the ActionExecutionStatus enum +func ActionExecutionStatus_Values() []string { + return []string{ + ActionExecutionStatusInProgress, + ActionExecutionStatusAbandoned, + ActionExecutionStatusSucceeded, + ActionExecutionStatusFailed, + } +} + const ( // ActionOwnerAws is a ActionOwner enum value ActionOwnerAws = "AWS" @@ -12783,6 +12814,15 @@ const ( ActionOwnerCustom = "Custom" ) +// ActionOwner_Values returns all elements of the ActionOwner enum +func ActionOwner_Values() []string { + return []string{ + ActionOwnerAws, + ActionOwnerThirdParty, + ActionOwnerCustom, + } +} + const ( // ApprovalStatusApproved is a ApprovalStatus enum value ApprovalStatusApproved = "Approved" @@ -12791,26 +12831,62 @@ const ( ApprovalStatusRejected = "Rejected" ) +// ApprovalStatus_Values returns all elements of the ApprovalStatus enum +func ApprovalStatus_Values() []string { + return []string{ + ApprovalStatusApproved, + ApprovalStatusRejected, + } +} + const ( // ArtifactLocationTypeS3 is a ArtifactLocationType enum value ArtifactLocationTypeS3 = "S3" ) +// ArtifactLocationType_Values returns all elements of the ArtifactLocationType enum +func ArtifactLocationType_Values() []string { + return []string{ + ArtifactLocationTypeS3, + } +} + const ( // ArtifactStoreTypeS3 is a ArtifactStoreType enum value ArtifactStoreTypeS3 = "S3" ) +// ArtifactStoreType_Values returns all elements of the ArtifactStoreType enum +func ArtifactStoreType_Values() []string { + return []string{ + ArtifactStoreTypeS3, + } +} + const ( // BlockerTypeSchedule is a BlockerType enum value BlockerTypeSchedule = "Schedule" ) +// BlockerType_Values returns all elements of the BlockerType enum +func BlockerType_Values() []string { + return []string{ + BlockerTypeSchedule, + } +} + const ( // EncryptionKeyTypeKms is a EncryptionKeyType enum value EncryptionKeyTypeKms = "KMS" ) +// EncryptionKeyType_Values returns all elements of the EncryptionKeyType enum +func EncryptionKeyType_Values() []string { + return []string{ + EncryptionKeyTypeKms, + } +} + const ( // FailureTypeJobFailed is a FailureType enum value FailureTypeJobFailed = "JobFailed" @@ -12831,6 +12907,18 @@ const ( FailureTypeSystemUnavailable = "SystemUnavailable" ) +// FailureType_Values returns all elements of the FailureType enum +func FailureType_Values() []string { + return []string{ + FailureTypeJobFailed, + FailureTypeConfigurationError, + FailureTypePermissionError, + FailureTypeRevisionOutOfSync, + FailureTypeRevisionUnavailable, + FailureTypeSystemUnavailable, + } +} + const ( // JobStatusCreated is a JobStatus enum value JobStatusCreated = "Created" @@ -12854,6 +12942,19 @@ const ( JobStatusFailed = "Failed" ) +// JobStatus_Values returns all elements of the JobStatus enum +func JobStatus_Values() []string { + return []string{ + JobStatusCreated, + JobStatusQueued, + JobStatusDispatched, + JobStatusInProgress, + JobStatusTimedOut, + JobStatusSucceeded, + JobStatusFailed, + } +} + const ( // PipelineExecutionStatusInProgress is a PipelineExecutionStatus enum value PipelineExecutionStatusInProgress = "InProgress" @@ -12874,6 +12975,18 @@ const ( PipelineExecutionStatusFailed = "Failed" ) +// PipelineExecutionStatus_Values returns all elements of the PipelineExecutionStatus enum +func PipelineExecutionStatus_Values() []string { + return []string{ + PipelineExecutionStatusInProgress, + PipelineExecutionStatusStopped, + PipelineExecutionStatusStopping, + PipelineExecutionStatusSucceeded, + PipelineExecutionStatusSuperseded, + PipelineExecutionStatusFailed, + } +} + const ( // StageExecutionStatusInProgress is a StageExecutionStatus enum value StageExecutionStatusInProgress = "InProgress" @@ -12891,11 +13004,29 @@ const ( StageExecutionStatusSucceeded = "Succeeded" ) +// StageExecutionStatus_Values returns all elements of the StageExecutionStatus enum +func StageExecutionStatus_Values() []string { + return []string{ + StageExecutionStatusInProgress, + StageExecutionStatusFailed, + StageExecutionStatusStopped, + StageExecutionStatusStopping, + StageExecutionStatusSucceeded, + } +} + const ( // StageRetryModeFailedActions is a StageRetryMode enum value StageRetryModeFailedActions = "FAILED_ACTIONS" ) +// StageRetryMode_Values returns all elements of the StageRetryMode enum +func StageRetryMode_Values() []string { + return []string{ + StageRetryModeFailedActions, + } +} + const ( // StageTransitionTypeInbound is a StageTransitionType enum value StageTransitionTypeInbound = "Inbound" @@ -12904,6 +13035,14 @@ const ( StageTransitionTypeOutbound = "Outbound" ) +// StageTransitionType_Values returns all elements of the StageTransitionType enum +func StageTransitionType_Values() []string { + return []string{ + StageTransitionTypeInbound, + StageTransitionTypeOutbound, + } +} + const ( // TriggerTypeCreatePipeline is a TriggerType enum value TriggerTypeCreatePipeline = "CreatePipeline" @@ -12924,6 +13063,18 @@ const ( TriggerTypePutActionRevision = "PutActionRevision" ) +// TriggerType_Values returns all elements of the TriggerType enum +func TriggerType_Values() []string { + return []string{ + TriggerTypeCreatePipeline, + TriggerTypeStartPipelineExecution, + TriggerTypePollForSourceChanges, + TriggerTypeWebhook, + TriggerTypeCloudWatchEvent, + TriggerTypePutActionRevision, + } +} + const ( // WebhookAuthenticationTypeGithubHmac is a WebhookAuthenticationType enum value WebhookAuthenticationTypeGithubHmac = "GITHUB_HMAC" @@ -12934,3 +13085,12 @@ const ( // WebhookAuthenticationTypeUnauthenticated is a WebhookAuthenticationType enum value WebhookAuthenticationTypeUnauthenticated = "UNAUTHENTICATED" ) + +// WebhookAuthenticationType_Values returns all elements of the WebhookAuthenticationType enum +func WebhookAuthenticationType_Values() []string { + return []string{ + WebhookAuthenticationTypeGithubHmac, + WebhookAuthenticationTypeIp, + WebhookAuthenticationTypeUnauthenticated, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/codestarnotifications/api.go b/vendor/github.com/aws/aws-sdk-go/service/codestarnotifications/api.go index 9f8640133b4..8f4a3324665 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/codestarnotifications/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/codestarnotifications/api.go @@ -3374,6 +3374,14 @@ const ( DetailTypeFull = "FULL" ) +// DetailType_Values returns all elements of the DetailType enum +func DetailType_Values() []string { + return []string{ + DetailTypeBasic, + DetailTypeFull, + } +} + const ( // ListEventTypesFilterNameResourceType is a ListEventTypesFilterName enum value ListEventTypesFilterNameResourceType = "RESOURCE_TYPE" @@ -3382,6 +3390,14 @@ const ( ListEventTypesFilterNameServiceName = "SERVICE_NAME" ) +// ListEventTypesFilterName_Values returns all elements of the ListEventTypesFilterName enum +func ListEventTypesFilterName_Values() []string { + return []string{ + ListEventTypesFilterNameResourceType, + ListEventTypesFilterNameServiceName, + } +} + const ( // ListNotificationRulesFilterNameEventTypeId is a ListNotificationRulesFilterName enum value ListNotificationRulesFilterNameEventTypeId = "EVENT_TYPE_ID" @@ -3396,6 +3412,16 @@ const ( ListNotificationRulesFilterNameTargetAddress = "TARGET_ADDRESS" ) +// ListNotificationRulesFilterName_Values returns all elements of the ListNotificationRulesFilterName enum +func ListNotificationRulesFilterName_Values() []string { + return []string{ + ListNotificationRulesFilterNameEventTypeId, + ListNotificationRulesFilterNameCreatedBy, + ListNotificationRulesFilterNameResource, + ListNotificationRulesFilterNameTargetAddress, + } +} + const ( // ListTargetsFilterNameTargetType is a ListTargetsFilterName enum value ListTargetsFilterNameTargetType = "TARGET_TYPE" @@ -3407,6 +3433,15 @@ const ( ListTargetsFilterNameTargetStatus = "TARGET_STATUS" ) +// ListTargetsFilterName_Values returns all elements of the ListTargetsFilterName enum +func ListTargetsFilterName_Values() []string { + return []string{ + ListTargetsFilterNameTargetType, + ListTargetsFilterNameTargetAddress, + ListTargetsFilterNameTargetStatus, + } +} + const ( // NotificationRuleStatusEnabled is a NotificationRuleStatus enum value NotificationRuleStatusEnabled = "ENABLED" @@ -3415,6 +3450,14 @@ const ( NotificationRuleStatusDisabled = "DISABLED" ) +// NotificationRuleStatus_Values returns all elements of the NotificationRuleStatus enum +func NotificationRuleStatus_Values() []string { + return []string{ + NotificationRuleStatusEnabled, + NotificationRuleStatusDisabled, + } +} + const ( // TargetStatusPending is a TargetStatus enum value TargetStatusPending = "PENDING" @@ -3431,3 +3474,14 @@ const ( // TargetStatusDeactivated is a TargetStatus enum value TargetStatusDeactivated = "DEACTIVATED" ) + +// TargetStatus_Values returns all elements of the TargetStatus enum +func TargetStatus_Values() []string { + return []string{ + TargetStatusPending, + TargetStatusActive, + TargetStatusUnreachable, + TargetStatusInactive, + TargetStatusDeactivated, + } +} 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 index adea5962eaa..07c69827869 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentity/api.go @@ -5240,6 +5240,14 @@ const ( AmbiguousRoleResolutionTypeDeny = "Deny" ) +// AmbiguousRoleResolutionType_Values returns all elements of the AmbiguousRoleResolutionType enum +func AmbiguousRoleResolutionType_Values() []string { + return []string{ + AmbiguousRoleResolutionTypeAuthenticatedRole, + AmbiguousRoleResolutionTypeDeny, + } +} + const ( // ErrorCodeAccessDenied is a ErrorCode enum value ErrorCodeAccessDenied = "AccessDenied" @@ -5248,6 +5256,14 @@ const ( ErrorCodeInternalServerError = "InternalServerError" ) +// ErrorCode_Values returns all elements of the ErrorCode enum +func ErrorCode_Values() []string { + return []string{ + ErrorCodeAccessDenied, + ErrorCodeInternalServerError, + } +} + const ( // MappingRuleMatchTypeEquals is a MappingRuleMatchType enum value MappingRuleMatchTypeEquals = "Equals" @@ -5262,6 +5278,16 @@ const ( MappingRuleMatchTypeNotEqual = "NotEqual" ) +// MappingRuleMatchType_Values returns all elements of the MappingRuleMatchType enum +func MappingRuleMatchType_Values() []string { + return []string{ + MappingRuleMatchTypeEquals, + MappingRuleMatchTypeContains, + MappingRuleMatchTypeStartsWith, + MappingRuleMatchTypeNotEqual, + } +} + const ( // RoleMappingTypeToken is a RoleMappingType enum value RoleMappingTypeToken = "Token" @@ -5269,3 +5295,11 @@ const ( // RoleMappingTypeRules is a RoleMappingType enum value RoleMappingTypeRules = "Rules" ) + +// RoleMappingType_Values returns all elements of the RoleMappingType enum +func RoleMappingType_Values() []string { + return []string{ + RoleMappingTypeToken, + RoleMappingTypeRules, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/cognitoidentityprovider/api.go b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentityprovider/api.go index 428171c8443..bc509c4b25b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/cognitoidentityprovider/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/cognitoidentityprovider/api.go @@ -383,9 +383,9 @@ func (c *CognitoIdentityProvider) AdminCreateUserRequest(input *AdminCreateUserI // If MessageAction is not set, the default is to send a welcome message via // email or phone (SMS). // -// This message is based on a template that you configured in your call to or -// . This template includes your custom sign-up instructions and placeholders -// for user name and temporary password. +// This message is based on a template that you configured in your call to create +// or update a user pool. This template includes your custom sign-up instructions +// and placeholders for user name and temporary password. // // Alternatively, you can call AdminCreateUser with “SUPPRESS” for the MessageAction // parameter, and Amazon Cognito will not send any email. @@ -737,7 +737,7 @@ func (c *CognitoIdentityProvider) AdminDisableProviderForUserRequest(input *Admi // sign-in. If the user to disable is a linked external IdP user, any link between // that user and an existing user is removed. The next time the external user // (no longer attached to the previously linked DestinationUser) signs in, they -// must create a new user account. See . +// must create a new user account. See AdminLinkProviderForUser (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminLinkProviderForUser.html). // // This action is enabled only for admin access and requires developer credentials. // @@ -756,10 +756,11 @@ func (c *CognitoIdentityProvider) AdminDisableProviderForUserRequest(input *Admi // For de-linking a SAML identity, there are two scenarios. If the linked identity // has not yet been used to sign-in, the ProviderAttributeName and ProviderAttributeValue // must be the same values that were used for the SourceUser when the identities -// were originally linked in the call. (If the linking was done with ProviderAttributeName -// set to Cognito_Subject, the same applies here). However, if the user has -// already signed in, the ProviderAttributeName must be Cognito_Subject and -// ProviderAttributeValue must be the subject of the SAML assertion. +// were originally linked using AdminLinkProviderForUser call. (If the linking +// was done with ProviderAttributeName set to Cognito_Subject, the same applies +// here). However, if the user has already signed in, the ProviderAttributeName +// must be Cognito_Subject and ProviderAttributeValue must be the subject of +// the SAML assertion. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1510,13 +1511,13 @@ func (c *CognitoIdentityProvider) AdminLinkProviderForUserRequest(input *AdminLi // API links that user to a federated user identity, so that when the federated // user identity is used, the user signs in as the existing user account. // +// The maximum number of federated identities linked to a user is 5. +// // Because this API allows a user with an external federated identity to sign // in as an existing user in the user pool, it is critical that it only be used // with external identity providers and provider attributes that have been trusted // by the application owner. // -// See also . -// // This action is enabled only for admin access and requires developer credentials. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1551,6 +1552,10 @@ func (c *CognitoIdentityProvider) AdminLinkProviderForUserRequest(input *AdminLi // account. This exception tells user that an account with this email or phone // already exists. // +// * LimitExceededException +// This exception is thrown when a user exceeds the limit for a requested AWS +// resource. +// // * InternalErrorException // This exception is thrown when Amazon Cognito encounters an internal error. // @@ -2652,7 +2657,8 @@ func (c *CognitoIdentityProvider) AdminSetUserSettingsRequest(input *AdminSetUse // // This action is no longer supported. You can use it to configure only SMS // MFA. You can't use it to configure TOTP software token MFA. To configure -// either type of MFA, use the AdminSetUserMFAPreference action instead. +// either type of MFA, use AdminSetUserMFAPreference (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserMFAPreference.html) +// instead. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3204,6 +3210,9 @@ func (c *CognitoIdentityProvider) AssociateSoftwareTokenRequest(input *Associate // API operation AssociateSoftwareToken for usage and error information. // // Returned Error Types: +// * ConcurrentModificationException +// This exception is thrown if two or more modifications are happening concurrently. +// // * InvalidParameterException // This exception is thrown when the Amazon Cognito service encounters an invalid // parameter. @@ -6060,10 +6069,11 @@ func (c *CognitoIdentityProvider) ForgotPasswordRequest(input *ForgotPasswordInp // code that is required to change the user's password. For the Username parameter, // you can use the username or user alias. The method used to send the confirmation // code is sent according to the specified AccountRecoverySetting. For more -// information, see Recovering User Accounts in the Amazon Cognito Developer -// Guide. If neither a verified phone number nor a verified email exists, an -// InvalidParameterException is thrown. To use the confirmation code for resetting -// the password, call . +// information, see Recovering User Accounts (https://docs.aws.amazon.com/cognito/latest/developerguide/how-to-recover-a-user-account.html) +// in the Amazon Cognito Developer Guide. If neither a verified phone number +// nor a verified email exists, an InvalidParameterException is thrown. To use +// the confirmation code for resetting the password, call ConfirmForgotPassword +// (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ConfirmForgotPassword.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 @@ -7204,6 +7214,7 @@ func (c *CognitoIdentityProvider) InitiateAuthRequest(input *InitiateAuthInput) output = &InitiateAuthOutput{} req = c.newRequest(op, input, output) + req.Config.Credentials = credentials.AnonymousCredentials return } @@ -8828,6 +8839,7 @@ func (c *CognitoIdentityProvider) RespondToAuthChallengeRequest(input *RespondTo output = &RespondToAuthChallengeOutput{} req = c.newRequest(op, input, output) + req.Config.Credentials = credentials.AnonymousCredentials return } @@ -8992,8 +9004,6 @@ func (c *CognitoIdentityProvider) SetRiskConfigurationRequest(input *SetRiskConf // To enable Amazon Cognito advanced security features, update the user pool // to include the UserPoolAddOns keyAdvancedSecurityMode. // -// See . -// // Returns awserr.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. @@ -9414,7 +9424,8 @@ func (c *CognitoIdentityProvider) SetUserSettingsRequest(input *SetUserSettingsI // // This action is no longer supported. You can use it to configure only SMS // MFA. You can't use it to configure TOTP software token MFA. To configure -// either type of MFA, use the SetUserMFAPreference action instead. +// either type of MFA, use SetUserMFAPreference (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SetUserMFAPreference.html) +// instead. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -10699,7 +10710,7 @@ func (c *CognitoIdentityProvider) UpdateUserPoolRequest(input *UpdateUserPoolInp // UpdateUserPool API operation for Amazon Cognito Identity Provider. // // Updates the specified user pool with the specified attributes. You can get -// a list of the current user pool settings with . +// a list of the current user pool settings using DescribeUserPool (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPool.html). // // If you don't provide a value for an attribute, it will be set to the default // value. @@ -10821,7 +10832,8 @@ func (c *CognitoIdentityProvider) UpdateUserPoolClientRequest(input *UpdateUserP // UpdateUserPoolClient API operation for Amazon Cognito Identity Provider. // // Updates the specified user pool app client with the specified attributes. -// You can get a list of the current user pool app client settings with . +// You can get a list of the current user pool app client settings using DescribeUserPoolClient +// (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPoolClient.html). // // If you don't provide a value for an attribute, it will be set to the default // value. @@ -11906,9 +11918,9 @@ type AdminCreateUserInput struct { // An array of name-value pairs that contain user attributes and attribute values // to be set for the user to be created. You can create a user without specifying // any attributes other than Username. However, any attributes that you specify - // as required (in or in the Attributes tab of the console) must be supplied - // either by you (in your call to AdminCreateUser) or by the user (when he or - // she signs up in response to your welcome message). + // as required (when creating a user pool or in the Attributes tab of the console) + // must be supplied either by you (in your call to AdminCreateUser) or by the + // user (when he or she signs up in response to your welcome message). // // For custom attributes, you must prepend the custom: prefix to the attribute // name. @@ -11920,7 +11932,7 @@ type AdminCreateUserInput struct { // // In your call to AdminCreateUser, you can set the email_verified attribute // to True, and you can set the phone_number_verified attribute to True. (You - // can also do this by calling .) + // can also do this by calling AdminUpdateUserAttributes (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html).) // // * email: The email address of the user to whom the message that contains // the code and username will be sent. Required if the email_verified attribute @@ -12742,7 +12754,7 @@ type AdminGetUserOutput struct { // This response parameter is no longer supported. It provides information only // about SMS MFA configurations. It doesn't provide information about TOTP software // token MFA configurations. To look up information about either type of MFA - // configuration, use the AdminGetUserResponse$UserMFASettingList response instead. + // configuration, use UserMFASettingList instead. MFAOptions []*MFAOptionType `type:"list"` // The user's preferred MFA setting. @@ -12902,17 +12914,19 @@ type AdminInitiateAuthInput struct { // that you are invoking. The required values depend on the value of AuthFlow: // // * For USER_SRP_AUTH: USERNAME (required), SRP_A (required), SECRET_HASH - // (required if the app client is configured with a client secret), DEVICE_KEY + // (required if the app client is configured with a client secret), DEVICE_KEY. // // * For REFRESH_TOKEN_AUTH/REFRESH_TOKEN: REFRESH_TOKEN (required), SECRET_HASH - // (required if the app client is configured with a client secret), DEVICE_KEY + // (required if the app client is configured with a client secret), DEVICE_KEY. // // * For ADMIN_NO_SRP_AUTH: USERNAME (required), SECRET_HASH (if app client - // is configured with client secret), PASSWORD (required), DEVICE_KEY + // is configured with client secret), PASSWORD (required), DEVICE_KEY. // // * For CUSTOM_AUTH: USERNAME (required), SECRET_HASH (if app client is - // configured with client secret), DEVICE_KEY - AuthParameters map[string]*string `type:"map"` + // configured with client secret), DEVICE_KEY. To start the authentication + // flow with password verification, include ChallengeName: SRP_A and SRP_A: + // (The SRP_A Value). + AuthParameters map[string]*string `type:"map" sensitive:"true"` // The app client ID. // @@ -13834,7 +13848,7 @@ type AdminRespondToAuthChallengeInput struct { // calls. AnalyticsMetadata *AnalyticsMetadataType `type:"structure"` - // The challenge name. For more information, see . + // The challenge name. For more information, see AdminInitiateAuth (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html). // // ChallengeName is a required field ChallengeName *string `type:"string" required:"true" enum:"ChallengeNameType"` @@ -14015,17 +14029,16 @@ type AdminRespondToAuthChallengeOutput struct { // The result returned by the server in response to the authentication request. AuthenticationResult *AuthenticationResultType `type:"structure"` - // The name of the challenge. For more information, see . + // The name of the challenge. For more information, see AdminInitiateAuth (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html). ChallengeName *string `type:"string" enum:"ChallengeNameType"` - // The challenge parameters. For more information, see . + // The challenge parameters. For more information, see AdminInitiateAuth (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html). ChallengeParameters map[string]*string `type:"map"` // The session which should be passed both ways in challenge-response calls - // to the service. If the or API call determines that the caller needs to go - // through another challenge, they return a session with other challenge parameters. - // This session should be passed as it is to the next RespondToAuthChallenge - // API call. + // to the service. If the caller needs to go through another challenge, they + // return a session with other challenge parameters. This session should be + // passed as it is to the next RespondToAuthChallenge API call. Session *string `min:"20" type:"string"` } @@ -14831,9 +14844,10 @@ func (s *AliasExistsException) RequestID() string { // The Amazon Pinpoint analytics configuration for collecting metrics for a // user pool. // -// Cognito User Pools only supports sending events to Amazon Pinpoint projects -// in the US East (N. Virginia) us-east-1 Region, regardless of the region in -// which the user pool resides. +// In regions where Pinpoint is not available, Cognito User Pools only supports +// sending events to Amazon Pinpoint projects in us-east-1. In regions where +// Pinpoint is available, Cognito User Pools will support sending events to +// Amazon Pinpoint projects within that same region. type AnalyticsConfigurationType struct { _ struct{} `type:"structure"` @@ -15811,7 +15825,7 @@ type ConfirmForgotPasswordInput struct { ClientMetadata map[string]*string `type:"map"` // The confirmation code sent by a user's request to retrieve a forgotten password. - // For more information, see + // For more information, see ForgotPassword (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html). // // ConfirmationCode is a required field ConfirmationCode *string `min:"1" type:"string" required:"true"` @@ -16353,8 +16367,9 @@ type CreateIdentityProviderInput struct { // The identity provider details. The following list describes the provider // detail keys for each identity provider type. // - // * For Google, Facebook and Login with Amazon: client_id client_secret - // authorize_scopes + // * For Google and Login with Amazon: client_id client_secret authorize_scopes + // + // * For Facebook: client_id client_secret authorize_scopes api_version // // * For Sign in with Apple: client_id team_id key_id private_key authorize_scopes // @@ -16363,7 +16378,7 @@ type CreateIdentityProviderInput struct { // URL specified by oidc_issuer key token_url if not available from discovery // URL specified by oidc_issuer key attributes_url if not available from // discovery URL specified by oidc_issuer key jwks_uri if not available from - // discovery URL specified by oidc_issuer key authorize_scopes + // discovery URL specified by oidc_issuer key // // * For SAML providers: MetadataFile OR MetadataURL IDPSignout optional // @@ -16710,6 +16725,11 @@ func (s *CreateUserImportJobOutput) SetUserImportJob(v *UserImportJobType) *Crea type CreateUserPoolClientInput struct { _ struct{} `type:"structure"` + // The time limit, between 5 minutes and 1 day, after which the access token + // is no longer valid and cannot be used. This value will be overridden if you + // have entered a value in TokenValidityUnits. + AccessTokenValidity *int64 `min:"1" type:"integer"` + // The allowed OAuth flows. // // Set to code to initiate a code grant flow, which provides an authorization @@ -16736,9 +16756,10 @@ type CreateUserPoolClientInput struct { // The Amazon Pinpoint analytics configuration for collecting metrics for this // user pool. // - // Cognito User Pools only supports sending events to Amazon Pinpoint projects - // in the US East (N. Virginia) us-east-1 Region, regardless of the region in - // which the user pool resides. + // In regions where Pinpoint is not available, Cognito User Pools only supports + // sending events to Amazon Pinpoint projects in us-east-1. In regions where + // Pinpoint is available, Cognito User Pools will support sending events to + // Amazon Pinpoint projects within that same region. AnalyticsConfiguration *AnalyticsConfigurationType `type:"structure"` // A list of allowed redirect (callback) URLs for the identity providers. @@ -16810,6 +16831,11 @@ type CreateUserPoolClientInput struct { // client being created. GenerateSecret *bool `type:"boolean"` + // The time limit, between 5 minutes and 1 day, after which the ID token is + // no longer valid and cannot be used. This value will be overridden if you + // have entered a value in TokenValidityUnits. + IdTokenValidity *int64 `min:"1" type:"integer"` + // A list of allowed logout URLs for the identity providers. LogoutURLs []*string `type:"list"` @@ -16829,24 +16855,6 @@ type CreateUserPoolClientInput struct { // * LEGACY - This represents the old behavior of Cognito where user existence // related errors are not prevented. // - // This setting affects the behavior of following APIs: - // - // * AdminInitiateAuth - // - // * AdminRespondToAuthChallenge - // - // * InitiateAuth - // - // * RespondToAuthChallenge - // - // * ForgotPassword - // - // * ConfirmForgotPassword - // - // * ConfirmSignUp - // - // * ResendConfirmationCode - // // After February 15th 2020, the value of PreventUserExistenceErrors will default // to ENABLED for newly created user pool clients if no value is provided. PreventUserExistenceErrors *string `type:"string" enum:"PreventUserExistenceErrorTypes"` @@ -16862,6 +16870,10 @@ type CreateUserPoolClientInput struct { // this client. The following are supported: COGNITO, Facebook, Google and LoginWithAmazon. SupportedIdentityProviders []*string `type:"list"` + // The units in which the validity times are represented in. Default for RefreshToken + // is days, and default for ID and access tokens are hours. + TokenValidityUnits *TokenValidityUnitsType `type:"structure"` + // The user pool ID for the user pool where you want to create a user pool client. // // UserPoolId is a required field @@ -16892,6 +16904,9 @@ func (s CreateUserPoolClientInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *CreateUserPoolClientInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "CreateUserPoolClientInput"} + if s.AccessTokenValidity != nil && *s.AccessTokenValidity < 1 { + invalidParams.Add(request.NewErrParamMinValue("AccessTokenValidity", 1)) + } if s.ClientName == nil { invalidParams.Add(request.NewErrParamRequired("ClientName")) } @@ -16901,6 +16916,9 @@ func (s *CreateUserPoolClientInput) Validate() error { if s.DefaultRedirectURI != nil && len(*s.DefaultRedirectURI) < 1 { invalidParams.Add(request.NewErrParamMinLen("DefaultRedirectURI", 1)) } + if s.IdTokenValidity != nil && *s.IdTokenValidity < 1 { + invalidParams.Add(request.NewErrParamMinValue("IdTokenValidity", 1)) + } if s.UserPoolId == nil { invalidParams.Add(request.NewErrParamRequired("UserPoolId")) } @@ -16919,6 +16937,12 @@ func (s *CreateUserPoolClientInput) Validate() error { return nil } +// SetAccessTokenValidity sets the AccessTokenValidity field's value. +func (s *CreateUserPoolClientInput) SetAccessTokenValidity(v int64) *CreateUserPoolClientInput { + s.AccessTokenValidity = &v + return s +} + // SetAllowedOAuthFlows sets the AllowedOAuthFlows field's value. func (s *CreateUserPoolClientInput) SetAllowedOAuthFlows(v []*string) *CreateUserPoolClientInput { s.AllowedOAuthFlows = v @@ -16973,6 +16997,12 @@ func (s *CreateUserPoolClientInput) SetGenerateSecret(v bool) *CreateUserPoolCli return s } +// SetIdTokenValidity sets the IdTokenValidity field's value. +func (s *CreateUserPoolClientInput) SetIdTokenValidity(v int64) *CreateUserPoolClientInput { + s.IdTokenValidity = &v + return s +} + // SetLogoutURLs sets the LogoutURLs field's value. func (s *CreateUserPoolClientInput) SetLogoutURLs(v []*string) *CreateUserPoolClientInput { s.LogoutURLs = v @@ -17003,6 +17033,12 @@ func (s *CreateUserPoolClientInput) SetSupportedIdentityProviders(v []*string) * return s } +// SetTokenValidityUnits sets the TokenValidityUnits field's value. +func (s *CreateUserPoolClientInput) SetTokenValidityUnits(v *TokenValidityUnitsType) *CreateUserPoolClientInput { + s.TokenValidityUnits = v + return s +} + // SetUserPoolId sets the UserPoolId field's value. func (s *CreateUserPoolClientInput) SetUserPoolId(v string) *CreateUserPoolClientInput { s.UserPoolId = &v @@ -17154,10 +17190,6 @@ type CreateUserPoolInput struct { // if the user also has SMS MFA enabled. In the absence of this setting, Cognito // uses the legacy behavior to determine the recovery method where SMS is preferred // over email. - // - // Starting February 1, 2020, the value of AccountRecoverySetting will default - // to verified_email first and verified_phone_number as the second option for - // newly created user pools if no value is provided. AccountRecoverySetting *AccountRecoverySettingType `type:"structure"` // The configuration for AdminCreateUser requests. @@ -17234,7 +17266,8 @@ type CreateUserPoolInput struct { // You can choose to set case sensitivity on the username input for the selected // sign-in option. For example, when this is set to False, users will be able // to sign in using either "username" or "Username". This configuration is immutable - // once it has been set. For more information, see . + // once it has been set. For more information, see UsernameConfigurationType + // (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UsernameConfigurationType.html). UsernameConfiguration *UsernameConfigurationType `type:"structure"` // The template for the verification message that the user sees when the app @@ -20143,8 +20176,7 @@ type GetUserOutput struct { // This response parameter is no longer supported. It provides information only // about SMS MFA configurations. It doesn't provide information about TOTP software // token MFA configurations. To look up information about either type of MFA - // configuration, use the use the GetUserResponse$UserMFASettingList response - // instead. + // configuration, use UserMFASettingList instead. MFAOptions []*MFAOptionType `type:"list"` // The user's preferred MFA setting. @@ -20552,8 +20584,9 @@ type IdentityProviderType struct { // The identity provider details. The following list describes the provider // detail keys for each identity provider type. // - // * For Google, Facebook and Login with Amazon: client_id client_secret - // authorize_scopes + // * For Google and Login with Amazon: client_id client_secret authorize_scopes + // + // * For Facebook: client_id client_secret authorize_scopes api_version // // * For Sign in with Apple: client_id team_id key_id private_key authorize_scopes // @@ -20684,14 +20717,16 @@ type InitiateAuthInput struct { // that you are invoking. The required values depend on the value of AuthFlow: // // * For USER_SRP_AUTH: USERNAME (required), SRP_A (required), SECRET_HASH - // (required if the app client is configured with a client secret), DEVICE_KEY + // (required if the app client is configured with a client secret), DEVICE_KEY. // // * For REFRESH_TOKEN_AUTH/REFRESH_TOKEN: REFRESH_TOKEN (required), SECRET_HASH - // (required if the app client is configured with a client secret), DEVICE_KEY + // (required if the app client is configured with a client secret), DEVICE_KEY. // // * For CUSTOM_AUTH: USERNAME (required), SECRET_HASH (if app client is - // configured with client secret), DEVICE_KEY - AuthParameters map[string]*string `type:"map"` + // configured with client secret), DEVICE_KEY. To start the authentication + // flow with password verification, include ChallengeName: SRP_A and SRP_A: + // (The SRP_A Value). + AuthParameters map[string]*string `type:"map" sensitive:"true"` // The app client ID. // @@ -20871,10 +20906,9 @@ type InitiateAuthOutput struct { ChallengeParameters map[string]*string `type:"map"` // The session which should be passed both ways in challenge-response calls - // to the service. If the or API call determines that the caller needs to go - // through another challenge, they return a session with other challenge parameters. - // This session should be passed as it is to the next RespondToAuthChallenge - // API call. + // to the service. If the caller needs to go through another challenge, they + // return a session with other challenge parameters. This session should be + // passed as it is to the next RespondToAuthChallenge API call. Session *string `min:"20" type:"string"` } @@ -22721,12 +22755,6 @@ func (s *MFAMethodNotFoundException) RequestID() string { // This data type is no longer supported. You can use it only for SMS MFA configurations. // You can't use it for TOTP software token MFA configurations. -// -// To set either type of MFA configuration, use the AdminSetUserMFAPreference -// or SetUserMFAPreference actions. -// -// To look up information about either type of MFA configuration, use the AdminGetUserResponse$UserMFASettingList -// or GetUserResponse$UserMFASettingList responses. type MFAOptionType struct { _ struct{} `type:"structure"` @@ -23835,7 +23863,7 @@ type RespondToAuthChallengeInput struct { // calls. AnalyticsMetadata *AnalyticsMetadataType `type:"structure"` - // The challenge name. For more information, see . + // The challenge name. For more information, see InitiateAuth (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html). // // ADMIN_NO_SRP_AUTH is not a valid value. // @@ -23997,17 +24025,16 @@ type RespondToAuthChallengeOutput struct { // the authentication challenge. AuthenticationResult *AuthenticationResultType `type:"structure"` - // The challenge name. For more information, see . + // The challenge name. For more information, see InitiateAuth (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html). ChallengeName *string `type:"string" enum:"ChallengeNameType"` - // The challenge parameters. For more information, see . + // The challenge parameters. For more information, see InitiateAuth (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html). ChallengeParameters map[string]*string `type:"map"` // The session which should be passed both ways in challenge-response calls - // to the service. If the or API call determines that the caller needs to go - // through another challenge, they return a session with other challenge parameters. - // This session should be passed as it is to the next RespondToAuthChallenge - // API call. + // to the service. If the caller needs to go through another challenge, they + // return a session with other challenge parameters. This session should be + // passed as it is to the next RespondToAuthChallenge API call. Session *string `min:"20" type:"string"` } @@ -24200,7 +24227,7 @@ type SchemaAttributeType struct { // Specifies whether the attribute type is developer only. This attribute can // only be modified by an administrator. Users will not be able to modify this // attribute using their access token. For example, DeveloperOnlyAttribute can - // be modified using the API but cannot be updated using the API. + // be modified using AdminUpdateUserAttributes but cannot be updated using UpdateUserAttributes. DeveloperOnlyAttribute *bool `type:"boolean"` // Specifies whether the value of the attribute can be changed. @@ -25580,6 +25607,52 @@ func (s TagResourceOutput) GoString() string { return s.String() } +// The data type for TokenValidityUnits that specifics the time measurements +// for token validity. +type TokenValidityUnitsType struct { + _ struct{} `type:"structure"` + + // A time unit in “seconds”, “minutes”, “hours” or “days” for + // the value in AccessTokenValidity, defaults to hours. + AccessToken *string `type:"string" enum:"TimeUnitsType"` + + // A time unit in “seconds”, “minutes”, “hours” or “days” for + // the value in IdTokenValidity, defaults to hours. + IdToken *string `type:"string" enum:"TimeUnitsType"` + + // A time unit in “seconds”, “minutes”, “hours” or “days” for + // the value in RefreshTokenValidity, defaults to days. + RefreshToken *string `type:"string" enum:"TimeUnitsType"` +} + +// String returns the string representation +func (s TokenValidityUnitsType) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TokenValidityUnitsType) GoString() string { + return s.String() +} + +// SetAccessToken sets the AccessToken field's value. +func (s *TokenValidityUnitsType) SetAccessToken(v string) *TokenValidityUnitsType { + s.AccessToken = &v + return s +} + +// SetIdToken sets the IdToken field's value. +func (s *TokenValidityUnitsType) SetIdToken(v string) *TokenValidityUnitsType { + s.IdToken = &v + return s +} + +// SetRefreshToken sets the RefreshToken field's value. +func (s *TokenValidityUnitsType) SetRefreshToken(v string) *TokenValidityUnitsType { + s.RefreshToken = &v + return s +} + // This exception is thrown when the user has made too many failed attempts // for a given action (e.g., sign in). type TooManyFailedAttemptsException struct { @@ -26228,7 +26301,7 @@ type UpdateGroupInput struct { GroupName *string `min:"1" type:"string" required:"true"` // The new precedence value for the group. For more information about this parameter, - // see . + // see CreateGroup (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateGroup.html). Precedence *int64 `type:"integer"` // The new role ARN for the group. This is used for setting the cognito:roles @@ -26690,6 +26763,10 @@ func (s *UpdateUserAttributesOutput) SetCodeDeliveryDetailsList(v []*CodeDeliver type UpdateUserPoolClientInput struct { _ struct{} `type:"structure"` + // The time limit, after which the access token is no longer valid and cannot + // be used. + AccessTokenValidity *int64 `min:"1" type:"integer"` + // The allowed OAuth flows. // // Set to code to initiate a code grant flow, which provides an authorization @@ -26716,9 +26793,10 @@ type UpdateUserPoolClientInput struct { // The Amazon Pinpoint analytics configuration for collecting metrics for this // user pool. // - // Cognito User Pools only supports sending events to Amazon Pinpoint projects - // in the US East (N. Virginia) us-east-1 Region, regardless of the region in - // which the user pool resides. + // In regions where Pinpoint is not available, Cognito User Pools only supports + // sending events to Amazon Pinpoint projects in us-east-1. In regions where + // Pinpoint is available, Cognito User Pools will support sending events to + // Amazon Pinpoint projects within that same region. AnalyticsConfiguration *AnalyticsConfigurationType `type:"structure"` // A list of allowed redirect (callback) URLs for the identity providers. @@ -26789,6 +26867,10 @@ type UpdateUserPoolClientInput struct { // * ALLOW_REFRESH_TOKEN_AUTH: Enable authflow to refresh tokens. ExplicitAuthFlows []*string `type:"list"` + // The time limit, after which the ID token is no longer valid and cannot be + // used. + IdTokenValidity *int64 `min:"1" type:"integer"` + // A list of allowed logout URLs for the identity providers. LogoutURLs []*string `type:"list"` @@ -26808,24 +26890,6 @@ type UpdateUserPoolClientInput struct { // * LEGACY - This represents the old behavior of Cognito where user existence // related errors are not prevented. // - // This setting affects the behavior of following APIs: - // - // * AdminInitiateAuth - // - // * AdminRespondToAuthChallenge - // - // * InitiateAuth - // - // * RespondToAuthChallenge - // - // * ForgotPassword - // - // * ConfirmForgotPassword - // - // * ConfirmSignUp - // - // * ResendConfirmationCode - // // After February 15th 2020, the value of PreventUserExistenceErrors will default // to ENABLED for newly created user pool clients if no value is provided. PreventUserExistenceErrors *string `type:"string" enum:"PreventUserExistenceErrorTypes"` @@ -26841,6 +26905,10 @@ type UpdateUserPoolClientInput struct { // this client. SupportedIdentityProviders []*string `type:"list"` + // The units in which the validity times are represented in. Default for RefreshToken + // is days, and default for ID and access tokens are hours. + TokenValidityUnits *TokenValidityUnitsType `type:"structure"` + // The user pool ID for the user pool where you want to update the user pool // client. // @@ -26864,6 +26932,9 @@ func (s UpdateUserPoolClientInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *UpdateUserPoolClientInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "UpdateUserPoolClientInput"} + if s.AccessTokenValidity != nil && *s.AccessTokenValidity < 1 { + invalidParams.Add(request.NewErrParamMinValue("AccessTokenValidity", 1)) + } if s.ClientId == nil { invalidParams.Add(request.NewErrParamRequired("ClientId")) } @@ -26876,6 +26947,9 @@ func (s *UpdateUserPoolClientInput) Validate() error { if s.DefaultRedirectURI != nil && len(*s.DefaultRedirectURI) < 1 { invalidParams.Add(request.NewErrParamMinLen("DefaultRedirectURI", 1)) } + if s.IdTokenValidity != nil && *s.IdTokenValidity < 1 { + invalidParams.Add(request.NewErrParamMinValue("IdTokenValidity", 1)) + } if s.UserPoolId == nil { invalidParams.Add(request.NewErrParamRequired("UserPoolId")) } @@ -26894,6 +26968,12 @@ func (s *UpdateUserPoolClientInput) Validate() error { return nil } +// SetAccessTokenValidity sets the AccessTokenValidity field's value. +func (s *UpdateUserPoolClientInput) SetAccessTokenValidity(v int64) *UpdateUserPoolClientInput { + s.AccessTokenValidity = &v + return s +} + // SetAllowedOAuthFlows sets the AllowedOAuthFlows field's value. func (s *UpdateUserPoolClientInput) SetAllowedOAuthFlows(v []*string) *UpdateUserPoolClientInput { s.AllowedOAuthFlows = v @@ -26948,6 +27028,12 @@ func (s *UpdateUserPoolClientInput) SetExplicitAuthFlows(v []*string) *UpdateUse return s } +// SetIdTokenValidity sets the IdTokenValidity field's value. +func (s *UpdateUserPoolClientInput) SetIdTokenValidity(v int64) *UpdateUserPoolClientInput { + s.IdTokenValidity = &v + return s +} + // SetLogoutURLs sets the LogoutURLs field's value. func (s *UpdateUserPoolClientInput) SetLogoutURLs(v []*string) *UpdateUserPoolClientInput { s.LogoutURLs = v @@ -26978,6 +27064,12 @@ func (s *UpdateUserPoolClientInput) SetSupportedIdentityProviders(v []*string) * return s } +// SetTokenValidityUnits sets the TokenValidityUnits field's value. +func (s *UpdateUserPoolClientInput) SetTokenValidityUnits(v *TokenValidityUnitsType) *UpdateUserPoolClientInput { + s.TokenValidityUnits = v + return s +} + // SetUserPoolId sets the UserPoolId field's value. func (s *UpdateUserPoolClientInput) SetUserPoolId(v string) *UpdateUserPoolClientInput { s.UserPoolId = &v @@ -27956,6 +28048,10 @@ func (s *UserPoolClientDescription) SetUserPoolId(v string) *UserPoolClientDescr type UserPoolClientType struct { _ struct{} `type:"structure"` + // The time limit, specified by tokenValidityUnits, defaulting to hours, after + // which the access token is no longer valid and cannot be used. + AccessTokenValidity *int64 `min:"1" type:"integer"` + // The allowed OAuth flows. // // Set to code to initiate a code grant flow, which provides an authorization @@ -28058,6 +28154,10 @@ type UserPoolClientType struct { // * ALLOW_REFRESH_TOKEN_AUTH: Enable authflow to refresh tokens. ExplicitAuthFlows []*string `type:"list"` + // The time limit, specified by tokenValidityUnits, defaulting to hours, after + // which the refresh token is no longer valid and cannot be used. + IdTokenValidity *int64 `min:"1" type:"integer"` + // The date the user pool client was last modified. LastModifiedDate *time.Time `type:"timestamp"` @@ -28080,24 +28180,6 @@ type UserPoolClientType struct { // * LEGACY - This represents the old behavior of Cognito where user existence // related errors are not prevented. // - // This setting affects the behavior of following APIs: - // - // * AdminInitiateAuth - // - // * AdminRespondToAuthChallenge - // - // * InitiateAuth - // - // * RespondToAuthChallenge - // - // * ForgotPassword - // - // * ConfirmForgotPassword - // - // * ConfirmSignUp - // - // * ResendConfirmationCode - // // After February 15th 2020, the value of PreventUserExistenceErrors will default // to ENABLED for newly created user pool clients if no value is provided. PreventUserExistenceErrors *string `type:"string" enum:"PreventUserExistenceErrorTypes"` @@ -28113,6 +28195,10 @@ type UserPoolClientType struct { // this client. SupportedIdentityProviders []*string `type:"list"` + // The time units used to specify the token validity times of their respective + // token. + TokenValidityUnits *TokenValidityUnitsType `type:"structure"` + // The user pool ID for the user pool client. UserPoolId *string `min:"1" type:"string"` @@ -28130,6 +28216,12 @@ func (s UserPoolClientType) GoString() string { return s.String() } +// SetAccessTokenValidity sets the AccessTokenValidity field's value. +func (s *UserPoolClientType) SetAccessTokenValidity(v int64) *UserPoolClientType { + s.AccessTokenValidity = &v + return s +} + // SetAllowedOAuthFlows sets the AllowedOAuthFlows field's value. func (s *UserPoolClientType) SetAllowedOAuthFlows(v []*string) *UserPoolClientType { s.AllowedOAuthFlows = v @@ -28196,6 +28288,12 @@ func (s *UserPoolClientType) SetExplicitAuthFlows(v []*string) *UserPoolClientTy return s } +// SetIdTokenValidity sets the IdTokenValidity field's value. +func (s *UserPoolClientType) SetIdTokenValidity(v int64) *UserPoolClientType { + s.IdTokenValidity = &v + return s +} + // SetLastModifiedDate sets the LastModifiedDate field's value. func (s *UserPoolClientType) SetLastModifiedDate(v time.Time) *UserPoolClientType { s.LastModifiedDate = &v @@ -28232,6 +28330,12 @@ func (s *UserPoolClientType) SetSupportedIdentityProviders(v []*string) *UserPoo return s } +// SetTokenValidityUnits sets the TokenValidityUnits field's value. +func (s *UserPoolClientType) SetTokenValidityUnits(v *TokenValidityUnitsType) *UserPoolClientType { + s.TokenValidityUnits = v + return s +} + // SetUserPoolId sets the UserPoolId field's value. func (s *UserPoolClientType) SetUserPoolId(v string) *UserPoolClientType { s.UserPoolId = &v @@ -28524,7 +28628,8 @@ type UserPoolType struct { // You can choose to enable case sensitivity on the username input for the selected // sign-in option. For example, when this is set to False, users will be able // to sign in using either "username" or "Username". This configuration is immutable - // once it has been set. For more information, see . + // once it has been set. For more information, see UsernameConfigurationType + // (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UsernameConfigurationType.html). UsernameConfiguration *UsernameConfigurationType `type:"structure"` // The template for verification messages. @@ -29039,7 +29144,8 @@ type VerifySoftwareTokenInput struct { // to the service. Session *string `min:"20" type:"string"` - // The one time password computed using the secret code returned by + // The one time password computed using the secret code returned by AssociateSoftwareToken" + // (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AssociateSoftwareToken.html). // // UserCode is a required field UserCode *string `min:"6" type:"string" required:"true"` @@ -29234,6 +29340,16 @@ const ( AccountTakeoverEventActionTypeNoAction = "NO_ACTION" ) +// AccountTakeoverEventActionType_Values returns all elements of the AccountTakeoverEventActionType enum +func AccountTakeoverEventActionType_Values() []string { + return []string{ + AccountTakeoverEventActionTypeBlock, + AccountTakeoverEventActionTypeMfaIfConfigured, + AccountTakeoverEventActionTypeMfaRequired, + AccountTakeoverEventActionTypeNoAction, + } +} + const ( // AdvancedSecurityModeTypeOff is a AdvancedSecurityModeType enum value AdvancedSecurityModeTypeOff = "OFF" @@ -29245,6 +29361,15 @@ const ( AdvancedSecurityModeTypeEnforced = "ENFORCED" ) +// AdvancedSecurityModeType_Values returns all elements of the AdvancedSecurityModeType enum +func AdvancedSecurityModeType_Values() []string { + return []string{ + AdvancedSecurityModeTypeOff, + AdvancedSecurityModeTypeAudit, + AdvancedSecurityModeTypeEnforced, + } +} + const ( // AliasAttributeTypePhoneNumber is a AliasAttributeType enum value AliasAttributeTypePhoneNumber = "phone_number" @@ -29256,6 +29381,15 @@ const ( AliasAttributeTypePreferredUsername = "preferred_username" ) +// AliasAttributeType_Values returns all elements of the AliasAttributeType enum +func AliasAttributeType_Values() []string { + return []string{ + AliasAttributeTypePhoneNumber, + AliasAttributeTypeEmail, + AliasAttributeTypePreferredUsername, + } +} + const ( // AttributeDataTypeString is a AttributeDataType enum value AttributeDataTypeString = "String" @@ -29270,6 +29404,16 @@ const ( AttributeDataTypeBoolean = "Boolean" ) +// AttributeDataType_Values returns all elements of the AttributeDataType enum +func AttributeDataType_Values() []string { + return []string{ + AttributeDataTypeString, + AttributeDataTypeNumber, + AttributeDataTypeDateTime, + AttributeDataTypeBoolean, + } +} + const ( // AuthFlowTypeUserSrpAuth is a AuthFlowType enum value AuthFlowTypeUserSrpAuth = "USER_SRP_AUTH" @@ -29293,6 +29437,19 @@ const ( AuthFlowTypeAdminUserPasswordAuth = "ADMIN_USER_PASSWORD_AUTH" ) +// AuthFlowType_Values returns all elements of the AuthFlowType enum +func AuthFlowType_Values() []string { + return []string{ + AuthFlowTypeUserSrpAuth, + AuthFlowTypeRefreshTokenAuth, + AuthFlowTypeRefreshToken, + AuthFlowTypeCustomAuth, + AuthFlowTypeAdminNoSrpAuth, + AuthFlowTypeUserPasswordAuth, + AuthFlowTypeAdminUserPasswordAuth, + } +} + const ( // ChallengeNamePassword is a ChallengeName enum value ChallengeNamePassword = "Password" @@ -29301,6 +29458,14 @@ const ( ChallengeNameMfa = "Mfa" ) +// ChallengeName_Values returns all elements of the ChallengeName enum +func ChallengeName_Values() []string { + return []string{ + ChallengeNamePassword, + ChallengeNameMfa, + } +} + const ( // ChallengeNameTypeSmsMfa is a ChallengeNameType enum value ChallengeNameTypeSmsMfa = "SMS_MFA" @@ -29333,6 +29498,22 @@ const ( ChallengeNameTypeNewPasswordRequired = "NEW_PASSWORD_REQUIRED" ) +// ChallengeNameType_Values returns all elements of the ChallengeNameType enum +func ChallengeNameType_Values() []string { + return []string{ + ChallengeNameTypeSmsMfa, + ChallengeNameTypeSoftwareTokenMfa, + ChallengeNameTypeSelectMfaType, + ChallengeNameTypeMfaSetup, + ChallengeNameTypePasswordVerifier, + ChallengeNameTypeCustomChallenge, + ChallengeNameTypeDeviceSrpAuth, + ChallengeNameTypeDevicePasswordVerifier, + ChallengeNameTypeAdminNoSrpAuth, + ChallengeNameTypeNewPasswordRequired, + } +} + const ( // ChallengeResponseSuccess is a ChallengeResponse enum value ChallengeResponseSuccess = "Success" @@ -29341,6 +29522,14 @@ const ( ChallengeResponseFailure = "Failure" ) +// ChallengeResponse_Values returns all elements of the ChallengeResponse enum +func ChallengeResponse_Values() []string { + return []string{ + ChallengeResponseSuccess, + ChallengeResponseFailure, + } +} + const ( // CompromisedCredentialsEventActionTypeBlock is a CompromisedCredentialsEventActionType enum value CompromisedCredentialsEventActionTypeBlock = "BLOCK" @@ -29349,6 +29538,14 @@ const ( CompromisedCredentialsEventActionTypeNoAction = "NO_ACTION" ) +// CompromisedCredentialsEventActionType_Values returns all elements of the CompromisedCredentialsEventActionType enum +func CompromisedCredentialsEventActionType_Values() []string { + return []string{ + CompromisedCredentialsEventActionTypeBlock, + CompromisedCredentialsEventActionTypeNoAction, + } +} + const ( // DefaultEmailOptionTypeConfirmWithLink is a DefaultEmailOptionType enum value DefaultEmailOptionTypeConfirmWithLink = "CONFIRM_WITH_LINK" @@ -29357,6 +29554,14 @@ const ( DefaultEmailOptionTypeConfirmWithCode = "CONFIRM_WITH_CODE" ) +// DefaultEmailOptionType_Values returns all elements of the DefaultEmailOptionType enum +func DefaultEmailOptionType_Values() []string { + return []string{ + DefaultEmailOptionTypeConfirmWithLink, + DefaultEmailOptionTypeConfirmWithCode, + } +} + const ( // DeliveryMediumTypeSms is a DeliveryMediumType enum value DeliveryMediumTypeSms = "SMS" @@ -29365,6 +29570,14 @@ const ( DeliveryMediumTypeEmail = "EMAIL" ) +// DeliveryMediumType_Values returns all elements of the DeliveryMediumType enum +func DeliveryMediumType_Values() []string { + return []string{ + DeliveryMediumTypeSms, + DeliveryMediumTypeEmail, + } +} + const ( // DeviceRememberedStatusTypeRemembered is a DeviceRememberedStatusType enum value DeviceRememberedStatusTypeRemembered = "remembered" @@ -29373,6 +29586,14 @@ const ( DeviceRememberedStatusTypeNotRemembered = "not_remembered" ) +// DeviceRememberedStatusType_Values returns all elements of the DeviceRememberedStatusType enum +func DeviceRememberedStatusType_Values() []string { + return []string{ + DeviceRememberedStatusTypeRemembered, + DeviceRememberedStatusTypeNotRemembered, + } +} + const ( // DomainStatusTypeCreating is a DomainStatusType enum value DomainStatusTypeCreating = "CREATING" @@ -29390,6 +29611,17 @@ const ( DomainStatusTypeFailed = "FAILED" ) +// DomainStatusType_Values returns all elements of the DomainStatusType enum +func DomainStatusType_Values() []string { + return []string{ + DomainStatusTypeCreating, + DomainStatusTypeDeleting, + DomainStatusTypeUpdating, + DomainStatusTypeActive, + DomainStatusTypeFailed, + } +} + const ( // EmailSendingAccountTypeCognitoDefault is a EmailSendingAccountType enum value EmailSendingAccountTypeCognitoDefault = "COGNITO_DEFAULT" @@ -29398,6 +29630,14 @@ const ( EmailSendingAccountTypeDeveloper = "DEVELOPER" ) +// EmailSendingAccountType_Values returns all elements of the EmailSendingAccountType enum +func EmailSendingAccountType_Values() []string { + return []string{ + EmailSendingAccountTypeCognitoDefault, + EmailSendingAccountTypeDeveloper, + } +} + const ( // EventFilterTypeSignIn is a EventFilterType enum value EventFilterTypeSignIn = "SIGN_IN" @@ -29409,6 +29649,15 @@ const ( EventFilterTypeSignUp = "SIGN_UP" ) +// EventFilterType_Values returns all elements of the EventFilterType enum +func EventFilterType_Values() []string { + return []string{ + EventFilterTypeSignIn, + EventFilterTypePasswordChange, + EventFilterTypeSignUp, + } +} + const ( // EventResponseTypeSuccess is a EventResponseType enum value EventResponseTypeSuccess = "Success" @@ -29417,6 +29666,14 @@ const ( EventResponseTypeFailure = "Failure" ) +// EventResponseType_Values returns all elements of the EventResponseType enum +func EventResponseType_Values() []string { + return []string{ + EventResponseTypeSuccess, + EventResponseTypeFailure, + } +} + const ( // EventTypeSignIn is a EventType enum value EventTypeSignIn = "SignIn" @@ -29428,6 +29685,15 @@ const ( EventTypeForgotPassword = "ForgotPassword" ) +// EventType_Values returns all elements of the EventType enum +func EventType_Values() []string { + return []string{ + EventTypeSignIn, + EventTypeSignUp, + EventTypeForgotPassword, + } +} + const ( // ExplicitAuthFlowsTypeAdminNoSrpAuth is a ExplicitAuthFlowsType enum value ExplicitAuthFlowsTypeAdminNoSrpAuth = "ADMIN_NO_SRP_AUTH" @@ -29454,6 +29720,20 @@ const ( ExplicitAuthFlowsTypeAllowRefreshTokenAuth = "ALLOW_REFRESH_TOKEN_AUTH" ) +// ExplicitAuthFlowsType_Values returns all elements of the ExplicitAuthFlowsType enum +func ExplicitAuthFlowsType_Values() []string { + return []string{ + ExplicitAuthFlowsTypeAdminNoSrpAuth, + ExplicitAuthFlowsTypeCustomAuthFlowOnly, + ExplicitAuthFlowsTypeUserPasswordAuth, + ExplicitAuthFlowsTypeAllowAdminUserPasswordAuth, + ExplicitAuthFlowsTypeAllowCustomAuth, + ExplicitAuthFlowsTypeAllowUserPasswordAuth, + ExplicitAuthFlowsTypeAllowUserSrpAuth, + ExplicitAuthFlowsTypeAllowRefreshTokenAuth, + } +} + const ( // FeedbackValueTypeValid is a FeedbackValueType enum value FeedbackValueTypeValid = "Valid" @@ -29462,6 +29742,14 @@ const ( FeedbackValueTypeInvalid = "Invalid" ) +// FeedbackValueType_Values returns all elements of the FeedbackValueType enum +func FeedbackValueType_Values() []string { + return []string{ + FeedbackValueTypeValid, + FeedbackValueTypeInvalid, + } +} + const ( // IdentityProviderTypeTypeSaml is a IdentityProviderTypeType enum value IdentityProviderTypeTypeSaml = "SAML" @@ -29482,6 +29770,18 @@ const ( IdentityProviderTypeTypeOidc = "OIDC" ) +// IdentityProviderTypeType_Values returns all elements of the IdentityProviderTypeType enum +func IdentityProviderTypeType_Values() []string { + return []string{ + IdentityProviderTypeTypeSaml, + IdentityProviderTypeTypeFacebook, + IdentityProviderTypeTypeGoogle, + IdentityProviderTypeTypeLoginWithAmazon, + IdentityProviderTypeTypeSignInWithApple, + IdentityProviderTypeTypeOidc, + } +} + const ( // MessageActionTypeResend is a MessageActionType enum value MessageActionTypeResend = "RESEND" @@ -29490,6 +29790,14 @@ const ( MessageActionTypeSuppress = "SUPPRESS" ) +// MessageActionType_Values returns all elements of the MessageActionType enum +func MessageActionType_Values() []string { + return []string{ + MessageActionTypeResend, + MessageActionTypeSuppress, + } +} + const ( // OAuthFlowTypeCode is a OAuthFlowType enum value OAuthFlowTypeCode = "code" @@ -29501,6 +29809,15 @@ const ( OAuthFlowTypeClientCredentials = "client_credentials" ) +// OAuthFlowType_Values returns all elements of the OAuthFlowType enum +func OAuthFlowType_Values() []string { + return []string{ + OAuthFlowTypeCode, + OAuthFlowTypeImplicit, + OAuthFlowTypeClientCredentials, + } +} + const ( // PreventUserExistenceErrorTypesLegacy is a PreventUserExistenceErrorTypes enum value PreventUserExistenceErrorTypesLegacy = "LEGACY" @@ -29509,6 +29826,14 @@ const ( PreventUserExistenceErrorTypesEnabled = "ENABLED" ) +// PreventUserExistenceErrorTypes_Values returns all elements of the PreventUserExistenceErrorTypes enum +func PreventUserExistenceErrorTypes_Values() []string { + return []string{ + PreventUserExistenceErrorTypesLegacy, + PreventUserExistenceErrorTypesEnabled, + } +} + const ( // RecoveryOptionNameTypeVerifiedEmail is a RecoveryOptionNameType enum value RecoveryOptionNameTypeVerifiedEmail = "verified_email" @@ -29520,6 +29845,15 @@ const ( RecoveryOptionNameTypeAdminOnly = "admin_only" ) +// RecoveryOptionNameType_Values returns all elements of the RecoveryOptionNameType enum +func RecoveryOptionNameType_Values() []string { + return []string{ + RecoveryOptionNameTypeVerifiedEmail, + RecoveryOptionNameTypeVerifiedPhoneNumber, + RecoveryOptionNameTypeAdminOnly, + } +} + const ( // RiskDecisionTypeNoRisk is a RiskDecisionType enum value RiskDecisionTypeNoRisk = "NoRisk" @@ -29531,6 +29865,15 @@ const ( RiskDecisionTypeBlock = "Block" ) +// RiskDecisionType_Values returns all elements of the RiskDecisionType enum +func RiskDecisionType_Values() []string { + return []string{ + RiskDecisionTypeNoRisk, + RiskDecisionTypeAccountTakeover, + RiskDecisionTypeBlock, + } +} + const ( // RiskLevelTypeLow is a RiskLevelType enum value RiskLevelTypeLow = "Low" @@ -29542,6 +29885,15 @@ const ( RiskLevelTypeHigh = "High" ) +// RiskLevelType_Values returns all elements of the RiskLevelType enum +func RiskLevelType_Values() []string { + return []string{ + RiskLevelTypeLow, + RiskLevelTypeMedium, + RiskLevelTypeHigh, + } +} + const ( // StatusTypeEnabled is a StatusType enum value StatusTypeEnabled = "Enabled" @@ -29550,6 +29902,38 @@ const ( StatusTypeDisabled = "Disabled" ) +// StatusType_Values returns all elements of the StatusType enum +func StatusType_Values() []string { + return []string{ + StatusTypeEnabled, + StatusTypeDisabled, + } +} + +const ( + // TimeUnitsTypeSeconds is a TimeUnitsType enum value + TimeUnitsTypeSeconds = "seconds" + + // TimeUnitsTypeMinutes is a TimeUnitsType enum value + TimeUnitsTypeMinutes = "minutes" + + // TimeUnitsTypeHours is a TimeUnitsType enum value + TimeUnitsTypeHours = "hours" + + // TimeUnitsTypeDays is a TimeUnitsType enum value + TimeUnitsTypeDays = "days" +) + +// TimeUnitsType_Values returns all elements of the TimeUnitsType enum +func TimeUnitsType_Values() []string { + return []string{ + TimeUnitsTypeSeconds, + TimeUnitsTypeMinutes, + TimeUnitsTypeHours, + TimeUnitsTypeDays, + } +} + const ( // UserImportJobStatusTypeCreated is a UserImportJobStatusType enum value UserImportJobStatusTypeCreated = "Created" @@ -29576,6 +29960,20 @@ const ( UserImportJobStatusTypeSucceeded = "Succeeded" ) +// UserImportJobStatusType_Values returns all elements of the UserImportJobStatusType enum +func UserImportJobStatusType_Values() []string { + return []string{ + UserImportJobStatusTypeCreated, + UserImportJobStatusTypePending, + UserImportJobStatusTypeInProgress, + UserImportJobStatusTypeStopping, + UserImportJobStatusTypeExpired, + UserImportJobStatusTypeStopped, + UserImportJobStatusTypeFailed, + UserImportJobStatusTypeSucceeded, + } +} + const ( // UserPoolMfaTypeOff is a UserPoolMfaType enum value UserPoolMfaTypeOff = "OFF" @@ -29587,6 +29985,15 @@ const ( UserPoolMfaTypeOptional = "OPTIONAL" ) +// UserPoolMfaType_Values returns all elements of the UserPoolMfaType enum +func UserPoolMfaType_Values() []string { + return []string{ + UserPoolMfaTypeOff, + UserPoolMfaTypeOn, + UserPoolMfaTypeOptional, + } +} + const ( // UserStatusTypeUnconfirmed is a UserStatusType enum value UserStatusTypeUnconfirmed = "UNCONFIRMED" @@ -29610,6 +30017,19 @@ const ( UserStatusTypeForceChangePassword = "FORCE_CHANGE_PASSWORD" ) +// UserStatusType_Values returns all elements of the UserStatusType enum +func UserStatusType_Values() []string { + return []string{ + UserStatusTypeUnconfirmed, + UserStatusTypeConfirmed, + UserStatusTypeArchived, + UserStatusTypeCompromised, + UserStatusTypeUnknown, + UserStatusTypeResetRequired, + UserStatusTypeForceChangePassword, + } +} + const ( // UsernameAttributeTypePhoneNumber is a UsernameAttributeType enum value UsernameAttributeTypePhoneNumber = "phone_number" @@ -29618,6 +30038,14 @@ const ( UsernameAttributeTypeEmail = "email" ) +// UsernameAttributeType_Values returns all elements of the UsernameAttributeType enum +func UsernameAttributeType_Values() []string { + return []string{ + UsernameAttributeTypePhoneNumber, + UsernameAttributeTypeEmail, + } +} + const ( // VerifiedAttributeTypePhoneNumber is a VerifiedAttributeType enum value VerifiedAttributeTypePhoneNumber = "phone_number" @@ -29626,6 +30054,14 @@ const ( VerifiedAttributeTypeEmail = "email" ) +// VerifiedAttributeType_Values returns all elements of the VerifiedAttributeType enum +func VerifiedAttributeType_Values() []string { + return []string{ + VerifiedAttributeTypePhoneNumber, + VerifiedAttributeTypeEmail, + } +} + const ( // VerifySoftwareTokenResponseTypeSuccess is a VerifySoftwareTokenResponseType enum value VerifySoftwareTokenResponseTypeSuccess = "SUCCESS" @@ -29633,3 +30069,11 @@ const ( // VerifySoftwareTokenResponseTypeError is a VerifySoftwareTokenResponseType enum value VerifySoftwareTokenResponseTypeError = "ERROR" ) + +// VerifySoftwareTokenResponseType_Values returns all elements of the VerifySoftwareTokenResponseType enum +func VerifySoftwareTokenResponseType_Values() []string { + return []string{ + VerifySoftwareTokenResponseTypeSuccess, + VerifySoftwareTokenResponseTypeError, + } +} 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 f767f1baf2d..9fc050a16b4 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 @@ -915,8 +915,12 @@ func (c *ConfigService) DeleteOrganizationConfigRuleRequest(input *DeleteOrganiz // DeleteOrganizationConfigRule API operation for AWS Config. // // Deletes the specified organization config rule and all of its evaluation -// results from all member accounts in that organization. Only a master account -// can delete an organization config rule. +// results from all member accounts in that organization. +// +// Only a master account and a delegated administrator account can delete an +// organization config rule. When calling this API with a delegated administrator, +// you must ensure AWS Organizations ListDelegatedAdministrator permissions +// are added. // // AWS Config sets the state of a rule to DELETE_IN_PROGRESS until the deletion // is complete. You cannot update a rule while it is in this state. @@ -1036,7 +1040,11 @@ func (c *ConfigService) DeleteOrganizationConformancePackRequest(input *DeleteOr // // Deletes the specified organization conformance pack and all of the config // rules and remediation actions from all member accounts in that organization. -// Only a master account can delete an organization conformance pack. +// +// Only a master account or a delegated administrator account can delete an +// organization conformance pack. When calling this API with a delegated administrator, +// you must ensure AWS Organizations ListDelegatedAdministrator permissions +// are added. // // AWS Config sets the state of a conformance pack to DELETE_IN_PROGRESS until // the deletion is complete. You cannot update a conformance pack while it is @@ -1343,6 +1351,10 @@ func (c *ConfigService) DeleteRemediationExceptionsRequest(input *DeleteRemediat // // Deletes one or more remediation exceptions mentioned in the resource keys. // +// AWS Config generates a remediation exception when a problem occurs executing +// a remediation action to a specific resource. Remediation exceptions blocks +// auto-remediation until the exception is cleared. +// // Returns awserr.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. @@ -2727,6 +2739,10 @@ func (c *ConfigService) DescribeConformancePackStatusRequest(input *DescribeConf // The specified next token is invalid. Specify the nextToken string that was // returned in the previous response to get the next page of results. // +// * InvalidParameterValueException +// One or more of the specified parameters are invalid. Verify that your parameters +// are valid and try again. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConformancePackStatus func (c *ConfigService) DescribeConformancePackStatus(input *DescribeConformancePackStatusInput) (*DescribeConformancePackStatusOutput, error) { req, out := c.DescribeConformancePackStatusRequest(input) @@ -2813,6 +2829,10 @@ func (c *ConfigService) DescribeConformancePacksRequest(input *DescribeConforman // The specified next token is invalid. Specify the nextToken string that was // returned in the previous response to get the next page of results. // +// * InvalidParameterValueException +// One or more of the specified parameters are invalid. Verify that your parameters +// are valid and try again. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeConformancePacks func (c *ConfigService) DescribeConformancePacks(input *DescribeConformancePacksInput) (*DescribeConformancePacksOutput, error) { req, out := c.DescribeConformancePacksRequest(input) @@ -3047,6 +3067,10 @@ func (c *ConfigService) DescribeOrganizationConfigRuleStatusesRequest(input *Des // // Provides organization config rule deployment status for an organization. // +// Only a master account and a delegated administrator account can call this +// API. When calling this API with a delegated administrator, you must ensure +// AWS Organizations ListDelegatedAdministrator permissions are added. +// // The status is not considered successful until organization config rule is // successfully deployed in all the member accounts with an exception of excluded // accounts. @@ -3056,8 +3080,6 @@ func (c *ConfigService) DescribeOrganizationConfigRuleStatusesRequest(input *Des // rule names. It is only applicable, when you request all the organization // config rules. // -// Only a master account can 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. @@ -3152,13 +3174,15 @@ func (c *ConfigService) DescribeOrganizationConfigRulesRequest(input *DescribeOr // // Returns a list of organization config rules. // +// Only a master account and a delegated administrator account can call this +// API. When calling this API with a delegated administrator, you must ensure +// AWS Organizations ListDelegatedAdministrator permissions are added. +// // When you specify the limit and the next token, you receive a paginated response. // Limit and next token are not applicable if you specify organization config // rule names. It is only applicable, when you request all the organization // config rules. // -// Only a master account can 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. @@ -3253,6 +3277,10 @@ func (c *ConfigService) DescribeOrganizationConformancePackStatusesRequest(input // // Provides organization conformance pack deployment status for an organization. // +// Only a master account and a delegated administrator account can call this +// API. When calling this API with a delegated administrator, you must ensure +// AWS Organizations ListDelegatedAdministrator permissions are added. +// // The status is not considered successful until organization conformance pack // is successfully deployed in all the member accounts with an exception of // excluded accounts. @@ -3262,8 +3290,6 @@ func (c *ConfigService) DescribeOrganizationConformancePackStatusesRequest(input // pack names. They are only applicable, when you request all the organization // conformance packs. // -// Only a master account can 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. @@ -3362,14 +3388,16 @@ func (c *ConfigService) DescribeOrganizationConformancePacksRequest(input *Descr // // Returns a list of organization conformance packs. // +// Only a master account and a delegated administrator account can call this +// API. When calling this API with a delegated administrator, you must ensure +// AWS Organizations ListDelegatedAdministrator permissions are added. +// // When you specify the limit and the next token, you receive a paginated response. // // Limit and next token are not applicable if you specify organization conformance // packs names. They are only applicable, when you request all the organization // conformance packs. // -// Only a master account can 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. @@ -3638,6 +3666,10 @@ func (c *ConfigService) DescribeRemediationExceptionsRequest(input *DescribeReme // of an exception and the time when the exception will be deleted. When you // specify the limit and the next token, you receive a paginated response. // +// AWS Config generates a remediation exception when a problem occurs executing +// a remediation action to a specific resource. Remediation exceptions blocks +// auto-remediation until the exception is cleared. +// // When you specify the limit and the next token, you receive a paginated response. // // Limit and next token are not applicable if you request resources in batch. @@ -5019,7 +5051,9 @@ func (c *ConfigService) GetOrganizationConfigRuleDetailedStatusRequest(input *Ge // Returns detailed status for each member account within an organization for // a given organization config rule. // -// Only a master account can call this API. +// Only a master account and a delegated administrator account can call this +// API. When calling this API with a delegated administrator, you must ensure +// AWS Organizations ListDelegatedAdministrator permissions are added. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -5116,7 +5150,9 @@ func (c *ConfigService) GetOrganizationConformancePackDetailedStatusRequest(inpu // Returns detailed status for each member account within an organization for // a given organization conformance pack. // -// Only a master account can call this API. +// Only a master account and a delegated administrator account can call this +// API. When calling this API with a delegated administrator, you must ensure +// AWS Organizations ListDelegatedAdministrator permissions are added. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -6143,8 +6179,7 @@ func (c *ConfigService) PutConformancePackRequest(input *PutConformancePackInput // // This API creates a service linked role AWSServiceRoleForConfigConforms in // your account. The service linked role is created only when the role does -// not exist in your account. AWS Config verifies the existence of role with -// GetRole action. +// not exist in your account. // // You must specify either the TemplateS3Uri or the TemplateBody parameter, // but not both. If you provide both AWS Config uses the TemplateS3Uri parameter @@ -6481,25 +6516,36 @@ func (c *ConfigService) PutOrganizationConfigRuleRequest(input *PutOrganizationC // PutOrganizationConfigRule API operation for AWS Config. // // Adds or updates organization config rule for your entire organization evaluating -// whether your AWS resources comply with your desired configurations. Only -// a master account can create or update an organization config rule. +// whether your AWS resources comply with your desired configurations. +// +// Only a master account and a delegated administrator can create or update +// an organization config rule. When calling this API with a delegated administrator, +// you must ensure AWS Organizations ListDelegatedAdministrator permissions +// are added. // // This API enables organization service access through the EnableAWSServiceAccess // action and creates a service linked role AWSServiceRoleForConfigMultiAccountSetup -// in the master account of your organization. The service linked role is created -// only when the role does not exist in the master account. AWS Config verifies -// the existence of role with GetRole action. +// in the master or delegated administrator account of your organization. The +// service linked role is created only when the role does not exist in the caller +// account. AWS Config verifies the existence of role with GetRole action. +// +// To use this API with delegated administrator, register a delegated administrator +// by calling AWS Organization register-delegated-administrator for config-multiaccountsetup.amazonaws.com. // // You can use this action to create both custom AWS Config rules and AWS managed // Config rules. If you are adding a new custom AWS Config rule, you must first -// create AWS Lambda function in the master account that the rule invokes to -// evaluate your resources. When you use the PutOrganizationConfigRule action -// to add the rule to AWS Config, you must specify the Amazon Resource Name -// (ARN) that AWS Lambda assigns to the function. If you are adding an AWS managed -// Config rule, specify the rule's identifier for the RuleIdentifier key. +// create AWS Lambda function in the master account or a delegated administrator +// that the rule invokes to evaluate your resources. When you use the PutOrganizationConfigRule +// action to add the rule to AWS Config, you must specify the Amazon Resource +// Name (ARN) that AWS Lambda assigns to the function. If you are adding an +// AWS managed Config rule, specify the rule's identifier for the RuleIdentifier +// key. // // The maximum number of organization config rules that AWS Config supports -// is 150. +// is 150 and 3 delegated administrator per organization. +// +// Prerequisite: Ensure you call EnableAllFeatures API to enable all features +// in an organization. // // Specify either OrganizationCustomRuleMetadata or OrganizationManagedRuleMetadata. // @@ -6649,21 +6695,31 @@ func (c *ConfigService) PutOrganizationConformancePackRequest(input *PutOrganiza // // Deploys conformance packs across member accounts in an AWS Organization. // +// Only a master account and a delegated administrator can call this API. When +// calling this API with a delegated administrator, you must ensure AWS Organizations +// ListDelegatedAdministrator permissions are added. +// // This API enables organization service access for config-multiaccountsetup.amazonaws.com // through the EnableAWSServiceAccess action and creates a service linked role -// AWSServiceRoleForConfigMultiAccountSetup in the master account of your organization. -// The service linked role is created only when the role does not exist in the -// master account. AWS Config verifies the existence of role with GetRole action. +// AWSServiceRoleForConfigMultiAccountSetup in the master or delegated administrator +// account of your organization. The service linked role is created only when +// the role does not exist in the caller account. To use this API with delegated +// administrator, register a delegated administrator by calling AWS Organization +// register-delegate-admin for config-multiaccountsetup.amazonaws.com. +// +// Prerequisite: Ensure you call EnableAllFeatures API to enable all features +// in an organization. // // You must specify either the TemplateS3Uri or the TemplateBody parameter, // but not both. If you provide both AWS Config uses the TemplateS3Uri parameter // and ignores the TemplateBody parameter. // // AWS Config sets the state of a conformance pack to CREATE_IN_PROGRESS and -// UPDATE_IN_PROGRESS until the confomance pack is created or updated. You cannot -// update a conformance pack while it is in this state. +// UPDATE_IN_PROGRESS until the conformance pack is created or updated. You +// cannot update a conformance pack while it is in this state. // -// You can create 6 conformance packs with 25 AWS Config rules in each pack. +// You can create 6 conformance packs with 25 AWS Config rules in each pack +// and 3 delegated administrator per organization. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -6815,6 +6871,9 @@ func (c *ConfigService) PutRemediationConfigurationsRequest(input *PutRemediatio // you to add a remediation configuration. The target (SSM document) must exist // and have permissions to use the target. // +// If you make backward incompatible changes to the SSM document, you must call +// this again to ensure the remediations can 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. @@ -6914,6 +6973,10 @@ func (c *ConfigService) PutRemediationExceptionsRequest(input *PutRemediationExc // for auto-remediation. This API adds a new exception or updates an exisiting // exception for a specific resource with a specific AWS Config rule. // +// AWS Config generates a remediation exception when a problem occurs executing +// a remediation action to a specific resource. Remediation exceptions blocks +// auto-remediation until the exception is cleared. +// // Returns awserr.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. @@ -6926,6 +6989,23 @@ func (c *ConfigService) PutRemediationExceptionsRequest(input *PutRemediationExc // One or more of the specified parameters are invalid. Verify that your parameters // are valid and try again. // +// * InsufficientPermissionsException +// Indicates one of the following errors: +// +// * For PutConfigRule, the rule cannot be created because the IAM role assigned +// to AWS Config lacks permissions to perform the config:Put* action. +// +// * For PutConfigRule, the AWS Lambda function cannot be invoked. Check +// the function ARN, and check the function's permissions. +// +// * For PutOrganizationConfigRule, organization config rule cannot be created +// because you do not have permissions to call IAM GetRole action or create +// a service linked role. +// +// * For PutConformancePack and PutOrganizationConformancePack, a conformance +// pack cannot be created because you do not have permissions: To call IAM +// GetRole action or create a service linked role. To read Amazon S3 bucket. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/PutRemediationExceptions func (c *ConfigService) PutRemediationExceptions(input *PutRemediationExceptionsInput) (*PutRemediationExceptionsOutput, error) { req, out := c.PutRemediationExceptionsRequest(input) @@ -7006,6 +7086,9 @@ func (c *ConfigService) PutResourceConfigRequest(input *PutResourceConfigInput) // resource provided in the request. This API does not change or remediate the // configuration of the resource. // +// Write-only schema properites are not recorded as part of the published configuration +// item. +// // Returns awserr.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. @@ -8489,7 +8572,23 @@ type BaseConfigurationItem struct { // The time when the configuration recording was initiated. ConfigurationItemCaptureTime *time.Time `locationName:"configurationItemCaptureTime" type:"timestamp"` - // The configuration item status. + // The configuration item status. The valid values are: + // + // * OK – The resource configuration has been updated + // + // * ResourceDiscovered – The resource was newly discovered + // + // * ResourceNotRecorded – The resource was discovered but its configuration + // was not recorded since the recorder excludes the recording of resources + // of this type + // + // * ResourceDeleted – The resource was deleted + // + // * ResourceDeletedNotRecorded – The resource was deleted but its configuration + // was not recorded since the recorder excludes the recording of resources + // of this type + // + // The CIs do not incur any cost. ConfigurationItemStatus *string `locationName:"configurationItemStatus" type:"string" enum:"ConfigurationItemStatus"` // An identifier that indicates the ordering of the configuration items of a @@ -9190,6 +9289,8 @@ type ConfigRule struct { // to constrain the resources that can trigger an evaluation for the rule. If // you do not specify a scope, evaluations are triggered when any resource in // the recording group changes. + // + // The scope can be empty. Scope *Scope `type:"structure"` // Provides the rule owner (AWS or customer), the rule identifier, and the notifications @@ -9455,6 +9556,7 @@ type ConfigRuleEvaluationStatus struct { // against the rule. FirstEvaluationStarted *bool `type:"boolean"` + // The time that you last turned off the AWS Config rule. LastDeactivatedTime *time.Time `type:"timestamp"` // The error code that AWS Config returned when the rule last failed. @@ -9691,6 +9793,9 @@ type ConfigurationAggregator struct { // The name of the aggregator. ConfigurationAggregatorName *string `min:"1" type:"string"` + // AWS service that created the configuration aggregator. + CreatedBy *string `min:"1" type:"string"` + // The time stamp when the configuration aggregator was created. CreationTime *time.Time `type:"timestamp"` @@ -9729,6 +9834,12 @@ func (s *ConfigurationAggregator) SetConfigurationAggregatorName(v string) *Conf return s } +// SetCreatedBy sets the CreatedBy field's value. +func (s *ConfigurationAggregator) SetCreatedBy(v string) *ConfigurationAggregator { + s.CreatedBy = &v + return s +} + // SetCreationTime sets the CreationTime field's value. func (s *ConfigurationAggregator) SetCreationTime(v time.Time) *ConfigurationAggregator { s.CreationTime = &v @@ -9775,7 +9886,23 @@ type ConfigurationItem struct { // that are associated with the same resource. ConfigurationItemMD5Hash *string `locationName:"configurationItemMD5Hash" type:"string"` - // The configuration item status. + // The configuration item status. The valid values are: + // + // * OK – The resource configuration has been updated + // + // * ResourceDiscovered – The resource was newly discovered + // + // * ResourceNotRecorded – The resource was discovered but its configuration + // was not recorded since the recorder excludes the recording of resources + // of this type + // + // * ResourceDeleted – The resource was deleted + // + // * ResourceDeletedNotRecorded – The resource was deleted but its configuration + // was not recorded since the recorder excludes the recording of resources + // of this type + // + // The CIs do not incur any cost. ConfigurationItemStatus *string `locationName:"configurationItemStatus" type:"string" enum:"ConfigurationItemStatus"` // An identifier that indicates the ordering of the configuration items of a @@ -10397,8 +10524,8 @@ func (s *ConformancePackEvaluationResult) SetResultRecordedTime(v time.Time) *Co } // Input parameters in the form of key-value pairs for the conformance pack, -// both of which you define. Keys can have a maximum character length of 128 -// characters, and values can have a maximum length of 256 characters. +// both of which you define. Keys can have a maximum character length of 255 +// characters, and values can have a maximum length of 4096 characters. type ConformancePackInputParameter struct { _ struct{} `type:"structure"` @@ -21000,8 +21127,8 @@ type RemediationConfiguration struct { // select a number, the default is 5. // // For example, if you specify MaximumAutomaticAttempts as 5 with RetryAttemptsSeconds - // as 50 seconds, AWS Config throws an exception after the 5th failed attempt - // within 50 seconds. + // as 50 seconds, AWS Config will put a RemediationException on your behalf + // for the failing resource after the 5th failed attempt within 50 seconds. MaximumAutomaticAttempts *int64 `min:"1" type:"integer"` // An object of the RemediationParameterValue. @@ -21029,6 +21156,9 @@ type RemediationConfiguration struct { TargetType *string `type:"string" required:"true" enum:"RemediationTargetType"` // Version of the target. For example, version of the SSM document. + // + // If you make backward incompatible changes to the SSM document, you must call + // PutRemediationConfiguration API again to ensure the remediations can run. TargetVersion *string `type:"string"` } @@ -22152,6 +22282,8 @@ type SelectAggregateResourceConfigInput struct { // The maximum number of query results returned on each page. Limit *int64 `type:"integer"` + // The maximum number of query results returned on each page. AWS Config also + // allows the Limit request parameter. MaxResults *int64 `type:"integer"` // The nextToken string returned in a previous request that you use to request @@ -23269,6 +23401,15 @@ const ( AggregatedSourceStatusTypeOutdated = "OUTDATED" ) +// AggregatedSourceStatusType_Values returns all elements of the AggregatedSourceStatusType enum +func AggregatedSourceStatusType_Values() []string { + return []string{ + AggregatedSourceStatusTypeFailed, + AggregatedSourceStatusTypeSucceeded, + AggregatedSourceStatusTypeOutdated, + } +} + const ( // AggregatedSourceTypeAccount is a AggregatedSourceType enum value AggregatedSourceTypeAccount = "ACCOUNT" @@ -23277,6 +23418,14 @@ const ( AggregatedSourceTypeOrganization = "ORGANIZATION" ) +// AggregatedSourceType_Values returns all elements of the AggregatedSourceType enum +func AggregatedSourceType_Values() []string { + return []string{ + AggregatedSourceTypeAccount, + AggregatedSourceTypeOrganization, + } +} + const ( // ChronologicalOrderReverse is a ChronologicalOrder enum value ChronologicalOrderReverse = "Reverse" @@ -23285,6 +23434,14 @@ const ( ChronologicalOrderForward = "Forward" ) +// ChronologicalOrder_Values returns all elements of the ChronologicalOrder enum +func ChronologicalOrder_Values() []string { + return []string{ + ChronologicalOrderReverse, + ChronologicalOrderForward, + } +} + const ( // ComplianceTypeCompliant is a ComplianceType enum value ComplianceTypeCompliant = "COMPLIANT" @@ -23299,6 +23456,16 @@ const ( ComplianceTypeInsufficientData = "INSUFFICIENT_DATA" ) +// ComplianceType_Values returns all elements of the ComplianceType enum +func ComplianceType_Values() []string { + return []string{ + ComplianceTypeCompliant, + ComplianceTypeNonCompliant, + ComplianceTypeNotApplicable, + ComplianceTypeInsufficientData, + } +} + const ( // ConfigRuleComplianceSummaryGroupKeyAccountId is a ConfigRuleComplianceSummaryGroupKey enum value ConfigRuleComplianceSummaryGroupKeyAccountId = "ACCOUNT_ID" @@ -23307,6 +23474,14 @@ const ( ConfigRuleComplianceSummaryGroupKeyAwsRegion = "AWS_REGION" ) +// ConfigRuleComplianceSummaryGroupKey_Values returns all elements of the ConfigRuleComplianceSummaryGroupKey enum +func ConfigRuleComplianceSummaryGroupKey_Values() []string { + return []string{ + ConfigRuleComplianceSummaryGroupKeyAccountId, + ConfigRuleComplianceSummaryGroupKeyAwsRegion, + } +} + const ( // ConfigRuleStateActive is a ConfigRuleState enum value ConfigRuleStateActive = "ACTIVE" @@ -23321,6 +23496,16 @@ const ( ConfigRuleStateEvaluating = "EVALUATING" ) +// ConfigRuleState_Values returns all elements of the ConfigRuleState enum +func ConfigRuleState_Values() []string { + return []string{ + ConfigRuleStateActive, + ConfigRuleStateDeleting, + ConfigRuleStateDeletingResults, + ConfigRuleStateEvaluating, + } +} + const ( // ConfigurationItemStatusOk is a ConfigurationItemStatus enum value ConfigurationItemStatusOk = "OK" @@ -23338,6 +23523,17 @@ const ( ConfigurationItemStatusResourceDeletedNotRecorded = "ResourceDeletedNotRecorded" ) +// ConfigurationItemStatus_Values returns all elements of the ConfigurationItemStatus enum +func ConfigurationItemStatus_Values() []string { + return []string{ + ConfigurationItemStatusOk, + ConfigurationItemStatusResourceDiscovered, + ConfigurationItemStatusResourceNotRecorded, + ConfigurationItemStatusResourceDeleted, + ConfigurationItemStatusResourceDeletedNotRecorded, + } +} + const ( // ConformancePackComplianceTypeCompliant is a ConformancePackComplianceType enum value ConformancePackComplianceTypeCompliant = "COMPLIANT" @@ -23346,6 +23542,14 @@ const ( ConformancePackComplianceTypeNonCompliant = "NON_COMPLIANT" ) +// ConformancePackComplianceType_Values returns all elements of the ConformancePackComplianceType enum +func ConformancePackComplianceType_Values() []string { + return []string{ + ConformancePackComplianceTypeCompliant, + ConformancePackComplianceTypeNonCompliant, + } +} + const ( // ConformancePackStateCreateInProgress is a ConformancePackState enum value ConformancePackStateCreateInProgress = "CREATE_IN_PROGRESS" @@ -23363,6 +23567,17 @@ const ( ConformancePackStateDeleteFailed = "DELETE_FAILED" ) +// ConformancePackState_Values returns all elements of the ConformancePackState enum +func ConformancePackState_Values() []string { + return []string{ + ConformancePackStateCreateInProgress, + ConformancePackStateCreateComplete, + ConformancePackStateCreateFailed, + ConformancePackStateDeleteInProgress, + ConformancePackStateDeleteFailed, + } +} + const ( // DeliveryStatusSuccess is a DeliveryStatus enum value DeliveryStatusSuccess = "Success" @@ -23374,11 +23589,27 @@ const ( DeliveryStatusNotApplicable = "Not_Applicable" ) +// DeliveryStatus_Values returns all elements of the DeliveryStatus enum +func DeliveryStatus_Values() []string { + return []string{ + DeliveryStatusSuccess, + DeliveryStatusFailure, + DeliveryStatusNotApplicable, + } +} + const ( // EventSourceAwsConfig is a EventSource enum value EventSourceAwsConfig = "aws.config" ) +// EventSource_Values returns all elements of the EventSource enum +func EventSource_Values() []string { + return []string{ + EventSourceAwsConfig, + } +} + const ( // MaximumExecutionFrequencyOneHour is a MaximumExecutionFrequency enum value MaximumExecutionFrequencyOneHour = "One_Hour" @@ -23396,6 +23627,17 @@ const ( MaximumExecutionFrequencyTwentyFourHours = "TwentyFour_Hours" ) +// MaximumExecutionFrequency_Values returns all elements of the MaximumExecutionFrequency enum +func MaximumExecutionFrequency_Values() []string { + return []string{ + MaximumExecutionFrequencyOneHour, + MaximumExecutionFrequencyThreeHours, + MaximumExecutionFrequencySixHours, + MaximumExecutionFrequencyTwelveHours, + MaximumExecutionFrequencyTwentyFourHours, + } +} + const ( // MemberAccountRuleStatusCreateSuccessful is a MemberAccountRuleStatus enum value MemberAccountRuleStatusCreateSuccessful = "CREATE_SUCCESSFUL" @@ -23425,6 +23667,21 @@ const ( MemberAccountRuleStatusUpdateFailed = "UPDATE_FAILED" ) +// MemberAccountRuleStatus_Values returns all elements of the MemberAccountRuleStatus enum +func MemberAccountRuleStatus_Values() []string { + return []string{ + MemberAccountRuleStatusCreateSuccessful, + MemberAccountRuleStatusCreateInProgress, + MemberAccountRuleStatusCreateFailed, + MemberAccountRuleStatusDeleteSuccessful, + MemberAccountRuleStatusDeleteFailed, + MemberAccountRuleStatusDeleteInProgress, + MemberAccountRuleStatusUpdateSuccessful, + MemberAccountRuleStatusUpdateInProgress, + MemberAccountRuleStatusUpdateFailed, + } +} + const ( // MessageTypeConfigurationItemChangeNotification is a MessageType enum value MessageTypeConfigurationItemChangeNotification = "ConfigurationItemChangeNotification" @@ -23439,6 +23696,16 @@ const ( MessageTypeOversizedConfigurationItemChangeNotification = "OversizedConfigurationItemChangeNotification" ) +// MessageType_Values returns all elements of the MessageType enum +func MessageType_Values() []string { + return []string{ + MessageTypeConfigurationItemChangeNotification, + MessageTypeConfigurationSnapshotDeliveryCompleted, + MessageTypeScheduledNotification, + MessageTypeOversizedConfigurationItemChangeNotification, + } +} + const ( // OrganizationConfigRuleTriggerTypeConfigurationItemChangeNotification is a OrganizationConfigRuleTriggerType enum value OrganizationConfigRuleTriggerTypeConfigurationItemChangeNotification = "ConfigurationItemChangeNotification" @@ -23450,6 +23717,15 @@ const ( OrganizationConfigRuleTriggerTypeScheduledNotification = "ScheduledNotification" ) +// OrganizationConfigRuleTriggerType_Values returns all elements of the OrganizationConfigRuleTriggerType enum +func OrganizationConfigRuleTriggerType_Values() []string { + return []string{ + OrganizationConfigRuleTriggerTypeConfigurationItemChangeNotification, + OrganizationConfigRuleTriggerTypeOversizedConfigurationItemChangeNotification, + OrganizationConfigRuleTriggerTypeScheduledNotification, + } +} + const ( // OrganizationResourceDetailedStatusCreateSuccessful is a OrganizationResourceDetailedStatus enum value OrganizationResourceDetailedStatusCreateSuccessful = "CREATE_SUCCESSFUL" @@ -23479,6 +23755,21 @@ const ( OrganizationResourceDetailedStatusUpdateFailed = "UPDATE_FAILED" ) +// OrganizationResourceDetailedStatus_Values returns all elements of the OrganizationResourceDetailedStatus enum +func OrganizationResourceDetailedStatus_Values() []string { + return []string{ + OrganizationResourceDetailedStatusCreateSuccessful, + OrganizationResourceDetailedStatusCreateInProgress, + OrganizationResourceDetailedStatusCreateFailed, + OrganizationResourceDetailedStatusDeleteSuccessful, + OrganizationResourceDetailedStatusDeleteFailed, + OrganizationResourceDetailedStatusDeleteInProgress, + OrganizationResourceDetailedStatusUpdateSuccessful, + OrganizationResourceDetailedStatusUpdateInProgress, + OrganizationResourceDetailedStatusUpdateFailed, + } +} + const ( // OrganizationResourceStatusCreateSuccessful is a OrganizationResourceStatus enum value OrganizationResourceStatusCreateSuccessful = "CREATE_SUCCESSFUL" @@ -23508,6 +23799,21 @@ const ( OrganizationResourceStatusUpdateFailed = "UPDATE_FAILED" ) +// OrganizationResourceStatus_Values returns all elements of the OrganizationResourceStatus enum +func OrganizationResourceStatus_Values() []string { + return []string{ + OrganizationResourceStatusCreateSuccessful, + OrganizationResourceStatusCreateInProgress, + OrganizationResourceStatusCreateFailed, + OrganizationResourceStatusDeleteSuccessful, + OrganizationResourceStatusDeleteFailed, + OrganizationResourceStatusDeleteInProgress, + OrganizationResourceStatusUpdateSuccessful, + OrganizationResourceStatusUpdateInProgress, + OrganizationResourceStatusUpdateFailed, + } +} + const ( // OrganizationRuleStatusCreateSuccessful is a OrganizationRuleStatus enum value OrganizationRuleStatusCreateSuccessful = "CREATE_SUCCESSFUL" @@ -23537,6 +23843,21 @@ const ( OrganizationRuleStatusUpdateFailed = "UPDATE_FAILED" ) +// OrganizationRuleStatus_Values returns all elements of the OrganizationRuleStatus enum +func OrganizationRuleStatus_Values() []string { + return []string{ + OrganizationRuleStatusCreateSuccessful, + OrganizationRuleStatusCreateInProgress, + OrganizationRuleStatusCreateFailed, + OrganizationRuleStatusDeleteSuccessful, + OrganizationRuleStatusDeleteFailed, + OrganizationRuleStatusDeleteInProgress, + OrganizationRuleStatusUpdateSuccessful, + OrganizationRuleStatusUpdateInProgress, + OrganizationRuleStatusUpdateFailed, + } +} + const ( // OwnerCustomLambda is a Owner enum value OwnerCustomLambda = "CUSTOM_LAMBDA" @@ -23545,6 +23866,14 @@ const ( OwnerAws = "AWS" ) +// Owner_Values returns all elements of the Owner enum +func Owner_Values() []string { + return []string{ + OwnerCustomLambda, + OwnerAws, + } +} + const ( // RecorderStatusPending is a RecorderStatus enum value RecorderStatusPending = "Pending" @@ -23556,6 +23885,15 @@ const ( RecorderStatusFailure = "Failure" ) +// RecorderStatus_Values returns all elements of the RecorderStatus enum +func RecorderStatus_Values() []string { + return []string{ + RecorderStatusPending, + RecorderStatusSuccess, + RecorderStatusFailure, + } +} + const ( // RemediationExecutionStateQueued is a RemediationExecutionState enum value RemediationExecutionStateQueued = "QUEUED" @@ -23570,6 +23908,16 @@ const ( RemediationExecutionStateFailed = "FAILED" ) +// RemediationExecutionState_Values returns all elements of the RemediationExecutionState enum +func RemediationExecutionState_Values() []string { + return []string{ + RemediationExecutionStateQueued, + RemediationExecutionStateInProgress, + RemediationExecutionStateSucceeded, + RemediationExecutionStateFailed, + } +} + const ( // RemediationExecutionStepStateSucceeded is a RemediationExecutionStepState enum value RemediationExecutionStepStateSucceeded = "SUCCEEDED" @@ -23581,11 +23929,27 @@ const ( RemediationExecutionStepStateFailed = "FAILED" ) +// RemediationExecutionStepState_Values returns all elements of the RemediationExecutionStepState enum +func RemediationExecutionStepState_Values() []string { + return []string{ + RemediationExecutionStepStateSucceeded, + RemediationExecutionStepStatePending, + RemediationExecutionStepStateFailed, + } +} + const ( // RemediationTargetTypeSsmDocument is a RemediationTargetType enum value RemediationTargetTypeSsmDocument = "SSM_DOCUMENT" ) +// RemediationTargetType_Values returns all elements of the RemediationTargetType enum +func RemediationTargetType_Values() []string { + return []string{ + RemediationTargetTypeSsmDocument, + } +} + const ( // ResourceCountGroupKeyResourceType is a ResourceCountGroupKey enum value ResourceCountGroupKeyResourceType = "RESOURCE_TYPE" @@ -23597,6 +23961,15 @@ const ( ResourceCountGroupKeyAwsRegion = "AWS_REGION" ) +// ResourceCountGroupKey_Values returns all elements of the ResourceCountGroupKey enum +func ResourceCountGroupKey_Values() []string { + return []string{ + ResourceCountGroupKeyResourceType, + ResourceCountGroupKeyAccountId, + ResourceCountGroupKeyAwsRegion, + } +} + const ( // ResourceTypeAwsEc2CustomerGateway is a ResourceType enum value ResourceTypeAwsEc2CustomerGateway = "AWS::EC2::CustomerGateway" @@ -23867,9 +24240,124 @@ const ( // ResourceTypeAwsQldbLedger is a ResourceType enum value ResourceTypeAwsQldbLedger = "AWS::QLDB::Ledger" + + // ResourceTypeAwsSecretsManagerSecret is a ResourceType enum value + ResourceTypeAwsSecretsManagerSecret = "AWS::SecretsManager::Secret" + + // ResourceTypeAwsSnsTopic is a ResourceType enum value + ResourceTypeAwsSnsTopic = "AWS::SNS::Topic" + + // ResourceTypeAwsSsmFileData is a ResourceType enum value + ResourceTypeAwsSsmFileData = "AWS::SSM::FileData" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeAwsEc2CustomerGateway, + ResourceTypeAwsEc2Eip, + ResourceTypeAwsEc2Host, + ResourceTypeAwsEc2Instance, + ResourceTypeAwsEc2InternetGateway, + ResourceTypeAwsEc2NetworkAcl, + ResourceTypeAwsEc2NetworkInterface, + ResourceTypeAwsEc2RouteTable, + ResourceTypeAwsEc2SecurityGroup, + ResourceTypeAwsEc2Subnet, + ResourceTypeAwsCloudTrailTrail, + ResourceTypeAwsEc2Volume, + ResourceTypeAwsEc2Vpc, + ResourceTypeAwsEc2Vpnconnection, + ResourceTypeAwsEc2Vpngateway, + ResourceTypeAwsEc2RegisteredHainstance, + ResourceTypeAwsEc2NatGateway, + ResourceTypeAwsEc2EgressOnlyInternetGateway, + ResourceTypeAwsEc2Vpcendpoint, + ResourceTypeAwsEc2VpcendpointService, + ResourceTypeAwsEc2FlowLog, + ResourceTypeAwsEc2VpcpeeringConnection, + ResourceTypeAwsElasticsearchDomain, + ResourceTypeAwsIamGroup, + ResourceTypeAwsIamPolicy, + ResourceTypeAwsIamRole, + ResourceTypeAwsIamUser, + ResourceTypeAwsElasticLoadBalancingV2LoadBalancer, + ResourceTypeAwsAcmCertificate, + ResourceTypeAwsRdsDbinstance, + ResourceTypeAwsRdsDbsubnetGroup, + ResourceTypeAwsRdsDbsecurityGroup, + ResourceTypeAwsRdsDbsnapshot, + ResourceTypeAwsRdsDbcluster, + ResourceTypeAwsRdsDbclusterSnapshot, + ResourceTypeAwsRdsEventSubscription, + ResourceTypeAwsS3Bucket, + ResourceTypeAwsS3AccountPublicAccessBlock, + ResourceTypeAwsRedshiftCluster, + ResourceTypeAwsRedshiftClusterSnapshot, + ResourceTypeAwsRedshiftClusterParameterGroup, + ResourceTypeAwsRedshiftClusterSecurityGroup, + ResourceTypeAwsRedshiftClusterSubnetGroup, + ResourceTypeAwsRedshiftEventSubscription, + ResourceTypeAwsSsmManagedInstanceInventory, + ResourceTypeAwsCloudWatchAlarm, + ResourceTypeAwsCloudFormationStack, + ResourceTypeAwsElasticLoadBalancingLoadBalancer, + ResourceTypeAwsAutoScalingAutoScalingGroup, + ResourceTypeAwsAutoScalingLaunchConfiguration, + ResourceTypeAwsAutoScalingScalingPolicy, + ResourceTypeAwsAutoScalingScheduledAction, + ResourceTypeAwsDynamoDbTable, + ResourceTypeAwsCodeBuildProject, + ResourceTypeAwsWafRateBasedRule, + ResourceTypeAwsWafRule, + ResourceTypeAwsWafRuleGroup, + ResourceTypeAwsWafWebAcl, + ResourceTypeAwsWafregionalRateBasedRule, + ResourceTypeAwsWafregionalRule, + ResourceTypeAwsWafregionalRuleGroup, + ResourceTypeAwsWafregionalWebAcl, + ResourceTypeAwsCloudFrontDistribution, + ResourceTypeAwsCloudFrontStreamingDistribution, + ResourceTypeAwsLambdaFunction, + ResourceTypeAwsElasticBeanstalkApplication, + ResourceTypeAwsElasticBeanstalkApplicationVersion, + ResourceTypeAwsElasticBeanstalkEnvironment, + ResourceTypeAwsWafv2WebAcl, + ResourceTypeAwsWafv2RuleGroup, + ResourceTypeAwsWafv2Ipset, + ResourceTypeAwsWafv2RegexPatternSet, + ResourceTypeAwsWafv2ManagedRuleSet, + ResourceTypeAwsXrayEncryptionConfig, + ResourceTypeAwsSsmAssociationCompliance, + ResourceTypeAwsSsmPatchCompliance, + ResourceTypeAwsShieldProtection, + ResourceTypeAwsShieldRegionalProtection, + ResourceTypeAwsConfigResourceCompliance, + ResourceTypeAwsApiGatewayStage, + ResourceTypeAwsApiGatewayRestApi, + ResourceTypeAwsApiGatewayV2Stage, + ResourceTypeAwsApiGatewayV2Api, + ResourceTypeAwsCodePipelinePipeline, + ResourceTypeAwsServiceCatalogCloudFormationProvisionedProduct, + ResourceTypeAwsServiceCatalogCloudFormationProduct, + ResourceTypeAwsServiceCatalogPortfolio, + ResourceTypeAwsSqsQueue, + ResourceTypeAwsKmsKey, + ResourceTypeAwsQldbLedger, + ResourceTypeAwsSecretsManagerSecret, + ResourceTypeAwsSnsTopic, + ResourceTypeAwsSsmFileData, + } +} + const ( // ResourceValueTypeResourceId is a ResourceValueType enum value ResourceValueTypeResourceId = "RESOURCE_ID" ) + +// ResourceValueType_Values returns all elements of the ResourceValueType enum +func ResourceValueType_Values() []string { + return []string{ + ResourceValueTypeResourceId, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/costandusagereportservice/api.go b/vendor/github.com/aws/aws-sdk-go/service/costandusagereportservice/api.go index 0c07466c9c7..92f4fc59584 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/costandusagereportservice/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/costandusagereportservice/api.go @@ -1112,6 +1112,23 @@ const ( AWSRegionApEast1 = "ap-east-1" ) +// AWSRegion_Values returns all elements of the AWSRegion enum +func AWSRegion_Values() []string { + return []string{ + AWSRegionUsEast1, + AWSRegionUsWest1, + AWSRegionUsWest2, + AWSRegionEuCentral1, + AWSRegionEuWest1, + AWSRegionApSoutheast1, + AWSRegionApSoutheast2, + AWSRegionApNortheast1, + AWSRegionEuNorth1, + AWSRegionApNortheast3, + AWSRegionApEast1, + } +} + // The types of manifest that you want AWS to create for this report. const ( // AdditionalArtifactRedshift is a AdditionalArtifact enum value @@ -1124,6 +1141,15 @@ const ( AdditionalArtifactAthena = "ATHENA" ) +// AdditionalArtifact_Values returns all elements of the AdditionalArtifact enum +func AdditionalArtifact_Values() []string { + return []string{ + AdditionalArtifactRedshift, + AdditionalArtifactQuicksight, + AdditionalArtifactAthena, + } +} + // The compression format that AWS uses for the report. const ( // CompressionFormatZip is a CompressionFormat enum value @@ -1136,6 +1162,15 @@ const ( CompressionFormatParquet = "Parquet" ) +// CompressionFormat_Values returns all elements of the CompressionFormat enum +func CompressionFormat_Values() []string { + return []string{ + CompressionFormatZip, + CompressionFormatGzip, + CompressionFormatParquet, + } +} + // The format that AWS saves the report in. const ( // ReportFormatTextOrcsv is a ReportFormat enum value @@ -1145,6 +1180,14 @@ const ( ReportFormatParquet = "Parquet" ) +// ReportFormat_Values returns all elements of the ReportFormat enum +func ReportFormat_Values() []string { + return []string{ + ReportFormatTextOrcsv, + ReportFormatParquet, + } +} + const ( // ReportVersioningCreateNewReport is a ReportVersioning enum value ReportVersioningCreateNewReport = "CREATE_NEW_REPORT" @@ -1153,12 +1196,27 @@ const ( ReportVersioningOverwriteReport = "OVERWRITE_REPORT" ) +// ReportVersioning_Values returns all elements of the ReportVersioning enum +func ReportVersioning_Values() []string { + return []string{ + ReportVersioningCreateNewReport, + ReportVersioningOverwriteReport, + } +} + // Whether or not AWS includes resource IDs in the report. const ( // SchemaElementResources is a SchemaElement enum value SchemaElementResources = "RESOURCES" ) +// SchemaElement_Values returns all elements of the SchemaElement enum +func SchemaElement_Values() []string { + return []string{ + SchemaElementResources, + } +} + // The length of time covered by the report. const ( // TimeUnitHourly is a TimeUnit enum value @@ -1167,3 +1225,11 @@ const ( // TimeUnitDaily is a TimeUnit enum value TimeUnitDaily = "DAILY" ) + +// TimeUnit_Values returns all elements of the TimeUnit enum +func TimeUnit_Values() []string { + return []string{ + TimeUnitHourly, + TimeUnitDaily, + } +} 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 eb43d9e24ad..6794691418e 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 @@ -176,6 +176,97 @@ func (c *DatabaseMigrationService) ApplyPendingMaintenanceActionWithContext(ctx return out, req.Send() } +const opCancelReplicationTaskAssessmentRun = "CancelReplicationTaskAssessmentRun" + +// CancelReplicationTaskAssessmentRunRequest generates a "aws/request.Request" representing the +// client's request for the CancelReplicationTaskAssessmentRun operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CancelReplicationTaskAssessmentRun for more information on using the CancelReplicationTaskAssessmentRun +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CancelReplicationTaskAssessmentRunRequest method. +// req, resp := client.CancelReplicationTaskAssessmentRunRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CancelReplicationTaskAssessmentRun +func (c *DatabaseMigrationService) CancelReplicationTaskAssessmentRunRequest(input *CancelReplicationTaskAssessmentRunInput) (req *request.Request, output *CancelReplicationTaskAssessmentRunOutput) { + op := &request.Operation{ + Name: opCancelReplicationTaskAssessmentRun, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CancelReplicationTaskAssessmentRunInput{} + } + + output = &CancelReplicationTaskAssessmentRunOutput{} + req = c.newRequest(op, input, output) + return +} + +// CancelReplicationTaskAssessmentRun API operation for AWS Database Migration Service. +// +// Cancels a single premigration assessment run. +// +// This operation prevents any individual assessments from running if they haven't +// started running. It also attempts to cancel any individual assessments that +// are currently running. +// +// Returns awserr.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 Database Migration Service's +// API operation CancelReplicationTaskAssessmentRun for usage and error information. +// +// Returned Error Types: +// * AccessDeniedFault +// AWS DMS was denied access to the endpoint. Check that the role is correctly +// configured. +// +// * ResourceNotFoundFault +// The resource could not be found. +// +// * InvalidResourceStateFault +// The resource is in a state that prevents it from being used for database +// migration. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/CancelReplicationTaskAssessmentRun +func (c *DatabaseMigrationService) CancelReplicationTaskAssessmentRun(input *CancelReplicationTaskAssessmentRunInput) (*CancelReplicationTaskAssessmentRunOutput, error) { + req, out := c.CancelReplicationTaskAssessmentRunRequest(input) + return out, req.Send() +} + +// CancelReplicationTaskAssessmentRunWithContext is the same as CancelReplicationTaskAssessmentRun with the addition of +// the ability to pass a context and additional request options. +// +// See CancelReplicationTaskAssessmentRun for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) CancelReplicationTaskAssessmentRunWithContext(ctx aws.Context, input *CancelReplicationTaskAssessmentRunInput, opts ...request.Option) (*CancelReplicationTaskAssessmentRunOutput, error) { + req, out := c.CancelReplicationTaskAssessmentRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateEndpoint = "CreateEndpoint" // CreateEndpointRequest generates a "aws/request.Request" representing the @@ -1295,6 +1386,97 @@ func (c *DatabaseMigrationService) DeleteReplicationTaskWithContext(ctx aws.Cont return out, req.Send() } +const opDeleteReplicationTaskAssessmentRun = "DeleteReplicationTaskAssessmentRun" + +// DeleteReplicationTaskAssessmentRunRequest generates a "aws/request.Request" representing the +// client's request for the DeleteReplicationTaskAssessmentRun operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteReplicationTaskAssessmentRun for more information on using the DeleteReplicationTaskAssessmentRun +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteReplicationTaskAssessmentRunRequest method. +// req, resp := client.DeleteReplicationTaskAssessmentRunRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationTaskAssessmentRun +func (c *DatabaseMigrationService) DeleteReplicationTaskAssessmentRunRequest(input *DeleteReplicationTaskAssessmentRunInput) (req *request.Request, output *DeleteReplicationTaskAssessmentRunOutput) { + op := &request.Operation{ + Name: opDeleteReplicationTaskAssessmentRun, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteReplicationTaskAssessmentRunInput{} + } + + output = &DeleteReplicationTaskAssessmentRunOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteReplicationTaskAssessmentRun API operation for AWS Database Migration Service. +// +// Deletes the record of a single premigration assessment run. +// +// This operation removes all metadata that AWS DMS maintains about this assessment +// run. However, the operation leaves untouched all information about this assessment +// run that is stored in your Amazon S3 bucket. +// +// Returns awserr.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 Database Migration Service's +// API operation DeleteReplicationTaskAssessmentRun for usage and error information. +// +// Returned Error Types: +// * AccessDeniedFault +// AWS DMS was denied access to the endpoint. Check that the role is correctly +// configured. +// +// * ResourceNotFoundFault +// The resource could not be found. +// +// * InvalidResourceStateFault +// The resource is in a state that prevents it from being used for database +// migration. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DeleteReplicationTaskAssessmentRun +func (c *DatabaseMigrationService) DeleteReplicationTaskAssessmentRun(input *DeleteReplicationTaskAssessmentRunInput) (*DeleteReplicationTaskAssessmentRunOutput, error) { + req, out := c.DeleteReplicationTaskAssessmentRunRequest(input) + return out, req.Send() +} + +// DeleteReplicationTaskAssessmentRunWithContext is the same as DeleteReplicationTaskAssessmentRun with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteReplicationTaskAssessmentRun for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DeleteReplicationTaskAssessmentRunWithContext(ctx aws.Context, input *DeleteReplicationTaskAssessmentRunInput, opts ...request.Option) (*DeleteReplicationTaskAssessmentRunOutput, error) { + req, out := c.DeleteReplicationTaskAssessmentRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeAccountAttributes = "DescribeAccountAttributes" // DescribeAccountAttributesRequest generates a "aws/request.Request" representing the @@ -1377,6 +1559,171 @@ func (c *DatabaseMigrationService) DescribeAccountAttributesWithContext(ctx aws. return out, req.Send() } +const opDescribeApplicableIndividualAssessments = "DescribeApplicableIndividualAssessments" + +// DescribeApplicableIndividualAssessmentsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeApplicableIndividualAssessments operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeApplicableIndividualAssessments for more information on using the DescribeApplicableIndividualAssessments +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeApplicableIndividualAssessmentsRequest method. +// req, resp := client.DescribeApplicableIndividualAssessmentsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeApplicableIndividualAssessments +func (c *DatabaseMigrationService) DescribeApplicableIndividualAssessmentsRequest(input *DescribeApplicableIndividualAssessmentsInput) (req *request.Request, output *DescribeApplicableIndividualAssessmentsOutput) { + op := &request.Operation{ + Name: opDescribeApplicableIndividualAssessments, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeApplicableIndividualAssessmentsInput{} + } + + output = &DescribeApplicableIndividualAssessmentsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeApplicableIndividualAssessments API operation for AWS Database Migration Service. +// +// Provides a list of individual assessments that you can specify for a new +// premigration assessment run, given one or more parameters. +// +// If you specify an existing migration task, this operation provides the default +// individual assessments you can specify for that task. Otherwise, the specified +// parameters model elements of a possible migration task on which to base a +// premigration assessment run. +// +// To use these migration task modeling parameters, you must specify an existing +// replication instance, a source database engine, a target database engine, +// and a migration type. This combination of parameters potentially limits the +// default individual assessments available for an assessment run created for +// a corresponding migration task. +// +// If you specify no parameters, this operation provides a list of all possible +// individual assessments that you can specify for an assessment run. If you +// specify any one of the task modeling parameters, you must specify all of +// them or the operation cannot provide a list of individual assessments. The +// only parameter that you can specify alone is for an existing migration task. +// The specified task definition then determines the default list of individual +// assessments that you can specify in an assessment run for the task. +// +// Returns awserr.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 Database Migration Service's +// API operation DescribeApplicableIndividualAssessments for usage and error information. +// +// Returned Error Types: +// * AccessDeniedFault +// AWS DMS was denied access to the endpoint. Check that the role is correctly +// configured. +// +// * ResourceNotFoundFault +// The resource could not be found. +// +// * InvalidResourceStateFault +// The resource is in a state that prevents it from being used for database +// migration. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeApplicableIndividualAssessments +func (c *DatabaseMigrationService) DescribeApplicableIndividualAssessments(input *DescribeApplicableIndividualAssessmentsInput) (*DescribeApplicableIndividualAssessmentsOutput, error) { + req, out := c.DescribeApplicableIndividualAssessmentsRequest(input) + return out, req.Send() +} + +// DescribeApplicableIndividualAssessmentsWithContext is the same as DescribeApplicableIndividualAssessments with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeApplicableIndividualAssessments for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeApplicableIndividualAssessmentsWithContext(ctx aws.Context, input *DescribeApplicableIndividualAssessmentsInput, opts ...request.Option) (*DescribeApplicableIndividualAssessmentsOutput, error) { + req, out := c.DescribeApplicableIndividualAssessmentsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeApplicableIndividualAssessmentsPages iterates over the pages of a DescribeApplicableIndividualAssessments operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeApplicableIndividualAssessments 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 DescribeApplicableIndividualAssessments operation. +// pageNum := 0 +// err := client.DescribeApplicableIndividualAssessmentsPages(params, +// func(page *databasemigrationservice.DescribeApplicableIndividualAssessmentsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DatabaseMigrationService) DescribeApplicableIndividualAssessmentsPages(input *DescribeApplicableIndividualAssessmentsInput, fn func(*DescribeApplicableIndividualAssessmentsOutput, bool) bool) error { + return c.DescribeApplicableIndividualAssessmentsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeApplicableIndividualAssessmentsPagesWithContext same as DescribeApplicableIndividualAssessmentsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeApplicableIndividualAssessmentsPagesWithContext(ctx aws.Context, input *DescribeApplicableIndividualAssessmentsInput, fn func(*DescribeApplicableIndividualAssessmentsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeApplicableIndividualAssessmentsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeApplicableIndividualAssessmentsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeApplicableIndividualAssessmentsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeCertificates = "DescribeCertificates" // DescribeCertificatesRequest generates a "aws/request.Request" representing the @@ -3182,32 +3529,316 @@ func (c *DatabaseMigrationService) DescribeReplicationTaskAssessmentResultsPages return p.Err() } -const opDescribeReplicationTasks = "DescribeReplicationTasks" +const opDescribeReplicationTaskAssessmentRuns = "DescribeReplicationTaskAssessmentRuns" -// DescribeReplicationTasksRequest generates a "aws/request.Request" representing the -// client's request for the DescribeReplicationTasks operation. The "output" return +// DescribeReplicationTaskAssessmentRunsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeReplicationTaskAssessmentRuns operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeReplicationTasks for more information on using the DescribeReplicationTasks +// See DescribeReplicationTaskAssessmentRuns for more information on using the DescribeReplicationTaskAssessmentRuns // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeReplicationTasksRequest method. -// req, resp := client.DescribeReplicationTasksRequest(params) +// // Example sending a request using the DescribeReplicationTaskAssessmentRunsRequest method. +// req, resp := client.DescribeReplicationTaskAssessmentRunsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTasks +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskAssessmentRuns +func (c *DatabaseMigrationService) DescribeReplicationTaskAssessmentRunsRequest(input *DescribeReplicationTaskAssessmentRunsInput) (req *request.Request, output *DescribeReplicationTaskAssessmentRunsOutput) { + op := &request.Operation{ + Name: opDescribeReplicationTaskAssessmentRuns, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeReplicationTaskAssessmentRunsInput{} + } + + output = &DescribeReplicationTaskAssessmentRunsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeReplicationTaskAssessmentRuns API operation for AWS Database Migration Service. +// +// Returns a paginated list of premigration assessment runs based on filter +// settings. +// +// These filter settings can specify a combination of premigration assessment +// runs, migration tasks, replication instances, and assessment run status values. +// +// This operation doesn't return information about individual assessments. For +// this information, see the DescribeReplicationTaskIndividualAssessments 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 Database Migration Service's +// API operation DescribeReplicationTaskAssessmentRuns for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundFault +// The resource could not be found. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskAssessmentRuns +func (c *DatabaseMigrationService) DescribeReplicationTaskAssessmentRuns(input *DescribeReplicationTaskAssessmentRunsInput) (*DescribeReplicationTaskAssessmentRunsOutput, error) { + req, out := c.DescribeReplicationTaskAssessmentRunsRequest(input) + return out, req.Send() +} + +// DescribeReplicationTaskAssessmentRunsWithContext is the same as DescribeReplicationTaskAssessmentRuns with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReplicationTaskAssessmentRuns for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeReplicationTaskAssessmentRunsWithContext(ctx aws.Context, input *DescribeReplicationTaskAssessmentRunsInput, opts ...request.Option) (*DescribeReplicationTaskAssessmentRunsOutput, error) { + req, out := c.DescribeReplicationTaskAssessmentRunsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeReplicationTaskAssessmentRunsPages iterates over the pages of a DescribeReplicationTaskAssessmentRuns operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeReplicationTaskAssessmentRuns 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 DescribeReplicationTaskAssessmentRuns operation. +// pageNum := 0 +// err := client.DescribeReplicationTaskAssessmentRunsPages(params, +// func(page *databasemigrationservice.DescribeReplicationTaskAssessmentRunsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DatabaseMigrationService) DescribeReplicationTaskAssessmentRunsPages(input *DescribeReplicationTaskAssessmentRunsInput, fn func(*DescribeReplicationTaskAssessmentRunsOutput, bool) bool) error { + return c.DescribeReplicationTaskAssessmentRunsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeReplicationTaskAssessmentRunsPagesWithContext same as DescribeReplicationTaskAssessmentRunsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeReplicationTaskAssessmentRunsPagesWithContext(ctx aws.Context, input *DescribeReplicationTaskAssessmentRunsInput, fn func(*DescribeReplicationTaskAssessmentRunsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeReplicationTaskAssessmentRunsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReplicationTaskAssessmentRunsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeReplicationTaskAssessmentRunsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opDescribeReplicationTaskIndividualAssessments = "DescribeReplicationTaskIndividualAssessments" + +// DescribeReplicationTaskIndividualAssessmentsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeReplicationTaskIndividualAssessments operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeReplicationTaskIndividualAssessments for more information on using the DescribeReplicationTaskIndividualAssessments +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeReplicationTaskIndividualAssessmentsRequest method. +// req, resp := client.DescribeReplicationTaskIndividualAssessmentsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskIndividualAssessments +func (c *DatabaseMigrationService) DescribeReplicationTaskIndividualAssessmentsRequest(input *DescribeReplicationTaskIndividualAssessmentsInput) (req *request.Request, output *DescribeReplicationTaskIndividualAssessmentsOutput) { + op := &request.Operation{ + Name: opDescribeReplicationTaskIndividualAssessments, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeReplicationTaskIndividualAssessmentsInput{} + } + + output = &DescribeReplicationTaskIndividualAssessmentsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeReplicationTaskIndividualAssessments API operation for AWS Database Migration Service. +// +// Returns a paginated list of individual assessments based on filter settings. +// +// These filter settings can specify a combination of premigration assessment +// runs, migration tasks, and assessment status values. +// +// Returns awserr.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 Database Migration Service's +// API operation DescribeReplicationTaskIndividualAssessments for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundFault +// The resource could not be found. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTaskIndividualAssessments +func (c *DatabaseMigrationService) DescribeReplicationTaskIndividualAssessments(input *DescribeReplicationTaskIndividualAssessmentsInput) (*DescribeReplicationTaskIndividualAssessmentsOutput, error) { + req, out := c.DescribeReplicationTaskIndividualAssessmentsRequest(input) + return out, req.Send() +} + +// DescribeReplicationTaskIndividualAssessmentsWithContext is the same as DescribeReplicationTaskIndividualAssessments with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReplicationTaskIndividualAssessments for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeReplicationTaskIndividualAssessmentsWithContext(ctx aws.Context, input *DescribeReplicationTaskIndividualAssessmentsInput, opts ...request.Option) (*DescribeReplicationTaskIndividualAssessmentsOutput, error) { + req, out := c.DescribeReplicationTaskIndividualAssessmentsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeReplicationTaskIndividualAssessmentsPages iterates over the pages of a DescribeReplicationTaskIndividualAssessments operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeReplicationTaskIndividualAssessments 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 DescribeReplicationTaskIndividualAssessments operation. +// pageNum := 0 +// err := client.DescribeReplicationTaskIndividualAssessmentsPages(params, +// func(page *databasemigrationservice.DescribeReplicationTaskIndividualAssessmentsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *DatabaseMigrationService) DescribeReplicationTaskIndividualAssessmentsPages(input *DescribeReplicationTaskIndividualAssessmentsInput, fn func(*DescribeReplicationTaskIndividualAssessmentsOutput, bool) bool) error { + return c.DescribeReplicationTaskIndividualAssessmentsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeReplicationTaskIndividualAssessmentsPagesWithContext same as DescribeReplicationTaskIndividualAssessmentsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeReplicationTaskIndividualAssessmentsPagesWithContext(ctx aws.Context, input *DescribeReplicationTaskIndividualAssessmentsInput, fn func(*DescribeReplicationTaskIndividualAssessmentsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeReplicationTaskIndividualAssessmentsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeReplicationTaskIndividualAssessmentsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeReplicationTaskIndividualAssessmentsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opDescribeReplicationTasks = "DescribeReplicationTasks" + +// DescribeReplicationTasksRequest generates a "aws/request.Request" representing the +// client's request for the DescribeReplicationTasks operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeReplicationTasks for more information on using the DescribeReplicationTasks +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeReplicationTasksRequest method. +// req, resp := client.DescribeReplicationTasksRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/DescribeReplicationTasks func (c *DatabaseMigrationService) DescribeReplicationTasksRequest(input *DescribeReplicationTasksInput) (req *request.Request, output *DescribeReplicationTasksOutput) { op := &request.Operation{ Name: opDescribeReplicationTasks, @@ -4776,60 +5407,72 @@ func (c *DatabaseMigrationService) StartReplicationTaskAssessmentWithContext(ctx return out, req.Send() } -const opStopReplicationTask = "StopReplicationTask" +const opStartReplicationTaskAssessmentRun = "StartReplicationTaskAssessmentRun" -// StopReplicationTaskRequest generates a "aws/request.Request" representing the -// client's request for the StopReplicationTask operation. The "output" return +// StartReplicationTaskAssessmentRunRequest generates a "aws/request.Request" representing the +// client's request for the StartReplicationTaskAssessmentRun operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See StopReplicationTask for more information on using the StopReplicationTask +// See StartReplicationTaskAssessmentRun for more information on using the StartReplicationTaskAssessmentRun // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the StopReplicationTaskRequest method. -// req, resp := client.StopReplicationTaskRequest(params) +// // Example sending a request using the StartReplicationTaskAssessmentRunRequest method. +// req, resp := client.StartReplicationTaskAssessmentRunRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StopReplicationTask -func (c *DatabaseMigrationService) StopReplicationTaskRequest(input *StopReplicationTaskInput) (req *request.Request, output *StopReplicationTaskOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTaskAssessmentRun +func (c *DatabaseMigrationService) StartReplicationTaskAssessmentRunRequest(input *StartReplicationTaskAssessmentRunInput) (req *request.Request, output *StartReplicationTaskAssessmentRunOutput) { op := &request.Operation{ - Name: opStopReplicationTask, + Name: opStartReplicationTaskAssessmentRun, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &StopReplicationTaskInput{} + input = &StartReplicationTaskAssessmentRunInput{} } - output = &StopReplicationTaskOutput{} + output = &StartReplicationTaskAssessmentRunOutput{} req = c.newRequest(op, input, output) return } -// StopReplicationTask API operation for AWS Database Migration Service. +// StartReplicationTaskAssessmentRun API operation for AWS Database Migration Service. // -// Stops the replication task. +// Starts a new premigration assessment run for one or more individual assessments +// of a migration task. +// +// The assessments that you can specify depend on the source and target database +// engine and the migration type defined for the given task. To run this operation, +// your migration task must already be created. After you run this operation, +// you can review the status of each individual assessment. You can also run +// the migration task manually after the assessment run and its individual assessments +// 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 Database Migration Service's -// API operation StopReplicationTask for usage and error information. +// API operation StartReplicationTaskAssessmentRun for usage and error information. // // Returned Error Types: +// * AccessDeniedFault +// AWS DMS was denied access to the endpoint. Check that the role is correctly +// configured. +// // * ResourceNotFoundFault // The resource could not be found. // @@ -4837,22 +5480,134 @@ func (c *DatabaseMigrationService) StopReplicationTaskRequest(input *StopReplica // The resource is in a state that prevents it from being used for database // migration. // -// See also, 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) - return out, req.Send() -} - -// StopReplicationTaskWithContext is the same as StopReplicationTask with the addition of -// the ability to pass a context and additional request options. +// * KMSAccessDeniedFault +// The ciphertext references a key that doesn't exist or that the DMS account +// doesn't have access to. // -// See StopReplicationTask for details on how to use this API operation. +// * KMSDisabledFault +// The specified master key (CMK) isn't enabled. // -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the 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) { +// * KMSFault +// An AWS Key Management Service (AWS KMS) error is preventing access to AWS +// KMS. +// +// * KMSInvalidStateFault +// The state of the specified AWS KMS resource isn't valid for this request. +// +// * KMSNotFoundFault +// The specified AWS KMS entity or resource can't be found. +// +// * KMSKeyNotAccessibleFault +// AWS DMS cannot access the AWS KMS key. +// +// * S3AccessDeniedFault +// Insufficient privileges are preventing access to an Amazon S3 object. +// +// * S3ResourceNotFoundFault +// A specified Amazon S3 bucket, bucket folder, or other object can't be found. +// +// * ResourceAlreadyExistsFault +// The resource you are attempting to create already exists. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StartReplicationTaskAssessmentRun +func (c *DatabaseMigrationService) StartReplicationTaskAssessmentRun(input *StartReplicationTaskAssessmentRunInput) (*StartReplicationTaskAssessmentRunOutput, error) { + req, out := c.StartReplicationTaskAssessmentRunRequest(input) + return out, req.Send() +} + +// StartReplicationTaskAssessmentRunWithContext is the same as StartReplicationTaskAssessmentRun with the addition of +// the ability to pass a context and additional request options. +// +// See StartReplicationTaskAssessmentRun for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) StartReplicationTaskAssessmentRunWithContext(ctx aws.Context, input *StartReplicationTaskAssessmentRunInput, opts ...request.Option) (*StartReplicationTaskAssessmentRunOutput, error) { + req, out := c.StartReplicationTaskAssessmentRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opStopReplicationTask = "StopReplicationTask" + +// StopReplicationTaskRequest generates a "aws/request.Request" representing the +// client's request for the StopReplicationTask operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See StopReplicationTask for more information on using the StopReplicationTask +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the StopReplicationTaskRequest method. +// req, resp := client.StopReplicationTaskRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/dms-2016-01-01/StopReplicationTask +func (c *DatabaseMigrationService) StopReplicationTaskRequest(input *StopReplicationTaskInput) (req *request.Request, output *StopReplicationTaskOutput) { + op := &request.Operation{ + Name: opStopReplicationTask, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &StopReplicationTaskInput{} + } + + output = &StopReplicationTaskOutput{} + req = c.newRequest(op, input, output) + return +} + +// StopReplicationTask API operation for AWS Database Migration Service. +// +// Stops the replication task. +// +// Returns awserr.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 Database Migration Service's +// API operation StopReplicationTask for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundFault +// The resource could not be found. +// +// * InvalidResourceStateFault +// The resource is in a state that prevents it from being used for database +// migration. +// +// See also, 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) + 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...) @@ -5220,7 +5975,7 @@ func (s *ApplyPendingMaintenanceActionOutput) SetResourcePendingMaintenanceActio return s } -// The name of the Availability Zone for use during database migration. +// The name of an Availability Zone for use during database migration. type AvailabilityZone struct { _ struct{} `type:"structure"` @@ -5244,6 +5999,67 @@ func (s *AvailabilityZone) SetName(v string) *AvailabilityZone { return s } +type CancelReplicationTaskAssessmentRunInput struct { + _ struct{} `type:"structure"` + + // Amazon Resource Name (ARN) of the premigration assessment run to be canceled. + // + // ReplicationTaskAssessmentRunArn is a required field + ReplicationTaskAssessmentRunArn *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s CancelReplicationTaskAssessmentRunInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CancelReplicationTaskAssessmentRunInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CancelReplicationTaskAssessmentRunInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CancelReplicationTaskAssessmentRunInput"} + if s.ReplicationTaskAssessmentRunArn == nil { + invalidParams.Add(request.NewErrParamRequired("ReplicationTaskAssessmentRunArn")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetReplicationTaskAssessmentRunArn sets the ReplicationTaskAssessmentRunArn field's value. +func (s *CancelReplicationTaskAssessmentRunInput) SetReplicationTaskAssessmentRunArn(v string) *CancelReplicationTaskAssessmentRunInput { + s.ReplicationTaskAssessmentRunArn = &v + return s +} + +type CancelReplicationTaskAssessmentRunOutput struct { + _ struct{} `type:"structure"` + + // The ReplicationTaskAssessmentRun object for the canceled assessment run. + ReplicationTaskAssessmentRun *ReplicationTaskAssessmentRun `type:"structure"` +} + +// String returns the string representation +func (s CancelReplicationTaskAssessmentRunOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CancelReplicationTaskAssessmentRunOutput) GoString() string { + return s.String() +} + +// SetReplicationTaskAssessmentRun sets the ReplicationTaskAssessmentRun field's value. +func (s *CancelReplicationTaskAssessmentRunOutput) SetReplicationTaskAssessmentRun(v *ReplicationTaskAssessmentRun) *CancelReplicationTaskAssessmentRunOutput { + s.ReplicationTaskAssessmentRun = v + return s +} + // The SSL certificate that can be used to encrypt connections between the endpoints // and the replication instance. type Certificate struct { @@ -5377,7 +6193,15 @@ type Connection struct { // string. ReplicationInstanceIdentifier *string `type:"string"` - // The connection status. + // The connection status. This parameter can return one of the following values: + // + // * "successful" + // + // * "testing" + // + // * "failed" + // + // * "deleting" Status *string `type:"string"` } @@ -5464,7 +6288,7 @@ type CreateEndpointInput struct { // Settings in JSON format for the target Elasticsearch endpoint. For more information // about the available settings, see Extra Connection Attributes When Using // Elasticsearch as a Target for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Elasticsearch.html#CHAP_Target.Elasticsearch.Configuration) - // in the AWS Database Migration User Guide. + // in the AWS Database Migration Service User Guide. ElasticsearchSettings *ElasticsearchSettings `type:"structure"` // The database endpoint identifier. Identifiers must begin with a letter and @@ -5482,7 +6306,7 @@ type CreateEndpointInput struct { // The type of engine for the endpoint. Valid values, depending on the EndpointType // value, include "mysql", "oracle", "postgres", "mariadb", "aurora", "aurora-postgresql", // "redshift", "s3", "db2", "azuredb", "sybase", "dynamodb", "mongodb", "kinesis", - // "kafka", "elasticsearch", "documentdb", and "sqlserver". + // "kafka", "elasticsearch", "documentdb", "sqlserver", and "neptune". // // EngineName is a required field EngineName *string `type:"string" required:"true"` @@ -5498,16 +6322,22 @@ type CreateEndpointInput struct { // in the AWS Database Migration Service User Guide. ExtraConnectionAttributes *string `type:"string"` + // Settings in JSON format for the source IBM Db2 LUW endpoint. For information + // about other available settings, see Extra connection attributes when using + // Db2 LUW as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.DB2.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + IBMDb2Settings *IBMDb2Settings `type:"structure"` + // Settings in JSON format for the target Apache Kafka endpoint. For more information // about the available settings, see Using Apache Kafka as a Target for AWS // Database Migration Service (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Kafka.html) - // in the AWS Database Migration User Guide. + // in the AWS Database Migration Service User Guide. KafkaSettings *KafkaSettings `type:"structure"` // Settings in JSON format for the target endpoint for Amazon Kinesis Data Streams. // For more information about the available settings, see Using Amazon Kinesis // Data Streams as a Target for AWS Database Migration Service (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Kinesis.html) - // in the AWS Database Migration User Guide. + // in the AWS Database Migration Service User Guide. KinesisSettings *KinesisSettings `type:"structure"` // An AWS KMS key identifier that is used to encrypt the connection parameters @@ -5520,24 +6350,56 @@ type CreateEndpointInput struct { // account has a different default encryption key for each AWS Region. KmsKeyId *string `type:"string"` + // Settings in JSON format for the source and target Microsoft SQL Server endpoint. + // For information about other available settings, see Extra connection attributes + // when using SQL Server as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.SQLServer.ConnectionAttrib) + // and Extra connection attributes when using SQL Server as a target for AWS + // DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.SQLServer.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + MicrosoftSQLServerSettings *MicrosoftSQLServerSettings `type:"structure"` + // Settings in JSON format for the source MongoDB endpoint. For more information // about the available settings, see Using MongoDB as a Target for AWS Database // Migration Service (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.MongoDB.html#CHAP_Source.MongoDB.Configuration) // in the AWS Database Migration Service User Guide. MongoDbSettings *MongoDbSettings `type:"structure"` + // Settings in JSON format for the source and target MySQL endpoint. For information + // about other available settings, see Extra connection attributes when using + // MySQL as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.MySQL.ConnectionAttrib) + // and Extra connection attributes when using a MySQL-compatible database as + // a target for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.MySQL.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + MySQLSettings *MySQLSettings `type:"structure"` + // Settings in JSON format for the target Amazon Neptune endpoint. For more - // information about the available settings, see https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Neptune.html#CHAP_Target.Neptune.EndpointSettings - // (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Neptune.html#CHAP_Target.Neptune.EndpointSettings) + // information about the available settings, see Specifying Endpoint Settings + // for Amazon Neptune as a Target (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Neptune.html#CHAP_Target.Neptune.EndpointSettings) // in the AWS Database Migration Service User Guide. NeptuneSettings *NeptuneSettings `type:"structure"` + // Settings in JSON format for the source and target Oracle endpoint. For information + // about other available settings, see Extra connection attributes when using + // Oracle as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.Oracle.ConnectionAttrib) + // and Extra connection attributes when using Oracle as a target for AWS DMS + // (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Oracle.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + OracleSettings *OracleSettings `type:"structure"` + // The password to be used to log in to the endpoint database. Password *string `type:"string" sensitive:"true"` // The port used by the endpoint database. Port *int64 `type:"integer"` + // Settings in JSON format for the source and target PostgreSQL endpoint. For + // information about other available settings, see Extra connection attributes + // when using PostgreSQL as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.PostgreSQL.ConnectionAttrib) + // and Extra connection attributes when using PostgreSQL as a target for AWS + // DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.PostgreSQL.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + PostgreSQLSettings *PostgreSQLSettings `type:"structure"` + // Provides information that defines an Amazon Redshift endpoint. RedshiftSettings *RedshiftSettings `type:"structure"` @@ -5558,6 +6420,14 @@ type CreateEndpointInput struct { // is none SslMode *string `type:"string" enum:"DmsSslModeValue"` + // Settings in JSON format for the source and target SAP ASE endpoint. For information + // about other available settings, see Extra connection attributes when using + // SAP ASE as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.SAP.ConnectionAttrib) + // and Extra connection attributes when using SAP ASE as a target for AWS DMS + // (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.SAP.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + SybaseSettings *SybaseSettings `type:"structure"` + // One or more tags to be assigned to the endpoint. Tags []*Tag `type:"list"` @@ -5669,6 +6539,12 @@ func (s *CreateEndpointInput) SetExtraConnectionAttributes(v string) *CreateEndp return s } +// SetIBMDb2Settings sets the IBMDb2Settings field's value. +func (s *CreateEndpointInput) SetIBMDb2Settings(v *IBMDb2Settings) *CreateEndpointInput { + s.IBMDb2Settings = v + return s +} + // SetKafkaSettings sets the KafkaSettings field's value. func (s *CreateEndpointInput) SetKafkaSettings(v *KafkaSettings) *CreateEndpointInput { s.KafkaSettings = v @@ -5687,18 +6563,36 @@ func (s *CreateEndpointInput) SetKmsKeyId(v string) *CreateEndpointInput { return s } +// SetMicrosoftSQLServerSettings sets the MicrosoftSQLServerSettings field's value. +func (s *CreateEndpointInput) SetMicrosoftSQLServerSettings(v *MicrosoftSQLServerSettings) *CreateEndpointInput { + s.MicrosoftSQLServerSettings = v + return s +} + // SetMongoDbSettings sets the MongoDbSettings field's value. func (s *CreateEndpointInput) SetMongoDbSettings(v *MongoDbSettings) *CreateEndpointInput { s.MongoDbSettings = v return s } +// SetMySQLSettings sets the MySQLSettings field's value. +func (s *CreateEndpointInput) SetMySQLSettings(v *MySQLSettings) *CreateEndpointInput { + s.MySQLSettings = v + return s +} + // SetNeptuneSettings sets the NeptuneSettings field's value. func (s *CreateEndpointInput) SetNeptuneSettings(v *NeptuneSettings) *CreateEndpointInput { s.NeptuneSettings = v return s } +// SetOracleSettings sets the OracleSettings field's value. +func (s *CreateEndpointInput) SetOracleSettings(v *OracleSettings) *CreateEndpointInput { + s.OracleSettings = v + return s +} + // SetPassword sets the Password field's value. func (s *CreateEndpointInput) SetPassword(v string) *CreateEndpointInput { s.Password = &v @@ -5711,6 +6605,12 @@ func (s *CreateEndpointInput) SetPort(v int64) *CreateEndpointInput { return s } +// SetPostgreSQLSettings sets the PostgreSQLSettings field's value. +func (s *CreateEndpointInput) SetPostgreSQLSettings(v *PostgreSQLSettings) *CreateEndpointInput { + s.PostgreSQLSettings = v + return s +} + // SetRedshiftSettings sets the RedshiftSettings field's value. func (s *CreateEndpointInput) SetRedshiftSettings(v *RedshiftSettings) *CreateEndpointInput { s.RedshiftSettings = v @@ -5741,6 +6641,12 @@ func (s *CreateEndpointInput) SetSslMode(v string) *CreateEndpointInput { return s } +// SetSybaseSettings sets the SybaseSettings field's value. +func (s *CreateEndpointInput) SetSybaseSettings(v *SybaseSettings) *CreateEndpointInput { + s.SybaseSettings = v + return s +} + // SetTags sets the Tags field's value. func (s *CreateEndpointInput) SetTags(v []*Tag) *CreateEndpointInput { s.Tags = v @@ -5932,7 +6838,11 @@ type CreateReplicationInstanceInput struct { // AWS Region, for example: us-east-1d AvailabilityZone *string `type:"string"` - // A list of DNS name servers supported for the replication instance. + // A list of custom DNS name servers supported for the replication instance + // to access your on-premise source or target database. This list overrides + // the default name servers supported by the replication instance. You can specify + // a comma-separated list of internet addresses for up to four on-premise DNS + // name servers. For example: "1.1.1.1,2.2.2.2,3.3.3.3,4.4.4.4" DnsNameServers *string `type:"string"` // The engine version number of the replication instance. @@ -5971,11 +6881,13 @@ type CreateReplicationInstanceInput struct { // represents an instance with a private IP address. The default value is true. PubliclyAccessible *bool `type:"boolean"` - // The compute and memory capacity of the replication instance as specified - // by the replication instance class. + // The compute and memory capacity of the replication instance as defined for + // the specified replication instance class. For example to specify the instance + // class dms.c4.large, set this parameter to "dms.c4.large". // - // Valid Values: dms.t2.micro | dms.t2.small | dms.t2.medium | dms.t2.large - // | dms.c4.large | dms.c4.xlarge | dms.c4.2xlarge | dms.c4.4xlarge + // For more information on the settings and capacities for the available replication + // instance classes, see Selecting the right AWS DMS replication instance for + // your migration (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html#CHAP_ReplicationInstance.InDepth). // // ReplicationInstanceClass is a required field ReplicationInstanceClass *string `type:"string" required:"true"` @@ -5985,7 +6897,7 @@ type CreateReplicationInstanceInput struct { // // Constraints: // - // * Must contain from 1 to 63 alphanumeric characters or hyphens. + // * Must contain 1-63 alphanumeric characters or hyphens. // // * First character must be a letter. // @@ -6297,7 +7209,7 @@ type CreateReplicationTaskInput struct { // // Constraints: // - // * Must contain from 1 to 255 alphanumeric characters or hyphens. + // * Must contain 1-255 alphanumeric characters or hyphens. // // * First character must be a letter. // @@ -6318,7 +7230,7 @@ type CreateReplicationTaskInput struct { // The table mappings for the task, in JSON format. For more information, see // Using Table Mapping to Specify Task Settings (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.CustomizingTasks.TableMapping.html) - // in the AWS Database Migration User Guide. + // in the AWS Database Migration Service User Guide. // // TableMappings is a required field TableMappings *string `type:"string" required:"true"` @@ -6334,7 +7246,7 @@ type CreateReplicationTaskInput struct { // Supplemental information that the task requires to migrate the data for certain // source and target endpoints. For more information, see Specifying Supplemental // Data for Task Settings (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.TaskData.html) - // in the AWS Database Migration User Guide. + // in the AWS Database Migration Service User Guide. TaskData *string `type:"string"` } @@ -6842,6 +7754,67 @@ func (s DeleteReplicationSubnetGroupOutput) GoString() string { return s.String() } +type DeleteReplicationTaskAssessmentRunInput struct { + _ struct{} `type:"structure"` + + // Amazon Resource Name (ARN) of the premigration assessment run to be deleted. + // + // ReplicationTaskAssessmentRunArn is a required field + ReplicationTaskAssessmentRunArn *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteReplicationTaskAssessmentRunInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteReplicationTaskAssessmentRunInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteReplicationTaskAssessmentRunInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteReplicationTaskAssessmentRunInput"} + if s.ReplicationTaskAssessmentRunArn == nil { + invalidParams.Add(request.NewErrParamRequired("ReplicationTaskAssessmentRunArn")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetReplicationTaskAssessmentRunArn sets the ReplicationTaskAssessmentRunArn field's value. +func (s *DeleteReplicationTaskAssessmentRunInput) SetReplicationTaskAssessmentRunArn(v string) *DeleteReplicationTaskAssessmentRunInput { + s.ReplicationTaskAssessmentRunArn = &v + return s +} + +type DeleteReplicationTaskAssessmentRunOutput struct { + _ struct{} `type:"structure"` + + // The ReplicationTaskAssessmentRun object for the deleted assessment run. + ReplicationTaskAssessmentRun *ReplicationTaskAssessmentRun `type:"structure"` +} + +// String returns the string representation +func (s DeleteReplicationTaskAssessmentRunOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteReplicationTaskAssessmentRunOutput) GoString() string { + return s.String() +} + +// SetReplicationTaskAssessmentRun sets the ReplicationTaskAssessmentRun field's value. +func (s *DeleteReplicationTaskAssessmentRunOutput) SetReplicationTaskAssessmentRun(v *ReplicationTaskAssessmentRun) *DeleteReplicationTaskAssessmentRunOutput { + s.ReplicationTaskAssessmentRun = v + return s +} + type DeleteReplicationTaskInput struct { _ struct{} `type:"structure"` @@ -6958,41 +7931,167 @@ func (s *DescribeAccountAttributesOutput) SetUniqueAccountIdentifier(v string) * return s } -type DescribeCertificatesInput struct { +type DescribeApplicableIndividualAssessmentsInput struct { _ struct{} `type:"structure"` - // Filters applied to the certificate described in the form of key-value pairs. - Filters []*Filter `type:"list"` - - // An optional pagination token provided by a previous request. If this parameter + // Optional pagination token provided by a previous request. If this parameter // is specified, the response includes only records beyond the marker, up to // the value specified by MaxRecords. Marker *string `type:"string"` - // The maximum number of records to include in the response. If more records - // exist than the specified MaxRecords value, a pagination token called a marker - // is included in the response so that the remaining results can be retrieved. - // - // Default: 10 + // Maximum number of records to include in the response. If more records exist + // than the specified MaxRecords value, a pagination token called a marker is + // included in the response so that the remaining results can be retrieved. MaxRecords *int64 `type:"integer"` + + // Name of the migration type that each provided individual assessment must + // support. + MigrationType *string `type:"string" enum:"MigrationTypeValue"` + + // ARN of a replication instance on which you want to base the default list + // of individual assessments. + ReplicationInstanceArn *string `type:"string"` + + // Amazon Resource Name (ARN) of a migration task on which you want to base + // the default list of individual assessments. + ReplicationTaskArn *string `type:"string"` + + // Name of a database engine that the specified replication instance supports + // as a source. + SourceEngineName *string `type:"string"` + + // Name of a database engine that the specified replication instance supports + // as a target. + TargetEngineName *string `type:"string"` } // String returns the string representation -func (s DescribeCertificatesInput) String() string { +func (s DescribeApplicableIndividualAssessmentsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeCertificatesInput) GoString() string { +func (s DescribeApplicableIndividualAssessmentsInput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeCertificatesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeCertificatesInput"} - if s.Filters != nil { - for i, v := range s.Filters { - if v == nil { +// SetMarker sets the Marker field's value. +func (s *DescribeApplicableIndividualAssessmentsInput) SetMarker(v string) *DescribeApplicableIndividualAssessmentsInput { + s.Marker = &v + return s +} + +// SetMaxRecords sets the MaxRecords field's value. +func (s *DescribeApplicableIndividualAssessmentsInput) SetMaxRecords(v int64) *DescribeApplicableIndividualAssessmentsInput { + s.MaxRecords = &v + return s +} + +// SetMigrationType sets the MigrationType field's value. +func (s *DescribeApplicableIndividualAssessmentsInput) SetMigrationType(v string) *DescribeApplicableIndividualAssessmentsInput { + s.MigrationType = &v + return s +} + +// SetReplicationInstanceArn sets the ReplicationInstanceArn field's value. +func (s *DescribeApplicableIndividualAssessmentsInput) SetReplicationInstanceArn(v string) *DescribeApplicableIndividualAssessmentsInput { + s.ReplicationInstanceArn = &v + return s +} + +// SetReplicationTaskArn sets the ReplicationTaskArn field's value. +func (s *DescribeApplicableIndividualAssessmentsInput) SetReplicationTaskArn(v string) *DescribeApplicableIndividualAssessmentsInput { + s.ReplicationTaskArn = &v + return s +} + +// SetSourceEngineName sets the SourceEngineName field's value. +func (s *DescribeApplicableIndividualAssessmentsInput) SetSourceEngineName(v string) *DescribeApplicableIndividualAssessmentsInput { + s.SourceEngineName = &v + return s +} + +// SetTargetEngineName sets the TargetEngineName field's value. +func (s *DescribeApplicableIndividualAssessmentsInput) SetTargetEngineName(v string) *DescribeApplicableIndividualAssessmentsInput { + s.TargetEngineName = &v + return s +} + +type DescribeApplicableIndividualAssessmentsOutput struct { + _ struct{} `type:"structure"` + + // List of names for the individual assessments supported by the premigration + // assessment run that you start based on the specified request parameters. + // For more information on the available individual assessments, including compatibility + // with different migration task configurations, see Working with premigration + // assessment runs (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.AssessmentReport.html) + // in the AWS Database Migration Service User Guide. + IndividualAssessmentNames []*string `type:"list"` + + // Pagination token returned for you to pass to a subsequent request. If you + // pass this token as the Marker value in a subsequent request, the response + // includes only records beyond the marker, up to the value specified in the + // request by MaxRecords. + Marker *string `type:"string"` +} + +// String returns the string representation +func (s DescribeApplicableIndividualAssessmentsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeApplicableIndividualAssessmentsOutput) GoString() string { + return s.String() +} + +// SetIndividualAssessmentNames sets the IndividualAssessmentNames field's value. +func (s *DescribeApplicableIndividualAssessmentsOutput) SetIndividualAssessmentNames(v []*string) *DescribeApplicableIndividualAssessmentsOutput { + s.IndividualAssessmentNames = v + return s +} + +// SetMarker sets the Marker field's value. +func (s *DescribeApplicableIndividualAssessmentsOutput) SetMarker(v string) *DescribeApplicableIndividualAssessmentsOutput { + s.Marker = &v + return s +} + +type DescribeCertificatesInput struct { + _ struct{} `type:"structure"` + + // Filters applied to the certificates described in the form of key-value pairs. + Filters []*Filter `type:"list"` + + // An optional pagination token provided by a previous request. If this parameter + // is specified, the response includes only records beyond the marker, up to + // the value specified by MaxRecords. + Marker *string `type:"string"` + + // The maximum number of records to include in the response. If more records + // exist than the specified MaxRecords value, a pagination token called a marker + // is included in the response so that the remaining results can be retrieved. + // + // Default: 10 + MaxRecords *int64 `type:"integer"` +} + +// String returns the string representation +func (s DescribeCertificatesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCertificatesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeCertificatesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeCertificatesInput"} + if s.Filters != nil { + for i, v := range s.Filters { + if v == nil { continue } if err := v.Validate(); err != nil { @@ -7166,7 +8265,7 @@ func (s *DescribeConnectionsOutput) SetMarker(v string) *DescribeConnectionsOutp type DescribeEndpointTypesInput struct { _ struct{} `type:"structure"` - // Filters applied to the describe action. + // Filters applied to the endpoint types. // // Valid filter names: engine-name | endpoint-type Filters []*Filter `type:"list"` @@ -7271,7 +8370,7 @@ func (s *DescribeEndpointTypesOutput) SetSupportedEndpointTypes(v []*SupportedEn type DescribeEndpointsInput struct { _ struct{} `type:"structure"` - // Filters applied to the describe action. + // Filters applied to the endpoints. // // Valid filter names: endpoint-arn | endpoint-type | endpoint-id | engine-name Filters []*Filter `type:"list"` @@ -7376,7 +8475,7 @@ func (s *DescribeEndpointsOutput) SetMarker(v string) *DescribeEndpointsOutput { type DescribeEventCategoriesInput struct { _ struct{} `type:"structure"` - // Filters applied to the action. + // Filters applied to the event categories. Filters []*Filter `type:"list"` // The type of AWS DMS resource that generates events. @@ -7453,7 +8552,7 @@ func (s *DescribeEventCategoriesOutput) SetEventCategoryGroupList(v []*EventCate type DescribeEventSubscriptionsInput struct { _ struct{} `type:"structure"` - // Filters applied to the action. + // Filters applied to event subscriptions. Filters []*Filter `type:"list"` // An optional pagination token provided by a previous request. If this parameter @@ -7574,7 +8673,7 @@ type DescribeEventsInput struct { // A list of event categories for the source type that you've chosen. EventCategories []*string `type:"list"` - // Filters applied to the action. + // Filters applied to events. Filters []*Filter `type:"list"` // An optional pagination token provided by a previous request. If this parameter @@ -8078,7 +9177,7 @@ func (s *DescribeReplicationInstanceTaskLogsOutput) SetReplicationInstanceTaskLo type DescribeReplicationInstancesInput struct { _ struct{} `type:"structure"` - // Filters applied to the describe action. + // Filters applied to replication instances. // // Valid filter names: replication-instance-arn | replication-instance-id | // replication-instance-class | engine-version @@ -8184,7 +9283,7 @@ func (s *DescribeReplicationInstancesOutput) SetReplicationInstances(v []*Replic type DescribeReplicationSubnetGroupsInput struct { _ struct{} `type:"structure"` - // Filters applied to the describe action. + // Filters applied to replication subnet groups. // // Valid filter names: replication-subnet-group-id Filters []*Filter `type:"list"` @@ -8380,10 +9479,218 @@ func (s *DescribeReplicationTaskAssessmentResultsOutput) SetReplicationTaskAsses return s } +type DescribeReplicationTaskAssessmentRunsInput struct { + _ struct{} `type:"structure"` + + // Filters applied to the premigration assessment runs described in the form + // of key-value pairs. + // + // Valid filter names: replication-task-assessment-run-arn, replication-task-arn, + // replication-instance-arn, status + Filters []*Filter `type:"list"` + + // An optional pagination token provided by a previous request. If this parameter + // is specified, the response includes only records beyond the marker, up to + // the value specified by MaxRecords. + Marker *string `type:"string"` + + // The maximum number of records to include in the response. If more records + // exist than the specified MaxRecords value, a pagination token called a marker + // is included in the response so that the remaining results can be retrieved. + MaxRecords *int64 `type:"integer"` +} + +// String returns the string representation +func (s DescribeReplicationTaskAssessmentRunsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeReplicationTaskAssessmentRunsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeReplicationTaskAssessmentRunsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeReplicationTaskAssessmentRunsInput"} + if s.Filters != nil { + for i, v := range s.Filters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetFilters sets the Filters field's value. +func (s *DescribeReplicationTaskAssessmentRunsInput) SetFilters(v []*Filter) *DescribeReplicationTaskAssessmentRunsInput { + s.Filters = v + return s +} + +// SetMarker sets the Marker field's value. +func (s *DescribeReplicationTaskAssessmentRunsInput) SetMarker(v string) *DescribeReplicationTaskAssessmentRunsInput { + s.Marker = &v + return s +} + +// SetMaxRecords sets the MaxRecords field's value. +func (s *DescribeReplicationTaskAssessmentRunsInput) SetMaxRecords(v int64) *DescribeReplicationTaskAssessmentRunsInput { + s.MaxRecords = &v + return s +} + +type DescribeReplicationTaskAssessmentRunsOutput struct { + _ struct{} `type:"structure"` + + // A pagination token returned for you to pass to a subsequent request. If you + // pass this token as the Marker value in a subsequent request, the response + // includes only records beyond the marker, up to the value specified in the + // request by MaxRecords. + Marker *string `type:"string"` + + // One or more premigration assessment runs as specified by Filters. + ReplicationTaskAssessmentRuns []*ReplicationTaskAssessmentRun `type:"list"` +} + +// String returns the string representation +func (s DescribeReplicationTaskAssessmentRunsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeReplicationTaskAssessmentRunsOutput) GoString() string { + return s.String() +} + +// SetMarker sets the Marker field's value. +func (s *DescribeReplicationTaskAssessmentRunsOutput) SetMarker(v string) *DescribeReplicationTaskAssessmentRunsOutput { + s.Marker = &v + return s +} + +// SetReplicationTaskAssessmentRuns sets the ReplicationTaskAssessmentRuns field's value. +func (s *DescribeReplicationTaskAssessmentRunsOutput) SetReplicationTaskAssessmentRuns(v []*ReplicationTaskAssessmentRun) *DescribeReplicationTaskAssessmentRunsOutput { + s.ReplicationTaskAssessmentRuns = v + return s +} + +type DescribeReplicationTaskIndividualAssessmentsInput struct { + _ struct{} `type:"structure"` + + // Filters applied to the individual assessments described in the form of key-value + // pairs. + // + // Valid filter names: replication-task-assessment-run-arn, replication-task-arn, + // status + Filters []*Filter `type:"list"` + + // An optional pagination token provided by a previous request. If this parameter + // is specified, the response includes only records beyond the marker, up to + // the value specified by MaxRecords. + Marker *string `type:"string"` + + // The maximum number of records to include in the response. If more records + // exist than the specified MaxRecords value, a pagination token called a marker + // is included in the response so that the remaining results can be retrieved. + MaxRecords *int64 `type:"integer"` +} + +// String returns the string representation +func (s DescribeReplicationTaskIndividualAssessmentsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeReplicationTaskIndividualAssessmentsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeReplicationTaskIndividualAssessmentsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeReplicationTaskIndividualAssessmentsInput"} + if s.Filters != nil { + for i, v := range s.Filters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetFilters sets the Filters field's value. +func (s *DescribeReplicationTaskIndividualAssessmentsInput) SetFilters(v []*Filter) *DescribeReplicationTaskIndividualAssessmentsInput { + s.Filters = v + return s +} + +// SetMarker sets the Marker field's value. +func (s *DescribeReplicationTaskIndividualAssessmentsInput) SetMarker(v string) *DescribeReplicationTaskIndividualAssessmentsInput { + s.Marker = &v + return s +} + +// SetMaxRecords sets the MaxRecords field's value. +func (s *DescribeReplicationTaskIndividualAssessmentsInput) SetMaxRecords(v int64) *DescribeReplicationTaskIndividualAssessmentsInput { + s.MaxRecords = &v + return s +} + +type DescribeReplicationTaskIndividualAssessmentsOutput struct { + _ struct{} `type:"structure"` + + // A pagination token returned for you to pass to a subsequent request. If you + // pass this token as the Marker value in a subsequent request, the response + // includes only records beyond the marker, up to the value specified in the + // request by MaxRecords. + Marker *string `type:"string"` + + // One or more individual assessments as specified by Filters. + ReplicationTaskIndividualAssessments []*ReplicationTaskIndividualAssessment `type:"list"` +} + +// String returns the string representation +func (s DescribeReplicationTaskIndividualAssessmentsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeReplicationTaskIndividualAssessmentsOutput) GoString() string { + return s.String() +} + +// SetMarker sets the Marker field's value. +func (s *DescribeReplicationTaskIndividualAssessmentsOutput) SetMarker(v string) *DescribeReplicationTaskIndividualAssessmentsOutput { + s.Marker = &v + return s +} + +// SetReplicationTaskIndividualAssessments sets the ReplicationTaskIndividualAssessments field's value. +func (s *DescribeReplicationTaskIndividualAssessmentsOutput) SetReplicationTaskIndividualAssessments(v []*ReplicationTaskIndividualAssessment) *DescribeReplicationTaskIndividualAssessmentsOutput { + s.ReplicationTaskIndividualAssessments = v + return s +} + type DescribeReplicationTasksInput struct { _ struct{} `type:"structure"` - // Filters applied to the describe action. + // Filters applied to replication tasks. // // Valid filter names: replication-task-arn | replication-task-id | migration-type // | endpoint-arn | replication-instance-arn @@ -8598,7 +9905,7 @@ func (s *DescribeSchemasOutput) SetSchemas(v []*string) *DescribeSchemasOutput { type DescribeTableStatisticsInput struct { _ struct{} `type:"structure"` - // Filters applied to the describe table statistics action. + // Filters applied to table statistics. // // Valid filter names: schema-name | table-name | table-state // @@ -8910,7 +10217,7 @@ type Endpoint struct { // "BucketName": "string", "CompressionType": "none"|"gzip" } DmsTransferSettings *DmsTransferSettings `type:"structure"` - // The settings for the target DynamoDB database. For more information, see + // The settings for the DynamoDB target endpoint. For more information, see // the DynamoDBSettings structure. DynamoDbSettings *DynamoDbSettings `type:"structure"` @@ -8936,7 +10243,7 @@ type Endpoint struct { // The database engine name. Valid values, depending on the EndpointType, include // "mysql", "oracle", "postgres", "mariadb", "aurora", "aurora-postgresql", // "redshift", "s3", "db2", "azuredb", "sybase", "dynamodb", "mongodb", "kinesis", - // "kafka", "elasticsearch", "documentdb", and "sqlserver". + // "kafka", "elasticsearch", "documentdb", "sqlserver", and "neptune". EngineName *string `type:"string"` // Value returned by a call to CreateEndpoint that can be used for cross-account @@ -8950,6 +10257,10 @@ type Endpoint struct { // Additional connection attributes used to connect to the endpoint. ExtraConnectionAttributes *string `type:"string"` + // The settings for the IBM Db2 LUW source endpoint. For more information, see + // the IBMDb2Settings structure. + IBMDb2Settings *IBMDb2Settings `type:"structure"` + // The settings for the Apache Kafka target endpoint. For more information, // see the KafkaSettings structure. KafkaSettings *KafkaSettings `type:"structure"` @@ -8968,17 +10279,33 @@ type Endpoint struct { // account has a different default encryption key for each AWS Region. KmsKeyId *string `type:"string"` + // The settings for the Microsoft SQL Server source and target endpoint. For + // more information, see the MicrosoftSQLServerSettings structure. + MicrosoftSQLServerSettings *MicrosoftSQLServerSettings `type:"structure"` + // The settings for the MongoDB source endpoint. For more information, see the // MongoDbSettings structure. MongoDbSettings *MongoDbSettings `type:"structure"` - // The settings for the MongoDB source endpoint. For more information, see the - // NeptuneSettings structure. + // The settings for the MySQL source and target endpoint. For more information, + // see the MySQLSettings structure. + MySQLSettings *MySQLSettings `type:"structure"` + + // The settings for the Amazon Neptune target endpoint. For more information, + // see the NeptuneSettings structure. NeptuneSettings *NeptuneSettings `type:"structure"` + // The settings for the Oracle source and target endpoint. For more information, + // see the OracleSettings structure. + OracleSettings *OracleSettings `type:"structure"` + // The port value used to access the endpoint. Port *int64 `type:"integer"` + // The settings for the PostgreSQL source and target endpoint. For more information, + // see the PostgreSQLSettings structure. + PostgreSQLSettings *PostgreSQLSettings `type:"structure"` + // Settings for the Amazon Redshift endpoint. RedshiftSettings *RedshiftSettings `type:"structure"` @@ -8998,6 +10325,10 @@ type Endpoint struct { // The status of the endpoint. Status *string `type:"string"` + // The settings for the SAP ASE source and target endpoint. For more information, + // see the SybaseSettings structure. + SybaseSettings *SybaseSettings `type:"structure"` + // The user name used to connect to the endpoint. Username *string `type:"string"` } @@ -9090,6 +10421,12 @@ func (s *Endpoint) SetExtraConnectionAttributes(v string) *Endpoint { return s } +// SetIBMDb2Settings sets the IBMDb2Settings field's value. +func (s *Endpoint) SetIBMDb2Settings(v *IBMDb2Settings) *Endpoint { + s.IBMDb2Settings = v + return s +} + // SetKafkaSettings sets the KafkaSettings field's value. func (s *Endpoint) SetKafkaSettings(v *KafkaSettings) *Endpoint { s.KafkaSettings = v @@ -9108,24 +10445,48 @@ func (s *Endpoint) SetKmsKeyId(v string) *Endpoint { return s } +// SetMicrosoftSQLServerSettings sets the MicrosoftSQLServerSettings field's value. +func (s *Endpoint) SetMicrosoftSQLServerSettings(v *MicrosoftSQLServerSettings) *Endpoint { + s.MicrosoftSQLServerSettings = v + return s +} + // SetMongoDbSettings sets the MongoDbSettings field's value. func (s *Endpoint) SetMongoDbSettings(v *MongoDbSettings) *Endpoint { s.MongoDbSettings = v return s } +// SetMySQLSettings sets the MySQLSettings field's value. +func (s *Endpoint) SetMySQLSettings(v *MySQLSettings) *Endpoint { + s.MySQLSettings = v + return s +} + // SetNeptuneSettings sets the NeptuneSettings field's value. func (s *Endpoint) SetNeptuneSettings(v *NeptuneSettings) *Endpoint { s.NeptuneSettings = v return s } +// SetOracleSettings sets the OracleSettings field's value. +func (s *Endpoint) SetOracleSettings(v *OracleSettings) *Endpoint { + s.OracleSettings = v + return s +} + // SetPort sets the Port field's value. func (s *Endpoint) SetPort(v int64) *Endpoint { s.Port = &v return s } +// SetPostgreSQLSettings sets the PostgreSQLSettings field's value. +func (s *Endpoint) SetPostgreSQLSettings(v *PostgreSQLSettings) *Endpoint { + s.PostgreSQLSettings = v + return s +} + // SetRedshiftSettings sets the RedshiftSettings field's value. func (s *Endpoint) SetRedshiftSettings(v *RedshiftSettings) *Endpoint { s.RedshiftSettings = v @@ -9162,6 +10523,12 @@ func (s *Endpoint) SetStatus(v string) *Endpoint { return s } +// SetSybaseSettings sets the SybaseSettings field's value. +func (s *Endpoint) SetSybaseSettings(v *SybaseSettings) *Endpoint { + s.SybaseSettings = v + return s +} + // SetUsername sets the Username field's value. func (s *Endpoint) SetUsername(v string) *Endpoint { s.Username = &v @@ -9310,7 +10677,7 @@ type EventSubscription struct { // topic was deleted after the subscription was created. Status *string `type:"string"` - // The time the RDS event notification subscription was created. + // The time the AWS DMS event notification subscription was created. SubscriptionCreationTime *string `type:"string"` } @@ -9378,17 +10745,19 @@ func (s *EventSubscription) SetSubscriptionCreationTime(v string) *EventSubscrip return s } -// Identifies the name and value of a source filter object used to limit the -// number and type of records transferred from your source to your target. +// Identifies the name and value of a filter object. This filter is used to +// limit the number and type of AWS DMS objects that are returned for a particular +// Describe* or similar operation. type Filter struct { _ struct{} `type:"structure"` - // The name of the filter. + // The name of the filter as specified for a Describe* or similar operation. // // Name is a required field Name *string `type:"string" required:"true"` - // The filter value. + // The filter value, which can specify one or more values used to narrow the + // returned results. // // Values is a required field Values []*string `type:"list" required:"true"` @@ -9432,6 +10801,66 @@ func (s *Filter) SetValues(v []*string) *Filter { return s } +// Provides information that defines an IBM Db2 LUW endpoint. +type IBMDb2Settings struct { + _ struct{} `type:"structure"` + + // Database name for the endpoint. + DatabaseName *string `type:"string"` + + // Endpoint connection password. + Password *string `type:"string" sensitive:"true"` + + // Endpoint TCP port. + Port *int64 `type:"integer"` + + // Fully qualified domain name of the endpoint. + ServerName *string `type:"string"` + + // Endpoint connection user name. + Username *string `type:"string"` +} + +// String returns the string representation +func (s IBMDb2Settings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s IBMDb2Settings) GoString() string { + return s.String() +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *IBMDb2Settings) SetDatabaseName(v string) *IBMDb2Settings { + s.DatabaseName = &v + return s +} + +// SetPassword sets the Password field's value. +func (s *IBMDb2Settings) SetPassword(v string) *IBMDb2Settings { + s.Password = &v + return s +} + +// SetPort sets the Port field's value. +func (s *IBMDb2Settings) SetPort(v int64) *IBMDb2Settings { + s.Port = &v + return s +} + +// SetServerName sets the ServerName field's value. +func (s *IBMDb2Settings) SetServerName(v string) *IBMDb2Settings { + s.ServerName = &v + return s +} + +// SetUsername sets the Username field's value. +func (s *IBMDb2Settings) SetUsername(v string) *IBMDb2Settings { + s.Username = &v + return s +} + type ImportCertificateInput struct { _ struct{} `type:"structure"` @@ -9862,6 +11291,63 @@ func (s *KMSDisabledFault) RequestID() string { return s.RespMetadata.RequestID } +// An AWS Key Management Service (AWS KMS) error is preventing access to AWS +// KMS. +type KMSFault struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s KMSFault) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s KMSFault) GoString() string { + return s.String() +} + +func newErrorKMSFault(v protocol.ResponseMetadata) error { + return &KMSFault{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *KMSFault) Code() string { + return "KMSFault" +} + +// Message returns the exception's message. +func (s *KMSFault) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *KMSFault) OrigErr() error { + return nil +} + +func (s *KMSFault) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *KMSFault) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *KMSFault) RequestID() string { + return s.RespMetadata.RequestID +} + // The state of the specified AWS KMS resource isn't valid for this request. type KMSInvalidStateFault struct { _ struct{} `type:"structure"` @@ -10097,6 +11583,38 @@ type KafkaSettings struct { // "ec2-12-345-678-901.compute-1.amazonaws.com:2345". Broker *string `type:"string"` + // Shows detailed control information for table definition, column definition, + // and table and column changes in the Kafka message output. The default is + // False. + IncludeControlDetails *bool `type:"boolean"` + + // Shows the partition value within the Kafka message output, unless the partition + // type is schema-table-type. The default is False. + IncludePartitionValue *bool `type:"boolean"` + + // Includes any data definition language (DDL) operations that change the table + // in the control data, such as rename-table, drop-table, add-column, drop-column, + // and rename-column. The default is False. + IncludeTableAlterOperations *bool `type:"boolean"` + + // Provides detailed transaction information from the source database. This + // information includes a commit timestamp, a log position, and values for transaction_id, + // previous transaction_id, and transaction_record_id (the record offset within + // a transaction). The default is False. + IncludeTransactionDetails *bool `type:"boolean"` + + // The output format for the records created on the endpoint. The message format + // is JSON (default) or JSON_UNFORMATTED (a single line with no tab). + MessageFormat *string `type:"string" enum:"MessageFormatValue"` + + // Prefixes schema and table names to partition values, when the partition type + // is primary-key-type. Doing this increases data distribution among Kafka partitions. + // For example, suppose that a SysBench schema has thousands of tables and each + // table has only limited range for a primary key. In this case, the same primary + // key is sent from thousands of tables to the same partition, which causes + // throttling. The default is False. + PartitionIncludeSchemaTable *bool `type:"boolean"` + // The topic to which you migrate the data. If you don't specify a topic, AWS // DMS specifies "kafka-default-topic" as the migration topic. Topic *string `type:"string"` @@ -10118,6 +11636,42 @@ func (s *KafkaSettings) SetBroker(v string) *KafkaSettings { return s } +// SetIncludeControlDetails sets the IncludeControlDetails field's value. +func (s *KafkaSettings) SetIncludeControlDetails(v bool) *KafkaSettings { + s.IncludeControlDetails = &v + return s +} + +// SetIncludePartitionValue sets the IncludePartitionValue field's value. +func (s *KafkaSettings) SetIncludePartitionValue(v bool) *KafkaSettings { + s.IncludePartitionValue = &v + return s +} + +// SetIncludeTableAlterOperations sets the IncludeTableAlterOperations field's value. +func (s *KafkaSettings) SetIncludeTableAlterOperations(v bool) *KafkaSettings { + s.IncludeTableAlterOperations = &v + return s +} + +// SetIncludeTransactionDetails sets the IncludeTransactionDetails field's value. +func (s *KafkaSettings) SetIncludeTransactionDetails(v bool) *KafkaSettings { + s.IncludeTransactionDetails = &v + return s +} + +// SetMessageFormat sets the MessageFormat field's value. +func (s *KafkaSettings) SetMessageFormat(v string) *KafkaSettings { + s.MessageFormat = &v + return s +} + +// SetPartitionIncludeSchemaTable sets the PartitionIncludeSchemaTable field's value. +func (s *KafkaSettings) SetPartitionIncludeSchemaTable(v bool) *KafkaSettings { + s.PartitionIncludeSchemaTable = &v + return s +} + // SetTopic sets the Topic field's value. func (s *KafkaSettings) SetTopic(v string) *KafkaSettings { s.Topic = &v @@ -10290,6 +11844,66 @@ func (s *ListTagsForResourceOutput) SetTagList(v []*Tag) *ListTagsForResourceOut return s } +// Provides information that defines a Microsoft SQL Server endpoint. +type MicrosoftSQLServerSettings struct { + _ struct{} `type:"structure"` + + // Database name for the endpoint. + DatabaseName *string `type:"string"` + + // Endpoint connection password. + Password *string `type:"string" sensitive:"true"` + + // Endpoint TCP port. + Port *int64 `type:"integer"` + + // Fully qualified domain name of the endpoint. + ServerName *string `type:"string"` + + // Endpoint connection user name. + Username *string `type:"string"` +} + +// String returns the string representation +func (s MicrosoftSQLServerSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MicrosoftSQLServerSettings) GoString() string { + return s.String() +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *MicrosoftSQLServerSettings) SetDatabaseName(v string) *MicrosoftSQLServerSettings { + s.DatabaseName = &v + return s +} + +// SetPassword sets the Password field's value. +func (s *MicrosoftSQLServerSettings) SetPassword(v string) *MicrosoftSQLServerSettings { + s.Password = &v + return s +} + +// SetPort sets the Port field's value. +func (s *MicrosoftSQLServerSettings) SetPort(v int64) *MicrosoftSQLServerSettings { + s.Port = &v + return s +} + +// SetServerName sets the ServerName field's value. +func (s *MicrosoftSQLServerSettings) SetServerName(v string) *MicrosoftSQLServerSettings { + s.ServerName = &v + return s +} + +// SetUsername sets the Username field's value. +func (s *MicrosoftSQLServerSettings) SetUsername(v string) *MicrosoftSQLServerSettings { + s.Username = &v + return s +} + type ModifyEndpointInput struct { _ struct{} `type:"structure"` @@ -10328,7 +11942,7 @@ type ModifyEndpointInput struct { // Settings in JSON format for the target Elasticsearch endpoint. For more information // about the available settings, see Extra Connection Attributes When Using // Elasticsearch as a Target for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Elasticsearch.html#CHAP_Target.Elasticsearch.Configuration) - // in the AWS Database Migration User Guide. + // in the AWS Database Migration Service User Guide. ElasticsearchSettings *ElasticsearchSettings `type:"structure"` // The Amazon Resource Name (ARN) string that uniquely identifies the endpoint. @@ -10347,7 +11961,7 @@ type ModifyEndpointInput struct { // The type of engine for the endpoint. Valid values, depending on the EndpointType, // include "mysql", "oracle", "postgres", "mariadb", "aurora", "aurora-postgresql", // "redshift", "s3", "db2", "azuredb", "sybase", "dynamodb", "mongodb", "kinesis", - // "kafka", "elasticsearch", "documentdb", and "sqlserver". + // "kafka", "elasticsearch", "documentdb", "sqlserver", and "neptune". EngineName *string `type:"string"` // The external table definition. @@ -10357,36 +11971,74 @@ type ModifyEndpointInput struct { // pass the empty string ("") as an argument. ExtraConnectionAttributes *string `type:"string"` + // Settings in JSON format for the source IBM Db2 LUW endpoint. For information + // about other available settings, see Extra connection attributes when using + // Db2 LUW as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.DB2.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + IBMDb2Settings *IBMDb2Settings `type:"structure"` + // Settings in JSON format for the target Apache Kafka endpoint. For more information // about the available settings, see Using Apache Kafka as a Target for AWS // Database Migration Service (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Kafka.html) - // in the AWS Database Migration User Guide. + // in the AWS Database Migration Service User Guide. KafkaSettings *KafkaSettings `type:"structure"` // Settings in JSON format for the target endpoint for Amazon Kinesis Data Streams. // For more information about the available settings, see Using Amazon Kinesis // Data Streams as a Target for AWS Database Migration Service (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Kinesis.html) - // in the AWS Database Migration User Guide. + // in the AWS Database Migration Service User Guide. KinesisSettings *KinesisSettings `type:"structure"` + // Settings in JSON format for the source and target Microsoft SQL Server endpoint. + // For information about other available settings, see Extra connection attributes + // when using SQL Server as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.SQLServer.ConnectionAttrib) + // and Extra connection attributes when using SQL Server as a target for AWS + // DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.SQLServer.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + MicrosoftSQLServerSettings *MicrosoftSQLServerSettings `type:"structure"` + // Settings in JSON format for the source MongoDB endpoint. For more information // about the available settings, see the configuration properties section in // Using MongoDB as a Target for AWS Database Migration Service (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.MongoDB.html) // in the AWS Database Migration Service User Guide. MongoDbSettings *MongoDbSettings `type:"structure"` + // Settings in JSON format for the source and target MySQL endpoint. For information + // about other available settings, see Extra connection attributes when using + // MySQL as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.MySQL.ConnectionAttrib) + // and Extra connection attributes when using a MySQL-compatible database as + // a target for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.MySQL.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + MySQLSettings *MySQLSettings `type:"structure"` + // Settings in JSON format for the target Amazon Neptune endpoint. For more - // information about the available settings, see https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Neptune.html#CHAP_Target.Neptune.EndpointSettings - // (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Neptune.html#CHAP_Target.Neptune.EndpointSettings) + // information about the available settings, see Specifying Endpoint Settings + // for Amazon Neptune as a Target (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Neptune.html#CHAP_Target.Neptune.EndpointSettings) // in the AWS Database Migration Service User Guide. NeptuneSettings *NeptuneSettings `type:"structure"` + // Settings in JSON format for the source and target Oracle endpoint. For information + // about other available settings, see Extra connection attributes when using + // Oracle as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.Oracle.ConnectionAttrib) + // and Extra connection attributes when using Oracle as a target for AWS DMS + // (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Oracle.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + OracleSettings *OracleSettings `type:"structure"` + // The password to be used to login to the endpoint database. Password *string `type:"string" sensitive:"true"` // The port used by the endpoint database. Port *int64 `type:"integer"` + // Settings in JSON format for the source and target PostgreSQL endpoint. For + // information about other available settings, see Extra connection attributes + // when using PostgreSQL as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.PostgreSQL.ConnectionAttrib) + // and Extra connection attributes when using PostgreSQL as a target for AWS + // DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.PostgreSQL.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + PostgreSQLSettings *PostgreSQLSettings `type:"structure"` + // Provides information that defines an Amazon Redshift endpoint. RedshiftSettings *RedshiftSettings `type:"structure"` @@ -10406,6 +12058,14 @@ type ModifyEndpointInput struct { // The SSL mode used to connect to the endpoint. The default value is none. SslMode *string `type:"string" enum:"DmsSslModeValue"` + // Settings in JSON format for the source and target SAP ASE endpoint. For information + // about other available settings, see Extra connection attributes when using + // SAP ASE as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.SAP.ConnectionAttrib) + // and Extra connection attributes when using SAP ASE as a target for AWS DMS + // (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.SAP.ConnectionAttrib) + // in the AWS Database Migration Service User Guide. + SybaseSettings *SybaseSettings `type:"structure"` + // The user name to be used to login to the endpoint database. Username *string `type:"string"` } @@ -10514,6 +12174,12 @@ func (s *ModifyEndpointInput) SetExtraConnectionAttributes(v string) *ModifyEndp return s } +// SetIBMDb2Settings sets the IBMDb2Settings field's value. +func (s *ModifyEndpointInput) SetIBMDb2Settings(v *IBMDb2Settings) *ModifyEndpointInput { + s.IBMDb2Settings = v + return s +} + // SetKafkaSettings sets the KafkaSettings field's value. func (s *ModifyEndpointInput) SetKafkaSettings(v *KafkaSettings) *ModifyEndpointInput { s.KafkaSettings = v @@ -10526,18 +12192,36 @@ func (s *ModifyEndpointInput) SetKinesisSettings(v *KinesisSettings) *ModifyEndp return s } +// SetMicrosoftSQLServerSettings sets the MicrosoftSQLServerSettings field's value. +func (s *ModifyEndpointInput) SetMicrosoftSQLServerSettings(v *MicrosoftSQLServerSettings) *ModifyEndpointInput { + s.MicrosoftSQLServerSettings = v + return s +} + // SetMongoDbSettings sets the MongoDbSettings field's value. func (s *ModifyEndpointInput) SetMongoDbSettings(v *MongoDbSettings) *ModifyEndpointInput { s.MongoDbSettings = v return s } +// SetMySQLSettings sets the MySQLSettings field's value. +func (s *ModifyEndpointInput) SetMySQLSettings(v *MySQLSettings) *ModifyEndpointInput { + s.MySQLSettings = v + return s +} + // SetNeptuneSettings sets the NeptuneSettings field's value. func (s *ModifyEndpointInput) SetNeptuneSettings(v *NeptuneSettings) *ModifyEndpointInput { s.NeptuneSettings = v return s } +// SetOracleSettings sets the OracleSettings field's value. +func (s *ModifyEndpointInput) SetOracleSettings(v *OracleSettings) *ModifyEndpointInput { + s.OracleSettings = v + return s +} + // SetPassword sets the Password field's value. func (s *ModifyEndpointInput) SetPassword(v string) *ModifyEndpointInput { s.Password = &v @@ -10550,6 +12234,12 @@ func (s *ModifyEndpointInput) SetPort(v int64) *ModifyEndpointInput { return s } +// SetPostgreSQLSettings sets the PostgreSQLSettings field's value. +func (s *ModifyEndpointInput) SetPostgreSQLSettings(v *PostgreSQLSettings) *ModifyEndpointInput { + s.PostgreSQLSettings = v + return s +} + // SetRedshiftSettings sets the RedshiftSettings field's value. func (s *ModifyEndpointInput) SetRedshiftSettings(v *RedshiftSettings) *ModifyEndpointInput { s.RedshiftSettings = v @@ -10580,6 +12270,12 @@ func (s *ModifyEndpointInput) SetSslMode(v string) *ModifyEndpointInput { return s } +// SetSybaseSettings sets the SybaseSettings field's value. +func (s *ModifyEndpointInput) SetSybaseSettings(v *SybaseSettings) *ModifyEndpointInput { + s.SybaseSettings = v + return s +} + // SetUsername sets the Username field's value. func (s *ModifyEndpointInput) SetUsername(v string) *ModifyEndpointInput { s.Username = &v @@ -10775,10 +12471,13 @@ type ModifyReplicationInstanceInput struct { // ReplicationInstanceArn is a required field ReplicationInstanceArn *string `type:"string" required:"true"` - // The compute and memory capacity of the replication instance. + // The compute and memory capacity of the replication instance as defined for + // the specified replication instance class. For example to specify the instance + // class dms.c4.large, set this parameter to "dms.c4.large". // - // Valid Values: dms.t2.micro | dms.t2.small | dms.t2.medium | dms.t2.large - // | dms.c4.large | dms.c4.xlarge | dms.c4.2xlarge | dms.c4.4xlarge + // For more information on the settings and capacities for the available replication + // instance classes, see Selecting the right AWS DMS replication instance for + // your migration (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html#CHAP_ReplicationInstance.InDepth). ReplicationInstanceClass *string `type:"string"` // The replication instance identifier. This parameter is stored as a lowercase @@ -11037,7 +12736,7 @@ type ModifyReplicationTaskInput struct { // // Constraints: // - // * Must contain from 1 to 255 alphanumeric characters or hyphens. + // * Must contain 1-255 alphanumeric characters or hyphens. // // * First character must be a letter. // @@ -11056,7 +12755,7 @@ type ModifyReplicationTaskInput struct { // Supplemental information that the task requires to migrate the data for certain // source and target endpoints. For more information, see Specifying Supplemental // Data for Task Settings (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.TaskData.html) - // in the AWS Database Migration User Guide. + // in the AWS Database Migration Service User Guide. TaskData *string `type:"string"` } @@ -11166,37 +12865,35 @@ type MongoDbSettings struct { // The authentication mechanism you use to access the MongoDB source endpoint. // - // Valid values: DEFAULT, MONGODB_CR, SCRAM_SHA_1 - // - // DEFAULT – For MongoDB version 2.x, use MONGODB_CR. For MongoDB version - // 3.x, use SCRAM_SHA_1. This setting isn't used when authType=No. + // For the default value, in MongoDB version 2.x, "default" is "mongodb_cr". + // For MongoDB version 3.x or later, "default" is "scram_sha_1". This setting + // isn't used when AuthType is set to "no". AuthMechanism *string `type:"string" enum:"AuthMechanismValue"` - // The MongoDB database name. This setting isn't used when authType=NO. + // The MongoDB database name. This setting isn't used when AuthType is set to + // "no". // - // The default is admin. + // The default is "admin". AuthSource *string `type:"string"` // The authentication type you use to access the MongoDB source endpoint. // - // Valid values: NO, PASSWORD - // - // When NO is selected, user name and password parameters are not used and can - // be empty. + // When when set to "no", user name and password parameters are not used and + // can be empty. AuthType *string `type:"string" enum:"AuthTypeValue"` // The database name on the MongoDB source endpoint. DatabaseName *string `type:"string"` // Indicates the number of documents to preview to determine the document organization. - // Use this setting when NestingLevel is set to ONE. + // Use this setting when NestingLevel is set to "one". // // Must be a positive value greater than 0. Default value is 1000. DocsToInvestigate *string `type:"string"` - // Specifies the document ID. Use this setting when NestingLevel is set to NONE. + // Specifies the document ID. Use this setting when NestingLevel is set to "none". // - // Default value is false. + // Default value is "false". ExtractDocId *string `type:"string"` // The AWS KMS key identifier that is used to encrypt the content on the replication @@ -11208,10 +12905,8 @@ type MongoDbSettings struct { // Specifies either document or table mode. // - // Valid values: NONE, ONE - // - // Default value is NONE. Specify NONE to use document mode. Specify ONE to - // use table mode. + // Default value is "none". Specify "none" to use document mode. Specify "one" + // to use table mode. NestingLevel *string `type:"string" enum:"NestingLevelValue"` // The password for the user account you use to access the MongoDB source endpoint. @@ -11309,47 +13004,108 @@ func (s *MongoDbSettings) SetUsername(v string) *MongoDbSettings { return s } -// Provides information that defines an Amazon Neptune endpoint. -type NeptuneSettings struct { +// Provides information that defines a MySQL endpoint. +type MySQLSettings struct { _ struct{} `type:"structure"` - // The number of milliseconds for AWS DMS to wait to retry a bulk-load of migrated - // graph data to the Neptune target database before raising an error. The default - // is 250. - ErrorRetryDuration *int64 `type:"integer"` + // Database name for the endpoint. + DatabaseName *string `type:"string"` - // If you want IAM authorization enabled for this endpoint, set this parameter - // to true and attach the appropriate role policy document to your service role - // specified by ServiceAccessRoleArn. The default is false. - IamAuthEnabled *bool `type:"boolean"` + // Endpoint connection password. + Password *string `type:"string" sensitive:"true"` - // The maximum size in KB of migrated graph data stored in a CSV file before - // AWS DMS bulk-loads the data to the Neptune target database. The default is - // 1048576 KB. If successful, AWS DMS clears the bucket, ready to store the - // next batch of migrated graph data. - MaxFileSize *int64 `type:"integer"` + // Endpoint TCP port. + Port *int64 `type:"integer"` + + // Fully qualified domain name of the endpoint. + ServerName *string `type:"string"` + + // Endpoint connection user name. + Username *string `type:"string"` +} + +// String returns the string representation +func (s MySQLSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MySQLSettings) GoString() string { + return s.String() +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *MySQLSettings) SetDatabaseName(v string) *MySQLSettings { + s.DatabaseName = &v + return s +} + +// SetPassword sets the Password field's value. +func (s *MySQLSettings) SetPassword(v string) *MySQLSettings { + s.Password = &v + return s +} + +// SetPort sets the Port field's value. +func (s *MySQLSettings) SetPort(v int64) *MySQLSettings { + s.Port = &v + return s +} + +// SetServerName sets the ServerName field's value. +func (s *MySQLSettings) SetServerName(v string) *MySQLSettings { + s.ServerName = &v + return s +} + +// SetUsername sets the Username field's value. +func (s *MySQLSettings) SetUsername(v string) *MySQLSettings { + s.Username = &v + return s +} + +// Provides information that defines an Amazon Neptune endpoint. +type NeptuneSettings struct { + _ struct{} `type:"structure"` + + // The number of milliseconds for AWS DMS to wait to retry a bulk-load of migrated + // graph data to the Neptune target database before raising an error. The default + // is 250. + ErrorRetryDuration *int64 `type:"integer"` - // The number of times for AWS DMS to retry a bulk-load of migrated graph data + // If you want AWS Identity and Access Management (IAM) authorization enabled + // for this endpoint, set this parameter to true. Then attach the appropriate + // IAM policy document to your service role specified by ServiceAccessRoleArn. + // The default is false. + IamAuthEnabled *bool `type:"boolean"` + + // The maximum size in kilobytes of migrated graph data stored in a .csv file + // before AWS DMS bulk-loads the data to the Neptune target database. The default + // is 1,048,576 KB. If the bulk load is successful, AWS DMS clears the bucket, + // ready to store the next batch of migrated graph data. + MaxFileSize *int64 `type:"integer"` + + // The number of times for AWS DMS to retry a bulk load of migrated graph data // to the Neptune target database before raising an error. The default is 5. MaxRetryCount *int64 `type:"integer"` - // A folder path where you where you want AWS DMS to store migrated graph data - // in the S3 bucket specified by S3BucketName + // A folder path where you want AWS DMS to store migrated graph data in the + // S3 bucket specified by S3BucketName // // S3BucketFolder is a required field S3BucketFolder *string `type:"string" required:"true"` - // The name of the S3 bucket for AWS DMS to temporarily store migrated graph - // data in CSV files before bulk-loading it to the Neptune target database. + // The name of the Amazon S3 bucket where AWS DMS can temporarily store migrated + // graph data in .csv files before bulk-loading it to the Neptune target database. // AWS DMS maps the SQL source data to graph data before storing it in these - // CSV files. + // .csv files. // // S3BucketName is a required field S3BucketName *string `type:"string" required:"true"` - // The ARN of the service role you have created for the Neptune target endpoint. - // For more information, see https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Neptune.html#CHAP_Target.Neptune.ServiceRole - // (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Neptune.html#CHAP_Target.Neptune.ServiceRole) + // The Amazon Resource Name (ARN) of the service role that you created for the + // Neptune target endpoint. For more information, see Creating an IAM Service + // Role for Accessing Amazon Neptune as a Target (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.Neptune.html#CHAP_Target.Neptune.ServiceRole) // in the AWS Database Migration Service User Guide. ServiceAccessRoleArn *string `type:"string"` } @@ -11422,6 +13178,138 @@ func (s *NeptuneSettings) SetServiceAccessRoleArn(v string) *NeptuneSettings { return s } +// Provides information that defines an Oracle endpoint. +type OracleSettings struct { + _ struct{} `type:"structure"` + + // For an Oracle source endpoint, your Oracle Automatic Storage Management (ASM) + // password. You can set this value from the asm_user_password value. You set + // this value as part of the comma-separated value that you set to the Password + // request parameter when you create the endpoint to access transaction logs + // using Binary Reader. For more information, see Configuration for change data + // capture (CDC) on an Oracle source database (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.Oracle.html#dms/latest/userguide/CHAP_Source.Oracle.html#CHAP_Source.Oracle.CDC.Configuration). + AsmPassword *string `type:"string" sensitive:"true"` + + // For an Oracle source endpoint, your ASM server address. You can set this + // value from the asm_server value. You set asm_server as part of the extra + // connection attribute string to access an Oracle server with Binary Reader + // that uses ASM. For more information, see Configuration for change data capture + // (CDC) on an Oracle source database (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.Oracle.html#dms/latest/userguide/CHAP_Source.Oracle.html#CHAP_Source.Oracle.CDC.Configuration). + AsmServer *string `type:"string"` + + // For an Oracle source endpoint, your ASM user name. You can set this value + // from the asm_user value. You set asm_user as part of the extra connection + // attribute string to access an Oracle server with Binary Reader that uses + // ASM. For more information, see Configuration for change data capture (CDC) + // on an Oracle source database (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.Oracle.html#dms/latest/userguide/CHAP_Source.Oracle.html#CHAP_Source.Oracle.CDC.Configuration). + AsmUser *string `type:"string"` + + // Database name for the endpoint. + DatabaseName *string `type:"string"` + + // Endpoint connection password. + Password *string `type:"string" sensitive:"true"` + + // Endpoint TCP port. + Port *int64 `type:"integer"` + + // For an Oracle source endpoint, the transparent data encryption (TDE) password + // required by AWM DMS to access Oracle redo logs encrypted by TDE using Binary + // Reader. It is also the TDE_Password part of the comma-separated value you + // set to the Password request parameter when you create the endpoint. The SecurityDbEncryptian + // setting is related to this SecurityDbEncryptionName setting. For more information, + // see Supported encryption methods for using Oracle as a source for AWS DMS + // (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.Oracle.html#CHAP_Source.Oracle.Encryption) + // in the AWS Database Migration Service User Guide. + SecurityDbEncryption *string `type:"string" sensitive:"true"` + + // For an Oracle source endpoint, the name of a key used for the transparent + // data encryption (TDE) of the columns and tablespaces in an Oracle source + // database that is encrypted using TDE. The key value is the value of the SecurityDbEncryption + // setting. For more information on setting the key name value of SecurityDbEncryptionName, + // see the information and example for setting the securityDbEncryptionName + // extra connection attribute in Supported encryption methods for using Oracle + // as a source for AWS DMS (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.Oracle.html#CHAP_Source.Oracle.Encryption) + // in the AWS Database Migration Service User Guide. + SecurityDbEncryptionName *string `type:"string"` + + // Fully qualified domain name of the endpoint. + ServerName *string `type:"string"` + + // Endpoint connection user name. + Username *string `type:"string"` +} + +// String returns the string representation +func (s OracleSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OracleSettings) GoString() string { + return s.String() +} + +// SetAsmPassword sets the AsmPassword field's value. +func (s *OracleSettings) SetAsmPassword(v string) *OracleSettings { + s.AsmPassword = &v + return s +} + +// SetAsmServer sets the AsmServer field's value. +func (s *OracleSettings) SetAsmServer(v string) *OracleSettings { + s.AsmServer = &v + return s +} + +// SetAsmUser sets the AsmUser field's value. +func (s *OracleSettings) SetAsmUser(v string) *OracleSettings { + s.AsmUser = &v + return s +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *OracleSettings) SetDatabaseName(v string) *OracleSettings { + s.DatabaseName = &v + return s +} + +// SetPassword sets the Password field's value. +func (s *OracleSettings) SetPassword(v string) *OracleSettings { + s.Password = &v + return s +} + +// SetPort sets the Port field's value. +func (s *OracleSettings) SetPort(v int64) *OracleSettings { + s.Port = &v + return s +} + +// SetSecurityDbEncryption sets the SecurityDbEncryption field's value. +func (s *OracleSettings) SetSecurityDbEncryption(v string) *OracleSettings { + s.SecurityDbEncryption = &v + return s +} + +// SetSecurityDbEncryptionName sets the SecurityDbEncryptionName field's value. +func (s *OracleSettings) SetSecurityDbEncryptionName(v string) *OracleSettings { + s.SecurityDbEncryptionName = &v + return s +} + +// SetServerName sets the ServerName field's value. +func (s *OracleSettings) SetServerName(v string) *OracleSettings { + s.ServerName = &v + return s +} + +// SetUsername sets the Username field's value. +func (s *OracleSettings) SetUsername(v string) *OracleSettings { + s.Username = &v + return s +} + // In response to the DescribeOrderableReplicationInstances operation, this // object describes an available replication instance. This description includes // the replication instance's type, engine version, and allocated storage. @@ -11456,10 +13344,13 @@ type OrderableReplicationInstance struct { // AWS DMS supports the ReleaseStatus parameter in versions 3.1.4 and later. ReleaseStatus *string `type:"string" enum:"ReleaseStatusValues"` - // The compute and memory capacity of the replication instance. + // The compute and memory capacity of the replication instance as defined for + // the specified replication instance class. For example to specify the instance + // class dms.c4.large, set this parameter to "dms.c4.large". // - // Valid Values: dms.t2.micro | dms.t2.small | dms.t2.medium | dms.t2.large - // | dms.c4.large | dms.c4.xlarge | dms.c4.2xlarge | dms.c4.4xlarge + // For more information on the settings and capacities for the available replication + // instance classes, see Selecting the right AWS DMS replication instance for + // your migration (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html#CHAP_ReplicationInstance.InDepth). ReplicationInstanceClass *string `type:"string"` // The type of storage used by the replication instance. @@ -11612,6 +13503,66 @@ func (s *PendingMaintenanceAction) SetOptInStatus(v string) *PendingMaintenanceA return s } +// Provides information that defines a PostgreSQL endpoint. +type PostgreSQLSettings struct { + _ struct{} `type:"structure"` + + // Database name for the endpoint. + DatabaseName *string `type:"string"` + + // Endpoint connection password. + Password *string `type:"string" sensitive:"true"` + + // Endpoint TCP port. + Port *int64 `type:"integer"` + + // Fully qualified domain name of the endpoint. + ServerName *string `type:"string"` + + // Endpoint connection user name. + Username *string `type:"string"` +} + +// String returns the string representation +func (s PostgreSQLSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PostgreSQLSettings) GoString() string { + return s.String() +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *PostgreSQLSettings) SetDatabaseName(v string) *PostgreSQLSettings { + s.DatabaseName = &v + return s +} + +// SetPassword sets the Password field's value. +func (s *PostgreSQLSettings) SetPassword(v string) *PostgreSQLSettings { + s.Password = &v + return s +} + +// SetPort sets the Port field's value. +func (s *PostgreSQLSettings) SetPort(v int64) *PostgreSQLSettings { + s.Port = &v + return s +} + +// SetServerName sets the ServerName field's value. +func (s *PostgreSQLSettings) SetServerName(v string) *PostgreSQLSettings { + s.ServerName = &v + return s +} + +// SetUsername sets the Username field's value. +func (s *PostgreSQLSettings) SetUsername(v string) *PostgreSQLSettings { + s.Username = &v + return s +} + type RebootReplicationInstanceInput struct { _ struct{} `type:"structure"` @@ -12149,6 +14100,16 @@ func (s *ReloadTablesInput) Validate() error { if s.TablesToReload == nil { invalidParams.Add(request.NewErrParamRequired("TablesToReload")) } + if s.TablesToReload != nil { + for i, v := range s.TablesToReload { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TablesToReload", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -12280,7 +14241,8 @@ type ReplicationInstance struct { // The Availability Zone for the instance. AvailabilityZone *string `type:"string"` - // The DNS name servers for the replication instance. + // The DNS name servers supported for the replication instance to access your + // on-premise source or target database. DnsNameServers *string `type:"string"` // The engine version number of the replication instance. @@ -12322,10 +14284,12 @@ type ReplicationInstance struct { // The Amazon Resource Name (ARN) of the replication instance. ReplicationInstanceArn *string `type:"string"` - // The compute and memory capacity of the replication instance. + // The compute and memory capacity of the replication instance as defined for + // the specified replication instance class. // - // Valid Values: dms.t2.micro | dms.t2.small | dms.t2.medium | dms.t2.large - // | dms.c4.large | dms.c4.xlarge | dms.c4.2xlarge | dms.c4.4xlarge + // For more information on the settings and capacities for the available replication + // instance classes, see Selecting the right AWS DMS replication instance for + // your migration (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html#CHAP_ReplicationInstance.InDepth). ReplicationInstanceClass *string `type:"string"` // The replication instance identifier. This parameter is stored as a lowercase @@ -12333,7 +14297,7 @@ type ReplicationInstance struct { // // Constraints: // - // * Must contain from 1 to 63 alphanumeric characters or hyphens. + // * Must contain 1-63 alphanumeric characters or hyphens. // // * First character must be a letter. // @@ -12358,7 +14322,33 @@ type ReplicationInstance struct { // One or more public IP addresses for the replication instance. ReplicationInstancePublicIpAddresses []*string `type:"list"` - // The status of the replication instance. + // The status of the replication instance. The possible return values include: + // + // * "available" + // + // * "creating" + // + // * "deleted" + // + // * "deleting" + // + // * "failed" + // + // * "modifying" + // + // * "upgrading" + // + // * "rebooting" + // + // * "resetting-master-credentials" + // + // * "storage-full" + // + // * "incompatible-credentials" + // + // * "incompatible-network" + // + // * "maintenance" ReplicationInstanceStatus *string `type:"string"` // The subnet group for the replication instance. @@ -12579,10 +14569,12 @@ type ReplicationPendingModifiedValues struct { // to true. MultiAZ *bool `type:"boolean"` - // The compute and memory capacity of the replication instance. + // The compute and memory capacity of the replication instance as defined for + // the specified replication instance class. // - // Valid Values: dms.t2.micro | dms.t2.small | dms.t2.medium | dms.t2.large - // | dms.c4.large | dms.c4.xlarge | dms.c4.2xlarge | dms.c4.4xlarge + // For more information on the settings and capacities for the available replication + // instance classes, see Selecting the right AWS DMS replication instance for + // your migration (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html#CHAP_ReplicationInstance.InDepth). ReplicationInstanceClass *string `type:"string"` } @@ -12789,7 +14781,7 @@ type ReplicationTask struct { // // Constraints: // - // * Must contain from 1 to 255 alphanumeric characters or hyphens. + // * Must contain 1-255 alphanumeric characters or hyphens. // // * First character must be a letter. // @@ -12812,7 +14804,20 @@ type ReplicationTask struct { // The status of the replication task. Status *string `type:"string"` - // The reason the replication task was stopped. + // The reason the replication task was stopped. This response parameter can + // return one of the following values: + // + // * "STOP_REASON_FULL_LOAD_COMPLETED" – Full-load migration completed. + // + // * "STOP_REASON_CACHED_CHANGES_APPLIED" – Change data capture (CDC) load + // completed. + // + // * "STOP_REASON_CACHED_CHANGES_NOT_APPLIED" – In a full-load and CDC + // migration, the full-load stopped as specified before starting the CDC + // migration. + // + // * "STOP_REASON_SERVER_TIME" – The migration stopped at the specified + // server time. StopReason *string `type:"string"` // Table mappings specified in the task. @@ -12824,7 +14829,7 @@ type ReplicationTask struct { // Supplemental information that the task requires to migrate the data for certain // source and target endpoints. For more information, see Specifying Supplemental // Data for Task Settings (https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.TaskData.html) - // in the AWS Database Migration User Guide. + // in the AWS Database Migration Service User Guide. TaskData *string `type:"string"` } @@ -13025,89 +15030,361 @@ func (s *ReplicationTaskAssessmentResult) SetS3ObjectUrl(v string) *ReplicationT return s } -// In response to a request by the DescribeReplicationTasks operation, this -// object provides a collection of statistics about a replication task. -type ReplicationTaskStats struct { +// Provides information that describes a premigration assessment run that you +// have started using the StartReplicationTaskAssessmentRun operation. +// +// Some of the information appears based on other operations that can return +// the ReplicationTaskAssessmentRun object. +type ReplicationTaskAssessmentRun struct { _ struct{} `type:"structure"` - // The elapsed time of the task, in milliseconds. - ElapsedTimeMillis *int64 `type:"long"` + // Indication of the completion progress for the individual assessments specified + // to run. + AssessmentProgress *ReplicationTaskAssessmentRunProgress `type:"structure"` - // The date the replication task was started either with a fresh start or a - // target reload. - FreshStartDate *time.Time `type:"timestamp"` + // Unique name of the assessment run. + AssessmentRunName *string `type:"string"` - // The date the replication task full load was completed. - FullLoadFinishDate *time.Time `type:"timestamp"` + // Last message generated by an individual assessment failure. + LastFailureMessage *string `type:"string"` - // The percent complete for the full load migration task. - FullLoadProgressPercent *int64 `type:"integer"` + // ARN of the migration task associated with this premigration assessment run. + ReplicationTaskArn *string `type:"string"` - // The date the replication task full load was started. - FullLoadStartDate *time.Time `type:"timestamp"` + // Amazon Resource Name (ARN) of this assessment run. + ReplicationTaskAssessmentRunArn *string `type:"string"` - // The date the replication task was started either with a fresh start or a - // resume. For more information, see StartReplicationTaskType (https://docs.aws.amazon.com/dms/latest/APIReference/API_StartReplicationTask.html#DMS-StartReplicationTask-request-StartReplicationTaskType). - StartDate *time.Time `type:"timestamp"` + // Date on which the assessment run was created using the StartReplicationTaskAssessmentRun + // operation. + ReplicationTaskAssessmentRunCreationDate *time.Time `type:"timestamp"` - // The date the replication task was stopped. - StopDate *time.Time `type:"timestamp"` + // Encryption mode used to encrypt the assessment run results. + ResultEncryptionMode *string `type:"string"` - // The number of errors that have occurred during this task. - TablesErrored *int64 `type:"integer"` + // ARN of the AWS KMS encryption key used to encrypt the assessment run results. + ResultKmsKeyArn *string `type:"string"` - // The number of tables loaded for this task. - TablesLoaded *int64 `type:"integer"` + // Amazon S3 bucket where AWS DMS stores the results of this assessment run. + ResultLocationBucket *string `type:"string"` - // The number of tables currently loading for this task. - TablesLoading *int64 `type:"integer"` + // Folder in an Amazon S3 bucket where AWS DMS stores the results of this assessment + // run. + ResultLocationFolder *string `type:"string"` - // The number of tables queued for this task. - TablesQueued *int64 `type:"integer"` + // ARN of the service role used to start the assessment run using the StartReplicationTaskAssessmentRun + // operation. + ServiceAccessRoleArn *string `type:"string"` + + // Assessment run status. + // + // This status can have one of the following values: + // + // * "cancelling" – The assessment run was canceled by the CancelReplicationTaskAssessmentRun + // operation. + // + // * "deleting" – The assessment run was deleted by the DeleteReplicationTaskAssessmentRun + // operation. + // + // * "failed" – At least one individual assessment completed with a failed + // status. + // + // * "error-provisioning" – An internal error occurred while resources + // were provisioned (during provisioning status). + // + // * "error-executing" – An internal error occurred while individual assessments + // ran (during running status). + // + // * "invalid state" – The assessment run is in an unknown state. + // + // * "passed" – All individual assessments have completed, and none has + // a failed status. + // + // * "provisioning" – Resources required to run individual assessments + // are being provisioned. + // + // * "running" – Individual assessments are being run. + // + // * "starting" – The assessment run is starting, but resources are not + // yet being provisioned for individual assessments. + Status *string `type:"string"` } // String returns the string representation -func (s ReplicationTaskStats) String() string { +func (s ReplicationTaskAssessmentRun) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ReplicationTaskStats) GoString() string { +func (s ReplicationTaskAssessmentRun) GoString() string { return s.String() } -// SetElapsedTimeMillis sets the ElapsedTimeMillis field's value. -func (s *ReplicationTaskStats) SetElapsedTimeMillis(v int64) *ReplicationTaskStats { - s.ElapsedTimeMillis = &v +// SetAssessmentProgress sets the AssessmentProgress field's value. +func (s *ReplicationTaskAssessmentRun) SetAssessmentProgress(v *ReplicationTaskAssessmentRunProgress) *ReplicationTaskAssessmentRun { + s.AssessmentProgress = v return s } -// SetFreshStartDate sets the FreshStartDate field's value. -func (s *ReplicationTaskStats) SetFreshStartDate(v time.Time) *ReplicationTaskStats { - s.FreshStartDate = &v +// SetAssessmentRunName sets the AssessmentRunName field's value. +func (s *ReplicationTaskAssessmentRun) SetAssessmentRunName(v string) *ReplicationTaskAssessmentRun { + s.AssessmentRunName = &v return s } -// SetFullLoadFinishDate sets the FullLoadFinishDate field's value. -func (s *ReplicationTaskStats) SetFullLoadFinishDate(v time.Time) *ReplicationTaskStats { - s.FullLoadFinishDate = &v +// SetLastFailureMessage sets the LastFailureMessage field's value. +func (s *ReplicationTaskAssessmentRun) SetLastFailureMessage(v string) *ReplicationTaskAssessmentRun { + s.LastFailureMessage = &v return s } -// SetFullLoadProgressPercent sets the FullLoadProgressPercent field's value. -func (s *ReplicationTaskStats) SetFullLoadProgressPercent(v int64) *ReplicationTaskStats { - s.FullLoadProgressPercent = &v +// SetReplicationTaskArn sets the ReplicationTaskArn field's value. +func (s *ReplicationTaskAssessmentRun) SetReplicationTaskArn(v string) *ReplicationTaskAssessmentRun { + s.ReplicationTaskArn = &v return s } -// SetFullLoadStartDate sets the FullLoadStartDate field's value. -func (s *ReplicationTaskStats) SetFullLoadStartDate(v time.Time) *ReplicationTaskStats { - s.FullLoadStartDate = &v +// SetReplicationTaskAssessmentRunArn sets the ReplicationTaskAssessmentRunArn field's value. +func (s *ReplicationTaskAssessmentRun) SetReplicationTaskAssessmentRunArn(v string) *ReplicationTaskAssessmentRun { + s.ReplicationTaskAssessmentRunArn = &v return s } -// SetStartDate sets the StartDate field's value. -func (s *ReplicationTaskStats) SetStartDate(v time.Time) *ReplicationTaskStats { +// SetReplicationTaskAssessmentRunCreationDate sets the ReplicationTaskAssessmentRunCreationDate field's value. +func (s *ReplicationTaskAssessmentRun) SetReplicationTaskAssessmentRunCreationDate(v time.Time) *ReplicationTaskAssessmentRun { + s.ReplicationTaskAssessmentRunCreationDate = &v + return s +} + +// SetResultEncryptionMode sets the ResultEncryptionMode field's value. +func (s *ReplicationTaskAssessmentRun) SetResultEncryptionMode(v string) *ReplicationTaskAssessmentRun { + s.ResultEncryptionMode = &v + return s +} + +// SetResultKmsKeyArn sets the ResultKmsKeyArn field's value. +func (s *ReplicationTaskAssessmentRun) SetResultKmsKeyArn(v string) *ReplicationTaskAssessmentRun { + s.ResultKmsKeyArn = &v + return s +} + +// SetResultLocationBucket sets the ResultLocationBucket field's value. +func (s *ReplicationTaskAssessmentRun) SetResultLocationBucket(v string) *ReplicationTaskAssessmentRun { + s.ResultLocationBucket = &v + return s +} + +// SetResultLocationFolder sets the ResultLocationFolder field's value. +func (s *ReplicationTaskAssessmentRun) SetResultLocationFolder(v string) *ReplicationTaskAssessmentRun { + s.ResultLocationFolder = &v + return s +} + +// SetServiceAccessRoleArn sets the ServiceAccessRoleArn field's value. +func (s *ReplicationTaskAssessmentRun) SetServiceAccessRoleArn(v string) *ReplicationTaskAssessmentRun { + s.ServiceAccessRoleArn = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *ReplicationTaskAssessmentRun) SetStatus(v string) *ReplicationTaskAssessmentRun { + s.Status = &v + return s +} + +// The progress values reported by the AssessmentProgress response element. +type ReplicationTaskAssessmentRunProgress struct { + _ struct{} `type:"structure"` + + // The number of individual assessments that have completed, successfully or + // not. + IndividualAssessmentCompletedCount *int64 `type:"integer"` + + // The number of individual assessments that are specified to run. + IndividualAssessmentCount *int64 `type:"integer"` +} + +// String returns the string representation +func (s ReplicationTaskAssessmentRunProgress) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ReplicationTaskAssessmentRunProgress) GoString() string { + return s.String() +} + +// SetIndividualAssessmentCompletedCount sets the IndividualAssessmentCompletedCount field's value. +func (s *ReplicationTaskAssessmentRunProgress) SetIndividualAssessmentCompletedCount(v int64) *ReplicationTaskAssessmentRunProgress { + s.IndividualAssessmentCompletedCount = &v + return s +} + +// SetIndividualAssessmentCount sets the IndividualAssessmentCount field's value. +func (s *ReplicationTaskAssessmentRunProgress) SetIndividualAssessmentCount(v int64) *ReplicationTaskAssessmentRunProgress { + s.IndividualAssessmentCount = &v + return s +} + +// Provides information that describes an individual assessment from a premigration +// assessment run. +type ReplicationTaskIndividualAssessment struct { + _ struct{} `type:"structure"` + + // Name of this individual assessment. + IndividualAssessmentName *string `type:"string"` + + // ARN of the premigration assessment run that is created to run this individual + // assessment. + ReplicationTaskAssessmentRunArn *string `type:"string"` + + // Amazon Resource Name (ARN) of this individual assessment. + ReplicationTaskIndividualAssessmentArn *string `type:"string"` + + // Date when this individual assessment was started as part of running the StartReplicationTaskAssessmentRun + // operation. + ReplicationTaskIndividualAssessmentStartDate *time.Time `type:"timestamp"` + + // Individual assessment status. + // + // This status can have one of the following values: + // + // * "cancelled" + // + // * "error" + // + // * "failed" + // + // * "passed" + // + // * "pending" + // + // * "running" + Status *string `type:"string"` +} + +// String returns the string representation +func (s ReplicationTaskIndividualAssessment) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ReplicationTaskIndividualAssessment) GoString() string { + return s.String() +} + +// SetIndividualAssessmentName sets the IndividualAssessmentName field's value. +func (s *ReplicationTaskIndividualAssessment) SetIndividualAssessmentName(v string) *ReplicationTaskIndividualAssessment { + s.IndividualAssessmentName = &v + return s +} + +// SetReplicationTaskAssessmentRunArn sets the ReplicationTaskAssessmentRunArn field's value. +func (s *ReplicationTaskIndividualAssessment) SetReplicationTaskAssessmentRunArn(v string) *ReplicationTaskIndividualAssessment { + s.ReplicationTaskAssessmentRunArn = &v + return s +} + +// SetReplicationTaskIndividualAssessmentArn sets the ReplicationTaskIndividualAssessmentArn field's value. +func (s *ReplicationTaskIndividualAssessment) SetReplicationTaskIndividualAssessmentArn(v string) *ReplicationTaskIndividualAssessment { + s.ReplicationTaskIndividualAssessmentArn = &v + return s +} + +// SetReplicationTaskIndividualAssessmentStartDate sets the ReplicationTaskIndividualAssessmentStartDate field's value. +func (s *ReplicationTaskIndividualAssessment) SetReplicationTaskIndividualAssessmentStartDate(v time.Time) *ReplicationTaskIndividualAssessment { + s.ReplicationTaskIndividualAssessmentStartDate = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *ReplicationTaskIndividualAssessment) SetStatus(v string) *ReplicationTaskIndividualAssessment { + s.Status = &v + return s +} + +// In response to a request by the DescribeReplicationTasks operation, this +// object provides a collection of statistics about a replication task. +type ReplicationTaskStats struct { + _ struct{} `type:"structure"` + + // The elapsed time of the task, in milliseconds. + ElapsedTimeMillis *int64 `type:"long"` + + // The date the replication task was started either with a fresh start or a + // target reload. + FreshStartDate *time.Time `type:"timestamp"` + + // The date the replication task full load was completed. + FullLoadFinishDate *time.Time `type:"timestamp"` + + // The percent complete for the full load migration task. + FullLoadProgressPercent *int64 `type:"integer"` + + // The date the replication task full load was started. + FullLoadStartDate *time.Time `type:"timestamp"` + + // The date the replication task was started either with a fresh start or a + // resume. For more information, see StartReplicationTaskType (https://docs.aws.amazon.com/dms/latest/APIReference/API_StartReplicationTask.html#DMS-StartReplicationTask-request-StartReplicationTaskType). + StartDate *time.Time `type:"timestamp"` + + // The date the replication task was stopped. + StopDate *time.Time `type:"timestamp"` + + // The number of errors that have occurred during this task. + TablesErrored *int64 `type:"integer"` + + // The number of tables loaded for this task. + TablesLoaded *int64 `type:"integer"` + + // The number of tables currently loading for this task. + TablesLoading *int64 `type:"integer"` + + // The number of tables queued for this task. + TablesQueued *int64 `type:"integer"` +} + +// String returns the string representation +func (s ReplicationTaskStats) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ReplicationTaskStats) GoString() string { + return s.String() +} + +// SetElapsedTimeMillis sets the ElapsedTimeMillis field's value. +func (s *ReplicationTaskStats) SetElapsedTimeMillis(v int64) *ReplicationTaskStats { + s.ElapsedTimeMillis = &v + return s +} + +// SetFreshStartDate sets the FreshStartDate field's value. +func (s *ReplicationTaskStats) SetFreshStartDate(v time.Time) *ReplicationTaskStats { + s.FreshStartDate = &v + return s +} + +// SetFullLoadFinishDate sets the FullLoadFinishDate field's value. +func (s *ReplicationTaskStats) SetFullLoadFinishDate(v time.Time) *ReplicationTaskStats { + s.FullLoadFinishDate = &v + return s +} + +// SetFullLoadProgressPercent sets the FullLoadProgressPercent field's value. +func (s *ReplicationTaskStats) SetFullLoadProgressPercent(v int64) *ReplicationTaskStats { + s.FullLoadProgressPercent = &v + return s +} + +// SetFullLoadStartDate sets the FullLoadStartDate field's value. +func (s *ReplicationTaskStats) SetFullLoadStartDate(v time.Time) *ReplicationTaskStats { + s.FullLoadStartDate = &v + return s +} + +// SetStartDate sets the StartDate field's value. +func (s *ReplicationTaskStats) SetStartDate(v time.Time) *ReplicationTaskStats { s.StartDate = &v return s } @@ -13348,6 +15625,118 @@ func (s *ResourceQuotaExceededFault) RequestID() string { return s.RespMetadata.RequestID } +// Insufficient privileges are preventing access to an Amazon S3 object. +type S3AccessDeniedFault struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s S3AccessDeniedFault) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s S3AccessDeniedFault) GoString() string { + return s.String() +} + +func newErrorS3AccessDeniedFault(v protocol.ResponseMetadata) error { + return &S3AccessDeniedFault{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *S3AccessDeniedFault) Code() string { + return "S3AccessDeniedFault" +} + +// Message returns the exception's message. +func (s *S3AccessDeniedFault) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *S3AccessDeniedFault) OrigErr() error { + return nil +} + +func (s *S3AccessDeniedFault) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *S3AccessDeniedFault) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *S3AccessDeniedFault) RequestID() string { + return s.RespMetadata.RequestID +} + +// A specified Amazon S3 bucket, bucket folder, or other object can't be found. +type S3ResourceNotFoundFault struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s S3ResourceNotFoundFault) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s S3ResourceNotFoundFault) GoString() string { + return s.String() +} + +func newErrorS3ResourceNotFoundFault(v protocol.ResponseMetadata) error { + return &S3ResourceNotFoundFault{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *S3ResourceNotFoundFault) Code() string { + return "S3ResourceNotFoundFault" +} + +// Message returns the exception's message. +func (s *S3ResourceNotFoundFault) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *S3ResourceNotFoundFault) OrigErr() error { + return nil +} + +func (s *S3ResourceNotFoundFault) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *S3ResourceNotFoundFault) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *S3ResourceNotFoundFault) RequestID() string { + return s.RespMetadata.RequestID +} + // Settings for exporting data to Amazon S3. type S3Settings struct { _ struct{} `type:"structure"` @@ -13895,6 +16284,187 @@ func (s *StartReplicationTaskAssessmentOutput) SetReplicationTask(v *Replication return s } +type StartReplicationTaskAssessmentRunInput struct { + _ struct{} `type:"structure"` + + // Unique name to identify the assessment run. + // + // AssessmentRunName is a required field + AssessmentRunName *string `type:"string" required:"true"` + + // Space-separated list of names for specific individual assessments that you + // want to exclude. These names come from the default list of individual assessments + // that AWS DMS supports for the associated migration task. This task is specified + // by ReplicationTaskArn. + // + // You can't set a value for Exclude if you also set a value for IncludeOnly + // in the API operation. + // + // To identify the names of the default individual assessments that AWS DMS + // supports for the associated migration task, run the DescribeApplicableIndividualAssessments + // operation using its own ReplicationTaskArn request parameter. + Exclude []*string `type:"list"` + + // Space-separated list of names for specific individual assessments that you + // want to include. These names come from the default list of individual assessments + // that AWS DMS supports for the associated migration task. This task is specified + // by ReplicationTaskArn. + // + // You can't set a value for IncludeOnly if you also set a value for Exclude + // in the API operation. + // + // To identify the names of the default individual assessments that AWS DMS + // supports for the associated migration task, run the DescribeApplicableIndividualAssessments + // operation using its own ReplicationTaskArn request parameter. + IncludeOnly []*string `type:"list"` + + // Amazon Resource Name (ARN) of the migration task associated with the premigration + // assessment run that you want to start. + // + // ReplicationTaskArn is a required field + ReplicationTaskArn *string `type:"string" required:"true"` + + // Encryption mode that you can specify to encrypt the results of this assessment + // run. If you don't specify this request parameter, AWS DMS stores the assessment + // run results without encryption. You can specify one of the options following: + // + // * "SSE_S3" – The server-side encryption provided as a default by Amazon + // S3. + // + // * "SSE_KMS" – AWS Key Management Service (AWS KMS) encryption. This + // encryption can use either a custom KMS encryption key that you specify + // or the default KMS encryption key that DMS provides. + ResultEncryptionMode *string `type:"string"` + + // ARN of a custom KMS encryption key that you specify when you set ResultEncryptionMode + // to "SSE_KMS". + ResultKmsKeyArn *string `type:"string"` + + // Amazon S3 bucket where you want AWS DMS to store the results of this assessment + // run. + // + // ResultLocationBucket is a required field + ResultLocationBucket *string `type:"string" required:"true"` + + // Folder within an Amazon S3 bucket where you want AWS DMS to store the results + // of this assessment run. + ResultLocationFolder *string `type:"string"` + + // ARN of a service role needed to start the assessment run. + // + // ServiceAccessRoleArn is a required field + ServiceAccessRoleArn *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s StartReplicationTaskAssessmentRunInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StartReplicationTaskAssessmentRunInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StartReplicationTaskAssessmentRunInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StartReplicationTaskAssessmentRunInput"} + if s.AssessmentRunName == nil { + invalidParams.Add(request.NewErrParamRequired("AssessmentRunName")) + } + if s.ReplicationTaskArn == nil { + invalidParams.Add(request.NewErrParamRequired("ReplicationTaskArn")) + } + if s.ResultLocationBucket == nil { + invalidParams.Add(request.NewErrParamRequired("ResultLocationBucket")) + } + if s.ServiceAccessRoleArn == nil { + invalidParams.Add(request.NewErrParamRequired("ServiceAccessRoleArn")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAssessmentRunName sets the AssessmentRunName field's value. +func (s *StartReplicationTaskAssessmentRunInput) SetAssessmentRunName(v string) *StartReplicationTaskAssessmentRunInput { + s.AssessmentRunName = &v + return s +} + +// SetExclude sets the Exclude field's value. +func (s *StartReplicationTaskAssessmentRunInput) SetExclude(v []*string) *StartReplicationTaskAssessmentRunInput { + s.Exclude = v + return s +} + +// SetIncludeOnly sets the IncludeOnly field's value. +func (s *StartReplicationTaskAssessmentRunInput) SetIncludeOnly(v []*string) *StartReplicationTaskAssessmentRunInput { + s.IncludeOnly = v + return s +} + +// SetReplicationTaskArn sets the ReplicationTaskArn field's value. +func (s *StartReplicationTaskAssessmentRunInput) SetReplicationTaskArn(v string) *StartReplicationTaskAssessmentRunInput { + s.ReplicationTaskArn = &v + return s +} + +// SetResultEncryptionMode sets the ResultEncryptionMode field's value. +func (s *StartReplicationTaskAssessmentRunInput) SetResultEncryptionMode(v string) *StartReplicationTaskAssessmentRunInput { + s.ResultEncryptionMode = &v + return s +} + +// SetResultKmsKeyArn sets the ResultKmsKeyArn field's value. +func (s *StartReplicationTaskAssessmentRunInput) SetResultKmsKeyArn(v string) *StartReplicationTaskAssessmentRunInput { + s.ResultKmsKeyArn = &v + return s +} + +// SetResultLocationBucket sets the ResultLocationBucket field's value. +func (s *StartReplicationTaskAssessmentRunInput) SetResultLocationBucket(v string) *StartReplicationTaskAssessmentRunInput { + s.ResultLocationBucket = &v + return s +} + +// SetResultLocationFolder sets the ResultLocationFolder field's value. +func (s *StartReplicationTaskAssessmentRunInput) SetResultLocationFolder(v string) *StartReplicationTaskAssessmentRunInput { + s.ResultLocationFolder = &v + return s +} + +// SetServiceAccessRoleArn sets the ServiceAccessRoleArn field's value. +func (s *StartReplicationTaskAssessmentRunInput) SetServiceAccessRoleArn(v string) *StartReplicationTaskAssessmentRunInput { + s.ServiceAccessRoleArn = &v + return s +} + +type StartReplicationTaskAssessmentRunOutput struct { + _ struct{} `type:"structure"` + + // The premigration assessment run that was started. + ReplicationTaskAssessmentRun *ReplicationTaskAssessmentRun `type:"structure"` +} + +// String returns the string representation +func (s StartReplicationTaskAssessmentRunOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StartReplicationTaskAssessmentRunOutput) GoString() string { + return s.String() +} + +// SetReplicationTaskAssessmentRun sets the ReplicationTaskAssessmentRun field's value. +func (s *StartReplicationTaskAssessmentRunOutput) SetReplicationTaskAssessmentRun(v *ReplicationTaskAssessmentRun) *StartReplicationTaskAssessmentRunOutput { + s.ReplicationTaskAssessmentRun = v + return s +} + type StartReplicationTaskInput struct { _ struct{} `type:"structure"` @@ -14257,7 +16827,7 @@ type SupportedEndpointType struct { // The database engine name. Valid values, depending on the EndpointType, include // "mysql", "oracle", "postgres", "mariadb", "aurora", "aurora-postgresql", // "redshift", "s3", "db2", "azuredb", "sybase", "dynamodb", "mongodb", "kinesis", - // "kafka", "elasticsearch", "documentdb", and "sqlserver". + // "kafka", "elasticsearch", "documentdb", "sqlserver", and "neptune". EngineName *string `type:"string"` // The earliest AWS DMS engine version that supports this endpoint engine. Note @@ -14309,6 +16879,66 @@ func (s *SupportedEndpointType) SetSupportsCDC(v bool) *SupportedEndpointType { return s } +// Provides information that defines a SAP ASE endpoint. +type SybaseSettings struct { + _ struct{} `type:"structure"` + + // Database name for the endpoint. + DatabaseName *string `type:"string"` + + // Endpoint connection password. + Password *string `type:"string" sensitive:"true"` + + // Endpoint TCP port. + Port *int64 `type:"integer"` + + // Fully qualified domain name of the endpoint. + ServerName *string `type:"string"` + + // Endpoint connection user name. + Username *string `type:"string"` +} + +// String returns the string representation +func (s SybaseSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SybaseSettings) GoString() string { + return s.String() +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *SybaseSettings) SetDatabaseName(v string) *SybaseSettings { + s.DatabaseName = &v + return s +} + +// SetPassword sets the Password field's value. +func (s *SybaseSettings) SetPassword(v string) *SybaseSettings { + s.Password = &v + return s +} + +// SetPort sets the Port field's value. +func (s *SybaseSettings) SetPort(v int64) *SybaseSettings { + s.Port = &v + return s +} + +// SetServerName sets the ServerName field's value. +func (s *SybaseSettings) SetServerName(v string) *SybaseSettings { + s.ServerName = &v + return s +} + +// SetUsername sets the Username field's value. +func (s *SybaseSettings) SetUsername(v string) *SybaseSettings { + s.Username = &v + return s +} + // Provides a collection of table statistics in response to a request by the // DescribeTableStatistics operation. type TableStatistics struct { @@ -14532,10 +17162,14 @@ type TableToReload struct { _ struct{} `type:"structure"` // The schema name of the table to be reloaded. - SchemaName *string `type:"string"` + // + // SchemaName is a required field + SchemaName *string `type:"string" required:"true"` // The table name of the table to be reloaded. - TableName *string `type:"string"` + // + // TableName is a required field + TableName *string `type:"string" required:"true"` } // String returns the string representation @@ -14548,6 +17182,22 @@ func (s TableToReload) GoString() string { return s.String() } +// Validate inspects the fields of the type to determine if they are valid. +func (s *TableToReload) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TableToReload"} + if s.SchemaName == nil { + invalidParams.Add(request.NewErrParamRequired("SchemaName")) + } + if s.TableName == nil { + invalidParams.Add(request.NewErrParamRequired("TableName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + // SetSchemaName sets the SchemaName field's value. func (s *TableToReload) SetSchemaName(v string) *TableToReload { s.SchemaName = &v @@ -14571,16 +17221,16 @@ func (s *TableToReload) SetTableName(v string) *TableToReload { type Tag struct { _ struct{} `type:"structure"` - // A key is the required name of the tag. The string value can be from 1 to - // 128 Unicode characters in length and can't be prefixed with "aws:" or "dms:". - // The string can only contain only the set of Unicode letters, digits, white-space, - // '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$"). + // A key is the required name of the tag. The string value can be 1-128 Unicode + // characters in length and can't be prefixed with "aws:" or "dms:". The string + // can only contain only the set of Unicode letters, digits, white-space, '_', + // '.', '/', '=', '+', '-' (Java regular expressions: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$"). Key *string `type:"string"` - // A value is the optional value of the tag. The string value can be from 1 - // to 256 Unicode characters in length and can't be prefixed with "aws:" or - // "dms:". The string can only contain only the set of Unicode letters, digits, - // white-space, '_', '.', '/', '=', '+', '-' (Java regex: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$"). + // A value is the optional value of the tag. The string value can be 1-256 Unicode + // characters in length and can't be prefixed with "aws:" or "dms:". The string + // can only contain only the set of Unicode letters, digits, white-space, '_', + // '.', '/', '=', '+', '-' (Java regular expressions: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$"). Value *string `type:"string"` } @@ -14737,15 +17387,15 @@ func (s *UpgradeDependencyFailureFault) RequestID() string { return s.RespMetadata.RequestID } -// Describes status of a security group associated with the virtual private -// cloud hosting your replication and DB instances. +// Describes the status of a security group associated with the virtual private +// cloud (VPC) hosting your replication and DB instances. type VpcSecurityGroupMembership struct { _ struct{} `type:"structure"` // The status of the VPC security group. Status *string `type:"string"` - // The VPC security group Id. + // The VPC security group ID. VpcSecurityGroupId *string `type:"string"` } @@ -14782,6 +17432,15 @@ const ( AuthMechanismValueScramSha1 = "scram_sha_1" ) +// AuthMechanismValue_Values returns all elements of the AuthMechanismValue enum +func AuthMechanismValue_Values() []string { + return []string{ + AuthMechanismValueDefault, + AuthMechanismValueMongodbCr, + AuthMechanismValueScramSha1, + } +} + const ( // AuthTypeValueNo is a AuthTypeValue enum value AuthTypeValueNo = "no" @@ -14790,6 +17449,14 @@ const ( AuthTypeValuePassword = "password" ) +// AuthTypeValue_Values returns all elements of the AuthTypeValue enum +func AuthTypeValue_Values() []string { + return []string{ + AuthTypeValueNo, + AuthTypeValuePassword, + } +} + const ( // CompressionTypeValueNone is a CompressionTypeValue enum value CompressionTypeValueNone = "none" @@ -14798,6 +17465,14 @@ const ( CompressionTypeValueGzip = "gzip" ) +// CompressionTypeValue_Values returns all elements of the CompressionTypeValue enum +func CompressionTypeValue_Values() []string { + return []string{ + CompressionTypeValueNone, + CompressionTypeValueGzip, + } +} + const ( // DataFormatValueCsv is a DataFormatValue enum value DataFormatValueCsv = "csv" @@ -14806,6 +17481,14 @@ const ( DataFormatValueParquet = "parquet" ) +// DataFormatValue_Values returns all elements of the DataFormatValue enum +func DataFormatValue_Values() []string { + return []string{ + DataFormatValueCsv, + DataFormatValueParquet, + } +} + const ( // DmsSslModeValueNone is a DmsSslModeValue enum value DmsSslModeValueNone = "none" @@ -14820,6 +17503,16 @@ const ( DmsSslModeValueVerifyFull = "verify-full" ) +// DmsSslModeValue_Values returns all elements of the DmsSslModeValue enum +func DmsSslModeValue_Values() []string { + return []string{ + DmsSslModeValueNone, + DmsSslModeValueRequire, + DmsSslModeValueVerifyCa, + DmsSslModeValueVerifyFull, + } +} + const ( // EncodingTypeValuePlain is a EncodingTypeValue enum value EncodingTypeValuePlain = "plain" @@ -14831,6 +17524,15 @@ const ( EncodingTypeValueRleDictionary = "rle-dictionary" ) +// EncodingTypeValue_Values returns all elements of the EncodingTypeValue enum +func EncodingTypeValue_Values() []string { + return []string{ + EncodingTypeValuePlain, + EncodingTypeValuePlainDictionary, + EncodingTypeValueRleDictionary, + } +} + const ( // EncryptionModeValueSseS3 is a EncryptionModeValue enum value EncryptionModeValueSseS3 = "sse-s3" @@ -14839,6 +17541,14 @@ const ( EncryptionModeValueSseKms = "sse-kms" ) +// EncryptionModeValue_Values returns all elements of the EncryptionModeValue enum +func EncryptionModeValue_Values() []string { + return []string{ + EncryptionModeValueSseS3, + EncryptionModeValueSseKms, + } +} + const ( // MessageFormatValueJson is a MessageFormatValue enum value MessageFormatValueJson = "json" @@ -14847,6 +17557,14 @@ const ( MessageFormatValueJsonUnformatted = "json-unformatted" ) +// MessageFormatValue_Values returns all elements of the MessageFormatValue enum +func MessageFormatValue_Values() []string { + return []string{ + MessageFormatValueJson, + MessageFormatValueJsonUnformatted, + } +} + const ( // MigrationTypeValueFullLoad is a MigrationTypeValue enum value MigrationTypeValueFullLoad = "full-load" @@ -14858,6 +17576,15 @@ const ( MigrationTypeValueFullLoadAndCdc = "full-load-and-cdc" ) +// MigrationTypeValue_Values returns all elements of the MigrationTypeValue enum +func MigrationTypeValue_Values() []string { + return []string{ + MigrationTypeValueFullLoad, + MigrationTypeValueCdc, + MigrationTypeValueFullLoadAndCdc, + } +} + const ( // NestingLevelValueNone is a NestingLevelValue enum value NestingLevelValueNone = "none" @@ -14866,6 +17593,14 @@ const ( NestingLevelValueOne = "one" ) +// NestingLevelValue_Values returns all elements of the NestingLevelValue enum +func NestingLevelValue_Values() []string { + return []string{ + NestingLevelValueNone, + NestingLevelValueOne, + } +} + const ( // ParquetVersionValueParquet10 is a ParquetVersionValue enum value ParquetVersionValueParquet10 = "parquet-1-0" @@ -14874,6 +17609,14 @@ const ( ParquetVersionValueParquet20 = "parquet-2-0" ) +// ParquetVersionValue_Values returns all elements of the ParquetVersionValue enum +func ParquetVersionValue_Values() []string { + return []string{ + ParquetVersionValueParquet10, + ParquetVersionValueParquet20, + } +} + const ( // RefreshSchemasStatusTypeValueSuccessful is a RefreshSchemasStatusTypeValue enum value RefreshSchemasStatusTypeValueSuccessful = "successful" @@ -14885,11 +17628,27 @@ const ( RefreshSchemasStatusTypeValueRefreshing = "refreshing" ) +// RefreshSchemasStatusTypeValue_Values returns all elements of the RefreshSchemasStatusTypeValue enum +func RefreshSchemasStatusTypeValue_Values() []string { + return []string{ + RefreshSchemasStatusTypeValueSuccessful, + RefreshSchemasStatusTypeValueFailed, + RefreshSchemasStatusTypeValueRefreshing, + } +} + const ( // ReleaseStatusValuesBeta is a ReleaseStatusValues enum value ReleaseStatusValuesBeta = "beta" ) +// ReleaseStatusValues_Values returns all elements of the ReleaseStatusValues enum +func ReleaseStatusValues_Values() []string { + return []string{ + ReleaseStatusValuesBeta, + } +} + const ( // ReloadOptionValueDataReload is a ReloadOptionValue enum value ReloadOptionValueDataReload = "data-reload" @@ -14898,6 +17657,14 @@ const ( ReloadOptionValueValidateOnly = "validate-only" ) +// ReloadOptionValue_Values returns all elements of the ReloadOptionValue enum +func ReloadOptionValue_Values() []string { + return []string{ + ReloadOptionValueDataReload, + ReloadOptionValueValidateOnly, + } +} + const ( // ReplicationEndpointTypeValueSource is a ReplicationEndpointTypeValue enum value ReplicationEndpointTypeValueSource = "source" @@ -14906,11 +17673,26 @@ const ( ReplicationEndpointTypeValueTarget = "target" ) +// ReplicationEndpointTypeValue_Values returns all elements of the ReplicationEndpointTypeValue enum +func ReplicationEndpointTypeValue_Values() []string { + return []string{ + ReplicationEndpointTypeValueSource, + ReplicationEndpointTypeValueTarget, + } +} + const ( // SourceTypeReplicationInstance is a SourceType enum value SourceTypeReplicationInstance = "replication-instance" ) +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeReplicationInstance, + } +} + const ( // StartReplicationTaskTypeValueStartReplication is a StartReplicationTaskTypeValue enum value StartReplicationTaskTypeValueStartReplication = "start-replication" @@ -14921,3 +17703,12 @@ const ( // StartReplicationTaskTypeValueReloadTarget is a StartReplicationTaskTypeValue enum value StartReplicationTaskTypeValueReloadTarget = "reload-target" ) + +// StartReplicationTaskTypeValue_Values returns all elements of the StartReplicationTaskTypeValue enum +func StartReplicationTaskTypeValue_Values() []string { + return []string{ + StartReplicationTaskTypeValueStartReplication, + StartReplicationTaskTypeValueResumeProcessing, + StartReplicationTaskTypeValueReloadTarget, + } +} 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 e2e32caf6f0..b02044ee188 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 @@ -53,6 +53,13 @@ const ( // The specified master key (CMK) isn't enabled. ErrCodeKMSDisabledFault = "KMSDisabledFault" + // ErrCodeKMSFault for service response error code + // "KMSFault". + // + // An AWS Key Management Service (AWS KMS) error is preventing access to AWS + // KMS. + ErrCodeKMSFault = "KMSFault" + // ErrCodeKMSInvalidStateFault for service response error code // "KMSInvalidStateFault". // @@ -102,6 +109,18 @@ const ( // The quota for this resource quota has been exceeded. ErrCodeResourceQuotaExceededFault = "ResourceQuotaExceededFault" + // ErrCodeS3AccessDeniedFault for service response error code + // "S3AccessDeniedFault". + // + // Insufficient privileges are preventing access to an Amazon S3 object. + ErrCodeS3AccessDeniedFault = "S3AccessDeniedFault" + + // ErrCodeS3ResourceNotFoundFault for service response error code + // "S3ResourceNotFoundFault". + // + // A specified Amazon S3 bucket, bucket folder, or other object can't be found. + ErrCodeS3ResourceNotFoundFault = "S3ResourceNotFoundFault" + // ErrCodeSNSInvalidTopicFault for service response error code // "SNSInvalidTopicFault". // @@ -141,6 +160,7 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "InvalidSubnet": newErrorInvalidSubnet, "KMSAccessDeniedFault": newErrorKMSAccessDeniedFault, "KMSDisabledFault": newErrorKMSDisabledFault, + "KMSFault": newErrorKMSFault, "KMSInvalidStateFault": newErrorKMSInvalidStateFault, "KMSKeyNotAccessibleFault": newErrorKMSKeyNotAccessibleFault, "KMSNotFoundFault": newErrorKMSNotFoundFault, @@ -149,6 +169,8 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "ResourceAlreadyExistsFault": newErrorResourceAlreadyExistsFault, "ResourceNotFoundFault": newErrorResourceNotFoundFault, "ResourceQuotaExceededFault": newErrorResourceQuotaExceededFault, + "S3AccessDeniedFault": newErrorS3AccessDeniedFault, + "S3ResourceNotFoundFault": newErrorS3ResourceNotFoundFault, "SNSInvalidTopicFault": newErrorSNSInvalidTopicFault, "SNSNoAuthorizationFault": newErrorSNSNoAuthorizationFault, "StorageQuotaExceededFault": newErrorStorageQuotaExceededFault, diff --git a/vendor/github.com/aws/aws-sdk-go/service/dataexchange/api.go b/vendor/github.com/aws/aws-sdk-go/service/dataexchange/api.go index eefda3be8c5..9eb037715ac 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dataexchange/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dataexchange/api.go @@ -3801,9 +3801,7 @@ type ExportServerSideEncryption struct { // The Amazon Resource Name (ARN) of the the AWS KMS key you want to use to // encrypt the Amazon S3 objects. This parameter is required if you choose aws:kms // as an encryption type. - // - // KmsKeyArn is a required field - KmsKeyArn *string `type:"string" required:"true"` + KmsKeyArn *string `type:"string"` // The type of server side encryption used for encrypting the objects in Amazon // S3. @@ -3825,9 +3823,6 @@ func (s ExportServerSideEncryption) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *ExportServerSideEncryption) Validate() error { invalidParams := request.ErrInvalidParams{Context: "ExportServerSideEncryption"} - if s.KmsKeyArn == nil { - invalidParams.Add(request.NewErrParamRequired("KmsKeyArn")) - } if s.Type == nil { invalidParams.Add(request.NewErrParamRequired("Type")) } @@ -6666,6 +6661,13 @@ const ( AssetTypeS3Snapshot = "S3_SNAPSHOT" ) +// AssetType_Values returns all elements of the AssetType enum +func AssetType_Values() []string { + return []string{ + AssetTypeS3Snapshot, + } +} + const ( // CodeAccessDeniedException is a Code enum value CodeAccessDeniedException = "ACCESS_DENIED_EXCEPTION" @@ -6689,6 +6691,19 @@ const ( CodeMalwareScanEncryptedFile = "MALWARE_SCAN_ENCRYPTED_FILE" ) +// Code_Values returns all elements of the Code enum +func Code_Values() []string { + return []string{ + CodeAccessDeniedException, + CodeInternalServerException, + CodeMalwareDetected, + CodeResourceNotFoundException, + CodeServiceQuotaExceededException, + CodeValidationException, + CodeMalwareScanEncryptedFile, + } +} + // The name of the limit that was reached. const ( // JobErrorLimitNameAssetsperrevision is a JobErrorLimitName enum value @@ -6698,6 +6713,14 @@ const ( JobErrorLimitNameAssetsizeinGb = "Asset size in GB" ) +// JobErrorLimitName_Values returns all elements of the JobErrorLimitName enum +func JobErrorLimitName_Values() []string { + return []string{ + JobErrorLimitNameAssetsperrevision, + JobErrorLimitNameAssetsizeinGb, + } +} + // The types of resource which the job error can apply to. const ( // JobErrorResourceTypesRevision is a JobErrorResourceTypes enum value @@ -6707,6 +6730,14 @@ const ( JobErrorResourceTypesAsset = "ASSET" ) +// JobErrorResourceTypes_Values returns all elements of the JobErrorResourceTypes enum +func JobErrorResourceTypes_Values() []string { + return []string{ + JobErrorResourceTypesRevision, + JobErrorResourceTypesAsset, + } +} + const ( // LimitNameProductsperaccount is a LimitName enum value LimitNameProductsperaccount = "Products per account" @@ -6745,6 +6776,24 @@ const ( LimitNameConcurrentinprogressjobstoexportassetstoasignedUrl = "Concurrent in progress jobs to export assets to a signed URL" ) +// LimitName_Values returns all elements of the LimitName enum +func LimitName_Values() []string { + return []string{ + LimitNameProductsperaccount, + LimitNameDatasetsperaccount, + LimitNameDatasetsperproduct, + LimitNameRevisionsperdataset, + LimitNameAssetsperrevision, + LimitNameAssetsperimportjobfromAmazonS3, + LimitNameAssetperexportjobfromAmazonS3, + LimitNameAssetsizeinGb, + LimitNameConcurrentinprogressjobstoimportassetsfromAmazonS3, + LimitNameConcurrentinprogressjobstoimportassetsfromasignedUrl, + LimitNameConcurrentinprogressjobstoexportassetstoAmazonS3, + LimitNameConcurrentinprogressjobstoexportassetstoasignedUrl, + } +} + // A property that defines the data set as OWNED by the account (for providers) // or ENTITLED to the account (for subscribers). When an owned data set is published // in a product, AWS Data Exchange creates a copy of the data set. Subscribers @@ -6757,6 +6806,14 @@ const ( OriginEntitled = "ENTITLED" ) +// Origin_Values returns all elements of the Origin enum +func Origin_Values() []string { + return []string{ + OriginOwned, + OriginEntitled, + } +} + const ( // ResourceTypeDataSet is a ResourceType enum value ResourceTypeDataSet = "DATA_SET" @@ -6771,6 +6828,16 @@ const ( ResourceTypeJob = "JOB" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeDataSet, + ResourceTypeRevision, + ResourceTypeAsset, + ResourceTypeJob, + } +} + // The types of encryption supported in export jobs to Amazon S3. const ( // ServerSideEncryptionTypesAwsKms is a ServerSideEncryptionTypes enum value @@ -6780,6 +6847,14 @@ const ( ServerSideEncryptionTypesAes256 = "AES256" ) +// ServerSideEncryptionTypes_Values returns all elements of the ServerSideEncryptionTypes enum +func ServerSideEncryptionTypes_Values() []string { + return []string{ + ServerSideEncryptionTypesAwsKms, + ServerSideEncryptionTypesAes256, + } +} + const ( // StateWaiting is a State enum value StateWaiting = "WAITING" @@ -6800,6 +6875,18 @@ const ( StateTimedOut = "TIMED_OUT" ) +// State_Values returns all elements of the State enum +func State_Values() []string { + return []string{ + StateWaiting, + StateInProgress, + StateError, + StateCompleted, + StateCancelled, + StateTimedOut, + } +} + const ( // TypeImportAssetsFromS3 is a Type enum value TypeImportAssetsFromS3 = "IMPORT_ASSETS_FROM_S3" @@ -6813,3 +6900,13 @@ const ( // TypeExportAssetToSignedUrl is a Type enum value TypeExportAssetToSignedUrl = "EXPORT_ASSET_TO_SIGNED_URL" ) + +// Type_Values returns all elements of the Type enum +func Type_Values() []string { + return []string{ + TypeImportAssetsFromS3, + TypeImportAssetFromSignedUrl, + TypeExportAssetsToS3, + TypeExportAssetToSignedUrl, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/datapipeline/api.go b/vendor/github.com/aws/aws-sdk-go/service/datapipeline/api.go index d4067601430..66aef55f79d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/datapipeline/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/datapipeline/api.go @@ -4956,6 +4956,17 @@ const ( OperatorTypeBetween = "BETWEEN" ) +// OperatorType_Values returns all elements of the OperatorType enum +func OperatorType_Values() []string { + return []string{ + OperatorTypeEq, + OperatorTypeRefEq, + OperatorTypeLe, + OperatorTypeGe, + OperatorTypeBetween, + } +} + const ( // TaskStatusFinished is a TaskStatus enum value TaskStatusFinished = "FINISHED" @@ -4966,3 +4977,12 @@ const ( // TaskStatusFalse is a TaskStatus enum value TaskStatusFalse = "FALSE" ) + +// TaskStatus_Values returns all elements of the TaskStatus enum +func TaskStatus_Values() []string { + return []string{ + TaskStatusFinished, + TaskStatusFailed, + TaskStatusFalse, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/datasync/api.go b/vendor/github.com/aws/aws-sdk-go/service/datasync/api.go index 79b332bbf01..0ce90849d06 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/datasync/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/datasync/api.go @@ -60,7 +60,7 @@ func (c *DataSync) CancelTaskExecutionRequest(input *CancelTaskExecutionInput) ( // // Cancels execution of a task. // -// When you cancel a task execution, the transfer of some files are abruptly +// When you cancel a task execution, the transfer of some files is abruptly // interrupted. The contents of files that are transferred to the destination // might be incomplete or inconsistent with the source files. However, if you // start a new task execution on the same task and you allow the task execution @@ -156,7 +156,7 @@ func (c *DataSync) CreateAgentRequest(input *CreateAgentInput) (req *request.Req // target locations (in Amazon S3 or Amazon EFS) reside. Your tasks are created // in this AWS Region. // -// You can activate the agent in a VPC (Virtual private Cloud) or provide the +// You can activate the agent in a VPC (virtual private cloud) or provide the // agent access to a VPC endpoint so you can run tasks without going over the // public Internet. // @@ -413,7 +413,7 @@ func (c *DataSync) CreateLocationNfsRequest(input *CreateLocationNfsInput) (req // CreateLocationNfs API operation for AWS DataSync. // // Defines a file system on a Network File System (NFS) server that can be read -// from or written to +// from or written to. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -451,6 +451,88 @@ func (c *DataSync) CreateLocationNfsWithContext(ctx aws.Context, input *CreateLo return out, req.Send() } +const opCreateLocationObjectStorage = "CreateLocationObjectStorage" + +// CreateLocationObjectStorageRequest generates a "aws/request.Request" representing the +// client's request for the CreateLocationObjectStorage operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateLocationObjectStorage for more information on using the CreateLocationObjectStorage +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateLocationObjectStorageRequest method. +// req, resp := client.CreateLocationObjectStorageRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationObjectStorage +func (c *DataSync) CreateLocationObjectStorageRequest(input *CreateLocationObjectStorageInput) (req *request.Request, output *CreateLocationObjectStorageOutput) { + op := &request.Operation{ + Name: opCreateLocationObjectStorage, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateLocationObjectStorageInput{} + } + + output = &CreateLocationObjectStorageOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateLocationObjectStorage API operation for AWS DataSync. +// +// Creates an endpoint for a self-managed object storage bucket. +// +// Returns awserr.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 DataSync's +// API operation CreateLocationObjectStorage for usage and error information. +// +// Returned Error Types: +// * InvalidRequestException +// This exception is thrown when the client submits a malformed request. +// +// * InternalException +// This exception is thrown when an error occurs in the AWS DataSync service. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/CreateLocationObjectStorage +func (c *DataSync) CreateLocationObjectStorage(input *CreateLocationObjectStorageInput) (*CreateLocationObjectStorageOutput, error) { + req, out := c.CreateLocationObjectStorageRequest(input) + return out, req.Send() +} + +// CreateLocationObjectStorageWithContext is the same as CreateLocationObjectStorage with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLocationObjectStorage for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DataSync) CreateLocationObjectStorageWithContext(ctx aws.Context, input *CreateLocationObjectStorageInput, opts ...request.Option) (*CreateLocationObjectStorageOutput, error) { + req, out := c.CreateLocationObjectStorageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateLocationS3 = "CreateLocationS3" // CreateLocationS3Request generates a "aws/request.Request" representing the @@ -586,7 +668,7 @@ func (c *DataSync) CreateLocationSmbRequest(input *CreateLocationSmbInput) (req // CreateLocationSmb API operation for AWS DataSync. // -// Defines a file system on an Server Message Block (SMB) server that can be +// Defines a file system on a Server Message Block (SMB) server that can be // read from or written to. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1269,7 +1351,7 @@ func (c *DataSync) DescribeLocationNfsRequest(input *DescribeLocationNfsInput) ( // DescribeLocationNfs API operation for AWS DataSync. // -// Returns metadata, such as the path information, about a NFS location. +// Returns metadata, such as the path information, about an NFS location. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1307,6 +1389,88 @@ func (c *DataSync) DescribeLocationNfsWithContext(ctx aws.Context, input *Descri return out, req.Send() } +const opDescribeLocationObjectStorage = "DescribeLocationObjectStorage" + +// DescribeLocationObjectStorageRequest generates a "aws/request.Request" representing the +// client's request for the DescribeLocationObjectStorage operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeLocationObjectStorage for more information on using the DescribeLocationObjectStorage +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeLocationObjectStorageRequest method. +// req, resp := client.DescribeLocationObjectStorageRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationObjectStorage +func (c *DataSync) DescribeLocationObjectStorageRequest(input *DescribeLocationObjectStorageInput) (req *request.Request, output *DescribeLocationObjectStorageOutput) { + op := &request.Operation{ + Name: opDescribeLocationObjectStorage, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeLocationObjectStorageInput{} + } + + output = &DescribeLocationObjectStorageOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeLocationObjectStorage API operation for AWS DataSync. +// +// Returns metadata about a self-managed object storage server location. +// +// Returns awserr.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 DataSync's +// API operation DescribeLocationObjectStorage for usage and error information. +// +// Returned Error Types: +// * InvalidRequestException +// This exception is thrown when the client submits a malformed request. +// +// * InternalException +// This exception is thrown when an error occurs in the AWS DataSync service. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/datasync-2018-11-09/DescribeLocationObjectStorage +func (c *DataSync) DescribeLocationObjectStorage(input *DescribeLocationObjectStorageInput) (*DescribeLocationObjectStorageOutput, error) { + req, out := c.DescribeLocationObjectStorageRequest(input) + return out, req.Send() +} + +// DescribeLocationObjectStorageWithContext is the same as DescribeLocationObjectStorage with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLocationObjectStorage for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DataSync) DescribeLocationObjectStorageWithContext(ctx aws.Context, input *DescribeLocationObjectStorageInput, opts ...request.Option) (*DescribeLocationObjectStorageOutput, error) { + req, out := c.DescribeLocationObjectStorageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeLocationS3 = "DescribeLocationS3" // DescribeLocationS3Request generates a "aws/request.Request" representing the @@ -1433,7 +1597,7 @@ func (c *DataSync) DescribeLocationSmbRequest(input *DescribeLocationSmbInput) ( // DescribeLocationSmb API operation for AWS DataSync. // -// Returns metadata, such as the path and user information about a SMB location. +// Returns metadata, such as the path and user information about an SMB location. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1835,7 +1999,7 @@ func (c *DataSync) ListLocationsRequest(input *ListLocationsInput) (req *request // ListLocations API operation for AWS DataSync. // -// Returns a lists of source and destination locations. +// Returns a list of source and destination locations. // // If you have more locations than are returned in a response (that is, the // response returns only a truncated list of your agents), the response contains @@ -1980,7 +2144,7 @@ func (c *DataSync) ListTagsForResourceRequest(input *ListTagsForResourceInput) ( // ListTagsForResource API operation for AWS DataSync. // -// Returns all the tags associated with a specified resources. +// Returns all the tags associated with a 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 @@ -2912,11 +3076,11 @@ type CreateAgentInput struct { // in UTF-8 format, and the following special characters: + - = . _ : / @. Tags []*TagListEntry `type:"list"` - // The ID of the VPC (Virtual Private Cloud) endpoint that the agent has access + // The ID of the VPC (virtual private cloud) endpoint that the agent has access // to. This is the client-side VPC endpoint, also called a PrivateLink. If you // don't have a PrivateLink VPC endpoint, see Creating a VPC Endpoint Service // Configuration (https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-service.html#create-endpoint-service) - // in the AWS VPC User Guide. + // in the Amazon VPC User Guide. // // VPC endpoint ID looks like this: vpce-01234d5aff67890e1. VpcEndpointId *string `type:"string"` @@ -3061,7 +3225,7 @@ type CreateLocationEfsInput struct { // system is used to read data from the EFS source location or write data to // the EFS destination. By default, AWS DataSync uses the root directory. // - // Subdirectory must be specified with forward slashes. For example /path/to/folder. + // Subdirectory must be specified with forward slashes. For example, /path/to/folder. Subdirectory *string `type:"string"` // The key-value pair that represents a tag that you want to add to the resource. @@ -3323,6 +3487,10 @@ type CreateLocationNfsInput struct { // Contains a list of Amazon Resource Names (ARNs) of agents that are used to // connect to an NFS server. // + // If you are copying data to or from your AWS Snowcone device, see NFS Server + // on AWS Snowcone (https://docs.aws.amazon.com/datasync/latest/userguide/create-nfs-location.html#nfs-on-snowcone) + // for more information. + // // OnPremConfig is a required field OnPremConfig *OnPremConfig `type:"structure" required:"true"` @@ -3330,6 +3498,10 @@ type CreateLocationNfsInput struct { // (DNS) name of the NFS server. An agent that is installed on-premises uses // this host name to mount the NFS server in a network. // + // If you are copying data to or from your AWS Snowcone device, see NFS Server + // on AWS Snowcone (https://docs.aws.amazon.com/datasync/latest/userguide/create-nfs-location.html#nfs-on-snowcone) + // for more information. + // // This name must either be DNS-compliant or must be an IP version 4 (IPv4) // address. // @@ -3354,6 +3526,10 @@ type CreateLocationNfsInput struct { // enables the agent to read the files. For the agent to access directories, // you must additionally enable all execute access. // + // If you are copying data to or from your AWS Snowcone device, see NFS Server + // on AWS Snowcone (https://docs.aws.amazon.com/datasync/latest/userguide/create-nfs-location.html#nfs-on-snowcone) + // for more information. + // // For information about NFS export configuration, see 18.7. The /etc/exports // Configuration File in the Red Hat Enterprise Linux documentation. // @@ -3464,6 +3640,189 @@ func (s *CreateLocationNfsOutput) SetLocationArn(v string) *CreateLocationNfsOut return s } +// CreateLocationObjectStorageRequest +type CreateLocationObjectStorageInput struct { + _ struct{} `type:"structure"` + + // Optional. The access key is used if credentials are required to access the + // self-managed object storage server. + AccessKey *string `min:"8" type:"string"` + + // The Amazon Resource Name (ARN) of the agents associated with the self-managed + // object storage server location. + // + // AgentArns is a required field + AgentArns []*string `min:"1" type:"list" required:"true"` + + // The bucket on the self-managed object storage server that is used to read + // data from. + // + // BucketName is a required field + BucketName *string `min:"3" type:"string" required:"true"` + + // Optional. The secret key is used if credentials are required to access the + // self-managed object storage server. + SecretKey *string `min:"8" type:"string" sensitive:"true"` + + // The name of the self-managed object storage server. This value is the IP + // address or Domain Name Service (DNS) name of the object storage server. An + // agent uses this host name to mount the object storage server in a network. + // + // ServerHostname is a required field + ServerHostname *string `type:"string" required:"true"` + + // The port that your self-managed object storage server accepts inbound network + // traffic on. The server port is set by default to TCP 80 (HTTP) or TCP 443 + // (HTTPS). You can specify a custom port if your self-managed object storage + // server requires one. + ServerPort *int64 `min:"1" type:"integer"` + + // The protocol that the object storage server uses to communicate. Valid values + // are HTTP or HTTPS. + ServerProtocol *string `type:"string" enum:"ObjectStorageServerProtocol"` + + // The subdirectory in the self-managed object storage server that is used to + // read data from. + Subdirectory *string `type:"string"` + + // The key-value pair that represents the tag that you want to add to the location. + // The value can be an empty string. We recommend using tags to name your resources. + Tags []*TagListEntry `type:"list"` +} + +// String returns the string representation +func (s CreateLocationObjectStorageInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateLocationObjectStorageInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateLocationObjectStorageInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateLocationObjectStorageInput"} + if s.AccessKey != nil && len(*s.AccessKey) < 8 { + invalidParams.Add(request.NewErrParamMinLen("AccessKey", 8)) + } + if s.AgentArns == nil { + invalidParams.Add(request.NewErrParamRequired("AgentArns")) + } + if s.AgentArns != nil && len(s.AgentArns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AgentArns", 1)) + } + if s.BucketName == nil { + invalidParams.Add(request.NewErrParamRequired("BucketName")) + } + if s.BucketName != nil && len(*s.BucketName) < 3 { + invalidParams.Add(request.NewErrParamMinLen("BucketName", 3)) + } + if s.SecretKey != nil && len(*s.SecretKey) < 8 { + invalidParams.Add(request.NewErrParamMinLen("SecretKey", 8)) + } + if s.ServerHostname == nil { + invalidParams.Add(request.NewErrParamRequired("ServerHostname")) + } + if s.ServerPort != nil && *s.ServerPort < 1 { + invalidParams.Add(request.NewErrParamMinValue("ServerPort", 1)) + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAccessKey sets the AccessKey field's value. +func (s *CreateLocationObjectStorageInput) SetAccessKey(v string) *CreateLocationObjectStorageInput { + s.AccessKey = &v + return s +} + +// SetAgentArns sets the AgentArns field's value. +func (s *CreateLocationObjectStorageInput) SetAgentArns(v []*string) *CreateLocationObjectStorageInput { + s.AgentArns = v + return s +} + +// SetBucketName sets the BucketName field's value. +func (s *CreateLocationObjectStorageInput) SetBucketName(v string) *CreateLocationObjectStorageInput { + s.BucketName = &v + return s +} + +// SetSecretKey sets the SecretKey field's value. +func (s *CreateLocationObjectStorageInput) SetSecretKey(v string) *CreateLocationObjectStorageInput { + s.SecretKey = &v + return s +} + +// SetServerHostname sets the ServerHostname field's value. +func (s *CreateLocationObjectStorageInput) SetServerHostname(v string) *CreateLocationObjectStorageInput { + s.ServerHostname = &v + return s +} + +// SetServerPort sets the ServerPort field's value. +func (s *CreateLocationObjectStorageInput) SetServerPort(v int64) *CreateLocationObjectStorageInput { + s.ServerPort = &v + return s +} + +// SetServerProtocol sets the ServerProtocol field's value. +func (s *CreateLocationObjectStorageInput) SetServerProtocol(v string) *CreateLocationObjectStorageInput { + s.ServerProtocol = &v + return s +} + +// SetSubdirectory sets the Subdirectory field's value. +func (s *CreateLocationObjectStorageInput) SetSubdirectory(v string) *CreateLocationObjectStorageInput { + s.Subdirectory = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateLocationObjectStorageInput) SetTags(v []*TagListEntry) *CreateLocationObjectStorageInput { + s.Tags = v + return s +} + +// CreateLocationObjectStorageResponse +type CreateLocationObjectStorageOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the agents associated with the self-managed + // object storage server location. + LocationArn *string `type:"string"` +} + +// String returns the string representation +func (s CreateLocationObjectStorageOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateLocationObjectStorageOutput) GoString() string { + return s.String() +} + +// SetLocationArn sets the LocationArn field's value. +func (s *CreateLocationObjectStorageOutput) SetLocationArn(v string) *CreateLocationObjectStorageOutput { + s.LocationArn = &v + return s +} + // CreateLocationS3Request type CreateLocationS3Input struct { _ struct{} `type:"structure"` @@ -3633,7 +3992,7 @@ type CreateLocationSmbInput struct { // The path should be such that it can be mounted by other SMB clients in your // network. // - // Subdirectory must be specified with forward slashes. For example /path/to/folder. + // Subdirectory must be specified with forward slashes. For example, /path/to/folder. // // To transfer all the data in the folder you specified, DataSync needs to have // permissions to mount the SMB share, as well as to access all the data in @@ -3785,12 +4144,6 @@ type CreateTaskInput struct { // The Amazon Resource Name (ARN) of the Amazon CloudWatch log group that is // used to monitor and log events in the task. - // - // For more information on these groups, see Working with Log Groups and Log - // Streams in the Amazon CloudWatch User Guide. - // - // For more information about how to use CloudWatch Logs with DataSync, see - // Monitoring Your Task in the AWS DataSync User Guide. CloudWatchLogGroupArn *string `type:"string"` // The Amazon Resource Name (ARN) of an AWS storage resource's location. @@ -3814,7 +4167,7 @@ type CreateTaskInput struct { // file permissions, data integrity verification, and so on. // // For each individual task execution, you can override these options by specifying - // the OverrideOptions before starting a the task execution. For more information, + // the OverrideOptions before starting the task execution. For more information, // see the operation. Options *Options `type:"structure"` @@ -4164,7 +4517,7 @@ type DescribeAgentOutput struct { CreationTime *time.Time `type:"timestamp"` // The type of endpoint that your agent is connected to. If the endpoint is - // a VPC endpoint, the agent is not accessible over the public Internet. + // a VPC endpoint, the agent is not accessible over the public internet. EndpointType *string `type:"string" enum:"EndpointType"` // The time that the agent last connected to DataSyc. @@ -4288,7 +4641,7 @@ type DescribeLocationEfsOutput struct { // with the security group on the mount target in the subnet specified. Ec2Config *Ec2Config `type:"structure"` - // The Amazon resource Name (ARN) of the EFS location that was described. + // The Amazon Resource Name (ARN) of the EFS location that was described. LocationArn *string `type:"string"` // The URL of the EFS location that was described. @@ -4376,14 +4729,14 @@ type DescribeLocationFsxWindowsOutput struct { // The name of the Windows domain that the FSx for Windows server belongs to. Domain *string `type:"string"` - // The Amazon resource Name (ARN) of the FSx for Windows location that was described. + // The Amazon Resource Name (ARN) of the FSx for Windows location that was described. LocationArn *string `type:"string"` // The URL of the FSx for Windows location that was described. LocationUri *string `type:"string"` // The Amazon Resource Names (ARNs) of the security groups that are configured - // for the for the FSx for Windows file system. + // for the FSx for Windows file system. SecurityGroupArns []*string `min:"1" type:"list"` // The user who has the permissions to access files and folders in the FSx for @@ -4441,7 +4794,7 @@ func (s *DescribeLocationFsxWindowsOutput) SetUser(v string) *DescribeLocationFs type DescribeLocationNfsInput struct { _ struct{} `type:"structure"` - // The Amazon resource Name (ARN) of the NFS location to describe. + // The Amazon Resource Name (ARN) of the NFS location to describe. // // LocationArn is a required field LocationArn *string `type:"string" required:"true"` @@ -4483,7 +4836,7 @@ type DescribeLocationNfsOutput struct { // The time that the NFS location was created. CreationTime *time.Time `type:"timestamp"` - // The Amazon resource Name (ARN) of the NFS location that was described. + // The Amazon Resource Name (ARN) of the NFS location that was described. LocationArn *string `type:"string"` // The URL of the source NFS location that was described. @@ -4537,6 +4890,131 @@ func (s *DescribeLocationNfsOutput) SetOnPremConfig(v *OnPremConfig) *DescribeLo return s } +// DescribeLocationObjectStorageRequest +type DescribeLocationObjectStorageInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the self-managed object storage server + // location that was described. + // + // LocationArn is a required field + LocationArn *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeLocationObjectStorageInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeLocationObjectStorageInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeLocationObjectStorageInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeLocationObjectStorageInput"} + if s.LocationArn == nil { + invalidParams.Add(request.NewErrParamRequired("LocationArn")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLocationArn sets the LocationArn field's value. +func (s *DescribeLocationObjectStorageInput) SetLocationArn(v string) *DescribeLocationObjectStorageInput { + s.LocationArn = &v + return s +} + +// DescribeLocationObjectStorageResponse +type DescribeLocationObjectStorageOutput struct { + _ struct{} `type:"structure"` + + // Optional. The access key is used if credentials are required to access the + // self-managed object storage server. + AccessKey *string `min:"8" type:"string"` + + // The Amazon Resource Name (ARN) of the agents associated with the self-managed + // object storage server location. + AgentArns []*string `min:"1" type:"list"` + + // The time that the self-managed object storage server agent was created. + CreationTime *time.Time `type:"timestamp"` + + // The Amazon Resource Name (ARN) of the self-managed object storage server + // location to describe. + LocationArn *string `type:"string"` + + // The URL of the source self-managed object storage server location that was + // described. + LocationUri *string `type:"string"` + + // The port that your self-managed object storage server accepts inbound network + // traffic on. The server port is set by default to TCP 80 (HTTP) or TCP 443 + // (HTTPS). + ServerPort *int64 `min:"1" type:"integer"` + + // The protocol that the object storage server uses to communicate. Valid values + // are HTTP or HTTPS. + ServerProtocol *string `type:"string" enum:"ObjectStorageServerProtocol"` +} + +// String returns the string representation +func (s DescribeLocationObjectStorageOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeLocationObjectStorageOutput) GoString() string { + return s.String() +} + +// SetAccessKey sets the AccessKey field's value. +func (s *DescribeLocationObjectStorageOutput) SetAccessKey(v string) *DescribeLocationObjectStorageOutput { + s.AccessKey = &v + return s +} + +// SetAgentArns sets the AgentArns field's value. +func (s *DescribeLocationObjectStorageOutput) SetAgentArns(v []*string) *DescribeLocationObjectStorageOutput { + s.AgentArns = v + return s +} + +// SetCreationTime sets the CreationTime field's value. +func (s *DescribeLocationObjectStorageOutput) SetCreationTime(v time.Time) *DescribeLocationObjectStorageOutput { + s.CreationTime = &v + return s +} + +// SetLocationArn sets the LocationArn field's value. +func (s *DescribeLocationObjectStorageOutput) SetLocationArn(v string) *DescribeLocationObjectStorageOutput { + s.LocationArn = &v + return s +} + +// SetLocationUri sets the LocationUri field's value. +func (s *DescribeLocationObjectStorageOutput) SetLocationUri(v string) *DescribeLocationObjectStorageOutput { + s.LocationUri = &v + return s +} + +// SetServerPort sets the ServerPort field's value. +func (s *DescribeLocationObjectStorageOutput) SetServerPort(v int64) *DescribeLocationObjectStorageOutput { + s.ServerPort = &v + return s +} + +// SetServerProtocol sets the ServerProtocol field's value. +func (s *DescribeLocationObjectStorageOutput) SetServerProtocol(v string) *DescribeLocationObjectStorageOutput { + s.ServerProtocol = &v + return s +} + // DescribeLocationS3Request type DescribeLocationS3Input struct { _ struct{} `type:"structure"` @@ -4649,7 +5127,7 @@ func (s *DescribeLocationS3Output) SetS3StorageClass(v string) *DescribeLocation type DescribeLocationSmbInput struct { _ struct{} `type:"structure"` - // The Amazon resource Name (ARN) of the SMB location to describe. + // The Amazon Resource Name (ARN) of the SMB location to describe. // // LocationArn is a required field LocationArn *string `type:"string" required:"true"` @@ -4698,7 +5176,7 @@ type DescribeLocationSmbOutput struct { // The name of the Windows domain that the SMB server belongs to. Domain *string `type:"string"` - // The Amazon resource Name (ARN) of the SMB location that was described. + // The Amazon Resource Name (ARN) of the SMB location that was described. LocationArn *string `type:"string"` // The URL of the source SBM location that was described. @@ -5938,10 +6416,12 @@ type Options struct { // NONE: Ignore UID and GID. Gid *string `type:"string" enum:"Gid"` - // A value that determines the type of logs DataSync will deliver to your AWS - // CloudWatch Logs file. If set to OFF, no logs will be delivered. BASIC will - // deliver a few logs per transfer operation and TRANSFER will deliver a verbose - // log that contains logs for every file that is transferred. + // A value that determines the type of logs that DataSync publishes to a log + // stream in the Amazon CloudWatch log group that you provide. For more information + // about providing a log group for DataSync, see CloudWatchLogGroupArn (https://docs.aws.amazon.com/datasync/latest/userguide/API_CreateTask.html#DataSync-CreateTask-request-CloudWatchLogGroupArn). + // If set to OFF, no logs are published. BASIC publishes logs on errors for + // individual files transferred, and TRANSFER publishes logs for every file + // or object that is transferred and integrity checked. LogLevel *string `type:"string" enum:"LogLevel"` // A value that indicates the last time that a file was modified (that is, a @@ -6012,10 +6492,16 @@ type Options struct { // A value that determines whether tasks should be queued before executing the // tasks. If set to ENABLED, the tasks will be queued. The default is ENABLED. // - // If you use the same agent to run multiple tasks you can enable the tasks - // to run in series. For more information see queue-task-execution. + // If you use the same agent to run multiple tasks, you can enable the tasks + // to run in series. For more information, see queue-task-execution. TaskQueueing *string `type:"string" enum:"TaskQueueing"` + // TransferMode has two values: CHANGED and ALL. CHANGED performs an "incremental" + // or "delta sync", it compares file modification time between source and destination + // to determine which files need to be transferred. ALL skips destination inventory + // and transfers all files discovered on the source. + TransferMode *string `type:"string" enum:"TransferMode"` + // The user ID (UID) of the file's owner. // // Default value: INT_VALUE. This preserves the integer value of the ID. @@ -6027,14 +6513,21 @@ type Options struct { // A value that determines whether a data integrity verification should be performed // at the end of a task execution after all data and metadata have been transferred. + // For more information, see create-task // // Default value: POINT_IN_TIME_CONSISTENT. // - // POINT_IN_TIME_CONSISTENT: Perform verification (recommended). + // ONLY_FILES_TRANSFERRED (recommended): Perform verification only on files + // that were transferred. // - // ONLY_FILES_TRANSFERRED: Perform verification on only files that were transferred. + // POINT_IN_TIME_CONSISTENT: Scan the entire source and entire destination at + // the end of the transfer to verify that source and destination are fully synchronized. + // This option isn't supported when transferring to S3 Glacier or S3 Glacier + // Deep Archive storage classes. // - // NONE: Skip verification. + // NONE: No additional verification is done at the end of the transfer, but + // all data transmissions are integrity-checked with checksum verification during + // the transfer. VerifyMode *string `type:"string" enum:"VerifyMode"` } @@ -6121,6 +6614,12 @@ func (s *Options) SetTaskQueueing(v string) *Options { return s } +// SetTransferMode sets the TransferMode field's value. +func (s *Options) SetTransferMode(v string) *Options { + s.TransferMode = &v + return s +} + // SetUid sets the Uid field's value. func (s *Options) SetUid(v string) *Options { s.Uid = &v @@ -6133,7 +6632,7 @@ func (s *Options) SetVerifyMode(v string) *Options { return s } -// The VPC endpoint, subnet and security group that an agent uses to access +// The VPC endpoint, subnet, and security group that an agent uses to access // IP addresses in a VPC (Virtual Private Cloud). type PrivateLinkConfig struct { _ struct{} `type:"structure"` @@ -6141,7 +6640,7 @@ type PrivateLinkConfig struct { // The private endpoint that is configured for an agent that has access to IP // addresses in a PrivateLink (https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-service.html). // An agent that is configured with this endpoint will not be accessible over - // the public Internet. + // the public internet. PrivateLinkEndpoint *string `min:"7" type:"string"` // The Amazon Resource Names (ARNs) of the security groups that are configured @@ -6155,7 +6654,7 @@ type PrivateLinkConfig struct { // The ID of the VPC endpoint that is configured for an agent. An agent that // is configured with a VPC endpoint will not be accessible over the public - // Internet. + // internet. VpcEndpointId *string `type:"string"` } @@ -6987,6 +7486,14 @@ const ( AgentStatusOffline = "OFFLINE" ) +// AgentStatus_Values returns all elements of the AgentStatus enum +func AgentStatus_Values() []string { + return []string{ + AgentStatusOnline, + AgentStatusOffline, + } +} + const ( // AtimeNone is a Atime enum value AtimeNone = "NONE" @@ -6995,6 +7502,14 @@ const ( AtimeBestEffort = "BEST_EFFORT" ) +// Atime_Values returns all elements of the Atime enum +func Atime_Values() []string { + return []string{ + AtimeNone, + AtimeBestEffort, + } +} + const ( // EndpointTypePublic is a EndpointType enum value EndpointTypePublic = "PUBLIC" @@ -7006,11 +7521,27 @@ const ( EndpointTypeFips = "FIPS" ) +// EndpointType_Values returns all elements of the EndpointType enum +func EndpointType_Values() []string { + return []string{ + EndpointTypePublic, + EndpointTypePrivateLink, + EndpointTypeFips, + } +} + const ( // FilterTypeSimplePattern is a FilterType enum value FilterTypeSimplePattern = "SIMPLE_PATTERN" ) +// FilterType_Values returns all elements of the FilterType enum +func FilterType_Values() []string { + return []string{ + FilterTypeSimplePattern, + } +} + const ( // GidNone is a Gid enum value GidNone = "NONE" @@ -7025,6 +7556,16 @@ const ( GidBoth = "BOTH" ) +// Gid_Values returns all elements of the Gid enum +func Gid_Values() []string { + return []string{ + GidNone, + GidIntValue, + GidName, + GidBoth, + } +} + const ( // LogLevelOff is a LogLevel enum value LogLevelOff = "OFF" @@ -7036,6 +7577,15 @@ const ( LogLevelTransfer = "TRANSFER" ) +// LogLevel_Values returns all elements of the LogLevel enum +func LogLevel_Values() []string { + return []string{ + LogLevelOff, + LogLevelBasic, + LogLevelTransfer, + } +} + const ( // MtimeNone is a Mtime enum value MtimeNone = "NONE" @@ -7044,6 +7594,14 @@ const ( MtimePreserve = "PRESERVE" ) +// Mtime_Values returns all elements of the Mtime enum +func Mtime_Values() []string { + return []string{ + MtimeNone, + MtimePreserve, + } +} + const ( // NfsVersionAutomatic is a NfsVersion enum value NfsVersionAutomatic = "AUTOMATIC" @@ -7058,6 +7616,32 @@ const ( NfsVersionNfs41 = "NFS4_1" ) +// NfsVersion_Values returns all elements of the NfsVersion enum +func NfsVersion_Values() []string { + return []string{ + NfsVersionAutomatic, + NfsVersionNfs3, + NfsVersionNfs40, + NfsVersionNfs41, + } +} + +const ( + // ObjectStorageServerProtocolHttps is a ObjectStorageServerProtocol enum value + ObjectStorageServerProtocolHttps = "HTTPS" + + // ObjectStorageServerProtocolHttp is a ObjectStorageServerProtocol enum value + ObjectStorageServerProtocolHttp = "HTTP" +) + +// ObjectStorageServerProtocol_Values returns all elements of the ObjectStorageServerProtocol enum +func ObjectStorageServerProtocol_Values() []string { + return []string{ + ObjectStorageServerProtocolHttps, + ObjectStorageServerProtocolHttp, + } +} + const ( // OverwriteModeAlways is a OverwriteMode enum value OverwriteModeAlways = "ALWAYS" @@ -7066,6 +7650,14 @@ const ( OverwriteModeNever = "NEVER" ) +// OverwriteMode_Values returns all elements of the OverwriteMode enum +func OverwriteMode_Values() []string { + return []string{ + OverwriteModeAlways, + OverwriteModeNever, + } +} + const ( // PhaseStatusPending is a PhaseStatus enum value PhaseStatusPending = "PENDING" @@ -7077,6 +7669,15 @@ const ( PhaseStatusError = "ERROR" ) +// PhaseStatus_Values returns all elements of the PhaseStatus enum +func PhaseStatus_Values() []string { + return []string{ + PhaseStatusPending, + PhaseStatusSuccess, + PhaseStatusError, + } +} + const ( // PosixPermissionsNone is a PosixPermissions enum value PosixPermissionsNone = "NONE" @@ -7085,6 +7686,14 @@ const ( PosixPermissionsPreserve = "PRESERVE" ) +// PosixPermissions_Values returns all elements of the PosixPermissions enum +func PosixPermissions_Values() []string { + return []string{ + PosixPermissionsNone, + PosixPermissionsPreserve, + } +} + const ( // PreserveDeletedFilesPreserve is a PreserveDeletedFiles enum value PreserveDeletedFilesPreserve = "PRESERVE" @@ -7093,6 +7702,14 @@ const ( PreserveDeletedFilesRemove = "REMOVE" ) +// PreserveDeletedFiles_Values returns all elements of the PreserveDeletedFiles enum +func PreserveDeletedFiles_Values() []string { + return []string{ + PreserveDeletedFilesPreserve, + PreserveDeletedFilesRemove, + } +} + const ( // PreserveDevicesNone is a PreserveDevices enum value PreserveDevicesNone = "NONE" @@ -7101,6 +7718,14 @@ const ( PreserveDevicesPreserve = "PRESERVE" ) +// PreserveDevices_Values returns all elements of the PreserveDevices enum +func PreserveDevices_Values() []string { + return []string{ + PreserveDevicesNone, + PreserveDevicesPreserve, + } +} + const ( // S3StorageClassStandard is a S3StorageClass enum value S3StorageClassStandard = "STANDARD" @@ -7121,6 +7746,18 @@ const ( S3StorageClassDeepArchive = "DEEP_ARCHIVE" ) +// S3StorageClass_Values returns all elements of the S3StorageClass enum +func S3StorageClass_Values() []string { + return []string{ + S3StorageClassStandard, + S3StorageClassStandardIa, + S3StorageClassOnezoneIa, + S3StorageClassIntelligentTiering, + S3StorageClassGlacier, + S3StorageClassDeepArchive, + } +} + const ( // SmbVersionAutomatic is a SmbVersion enum value SmbVersionAutomatic = "AUTOMATIC" @@ -7132,6 +7769,15 @@ const ( SmbVersionSmb3 = "SMB3" ) +// SmbVersion_Values returns all elements of the SmbVersion enum +func SmbVersion_Values() []string { + return []string{ + SmbVersionAutomatic, + SmbVersionSmb2, + SmbVersionSmb3, + } +} + const ( // TaskExecutionStatusQueued is a TaskExecutionStatus enum value TaskExecutionStatusQueued = "QUEUED" @@ -7155,6 +7801,19 @@ const ( TaskExecutionStatusError = "ERROR" ) +// TaskExecutionStatus_Values returns all elements of the TaskExecutionStatus enum +func TaskExecutionStatus_Values() []string { + return []string{ + TaskExecutionStatusQueued, + TaskExecutionStatusLaunching, + TaskExecutionStatusPreparing, + TaskExecutionStatusTransferring, + TaskExecutionStatusVerifying, + TaskExecutionStatusSuccess, + TaskExecutionStatusError, + } +} + const ( // TaskQueueingEnabled is a TaskQueueing enum value TaskQueueingEnabled = "ENABLED" @@ -7163,6 +7822,14 @@ const ( TaskQueueingDisabled = "DISABLED" ) +// TaskQueueing_Values returns all elements of the TaskQueueing enum +func TaskQueueing_Values() []string { + return []string{ + TaskQueueingEnabled, + TaskQueueingDisabled, + } +} + const ( // TaskStatusAvailable is a TaskStatus enum value TaskStatusAvailable = "AVAILABLE" @@ -7180,6 +7847,33 @@ const ( TaskStatusUnavailable = "UNAVAILABLE" ) +// TaskStatus_Values returns all elements of the TaskStatus enum +func TaskStatus_Values() []string { + return []string{ + TaskStatusAvailable, + TaskStatusCreating, + TaskStatusQueued, + TaskStatusRunning, + TaskStatusUnavailable, + } +} + +const ( + // TransferModeChanged is a TransferMode enum value + TransferModeChanged = "CHANGED" + + // TransferModeAll is a TransferMode enum value + TransferModeAll = "ALL" +) + +// TransferMode_Values returns all elements of the TransferMode enum +func TransferMode_Values() []string { + return []string{ + TransferModeChanged, + TransferModeAll, + } +} + const ( // UidNone is a Uid enum value UidNone = "NONE" @@ -7194,6 +7888,16 @@ const ( UidBoth = "BOTH" ) +// Uid_Values returns all elements of the Uid enum +func Uid_Values() []string { + return []string{ + UidNone, + UidIntValue, + UidName, + UidBoth, + } +} + const ( // VerifyModePointInTimeConsistent is a VerifyMode enum value VerifyModePointInTimeConsistent = "POINT_IN_TIME_CONSISTENT" @@ -7204,3 +7908,12 @@ const ( // VerifyModeNone is a VerifyMode enum value VerifyModeNone = "NONE" ) + +// VerifyMode_Values returns all elements of the VerifyMode enum +func VerifyMode_Values() []string { + return []string{ + VerifyModePointInTimeConsistent, + VerifyModeOnlyFilesTransferred, + VerifyModeNone, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/dax/api.go b/vendor/github.com/aws/aws-sdk-go/service/dax/api.go index 8a2add4a30e..1d3195713aa 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dax/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dax/api.go @@ -6218,6 +6218,14 @@ const ( ChangeTypeRequiresReboot = "REQUIRES_REBOOT" ) +// ChangeType_Values returns all elements of the ChangeType enum +func ChangeType_Values() []string { + return []string{ + ChangeTypeImmediate, + ChangeTypeRequiresReboot, + } +} + const ( // IsModifiableTrue is a IsModifiable enum value IsModifiableTrue = "TRUE" @@ -6229,6 +6237,15 @@ const ( IsModifiableConditional = "CONDITIONAL" ) +// IsModifiable_Values returns all elements of the IsModifiable enum +func IsModifiable_Values() []string { + return []string{ + IsModifiableTrue, + IsModifiableFalse, + IsModifiableConditional, + } +} + const ( // ParameterTypeDefault is a ParameterType enum value ParameterTypeDefault = "DEFAULT" @@ -6237,6 +6254,14 @@ const ( ParameterTypeNodeTypeSpecific = "NODE_TYPE_SPECIFIC" ) +// ParameterType_Values returns all elements of the ParameterType enum +func ParameterType_Values() []string { + return []string{ + ParameterTypeDefault, + ParameterTypeNodeTypeSpecific, + } +} + const ( // SSEStatusEnabling is a SSEStatus enum value SSEStatusEnabling = "ENABLING" @@ -6251,6 +6276,16 @@ const ( SSEStatusDisabled = "DISABLED" ) +// SSEStatus_Values returns all elements of the SSEStatus enum +func SSEStatus_Values() []string { + return []string{ + SSEStatusEnabling, + SSEStatusEnabled, + SSEStatusDisabling, + SSEStatusDisabled, + } +} + const ( // SourceTypeCluster is a SourceType enum value SourceTypeCluster = "CLUSTER" @@ -6261,3 +6296,12 @@ const ( // SourceTypeSubnetGroup is a SourceType enum value SourceTypeSubnetGroup = "SUBNET_GROUP" ) + +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeCluster, + SourceTypeParameterGroup, + SourceTypeSubnetGroup, + } +} 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 index 794dbc5c295..81646ad64ce 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/devicefarm/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/devicefarm/api.go @@ -19903,6 +19903,15 @@ const ( ArtifactCategoryLog = "LOG" ) +// ArtifactCategory_Values returns all elements of the ArtifactCategory enum +func ArtifactCategory_Values() []string { + return []string{ + ArtifactCategoryScreenshot, + ArtifactCategoryFile, + ArtifactCategoryLog, + } +} + const ( // ArtifactTypeUnknown is a ArtifactType enum value ArtifactTypeUnknown = "UNKNOWN" @@ -19989,6 +19998,40 @@ const ( ArtifactTypeTestspecOutput = "TESTSPEC_OUTPUT" ) +// ArtifactType_Values returns all elements of the ArtifactType enum +func ArtifactType_Values() []string { + return []string{ + ArtifactTypeUnknown, + ArtifactTypeScreenshot, + ArtifactTypeDeviceLog, + ArtifactTypeMessageLog, + ArtifactTypeVideoLog, + ArtifactTypeResultLog, + ArtifactTypeServiceLog, + ArtifactTypeWebkitLog, + ArtifactTypeInstrumentationOutput, + ArtifactTypeExerciserMonkeyOutput, + ArtifactTypeCalabashJsonOutput, + ArtifactTypeCalabashPrettyOutput, + ArtifactTypeCalabashStandardOutput, + ArtifactTypeCalabashJavaXmlOutput, + ArtifactTypeAutomationOutput, + ArtifactTypeAppiumServerOutput, + ArtifactTypeAppiumJavaOutput, + ArtifactTypeAppiumJavaXmlOutput, + ArtifactTypeAppiumPythonOutput, + ArtifactTypeAppiumPythonXmlOutput, + ArtifactTypeExplorerEventLog, + ArtifactTypeExplorerSummaryLog, + ArtifactTypeApplicationCrashReport, + ArtifactTypeXctestLog, + ArtifactTypeVideo, + ArtifactTypeCustomerArtifact, + ArtifactTypeCustomerArtifactLog, + ArtifactTypeTestspecOutput, + } +} + const ( // BillingMethodMetered is a BillingMethod enum value BillingMethodMetered = "METERED" @@ -19997,11 +20040,26 @@ const ( BillingMethodUnmetered = "UNMETERED" ) +// BillingMethod_Values returns all elements of the BillingMethod enum +func BillingMethod_Values() []string { + return []string{ + BillingMethodMetered, + BillingMethodUnmetered, + } +} + const ( // CurrencyCodeUsd is a CurrencyCode enum value CurrencyCodeUsd = "USD" ) +// CurrencyCode_Values returns all elements of the CurrencyCode enum +func CurrencyCode_Values() []string { + return []string{ + CurrencyCodeUsd, + } +} + const ( // DeviceAttributeArn is a DeviceAttribute enum value DeviceAttributeArn = "ARN" @@ -20043,6 +20101,25 @@ const ( DeviceAttributeAvailability = "AVAILABILITY" ) +// DeviceAttribute_Values returns all elements of the DeviceAttribute enum +func DeviceAttribute_Values() []string { + return []string{ + DeviceAttributeArn, + DeviceAttributePlatform, + DeviceAttributeFormFactor, + DeviceAttributeManufacturer, + DeviceAttributeRemoteAccessEnabled, + DeviceAttributeRemoteDebugEnabled, + DeviceAttributeAppiumVersion, + DeviceAttributeInstanceArn, + DeviceAttributeInstanceLabels, + DeviceAttributeFleetType, + DeviceAttributeOsVersion, + DeviceAttributeModel, + DeviceAttributeAvailability, + } +} + const ( // DeviceAvailabilityTemporaryNotAvailable is a DeviceAvailability enum value DeviceAvailabilityTemporaryNotAvailable = "TEMPORARY_NOT_AVAILABLE" @@ -20057,6 +20134,16 @@ const ( DeviceAvailabilityHighlyAvailable = "HIGHLY_AVAILABLE" ) +// DeviceAvailability_Values returns all elements of the DeviceAvailability enum +func DeviceAvailability_Values() []string { + return []string{ + DeviceAvailabilityTemporaryNotAvailable, + DeviceAvailabilityBusy, + DeviceAvailabilityAvailable, + DeviceAvailabilityHighlyAvailable, + } +} + const ( // DeviceFilterAttributeArn is a DeviceFilterAttribute enum value DeviceFilterAttributeArn = "ARN" @@ -20095,6 +20182,24 @@ const ( DeviceFilterAttributeFleetType = "FLEET_TYPE" ) +// DeviceFilterAttribute_Values returns all elements of the DeviceFilterAttribute enum +func DeviceFilterAttribute_Values() []string { + return []string{ + DeviceFilterAttributeArn, + DeviceFilterAttributePlatform, + DeviceFilterAttributeOsVersion, + DeviceFilterAttributeModel, + DeviceFilterAttributeAvailability, + DeviceFilterAttributeFormFactor, + DeviceFilterAttributeManufacturer, + DeviceFilterAttributeRemoteAccessEnabled, + DeviceFilterAttributeRemoteDebugEnabled, + DeviceFilterAttributeInstanceArn, + DeviceFilterAttributeInstanceLabels, + DeviceFilterAttributeFleetType, + } +} + const ( // DeviceFormFactorPhone is a DeviceFormFactor enum value DeviceFormFactorPhone = "PHONE" @@ -20103,6 +20208,14 @@ const ( DeviceFormFactorTablet = "TABLET" ) +// DeviceFormFactor_Values returns all elements of the DeviceFormFactor enum +func DeviceFormFactor_Values() []string { + return []string{ + DeviceFormFactorPhone, + DeviceFormFactorTablet, + } +} + const ( // DevicePlatformAndroid is a DevicePlatform enum value DevicePlatformAndroid = "ANDROID" @@ -20111,6 +20224,14 @@ const ( DevicePlatformIos = "IOS" ) +// DevicePlatform_Values returns all elements of the DevicePlatform enum +func DevicePlatform_Values() []string { + return []string{ + DevicePlatformAndroid, + DevicePlatformIos, + } +} + const ( // DevicePoolTypeCurated is a DevicePoolType enum value DevicePoolTypeCurated = "CURATED" @@ -20119,6 +20240,14 @@ const ( DevicePoolTypePrivate = "PRIVATE" ) +// DevicePoolType_Values returns all elements of the DevicePoolType enum +func DevicePoolType_Values() []string { + return []string{ + DevicePoolTypeCurated, + DevicePoolTypePrivate, + } +} + const ( // ExecutionResultPending is a ExecutionResult enum value ExecutionResultPending = "PENDING" @@ -20142,6 +20271,19 @@ const ( ExecutionResultStopped = "STOPPED" ) +// ExecutionResult_Values returns all elements of the ExecutionResult enum +func ExecutionResult_Values() []string { + return []string{ + ExecutionResultPending, + ExecutionResultPassed, + ExecutionResultWarned, + ExecutionResultFailed, + ExecutionResultSkipped, + ExecutionResultErrored, + ExecutionResultStopped, + } +} + const ( // ExecutionResultCodeParsingFailed is a ExecutionResultCode enum value ExecutionResultCodeParsingFailed = "PARSING_FAILED" @@ -20150,6 +20292,14 @@ const ( ExecutionResultCodeVpcEndpointSetupFailed = "VPC_ENDPOINT_SETUP_FAILED" ) +// ExecutionResultCode_Values returns all elements of the ExecutionResultCode enum +func ExecutionResultCode_Values() []string { + return []string{ + ExecutionResultCodeParsingFailed, + ExecutionResultCodeVpcEndpointSetupFailed, + } +} + const ( // ExecutionStatusPending is a ExecutionStatus enum value ExecutionStatusPending = "PENDING" @@ -20179,6 +20329,21 @@ const ( ExecutionStatusStopping = "STOPPING" ) +// ExecutionStatus_Values returns all elements of the ExecutionStatus enum +func ExecutionStatus_Values() []string { + return []string{ + ExecutionStatusPending, + ExecutionStatusPendingConcurrency, + ExecutionStatusPendingDevice, + ExecutionStatusProcessing, + ExecutionStatusScheduling, + ExecutionStatusPreparing, + ExecutionStatusRunning, + ExecutionStatusCompleted, + ExecutionStatusStopping, + } +} + const ( // InstanceStatusInUse is a InstanceStatus enum value InstanceStatusInUse = "IN_USE" @@ -20193,6 +20358,16 @@ const ( InstanceStatusNotAvailable = "NOT_AVAILABLE" ) +// InstanceStatus_Values returns all elements of the InstanceStatus enum +func InstanceStatus_Values() []string { + return []string{ + InstanceStatusInUse, + InstanceStatusPreparing, + InstanceStatusAvailable, + InstanceStatusNotAvailable, + } +} + const ( // InteractionModeInteractive is a InteractionMode enum value InteractionModeInteractive = "INTERACTIVE" @@ -20204,6 +20379,15 @@ const ( InteractionModeVideoOnly = "VIDEO_ONLY" ) +// InteractionMode_Values returns all elements of the InteractionMode enum +func InteractionMode_Values() []string { + return []string{ + InteractionModeInteractive, + InteractionModeNoVideo, + InteractionModeVideoOnly, + } +} + const ( // NetworkProfileTypeCurated is a NetworkProfileType enum value NetworkProfileTypeCurated = "CURATED" @@ -20212,6 +20396,14 @@ const ( NetworkProfileTypePrivate = "PRIVATE" ) +// NetworkProfileType_Values returns all elements of the NetworkProfileType enum +func NetworkProfileType_Values() []string { + return []string{ + NetworkProfileTypeCurated, + NetworkProfileTypePrivate, + } +} + const ( // OfferingTransactionTypePurchase is a OfferingTransactionType enum value OfferingTransactionTypePurchase = "PURCHASE" @@ -20223,16 +20415,39 @@ const ( OfferingTransactionTypeSystem = "SYSTEM" ) +// OfferingTransactionType_Values returns all elements of the OfferingTransactionType enum +func OfferingTransactionType_Values() []string { + return []string{ + OfferingTransactionTypePurchase, + OfferingTransactionTypeRenew, + OfferingTransactionTypeSystem, + } +} + const ( // OfferingTypeRecurring is a OfferingType enum value OfferingTypeRecurring = "RECURRING" ) +// OfferingType_Values returns all elements of the OfferingType enum +func OfferingType_Values() []string { + return []string{ + OfferingTypeRecurring, + } +} + const ( // RecurringChargeFrequencyMonthly is a RecurringChargeFrequency enum value RecurringChargeFrequencyMonthly = "MONTHLY" ) +// RecurringChargeFrequency_Values returns all elements of the RecurringChargeFrequency enum +func RecurringChargeFrequency_Values() []string { + return []string{ + RecurringChargeFrequencyMonthly, + } +} + const ( // RuleOperatorEquals is a RuleOperator enum value RuleOperatorEquals = "EQUALS" @@ -20259,6 +20474,20 @@ const ( RuleOperatorContains = "CONTAINS" ) +// RuleOperator_Values returns all elements of the RuleOperator enum +func RuleOperator_Values() []string { + return []string{ + RuleOperatorEquals, + RuleOperatorLessThan, + RuleOperatorLessThanOrEquals, + RuleOperatorGreaterThan, + RuleOperatorGreaterThanOrEquals, + RuleOperatorIn, + RuleOperatorNotIn, + RuleOperatorContains, + } +} + const ( // SampleTypeCpu is a SampleType enum value SampleTypeCpu = "CPU" @@ -20312,6 +20541,29 @@ const ( SampleTypeOpenglMaxDrawtime = "OPENGL_MAX_DRAWTIME" ) +// SampleType_Values returns all elements of the SampleType enum +func SampleType_Values() []string { + return []string{ + SampleTypeCpu, + SampleTypeMemory, + SampleTypeThreads, + SampleTypeRxRate, + SampleTypeTxRate, + SampleTypeRx, + SampleTypeTx, + SampleTypeNativeFrames, + SampleTypeNativeFps, + SampleTypeNativeMinDrawtime, + SampleTypeNativeAvgDrawtime, + SampleTypeNativeMaxDrawtime, + SampleTypeOpenglFrames, + SampleTypeOpenglFps, + SampleTypeOpenglMinDrawtime, + SampleTypeOpenglAvgDrawtime, + SampleTypeOpenglMaxDrawtime, + } +} + const ( // TestGridSessionArtifactCategoryVideo is a TestGridSessionArtifactCategory enum value TestGridSessionArtifactCategoryVideo = "VIDEO" @@ -20320,6 +20572,14 @@ const ( TestGridSessionArtifactCategoryLog = "LOG" ) +// TestGridSessionArtifactCategory_Values returns all elements of the TestGridSessionArtifactCategory enum +func TestGridSessionArtifactCategory_Values() []string { + return []string{ + TestGridSessionArtifactCategoryVideo, + TestGridSessionArtifactCategoryLog, + } +} + const ( // TestGridSessionArtifactTypeUnknown is a TestGridSessionArtifactType enum value TestGridSessionArtifactTypeUnknown = "UNKNOWN" @@ -20331,6 +20591,15 @@ const ( TestGridSessionArtifactTypeSeleniumLog = "SELENIUM_LOG" ) +// TestGridSessionArtifactType_Values returns all elements of the TestGridSessionArtifactType enum +func TestGridSessionArtifactType_Values() []string { + return []string{ + TestGridSessionArtifactTypeUnknown, + TestGridSessionArtifactTypeVideo, + TestGridSessionArtifactTypeSeleniumLog, + } +} + const ( // TestGridSessionStatusActive is a TestGridSessionStatus enum value TestGridSessionStatusActive = "ACTIVE" @@ -20342,6 +20611,15 @@ const ( TestGridSessionStatusErrored = "ERRORED" ) +// TestGridSessionStatus_Values returns all elements of the TestGridSessionStatus enum +func TestGridSessionStatus_Values() []string { + return []string{ + TestGridSessionStatusActive, + TestGridSessionStatusClosed, + TestGridSessionStatusErrored, + } +} + const ( // TestTypeBuiltinFuzz is a TestType enum value TestTypeBuiltinFuzz = "BUILTIN_FUZZ" @@ -20407,6 +20685,33 @@ const ( TestTypeRemoteAccessReplay = "REMOTE_ACCESS_REPLAY" ) +// TestType_Values returns all elements of the TestType enum +func TestType_Values() []string { + return []string{ + TestTypeBuiltinFuzz, + TestTypeBuiltinExplorer, + TestTypeWebPerformanceProfile, + TestTypeAppiumJavaJunit, + TestTypeAppiumJavaTestng, + TestTypeAppiumPython, + TestTypeAppiumNode, + TestTypeAppiumRuby, + TestTypeAppiumWebJavaJunit, + TestTypeAppiumWebJavaTestng, + TestTypeAppiumWebPython, + TestTypeAppiumWebNode, + TestTypeAppiumWebRuby, + TestTypeCalabash, + TestTypeInstrumentation, + TestTypeUiautomation, + TestTypeUiautomator, + TestTypeXctest, + TestTypeXctestUi, + TestTypeRemoteAccessRecord, + TestTypeRemoteAccessReplay, + } +} + const ( // UploadCategoryCurated is a UploadCategory enum value UploadCategoryCurated = "CURATED" @@ -20415,6 +20720,14 @@ const ( UploadCategoryPrivate = "PRIVATE" ) +// UploadCategory_Values returns all elements of the UploadCategory enum +func UploadCategory_Values() []string { + return []string{ + UploadCategoryCurated, + UploadCategoryPrivate, + } +} + const ( // UploadStatusInitialized is a UploadStatus enum value UploadStatusInitialized = "INITIALIZED" @@ -20429,6 +20742,16 @@ const ( UploadStatusFailed = "FAILED" ) +// UploadStatus_Values returns all elements of the UploadStatus enum +func UploadStatus_Values() []string { + return []string{ + UploadStatusInitialized, + UploadStatusProcessing, + UploadStatusSucceeded, + UploadStatusFailed, + } +} + const ( // UploadTypeAndroidApp is a UploadType enum value UploadTypeAndroidApp = "ANDROID_APP" @@ -20526,3 +20849,41 @@ const ( // UploadTypeXctestUiTestSpec is a UploadType enum value UploadTypeXctestUiTestSpec = "XCTEST_UI_TEST_SPEC" ) + +// UploadType_Values returns all elements of the UploadType enum +func UploadType_Values() []string { + return []string{ + UploadTypeAndroidApp, + UploadTypeIosApp, + UploadTypeWebApp, + UploadTypeExternalData, + UploadTypeAppiumJavaJunitTestPackage, + UploadTypeAppiumJavaTestngTestPackage, + UploadTypeAppiumPythonTestPackage, + UploadTypeAppiumNodeTestPackage, + UploadTypeAppiumRubyTestPackage, + UploadTypeAppiumWebJavaJunitTestPackage, + UploadTypeAppiumWebJavaTestngTestPackage, + UploadTypeAppiumWebPythonTestPackage, + UploadTypeAppiumWebNodeTestPackage, + UploadTypeAppiumWebRubyTestPackage, + UploadTypeCalabashTestPackage, + UploadTypeInstrumentationTestPackage, + UploadTypeUiautomationTestPackage, + UploadTypeUiautomatorTestPackage, + UploadTypeXctestTestPackage, + UploadTypeXctestUiTestPackage, + UploadTypeAppiumJavaJunitTestSpec, + UploadTypeAppiumJavaTestngTestSpec, + UploadTypeAppiumPythonTestSpec, + UploadTypeAppiumNodeTestSpec, + UploadTypeAppiumRubyTestSpec, + UploadTypeAppiumWebJavaJunitTestSpec, + UploadTypeAppiumWebJavaTestngTestSpec, + UploadTypeAppiumWebPythonTestSpec, + UploadTypeAppiumWebNodeTestSpec, + UploadTypeAppiumWebRubyTestSpec, + UploadTypeInstrumentationTestSpec, + UploadTypeXctestUiTestSpec, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/directconnect/api.go b/vendor/github.com/aws/aws-sdk-go/service/directconnect/api.go index fe73bb92626..bb67a8efe42 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/directconnect/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/directconnect/api.go @@ -1620,10 +1620,8 @@ func (c *DirectConnect) CreateDirectConnectGatewayAssociationProposalRequest(inp // Creates a proposal to associate the specified virtual private gateway or // transit gateway with the specified Direct Connect gateway. // -// You can only associate a Direct Connect gateway and virtual private gateway -// or transit gateway when the account that owns the Direct Connect gateway -// and the account that owns the virtual private gateway or transit gateway -// have the same AWS Payer ID. +// You can associate a Direct Connect gateway and virtual private gateway or +// transit gateway that is owned by any 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 @@ -1935,6 +1933,13 @@ func (c *DirectConnect) CreatePrivateVirtualInterfaceRequest(input *CreatePrivat // different AWS Regions. Connecting the private virtual interface to a VGW // only provides access to a single VPC within the same Region. // +// Setting the MTU of a virtual interface to 9001 (jumbo frames) can cause an +// update to the underlying physical connection if it wasn't updated to support +// jumbo frames. Updating the connection disrupts network connectivity for all +// virtual interfaces associated with the connection for up to 30 seconds. To +// check whether your connection supports jumbo frames, call DescribeConnections. +// To check whether your virtual interface supports jumbo frames, call DescribeVirtualInterfaces. +// // Returns awserr.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. @@ -2126,6 +2131,13 @@ func (c *DirectConnect) CreateTransitVirtualInterfaceRequest(input *CreateTransi // 64512 for both your the transit gateway and Direct Connect gateway, the association // request fails. // +// Setting the MTU of a virtual interface to 8500 (jumbo frames) can cause an +// update to the underlying physical connection if it wasn't updated to support +// jumbo frames. Updating the connection disrupts network connectivity for all +// virtual interfaces associated with the connection for up to 30 seconds. To +// check whether your connection supports jumbo frames, call DescribeConnections. +// To check whether your virtual interface supports jumbo frames, call DescribeVirtualInterfaces. +// // Returns awserr.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. @@ -4331,6 +4343,262 @@ func (c *DirectConnect) DisassociateConnectionFromLagWithContext(ctx aws.Context return out, req.Send() } +const opListVirtualInterfaceTestHistory = "ListVirtualInterfaceTestHistory" + +// ListVirtualInterfaceTestHistoryRequest generates a "aws/request.Request" representing the +// client's request for the ListVirtualInterfaceTestHistory operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListVirtualInterfaceTestHistory for more information on using the ListVirtualInterfaceTestHistory +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListVirtualInterfaceTestHistoryRequest method. +// req, resp := client.ListVirtualInterfaceTestHistoryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/ListVirtualInterfaceTestHistory +func (c *DirectConnect) ListVirtualInterfaceTestHistoryRequest(input *ListVirtualInterfaceTestHistoryInput) (req *request.Request, output *ListVirtualInterfaceTestHistoryOutput) { + op := &request.Operation{ + Name: opListVirtualInterfaceTestHistory, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListVirtualInterfaceTestHistoryInput{} + } + + output = &ListVirtualInterfaceTestHistoryOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListVirtualInterfaceTestHistory API operation for AWS Direct Connect. +// +// Lists the virtual interface failover test history. +// +// Returns awserr.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 Direct Connect's +// API operation ListVirtualInterfaceTestHistory for usage and error information. +// +// Returned Error Types: +// * ServerException +// A server-side error occurred. +// +// * ClientException +// One or more parameters are not valid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/ListVirtualInterfaceTestHistory +func (c *DirectConnect) ListVirtualInterfaceTestHistory(input *ListVirtualInterfaceTestHistoryInput) (*ListVirtualInterfaceTestHistoryOutput, error) { + req, out := c.ListVirtualInterfaceTestHistoryRequest(input) + return out, req.Send() +} + +// ListVirtualInterfaceTestHistoryWithContext is the same as ListVirtualInterfaceTestHistory with the addition of +// the ability to pass a context and additional request options. +// +// See ListVirtualInterfaceTestHistory for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DirectConnect) ListVirtualInterfaceTestHistoryWithContext(ctx aws.Context, input *ListVirtualInterfaceTestHistoryInput, opts ...request.Option) (*ListVirtualInterfaceTestHistoryOutput, error) { + req, out := c.ListVirtualInterfaceTestHistoryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opStartBgpFailoverTest = "StartBgpFailoverTest" + +// StartBgpFailoverTestRequest generates a "aws/request.Request" representing the +// client's request for the StartBgpFailoverTest operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See StartBgpFailoverTest for more information on using the StartBgpFailoverTest +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the StartBgpFailoverTestRequest method. +// req, resp := client.StartBgpFailoverTestRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/StartBgpFailoverTest +func (c *DirectConnect) StartBgpFailoverTestRequest(input *StartBgpFailoverTestInput) (req *request.Request, output *StartBgpFailoverTestOutput) { + op := &request.Operation{ + Name: opStartBgpFailoverTest, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &StartBgpFailoverTestInput{} + } + + output = &StartBgpFailoverTestOutput{} + req = c.newRequest(op, input, output) + return +} + +// StartBgpFailoverTest API operation for AWS Direct Connect. +// +// Starts the virtual interface failover test that verifies your configuration +// meets your resiliency requirements by placing the BGP peering session in +// the DOWN state. You can then send traffic to verify that there are no outages. +// +// You can run the test on public, private, transit, and hosted virtual interfaces. +// +// You can use ListVirtualInterfaceTestHistory (https://docs.aws.amazon.com/directconnect/latest/APIReference/API_ListVirtualInterfaceTestHistory.html) +// to view the virtual interface test history. +// +// If you need to stop the test before the test interval completes, use StopBgpFailoverTest +// (https://docs.aws.amazon.com/directconnect/latest/APIReference/API_StopBgpFailoverTest.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Direct Connect's +// API operation StartBgpFailoverTest for usage and error information. +// +// Returned Error Types: +// * ServerException +// A server-side error occurred. +// +// * ClientException +// One or more parameters are not valid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/StartBgpFailoverTest +func (c *DirectConnect) StartBgpFailoverTest(input *StartBgpFailoverTestInput) (*StartBgpFailoverTestOutput, error) { + req, out := c.StartBgpFailoverTestRequest(input) + return out, req.Send() +} + +// StartBgpFailoverTestWithContext is the same as StartBgpFailoverTest with the addition of +// the ability to pass a context and additional request options. +// +// See StartBgpFailoverTest for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DirectConnect) StartBgpFailoverTestWithContext(ctx aws.Context, input *StartBgpFailoverTestInput, opts ...request.Option) (*StartBgpFailoverTestOutput, error) { + req, out := c.StartBgpFailoverTestRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opStopBgpFailoverTest = "StopBgpFailoverTest" + +// StopBgpFailoverTestRequest generates a "aws/request.Request" representing the +// client's request for the StopBgpFailoverTest operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See StopBgpFailoverTest for more information on using the StopBgpFailoverTest +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the StopBgpFailoverTestRequest method. +// req, resp := client.StopBgpFailoverTestRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/StopBgpFailoverTest +func (c *DirectConnect) StopBgpFailoverTestRequest(input *StopBgpFailoverTestInput) (req *request.Request, output *StopBgpFailoverTestOutput) { + op := &request.Operation{ + Name: opStopBgpFailoverTest, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &StopBgpFailoverTestInput{} + } + + output = &StopBgpFailoverTestOutput{} + req = c.newRequest(op, input, output) + return +} + +// StopBgpFailoverTest API operation for AWS Direct Connect. +// +// Stops the virtual interface failover 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 Direct Connect's +// API operation StopBgpFailoverTest for usage and error information. +// +// Returned Error Types: +// * ServerException +// A server-side error occurred. +// +// * ClientException +// One or more parameters are not valid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/StopBgpFailoverTest +func (c *DirectConnect) StopBgpFailoverTest(input *StopBgpFailoverTestInput) (*StopBgpFailoverTestOutput, error) { + req, out := c.StopBgpFailoverTestRequest(input) + return out, req.Send() +} + +// StopBgpFailoverTestWithContext is the same as StopBgpFailoverTest with the addition of +// the ability to pass a context and additional request options. +// +// See StopBgpFailoverTest for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DirectConnect) StopBgpFailoverTestWithContext(ctx aws.Context, input *StopBgpFailoverTestInput, opts ...request.Option) (*StopBgpFailoverTestOutput, error) { + req, out := c.StopBgpFailoverTestRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opTagResource = "TagResource" // TagResourceRequest generates a "aws/request.Request" representing the @@ -4738,7 +5006,7 @@ func (c *DirectConnect) UpdateVirtualInterfaceAttributesRequest(input *UpdateVir // jumbo frames. Updating the connection disrupts network connectivity for all // virtual interfaces associated with the connection for up to 30 seconds. To // check whether your connection supports jumbo frames, call DescribeConnections. -// To check whether your virtual interface supports jumbo frames, call DescribeVirtualInterfaces. +// To check whether your virtual q interface supports jumbo frames, call DescribeVirtualInterfaces. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -9489,6 +9757,111 @@ func (s *Lag) SetTags(v []*Tag) *Lag { return s } +type ListVirtualInterfaceTestHistoryInput struct { + _ struct{} `type:"structure"` + + // The BGP peers that were placed in the DOWN state during the virtual interface + // failover test. + BgpPeers []*string `locationName:"bgpPeers" type:"list"` + + // The maximum number of results to return with a single call. To retrieve the + // remaining results, make another call with the returned nextToken value. + // + // If MaxResults is given a value larger than 100, only 100 results are returned. + MaxResults *int64 `locationName:"maxResults" type:"integer"` + + // The token for the next page of results. + NextToken *string `locationName:"nextToken" type:"string"` + + // The status of the virtual interface failover test. + Status *string `locationName:"status" type:"string"` + + // The ID of the virtual interface failover test. + TestId *string `locationName:"testId" type:"string"` + + // The ID of the virtual interface that was tested. + VirtualInterfaceId *string `locationName:"virtualInterfaceId" type:"string"` +} + +// String returns the string representation +func (s ListVirtualInterfaceTestHistoryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListVirtualInterfaceTestHistoryInput) GoString() string { + return s.String() +} + +// SetBgpPeers sets the BgpPeers field's value. +func (s *ListVirtualInterfaceTestHistoryInput) SetBgpPeers(v []*string) *ListVirtualInterfaceTestHistoryInput { + s.BgpPeers = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListVirtualInterfaceTestHistoryInput) SetMaxResults(v int64) *ListVirtualInterfaceTestHistoryInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListVirtualInterfaceTestHistoryInput) SetNextToken(v string) *ListVirtualInterfaceTestHistoryInput { + s.NextToken = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *ListVirtualInterfaceTestHistoryInput) SetStatus(v string) *ListVirtualInterfaceTestHistoryInput { + s.Status = &v + return s +} + +// SetTestId sets the TestId field's value. +func (s *ListVirtualInterfaceTestHistoryInput) SetTestId(v string) *ListVirtualInterfaceTestHistoryInput { + s.TestId = &v + return s +} + +// SetVirtualInterfaceId sets the VirtualInterfaceId field's value. +func (s *ListVirtualInterfaceTestHistoryInput) SetVirtualInterfaceId(v string) *ListVirtualInterfaceTestHistoryInput { + s.VirtualInterfaceId = &v + return s +} + +type ListVirtualInterfaceTestHistoryOutput struct { + _ struct{} `type:"structure"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` + + // The ID of the tested virtual interface. + VirtualInterfaceTestHistory []*VirtualInterfaceTestHistory `locationName:"virtualInterfaceTestHistory" type:"list"` +} + +// String returns the string representation +func (s ListVirtualInterfaceTestHistoryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListVirtualInterfaceTestHistoryOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListVirtualInterfaceTestHistoryOutput) SetNextToken(v string) *ListVirtualInterfaceTestHistoryOutput { + s.NextToken = &v + return s +} + +// SetVirtualInterfaceTestHistory sets the VirtualInterfaceTestHistory field's value. +func (s *ListVirtualInterfaceTestHistoryOutput) SetVirtualInterfaceTestHistory(v []*VirtualInterfaceTestHistory) *ListVirtualInterfaceTestHistoryOutput { + s.VirtualInterfaceTestHistory = v + return s +} + // Information about a Letter of Authorization - Connecting Facility Assignment // (LOA-CFA) for a connection. type Loa struct { @@ -9685,7 +10058,9 @@ type NewPrivateVirtualInterface struct { // The ID of the virtual private gateway. VirtualGatewayId *string `locationName:"virtualGatewayId" type:"string"` - // The name of the virtual interface assigned by the customer network. + // The name of the virtual interface assigned by the customer network. The name + // has a maximum of 100 characters. The following are valid characters: a-z, + // 0-9 and a hyphen (-). // // VirtualInterfaceName is a required field VirtualInterfaceName *string `locationName:"virtualInterfaceName" type:"string" required:"true"` @@ -9835,7 +10210,9 @@ type NewPrivateVirtualInterfaceAllocation struct { // The tags associated with the private virtual interface. Tags []*Tag `locationName:"tags" min:"1" type:"list"` - // The name of the virtual interface assigned by the customer network. + // The name of the virtual interface assigned by the customer network. The name + // has a maximum of 100 characters. The following are valid characters: a-z, + // 0-9 and a hyphen (-). // // VirtualInterfaceName is a required field VirtualInterfaceName *string `locationName:"virtualInterfaceName" type:"string" required:"true"` @@ -9973,7 +10350,9 @@ type NewPublicVirtualInterface struct { // The tags associated with the public virtual interface. Tags []*Tag `locationName:"tags" min:"1" type:"list"` - // The name of the virtual interface assigned by the customer network. + // The name of the virtual interface assigned by the customer network. The name + // has a maximum of 100 characters. The following are valid characters: a-z, + // 0-9 and a hyphen (-). // // VirtualInterfaceName is a required field VirtualInterfaceName *string `locationName:"virtualInterfaceName" type:"string" required:"true"` @@ -10111,7 +10490,9 @@ type NewPublicVirtualInterfaceAllocation struct { // The tags associated with the public virtual interface. Tags []*Tag `locationName:"tags" min:"1" type:"list"` - // The name of the virtual interface assigned by the customer network. + // The name of the virtual interface assigned by the customer network. The name + // has a maximum of 100 characters. The following are valid characters: a-z, + // 0-9 and a hyphen (-). // // VirtualInterfaceName is a required field VirtualInterfaceName *string `locationName:"virtualInterfaceName" type:"string" required:"true"` @@ -10250,7 +10631,9 @@ type NewTransitVirtualInterface struct { // The tags associated with the transitive virtual interface. Tags []*Tag `locationName:"tags" min:"1" type:"list"` - // The name of the virtual interface assigned by the customer network. + // The name of the virtual interface assigned by the customer network. The name + // has a maximum of 100 characters. The following are valid characters: a-z, + // 0-9 and a hyphen (-). VirtualInterfaceName *string `locationName:"virtualInterfaceName" type:"string"` // The ID of the VLAN. @@ -10379,7 +10762,9 @@ type NewTransitVirtualInterfaceAllocation struct { // The tags associated with the transitive virtual interface. Tags []*Tag `locationName:"tags" min:"1" type:"list"` - // The name of the virtual interface assigned by the customer network. + // The name of the virtual interface assigned by the customer network. The name + // has a maximum of 100 characters. The following are valid characters: a-z, + // 0-9 and a hyphen (-). VirtualInterfaceName *string `locationName:"virtualInterfaceName" type:"string"` // The ID of the VLAN. @@ -10588,6 +10973,150 @@ func (s *ServerException) RequestID() string { return s.RespMetadata.RequestID } +type StartBgpFailoverTestInput struct { + _ struct{} `type:"structure"` + + // The BGP peers to place in the DOWN state. + BgpPeers []*string `locationName:"bgpPeers" type:"list"` + + // The time in minutes that the virtual interface failover test will last. + // + // Maximum value: 180 minutes (3 hours). + // + // Default: 180 minutes (3 hours). + TestDurationInMinutes *int64 `locationName:"testDurationInMinutes" type:"integer"` + + // The ID of the virtual interface you want to test. + // + // VirtualInterfaceId is a required field + VirtualInterfaceId *string `locationName:"virtualInterfaceId" type:"string" required:"true"` +} + +// String returns the string representation +func (s StartBgpFailoverTestInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StartBgpFailoverTestInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StartBgpFailoverTestInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StartBgpFailoverTestInput"} + if s.VirtualInterfaceId == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualInterfaceId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBgpPeers sets the BgpPeers field's value. +func (s *StartBgpFailoverTestInput) SetBgpPeers(v []*string) *StartBgpFailoverTestInput { + s.BgpPeers = v + return s +} + +// SetTestDurationInMinutes sets the TestDurationInMinutes field's value. +func (s *StartBgpFailoverTestInput) SetTestDurationInMinutes(v int64) *StartBgpFailoverTestInput { + s.TestDurationInMinutes = &v + return s +} + +// SetVirtualInterfaceId sets the VirtualInterfaceId field's value. +func (s *StartBgpFailoverTestInput) SetVirtualInterfaceId(v string) *StartBgpFailoverTestInput { + s.VirtualInterfaceId = &v + return s +} + +type StartBgpFailoverTestOutput struct { + _ struct{} `type:"structure"` + + // Information about the virtual interface failover test. + VirtualInterfaceTest *VirtualInterfaceTestHistory `locationName:"virtualInterfaceTest" type:"structure"` +} + +// String returns the string representation +func (s StartBgpFailoverTestOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StartBgpFailoverTestOutput) GoString() string { + return s.String() +} + +// SetVirtualInterfaceTest sets the VirtualInterfaceTest field's value. +func (s *StartBgpFailoverTestOutput) SetVirtualInterfaceTest(v *VirtualInterfaceTestHistory) *StartBgpFailoverTestOutput { + s.VirtualInterfaceTest = v + return s +} + +type StopBgpFailoverTestInput struct { + _ struct{} `type:"structure"` + + // The ID of the virtual interface you no longer want to test. + // + // VirtualInterfaceId is a required field + VirtualInterfaceId *string `locationName:"virtualInterfaceId" type:"string" required:"true"` +} + +// String returns the string representation +func (s StopBgpFailoverTestInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopBgpFailoverTestInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StopBgpFailoverTestInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StopBgpFailoverTestInput"} + if s.VirtualInterfaceId == nil { + invalidParams.Add(request.NewErrParamRequired("VirtualInterfaceId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetVirtualInterfaceId sets the VirtualInterfaceId field's value. +func (s *StopBgpFailoverTestInput) SetVirtualInterfaceId(v string) *StopBgpFailoverTestInput { + s.VirtualInterfaceId = &v + return s +} + +type StopBgpFailoverTestOutput struct { + _ struct{} `type:"structure"` + + // Information about the virtual interface failover test. + VirtualInterfaceTest *VirtualInterfaceTestHistory `locationName:"virtualInterfaceTest" type:"structure"` +} + +// String returns the string representation +func (s StopBgpFailoverTestOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopBgpFailoverTestOutput) GoString() string { + return s.String() +} + +// SetVirtualInterfaceTest sets the VirtualInterfaceTest field's value. +func (s *StopBgpFailoverTestOutput) SetVirtualInterfaceTest(v *VirtualInterfaceTestHistory) *StopBgpFailoverTestOutput { + s.VirtualInterfaceTest = v + return s +} + // Information about a tag. type Tag struct { _ struct{} `type:"structure"` @@ -11079,7 +11608,9 @@ type UpdateVirtualInterfaceAttributesOutput struct { // The ID of the virtual interface. VirtualInterfaceId *string `locationName:"virtualInterfaceId" type:"string"` - // The name of the virtual interface assigned by the customer network. + // The name of the virtual interface assigned by the customer network. The name + // has a maximum of 100 characters. The following are valid characters: a-z, + // 0-9 and a hyphen (-). VirtualInterfaceName *string `locationName:"virtualInterfaceName" type:"string"` // The state of the virtual interface. The following are the possible values: @@ -11387,7 +11918,9 @@ type VirtualInterface struct { // The ID of the virtual interface. VirtualInterfaceId *string `locationName:"virtualInterfaceId" type:"string"` - // The name of the virtual interface assigned by the customer network. + // The name of the virtual interface assigned by the customer network. The name + // has a maximum of 100 characters. The following are valid characters: a-z, + // 0-9 and a hyphen (-). VirtualInterfaceName *string `locationName:"virtualInterfaceName" type:"string"` // The state of the virtual interface. The following are the possible values: @@ -11583,6 +12116,94 @@ func (s *VirtualInterface) SetVlan(v int64) *VirtualInterface { return s } +// Information about the virtual interface failover test. +type VirtualInterfaceTestHistory struct { + _ struct{} `type:"structure"` + + // The BGP peers that were put in the DOWN state as part of the virtual interface + // failover test. + BgpPeers []*string `locationName:"bgpPeers" type:"list"` + + // The time that the virtual interface moves out of the DOWN state. + EndTime *time.Time `locationName:"endTime" type:"timestamp"` + + // The owner ID of the tested virtual interface. + OwnerAccount *string `locationName:"ownerAccount" type:"string"` + + // The time that the virtual interface moves to the DOWN state. + StartTime *time.Time `locationName:"startTime" type:"timestamp"` + + // The status of the virtual interface failover test. + Status *string `locationName:"status" type:"string"` + + // The time that the virtual interface failover test ran in minutes. + TestDurationInMinutes *int64 `locationName:"testDurationInMinutes" type:"integer"` + + // The ID of the virtual interface failover test. + TestId *string `locationName:"testId" type:"string"` + + // The ID of the tested virtual interface. + VirtualInterfaceId *string `locationName:"virtualInterfaceId" type:"string"` +} + +// String returns the string representation +func (s VirtualInterfaceTestHistory) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s VirtualInterfaceTestHistory) GoString() string { + return s.String() +} + +// SetBgpPeers sets the BgpPeers field's value. +func (s *VirtualInterfaceTestHistory) SetBgpPeers(v []*string) *VirtualInterfaceTestHistory { + s.BgpPeers = v + return s +} + +// SetEndTime sets the EndTime field's value. +func (s *VirtualInterfaceTestHistory) SetEndTime(v time.Time) *VirtualInterfaceTestHistory { + s.EndTime = &v + return s +} + +// SetOwnerAccount sets the OwnerAccount field's value. +func (s *VirtualInterfaceTestHistory) SetOwnerAccount(v string) *VirtualInterfaceTestHistory { + s.OwnerAccount = &v + return s +} + +// SetStartTime sets the StartTime field's value. +func (s *VirtualInterfaceTestHistory) SetStartTime(v time.Time) *VirtualInterfaceTestHistory { + s.StartTime = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *VirtualInterfaceTestHistory) SetStatus(v string) *VirtualInterfaceTestHistory { + s.Status = &v + return s +} + +// SetTestDurationInMinutes sets the TestDurationInMinutes field's value. +func (s *VirtualInterfaceTestHistory) SetTestDurationInMinutes(v int64) *VirtualInterfaceTestHistory { + s.TestDurationInMinutes = &v + return s +} + +// SetTestId sets the TestId field's value. +func (s *VirtualInterfaceTestHistory) SetTestId(v string) *VirtualInterfaceTestHistory { + s.TestId = &v + return s +} + +// SetVirtualInterfaceId sets the VirtualInterfaceId field's value. +func (s *VirtualInterfaceTestHistory) SetVirtualInterfaceId(v string) *VirtualInterfaceTestHistory { + s.VirtualInterfaceId = &v + return s +} + const ( // AddressFamilyIpv4 is a AddressFamily enum value AddressFamilyIpv4 = "ipv4" @@ -11591,6 +12212,14 @@ const ( AddressFamilyIpv6 = "ipv6" ) +// AddressFamily_Values returns all elements of the AddressFamily enum +func AddressFamily_Values() []string { + return []string{ + AddressFamilyIpv4, + AddressFamilyIpv6, + } +} + const ( // BGPPeerStateVerifying is a BGPPeerState enum value BGPPeerStateVerifying = "verifying" @@ -11608,6 +12237,17 @@ const ( BGPPeerStateDeleted = "deleted" ) +// BGPPeerState_Values returns all elements of the BGPPeerState enum +func BGPPeerState_Values() []string { + return []string{ + BGPPeerStateVerifying, + BGPPeerStatePending, + BGPPeerStateAvailable, + BGPPeerStateDeleting, + BGPPeerStateDeleted, + } +} + const ( // BGPStatusUp is a BGPStatus enum value BGPStatusUp = "up" @@ -11619,6 +12259,15 @@ const ( BGPStatusUnknown = "unknown" ) +// BGPStatus_Values returns all elements of the BGPStatus enum +func BGPStatus_Values() []string { + return []string{ + BGPStatusUp, + BGPStatusDown, + BGPStatusUnknown, + } +} + const ( // ConnectionStateOrdering is a ConnectionState enum value ConnectionStateOrdering = "ordering" @@ -11648,6 +12297,21 @@ const ( ConnectionStateUnknown = "unknown" ) +// ConnectionState_Values returns all elements of the ConnectionState enum +func ConnectionState_Values() []string { + return []string{ + ConnectionStateOrdering, + ConnectionStateRequested, + ConnectionStatePending, + ConnectionStateAvailable, + ConnectionStateDown, + ConnectionStateDeleting, + ConnectionStateDeleted, + ConnectionStateRejected, + ConnectionStateUnknown, + } +} + const ( // GatewayAssociationProposalStateRequested is a GatewayAssociationProposalState enum value GatewayAssociationProposalStateRequested = "requested" @@ -11659,6 +12323,15 @@ const ( GatewayAssociationProposalStateDeleted = "deleted" ) +// GatewayAssociationProposalState_Values returns all elements of the GatewayAssociationProposalState enum +func GatewayAssociationProposalState_Values() []string { + return []string{ + GatewayAssociationProposalStateRequested, + GatewayAssociationProposalStateAccepted, + GatewayAssociationProposalStateDeleted, + } +} + const ( // GatewayAssociationStateAssociating is a GatewayAssociationState enum value GatewayAssociationStateAssociating = "associating" @@ -11676,6 +12349,17 @@ const ( GatewayAssociationStateUpdating = "updating" ) +// GatewayAssociationState_Values returns all elements of the GatewayAssociationState enum +func GatewayAssociationState_Values() []string { + return []string{ + GatewayAssociationStateAssociating, + GatewayAssociationStateAssociated, + GatewayAssociationStateDisassociating, + GatewayAssociationStateDisassociated, + GatewayAssociationStateUpdating, + } +} + const ( // GatewayAttachmentStateAttaching is a GatewayAttachmentState enum value GatewayAttachmentStateAttaching = "attaching" @@ -11690,6 +12374,16 @@ const ( GatewayAttachmentStateDetached = "detached" ) +// GatewayAttachmentState_Values returns all elements of the GatewayAttachmentState enum +func GatewayAttachmentState_Values() []string { + return []string{ + GatewayAttachmentStateAttaching, + GatewayAttachmentStateAttached, + GatewayAttachmentStateDetaching, + GatewayAttachmentStateDetached, + } +} + const ( // GatewayAttachmentTypeTransitVirtualInterface is a GatewayAttachmentType enum value GatewayAttachmentTypeTransitVirtualInterface = "TransitVirtualInterface" @@ -11698,6 +12392,14 @@ const ( GatewayAttachmentTypePrivateVirtualInterface = "PrivateVirtualInterface" ) +// GatewayAttachmentType_Values returns all elements of the GatewayAttachmentType enum +func GatewayAttachmentType_Values() []string { + return []string{ + GatewayAttachmentTypeTransitVirtualInterface, + GatewayAttachmentTypePrivateVirtualInterface, + } +} + const ( // GatewayStatePending is a GatewayState enum value GatewayStatePending = "pending" @@ -11712,6 +12414,16 @@ const ( GatewayStateDeleted = "deleted" ) +// GatewayState_Values returns all elements of the GatewayState enum +func GatewayState_Values() []string { + return []string{ + GatewayStatePending, + GatewayStateAvailable, + GatewayStateDeleting, + GatewayStateDeleted, + } +} + const ( // GatewayTypeVirtualPrivateGateway is a GatewayType enum value GatewayTypeVirtualPrivateGateway = "virtualPrivateGateway" @@ -11720,6 +12432,14 @@ const ( GatewayTypeTransitGateway = "transitGateway" ) +// GatewayType_Values returns all elements of the GatewayType enum +func GatewayType_Values() []string { + return []string{ + GatewayTypeVirtualPrivateGateway, + GatewayTypeTransitGateway, + } +} + const ( // HasLogicalRedundancyUnknown is a HasLogicalRedundancy enum value HasLogicalRedundancyUnknown = "unknown" @@ -11731,6 +12451,15 @@ const ( HasLogicalRedundancyNo = "no" ) +// HasLogicalRedundancy_Values returns all elements of the HasLogicalRedundancy enum +func HasLogicalRedundancy_Values() []string { + return []string{ + HasLogicalRedundancyUnknown, + HasLogicalRedundancyYes, + HasLogicalRedundancyNo, + } +} + const ( // InterconnectStateRequested is a InterconnectState enum value InterconnectStateRequested = "requested" @@ -11754,6 +12483,19 @@ const ( InterconnectStateUnknown = "unknown" ) +// InterconnectState_Values returns all elements of the InterconnectState enum +func InterconnectState_Values() []string { + return []string{ + InterconnectStateRequested, + InterconnectStatePending, + InterconnectStateAvailable, + InterconnectStateDown, + InterconnectStateDeleting, + InterconnectStateDeleted, + InterconnectStateUnknown, + } +} + const ( // LagStateRequested is a LagState enum value LagStateRequested = "requested" @@ -11777,11 +12519,31 @@ const ( LagStateUnknown = "unknown" ) +// LagState_Values returns all elements of the LagState enum +func LagState_Values() []string { + return []string{ + LagStateRequested, + LagStatePending, + LagStateAvailable, + LagStateDown, + LagStateDeleting, + LagStateDeleted, + LagStateUnknown, + } +} + const ( // LoaContentTypeApplicationPdf is a LoaContentType enum value LoaContentTypeApplicationPdf = "application/pdf" ) +// LoaContentType_Values returns all elements of the LoaContentType enum +func LoaContentType_Values() []string { + return []string{ + LoaContentTypeApplicationPdf, + } +} + const ( // VirtualInterfaceStateConfirming is a VirtualInterfaceState enum value VirtualInterfaceStateConfirming = "confirming" @@ -11810,3 +12572,18 @@ const ( // VirtualInterfaceStateUnknown is a VirtualInterfaceState enum value VirtualInterfaceStateUnknown = "unknown" ) + +// VirtualInterfaceState_Values returns all elements of the VirtualInterfaceState enum +func VirtualInterfaceState_Values() []string { + return []string{ + VirtualInterfaceStateConfirming, + VirtualInterfaceStateVerifying, + VirtualInterfaceStatePending, + VirtualInterfaceStateAvailable, + VirtualInterfaceStateDown, + VirtualInterfaceStateDeleting, + VirtualInterfaceStateDeleted, + VirtualInterfaceStateRejected, + VirtualInterfaceStateUnknown, + } +} 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 231dfd334d1..b53745a3019 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 @@ -14162,6 +14162,18 @@ const ( CertificateStateDeregisterFailed = "DeregisterFailed" ) +// CertificateState_Values returns all elements of the CertificateState enum +func CertificateState_Values() []string { + return []string{ + CertificateStateRegistering, + CertificateStateRegistered, + CertificateStateRegisterFailed, + CertificateStateDeregistering, + CertificateStateDeregistered, + CertificateStateDeregisterFailed, + } +} + const ( // DirectoryEditionEnterprise is a DirectoryEdition enum value DirectoryEditionEnterprise = "Enterprise" @@ -14170,6 +14182,14 @@ const ( DirectoryEditionStandard = "Standard" ) +// DirectoryEdition_Values returns all elements of the DirectoryEdition enum +func DirectoryEdition_Values() []string { + return []string{ + DirectoryEditionEnterprise, + DirectoryEditionStandard, + } +} + const ( // DirectorySizeSmall is a DirectorySize enum value DirectorySizeSmall = "Small" @@ -14178,6 +14198,14 @@ const ( DirectorySizeLarge = "Large" ) +// DirectorySize_Values returns all elements of the DirectorySize enum +func DirectorySize_Values() []string { + return []string{ + DirectorySizeSmall, + DirectorySizeLarge, + } +} + const ( // DirectoryStageRequested is a DirectoryStage enum value DirectoryStageRequested = "Requested" @@ -14213,6 +14241,23 @@ const ( DirectoryStageFailed = "Failed" ) +// DirectoryStage_Values returns all elements of the DirectoryStage enum +func DirectoryStage_Values() []string { + return []string{ + DirectoryStageRequested, + DirectoryStageCreating, + DirectoryStageCreated, + DirectoryStageActive, + DirectoryStageInoperable, + DirectoryStageImpaired, + DirectoryStageRestoring, + DirectoryStageRestoreFailed, + DirectoryStageDeleting, + DirectoryStageDeleted, + DirectoryStageFailed, + } +} + const ( // DirectoryTypeSimpleAd is a DirectoryType enum value DirectoryTypeSimpleAd = "SimpleAD" @@ -14227,6 +14272,16 @@ const ( DirectoryTypeSharedMicrosoftAd = "SharedMicrosoftAD" ) +// DirectoryType_Values returns all elements of the DirectoryType enum +func DirectoryType_Values() []string { + return []string{ + DirectoryTypeSimpleAd, + DirectoryTypeAdconnector, + DirectoryTypeMicrosoftAd, + DirectoryTypeSharedMicrosoftAd, + } +} + const ( // DomainControllerStatusCreating is a DomainControllerStatus enum value DomainControllerStatusCreating = "Creating" @@ -14250,6 +14305,19 @@ const ( DomainControllerStatusFailed = "Failed" ) +// DomainControllerStatus_Values returns all elements of the DomainControllerStatus enum +func DomainControllerStatus_Values() []string { + return []string{ + DomainControllerStatusCreating, + DomainControllerStatusActive, + DomainControllerStatusImpaired, + DomainControllerStatusRestoring, + DomainControllerStatusDeleting, + DomainControllerStatusDeleted, + DomainControllerStatusFailed, + } +} + const ( // IpRouteStatusMsgAdding is a IpRouteStatusMsg enum value IpRouteStatusMsgAdding = "Adding" @@ -14270,6 +14338,18 @@ const ( IpRouteStatusMsgRemoveFailed = "RemoveFailed" ) +// IpRouteStatusMsg_Values returns all elements of the IpRouteStatusMsg enum +func IpRouteStatusMsg_Values() []string { + return []string{ + IpRouteStatusMsgAdding, + IpRouteStatusMsgAdded, + IpRouteStatusMsgRemoving, + IpRouteStatusMsgRemoved, + IpRouteStatusMsgAddFailed, + IpRouteStatusMsgRemoveFailed, + } +} + const ( // LDAPSStatusEnabling is a LDAPSStatus enum value LDAPSStatusEnabling = "Enabling" @@ -14284,11 +14364,28 @@ const ( LDAPSStatusDisabled = "Disabled" ) +// LDAPSStatus_Values returns all elements of the LDAPSStatus enum +func LDAPSStatus_Values() []string { + return []string{ + LDAPSStatusEnabling, + LDAPSStatusEnabled, + LDAPSStatusEnableFailed, + LDAPSStatusDisabled, + } +} + const ( // LDAPSTypeClient is a LDAPSType enum value LDAPSTypeClient = "Client" ) +// LDAPSType_Values returns all elements of the LDAPSType enum +func LDAPSType_Values() []string { + return []string{ + LDAPSTypeClient, + } +} + const ( // RadiusAuthenticationProtocolPap is a RadiusAuthenticationProtocol enum value RadiusAuthenticationProtocolPap = "PAP" @@ -14303,6 +14400,16 @@ const ( RadiusAuthenticationProtocolMsChapv2 = "MS-CHAPv2" ) +// RadiusAuthenticationProtocol_Values returns all elements of the RadiusAuthenticationProtocol enum +func RadiusAuthenticationProtocol_Values() []string { + return []string{ + RadiusAuthenticationProtocolPap, + RadiusAuthenticationProtocolChap, + RadiusAuthenticationProtocolMsChapv1, + RadiusAuthenticationProtocolMsChapv2, + } +} + const ( // RadiusStatusCreating is a RadiusStatus enum value RadiusStatusCreating = "Creating" @@ -14314,11 +14421,27 @@ const ( RadiusStatusFailed = "Failed" ) +// RadiusStatus_Values returns all elements of the RadiusStatus enum +func RadiusStatus_Values() []string { + return []string{ + RadiusStatusCreating, + RadiusStatusCompleted, + RadiusStatusFailed, + } +} + const ( // ReplicationScopeDomain is a ReplicationScope enum value ReplicationScopeDomain = "Domain" ) +// ReplicationScope_Values returns all elements of the ReplicationScope enum +func ReplicationScope_Values() []string { + return []string{ + ReplicationScopeDomain, + } +} + const ( // SchemaExtensionStatusInitializing is a SchemaExtensionStatus enum value SchemaExtensionStatusInitializing = "Initializing" @@ -14348,6 +14471,21 @@ const ( SchemaExtensionStatusCompleted = "Completed" ) +// SchemaExtensionStatus_Values returns all elements of the SchemaExtensionStatus enum +func SchemaExtensionStatus_Values() []string { + return []string{ + SchemaExtensionStatusInitializing, + SchemaExtensionStatusCreatingSnapshot, + SchemaExtensionStatusUpdatingSchema, + SchemaExtensionStatusReplicating, + SchemaExtensionStatusCancelInProgress, + SchemaExtensionStatusRollbackInProgress, + SchemaExtensionStatusCancelled, + SchemaExtensionStatusFailed, + SchemaExtensionStatusCompleted, + } +} + const ( // SelectiveAuthEnabled is a SelectiveAuth enum value SelectiveAuthEnabled = "Enabled" @@ -14356,6 +14494,14 @@ const ( SelectiveAuthDisabled = "Disabled" ) +// SelectiveAuth_Values returns all elements of the SelectiveAuth enum +func SelectiveAuth_Values() []string { + return []string{ + SelectiveAuthEnabled, + SelectiveAuthDisabled, + } +} + const ( // ShareMethodOrganizations is a ShareMethod enum value ShareMethodOrganizations = "ORGANIZATIONS" @@ -14364,6 +14510,14 @@ const ( ShareMethodHandshake = "HANDSHAKE" ) +// ShareMethod_Values returns all elements of the ShareMethod enum +func ShareMethod_Values() []string { + return []string{ + ShareMethodOrganizations, + ShareMethodHandshake, + } +} + const ( // ShareStatusShared is a ShareStatus enum value ShareStatusShared = "Shared" @@ -14393,6 +14547,21 @@ const ( ShareStatusDeleting = "Deleting" ) +// ShareStatus_Values returns all elements of the ShareStatus enum +func ShareStatus_Values() []string { + return []string{ + ShareStatusShared, + ShareStatusPendingAcceptance, + ShareStatusRejected, + ShareStatusRejecting, + ShareStatusRejectFailed, + ShareStatusSharing, + ShareStatusShareFailed, + ShareStatusDeleted, + ShareStatusDeleting, + } +} + const ( // SnapshotStatusCreating is a SnapshotStatus enum value SnapshotStatusCreating = "Creating" @@ -14404,6 +14573,15 @@ const ( SnapshotStatusFailed = "Failed" ) +// SnapshotStatus_Values returns all elements of the SnapshotStatus enum +func SnapshotStatus_Values() []string { + return []string{ + SnapshotStatusCreating, + SnapshotStatusCompleted, + SnapshotStatusFailed, + } +} + const ( // SnapshotTypeAuto is a SnapshotType enum value SnapshotTypeAuto = "Auto" @@ -14412,11 +14590,26 @@ const ( SnapshotTypeManual = "Manual" ) +// SnapshotType_Values returns all elements of the SnapshotType enum +func SnapshotType_Values() []string { + return []string{ + SnapshotTypeAuto, + SnapshotTypeManual, + } +} + const ( // TargetTypeAccount is a TargetType enum value TargetTypeAccount = "ACCOUNT" ) +// TargetType_Values returns all elements of the TargetType enum +func TargetType_Values() []string { + return []string{ + TargetTypeAccount, + } +} + const ( // TopicStatusRegistered is a TopicStatus enum value TopicStatusRegistered = "Registered" @@ -14431,6 +14624,16 @@ const ( TopicStatusDeleted = "Deleted" ) +// TopicStatus_Values returns all elements of the TopicStatus enum +func TopicStatus_Values() []string { + return []string{ + TopicStatusRegistered, + TopicStatusTopicnotfound, + TopicStatusFailed, + TopicStatusDeleted, + } +} + const ( // TrustDirectionOneWayOutgoing is a TrustDirection enum value TrustDirectionOneWayOutgoing = "One-Way: Outgoing" @@ -14442,6 +14645,15 @@ const ( TrustDirectionTwoWay = "Two-Way" ) +// TrustDirection_Values returns all elements of the TrustDirection enum +func TrustDirection_Values() []string { + return []string{ + TrustDirectionOneWayOutgoing, + TrustDirectionOneWayIncoming, + TrustDirectionTwoWay, + } +} + const ( // TrustStateCreating is a TrustState enum value TrustStateCreating = "Creating" @@ -14477,6 +14689,23 @@ const ( TrustStateFailed = "Failed" ) +// TrustState_Values returns all elements of the TrustState enum +func TrustState_Values() []string { + return []string{ + TrustStateCreating, + TrustStateCreated, + TrustStateVerifying, + TrustStateVerifyFailed, + TrustStateVerified, + TrustStateUpdating, + TrustStateUpdateFailed, + TrustStateUpdated, + TrustStateDeleting, + TrustStateDeleted, + TrustStateFailed, + } +} + const ( // TrustTypeForest is a TrustType enum value TrustTypeForest = "Forest" @@ -14484,3 +14713,11 @@ const ( // TrustTypeExternal is a TrustType enum value TrustTypeExternal = "External" ) + +// TrustType_Values returns all elements of the TrustType enum +func TrustType_Values() []string { + return []string{ + TrustTypeForest, + TrustTypeExternal, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/dlm/api.go b/vendor/github.com/aws/aws-sdk-go/service/dlm/api.go index 4ad17a35eda..0450eebcc94 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dlm/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dlm/api.go @@ -830,23 +830,29 @@ func (s *CreateLifecyclePolicyOutput) SetPolicyId(v string) *CreateLifecyclePoli } // Specifies when to create snapshots of EBS volumes. +// +// You must specify either a Cron expression or an interval, interval unit, +// and start time. You cannot specify both. type CreateRule struct { _ struct{} `type:"structure"` + // The schedule, as a Cron expression. The schedule interval must be between + // 1 hour and 1 year. For more information, see Cron expressions (https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html#CronExpressions) + // in the Amazon CloudWatch User Guide. + CronExpression *string `min:"17" type:"string"` + // The interval between snapshots. The supported values are 1, 2, 3, 4, 6, 8, // 12, and 24. - // - // Interval is a required field - Interval *int64 `min:"1" type:"integer" required:"true"` + Interval *int64 `min:"1" type:"integer"` // The interval unit. - // - // IntervalUnit is a required field - IntervalUnit *string `type:"string" required:"true" enum:"IntervalUnitValues"` + IntervalUnit *string `type:"string" enum:"IntervalUnitValues"` // The time, in UTC, to start the operation. The supported format is hh:mm. // // The operation occurs within a one-hour window following the specified time. + // If you do not specify a time, Amazon DLM selects a time within the next 24 + // hours. Times []*string `type:"list"` } @@ -863,15 +869,12 @@ func (s CreateRule) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *CreateRule) Validate() error { invalidParams := request.ErrInvalidParams{Context: "CreateRule"} - if s.Interval == nil { - invalidParams.Add(request.NewErrParamRequired("Interval")) + if s.CronExpression != nil && len(*s.CronExpression) < 17 { + invalidParams.Add(request.NewErrParamMinLen("CronExpression", 17)) } if s.Interval != nil && *s.Interval < 1 { invalidParams.Add(request.NewErrParamMinValue("Interval", 1)) } - if s.IntervalUnit == nil { - invalidParams.Add(request.NewErrParamRequired("IntervalUnit")) - } if invalidParams.Len() > 0 { return invalidParams @@ -879,6 +882,12 @@ func (s *CreateRule) Validate() error { return nil } +// SetCronExpression sets the CronExpression field's value. +func (s *CreateRule) SetCronExpression(v string) *CreateRule { + s.CronExpression = &v + return s +} + // SetInterval sets the Interval field's value. func (s *CreateRule) SetInterval(v int64) *CreateRule { s.Interval = &v @@ -1777,7 +1786,8 @@ type PolicyDetails struct { // is EBS_SNAPSHOT_MANAGEMENT. PolicyType *string `type:"string" enum:"PolicyTypeValues"` - // The resource type. + // The resource type. Use VOLUME to create snapshots of individual volumes or + // use INSTANCE to create multi-volume snapshots from the volumes for an instance. ResourceTypes []*string `min:"1" type:"list"` // The schedule of policy-defined actions. @@ -2443,16 +2453,39 @@ const ( GettablePolicyStateValuesError = "ERROR" ) +// GettablePolicyStateValues_Values returns all elements of the GettablePolicyStateValues enum +func GettablePolicyStateValues_Values() []string { + return []string{ + GettablePolicyStateValuesEnabled, + GettablePolicyStateValuesDisabled, + GettablePolicyStateValuesError, + } +} + const ( // IntervalUnitValuesHours is a IntervalUnitValues enum value IntervalUnitValuesHours = "HOURS" ) +// IntervalUnitValues_Values returns all elements of the IntervalUnitValues enum +func IntervalUnitValues_Values() []string { + return []string{ + IntervalUnitValuesHours, + } +} + const ( // PolicyTypeValuesEbsSnapshotManagement is a PolicyTypeValues enum value PolicyTypeValuesEbsSnapshotManagement = "EBS_SNAPSHOT_MANAGEMENT" ) +// PolicyTypeValues_Values returns all elements of the PolicyTypeValues enum +func PolicyTypeValues_Values() []string { + return []string{ + PolicyTypeValuesEbsSnapshotManagement, + } +} + const ( // ResourceTypeValuesVolume is a ResourceTypeValues enum value ResourceTypeValuesVolume = "VOLUME" @@ -2461,6 +2494,14 @@ const ( ResourceTypeValuesInstance = "INSTANCE" ) +// ResourceTypeValues_Values returns all elements of the ResourceTypeValues enum +func ResourceTypeValues_Values() []string { + return []string{ + ResourceTypeValuesVolume, + ResourceTypeValuesInstance, + } +} + const ( // RetentionIntervalUnitValuesDays is a RetentionIntervalUnitValues enum value RetentionIntervalUnitValuesDays = "DAYS" @@ -2475,6 +2516,16 @@ const ( RetentionIntervalUnitValuesYears = "YEARS" ) +// RetentionIntervalUnitValues_Values returns all elements of the RetentionIntervalUnitValues enum +func RetentionIntervalUnitValues_Values() []string { + return []string{ + RetentionIntervalUnitValuesDays, + RetentionIntervalUnitValuesWeeks, + RetentionIntervalUnitValuesMonths, + RetentionIntervalUnitValuesYears, + } +} + const ( // SettablePolicyStateValuesEnabled is a SettablePolicyStateValues enum value SettablePolicyStateValuesEnabled = "ENABLED" @@ -2482,3 +2533,11 @@ const ( // SettablePolicyStateValuesDisabled is a SettablePolicyStateValues enum value SettablePolicyStateValuesDisabled = "DISABLED" ) + +// SettablePolicyStateValues_Values returns all elements of the SettablePolicyStateValues enum +func SettablePolicyStateValues_Values() []string { + return []string{ + SettablePolicyStateValuesEnabled, + SettablePolicyStateValuesDisabled, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/docdb/api.go b/vendor/github.com/aws/aws-sdk-go/service/docdb/api.go index c95a1db72a9..bda1563ca85 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/docdb/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/docdb/api.go @@ -11628,6 +11628,14 @@ const ( ApplyMethodPendingReboot = "pending-reboot" ) +// ApplyMethod_Values returns all elements of the ApplyMethod enum +func ApplyMethod_Values() []string { + return []string{ + ApplyMethodImmediate, + ApplyMethodPendingReboot, + } +} + const ( // SourceTypeDbInstance is a SourceType enum value SourceTypeDbInstance = "db-instance" @@ -11647,3 +11655,15 @@ const ( // SourceTypeDbClusterSnapshot is a SourceType enum value SourceTypeDbClusterSnapshot = "db-cluster-snapshot" ) + +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeDbInstance, + SourceTypeDbParameterGroup, + SourceTypeDbSecurityGroup, + SourceTypeDbSnapshot, + SourceTypeDbCluster, + SourceTypeDbClusterSnapshot, + } +} 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 e7983fa8e3d..e1e0b1b8f93 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 @@ -61,9 +61,9 @@ func (c *DynamoDB) BatchGetItemRequest(input *BatchGetItemInput) (req *request.R output = &BatchGetItemOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -282,9 +282,9 @@ func (c *DynamoDB) BatchWriteItemRequest(input *BatchWriteItemInput) (req *reque output = &BatchWriteItemOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -476,9 +476,9 @@ func (c *DynamoDB) CreateBackupRequest(input *CreateBackupInput) (req *request.R output = &CreateBackupOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -636,9 +636,9 @@ func (c *DynamoDB) CreateGlobalTableRequest(input *CreateGlobalTableInput) (req output = &CreateGlobalTableOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -670,7 +670,7 @@ func (c *DynamoDB) CreateGlobalTableRequest(input *CreateGlobalTableInput) (req // relationship between two or more DynamoDB tables with the same table name // in the provided Regions. // -// This method only applies to Version 2017.11.29 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html) +// This operation only applies to Version 2017.11.29 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html) // of global tables. // // If you want to add a new replica table to a global table, each of the following @@ -693,6 +693,14 @@ func (c *DynamoDB) CreateGlobalTableRequest(input *CreateGlobalTableInput) (req // * The global secondary indexes must have the same hash key and sort key // (if present). // +// If local secondary indexes are specified, then the following conditions must +// also be met: +// +// * The local secondary indexes must have the same name. +// +// * The local secondary indexes must have the same hash key and sort key +// (if present). +// // Write capacity settings should be set consistently across your replica tables // and secondary indexes. DynamoDB strongly recommends enabling auto scaling // to manage the write capacity settings for all of your global tables replicas @@ -796,9 +804,9 @@ func (c *DynamoDB) CreateTableRequest(input *CreateTableInput) (req *request.Req output = &CreateTableOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -933,9 +941,9 @@ func (c *DynamoDB) DeleteBackupRequest(input *DeleteBackupInput) (req *request.R output = &DeleteBackupOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -1060,9 +1068,9 @@ func (c *DynamoDB) DeleteItemRequest(input *DeleteItemInput) (req *request.Reque output = &DeleteItemOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -1204,9 +1212,9 @@ func (c *DynamoDB) DeleteTableRequest(input *DeleteTableInput) (req *request.Req output = &DeleteTableOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -1348,9 +1356,9 @@ func (c *DynamoDB) DescribeBackupRequest(input *DescribeBackupInput) (req *reque output = &DescribeBackupOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -1457,9 +1465,9 @@ func (c *DynamoDB) DescribeContinuousBackupsRequest(input *DescribeContinuousBac output = &DescribeContinuousBackupsOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -1807,9 +1815,9 @@ func (c *DynamoDB) DescribeGlobalTableRequest(input *DescribeGlobalTableInput) ( output = &DescribeGlobalTableOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -1839,8 +1847,10 @@ func (c *DynamoDB) DescribeGlobalTableRequest(input *DescribeGlobalTableInput) ( // // Returns information about the specified global table. // -// This method only applies to Version 2017.11.29 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html) -// of global tables. +// This operation only applies to Version 2017.11.29 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html) +// of global tables. If you are using global tables Version 2019.11.21 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V2.html) +// you can use DescribeTable (https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeTable.html) +// instead. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1917,9 +1927,9 @@ func (c *DynamoDB) DescribeGlobalTableSettingsRequest(input *DescribeGlobalTable output = &DescribeGlobalTableSettingsOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -1949,7 +1959,7 @@ func (c *DynamoDB) DescribeGlobalTableSettingsRequest(input *DescribeGlobalTable // // Describes Region-specific settings for a global table. // -// This method only applies to Version 2017.11.29 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html) +// This operation only applies to Version 2017.11.29 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html) // of global tables. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -2027,9 +2037,9 @@ func (c *DynamoDB) DescribeLimitsRequest(input *DescribeLimitsInput) (req *reque output = &DescribeLimitsOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -2188,9 +2198,9 @@ func (c *DynamoDB) DescribeTableRequest(input *DescribeTableInput) (req *request output = &DescribeTableOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -2311,7 +2321,7 @@ func (c *DynamoDB) DescribeTableReplicaAutoScalingRequest(input *DescribeTableRe // // Describes auto scaling settings across replicas of the global table at once. // -// This method only applies to Version 2019.11.21 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V2.html) +// This operation only applies to Version 2019.11.21 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V2.html) // of global tables. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -2390,9 +2400,9 @@ func (c *DynamoDB) DescribeTimeToLiveRequest(input *DescribeTimeToLiveInput) (re output = &DescribeTimeToLiveOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -2498,9 +2508,9 @@ func (c *DynamoDB) GetItemRequest(input *GetItemInput) (req *request.Request, ou output = &GetItemOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -2626,9 +2636,9 @@ func (c *DynamoDB) ListBackupsRequest(input *ListBackupsInput) (req *request.Req output = &ListBackupsOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -2880,9 +2890,9 @@ func (c *DynamoDB) ListGlobalTablesRequest(input *ListGlobalTablesInput) (req *r output = &ListGlobalTablesOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -2912,7 +2922,7 @@ func (c *DynamoDB) ListGlobalTablesRequest(input *ListGlobalTablesInput) (req *r // // Lists all global tables that have a replica in the specified Region. // -// This method only applies to Version 2017.11.29 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html) +// This operation only applies to Version 2017.11.29 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html) // of global tables. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -2993,9 +3003,9 @@ func (c *DynamoDB) ListTablesRequest(input *ListTablesInput) (req *request.Reque output = &ListTablesOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -3151,9 +3161,9 @@ func (c *DynamoDB) ListTagsOfResourceRequest(input *ListTagsOfResourceInput) (re output = &ListTagsOfResourceOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -3263,9 +3273,9 @@ func (c *DynamoDB) PutItemRequest(input *PutItemInput) (req *request.Request, ou output = &PutItemOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -3325,9 +3335,15 @@ func (c *DynamoDB) PutItemRequest(input *PutItemInput) (req *request.Request, ou // * PutItem in the AWS SDK for Ruby V2 (http://docs.aws.amazon.com/goto/SdkForRubyV2/dynamodb-2012-08-10/PutItem) // // When you add an item, the primary key attributes are the only required attributes. -// Attribute values cannot be null. String and Binary type attributes must have -// lengths greater than zero. Set type attributes cannot be empty. Requests -// with empty values will be rejected with a ValidationException exception. +// Attribute values cannot be null. +// +// Empty String and Binary attribute values are allowed. Attribute values of +// type String and Binary must have a length greater than zero if the attribute +// is used as a key attribute for a table or index. Set type attributes cannot +// be empty. +// +// Invalid Requests with empty values will be rejected with a ValidationException +// exception. // // To prevent a new item from replacing an existing item, use a conditional // expression that contains the attribute_not_exists function with the name @@ -3443,9 +3459,9 @@ func (c *DynamoDB) QueryRequest(input *QueryInput) (req *request.Request, output output = &QueryOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -3663,9 +3679,9 @@ func (c *DynamoDB) RestoreTableFromBackupRequest(input *RestoreTableFromBackupIn output = &RestoreTableFromBackupOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -3811,9 +3827,9 @@ func (c *DynamoDB) RestoreTableToPointInTimeRequest(input *RestoreTableToPointIn output = &RestoreTableToPointInTimeOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -3987,9 +4003,9 @@ func (c *DynamoDB) ScanRequest(input *ScanInput) (req *request.Request, output * output = &ScanOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -4188,9 +4204,9 @@ func (c *DynamoDB) TagResourceRequest(input *TagResourceInput) (req *request.Req output = &TagResourceOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -4321,9 +4337,9 @@ func (c *DynamoDB) TransactGetItemsRequest(input *TransactGetItemsInput) (req *r output = &TransactGetItemsOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -4548,9 +4564,9 @@ func (c *DynamoDB) TransactWriteItemsRequest(input *TransactWriteItemsInput) (re output = &TransactWriteItemsOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -4817,9 +4833,9 @@ func (c *DynamoDB) UntagResourceRequest(input *UntagResourceInput) (req *request output = &UntagResourceOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -4948,9 +4964,9 @@ func (c *DynamoDB) UpdateContinuousBackupsRequest(input *UpdateContinuousBackups output = &UpdateContinuousBackupsOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -5152,9 +5168,9 @@ func (c *DynamoDB) UpdateGlobalTableRequest(input *UpdateGlobalTableInput) (req output = &UpdateGlobalTableOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -5288,9 +5304,9 @@ func (c *DynamoDB) UpdateGlobalTableSettingsRequest(input *UpdateGlobalTableSett output = &UpdateGlobalTableSettingsOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -5420,9 +5436,9 @@ func (c *DynamoDB) UpdateItemRequest(input *UpdateItemInput) (req *request.Reque output = &UpdateItemOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -5558,9 +5574,9 @@ func (c *DynamoDB) UpdateTableRequest(input *UpdateTableInput) (req *request.Req output = &UpdateTableOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -5709,7 +5725,7 @@ func (c *DynamoDB) UpdateTableReplicaAutoScalingRequest(input *UpdateTableReplic // // Updates auto scaling settings on your global tables at once. // -// This method only applies to Version 2019.11.21 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V2.html) +// This operation only applies to Version 2019.11.21 (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V2.html) // of global tables. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -5807,9 +5823,9 @@ func (c *DynamoDB) UpdateTimeToLiveRequest(input *UpdateTimeToLiveInput) (req *r output = &UpdateTimeToLiveOutput{} req = c.newRequest(op, input, output) - // if a custom endpoint is provided for the request, - // we skip endpoint discovery workflow - if req.Config.Endpoint == nil { + // if custom endpoint for the request is set to a non empty string, + // we skip the endpoint discovery workflow. + if req.Config.Endpoint == nil || *req.Config.Endpoint == "" { if aws.BoolValue(req.Config.EnableEndpointDiscovery) { de := discovererDescribeEndpoints{ Required: false, @@ -13564,6 +13580,10 @@ type PutItemInput struct { // types for those attributes must match those of the schema in the table's // attribute definition. // + // Empty String and Binary attribute values are allowed. Attribute values of + // type String and Binary must have a length greater than zero if the attribute + // is used as a key attribute for a table or index. + // // For more information about primary keys, see Primary Key (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html#HowItWorks.CoreComponents.PrimaryKey) // in the Amazon DynamoDB Developer Guide. // @@ -19865,6 +19885,15 @@ const ( AttributeActionDelete = "DELETE" ) +// AttributeAction_Values returns all elements of the AttributeAction enum +func AttributeAction_Values() []string { + return []string{ + AttributeActionAdd, + AttributeActionPut, + AttributeActionDelete, + } +} + const ( // BackupStatusCreating is a BackupStatus enum value BackupStatusCreating = "CREATING" @@ -19876,6 +19905,15 @@ const ( BackupStatusAvailable = "AVAILABLE" ) +// BackupStatus_Values returns all elements of the BackupStatus enum +func BackupStatus_Values() []string { + return []string{ + BackupStatusCreating, + BackupStatusDeleted, + BackupStatusAvailable, + } +} + const ( // BackupTypeUser is a BackupType enum value BackupTypeUser = "USER" @@ -19887,6 +19925,15 @@ const ( BackupTypeAwsBackup = "AWS_BACKUP" ) +// BackupType_Values returns all elements of the BackupType enum +func BackupType_Values() []string { + return []string{ + BackupTypeUser, + BackupTypeSystem, + BackupTypeAwsBackup, + } +} + const ( // BackupTypeFilterUser is a BackupTypeFilter enum value BackupTypeFilterUser = "USER" @@ -19901,6 +19948,16 @@ const ( BackupTypeFilterAll = "ALL" ) +// BackupTypeFilter_Values returns all elements of the BackupTypeFilter enum +func BackupTypeFilter_Values() []string { + return []string{ + BackupTypeFilterUser, + BackupTypeFilterSystem, + BackupTypeFilterAwsBackup, + BackupTypeFilterAll, + } +} + const ( // BillingModeProvisioned is a BillingMode enum value BillingModeProvisioned = "PROVISIONED" @@ -19909,6 +19966,14 @@ const ( BillingModePayPerRequest = "PAY_PER_REQUEST" ) +// BillingMode_Values returns all elements of the BillingMode enum +func BillingMode_Values() []string { + return []string{ + BillingModeProvisioned, + BillingModePayPerRequest, + } +} + const ( // ComparisonOperatorEq is a ComparisonOperator enum value ComparisonOperatorEq = "EQ" @@ -19950,6 +20015,25 @@ const ( ComparisonOperatorBeginsWith = "BEGINS_WITH" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorEq, + ComparisonOperatorNe, + ComparisonOperatorIn, + ComparisonOperatorLe, + ComparisonOperatorLt, + ComparisonOperatorGe, + ComparisonOperatorGt, + ComparisonOperatorBetween, + ComparisonOperatorNotNull, + ComparisonOperatorNull, + ComparisonOperatorContains, + ComparisonOperatorNotContains, + ComparisonOperatorBeginsWith, + } +} + const ( // ConditionalOperatorAnd is a ConditionalOperator enum value ConditionalOperatorAnd = "AND" @@ -19958,6 +20042,14 @@ const ( ConditionalOperatorOr = "OR" ) +// ConditionalOperator_Values returns all elements of the ConditionalOperator enum +func ConditionalOperator_Values() []string { + return []string{ + ConditionalOperatorAnd, + ConditionalOperatorOr, + } +} + const ( // ContinuousBackupsStatusEnabled is a ContinuousBackupsStatus enum value ContinuousBackupsStatusEnabled = "ENABLED" @@ -19966,6 +20058,14 @@ const ( ContinuousBackupsStatusDisabled = "DISABLED" ) +// ContinuousBackupsStatus_Values returns all elements of the ContinuousBackupsStatus enum +func ContinuousBackupsStatus_Values() []string { + return []string{ + ContinuousBackupsStatusEnabled, + ContinuousBackupsStatusDisabled, + } +} + const ( // ContributorInsightsActionEnable is a ContributorInsightsAction enum value ContributorInsightsActionEnable = "ENABLE" @@ -19974,6 +20074,14 @@ const ( ContributorInsightsActionDisable = "DISABLE" ) +// ContributorInsightsAction_Values returns all elements of the ContributorInsightsAction enum +func ContributorInsightsAction_Values() []string { + return []string{ + ContributorInsightsActionEnable, + ContributorInsightsActionDisable, + } +} + const ( // ContributorInsightsStatusEnabling is a ContributorInsightsStatus enum value ContributorInsightsStatusEnabling = "ENABLING" @@ -19991,6 +20099,17 @@ const ( ContributorInsightsStatusFailed = "FAILED" ) +// ContributorInsightsStatus_Values returns all elements of the ContributorInsightsStatus enum +func ContributorInsightsStatus_Values() []string { + return []string{ + ContributorInsightsStatusEnabling, + ContributorInsightsStatusEnabled, + ContributorInsightsStatusDisabling, + ContributorInsightsStatusDisabled, + ContributorInsightsStatusFailed, + } +} + const ( // GlobalTableStatusCreating is a GlobalTableStatus enum value GlobalTableStatusCreating = "CREATING" @@ -20005,6 +20124,16 @@ const ( GlobalTableStatusUpdating = "UPDATING" ) +// GlobalTableStatus_Values returns all elements of the GlobalTableStatus enum +func GlobalTableStatus_Values() []string { + return []string{ + GlobalTableStatusCreating, + GlobalTableStatusActive, + GlobalTableStatusDeleting, + GlobalTableStatusUpdating, + } +} + const ( // IndexStatusCreating is a IndexStatus enum value IndexStatusCreating = "CREATING" @@ -20019,6 +20148,16 @@ const ( IndexStatusActive = "ACTIVE" ) +// IndexStatus_Values returns all elements of the IndexStatus enum +func IndexStatus_Values() []string { + return []string{ + IndexStatusCreating, + IndexStatusUpdating, + IndexStatusDeleting, + IndexStatusActive, + } +} + const ( // KeyTypeHash is a KeyType enum value KeyTypeHash = "HASH" @@ -20027,6 +20166,14 @@ const ( KeyTypeRange = "RANGE" ) +// KeyType_Values returns all elements of the KeyType enum +func KeyType_Values() []string { + return []string{ + KeyTypeHash, + KeyTypeRange, + } +} + const ( // PointInTimeRecoveryStatusEnabled is a PointInTimeRecoveryStatus enum value PointInTimeRecoveryStatusEnabled = "ENABLED" @@ -20035,6 +20182,14 @@ const ( PointInTimeRecoveryStatusDisabled = "DISABLED" ) +// PointInTimeRecoveryStatus_Values returns all elements of the PointInTimeRecoveryStatus enum +func PointInTimeRecoveryStatus_Values() []string { + return []string{ + PointInTimeRecoveryStatusEnabled, + PointInTimeRecoveryStatusDisabled, + } +} + const ( // ProjectionTypeAll is a ProjectionType enum value ProjectionTypeAll = "ALL" @@ -20046,6 +20201,15 @@ const ( ProjectionTypeInclude = "INCLUDE" ) +// ProjectionType_Values returns all elements of the ProjectionType enum +func ProjectionType_Values() []string { + return []string{ + ProjectionTypeAll, + ProjectionTypeKeysOnly, + ProjectionTypeInclude, + } +} + const ( // ReplicaStatusCreating is a ReplicaStatus enum value ReplicaStatusCreating = "CREATING" @@ -20063,6 +20227,17 @@ const ( ReplicaStatusActive = "ACTIVE" ) +// ReplicaStatus_Values returns all elements of the ReplicaStatus enum +func ReplicaStatus_Values() []string { + return []string{ + ReplicaStatusCreating, + ReplicaStatusCreationFailed, + ReplicaStatusUpdating, + ReplicaStatusDeleting, + ReplicaStatusActive, + } +} + // Determines the level of detail about provisioned throughput consumption that // is returned in the response: // @@ -20087,6 +20262,15 @@ const ( ReturnConsumedCapacityNone = "NONE" ) +// ReturnConsumedCapacity_Values returns all elements of the ReturnConsumedCapacity enum +func ReturnConsumedCapacity_Values() []string { + return []string{ + ReturnConsumedCapacityIndexes, + ReturnConsumedCapacityTotal, + ReturnConsumedCapacityNone, + } +} + const ( // ReturnItemCollectionMetricsSize is a ReturnItemCollectionMetrics enum value ReturnItemCollectionMetricsSize = "SIZE" @@ -20095,6 +20279,14 @@ const ( ReturnItemCollectionMetricsNone = "NONE" ) +// ReturnItemCollectionMetrics_Values returns all elements of the ReturnItemCollectionMetrics enum +func ReturnItemCollectionMetrics_Values() []string { + return []string{ + ReturnItemCollectionMetricsSize, + ReturnItemCollectionMetricsNone, + } +} + const ( // ReturnValueNone is a ReturnValue enum value ReturnValueNone = "NONE" @@ -20112,6 +20304,17 @@ const ( ReturnValueUpdatedNew = "UPDATED_NEW" ) +// ReturnValue_Values returns all elements of the ReturnValue enum +func ReturnValue_Values() []string { + return []string{ + ReturnValueNone, + ReturnValueAllOld, + ReturnValueUpdatedOld, + ReturnValueAllNew, + ReturnValueUpdatedNew, + } +} + const ( // ReturnValuesOnConditionCheckFailureAllOld is a ReturnValuesOnConditionCheckFailure enum value ReturnValuesOnConditionCheckFailureAllOld = "ALL_OLD" @@ -20120,6 +20323,14 @@ const ( ReturnValuesOnConditionCheckFailureNone = "NONE" ) +// ReturnValuesOnConditionCheckFailure_Values returns all elements of the ReturnValuesOnConditionCheckFailure enum +func ReturnValuesOnConditionCheckFailure_Values() []string { + return []string{ + ReturnValuesOnConditionCheckFailureAllOld, + ReturnValuesOnConditionCheckFailureNone, + } +} + const ( // SSEStatusEnabling is a SSEStatus enum value SSEStatusEnabling = "ENABLING" @@ -20137,6 +20348,17 @@ const ( SSEStatusUpdating = "UPDATING" ) +// SSEStatus_Values returns all elements of the SSEStatus enum +func SSEStatus_Values() []string { + return []string{ + SSEStatusEnabling, + SSEStatusEnabled, + SSEStatusDisabling, + SSEStatusDisabled, + SSEStatusUpdating, + } +} + const ( // SSETypeAes256 is a SSEType enum value SSETypeAes256 = "AES256" @@ -20145,6 +20367,14 @@ const ( SSETypeKms = "KMS" ) +// SSEType_Values returns all elements of the SSEType enum +func SSEType_Values() []string { + return []string{ + SSETypeAes256, + SSETypeKms, + } +} + const ( // ScalarAttributeTypeS is a ScalarAttributeType enum value ScalarAttributeTypeS = "S" @@ -20156,6 +20386,15 @@ const ( ScalarAttributeTypeB = "B" ) +// ScalarAttributeType_Values returns all elements of the ScalarAttributeType enum +func ScalarAttributeType_Values() []string { + return []string{ + ScalarAttributeTypeS, + ScalarAttributeTypeN, + ScalarAttributeTypeB, + } +} + const ( // SelectAllAttributes is a Select enum value SelectAllAttributes = "ALL_ATTRIBUTES" @@ -20170,6 +20409,16 @@ const ( SelectCount = "COUNT" ) +// Select_Values returns all elements of the Select enum +func Select_Values() []string { + return []string{ + SelectAllAttributes, + SelectAllProjectedAttributes, + SelectSpecificAttributes, + SelectCount, + } +} + const ( // StreamViewTypeNewImage is a StreamViewType enum value StreamViewTypeNewImage = "NEW_IMAGE" @@ -20184,6 +20433,16 @@ const ( StreamViewTypeKeysOnly = "KEYS_ONLY" ) +// StreamViewType_Values returns all elements of the StreamViewType enum +func StreamViewType_Values() []string { + return []string{ + StreamViewTypeNewImage, + StreamViewTypeOldImage, + StreamViewTypeNewAndOldImages, + StreamViewTypeKeysOnly, + } +} + const ( // TableStatusCreating is a TableStatus enum value TableStatusCreating = "CREATING" @@ -20207,6 +20466,19 @@ const ( TableStatusArchived = "ARCHIVED" ) +// TableStatus_Values returns all elements of the TableStatus enum +func TableStatus_Values() []string { + return []string{ + TableStatusCreating, + TableStatusUpdating, + TableStatusDeleting, + TableStatusActive, + TableStatusInaccessibleEncryptionCredentials, + TableStatusArchiving, + TableStatusArchived, + } +} + const ( // TimeToLiveStatusEnabling is a TimeToLiveStatus enum value TimeToLiveStatusEnabling = "ENABLING" @@ -20220,3 +20492,13 @@ const ( // TimeToLiveStatusDisabled is a TimeToLiveStatus enum value TimeToLiveStatusDisabled = "DISABLED" ) + +// TimeToLiveStatus_Values returns all elements of the TimeToLiveStatus enum +func TimeToLiveStatus_Values() []string { + return []string{ + TimeToLiveStatusEnabling, + TimeToLiveStatusDisabling, + TimeToLiveStatusEnabled, + TimeToLiveStatusDisabled, + } +} 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 3f68867ee8b..aeea19bf33c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go @@ -554,6 +554,10 @@ func (c *EC2) AllocateAddressRequest(input *AllocateAddressInput) (req *request. // For more information, see Elastic IP Addresses (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) // in the Amazon Elastic Compute Cloud User Guide. // +// You can allocate a carrier IP address which is a public IP address from a +// telecommunication carrier, to a network interface which resides in a subnet +// in a Wavelength Zone (for example an EC2 instance). +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -955,7 +959,8 @@ func (c *EC2) AssociateAddressRequest(input *AssociateAddressInput) (req *reques // AssociateAddress API operation for Amazon Elastic Compute Cloud. // -// Associates an Elastic IP address with an instance or a network interface. +// Associates an Elastic IP address, or carrier IP address (for instances that +// are in subnets in Wavelength Zones) with an instance or a network interface. // Before you can use an Elastic IP address, you must allocate it to your account. // // An Elastic IP address is for use in either the EC2-Classic platform or in @@ -976,6 +981,9 @@ func (c *EC2) AssociateAddressRequest(input *AssociateAddressInput) (req *reques // an Elastic IP address with an instance or network interface that has an existing // Elastic IP address. // +// [Subnets in Wavelength Zones] You can associate an IP address from the telecommunication +// carrier to the instance or network interface. +// // You cannot associate an Elastic IP address with an interface in a different // network border group. // @@ -3453,6 +3461,82 @@ func (c *EC2) CreateCapacityReservationWithContext(ctx aws.Context, input *Creat return out, req.Send() } +const opCreateCarrierGateway = "CreateCarrierGateway" + +// CreateCarrierGatewayRequest generates a "aws/request.Request" representing the +// client's request for the CreateCarrierGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateCarrierGateway for more information on using the CreateCarrierGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateCarrierGatewayRequest method. +// req, resp := client.CreateCarrierGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateCarrierGateway +func (c *EC2) CreateCarrierGatewayRequest(input *CreateCarrierGatewayInput) (req *request.Request, output *CreateCarrierGatewayOutput) { + op := &request.Operation{ + Name: opCreateCarrierGateway, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateCarrierGatewayInput{} + } + + output = &CreateCarrierGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateCarrierGateway API operation for Amazon Elastic Compute Cloud. +// +// Creates a carrier gateway. For more information about carrier gateways, see +// Carrier gateways (https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#wavelength-carrier-gateway) +// in the AWS Wavelength Developer Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation CreateCarrierGateway for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateCarrierGateway +func (c *EC2) CreateCarrierGateway(input *CreateCarrierGatewayInput) (*CreateCarrierGatewayOutput, error) { + req, out := c.CreateCarrierGatewayRequest(input) + return out, req.Send() +} + +// CreateCarrierGatewayWithContext is the same as CreateCarrierGateway with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCarrierGateway for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) CreateCarrierGatewayWithContext(ctx aws.Context, input *CreateCarrierGatewayInput, opts ...request.Option) (*CreateCarrierGatewayOutput, error) { + req, out := c.CreateCarrierGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateClientVpnEndpoint = "CreateClientVpnEndpoint" // CreateClientVpnEndpointRequest generates a "aws/request.Request" representing the @@ -3926,13 +4010,13 @@ func (c *EC2) CreateDhcpOptionsRequest(input *CreateDhcpOptionsInput) (req *requ // * domain-name - If you're using AmazonProvidedDNS in us-east-1, specify // ec2.internal. If you're using AmazonProvidedDNS in another Region, specify // region.compute.internal (for example, ap-northeast-1.compute.internal). -// Otherwise, specify a domain name (for example, MyCompany.com). This value -// is used to complete unqualified DNS hostnames. Important: Some Linux operating -// systems accept multiple domain names separated by spaces. However, Windows -// and other Linux operating systems treat the value as a single domain, -// which results in unexpected behavior. If your DHCP options set is associated -// with a VPC that has instances with multiple operating systems, specify -// only one domain name. +// Otherwise, specify a domain name (for example, ExampleCompany.com). This +// value is used to complete unqualified DNS hostnames. Important: Some Linux +// operating systems accept multiple domain names separated by spaces. However, +// Windows and other Linux operating systems treat the value as a single +// domain, which results in unexpected behavior. If your DHCP options set +// is associated with a VPC that has instances with multiple operating systems, +// specify only one domain name. // // * ntp-servers - The IP addresses of up to four Network Time Protocol (NTP) // servers. @@ -4432,7 +4516,7 @@ func (c *EC2) CreateInstanceExportTaskRequest(input *CreateInstanceExportTaskInp // CreateInstanceExportTask API operation for Amazon Elastic Compute Cloud. // -// Exports a running or stopped instance to an S3 bucket. +// Exports a running or stopped instance to an Amazon S3 bucket. // // For information about the supported operating systems, image formats, and // known limitations for the types of instances you can export, see Exporting @@ -4678,6 +4762,8 @@ func (c *EC2) CreateLaunchTemplateRequest(input *CreateLaunchTemplateInput) (req // Creates a launch template. A launch template contains the parameters to launch // an instance. When you launch an instance using RunInstances, you can specify // a launch template instead of providing the launch parameters in the request. +// For more information, see Launching an instance from a launch template (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html)in +// the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4757,6 +4843,9 @@ func (c *EC2) CreateLaunchTemplateVersionRequest(input *CreateLaunchTemplateVers // Launch template versions are numbered in the order in which they are created. // You cannot specify, change, or replace the numbering of launch template versions. // +// For more information, see Managing launch template versions (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#manage-launch-template-versions)in +// the Amazon Elastic Compute Cloud User Guide. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -4933,6 +5022,84 @@ func (c *EC2) CreateLocalGatewayRouteTableVpcAssociationWithContext(ctx aws.Cont return out, req.Send() } +const opCreateManagedPrefixList = "CreateManagedPrefixList" + +// CreateManagedPrefixListRequest generates a "aws/request.Request" representing the +// client's request for the CreateManagedPrefixList operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateManagedPrefixList for more information on using the CreateManagedPrefixList +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateManagedPrefixListRequest method. +// req, resp := client.CreateManagedPrefixListRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateManagedPrefixList +func (c *EC2) CreateManagedPrefixListRequest(input *CreateManagedPrefixListInput) (req *request.Request, output *CreateManagedPrefixListOutput) { + op := &request.Operation{ + Name: opCreateManagedPrefixList, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateManagedPrefixListInput{} + } + + output = &CreateManagedPrefixListOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateManagedPrefixList API operation for Amazon Elastic Compute Cloud. +// +// Creates a managed prefix list. You can specify one or more entries for the +// prefix list. Each entry consists of a CIDR block and an optional description. +// +// You must specify the maximum number of entries for the prefix list. The maximum +// number of entries cannot be changed later. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation CreateManagedPrefixList for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateManagedPrefixList +func (c *EC2) CreateManagedPrefixList(input *CreateManagedPrefixListInput) (*CreateManagedPrefixListOutput, error) { + req, out := c.CreateManagedPrefixListRequest(input) + return out, req.Send() +} + +// CreateManagedPrefixListWithContext is the same as CreateManagedPrefixList with the addition of +// the ability to pass a context and additional request options. +// +// See CreateManagedPrefixList for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) CreateManagedPrefixListWithContext(ctx aws.Context, input *CreateManagedPrefixListInput, opts ...request.Option) (*CreateManagedPrefixListOutput, error) { + req, out := c.CreateManagedPrefixListRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateNatGateway = "CreateNatGateway" // CreateNatGatewayRequest generates a "aws/request.Request" representing the @@ -5392,7 +5559,7 @@ func (c *EC2) CreatePlacementGroupRequest(input *CreatePlacementGroupInput) (req // instances in one partition do not share the same hardware with instances // in another partition. // -// For more information, see Placement Groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) +// For more information, see Placement groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -6017,7 +6184,7 @@ func (c *EC2) CreateSpotDatafeedSubscriptionRequest(input *CreateSpotDatafeedSub // // Creates a data feed for Spot Instances, enabling you to view Spot Instance // usage logs. You can create one data feed per AWS account. For more information, -// see Spot Instance Data Feed (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) +// see Spot Instance data feed (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) // in the Amazon EC2 User Guide for Linux Instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -6092,15 +6259,12 @@ func (c *EC2) CreateSubnetRequest(input *CreateSubnetInput) (req *request.Reques // CreateSubnet API operation for Amazon Elastic Compute Cloud. // -// Creates a subnet in an existing VPC. +// Creates a subnet in a specified VPC. // -// When you create each subnet, you provide the VPC ID and IPv4 CIDR block for -// the subnet. After you create a subnet, you can't change its CIDR block. The -// size of the subnet's IPv4 CIDR block can be the same as a VPC's IPv4 CIDR -// block, or a subset of a VPC's IPv4 CIDR block. If you create more than one -// subnet in a VPC, the subnets' CIDR blocks must not overlap. The smallest -// IPv4 subnet (and VPC) you can create uses a /28 netmask (16 IPv4 addresses), -// and the largest uses a /16 netmask (65,536 IPv4 addresses). +// You must specify an IPv4 CIDR block for the subnet. After you create a subnet, +// you can't change its CIDR block. The allowed block size is between a /16 +// netmask (65,536 IP addresses) and /28 netmask (16 IP addresses). The CIDR +// block must not overlap with the CIDR block of an existing subnet in the VPC. // // If you've associated an IPv6 CIDR block with your VPC, you can create a subnet // with an IPv6 CIDR block that uses a /64 prefix length. @@ -6111,9 +6275,7 @@ func (c *EC2) CreateSubnetRequest(input *CreateSubnetInput) (req *request.Reques // If you add more than one subnet to a VPC, they're set up in a star topology // with a logical router in the middle. // -// If you launch an instance in a VPC using an Amazon EBS-backed AMI, the IP -// address doesn't change if you stop and restart the instance (unlike a similar -// instance launched outside a VPC, which gets a new IP address when restarted). +// When you stop an instance in a subnet, it retains its private IPv4 address. // It's therefore possible to have a subnet with no running instances (they're // all stopped), but no remaining IP addresses available. // @@ -6193,9 +6355,10 @@ func (c *EC2) CreateTagsRequest(input *CreateTagsInput) (req *request.Request, o // CreateTags API operation for Amazon Elastic Compute Cloud. // -// Adds or overwrites the specified tags for the specified Amazon EC2 resource -// or resources. Each resource can have a maximum of 50 tags. Each tag consists -// of a key and optional value. Tag keys must be unique per resource. +// Adds or overwrites only the specified tags for the specified Amazon EC2 resource +// or resources. When you specify an existing tag key, the value is overwritten +// with the new value. Each resource can have a maximum of 50 tags. Each tag +// consists of a key and optional value. Tag keys must be unique per resource. // // For more information about tags, see Tagging Your Resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) // in the Amazon Elastic Compute Cloud User Guide. For more information about @@ -7616,15 +7779,15 @@ func (c *EC2) CreateVpnConnectionRequest(input *CreateVpnConnectionInput) (req * // CreateVpnConnection API operation for Amazon Elastic Compute Cloud. // -// Creates a VPN connection between an existing virtual private gateway and -// a VPN customer gateway. The supported connection type is ipsec.1. +// Creates a VPN connection between an existing virtual private gateway or transit +// gateway and a customer gateway. The supported connection type is ipsec.1. // // The response includes information that you need to give to your network administrator // to configure your customer gateway. // // We strongly recommend that you use HTTPS when calling this operation because // the response contains sensitive cryptographic information for configuring -// your customer gateway. +// your customer gateway device. // // If you decide to shut down your VPN connection for any reason and later create // a new VPN connection, you must reconfigure your customer gateway with the @@ -7824,6 +7987,84 @@ func (c *EC2) CreateVpnGatewayWithContext(ctx aws.Context, input *CreateVpnGatew return out, req.Send() } +const opDeleteCarrierGateway = "DeleteCarrierGateway" + +// DeleteCarrierGatewayRequest generates a "aws/request.Request" representing the +// client's request for the DeleteCarrierGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteCarrierGateway for more information on using the DeleteCarrierGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteCarrierGatewayRequest method. +// req, resp := client.DeleteCarrierGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteCarrierGateway +func (c *EC2) DeleteCarrierGatewayRequest(input *DeleteCarrierGatewayInput) (req *request.Request, output *DeleteCarrierGatewayOutput) { + op := &request.Operation{ + Name: opDeleteCarrierGateway, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteCarrierGatewayInput{} + } + + output = &DeleteCarrierGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteCarrierGateway API operation for Amazon Elastic Compute Cloud. +// +// Deletes a carrier gateway. +// +// If you do not delete the route that contains the carrier gateway as the Target, +// the route is a blackhole route. For information about how to delete a route, +// see DeleteRoute (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteRoute.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DeleteCarrierGateway for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteCarrierGateway +func (c *EC2) DeleteCarrierGateway(input *DeleteCarrierGatewayInput) (*DeleteCarrierGatewayOutput, error) { + req, out := c.DeleteCarrierGatewayRequest(input) + return out, req.Send() +} + +// DeleteCarrierGatewayWithContext is the same as DeleteCarrierGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCarrierGateway for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DeleteCarrierGatewayWithContext(ctx aws.Context, input *DeleteCarrierGatewayInput, opts ...request.Option) (*DeleteCarrierGatewayOutput, error) { + req, out := c.DeleteCarrierGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteClientVpnEndpoint = "DeleteClientVpnEndpoint" // DeleteClientVpnEndpointRequest generates a "aws/request.Request" representing the @@ -8884,6 +9125,81 @@ func (c *EC2) DeleteLocalGatewayRouteTableVpcAssociationWithContext(ctx aws.Cont return out, req.Send() } +const opDeleteManagedPrefixList = "DeleteManagedPrefixList" + +// DeleteManagedPrefixListRequest generates a "aws/request.Request" representing the +// client's request for the DeleteManagedPrefixList operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteManagedPrefixList for more information on using the DeleteManagedPrefixList +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteManagedPrefixListRequest method. +// req, resp := client.DeleteManagedPrefixListRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteManagedPrefixList +func (c *EC2) DeleteManagedPrefixListRequest(input *DeleteManagedPrefixListInput) (req *request.Request, output *DeleteManagedPrefixListOutput) { + op := &request.Operation{ + Name: opDeleteManagedPrefixList, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteManagedPrefixListInput{} + } + + output = &DeleteManagedPrefixListOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteManagedPrefixList API operation for Amazon Elastic Compute Cloud. +// +// Deletes the specified managed prefix list. You must first remove all references +// to the prefix list in your resources. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DeleteManagedPrefixList for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteManagedPrefixList +func (c *EC2) DeleteManagedPrefixList(input *DeleteManagedPrefixListInput) (*DeleteManagedPrefixListOutput, error) { + req, out := c.DeleteManagedPrefixListRequest(input) + return out, req.Send() +} + +// DeleteManagedPrefixListWithContext is the same as DeleteManagedPrefixList with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteManagedPrefixList for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DeleteManagedPrefixListWithContext(ctx aws.Context, input *DeleteManagedPrefixListInput, opts ...request.Option) (*DeleteManagedPrefixListOutput, error) { + req, out := c.DeleteManagedPrefixListRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteNatGateway = "DeleteNatGateway" // DeleteNatGatewayRequest generates a "aws/request.Request" representing the @@ -9312,7 +9628,7 @@ func (c *EC2) DeletePlacementGroupRequest(input *DeletePlacementGroupInput) (req // // Deletes the specified placement group. You must terminate all instances in // the placement group before you can delete the placement group. For more information, -// see Placement Groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) +// see Placement groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -11234,9 +11550,13 @@ func (c *EC2) DeleteVpnConnectionRequest(input *DeleteVpnConnectionInput) (req * // your VPN connection have been compromised, you can delete the VPN connection // and create a new one that has new keys, without needing to delete the VPC // or virtual private gateway. If you create a new VPN connection, you must -// reconfigure the customer gateway using the new configuration information +// reconfigure the customer gateway device using the new configuration information // returned with the new VPN connection ID. // +// For certificate-based authentication, delete all AWS Certificate Manager +// (ACM) private certificates used for the AWS-side tunnel endpoints for the +// VPN connection before deleting the VPN connection. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -12113,13 +12433,12 @@ func (c *EC2) DescribeAvailabilityZonesRequest(input *DescribeAvailabilityZonesI // DescribeAvailabilityZones API operation for Amazon Elastic Compute Cloud. // -// Describes the Availability Zones and Local Zones that are available to you. -// If there is an event impacting an Availability Zone or Local Zone, you can -// use this request to view the state and any provided messages for that Availability -// Zone or Local Zone. +// Describes the Availability Zones, Local Zones, and Wavelength Zones that +// are available to you. If there is an event impacting a zone, you can use +// this request to view the state and any provided messages for that zone. // -// For more information about Availability Zones and Local Zones, see Regions -// and Availability Zones (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) +// For more information about Availability Zones, Local Zones, and Wavelength +// Zones, see Regions, Zones and Outposts (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -12497,6 +12816,138 @@ func (c *EC2) DescribeCapacityReservationsPagesWithContext(ctx aws.Context, inpu return p.Err() } +const opDescribeCarrierGateways = "DescribeCarrierGateways" + +// DescribeCarrierGatewaysRequest generates a "aws/request.Request" representing the +// client's request for the DescribeCarrierGateways operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeCarrierGateways for more information on using the DescribeCarrierGateways +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeCarrierGatewaysRequest method. +// req, resp := client.DescribeCarrierGatewaysRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCarrierGateways +func (c *EC2) DescribeCarrierGatewaysRequest(input *DescribeCarrierGatewaysInput) (req *request.Request, output *DescribeCarrierGatewaysOutput) { + op := &request.Operation{ + Name: opDescribeCarrierGateways, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeCarrierGatewaysInput{} + } + + output = &DescribeCarrierGatewaysOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeCarrierGateways API operation for Amazon Elastic Compute Cloud. +// +// Describes one or more of your carrier gateways. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DescribeCarrierGateways for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCarrierGateways +func (c *EC2) DescribeCarrierGateways(input *DescribeCarrierGatewaysInput) (*DescribeCarrierGatewaysOutput, error) { + req, out := c.DescribeCarrierGatewaysRequest(input) + return out, req.Send() +} + +// DescribeCarrierGatewaysWithContext is the same as DescribeCarrierGateways with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCarrierGateways for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeCarrierGatewaysWithContext(ctx aws.Context, input *DescribeCarrierGatewaysInput, opts ...request.Option) (*DescribeCarrierGatewaysOutput, error) { + req, out := c.DescribeCarrierGatewaysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeCarrierGatewaysPages iterates over the pages of a DescribeCarrierGateways operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeCarrierGateways method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeCarrierGateways operation. +// pageNum := 0 +// err := client.DescribeCarrierGatewaysPages(params, +// func(page *ec2.DescribeCarrierGatewaysOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *EC2) DescribeCarrierGatewaysPages(input *DescribeCarrierGatewaysInput, fn func(*DescribeCarrierGatewaysOutput, bool) bool) error { + return c.DescribeCarrierGatewaysPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCarrierGatewaysPagesWithContext same as DescribeCarrierGatewaysPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeCarrierGatewaysPagesWithContext(ctx aws.Context, input *DescribeCarrierGatewaysInput, fn func(*DescribeCarrierGatewaysOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCarrierGatewaysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCarrierGatewaysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeCarrierGatewaysOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeClassicLinkInstances = "DescribeClassicLinkInstances" // DescribeClassicLinkInstancesRequest generates a "aws/request.Request" representing the @@ -13974,7 +14425,7 @@ func (c *EC2) DescribeExportImageTasksRequest(input *DescribeExportImageTasksInp // DescribeExportImageTasks API operation for Amazon Elastic Compute Cloud. // -// Describes the specified export image tasks or all your export image tasks. +// Describes the specified export image tasks or all of your export image tasks. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -14100,7 +14551,7 @@ func (c *EC2) DescribeExportTasksRequest(input *DescribeExportTasksInput) (req * // DescribeExportTasks API operation for Amazon Elastic Compute Cloud. // -// Describes the specified export instance tasks or all your export instance +// Describes the specified export instance tasks or all of your export instance // tasks. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -16185,7 +16636,7 @@ func (c *EC2) DescribeInstanceCreditSpecificationsRequest(input *DescribeInstanc // all, the call fails. If you specify only instance IDs in an unaffected zone, // the call works normally. // -// For more information, see Burstable Performance Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) +// For more information, see Burstable performance instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -16401,18 +16852,18 @@ func (c *EC2) DescribeInstanceStatusRequest(input *DescribeInstanceStatusInput) // // * Status checks - Amazon EC2 performs status checks on running EC2 instances // to identify hardware and software issues. For more information, see Status -// Checks for Your Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html) -// and Troubleshooting Instances with Failed Status Checks (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstances.html) +// checks for your instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html) +// and Troubleshooting instances with failed status checks (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstances.html) // in the Amazon Elastic Compute Cloud User Guide. // // * Scheduled events - Amazon EC2 can schedule events (such as reboot, stop, // or terminate) for your instances related to hardware issues, software -// updates, or system maintenance. For more information, see Scheduled Events -// for Your Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html) +// updates, or system maintenance. For more information, see Scheduled events +// for your instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html) // in the Amazon Elastic Compute Cloud User Guide. // // * Instance state - You can manage your instances from the moment you launch -// them through their termination. For more information, see Instance Lifecycle +// them through their termination. For more information, see Instance lifecycle // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) // in the Amazon Elastic Compute Cloud User Guide. // @@ -16680,7 +17131,7 @@ func (c *EC2) DescribeInstanceTypesRequest(input *DescribeInstanceTypesInput) (r // DescribeInstanceTypes API operation for Amazon Elastic Compute Cloud. // -// Returns a list of all instance types offered in your current AWS Region. +// Describes the details of the instance types that are offered in a location. // The results can be filtered by the attributes of the instance types. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -16813,13 +17264,17 @@ func (c *EC2) DescribeInstancesRequest(input *DescribeInstancesInput) (req *requ // DescribeInstances API operation for Amazon Elastic Compute Cloud. // -// Describes the specified instances or all of AWS account's instances. +// Describes the specified instances or all instances. // -// If you specify one or more instance IDs, Amazon EC2 returns information for -// those instances. If you do not specify instance IDs, Amazon EC2 returns information -// for all relevant instances. If you specify an instance ID that is not valid, -// an error is returned. If you specify an instance that you do not own, it -// is not included in the returned results. +// If you specify instance IDs, the output includes information for only the +// specified instances. If you specify filters, the output includes information +// for only those instances that meet the filter criteria. If you do not specify +// instance IDs or filters, the output includes information for all instances, +// which can affect performance. We recommend that you use pagination to ensure +// that the operation returns quickly and successfully. +// +// If you specify an instance ID that is not valid, an error is returned. If +// you specify an instance that you do not own, it is not included in the output. // // Recently terminated instances might appear in the returned results. This // interval is usually less than one hour. @@ -17302,7 +17757,9 @@ func (c *EC2) DescribeLaunchTemplateVersionsRequest(input *DescribeLaunchTemplat // DescribeLaunchTemplateVersions API operation for Amazon Elastic Compute Cloud. // // Describes one or more versions of a specified launch template. You can describe -// all versions, individual versions, or a range of versions. +// all versions, individual versions, or a range of versions. You can also describe +// all the latest versions or all the default versions of all the launch templates +// in your account. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -18312,6 +18769,140 @@ func (c *EC2) DescribeLocalGatewaysPagesWithContext(ctx aws.Context, input *Desc return p.Err() } +const opDescribeManagedPrefixLists = "DescribeManagedPrefixLists" + +// DescribeManagedPrefixListsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeManagedPrefixLists operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeManagedPrefixLists for more information on using the DescribeManagedPrefixLists +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeManagedPrefixListsRequest method. +// req, resp := client.DescribeManagedPrefixListsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeManagedPrefixLists +func (c *EC2) DescribeManagedPrefixListsRequest(input *DescribeManagedPrefixListsInput) (req *request.Request, output *DescribeManagedPrefixListsOutput) { + op := &request.Operation{ + Name: opDescribeManagedPrefixLists, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeManagedPrefixListsInput{} + } + + output = &DescribeManagedPrefixListsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeManagedPrefixLists API operation for Amazon Elastic Compute Cloud. +// +// Describes your managed prefix lists and any AWS-managed prefix lists. +// +// To view the entries for your prefix list, use GetManagedPrefixListEntries. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation DescribeManagedPrefixLists for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeManagedPrefixLists +func (c *EC2) DescribeManagedPrefixLists(input *DescribeManagedPrefixListsInput) (*DescribeManagedPrefixListsOutput, error) { + req, out := c.DescribeManagedPrefixListsRequest(input) + return out, req.Send() +} + +// DescribeManagedPrefixListsWithContext is the same as DescribeManagedPrefixLists with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeManagedPrefixLists for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeManagedPrefixListsWithContext(ctx aws.Context, input *DescribeManagedPrefixListsInput, opts ...request.Option) (*DescribeManagedPrefixListsOutput, error) { + req, out := c.DescribeManagedPrefixListsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeManagedPrefixListsPages iterates over the pages of a DescribeManagedPrefixLists operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeManagedPrefixLists method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeManagedPrefixLists operation. +// pageNum := 0 +// err := client.DescribeManagedPrefixListsPages(params, +// func(page *ec2.DescribeManagedPrefixListsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *EC2) DescribeManagedPrefixListsPages(input *DescribeManagedPrefixListsInput, fn func(*DescribeManagedPrefixListsOutput, bool) bool) error { + return c.DescribeManagedPrefixListsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeManagedPrefixListsPagesWithContext same as DescribeManagedPrefixListsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) DescribeManagedPrefixListsPagesWithContext(ctx aws.Context, input *DescribeManagedPrefixListsInput, fn func(*DescribeManagedPrefixListsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeManagedPrefixListsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeManagedPrefixListsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeManagedPrefixListsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMovingAddresses = "DescribeMovingAddresses" // DescribeMovingAddressesRequest generates a "aws/request.Request" representing the @@ -19097,7 +19688,7 @@ func (c *EC2) DescribePlacementGroupsRequest(input *DescribePlacementGroupsInput // DescribePlacementGroups API operation for Amazon Elastic Compute Cloud. // // Describes the specified placement groups or all of your placement groups. -// For more information, see Placement Groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) +// For more information, see Placement groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -19180,10 +19771,9 @@ func (c *EC2) DescribePrefixListsRequest(input *DescribePrefixListsInput) (req * // // Describes available AWS services in a prefix list format, which includes // the prefix list name and prefix list ID of the service and the IP address -// range for the service. A prefix list ID is required for creating an outbound -// security group rule that allows traffic from a VPC to access an AWS service -// through a gateway VPC endpoint. Currently, the services that support this -// action are Amazon S3 and Amazon DynamoDB. +// range for the service. +// +// We recommend that you use DescribeManagedPrefixLists instead. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -20870,12 +21460,12 @@ func (c *EC2) DescribeSnapshotsRequest(input *DescribeSnapshotsInput) (req *requ // (if you own the snapshots), self for snapshots for which you own or have // explicit permissions, or all for public snapshots. // -// If you are describing a long list of snapshots, you can paginate the output -// to make the list more manageable. The MaxResults parameter sets the maximum -// number of results returned in a single page. If the list of results exceeds -// your MaxResults value, then that number of results is returned along with -// a NextToken value that can be passed to a subsequent DescribeSnapshots request -// to retrieve the remaining results. +// If you are describing a long list of snapshots, we recommend that you paginate +// the output to make the list more manageable. The MaxResults parameter sets +// the maximum number of results returned in a single page. If the list of results +// exceeds your MaxResults value, then that number of results is returned along +// with a NextToken value that can be passed to a subsequent DescribeSnapshots +// request to retrieve the remaining results. // // To get the state of fast snapshot restores for a snapshot, use DescribeFastSnapshotRestores. // @@ -21007,7 +21597,7 @@ func (c *EC2) DescribeSpotDatafeedSubscriptionRequest(input *DescribeSpotDatafee // DescribeSpotDatafeedSubscription API operation for Amazon Elastic Compute Cloud. // // Describes the data feed for Spot Instances. For more information, see Spot -// Instance Data Feed (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) +// Instance data feed (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) // in the Amazon EC2 User Guide for Linux Instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -21525,7 +22115,7 @@ func (c *EC2) DescribeSpotPriceHistoryRequest(input *DescribeSpotPriceHistoryInp // DescribeSpotPriceHistory API operation for Amazon Elastic Compute Cloud. // // Describes the Spot price history. For more information, see Spot Instance -// Pricing History (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html) +// pricing history (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html) // in the Amazon EC2 User Guide for Linux Instances. // // When you specify a start and end time, this operation returns the prices @@ -23510,12 +24100,12 @@ func (c *EC2) DescribeVolumesRequest(input *DescribeVolumesInput) (req *request. // // Describes the specified EBS volumes or all of your EBS volumes. // -// If you are describing a long list of volumes, you can paginate the output -// to make the list more manageable. The MaxResults parameter sets the maximum -// number of results returned in a single page. If the list of results exceeds -// your MaxResults value, then that number of results is returned along with -// a NextToken value that can be passed to a subsequent DescribeVolumes request -// to retrieve the remaining results. +// If you are describing a long list of volumes, we recommend that you paginate +// the output to make the list more manageable. The MaxResults parameter sets +// the maximum number of results returned in a single page. If the list of results +// exceeds your MaxResults value, then that number of results is returned along +// with a NextToken value that can be passed to a subsequent DescribeVolumes +// request to retrieve the remaining results. // // For more information about EBS volumes, see Amazon EBS Volumes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html) // in the Amazon Elastic Compute Cloud User Guide. @@ -23650,19 +24240,17 @@ func (c *EC2) DescribeVolumesModificationsRequest(input *DescribeVolumesModifica // DescribeVolumesModifications API operation for Amazon Elastic Compute Cloud. // -// Reports the current modification status of EBS volumes. +// Describes the most recent volume modification request for the specified EBS +// volumes. // -// Current-generation EBS volumes support modification of attributes including -// type, size, and (for io1 volumes) IOPS provisioning while either attached -// to or detached from an instance. Following an action from the API or the -// console to modify a volume, the status of the modification may be modifying, -// optimizing, completed, or failed. If a volume has never been modified, then -// certain elements of the returned VolumeModification objects are null. +// If a volume has never been modified, some information in the output will +// be null. If a volume has been modified more than once, the output includes +// only the most recent modification request. // // You can also use CloudWatch Events to check the status of a modification // to an EBS volume. For information about CloudWatch Events, see the Amazon // CloudWatch Events User Guide (https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/). -// For more information, see Monitoring Volume Modifications" (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#monitoring_mods) +// For more information, see Monitoring Volume Modifications (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#monitoring_mods) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -28042,7 +28630,7 @@ func (c *EC2) GetDefaultCreditSpecificationRequest(input *GetDefaultCreditSpecif // Describes the default credit option for CPU usage of a burstable performance // instance family. // -// For more information, see Burstable Performance Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) +// For more information, see Burstable performance instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -28230,6 +28818,138 @@ func (c *EC2) GetEbsEncryptionByDefaultWithContext(ctx aws.Context, input *GetEb return out, req.Send() } +const opGetGroupsForCapacityReservation = "GetGroupsForCapacityReservation" + +// GetGroupsForCapacityReservationRequest generates a "aws/request.Request" representing the +// client's request for the GetGroupsForCapacityReservation operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetGroupsForCapacityReservation for more information on using the GetGroupsForCapacityReservation +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetGroupsForCapacityReservationRequest method. +// req, resp := client.GetGroupsForCapacityReservationRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetGroupsForCapacityReservation +func (c *EC2) GetGroupsForCapacityReservationRequest(input *GetGroupsForCapacityReservationInput) (req *request.Request, output *GetGroupsForCapacityReservationOutput) { + op := &request.Operation{ + Name: opGetGroupsForCapacityReservation, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetGroupsForCapacityReservationInput{} + } + + output = &GetGroupsForCapacityReservationOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetGroupsForCapacityReservation API operation for Amazon Elastic Compute Cloud. +// +// Lists the resource groups to which a Capacity Reservation has been added. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation GetGroupsForCapacityReservation for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetGroupsForCapacityReservation +func (c *EC2) GetGroupsForCapacityReservation(input *GetGroupsForCapacityReservationInput) (*GetGroupsForCapacityReservationOutput, error) { + req, out := c.GetGroupsForCapacityReservationRequest(input) + return out, req.Send() +} + +// GetGroupsForCapacityReservationWithContext is the same as GetGroupsForCapacityReservation with the addition of +// the ability to pass a context and additional request options. +// +// See GetGroupsForCapacityReservation for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetGroupsForCapacityReservationWithContext(ctx aws.Context, input *GetGroupsForCapacityReservationInput, opts ...request.Option) (*GetGroupsForCapacityReservationOutput, error) { + req, out := c.GetGroupsForCapacityReservationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetGroupsForCapacityReservationPages iterates over the pages of a GetGroupsForCapacityReservation operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetGroupsForCapacityReservation method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetGroupsForCapacityReservation operation. +// pageNum := 0 +// err := client.GetGroupsForCapacityReservationPages(params, +// func(page *ec2.GetGroupsForCapacityReservationOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *EC2) GetGroupsForCapacityReservationPages(input *GetGroupsForCapacityReservationInput, fn func(*GetGroupsForCapacityReservationOutput, bool) bool) error { + return c.GetGroupsForCapacityReservationPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetGroupsForCapacityReservationPagesWithContext same as GetGroupsForCapacityReservationPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetGroupsForCapacityReservationPagesWithContext(ctx aws.Context, input *GetGroupsForCapacityReservationInput, fn func(*GetGroupsForCapacityReservationOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetGroupsForCapacityReservationInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetGroupsForCapacityReservationRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetGroupsForCapacityReservationOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetHostReservationPurchasePreview = "GetHostReservationPurchasePreview" // GetHostReservationPurchasePreviewRequest generates a "aws/request.Request" representing the @@ -28356,6 +29076,12 @@ func (c *EC2) GetLaunchTemplateDataRequest(input *GetLaunchTemplateDataInput) (r // Retrieves the configuration data of the specified instance. You can use this // data to create a launch template. // +// This action calls on other describe actions to get instance information. +// Depending on your instance configuration, you may need to allow the following +// actions in your IAM policy: DescribeSpotInstanceRequests, DescribeInstanceCreditSpecifications, +// DescribeVolumes, DescribeInstanceAttribute, and DescribeElasticGpus. Or, +// you can allow describe* depending on your instance requirements. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -28384,6 +29110,271 @@ func (c *EC2) GetLaunchTemplateDataWithContext(ctx aws.Context, input *GetLaunch return out, req.Send() } +const opGetManagedPrefixListAssociations = "GetManagedPrefixListAssociations" + +// GetManagedPrefixListAssociationsRequest generates a "aws/request.Request" representing the +// client's request for the GetManagedPrefixListAssociations operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetManagedPrefixListAssociations for more information on using the GetManagedPrefixListAssociations +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetManagedPrefixListAssociationsRequest method. +// req, resp := client.GetManagedPrefixListAssociationsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListAssociations +func (c *EC2) GetManagedPrefixListAssociationsRequest(input *GetManagedPrefixListAssociationsInput) (req *request.Request, output *GetManagedPrefixListAssociationsOutput) { + op := &request.Operation{ + Name: opGetManagedPrefixListAssociations, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetManagedPrefixListAssociationsInput{} + } + + output = &GetManagedPrefixListAssociationsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetManagedPrefixListAssociations API operation for Amazon Elastic Compute Cloud. +// +// Gets information about the resources that are associated with the specified +// managed prefix list. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation GetManagedPrefixListAssociations for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListAssociations +func (c *EC2) GetManagedPrefixListAssociations(input *GetManagedPrefixListAssociationsInput) (*GetManagedPrefixListAssociationsOutput, error) { + req, out := c.GetManagedPrefixListAssociationsRequest(input) + return out, req.Send() +} + +// GetManagedPrefixListAssociationsWithContext is the same as GetManagedPrefixListAssociations with the addition of +// the ability to pass a context and additional request options. +// +// See GetManagedPrefixListAssociations for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetManagedPrefixListAssociationsWithContext(ctx aws.Context, input *GetManagedPrefixListAssociationsInput, opts ...request.Option) (*GetManagedPrefixListAssociationsOutput, error) { + req, out := c.GetManagedPrefixListAssociationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetManagedPrefixListAssociationsPages iterates over the pages of a GetManagedPrefixListAssociations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetManagedPrefixListAssociations method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetManagedPrefixListAssociations operation. +// pageNum := 0 +// err := client.GetManagedPrefixListAssociationsPages(params, +// func(page *ec2.GetManagedPrefixListAssociationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *EC2) GetManagedPrefixListAssociationsPages(input *GetManagedPrefixListAssociationsInput, fn func(*GetManagedPrefixListAssociationsOutput, bool) bool) error { + return c.GetManagedPrefixListAssociationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetManagedPrefixListAssociationsPagesWithContext same as GetManagedPrefixListAssociationsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetManagedPrefixListAssociationsPagesWithContext(ctx aws.Context, input *GetManagedPrefixListAssociationsInput, fn func(*GetManagedPrefixListAssociationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetManagedPrefixListAssociationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetManagedPrefixListAssociationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetManagedPrefixListAssociationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opGetManagedPrefixListEntries = "GetManagedPrefixListEntries" + +// GetManagedPrefixListEntriesRequest generates a "aws/request.Request" representing the +// client's request for the GetManagedPrefixListEntries operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetManagedPrefixListEntries for more information on using the GetManagedPrefixListEntries +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetManagedPrefixListEntriesRequest method. +// req, resp := client.GetManagedPrefixListEntriesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListEntries +func (c *EC2) GetManagedPrefixListEntriesRequest(input *GetManagedPrefixListEntriesInput) (req *request.Request, output *GetManagedPrefixListEntriesOutput) { + op := &request.Operation{ + Name: opGetManagedPrefixListEntries, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetManagedPrefixListEntriesInput{} + } + + output = &GetManagedPrefixListEntriesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetManagedPrefixListEntries API operation for Amazon Elastic Compute Cloud. +// +// Gets information about the entries for a specified managed prefix list. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation GetManagedPrefixListEntries for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListEntries +func (c *EC2) GetManagedPrefixListEntries(input *GetManagedPrefixListEntriesInput) (*GetManagedPrefixListEntriesOutput, error) { + req, out := c.GetManagedPrefixListEntriesRequest(input) + return out, req.Send() +} + +// GetManagedPrefixListEntriesWithContext is the same as GetManagedPrefixListEntries with the addition of +// the ability to pass a context and additional request options. +// +// See GetManagedPrefixListEntries for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetManagedPrefixListEntriesWithContext(ctx aws.Context, input *GetManagedPrefixListEntriesInput, opts ...request.Option) (*GetManagedPrefixListEntriesOutput, error) { + req, out := c.GetManagedPrefixListEntriesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetManagedPrefixListEntriesPages iterates over the pages of a GetManagedPrefixListEntries operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetManagedPrefixListEntries method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetManagedPrefixListEntries operation. +// pageNum := 0 +// err := client.GetManagedPrefixListEntriesPages(params, +// func(page *ec2.GetManagedPrefixListEntriesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *EC2) GetManagedPrefixListEntriesPages(input *GetManagedPrefixListEntriesInput, fn func(*GetManagedPrefixListEntriesOutput, bool) bool) error { + return c.GetManagedPrefixListEntriesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetManagedPrefixListEntriesPagesWithContext same as GetManagedPrefixListEntriesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetManagedPrefixListEntriesPagesWithContext(ctx aws.Context, input *GetManagedPrefixListEntriesInput, fn func(*GetManagedPrefixListEntriesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetManagedPrefixListEntriesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetManagedPrefixListEntriesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetManagedPrefixListEntriesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetPasswordData = "GetPasswordData" // GetPasswordDataRequest generates a "aws/request.Request" representing the @@ -29596,9 +30587,10 @@ func (c *EC2) ModifyAvailabilityZoneGroupRequest(input *ModifyAvailabilityZoneGr // ModifyAvailabilityZoneGroup API operation for Amazon Elastic Compute Cloud. // -// Enables or disables an Availability Zone group for your account. +// Changes the opt-in status of the Local Zone and Wavelength Zone group for +// your account. // -// Use describe-availability-zones (https://docs.aws.amazon.com/AWSEC2ApiDocReef/build/server-root/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html) +// Use DescribeAvailabilityZones (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html) // to view the value for GroupName. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -29840,7 +30832,7 @@ func (c *EC2) ModifyDefaultCreditSpecificationRequest(input *ModifyDefaultCredit // can call GetDefaultCreditSpecification and check DefaultCreditSpecification // for updates. // -// For more information, see Burstable Performance Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) +// For more information, see Burstable performance instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -30552,7 +31544,7 @@ func (c *EC2) ModifyInstanceAttributeRequest(input *ModifyInstanceAttributeInput // we recommend that you use the ModifyNetworkInterfaceAttribute action. // // To modify some attributes, the instance must be stopped. For more information, -// see Modifying Attributes of a Stopped Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_ChangingAttributesWhileInstanceStopped.html) +// see Modifying attributes of a stopped instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_ChangingAttributesWhileInstanceStopped.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -30707,7 +31699,7 @@ func (c *EC2) ModifyInstanceCreditSpecificationRequest(input *ModifyInstanceCred // Modifies the credit option for CPU usage on a running or stopped burstable // performance instance. The credit options are standard and unlimited. // -// For more information, see Burstable Performance Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) +// For more information, see Burstable performance instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -30862,7 +31854,7 @@ func (c *EC2) ModifyInstanceMetadataOptionsRequest(input *ModifyInstanceMetadata // the API responds with a state of “pending”. After the parameter modifications // are successfully applied to the instance, the state of the modifications // changes from “pending” to “applied” in subsequent describe-instances -// API calls. For more information, see Instance Metadata and User Data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html). +// API calls. For more information, see Instance metadata and user data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -31063,6 +32055,86 @@ func (c *EC2) ModifyLaunchTemplateWithContext(ctx aws.Context, input *ModifyLaun return out, req.Send() } +const opModifyManagedPrefixList = "ModifyManagedPrefixList" + +// ModifyManagedPrefixListRequest generates a "aws/request.Request" representing the +// client's request for the ModifyManagedPrefixList operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ModifyManagedPrefixList for more information on using the ModifyManagedPrefixList +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ModifyManagedPrefixListRequest method. +// req, resp := client.ModifyManagedPrefixListRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyManagedPrefixList +func (c *EC2) ModifyManagedPrefixListRequest(input *ModifyManagedPrefixListInput) (req *request.Request, output *ModifyManagedPrefixListOutput) { + op := &request.Operation{ + Name: opModifyManagedPrefixList, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ModifyManagedPrefixListInput{} + } + + output = &ModifyManagedPrefixListOutput{} + req = c.newRequest(op, input, output) + return +} + +// ModifyManagedPrefixList API operation for Amazon Elastic Compute Cloud. +// +// Modifies the specified managed prefix list. +// +// Adding or removing entries in a prefix list creates a new version of the +// prefix list. Changing the name of the prefix list does not affect the version. +// +// If you specify a current version number that does not match the true current +// version number, the request fails. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation ModifyManagedPrefixList for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyManagedPrefixList +func (c *EC2) ModifyManagedPrefixList(input *ModifyManagedPrefixListInput) (*ModifyManagedPrefixListOutput, error) { + req, out := c.ModifyManagedPrefixListRequest(input) + return out, req.Send() +} + +// ModifyManagedPrefixListWithContext is the same as ModifyManagedPrefixList with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyManagedPrefixList for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) ModifyManagedPrefixListWithContext(ctx aws.Context, input *ModifyManagedPrefixListInput, opts ...request.Option) (*ModifyManagedPrefixListOutput, error) { + req, out := c.ModifyManagedPrefixListRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opModifyNetworkInterfaceAttribute = "ModifyNetworkInterfaceAttribute" // ModifyNetworkInterfaceAttributeRequest generates a "aws/request.Request" representing the @@ -32598,8 +33670,9 @@ func (c *EC2) ModifyVpnConnectionRequest(input *ModifyVpnConnectionInput) (req * // ModifyVpnConnection API operation for Amazon Elastic Compute Cloud. // -// Modifies the target gateway of an AWS Site-to-Site VPN connection. The following -// migration options are available: +// Modifies the customer gateway or the target gateway of an AWS Site-to-Site +// VPN connection. To modify the target gateway, the following migration options +// are available: // // * An existing virtual private gateway to a new virtual private gateway // @@ -32864,7 +33937,7 @@ func (c *EC2) MonitorInstancesRequest(input *MonitorInstancesInput) (req *reques // MonitorInstances API operation for Amazon Elastic Compute Cloud. // // Enables detailed monitoring for a running instance. Otherwise, basic monitoring -// is enabled. For more information, see Monitoring Your Instances and Volumes +// is enabled. For more information, see Monitoring your instances and volumes // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) // in the Amazon Elastic Compute Cloud User Guide. // @@ -33368,8 +34441,8 @@ func (c *EC2) RebootInstancesRequest(input *RebootInstancesInput) (req *request. // If an instance does not cleanly shut down within four minutes, Amazon EC2 // performs a hard reboot. // -// For more information about troubleshooting, see Getting Console Output and -// Rebooting Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) +// For more information about troubleshooting, see Getting console output and +// rebooting instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -33446,7 +34519,7 @@ func (c *EC2) RegisterImageRequest(input *RegisterImageInput) (req *request.Requ // // Registers an AMI. When you're creating an AMI, this is the final step you // must complete before you can launch an instance from the AMI. For more information -// about creating AMIs, see Creating Your Own AMIs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami.html) +// about creating AMIs, see Creating your own AMIs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami.html) // in the Amazon Elastic Compute Cloud User Guide. // // For Amazon EBS-backed instances, CreateImage creates and registers the AMI @@ -33454,12 +34527,12 @@ func (c *EC2) RegisterImageRequest(input *RegisterImageInput) (req *request.Requ // // You can also use RegisterImage to create an Amazon EBS-backed Linux AMI from // a snapshot of a root device volume. You specify the snapshot using the block -// device mapping. For more information, see Launching a Linux Instance from -// a Backup (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-launch-snapshot.html) +// device mapping. For more information, see Launching a Linux instance from +// a backup (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-launch-snapshot.html) // in the Amazon Elastic Compute Cloud User Guide. // -// You can't register an image where a secondary (non-root) snapshot has AWS -// Marketplace product codes. +// If any snapshots have AWS Marketplace product codes, they are copied to the +// new AMI. // // Windows and some Linux distributions, such as Red Hat Enterprise Linux (RHEL) // and SUSE Linux Enterprise Server (SLES), use the EC2 billing product code @@ -33480,7 +34553,7 @@ func (c *EC2) RegisterImageRequest(input *RegisterImageInput) (req *request.Requ // a Reserved Instance without the matching billing product code, the Reserved // Instance will not be applied to the On-Demand Instance. For information about // how to obtain the platform details and billing information of an AMI, see -// Obtaining Billing Information (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html) +// Obtaining billing information (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html) // in the Amazon Elastic Compute Cloud User Guide. // // If needed, you can deregister an AMI at any time. Any modifications you make @@ -34858,7 +35931,7 @@ func (c *EC2) RequestSpotFleetRequest(input *RequestSpotFleetInput) (req *reques // the fleet. You cannot tag other resource types in a Spot Fleet request because // only the spot-fleet-request and instance resource types are supported. // -// For more information, see Spot Fleet Requests (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html) +// For more information, see Spot Fleet requests (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html) // in the Amazon EC2 User Guide for Linux Instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -34935,7 +36008,7 @@ func (c *EC2) RequestSpotInstancesRequest(input *RequestSpotInstancesInput) (req // // Creates a Spot Instance request. // -// For more information, see Spot Instance Requests (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html) +// For more information, see Spot Instance requests (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html) // in the Amazon EC2 User Guide for Linux Instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -35513,6 +36586,81 @@ func (c *EC2) RestoreAddressToClassicWithContext(ctx aws.Context, input *Restore return out, req.Send() } +const opRestoreManagedPrefixListVersion = "RestoreManagedPrefixListVersion" + +// RestoreManagedPrefixListVersionRequest generates a "aws/request.Request" representing the +// client's request for the RestoreManagedPrefixListVersion operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See RestoreManagedPrefixListVersion for more information on using the RestoreManagedPrefixListVersion +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the RestoreManagedPrefixListVersionRequest method. +// req, resp := client.RestoreManagedPrefixListVersionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RestoreManagedPrefixListVersion +func (c *EC2) RestoreManagedPrefixListVersionRequest(input *RestoreManagedPrefixListVersionInput) (req *request.Request, output *RestoreManagedPrefixListVersionOutput) { + op := &request.Operation{ + Name: opRestoreManagedPrefixListVersion, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &RestoreManagedPrefixListVersionInput{} + } + + output = &RestoreManagedPrefixListVersionOutput{} + req = c.newRequest(op, input, output) + return +} + +// RestoreManagedPrefixListVersion API operation for Amazon Elastic Compute Cloud. +// +// Restores the entries from a previous version of a managed prefix list to +// a new version of the prefix list. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Elastic Compute Cloud's +// API operation RestoreManagedPrefixListVersion for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RestoreManagedPrefixListVersion +func (c *EC2) RestoreManagedPrefixListVersion(input *RestoreManagedPrefixListVersionInput) (*RestoreManagedPrefixListVersionOutput, error) { + req, out := c.RestoreManagedPrefixListVersionRequest(input) + return out, req.Send() +} + +// RestoreManagedPrefixListVersionWithContext is the same as RestoreManagedPrefixListVersion with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreManagedPrefixListVersion for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) RestoreManagedPrefixListVersionWithContext(ctx aws.Context, input *RestoreManagedPrefixListVersionInput, opts ...request.Option) (*RestoreManagedPrefixListVersionOutput, error) { + req, out := c.RestoreManagedPrefixListVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opRevokeClientVpnIngress = "RevokeClientVpnIngress" // RevokeClientVpnIngressRequest generates a "aws/request.Request" representing the @@ -35823,17 +36971,17 @@ func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *request.Reques // // * Some instance types must be launched into a VPC. If you do not have // a default VPC, or if you do not specify a subnet ID, the request fails. -// For more information, see Instance Types Available Only in a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types). +// For more information, see Instance types available only in a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types). // // * [EC2-VPC] All instances have a network interface with a primary private // IPv4 address. If you don't specify this address, we choose one from the // IPv4 range of your subnet. // // * Not all instance types support IPv6 addresses. For more information, -// see Instance Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html). +// see Instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html). // // * If you don't specify a security group ID, we use the default security -// group. For more information, see Security Groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html). +// group. For more information, see Security groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html). // // * If any of the AMIs have a product code attached for which the user has // not subscribed, the request fails. @@ -35850,17 +36998,17 @@ func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *request.Reques // An instance is ready for you to use when it's in the running state. You can // check the state of your instance using DescribeInstances. You can tag instances // and EBS volumes during launch, after launch, or both. For more information, -// see CreateTags and Tagging Your Amazon EC2 Resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html). +// see CreateTags and Tagging your Amazon EC2 resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html). // // Linux instances have access to the public key of the key pair at boot. You // can use this key to provide secure access to the instance. Amazon EC2 public // images use this feature to provide secure access without passwords. For more -// information, see Key Pairs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) +// information, see Key pairs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) // in the Amazon Elastic Compute Cloud User Guide. // -// For troubleshooting, see What To Do If An Instance Immediately Terminates +// For troubleshooting, see What to do if an instance immediately terminates // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html), -// and Troubleshooting Connecting to Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) +// and Troubleshooting connecting to your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -36373,8 +37521,8 @@ func (c *EC2) SendDiagnosticInterruptRequest(input *SendDiagnosticInterruptInput // system is configured to perform the required diagnostic tasks. // // For more information about configuring your operating system to generate -// a crash dump when a kernel panic or stop error occurs, see Send a Diagnostic -// Interrupt (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/diagnostic-interrupt.html) +// a crash dump when a kernel panic or stop error occurs, see Send a diagnostic +// interrupt (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/diagnostic-interrupt.html) // (Linux instances) or Send a Diagnostic Interrupt (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/diagnostic-interrupt.html) // (Windows instances). // @@ -36471,7 +37619,7 @@ func (c *EC2) StartInstancesRequest(input *StartInstancesInput) (req *request.Re // Performing this operation on an instance that uses an instance store as its // root device returns an error. // -// For more information, see Stopping Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) +// For more information, see Stopping instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -36634,7 +37782,7 @@ func (c *EC2) StopInstancesRequest(input *StopInstancesInput) (req *request.Requ // You can use the Stop action to hibernate an instance if the instance is enabled // for hibernation (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) // and it meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites). -// For more information, see Hibernate Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) +// For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon Elastic Compute Cloud User Guide. // // We don't charge usage for a stopped instance, or data transfer fees; however, @@ -36650,7 +37798,7 @@ func (c *EC2) StopInstancesRequest(input *StopInstancesInput) (req *request.Requ // You can't stop or hibernate instance store-backed instances. You can't use // the Stop action to hibernate Spot Instances, but you can specify that Amazon // EC2 should hibernate Spot Instances when they are interrupted. For more information, -// see Hibernating Interrupted Spot Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) +// see Hibernating interrupted Spot Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) // in the Amazon Elastic Compute Cloud User Guide. // // When you stop or hibernate an instance, we shut it down. You can restart @@ -36666,13 +37814,13 @@ func (c *EC2) StopInstancesRequest(input *StopInstancesInput) (req *request.Requ // an instance, the root device and any other devices attached during the instance // launch are automatically deleted. For more information about the differences // between rebooting, stopping, hibernating, and terminating instances, see -// Instance Lifecycle (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) +// Instance lifecycle (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) // in the Amazon Elastic Compute Cloud User Guide. // // When you stop an instance, we attempt to shut it down forcibly after a short // while. If your instance appears stuck in the stopping state after a period // of time, there may be an issue with the underlying host computer. For more -// information, see Troubleshooting Stopping Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) +// information, see Troubleshooting stopping your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -36842,11 +37990,11 @@ func (c *EC2) TerminateInstancesRequest(input *TerminateInstancesInput) (req *re // an instance, any attached EBS volumes with the DeleteOnTermination block // device mapping parameter set to true are automatically deleted. For more // information about the differences between stopping and terminating instances, -// see Instance Lifecycle (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) +// see Instance lifecycle (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) // in the Amazon Elastic Compute Cloud User Guide. // -// For more information about troubleshooting, see Troubleshooting Terminating -// Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) +// For more information about troubleshooting, see Troubleshooting terminating +// your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -37071,7 +38219,7 @@ func (c *EC2) UnmonitorInstancesRequest(input *UnmonitorInstancesInput) (req *re // UnmonitorInstances API operation for Amazon Elastic Compute Cloud. // // Disables detailed monitoring for a running instance. For more information, -// see Monitoring Your Instances and Volumes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) +// see Monitoring your instances and volumes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -37840,7 +38988,57 @@ func (s *ActiveInstance) SetSpotInstanceRequestId(v string) *ActiveInstance { return s } -// Describes an Elastic IP address. +// An entry for a prefix list. +type AddPrefixListEntry struct { + _ struct{} `type:"structure"` + + // The CIDR block. + // + // Cidr is a required field + Cidr *string `type:"string" required:"true"` + + // A description for the entry. + // + // Constraints: Up to 255 characters in length. + Description *string `type:"string"` +} + +// String returns the string representation +func (s AddPrefixListEntry) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AddPrefixListEntry) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AddPrefixListEntry) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AddPrefixListEntry"} + if s.Cidr == nil { + invalidParams.Add(request.NewErrParamRequired("Cidr")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCidr sets the Cidr field's value. +func (s *AddPrefixListEntry) SetCidr(v string) *AddPrefixListEntry { + s.Cidr = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *AddPrefixListEntry) SetDescription(v string) *AddPrefixListEntry { + s.Description = &v + return s +} + +// Describes an Elastic IP address, or a carrier IP address. type Address struct { _ struct{} `type:"structure"` @@ -37851,6 +39049,11 @@ type Address struct { // VPC. AssociationId *string `locationName:"associationId" type:"string"` + // The carrier IP address associated. This option is only available for network + // interfaces which reside in a subnet in a Wavelength Zone (for example an + // EC2 instance). + CarrierIp *string `locationName:"carrierIp" type:"string"` + // The customer-owned IP address. CustomerOwnedIp *string `locationName:"customerOwnedIp" type:"string"` @@ -37864,7 +39067,8 @@ type Address struct { // The ID of the instance that the address is associated with (if any). InstanceId *string `locationName:"instanceId" type:"string"` - // The name of the location from which the IP address is advertised. + // The name of the unique set of Availability Zones, Local Zones, or Wavelength + // Zones from which AWS advertises IP addresses. NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` // The ID of the network interface. @@ -37908,6 +39112,12 @@ func (s *Address) SetAssociationId(v string) *Address { return s } +// SetCarrierIp sets the CarrierIp field's value. +func (s *Address) SetCarrierIp(v string) *Address { + s.CarrierIp = &v + return s +} + // SetCustomerOwnedIp sets the CustomerOwnedIp field's value. func (s *Address) SetCustomerOwnedIp(v string) *Address { s.CustomerOwnedIp = &v @@ -38060,9 +39270,11 @@ type AllocateAddressInput struct { // address from the address pool. CustomerOwnedIpv4Pool *string `type:"string"` - // Set to vpc to allocate the address for use with instances in a VPC. + // Indicates whether the Elastic IP address is for use with instances in a VPC + // or instances in EC2-Classic. // - // Default: The address is for use with instances in EC2-Classic. + // Default: If the Region supports EC2-Classic, the default is standard. Otherwise, + // the default is vpc. Domain *string `type:"string" enum:"DomainType"` // Checks whether you have the required permissions for the action, without @@ -38071,12 +39283,9 @@ type AllocateAddressInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // The location from which the IP address is advertised. Use this parameter - // to limit the address to this location. - // - // A network border group is a unique set of Availability Zones or Local Zones - // from where AWS advertises IP addresses and limits the addresses to the group. - // IP addresses cannot move between network border groups. + // A unique set of Availability Zones, Local Zones, or Wavelength Zones from + // which AWS advertises IP addresses. Use this parameter to limit the IP address + // to this location. IP addresses cannot move between network border groups. // // Use DescribeAvailabilityZones (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html) // to view the network border groups. @@ -38145,17 +39354,22 @@ type AllocateAddressOutput struct { // IP address for use with instances in a VPC. AllocationId *string `locationName:"allocationId" type:"string"` + // The carrier IP address. This option is only available for network interfaces + // which reside in a subnet in a Wavelength Zone (for example an EC2 instance). + CarrierIp *string `locationName:"carrierIp" type:"string"` + // The customer-owned IP address. CustomerOwnedIp *string `locationName:"customerOwnedIp" type:"string"` // The ID of the customer-owned address pool. CustomerOwnedIpv4Pool *string `locationName:"customerOwnedIpv4Pool" type:"string"` - // Indicates whether this Elastic IP address is for use with instances in EC2-Classic - // (standard) or instances in a VPC (vpc). + // Indicates whether the Elastic IP address is for use with instances in a VPC + // (vpc) or instances in EC2-Classic (standard). Domain *string `locationName:"domain" type:"string" enum:"DomainType"` - // The location from which the IP address is advertised. + // The set of Availability Zones, Local Zones, or Wavelength Zones from which + // AWS advertises IP addresses. NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` // The Elastic IP address. @@ -38181,6 +39395,12 @@ func (s *AllocateAddressOutput) SetAllocationId(v string) *AllocateAddressOutput return s } +// SetCarrierIp sets the CarrierIp field's value. +func (s *AllocateAddressOutput) SetCarrierIp(v string) *AllocateAddressOutput { + s.CarrierIp = &v + return s +} + // SetCustomerOwnedIp sets the CustomerOwnedIp field's value. func (s *AllocateAddressOutput) SetCustomerOwnedIp(v string) *AllocateAddressOutput { s.CustomerOwnedIp = &v @@ -39473,7 +40693,7 @@ type AssociateVpcCidrBlockInput struct { Ipv6CidrBlock *string `type:"string"` // The name of the location from which we advertise the IPV6 CIDR block. Use - // this parameter to limit the CiDR block to this location. + // this parameter to limit the CIDR block to this location. // // You must set AmazonProvidedIpv6CidrBlock to true to use this parameter. // @@ -40229,11 +41449,14 @@ func (s *AuthorizationRule) SetStatus(v *ClientVpnAuthorizationRuleStatus) *Auth type AuthorizeClientVpnIngressInput struct { _ struct{} `type:"structure"` - // The ID of the Active Directory group to grant access. + // The ID of the group to grant access to, for example, the Active Directory + // group or identity provider (IdP) group. Required if AuthorizeAllGroups is + // false or not specified. AccessGroupId *string `type:"string"` - // Indicates whether to grant access to all clients. Use true to grant all clients - // who successfully establish a VPN connection access to the network. + // Indicates whether to grant access to all clients. Specify true to grant all + // clients who successfully establish a VPN connection access to the network. + // Must be set to true if AccessGroupId is not specified. AuthorizeAllGroups *bool `type:"boolean"` // Unique, case-sensitive identifier that you provide to ensure the idempotency @@ -40641,38 +41864,52 @@ func (s AuthorizeSecurityGroupIngressOutput) GoString() string { return s.String() } -// Describes an Availability Zone or Local Zone. +// Describes Availability Zones, Local Zones, and Wavelength Zones. type AvailabilityZone struct { _ struct{} `type:"structure"` // For Availability Zones, this parameter has the same value as the Region name. // // For Local Zones, the name of the associated group, for example us-west-2-lax-1. + // + // For Wavelength Zones, the name of the associated group, for example us-east-1-wl1-bos-wlz-1. GroupName *string `locationName:"groupName" type:"string"` - // Any messages about the Availability Zone or Local Zone. + // Any messages about the Availability Zone, Local Zone, or Wavelength Zone. Messages []*AvailabilityZoneMessage `locationName:"messageSet" locationNameList:"item" type:"list"` - // The name of the location from which the address is advertised. + // The name of the network border group. NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` // For Availability Zones, this parameter always has the value of opt-in-not-required. // - // For Local Zones, this parameter is the opt in status. The possible values - // are opted-in, and not-opted-in. + // For Local Zones and Wavelength Zones, this parameter is the opt-in status. + // The possible values are opted-in, and not-opted-in. OptInStatus *string `locationName:"optInStatus" type:"string" enum:"AvailabilityZoneOptInStatus"` + // The ID of the zone that handles some of the Local Zone or Wavelength Zone + // control plane operations, such as API calls. + ParentZoneId *string `locationName:"parentZoneId" type:"string"` + + // The name of the zone that handles some of the Local Zone or Wavelength Zone + // control plane operations, such as API calls. + ParentZoneName *string `locationName:"parentZoneName" type:"string"` + // The name of the Region. RegionName *string `locationName:"regionName" type:"string"` - // The state of the Availability Zone or Local Zone. + // The state of the Availability Zone, Local Zone, or Wavelength Zone. State *string `locationName:"zoneState" type:"string" enum:"AvailabilityZoneState"` - // The ID of the Availability Zone or Local Zone. + // The ID of the Availability Zone, Local Zone, or Wavelength Zone. ZoneId *string `locationName:"zoneId" type:"string"` - // The name of the Availability Zone or Local Zone. + // The name of the Availability Zone, Local Zone, or Wavelength Zone. ZoneName *string `locationName:"zoneName" type:"string"` + + // The type of zone. The valid values are availability-zone, local-zone, and + // wavelength-zone. + ZoneType *string `locationName:"zoneType" type:"string"` } // String returns the string representation @@ -40709,6 +41946,18 @@ func (s *AvailabilityZone) SetOptInStatus(v string) *AvailabilityZone { return s } +// SetParentZoneId sets the ParentZoneId field's value. +func (s *AvailabilityZone) SetParentZoneId(v string) *AvailabilityZone { + s.ParentZoneId = &v + return s +} + +// SetParentZoneName sets the ParentZoneName field's value. +func (s *AvailabilityZone) SetParentZoneName(v string) *AvailabilityZone { + s.ParentZoneName = &v + return s +} + // SetRegionName sets the RegionName field's value. func (s *AvailabilityZone) SetRegionName(v string) *AvailabilityZone { s.RegionName = &v @@ -40733,11 +41982,18 @@ func (s *AvailabilityZone) SetZoneName(v string) *AvailabilityZone { return s } -// Describes a message about an Availability Zone or Local Zone. +// SetZoneType sets the ZoneType field's value. +func (s *AvailabilityZone) SetZoneType(v string) *AvailabilityZone { + s.ZoneType = &v + return s +} + +// Describes a message about an Availability Zone, Local Zone, or Wavelength +// Zone. type AvailabilityZoneMessage struct { _ struct{} `type:"structure"` - // The message about the Availability Zone or Local Zone. + // The message about the Availability Zone, Local Zone, or Wavelength Zone. Message *string `locationName:"message" type:"string"` } @@ -42120,6 +43376,39 @@ func (s *CapacityReservation) SetTotalInstanceCount(v int64) *CapacityReservatio return s } +// Describes a resource group to which a Capacity Reservation has been added. +type CapacityReservationGroup struct { + _ struct{} `type:"structure"` + + // The ARN of the resource group. + GroupArn *string `locationName:"groupArn" type:"string"` + + // The ID of the AWS account that owns the resource group. + OwnerId *string `locationName:"ownerId" type:"string"` +} + +// String returns the string representation +func (s CapacityReservationGroup) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CapacityReservationGroup) GoString() string { + return s.String() +} + +// SetGroupArn sets the GroupArn field's value. +func (s *CapacityReservationGroup) SetGroupArn(v string) *CapacityReservationGroup { + s.GroupArn = &v + return s +} + +// SetOwnerId sets the OwnerId field's value. +func (s *CapacityReservationGroup) SetOwnerId(v string) *CapacityReservationGroup { + s.OwnerId = &v + return s +} + // Describes the strategy for using unused Capacity Reservations for fulfilling // On-Demand capacity. // @@ -42218,7 +43507,7 @@ func (s *CapacityReservationOptionsRequest) SetUsageStrategy(v string) *Capacity // to run as an On-Demand Instance or to run in any open Capacity Reservation // that has matching attributes (instance type, platform, Availability Zone). // Use the CapacityReservationTarget parameter to explicitly target a specific -// Capacity Reservation. +// Capacity Reservation or a Capacity Reservation group. type CapacityReservationSpecification struct { _ struct{} `type:"structure"` @@ -42232,7 +43521,8 @@ type CapacityReservationSpecification struct { // one is available. The instance runs as an On-Demand Instance. CapacityReservationPreference *string `type:"string" enum:"CapacityReservationPreference"` - // Information about the target Capacity Reservation. + // Information about the target Capacity Reservation or Capacity Reservation + // group. CapacityReservationTarget *CapacityReservationTarget `type:"structure"` } @@ -42263,7 +43553,8 @@ func (s *CapacityReservationSpecification) SetCapacityReservationTarget(v *Capac // instance is configured to run in On-Demand capacity, or if it is configured // in run in any open Capacity Reservation that has matching attributes (instance // type, platform, Availability Zone). The action returns the capacityReservationTarget -// response element if the instance explicily targets a specific Capacity Reservation. +// response element if the instance explicily targets a specific Capacity Reservation +// or Capacity Reservation group. type CapacityReservationSpecificationResponse struct { _ struct{} `type:"structure"` @@ -42277,7 +43568,8 @@ type CapacityReservationSpecificationResponse struct { // one is available. The instance runs in On-Demand capacity. CapacityReservationPreference *string `locationName:"capacityReservationPreference" type:"string" enum:"CapacityReservationPreference"` - // Information about the targeted Capacity Reservation. + // Information about the targeted Capacity Reservation or Capacity Reservation + // group. CapacityReservationTarget *CapacityReservationTargetResponse `locationName:"capacityReservationTarget" type:"structure"` } @@ -42303,12 +43595,15 @@ func (s *CapacityReservationSpecificationResponse) SetCapacityReservationTarget( return s } -// Describes a target Capacity Reservation. +// Describes a target Capacity Reservation or Capacity Reservation group. type CapacityReservationTarget struct { _ struct{} `type:"structure"` - // The ID of the Capacity Reservation. + // The ID of the Capacity Reservation in which to run the instance. CapacityReservationId *string `type:"string"` + + // The ARN of the Capacity Reservation resource group in which to run the instance. + CapacityReservationResourceGroupArn *string `type:"string"` } // String returns the string representation @@ -42327,12 +43622,21 @@ func (s *CapacityReservationTarget) SetCapacityReservationId(v string) *Capacity return s } -// Describes a target Capacity Reservation. +// SetCapacityReservationResourceGroupArn sets the CapacityReservationResourceGroupArn field's value. +func (s *CapacityReservationTarget) SetCapacityReservationResourceGroupArn(v string) *CapacityReservationTarget { + s.CapacityReservationResourceGroupArn = &v + return s +} + +// Describes a target Capacity Reservation or Capacity Reservation group. type CapacityReservationTargetResponse struct { _ struct{} `type:"structure"` - // The ID of the Capacity Reservation. + // The ID of the targeted Capacity Reservation. CapacityReservationId *string `locationName:"capacityReservationId" type:"string"` + + // The ARN of the targeted Capacity Reservation group. + CapacityReservationResourceGroupArn *string `locationName:"capacityReservationResourceGroupArn" type:"string"` } // String returns the string representation @@ -42351,6 +43655,72 @@ func (s *CapacityReservationTargetResponse) SetCapacityReservationId(v string) * return s } +// SetCapacityReservationResourceGroupArn sets the CapacityReservationResourceGroupArn field's value. +func (s *CapacityReservationTargetResponse) SetCapacityReservationResourceGroupArn(v string) *CapacityReservationTargetResponse { + s.CapacityReservationResourceGroupArn = &v + return s +} + +// Describes a carrier gateway. +type CarrierGateway struct { + _ struct{} `type:"structure"` + + // The ID of the carrier gateway. + CarrierGatewayId *string `locationName:"carrierGatewayId" type:"string"` + + // The AWS account ID of the owner of the carrier gateway. + OwnerId *string `locationName:"ownerId" type:"string"` + + // The state of the carrier gateway. + State *string `locationName:"state" type:"string" enum:"CarrierGatewayState"` + + // The tags assigned to the carrier gateway. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` + + // The ID of the VPC associated with the carrier gateway. + VpcId *string `locationName:"vpcId" type:"string"` +} + +// String returns the string representation +func (s CarrierGateway) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CarrierGateway) GoString() string { + return s.String() +} + +// SetCarrierGatewayId sets the CarrierGatewayId field's value. +func (s *CarrierGateway) SetCarrierGatewayId(v string) *CarrierGateway { + s.CarrierGatewayId = &v + return s +} + +// SetOwnerId sets the OwnerId field's value. +func (s *CarrierGateway) SetOwnerId(v string) *CarrierGateway { + s.OwnerId = &v + return s +} + +// SetState sets the State field's value. +func (s *CarrierGateway) SetState(v string) *CarrierGateway { + s.State = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CarrierGateway) SetTags(v []*Tag) *CarrierGateway { + s.Tags = v + return s +} + +// SetVpcId sets the VpcId field's value. +func (s *CarrierGateway) SetVpcId(v string) *CarrierGateway { + s.VpcId = &v + return s +} + // Information about the client certificate used for authentication. type CertificateAuthentication struct { _ struct{} `type:"structure"` @@ -42712,9 +44082,8 @@ func (s *ClientData) SetUploadStart(v time.Time) *ClientData { return s } -// Describes the authentication methods used by a Client VPN endpoint. Client -// VPN supports Active Directory and mutual authentication. For more information, -// see Authentication (https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/authentication-authrization.html#client-authentication) +// Describes the authentication methods used by a Client VPN endpoint. For more +// information, see Authentication (https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/authentication-authrization.html#client-authentication) // in the AWS Client VPN Administrator Guide. type ClientVpnAuthentication struct { _ struct{} `type:"structure"` @@ -42722,6 +44091,9 @@ type ClientVpnAuthentication struct { // Information about the Active Directory, if applicable. ActiveDirectory *DirectoryServiceAuthentication `locationName:"activeDirectory" type:"structure"` + // Information about the IAM SAML identity provider, if applicable. + FederatedAuthentication *FederatedAuthentication `locationName:"federatedAuthentication" type:"structure"` + // Information about the authentication certificates, if applicable. MutualAuthentication *CertificateAuthentication `locationName:"mutualAuthentication" type:"structure"` @@ -42745,6 +44117,12 @@ func (s *ClientVpnAuthentication) SetActiveDirectory(v *DirectoryServiceAuthenti return s } +// SetFederatedAuthentication sets the FederatedAuthentication field's value. +func (s *ClientVpnAuthentication) SetFederatedAuthentication(v *FederatedAuthentication) *ClientVpnAuthentication { + s.FederatedAuthentication = v + return s +} + // SetMutualAuthentication sets the MutualAuthentication field's value. func (s *ClientVpnAuthentication) SetMutualAuthentication(v *CertificateAuthentication) *ClientVpnAuthentication { s.MutualAuthentication = v @@ -42758,8 +44136,7 @@ func (s *ClientVpnAuthentication) SetType(v string) *ClientVpnAuthentication { } // Describes the authentication method to be used by a Client VPN endpoint. -// Client VPN supports Active Directory and mutual authentication. For more -// information, see Authentication (https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/authentication-authrization.html#client-authentication) +// For more information, see Authentication (https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/authentication-authrization.html#client-authentication) // in the AWS Client VPN Administrator Guide. type ClientVpnAuthenticationRequest struct { _ struct{} `type:"structure"` @@ -42768,13 +44145,15 @@ type ClientVpnAuthenticationRequest struct { // provide this information if Type is directory-service-authentication. ActiveDirectory *DirectoryServiceAuthenticationRequest `type:"structure"` + // Information about the IAM SAML identity provider to be used, if applicable. + // You must provide this information if Type is federated-authentication. + FederatedAuthentication *FederatedAuthenticationRequest `type:"structure"` + // Information about the authentication certificates to be used, if applicable. // You must provide this information if Type is certificate-authentication. MutualAuthentication *CertificateAuthenticationRequest `type:"structure"` - // The type of client authentication to be used. Specify certificate-authentication - // to use certificate-based authentication, or directory-service-authentication - // to use Active Directory authentication. + // The type of client authentication to be used. Type *string `type:"string" enum:"ClientVpnAuthenticationType"` } @@ -42794,6 +44173,12 @@ func (s *ClientVpnAuthenticationRequest) SetActiveDirectory(v *DirectoryServiceA return s } +// SetFederatedAuthentication sets the FederatedAuthentication field's value. +func (s *ClientVpnAuthenticationRequest) SetFederatedAuthentication(v *FederatedAuthenticationRequest) *ClientVpnAuthenticationRequest { + s.FederatedAuthentication = v + return s +} + // SetMutualAuthentication sets the MutualAuthentication field's value. func (s *ClientVpnAuthenticationRequest) SetMutualAuthentication(v *CertificateAuthenticationRequest) *ClientVpnAuthenticationRequest { s.MutualAuthentication = v @@ -43419,6 +44804,9 @@ type CoipPool struct { // The ID of the local gateway route table. LocalGatewayRouteTableId *string `locationName:"localGatewayRouteTableId" type:"string"` + // The ARN of the address pool. + PoolArn *string `locationName:"poolArn" min:"1" type:"string"` + // The address ranges of the address pool. PoolCidrs []*string `locationName:"poolCidrSet" locationNameList:"item" type:"list"` @@ -43445,6 +44833,12 @@ func (s *CoipPool) SetLocalGatewayRouteTableId(v string) *CoipPool { return s } +// SetPoolArn sets the PoolArn field's value. +func (s *CoipPool) SetPoolArn(v string) *CoipPool { + s.PoolArn = &v + return s +} + // SetPoolCidrs sets the PoolCidrs field's value. func (s *CoipPool) SetPoolCidrs(v []*string) *CoipPool { s.PoolCidrs = v @@ -43565,7 +44959,8 @@ func (s *ConfirmProductInstanceOutput) SetReturn(v bool) *ConfirmProductInstance type ConnectionLogOptions struct { _ struct{} `type:"structure"` - // The name of the CloudWatch Logs log group. + // The name of the CloudWatch Logs log group. Required if connection logging + // is enabled. CloudwatchLogGroup *string `type:"string"` // The name of the CloudWatch Logs log stream to which the connection data is @@ -44366,8 +45761,6 @@ type CreateCapacityReservationInput struct { // Unique, case-sensitive identifier that you provide to ensure the idempotency // of the request. For more information, see How to Ensure Idempotency (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). - // - // Constraint: Maximum 64 ASCII characters. ClientToken *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -44595,6 +45988,98 @@ func (s *CreateCapacityReservationOutput) SetCapacityReservation(v *CapacityRese return s } +type CreateCarrierGatewayInput struct { + _ struct{} `type:"structure"` + + // Unique, case-sensitive identifier that you provide to ensure the idempotency + // of the request. For more information, see How to Ensure Idempotency (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html). + ClientToken *string `type:"string" idempotencyToken:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The tags to associate with the carrier gateway. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + + // The ID of the VPC to associate with the carrier gateway. + // + // VpcId is a required field + VpcId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateCarrierGatewayInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateCarrierGatewayInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateCarrierGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateCarrierGatewayInput"} + if s.VpcId == nil { + invalidParams.Add(request.NewErrParamRequired("VpcId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientToken sets the ClientToken field's value. +func (s *CreateCarrierGatewayInput) SetClientToken(v string) *CreateCarrierGatewayInput { + s.ClientToken = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *CreateCarrierGatewayInput) SetDryRun(v bool) *CreateCarrierGatewayInput { + s.DryRun = &v + return s +} + +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateCarrierGatewayInput) SetTagSpecifications(v []*TagSpecification) *CreateCarrierGatewayInput { + s.TagSpecifications = v + return s +} + +// SetVpcId sets the VpcId field's value. +func (s *CreateCarrierGatewayInput) SetVpcId(v string) *CreateCarrierGatewayInput { + s.VpcId = &v + return s +} + +type CreateCarrierGatewayOutput struct { + _ struct{} `type:"structure"` + + // Information about the carrier gateway. + CarrierGateway *CarrierGateway `locationName:"carrierGateway" type:"structure"` +} + +// String returns the string representation +func (s CreateCarrierGatewayOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateCarrierGatewayOutput) GoString() string { + return s.String() +} + +// SetCarrierGateway sets the CarrierGateway field's value. +func (s *CreateCarrierGatewayOutput) SetCarrierGateway(v *CarrierGateway) *CreateCarrierGatewayOutput { + s.CarrierGateway = v + return s +} + type CreateClientVpnEndpointInput struct { _ struct{} `type:"structure"` @@ -45003,6 +46488,9 @@ type CreateCustomerGatewayInput struct { // The address must be static. PublicIp *string `locationName:"IpAddress" type:"string"` + // The tags to apply to the customer gateway. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The type of VPN connection that this customer gateway supports (ipsec.1). // // Type is a required field @@ -45065,6 +46553,12 @@ func (s *CreateCustomerGatewayInput) SetPublicIp(v string) *CreateCustomerGatewa return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateCustomerGatewayInput) SetTagSpecifications(v []*TagSpecification) *CreateCustomerGatewayInput { + s.TagSpecifications = v + return s +} + // SetType sets the Type field's value. func (s *CreateCustomerGatewayInput) SetType(v string) *CreateCustomerGatewayInput { s.Type = &v @@ -45230,6 +46724,9 @@ type CreateDhcpOptionsInput struct { // the required permissions, the error response is DryRunOperation. Otherwise, // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` + + // The tags to assign to the DHCP option. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -45267,6 +46764,12 @@ func (s *CreateDhcpOptionsInput) SetDryRun(v bool) *CreateDhcpOptionsInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateDhcpOptionsInput) SetTagSpecifications(v []*TagSpecification) *CreateDhcpOptionsInput { + s.TagSpecifications = v + return s +} + type CreateDhcpOptionsOutput struct { _ struct{} `type:"structure"` @@ -45303,6 +46806,9 @@ type CreateEgressOnlyInternetGatewayInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` + // The tags to assign to the egress-only internet gateway. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the VPC for which to create the egress-only internet gateway. // // VpcId is a required field @@ -45344,6 +46850,12 @@ func (s *CreateEgressOnlyInternetGatewayInput) SetDryRun(v bool) *CreateEgressOn return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateEgressOnlyInternetGatewayInput) SetTagSpecifications(v []*TagSpecification) *CreateEgressOnlyInternetGatewayInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateEgressOnlyInternetGatewayInput) SetVpcId(v string) *CreateEgressOnlyInternetGatewayInput { s.VpcId = &v @@ -46230,7 +47742,7 @@ type CreateInstanceExportTaskInput struct { _ struct{} `type:"structure"` // A description for the conversion task or the resource being exported. The - // maximum length is 255 bytes. + // maximum length is 255 characters. Description *string `locationName:"description" type:"string"` // The format and location for an instance export task. @@ -46241,6 +47753,9 @@ type CreateInstanceExportTaskInput struct { // InstanceId is a required field InstanceId *string `locationName:"instanceId" type:"string" required:"true"` + // The tags to apply to the instance export task during creation. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The target virtualization environment. TargetEnvironment *string `locationName:"targetEnvironment" type:"string" enum:"ExportEnvironment"` } @@ -46286,6 +47801,12 @@ func (s *CreateInstanceExportTaskInput) SetInstanceId(v string) *CreateInstanceE return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateInstanceExportTaskInput) SetTagSpecifications(v []*TagSpecification) *CreateInstanceExportTaskInput { + s.TagSpecifications = v + return s +} + // SetTargetEnvironment sets the TargetEnvironment field's value. func (s *CreateInstanceExportTaskInput) SetTargetEnvironment(v string) *CreateInstanceExportTaskInput { s.TargetEnvironment = &v @@ -46323,6 +47844,9 @@ type CreateInternetGatewayInput struct { // the required permissions, the error response is DryRunOperation. Otherwise, // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` + + // The tags to assign to the internet gateway. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -46341,6 +47865,12 @@ func (s *CreateInternetGatewayInput) SetDryRun(v bool) *CreateInternetGatewayInp return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateInternetGatewayInput) SetTagSpecifications(v []*TagSpecification) *CreateInternetGatewayInput { + s.TagSpecifications = v + return s +} + type CreateInternetGatewayOutput struct { _ struct{} `type:"structure"` @@ -46592,6 +48122,11 @@ type CreateLaunchTemplateOutput struct { // Information about the launch template. LaunchTemplate *LaunchTemplate `locationName:"launchTemplate" type:"structure"` + + // If the launch template contains parameters or parameter combinations that + // are not valid, an error code and an error message are returned for each issue + // that's found. + Warning *ValidationWarning `locationName:"warning" type:"structure"` } // String returns the string representation @@ -46610,6 +48145,12 @@ func (s *CreateLaunchTemplateOutput) SetLaunchTemplate(v *LaunchTemplate) *Creat return s } +// SetWarning sets the Warning field's value. +func (s *CreateLaunchTemplateOutput) SetWarning(v *ValidationWarning) *CreateLaunchTemplateOutput { + s.Warning = v + return s +} + type CreateLaunchTemplateVersionInput struct { _ struct{} `type:"structure"` @@ -46727,6 +48268,11 @@ type CreateLaunchTemplateVersionOutput struct { // Information about the launch template version. LaunchTemplateVersion *LaunchTemplateVersion `locationName:"launchTemplateVersion" type:"structure"` + + // If the new version of the launch template contains parameters or parameter + // combinations that are not valid, an error code and an error message are returned + // for each issue that's found. + Warning *ValidationWarning `locationName:"warning" type:"structure"` } // String returns the string representation @@ -46745,6 +48291,12 @@ func (s *CreateLaunchTemplateVersionOutput) SetLaunchTemplateVersion(v *LaunchTe return s } +// SetWarning sets the Warning field's value. +func (s *CreateLaunchTemplateVersionOutput) SetWarning(v *ValidationWarning) *CreateLaunchTemplateVersionOutput { + s.Warning = v + return s +} + type CreateLocalGatewayRouteInput struct { _ struct{} `type:"structure"` @@ -46861,6 +48413,9 @@ type CreateLocalGatewayRouteTableVpcAssociationInput struct { // LocalGatewayRouteTableId is a required field LocalGatewayRouteTableId *string `type:"string" required:"true"` + // The tags to assign to the local gateway route table VPC association. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the VPC. // // VpcId is a required field @@ -46905,6 +48460,12 @@ func (s *CreateLocalGatewayRouteTableVpcAssociationInput) SetLocalGatewayRouteTa return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateLocalGatewayRouteTableVpcAssociationInput) SetTagSpecifications(v []*TagSpecification) *CreateLocalGatewayRouteTableVpcAssociationInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateLocalGatewayRouteTableVpcAssociationInput) SetVpcId(v string) *CreateLocalGatewayRouteTableVpcAssociationInput { s.VpcId = &v @@ -46934,6 +48495,151 @@ func (s *CreateLocalGatewayRouteTableVpcAssociationOutput) SetLocalGatewayRouteT return s } +type CreateManagedPrefixListInput struct { + _ struct{} `type:"structure"` + + // The IP address type. + // + // Valid Values: IPv4 | IPv6 + // + // AddressFamily is a required field + AddressFamily *string `type:"string" required:"true"` + + // Unique, case-sensitive identifier you provide to ensure the idempotency of + // the request. For more information, see Ensuring Idempotency (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). + // + // Constraints: Up to 255 UTF-8 characters in length. + ClientToken *string `type:"string" idempotencyToken:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // One or more entries for the prefix list. + Entries []*AddPrefixListEntry `locationName:"Entry" type:"list"` + + // The maximum number of entries for the prefix list. + // + // MaxEntries is a required field + MaxEntries *int64 `type:"integer" required:"true"` + + // A name for the prefix list. + // + // Constraints: Up to 255 characters in length. The name cannot start with com.amazonaws. + // + // PrefixListName is a required field + PrefixListName *string `type:"string" required:"true"` + + // The tags to apply to the prefix list during creation. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s CreateManagedPrefixListInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateManagedPrefixListInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateManagedPrefixListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateManagedPrefixListInput"} + if s.AddressFamily == nil { + invalidParams.Add(request.NewErrParamRequired("AddressFamily")) + } + if s.MaxEntries == nil { + invalidParams.Add(request.NewErrParamRequired("MaxEntries")) + } + if s.PrefixListName == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListName")) + } + if s.Entries != nil { + for i, v := range s.Entries { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Entries", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAddressFamily sets the AddressFamily field's value. +func (s *CreateManagedPrefixListInput) SetAddressFamily(v string) *CreateManagedPrefixListInput { + s.AddressFamily = &v + return s +} + +// SetClientToken sets the ClientToken field's value. +func (s *CreateManagedPrefixListInput) SetClientToken(v string) *CreateManagedPrefixListInput { + s.ClientToken = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *CreateManagedPrefixListInput) SetDryRun(v bool) *CreateManagedPrefixListInput { + s.DryRun = &v + return s +} + +// SetEntries sets the Entries field's value. +func (s *CreateManagedPrefixListInput) SetEntries(v []*AddPrefixListEntry) *CreateManagedPrefixListInput { + s.Entries = v + return s +} + +// SetMaxEntries sets the MaxEntries field's value. +func (s *CreateManagedPrefixListInput) SetMaxEntries(v int64) *CreateManagedPrefixListInput { + s.MaxEntries = &v + return s +} + +// SetPrefixListName sets the PrefixListName field's value. +func (s *CreateManagedPrefixListInput) SetPrefixListName(v string) *CreateManagedPrefixListInput { + s.PrefixListName = &v + return s +} + +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateManagedPrefixListInput) SetTagSpecifications(v []*TagSpecification) *CreateManagedPrefixListInput { + s.TagSpecifications = v + return s +} + +type CreateManagedPrefixListOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list. + PrefixList *ManagedPrefixList `locationName:"prefixList" type:"structure"` +} + +// String returns the string representation +func (s CreateManagedPrefixListOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateManagedPrefixListOutput) GoString() string { + return s.String() +} + +// SetPrefixList sets the PrefixList field's value. +func (s *CreateManagedPrefixListOutput) SetPrefixList(v *ManagedPrefixList) *CreateManagedPrefixListOutput { + s.PrefixList = v + return s +} + type CreateNatGatewayInput struct { _ struct{} `type:"structure"` @@ -47058,6 +48764,8 @@ type CreateNetworkAclEntryInput struct { _ struct{} `type:"structure"` // The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24). + // We modify the specified CIDR block to its canonical form; for example, if + // you specify 100.68.0.18/18, we modify it to 100.68.0.0/18. CidrBlock *string `locationName:"cidrBlock" type:"string"` // Checks whether you have the required permissions for the action, without @@ -47232,6 +48940,9 @@ type CreateNetworkAclInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` + // The tags to assign to the network ACL. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the VPC. // // VpcId is a required field @@ -47267,6 +48978,12 @@ func (s *CreateNetworkAclInput) SetDryRun(v bool) *CreateNetworkAclInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateNetworkAclInput) SetTagSpecifications(v []*TagSpecification) *CreateNetworkAclInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateNetworkAclInput) SetVpcId(v string) *CreateNetworkAclInput { s.VpcId = &v @@ -47353,6 +49070,9 @@ type CreateNetworkInterfaceInput struct { // // SubnetId is a required field SubnetId *string `locationName:"subnetId" type:"string" required:"true"` + + // The tags to apply to the new network interface. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -47438,6 +49158,12 @@ func (s *CreateNetworkInterfaceInput) SetSubnetId(v string) *CreateNetworkInterf return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateNetworkInterfaceInput) SetTagSpecifications(v []*TagSpecification) *CreateNetworkInterfaceInput { + s.TagSpecifications = v + return s +} + // Contains the output of CreateNetworkInterface. type CreateNetworkInterfaceOutput struct { _ struct{} `type:"structure"` @@ -47771,14 +49497,25 @@ func (s *CreateReservedInstancesListingOutput) SetReservedInstancesListings(v [] type CreateRouteInput struct { _ struct{} `type:"structure"` + // The ID of the carrier gateway. + // + // You can only use this option when the VPC contains a subnet which is associated + // with a Wavelength Zone. + CarrierGatewayId *string `type:"string"` + // The IPv4 CIDR address block used for the destination match. Routing decisions - // are based on the most specific match. + // are based on the most specific match. We modify the specified CIDR block + // to its canonical form; for example, if you specify 100.68.0.18/18, we modify + // it to 100.68.0.0/18. DestinationCidrBlock *string `locationName:"destinationCidrBlock" type:"string"` // The IPv6 CIDR block used for the destination match. Routing decisions are // based on the most specific match. DestinationIpv6CidrBlock *string `locationName:"destinationIpv6CidrBlock" type:"string"` + // The ID of a prefix list used for the destination match. + DestinationPrefixListId *string `type:"string"` + // Checks whether you have the required permissions for the action, without // actually making the request, and provides an error response. If you have // the required permissions, the error response is DryRunOperation. Otherwise, @@ -47840,6 +49577,12 @@ func (s *CreateRouteInput) Validate() error { return nil } +// SetCarrierGatewayId sets the CarrierGatewayId field's value. +func (s *CreateRouteInput) SetCarrierGatewayId(v string) *CreateRouteInput { + s.CarrierGatewayId = &v + return s +} + // SetDestinationCidrBlock sets the DestinationCidrBlock field's value. func (s *CreateRouteInput) SetDestinationCidrBlock(v string) *CreateRouteInput { s.DestinationCidrBlock = &v @@ -47852,6 +49595,12 @@ func (s *CreateRouteInput) SetDestinationIpv6CidrBlock(v string) *CreateRouteInp return s } +// SetDestinationPrefixListId sets the DestinationPrefixListId field's value. +func (s *CreateRouteInput) SetDestinationPrefixListId(v string) *CreateRouteInput { + s.DestinationPrefixListId = &v + return s +} + // SetDryRun sets the DryRun field's value. func (s *CreateRouteInput) SetDryRun(v bool) *CreateRouteInput { s.DryRun = &v @@ -47944,6 +49693,9 @@ type CreateRouteTableInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` + // The tags to assign to the route table. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the VPC. // // VpcId is a required field @@ -47979,6 +49731,12 @@ func (s *CreateRouteTableInput) SetDryRun(v bool) *CreateRouteTableInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateRouteTableInput) SetTagSpecifications(v []*TagSpecification) *CreateRouteTableInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateRouteTableInput) SetVpcId(v string) *CreateRouteTableInput { s.VpcId = &v @@ -48039,6 +49797,9 @@ type CreateSecurityGroupInput struct { // GroupName is a required field GroupName *string `type:"string" required:"true"` + // The tags to assign to the security group. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // [EC2-VPC] The ID of the VPC. Required for EC2-VPC. VpcId *string `type:"string"` } @@ -48087,6 +49848,12 @@ func (s *CreateSecurityGroupInput) SetGroupName(v string) *CreateSecurityGroupIn return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateSecurityGroupInput) SetTagSpecifications(v []*TagSpecification) *CreateSecurityGroupInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateSecurityGroupInput) SetVpcId(v string) *CreateSecurityGroupInput { s.VpcId = &v @@ -48098,6 +49865,9 @@ type CreateSecurityGroupOutput struct { // The ID of the security group. GroupId *string `locationName:"groupId" type:"string"` + + // The tags assigned to the security group. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` } // String returns the string representation @@ -48116,6 +49886,12 @@ func (s *CreateSecurityGroupOutput) SetGroupId(v string) *CreateSecurityGroupOut return s } +// SetTags sets the Tags field's value. +func (s *CreateSecurityGroupOutput) SetTags(v []*Tag) *CreateSecurityGroupOutput { + s.Tags = v + return s +} + type CreateSnapshotInput struct { _ struct{} `type:"structure"` @@ -48389,6 +50165,8 @@ type CreateSubnetInput struct { AvailabilityZoneId *string `type:"string"` // The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24. + // We modify the specified CIDR block to its canonical form; for example, if + // you specify 100.68.0.18/18, we modify it to 100.68.0.0/18. // // CidrBlock is a required field CidrBlock *string `type:"string" required:"true"` @@ -48403,9 +50181,13 @@ type CreateSubnetInput struct { // must use a /64 prefix length. Ipv6CidrBlock *string `type:"string"` - // The Amazon Resource Name (ARN) of the Outpost. + // The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost + // ARN, you must also specify the Availability Zone of the Outpost subnet. OutpostArn *string `type:"string"` + // The tags to assign to the subnet. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the VPC. // // VpcId is a required field @@ -48474,6 +50256,12 @@ func (s *CreateSubnetInput) SetOutpostArn(v string) *CreateSubnetInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateSubnetInput) SetTagSpecifications(v []*TagSpecification) *CreateSubnetInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateSubnetInput) SetVpcId(v string) *CreateSubnetInput { s.VpcId = &v @@ -50488,6 +52276,8 @@ type CreateVpcInput struct { AmazonProvidedIpv6CidrBlock *bool `locationName:"amazonProvidedIpv6CidrBlock" type:"boolean"` // The IPv4 network range for the VPC, in CIDR notation. For example, 10.0.0.0/16. + // We modify the specified CIDR block to its canonical form; for example, if + // you specify 100.68.0.18/18, we modify it to 100.68.0.0/18. // // CidrBlock is a required field CidrBlock *string `type:"string" required:"true"` @@ -50524,6 +52314,9 @@ type CreateVpcInput struct { // The ID of an IPv6 address pool from which to allocate the IPv6 CIDR block. Ipv6Pool *string `type:"string"` + + // The tags to assign to the VPC. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -50591,6 +52384,12 @@ func (s *CreateVpcInput) SetIpv6Pool(v string) *CreateVpcInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateVpcInput) SetTagSpecifications(v []*TagSpecification) *CreateVpcInput { + s.TagSpecifications = v + return s +} + type CreateVpcOutput struct { _ struct{} `type:"structure"` @@ -50638,6 +52437,9 @@ type CreateVpcPeeringConnectionInput struct { // You must specify this parameter in the request. PeerVpcId *string `locationName:"peerVpcId" type:"string"` + // The tags to assign to the peering connection. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the requester VPC. You must specify this parameter in the request. VpcId *string `locationName:"vpcId" type:"string"` } @@ -50676,6 +52478,12 @@ func (s *CreateVpcPeeringConnectionInput) SetPeerVpcId(v string) *CreateVpcPeeri return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateVpcPeeringConnectionInput) SetTagSpecifications(v []*TagSpecification) *CreateVpcPeeringConnectionInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateVpcPeeringConnectionInput) SetVpcId(v string) *CreateVpcPeeringConnectionInput { s.VpcId = &v @@ -50723,6 +52531,9 @@ type CreateVpnConnectionInput struct { // The options for the VPN connection. Options *VpnConnectionOptionsSpecification `locationName:"options" type:"structure"` + // The tags to apply to the VPN connection. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the transit gateway. If you specify a transit gateway, you cannot // specify a virtual private gateway. TransitGatewayId *string `type:"string"` @@ -50781,6 +52592,12 @@ func (s *CreateVpnConnectionInput) SetOptions(v *VpnConnectionOptionsSpecificati return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateVpnConnectionInput) SetTagSpecifications(v []*TagSpecification) *CreateVpnConnectionInput { + s.TagSpecifications = v + return s +} + // SetTransitGatewayId sets the TransitGatewayId field's value. func (s *CreateVpnConnectionInput) SetTransitGatewayId(v string) *CreateVpnConnectionInput { s.TransitGatewayId = &v @@ -50910,6 +52727,9 @@ type CreateVpnGatewayInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` + // The tags to apply to the virtual private gateway. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The type of VPN connection this virtual private gateway supports. // // Type is a required field @@ -50957,6 +52777,12 @@ func (s *CreateVpnGatewayInput) SetDryRun(v bool) *CreateVpnGatewayInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateVpnGatewayInput) SetTagSpecifications(v []*TagSpecification) *CreateVpnGatewayInput { + s.TagSpecifications = v + return s +} + // SetType sets the Type field's value. func (s *CreateVpnGatewayInput) SetType(v string) *CreateVpnGatewayInput { s.Type = &v @@ -50987,12 +52813,12 @@ func (s *CreateVpnGatewayOutput) SetVpnGateway(v *VpnGateway) *CreateVpnGatewayO return s } -// Describes the credit option for CPU usage of a T2 or T3 instance. +// Describes the credit option for CPU usage of a T2, T3, or T3a instance. type CreditSpecification struct { _ struct{} `type:"structure"` - // The credit option for CPU usage of a T2 or T3 instance. Valid values are - // standard and unlimited. + // The credit option for CPU usage of a T2, T3, or T3a instance. Valid values + // are standard and unlimited. CpuCredits *string `locationName:"cpuCredits" type:"string"` } @@ -51012,12 +52838,12 @@ func (s *CreditSpecification) SetCpuCredits(v string) *CreditSpecification { return s } -// The credit option for CPU usage of a T2 or T3 instance. +// The credit option for CPU usage of a T2, T3, or T3a instance. type CreditSpecificationRequest struct { _ struct{} `type:"structure"` - // The credit option for CPU usage of a T2 or T3 instance. Valid values are - // standard and unlimited. + // The credit option for CPU usage of a T2, T3, or T3a instance. Valid values + // are standard and unlimited. // // CpuCredits is a required field CpuCredits *string `type:"string" required:"true"` @@ -51141,6 +52967,79 @@ func (s *CustomerGateway) SetType(v string) *CustomerGateway { return s } +type DeleteCarrierGatewayInput struct { + _ struct{} `type:"structure"` + + // The ID of the carrier gateway. + // + // CarrierGatewayId is a required field + CarrierGatewayId *string `type:"string" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` +} + +// String returns the string representation +func (s DeleteCarrierGatewayInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCarrierGatewayInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteCarrierGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteCarrierGatewayInput"} + if s.CarrierGatewayId == nil { + invalidParams.Add(request.NewErrParamRequired("CarrierGatewayId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCarrierGatewayId sets the CarrierGatewayId field's value. +func (s *DeleteCarrierGatewayInput) SetCarrierGatewayId(v string) *DeleteCarrierGatewayInput { + s.CarrierGatewayId = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *DeleteCarrierGatewayInput) SetDryRun(v bool) *DeleteCarrierGatewayInput { + s.DryRun = &v + return s +} + +type DeleteCarrierGatewayOutput struct { + _ struct{} `type:"structure"` + + // Information about the carrier gateway. + CarrierGateway *CarrierGateway `locationName:"carrierGateway" type:"structure"` +} + +// String returns the string representation +func (s DeleteCarrierGatewayOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCarrierGatewayOutput) GoString() string { + return s.String() +} + +// SetCarrierGateway sets the CarrierGateway field's value. +func (s *DeleteCarrierGatewayOutput) SetCarrierGateway(v *CarrierGateway) *DeleteCarrierGatewayOutput { + s.CarrierGateway = v + return s +} + type DeleteClientVpnEndpointInput struct { _ struct{} `type:"structure"` @@ -52427,6 +54326,79 @@ func (s *DeleteLocalGatewayRouteTableVpcAssociationOutput) SetLocalGatewayRouteT return s } +type DeleteManagedPrefixListInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteManagedPrefixListInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteManagedPrefixListInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteManagedPrefixListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteManagedPrefixListInput"} + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *DeleteManagedPrefixListInput) SetDryRun(v bool) *DeleteManagedPrefixListInput { + s.DryRun = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *DeleteManagedPrefixListInput) SetPrefixListId(v string) *DeleteManagedPrefixListInput { + s.PrefixListId = &v + return s +} + +type DeleteManagedPrefixListOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list. + PrefixList *ManagedPrefixList `locationName:"prefixList" type:"structure"` +} + +// String returns the string representation +func (s DeleteManagedPrefixListOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteManagedPrefixListOutput) GoString() string { + return s.String() +} + +// SetPrefixList sets the PrefixList field's value. +func (s *DeleteManagedPrefixListOutput) SetPrefixList(v *ManagedPrefixList) *DeleteManagedPrefixListOutput { + s.PrefixList = v + return s +} + type DeleteNatGatewayInput struct { _ struct{} `type:"structure"` @@ -53000,6 +54972,9 @@ type DeleteRouteInput struct { // for the route exactly. DestinationIpv6CidrBlock *string `locationName:"destinationIpv6CidrBlock" type:"string"` + // The ID of the prefix list for the route. + DestinationPrefixListId *string `type:"string"` + // Checks whether you have the required permissions for the action, without // actually making the request, and provides an error response. If you have // the required permissions, the error response is DryRunOperation. Otherwise, @@ -53047,6 +55022,12 @@ func (s *DeleteRouteInput) SetDestinationIpv6CidrBlock(v string) *DeleteRouteInp return s } +// SetDestinationPrefixListId sets the DestinationPrefixListId field's value. +func (s *DeleteRouteInput) SetDestinationPrefixListId(v string) *DeleteRouteInput { + s.DestinationPrefixListId = &v + return s +} + // SetDryRun sets the DryRun field's value. func (s *DeleteRouteInput) SetDryRun(v bool) *DeleteRouteInput { s.DryRun = &v @@ -55279,7 +57260,8 @@ type DescribeAddressesInput struct { // * instance-id - The ID of the instance the address is associated with, // if any. // - // * network-border-group - The location from where the IP address is advertised. + // * network-border-group - A unique set of Availability Zones, Local Zones, + // or Wavelength Zones from where AWS advertises IP addresses. // // * network-interface-id - [EC2-VPC] The ID of the network interface that // the address is associated with, if any. @@ -55289,7 +57271,7 @@ type DescribeAddressesInput struct { // * private-ip-address - [EC2-VPC] The private IP address associated with // the Elastic IP address. // - // * public-ip - The Elastic IP address. + // * public-ip - The Elastic IP address, or the carrier IP address. // // * tag: - The key/value combination of a tag assigned to the resource. // Use the tag key in the filter name and the tag value as the filter value. @@ -55428,8 +57410,8 @@ func (s *DescribeAggregateIdFormatOutput) SetUseLongIdsAggregated(v bool) *Descr type DescribeAvailabilityZonesInput struct { _ struct{} `type:"structure"` - // Include all Availability Zones and Local Zones regardless of your opt in - // status. + // Include all Availability Zones, Local Zones, and Wavelength Zones regardless + // of your opt-in status. // // If you do not use this parameter, the results include only the zones for // the Regions where you have chosen the option to opt in. @@ -55445,29 +57427,41 @@ type DescribeAvailabilityZonesInput struct { // // * group-name - For Availability Zones, use the Region name. For Local // Zones, use the name of the group associated with the Local Zone (for example, - // us-west-2-lax-1). + // us-west-2-lax-1) For Wavelength Zones, use the name of the group associated + // with the Wavelength Zone (for example, us-east-1-wl1-bos-wlz-1). + // + // * message - The Zone message. // - // * message - The Availability Zone or Local Zone message. + // * opt-in-status - The opt-in status (opted-in, and not-opted-in | opt-in-not-required). // - // * opt-in-status - The opt in status (opted-in, and not-opted-in | opt-in-not-required). + // * parent-zoneID - The ID of the zone that handles some of the Local Zone + // and Wavelength Zone control plane operations, such as API calls. // - // * region-name - The name of the Region for the Availability Zone or Local - // Zone (for example, us-east-1). + // * parent-zoneName - The ID of the zone that handles some of the Local + // Zone and Wavelength Zone control plane operations, such as API calls. // - // * state - The state of the Availability Zone or Local Zone (available - // | information | impaired | unavailable). + // * region-name - The name of the Region for the Zone (for example, us-east-1). // - // * zone-id - The ID of the Availability Zone (for example, use1-az1) or - // the Local Zone (for example, use usw2-lax1-az1). + // * state - The state of the Availability Zone, the Local Zone, or the Wavelength + // Zone (available | information | impaired | unavailable). // - // * zone-name - The name of the Availability Zone (for example, us-east-1a) - // or the Local Zone (for example, use us-west-2-lax-1a). + // * zone-id - The ID of the Availability Zone (for example, use1-az1), the + // Local Zone (for example, usw2-lax1-az1), or the Wavelength Zone (for example, + // us-east-1-wl1-bos-wlz-1). + // + // * zone-type - The type of zone, for example, local-zone. + // + // * zone-name - The name of the Availability Zone (for example, us-east-1a), + // the Local Zone (for example, us-west-2-lax-1a), or the Wavelength Zone + // (for example, us-east-1-wl1-bos-wlz-1). + // + // * zone-type - The type of zone, for example, local-zone. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // The IDs of the Availability Zones and Local Zones. + // The IDs of the Availability Zones, Local Zones, and Wavelength Zones. ZoneIds []*string `locationName:"ZoneId" locationNameList:"ZoneId" type:"list"` - // The names of the Availability Zones and Local Zones. + // The names of the Availability Zones, Local Zones, and Wavelength Zones. ZoneNames []*string `locationName:"ZoneName" locationNameList:"ZoneName" type:"list"` } @@ -55514,7 +57508,7 @@ func (s *DescribeAvailabilityZonesInput) SetZoneNames(v []*string) *DescribeAvai type DescribeAvailabilityZonesOutput struct { _ struct{} `type:"structure"` - // Information about the Availability Zones and Local Zones. + // Information about the Availability Zones, Local Zones, and Wavelength Zones. AvailabilityZones []*AvailabilityZone `locationName:"availabilityZoneInfo" locationNameList:"item" type:"list"` } @@ -55789,10 +57783,11 @@ type DescribeCapacityReservationsInput struct { // The maximum number of results to return for the request in a single page. // The remaining results can be seen by sending another request with the returned - // nextToken value. + // nextToken value. This value can be between 5 and 500. If maxResults is given + // a larger value than 500, you receive an error. MaxResults *int64 `min:"1" type:"integer"` - // The token to retrieve the next page of results. + // The token to use to retrieve the next page of results. NextToken *string `type:"string"` } @@ -55882,6 +57877,134 @@ func (s *DescribeCapacityReservationsOutput) SetNextToken(v string) *DescribeCap return s } +type DescribeCarrierGatewaysInput struct { + _ struct{} `type:"structure"` + + // One or more carrier gateway IDs. + CarrierGatewayIds []*string `locationName:"CarrierGatewayId" type:"list"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // One or more filters. + // + // * carrier-gateway-id - The ID of the carrier gateway. + // + // * state - The state of the carrier gateway (pending | failed | available + // | deleting | deleted). + // + // * owner-id - The AWS account ID of the owner of the carrier gateway. + // + // * tag: - The key/value combination of a tag assigned to the resource. + // Use the tag key in the filter name and the tag value as the filter value. + // For example, to find all resources that have a tag with the key Owner + // and the value TeamA, specify tag:Owner for the filter name and TeamA for + // the filter value. + // + // * tag-key - The key of a tag assigned to the resource. Use this filter + // to find all resources assigned a tag with a specific key, regardless of + // the tag value. + // + // * vpc-id - The ID of the VPC associated with the carrier gateway. + Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` + + // The maximum number of results to return with a single call. To retrieve the + // remaining results, make another call with the returned nextToken value. + MaxResults *int64 `min:"5" type:"integer"` + + // The token for the next page of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeCarrierGatewaysInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCarrierGatewaysInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeCarrierGatewaysInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeCarrierGatewaysInput"} + if s.MaxResults != nil && *s.MaxResults < 5 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 5)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCarrierGatewayIds sets the CarrierGatewayIds field's value. +func (s *DescribeCarrierGatewaysInput) SetCarrierGatewayIds(v []*string) *DescribeCarrierGatewaysInput { + s.CarrierGatewayIds = v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *DescribeCarrierGatewaysInput) SetDryRun(v bool) *DescribeCarrierGatewaysInput { + s.DryRun = &v + return s +} + +// SetFilters sets the Filters field's value. +func (s *DescribeCarrierGatewaysInput) SetFilters(v []*Filter) *DescribeCarrierGatewaysInput { + s.Filters = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeCarrierGatewaysInput) SetMaxResults(v int64) *DescribeCarrierGatewaysInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeCarrierGatewaysInput) SetNextToken(v string) *DescribeCarrierGatewaysInput { + s.NextToken = &v + return s +} + +type DescribeCarrierGatewaysOutput struct { + _ struct{} `type:"structure"` + + // Information about the carrier gateway. + CarrierGateways []*CarrierGateway `locationName:"carrierGatewaySet" locationNameList:"item" type:"list"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s DescribeCarrierGatewaysOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCarrierGatewaysOutput) GoString() string { + return s.String() +} + +// SetCarrierGateways sets the CarrierGateways field's value. +func (s *DescribeCarrierGatewaysOutput) SetCarrierGateways(v []*CarrierGateway) *DescribeCarrierGatewaysOutput { + s.CarrierGateways = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeCarrierGatewaysOutput) SetNextToken(v string) *DescribeCarrierGatewaysOutput { + s.NextToken = &v + return s +} + type DescribeClassicLinkInstancesInput struct { _ struct{} `type:"structure"` @@ -57455,10 +59578,11 @@ type DescribeFastSnapshotRestoreSuccessItem struct { // The time at which fast snapshot restores entered the optimizing state. OptimizingTime *time.Time `locationName:"optimizingTime" type:"timestamp"` - // The alias of the snapshot owner. + // The AWS owner alias that enabled fast snapshot restores on the snapshot. + // This is intended for future use. OwnerAlias *string `locationName:"ownerAlias" type:"string"` - // The ID of the AWS account that owns the snapshot. + // The ID of the AWS account that enabled fast snapshot restores on the snapshot. OwnerId *string `locationName:"ownerId" type:"string"` // The ID of the snapshot. @@ -57566,7 +59690,8 @@ type DescribeFastSnapshotRestoresInput struct { // // * availability-zone: The Availability Zone of the snapshot. // - // * owner-id: The ID of the AWS account that owns the snapshot. + // * owner-id: The ID of the AWS account that enabled fast snapshot restore + // on the snapshot. // // * snapshot-id: The ID of the snapshot. // @@ -59296,11 +61421,13 @@ type DescribeImagesInput struct { // // * name - The name of the AMI (provided during image creation). // - // * owner-alias - String value from an Amazon-maintained list (amazon | - // aws-marketplace | microsoft) of snapshot owners. Not to be confused with - // the user-configured AWS account alias, which is set from the IAM console. + // * owner-alias - The owner alias, from an Amazon-maintained list (amazon + // | aws-marketplace). This is not the user-configured AWS account alias + // set using the IAM console. We recommend that you use the related parameter + // instead of this filter. // - // * owner-id - The AWS account ID of the image owner. + // * owner-id - The AWS account ID of the owner. We recommend that you use + // the related parameter instead of this filter. // // * platform - The platform. To only list Windows-based AMIs, use windows. // @@ -59342,10 +61469,10 @@ type DescribeImagesInput struct { // Default: Describes all images available to you. ImageIds []*string `locationName:"ImageId" locationNameList:"ImageId" type:"list"` - // Filters the images by the owner. Specify an AWS account ID, self (owner is - // the sender of the request), or an AWS owner alias (valid values are amazon - // | aws-marketplace | microsoft). Omitting this option returns all images for - // which you have launch permissions, regardless of ownership. + // Scopes the results to images with the specified owners. You can specify a + // combination of AWS account IDs, self, amazon, and aws-marketplace. If you + // omit this parameter, the results include all images for which you have launch + // permissions, regardless of ownership. Owners []*string `locationName:"Owner" locationNameList:"Owner" type:"list"` } @@ -60286,12 +62413,33 @@ type DescribeInstanceTypesInput struct { // * current-generation - Indicates whether this instance type is the latest // generation instance type of an instance family. (true | false) // + // * ebs-info.ebs-optimized-info.baseline-bandwidth-in-mbps - The baseline + // bandwidth performance for an EBS-optimized instance type, in Mbps. + // + // * ebs-info.ebs-optimized-info.baseline-throughput-in-mbps - The baseline + // throughput performance for an EBS-optimized instance type, in MBps. + // + // * ebs-info.ebs-optimized-info.baseline-iops - The baseline input/output + // storage operations per second for an EBS-optimized instance type. + // + // * ebs-info.ebs-optimized-info.maximum-bandwidth-in-mbps - The maximum + // bandwidth performance for an EBS-optimized instance type, in Mbps. + // + // * ebs-info.ebs-optimized-info.maximum-throughput-in-mbps - The maximum + // throughput performance for an EBS-optimized instance type, in MBps. + // + // * ebs-info.ebs-optimized-info.maximum-iops - The maximum input/output + // storage operations per second for an EBS-optimized instance type. + // // * ebs-info.ebs-optimized-support - Indicates whether the instance type // is EBS-optimized. (supported | unsupported | default) // // * ebs-info.encryption-support - Indicates whether EBS encryption is supported. // (supported | unsupported) // + // * ebs-info.nvme-support - Indicates whether non-volatile memory express + // (NVMe) is supported or required. (required | supported | unsupported) + // // * free-tier-eligible - Indicates whether the instance type is eligible // to use in the free tier. (true | false) // @@ -60319,6 +62467,9 @@ type DescribeInstanceTypesInput struct { // * network-info.ena-support - Indicates whether Elastic Network Adapter // (ENA) is supported or required. (required | supported | unsupported) // + // * network-info.efa-supported - Indicates whether the instance type supports + // Elastic Fabric Adapter (EFA). (true | false) + // // * network-info.ipv4-addresses-per-interface - The maximum number of private // IPv4 addresses per network interface. // @@ -61165,12 +63316,16 @@ type DescribeLaunchTemplateVersionsInput struct { // * ram-disk-id - The RAM disk ID. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // The ID of the launch template. You must specify either the launch template - // ID or launch template name in the request. + // The ID of the launch template. To describe one or more versions of a specified + // launch template, you must specify either the launch template ID or the launch + // template name in the request. To describe all the latest or default launch + // template versions in your account, you must omit this parameter. LaunchTemplateId *string `type:"string"` - // The name of the launch template. You must specify either the launch template - // ID or launch template name in the request. + // The name of the launch template. To describe one or more versions of a specified + // launch template, you must specify either the launch template ID or the launch + // template name in the request. To describe all the latest or default launch + // template versions in your account, you must omit this parameter. LaunchTemplateName *string `min:"3" type:"string"` // The maximum number of results to return in a single call. To retrieve the @@ -61187,7 +63342,18 @@ type DescribeLaunchTemplateVersionsInput struct { // The token to request the next page of results. NextToken *string `type:"string"` - // One or more versions of the launch template. + // One or more versions of the launch template. Valid values depend on whether + // you are describing a specified launch template (by ID or name) or all launch + // templates in your account. + // + // To describe one or more versions of a specified launch template, valid values + // are $Latest, $Default, and numbers. + // + // To describe all launch templates in your account that are defined as the + // latest version, the valid value is $Latest. To describe all launch templates + // in your account that are defined as the default version, the valid value + // is $Default. You can specify $Latest and $Default in the same call. You cannot + // specify numbers. Versions []*string `locationName:"LaunchTemplateVersion" locationNameList:"item" type:"list"` } @@ -61444,6 +63610,18 @@ type DescribeLocalGatewayRouteTableVirtualInterfaceGroupAssociationsInput struct DryRun *bool `type:"boolean"` // One or more filters. + // + // * local-gateway-id - The ID of a local gateway. + // + // * local-gateway-route-table-id - The ID of the local gateway route table. + // + // * local-gateway-route-table-virtual-interface-group-association-id - The + // ID of the association. + // + // * local-gateway-route-table-virtual-interface-group-id - The ID of the + // virtual interface group. + // + // * state - The state of the association. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The IDs of the associations. @@ -61553,6 +63731,16 @@ type DescribeLocalGatewayRouteTableVpcAssociationsInput struct { DryRun *bool `type:"boolean"` // One or more filters. + // + // * local-gateway-id - The ID of a local gateway. + // + // * local-gateway-route-table-id - The ID of the local gateway route table. + // + // * local-gateway-route-table-vpc-association-id - The ID of the association. + // + // * state - The state of the association. + // + // * vpc-id - The ID of the VPC. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The IDs of the associations. @@ -61662,6 +63850,14 @@ type DescribeLocalGatewayRouteTablesInput struct { DryRun *bool `type:"boolean"` // One or more filters. + // + // * local-gateway-id - The ID of a local gateway. + // + // * local-gateway-route-table-id - The ID of a local gateway route table. + // + // * outpost-arn - The Amazon Resource Name (ARN) of the Outpost. + // + // * state - The state of the local gateway route table. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The IDs of the local gateway route tables. @@ -61771,6 +63967,13 @@ type DescribeLocalGatewayVirtualInterfaceGroupsInput struct { DryRun *bool `type:"boolean"` // One or more filters. + // + // * local-gateway-id - The ID of a local gateway. + // + // * local-gateway-virtual-interface-id - The ID of the virtual interface. + // + // * local-gateway-virtual-interface-group-id - The ID of the virtual interface + // group. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The IDs of the virtual interface groups. @@ -61991,7 +64194,21 @@ type DescribeLocalGatewaysInput struct { // One or more filters. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // The IDs of the local gateways. + // One or more filters. + // + // * local-gateway-id - The ID of a local gateway. + // + // * local-gateway-route-table-id - The ID of the local gateway route table. + // + // * local-gateway-route-table-virtual-interface-group-association-id - The + // ID of the association. + // + // * local-gateway-route-table-virtual-interface-group-id - The ID of the + // virtual interface group. + // + // * outpost-arn - The Amazon Resource Name (ARN) of the Outpost. + // + // * state - The state of the association. LocalGatewayIds []*string `locationName:"LocalGatewayId" locationNameList:"item" type:"list"` // The maximum number of results to return with a single call. To retrieve the @@ -62088,6 +64305,121 @@ func (s *DescribeLocalGatewaysOutput) SetNextToken(v string) *DescribeLocalGatew return s } +type DescribeManagedPrefixListsInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // One or more filters. + // + // * owner-id - The ID of the prefix list owner. + // + // * prefix-list-id - The ID of the prefix list. + // + // * prefix-list-name - The name of the prefix list. + Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` + + // The maximum number of results to return with a single call. To retrieve the + // remaining results, make another call with the returned nextToken value. + MaxResults *int64 `min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `type:"string"` + + // One or more prefix list IDs. + PrefixListIds []*string `locationName:"PrefixListId" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s DescribeManagedPrefixListsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeManagedPrefixListsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeManagedPrefixListsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeManagedPrefixListsInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *DescribeManagedPrefixListsInput) SetDryRun(v bool) *DescribeManagedPrefixListsInput { + s.DryRun = &v + return s +} + +// SetFilters sets the Filters field's value. +func (s *DescribeManagedPrefixListsInput) SetFilters(v []*Filter) *DescribeManagedPrefixListsInput { + s.Filters = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeManagedPrefixListsInput) SetMaxResults(v int64) *DescribeManagedPrefixListsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeManagedPrefixListsInput) SetNextToken(v string) *DescribeManagedPrefixListsInput { + s.NextToken = &v + return s +} + +// SetPrefixListIds sets the PrefixListIds field's value. +func (s *DescribeManagedPrefixListsInput) SetPrefixListIds(v []*string) *DescribeManagedPrefixListsInput { + s.PrefixListIds = v + return s +} + +type DescribeManagedPrefixListsOutput struct { + _ struct{} `type:"structure"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` + + // Information about the prefix lists. + PrefixLists []*ManagedPrefixList `locationName:"prefixListSet" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s DescribeManagedPrefixListsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeManagedPrefixListsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeManagedPrefixListsOutput) SetNextToken(v string) *DescribeManagedPrefixListsOutput { + s.NextToken = &v + return s +} + +// SetPrefixLists sets the PrefixLists field's value. +func (s *DescribeManagedPrefixListsOutput) SetPrefixLists(v []*ManagedPrefixList) *DescribeManagedPrefixListsOutput { + s.PrefixLists = v + return s +} + type DescribeMovingAddressesInput struct { _ struct{} `type:"structure"` @@ -62778,9 +65110,6 @@ type DescribeNetworkInterfacesInput struct { // * attachment.instance-owner-id - The owner ID of the instance to which // the network interface is attached. // - // * attachment.nat-gateway-id - The ID of the NAT gateway to which the network - // interface is attached. - // // * attachment.status - The status of the attachment (attaching | attached // | detaching | detached). // @@ -64070,8 +66399,6 @@ type DescribeRouteTablesInput struct { // to find all resources assigned a tag with a specific key, regardless of // the tag value. // - // * transit-gateway-id - The ID of a transit gateway. - // // * vpc-id - The ID of the VPC for the route table. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -64560,8 +66887,8 @@ type DescribeSecurityGroupsInput struct { // * egress.ip-permission.ipv6-cidr - An IPv6 CIDR block for an outbound // security group rule. // - // * egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service - // to which a security group rule allows outbound access. + // * egress.ip-permission.prefix-list-id - The ID of a prefix list to which + // a security group rule allows outbound access. // // * egress.ip-permission.protocol - The IP protocol for an outbound security // group rule (tcp | udp | icmp or a protocol number). @@ -64591,8 +66918,8 @@ type DescribeSecurityGroupsInput struct { // * ip-permission.ipv6-cidr - An IPv6 CIDR block for an inbound security // group rule. // - // * ip-permission.prefix-list-id - The ID (prefix) of the AWS service from - // which a security group rule allows inbound access. + // * ip-permission.prefix-list-id - The ID of a prefix list from which a + // security group rule allows inbound access. // // * ip-permission.protocol - The IP protocol for an inbound security group // rule (tcp | udp | icmp or a protocol number). @@ -64855,12 +67182,12 @@ type DescribeSnapshotsInput struct { // // * encrypted - Indicates whether the snapshot is encrypted (true | false) // - // * owner-alias - Value from an Amazon-maintained list (amazon | self | - // all | aws-marketplace | microsoft) of snapshot owners. Not to be confused - // with the user-configured AWS account alias, which is set from the IAM - // console. + // * owner-alias - The owner alias, from an Amazon-maintained list (amazon). + // This is not the user-configured AWS account alias set using the IAM console. + // We recommend that you use the related parameter instead of this filter. // - // * owner-id - The ID of the AWS account that owns the snapshot. + // * owner-id - The AWS account ID of the owner. We recommend that you use + // the related parameter instead of this filter. // // * progress - The progress of the snapshot, as a percentage (for example, // 80%). @@ -64904,7 +67231,8 @@ type DescribeSnapshotsInput struct { // to return. NextToken *string `type:"string"` - // Describes the snapshots owned by these owners. + // Scopes the results to snapshots with the specified owners. You can specify + // a combination of AWS account IDs, self, and amazon. OwnerIds []*string `locationName:"Owner" locationNameList:"Owner" type:"list"` // The IDs of the AWS accounts that can create volumes from the snapshot. @@ -65515,7 +67843,7 @@ type DescribeSpotInstanceRequestsInput struct { // * state - The state of the Spot Instance request (open | active | closed // | cancelled | failed). Spot request status information can help you track // your Amazon EC2 Spot Instance requests. For more information, see Spot - // Request Status (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) + // request status (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) // in the Amazon EC2 User Guide for Linux Instances. // // * status-code - The short code describing the most recent evaluation of @@ -67643,9 +69971,34 @@ type DescribeVolumesModificationsInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The filters. Supported filters: volume-id | modification-state | target-size - // | target-iops | target-volume-type | original-size | original-iops | original-volume-type - // | start-time | originalMultiAttachEnabled | targetMultiAttachEnabled. + // The filters. + // + // * modification-state - The current modification state (modifying | optimizing + // | completed | failed). + // + // * original-iops - The original IOPS rate of the volume. + // + // * original-size - The original size of the volume, in GiB. + // + // * original-volume-type - The original volume type of the volume (standard + // | io1 | gp2 | sc1 | st1). + // + // * originalMultiAttachEnabled - Indicates whether Multi-Attach support + // was enabled (true | false). + // + // * start-time - The modification start time. + // + // * target-iops - The target IOPS rate of the volume. + // + // * target-size - The target size of the volume, in GiB. + // + // * target-volume-type - The target volume type of the volume (standard + // | io1 | gp2 | sc1 | st1). + // + // * targetMultiAttachEnabled - Indicates whether Multi-Attach support is + // to be enabled (true | false). + // + // * volume-id - The ID of the volume. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The maximum number of results (up to a limit of 500) to be returned in a @@ -67655,7 +70008,7 @@ type DescribeVolumesModificationsInput struct { // The nextToken value returned by a previous paginated request. NextToken *string `type:"string"` - // The IDs of the volumes for which in-progress modifications will be described. + // The IDs of the volumes. VolumeIds []*string `locationName:"VolumeId" locationNameList:"VolumeId" type:"list"` } @@ -69966,10 +72319,11 @@ type DisableFastSnapshotRestoreSuccessItem struct { // The time at which fast snapshot restores entered the optimizing state. OptimizingTime *time.Time `locationName:"optimizingTime" type:"timestamp"` - // The alias of the snapshot owner. + // The AWS owner alias that enabled fast snapshot restores on the snapshot. + // This is intended for future use. OwnerAlias *string `locationName:"ownerAlias" type:"string"` - // The ID of the AWS account that owns the snapshot. + // The ID of the AWS account that enabled fast snapshot restores on the snapshot. OwnerId *string `locationName:"ownerId" type:"string"` // The ID of the snapshot. @@ -71382,7 +73736,7 @@ type EbsBlockDevice struct { _ struct{} `type:"structure"` // Indicates whether the EBS volume is deleted on instance termination. For - // more information, see Preserving Amazon EBS Volumes on Instance Termination + // more information, see Preserving Amazon EBS volumes on instance termination // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) // in the Amazon Elastic Compute Cloud User Guide. DeleteOnTermination *bool `locationName:"deleteOnTermination" type:"boolean"` @@ -71397,7 +73751,7 @@ type EbsBlockDevice struct { // In no case can you remove encryption from an encrypted volume. // // Encrypted volumes can only be attached to instances that support Amazon EBS - // encryption. For more information, see Supported Instance Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances). + // encryption. For more information, see Supported instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances). // // This parameter is not returned by . Encrypted *bool `locationName:"encrypted" type:"boolean"` @@ -71406,10 +73760,10 @@ type EbsBlockDevice struct { // For io1 volumes, this represents the number of IOPS that are provisioned // for the volume. For gp2 volumes, this represents the baseline performance // of the volume and the rate at which the volume accumulates I/O credits for - // bursting. For more information, see Amazon EBS Volume Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) + // bursting. For more information, see Amazon EBS volume types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) // in the Amazon Elastic Compute Cloud User Guide. // - // Constraints: Range is 100-16,000 IOPS for gp2 volumes and 100 to 64,000IOPS + // Constraints: Range is 100-16,000 IOPS for gp2 volumes and 100 to 64,000 IOPS // for io1 volumes in most Regions. Maximum io1 IOPS of 64,000 is guaranteed // only on Nitro-based instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). // Other instance families guarantee performance up to 32,000 IOPS. For more @@ -71508,6 +73862,9 @@ func (s *EbsBlockDevice) SetVolumeType(v string) *EbsBlockDevice { type EbsInfo struct { _ struct{} `type:"structure"` + // Describes the optimized EBS performance for the instance type. + EbsOptimizedInfo *EbsOptimizedInfo `locationName:"ebsOptimizedInfo" type:"structure"` + // Indicates that the instance type is Amazon EBS-optimized. For more information, // see Amazon EBS-Optimized Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html) // in Amazon EC2 User Guide for Linux Instances. @@ -71515,6 +73872,9 @@ type EbsInfo struct { // Indicates whether Amazon EBS encryption is supported. EncryptionSupport *string `locationName:"encryptionSupport" type:"string" enum:"EbsEncryptionSupport"` + + // Indicates whether non-volatile memory express (NVMe) is supported. + NvmeSupport *string `locationName:"nvmeSupport" type:"string" enum:"EbsNvmeSupport"` } // String returns the string representation @@ -71527,6 +73887,12 @@ func (s EbsInfo) GoString() string { return s.String() } +// SetEbsOptimizedInfo sets the EbsOptimizedInfo field's value. +func (s *EbsInfo) SetEbsOptimizedInfo(v *EbsOptimizedInfo) *EbsInfo { + s.EbsOptimizedInfo = v + return s +} + // SetEbsOptimizedSupport sets the EbsOptimizedSupport field's value. func (s *EbsInfo) SetEbsOptimizedSupport(v string) *EbsInfo { s.EbsOptimizedSupport = &v @@ -71539,6 +73905,12 @@ func (s *EbsInfo) SetEncryptionSupport(v string) *EbsInfo { return s } +// SetNvmeSupport sets the NvmeSupport field's value. +func (s *EbsInfo) SetNvmeSupport(v string) *EbsInfo { + s.NvmeSupport = &v + return s +} + // Describes a parameter used to set up an EBS volume in a block device mapping. type EbsInstanceBlockDevice struct { _ struct{} `type:"structure"` @@ -71624,6 +73996,81 @@ func (s *EbsInstanceBlockDeviceSpecification) SetVolumeId(v string) *EbsInstance return s } +// Describes the optimized EBS performance for supported instance types. +type EbsOptimizedInfo struct { + _ struct{} `type:"structure"` + + // The baseline bandwidth performance for an EBS-optimized instance type, in + // Mbps. + BaselineBandwidthInMbps *int64 `locationName:"baselineBandwidthInMbps" type:"integer"` + + // The baseline input/output storage operations per seconds for an EBS-optimized + // instance type. + BaselineIops *int64 `locationName:"baselineIops" type:"integer"` + + // The baseline throughput performance for an EBS-optimized instance type, in + // MBps. + BaselineThroughputInMBps *float64 `locationName:"baselineThroughputInMBps" type:"double"` + + // The maximum bandwidth performance for an EBS-optimized instance type, in + // Mbps. + MaximumBandwidthInMbps *int64 `locationName:"maximumBandwidthInMbps" type:"integer"` + + // The maximum input/output storage operations per second for an EBS-optimized + // instance type. + MaximumIops *int64 `locationName:"maximumIops" type:"integer"` + + // The maximum throughput performance for an EBS-optimized instance type, in + // MBps. + MaximumThroughputInMBps *float64 `locationName:"maximumThroughputInMBps" type:"double"` +} + +// String returns the string representation +func (s EbsOptimizedInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EbsOptimizedInfo) GoString() string { + return s.String() +} + +// SetBaselineBandwidthInMbps sets the BaselineBandwidthInMbps field's value. +func (s *EbsOptimizedInfo) SetBaselineBandwidthInMbps(v int64) *EbsOptimizedInfo { + s.BaselineBandwidthInMbps = &v + return s +} + +// SetBaselineIops sets the BaselineIops field's value. +func (s *EbsOptimizedInfo) SetBaselineIops(v int64) *EbsOptimizedInfo { + s.BaselineIops = &v + return s +} + +// SetBaselineThroughputInMBps sets the BaselineThroughputInMBps field's value. +func (s *EbsOptimizedInfo) SetBaselineThroughputInMBps(v float64) *EbsOptimizedInfo { + s.BaselineThroughputInMBps = &v + return s +} + +// SetMaximumBandwidthInMbps sets the MaximumBandwidthInMbps field's value. +func (s *EbsOptimizedInfo) SetMaximumBandwidthInMbps(v int64) *EbsOptimizedInfo { + s.MaximumBandwidthInMbps = &v + return s +} + +// SetMaximumIops sets the MaximumIops field's value. +func (s *EbsOptimizedInfo) SetMaximumIops(v int64) *EbsOptimizedInfo { + s.MaximumIops = &v + return s +} + +// SetMaximumThroughputInMBps sets the MaximumThroughputInMBps field's value. +func (s *EbsOptimizedInfo) SetMaximumThroughputInMBps(v float64) *EbsOptimizedInfo { + s.MaximumThroughputInMBps = &v + return s +} + // Describes an egress-only internet gateway. type EgressOnlyInternetGateway struct { _ struct{} `type:"structure"` @@ -71896,7 +74343,7 @@ type ElasticInferenceAccelerator struct { Count *int64 `min:"1" type:"integer"` // The type of elastic inference accelerator. The possible values are eia1.medium, - // eia1.large, and eia1.xlarge. + // eia1.large, eia1.xlarge, eia2.medium, eia2.large, and eia2.xlarge. // // Type is a required field Type *string `type:"string" required:"true"` @@ -72164,10 +74611,11 @@ type EnableFastSnapshotRestoreSuccessItem struct { // The time at which fast snapshot restores entered the optimizing state. OptimizingTime *time.Time `locationName:"optimizingTime" type:"timestamp"` - // The alias of the snapshot owner. + // The AWS owner alias that enabled fast snapshot restores on the snapshot. + // This is intended for future use. OwnerAlias *string `locationName:"ownerAlias" type:"string"` - // The ID of the AWS account that owns the snapshot. + // The ID of the AWS account that enabled fast snapshot restores on the snapshot. OwnerId *string `locationName:"ownerId" type:"string"` // The ID of the snapshot. @@ -72979,7 +75427,7 @@ type ExportImageInput struct { // Token to enable idempotency for export image requests. ClientToken *string `type:"string" idempotencyToken:"true"` - // A description of the image being exported. The maximum length is 255 bytes. + // A description of the image being exported. The maximum length is 255 characters. Description *string `type:"string"` // The disk image format. @@ -72999,15 +75447,18 @@ type ExportImageInput struct { ImageId *string `type:"string" required:"true"` // The name of the role that grants VM Import/Export permission to export images - // to your S3 bucket. If this parameter is not specified, the default role is - // named 'vmimport'. + // to your Amazon S3 bucket. If this parameter is not specified, the default + // role is named 'vmimport'. RoleName *string `type:"string"` - // Information about the destination S3 bucket. The bucket must exist and grant - // WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. + // Information about the destination Amazon S3 bucket. The bucket must exist + // and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. // // S3ExportLocation is a required field S3ExportLocation *ExportTaskS3LocationRequest `type:"structure" required:"true"` + + // The tags to apply to the image being exported. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -73086,6 +75537,12 @@ func (s *ExportImageInput) SetS3ExportLocation(v *ExportTaskS3LocationRequest) * return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *ExportImageInput) SetTagSpecifications(v []*TagSpecification) *ExportImageInput { + s.TagSpecifications = v + return s +} + type ExportImageOutput struct { _ struct{} `type:"structure"` @@ -73105,10 +75562,10 @@ type ExportImageOutput struct { Progress *string `locationName:"progress" type:"string"` // The name of the role that grants VM Import/Export permission to export images - // to your S3 bucket. + // to your Amazon S3 bucket. RoleName *string `locationName:"roleName" type:"string"` - // Information about the destination S3 bucket. + // Information about the destination Amazon S3 bucket. S3ExportLocation *ExportTaskS3Location `locationName:"s3ExportLocation" type:"structure"` // The status of the export image task. The possible values are active, completed, @@ -73117,6 +75574,9 @@ type ExportImageOutput struct { // The status message for the export image task. StatusMessage *string `locationName:"statusMessage" type:"string"` + + // Any tags assigned to the image being exported. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` } // String returns the string representation @@ -73183,6 +75643,12 @@ func (s *ExportImageOutput) SetStatusMessage(v string) *ExportImageOutput { return s } +// SetTags sets the Tags field's value. +func (s *ExportImageOutput) SetTags(v []*Tag) *ExportImageOutput { + s.Tags = v + return s +} + // Describes an export image task. type ExportImageTask struct { _ struct{} `type:"structure"` @@ -73199,7 +75665,7 @@ type ExportImageTask struct { // The percent complete of the export image task. Progress *string `locationName:"progress" type:"string"` - // Information about the destination S3 bucket. + // Information about the destination Amazon S3 bucket. S3ExportLocation *ExportTaskS3Location `locationName:"s3ExportLocation" type:"structure"` // The status of the export image task. The possible values are active, completed, @@ -73208,6 +75674,9 @@ type ExportImageTask struct { // The status message for the export image task. StatusMessage *string `locationName:"statusMessage" type:"string"` + + // Any tags assigned to the image being exported. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` } // String returns the string representation @@ -73262,6 +75731,12 @@ func (s *ExportImageTask) SetStatusMessage(v string) *ExportImageTask { return s } +// SetTags sets the Tags field's value. +func (s *ExportImageTask) SetTags(v []*Tag) *ExportImageTask { + s.Tags = v + return s +} + // Describes an instance export task. type ExportTask struct { _ struct{} `type:"structure"` @@ -73344,7 +75819,7 @@ func (s *ExportTask) SetTags(v []*Tag) *ExportTask { type ExportTaskS3Location struct { _ struct{} `type:"structure"` - // The destination S3 bucket. + // The destination Amazon S3 bucket. S3Bucket *string `locationName:"s3Bucket" type:"string"` // The prefix (logical hierarchy) in the bucket. @@ -73377,7 +75852,7 @@ func (s *ExportTaskS3Location) SetS3Prefix(v string) *ExportTaskS3Location { type ExportTaskS3LocationRequest struct { _ struct{} `type:"structure"` - // The destination S3 bucket. + // The destination Amazon S3 bucket. // // S3Bucket is a required field S3Bucket *string `type:"string" required:"true"` @@ -73432,8 +75907,8 @@ type ExportToS3Task struct { // The format for the exported image. DiskImageFormat *string `locationName:"diskImageFormat" type:"string" enum:"DiskImageFormat"` - // The S3 bucket for the destination image. The destination bucket must exist - // and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. + // The Amazon S3 bucket for the destination image. The destination bucket must + // exist and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. S3Bucket *string `locationName:"s3Bucket" type:"string"` // The encryption key for your S3 bucket. @@ -73485,12 +75960,12 @@ type ExportToS3TaskSpecification struct { // The format for the exported image. DiskImageFormat *string `locationName:"diskImageFormat" type:"string" enum:"DiskImageFormat"` - // The S3 bucket for the destination image. The destination bucket must exist - // and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. + // The Amazon S3 bucket for the destination image. The destination bucket must + // exist and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. S3Bucket *string `locationName:"s3Bucket" type:"string"` - // The image is written to a single object in the S3 bucket at the S3 key s3prefix - // + exportTaskId + '.' + diskImageFormat. + // The image is written to a single object in the Amazon S3 bucket at the S3 + // key s3prefix + exportTaskId + '.' + diskImageFormat. S3Prefix *string `locationName:"s3Prefix" type:"string"` } @@ -73683,6 +76158,54 @@ func (s *FailedQueuedPurchaseDeletion) SetReservedInstancesId(v string) *FailedQ return s } +// Describes the IAM SAML identity provider used for federated authentication. +type FederatedAuthentication struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the IAM SAML identity provider. + SamlProviderArn *string `locationName:"samlProviderArn" type:"string"` +} + +// String returns the string representation +func (s FederatedAuthentication) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FederatedAuthentication) GoString() string { + return s.String() +} + +// SetSamlProviderArn sets the SamlProviderArn field's value. +func (s *FederatedAuthentication) SetSamlProviderArn(v string) *FederatedAuthentication { + s.SamlProviderArn = &v + return s +} + +// The IAM SAML identity provider used for federated authentication. +type FederatedAuthenticationRequest struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the IAM SAML identity provider. + SAMLProviderArn *string `type:"string"` +} + +// String returns the string representation +func (s FederatedAuthenticationRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FederatedAuthenticationRequest) GoString() string { + return s.String() +} + +// SetSAMLProviderArn sets the SAMLProviderArn field's value. +func (s *FederatedAuthenticationRequest) SetSAMLProviderArn(v string) *FederatedAuthenticationRequest { + s.SAMLProviderArn = &v + return s +} + // A filter name and value pair that is used to return a more specific list // of results from a describe operation. Filters can be used to match a set // of resources by specific criteria, such as tags, attributes, or IDs. The @@ -74214,19 +76737,30 @@ func (s *FleetLaunchTemplateOverridesRequest) SetWeightedCapacity(v float64) *Fl return s } -// Describes a launch template. +// Describes the Amazon EC2 launch template and the launch template version +// that can be used by a Spot Fleet request to configure Amazon EC2 instances. +// For information about launch templates, see Launching an instance from a +// launch template (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) +// in the Amazon EC2 User Guide for Linux Instances. type FleetLaunchTemplateSpecification struct { _ struct{} `type:"structure"` - // The ID of the launch template. You must specify either a template ID or a - // template name. + // The ID of the launch template. If you specify the template ID, you can't + // specify the template name. LaunchTemplateId *string `locationName:"launchTemplateId" type:"string"` - // The name of the launch template. You must specify either a template name - // or a template ID. + // The name of the launch template. If you specify the template name, you can't + // specify the template ID. LaunchTemplateName *string `locationName:"launchTemplateName" min:"3" type:"string"` - // The version number of the launch template. You must specify a version number. + // The launch template version number, $Latest, or $Default. You must specify + // a value, otherwise the request fails. + // + // If the value is $Latest, Amazon EC2 uses the latest version of the launch + // template. + // + // If the value is $Default, Amazon EC2 uses the default version of the launch + // template. Version *string `locationName:"version" type:"string"` } @@ -74271,19 +76805,30 @@ func (s *FleetLaunchTemplateSpecification) SetVersion(v string) *FleetLaunchTemp return s } -// The launch template to use. You must specify either the launch template ID -// or launch template name in the request. +// Describes the Amazon EC2 launch template and the launch template version +// that can be used by an EC2 Fleet to configure Amazon EC2 instances. For information +// about launch templates, see Launching an instance from a launch template +// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) +// in the Amazon Elastic Compute Cloud User Guide. type FleetLaunchTemplateSpecificationRequest struct { _ struct{} `type:"structure"` - // The ID of the launch template. + // The ID of the launch template. If you specify the template ID, you can't + // specify the template name. LaunchTemplateId *string `type:"string"` - // The name of the launch template. + // The name of the launch template. If you specify the template name, you can't + // specify the template ID. LaunchTemplateName *string `min:"3" type:"string"` - // The version number of the launch template. Note: This is a required parameter - // and will be updated soon. + // The launch template version number, $Latest, or $Default. You must specify + // a value, otherwise the request fails. + // + // If the value is $Latest, Amazon EC2 uses the latest version of the launch + // template. + // + // If the value is $Default, Amazon EC2 uses the default version of the launch + // template. Version *string `type:"string"` } @@ -74968,12 +77513,13 @@ type GetCapacityReservationUsageInput struct { // The maximum number of results to return for the request in a single page. // The remaining results can be seen by sending another request with the returned - // nextToken value. + // nextToken value. This value can be between 5 and 500. If maxResults is given + // a larger value than 500, you receive an error. // // Valid range: Minimum value of 1. Maximum value of 1000. MaxResults *int64 `min:"1" type:"integer"` - // The token to retrieve the next page of results. + // The token to use to retrieve the next page of results. NextToken *string `type:"string"` } @@ -75620,6 +78166,114 @@ func (s *GetEbsEncryptionByDefaultOutput) SetEbsEncryptionByDefault(v bool) *Get return s } +type GetGroupsForCapacityReservationInput struct { + _ struct{} `type:"structure"` + + // The ID of the Capacity Reservation. + // + // CapacityReservationId is a required field + CapacityReservationId *string `type:"string" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The maximum number of results to return for the request in a single page. + // The remaining results can be seen by sending another request with the returned + // nextToken value. This value can be between 5 and 500. If maxResults is given + // a larger value than 500, you receive an error. + MaxResults *int64 `min:"1" type:"integer"` + + // The token to use to retrieve the next page of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s GetGroupsForCapacityReservationInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetGroupsForCapacityReservationInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetGroupsForCapacityReservationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetGroupsForCapacityReservationInput"} + if s.CapacityReservationId == nil { + invalidParams.Add(request.NewErrParamRequired("CapacityReservationId")) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCapacityReservationId sets the CapacityReservationId field's value. +func (s *GetGroupsForCapacityReservationInput) SetCapacityReservationId(v string) *GetGroupsForCapacityReservationInput { + s.CapacityReservationId = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *GetGroupsForCapacityReservationInput) SetDryRun(v bool) *GetGroupsForCapacityReservationInput { + s.DryRun = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetGroupsForCapacityReservationInput) SetMaxResults(v int64) *GetGroupsForCapacityReservationInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetGroupsForCapacityReservationInput) SetNextToken(v string) *GetGroupsForCapacityReservationInput { + s.NextToken = &v + return s +} + +type GetGroupsForCapacityReservationOutput struct { + _ struct{} `type:"structure"` + + // Information about the resource groups to which the Capacity Reservation has + // been added. + CapacityReservationGroups []*CapacityReservationGroup `locationName:"capacityReservationGroupSet" locationNameList:"item" type:"list"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s GetGroupsForCapacityReservationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetGroupsForCapacityReservationOutput) GoString() string { + return s.String() +} + +// SetCapacityReservationGroups sets the CapacityReservationGroups field's value. +func (s *GetGroupsForCapacityReservationOutput) SetCapacityReservationGroups(v []*CapacityReservationGroup) *GetGroupsForCapacityReservationOutput { + s.CapacityReservationGroups = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetGroupsForCapacityReservationOutput) SetNextToken(v string) *GetGroupsForCapacityReservationOutput { + s.NextToken = &v + return s +} + type GetHostReservationPurchasePreviewInput struct { _ struct{} `type:"structure"` @@ -75797,6 +78451,226 @@ func (s *GetLaunchTemplateDataOutput) SetLaunchTemplateData(v *ResponseLaunchTem return s } +type GetManagedPrefixListAssociationsInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The maximum number of results to return with a single call. To retrieve the + // remaining results, make another call with the returned nextToken value. + MaxResults *int64 `min:"5" type:"integer"` + + // The token for the next page of results. + NextToken *string `type:"string"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s GetManagedPrefixListAssociationsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetManagedPrefixListAssociationsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetManagedPrefixListAssociationsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetManagedPrefixListAssociationsInput"} + if s.MaxResults != nil && *s.MaxResults < 5 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 5)) + } + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *GetManagedPrefixListAssociationsInput) SetDryRun(v bool) *GetManagedPrefixListAssociationsInput { + s.DryRun = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetManagedPrefixListAssociationsInput) SetMaxResults(v int64) *GetManagedPrefixListAssociationsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetManagedPrefixListAssociationsInput) SetNextToken(v string) *GetManagedPrefixListAssociationsInput { + s.NextToken = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *GetManagedPrefixListAssociationsInput) SetPrefixListId(v string) *GetManagedPrefixListAssociationsInput { + s.PrefixListId = &v + return s +} + +type GetManagedPrefixListAssociationsOutput struct { + _ struct{} `type:"structure"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` + + // Information about the associations. + PrefixListAssociations []*PrefixListAssociation `locationName:"prefixListAssociationSet" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s GetManagedPrefixListAssociationsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetManagedPrefixListAssociationsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *GetManagedPrefixListAssociationsOutput) SetNextToken(v string) *GetManagedPrefixListAssociationsOutput { + s.NextToken = &v + return s +} + +// SetPrefixListAssociations sets the PrefixListAssociations field's value. +func (s *GetManagedPrefixListAssociationsOutput) SetPrefixListAssociations(v []*PrefixListAssociation) *GetManagedPrefixListAssociationsOutput { + s.PrefixListAssociations = v + return s +} + +type GetManagedPrefixListEntriesInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The maximum number of results to return with a single call. To retrieve the + // remaining results, make another call with the returned nextToken value. + MaxResults *int64 `min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `type:"string"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` + + // The version of the prefix list for which to return the entries. The default + // is the current version. + TargetVersion *int64 `type:"long"` +} + +// String returns the string representation +func (s GetManagedPrefixListEntriesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetManagedPrefixListEntriesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetManagedPrefixListEntriesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetManagedPrefixListEntriesInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *GetManagedPrefixListEntriesInput) SetDryRun(v bool) *GetManagedPrefixListEntriesInput { + s.DryRun = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetManagedPrefixListEntriesInput) SetMaxResults(v int64) *GetManagedPrefixListEntriesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetManagedPrefixListEntriesInput) SetNextToken(v string) *GetManagedPrefixListEntriesInput { + s.NextToken = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *GetManagedPrefixListEntriesInput) SetPrefixListId(v string) *GetManagedPrefixListEntriesInput { + s.PrefixListId = &v + return s +} + +// SetTargetVersion sets the TargetVersion field's value. +func (s *GetManagedPrefixListEntriesInput) SetTargetVersion(v int64) *GetManagedPrefixListEntriesInput { + s.TargetVersion = &v + return s +} + +type GetManagedPrefixListEntriesOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list entries. + Entries []*PrefixListEntry `locationName:"entrySet" locationNameList:"item" type:"list"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s GetManagedPrefixListEntriesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetManagedPrefixListEntriesOutput) GoString() string { + return s.String() +} + +// SetEntries sets the Entries field's value. +func (s *GetManagedPrefixListEntriesOutput) SetEntries(v []*PrefixListEntry) *GetManagedPrefixListEntriesOutput { + s.Entries = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetManagedPrefixListEntriesOutput) SetNextToken(v string) *GetManagedPrefixListEntriesOutput { + s.NextToken = &v + return s +} + type GetPasswordDataInput struct { _ struct{} `type:"structure"` @@ -76676,7 +79550,7 @@ func (s *GroupIdentifier) SetGroupName(v string) *GroupIdentifier { // Indicates whether your instance is configured for hibernation. This parameter // is valid only if the instance meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites). -// For more information, see Hibernate Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) +// For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon Elastic Compute Cloud User Guide. type HibernationOptions struct { _ struct{} `type:"structure"` @@ -76704,7 +79578,7 @@ func (s *HibernationOptions) SetConfigured(v bool) *HibernationOptions { // Indicates whether your instance is configured for hibernation. This parameter // is valid only if the instance meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites). -// For more information, see Hibernate Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) +// For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon Elastic Compute Cloud User Guide. type HibernationOptionsRequest struct { _ struct{} `type:"structure"` @@ -77854,7 +80728,7 @@ type ImageDiskContainer struct { // The format of the disk image being imported. // - // Valid values: VHD | VMDK | OVA + // Valid values: OVA | VHD | VHDX |VMDK Format *string `type:"string"` // The ID of the EBS snapshot to be used for importing the snapshot. @@ -78096,6 +80970,9 @@ type ImportImageInput struct { // The name of the role to use when not using the default role, 'vmimport'. RoleName *string `type:"string"` + + // The tags to apply to the image being imported. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -78186,6 +81063,12 @@ func (s *ImportImageInput) SetRoleName(v string) *ImportImageInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *ImportImageInput) SetTagSpecifications(v []*TagSpecification) *ImportImageInput { + s.TagSpecifications = v + return s +} + // The request information of license configurations. type ImportImageLicenseConfigurationRequest struct { _ struct{} `type:"structure"` @@ -78243,7 +81126,7 @@ type ImportImageOutput struct { // A description of the import task. Description *string `locationName:"description" type:"string"` - // Indicates whether the AMI is encypted. + // Indicates whether the AMI is encrypted. Encrypted *bool `locationName:"encrypted" type:"boolean"` // The target hypervisor of the import task. @@ -78279,6 +81162,9 @@ type ImportImageOutput struct { // A detailed status message of the import task. StatusMessage *string `locationName:"statusMessage" type:"string"` + + // Any tags assigned to the image being imported. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` } // String returns the string representation @@ -78375,6 +81261,12 @@ func (s *ImportImageOutput) SetStatusMessage(v string) *ImportImageOutput { return s } +// SetTags sets the Tags field's value. +func (s *ImportImageOutput) SetTags(v []*Tag) *ImportImageOutput { + s.Tags = v + return s +} + // Describes an import image task. type ImportImageTask struct { _ struct{} `type:"structure"` @@ -79075,6 +81967,9 @@ type ImportSnapshotInput struct { // The name of the role to use when not using the default role, 'vmimport'. RoleName *string `type:"string"` + + // The tags to apply to the snapshot being imported. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -79135,6 +82030,12 @@ func (s *ImportSnapshotInput) SetRoleName(v string) *ImportSnapshotInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *ImportSnapshotInput) SetTagSpecifications(v []*TagSpecification) *ImportSnapshotInput { + s.TagSpecifications = v + return s +} + type ImportSnapshotOutput struct { _ struct{} `type:"structure"` @@ -79146,6 +82047,9 @@ type ImportSnapshotOutput struct { // Information about the import snapshot task. SnapshotTaskDetail *SnapshotTaskDetail `locationName:"snapshotTaskDetail" type:"structure"` + + // Any tags assigned to the snapshot being imported. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` } // String returns the string representation @@ -79176,6 +82080,12 @@ func (s *ImportSnapshotOutput) SetSnapshotTaskDetail(v *SnapshotTaskDetail) *Imp return s } +// SetTags sets the Tags field's value. +func (s *ImportSnapshotOutput) SetTags(v []*Tag) *ImportSnapshotOutput { + s.Tags = v + return s +} + // Describes an import snapshot task. type ImportSnapshotTask struct { _ struct{} `type:"structure"` @@ -79589,7 +82499,11 @@ type Instance struct { // name is only available if you've enabled DNS hostnames for your VPC. PublicDnsName *string `locationName:"dnsName" type:"string"` - // The public IPv4 address assigned to the instance, if applicable. + // The public IPv4 address, or the Carrier IP address assigned to the instance, + // if applicable. + // + // A Carrier IP address only applies to an instance launched in a subnet associated + // with a Wavelength Zone. PublicIpAddress *string `locationName:"ipAddress" type:"string"` // The RAM disk associated with this instance, if applicable. @@ -80654,6 +83568,9 @@ func (s *InstanceNetworkInterface) SetVpcId(v string) *InstanceNetworkInterface type InstanceNetworkInterfaceAssociation struct { _ struct{} `type:"structure"` + // The carrier IP address associated with the network interface. + CarrierIp *string `locationName:"carrierIp" type:"string"` + // The ID of the owner of the Elastic IP address. IpOwnerId *string `locationName:"ipOwnerId" type:"string"` @@ -80674,6 +83591,12 @@ func (s InstanceNetworkInterfaceAssociation) GoString() string { return s.String() } +// SetCarrierIp sets the CarrierIp field's value. +func (s *InstanceNetworkInterfaceAssociation) SetCarrierIp(v string) *InstanceNetworkInterfaceAssociation { + s.CarrierIp = &v + return s +} + // SetIpOwnerId sets the IpOwnerId field's value. func (s *InstanceNetworkInterfaceAssociation) SetIpOwnerId(v string) *InstanceNetworkInterfaceAssociation { s.IpOwnerId = &v @@ -80756,6 +83679,13 @@ func (s *InstanceNetworkInterfaceAttachment) SetStatus(v string) *InstanceNetwor type InstanceNetworkInterfaceSpecification struct { _ struct{} `type:"structure"` + // Indicates whether to assign a carrier IP address to the network interface. + // + // You can only assign a carrier IP address to a network interface that is in + // a subnet in a Wavelength Zone. For more information about carrier IP addresses, + // see Carrier IP addresses in the AWS Wavelength Developer Guide. + AssociateCarrierIpAddress *bool `type:"boolean"` + // Indicates whether to assign a public IPv4 address to an instance you launch // in a VPC. The public IP address can only be assigned to a network interface // for eth0, and can only be assigned to a new network interface, not an existing @@ -80846,6 +83776,12 @@ func (s InstanceNetworkInterfaceSpecification) GoString() string { return s.String() } +// SetAssociateCarrierIpAddress sets the AssociateCarrierIpAddress field's value. +func (s *InstanceNetworkInterfaceSpecification) SetAssociateCarrierIpAddress(v bool) *InstanceNetworkInterfaceSpecification { + s.AssociateCarrierIpAddress = &v + return s +} + // SetAssociatePublicIpAddress sets the AssociatePublicIpAddress field's value. func (s *InstanceNetworkInterfaceSpecification) SetAssociatePublicIpAddress(v bool) *InstanceNetworkInterfaceSpecification { s.AssociatePublicIpAddress = &v @@ -81476,6 +84412,9 @@ type InstanceTypeInfo struct { // Indicates whether the instance type is offered for spot or On-Demand. SupportedUsageClasses []*string `locationName:"supportedUsageClasses" locationNameList:"item" type:"list"` + // The supported virtualization types. + SupportedVirtualizationTypes []*string `locationName:"supportedVirtualizationTypes" locationNameList:"item" type:"list"` + // Describes the vCPU configurations for the instance type. VCpuInfo *VCpuInfo `locationName:"vCpuInfo" type:"structure"` } @@ -81616,6 +84555,12 @@ func (s *InstanceTypeInfo) SetSupportedUsageClasses(v []*string) *InstanceTypeIn return s } +// SetSupportedVirtualizationTypes sets the SupportedVirtualizationTypes field's value. +func (s *InstanceTypeInfo) SetSupportedVirtualizationTypes(v []*string) *InstanceTypeInfo { + s.SupportedVirtualizationTypes = v + return s +} + // SetVCpuInfo sets the VCpuInfo field's value. func (s *InstanceTypeInfo) SetVCpuInfo(v *VCpuInfo) *InstanceTypeInfo { s.VCpuInfo = v @@ -81812,9 +84757,7 @@ type IpPermission struct { // [VPC only] The IPv6 ranges. Ipv6Ranges []*Ipv6Range `locationName:"ipv6Ranges" locationNameList:"item" type:"list"` - // [VPC only] The prefix list IDs for an AWS service. With outbound rules, this - // is the AWS service to access through a VPC endpoint from instances associated - // with the security group. + // [VPC only] The prefix list IDs. PrefixListIds []*PrefixListId `locationName:"prefixListIds" locationNameList:"item" type:"list"` // The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. @@ -82601,7 +85544,7 @@ func (s *LaunchTemplateBlockDeviceMappingRequest) SetVirtualName(v string) *Laun // to configure the instance to run in On-Demand capacity or to run in any open // Capacity Reservation that has matching attributes (instance type, platform, // Availability Zone). Use the CapacityReservationTarget parameter to explicitly -// target a specific Capacity Reservation. +// target a specific Capacity Reservation or a Capacity Reservation group. type LaunchTemplateCapacityReservationSpecificationRequest struct { _ struct{} `type:"structure"` @@ -82615,7 +85558,8 @@ type LaunchTemplateCapacityReservationSpecificationRequest struct { // one is available. The instance runs in On-Demand capacity. CapacityReservationPreference *string `type:"string" enum:"CapacityReservationPreference"` - // Information about the target Capacity Reservation. + // Information about the target Capacity Reservation or Capacity Reservation + // group. CapacityReservationTarget *CapacityReservationTarget `type:"structure"` } @@ -82655,7 +85599,8 @@ type LaunchTemplateCapacityReservationSpecificationResponse struct { // one is available. The instance runs in On-Demand capacity. CapacityReservationPreference *string `locationName:"capacityReservationPreference" type:"string" enum:"CapacityReservationPreference"` - // Information about the target Capacity Reservation. + // Information about the target Capacity Reservation or Capacity Reservation + // group. CapacityReservationTarget *CapacityReservationTargetResponse `locationName:"capacityReservationTarget" type:"structure"` } @@ -83391,6 +86336,15 @@ func (s *LaunchTemplateInstanceMetadataOptionsRequest) SetHttpTokens(v string) * type LaunchTemplateInstanceNetworkInterfaceSpecification struct { _ struct{} `type:"structure"` + // Indicates whether to associate a Carrier IP address with eth0 for a new network + // interface. + // + // Use this option when you launch an instance in a Wavelength Zone and want + // to associate a Carrier IP address with the network interface. For more information + // about Carrier IP addresses, see Carrier IP addresses (https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#provider-owned-ip) + // in the AWS Wavelength Developer Guide. + AssociateCarrierIpAddress *bool `locationName:"associateCarrierIpAddress" type:"boolean"` + // Indicates whether to associate a public IPv4 address with eth0 for a new // network interface. AssociatePublicIpAddress *bool `locationName:"associatePublicIpAddress" type:"boolean"` @@ -83442,6 +86396,12 @@ func (s LaunchTemplateInstanceNetworkInterfaceSpecification) GoString() string { return s.String() } +// SetAssociateCarrierIpAddress sets the AssociateCarrierIpAddress field's value. +func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetAssociateCarrierIpAddress(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecification { + s.AssociateCarrierIpAddress = &v + return s +} + // SetAssociatePublicIpAddress sets the AssociatePublicIpAddress field's value. func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetAssociatePublicIpAddress(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecification { s.AssociatePublicIpAddress = &v @@ -83524,6 +86484,14 @@ func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetSubnetId(v stri type LaunchTemplateInstanceNetworkInterfaceSpecificationRequest struct { _ struct{} `type:"structure"` + // Associates a Carrier IP address with eth0 for a new network interface. + // + // Use this option when you launch an instance in a Wavelength Zone and want + // to associate a Carrier IP address with the network interface. For more information + // about Carrier IP addresses, see Carrier IP addresses (https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#provider-owned-ip) + // in the AWS Wavelength Developer Guide. + AssociateCarrierIpAddress *bool `type:"boolean"` + // Associates a public IPv4 address with eth0 for a new network interface. AssociatePublicIpAddress *bool `type:"boolean"` @@ -83583,6 +86551,12 @@ func (s LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) GoString() s return s.String() } +// SetAssociateCarrierIpAddress sets the AssociateCarrierIpAddress field's value. +func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetAssociateCarrierIpAddress(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest { + s.AssociateCarrierIpAddress = &v + return s +} + // SetAssociatePublicIpAddress sets the AssociatePublicIpAddress field's value. func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetAssociatePublicIpAddress(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest { s.AssociatePublicIpAddress = &v @@ -85003,6 +87977,111 @@ func (s *LocalGatewayVirtualInterfaceGroup) SetTags(v []*Tag) *LocalGatewayVirtu return s } +// Describes a managed prefix list. +type ManagedPrefixList struct { + _ struct{} `type:"structure"` + + // The IP address version. + AddressFamily *string `locationName:"addressFamily" type:"string"` + + // The maximum number of entries for the prefix list. + MaxEntries *int64 `locationName:"maxEntries" type:"integer"` + + // The ID of the owner of the prefix list. + OwnerId *string `locationName:"ownerId" type:"string"` + + // The Amazon Resource Name (ARN) for the prefix list. + PrefixListArn *string `locationName:"prefixListArn" min:"1" type:"string"` + + // The ID of the prefix list. + PrefixListId *string `locationName:"prefixListId" type:"string"` + + // The name of the prefix list. + PrefixListName *string `locationName:"prefixListName" type:"string"` + + // The state of the prefix list. + State *string `locationName:"state" type:"string" enum:"PrefixListState"` + + // The state message. + StateMessage *string `locationName:"stateMessage" type:"string"` + + // The tags for the prefix list. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` + + // The version of the prefix list. + Version *int64 `locationName:"version" type:"long"` +} + +// String returns the string representation +func (s ManagedPrefixList) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ManagedPrefixList) GoString() string { + return s.String() +} + +// SetAddressFamily sets the AddressFamily field's value. +func (s *ManagedPrefixList) SetAddressFamily(v string) *ManagedPrefixList { + s.AddressFamily = &v + return s +} + +// SetMaxEntries sets the MaxEntries field's value. +func (s *ManagedPrefixList) SetMaxEntries(v int64) *ManagedPrefixList { + s.MaxEntries = &v + return s +} + +// SetOwnerId sets the OwnerId field's value. +func (s *ManagedPrefixList) SetOwnerId(v string) *ManagedPrefixList { + s.OwnerId = &v + return s +} + +// SetPrefixListArn sets the PrefixListArn field's value. +func (s *ManagedPrefixList) SetPrefixListArn(v string) *ManagedPrefixList { + s.PrefixListArn = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *ManagedPrefixList) SetPrefixListId(v string) *ManagedPrefixList { + s.PrefixListId = &v + return s +} + +// SetPrefixListName sets the PrefixListName field's value. +func (s *ManagedPrefixList) SetPrefixListName(v string) *ManagedPrefixList { + s.PrefixListName = &v + return s +} + +// SetState sets the State field's value. +func (s *ManagedPrefixList) SetState(v string) *ManagedPrefixList { + s.State = &v + return s +} + +// SetStateMessage sets the StateMessage field's value. +func (s *ManagedPrefixList) SetStateMessage(v string) *ManagedPrefixList { + s.StateMessage = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *ManagedPrefixList) SetTags(v []*Tag) *ManagedPrefixList { + s.Tags = v + return s +} + +// SetVersion sets the Version field's value. +func (s *ManagedPrefixList) SetVersion(v int64) *ManagedPrefixList { + s.Version = &v + return s +} + // Describes the memory for the instance type. type MemoryInfo struct { _ struct{} `type:"structure"` @@ -85036,14 +88115,16 @@ type ModifyAvailabilityZoneGroupInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The name of the Availability Zone Group. + // The name of the Availability Zone group, Local Zone group, or Wavelength + // Zone group. // // GroupName is a required field GroupName *string `type:"string" required:"true"` - // Indicates whether to enable or disable membership. The valid values are opted-in. - // You must contact AWS Support (https://console.aws.amazon.com/support/home#/case/create%3FissueType=customer-service%26serviceCode=general-info%26getting-started%26categoryCode=using-aws%26services) - // to disable an Availability Zone group. + // Indicates whether you are opted in to the Local Zone group or Wavelength + // Zone group. The only valid value is opted-in. You must contact AWS Support + // (https://console.aws.amazon.com/support/home#/case/create%3FissueType=customer-service%26serviceCode=general-info%26getting-started%26categoryCode=using-aws%26services) + // to opt out of a Local Zone group, or Wavelength Zone group. // // OptInStatus is a required field OptInStatus *string `type:"string" required:"true" enum:"ModifyAvailabilityZoneOptInStatus"` @@ -86274,7 +89355,7 @@ type ModifyInstanceAttributeInput struct { // // To add instance store volumes to an Amazon EBS-backed instance, you must // add them when you launch the instance. For more information, see Updating - // the Block Device Mapping when Launching an Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#Using_OverridingAMIBDM) + // the block device mapping when launching an instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#Using_OverridingAMIBDM) // in the Amazon Elastic Compute Cloud User Guide. BlockDeviceMappings []*InstanceBlockDeviceMappingSpecification `locationName:"blockDeviceMapping" locationNameList:"item" type:"list"` @@ -86317,7 +89398,7 @@ type ModifyInstanceAttributeInput struct { InstanceInitiatedShutdownBehavior *AttributeValue `locationName:"instanceInitiatedShutdownBehavior" type:"structure"` // Changes the instance type to the specified value. For more information, see - // Instance Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html). + // Instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html). // If the instance type is not valid, the error returned is InvalidInstanceAttributeValue. InstanceType *AttributeValue `locationName:"instanceType" type:"structure"` @@ -87125,6 +90206,135 @@ func (s *ModifyLaunchTemplateOutput) SetLaunchTemplate(v *LaunchTemplate) *Modif return s } +type ModifyManagedPrefixListInput struct { + _ struct{} `type:"structure"` + + // One or more entries to add to the prefix list. + AddEntries []*AddPrefixListEntry `locationName:"AddEntry" type:"list"` + + // The current version of the prefix list. + CurrentVersion *int64 `type:"long"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` + + // A name for the prefix list. + PrefixListName *string `type:"string"` + + // One or more entries to remove from the prefix list. + RemoveEntries []*RemovePrefixListEntry `locationName:"RemoveEntry" type:"list"` +} + +// String returns the string representation +func (s ModifyManagedPrefixListInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModifyManagedPrefixListInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ModifyManagedPrefixListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ModifyManagedPrefixListInput"} + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + if s.AddEntries != nil { + for i, v := range s.AddEntries { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "AddEntries", i), err.(request.ErrInvalidParams)) + } + } + } + if s.RemoveEntries != nil { + for i, v := range s.RemoveEntries { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RemoveEntries", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAddEntries sets the AddEntries field's value. +func (s *ModifyManagedPrefixListInput) SetAddEntries(v []*AddPrefixListEntry) *ModifyManagedPrefixListInput { + s.AddEntries = v + return s +} + +// SetCurrentVersion sets the CurrentVersion field's value. +func (s *ModifyManagedPrefixListInput) SetCurrentVersion(v int64) *ModifyManagedPrefixListInput { + s.CurrentVersion = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *ModifyManagedPrefixListInput) SetDryRun(v bool) *ModifyManagedPrefixListInput { + s.DryRun = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *ModifyManagedPrefixListInput) SetPrefixListId(v string) *ModifyManagedPrefixListInput { + s.PrefixListId = &v + return s +} + +// SetPrefixListName sets the PrefixListName field's value. +func (s *ModifyManagedPrefixListInput) SetPrefixListName(v string) *ModifyManagedPrefixListInput { + s.PrefixListName = &v + return s +} + +// SetRemoveEntries sets the RemoveEntries field's value. +func (s *ModifyManagedPrefixListInput) SetRemoveEntries(v []*RemovePrefixListEntry) *ModifyManagedPrefixListInput { + s.RemoveEntries = v + return s +} + +type ModifyManagedPrefixListOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list. + PrefixList *ManagedPrefixList `locationName:"prefixList" type:"structure"` +} + +// String returns the string representation +func (s ModifyManagedPrefixListOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModifyManagedPrefixListOutput) GoString() string { + return s.String() +} + +// SetPrefixList sets the PrefixList field's value. +func (s *ModifyManagedPrefixListOutput) SetPrefixList(v *ManagedPrefixList) *ModifyManagedPrefixListOutput { + s.PrefixList = v + return s +} + // Contains the parameters for ModifyNetworkInterfaceAttribute. type ModifyNetworkInterfaceAttributeInput struct { _ struct{} `type:"structure"` @@ -89395,19 +92605,19 @@ type ModifyVpnTunnelOptionsSpecification struct { // One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel // for phase 1 IKE negotiations. // - // Valid values: 2 | 14 | 15 | 16 | 17 | 18 | 22 | 23 | 24 + // Valid values: 2 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 Phase1DHGroupNumbers []*Phase1DHGroupNumbersRequestListValue `locationName:"Phase1DHGroupNumber" locationNameList:"item" type:"list"` // One or more encryption algorithms that are permitted for the VPN tunnel for // phase 1 IKE negotiations. // - // Valid values: AES128 | AES256 + // Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 Phase1EncryptionAlgorithms []*Phase1EncryptionAlgorithmsRequestListValue `locationName:"Phase1EncryptionAlgorithm" locationNameList:"item" type:"list"` // One or more integrity algorithms that are permitted for the VPN tunnel for // phase 1 IKE negotiations. // - // Valid values: SHA1 | SHA2-256 + // Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 Phase1IntegrityAlgorithms []*Phase1IntegrityAlgorithmsRequestListValue `locationName:"Phase1IntegrityAlgorithm" locationNameList:"item" type:"list"` // The lifetime for phase 1 of the IKE negotiation, in seconds. @@ -89420,19 +92630,19 @@ type ModifyVpnTunnelOptionsSpecification struct { // One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel // for phase 2 IKE negotiations. // - // Valid values: 2 | 5 | 14 | 15 | 16 | 17 | 18 | 22 | 23 | 24 + // Valid values: 2 | 5 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 Phase2DHGroupNumbers []*Phase2DHGroupNumbersRequestListValue `locationName:"Phase2DHGroupNumber" locationNameList:"item" type:"list"` // One or more encryption algorithms that are permitted for the VPN tunnel for // phase 2 IKE negotiations. // - // Valid values: AES128 | AES256 + // Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 Phase2EncryptionAlgorithms []*Phase2EncryptionAlgorithmsRequestListValue `locationName:"Phase2EncryptionAlgorithm" locationNameList:"item" type:"list"` // One or more integrity algorithms that are permitted for the VPN tunnel for // phase 2 IKE negotiations. // - // Valid values: SHA1 | SHA2-256 + // Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 Phase2IntegrityAlgorithms []*Phase2IntegrityAlgorithmsRequestListValue `locationName:"Phase2IntegrityAlgorithm" locationNameList:"item" type:"list"` // The lifetime for phase 2 of the IKE negotiation, in seconds. @@ -89475,7 +92685,7 @@ type ModifyVpnTunnelOptionsSpecification struct { // Default: 1024 ReplayWindowSize *int64 `type:"integer"` - // The range of inside IP addresses for the tunnel. Any specified CIDR blocks + // The range of inside IPv4 addresses for the tunnel. Any specified CIDR blocks // must be unique across all VPN connections that use the same virtual private // gateway. // @@ -89496,6 +92706,12 @@ type ModifyVpnTunnelOptionsSpecification struct { // // * 169.254.169.252/30 TunnelInsideCidr *string `type:"string"` + + // The range of inside IPv6 addresses for the tunnel. Any specified CIDR blocks + // must be unique across all VPN connections that use the same transit gateway. + // + // Constraints: A size /126 CIDR block from the local fd00::/8 range. + TunnelInsideIpv6Cidr *string `type:"string"` } // String returns the string representation @@ -89598,6 +92814,12 @@ func (s *ModifyVpnTunnelOptionsSpecification) SetTunnelInsideCidr(v string) *Mod return s } +// SetTunnelInsideIpv6Cidr sets the TunnelInsideIpv6Cidr field's value. +func (s *ModifyVpnTunnelOptionsSpecification) SetTunnelInsideIpv6Cidr(v string) *ModifyVpnTunnelOptionsSpecification { + s.TunnelInsideIpv6Cidr = &v + return s +} + type MonitorInstancesInput struct { _ struct{} `type:"structure"` @@ -90231,6 +93453,9 @@ func (s *NetworkAclEntry) SetRuleNumber(v int64) *NetworkAclEntry { type NetworkInfo struct { _ struct{} `type:"structure"` + // Indicates whether Elastic Fabric Adapter (EFA) is supported. + EfaSupported *bool `locationName:"efaSupported" type:"boolean"` + // Indicates whether Elastic Network Adapter (ENA) is supported. EnaSupport *string `locationName:"enaSupport" type:"string" enum:"EnaSupport"` @@ -90260,6 +93485,12 @@ func (s NetworkInfo) GoString() string { return s.String() } +// SetEfaSupported sets the EfaSupported field's value. +func (s *NetworkInfo) SetEfaSupported(v bool) *NetworkInfo { + s.EfaSupported = &v + return s +} + // SetEnaSupport sets the EnaSupport field's value. func (s *NetworkInfo) SetEnaSupport(v string) *NetworkInfo { s.EnaSupport = &v @@ -90502,7 +93733,9 @@ func (s *NetworkInterface) SetVpcId(v string) *NetworkInterface { return s } -// Describes association information for an Elastic IP address (IPv4 only). +// Describes association information for an Elastic IP address (IPv4 only), +// or a Carrier IP address (for a network interface which resides in a subnet +// in a Wavelength Zone). type NetworkInterfaceAssociation struct { _ struct{} `type:"structure"` @@ -90512,13 +93745,23 @@ type NetworkInterfaceAssociation struct { // The association ID. AssociationId *string `locationName:"associationId" type:"string"` + // The carrier IP address associated with the network interface. + // + // This option is only available when the network interface is in a subnet which + // is associated with a Wavelength Zone. + CarrierIp *string `locationName:"carrierIp" type:"string"` + + // The customer-owned IP address associated with the network interface. + CustomerOwnedIp *string `locationName:"customerOwnedIp" type:"string"` + // The ID of the Elastic IP address owner. IpOwnerId *string `locationName:"ipOwnerId" type:"string"` // The public DNS name. PublicDnsName *string `locationName:"publicDnsName" type:"string"` - // The address of the Elastic IP address bound to the network interface. + // The address of the Elastic IP address or Carrier IP address bound to the + // network interface. PublicIp *string `locationName:"publicIp" type:"string"` } @@ -90544,6 +93787,18 @@ func (s *NetworkInterfaceAssociation) SetAssociationId(v string) *NetworkInterfa return s } +// SetCarrierIp sets the CarrierIp field's value. +func (s *NetworkInterfaceAssociation) SetCarrierIp(v string) *NetworkInterfaceAssociation { + s.CarrierIp = &v + return s +} + +// SetCustomerOwnedIp sets the CustomerOwnedIp field's value. +func (s *NetworkInterfaceAssociation) SetCustomerOwnedIp(v string) *NetworkInterfaceAssociation { + s.CustomerOwnedIp = &v + return s +} + // SetIpOwnerId sets the IpOwnerId field's value. func (s *NetworkInterfaceAssociation) SetIpOwnerId(v string) *NetworkInterfaceAssociation { s.IpOwnerId = &v @@ -91877,6 +95132,72 @@ func (s *PrefixList) SetPrefixListName(v string) *PrefixList { return s } +// Describes the resource with which a prefix list is associated. +type PrefixListAssociation struct { + _ struct{} `type:"structure"` + + // The ID of the resource. + ResourceId *string `locationName:"resourceId" type:"string"` + + // The owner of the resource. + ResourceOwner *string `locationName:"resourceOwner" type:"string"` +} + +// String returns the string representation +func (s PrefixListAssociation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PrefixListAssociation) GoString() string { + return s.String() +} + +// SetResourceId sets the ResourceId field's value. +func (s *PrefixListAssociation) SetResourceId(v string) *PrefixListAssociation { + s.ResourceId = &v + return s +} + +// SetResourceOwner sets the ResourceOwner field's value. +func (s *PrefixListAssociation) SetResourceOwner(v string) *PrefixListAssociation { + s.ResourceOwner = &v + return s +} + +// Describes a prefix list entry. +type PrefixListEntry struct { + _ struct{} `type:"structure"` + + // The CIDR block. + Cidr *string `locationName:"cidr" type:"string"` + + // The description. + Description *string `locationName:"description" type:"string"` +} + +// String returns the string representation +func (s PrefixListEntry) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PrefixListEntry) GoString() string { + return s.String() +} + +// SetCidr sets the Cidr field's value. +func (s *PrefixListEntry) SetCidr(v string) *PrefixListEntry { + s.Cidr = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *PrefixListEntry) SetDescription(v string) *PrefixListEntry { + s.Description = &v + return s +} + // Describes a prefix list ID. type PrefixListId struct { _ struct{} `type:"structure"` @@ -92293,6 +95614,9 @@ type ProvisionByoipCidrInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` + // The tags to apply to the address pool. + PoolTagSpecifications []*TagSpecification `locationName:"PoolTagSpecification" locationNameList:"item" type:"list"` + // (IPv6 only) Indicate whether the address range will be publicly advertised // to the internet. // @@ -92352,6 +95676,12 @@ func (s *ProvisionByoipCidrInput) SetDryRun(v bool) *ProvisionByoipCidrInput { return s } +// SetPoolTagSpecifications sets the PoolTagSpecifications field's value. +func (s *ProvisionByoipCidrInput) SetPoolTagSpecifications(v []*TagSpecification) *ProvisionByoipCidrInput { + s.PoolTagSpecifications = v + return s +} + // SetPubliclyAdvertisable sets the PubliclyAdvertisable field's value. func (s *ProvisionByoipCidrInput) SetPubliclyAdvertisable(v bool) *ProvisionByoipCidrInput { s.PubliclyAdvertisable = &v @@ -92460,6 +95790,11 @@ type PublicIpv4Pool struct { // A description of the address pool. Description *string `locationName:"description" type:"string"` + // The name of the location from which the address pool is advertised. A network + // border group is a unique set of Availability Zones or Local Zones from where + // AWS advertises public IP addresses. + NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` + // The address ranges. PoolAddressRanges []*PublicIpv4PoolRange `locationName:"poolAddressRangeSet" locationNameList:"item" type:"list"` @@ -92492,6 +95827,12 @@ func (s *PublicIpv4Pool) SetDescription(v string) *PublicIpv4Pool { return s } +// SetNetworkBorderGroup sets the NetworkBorderGroup field's value. +func (s *PublicIpv4Pool) SetNetworkBorderGroup(v string) *PublicIpv4Pool { + s.NetworkBorderGroup = &v + return s +} + // SetPoolAddressRanges sets the PoolAddressRanges field's value. func (s *PublicIpv4Pool) SetPoolAddressRanges(v []*PublicIpv4PoolRange) *PublicIpv4Pool { s.PoolAddressRanges = v @@ -92690,6 +96031,9 @@ type PurchaseHostReservationInput struct { // // OfferingId is a required field OfferingId *string `type:"string" required:"true"` + + // The tags to apply to the Dedicated Host Reservation during purchase. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -92748,6 +96092,12 @@ func (s *PurchaseHostReservationInput) SetOfferingId(v string) *PurchaseHostRese return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *PurchaseHostReservationInput) SetTagSpecifications(v []*TagSpecification) *PurchaseHostReservationInput { + s.TagSpecifications = v + return s +} + type PurchaseHostReservationOutput struct { _ struct{} `type:"structure"` @@ -93976,7 +97326,8 @@ type ReleaseAddressInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // The location that the IP address is released from. + // The set of Availability Zones, Local Zones, or Wavelength Zones from which + // AWS advertises IP addresses. // // If you provide an incorrect network border group, you will receive an InvalidAddress.NotFound // error. For more information, see Error Codes (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html). @@ -94109,6 +97460,45 @@ func (s *ReleaseHostsOutput) SetUnsuccessful(v []*UnsuccessfulItem) *ReleaseHost return s } +// An entry for a prefix list. +type RemovePrefixListEntry struct { + _ struct{} `type:"structure"` + + // The CIDR block. + // + // Cidr is a required field + Cidr *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s RemovePrefixListEntry) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RemovePrefixListEntry) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RemovePrefixListEntry) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RemovePrefixListEntry"} + if s.Cidr == nil { + invalidParams.Add(request.NewErrParamRequired("Cidr")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCidr sets the Cidr field's value. +func (s *RemovePrefixListEntry) SetCidr(v string) *RemovePrefixListEntry { + s.Cidr = &v + return s +} + type ReplaceIamInstanceProfileAssociationInput struct { _ struct{} `type:"structure"` @@ -94441,6 +97831,9 @@ func (s ReplaceNetworkAclEntryOutput) GoString() string { type ReplaceRouteInput struct { _ struct{} `type:"structure"` + // [IPv4 traffic only] The ID of a carrier gateway. + CarrierGatewayId *string `type:"string"` + // The IPv4 CIDR address block used for the destination match. The value that // you provide must match the CIDR of an existing route in the table. DestinationCidrBlock *string `locationName:"destinationCidrBlock" type:"string"` @@ -94449,6 +97842,9 @@ type ReplaceRouteInput struct { // you provide must match the CIDR of an existing route in the table. DestinationIpv6CidrBlock *string `locationName:"destinationIpv6CidrBlock" type:"string"` + // The ID of the prefix list for the route. + DestinationPrefixListId *string `type:"string"` + // Checks whether you have the required permissions for the action, without // actually making the request, and provides an error response. If you have // the required permissions, the error response is DryRunOperation. Otherwise, @@ -94511,6 +97907,12 @@ func (s *ReplaceRouteInput) Validate() error { return nil } +// SetCarrierGatewayId sets the CarrierGatewayId field's value. +func (s *ReplaceRouteInput) SetCarrierGatewayId(v string) *ReplaceRouteInput { + s.CarrierGatewayId = &v + return s +} + // SetDestinationCidrBlock sets the DestinationCidrBlock field's value. func (s *ReplaceRouteInput) SetDestinationCidrBlock(v string) *ReplaceRouteInput { s.DestinationCidrBlock = &v @@ -94523,6 +97925,12 @@ func (s *ReplaceRouteInput) SetDestinationIpv6CidrBlock(v string) *ReplaceRouteI return s } +// SetDestinationPrefixListId sets the DestinationPrefixListId field's value. +func (s *ReplaceRouteInput) SetDestinationPrefixListId(v string) *ReplaceRouteInput { + s.DestinationPrefixListId = &v + return s +} + // SetDryRun sets the DryRun field's value. func (s *ReplaceRouteInput) SetDryRun(v bool) *ReplaceRouteInput { s.DryRun = &v @@ -94963,8 +98371,8 @@ type RequestLaunchTemplateData struct { // in the Amazon Elastic Compute Cloud User Guide. CpuOptions *LaunchTemplateCpuOptionsRequest `type:"structure"` - // The credit option for CPU usage of the instance. Valid for T2 or T3 instances - // only. + // The credit option for CPU usage of the instance. Valid for T2, T3, or T3a + // instances only. CreditSpecification *CreditSpecificationRequest `type:"structure"` // If you set this parameter to true, you can't terminate the instance using @@ -95426,6 +98834,12 @@ type RequestSpotInstancesInput struct { // The default is the On-Demand price. SpotPrice *string `locationName:"spotPrice" type:"string"` + // The key-value pair for tagging the Spot Instance request on creation. The + // value for ResourceType must be spot-instances-request, otherwise the Spot + // Instance request fails. To tag the Spot Instance request after it has been + // created, see CreateTags (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html). + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The Spot Instance request type. // // Default: one-time @@ -95529,6 +98943,12 @@ func (s *RequestSpotInstancesInput) SetSpotPrice(v string) *RequestSpotInstances return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *RequestSpotInstancesInput) SetTagSpecifications(v []*TagSpecification) *RequestSpotInstancesInput { + s.TagSpecifications = v + return s +} + // SetType sets the Type field's value. func (s *RequestSpotInstancesInput) SetType(v string) *RequestSpotInstancesInput { s.Type = &v @@ -97416,6 +100836,107 @@ func (s *RestoreAddressToClassicOutput) SetStatus(v string) *RestoreAddressToCla return s } +type RestoreManagedPrefixListVersionInput struct { + _ struct{} `type:"structure"` + + // The current version number for the prefix list. + // + // CurrentVersion is a required field + CurrentVersion *int64 `type:"long" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` + + // The version to restore. + // + // PreviousVersion is a required field + PreviousVersion *int64 `type:"long" required:"true"` +} + +// String returns the string representation +func (s RestoreManagedPrefixListVersionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RestoreManagedPrefixListVersionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RestoreManagedPrefixListVersionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RestoreManagedPrefixListVersionInput"} + if s.CurrentVersion == nil { + invalidParams.Add(request.NewErrParamRequired("CurrentVersion")) + } + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + if s.PreviousVersion == nil { + invalidParams.Add(request.NewErrParamRequired("PreviousVersion")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCurrentVersion sets the CurrentVersion field's value. +func (s *RestoreManagedPrefixListVersionInput) SetCurrentVersion(v int64) *RestoreManagedPrefixListVersionInput { + s.CurrentVersion = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *RestoreManagedPrefixListVersionInput) SetDryRun(v bool) *RestoreManagedPrefixListVersionInput { + s.DryRun = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *RestoreManagedPrefixListVersionInput) SetPrefixListId(v string) *RestoreManagedPrefixListVersionInput { + s.PrefixListId = &v + return s +} + +// SetPreviousVersion sets the PreviousVersion field's value. +func (s *RestoreManagedPrefixListVersionInput) SetPreviousVersion(v int64) *RestoreManagedPrefixListVersionInput { + s.PreviousVersion = &v + return s +} + +type RestoreManagedPrefixListVersionOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list. + PrefixList *ManagedPrefixList `locationName:"prefixList" type:"structure"` +} + +// String returns the string representation +func (s RestoreManagedPrefixListVersionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RestoreManagedPrefixListVersionOutput) GoString() string { + return s.String() +} + +// SetPrefixList sets the PrefixList field's value. +func (s *RestoreManagedPrefixListVersionOutput) SetPrefixList(v *ManagedPrefixList) *RestoreManagedPrefixListVersionOutput { + s.PrefixList = v + return s +} + type RevokeClientVpnIngressInput struct { _ struct{} `type:"structure"` @@ -97796,6 +101317,9 @@ func (s RevokeSecurityGroupIngressOutput) GoString() string { type Route struct { _ struct{} `type:"structure"` + // The ID of the carrier gateway. + CarrierGatewayId *string `locationName:"carrierGatewayId" type:"string"` + // The IPv4 CIDR block used for the destination match. DestinationCidrBlock *string `locationName:"destinationCidrBlock" type:"string"` @@ -97858,6 +101382,12 @@ func (s Route) GoString() string { return s.String() } +// SetCarrierGatewayId sets the CarrierGatewayId field's value. +func (s *Route) SetCarrierGatewayId(v string) *Route { + s.CarrierGatewayId = &v + return s +} + // SetDestinationCidrBlock sets the DestinationCidrBlock field's value. func (s *Route) SetDestinationCidrBlock(v string) *Route { s.DestinationCidrBlock = &v @@ -98145,17 +101675,17 @@ type RunInstancesInput struct { // For more information, see Ensuring Idempotency (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). // // Constraints: Maximum 64 ASCII characters - ClientToken *string `locationName:"clientToken" type:"string"` + ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` // The CPU options for the instance. For more information, see Optimizing CPU - // Options (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) + // options (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) // in the Amazon Elastic Compute Cloud User Guide. CpuOptions *CpuOptionsRequest `type:"structure"` // The credit option for CPU usage of the burstable performance instance. Valid // values are standard and unlimited. To change this attribute after launch, // use ModifyInstanceCreditSpecification (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceCreditSpecification.html). - // For more information, see Burstable Performance Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) + // For more information, see Burstable performance instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) // in the Amazon Elastic Compute Cloud User Guide. // // Default: standard (T2 instances) or unlimited (T3/T3a instances) @@ -98194,10 +101724,12 @@ type RunInstancesInput struct { // An elastic inference accelerator to associate with the instance. Elastic // inference accelerators are a resource you can attach to your Amazon EC2 instances // to accelerate your Deep Learning (DL) inference workloads. + // + // You cannot specify accelerators from different generations in the same request. ElasticInferenceAccelerators []*ElasticInferenceAccelerator `locationName:"ElasticInferenceAccelerator" locationNameList:"item" type:"list"` // Indicates whether an instance is enabled for hibernation. For more information, - // see Hibernate Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) + // see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon Elastic Compute Cloud User Guide. HibernationOptions *HibernationOptionsRequest `type:"structure"` @@ -98220,7 +101752,7 @@ type RunInstancesInput struct { // InstanceInterruptionBehavior is set to either hibernate or stop. InstanceMarketOptions *InstanceMarketOptionsRequest `type:"structure"` - // The instance type. For more information, see Instance Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) + // The instance type. For more information, see Instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) // in the Amazon Elastic Compute Cloud User Guide. // // Default: m1.small @@ -98280,7 +101812,7 @@ type RunInstancesInput struct { MaxCount *int64 `type:"integer" required:"true"` // The metadata options for the instance. For more information, see Instance - // Metadata and User Data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html). + // metadata and user data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html). MetadataOptions *InstanceMetadataOptionsRequest `type:"structure"` // The minimum number of instances to launch. If you specify a minimum that @@ -98357,7 +101889,7 @@ type RunInstancesInput struct { TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` // The user data to make available to the instance. For more information, see - // Running Commands on Your Linux Instance at Launch (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) + // Running commands on your Linux instance at launch (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) // (Linux) and Adding User Data (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) // (Windows). If you are using a command line tool, base64-encoding is performed // for you, and you can load the text from a file. Otherwise, you must provide @@ -100863,9 +104395,10 @@ type Snapshot struct { // key for the parent volume. KmsKeyId *string `locationName:"kmsKeyId" type:"string"` - // Value from an Amazon-maintained list (amazon | self | all | aws-marketplace - // | microsoft) of snapshot owners. Not to be confused with the user-configured - // AWS account alias, which is set from the IAM console. + // The AWS owner alias, as maintained by Amazon. The possible values are: amazon + // | self | all | aws-marketplace | microsoft. This AWS owner alias is not to + // be confused with the user-configured AWS account alias, which is set from + // the IAM console. OwnerAlias *string `locationName:"ownerAlias" type:"string"` // The AWS account ID of the EBS snapshot owner. @@ -101028,7 +104561,7 @@ type SnapshotDetail struct { // The URL used to access the disk image. Url *string `locationName:"url" type:"string"` - // The S3 bucket for the disk image. + // The Amazon S3 bucket for the disk image. UserBucket *UserBucketDetails `locationName:"userBucket" type:"structure"` } @@ -101118,7 +104651,7 @@ type SnapshotDiskContainer struct { // a https URL (https://..) or an Amazon S3 URL (s3://..). Url *string `type:"string"` - // The S3 bucket for the disk image. + // The Amazon S3 bucket for the disk image. UserBucket *UserBucket `type:"structure"` } @@ -101298,7 +104831,7 @@ type SnapshotTaskDetail struct { // The URL of the disk image from which the snapshot is created. Url *string `locationName:"url" type:"string"` - // The S3 bucket for the disk image. + // The Amazon S3 bucket for the disk image. UserBucket *UserBucketDetails `locationName:"userBucket" type:"structure"` } @@ -101778,7 +105311,7 @@ type SpotFleetRequestConfigData struct { // The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) // role that grants the Spot Fleet the permission to request, launch, terminate, - // and tag instances on your behalf. For more information, see Spot Fleet Prerequisites + // and tag instances on your behalf. For more information, see Spot Fleet prerequisites // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html#spot-fleet-prerequisites) // in the Amazon EC2 User Guide for Linux Instances. Spot Fleet can terminate // Spot Instances on your behalf when you cancel its Spot Fleet request using @@ -102170,7 +105703,7 @@ type SpotInstanceRequest struct { SpotPrice *string `locationName:"spotPrice" type:"string"` // The state of the Spot Instance request. Spot status information helps track - // your Spot Instance requests. For more information, see Spot Status (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) + // your Spot Instance requests. For more information, see Spot status (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) // in the Amazon EC2 User Guide for Linux Instances. State *string `locationName:"state" type:"string" enum:"SpotInstanceState"` @@ -102356,7 +105889,7 @@ func (s *SpotInstanceStateFault) SetMessage(v string) *SpotInstanceStateFault { type SpotInstanceStatus struct { _ struct{} `type:"structure"` - // The status code. For a list of status codes, see Spot Status Codes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html#spot-instance-bid-status-understand) + // The status code. For a list of status codes, see Spot status codes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html#spot-instance-bid-status-understand) // in the Amazon EC2 User Guide for Linux Instances. Code *string `locationName:"code" type:"string"` @@ -102780,8 +106313,7 @@ type StaleIpPermission struct { // The IP ranges. Not applicable for stale security group rules. IpRanges []*string `locationName:"ipRanges" locationNameList:"item" type:"list"` - // The prefix list IDs for an AWS service. Not applicable for stale security - // group rules. + // The prefix list IDs. Not applicable for stale security group rules. PrefixListIds []*string `locationName:"prefixListIds" locationNameList:"item" type:"list"` // The end of the port range for the TCP and UDP protocols, or an ICMP type @@ -103153,7 +106685,7 @@ type StopInstancesInput struct { // Hibernates the instance if the instance was enabled for hibernation at launch. // If the instance cannot hibernate successfully, a normal shutdown occurs. - // For more information, see Hibernate Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) + // For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon Elastic Compute Cloud User Guide. // // Default: false @@ -103717,12 +107249,17 @@ type TagSpecification struct { _ struct{} `type:"structure"` // The type of resource to tag. Currently, the resource types that support tagging - // on creation are: capacity-reservation | client-vpn-endpoint | dedicated-host - // | fleet | fpga-image | instance | key-pair | launch-template | | natgateway - // | spot-fleet-request | placement-group | snapshot | traffic-mirror-filter - // | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment - // | transit-gateway-route-table | vpc-endpoint (for interface VPC endpoints)| - // vpc-endpoint-service (for gateway VPC endpoints) | volume | vpc-flow-log. + // on creation are: capacity-reservation | client-vpn-endpoint | customer-gateway + // | dedicated-host | dhcp-options | export-image-task | export-instance-task + // | fleet | fpga-image | host-reservation | import-image-task | import-snapshot-task + // | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | + // launch-template | placement-group | prefix-list | natgateway | network-acl + // | route-table | security-group | spot-fleet-request | spot-instances-request + // | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target + // | transit-gateway | transit-gateway-attachment | transit-gateway-route-table + // | volume |vpc | vpc-peering-connection | vpc-endpoint (for interface and + // gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log + // | vpn-connection | vpn-gateway. // // To tag a resource after it has been created, see CreateTags (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html). ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` @@ -105833,28 +109370,28 @@ type TransitGatewayRequestOptions struct { // A private Autonomous System Number (ASN) for the Amazon side of a BGP session. // The range is 64512 to 65534 for 16-bit ASNs and 4200000000 to 4294967294 - // for 32-bit ASNs. + // for 32-bit ASNs. The default is 64512. AmazonSideAsn *int64 `type:"long"` - // Enable or disable automatic acceptance of attachment requests. The default - // is disable. + // Enable or disable automatic acceptance of attachment requests. Disabled by + // default. AutoAcceptSharedAttachments *string `type:"string" enum:"AutoAcceptSharedAttachmentsValue"` // Enable or disable automatic association with the default association route - // table. The default is enable. + // table. Enabled by default. DefaultRouteTableAssociation *string `type:"string" enum:"DefaultRouteTableAssociationValue"` // Enable or disable automatic propagation of routes to the default propagation - // route table. The default is enable. + // route table. Enabled by default. DefaultRouteTablePropagation *string `type:"string" enum:"DefaultRouteTablePropagationValue"` - // Enable or disable DNS support. + // Enable or disable DNS support. Enabled by default. DnsSupport *string `type:"string" enum:"DnsSupportValue"` // Indicates whether multicast is enabled on the transit gateway MulticastSupport *string `type:"string" enum:"MulticastSupportValue"` - // Enable or disable Equal Cost Multipath Protocol support. + // Enable or disable Equal Cost Multipath Protocol support. Enabled by default. VpnEcmpSupport *string `type:"string" enum:"VpnEcmpSupportValue"` } @@ -106368,8 +109905,11 @@ type TunnelOption struct { // The number of packets in an IKE replay window. ReplayWindowSize *int64 `locationName:"replayWindowSize" type:"integer"` - // The range of inside IP addresses for the tunnel. + // The range of inside IPv4 addresses for the tunnel. TunnelInsideCidr *string `locationName:"tunnelInsideCidr" type:"string"` + + // The range of inside IPv6 addresses for the tunnel. + TunnelInsideIpv6Cidr *string `locationName:"tunnelInsideIpv6Cidr" type:"string"` } // String returns the string representation @@ -106478,6 +110018,12 @@ func (s *TunnelOption) SetTunnelInsideCidr(v string) *TunnelOption { return s } +// SetTunnelInsideIpv6Cidr sets the TunnelInsideIpv6Cidr field's value. +func (s *TunnelOption) SetTunnelInsideIpv6Cidr(v string) *TunnelOption { + s.TunnelInsideIpv6Cidr = &v + return s +} + type UnassignIpv6AddressesInput struct { _ struct{} `type:"structure"` @@ -107027,11 +110573,11 @@ func (s *UpdateSecurityGroupRuleDescriptionsIngressOutput) SetReturn(v bool) *Up return s } -// Describes the S3 bucket for the disk image. +// Describes the Amazon S3 bucket for the disk image. type UserBucket struct { _ struct{} `type:"structure"` - // The name of the S3 bucket where the disk image is located. + // The name of the Amazon S3 bucket where the disk image is located. S3Bucket *string `type:"string"` // The file name of the disk image. @@ -107060,11 +110606,11 @@ func (s *UserBucket) SetS3Key(v string) *UserBucket { return s } -// Describes the S3 bucket for the disk image. +// Describes the Amazon S3 bucket for the disk image. type UserBucketDetails struct { _ struct{} `type:"structure"` - // The S3 bucket from which the disk image was created. + // The Amazon S3 bucket from which the disk image was created. S3Bucket *string `locationName:"s3Bucket" type:"string"` // The file name of the disk image. @@ -107275,6 +110821,70 @@ func (s *VCpuInfo) SetValidThreadsPerCore(v []*int64) *VCpuInfo { return s } +// The error code and error message that is returned for a parameter or parameter +// combination that is not valid when a new launch template or new version of +// a launch template is created. +type ValidationError struct { + _ struct{} `type:"structure"` + + // The error code that indicates why the parameter or parameter combination + // is not valid. For more information about error codes, see Error Codes (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html). + Code *string `locationName:"code" type:"string"` + + // The error message that describes why the parameter or parameter combination + // is not valid. For more information about error messages, see Error Codes + // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html). + Message *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ValidationError) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationError) GoString() string { + return s.String() +} + +// SetCode sets the Code field's value. +func (s *ValidationError) SetCode(v string) *ValidationError { + s.Code = &v + return s +} + +// SetMessage sets the Message field's value. +func (s *ValidationError) SetMessage(v string) *ValidationError { + s.Message = &v + return s +} + +// The error codes and error messages that are returned for the parameters or +// parameter combinations that are not valid when a new launch template or new +// version of a launch template is created. +type ValidationWarning struct { + _ struct{} `type:"structure"` + + // The error codes and error messages. + Errors []*ValidationError `locationName:"errorSet" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s ValidationWarning) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationWarning) GoString() string { + return s.String() +} + +// SetErrors sets the Errors field's value. +func (s *ValidationWarning) SetErrors(v []*ValidationError) *ValidationWarning { + s.Errors = v + return s +} + // Describes telemetry for a VPN tunnel. type VgwTelemetry struct { _ struct{} `type:"structure"` @@ -107637,7 +111247,7 @@ type VolumeModification struct { // The original IOPS rate of the volume. OriginalIops *int64 `locationName:"originalIops" type:"integer"` - // The original size of the volume. + // The original size of the volume, in GiB. OriginalSize *int64 `locationName:"originalSize" type:"integer"` // The original EBS volume type of the volume. @@ -108054,8 +111664,7 @@ type Vpc struct { // Information about the IPv4 CIDR blocks associated with the VPC. CidrBlockAssociationSet []*VpcCidrBlockAssociation `locationName:"cidrBlockAssociationSet" locationNameList:"item" type:"list"` - // The ID of the set of DHCP options you've associated with the VPC (or default - // if the default options are associated with the VPC). + // The ID of the set of DHCP options you've associated with the VPC. DhcpOptionsId *string `locationName:"dhcpOptionsId" type:"string"` // The allowed tenancy of instances launched into the VPC. @@ -108564,7 +112173,8 @@ type VpcIpv6CidrBlockAssociation struct { // The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. Ipv6Pool *string `locationName:"ipv6Pool" type:"string"` - // The name of the location from which we advertise the IPV6 CIDR block. + // The name of the unique set of Availability Zones, Local Zones, or Wavelength + // Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1. NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` } @@ -108974,6 +112584,9 @@ type VpnConnectionOptions struct { // must be used for devices that don't support BGP. StaticRoutesOnly *bool `locationName:"staticRoutesOnly" type:"boolean"` + // Indicates whether the VPN tunnels process IPv4 or IPv6 traffic. + TunnelInsideIpVersion *string `locationName:"tunnelInsideIpVersion" type:"string" enum:"TunnelInsideIpVersion"` + // Indicates the VPN tunnel options. TunnelOptions []*TunnelOption `locationName:"tunnelOptionSet" locationNameList:"item" type:"list"` } @@ -109000,6 +112613,12 @@ func (s *VpnConnectionOptions) SetStaticRoutesOnly(v bool) *VpnConnectionOptions return s } +// SetTunnelInsideIpVersion sets the TunnelInsideIpVersion field's value. +func (s *VpnConnectionOptions) SetTunnelInsideIpVersion(v string) *VpnConnectionOptions { + s.TunnelInsideIpVersion = &v + return s +} + // SetTunnelOptions sets the TunnelOptions field's value. func (s *VpnConnectionOptions) SetTunnelOptions(v []*TunnelOption) *VpnConnectionOptions { s.TunnelOptions = v @@ -109022,6 +112641,11 @@ type VpnConnectionOptionsSpecification struct { // Default: false StaticRoutesOnly *bool `locationName:"staticRoutesOnly" type:"boolean"` + // Indicate whether the VPN tunnels process IPv4 or IPv6 traffic. + // + // Default: ipv4 + TunnelInsideIpVersion *string `type:"string" enum:"TunnelInsideIpVersion"` + // The tunnel options for the VPN connection. TunnelOptions []*VpnTunnelOptionsSpecification `type:"list"` } @@ -109048,6 +112672,12 @@ func (s *VpnConnectionOptionsSpecification) SetStaticRoutesOnly(v bool) *VpnConn return s } +// SetTunnelInsideIpVersion sets the TunnelInsideIpVersion field's value. +func (s *VpnConnectionOptionsSpecification) SetTunnelInsideIpVersion(v string) *VpnConnectionOptionsSpecification { + s.TunnelInsideIpVersion = &v + return s +} + // SetTunnelOptions sets the TunnelOptions field's value. func (s *VpnConnectionOptionsSpecification) SetTunnelOptions(v []*VpnTunnelOptionsSpecification) *VpnConnectionOptionsSpecification { s.TunnelOptions = v @@ -109194,19 +112824,19 @@ type VpnTunnelOptionsSpecification struct { // One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel // for phase 1 IKE negotiations. // - // Valid values: 2 | 14 | 15 | 16 | 17 | 18 | 22 | 23 | 24 + // Valid values: 2 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 Phase1DHGroupNumbers []*Phase1DHGroupNumbersRequestListValue `locationName:"Phase1DHGroupNumber" locationNameList:"item" type:"list"` // One or more encryption algorithms that are permitted for the VPN tunnel for // phase 1 IKE negotiations. // - // Valid values: AES128 | AES256 + // Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 Phase1EncryptionAlgorithms []*Phase1EncryptionAlgorithmsRequestListValue `locationName:"Phase1EncryptionAlgorithm" locationNameList:"item" type:"list"` // One or more integrity algorithms that are permitted for the VPN tunnel for // phase 1 IKE negotiations. // - // Valid values: SHA1 | SHA2-256 + // Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 Phase1IntegrityAlgorithms []*Phase1IntegrityAlgorithmsRequestListValue `locationName:"Phase1IntegrityAlgorithm" locationNameList:"item" type:"list"` // The lifetime for phase 1 of the IKE negotiation, in seconds. @@ -109219,19 +112849,19 @@ type VpnTunnelOptionsSpecification struct { // One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel // for phase 2 IKE negotiations. // - // Valid values: 2 | 5 | 14 | 15 | 16 | 17 | 18 | 22 | 23 | 24 + // Valid values: 2 | 5 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 Phase2DHGroupNumbers []*Phase2DHGroupNumbersRequestListValue `locationName:"Phase2DHGroupNumber" locationNameList:"item" type:"list"` // One or more encryption algorithms that are permitted for the VPN tunnel for // phase 2 IKE negotiations. // - // Valid values: AES128 | AES256 + // Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 Phase2EncryptionAlgorithms []*Phase2EncryptionAlgorithmsRequestListValue `locationName:"Phase2EncryptionAlgorithm" locationNameList:"item" type:"list"` // One or more integrity algorithms that are permitted for the VPN tunnel for // phase 2 IKE negotiations. // - // Valid values: SHA1 | SHA2-256 + // Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 Phase2IntegrityAlgorithms []*Phase2IntegrityAlgorithmsRequestListValue `locationName:"Phase2IntegrityAlgorithm" locationNameList:"item" type:"list"` // The lifetime for phase 2 of the IKE negotiation, in seconds. @@ -109274,7 +112904,7 @@ type VpnTunnelOptionsSpecification struct { // Default: 1024 ReplayWindowSize *int64 `type:"integer"` - // The range of inside IP addresses for the tunnel. Any specified CIDR blocks + // The range of inside IPv4 addresses for the tunnel. Any specified CIDR blocks // must be unique across all VPN connections that use the same virtual private // gateway. // @@ -109295,6 +112925,12 @@ type VpnTunnelOptionsSpecification struct { // // * 169.254.169.252/30 TunnelInsideCidr *string `type:"string"` + + // The range of inside IPv6 addresses for the tunnel. Any specified CIDR blocks + // must be unique across all VPN connections that use the same transit gateway. + // + // Constraints: A size /126 CIDR block from the local fd00::/8 range. + TunnelInsideIpv6Cidr *string `type:"string"` } // String returns the string representation @@ -109397,6 +113033,12 @@ func (s *VpnTunnelOptionsSpecification) SetTunnelInsideCidr(v string) *VpnTunnel return s } +// SetTunnelInsideIpv6Cidr sets the TunnelInsideIpv6Cidr field's value. +func (s *VpnTunnelOptionsSpecification) SetTunnelInsideIpv6Cidr(v string) *VpnTunnelOptionsSpecification { + s.TunnelInsideIpv6Cidr = &v + return s +} + type WithdrawByoipCidrInput struct { _ struct{} `type:"structure"` @@ -109478,6 +113120,14 @@ const ( AccountAttributeNameDefaultVpc = "default-vpc" ) +// AccountAttributeName_Values returns all elements of the AccountAttributeName enum +func AccountAttributeName_Values() []string { + return []string{ + AccountAttributeNameSupportedPlatforms, + AccountAttributeNameDefaultVpc, + } +} + const ( // ActivityStatusError is a ActivityStatus enum value ActivityStatusError = "error" @@ -109492,6 +113142,16 @@ const ( ActivityStatusFulfilled = "fulfilled" ) +// ActivityStatus_Values returns all elements of the ActivityStatus enum +func ActivityStatus_Values() []string { + return []string{ + ActivityStatusError, + ActivityStatusPendingFulfillment, + ActivityStatusPendingTermination, + ActivityStatusFulfilled, + } +} + const ( // AffinityDefault is a Affinity enum value AffinityDefault = "default" @@ -109500,6 +113160,14 @@ const ( AffinityHost = "host" ) +// Affinity_Values returns all elements of the Affinity enum +func Affinity_Values() []string { + return []string{ + AffinityDefault, + AffinityHost, + } +} + const ( // AllocationStateAvailable is a AllocationState enum value AllocationStateAvailable = "available" @@ -109520,6 +113188,18 @@ const ( AllocationStatePending = "pending" ) +// AllocationState_Values returns all elements of the AllocationState enum +func AllocationState_Values() []string { + return []string{ + AllocationStateAvailable, + AllocationStateUnderAssessment, + AllocationStatePermanentFailure, + AllocationStateReleased, + AllocationStateReleasedPermanentFailure, + AllocationStatePending, + } +} + const ( // AllocationStrategyLowestPrice is a AllocationStrategy enum value AllocationStrategyLowestPrice = "lowestPrice" @@ -109531,6 +113211,15 @@ const ( AllocationStrategyCapacityOptimized = "capacityOptimized" ) +// AllocationStrategy_Values returns all elements of the AllocationStrategy enum +func AllocationStrategy_Values() []string { + return []string{ + AllocationStrategyLowestPrice, + AllocationStrategyDiversified, + AllocationStrategyCapacityOptimized, + } +} + const ( // AllowsMultipleInstanceTypesOn is a AllowsMultipleInstanceTypes enum value AllowsMultipleInstanceTypesOn = "on" @@ -109539,6 +113228,14 @@ const ( AllowsMultipleInstanceTypesOff = "off" ) +// AllowsMultipleInstanceTypes_Values returns all elements of the AllowsMultipleInstanceTypes enum +func AllowsMultipleInstanceTypes_Values() []string { + return []string{ + AllowsMultipleInstanceTypesOn, + AllowsMultipleInstanceTypesOff, + } +} + const ( // ArchitectureTypeI386 is a ArchitectureType enum value ArchitectureTypeI386 = "i386" @@ -109550,6 +113247,15 @@ const ( ArchitectureTypeArm64 = "arm64" ) +// ArchitectureType_Values returns all elements of the ArchitectureType enum +func ArchitectureType_Values() []string { + return []string{ + ArchitectureTypeI386, + ArchitectureTypeX8664, + ArchitectureTypeArm64, + } +} + const ( // ArchitectureValuesI386 is a ArchitectureValues enum value ArchitectureValuesI386 = "i386" @@ -109561,11 +113267,27 @@ const ( ArchitectureValuesArm64 = "arm64" ) +// ArchitectureValues_Values returns all elements of the ArchitectureValues enum +func ArchitectureValues_Values() []string { + return []string{ + ArchitectureValuesI386, + ArchitectureValuesX8664, + ArchitectureValuesArm64, + } +} + const ( // AssociatedNetworkTypeVpc is a AssociatedNetworkType enum value AssociatedNetworkTypeVpc = "vpc" ) +// AssociatedNetworkType_Values returns all elements of the AssociatedNetworkType enum +func AssociatedNetworkType_Values() []string { + return []string{ + AssociatedNetworkTypeVpc, + } +} + const ( // AssociationStatusCodeAssociating is a AssociationStatusCode enum value AssociationStatusCodeAssociating = "associating" @@ -109583,6 +113305,17 @@ const ( AssociationStatusCodeDisassociated = "disassociated" ) +// AssociationStatusCode_Values returns all elements of the AssociationStatusCode enum +func AssociationStatusCode_Values() []string { + return []string{ + AssociationStatusCodeAssociating, + AssociationStatusCodeAssociated, + AssociationStatusCodeAssociationFailed, + AssociationStatusCodeDisassociating, + AssociationStatusCodeDisassociated, + } +} + const ( // AttachmentStatusAttaching is a AttachmentStatus enum value AttachmentStatusAttaching = "attaching" @@ -109597,6 +113330,16 @@ const ( AttachmentStatusDetached = "detached" ) +// AttachmentStatus_Values returns all elements of the AttachmentStatus enum +func AttachmentStatus_Values() []string { + return []string{ + AttachmentStatusAttaching, + AttachmentStatusAttached, + AttachmentStatusDetaching, + AttachmentStatusDetached, + } +} + const ( // AutoAcceptSharedAttachmentsValueEnable is a AutoAcceptSharedAttachmentsValue enum value AutoAcceptSharedAttachmentsValueEnable = "enable" @@ -109605,6 +113348,14 @@ const ( AutoAcceptSharedAttachmentsValueDisable = "disable" ) +// AutoAcceptSharedAttachmentsValue_Values returns all elements of the AutoAcceptSharedAttachmentsValue enum +func AutoAcceptSharedAttachmentsValue_Values() []string { + return []string{ + AutoAcceptSharedAttachmentsValueEnable, + AutoAcceptSharedAttachmentsValueDisable, + } +} + const ( // AutoPlacementOn is a AutoPlacement enum value AutoPlacementOn = "on" @@ -109613,6 +113364,14 @@ const ( AutoPlacementOff = "off" ) +// AutoPlacement_Values returns all elements of the AutoPlacement enum +func AutoPlacement_Values() []string { + return []string{ + AutoPlacementOn, + AutoPlacementOff, + } +} + const ( // AvailabilityZoneOptInStatusOptInNotRequired is a AvailabilityZoneOptInStatus enum value AvailabilityZoneOptInStatusOptInNotRequired = "opt-in-not-required" @@ -109624,6 +113383,15 @@ const ( AvailabilityZoneOptInStatusNotOptedIn = "not-opted-in" ) +// AvailabilityZoneOptInStatus_Values returns all elements of the AvailabilityZoneOptInStatus enum +func AvailabilityZoneOptInStatus_Values() []string { + return []string{ + AvailabilityZoneOptInStatusOptInNotRequired, + AvailabilityZoneOptInStatusOptedIn, + AvailabilityZoneOptInStatusNotOptedIn, + } +} + const ( // AvailabilityZoneStateAvailable is a AvailabilityZoneState enum value AvailabilityZoneStateAvailable = "available" @@ -109638,6 +113406,16 @@ const ( AvailabilityZoneStateUnavailable = "unavailable" ) +// AvailabilityZoneState_Values returns all elements of the AvailabilityZoneState enum +func AvailabilityZoneState_Values() []string { + return []string{ + AvailabilityZoneStateAvailable, + AvailabilityZoneStateInformation, + AvailabilityZoneStateImpaired, + AvailabilityZoneStateUnavailable, + } +} + const ( // BatchStateSubmitted is a BatchState enum value BatchStateSubmitted = "submitted" @@ -109661,6 +113439,19 @@ const ( BatchStateModifying = "modifying" ) +// BatchState_Values returns all elements of the BatchState enum +func BatchState_Values() []string { + return []string{ + BatchStateSubmitted, + BatchStateActive, + BatchStateCancelled, + BatchStateFailed, + BatchStateCancelledRunning, + BatchStateCancelledTerminating, + BatchStateModifying, + } +} + const ( // BundleTaskStatePending is a BundleTaskState enum value BundleTaskStatePending = "pending" @@ -109684,6 +113475,19 @@ const ( BundleTaskStateFailed = "failed" ) +// BundleTaskState_Values returns all elements of the BundleTaskState enum +func BundleTaskState_Values() []string { + return []string{ + BundleTaskStatePending, + BundleTaskStateWaitingForShutdown, + BundleTaskStateBundling, + BundleTaskStateStoring, + BundleTaskStateCancelling, + BundleTaskStateComplete, + BundleTaskStateFailed, + } +} + const ( // ByoipCidrStateAdvertised is a ByoipCidrState enum value ByoipCidrStateAdvertised = "advertised" @@ -109710,6 +113514,20 @@ const ( ByoipCidrStateProvisionedNotPubliclyAdvertisable = "provisioned-not-publicly-advertisable" ) +// ByoipCidrState_Values returns all elements of the ByoipCidrState enum +func ByoipCidrState_Values() []string { + return []string{ + ByoipCidrStateAdvertised, + ByoipCidrStateDeprovisioned, + ByoipCidrStateFailedDeprovision, + ByoipCidrStateFailedProvision, + ByoipCidrStatePendingDeprovision, + ByoipCidrStatePendingProvision, + ByoipCidrStateProvisioned, + ByoipCidrStateProvisionedNotPubliclyAdvertisable, + } +} + const ( // CancelBatchErrorCodeFleetRequestIdDoesNotExist is a CancelBatchErrorCode enum value CancelBatchErrorCodeFleetRequestIdDoesNotExist = "fleetRequestIdDoesNotExist" @@ -109724,6 +113542,16 @@ const ( CancelBatchErrorCodeUnexpectedError = "unexpectedError" ) +// CancelBatchErrorCode_Values returns all elements of the CancelBatchErrorCode enum +func CancelBatchErrorCode_Values() []string { + return []string{ + CancelBatchErrorCodeFleetRequestIdDoesNotExist, + CancelBatchErrorCodeFleetRequestIdMalformed, + CancelBatchErrorCodeFleetRequestNotInCancellableState, + CancelBatchErrorCodeUnexpectedError, + } +} + const ( // CancelSpotInstanceRequestStateActive is a CancelSpotInstanceRequestState enum value CancelSpotInstanceRequestStateActive = "active" @@ -109741,6 +113569,17 @@ const ( CancelSpotInstanceRequestStateCompleted = "completed" ) +// CancelSpotInstanceRequestState_Values returns all elements of the CancelSpotInstanceRequestState enum +func CancelSpotInstanceRequestState_Values() []string { + return []string{ + CancelSpotInstanceRequestStateActive, + CancelSpotInstanceRequestStateOpen, + CancelSpotInstanceRequestStateClosed, + CancelSpotInstanceRequestStateCancelled, + CancelSpotInstanceRequestStateCompleted, + } +} + const ( // CapacityReservationInstancePlatformLinuxUnix is a CapacityReservationInstancePlatform enum value CapacityReservationInstancePlatformLinuxUnix = "Linux/UNIX" @@ -109776,6 +113615,23 @@ const ( CapacityReservationInstancePlatformLinuxwithSqlserverEnterprise = "Linux with SQL Server Enterprise" ) +// CapacityReservationInstancePlatform_Values returns all elements of the CapacityReservationInstancePlatform enum +func CapacityReservationInstancePlatform_Values() []string { + return []string{ + CapacityReservationInstancePlatformLinuxUnix, + CapacityReservationInstancePlatformRedHatEnterpriseLinux, + CapacityReservationInstancePlatformSuselinux, + CapacityReservationInstancePlatformWindows, + CapacityReservationInstancePlatformWindowswithSqlserver, + CapacityReservationInstancePlatformWindowswithSqlserverEnterprise, + CapacityReservationInstancePlatformWindowswithSqlserverStandard, + CapacityReservationInstancePlatformWindowswithSqlserverWeb, + CapacityReservationInstancePlatformLinuxwithSqlserverStandard, + CapacityReservationInstancePlatformLinuxwithSqlserverWeb, + CapacityReservationInstancePlatformLinuxwithSqlserverEnterprise, + } +} + const ( // CapacityReservationPreferenceOpen is a CapacityReservationPreference enum value CapacityReservationPreferenceOpen = "open" @@ -109784,6 +113640,14 @@ const ( CapacityReservationPreferenceNone = "none" ) +// CapacityReservationPreference_Values returns all elements of the CapacityReservationPreference enum +func CapacityReservationPreference_Values() []string { + return []string{ + CapacityReservationPreferenceOpen, + CapacityReservationPreferenceNone, + } +} + const ( // CapacityReservationStateActive is a CapacityReservationState enum value CapacityReservationStateActive = "active" @@ -109801,6 +113665,17 @@ const ( CapacityReservationStateFailed = "failed" ) +// CapacityReservationState_Values returns all elements of the CapacityReservationState enum +func CapacityReservationState_Values() []string { + return []string{ + CapacityReservationStateActive, + CapacityReservationStateExpired, + CapacityReservationStateCancelled, + CapacityReservationStatePending, + CapacityReservationStateFailed, + } +} + const ( // CapacityReservationTenancyDefault is a CapacityReservationTenancy enum value CapacityReservationTenancyDefault = "default" @@ -109809,6 +113684,38 @@ const ( CapacityReservationTenancyDedicated = "dedicated" ) +// CapacityReservationTenancy_Values returns all elements of the CapacityReservationTenancy enum +func CapacityReservationTenancy_Values() []string { + return []string{ + CapacityReservationTenancyDefault, + CapacityReservationTenancyDedicated, + } +} + +const ( + // CarrierGatewayStatePending is a CarrierGatewayState enum value + CarrierGatewayStatePending = "pending" + + // CarrierGatewayStateAvailable is a CarrierGatewayState enum value + CarrierGatewayStateAvailable = "available" + + // CarrierGatewayStateDeleting is a CarrierGatewayState enum value + CarrierGatewayStateDeleting = "deleting" + + // CarrierGatewayStateDeleted is a CarrierGatewayState enum value + CarrierGatewayStateDeleted = "deleted" +) + +// CarrierGatewayState_Values returns all elements of the CarrierGatewayState enum +func CarrierGatewayState_Values() []string { + return []string{ + CarrierGatewayStatePending, + CarrierGatewayStateAvailable, + CarrierGatewayStateDeleting, + CarrierGatewayStateDeleted, + } +} + const ( // ClientCertificateRevocationListStatusCodePending is a ClientCertificateRevocationListStatusCode enum value ClientCertificateRevocationListStatusCodePending = "pending" @@ -109817,14 +113724,34 @@ const ( ClientCertificateRevocationListStatusCodeActive = "active" ) +// ClientCertificateRevocationListStatusCode_Values returns all elements of the ClientCertificateRevocationListStatusCode enum +func ClientCertificateRevocationListStatusCode_Values() []string { + return []string{ + ClientCertificateRevocationListStatusCodePending, + ClientCertificateRevocationListStatusCodeActive, + } +} + const ( // ClientVpnAuthenticationTypeCertificateAuthentication is a ClientVpnAuthenticationType enum value ClientVpnAuthenticationTypeCertificateAuthentication = "certificate-authentication" // ClientVpnAuthenticationTypeDirectoryServiceAuthentication is a ClientVpnAuthenticationType enum value ClientVpnAuthenticationTypeDirectoryServiceAuthentication = "directory-service-authentication" + + // ClientVpnAuthenticationTypeFederatedAuthentication is a ClientVpnAuthenticationType enum value + ClientVpnAuthenticationTypeFederatedAuthentication = "federated-authentication" ) +// ClientVpnAuthenticationType_Values returns all elements of the ClientVpnAuthenticationType enum +func ClientVpnAuthenticationType_Values() []string { + return []string{ + ClientVpnAuthenticationTypeCertificateAuthentication, + ClientVpnAuthenticationTypeDirectoryServiceAuthentication, + ClientVpnAuthenticationTypeFederatedAuthentication, + } +} + const ( // ClientVpnAuthorizationRuleStatusCodeAuthorizing is a ClientVpnAuthorizationRuleStatusCode enum value ClientVpnAuthorizationRuleStatusCodeAuthorizing = "authorizing" @@ -109839,6 +113766,16 @@ const ( ClientVpnAuthorizationRuleStatusCodeRevoking = "revoking" ) +// ClientVpnAuthorizationRuleStatusCode_Values returns all elements of the ClientVpnAuthorizationRuleStatusCode enum +func ClientVpnAuthorizationRuleStatusCode_Values() []string { + return []string{ + ClientVpnAuthorizationRuleStatusCodeAuthorizing, + ClientVpnAuthorizationRuleStatusCodeActive, + ClientVpnAuthorizationRuleStatusCodeFailed, + ClientVpnAuthorizationRuleStatusCodeRevoking, + } +} + const ( // ClientVpnConnectionStatusCodeActive is a ClientVpnConnectionStatusCode enum value ClientVpnConnectionStatusCodeActive = "active" @@ -109853,6 +113790,16 @@ const ( ClientVpnConnectionStatusCodeTerminated = "terminated" ) +// ClientVpnConnectionStatusCode_Values returns all elements of the ClientVpnConnectionStatusCode enum +func ClientVpnConnectionStatusCode_Values() []string { + return []string{ + ClientVpnConnectionStatusCodeActive, + ClientVpnConnectionStatusCodeFailedToTerminate, + ClientVpnConnectionStatusCodeTerminating, + ClientVpnConnectionStatusCodeTerminated, + } +} + const ( // ClientVpnEndpointStatusCodePendingAssociate is a ClientVpnEndpointStatusCode enum value ClientVpnEndpointStatusCodePendingAssociate = "pending-associate" @@ -109867,6 +113814,16 @@ const ( ClientVpnEndpointStatusCodeDeleted = "deleted" ) +// ClientVpnEndpointStatusCode_Values returns all elements of the ClientVpnEndpointStatusCode enum +func ClientVpnEndpointStatusCode_Values() []string { + return []string{ + ClientVpnEndpointStatusCodePendingAssociate, + ClientVpnEndpointStatusCodeAvailable, + ClientVpnEndpointStatusCodeDeleting, + ClientVpnEndpointStatusCodeDeleted, + } +} + const ( // ClientVpnRouteStatusCodeCreating is a ClientVpnRouteStatusCode enum value ClientVpnRouteStatusCodeCreating = "creating" @@ -109881,6 +113838,16 @@ const ( ClientVpnRouteStatusCodeDeleting = "deleting" ) +// ClientVpnRouteStatusCode_Values returns all elements of the ClientVpnRouteStatusCode enum +func ClientVpnRouteStatusCode_Values() []string { + return []string{ + ClientVpnRouteStatusCodeCreating, + ClientVpnRouteStatusCodeActive, + ClientVpnRouteStatusCodeFailed, + ClientVpnRouteStatusCodeDeleting, + } +} + const ( // ConnectionNotificationStateEnabled is a ConnectionNotificationState enum value ConnectionNotificationStateEnabled = "Enabled" @@ -109889,16 +113856,38 @@ const ( ConnectionNotificationStateDisabled = "Disabled" ) +// ConnectionNotificationState_Values returns all elements of the ConnectionNotificationState enum +func ConnectionNotificationState_Values() []string { + return []string{ + ConnectionNotificationStateEnabled, + ConnectionNotificationStateDisabled, + } +} + const ( // ConnectionNotificationTypeTopic is a ConnectionNotificationType enum value ConnectionNotificationTypeTopic = "Topic" ) +// ConnectionNotificationType_Values returns all elements of the ConnectionNotificationType enum +func ConnectionNotificationType_Values() []string { + return []string{ + ConnectionNotificationTypeTopic, + } +} + const ( // ContainerFormatOva is a ContainerFormat enum value ContainerFormatOva = "ova" ) +// ContainerFormat_Values returns all elements of the ContainerFormat enum +func ContainerFormat_Values() []string { + return []string{ + ContainerFormatOva, + } +} + const ( // ConversionTaskStateActive is a ConversionTaskState enum value ConversionTaskStateActive = "active" @@ -109913,16 +113902,40 @@ const ( ConversionTaskStateCompleted = "completed" ) +// ConversionTaskState_Values returns all elements of the ConversionTaskState enum +func ConversionTaskState_Values() []string { + return []string{ + ConversionTaskStateActive, + ConversionTaskStateCancelling, + ConversionTaskStateCancelled, + ConversionTaskStateCompleted, + } +} + const ( // CopyTagsFromSourceVolume is a CopyTagsFromSource enum value CopyTagsFromSourceVolume = "volume" ) +// CopyTagsFromSource_Values returns all elements of the CopyTagsFromSource enum +func CopyTagsFromSource_Values() []string { + return []string{ + CopyTagsFromSourceVolume, + } +} + const ( // CurrencyCodeValuesUsd is a CurrencyCodeValues enum value CurrencyCodeValuesUsd = "USD" ) +// CurrencyCodeValues_Values returns all elements of the CurrencyCodeValues enum +func CurrencyCodeValues_Values() []string { + return []string{ + CurrencyCodeValuesUsd, + } +} + const ( // DatafeedSubscriptionStateActive is a DatafeedSubscriptionState enum value DatafeedSubscriptionStateActive = "Active" @@ -109931,6 +113944,14 @@ const ( DatafeedSubscriptionStateInactive = "Inactive" ) +// DatafeedSubscriptionState_Values returns all elements of the DatafeedSubscriptionState enum +func DatafeedSubscriptionState_Values() []string { + return []string{ + DatafeedSubscriptionStateActive, + DatafeedSubscriptionStateInactive, + } +} + const ( // DefaultRouteTableAssociationValueEnable is a DefaultRouteTableAssociationValue enum value DefaultRouteTableAssociationValueEnable = "enable" @@ -109939,6 +113960,14 @@ const ( DefaultRouteTableAssociationValueDisable = "disable" ) +// DefaultRouteTableAssociationValue_Values returns all elements of the DefaultRouteTableAssociationValue enum +func DefaultRouteTableAssociationValue_Values() []string { + return []string{ + DefaultRouteTableAssociationValueEnable, + DefaultRouteTableAssociationValueDisable, + } +} + const ( // DefaultRouteTablePropagationValueEnable is a DefaultRouteTablePropagationValue enum value DefaultRouteTablePropagationValueEnable = "enable" @@ -109947,6 +113976,14 @@ const ( DefaultRouteTablePropagationValueDisable = "disable" ) +// DefaultRouteTablePropagationValue_Values returns all elements of the DefaultRouteTablePropagationValue enum +func DefaultRouteTablePropagationValue_Values() []string { + return []string{ + DefaultRouteTablePropagationValueEnable, + DefaultRouteTablePropagationValueDisable, + } +} + const ( // DefaultTargetCapacityTypeSpot is a DefaultTargetCapacityType enum value DefaultTargetCapacityTypeSpot = "spot" @@ -109955,6 +113992,14 @@ const ( DefaultTargetCapacityTypeOnDemand = "on-demand" ) +// DefaultTargetCapacityType_Values returns all elements of the DefaultTargetCapacityType enum +func DefaultTargetCapacityType_Values() []string { + return []string{ + DefaultTargetCapacityTypeSpot, + DefaultTargetCapacityTypeOnDemand, + } +} + const ( // DeleteFleetErrorCodeFleetIdDoesNotExist is a DeleteFleetErrorCode enum value DeleteFleetErrorCodeFleetIdDoesNotExist = "fleetIdDoesNotExist" @@ -109969,6 +114014,16 @@ const ( DeleteFleetErrorCodeUnexpectedError = "unexpectedError" ) +// DeleteFleetErrorCode_Values returns all elements of the DeleteFleetErrorCode enum +func DeleteFleetErrorCode_Values() []string { + return []string{ + DeleteFleetErrorCodeFleetIdDoesNotExist, + DeleteFleetErrorCodeFleetIdMalformed, + DeleteFleetErrorCodeFleetNotInDeletableState, + DeleteFleetErrorCodeUnexpectedError, + } +} + const ( // DeleteQueuedReservedInstancesErrorCodeReservedInstancesIdInvalid is a DeleteQueuedReservedInstancesErrorCode enum value DeleteQueuedReservedInstancesErrorCodeReservedInstancesIdInvalid = "reserved-instances-id-invalid" @@ -109980,6 +114035,15 @@ const ( DeleteQueuedReservedInstancesErrorCodeUnexpectedError = "unexpected-error" ) +// DeleteQueuedReservedInstancesErrorCode_Values returns all elements of the DeleteQueuedReservedInstancesErrorCode enum +func DeleteQueuedReservedInstancesErrorCode_Values() []string { + return []string{ + DeleteQueuedReservedInstancesErrorCodeReservedInstancesIdInvalid, + DeleteQueuedReservedInstancesErrorCodeReservedInstancesNotInQueuedState, + DeleteQueuedReservedInstancesErrorCodeUnexpectedError, + } +} + const ( // DeviceTypeEbs is a DeviceType enum value DeviceTypeEbs = "ebs" @@ -109988,6 +114052,14 @@ const ( DeviceTypeInstanceStore = "instance-store" ) +// DeviceType_Values returns all elements of the DeviceType enum +func DeviceType_Values() []string { + return []string{ + DeviceTypeEbs, + DeviceTypeInstanceStore, + } +} + const ( // DiskImageFormatVmdk is a DiskImageFormat enum value DiskImageFormatVmdk = "VMDK" @@ -109999,6 +114071,15 @@ const ( DiskImageFormatVhd = "VHD" ) +// DiskImageFormat_Values returns all elements of the DiskImageFormat enum +func DiskImageFormat_Values() []string { + return []string{ + DiskImageFormatVmdk, + DiskImageFormatRaw, + DiskImageFormatVhd, + } +} + const ( // DiskTypeHdd is a DiskType enum value DiskTypeHdd = "hdd" @@ -110007,6 +114088,14 @@ const ( DiskTypeSsd = "ssd" ) +// DiskType_Values returns all elements of the DiskType enum +func DiskType_Values() []string { + return []string{ + DiskTypeHdd, + DiskTypeSsd, + } +} + const ( // DnsNameStatePendingVerification is a DnsNameState enum value DnsNameStatePendingVerification = "pendingVerification" @@ -110018,6 +114107,15 @@ const ( DnsNameStateFailed = "failed" ) +// DnsNameState_Values returns all elements of the DnsNameState enum +func DnsNameState_Values() []string { + return []string{ + DnsNameStatePendingVerification, + DnsNameStateVerified, + DnsNameStateFailed, + } +} + const ( // DnsSupportValueEnable is a DnsSupportValue enum value DnsSupportValueEnable = "enable" @@ -110026,6 +114124,14 @@ const ( DnsSupportValueDisable = "disable" ) +// DnsSupportValue_Values returns all elements of the DnsSupportValue enum +func DnsSupportValue_Values() []string { + return []string{ + DnsSupportValueEnable, + DnsSupportValueDisable, + } +} + const ( // DomainTypeVpc is a DomainType enum value DomainTypeVpc = "vpc" @@ -110034,6 +114140,14 @@ const ( DomainTypeStandard = "standard" ) +// DomainType_Values returns all elements of the DomainType enum +func DomainType_Values() []string { + return []string{ + DomainTypeVpc, + DomainTypeStandard, + } +} + const ( // EbsEncryptionSupportUnsupported is a EbsEncryptionSupport enum value EbsEncryptionSupportUnsupported = "unsupported" @@ -110042,6 +114156,34 @@ const ( EbsEncryptionSupportSupported = "supported" ) +// EbsEncryptionSupport_Values returns all elements of the EbsEncryptionSupport enum +func EbsEncryptionSupport_Values() []string { + return []string{ + EbsEncryptionSupportUnsupported, + EbsEncryptionSupportSupported, + } +} + +const ( + // EbsNvmeSupportUnsupported is a EbsNvmeSupport enum value + EbsNvmeSupportUnsupported = "unsupported" + + // EbsNvmeSupportSupported is a EbsNvmeSupport enum value + EbsNvmeSupportSupported = "supported" + + // EbsNvmeSupportRequired is a EbsNvmeSupport enum value + EbsNvmeSupportRequired = "required" +) + +// EbsNvmeSupport_Values returns all elements of the EbsNvmeSupport enum +func EbsNvmeSupport_Values() []string { + return []string{ + EbsNvmeSupportUnsupported, + EbsNvmeSupportSupported, + EbsNvmeSupportRequired, + } +} + const ( // EbsOptimizedSupportUnsupported is a EbsOptimizedSupport enum value EbsOptimizedSupportUnsupported = "unsupported" @@ -110053,11 +114195,27 @@ const ( EbsOptimizedSupportDefault = "default" ) +// EbsOptimizedSupport_Values returns all elements of the EbsOptimizedSupport enum +func EbsOptimizedSupport_Values() []string { + return []string{ + EbsOptimizedSupportUnsupported, + EbsOptimizedSupportSupported, + EbsOptimizedSupportDefault, + } +} + const ( // ElasticGpuStateAttached is a ElasticGpuState enum value ElasticGpuStateAttached = "ATTACHED" ) +// ElasticGpuState_Values returns all elements of the ElasticGpuState enum +func ElasticGpuState_Values() []string { + return []string{ + ElasticGpuStateAttached, + } +} + const ( // ElasticGpuStatusOk is a ElasticGpuStatus enum value ElasticGpuStatusOk = "OK" @@ -110066,6 +114224,14 @@ const ( ElasticGpuStatusImpaired = "IMPAIRED" ) +// ElasticGpuStatus_Values returns all elements of the ElasticGpuStatus enum +func ElasticGpuStatus_Values() []string { + return []string{ + ElasticGpuStatusOk, + ElasticGpuStatusImpaired, + } +} + const ( // EnaSupportUnsupported is a EnaSupport enum value EnaSupportUnsupported = "unsupported" @@ -110077,6 +114243,15 @@ const ( EnaSupportRequired = "required" ) +// EnaSupport_Values returns all elements of the EnaSupport enum +func EnaSupport_Values() []string { + return []string{ + EnaSupportUnsupported, + EnaSupportSupported, + EnaSupportRequired, + } +} + const ( // EndDateTypeUnlimited is a EndDateType enum value EndDateTypeUnlimited = "unlimited" @@ -110085,6 +114260,14 @@ const ( EndDateTypeLimited = "limited" ) +// EndDateType_Values returns all elements of the EndDateType enum +func EndDateType_Values() []string { + return []string{ + EndDateTypeUnlimited, + EndDateTypeLimited, + } +} + const ( // EventCodeInstanceReboot is a EventCode enum value EventCodeInstanceReboot = "instance-reboot" @@ -110102,6 +114285,17 @@ const ( EventCodeInstanceStop = "instance-stop" ) +// EventCode_Values returns all elements of the EventCode enum +func EventCode_Values() []string { + return []string{ + EventCodeInstanceReboot, + EventCodeSystemReboot, + EventCodeSystemMaintenance, + EventCodeInstanceRetirement, + EventCodeInstanceStop, + } +} + const ( // EventTypeInstanceChange is a EventType enum value EventTypeInstanceChange = "instanceChange" @@ -110116,6 +114310,16 @@ const ( EventTypeInformation = "information" ) +// EventType_Values returns all elements of the EventType enum +func EventType_Values() []string { + return []string{ + EventTypeInstanceChange, + EventTypeFleetRequestChange, + EventTypeError, + EventTypeInformation, + } +} + const ( // ExcessCapacityTerminationPolicyNoTermination is a ExcessCapacityTerminationPolicy enum value ExcessCapacityTerminationPolicyNoTermination = "noTermination" @@ -110124,6 +114328,14 @@ const ( ExcessCapacityTerminationPolicyDefault = "default" ) +// ExcessCapacityTerminationPolicy_Values returns all elements of the ExcessCapacityTerminationPolicy enum +func ExcessCapacityTerminationPolicy_Values() []string { + return []string{ + ExcessCapacityTerminationPolicyNoTermination, + ExcessCapacityTerminationPolicyDefault, + } +} + const ( // ExportEnvironmentCitrix is a ExportEnvironment enum value ExportEnvironmentCitrix = "citrix" @@ -110135,6 +114347,15 @@ const ( ExportEnvironmentMicrosoft = "microsoft" ) +// ExportEnvironment_Values returns all elements of the ExportEnvironment enum +func ExportEnvironment_Values() []string { + return []string{ + ExportEnvironmentCitrix, + ExportEnvironmentVmware, + ExportEnvironmentMicrosoft, + } +} + const ( // ExportTaskStateActive is a ExportTaskState enum value ExportTaskStateActive = "active" @@ -110149,6 +114370,16 @@ const ( ExportTaskStateCompleted = "completed" ) +// ExportTaskState_Values returns all elements of the ExportTaskState enum +func ExportTaskState_Values() []string { + return []string{ + ExportTaskStateActive, + ExportTaskStateCancelling, + ExportTaskStateCancelled, + ExportTaskStateCompleted, + } +} + const ( // FastSnapshotRestoreStateCodeEnabling is a FastSnapshotRestoreStateCode enum value FastSnapshotRestoreStateCodeEnabling = "enabling" @@ -110166,6 +114397,17 @@ const ( FastSnapshotRestoreStateCodeDisabled = "disabled" ) +// FastSnapshotRestoreStateCode_Values returns all elements of the FastSnapshotRestoreStateCode enum +func FastSnapshotRestoreStateCode_Values() []string { + return []string{ + FastSnapshotRestoreStateCodeEnabling, + FastSnapshotRestoreStateCodeOptimizing, + FastSnapshotRestoreStateCodeEnabled, + FastSnapshotRestoreStateCodeDisabling, + FastSnapshotRestoreStateCodeDisabled, + } +} + const ( // FleetActivityStatusError is a FleetActivityStatus enum value FleetActivityStatusError = "error" @@ -110180,11 +114422,28 @@ const ( FleetActivityStatusFulfilled = "fulfilled" ) +// FleetActivityStatus_Values returns all elements of the FleetActivityStatus enum +func FleetActivityStatus_Values() []string { + return []string{ + FleetActivityStatusError, + FleetActivityStatusPendingFulfillment, + FleetActivityStatusPendingTermination, + FleetActivityStatusFulfilled, + } +} + const ( // FleetCapacityReservationUsageStrategyUseCapacityReservationsFirst is a FleetCapacityReservationUsageStrategy enum value FleetCapacityReservationUsageStrategyUseCapacityReservationsFirst = "use-capacity-reservations-first" ) +// FleetCapacityReservationUsageStrategy_Values returns all elements of the FleetCapacityReservationUsageStrategy enum +func FleetCapacityReservationUsageStrategy_Values() []string { + return []string{ + FleetCapacityReservationUsageStrategyUseCapacityReservationsFirst, + } +} + const ( // FleetEventTypeInstanceChange is a FleetEventType enum value FleetEventTypeInstanceChange = "instance-change" @@ -110196,6 +114455,15 @@ const ( FleetEventTypeServiceError = "service-error" ) +// FleetEventType_Values returns all elements of the FleetEventType enum +func FleetEventType_Values() []string { + return []string{ + FleetEventTypeInstanceChange, + FleetEventTypeFleetChange, + FleetEventTypeServiceError, + } +} + const ( // FleetExcessCapacityTerminationPolicyNoTermination is a FleetExcessCapacityTerminationPolicy enum value FleetExcessCapacityTerminationPolicyNoTermination = "no-termination" @@ -110204,6 +114472,14 @@ const ( FleetExcessCapacityTerminationPolicyTermination = "termination" ) +// FleetExcessCapacityTerminationPolicy_Values returns all elements of the FleetExcessCapacityTerminationPolicy enum +func FleetExcessCapacityTerminationPolicy_Values() []string { + return []string{ + FleetExcessCapacityTerminationPolicyNoTermination, + FleetExcessCapacityTerminationPolicyTermination, + } +} + const ( // FleetOnDemandAllocationStrategyLowestPrice is a FleetOnDemandAllocationStrategy enum value FleetOnDemandAllocationStrategyLowestPrice = "lowest-price" @@ -110212,6 +114488,14 @@ const ( FleetOnDemandAllocationStrategyPrioritized = "prioritized" ) +// FleetOnDemandAllocationStrategy_Values returns all elements of the FleetOnDemandAllocationStrategy enum +func FleetOnDemandAllocationStrategy_Values() []string { + return []string{ + FleetOnDemandAllocationStrategyLowestPrice, + FleetOnDemandAllocationStrategyPrioritized, + } +} + const ( // FleetStateCodeSubmitted is a FleetStateCode enum value FleetStateCodeSubmitted = "submitted" @@ -110235,6 +114519,19 @@ const ( FleetStateCodeModifying = "modifying" ) +// FleetStateCode_Values returns all elements of the FleetStateCode enum +func FleetStateCode_Values() []string { + return []string{ + FleetStateCodeSubmitted, + FleetStateCodeActive, + FleetStateCodeDeleted, + FleetStateCodeFailed, + FleetStateCodeDeletedRunning, + FleetStateCodeDeletedTerminating, + FleetStateCodeModifying, + } +} + const ( // FleetTypeRequest is a FleetType enum value FleetTypeRequest = "request" @@ -110246,6 +114543,15 @@ const ( FleetTypeInstant = "instant" ) +// FleetType_Values returns all elements of the FleetType enum +func FleetType_Values() []string { + return []string{ + FleetTypeRequest, + FleetTypeMaintain, + FleetTypeInstant, + } +} + const ( // FlowLogsResourceTypeVpc is a FlowLogsResourceType enum value FlowLogsResourceTypeVpc = "VPC" @@ -110257,6 +114563,15 @@ const ( FlowLogsResourceTypeNetworkInterface = "NetworkInterface" ) +// FlowLogsResourceType_Values returns all elements of the FlowLogsResourceType enum +func FlowLogsResourceType_Values() []string { + return []string{ + FlowLogsResourceTypeVpc, + FlowLogsResourceTypeSubnet, + FlowLogsResourceTypeNetworkInterface, + } +} + const ( // FpgaImageAttributeNameDescription is a FpgaImageAttributeName enum value FpgaImageAttributeNameDescription = "description" @@ -110271,6 +114586,16 @@ const ( FpgaImageAttributeNameProductCodes = "productCodes" ) +// FpgaImageAttributeName_Values returns all elements of the FpgaImageAttributeName enum +func FpgaImageAttributeName_Values() []string { + return []string{ + FpgaImageAttributeNameDescription, + FpgaImageAttributeNameName, + FpgaImageAttributeNameLoadPermission, + FpgaImageAttributeNameProductCodes, + } +} + const ( // FpgaImageStateCodePending is a FpgaImageStateCode enum value FpgaImageStateCodePending = "pending" @@ -110285,11 +114610,28 @@ const ( FpgaImageStateCodeUnavailable = "unavailable" ) +// FpgaImageStateCode_Values returns all elements of the FpgaImageStateCode enum +func FpgaImageStateCode_Values() []string { + return []string{ + FpgaImageStateCodePending, + FpgaImageStateCodeFailed, + FpgaImageStateCodeAvailable, + FpgaImageStateCodeUnavailable, + } +} + const ( // GatewayTypeIpsec1 is a GatewayType enum value GatewayTypeIpsec1 = "ipsec.1" ) +// GatewayType_Values returns all elements of the GatewayType enum +func GatewayType_Values() []string { + return []string{ + GatewayTypeIpsec1, + } +} + const ( // HostRecoveryOn is a HostRecovery enum value HostRecoveryOn = "on" @@ -110298,6 +114640,14 @@ const ( HostRecoveryOff = "off" ) +// HostRecovery_Values returns all elements of the HostRecovery enum +func HostRecovery_Values() []string { + return []string{ + HostRecoveryOn, + HostRecoveryOff, + } +} + const ( // HostTenancyDedicated is a HostTenancy enum value HostTenancyDedicated = "dedicated" @@ -110306,6 +114656,14 @@ const ( HostTenancyHost = "host" ) +// HostTenancy_Values returns all elements of the HostTenancy enum +func HostTenancy_Values() []string { + return []string{ + HostTenancyDedicated, + HostTenancyHost, + } +} + const ( // HttpTokensStateOptional is a HttpTokensState enum value HttpTokensStateOptional = "optional" @@ -110314,6 +114672,14 @@ const ( HttpTokensStateRequired = "required" ) +// HttpTokensState_Values returns all elements of the HttpTokensState enum +func HttpTokensState_Values() []string { + return []string{ + HttpTokensStateOptional, + HttpTokensStateRequired, + } +} + const ( // HypervisorTypeOvm is a HypervisorType enum value HypervisorTypeOvm = "ovm" @@ -110322,6 +114688,14 @@ const ( HypervisorTypeXen = "xen" ) +// HypervisorType_Values returns all elements of the HypervisorType enum +func HypervisorType_Values() []string { + return []string{ + HypervisorTypeOvm, + HypervisorTypeXen, + } +} + const ( // IamInstanceProfileAssociationStateAssociating is a IamInstanceProfileAssociationState enum value IamInstanceProfileAssociationStateAssociating = "associating" @@ -110336,6 +114710,16 @@ const ( IamInstanceProfileAssociationStateDisassociated = "disassociated" ) +// IamInstanceProfileAssociationState_Values returns all elements of the IamInstanceProfileAssociationState enum +func IamInstanceProfileAssociationState_Values() []string { + return []string{ + IamInstanceProfileAssociationStateAssociating, + IamInstanceProfileAssociationStateAssociated, + IamInstanceProfileAssociationStateDisassociating, + IamInstanceProfileAssociationStateDisassociated, + } +} + const ( // ImageAttributeNameDescription is a ImageAttributeName enum value ImageAttributeNameDescription = "description" @@ -110359,6 +114743,19 @@ const ( ImageAttributeNameSriovNetSupport = "sriovNetSupport" ) +// ImageAttributeName_Values returns all elements of the ImageAttributeName enum +func ImageAttributeName_Values() []string { + return []string{ + ImageAttributeNameDescription, + ImageAttributeNameKernel, + ImageAttributeNameRamdisk, + ImageAttributeNameLaunchPermission, + ImageAttributeNameProductCodes, + ImageAttributeNameBlockDeviceMapping, + ImageAttributeNameSriovNetSupport, + } +} + const ( // ImageStatePending is a ImageState enum value ImageStatePending = "pending" @@ -110382,6 +114779,19 @@ const ( ImageStateError = "error" ) +// ImageState_Values returns all elements of the ImageState enum +func ImageState_Values() []string { + return []string{ + ImageStatePending, + ImageStateAvailable, + ImageStateInvalid, + ImageStateDeregistered, + ImageStateTransient, + ImageStateFailed, + ImageStateError, + } +} + const ( // ImageTypeValuesMachine is a ImageTypeValues enum value ImageTypeValuesMachine = "machine" @@ -110393,6 +114803,15 @@ const ( ImageTypeValuesRamdisk = "ramdisk" ) +// ImageTypeValues_Values returns all elements of the ImageTypeValues enum +func ImageTypeValues_Values() []string { + return []string{ + ImageTypeValuesMachine, + ImageTypeValuesKernel, + ImageTypeValuesRamdisk, + } +} + const ( // InstanceAttributeNameInstanceType is a InstanceAttributeName enum value InstanceAttributeNameInstanceType = "instanceType" @@ -110437,6 +114856,26 @@ const ( InstanceAttributeNameEnaSupport = "enaSupport" ) +// InstanceAttributeName_Values returns all elements of the InstanceAttributeName enum +func InstanceAttributeName_Values() []string { + return []string{ + InstanceAttributeNameInstanceType, + InstanceAttributeNameKernel, + InstanceAttributeNameRamdisk, + InstanceAttributeNameUserData, + InstanceAttributeNameDisableApiTermination, + InstanceAttributeNameInstanceInitiatedShutdownBehavior, + InstanceAttributeNameRootDeviceName, + InstanceAttributeNameBlockDeviceMapping, + InstanceAttributeNameProductCodes, + InstanceAttributeNameSourceDestCheck, + InstanceAttributeNameGroupSet, + InstanceAttributeNameEbsOptimized, + InstanceAttributeNameSriovNetSupport, + InstanceAttributeNameEnaSupport, + } +} + const ( // InstanceHealthStatusHealthy is a InstanceHealthStatus enum value InstanceHealthStatusHealthy = "healthy" @@ -110445,6 +114884,14 @@ const ( InstanceHealthStatusUnhealthy = "unhealthy" ) +// InstanceHealthStatus_Values returns all elements of the InstanceHealthStatus enum +func InstanceHealthStatus_Values() []string { + return []string{ + InstanceHealthStatusHealthy, + InstanceHealthStatusUnhealthy, + } +} + const ( // InstanceInterruptionBehaviorHibernate is a InstanceInterruptionBehavior enum value InstanceInterruptionBehaviorHibernate = "hibernate" @@ -110456,6 +114903,15 @@ const ( InstanceInterruptionBehaviorTerminate = "terminate" ) +// InstanceInterruptionBehavior_Values returns all elements of the InstanceInterruptionBehavior enum +func InstanceInterruptionBehavior_Values() []string { + return []string{ + InstanceInterruptionBehaviorHibernate, + InstanceInterruptionBehaviorStop, + InstanceInterruptionBehaviorTerminate, + } +} + const ( // InstanceLifecycleSpot is a InstanceLifecycle enum value InstanceLifecycleSpot = "spot" @@ -110464,6 +114920,14 @@ const ( InstanceLifecycleOnDemand = "on-demand" ) +// InstanceLifecycle_Values returns all elements of the InstanceLifecycle enum +func InstanceLifecycle_Values() []string { + return []string{ + InstanceLifecycleSpot, + InstanceLifecycleOnDemand, + } +} + const ( // InstanceLifecycleTypeSpot is a InstanceLifecycleType enum value InstanceLifecycleTypeSpot = "spot" @@ -110472,6 +114936,14 @@ const ( InstanceLifecycleTypeScheduled = "scheduled" ) +// InstanceLifecycleType_Values returns all elements of the InstanceLifecycleType enum +func InstanceLifecycleType_Values() []string { + return []string{ + InstanceLifecycleTypeSpot, + InstanceLifecycleTypeScheduled, + } +} + const ( // InstanceMatchCriteriaOpen is a InstanceMatchCriteria enum value InstanceMatchCriteriaOpen = "open" @@ -110480,6 +114952,14 @@ const ( InstanceMatchCriteriaTargeted = "targeted" ) +// InstanceMatchCriteria_Values returns all elements of the InstanceMatchCriteria enum +func InstanceMatchCriteria_Values() []string { + return []string{ + InstanceMatchCriteriaOpen, + InstanceMatchCriteriaTargeted, + } +} + const ( // InstanceMetadataEndpointStateDisabled is a InstanceMetadataEndpointState enum value InstanceMetadataEndpointStateDisabled = "disabled" @@ -110488,6 +114968,14 @@ const ( InstanceMetadataEndpointStateEnabled = "enabled" ) +// InstanceMetadataEndpointState_Values returns all elements of the InstanceMetadataEndpointState enum +func InstanceMetadataEndpointState_Values() []string { + return []string{ + InstanceMetadataEndpointStateDisabled, + InstanceMetadataEndpointStateEnabled, + } +} + const ( // InstanceMetadataOptionsStatePending is a InstanceMetadataOptionsState enum value InstanceMetadataOptionsStatePending = "pending" @@ -110496,6 +114984,14 @@ const ( InstanceMetadataOptionsStateApplied = "applied" ) +// InstanceMetadataOptionsState_Values returns all elements of the InstanceMetadataOptionsState enum +func InstanceMetadataOptionsState_Values() []string { + return []string{ + InstanceMetadataOptionsStatePending, + InstanceMetadataOptionsStateApplied, + } +} + const ( // InstanceStateNamePending is a InstanceStateName enum value InstanceStateNamePending = "pending" @@ -110516,6 +115012,18 @@ const ( InstanceStateNameStopped = "stopped" ) +// InstanceStateName_Values returns all elements of the InstanceStateName enum +func InstanceStateName_Values() []string { + return []string{ + InstanceStateNamePending, + InstanceStateNameRunning, + InstanceStateNameShuttingDown, + InstanceStateNameTerminated, + InstanceStateNameStopping, + InstanceStateNameStopped, + } +} + const ( // InstanceTypeT1Micro is a InstanceType enum value InstanceTypeT1Micro = "t1.micro" @@ -110772,6 +115280,60 @@ const ( // InstanceTypeR5ad24xlarge is a InstanceType enum value InstanceTypeR5ad24xlarge = "r5ad.24xlarge" + // InstanceTypeR6gMetal is a InstanceType enum value + InstanceTypeR6gMetal = "r6g.metal" + + // InstanceTypeR6gMedium is a InstanceType enum value + InstanceTypeR6gMedium = "r6g.medium" + + // InstanceTypeR6gLarge is a InstanceType enum value + InstanceTypeR6gLarge = "r6g.large" + + // InstanceTypeR6gXlarge is a InstanceType enum value + InstanceTypeR6gXlarge = "r6g.xlarge" + + // InstanceTypeR6g2xlarge is a InstanceType enum value + InstanceTypeR6g2xlarge = "r6g.2xlarge" + + // InstanceTypeR6g4xlarge is a InstanceType enum value + InstanceTypeR6g4xlarge = "r6g.4xlarge" + + // InstanceTypeR6g8xlarge is a InstanceType enum value + InstanceTypeR6g8xlarge = "r6g.8xlarge" + + // InstanceTypeR6g12xlarge is a InstanceType enum value + InstanceTypeR6g12xlarge = "r6g.12xlarge" + + // InstanceTypeR6g16xlarge is a InstanceType enum value + InstanceTypeR6g16xlarge = "r6g.16xlarge" + + // InstanceTypeR6gdMetal is a InstanceType enum value + InstanceTypeR6gdMetal = "r6gd.metal" + + // InstanceTypeR6gdMedium is a InstanceType enum value + InstanceTypeR6gdMedium = "r6gd.medium" + + // InstanceTypeR6gdLarge is a InstanceType enum value + InstanceTypeR6gdLarge = "r6gd.large" + + // InstanceTypeR6gdXlarge is a InstanceType enum value + InstanceTypeR6gdXlarge = "r6gd.xlarge" + + // InstanceTypeR6gd2xlarge is a InstanceType enum value + InstanceTypeR6gd2xlarge = "r6gd.2xlarge" + + // InstanceTypeR6gd4xlarge is a InstanceType enum value + InstanceTypeR6gd4xlarge = "r6gd.4xlarge" + + // InstanceTypeR6gd8xlarge is a InstanceType enum value + InstanceTypeR6gd8xlarge = "r6gd.8xlarge" + + // InstanceTypeR6gd12xlarge is a InstanceType enum value + InstanceTypeR6gd12xlarge = "r6gd.12xlarge" + + // InstanceTypeR6gd16xlarge is a InstanceType enum value + InstanceTypeR6gd16xlarge = "r6gd.16xlarge" + // InstanceTypeX116xlarge is a InstanceType enum value InstanceTypeX116xlarge = "x1.16xlarge" @@ -110922,6 +115484,30 @@ const ( // InstanceTypeC5Metal is a InstanceType enum value InstanceTypeC5Metal = "c5.metal" + // InstanceTypeC5aLarge is a InstanceType enum value + InstanceTypeC5aLarge = "c5a.large" + + // InstanceTypeC5aXlarge is a InstanceType enum value + InstanceTypeC5aXlarge = "c5a.xlarge" + + // InstanceTypeC5a2xlarge is a InstanceType enum value + InstanceTypeC5a2xlarge = "c5a.2xlarge" + + // InstanceTypeC5a4xlarge is a InstanceType enum value + InstanceTypeC5a4xlarge = "c5a.4xlarge" + + // InstanceTypeC5a8xlarge is a InstanceType enum value + InstanceTypeC5a8xlarge = "c5a.8xlarge" + + // InstanceTypeC5a12xlarge is a InstanceType enum value + InstanceTypeC5a12xlarge = "c5a.12xlarge" + + // InstanceTypeC5a16xlarge is a InstanceType enum value + InstanceTypeC5a16xlarge = "c5a.16xlarge" + + // InstanceTypeC5a24xlarge is a InstanceType enum value + InstanceTypeC5a24xlarge = "c5a.24xlarge" + // InstanceTypeC5dLarge is a InstanceType enum value InstanceTypeC5dLarge = "c5d.large" @@ -110967,6 +115553,60 @@ const ( // InstanceTypeC5n18xlarge is a InstanceType enum value InstanceTypeC5n18xlarge = "c5n.18xlarge" + // InstanceTypeC6gMetal is a InstanceType enum value + InstanceTypeC6gMetal = "c6g.metal" + + // InstanceTypeC6gMedium is a InstanceType enum value + InstanceTypeC6gMedium = "c6g.medium" + + // InstanceTypeC6gLarge is a InstanceType enum value + InstanceTypeC6gLarge = "c6g.large" + + // InstanceTypeC6gXlarge is a InstanceType enum value + InstanceTypeC6gXlarge = "c6g.xlarge" + + // InstanceTypeC6g2xlarge is a InstanceType enum value + InstanceTypeC6g2xlarge = "c6g.2xlarge" + + // InstanceTypeC6g4xlarge is a InstanceType enum value + InstanceTypeC6g4xlarge = "c6g.4xlarge" + + // InstanceTypeC6g8xlarge is a InstanceType enum value + InstanceTypeC6g8xlarge = "c6g.8xlarge" + + // InstanceTypeC6g12xlarge is a InstanceType enum value + InstanceTypeC6g12xlarge = "c6g.12xlarge" + + // InstanceTypeC6g16xlarge is a InstanceType enum value + InstanceTypeC6g16xlarge = "c6g.16xlarge" + + // InstanceTypeC6gdMetal is a InstanceType enum value + InstanceTypeC6gdMetal = "c6gd.metal" + + // InstanceTypeC6gdMedium is a InstanceType enum value + InstanceTypeC6gdMedium = "c6gd.medium" + + // InstanceTypeC6gdLarge is a InstanceType enum value + InstanceTypeC6gdLarge = "c6gd.large" + + // InstanceTypeC6gdXlarge is a InstanceType enum value + InstanceTypeC6gdXlarge = "c6gd.xlarge" + + // InstanceTypeC6gd2xlarge is a InstanceType enum value + InstanceTypeC6gd2xlarge = "c6gd.2xlarge" + + // InstanceTypeC6gd4xlarge is a InstanceType enum value + InstanceTypeC6gd4xlarge = "c6gd.4xlarge" + + // InstanceTypeC6gd8xlarge is a InstanceType enum value + InstanceTypeC6gd8xlarge = "c6gd.8xlarge" + + // InstanceTypeC6gd12xlarge is a InstanceType enum value + InstanceTypeC6gd12xlarge = "c6gd.12xlarge" + + // InstanceTypeC6gd16xlarge is a InstanceType enum value + InstanceTypeC6gd16xlarge = "c6gd.16xlarge" + // InstanceTypeCc14xlarge is a InstanceType enum value InstanceTypeCc14xlarge = "cc1.4xlarge" @@ -111009,6 +115649,9 @@ const ( // InstanceTypeG4dn16xlarge is a InstanceType enum value InstanceTypeG4dn16xlarge = "g4dn.16xlarge" + // InstanceTypeG4dnMetal is a InstanceType enum value + InstanceTypeG4dnMetal = "g4dn.metal" + // InstanceTypeCg14xlarge is a InstanceType enum value InstanceTypeCg14xlarge = "cg1.4xlarge" @@ -111329,8 +115972,402 @@ const ( // InstanceTypeInf124xlarge is a InstanceType enum value InstanceTypeInf124xlarge = "inf1.24xlarge" + + // InstanceTypeM6gMetal is a InstanceType enum value + InstanceTypeM6gMetal = "m6g.metal" + + // InstanceTypeM6gMedium is a InstanceType enum value + InstanceTypeM6gMedium = "m6g.medium" + + // InstanceTypeM6gLarge is a InstanceType enum value + InstanceTypeM6gLarge = "m6g.large" + + // InstanceTypeM6gXlarge is a InstanceType enum value + InstanceTypeM6gXlarge = "m6g.xlarge" + + // InstanceTypeM6g2xlarge is a InstanceType enum value + InstanceTypeM6g2xlarge = "m6g.2xlarge" + + // InstanceTypeM6g4xlarge is a InstanceType enum value + InstanceTypeM6g4xlarge = "m6g.4xlarge" + + // InstanceTypeM6g8xlarge is a InstanceType enum value + InstanceTypeM6g8xlarge = "m6g.8xlarge" + + // InstanceTypeM6g12xlarge is a InstanceType enum value + InstanceTypeM6g12xlarge = "m6g.12xlarge" + + // InstanceTypeM6g16xlarge is a InstanceType enum value + InstanceTypeM6g16xlarge = "m6g.16xlarge" + + // InstanceTypeM6gdMetal is a InstanceType enum value + InstanceTypeM6gdMetal = "m6gd.metal" + + // InstanceTypeM6gdMedium is a InstanceType enum value + InstanceTypeM6gdMedium = "m6gd.medium" + + // InstanceTypeM6gdLarge is a InstanceType enum value + InstanceTypeM6gdLarge = "m6gd.large" + + // InstanceTypeM6gdXlarge is a InstanceType enum value + InstanceTypeM6gdXlarge = "m6gd.xlarge" + + // InstanceTypeM6gd2xlarge is a InstanceType enum value + InstanceTypeM6gd2xlarge = "m6gd.2xlarge" + + // InstanceTypeM6gd4xlarge is a InstanceType enum value + InstanceTypeM6gd4xlarge = "m6gd.4xlarge" + + // InstanceTypeM6gd8xlarge is a InstanceType enum value + InstanceTypeM6gd8xlarge = "m6gd.8xlarge" + + // InstanceTypeM6gd12xlarge is a InstanceType enum value + InstanceTypeM6gd12xlarge = "m6gd.12xlarge" + + // InstanceTypeM6gd16xlarge is a InstanceType enum value + InstanceTypeM6gd16xlarge = "m6gd.16xlarge" ) +// InstanceType_Values returns all elements of the InstanceType enum +func InstanceType_Values() []string { + return []string{ + InstanceTypeT1Micro, + InstanceTypeT2Nano, + InstanceTypeT2Micro, + InstanceTypeT2Small, + InstanceTypeT2Medium, + InstanceTypeT2Large, + InstanceTypeT2Xlarge, + InstanceTypeT22xlarge, + InstanceTypeT3Nano, + InstanceTypeT3Micro, + InstanceTypeT3Small, + InstanceTypeT3Medium, + InstanceTypeT3Large, + InstanceTypeT3Xlarge, + InstanceTypeT32xlarge, + InstanceTypeT3aNano, + InstanceTypeT3aMicro, + InstanceTypeT3aSmall, + InstanceTypeT3aMedium, + InstanceTypeT3aLarge, + InstanceTypeT3aXlarge, + InstanceTypeT3a2xlarge, + InstanceTypeM1Small, + InstanceTypeM1Medium, + InstanceTypeM1Large, + InstanceTypeM1Xlarge, + InstanceTypeM3Medium, + InstanceTypeM3Large, + InstanceTypeM3Xlarge, + InstanceTypeM32xlarge, + InstanceTypeM4Large, + InstanceTypeM4Xlarge, + InstanceTypeM42xlarge, + InstanceTypeM44xlarge, + InstanceTypeM410xlarge, + InstanceTypeM416xlarge, + InstanceTypeM2Xlarge, + InstanceTypeM22xlarge, + InstanceTypeM24xlarge, + InstanceTypeCr18xlarge, + InstanceTypeR3Large, + InstanceTypeR3Xlarge, + InstanceTypeR32xlarge, + InstanceTypeR34xlarge, + InstanceTypeR38xlarge, + InstanceTypeR4Large, + InstanceTypeR4Xlarge, + InstanceTypeR42xlarge, + InstanceTypeR44xlarge, + InstanceTypeR48xlarge, + InstanceTypeR416xlarge, + InstanceTypeR5Large, + InstanceTypeR5Xlarge, + InstanceTypeR52xlarge, + InstanceTypeR54xlarge, + InstanceTypeR58xlarge, + InstanceTypeR512xlarge, + InstanceTypeR516xlarge, + InstanceTypeR524xlarge, + InstanceTypeR5Metal, + InstanceTypeR5aLarge, + InstanceTypeR5aXlarge, + InstanceTypeR5a2xlarge, + InstanceTypeR5a4xlarge, + InstanceTypeR5a8xlarge, + InstanceTypeR5a12xlarge, + InstanceTypeR5a16xlarge, + InstanceTypeR5a24xlarge, + InstanceTypeR5dLarge, + InstanceTypeR5dXlarge, + InstanceTypeR5d2xlarge, + InstanceTypeR5d4xlarge, + InstanceTypeR5d8xlarge, + InstanceTypeR5d12xlarge, + InstanceTypeR5d16xlarge, + InstanceTypeR5d24xlarge, + InstanceTypeR5dMetal, + InstanceTypeR5adLarge, + InstanceTypeR5adXlarge, + InstanceTypeR5ad2xlarge, + InstanceTypeR5ad4xlarge, + InstanceTypeR5ad8xlarge, + InstanceTypeR5ad12xlarge, + InstanceTypeR5ad16xlarge, + InstanceTypeR5ad24xlarge, + InstanceTypeR6gMetal, + InstanceTypeR6gMedium, + InstanceTypeR6gLarge, + InstanceTypeR6gXlarge, + InstanceTypeR6g2xlarge, + InstanceTypeR6g4xlarge, + InstanceTypeR6g8xlarge, + InstanceTypeR6g12xlarge, + InstanceTypeR6g16xlarge, + InstanceTypeR6gdMetal, + InstanceTypeR6gdMedium, + InstanceTypeR6gdLarge, + InstanceTypeR6gdXlarge, + InstanceTypeR6gd2xlarge, + InstanceTypeR6gd4xlarge, + InstanceTypeR6gd8xlarge, + InstanceTypeR6gd12xlarge, + InstanceTypeR6gd16xlarge, + InstanceTypeX116xlarge, + InstanceTypeX132xlarge, + InstanceTypeX1eXlarge, + InstanceTypeX1e2xlarge, + InstanceTypeX1e4xlarge, + InstanceTypeX1e8xlarge, + InstanceTypeX1e16xlarge, + InstanceTypeX1e32xlarge, + InstanceTypeI2Xlarge, + InstanceTypeI22xlarge, + InstanceTypeI24xlarge, + InstanceTypeI28xlarge, + InstanceTypeI3Large, + InstanceTypeI3Xlarge, + InstanceTypeI32xlarge, + InstanceTypeI34xlarge, + InstanceTypeI38xlarge, + InstanceTypeI316xlarge, + InstanceTypeI3Metal, + InstanceTypeI3enLarge, + InstanceTypeI3enXlarge, + InstanceTypeI3en2xlarge, + InstanceTypeI3en3xlarge, + InstanceTypeI3en6xlarge, + InstanceTypeI3en12xlarge, + InstanceTypeI3en24xlarge, + InstanceTypeI3enMetal, + InstanceTypeHi14xlarge, + InstanceTypeHs18xlarge, + InstanceTypeC1Medium, + InstanceTypeC1Xlarge, + InstanceTypeC3Large, + InstanceTypeC3Xlarge, + InstanceTypeC32xlarge, + InstanceTypeC34xlarge, + InstanceTypeC38xlarge, + InstanceTypeC4Large, + InstanceTypeC4Xlarge, + InstanceTypeC42xlarge, + InstanceTypeC44xlarge, + InstanceTypeC48xlarge, + InstanceTypeC5Large, + InstanceTypeC5Xlarge, + InstanceTypeC52xlarge, + InstanceTypeC54xlarge, + InstanceTypeC59xlarge, + InstanceTypeC512xlarge, + InstanceTypeC518xlarge, + InstanceTypeC524xlarge, + InstanceTypeC5Metal, + InstanceTypeC5aLarge, + InstanceTypeC5aXlarge, + InstanceTypeC5a2xlarge, + InstanceTypeC5a4xlarge, + InstanceTypeC5a8xlarge, + InstanceTypeC5a12xlarge, + InstanceTypeC5a16xlarge, + InstanceTypeC5a24xlarge, + InstanceTypeC5dLarge, + InstanceTypeC5dXlarge, + InstanceTypeC5d2xlarge, + InstanceTypeC5d4xlarge, + InstanceTypeC5d9xlarge, + InstanceTypeC5d12xlarge, + InstanceTypeC5d18xlarge, + InstanceTypeC5d24xlarge, + InstanceTypeC5dMetal, + InstanceTypeC5nLarge, + InstanceTypeC5nXlarge, + InstanceTypeC5n2xlarge, + InstanceTypeC5n4xlarge, + InstanceTypeC5n9xlarge, + InstanceTypeC5n18xlarge, + InstanceTypeC6gMetal, + InstanceTypeC6gMedium, + InstanceTypeC6gLarge, + InstanceTypeC6gXlarge, + InstanceTypeC6g2xlarge, + InstanceTypeC6g4xlarge, + InstanceTypeC6g8xlarge, + InstanceTypeC6g12xlarge, + InstanceTypeC6g16xlarge, + InstanceTypeC6gdMetal, + InstanceTypeC6gdMedium, + InstanceTypeC6gdLarge, + InstanceTypeC6gdXlarge, + InstanceTypeC6gd2xlarge, + InstanceTypeC6gd4xlarge, + InstanceTypeC6gd8xlarge, + InstanceTypeC6gd12xlarge, + InstanceTypeC6gd16xlarge, + InstanceTypeCc14xlarge, + InstanceTypeCc28xlarge, + InstanceTypeG22xlarge, + InstanceTypeG28xlarge, + InstanceTypeG34xlarge, + InstanceTypeG38xlarge, + InstanceTypeG316xlarge, + InstanceTypeG3sXlarge, + InstanceTypeG4dnXlarge, + InstanceTypeG4dn2xlarge, + InstanceTypeG4dn4xlarge, + InstanceTypeG4dn8xlarge, + InstanceTypeG4dn12xlarge, + InstanceTypeG4dn16xlarge, + InstanceTypeG4dnMetal, + InstanceTypeCg14xlarge, + InstanceTypeP2Xlarge, + InstanceTypeP28xlarge, + InstanceTypeP216xlarge, + InstanceTypeP32xlarge, + InstanceTypeP38xlarge, + InstanceTypeP316xlarge, + InstanceTypeP3dn24xlarge, + InstanceTypeD2Xlarge, + InstanceTypeD22xlarge, + InstanceTypeD24xlarge, + InstanceTypeD28xlarge, + InstanceTypeF12xlarge, + InstanceTypeF14xlarge, + InstanceTypeF116xlarge, + InstanceTypeM5Large, + InstanceTypeM5Xlarge, + InstanceTypeM52xlarge, + InstanceTypeM54xlarge, + InstanceTypeM58xlarge, + InstanceTypeM512xlarge, + InstanceTypeM516xlarge, + InstanceTypeM524xlarge, + InstanceTypeM5Metal, + InstanceTypeM5aLarge, + InstanceTypeM5aXlarge, + InstanceTypeM5a2xlarge, + InstanceTypeM5a4xlarge, + InstanceTypeM5a8xlarge, + InstanceTypeM5a12xlarge, + InstanceTypeM5a16xlarge, + InstanceTypeM5a24xlarge, + InstanceTypeM5dLarge, + InstanceTypeM5dXlarge, + InstanceTypeM5d2xlarge, + InstanceTypeM5d4xlarge, + InstanceTypeM5d8xlarge, + InstanceTypeM5d12xlarge, + InstanceTypeM5d16xlarge, + InstanceTypeM5d24xlarge, + InstanceTypeM5dMetal, + InstanceTypeM5adLarge, + InstanceTypeM5adXlarge, + InstanceTypeM5ad2xlarge, + InstanceTypeM5ad4xlarge, + InstanceTypeM5ad8xlarge, + InstanceTypeM5ad12xlarge, + InstanceTypeM5ad16xlarge, + InstanceTypeM5ad24xlarge, + InstanceTypeH12xlarge, + InstanceTypeH14xlarge, + InstanceTypeH18xlarge, + InstanceTypeH116xlarge, + InstanceTypeZ1dLarge, + InstanceTypeZ1dXlarge, + InstanceTypeZ1d2xlarge, + InstanceTypeZ1d3xlarge, + InstanceTypeZ1d6xlarge, + InstanceTypeZ1d12xlarge, + InstanceTypeZ1dMetal, + InstanceTypeU6tb1Metal, + InstanceTypeU9tb1Metal, + InstanceTypeU12tb1Metal, + InstanceTypeU18tb1Metal, + InstanceTypeU24tb1Metal, + InstanceTypeA1Medium, + InstanceTypeA1Large, + InstanceTypeA1Xlarge, + InstanceTypeA12xlarge, + InstanceTypeA14xlarge, + InstanceTypeA1Metal, + InstanceTypeM5dnLarge, + InstanceTypeM5dnXlarge, + InstanceTypeM5dn2xlarge, + InstanceTypeM5dn4xlarge, + InstanceTypeM5dn8xlarge, + InstanceTypeM5dn12xlarge, + InstanceTypeM5dn16xlarge, + InstanceTypeM5dn24xlarge, + InstanceTypeM5nLarge, + InstanceTypeM5nXlarge, + InstanceTypeM5n2xlarge, + InstanceTypeM5n4xlarge, + InstanceTypeM5n8xlarge, + InstanceTypeM5n12xlarge, + InstanceTypeM5n16xlarge, + InstanceTypeM5n24xlarge, + InstanceTypeR5dnLarge, + InstanceTypeR5dnXlarge, + InstanceTypeR5dn2xlarge, + InstanceTypeR5dn4xlarge, + InstanceTypeR5dn8xlarge, + InstanceTypeR5dn12xlarge, + InstanceTypeR5dn16xlarge, + InstanceTypeR5dn24xlarge, + InstanceTypeR5nLarge, + InstanceTypeR5nXlarge, + InstanceTypeR5n2xlarge, + InstanceTypeR5n4xlarge, + InstanceTypeR5n8xlarge, + InstanceTypeR5n12xlarge, + InstanceTypeR5n16xlarge, + InstanceTypeR5n24xlarge, + InstanceTypeInf1Xlarge, + InstanceTypeInf12xlarge, + InstanceTypeInf16xlarge, + InstanceTypeInf124xlarge, + InstanceTypeM6gMetal, + InstanceTypeM6gMedium, + InstanceTypeM6gLarge, + InstanceTypeM6gXlarge, + InstanceTypeM6g2xlarge, + InstanceTypeM6g4xlarge, + InstanceTypeM6g8xlarge, + InstanceTypeM6g12xlarge, + InstanceTypeM6g16xlarge, + InstanceTypeM6gdMetal, + InstanceTypeM6gdMedium, + InstanceTypeM6gdLarge, + InstanceTypeM6gdXlarge, + InstanceTypeM6gd2xlarge, + InstanceTypeM6gd4xlarge, + InstanceTypeM6gd8xlarge, + InstanceTypeM6gd12xlarge, + InstanceTypeM6gd16xlarge, + } +} + const ( // InstanceTypeHypervisorNitro is a InstanceTypeHypervisor enum value InstanceTypeHypervisorNitro = "nitro" @@ -111339,6 +116376,14 @@ const ( InstanceTypeHypervisorXen = "xen" ) +// InstanceTypeHypervisor_Values returns all elements of the InstanceTypeHypervisor enum +func InstanceTypeHypervisor_Values() []string { + return []string{ + InstanceTypeHypervisorNitro, + InstanceTypeHypervisorXen, + } +} + const ( // InterfacePermissionTypeInstanceAttach is a InterfacePermissionType enum value InterfacePermissionTypeInstanceAttach = "INSTANCE-ATTACH" @@ -111347,6 +116392,14 @@ const ( InterfacePermissionTypeEipAssociate = "EIP-ASSOCIATE" ) +// InterfacePermissionType_Values returns all elements of the InterfacePermissionType enum +func InterfacePermissionType_Values() []string { + return []string{ + InterfacePermissionTypeInstanceAttach, + InterfacePermissionTypeEipAssociate, + } +} + const ( // Ipv6SupportValueEnable is a Ipv6SupportValue enum value Ipv6SupportValueEnable = "enable" @@ -111355,6 +116408,14 @@ const ( Ipv6SupportValueDisable = "disable" ) +// Ipv6SupportValue_Values returns all elements of the Ipv6SupportValue enum +func Ipv6SupportValue_Values() []string { + return []string{ + Ipv6SupportValueEnable, + Ipv6SupportValueDisable, + } +} + const ( // LaunchTemplateErrorCodeLaunchTemplateIdDoesNotExist is a LaunchTemplateErrorCode enum value LaunchTemplateErrorCodeLaunchTemplateIdDoesNotExist = "launchTemplateIdDoesNotExist" @@ -111375,6 +116436,18 @@ const ( LaunchTemplateErrorCodeUnexpectedError = "unexpectedError" ) +// LaunchTemplateErrorCode_Values returns all elements of the LaunchTemplateErrorCode enum +func LaunchTemplateErrorCode_Values() []string { + return []string{ + LaunchTemplateErrorCodeLaunchTemplateIdDoesNotExist, + LaunchTemplateErrorCodeLaunchTemplateIdMalformed, + LaunchTemplateErrorCodeLaunchTemplateNameDoesNotExist, + LaunchTemplateErrorCodeLaunchTemplateNameMalformed, + LaunchTemplateErrorCodeLaunchTemplateVersionDoesNotExist, + LaunchTemplateErrorCodeUnexpectedError, + } +} + const ( // LaunchTemplateHttpTokensStateOptional is a LaunchTemplateHttpTokensState enum value LaunchTemplateHttpTokensStateOptional = "optional" @@ -111383,6 +116456,14 @@ const ( LaunchTemplateHttpTokensStateRequired = "required" ) +// LaunchTemplateHttpTokensState_Values returns all elements of the LaunchTemplateHttpTokensState enum +func LaunchTemplateHttpTokensState_Values() []string { + return []string{ + LaunchTemplateHttpTokensStateOptional, + LaunchTemplateHttpTokensStateRequired, + } +} + const ( // LaunchTemplateInstanceMetadataEndpointStateDisabled is a LaunchTemplateInstanceMetadataEndpointState enum value LaunchTemplateInstanceMetadataEndpointStateDisabled = "disabled" @@ -111391,6 +116472,14 @@ const ( LaunchTemplateInstanceMetadataEndpointStateEnabled = "enabled" ) +// LaunchTemplateInstanceMetadataEndpointState_Values returns all elements of the LaunchTemplateInstanceMetadataEndpointState enum +func LaunchTemplateInstanceMetadataEndpointState_Values() []string { + return []string{ + LaunchTemplateInstanceMetadataEndpointStateDisabled, + LaunchTemplateInstanceMetadataEndpointStateEnabled, + } +} + const ( // LaunchTemplateInstanceMetadataOptionsStatePending is a LaunchTemplateInstanceMetadataOptionsState enum value LaunchTemplateInstanceMetadataOptionsStatePending = "pending" @@ -111399,6 +116488,14 @@ const ( LaunchTemplateInstanceMetadataOptionsStateApplied = "applied" ) +// LaunchTemplateInstanceMetadataOptionsState_Values returns all elements of the LaunchTemplateInstanceMetadataOptionsState enum +func LaunchTemplateInstanceMetadataOptionsState_Values() []string { + return []string{ + LaunchTemplateInstanceMetadataOptionsStatePending, + LaunchTemplateInstanceMetadataOptionsStateApplied, + } +} + const ( // ListingStateAvailable is a ListingState enum value ListingStateAvailable = "available" @@ -111413,6 +116510,16 @@ const ( ListingStatePending = "pending" ) +// ListingState_Values returns all elements of the ListingState enum +func ListingState_Values() []string { + return []string{ + ListingStateAvailable, + ListingStateSold, + ListingStateCancelled, + ListingStatePending, + } +} + const ( // ListingStatusActive is a ListingStatus enum value ListingStatusActive = "active" @@ -111427,6 +116534,16 @@ const ( ListingStatusClosed = "closed" ) +// ListingStatus_Values returns all elements of the ListingStatus enum +func ListingStatus_Values() []string { + return []string{ + ListingStatusActive, + ListingStatusPending, + ListingStatusCancelled, + ListingStatusClosed, + } +} + const ( // LocalGatewayRouteStatePending is a LocalGatewayRouteState enum value LocalGatewayRouteStatePending = "pending" @@ -111444,6 +116561,17 @@ const ( LocalGatewayRouteStateDeleted = "deleted" ) +// LocalGatewayRouteState_Values returns all elements of the LocalGatewayRouteState enum +func LocalGatewayRouteState_Values() []string { + return []string{ + LocalGatewayRouteStatePending, + LocalGatewayRouteStateActive, + LocalGatewayRouteStateBlackhole, + LocalGatewayRouteStateDeleting, + LocalGatewayRouteStateDeleted, + } +} + const ( // LocalGatewayRouteTypeStatic is a LocalGatewayRouteType enum value LocalGatewayRouteTypeStatic = "static" @@ -111452,6 +116580,14 @@ const ( LocalGatewayRouteTypePropagated = "propagated" ) +// LocalGatewayRouteType_Values returns all elements of the LocalGatewayRouteType enum +func LocalGatewayRouteType_Values() []string { + return []string{ + LocalGatewayRouteTypeStatic, + LocalGatewayRouteTypePropagated, + } +} + const ( // LocationTypeRegion is a LocationType enum value LocationTypeRegion = "region" @@ -111463,6 +116599,15 @@ const ( LocationTypeAvailabilityZoneId = "availability-zone-id" ) +// LocationType_Values returns all elements of the LocationType enum +func LocationType_Values() []string { + return []string{ + LocationTypeRegion, + LocationTypeAvailabilityZone, + LocationTypeAvailabilityZoneId, + } +} + const ( // LogDestinationTypeCloudWatchLogs is a LogDestinationType enum value LogDestinationTypeCloudWatchLogs = "cloud-watch-logs" @@ -111471,11 +116616,26 @@ const ( LogDestinationTypeS3 = "s3" ) +// LogDestinationType_Values returns all elements of the LogDestinationType enum +func LogDestinationType_Values() []string { + return []string{ + LogDestinationTypeCloudWatchLogs, + LogDestinationTypeS3, + } +} + const ( // MarketTypeSpot is a MarketType enum value MarketTypeSpot = "spot" ) +// MarketType_Values returns all elements of the MarketType enum +func MarketType_Values() []string { + return []string{ + MarketTypeSpot, + } +} + const ( // MembershipTypeStatic is a MembershipType enum value MembershipTypeStatic = "static" @@ -111484,6 +116644,14 @@ const ( MembershipTypeIgmp = "igmp" ) +// MembershipType_Values returns all elements of the MembershipType enum +func MembershipType_Values() []string { + return []string{ + MembershipTypeStatic, + MembershipTypeIgmp, + } +} + const ( // ModifyAvailabilityZoneOptInStatusOptedIn is a ModifyAvailabilityZoneOptInStatus enum value ModifyAvailabilityZoneOptInStatusOptedIn = "opted-in" @@ -111492,6 +116660,14 @@ const ( ModifyAvailabilityZoneOptInStatusNotOptedIn = "not-opted-in" ) +// ModifyAvailabilityZoneOptInStatus_Values returns all elements of the ModifyAvailabilityZoneOptInStatus enum +func ModifyAvailabilityZoneOptInStatus_Values() []string { + return []string{ + ModifyAvailabilityZoneOptInStatusOptedIn, + ModifyAvailabilityZoneOptInStatusNotOptedIn, + } +} + const ( // MonitoringStateDisabled is a MonitoringState enum value MonitoringStateDisabled = "disabled" @@ -111506,6 +116682,16 @@ const ( MonitoringStatePending = "pending" ) +// MonitoringState_Values returns all elements of the MonitoringState enum +func MonitoringState_Values() []string { + return []string{ + MonitoringStateDisabled, + MonitoringStateDisabling, + MonitoringStateEnabled, + MonitoringStatePending, + } +} + const ( // MoveStatusMovingToVpc is a MoveStatus enum value MoveStatusMovingToVpc = "movingToVpc" @@ -111514,6 +116700,14 @@ const ( MoveStatusRestoringToClassic = "restoringToClassic" ) +// MoveStatus_Values returns all elements of the MoveStatus enum +func MoveStatus_Values() []string { + return []string{ + MoveStatusMovingToVpc, + MoveStatusRestoringToClassic, + } +} + const ( // MulticastSupportValueEnable is a MulticastSupportValue enum value MulticastSupportValueEnable = "enable" @@ -111522,6 +116716,14 @@ const ( MulticastSupportValueDisable = "disable" ) +// MulticastSupportValue_Values returns all elements of the MulticastSupportValue enum +func MulticastSupportValue_Values() []string { + return []string{ + MulticastSupportValueEnable, + MulticastSupportValueDisable, + } +} + const ( // NatGatewayStatePending is a NatGatewayState enum value NatGatewayStatePending = "pending" @@ -111539,6 +116741,17 @@ const ( NatGatewayStateDeleted = "deleted" ) +// NatGatewayState_Values returns all elements of the NatGatewayState enum +func NatGatewayState_Values() []string { + return []string{ + NatGatewayStatePending, + NatGatewayStateFailed, + NatGatewayStateAvailable, + NatGatewayStateDeleting, + NatGatewayStateDeleted, + } +} + const ( // NetworkInterfaceAttributeDescription is a NetworkInterfaceAttribute enum value NetworkInterfaceAttributeDescription = "description" @@ -111553,11 +116766,28 @@ const ( NetworkInterfaceAttributeAttachment = "attachment" ) +// NetworkInterfaceAttribute_Values returns all elements of the NetworkInterfaceAttribute enum +func NetworkInterfaceAttribute_Values() []string { + return []string{ + NetworkInterfaceAttributeDescription, + NetworkInterfaceAttributeGroupSet, + NetworkInterfaceAttributeSourceDestCheck, + NetworkInterfaceAttributeAttachment, + } +} + const ( // NetworkInterfaceCreationTypeEfa is a NetworkInterfaceCreationType enum value NetworkInterfaceCreationTypeEfa = "efa" ) +// NetworkInterfaceCreationType_Values returns all elements of the NetworkInterfaceCreationType enum +func NetworkInterfaceCreationType_Values() []string { + return []string{ + NetworkInterfaceCreationTypeEfa, + } +} + const ( // NetworkInterfacePermissionStateCodePending is a NetworkInterfacePermissionStateCode enum value NetworkInterfacePermissionStateCodePending = "pending" @@ -111572,6 +116802,16 @@ const ( NetworkInterfacePermissionStateCodeRevoked = "revoked" ) +// NetworkInterfacePermissionStateCode_Values returns all elements of the NetworkInterfacePermissionStateCode enum +func NetworkInterfacePermissionStateCode_Values() []string { + return []string{ + NetworkInterfacePermissionStateCodePending, + NetworkInterfacePermissionStateCodeGranted, + NetworkInterfacePermissionStateCodeRevoking, + NetworkInterfacePermissionStateCodeRevoked, + } +} + const ( // NetworkInterfaceStatusAvailable is a NetworkInterfaceStatus enum value NetworkInterfaceStatusAvailable = "available" @@ -111589,6 +116829,17 @@ const ( NetworkInterfaceStatusDetaching = "detaching" ) +// NetworkInterfaceStatus_Values returns all elements of the NetworkInterfaceStatus enum +func NetworkInterfaceStatus_Values() []string { + return []string{ + NetworkInterfaceStatusAvailable, + NetworkInterfaceStatusAssociated, + NetworkInterfaceStatusAttaching, + NetworkInterfaceStatusInUse, + NetworkInterfaceStatusDetaching, + } +} + const ( // NetworkInterfaceTypeInterface is a NetworkInterfaceType enum value NetworkInterfaceTypeInterface = "interface" @@ -111600,6 +116851,15 @@ const ( NetworkInterfaceTypeEfa = "efa" ) +// NetworkInterfaceType_Values returns all elements of the NetworkInterfaceType enum +func NetworkInterfaceType_Values() []string { + return []string{ + NetworkInterfaceTypeInterface, + NetworkInterfaceTypeNatGateway, + NetworkInterfaceTypeEfa, + } +} + const ( // OfferingClassTypeStandard is a OfferingClassType enum value OfferingClassTypeStandard = "standard" @@ -111608,6 +116868,14 @@ const ( OfferingClassTypeConvertible = "convertible" ) +// OfferingClassType_Values returns all elements of the OfferingClassType enum +func OfferingClassType_Values() []string { + return []string{ + OfferingClassTypeStandard, + OfferingClassTypeConvertible, + } +} + const ( // OfferingTypeValuesHeavyUtilization is a OfferingTypeValues enum value OfferingTypeValuesHeavyUtilization = "Heavy Utilization" @@ -111628,6 +116896,18 @@ const ( OfferingTypeValuesAllUpfront = "All Upfront" ) +// OfferingTypeValues_Values returns all elements of the OfferingTypeValues enum +func OfferingTypeValues_Values() []string { + return []string{ + OfferingTypeValuesHeavyUtilization, + OfferingTypeValuesMediumUtilization, + OfferingTypeValuesLightUtilization, + OfferingTypeValuesNoUpfront, + OfferingTypeValuesPartialUpfront, + OfferingTypeValuesAllUpfront, + } +} + const ( // OnDemandAllocationStrategyLowestPrice is a OnDemandAllocationStrategy enum value OnDemandAllocationStrategyLowestPrice = "lowestPrice" @@ -111636,6 +116916,14 @@ const ( OnDemandAllocationStrategyPrioritized = "prioritized" ) +// OnDemandAllocationStrategy_Values returns all elements of the OnDemandAllocationStrategy enum +func OnDemandAllocationStrategy_Values() []string { + return []string{ + OnDemandAllocationStrategyLowestPrice, + OnDemandAllocationStrategyPrioritized, + } +} + const ( // OperationTypeAdd is a OperationType enum value OperationTypeAdd = "add" @@ -111644,6 +116932,14 @@ const ( OperationTypeRemove = "remove" ) +// OperationType_Values returns all elements of the OperationType enum +func OperationType_Values() []string { + return []string{ + OperationTypeAdd, + OperationTypeRemove, + } +} + const ( // PaymentOptionAllUpfront is a PaymentOption enum value PaymentOptionAllUpfront = "AllUpfront" @@ -111655,11 +116951,27 @@ const ( PaymentOptionNoUpfront = "NoUpfront" ) +// PaymentOption_Values returns all elements of the PaymentOption enum +func PaymentOption_Values() []string { + return []string{ + PaymentOptionAllUpfront, + PaymentOptionPartialUpfront, + PaymentOptionNoUpfront, + } +} + const ( // PermissionGroupAll is a PermissionGroup enum value PermissionGroupAll = "all" ) +// PermissionGroup_Values returns all elements of the PermissionGroup enum +func PermissionGroup_Values() []string { + return []string{ + PermissionGroupAll, + } +} + const ( // PlacementGroupStatePending is a PlacementGroupState enum value PlacementGroupStatePending = "pending" @@ -111674,6 +116986,16 @@ const ( PlacementGroupStateDeleted = "deleted" ) +// PlacementGroupState_Values returns all elements of the PlacementGroupState enum +func PlacementGroupState_Values() []string { + return []string{ + PlacementGroupStatePending, + PlacementGroupStateAvailable, + PlacementGroupStateDeleting, + PlacementGroupStateDeleted, + } +} + const ( // PlacementGroupStrategyCluster is a PlacementGroupStrategy enum value PlacementGroupStrategyCluster = "cluster" @@ -111685,6 +117007,15 @@ const ( PlacementGroupStrategySpread = "spread" ) +// PlacementGroupStrategy_Values returns all elements of the PlacementGroupStrategy enum +func PlacementGroupStrategy_Values() []string { + return []string{ + PlacementGroupStrategyCluster, + PlacementGroupStrategyPartition, + PlacementGroupStrategySpread, + } +} + const ( // PlacementStrategyCluster is a PlacementStrategy enum value PlacementStrategyCluster = "cluster" @@ -111696,11 +117027,83 @@ const ( PlacementStrategyPartition = "partition" ) +// PlacementStrategy_Values returns all elements of the PlacementStrategy enum +func PlacementStrategy_Values() []string { + return []string{ + PlacementStrategyCluster, + PlacementStrategySpread, + PlacementStrategyPartition, + } +} + const ( // PlatformValuesWindows is a PlatformValues enum value PlatformValuesWindows = "Windows" ) +// PlatformValues_Values returns all elements of the PlatformValues enum +func PlatformValues_Values() []string { + return []string{ + PlatformValuesWindows, + } +} + +const ( + // PrefixListStateCreateInProgress is a PrefixListState enum value + PrefixListStateCreateInProgress = "create-in-progress" + + // PrefixListStateCreateComplete is a PrefixListState enum value + PrefixListStateCreateComplete = "create-complete" + + // PrefixListStateCreateFailed is a PrefixListState enum value + PrefixListStateCreateFailed = "create-failed" + + // PrefixListStateModifyInProgress is a PrefixListState enum value + PrefixListStateModifyInProgress = "modify-in-progress" + + // PrefixListStateModifyComplete is a PrefixListState enum value + PrefixListStateModifyComplete = "modify-complete" + + // PrefixListStateModifyFailed is a PrefixListState enum value + PrefixListStateModifyFailed = "modify-failed" + + // PrefixListStateRestoreInProgress is a PrefixListState enum value + PrefixListStateRestoreInProgress = "restore-in-progress" + + // PrefixListStateRestoreComplete is a PrefixListState enum value + PrefixListStateRestoreComplete = "restore-complete" + + // PrefixListStateRestoreFailed is a PrefixListState enum value + PrefixListStateRestoreFailed = "restore-failed" + + // PrefixListStateDeleteInProgress is a PrefixListState enum value + PrefixListStateDeleteInProgress = "delete-in-progress" + + // PrefixListStateDeleteComplete is a PrefixListState enum value + PrefixListStateDeleteComplete = "delete-complete" + + // PrefixListStateDeleteFailed is a PrefixListState enum value + PrefixListStateDeleteFailed = "delete-failed" +) + +// PrefixListState_Values returns all elements of the PrefixListState enum +func PrefixListState_Values() []string { + return []string{ + PrefixListStateCreateInProgress, + PrefixListStateCreateComplete, + PrefixListStateCreateFailed, + PrefixListStateModifyInProgress, + PrefixListStateModifyComplete, + PrefixListStateModifyFailed, + PrefixListStateRestoreInProgress, + PrefixListStateRestoreComplete, + PrefixListStateRestoreFailed, + PrefixListStateDeleteInProgress, + PrefixListStateDeleteComplete, + PrefixListStateDeleteFailed, + } +} + const ( // PrincipalTypeAll is a PrincipalType enum value PrincipalTypeAll = "All" @@ -111721,6 +117124,18 @@ const ( PrincipalTypeRole = "Role" ) +// PrincipalType_Values returns all elements of the PrincipalType enum +func PrincipalType_Values() []string { + return []string{ + PrincipalTypeAll, + PrincipalTypeService, + PrincipalTypeOrganizationUnit, + PrincipalTypeAccount, + PrincipalTypeUser, + PrincipalTypeRole, + } +} + const ( // ProductCodeValuesDevpay is a ProductCodeValues enum value ProductCodeValuesDevpay = "devpay" @@ -111729,6 +117144,14 @@ const ( ProductCodeValuesMarketplace = "marketplace" ) +// ProductCodeValues_Values returns all elements of the ProductCodeValues enum +func ProductCodeValues_Values() []string { + return []string{ + ProductCodeValuesDevpay, + ProductCodeValuesMarketplace, + } +} + const ( // RIProductDescriptionLinuxUnix is a RIProductDescription enum value RIProductDescriptionLinuxUnix = "Linux/UNIX" @@ -111743,11 +117166,28 @@ const ( RIProductDescriptionWindowsAmazonVpc = "Windows (Amazon VPC)" ) +// RIProductDescription_Values returns all elements of the RIProductDescription enum +func RIProductDescription_Values() []string { + return []string{ + RIProductDescriptionLinuxUnix, + RIProductDescriptionLinuxUnixamazonVpc, + RIProductDescriptionWindows, + RIProductDescriptionWindowsAmazonVpc, + } +} + const ( // RecurringChargeFrequencyHourly is a RecurringChargeFrequency enum value RecurringChargeFrequencyHourly = "Hourly" ) +// RecurringChargeFrequency_Values returns all elements of the RecurringChargeFrequency enum +func RecurringChargeFrequency_Values() []string { + return []string{ + RecurringChargeFrequencyHourly, + } +} + const ( // ReportInstanceReasonCodesInstanceStuckInState is a ReportInstanceReasonCodes enum value ReportInstanceReasonCodesInstanceStuckInState = "instance-stuck-in-state" @@ -111777,6 +117217,21 @@ const ( ReportInstanceReasonCodesOther = "other" ) +// ReportInstanceReasonCodes_Values returns all elements of the ReportInstanceReasonCodes enum +func ReportInstanceReasonCodes_Values() []string { + return []string{ + ReportInstanceReasonCodesInstanceStuckInState, + ReportInstanceReasonCodesUnresponsive, + ReportInstanceReasonCodesNotAcceptingCredentials, + ReportInstanceReasonCodesPasswordNotAvailable, + ReportInstanceReasonCodesPerformanceNetwork, + ReportInstanceReasonCodesPerformanceInstanceStore, + ReportInstanceReasonCodesPerformanceEbsVolume, + ReportInstanceReasonCodesPerformanceOther, + ReportInstanceReasonCodesOther, + } +} + const ( // ReportStatusTypeOk is a ReportStatusType enum value ReportStatusTypeOk = "ok" @@ -111785,6 +117240,14 @@ const ( ReportStatusTypeImpaired = "impaired" ) +// ReportStatusType_Values returns all elements of the ReportStatusType enum +func ReportStatusType_Values() []string { + return []string{ + ReportStatusTypeOk, + ReportStatusTypeImpaired, + } +} + const ( // ReservationStatePaymentPending is a ReservationState enum value ReservationStatePaymentPending = "payment-pending" @@ -111799,6 +117262,16 @@ const ( ReservationStateRetired = "retired" ) +// ReservationState_Values returns all elements of the ReservationState enum +func ReservationState_Values() []string { + return []string{ + ReservationStatePaymentPending, + ReservationStatePaymentFailed, + ReservationStateActive, + ReservationStateRetired, + } +} + const ( // ReservedInstanceStatePaymentPending is a ReservedInstanceState enum value ReservedInstanceStatePaymentPending = "payment-pending" @@ -111819,16 +117292,42 @@ const ( ReservedInstanceStateQueuedDeleted = "queued-deleted" ) +// ReservedInstanceState_Values returns all elements of the ReservedInstanceState enum +func ReservedInstanceState_Values() []string { + return []string{ + ReservedInstanceStatePaymentPending, + ReservedInstanceStateActive, + ReservedInstanceStatePaymentFailed, + ReservedInstanceStateRetired, + ReservedInstanceStateQueued, + ReservedInstanceStateQueuedDeleted, + } +} + const ( // ResetFpgaImageAttributeNameLoadPermission is a ResetFpgaImageAttributeName enum value ResetFpgaImageAttributeNameLoadPermission = "loadPermission" ) +// ResetFpgaImageAttributeName_Values returns all elements of the ResetFpgaImageAttributeName enum +func ResetFpgaImageAttributeName_Values() []string { + return []string{ + ResetFpgaImageAttributeNameLoadPermission, + } +} + const ( // ResetImageAttributeNameLaunchPermission is a ResetImageAttributeName enum value ResetImageAttributeNameLaunchPermission = "launchPermission" ) +// ResetImageAttributeName_Values returns all elements of the ResetImageAttributeName enum +func ResetImageAttributeName_Values() []string { + return []string{ + ResetImageAttributeNameLaunchPermission, + } +} + const ( // ResourceTypeClientVpnEndpoint is a ResourceType enum value ResourceTypeClientVpnEndpoint = "client-vpn-endpoint" @@ -111845,6 +117344,15 @@ const ( // ResourceTypeElasticIp is a ResourceType enum value ResourceTypeElasticIp = "elastic-ip" + // ResourceTypeElasticGpu is a ResourceType enum value + ResourceTypeElasticGpu = "elastic-gpu" + + // ResourceTypeExportImageTask is a ResourceType enum value + ResourceTypeExportImageTask = "export-image-task" + + // ResourceTypeExportInstanceTask is a ResourceType enum value + ResourceTypeExportInstanceTask = "export-instance-task" + // ResourceTypeFleet is a ResourceType enum value ResourceTypeFleet = "fleet" @@ -111857,6 +117365,12 @@ const ( // ResourceTypeImage is a ResourceType enum value ResourceTypeImage = "image" + // ResourceTypeImportImageTask is a ResourceType enum value + ResourceTypeImportImageTask = "import-image-task" + + // ResourceTypeImportSnapshotTask is a ResourceType enum value + ResourceTypeImportSnapshotTask = "import-snapshot-task" + // ResourceTypeInstance is a ResourceType enum value ResourceTypeInstance = "instance" @@ -111869,6 +117383,9 @@ const ( // ResourceTypeLaunchTemplate is a ResourceType enum value ResourceTypeLaunchTemplate = "launch-template" + // ResourceTypeLocalGatewayRouteTableVpcAssociation is a ResourceType enum value + ResourceTypeLocalGatewayRouteTableVpcAssociation = "local-gateway-route-table-vpc-association" + // ResourceTypeNatgateway is a ResourceType enum value ResourceTypeNatgateway = "natgateway" @@ -111942,6 +117459,55 @@ const ( ResourceTypeVpcFlowLog = "vpc-flow-log" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeClientVpnEndpoint, + ResourceTypeCustomerGateway, + ResourceTypeDedicatedHost, + ResourceTypeDhcpOptions, + ResourceTypeElasticIp, + ResourceTypeElasticGpu, + ResourceTypeExportImageTask, + ResourceTypeExportInstanceTask, + ResourceTypeFleet, + ResourceTypeFpgaImage, + ResourceTypeHostReservation, + ResourceTypeImage, + ResourceTypeImportImageTask, + ResourceTypeImportSnapshotTask, + ResourceTypeInstance, + ResourceTypeInternetGateway, + ResourceTypeKeyPair, + ResourceTypeLaunchTemplate, + ResourceTypeLocalGatewayRouteTableVpcAssociation, + ResourceTypeNatgateway, + ResourceTypeNetworkAcl, + ResourceTypeNetworkInterface, + ResourceTypePlacementGroup, + ResourceTypeReservedInstances, + ResourceTypeRouteTable, + ResourceTypeSecurityGroup, + ResourceTypeSnapshot, + ResourceTypeSpotFleetRequest, + ResourceTypeSpotInstancesRequest, + ResourceTypeSubnet, + ResourceTypeTrafficMirrorFilter, + ResourceTypeTrafficMirrorSession, + ResourceTypeTrafficMirrorTarget, + ResourceTypeTransitGateway, + ResourceTypeTransitGatewayAttachment, + ResourceTypeTransitGatewayMulticastDomain, + ResourceTypeTransitGatewayRouteTable, + ResourceTypeVolume, + ResourceTypeVpc, + ResourceTypeVpcPeeringConnection, + ResourceTypeVpnConnection, + ResourceTypeVpnGateway, + ResourceTypeVpcFlowLog, + } +} + const ( // RootDeviceTypeEbs is a RootDeviceType enum value RootDeviceTypeEbs = "ebs" @@ -111950,6 +117516,14 @@ const ( RootDeviceTypeInstanceStore = "instance-store" ) +// RootDeviceType_Values returns all elements of the RootDeviceType enum +func RootDeviceType_Values() []string { + return []string{ + RootDeviceTypeEbs, + RootDeviceTypeInstanceStore, + } +} + const ( // RouteOriginCreateRouteTable is a RouteOrigin enum value RouteOriginCreateRouteTable = "CreateRouteTable" @@ -111961,6 +117535,15 @@ const ( RouteOriginEnableVgwRoutePropagation = "EnableVgwRoutePropagation" ) +// RouteOrigin_Values returns all elements of the RouteOrigin enum +func RouteOrigin_Values() []string { + return []string{ + RouteOriginCreateRouteTable, + RouteOriginCreateRoute, + RouteOriginEnableVgwRoutePropagation, + } +} + const ( // RouteStateActive is a RouteState enum value RouteStateActive = "active" @@ -111969,6 +117552,14 @@ const ( RouteStateBlackhole = "blackhole" ) +// RouteState_Values returns all elements of the RouteState enum +func RouteState_Values() []string { + return []string{ + RouteStateActive, + RouteStateBlackhole, + } +} + const ( // RouteTableAssociationStateCodeAssociating is a RouteTableAssociationStateCode enum value RouteTableAssociationStateCodeAssociating = "associating" @@ -111986,6 +117577,17 @@ const ( RouteTableAssociationStateCodeFailed = "failed" ) +// RouteTableAssociationStateCode_Values returns all elements of the RouteTableAssociationStateCode enum +func RouteTableAssociationStateCode_Values() []string { + return []string{ + RouteTableAssociationStateCodeAssociating, + RouteTableAssociationStateCodeAssociated, + RouteTableAssociationStateCodeDisassociating, + RouteTableAssociationStateCodeDisassociated, + RouteTableAssociationStateCodeFailed, + } +} + const ( // RuleActionAllow is a RuleAction enum value RuleActionAllow = "allow" @@ -111994,6 +117596,14 @@ const ( RuleActionDeny = "deny" ) +// RuleAction_Values returns all elements of the RuleAction enum +func RuleAction_Values() []string { + return []string{ + RuleActionAllow, + RuleActionDeny, + } +} + const ( // ScopeAvailabilityZone is a Scope enum value ScopeAvailabilityZone = "Availability Zone" @@ -112002,6 +117612,14 @@ const ( ScopeRegion = "Region" ) +// Scope_Values returns all elements of the Scope enum +func Scope_Values() []string { + return []string{ + ScopeAvailabilityZone, + ScopeRegion, + } +} + const ( // ServiceStatePending is a ServiceState enum value ServiceStatePending = "Pending" @@ -112019,6 +117637,17 @@ const ( ServiceStateFailed = "Failed" ) +// ServiceState_Values returns all elements of the ServiceState enum +func ServiceState_Values() []string { + return []string{ + ServiceStatePending, + ServiceStateAvailable, + ServiceStateDeleting, + ServiceStateDeleted, + ServiceStateFailed, + } +} + const ( // ServiceTypeInterface is a ServiceType enum value ServiceTypeInterface = "Interface" @@ -112027,6 +117656,14 @@ const ( ServiceTypeGateway = "Gateway" ) +// ServiceType_Values returns all elements of the ServiceType enum +func ServiceType_Values() []string { + return []string{ + ServiceTypeInterface, + ServiceTypeGateway, + } +} + const ( // ShutdownBehaviorStop is a ShutdownBehavior enum value ShutdownBehaviorStop = "stop" @@ -112035,6 +117672,14 @@ const ( ShutdownBehaviorTerminate = "terminate" ) +// ShutdownBehavior_Values returns all elements of the ShutdownBehavior enum +func ShutdownBehavior_Values() []string { + return []string{ + ShutdownBehaviorStop, + ShutdownBehaviorTerminate, + } +} + const ( // SnapshotAttributeNameProductCodes is a SnapshotAttributeName enum value SnapshotAttributeNameProductCodes = "productCodes" @@ -112043,6 +117688,14 @@ const ( SnapshotAttributeNameCreateVolumePermission = "createVolumePermission" ) +// SnapshotAttributeName_Values returns all elements of the SnapshotAttributeName enum +func SnapshotAttributeName_Values() []string { + return []string{ + SnapshotAttributeNameProductCodes, + SnapshotAttributeNameCreateVolumePermission, + } +} + const ( // SnapshotStatePending is a SnapshotState enum value SnapshotStatePending = "pending" @@ -112054,6 +117707,15 @@ const ( SnapshotStateError = "error" ) +// SnapshotState_Values returns all elements of the SnapshotState enum +func SnapshotState_Values() []string { + return []string{ + SnapshotStatePending, + SnapshotStateCompleted, + SnapshotStateError, + } +} + const ( // SpotAllocationStrategyLowestPrice is a SpotAllocationStrategy enum value SpotAllocationStrategyLowestPrice = "lowest-price" @@ -112065,6 +117727,15 @@ const ( SpotAllocationStrategyCapacityOptimized = "capacity-optimized" ) +// SpotAllocationStrategy_Values returns all elements of the SpotAllocationStrategy enum +func SpotAllocationStrategy_Values() []string { + return []string{ + SpotAllocationStrategyLowestPrice, + SpotAllocationStrategyDiversified, + SpotAllocationStrategyCapacityOptimized, + } +} + const ( // SpotInstanceInterruptionBehaviorHibernate is a SpotInstanceInterruptionBehavior enum value SpotInstanceInterruptionBehaviorHibernate = "hibernate" @@ -112076,6 +117747,15 @@ const ( SpotInstanceInterruptionBehaviorTerminate = "terminate" ) +// SpotInstanceInterruptionBehavior_Values returns all elements of the SpotInstanceInterruptionBehavior enum +func SpotInstanceInterruptionBehavior_Values() []string { + return []string{ + SpotInstanceInterruptionBehaviorHibernate, + SpotInstanceInterruptionBehaviorStop, + SpotInstanceInterruptionBehaviorTerminate, + } +} + const ( // SpotInstanceStateOpen is a SpotInstanceState enum value SpotInstanceStateOpen = "open" @@ -112093,6 +117773,17 @@ const ( SpotInstanceStateFailed = "failed" ) +// SpotInstanceState_Values returns all elements of the SpotInstanceState enum +func SpotInstanceState_Values() []string { + return []string{ + SpotInstanceStateOpen, + SpotInstanceStateActive, + SpotInstanceStateClosed, + SpotInstanceStateCancelled, + SpotInstanceStateFailed, + } +} + const ( // SpotInstanceTypeOneTime is a SpotInstanceType enum value SpotInstanceTypeOneTime = "one-time" @@ -112101,6 +117792,14 @@ const ( SpotInstanceTypePersistent = "persistent" ) +// SpotInstanceType_Values returns all elements of the SpotInstanceType enum +func SpotInstanceType_Values() []string { + return []string{ + SpotInstanceTypeOneTime, + SpotInstanceTypePersistent, + } +} + const ( // StatePendingAcceptance is a State enum value StatePendingAcceptance = "PendingAcceptance" @@ -112127,6 +117826,20 @@ const ( StateExpired = "Expired" ) +// State_Values returns all elements of the State enum +func State_Values() []string { + return []string{ + StatePendingAcceptance, + StatePending, + StateAvailable, + StateDeleting, + StateDeleted, + StateRejected, + StateFailed, + StateExpired, + } +} + const ( // StatusMoveInProgress is a Status enum value StatusMoveInProgress = "MoveInProgress" @@ -112138,11 +117851,27 @@ const ( StatusInClassic = "InClassic" ) +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusMoveInProgress, + StatusInVpc, + StatusInClassic, + } +} + const ( // StatusNameReachability is a StatusName enum value StatusNameReachability = "reachability" ) +// StatusName_Values returns all elements of the StatusName enum +func StatusName_Values() []string { + return []string{ + StatusNameReachability, + } +} + const ( // StatusTypePassed is a StatusType enum value StatusTypePassed = "passed" @@ -112157,6 +117886,16 @@ const ( StatusTypeInitializing = "initializing" ) +// StatusType_Values returns all elements of the StatusType enum +func StatusType_Values() []string { + return []string{ + StatusTypePassed, + StatusTypeFailed, + StatusTypeInsufficientData, + StatusTypeInitializing, + } +} + const ( // SubnetCidrBlockStateCodeAssociating is a SubnetCidrBlockStateCode enum value SubnetCidrBlockStateCodeAssociating = "associating" @@ -112177,6 +117916,18 @@ const ( SubnetCidrBlockStateCodeFailed = "failed" ) +// SubnetCidrBlockStateCode_Values returns all elements of the SubnetCidrBlockStateCode enum +func SubnetCidrBlockStateCode_Values() []string { + return []string{ + SubnetCidrBlockStateCodeAssociating, + SubnetCidrBlockStateCodeAssociated, + SubnetCidrBlockStateCodeDisassociating, + SubnetCidrBlockStateCodeDisassociated, + SubnetCidrBlockStateCodeFailing, + SubnetCidrBlockStateCodeFailed, + } +} + const ( // SubnetStatePending is a SubnetState enum value SubnetStatePending = "pending" @@ -112185,6 +117936,14 @@ const ( SubnetStateAvailable = "available" ) +// SubnetState_Values returns all elements of the SubnetState enum +func SubnetState_Values() []string { + return []string{ + SubnetStatePending, + SubnetStateAvailable, + } +} + const ( // SummaryStatusOk is a SummaryStatus enum value SummaryStatusOk = "ok" @@ -112202,6 +117961,17 @@ const ( SummaryStatusInitializing = "initializing" ) +// SummaryStatus_Values returns all elements of the SummaryStatus enum +func SummaryStatus_Values() []string { + return []string{ + SummaryStatusOk, + SummaryStatusImpaired, + SummaryStatusInsufficientData, + SummaryStatusNotApplicable, + SummaryStatusInitializing, + } +} + const ( // TelemetryStatusUp is a TelemetryStatus enum value TelemetryStatusUp = "UP" @@ -112210,6 +117980,14 @@ const ( TelemetryStatusDown = "DOWN" ) +// TelemetryStatus_Values returns all elements of the TelemetryStatus enum +func TelemetryStatus_Values() []string { + return []string{ + TelemetryStatusUp, + TelemetryStatusDown, + } +} + const ( // TenancyDefault is a Tenancy enum value TenancyDefault = "default" @@ -112221,6 +117999,15 @@ const ( TenancyHost = "host" ) +// Tenancy_Values returns all elements of the Tenancy enum +func Tenancy_Values() []string { + return []string{ + TenancyDefault, + TenancyDedicated, + TenancyHost, + } +} + const ( // TrafficDirectionIngress is a TrafficDirection enum value TrafficDirectionIngress = "ingress" @@ -112229,6 +118016,14 @@ const ( TrafficDirectionEgress = "egress" ) +// TrafficDirection_Values returns all elements of the TrafficDirection enum +func TrafficDirection_Values() []string { + return []string{ + TrafficDirectionIngress, + TrafficDirectionEgress, + } +} + const ( // TrafficMirrorFilterRuleFieldDestinationPortRange is a TrafficMirrorFilterRuleField enum value TrafficMirrorFilterRuleFieldDestinationPortRange = "destination-port-range" @@ -112243,11 +118038,28 @@ const ( TrafficMirrorFilterRuleFieldDescription = "description" ) +// TrafficMirrorFilterRuleField_Values returns all elements of the TrafficMirrorFilterRuleField enum +func TrafficMirrorFilterRuleField_Values() []string { + return []string{ + TrafficMirrorFilterRuleFieldDestinationPortRange, + TrafficMirrorFilterRuleFieldSourcePortRange, + TrafficMirrorFilterRuleFieldProtocol, + TrafficMirrorFilterRuleFieldDescription, + } +} + const ( // TrafficMirrorNetworkServiceAmazonDns is a TrafficMirrorNetworkService enum value TrafficMirrorNetworkServiceAmazonDns = "amazon-dns" ) +// TrafficMirrorNetworkService_Values returns all elements of the TrafficMirrorNetworkService enum +func TrafficMirrorNetworkService_Values() []string { + return []string{ + TrafficMirrorNetworkServiceAmazonDns, + } +} + const ( // TrafficMirrorRuleActionAccept is a TrafficMirrorRuleAction enum value TrafficMirrorRuleActionAccept = "accept" @@ -112256,6 +118068,14 @@ const ( TrafficMirrorRuleActionReject = "reject" ) +// TrafficMirrorRuleAction_Values returns all elements of the TrafficMirrorRuleAction enum +func TrafficMirrorRuleAction_Values() []string { + return []string{ + TrafficMirrorRuleActionAccept, + TrafficMirrorRuleActionReject, + } +} + const ( // TrafficMirrorSessionFieldPacketLength is a TrafficMirrorSessionField enum value TrafficMirrorSessionFieldPacketLength = "packet-length" @@ -112267,6 +118087,15 @@ const ( TrafficMirrorSessionFieldVirtualNetworkId = "virtual-network-id" ) +// TrafficMirrorSessionField_Values returns all elements of the TrafficMirrorSessionField enum +func TrafficMirrorSessionField_Values() []string { + return []string{ + TrafficMirrorSessionFieldPacketLength, + TrafficMirrorSessionFieldDescription, + TrafficMirrorSessionFieldVirtualNetworkId, + } +} + const ( // TrafficMirrorTargetTypeNetworkInterface is a TrafficMirrorTargetType enum value TrafficMirrorTargetTypeNetworkInterface = "network-interface" @@ -112275,6 +118104,14 @@ const ( TrafficMirrorTargetTypeNetworkLoadBalancer = "network-load-balancer" ) +// TrafficMirrorTargetType_Values returns all elements of the TrafficMirrorTargetType enum +func TrafficMirrorTargetType_Values() []string { + return []string{ + TrafficMirrorTargetTypeNetworkInterface, + TrafficMirrorTargetTypeNetworkLoadBalancer, + } +} + const ( // TrafficTypeAccept is a TrafficType enum value TrafficTypeAccept = "ACCEPT" @@ -112286,6 +118123,15 @@ const ( TrafficTypeAll = "ALL" ) +// TrafficType_Values returns all elements of the TrafficType enum +func TrafficType_Values() []string { + return []string{ + TrafficTypeAccept, + TrafficTypeReject, + TrafficTypeAll, + } +} + const ( // TransitGatewayAssociationStateAssociating is a TransitGatewayAssociationState enum value TransitGatewayAssociationStateAssociating = "associating" @@ -112300,6 +118146,16 @@ const ( TransitGatewayAssociationStateDisassociated = "disassociated" ) +// TransitGatewayAssociationState_Values returns all elements of the TransitGatewayAssociationState enum +func TransitGatewayAssociationState_Values() []string { + return []string{ + TransitGatewayAssociationStateAssociating, + TransitGatewayAssociationStateAssociated, + TransitGatewayAssociationStateDisassociating, + TransitGatewayAssociationStateDisassociated, + } +} + const ( // TransitGatewayAttachmentResourceTypeVpc is a TransitGatewayAttachmentResourceType enum value TransitGatewayAttachmentResourceTypeVpc = "vpc" @@ -112314,6 +118170,16 @@ const ( TransitGatewayAttachmentResourceTypeTgwPeering = "tgw-peering" ) +// TransitGatewayAttachmentResourceType_Values returns all elements of the TransitGatewayAttachmentResourceType enum +func TransitGatewayAttachmentResourceType_Values() []string { + return []string{ + TransitGatewayAttachmentResourceTypeVpc, + TransitGatewayAttachmentResourceTypeVpn, + TransitGatewayAttachmentResourceTypeDirectConnectGateway, + TransitGatewayAttachmentResourceTypeTgwPeering, + } +} + const ( // TransitGatewayAttachmentStateInitiating is a TransitGatewayAttachmentState enum value TransitGatewayAttachmentStateInitiating = "initiating" @@ -112352,6 +118218,24 @@ const ( TransitGatewayAttachmentStateFailing = "failing" ) +// TransitGatewayAttachmentState_Values returns all elements of the TransitGatewayAttachmentState enum +func TransitGatewayAttachmentState_Values() []string { + return []string{ + TransitGatewayAttachmentStateInitiating, + TransitGatewayAttachmentStatePendingAcceptance, + TransitGatewayAttachmentStateRollingBack, + TransitGatewayAttachmentStatePending, + TransitGatewayAttachmentStateAvailable, + TransitGatewayAttachmentStateModifying, + TransitGatewayAttachmentStateDeleting, + TransitGatewayAttachmentStateDeleted, + TransitGatewayAttachmentStateFailed, + TransitGatewayAttachmentStateRejected, + TransitGatewayAttachmentStateRejecting, + TransitGatewayAttachmentStateFailing, + } +} + const ( // TransitGatewayMulitcastDomainAssociationStateAssociating is a TransitGatewayMulitcastDomainAssociationState enum value TransitGatewayMulitcastDomainAssociationStateAssociating = "associating" @@ -112366,6 +118250,16 @@ const ( TransitGatewayMulitcastDomainAssociationStateDisassociated = "disassociated" ) +// TransitGatewayMulitcastDomainAssociationState_Values returns all elements of the TransitGatewayMulitcastDomainAssociationState enum +func TransitGatewayMulitcastDomainAssociationState_Values() []string { + return []string{ + TransitGatewayMulitcastDomainAssociationStateAssociating, + TransitGatewayMulitcastDomainAssociationStateAssociated, + TransitGatewayMulitcastDomainAssociationStateDisassociating, + TransitGatewayMulitcastDomainAssociationStateDisassociated, + } +} + const ( // TransitGatewayMulticastDomainStatePending is a TransitGatewayMulticastDomainState enum value TransitGatewayMulticastDomainStatePending = "pending" @@ -112380,6 +118274,16 @@ const ( TransitGatewayMulticastDomainStateDeleted = "deleted" ) +// TransitGatewayMulticastDomainState_Values returns all elements of the TransitGatewayMulticastDomainState enum +func TransitGatewayMulticastDomainState_Values() []string { + return []string{ + TransitGatewayMulticastDomainStatePending, + TransitGatewayMulticastDomainStateAvailable, + TransitGatewayMulticastDomainStateDeleting, + TransitGatewayMulticastDomainStateDeleted, + } +} + const ( // TransitGatewayPropagationStateEnabling is a TransitGatewayPropagationState enum value TransitGatewayPropagationStateEnabling = "enabling" @@ -112394,6 +118298,16 @@ const ( TransitGatewayPropagationStateDisabled = "disabled" ) +// TransitGatewayPropagationState_Values returns all elements of the TransitGatewayPropagationState enum +func TransitGatewayPropagationState_Values() []string { + return []string{ + TransitGatewayPropagationStateEnabling, + TransitGatewayPropagationStateEnabled, + TransitGatewayPropagationStateDisabling, + TransitGatewayPropagationStateDisabled, + } +} + const ( // TransitGatewayRouteStatePending is a TransitGatewayRouteState enum value TransitGatewayRouteStatePending = "pending" @@ -112411,6 +118325,17 @@ const ( TransitGatewayRouteStateDeleted = "deleted" ) +// TransitGatewayRouteState_Values returns all elements of the TransitGatewayRouteState enum +func TransitGatewayRouteState_Values() []string { + return []string{ + TransitGatewayRouteStatePending, + TransitGatewayRouteStateActive, + TransitGatewayRouteStateBlackhole, + TransitGatewayRouteStateDeleting, + TransitGatewayRouteStateDeleted, + } +} + const ( // TransitGatewayRouteTableStatePending is a TransitGatewayRouteTableState enum value TransitGatewayRouteTableStatePending = "pending" @@ -112425,6 +118350,16 @@ const ( TransitGatewayRouteTableStateDeleted = "deleted" ) +// TransitGatewayRouteTableState_Values returns all elements of the TransitGatewayRouteTableState enum +func TransitGatewayRouteTableState_Values() []string { + return []string{ + TransitGatewayRouteTableStatePending, + TransitGatewayRouteTableStateAvailable, + TransitGatewayRouteTableStateDeleting, + TransitGatewayRouteTableStateDeleted, + } +} + const ( // TransitGatewayRouteTypeStatic is a TransitGatewayRouteType enum value TransitGatewayRouteTypeStatic = "static" @@ -112433,6 +118368,14 @@ const ( TransitGatewayRouteTypePropagated = "propagated" ) +// TransitGatewayRouteType_Values returns all elements of the TransitGatewayRouteType enum +func TransitGatewayRouteType_Values() []string { + return []string{ + TransitGatewayRouteTypeStatic, + TransitGatewayRouteTypePropagated, + } +} + const ( // TransitGatewayStatePending is a TransitGatewayState enum value TransitGatewayStatePending = "pending" @@ -112450,6 +118393,17 @@ const ( TransitGatewayStateDeleted = "deleted" ) +// TransitGatewayState_Values returns all elements of the TransitGatewayState enum +func TransitGatewayState_Values() []string { + return []string{ + TransitGatewayStatePending, + TransitGatewayStateAvailable, + TransitGatewayStateModifying, + TransitGatewayStateDeleting, + TransitGatewayStateDeleted, + } +} + const ( // TransportProtocolTcp is a TransportProtocol enum value TransportProtocolTcp = "tcp" @@ -112458,6 +118412,30 @@ const ( TransportProtocolUdp = "udp" ) +// TransportProtocol_Values returns all elements of the TransportProtocol enum +func TransportProtocol_Values() []string { + return []string{ + TransportProtocolTcp, + TransportProtocolUdp, + } +} + +const ( + // TunnelInsideIpVersionIpv4 is a TunnelInsideIpVersion enum value + TunnelInsideIpVersionIpv4 = "ipv4" + + // TunnelInsideIpVersionIpv6 is a TunnelInsideIpVersion enum value + TunnelInsideIpVersionIpv6 = "ipv6" +) + +// TunnelInsideIpVersion_Values returns all elements of the TunnelInsideIpVersion enum +func TunnelInsideIpVersion_Values() []string { + return []string{ + TunnelInsideIpVersionIpv4, + TunnelInsideIpVersionIpv6, + } +} + const ( // UnlimitedSupportedInstanceFamilyT2 is a UnlimitedSupportedInstanceFamily enum value UnlimitedSupportedInstanceFamilyT2 = "t2" @@ -112469,6 +118447,15 @@ const ( UnlimitedSupportedInstanceFamilyT3a = "t3a" ) +// UnlimitedSupportedInstanceFamily_Values returns all elements of the UnlimitedSupportedInstanceFamily enum +func UnlimitedSupportedInstanceFamily_Values() []string { + return []string{ + UnlimitedSupportedInstanceFamilyT2, + UnlimitedSupportedInstanceFamilyT3, + UnlimitedSupportedInstanceFamilyT3a, + } +} + const ( // UnsuccessfulInstanceCreditSpecificationErrorCodeInvalidInstanceIdMalformed is a UnsuccessfulInstanceCreditSpecificationErrorCode enum value UnsuccessfulInstanceCreditSpecificationErrorCodeInvalidInstanceIdMalformed = "InvalidInstanceID.Malformed" @@ -112483,6 +118470,16 @@ const ( UnsuccessfulInstanceCreditSpecificationErrorCodeInstanceCreditSpecificationNotSupported = "InstanceCreditSpecification.NotSupported" ) +// UnsuccessfulInstanceCreditSpecificationErrorCode_Values returns all elements of the UnsuccessfulInstanceCreditSpecificationErrorCode enum +func UnsuccessfulInstanceCreditSpecificationErrorCode_Values() []string { + return []string{ + UnsuccessfulInstanceCreditSpecificationErrorCodeInvalidInstanceIdMalformed, + UnsuccessfulInstanceCreditSpecificationErrorCodeInvalidInstanceIdNotFound, + UnsuccessfulInstanceCreditSpecificationErrorCodeIncorrectInstanceState, + UnsuccessfulInstanceCreditSpecificationErrorCodeInstanceCreditSpecificationNotSupported, + } +} + const ( // UsageClassTypeSpot is a UsageClassType enum value UsageClassTypeSpot = "spot" @@ -112491,6 +118488,14 @@ const ( UsageClassTypeOnDemand = "on-demand" ) +// UsageClassType_Values returns all elements of the UsageClassType enum +func UsageClassType_Values() []string { + return []string{ + UsageClassTypeSpot, + UsageClassTypeOnDemand, + } +} + const ( // VirtualizationTypeHvm is a VirtualizationType enum value VirtualizationTypeHvm = "hvm" @@ -112499,6 +118504,14 @@ const ( VirtualizationTypeParavirtual = "paravirtual" ) +// VirtualizationType_Values returns all elements of the VirtualizationType enum +func VirtualizationType_Values() []string { + return []string{ + VirtualizationTypeHvm, + VirtualizationTypeParavirtual, + } +} + const ( // VolumeAttachmentStateAttaching is a VolumeAttachmentState enum value VolumeAttachmentStateAttaching = "attaching" @@ -112516,6 +118529,17 @@ const ( VolumeAttachmentStateBusy = "busy" ) +// VolumeAttachmentState_Values returns all elements of the VolumeAttachmentState enum +func VolumeAttachmentState_Values() []string { + return []string{ + VolumeAttachmentStateAttaching, + VolumeAttachmentStateAttached, + VolumeAttachmentStateDetaching, + VolumeAttachmentStateDetached, + VolumeAttachmentStateBusy, + } +} + const ( // VolumeAttributeNameAutoEnableIo is a VolumeAttributeName enum value VolumeAttributeNameAutoEnableIo = "autoEnableIO" @@ -112524,6 +118548,14 @@ const ( VolumeAttributeNameProductCodes = "productCodes" ) +// VolumeAttributeName_Values returns all elements of the VolumeAttributeName enum +func VolumeAttributeName_Values() []string { + return []string{ + VolumeAttributeNameAutoEnableIo, + VolumeAttributeNameProductCodes, + } +} + const ( // VolumeModificationStateModifying is a VolumeModificationState enum value VolumeModificationStateModifying = "modifying" @@ -112538,6 +118570,16 @@ const ( VolumeModificationStateFailed = "failed" ) +// VolumeModificationState_Values returns all elements of the VolumeModificationState enum +func VolumeModificationState_Values() []string { + return []string{ + VolumeModificationStateModifying, + VolumeModificationStateOptimizing, + VolumeModificationStateCompleted, + VolumeModificationStateFailed, + } +} + const ( // VolumeStateCreating is a VolumeState enum value VolumeStateCreating = "creating" @@ -112558,6 +118600,18 @@ const ( VolumeStateError = "error" ) +// VolumeState_Values returns all elements of the VolumeState enum +func VolumeState_Values() []string { + return []string{ + VolumeStateCreating, + VolumeStateAvailable, + VolumeStateInUse, + VolumeStateDeleting, + VolumeStateDeleted, + VolumeStateError, + } +} + const ( // VolumeStatusInfoStatusOk is a VolumeStatusInfoStatus enum value VolumeStatusInfoStatusOk = "ok" @@ -112569,6 +118623,15 @@ const ( VolumeStatusInfoStatusInsufficientData = "insufficient-data" ) +// VolumeStatusInfoStatus_Values returns all elements of the VolumeStatusInfoStatus enum +func VolumeStatusInfoStatus_Values() []string { + return []string{ + VolumeStatusInfoStatusOk, + VolumeStatusInfoStatusImpaired, + VolumeStatusInfoStatusInsufficientData, + } +} + const ( // VolumeStatusNameIoEnabled is a VolumeStatusName enum value VolumeStatusNameIoEnabled = "io-enabled" @@ -112577,6 +118640,14 @@ const ( VolumeStatusNameIoPerformance = "io-performance" ) +// VolumeStatusName_Values returns all elements of the VolumeStatusName enum +func VolumeStatusName_Values() []string { + return []string{ + VolumeStatusNameIoEnabled, + VolumeStatusNameIoPerformance, + } +} + const ( // VolumeTypeStandard is a VolumeType enum value VolumeTypeStandard = "standard" @@ -112594,6 +118665,17 @@ const ( VolumeTypeSt1 = "st1" ) +// VolumeType_Values returns all elements of the VolumeType enum +func VolumeType_Values() []string { + return []string{ + VolumeTypeStandard, + VolumeTypeIo1, + VolumeTypeGp2, + VolumeTypeSc1, + VolumeTypeSt1, + } +} + const ( // VpcAttributeNameEnableDnsSupport is a VpcAttributeName enum value VpcAttributeNameEnableDnsSupport = "enableDnsSupport" @@ -112602,6 +118684,14 @@ const ( VpcAttributeNameEnableDnsHostnames = "enableDnsHostnames" ) +// VpcAttributeName_Values returns all elements of the VpcAttributeName enum +func VpcAttributeName_Values() []string { + return []string{ + VpcAttributeNameEnableDnsSupport, + VpcAttributeNameEnableDnsHostnames, + } +} + const ( // VpcCidrBlockStateCodeAssociating is a VpcCidrBlockStateCode enum value VpcCidrBlockStateCodeAssociating = "associating" @@ -112622,6 +118712,18 @@ const ( VpcCidrBlockStateCodeFailed = "failed" ) +// VpcCidrBlockStateCode_Values returns all elements of the VpcCidrBlockStateCode enum +func VpcCidrBlockStateCode_Values() []string { + return []string{ + VpcCidrBlockStateCodeAssociating, + VpcCidrBlockStateCodeAssociated, + VpcCidrBlockStateCodeDisassociating, + VpcCidrBlockStateCodeDisassociated, + VpcCidrBlockStateCodeFailing, + VpcCidrBlockStateCodeFailed, + } +} + const ( // VpcEndpointTypeInterface is a VpcEndpointType enum value VpcEndpointTypeInterface = "Interface" @@ -112630,6 +118732,14 @@ const ( VpcEndpointTypeGateway = "Gateway" ) +// VpcEndpointType_Values returns all elements of the VpcEndpointType enum +func VpcEndpointType_Values() []string { + return []string{ + VpcEndpointTypeInterface, + VpcEndpointTypeGateway, + } +} + const ( // VpcPeeringConnectionStateReasonCodeInitiatingRequest is a VpcPeeringConnectionStateReasonCode enum value VpcPeeringConnectionStateReasonCodeInitiatingRequest = "initiating-request" @@ -112659,6 +118769,21 @@ const ( VpcPeeringConnectionStateReasonCodeDeleting = "deleting" ) +// VpcPeeringConnectionStateReasonCode_Values returns all elements of the VpcPeeringConnectionStateReasonCode enum +func VpcPeeringConnectionStateReasonCode_Values() []string { + return []string{ + VpcPeeringConnectionStateReasonCodeInitiatingRequest, + VpcPeeringConnectionStateReasonCodePendingAcceptance, + VpcPeeringConnectionStateReasonCodeActive, + VpcPeeringConnectionStateReasonCodeDeleted, + VpcPeeringConnectionStateReasonCodeRejected, + VpcPeeringConnectionStateReasonCodeFailed, + VpcPeeringConnectionStateReasonCodeExpired, + VpcPeeringConnectionStateReasonCodeProvisioning, + VpcPeeringConnectionStateReasonCodeDeleting, + } +} + const ( // VpcStatePending is a VpcState enum value VpcStatePending = "pending" @@ -112667,11 +118792,26 @@ const ( VpcStateAvailable = "available" ) +// VpcState_Values returns all elements of the VpcState enum +func VpcState_Values() []string { + return []string{ + VpcStatePending, + VpcStateAvailable, + } +} + const ( // VpcTenancyDefault is a VpcTenancy enum value VpcTenancyDefault = "default" ) +// VpcTenancy_Values returns all elements of the VpcTenancy enum +func VpcTenancy_Values() []string { + return []string{ + VpcTenancyDefault, + } +} + const ( // VpnEcmpSupportValueEnable is a VpnEcmpSupportValue enum value VpnEcmpSupportValueEnable = "enable" @@ -112680,11 +118820,26 @@ const ( VpnEcmpSupportValueDisable = "disable" ) +// VpnEcmpSupportValue_Values returns all elements of the VpnEcmpSupportValue enum +func VpnEcmpSupportValue_Values() []string { + return []string{ + VpnEcmpSupportValueEnable, + VpnEcmpSupportValueDisable, + } +} + const ( // VpnProtocolOpenvpn is a VpnProtocol enum value VpnProtocolOpenvpn = "openvpn" ) +// VpnProtocol_Values returns all elements of the VpnProtocol enum +func VpnProtocol_Values() []string { + return []string{ + VpnProtocolOpenvpn, + } +} + const ( // VpnStatePending is a VpnState enum value VpnStatePending = "pending" @@ -112699,7 +118854,24 @@ const ( VpnStateDeleted = "deleted" ) +// VpnState_Values returns all elements of the VpnState enum +func VpnState_Values() []string { + return []string{ + VpnStatePending, + VpnStateAvailable, + VpnStateDeleting, + VpnStateDeleted, + } +} + const ( // VpnStaticRouteSourceStatic is a VpnStaticRouteSource enum value VpnStaticRouteSourceStatic = "Static" ) + +// VpnStaticRouteSource_Values returns all elements of the VpnStaticRouteSource enum +func VpnStaticRouteSource_Values() []string { + return []string{ + VpnStaticRouteSourceStatic, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go index efec8d8a94e..3ad30591894 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go @@ -26,8 +26,12 @@ func init() { // only set the retryer on request if config doesn't have a retryer if r.Config.Retryer == nil && (r.Operation.Name == opModifyNetworkInterfaceAttribute || r.Operation.Name == opAssignPrivateIpAddresses) { + maxRetries := client.DefaultRetryerMaxNumRetries + if m := r.Config.MaxRetries; m != nil && *m != aws.UseServiceDefaultRetries { + maxRetries = *m + } r.Retryer = client.DefaultRetryer{ - NumMaxRetries: client.DefaultRetryerMaxNumRetries, + NumMaxRetries: maxRetries, MinRetryDelay: customRetryerMinRetryDelay, MinThrottleDelay: customRetryerMinRetryDelay, MaxRetryDelay: customRetryerMaxRetryDelay, diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecr/api.go b/vendor/github.com/aws/aws-sdk-go/service/ecr/api.go index 91e36f08d1c..990eae4ec29 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 @@ -369,7 +369,7 @@ func (c *ECR) CompleteLayerUploadRequest(input *CompleteLayerUploadInput) (req * // repository and ensure that you are performing operations on the correct registry. // // * UploadNotFoundException -// The upload could not be found, or the specified upload id is not valid for +// The upload could not be found, or the specified upload ID is not valid for // this repository. // // * InvalidLayerException @@ -385,6 +385,9 @@ func (c *ECR) CompleteLayerUploadRequest(input *CompleteLayerUploadInput) (req * // * EmptyUploadException // The specified layer upload does not contain any layer parts. // +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/CompleteLayerUpload func (c *ECR) CompleteLayerUpload(input *CompleteLayerUploadInput) (*CompleteLayerUploadOutput, error) { req, out := c.CompleteLayerUploadRequest(input) @@ -483,10 +486,12 @@ func (c *ECR) CreateRepositoryRequest(input *CreateRepositoryInput) (req *reques // // * LimitExceededException // The operation did not succeed because it would have exceeded a service limit -// for your account. For more information, see Amazon ECR Default Service Limits -// (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service_limits.html) +// for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // in the Amazon Elastic Container Registry User Guide. // +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/CreateRepository func (c *ECR) CreateRepository(input *CreateRepositoryInput) (*CreateRepositoryOutput, error) { req, out := c.CreateRepositoryRequest(input) @@ -670,6 +675,9 @@ func (c *ECR) DeleteRepositoryRequest(input *DeleteRepositoryInput) (req *reques // The specified repository contains images. To delete a repository that contains // images, you must force the deletion with the force parameter. // +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/DeleteRepository func (c *ECR) DeleteRepository(input *DeleteRepositoryInput) (*DeleteRepositoryOutput, error) { req, out := c.DeleteRepositoryRequest(input) @@ -1831,6 +1839,9 @@ func (c *ECR) InitiateLayerUploadRequest(input *InitiateLayerUploadInput) (req * // The specified repository could not be found. Check the spelling of the specified // repository and ensure that you are performing operations on the correct registry. // +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/InitiateLayerUpload func (c *ECR) InitiateLayerUpload(input *InitiateLayerUploadInput) (*InitiateLayerUploadOutput, error) { req, out := c.InitiateLayerUploadRequest(input) @@ -2178,14 +2189,20 @@ func (c *ECR) PutImageRequest(input *PutImageInput) (req *request.Request, outpu // // * LimitExceededException // The operation did not succeed because it would have exceeded a service limit -// for your account. For more information, see Amazon ECR Default Service Limits -// (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service_limits.html) +// for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // in the Amazon Elastic Container Registry User Guide. // // * ImageTagAlreadyExistsException // The specified image is tagged with a tag that already exists. The repository // is configured for tag immutability. // +// * ImageDigestDoesNotMatchException +// The specified image digest does not match the digest that Amazon ECR calculated +// for the image. +// +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/PutImage func (c *ECR) PutImage(input *PutImageInput) (*PutImageOutput, error) { req, out := c.PutImageRequest(input) @@ -2517,7 +2534,7 @@ func (c *ECR) SetRepositoryPolicyRequest(input *SetRepositoryPolicyInput) (req * // SetRepositoryPolicy API operation for Amazon EC2 Container Registry. // // Applies a repository policy to the specified repository to control access -// permissions. For more information, see Amazon ECR Repository Policies (https://docs.aws.amazon.com/AmazonECR/latest/userguide/RepositoryPolicies.html) +// permissions. For more information, see Amazon ECR Repository Policies (https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policies.html) // in the Amazon Elastic Container Registry User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -2630,8 +2647,7 @@ func (c *ECR) StartImageScanRequest(input *StartImageScanInput) (req *request.Re // // * LimitExceededException // The operation did not succeed because it would have exceeded a service limit -// for your account. For more information, see Amazon ECR Default Service Limits -// (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service_limits.html) +// for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // in the Amazon Elastic Container Registry User Guide. // // * RepositoryNotFoundException @@ -2734,8 +2750,8 @@ func (c *ECR) StartLifecyclePolicyPreviewRequest(input *StartLifecyclePolicyPrev // The lifecycle policy could not be found, and no policy is set to the repository. // // * LifecyclePolicyPreviewInProgressException -// The previous lifecycle policy preview request has not completed. Please try -// again later. +// The previous lifecycle policy preview request has not completed. Wait and +// try again. // // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/StartLifecyclePolicyPreview func (c *ECR) StartLifecyclePolicyPreview(input *StartLifecyclePolicyPreviewInput) (*StartLifecyclePolicyPreviewOutput, error) { @@ -3032,15 +3048,17 @@ func (c *ECR) UploadLayerPartRequest(input *UploadLayerPartInput) (req *request. // repository and ensure that you are performing operations on the correct registry. // // * UploadNotFoundException -// The upload could not be found, or the specified upload id is not valid for +// The upload could not be found, or the specified upload ID is not valid for // this repository. // // * LimitExceededException // The operation did not succeed because it would have exceeded a service limit -// for your account. For more information, see Amazon ECR Default Service Limits -// (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service_limits.html) +// for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // in the Amazon Elastic Container Registry User Guide. // +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/UploadLayerPart func (c *ECR) UploadLayerPart(input *UploadLayerPartInput) (*UploadLayerPartOutput, error) { req, out := c.UploadLayerPartRequest(input) @@ -3621,9 +3639,12 @@ func (s *CompleteLayerUploadOutput) SetUploadId(v string) *CompleteLayerUploadOu type CreateRepositoryInput struct { _ struct{} `type:"structure"` - // The image scanning configuration for the repository. This setting determines - // whether images are scanned for known vulnerabilities after being pushed to - // the repository. + // The encryption configuration for the repository. This determines how the + // contents of your repository are encrypted at rest. + EncryptionConfiguration *EncryptionConfiguration `locationName:"encryptionConfiguration" type:"structure"` + + // The image scanning configuration for the repository. This determines whether + // images are scanned for known vulnerabilities after being pushed to the repository. ImageScanningConfiguration *ImageScanningConfiguration `locationName:"imageScanningConfiguration" type:"structure"` // The tag mutability setting for the repository. If this parameter is omitted, @@ -3665,6 +3686,11 @@ func (s *CreateRepositoryInput) Validate() error { if s.RepositoryName != nil && len(*s.RepositoryName) < 2 { invalidParams.Add(request.NewErrParamMinLen("RepositoryName", 2)) } + if s.EncryptionConfiguration != nil { + if err := s.EncryptionConfiguration.Validate(); err != nil { + invalidParams.AddNested("EncryptionConfiguration", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -3672,6 +3698,12 @@ func (s *CreateRepositoryInput) Validate() error { return nil } +// SetEncryptionConfiguration sets the EncryptionConfiguration field's value. +func (s *CreateRepositoryInput) SetEncryptionConfiguration(v *EncryptionConfiguration) *CreateRepositoryInput { + s.EncryptionConfiguration = v + return s +} + // SetImageScanningConfiguration sets the ImageScanningConfiguration field's value. func (s *CreateRepositoryInput) SetImageScanningConfiguration(v *ImageScanningConfiguration) *CreateRepositoryInput { s.ImageScanningConfiguration = v @@ -4522,6 +4554,87 @@ func (s *EmptyUploadException) RequestID() string { return s.RespMetadata.RequestID } +// The encryption configuration for the repository. This determines how the +// contents of your repository are encrypted at rest. +// +// By default, when no encryption configuration is set or the AES256 encryption +// type is used, Amazon ECR uses server-side encryption with Amazon S3-managed +// encryption keys which encrypts your data at rest using an AES-256 encryption +// algorithm. This does not require any action on your part. +// +// For more control over the encryption of the contents of your repository, +// you can use server-side encryption with customer master keys (CMKs) stored +// in AWS Key Management Service (AWS KMS) to encrypt your images. For more +// information, see Amazon ECR encryption at rest (https://docs.aws.amazon.com/AmazonECR/latest/userguide/encryption-at-rest.html) +// in the Amazon Elastic Container Registry User Guide. +type EncryptionConfiguration struct { + _ struct{} `type:"structure"` + + // The encryption type to use. + // + // If you use the KMS encryption type, the contents of the repository will be + // encrypted using server-side encryption with customer master keys (CMKs) stored + // in AWS KMS. When you use AWS KMS to encrypt your data, you can either use + // the default AWS managed CMK for Amazon ECR, or specify your own CMK, which + // you already created. For more information, see Protecting Data Using Server-Side + // Encryption with CMKs Stored in AWS Key Management Service (SSE-KMS) (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html) + // in the Amazon Simple Storage Service Console Developer Guide.. + // + // If you use the AES256 encryption type, Amazon ECR uses server-side encryption + // with Amazon S3-managed encryption keys which encrypts the images in the repository + // using an AES-256 encryption algorithm. For more information, see Protecting + // Data Using Server-Side Encryption with Amazon S3-Managed Encryption Keys + // (SSE-S3) (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html) + // in the Amazon Simple Storage Service Console Developer Guide.. + // + // EncryptionType is a required field + EncryptionType *string `locationName:"encryptionType" type:"string" required:"true" enum:"EncryptionType"` + + // If you use the KMS encryption type, specify the CMK to use for encryption. + // The alias, key ID, or full ARN of the CMK can be specified. The key must + // exist in the same Region as the repository. If no key is specified, the default + // AWS managed CMK for Amazon ECR will be used. + KmsKey *string `locationName:"kmsKey" min:"1" type:"string"` +} + +// String returns the string representation +func (s EncryptionConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EncryptionConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *EncryptionConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "EncryptionConfiguration"} + if s.EncryptionType == nil { + invalidParams.Add(request.NewErrParamRequired("EncryptionType")) + } + if s.KmsKey != nil && len(*s.KmsKey) < 1 { + invalidParams.Add(request.NewErrParamMinLen("KmsKey", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetEncryptionType sets the EncryptionType field's value. +func (s *EncryptionConfiguration) SetEncryptionType(v string) *EncryptionConfiguration { + s.EncryptionType = &v + return s +} + +// SetKmsKey sets the KmsKey field's value. +func (s *EncryptionConfiguration) SetKmsKey(v string) *EncryptionConfiguration { + s.KmsKey = &v + return s +} + type GetAuthorizationTokenInput struct { _ struct{} `type:"structure"` @@ -5080,6 +5193,9 @@ type Image struct { // The image manifest associated with the image. ImageManifest *string `locationName:"imageManifest" min:"1" type:"string"` + // The media type associated with the image manifest. + ImageManifestMediaType *string `locationName:"imageManifestMediaType" type:"string"` + // The AWS account ID associated with the registry containing the image. RegistryId *string `locationName:"registryId" type:"string"` @@ -5109,6 +5225,12 @@ func (s *Image) SetImageManifest(v string) *Image { return s } +// SetImageManifestMediaType sets the ImageManifestMediaType field's value. +func (s *Image) SetImageManifestMediaType(v string) *Image { + s.ImageManifestMediaType = &v + return s +} + // SetRegistryId sets the RegistryId field's value. func (s *Image) SetRegistryId(v string) *Image { s.RegistryId = &v @@ -5275,6 +5397,63 @@ func (s *ImageDetail) SetRepositoryName(v string) *ImageDetail { return s } +// The specified image digest does not match the digest that Amazon ECR calculated +// for the image. +type ImageDigestDoesNotMatchException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ImageDigestDoesNotMatchException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ImageDigestDoesNotMatchException) GoString() string { + return s.String() +} + +func newErrorImageDigestDoesNotMatchException(v protocol.ResponseMetadata) error { + return &ImageDigestDoesNotMatchException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ImageDigestDoesNotMatchException) Code() string { + return "ImageDigestDoesNotMatchException" +} + +// Message returns the exception's message. +func (s *ImageDigestDoesNotMatchException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ImageDigestDoesNotMatchException) OrigErr() error { + return nil +} + +func (s *ImageDigestDoesNotMatchException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ImageDigestDoesNotMatchException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ImageDigestDoesNotMatchException) RequestID() string { + return s.RespMetadata.RequestID +} + // An object representing an Amazon ECR image failure. type ImageFailure struct { _ struct{} `type:"structure"` @@ -6020,6 +6199,65 @@ func (s *InvalidTagParameterException) RequestID() string { return s.RespMetadata.RequestID } +// The operation failed due to a KMS exception. +type KmsException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // The error code returned by AWS KMS. + KmsError *string `locationName:"kmsError" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s KmsException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s KmsException) GoString() string { + return s.String() +} + +func newErrorKmsException(v protocol.ResponseMetadata) error { + return &KmsException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *KmsException) Code() string { + return "KmsException" +} + +// Message returns the exception's message. +func (s *KmsException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *KmsException) OrigErr() error { + return nil +} + +func (s *KmsException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *KmsException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *KmsException) RequestID() string { + return s.RespMetadata.RequestID +} + // An object representing an Amazon ECR image layer. type Layer struct { _ struct{} `type:"structure"` @@ -6424,8 +6662,8 @@ func (s *LifecyclePolicyPreviewFilter) SetTagStatus(v string) *LifecyclePolicyPr return s } -// The previous lifecycle policy preview request has not completed. Please try -// again later. +// The previous lifecycle policy preview request has not completed. Wait and +// try again. type LifecyclePolicyPreviewInProgressException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -6647,8 +6885,7 @@ func (s *LifecyclePolicyRuleAction) SetType(v string) *LifecyclePolicyRuleAction } // The operation did not succeed because it would have exceeded a service limit -// for your account. For more information, see Amazon ECR Default Service Limits -// (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service_limits.html) +// for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // in the Amazon Elastic Container Registry User Guide. type LimitExceededException struct { _ struct{} `type:"structure"` @@ -6925,13 +7162,22 @@ func (s *ListTagsForResourceOutput) SetTags(v []*Tag) *ListTagsForResourceOutput type PutImageInput struct { _ struct{} `type:"structure"` + // The image digest of the image manifest corresponding to the image. + ImageDigest *string `locationName:"imageDigest" type:"string"` + // The image manifest corresponding to the image to be uploaded. // // ImageManifest is a required field ImageManifest *string `locationName:"imageManifest" min:"1" type:"string" required:"true"` + // The media type of the image manifest. If you push an image manifest that + // does not contain the mediaType field, you must specify the imageManifestMediaType + // in the request. + ImageManifestMediaType *string `locationName:"imageManifestMediaType" type:"string"` + // The tag to associate with the image. This parameter is required for images - // that use the Docker Image Manifest V2 Schema 2 or OCI formats. + // that use the Docker Image Manifest V2 Schema 2 or Open Container Initiative + // (OCI) formats. ImageTag *string `locationName:"imageTag" min:"1" type:"string"` // The AWS account ID associated with the registry that contains the repository @@ -6980,12 +7226,24 @@ func (s *PutImageInput) Validate() error { return nil } +// SetImageDigest sets the ImageDigest field's value. +func (s *PutImageInput) SetImageDigest(v string) *PutImageInput { + s.ImageDigest = &v + return s +} + // SetImageManifest sets the ImageManifest field's value. func (s *PutImageInput) SetImageManifest(v string) *PutImageInput { s.ImageManifest = &v return s } +// SetImageManifestMediaType sets the ImageManifestMediaType field's value. +func (s *PutImageInput) SetImageManifestMediaType(v string) *PutImageInput { + s.ImageManifestMediaType = &v + return s +} + // SetImageTag sets the ImageTag field's value. func (s *PutImageInput) SetImageTag(v string) *PutImageInput { s.ImageTag = &v @@ -7418,6 +7676,10 @@ type Repository struct { // The date and time, in JavaScript date format, when the repository was created. CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + // The encryption configuration for the repository. This determines how the + // contents of your repository are encrypted at rest. + EncryptionConfiguration *EncryptionConfiguration `locationName:"encryptionConfiguration" type:"structure"` + // The image scanning configuration for a repository. ImageScanningConfiguration *ImageScanningConfiguration `locationName:"imageScanningConfiguration" type:"structure"` @@ -7436,8 +7698,8 @@ type Repository struct { // The name of the repository. RepositoryName *string `locationName:"repositoryName" min:"2" type:"string"` - // The URI for the repository. You can use this URI for Docker push or pull - // operations. + // The URI for the repository. You can use this URI for container image push + // and pull operations. RepositoryUri *string `locationName:"repositoryUri" type:"string"` } @@ -7457,6 +7719,12 @@ func (s *Repository) SetCreatedAt(v time.Time) *Repository { return s } +// SetEncryptionConfiguration sets the EncryptionConfiguration field's value. +func (s *Repository) SetEncryptionConfiguration(v *EncryptionConfiguration) *Repository { + s.EncryptionConfiguration = v + return s +} + // SetImageScanningConfiguration sets the ImageScanningConfiguration field's value. func (s *Repository) SetImageScanningConfiguration(v *ImageScanningConfiguration) *Repository { s.ImageScanningConfiguration = v @@ -7847,7 +8115,7 @@ type SetRepositoryPolicyInput struct { Force *bool `locationName:"force" type:"boolean"` // The JSON repository policy text to apply to the repository. For more information, - // see Amazon ECR Repository Policy Examples (https://docs.aws.amazon.com/AmazonECR/latest/userguide/RepositoryPolicyExamples.html) + // see Amazon ECR Repository Policies (https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policy-examples.html) // in the Amazon Elastic Container Registry User Guide. // // PolicyText is a required field @@ -8489,12 +8757,14 @@ type UploadLayerPartInput struct { // LayerPartBlob is a required field LayerPartBlob []byte `locationName:"layerPartBlob" type:"blob" required:"true"` - // The integer value of the first byte of the layer part. + // The position of the first byte of the layer part witin the overall image + // layer. // // PartFirstByte is a required field PartFirstByte *int64 `locationName:"partFirstByte" type:"long" required:"true"` - // The integer value of the last byte of the layer part. + // The position of the last byte of the layer part within the overall image + // layer. // // PartLastByte is a required field PartLastByte *int64 `locationName:"partLastByte" type:"long" required:"true"` @@ -8639,7 +8909,7 @@ func (s *UploadLayerPartOutput) SetUploadId(v string) *UploadLayerPartOutput { return s } -// The upload could not be found, or the specified upload id is not valid for +// The upload could not be found, or the specified upload ID is not valid for // this repository. type UploadNotFoundException struct { _ struct{} `type:"structure"` @@ -8697,6 +8967,22 @@ func (s *UploadNotFoundException) RequestID() string { return s.RespMetadata.RequestID } +const ( + // EncryptionTypeAes256 is a EncryptionType enum value + EncryptionTypeAes256 = "AES256" + + // EncryptionTypeKms is a EncryptionType enum value + EncryptionTypeKms = "KMS" +) + +// EncryptionType_Values returns all elements of the EncryptionType enum +func EncryptionType_Values() []string { + return []string{ + EncryptionTypeAes256, + EncryptionTypeKms, + } +} + const ( // FindingSeverityInformational is a FindingSeverity enum value FindingSeverityInformational = "INFORMATIONAL" @@ -8717,11 +9003,30 @@ const ( FindingSeverityUndefined = "UNDEFINED" ) +// FindingSeverity_Values returns all elements of the FindingSeverity enum +func FindingSeverity_Values() []string { + return []string{ + FindingSeverityInformational, + FindingSeverityLow, + FindingSeverityMedium, + FindingSeverityHigh, + FindingSeverityCritical, + FindingSeverityUndefined, + } +} + const ( // ImageActionTypeExpire is a ImageActionType enum value ImageActionTypeExpire = "EXPIRE" ) +// ImageActionType_Values returns all elements of the ImageActionType enum +func ImageActionType_Values() []string { + return []string{ + ImageActionTypeExpire, + } +} + const ( // ImageFailureCodeInvalidImageDigest is a ImageFailureCode enum value ImageFailureCodeInvalidImageDigest = "InvalidImageDigest" @@ -8740,8 +9045,24 @@ const ( // ImageFailureCodeImageReferencedByManifestList is a ImageFailureCode enum value ImageFailureCodeImageReferencedByManifestList = "ImageReferencedByManifestList" + + // ImageFailureCodeKmsError is a ImageFailureCode enum value + ImageFailureCodeKmsError = "KmsError" ) +// ImageFailureCode_Values returns all elements of the ImageFailureCode enum +func ImageFailureCode_Values() []string { + return []string{ + ImageFailureCodeInvalidImageDigest, + ImageFailureCodeInvalidImageTag, + ImageFailureCodeImageTagDoesNotMatchDigest, + ImageFailureCodeImageNotFound, + ImageFailureCodeMissingDigestAndTag, + ImageFailureCodeImageReferencedByManifestList, + ImageFailureCodeKmsError, + } +} + const ( // ImageTagMutabilityMutable is a ImageTagMutability enum value ImageTagMutabilityMutable = "MUTABLE" @@ -8750,6 +9071,14 @@ const ( ImageTagMutabilityImmutable = "IMMUTABLE" ) +// ImageTagMutability_Values returns all elements of the ImageTagMutability enum +func ImageTagMutability_Values() []string { + return []string{ + ImageTagMutabilityMutable, + ImageTagMutabilityImmutable, + } +} + const ( // LayerAvailabilityAvailable is a LayerAvailability enum value LayerAvailabilityAvailable = "AVAILABLE" @@ -8758,6 +9087,14 @@ const ( LayerAvailabilityUnavailable = "UNAVAILABLE" ) +// LayerAvailability_Values returns all elements of the LayerAvailability enum +func LayerAvailability_Values() []string { + return []string{ + LayerAvailabilityAvailable, + LayerAvailabilityUnavailable, + } +} + const ( // LayerFailureCodeInvalidLayerDigest is a LayerFailureCode enum value LayerFailureCodeInvalidLayerDigest = "InvalidLayerDigest" @@ -8766,6 +9103,14 @@ const ( LayerFailureCodeMissingLayerDigest = "MissingLayerDigest" ) +// LayerFailureCode_Values returns all elements of the LayerFailureCode enum +func LayerFailureCode_Values() []string { + return []string{ + LayerFailureCodeInvalidLayerDigest, + LayerFailureCodeMissingLayerDigest, + } +} + const ( // LifecyclePolicyPreviewStatusInProgress is a LifecyclePolicyPreviewStatus enum value LifecyclePolicyPreviewStatusInProgress = "IN_PROGRESS" @@ -8780,6 +9125,16 @@ const ( LifecyclePolicyPreviewStatusFailed = "FAILED" ) +// LifecyclePolicyPreviewStatus_Values returns all elements of the LifecyclePolicyPreviewStatus enum +func LifecyclePolicyPreviewStatus_Values() []string { + return []string{ + LifecyclePolicyPreviewStatusInProgress, + LifecyclePolicyPreviewStatusComplete, + LifecyclePolicyPreviewStatusExpired, + LifecyclePolicyPreviewStatusFailed, + } +} + const ( // ScanStatusInProgress is a ScanStatus enum value ScanStatusInProgress = "IN_PROGRESS" @@ -8791,6 +9146,15 @@ const ( ScanStatusFailed = "FAILED" ) +// ScanStatus_Values returns all elements of the ScanStatus enum +func ScanStatus_Values() []string { + return []string{ + ScanStatusInProgress, + ScanStatusComplete, + ScanStatusFailed, + } +} + const ( // TagStatusTagged is a TagStatus enum value TagStatusTagged = "TAGGED" @@ -8801,3 +9165,12 @@ const ( // TagStatusAny is a TagStatus enum value TagStatusAny = "ANY" ) + +// TagStatus_Values returns all elements of the TagStatus enum +func TagStatus_Values() []string { + return []string{ + TagStatusTagged, + TagStatusUntagged, + TagStatusAny, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecr/doc.go b/vendor/github.com/aws/aws-sdk-go/service/ecr/doc.go index d970974bcda..3c3843ae3e5 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ecr/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ecr/doc.go @@ -3,12 +3,13 @@ // Package ecr provides the client and types for making API // requests to Amazon EC2 Container Registry. // -// Amazon Elastic Container Registry (Amazon ECR) is a managed Docker registry -// service. Customers can use the familiar Docker CLI to push, pull, and manage -// images. Amazon ECR provides a secure, scalable, and reliable registry. Amazon -// ECR supports private Docker repositories with resource-based permissions +// Amazon Elastic Container Registry (Amazon ECR) is a managed container image +// registry service. Customers can use the familiar Docker CLI, or their preferred +// client, to push, pull, and manage images. Amazon ECR provides a secure, scalable, +// and reliable registry for your Docker or Open Container Initiative (OCI) +// images. Amazon ECR supports private repositories with resource-based permissions // using IAM so that specific users or Amazon EC2 instances can access repositories -// and images. Developers can use the Docker CLI to author and manage images. +// and images. // // See https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21 for more information on this service. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecr/errors.go b/vendor/github.com/aws/aws-sdk-go/service/ecr/errors.go index c4e9b4013b4..8191013264f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ecr/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ecr/errors.go @@ -21,6 +21,13 @@ const ( // the manifest or image tag after the last push. ErrCodeImageAlreadyExistsException = "ImageAlreadyExistsException" + // ErrCodeImageDigestDoesNotMatchException for service response error code + // "ImageDigestDoesNotMatchException". + // + // The specified image digest does not match the digest that Amazon ECR calculated + // for the image. + ErrCodeImageDigestDoesNotMatchException = "ImageDigestDoesNotMatchException" + // ErrCodeImageNotFoundException for service response error code // "ImageNotFoundException". // @@ -63,6 +70,12 @@ const ( // characters. ErrCodeInvalidTagParameterException = "InvalidTagParameterException" + // ErrCodeKmsException for service response error code + // "KmsException". + // + // The operation failed due to a KMS exception. + ErrCodeKmsException = "KmsException" + // ErrCodeLayerAlreadyExistsException for service response error code // "LayerAlreadyExistsException". // @@ -98,8 +111,8 @@ const ( // ErrCodeLifecyclePolicyPreviewInProgressException for service response error code // "LifecyclePolicyPreviewInProgressException". // - // The previous lifecycle policy preview request has not completed. Please try - // again later. + // The previous lifecycle policy preview request has not completed. Wait and + // try again. ErrCodeLifecyclePolicyPreviewInProgressException = "LifecyclePolicyPreviewInProgressException" // ErrCodeLifecyclePolicyPreviewNotFoundException for service response error code @@ -112,8 +125,7 @@ const ( // "LimitExceededException". // // The operation did not succeed because it would have exceeded a service limit - // for your account. For more information, see Amazon ECR Default Service Limits - // (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service_limits.html) + // for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // in the Amazon Elastic Container Registry User Guide. ErrCodeLimitExceededException = "LimitExceededException" @@ -179,7 +191,7 @@ const ( // ErrCodeUploadNotFoundException for service response error code // "UploadNotFoundException". // - // The upload could not be found, or the specified upload id is not valid for + // The upload could not be found, or the specified upload ID is not valid for // this repository. ErrCodeUploadNotFoundException = "UploadNotFoundException" ) @@ -187,12 +199,14 @@ const ( var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "EmptyUploadException": newErrorEmptyUploadException, "ImageAlreadyExistsException": newErrorImageAlreadyExistsException, + "ImageDigestDoesNotMatchException": newErrorImageDigestDoesNotMatchException, "ImageNotFoundException": newErrorImageNotFoundException, "ImageTagAlreadyExistsException": newErrorImageTagAlreadyExistsException, "InvalidLayerException": newErrorInvalidLayerException, "InvalidLayerPartException": newErrorInvalidLayerPartException, "InvalidParameterException": newErrorInvalidParameterException, "InvalidTagParameterException": newErrorInvalidTagParameterException, + "KmsException": newErrorKmsException, "LayerAlreadyExistsException": newErrorLayerAlreadyExistsException, "LayerInaccessibleException": newErrorLayerInaccessibleException, "LayerPartTooSmallException": newErrorLayerPartTooSmallException, 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 533e5460c24..d9f695785b2 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 @@ -89,6 +89,13 @@ func (c *ECS) CreateCapacityProviderRequest(input *CreateCapacityProviderInput) // * LimitExceededException // The limit for the resource has been exceeded. // +// * UpdateInProgressException +// There is already a current Amazon ECS container agent update in progress +// on the specified container instance. If the container agent becomes disconnected +// while it is in a transitional stage, such as PENDING or STAGING, the update +// process can get stuck in that state. However, when the agent reconnects, +// it resumes where it stopped previously. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/CreateCapacityProvider func (c *ECS) CreateCapacityProvider(input *CreateCapacityProviderInput) (*CreateCapacityProviderOutput, error) { req, out := c.CreateCapacityProviderRequest(input) @@ -708,6 +715,108 @@ func (c *ECS) DeleteAttributesWithContext(ctx aws.Context, input *DeleteAttribut return out, req.Send() } +const opDeleteCapacityProvider = "DeleteCapacityProvider" + +// DeleteCapacityProviderRequest generates a "aws/request.Request" representing the +// client's request for the DeleteCapacityProvider operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteCapacityProvider for more information on using the DeleteCapacityProvider +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteCapacityProviderRequest method. +// req, resp := client.DeleteCapacityProviderRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DeleteCapacityProvider +func (c *ECS) DeleteCapacityProviderRequest(input *DeleteCapacityProviderInput) (req *request.Request, output *DeleteCapacityProviderOutput) { + op := &request.Operation{ + Name: opDeleteCapacityProvider, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteCapacityProviderInput{} + } + + output = &DeleteCapacityProviderOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteCapacityProvider API operation for Amazon EC2 Container Service. +// +// Deletes the specified capacity provider. +// +// The FARGATE and FARGATE_SPOT capacity providers are reserved and cannot be +// deleted. You can disassociate them from a cluster using either the PutClusterCapacityProviders +// API or by deleting the cluster. +// +// Prior to a capacity provider being deleted, the capacity provider must be +// removed from the capacity provider strategy from all services. The UpdateService +// API can be used to remove a capacity provider from a service's capacity provider +// strategy. When updating a service, the forceNewDeployment option can be used +// to ensure that any tasks using the Amazon EC2 instance capacity provided +// by the capacity provider are transitioned to use the capacity from the remaining +// capacity providers. Only capacity providers that are not associated with +// a cluster can be deleted. To remove a capacity provider from a cluster, you +// can either use PutClusterCapacityProviders or delete the cluster. +// +// Returns awserr.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 EC2 Container Service's +// API operation DeleteCapacityProvider for usage and error information. +// +// Returned Error Types: +// * ServerException +// These errors are usually caused by a server issue. +// +// * ClientException +// These errors are usually caused by a client action, such as using an action +// or resource on behalf of a user that doesn't have permissions to use the +// action or resource, or specifying an identifier that is not valid. +// +// * InvalidParameterException +// The specified parameter is invalid. Review the available parameters for the +// API request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/DeleteCapacityProvider +func (c *ECS) DeleteCapacityProvider(input *DeleteCapacityProviderInput) (*DeleteCapacityProviderOutput, error) { + req, out := c.DeleteCapacityProviderRequest(input) + return out, req.Send() +} + +// DeleteCapacityProviderWithContext is the same as DeleteCapacityProvider with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCapacityProvider for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DeleteCapacityProviderWithContext(ctx aws.Context, input *DeleteCapacityProviderInput, opts ...request.Option) (*DeleteCapacityProviderOutput, error) { + req, out := c.DeleteCapacityProviderRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteCluster = "DeleteCluster" // DeleteClusterRequest generates a "aws/request.Request" representing the @@ -6033,7 +6142,8 @@ type CapacityProvider struct { Name *string `locationName:"name" type:"string"` // The current status of the capacity provider. Only capacity providers in an - // ACTIVE state can be used in a cluster. + // ACTIVE state can be used in a cluster. When a capacity provider is successfully + // deleted, it will have an INACTIVE status. Status *string `locationName:"status" type:"string" enum:"CapacityProviderStatus"` // The metadata that you apply to the capacity provider to help you categorize @@ -6063,6 +6173,28 @@ type CapacityProvider struct { // cannot edit or delete tag keys or values with this prefix. Tags with this // prefix do not count against your tags per resource limit. Tags []*Tag `locationName:"tags" type:"list"` + + // The update status of the capacity provider. The following are the possible + // states that will be returned. + // + // DELETE_IN_PROGRESS + // + // The capacity provider is in the process of being deleted. + // + // DELETE_COMPLETE + // + // The capacity provider has been successfully deleted and will have an INACTIVE + // status. + // + // DELETE_FAILED + // + // The capacity provider was unable to be deleted. The update status reason + // will provide further details about why the delete failed. + UpdateStatus *string `locationName:"updateStatus" type:"string" enum:"CapacityProviderUpdateStatus"` + + // The update status reason. This provides further details about the update + // status for the capacity provider. + UpdateStatusReason *string `locationName:"updateStatusReason" type:"string"` } // String returns the string representation @@ -6105,6 +6237,18 @@ func (s *CapacityProvider) SetTags(v []*Tag) *CapacityProvider { return s } +// SetUpdateStatus sets the UpdateStatus field's value. +func (s *CapacityProvider) SetUpdateStatus(v string) *CapacityProvider { + s.UpdateStatus = &v + return s +} + +// SetUpdateStatusReason sets the UpdateStatusReason field's value. +func (s *CapacityProvider) SetUpdateStatusReason(v string) *CapacityProvider { + s.UpdateStatusReason = &v + return s +} + // The details of a capacity provider strategy. type CapacityProviderStrategyItem struct { _ struct{} `type:"structure"` @@ -7060,6 +7204,27 @@ type ContainerDefinition struct { // such as credential data. Environment []*KeyValuePair `locationName:"environment" type:"list"` + // A list of files containing the environment variables to pass to a container. + // This parameter maps to the --env-file option to docker run (https://docs.docker.com/engine/reference/run/). + // + // You can specify up to ten environment files. The file must have a .env file + // extension. Each line in an environment file should contain an environment + // variable in VARIABLE=VALUE format. Lines beginning with # are treated as + // comments and are ignored. For more information on the environment variable + // file syntax, see Declare default environment variables in file (https://docs.docker.com/compose/env-file/). + // + // If there are environment variables specified using the environment parameter + // in a container definition, they take precedence over the variables contained + // within an environment file. If multiple environment files are specified that + // contain the same variable, they are processed from the top down. It is recommended + // to use unique variable names. For more information, see Specifying Environment + // Variables (https://docs.aws.amazon.com/AmazonECS/latest/developerguide/taskdef-envfiles.html) + // in the Amazon Elastic Container Service Developer Guide. + // + // This field is not valid for containers in tasks using the Fargate launch + // type. + EnvironmentFiles []*EnvironmentFile `locationName:"environmentFiles" type:"list"` + // If the essential parameter of a container is marked as true, and that container // fails or stops for any reason, all other containers that are part of the // task are stopped. If the essential parameter of a container is marked as @@ -7400,8 +7565,9 @@ type ContainerDefinition struct { // namespaced kernel parameters as well as the containers. SystemControls []*SystemControl `locationName:"systemControls" type:"list"` - // A list of ulimits to set in the container. This parameter maps to Ulimits - // in the Create a container (https://docs.docker.com/engine/api/v1.35/#operation/ContainerCreate) + // A list of ulimits to set in the container. If a ulimit value is specified + // in a task definition, it will override the default values set by Docker. + // This parameter maps to Ulimits in the Create a container (https://docs.docker.com/engine/api/v1.35/#operation/ContainerCreate) // section of the Docker Remote API (https://docs.docker.com/engine/api/v1.35/) // and the --ulimit option to docker run (https://docs.docker.com/engine/reference/run/). // Valid naming values are displayed in the Ulimit data type. This parameter @@ -7472,6 +7638,16 @@ func (s *ContainerDefinition) Validate() error { } } } + if s.EnvironmentFiles != nil { + for i, v := range s.EnvironmentFiles { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "EnvironmentFiles", i), err.(request.ErrInvalidParams)) + } + } + } if s.ExtraHosts != nil { for i, v := range s.ExtraHosts { if v == nil { @@ -7604,6 +7780,12 @@ func (s *ContainerDefinition) SetEnvironment(v []*KeyValuePair) *ContainerDefini return s } +// SetEnvironmentFiles sets the EnvironmentFiles field's value. +func (s *ContainerDefinition) SetEnvironmentFiles(v []*EnvironmentFile) *ContainerDefinition { + s.EnvironmentFiles = v + return s +} + // SetEssential sets the Essential field's value. func (s *ContainerDefinition) SetEssential(v bool) *ContainerDefinition { s.Essential = &v @@ -8119,6 +8301,10 @@ type ContainerOverride struct { // You must also specify a container name. Environment []*KeyValuePair `locationName:"environment" type:"list"` + // A list of files containing the environment variables to pass to a container, + // instead of the value from the container definition. + EnvironmentFiles []*EnvironmentFile `locationName:"environmentFiles" type:"list"` + // The hard limit (in MiB) of memory to present to the container, instead of // the default value from the task definition. If your container attempts to // exceed the memory specified here, the container is killed. You must also @@ -8153,6 +8339,16 @@ func (s ContainerOverride) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *ContainerOverride) Validate() error { invalidParams := request.ErrInvalidParams{Context: "ContainerOverride"} + if s.EnvironmentFiles != nil { + for i, v := range s.EnvironmentFiles { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "EnvironmentFiles", i), err.(request.ErrInvalidParams)) + } + } + } if s.ResourceRequirements != nil { for i, v := range s.ResourceRequirements { if v == nil { @@ -8188,6 +8384,12 @@ func (s *ContainerOverride) SetEnvironment(v []*KeyValuePair) *ContainerOverride return s } +// SetEnvironmentFiles sets the EnvironmentFiles field's value. +func (s *ContainerOverride) SetEnvironmentFiles(v []*EnvironmentFile) *ContainerOverride { + s.EnvironmentFiles = v + return s +} + // SetMemory sets the Memory field's value. func (s *ContainerOverride) SetMemory(v int64) *ContainerOverride { s.Memory = &v @@ -9492,6 +9694,68 @@ func (s *DeleteAttributesOutput) SetAttributes(v []*Attribute) *DeleteAttributes return s } +type DeleteCapacityProviderInput struct { + _ struct{} `type:"structure"` + + // The short name or full Amazon Resource Name (ARN) of the capacity provider + // to delete. + // + // CapacityProvider is a required field + CapacityProvider *string `locationName:"capacityProvider" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteCapacityProviderInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCapacityProviderInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteCapacityProviderInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteCapacityProviderInput"} + if s.CapacityProvider == nil { + invalidParams.Add(request.NewErrParamRequired("CapacityProvider")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCapacityProvider sets the CapacityProvider field's value. +func (s *DeleteCapacityProviderInput) SetCapacityProvider(v string) *DeleteCapacityProviderInput { + s.CapacityProvider = &v + return s +} + +type DeleteCapacityProviderOutput struct { + _ struct{} `type:"structure"` + + // The details of a capacity provider. + CapacityProvider *CapacityProvider `locationName:"capacityProvider" type:"structure"` +} + +// String returns the string representation +func (s DeleteCapacityProviderOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCapacityProviderOutput) GoString() string { + return s.String() +} + +// SetCapacityProvider sets the CapacityProvider field's value. +func (s *DeleteCapacityProviderOutput) SetCapacityProvider(v *CapacityProvider) *DeleteCapacityProviderOutput { + s.CapacityProvider = v + return s +} + type DeleteClusterInput struct { _ struct{} `type:"structure"` @@ -11219,6 +11483,76 @@ func (s *EFSVolumeConfiguration) SetTransitEncryptionPort(v int64) *EFSVolumeCon return s } +// A list of files containing the environment variables to pass to a container. +// You can specify up to ten environment files. The file must have a .env file +// extension. Each line in an environment file should contain an environment +// variable in VARIABLE=VALUE format. Lines beginning with # are treated as +// comments and are ignored. For more information on the environment variable +// file syntax, see Declare default environment variables in file (https://docs.docker.com/compose/env-file/). +// +// If there are environment variables specified using the environment parameter +// in a container definition, they take precedence over the variables contained +// within an environment file. If multiple environment files are specified that +// contain the same variable, they are processed from the top down. It is recommended +// to use unique variable names. For more information, see Specifying Environment +// Variables (https://docs.aws.amazon.com/AmazonECS/latest/developerguide/taskdef-envfiles.html) +// in the Amazon Elastic Container Service Developer Guide. +// +// This field is not valid for containers in tasks using the Fargate launch +// type. +type EnvironmentFile struct { + _ struct{} `type:"structure"` + + // The file type to use. The only supported value is s3. + // + // Type is a required field + Type *string `locationName:"type" type:"string" required:"true" enum:"EnvironmentFileType"` + + // The Amazon Resource Name (ARN) of the Amazon S3 object containing the environment + // variable file. + // + // Value is a required field + Value *string `locationName:"value" type:"string" required:"true"` +} + +// String returns the string representation +func (s EnvironmentFile) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EnvironmentFile) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *EnvironmentFile) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "EnvironmentFile"} + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + if s.Value == nil { + invalidParams.Add(request.NewErrParamRequired("Value")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetType sets the Type field's value. +func (s *EnvironmentFile) SetType(v string) *EnvironmentFile { + s.Type = &v + return s +} + +// SetValue sets the Value field's value. +func (s *EnvironmentFile) SetValue(v string) *EnvironmentFile { + s.Value = &v + return s +} + // A failed resource. type Failure struct { _ struct{} `type:"structure"` @@ -11715,8 +12049,9 @@ type KernelCapabilities struct { // section of the Docker Remote API (https://docs.docker.com/engine/api/v1.35/) // and the --cap-add option to docker run (https://docs.docker.com/engine/reference/run/). // - // If you are using tasks that use the Fargate launch type, the add parameter - // is not supported. + // The SYS_PTRACE capability is supported for tasks that use the Fargate launch + // type if they are also using platform version 1.4.0. The other capabilities + // are not supported for any platform versions. // // Valid values: "ALL" | "AUDIT_CONTROL" | "AUDIT_WRITE" | "BLOCK_SUSPEND" | // "CHOWN" | "DAC_OVERRIDE" | "DAC_READ_SEARCH" | "FOWNER" | "FSETID" | "IPC_LOCK" @@ -11865,8 +12200,9 @@ type LinuxParameters struct { // The Linux capabilities for the container that are added to or dropped from // the default configuration provided by Docker. // - // If you are using tasks that use the Fargate launch type, capabilities is - // supported but the add parameter is not supported. + // For tasks that use the Fargate launch type, capabilities is supported for + // all platform versions but the add parameter is only supported if using platform + // version 1.4.0 or later. Capabilities *KernelCapabilities `locationName:"capabilities" type:"structure"` // Any host devices to expose to the container. This parameter maps to Devices @@ -12028,7 +12364,7 @@ type ListAccountSettingsInput struct { // returns up to 10 results and a nextToken value if applicable. MaxResults *int64 `locationName:"maxResults" type:"integer"` - // The resource name you want to list the account settings for. + // The name of the account setting you want to list the settings for. Name *string `locationName:"name" type:"string" enum:"SettingName"` // The nextToken value returned from a ListAccountSettings request indicating @@ -14692,8 +15028,11 @@ type RegisterTaskDefinitionInput struct { // (30 GB) in increments of 1024 (1 GB) Cpu *string `locationName:"cpu" type:"string"` - // The Amazon Resource Name (ARN) of the task execution role that the Amazon - // ECS container agent and the Docker daemon can assume. + // The Amazon Resource Name (ARN) of the task execution role that grants the + // Amazon ECS container agent permission to make AWS API calls on your behalf. + // The task execution IAM role is required depending on the requirements of + // your task. For more information, see Amazon ECS task execution IAM role (https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html) + // in the Amazon Elastic Container Service Developer Guide. ExecutionRoleArn *string `locationName:"executionRoleArn" type:"string"` // You must specify a family for a task definition, which allows you to track @@ -17872,9 +18211,11 @@ type TaskDefinition struct { // (30 GB) in increments of 1024 (1 GB) Cpu *string `locationName:"cpu" type:"string"` - // The Amazon Resource Name (ARN) of the task execution role that containers - // in this task can assume. All containers in this task are granted the permissions - // that are specified in this role. + // The Amazon Resource Name (ARN) of the task execution role that grants the + // Amazon ECS container agent permission to make AWS API calls on your behalf. + // The task execution IAM role is required depending on the requirements of + // your task. For more information, see Amazon ECS task execution IAM role (https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html) + // in the Amazon Elastic Container Service Developer Guide. ExecutionRoleArn *string `locationName:"executionRoleArn" type:"string"` // The name of a family that this task definition is registered to. Up to 255 @@ -18237,8 +18578,8 @@ type TaskOverride struct { // The cpu override for the task. Cpu *string `locationName:"cpu" type:"string"` - // The Amazon Resource Name (ARN) of the task execution role that the Amazon - // ECS container agent and the Docker daemon can assume. + // The Amazon Resource Name (ARN) of the task execution IAM role override for + // the task. ExecutionRoleArn *string `locationName:"executionRoleArn" type:"string"` // The Elastic Inference accelerator override for the task. @@ -19737,10 +20078,11 @@ func (s *VersionInfo) SetDockerVersion(v string) *VersionInfo { return s } -// A data volume used in a task definition. For tasks that use a Docker volume, -// specify a DockerVolumeConfiguration. For tasks that use a bind mount host -// volume, specify a host and optional sourcePath. For more information, see -// Using Data Volumes in Tasks (https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_data_volumes.html). +// A data volume used in a task definition. For tasks that use Amazon Elastic +// File System (Amazon EFS) file storage, specify an efsVolumeConfiguration. +// For tasks that use a Docker volume, specify a DockerVolumeConfiguration. +// For tasks that use a bind mount host volume, specify a host and optional +// sourcePath. For more information, see Using Data Volumes in Tasks (https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_data_volumes.html). type Volume struct { _ struct{} `type:"structure"` @@ -19751,23 +20093,15 @@ type Volume struct { DockerVolumeConfiguration *DockerVolumeConfiguration `locationName:"dockerVolumeConfiguration" type:"structure"` // This parameter is specified when you are using an Amazon Elastic File System - // (Amazon EFS) file storage. Amazon EFS file systems are only supported when - // you are using the EC2 launch type. - // - // EFSVolumeConfiguration remains in preview and is a Beta Service as defined - // by and subject to the Beta Service Participation Service Terms located at - // https://aws.amazon.com/service-terms (https://aws.amazon.com/service-terms) - // ("Beta Terms"). These Beta Terms apply to your participation in this preview - // of EFSVolumeConfiguration. + // file system for task storage. EfsVolumeConfiguration *EFSVolumeConfiguration `locationName:"efsVolumeConfiguration" type:"structure"` - // This parameter is specified when you are using bind mount host volumes. Bind - // mount host volumes are supported when you are using either the EC2 or Fargate - // launch types. The contents of the host parameter determine whether your bind - // mount host volume persists on the host container instance and where it is - // stored. If the host parameter is empty, then the Docker daemon assigns a - // host path for your data volume. However, the data is not guaranteed to persist - // after the containers associated with it stop running. + // This parameter is specified when you are using bind mount host volumes. The + // contents of the host parameter determine whether your bind mount host volume + // persists on the host container instance and where it is stored. If the host + // parameter is empty, then the Docker daemon assigns a host path for your data + // volume. However, the data is not guaranteed to persist after the containers + // associated with it stop running. // // Windows containers can mount whole directories on the same drive as $env:ProgramData. // Windows containers cannot mount directories on a different drive, and mount @@ -19886,6 +20220,18 @@ const ( AgentUpdateStatusFailed = "FAILED" ) +// AgentUpdateStatus_Values returns all elements of the AgentUpdateStatus enum +func AgentUpdateStatus_Values() []string { + return []string{ + AgentUpdateStatusPending, + AgentUpdateStatusStaging, + AgentUpdateStatusStaged, + AgentUpdateStatusUpdating, + AgentUpdateStatusUpdated, + AgentUpdateStatusFailed, + } +} + const ( // AssignPublicIpEnabled is a AssignPublicIp enum value AssignPublicIpEnabled = "ENABLED" @@ -19894,16 +20240,62 @@ const ( AssignPublicIpDisabled = "DISABLED" ) +// AssignPublicIp_Values returns all elements of the AssignPublicIp enum +func AssignPublicIp_Values() []string { + return []string{ + AssignPublicIpEnabled, + AssignPublicIpDisabled, + } +} + const ( // CapacityProviderFieldTags is a CapacityProviderField enum value CapacityProviderFieldTags = "TAGS" ) +// CapacityProviderField_Values returns all elements of the CapacityProviderField enum +func CapacityProviderField_Values() []string { + return []string{ + CapacityProviderFieldTags, + } +} + const ( // CapacityProviderStatusActive is a CapacityProviderStatus enum value CapacityProviderStatusActive = "ACTIVE" + + // CapacityProviderStatusInactive is a CapacityProviderStatus enum value + CapacityProviderStatusInactive = "INACTIVE" ) +// CapacityProviderStatus_Values returns all elements of the CapacityProviderStatus enum +func CapacityProviderStatus_Values() []string { + return []string{ + CapacityProviderStatusActive, + CapacityProviderStatusInactive, + } +} + +const ( + // CapacityProviderUpdateStatusDeleteInProgress is a CapacityProviderUpdateStatus enum value + CapacityProviderUpdateStatusDeleteInProgress = "DELETE_IN_PROGRESS" + + // CapacityProviderUpdateStatusDeleteComplete is a CapacityProviderUpdateStatus enum value + CapacityProviderUpdateStatusDeleteComplete = "DELETE_COMPLETE" + + // CapacityProviderUpdateStatusDeleteFailed is a CapacityProviderUpdateStatus enum value + CapacityProviderUpdateStatusDeleteFailed = "DELETE_FAILED" +) + +// CapacityProviderUpdateStatus_Values returns all elements of the CapacityProviderUpdateStatus enum +func CapacityProviderUpdateStatus_Values() []string { + return []string{ + CapacityProviderUpdateStatusDeleteInProgress, + CapacityProviderUpdateStatusDeleteComplete, + CapacityProviderUpdateStatusDeleteFailed, + } +} + const ( // ClusterFieldAttachments is a ClusterField enum value ClusterFieldAttachments = "ATTACHMENTS" @@ -19918,11 +20310,28 @@ const ( ClusterFieldTags = "TAGS" ) +// ClusterField_Values returns all elements of the ClusterField enum +func ClusterField_Values() []string { + return []string{ + ClusterFieldAttachments, + ClusterFieldSettings, + ClusterFieldStatistics, + ClusterFieldTags, + } +} + const ( // ClusterSettingNameContainerInsights is a ClusterSettingName enum value ClusterSettingNameContainerInsights = "containerInsights" ) +// ClusterSettingName_Values returns all elements of the ClusterSettingName enum +func ClusterSettingName_Values() []string { + return []string{ + ClusterSettingNameContainerInsights, + } +} + const ( // CompatibilityEc2 is a Compatibility enum value CompatibilityEc2 = "EC2" @@ -19931,6 +20340,14 @@ const ( CompatibilityFargate = "FARGATE" ) +// Compatibility_Values returns all elements of the Compatibility enum +func Compatibility_Values() []string { + return []string{ + CompatibilityEc2, + CompatibilityFargate, + } +} + const ( // ConnectivityConnected is a Connectivity enum value ConnectivityConnected = "CONNECTED" @@ -19939,6 +20356,14 @@ const ( ConnectivityDisconnected = "DISCONNECTED" ) +// Connectivity_Values returns all elements of the Connectivity enum +func Connectivity_Values() []string { + return []string{ + ConnectivityConnected, + ConnectivityDisconnected, + } +} + const ( // ContainerConditionStart is a ContainerCondition enum value ContainerConditionStart = "START" @@ -19953,11 +20378,28 @@ const ( ContainerConditionHealthy = "HEALTHY" ) +// ContainerCondition_Values returns all elements of the ContainerCondition enum +func ContainerCondition_Values() []string { + return []string{ + ContainerConditionStart, + ContainerConditionComplete, + ContainerConditionSuccess, + ContainerConditionHealthy, + } +} + const ( // ContainerInstanceFieldTags is a ContainerInstanceField enum value ContainerInstanceFieldTags = "TAGS" ) +// ContainerInstanceField_Values returns all elements of the ContainerInstanceField enum +func ContainerInstanceField_Values() []string { + return []string{ + ContainerInstanceFieldTags, + } +} + const ( // ContainerInstanceStatusActive is a ContainerInstanceStatus enum value ContainerInstanceStatusActive = "ACTIVE" @@ -19975,6 +20417,17 @@ const ( ContainerInstanceStatusRegistrationFailed = "REGISTRATION_FAILED" ) +// ContainerInstanceStatus_Values returns all elements of the ContainerInstanceStatus enum +func ContainerInstanceStatus_Values() []string { + return []string{ + ContainerInstanceStatusActive, + ContainerInstanceStatusDraining, + ContainerInstanceStatusRegistering, + ContainerInstanceStatusDeregistering, + ContainerInstanceStatusRegistrationFailed, + } +} + const ( // DeploymentControllerTypeEcs is a DeploymentControllerType enum value DeploymentControllerTypeEcs = "ECS" @@ -19986,6 +20439,15 @@ const ( DeploymentControllerTypeExternal = "EXTERNAL" ) +// DeploymentControllerType_Values returns all elements of the DeploymentControllerType enum +func DeploymentControllerType_Values() []string { + return []string{ + DeploymentControllerTypeEcs, + DeploymentControllerTypeCodeDeploy, + DeploymentControllerTypeExternal, + } +} + const ( // DesiredStatusRunning is a DesiredStatus enum value DesiredStatusRunning = "RUNNING" @@ -19997,6 +20459,15 @@ const ( DesiredStatusStopped = "STOPPED" ) +// DesiredStatus_Values returns all elements of the DesiredStatus enum +func DesiredStatus_Values() []string { + return []string{ + DesiredStatusRunning, + DesiredStatusPending, + DesiredStatusStopped, + } +} + const ( // DeviceCgroupPermissionRead is a DeviceCgroupPermission enum value DeviceCgroupPermissionRead = "read" @@ -20008,6 +20479,15 @@ const ( DeviceCgroupPermissionMknod = "mknod" ) +// DeviceCgroupPermission_Values returns all elements of the DeviceCgroupPermission enum +func DeviceCgroupPermission_Values() []string { + return []string{ + DeviceCgroupPermissionRead, + DeviceCgroupPermissionWrite, + DeviceCgroupPermissionMknod, + } +} + const ( // EFSAuthorizationConfigIAMEnabled is a EFSAuthorizationConfigIAM enum value EFSAuthorizationConfigIAMEnabled = "ENABLED" @@ -20016,6 +20496,14 @@ const ( EFSAuthorizationConfigIAMDisabled = "DISABLED" ) +// EFSAuthorizationConfigIAM_Values returns all elements of the EFSAuthorizationConfigIAM enum +func EFSAuthorizationConfigIAM_Values() []string { + return []string{ + EFSAuthorizationConfigIAMEnabled, + EFSAuthorizationConfigIAMDisabled, + } +} + const ( // EFSTransitEncryptionEnabled is a EFSTransitEncryption enum value EFSTransitEncryptionEnabled = "ENABLED" @@ -20024,6 +20512,26 @@ const ( EFSTransitEncryptionDisabled = "DISABLED" ) +// EFSTransitEncryption_Values returns all elements of the EFSTransitEncryption enum +func EFSTransitEncryption_Values() []string { + return []string{ + EFSTransitEncryptionEnabled, + EFSTransitEncryptionDisabled, + } +} + +const ( + // EnvironmentFileTypeS3 is a EnvironmentFileType enum value + EnvironmentFileTypeS3 = "s3" +) + +// EnvironmentFileType_Values returns all elements of the EnvironmentFileType enum +func EnvironmentFileType_Values() []string { + return []string{ + EnvironmentFileTypeS3, + } +} + const ( // FirelensConfigurationTypeFluentd is a FirelensConfigurationType enum value FirelensConfigurationTypeFluentd = "fluentd" @@ -20032,6 +20540,14 @@ const ( FirelensConfigurationTypeFluentbit = "fluentbit" ) +// FirelensConfigurationType_Values returns all elements of the FirelensConfigurationType enum +func FirelensConfigurationType_Values() []string { + return []string{ + FirelensConfigurationTypeFluentd, + FirelensConfigurationTypeFluentbit, + } +} + const ( // HealthStatusHealthy is a HealthStatus enum value HealthStatusHealthy = "HEALTHY" @@ -20043,6 +20559,15 @@ const ( HealthStatusUnknown = "UNKNOWN" ) +// HealthStatus_Values returns all elements of the HealthStatus enum +func HealthStatus_Values() []string { + return []string{ + HealthStatusHealthy, + HealthStatusUnhealthy, + HealthStatusUnknown, + } +} + const ( // IpcModeHost is a IpcMode enum value IpcModeHost = "host" @@ -20054,6 +20579,15 @@ const ( IpcModeNone = "none" ) +// IpcMode_Values returns all elements of the IpcMode enum +func IpcMode_Values() []string { + return []string{ + IpcModeHost, + IpcModeTask, + IpcModeNone, + } +} + const ( // LaunchTypeEc2 is a LaunchType enum value LaunchTypeEc2 = "EC2" @@ -20062,6 +20596,14 @@ const ( LaunchTypeFargate = "FARGATE" ) +// LaunchType_Values returns all elements of the LaunchType enum +func LaunchType_Values() []string { + return []string{ + LaunchTypeEc2, + LaunchTypeFargate, + } +} + const ( // LogDriverJsonFile is a LogDriver enum value LogDriverJsonFile = "json-file" @@ -20088,6 +20630,20 @@ const ( LogDriverAwsfirelens = "awsfirelens" ) +// LogDriver_Values returns all elements of the LogDriver enum +func LogDriver_Values() []string { + return []string{ + LogDriverJsonFile, + LogDriverSyslog, + LogDriverJournald, + LogDriverGelf, + LogDriverFluentd, + LogDriverAwslogs, + LogDriverSplunk, + LogDriverAwsfirelens, + } +} + const ( // ManagedScalingStatusEnabled is a ManagedScalingStatus enum value ManagedScalingStatusEnabled = "ENABLED" @@ -20096,6 +20652,14 @@ const ( ManagedScalingStatusDisabled = "DISABLED" ) +// ManagedScalingStatus_Values returns all elements of the ManagedScalingStatus enum +func ManagedScalingStatus_Values() []string { + return []string{ + ManagedScalingStatusEnabled, + ManagedScalingStatusDisabled, + } +} + const ( // ManagedTerminationProtectionEnabled is a ManagedTerminationProtection enum value ManagedTerminationProtectionEnabled = "ENABLED" @@ -20104,6 +20668,14 @@ const ( ManagedTerminationProtectionDisabled = "DISABLED" ) +// ManagedTerminationProtection_Values returns all elements of the ManagedTerminationProtection enum +func ManagedTerminationProtection_Values() []string { + return []string{ + ManagedTerminationProtectionEnabled, + ManagedTerminationProtectionDisabled, + } +} + const ( // NetworkModeBridge is a NetworkMode enum value NetworkModeBridge = "bridge" @@ -20118,6 +20690,16 @@ const ( NetworkModeNone = "none" ) +// NetworkMode_Values returns all elements of the NetworkMode enum +func NetworkMode_Values() []string { + return []string{ + NetworkModeBridge, + NetworkModeHost, + NetworkModeAwsvpc, + NetworkModeNone, + } +} + const ( // PidModeHost is a PidMode enum value PidModeHost = "host" @@ -20126,6 +20708,14 @@ const ( PidModeTask = "task" ) +// PidMode_Values returns all elements of the PidMode enum +func PidMode_Values() []string { + return []string{ + PidModeHost, + PidModeTask, + } +} + const ( // PlacementConstraintTypeDistinctInstance is a PlacementConstraintType enum value PlacementConstraintTypeDistinctInstance = "distinctInstance" @@ -20134,6 +20724,14 @@ const ( PlacementConstraintTypeMemberOf = "memberOf" ) +// PlacementConstraintType_Values returns all elements of the PlacementConstraintType enum +func PlacementConstraintType_Values() []string { + return []string{ + PlacementConstraintTypeDistinctInstance, + PlacementConstraintTypeMemberOf, + } +} + const ( // PlacementStrategyTypeRandom is a PlacementStrategyType enum value PlacementStrategyTypeRandom = "random" @@ -20145,11 +20743,27 @@ const ( PlacementStrategyTypeBinpack = "binpack" ) +// PlacementStrategyType_Values returns all elements of the PlacementStrategyType enum +func PlacementStrategyType_Values() []string { + return []string{ + PlacementStrategyTypeRandom, + PlacementStrategyTypeSpread, + PlacementStrategyTypeBinpack, + } +} + const ( // PlatformDeviceTypeGpu is a PlatformDeviceType enum value PlatformDeviceTypeGpu = "GPU" ) +// PlatformDeviceType_Values returns all elements of the PlatformDeviceType enum +func PlatformDeviceType_Values() []string { + return []string{ + PlatformDeviceTypeGpu, + } +} + const ( // PropagateTagsTaskDefinition is a PropagateTags enum value PropagateTagsTaskDefinition = "TASK_DEFINITION" @@ -20158,11 +20772,26 @@ const ( PropagateTagsService = "SERVICE" ) +// PropagateTags_Values returns all elements of the PropagateTags enum +func PropagateTags_Values() []string { + return []string{ + PropagateTagsTaskDefinition, + PropagateTagsService, + } +} + const ( // ProxyConfigurationTypeAppmesh is a ProxyConfigurationType enum value ProxyConfigurationTypeAppmesh = "APPMESH" ) +// ProxyConfigurationType_Values returns all elements of the ProxyConfigurationType enum +func ProxyConfigurationType_Values() []string { + return []string{ + ProxyConfigurationTypeAppmesh, + } +} + const ( // ResourceTypeGpu is a ResourceType enum value ResourceTypeGpu = "GPU" @@ -20171,11 +20800,26 @@ const ( ResourceTypeInferenceAccelerator = "InferenceAccelerator" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeGpu, + ResourceTypeInferenceAccelerator, + } +} + const ( // ScaleUnitPercent is a ScaleUnit enum value ScaleUnitPercent = "PERCENT" ) +// ScaleUnit_Values returns all elements of the ScaleUnit enum +func ScaleUnit_Values() []string { + return []string{ + ScaleUnitPercent, + } +} + const ( // SchedulingStrategyReplica is a SchedulingStrategy enum value SchedulingStrategyReplica = "REPLICA" @@ -20184,6 +20828,14 @@ const ( SchedulingStrategyDaemon = "DAEMON" ) +// SchedulingStrategy_Values returns all elements of the SchedulingStrategy enum +func SchedulingStrategy_Values() []string { + return []string{ + SchedulingStrategyReplica, + SchedulingStrategyDaemon, + } +} + const ( // ScopeTask is a Scope enum value ScopeTask = "task" @@ -20192,11 +20844,26 @@ const ( ScopeShared = "shared" ) +// Scope_Values returns all elements of the Scope enum +func Scope_Values() []string { + return []string{ + ScopeTask, + ScopeShared, + } +} + const ( // ServiceFieldTags is a ServiceField enum value ServiceFieldTags = "TAGS" ) +// ServiceField_Values returns all elements of the ServiceField enum +func ServiceField_Values() []string { + return []string{ + ServiceFieldTags, + } +} + const ( // SettingNameServiceLongArnFormat is a SettingName enum value SettingNameServiceLongArnFormat = "serviceLongArnFormat" @@ -20214,6 +20881,17 @@ const ( SettingNameContainerInsights = "containerInsights" ) +// SettingName_Values returns all elements of the SettingName enum +func SettingName_Values() []string { + return []string{ + SettingNameServiceLongArnFormat, + SettingNameTaskLongArnFormat, + SettingNameContainerInstanceLongArnFormat, + SettingNameAwsvpcTrunking, + SettingNameContainerInsights, + } +} + const ( // SortOrderAsc is a SortOrder enum value SortOrderAsc = "ASC" @@ -20222,6 +20900,14 @@ const ( SortOrderDesc = "DESC" ) +// SortOrder_Values returns all elements of the SortOrder enum +func SortOrder_Values() []string { + return []string{ + SortOrderAsc, + SortOrderDesc, + } +} + const ( // StabilityStatusSteadyState is a StabilityStatus enum value StabilityStatusSteadyState = "STEADY_STATE" @@ -20230,11 +20916,26 @@ const ( StabilityStatusStabilizing = "STABILIZING" ) +// StabilityStatus_Values returns all elements of the StabilityStatus enum +func StabilityStatus_Values() []string { + return []string{ + StabilityStatusSteadyState, + StabilityStatusStabilizing, + } +} + const ( // TargetTypeContainerInstance is a TargetType enum value TargetTypeContainerInstance = "container-instance" ) +// TargetType_Values returns all elements of the TargetType enum +func TargetType_Values() []string { + return []string{ + TargetTypeContainerInstance, + } +} + const ( // TaskDefinitionFamilyStatusActive is a TaskDefinitionFamilyStatus enum value TaskDefinitionFamilyStatusActive = "ACTIVE" @@ -20246,16 +20947,39 @@ const ( TaskDefinitionFamilyStatusAll = "ALL" ) +// TaskDefinitionFamilyStatus_Values returns all elements of the TaskDefinitionFamilyStatus enum +func TaskDefinitionFamilyStatus_Values() []string { + return []string{ + TaskDefinitionFamilyStatusActive, + TaskDefinitionFamilyStatusInactive, + TaskDefinitionFamilyStatusAll, + } +} + const ( // TaskDefinitionFieldTags is a TaskDefinitionField enum value TaskDefinitionFieldTags = "TAGS" ) +// TaskDefinitionField_Values returns all elements of the TaskDefinitionField enum +func TaskDefinitionField_Values() []string { + return []string{ + TaskDefinitionFieldTags, + } +} + const ( // TaskDefinitionPlacementConstraintTypeMemberOf is a TaskDefinitionPlacementConstraintType enum value TaskDefinitionPlacementConstraintTypeMemberOf = "memberOf" ) +// TaskDefinitionPlacementConstraintType_Values returns all elements of the TaskDefinitionPlacementConstraintType enum +func TaskDefinitionPlacementConstraintType_Values() []string { + return []string{ + TaskDefinitionPlacementConstraintTypeMemberOf, + } +} + const ( // TaskDefinitionStatusActive is a TaskDefinitionStatus enum value TaskDefinitionStatusActive = "ACTIVE" @@ -20264,16 +20988,38 @@ const ( TaskDefinitionStatusInactive = "INACTIVE" ) +// TaskDefinitionStatus_Values returns all elements of the TaskDefinitionStatus enum +func TaskDefinitionStatus_Values() []string { + return []string{ + TaskDefinitionStatusActive, + TaskDefinitionStatusInactive, + } +} + const ( // TaskFieldTags is a TaskField enum value TaskFieldTags = "TAGS" ) +// TaskField_Values returns all elements of the TaskField enum +func TaskField_Values() []string { + return []string{ + TaskFieldTags, + } +} + const ( // TaskSetFieldTags is a TaskSetField enum value TaskSetFieldTags = "TAGS" ) +// TaskSetField_Values returns all elements of the TaskSetField enum +func TaskSetField_Values() []string { + return []string{ + TaskSetFieldTags, + } +} + const ( // TaskStopCodeTaskFailedToStart is a TaskStopCode enum value TaskStopCodeTaskFailedToStart = "TaskFailedToStart" @@ -20285,6 +21031,15 @@ const ( TaskStopCodeUserInitiated = "UserInitiated" ) +// TaskStopCode_Values returns all elements of the TaskStopCode enum +func TaskStopCode_Values() []string { + return []string{ + TaskStopCodeTaskFailedToStart, + TaskStopCodeEssentialContainerExited, + TaskStopCodeUserInitiated, + } +} + const ( // TransportProtocolTcp is a TransportProtocol enum value TransportProtocolTcp = "tcp" @@ -20293,6 +21048,14 @@ const ( TransportProtocolUdp = "udp" ) +// TransportProtocol_Values returns all elements of the TransportProtocol enum +func TransportProtocol_Values() []string { + return []string{ + TransportProtocolTcp, + TransportProtocolUdp, + } +} + const ( // UlimitNameCore is a UlimitName enum value UlimitNameCore = "core" @@ -20339,3 +21102,24 @@ const ( // UlimitNameStack is a UlimitName enum value UlimitNameStack = "stack" ) + +// UlimitName_Values returns all elements of the UlimitName enum +func UlimitName_Values() []string { + return []string{ + UlimitNameCore, + UlimitNameCpu, + UlimitNameData, + UlimitNameFsize, + UlimitNameLocks, + UlimitNameMemlock, + UlimitNameMsgqueue, + UlimitNameNice, + UlimitNameNofile, + UlimitNameNproc, + UlimitNameRss, + UlimitNameRtprio, + UlimitNameRttime, + UlimitNameSigpending, + UlimitNameStack, + } +} 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 c2bb5354400..32d25cdd2d3 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 @@ -85,6 +85,9 @@ func (c *EFS) CreateAccessPointRequest(input *CreateAccessPointInput) (req *requ // Returned if the access point you are trying to create already exists, with // the creation token you provided in the request. // +// * IncorrectFileSystemLifeCycleState +// Returned if the file system's lifecycle state is not "available". +// // * InternalServerError // Returned if an error occurred on the server side. // @@ -1248,6 +1251,101 @@ func (c *EFS) DescribeAccessPointsPagesWithContext(ctx aws.Context, input *Descr return p.Err() } +const opDescribeBackupPolicy = "DescribeBackupPolicy" + +// DescribeBackupPolicyRequest generates a "aws/request.Request" representing the +// client's request for the DescribeBackupPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeBackupPolicy for more information on using the DescribeBackupPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeBackupPolicyRequest method. +// req, resp := client.DescribeBackupPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DescribeBackupPolicy +func (c *EFS) DescribeBackupPolicyRequest(input *DescribeBackupPolicyInput) (req *request.Request, output *DescribeBackupPolicyOutput) { + op := &request.Operation{ + Name: opDescribeBackupPolicy, + HTTPMethod: "GET", + HTTPPath: "/2015-02-01/file-systems/{FileSystemId}/backup-policy", + } + + if input == nil { + input = &DescribeBackupPolicyInput{} + } + + output = &DescribeBackupPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeBackupPolicy API operation for Amazon Elastic File System. +// +// Returns the backup policy for the specified EFS file 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 Amazon Elastic File System's +// API operation DescribeBackupPolicy for usage and error information. +// +// Returned Error Types: +// * BadRequest +// Returned if the request is malformed or contains an error such as an invalid +// parameter value or a missing required parameter. +// +// * FileSystemNotFound +// Returned if the specified FileSystemId value doesn't exist in the requester's +// AWS account. +// +// * InternalServerError +// Returned if an error occurred on the server side. +// +// * PolicyNotFound +// Returned if the default file system policy is in effect for the EFS file +// system specified. +// +// * ValidationException +// Returned if the AWS Backup service is not available in the region that the +// request was made. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/DescribeBackupPolicy +func (c *EFS) DescribeBackupPolicy(input *DescribeBackupPolicyInput) (*DescribeBackupPolicyOutput, error) { + req, out := c.DescribeBackupPolicyRequest(input) + return out, req.Send() +} + +// DescribeBackupPolicyWithContext is the same as DescribeBackupPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeBackupPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeBackupPolicyWithContext(ctx aws.Context, input *DescribeBackupPolicyInput, opts ...request.Option) (*DescribeBackupPolicyOutput, error) { + req, out := c.DescribeBackupPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeFileSystemPolicy = "DescribeFileSystemPolicy" // DescribeFileSystemPolicyRequest generates a "aws/request.Request" representing the @@ -2231,6 +2329,101 @@ func (c *EFS) ModifyMountTargetSecurityGroupsWithContext(ctx aws.Context, input return out, req.Send() } +const opPutBackupPolicy = "PutBackupPolicy" + +// PutBackupPolicyRequest generates a "aws/request.Request" representing the +// client's request for the PutBackupPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutBackupPolicy for more information on using the PutBackupPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutBackupPolicyRequest method. +// req, resp := client.PutBackupPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/PutBackupPolicy +func (c *EFS) PutBackupPolicyRequest(input *PutBackupPolicyInput) (req *request.Request, output *PutBackupPolicyOutput) { + op := &request.Operation{ + Name: opPutBackupPolicy, + HTTPMethod: "PUT", + HTTPPath: "/2015-02-01/file-systems/{FileSystemId}/backup-policy", + } + + if input == nil { + input = &PutBackupPolicyInput{} + } + + output = &PutBackupPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// PutBackupPolicy API operation for Amazon Elastic File System. +// +// Updates the file system's backup policy. Use this action to start or stop +// automatic backups of the file 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 Amazon Elastic File System's +// API operation PutBackupPolicy for usage and error information. +// +// Returned Error Types: +// * BadRequest +// Returned if the request is malformed or contains an error such as an invalid +// parameter value or a missing required parameter. +// +// * FileSystemNotFound +// Returned if the specified FileSystemId value doesn't exist in the requester's +// AWS account. +// +// * IncorrectFileSystemLifeCycleState +// Returned if the file system's lifecycle state is not "available". +// +// * InternalServerError +// Returned if an error occurred on the server side. +// +// * ValidationException +// Returned if the AWS Backup service is not available in the region that the +// request was made. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticfilesystem-2015-02-01/PutBackupPolicy +func (c *EFS) PutBackupPolicy(input *PutBackupPolicyInput) (*PutBackupPolicyOutput, error) { + req, out := c.PutBackupPolicyRequest(input) + return out, req.Send() +} + +// PutBackupPolicyWithContext is the same as PutBackupPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutBackupPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) PutBackupPolicyWithContext(ctx aws.Context, input *PutBackupPolicyInput, opts ...request.Option) (*PutBackupPolicyOutput, error) { + req, out := c.PutBackupPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opPutFileSystemPolicy = "PutFileSystemPolicy" // PutFileSystemPolicyRequest generates a "aws/request.Request" representing the @@ -3037,6 +3230,54 @@ func (s *AccessPointNotFound) RequestID() string { return s.RespMetadata.RequestID } +// The backup policy for the file system, showing the curent status. If ENABLED, +// the file system is being backed up. +type BackupPolicy struct { + _ struct{} `type:"structure"` + + // Describes the status of the file system's backup policy. + // + // * ENABLED - EFS is automatically backing up the file system. + // + // * ENABLING - EFS is turning on automatic backups for the file system. + // + // * DISABLED - automatic back ups are turned off for the file system. + // + // * DISABLED - EFS is turning off automatic backups for the file system. + // + // Status is a required field + Status *string `type:"string" required:"true" enum:"Status"` +} + +// String returns the string representation +func (s BackupPolicy) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BackupPolicy) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *BackupPolicy) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "BackupPolicy"} + if s.Status == nil { + invalidParams.Add(request.NewErrParamRequired("Status")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetStatus sets the Status field's value. +func (s *BackupPolicy) SetStatus(v string) *BackupPolicy { + s.Status = &v + return s +} + // Returned if the request is malformed or contains an error such as an invalid // parameter value or a missing required parameter. type BadRequest struct { @@ -3343,7 +3584,7 @@ type CreateFileSystemInput struct { // // EFS accepts only symmetric CMKs. You cannot use asymmetric CMKs with EFS // file systems. - KmsKeyId *string `min:"1" type:"string"` + KmsKeyId *string `type:"string"` // The performance mode of the file system. We recommend generalPurpose performance // mode for most file systems. File systems using the maxIO performance mode @@ -3392,9 +3633,6 @@ func (s *CreateFileSystemInput) Validate() error { if s.CreationToken != nil && len(*s.CreationToken) < 1 { invalidParams.Add(request.NewErrParamMinLen("CreationToken", 1)) } - if s.KmsKeyId != nil && len(*s.KmsKeyId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("KmsKeyId", 1)) - } if s.ProvisionedThroughputInMibps != nil && *s.ProvisionedThroughputInMibps < 1 { invalidParams.Add(request.NewErrParamMinValue("ProvisionedThroughputInMibps", 1)) } @@ -3466,7 +3704,7 @@ type CreateMountTargetInput struct { FileSystemId *string `type:"string" required:"true"` // Valid IPv4 address within the address range of the specified subnet. - IpAddress *string `type:"string"` + IpAddress *string `min:"7" type:"string"` // Up to five VPC security group IDs, of the form sg-xxxxxxxx. These must be // for the same VPC as subnet specified. @@ -3475,7 +3713,7 @@ type CreateMountTargetInput struct { // The ID of the subnet to add the mount target in. // // SubnetId is a required field - SubnetId *string `type:"string" required:"true"` + SubnetId *string `min:"15" type:"string" required:"true"` } // String returns the string representation @@ -3494,9 +3732,15 @@ func (s *CreateMountTargetInput) Validate() error { if s.FileSystemId == nil { invalidParams.Add(request.NewErrParamRequired("FileSystemId")) } + if s.IpAddress != nil && len(*s.IpAddress) < 7 { + invalidParams.Add(request.NewErrParamMinLen("IpAddress", 7)) + } if s.SubnetId == nil { invalidParams.Add(request.NewErrParamRequired("SubnetId")) } + if s.SubnetId != nil && len(*s.SubnetId) < 15 { + invalidParams.Add(request.NewErrParamMinLen("SubnetId", 15)) + } if invalidParams.Len() > 0 { return invalidParams @@ -3856,7 +4100,7 @@ type DeleteMountTargetInput struct { // The ID of the mount target to delete (String). // // MountTargetId is a required field - MountTargetId *string `location:"uri" locationName:"MountTargetId" type:"string" required:"true"` + MountTargetId *string `location:"uri" locationName:"MountTargetId" min:"13" type:"string" required:"true"` } // String returns the string representation @@ -3875,8 +4119,8 @@ func (s *DeleteMountTargetInput) Validate() error { if s.MountTargetId == nil { invalidParams.Add(request.NewErrParamRequired("MountTargetId")) } - if s.MountTargetId != nil && len(*s.MountTargetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MountTargetId", 1)) + if s.MountTargetId != nil && len(*s.MountTargetId) < 13 { + invalidParams.Add(request.NewErrParamMinLen("MountTargetId", 13)) } if invalidParams.Len() > 0 { @@ -4139,6 +4383,71 @@ func (s *DescribeAccessPointsOutput) SetNextToken(v string) *DescribeAccessPoint return s } +type DescribeBackupPolicyInput struct { + _ struct{} `type:"structure"` + + // Specifies which EFS file system to retrieve the BackupPolicy for. + // + // FileSystemId is a required field + FileSystemId *string `location:"uri" locationName:"FileSystemId" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeBackupPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeBackupPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeBackupPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeBackupPolicyInput"} + if s.FileSystemId == nil { + invalidParams.Add(request.NewErrParamRequired("FileSystemId")) + } + if s.FileSystemId != nil && len(*s.FileSystemId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("FileSystemId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetFileSystemId sets the FileSystemId field's value. +func (s *DescribeBackupPolicyInput) SetFileSystemId(v string) *DescribeBackupPolicyInput { + s.FileSystemId = &v + return s +} + +type DescribeBackupPolicyOutput struct { + _ struct{} `type:"structure"` + + // Describes the file system's backup policy, indicating whether automatic backups + // are turned on or off.. + BackupPolicy *BackupPolicy `type:"structure"` +} + +// String returns the string representation +func (s DescribeBackupPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeBackupPolicyOutput) GoString() string { + return s.String() +} + +// SetBackupPolicy sets the BackupPolicy field's value. +func (s *DescribeBackupPolicyOutput) SetBackupPolicy(v *BackupPolicy) *DescribeBackupPolicyOutput { + s.BackupPolicy = v + return s +} + type DescribeFileSystemPolicyInput struct { _ struct{} `type:"structure"` @@ -4226,7 +4535,7 @@ type DescribeFileSystemsInput struct { // (Optional) Opaque pagination token returned from a previous DescribeFileSystems // operation (String). If present, specifies to continue the list from where // the returning call had left off. - Marker *string `location:"querystring" locationName:"Marker" type:"string"` + Marker *string `location:"querystring" locationName:"Marker" min:"1" type:"string"` // (Optional) Specifies the maximum number of file systems to return in the // response (integer). This number is automatically set to 100. The response @@ -4250,6 +4559,9 @@ func (s *DescribeFileSystemsInput) Validate() error { if s.CreationToken != nil && len(*s.CreationToken) < 1 { invalidParams.Add(request.NewErrParamMinLen("CreationToken", 1)) } + if s.Marker != nil && len(*s.Marker) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) + } if s.MaxItems != nil && *s.MaxItems < 1 { invalidParams.Add(request.NewErrParamMinValue("MaxItems", 1)) } @@ -4291,11 +4603,11 @@ type DescribeFileSystemsOutput struct { FileSystems []*FileSystemDescription `type:"list"` // Present if provided by caller in the request (String). - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // Present if there are more file systems than returned in the response (String). // You can use the NextMarker in the subsequent request to fetch the descriptions. - NextMarker *string `type:"string"` + NextMarker *string `min:"1" type:"string"` } // String returns the string representation @@ -4398,7 +4710,7 @@ type DescribeMountTargetSecurityGroupsInput struct { // The ID of the mount target whose security groups you want to retrieve. // // MountTargetId is a required field - MountTargetId *string `location:"uri" locationName:"MountTargetId" type:"string" required:"true"` + MountTargetId *string `location:"uri" locationName:"MountTargetId" min:"13" type:"string" required:"true"` } // String returns the string representation @@ -4417,8 +4729,8 @@ func (s *DescribeMountTargetSecurityGroupsInput) Validate() error { if s.MountTargetId == nil { invalidParams.Add(request.NewErrParamRequired("MountTargetId")) } - if s.MountTargetId != nil && len(*s.MountTargetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MountTargetId", 1)) + if s.MountTargetId != nil && len(*s.MountTargetId) < 13 { + invalidParams.Add(request.NewErrParamMinLen("MountTargetId", 13)) } if invalidParams.Len() > 0 { @@ -4475,7 +4787,7 @@ type DescribeMountTargetsInput struct { // (Optional) Opaque pagination token returned from a previous DescribeMountTargets // operation (String). If present, it specifies to continue the list from where // the previous returning call left off. - Marker *string `location:"querystring" locationName:"Marker" type:"string"` + Marker *string `location:"querystring" locationName:"Marker" min:"1" type:"string"` // (Optional) Maximum number of mount targets to return in the response. Currently, // this number is automatically set to 10, and other values are ignored. The @@ -4485,7 +4797,7 @@ type DescribeMountTargetsInput struct { // (Optional) ID of the mount target that you want to have described (String). // It must be included in your request if FileSystemId is not included. Accepts // either a mount target ID or ARN as input. - MountTargetId *string `location:"querystring" locationName:"MountTargetId" type:"string"` + MountTargetId *string `location:"querystring" locationName:"MountTargetId" min:"13" type:"string"` } // String returns the string representation @@ -4501,9 +4813,15 @@ func (s DescribeMountTargetsInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeMountTargetsInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "DescribeMountTargetsInput"} + if s.Marker != nil && len(*s.Marker) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) + } if s.MaxItems != nil && *s.MaxItems < 1 { invalidParams.Add(request.NewErrParamMinValue("MaxItems", 1)) } + if s.MountTargetId != nil && len(*s.MountTargetId) < 13 { + invalidParams.Add(request.NewErrParamMinLen("MountTargetId", 13)) + } if invalidParams.Len() > 0 { return invalidParams @@ -4546,7 +4864,7 @@ type DescribeMountTargetsOutput struct { // If the request included the Marker, the response returns that value in this // field. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // Returns the file system's mount targets as an array of MountTargetDescription // objects. @@ -4555,7 +4873,7 @@ type DescribeMountTargetsOutput struct { // If a value is present, there are more mount targets to return. In a subsequent // request, you can provide Marker in your request with this value to retrieve // the next set of mount targets. - NextMarker *string `type:"string"` + NextMarker *string `min:"1" type:"string"` } // String returns the string representation @@ -4597,7 +4915,7 @@ type DescribeTagsInput struct { // (Optional) An opaque pagination token returned from a previous DescribeTags // operation (String). If present, it specifies to continue the list from where // the previous call left off. - Marker *string `location:"querystring" locationName:"Marker" type:"string"` + Marker *string `location:"querystring" locationName:"Marker" min:"1" type:"string"` // (Optional) The maximum number of file system tags to return in the response. // Currently, this number is automatically set to 100, and other values are @@ -4625,6 +4943,9 @@ func (s *DescribeTagsInput) Validate() error { if s.FileSystemId != nil && len(*s.FileSystemId) < 1 { invalidParams.Add(request.NewErrParamMinLen("FileSystemId", 1)) } + if s.Marker != nil && len(*s.Marker) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) + } if s.MaxItems != nil && *s.MaxItems < 1 { invalidParams.Add(request.NewErrParamMinValue("MaxItems", 1)) } @@ -4658,12 +4979,12 @@ type DescribeTagsOutput struct { // If the request included a Marker, the response returns that value in this // field. - Marker *string `type:"string"` + Marker *string `min:"1" type:"string"` // If a value is present, there are more tags to return. In a subsequent request, // you can provide the value of NextMarker as the value of the Marker parameter // in your next request to retrieve the next set of tags. - NextMarker *string `type:"string"` + NextMarker *string `min:"1" type:"string"` // Returns tags associated with the file system as an array of Tag objects. // @@ -4779,6 +5100,10 @@ type FileSystemDescription struct { // A Boolean value that, if true, indicates that the file system is encrypted. Encrypted *bool `type:"boolean"` + // The Amazon Resource Name (ARN) for the EFS file system, in the format arn:aws:elasticfilesystem:region:account-id:file-system/file-system-id + // . Example with sample data: arn:aws:elasticfilesystem:us-west-2:1111333322228888:file-system/fs-01234567 + FileSystemArn *string `type:"string"` + // The ID of the file system, assigned by Amazon EFS. // // FileSystemId is a required field @@ -4786,7 +5111,7 @@ type FileSystemDescription struct { // The ID of an AWS Key Management Service (AWS KMS) customer master key (CMK) // that was used to protect the encrypted file system. - KmsKeyId *string `min:"1" type:"string"` + KmsKeyId *string `type:"string"` // The lifecycle phase of the file system. // @@ -4878,6 +5203,12 @@ func (s *FileSystemDescription) SetEncrypted(v bool) *FileSystemDescription { return s } +// SetFileSystemArn sets the FileSystemArn field's value. +func (s *FileSystemDescription) SetFileSystemArn(v string) *FileSystemDescription { + s.FileSystemArn = &v + return s +} + // SetFileSystemId sets the FileSystemId field's value. func (s *FileSystemDescription) SetFileSystemId(v string) *FileSystemDescription { s.FileSystemId = &v @@ -5677,7 +6008,7 @@ type ModifyMountTargetSecurityGroupsInput struct { // The ID of the mount target whose security groups you want to modify. // // MountTargetId is a required field - MountTargetId *string `location:"uri" locationName:"MountTargetId" type:"string" required:"true"` + MountTargetId *string `location:"uri" locationName:"MountTargetId" min:"13" type:"string" required:"true"` // An array of up to five VPC security group IDs. SecurityGroups []*string `type:"list"` @@ -5699,8 +6030,8 @@ func (s *ModifyMountTargetSecurityGroupsInput) Validate() error { if s.MountTargetId == nil { invalidParams.Add(request.NewErrParamRequired("MountTargetId")) } - if s.MountTargetId != nil && len(*s.MountTargetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MountTargetId", 1)) + if s.MountTargetId != nil && len(*s.MountTargetId) < 13 { + invalidParams.Add(request.NewErrParamMinLen("MountTargetId", 13)) } if invalidParams.Len() > 0 { @@ -5816,7 +6147,7 @@ type MountTargetDescription struct { FileSystemId *string `type:"string" required:"true"` // Address at which the file system can be mounted by using the mount target. - IpAddress *string `type:"string"` + IpAddress *string `min:"7" type:"string"` // Lifecycle state of the mount target. // @@ -5826,7 +6157,7 @@ type MountTargetDescription struct { // System-assigned mount target ID. // // MountTargetId is a required field - MountTargetId *string `type:"string" required:"true"` + MountTargetId *string `min:"13" type:"string" required:"true"` // The ID of the network interface that Amazon EFS created when it created the // mount target. @@ -5838,7 +6169,10 @@ type MountTargetDescription struct { // The ID of the mount target's subnet. // // SubnetId is a required field - SubnetId *string `type:"string" required:"true"` + SubnetId *string `min:"15" type:"string" required:"true"` + + // The Virtual Private Cloud (VPC) ID that the mount target is configured in. + VpcId *string `type:"string"` } // String returns the string representation @@ -5905,6 +6239,12 @@ func (s *MountTargetDescription) SetSubnetId(v string) *MountTargetDescription { return s } +// SetVpcId sets the VpcId field's value. +func (s *MountTargetDescription) SetVpcId(v string) *MountTargetDescription { + s.VpcId = &v + return s +} + // Returned if there is no mount target with the specified ID found in the caller's // account. type MountTargetNotFound struct { @@ -6214,6 +6554,90 @@ func (s *PosixUser) SetUid(v int64) *PosixUser { return s } +type PutBackupPolicyInput struct { + _ struct{} `type:"structure"` + + // The backup policy included in the PutBackupPolicy request. + // + // BackupPolicy is a required field + BackupPolicy *BackupPolicy `type:"structure" required:"true"` + + // Specifies which EFS file system to update the backup policy for. + // + // FileSystemId is a required field + FileSystemId *string `location:"uri" locationName:"FileSystemId" type:"string" required:"true"` +} + +// String returns the string representation +func (s PutBackupPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutBackupPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutBackupPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutBackupPolicyInput"} + if s.BackupPolicy == nil { + invalidParams.Add(request.NewErrParamRequired("BackupPolicy")) + } + if s.FileSystemId == nil { + invalidParams.Add(request.NewErrParamRequired("FileSystemId")) + } + if s.FileSystemId != nil && len(*s.FileSystemId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("FileSystemId", 1)) + } + if s.BackupPolicy != nil { + if err := s.BackupPolicy.Validate(); err != nil { + invalidParams.AddNested("BackupPolicy", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBackupPolicy sets the BackupPolicy field's value. +func (s *PutBackupPolicyInput) SetBackupPolicy(v *BackupPolicy) *PutBackupPolicyInput { + s.BackupPolicy = v + return s +} + +// SetFileSystemId sets the FileSystemId field's value. +func (s *PutBackupPolicyInput) SetFileSystemId(v string) *PutBackupPolicyInput { + s.FileSystemId = &v + return s +} + +type PutBackupPolicyOutput struct { + _ struct{} `type:"structure"` + + // Describes the file system's backup policy, indicating whether automatic backups + // are turned on or off.. + BackupPolicy *BackupPolicy `type:"structure"` +} + +// String returns the string representation +func (s PutBackupPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutBackupPolicyOutput) GoString() string { + return s.String() +} + +// SetBackupPolicy sets the BackupPolicy field's value. +func (s *PutBackupPolicyOutput) SetBackupPolicy(v *BackupPolicy) *PutBackupPolicyOutput { + s.BackupPolicy = v + return s +} + type PutFileSystemPolicyInput struct { _ struct{} `type:"structure"` @@ -7119,6 +7543,10 @@ type UpdateFileSystemOutput struct { // A Boolean value that, if true, indicates that the file system is encrypted. Encrypted *bool `type:"boolean"` + // The Amazon Resource Name (ARN) for the EFS file system, in the format arn:aws:elasticfilesystem:region:account-id:file-system/file-system-id + // . Example with sample data: arn:aws:elasticfilesystem:us-west-2:1111333322228888:file-system/fs-01234567 + FileSystemArn *string `type:"string"` + // The ID of the file system, assigned by Amazon EFS. // // FileSystemId is a required field @@ -7126,7 +7554,7 @@ type UpdateFileSystemOutput struct { // The ID of an AWS Key Management Service (AWS KMS) customer master key (CMK) // that was used to protect the encrypted file system. - KmsKeyId *string `min:"1" type:"string"` + KmsKeyId *string `type:"string"` // The lifecycle phase of the file system. // @@ -7218,6 +7646,12 @@ func (s *UpdateFileSystemOutput) SetEncrypted(v bool) *UpdateFileSystemOutput { return s } +// SetFileSystemArn sets the FileSystemArn field's value. +func (s *UpdateFileSystemOutput) SetFileSystemArn(v string) *UpdateFileSystemOutput { + s.FileSystemArn = &v + return s +} + // SetFileSystemId sets the FileSystemId field's value. func (s *UpdateFileSystemOutput) SetFileSystemId(v string) *UpdateFileSystemOutput { s.FileSystemId = &v @@ -7284,6 +7718,66 @@ func (s *UpdateFileSystemOutput) SetThroughputMode(v string) *UpdateFileSystemOu return s } +// Returned if the AWS Backup service is not available in the region that the +// request was made. +type ValidationException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // ErrorCode is a required field + ErrorCode *string `min:"1" type:"string" required:"true"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s ValidationException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationException) GoString() string { + return s.String() +} + +func newErrorValidationException(v protocol.ResponseMetadata) error { + return &ValidationException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ValidationException) Code() string { + return "ValidationException" +} + +// Message returns the exception's message. +func (s *ValidationException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ValidationException) OrigErr() error { + return nil +} + +func (s *ValidationException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ValidationException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ValidationException) RequestID() string { + return s.RespMetadata.RequestID +} + const ( // LifeCycleStateCreating is a LifeCycleState enum value LifeCycleStateCreating = "creating" @@ -7301,6 +7795,17 @@ const ( LifeCycleStateDeleted = "deleted" ) +// LifeCycleState_Values returns all elements of the LifeCycleState enum +func LifeCycleState_Values() []string { + return []string{ + LifeCycleStateCreating, + LifeCycleStateAvailable, + LifeCycleStateUpdating, + LifeCycleStateDeleting, + LifeCycleStateDeleted, + } +} + const ( // PerformanceModeGeneralPurpose is a PerformanceMode enum value PerformanceModeGeneralPurpose = "generalPurpose" @@ -7309,6 +7814,38 @@ const ( PerformanceModeMaxIo = "maxIO" ) +// PerformanceMode_Values returns all elements of the PerformanceMode enum +func PerformanceMode_Values() []string { + return []string{ + PerformanceModeGeneralPurpose, + PerformanceModeMaxIo, + } +} + +const ( + // StatusEnabled is a Status enum value + StatusEnabled = "ENABLED" + + // StatusEnabling is a Status enum value + StatusEnabling = "ENABLING" + + // StatusDisabled is a Status enum value + StatusDisabled = "DISABLED" + + // StatusDisabling is a Status enum value + StatusDisabling = "DISABLING" +) + +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusEnabled, + StatusEnabling, + StatusDisabled, + StatusDisabling, + } +} + const ( // ThroughputModeBursting is a ThroughputMode enum value ThroughputModeBursting = "bursting" @@ -7317,6 +7854,14 @@ const ( ThroughputModeProvisioned = "provisioned" ) +// ThroughputMode_Values returns all elements of the ThroughputMode enum +func ThroughputMode_Values() []string { + return []string{ + ThroughputModeBursting, + ThroughputModeProvisioned, + } +} + const ( // TransitionToIARulesAfter7Days is a TransitionToIARules enum value TransitionToIARulesAfter7Days = "AFTER_7_DAYS" @@ -7333,3 +7878,14 @@ const ( // TransitionToIARulesAfter90Days is a TransitionToIARules enum value TransitionToIARulesAfter90Days = "AFTER_90_DAYS" ) + +// TransitionToIARules_Values returns all elements of the TransitionToIARules enum +func TransitionToIARules_Values() []string { + return []string{ + TransitionToIARulesAfter7Days, + TransitionToIARulesAfter14Days, + TransitionToIARulesAfter30Days, + TransitionToIARulesAfter60Days, + TransitionToIARulesAfter90Days, + } +} 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 bccb1f84ff2..7e2f36abb24 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 @@ -189,6 +189,13 @@ const ( // ErrCodeUnsupportedAvailabilityZone for service response error code // "UnsupportedAvailabilityZone". ErrCodeUnsupportedAvailabilityZone = "UnsupportedAvailabilityZone" + + // ErrCodeValidationException for service response error code + // "ValidationException". + // + // Returned if the AWS Backup service is not available in the region that the + // request was made. + ErrCodeValidationException = "ValidationException" ) var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ @@ -218,4 +225,5 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "ThroughputLimitExceeded": newErrorThroughputLimitExceeded, "TooManyRequests": newErrorTooManyRequests, "UnsupportedAvailabilityZone": newErrorUnsupportedAvailabilityZone, + "ValidationException": newErrorValidationException, } diff --git a/vendor/github.com/aws/aws-sdk-go/service/eks/api.go b/vendor/github.com/aws/aws-sdk-go/service/eks/api.go index 5c5f2e20ac1..8b0d8e0e1ec 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/eks/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/eks/api.go @@ -335,7 +335,9 @@ func (c *EKS) CreateNodegroupRequest(input *CreateNodegroupInput) (req *request. // Creates a managed worker node group for an Amazon EKS cluster. You can only // create a node group for your cluster that is equal to the current Kubernetes // version for the cluster. All node groups are created with the latest AMI -// release version for the respective minor Kubernetes version of the cluster. +// release version for the respective minor Kubernetes version of the cluster, +// unless you deploy a custom AMI using a launch template. For more information +// about using launch templates, see Launch template support (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html). // // An Amazon EKS managed node group is an Amazon EC2 Auto Scaling group and // associated Amazon EC2 instances that are managed by AWS for an Amazon EKS @@ -2352,11 +2354,18 @@ func (c *EKS) UpdateNodegroupVersionRequest(input *UpdateNodegroupVersionInput) // Updates the Kubernetes version or AMI version of an Amazon EKS managed node // group. // -// You can update to the latest available AMI version of a node group's current -// Kubernetes version by not specifying a Kubernetes version in the request. -// You can update to the latest AMI version of your cluster's current Kubernetes -// version by specifying your cluster's Kubernetes version in the request. For -// more information, see Amazon EKS-Optimized Linux AMI Versions (https://docs.aws.amazon.com/eks/latest/userguide/eks-linux-ami-versions.html) +// You can update a node group using a launch template only if the node group +// was originally deployed with a launch template. If you need to update a custom +// AMI in a node group that was deployed with a launch template, then update +// your custom AMI, specify the new ID in a new version of the launch template, +// and then update the node group to the new version of the launch template. +// +// If you update without a launch template, then you can update to the latest +// available AMI version of a node group's current Kubernetes version by not +// specifying a Kubernetes version in the request. You can update to the latest +// AMI version of your cluster's current Kubernetes version by specifying your +// cluster's Kubernetes version in the request. For more information, see Amazon +// EKS-Optimized Linux AMI Versions (https://docs.aws.amazon.com/eks/latest/userguide/eks-linux-ami-versions.html) // in the Amazon EKS User Guide. // // You cannot roll back a node group to an earlier Kubernetes version or AMI @@ -2795,8 +2804,8 @@ type CreateClusterInput struct { ResourcesVpcConfig *VpcConfigRequest `locationName:"resourcesVpcConfig" type:"structure" required:"true"` // The Amazon Resource Name (ARN) of the IAM role that provides permissions - // for Amazon EKS to make calls to other AWS API operations on your behalf. - // For more information, see Amazon EKS Service IAM Role (https://docs.aws.amazon.com/eks/latest/userguide/service_IAM_role.html) + // for the Kubernetes control plane to make calls to AWS API operations on your + // behalf. For more information, see Amazon EKS Service IAM Role (https://docs.aws.amazon.com/eks/latest/userguide/service_IAM_role.html) // in the Amazon EKS User Guide . // // RoleArn is a required field @@ -3068,7 +3077,11 @@ type CreateNodegroupInput struct { // The AMI type for your node group. GPU instance types should use the AL2_x86_64_GPU // AMI type, which uses the Amazon EKS-optimized Linux AMI with GPU support. // Non-GPU instances should use the AL2_x86_64 AMI type, which uses the Amazon - // EKS-optimized Linux AMI. + // EKS-optimized Linux AMI. If you specify launchTemplate, and your launch template + // uses a custom AMI, then don't specify amiType, or the node group deployment + // will fail. For more information about using launch templates with Amazon + // EKS, see Launch template support (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html) + // in the Amazon EKS User Guide. AmiType *string `locationName:"amiType" type:"string" enum:"AMITypes"` // Unique, case-sensitive identifier that you provide to ensure the idempotency @@ -3081,19 +3094,31 @@ type CreateNodegroupInput struct { ClusterName *string `location:"uri" locationName:"name" type:"string" required:"true"` // The root device disk size (in GiB) for your node group instances. The default - // disk size is 20 GiB. + // disk size is 20 GiB. If you specify launchTemplate, then don't specify diskSize, + // or the node group deployment will fail. For more information about using + // launch templates with Amazon EKS, see Launch template support (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html) + // in the Amazon EKS User Guide. DiskSize *int64 `locationName:"diskSize" type:"integer"` - // The instance type to use for your node group. Currently, you can specify - // a single instance type for a node group. The default value for this parameter - // is t3.medium. If you choose a GPU instance type, be sure to specify the AL2_x86_64_GPU - // with the amiType parameter. + // The instance type to use for your node group. You can specify a single instance + // type for a node group. The default value for instanceTypes is t3.medium. + // If you choose a GPU instance type, be sure to specify AL2_x86_64_GPU with + // the amiType parameter. If you specify launchTemplate, then don't specify + // instanceTypes, or the node group deployment will fail. For more information + // about using launch templates with Amazon EKS, see Launch template support + // (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html) + // in the Amazon EKS User Guide. InstanceTypes []*string `locationName:"instanceTypes" type:"list"` // The Kubernetes labels to be applied to the nodes in the node group when they // are created. Labels map[string]*string `locationName:"labels" type:"map"` + // An object representing a node group's launch template specification. If specified, + // then do not specify instanceTypes, diskSize, or remoteAccess. If specified, + // make sure that the launch template meets the requirements in launchTemplateSpecification. + LaunchTemplate *LaunchTemplateSpecification `locationName:"launchTemplate" type:"structure"` + // The Amazon Resource Name (ARN) of the IAM role to associate with your node // group. The Amazon EKS worker node kubelet daemon makes calls to AWS APIs // on your behalf. Worker nodes receive permissions for these API calls through @@ -3101,7 +3126,12 @@ type CreateNodegroupInput struct { // nodes and register them into a cluster, you must create an IAM role for those // worker nodes to use when they are launched. For more information, see Amazon // EKS Worker Node IAM Role (https://docs.aws.amazon.com/eks/latest/userguide/worker_node_IAM_role.html) - // in the Amazon EKS User Guide . + // in the Amazon EKS User Guide . If you specify launchTemplate, then don't + // specify IamInstanceProfile (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_IamInstanceProfile.html) + // in your launch template, or the node group deployment will fail. For more + // information about using launch templates with Amazon EKS, see Launch template + // support (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html) + // in the Amazon EKS User Guide. // // NodeRole is a required field NodeRole *string `locationName:"nodeRole" type:"string" required:"true"` @@ -3115,10 +3145,18 @@ type CreateNodegroupInput struct { // By default, the latest available AMI version for the node group's current // Kubernetes version is used. For more information, see Amazon EKS-Optimized // Linux AMI Versions (https://docs.aws.amazon.com/eks/latest/userguide/eks-linux-ami-versions.html) + // in the Amazon EKS User Guide. If you specify launchTemplate, and your launch + // template uses a custom AMI, then don't specify releaseVersion, or the node + // group deployment will fail. For more information about using launch templates + // with Amazon EKS, see Launch template support (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html) // in the Amazon EKS User Guide. ReleaseVersion *string `locationName:"releaseVersion" type:"string"` - // The remote access (SSH) configuration to use with your node group. + // The remote access (SSH) configuration to use with your node group. If you + // specify launchTemplate, then don't specify remoteAccess, or the node group + // deployment will fail. For more information about using launch templates with + // Amazon EKS, see Launch template support (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html) + // in the Amazon EKS User Guide. RemoteAccess *RemoteAccessConfig `locationName:"remoteAccess" type:"structure"` // The scaling configuration details for the Auto Scaling group that is created @@ -3128,7 +3166,11 @@ type CreateNodegroupInput struct { // The subnets to use for the Auto Scaling group that is created for your node // group. These subnets must have the tag key kubernetes.io/cluster/CLUSTER_NAME // with a value of shared, where CLUSTER_NAME is replaced with the name of your - // cluster. + // cluster. If you specify launchTemplate, then don't specify SubnetId (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateNetworkInterface.html) + // in your launch template, or the node group deployment will fail. For more + // information about using launch templates with Amazon EKS, see Launch template + // support (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html) + // in the Amazon EKS User Guide. // // Subnets is a required field Subnets []*string `locationName:"subnets" type:"list" required:"true"` @@ -3141,6 +3183,11 @@ type CreateNodegroupInput struct { // The Kubernetes version to use for your managed nodes. By default, the Kubernetes // version of the cluster is used, and this is the only accepted specified value. + // If you specify launchTemplate, and your launch template uses a custom AMI, + // then don't specify version, or the node group deployment will fail. For more + // information about using launch templates with Amazon EKS, see Launch template + // support (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html) + // in the Amazon EKS User Guide. Version *string `locationName:"version" type:"string"` } @@ -3223,6 +3270,12 @@ func (s *CreateNodegroupInput) SetLabels(v map[string]*string) *CreateNodegroupI return s } +// SetLaunchTemplate sets the LaunchTemplate field's value. +func (s *CreateNodegroupInput) SetLaunchTemplate(v *LaunchTemplateSpecification) *CreateNodegroupInput { + s.LaunchTemplate = v + return s +} + // SetNodeRole sets the NodeRole field's value. func (s *CreateNodegroupInput) SetNodeRole(v string) *CreateNodegroupInput { s.NodeRole = &v @@ -4250,6 +4303,14 @@ type Issue struct { // created. You may be able to revert to the version that Amazon EKS created // to recover. // + // * Ec2SubnetInvalidConfiguration: One or more Amazon EC2 subnets specified + // for a node group do not automatically assign public IP addresses to instances + // launched into it. If you want your instances to be assigned a public IP + // address, then you need to enable the auto-assign public IP address setting + // for the subnet. See Modifying the public IPv4 addressing attribute for + // your subnet (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-ip-addressing.html#subnet-public-ip) + // in the Amazon VPC User Guide. + // // * IamInstanceProfileNotFound: We couldn't find the IAM instance profile // for your managed node group. You may be able to recreate an instance profile // with the same settings to recover. @@ -4316,6 +4377,61 @@ func (s *Issue) SetResourceIds(v []*string) *Issue { return s } +// An object representing a node group launch template specification. The launch +// template cannot include SubnetId (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateNetworkInterface.html), +// IamInstanceProfile (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_IamInstanceProfile.html), +// RequestSpotInstances (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RequestSpotInstances.html), +// HibernationOptions (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_HibernationOptionsRequest.html), +// or TerminateInstances (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_TerminateInstances.html), +// or the node group deployment or update will fail. For more information about +// launch templates, see CreateLaunchTemplate (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateLaunchTemplate.html) +// in the Amazon EC2 API Reference. For more information about using launch +// templates with Amazon EKS, see Launch template support (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html) +// in the Amazon EKS User Guide. +// +// Specify either name or id, but not both. +type LaunchTemplateSpecification struct { + _ struct{} `type:"structure"` + + // The ID of the launch template. + Id *string `locationName:"id" type:"string"` + + // The name of the launch template. + Name *string `locationName:"name" type:"string"` + + // The version of the launch template to use. If no version is specified, then + // the template's default version is used. + Version *string `locationName:"version" type:"string"` +} + +// String returns the string representation +func (s LaunchTemplateSpecification) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s LaunchTemplateSpecification) GoString() string { + return s.String() +} + +// SetId sets the Id field's value. +func (s *LaunchTemplateSpecification) SetId(v string) *LaunchTemplateSpecification { + s.Id = &v + return s +} + +// SetName sets the Name field's value. +func (s *LaunchTemplateSpecification) SetName(v string) *LaunchTemplateSpecification { + s.Name = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *LaunchTemplateSpecification) SetVersion(v string) *LaunchTemplateSpecification { + s.Version = &v + return s +} + type ListClustersInput struct { _ struct{} `type:"structure"` @@ -4868,10 +4984,9 @@ func (s *Logging) SetClusterLogging(v []*LogSetup) *Logging { type Nodegroup struct { _ struct{} `type:"structure"` - // The AMI type associated with your node group. GPU instance types should use - // the AL2_x86_64_GPU AMI type, which uses the Amazon EKS-optimized Linux AMI - // with GPU support. Non-GPU instances should use the AL2_x86_64 AMI type, which - // uses the Amazon EKS-optimized Linux AMI. + // If the node group was deployed using a launch template with a custom AMI, + // then this is CUSTOM. For node groups that weren't deployed using a launch + // template, this is the AMI type that was specified in the node group configuration. AmiType *string `locationName:"amiType" type:"string" enum:"AMITypes"` // The name of the cluster that the managed node group resides in. @@ -4880,15 +4995,18 @@ type Nodegroup struct { // The Unix epoch timestamp in seconds for when the managed node group was created. CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - // The root device disk size (in GiB) for your node group instances. The default - // disk size is 20 GiB. + // If the node group wasn't deployed with a launch template, then this is the + // disk size in the node group configuration. If the node group was deployed + // with a launch template, then diskSize is null. DiskSize *int64 `locationName:"diskSize" type:"integer"` // The health status of the node group. If there are issues with your node group's // health, they are listed here. Health *NodegroupHealth `locationName:"health" type:"structure"` - // The instance types associated with your node group. + // If the node group wasn't deployed with a launch template, then this is the + // instance type that is associated with the node group. If the node group was + // deployed with a launch template, then instanceTypes is null. InstanceTypes []*string `locationName:"instanceTypes" type:"list"` // The Kubernetes labels applied to the nodes in the node group. @@ -4897,6 +5015,10 @@ type Nodegroup struct { // may be other Kubernetes labels applied to the nodes in this group. Labels map[string]*string `locationName:"labels" type:"map"` + // If a launch template was used to create the node group, then this is the + // launch template that was used. + LaunchTemplate *LaunchTemplateSpecification `locationName:"launchTemplate" type:"structure"` + // The Unix epoch timestamp in seconds for when the managed node group was last // modified. ModifiedAt *time.Time `locationName:"modifiedAt" type:"timestamp"` @@ -4904,10 +5026,7 @@ type Nodegroup struct { // The IAM role associated with your node group. The Amazon EKS worker node // kubelet daemon makes calls to AWS APIs on your behalf. Worker nodes receive // permissions for these API calls through an IAM instance profile and associated - // policies. Before you can launch worker nodes and register them into a cluster, - // you must create an IAM role for those worker nodes to use when they are launched. - // For more information, see Amazon EKS Worker Node IAM Role (https://docs.aws.amazon.com/eks/latest/userguide/worker_node_IAM_role.html) - // in the Amazon EKS User Guide . + // policies. NodeRole *string `locationName:"nodeRole" type:"string"` // The Amazon Resource Name (ARN) associated with the managed node group. @@ -4916,12 +5035,15 @@ type Nodegroup struct { // The name associated with an Amazon EKS managed node group. NodegroupName *string `locationName:"nodegroupName" type:"string"` - // The AMI version of the managed node group. For more information, see Amazon - // EKS-Optimized Linux AMI Versions (https://docs.aws.amazon.com/eks/latest/userguide/eks-linux-ami-versions.html) - // in the Amazon EKS User Guide. + // If the node group was deployed using a launch template with a custom AMI, + // then this is the AMI ID that was specified in the launch template. For node + // groups that weren't deployed using a launch template, this is the version + // of the Amazon EKS-optimized AMI that the node group was deployed with. ReleaseVersion *string `locationName:"releaseVersion" type:"string"` - // The remote access (SSH) configuration that is associated with the node group. + // If the node group wasn't deployed with a launch template, then this is the + // remote access configuration that is associated with the node group. If the + // node group was deployed with a launch template, then remoteAccess is null. RemoteAccess *RemoteAccessConfig `locationName:"remoteAccess" type:"structure"` // The resources associated with the node group, such as Auto Scaling groups @@ -4935,9 +5057,8 @@ type Nodegroup struct { // The current status of the managed node group. Status *string `locationName:"status" type:"string" enum:"NodegroupStatus"` - // The subnets allowed for the Auto Scaling group that is associated with your - // node group. These subnets must have the following tag: kubernetes.io/cluster/CLUSTER_NAME, - // where CLUSTER_NAME is replaced with the name of your cluster. + // The subnets that were specified for the Auto Scaling group that is associated + // with your node group. Subnets []*string `locationName:"subnets" type:"list"` // The metadata applied to the node group to assist with categorization and @@ -5002,6 +5123,12 @@ func (s *Nodegroup) SetLabels(v map[string]*string) *Nodegroup { return s } +// SetLaunchTemplate sets the LaunchTemplate field's value. +func (s *Nodegroup) SetLaunchTemplate(v *LaunchTemplateSpecification) *Nodegroup { + s.LaunchTemplate = v + return s +} + // SetModifiedAt sets the ModifiedAt field's value. func (s *Nodegroup) SetModifiedAt(v time.Time) *Nodegroup { s.ModifiedAt = &v @@ -5134,7 +5261,8 @@ func (s *NodegroupResources) SetRemoteAccessSecurityGroup(v string) *NodegroupRe } // An object representing the scaling configuration details for the Auto Scaling -// group that is associated with your node group. +// group that is associated with your node group. If you specify a value for +// any property, then you must specify values for all of the properties. type NodegroupScalingConfig struct { _ struct{} `type:"structure"` @@ -6300,6 +6428,11 @@ type UpdateNodegroupVersionInput struct { // old node whether or not any pods are running on the node. Force *bool `locationName:"force" type:"boolean"` + // An object representing a node group's launch template specification. You + // can only update a node group using a launch template if the node group was + // originally deployed with a launch template. + LaunchTemplate *LaunchTemplateSpecification `locationName:"launchTemplate" type:"structure"` + // The name of the managed node group to update. // // NodegroupName is a required field @@ -6309,13 +6442,21 @@ type UpdateNodegroupVersionInput struct { // default, the latest available AMI version for the node group's Kubernetes // version is used. For more information, see Amazon EKS-Optimized Linux AMI // Versions (https://docs.aws.amazon.com/eks/latest/userguide/eks-linux-ami-versions.html) + // in the Amazon EKS User Guide. If you specify launchTemplate, and your launch + // template uses a custom AMI, then don't specify releaseVersion, or the node + // group update will fail. For more information about using launch templates + // with Amazon EKS, see Launch template support (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html) // in the Amazon EKS User Guide. ReleaseVersion *string `locationName:"releaseVersion" type:"string"` // The Kubernetes version to update to. If no version is specified, then the // Kubernetes version of the node group does not change. You can specify the // Kubernetes version of the cluster to update the node group to the latest - // AMI version of the cluster's Kubernetes version. + // AMI version of the cluster's Kubernetes version. If you specify launchTemplate, + // and your launch template uses a custom AMI, then don't specify version, or + // the node group update will fail. For more information about using launch + // templates with Amazon EKS, see Launch template support (https://docs.aws.amazon.com/eks/latest/userguide/launch-templates.html) + // in the Amazon EKS User Guide. Version *string `locationName:"version" type:"string"` } @@ -6369,6 +6510,12 @@ func (s *UpdateNodegroupVersionInput) SetForce(v bool) *UpdateNodegroupVersionIn return s } +// SetLaunchTemplate sets the LaunchTemplate field's value. +func (s *UpdateNodegroupVersionInput) SetLaunchTemplate(v *LaunchTemplateSpecification) *UpdateNodegroupVersionInput { + s.LaunchTemplate = v + return s +} + // SetNodegroupName sets the NodegroupName field's value. func (s *UpdateNodegroupVersionInput) SetNodegroupName(v string) *UpdateNodegroupVersionInput { s.NodegroupName = &v @@ -6635,8 +6782,20 @@ const ( // AMITypesAl2X8664Gpu is a AMITypes enum value AMITypesAl2X8664Gpu = "AL2_x86_64_GPU" + + // AMITypesAl2Arm64 is a AMITypes enum value + AMITypesAl2Arm64 = "AL2_ARM_64" ) +// AMITypes_Values returns all elements of the AMITypes enum +func AMITypes_Values() []string { + return []string{ + AMITypesAl2X8664, + AMITypesAl2X8664Gpu, + AMITypesAl2Arm64, + } +} + const ( // ClusterStatusCreating is a ClusterStatus enum value ClusterStatusCreating = "CREATING" @@ -6654,6 +6813,17 @@ const ( ClusterStatusUpdating = "UPDATING" ) +// ClusterStatus_Values returns all elements of the ClusterStatus enum +func ClusterStatus_Values() []string { + return []string{ + ClusterStatusCreating, + ClusterStatusActive, + ClusterStatusDeleting, + ClusterStatusFailed, + ClusterStatusUpdating, + } +} + const ( // ErrorCodeSubnetNotFound is a ErrorCode enum value ErrorCodeSubnetNotFound = "SubnetNotFound" @@ -6689,6 +6859,23 @@ const ( ErrorCodeInsufficientFreeAddresses = "InsufficientFreeAddresses" ) +// ErrorCode_Values returns all elements of the ErrorCode enum +func ErrorCode_Values() []string { + return []string{ + ErrorCodeSubnetNotFound, + ErrorCodeSecurityGroupNotFound, + ErrorCodeEniLimitReached, + ErrorCodeIpNotAvailable, + ErrorCodeAccessDenied, + ErrorCodeOperationNotPermitted, + ErrorCodeVpcIdNotFound, + ErrorCodeUnknown, + ErrorCodeNodeCreationFailure, + ErrorCodePodEvictionFailure, + ErrorCodeInsufficientFreeAddresses, + } +} + const ( // FargateProfileStatusCreating is a FargateProfileStatus enum value FargateProfileStatusCreating = "CREATING" @@ -6706,6 +6893,17 @@ const ( FargateProfileStatusDeleteFailed = "DELETE_FAILED" ) +// FargateProfileStatus_Values returns all elements of the FargateProfileStatus enum +func FargateProfileStatus_Values() []string { + return []string{ + FargateProfileStatusCreating, + FargateProfileStatusActive, + FargateProfileStatusDeleting, + FargateProfileStatusCreateFailed, + FargateProfileStatusDeleteFailed, + } +} + const ( // LogTypeApi is a LogType enum value LogTypeApi = "api" @@ -6723,6 +6921,17 @@ const ( LogTypeScheduler = "scheduler" ) +// LogType_Values returns all elements of the LogType enum +func LogType_Values() []string { + return []string{ + LogTypeApi, + LogTypeAudit, + LogTypeAuthenticator, + LogTypeControllerManager, + LogTypeScheduler, + } +} + const ( // NodegroupIssueCodeAutoScalingGroupNotFound is a NodegroupIssueCode enum value NodegroupIssueCodeAutoScalingGroupNotFound = "AutoScalingGroupNotFound" @@ -6776,6 +6985,29 @@ const ( NodegroupIssueCodeInternalFailure = "InternalFailure" ) +// NodegroupIssueCode_Values returns all elements of the NodegroupIssueCode enum +func NodegroupIssueCode_Values() []string { + return []string{ + NodegroupIssueCodeAutoScalingGroupNotFound, + NodegroupIssueCodeAutoScalingGroupInvalidConfiguration, + NodegroupIssueCodeEc2securityGroupNotFound, + NodegroupIssueCodeEc2securityGroupDeletionFailure, + NodegroupIssueCodeEc2launchTemplateNotFound, + NodegroupIssueCodeEc2launchTemplateVersionMismatch, + NodegroupIssueCodeEc2subnetNotFound, + NodegroupIssueCodeEc2subnetInvalidConfiguration, + NodegroupIssueCodeIamInstanceProfileNotFound, + NodegroupIssueCodeIamLimitExceeded, + NodegroupIssueCodeIamNodeRoleNotFound, + NodegroupIssueCodeNodeCreationFailure, + NodegroupIssueCodeAsgInstanceLaunchFailures, + NodegroupIssueCodeInstanceLimitExceeded, + NodegroupIssueCodeInsufficientFreeAddresses, + NodegroupIssueCodeAccessDenied, + NodegroupIssueCodeInternalFailure, + } +} + const ( // NodegroupStatusCreating is a NodegroupStatus enum value NodegroupStatusCreating = "CREATING" @@ -6799,6 +7031,19 @@ const ( NodegroupStatusDegraded = "DEGRADED" ) +// NodegroupStatus_Values returns all elements of the NodegroupStatus enum +func NodegroupStatus_Values() []string { + return []string{ + NodegroupStatusCreating, + NodegroupStatusActive, + NodegroupStatusUpdating, + NodegroupStatusDeleting, + NodegroupStatusCreateFailed, + NodegroupStatusDeleteFailed, + NodegroupStatusDegraded, + } +} + const ( // UpdateParamTypeVersion is a UpdateParamType enum value UpdateParamTypeVersion = "Version" @@ -6837,6 +7082,24 @@ const ( UpdateParamTypePublicAccessCidrs = "PublicAccessCidrs" ) +// UpdateParamType_Values returns all elements of the UpdateParamType enum +func UpdateParamType_Values() []string { + return []string{ + UpdateParamTypeVersion, + UpdateParamTypePlatformVersion, + UpdateParamTypeEndpointPrivateAccess, + UpdateParamTypeEndpointPublicAccess, + UpdateParamTypeClusterLogging, + UpdateParamTypeDesiredSize, + UpdateParamTypeLabelsToAdd, + UpdateParamTypeLabelsToRemove, + UpdateParamTypeMaxSize, + UpdateParamTypeMinSize, + UpdateParamTypeReleaseVersion, + UpdateParamTypePublicAccessCidrs, + } +} + const ( // UpdateStatusInProgress is a UpdateStatus enum value UpdateStatusInProgress = "InProgress" @@ -6851,6 +7114,16 @@ const ( UpdateStatusSuccessful = "Successful" ) +// UpdateStatus_Values returns all elements of the UpdateStatus enum +func UpdateStatus_Values() []string { + return []string{ + UpdateStatusInProgress, + UpdateStatusFailed, + UpdateStatusCancelled, + UpdateStatusSuccessful, + } +} + const ( // UpdateTypeVersionUpdate is a UpdateType enum value UpdateTypeVersionUpdate = "VersionUpdate" @@ -6864,3 +7137,13 @@ const ( // UpdateTypeConfigUpdate is a UpdateType enum value UpdateTypeConfigUpdate = "ConfigUpdate" ) + +// UpdateType_Values returns all elements of the UpdateType enum +func UpdateType_Values() []string { + return []string{ + UpdateTypeVersionUpdate, + UpdateTypeEndpointAccessUpdate, + UpdateTypeLoggingUpdate, + UpdateTypeConfigUpdate, + } +} 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 e1e52e34aed..a2767843498 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 @@ -1089,7 +1089,7 @@ func (c *ElastiCache) CreateGlobalReplicationGroupRequest(input *CreateGlobalRep // reads and disaster recovery across regions. For more information, see Replication // Across Regions Using Global Datastore (/AmazonElastiCache/latest/red-ug/Redis-Global-Clusters.html). // -// * The GlobalReplicationGroupId is the name of the Global Datastore. +// * The GlobalReplicationGroupIdSuffix is the name of the Global Datastore. // // * The PrimaryReplicationGroupId represents the name of the primary cluster // that accepts writes and will replicate updates to the secondary cluster. @@ -1201,11 +1201,9 @@ 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. 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 (https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/backups-restoring.html) +// read replicas. If you need to increase or decrease the number of node groups +// (console: shards), you can avail yourself of ElastiCache for Redis' scaling. +// For more information, see Scaling ElastiCache for Redis Clusters (https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Scaling.html) // in the ElastiCache User Guide. // // This operation is valid for Redis only. @@ -1273,7 +1271,7 @@ func (c *ElastiCache) CreateReplicationGroupRequest(input *CreateReplicationGrou // The Global Datastore does not exist // // * ErrCodeInvalidGlobalReplicationGroupStateFault "InvalidGlobalReplicationGroupState" -// The Global Datastore is not available +// The Global Datastore is not available or in primary-only state. // // * ErrCodeInvalidParameterValueException "InvalidParameterValue" // The value for a parameter is invalid. @@ -1476,7 +1474,7 @@ func (c *ElastiCache) DecreaseNodeGroupsInGlobalReplicationGroupRequest(input *D // The Global Datastore does not exist // // * ErrCodeInvalidGlobalReplicationGroupStateFault "InvalidGlobalReplicationGroupState" -// The Global Datastore is not available +// The Global Datastore is not available or in primary-only state. // // * ErrCodeInvalidParameterValueException "InvalidParameterValue" // The value for a parameter is invalid. @@ -2078,8 +2076,6 @@ func (c *ElastiCache) DeleteGlobalReplicationGroupRequest(input *DeleteGlobalRep // immediately begins deleting the selected resources; you cannot cancel or // revert this operation. // -// This operation is valid for Redis only. -// // Returns awserr.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. @@ -2092,7 +2088,7 @@ func (c *ElastiCache) DeleteGlobalReplicationGroupRequest(input *DeleteGlobalRep // The Global Datastore does not exist // // * ErrCodeInvalidGlobalReplicationGroupStateFault "InvalidGlobalReplicationGroupState" -// The Global Datastore is not available +// The Global Datastore is not available or in primary-only state. // // * ErrCodeInvalidParameterValueException "InvalidParameterValue" // The value for a parameter is invalid. @@ -4559,7 +4555,7 @@ func (c *ElastiCache) DisassociateGlobalReplicationGroupRequest(input *Disassoci // The Global Datastore does not exist // // * ErrCodeInvalidGlobalReplicationGroupStateFault "InvalidGlobalReplicationGroupState" -// The Global Datastore is not available +// The Global Datastore is not available or in primary-only state. // // * ErrCodeInvalidParameterValueException "InvalidParameterValue" // The value for a parameter is invalid. @@ -4633,7 +4629,9 @@ func (c *ElastiCache) FailoverGlobalReplicationGroupRequest(input *FailoverGloba // FailoverGlobalReplicationGroup API operation for Amazon ElastiCache. // -// Used to failover the primary region to a selected secondary region. +// Used to failover the primary region to a selected secondary region. The selected +// secondary region will become primary, and all other clusters will become +// secondary. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4647,7 +4645,7 @@ func (c *ElastiCache) FailoverGlobalReplicationGroupRequest(input *FailoverGloba // The Global Datastore does not exist // // * ErrCodeInvalidGlobalReplicationGroupStateFault "InvalidGlobalReplicationGroupState" -// The Global Datastore is not available +// The Global Datastore is not available or in primary-only state. // // * ErrCodeInvalidParameterValueException "InvalidParameterValue" // The value for a parameter is invalid. @@ -4735,7 +4733,7 @@ func (c *ElastiCache) IncreaseNodeGroupsInGlobalReplicationGroupRequest(input *I // The Global Datastore does not exist // // * ErrCodeInvalidGlobalReplicationGroupStateFault "InvalidGlobalReplicationGroupState" -// The Global Datastore is not available +// The Global Datastore is not available or in primary-only state. // // * ErrCodeInvalidParameterValueException "InvalidParameterValue" // The value for a parameter is invalid. @@ -5258,7 +5256,7 @@ func (c *ElastiCache) ModifyCacheParameterGroupRequest(input *ModifyCacheParamet // Two or more incompatible parameters were specified. // // * ErrCodeInvalidGlobalReplicationGroupStateFault "InvalidGlobalReplicationGroupState" -// The Global Datastore is not available +// The Global Datastore is not available or in primary-only state. // // See also, https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/ModifyCacheParameterGroup func (c *ElastiCache) ModifyCacheParameterGroup(input *ModifyCacheParameterGroupInput) (*CacheParameterGroupNameMessage, error) { @@ -5430,7 +5428,7 @@ func (c *ElastiCache) ModifyGlobalReplicationGroupRequest(input *ModifyGlobalRep // The Global Datastore does not exist // // * ErrCodeInvalidGlobalReplicationGroupStateFault "InvalidGlobalReplicationGroupState" -// The Global Datastore is not available +// The Global Datastore is not available or in primary-only state. // // * ErrCodeInvalidParameterValueException "InvalidParameterValue" // The value for a parameter is invalid. @@ -5503,10 +5501,6 @@ func (c *ElastiCache) ModifyReplicationGroupRequest(input *ModifyReplicationGrou // // Modifies the settings for a replication group. // -// For Redis (cluster mode enabled) clusters, this operation cannot be used -// to change a cluster's node type or engine version. For more information, -// see: -// // * Scaling for Amazon ElastiCache for Redis (cluster mode enabled) (https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/scaling-redis-cluster-mode-enabled.html) // in the ElastiCache User Guide // @@ -5841,7 +5835,7 @@ func (c *ElastiCache) RebalanceSlotsInGlobalReplicationGroupRequest(input *Rebal // RebalanceSlotsInGlobalReplicationGroup API operation for Amazon ElastiCache. // -// Redistribute slots to ensure unifirom distribution across existing shards +// Redistribute slots to ensure uniform distribution across existing shards // in the cluster. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -5856,7 +5850,7 @@ func (c *ElastiCache) RebalanceSlotsInGlobalReplicationGroupRequest(input *Rebal // The Global Datastore does not exist // // * ErrCodeInvalidGlobalReplicationGroupStateFault "InvalidGlobalReplicationGroupState" -// The Global Datastore is not available +// The Global Datastore is not available or in primary-only state. // // * ErrCodeInvalidParameterValueException "InvalidParameterValue" // The value for a parameter is invalid. @@ -6141,7 +6135,7 @@ func (c *ElastiCache) ResetCacheParameterGroupRequest(input *ResetCacheParameter // Two or more incompatible parameters were specified. // // * ErrCodeInvalidGlobalReplicationGroupStateFault "InvalidGlobalReplicationGroupState" -// The Global Datastore is not available +// The Global Datastore is not available or in primary-only state. // // See also, https://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/ResetCacheParameterGroup func (c *ElastiCache) ResetCacheParameterGroup(input *ResetCacheParameterGroupInput) (*CacheParameterGroupNameMessage, error) { @@ -6421,7 +6415,7 @@ func (c *ElastiCache) TestFailoverRequest(input *TestFailoverInput) (req *reques // in the ElastiCache User Guide DescribeEvents (https://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DescribeEvents.html) // in the ElastiCache API Reference // -// Also see, Testing Multi-AZ with Automatic Failover (https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/AutoFailover.html#auto-failover-test) +// Also see, Testing Multi-AZ (https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/AutoFailover.html#auto-failover-test) // in the ElastiCache User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -6846,6 +6840,9 @@ func (s *BatchStopUpdateActionOutput) SetUnprocessedUpdateActions(v []*Unprocess type CacheCluster struct { _ struct{} `type:"structure"` + // The ARN (Amazon Resource Name) of the cache cluster. + ARN *string `type:"string"` + // A flag that enables encryption at-rest when set to true. // // You cannot modify the value of AtRestEncryptionEnabled after the cluster @@ -7034,6 +7031,12 @@ func (s CacheCluster) GoString() string { return s.String() } +// SetARN sets the ARN field's value. +func (s *CacheCluster) SetARN(v string) *CacheCluster { + s.ARN = &v + return s +} + // SetAtRestEncryptionEnabled sets the AtRestEncryptionEnabled field's value. func (s *CacheCluster) SetAtRestEncryptionEnabled(v bool) *CacheCluster { s.AtRestEncryptionEnabled = &v @@ -7600,6 +7603,9 @@ func (s *CacheNodeUpdateStatus) SetNodeUpdateStatusModifiedDate(v time.Time) *Ca type CacheParameterGroup struct { _ struct{} `type:"structure"` + // The ARN (Amazon Resource Name) of the cache parameter group. + ARN *string `type:"string"` + // The name of the cache parameter group family that this cache parameter group // is compatible with. // @@ -7627,6 +7633,12 @@ func (s CacheParameterGroup) GoString() string { return s.String() } +// SetARN sets the ARN field's value. +func (s *CacheParameterGroup) SetARN(v string) *CacheParameterGroup { + s.ARN = &v + return s +} + // SetCacheParameterGroupFamily sets the CacheParameterGroupFamily field's value. func (s *CacheParameterGroup) SetCacheParameterGroupFamily(v string) *CacheParameterGroup { s.CacheParameterGroupFamily = &v @@ -7732,6 +7744,9 @@ func (s *CacheParameterGroupStatus) SetParameterApplyStatus(v string) *CachePara type CacheSecurityGroup struct { _ struct{} `type:"structure"` + // The ARN (Amazon Resource Name) of the cache security group. + ARN *string `type:"string"` + // The name of the cache security group. CacheSecurityGroupName *string `type:"string"` @@ -7756,6 +7771,12 @@ func (s CacheSecurityGroup) GoString() string { return s.String() } +// SetARN sets the ARN field's value. +func (s *CacheSecurityGroup) SetARN(v string) *CacheSecurityGroup { + s.ARN = &v + return s +} + // SetCacheSecurityGroupName sets the CacheSecurityGroupName field's value. func (s *CacheSecurityGroup) SetCacheSecurityGroupName(v string) *CacheSecurityGroup { s.CacheSecurityGroupName = &v @@ -7823,6 +7844,9 @@ func (s *CacheSecurityGroupMembership) SetStatus(v string) *CacheSecurityGroupMe type CacheSubnetGroup struct { _ struct{} `type:"structure"` + // The ARN (Amazon Resource Name) of the cache subnet group. + ARN *string `type:"string"` + // The description of the cache subnet group. CacheSubnetGroupDescription *string `type:"string"` @@ -7847,6 +7871,12 @@ func (s CacheSubnetGroup) GoString() string { return s.String() } +// SetARN sets the ARN field's value. +func (s *CacheSubnetGroup) SetARN(v string) *CacheSubnetGroup { + s.ARN = &v + return s +} + // SetCacheSubnetGroupDescription sets the CacheSubnetGroupDescription field's value. func (s *CacheSubnetGroup) SetCacheSubnetGroupDescription(v string) *CacheSubnetGroup { s.CacheSubnetGroupDescription = &v @@ -7955,8 +7985,7 @@ type ConfigureShard struct { // // The minimum number of replicas in a shard or replication group is: // - // * Redis (cluster mode disabled) If Multi-AZ with Automatic Failover is - // enabled: 1 If Multi-AZ with Automatic Failover is not enable: 0 + // * Redis (cluster mode disabled) If Multi-AZ: 1 If Multi-AZ: 0 // // * Redis (cluster mode enabled): 0 (though you will not be able to failover // to a replica if your primary node fails) @@ -8277,9 +8306,9 @@ type CreateCacheClusterInput struct { // The EC2 Availability Zone in which the cluster is created. // - // All nodes belonging to this Memcached cluster are placed in the preferred - // Availability Zone. If you want to create your nodes across multiple Availability - // Zones, use PreferredAvailabilityZones. + // All nodes belonging to this cluster are placed in the preferred Availability + // Zone. If you want to create your nodes across multiple Availability Zones, + // use PreferredAvailabilityZones. // // Default: System chosen Availability Zone. PreferredAvailabilityZone *string `type:"string"` @@ -8858,8 +8887,8 @@ type CreateGlobalReplicationGroupInput struct { // Provides details of the Global Datastore GlobalReplicationGroupDescription *string `type:"string"` - // The suffix for name of a Global Datastore. The suffix guarantees uniqueness - // of the Global Datastore name across multiple regions. + // The suffix name of a Global Datastore. The suffix guarantees uniqueness of + // the Global Datastore name across multiple regions. // // GlobalReplicationGroupIdSuffix is a required field GlobalReplicationGroupIdSuffix *string `type:"string" required:"true"` @@ -8923,8 +8952,8 @@ type CreateGlobalReplicationGroupOutput struct { // only reads. The primary cluster automatically replicates updates to the secondary // cluster. // - // * The GlobalReplicationGroupId represents the name of the Global Datastore, - // which is what you use to associate a secondary cluster. + // * The GlobalReplicationGroupIdSuffix represents the name of the Global + // Datastore, which is what you use to associate a secondary cluster. GlobalReplicationGroup *GlobalReplicationGroup `type:"structure"` } @@ -8989,22 +9018,10 @@ type CreateReplicationGroupInput struct { // Specifies whether a read-only replica is automatically promoted to read/write // primary if the existing primary fails. // - // If true, Multi-AZ is enabled for this replication group. If false, Multi-AZ - // is disabled for this replication group. - // // AutomaticFailoverEnabled must be enabled for Redis (cluster mode enabled) // replication groups. // // Default: false - // - // Amazon ElastiCache for Redis does not support Multi-AZ with automatic failover - // on: - // - // * Redis versions earlier than 2.8.6. - // - // * Redis (cluster mode disabled): T1 node types. - // - // * Redis (cluster mode enabled): T1 node types. AutomaticFailoverEnabled *bool `type:"boolean"` // The compute and memory capacity of the nodes in the node group (shard). @@ -9093,16 +9110,20 @@ type CreateReplicationGroupInput struct { // The ID of the KMS key used to encrypt the disk in the cluster. KmsKeyId *string `type:"string"` + // A flag indicating if you have Multi-AZ enabled to enhance fault tolerance. + // For more information, see Minimizing Downtime: Multi-AZ (http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/AutoFailover.html). + MultiAZEnabled *bool `type:"boolean"` + // A list of node group (shard) configuration options. Each node group (shard) // configuration has the following members: PrimaryAvailabilityZone, ReplicaAvailabilityZones, // ReplicaCount, and Slots. // // If you're creating a Redis (cluster mode disabled) or a Redis (cluster mode // enabled) replication group, you can use this parameter to individually configure - // each node group (shard), or you can omit this parameter. However, when seeding - // a Redis (cluster mode enabled) cluster from a S3 rdb file, you must configure - // each node group (shard) using this parameter because you must specify the - // slots for each node group. + // each node group (shard), or you can omit this parameter. However, it is required + // when seeding a Redis (cluster mode enabled) cluster from a S3 rdb file. You + // must configure each node group (shard) using this parameter because you must + // specify the slots for each node group. NodeGroupConfiguration []*NodeGroupConfiguration `locationNameList:"NodeGroupConfiguration" type:"list"` // The Amazon Resource Name (ARN) of the Amazon Simple Notification Service @@ -9382,6 +9403,12 @@ func (s *CreateReplicationGroupInput) SetKmsKeyId(v string) *CreateReplicationGr return s } +// SetMultiAZEnabled sets the MultiAZEnabled field's value. +func (s *CreateReplicationGroupInput) SetMultiAZEnabled(v bool) *CreateReplicationGroupInput { + s.MultiAZEnabled = &v + return s +} + // SetNodeGroupConfiguration sets the NodeGroupConfiguration field's value. func (s *CreateReplicationGroupInput) SetNodeGroupConfiguration(v []*NodeGroupConfiguration) *CreateReplicationGroupInput { s.NodeGroupConfiguration = v @@ -9740,8 +9767,8 @@ type DecreaseNodeGroupsInGlobalReplicationGroupOutput struct { // only reads. The primary cluster automatically replicates updates to the secondary // cluster. // - // * The GlobalReplicationGroupId represents the name of the Global Datastore, - // which is what you use to associate a secondary cluster. + // * The GlobalReplicationGroupIdSuffix represents the name of the Global + // Datastore, which is what you use to associate a secondary cluster. GlobalReplicationGroup *GlobalReplicationGroup `type:"structure"` } @@ -9778,8 +9805,8 @@ type DecreaseReplicaCountInput struct { // // The minimum number of replicas in a shard or replication group is: // - // * Redis (cluster mode disabled) If Multi-AZ with Automatic Failover is - // enabled: 1 If Multi-AZ with Automatic Failover is not enabled: 0 + // * Redis (cluster mode disabled) If Multi-AZ is enabled: 1 If Multi-AZ + // is not enabled: 0 // // * Redis (cluster mode enabled): 0 (though you will not be able to failover // to a replica if your primary node fails) @@ -10136,8 +10163,7 @@ type DeleteGlobalReplicationGroupInput struct { // GlobalReplicationGroupId is a required field GlobalReplicationGroupId *string `type:"string" required:"true"` - // If set to true, the primary replication is retained as a standalone replication - // group. + // The primary replication group is retained as a standalone replication group. // // RetainPrimaryReplicationGroup is a required field RetainPrimaryReplicationGroup *bool `type:"boolean" required:"true"` @@ -10189,8 +10215,8 @@ type DeleteGlobalReplicationGroupOutput struct { // only reads. The primary cluster automatically replicates updates to the secondary // cluster. // - // * The GlobalReplicationGroupId represents the name of the Global Datastore, - // which is what you use to associate a secondary cluster. + // * The GlobalReplicationGroupIdSuffix represents the name of the Global + // Datastore, which is what you use to associate a secondary cluster. GlobalReplicationGroup *GlobalReplicationGroup `type:"structure"` } @@ -12127,8 +12153,8 @@ type DisassociateGlobalReplicationGroupOutput struct { // only reads. The primary cluster automatically replicates updates to the secondary // cluster. // - // * The GlobalReplicationGroupId represents the name of the Global Datastore, - // which is what you use to associate a secondary cluster. + // * The GlobalReplicationGroupIdSuffix represents the name of the Global + // Datastore, which is what you use to associate a secondary cluster. GlobalReplicationGroup *GlobalReplicationGroup `type:"structure"` } @@ -12409,8 +12435,8 @@ type FailoverGlobalReplicationGroupOutput struct { // only reads. The primary cluster automatically replicates updates to the secondary // cluster. // - // * The GlobalReplicationGroupId represents the name of the Global Datastore, - // which is what you use to associate a secondary cluster. + // * The GlobalReplicationGroupIdSuffix represents the name of the Global + // Datastore, which is what you use to associate a secondary cluster. GlobalReplicationGroup *GlobalReplicationGroup `type:"structure"` } @@ -12468,11 +12494,14 @@ func (s *GlobalNodeGroup) SetSlots(v string) *GlobalNodeGroup { // only reads. The primary cluster automatically replicates updates to the secondary // cluster. // -// * The GlobalReplicationGroupId represents the name of the Global Datastore, -// which is what you use to associate a secondary cluster. +// * The GlobalReplicationGroupIdSuffix represents the name of the Global +// Datastore, which is what you use to associate a secondary cluster. type GlobalReplicationGroup struct { _ struct{} `type:"structure"` + // The ARN (Amazon Resource Name) of the global replication group. + ARN *string `type:"string"` + // A flag that enables encryption at rest when set to true. // // You cannot modify the value of AtRestEncryptionEnabled after the replication @@ -12495,7 +12524,7 @@ type GlobalReplicationGroup struct { // A flag that indicates whether the Global Datastore is cluster enabled. ClusterEnabled *bool `type:"boolean"` - // The Elasticache engine. For preview, it is Redis only. + // The Elasticache engine. For Redis only. Engine *string `type:"string"` // The Elasticache Redis engine version. For preview, it is Redis version 5.0.5 @@ -12534,6 +12563,12 @@ func (s GlobalReplicationGroup) GoString() string { return s.String() } +// SetARN sets the ARN field's value. +func (s *GlobalReplicationGroup) SetARN(v string) *GlobalReplicationGroup { + s.ARN = &v + return s +} + // SetAtRestEncryptionEnabled sets the AtRestEncryptionEnabled field's value. func (s *GlobalReplicationGroup) SetAtRestEncryptionEnabled(v bool) *GlobalReplicationGroup { s.AtRestEncryptionEnabled = &v @@ -12797,8 +12832,8 @@ type IncreaseNodeGroupsInGlobalReplicationGroupOutput struct { // only reads. The primary cluster automatically replicates updates to the secondary // cluster. // - // * The GlobalReplicationGroupId represents the name of the Global Datastore, - // which is what you use to associate a secondary cluster. + // * The GlobalReplicationGroupIdSuffix represents the name of the Global + // Datastore, which is what you use to associate a secondary cluster. GlobalReplicationGroup *GlobalReplicationGroup `type:"structure"` } @@ -13603,12 +13638,9 @@ func (s *ModifyCacheSubnetGroupOutput) SetCacheSubnetGroup(v *CacheSubnetGroup) type ModifyGlobalReplicationGroupInput struct { _ struct{} `type:"structure"` - // If true, this parameter causes the modifications in this request and any - // pending modifications to be applied, asynchronously and as soon as possible, - // regardless of the PreferredMaintenanceWindow setting for the replication - // group. If false, changes to the nodes in the replication group are applied - // on the next maintenance reboot, or the next failure reboot, whichever occurs - // first. + // This parameter causes the modifications in this request and any pending modifications + // to be applied, asynchronously and as soon as possible. Modifications to Global + // Replication Groups cannot be requested to be applied in PreferredMaintenceWindow. // // ApplyImmediately is a required field ApplyImmediately *bool `type:"boolean" required:"true"` @@ -13703,8 +13735,8 @@ type ModifyGlobalReplicationGroupOutput struct { // only reads. The primary cluster automatically replicates updates to the secondary // cluster. // - // * The GlobalReplicationGroupId represents the name of the Global Datastore, - // which is what you use to associate a secondary cluster. + // * The GlobalReplicationGroupIdSuffix represents the name of the Global + // Datastore, which is what you use to associate a secondary cluster. GlobalReplicationGroup *GlobalReplicationGroup `type:"structure"` } @@ -13771,15 +13803,6 @@ type ModifyReplicationGroupInput struct { // primary if the existing primary encounters a failure. // // Valid values: true | false - // - // Amazon ElastiCache for Redis does not support Multi-AZ with automatic failover - // on: - // - // * Redis versions earlier than 2.8.6. - // - // * Redis (cluster mode disabled): T1 node types. - // - // * Redis (cluster mode enabled): T1 node types. AutomaticFailoverEnabled *bool `type:"boolean"` // A valid cache node type that you want to scale this replication group to. @@ -13811,6 +13834,10 @@ type ModifyReplicationGroupInput struct { // and create it anew with the earlier engine version. EngineVersion *string `type:"string"` + // A flag indicating if you have Multi-AZ enabled to enhance fault tolerance. + // For more information, see Minimizing Downtime: Multi-AZ (http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/AutoFailover.html). + MultiAZEnabled *bool `type:"boolean"` + // Deprecated. This parameter is not used. // // Deprecated: NodeGroupId has been deprecated @@ -13973,6 +14000,12 @@ func (s *ModifyReplicationGroupInput) SetEngineVersion(v string) *ModifyReplicat return s } +// SetMultiAZEnabled sets the MultiAZEnabled field's value. +func (s *ModifyReplicationGroupInput) SetMultiAZEnabled(v bool) *ModifyReplicationGroupInput { + s.MultiAZEnabled = &v + return s +} + // SetNodeGroupId sets the NodeGroupId field's value. func (s *ModifyReplicationGroupInput) SetNodeGroupId(v string) *ModifyReplicationGroupInput { s.NodeGroupId = &v @@ -14237,7 +14270,8 @@ type NodeGroup struct { // The keyspace for this node group (shard). Slots *string `type:"string"` - // The current state of this replication group - creating, available, etc. + // The current state of this replication group - creating, available, modifying, + // deleting. Status *string `type:"string"` } @@ -15078,8 +15112,8 @@ type RebalanceSlotsInGlobalReplicationGroupOutput struct { // only reads. The primary cluster automatically replicates updates to the secondary // cluster. // - // * The GlobalReplicationGroupId represents the name of the Global Datastore, - // which is what you use to associate a secondary cluster. + // * The GlobalReplicationGroupIdSuffix represents the name of the Global + // Datastore, which is what you use to associate a secondary cluster. GlobalReplicationGroup *GlobalReplicationGroup `type:"structure"` } @@ -15350,6 +15384,9 @@ func (s *RemoveTagsFromResourceInput) SetTagKeys(v []*string) *RemoveTagsFromRes type ReplicationGroup struct { _ struct{} `type:"structure"` + // The ARN (Amazon Resource Name) of the replication group. + ARN *string `type:"string"` + // A flag that enables encryption at-rest when set to true. // // You cannot modify the value of AtRestEncryptionEnabled after the cluster @@ -15370,17 +15407,7 @@ type ReplicationGroup struct { // The date the auth token was last modified AuthTokenLastModifiedDate *time.Time `type:"timestamp"` - // Indicates the status of Multi-AZ with automatic failover for this Redis replication - // group. - // - // Amazon ElastiCache for Redis does not support Multi-AZ with automatic failover - // on: - // - // * Redis versions earlier than 2.8.6. - // - // * Redis (cluster mode disabled): T1 node types. - // - // * Redis (cluster mode enabled): T1 node types. + // Indicates the status of automatic failover for this Redis replication group. AutomaticFailover *string `type:"string" enum:"AutomaticFailoverStatus"` // The name of the compute and memory capacity node type for each node in the @@ -15411,6 +15438,10 @@ type ReplicationGroup struct { // The names of all the cache clusters that are part of this replication group. MemberClusters []*string `locationNameList:"ClusterId" type:"list"` + // A flag indicating if you have Multi-AZ enabled to enhance fault tolerance. + // For more information, see Minimizing Downtime: Multi-AZ (http://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/AutoFailover.html) + MultiAZ *string `type:"string" enum:"MultiAZStatus"` + // A list of node groups in this replication group. For Redis (cluster mode // disabled) replication groups, this is a single-element list. For Redis (cluster // mode enabled) replication groups, the list contains an entry for each node @@ -15474,6 +15505,12 @@ func (s ReplicationGroup) GoString() string { return s.String() } +// SetARN sets the ARN field's value. +func (s *ReplicationGroup) SetARN(v string) *ReplicationGroup { + s.ARN = &v + return s +} + // SetAtRestEncryptionEnabled sets the AtRestEncryptionEnabled field's value. func (s *ReplicationGroup) SetAtRestEncryptionEnabled(v bool) *ReplicationGroup { s.AtRestEncryptionEnabled = &v @@ -15540,6 +15577,12 @@ func (s *ReplicationGroup) SetMemberClusters(v []*string) *ReplicationGroup { return s } +// SetMultiAZ sets the MultiAZ field's value. +func (s *ReplicationGroup) SetMultiAZ(v string) *ReplicationGroup { + s.MultiAZ = &v + return s +} + // SetNodeGroups sets the NodeGroups field's value. func (s *ReplicationGroup) SetNodeGroups(v []*NodeGroup) *ReplicationGroup { s.NodeGroups = v @@ -15596,17 +15639,7 @@ type ReplicationGroupPendingModifiedValues struct { // The auth token status AuthTokenStatus *string `type:"string" enum:"AuthTokenUpdateStatus"` - // Indicates the status of Multi-AZ with automatic failover for this Redis replication - // group. - // - // Amazon ElastiCache for Redis does not support Multi-AZ with automatic failover - // on: - // - // * Redis versions earlier than 2.8.6. - // - // * Redis (cluster mode disabled): T1 node types. - // - // * Redis (cluster mode enabled): T1 node types. + // Indicates the status of automatic failover for this Redis replication group. AutomaticFailoverStatus *string `type:"string" enum:"PendingAutomaticFailoverStatus"` // The primary cluster ID that is applied immediately (if --apply-immediately @@ -16366,20 +16399,14 @@ func (s *SlotMigration) SetProgressPercentage(v float64) *SlotMigration { type Snapshot struct { _ struct{} `type:"structure"` + // The ARN (Amazon Resource Name) of the snapshot. + ARN *string `type:"string"` + // This parameter is currently disabled. AutoMinorVersionUpgrade *bool `type:"boolean"` - // Indicates the status of Multi-AZ with automatic failover for the source Redis - // replication group. - // - // Amazon ElastiCache for Redis does not support Multi-AZ with automatic failover - // on: - // - // * Redis versions earlier than 2.8.6. - // - // * Redis (cluster mode disabled): T1 node types. - // - // * Redis (cluster mode enabled): T1 node types. + // Indicates the status of automatic failover for the source Redis replication + // group. AutomaticFailover *string `type:"string" enum:"AutomaticFailoverStatus"` // The date and time when the source cluster was created. @@ -16537,6 +16564,12 @@ func (s Snapshot) GoString() string { return s.String() } +// SetARN sets the ARN field's value. +func (s *Snapshot) SetARN(v string) *Snapshot { + s.ARN = &v + return s +} + // SetAutoMinorVersionUpgrade sets the AutoMinorVersionUpgrade field's value. func (s *Snapshot) SetAutoMinorVersionUpgrade(v bool) *Snapshot { s.AutoMinorVersionUpgrade = &v @@ -17215,6 +17248,14 @@ const ( AZModeCrossAz = "cross-az" ) +// AZMode_Values returns all elements of the AZMode enum +func AZMode_Values() []string { + return []string{ + AZModeSingleAz, + AZModeCrossAz, + } +} + const ( // AuthTokenUpdateStatusSetting is a AuthTokenUpdateStatus enum value AuthTokenUpdateStatusSetting = "SETTING" @@ -17223,6 +17264,14 @@ const ( AuthTokenUpdateStatusRotating = "ROTATING" ) +// AuthTokenUpdateStatus_Values returns all elements of the AuthTokenUpdateStatus enum +func AuthTokenUpdateStatus_Values() []string { + return []string{ + AuthTokenUpdateStatusSetting, + AuthTokenUpdateStatusRotating, + } +} + const ( // AuthTokenUpdateStrategyTypeSet is a AuthTokenUpdateStrategyType enum value AuthTokenUpdateStrategyTypeSet = "SET" @@ -17231,6 +17280,14 @@ const ( AuthTokenUpdateStrategyTypeRotate = "ROTATE" ) +// AuthTokenUpdateStrategyType_Values returns all elements of the AuthTokenUpdateStrategyType enum +func AuthTokenUpdateStrategyType_Values() []string { + return []string{ + AuthTokenUpdateStrategyTypeSet, + AuthTokenUpdateStrategyTypeRotate, + } +} + const ( // AutomaticFailoverStatusEnabled is a AutomaticFailoverStatus enum value AutomaticFailoverStatusEnabled = "enabled" @@ -17245,6 +17302,16 @@ const ( AutomaticFailoverStatusDisabling = "disabling" ) +// AutomaticFailoverStatus_Values returns all elements of the AutomaticFailoverStatus enum +func AutomaticFailoverStatus_Values() []string { + return []string{ + AutomaticFailoverStatusEnabled, + AutomaticFailoverStatusDisabled, + AutomaticFailoverStatusEnabling, + AutomaticFailoverStatusDisabling, + } +} + const ( // ChangeTypeImmediate is a ChangeType enum value ChangeTypeImmediate = "immediate" @@ -17253,6 +17320,30 @@ const ( ChangeTypeRequiresReboot = "requires-reboot" ) +// ChangeType_Values returns all elements of the ChangeType enum +func ChangeType_Values() []string { + return []string{ + ChangeTypeImmediate, + ChangeTypeRequiresReboot, + } +} + +const ( + // MultiAZStatusEnabled is a MultiAZStatus enum value + MultiAZStatusEnabled = "enabled" + + // MultiAZStatusDisabled is a MultiAZStatus enum value + MultiAZStatusDisabled = "disabled" +) + +// MultiAZStatus_Values returns all elements of the MultiAZStatus enum +func MultiAZStatus_Values() []string { + return []string{ + MultiAZStatusEnabled, + MultiAZStatusDisabled, + } +} + const ( // NodeUpdateInitiatedBySystem is a NodeUpdateInitiatedBy enum value NodeUpdateInitiatedBySystem = "system" @@ -17261,6 +17352,14 @@ const ( NodeUpdateInitiatedByCustomer = "customer" ) +// NodeUpdateInitiatedBy_Values returns all elements of the NodeUpdateInitiatedBy enum +func NodeUpdateInitiatedBy_Values() []string { + return []string{ + NodeUpdateInitiatedBySystem, + NodeUpdateInitiatedByCustomer, + } +} + const ( // NodeUpdateStatusNotApplied is a NodeUpdateStatus enum value NodeUpdateStatusNotApplied = "not-applied" @@ -17281,6 +17380,18 @@ const ( NodeUpdateStatusComplete = "complete" ) +// NodeUpdateStatus_Values returns all elements of the NodeUpdateStatus enum +func NodeUpdateStatus_Values() []string { + return []string{ + NodeUpdateStatusNotApplied, + NodeUpdateStatusWaitingToStart, + NodeUpdateStatusInProgress, + NodeUpdateStatusStopping, + NodeUpdateStatusStopped, + NodeUpdateStatusComplete, + } +} + const ( // PendingAutomaticFailoverStatusEnabled is a PendingAutomaticFailoverStatus enum value PendingAutomaticFailoverStatusEnabled = "enabled" @@ -17289,6 +17400,14 @@ const ( PendingAutomaticFailoverStatusDisabled = "disabled" ) +// PendingAutomaticFailoverStatus_Values returns all elements of the PendingAutomaticFailoverStatus enum +func PendingAutomaticFailoverStatus_Values() []string { + return []string{ + PendingAutomaticFailoverStatusEnabled, + PendingAutomaticFailoverStatusDisabled, + } +} + const ( // ServiceUpdateSeverityCritical is a ServiceUpdateSeverity enum value ServiceUpdateSeverityCritical = "critical" @@ -17303,6 +17422,16 @@ const ( ServiceUpdateSeverityLow = "low" ) +// ServiceUpdateSeverity_Values returns all elements of the ServiceUpdateSeverity enum +func ServiceUpdateSeverity_Values() []string { + return []string{ + ServiceUpdateSeverityCritical, + ServiceUpdateSeverityImportant, + ServiceUpdateSeverityMedium, + ServiceUpdateSeverityLow, + } +} + const ( // ServiceUpdateStatusAvailable is a ServiceUpdateStatus enum value ServiceUpdateStatusAvailable = "available" @@ -17314,11 +17443,27 @@ const ( ServiceUpdateStatusExpired = "expired" ) +// ServiceUpdateStatus_Values returns all elements of the ServiceUpdateStatus enum +func ServiceUpdateStatus_Values() []string { + return []string{ + ServiceUpdateStatusAvailable, + ServiceUpdateStatusCancelled, + ServiceUpdateStatusExpired, + } +} + const ( // ServiceUpdateTypeSecurityUpdate is a ServiceUpdateType enum value ServiceUpdateTypeSecurityUpdate = "security-update" ) +// ServiceUpdateType_Values returns all elements of the ServiceUpdateType enum +func ServiceUpdateType_Values() []string { + return []string{ + ServiceUpdateTypeSecurityUpdate, + } +} + const ( // SlaMetYes is a SlaMet enum value SlaMetYes = "yes" @@ -17330,6 +17475,15 @@ const ( SlaMetNA = "n/a" ) +// SlaMet_Values returns all elements of the SlaMet enum +func SlaMet_Values() []string { + return []string{ + SlaMetYes, + SlaMetNo, + SlaMetNA, + } +} + const ( // SourceTypeCacheCluster is a SourceType enum value SourceTypeCacheCluster = "cache-cluster" @@ -17347,6 +17501,17 @@ const ( SourceTypeReplicationGroup = "replication-group" ) +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeCacheCluster, + SourceTypeCacheParameterGroup, + SourceTypeCacheSecurityGroup, + SourceTypeCacheSubnetGroup, + SourceTypeReplicationGroup, + } +} + const ( // UpdateActionStatusNotApplied is a UpdateActionStatus enum value UpdateActionStatusNotApplied = "not-applied" @@ -17365,4 +17530,28 @@ const ( // UpdateActionStatusComplete is a UpdateActionStatus enum value UpdateActionStatusComplete = "complete" + + // UpdateActionStatusScheduling is a UpdateActionStatus enum value + UpdateActionStatusScheduling = "scheduling" + + // UpdateActionStatusScheduled is a UpdateActionStatus enum value + UpdateActionStatusScheduled = "scheduled" + + // UpdateActionStatusNotApplicable is a UpdateActionStatus enum value + UpdateActionStatusNotApplicable = "not-applicable" ) + +// UpdateActionStatus_Values returns all elements of the UpdateActionStatus enum +func UpdateActionStatus_Values() []string { + return []string{ + UpdateActionStatusNotApplied, + UpdateActionStatusWaitingToStart, + UpdateActionStatusInProgress, + UpdateActionStatusStopping, + UpdateActionStatusStopped, + UpdateActionStatusComplete, + UpdateActionStatusScheduling, + UpdateActionStatusScheduled, + UpdateActionStatusNotApplicable, + } +} 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 e68e0121ffb..4e78aa9320e 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 @@ -165,7 +165,7 @@ const ( // ErrCodeInvalidGlobalReplicationGroupStateFault for service response error code // "InvalidGlobalReplicationGroupState". // - // The Global Datastore is not available + // The Global Datastore is not available or in primary-only state. ErrCodeInvalidGlobalReplicationGroupStateFault = "InvalidGlobalReplicationGroupState" // ErrCodeInvalidKMSKeyFault for service response error code 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 0a41523adeb..4f9e06cbe86 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 @@ -179,6 +179,91 @@ func (c *ElasticBeanstalk) ApplyEnvironmentManagedActionWithContext(ctx aws.Cont return out, req.Send() } +const opAssociateEnvironmentOperationsRole = "AssociateEnvironmentOperationsRole" + +// AssociateEnvironmentOperationsRoleRequest generates a "aws/request.Request" representing the +// client's request for the AssociateEnvironmentOperationsRole operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See AssociateEnvironmentOperationsRole for more information on using the AssociateEnvironmentOperationsRole +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the AssociateEnvironmentOperationsRoleRequest method. +// req, resp := client.AssociateEnvironmentOperationsRoleRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/AssociateEnvironmentOperationsRole +func (c *ElasticBeanstalk) AssociateEnvironmentOperationsRoleRequest(input *AssociateEnvironmentOperationsRoleInput) (req *request.Request, output *AssociateEnvironmentOperationsRoleOutput) { + op := &request.Operation{ + Name: opAssociateEnvironmentOperationsRole, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &AssociateEnvironmentOperationsRoleInput{} + } + + output = &AssociateEnvironmentOperationsRoleOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// AssociateEnvironmentOperationsRole API operation for AWS Elastic Beanstalk. +// +// Add or change the operations role used by an environment. After this call +// is made, Elastic Beanstalk uses the associated operations role for permissions +// to downstream services during subsequent calls acting on this environment. +// For more information, see Operations roles (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html) +// in the AWS Elastic Beanstalk Developer Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Elastic Beanstalk's +// API operation AssociateEnvironmentOperationsRole for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInsufficientPrivilegesException "InsufficientPrivilegesException" +// The specified account does not have sufficient privileges for one or more +// AWS services. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/AssociateEnvironmentOperationsRole +func (c *ElasticBeanstalk) AssociateEnvironmentOperationsRole(input *AssociateEnvironmentOperationsRoleInput) (*AssociateEnvironmentOperationsRoleOutput, error) { + req, out := c.AssociateEnvironmentOperationsRoleRequest(input) + return out, req.Send() +} + +// AssociateEnvironmentOperationsRoleWithContext is the same as AssociateEnvironmentOperationsRole with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateEnvironmentOperationsRole for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) AssociateEnvironmentOperationsRoleWithContext(ctx aws.Context, input *AssociateEnvironmentOperationsRoleInput, opts ...request.Option) (*AssociateEnvironmentOperationsRoleOutput, error) { + req, out := c.AssociateEnvironmentOperationsRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCheckDNSAvailability = "CheckDNSAvailability" // CheckDNSAvailabilityRequest generates a "aws/request.Request" representing the @@ -1865,6 +1950,12 @@ func (c *ElasticBeanstalk) DescribeEnvironmentManagedActionHistoryRequest(input Name: opDescribeEnvironmentManagedActionHistory, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxItems", + TruncationToken: "", + }, } if input == nil { @@ -1913,6 +2004,58 @@ func (c *ElasticBeanstalk) DescribeEnvironmentManagedActionHistoryWithContext(ct return out, req.Send() } +// DescribeEnvironmentManagedActionHistoryPages iterates over the pages of a DescribeEnvironmentManagedActionHistory operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeEnvironmentManagedActionHistory 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 DescribeEnvironmentManagedActionHistory operation. +// pageNum := 0 +// err := client.DescribeEnvironmentManagedActionHistoryPages(params, +// func(page *elasticbeanstalk.DescribeEnvironmentManagedActionHistoryOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *ElasticBeanstalk) DescribeEnvironmentManagedActionHistoryPages(input *DescribeEnvironmentManagedActionHistoryInput, fn func(*DescribeEnvironmentManagedActionHistoryOutput, bool) bool) error { + return c.DescribeEnvironmentManagedActionHistoryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEnvironmentManagedActionHistoryPagesWithContext same as DescribeEnvironmentManagedActionHistoryPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeEnvironmentManagedActionHistoryPagesWithContext(ctx aws.Context, input *DescribeEnvironmentManagedActionHistoryInput, fn func(*DescribeEnvironmentManagedActionHistoryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEnvironmentManagedActionHistoryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEnvironmentManagedActionHistoryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeEnvironmentManagedActionHistoryOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeEnvironmentManagedActions = "DescribeEnvironmentManagedActions" // DescribeEnvironmentManagedActionsRequest generates a "aws/request.Request" representing the @@ -2451,6 +2594,91 @@ func (c *ElasticBeanstalk) DescribePlatformVersionWithContext(ctx aws.Context, i return out, req.Send() } +const opDisassociateEnvironmentOperationsRole = "DisassociateEnvironmentOperationsRole" + +// DisassociateEnvironmentOperationsRoleRequest generates a "aws/request.Request" representing the +// client's request for the DisassociateEnvironmentOperationsRole operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DisassociateEnvironmentOperationsRole for more information on using the DisassociateEnvironmentOperationsRole +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DisassociateEnvironmentOperationsRoleRequest method. +// req, resp := client.DisassociateEnvironmentOperationsRoleRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DisassociateEnvironmentOperationsRole +func (c *ElasticBeanstalk) DisassociateEnvironmentOperationsRoleRequest(input *DisassociateEnvironmentOperationsRoleInput) (req *request.Request, output *DisassociateEnvironmentOperationsRoleOutput) { + op := &request.Operation{ + Name: opDisassociateEnvironmentOperationsRole, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DisassociateEnvironmentOperationsRoleInput{} + } + + output = &DisassociateEnvironmentOperationsRoleOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(query.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DisassociateEnvironmentOperationsRole API operation for AWS Elastic Beanstalk. +// +// Disassociate the operations role from an environment. After this call is +// made, Elastic Beanstalk uses the caller's permissions for permissions to +// downstream services during subsequent calls acting on this environment. For +// more information, see Operations roles (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html) +// in the AWS Elastic Beanstalk Developer Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Elastic Beanstalk's +// API operation DisassociateEnvironmentOperationsRole for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInsufficientPrivilegesException "InsufficientPrivilegesException" +// The specified account does not have sufficient privileges for one or more +// AWS services. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/DisassociateEnvironmentOperationsRole +func (c *ElasticBeanstalk) DisassociateEnvironmentOperationsRole(input *DisassociateEnvironmentOperationsRoleInput) (*DisassociateEnvironmentOperationsRoleOutput, error) { + req, out := c.DisassociateEnvironmentOperationsRoleRequest(input) + return out, req.Send() +} + +// DisassociateEnvironmentOperationsRoleWithContext is the same as DisassociateEnvironmentOperationsRole with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateEnvironmentOperationsRole for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DisassociateEnvironmentOperationsRoleWithContext(ctx aws.Context, input *DisassociateEnvironmentOperationsRoleInput, opts ...request.Option) (*DisassociateEnvironmentOperationsRoleOutput, error) { + req, out := c.DisassociateEnvironmentOperationsRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opListAvailableSolutionStacks = "ListAvailableSolutionStacks" // ListAvailableSolutionStacksRequest generates a "aws/request.Request" representing the @@ -2693,6 +2921,12 @@ func (c *ElasticBeanstalk) ListPlatformVersionsRequest(input *ListPlatformVersio Name: opListPlatformVersions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, } if input == nil { @@ -2750,6 +2984,58 @@ func (c *ElasticBeanstalk) ListPlatformVersionsWithContext(ctx aws.Context, inpu return out, req.Send() } +// ListPlatformVersionsPages iterates over the pages of a ListPlatformVersions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListPlatformVersions 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 ListPlatformVersions operation. +// pageNum := 0 +// err := client.ListPlatformVersionsPages(params, +// func(page *elasticbeanstalk.ListPlatformVersionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *ElasticBeanstalk) ListPlatformVersionsPages(input *ListPlatformVersionsInput, fn func(*ListPlatformVersionsOutput, bool) bool) error { + return c.ListPlatformVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPlatformVersionsPagesWithContext same as ListPlatformVersionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListPlatformVersionsPagesWithContext(ctx aws.Context, input *ListPlatformVersionsInput, fn func(*ListPlatformVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPlatformVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPlatformVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListPlatformVersionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListTagsForResource = "ListTagsForResource" // ListTagsForResourceRequest generates a "aws/request.Request" representing the @@ -4552,6 +4838,80 @@ func (s *ApplyEnvironmentManagedActionOutput) SetStatus(v string) *ApplyEnvironm return s } +// Request to add or change the operations role used by an environment. +type AssociateEnvironmentOperationsRoleInput struct { + _ struct{} `type:"structure"` + + // The name of the environment to which to set the operations role. + // + // EnvironmentName is a required field + EnvironmentName *string `min:"4" type:"string" required:"true"` + + // The Amazon Resource Name (ARN) of an existing IAM role to be used as the + // environment's operations role. + // + // OperationsRole is a required field + OperationsRole *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s AssociateEnvironmentOperationsRoleInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateEnvironmentOperationsRoleInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AssociateEnvironmentOperationsRoleInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AssociateEnvironmentOperationsRoleInput"} + if s.EnvironmentName == nil { + invalidParams.Add(request.NewErrParamRequired("EnvironmentName")) + } + if s.EnvironmentName != nil && len(*s.EnvironmentName) < 4 { + invalidParams.Add(request.NewErrParamMinLen("EnvironmentName", 4)) + } + if s.OperationsRole == nil { + invalidParams.Add(request.NewErrParamRequired("OperationsRole")) + } + if s.OperationsRole != nil && len(*s.OperationsRole) < 1 { + invalidParams.Add(request.NewErrParamMinLen("OperationsRole", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetEnvironmentName sets the EnvironmentName field's value. +func (s *AssociateEnvironmentOperationsRoleInput) SetEnvironmentName(v string) *AssociateEnvironmentOperationsRoleInput { + s.EnvironmentName = &v + return s +} + +// SetOperationsRole sets the OperationsRole field's value. +func (s *AssociateEnvironmentOperationsRoleInput) SetOperationsRole(v string) *AssociateEnvironmentOperationsRoleInput { + s.OperationsRole = &v + return s +} + +type AssociateEnvironmentOperationsRoleOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s AssociateEnvironmentOperationsRoleOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateEnvironmentOperationsRoleOutput) GoString() string { + return s.String() +} + // Describes an Auto Scaling launch configuration. type AutoScalingGroup struct { _ struct{} `type:"structure"` @@ -5762,6 +6122,15 @@ type CreateEnvironmentInput struct { // for details. GroupName *string `min:"1" type:"string"` + // The Amazon Resource Name (ARN) of an existing IAM role to be used as the + // environment's operations role. If specified, Elastic Beanstalk uses the operations + // role for permissions to downstream services during this call and during subsequent + // calls acting on this environment. To specify an operations role, you must + // have the iam:PassRole permission for the role. For more information, see + // Operations roles (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html) + // in the AWS Elastic Beanstalk Developer Guide. + OperationsRole *string `min:"1" type:"string"` + // If specified, AWS Elastic Beanstalk sets the specified configuration options // to the requested value in the configuration set for the new environment. // These override the values obtained from the solution stack or the configuration @@ -5839,6 +6208,9 @@ func (s *CreateEnvironmentInput) Validate() error { if s.GroupName != nil && len(*s.GroupName) < 1 { invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) } + if s.OperationsRole != nil && len(*s.OperationsRole) < 1 { + invalidParams.Add(request.NewErrParamMinLen("OperationsRole", 1)) + } if s.TemplateName != nil && len(*s.TemplateName) < 1 { invalidParams.Add(request.NewErrParamMinLen("TemplateName", 1)) } @@ -5912,6 +6284,12 @@ func (s *CreateEnvironmentInput) SetGroupName(v string) *CreateEnvironmentInput return s } +// SetOperationsRole sets the OperationsRole field's value. +func (s *CreateEnvironmentInput) SetOperationsRole(v string) *CreateEnvironmentInput { + s.OperationsRole = &v + return s +} + // SetOptionSettings sets the OptionSettings field's value. func (s *CreateEnvironmentInput) SetOptionSettings(v []*ConfigurationOptionSetting) *CreateEnvironmentInput { s.OptionSettings = v @@ -7896,6 +8274,62 @@ func (s *DescribePlatformVersionOutput) SetPlatformDescription(v *PlatformDescri return s } +// Request to disassociate the operations role from an environment. +type DisassociateEnvironmentOperationsRoleInput struct { + _ struct{} `type:"structure"` + + // The name of the environment from which to disassociate the operations role. + // + // EnvironmentName is a required field + EnvironmentName *string `min:"4" type:"string" required:"true"` +} + +// String returns the string representation +func (s DisassociateEnvironmentOperationsRoleInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisassociateEnvironmentOperationsRoleInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DisassociateEnvironmentOperationsRoleInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DisassociateEnvironmentOperationsRoleInput"} + if s.EnvironmentName == nil { + invalidParams.Add(request.NewErrParamRequired("EnvironmentName")) + } + if s.EnvironmentName != nil && len(*s.EnvironmentName) < 4 { + invalidParams.Add(request.NewErrParamMinLen("EnvironmentName", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetEnvironmentName sets the EnvironmentName field's value. +func (s *DisassociateEnvironmentOperationsRoleInput) SetEnvironmentName(v string) *DisassociateEnvironmentOperationsRoleInput { + s.EnvironmentName = &v + return s +} + +type DisassociateEnvironmentOperationsRoleOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DisassociateEnvironmentOperationsRoleOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisassociateEnvironmentOperationsRoleOutput) GoString() string { + return s.String() +} + // Describes the properties of an environment. type EnvironmentDescription struct { _ struct{} `type:"structure"` @@ -7962,6 +8396,11 @@ type EnvironmentDescription struct { // For more information, see Health Colors and Statuses (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/health-enhanced-status.html). HealthStatus *string `type:"string" enum:"EnvironmentHealthStatus"` + // The Amazon Resource Name (ARN) of the environment's operations role. For + // more information, see Operations roles (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html) + // in the AWS Elastic Beanstalk Developer Guide. + OperationsRole *string `min:"1" type:"string"` + // The ARN of the platform version. PlatformArn *string `type:"string"` @@ -8084,6 +8523,12 @@ func (s *EnvironmentDescription) SetHealthStatus(v string) *EnvironmentDescripti return s } +// SetOperationsRole sets the OperationsRole field's value. +func (s *EnvironmentDescription) SetOperationsRole(v string) *EnvironmentDescription { + s.OperationsRole = &v + return s +} + // SetPlatformArn sets the PlatformArn field's value. func (s *EnvironmentDescription) SetPlatformArn(v string) *EnvironmentDescription { s.PlatformArn = &v @@ -11795,14 +12240,16 @@ type UpdateTagsForResourceInput struct { // ResourceArn is a required field ResourceArn *string `type:"string" required:"true"` - // A list of tags to add or update. + // A list of tags to add or update. If a key of an existing tag is added, the + // tag's value is updated. // - // If a key of an existing tag is added, the tag's value is updated. + // Specify at least one of these parameters: TagsToAdd, TagsToRemove. TagsToAdd []*Tag `type:"list"` - // A list of tag keys to remove. + // A list of tag keys to remove. If a tag key doesn't exist, it is silently + // ignored. // - // If a tag key doesn't exist, it is silently ignored. + // Specify at least one of these parameters: TagsToAdd, TagsToRemove. TagsToRemove []*string `type:"list"` } @@ -12058,6 +12505,15 @@ const ( ActionHistoryStatusUnknown = "Unknown" ) +// ActionHistoryStatus_Values returns all elements of the ActionHistoryStatus enum +func ActionHistoryStatus_Values() []string { + return []string{ + ActionHistoryStatusCompleted, + ActionHistoryStatusFailed, + ActionHistoryStatusUnknown, + } +} + const ( // ActionStatusScheduled is a ActionStatus enum value ActionStatusScheduled = "Scheduled" @@ -12072,6 +12528,16 @@ const ( ActionStatusUnknown = "Unknown" ) +// ActionStatus_Values returns all elements of the ActionStatus enum +func ActionStatus_Values() []string { + return []string{ + ActionStatusScheduled, + ActionStatusPending, + ActionStatusRunning, + ActionStatusUnknown, + } +} + const ( // ActionTypeInstanceRefresh is a ActionType enum value ActionTypeInstanceRefresh = "InstanceRefresh" @@ -12083,6 +12549,15 @@ const ( ActionTypeUnknown = "Unknown" ) +// ActionType_Values returns all elements of the ActionType enum +func ActionType_Values() []string { + return []string{ + ActionTypeInstanceRefresh, + ActionTypePlatformUpdate, + ActionTypeUnknown, + } +} + const ( // ApplicationVersionStatusProcessed is a ApplicationVersionStatus enum value ApplicationVersionStatusProcessed = "Processed" @@ -12100,6 +12575,17 @@ const ( ApplicationVersionStatusBuilding = "Building" ) +// ApplicationVersionStatus_Values returns all elements of the ApplicationVersionStatus enum +func ApplicationVersionStatus_Values() []string { + return []string{ + ApplicationVersionStatusProcessed, + ApplicationVersionStatusUnprocessed, + ApplicationVersionStatusFailed, + ApplicationVersionStatusProcessing, + ApplicationVersionStatusBuilding, + } +} + const ( // ComputeTypeBuildGeneral1Small is a ComputeType enum value ComputeTypeBuildGeneral1Small = "BUILD_GENERAL1_SMALL" @@ -12111,6 +12597,15 @@ const ( ComputeTypeBuildGeneral1Large = "BUILD_GENERAL1_LARGE" ) +// ComputeType_Values returns all elements of the ComputeType enum +func ComputeType_Values() []string { + return []string{ + ComputeTypeBuildGeneral1Small, + ComputeTypeBuildGeneral1Medium, + ComputeTypeBuildGeneral1Large, + } +} + const ( // ConfigurationDeploymentStatusDeployed is a ConfigurationDeploymentStatus enum value ConfigurationDeploymentStatusDeployed = "deployed" @@ -12122,6 +12617,15 @@ const ( ConfigurationDeploymentStatusFailed = "failed" ) +// ConfigurationDeploymentStatus_Values returns all elements of the ConfigurationDeploymentStatus enum +func ConfigurationDeploymentStatus_Values() []string { + return []string{ + ConfigurationDeploymentStatusDeployed, + ConfigurationDeploymentStatusPending, + ConfigurationDeploymentStatusFailed, + } +} + const ( // ConfigurationOptionValueTypeScalar is a ConfigurationOptionValueType enum value ConfigurationOptionValueTypeScalar = "Scalar" @@ -12130,6 +12634,14 @@ const ( ConfigurationOptionValueTypeList = "List" ) +// ConfigurationOptionValueType_Values returns all elements of the ConfigurationOptionValueType enum +func ConfigurationOptionValueType_Values() []string { + return []string{ + ConfigurationOptionValueTypeScalar, + ConfigurationOptionValueTypeList, + } +} + const ( // EnvironmentHealthGreen is a EnvironmentHealth enum value EnvironmentHealthGreen = "Green" @@ -12144,6 +12656,16 @@ const ( EnvironmentHealthGrey = "Grey" ) +// EnvironmentHealth_Values returns all elements of the EnvironmentHealth enum +func EnvironmentHealth_Values() []string { + return []string{ + EnvironmentHealthGreen, + EnvironmentHealthYellow, + EnvironmentHealthRed, + EnvironmentHealthGrey, + } +} + const ( // EnvironmentHealthAttributeStatus is a EnvironmentHealthAttribute enum value EnvironmentHealthAttributeStatus = "Status" @@ -12170,6 +12692,20 @@ const ( EnvironmentHealthAttributeRefreshedAt = "RefreshedAt" ) +// EnvironmentHealthAttribute_Values returns all elements of the EnvironmentHealthAttribute enum +func EnvironmentHealthAttribute_Values() []string { + return []string{ + EnvironmentHealthAttributeStatus, + EnvironmentHealthAttributeColor, + EnvironmentHealthAttributeCauses, + EnvironmentHealthAttributeApplicationMetrics, + EnvironmentHealthAttributeInstancesHealth, + EnvironmentHealthAttributeAll, + EnvironmentHealthAttributeHealthStatus, + EnvironmentHealthAttributeRefreshedAt, + } +} + const ( // EnvironmentHealthStatusNoData is a EnvironmentHealthStatus enum value EnvironmentHealthStatusNoData = "NoData" @@ -12199,6 +12735,21 @@ const ( EnvironmentHealthStatusSuspended = "Suspended" ) +// EnvironmentHealthStatus_Values returns all elements of the EnvironmentHealthStatus enum +func EnvironmentHealthStatus_Values() []string { + return []string{ + EnvironmentHealthStatusNoData, + EnvironmentHealthStatusUnknown, + EnvironmentHealthStatusPending, + EnvironmentHealthStatusOk, + EnvironmentHealthStatusInfo, + EnvironmentHealthStatusWarning, + EnvironmentHealthStatusDegraded, + EnvironmentHealthStatusSevere, + EnvironmentHealthStatusSuspended, + } +} + const ( // EnvironmentInfoTypeTail is a EnvironmentInfoType enum value EnvironmentInfoTypeTail = "tail" @@ -12207,6 +12758,14 @@ const ( EnvironmentInfoTypeBundle = "bundle" ) +// EnvironmentInfoType_Values returns all elements of the EnvironmentInfoType enum +func EnvironmentInfoType_Values() []string { + return []string{ + EnvironmentInfoTypeTail, + EnvironmentInfoTypeBundle, + } +} + const ( // EnvironmentStatusLaunching is a EnvironmentStatus enum value EnvironmentStatusLaunching = "Launching" @@ -12224,6 +12783,17 @@ const ( EnvironmentStatusTerminated = "Terminated" ) +// EnvironmentStatus_Values returns all elements of the EnvironmentStatus enum +func EnvironmentStatus_Values() []string { + return []string{ + EnvironmentStatusLaunching, + EnvironmentStatusUpdating, + EnvironmentStatusReady, + EnvironmentStatusTerminating, + EnvironmentStatusTerminated, + } +} + const ( // EventSeverityTrace is a EventSeverity enum value EventSeverityTrace = "TRACE" @@ -12244,6 +12814,18 @@ const ( EventSeverityFatal = "FATAL" ) +// EventSeverity_Values returns all elements of the EventSeverity enum +func EventSeverity_Values() []string { + return []string{ + EventSeverityTrace, + EventSeverityDebug, + EventSeverityInfo, + EventSeverityWarn, + EventSeverityError, + EventSeverityFatal, + } +} + const ( // FailureTypeUpdateCancelled is a FailureType enum value FailureTypeUpdateCancelled = "UpdateCancelled" @@ -12267,6 +12849,19 @@ const ( FailureTypePermissionsError = "PermissionsError" ) +// FailureType_Values returns all elements of the FailureType enum +func FailureType_Values() []string { + return []string{ + FailureTypeUpdateCancelled, + FailureTypeCancellationFailed, + FailureTypeRollbackFailed, + FailureTypeRollbackSuccessful, + FailureTypeInternalFailure, + FailureTypeInvalidEnvironmentState, + FailureTypePermissionsError, + } +} + const ( // InstancesHealthAttributeHealthStatus is a InstancesHealthAttribute enum value InstancesHealthAttributeHealthStatus = "HealthStatus" @@ -12302,6 +12897,23 @@ const ( InstancesHealthAttributeAll = "All" ) +// InstancesHealthAttribute_Values returns all elements of the InstancesHealthAttribute enum +func InstancesHealthAttribute_Values() []string { + return []string{ + InstancesHealthAttributeHealthStatus, + InstancesHealthAttributeColor, + InstancesHealthAttributeCauses, + InstancesHealthAttributeApplicationMetrics, + InstancesHealthAttributeRefreshedAt, + InstancesHealthAttributeLaunchedAt, + InstancesHealthAttributeSystem, + InstancesHealthAttributeDeployment, + InstancesHealthAttributeAvailabilityZone, + InstancesHealthAttributeInstanceType, + InstancesHealthAttributeAll, + } +} + const ( // PlatformStatusCreating is a PlatformStatus enum value PlatformStatusCreating = "Creating" @@ -12319,6 +12931,17 @@ const ( PlatformStatusDeleted = "Deleted" ) +// PlatformStatus_Values returns all elements of the PlatformStatus enum +func PlatformStatus_Values() []string { + return []string{ + PlatformStatusCreating, + PlatformStatusFailed, + PlatformStatusReady, + PlatformStatusDeleting, + PlatformStatusDeleted, + } +} + const ( // SourceRepositoryCodeCommit is a SourceRepository enum value SourceRepositoryCodeCommit = "CodeCommit" @@ -12327,6 +12950,14 @@ const ( SourceRepositoryS3 = "S3" ) +// SourceRepository_Values returns all elements of the SourceRepository enum +func SourceRepository_Values() []string { + return []string{ + SourceRepositoryCodeCommit, + SourceRepositoryS3, + } +} + const ( // SourceTypeGit is a SourceType enum value SourceTypeGit = "Git" @@ -12335,6 +12966,14 @@ const ( SourceTypeZip = "Zip" ) +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeGit, + SourceTypeZip, + } +} + const ( // ValidationSeverityError is a ValidationSeverity enum value ValidationSeverityError = "error" @@ -12342,3 +12981,11 @@ const ( // ValidationSeverityWarning is a ValidationSeverity enum value ValidationSeverityWarning = "warning" ) + +// ValidationSeverity_Values returns all elements of the ValidationSeverity enum +func ValidationSeverity_Values() []string { + return []string{ + ValidationSeverityError, + ValidationSeverityWarning, + } +} 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 index 3a180495824..9e4abcaea29 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/doc.go @@ -9,8 +9,8 @@ // // 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). +// latest AWS Elastic Beanstalk WSDL is https://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl +// (https://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/). diff --git a/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/waiters.go new file mode 100644 index 00000000000..c02c0aba934 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/elasticbeanstalk/waiters.go @@ -0,0 +1,163 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package elasticbeanstalk + +import ( + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" +) + +// WaitUntilEnvironmentExists uses the Elastic Beanstalk API operation +// DescribeEnvironments to wait for a condition to be met before returning. +// If the condition is not met within the max attempt window, an error will +// be returned. +func (c *ElasticBeanstalk) WaitUntilEnvironmentExists(input *DescribeEnvironmentsInput) error { + return c.WaitUntilEnvironmentExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilEnvironmentExistsWithContext is an extended version of WaitUntilEnvironmentExists. +// 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 *ElasticBeanstalk) WaitUntilEnvironmentExistsWithContext(ctx aws.Context, input *DescribeEnvironmentsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilEnvironmentExists", + MaxAttempts: 20, + Delay: request.ConstantWaiterDelay(20 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Environments[].Status", + Expected: "Ready", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Environments[].Status", + Expected: "Launching", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeEnvironmentsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEnvironmentsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} + +// WaitUntilEnvironmentTerminated uses the Elastic Beanstalk API operation +// DescribeEnvironments to wait for a condition to be met before returning. +// If the condition is not met within the max attempt window, an error will +// be returned. +func (c *ElasticBeanstalk) WaitUntilEnvironmentTerminated(input *DescribeEnvironmentsInput) error { + return c.WaitUntilEnvironmentTerminatedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilEnvironmentTerminatedWithContext is an extended version of WaitUntilEnvironmentTerminated. +// 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 *ElasticBeanstalk) WaitUntilEnvironmentTerminatedWithContext(ctx aws.Context, input *DescribeEnvironmentsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilEnvironmentTerminated", + MaxAttempts: 20, + Delay: request.ConstantWaiterDelay(20 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Environments[].Status", + Expected: "Terminated", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Environments[].Status", + Expected: "Terminating", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeEnvironmentsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEnvironmentsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} + +// WaitUntilEnvironmentUpdated uses the Elastic Beanstalk API operation +// DescribeEnvironments to wait for a condition to be met before returning. +// If the condition is not met within the max attempt window, an error will +// be returned. +func (c *ElasticBeanstalk) WaitUntilEnvironmentUpdated(input *DescribeEnvironmentsInput) error { + return c.WaitUntilEnvironmentUpdatedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilEnvironmentUpdatedWithContext is an extended version of WaitUntilEnvironmentUpdated. +// 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 *ElasticBeanstalk) WaitUntilEnvironmentUpdatedWithContext(ctx aws.Context, input *DescribeEnvironmentsInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilEnvironmentUpdated", + MaxAttempts: 20, + Delay: request.ConstantWaiterDelay(20 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Environments[].Status", + Expected: "Ready", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathAllWaiterMatch, Argument: "Environments[].Status", + Expected: "Updating", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeEnvironmentsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEnvironmentsRequest(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/elasticsearchservice/api.go b/vendor/github.com/aws/aws-sdk-go/service/elasticsearchservice/api.go index ce50a0588d5..888f303cba3 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 @@ -13,6 +13,92 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restjson" ) +const opAcceptInboundCrossClusterSearchConnection = "AcceptInboundCrossClusterSearchConnection" + +// AcceptInboundCrossClusterSearchConnectionRequest generates a "aws/request.Request" representing the +// client's request for the AcceptInboundCrossClusterSearchConnection operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See AcceptInboundCrossClusterSearchConnection for more information on using the AcceptInboundCrossClusterSearchConnection +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the AcceptInboundCrossClusterSearchConnectionRequest method. +// req, resp := client.AcceptInboundCrossClusterSearchConnectionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *ElasticsearchService) AcceptInboundCrossClusterSearchConnectionRequest(input *AcceptInboundCrossClusterSearchConnectionInput) (req *request.Request, output *AcceptInboundCrossClusterSearchConnectionOutput) { + op := &request.Operation{ + Name: opAcceptInboundCrossClusterSearchConnection, + HTTPMethod: "PUT", + HTTPPath: "/2015-01-01/es/ccs/inboundConnection/{ConnectionId}/accept", + } + + if input == nil { + input = &AcceptInboundCrossClusterSearchConnectionInput{} + } + + output = &AcceptInboundCrossClusterSearchConnectionOutput{} + req = c.newRequest(op, input, output) + return +} + +// AcceptInboundCrossClusterSearchConnection API operation for Amazon Elasticsearch Service. +// +// Allows the destination domain owner to accept an inbound cross-cluster search +// connection 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 Amazon Elasticsearch Service's +// API operation AcceptInboundCrossClusterSearchConnection for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// An exception for accessing or deleting a resource that does not exist. Gives +// http status code of 400. +// +// * LimitExceededException +// An exception for trying to create more than allowed resources or sub-resources. +// Gives http status code of 409. +// +// * DisabledOperationException +// An error occured because the client wanted to access a not supported operation. +// Gives http status code of 409. +// +func (c *ElasticsearchService) AcceptInboundCrossClusterSearchConnection(input *AcceptInboundCrossClusterSearchConnectionInput) (*AcceptInboundCrossClusterSearchConnectionOutput, error) { + req, out := c.AcceptInboundCrossClusterSearchConnectionRequest(input) + return out, req.Send() +} + +// AcceptInboundCrossClusterSearchConnectionWithContext is the same as AcceptInboundCrossClusterSearchConnection with the addition of +// the ability to pass a context and additional request options. +// +// See AcceptInboundCrossClusterSearchConnection for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) AcceptInboundCrossClusterSearchConnectionWithContext(ctx aws.Context, input *AcceptInboundCrossClusterSearchConnectionInput, opts ...request.Option) (*AcceptInboundCrossClusterSearchConnectionOutput, error) { + req, out := c.AcceptInboundCrossClusterSearchConnectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opAddTags = "AddTags" // AddTagsRequest generates a "aws/request.Request" representing the @@ -396,6 +482,97 @@ func (c *ElasticsearchService) CreateElasticsearchDomainWithContext(ctx aws.Cont return out, req.Send() } +const opCreateOutboundCrossClusterSearchConnection = "CreateOutboundCrossClusterSearchConnection" + +// CreateOutboundCrossClusterSearchConnectionRequest generates a "aws/request.Request" representing the +// client's request for the CreateOutboundCrossClusterSearchConnection operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateOutboundCrossClusterSearchConnection for more information on using the CreateOutboundCrossClusterSearchConnection +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateOutboundCrossClusterSearchConnectionRequest method. +// req, resp := client.CreateOutboundCrossClusterSearchConnectionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *ElasticsearchService) CreateOutboundCrossClusterSearchConnectionRequest(input *CreateOutboundCrossClusterSearchConnectionInput) (req *request.Request, output *CreateOutboundCrossClusterSearchConnectionOutput) { + op := &request.Operation{ + Name: opCreateOutboundCrossClusterSearchConnection, + HTTPMethod: "POST", + HTTPPath: "/2015-01-01/es/ccs/outboundConnection", + } + + if input == nil { + input = &CreateOutboundCrossClusterSearchConnectionInput{} + } + + output = &CreateOutboundCrossClusterSearchConnectionOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateOutboundCrossClusterSearchConnection API operation for Amazon Elasticsearch Service. +// +// Creates a new cross-cluster search connection from a source domain to a destination +// domain. +// +// Returns awserr.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 Elasticsearch Service's +// API operation CreateOutboundCrossClusterSearchConnection for usage and error information. +// +// Returned Error Types: +// * LimitExceededException +// An exception for trying to create more than allowed resources or sub-resources. +// Gives http status code of 409. +// +// * InternalException +// The request processing has failed because of an unknown error, exception +// or failure (the failure is internal to the service) . Gives http status code +// of 500. +// +// * ResourceAlreadyExistsException +// An exception for creating a resource that already exists. Gives http status +// code of 400. +// +// * DisabledOperationException +// An error occured because the client wanted to access a not supported operation. +// Gives http status code of 409. +// +func (c *ElasticsearchService) CreateOutboundCrossClusterSearchConnection(input *CreateOutboundCrossClusterSearchConnectionInput) (*CreateOutboundCrossClusterSearchConnectionOutput, error) { + req, out := c.CreateOutboundCrossClusterSearchConnectionRequest(input) + return out, req.Send() +} + +// CreateOutboundCrossClusterSearchConnectionWithContext is the same as CreateOutboundCrossClusterSearchConnection with the addition of +// the ability to pass a context and additional request options. +// +// See CreateOutboundCrossClusterSearchConnection for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) CreateOutboundCrossClusterSearchConnectionWithContext(ctx aws.Context, input *CreateOutboundCrossClusterSearchConnectionInput, opts ...request.Option) (*CreateOutboundCrossClusterSearchConnectionOutput, error) { + req, out := c.CreateOutboundCrossClusterSearchConnectionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreatePackage = "CreatePackage" // CreatePackageRequest generates a "aws/request.Request" representing the @@ -677,245 +854,220 @@ func (c *ElasticsearchService) DeleteElasticsearchServiceRoleWithContext(ctx aws return out, req.Send() } -const opDeletePackage = "DeletePackage" +const opDeleteInboundCrossClusterSearchConnection = "DeleteInboundCrossClusterSearchConnection" -// DeletePackageRequest generates a "aws/request.Request" representing the -// client's request for the DeletePackage operation. The "output" return +// DeleteInboundCrossClusterSearchConnectionRequest generates a "aws/request.Request" representing the +// client's request for the DeleteInboundCrossClusterSearchConnection operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeletePackage for more information on using the DeletePackage +// See DeleteInboundCrossClusterSearchConnection for more information on using the DeleteInboundCrossClusterSearchConnection // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeletePackageRequest method. -// req, resp := client.DeletePackageRequest(params) +// // Example sending a request using the DeleteInboundCrossClusterSearchConnectionRequest method. +// req, resp := client.DeleteInboundCrossClusterSearchConnectionRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } -func (c *ElasticsearchService) DeletePackageRequest(input *DeletePackageInput) (req *request.Request, output *DeletePackageOutput) { +func (c *ElasticsearchService) DeleteInboundCrossClusterSearchConnectionRequest(input *DeleteInboundCrossClusterSearchConnectionInput) (req *request.Request, output *DeleteInboundCrossClusterSearchConnectionOutput) { op := &request.Operation{ - Name: opDeletePackage, + Name: opDeleteInboundCrossClusterSearchConnection, HTTPMethod: "DELETE", - HTTPPath: "/2015-01-01/packages/{PackageID}", + HTTPPath: "/2015-01-01/es/ccs/inboundConnection/{ConnectionId}", } if input == nil { - input = &DeletePackageInput{} + input = &DeleteInboundCrossClusterSearchConnectionInput{} } - output = &DeletePackageOutput{} + output = &DeleteInboundCrossClusterSearchConnectionOutput{} req = c.newRequest(op, input, output) return } -// DeletePackage API operation for Amazon Elasticsearch Service. +// DeleteInboundCrossClusterSearchConnection API operation for Amazon Elasticsearch Service. // -// Delete the package. +// Allows the destination domain owner to delete an existing inbound cross-cluster +// search connection. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Elasticsearch Service's -// API operation DeletePackage for usage and error information. +// API operation DeleteInboundCrossClusterSearchConnection for usage and error information. // // Returned Error Types: -// * BaseException -// An error occurred while processing the request. -// -// * InternalException -// The request processing has failed because of an unknown error, exception -// or failure (the failure is internal to the service) . Gives http status code -// of 500. -// // * ResourceNotFoundException // An exception for accessing or deleting a resource that does not exist. Gives // http status code of 400. // -// * AccessDeniedException -// An error occurred because user does not have permissions to access the resource. -// Returns HTTP status code 403. -// -// * ValidationException -// An exception for missing / invalid input fields. Gives http status code of -// 400. -// -// * ConflictException -// An error occurred because the client attempts to remove a resource that is -// currently in use. Returns HTTP status code 409. +// * DisabledOperationException +// An error occured because the client wanted to access a not supported operation. +// Gives http status code of 409. // -func (c *ElasticsearchService) DeletePackage(input *DeletePackageInput) (*DeletePackageOutput, error) { - req, out := c.DeletePackageRequest(input) +func (c *ElasticsearchService) DeleteInboundCrossClusterSearchConnection(input *DeleteInboundCrossClusterSearchConnectionInput) (*DeleteInboundCrossClusterSearchConnectionOutput, error) { + req, out := c.DeleteInboundCrossClusterSearchConnectionRequest(input) return out, req.Send() } -// DeletePackageWithContext is the same as DeletePackage with the addition of +// DeleteInboundCrossClusterSearchConnectionWithContext is the same as DeleteInboundCrossClusterSearchConnection with the addition of // the ability to pass a context and additional request options. // -// See DeletePackage for details on how to use this API operation. +// See DeleteInboundCrossClusterSearchConnection for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) DeletePackageWithContext(ctx aws.Context, input *DeletePackageInput, opts ...request.Option) (*DeletePackageOutput, error) { - req, out := c.DeletePackageRequest(input) +func (c *ElasticsearchService) DeleteInboundCrossClusterSearchConnectionWithContext(ctx aws.Context, input *DeleteInboundCrossClusterSearchConnectionInput, opts ...request.Option) (*DeleteInboundCrossClusterSearchConnectionOutput, error) { + req, out := c.DeleteInboundCrossClusterSearchConnectionRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeElasticsearchDomain = "DescribeElasticsearchDomain" +const opDeleteOutboundCrossClusterSearchConnection = "DeleteOutboundCrossClusterSearchConnection" -// DescribeElasticsearchDomainRequest generates a "aws/request.Request" representing the -// client's request for the DescribeElasticsearchDomain operation. The "output" return +// DeleteOutboundCrossClusterSearchConnectionRequest generates a "aws/request.Request" representing the +// client's request for the DeleteOutboundCrossClusterSearchConnection operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeElasticsearchDomain for more information on using the DescribeElasticsearchDomain +// See DeleteOutboundCrossClusterSearchConnection for more information on using the DeleteOutboundCrossClusterSearchConnection // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeElasticsearchDomainRequest method. -// req, resp := client.DescribeElasticsearchDomainRequest(params) +// // Example sending a request using the DeleteOutboundCrossClusterSearchConnectionRequest method. +// req, resp := client.DeleteOutboundCrossClusterSearchConnectionRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } -func (c *ElasticsearchService) DescribeElasticsearchDomainRequest(input *DescribeElasticsearchDomainInput) (req *request.Request, output *DescribeElasticsearchDomainOutput) { +func (c *ElasticsearchService) DeleteOutboundCrossClusterSearchConnectionRequest(input *DeleteOutboundCrossClusterSearchConnectionInput) (req *request.Request, output *DeleteOutboundCrossClusterSearchConnectionOutput) { op := &request.Operation{ - Name: opDescribeElasticsearchDomain, - HTTPMethod: "GET", - HTTPPath: "/2015-01-01/es/domain/{DomainName}", + Name: opDeleteOutboundCrossClusterSearchConnection, + HTTPMethod: "DELETE", + HTTPPath: "/2015-01-01/es/ccs/outboundConnection/{ConnectionId}", } if input == nil { - input = &DescribeElasticsearchDomainInput{} + input = &DeleteOutboundCrossClusterSearchConnectionInput{} } - output = &DescribeElasticsearchDomainOutput{} + output = &DeleteOutboundCrossClusterSearchConnectionOutput{} req = c.newRequest(op, input, output) return } -// DescribeElasticsearchDomain API operation for Amazon Elasticsearch Service. +// DeleteOutboundCrossClusterSearchConnection API operation for Amazon Elasticsearch Service. // -// Returns domain configuration information about the specified Elasticsearch -// domain, including the domain ID, domain endpoint, and domain ARN. +// Allows the source domain owner to delete an existing outbound cross-cluster +// search connection. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Elasticsearch Service's -// API operation DescribeElasticsearchDomain for usage and error information. +// API operation DeleteOutboundCrossClusterSearchConnection for usage and error information. // // Returned Error Types: -// * BaseException -// An error occurred while processing the request. -// -// * InternalException -// The request processing has failed because of an unknown error, exception -// or failure (the failure is internal to the service) . Gives http status code -// of 500. -// // * ResourceNotFoundException // An exception for accessing or deleting a resource that does not exist. Gives // http status code of 400. // -// * ValidationException -// An exception for missing / invalid input fields. Gives http status code of -// 400. +// * DisabledOperationException +// An error occured because the client wanted to access a not supported operation. +// Gives http status code of 409. // -func (c *ElasticsearchService) DescribeElasticsearchDomain(input *DescribeElasticsearchDomainInput) (*DescribeElasticsearchDomainOutput, error) { - req, out := c.DescribeElasticsearchDomainRequest(input) +func (c *ElasticsearchService) DeleteOutboundCrossClusterSearchConnection(input *DeleteOutboundCrossClusterSearchConnectionInput) (*DeleteOutboundCrossClusterSearchConnectionOutput, error) { + req, out := c.DeleteOutboundCrossClusterSearchConnectionRequest(input) return out, req.Send() } -// DescribeElasticsearchDomainWithContext is the same as DescribeElasticsearchDomain with the addition of +// DeleteOutboundCrossClusterSearchConnectionWithContext is the same as DeleteOutboundCrossClusterSearchConnection 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. +// See DeleteOutboundCrossClusterSearchConnection for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *ElasticsearchService) DeleteOutboundCrossClusterSearchConnectionWithContext(ctx aws.Context, input *DeleteOutboundCrossClusterSearchConnectionInput, opts ...request.Option) (*DeleteOutboundCrossClusterSearchConnectionOutput, error) { + req, out := c.DeleteOutboundCrossClusterSearchConnectionRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeElasticsearchDomainConfig = "DescribeElasticsearchDomainConfig" +const opDeletePackage = "DeletePackage" -// DescribeElasticsearchDomainConfigRequest generates a "aws/request.Request" representing the -// client's request for the DescribeElasticsearchDomainConfig operation. The "output" return +// DeletePackageRequest generates a "aws/request.Request" representing the +// client's request for the DeletePackage operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeElasticsearchDomainConfig for more information on using the DescribeElasticsearchDomainConfig +// See DeletePackage for more information on using the DeletePackage // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeElasticsearchDomainConfigRequest method. -// req, resp := client.DescribeElasticsearchDomainConfigRequest(params) +// // Example sending a request using the DeletePackageRequest method. +// req, resp := client.DeletePackageRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } -func (c *ElasticsearchService) DescribeElasticsearchDomainConfigRequest(input *DescribeElasticsearchDomainConfigInput) (req *request.Request, output *DescribeElasticsearchDomainConfigOutput) { +func (c *ElasticsearchService) DeletePackageRequest(input *DeletePackageInput) (req *request.Request, output *DeletePackageOutput) { op := &request.Operation{ - Name: opDescribeElasticsearchDomainConfig, - HTTPMethod: "GET", - HTTPPath: "/2015-01-01/es/domain/{DomainName}/config", + Name: opDeletePackage, + HTTPMethod: "DELETE", + HTTPPath: "/2015-01-01/packages/{PackageID}", } if input == nil { - input = &DescribeElasticsearchDomainConfigInput{} + input = &DeletePackageInput{} } - output = &DescribeElasticsearchDomainConfigOutput{} + output = &DeletePackageOutput{} req = c.newRequest(op, input, output) return } -// DescribeElasticsearchDomainConfig API operation for Amazon Elasticsearch Service. +// DeletePackage API operation for Amazon Elasticsearch Service. // -// Provides cluster configuration information about the specified Elasticsearch -// domain, such as the state, creation date, update version, and update date -// for cluster options. +// Delete the package. // // Returns awserr.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 Elasticsearch Service's -// API operation DescribeElasticsearchDomainConfig for usage and error information. +// API operation DeletePackage for usage and error information. // // Returned Error Types: // * BaseException @@ -930,16 +1082,205 @@ func (c *ElasticsearchService) DescribeElasticsearchDomainConfigRequest(input *D // An exception for accessing or deleting a resource that does not exist. Gives // http status code of 400. // +// * AccessDeniedException +// An error occurred because user does not have permissions to access the resource. +// Returns HTTP status code 403. +// // * ValidationException // An exception for missing / invalid input fields. Gives http status code of // 400. // -func (c *ElasticsearchService) DescribeElasticsearchDomainConfig(input *DescribeElasticsearchDomainConfigInput) (*DescribeElasticsearchDomainConfigOutput, error) { - req, out := c.DescribeElasticsearchDomainConfigRequest(input) - return out, req.Send() -} - -// DescribeElasticsearchDomainConfigWithContext is the same as DescribeElasticsearchDomainConfig with the addition of +// * ConflictException +// An error occurred because the client attempts to remove a resource that is +// currently in use. Returns HTTP status code 409. +// +func (c *ElasticsearchService) DeletePackage(input *DeletePackageInput) (*DeletePackageOutput, error) { + req, out := c.DeletePackageRequest(input) + return out, req.Send() +} + +// DeletePackageWithContext is the same as DeletePackage with the addition of +// the ability to pass a context and additional request options. +// +// See DeletePackage for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DeletePackageWithContext(ctx aws.Context, input *DeletePackageInput, opts ...request.Option) (*DeletePackageOutput, error) { + req, out := c.DeletePackageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDescribeElasticsearchDomain = "DescribeElasticsearchDomain" + +// DescribeElasticsearchDomainRequest generates a "aws/request.Request" representing the +// client's request for the DescribeElasticsearchDomain operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeElasticsearchDomain for more information on using the DescribeElasticsearchDomain +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeElasticsearchDomainRequest method. +// req, resp := client.DescribeElasticsearchDomainRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *ElasticsearchService) DescribeElasticsearchDomainRequest(input *DescribeElasticsearchDomainInput) (req *request.Request, output *DescribeElasticsearchDomainOutput) { + op := &request.Operation{ + Name: opDescribeElasticsearchDomain, + HTTPMethod: "GET", + HTTPPath: "/2015-01-01/es/domain/{DomainName}", + } + + if input == nil { + input = &DescribeElasticsearchDomainInput{} + } + + output = &DescribeElasticsearchDomainOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeElasticsearchDomain API operation for Amazon Elasticsearch Service. +// +// Returns domain configuration information about the specified Elasticsearch +// domain, including the domain ID, domain endpoint, and domain 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 Amazon Elasticsearch Service's +// API operation DescribeElasticsearchDomain for usage and error information. +// +// Returned Error Types: +// * BaseException +// An error occurred while processing the request. +// +// * InternalException +// The request processing has failed because of an unknown error, exception +// or failure (the failure is internal to the service) . Gives http status code +// of 500. +// +// * ResourceNotFoundException +// An exception for accessing or deleting a resource that does not exist. Gives +// http status code of 400. +// +// * ValidationException +// An exception for missing / invalid input fields. Gives http status code of +// 400. +// +func (c *ElasticsearchService) DescribeElasticsearchDomain(input *DescribeElasticsearchDomainInput) (*DescribeElasticsearchDomainOutput, error) { + req, out := c.DescribeElasticsearchDomainRequest(input) + 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" + +// DescribeElasticsearchDomainConfigRequest generates a "aws/request.Request" representing the +// client's request for the DescribeElasticsearchDomainConfig operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeElasticsearchDomainConfig for more information on using the DescribeElasticsearchDomainConfig +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeElasticsearchDomainConfigRequest method. +// req, resp := client.DescribeElasticsearchDomainConfigRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *ElasticsearchService) DescribeElasticsearchDomainConfigRequest(input *DescribeElasticsearchDomainConfigInput) (req *request.Request, output *DescribeElasticsearchDomainConfigOutput) { + op := &request.Operation{ + Name: opDescribeElasticsearchDomainConfig, + HTTPMethod: "GET", + HTTPPath: "/2015-01-01/es/domain/{DomainName}/config", + } + + if input == nil { + input = &DescribeElasticsearchDomainConfigInput{} + } + + output = &DescribeElasticsearchDomainConfigOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeElasticsearchDomainConfig API operation for Amazon Elasticsearch Service. +// +// Provides cluster configuration information about the specified Elasticsearch +// domain, such as the state, creation date, update version, and update date +// for cluster options. +// +// Returns awserr.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 Elasticsearch Service's +// API operation DescribeElasticsearchDomainConfig for usage and error information. +// +// Returned Error Types: +// * BaseException +// An error occurred while processing the request. +// +// * InternalException +// The request processing has failed because of an unknown error, exception +// or failure (the failure is internal to the service) . Gives http status code +// of 500. +// +// * ResourceNotFoundException +// An exception for accessing or deleting a resource that does not exist. Gives +// http status code of 400. +// +// * ValidationException +// An exception for missing / invalid input fields. Gives http status code of +// 400. +// +func (c *ElasticsearchService) DescribeElasticsearchDomainConfig(input *DescribeElasticsearchDomainConfigInput) (*DescribeElasticsearchDomainConfigOutput, error) { + req, out := c.DescribeElasticsearchDomainConfigRequest(input) + 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. @@ -1140,6 +1481,285 @@ func (c *ElasticsearchService) DescribeElasticsearchInstanceTypeLimitsWithContex return out, req.Send() } +const opDescribeInboundCrossClusterSearchConnections = "DescribeInboundCrossClusterSearchConnections" + +// DescribeInboundCrossClusterSearchConnectionsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeInboundCrossClusterSearchConnections operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeInboundCrossClusterSearchConnections for more information on using the DescribeInboundCrossClusterSearchConnections +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeInboundCrossClusterSearchConnectionsRequest method. +// req, resp := client.DescribeInboundCrossClusterSearchConnectionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *ElasticsearchService) DescribeInboundCrossClusterSearchConnectionsRequest(input *DescribeInboundCrossClusterSearchConnectionsInput) (req *request.Request, output *DescribeInboundCrossClusterSearchConnectionsOutput) { + op := &request.Operation{ + Name: opDescribeInboundCrossClusterSearchConnections, + HTTPMethod: "POST", + HTTPPath: "/2015-01-01/es/ccs/inboundConnection/search", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeInboundCrossClusterSearchConnectionsInput{} + } + + output = &DescribeInboundCrossClusterSearchConnectionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeInboundCrossClusterSearchConnections API operation for Amazon Elasticsearch Service. +// +// Lists all the inbound cross-cluster search connections for a destination +// domain. +// +// Returns awserr.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 Elasticsearch Service's +// API operation DescribeInboundCrossClusterSearchConnections for usage and error information. +// +// Returned Error Types: +// * InvalidPaginationTokenException +// The request processing has failed because of invalid pagination token provided +// by customer. Returns an HTTP status code of 400. +// +// * DisabledOperationException +// An error occured because the client wanted to access a not supported operation. +// Gives http status code of 409. +// +func (c *ElasticsearchService) DescribeInboundCrossClusterSearchConnections(input *DescribeInboundCrossClusterSearchConnectionsInput) (*DescribeInboundCrossClusterSearchConnectionsOutput, error) { + req, out := c.DescribeInboundCrossClusterSearchConnectionsRequest(input) + return out, req.Send() +} + +// DescribeInboundCrossClusterSearchConnectionsWithContext is the same as DescribeInboundCrossClusterSearchConnections with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInboundCrossClusterSearchConnections for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeInboundCrossClusterSearchConnectionsWithContext(ctx aws.Context, input *DescribeInboundCrossClusterSearchConnectionsInput, opts ...request.Option) (*DescribeInboundCrossClusterSearchConnectionsOutput, error) { + req, out := c.DescribeInboundCrossClusterSearchConnectionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeInboundCrossClusterSearchConnectionsPages iterates over the pages of a DescribeInboundCrossClusterSearchConnections operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInboundCrossClusterSearchConnections 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 DescribeInboundCrossClusterSearchConnections operation. +// pageNum := 0 +// err := client.DescribeInboundCrossClusterSearchConnectionsPages(params, +// func(page *elasticsearchservice.DescribeInboundCrossClusterSearchConnectionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *ElasticsearchService) DescribeInboundCrossClusterSearchConnectionsPages(input *DescribeInboundCrossClusterSearchConnectionsInput, fn func(*DescribeInboundCrossClusterSearchConnectionsOutput, bool) bool) error { + return c.DescribeInboundCrossClusterSearchConnectionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInboundCrossClusterSearchConnectionsPagesWithContext same as DescribeInboundCrossClusterSearchConnectionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeInboundCrossClusterSearchConnectionsPagesWithContext(ctx aws.Context, input *DescribeInboundCrossClusterSearchConnectionsInput, fn func(*DescribeInboundCrossClusterSearchConnectionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInboundCrossClusterSearchConnectionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInboundCrossClusterSearchConnectionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInboundCrossClusterSearchConnectionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opDescribeOutboundCrossClusterSearchConnections = "DescribeOutboundCrossClusterSearchConnections" + +// DescribeOutboundCrossClusterSearchConnectionsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeOutboundCrossClusterSearchConnections operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeOutboundCrossClusterSearchConnections for more information on using the DescribeOutboundCrossClusterSearchConnections +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeOutboundCrossClusterSearchConnectionsRequest method. +// req, resp := client.DescribeOutboundCrossClusterSearchConnectionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *ElasticsearchService) DescribeOutboundCrossClusterSearchConnectionsRequest(input *DescribeOutboundCrossClusterSearchConnectionsInput) (req *request.Request, output *DescribeOutboundCrossClusterSearchConnectionsOutput) { + op := &request.Operation{ + Name: opDescribeOutboundCrossClusterSearchConnections, + HTTPMethod: "POST", + HTTPPath: "/2015-01-01/es/ccs/outboundConnection/search", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeOutboundCrossClusterSearchConnectionsInput{} + } + + output = &DescribeOutboundCrossClusterSearchConnectionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeOutboundCrossClusterSearchConnections API operation for Amazon Elasticsearch Service. +// +// Lists all the outbound cross-cluster search connections for a source domain. +// +// Returns awserr.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 Elasticsearch Service's +// API operation DescribeOutboundCrossClusterSearchConnections for usage and error information. +// +// Returned Error Types: +// * InvalidPaginationTokenException +// The request processing has failed because of invalid pagination token provided +// by customer. Returns an HTTP status code of 400. +// +// * DisabledOperationException +// An error occured because the client wanted to access a not supported operation. +// Gives http status code of 409. +// +func (c *ElasticsearchService) DescribeOutboundCrossClusterSearchConnections(input *DescribeOutboundCrossClusterSearchConnectionsInput) (*DescribeOutboundCrossClusterSearchConnectionsOutput, error) { + req, out := c.DescribeOutboundCrossClusterSearchConnectionsRequest(input) + return out, req.Send() +} + +// DescribeOutboundCrossClusterSearchConnectionsWithContext is the same as DescribeOutboundCrossClusterSearchConnections with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeOutboundCrossClusterSearchConnections for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeOutboundCrossClusterSearchConnectionsWithContext(ctx aws.Context, input *DescribeOutboundCrossClusterSearchConnectionsInput, opts ...request.Option) (*DescribeOutboundCrossClusterSearchConnectionsOutput, error) { + req, out := c.DescribeOutboundCrossClusterSearchConnectionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeOutboundCrossClusterSearchConnectionsPages iterates over the pages of a DescribeOutboundCrossClusterSearchConnections operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeOutboundCrossClusterSearchConnections 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 DescribeOutboundCrossClusterSearchConnections operation. +// pageNum := 0 +// err := client.DescribeOutboundCrossClusterSearchConnectionsPages(params, +// func(page *elasticsearchservice.DescribeOutboundCrossClusterSearchConnectionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *ElasticsearchService) DescribeOutboundCrossClusterSearchConnectionsPages(input *DescribeOutboundCrossClusterSearchConnectionsInput, fn func(*DescribeOutboundCrossClusterSearchConnectionsOutput, bool) bool) error { + return c.DescribeOutboundCrossClusterSearchConnectionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeOutboundCrossClusterSearchConnectionsPagesWithContext same as DescribeOutboundCrossClusterSearchConnectionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeOutboundCrossClusterSearchConnectionsPagesWithContext(ctx aws.Context, input *DescribeOutboundCrossClusterSearchConnectionsInput, fn func(*DescribeOutboundCrossClusterSearchConnectionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeOutboundCrossClusterSearchConnectionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeOutboundCrossClusterSearchConnectionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeOutboundCrossClusterSearchConnectionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribePackages = "DescribePackages" // DescribePackagesRequest generates a "aws/request.Request" representing the @@ -2792,99 +3412,181 @@ func (c *ElasticsearchService) ListTagsWithContext(ctx aws.Context, input *ListT return out, req.Send() } -const opPurchaseReservedElasticsearchInstanceOffering = "PurchaseReservedElasticsearchInstanceOffering" +const opPurchaseReservedElasticsearchInstanceOffering = "PurchaseReservedElasticsearchInstanceOffering" + +// PurchaseReservedElasticsearchInstanceOfferingRequest generates a "aws/request.Request" representing the +// client's request for the PurchaseReservedElasticsearchInstanceOffering operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PurchaseReservedElasticsearchInstanceOffering for more information on using the PurchaseReservedElasticsearchInstanceOffering +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PurchaseReservedElasticsearchInstanceOfferingRequest method. +// req, resp := client.PurchaseReservedElasticsearchInstanceOfferingRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *ElasticsearchService) PurchaseReservedElasticsearchInstanceOfferingRequest(input *PurchaseReservedElasticsearchInstanceOfferingInput) (req *request.Request, output *PurchaseReservedElasticsearchInstanceOfferingOutput) { + op := &request.Operation{ + Name: opPurchaseReservedElasticsearchInstanceOffering, + HTTPMethod: "POST", + HTTPPath: "/2015-01-01/es/purchaseReservedInstanceOffering", + } + + if input == nil { + input = &PurchaseReservedElasticsearchInstanceOfferingInput{} + } + + output = &PurchaseReservedElasticsearchInstanceOfferingOutput{} + req = c.newRequest(op, input, output) + return +} + +// PurchaseReservedElasticsearchInstanceOffering API operation for Amazon Elasticsearch Service. +// +// Allows you to purchase reserved Elasticsearch 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 +// the error. +// +// See the AWS API reference guide for Amazon Elasticsearch Service's +// API operation PurchaseReservedElasticsearchInstanceOffering for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// An exception for accessing or deleting a resource that does not exist. Gives +// http status code of 400. +// +// * ResourceAlreadyExistsException +// An exception for creating a resource that already exists. Gives http status +// code of 400. +// +// * LimitExceededException +// An exception for trying to create more than allowed resources or sub-resources. +// Gives http status code of 409. +// +// * DisabledOperationException +// An error occured because the client wanted to access a not supported operation. +// Gives http status code of 409. +// +// * ValidationException +// An exception for missing / invalid input fields. Gives http status code of +// 400. +// +// * InternalException +// The request processing has failed because of an unknown error, exception +// or failure (the failure is internal to the service) . Gives http status code +// of 500. +// +func (c *ElasticsearchService) PurchaseReservedElasticsearchInstanceOffering(input *PurchaseReservedElasticsearchInstanceOfferingInput) (*PurchaseReservedElasticsearchInstanceOfferingOutput, error) { + req, out := c.PurchaseReservedElasticsearchInstanceOfferingRequest(input) + return out, req.Send() +} + +// PurchaseReservedElasticsearchInstanceOfferingWithContext is the same as PurchaseReservedElasticsearchInstanceOffering with the addition of +// the ability to pass a context and additional request options. +// +// See PurchaseReservedElasticsearchInstanceOffering for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) PurchaseReservedElasticsearchInstanceOfferingWithContext(ctx aws.Context, input *PurchaseReservedElasticsearchInstanceOfferingInput, opts ...request.Option) (*PurchaseReservedElasticsearchInstanceOfferingOutput, error) { + req, out := c.PurchaseReservedElasticsearchInstanceOfferingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opRejectInboundCrossClusterSearchConnection = "RejectInboundCrossClusterSearchConnection" -// PurchaseReservedElasticsearchInstanceOfferingRequest generates a "aws/request.Request" representing the -// client's request for the PurchaseReservedElasticsearchInstanceOffering operation. The "output" return +// RejectInboundCrossClusterSearchConnectionRequest generates a "aws/request.Request" representing the +// client's request for the RejectInboundCrossClusterSearchConnection operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See PurchaseReservedElasticsearchInstanceOffering for more information on using the PurchaseReservedElasticsearchInstanceOffering +// See RejectInboundCrossClusterSearchConnection for more information on using the RejectInboundCrossClusterSearchConnection // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the PurchaseReservedElasticsearchInstanceOfferingRequest method. -// req, resp := client.PurchaseReservedElasticsearchInstanceOfferingRequest(params) +// // Example sending a request using the RejectInboundCrossClusterSearchConnectionRequest method. +// req, resp := client.RejectInboundCrossClusterSearchConnectionRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } -func (c *ElasticsearchService) PurchaseReservedElasticsearchInstanceOfferingRequest(input *PurchaseReservedElasticsearchInstanceOfferingInput) (req *request.Request, output *PurchaseReservedElasticsearchInstanceOfferingOutput) { +func (c *ElasticsearchService) RejectInboundCrossClusterSearchConnectionRequest(input *RejectInboundCrossClusterSearchConnectionInput) (req *request.Request, output *RejectInboundCrossClusterSearchConnectionOutput) { op := &request.Operation{ - Name: opPurchaseReservedElasticsearchInstanceOffering, - HTTPMethod: "POST", - HTTPPath: "/2015-01-01/es/purchaseReservedInstanceOffering", + Name: opRejectInboundCrossClusterSearchConnection, + HTTPMethod: "PUT", + HTTPPath: "/2015-01-01/es/ccs/inboundConnection/{ConnectionId}/reject", } if input == nil { - input = &PurchaseReservedElasticsearchInstanceOfferingInput{} + input = &RejectInboundCrossClusterSearchConnectionInput{} } - output = &PurchaseReservedElasticsearchInstanceOfferingOutput{} + output = &RejectInboundCrossClusterSearchConnectionOutput{} req = c.newRequest(op, input, output) return } -// PurchaseReservedElasticsearchInstanceOffering API operation for Amazon Elasticsearch Service. +// RejectInboundCrossClusterSearchConnection API operation for Amazon Elasticsearch Service. // -// Allows you to purchase reserved Elasticsearch instances. +// Allows the destination domain owner to reject an inbound cross-cluster search +// connection 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 Amazon Elasticsearch Service's -// API operation PurchaseReservedElasticsearchInstanceOffering for usage and error information. +// API operation RejectInboundCrossClusterSearchConnection for usage and error information. // // Returned Error Types: // * ResourceNotFoundException // An exception for accessing or deleting a resource that does not exist. Gives // http status code of 400. // -// * ResourceAlreadyExistsException -// An exception for creating a resource that already exists. Gives http status -// code of 400. -// -// * LimitExceededException -// An exception for trying to create more than allowed resources or sub-resources. -// Gives http status code of 409. -// // * DisabledOperationException // An error occured because the client wanted to access a not supported operation. // Gives http status code of 409. // -// * ValidationException -// An exception for missing / invalid input fields. Gives http status code of -// 400. -// -// * InternalException -// The request processing has failed because of an unknown error, exception -// or failure (the failure is internal to the service) . Gives http status code -// of 500. -// -func (c *ElasticsearchService) PurchaseReservedElasticsearchInstanceOffering(input *PurchaseReservedElasticsearchInstanceOfferingInput) (*PurchaseReservedElasticsearchInstanceOfferingOutput, error) { - req, out := c.PurchaseReservedElasticsearchInstanceOfferingRequest(input) +func (c *ElasticsearchService) RejectInboundCrossClusterSearchConnection(input *RejectInboundCrossClusterSearchConnectionInput) (*RejectInboundCrossClusterSearchConnectionOutput, error) { + req, out := c.RejectInboundCrossClusterSearchConnectionRequest(input) return out, req.Send() } -// PurchaseReservedElasticsearchInstanceOfferingWithContext is the same as PurchaseReservedElasticsearchInstanceOffering with the addition of +// RejectInboundCrossClusterSearchConnectionWithContext is the same as RejectInboundCrossClusterSearchConnection with the addition of // the ability to pass a context and additional request options. // -// See PurchaseReservedElasticsearchInstanceOffering for details on how to use this API operation. +// See RejectInboundCrossClusterSearchConnection for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) PurchaseReservedElasticsearchInstanceOfferingWithContext(ctx aws.Context, input *PurchaseReservedElasticsearchInstanceOfferingInput, opts ...request.Option) (*PurchaseReservedElasticsearchInstanceOfferingOutput, error) { - req, out := c.PurchaseReservedElasticsearchInstanceOfferingRequest(input) +func (c *ElasticsearchService) RejectInboundCrossClusterSearchConnectionWithContext(ctx aws.Context, input *RejectInboundCrossClusterSearchConnectionInput, opts ...request.Option) (*RejectInboundCrossClusterSearchConnectionOutput, error) { + req, out := c.RejectInboundCrossClusterSearchConnectionRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() @@ -3261,6 +3963,74 @@ func (c *ElasticsearchService) UpgradeElasticsearchDomainWithContext(ctx aws.Con return out, req.Send() } +// Container for the parameters to the AcceptInboundCrossClusterSearchConnection +// operation. +type AcceptInboundCrossClusterSearchConnectionInput struct { + _ struct{} `type:"structure"` + + // The id of the inbound connection that you want to accept. + // + // CrossClusterSearchConnectionId is a required field + CrossClusterSearchConnectionId *string `location:"uri" locationName:"ConnectionId" type:"string" required:"true"` +} + +// String returns the string representation +func (s AcceptInboundCrossClusterSearchConnectionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AcceptInboundCrossClusterSearchConnectionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AcceptInboundCrossClusterSearchConnectionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AcceptInboundCrossClusterSearchConnectionInput"} + if s.CrossClusterSearchConnectionId == nil { + invalidParams.Add(request.NewErrParamRequired("CrossClusterSearchConnectionId")) + } + if s.CrossClusterSearchConnectionId != nil && len(*s.CrossClusterSearchConnectionId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CrossClusterSearchConnectionId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCrossClusterSearchConnectionId sets the CrossClusterSearchConnectionId field's value. +func (s *AcceptInboundCrossClusterSearchConnectionInput) SetCrossClusterSearchConnectionId(v string) *AcceptInboundCrossClusterSearchConnectionInput { + s.CrossClusterSearchConnectionId = &v + return s +} + +// The result of a AcceptInboundCrossClusterSearchConnection operation. Contains +// details of accepted inbound connection. +type AcceptInboundCrossClusterSearchConnectionOutput struct { + _ struct{} `type:"structure"` + + // Specifies the InboundCrossClusterSearchConnection of accepted inbound connection. + CrossClusterSearchConnection *InboundCrossClusterSearchConnection `type:"structure"` +} + +// String returns the string representation +func (s AcceptInboundCrossClusterSearchConnectionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AcceptInboundCrossClusterSearchConnectionOutput) GoString() string { + return s.String() +} + +// SetCrossClusterSearchConnection sets the CrossClusterSearchConnection field's value. +func (s *AcceptInboundCrossClusterSearchConnectionOutput) SetCrossClusterSearchConnection(v *InboundCrossClusterSearchConnection) *AcceptInboundCrossClusterSearchConnectionOutput { + s.CrossClusterSearchConnection = v + return s +} + // An error occurred because user does not have permissions to access the resource. // Returns HTTP status code 403. type AccessDeniedException struct { @@ -4282,6 +5052,148 @@ func (s *CreateElasticsearchDomainOutput) SetDomainStatus(v *ElasticsearchDomain return s } +// Container for the parameters to the CreateOutboundCrossClusterSearchConnection +// operation. +type CreateOutboundCrossClusterSearchConnectionInput struct { + _ struct{} `type:"structure"` + + // Specifies the connection alias that will be used by the customer for this + // connection. + // + // ConnectionAlias is a required field + ConnectionAlias *string `type:"string" required:"true"` + + // Specifies the DomainInformation for the destination Elasticsearch domain. + // + // DestinationDomainInfo is a required field + DestinationDomainInfo *DomainInformation `type:"structure" required:"true"` + + // Specifies the DomainInformation for the source Elasticsearch domain. + // + // SourceDomainInfo is a required field + SourceDomainInfo *DomainInformation `type:"structure" required:"true"` +} + +// String returns the string representation +func (s CreateOutboundCrossClusterSearchConnectionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateOutboundCrossClusterSearchConnectionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateOutboundCrossClusterSearchConnectionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateOutboundCrossClusterSearchConnectionInput"} + if s.ConnectionAlias == nil { + invalidParams.Add(request.NewErrParamRequired("ConnectionAlias")) + } + if s.DestinationDomainInfo == nil { + invalidParams.Add(request.NewErrParamRequired("DestinationDomainInfo")) + } + if s.SourceDomainInfo == nil { + invalidParams.Add(request.NewErrParamRequired("SourceDomainInfo")) + } + if s.DestinationDomainInfo != nil { + if err := s.DestinationDomainInfo.Validate(); err != nil { + invalidParams.AddNested("DestinationDomainInfo", err.(request.ErrInvalidParams)) + } + } + if s.SourceDomainInfo != nil { + if err := s.SourceDomainInfo.Validate(); err != nil { + invalidParams.AddNested("SourceDomainInfo", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetConnectionAlias sets the ConnectionAlias field's value. +func (s *CreateOutboundCrossClusterSearchConnectionInput) SetConnectionAlias(v string) *CreateOutboundCrossClusterSearchConnectionInput { + s.ConnectionAlias = &v + return s +} + +// SetDestinationDomainInfo sets the DestinationDomainInfo field's value. +func (s *CreateOutboundCrossClusterSearchConnectionInput) SetDestinationDomainInfo(v *DomainInformation) *CreateOutboundCrossClusterSearchConnectionInput { + s.DestinationDomainInfo = v + return s +} + +// SetSourceDomainInfo sets the SourceDomainInfo field's value. +func (s *CreateOutboundCrossClusterSearchConnectionInput) SetSourceDomainInfo(v *DomainInformation) *CreateOutboundCrossClusterSearchConnectionInput { + s.SourceDomainInfo = v + return s +} + +// The result of a CreateOutboundCrossClusterSearchConnection request. Contains +// the details of the newly created cross-cluster search connection. +type CreateOutboundCrossClusterSearchConnectionOutput struct { + _ struct{} `type:"structure"` + + // Specifies the connection alias provided during the create connection request. + ConnectionAlias *string `type:"string"` + + // Specifies the OutboundCrossClusterSearchConnectionStatus for the newly created + // connection. + ConnectionStatus *OutboundCrossClusterSearchConnectionStatus `type:"structure"` + + // Unique id for the created outbound connection, which is used for subsequent + // operations on connection. + CrossClusterSearchConnectionId *string `type:"string"` + + // Specifies the DomainInformation for the destination Elasticsearch domain. + DestinationDomainInfo *DomainInformation `type:"structure"` + + // Specifies the DomainInformation for the source Elasticsearch domain. + SourceDomainInfo *DomainInformation `type:"structure"` +} + +// String returns the string representation +func (s CreateOutboundCrossClusterSearchConnectionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateOutboundCrossClusterSearchConnectionOutput) GoString() string { + return s.String() +} + +// SetConnectionAlias sets the ConnectionAlias field's value. +func (s *CreateOutboundCrossClusterSearchConnectionOutput) SetConnectionAlias(v string) *CreateOutboundCrossClusterSearchConnectionOutput { + s.ConnectionAlias = &v + return s +} + +// SetConnectionStatus sets the ConnectionStatus field's value. +func (s *CreateOutboundCrossClusterSearchConnectionOutput) SetConnectionStatus(v *OutboundCrossClusterSearchConnectionStatus) *CreateOutboundCrossClusterSearchConnectionOutput { + s.ConnectionStatus = v + return s +} + +// SetCrossClusterSearchConnectionId sets the CrossClusterSearchConnectionId field's value. +func (s *CreateOutboundCrossClusterSearchConnectionOutput) SetCrossClusterSearchConnectionId(v string) *CreateOutboundCrossClusterSearchConnectionOutput { + s.CrossClusterSearchConnectionId = &v + return s +} + +// SetDestinationDomainInfo sets the DestinationDomainInfo field's value. +func (s *CreateOutboundCrossClusterSearchConnectionOutput) SetDestinationDomainInfo(v *DomainInformation) *CreateOutboundCrossClusterSearchConnectionOutput { + s.DestinationDomainInfo = v + return s +} + +// SetSourceDomainInfo sets the SourceDomainInfo field's value. +func (s *CreateOutboundCrossClusterSearchConnectionOutput) SetSourceDomainInfo(v *DomainInformation) *CreateOutboundCrossClusterSearchConnectionOutput { + s.SourceDomainInfo = v + return s +} + // Container for request parameters to CreatePackage operation. type CreatePackageInput struct { _ struct{} `type:"structure"` @@ -4366,59 +5278,156 @@ func (s *CreatePackageInput) SetPackageType(v string) *CreatePackageInput { return s } -// Container for response returned by CreatePackage operation. -type CreatePackageOutput struct { - _ struct{} `type:"structure"` +// Container for response returned by CreatePackage operation. +type CreatePackageOutput struct { + _ struct{} `type:"structure"` + + // Information about the package PackageDetails. + PackageDetails *PackageDetails `type:"structure"` +} + +// String returns the string representation +func (s CreatePackageOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreatePackageOutput) GoString() string { + return s.String() +} + +// SetPackageDetails sets the PackageDetails field's value. +func (s *CreatePackageOutput) SetPackageDetails(v *PackageDetails) *CreatePackageOutput { + s.PackageDetails = v + return s +} + +// Container for the parameters to the DeleteElasticsearchDomain operation. +// Specifies the name of the Elasticsearch domain that you want to delete. +type DeleteElasticsearchDomainInput struct { + _ struct{} `type:"structure"` + + // The name of the Elasticsearch domain that you want to permanently delete. + // + // DomainName is a required field + DomainName *string `location:"uri" locationName:"DomainName" min:"3" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteElasticsearchDomainInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteElasticsearchDomainInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteElasticsearchDomainInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteElasticsearchDomainInput"} + if s.DomainName == nil { + invalidParams.Add(request.NewErrParamRequired("DomainName")) + } + if s.DomainName != nil && len(*s.DomainName) < 3 { + invalidParams.Add(request.NewErrParamMinLen("DomainName", 3)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomainName sets the DomainName field's value. +func (s *DeleteElasticsearchDomainInput) SetDomainName(v string) *DeleteElasticsearchDomainInput { + s.DomainName = &v + return s +} + +// The result of a DeleteElasticsearchDomain request. Contains the status of +// the pending deletion, or no status if the domain and all of its resources +// have been deleted. +type DeleteElasticsearchDomainOutput struct { + _ struct{} `type:"structure"` + + // The status of the Elasticsearch domain being deleted. + DomainStatus *ElasticsearchDomainStatus `type:"structure"` +} + +// String returns the string representation +func (s DeleteElasticsearchDomainOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteElasticsearchDomainOutput) GoString() string { + return s.String() +} + +// SetDomainStatus sets the DomainStatus field's value. +func (s *DeleteElasticsearchDomainOutput) SetDomainStatus(v *ElasticsearchDomainStatus) *DeleteElasticsearchDomainOutput { + s.DomainStatus = v + return s +} + +type DeleteElasticsearchServiceRoleInput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteElasticsearchServiceRoleInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteElasticsearchServiceRoleInput) GoString() string { + return s.String() +} - // Information about the package PackageDetails. - PackageDetails *PackageDetails `type:"structure"` +type DeleteElasticsearchServiceRoleOutput struct { + _ struct{} `type:"structure"` } // String returns the string representation -func (s CreatePackageOutput) String() string { +func (s DeleteElasticsearchServiceRoleOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreatePackageOutput) GoString() string { +func (s DeleteElasticsearchServiceRoleOutput) GoString() string { return s.String() } -// SetPackageDetails sets the PackageDetails field's value. -func (s *CreatePackageOutput) SetPackageDetails(v *PackageDetails) *CreatePackageOutput { - s.PackageDetails = v - return s -} - -// Container for the parameters to the DeleteElasticsearchDomain operation. -// Specifies the name of the Elasticsearch domain that you want to delete. -type DeleteElasticsearchDomainInput struct { +// Container for the parameters to the DeleteInboundCrossClusterSearchConnection +// operation. +type DeleteInboundCrossClusterSearchConnectionInput struct { _ struct{} `type:"structure"` - // The name of the Elasticsearch domain that you want to permanently delete. + // The id of the inbound connection that you want to permanently delete. // - // DomainName is a required field - DomainName *string `location:"uri" locationName:"DomainName" min:"3" type:"string" required:"true"` + // CrossClusterSearchConnectionId is a required field + CrossClusterSearchConnectionId *string `location:"uri" locationName:"ConnectionId" type:"string" required:"true"` } // String returns the string representation -func (s DeleteElasticsearchDomainInput) String() string { +func (s DeleteInboundCrossClusterSearchConnectionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteElasticsearchDomainInput) GoString() string { +func (s DeleteInboundCrossClusterSearchConnectionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteElasticsearchDomainInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteElasticsearchDomainInput"} - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) +func (s *DeleteInboundCrossClusterSearchConnectionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteInboundCrossClusterSearchConnectionInput"} + if s.CrossClusterSearchConnectionId == nil { + invalidParams.Add(request.NewErrParamRequired("CrossClusterSearchConnectionId")) } - if s.DomainName != nil && len(*s.DomainName) < 3 { - invalidParams.Add(request.NewErrParamMinLen("DomainName", 3)) + if s.CrossClusterSearchConnectionId != nil && len(*s.CrossClusterSearchConnectionId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CrossClusterSearchConnectionId", 1)) } if invalidParams.Len() > 0 { @@ -4427,66 +5436,105 @@ func (s *DeleteElasticsearchDomainInput) Validate() error { return nil } -// SetDomainName sets the DomainName field's value. -func (s *DeleteElasticsearchDomainInput) SetDomainName(v string) *DeleteElasticsearchDomainInput { - s.DomainName = &v +// SetCrossClusterSearchConnectionId sets the CrossClusterSearchConnectionId field's value. +func (s *DeleteInboundCrossClusterSearchConnectionInput) SetCrossClusterSearchConnectionId(v string) *DeleteInboundCrossClusterSearchConnectionInput { + s.CrossClusterSearchConnectionId = &v return s } -// The result of a DeleteElasticsearchDomain request. Contains the status of -// the pending deletion, or no status if the domain and all of its resources -// have been deleted. -type DeleteElasticsearchDomainOutput struct { +// The result of a DeleteInboundCrossClusterSearchConnection operation. Contains +// details of deleted inbound connection. +type DeleteInboundCrossClusterSearchConnectionOutput struct { _ struct{} `type:"structure"` - // The status of the Elasticsearch domain being deleted. - DomainStatus *ElasticsearchDomainStatus `type:"structure"` + // Specifies the InboundCrossClusterSearchConnection of deleted inbound connection. + CrossClusterSearchConnection *InboundCrossClusterSearchConnection `type:"structure"` } // String returns the string representation -func (s DeleteElasticsearchDomainOutput) String() string { +func (s DeleteInboundCrossClusterSearchConnectionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteElasticsearchDomainOutput) GoString() string { +func (s DeleteInboundCrossClusterSearchConnectionOutput) GoString() string { return s.String() } -// SetDomainStatus sets the DomainStatus field's value. -func (s *DeleteElasticsearchDomainOutput) SetDomainStatus(v *ElasticsearchDomainStatus) *DeleteElasticsearchDomainOutput { - s.DomainStatus = v +// SetCrossClusterSearchConnection sets the CrossClusterSearchConnection field's value. +func (s *DeleteInboundCrossClusterSearchConnectionOutput) SetCrossClusterSearchConnection(v *InboundCrossClusterSearchConnection) *DeleteInboundCrossClusterSearchConnectionOutput { + s.CrossClusterSearchConnection = v return s } -type DeleteElasticsearchServiceRoleInput struct { +// Container for the parameters to the DeleteOutboundCrossClusterSearchConnection +// operation. +type DeleteOutboundCrossClusterSearchConnectionInput struct { _ struct{} `type:"structure"` + + // The id of the outbound connection that you want to permanently delete. + // + // CrossClusterSearchConnectionId is a required field + CrossClusterSearchConnectionId *string `location:"uri" locationName:"ConnectionId" type:"string" required:"true"` } // String returns the string representation -func (s DeleteElasticsearchServiceRoleInput) String() string { +func (s DeleteOutboundCrossClusterSearchConnectionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteElasticsearchServiceRoleInput) GoString() string { +func (s DeleteOutboundCrossClusterSearchConnectionInput) GoString() string { return s.String() } -type DeleteElasticsearchServiceRoleOutput struct { +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteOutboundCrossClusterSearchConnectionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteOutboundCrossClusterSearchConnectionInput"} + if s.CrossClusterSearchConnectionId == nil { + invalidParams.Add(request.NewErrParamRequired("CrossClusterSearchConnectionId")) + } + if s.CrossClusterSearchConnectionId != nil && len(*s.CrossClusterSearchConnectionId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CrossClusterSearchConnectionId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCrossClusterSearchConnectionId sets the CrossClusterSearchConnectionId field's value. +func (s *DeleteOutboundCrossClusterSearchConnectionInput) SetCrossClusterSearchConnectionId(v string) *DeleteOutboundCrossClusterSearchConnectionInput { + s.CrossClusterSearchConnectionId = &v + return s +} + +// The result of a DeleteOutboundCrossClusterSearchConnection operation. Contains +// details of deleted outbound connection. +type DeleteOutboundCrossClusterSearchConnectionOutput struct { _ struct{} `type:"structure"` + + // Specifies the OutboundCrossClusterSearchConnection of deleted outbound connection. + CrossClusterSearchConnection *OutboundCrossClusterSearchConnection `type:"structure"` } // String returns the string representation -func (s DeleteElasticsearchServiceRoleOutput) String() string { +func (s DeleteOutboundCrossClusterSearchConnectionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteElasticsearchServiceRoleOutput) GoString() string { +func (s DeleteOutboundCrossClusterSearchConnectionOutput) GoString() string { return s.String() } +// SetCrossClusterSearchConnection sets the CrossClusterSearchConnection field's value. +func (s *DeleteOutboundCrossClusterSearchConnectionOutput) SetCrossClusterSearchConnection(v *OutboundCrossClusterSearchConnection) *DeleteOutboundCrossClusterSearchConnectionOutput { + s.CrossClusterSearchConnection = v + return s +} + // Container for request parameters to DeletePackage operation. type DeletePackageInput struct { _ struct{} `type:"structure"` @@ -4755,60 +5803,277 @@ func (s DescribeElasticsearchDomainsOutput) GoString() string { return s.String() } -// SetDomainStatusList sets the DomainStatusList field's value. -func (s *DescribeElasticsearchDomainsOutput) SetDomainStatusList(v []*ElasticsearchDomainStatus) *DescribeElasticsearchDomainsOutput { - s.DomainStatusList = v +// SetDomainStatusList sets the DomainStatusList field's value. +func (s *DescribeElasticsearchDomainsOutput) SetDomainStatusList(v []*ElasticsearchDomainStatus) *DescribeElasticsearchDomainsOutput { + s.DomainStatusList = v + return s +} + +// Container for the parameters to DescribeElasticsearchInstanceTypeLimits operation. +type DescribeElasticsearchInstanceTypeLimitsInput struct { + _ struct{} `type:"structure"` + + // DomainName represents the name of the Domain that we are trying to modify. + // This should be present only if we are querying for Elasticsearch Limits for + // existing domain. + DomainName *string `location:"querystring" locationName:"domainName" min:"3" type:"string"` + + // Version of Elasticsearch for which Limits are needed. + // + // ElasticsearchVersion is a required field + ElasticsearchVersion *string `location:"uri" locationName:"ElasticsearchVersion" type:"string" required:"true"` + + // The instance type for an Elasticsearch cluster for which Elasticsearch Limits + // are needed. + // + // InstanceType is a required field + InstanceType *string `location:"uri" locationName:"InstanceType" type:"string" required:"true" enum:"ESPartitionInstanceType"` +} + +// String returns the string representation +func (s DescribeElasticsearchInstanceTypeLimitsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeElasticsearchInstanceTypeLimitsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeElasticsearchInstanceTypeLimitsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeElasticsearchInstanceTypeLimitsInput"} + if s.DomainName != nil && len(*s.DomainName) < 3 { + invalidParams.Add(request.NewErrParamMinLen("DomainName", 3)) + } + if s.ElasticsearchVersion == nil { + invalidParams.Add(request.NewErrParamRequired("ElasticsearchVersion")) + } + if s.ElasticsearchVersion != nil && len(*s.ElasticsearchVersion) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ElasticsearchVersion", 1)) + } + if s.InstanceType == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceType")) + } + if s.InstanceType != nil && len(*s.InstanceType) < 1 { + invalidParams.Add(request.NewErrParamMinLen("InstanceType", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomainName sets the DomainName field's value. +func (s *DescribeElasticsearchInstanceTypeLimitsInput) SetDomainName(v string) *DescribeElasticsearchInstanceTypeLimitsInput { + s.DomainName = &v + return s +} + +// SetElasticsearchVersion sets the ElasticsearchVersion field's value. +func (s *DescribeElasticsearchInstanceTypeLimitsInput) SetElasticsearchVersion(v string) *DescribeElasticsearchInstanceTypeLimitsInput { + s.ElasticsearchVersion = &v + return s +} + +// SetInstanceType sets the InstanceType field's value. +func (s *DescribeElasticsearchInstanceTypeLimitsInput) SetInstanceType(v string) *DescribeElasticsearchInstanceTypeLimitsInput { + s.InstanceType = &v + return s +} + +// Container for the parameters received from DescribeElasticsearchInstanceTypeLimits +// operation. +type DescribeElasticsearchInstanceTypeLimitsOutput struct { + _ struct{} `type:"structure"` + + // Map of Role of the Instance and Limits that are applicable. Role performed + // by given Instance in Elasticsearch can be one of the following: + // * data: If the given InstanceType is used as data node + // + // * master: If the given InstanceType is used as master node + // + // * ultra_warm: If the given InstanceType is used as warm node + LimitsByRole map[string]*Limits `type:"map"` +} + +// String returns the string representation +func (s DescribeElasticsearchInstanceTypeLimitsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeElasticsearchInstanceTypeLimitsOutput) GoString() string { + return s.String() +} + +// SetLimitsByRole sets the LimitsByRole field's value. +func (s *DescribeElasticsearchInstanceTypeLimitsOutput) SetLimitsByRole(v map[string]*Limits) *DescribeElasticsearchInstanceTypeLimitsOutput { + s.LimitsByRole = v + return s +} + +// Container for the parameters to the DescribeInboundCrossClusterSearchConnections +// operation. +type DescribeInboundCrossClusterSearchConnectionsInput struct { + _ struct{} `type:"structure"` + + // A list of filters used to match properties for inbound cross-cluster search + // connection. Available Filter names for this operation are: + // * cross-cluster-search-connection-id + // + // * source-domain-info.domain-name + // + // * source-domain-info.owner-id + // + // * source-domain-info.region + // + // * destination-domain-info.domain-name + Filters []*Filter `type:"list"` + + // Set this value to limit the number of results returned. If not specified, + // defaults to 100. + MaxResults *int64 `type:"integer"` + + // NextToken is sent in case the earlier API call results contain the NextToken. + // It is used for pagination. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeInboundCrossClusterSearchConnectionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeInboundCrossClusterSearchConnectionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeInboundCrossClusterSearchConnectionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeInboundCrossClusterSearchConnectionsInput"} + if s.Filters != nil { + for i, v := range s.Filters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetFilters sets the Filters field's value. +func (s *DescribeInboundCrossClusterSearchConnectionsInput) SetFilters(v []*Filter) *DescribeInboundCrossClusterSearchConnectionsInput { + s.Filters = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeInboundCrossClusterSearchConnectionsInput) SetMaxResults(v int64) *DescribeInboundCrossClusterSearchConnectionsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeInboundCrossClusterSearchConnectionsInput) SetNextToken(v string) *DescribeInboundCrossClusterSearchConnectionsInput { + s.NextToken = &v + return s +} + +// The result of a DescribeInboundCrossClusterSearchConnections request. Contains +// the list of connections matching the filter criteria. +type DescribeInboundCrossClusterSearchConnectionsOutput struct { + _ struct{} `type:"structure"` + + // Consists of list of InboundCrossClusterSearchConnection matching the specified + // filter criteria. + CrossClusterSearchConnections []*InboundCrossClusterSearchConnection `type:"list"` + + // If more results are available and NextToken is present, make the next request + // to the same API with the received NextToken to paginate the remaining results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeInboundCrossClusterSearchConnectionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeInboundCrossClusterSearchConnectionsOutput) GoString() string { + return s.String() +} + +// SetCrossClusterSearchConnections sets the CrossClusterSearchConnections field's value. +func (s *DescribeInboundCrossClusterSearchConnectionsOutput) SetCrossClusterSearchConnections(v []*InboundCrossClusterSearchConnection) *DescribeInboundCrossClusterSearchConnectionsOutput { + s.CrossClusterSearchConnections = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeInboundCrossClusterSearchConnectionsOutput) SetNextToken(v string) *DescribeInboundCrossClusterSearchConnectionsOutput { + s.NextToken = &v return s } -// Container for the parameters to DescribeElasticsearchInstanceTypeLimits operation. -type DescribeElasticsearchInstanceTypeLimitsInput struct { +// Container for the parameters to the DescribeOutboundCrossClusterSearchConnections +// operation. +type DescribeOutboundCrossClusterSearchConnectionsInput struct { _ struct{} `type:"structure"` - // DomainName represents the name of the Domain that we are trying to modify. - // This should be present only if we are querying for Elasticsearch Limits for - // existing domain. - DomainName *string `location:"querystring" locationName:"domainName" min:"3" type:"string"` - - // Version of Elasticsearch for which Limits are needed. + // A list of filters used to match properties for outbound cross-cluster search + // connection. Available Filter names for this operation are: + // * cross-cluster-search-connection-id // - // ElasticsearchVersion is a required field - ElasticsearchVersion *string `location:"uri" locationName:"ElasticsearchVersion" type:"string" required:"true"` - - // The instance type for an Elasticsearch cluster for which Elasticsearch Limits - // are needed. + // * destination-domain-info.domain-name // - // InstanceType is a required field - InstanceType *string `location:"uri" locationName:"InstanceType" type:"string" required:"true" enum:"ESPartitionInstanceType"` + // * destination-domain-info.owner-id + // + // * destination-domain-info.region + // + // * source-domain-info.domain-name + Filters []*Filter `type:"list"` + + // Set this value to limit the number of results returned. If not specified, + // defaults to 100. + MaxResults *int64 `type:"integer"` + + // NextToken is sent in case the earlier API call results contain the NextToken. + // It is used for pagination. + NextToken *string `type:"string"` } // String returns the string representation -func (s DescribeElasticsearchInstanceTypeLimitsInput) String() string { +func (s DescribeOutboundCrossClusterSearchConnectionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeElasticsearchInstanceTypeLimitsInput) GoString() string { +func (s DescribeOutboundCrossClusterSearchConnectionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeElasticsearchInstanceTypeLimitsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeElasticsearchInstanceTypeLimitsInput"} - if s.DomainName != nil && len(*s.DomainName) < 3 { - invalidParams.Add(request.NewErrParamMinLen("DomainName", 3)) - } - if s.ElasticsearchVersion == nil { - invalidParams.Add(request.NewErrParamRequired("ElasticsearchVersion")) - } - if s.ElasticsearchVersion != nil && len(*s.ElasticsearchVersion) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ElasticsearchVersion", 1)) - } - if s.InstanceType == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceType")) - } - if s.InstanceType != nil && len(*s.InstanceType) < 1 { - invalidParams.Add(request.NewErrParamMinLen("InstanceType", 1)) +func (s *DescribeOutboundCrossClusterSearchConnectionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeOutboundCrossClusterSearchConnectionsInput"} + if s.Filters != nil { + for i, v := range s.Filters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -4817,52 +6082,57 @@ func (s *DescribeElasticsearchInstanceTypeLimitsInput) Validate() error { return nil } -// SetDomainName sets the DomainName field's value. -func (s *DescribeElasticsearchInstanceTypeLimitsInput) SetDomainName(v string) *DescribeElasticsearchInstanceTypeLimitsInput { - s.DomainName = &v +// SetFilters sets the Filters field's value. +func (s *DescribeOutboundCrossClusterSearchConnectionsInput) SetFilters(v []*Filter) *DescribeOutboundCrossClusterSearchConnectionsInput { + s.Filters = v return s } -// SetElasticsearchVersion sets the ElasticsearchVersion field's value. -func (s *DescribeElasticsearchInstanceTypeLimitsInput) SetElasticsearchVersion(v string) *DescribeElasticsearchInstanceTypeLimitsInput { - s.ElasticsearchVersion = &v +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeOutboundCrossClusterSearchConnectionsInput) SetMaxResults(v int64) *DescribeOutboundCrossClusterSearchConnectionsInput { + s.MaxResults = &v return s } -// SetInstanceType sets the InstanceType field's value. -func (s *DescribeElasticsearchInstanceTypeLimitsInput) SetInstanceType(v string) *DescribeElasticsearchInstanceTypeLimitsInput { - s.InstanceType = &v +// SetNextToken sets the NextToken field's value. +func (s *DescribeOutboundCrossClusterSearchConnectionsInput) SetNextToken(v string) *DescribeOutboundCrossClusterSearchConnectionsInput { + s.NextToken = &v return s } -// Container for the parameters received from DescribeElasticsearchInstanceTypeLimits -// operation. -type DescribeElasticsearchInstanceTypeLimitsOutput struct { +// The result of a DescribeOutboundCrossClusterSearchConnections request. Contains +// the list of connections matching the filter criteria. +type DescribeOutboundCrossClusterSearchConnectionsOutput struct { _ struct{} `type:"structure"` - // Map of Role of the Instance and Limits that are applicable. Role performed - // by given Instance in Elasticsearch can be one of the following: - // * data: If the given InstanceType is used as data node - // - // * master: If the given InstanceType is used as master node - // - // * ultra_warm: If the given InstanceType is used as warm node - LimitsByRole map[string]*Limits `type:"map"` + // Consists of list of OutboundCrossClusterSearchConnection matching the specified + // filter criteria. + CrossClusterSearchConnections []*OutboundCrossClusterSearchConnection `type:"list"` + + // If more results are available and NextToken is present, make the next request + // to the same API with the received NextToken to paginate the remaining results. + NextToken *string `type:"string"` } // String returns the string representation -func (s DescribeElasticsearchInstanceTypeLimitsOutput) String() string { +func (s DescribeOutboundCrossClusterSearchConnectionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeElasticsearchInstanceTypeLimitsOutput) GoString() string { +func (s DescribeOutboundCrossClusterSearchConnectionsOutput) GoString() string { return s.String() } -// SetLimitsByRole sets the LimitsByRole field's value. -func (s *DescribeElasticsearchInstanceTypeLimitsOutput) SetLimitsByRole(v map[string]*Limits) *DescribeElasticsearchInstanceTypeLimitsOutput { - s.LimitsByRole = v +// SetCrossClusterSearchConnections sets the CrossClusterSearchConnections field's value. +func (s *DescribeOutboundCrossClusterSearchConnectionsOutput) SetCrossClusterSearchConnections(v []*OutboundCrossClusterSearchConnection) *DescribeOutboundCrossClusterSearchConnectionsOutput { + s.CrossClusterSearchConnections = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeOutboundCrossClusterSearchConnectionsOutput) SetNextToken(v string) *DescribeOutboundCrossClusterSearchConnectionsOutput { + s.NextToken = &v return s } @@ -5372,6 +6642,69 @@ func (s *DomainInfo) SetDomainName(v string) *DomainInfo { return s } +type DomainInformation struct { + _ struct{} `type:"structure"` + + // The name of an Elasticsearch domain. Domain names are unique across the domains + // owned by an account within an AWS region. Domain names start with a letter + // or number and can contain the following characters: a-z (lowercase), 0-9, + // and - (hyphen). + // + // DomainName is a required field + DomainName *string `min:"3" type:"string" required:"true"` + + OwnerId *string `min:"12" type:"string"` + + Region *string `type:"string"` +} + +// String returns the string representation +func (s DomainInformation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DomainInformation) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DomainInformation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DomainInformation"} + if s.DomainName == nil { + invalidParams.Add(request.NewErrParamRequired("DomainName")) + } + if s.DomainName != nil && len(*s.DomainName) < 3 { + invalidParams.Add(request.NewErrParamMinLen("DomainName", 3)) + } + if s.OwnerId != nil && len(*s.OwnerId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("OwnerId", 12)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomainName sets the DomainName field's value. +func (s *DomainInformation) SetDomainName(v string) *DomainInformation { + s.DomainName = &v + return s +} + +// SetOwnerId sets the OwnerId field's value. +func (s *DomainInformation) SetOwnerId(v string) *DomainInformation { + s.OwnerId = &v + return s +} + +// SetRegion sets the Region field's value. +func (s *DomainInformation) SetRegion(v string) *DomainInformation { + s.Region = &v + return s +} + // Information on a package that is associated with a domain. type DomainPackageDetails struct { _ struct{} `type:"structure"` @@ -6237,6 +7570,58 @@ func (s *ErrorDetails) SetErrorType(v string) *ErrorDetails { return s } +// A filter used to limit results when describing inbound or outbound cross-cluster +// search connections. Multiple values can be specified per filter. A cross-cluster +// search connection must match at least one of the specified values for it +// to be returned from an operation. +type Filter struct { + _ struct{} `type:"structure"` + + // Specifies the name of the filter. + Name *string `min:"1" type:"string"` + + // Contains one or more values for the filter. + Values []*string `min:"1" type:"list"` +} + +// String returns the string representation +func (s Filter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Filter) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Filter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Filter"} + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.Values != nil && len(s.Values) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Values", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *Filter) SetName(v string) *Filter { + s.Name = &v + return s +} + +// SetValues sets the Values field's value. +func (s *Filter) SetValues(v []*string) *Filter { + s.Values = v + return s +} + // Container for request parameters to GetCompatibleElasticsearchVersions operation. type GetCompatibleElasticsearchVersionsInput struct { _ struct{} `type:"structure"` @@ -6436,71 +7821,170 @@ func (s *GetUpgradeStatusInput) Validate() error { invalidParams.Add(request.NewErrParamMinLen("DomainName", 3)) } - if invalidParams.Len() > 0 { - return invalidParams - } - return nil + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomainName sets the DomainName field's value. +func (s *GetUpgradeStatusInput) SetDomainName(v string) *GetUpgradeStatusInput { + s.DomainName = &v + return s +} + +// Container for response returned by GetUpgradeStatus operation. +type GetUpgradeStatusOutput struct { + _ struct{} `type:"structure"` + + // One of 4 statuses that a step can go through returned as part of the GetUpgradeStatusResponse + // object. The status can take one of the following values: + // * In Progress + // + // * Succeeded + // + // * Succeeded with Issues + // + // * Failed + StepStatus *string `type:"string" enum:"UpgradeStatus"` + + // A string that describes the update briefly + UpgradeName *string `type:"string"` + + // Represents one of 3 steps that an Upgrade or Upgrade Eligibility Check does + // through: + // * PreUpgradeCheck + // + // * Snapshot + // + // * Upgrade + UpgradeStep *string `type:"string" enum:"UpgradeStep"` +} + +// String returns the string representation +func (s GetUpgradeStatusOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetUpgradeStatusOutput) GoString() string { + return s.String() +} + +// SetStepStatus sets the StepStatus field's value. +func (s *GetUpgradeStatusOutput) SetStepStatus(v string) *GetUpgradeStatusOutput { + s.StepStatus = &v + return s +} + +// SetUpgradeName sets the UpgradeName field's value. +func (s *GetUpgradeStatusOutput) SetUpgradeName(v string) *GetUpgradeStatusOutput { + s.UpgradeName = &v + return s +} + +// SetUpgradeStep sets the UpgradeStep field's value. +func (s *GetUpgradeStatusOutput) SetUpgradeStep(v string) *GetUpgradeStatusOutput { + s.UpgradeStep = &v + return s +} + +// Specifies details of an inbound connection. +type InboundCrossClusterSearchConnection struct { + _ struct{} `type:"structure"` + + // Specifies the InboundCrossClusterSearchConnectionStatus for the outbound + // connection. + ConnectionStatus *InboundCrossClusterSearchConnectionStatus `type:"structure"` + + // Specifies the connection id for the inbound cross-cluster search connection. + CrossClusterSearchConnectionId *string `type:"string"` + + // Specifies the DomainInformation for the destination Elasticsearch domain. + DestinationDomainInfo *DomainInformation `type:"structure"` + + // Specifies the DomainInformation for the source Elasticsearch domain. + SourceDomainInfo *DomainInformation `type:"structure"` +} + +// String returns the string representation +func (s InboundCrossClusterSearchConnection) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InboundCrossClusterSearchConnection) GoString() string { + return s.String() +} + +// SetConnectionStatus sets the ConnectionStatus field's value. +func (s *InboundCrossClusterSearchConnection) SetConnectionStatus(v *InboundCrossClusterSearchConnectionStatus) *InboundCrossClusterSearchConnection { + s.ConnectionStatus = v + return s +} + +// SetCrossClusterSearchConnectionId sets the CrossClusterSearchConnectionId field's value. +func (s *InboundCrossClusterSearchConnection) SetCrossClusterSearchConnectionId(v string) *InboundCrossClusterSearchConnection { + s.CrossClusterSearchConnectionId = &v + return s } -// SetDomainName sets the DomainName field's value. -func (s *GetUpgradeStatusInput) SetDomainName(v string) *GetUpgradeStatusInput { - s.DomainName = &v +// SetDestinationDomainInfo sets the DestinationDomainInfo field's value. +func (s *InboundCrossClusterSearchConnection) SetDestinationDomainInfo(v *DomainInformation) *InboundCrossClusterSearchConnection { + s.DestinationDomainInfo = v return s } -// Container for response returned by GetUpgradeStatus operation. -type GetUpgradeStatusOutput struct { +// SetSourceDomainInfo sets the SourceDomainInfo field's value. +func (s *InboundCrossClusterSearchConnection) SetSourceDomainInfo(v *DomainInformation) *InboundCrossClusterSearchConnection { + s.SourceDomainInfo = v + return s +} + +// Specifies the coonection status of an inbound cross-cluster search connection. +type InboundCrossClusterSearchConnectionStatus struct { _ struct{} `type:"structure"` - // One of 4 statuses that a step can go through returned as part of the GetUpgradeStatusResponse - // object. The status can take one of the following values: - // * In Progress + // Specifies verbose information for the inbound connection status. + Message *string `type:"string"` + + // The state code for inbound connection. This can be one of the following: // - // * Succeeded + // * PENDING_ACCEPTANCE: Inbound connection is not yet accepted by destination + // domain owner. // - // * Succeeded with Issues + // * APPROVED: Inbound connection is pending acceptance by destination domain + // owner. // - // * Failed - StepStatus *string `type:"string" enum:"UpgradeStatus"` - - // A string that describes the update briefly - UpgradeName *string `type:"string"` - - // Represents one of 3 steps that an Upgrade or Upgrade Eligibility Check does - // through: - // * PreUpgradeCheck + // * REJECTING: Inbound connection rejection is in process. // - // * Snapshot + // * REJECTED: Inbound connection is rejected. // - // * Upgrade - UpgradeStep *string `type:"string" enum:"UpgradeStep"` + // * DELETING: Inbound connection deletion is in progress. + // + // * DELETED: Inbound connection is deleted and cannot be used further. + StatusCode *string `type:"string" enum:"InboundCrossClusterSearchConnectionStatusCode"` } // String returns the string representation -func (s GetUpgradeStatusOutput) String() string { +func (s InboundCrossClusterSearchConnectionStatus) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetUpgradeStatusOutput) GoString() string { +func (s InboundCrossClusterSearchConnectionStatus) GoString() string { return s.String() } -// SetStepStatus sets the StepStatus field's value. -func (s *GetUpgradeStatusOutput) SetStepStatus(v string) *GetUpgradeStatusOutput { - s.StepStatus = &v - return s -} - -// SetUpgradeName sets the UpgradeName field's value. -func (s *GetUpgradeStatusOutput) SetUpgradeName(v string) *GetUpgradeStatusOutput { - s.UpgradeName = &v +// SetMessage sets the Message field's value. +func (s *InboundCrossClusterSearchConnectionStatus) SetMessage(v string) *InboundCrossClusterSearchConnectionStatus { + s.Message = &v return s } -// SetUpgradeStep sets the UpgradeStep field's value. -func (s *GetUpgradeStatusOutput) SetUpgradeStep(v string) *GetUpgradeStatusOutput { - s.UpgradeStep = &v +// SetStatusCode sets the StatusCode field's value. +func (s *InboundCrossClusterSearchConnectionStatus) SetStatusCode(v string) *InboundCrossClusterSearchConnectionStatus { + s.StatusCode = &v return s } @@ -6622,6 +8106,63 @@ func (s *InternalException) RequestID() string { return s.RespMetadata.RequestID } +// The request processing has failed because of invalid pagination token provided +// by customer. Returns an HTTP status code of 400. +type InvalidPaginationTokenException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s InvalidPaginationTokenException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InvalidPaginationTokenException) GoString() string { + return s.String() +} + +func newErrorInvalidPaginationTokenException(v protocol.ResponseMetadata) error { + return &InvalidPaginationTokenException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidPaginationTokenException) Code() string { + return "InvalidPaginationTokenException" +} + +// Message returns the exception's message. +func (s *InvalidPaginationTokenException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidPaginationTokenException) OrigErr() error { + return nil +} + +func (s *InvalidPaginationTokenException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidPaginationTokenException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidPaginationTokenException) RequestID() string { + return s.RespMetadata.RequestID +} + // An exception for trying to create or access sub-resource that is either invalid // or not supported. Gives http status code of 409. type InvalidTypeException struct { @@ -7529,6 +9070,118 @@ func (s *OptionStatus) SetUpdateVersion(v int64) *OptionStatus { return s } +// Specifies details of an outbound connection. +type OutboundCrossClusterSearchConnection struct { + _ struct{} `type:"structure"` + + // Specifies the connection alias for the outbound cross-cluster search connection. + ConnectionAlias *string `type:"string"` + + // Specifies the OutboundCrossClusterSearchConnectionStatus for the outbound + // connection. + ConnectionStatus *OutboundCrossClusterSearchConnectionStatus `type:"structure"` + + // Specifies the connection id for the outbound cross-cluster search connection. + CrossClusterSearchConnectionId *string `type:"string"` + + // Specifies the DomainInformation for the destination Elasticsearch domain. + DestinationDomainInfo *DomainInformation `type:"structure"` + + // Specifies the DomainInformation for the source Elasticsearch domain. + SourceDomainInfo *DomainInformation `type:"structure"` +} + +// String returns the string representation +func (s OutboundCrossClusterSearchConnection) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OutboundCrossClusterSearchConnection) GoString() string { + return s.String() +} + +// SetConnectionAlias sets the ConnectionAlias field's value. +func (s *OutboundCrossClusterSearchConnection) SetConnectionAlias(v string) *OutboundCrossClusterSearchConnection { + s.ConnectionAlias = &v + return s +} + +// SetConnectionStatus sets the ConnectionStatus field's value. +func (s *OutboundCrossClusterSearchConnection) SetConnectionStatus(v *OutboundCrossClusterSearchConnectionStatus) *OutboundCrossClusterSearchConnection { + s.ConnectionStatus = v + return s +} + +// SetCrossClusterSearchConnectionId sets the CrossClusterSearchConnectionId field's value. +func (s *OutboundCrossClusterSearchConnection) SetCrossClusterSearchConnectionId(v string) *OutboundCrossClusterSearchConnection { + s.CrossClusterSearchConnectionId = &v + return s +} + +// SetDestinationDomainInfo sets the DestinationDomainInfo field's value. +func (s *OutboundCrossClusterSearchConnection) SetDestinationDomainInfo(v *DomainInformation) *OutboundCrossClusterSearchConnection { + s.DestinationDomainInfo = v + return s +} + +// SetSourceDomainInfo sets the SourceDomainInfo field's value. +func (s *OutboundCrossClusterSearchConnection) SetSourceDomainInfo(v *DomainInformation) *OutboundCrossClusterSearchConnection { + s.SourceDomainInfo = v + return s +} + +// Specifies the connection status of an outbound cross-cluster search connection. +type OutboundCrossClusterSearchConnectionStatus struct { + _ struct{} `type:"structure"` + + // Specifies verbose information for the outbound connection status. + Message *string `type:"string"` + + // The state code for outbound connection. This can be one of the following: + // + // * VALIDATING: The outbound connection request is being validated. + // + // * VALIDATION_FAILED: Validation failed for the connection request. + // + // * PENDING_ACCEPTANCE: Outbound connection request is validated and is + // not yet accepted by destination domain owner. + // + // * PROVISIONING: Outbound connection request is in process. + // + // * ACTIVE: Outbound connection is active and ready to use. + // + // * REJECTED: Outbound connection request is rejected by destination domain + // owner. + // + // * DELETING: Outbound connection deletion is in progress. + // + // * DELETED: Outbound connection is deleted and cannot be used further. + StatusCode *string `type:"string" enum:"OutboundCrossClusterSearchConnectionStatusCode"` +} + +// String returns the string representation +func (s OutboundCrossClusterSearchConnectionStatus) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OutboundCrossClusterSearchConnectionStatus) GoString() string { + return s.String() +} + +// SetMessage sets the Message field's value. +func (s *OutboundCrossClusterSearchConnectionStatus) SetMessage(v string) *OutboundCrossClusterSearchConnectionStatus { + s.Message = &v + return s +} + +// SetStatusCode sets the StatusCode field's value. +func (s *OutboundCrossClusterSearchConnectionStatus) SetStatusCode(v string) *OutboundCrossClusterSearchConnectionStatus { + s.StatusCode = &v + return s +} + // Basic information about a package. type PackageDetails struct { _ struct{} `type:"structure"` @@ -7789,6 +9442,74 @@ func (s *RecurringCharge) SetRecurringChargeFrequency(v string) *RecurringCharge return s } +// Container for the parameters to the RejectInboundCrossClusterSearchConnection +// operation. +type RejectInboundCrossClusterSearchConnectionInput struct { + _ struct{} `type:"structure"` + + // The id of the inbound connection that you want to reject. + // + // CrossClusterSearchConnectionId is a required field + CrossClusterSearchConnectionId *string `location:"uri" locationName:"ConnectionId" type:"string" required:"true"` +} + +// String returns the string representation +func (s RejectInboundCrossClusterSearchConnectionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RejectInboundCrossClusterSearchConnectionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RejectInboundCrossClusterSearchConnectionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RejectInboundCrossClusterSearchConnectionInput"} + if s.CrossClusterSearchConnectionId == nil { + invalidParams.Add(request.NewErrParamRequired("CrossClusterSearchConnectionId")) + } + if s.CrossClusterSearchConnectionId != nil && len(*s.CrossClusterSearchConnectionId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CrossClusterSearchConnectionId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCrossClusterSearchConnectionId sets the CrossClusterSearchConnectionId field's value. +func (s *RejectInboundCrossClusterSearchConnectionInput) SetCrossClusterSearchConnectionId(v string) *RejectInboundCrossClusterSearchConnectionInput { + s.CrossClusterSearchConnectionId = &v + return s +} + +// The result of a RejectInboundCrossClusterSearchConnection operation. Contains +// details of rejected inbound connection. +type RejectInboundCrossClusterSearchConnectionOutput struct { + _ struct{} `type:"structure"` + + // Specifies the InboundCrossClusterSearchConnection of rejected inbound connection. + CrossClusterSearchConnection *InboundCrossClusterSearchConnection `type:"structure"` +} + +// String returns the string representation +func (s RejectInboundCrossClusterSearchConnectionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RejectInboundCrossClusterSearchConnectionOutput) GoString() string { + return s.String() +} + +// SetCrossClusterSearchConnection sets the CrossClusterSearchConnection field's value. +func (s *RejectInboundCrossClusterSearchConnectionOutput) SetCrossClusterSearchConnection(v *InboundCrossClusterSearchConnection) *RejectInboundCrossClusterSearchConnectionOutput { + s.CrossClusterSearchConnection = v + return s +} + // Container for the parameters to the RemoveTags operation. Specify the ARN // for the Elasticsearch domain from which you want to remove the specified // TagKey. @@ -9222,6 +10943,17 @@ const ( DeploymentStatusEligible = "ELIGIBLE" ) +// DeploymentStatus_Values returns all elements of the DeploymentStatus enum +func DeploymentStatus_Values() []string { + return []string{ + DeploymentStatusPendingUpdate, + DeploymentStatusInProgress, + DeploymentStatusCompleted, + DeploymentStatusNotEligible, + DeploymentStatusEligible, + } +} + const ( // DescribePackagesFilterNamePackageId is a DescribePackagesFilterName enum value DescribePackagesFilterNamePackageId = "PackageID" @@ -9233,6 +10965,15 @@ const ( DescribePackagesFilterNamePackageStatus = "PackageStatus" ) +// DescribePackagesFilterName_Values returns all elements of the DescribePackagesFilterName enum +func DescribePackagesFilterName_Values() []string { + return []string{ + DescribePackagesFilterNamePackageId, + DescribePackagesFilterNamePackageName, + DescribePackagesFilterNamePackageStatus, + } +} + const ( // DomainPackageStatusAssociating is a DomainPackageStatus enum value DomainPackageStatusAssociating = "ASSOCIATING" @@ -9250,6 +10991,17 @@ const ( DomainPackageStatusDissociationFailed = "DISSOCIATION_FAILED" ) +// DomainPackageStatus_Values returns all elements of the DomainPackageStatus enum +func DomainPackageStatus_Values() []string { + return []string{ + DomainPackageStatusAssociating, + DomainPackageStatusAssociationFailed, + DomainPackageStatusActive, + DomainPackageStatusDissociating, + DomainPackageStatusDissociationFailed, + } +} + const ( // ESPartitionInstanceTypeM3MediumElasticsearch is a ESPartitionInstanceType enum value ESPartitionInstanceTypeM3MediumElasticsearch = "m3.medium.elasticsearch" @@ -9426,6 +11178,70 @@ const ( ESPartitionInstanceTypeI316xlargeElasticsearch = "i3.16xlarge.elasticsearch" ) +// ESPartitionInstanceType_Values returns all elements of the ESPartitionInstanceType enum +func ESPartitionInstanceType_Values() []string { + return []string{ + ESPartitionInstanceTypeM3MediumElasticsearch, + ESPartitionInstanceTypeM3LargeElasticsearch, + ESPartitionInstanceTypeM3XlargeElasticsearch, + ESPartitionInstanceTypeM32xlargeElasticsearch, + ESPartitionInstanceTypeM4LargeElasticsearch, + ESPartitionInstanceTypeM4XlargeElasticsearch, + ESPartitionInstanceTypeM42xlargeElasticsearch, + ESPartitionInstanceTypeM44xlargeElasticsearch, + ESPartitionInstanceTypeM410xlargeElasticsearch, + ESPartitionInstanceTypeM5LargeElasticsearch, + ESPartitionInstanceTypeM5XlargeElasticsearch, + ESPartitionInstanceTypeM52xlargeElasticsearch, + ESPartitionInstanceTypeM54xlargeElasticsearch, + ESPartitionInstanceTypeM512xlargeElasticsearch, + ESPartitionInstanceTypeR5LargeElasticsearch, + ESPartitionInstanceTypeR5XlargeElasticsearch, + ESPartitionInstanceTypeR52xlargeElasticsearch, + ESPartitionInstanceTypeR54xlargeElasticsearch, + ESPartitionInstanceTypeR512xlargeElasticsearch, + ESPartitionInstanceTypeC5LargeElasticsearch, + ESPartitionInstanceTypeC5XlargeElasticsearch, + ESPartitionInstanceTypeC52xlargeElasticsearch, + ESPartitionInstanceTypeC54xlargeElasticsearch, + ESPartitionInstanceTypeC59xlargeElasticsearch, + ESPartitionInstanceTypeC518xlargeElasticsearch, + ESPartitionInstanceTypeUltrawarm1MediumElasticsearch, + ESPartitionInstanceTypeUltrawarm1LargeElasticsearch, + ESPartitionInstanceTypeT2MicroElasticsearch, + ESPartitionInstanceTypeT2SmallElasticsearch, + ESPartitionInstanceTypeT2MediumElasticsearch, + ESPartitionInstanceTypeR3LargeElasticsearch, + ESPartitionInstanceTypeR3XlargeElasticsearch, + ESPartitionInstanceTypeR32xlargeElasticsearch, + ESPartitionInstanceTypeR34xlargeElasticsearch, + ESPartitionInstanceTypeR38xlargeElasticsearch, + ESPartitionInstanceTypeI2XlargeElasticsearch, + ESPartitionInstanceTypeI22xlargeElasticsearch, + ESPartitionInstanceTypeD2XlargeElasticsearch, + ESPartitionInstanceTypeD22xlargeElasticsearch, + ESPartitionInstanceTypeD24xlargeElasticsearch, + ESPartitionInstanceTypeD28xlargeElasticsearch, + ESPartitionInstanceTypeC4LargeElasticsearch, + ESPartitionInstanceTypeC4XlargeElasticsearch, + ESPartitionInstanceTypeC42xlargeElasticsearch, + ESPartitionInstanceTypeC44xlargeElasticsearch, + ESPartitionInstanceTypeC48xlargeElasticsearch, + ESPartitionInstanceTypeR4LargeElasticsearch, + ESPartitionInstanceTypeR4XlargeElasticsearch, + ESPartitionInstanceTypeR42xlargeElasticsearch, + ESPartitionInstanceTypeR44xlargeElasticsearch, + ESPartitionInstanceTypeR48xlargeElasticsearch, + ESPartitionInstanceTypeR416xlargeElasticsearch, + ESPartitionInstanceTypeI3LargeElasticsearch, + ESPartitionInstanceTypeI3XlargeElasticsearch, + ESPartitionInstanceTypeI32xlargeElasticsearch, + ESPartitionInstanceTypeI34xlargeElasticsearch, + ESPartitionInstanceTypeI38xlargeElasticsearch, + ESPartitionInstanceTypeI316xlargeElasticsearch, + } +} + const ( // ESWarmPartitionInstanceTypeUltrawarm1MediumElasticsearch is a ESWarmPartitionInstanceType enum value ESWarmPartitionInstanceTypeUltrawarm1MediumElasticsearch = "ultrawarm1.medium.elasticsearch" @@ -9434,6 +11250,46 @@ const ( ESWarmPartitionInstanceTypeUltrawarm1LargeElasticsearch = "ultrawarm1.large.elasticsearch" ) +// ESWarmPartitionInstanceType_Values returns all elements of the ESWarmPartitionInstanceType enum +func ESWarmPartitionInstanceType_Values() []string { + return []string{ + ESWarmPartitionInstanceTypeUltrawarm1MediumElasticsearch, + ESWarmPartitionInstanceTypeUltrawarm1LargeElasticsearch, + } +} + +const ( + // InboundCrossClusterSearchConnectionStatusCodePendingAcceptance is a InboundCrossClusterSearchConnectionStatusCode enum value + InboundCrossClusterSearchConnectionStatusCodePendingAcceptance = "PENDING_ACCEPTANCE" + + // InboundCrossClusterSearchConnectionStatusCodeApproved is a InboundCrossClusterSearchConnectionStatusCode enum value + InboundCrossClusterSearchConnectionStatusCodeApproved = "APPROVED" + + // InboundCrossClusterSearchConnectionStatusCodeRejecting is a InboundCrossClusterSearchConnectionStatusCode enum value + InboundCrossClusterSearchConnectionStatusCodeRejecting = "REJECTING" + + // InboundCrossClusterSearchConnectionStatusCodeRejected is a InboundCrossClusterSearchConnectionStatusCode enum value + InboundCrossClusterSearchConnectionStatusCodeRejected = "REJECTED" + + // InboundCrossClusterSearchConnectionStatusCodeDeleting is a InboundCrossClusterSearchConnectionStatusCode enum value + InboundCrossClusterSearchConnectionStatusCodeDeleting = "DELETING" + + // InboundCrossClusterSearchConnectionStatusCodeDeleted is a InboundCrossClusterSearchConnectionStatusCode enum value + InboundCrossClusterSearchConnectionStatusCodeDeleted = "DELETED" +) + +// InboundCrossClusterSearchConnectionStatusCode_Values returns all elements of the InboundCrossClusterSearchConnectionStatusCode enum +func InboundCrossClusterSearchConnectionStatusCode_Values() []string { + return []string{ + InboundCrossClusterSearchConnectionStatusCodePendingAcceptance, + InboundCrossClusterSearchConnectionStatusCodeApproved, + InboundCrossClusterSearchConnectionStatusCodeRejecting, + InboundCrossClusterSearchConnectionStatusCodeRejected, + InboundCrossClusterSearchConnectionStatusCodeDeleting, + InboundCrossClusterSearchConnectionStatusCodeDeleted, + } +} + // Type of Log File, it can be one of the following: // * INDEX_SLOW_LOGS: Index slow logs contain insert requests that took more // time than configured index query log threshold to execute. @@ -9455,6 +11311,15 @@ const ( LogTypeEsApplicationLogs = "ES_APPLICATION_LOGS" ) +// LogType_Values returns all elements of the LogType enum +func LogType_Values() []string { + return []string{ + LogTypeIndexSlowLogs, + LogTypeSearchSlowLogs, + LogTypeEsApplicationLogs, + } +} + // The state of a requested change. One of the following: // // * Processing: The request change is still in-process. @@ -9472,6 +11337,55 @@ const ( OptionStateActive = "Active" ) +// OptionState_Values returns all elements of the OptionState enum +func OptionState_Values() []string { + return []string{ + OptionStateRequiresIndexDocuments, + OptionStateProcessing, + OptionStateActive, + } +} + +const ( + // OutboundCrossClusterSearchConnectionStatusCodePendingAcceptance is a OutboundCrossClusterSearchConnectionStatusCode enum value + OutboundCrossClusterSearchConnectionStatusCodePendingAcceptance = "PENDING_ACCEPTANCE" + + // OutboundCrossClusterSearchConnectionStatusCodeValidating is a OutboundCrossClusterSearchConnectionStatusCode enum value + OutboundCrossClusterSearchConnectionStatusCodeValidating = "VALIDATING" + + // OutboundCrossClusterSearchConnectionStatusCodeValidationFailed is a OutboundCrossClusterSearchConnectionStatusCode enum value + OutboundCrossClusterSearchConnectionStatusCodeValidationFailed = "VALIDATION_FAILED" + + // OutboundCrossClusterSearchConnectionStatusCodeProvisioning is a OutboundCrossClusterSearchConnectionStatusCode enum value + OutboundCrossClusterSearchConnectionStatusCodeProvisioning = "PROVISIONING" + + // OutboundCrossClusterSearchConnectionStatusCodeActive is a OutboundCrossClusterSearchConnectionStatusCode enum value + OutboundCrossClusterSearchConnectionStatusCodeActive = "ACTIVE" + + // OutboundCrossClusterSearchConnectionStatusCodeRejected is a OutboundCrossClusterSearchConnectionStatusCode enum value + OutboundCrossClusterSearchConnectionStatusCodeRejected = "REJECTED" + + // OutboundCrossClusterSearchConnectionStatusCodeDeleting is a OutboundCrossClusterSearchConnectionStatusCode enum value + OutboundCrossClusterSearchConnectionStatusCodeDeleting = "DELETING" + + // OutboundCrossClusterSearchConnectionStatusCodeDeleted is a OutboundCrossClusterSearchConnectionStatusCode enum value + OutboundCrossClusterSearchConnectionStatusCodeDeleted = "DELETED" +) + +// OutboundCrossClusterSearchConnectionStatusCode_Values returns all elements of the OutboundCrossClusterSearchConnectionStatusCode enum +func OutboundCrossClusterSearchConnectionStatusCode_Values() []string { + return []string{ + OutboundCrossClusterSearchConnectionStatusCodePendingAcceptance, + OutboundCrossClusterSearchConnectionStatusCodeValidating, + OutboundCrossClusterSearchConnectionStatusCodeValidationFailed, + OutboundCrossClusterSearchConnectionStatusCodeProvisioning, + OutboundCrossClusterSearchConnectionStatusCodeActive, + OutboundCrossClusterSearchConnectionStatusCodeRejected, + OutboundCrossClusterSearchConnectionStatusCodeDeleting, + OutboundCrossClusterSearchConnectionStatusCodeDeleted, + } +} + const ( // PackageStatusCopying is a PackageStatus enum value PackageStatusCopying = "COPYING" @@ -9498,11 +11412,32 @@ const ( PackageStatusDeleteFailed = "DELETE_FAILED" ) +// PackageStatus_Values returns all elements of the PackageStatus enum +func PackageStatus_Values() []string { + return []string{ + PackageStatusCopying, + PackageStatusCopyFailed, + PackageStatusValidating, + PackageStatusValidationFailed, + PackageStatusAvailable, + PackageStatusDeleting, + PackageStatusDeleted, + PackageStatusDeleteFailed, + } +} + const ( // PackageTypeTxtDictionary is a PackageType enum value PackageTypeTxtDictionary = "TXT-DICTIONARY" ) +// PackageType_Values returns all elements of the PackageType enum +func PackageType_Values() []string { + return []string{ + PackageTypeTxtDictionary, + } +} + const ( // ReservedElasticsearchInstancePaymentOptionAllUpfront is a ReservedElasticsearchInstancePaymentOption enum value ReservedElasticsearchInstancePaymentOptionAllUpfront = "ALL_UPFRONT" @@ -9514,6 +11449,15 @@ const ( ReservedElasticsearchInstancePaymentOptionNoUpfront = "NO_UPFRONT" ) +// ReservedElasticsearchInstancePaymentOption_Values returns all elements of the ReservedElasticsearchInstancePaymentOption enum +func ReservedElasticsearchInstancePaymentOption_Values() []string { + return []string{ + ReservedElasticsearchInstancePaymentOptionAllUpfront, + ReservedElasticsearchInstancePaymentOptionPartialUpfront, + ReservedElasticsearchInstancePaymentOptionNoUpfront, + } +} + const ( // TLSSecurityPolicyPolicyMinTls10201907 is a TLSSecurityPolicy enum value TLSSecurityPolicyPolicyMinTls10201907 = "Policy-Min-TLS-1-0-2019-07" @@ -9522,6 +11466,14 @@ const ( TLSSecurityPolicyPolicyMinTls12201907 = "Policy-Min-TLS-1-2-2019-07" ) +// TLSSecurityPolicy_Values returns all elements of the TLSSecurityPolicy enum +func TLSSecurityPolicy_Values() []string { + return []string{ + TLSSecurityPolicyPolicyMinTls10201907, + TLSSecurityPolicyPolicyMinTls12201907, + } +} + const ( // UpgradeStatusInProgress is a UpgradeStatus enum value UpgradeStatusInProgress = "IN_PROGRESS" @@ -9536,6 +11488,16 @@ const ( UpgradeStatusFailed = "FAILED" ) +// UpgradeStatus_Values returns all elements of the UpgradeStatus enum +func UpgradeStatus_Values() []string { + return []string{ + UpgradeStatusInProgress, + UpgradeStatusSucceeded, + UpgradeStatusSucceededWithIssues, + UpgradeStatusFailed, + } +} + const ( // UpgradeStepPreUpgradeCheck is a UpgradeStep enum value UpgradeStepPreUpgradeCheck = "PRE_UPGRADE_CHECK" @@ -9547,6 +11509,15 @@ const ( UpgradeStepUpgrade = "UPGRADE" ) +// UpgradeStep_Values returns all elements of the UpgradeStep enum +func UpgradeStep_Values() []string { + return []string{ + UpgradeStepPreUpgradeCheck, + UpgradeStepSnapshot, + UpgradeStepUpgrade, + } +} + // The type of EBS volume, standard, gp2, or io1. See Configuring EBS-based // Storage (http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html#es-createdomain-configure-ebs)for // more information. @@ -9560,3 +11531,12 @@ const ( // VolumeTypeIo1 is a VolumeType enum value VolumeTypeIo1 = "io1" ) + +// VolumeType_Values returns all elements of the VolumeType enum +func VolumeType_Values() []string { + return []string{ + VolumeTypeStandard, + VolumeTypeGp2, + VolumeTypeIo1, + } +} 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 d0ca4fe8804..46f3ae0daa4 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 @@ -43,6 +43,13 @@ const ( // of 500. ErrCodeInternalException = "InternalException" + // ErrCodeInvalidPaginationTokenException for service response error code + // "InvalidPaginationTokenException". + // + // The request processing has failed because of invalid pagination token provided + // by customer. Returns an HTTP status code of 400. + ErrCodeInvalidPaginationTokenException = "InvalidPaginationTokenException" + // ErrCodeInvalidTypeException for service response error code // "InvalidTypeException". // @@ -80,14 +87,15 @@ const ( ) var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ - "AccessDeniedException": newErrorAccessDeniedException, - "BaseException": newErrorBaseException, - "ConflictException": newErrorConflictException, - "DisabledOperationException": newErrorDisabledOperationException, - "InternalException": newErrorInternalException, - "InvalidTypeException": newErrorInvalidTypeException, - "LimitExceededException": newErrorLimitExceededException, - "ResourceAlreadyExistsException": newErrorResourceAlreadyExistsException, - "ResourceNotFoundException": newErrorResourceNotFoundException, - "ValidationException": newErrorValidationException, + "AccessDeniedException": newErrorAccessDeniedException, + "BaseException": newErrorBaseException, + "ConflictException": newErrorConflictException, + "DisabledOperationException": newErrorDisabledOperationException, + "InternalException": newErrorInternalException, + "InvalidPaginationTokenException": newErrorInvalidPaginationTokenException, + "InvalidTypeException": newErrorInvalidTypeException, + "LimitExceededException": newErrorLimitExceededException, + "ResourceAlreadyExistsException": newErrorResourceAlreadyExistsException, + "ResourceNotFoundException": newErrorResourceNotFoundException, + "ValidationException": newErrorValidationException, } 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 c1903d5141d..de56e7e95a8 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 @@ -325,6 +325,9 @@ func (c *ELBV2) CreateListenerRequest(input *CreateListenerInput) (req *request. // across all listeners. If a target group is used by multiple actions for a // load balancer, it is counted as only one use. // +// * ErrCodeALPNPolicyNotSupportedException "ALPNPolicyNotFound" +// The specified ALPN policy is not supported. +// // See also, 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) @@ -2378,6 +2381,9 @@ func (c *ELBV2) ModifyListenerRequest(input *ModifyListenerInput) (req *request. // across all listeners. If a target group is used by multiple actions for a // load balancer, it is counted as only one use. // +// * ErrCodeALPNPolicyNotSupportedException "ALPNPolicyNotFound" +// The specified ALPN policy is not supported. +// // See also, 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) @@ -4143,6 +4149,23 @@ func (s *Cipher) SetPriority(v int64) *Cipher { type CreateListenerInput struct { _ struct{} `type:"structure"` + // [TLS listeners] The name of the Application-Layer Protocol Negotiation (ALPN) + // policy. You can specify one policy name. The following are the possible values: + // + // * HTTP1Only + // + // * HTTP2Only + // + // * HTTP2Optional + // + // * HTTP2Preferred + // + // * None + // + // For more information, see ALPN Policies (https://docs.aws.amazon.com/elasticloadbalancing/latest/network/create-tls-listener.html#alpn-policies) + // in the Network Load Balancers Guide. + AlpnPolicy []*string `type:"list"` + // [HTTPS and TLS listeners] The default certificate for the listener. You must // provide exactly one certificate. Set CertificateArn to the certificate ARN // but do not set IsDefault. @@ -4262,6 +4285,12 @@ func (s *CreateListenerInput) Validate() error { return nil } +// SetAlpnPolicy sets the AlpnPolicy field's value. +func (s *CreateListenerInput) SetAlpnPolicy(v []*string) *CreateListenerInput { + s.AlpnPolicy = v + return s +} + // SetCertificates sets the Certificates field's value. func (s *CreateListenerInput) SetCertificates(v []*Certificate) *CreateListenerInput { s.Certificates = v @@ -6360,6 +6389,10 @@ func (s *Limit) SetName(v string) *Limit { type Listener struct { _ struct{} `type:"structure"` + // [TLS listener] The name of the Application-Layer Protocol Negotiation (ALPN) + // policy. + AlpnPolicy []*string `type:"list"` + // [HTTPS or TLS listener] The default certificate for the listener. Certificates []*Certificate `type:"list"` @@ -6393,6 +6426,12 @@ func (s Listener) GoString() string { return s.String() } +// SetAlpnPolicy sets the AlpnPolicy field's value. +func (s *Listener) SetAlpnPolicy(v []*string) *Listener { + s.AlpnPolicy = v + return s +} + // SetCertificates sets the Certificates field's value. func (s *Listener) SetCertificates(v []*Certificate) *Listener { s.Certificates = v @@ -6762,6 +6801,23 @@ func (s *Matcher) SetHttpCode(v string) *Matcher { type ModifyListenerInput struct { _ struct{} `type:"structure"` + // [TLS listeners] The name of the Application-Layer Protocol Negotiation (ALPN) + // policy. You can specify one policy name. The following are the possible values: + // + // * HTTP1Only + // + // * HTTP2Only + // + // * HTTP2Optional + // + // * HTTP2Preferred + // + // * None + // + // For more information, see ALPN Policies (https://docs.aws.amazon.com/elasticloadbalancing/latest/network/create-tls-listener.html#alpn-policies) + // in the Network Load Balancers Guide. + AlpnPolicy []*string `type:"list"` + // [HTTPS and TLS listeners] The default certificate for the listener. You must // provide exactly one certificate. Set CertificateArn to the certificate ARN // but do not set IsDefault. @@ -6866,6 +6922,12 @@ func (s *ModifyListenerInput) Validate() error { return nil } +// SetAlpnPolicy sets the AlpnPolicy field's value. +func (s *ModifyListenerInput) SetAlpnPolicy(v []*string) *ModifyListenerInput { + s.AlpnPolicy = v + return s +} + // SetCertificates sets the Certificates field's value. func (s *ModifyListenerInput) SetCertificates(v []*Certificate) *ModifyListenerInput { s.Certificates = v @@ -8820,16 +8882,16 @@ type TargetGroupAttribute struct { // lb_cookie for Application Load Balancers or source_ip for Network Load // Balancers. // - // The following attributes are supported by Application Load Balancers if the - // target is not a Lambda function: + // The following attributes are supported only if the load balancer is an Application + // Load Balancer and the target is an instance or an IP address: // // * load_balancing.algorithm.type - The load balancing algorithm determines // how the load balancer selects targets when routing requests. The value // is round_robin or least_outstanding_requests. The default is round_robin. // // * slow_start.duration_seconds - The time period, in seconds, during which - // a newly registered target receives a linearly increasing share of the - // traffic to the target group. After this time period ends, the target receives + // a newly registered target receives an increasing share of the traffic + // to the target group. After this time period ends, the target receives // its full share of traffic. The range is 30-900 seconds (15 minutes). Slow // start mode is disabled by default. // @@ -8839,14 +8901,15 @@ type TargetGroupAttribute struct { // considered stale. The range is 1 second to 1 week (604800 seconds). The // default value is 1 day (86400 seconds). // - // The following attribute is supported only if the target is a Lambda function. + // The following attribute is supported only if the load balancer is an Application + // Load Balancer and the target is a Lambda function: // // * lambda.multi_value_headers.enabled - Indicates whether the request and - // response headers exchanged between the load balancer and the Lambda function - // include arrays of values or strings. The value is true or false. The default - // is false. If the value is false and the request contains a duplicate header - // field name or query parameter key, the load balancer uses the last value - // sent by the client. + // response headers that are exchanged between the load balancer and the + // Lambda function include arrays of values or strings. The value is true + // or false. The default is false. If the value is false and the request + // contains a duplicate header field name or query parameter key, the load + // balancer uses the last value sent by the client. // // The following attribute is supported only by Network Load Balancers: // @@ -9105,6 +9168,17 @@ const ( ActionTypeEnumFixedResponse = "fixed-response" ) +// ActionTypeEnum_Values returns all elements of the ActionTypeEnum enum +func ActionTypeEnum_Values() []string { + return []string{ + ActionTypeEnumForward, + ActionTypeEnumAuthenticateOidc, + ActionTypeEnumAuthenticateCognito, + ActionTypeEnumRedirect, + ActionTypeEnumFixedResponse, + } +} + const ( // AuthenticateCognitoActionConditionalBehaviorEnumDeny is a AuthenticateCognitoActionConditionalBehaviorEnum enum value AuthenticateCognitoActionConditionalBehaviorEnumDeny = "deny" @@ -9116,6 +9190,15 @@ const ( AuthenticateCognitoActionConditionalBehaviorEnumAuthenticate = "authenticate" ) +// AuthenticateCognitoActionConditionalBehaviorEnum_Values returns all elements of the AuthenticateCognitoActionConditionalBehaviorEnum enum +func AuthenticateCognitoActionConditionalBehaviorEnum_Values() []string { + return []string{ + AuthenticateCognitoActionConditionalBehaviorEnumDeny, + AuthenticateCognitoActionConditionalBehaviorEnumAllow, + AuthenticateCognitoActionConditionalBehaviorEnumAuthenticate, + } +} + const ( // AuthenticateOidcActionConditionalBehaviorEnumDeny is a AuthenticateOidcActionConditionalBehaviorEnum enum value AuthenticateOidcActionConditionalBehaviorEnumDeny = "deny" @@ -9127,6 +9210,15 @@ const ( AuthenticateOidcActionConditionalBehaviorEnumAuthenticate = "authenticate" ) +// AuthenticateOidcActionConditionalBehaviorEnum_Values returns all elements of the AuthenticateOidcActionConditionalBehaviorEnum enum +func AuthenticateOidcActionConditionalBehaviorEnum_Values() []string { + return []string{ + AuthenticateOidcActionConditionalBehaviorEnumDeny, + AuthenticateOidcActionConditionalBehaviorEnumAllow, + AuthenticateOidcActionConditionalBehaviorEnumAuthenticate, + } +} + const ( // IpAddressTypeIpv4 is a IpAddressType enum value IpAddressTypeIpv4 = "ipv4" @@ -9135,6 +9227,14 @@ const ( IpAddressTypeDualstack = "dualstack" ) +// IpAddressType_Values returns all elements of the IpAddressType enum +func IpAddressType_Values() []string { + return []string{ + IpAddressTypeIpv4, + IpAddressTypeDualstack, + } +} + const ( // LoadBalancerSchemeEnumInternetFacing is a LoadBalancerSchemeEnum enum value LoadBalancerSchemeEnumInternetFacing = "internet-facing" @@ -9143,6 +9243,14 @@ const ( LoadBalancerSchemeEnumInternal = "internal" ) +// LoadBalancerSchemeEnum_Values returns all elements of the LoadBalancerSchemeEnum enum +func LoadBalancerSchemeEnum_Values() []string { + return []string{ + LoadBalancerSchemeEnumInternetFacing, + LoadBalancerSchemeEnumInternal, + } +} + const ( // LoadBalancerStateEnumActive is a LoadBalancerStateEnum enum value LoadBalancerStateEnumActive = "active" @@ -9157,6 +9265,16 @@ const ( LoadBalancerStateEnumFailed = "failed" ) +// LoadBalancerStateEnum_Values returns all elements of the LoadBalancerStateEnum enum +func LoadBalancerStateEnum_Values() []string { + return []string{ + LoadBalancerStateEnumActive, + LoadBalancerStateEnumProvisioning, + LoadBalancerStateEnumActiveImpaired, + LoadBalancerStateEnumFailed, + } +} + const ( // LoadBalancerTypeEnumApplication is a LoadBalancerTypeEnum enum value LoadBalancerTypeEnumApplication = "application" @@ -9165,6 +9283,14 @@ const ( LoadBalancerTypeEnumNetwork = "network" ) +// LoadBalancerTypeEnum_Values returns all elements of the LoadBalancerTypeEnum enum +func LoadBalancerTypeEnum_Values() []string { + return []string{ + LoadBalancerTypeEnumApplication, + LoadBalancerTypeEnumNetwork, + } +} + const ( // ProtocolEnumHttp is a ProtocolEnum enum value ProtocolEnumHttp = "HTTP" @@ -9185,6 +9311,18 @@ const ( ProtocolEnumTcpUdp = "TCP_UDP" ) +// ProtocolEnum_Values returns all elements of the ProtocolEnum enum +func ProtocolEnum_Values() []string { + return []string{ + ProtocolEnumHttp, + ProtocolEnumHttps, + ProtocolEnumTcp, + ProtocolEnumTls, + ProtocolEnumUdp, + ProtocolEnumTcpUdp, + } +} + const ( // RedirectActionStatusCodeEnumHttp301 is a RedirectActionStatusCodeEnum enum value RedirectActionStatusCodeEnumHttp301 = "HTTP_301" @@ -9193,6 +9331,14 @@ const ( RedirectActionStatusCodeEnumHttp302 = "HTTP_302" ) +// RedirectActionStatusCodeEnum_Values returns all elements of the RedirectActionStatusCodeEnum enum +func RedirectActionStatusCodeEnum_Values() []string { + return []string{ + RedirectActionStatusCodeEnumHttp301, + RedirectActionStatusCodeEnumHttp302, + } +} + const ( // TargetHealthReasonEnumElbRegistrationInProgress is a TargetHealthReasonEnum enum value TargetHealthReasonEnumElbRegistrationInProgress = "Elb.RegistrationInProgress" @@ -9231,6 +9377,24 @@ const ( TargetHealthReasonEnumElbInternalError = "Elb.InternalError" ) +// TargetHealthReasonEnum_Values returns all elements of the TargetHealthReasonEnum enum +func TargetHealthReasonEnum_Values() []string { + return []string{ + TargetHealthReasonEnumElbRegistrationInProgress, + TargetHealthReasonEnumElbInitialHealthChecking, + TargetHealthReasonEnumTargetResponseCodeMismatch, + TargetHealthReasonEnumTargetTimeout, + TargetHealthReasonEnumTargetFailedHealthChecks, + TargetHealthReasonEnumTargetNotRegistered, + TargetHealthReasonEnumTargetNotInUse, + TargetHealthReasonEnumTargetDeregistrationInProgress, + TargetHealthReasonEnumTargetInvalidState, + TargetHealthReasonEnumTargetIpUnusable, + TargetHealthReasonEnumTargetHealthCheckDisabled, + TargetHealthReasonEnumElbInternalError, + } +} + const ( // TargetHealthStateEnumInitial is a TargetHealthStateEnum enum value TargetHealthStateEnumInitial = "initial" @@ -9251,6 +9415,18 @@ const ( TargetHealthStateEnumUnavailable = "unavailable" ) +// TargetHealthStateEnum_Values returns all elements of the TargetHealthStateEnum enum +func TargetHealthStateEnum_Values() []string { + return []string{ + TargetHealthStateEnumInitial, + TargetHealthStateEnumHealthy, + TargetHealthStateEnumUnhealthy, + TargetHealthStateEnumUnused, + TargetHealthStateEnumDraining, + TargetHealthStateEnumUnavailable, + } +} + const ( // TargetTypeEnumInstance is a TargetTypeEnum enum value TargetTypeEnumInstance = "instance" @@ -9261,3 +9437,12 @@ const ( // TargetTypeEnumLambda is a TargetTypeEnum enum value TargetTypeEnumLambda = "lambda" ) + +// TargetTypeEnum_Values returns all elements of the TargetTypeEnum enum +func TargetTypeEnum_Values() []string { + return []string{ + TargetTypeEnumInstance, + TargetTypeEnumIp, + TargetTypeEnumLambda, + } +} 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 fa10830ff9c..3a9ab86f1b9 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 @@ -4,6 +4,12 @@ package elbv2 const ( + // ErrCodeALPNPolicyNotSupportedException for service response error code + // "ALPNPolicyNotFound". + // + // The specified ALPN policy is not supported. + ErrCodeALPNPolicyNotSupportedException = "ALPNPolicyNotFound" + // ErrCodeAllocationIdNotFoundException for service response error code // "AllocationIdNotFound". // 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 3633bd5f97e..88123dfabb0 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 @@ -4373,6 +4373,11 @@ type Cluster struct { // in the EMR Management Guide. KerberosAttributes *KerberosAttributes `type:"structure"` + // The AWS KMS customer master key (CMK) used for encrypting log files. This + // attribute is only available with EMR version 5.30.0 and later, excluding + // EMR 6.0.0. + LogEncryptionKmsKeyId *string `type:"string"` + // The path to the Amazon S3 location where logs for this cluster are stored. LogUri *string `type:"string"` @@ -4537,6 +4542,12 @@ func (s *Cluster) SetKerberosAttributes(v *KerberosAttributes) *Cluster { return s } +// SetLogEncryptionKmsKeyId sets the LogEncryptionKmsKeyId field's value. +func (s *Cluster) SetLogEncryptionKmsKeyId(v string) *Cluster { + s.LogEncryptionKmsKeyId = &v + return s +} + // SetLogUri sets the LogUri field's value. func (s *Cluster) SetLogUri(v string) *Cluster { s.LogUri = &v @@ -4889,11 +4900,18 @@ type ComputeLimits struct { // MaximumCapacityUnits is a required field MaximumCapacityUnits *int64 `type:"integer" required:"true"` - // The upper boundary of on-demand EC2 units. It is measured through VCPU cores + // The upper boundary of EC2 units for core node type in a cluster. It is measured + // through VCPU cores or instances for instance groups and measured through + // units for instance fleets. The core units are not allowed to scale beyond + // this boundary. The parameter is used to split capacity allocation between + // core and task nodes. + MaximumCoreCapacityUnits *int64 `type:"integer"` + + // The upper boundary of On-Demand EC2 units. It is measured through VCPU cores // or instances for instance groups and measured through units for instance - // fleets. The on-demand units are not allowed to scale beyond this boundary. - // The limit only applies to the core and task nodes. The master node cannot - // be scaled after initial configuration. + // fleets. The On-Demand units are not allowed to scale beyond this boundary. + // The parameter is used to split capacity allocation between On-Demand and + // Spot instances. MaximumOnDemandCapacityUnits *int64 `type:"integer"` // The lower boundary of EC2 units. It is measured through VCPU cores or instances @@ -4946,6 +4964,12 @@ func (s *ComputeLimits) SetMaximumCapacityUnits(v int64) *ComputeLimits { return s } +// SetMaximumCoreCapacityUnits sets the MaximumCoreCapacityUnits field's value. +func (s *ComputeLimits) SetMaximumCoreCapacityUnits(v int64) *ComputeLimits { + s.MaximumCoreCapacityUnits = &v + return s +} + // SetMaximumOnDemandCapacityUnits sets the MaximumOnDemandCapacityUnits field's value. func (s *ComputeLimits) SetMaximumOnDemandCapacityUnits(v int64) *ComputeLimits { s.MaximumOnDemandCapacityUnits = &v @@ -6538,18 +6562,25 @@ func (s *InstanceFleetModifyConfig) SetTargetSpotCapacity(v int64) *InstanceFlee } // The launch specification for Spot instances in the fleet, which determines -// the defined duration and provisioning timeout behavior. +// the defined duration, provisioning timeout behavior, and allocation strategy. // // The instance fleet configuration is available only in Amazon EMR versions -// 4.8.0 and later, excluding 5.0.x versions. +// 4.8.0 and later, excluding 5.0.x versions. On-Demand and Spot instance allocation +// strategies are available in Amazon EMR version 5.12.1 and later. type InstanceFleetProvisioningSpecifications struct { _ struct{} `type:"structure"` - // The launch specification for Spot instances in the fleet, which determines - // the defined duration and provisioning timeout behavior. + // The launch specification for On-Demand instances in the instance fleet, which + // determines the allocation strategy. // - // SpotSpecification is a required field - SpotSpecification *SpotProvisioningSpecification `type:"structure" required:"true"` + // The instance fleet configuration is available only in Amazon EMR versions + // 4.8.0 and later, excluding 5.0.x versions. On-Demand instances allocation + // strategy is available in Amazon EMR version 5.12.1 and later. + OnDemandSpecification *OnDemandProvisioningSpecification `type:"structure"` + + // The launch specification for Spot instances in the fleet, which determines + // the defined duration, provisioning timeout behavior, and allocation strategy. + SpotSpecification *SpotProvisioningSpecification `type:"structure"` } // String returns the string representation @@ -6565,8 +6596,10 @@ func (s InstanceFleetProvisioningSpecifications) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *InstanceFleetProvisioningSpecifications) Validate() error { invalidParams := request.ErrInvalidParams{Context: "InstanceFleetProvisioningSpecifications"} - if s.SpotSpecification == nil { - invalidParams.Add(request.NewErrParamRequired("SpotSpecification")) + if s.OnDemandSpecification != nil { + if err := s.OnDemandSpecification.Validate(); err != nil { + invalidParams.AddNested("OnDemandSpecification", err.(request.ErrInvalidParams)) + } } if s.SpotSpecification != nil { if err := s.SpotSpecification.Validate(); err != nil { @@ -6580,6 +6613,12 @@ func (s *InstanceFleetProvisioningSpecifications) Validate() error { return nil } +// SetOnDemandSpecification sets the OnDemandSpecification field's value. +func (s *InstanceFleetProvisioningSpecifications) SetOnDemandSpecification(v *OnDemandProvisioningSpecification) *InstanceFleetProvisioningSpecifications { + s.OnDemandSpecification = v + return s +} + // SetSpotSpecification sets the SpotSpecification field's value. func (s *InstanceFleetProvisioningSpecifications) SetSpotSpecification(v *SpotProvisioningSpecification) *InstanceFleetProvisioningSpecifications { s.SpotSpecification = v @@ -7985,6 +8024,11 @@ type JobFlowDetail struct { // of the job flow assume this role. JobFlowRole *string `type:"string"` + // The AWS KMS customer master key (CMK) used for encrypting log files. This + // attribute is only available with EMR version 5.30.0 and later, excluding + // EMR 6.0.0. + LogEncryptionKmsKeyId *string `type:"string"` + // The location in Amazon S3 where log files for the job are stored. LogUri *string `type:"string"` @@ -8082,6 +8126,12 @@ func (s *JobFlowDetail) SetJobFlowRole(v string) *JobFlowDetail { return s } +// SetLogEncryptionKmsKeyId sets the LogEncryptionKmsKeyId field's value. +func (s *JobFlowDetail) SetLogEncryptionKmsKeyId(v string) *JobFlowDetail { + s.LogEncryptionKmsKeyId = &v + return s +} + // SetLogUri sets the LogUri field's value. func (s *JobFlowDetail) SetLogUri(v string) *JobFlowDetail { s.LogUri = &v @@ -9610,6 +9660,52 @@ func (s ModifyInstanceGroupsOutput) GoString() string { return s.String() } +// The launch specification for On-Demand instances in the instance fleet, which +// determines the allocation strategy. +// +// The instance fleet configuration is available only in Amazon EMR versions +// 4.8.0 and later, excluding 5.0.x versions. On-Demand instances allocation +// strategy is available in Amazon EMR version 5.12.1 and later. +type OnDemandProvisioningSpecification struct { + _ struct{} `type:"structure"` + + // Specifies the strategy to use in launching On-Demand instance fleets. Currently, + // the only option is lowest-price (the default), which launches the lowest + // price first. + // + // AllocationStrategy is a required field + AllocationStrategy *string `type:"string" required:"true" enum:"OnDemandProvisioningAllocationStrategy"` +} + +// String returns the string representation +func (s OnDemandProvisioningSpecification) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OnDemandProvisioningSpecification) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *OnDemandProvisioningSpecification) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OnDemandProvisioningSpecification"} + if s.AllocationStrategy == nil { + invalidParams.Add(request.NewErrParamRequired("AllocationStrategy")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAllocationStrategy sets the AllocationStrategy field's value. +func (s *OnDemandProvisioningSpecification) SetAllocationStrategy(v string) *OnDemandProvisioningSpecification { + s.AllocationStrategy = &v + return s +} + // The Amazon EC2 Availability Zone configuration of the cluster (job flow). type PlacementType struct { _ struct{} `type:"structure"` @@ -10220,6 +10316,11 @@ type RunJobFlowInput struct { // in the EMR Management Guide. KerberosAttributes *KerberosAttributes `type:"structure"` + // The AWS KMS customer master key (CMK) used for encrypting log files. If a + // value is not provided, the logs will remain encrypted by AES-256. This attribute + // is only available with EMR version 5.30.0 and later, excluding EMR 6.0.0. + LogEncryptionKmsKeyId *string `type:"string"` + // The location in Amazon S3 to write the log files of the job flow. If a value // is not provided, logs are not created. LogUri *string `type:"string"` @@ -10456,6 +10557,12 @@ func (s *RunJobFlowInput) SetKerberosAttributes(v *KerberosAttributes) *RunJobFl return s } +// SetLogEncryptionKmsKeyId sets the LogEncryptionKmsKeyId field's value. +func (s *RunJobFlowInput) SetLogEncryptionKmsKeyId(v string) *RunJobFlowInput { + s.LogEncryptionKmsKeyId = &v + return s +} + // SetLogUri sets the LogUri field's value. func (s *RunJobFlowInput) SetLogUri(v string) *RunJobFlowInput { s.LogUri = &v @@ -11160,13 +11267,21 @@ func (s *SimpleScalingPolicyConfiguration) SetScalingAdjustment(v int64) *Simple } // The launch specification for Spot instances in the instance fleet, which -// determines the defined duration and provisioning timeout behavior. +// determines the defined duration, provisioning timeout behavior, and allocation +// strategy. // // The instance fleet configuration is available only in Amazon EMR versions -// 4.8.0 and later, excluding 5.0.x versions. +// 4.8.0 and later, excluding 5.0.x versions. Spot instance allocation strategy +// is available in Amazon EMR version 5.12.1 and later. type SpotProvisioningSpecification struct { _ struct{} `type:"structure"` + // Specifies the strategy to use in launching Spot instance fleets. Currently, + // the only option is capacity-optimized (the default), which launches instances + // from Spot instance pools with optimal capacity for the number of instances + // that are launching. + AllocationStrategy *string `type:"string" enum:"SpotProvisioningAllocationStrategy"` + // The defined duration for Spot instances (also known as Spot blocks) in minutes. // When specified, the Spot instance does not terminate before the defined duration // expires, and defined duration pricing for Spot instances applies. Valid values @@ -11222,6 +11337,12 @@ func (s *SpotProvisioningSpecification) Validate() error { return nil } +// SetAllocationStrategy sets the AllocationStrategy field's value. +func (s *SpotProvisioningSpecification) SetAllocationStrategy(v string) *SpotProvisioningSpecification { + s.AllocationStrategy = &v + return s +} + // SetBlockDurationMinutes sets the BlockDurationMinutes field's value. func (s *SpotProvisioningSpecification) SetBlockDurationMinutes(v int64) *SpotProvisioningSpecification { s.BlockDurationMinutes = &v @@ -11866,6 +11987,16 @@ const ( ActionOnFailureContinue = "CONTINUE" ) +// ActionOnFailure_Values returns all elements of the ActionOnFailure enum +func ActionOnFailure_Values() []string { + return []string{ + ActionOnFailureTerminateJobFlow, + ActionOnFailureTerminateCluster, + ActionOnFailureCancelAndWait, + ActionOnFailureContinue, + } +} + const ( // AdjustmentTypeChangeInCapacity is a AdjustmentType enum value AdjustmentTypeChangeInCapacity = "CHANGE_IN_CAPACITY" @@ -11877,6 +12008,15 @@ const ( AdjustmentTypeExactCapacity = "EXACT_CAPACITY" ) +// AdjustmentType_Values returns all elements of the AdjustmentType enum +func AdjustmentType_Values() []string { + return []string{ + AdjustmentTypeChangeInCapacity, + AdjustmentTypePercentChangeInCapacity, + AdjustmentTypeExactCapacity, + } +} + const ( // AutoScalingPolicyStatePending is a AutoScalingPolicyState enum value AutoScalingPolicyStatePending = "PENDING" @@ -11897,6 +12037,18 @@ const ( AutoScalingPolicyStateFailed = "FAILED" ) +// AutoScalingPolicyState_Values returns all elements of the AutoScalingPolicyState enum +func AutoScalingPolicyState_Values() []string { + return []string{ + AutoScalingPolicyStatePending, + AutoScalingPolicyStateAttaching, + AutoScalingPolicyStateAttached, + AutoScalingPolicyStateDetaching, + AutoScalingPolicyStateDetached, + AutoScalingPolicyStateFailed, + } +} + const ( // AutoScalingPolicyStateChangeReasonCodeUserRequest is a AutoScalingPolicyStateChangeReasonCode enum value AutoScalingPolicyStateChangeReasonCodeUserRequest = "USER_REQUEST" @@ -11908,6 +12060,15 @@ const ( AutoScalingPolicyStateChangeReasonCodeCleanupFailure = "CLEANUP_FAILURE" ) +// AutoScalingPolicyStateChangeReasonCode_Values returns all elements of the AutoScalingPolicyStateChangeReasonCode enum +func AutoScalingPolicyStateChangeReasonCode_Values() []string { + return []string{ + AutoScalingPolicyStateChangeReasonCodeUserRequest, + AutoScalingPolicyStateChangeReasonCodeProvisionFailure, + AutoScalingPolicyStateChangeReasonCodeCleanupFailure, + } +} + const ( // CancelStepsRequestStatusSubmitted is a CancelStepsRequestStatus enum value CancelStepsRequestStatusSubmitted = "SUBMITTED" @@ -11916,6 +12077,14 @@ const ( CancelStepsRequestStatusFailed = "FAILED" ) +// CancelStepsRequestStatus_Values returns all elements of the CancelStepsRequestStatus enum +func CancelStepsRequestStatus_Values() []string { + return []string{ + CancelStepsRequestStatusSubmitted, + CancelStepsRequestStatusFailed, + } +} + const ( // ClusterStateStarting is a ClusterState enum value ClusterStateStarting = "STARTING" @@ -11939,6 +12108,19 @@ const ( ClusterStateTerminatedWithErrors = "TERMINATED_WITH_ERRORS" ) +// ClusterState_Values returns all elements of the ClusterState enum +func ClusterState_Values() []string { + return []string{ + ClusterStateStarting, + ClusterStateBootstrapping, + ClusterStateRunning, + ClusterStateWaiting, + ClusterStateTerminating, + ClusterStateTerminated, + ClusterStateTerminatedWithErrors, + } +} + const ( // ClusterStateChangeReasonCodeInternalError is a ClusterStateChangeReasonCode enum value ClusterStateChangeReasonCodeInternalError = "INTERNAL_ERROR" @@ -11965,6 +12147,20 @@ const ( ClusterStateChangeReasonCodeAllStepsCompleted = "ALL_STEPS_COMPLETED" ) +// ClusterStateChangeReasonCode_Values returns all elements of the ClusterStateChangeReasonCode enum +func ClusterStateChangeReasonCode_Values() []string { + return []string{ + ClusterStateChangeReasonCodeInternalError, + ClusterStateChangeReasonCodeValidationError, + ClusterStateChangeReasonCodeInstanceFailure, + ClusterStateChangeReasonCodeInstanceFleetTimeout, + ClusterStateChangeReasonCodeBootstrapFailure, + ClusterStateChangeReasonCodeUserRequest, + ClusterStateChangeReasonCodeStepFailure, + ClusterStateChangeReasonCodeAllStepsCompleted, + } +} + const ( // ComparisonOperatorGreaterThanOrEqual is a ComparisonOperator enum value ComparisonOperatorGreaterThanOrEqual = "GREATER_THAN_OR_EQUAL" @@ -11979,6 +12175,16 @@ const ( ComparisonOperatorLessThanOrEqual = "LESS_THAN_OR_EQUAL" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorGreaterThanOrEqual, + ComparisonOperatorGreaterThan, + ComparisonOperatorLessThan, + ComparisonOperatorLessThanOrEqual, + } +} + const ( // ComputeLimitsUnitTypeInstanceFleetUnits is a ComputeLimitsUnitType enum value ComputeLimitsUnitTypeInstanceFleetUnits = "InstanceFleetUnits" @@ -11990,6 +12196,15 @@ const ( ComputeLimitsUnitTypeVcpu = "VCPU" ) +// ComputeLimitsUnitType_Values returns all elements of the ComputeLimitsUnitType enum +func ComputeLimitsUnitType_Values() []string { + return []string{ + ComputeLimitsUnitTypeInstanceFleetUnits, + ComputeLimitsUnitTypeInstances, + ComputeLimitsUnitTypeVcpu, + } +} + const ( // InstanceCollectionTypeInstanceFleet is a InstanceCollectionType enum value InstanceCollectionTypeInstanceFleet = "INSTANCE_FLEET" @@ -11998,6 +12213,14 @@ const ( InstanceCollectionTypeInstanceGroup = "INSTANCE_GROUP" ) +// InstanceCollectionType_Values returns all elements of the InstanceCollectionType enum +func InstanceCollectionType_Values() []string { + return []string{ + InstanceCollectionTypeInstanceFleet, + InstanceCollectionTypeInstanceGroup, + } +} + const ( // InstanceFleetStateProvisioning is a InstanceFleetState enum value InstanceFleetStateProvisioning = "PROVISIONING" @@ -12021,6 +12244,19 @@ const ( InstanceFleetStateTerminated = "TERMINATED" ) +// InstanceFleetState_Values returns all elements of the InstanceFleetState enum +func InstanceFleetState_Values() []string { + return []string{ + InstanceFleetStateProvisioning, + InstanceFleetStateBootstrapping, + InstanceFleetStateRunning, + InstanceFleetStateResizing, + InstanceFleetStateSuspended, + InstanceFleetStateTerminating, + InstanceFleetStateTerminated, + } +} + const ( // InstanceFleetStateChangeReasonCodeInternalError is a InstanceFleetStateChangeReasonCode enum value InstanceFleetStateChangeReasonCodeInternalError = "INTERNAL_ERROR" @@ -12035,6 +12271,16 @@ const ( InstanceFleetStateChangeReasonCodeClusterTerminated = "CLUSTER_TERMINATED" ) +// InstanceFleetStateChangeReasonCode_Values returns all elements of the InstanceFleetStateChangeReasonCode enum +func InstanceFleetStateChangeReasonCode_Values() []string { + return []string{ + InstanceFleetStateChangeReasonCodeInternalError, + InstanceFleetStateChangeReasonCodeValidationError, + InstanceFleetStateChangeReasonCodeInstanceFailure, + InstanceFleetStateChangeReasonCodeClusterTerminated, + } +} + const ( // InstanceFleetTypeMaster is a InstanceFleetType enum value InstanceFleetTypeMaster = "MASTER" @@ -12046,6 +12292,15 @@ const ( InstanceFleetTypeTask = "TASK" ) +// InstanceFleetType_Values returns all elements of the InstanceFleetType enum +func InstanceFleetType_Values() []string { + return []string{ + InstanceFleetTypeMaster, + InstanceFleetTypeCore, + InstanceFleetTypeTask, + } +} + const ( // InstanceGroupStateProvisioning is a InstanceGroupState enum value InstanceGroupStateProvisioning = "PROVISIONING" @@ -12081,6 +12336,23 @@ const ( InstanceGroupStateEnded = "ENDED" ) +// InstanceGroupState_Values returns all elements of the InstanceGroupState enum +func InstanceGroupState_Values() []string { + return []string{ + InstanceGroupStateProvisioning, + InstanceGroupStateBootstrapping, + InstanceGroupStateRunning, + InstanceGroupStateReconfiguring, + InstanceGroupStateResizing, + InstanceGroupStateSuspended, + InstanceGroupStateTerminating, + InstanceGroupStateTerminated, + InstanceGroupStateArrested, + InstanceGroupStateShuttingDown, + InstanceGroupStateEnded, + } +} + const ( // InstanceGroupStateChangeReasonCodeInternalError is a InstanceGroupStateChangeReasonCode enum value InstanceGroupStateChangeReasonCodeInternalError = "INTERNAL_ERROR" @@ -12095,6 +12367,16 @@ const ( InstanceGroupStateChangeReasonCodeClusterTerminated = "CLUSTER_TERMINATED" ) +// InstanceGroupStateChangeReasonCode_Values returns all elements of the InstanceGroupStateChangeReasonCode enum +func InstanceGroupStateChangeReasonCode_Values() []string { + return []string{ + InstanceGroupStateChangeReasonCodeInternalError, + InstanceGroupStateChangeReasonCodeValidationError, + InstanceGroupStateChangeReasonCodeInstanceFailure, + InstanceGroupStateChangeReasonCodeClusterTerminated, + } +} + const ( // InstanceGroupTypeMaster is a InstanceGroupType enum value InstanceGroupTypeMaster = "MASTER" @@ -12106,6 +12388,15 @@ const ( InstanceGroupTypeTask = "TASK" ) +// InstanceGroupType_Values returns all elements of the InstanceGroupType enum +func InstanceGroupType_Values() []string { + return []string{ + InstanceGroupTypeMaster, + InstanceGroupTypeCore, + InstanceGroupTypeTask, + } +} + const ( // InstanceRoleTypeMaster is a InstanceRoleType enum value InstanceRoleTypeMaster = "MASTER" @@ -12117,6 +12408,15 @@ const ( InstanceRoleTypeTask = "TASK" ) +// InstanceRoleType_Values returns all elements of the InstanceRoleType enum +func InstanceRoleType_Values() []string { + return []string{ + InstanceRoleTypeMaster, + InstanceRoleTypeCore, + InstanceRoleTypeTask, + } +} + const ( // InstanceStateAwaitingFulfillment is a InstanceState enum value InstanceStateAwaitingFulfillment = "AWAITING_FULFILLMENT" @@ -12134,6 +12434,17 @@ const ( InstanceStateTerminated = "TERMINATED" ) +// InstanceState_Values returns all elements of the InstanceState enum +func InstanceState_Values() []string { + return []string{ + InstanceStateAwaitingFulfillment, + InstanceStateProvisioning, + InstanceStateBootstrapping, + InstanceStateRunning, + InstanceStateTerminated, + } +} + const ( // InstanceStateChangeReasonCodeInternalError is a InstanceStateChangeReasonCode enum value InstanceStateChangeReasonCodeInternalError = "INTERNAL_ERROR" @@ -12151,6 +12462,17 @@ const ( InstanceStateChangeReasonCodeClusterTerminated = "CLUSTER_TERMINATED" ) +// InstanceStateChangeReasonCode_Values returns all elements of the InstanceStateChangeReasonCode enum +func InstanceStateChangeReasonCode_Values() []string { + return []string{ + InstanceStateChangeReasonCodeInternalError, + InstanceStateChangeReasonCodeValidationError, + InstanceStateChangeReasonCodeInstanceFailure, + InstanceStateChangeReasonCodeBootstrapFailure, + InstanceStateChangeReasonCodeClusterTerminated, + } +} + // The type of instance. const ( // JobFlowExecutionStateStarting is a JobFlowExecutionState enum value @@ -12178,6 +12500,20 @@ const ( JobFlowExecutionStateFailed = "FAILED" ) +// JobFlowExecutionState_Values returns all elements of the JobFlowExecutionState enum +func JobFlowExecutionState_Values() []string { + return []string{ + JobFlowExecutionStateStarting, + JobFlowExecutionStateBootstrapping, + JobFlowExecutionStateRunning, + JobFlowExecutionStateWaiting, + JobFlowExecutionStateShuttingDown, + JobFlowExecutionStateTerminated, + JobFlowExecutionStateCompleted, + JobFlowExecutionStateFailed, + } +} + const ( // MarketTypeOnDemand is a MarketType enum value MarketTypeOnDemand = "ON_DEMAND" @@ -12186,6 +12522,26 @@ const ( MarketTypeSpot = "SPOT" ) +// MarketType_Values returns all elements of the MarketType enum +func MarketType_Values() []string { + return []string{ + MarketTypeOnDemand, + MarketTypeSpot, + } +} + +const ( + // OnDemandProvisioningAllocationStrategyLowestPrice is a OnDemandProvisioningAllocationStrategy enum value + OnDemandProvisioningAllocationStrategyLowestPrice = "lowest-price" +) + +// OnDemandProvisioningAllocationStrategy_Values returns all elements of the OnDemandProvisioningAllocationStrategy enum +func OnDemandProvisioningAllocationStrategy_Values() []string { + return []string{ + OnDemandProvisioningAllocationStrategyLowestPrice, + } +} + const ( // RepoUpgradeOnBootSecurity is a RepoUpgradeOnBoot enum value RepoUpgradeOnBootSecurity = "SECURITY" @@ -12194,6 +12550,14 @@ const ( RepoUpgradeOnBootNone = "NONE" ) +// RepoUpgradeOnBoot_Values returns all elements of the RepoUpgradeOnBoot enum +func RepoUpgradeOnBoot_Values() []string { + return []string{ + RepoUpgradeOnBootSecurity, + RepoUpgradeOnBootNone, + } +} + const ( // ScaleDownBehaviorTerminateAtInstanceHour is a ScaleDownBehavior enum value ScaleDownBehaviorTerminateAtInstanceHour = "TERMINATE_AT_INSTANCE_HOUR" @@ -12202,6 +12566,26 @@ const ( ScaleDownBehaviorTerminateAtTaskCompletion = "TERMINATE_AT_TASK_COMPLETION" ) +// ScaleDownBehavior_Values returns all elements of the ScaleDownBehavior enum +func ScaleDownBehavior_Values() []string { + return []string{ + ScaleDownBehaviorTerminateAtInstanceHour, + ScaleDownBehaviorTerminateAtTaskCompletion, + } +} + +const ( + // SpotProvisioningAllocationStrategyCapacityOptimized is a SpotProvisioningAllocationStrategy enum value + SpotProvisioningAllocationStrategyCapacityOptimized = "capacity-optimized" +) + +// SpotProvisioningAllocationStrategy_Values returns all elements of the SpotProvisioningAllocationStrategy enum +func SpotProvisioningAllocationStrategy_Values() []string { + return []string{ + SpotProvisioningAllocationStrategyCapacityOptimized, + } +} + const ( // SpotProvisioningTimeoutActionSwitchToOnDemand is a SpotProvisioningTimeoutAction enum value SpotProvisioningTimeoutActionSwitchToOnDemand = "SWITCH_TO_ON_DEMAND" @@ -12210,6 +12594,14 @@ const ( SpotProvisioningTimeoutActionTerminateCluster = "TERMINATE_CLUSTER" ) +// SpotProvisioningTimeoutAction_Values returns all elements of the SpotProvisioningTimeoutAction enum +func SpotProvisioningTimeoutAction_Values() []string { + return []string{ + SpotProvisioningTimeoutActionSwitchToOnDemand, + SpotProvisioningTimeoutActionTerminateCluster, + } +} + const ( // StatisticSampleCount is a Statistic enum value StatisticSampleCount = "SAMPLE_COUNT" @@ -12227,6 +12619,17 @@ const ( StatisticMaximum = "MAXIMUM" ) +// Statistic_Values returns all elements of the Statistic enum +func Statistic_Values() []string { + return []string{ + StatisticSampleCount, + StatisticAverage, + StatisticSum, + StatisticMinimum, + StatisticMaximum, + } +} + const ( // StepCancellationOptionSendInterrupt is a StepCancellationOption enum value StepCancellationOptionSendInterrupt = "SEND_INTERRUPT" @@ -12235,6 +12638,14 @@ const ( StepCancellationOptionTerminateProcess = "TERMINATE_PROCESS" ) +// StepCancellationOption_Values returns all elements of the StepCancellationOption enum +func StepCancellationOption_Values() []string { + return []string{ + StepCancellationOptionSendInterrupt, + StepCancellationOptionTerminateProcess, + } +} + const ( // StepExecutionStatePending is a StepExecutionState enum value StepExecutionStatePending = "PENDING" @@ -12258,6 +12669,19 @@ const ( StepExecutionStateInterrupted = "INTERRUPTED" ) +// StepExecutionState_Values returns all elements of the StepExecutionState enum +func StepExecutionState_Values() []string { + return []string{ + StepExecutionStatePending, + StepExecutionStateRunning, + StepExecutionStateContinue, + StepExecutionStateCompleted, + StepExecutionStateCancelled, + StepExecutionStateFailed, + StepExecutionStateInterrupted, + } +} + const ( // StepStatePending is a StepState enum value StepStatePending = "PENDING" @@ -12281,11 +12705,31 @@ const ( StepStateInterrupted = "INTERRUPTED" ) +// StepState_Values returns all elements of the StepState enum +func StepState_Values() []string { + return []string{ + StepStatePending, + StepStateCancelPending, + StepStateRunning, + StepStateCompleted, + StepStateCancelled, + StepStateFailed, + StepStateInterrupted, + } +} + const ( // StepStateChangeReasonCodeNone is a StepStateChangeReasonCode enum value StepStateChangeReasonCodeNone = "NONE" ) +// StepStateChangeReasonCode_Values returns all elements of the StepStateChangeReasonCode enum +func StepStateChangeReasonCode_Values() []string { + return []string{ + StepStateChangeReasonCodeNone, + } +} + const ( // UnitNone is a Unit enum value UnitNone = "NONE" @@ -12368,3 +12812,36 @@ const ( // UnitCountPerSecond is a Unit enum value UnitCountPerSecond = "COUNT_PER_SECOND" ) + +// Unit_Values returns all elements of the Unit enum +func Unit_Values() []string { + return []string{ + UnitNone, + UnitSeconds, + UnitMicroSeconds, + UnitMilliSeconds, + UnitBytes, + UnitKiloBytes, + UnitMegaBytes, + UnitGigaBytes, + UnitTeraBytes, + UnitBits, + UnitKiloBits, + UnitMegaBits, + UnitGigaBits, + UnitTeraBits, + UnitPercent, + UnitCount, + UnitBytesPerSecond, + UnitKiloBytesPerSecond, + UnitMegaBytesPerSecond, + UnitGigaBytesPerSecond, + UnitTeraBytesPerSecond, + UnitBitsPerSecond, + UnitKiloBitsPerSecond, + UnitMegaBitsPerSecond, + UnitGigaBitsPerSecond, + UnitTeraBitsPerSecond, + UnitCountPerSecond, + } +} 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 63f397348f4..3db7c5a87b2 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 @@ -696,11 +696,8 @@ func (c *Firehose) PutRecordBatchRequest(input *PutRecordBatchInput) (req *reque // To write single data records into a delivery stream, use PutRecord. Applications // using these operations are referred to as producers. // -// By default, each delivery stream can take in up to 2,000 transactions per -// second, 5,000 records per second, or 5 MB per second. If you use PutRecord -// and PutRecordBatch, the limits are an aggregate across these two operations -// for each delivery stream. For more information about limits, see Amazon Kinesis -// Data Firehose Limits (https://docs.aws.amazon.com/firehose/latest/dev/limits.html). +// For information about service quota, see Amazon Kinesis Data Firehose Quota +// (https://docs.aws.amazon.com/firehose/latest/dev/limits.html). // // Each PutRecordBatch request supports up to 500 records. Each record in the // request can be as large as 1,000 KB (before 64-bit encoding), up to a limit @@ -1637,6 +1634,10 @@ type CreateDeliveryStreamInput struct { // The destination in Amazon S3. You can specify only one destination. ExtendedS3DestinationConfiguration *ExtendedS3DestinationConfiguration `type:"structure"` + // Enables configuring Kinesis Firehose to deliver data to any HTTP endpoint + // destination. You can specify only one destination. + HttpEndpointDestinationConfiguration *HttpEndpointDestinationConfiguration `type:"structure"` + // When a Kinesis data stream is used as the source for the delivery stream, // a KinesisStreamSourceConfiguration containing the Kinesis data stream Amazon // Resource Name (ARN) and the role ARN for the source stream. @@ -1701,6 +1702,11 @@ func (s *CreateDeliveryStreamInput) Validate() error { invalidParams.AddNested("ExtendedS3DestinationConfiguration", err.(request.ErrInvalidParams)) } } + if s.HttpEndpointDestinationConfiguration != nil { + if err := s.HttpEndpointDestinationConfiguration.Validate(); err != nil { + invalidParams.AddNested("HttpEndpointDestinationConfiguration", err.(request.ErrInvalidParams)) + } + } if s.KinesisStreamSourceConfiguration != nil { if err := s.KinesisStreamSourceConfiguration.Validate(); err != nil { invalidParams.AddNested("KinesisStreamSourceConfiguration", err.(request.ErrInvalidParams)) @@ -1768,6 +1774,12 @@ func (s *CreateDeliveryStreamInput) SetExtendedS3DestinationConfiguration(v *Ext return s } +// SetHttpEndpointDestinationConfiguration sets the HttpEndpointDestinationConfiguration field's value. +func (s *CreateDeliveryStreamInput) SetHttpEndpointDestinationConfiguration(v *HttpEndpointDestinationConfiguration) *CreateDeliveryStreamInput { + s.HttpEndpointDestinationConfiguration = v + return s +} + // SetKinesisStreamSourceConfiguration sets the KinesisStreamSourceConfiguration field's value. func (s *CreateDeliveryStreamInput) SetKinesisStreamSourceConfiguration(v *KinesisStreamSourceConfiguration) *CreateDeliveryStreamInput { s.KinesisStreamSourceConfiguration = v @@ -2418,6 +2430,9 @@ type DestinationDescription struct { // The destination in Amazon S3. ExtendedS3DestinationDescription *ExtendedS3DestinationDescription `type:"structure"` + // Describes the specified HTTP endpoint destination. + HttpEndpointDestinationDescription *HttpEndpointDestinationDescription `type:"structure"` + // The destination in Amazon Redshift. RedshiftDestinationDescription *RedshiftDestinationDescription `type:"structure"` @@ -2456,6 +2471,12 @@ func (s *DestinationDescription) SetExtendedS3DestinationDescription(v *Extended return s } +// SetHttpEndpointDestinationDescription sets the HttpEndpointDestinationDescription field's value. +func (s *DestinationDescription) SetHttpEndpointDestinationDescription(v *HttpEndpointDestinationDescription) *DestinationDescription { + s.HttpEndpointDestinationDescription = v + return s +} + // SetRedshiftDestinationDescription sets the RedshiftDestinationDescription field's value. func (s *DestinationDescription) SetRedshiftDestinationDescription(v *RedshiftDestinationDescription) *DestinationDescription { s.RedshiftDestinationDescription = v @@ -2588,6 +2609,8 @@ type ElasticsearchDestinationConfiguration struct { // with elasticsearch-failed/ appended to the prefix. For more information, // see Amazon S3 Backup for the Amazon ES Destination (https://docs.aws.amazon.com/firehose/latest/dev/basic-deliver.html#es-s3-backup). // Default value is FailedDocumentsOnly. + // + // You can't change this backup mode after you create the delivery stream. S3BackupMode *string `type:"string" enum:"ElasticsearchS3BackupMode"` // The configuration for the backup Amazon S3 location. @@ -3187,7 +3210,9 @@ type ExtendedS3DestinationConfiguration struct { // The configuration for backup in Amazon S3. S3BackupConfiguration *S3DestinationConfiguration `type:"structure"` - // The Amazon S3 backup mode. + // The Amazon S3 backup mode. After you create a delivery stream, you can update + // it to enable Amazon S3 backup if it is disabled. If backup is enabled, you + // can't update the delivery stream to disable it. S3BackupMode *string `type:"string" enum:"S3BackupMode"` } @@ -3483,51 +3508,762 @@ type ExtendedS3DestinationUpdate struct { // format to the Parquet or ORC format before writing it to Amazon S3. DataFormatConversionConfiguration *DataFormatConversionConfiguration `type:"structure"` - // The encryption configuration. If no value is specified, the default is no - // encryption. - EncryptionConfiguration *EncryptionConfiguration `type:"structure"` + // The encryption configuration. If no value is specified, the default is no + // encryption. + EncryptionConfiguration *EncryptionConfiguration `type:"structure"` + + // A prefix that Kinesis Data Firehose evaluates and adds to failed records + // before writing them to S3. This prefix appears immediately following the + // bucket name. For information about how to specify this prefix, see Custom + // Prefixes for Amazon S3 Objects (https://docs.aws.amazon.com/firehose/latest/dev/s3-prefixes.html). + ErrorOutputPrefix *string `type:"string"` + + // The "YYYY/MM/DD/HH" time format prefix is automatically used for delivered + // Amazon S3 files. You can also specify a custom prefix, as described in Custom + // Prefixes for Amazon S3 Objects (https://docs.aws.amazon.com/firehose/latest/dev/s3-prefixes.html). + Prefix *string `type:"string"` + + // The data processing configuration. + ProcessingConfiguration *ProcessingConfiguration `type:"structure"` + + // The Amazon Resource Name (ARN) of the AWS credentials. For more information, + // see Amazon Resource Names (ARNs) and AWS Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). + RoleARN *string `min:"1" type:"string"` + + // You can update a delivery stream to enable Amazon S3 backup if it is disabled. + // If backup is enabled, you can't update the delivery stream to disable it. + S3BackupMode *string `type:"string" enum:"S3BackupMode"` + + // The Amazon S3 destination for backup. + S3BackupUpdate *S3DestinationUpdate `type:"structure"` +} + +// String returns the string representation +func (s ExtendedS3DestinationUpdate) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ExtendedS3DestinationUpdate) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ExtendedS3DestinationUpdate) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ExtendedS3DestinationUpdate"} + if s.BucketARN != nil && len(*s.BucketARN) < 1 { + invalidParams.Add(request.NewErrParamMinLen("BucketARN", 1)) + } + if s.RoleARN != nil && len(*s.RoleARN) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RoleARN", 1)) + } + if s.BufferingHints != nil { + if err := s.BufferingHints.Validate(); err != nil { + invalidParams.AddNested("BufferingHints", err.(request.ErrInvalidParams)) + } + } + if s.DataFormatConversionConfiguration != nil { + if err := s.DataFormatConversionConfiguration.Validate(); err != nil { + invalidParams.AddNested("DataFormatConversionConfiguration", err.(request.ErrInvalidParams)) + } + } + if s.EncryptionConfiguration != nil { + if err := s.EncryptionConfiguration.Validate(); err != nil { + invalidParams.AddNested("EncryptionConfiguration", err.(request.ErrInvalidParams)) + } + } + if s.ProcessingConfiguration != nil { + if err := s.ProcessingConfiguration.Validate(); err != nil { + invalidParams.AddNested("ProcessingConfiguration", err.(request.ErrInvalidParams)) + } + } + if s.S3BackupUpdate != nil { + if err := s.S3BackupUpdate.Validate(); err != nil { + invalidParams.AddNested("S3BackupUpdate", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBucketARN sets the BucketARN field's value. +func (s *ExtendedS3DestinationUpdate) SetBucketARN(v string) *ExtendedS3DestinationUpdate { + s.BucketARN = &v + return s +} + +// SetBufferingHints sets the BufferingHints field's value. +func (s *ExtendedS3DestinationUpdate) SetBufferingHints(v *BufferingHints) *ExtendedS3DestinationUpdate { + s.BufferingHints = v + return s +} + +// SetCloudWatchLoggingOptions sets the CloudWatchLoggingOptions field's value. +func (s *ExtendedS3DestinationUpdate) SetCloudWatchLoggingOptions(v *CloudWatchLoggingOptions) *ExtendedS3DestinationUpdate { + s.CloudWatchLoggingOptions = v + return s +} + +// SetCompressionFormat sets the CompressionFormat field's value. +func (s *ExtendedS3DestinationUpdate) SetCompressionFormat(v string) *ExtendedS3DestinationUpdate { + s.CompressionFormat = &v + return s +} + +// SetDataFormatConversionConfiguration sets the DataFormatConversionConfiguration field's value. +func (s *ExtendedS3DestinationUpdate) SetDataFormatConversionConfiguration(v *DataFormatConversionConfiguration) *ExtendedS3DestinationUpdate { + s.DataFormatConversionConfiguration = v + return s +} + +// SetEncryptionConfiguration sets the EncryptionConfiguration field's value. +func (s *ExtendedS3DestinationUpdate) SetEncryptionConfiguration(v *EncryptionConfiguration) *ExtendedS3DestinationUpdate { + s.EncryptionConfiguration = v + return s +} + +// SetErrorOutputPrefix sets the ErrorOutputPrefix field's value. +func (s *ExtendedS3DestinationUpdate) SetErrorOutputPrefix(v string) *ExtendedS3DestinationUpdate { + s.ErrorOutputPrefix = &v + return s +} + +// SetPrefix sets the Prefix field's value. +func (s *ExtendedS3DestinationUpdate) SetPrefix(v string) *ExtendedS3DestinationUpdate { + s.Prefix = &v + return s +} + +// SetProcessingConfiguration sets the ProcessingConfiguration field's value. +func (s *ExtendedS3DestinationUpdate) SetProcessingConfiguration(v *ProcessingConfiguration) *ExtendedS3DestinationUpdate { + s.ProcessingConfiguration = v + return s +} + +// SetRoleARN sets the RoleARN field's value. +func (s *ExtendedS3DestinationUpdate) SetRoleARN(v string) *ExtendedS3DestinationUpdate { + s.RoleARN = &v + return s +} + +// SetS3BackupMode sets the S3BackupMode field's value. +func (s *ExtendedS3DestinationUpdate) SetS3BackupMode(v string) *ExtendedS3DestinationUpdate { + s.S3BackupMode = &v + return s +} + +// SetS3BackupUpdate sets the S3BackupUpdate field's value. +func (s *ExtendedS3DestinationUpdate) SetS3BackupUpdate(v *S3DestinationUpdate) *ExtendedS3DestinationUpdate { + s.S3BackupUpdate = v + return s +} + +// Provides details in case one of the following operations fails due to an +// error related to KMS: CreateDeliveryStream, DeleteDeliveryStream, StartDeliveryStreamEncryption, +// StopDeliveryStreamEncryption. +type FailureDescription struct { + _ struct{} `type:"structure"` + + // A message providing details about the error that caused the failure. + // + // Details is a required field + Details *string `min:"1" type:"string" required:"true"` + + // The type of error that caused the failure. + // + // Type is a required field + Type *string `type:"string" required:"true" enum:"DeliveryStreamFailureType"` +} + +// String returns the string representation +func (s FailureDescription) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FailureDescription) GoString() string { + return s.String() +} + +// SetDetails sets the Details field's value. +func (s *FailureDescription) SetDetails(v string) *FailureDescription { + s.Details = &v + return s +} + +// SetType sets the Type field's value. +func (s *FailureDescription) SetType(v string) *FailureDescription { + s.Type = &v + return s +} + +// The native Hive / HCatalog JsonSerDe. Used by Kinesis Data Firehose for deserializing +// data, which means converting it from the JSON format in preparation for serializing +// it to the Parquet or ORC format. This is one of two deserializers you can +// choose, depending on which one offers the functionality you need. The other +// option is the OpenX SerDe. +type HiveJsonSerDe struct { + _ struct{} `type:"structure"` + + // Indicates how you want Kinesis Data Firehose to parse the date and timestamps + // that may be present in your input data JSON. To specify these format strings, + // follow the pattern syntax of JodaTime's DateTimeFormat format strings. For + // more information, see Class DateTimeFormat (https://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html). + // You can also use the special value millis to parse timestamps in epoch milliseconds. + // If you don't specify a format, Kinesis Data Firehose uses java.sql.Timestamp::valueOf + // by default. + TimestampFormats []*string `type:"list"` +} + +// String returns the string representation +func (s HiveJsonSerDe) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s HiveJsonSerDe) GoString() string { + return s.String() +} + +// SetTimestampFormats sets the TimestampFormats field's value. +func (s *HiveJsonSerDe) SetTimestampFormats(v []*string) *HiveJsonSerDe { + s.TimestampFormats = v + return s +} + +// Describes the buffering options that can be applied before data is delivered +// to the HTTP endpoint destination. Kinesis Data Firehose treats these options +// as hints, and it might choose to use more optimal values. The SizeInMBs and +// IntervalInSeconds parameters are optional. However, if specify a value for +// one of them, you must also provide a value for the other. +type HttpEndpointBufferingHints struct { + _ struct{} `type:"structure"` + + // Buffer incoming data for the specified period of time, in seconds, before + // delivering it to the destination. The default value is 300 (5 minutes). + IntervalInSeconds *int64 `min:"60" type:"integer"` + + // Buffer incoming data to the specified size, in MBs, before delivering it + // to the destination. The default value is 5. + // + // We recommend setting this parameter to a value greater than the amount of + // data you typically ingest into the delivery stream in 10 seconds. For example, + // if you typically ingest data at 1 MB/sec, the value should be 10 MB or higher. + SizeInMBs *int64 `min:"1" type:"integer"` +} + +// String returns the string representation +func (s HttpEndpointBufferingHints) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s HttpEndpointBufferingHints) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *HttpEndpointBufferingHints) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpEndpointBufferingHints"} + if s.IntervalInSeconds != nil && *s.IntervalInSeconds < 60 { + invalidParams.Add(request.NewErrParamMinValue("IntervalInSeconds", 60)) + } + if s.SizeInMBs != nil && *s.SizeInMBs < 1 { + invalidParams.Add(request.NewErrParamMinValue("SizeInMBs", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIntervalInSeconds sets the IntervalInSeconds field's value. +func (s *HttpEndpointBufferingHints) SetIntervalInSeconds(v int64) *HttpEndpointBufferingHints { + s.IntervalInSeconds = &v + return s +} + +// SetSizeInMBs sets the SizeInMBs field's value. +func (s *HttpEndpointBufferingHints) SetSizeInMBs(v int64) *HttpEndpointBufferingHints { + s.SizeInMBs = &v + return s +} + +// Describes the metadata that's delivered to the specified HTTP endpoint destination. +type HttpEndpointCommonAttribute struct { + _ struct{} `type:"structure"` + + // The name of the HTTP endpoint common attribute. + // + // AttributeName is a required field + AttributeName *string `min:"1" type:"string" required:"true" sensitive:"true"` + + // The value of the HTTP endpoint common attribute. + // + // AttributeValue is a required field + AttributeValue *string `type:"string" required:"true" sensitive:"true"` +} + +// String returns the string representation +func (s HttpEndpointCommonAttribute) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s HttpEndpointCommonAttribute) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *HttpEndpointCommonAttribute) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpEndpointCommonAttribute"} + if s.AttributeName == nil { + invalidParams.Add(request.NewErrParamRequired("AttributeName")) + } + if s.AttributeName != nil && len(*s.AttributeName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AttributeName", 1)) + } + if s.AttributeValue == nil { + invalidParams.Add(request.NewErrParamRequired("AttributeValue")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAttributeName sets the AttributeName field's value. +func (s *HttpEndpointCommonAttribute) SetAttributeName(v string) *HttpEndpointCommonAttribute { + s.AttributeName = &v + return s +} + +// SetAttributeValue sets the AttributeValue field's value. +func (s *HttpEndpointCommonAttribute) SetAttributeValue(v string) *HttpEndpointCommonAttribute { + s.AttributeValue = &v + return s +} + +// Describes the configuration of the HTTP endpoint to which Kinesis Firehose +// delivers data. +type HttpEndpointConfiguration struct { + _ struct{} `type:"structure"` + + // The access key required for Kinesis Firehose to authenticate with the HTTP + // endpoint selected as the destination. + AccessKey *string `type:"string" sensitive:"true"` + + // The name of the HTTP endpoint selected as the destination. + Name *string `min:"1" type:"string"` + + // The URL of the HTTP endpoint selected as the destination. + // + // Url is a required field + Url *string `min:"1" type:"string" required:"true" sensitive:"true"` +} + +// String returns the string representation +func (s HttpEndpointConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s HttpEndpointConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *HttpEndpointConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpEndpointConfiguration"} + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.Url == nil { + invalidParams.Add(request.NewErrParamRequired("Url")) + } + if s.Url != nil && len(*s.Url) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Url", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAccessKey sets the AccessKey field's value. +func (s *HttpEndpointConfiguration) SetAccessKey(v string) *HttpEndpointConfiguration { + s.AccessKey = &v + return s +} + +// SetName sets the Name field's value. +func (s *HttpEndpointConfiguration) SetName(v string) *HttpEndpointConfiguration { + s.Name = &v + return s +} + +// SetUrl sets the Url field's value. +func (s *HttpEndpointConfiguration) SetUrl(v string) *HttpEndpointConfiguration { + s.Url = &v + return s +} + +// Describes the HTTP endpoint selected as the destination. +type HttpEndpointDescription struct { + _ struct{} `type:"structure"` + + // The name of the HTTP endpoint selected as the destination. + Name *string `min:"1" type:"string"` + + // The URL of the HTTP endpoint selected as the destination. + Url *string `min:"1" type:"string" sensitive:"true"` +} + +// String returns the string representation +func (s HttpEndpointDescription) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s HttpEndpointDescription) GoString() string { + return s.String() +} + +// SetName sets the Name field's value. +func (s *HttpEndpointDescription) SetName(v string) *HttpEndpointDescription { + s.Name = &v + return s +} + +// SetUrl sets the Url field's value. +func (s *HttpEndpointDescription) SetUrl(v string) *HttpEndpointDescription { + s.Url = &v + return s +} + +// Describes the configuration of the HTTP endpoint destination. +type HttpEndpointDestinationConfiguration struct { + _ struct{} `type:"structure"` + + // The buffering options that can be used before data is delivered to the specified + // destination. Kinesis Data Firehose treats these options as hints, and it + // might choose to use more optimal values. The SizeInMBs and IntervalInSeconds + // parameters are optional. However, if you specify a value for one of them, + // you must also provide a value for the other. + BufferingHints *HttpEndpointBufferingHints `type:"structure"` + + // Describes the Amazon CloudWatch logging options for your delivery stream. + CloudWatchLoggingOptions *CloudWatchLoggingOptions `type:"structure"` + + // The configuration of the HTTP endpoint selected as the destination. + // + // EndpointConfiguration is a required field + EndpointConfiguration *HttpEndpointConfiguration `type:"structure" required:"true"` + + // Describes a data processing configuration. + ProcessingConfiguration *ProcessingConfiguration `type:"structure"` + + // The configuration of the requeste sent to the HTTP endpoint specified as + // the destination. + RequestConfiguration *HttpEndpointRequestConfiguration `type:"structure"` + + // Describes the retry behavior in case Kinesis Data Firehose is unable to deliver + // data to the specified HTTP endpoint destination, or if it doesn't receive + // a valid acknowledgment of receipt from the specified HTTP endpoint destination. + RetryOptions *HttpEndpointRetryOptions `type:"structure"` + + // Kinesis Data Firehose uses this IAM role for all the permissions that the + // delivery stream needs. + RoleARN *string `min:"1" type:"string"` + + // Describes the S3 bucket backup options for the data that Kinesis Data Firehose + // delivers to the HTTP endpoint destination. You can back up all documents + // (AllData) or only the documents that Kinesis Data Firehose could not deliver + // to the specified HTTP endpoint destination (FailedDataOnly). + S3BackupMode *string `type:"string" enum:"HttpEndpointS3BackupMode"` + + // Describes the configuration of a destination in Amazon S3. + // + // S3Configuration is a required field + S3Configuration *S3DestinationConfiguration `type:"structure" required:"true"` +} + +// String returns the string representation +func (s HttpEndpointDestinationConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s HttpEndpointDestinationConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *HttpEndpointDestinationConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpEndpointDestinationConfiguration"} + if s.EndpointConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("EndpointConfiguration")) + } + if s.RoleARN != nil && len(*s.RoleARN) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RoleARN", 1)) + } + if s.S3Configuration == nil { + invalidParams.Add(request.NewErrParamRequired("S3Configuration")) + } + if s.BufferingHints != nil { + if err := s.BufferingHints.Validate(); err != nil { + invalidParams.AddNested("BufferingHints", err.(request.ErrInvalidParams)) + } + } + if s.EndpointConfiguration != nil { + if err := s.EndpointConfiguration.Validate(); err != nil { + invalidParams.AddNested("EndpointConfiguration", err.(request.ErrInvalidParams)) + } + } + if s.ProcessingConfiguration != nil { + if err := s.ProcessingConfiguration.Validate(); err != nil { + invalidParams.AddNested("ProcessingConfiguration", err.(request.ErrInvalidParams)) + } + } + if s.RequestConfiguration != nil { + if err := s.RequestConfiguration.Validate(); err != nil { + invalidParams.AddNested("RequestConfiguration", err.(request.ErrInvalidParams)) + } + } + if s.S3Configuration != nil { + if err := s.S3Configuration.Validate(); err != nil { + invalidParams.AddNested("S3Configuration", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBufferingHints sets the BufferingHints field's value. +func (s *HttpEndpointDestinationConfiguration) SetBufferingHints(v *HttpEndpointBufferingHints) *HttpEndpointDestinationConfiguration { + s.BufferingHints = v + return s +} + +// SetCloudWatchLoggingOptions sets the CloudWatchLoggingOptions field's value. +func (s *HttpEndpointDestinationConfiguration) SetCloudWatchLoggingOptions(v *CloudWatchLoggingOptions) *HttpEndpointDestinationConfiguration { + s.CloudWatchLoggingOptions = v + return s +} + +// SetEndpointConfiguration sets the EndpointConfiguration field's value. +func (s *HttpEndpointDestinationConfiguration) SetEndpointConfiguration(v *HttpEndpointConfiguration) *HttpEndpointDestinationConfiguration { + s.EndpointConfiguration = v + return s +} + +// SetProcessingConfiguration sets the ProcessingConfiguration field's value. +func (s *HttpEndpointDestinationConfiguration) SetProcessingConfiguration(v *ProcessingConfiguration) *HttpEndpointDestinationConfiguration { + s.ProcessingConfiguration = v + return s +} + +// SetRequestConfiguration sets the RequestConfiguration field's value. +func (s *HttpEndpointDestinationConfiguration) SetRequestConfiguration(v *HttpEndpointRequestConfiguration) *HttpEndpointDestinationConfiguration { + s.RequestConfiguration = v + return s +} + +// SetRetryOptions sets the RetryOptions field's value. +func (s *HttpEndpointDestinationConfiguration) SetRetryOptions(v *HttpEndpointRetryOptions) *HttpEndpointDestinationConfiguration { + s.RetryOptions = v + return s +} + +// SetRoleARN sets the RoleARN field's value. +func (s *HttpEndpointDestinationConfiguration) SetRoleARN(v string) *HttpEndpointDestinationConfiguration { + s.RoleARN = &v + return s +} + +// SetS3BackupMode sets the S3BackupMode field's value. +func (s *HttpEndpointDestinationConfiguration) SetS3BackupMode(v string) *HttpEndpointDestinationConfiguration { + s.S3BackupMode = &v + return s +} + +// SetS3Configuration sets the S3Configuration field's value. +func (s *HttpEndpointDestinationConfiguration) SetS3Configuration(v *S3DestinationConfiguration) *HttpEndpointDestinationConfiguration { + s.S3Configuration = v + return s +} + +// Describes the HTTP endpoint destination. +type HttpEndpointDestinationDescription struct { + _ struct{} `type:"structure"` + + // Describes buffering options that can be applied to the data before it is + // delivered to the HTTPS endpoint destination. Kinesis Data Firehose teats + // these options as hints, and it might choose to use more optimal values. The + // SizeInMBs and IntervalInSeconds parameters are optional. However, if specify + // a value for one of them, you must also provide a value for the other. + BufferingHints *HttpEndpointBufferingHints `type:"structure"` + + // Describes the Amazon CloudWatch logging options for your delivery stream. + CloudWatchLoggingOptions *CloudWatchLoggingOptions `type:"structure"` + + // The configuration of the specified HTTP endpoint destination. + EndpointConfiguration *HttpEndpointDescription `type:"structure"` + + // Describes a data processing configuration. + ProcessingConfiguration *ProcessingConfiguration `type:"structure"` + + // The configuration of request sent to the HTTP endpoint specified as the destination. + RequestConfiguration *HttpEndpointRequestConfiguration `type:"structure"` + + // Describes the retry behavior in case Kinesis Data Firehose is unable to deliver + // data to the specified HTTP endpoint destination, or if it doesn't receive + // a valid acknowledgment of receipt from the specified HTTP endpoint destination. + RetryOptions *HttpEndpointRetryOptions `type:"structure"` + + // Kinesis Data Firehose uses this IAM role for all the permissions that the + // delivery stream needs. + RoleARN *string `min:"1" type:"string"` + + // Describes the S3 bucket backup options for the data that Kinesis Firehose + // delivers to the HTTP endpoint destination. You can back up all documents + // (AllData) or only the documents that Kinesis Data Firehose could not deliver + // to the specified HTTP endpoint destination (FailedDataOnly). + S3BackupMode *string `type:"string" enum:"HttpEndpointS3BackupMode"` + + // Describes a destination in Amazon S3. + S3DestinationDescription *S3DestinationDescription `type:"structure"` +} + +// String returns the string representation +func (s HttpEndpointDestinationDescription) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s HttpEndpointDestinationDescription) GoString() string { + return s.String() +} + +// SetBufferingHints sets the BufferingHints field's value. +func (s *HttpEndpointDestinationDescription) SetBufferingHints(v *HttpEndpointBufferingHints) *HttpEndpointDestinationDescription { + s.BufferingHints = v + return s +} + +// SetCloudWatchLoggingOptions sets the CloudWatchLoggingOptions field's value. +func (s *HttpEndpointDestinationDescription) SetCloudWatchLoggingOptions(v *CloudWatchLoggingOptions) *HttpEndpointDestinationDescription { + s.CloudWatchLoggingOptions = v + return s +} + +// SetEndpointConfiguration sets the EndpointConfiguration field's value. +func (s *HttpEndpointDestinationDescription) SetEndpointConfiguration(v *HttpEndpointDescription) *HttpEndpointDestinationDescription { + s.EndpointConfiguration = v + return s +} + +// SetProcessingConfiguration sets the ProcessingConfiguration field's value. +func (s *HttpEndpointDestinationDescription) SetProcessingConfiguration(v *ProcessingConfiguration) *HttpEndpointDestinationDescription { + s.ProcessingConfiguration = v + return s +} + +// SetRequestConfiguration sets the RequestConfiguration field's value. +func (s *HttpEndpointDestinationDescription) SetRequestConfiguration(v *HttpEndpointRequestConfiguration) *HttpEndpointDestinationDescription { + s.RequestConfiguration = v + return s +} + +// SetRetryOptions sets the RetryOptions field's value. +func (s *HttpEndpointDestinationDescription) SetRetryOptions(v *HttpEndpointRetryOptions) *HttpEndpointDestinationDescription { + s.RetryOptions = v + return s +} + +// SetRoleARN sets the RoleARN field's value. +func (s *HttpEndpointDestinationDescription) SetRoleARN(v string) *HttpEndpointDestinationDescription { + s.RoleARN = &v + return s +} + +// SetS3BackupMode sets the S3BackupMode field's value. +func (s *HttpEndpointDestinationDescription) SetS3BackupMode(v string) *HttpEndpointDestinationDescription { + s.S3BackupMode = &v + return s +} + +// SetS3DestinationDescription sets the S3DestinationDescription field's value. +func (s *HttpEndpointDestinationDescription) SetS3DestinationDescription(v *S3DestinationDescription) *HttpEndpointDestinationDescription { + s.S3DestinationDescription = v + return s +} + +// Updates the specified HTTP endpoint destination. +type HttpEndpointDestinationUpdate struct { + _ struct{} `type:"structure"` - // A prefix that Kinesis Data Firehose evaluates and adds to failed records - // before writing them to S3. This prefix appears immediately following the - // bucket name. For information about how to specify this prefix, see Custom - // Prefixes for Amazon S3 Objects (https://docs.aws.amazon.com/firehose/latest/dev/s3-prefixes.html). - ErrorOutputPrefix *string `type:"string"` + // Describes buffering options that can be applied to the data before it is + // delivered to the HTTPS endpoint destination. Kinesis Data Firehose teats + // these options as hints, and it might choose to use more optimal values. The + // SizeInMBs and IntervalInSeconds parameters are optional. However, if specify + // a value for one of them, you must also provide a value for the other. + BufferingHints *HttpEndpointBufferingHints `type:"structure"` - // The "YYYY/MM/DD/HH" time format prefix is automatically used for delivered - // Amazon S3 files. You can also specify a custom prefix, as described in Custom - // Prefixes for Amazon S3 Objects (https://docs.aws.amazon.com/firehose/latest/dev/s3-prefixes.html). - Prefix *string `type:"string"` + // Describes the Amazon CloudWatch logging options for your delivery stream. + CloudWatchLoggingOptions *CloudWatchLoggingOptions `type:"structure"` - // The data processing configuration. + // Describes the configuration of the HTTP endpoint destination. + EndpointConfiguration *HttpEndpointConfiguration `type:"structure"` + + // Describes a data processing configuration. ProcessingConfiguration *ProcessingConfiguration `type:"structure"` - // The Amazon Resource Name (ARN) of the AWS credentials. For more information, - // see Amazon Resource Names (ARNs) and AWS Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). + // The configuration of the request sent to the HTTP endpoint specified as the + // destination. + RequestConfiguration *HttpEndpointRequestConfiguration `type:"structure"` + + // Describes the retry behavior in case Kinesis Data Firehose is unable to deliver + // data to the specified HTTP endpoint destination, or if it doesn't receive + // a valid acknowledgment of receipt from the specified HTTP endpoint destination. + RetryOptions *HttpEndpointRetryOptions `type:"structure"` + + // Kinesis Data Firehose uses this IAM role for all the permissions that the + // delivery stream needs. RoleARN *string `min:"1" type:"string"` - // Enables or disables Amazon S3 backup mode. - S3BackupMode *string `type:"string" enum:"S3BackupMode"` + // Describes the S3 bucket backup options for the data that Kinesis Firehose + // delivers to the HTTP endpoint destination. You can back up all documents + // (AllData) or only the documents that Kinesis Data Firehose could not deliver + // to the specified HTTP endpoint destination (FailedDataOnly). + S3BackupMode *string `type:"string" enum:"HttpEndpointS3BackupMode"` - // The Amazon S3 destination for backup. - S3BackupUpdate *S3DestinationUpdate `type:"structure"` + // Describes an update for a destination in Amazon S3. + S3Update *S3DestinationUpdate `type:"structure"` } // String returns the string representation -func (s ExtendedS3DestinationUpdate) String() string { +func (s HttpEndpointDestinationUpdate) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ExtendedS3DestinationUpdate) GoString() string { +func (s HttpEndpointDestinationUpdate) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ExtendedS3DestinationUpdate) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ExtendedS3DestinationUpdate"} - if s.BucketARN != nil && len(*s.BucketARN) < 1 { - invalidParams.Add(request.NewErrParamMinLen("BucketARN", 1)) - } +func (s *HttpEndpointDestinationUpdate) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpEndpointDestinationUpdate"} if s.RoleARN != nil && len(*s.RoleARN) < 1 { invalidParams.Add(request.NewErrParamMinLen("RoleARN", 1)) } @@ -3536,14 +4272,9 @@ func (s *ExtendedS3DestinationUpdate) Validate() error { invalidParams.AddNested("BufferingHints", err.(request.ErrInvalidParams)) } } - if s.DataFormatConversionConfiguration != nil { - if err := s.DataFormatConversionConfiguration.Validate(); err != nil { - invalidParams.AddNested("DataFormatConversionConfiguration", err.(request.ErrInvalidParams)) - } - } - if s.EncryptionConfiguration != nil { - if err := s.EncryptionConfiguration.Validate(); err != nil { - invalidParams.AddNested("EncryptionConfiguration", err.(request.ErrInvalidParams)) + if s.EndpointConfiguration != nil { + if err := s.EndpointConfiguration.Validate(); err != nil { + invalidParams.AddNested("EndpointConfiguration", err.(request.ErrInvalidParams)) } } if s.ProcessingConfiguration != nil { @@ -3551,9 +4282,14 @@ func (s *ExtendedS3DestinationUpdate) Validate() error { invalidParams.AddNested("ProcessingConfiguration", err.(request.ErrInvalidParams)) } } - if s.S3BackupUpdate != nil { - if err := s.S3BackupUpdate.Validate(); err != nil { - invalidParams.AddNested("S3BackupUpdate", err.(request.ErrInvalidParams)) + if s.RequestConfiguration != nil { + if err := s.RequestConfiguration.Validate(); err != nil { + invalidParams.AddNested("RequestConfiguration", err.(request.ErrInvalidParams)) + } + } + if s.S3Update != nil { + if err := s.S3Update.Validate(); err != nil { + invalidParams.AddNested("S3Update", err.(request.ErrInvalidParams)) } } @@ -3563,148 +4299,143 @@ func (s *ExtendedS3DestinationUpdate) Validate() error { return nil } -// SetBucketARN sets the BucketARN field's value. -func (s *ExtendedS3DestinationUpdate) SetBucketARN(v string) *ExtendedS3DestinationUpdate { - s.BucketARN = &v - return s -} - // SetBufferingHints sets the BufferingHints field's value. -func (s *ExtendedS3DestinationUpdate) SetBufferingHints(v *BufferingHints) *ExtendedS3DestinationUpdate { +func (s *HttpEndpointDestinationUpdate) SetBufferingHints(v *HttpEndpointBufferingHints) *HttpEndpointDestinationUpdate { s.BufferingHints = v return s } // SetCloudWatchLoggingOptions sets the CloudWatchLoggingOptions field's value. -func (s *ExtendedS3DestinationUpdate) SetCloudWatchLoggingOptions(v *CloudWatchLoggingOptions) *ExtendedS3DestinationUpdate { +func (s *HttpEndpointDestinationUpdate) SetCloudWatchLoggingOptions(v *CloudWatchLoggingOptions) *HttpEndpointDestinationUpdate { s.CloudWatchLoggingOptions = v return s } -// SetCompressionFormat sets the CompressionFormat field's value. -func (s *ExtendedS3DestinationUpdate) SetCompressionFormat(v string) *ExtendedS3DestinationUpdate { - s.CompressionFormat = &v - return s -} - -// SetDataFormatConversionConfiguration sets the DataFormatConversionConfiguration field's value. -func (s *ExtendedS3DestinationUpdate) SetDataFormatConversionConfiguration(v *DataFormatConversionConfiguration) *ExtendedS3DestinationUpdate { - s.DataFormatConversionConfiguration = v - return s -} - -// SetEncryptionConfiguration sets the EncryptionConfiguration field's value. -func (s *ExtendedS3DestinationUpdate) SetEncryptionConfiguration(v *EncryptionConfiguration) *ExtendedS3DestinationUpdate { - s.EncryptionConfiguration = v +// SetEndpointConfiguration sets the EndpointConfiguration field's value. +func (s *HttpEndpointDestinationUpdate) SetEndpointConfiguration(v *HttpEndpointConfiguration) *HttpEndpointDestinationUpdate { + s.EndpointConfiguration = v return s } -// SetErrorOutputPrefix sets the ErrorOutputPrefix field's value. -func (s *ExtendedS3DestinationUpdate) SetErrorOutputPrefix(v string) *ExtendedS3DestinationUpdate { - s.ErrorOutputPrefix = &v +// SetProcessingConfiguration sets the ProcessingConfiguration field's value. +func (s *HttpEndpointDestinationUpdate) SetProcessingConfiguration(v *ProcessingConfiguration) *HttpEndpointDestinationUpdate { + s.ProcessingConfiguration = v return s } -// SetPrefix sets the Prefix field's value. -func (s *ExtendedS3DestinationUpdate) SetPrefix(v string) *ExtendedS3DestinationUpdate { - s.Prefix = &v +// SetRequestConfiguration sets the RequestConfiguration field's value. +func (s *HttpEndpointDestinationUpdate) SetRequestConfiguration(v *HttpEndpointRequestConfiguration) *HttpEndpointDestinationUpdate { + s.RequestConfiguration = v return s } -// SetProcessingConfiguration sets the ProcessingConfiguration field's value. -func (s *ExtendedS3DestinationUpdate) SetProcessingConfiguration(v *ProcessingConfiguration) *ExtendedS3DestinationUpdate { - s.ProcessingConfiguration = v +// SetRetryOptions sets the RetryOptions field's value. +func (s *HttpEndpointDestinationUpdate) SetRetryOptions(v *HttpEndpointRetryOptions) *HttpEndpointDestinationUpdate { + s.RetryOptions = v return s } // SetRoleARN sets the RoleARN field's value. -func (s *ExtendedS3DestinationUpdate) SetRoleARN(v string) *ExtendedS3DestinationUpdate { +func (s *HttpEndpointDestinationUpdate) SetRoleARN(v string) *HttpEndpointDestinationUpdate { s.RoleARN = &v return s } // SetS3BackupMode sets the S3BackupMode field's value. -func (s *ExtendedS3DestinationUpdate) SetS3BackupMode(v string) *ExtendedS3DestinationUpdate { +func (s *HttpEndpointDestinationUpdate) SetS3BackupMode(v string) *HttpEndpointDestinationUpdate { s.S3BackupMode = &v return s } -// SetS3BackupUpdate sets the S3BackupUpdate field's value. -func (s *ExtendedS3DestinationUpdate) SetS3BackupUpdate(v *S3DestinationUpdate) *ExtendedS3DestinationUpdate { - s.S3BackupUpdate = v +// SetS3Update sets the S3Update field's value. +func (s *HttpEndpointDestinationUpdate) SetS3Update(v *S3DestinationUpdate) *HttpEndpointDestinationUpdate { + s.S3Update = v return s } -// Provides details in case one of the following operations fails due to an -// error related to KMS: CreateDeliveryStream, DeleteDeliveryStream, StartDeliveryStreamEncryption, -// StopDeliveryStreamEncryption. -type FailureDescription struct { +// The configuration of the HTTP endpoint request. +type HttpEndpointRequestConfiguration struct { _ struct{} `type:"structure"` - // A message providing details about the error that caused the failure. - // - // Details is a required field - Details *string `min:"1" type:"string" required:"true"` + // Describes the metadata sent to the HTTP endpoint destination. + CommonAttributes []*HttpEndpointCommonAttribute `type:"list"` - // The type of error that caused the failure. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"DeliveryStreamFailureType"` + // Kinesis Data Firehose uses the content encoding to compress the body of a + // request before sending the request to the destination. For more information, + // see Content-Encoding (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding) + // in MDN Web Docs, the official Mozilla documentation. + ContentEncoding *string `type:"string" enum:"ContentEncoding"` } // String returns the string representation -func (s FailureDescription) String() string { +func (s HttpEndpointRequestConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FailureDescription) GoString() string { +func (s HttpEndpointRequestConfiguration) GoString() string { return s.String() } -// SetDetails sets the Details field's value. -func (s *FailureDescription) SetDetails(v string) *FailureDescription { - s.Details = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *HttpEndpointRequestConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "HttpEndpointRequestConfiguration"} + if s.CommonAttributes != nil { + for i, v := range s.CommonAttributes { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "CommonAttributes", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCommonAttributes sets the CommonAttributes field's value. +func (s *HttpEndpointRequestConfiguration) SetCommonAttributes(v []*HttpEndpointCommonAttribute) *HttpEndpointRequestConfiguration { + s.CommonAttributes = v return s } -// SetType sets the Type field's value. -func (s *FailureDescription) SetType(v string) *FailureDescription { - s.Type = &v +// SetContentEncoding sets the ContentEncoding field's value. +func (s *HttpEndpointRequestConfiguration) SetContentEncoding(v string) *HttpEndpointRequestConfiguration { + s.ContentEncoding = &v return s } -// The native Hive / HCatalog JsonSerDe. Used by Kinesis Data Firehose for deserializing -// data, which means converting it from the JSON format in preparation for serializing -// it to the Parquet or ORC format. This is one of two deserializers you can -// choose, depending on which one offers the functionality you need. The other -// option is the OpenX SerDe. -type HiveJsonSerDe struct { +// Describes the retry behavior in case Kinesis Data Firehose is unable to deliver +// data to the specified HTTP endpoint destination, or if it doesn't receive +// a valid acknowledgment of receipt from the specified HTTP endpoint destination. +type HttpEndpointRetryOptions struct { _ struct{} `type:"structure"` - // Indicates how you want Kinesis Data Firehose to parse the date and timestamps - // that may be present in your input data JSON. To specify these format strings, - // follow the pattern syntax of JodaTime's DateTimeFormat format strings. For - // more information, see Class DateTimeFormat (https://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html). - // You can also use the special value millis to parse timestamps in epoch milliseconds. - // If you don't specify a format, Kinesis Data Firehose uses java.sql.Timestamp::valueOf - // by default. - TimestampFormats []*string `type:"list"` + // The total amount of time that Kinesis Data Firehose spends on retries. This + // duration starts after the initial attempt to send data to the custom destination + // via HTTPS endpoint fails. It doesn't include the periods during which Kinesis + // Data Firehose waits for acknowledgment from the specified destination after + // each attempt. + DurationInSeconds *int64 `type:"integer"` } // String returns the string representation -func (s HiveJsonSerDe) String() string { +func (s HttpEndpointRetryOptions) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s HiveJsonSerDe) GoString() string { +func (s HttpEndpointRetryOptions) GoString() string { return s.String() } -// SetTimestampFormats sets the TimestampFormats field's value. -func (s *HiveJsonSerDe) SetTimestampFormats(v []*string) *HiveJsonSerDe { - s.TimestampFormats = v +// SetDurationInSeconds sets the DurationInSeconds field's value. +func (s *HttpEndpointRetryOptions) SetDurationInSeconds(v int64) *HttpEndpointRetryOptions { + s.DurationInSeconds = &v return s } @@ -5120,7 +5851,9 @@ type RedshiftDestinationConfiguration struct { // The configuration for backup in Amazon S3. S3BackupConfiguration *S3DestinationConfiguration `type:"structure"` - // The Amazon S3 backup mode. + // The Amazon S3 backup mode. After you create a delivery stream, you can update + // it to enable Amazon S3 backup if it is disabled. If backup is enabled, you + // can't update the delivery stream to disable it. S3BackupMode *string `type:"string" enum:"RedshiftS3BackupMode"` // The configuration for the intermediate Amazon S3 location from which Amazon @@ -5419,7 +6152,8 @@ type RedshiftDestinationUpdate struct { // see Amazon Resource Names (ARNs) and AWS Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). RoleARN *string `min:"1" type:"string"` - // The Amazon S3 backup mode. + // You can update a delivery stream to enable Amazon S3 backup if it is disabled. + // If backup is enabled, you can't update the delivery stream to disable it. S3BackupMode *string `type:"string" enum:"RedshiftS3BackupMode"` // The Amazon S3 destination for backup. @@ -6352,11 +7086,14 @@ type SplunkDestinationConfiguration struct { // to Splunk, or if it doesn't receive an acknowledgment of receipt from Splunk. RetryOptions *SplunkRetryOptions `type:"structure"` - // Defines how documents should be delivered to Amazon S3. When set to FailedDocumentsOnly, + // Defines how documents should be delivered to Amazon S3. When set to FailedEventsOnly, // Kinesis Data Firehose writes any data that could not be indexed to the configured - // Amazon S3 destination. When set to AllDocuments, Kinesis Data Firehose delivers + // Amazon S3 destination. When set to AllEvents, Kinesis Data Firehose delivers // all incoming records to Amazon S3, and also writes failed documents to Amazon - // S3. Default value is FailedDocumentsOnly. + // S3. The default value is FailedEventsOnly. + // + // You can update this backup mode from FailedEventsOnly to AllEvents. You can't + // update it from AllEvents to FailedEventsOnly. S3BackupMode *string `type:"string" enum:"SplunkS3BackupMode"` // The configuration for the backup Amazon S3 location. @@ -6600,11 +7337,14 @@ type SplunkDestinationUpdate struct { // to Splunk or if it doesn't receive an acknowledgment of receipt from Splunk. RetryOptions *SplunkRetryOptions `type:"structure"` - // Defines how documents should be delivered to Amazon S3. When set to FailedDocumentsOnly, - // Kinesis Data Firehose writes any data that could not be indexed to the configured - // Amazon S3 destination. When set to AllDocuments, Kinesis Data Firehose delivers - // all incoming records to Amazon S3, and also writes failed documents to Amazon - // S3. Default value is FailedDocumentsOnly. + // Specifies how you want Kinesis Data Firehose to back up documents to Amazon + // S3. When set to FailedDocumentsOnly, Kinesis Data Firehose writes any data + // that could not be indexed to the configured Amazon S3 destination. When set + // to AllEvents, Kinesis Data Firehose delivers all incoming records to Amazon + // S3, and also writes failed documents to Amazon S3. The default value is FailedEventsOnly. + // + // You can update this backup mode from FailedEventsOnly to AllEvents. You can't + // update it from AllEvents to FailedEventsOnly. S3BackupMode *string `type:"string" enum:"SplunkS3BackupMode"` // Your update to the configuration of the backup Amazon S3 location. @@ -7091,6 +7831,9 @@ type UpdateDestinationInput struct { // Describes an update for a destination in Amazon S3. ExtendedS3DestinationUpdate *ExtendedS3DestinationUpdate `type:"structure"` + // Describes an update to the specified HTTP endpoint destination. + HttpEndpointDestinationUpdate *HttpEndpointDestinationUpdate `type:"structure"` + // Describes an update for a destination in Amazon Redshift. RedshiftDestinationUpdate *RedshiftDestinationUpdate `type:"structure"` @@ -7144,6 +7887,11 @@ func (s *UpdateDestinationInput) Validate() error { invalidParams.AddNested("ExtendedS3DestinationUpdate", err.(request.ErrInvalidParams)) } } + if s.HttpEndpointDestinationUpdate != nil { + if err := s.HttpEndpointDestinationUpdate.Validate(); err != nil { + invalidParams.AddNested("HttpEndpointDestinationUpdate", err.(request.ErrInvalidParams)) + } + } if s.RedshiftDestinationUpdate != nil { if err := s.RedshiftDestinationUpdate.Validate(); err != nil { invalidParams.AddNested("RedshiftDestinationUpdate", err.(request.ErrInvalidParams)) @@ -7196,6 +7944,12 @@ func (s *UpdateDestinationInput) SetExtendedS3DestinationUpdate(v *ExtendedS3Des return s } +// SetHttpEndpointDestinationUpdate sets the HttpEndpointDestinationUpdate field's value. +func (s *UpdateDestinationInput) SetHttpEndpointDestinationUpdate(v *HttpEndpointDestinationUpdate) *UpdateDestinationInput { + s.HttpEndpointDestinationUpdate = v + return s +} + // SetRedshiftDestinationUpdate sets the RedshiftDestinationUpdate field's value. func (s *UpdateDestinationInput) SetRedshiftDestinationUpdate(v *RedshiftDestinationUpdate) *UpdateDestinationInput { s.RedshiftDestinationUpdate = v @@ -7233,13 +7987,45 @@ type VpcConfiguration struct { _ struct{} `type:"structure"` // The ARN of the IAM role that you want the delivery stream to use to create - // endpoints in the destination VPC. + // endpoints in the destination VPC. You can use your existing Kinesis Data + // Firehose delivery role or you can specify a new role. In either case, make + // sure that the role trusts the Kinesis Data Firehose service principal and + // that it grants the following permissions: + // + // * ec2:DescribeVpcs + // + // * ec2:DescribeVpcAttribute + // + // * ec2:DescribeSubnets + // + // * ec2:DescribeSecurityGroups + // + // * ec2:DescribeNetworkInterfaces + // + // * ec2:CreateNetworkInterface + // + // * ec2:CreateNetworkInterfacePermission + // + // * ec2:DeleteNetworkInterface + // + // If you revoke these permissions after you create the delivery stream, Kinesis + // Data Firehose can't scale out by creating more ENIs when necessary. You might + // therefore see a degradation in performance. // // RoleARN is a required field RoleARN *string `min:"1" type:"string" required:"true"` // The IDs of the security groups that you want Kinesis Data Firehose to use - // when it creates ENIs in the VPC of the Amazon ES destination. + // when it creates ENIs in the VPC of the Amazon ES destination. You can use + // the same security group that the Amazon ES domain uses or different ones. + // If you specify different security groups here, ensure that they allow outbound + // HTTPS traffic to the Amazon ES domain's security group. Also ensure that + // the Amazon ES domain's security group allows HTTPS traffic from the security + // groups specified here. If you use the same security group for both your delivery + // stream and the Amazon ES domain, make sure the security group inbound rule + // allows HTTPS traffic. For more information about security group rules, see + // Security group rules (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#SecurityGroupRules) + // in the Amazon VPC documentation. // // SecurityGroupIds is a required field SecurityGroupIds []*string `min:"1" type:"list" required:"true"` @@ -7324,14 +8110,46 @@ func (s *VpcConfiguration) SetSubnetIds(v []*string) *VpcConfiguration { type VpcConfigurationDescription struct { _ struct{} `type:"structure"` - // The ARN of the IAM role that you want the delivery stream uses to create - // endpoints in the destination VPC. + // The ARN of the IAM role that the delivery stream uses to create endpoints + // in the destination VPC. You can use your existing Kinesis Data Firehose delivery + // role or you can specify a new role. In either case, make sure that the role + // trusts the Kinesis Data Firehose service principal and that it grants the + // following permissions: + // + // * ec2:DescribeVpcs + // + // * ec2:DescribeVpcAttribute + // + // * ec2:DescribeSubnets + // + // * ec2:DescribeSecurityGroups + // + // * ec2:DescribeNetworkInterfaces + // + // * ec2:CreateNetworkInterface + // + // * ec2:CreateNetworkInterfacePermission + // + // * ec2:DeleteNetworkInterface + // + // If you revoke these permissions after you create the delivery stream, Kinesis + // Data Firehose can't scale out by creating more ENIs when necessary. You might + // therefore see a degradation in performance. // // RoleARN is a required field RoleARN *string `min:"1" type:"string" required:"true"` // The IDs of the security groups that Kinesis Data Firehose uses when it creates - // ENIs in the VPC of the Amazon ES destination. + // ENIs in the VPC of the Amazon ES destination. You can use the same security + // group that the Amazon ES domain uses or different ones. If you specify different + // security groups, ensure that they allow outbound HTTPS traffic to the Amazon + // ES domain's security group. Also ensure that the Amazon ES domain's security + // group allows HTTPS traffic from the security groups specified here. If you + // use the same security group for both your delivery stream and the Amazon + // ES domain, make sure the security group inbound rule allows HTTPS traffic. + // For more information about security group rules, see Security group rules + // (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#SecurityGroupRules) + // in the Amazon VPC documentation. // // SecurityGroupIds is a required field SecurityGroupIds []*string `min:"1" type:"list" required:"true"` @@ -7412,6 +8230,33 @@ const ( CompressionFormatHadoopSnappy = "HADOOP_SNAPPY" ) +// CompressionFormat_Values returns all elements of the CompressionFormat enum +func CompressionFormat_Values() []string { + return []string{ + CompressionFormatUncompressed, + CompressionFormatGzip, + CompressionFormatZip, + CompressionFormatSnappy, + CompressionFormatHadoopSnappy, + } +} + +const ( + // ContentEncodingNone is a ContentEncoding enum value + ContentEncodingNone = "NONE" + + // ContentEncodingGzip is a ContentEncoding enum value + ContentEncodingGzip = "GZIP" +) + +// ContentEncoding_Values returns all elements of the ContentEncoding enum +func ContentEncoding_Values() []string { + return []string{ + ContentEncodingNone, + ContentEncodingGzip, + } +} + const ( // DeliveryStreamEncryptionStatusEnabled is a DeliveryStreamEncryptionStatus enum value DeliveryStreamEncryptionStatusEnabled = "ENABLED" @@ -7432,6 +8277,18 @@ const ( DeliveryStreamEncryptionStatusDisablingFailed = "DISABLING_FAILED" ) +// DeliveryStreamEncryptionStatus_Values returns all elements of the DeliveryStreamEncryptionStatus enum +func DeliveryStreamEncryptionStatus_Values() []string { + return []string{ + DeliveryStreamEncryptionStatusEnabled, + DeliveryStreamEncryptionStatusEnabling, + DeliveryStreamEncryptionStatusEnablingFailed, + DeliveryStreamEncryptionStatusDisabled, + DeliveryStreamEncryptionStatusDisabling, + DeliveryStreamEncryptionStatusDisablingFailed, + } +} + const ( // DeliveryStreamFailureTypeRetireKmsGrantFailed is a DeliveryStreamFailureType enum value DeliveryStreamFailureTypeRetireKmsGrantFailed = "RETIRE_KMS_GRANT_FAILED" @@ -7479,6 +8336,27 @@ const ( DeliveryStreamFailureTypeUnknownError = "UNKNOWN_ERROR" ) +// DeliveryStreamFailureType_Values returns all elements of the DeliveryStreamFailureType enum +func DeliveryStreamFailureType_Values() []string { + return []string{ + DeliveryStreamFailureTypeRetireKmsGrantFailed, + DeliveryStreamFailureTypeCreateKmsGrantFailed, + DeliveryStreamFailureTypeKmsAccessDenied, + DeliveryStreamFailureTypeDisabledKmsKey, + DeliveryStreamFailureTypeInvalidKmsKey, + DeliveryStreamFailureTypeKmsKeyNotFound, + DeliveryStreamFailureTypeKmsOptInRequired, + DeliveryStreamFailureTypeCreateEniFailed, + DeliveryStreamFailureTypeDeleteEniFailed, + DeliveryStreamFailureTypeSubnetNotFound, + DeliveryStreamFailureTypeSecurityGroupNotFound, + DeliveryStreamFailureTypeEniAccessDenied, + DeliveryStreamFailureTypeSubnetAccessDenied, + DeliveryStreamFailureTypeSecurityGroupAccessDenied, + DeliveryStreamFailureTypeUnknownError, + } +} + const ( // DeliveryStreamStatusCreating is a DeliveryStreamStatus enum value DeliveryStreamStatusCreating = "CREATING" @@ -7496,6 +8374,17 @@ const ( DeliveryStreamStatusActive = "ACTIVE" ) +// DeliveryStreamStatus_Values returns all elements of the DeliveryStreamStatus enum +func DeliveryStreamStatus_Values() []string { + return []string{ + DeliveryStreamStatusCreating, + DeliveryStreamStatusCreatingFailed, + DeliveryStreamStatusDeleting, + DeliveryStreamStatusDeletingFailed, + DeliveryStreamStatusActive, + } +} + const ( // DeliveryStreamTypeDirectPut is a DeliveryStreamType enum value DeliveryStreamTypeDirectPut = "DirectPut" @@ -7504,6 +8393,14 @@ const ( DeliveryStreamTypeKinesisStreamAsSource = "KinesisStreamAsSource" ) +// DeliveryStreamType_Values returns all elements of the DeliveryStreamType enum +func DeliveryStreamType_Values() []string { + return []string{ + DeliveryStreamTypeDirectPut, + DeliveryStreamTypeKinesisStreamAsSource, + } +} + const ( // ElasticsearchIndexRotationPeriodNoRotation is a ElasticsearchIndexRotationPeriod enum value ElasticsearchIndexRotationPeriodNoRotation = "NoRotation" @@ -7521,6 +8418,17 @@ const ( ElasticsearchIndexRotationPeriodOneMonth = "OneMonth" ) +// ElasticsearchIndexRotationPeriod_Values returns all elements of the ElasticsearchIndexRotationPeriod enum +func ElasticsearchIndexRotationPeriod_Values() []string { + return []string{ + ElasticsearchIndexRotationPeriodNoRotation, + ElasticsearchIndexRotationPeriodOneHour, + ElasticsearchIndexRotationPeriodOneDay, + ElasticsearchIndexRotationPeriodOneWeek, + ElasticsearchIndexRotationPeriodOneMonth, + } +} + const ( // ElasticsearchS3BackupModeFailedDocumentsOnly is a ElasticsearchS3BackupMode enum value ElasticsearchS3BackupModeFailedDocumentsOnly = "FailedDocumentsOnly" @@ -7529,6 +8437,14 @@ const ( ElasticsearchS3BackupModeAllDocuments = "AllDocuments" ) +// ElasticsearchS3BackupMode_Values returns all elements of the ElasticsearchS3BackupMode enum +func ElasticsearchS3BackupMode_Values() []string { + return []string{ + ElasticsearchS3BackupModeFailedDocumentsOnly, + ElasticsearchS3BackupModeAllDocuments, + } +} + const ( // HECEndpointTypeRaw is a HECEndpointType enum value HECEndpointTypeRaw = "Raw" @@ -7537,6 +8453,30 @@ const ( HECEndpointTypeEvent = "Event" ) +// HECEndpointType_Values returns all elements of the HECEndpointType enum +func HECEndpointType_Values() []string { + return []string{ + HECEndpointTypeRaw, + HECEndpointTypeEvent, + } +} + +const ( + // HttpEndpointS3BackupModeFailedDataOnly is a HttpEndpointS3BackupMode enum value + HttpEndpointS3BackupModeFailedDataOnly = "FailedDataOnly" + + // HttpEndpointS3BackupModeAllData is a HttpEndpointS3BackupMode enum value + HttpEndpointS3BackupModeAllData = "AllData" +) + +// HttpEndpointS3BackupMode_Values returns all elements of the HttpEndpointS3BackupMode enum +func HttpEndpointS3BackupMode_Values() []string { + return []string{ + HttpEndpointS3BackupModeFailedDataOnly, + HttpEndpointS3BackupModeAllData, + } +} + const ( // KeyTypeAwsOwnedCmk is a KeyType enum value KeyTypeAwsOwnedCmk = "AWS_OWNED_CMK" @@ -7545,11 +8485,26 @@ const ( KeyTypeCustomerManagedCmk = "CUSTOMER_MANAGED_CMK" ) +// KeyType_Values returns all elements of the KeyType enum +func KeyType_Values() []string { + return []string{ + KeyTypeAwsOwnedCmk, + KeyTypeCustomerManagedCmk, + } +} + const ( // NoEncryptionConfigNoEncryption is a NoEncryptionConfig enum value NoEncryptionConfigNoEncryption = "NoEncryption" ) +// NoEncryptionConfig_Values returns all elements of the NoEncryptionConfig enum +func NoEncryptionConfig_Values() []string { + return []string{ + NoEncryptionConfigNoEncryption, + } +} + const ( // OrcCompressionNone is a OrcCompression enum value OrcCompressionNone = "NONE" @@ -7561,6 +8516,15 @@ const ( OrcCompressionSnappy = "SNAPPY" ) +// OrcCompression_Values returns all elements of the OrcCompression enum +func OrcCompression_Values() []string { + return []string{ + OrcCompressionNone, + OrcCompressionZlib, + OrcCompressionSnappy, + } +} + const ( // OrcFormatVersionV011 is a OrcFormatVersion enum value OrcFormatVersionV011 = "V0_11" @@ -7569,6 +8533,14 @@ const ( OrcFormatVersionV012 = "V0_12" ) +// OrcFormatVersion_Values returns all elements of the OrcFormatVersion enum +func OrcFormatVersion_Values() []string { + return []string{ + OrcFormatVersionV011, + OrcFormatVersionV012, + } +} + const ( // ParquetCompressionUncompressed is a ParquetCompression enum value ParquetCompressionUncompressed = "UNCOMPRESSED" @@ -7580,6 +8552,15 @@ const ( ParquetCompressionSnappy = "SNAPPY" ) +// ParquetCompression_Values returns all elements of the ParquetCompression enum +func ParquetCompression_Values() []string { + return []string{ + ParquetCompressionUncompressed, + ParquetCompressionGzip, + ParquetCompressionSnappy, + } +} + const ( // ParquetWriterVersionV1 is a ParquetWriterVersion enum value ParquetWriterVersionV1 = "V1" @@ -7588,6 +8569,14 @@ const ( ParquetWriterVersionV2 = "V2" ) +// ParquetWriterVersion_Values returns all elements of the ParquetWriterVersion enum +func ParquetWriterVersion_Values() []string { + return []string{ + ParquetWriterVersionV1, + ParquetWriterVersionV2, + } +} + const ( // ProcessorParameterNameLambdaArn is a ProcessorParameterName enum value ProcessorParameterNameLambdaArn = "LambdaArn" @@ -7605,11 +8594,29 @@ const ( ProcessorParameterNameBufferIntervalInSeconds = "BufferIntervalInSeconds" ) +// ProcessorParameterName_Values returns all elements of the ProcessorParameterName enum +func ProcessorParameterName_Values() []string { + return []string{ + ProcessorParameterNameLambdaArn, + ProcessorParameterNameNumberOfRetries, + ProcessorParameterNameRoleArn, + ProcessorParameterNameBufferSizeInMbs, + ProcessorParameterNameBufferIntervalInSeconds, + } +} + const ( // ProcessorTypeLambda is a ProcessorType enum value ProcessorTypeLambda = "Lambda" ) +// ProcessorType_Values returns all elements of the ProcessorType enum +func ProcessorType_Values() []string { + return []string{ + ProcessorTypeLambda, + } +} + const ( // RedshiftS3BackupModeDisabled is a RedshiftS3BackupMode enum value RedshiftS3BackupModeDisabled = "Disabled" @@ -7618,6 +8625,14 @@ const ( RedshiftS3BackupModeEnabled = "Enabled" ) +// RedshiftS3BackupMode_Values returns all elements of the RedshiftS3BackupMode enum +func RedshiftS3BackupMode_Values() []string { + return []string{ + RedshiftS3BackupModeDisabled, + RedshiftS3BackupModeEnabled, + } +} + const ( // S3BackupModeDisabled is a S3BackupMode enum value S3BackupModeDisabled = "Disabled" @@ -7626,6 +8641,14 @@ const ( S3BackupModeEnabled = "Enabled" ) +// S3BackupMode_Values returns all elements of the S3BackupMode enum +func S3BackupMode_Values() []string { + return []string{ + S3BackupModeDisabled, + S3BackupModeEnabled, + } +} + const ( // SplunkS3BackupModeFailedEventsOnly is a SplunkS3BackupMode enum value SplunkS3BackupModeFailedEventsOnly = "FailedEventsOnly" @@ -7633,3 +8656,11 @@ const ( // SplunkS3BackupModeAllEvents is a SplunkS3BackupMode enum value SplunkS3BackupModeAllEvents = "AllEvents" ) + +// SplunkS3BackupMode_Values returns all elements of the SplunkS3BackupMode enum +func SplunkS3BackupMode_Values() []string { + return []string{ + SplunkS3BackupModeFailedEventsOnly, + SplunkS3BackupModeAllEvents, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/fms/api.go b/vendor/github.com/aws/aws-sdk-go/service/fms/api.go index 36baa3ac82a..7c40138631b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/fms/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/fms/api.go @@ -76,9 +76,12 @@ func (c *FMS) AssociateAdminAccountRequest(input *AssociateAdminAccountInput) (r // // Returned Error Types: // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * InvalidInputException // The parameters of the request were invalid. @@ -112,6 +115,98 @@ func (c *FMS) AssociateAdminAccountWithContext(ctx aws.Context, input *Associate return out, req.Send() } +const opDeleteAppsList = "DeleteAppsList" + +// DeleteAppsListRequest generates a "aws/request.Request" representing the +// client's request for the DeleteAppsList operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteAppsList for more information on using the DeleteAppsList +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteAppsListRequest method. +// req, resp := client.DeleteAppsListRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/DeleteAppsList +func (c *FMS) DeleteAppsListRequest(input *DeleteAppsListInput) (req *request.Request, output *DeleteAppsListOutput) { + op := &request.Operation{ + Name: opDeleteAppsList, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteAppsListInput{} + } + + output = &DeleteAppsListOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteAppsList API operation for Firewall Management Service. +// +// Permanently deletes an AWS Firewall Manager applications list. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Firewall Management Service's +// API operation DeleteAppsList for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The specified resource was not found. +// +// * InvalidOperationException +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. +// +// * InternalErrorException +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/DeleteAppsList +func (c *FMS) DeleteAppsList(input *DeleteAppsListInput) (*DeleteAppsListOutput, error) { + req, out := c.DeleteAppsListRequest(input) + return out, req.Send() +} + +// DeleteAppsListWithContext is the same as DeleteAppsList with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAppsList for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *FMS) DeleteAppsListWithContext(ctx aws.Context, input *DeleteAppsListInput, opts ...request.Option) (*DeleteAppsListOutput, error) { + req, out := c.DeleteAppsListRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteNotificationChannel = "DeleteNotificationChannel" // DeleteNotificationChannelRequest generates a "aws/request.Request" representing the @@ -173,9 +268,12 @@ func (c *FMS) DeleteNotificationChannelRequest(input *DeleteNotificationChannelI // The specified resource was not found. // // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * InternalErrorException // The operation failed because of a system problem, even though the request @@ -262,9 +360,12 @@ func (c *FMS) DeletePolicyRequest(input *DeletePolicyInput) (req *request.Reques // The specified resource was not found. // // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * InternalErrorException // The operation failed because of a system problem, even though the request @@ -292,6 +393,98 @@ func (c *FMS) DeletePolicyWithContext(ctx aws.Context, input *DeletePolicyInput, return out, req.Send() } +const opDeleteProtocolsList = "DeleteProtocolsList" + +// DeleteProtocolsListRequest generates a "aws/request.Request" representing the +// client's request for the DeleteProtocolsList operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteProtocolsList for more information on using the DeleteProtocolsList +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteProtocolsListRequest method. +// req, resp := client.DeleteProtocolsListRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/DeleteProtocolsList +func (c *FMS) DeleteProtocolsListRequest(input *DeleteProtocolsListInput) (req *request.Request, output *DeleteProtocolsListOutput) { + op := &request.Operation{ + Name: opDeleteProtocolsList, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteProtocolsListInput{} + } + + output = &DeleteProtocolsListOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteProtocolsList API operation for Firewall Management Service. +// +// Permanently deletes an AWS Firewall Manager protocols list. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Firewall Management Service's +// API operation DeleteProtocolsList for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The specified resource was not found. +// +// * InvalidOperationException +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. +// +// * InternalErrorException +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/DeleteProtocolsList +func (c *FMS) DeleteProtocolsList(input *DeleteProtocolsListInput) (*DeleteProtocolsListOutput, error) { + req, out := c.DeleteProtocolsListRequest(input) + return out, req.Send() +} + +// DeleteProtocolsListWithContext is the same as DeleteProtocolsList with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteProtocolsList for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *FMS) DeleteProtocolsListWithContext(ctx aws.Context, input *DeleteProtocolsListInput, opts ...request.Option) (*DeleteProtocolsListOutput, error) { + req, out := c.DeleteProtocolsListRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDisassociateAdminAccount = "DisassociateAdminAccount" // DisassociateAdminAccountRequest generates a "aws/request.Request" representing the @@ -350,9 +543,12 @@ func (c *FMS) DisassociateAdminAccountRequest(input *DisassociateAdminAccountInp // // Returned Error Types: // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * ResourceNotFoundException // The specified resource was not found. @@ -439,9 +635,12 @@ func (c *FMS) GetAdminAccountRequest(input *GetAdminAccountInput) (req *request. // // Returned Error Types: // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * ResourceNotFoundException // The specified resource was not found. @@ -472,6 +671,98 @@ func (c *FMS) GetAdminAccountWithContext(ctx aws.Context, input *GetAdminAccount return out, req.Send() } +const opGetAppsList = "GetAppsList" + +// GetAppsListRequest generates a "aws/request.Request" representing the +// client's request for the GetAppsList operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetAppsList for more information on using the GetAppsList +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetAppsListRequest method. +// req, resp := client.GetAppsListRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/GetAppsList +func (c *FMS) GetAppsListRequest(input *GetAppsListInput) (req *request.Request, output *GetAppsListOutput) { + op := &request.Operation{ + Name: opGetAppsList, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetAppsListInput{} + } + + output = &GetAppsListOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetAppsList API operation for Firewall Management Service. +// +// Returns information about the specified AWS Firewall Manager applications +// list. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Firewall Management Service's +// API operation GetAppsList for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The specified resource was not found. +// +// * InvalidOperationException +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. +// +// * InternalErrorException +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/GetAppsList +func (c *FMS) GetAppsList(input *GetAppsListInput) (*GetAppsListOutput, error) { + req, out := c.GetAppsListRequest(input) + return out, req.Send() +} + +// GetAppsListWithContext is the same as GetAppsList with the addition of +// the ability to pass a context and additional request options. +// +// See GetAppsList for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *FMS) GetAppsListWithContext(ctx aws.Context, input *GetAppsListInput, opts ...request.Option) (*GetAppsListOutput, error) { + req, out := c.GetAppsListRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetComplianceDetail = "GetComplianceDetail" // GetComplianceDetailRequest generates a "aws/request.Request" representing the @@ -539,6 +830,17 @@ func (c *FMS) GetComplianceDetailRequest(input *GetComplianceDetailInput) (req * // The operation failed because of a system problem, even though the request // was valid. Retry your request. // +// * InvalidInputException +// The parameters of the request were invalid. +// +// * InvalidOperationException +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/GetComplianceDetail func (c *FMS) GetComplianceDetail(input *GetComplianceDetailInput) (*GetComplianceDetailOutput, error) { req, out := c.GetComplianceDetailRequest(input) @@ -620,9 +922,12 @@ func (c *FMS) GetNotificationChannelRequest(input *GetNotificationChannelInput) // The specified resource was not found. // // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * InternalErrorException // The operation failed because of a system problem, even though the request @@ -708,9 +1013,12 @@ func (c *FMS) GetPolicyRequest(input *GetPolicyInput) (req *request.Request, out // The specified resource was not found. // // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * InternalErrorException // The operation failed because of a system problem, even though the request @@ -829,120 +1137,395 @@ func (c *FMS) GetProtectionStatusWithContext(ctx aws.Context, input *GetProtecti return out, req.Send() } -const opListComplianceStatus = "ListComplianceStatus" +const opGetProtocolsList = "GetProtocolsList" -// ListComplianceStatusRequest generates a "aws/request.Request" representing the -// client's request for the ListComplianceStatus operation. The "output" return +// GetProtocolsListRequest generates a "aws/request.Request" representing the +// client's request for the GetProtocolsList operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListComplianceStatus for more information on using the ListComplianceStatus +// See GetProtocolsList for more information on using the GetProtocolsList // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListComplianceStatusRequest method. -// req, resp := client.ListComplianceStatusRequest(params) +// // Example sending a request using the GetProtocolsListRequest method. +// req, resp := client.GetProtocolsListRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListComplianceStatus -func (c *FMS) ListComplianceStatusRequest(input *ListComplianceStatusInput) (req *request.Request, output *ListComplianceStatusOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/GetProtocolsList +func (c *FMS) GetProtocolsListRequest(input *GetProtocolsListInput) (req *request.Request, output *GetProtocolsListOutput) { op := &request.Operation{ - Name: opListComplianceStatus, + Name: opGetProtocolsList, HTTPMethod: "POST", HTTPPath: "/", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, - OutputTokens: []string{"NextToken"}, - LimitToken: "MaxResults", - TruncationToken: "", - }, } if input == nil { - input = &ListComplianceStatusInput{} + input = &GetProtocolsListInput{} } - output = &ListComplianceStatusOutput{} + output = &GetProtocolsListOutput{} req = c.newRequest(op, input, output) return } -// ListComplianceStatus API operation for Firewall Management Service. +// GetProtocolsList API operation for Firewall Management Service. // -// Returns an array of PolicyComplianceStatus objects in the response. Use PolicyComplianceStatus -// to get a summary of which member accounts are protected by the specified -// policy. +// Returns information about the specified AWS Firewall Manager protocols list. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Firewall Management Service's -// API operation ListComplianceStatus for usage and error information. +// API operation GetProtocolsList for usage and error information. // // Returned Error Types: // * ResourceNotFoundException // The specified resource was not found. // +// * InvalidOperationException +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. +// // * InternalErrorException // The operation failed because of a system problem, even though the request // was valid. Retry your request. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListComplianceStatus -func (c *FMS) ListComplianceStatus(input *ListComplianceStatusInput) (*ListComplianceStatusOutput, error) { - req, out := c.ListComplianceStatusRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/GetProtocolsList +func (c *FMS) GetProtocolsList(input *GetProtocolsListInput) (*GetProtocolsListOutput, error) { + req, out := c.GetProtocolsListRequest(input) return out, req.Send() } -// ListComplianceStatusWithContext is the same as ListComplianceStatus with the addition of +// GetProtocolsListWithContext is the same as GetProtocolsList with the addition of // the ability to pass a context and additional request options. // -// See ListComplianceStatus for details on how to use this API operation. +// See GetProtocolsList for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *FMS) ListComplianceStatusWithContext(ctx aws.Context, input *ListComplianceStatusInput, opts ...request.Option) (*ListComplianceStatusOutput, error) { - req, out := c.ListComplianceStatusRequest(input) +func (c *FMS) GetProtocolsListWithContext(ctx aws.Context, input *GetProtocolsListInput, opts ...request.Option) (*GetProtocolsListOutput, error) { + req, out := c.GetProtocolsListRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListComplianceStatusPages iterates over the pages of a ListComplianceStatus operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. +const opGetViolationDetails = "GetViolationDetails" + +// GetViolationDetailsRequest generates a "aws/request.Request" representing the +// client's request for the GetViolationDetails operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// See ListComplianceStatus method for more information on how to use this operation. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Note: This operation can generate multiple requests to a service. +// See GetViolationDetails for more information on using the GetViolationDetails +// API call, and error handling. // -// // Example iterating over at most 3 pages of a ListComplianceStatus operation. -// pageNum := 0 -// err := client.ListComplianceStatusPages(params, -// func(page *fms.ListComplianceStatusOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -func (c *FMS) ListComplianceStatusPages(input *ListComplianceStatusInput, fn func(*ListComplianceStatusOutput, bool) bool) error { - return c.ListComplianceStatusPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListComplianceStatusPagesWithContext same as ListComplianceStatusPages except -// it takes a Context and allows setting request options on the pages. +// +// // Example sending a request using the GetViolationDetailsRequest method. +// req, resp := client.GetViolationDetailsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/GetViolationDetails +func (c *FMS) GetViolationDetailsRequest(input *GetViolationDetailsInput) (req *request.Request, output *GetViolationDetailsOutput) { + op := &request.Operation{ + Name: opGetViolationDetails, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetViolationDetailsInput{} + } + + output = &GetViolationDetailsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetViolationDetails API operation for Firewall Management Service. +// +// Retrieves violations for a resource based on the specified AWS Firewall Manager +// policy and 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. +// +// See the AWS API reference guide for Firewall Management Service's +// API operation GetViolationDetails for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The specified resource was not found. +// +// * InvalidInputException +// The parameters of the request were invalid. +// +// * InternalErrorException +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/GetViolationDetails +func (c *FMS) GetViolationDetails(input *GetViolationDetailsInput) (*GetViolationDetailsOutput, error) { + req, out := c.GetViolationDetailsRequest(input) + return out, req.Send() +} + +// GetViolationDetailsWithContext is the same as GetViolationDetails with the addition of +// the ability to pass a context and additional request options. +// +// See GetViolationDetails for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *FMS) GetViolationDetailsWithContext(ctx aws.Context, input *GetViolationDetailsInput, opts ...request.Option) (*GetViolationDetailsOutput, error) { + req, out := c.GetViolationDetailsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListAppsLists = "ListAppsLists" + +// ListAppsListsRequest generates a "aws/request.Request" representing the +// client's request for the ListAppsLists operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListAppsLists for more information on using the ListAppsLists +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListAppsListsRequest method. +// req, resp := client.ListAppsListsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListAppsLists +func (c *FMS) ListAppsListsRequest(input *ListAppsListsInput) (req *request.Request, output *ListAppsListsOutput) { + op := &request.Operation{ + Name: opListAppsLists, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListAppsListsInput{} + } + + output = &ListAppsListsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListAppsLists API operation for Firewall Management Service. +// +// Returns an array of AppsListDataSummary 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 Firewall Management Service's +// API operation ListAppsLists for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The specified resource was not found. +// +// * InvalidOperationException +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. +// +// * LimitExceededException +// The operation exceeds a resource limit, for example, the maximum number of +// policy objects that you can create for an AWS account. For more information, +// see Firewall Manager Limits (https://docs.aws.amazon.com/waf/latest/developerguide/fms-limits.html) +// in the AWS WAF Developer Guide. +// +// * InternalErrorException +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListAppsLists +func (c *FMS) ListAppsLists(input *ListAppsListsInput) (*ListAppsListsOutput, error) { + req, out := c.ListAppsListsRequest(input) + return out, req.Send() +} + +// ListAppsListsWithContext is the same as ListAppsLists with the addition of +// the ability to pass a context and additional request options. +// +// See ListAppsLists for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *FMS) ListAppsListsWithContext(ctx aws.Context, input *ListAppsListsInput, opts ...request.Option) (*ListAppsListsOutput, error) { + req, out := c.ListAppsListsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListComplianceStatus = "ListComplianceStatus" + +// ListComplianceStatusRequest generates a "aws/request.Request" representing the +// client's request for the ListComplianceStatus operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListComplianceStatus for more information on using the ListComplianceStatus +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListComplianceStatusRequest method. +// req, resp := client.ListComplianceStatusRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListComplianceStatus +func (c *FMS) ListComplianceStatusRequest(input *ListComplianceStatusInput) (req *request.Request, output *ListComplianceStatusOutput) { + op := &request.Operation{ + Name: opListComplianceStatus, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListComplianceStatusInput{} + } + + output = &ListComplianceStatusOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListComplianceStatus API operation for Firewall Management Service. +// +// Returns an array of PolicyComplianceStatus objects. Use PolicyComplianceStatus +// to get a summary of which member accounts are protected by the specified +// 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. +// +// See the AWS API reference guide for Firewall Management Service's +// API operation ListComplianceStatus for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The specified resource was not found. +// +// * InternalErrorException +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListComplianceStatus +func (c *FMS) ListComplianceStatus(input *ListComplianceStatusInput) (*ListComplianceStatusOutput, error) { + req, out := c.ListComplianceStatusRequest(input) + return out, req.Send() +} + +// ListComplianceStatusWithContext is the same as ListComplianceStatus with the addition of +// the ability to pass a context and additional request options. +// +// See ListComplianceStatus for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *FMS) ListComplianceStatusWithContext(ctx aws.Context, input *ListComplianceStatusInput, opts ...request.Option) (*ListComplianceStatusOutput, error) { + req, out := c.ListComplianceStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListComplianceStatusPages iterates over the pages of a ListComplianceStatus operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListComplianceStatus 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 ListComplianceStatus operation. +// pageNum := 0 +// err := client.ListComplianceStatusPages(params, +// func(page *fms.ListComplianceStatusOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *FMS) ListComplianceStatusPages(input *ListComplianceStatusInput, fn func(*ListComplianceStatusOutput, bool) bool) error { + return c.ListComplianceStatusPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListComplianceStatusPagesWithContext same as ListComplianceStatusPages except +// it takes a Context and allows setting request options on the pages. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create @@ -1167,7 +1750,7 @@ func (c *FMS) ListPoliciesRequest(input *ListPoliciesInput) (req *request.Reques // ListPolicies API operation for Firewall Management Service. // -// Returns an array of PolicySummary objects in the response. +// Returns an array of PolicySummary 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 @@ -1181,9 +1764,12 @@ func (c *FMS) ListPoliciesRequest(input *ListPoliciesInput) (req *request.Reques // The specified resource was not found. // // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * LimitExceededException // The operation exceeds a resource limit, for example, the maximum number of @@ -1269,78 +1855,172 @@ func (c *FMS) ListPoliciesPagesWithContext(ctx aws.Context, input *ListPoliciesI return p.Err() } -const opListTagsForResource = "ListTagsForResource" +const opListProtocolsLists = "ListProtocolsLists" -// ListTagsForResourceRequest generates a "aws/request.Request" representing the -// client's request for the ListTagsForResource operation. The "output" return +// ListProtocolsListsRequest generates a "aws/request.Request" representing the +// client's request for the ListProtocolsLists operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListTagsForResource for more information on using the ListTagsForResource +// See ListProtocolsLists for more information on using the ListProtocolsLists // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListTagsForResourceRequest method. -// req, resp := client.ListTagsForResourceRequest(params) +// // Example sending a request using the ListProtocolsListsRequest method. +// req, resp := client.ListProtocolsListsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListTagsForResource -func (c *FMS) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListProtocolsLists +func (c *FMS) ListProtocolsListsRequest(input *ListProtocolsListsInput) (req *request.Request, output *ListProtocolsListsOutput) { op := &request.Operation{ - Name: opListTagsForResource, + Name: opListProtocolsLists, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &ListTagsForResourceInput{} + input = &ListProtocolsListsInput{} } - output = &ListTagsForResourceOutput{} + output = &ListProtocolsListsOutput{} req = c.newRequest(op, input, output) return } -// ListTagsForResource API operation for Firewall Management Service. +// ListProtocolsLists API operation for Firewall Management Service. // -// Retrieves the list of tags for the specified AWS resource. +// Returns an array of ProtocolsListDataSummary 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 Firewall Management Service's -// API operation ListTagsForResource for usage and error information. +// API operation ListProtocolsLists for usage and error information. // // Returned Error Types: // * ResourceNotFoundException // The specified resource was not found. // // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * InternalErrorException // The operation failed because of a system problem, even though the request // was valid. Retry your request. // -// * InvalidInputException -// The parameters of the request were invalid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListTagsForResource -func (c *FMS) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { - req, out := c.ListTagsForResourceRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListProtocolsLists +func (c *FMS) ListProtocolsLists(input *ListProtocolsListsInput) (*ListProtocolsListsOutput, error) { + req, out := c.ListProtocolsListsRequest(input) + return out, req.Send() +} + +// ListProtocolsListsWithContext is the same as ListProtocolsLists with the addition of +// the ability to pass a context and additional request options. +// +// See ListProtocolsLists for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *FMS) ListProtocolsListsWithContext(ctx aws.Context, input *ListProtocolsListsInput, opts ...request.Option) (*ListProtocolsListsOutput, error) { + req, out := c.ListProtocolsListsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListTagsForResource = "ListTagsForResource" + +// ListTagsForResourceRequest generates a "aws/request.Request" representing the +// client's request for the ListTagsForResource operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListTagsForResource for more information on using the ListTagsForResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListTagsForResourceRequest method. +// req, resp := client.ListTagsForResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListTagsForResource +func (c *FMS) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { + op := &request.Operation{ + Name: opListTagsForResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListTagsForResourceInput{} + } + + output = &ListTagsForResourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListTagsForResource API operation for Firewall Management Service. +// +// Retrieves the list of tags for the specified AWS 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 Firewall Management Service's +// API operation ListTagsForResource for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The specified resource was not found. +// +// * InvalidOperationException +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. +// +// * InternalErrorException +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// * InvalidInputException +// The parameters of the request were invalid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/ListTagsForResource +func (c *FMS) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) return out, req.Send() } @@ -1360,6 +2040,106 @@ func (c *FMS) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsFor return out, req.Send() } +const opPutAppsList = "PutAppsList" + +// PutAppsListRequest generates a "aws/request.Request" representing the +// client's request for the PutAppsList operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutAppsList for more information on using the PutAppsList +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutAppsListRequest method. +// req, resp := client.PutAppsListRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/PutAppsList +func (c *FMS) PutAppsListRequest(input *PutAppsListInput) (req *request.Request, output *PutAppsListOutput) { + op := &request.Operation{ + Name: opPutAppsList, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &PutAppsListInput{} + } + + output = &PutAppsListOutput{} + req = c.newRequest(op, input, output) + return +} + +// PutAppsList API operation for Firewall Management Service. +// +// Creates an AWS Firewall Manager applications list. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Firewall Management Service's +// API operation PutAppsList for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The specified resource was not found. +// +// * InvalidOperationException +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. +// +// * InvalidInputException +// The parameters of the request were invalid. +// +// * LimitExceededException +// The operation exceeds a resource limit, for example, the maximum number of +// policy objects that you can create for an AWS account. For more information, +// see Firewall Manager Limits (https://docs.aws.amazon.com/waf/latest/developerguide/fms-limits.html) +// in the AWS WAF Developer Guide. +// +// * InternalErrorException +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/PutAppsList +func (c *FMS) PutAppsList(input *PutAppsListInput) (*PutAppsListOutput, error) { + req, out := c.PutAppsListRequest(input) + return out, req.Send() +} + +// PutAppsListWithContext is the same as PutAppsList with the addition of +// the ability to pass a context and additional request options. +// +// See PutAppsList for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *FMS) PutAppsListWithContext(ctx aws.Context, input *PutAppsListInput, opts ...request.Option) (*PutAppsListOutput, error) { + req, out := c.PutAppsListRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opPutNotificationChannel = "PutNotificationChannel" // PutNotificationChannelRequest generates a "aws/request.Request" representing the @@ -1420,9 +2200,12 @@ func (c *FMS) PutNotificationChannelRequest(input *PutNotificationChannelInput) // The specified resource was not found. // // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * InternalErrorException // The operation failed because of a system problem, even though the request @@ -1530,9 +2313,12 @@ func (c *FMS) PutPolicyRequest(input *PutPolicyInput) (req *request.Request, out // The specified resource was not found. // // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * InvalidInputException // The parameters of the request were invalid. @@ -1572,6 +2358,106 @@ func (c *FMS) PutPolicyWithContext(ctx aws.Context, input *PutPolicyInput, opts return out, req.Send() } +const opPutProtocolsList = "PutProtocolsList" + +// PutProtocolsListRequest generates a "aws/request.Request" representing the +// client's request for the PutProtocolsList operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutProtocolsList for more information on using the PutProtocolsList +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutProtocolsListRequest method. +// req, resp := client.PutProtocolsListRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/PutProtocolsList +func (c *FMS) PutProtocolsListRequest(input *PutProtocolsListInput) (req *request.Request, output *PutProtocolsListOutput) { + op := &request.Operation{ + Name: opPutProtocolsList, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &PutProtocolsListInput{} + } + + output = &PutProtocolsListOutput{} + req = c.newRequest(op, input, output) + return +} + +// PutProtocolsList API operation for Firewall Management Service. +// +// Creates an AWS Firewall Manager protocols list. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Firewall Management Service's +// API operation PutProtocolsList for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The specified resource was not found. +// +// * InvalidOperationException +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. +// +// * InvalidInputException +// The parameters of the request were invalid. +// +// * LimitExceededException +// The operation exceeds a resource limit, for example, the maximum number of +// policy objects that you can create for an AWS account. For more information, +// see Firewall Manager Limits (https://docs.aws.amazon.com/waf/latest/developerguide/fms-limits.html) +// in the AWS WAF Developer Guide. +// +// * InternalErrorException +// The operation failed because of a system problem, even though the request +// was valid. Retry your request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/fms-2018-01-01/PutProtocolsList +func (c *FMS) PutProtocolsList(input *PutProtocolsListInput) (*PutProtocolsListOutput, error) { + req, out := c.PutProtocolsListRequest(input) + return out, req.Send() +} + +// PutProtocolsListWithContext is the same as PutProtocolsList with the addition of +// the ability to pass a context and additional request options. +// +// See PutProtocolsList for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *FMS) PutProtocolsListWithContext(ctx aws.Context, input *PutProtocolsListInput, opts ...request.Option) (*PutProtocolsListOutput, error) { + req, out := c.PutProtocolsListRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opTagResource = "TagResource" // TagResourceRequest generates a "aws/request.Request" representing the @@ -1631,9 +2517,12 @@ func (c *FMS) TagResourceRequest(input *TagResourceInput) (req *request.Request, // The specified resource was not found. // // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * InternalErrorException // The operation failed because of a system problem, even though the request @@ -1729,9 +2618,12 @@ func (c *FMS) UntagResourceRequest(input *UntagResourceInput) (req *request.Requ // The specified resource was not found. // // * InvalidOperationException -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. // // * InternalErrorException // The operation failed because of a system problem, even though the request @@ -1762,36 +2654,54 @@ func (c *FMS) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInpu return out, req.Send() } -type AssociateAdminAccountInput struct { +// An individual AWS Firewall Manager application. +type App struct { _ struct{} `type:"structure"` - // The AWS account ID to associate with AWS Firewall Manager as the AWS Firewall - // Manager administrator account. This can be an AWS Organizations master account - // or a member account. For more information about AWS Organizations and master - // accounts, see Managing the AWS Accounts in Your Organization (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts.html). + // The application's name. // - // AdminAccount is a required field - AdminAccount *string `min:"1" type:"string" required:"true"` + // AppName is a required field + AppName *string `min:"1" type:"string" required:"true"` + + // The application's port number, for example 80. + // + // Port is a required field + Port *int64 `type:"long" required:"true"` + + // The IP protocol name or number. The name can be one of tcp, udp, or icmp. + // For information on possible numbers, see Protocol Numbers (https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml). + // + // Protocol is a required field + Protocol *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s AssociateAdminAccountInput) String() string { +func (s App) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AssociateAdminAccountInput) GoString() string { +func (s App) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *AssociateAdminAccountInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssociateAdminAccountInput"} - if s.AdminAccount == nil { - invalidParams.Add(request.NewErrParamRequired("AdminAccount")) +func (s *App) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "App"} + if s.AppName == nil { + invalidParams.Add(request.NewErrParamRequired("AppName")) } - if s.AdminAccount != nil && len(*s.AdminAccount) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AdminAccount", 1)) + if s.AppName != nil && len(*s.AppName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AppName", 1)) + } + if s.Port == nil { + invalidParams.Add(request.NewErrParamRequired("Port")) + } + if s.Protocol == nil { + invalidParams.Add(request.NewErrParamRequired("Protocol")) + } + if s.Protocol != nil && len(*s.Protocol) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Protocol", 1)) } if invalidParams.Len() > 0 { @@ -1800,13 +2710,239 @@ func (s *AssociateAdminAccountInput) Validate() error { return nil } -// SetAdminAccount sets the AdminAccount field's value. -func (s *AssociateAdminAccountInput) SetAdminAccount(v string) *AssociateAdminAccountInput { - s.AdminAccount = &v +// SetAppName sets the AppName field's value. +func (s *App) SetAppName(v string) *App { + s.AppName = &v return s } -type AssociateAdminAccountOutput struct { +// SetPort sets the Port field's value. +func (s *App) SetPort(v int64) *App { + s.Port = &v + return s +} + +// SetProtocol sets the Protocol field's value. +func (s *App) SetProtocol(v string) *App { + s.Protocol = &v + return s +} + +// An AWS Firewall Manager applications list. +type AppsListData struct { + _ struct{} `type:"structure"` + + // An array of applications in the AWS Firewall Manager applications list. + // + // AppsList is a required field + AppsList []*App `type:"list" required:"true"` + + // The time that the AWS Firewall Manager applications list was created. + CreateTime *time.Time `type:"timestamp"` + + // The time that the AWS Firewall Manager applications list was last updated. + LastUpdateTime *time.Time `type:"timestamp"` + + // The ID of the AWS Firewall Manager applications list. + ListId *string `min:"36" type:"string"` + + // The name of the AWS Firewall Manager applications list. + // + // ListName is a required field + ListName *string `min:"1" type:"string" required:"true"` + + // A unique identifier for each update to the list. When you update the list, + // the update token must match the token of the current version of the application + // list. You can retrieve the update token by getting the list. + ListUpdateToken *string `min:"1" type:"string"` + + // A map of previous version numbers to their corresponding App object arrays. + PreviousAppsList map[string][]*App `type:"map"` +} + +// String returns the string representation +func (s AppsListData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AppsListData) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AppsListData) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AppsListData"} + if s.AppsList == nil { + invalidParams.Add(request.NewErrParamRequired("AppsList")) + } + if s.ListId != nil && len(*s.ListId) < 36 { + invalidParams.Add(request.NewErrParamMinLen("ListId", 36)) + } + if s.ListName == nil { + invalidParams.Add(request.NewErrParamRequired("ListName")) + } + if s.ListName != nil && len(*s.ListName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ListName", 1)) + } + if s.ListUpdateToken != nil && len(*s.ListUpdateToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ListUpdateToken", 1)) + } + if s.AppsList != nil { + for i, v := range s.AppsList { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "AppsList", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAppsList sets the AppsList field's value. +func (s *AppsListData) SetAppsList(v []*App) *AppsListData { + s.AppsList = v + return s +} + +// SetCreateTime sets the CreateTime field's value. +func (s *AppsListData) SetCreateTime(v time.Time) *AppsListData { + s.CreateTime = &v + return s +} + +// SetLastUpdateTime sets the LastUpdateTime field's value. +func (s *AppsListData) SetLastUpdateTime(v time.Time) *AppsListData { + s.LastUpdateTime = &v + return s +} + +// SetListId sets the ListId field's value. +func (s *AppsListData) SetListId(v string) *AppsListData { + s.ListId = &v + return s +} + +// SetListName sets the ListName field's value. +func (s *AppsListData) SetListName(v string) *AppsListData { + s.ListName = &v + return s +} + +// SetListUpdateToken sets the ListUpdateToken field's value. +func (s *AppsListData) SetListUpdateToken(v string) *AppsListData { + s.ListUpdateToken = &v + return s +} + +// SetPreviousAppsList sets the PreviousAppsList field's value. +func (s *AppsListData) SetPreviousAppsList(v map[string][]*App) *AppsListData { + s.PreviousAppsList = v + return s +} + +// Details of the AWS Firewall Manager applications list. +type AppsListDataSummary struct { + _ struct{} `type:"structure"` + + // An array of App objects in the AWS Firewall Manager applications list. + AppsList []*App `type:"list"` + + // The Amazon Resource Name (ARN) of the applications list. + ListArn *string `min:"1" type:"string"` + + // The ID of the applications list. + ListId *string `min:"36" type:"string"` + + // The name of the applications list. + ListName *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s AppsListDataSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AppsListDataSummary) GoString() string { + return s.String() +} + +// SetAppsList sets the AppsList field's value. +func (s *AppsListDataSummary) SetAppsList(v []*App) *AppsListDataSummary { + s.AppsList = v + return s +} + +// SetListArn sets the ListArn field's value. +func (s *AppsListDataSummary) SetListArn(v string) *AppsListDataSummary { + s.ListArn = &v + return s +} + +// SetListId sets the ListId field's value. +func (s *AppsListDataSummary) SetListId(v string) *AppsListDataSummary { + s.ListId = &v + return s +} + +// SetListName sets the ListName field's value. +func (s *AppsListDataSummary) SetListName(v string) *AppsListDataSummary { + s.ListName = &v + return s +} + +type AssociateAdminAccountInput struct { + _ struct{} `type:"structure"` + + // The AWS account ID to associate with AWS Firewall Manager as the AWS Firewall + // Manager administrator account. This can be an AWS Organizations master account + // or a member account. For more information about AWS Organizations and master + // accounts, see Managing the AWS Accounts in Your Organization (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts.html). + // + // AdminAccount is a required field + AdminAccount *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s AssociateAdminAccountInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateAdminAccountInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AssociateAdminAccountInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AssociateAdminAccountInput"} + if s.AdminAccount == nil { + invalidParams.Add(request.NewErrParamRequired("AdminAccount")) + } + if s.AdminAccount != nil && len(*s.AdminAccount) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AdminAccount", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAdminAccount sets the AdminAccount field's value. +func (s *AssociateAdminAccountInput) SetAdminAccount(v string) *AssociateAdminAccountInput { + s.AdminAccount = &v + return s +} + +type AssociateAdminAccountOutput struct { _ struct{} `type:"structure"` } @@ -1820,6 +2956,126 @@ func (s AssociateAdminAccountOutput) GoString() string { return s.String() } +// Violations for an EC2 instance resource. +type AwsEc2InstanceViolation struct { + _ struct{} `type:"structure"` + + // Violations for network interfaces associated with the EC2 instance. + AwsEc2NetworkInterfaceViolations []*AwsEc2NetworkInterfaceViolation `type:"list"` + + // The resource ID of the EC2 instance. + ViolationTarget *string `type:"string"` +} + +// String returns the string representation +func (s AwsEc2InstanceViolation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsEc2InstanceViolation) GoString() string { + return s.String() +} + +// SetAwsEc2NetworkInterfaceViolations sets the AwsEc2NetworkInterfaceViolations field's value. +func (s *AwsEc2InstanceViolation) SetAwsEc2NetworkInterfaceViolations(v []*AwsEc2NetworkInterfaceViolation) *AwsEc2InstanceViolation { + s.AwsEc2NetworkInterfaceViolations = v + return s +} + +// SetViolationTarget sets the ViolationTarget field's value. +func (s *AwsEc2InstanceViolation) SetViolationTarget(v string) *AwsEc2InstanceViolation { + s.ViolationTarget = &v + return s +} + +// Violations for network interfaces associated with an EC2 instance. +type AwsEc2NetworkInterfaceViolation struct { + _ struct{} `type:"structure"` + + // List of security groups that violate the rules specified in the master security + // group of the AWS Firewall Manager policy. + ViolatingSecurityGroups []*string `type:"list"` + + // The resource ID of the network interface. + ViolationTarget *string `type:"string"` +} + +// String returns the string representation +func (s AwsEc2NetworkInterfaceViolation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsEc2NetworkInterfaceViolation) GoString() string { + return s.String() +} + +// SetViolatingSecurityGroups sets the ViolatingSecurityGroups field's value. +func (s *AwsEc2NetworkInterfaceViolation) SetViolatingSecurityGroups(v []*string) *AwsEc2NetworkInterfaceViolation { + s.ViolatingSecurityGroups = v + return s +} + +// SetViolationTarget sets the ViolationTarget field's value. +func (s *AwsEc2NetworkInterfaceViolation) SetViolationTarget(v string) *AwsEc2NetworkInterfaceViolation { + s.ViolationTarget = &v + return s +} + +// Details of the rule violation in a security group when compared to the master +// security group of the AWS Firewall Manager policy. +type AwsVPCSecurityGroupViolation struct { + _ struct{} `type:"structure"` + + // List of rules specified in the security group of the AWS Firewall Manager + // policy that partially match the ViolationTarget rule. + PartialMatches []*PartialMatch `type:"list"` + + // Remediation options for the rule specified in the ViolationTarget. + PossibleSecurityGroupRemediationActions []*SecurityGroupRemediationAction `type:"list"` + + // The security group rule that is being evaluated. + ViolationTarget *string `type:"string"` + + // A description of the security group that violates the policy. + ViolationTargetDescription *string `type:"string"` +} + +// String returns the string representation +func (s AwsVPCSecurityGroupViolation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsVPCSecurityGroupViolation) GoString() string { + return s.String() +} + +// SetPartialMatches sets the PartialMatches field's value. +func (s *AwsVPCSecurityGroupViolation) SetPartialMatches(v []*PartialMatch) *AwsVPCSecurityGroupViolation { + s.PartialMatches = v + return s +} + +// SetPossibleSecurityGroupRemediationActions sets the PossibleSecurityGroupRemediationActions field's value. +func (s *AwsVPCSecurityGroupViolation) SetPossibleSecurityGroupRemediationActions(v []*SecurityGroupRemediationAction) *AwsVPCSecurityGroupViolation { + s.PossibleSecurityGroupRemediationActions = v + return s +} + +// SetViolationTarget sets the ViolationTarget field's value. +func (s *AwsVPCSecurityGroupViolation) SetViolationTarget(v string) *AwsVPCSecurityGroupViolation { + s.ViolationTarget = &v + return s +} + +// SetViolationTargetDescription sets the ViolationTargetDescription field's value. +func (s *AwsVPCSecurityGroupViolation) SetViolationTargetDescription(v string) *AwsVPCSecurityGroupViolation { + s.ViolationTargetDescription = &v + return s +} + // Details of the resource that is not protected by the policy. type ComplianceViolator struct { _ struct{} `type:"structure"` @@ -1864,6 +3120,62 @@ func (s *ComplianceViolator) SetViolationReason(v string) *ComplianceViolator { return s } +type DeleteAppsListInput struct { + _ struct{} `type:"structure"` + + // The ID of the applications list that you want to delete. You can retrieve + // this ID from PutAppsList, ListAppsLists, and GetAppsList. + // + // ListId is a required field + ListId *string `min:"36" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteAppsListInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteAppsListInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteAppsListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteAppsListInput"} + if s.ListId == nil { + invalidParams.Add(request.NewErrParamRequired("ListId")) + } + if s.ListId != nil && len(*s.ListId) < 36 { + invalidParams.Add(request.NewErrParamMinLen("ListId", 36)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetListId sets the ListId field's value. +func (s *DeleteAppsListInput) SetListId(v string) *DeleteAppsListInput { + s.ListId = &v + return s +} + +type DeleteAppsListOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteAppsListOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteAppsListOutput) GoString() string { + return s.String() +} + type DeleteNotificationChannelInput struct { _ struct{} `type:"structure"` } @@ -1922,8 +3234,8 @@ type DeletePolicyInput struct { // If you don't specify tags or accounts, all resources are in scope. DeleteAllPolicyResources *bool `type:"boolean"` - // The ID of the policy that you want to delete. PolicyId is returned by PutPolicy - // and by ListPolicies. + // The ID of the policy that you want to delete. You can retrieve this ID from + // PutPolicy and ListPolicies. // // PolicyId is a required field PolicyId *string `min:"36" type:"string" required:"true"` @@ -1981,6 +3293,62 @@ func (s DeletePolicyOutput) GoString() string { return s.String() } +type DeleteProtocolsListInput struct { + _ struct{} `type:"structure"` + + // The ID of the protocols list that you want to delete. You can retrieve this + // ID from PutProtocolsList, ListProtocolsLists, and GetProtocolsLost. + // + // ListId is a required field + ListId *string `min:"36" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteProtocolsListInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteProtocolsListInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteProtocolsListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteProtocolsListInput"} + if s.ListId == nil { + invalidParams.Add(request.NewErrParamRequired("ListId")) + } + if s.ListId != nil && len(*s.ListId) < 36 { + invalidParams.Add(request.NewErrParamMinLen("ListId", 36)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetListId sets the ListId field's value. +func (s *DeleteProtocolsListInput) SetListId(v string) *DeleteProtocolsListInput { + s.ListId = &v + return s +} + +type DeleteProtocolsListOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteProtocolsListOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteProtocolsListOutput) GoString() string { + return s.String() +} + type DisassociateAdminAccountInput struct { _ struct{} `type:"structure"` } @@ -2046,61 +3414,145 @@ func (s *EvaluationResult) SetComplianceStatus(v string) *EvaluationResult { return s } -// SetEvaluationLimitExceeded sets the EvaluationLimitExceeded field's value. -func (s *EvaluationResult) SetEvaluationLimitExceeded(v bool) *EvaluationResult { - s.EvaluationLimitExceeded = &v +// SetEvaluationLimitExceeded sets the EvaluationLimitExceeded field's value. +func (s *EvaluationResult) SetEvaluationLimitExceeded(v bool) *EvaluationResult { + s.EvaluationLimitExceeded = &v + return s +} + +// SetViolatorCount sets the ViolatorCount field's value. +func (s *EvaluationResult) SetViolatorCount(v int64) *EvaluationResult { + s.ViolatorCount = &v + return s +} + +type GetAdminAccountInput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s GetAdminAccountInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetAdminAccountInput) GoString() string { + return s.String() +} + +type GetAdminAccountOutput struct { + _ struct{} `type:"structure"` + + // The AWS account that is set as the AWS Firewall Manager administrator. + AdminAccount *string `min:"1" type:"string"` + + // The status of the AWS account that you set as the AWS Firewall Manager administrator. + RoleStatus *string `type:"string" enum:"AccountRoleStatus"` +} + +// String returns the string representation +func (s GetAdminAccountOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetAdminAccountOutput) GoString() string { + return s.String() +} + +// SetAdminAccount sets the AdminAccount field's value. +func (s *GetAdminAccountOutput) SetAdminAccount(v string) *GetAdminAccountOutput { + s.AdminAccount = &v return s } -// SetViolatorCount sets the ViolatorCount field's value. -func (s *EvaluationResult) SetViolatorCount(v int64) *EvaluationResult { - s.ViolatorCount = &v +// SetRoleStatus sets the RoleStatus field's value. +func (s *GetAdminAccountOutput) SetRoleStatus(v string) *GetAdminAccountOutput { + s.RoleStatus = &v return s } -type GetAdminAccountInput struct { +type GetAppsListInput struct { _ struct{} `type:"structure"` + + // Specifies whether the list to retrieve is a default list owned by AWS Firewall + // Manager. + DefaultList *bool `type:"boolean"` + + // The ID of the AWS Firewall Manager applications list that you want the details + // for. + // + // ListId is a required field + ListId *string `min:"36" type:"string" required:"true"` } // String returns the string representation -func (s GetAdminAccountInput) String() string { +func (s GetAppsListInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetAdminAccountInput) GoString() string { +func (s GetAppsListInput) GoString() string { return s.String() } -type GetAdminAccountOutput struct { +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetAppsListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetAppsListInput"} + if s.ListId == nil { + invalidParams.Add(request.NewErrParamRequired("ListId")) + } + if s.ListId != nil && len(*s.ListId) < 36 { + invalidParams.Add(request.NewErrParamMinLen("ListId", 36)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDefaultList sets the DefaultList field's value. +func (s *GetAppsListInput) SetDefaultList(v bool) *GetAppsListInput { + s.DefaultList = &v + return s +} + +// SetListId sets the ListId field's value. +func (s *GetAppsListInput) SetListId(v string) *GetAppsListInput { + s.ListId = &v + return s +} + +type GetAppsListOutput struct { _ struct{} `type:"structure"` - // The AWS account that is set as the AWS Firewall Manager administrator. - AdminAccount *string `min:"1" type:"string"` + // Information about the specified AWS Firewall Manager applications list. + AppsList *AppsListData `type:"structure"` - // The status of the AWS account that you set as the AWS Firewall Manager administrator. - RoleStatus *string `type:"string" enum:"AccountRoleStatus"` + // The Amazon Resource Name (ARN) of the applications list. + AppsListArn *string `min:"1" type:"string"` } // String returns the string representation -func (s GetAdminAccountOutput) String() string { +func (s GetAppsListOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetAdminAccountOutput) GoString() string { +func (s GetAppsListOutput) GoString() string { return s.String() } -// SetAdminAccount sets the AdminAccount field's value. -func (s *GetAdminAccountOutput) SetAdminAccount(v string) *GetAdminAccountOutput { - s.AdminAccount = &v +// SetAppsList sets the AppsList field's value. +func (s *GetAppsListOutput) SetAppsList(v *AppsListData) *GetAppsListOutput { + s.AppsList = v return s } -// SetRoleStatus sets the RoleStatus field's value. -func (s *GetAdminAccountOutput) SetRoleStatus(v string) *GetAdminAccountOutput { - s.RoleStatus = &v +// SetAppsListArn sets the AppsListArn field's value. +func (s *GetAppsListOutput) SetAppsListArn(v string) *GetAppsListOutput { + s.AppsListArn = &v return s } @@ -2488,6 +3940,209 @@ func (s *GetProtectionStatusOutput) SetServiceType(v string) *GetProtectionStatu return s } +type GetProtocolsListInput struct { + _ struct{} `type:"structure"` + + // Specifies whether the list to retrieve is a default list owned by AWS Firewall + // Manager. + DefaultList *bool `type:"boolean"` + + // The ID of the AWS Firewall Manager protocols list that you want the details + // for. + // + // ListId is a required field + ListId *string `min:"36" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetProtocolsListInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetProtocolsListInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetProtocolsListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetProtocolsListInput"} + if s.ListId == nil { + invalidParams.Add(request.NewErrParamRequired("ListId")) + } + if s.ListId != nil && len(*s.ListId) < 36 { + invalidParams.Add(request.NewErrParamMinLen("ListId", 36)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDefaultList sets the DefaultList field's value. +func (s *GetProtocolsListInput) SetDefaultList(v bool) *GetProtocolsListInput { + s.DefaultList = &v + return s +} + +// SetListId sets the ListId field's value. +func (s *GetProtocolsListInput) SetListId(v string) *GetProtocolsListInput { + s.ListId = &v + return s +} + +type GetProtocolsListOutput struct { + _ struct{} `type:"structure"` + + // Information about the specified AWS Firewall Manager protocols list. + ProtocolsList *ProtocolsListData `type:"structure"` + + // The Amazon Resource Name (ARN) of the specified protocols list. + ProtocolsListArn *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s GetProtocolsListOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetProtocolsListOutput) GoString() string { + return s.String() +} + +// SetProtocolsList sets the ProtocolsList field's value. +func (s *GetProtocolsListOutput) SetProtocolsList(v *ProtocolsListData) *GetProtocolsListOutput { + s.ProtocolsList = v + return s +} + +// SetProtocolsListArn sets the ProtocolsListArn field's value. +func (s *GetProtocolsListOutput) SetProtocolsListArn(v string) *GetProtocolsListOutput { + s.ProtocolsListArn = &v + return s +} + +type GetViolationDetailsInput struct { + _ struct{} `type:"structure"` + + // The AWS account ID that you want the details for. + // + // MemberAccount is a required field + MemberAccount *string `min:"1" type:"string" required:"true"` + + // The ID of the AWS Firewall Manager policy that you want the details for. + // This currently only supports security group content audit policies. + // + // PolicyId is a required field + PolicyId *string `min:"36" type:"string" required:"true"` + + // The ID of the resource that has violations. + // + // ResourceId is a required field + ResourceId *string `min:"1" type:"string" required:"true"` + + // The resource type. This is in the format shown in the AWS Resource Types + // Reference (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html). + // Supported resource types are: AWS::EC2::Instance, AWS::EC2::NetworkInterface, + // or AWS::EC2::SecurityGroup. + // + // ResourceType is a required field + ResourceType *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetViolationDetailsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetViolationDetailsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetViolationDetailsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetViolationDetailsInput"} + if s.MemberAccount == nil { + invalidParams.Add(request.NewErrParamRequired("MemberAccount")) + } + if s.MemberAccount != nil && len(*s.MemberAccount) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MemberAccount", 1)) + } + if s.PolicyId == nil { + invalidParams.Add(request.NewErrParamRequired("PolicyId")) + } + if s.PolicyId != nil && len(*s.PolicyId) < 36 { + invalidParams.Add(request.NewErrParamMinLen("PolicyId", 36)) + } + if s.ResourceId == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceId")) + } + if s.ResourceId != nil && len(*s.ResourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceId", 1)) + } + if s.ResourceType == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceType")) + } + if s.ResourceType != nil && len(*s.ResourceType) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceType", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMemberAccount sets the MemberAccount field's value. +func (s *GetViolationDetailsInput) SetMemberAccount(v string) *GetViolationDetailsInput { + s.MemberAccount = &v + return s +} + +// SetPolicyId sets the PolicyId field's value. +func (s *GetViolationDetailsInput) SetPolicyId(v string) *GetViolationDetailsInput { + s.PolicyId = &v + return s +} + +// SetResourceId sets the ResourceId field's value. +func (s *GetViolationDetailsInput) SetResourceId(v string) *GetViolationDetailsInput { + s.ResourceId = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *GetViolationDetailsInput) SetResourceType(v string) *GetViolationDetailsInput { + s.ResourceType = &v + return s +} + +type GetViolationDetailsOutput struct { + _ struct{} `type:"structure"` + + // Violation detail for a resource. + ViolationDetail *ViolationDetail `type:"structure"` +} + +// String returns the string representation +func (s GetViolationDetailsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetViolationDetailsOutput) GoString() string { + return s.String() +} + +// SetViolationDetail sets the ViolationDetail field's value. +func (s *GetViolationDetailsOutput) SetViolationDetail(v *ViolationDetail) *GetViolationDetailsOutput { + s.ViolationDetail = v + return s +} + // The operation failed because of a system problem, even though the request // was valid. Retry your request. type InternalErrorException struct { @@ -2601,9 +4256,12 @@ func (s *InvalidInputException) RequestID() string { return s.RespMetadata.RequestID } -// The operation failed because there was nothing to do. For example, you might -// have submitted an AssociateAdminAccount request, but the account ID that -// you submitted was already set as the AWS Firewall Manager administrator. +// The operation failed because there was nothing to do or the operation wasn't +// possible. For example, you might have submitted an AssociateAdminAccount +// request for an account ID that was already set as the AWS Firewall Manager +// administrator. Or you might have tried to access a Region that's disabled +// by default, and that you need to enable for the Firewall Manager administrator +// account and for AWS Organizations before you can access it. type InvalidOperationException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -2764,14 +4422,121 @@ func (s *LimitExceededException) Error() string { return fmt.Sprintf("%s: %s", s.Code(), s.Message()) } -// Status code returns the HTTP status code for the request's response error. -func (s *LimitExceededException) StatusCode() int { - return s.RespMetadata.StatusCode +// Status code returns the HTTP status code for the request's response error. +func (s *LimitExceededException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *LimitExceededException) RequestID() string { + return s.RespMetadata.RequestID +} + +type ListAppsListsInput struct { + _ struct{} `type:"structure"` + + // Specifies whether the lists to retrieve are default lists owned by AWS Firewall + // Manager. + DefaultLists *bool `type:"boolean"` + + // The maximum number of objects that you want AWS Firewall Manager to return + // for this request. If more objects are available, in the response, AWS Firewall + // Manager provides a NextToken value that you can use in a subsequent call + // to get the next batch of objects. + // + // If you don't specify this, AWS Firewall Manager returns all available objects. + // + // MaxResults is a required field + MaxResults *int64 `min:"1" type:"integer" required:"true"` + + // If you specify a value for MaxResults in your list request, and you have + // more objects than the maximum, AWS Firewall Manager returns this token in + // the response. For all but the first request, you provide the token returned + // by the prior request in the request parameters, to retrieve the next batch + // of objects. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListAppsListsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListAppsListsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListAppsListsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListAppsListsInput"} + 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 +} + +// SetDefaultLists sets the DefaultLists field's value. +func (s *ListAppsListsInput) SetDefaultLists(v bool) *ListAppsListsInput { + s.DefaultLists = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListAppsListsInput) SetMaxResults(v int64) *ListAppsListsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListAppsListsInput) SetNextToken(v string) *ListAppsListsInput { + s.NextToken = &v + return s +} + +type ListAppsListsOutput struct { + _ struct{} `type:"structure"` + + // An array of AppsListDataSummary objects. + AppsLists []*AppsListDataSummary `type:"list"` + + // If you specify a value for MaxResults in your list request, and you have + // more objects than the maximum, AWS Firewall Manager returns this token in + // the response. You can use this token in subsequent requests to retrieve the + // next batch of objects. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListAppsListsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListAppsListsOutput) GoString() string { + return s.String() +} + +// SetAppsLists sets the AppsLists field's value. +func (s *ListAppsListsOutput) SetAppsLists(v []*AppsListDataSummary) *ListAppsListsOutput { + s.AppsLists = v + return s } -// RequestID returns the service's response RequestID for request. -func (s *LimitExceededException) RequestID() string { - return s.RespMetadata.RequestID +// SetNextToken sets the NextToken field's value. +func (s *ListAppsListsOutput) SetNextToken(v string) *ListAppsListsOutput { + s.NextToken = &v + return s } type ListComplianceStatusInput struct { @@ -3067,12 +4832,119 @@ func (s *ListPoliciesOutput) SetPolicyList(v []*PolicySummary) *ListPoliciesOutp return s } +type ListProtocolsListsInput struct { + _ struct{} `type:"structure"` + + // Specifies whether the lists to retrieve are default lists owned by AWS Firewall + // Manager. + DefaultLists *bool `type:"boolean"` + + // The maximum number of objects that you want AWS Firewall Manager to return + // for this request. If more objects are available, in the response, AWS Firewall + // Manager provides a NextToken value that you can use in a subsequent call + // to get the next batch of objects. + // + // If you don't specify this, AWS Firewall Manager returns all available objects. + // + // MaxResults is a required field + MaxResults *int64 `min:"1" type:"integer" required:"true"` + + // If you specify a value for MaxResults in your list request, and you have + // more objects than the maximum, AWS Firewall Manager returns this token in + // the response. For all but the first request, you provide the token returned + // by the prior request in the request parameters, to retrieve the next batch + // of objects. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListProtocolsListsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListProtocolsListsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListProtocolsListsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListProtocolsListsInput"} + 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 +} + +// SetDefaultLists sets the DefaultLists field's value. +func (s *ListProtocolsListsInput) SetDefaultLists(v bool) *ListProtocolsListsInput { + s.DefaultLists = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListProtocolsListsInput) SetMaxResults(v int64) *ListProtocolsListsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListProtocolsListsInput) SetNextToken(v string) *ListProtocolsListsInput { + s.NextToken = &v + return s +} + +type ListProtocolsListsOutput struct { + _ struct{} `type:"structure"` + + // If you specify a value for MaxResults in your list request, and you have + // more objects than the maximum, AWS Firewall Manager returns this token in + // the response. You can use this token in subsequent requests to retrieve the + // next batch of objects. + NextToken *string `min:"1" type:"string"` + + // An array of ProtocolsListDataSummary objects. + ProtocolsLists []*ProtocolsListDataSummary `type:"list"` +} + +// String returns the string representation +func (s ListProtocolsListsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListProtocolsListsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListProtocolsListsOutput) SetNextToken(v string) *ListProtocolsListsOutput { + s.NextToken = &v + return s +} + +// SetProtocolsLists sets the ProtocolsLists field's value. +func (s *ListProtocolsListsOutput) SetProtocolsLists(v []*ProtocolsListDataSummary) *ListProtocolsListsOutput { + s.ProtocolsLists = v + return s +} + type ListTagsForResourceInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource to return tags for. The Firewall - // Manager policy is the only AWS resource that supports tagging, so this ARN - // is a policy ARN.. + // The Amazon Resource Name (ARN) of the resource to return tags for. The AWS + // Firewall Manager resources that support tagging are policies, applications + // lists, and protocols lists. // // ResourceArn is a required field ResourceArn *string `min:"1" type:"string" required:"true"` @@ -3133,6 +5005,41 @@ func (s *ListTagsForResourceOutput) SetTagList(v []*Tag) *ListTagsForResourceOut return s } +// The reference rule that partially matches the ViolationTarget rule and violation +// reason. +type PartialMatch struct { + _ struct{} `type:"structure"` + + // The reference rule from the master security group of the AWS Firewall Manager + // policy. + Reference *string `type:"string"` + + // The violation reason. + TargetViolationReasons []*string `type:"list"` +} + +// String returns the string representation +func (s PartialMatch) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PartialMatch) GoString() string { + return s.String() +} + +// SetReference sets the Reference field's value. +func (s *PartialMatch) SetReference(v string) *PartialMatch { + s.Reference = &v + return s +} + +// SetTargetViolationReasons sets the TargetViolationReasons field's value. +func (s *PartialMatch) SetTargetViolationReasons(v []*string) *PartialMatch { + s.TargetViolationReasons = v + return s +} + // An AWS Firewall Manager policy. type Policy struct { _ struct{} `type:"structure"` @@ -3196,7 +5103,7 @@ type Policy struct { // The ID of the AWS Firewall Manager policy. PolicyId *string `min:"36" type:"string"` - // The friendly name of the AWS Firewall Manager policy. + // The name of the AWS Firewall Manager policy. // // PolicyName is a required field PolicyName *string `min:"1" type:"string" required:"true"` @@ -3475,7 +5382,7 @@ type PolicyComplianceStatus struct { // The ID of the AWS Firewall Manager policy. PolicyId *string `min:"36" type:"string"` - // The friendly name of the AWS Firewall Manager policy. + // The name of the AWS Firewall Manager policy. PolicyName *string `min:"1" type:"string"` // The AWS account that created the AWS Firewall Manager policy. @@ -3544,7 +5451,7 @@ type PolicySummary struct { // The ID of the specified policy. PolicyId *string `min:"36" type:"string"` - // The friendly name of the specified policy. + // The name of the specified policy. PolicyName *string `min:"1" type:"string"` // Indicates if the policy should be automatically applied to new resources. @@ -3582,33 +5489,287 @@ func (s *PolicySummary) SetPolicyArn(v string) *PolicySummary { return s } -// SetPolicyId sets the PolicyId field's value. -func (s *PolicySummary) SetPolicyId(v string) *PolicySummary { - s.PolicyId = &v - return s +// SetPolicyId sets the PolicyId field's value. +func (s *PolicySummary) SetPolicyId(v string) *PolicySummary { + s.PolicyId = &v + return s +} + +// SetPolicyName sets the PolicyName field's value. +func (s *PolicySummary) SetPolicyName(v string) *PolicySummary { + s.PolicyName = &v + return s +} + +// SetRemediationEnabled sets the RemediationEnabled field's value. +func (s *PolicySummary) SetRemediationEnabled(v bool) *PolicySummary { + s.RemediationEnabled = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *PolicySummary) SetResourceType(v string) *PolicySummary { + s.ResourceType = &v + return s +} + +// SetSecurityServiceType sets the SecurityServiceType field's value. +func (s *PolicySummary) SetSecurityServiceType(v string) *PolicySummary { + s.SecurityServiceType = &v + return s +} + +// An AWS Firewall Manager protocols list. +type ProtocolsListData struct { + _ struct{} `type:"structure"` + + // The time that the AWS Firewall Manager protocols list was created. + CreateTime *time.Time `type:"timestamp"` + + // The time that the AWS Firewall Manager protocols list was last updated. + LastUpdateTime *time.Time `type:"timestamp"` + + // The ID of the AWS Firewall Manager protocols list. + ListId *string `min:"36" type:"string"` + + // The name of the AWS Firewall Manager protocols list. + // + // ListName is a required field + ListName *string `min:"1" type:"string" required:"true"` + + // A unique identifier for each update to the list. When you update the list, + // the update token must match the token of the current version of the application + // list. You can retrieve the update token by getting the list. + ListUpdateToken *string `min:"1" type:"string"` + + // A map of previous version numbers to their corresponding protocol arrays. + PreviousProtocolsList map[string][]*string `type:"map"` + + // An array of protocols in the AWS Firewall Manager protocols list. + // + // ProtocolsList is a required field + ProtocolsList []*string `type:"list" required:"true"` +} + +// String returns the string representation +func (s ProtocolsListData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ProtocolsListData) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ProtocolsListData) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ProtocolsListData"} + if s.ListId != nil && len(*s.ListId) < 36 { + invalidParams.Add(request.NewErrParamMinLen("ListId", 36)) + } + if s.ListName == nil { + invalidParams.Add(request.NewErrParamRequired("ListName")) + } + if s.ListName != nil && len(*s.ListName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ListName", 1)) + } + if s.ListUpdateToken != nil && len(*s.ListUpdateToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ListUpdateToken", 1)) + } + if s.ProtocolsList == nil { + invalidParams.Add(request.NewErrParamRequired("ProtocolsList")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCreateTime sets the CreateTime field's value. +func (s *ProtocolsListData) SetCreateTime(v time.Time) *ProtocolsListData { + s.CreateTime = &v + return s +} + +// SetLastUpdateTime sets the LastUpdateTime field's value. +func (s *ProtocolsListData) SetLastUpdateTime(v time.Time) *ProtocolsListData { + s.LastUpdateTime = &v + return s +} + +// SetListId sets the ListId field's value. +func (s *ProtocolsListData) SetListId(v string) *ProtocolsListData { + s.ListId = &v + return s +} + +// SetListName sets the ListName field's value. +func (s *ProtocolsListData) SetListName(v string) *ProtocolsListData { + s.ListName = &v + return s +} + +// SetListUpdateToken sets the ListUpdateToken field's value. +func (s *ProtocolsListData) SetListUpdateToken(v string) *ProtocolsListData { + s.ListUpdateToken = &v + return s +} + +// SetPreviousProtocolsList sets the PreviousProtocolsList field's value. +func (s *ProtocolsListData) SetPreviousProtocolsList(v map[string][]*string) *ProtocolsListData { + s.PreviousProtocolsList = v + return s +} + +// SetProtocolsList sets the ProtocolsList field's value. +func (s *ProtocolsListData) SetProtocolsList(v []*string) *ProtocolsListData { + s.ProtocolsList = v + return s +} + +// Details of the AWS Firewall Manager protocols list. +type ProtocolsListDataSummary struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the specified protocols list. + ListArn *string `min:"1" type:"string"` + + // The ID of the specified protocols list. + ListId *string `min:"36" type:"string"` + + // The name of the specified protocols list. + ListName *string `min:"1" type:"string"` + + // An array of protocols in the AWS Firewall Manager protocols list. + ProtocolsList []*string `type:"list"` +} + +// String returns the string representation +func (s ProtocolsListDataSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ProtocolsListDataSummary) GoString() string { + return s.String() +} + +// SetListArn sets the ListArn field's value. +func (s *ProtocolsListDataSummary) SetListArn(v string) *ProtocolsListDataSummary { + s.ListArn = &v + return s +} + +// SetListId sets the ListId field's value. +func (s *ProtocolsListDataSummary) SetListId(v string) *ProtocolsListDataSummary { + s.ListId = &v + return s +} + +// SetListName sets the ListName field's value. +func (s *ProtocolsListDataSummary) SetListName(v string) *ProtocolsListDataSummary { + s.ListName = &v + return s +} + +// SetProtocolsList sets the ProtocolsList field's value. +func (s *ProtocolsListDataSummary) SetProtocolsList(v []*string) *ProtocolsListDataSummary { + s.ProtocolsList = v + return s +} + +type PutAppsListInput struct { + _ struct{} `type:"structure"` + + // The details of the AWS Firewall Manager applications list to be created. + // + // AppsList is a required field + AppsList *AppsListData `type:"structure" required:"true"` + + // The tags associated with the resource. + TagList []*Tag `type:"list"` +} + +// String returns the string representation +func (s PutAppsListInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutAppsListInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutAppsListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutAppsListInput"} + if s.AppsList == nil { + invalidParams.Add(request.NewErrParamRequired("AppsList")) + } + if s.AppsList != nil { + if err := s.AppsList.Validate(); err != nil { + invalidParams.AddNested("AppsList", err.(request.ErrInvalidParams)) + } + } + if s.TagList != nil { + for i, v := range s.TagList { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TagList", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAppsList sets the AppsList field's value. +func (s *PutAppsListInput) SetAppsList(v *AppsListData) *PutAppsListInput { + s.AppsList = v + return s +} + +// SetTagList sets the TagList field's value. +func (s *PutAppsListInput) SetTagList(v []*Tag) *PutAppsListInput { + s.TagList = v + return s +} + +type PutAppsListOutput struct { + _ struct{} `type:"structure"` + + // The details of the AWS Firewall Manager applications list. + AppsList *AppsListData `type:"structure"` + + // The Amazon Resource Name (ARN) of the applications list. + AppsListArn *string `min:"1" type:"string"` } -// SetPolicyName sets the PolicyName field's value. -func (s *PolicySummary) SetPolicyName(v string) *PolicySummary { - s.PolicyName = &v - return s +// String returns the string representation +func (s PutAppsListOutput) String() string { + return awsutil.Prettify(s) } -// SetRemediationEnabled sets the RemediationEnabled field's value. -func (s *PolicySummary) SetRemediationEnabled(v bool) *PolicySummary { - s.RemediationEnabled = &v - return s +// GoString returns the string representation +func (s PutAppsListOutput) GoString() string { + return s.String() } -// SetResourceType sets the ResourceType field's value. -func (s *PolicySummary) SetResourceType(v string) *PolicySummary { - s.ResourceType = &v +// SetAppsList sets the AppsList field's value. +func (s *PutAppsListOutput) SetAppsList(v *AppsListData) *PutAppsListOutput { + s.AppsList = v return s } -// SetSecurityServiceType sets the SecurityServiceType field's value. -func (s *PolicySummary) SetSecurityServiceType(v string) *PolicySummary { - s.SecurityServiceType = &v +// SetAppsListArn sets the AppsListArn field's value. +func (s *PutAppsListOutput) SetAppsListArn(v string) *PutAppsListOutput { + s.AppsListArn = &v return s } @@ -3751,10 +5912,10 @@ func (s *PutPolicyInput) SetTagList(v []*Tag) *PutPolicyInput { type PutPolicyOutput struct { _ struct{} `type:"structure"` - // The details of the AWS Firewall Manager policy that was created. + // The details of the AWS Firewall Manager policy. Policy *Policy `type:"structure"` - // The Amazon Resource Name (ARN) of the policy that was created. + // The Amazon Resource Name (ARN) of the policy. PolicyArn *string `min:"1" type:"string"` } @@ -3780,6 +5941,100 @@ func (s *PutPolicyOutput) SetPolicyArn(v string) *PutPolicyOutput { return s } +type PutProtocolsListInput struct { + _ struct{} `type:"structure"` + + // The details of the AWS Firewall Manager protocols list to be created. + // + // ProtocolsList is a required field + ProtocolsList *ProtocolsListData `type:"structure" required:"true"` + + // The tags associated with the resource. + TagList []*Tag `type:"list"` +} + +// String returns the string representation +func (s PutProtocolsListInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutProtocolsListInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutProtocolsListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutProtocolsListInput"} + if s.ProtocolsList == nil { + invalidParams.Add(request.NewErrParamRequired("ProtocolsList")) + } + if s.ProtocolsList != nil { + if err := s.ProtocolsList.Validate(); err != nil { + invalidParams.AddNested("ProtocolsList", err.(request.ErrInvalidParams)) + } + } + if s.TagList != nil { + for i, v := range s.TagList { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TagList", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetProtocolsList sets the ProtocolsList field's value. +func (s *PutProtocolsListInput) SetProtocolsList(v *ProtocolsListData) *PutProtocolsListInput { + s.ProtocolsList = v + return s +} + +// SetTagList sets the TagList field's value. +func (s *PutProtocolsListInput) SetTagList(v []*Tag) *PutProtocolsListInput { + s.TagList = v + return s +} + +type PutProtocolsListOutput struct { + _ struct{} `type:"structure"` + + // The details of the AWS Firewall Manager protocols list. + ProtocolsList *ProtocolsListData `type:"structure"` + + // The Amazon Resource Name (ARN) of the protocols list. + ProtocolsListArn *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s PutProtocolsListOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutProtocolsListOutput) GoString() string { + return s.String() +} + +// SetProtocolsList sets the ProtocolsList field's value. +func (s *PutProtocolsListOutput) SetProtocolsList(v *ProtocolsListData) *PutProtocolsListOutput { + s.ProtocolsList = v + return s +} + +// SetProtocolsListArn sets the ProtocolsListArn field's value. +func (s *PutProtocolsListOutput) SetProtocolsListArn(v string) *PutProtocolsListOutput { + s.ProtocolsListArn = &v + return s +} + // The specified resource was not found. type ResourceNotFoundException struct { _ struct{} `type:"structure"` @@ -3894,6 +6149,171 @@ func (s *ResourceTag) SetValue(v string) *ResourceTag { return s } +// Violation detail based on resource type. +type ResourceViolation struct { + _ struct{} `type:"structure"` + + // Violation details for an EC2 instance. + AwsEc2InstanceViolation *AwsEc2InstanceViolation `type:"structure"` + + // Violation details for network interface. + AwsEc2NetworkInterfaceViolation *AwsEc2NetworkInterfaceViolation `type:"structure"` + + // Violation details for security groups. + AwsVPCSecurityGroupViolation *AwsVPCSecurityGroupViolation `type:"structure"` +} + +// String returns the string representation +func (s ResourceViolation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResourceViolation) GoString() string { + return s.String() +} + +// SetAwsEc2InstanceViolation sets the AwsEc2InstanceViolation field's value. +func (s *ResourceViolation) SetAwsEc2InstanceViolation(v *AwsEc2InstanceViolation) *ResourceViolation { + s.AwsEc2InstanceViolation = v + return s +} + +// SetAwsEc2NetworkInterfaceViolation sets the AwsEc2NetworkInterfaceViolation field's value. +func (s *ResourceViolation) SetAwsEc2NetworkInterfaceViolation(v *AwsEc2NetworkInterfaceViolation) *ResourceViolation { + s.AwsEc2NetworkInterfaceViolation = v + return s +} + +// SetAwsVPCSecurityGroupViolation sets the AwsVPCSecurityGroupViolation field's value. +func (s *ResourceViolation) SetAwsVPCSecurityGroupViolation(v *AwsVPCSecurityGroupViolation) *ResourceViolation { + s.AwsVPCSecurityGroupViolation = v + return s +} + +// Remediation option for the rule specified in the ViolationTarget. +type SecurityGroupRemediationAction struct { + _ struct{} `type:"structure"` + + // Brief description of the action that will be performed. + Description *string `type:"string"` + + // Indicates if the current action is the default action. + IsDefaultAction *bool `type:"boolean"` + + // The remediation action that will be performed. + RemediationActionType *string `type:"string" enum:"RemediationActionType"` + + // The final state of the rule specified in the ViolationTarget after it is + // remediated. + RemediationResult *SecurityGroupRuleDescription `type:"structure"` +} + +// String returns the string representation +func (s SecurityGroupRemediationAction) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SecurityGroupRemediationAction) GoString() string { + return s.String() +} + +// SetDescription sets the Description field's value. +func (s *SecurityGroupRemediationAction) SetDescription(v string) *SecurityGroupRemediationAction { + s.Description = &v + return s +} + +// SetIsDefaultAction sets the IsDefaultAction field's value. +func (s *SecurityGroupRemediationAction) SetIsDefaultAction(v bool) *SecurityGroupRemediationAction { + s.IsDefaultAction = &v + return s +} + +// SetRemediationActionType sets the RemediationActionType field's value. +func (s *SecurityGroupRemediationAction) SetRemediationActionType(v string) *SecurityGroupRemediationAction { + s.RemediationActionType = &v + return s +} + +// SetRemediationResult sets the RemediationResult field's value. +func (s *SecurityGroupRemediationAction) SetRemediationResult(v *SecurityGroupRuleDescription) *SecurityGroupRemediationAction { + s.RemediationResult = v + return s +} + +// Describes a set of permissions for a security group rule. +type SecurityGroupRuleDescription struct { + _ struct{} `type:"structure"` + + // The start of the port range for the TCP and UDP protocols, or an ICMP/ICMPv6 + // type number. A value of -1 indicates all ICMP/ICMPv6 types. + FromPort *int64 `type:"long"` + + // The IPv4 ranges for the security group rule. + IPV4Range *string `type:"string"` + + // The IPv6 ranges for the security group rule. + IPV6Range *string `type:"string"` + + // The ID of the prefix list for the security group rule. + PrefixListId *string `min:"1" type:"string"` + + // The IP protocol name (tcp, udp, icmp, icmpv6) or number. + Protocol *string `type:"string"` + + // The end of the port range for the TCP and UDP protocols, or an ICMP/ICMPv6 + // code. A value of -1 indicates all ICMP/ICMPv6 codes. + ToPort *int64 `type:"long"` +} + +// String returns the string representation +func (s SecurityGroupRuleDescription) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SecurityGroupRuleDescription) GoString() string { + return s.String() +} + +// SetFromPort sets the FromPort field's value. +func (s *SecurityGroupRuleDescription) SetFromPort(v int64) *SecurityGroupRuleDescription { + s.FromPort = &v + return s +} + +// SetIPV4Range sets the IPV4Range field's value. +func (s *SecurityGroupRuleDescription) SetIPV4Range(v string) *SecurityGroupRuleDescription { + s.IPV4Range = &v + return s +} + +// SetIPV6Range sets the IPV6Range field's value. +func (s *SecurityGroupRuleDescription) SetIPV6Range(v string) *SecurityGroupRuleDescription { + s.IPV6Range = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *SecurityGroupRuleDescription) SetPrefixListId(v string) *SecurityGroupRuleDescription { + s.PrefixListId = &v + return s +} + +// SetProtocol sets the Protocol field's value. +func (s *SecurityGroupRuleDescription) SetProtocol(v string) *SecurityGroupRuleDescription { + s.Protocol = &v + return s +} + +// SetToPort sets the ToPort field's value. +func (s *SecurityGroupRuleDescription) SetToPort(v int64) *SecurityGroupRuleDescription { + s.ToPort = &v + return s +} + // Details about the security service that is being used to protect the resources. type SecurityServicePolicyData struct { _ struct{} `type:"structure"` @@ -3901,7 +6321,7 @@ type SecurityServicePolicyData struct { // Details about the service that are specific to the service type, in JSON // format. For service type SHIELD_ADVANCED, this is an empty string. // - // * Example: WAFV2 "ManagedServiceData": "{\"type\":\"WAFV2\",\"defaultAction\":{\"type\":\"ALLOW\"},\"preProcessRuleGroups\":[{\"managedRuleGroupIdentifier\":null,\"ruleGroupArn\":\"rulegrouparn\",\"overrideAction\":{\"type\":\"COUNT\"},\"excludedRules\":[{\"name\":\"EntityName\"}],\"ruleGroupType\":\"RuleGroup\"}],\"postProcessRuleGroups\":[{\"managedRuleGroupIdentifier\":{\"managedRuleGroupName\":\"AWSManagedRulesAdminProtectionRuleSet\",\"vendor\":\"AWS\"},\"ruleGroupArn\":\"rulegrouparn\",\"overrideAction\":{\"type\":\"NONE\"},\"excludedRules\":[],\"ruleGroupType\":\"ManagedRuleGroup\"}],\"overrideCustomerWebACLAssociation\":false}" + // * Example: WAFV2 "ManagedServiceData": "{\"type\":\"WAFV2\",\"defaultAction\":{\"type\":\"ALLOW\"},\"preProcessRuleGroups\":[{\"managedRuleGroupIdentifier\":null,\"ruleGroupArn\":\"rulegrouparn\",\"overrideAction\":{\"type\":\"COUNT\"},\"excludeRules\":[{\"name\":\"EntityName\"}],\"ruleGroupType\":\"RuleGroup\"}],\"postProcessRuleGroups\":[{\"managedRuleGroupIdentifier\":{\"managedRuleGroupName\":\"AWSManagedRulesAdminProtectionRuleSet\",\"vendorName\":\"AWS\"},\"ruleGroupArn\":\"rulegrouparn\",\"overrideAction\":{\"type\":\"NONE\"},\"excludeRules\":[],\"ruleGroupType\":\"ManagedRuleGroup\"}],\"overrideCustomerWebACLAssociation\":false}" // // * Example: WAF Classic "ManagedServiceData": "{\"type\": \"WAF\", \"ruleGroups\": // [{\"id\": \"12345678-1bcd-9012-efga-0987654321ab\", \"overrideAction\" @@ -4037,8 +6457,9 @@ func (s *Tag) SetValue(v string) *Tag { type TagResourceInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. The Firewall Manager policy - // is the only AWS resource that supports tagging, so this ARN is a policy ARN. + // The Amazon Resource Name (ARN) of the resource to return tags for. The AWS + // Firewall Manager resources that support tagging are policies, applications + // lists, and protocols lists. // // ResourceArn is a required field ResourceArn *string `min:"1" type:"string" required:"true"` @@ -4117,8 +6538,9 @@ func (s TagResourceOutput) GoString() string { type UntagResourceInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. The Firewall Manager policy - // is the only AWS resource that supports tagging, so this ARN is a policy ARN. + // The Amazon Resource Name (ARN) of the resource to return tags for. The AWS + // Firewall Manager resources that support tagging are policies, applications + // lists, and protocols lists. // // ResourceArn is a required field ResourceArn *string `min:"1" type:"string" required:"true"` @@ -4184,6 +6606,96 @@ func (s UntagResourceOutput) GoString() string { return s.String() } +// Violations for a resource based on the specified AWS Firewall Manager policy +// and AWS account. +type ViolationDetail struct { + _ struct{} `type:"structure"` + + // The AWS account that the violation details were requested for. + // + // MemberAccount is a required field + MemberAccount *string `min:"1" type:"string" required:"true"` + + // The ID of the AWS Firewall Manager policy that the violation details were + // requested for. + // + // PolicyId is a required field + PolicyId *string `min:"36" type:"string" required:"true"` + + // Brief description for the requested resource. + ResourceDescription *string `type:"string"` + + // The resource ID that the violation details were requested for. + // + // ResourceId is a required field + ResourceId *string `min:"1" type:"string" required:"true"` + + // The ResourceTag objects associated with the resource. + ResourceTags []*Tag `type:"list"` + + // The resource type that the violation details were requested for. + // + // ResourceType is a required field + ResourceType *string `min:"1" type:"string" required:"true"` + + // List of violations for the requested resource. + // + // ResourceViolations is a required field + ResourceViolations []*ResourceViolation `type:"list" required:"true"` +} + +// String returns the string representation +func (s ViolationDetail) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ViolationDetail) GoString() string { + return s.String() +} + +// SetMemberAccount sets the MemberAccount field's value. +func (s *ViolationDetail) SetMemberAccount(v string) *ViolationDetail { + s.MemberAccount = &v + return s +} + +// SetPolicyId sets the PolicyId field's value. +func (s *ViolationDetail) SetPolicyId(v string) *ViolationDetail { + s.PolicyId = &v + return s +} + +// SetResourceDescription sets the ResourceDescription field's value. +func (s *ViolationDetail) SetResourceDescription(v string) *ViolationDetail { + s.ResourceDescription = &v + return s +} + +// SetResourceId sets the ResourceId field's value. +func (s *ViolationDetail) SetResourceId(v string) *ViolationDetail { + s.ResourceId = &v + return s +} + +// SetResourceTags sets the ResourceTags field's value. +func (s *ViolationDetail) SetResourceTags(v []*Tag) *ViolationDetail { + s.ResourceTags = v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *ViolationDetail) SetResourceType(v string) *ViolationDetail { + s.ResourceType = &v + return s +} + +// SetResourceViolations sets the ResourceViolations field's value. +func (s *ViolationDetail) SetResourceViolations(v []*ResourceViolation) *ViolationDetail { + s.ResourceViolations = v + return s +} + const ( // AccountRoleStatusReady is a AccountRoleStatus enum value AccountRoleStatusReady = "READY" @@ -4201,6 +6713,17 @@ const ( AccountRoleStatusDeleted = "DELETED" ) +// AccountRoleStatus_Values returns all elements of the AccountRoleStatus enum +func AccountRoleStatus_Values() []string { + return []string{ + AccountRoleStatusReady, + AccountRoleStatusCreating, + AccountRoleStatusPendingDeletion, + AccountRoleStatusDeleting, + AccountRoleStatusDeleted, + } +} + const ( // CustomerPolicyScopeIdTypeAccount is a CustomerPolicyScopeIdType enum value CustomerPolicyScopeIdTypeAccount = "ACCOUNT" @@ -4209,6 +6732,14 @@ const ( CustomerPolicyScopeIdTypeOrgUnit = "ORG_UNIT" ) +// CustomerPolicyScopeIdType_Values returns all elements of the CustomerPolicyScopeIdType enum +func CustomerPolicyScopeIdType_Values() []string { + return []string{ + CustomerPolicyScopeIdTypeAccount, + CustomerPolicyScopeIdTypeOrgUnit, + } +} + const ( // DependentServiceNameAwsconfig is a DependentServiceName enum value DependentServiceNameAwsconfig = "AWSCONFIG" @@ -4223,6 +6754,16 @@ const ( DependentServiceNameAwsvpc = "AWSVPC" ) +// DependentServiceName_Values returns all elements of the DependentServiceName enum +func DependentServiceName_Values() []string { + return []string{ + DependentServiceNameAwsconfig, + DependentServiceNameAwswaf, + DependentServiceNameAwsshieldAdvanced, + DependentServiceNameAwsvpc, + } +} + const ( // PolicyComplianceStatusTypeCompliant is a PolicyComplianceStatusType enum value PolicyComplianceStatusTypeCompliant = "COMPLIANT" @@ -4231,6 +6772,30 @@ const ( PolicyComplianceStatusTypeNonCompliant = "NON_COMPLIANT" ) +// PolicyComplianceStatusType_Values returns all elements of the PolicyComplianceStatusType enum +func PolicyComplianceStatusType_Values() []string { + return []string{ + PolicyComplianceStatusTypeCompliant, + PolicyComplianceStatusTypeNonCompliant, + } +} + +const ( + // RemediationActionTypeRemove is a RemediationActionType enum value + RemediationActionTypeRemove = "REMOVE" + + // RemediationActionTypeModify is a RemediationActionType enum value + RemediationActionTypeModify = "MODIFY" +) + +// RemediationActionType_Values returns all elements of the RemediationActionType enum +func RemediationActionType_Values() []string { + return []string{ + RemediationActionTypeRemove, + RemediationActionTypeModify, + } +} + const ( // SecurityServiceTypeWaf is a SecurityServiceType enum value SecurityServiceTypeWaf = "WAF" @@ -4251,6 +6816,18 @@ const ( SecurityServiceTypeSecurityGroupsUsageAudit = "SECURITY_GROUPS_USAGE_AUDIT" ) +// SecurityServiceType_Values returns all elements of the SecurityServiceType enum +func SecurityServiceType_Values() []string { + return []string{ + SecurityServiceTypeWaf, + SecurityServiceTypeWafv2, + SecurityServiceTypeShieldAdvanced, + SecurityServiceTypeSecurityGroupsCommon, + SecurityServiceTypeSecurityGroupsContentAudit, + SecurityServiceTypeSecurityGroupsUsageAudit, + } +} + const ( // ViolationReasonWebAclMissingRuleGroup is a ViolationReason enum value ViolationReasonWebAclMissingRuleGroup = "WEB_ACL_MISSING_RULE_GROUP" @@ -4279,3 +6856,18 @@ const ( // ViolationReasonSecurityGroupRedundant is a ViolationReason enum value ViolationReasonSecurityGroupRedundant = "SECURITY_GROUP_REDUNDANT" ) + +// ViolationReason_Values returns all elements of the ViolationReason enum +func ViolationReason_Values() []string { + return []string{ + ViolationReasonWebAclMissingRuleGroup, + ViolationReasonResourceMissingWebAcl, + ViolationReasonResourceIncorrectWebAcl, + ViolationReasonResourceMissingShieldProtection, + ViolationReasonResourceMissingWebAclOrShieldProtection, + ViolationReasonResourceMissingSecurityGroup, + ViolationReasonResourceViolatesAuditSecurityGroup, + ViolationReasonSecurityGroupUnused, + ViolationReasonSecurityGroupRedundant, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/fms/errors.go b/vendor/github.com/aws/aws-sdk-go/service/fms/errors.go index 0fc209a4a74..fc0663349f0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/fms/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/fms/errors.go @@ -24,9 +24,12 @@ const ( // ErrCodeInvalidOperationException for service response error code // "InvalidOperationException". // - // The operation failed because there was nothing to do. For example, you might - // have submitted an AssociateAdminAccount request, but the account ID that - // you submitted was already set as the AWS Firewall Manager administrator. + // The operation failed because there was nothing to do or the operation wasn't + // possible. For example, you might have submitted an AssociateAdminAccount + // request for an account ID that was already set as the AWS Firewall Manager + // administrator. Or you might have tried to access a Region that's disabled + // by default, and that you need to enable for the Firewall Manager administrator + // account and for AWS Organizations before you can access it. ErrCodeInvalidOperationException = "InvalidOperationException" // ErrCodeInvalidTypeException for service response error code diff --git a/vendor/github.com/aws/aws-sdk-go/service/forecastservice/api.go b/vendor/github.com/aws/aws-sdk-go/service/forecastservice/api.go index e6425c8afb7..1fcdbefb290 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/forecastservice/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/forecastservice/api.go @@ -79,7 +79,7 @@ func (c *ForecastService) CreateDatasetRequest(input *CreateDatasetInput) (req * // To get a list of all your datasets, use the ListDatasets operation. // // For example Forecast datasets, see the Amazon Forecast Sample GitHub repository -// (https://github.com/aws-samples/amazon-forecast-samples/tree/master/data). +// (https://github.com/aws-samples/amazon-forecast-samples). // // The Status of a dataset must be ACTIVE before you can import training data. // Use the DescribeDataset operation to get the status. @@ -278,8 +278,9 @@ func (c *ForecastService) CreateDatasetImportJobRequest(input *CreateDatasetImpo // to import the data to. // // You must specify a DataSource object that includes an AWS Identity and Access -// Management (IAM) role that Amazon Forecast can assume to access the data. -// For more information, see aws-forecast-iam-roles. +// Management (IAM) role that Amazon Forecast can assume to access the data, +// as Amazon Forecast makes a copy of your data and processes it in an internal +// AWS system. For more information, see aws-forecast-iam-roles. // // The training data must be in CSV format. The delimiter must be a comma (,). // @@ -287,6 +288,12 @@ func (c *ForecastService) CreateDatasetImportJobRequest(input *CreateDatasetImpo // in the S3 bucket. For the latter two cases, Amazon Forecast imports all files // up to the limit of 10,000 files. // +// Because dataset imports are not aggregated, your most recent dataset import +// is the one that is used when training a predictor or generating a forecast. +// Make sure that your most recent dataset import contains all of the data you +// want to model off of, and not just the new data collected since the previous +// import. +// // To get a list of all your dataset import jobs, filtered by specified criteria, // use the ListDatasetImportJobs operation. // @@ -388,9 +395,8 @@ func (c *ForecastService) CreateForecastRequest(input *CreateForecastInput) (req // use the CreateForecastExportJob operation. // // The range of the forecast is determined by the ForecastHorizon value, which -// you specify in the CreatePredictor request, multiplied by the DataFrequency -// value, which you specify in the CreateDataset request. When you query a forecast, -// you can request a specific date range within the forecast. +// you specify in the CreatePredictor request. When you query a forecast, you +// can request a specific date range within the forecast. // // To get a list of all your forecasts, use the ListForecasts operation. // @@ -497,7 +503,7 @@ func (c *ForecastService) CreateForecastExportJobRequest(input *CreateForecastEx // Simple Storage Service (Amazon S3) bucket. The forecast file name will match // the following conventions: // -// __ +// __ // // where the component is in Java SimpleDateFormat (yyyy-MM-ddTHH-mm-ssZ). // @@ -748,6 +754,10 @@ func (c *ForecastService) DeleteDatasetRequest(input *DeleteDatasetInput) (req * // operation. You can only delete datasets that have a status of ACTIVE or CREATE_FAILED. // To get the status use the DescribeDataset operation. // +// Forecast does not automatically update any dataset groups that contain the +// deleted dataset. In order to update the dataset group, use the operation, +// omitting the deleted dataset's 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. @@ -2791,6 +2801,266 @@ func (c *ForecastService) ListPredictorsPagesWithContext(ctx aws.Context, input return p.Err() } +const opListTagsForResource = "ListTagsForResource" + +// ListTagsForResourceRequest generates a "aws/request.Request" representing the +// client's request for the ListTagsForResource operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListTagsForResource for more information on using the ListTagsForResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListTagsForResourceRequest method. +// req, resp := client.ListTagsForResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/forecast-2018-06-26/ListTagsForResource +func (c *ForecastService) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { + op := &request.Operation{ + Name: opListTagsForResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListTagsForResourceInput{} + } + + output = &ListTagsForResourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListTagsForResource API operation for Amazon Forecast Service. +// +// Lists the tags for an Amazon Forecast 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 Amazon Forecast Service's +// API operation ListTagsForResource for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// We can't find a resource with that Amazon Resource Name (ARN). Check the +// ARN and try again. +// +// * InvalidInputException +// We can't process the request because it includes an invalid value or a value +// that exceeds the valid range. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/forecast-2018-06-26/ListTagsForResource +func (c *ForecastService) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + 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 *ForecastService) 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 = "TagResource" + +// TagResourceRequest generates a "aws/request.Request" representing the +// client's request for the TagResource operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See TagResource for more information on using the TagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the TagResourceRequest method. +// req, resp := client.TagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/forecast-2018-06-26/TagResource +func (c *ForecastService) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { + op := &request.Operation{ + Name: opTagResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &TagResourceInput{} + } + + output = &TagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// TagResource API operation for Amazon Forecast Service. +// +// Associates the specified tags to a resource with the specified resourceArn. +// If existing tags on a resource are not specified in the request parameters, +// they are not changed. When a resource is deleted, the tags associated with +// that resource are also deleted. +// +// Returns awserr.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 Forecast Service's +// API operation TagResource for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// We can't find a resource with that Amazon Resource Name (ARN). Check the +// ARN and try again. +// +// * LimitExceededException +// The limit on the number of resources per account has been exceeded. +// +// * InvalidInputException +// We can't process the request because it includes an invalid value or a value +// that exceeds the valid range. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/forecast-2018-06-26/TagResource +func (c *ForecastService) 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 *ForecastService) 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 will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UntagResource for more information on using the UntagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UntagResourceRequest method. +// req, resp := client.UntagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/forecast-2018-06-26/UntagResource +func (c *ForecastService) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { + op := &request.Operation{ + Name: opUntagResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UntagResourceInput{} + } + + output = &UntagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UntagResource API operation for Amazon Forecast Service. +// +// Deletes the specified tags from 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 Amazon Forecast Service's +// API operation UntagResource for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// We can't find a resource with that Amazon Resource Name (ARN). Check the +// ARN and try again. +// +// * InvalidInputException +// We can't process the request because it includes an invalid value or a value +// that exceeds the valid range. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/forecast-2018-06-26/UntagResource +func (c *ForecastService) 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 *ForecastService) 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 opUpdateDatasetGroup = "UpdateDatasetGroup" // UpdateDatasetGroupRequest generates a "aws/request.Request" representing the @@ -3076,6 +3346,37 @@ type CreateDatasetGroupInput struct { // // Domain is a required field Domain *string `type:"string" required:"true" enum:"Domain"` + + // The optional metadata that you apply to the dataset group to help you categorize + // and organize them. Each tag consists of a key and an optional value, both + // of which you define. + // + // The following basic restrictions apply to tags: + // + // * Maximum number of tags per resource - 50. + // + // * For each resource, each tag key must be unique, and each tag key can + // have only one value. + // + // * Maximum key length - 128 Unicode characters in UTF-8. + // + // * Maximum value length - 256 Unicode characters in UTF-8. + // + // * If your tagging schema is used across multiple services and resources, + // remember that other services may have restrictions on allowed characters. + // Generally allowed characters are: letters, numbers, and spaces representable + // in UTF-8, and the following characters: + - = . _ : / @. + // + // * Tag keys and values are case sensitive. + // + // * Do not use aws:, AWS:, or any upper or lowercase combination of such + // as a prefix for keys as it is reserved for AWS use. You cannot edit or + // delete tag keys with this prefix. Values can have this prefix. If a tag + // value has aws as its prefix but the key does not, then Forecast considers + // it to be a user tag and will count against the limit of 50 tags. Tags + // with only the key prefix of aws do not count against your tags per resource + // limit. + Tags []*Tag `type:"list"` } // String returns the string representation @@ -3100,6 +3401,16 @@ func (s *CreateDatasetGroupInput) Validate() error { if s.Domain == nil { invalidParams.Add(request.NewErrParamRequired("Domain")) } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -3125,6 +3436,12 @@ func (s *CreateDatasetGroupInput) SetDomain(v string) *CreateDatasetGroupInput { return s } +// SetTags sets the Tags field's value. +func (s *CreateDatasetGroupInput) SetTags(v []*Tag) *CreateDatasetGroupInput { + s.Tags = v + return s +} + type CreateDatasetGroupOutput struct { _ struct{} `type:"structure"` @@ -3176,6 +3493,37 @@ type CreateDatasetImportJobInput struct { // DatasetImportJobName is a required field DatasetImportJobName *string `min:"1" type:"string" required:"true"` + // The optional metadata that you apply to the dataset import job to help you + // categorize and organize them. Each tag consists of a key and an optional + // value, both of which you define. + // + // The following basic restrictions apply to tags: + // + // * Maximum number of tags per resource - 50. + // + // * For each resource, each tag key must be unique, and each tag key can + // have only one value. + // + // * Maximum key length - 128 Unicode characters in UTF-8. + // + // * Maximum value length - 256 Unicode characters in UTF-8. + // + // * If your tagging schema is used across multiple services and resources, + // remember that other services may have restrictions on allowed characters. + // Generally allowed characters are: letters, numbers, and spaces representable + // in UTF-8, and the following characters: + - = . _ : / @. + // + // * Tag keys and values are case sensitive. + // + // * Do not use aws:, AWS:, or any upper or lowercase combination of such + // as a prefix for keys as it is reserved for AWS use. You cannot edit or + // delete tag keys with this prefix. Values can have this prefix. If a tag + // value has aws as its prefix but the key does not, then Forecast considers + // it to be a user tag and will count against the limit of 50 tags. Tags + // with only the key prefix of aws do not count against your tags per resource + // limit. + Tags []*Tag `type:"list"` + // The format of timestamps in the dataset. The format that you specify depends // on the DataFrequency specified when the dataset was created. The following // formats are supported @@ -3220,6 +3568,16 @@ func (s *CreateDatasetImportJobInput) Validate() error { invalidParams.AddNested("DataSource", err.(request.ErrInvalidParams)) } } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -3245,6 +3603,12 @@ func (s *CreateDatasetImportJobInput) SetDatasetImportJobName(v string) *CreateD return s } +// SetTags sets the Tags field's value. +func (s *CreateDatasetImportJobInput) SetTags(v []*Tag) *CreateDatasetImportJobInput { + s.Tags = v + return s +} + // SetTimestampFormat sets the TimestampFormat field's value. func (s *CreateDatasetImportJobInput) SetTimestampFormat(v string) *CreateDatasetImportJobInput { s.TimestampFormat = &v @@ -3320,6 +3684,37 @@ type CreateDatasetInput struct { // // Schema is a required field Schema *Schema `type:"structure" required:"true"` + + // The optional metadata that you apply to the dataset to help you categorize + // and organize them. Each tag consists of a key and an optional value, both + // of which you define. + // + // The following basic restrictions apply to tags: + // + // * Maximum number of tags per resource - 50. + // + // * For each resource, each tag key must be unique, and each tag key can + // have only one value. + // + // * Maximum key length - 128 Unicode characters in UTF-8. + // + // * Maximum value length - 256 Unicode characters in UTF-8. + // + // * If your tagging schema is used across multiple services and resources, + // remember that other services may have restrictions on allowed characters. + // Generally allowed characters are: letters, numbers, and spaces representable + // in UTF-8, and the following characters: + - = . _ : / @. + // + // * Tag keys and values are case sensitive. + // + // * Do not use aws:, AWS:, or any upper or lowercase combination of such + // as a prefix for keys as it is reserved for AWS use. You cannot edit or + // delete tag keys with this prefix. Values can have this prefix. If a tag + // value has aws as its prefix but the key does not, then Forecast considers + // it to be a user tag and will count against the limit of 50 tags. Tags + // with only the key prefix of aws do not count against your tags per resource + // limit. + Tags []*Tag `type:"list"` } // String returns the string representation @@ -3360,6 +3755,16 @@ func (s *CreateDatasetInput) Validate() error { invalidParams.AddNested("Schema", err.(request.ErrInvalidParams)) } } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -3403,6 +3808,12 @@ func (s *CreateDatasetInput) SetSchema(v *Schema) *CreateDatasetInput { return s } +// SetTags sets the Tags field's value. +func (s *CreateDatasetInput) SetTags(v []*Tag) *CreateDatasetInput { + s.Tags = v + return s +} + type CreateDatasetOutput struct { _ struct{} `type:"structure"` @@ -3449,10 +3860,41 @@ type CreateForecastExportJobInput struct { // // ForecastExportJobName is a required field ForecastExportJobName *string `min:"1" type:"string" required:"true"` -} -// String returns the string representation -func (s CreateForecastExportJobInput) String() string { + // The optional metadata that you apply to the forecast export job to help you + // categorize and organize them. Each tag consists of a key and an optional + // value, both of which you define. + // + // The following basic restrictions apply to tags: + // + // * Maximum number of tags per resource - 50. + // + // * For each resource, each tag key must be unique, and each tag key can + // have only one value. + // + // * Maximum key length - 128 Unicode characters in UTF-8. + // + // * Maximum value length - 256 Unicode characters in UTF-8. + // + // * If your tagging schema is used across multiple services and resources, + // remember that other services may have restrictions on allowed characters. + // Generally allowed characters are: letters, numbers, and spaces representable + // in UTF-8, and the following characters: + - = . _ : / @. + // + // * Tag keys and values are case sensitive. + // + // * Do not use aws:, AWS:, or any upper or lowercase combination of such + // as a prefix for keys as it is reserved for AWS use. You cannot edit or + // delete tag keys with this prefix. Values can have this prefix. If a tag + // value has aws as its prefix but the key does not, then Forecast considers + // it to be a user tag and will count against the limit of 50 tags. Tags + // with only the key prefix of aws do not count against your tags per resource + // limit. + Tags []*Tag `type:"list"` +} + +// String returns the string representation +func (s CreateForecastExportJobInput) String() string { return awsutil.Prettify(s) } @@ -3481,6 +3923,16 @@ func (s *CreateForecastExportJobInput) Validate() error { invalidParams.AddNested("Destination", err.(request.ErrInvalidParams)) } } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -3506,6 +3958,12 @@ func (s *CreateForecastExportJobInput) SetForecastExportJobName(v string) *Creat return s } +// SetTags sets the Tags field's value. +func (s *CreateForecastExportJobInput) SetTags(v []*Tag) *CreateForecastExportJobInput { + s.Tags = v + return s +} + type CreateForecastExportJobOutput struct { _ struct{} `type:"structure"` @@ -3537,17 +3995,48 @@ type CreateForecastInput struct { // ForecastName is a required field ForecastName *string `min:"1" type:"string" required:"true"` - // The quantiles at which probabilistic forecasts are generated. You can specify - // up to 5 quantiles per forecast. Accepted values include 0.01 to 0.99 (increments - // of .01 only) and mean. The mean forecast is different from the median (0.50) - // when the distribution is not symmetric (e.g. Beta, Negative Binomial). The - // default value is ["0.1", "0.5", "0.9"]. + // The quantiles at which probabilistic forecasts are generated. You can currently + // specify up to 5 quantiles per forecast. Accepted values include 0.01 to 0.99 + // (increments of .01 only) and mean. The mean forecast is different from the + // median (0.50) when the distribution is not symmetric (for example, Beta and + // Negative Binomial). The default value is ["0.1", "0.5", "0.9"]. ForecastTypes []*string `min:"1" type:"list"` // The Amazon Resource Name (ARN) of the predictor to use to generate the forecast. // // PredictorArn is a required field PredictorArn *string `type:"string" required:"true"` + + // The optional metadata that you apply to the forecast to help you categorize + // and organize them. Each tag consists of a key and an optional value, both + // of which you define. + // + // The following basic restrictions apply to tags: + // + // * Maximum number of tags per resource - 50. + // + // * For each resource, each tag key must be unique, and each tag key can + // have only one value. + // + // * Maximum key length - 128 Unicode characters in UTF-8. + // + // * Maximum value length - 256 Unicode characters in UTF-8. + // + // * If your tagging schema is used across multiple services and resources, + // remember that other services may have restrictions on allowed characters. + // Generally allowed characters are: letters, numbers, and spaces representable + // in UTF-8, and the following characters: + - = . _ : / @. + // + // * Tag keys and values are case sensitive. + // + // * Do not use aws:, AWS:, or any upper or lowercase combination of such + // as a prefix for keys as it is reserved for AWS use. You cannot edit or + // delete tag keys with this prefix. Values can have this prefix. If a tag + // value has aws as its prefix but the key does not, then Forecast considers + // it to be a user tag and will count against the limit of 50 tags. Tags + // with only the key prefix of aws do not count against your tags per resource + // limit. + Tags []*Tag `type:"list"` } // String returns the string representation @@ -3575,6 +4064,16 @@ func (s *CreateForecastInput) Validate() error { if s.PredictorArn == nil { invalidParams.Add(request.NewErrParamRequired("PredictorArn")) } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -3600,6 +4099,12 @@ func (s *CreateForecastInput) SetPredictorArn(v string) *CreateForecastInput { return s } +// SetTags sets the Tags field's value. +func (s *CreateForecastInput) SetTags(v []*Tag) *CreateForecastInput { + s.Tags = v + return s +} + type CreateForecastOutput struct { _ struct{} `type:"structure"` @@ -3719,6 +4224,37 @@ type CreatePredictorInput struct { // PredictorName is a required field PredictorName *string `min:"1" type:"string" required:"true"` + // The optional metadata that you apply to the predictor to help you categorize + // and organize them. Each tag consists of a key and an optional value, both + // of which you define. + // + // The following basic restrictions apply to tags: + // + // * Maximum number of tags per resource - 50. + // + // * For each resource, each tag key must be unique, and each tag key can + // have only one value. + // + // * Maximum key length - 128 Unicode characters in UTF-8. + // + // * Maximum value length - 256 Unicode characters in UTF-8. + // + // * If your tagging schema is used across multiple services and resources, + // remember that other services may have restrictions on allowed characters. + // Generally allowed characters are: letters, numbers, and spaces representable + // in UTF-8, and the following characters: + - = . _ : / @. + // + // * Tag keys and values are case sensitive. + // + // * Do not use aws:, AWS:, or any upper or lowercase combination of such + // as a prefix for keys as it is reserved for AWS use. You cannot edit or + // delete tag keys with this prefix. Values can have this prefix. If a tag + // value has aws as its prefix but the key does not, then Forecast considers + // it to be a user tag and will count against the limit of 50 tags. Tags + // with only the key prefix of aws do not count against your tags per resource + // limit. + Tags []*Tag `type:"list"` + // The hyperparameters to override for model training. The hyperparameters that // you can override are listed in the individual algorithms. For the list of // supported algorithms, see aws-forecast-choosing-recipes. @@ -3773,6 +4309,16 @@ func (s *CreatePredictorInput) Validate() error { invalidParams.AddNested("InputDataConfig", err.(request.ErrInvalidParams)) } } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -3840,6 +4386,12 @@ func (s *CreatePredictorInput) SetPredictorName(v string) *CreatePredictorInput return s } +// SetTags sets the Tags field's value. +func (s *CreatePredictorInput) SetTags(v []*Tag) *CreatePredictorInput { + s.Tags = v + return s +} + // SetTrainingParameters sets the TrainingParameters field's value. func (s *CreatePredictorInput) SetTrainingParameters(v map[string]*string) *CreatePredictorInput { s.TrainingParameters = v @@ -5170,7 +5722,7 @@ type DescribeForecastOutput struct { // The name of the forecast. ForecastName *string `min:"1" type:"string"` - // The quantiles at which proababilistic forecasts were generated. + // The quantiles at which probabilistic forecasts were generated. ForecastTypes []*string `min:"1" type:"list"` // Initially, the same as CreationTime (status is CREATE_PENDING). Updated when @@ -5673,9 +6225,10 @@ type Featurization struct { _ struct{} `type:"structure"` // The name of the schema attribute that specifies the data field to be featurized. - // Only the target field of the TARGET_TIME_SERIES dataset type is supported. - // For example, for the RETAIL domain, the target is demand, and for the CUSTOM - // domain, the target is target_value. + // Amazon Forecast supports the target field of the TARGET_TIME_SERIES and the + // RELATED_TIME_SERIES datasets. For example, for the RETAIL domain, the target + // is demand, and for the CUSTOM domain, the target is target_value. For more + // information, see howitworks-missing-values. // // AttributeName is a required field AttributeName *string `min:"1" type:"string" required:"true"` @@ -5744,8 +6297,8 @@ func (s *Featurization) SetFeaturizationPipeline(v []*FeaturizationMethod) *Feat // You define featurization using the FeaturizationConfig object. You specify // an array of transformations, one for each field that you want to featurize. // You then include the FeaturizationConfig object in your CreatePredictor request. -// Amazon Forecast applies the featurization to the TARGET_TIME_SERIES dataset -// before model training. +// Amazon Forecast applies the featurization to the TARGET_TIME_SERIES and RELATED_TIME_SERIES +// datasets before model training. // // You can create multiple featurization configurations. For example, you might // call the CreatePredictor operation twice by specifying different featurization @@ -5754,7 +6307,7 @@ type FeaturizationConfig struct { _ struct{} `type:"structure"` // An array of featurization (transformation) information for the fields of - // a dataset. Only a single featurization is supported. + // a dataset. Featurizations []*Featurization `min:"1" type:"list"` // An array of dimension (field) names that specify how to group the generated @@ -5847,8 +6400,7 @@ func (s *FeaturizationConfig) SetForecastFrequency(v string) *FeaturizationConfi // Provides information about the method that featurizes (transforms) a dataset // field. The method is part of the FeaturizationPipeline of the Featurization -// object. If you don't specify FeaturizationMethodParameters, Amazon Forecast -// uses default parameters. +// object. // // The following is an example of how you specify a FeaturizationMethod object. // @@ -5856,7 +6408,8 @@ func (s *FeaturizationConfig) SetForecastFrequency(v string) *FeaturizationConfi // // "FeaturizationMethodName": "filling", // -// "FeaturizationMethodParameters": {"aggregation": "avg", "backfill": "nan"} +// "FeaturizationMethodParameters": {"aggregation": "sum", "middlefill": "zero", +// "backfill": "zero"} // // } type FeaturizationMethod struct { @@ -5867,17 +6420,30 @@ type FeaturizationMethod struct { // FeaturizationMethodName is a required field FeaturizationMethodName *string `type:"string" required:"true" enum:"FeaturizationMethodName"` - // The method parameters (key-value pairs). Specify these parameters to override - // the default values. The following list shows the parameters and their valid - // values. Bold signifies the default value. + // The method parameters (key-value pairs), which are a map of override parameters. + // Specify these parameters to override the default values. Related Time Series + // attributes do not accept aggregation parameters. + // + // The following list shows the parameters and their valid values for the "filling" + // featurization method for a Target Time Series dataset. Bold signifies the + // default value. // // * aggregation: sum, avg, first, min, max // // * frontfill: none // - // * middlefill: zero, nan (not a number) + // * middlefill: zero, nan (not a number), value, median, mean, min, max + // + // * backfill: zero, nan, value, median, mean, min, max + // + // The following list shows the parameters and their valid values for a Related + // Time Series featurization method (there are no defaults): // - // * backfill: zero, nan + // * middlefill: zero, value, median, mean, min, max + // + // * backfill: zero, value, median, mean, min, max + // + // * futurefill: zero, value, median, mean, min, max FeaturizationMethodParameters map[string]*string `min:"1" type:"map"` } @@ -7286,6 +7852,70 @@ func (s *ListPredictorsOutput) SetPredictors(v []*PredictorSummary) *ListPredict return s } +type ListTagsForResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that identifies the resource for which to + // list the tags. Currently, the supported resources are Forecast dataset groups, + // datasets, dataset import jobs, predictors, forecasts, and forecast export + // jobs. + // + // ResourceArn is a required field + ResourceArn *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s ListTagsForResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsForResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTagsForResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResourceInput { + s.ResourceArn = &v + return s +} + +type ListTagsForResourceOutput struct { + _ struct{} `type:"structure"` + + // The tags for the resource. + Tags []*Tag `type:"list"` +} + +// String returns the string representation +func (s ListTagsForResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsForResourceOutput) GoString() string { + return s.String() +} + +// SetTags sets the Tags field's value. +func (s *ListTagsForResourceOutput) SetTags(v []*Tag) *ListTagsForResourceOutput { + s.Tags = v + return s +} + // Provides metrics that are used to evaluate the performance of a predictor. // This object is part of the WindowSummary object. type Metrics struct { @@ -7821,7 +8451,7 @@ type Schema struct { _ struct{} `type:"structure"` // An array of attributes specifying the name and type of each field in a dataset. - Attributes []*SchemaAttribute `type:"list"` + Attributes []*SchemaAttribute `min:"1" type:"list"` } // String returns the string representation @@ -7837,6 +8467,9 @@ func (s Schema) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *Schema) Validate() error { invalidParams := request.ErrInvalidParams{Context: "Schema"} + if s.Attributes != nil && len(s.Attributes) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Attributes", 1)) + } if s.Attributes != nil { for i, v := range s.Attributes { if v == nil { @@ -8003,6 +8636,35 @@ func (s *Statistics) SetStddev(v float64) *Statistics { // all data in the datasets should belong to the same country as the calendar. // For the holiday calendar data, see the Jollyday (http://jollyday.sourceforge.net/data.html) // web site. +// +// India and Korea's holidays are not included in the Jollyday library, but +// both are supported by Amazon Forecast. Their holidays are: +// +// "IN" - INDIA +// +// * JANUARY 26 - REPUBLIC DAY +// +// * AUGUST 15 - INDEPENDENCE DAY +// +// * OCTOBER 2 GANDHI'S BIRTHDAY +// +// "KR" - KOREA +// +// * JANUARY 1 - NEW YEAR +// +// * MARCH 1 - INDEPENDENCE MOVEMENT DAY +// +// * MAY 5 - CHILDREN'S DAY +// +// * JUNE 6 - MEMORIAL DAY +// +// * AUGUST 15 - LIBERATION DAY +// +// * OCTOBER 3 - NATIONAL FOUNDATION DAY +// +// * OCTOBER 9 - HANGEUL DAY +// +// * DECEMBER 25 - CHRISTMAS DAY type SupplementaryFeature struct { _ struct{} `type:"structure"` @@ -8013,15 +8675,69 @@ type SupplementaryFeature struct { // One of the following 2 letter country codes: // + // * "AR" - ARGENTINA + // + // * "AT" - AUSTRIA + // // * "AU" - AUSTRALIA // + // * "BE" - BELGIUM + // + // * "BR" - BRAZIL + // + // * "CA" - CANADA + // + // * "CN" - CHINA + // + // * "CZ" - CZECH REPUBLIC + // + // * "DK" - DENMARK + // + // * "EC" - ECUADOR + // + // * "FI" - FINLAND + // + // * "FR" - FRANCE + // // * "DE" - GERMANY // + // * "HU" - HUNGARY + // + // * "IE" - IRELAND + // + // * "IN" - INDIA + // + // * "IT" - ITALY + // // * "JP" - JAPAN // - // * "US" - UNITED_STATES + // * "KR" - KOREA + // + // * "LU" - LUXEMBOURG + // + // * "MX" - MEXICO + // + // * "NL" - NETHERLANDS // - // * "UK" - UNITED_KINGDOM + // * "NO" - NORWAY + // + // * "PL" - POLAND + // + // * "PT" - PORTUGAL + // + // * "RU" - RUSSIA + // + // * "ZA" - SOUTH AFRICA + // + // * "ES" - SPAIN + // + // * "SE" - SWEDEN + // + // * "CH" - SWITZERLAND + // + // * "US" - UNITED STATES + // + // * "UK" - UNITED KINGDOM // // Value is a required field Value *string `type:"string" required:"true"` @@ -8068,6 +8784,197 @@ func (s *SupplementaryFeature) SetValue(v string) *SupplementaryFeature { return s } +// The optional metadata that you apply to a resource to help you categorize +// and organize them. Each tag consists of a key and an optional value, both +// of which you define. +// +// The following basic restrictions apply to tags: +// +// * Maximum number of tags per resource - 50. +// +// * For each resource, each tag key must be unique, and each tag key can +// have only one value. +// +// * Maximum key length - 128 Unicode characters in UTF-8. +// +// * Maximum value length - 256 Unicode characters in UTF-8. +// +// * If your tagging schema is used across multiple services and resources, +// remember that other services may have restrictions on allowed characters. +// Generally allowed characters are: letters, numbers, and spaces representable +// in UTF-8, and the following characters: + - = . _ : / @. +// +// * Tag keys and values are case sensitive. +// +// * Do not use aws:, AWS:, or any upper or lowercase combination of such +// as a prefix for keys as it is reserved for AWS use. You cannot edit or +// delete tag keys with this prefix. Values can have this prefix. If a tag +// value has aws as its prefix but the key does not, then Forecast considers +// it to be a user tag and will count against the limit of 50 tags. Tags +// with only the key prefix of aws do not count against your tags per resource +// limit. +type Tag struct { + _ struct{} `type:"structure"` + + // One part of a key-value pair that makes up a tag. A key is a general label + // that acts like a category for more specific tag values. + // + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` + + // The optional part of a key-value pair that makes up a tag. A value acts as + // a descriptor within a tag category (key). + // + // Value is a required field + Value *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s Tag) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Tag) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Tag) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Tag"} + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + if s.Value == nil { + invalidParams.Add(request.NewErrParamRequired("Value")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKey sets the Key field's value. +func (s *Tag) SetKey(v string) *Tag { + s.Key = &v + return s +} + +// SetValue sets the Value field's value. +func (s *Tag) SetValue(v string) *Tag { + s.Value = &v + return s +} + +type TagResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that identifies the resource for which to + // list the tags. Currently, the supported resources are Forecast dataset groups, + // datasets, dataset import jobs, predictors, forecasts, and forecast export + // jobs. + // + // ResourceArn is a required field + ResourceArn *string `type:"string" required:"true"` + + // The tags to add to the resource. A tag is an array of key-value pairs. + // + // The following basic restrictions apply to tags: + // + // * Maximum number of tags per resource - 50. + // + // * For each resource, each tag key must be unique, and each tag key can + // have only one value. + // + // * Maximum key length - 128 Unicode characters in UTF-8. + // + // * Maximum value length - 256 Unicode characters in UTF-8. + // + // * If your tagging schema is used across multiple services and resources, + // remember that other services may have restrictions on allowed characters. + // Generally allowed characters are: letters, numbers, and spaces representable + // in UTF-8, and the following characters: + - = . _ : / @. + // + // * Tag keys and values are case sensitive. + // + // * Do not use aws:, AWS:, or any upper or lowercase combination of such + // as a prefix for keys as it is reserved for AWS use. You cannot edit or + // delete tag keys with this prefix. Values can have this prefix. If a tag + // value has aws as its prefix but the key does not, then Forecast considers + // it to be a user tag and will count against the limit of 50 tags. Tags + // with only the key prefix of aws do not count against your tags per resource + // limit. + // + // Tags is a required field + Tags []*Tag `type:"list" required:"true"` +} + +// String returns the string representation +func (s TagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *TagResourceInput) SetTags(v []*Tag) *TagResourceInput { + s.Tags = v + return s +} + +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 status, start time, and end time of a backtest, as well as a failure // reason if applicable. type TestWindowSummary struct { @@ -8126,6 +9033,74 @@ func (s *TestWindowSummary) SetTestWindowStart(v time.Time) *TestWindowSummary { return s } +type UntagResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that identifies the resource for which to + // list the tags. Currently, the supported resources are Forecast dataset groups, + // datasets, dataset import jobs, predictors, forecasts, and forecast exports. + // + // ResourceArn is a required field + ResourceArn *string `type:"string" required:"true"` + + // The keys of the tags to be removed. + // + // TagKeys is a required field + TagKeys []*string `type:"list" required:"true"` +} + +// String returns the string representation +func (s UntagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UntagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTagKeys sets the TagKeys field's value. +func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { + s.TagKeys = v + return s +} + +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 UpdateDatasetGroupInput struct { _ struct{} `type:"structure"` @@ -8312,6 +9287,16 @@ const ( AttributeTypeTimestamp = "timestamp" ) +// AttributeType_Values returns all elements of the AttributeType enum +func AttributeType_Values() []string { + return []string{ + AttributeTypeString, + AttributeTypeInteger, + AttributeTypeFloat, + AttributeTypeTimestamp, + } +} + const ( // DatasetTypeTargetTimeSeries is a DatasetType enum value DatasetTypeTargetTimeSeries = "TARGET_TIME_SERIES" @@ -8323,6 +9308,15 @@ const ( DatasetTypeItemMetadata = "ITEM_METADATA" ) +// DatasetType_Values returns all elements of the DatasetType enum +func DatasetType_Values() []string { + return []string{ + DatasetTypeTargetTimeSeries, + DatasetTypeRelatedTimeSeries, + DatasetTypeItemMetadata, + } +} + const ( // DomainRetail is a Domain enum value DomainRetail = "RETAIL" @@ -8346,6 +9340,19 @@ const ( DomainMetrics = "METRICS" ) +// Domain_Values returns all elements of the Domain enum +func Domain_Values() []string { + return []string{ + DomainRetail, + DomainCustom, + DomainInventoryPlanning, + DomainEc2Capacity, + DomainWorkForce, + DomainWebTraffic, + DomainMetrics, + } +} + const ( // EvaluationTypeSummary is a EvaluationType enum value EvaluationTypeSummary = "SUMMARY" @@ -8354,11 +9361,26 @@ const ( EvaluationTypeComputed = "COMPUTED" ) +// EvaluationType_Values returns all elements of the EvaluationType enum +func EvaluationType_Values() []string { + return []string{ + EvaluationTypeSummary, + EvaluationTypeComputed, + } +} + const ( // FeaturizationMethodNameFilling is a FeaturizationMethodName enum value FeaturizationMethodNameFilling = "filling" ) +// FeaturizationMethodName_Values returns all elements of the FeaturizationMethodName enum +func FeaturizationMethodName_Values() []string { + return []string{ + FeaturizationMethodNameFilling, + } +} + const ( // FilterConditionStringIs is a FilterConditionString enum value FilterConditionStringIs = "IS" @@ -8367,6 +9389,14 @@ const ( FilterConditionStringIsNot = "IS_NOT" ) +// FilterConditionString_Values returns all elements of the FilterConditionString enum +func FilterConditionString_Values() []string { + return []string{ + FilterConditionStringIs, + FilterConditionStringIsNot, + } +} + const ( // ScalingTypeAuto is a ScalingType enum value ScalingTypeAuto = "Auto" @@ -8380,3 +9410,13 @@ const ( // ScalingTypeReverseLogarithmic is a ScalingType enum value ScalingTypeReverseLogarithmic = "ReverseLogarithmic" ) + +// ScalingType_Values returns all elements of the ScalingType enum +func ScalingType_Values() []string { + return []string{ + ScalingTypeAuto, + ScalingTypeLinear, + ScalingTypeLogarithmic, + ScalingTypeReverseLogarithmic, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/fsx/api.go b/vendor/github.com/aws/aws-sdk-go/service/fsx/api.go index 91aa12c43ec..12c80deb9fc 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/fsx/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/fsx/api.go @@ -158,10 +158,22 @@ func (c *FSx) CreateBackupRequest(input *CreateBackupInput) (req *request.Reques // CreateBackup API operation for Amazon FSx. // -// Creates a backup of an existing Amazon FSx for Windows File Server file system. -// Creating regular backups for your file system is a best practice that complements -// the replication that Amazon FSx for Windows File Server performs for your -// file system. It also enables you to restore from user modification of data. +// Creates a backup of an existing Amazon FSx file system. Creating regular +// backups for your file system is a best practice, enabling you to restore +// a file system from a backup if an issue arises with the original file system. +// +// For Amazon FSx for Lustre file systems, you can create a backup only for +// file systems with the following configuration: +// +// * a Persistent deployment type +// +// * is not linked to an Amazon S3 data respository. +// +// For more information about backing up Amazon FSx for Lustre file systems, +// see Working with FSx for Lustre backups (https://docs.aws.amazon.com/fsx/latest/LustreGuide/using-backups-fsx.html). +// +// For more information about backing up Amazon FSx for Lustre file systems, +// see Working with FSx for Windows backups (https://docs.aws.amazon.com/fsx/latest/WindowsGuide/using-backups.html). // // If a backup with the specified client request token exists, and the parameters // match, this operation returns the description of the existing backup. If @@ -181,10 +193,9 @@ func (c *FSx) CreateBackupRequest(input *CreateBackupInput) (req *request.Reques // created a backup, the operation returns a successful result because all the // parameters are the same. // -// The CreateFileSystem operation returns while the backup's lifecycle state -// is still CREATING. You can check the file system creation status by calling -// the DescribeBackups operation, which returns the backup state along with -// other information. +// The CreateBackup operation returns while the backup's lifecycle state is +// still CREATING. You can check the backup creation status by calling the DescribeBackups +// operation, which returns the backup state along with other information. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -538,8 +549,7 @@ func (c *FSx) CreateFileSystemFromBackupRequest(input *CreateFileSystemFromBacku // CreateFileSystemFromBackup API operation for Amazon FSx. // -// Creates a new Amazon FSx file system from an existing Amazon FSx for Windows -// File Server backup. +// Creates a new Amazon FSx file system from an existing Amazon FSx backup. // // If a file system with the specified client request token exists and the parameters // match, this operation returns the description of the file system. If a client @@ -597,6 +607,10 @@ func (c *FSx) CreateFileSystemFromBackupRequest(input *CreateFileSystemFromBacku // of IDs for security groups that are either invalid or not part of the VPC // specified. // +// * InvalidPerUnitStorageThroughput +// An invalid value for PerUnitStorageThroughput was provided. Please create +// your file system again, using a valid value. +// // * ServiceLimitExceeded // An error indicating that a particular service limit was exceeded. You can // increase some service limits by contacting AWS Support. @@ -676,8 +690,8 @@ func (c *FSx) DeleteBackupRequest(input *DeleteBackupInput) (req *request.Reques // DeleteBackup API operation for Amazon FSx. // -// Deletes an Amazon FSx for Windows File Server backup, deleting its contents. -// After deletion, the backup no longer exists, and its data is gone. +// Deletes an Amazon FSx backup, deleting its contents. After deletion, the +// backup no longer exists, and its data is gone. // // The DeleteBackup call returns instantly. The backup will not show up in later // DescribeBackups calls. @@ -898,10 +912,9 @@ func (c *FSx) DescribeBackupsRequest(input *DescribeBackupsInput) (req *request. // DescribeBackups API operation for Amazon FSx. // -// Returns the description of specific Amazon FSx for Windows File Server backups, -// if a BackupIds value is provided for that backup. Otherwise, it returns all -// backups owned by your AWS account in the AWS Region of the endpoint that -// you're calling. +// Returns the description of specific Amazon FSx backups, if a BackupIds value +// is provided for that backup. Otherwise, it returns all backups owned by your +// AWS account in the AWS Region of the endpoint that you're calling. // // When retrieving all backups, you can optionally specify the MaxResults parameter // to limit the number of backups in a response. If more backups remain, Amazon @@ -1683,7 +1696,33 @@ func (c *FSx) UpdateFileSystemRequest(input *UpdateFileSystemInput) (req *reques // UpdateFileSystem API operation for Amazon FSx. // -// Updates a file system configuration. +// Use this operation to update the configuration of an existing Amazon FSx +// file system. You can update multiple properties in a single request. +// +// For Amazon FSx for Windows File Server file systems, you can update the following +// properties: +// +// * AutomaticBackupRetentionDays +// +// * DailyAutomaticBackupStartTime +// +// * SelfManagedActiveDirectoryConfiguration +// +// * StorageCapacity +// +// * ThroughputCapacity +// +// * WeeklyMaintenanceStartTime +// +// For Amazon FSx for Lustre file systems, you can update the following properties: +// +// * AutoImportPolicy +// +// * AutomaticBackupRetentionDays +// +// * DailyAutomaticBackupStartTime +// +// * WeeklyMaintenanceStartTime // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1713,6 +1752,10 @@ func (c *FSx) UpdateFileSystemRequest(input *UpdateFileSystemInput) (req *reques // * MissingFileSystemConfiguration // A file system configuration is required for this operation. // +// * ServiceLimitExceeded +// An error indicating that a particular service limit was exceeded. You can +// increase some service limits by contacting AWS Support. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/fsx-2018-03-01/UpdateFileSystem func (c *FSx) UpdateFileSystem(input *UpdateFileSystemInput) (*UpdateFileSystemOutput, error) { req, out := c.UpdateFileSystemRequest(input) @@ -1835,8 +1878,128 @@ func (s *ActiveDirectoryError) RequestID() string { return s.RespMetadata.RequestID } -// A backup of an Amazon FSx for Windows File Server file system. You can create -// a new file system from a backup to protect against data loss. +// Describes a specific Amazon FSx Administrative Action for the current Windows +// file system. +type AdministrativeAction struct { + _ struct{} `type:"structure"` + + // Describes the type of administrative action, as follows: + // + // * FILE_SYSTEM_UPDATE - A file system update administrative action initiated + // by the user from the Amazon FSx console, API (UpdateFileSystem), or CLI + // (update-file-system). A + // + // * STORAGE_OPTIMIZATION - Once the FILE_SYSTEM_UPDATE task to increase + // a file system's storage capacity completes successfully, a STORAGE_OPTIMIZATION + // task starts. Storage optimization is the process of migrating the file + // system data to the new, larger disks. You can track the storage migration + // progress using the ProgressPercent property. When STORAGE_OPTIMIZATION + // completes successfully, the parent FILE_SYSTEM_UPDATE action status changes + // to COMPLETED. For more information, see Managing Storage Capacity (https://docs.aws.amazon.com/fsx/latest/WindowsGuide/managing-storage-capacity.html). + AdministrativeActionType *string `type:"string" enum:"AdministrativeActionType"` + + // Provides information about a failed administrative action. + FailureDetails *AdministrativeActionFailureDetails `type:"structure"` + + // Provides the percent complete of a STORAGE_OPTIMIZATION administrative action. + ProgressPercent *int64 `type:"integer"` + + // Time that the administrative action request was received. + RequestTime *time.Time `type:"timestamp"` + + // Describes the status of the administrative action, as follows: + // + // * FAILED - Amazon FSx failed to process the administrative action successfully. + // + // * IN_PROGRESS - Amazon FSx is processing the administrative action. + // + // * PENDING - Amazon FSx is waiting to process the administrative action. + // + // * COMPLETED - Amazon FSx has finished processing the administrative task. + // + // * UPDATED_OPTIMIZING - For a storage capacity increase update, Amazon + // FSx has updated the file system with the new storage capacity, and is + // now performing the storage optimization process. For more information, + // see Managing Storage Capacity (https://docs.aws.amazon.com/fsx/latest/WindowsGuide/managing-storage-capacity.html). + Status *string `type:"string" enum:"Status"` + + // Describes the target StorageCapacity or ThroughputCapacity value provided + // in the UpdateFileSystem operation. Returned for FILE_SYSTEM_UPDATE administrative + // actions. + TargetFileSystemValues *FileSystem `type:"structure"` +} + +// String returns the string representation +func (s AdministrativeAction) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AdministrativeAction) GoString() string { + return s.String() +} + +// SetAdministrativeActionType sets the AdministrativeActionType field's value. +func (s *AdministrativeAction) SetAdministrativeActionType(v string) *AdministrativeAction { + s.AdministrativeActionType = &v + return s +} + +// SetFailureDetails sets the FailureDetails field's value. +func (s *AdministrativeAction) SetFailureDetails(v *AdministrativeActionFailureDetails) *AdministrativeAction { + s.FailureDetails = v + return s +} + +// SetProgressPercent sets the ProgressPercent field's value. +func (s *AdministrativeAction) SetProgressPercent(v int64) *AdministrativeAction { + s.ProgressPercent = &v + return s +} + +// SetRequestTime sets the RequestTime field's value. +func (s *AdministrativeAction) SetRequestTime(v time.Time) *AdministrativeAction { + s.RequestTime = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *AdministrativeAction) SetStatus(v string) *AdministrativeAction { + s.Status = &v + return s +} + +// SetTargetFileSystemValues sets the TargetFileSystemValues field's value. +func (s *AdministrativeAction) SetTargetFileSystemValues(v *FileSystem) *AdministrativeAction { + s.TargetFileSystemValues = v + return s +} + +// Provides information about a failed administrative action. +type AdministrativeActionFailureDetails struct { + _ struct{} `type:"structure"` + + // Error message providing details about the failure. + Message *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s AdministrativeActionFailureDetails) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AdministrativeActionFailureDetails) GoString() string { + return s.String() +} + +// SetMessage sets the Message field's value. +func (s *AdministrativeActionFailureDetails) SetMessage(v string) *AdministrativeActionFailureDetails { + s.Message = &v + return s +} + +// A backup of an Amazon FSx for file system. type Backup struct { _ struct{} `type:"structure"` @@ -1882,7 +2045,7 @@ type Backup struct { // Tags associated with a particular file system. Tags []*Tag `min:"1" type:"list"` - // The type of the backup. + // The type of the file system backup. // // Type is a required field Type *string `type:"string" required:"true" enum:"BackupType"` @@ -2401,9 +2564,9 @@ func (s *CompletionReport) SetScope(v string) *CompletionReport { type CreateBackupInput struct { _ struct{} `type:"structure"` - // (Optional) A string of up to 64 ASCII characters that Amazon FSx uses to - // ensure idempotent creation. This string is automatically filled on your behalf - // when you use the AWS Command Line Interface (AWS CLI) or an AWS SDK. + // A string of up to 64 ASCII characters that Amazon FSx uses to ensure idempotent + // creation. This string is automatically filled on your behalf when you use + // the AWS Command Line Interface (AWS CLI) or an AWS SDK. ClientRequestToken *string `min:"1" type:"string" idempotencyToken:"true"` // The ID of the file system to back up. @@ -2412,7 +2575,10 @@ type CreateBackupInput struct { FileSystemId *string `min:"11" type:"string" required:"true"` // The tags to apply to the backup at backup creation. The key value of the - // Name tag appears in the console as the backup name. + // Name tag appears in the console as the backup name. If you have set CopyTagsToBackups + // to true, and you specify one or more tags using the CreateBackup action, + // no existing tags on the file system are copied from the file system to the + // backup. Tags []*Tag `min:"1" type:"list"` } @@ -2660,11 +2826,14 @@ type CreateFileSystemFromBackupInput struct { // BackupId is a required field BackupId *string `min:"12" type:"string" required:"true"` - // (Optional) A string of up to 64 ASCII characters that Amazon FSx uses to - // ensure idempotent creation. This string is automatically filled on your behalf - // when you use the AWS Command Line Interface (AWS CLI) or an AWS SDK. + // A string of up to 64 ASCII characters that Amazon FSx uses to ensure idempotent + // creation. This string is automatically filled on your behalf when you use + // the AWS Command Line Interface (AWS CLI) or an AWS SDK. ClientRequestToken *string `min:"1" type:"string" idempotencyToken:"true"` + // The Lustre configuration for the file system being created. + LustreConfiguration *CreateFileSystemLustreConfiguration `type:"structure"` + // A list of IDs for the security groups that apply to the specified network // interfaces created for file system access. These security groups apply to // all network interfaces. This value isn't returned in later DescribeFileSystem @@ -2738,6 +2907,11 @@ func (s *CreateFileSystemFromBackupInput) Validate() error { if s.Tags != nil && len(s.Tags) < 1 { invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) } + if s.LustreConfiguration != nil { + if err := s.LustreConfiguration.Validate(); err != nil { + invalidParams.AddNested("LustreConfiguration", err.(request.ErrInvalidParams)) + } + } if s.Tags != nil { for i, v := range s.Tags { if v == nil { @@ -2772,6 +2946,12 @@ func (s *CreateFileSystemFromBackupInput) SetClientRequestToken(v string) *Creat return s } +// SetLustreConfiguration sets the LustreConfiguration field's value. +func (s *CreateFileSystemFromBackupInput) SetLustreConfiguration(v *CreateFileSystemLustreConfiguration) *CreateFileSystemFromBackupInput { + s.LustreConfiguration = v + return s +} + // SetSecurityGroupIds sets the SecurityGroupIds field's value. func (s *CreateFileSystemFromBackupInput) SetSecurityGroupIds(v []*string) *CreateFileSystemFromBackupInput { s.SecurityGroupIds = v @@ -2830,9 +3010,9 @@ func (s *CreateFileSystemFromBackupOutput) SetFileSystem(v *FileSystem) *CreateF type CreateFileSystemInput struct { _ struct{} `type:"structure"` - // (Optional) A string of up to 64 ASCII characters that Amazon FSx uses to - // ensure idempotent creation. This string is automatically filled on your behalf - // when you use the AWS Command Line Interface (AWS CLI) or an AWS SDK. + // A string of up to 64 ASCII characters that Amazon FSx uses to ensure idempotent + // creation. This string is automatically filled on your behalf when you use + // the AWS Command Line Interface (AWS CLI) or an AWS SDK. ClientRequestToken *string `min:"1" type:"string" idempotencyToken:"true"` // The type of Amazon FSx file system to create, either WINDOWS or LUSTRE. @@ -2885,7 +3065,7 @@ type CreateFileSystemInput struct { // * Set to HDD to use hard disk drive storage. HDD is supported on SINGLE_AZ_2 // and MULTI_AZ_1 Windows file system deployment types. // - // Default value is SSD. For more information, see Storage Type Options (https://docs.aws.amazon.com/fsx/latest/WindowsGuide/optimize-fsx-tco.html#saz-maz-storage-type) + // Default value is SSD. For more information, see Storage Type Options (https://docs.aws.amazon.com/fsx/latest/WindowsGuide/optimize-fsx-costs.html#storage-type-options) // in the Amazon FSx for Windows User Guide. StorageType *string `type:"string" enum:"StorageType"` @@ -3032,10 +3212,55 @@ func (s *CreateFileSystemInput) SetWindowsConfiguration(v *CreateFileSystemWindo type CreateFileSystemLustreConfiguration struct { _ struct{} `type:"structure"` - // (Optional) Choose SCRATCH_1 and SCRATCH_2 deployment types when you need - // temporary storage and shorter-term processing of data. The SCRATCH_2 deployment - // type provides in-transit encryption of data and higher burst throughput capacity - // than SCRATCH_1. + // (Optional) Use this property to configure the AutoImport feature on the file + // system's linked Amazon S3 data repository. You use AutoImport to update the + // contents of your FSx for Lustre file system automatically with changes that + // occur in the linked S3 data repository. AutoImportPolicy can have the following + // values: + // + // * NONE - (Default) AutoImport is off. Changes in the linked data repository + // are not reflected on the FSx file system. + // + // * NEW - AutoImport is on. New files in the linked data repository that + // do not currently exist in the FSx file system are automatically imported. + // Updates to existing FSx files are not imported to the FSx file system. + // Files deleted from the linked data repository are not deleted from the + // FSx file system. + // + // * NEW_CHANGED - AutoImport is on. New files in the linked S3 data repository + // that do not currently exist in the FSx file system are automatically imported. + // Changes to existing FSx files in the linked repository are also automatically + // imported to the FSx file system. Files deleted from the linked data repository + // are not deleted from the FSx file system. + // + // For more information, see Automatically import updates from your S3 bucket + // (https://docs.aws.amazon.com/fsx/latest/LustreGuide/autoimport-data-repo.html). + AutoImportPolicy *string `type:"string" enum:"AutoImportPolicyType"` + + // The number of days to retain automatic backups. Setting this to 0 disables + // automatic backups. You can retain automatic backups for a maximum of 90 days. + // The default is 0. + AutomaticBackupRetentionDays *int64 `type:"integer"` + + // A boolean flag indicating whether tags for the file system should be copied + // to backups. This value defaults to false. If it's set to true, all tags for + // the file system are copied to all automatic and user-initiated backups where + // the user doesn't specify tags. If this value is true, and you specify one + // or more tags, only the specified tags are copied to backups. If you specify + // one or more tags when creating a user-initiated backup, no tags are copied + // from the file system, regardless of this value. + // + // For more information, see Working with backups (https://docs.aws.amazon.com/fsx/latest/LustreGuide/using-backups-fsx.html). + CopyTagsToBackups *bool `type:"boolean"` + + // A recurring daily time, in the format HH:MM. HH is the zero-padded hour of + // the day (0-23), and MM is the zero-padded minute of the hour. For example, + // 05:00 specifies 5 AM daily. + DailyAutomaticBackupStartTime *string `min:"5" type:"string"` + + // Choose SCRATCH_1 and SCRATCH_2 deployment types when you need temporary storage + // and shorter-term processing of data. The SCRATCH_2 deployment type provides + // in-transit encryption of data and higher burst throughput capacity than SCRATCH_1. // // Choose PERSISTENT_1 deployment type for longer-term storage and workloads // and encryption of data in transit. To learn more about deployment types, @@ -3051,6 +3276,14 @@ type CreateFileSystemLustreConfiguration struct { // Regions. To learn more, Encrypting Data in Transit (https://docs.aws.amazon.com/fsx/latest/LustreGuide/encryption-in-transit-fsxl.html). DeploymentType *string `type:"string" enum:"LustreDeploymentType"` + // The type of drive cache used by PERSISTENT_1 file systems that are provisioned + // with HDD storage devices. This parameter is required when storage type is + // HDD. Set to READ, improve the performance for frequently accessed files and + // allows 20% of the total storage capacity of the file system to be cached. + // + // This parameter is required when StorageType is set to HDD. + DriveCacheType *string `type:"string" enum:"DriveCacheType"` + // (Optional) The path in Amazon S3 where the root of your Amazon FSx file system // is exported. The path must use the same Amazon S3 bucket as specified in // ImportPath. You can provide an optional prefix to which new and changed data @@ -3092,10 +3325,13 @@ type CreateFileSystemLustreConfiguration struct { // provisioning 50 MB/s/TiB of PerUnitStorageThroughput yields 117 MB/s of file // system throughput. You pay for the amount of throughput that you provision. // - // Valid values are 50, 100, 200. - PerUnitStorageThroughput *int64 `min:"50" type:"integer"` + // Valid values for SSD storage: 50, 100, 200. Valid values for HDD storage: + // 12, 40. + PerUnitStorageThroughput *int64 `min:"12" type:"integer"` - // The preferred time to perform weekly maintenance, in the UTC time zone. + // The preferred start time to perform weekly maintenance, formatted d:HH:MM + // in the UTC time zone, where d is the weekday number, from 1 through 7, beginning + // with Monday and ending with Sunday. WeeklyMaintenanceStartTime *string `min:"7" type:"string"` } @@ -3112,6 +3348,9 @@ func (s CreateFileSystemLustreConfiguration) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *CreateFileSystemLustreConfiguration) Validate() error { invalidParams := request.ErrInvalidParams{Context: "CreateFileSystemLustreConfiguration"} + if s.DailyAutomaticBackupStartTime != nil && len(*s.DailyAutomaticBackupStartTime) < 5 { + invalidParams.Add(request.NewErrParamMinLen("DailyAutomaticBackupStartTime", 5)) + } if s.ExportPath != nil && len(*s.ExportPath) < 3 { invalidParams.Add(request.NewErrParamMinLen("ExportPath", 3)) } @@ -3121,8 +3360,8 @@ func (s *CreateFileSystemLustreConfiguration) Validate() error { if s.ImportedFileChunkSize != nil && *s.ImportedFileChunkSize < 1 { invalidParams.Add(request.NewErrParamMinValue("ImportedFileChunkSize", 1)) } - if s.PerUnitStorageThroughput != nil && *s.PerUnitStorageThroughput < 50 { - invalidParams.Add(request.NewErrParamMinValue("PerUnitStorageThroughput", 50)) + if s.PerUnitStorageThroughput != nil && *s.PerUnitStorageThroughput < 12 { + invalidParams.Add(request.NewErrParamMinValue("PerUnitStorageThroughput", 12)) } if s.WeeklyMaintenanceStartTime != nil && len(*s.WeeklyMaintenanceStartTime) < 7 { invalidParams.Add(request.NewErrParamMinLen("WeeklyMaintenanceStartTime", 7)) @@ -3134,12 +3373,42 @@ func (s *CreateFileSystemLustreConfiguration) Validate() error { return nil } +// SetAutoImportPolicy sets the AutoImportPolicy field's value. +func (s *CreateFileSystemLustreConfiguration) SetAutoImportPolicy(v string) *CreateFileSystemLustreConfiguration { + s.AutoImportPolicy = &v + return s +} + +// SetAutomaticBackupRetentionDays sets the AutomaticBackupRetentionDays field's value. +func (s *CreateFileSystemLustreConfiguration) SetAutomaticBackupRetentionDays(v int64) *CreateFileSystemLustreConfiguration { + s.AutomaticBackupRetentionDays = &v + return s +} + +// SetCopyTagsToBackups sets the CopyTagsToBackups field's value. +func (s *CreateFileSystemLustreConfiguration) SetCopyTagsToBackups(v bool) *CreateFileSystemLustreConfiguration { + s.CopyTagsToBackups = &v + return s +} + +// SetDailyAutomaticBackupStartTime sets the DailyAutomaticBackupStartTime field's value. +func (s *CreateFileSystemLustreConfiguration) SetDailyAutomaticBackupStartTime(v string) *CreateFileSystemLustreConfiguration { + s.DailyAutomaticBackupStartTime = &v + return s +} + // SetDeploymentType sets the DeploymentType field's value. func (s *CreateFileSystemLustreConfiguration) SetDeploymentType(v string) *CreateFileSystemLustreConfiguration { s.DeploymentType = &v return s } +// SetDriveCacheType sets the DriveCacheType field's value. +func (s *CreateFileSystemLustreConfiguration) SetDriveCacheType(v string) *CreateFileSystemLustreConfiguration { + s.DriveCacheType = &v + return s +} + // SetExportPath sets the ExportPath field's value. func (s *CreateFileSystemLustreConfiguration) SetExportPath(v string) *CreateFileSystemLustreConfiguration { s.ExportPath = &v @@ -3205,7 +3474,7 @@ type CreateFileSystemWindowsConfiguration struct { // The number of days to retain automatic backups. The default is to retain // backups for 7 days. Setting this value to 0 disables the creation of automatic - // backups. The maximum retention period for backups is 35 days. + // backups. The maximum retention period for backups is 90 days. AutomaticBackupRetentionDays *int64 `type:"integer"` // A boolean flag indicating whether tags for the file system should be copied @@ -3258,7 +3527,8 @@ type CreateFileSystemWindowsConfiguration struct { ThroughputCapacity *int64 `min:"8" type:"integer" required:"true"` // The preferred start time to perform weekly maintenance, formatted d:HH:MM - // in the UTC time zone. + // in the UTC time zone, where d is the weekday number, from 1 through 7, beginning + // with Monday and ending with Sunday. WeeklyMaintenanceStartTime *string `min:"7" type:"string"` } @@ -3364,10 +3634,38 @@ func (s *CreateFileSystemWindowsConfiguration) SetWeeklyMaintenanceStartTime(v s type DataRepositoryConfiguration struct { _ struct{} `type:"structure"` + // Describes the file system's linked S3 data repository's AutoImportPolicy. + // The AutoImportPolicy configures how your FSx for Lustre file system automatically + // updates its contents with changes that occur in the linked S3 data repository. + // AutoImportPolicy can have the following values: + // + // * NONE - (Default) AutoImport is off. Changes in the linked data repository + // are not reflected on the FSx file system. + // + // * NEW - AutoImport is on. New files in the linked data repository that + // do not currently exist in the FSx file system are automatically imported. + // Updates to existing FSx files are not imported to the FSx file system. + // Files deleted from the linked data repository are not deleted from the + // FSx file system. + // + // * NEW_CHANGED - AutoImport is on. New files in the linked S3 data repository + // that do not currently exist in the FSx file system are automatically imported. + // Changes to existing FSx files in the linked repository are also automatically + // imported to the FSx file system. Files deleted from the linked data repository + // are not deleted from the FSx file system. + // + // For more information, see Automatically import updates from your S3 bucket + // (https://docs.aws.amazon.com/fsx/latest/LustreGuide/autoimport-data-repo.html). + AutoImportPolicy *string `type:"string" enum:"AutoImportPolicyType"` + // The export path to the Amazon S3 bucket (and prefix) that you are using to // store new and changed Lustre file system files in S3. ExportPath *string `min:"3" type:"string"` + // Provides detailed information about the data respository if its Lifecycle + // is set to MISCONFIGURED. + FailureDetails *DataRepositoryFailureDetails `type:"structure"` + // The import path to the Amazon S3 bucket (and optional prefix) that you're // using as the data repository for your FSx for Lustre file system, for example // s3://import-bucket/optional-prefix. If a prefix is specified after the Amazon @@ -3383,6 +3681,25 @@ type DataRepositoryConfiguration struct { // The default chunk size is 1,024 MiB (1 GiB) and can go as high as 512,000 // MiB (500 GiB). Amazon S3 objects have a maximum size of 5 TB. ImportedFileChunkSize *int64 `min:"1" type:"integer"` + + // Describes the state of the file system's S3 durable data repository, if it + // is configured with an S3 repository. The lifecycle can have the following + // values: + // + // * CREATING - The data repository configuration between the FSx file system + // and the linked S3 data repository is being created. The data repository + // is unavailable. + // + // * AVAILABLE - The data repository is available for use. + // + // * MISCONFIGURED - Amazon FSx cannot automatically import updates from + // the S3 bucket until the data repository configuration is corrected. For + // more information, see Troubleshooting a Misconfigured linked S3 bucket + // (https://docs.aws.amazon.com/fsx/latest/LustreGuide/troubleshooting.html#troubleshooting-misconfigured-data-repository). + // + // * UPDATING - The data repository is undergoing a customer initiated update + // and availability may be impacted. + Lifecycle *string `type:"string" enum:"DataRepositoryLifecycle"` } // String returns the string representation @@ -3395,12 +3712,24 @@ func (s DataRepositoryConfiguration) GoString() string { return s.String() } +// SetAutoImportPolicy sets the AutoImportPolicy field's value. +func (s *DataRepositoryConfiguration) SetAutoImportPolicy(v string) *DataRepositoryConfiguration { + s.AutoImportPolicy = &v + return s +} + // SetExportPath sets the ExportPath field's value. func (s *DataRepositoryConfiguration) SetExportPath(v string) *DataRepositoryConfiguration { s.ExportPath = &v return s } +// SetFailureDetails sets the FailureDetails field's value. +func (s *DataRepositoryConfiguration) SetFailureDetails(v *DataRepositoryFailureDetails) *DataRepositoryConfiguration { + s.FailureDetails = v + return s +} + // SetImportPath sets the ImportPath field's value. func (s *DataRepositoryConfiguration) SetImportPath(v string) *DataRepositoryConfiguration { s.ImportPath = &v @@ -3413,6 +3742,37 @@ func (s *DataRepositoryConfiguration) SetImportedFileChunkSize(v int64) *DataRep return s } +// SetLifecycle sets the Lifecycle field's value. +func (s *DataRepositoryConfiguration) SetLifecycle(v string) *DataRepositoryConfiguration { + s.Lifecycle = &v + return s +} + +// Provides detailed information about the data respository if its Lifecycle +// is set to MISCONFIGURED. +type DataRepositoryFailureDetails struct { + _ struct{} `type:"structure"` + + // A detailed error message. + Message *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s DataRepositoryFailureDetails) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DataRepositoryFailureDetails) GoString() string { + return s.String() +} + +// SetMessage sets the Message field's value. +func (s *DataRepositoryFailureDetails) SetMessage(v string) *DataRepositoryFailureDetails { + s.Message = &v + return s +} + // A description of the data repository task. You use data repository tasks // to perform bulk transfer operations between your Amazon FSx file system and // its linked data repository. @@ -3903,9 +4263,9 @@ type DeleteBackupInput struct { // BackupId is a required field BackupId *string `min:"12" type:"string" required:"true"` - // (Optional) A string of up to 64 ASCII characters that Amazon FSx uses to - // ensure idempotent deletion. This is automatically filled on your behalf when - // using the AWS CLI or SDK. + // A string of up to 64 ASCII characters that Amazon FSx uses to ensure idempotent + // deletion. This is automatically filled on your behalf when using the AWS + // CLI or SDK. ClientRequestToken *string `min:"1" type:"string" idempotencyToken:"true"` } @@ -3987,9 +4347,9 @@ func (s *DeleteBackupOutput) SetLifecycle(v string) *DeleteBackupOutput { type DeleteFileSystemInput struct { _ struct{} `type:"structure"` - // (Optional) A string of up to 64 ASCII characters that Amazon FSx uses to - // ensure idempotent deletion. This is automatically filled on your behalf when - // using the AWS CLI or SDK. + // A string of up to 64 ASCII characters that Amazon FSx uses to ensure idempotent + // deletion. This is automatically filled on your behalf when using the AWS + // CLI or SDK. ClientRequestToken *string `min:"1" type:"string" idempotencyToken:"true"` // The ID of the file system you want to delete. @@ -3997,6 +4357,10 @@ type DeleteFileSystemInput struct { // FileSystemId is a required field FileSystemId *string `min:"11" type:"string" required:"true"` + // The configuration object for the Amazon FSx for Lustre file system being + // deleted in the DeleteFileSystem operation. + LustreConfiguration *DeleteFileSystemLustreConfiguration `type:"structure"` + // The configuration object for the Microsoft Windows file system used in the // DeleteFileSystem operation. WindowsConfiguration *DeleteFileSystemWindowsConfiguration `type:"structure"` @@ -4024,6 +4388,11 @@ func (s *DeleteFileSystemInput) Validate() error { if s.FileSystemId != nil && len(*s.FileSystemId) < 11 { invalidParams.Add(request.NewErrParamMinLen("FileSystemId", 11)) } + if s.LustreConfiguration != nil { + if err := s.LustreConfiguration.Validate(); err != nil { + invalidParams.AddNested("LustreConfiguration", err.(request.ErrInvalidParams)) + } + } if s.WindowsConfiguration != nil { if err := s.WindowsConfiguration.Validate(); err != nil { invalidParams.AddNested("WindowsConfiguration", err.(request.ErrInvalidParams)) @@ -4048,12 +4417,115 @@ func (s *DeleteFileSystemInput) SetFileSystemId(v string) *DeleteFileSystemInput return s } +// SetLustreConfiguration sets the LustreConfiguration field's value. +func (s *DeleteFileSystemInput) SetLustreConfiguration(v *DeleteFileSystemLustreConfiguration) *DeleteFileSystemInput { + s.LustreConfiguration = v + return s +} + // SetWindowsConfiguration sets the WindowsConfiguration field's value. func (s *DeleteFileSystemInput) SetWindowsConfiguration(v *DeleteFileSystemWindowsConfiguration) *DeleteFileSystemInput { s.WindowsConfiguration = v return s } +// The configuration object for the Amazon FSx for Lustre file system being +// deleted in the DeleteFileSystem operation. +type DeleteFileSystemLustreConfiguration struct { + _ struct{} `type:"structure"` + + // Use if SkipFinalBackup is set to false, and you want to apply an array of + // tags to the final backup. If you have set the file system property CopyTagsToBackups + // to true, and you specify one or more FinalBackupTags when deleting a file + // system, Amazon FSx will not copy any existing file system tags to the backup. + FinalBackupTags []*Tag `min:"1" type:"list"` + + // Set SkipFinalBackup to false if you want to take a final backup of the file + // system you are deleting. By default, Amazon FSx will not take a final backup + // on your behalf when the DeleteFileSystem operation is invoked. (Default = + // true) + SkipFinalBackup *bool `type:"boolean"` +} + +// String returns the string representation +func (s DeleteFileSystemLustreConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteFileSystemLustreConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteFileSystemLustreConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteFileSystemLustreConfiguration"} + if s.FinalBackupTags != nil && len(s.FinalBackupTags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("FinalBackupTags", 1)) + } + if s.FinalBackupTags != nil { + for i, v := range s.FinalBackupTags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "FinalBackupTags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetFinalBackupTags sets the FinalBackupTags field's value. +func (s *DeleteFileSystemLustreConfiguration) SetFinalBackupTags(v []*Tag) *DeleteFileSystemLustreConfiguration { + s.FinalBackupTags = v + return s +} + +// SetSkipFinalBackup sets the SkipFinalBackup field's value. +func (s *DeleteFileSystemLustreConfiguration) SetSkipFinalBackup(v bool) *DeleteFileSystemLustreConfiguration { + s.SkipFinalBackup = &v + return s +} + +// The response object for the Amazon FSx for Lustre file system being deleted +// in the DeleteFileSystem operation. +type DeleteFileSystemLustreResponse struct { + _ struct{} `type:"structure"` + + // The ID of the final backup for this file system. + FinalBackupId *string `min:"12" type:"string"` + + // The set of tags applied to the final backup. + FinalBackupTags []*Tag `min:"1" type:"list"` +} + +// String returns the string representation +func (s DeleteFileSystemLustreResponse) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteFileSystemLustreResponse) GoString() string { + return s.String() +} + +// SetFinalBackupId sets the FinalBackupId field's value. +func (s *DeleteFileSystemLustreResponse) SetFinalBackupId(v string) *DeleteFileSystemLustreResponse { + s.FinalBackupId = &v + return s +} + +// SetFinalBackupTags sets the FinalBackupTags field's value. +func (s *DeleteFileSystemLustreResponse) SetFinalBackupTags(v []*Tag) *DeleteFileSystemLustreResponse { + s.FinalBackupTags = v + return s +} + // The response object for the DeleteFileSystem operation. type DeleteFileSystemOutput struct { _ struct{} `type:"structure"` @@ -4064,6 +4536,10 @@ type DeleteFileSystemOutput struct { // The file system lifecycle for the deletion request. Should be DELETING. Lifecycle *string `type:"string" enum:"FileSystemLifecycle"` + // The response object for the Amazon FSx for Lustre file system being deleted + // in the DeleteFileSystem operation. + LustreResponse *DeleteFileSystemLustreResponse `type:"structure"` + // The response object for the Microsoft Windows file system used in the DeleteFileSystem // operation. WindowsResponse *DeleteFileSystemWindowsResponse `type:"structure"` @@ -4091,6 +4567,12 @@ func (s *DeleteFileSystemOutput) SetLifecycle(v string) *DeleteFileSystemOutput return s } +// SetLustreResponse sets the LustreResponse field's value. +func (s *DeleteFileSystemOutput) SetLustreResponse(v *DeleteFileSystemLustreResponse) *DeleteFileSystemOutput { + s.LustreResponse = v + return s +} + // SetWindowsResponse sets the WindowsResponse field's value. func (s *DeleteFileSystemOutput) SetWindowsResponse(v *DeleteFileSystemWindowsResponse) *DeleteFileSystemOutput { s.WindowsResponse = v @@ -4195,22 +4677,22 @@ func (s *DeleteFileSystemWindowsResponse) SetFinalBackupTags(v []*Tag) *DeleteFi type DescribeBackupsInput struct { _ struct{} `type:"structure"` - // (Optional) IDs of the backups you want to retrieve (String). This overrides - // any filters. If any IDs are not found, BackupNotFound will be thrown. + // IDs of the backups you want to retrieve (String). This overrides any filters. + // If any IDs are not found, BackupNotFound will be thrown. BackupIds []*string `type:"list"` - // (Optional) Filters structure. Supported names are file-system-id and backup-type. + // Filters structure. Supported names are file-system-id and backup-type. Filters []*Filter `type:"list"` - // (Optional) Maximum number of backups to return in the response (integer). - // This parameter value must be greater than 0. The number of items that Amazon - // FSx returns is the minimum of the MaxResults parameter specified in the request - // and the service's internal maximum number of items per page. + // Maximum number of backups to return in the response (integer). This parameter + // value must be greater than 0. The number of items that Amazon FSx returns + // is the minimum of the MaxResults parameter specified in the request and the + // service's internal maximum number of items per page. MaxResults *int64 `min:"1" type:"integer"` - // (Optional) Opaque pagination token returned from a previous DescribeBackups - // operation (String). If a token present, the action continues the list from - // where the returning call left off. + // Opaque pagination token returned from a previous DescribeBackups operation + // (String). If a token present, the action continues the list from where the + // returning call left off. NextToken *string `min:"1" type:"string"` } @@ -4407,19 +4889,18 @@ func (s *DescribeDataRepositoryTasksOutput) SetNextToken(v string) *DescribeData type DescribeFileSystemsInput struct { _ struct{} `type:"structure"` - // (Optional) IDs of the file systems whose descriptions you want to retrieve - // (String). + // IDs of the file systems whose descriptions you want to retrieve (String). FileSystemIds []*string `type:"list"` - // (Optional) Maximum number of file systems to return in the response (integer). - // This parameter value must be greater than 0. The number of items that Amazon - // FSx returns is the minimum of the MaxResults parameter specified in the request + // Maximum number of file systems to return in the response (integer). This + // parameter value must be greater than 0. The number of items that Amazon FSx + // returns is the minimum of the MaxResults parameter specified in the request // and the service's internal maximum number of items per page. MaxResults *int64 `min:"1" type:"integer"` - // (Optional) Opaque pagination token returned from a previous DescribeFileSystems - // operation (String). If a token present, the action continues the list from - // where the returning call left off. + // Opaque pagination token returned from a previous DescribeFileSystems operation + // (String). If a token present, the action continues the list from where the + // returning call left off. NextToken *string `min:"1" type:"string"` } @@ -4505,6 +4986,11 @@ func (s *DescribeFileSystemsOutput) SetNextToken(v string) *DescribeFileSystemsO type FileSystem struct { _ struct{} `type:"structure"` + // A list of administrative actions for the file system that are in process + // or waiting to be processed. Administrative actions describe changes to the + // Windows file system that you have initiated using the UpdateFileSystem action. + AdministrativeActions []*AdministrativeAction `type:"list"` + // The time that the file system was created, in seconds (since 1970-01-01T00:00:00Z), // also known as Unix time. CreationTime *time.Time `type:"timestamp"` @@ -4616,6 +5102,12 @@ func (s FileSystem) GoString() string { return s.String() } +// SetAdministrativeActions sets the AdministrativeActions field's value. +func (s *FileSystem) SetAdministrativeActions(v []*AdministrativeAction) *FileSystem { + s.AdministrativeActions = v + return s +} + // SetCreationTime sets the CreationTime field's value. func (s *FileSystem) SetCreationTime(v time.Time) *FileSystem { s.CreationTime = &v @@ -5206,15 +5698,15 @@ func (s *InvalidPerUnitStorageThroughput) RequestID() string { type ListTagsForResourceInput struct { _ struct{} `type:"structure"` - // (Optional) Maximum number of tags to return in the response (integer). This - // parameter value must be greater than 0. The number of items that Amazon FSx - // returns is the minimum of the MaxResults parameter specified in the request - // and the service's internal maximum number of items per page. + // Maximum number of tags to return in the response (integer). This parameter + // value must be greater than 0. The number of items that Amazon FSx returns + // is the minimum of the MaxResults parameter specified in the request and the + // service's internal maximum number of items per page. MaxResults *int64 `min:"1" type:"integer"` - // (Optional) Opaque pagination token returned from a previous ListTagsForResource - // operation (String). If a token present, the action continues the list from - // where the returning call left off. + // Opaque pagination token returned from a previous ListTagsForResource operation + // (String). If a token present, the action continues the list from where the + // returning call left off. NextToken *string `min:"1" type:"string"` // The ARN of the Amazon FSx resource that will have its tags listed. @@ -5311,13 +5803,51 @@ func (s *ListTagsForResourceOutput) SetTags(v []*Tag) *ListTagsForResourceOutput type LustreFileSystemConfiguration struct { _ struct{} `type:"structure"` + // The number of days to retain automatic backups. Setting this to 0 disables + // automatic backups. You can retain automatic backups for a maximum of 90 days. + // The default is 0. + AutomaticBackupRetentionDays *int64 `type:"integer"` + + // A boolean flag indicating whether tags on the file system should be copied + // to backups. If it's set to true, all tags on the file system are copied to + // all automatic backups and any user-initiated backups where the user doesn't + // specify any tags. If this value is true, and you specify one or more tags, + // only the specified tags are copied to backups. If you specify one or more + // tags when creating a user-initiated backup, no tags are copied from the file + // system, regardless of this value. (Default = false) + CopyTagsToBackups *bool `type:"boolean"` + + // A recurring daily time, in the format HH:MM. HH is the zero-padded hour of + // the day (0-23), and MM is the zero-padded minute of the hour. For example, + // 05:00 specifies 5 AM daily. + DailyAutomaticBackupStartTime *string `min:"5" type:"string"` + // The data repository configuration object for Lustre file systems returned // in the response of the CreateFileSystem operation. DataRepositoryConfiguration *DataRepositoryConfiguration `type:"structure"` - // The deployment type of the FSX for Lustre file system. + // The deployment type of the FSX for Lustre file system. Scratch deployment + // type is designed for temporary storage and shorter-term processing of data. + // + // SCRATCH_1 and SCRATCH_2 deployment types are best suited for when you need + // temporary storage and shorter-term processing of data. The SCRATCH_2 deployment + // type provides in-transit encryption of data and higher burst throughput capacity + // than SCRATCH_1. + // + // The PERSISTENT_1 deployment type is used for longer-term storage and workloads + // and encryption of data in transit. To learn more about deployment types, + // see FSx for Lustre Deployment Options (https://docs.aws.amazon.com/fsx/latest/LustreGuide/lustre-deployment-types.html). + // (Default = SCRATCH_1) DeploymentType *string `type:"string" enum:"LustreDeploymentType"` + // The type of drive cache used by PERSISTENT_1 file systems that are provisioned + // with HDD storage devices. This parameter is required when storage type is + // HDD. Set to READ, improve the performance for frequently accessed files and + // allows 20% of the total storage capacity of the file system to be cached. + // + // This parameter is required when StorageType is set to HDD. + DriveCacheType *string `type:"string" enum:"DriveCacheType"` + // You use the MountName value when mounting the file system. // // For the SCRATCH_1 deployment type, this value is always "fsx". For SCRATCH_2 @@ -5328,11 +5858,15 @@ type LustreFileSystemConfiguration struct { // Per unit storage throughput represents the megabytes per second of read or // write throughput per 1 tebibyte of storage provisioned. File system throughput // capacity is equal to Storage capacity (TiB) * PerUnitStorageThroughput (MB/s/TiB). - // This option is only valid for PERSISTENT_1 deployment types. Valid values - // are 50, 100, 200. - PerUnitStorageThroughput *int64 `min:"50" type:"integer"` + // This option is only valid for PERSISTENT_1 deployment types. + // + // Valid values for SSD storage: 50, 100, 200. Valid values for HDD storage: + // 12, 40. + PerUnitStorageThroughput *int64 `min:"12" type:"integer"` - // The UTC time that you want to begin your weekly maintenance window. + // The preferred start time to perform weekly maintenance, formatted d:HH:MM + // in the UTC time zone. d is the weekday number, from 1 through 7, beginning + // with Monday and ending with Sunday. WeeklyMaintenanceStartTime *string `min:"7" type:"string"` } @@ -5346,6 +5880,24 @@ func (s LustreFileSystemConfiguration) GoString() string { return s.String() } +// SetAutomaticBackupRetentionDays sets the AutomaticBackupRetentionDays field's value. +func (s *LustreFileSystemConfiguration) SetAutomaticBackupRetentionDays(v int64) *LustreFileSystemConfiguration { + s.AutomaticBackupRetentionDays = &v + return s +} + +// SetCopyTagsToBackups sets the CopyTagsToBackups field's value. +func (s *LustreFileSystemConfiguration) SetCopyTagsToBackups(v bool) *LustreFileSystemConfiguration { + s.CopyTagsToBackups = &v + return s +} + +// SetDailyAutomaticBackupStartTime sets the DailyAutomaticBackupStartTime field's value. +func (s *LustreFileSystemConfiguration) SetDailyAutomaticBackupStartTime(v string) *LustreFileSystemConfiguration { + s.DailyAutomaticBackupStartTime = &v + return s +} + // SetDataRepositoryConfiguration sets the DataRepositoryConfiguration field's value. func (s *LustreFileSystemConfiguration) SetDataRepositoryConfiguration(v *DataRepositoryConfiguration) *LustreFileSystemConfiguration { s.DataRepositoryConfiguration = v @@ -5358,6 +5910,12 @@ func (s *LustreFileSystemConfiguration) SetDeploymentType(v string) *LustreFileS return s } +// SetDriveCacheType sets the DriveCacheType field's value. +func (s *LustreFileSystemConfiguration) SetDriveCacheType(v string) *LustreFileSystemConfiguration { + s.DriveCacheType = &v + return s +} + // SetMountName sets the MountName field's value. func (s *LustreFileSystemConfiguration) SetMountName(v string) *LustreFileSystemConfiguration { s.MountName = &v @@ -5836,7 +6394,7 @@ func (s *SelfManagedActiveDirectoryConfiguration) SetUserName(v string) *SelfMan } // The configuration that Amazon FSx uses to join the Windows File Server instance -// to the self-managed Microsoft Active Directory (AD) directory. +// to a self-managed Microsoft Active Directory (AD) directory. type SelfManagedActiveDirectoryConfigurationUpdates struct { _ struct{} `type:"structure"` @@ -5971,13 +6529,17 @@ type Tag struct { // A value that specifies the TagKey, the name of the tag. Tag keys must be // unique for the resource to which they are attached. - Key *string `min:"1" type:"string"` + // + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` // A value that specifies the TagValue, the value assigned to the corresponding // tag key. Tag values can be null and don't have to be unique in a tag set. // For example, you can have a key-value pair in a tag set of finances : April // and also of payroll : April. - Value *string `type:"string"` + // + // Value is a required field + Value *string `type:"string" required:"true"` } // String returns the string representation @@ -5993,9 +6555,15 @@ func (s Tag) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *Tag) Validate() error { invalidParams := request.ErrInvalidParams{Context: "Tag"} + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } if s.Key != nil && len(*s.Key) < 1 { invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } + if s.Value == nil { + invalidParams.Add(request.NewErrParamRequired("Value")) + } if invalidParams.Len() > 0 { return invalidParams @@ -6237,12 +6805,12 @@ func (s UntagResourceOutput) GoString() string { type UpdateFileSystemInput struct { _ struct{} `type:"structure"` - // (Optional) A string of up to 64 ASCII characters that Amazon FSx uses to - // ensure idempotent updates. This string is automatically filled on your behalf - // when you use the AWS Command Line Interface (AWS CLI) or an AWS SDK. + // A string of up to 64 ASCII characters that Amazon FSx uses to ensure idempotent + // updates. This string is automatically filled on your behalf when you use + // the AWS Command Line Interface (AWS CLI) or an AWS SDK. ClientRequestToken *string `min:"1" type:"string" idempotencyToken:"true"` - // The globally unique ID of the file system, assigned by Amazon FSx. + // Identifies the file system that you are updating. // // FileSystemId is a required field FileSystemId *string `min:"11" type:"string" required:"true"` @@ -6251,9 +6819,18 @@ type UpdateFileSystemInput struct { // UpdateFileSystem operation. LustreConfiguration *UpdateFileSystemLustreConfiguration `type:"structure"` - // The configuration update for this Microsoft Windows file system. The only - // supported options are for backup and maintenance and for self-managed Active - // Directory configuration. + // Use this parameter to increase the storage capacity of an Amazon FSx for + // Windows File Server file system. Specifies the storage capacity target value, + // GiB, for the file system you're updating. The storage capacity target value + // must be at least 10 percent (%) greater than the current storage capacity + // value. In order to increase storage capacity, the file system needs to have + // at least 16 MB/s of throughput capacity. You cannot make a storage capacity + // increase request if there is an existing storage capacity increase request + // in progress. For more information, see Managing Storage Capacity (https://docs.aws.amazon.com/fsx/latest/WindowsGuide/managing-storage-capacity.html). + StorageCapacity *int64 `type:"integer"` + + // The configuration updates for an Amazon FSx for Windows File Server file + // system. WindowsConfiguration *UpdateFileSystemWindowsConfiguration `type:"structure"` } @@ -6314,6 +6891,12 @@ func (s *UpdateFileSystemInput) SetLustreConfiguration(v *UpdateFileSystemLustre return s } +// SetStorageCapacity sets the StorageCapacity field's value. +func (s *UpdateFileSystemInput) SetStorageCapacity(v int64) *UpdateFileSystemInput { + s.StorageCapacity = &v + return s +} + // SetWindowsConfiguration sets the WindowsConfiguration field's value. func (s *UpdateFileSystemInput) SetWindowsConfiguration(v *UpdateFileSystemWindowsConfiguration) *UpdateFileSystemInput { s.WindowsConfiguration = v @@ -6325,7 +6908,44 @@ func (s *UpdateFileSystemInput) SetWindowsConfiguration(v *UpdateFileSystemWindo type UpdateFileSystemLustreConfiguration struct { _ struct{} `type:"structure"` - // The preferred time to perform weekly maintenance, in the UTC time zone. + // (Optional) Use this property to configure the AutoImport feature on the file + // system's linked Amazon S3 data repository. You use AutoImport to update the + // contents of your FSx for Lustre file system automatically with changes that + // occur in the linked S3 data repository. AutoImportPolicy can have the following + // values: + // + // * NONE - (Default) AutoImport is off. Changes in the linked data repository + // are not reflected on the FSx file system. + // + // * NEW - AutoImport is on. New files in the linked data repository that + // do not currently exist in the FSx file system are automatically imported. + // Updates to existing FSx files are not imported to the FSx file system. + // Files deleted from the linked data repository are not deleted from the + // FSx file system. + // + // * NEW_CHANGED - AutoImport is on. New files in the linked S3 data repository + // that do not currently exist in the FSx file system are automatically imported. + // Changes to existing FSx files in the linked repository are also automatically + // imported to the FSx file system. Files deleted from the linked data repository + // are not deleted from the FSx file system. + // + // For more information, see Automatically import updates from your S3 bucket + // (https://docs.aws.amazon.com/fsx/latest/LustreGuide/autoimport-data-repo.html). + AutoImportPolicy *string `type:"string" enum:"AutoImportPolicyType"` + + // The number of days to retain automatic backups. Setting this to 0 disables + // automatic backups. You can retain automatic backups for a maximum of 90 days. + // The default is 0. + AutomaticBackupRetentionDays *int64 `type:"integer"` + + // A recurring daily time, in the format HH:MM. HH is the zero-padded hour of + // the day (0-23), and MM is the zero-padded minute of the hour. For example, + // 05:00 specifies 5 AM daily. + DailyAutomaticBackupStartTime *string `min:"5" type:"string"` + + // The preferred start time to perform weekly maintenance, formatted d:HH:MM + // in the UTC time zone. d is the weekday number, from 1 through 7, beginning + // with Monday and ending with Sunday. WeeklyMaintenanceStartTime *string `min:"7" type:"string"` } @@ -6342,6 +6962,9 @@ func (s UpdateFileSystemLustreConfiguration) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *UpdateFileSystemLustreConfiguration) Validate() error { invalidParams := request.ErrInvalidParams{Context: "UpdateFileSystemLustreConfiguration"} + if s.DailyAutomaticBackupStartTime != nil && len(*s.DailyAutomaticBackupStartTime) < 5 { + invalidParams.Add(request.NewErrParamMinLen("DailyAutomaticBackupStartTime", 5)) + } if s.WeeklyMaintenanceStartTime != nil && len(*s.WeeklyMaintenanceStartTime) < 7 { invalidParams.Add(request.NewErrParamMinLen("WeeklyMaintenanceStartTime", 7)) } @@ -6352,6 +6975,24 @@ func (s *UpdateFileSystemLustreConfiguration) Validate() error { return nil } +// SetAutoImportPolicy sets the AutoImportPolicy field's value. +func (s *UpdateFileSystemLustreConfiguration) SetAutoImportPolicy(v string) *UpdateFileSystemLustreConfiguration { + s.AutoImportPolicy = &v + return s +} + +// SetAutomaticBackupRetentionDays sets the AutomaticBackupRetentionDays field's value. +func (s *UpdateFileSystemLustreConfiguration) SetAutomaticBackupRetentionDays(v int64) *UpdateFileSystemLustreConfiguration { + s.AutomaticBackupRetentionDays = &v + return s +} + +// SetDailyAutomaticBackupStartTime sets the DailyAutomaticBackupStartTime field's value. +func (s *UpdateFileSystemLustreConfiguration) SetDailyAutomaticBackupStartTime(v string) *UpdateFileSystemLustreConfiguration { + s.DailyAutomaticBackupStartTime = &v + return s +} + // SetWeeklyMaintenanceStartTime sets the WeeklyMaintenanceStartTime field's value. func (s *UpdateFileSystemLustreConfiguration) SetWeeklyMaintenanceStartTime(v string) *UpdateFileSystemLustreConfiguration { s.WeeklyMaintenanceStartTime = &v @@ -6382,25 +7023,38 @@ func (s *UpdateFileSystemOutput) SetFileSystem(v *FileSystem) *UpdateFileSystemO return s } -// Updates the Microsoft Windows configuration for an existing Amazon FSx for -// Windows File Server file system. Amazon FSx overwrites existing properties -// with non-null values provided in the request. If you don't specify a non-null -// value for a property, that property is not updated. +// Updates the configuration for an existing Amazon FSx for Windows File Server +// file system. Amazon FSx only overwrites existing properties with non-null +// values provided in the request. type UpdateFileSystemWindowsConfiguration struct { _ struct{} `type:"structure"` - // The number of days to retain automatic backups. Setting this to 0 disables - // automatic backups. You can retain automatic backups for a maximum of 35 days. + // The number of days to retain automatic daily backups. Setting this to zero + // (0) disables automatic daily backups. You can retain automatic daily backups + // for a maximum of 90 days. For more information, see Working with Automatic + // Daily Backups (https://docs.aws.amazon.com/fsx/latest/WindowsGuide/using-backups.html#automatic-backups). AutomaticBackupRetentionDays *int64 `type:"integer"` - // The preferred time to take daily automatic backups, in the UTC time zone. + // The preferred time to start the daily automatic backup, in the UTC time zone, + // for example, 02:00 DailyAutomaticBackupStartTime *string `min:"5" type:"string"` // The configuration Amazon FSx uses to join the Windows File Server instance - // to the self-managed Microsoft AD directory. + // to the self-managed Microsoft AD directory. You cannot make a self-managed + // Microsoft AD update request if there is an existing self-managed Microsoft + // AD update request in progress. SelfManagedActiveDirectoryConfiguration *SelfManagedActiveDirectoryConfigurationUpdates `type:"structure"` - // The preferred time to perform weekly maintenance, in the UTC time zone. + // Sets the target value for a file system's throughput capacity, in MB/s, that + // you are updating the file system to. Valid values are 8, 16, 32, 64, 128, + // 256, 512, 1024, 2048. You cannot make a throughput capacity update request + // if there is an existing throughput capacity update request in progress. For + // more information, see Managing Throughput Capacity (https://docs.aws.amazon.com/fsx/latest/WindowsGuide/managing-throughput-capacity.html). + ThroughputCapacity *int64 `min:"8" type:"integer"` + + // The preferred start time to perform weekly maintenance, formatted d:HH:MM + // in the UTC time zone. Where d is the weekday number, from 1 through 7, with + // 1 = Monday and 7 = Sunday. WeeklyMaintenanceStartTime *string `min:"7" type:"string"` } @@ -6420,6 +7074,9 @@ func (s *UpdateFileSystemWindowsConfiguration) Validate() error { if s.DailyAutomaticBackupStartTime != nil && len(*s.DailyAutomaticBackupStartTime) < 5 { invalidParams.Add(request.NewErrParamMinLen("DailyAutomaticBackupStartTime", 5)) } + if s.ThroughputCapacity != nil && *s.ThroughputCapacity < 8 { + invalidParams.Add(request.NewErrParamMinValue("ThroughputCapacity", 8)) + } if s.WeeklyMaintenanceStartTime != nil && len(*s.WeeklyMaintenanceStartTime) < 7 { invalidParams.Add(request.NewErrParamMinLen("WeeklyMaintenanceStartTime", 7)) } @@ -6453,6 +7110,12 @@ func (s *UpdateFileSystemWindowsConfiguration) SetSelfManagedActiveDirectoryConf return s } +// SetThroughputCapacity sets the ThroughputCapacity field's value. +func (s *UpdateFileSystemWindowsConfiguration) SetThroughputCapacity(v int64) *UpdateFileSystemWindowsConfiguration { + s.ThroughputCapacity = &v + return s +} + // SetWeeklyMaintenanceStartTime sets the WeeklyMaintenanceStartTime field's value. func (s *UpdateFileSystemWindowsConfiguration) SetWeeklyMaintenanceStartTime(v string) *UpdateFileSystemWindowsConfiguration { s.WeeklyMaintenanceStartTime = &v @@ -6468,7 +7131,7 @@ type WindowsFileSystemConfiguration struct { ActiveDirectoryId *string `min:"12" type:"string"` // The number of days to retain automatic backups. Setting this to 0 disables - // automatic backups. You can retain automatic backups for a maximum of 35 days. + // automatic backups. You can retain automatic backups for a maximum of 90 days. AutomaticBackupRetentionDays *int64 `type:"integer"` // A boolean flag indicating whether tags on the file system should be copied @@ -6541,7 +7204,9 @@ type WindowsFileSystemConfiguration struct { // The throughput of an Amazon FSx file system, measured in megabytes per second. ThroughputCapacity *int64 `min:"8" type:"integer"` - // The preferred time to perform weekly maintenance, in the UTC time zone. + // The preferred start time to perform weekly maintenance, formatted d:HH:MM + // in the UTC time zone. d is the weekday number, from 1 through 7, beginning + // with Monday and ending with Sunday. WeeklyMaintenanceStartTime *string `min:"7" type:"string"` } @@ -6647,6 +7312,65 @@ const ( ActiveDirectoryErrorTypeInvalidDomainStage = "INVALID_DOMAIN_STAGE" ) +// ActiveDirectoryErrorType_Values returns all elements of the ActiveDirectoryErrorType enum +func ActiveDirectoryErrorType_Values() []string { + return []string{ + ActiveDirectoryErrorTypeDomainNotFound, + ActiveDirectoryErrorTypeIncompatibleDomainMode, + ActiveDirectoryErrorTypeWrongVpc, + ActiveDirectoryErrorTypeInvalidDomainStage, + } +} + +// Describes the type of administrative action, as follows: +// +// * FILE_SYSTEM_UPDATE - A file system update administrative action initiated +// by the user from the Amazon FSx console, API (UpdateFileSystem), or CLI +// (update-file-system). A +// +// * STORAGE_OPTIMIZATION - Once the FILE_SYSTEM_UPDATE task to increase +// a file system's storage capacity completes successfully, a STORAGE_OPTIMIZATION +// task starts. Storage optimization is the process of migrating the file +// system data to the new, larger disks. You can track the storage migration +// progress using the ProgressPercent property. When STORAGE_OPTIMIZATION +// completes successfully, the parent FILE_SYSTEM_UPDATE action status changes +// to COMPLETED. For more information, see Managing Storage Capacity (https://docs.aws.amazon.com/fsx/latest/WindowsGuide/managing-storage-capacity.html). +const ( + // AdministrativeActionTypeFileSystemUpdate is a AdministrativeActionType enum value + AdministrativeActionTypeFileSystemUpdate = "FILE_SYSTEM_UPDATE" + + // AdministrativeActionTypeStorageOptimization is a AdministrativeActionType enum value + AdministrativeActionTypeStorageOptimization = "STORAGE_OPTIMIZATION" +) + +// AdministrativeActionType_Values returns all elements of the AdministrativeActionType enum +func AdministrativeActionType_Values() []string { + return []string{ + AdministrativeActionTypeFileSystemUpdate, + AdministrativeActionTypeStorageOptimization, + } +} + +const ( + // AutoImportPolicyTypeNone is a AutoImportPolicyType enum value + AutoImportPolicyTypeNone = "NONE" + + // AutoImportPolicyTypeNew is a AutoImportPolicyType enum value + AutoImportPolicyTypeNew = "NEW" + + // AutoImportPolicyTypeNewChanged is a AutoImportPolicyType enum value + AutoImportPolicyTypeNewChanged = "NEW_CHANGED" +) + +// AutoImportPolicyType_Values returns all elements of the AutoImportPolicyType enum +func AutoImportPolicyType_Values() []string { + return []string{ + AutoImportPolicyTypeNone, + AutoImportPolicyTypeNew, + AutoImportPolicyTypeNewChanged, + } +} + // The lifecycle status of the backup. const ( // BackupLifecycleAvailable is a BackupLifecycle enum value @@ -6655,6 +7379,9 @@ const ( // BackupLifecycleCreating is a BackupLifecycle enum value BackupLifecycleCreating = "CREATING" + // BackupLifecycleTransferring is a BackupLifecycle enum value + BackupLifecycleTransferring = "TRANSFERRING" + // BackupLifecycleDeleted is a BackupLifecycle enum value BackupLifecycleDeleted = "DELETED" @@ -6662,6 +7389,17 @@ const ( BackupLifecycleFailed = "FAILED" ) +// BackupLifecycle_Values returns all elements of the BackupLifecycle enum +func BackupLifecycle_Values() []string { + return []string{ + BackupLifecycleAvailable, + BackupLifecycleCreating, + BackupLifecycleTransferring, + BackupLifecycleDeleted, + BackupLifecycleFailed, + } +} + // The type of the backup. const ( // BackupTypeAutomatic is a BackupType enum value @@ -6671,6 +7409,42 @@ const ( BackupTypeUserInitiated = "USER_INITIATED" ) +// BackupType_Values returns all elements of the BackupType enum +func BackupType_Values() []string { + return []string{ + BackupTypeAutomatic, + BackupTypeUserInitiated, + } +} + +const ( + // DataRepositoryLifecycleCreating is a DataRepositoryLifecycle enum value + DataRepositoryLifecycleCreating = "CREATING" + + // DataRepositoryLifecycleAvailable is a DataRepositoryLifecycle enum value + DataRepositoryLifecycleAvailable = "AVAILABLE" + + // DataRepositoryLifecycleMisconfigured is a DataRepositoryLifecycle enum value + DataRepositoryLifecycleMisconfigured = "MISCONFIGURED" + + // DataRepositoryLifecycleUpdating is a DataRepositoryLifecycle enum value + DataRepositoryLifecycleUpdating = "UPDATING" + + // DataRepositoryLifecycleDeleting is a DataRepositoryLifecycle enum value + DataRepositoryLifecycleDeleting = "DELETING" +) + +// DataRepositoryLifecycle_Values returns all elements of the DataRepositoryLifecycle enum +func DataRepositoryLifecycle_Values() []string { + return []string{ + DataRepositoryLifecycleCreating, + DataRepositoryLifecycleAvailable, + DataRepositoryLifecycleMisconfigured, + DataRepositoryLifecycleUpdating, + DataRepositoryLifecycleDeleting, + } +} + const ( // DataRepositoryTaskFilterNameFileSystemId is a DataRepositoryTaskFilterName enum value DataRepositoryTaskFilterNameFileSystemId = "file-system-id" @@ -6679,6 +7453,14 @@ const ( DataRepositoryTaskFilterNameTaskLifecycle = "task-lifecycle" ) +// DataRepositoryTaskFilterName_Values returns all elements of the DataRepositoryTaskFilterName enum +func DataRepositoryTaskFilterName_Values() []string { + return []string{ + DataRepositoryTaskFilterNameFileSystemId, + DataRepositoryTaskFilterNameTaskLifecycle, + } +} + const ( // DataRepositoryTaskLifecyclePending is a DataRepositoryTaskLifecycle enum value DataRepositoryTaskLifecyclePending = "PENDING" @@ -6699,11 +7481,46 @@ const ( DataRepositoryTaskLifecycleCanceling = "CANCELING" ) +// DataRepositoryTaskLifecycle_Values returns all elements of the DataRepositoryTaskLifecycle enum +func DataRepositoryTaskLifecycle_Values() []string { + return []string{ + DataRepositoryTaskLifecyclePending, + DataRepositoryTaskLifecycleExecuting, + DataRepositoryTaskLifecycleFailed, + DataRepositoryTaskLifecycleSucceeded, + DataRepositoryTaskLifecycleCanceled, + DataRepositoryTaskLifecycleCanceling, + } +} + const ( // DataRepositoryTaskTypeExportToRepository is a DataRepositoryTaskType enum value DataRepositoryTaskTypeExportToRepository = "EXPORT_TO_REPOSITORY" ) +// DataRepositoryTaskType_Values returns all elements of the DataRepositoryTaskType enum +func DataRepositoryTaskType_Values() []string { + return []string{ + DataRepositoryTaskTypeExportToRepository, + } +} + +const ( + // DriveCacheTypeNone is a DriveCacheType enum value + DriveCacheTypeNone = "NONE" + + // DriveCacheTypeRead is a DriveCacheType enum value + DriveCacheTypeRead = "READ" +) + +// DriveCacheType_Values returns all elements of the DriveCacheType enum +func DriveCacheType_Values() []string { + return []string{ + DriveCacheTypeNone, + DriveCacheTypeRead, + } +} + // The lifecycle status of the file system. const ( // FileSystemLifecycleAvailable is a FileSystemLifecycle enum value @@ -6725,6 +7542,18 @@ const ( FileSystemLifecycleUpdating = "UPDATING" ) +// FileSystemLifecycle_Values returns all elements of the FileSystemLifecycle enum +func FileSystemLifecycle_Values() []string { + return []string{ + FileSystemLifecycleAvailable, + FileSystemLifecycleCreating, + FileSystemLifecycleFailed, + FileSystemLifecycleDeleting, + FileSystemLifecycleMisconfigured, + FileSystemLifecycleUpdating, + } +} + // An enumeration specifying the currently ongoing maintenance operation. const ( // FileSystemMaintenanceOperationPatching is a FileSystemMaintenanceOperation enum value @@ -6734,6 +7563,14 @@ const ( FileSystemMaintenanceOperationBackingUp = "BACKING_UP" ) +// FileSystemMaintenanceOperation_Values returns all elements of the FileSystemMaintenanceOperation enum +func FileSystemMaintenanceOperation_Values() []string { + return []string{ + FileSystemMaintenanceOperationPatching, + FileSystemMaintenanceOperationBackingUp, + } +} + // The type of file system. const ( // FileSystemTypeWindows is a FileSystemType enum value @@ -6743,6 +7580,14 @@ const ( FileSystemTypeLustre = "LUSTRE" ) +// FileSystemType_Values returns all elements of the FileSystemType enum +func FileSystemType_Values() []string { + return []string{ + FileSystemTypeWindows, + FileSystemTypeLustre, + } +} + // The name for a filter. const ( // FilterNameFileSystemId is a FilterName enum value @@ -6750,8 +7595,20 @@ const ( // FilterNameBackupType is a FilterName enum value FilterNameBackupType = "backup-type" + + // FilterNameFileSystemType is a FilterName enum value + FilterNameFileSystemType = "file-system-type" ) +// FilterName_Values returns all elements of the FilterName enum +func FilterName_Values() []string { + return []string{ + FilterNameFileSystemId, + FilterNameBackupType, + FilterNameFileSystemType, + } +} + const ( // LustreDeploymentTypeScratch1 is a LustreDeploymentType enum value LustreDeploymentTypeScratch1 = "SCRATCH_1" @@ -6763,16 +7620,39 @@ const ( LustreDeploymentTypePersistent1 = "PERSISTENT_1" ) +// LustreDeploymentType_Values returns all elements of the LustreDeploymentType enum +func LustreDeploymentType_Values() []string { + return []string{ + LustreDeploymentTypeScratch1, + LustreDeploymentTypeScratch2, + LustreDeploymentTypePersistent1, + } +} + const ( // ReportFormatReportCsv20191124 is a ReportFormat enum value ReportFormatReportCsv20191124 = "REPORT_CSV_20191124" ) +// ReportFormat_Values returns all elements of the ReportFormat enum +func ReportFormat_Values() []string { + return []string{ + ReportFormatReportCsv20191124, + } +} + const ( // ReportScopeFailedFilesOnly is a ReportScope enum value ReportScopeFailedFilesOnly = "FAILED_FILES_ONLY" ) +// ReportScope_Values returns all elements of the ReportScope enum +func ReportScope_Values() []string { + return []string{ + ReportScopeFailedFilesOnly, + } +} + // The types of limits on your service utilization. Limits include file system // count, total throughput capacity, total storage, and total user-initiated // backups. These limits apply for a specific account in a specific AWS Region. @@ -6791,6 +7671,44 @@ const ( ServiceLimitTotalUserInitiatedBackups = "TOTAL_USER_INITIATED_BACKUPS" ) +// ServiceLimit_Values returns all elements of the ServiceLimit enum +func ServiceLimit_Values() []string { + return []string{ + ServiceLimitFileSystemCount, + ServiceLimitTotalThroughputCapacity, + ServiceLimitTotalStorage, + ServiceLimitTotalUserInitiatedBackups, + } +} + +const ( + // StatusFailed is a Status enum value + StatusFailed = "FAILED" + + // StatusInProgress is a Status enum value + StatusInProgress = "IN_PROGRESS" + + // StatusPending is a Status enum value + StatusPending = "PENDING" + + // StatusCompleted is a Status enum value + StatusCompleted = "COMPLETED" + + // StatusUpdatedOptimizing is a Status enum value + StatusUpdatedOptimizing = "UPDATED_OPTIMIZING" +) + +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusFailed, + StatusInProgress, + StatusPending, + StatusCompleted, + StatusUpdatedOptimizing, + } +} + // The storage type for your Amazon FSx file system. const ( // StorageTypeSsd is a StorageType enum value @@ -6800,6 +7718,14 @@ const ( StorageTypeHdd = "HDD" ) +// StorageType_Values returns all elements of the StorageType enum +func StorageType_Values() []string { + return []string{ + StorageTypeSsd, + StorageTypeHdd, + } +} + const ( // WindowsDeploymentTypeMultiAz1 is a WindowsDeploymentType enum value WindowsDeploymentTypeMultiAz1 = "MULTI_AZ_1" @@ -6810,3 +7736,12 @@ const ( // WindowsDeploymentTypeSingleAz2 is a WindowsDeploymentType enum value WindowsDeploymentTypeSingleAz2 = "SINGLE_AZ_2" ) + +// WindowsDeploymentType_Values returns all elements of the WindowsDeploymentType enum +func WindowsDeploymentType_Values() []string { + return []string{ + WindowsDeploymentTypeMultiAz1, + WindowsDeploymentTypeSingleAz1, + WindowsDeploymentTypeSingleAz2, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/gamelift/api.go b/vendor/github.com/aws/aws-sdk-go/service/gamelift/api.go index d4e7cf76e2d..2dfc0b4c36e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/gamelift/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/gamelift/api.go @@ -26088,6 +26088,14 @@ const ( AcceptanceTypeReject = "REJECT" ) +// AcceptanceType_Values returns all elements of the AcceptanceType enum +func AcceptanceType_Values() []string { + return []string{ + AcceptanceTypeAccept, + AcceptanceTypeReject, + } +} + const ( // BackfillModeAutomatic is a BackfillMode enum value BackfillModeAutomatic = "AUTOMATIC" @@ -26096,6 +26104,14 @@ const ( BackfillModeManual = "MANUAL" ) +// BackfillMode_Values returns all elements of the BackfillMode enum +func BackfillMode_Values() []string { + return []string{ + BackfillModeAutomatic, + BackfillModeManual, + } +} + const ( // BalancingStrategySpotOnly is a BalancingStrategy enum value BalancingStrategySpotOnly = "SPOT_ONLY" @@ -26104,6 +26120,14 @@ const ( BalancingStrategySpotPreferred = "SPOT_PREFERRED" ) +// BalancingStrategy_Values returns all elements of the BalancingStrategy enum +func BalancingStrategy_Values() []string { + return []string{ + BalancingStrategySpotOnly, + BalancingStrategySpotPreferred, + } +} + const ( // BuildStatusInitialized is a BuildStatus enum value BuildStatusInitialized = "INITIALIZED" @@ -26115,6 +26139,15 @@ const ( BuildStatusFailed = "FAILED" ) +// BuildStatus_Values returns all elements of the BuildStatus enum +func BuildStatus_Values() []string { + return []string{ + BuildStatusInitialized, + BuildStatusReady, + BuildStatusFailed, + } +} + const ( // CertificateTypeDisabled is a CertificateType enum value CertificateTypeDisabled = "DISABLED" @@ -26123,6 +26156,14 @@ const ( CertificateTypeGenerated = "GENERATED" ) +// CertificateType_Values returns all elements of the CertificateType enum +func CertificateType_Values() []string { + return []string{ + CertificateTypeDisabled, + CertificateTypeGenerated, + } +} + const ( // ComparisonOperatorTypeGreaterThanOrEqualToThreshold is a ComparisonOperatorType enum value ComparisonOperatorTypeGreaterThanOrEqualToThreshold = "GreaterThanOrEqualToThreshold" @@ -26137,6 +26178,16 @@ const ( ComparisonOperatorTypeLessThanOrEqualToThreshold = "LessThanOrEqualToThreshold" ) +// ComparisonOperatorType_Values returns all elements of the ComparisonOperatorType enum +func ComparisonOperatorType_Values() []string { + return []string{ + ComparisonOperatorTypeGreaterThanOrEqualToThreshold, + ComparisonOperatorTypeGreaterThanThreshold, + ComparisonOperatorTypeLessThanThreshold, + ComparisonOperatorTypeLessThanOrEqualToThreshold, + } +} + const ( // EC2InstanceTypeT2Micro is a EC2InstanceType enum value EC2InstanceTypeT2Micro = "t2.micro" @@ -26313,6 +26364,70 @@ const ( EC2InstanceTypeM524xlarge = "m5.24xlarge" ) +// EC2InstanceType_Values returns all elements of the EC2InstanceType enum +func EC2InstanceType_Values() []string { + return []string{ + EC2InstanceTypeT2Micro, + EC2InstanceTypeT2Small, + EC2InstanceTypeT2Medium, + EC2InstanceTypeT2Large, + EC2InstanceTypeC3Large, + EC2InstanceTypeC3Xlarge, + EC2InstanceTypeC32xlarge, + EC2InstanceTypeC34xlarge, + EC2InstanceTypeC38xlarge, + EC2InstanceTypeC4Large, + EC2InstanceTypeC4Xlarge, + EC2InstanceTypeC42xlarge, + EC2InstanceTypeC44xlarge, + EC2InstanceTypeC48xlarge, + EC2InstanceTypeC5Large, + EC2InstanceTypeC5Xlarge, + EC2InstanceTypeC52xlarge, + EC2InstanceTypeC54xlarge, + EC2InstanceTypeC59xlarge, + EC2InstanceTypeC512xlarge, + EC2InstanceTypeC518xlarge, + EC2InstanceTypeC524xlarge, + EC2InstanceTypeR3Large, + EC2InstanceTypeR3Xlarge, + EC2InstanceTypeR32xlarge, + EC2InstanceTypeR34xlarge, + EC2InstanceTypeR38xlarge, + EC2InstanceTypeR4Large, + EC2InstanceTypeR4Xlarge, + EC2InstanceTypeR42xlarge, + EC2InstanceTypeR44xlarge, + EC2InstanceTypeR48xlarge, + EC2InstanceTypeR416xlarge, + EC2InstanceTypeR5Large, + EC2InstanceTypeR5Xlarge, + EC2InstanceTypeR52xlarge, + EC2InstanceTypeR54xlarge, + EC2InstanceTypeR58xlarge, + EC2InstanceTypeR512xlarge, + EC2InstanceTypeR516xlarge, + EC2InstanceTypeR524xlarge, + EC2InstanceTypeM3Medium, + EC2InstanceTypeM3Large, + EC2InstanceTypeM3Xlarge, + EC2InstanceTypeM32xlarge, + EC2InstanceTypeM4Large, + EC2InstanceTypeM4Xlarge, + EC2InstanceTypeM42xlarge, + EC2InstanceTypeM44xlarge, + EC2InstanceTypeM410xlarge, + EC2InstanceTypeM5Large, + EC2InstanceTypeM5Xlarge, + EC2InstanceTypeM52xlarge, + EC2InstanceTypeM54xlarge, + EC2InstanceTypeM58xlarge, + EC2InstanceTypeM512xlarge, + EC2InstanceTypeM516xlarge, + EC2InstanceTypeM524xlarge, + } +} + const ( // EventCodeGenericEvent is a EventCode enum value EventCodeGenericEvent = "GENERIC_EVENT" @@ -26414,11 +26529,57 @@ const ( EventCodeInstanceInterrupted = "INSTANCE_INTERRUPTED" ) +// EventCode_Values returns all elements of the EventCode enum +func EventCode_Values() []string { + return []string{ + EventCodeGenericEvent, + EventCodeFleetCreated, + EventCodeFleetDeleted, + EventCodeFleetScalingEvent, + EventCodeFleetStateDownloading, + EventCodeFleetStateValidating, + EventCodeFleetStateBuilding, + EventCodeFleetStateActivating, + EventCodeFleetStateActive, + EventCodeFleetStateError, + EventCodeFleetInitializationFailed, + EventCodeFleetBinaryDownloadFailed, + EventCodeFleetValidationLaunchPathNotFound, + EventCodeFleetValidationExecutableRuntimeFailure, + EventCodeFleetValidationTimedOut, + EventCodeFleetActivationFailed, + EventCodeFleetActivationFailedNoInstances, + EventCodeFleetNewGameSessionProtectionPolicyUpdated, + EventCodeServerProcessInvalidPath, + EventCodeServerProcessSdkInitializationTimeout, + EventCodeServerProcessProcessReadyTimeout, + EventCodeServerProcessCrashed, + EventCodeServerProcessTerminatedUnhealthy, + EventCodeServerProcessForceTerminated, + EventCodeServerProcessProcessExitTimeout, + EventCodeGameSessionActivationTimeout, + EventCodeFleetCreationExtractingBuild, + EventCodeFleetCreationRunningInstaller, + EventCodeFleetCreationValidatingRuntimeConfig, + EventCodeFleetVpcPeeringSucceeded, + EventCodeFleetVpcPeeringFailed, + EventCodeFleetVpcPeeringDeleted, + EventCodeInstanceInterrupted, + } +} + const ( // FleetActionAutoScaling is a FleetAction enum value FleetActionAutoScaling = "AUTO_SCALING" ) +// FleetAction_Values returns all elements of the FleetAction enum +func FleetAction_Values() []string { + return []string{ + FleetActionAutoScaling, + } +} + const ( // FleetStatusNew is a FleetStatus enum value FleetStatusNew = "NEW" @@ -26448,6 +26609,21 @@ const ( FleetStatusTerminated = "TERMINATED" ) +// FleetStatus_Values returns all elements of the FleetStatus enum +func FleetStatus_Values() []string { + return []string{ + FleetStatusNew, + FleetStatusDownloading, + FleetStatusValidating, + FleetStatusBuilding, + FleetStatusActivating, + FleetStatusActive, + FleetStatusDeleting, + FleetStatusError, + FleetStatusTerminated, + } +} + const ( // FleetTypeOnDemand is a FleetType enum value FleetTypeOnDemand = "ON_DEMAND" @@ -26456,16 +26632,38 @@ const ( FleetTypeSpot = "SPOT" ) +// FleetType_Values returns all elements of the FleetType enum +func FleetType_Values() []string { + return []string{ + FleetTypeOnDemand, + FleetTypeSpot, + } +} + const ( // GameServerClaimStatusClaimed is a GameServerClaimStatus enum value GameServerClaimStatusClaimed = "CLAIMED" ) +// GameServerClaimStatus_Values returns all elements of the GameServerClaimStatus enum +func GameServerClaimStatus_Values() []string { + return []string{ + GameServerClaimStatusClaimed, + } +} + const ( // GameServerGroupActionReplaceInstanceTypes is a GameServerGroupAction enum value GameServerGroupActionReplaceInstanceTypes = "REPLACE_INSTANCE_TYPES" ) +// GameServerGroupAction_Values returns all elements of the GameServerGroupAction enum +func GameServerGroupAction_Values() []string { + return []string{ + GameServerGroupActionReplaceInstanceTypes, + } +} + const ( // GameServerGroupDeleteOptionSafeDelete is a GameServerGroupDeleteOption enum value GameServerGroupDeleteOptionSafeDelete = "SAFE_DELETE" @@ -26477,6 +26675,15 @@ const ( GameServerGroupDeleteOptionRetain = "RETAIN" ) +// GameServerGroupDeleteOption_Values returns all elements of the GameServerGroupDeleteOption enum +func GameServerGroupDeleteOption_Values() []string { + return []string{ + GameServerGroupDeleteOptionSafeDelete, + GameServerGroupDeleteOptionForceDelete, + GameServerGroupDeleteOptionRetain, + } +} + const ( // GameServerGroupInstanceTypeC4Large is a GameServerGroupInstanceType enum value GameServerGroupInstanceTypeC4Large = "c4.large" @@ -26599,6 +26806,52 @@ const ( GameServerGroupInstanceTypeM524xlarge = "m5.24xlarge" ) +// GameServerGroupInstanceType_Values returns all elements of the GameServerGroupInstanceType enum +func GameServerGroupInstanceType_Values() []string { + return []string{ + GameServerGroupInstanceTypeC4Large, + GameServerGroupInstanceTypeC4Xlarge, + GameServerGroupInstanceTypeC42xlarge, + GameServerGroupInstanceTypeC44xlarge, + GameServerGroupInstanceTypeC48xlarge, + GameServerGroupInstanceTypeC5Large, + GameServerGroupInstanceTypeC5Xlarge, + GameServerGroupInstanceTypeC52xlarge, + GameServerGroupInstanceTypeC54xlarge, + GameServerGroupInstanceTypeC59xlarge, + GameServerGroupInstanceTypeC512xlarge, + GameServerGroupInstanceTypeC518xlarge, + GameServerGroupInstanceTypeC524xlarge, + GameServerGroupInstanceTypeR4Large, + GameServerGroupInstanceTypeR4Xlarge, + GameServerGroupInstanceTypeR42xlarge, + GameServerGroupInstanceTypeR44xlarge, + GameServerGroupInstanceTypeR48xlarge, + GameServerGroupInstanceTypeR416xlarge, + GameServerGroupInstanceTypeR5Large, + GameServerGroupInstanceTypeR5Xlarge, + GameServerGroupInstanceTypeR52xlarge, + GameServerGroupInstanceTypeR54xlarge, + GameServerGroupInstanceTypeR58xlarge, + GameServerGroupInstanceTypeR512xlarge, + GameServerGroupInstanceTypeR516xlarge, + GameServerGroupInstanceTypeR524xlarge, + GameServerGroupInstanceTypeM4Large, + GameServerGroupInstanceTypeM4Xlarge, + GameServerGroupInstanceTypeM42xlarge, + GameServerGroupInstanceTypeM44xlarge, + GameServerGroupInstanceTypeM410xlarge, + GameServerGroupInstanceTypeM5Large, + GameServerGroupInstanceTypeM5Xlarge, + GameServerGroupInstanceTypeM52xlarge, + GameServerGroupInstanceTypeM54xlarge, + GameServerGroupInstanceTypeM58xlarge, + GameServerGroupInstanceTypeM512xlarge, + GameServerGroupInstanceTypeM516xlarge, + GameServerGroupInstanceTypeM524xlarge, + } +} + const ( // GameServerGroupStatusNew is a GameServerGroupStatus enum value GameServerGroupStatusNew = "NEW" @@ -26622,11 +26875,31 @@ const ( GameServerGroupStatusError = "ERROR" ) +// GameServerGroupStatus_Values returns all elements of the GameServerGroupStatus enum +func GameServerGroupStatus_Values() []string { + return []string{ + GameServerGroupStatusNew, + GameServerGroupStatusActivating, + GameServerGroupStatusActive, + GameServerGroupStatusDeleteScheduled, + GameServerGroupStatusDeleting, + GameServerGroupStatusDeleted, + GameServerGroupStatusError, + } +} + const ( // GameServerHealthCheckHealthy is a GameServerHealthCheck enum value GameServerHealthCheckHealthy = "HEALTHY" ) +// GameServerHealthCheck_Values returns all elements of the GameServerHealthCheck enum +func GameServerHealthCheck_Values() []string { + return []string{ + GameServerHealthCheckHealthy, + } +} + const ( // GameServerProtectionPolicyNoProtection is a GameServerProtectionPolicy enum value GameServerProtectionPolicyNoProtection = "NO_PROTECTION" @@ -26635,6 +26908,14 @@ const ( GameServerProtectionPolicyFullProtection = "FULL_PROTECTION" ) +// GameServerProtectionPolicy_Values returns all elements of the GameServerProtectionPolicy enum +func GameServerProtectionPolicy_Values() []string { + return []string{ + GameServerProtectionPolicyNoProtection, + GameServerProtectionPolicyFullProtection, + } +} + const ( // GameServerUtilizationStatusAvailable is a GameServerUtilizationStatus enum value GameServerUtilizationStatusAvailable = "AVAILABLE" @@ -26643,6 +26924,14 @@ const ( GameServerUtilizationStatusUtilized = "UTILIZED" ) +// GameServerUtilizationStatus_Values returns all elements of the GameServerUtilizationStatus enum +func GameServerUtilizationStatus_Values() []string { + return []string{ + GameServerUtilizationStatusAvailable, + GameServerUtilizationStatusUtilized, + } +} + const ( // GameSessionPlacementStatePending is a GameSessionPlacementState enum value GameSessionPlacementStatePending = "PENDING" @@ -26660,6 +26949,17 @@ const ( GameSessionPlacementStateFailed = "FAILED" ) +// GameSessionPlacementState_Values returns all elements of the GameSessionPlacementState enum +func GameSessionPlacementState_Values() []string { + return []string{ + GameSessionPlacementStatePending, + GameSessionPlacementStateFulfilled, + GameSessionPlacementStateCancelled, + GameSessionPlacementStateTimedOut, + GameSessionPlacementStateFailed, + } +} + const ( // GameSessionStatusActive is a GameSessionStatus enum value GameSessionStatusActive = "ACTIVE" @@ -26677,11 +26977,29 @@ const ( GameSessionStatusError = "ERROR" ) +// GameSessionStatus_Values returns all elements of the GameSessionStatus enum +func GameSessionStatus_Values() []string { + return []string{ + GameSessionStatusActive, + GameSessionStatusActivating, + GameSessionStatusTerminated, + GameSessionStatusTerminating, + GameSessionStatusError, + } +} + const ( // GameSessionStatusReasonInterrupted is a GameSessionStatusReason enum value GameSessionStatusReasonInterrupted = "INTERRUPTED" ) +// GameSessionStatusReason_Values returns all elements of the GameSessionStatusReason enum +func GameSessionStatusReason_Values() []string { + return []string{ + GameSessionStatusReasonInterrupted, + } +} + const ( // InstanceStatusPending is a InstanceStatus enum value InstanceStatusPending = "PENDING" @@ -26693,6 +27011,15 @@ const ( InstanceStatusTerminating = "TERMINATING" ) +// InstanceStatus_Values returns all elements of the InstanceStatus enum +func InstanceStatus_Values() []string { + return []string{ + InstanceStatusPending, + InstanceStatusActive, + InstanceStatusTerminating, + } +} + const ( // IpProtocolTcp is a IpProtocol enum value IpProtocolTcp = "TCP" @@ -26701,6 +27028,14 @@ const ( IpProtocolUdp = "UDP" ) +// IpProtocol_Values returns all elements of the IpProtocol enum +func IpProtocol_Values() []string { + return []string{ + IpProtocolTcp, + IpProtocolUdp, + } +} + const ( // MatchmakingConfigurationStatusCancelled is a MatchmakingConfigurationStatus enum value MatchmakingConfigurationStatusCancelled = "CANCELLED" @@ -26727,6 +27062,20 @@ const ( MatchmakingConfigurationStatusTimedOut = "TIMED_OUT" ) +// MatchmakingConfigurationStatus_Values returns all elements of the MatchmakingConfigurationStatus enum +func MatchmakingConfigurationStatus_Values() []string { + return []string{ + MatchmakingConfigurationStatusCancelled, + MatchmakingConfigurationStatusCompleted, + MatchmakingConfigurationStatusFailed, + MatchmakingConfigurationStatusPlacing, + MatchmakingConfigurationStatusQueued, + MatchmakingConfigurationStatusRequiresAcceptance, + MatchmakingConfigurationStatusSearching, + MatchmakingConfigurationStatusTimedOut, + } +} + const ( // MetricNameActivatingGameSessions is a MetricName enum value MetricNameActivatingGameSessions = "ActivatingGameSessions" @@ -26762,6 +27111,23 @@ const ( MetricNameWaitTime = "WaitTime" ) +// MetricName_Values returns all elements of the MetricName enum +func MetricName_Values() []string { + return []string{ + MetricNameActivatingGameSessions, + MetricNameActiveGameSessions, + MetricNameActiveInstances, + MetricNameAvailableGameSessions, + MetricNameAvailablePlayerSessions, + MetricNameCurrentPlayerSessions, + MetricNameIdleInstances, + MetricNamePercentAvailableGameSessions, + MetricNamePercentIdleInstances, + MetricNameQueueDepth, + MetricNameWaitTime, + } +} + const ( // OperatingSystemWindows2012 is a OperatingSystem enum value OperatingSystemWindows2012 = "WINDOWS_2012" @@ -26773,6 +27139,15 @@ const ( OperatingSystemAmazonLinux2 = "AMAZON_LINUX_2" ) +// OperatingSystem_Values returns all elements of the OperatingSystem enum +func OperatingSystem_Values() []string { + return []string{ + OperatingSystemWindows2012, + OperatingSystemAmazonLinux, + OperatingSystemAmazonLinux2, + } +} + const ( // PlayerSessionCreationPolicyAcceptAll is a PlayerSessionCreationPolicy enum value PlayerSessionCreationPolicyAcceptAll = "ACCEPT_ALL" @@ -26781,6 +27156,14 @@ const ( PlayerSessionCreationPolicyDenyAll = "DENY_ALL" ) +// PlayerSessionCreationPolicy_Values returns all elements of the PlayerSessionCreationPolicy enum +func PlayerSessionCreationPolicy_Values() []string { + return []string{ + PlayerSessionCreationPolicyAcceptAll, + PlayerSessionCreationPolicyDenyAll, + } +} + const ( // PlayerSessionStatusReserved is a PlayerSessionStatus enum value PlayerSessionStatusReserved = "RESERVED" @@ -26795,6 +27178,16 @@ const ( PlayerSessionStatusTimedout = "TIMEDOUT" ) +// PlayerSessionStatus_Values returns all elements of the PlayerSessionStatus enum +func PlayerSessionStatus_Values() []string { + return []string{ + PlayerSessionStatusReserved, + PlayerSessionStatusActive, + PlayerSessionStatusCompleted, + PlayerSessionStatusTimedout, + } +} + const ( // PolicyTypeRuleBased is a PolicyType enum value PolicyTypeRuleBased = "RuleBased" @@ -26803,6 +27196,14 @@ const ( PolicyTypeTargetBased = "TargetBased" ) +// PolicyType_Values returns all elements of the PolicyType enum +func PolicyType_Values() []string { + return []string{ + PolicyTypeRuleBased, + PolicyTypeTargetBased, + } +} + const ( // ProtectionPolicyNoProtection is a ProtectionPolicy enum value ProtectionPolicyNoProtection = "NoProtection" @@ -26811,6 +27212,14 @@ const ( ProtectionPolicyFullProtection = "FullProtection" ) +// ProtectionPolicy_Values returns all elements of the ProtectionPolicy enum +func ProtectionPolicy_Values() []string { + return []string{ + ProtectionPolicyNoProtection, + ProtectionPolicyFullProtection, + } +} + const ( // RoutingStrategyTypeSimple is a RoutingStrategyType enum value RoutingStrategyTypeSimple = "SIMPLE" @@ -26819,6 +27228,14 @@ const ( RoutingStrategyTypeTerminal = "TERMINAL" ) +// RoutingStrategyType_Values returns all elements of the RoutingStrategyType enum +func RoutingStrategyType_Values() []string { + return []string{ + RoutingStrategyTypeSimple, + RoutingStrategyTypeTerminal, + } +} + const ( // ScalingAdjustmentTypeChangeInCapacity is a ScalingAdjustmentType enum value ScalingAdjustmentTypeChangeInCapacity = "ChangeInCapacity" @@ -26830,6 +27247,15 @@ const ( ScalingAdjustmentTypePercentChangeInCapacity = "PercentChangeInCapacity" ) +// ScalingAdjustmentType_Values returns all elements of the ScalingAdjustmentType enum +func ScalingAdjustmentType_Values() []string { + return []string{ + ScalingAdjustmentTypeChangeInCapacity, + ScalingAdjustmentTypeExactCapacity, + ScalingAdjustmentTypePercentChangeInCapacity, + } +} + const ( // ScalingStatusTypeActive is a ScalingStatusType enum value ScalingStatusTypeActive = "ACTIVE" @@ -26853,6 +27279,19 @@ const ( ScalingStatusTypeError = "ERROR" ) +// ScalingStatusType_Values returns all elements of the ScalingStatusType enum +func ScalingStatusType_Values() []string { + return []string{ + ScalingStatusTypeActive, + ScalingStatusTypeUpdateRequested, + ScalingStatusTypeUpdating, + ScalingStatusTypeDeleteRequested, + ScalingStatusTypeDeleting, + ScalingStatusTypeDeleted, + ScalingStatusTypeError, + } +} + const ( // SortOrderAscending is a SortOrder enum value SortOrderAscending = "ASCENDING" @@ -26860,3 +27299,11 @@ const ( // SortOrderDescending is a SortOrder enum value SortOrderDescending = "DESCENDING" ) + +// SortOrder_Values returns all elements of the SortOrder enum +func SortOrder_Values() []string { + return []string{ + SortOrderAscending, + SortOrderDescending, + } +} 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 4ddaba08c45..9201d9da054 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 @@ -8986,6 +8986,15 @@ const ( ActionCodeSelect = "Select" ) +// ActionCode_Values returns all elements of the ActionCode enum +func ActionCode_Values() []string { + return []string{ + ActionCodeArchiveRetrieval, + ActionCodeInventoryRetrieval, + ActionCodeSelect, + } +} + const ( // CannedACLPrivate is a CannedACL enum value CannedACLPrivate = "private" @@ -9009,6 +9018,19 @@ const ( CannedACLBucketOwnerFullControl = "bucket-owner-full-control" ) +// CannedACL_Values returns all elements of the CannedACL enum +func CannedACL_Values() []string { + return []string{ + CannedACLPrivate, + CannedACLPublicRead, + CannedACLPublicReadWrite, + CannedACLAwsExecRead, + CannedACLAuthenticatedRead, + CannedACLBucketOwnerRead, + CannedACLBucketOwnerFullControl, + } +} + const ( // EncryptionTypeAwsKms is a EncryptionType enum value EncryptionTypeAwsKms = "aws:kms" @@ -9017,11 +9039,26 @@ const ( EncryptionTypeAes256 = "AES256" ) +// EncryptionType_Values returns all elements of the EncryptionType enum +func EncryptionType_Values() []string { + return []string{ + EncryptionTypeAwsKms, + EncryptionTypeAes256, + } +} + const ( // ExpressionTypeSql is a ExpressionType enum value ExpressionTypeSql = "SQL" ) +// ExpressionType_Values returns all elements of the ExpressionType enum +func ExpressionType_Values() []string { + return []string{ + ExpressionTypeSql, + } +} + const ( // FileHeaderInfoUse is a FileHeaderInfo enum value FileHeaderInfoUse = "USE" @@ -9033,6 +9070,15 @@ const ( FileHeaderInfoNone = "NONE" ) +// FileHeaderInfo_Values returns all elements of the FileHeaderInfo enum +func FileHeaderInfo_Values() []string { + return []string{ + FileHeaderInfoUse, + FileHeaderInfoIgnore, + FileHeaderInfoNone, + } +} + const ( // PermissionFullControl is a Permission enum value PermissionFullControl = "FULL_CONTROL" @@ -9050,6 +9096,17 @@ const ( PermissionReadAcp = "READ_ACP" ) +// Permission_Values returns all elements of the Permission enum +func Permission_Values() []string { + return []string{ + PermissionFullControl, + PermissionWrite, + PermissionWriteAcp, + PermissionRead, + PermissionReadAcp, + } +} + const ( // QuoteFieldsAlways is a QuoteFields enum value QuoteFieldsAlways = "ALWAYS" @@ -9058,6 +9115,14 @@ const ( QuoteFieldsAsneeded = "ASNEEDED" ) +// QuoteFields_Values returns all elements of the QuoteFields enum +func QuoteFields_Values() []string { + return []string{ + QuoteFieldsAlways, + QuoteFieldsAsneeded, + } +} + const ( // StatusCodeInProgress is a StatusCode enum value StatusCodeInProgress = "InProgress" @@ -9069,6 +9134,15 @@ const ( StatusCodeFailed = "Failed" ) +// StatusCode_Values returns all elements of the StatusCode enum +func StatusCode_Values() []string { + return []string{ + StatusCodeInProgress, + StatusCodeSucceeded, + StatusCodeFailed, + } +} + const ( // StorageClassStandard is a StorageClass enum value StorageClassStandard = "STANDARD" @@ -9080,6 +9154,15 @@ const ( StorageClassStandardIa = "STANDARD_IA" ) +// StorageClass_Values returns all elements of the StorageClass enum +func StorageClass_Values() []string { + return []string{ + StorageClassStandard, + StorageClassReducedRedundancy, + StorageClassStandardIa, + } +} + const ( // TypeAmazonCustomerByEmail is a Type enum value TypeAmazonCustomerByEmail = "AmazonCustomerByEmail" @@ -9090,3 +9173,12 @@ const ( // TypeGroup is a Type enum value TypeGroup = "Group" ) + +// Type_Values returns all elements of the Type enum +func Type_Values() []string { + return []string{ + TypeAmazonCustomerByEmail, + TypeCanonicalUser, + TypeGroup, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/globalaccelerator/api.go b/vendor/github.com/aws/aws-sdk-go/service/globalaccelerator/api.go index 4f7f98e02e0..49b904885a0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/globalaccelerator/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/globalaccelerator/api.go @@ -6179,6 +6179,14 @@ const ( AcceleratorStatusInProgress = "IN_PROGRESS" ) +// AcceleratorStatus_Values returns all elements of the AcceleratorStatus enum +func AcceleratorStatus_Values() []string { + return []string{ + AcceleratorStatusDeployed, + AcceleratorStatusInProgress, + } +} + const ( // ByoipCidrStatePendingProvisioning is a ByoipCidrState enum value ByoipCidrStatePendingProvisioning = "PENDING_PROVISIONING" @@ -6214,6 +6222,23 @@ const ( ByoipCidrStateFailedDeprovision = "FAILED_DEPROVISION" ) +// ByoipCidrState_Values returns all elements of the ByoipCidrState enum +func ByoipCidrState_Values() []string { + return []string{ + ByoipCidrStatePendingProvisioning, + ByoipCidrStateReady, + ByoipCidrStatePendingAdvertising, + ByoipCidrStateAdvertising, + ByoipCidrStatePendingWithdrawing, + ByoipCidrStatePendingDeprovisioning, + ByoipCidrStateDeprovisioned, + ByoipCidrStateFailedProvision, + ByoipCidrStateFailedAdvertising, + ByoipCidrStateFailedWithdraw, + ByoipCidrStateFailedDeprovision, + } +} + const ( // ClientAffinityNone is a ClientAffinity enum value ClientAffinityNone = "NONE" @@ -6222,6 +6247,14 @@ const ( ClientAffinitySourceIp = "SOURCE_IP" ) +// ClientAffinity_Values returns all elements of the ClientAffinity enum +func ClientAffinity_Values() []string { + return []string{ + ClientAffinityNone, + ClientAffinitySourceIp, + } +} + const ( // HealthCheckProtocolTcp is a HealthCheckProtocol enum value HealthCheckProtocolTcp = "TCP" @@ -6233,6 +6266,15 @@ const ( HealthCheckProtocolHttps = "HTTPS" ) +// HealthCheckProtocol_Values returns all elements of the HealthCheckProtocol enum +func HealthCheckProtocol_Values() []string { + return []string{ + HealthCheckProtocolTcp, + HealthCheckProtocolHttp, + HealthCheckProtocolHttps, + } +} + const ( // HealthStateInitial is a HealthState enum value HealthStateInitial = "INITIAL" @@ -6244,11 +6286,27 @@ const ( HealthStateUnhealthy = "UNHEALTHY" ) +// HealthState_Values returns all elements of the HealthState enum +func HealthState_Values() []string { + return []string{ + HealthStateInitial, + HealthStateHealthy, + HealthStateUnhealthy, + } +} + const ( // IpAddressTypeIpv4 is a IpAddressType enum value IpAddressTypeIpv4 = "IPV4" ) +// IpAddressType_Values returns all elements of the IpAddressType enum +func IpAddressType_Values() []string { + return []string{ + IpAddressTypeIpv4, + } +} + const ( // ProtocolTcp is a Protocol enum value ProtocolTcp = "TCP" @@ -6256,3 +6314,11 @@ const ( // ProtocolUdp is a Protocol enum value ProtocolUdp = "UDP" ) + +// Protocol_Values returns all elements of the Protocol enum +func Protocol_Values() []string { + return []string{ + ProtocolTcp, + ProtocolUdp, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/glue/api.go b/vendor/github.com/aws/aws-sdk-go/service/glue/api.go index 965e0382e61..65c4941a502 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/glue/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/glue/api.go @@ -2595,6 +2595,190 @@ func (c *Glue) DeleteClassifierWithContext(ctx aws.Context, input *DeleteClassif return out, req.Send() } +const opDeleteColumnStatisticsForPartition = "DeleteColumnStatisticsForPartition" + +// DeleteColumnStatisticsForPartitionRequest generates a "aws/request.Request" representing the +// client's request for the DeleteColumnStatisticsForPartition operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteColumnStatisticsForPartition for more information on using the DeleteColumnStatisticsForPartition +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteColumnStatisticsForPartitionRequest method. +// req, resp := client.DeleteColumnStatisticsForPartitionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/DeleteColumnStatisticsForPartition +func (c *Glue) DeleteColumnStatisticsForPartitionRequest(input *DeleteColumnStatisticsForPartitionInput) (req *request.Request, output *DeleteColumnStatisticsForPartitionOutput) { + op := &request.Operation{ + Name: opDeleteColumnStatisticsForPartition, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteColumnStatisticsForPartitionInput{} + } + + output = &DeleteColumnStatisticsForPartitionOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteColumnStatisticsForPartition API operation for AWS Glue. +// +// Delete the partition column statistics of a column. +// +// Returns awserr.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 Glue's +// API operation DeleteColumnStatisticsForPartition for usage and error information. +// +// Returned Error Types: +// * EntityNotFoundException +// A specified entity does not exist +// +// * InvalidInputException +// The input provided was not valid. +// +// * InternalServiceException +// An internal service error occurred. +// +// * OperationTimeoutException +// The operation timed out. +// +// * EncryptionException +// An encryption operation failed. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/DeleteColumnStatisticsForPartition +func (c *Glue) DeleteColumnStatisticsForPartition(input *DeleteColumnStatisticsForPartitionInput) (*DeleteColumnStatisticsForPartitionOutput, error) { + req, out := c.DeleteColumnStatisticsForPartitionRequest(input) + return out, req.Send() +} + +// DeleteColumnStatisticsForPartitionWithContext is the same as DeleteColumnStatisticsForPartition with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteColumnStatisticsForPartition for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glue) DeleteColumnStatisticsForPartitionWithContext(ctx aws.Context, input *DeleteColumnStatisticsForPartitionInput, opts ...request.Option) (*DeleteColumnStatisticsForPartitionOutput, error) { + req, out := c.DeleteColumnStatisticsForPartitionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteColumnStatisticsForTable = "DeleteColumnStatisticsForTable" + +// DeleteColumnStatisticsForTableRequest generates a "aws/request.Request" representing the +// client's request for the DeleteColumnStatisticsForTable operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteColumnStatisticsForTable for more information on using the DeleteColumnStatisticsForTable +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteColumnStatisticsForTableRequest method. +// req, resp := client.DeleteColumnStatisticsForTableRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/DeleteColumnStatisticsForTable +func (c *Glue) DeleteColumnStatisticsForTableRequest(input *DeleteColumnStatisticsForTableInput) (req *request.Request, output *DeleteColumnStatisticsForTableOutput) { + op := &request.Operation{ + Name: opDeleteColumnStatisticsForTable, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteColumnStatisticsForTableInput{} + } + + output = &DeleteColumnStatisticsForTableOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteColumnStatisticsForTable API operation for AWS Glue. +// +// Retrieves table statistics of columns. +// +// Returns awserr.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 Glue's +// API operation DeleteColumnStatisticsForTable for usage and error information. +// +// Returned Error Types: +// * EntityNotFoundException +// A specified entity does not exist +// +// * InvalidInputException +// The input provided was not valid. +// +// * InternalServiceException +// An internal service error occurred. +// +// * OperationTimeoutException +// The operation timed out. +// +// * EncryptionException +// An encryption operation failed. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/DeleteColumnStatisticsForTable +func (c *Glue) DeleteColumnStatisticsForTable(input *DeleteColumnStatisticsForTableInput) (*DeleteColumnStatisticsForTableOutput, error) { + req, out := c.DeleteColumnStatisticsForTableRequest(input) + return out, req.Send() +} + +// DeleteColumnStatisticsForTableWithContext is the same as DeleteColumnStatisticsForTable with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteColumnStatisticsForTable for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glue) DeleteColumnStatisticsForTableWithContext(ctx aws.Context, input *DeleteColumnStatisticsForTableInput, opts ...request.Option) (*DeleteColumnStatisticsForTableOutput, error) { + req, out := c.DeleteColumnStatisticsForTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteConnection = "DeleteConnection" // DeleteConnectionRequest generates a "aws/request.Request" representing the @@ -4160,6 +4344,188 @@ func (c *Glue) GetClassifiersPagesWithContext(ctx aws.Context, input *GetClassif return p.Err() } +const opGetColumnStatisticsForPartition = "GetColumnStatisticsForPartition" + +// GetColumnStatisticsForPartitionRequest generates a "aws/request.Request" representing the +// client's request for the GetColumnStatisticsForPartition operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetColumnStatisticsForPartition for more information on using the GetColumnStatisticsForPartition +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetColumnStatisticsForPartitionRequest method. +// req, resp := client.GetColumnStatisticsForPartitionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/GetColumnStatisticsForPartition +func (c *Glue) GetColumnStatisticsForPartitionRequest(input *GetColumnStatisticsForPartitionInput) (req *request.Request, output *GetColumnStatisticsForPartitionOutput) { + op := &request.Operation{ + Name: opGetColumnStatisticsForPartition, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetColumnStatisticsForPartitionInput{} + } + + output = &GetColumnStatisticsForPartitionOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetColumnStatisticsForPartition API operation for AWS Glue. +// +// Retrieves partition statistics of columns. +// +// Returns awserr.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 Glue's +// API operation GetColumnStatisticsForPartition for usage and error information. +// +// Returned Error Types: +// * EntityNotFoundException +// A specified entity does not exist +// +// * InvalidInputException +// The input provided was not valid. +// +// * InternalServiceException +// An internal service error occurred. +// +// * OperationTimeoutException +// The operation timed out. +// +// * EncryptionException +// An encryption operation failed. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/GetColumnStatisticsForPartition +func (c *Glue) GetColumnStatisticsForPartition(input *GetColumnStatisticsForPartitionInput) (*GetColumnStatisticsForPartitionOutput, error) { + req, out := c.GetColumnStatisticsForPartitionRequest(input) + return out, req.Send() +} + +// GetColumnStatisticsForPartitionWithContext is the same as GetColumnStatisticsForPartition with the addition of +// the ability to pass a context and additional request options. +// +// See GetColumnStatisticsForPartition for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glue) GetColumnStatisticsForPartitionWithContext(ctx aws.Context, input *GetColumnStatisticsForPartitionInput, opts ...request.Option) (*GetColumnStatisticsForPartitionOutput, error) { + req, out := c.GetColumnStatisticsForPartitionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetColumnStatisticsForTable = "GetColumnStatisticsForTable" + +// GetColumnStatisticsForTableRequest generates a "aws/request.Request" representing the +// client's request for the GetColumnStatisticsForTable operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetColumnStatisticsForTable for more information on using the GetColumnStatisticsForTable +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetColumnStatisticsForTableRequest method. +// req, resp := client.GetColumnStatisticsForTableRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/GetColumnStatisticsForTable +func (c *Glue) GetColumnStatisticsForTableRequest(input *GetColumnStatisticsForTableInput) (req *request.Request, output *GetColumnStatisticsForTableOutput) { + op := &request.Operation{ + Name: opGetColumnStatisticsForTable, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetColumnStatisticsForTableInput{} + } + + output = &GetColumnStatisticsForTableOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetColumnStatisticsForTable API operation for AWS Glue. +// +// Retrieves table statistics of columns. +// +// Returns awserr.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 Glue's +// API operation GetColumnStatisticsForTable for usage and error information. +// +// Returned Error Types: +// * EntityNotFoundException +// A specified entity does not exist +// +// * InvalidInputException +// The input provided was not valid. +// +// * InternalServiceException +// An internal service error occurred. +// +// * OperationTimeoutException +// The operation timed out. +// +// * EncryptionException +// An encryption operation failed. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/GetColumnStatisticsForTable +func (c *Glue) GetColumnStatisticsForTable(input *GetColumnStatisticsForTableInput) (*GetColumnStatisticsForTableOutput, error) { + req, out := c.GetColumnStatisticsForTableRequest(input) + return out, req.Send() +} + +// GetColumnStatisticsForTableWithContext is the same as GetColumnStatisticsForTable with the addition of +// the ability to pass a context and additional request options. +// +// See GetColumnStatisticsForTable for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glue) GetColumnStatisticsForTableWithContext(ctx aws.Context, input *GetColumnStatisticsForTableInput, opts ...request.Option) (*GetColumnStatisticsForTableOutput, error) { + req, out := c.GetColumnStatisticsForTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetConnection = "GetConnection" // GetConnectionRequest generates a "aws/request.Request" representing the @@ -6860,6 +7226,100 @@ func (c *Glue) GetPlanWithContext(ctx aws.Context, input *GetPlanInput, opts ... return out, req.Send() } +const opGetResourcePolicies = "GetResourcePolicies" + +// GetResourcePoliciesRequest generates a "aws/request.Request" representing the +// client's request for the GetResourcePolicies operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetResourcePolicies for more information on using the GetResourcePolicies +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetResourcePoliciesRequest method. +// req, resp := client.GetResourcePoliciesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/GetResourcePolicies +func (c *Glue) GetResourcePoliciesRequest(input *GetResourcePoliciesInput) (req *request.Request, output *GetResourcePoliciesOutput) { + op := &request.Operation{ + Name: opGetResourcePolicies, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetResourcePoliciesInput{} + } + + output = &GetResourcePoliciesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetResourcePolicies API operation for AWS Glue. +// +// Retrieves the security configurations for the resource policies set on individual +// resources, and also the account-level policy. +// +// This operation also returns the Data Catalog resource policy. However, if +// you enabled metadata encryption in Data Catalog settings, and you do not +// have permission on the AWS KMS key, the operation can't return the Data Catalog +// resource 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. +// +// See the AWS API reference guide for AWS Glue's +// API operation GetResourcePolicies for usage and error information. +// +// Returned Error Types: +// * InternalServiceException +// An internal service error occurred. +// +// * OperationTimeoutException +// The operation timed out. +// +// * InvalidInputException +// The input provided was not valid. +// +// * EncryptionException +// An encryption operation failed. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/GetResourcePolicies +func (c *Glue) GetResourcePolicies(input *GetResourcePoliciesInput) (*GetResourcePoliciesOutput, error) { + req, out := c.GetResourcePoliciesRequest(input) + return out, req.Send() +} + +// GetResourcePoliciesWithContext is the same as GetResourcePolicies with the addition of +// the ability to pass a context and additional request options. +// +// See GetResourcePolicies for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glue) GetResourcePoliciesWithContext(ctx aws.Context, input *GetResourcePoliciesInput, opts ...request.Option) (*GetResourcePoliciesOutput, error) { + req, out := c.GetResourcePoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetResourcePolicy = "GetResourcePolicy" // GetResourcePolicyRequest generates a "aws/request.Request" representing the @@ -9977,6 +10437,102 @@ func (c *Glue) ResetJobBookmarkWithContext(ctx aws.Context, input *ResetJobBookm return out, req.Send() } +const opResumeWorkflowRun = "ResumeWorkflowRun" + +// ResumeWorkflowRunRequest generates a "aws/request.Request" representing the +// client's request for the ResumeWorkflowRun operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ResumeWorkflowRun for more information on using the ResumeWorkflowRun +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ResumeWorkflowRunRequest method. +// req, resp := client.ResumeWorkflowRunRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/ResumeWorkflowRun +func (c *Glue) ResumeWorkflowRunRequest(input *ResumeWorkflowRunInput) (req *request.Request, output *ResumeWorkflowRunOutput) { + op := &request.Operation{ + Name: opResumeWorkflowRun, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ResumeWorkflowRunInput{} + } + + output = &ResumeWorkflowRunOutput{} + req = c.newRequest(op, input, output) + return +} + +// ResumeWorkflowRun API operation for AWS Glue. +// +// Restarts selected nodes of a previous partially completed workflow run and +// resumes the workflow run. The selected nodes and all nodes that are downstream +// from the selected nodes are 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 Glue's +// API operation ResumeWorkflowRun for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input provided was not valid. +// +// * EntityNotFoundException +// A specified entity does not exist +// +// * InternalServiceException +// An internal service error occurred. +// +// * OperationTimeoutException +// The operation timed out. +// +// * ConcurrentRunsExceededException +// Too many jobs are being run concurrently. +// +// * IllegalWorkflowStateException +// The workflow is in an invalid state to perform a requested operation. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/ResumeWorkflowRun +func (c *Glue) ResumeWorkflowRun(input *ResumeWorkflowRunInput) (*ResumeWorkflowRunOutput, error) { + req, out := c.ResumeWorkflowRunRequest(input) + return out, req.Send() +} + +// ResumeWorkflowRunWithContext is the same as ResumeWorkflowRun with the addition of +// the ability to pass a context and additional request options. +// +// See ResumeWorkflowRun for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glue) ResumeWorkflowRunWithContext(ctx aws.Context, input *ResumeWorkflowRunInput, opts ...request.Option) (*ResumeWorkflowRunOutput, error) { + req, out := c.ResumeWorkflowRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opSearchTables = "SearchTables" // SearchTablesRequest generates a "aws/request.Request" representing the @@ -11279,6 +11835,98 @@ func (c *Glue) StopTriggerWithContext(ctx aws.Context, input *StopTriggerInput, return out, req.Send() } +const opStopWorkflowRun = "StopWorkflowRun" + +// StopWorkflowRunRequest generates a "aws/request.Request" representing the +// client's request for the StopWorkflowRun operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See StopWorkflowRun for more information on using the StopWorkflowRun +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the StopWorkflowRunRequest method. +// req, resp := client.StopWorkflowRunRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/StopWorkflowRun +func (c *Glue) StopWorkflowRunRequest(input *StopWorkflowRunInput) (req *request.Request, output *StopWorkflowRunOutput) { + op := &request.Operation{ + Name: opStopWorkflowRun, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &StopWorkflowRunInput{} + } + + output = &StopWorkflowRunOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// StopWorkflowRun API operation for AWS Glue. +// +// Stops the execution of the specified workflow 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 Glue's +// API operation StopWorkflowRun for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// The input provided was not valid. +// +// * EntityNotFoundException +// A specified entity does not exist +// +// * InternalServiceException +// An internal service error occurred. +// +// * OperationTimeoutException +// The operation timed out. +// +// * IllegalWorkflowStateException +// The workflow is in an invalid state to perform a requested operation. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/StopWorkflowRun +func (c *Glue) StopWorkflowRun(input *StopWorkflowRunInput) (*StopWorkflowRunOutput, error) { + req, out := c.StopWorkflowRunRequest(input) + return out, req.Send() +} + +// StopWorkflowRunWithContext is the same as StopWorkflowRun with the addition of +// the ability to pass a context and additional request options. +// +// See StopWorkflowRun for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glue) StopWorkflowRunWithContext(ctx aws.Context, input *StopWorkflowRunInput, opts ...request.Option) (*StopWorkflowRunOutput, error) { + req, out := c.StopWorkflowRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opTagResource = "TagResource" // TagResourceRequest generates a "aws/request.Request" representing the @@ -11549,6 +12197,188 @@ func (c *Glue) UpdateClassifierWithContext(ctx aws.Context, input *UpdateClassif return out, req.Send() } +const opUpdateColumnStatisticsForPartition = "UpdateColumnStatisticsForPartition" + +// UpdateColumnStatisticsForPartitionRequest generates a "aws/request.Request" representing the +// client's request for the UpdateColumnStatisticsForPartition operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateColumnStatisticsForPartition for more information on using the UpdateColumnStatisticsForPartition +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateColumnStatisticsForPartitionRequest method. +// req, resp := client.UpdateColumnStatisticsForPartitionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/UpdateColumnStatisticsForPartition +func (c *Glue) UpdateColumnStatisticsForPartitionRequest(input *UpdateColumnStatisticsForPartitionInput) (req *request.Request, output *UpdateColumnStatisticsForPartitionOutput) { + op := &request.Operation{ + Name: opUpdateColumnStatisticsForPartition, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateColumnStatisticsForPartitionInput{} + } + + output = &UpdateColumnStatisticsForPartitionOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateColumnStatisticsForPartition API operation for AWS Glue. +// +// Creates or updates partition statistics of columns. +// +// Returns awserr.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 Glue's +// API operation UpdateColumnStatisticsForPartition for usage and error information. +// +// Returned Error Types: +// * EntityNotFoundException +// A specified entity does not exist +// +// * InvalidInputException +// The input provided was not valid. +// +// * InternalServiceException +// An internal service error occurred. +// +// * OperationTimeoutException +// The operation timed out. +// +// * EncryptionException +// An encryption operation failed. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/UpdateColumnStatisticsForPartition +func (c *Glue) UpdateColumnStatisticsForPartition(input *UpdateColumnStatisticsForPartitionInput) (*UpdateColumnStatisticsForPartitionOutput, error) { + req, out := c.UpdateColumnStatisticsForPartitionRequest(input) + return out, req.Send() +} + +// UpdateColumnStatisticsForPartitionWithContext is the same as UpdateColumnStatisticsForPartition with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateColumnStatisticsForPartition for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glue) UpdateColumnStatisticsForPartitionWithContext(ctx aws.Context, input *UpdateColumnStatisticsForPartitionInput, opts ...request.Option) (*UpdateColumnStatisticsForPartitionOutput, error) { + req, out := c.UpdateColumnStatisticsForPartitionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateColumnStatisticsForTable = "UpdateColumnStatisticsForTable" + +// UpdateColumnStatisticsForTableRequest generates a "aws/request.Request" representing the +// client's request for the UpdateColumnStatisticsForTable operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateColumnStatisticsForTable for more information on using the UpdateColumnStatisticsForTable +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateColumnStatisticsForTableRequest method. +// req, resp := client.UpdateColumnStatisticsForTableRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/UpdateColumnStatisticsForTable +func (c *Glue) UpdateColumnStatisticsForTableRequest(input *UpdateColumnStatisticsForTableInput) (req *request.Request, output *UpdateColumnStatisticsForTableOutput) { + op := &request.Operation{ + Name: opUpdateColumnStatisticsForTable, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateColumnStatisticsForTableInput{} + } + + output = &UpdateColumnStatisticsForTableOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateColumnStatisticsForTable API operation for AWS Glue. +// +// Creates or updates table statistics of columns. +// +// Returns awserr.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 Glue's +// API operation UpdateColumnStatisticsForTable for usage and error information. +// +// Returned Error Types: +// * EntityNotFoundException +// A specified entity does not exist +// +// * InvalidInputException +// The input provided was not valid. +// +// * InternalServiceException +// An internal service error occurred. +// +// * OperationTimeoutException +// The operation timed out. +// +// * EncryptionException +// An encryption operation failed. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/UpdateColumnStatisticsForTable +func (c *Glue) UpdateColumnStatisticsForTable(input *UpdateColumnStatisticsForTableInput) (*UpdateColumnStatisticsForTableOutput, error) { + req, out := c.UpdateColumnStatisticsForTableRequest(input) + return out, req.Send() +} + +// UpdateColumnStatisticsForTableWithContext is the same as UpdateColumnStatisticsForTable with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateColumnStatisticsForTable for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Glue) UpdateColumnStatisticsForTableWithContext(ctx aws.Context, input *UpdateColumnStatisticsForTableInput, opts ...request.Option) (*UpdateColumnStatisticsForTableOutput, error) { + req, out := c.UpdateColumnStatisticsForTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opUpdateConnection = "UpdateConnection" // UpdateConnectionRequest generates a "aws/request.Request" representing the @@ -14073,6 +14903,140 @@ func (s *BatchStopJobRunSuccessfulSubmission) SetJobRunId(v string) *BatchStopJo return s } +// Defines a binary column statistics data. +type BinaryColumnStatisticsData struct { + _ struct{} `type:"structure"` + + // Average length of the column. + // + // AverageLength is a required field + AverageLength *float64 `type:"double" required:"true"` + + // Maximum length of the column. + // + // MaximumLength is a required field + MaximumLength *int64 `type:"long" required:"true"` + + // Number of nulls. + // + // NumberOfNulls is a required field + NumberOfNulls *int64 `type:"long" required:"true"` +} + +// String returns the string representation +func (s BinaryColumnStatisticsData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BinaryColumnStatisticsData) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *BinaryColumnStatisticsData) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "BinaryColumnStatisticsData"} + if s.AverageLength == nil { + invalidParams.Add(request.NewErrParamRequired("AverageLength")) + } + if s.MaximumLength == nil { + invalidParams.Add(request.NewErrParamRequired("MaximumLength")) + } + if s.NumberOfNulls == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfNulls")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAverageLength sets the AverageLength field's value. +func (s *BinaryColumnStatisticsData) SetAverageLength(v float64) *BinaryColumnStatisticsData { + s.AverageLength = &v + return s +} + +// SetMaximumLength sets the MaximumLength field's value. +func (s *BinaryColumnStatisticsData) SetMaximumLength(v int64) *BinaryColumnStatisticsData { + s.MaximumLength = &v + return s +} + +// SetNumberOfNulls sets the NumberOfNulls field's value. +func (s *BinaryColumnStatisticsData) SetNumberOfNulls(v int64) *BinaryColumnStatisticsData { + s.NumberOfNulls = &v + return s +} + +// Defines a boolean column statistics. +type BooleanColumnStatisticsData struct { + _ struct{} `type:"structure"` + + // Number of false value. + // + // NumberOfFalses is a required field + NumberOfFalses *int64 `type:"long" required:"true"` + + // Number of nulls. + // + // NumberOfNulls is a required field + NumberOfNulls *int64 `type:"long" required:"true"` + + // Number of true value. + // + // NumberOfTrues is a required field + NumberOfTrues *int64 `type:"long" required:"true"` +} + +// String returns the string representation +func (s BooleanColumnStatisticsData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BooleanColumnStatisticsData) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *BooleanColumnStatisticsData) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "BooleanColumnStatisticsData"} + if s.NumberOfFalses == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfFalses")) + } + if s.NumberOfNulls == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfNulls")) + } + if s.NumberOfTrues == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfTrues")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetNumberOfFalses sets the NumberOfFalses field's value. +func (s *BooleanColumnStatisticsData) SetNumberOfFalses(v int64) *BooleanColumnStatisticsData { + s.NumberOfFalses = &v + return s +} + +// SetNumberOfNulls sets the NumberOfNulls field's value. +func (s *BooleanColumnStatisticsData) SetNumberOfNulls(v int64) *BooleanColumnStatisticsData { + s.NumberOfNulls = &v + return s +} + +// SetNumberOfTrues sets the NumberOfTrues field's value. +func (s *BooleanColumnStatisticsData) SetNumberOfTrues(v int64) *BooleanColumnStatisticsData { + s.NumberOfTrues = &v + return s +} + type CancelMLTaskRunInput struct { _ struct{} `type:"structure"` @@ -14712,6 +15676,298 @@ func (s *Column) SetType(v string) *Column { return s } +// Defines a column containing error. +type ColumnError struct { + _ struct{} `type:"structure"` + + // The name of the column. + ColumnName *string `min:"1" type:"string"` + + // The error message occurred during operation. + Error *ErrorDetail `type:"structure"` +} + +// String returns the string representation +func (s ColumnError) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ColumnError) GoString() string { + return s.String() +} + +// SetColumnName sets the ColumnName field's value. +func (s *ColumnError) SetColumnName(v string) *ColumnError { + s.ColumnName = &v + return s +} + +// SetError sets the Error field's value. +func (s *ColumnError) SetError(v *ErrorDetail) *ColumnError { + s.Error = v + return s +} + +// Defines a column statistics. +type ColumnStatistics struct { + _ struct{} `type:"structure"` + + // The analyzed time of the column statistics. + // + // AnalyzedTime is a required field + AnalyzedTime *time.Time `type:"timestamp" required:"true"` + + // The name of the column. + // + // ColumnName is a required field + ColumnName *string `min:"1" type:"string" required:"true"` + + // The type of the column. + // + // ColumnType is a required field + ColumnType *string `type:"string" required:"true"` + + // The statistics of the column. + // + // StatisticsData is a required field + StatisticsData *ColumnStatisticsData `type:"structure" required:"true"` +} + +// String returns the string representation +func (s ColumnStatistics) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ColumnStatistics) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ColumnStatistics) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ColumnStatistics"} + if s.AnalyzedTime == nil { + invalidParams.Add(request.NewErrParamRequired("AnalyzedTime")) + } + if s.ColumnName == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnName")) + } + if s.ColumnName != nil && len(*s.ColumnName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ColumnName", 1)) + } + if s.ColumnType == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnType")) + } + if s.StatisticsData == nil { + invalidParams.Add(request.NewErrParamRequired("StatisticsData")) + } + if s.StatisticsData != nil { + if err := s.StatisticsData.Validate(); err != nil { + invalidParams.AddNested("StatisticsData", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAnalyzedTime sets the AnalyzedTime field's value. +func (s *ColumnStatistics) SetAnalyzedTime(v time.Time) *ColumnStatistics { + s.AnalyzedTime = &v + return s +} + +// SetColumnName sets the ColumnName field's value. +func (s *ColumnStatistics) SetColumnName(v string) *ColumnStatistics { + s.ColumnName = &v + return s +} + +// SetColumnType sets the ColumnType field's value. +func (s *ColumnStatistics) SetColumnType(v string) *ColumnStatistics { + s.ColumnType = &v + return s +} + +// SetStatisticsData sets the StatisticsData field's value. +func (s *ColumnStatistics) SetStatisticsData(v *ColumnStatisticsData) *ColumnStatistics { + s.StatisticsData = v + return s +} + +// Defines a column statistics data. +type ColumnStatisticsData struct { + _ struct{} `type:"structure"` + + // Binary Column Statistics Data. + BinaryColumnStatisticsData *BinaryColumnStatisticsData `type:"structure"` + + // Boolean Column Statistics Data. + BooleanColumnStatisticsData *BooleanColumnStatisticsData `type:"structure"` + + // Date Column Statistics Data. + DateColumnStatisticsData *DateColumnStatisticsData `type:"structure"` + + // Decimal Column Statistics Data. + DecimalColumnStatisticsData *DecimalColumnStatisticsData `type:"structure"` + + // Double Column Statistics Data. + DoubleColumnStatisticsData *DoubleColumnStatisticsData `type:"structure"` + + // Long Column Statistics Data. + LongColumnStatisticsData *LongColumnStatisticsData `type:"structure"` + + // String Column Statistics Data. + StringColumnStatisticsData *StringColumnStatisticsData `type:"structure"` + + // The name of the column. + // + // Type is a required field + Type *string `type:"string" required:"true" enum:"ColumnStatisticsType"` +} + +// String returns the string representation +func (s ColumnStatisticsData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ColumnStatisticsData) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ColumnStatisticsData) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ColumnStatisticsData"} + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + if s.BinaryColumnStatisticsData != nil { + if err := s.BinaryColumnStatisticsData.Validate(); err != nil { + invalidParams.AddNested("BinaryColumnStatisticsData", err.(request.ErrInvalidParams)) + } + } + if s.BooleanColumnStatisticsData != nil { + if err := s.BooleanColumnStatisticsData.Validate(); err != nil { + invalidParams.AddNested("BooleanColumnStatisticsData", err.(request.ErrInvalidParams)) + } + } + if s.DateColumnStatisticsData != nil { + if err := s.DateColumnStatisticsData.Validate(); err != nil { + invalidParams.AddNested("DateColumnStatisticsData", err.(request.ErrInvalidParams)) + } + } + if s.DecimalColumnStatisticsData != nil { + if err := s.DecimalColumnStatisticsData.Validate(); err != nil { + invalidParams.AddNested("DecimalColumnStatisticsData", err.(request.ErrInvalidParams)) + } + } + if s.DoubleColumnStatisticsData != nil { + if err := s.DoubleColumnStatisticsData.Validate(); err != nil { + invalidParams.AddNested("DoubleColumnStatisticsData", err.(request.ErrInvalidParams)) + } + } + if s.LongColumnStatisticsData != nil { + if err := s.LongColumnStatisticsData.Validate(); err != nil { + invalidParams.AddNested("LongColumnStatisticsData", err.(request.ErrInvalidParams)) + } + } + if s.StringColumnStatisticsData != nil { + if err := s.StringColumnStatisticsData.Validate(); err != nil { + invalidParams.AddNested("StringColumnStatisticsData", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBinaryColumnStatisticsData sets the BinaryColumnStatisticsData field's value. +func (s *ColumnStatisticsData) SetBinaryColumnStatisticsData(v *BinaryColumnStatisticsData) *ColumnStatisticsData { + s.BinaryColumnStatisticsData = v + return s +} + +// SetBooleanColumnStatisticsData sets the BooleanColumnStatisticsData field's value. +func (s *ColumnStatisticsData) SetBooleanColumnStatisticsData(v *BooleanColumnStatisticsData) *ColumnStatisticsData { + s.BooleanColumnStatisticsData = v + return s +} + +// SetDateColumnStatisticsData sets the DateColumnStatisticsData field's value. +func (s *ColumnStatisticsData) SetDateColumnStatisticsData(v *DateColumnStatisticsData) *ColumnStatisticsData { + s.DateColumnStatisticsData = v + return s +} + +// SetDecimalColumnStatisticsData sets the DecimalColumnStatisticsData field's value. +func (s *ColumnStatisticsData) SetDecimalColumnStatisticsData(v *DecimalColumnStatisticsData) *ColumnStatisticsData { + s.DecimalColumnStatisticsData = v + return s +} + +// SetDoubleColumnStatisticsData sets the DoubleColumnStatisticsData field's value. +func (s *ColumnStatisticsData) SetDoubleColumnStatisticsData(v *DoubleColumnStatisticsData) *ColumnStatisticsData { + s.DoubleColumnStatisticsData = v + return s +} + +// SetLongColumnStatisticsData sets the LongColumnStatisticsData field's value. +func (s *ColumnStatisticsData) SetLongColumnStatisticsData(v *LongColumnStatisticsData) *ColumnStatisticsData { + s.LongColumnStatisticsData = v + return s +} + +// SetStringColumnStatisticsData sets the StringColumnStatisticsData field's value. +func (s *ColumnStatisticsData) SetStringColumnStatisticsData(v *StringColumnStatisticsData) *ColumnStatisticsData { + s.StringColumnStatisticsData = v + return s +} + +// SetType sets the Type field's value. +func (s *ColumnStatisticsData) SetType(v string) *ColumnStatisticsData { + s.Type = &v + return s +} + +// Defines a column containing error. +type ColumnStatisticsError struct { + _ struct{} `type:"structure"` + + // The ColumnStatistics of the column. + ColumnStatistics *ColumnStatistics `type:"structure"` + + // The error message occurred during operation. + Error *ErrorDetail `type:"structure"` +} + +// String returns the string representation +func (s ColumnStatisticsError) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ColumnStatisticsError) GoString() string { + return s.String() +} + +// SetColumnStatistics sets the ColumnStatistics field's value. +func (s *ColumnStatisticsError) SetColumnStatistics(v *ColumnStatistics) *ColumnStatisticsError { + s.ColumnStatistics = v + return s +} + +// SetError sets the Error field's value. +func (s *ColumnStatisticsError) SetError(v *ErrorDetail) *ColumnStatisticsError { + s.Error = v + return s +} + // Two processes are trying to modify a resource simultaneously. type ConcurrentModificationException struct { _ struct{} `type:"structure"` @@ -14843,8 +16099,9 @@ type Condition struct { // A logical operator. LogicalOperator *string `type:"string" enum:"LogicalOperator"` - // The condition state. Currently, the values supported are SUCCEEDED, STOPPED, - // TIMEOUT, and FAILED. + // The condition state. Currently, the only job states that a trigger can listen + // for are SUCCEEDED, STOPPED, FAILED, and TIMEOUT. The only crawler states + // that a trigger can listen for are SUCCEEDED, FAILED, and CANCELLED. State *string `type:"string" enum:"JobRunState"` } @@ -15085,10 +16342,19 @@ type Connection struct { // * KAFKA_BOOTSTRAP_SERVERS - A comma-separated list of host and port pairs // that are the addresses of the Apache Kafka brokers in a Kafka cluster // to which a Kafka client will connect to and bootstrap itself. + // + // * KAFKA_SSL_ENABLED - Whether to enable or disable SSL on an Apache Kafka + // connection. Default value is "true". + // + // * KAFKA_CUSTOM_CERT - The Amazon S3 URL for the private CA cert file (.pem + // format). The default is an empty string. + // + // * KAFKA_SKIP_CUSTOM_CERT_VALIDATION - Whether to skip the validation of + // the CA cert file or not. AWS Glue validates for three algorithms: SHA256withRSA, + // SHA384withRSA and SHA512withRSA. Default value is "false". ConnectionProperties map[string]*string `type:"map"` - // The type of the connection. Currently, only JDBC is supported; SFTP is not - // supported. + // The type of the connection. Currently, SFTP is not supported. ConnectionType *string `type:"string" enum:"ConnectionType"` // The time that this connection definition was created. @@ -15196,6 +16462,9 @@ type ConnectionInput struct { // // * MONGODB - Designates a connection to a MongoDB document database. // + // * NETWORK - Designates a network connection to a data source within an + // Amazon Virtual Private Cloud environment (Amazon VPC). + // // SFTP is not supported. // // ConnectionType is a required field @@ -15467,7 +16736,7 @@ type Crawler struct { // Crawler configuration information. This versioned JSON string allows users // to specify aspects of a crawler's behavior. For more information, see Configuring - // a Crawler (http://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html). + // a Crawler (https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html). Configuration *string `type:"string"` // If the crawler is running, contains the total time elapsed since the last @@ -16157,9 +17426,9 @@ type CreateCrawlerInput struct { // always override the default classifiers for a given classification. Classifiers []*string `type:"list"` - // The crawler configuration information. This versioned JSON string allows - // users to specify aspects of a crawler's behavior. For more information, see - // Configuring a Crawler (http://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html). + // Crawler configuration information. This versioned JSON string allows users + // to specify aspects of a crawler's behavior. For more information, see Configuring + // a Crawler (https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html). Configuration *string `type:"string"` // The name of the SecurityConfiguration structure to be used by this crawler. @@ -16182,10 +17451,10 @@ type CreateCrawlerInput struct { // Role is a required field Role *string `type:"string" required:"true"` - // A cron expression used to specify the schedule. For more information, see - // Time-Based Schedules for Jobs and Crawlers (http://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html). - // For example, to run something every day at 12:15 UTC, specify cron(15 12 - // * * ? *). + // A cron expression used to specify the schedule (see Time-Based Schedules + // for Jobs and Crawlers (https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html). + // For example, to run something every day at 12:15 UTC, you would specify: + // cron(15 12 * * ? *). Schedule *string `type:"string"` // The policy for the crawler's update and deletion behavior. @@ -16194,8 +17463,10 @@ type CreateCrawlerInput struct { // The table prefix used for catalog tables that are created. TablePrefix *string `type:"string"` - // The tags to use with this crawler request. You can use tags to limit access - // to the crawler. For more information, see AWS Tags in AWS Glue (http://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html). + // The tags to use with this crawler request. You may use tags to limit access + // to the crawler. For more information about tags in AWS Glue, see AWS Tags + // in AWS Glue (https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html) + // in the developer guide. Tags map[string]*string `type:"map"` // A list of collection of targets to crawl. @@ -17084,9 +18355,10 @@ type CreateJobInput struct { // * When you specify a Python shell job (JobCommand.Name="pythonshell"), // you can allocate either 0.0625 or 1 DPU. The default is 0.0625 DPU. // - // * When you specify an Apache Spark ETL job (JobCommand.Name="glueetl"), - // you can allocate from 2 to 100 DPUs. The default is 10 DPUs. This job - // type cannot have a fractional DPU allocation. + // * When you specify an Apache Spark ETL job (JobCommand.Name="glueetl") + // or Apache Spark streaming ETL job (JobCommand.Name="gluestreaming"), you + // can allocate from 2 to 100 DPUs. The default is 10 DPUs. This job type + // cannot have a fractional DPU allocation. MaxCapacity *float64 `type:"double"` // The maximum number of times to retry this job if it fails. @@ -18307,6 +19579,12 @@ type CreateWorkflowInput struct { // A description of the workflow. Description *string `type:"string"` + // You can use this parameter to prevent unwanted multiple updates to data, + // to control costs, or in some cases, to prevent exceeding the maximum number + // of concurrent runs of any of the component jobs. If you leave this parameter + // blank, there is no limit to the number of concurrent workflow runs. + MaxConcurrentRuns *int64 `type:"integer"` + // The name to be assigned to the workflow. It should be unique within your // account. // @@ -18355,6 +19633,12 @@ func (s *CreateWorkflowInput) SetDescription(v string) *CreateWorkflowInput { return s } +// SetMaxConcurrentRuns sets the MaxConcurrentRuns field's value. +func (s *CreateWorkflowInput) SetMaxConcurrentRuns(v int64) *CreateWorkflowInput { + s.MaxConcurrentRuns = &v + return s +} + // SetName sets the Name field's value. func (s *CreateWorkflowInput) SetName(v string) *CreateWorkflowInput { s.Name = &v @@ -18666,6 +19950,9 @@ func (s *DataLakePrincipal) SetDataLakePrincipalIdentifier(v string) *DataLakePr type Database struct { _ struct{} `type:"structure"` + // The ID of the Data Catalog in which the database resides. + CatalogId *string `min:"1" type:"string"` + // Creates a set of default permissions on the table for principals. CreateTableDefaultPermissions []*PrincipalPermissions `type:"list"` @@ -18686,6 +19973,10 @@ type Database struct { // These key-value pairs define parameters and properties of the database. Parameters map[string]*string `type:"map"` + + // A DatabaseIdentifier structure that describes a target database for resource + // linking. + TargetDatabase *DatabaseIdentifier `type:"structure"` } // String returns the string representation @@ -18698,6 +19989,12 @@ func (s Database) GoString() string { return s.String() } +// SetCatalogId sets the CatalogId field's value. +func (s *Database) SetCatalogId(v string) *Database { + s.CatalogId = &v + return s +} + // SetCreateTableDefaultPermissions sets the CreateTableDefaultPermissions field's value. func (s *Database) SetCreateTableDefaultPermissions(v []*PrincipalPermissions) *Database { s.CreateTableDefaultPermissions = v @@ -18734,6 +20031,61 @@ func (s *Database) SetParameters(v map[string]*string) *Database { return s } +// SetTargetDatabase sets the TargetDatabase field's value. +func (s *Database) SetTargetDatabase(v *DatabaseIdentifier) *Database { + s.TargetDatabase = v + return s +} + +// A structure that describes a target database for resource linking. +type DatabaseIdentifier struct { + _ struct{} `type:"structure"` + + // The ID of the Data Catalog in which the database resides. + CatalogId *string `min:"1" type:"string"` + + // The name of the catalog database. + DatabaseName *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s DatabaseIdentifier) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DatabaseIdentifier) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DatabaseIdentifier) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DatabaseIdentifier"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } + if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCatalogId sets the CatalogId field's value. +func (s *DatabaseIdentifier) SetCatalogId(v string) *DatabaseIdentifier { + s.CatalogId = &v + return s +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *DatabaseIdentifier) SetDatabaseName(v string) *DatabaseIdentifier { + s.DatabaseName = &v + return s +} + // The structure used to create or update a database. type DatabaseInput struct { _ struct{} `type:"structure"` @@ -18757,6 +20109,10 @@ type DatabaseInput struct { // // These key-value pairs define parameters and properties of the database. Parameters map[string]*string `type:"map"` + + // A DatabaseIdentifier structure that describes a target database for resource + // linking. + TargetDatabase *DatabaseIdentifier `type:"structure"` } // String returns the string representation @@ -18791,6 +20147,11 @@ func (s *DatabaseInput) Validate() error { } } } + if s.TargetDatabase != nil { + if err := s.TargetDatabase.Validate(); err != nil { + invalidParams.AddNested("TargetDatabase", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -18828,6 +20189,219 @@ func (s *DatabaseInput) SetParameters(v map[string]*string) *DatabaseInput { return s } +// SetTargetDatabase sets the TargetDatabase field's value. +func (s *DatabaseInput) SetTargetDatabase(v *DatabaseIdentifier) *DatabaseInput { + s.TargetDatabase = v + return s +} + +// Defines a date column statistics data. +type DateColumnStatisticsData struct { + _ struct{} `type:"structure"` + + // Maximum value of the column. + MaximumValue *time.Time `type:"timestamp"` + + // Minimum value of the column. + MinimumValue *time.Time `type:"timestamp"` + + // Number of distinct values. + // + // NumberOfDistinctValues is a required field + NumberOfDistinctValues *int64 `type:"long" required:"true"` + + // Number of nulls. + // + // NumberOfNulls is a required field + NumberOfNulls *int64 `type:"long" required:"true"` +} + +// String returns the string representation +func (s DateColumnStatisticsData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DateColumnStatisticsData) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DateColumnStatisticsData) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DateColumnStatisticsData"} + if s.NumberOfDistinctValues == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfDistinctValues")) + } + if s.NumberOfNulls == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfNulls")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaximumValue sets the MaximumValue field's value. +func (s *DateColumnStatisticsData) SetMaximumValue(v time.Time) *DateColumnStatisticsData { + s.MaximumValue = &v + return s +} + +// SetMinimumValue sets the MinimumValue field's value. +func (s *DateColumnStatisticsData) SetMinimumValue(v time.Time) *DateColumnStatisticsData { + s.MinimumValue = &v + return s +} + +// SetNumberOfDistinctValues sets the NumberOfDistinctValues field's value. +func (s *DateColumnStatisticsData) SetNumberOfDistinctValues(v int64) *DateColumnStatisticsData { + s.NumberOfDistinctValues = &v + return s +} + +// SetNumberOfNulls sets the NumberOfNulls field's value. +func (s *DateColumnStatisticsData) SetNumberOfNulls(v int64) *DateColumnStatisticsData { + s.NumberOfNulls = &v + return s +} + +// Defines a decimal column statistics data. +type DecimalColumnStatisticsData struct { + _ struct{} `type:"structure"` + + // Maximum value of the column. + MaximumValue *DecimalNumber `type:"structure"` + + // Minimum value of the column. + MinimumValue *DecimalNumber `type:"structure"` + + // Number of distinct values. + // + // NumberOfDistinctValues is a required field + NumberOfDistinctValues *int64 `type:"long" required:"true"` + + // Number of nulls. + // + // NumberOfNulls is a required field + NumberOfNulls *int64 `type:"long" required:"true"` +} + +// String returns the string representation +func (s DecimalColumnStatisticsData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DecimalColumnStatisticsData) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DecimalColumnStatisticsData) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DecimalColumnStatisticsData"} + if s.NumberOfDistinctValues == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfDistinctValues")) + } + if s.NumberOfNulls == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfNulls")) + } + if s.MaximumValue != nil { + if err := s.MaximumValue.Validate(); err != nil { + invalidParams.AddNested("MaximumValue", err.(request.ErrInvalidParams)) + } + } + if s.MinimumValue != nil { + if err := s.MinimumValue.Validate(); err != nil { + invalidParams.AddNested("MinimumValue", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaximumValue sets the MaximumValue field's value. +func (s *DecimalColumnStatisticsData) SetMaximumValue(v *DecimalNumber) *DecimalColumnStatisticsData { + s.MaximumValue = v + return s +} + +// SetMinimumValue sets the MinimumValue field's value. +func (s *DecimalColumnStatisticsData) SetMinimumValue(v *DecimalNumber) *DecimalColumnStatisticsData { + s.MinimumValue = v + return s +} + +// SetNumberOfDistinctValues sets the NumberOfDistinctValues field's value. +func (s *DecimalColumnStatisticsData) SetNumberOfDistinctValues(v int64) *DecimalColumnStatisticsData { + s.NumberOfDistinctValues = &v + return s +} + +// SetNumberOfNulls sets the NumberOfNulls field's value. +func (s *DecimalColumnStatisticsData) SetNumberOfNulls(v int64) *DecimalColumnStatisticsData { + s.NumberOfNulls = &v + return s +} + +// Contains a numeric value in decimal format. +type DecimalNumber struct { + _ struct{} `type:"structure"` + + // The scale that determines where the decimal point falls in the unscaled value. + // + // Scale is a required field + Scale *int64 `type:"integer" required:"true"` + + // The unscaled numeric value. + // + // UnscaledValue is automatically base64 encoded/decoded by the SDK. + // + // UnscaledValue is a required field + UnscaledValue []byte `type:"blob" required:"true"` +} + +// String returns the string representation +func (s DecimalNumber) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DecimalNumber) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DecimalNumber) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DecimalNumber"} + if s.Scale == nil { + invalidParams.Add(request.NewErrParamRequired("Scale")) + } + if s.UnscaledValue == nil { + invalidParams.Add(request.NewErrParamRequired("UnscaledValue")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetScale sets the Scale field's value. +func (s *DecimalNumber) SetScale(v int64) *DecimalNumber { + s.Scale = &v + return s +} + +// SetUnscaledValue sets the UnscaledValue field's value. +func (s *DecimalNumber) SetUnscaledValue(v []byte) *DecimalNumber { + s.UnscaledValue = v + return s +} + type DeleteClassifierInput struct { _ struct{} `type:"structure"` @@ -18883,6 +20457,224 @@ func (s DeleteClassifierOutput) GoString() string { return s.String() } +type DeleteColumnStatisticsForPartitionInput struct { + _ struct{} `type:"structure"` + + // The ID of the Data Catalog where the partitions in question reside. If none + // is supplied, the AWS account ID is used by default. + CatalogId *string `min:"1" type:"string"` + + // Name of the column. + // + // ColumnName is a required field + ColumnName *string `min:"1" type:"string" required:"true"` + + // The name of the catalog database where the partitions reside. + // + // DatabaseName is a required field + DatabaseName *string `min:"1" type:"string" required:"true"` + + // A list of partition values identifying the partition. + // + // PartitionValues is a required field + PartitionValues []*string `type:"list" required:"true"` + + // The name of the partitions' table. + // + // TableName is a required field + TableName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteColumnStatisticsForPartitionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteColumnStatisticsForPartitionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteColumnStatisticsForPartitionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteColumnStatisticsForPartitionInput"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } + if s.ColumnName == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnName")) + } + if s.ColumnName != nil && len(*s.ColumnName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ColumnName", 1)) + } + if s.DatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("DatabaseName")) + } + if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) + } + if s.PartitionValues == nil { + invalidParams.Add(request.NewErrParamRequired("PartitionValues")) + } + if s.TableName == nil { + invalidParams.Add(request.NewErrParamRequired("TableName")) + } + if s.TableName != nil && len(*s.TableName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TableName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCatalogId sets the CatalogId field's value. +func (s *DeleteColumnStatisticsForPartitionInput) SetCatalogId(v string) *DeleteColumnStatisticsForPartitionInput { + s.CatalogId = &v + return s +} + +// SetColumnName sets the ColumnName field's value. +func (s *DeleteColumnStatisticsForPartitionInput) SetColumnName(v string) *DeleteColumnStatisticsForPartitionInput { + s.ColumnName = &v + return s +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *DeleteColumnStatisticsForPartitionInput) SetDatabaseName(v string) *DeleteColumnStatisticsForPartitionInput { + s.DatabaseName = &v + return s +} + +// SetPartitionValues sets the PartitionValues field's value. +func (s *DeleteColumnStatisticsForPartitionInput) SetPartitionValues(v []*string) *DeleteColumnStatisticsForPartitionInput { + s.PartitionValues = v + return s +} + +// SetTableName sets the TableName field's value. +func (s *DeleteColumnStatisticsForPartitionInput) SetTableName(v string) *DeleteColumnStatisticsForPartitionInput { + s.TableName = &v + return s +} + +type DeleteColumnStatisticsForPartitionOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteColumnStatisticsForPartitionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteColumnStatisticsForPartitionOutput) GoString() string { + return s.String() +} + +type DeleteColumnStatisticsForTableInput struct { + _ struct{} `type:"structure"` + + // The ID of the Data Catalog where the partitions in question reside. If none + // is supplied, the AWS account ID is used by default. + CatalogId *string `min:"1" type:"string"` + + // The name of the column. + // + // ColumnName is a required field + ColumnName *string `min:"1" type:"string" required:"true"` + + // The name of the catalog database where the partitions reside. + // + // DatabaseName is a required field + DatabaseName *string `min:"1" type:"string" required:"true"` + + // The name of the partitions' table. + // + // TableName is a required field + TableName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteColumnStatisticsForTableInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteColumnStatisticsForTableInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteColumnStatisticsForTableInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteColumnStatisticsForTableInput"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } + if s.ColumnName == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnName")) + } + if s.ColumnName != nil && len(*s.ColumnName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ColumnName", 1)) + } + if s.DatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("DatabaseName")) + } + if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) + } + if s.TableName == nil { + invalidParams.Add(request.NewErrParamRequired("TableName")) + } + if s.TableName != nil && len(*s.TableName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TableName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCatalogId sets the CatalogId field's value. +func (s *DeleteColumnStatisticsForTableInput) SetCatalogId(v string) *DeleteColumnStatisticsForTableInput { + s.CatalogId = &v + return s +} + +// SetColumnName sets the ColumnName field's value. +func (s *DeleteColumnStatisticsForTableInput) SetColumnName(v string) *DeleteColumnStatisticsForTableInput { + s.ColumnName = &v + return s +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *DeleteColumnStatisticsForTableInput) SetDatabaseName(v string) *DeleteColumnStatisticsForTableInput { + s.DatabaseName = &v + return s +} + +// SetTableName sets the TableName field's value. +func (s *DeleteColumnStatisticsForTableInput) SetTableName(v string) *DeleteColumnStatisticsForTableInput { + s.TableName = &v + return s +} + +type DeleteColumnStatisticsForTableOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteColumnStatisticsForTableOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteColumnStatisticsForTableOutput) GoString() string { + return s.String() +} + type DeleteConnectionInput struct { _ struct{} `type:"structure"` @@ -19359,6 +21151,9 @@ type DeleteResourcePolicyInput struct { // The hash value returned when this policy was set. PolicyHashCondition *string `min:"1" type:"string"` + + // The ARN of the AWS Glue resource for the resource policy to be deleted. + ResourceArn *string `min:"1" type:"string"` } // String returns the string representation @@ -19377,6 +21172,9 @@ func (s *DeleteResourcePolicyInput) Validate() error { if s.PolicyHashCondition != nil && len(*s.PolicyHashCondition) < 1 { invalidParams.Add(request.NewErrParamMinLen("PolicyHashCondition", 1)) } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -19390,6 +21188,12 @@ func (s *DeleteResourcePolicyInput) SetPolicyHashCondition(v string) *DeleteReso return s } +// SetResourceArn sets the ResourceArn field's value. +func (s *DeleteResourcePolicyInput) SetResourceArn(v string) *DeleteResourcePolicyInput { + s.ResourceArn = &v + return s +} + type DeleteResourcePolicyOutput struct { _ struct{} `type:"structure"` } @@ -20212,12 +22016,102 @@ func (s *DevEndpointCustomLibraries) SetExtraPythonLibsS3Path(v string) *DevEndp return s } +// Defines a double column statistics data. +type DoubleColumnStatisticsData struct { + _ struct{} `type:"structure"` + + // Maximum value of the column. + MaximumValue *float64 `type:"double"` + + // Minimum value of the column. + MinimumValue *float64 `type:"double"` + + // Number of distinct values. + // + // NumberOfDistinctValues is a required field + NumberOfDistinctValues *int64 `type:"long" required:"true"` + + // Number of nulls. + // + // NumberOfNulls is a required field + NumberOfNulls *int64 `type:"long" required:"true"` +} + +// String returns the string representation +func (s DoubleColumnStatisticsData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DoubleColumnStatisticsData) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DoubleColumnStatisticsData) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DoubleColumnStatisticsData"} + if s.NumberOfDistinctValues == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfDistinctValues")) + } + if s.NumberOfNulls == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfNulls")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaximumValue sets the MaximumValue field's value. +func (s *DoubleColumnStatisticsData) SetMaximumValue(v float64) *DoubleColumnStatisticsData { + s.MaximumValue = &v + return s +} + +// SetMinimumValue sets the MinimumValue field's value. +func (s *DoubleColumnStatisticsData) SetMinimumValue(v float64) *DoubleColumnStatisticsData { + s.MinimumValue = &v + return s +} + +// SetNumberOfDistinctValues sets the NumberOfDistinctValues field's value. +func (s *DoubleColumnStatisticsData) SetNumberOfDistinctValues(v int64) *DoubleColumnStatisticsData { + s.NumberOfDistinctValues = &v + return s +} + +// SetNumberOfNulls sets the NumberOfNulls field's value. +func (s *DoubleColumnStatisticsData) SetNumberOfNulls(v int64) *DoubleColumnStatisticsData { + s.NumberOfNulls = &v + return s +} + // Specifies an Amazon DynamoDB table to crawl. type DynamoDBTarget struct { _ struct{} `type:"structure"` // The name of the DynamoDB table to crawl. Path *string `type:"string"` + + // Indicates whether to scan all the records, or to sample rows from the table. + // Scanning all the records can take a long time when the table is not a high + // throughput table. + // + // A value of true means to scan all records, while a value of false means to + // sample the records. If no value is specified, the value defaults to true. + ScanAll *bool `locationName:"scanAll" type:"boolean"` + + // The percentage of the configured read capacity units to use by the AWS Glue + // crawler. Read capacity units is a term defined by DynamoDB, and is a numeric + // value that acts as rate limiter for the number of reads that can be performed + // on that table per second. + // + // The valid values are null or a value between 0.1 to 1.5. A null value is + // used when user does not provide a value, and defaults to 0.5 of the configured + // Read Capacity Unit (for provisioned tables), or 0.25 of the max configured + // Read Capacity Unit (for tables using on-demand mode). + ScanRate *float64 `locationName:"scanRate" type:"double"` } // String returns the string representation @@ -20236,8 +22130,20 @@ func (s *DynamoDBTarget) SetPath(v string) *DynamoDBTarget { return s } +// SetScanAll sets the ScanAll field's value. +func (s *DynamoDBTarget) SetScanAll(v bool) *DynamoDBTarget { + s.ScanAll = &v + return s +} + +// SetScanRate sets the ScanRate field's value. +func (s *DynamoDBTarget) SetScanRate(v float64) *DynamoDBTarget { + s.ScanRate = &v + return s +} + // An edge represents a directed connection between two AWS Glue components -// which are part of the workflow the edge belongs to. +// that are part of the workflow the edge belongs to. type Edge struct { _ struct{} `type:"structure"` @@ -21023,6 +22929,254 @@ func (s *GetClassifiersOutput) SetNextToken(v string) *GetClassifiersOutput { return s } +type GetColumnStatisticsForPartitionInput struct { + _ struct{} `type:"structure"` + + // The ID of the Data Catalog where the partitions in question reside. If none + // is supplied, the AWS account ID is used by default. + CatalogId *string `min:"1" type:"string"` + + // A list of the column names. + // + // ColumnNames is a required field + ColumnNames []*string `type:"list" required:"true"` + + // The name of the catalog database where the partitions reside. + // + // DatabaseName is a required field + DatabaseName *string `min:"1" type:"string" required:"true"` + + // A list of partition values identifying the partition. + // + // PartitionValues is a required field + PartitionValues []*string `type:"list" required:"true"` + + // The name of the partitions' table. + // + // TableName is a required field + TableName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetColumnStatisticsForPartitionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetColumnStatisticsForPartitionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetColumnStatisticsForPartitionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetColumnStatisticsForPartitionInput"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } + if s.ColumnNames == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnNames")) + } + if s.DatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("DatabaseName")) + } + if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) + } + if s.PartitionValues == nil { + invalidParams.Add(request.NewErrParamRequired("PartitionValues")) + } + if s.TableName == nil { + invalidParams.Add(request.NewErrParamRequired("TableName")) + } + if s.TableName != nil && len(*s.TableName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TableName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCatalogId sets the CatalogId field's value. +func (s *GetColumnStatisticsForPartitionInput) SetCatalogId(v string) *GetColumnStatisticsForPartitionInput { + s.CatalogId = &v + return s +} + +// SetColumnNames sets the ColumnNames field's value. +func (s *GetColumnStatisticsForPartitionInput) SetColumnNames(v []*string) *GetColumnStatisticsForPartitionInput { + s.ColumnNames = v + return s +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *GetColumnStatisticsForPartitionInput) SetDatabaseName(v string) *GetColumnStatisticsForPartitionInput { + s.DatabaseName = &v + return s +} + +// SetPartitionValues sets the PartitionValues field's value. +func (s *GetColumnStatisticsForPartitionInput) SetPartitionValues(v []*string) *GetColumnStatisticsForPartitionInput { + s.PartitionValues = v + return s +} + +// SetTableName sets the TableName field's value. +func (s *GetColumnStatisticsForPartitionInput) SetTableName(v string) *GetColumnStatisticsForPartitionInput { + s.TableName = &v + return s +} + +type GetColumnStatisticsForPartitionOutput struct { + _ struct{} `type:"structure"` + + // List of ColumnStatistics that failed to be retrieved. + ColumnStatisticsList []*ColumnStatistics `type:"list"` + + // Error occurred during retrieving column statistics data. + Errors []*ColumnError `type:"list"` +} + +// String returns the string representation +func (s GetColumnStatisticsForPartitionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetColumnStatisticsForPartitionOutput) GoString() string { + return s.String() +} + +// SetColumnStatisticsList sets the ColumnStatisticsList field's value. +func (s *GetColumnStatisticsForPartitionOutput) SetColumnStatisticsList(v []*ColumnStatistics) *GetColumnStatisticsForPartitionOutput { + s.ColumnStatisticsList = v + return s +} + +// SetErrors sets the Errors field's value. +func (s *GetColumnStatisticsForPartitionOutput) SetErrors(v []*ColumnError) *GetColumnStatisticsForPartitionOutput { + s.Errors = v + return s +} + +type GetColumnStatisticsForTableInput struct { + _ struct{} `type:"structure"` + + // The ID of the Data Catalog where the partitions in question reside. If none + // is supplied, the AWS account ID is used by default. + CatalogId *string `min:"1" type:"string"` + + // A list of the column names. + // + // ColumnNames is a required field + ColumnNames []*string `type:"list" required:"true"` + + // The name of the catalog database where the partitions reside. + // + // DatabaseName is a required field + DatabaseName *string `min:"1" type:"string" required:"true"` + + // The name of the partitions' table. + // + // TableName is a required field + TableName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetColumnStatisticsForTableInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetColumnStatisticsForTableInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetColumnStatisticsForTableInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetColumnStatisticsForTableInput"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } + if s.ColumnNames == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnNames")) + } + if s.DatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("DatabaseName")) + } + if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) + } + if s.TableName == nil { + invalidParams.Add(request.NewErrParamRequired("TableName")) + } + if s.TableName != nil && len(*s.TableName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TableName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCatalogId sets the CatalogId field's value. +func (s *GetColumnStatisticsForTableInput) SetCatalogId(v string) *GetColumnStatisticsForTableInput { + s.CatalogId = &v + return s +} + +// SetColumnNames sets the ColumnNames field's value. +func (s *GetColumnStatisticsForTableInput) SetColumnNames(v []*string) *GetColumnStatisticsForTableInput { + s.ColumnNames = v + return s +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *GetColumnStatisticsForTableInput) SetDatabaseName(v string) *GetColumnStatisticsForTableInput { + s.DatabaseName = &v + return s +} + +// SetTableName sets the TableName field's value. +func (s *GetColumnStatisticsForTableInput) SetTableName(v string) *GetColumnStatisticsForTableInput { + s.TableName = &v + return s +} + +type GetColumnStatisticsForTableOutput struct { + _ struct{} `type:"structure"` + + // List of ColumnStatistics that failed to be retrieved. + ColumnStatisticsList []*ColumnStatistics `type:"list"` + + // List of ColumnStatistics that failed to be retrieved. + Errors []*ColumnError `type:"list"` +} + +// String returns the string representation +func (s GetColumnStatisticsForTableOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetColumnStatisticsForTableOutput) GoString() string { + return s.String() +} + +// SetColumnStatisticsList sets the ColumnStatisticsList field's value. +func (s *GetColumnStatisticsForTableOutput) SetColumnStatisticsList(v []*ColumnStatistics) *GetColumnStatisticsForTableOutput { + s.ColumnStatisticsList = v + return s +} + +// SetErrors sets the Errors field's value. +func (s *GetColumnStatisticsForTableOutput) SetErrors(v []*ColumnError) *GetColumnStatisticsForTableOutput { + s.Errors = v + return s +} + type GetConnectionInput struct { _ struct{} `type:"structure"` @@ -21118,8 +23272,7 @@ func (s *GetConnectionOutput) SetConnection(v *Connection) *GetConnectionOutput type GetConnectionsFilter struct { _ struct{} `type:"structure"` - // The type of connections to return. Currently, only JDBC is supported; SFTP - // is not supported. + // The type of connections to return. Currently, SFTP is not supported. ConnectionType *string `type:"string" enum:"ConnectionType"` // A criteria string that must match the criteria recorded in the connection @@ -21641,6 +23794,15 @@ type GetDatabasesInput struct { // A continuation token, if this is a continuation call. NextToken *string `type:"string"` + + // Allows you to specify that you want to list the databases shared with your + // account. The allowable values are FOREIGN or ALL. + // + // * If set to FOREIGN, will list the databases shared with your account. + // + // * If set to ALL, will list the databases shared with your account, as + // well as the databases in yor local account. + ResourceShareType *string `type:"string" enum:"ResourceShareType"` } // String returns the string representation @@ -21687,6 +23849,12 @@ func (s *GetDatabasesInput) SetNextToken(v string) *GetDatabasesInput { return s } +// SetResourceShareType sets the ResourceShareType field's value. +func (s *GetDatabasesInput) SetResourceShareType(v string) *GetDatabasesInput { + s.ResourceShareType = &v + return s +} + type GetDatabasesOutput struct { _ struct{} `type:"structure"` @@ -23517,8 +25685,92 @@ func (s *GetPlanOutput) SetScalaCode(v string) *GetPlanOutput { return s } +type GetResourcePoliciesInput struct { + _ struct{} `type:"structure"` + + // The maximum size of a list to return. + MaxResults *int64 `min:"1" type:"integer"` + + // A continuation token, if this is a continuation request. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s GetResourcePoliciesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetResourcePoliciesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetResourcePoliciesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetResourcePoliciesInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetResourcePoliciesInput) SetMaxResults(v int64) *GetResourcePoliciesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetResourcePoliciesInput) SetNextToken(v string) *GetResourcePoliciesInput { + s.NextToken = &v + return s +} + +type GetResourcePoliciesOutput struct { + _ struct{} `type:"structure"` + + // A list of the individual resource policies and the account-level resource + // policy. + GetResourcePoliciesResponseList []*GluePolicy `type:"list"` + + // A continuation token, if the returned list does not contain the last resource + // policy available. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s GetResourcePoliciesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetResourcePoliciesOutput) GoString() string { + return s.String() +} + +// SetGetResourcePoliciesResponseList sets the GetResourcePoliciesResponseList field's value. +func (s *GetResourcePoliciesOutput) SetGetResourcePoliciesResponseList(v []*GluePolicy) *GetResourcePoliciesOutput { + s.GetResourcePoliciesResponseList = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetResourcePoliciesOutput) SetNextToken(v string) *GetResourcePoliciesOutput { + s.NextToken = &v + return s +} + type GetResourcePolicyInput struct { _ struct{} `type:"structure"` + + // The ARN of the AWS Glue resource for the resource policy to be retrieved. + // For more information about AWS Glue resource ARNs, see the AWS Glue ARN string + // pattern (https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-common.html#aws-glue-api-regex-aws-glue-arn-id) + ResourceArn *string `min:"1" type:"string"` } // String returns the string representation @@ -23531,6 +25783,25 @@ func (s GetResourcePolicyInput) GoString() string { return s.String() } +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetResourcePolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetResourcePolicyInput"} + 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 *GetResourcePolicyInput) SetResourceArn(v string) *GetResourcePolicyInput { + s.ResourceArn = &v + return s +} + type GetResourcePolicyOutput struct { _ struct{} `type:"structure"` @@ -24489,7 +26760,9 @@ type GetUserDefinedFunctionsInput struct { // If none is provided, the AWS account ID is used by default. CatalogId *string `min:"1" type:"string"` - // The name of the catalog database where the functions are located. + // The name of the catalog database where the functions are located. If none + // is provided, functions from all the databases across the catalog will be + // returned. DatabaseName *string `min:"1" type:"string"` // The maximum number of functions to return in one response. @@ -24951,6 +27224,57 @@ func (s *GetWorkflowRunsOutput) SetRuns(v []*WorkflowRun) *GetWorkflowRunsOutput return s } +// A structure for returning a resource policy. +type GluePolicy struct { + _ struct{} `type:"structure"` + + // The date and time at which the policy was created. + CreateTime *time.Time `type:"timestamp"` + + // Contains the hash value associated with this policy. + PolicyHash *string `min:"1" type:"string"` + + // Contains the requested policy document, in JSON format. + PolicyInJson *string `min:"2" type:"string"` + + // The date and time at which the policy was last updated. + UpdateTime *time.Time `type:"timestamp"` +} + +// String returns the string representation +func (s GluePolicy) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GluePolicy) GoString() string { + return s.String() +} + +// SetCreateTime sets the CreateTime field's value. +func (s *GluePolicy) SetCreateTime(v time.Time) *GluePolicy { + s.CreateTime = &v + return s +} + +// SetPolicyHash sets the PolicyHash field's value. +func (s *GluePolicy) SetPolicyHash(v string) *GluePolicy { + s.PolicyHash = &v + return s +} + +// SetPolicyInJson sets the PolicyInJson field's value. +func (s *GluePolicy) SetPolicyInJson(v string) *GluePolicy { + s.PolicyInJson = &v + return s +} + +// SetUpdateTime sets the UpdateTime field's value. +func (s *GluePolicy) SetUpdateTime(v time.Time) *GluePolicy { + s.UpdateTime = &v + return s +} + // A classifier that uses grok patterns. type GrokClassifier struct { _ struct{} `type:"structure"` @@ -24965,11 +27289,11 @@ type GrokClassifier struct { CreationTime *time.Time `type:"timestamp"` // Optional custom grok patterns defined by this classifier. For more information, - // see custom patterns in Writing Custom Classifiers (http://docs.aws.amazon.com/glue/latest/dg/custom-classifier.html). + // see custom patterns in Writing Custom Classifiers (https://docs.aws.amazon.com/glue/latest/dg/custom-classifier.html). CustomPatterns *string `type:"string"` // The grok pattern applied to a data store by this classifier. For more information, - // see built-in patterns in Writing Custom Classifiers (http://docs.aws.amazon.com/glue/latest/dg/custom-classifier.html). + // see built-in patterns in Writing Custom Classifiers (https://docs.aws.amazon.com/glue/latest/dg/custom-classifier.html). // // GrokPattern is a required field GrokPattern *string `min:"1" type:"string" required:"true"` @@ -25095,6 +27419,63 @@ func (s *IdempotentParameterMismatchException) RequestID() string { return s.RespMetadata.RequestID } +// The workflow is in an invalid state to perform a requested operation. +type IllegalWorkflowStateException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // A message describing the problem. + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s IllegalWorkflowStateException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s IllegalWorkflowStateException) GoString() string { + return s.String() +} + +func newErrorIllegalWorkflowStateException(v protocol.ResponseMetadata) error { + return &IllegalWorkflowStateException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *IllegalWorkflowStateException) Code() string { + return "IllegalWorkflowStateException" +} + +// Message returns the exception's message. +func (s *IllegalWorkflowStateException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *IllegalWorkflowStateException) OrigErr() error { + return nil +} + +func (s *IllegalWorkflowStateException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *IllegalWorkflowStateException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *IllegalWorkflowStateException) RequestID() string { + return s.RespMetadata.RequestID +} + type ImportCatalogToGlueInput struct { _ struct{} `type:"structure"` @@ -25302,7 +27683,7 @@ type JdbcTarget struct { ConnectionName *string `type:"string"` // A list of glob patterns used to exclude from the crawl. For more information, - // see Catalog Tables with a Crawler (http://docs.aws.amazon.com/glue/latest/dg/add-crawler.html). + // see Catalog Tables with a Crawler (https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html). Exclusions []*string `type:"list"` // The path of the JDBC target. @@ -25407,14 +27788,16 @@ type Job struct { // Do not set Max Capacity if using WorkerType and NumberOfWorkers. // // The value that can be allocated for MaxCapacity depends on whether you are - // running a Python shell job or an Apache Spark ETL job: + // running a Python shell job, an Apache Spark ETL job, or an Apache Spark streaming + // ETL job: // // * When you specify a Python shell job (JobCommand.Name="pythonshell"), // you can allocate either 0.0625 or 1 DPU. The default is 0.0625 DPU. // - // * When you specify an Apache Spark ETL job (JobCommand.Name="glueetl"), - // you can allocate from 2 to 100 DPUs. The default is 10 DPUs. This job - // type cannot have a fractional DPU allocation. + // * When you specify an Apache Spark ETL job (JobCommand.Name="glueetl") + // or Apache Spark streaming ETL job (JobCommand.Name="gluestreaming"), you + // can allocate from 2 to 100 DPUs. The default is 10 DPUs. This job type + // cannot have a fractional DPU allocation. MaxCapacity *float64 `type:"double"` // The maximum number of times to retry this job after a JobRun fails. @@ -25710,7 +28093,8 @@ type JobCommand struct { _ struct{} `type:"structure"` // The name of the job command. For an Apache Spark ETL job, this must be glueetl. - // For a Python shell job, it must be pythonshell. + // For a Python shell job, it must be pythonshell. For an Apache Spark streaming + // ETL job, this must be gluestreaming. Name *string `type:"string"` // The Python version being used to execute a Python shell job. Allowed values @@ -25833,7 +28217,8 @@ type JobRun struct { // The name of the job definition being used in this run. JobName *string `min:"1" type:"string"` - // The current state of the job run. + // The current state of the job run. For more information about the statuses + // of jobs that have terminated abnormally, see AWS Glue Job Run Statuses (https://docs.aws.amazon.com/glue/latest/dg/job-run-statuses.html). JobRunState *string `type:"string" enum:"JobRunState"` // The last time that this job run was modified. @@ -26121,9 +28506,10 @@ type JobUpdate struct { // * When you specify a Python shell job (JobCommand.Name="pythonshell"), // you can allocate either 0.0625 or 1 DPU. The default is 0.0625 DPU. // - // * When you specify an Apache Spark ETL job (JobCommand.Name="glueetl"), - // you can allocate from 2 to 100 DPUs. The default is 10 DPUs. This job - // type cannot have a fractional DPU allocation. + // * When you specify an Apache Spark ETL job (JobCommand.Name="glueetl") + // or Apache Spark streaming ETL job (JobCommand.Name="gluestreaming"), you + // can allocate from 2 to 100 DPUs. The default is 10 DPUs. This job type + // cannot have a fractional DPU allocation. MaxCapacity *float64 `type:"double"` // The maximum number of times to retry this job if it fails. @@ -27108,6 +29494,77 @@ func (s *Location) SetS3(v []*CodeGenNodeArg) *Location { return s } +// Defines a long column statistics data. +type LongColumnStatisticsData struct { + _ struct{} `type:"structure"` + + // Maximum value of the column. + MaximumValue *int64 `type:"long"` + + // Minimum value of the column. + MinimumValue *int64 `type:"long"` + + // Number of distinct values. + // + // NumberOfDistinctValues is a required field + NumberOfDistinctValues *int64 `type:"long" required:"true"` + + // Number of nulls. + // + // NumberOfNulls is a required field + NumberOfNulls *int64 `type:"long" required:"true"` +} + +// String returns the string representation +func (s LongColumnStatisticsData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s LongColumnStatisticsData) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *LongColumnStatisticsData) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LongColumnStatisticsData"} + if s.NumberOfDistinctValues == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfDistinctValues")) + } + if s.NumberOfNulls == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfNulls")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaximumValue sets the MaximumValue field's value. +func (s *LongColumnStatisticsData) SetMaximumValue(v int64) *LongColumnStatisticsData { + s.MaximumValue = &v + return s +} + +// SetMinimumValue sets the MinimumValue field's value. +func (s *LongColumnStatisticsData) SetMinimumValue(v int64) *LongColumnStatisticsData { + s.MinimumValue = &v + return s +} + +// SetNumberOfDistinctValues sets the NumberOfDistinctValues field's value. +func (s *LongColumnStatisticsData) SetNumberOfDistinctValues(v int64) *LongColumnStatisticsData { + s.NumberOfDistinctValues = &v + return s +} + +// SetNumberOfNulls sets the NumberOfNulls field's value. +func (s *LongColumnStatisticsData) SetNumberOfNulls(v int64) *LongColumnStatisticsData { + s.NumberOfNulls = &v + return s +} + // A structure for a machine learning transform. type MLTransform struct { _ struct{} `type:"structure"` @@ -27539,8 +29996,8 @@ func (s *NoScheduleException) RequestID() string { return s.RespMetadata.RequestID } -// A node represents an AWS Glue component like Trigger, Job etc. which is part -// of a workflow. +// A node represents an AWS Glue component such as a trigger, or job, etc., +// that is part of a workflow. type Node struct { _ struct{} `type:"structure"` @@ -27765,6 +30222,9 @@ func (s *Order) SetSortOrder(v int64) *Order { type Partition struct { _ struct{} `type:"structure"` + // The ID of the Data Catalog in which the partition resides. + CatalogId *string `min:"1" type:"string"` + // The time at which the partition was created. CreationTime *time.Time `type:"timestamp"` @@ -27800,6 +30260,12 @@ func (s Partition) GoString() string { return s.String() } +// SetCatalogId sets the CatalogId field's value. +func (s *Partition) SetCatalogId(v string) *Partition { + s.CatalogId = &v + return s +} + // SetCreationTime sets the CreationTime field's value. func (s *Partition) SetCreationTime(v time.Time) *Partition { s.CreationTime = &v @@ -28312,6 +30778,15 @@ func (s PutDataCatalogEncryptionSettingsOutput) GoString() string { type PutResourcePolicyInput struct { _ struct{} `type:"structure"` + // Allows you to specify if you want to use both resource-level and account/catalog-level + // resource policies. A resource-level policy is a policy attached to an individual + // resource such as a database or a table. + // + // The default value of NO indicates that resource-level policies cannot co-exist + // with an account-level policy. A value of YES means the use of both resource-level + // and account/catalog-level resource policies is allowed. + EnableHybrid *string `type:"string" enum:"EnableHybridValues"` + // A value of MUST_EXIST is used to update a policy. A value of NOT_EXIST is // used to create a new policy. If a value of NONE or a null value is used, // the call will not depend on the existence of a policy. @@ -28326,6 +30801,11 @@ type PutResourcePolicyInput struct { // // PolicyInJson is a required field PolicyInJson *string `min:"2" type:"string" required:"true"` + + // The ARN of the AWS Glue resource for the resource policy to be set. For more + // information about AWS Glue resource ARNs, see the AWS Glue ARN string pattern + // (https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-common.html#aws-glue-api-regex-aws-glue-arn-id) + ResourceArn *string `min:"1" type:"string"` } // String returns the string representation @@ -28350,6 +30830,9 @@ func (s *PutResourcePolicyInput) Validate() error { if s.PolicyInJson != nil && len(*s.PolicyInJson) < 2 { invalidParams.Add(request.NewErrParamMinLen("PolicyInJson", 2)) } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -28357,6 +30840,12 @@ func (s *PutResourcePolicyInput) Validate() error { return nil } +// SetEnableHybrid sets the EnableHybrid field's value. +func (s *PutResourcePolicyInput) SetEnableHybrid(v string) *PutResourcePolicyInput { + s.EnableHybrid = &v + return s +} + // SetPolicyExistsCondition sets the PolicyExistsCondition field's value. func (s *PutResourcePolicyInput) SetPolicyExistsCondition(v string) *PutResourcePolicyInput { s.PolicyExistsCondition = &v @@ -28375,6 +30864,12 @@ func (s *PutResourcePolicyInput) SetPolicyInJson(v string) *PutResourcePolicyInp return s } +// SetResourceArn sets the ResourceArn field's value. +func (s *PutResourcePolicyInput) SetResourceArn(v string) *PutResourcePolicyInput { + s.ResourceArn = &v + return s +} + type PutResourcePolicyOutput struct { _ struct{} `type:"structure"` @@ -28658,6 +31153,112 @@ func (s *ResourceUri) SetUri(v string) *ResourceUri { return s } +type ResumeWorkflowRunInput struct { + _ struct{} `type:"structure"` + + // The name of the workflow to resume. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // A list of the node IDs for the nodes you want to restart. The nodes that + // are to be restarted must have a run attempt in the original run. + // + // NodeIds is a required field + NodeIds []*string `type:"list" required:"true"` + + // The ID of the workflow run to resume. + // + // RunId is a required field + RunId *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s ResumeWorkflowRunInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResumeWorkflowRunInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ResumeWorkflowRunInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ResumeWorkflowRunInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.NodeIds == nil { + invalidParams.Add(request.NewErrParamRequired("NodeIds")) + } + if s.RunId == nil { + invalidParams.Add(request.NewErrParamRequired("RunId")) + } + if s.RunId != nil && len(*s.RunId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RunId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *ResumeWorkflowRunInput) SetName(v string) *ResumeWorkflowRunInput { + s.Name = &v + return s +} + +// SetNodeIds sets the NodeIds field's value. +func (s *ResumeWorkflowRunInput) SetNodeIds(v []*string) *ResumeWorkflowRunInput { + s.NodeIds = v + return s +} + +// SetRunId sets the RunId field's value. +func (s *ResumeWorkflowRunInput) SetRunId(v string) *ResumeWorkflowRunInput { + s.RunId = &v + return s +} + +type ResumeWorkflowRunOutput struct { + _ struct{} `type:"structure"` + + // A list of the node IDs for the nodes that were actually restarted. + NodeIds []*string `type:"list"` + + // The new ID assigned to the resumed workflow run. Each resume of a workflow + // run will have a new run ID. + RunId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ResumeWorkflowRunOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResumeWorkflowRunOutput) GoString() string { + return s.String() +} + +// SetNodeIds sets the NodeIds field's value. +func (s *ResumeWorkflowRunOutput) SetNodeIds(v []*string) *ResumeWorkflowRunOutput { + s.NodeIds = v + return s +} + +// SetRunId sets the RunId field's value. +func (s *ResumeWorkflowRunOutput) SetRunId(v string) *ResumeWorkflowRunOutput { + s.RunId = &v + return s +} + // Specifies how Amazon Simple Storage Service (Amazon S3) data should be encrypted. type S3Encryption struct { _ struct{} `type:"structure"` @@ -28695,8 +31296,12 @@ func (s *S3Encryption) SetS3EncryptionMode(v string) *S3Encryption { type S3Target struct { _ struct{} `type:"structure"` + // The name of a connection which allows a job or crawler to access data in + // Amazon S3 within an Amazon Virtual Private Cloud environment (Amazon VPC). + ConnectionName *string `type:"string"` + // A list of glob patterns used to exclude from the crawl. For more information, - // see Catalog Tables with a Crawler (http://docs.aws.amazon.com/glue/latest/dg/add-crawler.html). + // see Catalog Tables with a Crawler (https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html). Exclusions []*string `type:"list"` // The path to the Amazon S3 target. @@ -28713,6 +31318,12 @@ func (s S3Target) GoString() string { return s.String() } +// SetConnectionName sets the ConnectionName field's value. +func (s *S3Target) SetConnectionName(v string) *S3Target { + s.ConnectionName = &v + return s +} + // SetExclusions sets the Exclusions field's value. func (s *S3Target) SetExclusions(v []*string) *S3Target { s.Exclusions = v @@ -28729,10 +31340,10 @@ func (s *S3Target) SetPath(v string) *S3Target { type Schedule struct { _ struct{} `type:"structure"` - // A cron expression used to specify the schedule. For more information, see - // Time-Based Schedules for Jobs and Crawlers (http://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html). - // For example, to run something every day at 12:15 UTC, specify cron(15 12 - // * * ? *). + // A cron expression used to specify the schedule (see Time-Based Schedules + // for Jobs and Crawlers (https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html). + // For example, to run something every day at 12:15 UTC, you would specify: + // cron(15 12 * * ? *). ScheduleExpression *string `type:"string"` // The state of the schedule. @@ -29016,11 +31627,20 @@ func (s *SchemaColumn) SetName(v string) *SchemaColumn { type SearchTablesInput struct { _ struct{} `type:"structure"` - // A unique identifier, consisting of account_id/datalake. + // A unique identifier, consisting of account_id . CatalogId *string `min:"1" type:"string"` // A list of key-value pairs, and a comparator used to filter the search results. // Returns all entities matching the predicate. + // + // The Comparator member of the PropertyPredicate struct is used only for time + // fields, and can be omitted for other field types. Also, when comparing string + // values, such as when Key=Name, a fuzzy match algorithm is used. The Key field + // (for example, the value of the Name field) is split on certain punctuation + // characters, for example, -, :, #, etc. into tokens. Then each token is exact-match + // compared with the Value member of PropertyPredicate. For example, if Key=Name + // and Value=link, tables named customer-link and xx-link-yy are returned, but + // xxlinkyy is not returned. Filters []*PropertyPredicate `type:"list"` // The maximum number of tables to return in a single response. @@ -29029,6 +31649,15 @@ type SearchTablesInput struct { // A continuation token, included if this is a continuation call. NextToken *string `type:"string"` + // Allows you to specify that you want to search the tables shared with your + // account. The allowable values are FOREIGN or ALL. + // + // * If set to FOREIGN, will search the tables shared with your account. + // + // * If set to ALL, will search the tables shared with your account, as well + // as the tables in yor local account. + ResourceShareType *string `type:"string" enum:"ResourceShareType"` + // A string used for a text search. // // Specifying a value in quotes filters based on an exact match to the value. @@ -29089,6 +31718,12 @@ func (s *SearchTablesInput) SetNextToken(v string) *SearchTablesInput { return s } +// SetResourceShareType sets the ResourceShareType field's value. +func (s *SearchTablesInput) SetResourceShareType(v string) *SearchTablesInput { + s.ResourceShareType = &v + return s +} + // SetSearchText sets the SearchText field's value. func (s *SearchTablesInput) SetSearchText(v string) *SearchTablesInput { s.SearchText = &v @@ -30302,6 +32937,78 @@ func (s *StopTriggerOutput) SetName(v string) *StopTriggerOutput { return s } +type StopWorkflowRunInput struct { + _ struct{} `type:"structure"` + + // The name of the workflow to stop. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // The ID of the workflow run to stop. + // + // RunId is a required field + RunId *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s StopWorkflowRunInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopWorkflowRunInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StopWorkflowRunInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StopWorkflowRunInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.RunId == nil { + invalidParams.Add(request.NewErrParamRequired("RunId")) + } + if s.RunId != nil && len(*s.RunId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RunId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *StopWorkflowRunInput) SetName(v string) *StopWorkflowRunInput { + s.Name = &v + return s +} + +// SetRunId sets the RunId field's value. +func (s *StopWorkflowRunInput) SetRunId(v string) *StopWorkflowRunInput { + s.RunId = &v + return s +} + +type StopWorkflowRunOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s StopWorkflowRunOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopWorkflowRunOutput) GoString() string { + return s.String() +} + // Describes the physical storage of table data. type StorageDescriptor struct { _ struct{} `type:"structure"` @@ -30465,6 +33172,87 @@ func (s *StorageDescriptor) SetStoredAsSubDirectories(v bool) *StorageDescriptor return s } +// Defines a string column statistics data. +type StringColumnStatisticsData struct { + _ struct{} `type:"structure"` + + // Average value of the column. + // + // AverageLength is a required field + AverageLength *float64 `type:"double" required:"true"` + + // Maximum value of the column. + // + // MaximumLength is a required field + MaximumLength *int64 `type:"long" required:"true"` + + // Number of distinct values. + // + // NumberOfDistinctValues is a required field + NumberOfDistinctValues *int64 `type:"long" required:"true"` + + // Number of nulls. + // + // NumberOfNulls is a required field + NumberOfNulls *int64 `type:"long" required:"true"` +} + +// String returns the string representation +func (s StringColumnStatisticsData) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StringColumnStatisticsData) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StringColumnStatisticsData) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StringColumnStatisticsData"} + if s.AverageLength == nil { + invalidParams.Add(request.NewErrParamRequired("AverageLength")) + } + if s.MaximumLength == nil { + invalidParams.Add(request.NewErrParamRequired("MaximumLength")) + } + if s.NumberOfDistinctValues == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfDistinctValues")) + } + if s.NumberOfNulls == nil { + invalidParams.Add(request.NewErrParamRequired("NumberOfNulls")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAverageLength sets the AverageLength field's value. +func (s *StringColumnStatisticsData) SetAverageLength(v float64) *StringColumnStatisticsData { + s.AverageLength = &v + return s +} + +// SetMaximumLength sets the MaximumLength field's value. +func (s *StringColumnStatisticsData) SetMaximumLength(v int64) *StringColumnStatisticsData { + s.MaximumLength = &v + return s +} + +// SetNumberOfDistinctValues sets the NumberOfDistinctValues field's value. +func (s *StringColumnStatisticsData) SetNumberOfDistinctValues(v int64) *StringColumnStatisticsData { + s.NumberOfDistinctValues = &v + return s +} + +// SetNumberOfNulls sets the NumberOfNulls field's value. +func (s *StringColumnStatisticsData) SetNumberOfNulls(v int64) *StringColumnStatisticsData { + s.NumberOfNulls = &v + return s +} + // The database and table in the AWS Glue Data Catalog that is used for input // or output data. type Table struct { @@ -30553,6 +33341,9 @@ func (s *Table) SetTableName(v string) *Table { type TableData struct { _ struct{} `type:"structure"` + // The ID of the Data Catalog in which the table resides. + CatalogId *string `min:"1" type:"string"` + // The time when the table definition was created in the Data Catalog. CreateTime *time.Time `type:"timestamp"` @@ -30607,6 +33398,9 @@ type TableData struct { // The type of this table (EXTERNAL_TABLE, VIRTUAL_VIEW, etc.). TableType *string `type:"string"` + // A TableIdentifier structure that describes a target table for resource linking. + TargetTable *TableIdentifier `type:"structure"` + // The last time that the table was updated. UpdateTime *time.Time `type:"timestamp"` @@ -30627,6 +33421,12 @@ func (s TableData) GoString() string { return s.String() } +// SetCatalogId sets the CatalogId field's value. +func (s *TableData) SetCatalogId(v string) *TableData { + s.CatalogId = &v + return s +} + // SetCreateTime sets the CreateTime field's value. func (s *TableData) SetCreateTime(v time.Time) *TableData { s.CreateTime = &v @@ -30711,6 +33511,12 @@ func (s *TableData) SetTableType(v string) *TableData { return s } +// SetTargetTable sets the TargetTable field's value. +func (s *TableData) SetTargetTable(v *TableIdentifier) *TableData { + s.TargetTable = v + return s +} + // SetUpdateTime sets the UpdateTime field's value. func (s *TableData) SetUpdateTime(v time.Time) *TableData { s.UpdateTime = &v @@ -30762,6 +33568,67 @@ func (s *TableError) SetTableName(v string) *TableError { return s } +// A structure that describes a target table for resource linking. +type TableIdentifier struct { + _ struct{} `type:"structure"` + + // The ID of the Data Catalog in which the table resides. + CatalogId *string `min:"1" type:"string"` + + // The name of the catalog database that contains the target table. + DatabaseName *string `min:"1" type:"string"` + + // The name of the target table. + Name *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s TableIdentifier) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TableIdentifier) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TableIdentifier) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TableIdentifier"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } + if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCatalogId sets the CatalogId field's value. +func (s *TableIdentifier) SetCatalogId(v string) *TableIdentifier { + s.CatalogId = &v + return s +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *TableIdentifier) SetDatabaseName(v string) *TableIdentifier { + s.DatabaseName = &v + return s +} + +// SetName sets the Name field's value. +func (s *TableIdentifier) SetName(v string) *TableIdentifier { + s.Name = &v + return s +} + // A structure used to define a table. type TableInput struct { _ struct{} `type:"structure"` @@ -30807,6 +33674,9 @@ type TableInput struct { // The type of this table (EXTERNAL_TABLE, VIRTUAL_VIEW, etc.). TableType *string `type:"string"` + // A TableIdentifier structure that describes a target table for resource linking. + TargetTable *TableIdentifier `type:"structure"` + // If the table is a view, the expanded text of the view; otherwise null. ViewExpandedText *string `type:"string"` @@ -30851,6 +33721,11 @@ func (s *TableInput) Validate() error { invalidParams.AddNested("StorageDescriptor", err.(request.ErrInvalidParams)) } } + if s.TargetTable != nil { + if err := s.TargetTable.Validate(); err != nil { + invalidParams.AddNested("TargetTable", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -30918,6 +33793,12 @@ func (s *TableInput) SetTableType(v string) *TableInput { return s } +// SetTargetTable sets the TargetTable field's value. +func (s *TableInput) SetTargetTable(v *TableIdentifier) *TableInput { + s.TargetTable = v + return s +} + // SetViewExpandedText sets the ViewExpandedText field's value. func (s *TableInput) SetViewExpandedText(v string) *TableInput { s.ViewExpandedText = &v @@ -31973,6 +34854,256 @@ func (s UpdateClassifierOutput) GoString() string { return s.String() } +type UpdateColumnStatisticsForPartitionInput struct { + _ struct{} `type:"structure"` + + // The ID of the Data Catalog where the partitions in question reside. If none + // is supplied, the AWS account ID is used by default. + CatalogId *string `min:"1" type:"string"` + + // A list of the column statistics. + // + // ColumnStatisticsList is a required field + ColumnStatisticsList []*ColumnStatistics `type:"list" required:"true"` + + // The name of the catalog database where the partitions reside. + // + // DatabaseName is a required field + DatabaseName *string `min:"1" type:"string" required:"true"` + + // A list of partition values identifying the partition. + // + // PartitionValues is a required field + PartitionValues []*string `type:"list" required:"true"` + + // The name of the partitions' table. + // + // TableName is a required field + TableName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s UpdateColumnStatisticsForPartitionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateColumnStatisticsForPartitionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateColumnStatisticsForPartitionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateColumnStatisticsForPartitionInput"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } + if s.ColumnStatisticsList == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnStatisticsList")) + } + if s.DatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("DatabaseName")) + } + if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) + } + if s.PartitionValues == nil { + invalidParams.Add(request.NewErrParamRequired("PartitionValues")) + } + if s.TableName == nil { + invalidParams.Add(request.NewErrParamRequired("TableName")) + } + if s.TableName != nil && len(*s.TableName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TableName", 1)) + } + if s.ColumnStatisticsList != nil { + for i, v := range s.ColumnStatisticsList { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ColumnStatisticsList", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCatalogId sets the CatalogId field's value. +func (s *UpdateColumnStatisticsForPartitionInput) SetCatalogId(v string) *UpdateColumnStatisticsForPartitionInput { + s.CatalogId = &v + return s +} + +// SetColumnStatisticsList sets the ColumnStatisticsList field's value. +func (s *UpdateColumnStatisticsForPartitionInput) SetColumnStatisticsList(v []*ColumnStatistics) *UpdateColumnStatisticsForPartitionInput { + s.ColumnStatisticsList = v + return s +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *UpdateColumnStatisticsForPartitionInput) SetDatabaseName(v string) *UpdateColumnStatisticsForPartitionInput { + s.DatabaseName = &v + return s +} + +// SetPartitionValues sets the PartitionValues field's value. +func (s *UpdateColumnStatisticsForPartitionInput) SetPartitionValues(v []*string) *UpdateColumnStatisticsForPartitionInput { + s.PartitionValues = v + return s +} + +// SetTableName sets the TableName field's value. +func (s *UpdateColumnStatisticsForPartitionInput) SetTableName(v string) *UpdateColumnStatisticsForPartitionInput { + s.TableName = &v + return s +} + +type UpdateColumnStatisticsForPartitionOutput struct { + _ struct{} `type:"structure"` + + // Error occurred during updating column statistics data. + Errors []*ColumnStatisticsError `type:"list"` +} + +// String returns the string representation +func (s UpdateColumnStatisticsForPartitionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateColumnStatisticsForPartitionOutput) GoString() string { + return s.String() +} + +// SetErrors sets the Errors field's value. +func (s *UpdateColumnStatisticsForPartitionOutput) SetErrors(v []*ColumnStatisticsError) *UpdateColumnStatisticsForPartitionOutput { + s.Errors = v + return s +} + +type UpdateColumnStatisticsForTableInput struct { + _ struct{} `type:"structure"` + + // The ID of the Data Catalog where the partitions in question reside. If none + // is supplied, the AWS account ID is used by default. + CatalogId *string `min:"1" type:"string"` + + // A list of the column statistics. + // + // ColumnStatisticsList is a required field + ColumnStatisticsList []*ColumnStatistics `type:"list" required:"true"` + + // The name of the catalog database where the partitions reside. + // + // DatabaseName is a required field + DatabaseName *string `min:"1" type:"string" required:"true"` + + // The name of the partitions' table. + // + // TableName is a required field + TableName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s UpdateColumnStatisticsForTableInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateColumnStatisticsForTableInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateColumnStatisticsForTableInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateColumnStatisticsForTableInput"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } + if s.ColumnStatisticsList == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnStatisticsList")) + } + if s.DatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("DatabaseName")) + } + if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) + } + if s.TableName == nil { + invalidParams.Add(request.NewErrParamRequired("TableName")) + } + if s.TableName != nil && len(*s.TableName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TableName", 1)) + } + if s.ColumnStatisticsList != nil { + for i, v := range s.ColumnStatisticsList { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ColumnStatisticsList", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCatalogId sets the CatalogId field's value. +func (s *UpdateColumnStatisticsForTableInput) SetCatalogId(v string) *UpdateColumnStatisticsForTableInput { + s.CatalogId = &v + return s +} + +// SetColumnStatisticsList sets the ColumnStatisticsList field's value. +func (s *UpdateColumnStatisticsForTableInput) SetColumnStatisticsList(v []*ColumnStatistics) *UpdateColumnStatisticsForTableInput { + s.ColumnStatisticsList = v + return s +} + +// SetDatabaseName sets the DatabaseName field's value. +func (s *UpdateColumnStatisticsForTableInput) SetDatabaseName(v string) *UpdateColumnStatisticsForTableInput { + s.DatabaseName = &v + return s +} + +// SetTableName sets the TableName field's value. +func (s *UpdateColumnStatisticsForTableInput) SetTableName(v string) *UpdateColumnStatisticsForTableInput { + s.TableName = &v + return s +} + +type UpdateColumnStatisticsForTableOutput struct { + _ struct{} `type:"structure"` + + // List of ColumnStatisticsErrors. + Errors []*ColumnStatisticsError `type:"list"` +} + +// String returns the string representation +func (s UpdateColumnStatisticsForTableOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateColumnStatisticsForTableOutput) GoString() string { + return s.String() +} + +// SetErrors sets the Errors field's value. +func (s *UpdateColumnStatisticsForTableOutput) SetErrors(v []*ColumnStatisticsError) *UpdateColumnStatisticsForTableOutput { + s.Errors = v + return s +} + type UpdateConnectionInput struct { _ struct{} `type:"structure"` @@ -32068,9 +35199,9 @@ type UpdateCrawlerInput struct { // always override the default classifiers for a given classification. Classifiers []*string `type:"list"` - // The crawler configuration information. This versioned JSON string allows - // users to specify aspects of a crawler's behavior. For more information, see - // Configuring a Crawler (http://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html). + // Crawler configuration information. This versioned JSON string allows users + // to specify aspects of a crawler's behavior. For more information, see Configuring + // a Crawler (https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html). Configuration *string `type:"string"` // The name of the SecurityConfiguration structure to be used by this crawler. @@ -32091,10 +35222,10 @@ type UpdateCrawlerInput struct { // the new crawler to access customer resources. Role *string `type:"string"` - // A cron expression used to specify the schedule. For more information, see - // Time-Based Schedules for Jobs and Crawlers (http://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html). - // For example, to run something every day at 12:15 UTC, specify cron(15 12 - // * * ? *). + // A cron expression used to specify the schedule (see Time-Based Schedules + // for Jobs and Crawlers (https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html). + // For example, to run something every day at 12:15 UTC, you would specify: + // cron(15 12 * * ? *). Schedule *string `type:"string"` // The policy for the crawler's update and deletion behavior. @@ -32226,10 +35357,10 @@ type UpdateCrawlerScheduleInput struct { // CrawlerName is a required field CrawlerName *string `min:"1" type:"string" required:"true"` - // The updated cron expression used to specify the schedule. For more information, - // see Time-Based Schedules for Jobs and Crawlers (http://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html). - // For example, to run something every day at 12:15 UTC, specify cron(15 12 - // * * ? *). + // The updated cron expression used to specify the schedule (see Time-Based + // Schedules for Jobs and Crawlers (https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html). + // For example, to run something every day at 12:15 UTC, you would specify: + // cron(15 12 * * ? *). Schedule *string `type:"string"` } @@ -33025,10 +36156,13 @@ type UpdatePartitionInput struct { // The new partition object to update the partition to. // + // The Values property can't be changed. If you want to change the partition + // key values for a partition, delete and recreate the partition. + // // PartitionInput is a required field PartitionInput *PartitionInput `type:"structure" required:"true"` - // A list of the values defining the partition. + // List of partition key values that define the partition to update. // // PartitionValueList is a required field PartitionValueList []*string `type:"list" required:"true"` @@ -33424,6 +36558,12 @@ type UpdateWorkflowInput struct { // The description of the workflow. Description *string `type:"string"` + // You can use this parameter to prevent unwanted multiple updates to data, + // to control costs, or in some cases, to prevent exceeding the maximum number + // of concurrent runs of any of the component jobs. If you leave this parameter + // blank, there is no limit to the number of concurrent workflow runs. + MaxConcurrentRuns *int64 `type:"integer"` + // Name of the workflow to be updated. // // Name is a required field @@ -33468,6 +36608,12 @@ func (s *UpdateWorkflowInput) SetDescription(v string) *UpdateWorkflowInput { return s } +// SetMaxConcurrentRuns sets the MaxConcurrentRuns field's value. +func (s *UpdateWorkflowInput) SetMaxConcurrentRuns(v int64) *UpdateWorkflowInput { + s.MaxConcurrentRuns = &v + return s +} + // SetName sets the Name field's value. func (s *UpdateWorkflowInput) SetName(v string) *UpdateWorkflowInput { s.Name = &v @@ -33565,12 +36711,18 @@ func (s *UpdateXMLClassifierRequest) SetRowTag(v string) *UpdateXMLClassifierReq type UserDefinedFunction struct { _ struct{} `type:"structure"` + // The ID of the Data Catalog in which the function resides. + CatalogId *string `min:"1" type:"string"` + // The Java class that contains the function code. ClassName *string `min:"1" type:"string"` // The time at which the function was created. CreateTime *time.Time `type:"timestamp"` + // The name of the catalog database that contains the function. + DatabaseName *string `min:"1" type:"string"` + // The name of the function. FunctionName *string `min:"1" type:"string"` @@ -33594,6 +36746,12 @@ func (s UserDefinedFunction) GoString() string { return s.String() } +// SetCatalogId sets the CatalogId field's value. +func (s *UserDefinedFunction) SetCatalogId(v string) *UserDefinedFunction { + s.CatalogId = &v + return s +} + // SetClassName sets the ClassName field's value. func (s *UserDefinedFunction) SetClassName(v string) *UserDefinedFunction { s.ClassName = &v @@ -33606,6 +36764,12 @@ func (s *UserDefinedFunction) SetCreateTime(v time.Time) *UserDefinedFunction { return s } +// SetDatabaseName sets the DatabaseName field's value. +func (s *UserDefinedFunction) SetDatabaseName(v string) *UserDefinedFunction { + s.DatabaseName = &v + return s +} + // SetFunctionName sets the FunctionName field's value. func (s *UserDefinedFunction) SetFunctionName(v string) *UserDefinedFunction { s.FunctionName = &v @@ -33857,6 +37021,12 @@ type Workflow struct { // The information about the last execution of the workflow. LastRun *WorkflowRun `type:"structure"` + // You can use this parameter to prevent unwanted multiple updates to data, + // to control costs, or in some cases, to prevent exceeding the maximum number + // of concurrent runs of any of the component jobs. If you leave this parameter + // blank, there is no limit to the number of concurrent workflow runs. + MaxConcurrentRuns *int64 `type:"integer"` + // The name of the workflow representing the flow. Name *string `min:"1" type:"string"` } @@ -33907,6 +37077,12 @@ func (s *Workflow) SetLastRun(v *WorkflowRun) *Workflow { return s } +// SetMaxConcurrentRuns sets the MaxConcurrentRuns field's value. +func (s *Workflow) SetMaxConcurrentRuns(v int64) *Workflow { + s.MaxConcurrentRuns = &v + return s +} + // SetName sets the Name field's value. func (s *Workflow) SetName(v string) *Workflow { s.Name = &v @@ -33957,13 +37133,21 @@ type WorkflowRun struct { // The date and time when the workflow run completed. CompletedOn *time.Time `type:"timestamp"` + // This error message describes any error that may have occurred in starting + // the workflow run. Currently the only error message is "Concurrent runs exceeded + // for workflow: foo." + ErrorMessage *string `type:"string"` + // The graph representing all the AWS Glue components that belong to the workflow // as nodes and directed connections between them as edges. Graph *WorkflowGraph `type:"structure"` - // Name of the workflow which was executed. + // Name of the workflow that was executed. Name *string `min:"1" type:"string"` + // The ID of the previous workflow run. + PreviousRunId *string `min:"1" type:"string"` + // The date and time when the workflow run was started. StartedOn *time.Time `type:"timestamp"` @@ -33996,6 +37180,12 @@ func (s *WorkflowRun) SetCompletedOn(v time.Time) *WorkflowRun { return s } +// SetErrorMessage sets the ErrorMessage field's value. +func (s *WorkflowRun) SetErrorMessage(v string) *WorkflowRun { + s.ErrorMessage = &v + return s +} + // SetGraph sets the Graph field's value. func (s *WorkflowRun) SetGraph(v *WorkflowGraph) *WorkflowRun { s.Graph = v @@ -34008,6 +37198,12 @@ func (s *WorkflowRun) SetName(v string) *WorkflowRun { return s } +// SetPreviousRunId sets the PreviousRunId field's value. +func (s *WorkflowRun) SetPreviousRunId(v string) *WorkflowRun { + s.PreviousRunId = &v + return s +} + // SetStartedOn sets the StartedOn field's value. func (s *WorkflowRun) SetStartedOn(v time.Time) *WorkflowRun { s.StartedOn = &v @@ -34042,19 +37238,19 @@ func (s *WorkflowRun) SetWorkflowRunProperties(v map[string]*string) *WorkflowRu type WorkflowRunStatistics struct { _ struct{} `type:"structure"` - // Total number of Actions which have failed. + // Total number of Actions that have failed. FailedActions *int64 `type:"integer"` // Total number Actions in running state. RunningActions *int64 `type:"integer"` - // Total number of Actions which have stopped. + // Total number of Actions that have stopped. StoppedActions *int64 `type:"integer"` - // Total number of Actions which have succeeded. + // Total number of Actions that have succeeded. SucceededActions *int64 `type:"integer"` - // Total number of Actions which timed out. + // Total number of Actions that timed out. TimeoutActions *int64 `type:"integer"` // Total number of Actions in the workflow run. @@ -34192,6 +37388,14 @@ const ( CatalogEncryptionModeSseKms = "SSE-KMS" ) +// CatalogEncryptionMode_Values returns all elements of the CatalogEncryptionMode enum +func CatalogEncryptionMode_Values() []string { + return []string{ + CatalogEncryptionModeDisabled, + CatalogEncryptionModeSseKms, + } +} + const ( // CloudWatchEncryptionModeDisabled is a CloudWatchEncryptionMode enum value CloudWatchEncryptionModeDisabled = "DISABLED" @@ -34200,6 +37404,50 @@ const ( CloudWatchEncryptionModeSseKms = "SSE-KMS" ) +// CloudWatchEncryptionMode_Values returns all elements of the CloudWatchEncryptionMode enum +func CloudWatchEncryptionMode_Values() []string { + return []string{ + CloudWatchEncryptionModeDisabled, + CloudWatchEncryptionModeSseKms, + } +} + +const ( + // ColumnStatisticsTypeBoolean is a ColumnStatisticsType enum value + ColumnStatisticsTypeBoolean = "BOOLEAN" + + // ColumnStatisticsTypeDate is a ColumnStatisticsType enum value + ColumnStatisticsTypeDate = "DATE" + + // ColumnStatisticsTypeDecimal is a ColumnStatisticsType enum value + ColumnStatisticsTypeDecimal = "DECIMAL" + + // ColumnStatisticsTypeDouble is a ColumnStatisticsType enum value + ColumnStatisticsTypeDouble = "DOUBLE" + + // ColumnStatisticsTypeLong is a ColumnStatisticsType enum value + ColumnStatisticsTypeLong = "LONG" + + // ColumnStatisticsTypeString is a ColumnStatisticsType enum value + ColumnStatisticsTypeString = "STRING" + + // ColumnStatisticsTypeBinary is a ColumnStatisticsType enum value + ColumnStatisticsTypeBinary = "BINARY" +) + +// ColumnStatisticsType_Values returns all elements of the ColumnStatisticsType enum +func ColumnStatisticsType_Values() []string { + return []string{ + ColumnStatisticsTypeBoolean, + ColumnStatisticsTypeDate, + ColumnStatisticsTypeDecimal, + ColumnStatisticsTypeDouble, + ColumnStatisticsTypeLong, + ColumnStatisticsTypeString, + ColumnStatisticsTypeBinary, + } +} + const ( // ComparatorEquals is a Comparator enum value ComparatorEquals = "EQUALS" @@ -34217,6 +37465,17 @@ const ( ComparatorLessThanEquals = "LESS_THAN_EQUALS" ) +// Comparator_Values returns all elements of the Comparator enum +func Comparator_Values() []string { + return []string{ + ComparatorEquals, + ComparatorGreaterThan, + ComparatorLessThan, + ComparatorGreaterThanEquals, + ComparatorLessThanEquals, + } +} + const ( // ConnectionPropertyKeyHost is a ConnectionPropertyKey enum value ConnectionPropertyKeyHost = "HOST" @@ -34271,8 +37530,44 @@ const ( // ConnectionPropertyKeyKafkaBootstrapServers is a ConnectionPropertyKey enum value ConnectionPropertyKeyKafkaBootstrapServers = "KAFKA_BOOTSTRAP_SERVERS" + + // ConnectionPropertyKeyKafkaSslEnabled is a ConnectionPropertyKey enum value + ConnectionPropertyKeyKafkaSslEnabled = "KAFKA_SSL_ENABLED" + + // ConnectionPropertyKeyKafkaCustomCert is a ConnectionPropertyKey enum value + ConnectionPropertyKeyKafkaCustomCert = "KAFKA_CUSTOM_CERT" + + // ConnectionPropertyKeyKafkaSkipCustomCertValidation is a ConnectionPropertyKey enum value + ConnectionPropertyKeyKafkaSkipCustomCertValidation = "KAFKA_SKIP_CUSTOM_CERT_VALIDATION" ) +// ConnectionPropertyKey_Values returns all elements of the ConnectionPropertyKey enum +func ConnectionPropertyKey_Values() []string { + return []string{ + ConnectionPropertyKeyHost, + ConnectionPropertyKeyPort, + ConnectionPropertyKeyUsername, + ConnectionPropertyKeyPassword, + ConnectionPropertyKeyEncryptedPassword, + ConnectionPropertyKeyJdbcDriverJarUri, + ConnectionPropertyKeyJdbcDriverClassName, + ConnectionPropertyKeyJdbcEngine, + ConnectionPropertyKeyJdbcEngineVersion, + ConnectionPropertyKeyConfigFiles, + ConnectionPropertyKeyInstanceId, + ConnectionPropertyKeyJdbcConnectionUrl, + ConnectionPropertyKeyJdbcEnforceSsl, + ConnectionPropertyKeyCustomJdbcCert, + ConnectionPropertyKeySkipCustomJdbcCertValidation, + ConnectionPropertyKeyCustomJdbcCertString, + ConnectionPropertyKeyConnectionUrl, + ConnectionPropertyKeyKafkaBootstrapServers, + ConnectionPropertyKeyKafkaSslEnabled, + ConnectionPropertyKeyKafkaCustomCert, + ConnectionPropertyKeyKafkaSkipCustomCertValidation, + } +} + const ( // ConnectionTypeJdbc is a ConnectionType enum value ConnectionTypeJdbc = "JDBC" @@ -34285,22 +37580,50 @@ const ( // ConnectionTypeKafka is a ConnectionType enum value ConnectionTypeKafka = "KAFKA" + + // ConnectionTypeNetwork is a ConnectionType enum value + ConnectionTypeNetwork = "NETWORK" ) +// ConnectionType_Values returns all elements of the ConnectionType enum +func ConnectionType_Values() []string { + return []string{ + ConnectionTypeJdbc, + ConnectionTypeSftp, + ConnectionTypeMongodb, + ConnectionTypeKafka, + ConnectionTypeNetwork, + } +} + const ( // CrawlStateRunning is a CrawlState enum value CrawlStateRunning = "RUNNING" - // CrawlStateSucceeded is a CrawlState enum value - CrawlStateSucceeded = "SUCCEEDED" + // CrawlStateCancelling is a CrawlState enum value + CrawlStateCancelling = "CANCELLING" // CrawlStateCancelled is a CrawlState enum value CrawlStateCancelled = "CANCELLED" + // CrawlStateSucceeded is a CrawlState enum value + CrawlStateSucceeded = "SUCCEEDED" + // CrawlStateFailed is a CrawlState enum value CrawlStateFailed = "FAILED" ) +// CrawlState_Values returns all elements of the CrawlState enum +func CrawlState_Values() []string { + return []string{ + CrawlStateRunning, + CrawlStateCancelling, + CrawlStateCancelled, + CrawlStateSucceeded, + CrawlStateFailed, + } +} + const ( // CrawlerStateReady is a CrawlerState enum value CrawlerStateReady = "READY" @@ -34312,6 +37635,15 @@ const ( CrawlerStateStopping = "STOPPING" ) +// CrawlerState_Values returns all elements of the CrawlerState enum +func CrawlerState_Values() []string { + return []string{ + CrawlerStateReady, + CrawlerStateRunning, + CrawlerStateStopping, + } +} + const ( // CsvHeaderOptionUnknown is a CsvHeaderOption enum value CsvHeaderOptionUnknown = "UNKNOWN" @@ -34323,6 +37655,15 @@ const ( CsvHeaderOptionAbsent = "ABSENT" ) +// CsvHeaderOption_Values returns all elements of the CsvHeaderOption enum +func CsvHeaderOption_Values() []string { + return []string{ + CsvHeaderOptionUnknown, + CsvHeaderOptionPresent, + CsvHeaderOptionAbsent, + } +} + const ( // DeleteBehaviorLog is a DeleteBehavior enum value DeleteBehaviorLog = "LOG" @@ -34334,6 +37675,31 @@ const ( DeleteBehaviorDeprecateInDatabase = "DEPRECATE_IN_DATABASE" ) +// DeleteBehavior_Values returns all elements of the DeleteBehavior enum +func DeleteBehavior_Values() []string { + return []string{ + DeleteBehaviorLog, + DeleteBehaviorDeleteFromDatabase, + DeleteBehaviorDeprecateInDatabase, + } +} + +const ( + // EnableHybridValuesTrue is a EnableHybridValues enum value + EnableHybridValuesTrue = "TRUE" + + // EnableHybridValuesFalse is a EnableHybridValues enum value + EnableHybridValuesFalse = "FALSE" +) + +// EnableHybridValues_Values returns all elements of the EnableHybridValues enum +func EnableHybridValues_Values() []string { + return []string{ + EnableHybridValuesTrue, + EnableHybridValuesFalse, + } +} + const ( // ExistConditionMustExist is a ExistCondition enum value ExistConditionMustExist = "MUST_EXIST" @@ -34345,6 +37711,15 @@ const ( ExistConditionNone = "NONE" ) +// ExistCondition_Values returns all elements of the ExistCondition enum +func ExistCondition_Values() []string { + return []string{ + ExistConditionMustExist, + ExistConditionNotExist, + ExistConditionNone, + } +} + const ( // JobBookmarksEncryptionModeDisabled is a JobBookmarksEncryptionMode enum value JobBookmarksEncryptionModeDisabled = "DISABLED" @@ -34353,6 +37728,14 @@ const ( JobBookmarksEncryptionModeCseKms = "CSE-KMS" ) +// JobBookmarksEncryptionMode_Values returns all elements of the JobBookmarksEncryptionMode enum +func JobBookmarksEncryptionMode_Values() []string { + return []string{ + JobBookmarksEncryptionModeDisabled, + JobBookmarksEncryptionModeCseKms, + } +} + const ( // JobRunStateStarting is a JobRunState enum value JobRunStateStarting = "STARTING" @@ -34376,6 +37759,19 @@ const ( JobRunStateTimeout = "TIMEOUT" ) +// JobRunState_Values returns all elements of the JobRunState enum +func JobRunState_Values() []string { + return []string{ + JobRunStateStarting, + JobRunStateRunning, + JobRunStateStopping, + JobRunStateStopped, + JobRunStateSucceeded, + JobRunStateFailed, + JobRunStateTimeout, + } +} + const ( // LanguagePython is a Language enum value LanguagePython = "PYTHON" @@ -34384,6 +37780,14 @@ const ( LanguageScala = "SCALA" ) +// Language_Values returns all elements of the Language enum +func Language_Values() []string { + return []string{ + LanguagePython, + LanguageScala, + } +} + const ( // LastCrawlStatusSucceeded is a LastCrawlStatus enum value LastCrawlStatusSucceeded = "SUCCEEDED" @@ -34395,6 +37799,15 @@ const ( LastCrawlStatusFailed = "FAILED" ) +// LastCrawlStatus_Values returns all elements of the LastCrawlStatus enum +func LastCrawlStatus_Values() []string { + return []string{ + LastCrawlStatusSucceeded, + LastCrawlStatusCancelled, + LastCrawlStatusFailed, + } +} + const ( // LogicalAnd is a Logical enum value LogicalAnd = "AND" @@ -34403,11 +37816,26 @@ const ( LogicalAny = "ANY" ) +// Logical_Values returns all elements of the Logical enum +func Logical_Values() []string { + return []string{ + LogicalAnd, + LogicalAny, + } +} + const ( // LogicalOperatorEquals is a LogicalOperator enum value LogicalOperatorEquals = "EQUALS" ) +// LogicalOperator_Values returns all elements of the LogicalOperator enum +func LogicalOperator_Values() []string { + return []string{ + LogicalOperatorEquals, + } +} + const ( // NodeTypeCrawler is a NodeType enum value NodeTypeCrawler = "CRAWLER" @@ -34419,6 +37847,15 @@ const ( NodeTypeTrigger = "TRIGGER" ) +// NodeType_Values returns all elements of the NodeType enum +func NodeType_Values() []string { + return []string{ + NodeTypeCrawler, + NodeTypeJob, + NodeTypeTrigger, + } +} + const ( // PermissionAll is a Permission enum value PermissionAll = "ALL" @@ -34448,6 +37885,21 @@ const ( PermissionDataLocationAccess = "DATA_LOCATION_ACCESS" ) +// Permission_Values returns all elements of the Permission enum +func Permission_Values() []string { + return []string{ + PermissionAll, + PermissionSelect, + PermissionAlter, + PermissionDrop, + PermissionDelete, + PermissionInsert, + PermissionCreateDatabase, + PermissionCreateTable, + PermissionDataLocationAccess, + } +} + const ( // PrincipalTypeUser is a PrincipalType enum value PrincipalTypeUser = "USER" @@ -34459,6 +37911,31 @@ const ( PrincipalTypeGroup = "GROUP" ) +// PrincipalType_Values returns all elements of the PrincipalType enum +func PrincipalType_Values() []string { + return []string{ + PrincipalTypeUser, + PrincipalTypeRole, + PrincipalTypeGroup, + } +} + +const ( + // ResourceShareTypeForeign is a ResourceShareType enum value + ResourceShareTypeForeign = "FOREIGN" + + // ResourceShareTypeAll is a ResourceShareType enum value + ResourceShareTypeAll = "ALL" +) + +// ResourceShareType_Values returns all elements of the ResourceShareType enum +func ResourceShareType_Values() []string { + return []string{ + ResourceShareTypeForeign, + ResourceShareTypeAll, + } +} + const ( // ResourceTypeJar is a ResourceType enum value ResourceTypeJar = "JAR" @@ -34470,6 +37947,15 @@ const ( ResourceTypeArchive = "ARCHIVE" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeJar, + ResourceTypeFile, + ResourceTypeArchive, + } +} + const ( // S3EncryptionModeDisabled is a S3EncryptionMode enum value S3EncryptionModeDisabled = "DISABLED" @@ -34481,6 +37967,15 @@ const ( S3EncryptionModeSseS3 = "SSE-S3" ) +// S3EncryptionMode_Values returns all elements of the S3EncryptionMode enum +func S3EncryptionMode_Values() []string { + return []string{ + S3EncryptionModeDisabled, + S3EncryptionModeSseKms, + S3EncryptionModeSseS3, + } +} + const ( // ScheduleStateScheduled is a ScheduleState enum value ScheduleStateScheduled = "SCHEDULED" @@ -34492,6 +37987,15 @@ const ( ScheduleStateTransitioning = "TRANSITIONING" ) +// ScheduleState_Values returns all elements of the ScheduleState enum +func ScheduleState_Values() []string { + return []string{ + ScheduleStateScheduled, + ScheduleStateNotScheduled, + ScheduleStateTransitioning, + } +} + const ( // SortAsc is a Sort enum value SortAsc = "ASC" @@ -34500,6 +38004,14 @@ const ( SortDesc = "DESC" ) +// Sort_Values returns all elements of the Sort enum +func Sort_Values() []string { + return []string{ + SortAsc, + SortDesc, + } +} + const ( // SortDirectionTypeDescending is a SortDirectionType enum value SortDirectionTypeDescending = "DESCENDING" @@ -34508,6 +38020,14 @@ const ( SortDirectionTypeAscending = "ASCENDING" ) +// SortDirectionType_Values returns all elements of the SortDirectionType enum +func SortDirectionType_Values() []string { + return []string{ + SortDirectionTypeDescending, + SortDirectionTypeAscending, + } +} + const ( // TaskRunSortColumnTypeTaskRunType is a TaskRunSortColumnType enum value TaskRunSortColumnTypeTaskRunType = "TASK_RUN_TYPE" @@ -34519,6 +38039,15 @@ const ( TaskRunSortColumnTypeStarted = "STARTED" ) +// TaskRunSortColumnType_Values returns all elements of the TaskRunSortColumnType enum +func TaskRunSortColumnType_Values() []string { + return []string{ + TaskRunSortColumnTypeTaskRunType, + TaskRunSortColumnTypeStatus, + TaskRunSortColumnTypeStarted, + } +} + const ( // TaskStatusTypeStarting is a TaskStatusType enum value TaskStatusTypeStarting = "STARTING" @@ -34542,6 +38071,19 @@ const ( TaskStatusTypeTimeout = "TIMEOUT" ) +// TaskStatusType_Values returns all elements of the TaskStatusType enum +func TaskStatusType_Values() []string { + return []string{ + TaskStatusTypeStarting, + TaskStatusTypeRunning, + TaskStatusTypeStopping, + TaskStatusTypeStopped, + TaskStatusTypeSucceeded, + TaskStatusTypeFailed, + TaskStatusTypeTimeout, + } +} + const ( // TaskTypeEvaluation is a TaskType enum value TaskTypeEvaluation = "EVALUATION" @@ -34559,6 +38101,17 @@ const ( TaskTypeFindMatches = "FIND_MATCHES" ) +// TaskType_Values returns all elements of the TaskType enum +func TaskType_Values() []string { + return []string{ + TaskTypeEvaluation, + TaskTypeLabelingSetGeneration, + TaskTypeImportLabels, + TaskTypeExportLabels, + TaskTypeFindMatches, + } +} + const ( // TransformSortColumnTypeName is a TransformSortColumnType enum value TransformSortColumnTypeName = "NAME" @@ -34576,6 +38129,17 @@ const ( TransformSortColumnTypeLastModified = "LAST_MODIFIED" ) +// TransformSortColumnType_Values returns all elements of the TransformSortColumnType enum +func TransformSortColumnType_Values() []string { + return []string{ + TransformSortColumnTypeName, + TransformSortColumnTypeTransformType, + TransformSortColumnTypeStatus, + TransformSortColumnTypeCreated, + TransformSortColumnTypeLastModified, + } +} + const ( // TransformStatusTypeNotReady is a TransformStatusType enum value TransformStatusTypeNotReady = "NOT_READY" @@ -34587,11 +38151,27 @@ const ( TransformStatusTypeDeleting = "DELETING" ) +// TransformStatusType_Values returns all elements of the TransformStatusType enum +func TransformStatusType_Values() []string { + return []string{ + TransformStatusTypeNotReady, + TransformStatusTypeReady, + TransformStatusTypeDeleting, + } +} + const ( // TransformTypeFindMatches is a TransformType enum value TransformTypeFindMatches = "FIND_MATCHES" ) +// TransformType_Values returns all elements of the TransformType enum +func TransformType_Values() []string { + return []string{ + TransformTypeFindMatches, + } +} + const ( // TriggerStateCreating is a TriggerState enum value TriggerStateCreating = "CREATING" @@ -34618,6 +38198,20 @@ const ( TriggerStateUpdating = "UPDATING" ) +// TriggerState_Values returns all elements of the TriggerState enum +func TriggerState_Values() []string { + return []string{ + TriggerStateCreating, + TriggerStateCreated, + TriggerStateActivating, + TriggerStateActivated, + TriggerStateDeactivating, + TriggerStateDeactivated, + TriggerStateDeleting, + TriggerStateUpdating, + } +} + const ( // TriggerTypeScheduled is a TriggerType enum value TriggerTypeScheduled = "SCHEDULED" @@ -34629,6 +38223,15 @@ const ( TriggerTypeOnDemand = "ON_DEMAND" ) +// TriggerType_Values returns all elements of the TriggerType enum +func TriggerType_Values() []string { + return []string{ + TriggerTypeScheduled, + TriggerTypeConditional, + TriggerTypeOnDemand, + } +} + const ( // UpdateBehaviorLog is a UpdateBehavior enum value UpdateBehaviorLog = "LOG" @@ -34637,6 +38240,14 @@ const ( UpdateBehaviorUpdateInDatabase = "UPDATE_IN_DATABASE" ) +// UpdateBehavior_Values returns all elements of the UpdateBehavior enum +func UpdateBehavior_Values() []string { + return []string{ + UpdateBehaviorLog, + UpdateBehaviorUpdateInDatabase, + } +} + const ( // WorkerTypeStandard is a WorkerType enum value WorkerTypeStandard = "Standard" @@ -34648,10 +38259,39 @@ const ( WorkerTypeG2x = "G.2X" ) +// WorkerType_Values returns all elements of the WorkerType enum +func WorkerType_Values() []string { + return []string{ + WorkerTypeStandard, + WorkerTypeG1x, + WorkerTypeG2x, + } +} + const ( // WorkflowRunStatusRunning is a WorkflowRunStatus enum value WorkflowRunStatusRunning = "RUNNING" // WorkflowRunStatusCompleted is a WorkflowRunStatus enum value WorkflowRunStatusCompleted = "COMPLETED" + + // WorkflowRunStatusStopping is a WorkflowRunStatus enum value + WorkflowRunStatusStopping = "STOPPING" + + // WorkflowRunStatusStopped is a WorkflowRunStatus enum value + WorkflowRunStatusStopped = "STOPPED" + + // WorkflowRunStatusError is a WorkflowRunStatus enum value + WorkflowRunStatusError = "ERROR" ) + +// WorkflowRunStatus_Values returns all elements of the WorkflowRunStatus enum +func WorkflowRunStatus_Values() []string { + return []string{ + WorkflowRunStatusRunning, + WorkflowRunStatusCompleted, + WorkflowRunStatusStopping, + WorkflowRunStatusStopped, + WorkflowRunStatusError, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/glue/errors.go b/vendor/github.com/aws/aws-sdk-go/service/glue/errors.go index dc5ad7afd38..95a992b0233 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/glue/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/glue/errors.go @@ -74,6 +74,12 @@ const ( // The same unique identifier was associated with two different records. ErrCodeIdempotentParameterMismatchException = "IdempotentParameterMismatchException" + // ErrCodeIllegalWorkflowStateException for service response error code + // "IllegalWorkflowStateException". + // + // The workflow is in an invalid state to perform a requested operation. + ErrCodeIllegalWorkflowStateException = "IllegalWorkflowStateException" + // ErrCodeInternalServiceException for service response error code // "InternalServiceException". // @@ -153,6 +159,7 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "GlueEncryptionException": newErrorEncryptionException, "EntityNotFoundException": newErrorEntityNotFoundException, "IdempotentParameterMismatchException": newErrorIdempotentParameterMismatchException, + "IllegalWorkflowStateException": newErrorIllegalWorkflowStateException, "InternalServiceException": newErrorInternalServiceException, "InvalidInputException": newErrorInvalidInputException, "MLTransformNotReadyException": newErrorMLTransformNotReadyException, diff --git a/vendor/github.com/aws/aws-sdk-go/service/greengrass/api.go b/vendor/github.com/aws/aws-sdk-go/service/greengrass/api.go index e67104de93f..7d864204ccc 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/greengrass/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/greengrass/api.go @@ -17704,6 +17704,18 @@ const ( BulkDeploymentStatusFailed = "Failed" ) +// BulkDeploymentStatus_Values returns all elements of the BulkDeploymentStatus enum +func BulkDeploymentStatus_Values() []string { + return []string{ + BulkDeploymentStatusInitializing, + BulkDeploymentStatusRunning, + BulkDeploymentStatusCompleted, + BulkDeploymentStatusStopping, + BulkDeploymentStatusStopped, + BulkDeploymentStatusFailed, + } +} + // The type of deployment. When used for ''CreateDeployment'', only ''NewDeployment'' // and ''Redeployment'' are valid. const ( @@ -17720,6 +17732,16 @@ const ( DeploymentTypeForceResetDeployment = "ForceResetDeployment" ) +// DeploymentType_Values returns all elements of the DeploymentType enum +func DeploymentType_Values() []string { + return []string{ + DeploymentTypeNewDeployment, + DeploymentTypeRedeployment, + DeploymentTypeResetDeployment, + DeploymentTypeForceResetDeployment, + } +} + const ( // EncodingTypeBinary is a EncodingType enum value EncodingTypeBinary = "binary" @@ -17728,6 +17750,14 @@ const ( EncodingTypeJson = "json" ) +// EncodingType_Values returns all elements of the EncodingType enum +func EncodingType_Values() []string { + return []string{ + EncodingTypeBinary, + EncodingTypeJson, + } +} + // Specifies whether the Lambda function runs in a Greengrass container (default) // or without containerization. Unless your scenario requires that you run without // containerization, we recommend that you run in a Greengrass container. Omit @@ -17741,6 +17771,14 @@ const ( FunctionIsolationModeNoContainer = "NoContainer" ) +// FunctionIsolationMode_Values returns all elements of the FunctionIsolationMode enum +func FunctionIsolationMode_Values() []string { + return []string{ + FunctionIsolationModeGreengrassContainer, + FunctionIsolationModeNoContainer, + } +} + const ( // LoggerComponentGreengrassSystem is a LoggerComponent enum value LoggerComponentGreengrassSystem = "GreengrassSystem" @@ -17749,6 +17787,14 @@ const ( LoggerComponentLambda = "Lambda" ) +// LoggerComponent_Values returns all elements of the LoggerComponent enum +func LoggerComponent_Values() []string { + return []string{ + LoggerComponentGreengrassSystem, + LoggerComponentLambda, + } +} + const ( // LoggerLevelDebug is a LoggerLevel enum value LoggerLevelDebug = "DEBUG" @@ -17766,6 +17812,17 @@ const ( LoggerLevelFatal = "FATAL" ) +// LoggerLevel_Values returns all elements of the LoggerLevel enum +func LoggerLevel_Values() []string { + return []string{ + LoggerLevelDebug, + LoggerLevelInfo, + LoggerLevelWarn, + LoggerLevelError, + LoggerLevelFatal, + } +} + const ( // LoggerTypeFileSystem is a LoggerType enum value LoggerTypeFileSystem = "FileSystem" @@ -17774,6 +17831,14 @@ const ( LoggerTypeAwscloudWatch = "AWSCloudWatch" ) +// LoggerType_Values returns all elements of the LoggerType enum +func LoggerType_Values() []string { + return []string{ + LoggerTypeFileSystem, + LoggerTypeAwscloudWatch, + } +} + // The type of permission a function has to access a resource. const ( // PermissionRo is a Permission enum value @@ -17783,6 +17848,14 @@ const ( PermissionRw = "rw" ) +// Permission_Values returns all elements of the Permission enum +func Permission_Values() []string { + return []string{ + PermissionRo, + PermissionRw, + } +} + // The piece of software on the Greengrass core that will be updated. const ( // SoftwareToUpdateCore is a SoftwareToUpdate enum value @@ -17792,6 +17865,14 @@ const ( SoftwareToUpdateOtaAgent = "ota_agent" ) +// SoftwareToUpdate_Values returns all elements of the SoftwareToUpdate enum +func SoftwareToUpdate_Values() []string { + return []string{ + SoftwareToUpdateCore, + SoftwareToUpdateOtaAgent, + } +} + // The minimum level of log statements that should be logged by the OTA Agent // during an update. const ( @@ -17820,6 +17901,20 @@ const ( UpdateAgentLogLevelFatal = "FATAL" ) +// UpdateAgentLogLevel_Values returns all elements of the UpdateAgentLogLevel enum +func UpdateAgentLogLevel_Values() []string { + return []string{ + UpdateAgentLogLevelNone, + UpdateAgentLogLevelTrace, + UpdateAgentLogLevelDebug, + UpdateAgentLogLevelVerbose, + UpdateAgentLogLevelInfo, + UpdateAgentLogLevelWarn, + UpdateAgentLogLevelError, + UpdateAgentLogLevelFatal, + } +} + // The architecture of the cores which are the targets of an update. const ( // UpdateTargetsArchitectureArmv6l is a UpdateTargetsArchitecture enum value @@ -17835,6 +17930,16 @@ const ( UpdateTargetsArchitectureAarch64 = "aarch64" ) +// UpdateTargetsArchitecture_Values returns all elements of the UpdateTargetsArchitecture enum +func UpdateTargetsArchitecture_Values() []string { + return []string{ + UpdateTargetsArchitectureArmv6l, + UpdateTargetsArchitectureArmv7l, + UpdateTargetsArchitectureX8664, + UpdateTargetsArchitectureAarch64, + } +} + // The operating system of the cores which are the targets of an update. const ( // UpdateTargetsOperatingSystemUbuntu is a UpdateTargetsOperatingSystem enum value @@ -17849,3 +17954,13 @@ const ( // UpdateTargetsOperatingSystemOpenwrt is a UpdateTargetsOperatingSystem enum value UpdateTargetsOperatingSystemOpenwrt = "openwrt" ) + +// UpdateTargetsOperatingSystem_Values returns all elements of the UpdateTargetsOperatingSystem enum +func UpdateTargetsOperatingSystem_Values() []string { + return []string{ + UpdateTargetsOperatingSystemUbuntu, + UpdateTargetsOperatingSystemRaspbian, + UpdateTargetsOperatingSystemAmazonLinux, + UpdateTargetsOperatingSystemOpenwrt, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/guardduty/api.go b/vendor/github.com/aws/aws-sdk-go/service/guardduty/api.go index b1e8e563acc..afae1141d29 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/guardduty/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/guardduty/api.go @@ -4,6 +4,7 @@ package guardduty import ( "fmt" + "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" @@ -228,7 +229,8 @@ func (c *GuardDuty) CreateDetectorRequest(input *CreateDetectorInput) (req *requ // Creates a single Amazon GuardDuty detector. A detector is a resource that // represents the GuardDuty service. To start using GuardDuty, you must create // a detector in each Region where you enable the service. You can have only -// one detector per account per Region. +// one detector per account per Region. All data sources are enabled in a new +// detector by default. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -479,8 +481,17 @@ func (c *GuardDuty) CreateMembersRequest(input *CreateMembersInput) (req *reques // CreateMembers API operation for Amazon GuardDuty. // // Creates member accounts of the current AWS account by specifying a list of -// AWS account IDs. The current AWS account can then invite these members to -// manage GuardDuty in their accounts. +// AWS account IDs. This step is a prerequisite for managing the associated +// member accounts either by invitation or through an organization. +// +// When using Create Members as an organizations delegated administrator this +// action will enable GuardDuty in the added member accounts, with the exception +// of the organization master account, which must enable GuardDuty prior to +// being added as a member. +// +// If you are adding accounts by invitation use this action after GuardDuty +// has been enabled in potential member accounts and before using Invite Members +// (https://docs.aws.amazon.com/guardduty/latest/APIReference/API_InviteMembers.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 @@ -1646,8 +1657,8 @@ func (c *GuardDuty) DisableOrganizationAdminAccountRequest(input *DisableOrganiz // DisableOrganizationAdminAccount API operation for Amazon GuardDuty. // -// Disables GuardDuty administrator permissions for an AWS account within the -// Organization. +// Disables an AWS account within the Organization as the GuardDuty delegated +// administrator. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1896,8 +1907,8 @@ func (c *GuardDuty) EnableOrganizationAdminAccountRequest(input *EnableOrganizat // EnableOrganizationAdminAccount API operation for Amazon GuardDuty. // -// Enables GuardDuty administrator permissions for an AWS account within the -// organization. +// Enables an AWS account within the organization as the GuardDuty delegated +// administrator. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2511,6 +2522,88 @@ func (c *GuardDuty) GetMasterAccountWithContext(ctx aws.Context, input *GetMaste return out, req.Send() } +const opGetMemberDetectors = "GetMemberDetectors" + +// GetMemberDetectorsRequest generates a "aws/request.Request" representing the +// client's request for the GetMemberDetectors operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetMemberDetectors for more information on using the GetMemberDetectors +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetMemberDetectorsRequest method. +// req, resp := client.GetMemberDetectorsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/guardduty-2017-11-28/GetMemberDetectors +func (c *GuardDuty) GetMemberDetectorsRequest(input *GetMemberDetectorsInput) (req *request.Request, output *GetMemberDetectorsOutput) { + op := &request.Operation{ + Name: opGetMemberDetectors, + HTTPMethod: "POST", + HTTPPath: "/detector/{detectorId}/member/detector/get", + } + + if input == nil { + input = &GetMemberDetectorsInput{} + } + + output = &GetMemberDetectorsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetMemberDetectors API operation for Amazon GuardDuty. +// +// Describes which data sources are enabled for the member account's detector. +// +// Returns awserr.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 GuardDuty's +// API operation GetMemberDetectors for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// A bad request exception object. +// +// * InternalServerErrorException +// An internal server error exception object. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/guardduty-2017-11-28/GetMemberDetectors +func (c *GuardDuty) GetMemberDetectors(input *GetMemberDetectorsInput) (*GetMemberDetectorsOutput, error) { + req, out := c.GetMemberDetectorsRequest(input) + return out, req.Send() +} + +// GetMemberDetectorsWithContext is the same as GetMemberDetectors with the addition of +// the ability to pass a context and additional request options. +// +// See GetMemberDetectors for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *GuardDuty) GetMemberDetectorsWithContext(ctx aws.Context, input *GetMemberDetectorsInput, opts ...request.Option) (*GetMemberDetectorsOutput, error) { + req, out := c.GetMemberDetectorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetMembers = "GetMembers" // GetMembersRequest generates a "aws/request.Request" representing the @@ -2676,6 +2769,151 @@ func (c *GuardDuty) GetThreatIntelSetWithContext(ctx aws.Context, input *GetThre return out, req.Send() } +const opGetUsageStatistics = "GetUsageStatistics" + +// GetUsageStatisticsRequest generates a "aws/request.Request" representing the +// client's request for the GetUsageStatistics operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetUsageStatistics for more information on using the GetUsageStatistics +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetUsageStatisticsRequest method. +// req, resp := client.GetUsageStatisticsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/guardduty-2017-11-28/GetUsageStatistics +func (c *GuardDuty) GetUsageStatisticsRequest(input *GetUsageStatisticsInput) (req *request.Request, output *GetUsageStatisticsOutput) { + op := &request.Operation{ + Name: opGetUsageStatistics, + HTTPMethod: "POST", + HTTPPath: "/detector/{detectorId}/usage/statistics", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetUsageStatisticsInput{} + } + + output = &GetUsageStatisticsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetUsageStatistics API operation for Amazon GuardDuty. +// +// Lists Amazon GuardDuty usage statistics over the last 30 days for the specified +// detector ID. For newly enabled detectors or data sources the cost returned +// will include only the usage so far under 30 days, this may differ from the +// cost metrics in the console, which projects usage over 30 days to provide +// a monthly cost estimate. For more information see Understanding How Usage +// Costs are Calculated (https://docs.aws.amazon.com/guardduty/latest/ug/monitoring_costs.html#usage-calculations). +// +// Returns awserr.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 GuardDuty's +// API operation GetUsageStatistics for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// A bad request exception object. +// +// * InternalServerErrorException +// An internal server error exception object. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/guardduty-2017-11-28/GetUsageStatistics +func (c *GuardDuty) GetUsageStatistics(input *GetUsageStatisticsInput) (*GetUsageStatisticsOutput, error) { + req, out := c.GetUsageStatisticsRequest(input) + return out, req.Send() +} + +// GetUsageStatisticsWithContext is the same as GetUsageStatistics with the addition of +// the ability to pass a context and additional request options. +// +// See GetUsageStatistics for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *GuardDuty) GetUsageStatisticsWithContext(ctx aws.Context, input *GetUsageStatisticsInput, opts ...request.Option) (*GetUsageStatisticsOutput, error) { + req, out := c.GetUsageStatisticsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetUsageStatisticsPages iterates over the pages of a GetUsageStatistics operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetUsageStatistics 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 GetUsageStatistics operation. +// pageNum := 0 +// err := client.GetUsageStatisticsPages(params, +// func(page *guardduty.GetUsageStatisticsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *GuardDuty) GetUsageStatisticsPages(input *GetUsageStatisticsInput, fn func(*GetUsageStatisticsOutput, bool) bool) error { + return c.GetUsageStatisticsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetUsageStatisticsPagesWithContext same as GetUsageStatisticsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *GuardDuty) GetUsageStatisticsPagesWithContext(ctx aws.Context, input *GetUsageStatisticsInput, fn func(*GetUsageStatisticsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetUsageStatisticsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetUsageStatisticsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetUsageStatisticsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opInviteMembers = "InviteMembers" // InviteMembersRequest generates a "aws/request.Request" representing the @@ -3514,8 +3752,8 @@ func (c *GuardDuty) ListMembersRequest(input *ListMembersInput) (req *request.Re // ListMembers API operation for Amazon GuardDuty. // -// Lists details about associated member accounts for the current GuardDuty -// master account. +// Lists details about all member accounts for the current GuardDuty master +// 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 @@ -3655,7 +3893,7 @@ func (c *GuardDuty) ListOrganizationAdminAccountsRequest(input *ListOrganization // ListOrganizationAdminAccounts API operation for Amazon GuardDuty. // -// Lists the accounts configured as AWS Organization delegated administrators. +// Lists the accounts configured as GuardDuty delegated administrators. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4859,6 +5097,88 @@ func (c *GuardDuty) UpdateIPSetWithContext(ctx aws.Context, input *UpdateIPSetIn return out, req.Send() } +const opUpdateMemberDetectors = "UpdateMemberDetectors" + +// UpdateMemberDetectorsRequest generates a "aws/request.Request" representing the +// client's request for the UpdateMemberDetectors operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateMemberDetectors for more information on using the UpdateMemberDetectors +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateMemberDetectorsRequest method. +// req, resp := client.UpdateMemberDetectorsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/guardduty-2017-11-28/UpdateMemberDetectors +func (c *GuardDuty) UpdateMemberDetectorsRequest(input *UpdateMemberDetectorsInput) (req *request.Request, output *UpdateMemberDetectorsOutput) { + op := &request.Operation{ + Name: opUpdateMemberDetectors, + HTTPMethod: "POST", + HTTPPath: "/detector/{detectorId}/member/detector/update", + } + + if input == nil { + input = &UpdateMemberDetectorsInput{} + } + + output = &UpdateMemberDetectorsOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateMemberDetectors API operation for Amazon GuardDuty. +// +// Contains information on member accounts to be updated. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon GuardDuty's +// API operation UpdateMemberDetectors for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// A bad request exception object. +// +// * InternalServerErrorException +// An internal server error exception object. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/guardduty-2017-11-28/UpdateMemberDetectors +func (c *GuardDuty) UpdateMemberDetectors(input *UpdateMemberDetectorsInput) (*UpdateMemberDetectorsOutput, error) { + req, out := c.UpdateMemberDetectorsRequest(input) + return out, req.Send() +} + +// UpdateMemberDetectorsWithContext is the same as UpdateMemberDetectors with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateMemberDetectors for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *GuardDuty) UpdateMemberDetectorsWithContext(ctx aws.Context, input *UpdateMemberDetectorsInput, opts ...request.Option) (*UpdateMemberDetectorsOutput, error) { + req, out := c.UpdateMemberDetectorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opUpdateOrganizationConfiguration = "UpdateOrganizationConfiguration" // UpdateOrganizationConfigurationRequest generates a "aws/request.Request" representing the @@ -5191,6 +5511,41 @@ func (s AcceptInvitationOutput) GoString() string { return s.String() } +// Contains information on the current access control policies for the bucket. +type AccessControlList struct { + _ struct{} `type:"structure"` + + // A value that indicates whether public read access for the bucket is enabled + // through an Access Control List (ACL). + AllowsPublicReadAccess *bool `locationName:"allowsPublicReadAccess" type:"boolean"` + + // A value that indicates whether public write access for the bucket is enabled + // through an Access Control List (ACL). + AllowsPublicWriteAccess *bool `locationName:"allowsPublicWriteAccess" type:"boolean"` +} + +// String returns the string representation +func (s AccessControlList) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccessControlList) GoString() string { + return s.String() +} + +// SetAllowsPublicReadAccess sets the AllowsPublicReadAccess field's value. +func (s *AccessControlList) SetAllowsPublicReadAccess(v bool) *AccessControlList { + s.AllowsPublicReadAccess = &v + return s +} + +// SetAllowsPublicWriteAccess sets the AllowsPublicWriteAccess field's value. +func (s *AccessControlList) SetAllowsPublicWriteAccess(v bool) *AccessControlList { + s.AllowsPublicWriteAccess = &v + return s +} + // Contains information about the access keys. type AccessKeyDetails struct { _ struct{} `type:"structure"` @@ -5301,14 +5656,38 @@ func (s *AccountDetail) SetEmail(v string) *AccountDetail { return s } -// Contains information about actions. -type Action struct { +// Contains information about the account level permissions on the S3 bucket. +type AccountLevelPermissions struct { _ struct{} `type:"structure"` - // The GuardDuty finding activity type. - ActionType *string `locationName:"actionType" type:"string"` + // Describes the S3 Block Public Access settings of the bucket's parent account. + BlockPublicAccess *BlockPublicAccess `locationName:"blockPublicAccess" type:"structure"` +} - // Information about the AWS_API_CALL action described in this finding. +// String returns the string representation +func (s AccountLevelPermissions) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccountLevelPermissions) GoString() string { + return s.String() +} + +// SetBlockPublicAccess sets the BlockPublicAccess field's value. +func (s *AccountLevelPermissions) SetBlockPublicAccess(v *BlockPublicAccess) *AccountLevelPermissions { + s.BlockPublicAccess = v + return s +} + +// Contains information about actions. +type Action struct { + _ struct{} `type:"structure"` + + // The GuardDuty finding activity type. + ActionType *string `locationName:"actionType" type:"string"` + + // Information about the AWS_API_CALL action described in this finding. AwsApiCallAction *AwsApiCallAction `locationName:"awsApiCallAction" type:"structure"` // Information about the DNS_REQUEST action described in this finding. @@ -5585,6 +5964,137 @@ func (s *BadRequestException) RequestID() string { return s.RespMetadata.RequestID } +// Contains information on how the bucker owner's S3 Block Public Access settings +// are being applied to the S3 bucket. See S3 Block Public Access (https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html) +// for more information. +type BlockPublicAccess struct { + _ struct{} `type:"structure"` + + // Indicates if S3 Block Public Access is set to BlockPublicAcls. + BlockPublicAcls *bool `locationName:"blockPublicAcls" type:"boolean"` + + // Indicates if S3 Block Public Access is set to BlockPublicPolicy. + BlockPublicPolicy *bool `locationName:"blockPublicPolicy" type:"boolean"` + + // Indicates if S3 Block Public Access is set to IgnorePublicAcls. + IgnorePublicAcls *bool `locationName:"ignorePublicAcls" type:"boolean"` + + // Indicates if S3 Block Public Access is set to RestrictPublicBuckets. + RestrictPublicBuckets *bool `locationName:"restrictPublicBuckets" type:"boolean"` +} + +// String returns the string representation +func (s BlockPublicAccess) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BlockPublicAccess) GoString() string { + return s.String() +} + +// SetBlockPublicAcls sets the BlockPublicAcls field's value. +func (s *BlockPublicAccess) SetBlockPublicAcls(v bool) *BlockPublicAccess { + s.BlockPublicAcls = &v + return s +} + +// SetBlockPublicPolicy sets the BlockPublicPolicy field's value. +func (s *BlockPublicAccess) SetBlockPublicPolicy(v bool) *BlockPublicAccess { + s.BlockPublicPolicy = &v + return s +} + +// SetIgnorePublicAcls sets the IgnorePublicAcls field's value. +func (s *BlockPublicAccess) SetIgnorePublicAcls(v bool) *BlockPublicAccess { + s.IgnorePublicAcls = &v + return s +} + +// SetRestrictPublicBuckets sets the RestrictPublicBuckets field's value. +func (s *BlockPublicAccess) SetRestrictPublicBuckets(v bool) *BlockPublicAccess { + s.RestrictPublicBuckets = &v + return s +} + +// Contains information about the bucket level permissions for the S3 bucket. +type BucketLevelPermissions struct { + _ struct{} `type:"structure"` + + // Contains information on how Access Control Policies are applied to the bucket. + AccessControlList *AccessControlList `locationName:"accessControlList" type:"structure"` + + // Contains information on which account level S3 Block Public Access settings + // are applied to the S3 bucket. + BlockPublicAccess *BlockPublicAccess `locationName:"blockPublicAccess" type:"structure"` + + // Contains information on the bucket policies for the S3 bucket. + BucketPolicy *BucketPolicy `locationName:"bucketPolicy" type:"structure"` +} + +// String returns the string representation +func (s BucketLevelPermissions) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BucketLevelPermissions) GoString() string { + return s.String() +} + +// SetAccessControlList sets the AccessControlList field's value. +func (s *BucketLevelPermissions) SetAccessControlList(v *AccessControlList) *BucketLevelPermissions { + s.AccessControlList = v + return s +} + +// SetBlockPublicAccess sets the BlockPublicAccess field's value. +func (s *BucketLevelPermissions) SetBlockPublicAccess(v *BlockPublicAccess) *BucketLevelPermissions { + s.BlockPublicAccess = v + return s +} + +// SetBucketPolicy sets the BucketPolicy field's value. +func (s *BucketLevelPermissions) SetBucketPolicy(v *BucketPolicy) *BucketLevelPermissions { + s.BucketPolicy = v + return s +} + +// Contains information on the current bucket policies for the S3 bucket. +type BucketPolicy struct { + _ struct{} `type:"structure"` + + // A value that indicates whether public read access for the bucket is enabled + // through a bucket policy. + AllowsPublicReadAccess *bool `locationName:"allowsPublicReadAccess" type:"boolean"` + + // A value that indicates whether public write access for the bucket is enabled + // through a bucket policy. + AllowsPublicWriteAccess *bool `locationName:"allowsPublicWriteAccess" type:"boolean"` +} + +// String returns the string representation +func (s BucketPolicy) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BucketPolicy) GoString() string { + return s.String() +} + +// SetAllowsPublicReadAccess sets the AllowsPublicReadAccess field's value. +func (s *BucketPolicy) SetAllowsPublicReadAccess(v bool) *BucketPolicy { + s.AllowsPublicReadAccess = &v + return s +} + +// SetAllowsPublicWriteAccess sets the AllowsPublicWriteAccess field's value. +func (s *BucketPolicy) SetAllowsPublicWriteAccess(v bool) *BucketPolicy { + s.AllowsPublicWriteAccess = &v + return s +} + // Contains information about the city associated with the IP address. type City struct { _ struct{} `type:"structure"` @@ -5609,6 +6119,33 @@ func (s *City) SetCityName(v string) *City { return s } +// Contains information on the status of CloudTrail as a data source for the +// detector. +type CloudTrailConfigurationResult struct { + _ struct{} `type:"structure"` + + // Describes whether CloudTrail is enabled as a data source for the detector. + // + // Status is a required field + Status *string `locationName:"status" min:"1" type:"string" required:"true" enum:"DataSourceStatus"` +} + +// String returns the string representation +func (s CloudTrailConfigurationResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CloudTrailConfigurationResult) GoString() string { + return s.String() +} + +// SetStatus sets the Status field's value. +func (s *CloudTrailConfigurationResult) SetStatus(v string) *CloudTrailConfigurationResult { + s.Status = &v + return s +} + // Contains information about the condition. type Condition struct { _ struct{} `type:"structure"` @@ -5795,6 +6332,9 @@ type CreateDetectorInput struct { // The idempotency token for the create request. ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` + // An object that describes which data sources will be enabled for the detector. + DataSources *DataSourceConfigurations `locationName:"dataSources" type:"structure"` + // A Boolean value that specifies whether the detector is to be enabled. // // Enable is a required field @@ -5826,6 +6366,11 @@ func (s *CreateDetectorInput) Validate() error { if s.Tags != nil && len(s.Tags) < 1 { invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) } + if s.DataSources != nil { + if err := s.DataSources.Validate(); err != nil { + invalidParams.AddNested("DataSources", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -5839,6 +6384,12 @@ func (s *CreateDetectorInput) SetClientToken(v string) *CreateDetectorInput { return s } +// SetDataSources sets the DataSources field's value. +func (s *CreateDetectorInput) SetDataSources(v *DataSourceConfigurations) *CreateDetectorInput { + s.DataSources = v + return s +} + // SetEnable sets the Enable field's value. func (s *CreateDetectorInput) SetEnable(v bool) *CreateDetectorInput { s.Enable = &v @@ -5977,6 +6528,8 @@ type CreateFilterInput struct { // // * service.action.networkConnectionAction.protocol // + // * service.action.networkConnectionAction.localIpDetails.ipAddressV4 + // // * service.action.networkConnectionAction.remoteIpDetails.city.cityName // // * service.action.networkConnectionAction.remoteIpDetails.country.countryName @@ -6717,6 +7270,133 @@ func (s *CreateThreatIntelSetOutput) SetThreatIntelSetId(v string) *CreateThreat return s } +// Contains information on the status of DNS logs as a data source. +type DNSLogsConfigurationResult struct { + _ struct{} `type:"structure"` + + // Denotes whether DNS logs is enabled as a data source. + // + // Status is a required field + Status *string `locationName:"status" min:"1" type:"string" required:"true" enum:"DataSourceStatus"` +} + +// String returns the string representation +func (s DNSLogsConfigurationResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DNSLogsConfigurationResult) GoString() string { + return s.String() +} + +// SetStatus sets the Status field's value. +func (s *DNSLogsConfigurationResult) SetStatus(v string) *DNSLogsConfigurationResult { + s.Status = &v + return s +} + +// Contains information about which data sources are enabled. +type DataSourceConfigurations struct { + _ struct{} `type:"structure"` + + // Describes whether S3 data event logs are enabled as a data source. + S3Logs *S3LogsConfiguration `locationName:"s3Logs" type:"structure"` +} + +// String returns the string representation +func (s DataSourceConfigurations) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DataSourceConfigurations) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DataSourceConfigurations) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DataSourceConfigurations"} + if s.S3Logs != nil { + if err := s.S3Logs.Validate(); err != nil { + invalidParams.AddNested("S3Logs", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetS3Logs sets the S3Logs field's value. +func (s *DataSourceConfigurations) SetS3Logs(v *S3LogsConfiguration) *DataSourceConfigurations { + s.S3Logs = v + return s +} + +// Contains information on the status of data sources for the detector. +type DataSourceConfigurationsResult struct { + _ struct{} `type:"structure"` + + // An object that contains information on the status of CloudTrail as a data + // source. + // + // CloudTrail is a required field + CloudTrail *CloudTrailConfigurationResult `locationName:"cloudTrail" type:"structure" required:"true"` + + // An object that contains information on the status of DNS logs as a data source. + // + // DNSLogs is a required field + DNSLogs *DNSLogsConfigurationResult `locationName:"dnsLogs" type:"structure" required:"true"` + + // An object that contains information on the status of VPC flow logs as a data + // source. + // + // FlowLogs is a required field + FlowLogs *FlowLogsConfigurationResult `locationName:"flowLogs" type:"structure" required:"true"` + + // An object that contains information on the status of S3 Data event logs as + // a data source. + // + // S3Logs is a required field + S3Logs *S3LogsConfigurationResult `locationName:"s3Logs" type:"structure" required:"true"` +} + +// String returns the string representation +func (s DataSourceConfigurationsResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DataSourceConfigurationsResult) GoString() string { + return s.String() +} + +// SetCloudTrail sets the CloudTrail field's value. +func (s *DataSourceConfigurationsResult) SetCloudTrail(v *CloudTrailConfigurationResult) *DataSourceConfigurationsResult { + s.CloudTrail = v + return s +} + +// SetDNSLogs sets the DNSLogs field's value. +func (s *DataSourceConfigurationsResult) SetDNSLogs(v *DNSLogsConfigurationResult) *DataSourceConfigurationsResult { + s.DNSLogs = v + return s +} + +// SetFlowLogs sets the FlowLogs field's value. +func (s *DataSourceConfigurationsResult) SetFlowLogs(v *FlowLogsConfigurationResult) *DataSourceConfigurationsResult { + s.FlowLogs = v + return s +} + +// SetS3Logs sets the S3Logs field's value. +func (s *DataSourceConfigurationsResult) SetS3Logs(v *S3LogsConfigurationResult) *DataSourceConfigurationsResult { + s.S3Logs = v + return s +} + type DeclineInvitationsInput struct { _ struct{} `type:"structure"` @@ -6785,6 +7465,42 @@ func (s *DeclineInvitationsOutput) SetUnprocessedAccounts(v []*UnprocessedAccoun return s } +// Contains information on the server side encryption method used in the S3 +// bucket. See S3 Server-Side Encryption (https://docs.aws.amazon.com/AmazonS3/atest/dev/serv-side-encryption.html) +// for more information. +type DefaultServerSideEncryption struct { + _ struct{} `type:"structure"` + + // The type of encryption used for objects within the S3 bucket. + EncryptionType *string `locationName:"encryptionType" type:"string"` + + // The Amazon Resource Name (ARN) of the KMS encryption key. Only available + // if the bucket EncryptionType is aws:kms. + KmsMasterKeyArn *string `locationName:"kmsMasterKeyArn" type:"string"` +} + +// String returns the string representation +func (s DefaultServerSideEncryption) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DefaultServerSideEncryption) GoString() string { + return s.String() +} + +// SetEncryptionType sets the EncryptionType field's value. +func (s *DefaultServerSideEncryption) SetEncryptionType(v string) *DefaultServerSideEncryption { + s.EncryptionType = &v + return s +} + +// SetKmsMasterKeyArn sets the KmsMasterKeyArn field's value. +func (s *DefaultServerSideEncryption) SetKmsMasterKeyArn(v string) *DefaultServerSideEncryption { + s.KmsMasterKeyArn = &v + return s +} + type DeleteDetectorInput struct { _ struct{} `type:"structure"` @@ -7332,6 +8048,10 @@ type DescribeOrganizationConfigurationOutput struct { // AutoEnable is a required field AutoEnable *bool `locationName:"autoEnable" type:"boolean" required:"true"` + // An object that describes which data sources are enabled automatically for + // member accounts. + DataSources *OrganizationDataSourceConfigurationsResult `locationName:"dataSources" type:"structure"` + // Indicates whether the maximum number of allowed member accounts are already // associated with the delegated administrator master account. // @@ -7355,6 +8075,12 @@ func (s *DescribeOrganizationConfigurationOutput) SetAutoEnable(v bool) *Describ return s } +// SetDataSources sets the DataSources field's value. +func (s *DescribeOrganizationConfigurationOutput) SetDataSources(v *OrganizationDataSourceConfigurationsResult) *DescribeOrganizationConfigurationOutput { + s.DataSources = v + return s +} + // SetMemberAccountLimitReached sets the MemberAccountLimitReached field's value. func (s *DescribeOrganizationConfigurationOutput) SetMemberAccountLimitReached(v bool) *DescribeOrganizationConfigurationOutput { s.MemberAccountLimitReached = &v @@ -7579,7 +8305,7 @@ func (s *DestinationProperties) SetKmsKeyArn(v string) *DestinationProperties { type DisableOrganizationAdminAccountInput struct { _ struct{} `type:"structure"` - // The AWS Account ID for the Organizations account to be disabled as a GuardDuty + // The AWS Account ID for the organizations account to be disabled as a GuardDuty // delegated administrator. // // AdminAccountId is a required field @@ -7821,7 +8547,7 @@ func (s *DomainDetails) SetDomain(v string) *DomainDetails { type EnableOrganizationAdminAccountInput struct { _ struct{} `type:"structure"` - // The AWS Account ID for the Organizations account to be enabled as a GuardDuty + // The AWS Account ID for the organization account to be enabled as a GuardDuty // delegated administrator. // // AdminAccountId is a required field @@ -8116,6 +8842,32 @@ func (s *FindingStatistics) SetCountBySeverity(v map[string]*int64) *FindingStat return s } +// Contains information on the status of VPC flow logs as a data source. +type FlowLogsConfigurationResult struct { + _ struct{} `type:"structure"` + + // Denotes whether VPC flow logs is enabled as a data source. + // + // Status is a required field + Status *string `locationName:"status" min:"1" type:"string" required:"true" enum:"DataSourceStatus"` +} + +// String returns the string representation +func (s FlowLogsConfigurationResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FlowLogsConfigurationResult) GoString() string { + return s.String() +} + +// SetStatus sets the Status field's value. +func (s *FlowLogsConfigurationResult) SetStatus(v string) *FlowLogsConfigurationResult { + s.Status = &v + return s +} + // Contains information about the location of the remote IP address. type GeoLocation struct { _ struct{} `type:"structure"` @@ -8196,6 +8948,9 @@ type GetDetectorOutput struct { // The timestamp of when the detector was created. CreatedAt *string `locationName:"createdAt" type:"string"` + // An object that describes which data sources are enabled for the detector. + DataSources *DataSourceConfigurationsResult `locationName:"dataSources" type:"structure"` + // The publishing frequency of the finding. FindingPublishingFrequency *string `locationName:"findingPublishingFrequency" type:"string" enum:"FindingPublishingFrequency"` @@ -8232,6 +8987,12 @@ func (s *GetDetectorOutput) SetCreatedAt(v string) *GetDetectorOutput { return s } +// SetDataSources sets the DataSources field's value. +func (s *GetDetectorOutput) SetDataSources(v *DataSourceConfigurationsResult) *GetDetectorOutput { + s.DataSources = v + return s +} + // SetFindingPublishingFrequency sets the FindingPublishingFrequency field's value. func (s *GetDetectorOutput) SetFindingPublishingFrequency(v string) *GetDetectorOutput { s.FindingPublishingFrequency = &v @@ -8804,34 +9565,33 @@ func (s *GetMasterAccountOutput) SetMaster(v *Master) *GetMasterAccountOutput { return s } -type GetMembersInput struct { +type GetMemberDetectorsInput struct { _ struct{} `type:"structure"` - // A list of account IDs of the GuardDuty member accounts that you want to describe. + // The account ID of the member account. // // AccountIds is a required field AccountIds []*string `locationName:"accountIds" min:"1" type:"list" required:"true"` - // The unique ID of the detector of the GuardDuty account whose members you - // want to retrieve. + // The detector ID for the master account. // // DetectorId is a required field DetectorId *string `location:"uri" locationName:"detectorId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s GetMembersInput) String() string { +func (s GetMemberDetectorsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetMembersInput) GoString() string { +func (s GetMemberDetectorsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetMembersInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetMembersInput"} +func (s *GetMemberDetectorsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetMemberDetectorsInput"} if s.AccountIds == nil { invalidParams.Add(request.NewErrParamRequired("AccountIds")) } @@ -8852,45 +9612,141 @@ func (s *GetMembersInput) Validate() error { } // SetAccountIds sets the AccountIds field's value. -func (s *GetMembersInput) SetAccountIds(v []*string) *GetMembersInput { +func (s *GetMemberDetectorsInput) SetAccountIds(v []*string) *GetMemberDetectorsInput { s.AccountIds = v return s } // SetDetectorId sets the DetectorId field's value. -func (s *GetMembersInput) SetDetectorId(v string) *GetMembersInput { +func (s *GetMemberDetectorsInput) SetDetectorId(v string) *GetMemberDetectorsInput { s.DetectorId = &v return s } -type GetMembersOutput struct { +type GetMemberDetectorsOutput struct { _ struct{} `type:"structure"` - // A list of members. + // An object that describes which data sources are enabled for a member account. // - // Members is a required field - Members []*Member `locationName:"members" type:"list" required:"true"` + // MemberDataSourceConfigurations is a required field + MemberDataSourceConfigurations []*MemberDataSourceConfiguration `locationName:"members" min:"1" type:"list" required:"true"` - // A list of objects that contain the unprocessed account and a result string - // that explains why it was unprocessed. + // A list of member account IDs that were unable to be processed along with + // an explanation for why they were not processed. // // UnprocessedAccounts is a required field UnprocessedAccounts []*UnprocessedAccount `locationName:"unprocessedAccounts" type:"list" required:"true"` } // String returns the string representation -func (s GetMembersOutput) String() string { +func (s GetMemberDetectorsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetMembersOutput) GoString() string { +func (s GetMemberDetectorsOutput) GoString() string { return s.String() } -// SetMembers sets the Members field's value. -func (s *GetMembersOutput) SetMembers(v []*Member) *GetMembersOutput { - s.Members = v +// SetMemberDataSourceConfigurations sets the MemberDataSourceConfigurations field's value. +func (s *GetMemberDetectorsOutput) SetMemberDataSourceConfigurations(v []*MemberDataSourceConfiguration) *GetMemberDetectorsOutput { + s.MemberDataSourceConfigurations = v + return s +} + +// SetUnprocessedAccounts sets the UnprocessedAccounts field's value. +func (s *GetMemberDetectorsOutput) SetUnprocessedAccounts(v []*UnprocessedAccount) *GetMemberDetectorsOutput { + s.UnprocessedAccounts = v + return s +} + +type GetMembersInput struct { + _ struct{} `type:"structure"` + + // A list of account IDs of the GuardDuty member accounts that you want to describe. + // + // AccountIds is a required field + AccountIds []*string `locationName:"accountIds" min:"1" type:"list" required:"true"` + + // The unique ID of the detector of the GuardDuty account whose members you + // want to retrieve. + // + // DetectorId is a required field + DetectorId *string `location:"uri" locationName:"detectorId" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetMembersInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetMembersInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetMembersInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetMembersInput"} + if s.AccountIds == nil { + invalidParams.Add(request.NewErrParamRequired("AccountIds")) + } + if s.AccountIds != nil && len(s.AccountIds) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AccountIds", 1)) + } + if s.DetectorId == nil { + invalidParams.Add(request.NewErrParamRequired("DetectorId")) + } + if s.DetectorId != nil && len(*s.DetectorId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DetectorId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAccountIds sets the AccountIds field's value. +func (s *GetMembersInput) SetAccountIds(v []*string) *GetMembersInput { + s.AccountIds = v + return s +} + +// SetDetectorId sets the DetectorId field's value. +func (s *GetMembersInput) SetDetectorId(v string) *GetMembersInput { + s.DetectorId = &v + return s +} + +type GetMembersOutput struct { + _ struct{} `type:"structure"` + + // A list of members. + // + // Members is a required field + Members []*Member `locationName:"members" type:"list" required:"true"` + + // A list of objects that contain the unprocessed account and a result string + // that explains why it was unprocessed. + // + // UnprocessedAccounts is a required field + UnprocessedAccounts []*UnprocessedAccount `locationName:"unprocessedAccounts" type:"list" required:"true"` +} + +// String returns the string representation +func (s GetMembersOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetMembersOutput) GoString() string { + return s.String() +} + +// SetMembers sets the Members field's value. +func (s *GetMembersOutput) SetMembers(v []*Member) *GetMembersOutput { + s.Members = v return s } @@ -9026,6 +9882,149 @@ func (s *GetThreatIntelSetOutput) SetTags(v map[string]*string) *GetThreatIntelS return s } +type GetUsageStatisticsInput struct { + _ struct{} `type:"structure"` + + // The ID of the detector that specifies the GuardDuty service whose usage statistics + // you want to retrieve. + // + // DetectorId is a required field + DetectorId *string `location:"uri" locationName:"detectorId" min:"1" type:"string" required:"true"` + + // The maximum number of results to return in the response. + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` + + // A token to use for paginating results that are returned in the response. + // Set the value of this parameter to null for the first request to a list action. + // For subsequent calls, use the NextToken value returned from the previous + // request to continue listing results after the first page. + NextToken *string `locationName:"nextToken" type:"string"` + + // The currency unit you would like to view your usage statistics in. Current + // valid values are USD. + Unit *string `locationName:"unit" type:"string"` + + // Represents the criteria used for querying usage. + // + // UsageCriteria is a required field + UsageCriteria *UsageCriteria `locationName:"usageCriteria" type:"structure" required:"true"` + + // The type of usage statistics to retrieve. + // + // UsageStatisticType is a required field + UsageStatisticType *string `locationName:"usageStatisticsType" type:"string" required:"true" enum:"UsageStatisticType"` +} + +// String returns the string representation +func (s GetUsageStatisticsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetUsageStatisticsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetUsageStatisticsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetUsageStatisticsInput"} + if s.DetectorId == nil { + invalidParams.Add(request.NewErrParamRequired("DetectorId")) + } + if s.DetectorId != nil && len(*s.DetectorId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DetectorId", 1)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.UsageCriteria == nil { + invalidParams.Add(request.NewErrParamRequired("UsageCriteria")) + } + if s.UsageStatisticType == nil { + invalidParams.Add(request.NewErrParamRequired("UsageStatisticType")) + } + if s.UsageCriteria != nil { + if err := s.UsageCriteria.Validate(); err != nil { + invalidParams.AddNested("UsageCriteria", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDetectorId sets the DetectorId field's value. +func (s *GetUsageStatisticsInput) SetDetectorId(v string) *GetUsageStatisticsInput { + s.DetectorId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetUsageStatisticsInput) SetMaxResults(v int64) *GetUsageStatisticsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetUsageStatisticsInput) SetNextToken(v string) *GetUsageStatisticsInput { + s.NextToken = &v + return s +} + +// SetUnit sets the Unit field's value. +func (s *GetUsageStatisticsInput) SetUnit(v string) *GetUsageStatisticsInput { + s.Unit = &v + return s +} + +// SetUsageCriteria sets the UsageCriteria field's value. +func (s *GetUsageStatisticsInput) SetUsageCriteria(v *UsageCriteria) *GetUsageStatisticsInput { + s.UsageCriteria = v + return s +} + +// SetUsageStatisticType sets the UsageStatisticType field's value. +func (s *GetUsageStatisticsInput) SetUsageStatisticType(v string) *GetUsageStatisticsInput { + s.UsageStatisticType = &v + return s +} + +type GetUsageStatisticsOutput struct { + _ struct{} `type:"structure"` + + // The pagination parameter to be used on the next list operation to retrieve + // more items. + NextToken *string `locationName:"nextToken" type:"string"` + + // The usage statistics object. If a UsageStatisticType was provided, the objects + // representing other types will be null. + UsageStatistics *UsageStatistics `locationName:"usageStatistics" type:"structure"` +} + +// String returns the string representation +func (s GetUsageStatisticsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetUsageStatisticsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *GetUsageStatisticsOutput) SetNextToken(v string) *GetUsageStatisticsOutput { + s.NextToken = &v + return s +} + +// SetUsageStatistics sets the UsageStatistics field's value. +func (s *GetUsageStatisticsOutput) SetUsageStatistics(v *UsageStatistics) *GetUsageStatisticsOutput { + s.UsageStatistics = v + return s +} + // Contains information about the EC2 instance profile. type IamInstanceProfile struct { _ struct{} `type:"structure"` @@ -9320,10 +10319,10 @@ type InviteMembersInput struct { DetectorId *string `location:"uri" locationName:"detectorId" min:"1" type:"string" required:"true"` // A Boolean value that specifies whether you want to disable email notification - // to the accounts that you’re inviting to GuardDuty as members. + // to the accounts that you are inviting to GuardDuty as members. DisableEmailNotification *bool `locationName:"disableEmailNotification" type:"boolean"` - // The invitation message that you want to send to the accounts that you’re + // The invitation message that you want to send to the accounts that you're // inviting to GuardDuty as members. Message *string `locationName:"message" type:"string"` } @@ -10017,10 +11016,8 @@ type ListMembersInput struct { // from the previous response to continue listing data. NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` - // Specifies what member accounts the response includes based on their relationship - // status with the master account. The default value is "true". If set to "false" - // the response includes all existing member accounts (including members who - // haven't been invited yet or have been disassociated). + // Specifies whether to only return associated members or to return all members + // (including members who haven't been invited yet or have been disassociated). OnlyAssociated *string `location:"querystring" locationName:"onlyAssociated" type:"string"` } @@ -10656,6 +11653,43 @@ func (s *Member) SetUpdatedAt(v string) *Member { return s } +// Contains information on which data sources are enabled for a member account. +type MemberDataSourceConfiguration struct { + _ struct{} `type:"structure"` + + // The account ID for the member account. + // + // AccountId is a required field + AccountId *string `locationName:"accountId" min:"12" type:"string" required:"true"` + + // Contains information on the status of data sources for the account. + // + // DataSources is a required field + DataSources *DataSourceConfigurationsResult `locationName:"dataSources" type:"structure" required:"true"` +} + +// String returns the string representation +func (s MemberDataSourceConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s MemberDataSourceConfiguration) GoString() string { + return s.String() +} + +// SetAccountId sets the AccountId field's value. +func (s *MemberDataSourceConfiguration) SetAccountId(v string) *MemberDataSourceConfiguration { + s.AccountId = &v + return s +} + +// SetDataSources sets the DataSources field's value. +func (s *MemberDataSourceConfiguration) SetDataSources(v *DataSourceConfigurationsResult) *MemberDataSourceConfiguration { + s.DataSources = v + return s +} + // Contains information about the NETWORK_CONNECTION action described in the // finding. type NetworkConnectionAction struct { @@ -10892,56 +11926,250 @@ func (s *Organization) SetOrg(v string) *Organization { return s } -// Contains information about the PORT_PROBE action described in the finding. -type PortProbeAction struct { +// An object that contains information on which data sources will be configured +// to be automatically enabled for new members within the organization. +type OrganizationDataSourceConfigurations struct { _ struct{} `type:"structure"` - // Indicates whether EC2 blocked the port probe to the instance, such as with - // an ACL. - Blocked *bool `locationName:"blocked" type:"boolean"` - - // A list of objects related to port probe details. - PortProbeDetails []*PortProbeDetail `locationName:"portProbeDetails" type:"list"` + // Describes whether S3 data event logs are enabled for new members of the organization. + S3Logs *OrganizationS3LogsConfiguration `locationName:"s3Logs" type:"structure"` } // String returns the string representation -func (s PortProbeAction) String() string { +func (s OrganizationDataSourceConfigurations) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PortProbeAction) GoString() string { +func (s OrganizationDataSourceConfigurations) GoString() string { return s.String() } -// SetBlocked sets the Blocked field's value. -func (s *PortProbeAction) SetBlocked(v bool) *PortProbeAction { - s.Blocked = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *OrganizationDataSourceConfigurations) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OrganizationDataSourceConfigurations"} + if s.S3Logs != nil { + if err := s.S3Logs.Validate(); err != nil { + invalidParams.AddNested("S3Logs", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetPortProbeDetails sets the PortProbeDetails field's value. -func (s *PortProbeAction) SetPortProbeDetails(v []*PortProbeDetail) *PortProbeAction { - s.PortProbeDetails = v +// SetS3Logs sets the S3Logs field's value. +func (s *OrganizationDataSourceConfigurations) SetS3Logs(v *OrganizationS3LogsConfiguration) *OrganizationDataSourceConfigurations { + s.S3Logs = v return s } -// Contains information about the port probe details. -type PortProbeDetail struct { +// An object that contains information on which data sources are automatically +// enabled for new members within the organization. +type OrganizationDataSourceConfigurationsResult struct { _ struct{} `type:"structure"` - // The local IP information of the connection. - LocalIpDetails *LocalIpDetails `locationName:"localIpDetails" type:"structure"` - - // The local port information of the connection. - LocalPortDetails *LocalPortDetails `locationName:"localPortDetails" type:"structure"` - - // The remote IP information of the connection. - RemoteIpDetails *RemoteIpDetails `locationName:"remoteIpDetails" type:"structure"` + // Describes whether S3 data event logs are enabled as a data source. + // + // S3Logs is a required field + S3Logs *OrganizationS3LogsConfigurationResult `locationName:"s3Logs" type:"structure" required:"true"` } // String returns the string representation -func (s PortProbeDetail) String() string { +func (s OrganizationDataSourceConfigurationsResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OrganizationDataSourceConfigurationsResult) GoString() string { + return s.String() +} + +// SetS3Logs sets the S3Logs field's value. +func (s *OrganizationDataSourceConfigurationsResult) SetS3Logs(v *OrganizationS3LogsConfigurationResult) *OrganizationDataSourceConfigurationsResult { + s.S3Logs = v + return s +} + +// Describes whether S3 data event logs will be automatically enabled for new +// members of the organization. +type OrganizationS3LogsConfiguration struct { + _ struct{} `type:"structure"` + + // A value that contains information on whether S3 data event logs will be enabled + // automatically as a data source for the organization. + // + // AutoEnable is a required field + AutoEnable *bool `locationName:"autoEnable" type:"boolean" required:"true"` +} + +// String returns the string representation +func (s OrganizationS3LogsConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OrganizationS3LogsConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *OrganizationS3LogsConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OrganizationS3LogsConfiguration"} + if s.AutoEnable == nil { + invalidParams.Add(request.NewErrParamRequired("AutoEnable")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAutoEnable sets the AutoEnable field's value. +func (s *OrganizationS3LogsConfiguration) SetAutoEnable(v bool) *OrganizationS3LogsConfiguration { + s.AutoEnable = &v + return s +} + +// The current configuration of S3 data event logs as a data source for the +// organization. +type OrganizationS3LogsConfigurationResult struct { + _ struct{} `type:"structure"` + + // A value that describes whether S3 data event logs are automatically enabled + // for new members of the organization. + // + // AutoEnable is a required field + AutoEnable *bool `locationName:"autoEnable" type:"boolean" required:"true"` +} + +// String returns the string representation +func (s OrganizationS3LogsConfigurationResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OrganizationS3LogsConfigurationResult) GoString() string { + return s.String() +} + +// SetAutoEnable sets the AutoEnable field's value. +func (s *OrganizationS3LogsConfigurationResult) SetAutoEnable(v bool) *OrganizationS3LogsConfigurationResult { + s.AutoEnable = &v + return s +} + +// Contains information on the owner of the bucket. +type Owner struct { + _ struct{} `type:"structure"` + + // The canonical user ID of the bucket owner. For information about locating + // your canonical user ID see Finding Your Account Canonical User ID. (https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html#FindingCanonicalId) + Id *string `locationName:"id" type:"string"` +} + +// String returns the string representation +func (s Owner) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Owner) GoString() string { + return s.String() +} + +// SetId sets the Id field's value. +func (s *Owner) SetId(v string) *Owner { + s.Id = &v + return s +} + +// Contains information about how permissions are configured for the S3 bucket. +type PermissionConfiguration struct { + _ struct{} `type:"structure"` + + // Contains information about the account level permissions on the S3 bucket. + AccountLevelPermissions *AccountLevelPermissions `locationName:"accountLevelPermissions" type:"structure"` + + // Contains information about the bucket level permissions for the S3 bucket. + BucketLevelPermissions *BucketLevelPermissions `locationName:"bucketLevelPermissions" type:"structure"` +} + +// String returns the string representation +func (s PermissionConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PermissionConfiguration) GoString() string { + return s.String() +} + +// SetAccountLevelPermissions sets the AccountLevelPermissions field's value. +func (s *PermissionConfiguration) SetAccountLevelPermissions(v *AccountLevelPermissions) *PermissionConfiguration { + s.AccountLevelPermissions = v + return s +} + +// SetBucketLevelPermissions sets the BucketLevelPermissions field's value. +func (s *PermissionConfiguration) SetBucketLevelPermissions(v *BucketLevelPermissions) *PermissionConfiguration { + s.BucketLevelPermissions = v + return s +} + +// Contains information about the PORT_PROBE action described in the finding. +type PortProbeAction struct { + _ struct{} `type:"structure"` + + // Indicates whether EC2 blocked the port probe to the instance, such as with + // an ACL. + Blocked *bool `locationName:"blocked" type:"boolean"` + + // A list of objects related to port probe details. + PortProbeDetails []*PortProbeDetail `locationName:"portProbeDetails" type:"list"` +} + +// String returns the string representation +func (s PortProbeAction) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PortProbeAction) GoString() string { + return s.String() +} + +// SetBlocked sets the Blocked field's value. +func (s *PortProbeAction) SetBlocked(v bool) *PortProbeAction { + s.Blocked = &v + return s +} + +// SetPortProbeDetails sets the PortProbeDetails field's value. +func (s *PortProbeAction) SetPortProbeDetails(v []*PortProbeDetail) *PortProbeAction { + s.PortProbeDetails = v + return s +} + +// Contains information about the port probe details. +type PortProbeDetail struct { + _ struct{} `type:"structure"` + + // The local IP information of the connection. + LocalIpDetails *LocalIpDetails `locationName:"localIpDetails" type:"structure"` + + // The local port information of the connection. + LocalPortDetails *LocalPortDetails `locationName:"localPortDetails" type:"structure"` + + // The remote IP information of the connection. + RemoteIpDetails *RemoteIpDetails `locationName:"remoteIpDetails" type:"structure"` +} + +// String returns the string representation +func (s PortProbeDetail) String() string { return awsutil.Prettify(s) } @@ -11034,6 +12262,40 @@ func (s *ProductCode) SetProductType(v string) *ProductCode { return s } +// Describes the public access policies that apply to the S3 bucket. +type PublicAccess struct { + _ struct{} `type:"structure"` + + // Describes the effective permission on this bucket after factoring all attached + // policies. + EffectivePermission *string `locationName:"effectivePermission" type:"string"` + + // Contains information about how permissions are configured for the S3 bucket. + PermissionConfiguration *PermissionConfiguration `locationName:"permissionConfiguration" type:"structure"` +} + +// String returns the string representation +func (s PublicAccess) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PublicAccess) GoString() string { + return s.String() +} + +// SetEffectivePermission sets the EffectivePermission field's value. +func (s *PublicAccess) SetEffectivePermission(v string) *PublicAccess { + s.EffectivePermission = &v + return s +} + +// SetPermissionConfiguration sets the PermissionConfiguration field's value. +func (s *PublicAccess) SetPermissionConfiguration(v *PermissionConfiguration) *PublicAccess { + s.PermissionConfiguration = v + return s +} + // Contains information about the remote IP address of the connection. type RemoteIpDetails struct { _ struct{} `type:"structure"` @@ -11142,6 +12404,9 @@ type Resource struct { // The type of AWS resource. ResourceType *string `locationName:"resourceType" type:"string"` + + // Contains information on the S3 bucket. + S3BucketDetails []*S3BucketDetail `locationName:"s3BucketDetails" type:"list"` } // String returns the string representation @@ -11172,6 +12437,165 @@ func (s *Resource) SetResourceType(v string) *Resource { return s } +// SetS3BucketDetails sets the S3BucketDetails field's value. +func (s *Resource) SetS3BucketDetails(v []*S3BucketDetail) *Resource { + s.S3BucketDetails = v + return s +} + +// Contains information on the S3 bucket. +type S3BucketDetail struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the S3 bucket. + Arn *string `locationName:"arn" type:"string"` + + // The date and time the bucket was created at. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + + // Describes the server side encryption method used in the S3 bucket. + DefaultServerSideEncryption *DefaultServerSideEncryption `locationName:"defaultServerSideEncryption" type:"structure"` + + // The name of the S3 bucket. + Name *string `locationName:"name" type:"string"` + + // The owner of the S3 bucket. + Owner *Owner `locationName:"owner" type:"structure"` + + // Describes the public access policies that apply to the S3 bucket. + PublicAccess *PublicAccess `locationName:"publicAccess" type:"structure"` + + // All tags attached to the S3 bucket + Tags []*Tag `locationName:"tags" type:"list"` + + // Describes whether the bucket is a source or destination bucket. + Type *string `locationName:"type" type:"string"` +} + +// String returns the string representation +func (s S3BucketDetail) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s S3BucketDetail) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *S3BucketDetail) SetArn(v string) *S3BucketDetail { + s.Arn = &v + return s +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *S3BucketDetail) SetCreatedAt(v time.Time) *S3BucketDetail { + s.CreatedAt = &v + return s +} + +// SetDefaultServerSideEncryption sets the DefaultServerSideEncryption field's value. +func (s *S3BucketDetail) SetDefaultServerSideEncryption(v *DefaultServerSideEncryption) *S3BucketDetail { + s.DefaultServerSideEncryption = v + return s +} + +// SetName sets the Name field's value. +func (s *S3BucketDetail) SetName(v string) *S3BucketDetail { + s.Name = &v + return s +} + +// SetOwner sets the Owner field's value. +func (s *S3BucketDetail) SetOwner(v *Owner) *S3BucketDetail { + s.Owner = v + return s +} + +// SetPublicAccess sets the PublicAccess field's value. +func (s *S3BucketDetail) SetPublicAccess(v *PublicAccess) *S3BucketDetail { + s.PublicAccess = v + return s +} + +// SetTags sets the Tags field's value. +func (s *S3BucketDetail) SetTags(v []*Tag) *S3BucketDetail { + s.Tags = v + return s +} + +// SetType sets the Type field's value. +func (s *S3BucketDetail) SetType(v string) *S3BucketDetail { + s.Type = &v + return s +} + +// Describes whether S3 data event logs will be enabled as a data source. +type S3LogsConfiguration struct { + _ struct{} `type:"structure"` + + // The status of S3 data event logs as a data source. + // + // Enable is a required field + Enable *bool `locationName:"enable" type:"boolean" required:"true"` +} + +// String returns the string representation +func (s S3LogsConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s S3LogsConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *S3LogsConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "S3LogsConfiguration"} + if s.Enable == nil { + invalidParams.Add(request.NewErrParamRequired("Enable")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetEnable sets the Enable field's value. +func (s *S3LogsConfiguration) SetEnable(v bool) *S3LogsConfiguration { + s.Enable = &v + return s +} + +// Describes whether S3 data event logs will be enabled as a data source. +type S3LogsConfigurationResult struct { + _ struct{} `type:"structure"` + + // A value that describes whether S3 data event logs are automatically enabled + // for new members of the organization. + // + // Status is a required field + Status *string `locationName:"status" min:"1" type:"string" required:"true" enum:"DataSourceStatus"` +} + +// String returns the string representation +func (s S3LogsConfigurationResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s S3LogsConfigurationResult) GoString() string { + return s.String() +} + +// SetStatus sets the Status field's value. +func (s *S3LogsConfigurationResult) SetStatus(v string) *S3LogsConfigurationResult { + s.Status = &v + return s +} + // Contains information about the security groups associated with the EC2 instance. type SecurityGroup struct { _ struct{} `type:"structure"` @@ -11658,6 +13082,39 @@ func (s *ThreatIntelligenceDetail) SetThreatNames(v []*string) *ThreatIntelligen return s } +// Contains the total usage with the corresponding currency unit for that value. +type Total struct { + _ struct{} `type:"structure"` + + // The total usage. + Amount *string `locationName:"amount" type:"string"` + + // The currency unit that the amount is given in. + Unit *string `locationName:"unit" type:"string"` +} + +// String returns the string representation +func (s Total) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Total) GoString() string { + return s.String() +} + +// SetAmount sets the Amount field's value. +func (s *Total) SetAmount(v string) *Total { + s.Amount = &v + return s +} + +// SetUnit sets the Unit field's value. +func (s *Total) SetUnit(v string) *Total { + s.Unit = &v + return s +} + type UnarchiveFindingsInput struct { _ struct{} `type:"structure"` @@ -11839,6 +13296,9 @@ func (s UntagResourceOutput) GoString() string { type UpdateDetectorInput struct { _ struct{} `type:"structure"` + // An object that describes which data sources will be updated. + DataSources *DataSourceConfigurations `locationName:"dataSources" type:"structure"` + // The unique ID of the detector to update. // // DetectorId is a required field @@ -11871,6 +13331,11 @@ func (s *UpdateDetectorInput) Validate() error { if s.DetectorId != nil && len(*s.DetectorId) < 1 { invalidParams.Add(request.NewErrParamMinLen("DetectorId", 1)) } + if s.DataSources != nil { + if err := s.DataSources.Validate(); err != nil { + invalidParams.AddNested("DataSources", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -11878,6 +13343,12 @@ func (s *UpdateDetectorInput) Validate() error { return nil } +// SetDataSources sets the DataSources field's value. +func (s *UpdateDetectorInput) SetDataSources(v *DataSourceConfigurations) *UpdateDetectorInput { + s.DataSources = v + return s +} + // SetDetectorId sets the DetectorId field's value. func (s *UpdateDetectorInput) SetDetectorId(v string) *UpdateDetectorInput { s.DetectorId = &v @@ -12155,35 +13626,133 @@ type UpdateIPSetInput struct { } // String returns the string representation -func (s UpdateIPSetInput) String() string { +func (s UpdateIPSetInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateIPSetInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateIPSetInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateIPSetInput"} + if s.DetectorId == nil { + invalidParams.Add(request.NewErrParamRequired("DetectorId")) + } + if s.DetectorId != nil && len(*s.DetectorId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DetectorId", 1)) + } + if s.IpSetId == nil { + invalidParams.Add(request.NewErrParamRequired("IpSetId")) + } + if s.IpSetId != nil && len(*s.IpSetId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IpSetId", 1)) + } + if s.Location != nil && len(*s.Location) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Location", 1)) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetActivate sets the Activate field's value. +func (s *UpdateIPSetInput) SetActivate(v bool) *UpdateIPSetInput { + s.Activate = &v + return s +} + +// SetDetectorId sets the DetectorId field's value. +func (s *UpdateIPSetInput) SetDetectorId(v string) *UpdateIPSetInput { + s.DetectorId = &v + return s +} + +// SetIpSetId sets the IpSetId field's value. +func (s *UpdateIPSetInput) SetIpSetId(v string) *UpdateIPSetInput { + s.IpSetId = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *UpdateIPSetInput) SetLocation(v string) *UpdateIPSetInput { + s.Location = &v + return s +} + +// SetName sets the Name field's value. +func (s *UpdateIPSetInput) SetName(v string) *UpdateIPSetInput { + s.Name = &v + return s +} + +type UpdateIPSetOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UpdateIPSetOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateIPSetOutput) GoString() string { + return s.String() +} + +type UpdateMemberDetectorsInput struct { + _ struct{} `type:"structure"` + + // A list of member account IDs to be updated. + // + // AccountIds is a required field + AccountIds []*string `locationName:"accountIds" min:"1" type:"list" required:"true"` + + // An object describes which data sources will be updated. + DataSources *DataSourceConfigurations `locationName:"dataSources" type:"structure"` + + // The detector ID of the master account. + // + // DetectorId is a required field + DetectorId *string `location:"uri" locationName:"detectorId" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s UpdateMemberDetectorsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateIPSetInput) GoString() string { +func (s UpdateMemberDetectorsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateIPSetInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateIPSetInput"} +func (s *UpdateMemberDetectorsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateMemberDetectorsInput"} + if s.AccountIds == nil { + invalidParams.Add(request.NewErrParamRequired("AccountIds")) + } + if s.AccountIds != nil && len(s.AccountIds) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AccountIds", 1)) + } if s.DetectorId == nil { invalidParams.Add(request.NewErrParamRequired("DetectorId")) } if s.DetectorId != nil && len(*s.DetectorId) < 1 { invalidParams.Add(request.NewErrParamMinLen("DetectorId", 1)) } - if s.IpSetId == nil { - invalidParams.Add(request.NewErrParamRequired("IpSetId")) - } - if s.IpSetId != nil && len(*s.IpSetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("IpSetId", 1)) - } - if s.Location != nil && len(*s.Location) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Location", 1)) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + if s.DataSources != nil { + if err := s.DataSources.Validate(); err != nil { + invalidParams.AddNested("DataSources", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -12192,50 +13761,50 @@ func (s *UpdateIPSetInput) Validate() error { return nil } -// SetActivate sets the Activate field's value. -func (s *UpdateIPSetInput) SetActivate(v bool) *UpdateIPSetInput { - s.Activate = &v - return s -} - -// SetDetectorId sets the DetectorId field's value. -func (s *UpdateIPSetInput) SetDetectorId(v string) *UpdateIPSetInput { - s.DetectorId = &v - return s -} - -// SetIpSetId sets the IpSetId field's value. -func (s *UpdateIPSetInput) SetIpSetId(v string) *UpdateIPSetInput { - s.IpSetId = &v +// SetAccountIds sets the AccountIds field's value. +func (s *UpdateMemberDetectorsInput) SetAccountIds(v []*string) *UpdateMemberDetectorsInput { + s.AccountIds = v return s } -// SetLocation sets the Location field's value. -func (s *UpdateIPSetInput) SetLocation(v string) *UpdateIPSetInput { - s.Location = &v +// SetDataSources sets the DataSources field's value. +func (s *UpdateMemberDetectorsInput) SetDataSources(v *DataSourceConfigurations) *UpdateMemberDetectorsInput { + s.DataSources = v return s } -// SetName sets the Name field's value. -func (s *UpdateIPSetInput) SetName(v string) *UpdateIPSetInput { - s.Name = &v +// SetDetectorId sets the DetectorId field's value. +func (s *UpdateMemberDetectorsInput) SetDetectorId(v string) *UpdateMemberDetectorsInput { + s.DetectorId = &v return s } -type UpdateIPSetOutput struct { +type UpdateMemberDetectorsOutput struct { _ struct{} `type:"structure"` + + // A list of member account IDs that were unable to be processed along with + // an explanation for why they were not processed. + // + // UnprocessedAccounts is a required field + UnprocessedAccounts []*UnprocessedAccount `locationName:"unprocessedAccounts" type:"list" required:"true"` } // String returns the string representation -func (s UpdateIPSetOutput) String() string { +func (s UpdateMemberDetectorsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateIPSetOutput) GoString() string { +func (s UpdateMemberDetectorsOutput) GoString() string { return s.String() } +// SetUnprocessedAccounts sets the UnprocessedAccounts field's value. +func (s *UpdateMemberDetectorsOutput) SetUnprocessedAccounts(v []*UnprocessedAccount) *UpdateMemberDetectorsOutput { + s.UnprocessedAccounts = v + return s +} + type UpdateOrganizationConfigurationInput struct { _ struct{} `type:"structure"` @@ -12244,6 +13813,9 @@ type UpdateOrganizationConfigurationInput struct { // AutoEnable is a required field AutoEnable *bool `locationName:"autoEnable" type:"boolean" required:"true"` + // An object describes which data sources will be updated. + DataSources *OrganizationDataSourceConfigurations `locationName:"dataSources" type:"structure"` + // The ID of the detector to update the delegated administrator for. // // DetectorId is a required field @@ -12272,6 +13844,11 @@ func (s *UpdateOrganizationConfigurationInput) Validate() error { if s.DetectorId != nil && len(*s.DetectorId) < 1 { invalidParams.Add(request.NewErrParamMinLen("DetectorId", 1)) } + if s.DataSources != nil { + if err := s.DataSources.Validate(); err != nil { + invalidParams.AddNested("DataSources", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -12285,6 +13862,12 @@ func (s *UpdateOrganizationConfigurationInput) SetAutoEnable(v bool) *UpdateOrga return s } +// SetDataSources sets the DataSources field's value. +func (s *UpdateOrganizationConfigurationInput) SetDataSources(v *OrganizationDataSourceConfigurations) *UpdateOrganizationConfigurationInput { + s.DataSources = v + return s +} + // SetDetectorId sets the DetectorId field's value. func (s *UpdateOrganizationConfigurationInput) SetDetectorId(v string) *UpdateOrganizationConfigurationInput { s.DetectorId = &v @@ -12495,6 +14078,219 @@ func (s UpdateThreatIntelSetOutput) GoString() string { return s.String() } +// Contains information on the total of usage based on account IDs. +type UsageAccountResult struct { + _ struct{} `type:"structure"` + + // The Account ID that generated usage. + AccountId *string `locationName:"accountId" min:"12" type:"string"` + + // Represents the total of usage for the Account ID. + Total *Total `locationName:"total" type:"structure"` +} + +// String returns the string representation +func (s UsageAccountResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UsageAccountResult) GoString() string { + return s.String() +} + +// SetAccountId sets the AccountId field's value. +func (s *UsageAccountResult) SetAccountId(v string) *UsageAccountResult { + s.AccountId = &v + return s +} + +// SetTotal sets the Total field's value. +func (s *UsageAccountResult) SetTotal(v *Total) *UsageAccountResult { + s.Total = v + return s +} + +// Contains information about the criteria used to query usage statistics. +type UsageCriteria struct { + _ struct{} `type:"structure"` + + // The account IDs to aggregate usage statistics from. + AccountIds []*string `locationName:"accountIds" min:"1" type:"list"` + + // The data sources to aggregate usage statistics from. + // + // DataSources is a required field + DataSources []*string `locationName:"dataSources" type:"list" required:"true"` + + // The resources to aggregate usage statistics from. Only accepts exact resource + // names. + Resources []*string `locationName:"resources" type:"list"` +} + +// String returns the string representation +func (s UsageCriteria) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UsageCriteria) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UsageCriteria) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UsageCriteria"} + if s.AccountIds != nil && len(s.AccountIds) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AccountIds", 1)) + } + if s.DataSources == nil { + invalidParams.Add(request.NewErrParamRequired("DataSources")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAccountIds sets the AccountIds field's value. +func (s *UsageCriteria) SetAccountIds(v []*string) *UsageCriteria { + s.AccountIds = v + return s +} + +// SetDataSources sets the DataSources field's value. +func (s *UsageCriteria) SetDataSources(v []*string) *UsageCriteria { + s.DataSources = v + return s +} + +// SetResources sets the Resources field's value. +func (s *UsageCriteria) SetResources(v []*string) *UsageCriteria { + s.Resources = v + return s +} + +// Contains information on the result of usage based on data source type. +type UsageDataSourceResult struct { + _ struct{} `type:"structure"` + + // The data source type that generated usage. + DataSource *string `locationName:"dataSource" type:"string" enum:"DataSource"` + + // Represents the total of usage for the specified data source. + Total *Total `locationName:"total" type:"structure"` +} + +// String returns the string representation +func (s UsageDataSourceResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UsageDataSourceResult) GoString() string { + return s.String() +} + +// SetDataSource sets the DataSource field's value. +func (s *UsageDataSourceResult) SetDataSource(v string) *UsageDataSourceResult { + s.DataSource = &v + return s +} + +// SetTotal sets the Total field's value. +func (s *UsageDataSourceResult) SetTotal(v *Total) *UsageDataSourceResult { + s.Total = v + return s +} + +// Contains information on the sum of usage based on an AWS resource. +type UsageResourceResult struct { + _ struct{} `type:"structure"` + + // The AWS resource that generated usage. + Resource *string `locationName:"resource" type:"string"` + + // Represents the sum total of usage for the specified resource type. + Total *Total `locationName:"total" type:"structure"` +} + +// String returns the string representation +func (s UsageResourceResult) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UsageResourceResult) GoString() string { + return s.String() +} + +// SetResource sets the Resource field's value. +func (s *UsageResourceResult) SetResource(v string) *UsageResourceResult { + s.Resource = &v + return s +} + +// SetTotal sets the Total field's value. +func (s *UsageResourceResult) SetTotal(v *Total) *UsageResourceResult { + s.Total = v + return s +} + +// Contains the result of GuardDuty usage. If a UsageStatisticType is provided +// the result for other types will be null. +type UsageStatistics struct { + _ struct{} `type:"structure"` + + // The usage statistic sum organized by account ID. + SumByAccount []*UsageAccountResult `locationName:"sumByAccount" type:"list"` + + // The usage statistic sum organized by on data source. + SumByDataSource []*UsageDataSourceResult `locationName:"sumByDataSource" type:"list"` + + // The usage statistic sum organized by resource. + SumByResource []*UsageResourceResult `locationName:"sumByResource" type:"list"` + + // Lists the top 50 resources that have generated the most GuardDuty usage, + // in order from most to least expensive. + TopResources []*UsageResourceResult `locationName:"topResources" type:"list"` +} + +// String returns the string representation +func (s UsageStatistics) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UsageStatistics) GoString() string { + return s.String() +} + +// SetSumByAccount sets the SumByAccount field's value. +func (s *UsageStatistics) SetSumByAccount(v []*UsageAccountResult) *UsageStatistics { + s.SumByAccount = v + return s +} + +// SetSumByDataSource sets the SumByDataSource field's value. +func (s *UsageStatistics) SetSumByDataSource(v []*UsageDataSourceResult) *UsageStatistics { + s.SumByDataSource = v + return s +} + +// SetSumByResource sets the SumByResource field's value. +func (s *UsageStatistics) SetSumByResource(v []*UsageResourceResult) *UsageStatistics { + s.SumByResource = v + return s +} + +// SetTopResources sets the TopResources field's value. +func (s *UsageStatistics) SetTopResources(v []*UsageResourceResult) *UsageStatistics { + s.TopResources = v + return s +} + const ( // AdminStatusEnabled is a AdminStatus enum value AdminStatusEnabled = "ENABLED" @@ -12503,11 +14299,66 @@ const ( AdminStatusDisableInProgress = "DISABLE_IN_PROGRESS" ) +// AdminStatus_Values returns all elements of the AdminStatus enum +func AdminStatus_Values() []string { + return []string{ + AdminStatusEnabled, + AdminStatusDisableInProgress, + } +} + +const ( + // DataSourceFlowLogs is a DataSource enum value + DataSourceFlowLogs = "FLOW_LOGS" + + // DataSourceCloudTrail is a DataSource enum value + DataSourceCloudTrail = "CLOUD_TRAIL" + + // DataSourceDnsLogs is a DataSource enum value + DataSourceDnsLogs = "DNS_LOGS" + + // DataSourceS3Logs is a DataSource enum value + DataSourceS3Logs = "S3_LOGS" +) + +// DataSource_Values returns all elements of the DataSource enum +func DataSource_Values() []string { + return []string{ + DataSourceFlowLogs, + DataSourceCloudTrail, + DataSourceDnsLogs, + DataSourceS3Logs, + } +} + +const ( + // DataSourceStatusEnabled is a DataSourceStatus enum value + DataSourceStatusEnabled = "ENABLED" + + // DataSourceStatusDisabled is a DataSourceStatus enum value + DataSourceStatusDisabled = "DISABLED" +) + +// DataSourceStatus_Values returns all elements of the DataSourceStatus enum +func DataSourceStatus_Values() []string { + return []string{ + DataSourceStatusEnabled, + DataSourceStatusDisabled, + } +} + const ( // DestinationTypeS3 is a DestinationType enum value DestinationTypeS3 = "S3" ) +// DestinationType_Values returns all elements of the DestinationType enum +func DestinationType_Values() []string { + return []string{ + DestinationTypeS3, + } +} + const ( // DetectorStatusEnabled is a DetectorStatus enum value DetectorStatusEnabled = "ENABLED" @@ -12516,6 +14367,14 @@ const ( DetectorStatusDisabled = "DISABLED" ) +// DetectorStatus_Values returns all elements of the DetectorStatus enum +func DetectorStatus_Values() []string { + return []string{ + DetectorStatusEnabled, + DetectorStatusDisabled, + } +} + const ( // FeedbackUseful is a Feedback enum value FeedbackUseful = "USEFUL" @@ -12524,6 +14383,14 @@ const ( FeedbackNotUseful = "NOT_USEFUL" ) +// Feedback_Values returns all elements of the Feedback enum +func Feedback_Values() []string { + return []string{ + FeedbackUseful, + FeedbackNotUseful, + } +} + const ( // FilterActionNoop is a FilterAction enum value FilterActionNoop = "NOOP" @@ -12532,6 +14399,14 @@ const ( FilterActionArchive = "ARCHIVE" ) +// FilterAction_Values returns all elements of the FilterAction enum +func FilterAction_Values() []string { + return []string{ + FilterActionNoop, + FilterActionArchive, + } +} + const ( // FindingPublishingFrequencyFifteenMinutes is a FindingPublishingFrequency enum value FindingPublishingFrequencyFifteenMinutes = "FIFTEEN_MINUTES" @@ -12543,11 +14418,27 @@ const ( FindingPublishingFrequencySixHours = "SIX_HOURS" ) +// FindingPublishingFrequency_Values returns all elements of the FindingPublishingFrequency enum +func FindingPublishingFrequency_Values() []string { + return []string{ + FindingPublishingFrequencyFifteenMinutes, + FindingPublishingFrequencyOneHour, + FindingPublishingFrequencySixHours, + } +} + const ( // FindingStatisticTypeCountBySeverity is a FindingStatisticType enum value FindingStatisticTypeCountBySeverity = "COUNT_BY_SEVERITY" ) +// FindingStatisticType_Values returns all elements of the FindingStatisticType enum +func FindingStatisticType_Values() []string { + return []string{ + FindingStatisticTypeCountBySeverity, + } +} + const ( // IpSetFormatTxt is a IpSetFormat enum value IpSetFormatTxt = "TXT" @@ -12568,6 +14459,18 @@ const ( IpSetFormatFireEye = "FIRE_EYE" ) +// IpSetFormat_Values returns all elements of the IpSetFormat enum +func IpSetFormat_Values() []string { + return []string{ + IpSetFormatTxt, + IpSetFormatStix, + IpSetFormatOtxCsv, + IpSetFormatAlienVault, + IpSetFormatProofPoint, + IpSetFormatFireEye, + } +} + const ( // IpSetStatusInactive is a IpSetStatus enum value IpSetStatusInactive = "INACTIVE" @@ -12591,6 +14494,19 @@ const ( IpSetStatusDeleted = "DELETED" ) +// IpSetStatus_Values returns all elements of the IpSetStatus enum +func IpSetStatus_Values() []string { + return []string{ + IpSetStatusInactive, + IpSetStatusActivating, + IpSetStatusActive, + IpSetStatusDeactivating, + IpSetStatusError, + IpSetStatusDeletePending, + IpSetStatusDeleted, + } +} + const ( // OrderByAsc is a OrderBy enum value OrderByAsc = "ASC" @@ -12599,6 +14515,14 @@ const ( OrderByDesc = "DESC" ) +// OrderBy_Values returns all elements of the OrderBy enum +func OrderBy_Values() []string { + return []string{ + OrderByAsc, + OrderByDesc, + } +} + const ( // PublishingStatusPendingVerification is a PublishingStatus enum value PublishingStatusPendingVerification = "PENDING_VERIFICATION" @@ -12613,6 +14537,16 @@ const ( PublishingStatusStopped = "STOPPED" ) +// PublishingStatus_Values returns all elements of the PublishingStatus enum +func PublishingStatus_Values() []string { + return []string{ + PublishingStatusPendingVerification, + PublishingStatusPublishing, + PublishingStatusUnableToPublishFixDestinationProperty, + PublishingStatusStopped, + } +} + const ( // ThreatIntelSetFormatTxt is a ThreatIntelSetFormat enum value ThreatIntelSetFormatTxt = "TXT" @@ -12633,6 +14567,18 @@ const ( ThreatIntelSetFormatFireEye = "FIRE_EYE" ) +// ThreatIntelSetFormat_Values returns all elements of the ThreatIntelSetFormat enum +func ThreatIntelSetFormat_Values() []string { + return []string{ + ThreatIntelSetFormatTxt, + ThreatIntelSetFormatStix, + ThreatIntelSetFormatOtxCsv, + ThreatIntelSetFormatAlienVault, + ThreatIntelSetFormatProofPoint, + ThreatIntelSetFormatFireEye, + } +} + const ( // ThreatIntelSetStatusInactive is a ThreatIntelSetStatus enum value ThreatIntelSetStatusInactive = "INACTIVE" @@ -12655,3 +14601,40 @@ const ( // ThreatIntelSetStatusDeleted is a ThreatIntelSetStatus enum value ThreatIntelSetStatusDeleted = "DELETED" ) + +// ThreatIntelSetStatus_Values returns all elements of the ThreatIntelSetStatus enum +func ThreatIntelSetStatus_Values() []string { + return []string{ + ThreatIntelSetStatusInactive, + ThreatIntelSetStatusActivating, + ThreatIntelSetStatusActive, + ThreatIntelSetStatusDeactivating, + ThreatIntelSetStatusError, + ThreatIntelSetStatusDeletePending, + ThreatIntelSetStatusDeleted, + } +} + +const ( + // UsageStatisticTypeSumByAccount is a UsageStatisticType enum value + UsageStatisticTypeSumByAccount = "SUM_BY_ACCOUNT" + + // UsageStatisticTypeSumByDataSource is a UsageStatisticType enum value + UsageStatisticTypeSumByDataSource = "SUM_BY_DATA_SOURCE" + + // UsageStatisticTypeSumByResource is a UsageStatisticType enum value + UsageStatisticTypeSumByResource = "SUM_BY_RESOURCE" + + // UsageStatisticTypeTopResources is a UsageStatisticType enum value + UsageStatisticTypeTopResources = "TOP_RESOURCES" +) + +// UsageStatisticType_Values returns all elements of the UsageStatisticType enum +func UsageStatisticType_Values() []string { + return []string{ + UsageStatisticTypeSumByAccount, + UsageStatisticTypeSumByDataSource, + UsageStatisticTypeSumByResource, + UsageStatisticTypeTopResources, + } +} 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 eb606e83573..7c3a5dd0dc9 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/api.go @@ -82,7 +82,8 @@ func (c *IAM) AddClientIDToOpenIDConnectProviderRequest(input *AddClientIDToOpen // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -156,10 +157,12 @@ func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInp // AddRoleToInstanceProfile API operation for AWS Identity and Access Management. // // Adds the specified IAM role to the specified instance profile. An instance -// profile can contain only one role, and this limit cannot be increased. You -// can remove the existing role and then add a different role to an instance -// profile. You must then wait for the change to appear across all of AWS because -// of eventual consistency (https://en.wikipedia.org/wiki/Eventual_consistency). +// profile can contain only one role. (The number and size of IAM resources +// in an AWS account are limited. For more information, see IAM and STS Quotas +// (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) +// in the IAM User Guide.) You can remove the existing role and then add a different +// role to an instance profile. You must then wait for the change to appear +// across all of AWS because of eventual consistency (https://en.wikipedia.org/wiki/Eventual_consistency). // To force the change, you must disassociate the instance profile (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisassociateIamInstanceProfile.html) // and then associate the instance profile (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateIamInstanceProfile.html), // or you can stop your instance and then restart it. @@ -189,7 +192,8 @@ func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInp // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -284,7 +288,8 @@ func (c *IAM) AddUserToGroupRequest(input *AddUserToGroupInput) (req *request.Re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -380,7 +385,8 @@ func (c *IAM) AttachGroupPolicyRequest(input *AttachGroupPolicyInput) (req *requ // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -488,7 +494,8 @@ func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -598,7 +605,8 @@ func (c *IAM) AttachUserPolicyRequest(input *AttachUserPolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -704,7 +712,8 @@ func (c *IAM) ChangePasswordRequest(input *ChangePasswordInput) (req *request.Re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityTemporarilyUnmodifiableException "EntityTemporarilyUnmodifiable" // The request was rejected because it referenced an entity that is temporarily @@ -795,8 +804,8 @@ func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *request. // to manage AWS account root user credentials. This is true even if the AWS // account has no associated users. // -// For information about limits on the number of keys you can create, see Limitations -// on IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // To ensure the security of your AWS account, the secret access key is accessible @@ -819,7 +828,8 @@ func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *request. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -910,7 +920,8 @@ func (c *IAM) CreateAccountAliasRequest(input *CreateAccountAliasInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -984,8 +995,8 @@ func (c *IAM) CreateGroupRequest(input *CreateGroupInput) (req *request.Request, // // Creates a new group. // -// For information about the number of groups you can create, see Limitations -// on IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -998,7 +1009,8 @@ func (c *IAM) CreateGroupRequest(input *CreateGroupInput) (req *request.Request, // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -1081,8 +1093,8 @@ func (c *IAM) CreateInstanceProfileRequest(input *CreateInstanceProfileInput) (r // Creates a new instance profile. For information about instance profiles, // go to About Instance Profiles (https://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html). // -// For information about the number of instance profiles you can create, see -// Limitations on IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1099,7 +1111,8 @@ func (c *IAM) CreateInstanceProfileRequest(input *CreateInstanceProfileInput) (r // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -1198,7 +1211,8 @@ func (c *IAM) CreateLoginProfileRequest(input *CreateLoginProfileInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -1312,7 +1326,8 @@ func (c *IAM) CreateOpenIDConnectProviderRequest(input *CreateOpenIDConnectProvi // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -1409,7 +1424,8 @@ func (c *IAM) CreatePolicyRequest(input *CreatePolicyInput) (req *request.Reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -1524,7 +1540,8 @@ func (c *IAM) CreatePolicyVersionRequest(input *CreatePolicyVersionInput) (req * // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -1598,8 +1615,8 @@ func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *request.Request, o // // Creates a new role for your AWS account. For more information about roles, // go to IAM Roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html). -// For information about limitations on role names and the number of roles you -// can create, go to Limitations on IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1612,7 +1629,8 @@ func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *request.Request, o // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -1742,7 +1760,8 @@ func (c *IAM) CreateSAMLProviderRequest(input *CreateSAMLProviderInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -1840,7 +1859,8 @@ func (c *IAM) CreateServiceLinkedRoleRequest(input *CreateServiceLinkedRoleInput // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -1941,7 +1961,8 @@ func (c *IAM) CreateServiceSpecificCredentialRequest(input *CreateServiceSpecifi // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -2018,8 +2039,8 @@ func (c *IAM) CreateUserRequest(input *CreateUserInput) (req *request.Request, o // // Creates a new IAM user for your AWS account. // -// For information about limitations on the number of IAM users you can create, -// see Limitations on IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -2032,7 +2053,8 @@ func (c *IAM) CreateUserRequest(input *CreateUserInput) (req *request.Request, o // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -2127,8 +2149,8 @@ func (c *IAM) CreateVirtualMFADeviceRequest(input *CreateVirtualMFADeviceInput) // go to Using a Virtual MFA Device (https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html) // in the IAM User Guide. // -// For information about limits on the number of MFA devices you can create, -// see Limitations on Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // The seed information contained in the QR code and the Base32 string should @@ -2147,7 +2169,8 @@ func (c *IAM) CreateVirtualMFADeviceRequest(input *CreateVirtualMFADeviceInput) // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -2251,7 +2274,8 @@ func (c *IAM) DeactivateMFADeviceRequest(input *DeactivateMFADeviceInput) (req * // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2346,7 +2370,8 @@ func (c *IAM) DeleteAccessKeyRequest(input *DeleteAccessKeyInput) (req *request. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2437,7 +2462,8 @@ func (c *IAM) DeleteAccountAliasRequest(input *DeleteAccountAliasInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2526,7 +2552,8 @@ func (c *IAM) DeleteAccountPasswordPolicyRequest(input *DeleteAccountPasswordPol // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2620,7 +2647,8 @@ func (c *IAM) DeleteGroupRequest(input *DeleteGroupInput) (req *request.Request, // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2715,7 +2743,8 @@ func (c *IAM) DeleteGroupPolicyRequest(input *DeleteGroupPolicyInput) (req *requ // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2817,7 +2846,8 @@ func (c *IAM) DeleteInstanceProfileRequest(input *DeleteInstanceProfileInput) (r // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2918,7 +2948,8 @@ func (c *IAM) DeleteLoginProfileRequest(input *DeleteLoginProfileInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -3125,7 +3156,8 @@ func (c *IAM) DeletePolicyRequest(input *DeletePolicyInput) (req *request.Reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -3230,7 +3262,8 @@ func (c *IAM) DeletePolicyVersionRequest(input *DeletePolicyVersionInput) (req * // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -3337,7 +3370,8 @@ func (c *IAM) DeleteRoleRequest(input *DeleteRoleInput) (req *request.Request, o // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -3538,7 +3572,8 @@ func (c *IAM) DeleteRolePolicyRequest(input *DeleteRolePolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -3640,7 +3675,8 @@ func (c *IAM) DeleteSAMLProviderRequest(input *DeleteSAMLProviderInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -3839,7 +3875,8 @@ func (c *IAM) DeleteServerCertificateRequest(input *DeleteServerCertificateInput // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -3946,7 +3983,8 @@ func (c *IAM) DeleteServiceLinkedRoleRequest(input *DeleteServiceLinkedRoleInput // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -4122,7 +4160,8 @@ func (c *IAM) DeleteSigningCertificateRequest(input *DeleteSigningCertificateInp // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -4229,7 +4268,8 @@ func (c *IAM) DeleteUserRequest(input *DeleteUserInput) (req *request.Request, o // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -4426,7 +4466,8 @@ func (c *IAM) DeleteUserPolicyRequest(input *DeleteUserPolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -4522,7 +4563,8 @@ func (c *IAM) DeleteVirtualMFADeviceRequest(input *DeleteVirtualMFADeviceInput) // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -4616,7 +4658,8 @@ func (c *IAM) DetachGroupPolicyRequest(input *DetachGroupPolicyInput) (req *requ // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -4714,7 +4757,8 @@ func (c *IAM) DetachRolePolicyRequest(input *DetachRolePolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -4818,7 +4862,8 @@ func (c *IAM) DetachUserPolicyRequest(input *DetachUserPolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -4923,7 +4968,8 @@ func (c *IAM) EnableMFADeviceRequest(input *EnableMFADeviceInput) (req *request. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -5013,7 +5059,8 @@ func (c *IAM) GenerateCredentialReportRequest(input *GenerateCredentialReportInp // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -5326,8 +5373,8 @@ func (c *IAM) GenerateServiceLastAccessedDetailsRequest(input *GenerateServiceLa // see Evaluating Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-basics) // in the IAM User Guide. // -// For more information about service last accessed data, see Reducing Policy -// Scope by Viewing User Activity (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html) +// For more information about service and action last accessed data, see Reducing +// Permissions Using Service Last Accessed Data (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -5726,8 +5773,8 @@ func (c *IAM) GetAccountSummaryRequest(input *GetAccountSummaryInput) (req *requ // // Retrieves information about IAM entity usage and IAM quotas in the AWS account. // -// For information about limitations on IAM entities, see Limitations on IAM -// Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -7410,6 +7457,15 @@ func (c *IAM) GetServiceLastAccessedDetailsRequest(input *GetServiceLastAccessed // // By default, the list is sorted by service namespace. // +// If you specified ACTION_LEVEL granularity when you generated the report, +// this operation returns service and action last accessed data. This includes +// the most recent access attempt for each tracked action within a service. +// Otherwise, this operation returns only service data. +// +// For more information about service and action last accessed data, see Reducing +// Permissions Using Service Last Accessed Data (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html) +// in the IAM User Guide. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -11715,7 +11771,8 @@ func (c *IAM) PutGroupPolicyRequest(input *PutGroupPolicyInput) (req *request.Re // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" // The request was rejected because the policy document was malformed. The error @@ -11941,7 +11998,8 @@ func (c *IAM) PutRolePolicyRequest(input *PutRolePolicyInput) (req *request.Requ // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" // The request was rejected because the policy document was malformed. The error @@ -12159,7 +12217,8 @@ func (c *IAM) PutUserPolicyRequest(input *PutUserPolicyInput) (req *request.Requ // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" // The request was rejected because the policy document was malformed. The error @@ -12359,7 +12418,8 @@ func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstance // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -12454,7 +12514,8 @@ func (c *IAM) RemoveUserFromGroupRequest(input *RemoveUserFromGroupInput) (req * // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -12635,7 +12696,8 @@ func (c *IAM) ResyncMFADeviceRequest(input *ResyncMFADeviceInput) (req *request. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -12737,7 +12799,8 @@ func (c *IAM) SetDefaultPolicyVersionRequest(input *SetDefaultPolicyVersionInput // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -13292,7 +13355,8 @@ func (c *IAM) TagRoleRequest(input *TagRoleInput) (req *request.Request, output // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -13422,7 +13486,8 @@ func (c *IAM) TagUserRequest(input *TagUserInput) (req *request.Request, output // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -13715,7 +13780,8 @@ func (c *IAM) UpdateAccessKeyRequest(input *UpdateAccessKeyInput) (req *request. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -13819,7 +13885,8 @@ func (c *IAM) UpdateAccountPasswordPolicyRequest(input *UpdateAccountPasswordPol // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -13915,7 +13982,8 @@ func (c *IAM) UpdateAssumeRolePolicyRequest(input *UpdateAssumeRolePolicyInput) // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -14025,7 +14093,8 @@ func (c *IAM) UpdateGroupRequest(input *UpdateGroupInput) (req *request.Request, // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -14128,7 +14197,8 @@ func (c *IAM) UpdateLoginProfileRequest(input *UpdateLoginProfileInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -14509,7 +14579,8 @@ func (c *IAM) UpdateSAMLProviderRequest(input *UpdateSAMLProviderInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -14711,7 +14782,8 @@ func (c *IAM) UpdateServerCertificateRequest(input *UpdateServerCertificateInput // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -14892,7 +14964,8 @@ func (c *IAM) UpdateSigningCertificateRequest(input *UpdateSigningCertificateInp // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -14992,7 +15065,8 @@ func (c *IAM) UpdateUserRequest(input *UpdateUserInput) (req *request.Request, o // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -15097,7 +15171,8 @@ func (c *IAM) UploadSSHPublicKeyRequest(input *UploadSSHPublicKeyInput) (req *re // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -15218,7 +15293,8 @@ func (c *IAM) UploadServerCertificateRequest(input *UploadServerCertificateInput // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -15331,7 +15407,8 @@ func (c *IAM) UploadSigningCertificateRequest(input *UploadSigningCertificateInp // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -20346,6 +20423,14 @@ type GenerateServiceLastAccessedDetailsInput struct { // // Arn is a required field Arn *string `min:"20" type:"string" required:"true"` + + // The level of detail that you want to generate. You can specify whether you + // want to generate information about the last attempt to access services or + // actions. If you specify service-level granularity, this operation generates + // only service data. If you specify action-level granularity, it generates + // service and action data. If you don't include this optional parameter, the + // operation generates service data. + Granularity *string `type:"string" enum:"AccessAdvisorUsageGranularityType"` } // String returns the string representation @@ -20380,6 +20465,12 @@ func (s *GenerateServiceLastAccessedDetailsInput) SetArn(v string) *GenerateServ return s } +// SetGranularity sets the Granularity field's value. +func (s *GenerateServiceLastAccessedDetailsInput) SetGranularity(v string) *GenerateServiceLastAccessedDetailsInput { + s.Granularity = &v + return s +} + type GenerateServiceLastAccessedDetailsOutput struct { _ struct{} `type:"structure"` @@ -22358,6 +22449,11 @@ type GetServiceLastAccessedDetailsOutput struct { // JobStatus is a required field JobStatus *string `type:"string" required:"true" enum:"JobStatusType"` + // The type of job. Service jobs return information about when each service + // was last accessed. Action jobs also include information about when tracked + // actions within the service were last accessed. + JobType *string `type:"string" enum:"AccessAdvisorUsageGranularityType"` + // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. Marker *string `type:"string"` @@ -22409,6 +22505,12 @@ func (s *GetServiceLastAccessedDetailsOutput) SetJobStatus(v string) *GetService return s } +// SetJobType sets the JobType field's value. +func (s *GetServiceLastAccessedDetailsOutput) SetJobType(v string) *GetServiceLastAccessedDetailsOutput { + s.JobType = &v + return s +} + // SetMarker sets the Marker field's value. func (s *GetServiceLastAccessedDetailsOutput) SetMarker(v string) *GetServiceLastAccessedDetailsOutput { s.Marker = &v @@ -29462,6 +29564,13 @@ type ServiceLastAccessed struct { // the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). LastAuthenticatedEntity *string `min:"20" type:"string"` + // The Region from which the authenticated entity (user or role) last attempted + // to access the service. AWS does not report unauthenticated requests. + // + // This field is null if no IAM entities attempted to access the service within + // the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + LastAuthenticatedRegion *string `type:"string"` + // The name of the service in which access was attempted. // // ServiceName is a required field @@ -29486,6 +29595,16 @@ type ServiceLastAccessed struct { // This field is null if no principals attempted to access the service within // the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). TotalAuthenticatedEntities *int64 `type:"integer"` + + // An object that contains details about the most recent attempt to access a + // tracked action within the service. + // + // This field is null if there no tracked actions or if the principal did not + // use the tracked actions within the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + // This field is also null if the report was generated at the service level + // and not the action level. For more information, see the Granularity field + // in GenerateServiceLastAccessedDetails. + TrackedActionsLastAccessed []*TrackedActionLastAccessed `type:"list"` } // String returns the string representation @@ -29510,6 +29629,12 @@ func (s *ServiceLastAccessed) SetLastAuthenticatedEntity(v string) *ServiceLastA return s } +// SetLastAuthenticatedRegion sets the LastAuthenticatedRegion field's value. +func (s *ServiceLastAccessed) SetLastAuthenticatedRegion(v string) *ServiceLastAccessed { + s.LastAuthenticatedRegion = &v + return s +} + // SetServiceName sets the ServiceName field's value. func (s *ServiceLastAccessed) SetServiceName(v string) *ServiceLastAccessed { s.ServiceName = &v @@ -29528,6 +29653,12 @@ func (s *ServiceLastAccessed) SetTotalAuthenticatedEntities(v int64) *ServiceLas return s } +// SetTrackedActionsLastAccessed sets the TrackedActionsLastAccessed field's value. +func (s *ServiceLastAccessed) SetTrackedActionsLastAccessed(v []*TrackedActionLastAccessed) *ServiceLastAccessed { + s.TrackedActionsLastAccessed = v + return s +} + // Contains the details of a service-specific credential. type ServiceSpecificCredential struct { _ struct{} `type:"structure"` @@ -30313,7 +30444,7 @@ type SimulatePrincipalPolicyInput struct { // one permissions boundary when you pass a policy to this operation. An IAM // entity can only have one permissions boundary in effect at a time. For example, // if a permissions boundary is attached to an entity and you pass in a different - // permissions boundary policy using this parameter, then the new permission + // permissions boundary policy using this parameter, then the new permissions // boundary policy is used for the simulation. For more information about permissions // boundaries, see Permissions Boundaries for IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) // in the IAM User Guide. The policy input is specified as a string containing @@ -30857,6 +30988,75 @@ func (s TagUserOutput) GoString() string { return s.String() } +// Contains details about the most recent attempt to access an action within +// the service. +// +// This data type is used as a response element in the GetServiceLastAccessedDetails +// operation. +type TrackedActionLastAccessed struct { + _ struct{} `type:"structure"` + + // The name of the tracked action to which access was attempted. Tracked actions + // are actions that report activity to IAM. + ActionName *string `type:"string"` + + // The Amazon Resource Name (ARN). ARNs are unique identifiers for AWS resources. + // + // For more information about ARNs, go to Amazon Resource Names (ARNs) and AWS + // Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) + // in the AWS General Reference. + LastAccessedEntity *string `min:"20" type:"string"` + + // The Region from which the authenticated entity (user or role) last attempted + // to access the tracked action. AWS does not report unauthenticated requests. + // + // This field is null if no IAM entities attempted to access the service within + // the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + LastAccessedRegion *string `type:"string"` + + // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), + // when an authenticated entity most recently attempted to access the tracked + // service. AWS does not report unauthenticated requests. + // + // This field is null if no IAM entities attempted to access the service within + // the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + LastAccessedTime *time.Time `type:"timestamp"` +} + +// String returns the string representation +func (s TrackedActionLastAccessed) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TrackedActionLastAccessed) GoString() string { + return s.String() +} + +// SetActionName sets the ActionName field's value. +func (s *TrackedActionLastAccessed) SetActionName(v string) *TrackedActionLastAccessed { + s.ActionName = &v + return s +} + +// SetLastAccessedEntity sets the LastAccessedEntity field's value. +func (s *TrackedActionLastAccessed) SetLastAccessedEntity(v string) *TrackedActionLastAccessed { + s.LastAccessedEntity = &v + return s +} + +// SetLastAccessedRegion sets the LastAccessedRegion field's value. +func (s *TrackedActionLastAccessed) SetLastAccessedRegion(v string) *TrackedActionLastAccessed { + s.LastAccessedRegion = &v + return s +} + +// SetLastAccessedTime sets the LastAccessedTime field's value. +func (s *TrackedActionLastAccessed) SetLastAccessedTime(v time.Time) *TrackedActionLastAccessed { + s.LastAccessedTime = &v + return s +} + type UntagRoleInput struct { _ struct{} `type:"structure"` @@ -33066,6 +33266,22 @@ func (s *VirtualMFADevice) SetUser(v *User) *VirtualMFADevice { return s } +const ( + // AccessAdvisorUsageGranularityTypeServiceLevel is a AccessAdvisorUsageGranularityType enum value + AccessAdvisorUsageGranularityTypeServiceLevel = "SERVICE_LEVEL" + + // AccessAdvisorUsageGranularityTypeActionLevel is a AccessAdvisorUsageGranularityType enum value + AccessAdvisorUsageGranularityTypeActionLevel = "ACTION_LEVEL" +) + +// AccessAdvisorUsageGranularityType_Values returns all elements of the AccessAdvisorUsageGranularityType enum +func AccessAdvisorUsageGranularityType_Values() []string { + return []string{ + AccessAdvisorUsageGranularityTypeServiceLevel, + AccessAdvisorUsageGranularityTypeActionLevel, + } +} + const ( // AssignmentStatusTypeAssigned is a AssignmentStatusType enum value AssignmentStatusTypeAssigned = "Assigned" @@ -33077,6 +33293,15 @@ const ( AssignmentStatusTypeAny = "Any" ) +// AssignmentStatusType_Values returns all elements of the AssignmentStatusType enum +func AssignmentStatusType_Values() []string { + return []string{ + AssignmentStatusTypeAssigned, + AssignmentStatusTypeUnassigned, + AssignmentStatusTypeAny, + } +} + const ( // ContextKeyTypeEnumString is a ContextKeyTypeEnum enum value ContextKeyTypeEnumString = "string" @@ -33115,6 +33340,24 @@ const ( ContextKeyTypeEnumDateList = "dateList" ) +// ContextKeyTypeEnum_Values returns all elements of the ContextKeyTypeEnum enum +func ContextKeyTypeEnum_Values() []string { + return []string{ + ContextKeyTypeEnumString, + ContextKeyTypeEnumStringList, + ContextKeyTypeEnumNumeric, + ContextKeyTypeEnumNumericList, + ContextKeyTypeEnumBoolean, + ContextKeyTypeEnumBooleanList, + ContextKeyTypeEnumIp, + ContextKeyTypeEnumIpList, + ContextKeyTypeEnumBinary, + ContextKeyTypeEnumBinaryList, + ContextKeyTypeEnumDate, + ContextKeyTypeEnumDateList, + } +} + const ( // DeletionTaskStatusTypeSucceeded is a DeletionTaskStatusType enum value DeletionTaskStatusTypeSucceeded = "SUCCEEDED" @@ -33129,6 +33372,16 @@ const ( DeletionTaskStatusTypeNotStarted = "NOT_STARTED" ) +// DeletionTaskStatusType_Values returns all elements of the DeletionTaskStatusType enum +func DeletionTaskStatusType_Values() []string { + return []string{ + DeletionTaskStatusTypeSucceeded, + DeletionTaskStatusTypeInProgress, + DeletionTaskStatusTypeFailed, + DeletionTaskStatusTypeNotStarted, + } +} + const ( // EncodingTypeSsh is a EncodingType enum value EncodingTypeSsh = "SSH" @@ -33137,6 +33390,14 @@ const ( EncodingTypePem = "PEM" ) +// EncodingType_Values returns all elements of the EncodingType enum +func EncodingType_Values() []string { + return []string{ + EncodingTypeSsh, + EncodingTypePem, + } +} + const ( // EntityTypeUser is a EntityType enum value EntityTypeUser = "User" @@ -33154,6 +33415,17 @@ const ( EntityTypeAwsmanagedPolicy = "AWSManagedPolicy" ) +// EntityType_Values returns all elements of the EntityType enum +func EntityType_Values() []string { + return []string{ + EntityTypeUser, + EntityTypeRole, + EntityTypeGroup, + EntityTypeLocalManagedPolicy, + EntityTypeAwsmanagedPolicy, + } +} + const ( // GlobalEndpointTokenVersionV1token is a GlobalEndpointTokenVersion enum value GlobalEndpointTokenVersionV1token = "v1Token" @@ -33162,6 +33434,14 @@ const ( GlobalEndpointTokenVersionV2token = "v2Token" ) +// GlobalEndpointTokenVersion_Values returns all elements of the GlobalEndpointTokenVersion enum +func GlobalEndpointTokenVersion_Values() []string { + return []string{ + GlobalEndpointTokenVersionV1token, + GlobalEndpointTokenVersionV2token, + } +} + const ( // JobStatusTypeInProgress is a JobStatusType enum value JobStatusTypeInProgress = "IN_PROGRESS" @@ -33173,11 +33453,27 @@ const ( JobStatusTypeFailed = "FAILED" ) +// JobStatusType_Values returns all elements of the JobStatusType enum +func JobStatusType_Values() []string { + return []string{ + JobStatusTypeInProgress, + JobStatusTypeCompleted, + JobStatusTypeFailed, + } +} + const ( // PermissionsBoundaryAttachmentTypePermissionsBoundaryPolicy is a PermissionsBoundaryAttachmentType enum value PermissionsBoundaryAttachmentTypePermissionsBoundaryPolicy = "PermissionsBoundaryPolicy" ) +// PermissionsBoundaryAttachmentType_Values returns all elements of the PermissionsBoundaryAttachmentType enum +func PermissionsBoundaryAttachmentType_Values() []string { + return []string{ + PermissionsBoundaryAttachmentTypePermissionsBoundaryPolicy, + } +} + const ( // PolicyEvaluationDecisionTypeAllowed is a PolicyEvaluationDecisionType enum value PolicyEvaluationDecisionTypeAllowed = "allowed" @@ -33189,6 +33485,15 @@ const ( PolicyEvaluationDecisionTypeImplicitDeny = "implicitDeny" ) +// PolicyEvaluationDecisionType_Values returns all elements of the PolicyEvaluationDecisionType enum +func PolicyEvaluationDecisionType_Values() []string { + return []string{ + PolicyEvaluationDecisionTypeAllowed, + PolicyEvaluationDecisionTypeExplicitDeny, + PolicyEvaluationDecisionTypeImplicitDeny, + } +} + const ( // PolicyOwnerEntityTypeUser is a PolicyOwnerEntityType enum value PolicyOwnerEntityTypeUser = "USER" @@ -33200,6 +33505,15 @@ const ( PolicyOwnerEntityTypeGroup = "GROUP" ) +// PolicyOwnerEntityType_Values returns all elements of the PolicyOwnerEntityType enum +func PolicyOwnerEntityType_Values() []string { + return []string{ + PolicyOwnerEntityTypeUser, + PolicyOwnerEntityTypeRole, + PolicyOwnerEntityTypeGroup, + } +} + const ( // PolicyScopeTypeAll is a PolicyScopeType enum value PolicyScopeTypeAll = "All" @@ -33211,6 +33525,15 @@ const ( PolicyScopeTypeLocal = "Local" ) +// PolicyScopeType_Values returns all elements of the PolicyScopeType enum +func PolicyScopeType_Values() []string { + return []string{ + PolicyScopeTypeAll, + PolicyScopeTypeAws, + PolicyScopeTypeLocal, + } +} + const ( // PolicySourceTypeUser is a PolicySourceType enum value PolicySourceTypeUser = "user" @@ -33234,6 +33557,19 @@ const ( PolicySourceTypeNone = "none" ) +// PolicySourceType_Values returns all elements of the PolicySourceType enum +func PolicySourceType_Values() []string { + return []string{ + PolicySourceTypeUser, + PolicySourceTypeGroup, + PolicySourceTypeRole, + PolicySourceTypeAwsManaged, + PolicySourceTypeUserManaged, + PolicySourceTypeResource, + PolicySourceTypeNone, + } +} + const ( // PolicyTypeInline is a PolicyType enum value PolicyTypeInline = "INLINE" @@ -33242,6 +33578,14 @@ const ( PolicyTypeManaged = "MANAGED" ) +// PolicyType_Values returns all elements of the PolicyType enum +func PolicyType_Values() []string { + return []string{ + PolicyTypeInline, + PolicyTypeManaged, + } +} + // The policy usage type that indicates whether the policy is used as a permissions // policy or as the permissions boundary for an entity. // @@ -33256,11 +33600,26 @@ const ( PolicyUsageTypePermissionsBoundary = "PermissionsBoundary" ) +// PolicyUsageType_Values returns all elements of the PolicyUsageType enum +func PolicyUsageType_Values() []string { + return []string{ + PolicyUsageTypePermissionsPolicy, + PolicyUsageTypePermissionsBoundary, + } +} + const ( // ReportFormatTypeTextCsv is a ReportFormatType enum value ReportFormatTypeTextCsv = "text/csv" ) +// ReportFormatType_Values returns all elements of the ReportFormatType enum +func ReportFormatType_Values() []string { + return []string{ + ReportFormatTypeTextCsv, + } +} + const ( // ReportStateTypeStarted is a ReportStateType enum value ReportStateTypeStarted = "STARTED" @@ -33272,6 +33631,15 @@ const ( ReportStateTypeComplete = "COMPLETE" ) +// ReportStateType_Values returns all elements of the ReportStateType enum +func ReportStateType_Values() []string { + return []string{ + ReportStateTypeStarted, + ReportStateTypeInprogress, + ReportStateTypeComplete, + } +} + const ( // SortKeyTypeServiceNamespaceAscending is a SortKeyType enum value SortKeyTypeServiceNamespaceAscending = "SERVICE_NAMESPACE_ASCENDING" @@ -33286,6 +33654,16 @@ const ( SortKeyTypeLastAuthenticatedTimeDescending = "LAST_AUTHENTICATED_TIME_DESCENDING" ) +// SortKeyType_Values returns all elements of the SortKeyType enum +func SortKeyType_Values() []string { + return []string{ + SortKeyTypeServiceNamespaceAscending, + SortKeyTypeServiceNamespaceDescending, + SortKeyTypeLastAuthenticatedTimeAscending, + SortKeyTypeLastAuthenticatedTimeDescending, + } +} + const ( // StatusTypeActive is a StatusType enum value StatusTypeActive = "Active" @@ -33294,6 +33672,14 @@ const ( StatusTypeInactive = "Inactive" ) +// StatusType_Values returns all elements of the StatusType enum +func StatusType_Values() []string { + return []string{ + StatusTypeActive, + StatusTypeInactive, + } +} + const ( // SummaryKeyTypeUsers is a SummaryKeyType enum value SummaryKeyTypeUsers = "Users" @@ -33373,3 +33759,35 @@ const ( // SummaryKeyTypeGlobalEndpointTokenVersion is a SummaryKeyType enum value SummaryKeyTypeGlobalEndpointTokenVersion = "GlobalEndpointTokenVersion" ) + +// SummaryKeyType_Values returns all elements of the SummaryKeyType enum +func SummaryKeyType_Values() []string { + return []string{ + SummaryKeyTypeUsers, + SummaryKeyTypeUsersQuota, + SummaryKeyTypeGroups, + SummaryKeyTypeGroupsQuota, + SummaryKeyTypeServerCertificates, + SummaryKeyTypeServerCertificatesQuota, + SummaryKeyTypeUserPolicySizeQuota, + SummaryKeyTypeGroupPolicySizeQuota, + SummaryKeyTypeGroupsPerUserQuota, + SummaryKeyTypeSigningCertificatesPerUserQuota, + SummaryKeyTypeAccessKeysPerUserQuota, + SummaryKeyTypeMfadevices, + SummaryKeyTypeMfadevicesInUse, + SummaryKeyTypeAccountMfaenabled, + SummaryKeyTypeAccountAccessKeysPresent, + SummaryKeyTypeAccountSigningCertificatesPresent, + SummaryKeyTypeAttachedPoliciesPerGroupQuota, + SummaryKeyTypeAttachedPoliciesPerRoleQuota, + SummaryKeyTypeAttachedPoliciesPerUserQuota, + SummaryKeyTypePolicies, + SummaryKeyTypePoliciesQuota, + SummaryKeyTypePolicySizeQuota, + SummaryKeyTypePolicyVersionsInUse, + SummaryKeyTypePolicyVersionsInUseQuota, + SummaryKeyTypeVersionsPerPolicyQuota, + SummaryKeyTypeGlobalEndpointTokenVersion, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go b/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go index 0d709cd275b..13f89fa1900 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go @@ -3,59 +3,12 @@ // Package iam provides the client and types for making API // requests to AWS Identity and Access Management. // -// AWS Identity and Access Management (IAM) is a web service that you can use -// to manage users and user permissions under your AWS account. This guide provides -// descriptions of IAM actions that you can call programmatically. For general -// information about IAM, see AWS Identity and Access Management (IAM) (http://aws.amazon.com/iam/). -// For the user guide for IAM, see Using IAM (https://docs.aws.amazon.com/IAM/latest/UserGuide/). -// -// AWS provides SDKs that consist of libraries and sample code for various programming -// languages and platforms (Java, Ruby, .NET, iOS, Android, etc.). The SDKs -// provide a convenient way to create programmatic access to IAM and AWS. For -// example, the SDKs take care of tasks such as cryptographically signing requests -// (see below), managing errors, and retrying requests automatically. For information -// about the AWS SDKs, including how to download and install them, see the Tools -// for Amazon Web Services (http://aws.amazon.com/tools/) page. -// -// We recommend that you use the AWS SDKs to make programmatic API calls to -// IAM. However, you can also use the IAM Query API to make direct calls to -// the IAM web service. To learn more about the IAM Query API, see Making Query -// Requests (https://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) -// in the Using IAM guide. IAM supports GET and POST requests for all actions. -// That is, the API does not require you to use GET for some actions and POST -// for others. However, GET requests are subject to the limitation size of a -// URL. Therefore, for operations that require larger sizes, use a POST request. -// -// Signing Requests -// -// Requests must be signed using an access key ID and a secret access key. We -// strongly recommend that you do not use your AWS account access key ID and -// secret access key for everyday work with IAM. You can use the access key -// ID and secret access key for an IAM user or you can use the AWS Security -// Token Service to generate temporary security credentials and use those to -// sign requests. -// -// To sign requests, we recommend that you use Signature Version 4 (https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). -// If you have an existing application that uses Signature Version 2, you do -// not have to update it to use Signature Version 4. However, some operations -// now require Signature Version 4. The documentation for operations that require -// version 4 indicate this requirement. -// -// Additional Resources -// -// For more information, see the following: -// -// * AWS Security Credentials (https://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html). -// This topic provides general information about the types of credentials -// used for accessing AWS. -// -// * IAM Best Practices (https://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPractices.html). -// This topic presents a list of suggestions for using the IAM service to -// help secure your AWS resources. -// -// * Signing AWS API Requests (https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html). -// This set of topics walk you through the process of signing a request using -// an access key ID and secret access key. +// AWS Identity and Access Management (IAM) is a web service for securely controlling +// access to AWS services. With IAM, you can centrally manage users, security +// credentials such as access keys, and permissions that control which AWS resources +// users and applications can access. For more information about IAM, see AWS +// Identity and Access Management (IAM) (http://aws.amazon.com/iam/) and the +// AWS Identity and Access Management User Guide (https://docs.aws.amazon.com/IAM/latest/UserGuide/). // // See https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08 for more information on this service. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go b/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go index 30a85b3b44d..74afac25e08 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go @@ -117,7 +117,8 @@ const ( // "LimitExceeded". // // The request was rejected because it attempted to create resources beyond - // the current AWS account limits. The error message describes the limit exceeded. + // the current AWS account limitations. The error message describes the limit + // exceeded. ErrCodeLimitExceededException = "LimitExceeded" // ErrCodeMalformedCertificateException for service response error code diff --git a/vendor/github.com/aws/aws-sdk-go/service/imagebuilder/api.go b/vendor/github.com/aws/aws-sdk-go/service/imagebuilder/api.go index 10a6d1a9a06..ea48fda27f7 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/imagebuilder/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/imagebuilder/api.go @@ -207,6 +207,10 @@ func (c *Imagebuilder) CreateComponentRequest(input *CreateComponentInput) (req // You have specified two or more mutually exclusive parameters. Review the // error message for details. // +// * ServiceQuotaExceededException +// You have exceeded the number of permitted resources or operations for this +// service. For service quotas, see EC2 Image Builder endpoints and quotas (https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder). +// // See also, https://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateComponent func (c *Imagebuilder) CreateComponent(input *CreateComponentInput) (*CreateComponentOutput, error) { req, out := c.CreateComponentRequest(input) @@ -319,6 +323,10 @@ func (c *Imagebuilder) CreateDistributionConfigurationRequest(input *CreateDistr // You have specified two or more mutually exclusive parameters. Review the // error message for details. // +// * ServiceQuotaExceededException +// You have exceeded the number of permitted resources or operations for this +// service. For service quotas, see EC2 Image Builder endpoints and quotas (https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder). +// // See also, https://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateDistributionConfiguration func (c *Imagebuilder) CreateDistributionConfiguration(input *CreateDistributionConfigurationInput) (*CreateDistributionConfigurationOutput, error) { req, out := c.CreateDistributionConfigurationRequest(input) @@ -424,6 +432,10 @@ func (c *Imagebuilder) CreateImageRequest(input *CreateImageInput) (req *request // The resource that you are trying to operate on is currently in use. Review // the message details and retry later. // +// * ServiceQuotaExceededException +// You have exceeded the number of permitted resources or operations for this +// service. For service quotas, see EC2 Image Builder endpoints and quotas (https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder). +// // See also, https://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateImage func (c *Imagebuilder) CreateImage(input *CreateImageInput) (*CreateImageOutput, error) { req, out := c.CreateImageRequest(input) @@ -532,6 +544,10 @@ func (c *Imagebuilder) CreateImagePipelineRequest(input *CreateImagePipelineInpu // * ResourceAlreadyExistsException // The resource that you are trying to create already exists. // +// * ServiceQuotaExceededException +// You have exceeded the number of permitted resources or operations for this +// service. For service quotas, see EC2 Image Builder endpoints and quotas (https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder). +// // See also, https://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateImagePipeline func (c *Imagebuilder) CreateImagePipeline(input *CreateImagePipelineInput) (*CreateImagePipelineOutput, error) { req, out := c.CreateImagePipelineRequest(input) @@ -643,6 +659,10 @@ func (c *Imagebuilder) CreateImageRecipeRequest(input *CreateImageRecipeInput) ( // * ResourceAlreadyExistsException // The resource that you are trying to create already exists. // +// * ServiceQuotaExceededException +// You have exceeded the number of permitted resources or operations for this +// service. For service quotas, see EC2 Image Builder endpoints and quotas (https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder). +// // See also, https://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateImageRecipe func (c *Imagebuilder) CreateImageRecipe(input *CreateImageRecipeInput) (*CreateImageRecipeOutput, error) { req, out := c.CreateImageRecipeRequest(input) @@ -751,6 +771,10 @@ func (c *Imagebuilder) CreateInfrastructureConfigurationRequest(input *CreateInf // * ResourceAlreadyExistsException // The resource that you are trying to create already exists. // +// * ServiceQuotaExceededException +// You have exceeded the number of permitted resources or operations for this +// service. For service quotas, see EC2 Image Builder endpoints and quotas (https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder). +// // See also, https://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/CreateInfrastructureConfiguration func (c *Imagebuilder) CreateInfrastructureConfiguration(input *CreateInfrastructureConfigurationInput) (*CreateInfrastructureConfigurationOutput, error) { req, out := c.CreateInfrastructureConfigurationRequest(input) @@ -2863,7 +2887,7 @@ func (c *Imagebuilder) ListImageBuildVersionsRequest(input *ListImageBuildVersio // ListImageBuildVersions API operation for EC2 Image Builder. // -// Returns a list of distribution configurations. +// Returns a list of image build versions. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3494,7 +3518,7 @@ func (c *Imagebuilder) ListImagesRequest(input *ListImagesInput) (req *request.R // ListImages API operation for EC2 Image Builder. // -// Returns the list of image build versions for the specified semantic version. +// Returns the list of images that you have access to. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4835,6 +4859,9 @@ type AmiDistributionConfiguration struct { // The description of the distribution configuration. Description *string `locationName:"description" min:"1" type:"string"` + // The KMS key identifier used to encrypt the distributed image. + KmsKeyId *string `locationName:"kmsKeyId" min:"1" type:"string"` + // Launch permissions can be used to configure which AWS accounts can use the // AMI to launch instances. LaunchPermission *LaunchPermissionConfiguration `locationName:"launchPermission" type:"structure"` @@ -4862,6 +4889,9 @@ func (s *AmiDistributionConfiguration) Validate() error { if s.Description != nil && len(*s.Description) < 1 { invalidParams.Add(request.NewErrParamMinLen("Description", 1)) } + if s.KmsKeyId != nil && len(*s.KmsKeyId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("KmsKeyId", 1)) + } if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } @@ -4884,6 +4914,12 @@ func (s *AmiDistributionConfiguration) SetDescription(v string) *AmiDistribution return s } +// SetKmsKeyId sets the KmsKeyId field's value. +func (s *AmiDistributionConfiguration) SetKmsKeyId(v string) *AmiDistributionConfiguration { + s.KmsKeyId = &v + return s +} + // SetLaunchPermission sets the LaunchPermission field's value. func (s *AmiDistributionConfiguration) SetLaunchPermission(v *LaunchPermissionConfiguration) *AmiDistributionConfiguration { s.LaunchPermission = v @@ -5135,6 +5171,11 @@ type Component struct { // The platform of the component. Platform *string `locationName:"platform" type:"string" enum:"Platform"` + // The operating system (OS) version supported by the component. If the OS information + // is available, a prefix match is performed against the parent image OS version + // during image recipe creation. + SupportedOsVersions []*string `locationName:"supportedOsVersions" min:"1" type:"list"` + // The tags associated with the component. Tags map[string]*string `locationName:"tags" min:"1" type:"map"` @@ -5216,6 +5257,12 @@ func (s *Component) SetPlatform(v string) *Component { return s } +// SetSupportedOsVersions sets the SupportedOsVersions field's value. +func (s *Component) SetSupportedOsVersions(v []*string) *Component { + s.SupportedOsVersions = v + return s +} + // SetTags sets the Tags field's value. func (s *Component) SetTags(v map[string]*string) *Component { s.Tags = v @@ -5298,6 +5345,11 @@ type ComponentSummary struct { // The platform of the component. Platform *string `locationName:"platform" type:"string" enum:"Platform"` + // The operating system (OS) version supported by the component. If the OS information + // is available, a prefix match is performed against the parent image OS version + // during image recipe creation. + SupportedOsVersions []*string `locationName:"supportedOsVersions" min:"1" type:"list"` + // The tags associated with the component. Tags map[string]*string `locationName:"tags" min:"1" type:"map"` @@ -5361,6 +5413,12 @@ func (s *ComponentSummary) SetPlatform(v string) *ComponentSummary { return s } +// SetSupportedOsVersions sets the SupportedOsVersions field's value. +func (s *ComponentSummary) SetSupportedOsVersions(v []*string) *ComponentSummary { + s.SupportedOsVersions = v + return s +} + // SetTags sets the Tags field's value. func (s *ComponentSummary) SetTags(v map[string]*string) *ComponentSummary { s.Tags = v @@ -5401,6 +5459,11 @@ type ComponentVersion struct { // The platform of the component. Platform *string `locationName:"platform" type:"string" enum:"Platform"` + // The operating system (OS) version supported by the component. If the OS information + // is available, a prefix match is performed against the parent image OS version + // during image recipe creation. + SupportedOsVersions []*string `locationName:"supportedOsVersions" min:"1" type:"list"` + // The type of the component denotes whether the component is used to build // the image or only to test it. Type *string `locationName:"type" type:"string" enum:"ComponentType"` @@ -5455,6 +5518,12 @@ func (s *ComponentVersion) SetPlatform(v string) *ComponentVersion { return s } +// SetSupportedOsVersions sets the SupportedOsVersions field's value. +func (s *ComponentVersion) SetSupportedOsVersions(v []*string) *ComponentVersion { + s.SupportedOsVersions = v + return s +} + // SetType sets the Type field's value. func (s *ComponentVersion) SetType(v string) *ComponentVersion { s.Type = &v @@ -5505,6 +5574,11 @@ type CreateComponentInput struct { // SemanticVersion is a required field SemanticVersion *string `locationName:"semanticVersion" type:"string" required:"true"` + // The operating system (OS) version supported by the component. If the OS information + // is available, a prefix match is performed against the parent image OS version + // during image recipe creation. + SupportedOsVersions []*string `locationName:"supportedOsVersions" min:"1" type:"list"` + // The tags of the component. Tags map[string]*string `locationName:"tags" min:"1" type:"map"` @@ -5552,6 +5626,9 @@ func (s *CreateComponentInput) Validate() error { if s.SemanticVersion == nil { invalidParams.Add(request.NewErrParamRequired("SemanticVersion")) } + if s.SupportedOsVersions != nil && len(s.SupportedOsVersions) < 1 { + invalidParams.Add(request.NewErrParamMinLen("SupportedOsVersions", 1)) + } if s.Tags != nil && len(s.Tags) < 1 { invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) } @@ -5610,6 +5687,12 @@ func (s *CreateComponentInput) SetSemanticVersion(v string) *CreateComponentInpu return s } +// SetSupportedOsVersions sets the SupportedOsVersions field's value. +func (s *CreateComponentInput) SetSupportedOsVersions(v []*string) *CreateComponentInput { + s.SupportedOsVersions = v + return s +} + // SetTags sets the Tags field's value. func (s *CreateComponentInput) SetTags(v map[string]*string) *CreateComponentInput { s.Tags = v @@ -6206,6 +6289,9 @@ type CreateImageRecipeInput struct { // The tags of the image recipe. Tags map[string]*string `locationName:"tags" min:"1" type:"map"` + + // The working directory to be used during build and test workflows. + WorkingDirectory *string `locationName:"workingDirectory" min:"1" type:"string"` } // String returns the string representation @@ -6248,6 +6334,9 @@ func (s *CreateImageRecipeInput) Validate() error { if s.Tags != nil && len(s.Tags) < 1 { invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) } + if s.WorkingDirectory != nil && len(*s.WorkingDirectory) < 1 { + invalidParams.Add(request.NewErrParamMinLen("WorkingDirectory", 1)) + } if s.BlockDeviceMappings != nil { for i, v := range s.BlockDeviceMappings { if v == nil { @@ -6323,6 +6412,12 @@ func (s *CreateImageRecipeInput) SetTags(v map[string]*string) *CreateImageRecip return s } +// SetWorkingDirectory sets the WorkingDirectory field's value. +func (s *CreateImageRecipeInput) SetWorkingDirectory(v string) *CreateImageRecipeInput { + s.WorkingDirectory = &v + return s +} + type CreateImageRecipeOutput struct { _ struct{} `type:"structure"` @@ -6397,6 +6492,9 @@ type CreateInfrastructureConfigurationInput struct { // Name is a required field Name *string `locationName:"name" type:"string" required:"true"` + // The tags attached to the resource created by Image Builder. + ResourceTags map[string]*string `locationName:"resourceTags" min:"1" type:"map"` + // The security group IDs to associate with the instance used to customize your // EC2 AMI. SecurityGroupIds []*string `locationName:"securityGroupIds" type:"list"` @@ -6447,6 +6545,9 @@ func (s *CreateInfrastructureConfigurationInput) Validate() error { if s.Name == nil { invalidParams.Add(request.NewErrParamRequired("Name")) } + if s.ResourceTags != nil && len(s.ResourceTags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceTags", 1)) + } if s.SubnetId != nil && len(*s.SubnetId) < 1 { invalidParams.Add(request.NewErrParamMinLen("SubnetId", 1)) } @@ -6507,6 +6608,12 @@ func (s *CreateInfrastructureConfigurationInput) SetName(v string) *CreateInfras return s } +// SetResourceTags sets the ResourceTags field's value. +func (s *CreateInfrastructureConfigurationInput) SetResourceTags(v map[string]*string) *CreateInfrastructureConfigurationInput { + s.ResourceTags = v + return s +} + // SetSecurityGroupIds sets the SecurityGroupIds field's value. func (s *CreateInfrastructureConfigurationInput) SetSecurityGroupIds(v []*string) *CreateInfrastructureConfigurationInput { s.SecurityGroupIds = v @@ -8487,6 +8594,9 @@ type ImageRecipe struct { // The version of the image recipe. Version *string `locationName:"version" type:"string"` + + // The working directory to be used during build and test workflows. + WorkingDirectory *string `locationName:"workingDirectory" min:"1" type:"string"` } // String returns the string representation @@ -8565,6 +8675,12 @@ func (s *ImageRecipe) SetVersion(v string) *ImageRecipe { return s } +// SetWorkingDirectory sets the WorkingDirectory field's value. +func (s *ImageRecipe) SetWorkingDirectory(v string) *ImageRecipe { + s.WorkingDirectory = &v + return s +} + // A summary of an image recipe. type ImageRecipeSummary struct { _ struct{} `type:"structure"` @@ -9163,6 +9279,9 @@ type InfrastructureConfiguration struct { // The name of the infrastructure configuration. Name *string `locationName:"name" type:"string"` + // The tags attached to the resource created by Image Builder. + ResourceTags map[string]*string `locationName:"resourceTags" min:"1" type:"map"` + // The security group IDs of the infrastructure configuration. SecurityGroupIds []*string `locationName:"securityGroupIds" type:"list"` @@ -9243,6 +9362,12 @@ func (s *InfrastructureConfiguration) SetName(v string) *InfrastructureConfigura return s } +// SetResourceTags sets the ResourceTags field's value. +func (s *InfrastructureConfiguration) SetResourceTags(v map[string]*string) *InfrastructureConfiguration { + s.ResourceTags = v + return s +} + // SetSecurityGroupIds sets the SecurityGroupIds field's value. func (s *InfrastructureConfiguration) SetSecurityGroupIds(v []*string) *InfrastructureConfiguration { s.SecurityGroupIds = v @@ -9292,6 +9417,9 @@ type InfrastructureConfigurationSummary struct { // The name of the infrastructure configuration. Name *string `locationName:"name" type:"string"` + // The tags attached to the image created by Image Builder. + ResourceTags map[string]*string `locationName:"resourceTags" min:"1" type:"map"` + // The tags of the infrastructure configuration. Tags map[string]*string `locationName:"tags" min:"1" type:"map"` } @@ -9336,6 +9464,12 @@ func (s *InfrastructureConfigurationSummary) SetName(v string) *InfrastructureCo return s } +// SetResourceTags sets the ResourceTags field's value. +func (s *InfrastructureConfigurationSummary) SetResourceTags(v map[string]*string) *InfrastructureConfigurationSummary { + s.ResourceTags = v + return s +} + // SetTags sets the Tags field's value. func (s *InfrastructureConfigurationSummary) SetTags(v map[string]*string) *InfrastructureConfigurationSummary { s.Tags = v @@ -9755,7 +9889,9 @@ func (s *InvalidVersionNumberException) RequestID() string { // Describes the configuration for a launch permission. The launch permission // modification request is sent to the EC2 ModifyImageAttribute (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyImageAttribute.html) // API on behalf of the user for each Region they have selected to distribute -// the AMI. +// the AMI. To make an AMI public, set the launch permission authorized accounts +// to all. See the examples for making an AMI public at EC2 ModifyImageAttribute +// (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyImageAttribute.html). type LaunchPermissionConfiguration struct { _ struct{} `type:"structure"` @@ -10025,6 +10161,8 @@ type ListDistributionConfigurationsInput struct { _ struct{} `type:"structure"` // The filters. + // + // * name - The name of this distribution configuration. Filters []*Filter `locationName:"filters" min:"1" type:"list"` // The maximum items to return in a request. @@ -11649,6 +11787,63 @@ func (s *ServiceException) RequestID() string { return s.RespMetadata.RequestID } +// You have exceeded the number of permitted resources or operations for this +// service. For service quotas, see EC2 Image Builder endpoints and quotas (https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder). +type ServiceQuotaExceededException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ServiceQuotaExceededException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ServiceQuotaExceededException) GoString() string { + return s.String() +} + +func newErrorServiceQuotaExceededException(v protocol.ResponseMetadata) error { + return &ServiceQuotaExceededException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ServiceQuotaExceededException) Code() string { + return "ServiceQuotaExceededException" +} + +// Message returns the exception's message. +func (s *ServiceQuotaExceededException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ServiceQuotaExceededException) OrigErr() error { + return nil +} + +func (s *ServiceQuotaExceededException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ServiceQuotaExceededException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ServiceQuotaExceededException) RequestID() string { + return s.RespMetadata.RequestID +} + // The service is unable to process your request at this time. type ServiceUnavailableException struct { _ struct{} `type:"structure"` @@ -12296,6 +12491,9 @@ type UpdateInfrastructureConfigurationInput struct { // The logging configuration of the infrastructure configuration. Logging *Logging `locationName:"logging" type:"structure"` + // The tags attached to the resource created by Image Builder. + ResourceTags map[string]*string `locationName:"resourceTags" min:"1" type:"map"` + // The security group IDs to associate with the instance used to customize your // EC2 AMI. SecurityGroupIds []*string `locationName:"securityGroupIds" type:"list"` @@ -12343,6 +12541,9 @@ func (s *UpdateInfrastructureConfigurationInput) Validate() error { if s.KeyPair != nil && len(*s.KeyPair) < 1 { invalidParams.Add(request.NewErrParamMinLen("KeyPair", 1)) } + if s.ResourceTags != nil && len(s.ResourceTags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceTags", 1)) + } if s.SubnetId != nil && len(*s.SubnetId) < 1 { invalidParams.Add(request.NewErrParamMinLen("SubnetId", 1)) } @@ -12400,6 +12601,12 @@ func (s *UpdateInfrastructureConfigurationInput) SetLogging(v *Logging) *UpdateI return s } +// SetResourceTags sets the ResourceTags field's value. +func (s *UpdateInfrastructureConfigurationInput) SetResourceTags(v map[string]*string) *UpdateInfrastructureConfigurationInput { + s.ResourceTags = v + return s +} + // SetSecurityGroupIds sets the SecurityGroupIds field's value. func (s *UpdateInfrastructureConfigurationInput) SetSecurityGroupIds(v []*string) *UpdateInfrastructureConfigurationInput { s.SecurityGroupIds = v @@ -12471,6 +12678,13 @@ const ( ComponentFormatShell = "SHELL" ) +// ComponentFormat_Values returns all elements of the ComponentFormat enum +func ComponentFormat_Values() []string { + return []string{ + ComponentFormatShell, + } +} + const ( // ComponentTypeBuild is a ComponentType enum value ComponentTypeBuild = "BUILD" @@ -12479,6 +12693,14 @@ const ( ComponentTypeTest = "TEST" ) +// ComponentType_Values returns all elements of the ComponentType enum +func ComponentType_Values() []string { + return []string{ + ComponentTypeBuild, + ComponentTypeTest, + } +} + const ( // EbsVolumeTypeStandard is a EbsVolumeType enum value EbsVolumeTypeStandard = "standard" @@ -12496,6 +12718,17 @@ const ( EbsVolumeTypeSt1 = "st1" ) +// EbsVolumeType_Values returns all elements of the EbsVolumeType enum +func EbsVolumeType_Values() []string { + return []string{ + EbsVolumeTypeStandard, + EbsVolumeTypeIo1, + EbsVolumeTypeGp2, + EbsVolumeTypeSc1, + EbsVolumeTypeSt1, + } +} + const ( // ImageStatusPending is a ImageStatus enum value ImageStatusPending = "PENDING" @@ -12531,6 +12764,23 @@ const ( ImageStatusDeleted = "DELETED" ) +// ImageStatus_Values returns all elements of the ImageStatus enum +func ImageStatus_Values() []string { + return []string{ + ImageStatusPending, + ImageStatusCreating, + ImageStatusBuilding, + ImageStatusTesting, + ImageStatusDistributing, + ImageStatusIntegrating, + ImageStatusAvailable, + ImageStatusCancelled, + ImageStatusFailed, + ImageStatusDeprecated, + ImageStatusDeleted, + } +} + const ( // OwnershipSelf is a Ownership enum value OwnershipSelf = "Self" @@ -12542,6 +12792,15 @@ const ( OwnershipAmazon = "Amazon" ) +// Ownership_Values returns all elements of the Ownership enum +func Ownership_Values() []string { + return []string{ + OwnershipSelf, + OwnershipShared, + OwnershipAmazon, + } +} + const ( // PipelineExecutionStartConditionExpressionMatchOnly is a PipelineExecutionStartCondition enum value PipelineExecutionStartConditionExpressionMatchOnly = "EXPRESSION_MATCH_ONLY" @@ -12550,6 +12809,14 @@ const ( PipelineExecutionStartConditionExpressionMatchAndDependencyUpdatesAvailable = "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE" ) +// PipelineExecutionStartCondition_Values returns all elements of the PipelineExecutionStartCondition enum +func PipelineExecutionStartCondition_Values() []string { + return []string{ + PipelineExecutionStartConditionExpressionMatchOnly, + PipelineExecutionStartConditionExpressionMatchAndDependencyUpdatesAvailable, + } +} + const ( // PipelineStatusDisabled is a PipelineStatus enum value PipelineStatusDisabled = "DISABLED" @@ -12558,6 +12825,14 @@ const ( PipelineStatusEnabled = "ENABLED" ) +// PipelineStatus_Values returns all elements of the PipelineStatus enum +func PipelineStatus_Values() []string { + return []string{ + PipelineStatusDisabled, + PipelineStatusEnabled, + } +} + const ( // PlatformWindows is a Platform enum value PlatformWindows = "Windows" @@ -12565,3 +12840,11 @@ const ( // PlatformLinux is a Platform enum value PlatformLinux = "Linux" ) + +// Platform_Values returns all elements of the Platform enum +func Platform_Values() []string { + return []string{ + PlatformWindows, + PlatformLinux, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/imagebuilder/errors.go b/vendor/github.com/aws/aws-sdk-go/service/imagebuilder/errors.go index 3f688043e53..d40ea63665e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/imagebuilder/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/imagebuilder/errors.go @@ -105,6 +105,13 @@ const ( // This exception is thrown when the service encounters an unrecoverable exception. ErrCodeServiceException = "ServiceException" + // ErrCodeServiceQuotaExceededException for service response error code + // "ServiceQuotaExceededException". + // + // You have exceeded the number of permitted resources or operations for this + // service. For service quotas, see EC2 Image Builder endpoints and quotas (https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder). + ErrCodeServiceQuotaExceededException = "ServiceQuotaExceededException" + // ErrCodeServiceUnavailableException for service response error code // "ServiceUnavailableException". // @@ -128,5 +135,6 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "ResourceInUseException": newErrorResourceInUseException, "ResourceNotFoundException": newErrorResourceNotFoundException, "ServiceException": newErrorServiceException, + "ServiceQuotaExceededException": newErrorServiceQuotaExceededException, "ServiceUnavailableException": newErrorServiceUnavailableException, } 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 f7e27d35cc4..bffa5642d2e 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 @@ -10339,6 +10339,20 @@ const ( AccessDeniedErrorCodeAccessDeniedToIamRole = "ACCESS_DENIED_TO_IAM_ROLE" ) +// AccessDeniedErrorCode_Values returns all elements of the AccessDeniedErrorCode enum +func AccessDeniedErrorCode_Values() []string { + return []string{ + AccessDeniedErrorCodeAccessDeniedToAssessmentTarget, + AccessDeniedErrorCodeAccessDeniedToAssessmentTemplate, + AccessDeniedErrorCodeAccessDeniedToAssessmentRun, + AccessDeniedErrorCodeAccessDeniedToFinding, + AccessDeniedErrorCodeAccessDeniedToResourceGroup, + AccessDeniedErrorCodeAccessDeniedToRulesPackage, + AccessDeniedErrorCodeAccessDeniedToSnsTopic, + AccessDeniedErrorCodeAccessDeniedToIamRole, + } +} + const ( // AgentHealthHealthy is a AgentHealth enum value AgentHealthHealthy = "HEALTHY" @@ -10350,6 +10364,15 @@ const ( AgentHealthUnknown = "UNKNOWN" ) +// AgentHealth_Values returns all elements of the AgentHealth enum +func AgentHealth_Values() []string { + return []string{ + AgentHealthHealthy, + AgentHealthUnhealthy, + AgentHealthUnknown, + } +} + const ( // AgentHealthCodeIdle is a AgentHealthCode enum value AgentHealthCodeIdle = "IDLE" @@ -10370,6 +10393,18 @@ const ( AgentHealthCodeUnknown = "UNKNOWN" ) +// AgentHealthCode_Values returns all elements of the AgentHealthCode enum +func AgentHealthCode_Values() []string { + return []string{ + AgentHealthCodeIdle, + AgentHealthCodeRunning, + AgentHealthCodeShutdown, + AgentHealthCodeUnhealthy, + AgentHealthCodeThrottled, + AgentHealthCodeUnknown, + } +} + const ( // AssessmentRunNotificationSnsStatusCodeSuccess is a AssessmentRunNotificationSnsStatusCode enum value AssessmentRunNotificationSnsStatusCodeSuccess = "SUCCESS" @@ -10384,6 +10419,16 @@ const ( AssessmentRunNotificationSnsStatusCodeInternalError = "INTERNAL_ERROR" ) +// AssessmentRunNotificationSnsStatusCode_Values returns all elements of the AssessmentRunNotificationSnsStatusCode enum +func AssessmentRunNotificationSnsStatusCode_Values() []string { + return []string{ + AssessmentRunNotificationSnsStatusCodeSuccess, + AssessmentRunNotificationSnsStatusCodeTopicDoesNotExist, + AssessmentRunNotificationSnsStatusCodeAccessDenied, + AssessmentRunNotificationSnsStatusCodeInternalError, + } +} + const ( // AssessmentRunStateCreated is a AssessmentRunState enum value AssessmentRunStateCreated = "CREATED" @@ -10425,11 +10470,37 @@ const ( AssessmentRunStateCanceled = "CANCELED" ) +// AssessmentRunState_Values returns all elements of the AssessmentRunState enum +func AssessmentRunState_Values() []string { + return []string{ + AssessmentRunStateCreated, + AssessmentRunStateStartDataCollectionPending, + AssessmentRunStateStartDataCollectionInProgress, + AssessmentRunStateCollectingData, + AssessmentRunStateStopDataCollectionPending, + AssessmentRunStateDataCollected, + AssessmentRunStateStartEvaluatingRulesPending, + AssessmentRunStateEvaluatingRules, + AssessmentRunStateFailed, + AssessmentRunStateError, + AssessmentRunStateCompleted, + AssessmentRunStateCompletedWithErrors, + AssessmentRunStateCanceled, + } +} + const ( // AssetTypeEc2Instance is a AssetType enum value AssetTypeEc2Instance = "ec2-instance" ) +// AssetType_Values returns all elements of the AssetType enum +func AssetType_Values() []string { + return []string{ + AssetTypeEc2Instance, + } +} + const ( // EventAssessmentRunStarted is a Event enum value EventAssessmentRunStarted = "ASSESSMENT_RUN_STARTED" @@ -10447,6 +10518,17 @@ const ( EventOther = "OTHER" ) +// Event_Values returns all elements of the Event enum +func Event_Values() []string { + return []string{ + EventAssessmentRunStarted, + EventAssessmentRunCompleted, + EventAssessmentRunStateChanged, + EventFindingReported, + EventOther, + } +} + const ( // FailedItemErrorCodeInvalidArn is a FailedItemErrorCode enum value FailedItemErrorCodeInvalidArn = "INVALID_ARN" @@ -10467,6 +10549,18 @@ const ( FailedItemErrorCodeInternalError = "INTERNAL_ERROR" ) +// FailedItemErrorCode_Values returns all elements of the FailedItemErrorCode enum +func FailedItemErrorCode_Values() []string { + return []string{ + FailedItemErrorCodeInvalidArn, + FailedItemErrorCodeDuplicateArn, + FailedItemErrorCodeItemDoesNotExist, + FailedItemErrorCodeAccessDenied, + FailedItemErrorCodeLimitExceeded, + FailedItemErrorCodeInternalError, + } +} + const ( // InvalidCrossAccountRoleErrorCodeRoleDoesNotExistOrInvalidTrustRelationship is a InvalidCrossAccountRoleErrorCode enum value InvalidCrossAccountRoleErrorCodeRoleDoesNotExistOrInvalidTrustRelationship = "ROLE_DOES_NOT_EXIST_OR_INVALID_TRUST_RELATIONSHIP" @@ -10475,6 +10569,14 @@ const ( InvalidCrossAccountRoleErrorCodeRoleDoesNotHaveCorrectPolicy = "ROLE_DOES_NOT_HAVE_CORRECT_POLICY" ) +// InvalidCrossAccountRoleErrorCode_Values returns all elements of the InvalidCrossAccountRoleErrorCode enum +func InvalidCrossAccountRoleErrorCode_Values() []string { + return []string{ + InvalidCrossAccountRoleErrorCodeRoleDoesNotExistOrInvalidTrustRelationship, + InvalidCrossAccountRoleErrorCodeRoleDoesNotHaveCorrectPolicy, + } +} + const ( // InvalidInputErrorCodeInvalidAssessmentTargetArn is a InvalidInputErrorCode enum value InvalidInputErrorCodeInvalidAssessmentTargetArn = "INVALID_ASSESSMENT_TARGET_ARN" @@ -10639,6 +10741,66 @@ const ( InvalidInputErrorCodeInvalidNumberOfSeverities = "INVALID_NUMBER_OF_SEVERITIES" ) +// InvalidInputErrorCode_Values returns all elements of the InvalidInputErrorCode enum +func InvalidInputErrorCode_Values() []string { + return []string{ + InvalidInputErrorCodeInvalidAssessmentTargetArn, + InvalidInputErrorCodeInvalidAssessmentTemplateArn, + InvalidInputErrorCodeInvalidAssessmentRunArn, + InvalidInputErrorCodeInvalidFindingArn, + InvalidInputErrorCodeInvalidResourceGroupArn, + InvalidInputErrorCodeInvalidRulesPackageArn, + InvalidInputErrorCodeInvalidResourceArn, + InvalidInputErrorCodeInvalidSnsTopicArn, + InvalidInputErrorCodeInvalidIamRoleArn, + InvalidInputErrorCodeInvalidAssessmentTargetName, + InvalidInputErrorCodeInvalidAssessmentTargetNamePattern, + InvalidInputErrorCodeInvalidAssessmentTemplateName, + InvalidInputErrorCodeInvalidAssessmentTemplateNamePattern, + InvalidInputErrorCodeInvalidAssessmentTemplateDuration, + InvalidInputErrorCodeInvalidAssessmentTemplateDurationRange, + InvalidInputErrorCodeInvalidAssessmentRunDurationRange, + InvalidInputErrorCodeInvalidAssessmentRunStartTimeRange, + InvalidInputErrorCodeInvalidAssessmentRunCompletionTimeRange, + InvalidInputErrorCodeInvalidAssessmentRunStateChangeTimeRange, + InvalidInputErrorCodeInvalidAssessmentRunState, + InvalidInputErrorCodeInvalidTag, + InvalidInputErrorCodeInvalidTagKey, + InvalidInputErrorCodeInvalidTagValue, + InvalidInputErrorCodeInvalidResourceGroupTagKey, + InvalidInputErrorCodeInvalidResourceGroupTagValue, + InvalidInputErrorCodeInvalidAttribute, + InvalidInputErrorCodeInvalidUserAttribute, + InvalidInputErrorCodeInvalidUserAttributeKey, + InvalidInputErrorCodeInvalidUserAttributeValue, + InvalidInputErrorCodeInvalidPaginationToken, + InvalidInputErrorCodeInvalidMaxResults, + InvalidInputErrorCodeInvalidAgentId, + InvalidInputErrorCodeInvalidAutoScalingGroup, + InvalidInputErrorCodeInvalidRuleName, + InvalidInputErrorCodeInvalidSeverity, + InvalidInputErrorCodeInvalidLocale, + InvalidInputErrorCodeInvalidEvent, + InvalidInputErrorCodeAssessmentTargetNameAlreadyTaken, + InvalidInputErrorCodeAssessmentTemplateNameAlreadyTaken, + InvalidInputErrorCodeInvalidNumberOfAssessmentTargetArns, + InvalidInputErrorCodeInvalidNumberOfAssessmentTemplateArns, + InvalidInputErrorCodeInvalidNumberOfAssessmentRunArns, + InvalidInputErrorCodeInvalidNumberOfFindingArns, + InvalidInputErrorCodeInvalidNumberOfResourceGroupArns, + InvalidInputErrorCodeInvalidNumberOfRulesPackageArns, + InvalidInputErrorCodeInvalidNumberOfAssessmentRunStates, + InvalidInputErrorCodeInvalidNumberOfTags, + InvalidInputErrorCodeInvalidNumberOfResourceGroupTags, + InvalidInputErrorCodeInvalidNumberOfAttributes, + InvalidInputErrorCodeInvalidNumberOfUserAttributes, + InvalidInputErrorCodeInvalidNumberOfAgentIds, + InvalidInputErrorCodeInvalidNumberOfAutoScalingGroups, + InvalidInputErrorCodeInvalidNumberOfRuleNames, + InvalidInputErrorCodeInvalidNumberOfSeverities, + } +} + const ( // LimitExceededErrorCodeAssessmentTargetLimitExceeded is a LimitExceededErrorCode enum value LimitExceededErrorCodeAssessmentTargetLimitExceeded = "ASSESSMENT_TARGET_LIMIT_EXCEEDED" @@ -10656,11 +10818,29 @@ const ( LimitExceededErrorCodeEventSubscriptionLimitExceeded = "EVENT_SUBSCRIPTION_LIMIT_EXCEEDED" ) +// LimitExceededErrorCode_Values returns all elements of the LimitExceededErrorCode enum +func LimitExceededErrorCode_Values() []string { + return []string{ + LimitExceededErrorCodeAssessmentTargetLimitExceeded, + LimitExceededErrorCodeAssessmentTemplateLimitExceeded, + LimitExceededErrorCodeAssessmentRunLimitExceeded, + LimitExceededErrorCodeResourceGroupLimitExceeded, + LimitExceededErrorCodeEventSubscriptionLimitExceeded, + } +} + const ( // LocaleEnUs is a Locale enum value LocaleEnUs = "EN_US" ) +// Locale_Values returns all elements of the Locale enum +func Locale_Values() []string { + return []string{ + LocaleEnUs, + } +} + const ( // NoSuchEntityErrorCodeAssessmentTargetDoesNotExist is a NoSuchEntityErrorCode enum value NoSuchEntityErrorCodeAssessmentTargetDoesNotExist = "ASSESSMENT_TARGET_DOES_NOT_EXIST" @@ -10687,6 +10867,20 @@ const ( NoSuchEntityErrorCodeIamRoleDoesNotExist = "IAM_ROLE_DOES_NOT_EXIST" ) +// NoSuchEntityErrorCode_Values returns all elements of the NoSuchEntityErrorCode enum +func NoSuchEntityErrorCode_Values() []string { + return []string{ + NoSuchEntityErrorCodeAssessmentTargetDoesNotExist, + NoSuchEntityErrorCodeAssessmentTemplateDoesNotExist, + NoSuchEntityErrorCodeAssessmentRunDoesNotExist, + NoSuchEntityErrorCodeFindingDoesNotExist, + NoSuchEntityErrorCodeResourceGroupDoesNotExist, + NoSuchEntityErrorCodeRulesPackageDoesNotExist, + NoSuchEntityErrorCodeSnsTopicDoesNotExist, + NoSuchEntityErrorCodeIamRoleDoesNotExist, + } +} + const ( // PreviewStatusWorkInProgress is a PreviewStatus enum value PreviewStatusWorkInProgress = "WORK_IN_PROGRESS" @@ -10695,6 +10889,14 @@ const ( PreviewStatusCompleted = "COMPLETED" ) +// PreviewStatus_Values returns all elements of the PreviewStatus enum +func PreviewStatus_Values() []string { + return []string{ + PreviewStatusWorkInProgress, + PreviewStatusCompleted, + } +} + const ( // ReportFileFormatHtml is a ReportFileFormat enum value ReportFileFormatHtml = "HTML" @@ -10703,6 +10905,14 @@ const ( ReportFileFormatPdf = "PDF" ) +// ReportFileFormat_Values returns all elements of the ReportFileFormat enum +func ReportFileFormat_Values() []string { + return []string{ + ReportFileFormatHtml, + ReportFileFormatPdf, + } +} + const ( // ReportStatusWorkInProgress is a ReportStatus enum value ReportStatusWorkInProgress = "WORK_IN_PROGRESS" @@ -10714,6 +10924,15 @@ const ( ReportStatusCompleted = "COMPLETED" ) +// ReportStatus_Values returns all elements of the ReportStatus enum +func ReportStatus_Values() []string { + return []string{ + ReportStatusWorkInProgress, + ReportStatusFailed, + ReportStatusCompleted, + } +} + const ( // ReportTypeFinding is a ReportType enum value ReportTypeFinding = "FINDING" @@ -10722,6 +10941,14 @@ const ( ReportTypeFull = "FULL" ) +// ReportType_Values returns all elements of the ReportType enum +func ReportType_Values() []string { + return []string{ + ReportTypeFinding, + ReportTypeFull, + } +} + const ( // ScopeTypeInstanceId is a ScopeType enum value ScopeTypeInstanceId = "INSTANCE_ID" @@ -10730,6 +10957,14 @@ const ( ScopeTypeRulesPackageArn = "RULES_PACKAGE_ARN" ) +// ScopeType_Values returns all elements of the ScopeType enum +func ScopeType_Values() []string { + return []string{ + ScopeTypeInstanceId, + ScopeTypeRulesPackageArn, + } +} + const ( // SeverityLow is a Severity enum value SeverityLow = "Low" @@ -10747,6 +10982,17 @@ const ( SeverityUndefined = "Undefined" ) +// Severity_Values returns all elements of the Severity enum +func Severity_Values() []string { + return []string{ + SeverityLow, + SeverityMedium, + SeverityHigh, + SeverityInformational, + SeverityUndefined, + } +} + const ( // StopActionStartEvaluation is a StopAction enum value StopActionStartEvaluation = "START_EVALUATION" @@ -10754,3 +11000,11 @@ const ( // StopActionSkipEvaluation is a StopAction enum value StopActionSkipEvaluation = "SKIP_EVALUATION" ) + +// StopAction_Values returns all elements of the StopAction enum +func StopAction_Values() []string { + return []string{ + StopActionStartEvaluation, + StopActionSkipEvaluation, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/iot/api.go b/vendor/github.com/aws/aws-sdk-go/service/iot/api.go index 0a75d6e8d41..0c4177de470 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iot/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iot/api.go @@ -1417,6 +1417,95 @@ func (c *IoT) ConfirmTopicRuleDestinationWithContext(ctx aws.Context, input *Con return out, req.Send() } +const opCreateAuditSuppression = "CreateAuditSuppression" + +// CreateAuditSuppressionRequest generates a "aws/request.Request" representing the +// client's request for the CreateAuditSuppression operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateAuditSuppression for more information on using the CreateAuditSuppression +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateAuditSuppressionRequest method. +// req, resp := client.CreateAuditSuppressionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *IoT) CreateAuditSuppressionRequest(input *CreateAuditSuppressionInput) (req *request.Request, output *CreateAuditSuppressionOutput) { + op := &request.Operation{ + Name: opCreateAuditSuppression, + HTTPMethod: "POST", + HTTPPath: "/audit/suppressions/create", + } + + if input == nil { + input = &CreateAuditSuppressionInput{} + } + + output = &CreateAuditSuppressionOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// CreateAuditSuppression API operation for AWS IoT. +// +// Creates a Device Defender audit suppression. +// +// Returns awserr.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 IoT's +// API operation CreateAuditSuppression for usage and error information. +// +// Returned Error Types: +// * InvalidRequestException +// The request is not valid. +// +// * ResourceAlreadyExistsException +// The resource already exists. +// +// * ThrottlingException +// The rate exceeds the limit. +// +// * InternalFailureException +// An unexpected error has occurred. +// +// * LimitExceededException +// A limit has been exceeded. +// +func (c *IoT) CreateAuditSuppression(input *CreateAuditSuppressionInput) (*CreateAuditSuppressionOutput, error) { + req, out := c.CreateAuditSuppressionRequest(input) + return out, req.Send() +} + +// CreateAuditSuppressionWithContext is the same as CreateAuditSuppression with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAuditSuppression for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) CreateAuditSuppressionWithContext(ctx aws.Context, input *CreateAuditSuppressionInput, opts ...request.Option) (*CreateAuditSuppressionOutput, error) { + req, out := c.CreateAuditSuppressionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateAuthorizer = "CreateAuthorizer" // CreateAuthorizerRequest generates a "aws/request.Request" representing the @@ -2236,6 +2325,8 @@ func (c *IoT) CreateMitigationActionRequest(input *CreateMitigationActionInput) // CreateMitigationAction API operation for AWS IoT. // // Defines an action that can be applied to audit findings by using StartAuditMitigationActionsTask. +// Only certain types of mitigation actions can be applied to specific check +// names. For more information, see Mitigation actions (https://docs.aws.amazon.com/iot/latest/developerguide/device-defender-mitigation-actions.html). // Each mitigation action can apply only one type of change. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -3776,6 +3867,89 @@ func (c *IoT) DeleteAccountAuditConfigurationWithContext(ctx aws.Context, input return out, req.Send() } +const opDeleteAuditSuppression = "DeleteAuditSuppression" + +// DeleteAuditSuppressionRequest generates a "aws/request.Request" representing the +// client's request for the DeleteAuditSuppression operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteAuditSuppression for more information on using the DeleteAuditSuppression +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteAuditSuppressionRequest method. +// req, resp := client.DeleteAuditSuppressionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *IoT) DeleteAuditSuppressionRequest(input *DeleteAuditSuppressionInput) (req *request.Request, output *DeleteAuditSuppressionOutput) { + op := &request.Operation{ + Name: opDeleteAuditSuppression, + HTTPMethod: "POST", + HTTPPath: "/audit/suppressions/delete", + } + + if input == nil { + input = &DeleteAuditSuppressionInput{} + } + + output = &DeleteAuditSuppressionOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteAuditSuppression API operation for AWS IoT. +// +// Deletes a Device Defender audit suppression. +// +// Returns awserr.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 IoT's +// API operation DeleteAuditSuppression for usage and error information. +// +// Returned Error Types: +// * InvalidRequestException +// The request is not valid. +// +// * ThrottlingException +// The rate exceeds the limit. +// +// * InternalFailureException +// An unexpected error has occurred. +// +func (c *IoT) DeleteAuditSuppression(input *DeleteAuditSuppressionInput) (*DeleteAuditSuppressionOutput, error) { + req, out := c.DeleteAuditSuppressionRequest(input) + return out, req.Send() +} + +// DeleteAuditSuppressionWithContext is the same as DeleteAuditSuppression with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAuditSuppression for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) DeleteAuditSuppressionWithContext(ctx aws.Context, input *DeleteAuditSuppressionInput, opts ...request.Option) (*DeleteAuditSuppressionOutput, error) { + req, out := c.DeleteAuditSuppressionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteAuthorizer = "DeleteAuthorizer" // DeleteAuthorizerRequest generates a "aws/request.Request" representing the @@ -6524,6 +6698,91 @@ func (c *IoT) DescribeAuditMitigationActionsTaskWithContext(ctx aws.Context, inp return out, req.Send() } +const opDescribeAuditSuppression = "DescribeAuditSuppression" + +// DescribeAuditSuppressionRequest generates a "aws/request.Request" representing the +// client's request for the DescribeAuditSuppression operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeAuditSuppression for more information on using the DescribeAuditSuppression +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeAuditSuppressionRequest method. +// req, resp := client.DescribeAuditSuppressionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *IoT) DescribeAuditSuppressionRequest(input *DescribeAuditSuppressionInput) (req *request.Request, output *DescribeAuditSuppressionOutput) { + op := &request.Operation{ + Name: opDescribeAuditSuppression, + HTTPMethod: "POST", + HTTPPath: "/audit/suppressions/describe", + } + + if input == nil { + input = &DescribeAuditSuppressionInput{} + } + + output = &DescribeAuditSuppressionOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeAuditSuppression API operation for AWS IoT. +// +// Gets information about a Device Defender audit suppression. +// +// Returns awserr.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 IoT's +// API operation DescribeAuditSuppression for usage and error information. +// +// Returned Error Types: +// * InvalidRequestException +// The request is not valid. +// +// * ResourceNotFoundException +// The specified resource does not exist. +// +// * ThrottlingException +// The rate exceeds the limit. +// +// * InternalFailureException +// An unexpected error has occurred. +// +func (c *IoT) DescribeAuditSuppression(input *DescribeAuditSuppressionInput) (*DescribeAuditSuppressionOutput, error) { + req, out := c.DescribeAuditSuppressionRequest(input) + return out, req.Send() +} + +// DescribeAuditSuppressionWithContext is the same as DescribeAuditSuppression with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeAuditSuppression for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) DescribeAuditSuppressionWithContext(ctx aws.Context, input *DescribeAuditSuppressionInput, opts ...request.Option) (*DescribeAuditSuppressionOutput, error) { + req, out := c.DescribeAuditSuppressionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeAuditTask = "DescribeAuditTask" // DescribeAuditTaskRequest generates a "aws/request.Request" representing the @@ -10494,6 +10753,12 @@ func (c *IoT) ListActiveViolationsRequest(input *ListActiveViolationsInput) (req Name: opListActiveViolations, HTTPMethod: "GET", HTTPPath: "/active-violations", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -10550,6 +10815,58 @@ func (c *IoT) ListActiveViolationsWithContext(ctx aws.Context, input *ListActive return out, req.Send() } +// ListActiveViolationsPages iterates over the pages of a ListActiveViolations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListActiveViolations 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 ListActiveViolations operation. +// pageNum := 0 +// err := client.ListActiveViolationsPages(params, +// func(page *iot.ListActiveViolationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListActiveViolationsPages(input *ListActiveViolationsInput, fn func(*ListActiveViolationsOutput, bool) bool) error { + return c.ListActiveViolationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListActiveViolationsPagesWithContext same as ListActiveViolationsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListActiveViolationsPagesWithContext(ctx aws.Context, input *ListActiveViolationsInput, fn func(*ListActiveViolationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListActiveViolationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListActiveViolationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListActiveViolationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListAttachedPolicies = "ListAttachedPolicies" // ListAttachedPoliciesRequest generates a "aws/request.Request" representing the @@ -10579,6 +10896,12 @@ func (c *IoT) ListAttachedPoliciesRequest(input *ListAttachedPoliciesInput) (req Name: opListAttachedPolicies, HTTPMethod: "POST", HTTPPath: "/attached-policies/{target}", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -10644,6 +10967,58 @@ func (c *IoT) ListAttachedPoliciesWithContext(ctx aws.Context, input *ListAttach return out, req.Send() } +// ListAttachedPoliciesPages iterates over the pages of a ListAttachedPolicies operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListAttachedPolicies 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 ListAttachedPolicies operation. +// pageNum := 0 +// err := client.ListAttachedPoliciesPages(params, +// func(page *iot.ListAttachedPoliciesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListAttachedPoliciesPages(input *ListAttachedPoliciesInput, fn func(*ListAttachedPoliciesOutput, bool) bool) error { + return c.ListAttachedPoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAttachedPoliciesPagesWithContext same as ListAttachedPoliciesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListAttachedPoliciesPagesWithContext(ctx aws.Context, input *ListAttachedPoliciesInput, fn func(*ListAttachedPoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAttachedPoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAttachedPoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListAttachedPoliciesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListAuditFindings = "ListAuditFindings" // ListAuditFindingsRequest generates a "aws/request.Request" representing the @@ -10673,6 +11048,12 @@ func (c *IoT) ListAuditFindingsRequest(input *ListAuditFindingsInput) (req *requ Name: opListAuditFindings, HTTPMethod: "POST", HTTPPath: "/audit/findings", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -10728,6 +11109,58 @@ func (c *IoT) ListAuditFindingsWithContext(ctx aws.Context, input *ListAuditFind return out, req.Send() } +// ListAuditFindingsPages iterates over the pages of a ListAuditFindings operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListAuditFindings 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 ListAuditFindings operation. +// pageNum := 0 +// err := client.ListAuditFindingsPages(params, +// func(page *iot.ListAuditFindingsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListAuditFindingsPages(input *ListAuditFindingsInput, fn func(*ListAuditFindingsOutput, bool) bool) error { + return c.ListAuditFindingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAuditFindingsPagesWithContext same as ListAuditFindingsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListAuditFindingsPagesWithContext(ctx aws.Context, input *ListAuditFindingsInput, fn func(*ListAuditFindingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAuditFindingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAuditFindingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListAuditFindingsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListAuditMitigationActionsExecutions = "ListAuditMitigationActionsExecutions" // ListAuditMitigationActionsExecutionsRequest generates a "aws/request.Request" representing the @@ -10757,6 +11190,12 @@ func (c *IoT) ListAuditMitigationActionsExecutionsRequest(input *ListAuditMitiga Name: opListAuditMitigationActionsExecutions, HTTPMethod: "GET", HTTPPath: "/audit/mitigationactions/executions", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -10810,6 +11249,58 @@ func (c *IoT) ListAuditMitigationActionsExecutionsWithContext(ctx aws.Context, i return out, req.Send() } +// ListAuditMitigationActionsExecutionsPages iterates over the pages of a ListAuditMitigationActionsExecutions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListAuditMitigationActionsExecutions 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 ListAuditMitigationActionsExecutions operation. +// pageNum := 0 +// err := client.ListAuditMitigationActionsExecutionsPages(params, +// func(page *iot.ListAuditMitigationActionsExecutionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListAuditMitigationActionsExecutionsPages(input *ListAuditMitigationActionsExecutionsInput, fn func(*ListAuditMitigationActionsExecutionsOutput, bool) bool) error { + return c.ListAuditMitigationActionsExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAuditMitigationActionsExecutionsPagesWithContext same as ListAuditMitigationActionsExecutionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListAuditMitigationActionsExecutionsPagesWithContext(ctx aws.Context, input *ListAuditMitigationActionsExecutionsInput, fn func(*ListAuditMitigationActionsExecutionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAuditMitigationActionsExecutionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAuditMitigationActionsExecutionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListAuditMitigationActionsExecutionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListAuditMitigationActionsTasks = "ListAuditMitigationActionsTasks" // ListAuditMitigationActionsTasksRequest generates a "aws/request.Request" representing the @@ -10839,6 +11330,12 @@ func (c *IoT) ListAuditMitigationActionsTasksRequest(input *ListAuditMitigationA Name: opListAuditMitigationActionsTasks, HTTPMethod: "GET", HTTPPath: "/audit/mitigationactions/tasks", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -10892,6 +11389,198 @@ func (c *IoT) ListAuditMitigationActionsTasksWithContext(ctx aws.Context, input return out, req.Send() } +// ListAuditMitigationActionsTasksPages iterates over the pages of a ListAuditMitigationActionsTasks operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListAuditMitigationActionsTasks 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 ListAuditMitigationActionsTasks operation. +// pageNum := 0 +// err := client.ListAuditMitigationActionsTasksPages(params, +// func(page *iot.ListAuditMitigationActionsTasksOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListAuditMitigationActionsTasksPages(input *ListAuditMitigationActionsTasksInput, fn func(*ListAuditMitigationActionsTasksOutput, bool) bool) error { + return c.ListAuditMitigationActionsTasksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAuditMitigationActionsTasksPagesWithContext same as ListAuditMitigationActionsTasksPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListAuditMitigationActionsTasksPagesWithContext(ctx aws.Context, input *ListAuditMitigationActionsTasksInput, fn func(*ListAuditMitigationActionsTasksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAuditMitigationActionsTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAuditMitigationActionsTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListAuditMitigationActionsTasksOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListAuditSuppressions = "ListAuditSuppressions" + +// ListAuditSuppressionsRequest generates a "aws/request.Request" representing the +// client's request for the ListAuditSuppressions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListAuditSuppressions for more information on using the ListAuditSuppressions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListAuditSuppressionsRequest method. +// req, resp := client.ListAuditSuppressionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *IoT) ListAuditSuppressionsRequest(input *ListAuditSuppressionsInput) (req *request.Request, output *ListAuditSuppressionsOutput) { + op := &request.Operation{ + Name: opListAuditSuppressions, + HTTPMethod: "POST", + HTTPPath: "/audit/suppressions/list", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListAuditSuppressionsInput{} + } + + output = &ListAuditSuppressionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListAuditSuppressions API operation for AWS IoT. +// +// Lists your Device Defender audit listings. +// +// Returns awserr.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 IoT's +// API operation ListAuditSuppressions for usage and error information. +// +// Returned Error Types: +// * InvalidRequestException +// The request is not valid. +// +// * ThrottlingException +// The rate exceeds the limit. +// +// * InternalFailureException +// An unexpected error has occurred. +// +func (c *IoT) ListAuditSuppressions(input *ListAuditSuppressionsInput) (*ListAuditSuppressionsOutput, error) { + req, out := c.ListAuditSuppressionsRequest(input) + return out, req.Send() +} + +// ListAuditSuppressionsWithContext is the same as ListAuditSuppressions with the addition of +// the ability to pass a context and additional request options. +// +// See ListAuditSuppressions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListAuditSuppressionsWithContext(ctx aws.Context, input *ListAuditSuppressionsInput, opts ...request.Option) (*ListAuditSuppressionsOutput, error) { + req, out := c.ListAuditSuppressionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListAuditSuppressionsPages iterates over the pages of a ListAuditSuppressions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListAuditSuppressions 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 ListAuditSuppressions operation. +// pageNum := 0 +// err := client.ListAuditSuppressionsPages(params, +// func(page *iot.ListAuditSuppressionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListAuditSuppressionsPages(input *ListAuditSuppressionsInput, fn func(*ListAuditSuppressionsOutput, bool) bool) error { + return c.ListAuditSuppressionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAuditSuppressionsPagesWithContext same as ListAuditSuppressionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListAuditSuppressionsPagesWithContext(ctx aws.Context, input *ListAuditSuppressionsInput, fn func(*ListAuditSuppressionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAuditSuppressionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAuditSuppressionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListAuditSuppressionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListAuditTasks = "ListAuditTasks" // ListAuditTasksRequest generates a "aws/request.Request" representing the @@ -10921,6 +11610,12 @@ func (c *IoT) ListAuditTasksRequest(input *ListAuditTasksInput) (req *request.Re Name: opListAuditTasks, HTTPMethod: "GET", HTTPPath: "/audit/tasks", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -10975,6 +11670,58 @@ func (c *IoT) ListAuditTasksWithContext(ctx aws.Context, input *ListAuditTasksIn return out, req.Send() } +// ListAuditTasksPages iterates over the pages of a ListAuditTasks operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListAuditTasks 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 ListAuditTasks operation. +// pageNum := 0 +// err := client.ListAuditTasksPages(params, +// func(page *iot.ListAuditTasksOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListAuditTasksPages(input *ListAuditTasksInput, fn func(*ListAuditTasksOutput, bool) bool) error { + return c.ListAuditTasksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAuditTasksPagesWithContext same as ListAuditTasksPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListAuditTasksPagesWithContext(ctx aws.Context, input *ListAuditTasksInput, fn func(*ListAuditTasksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAuditTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAuditTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListAuditTasksOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListAuthorizers = "ListAuthorizers" // ListAuthorizersRequest generates a "aws/request.Request" representing the @@ -11004,6 +11751,12 @@ func (c *IoT) ListAuthorizersRequest(input *ListAuthorizersInput) (req *request. Name: opListAuthorizers, HTTPMethod: "GET", HTTPPath: "/authorizers/", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -11063,6 +11816,58 @@ func (c *IoT) ListAuthorizersWithContext(ctx aws.Context, input *ListAuthorizers return out, req.Send() } +// ListAuthorizersPages iterates over the pages of a ListAuthorizers operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListAuthorizers 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 ListAuthorizers operation. +// pageNum := 0 +// err := client.ListAuthorizersPages(params, +// func(page *iot.ListAuthorizersOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListAuthorizersPages(input *ListAuthorizersInput, fn func(*ListAuthorizersOutput, bool) bool) error { + return c.ListAuthorizersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAuthorizersPagesWithContext same as ListAuthorizersPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListAuthorizersPagesWithContext(ctx aws.Context, input *ListAuthorizersInput, fn func(*ListAuthorizersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAuthorizersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAuthorizersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListAuthorizersOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListBillingGroups = "ListBillingGroups" // ListBillingGroupsRequest generates a "aws/request.Request" representing the @@ -11092,6 +11897,12 @@ func (c *IoT) ListBillingGroupsRequest(input *ListBillingGroupsInput) (req *requ Name: opListBillingGroups, HTTPMethod: "GET", HTTPPath: "/billing-groups", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -11148,6 +11959,58 @@ func (c *IoT) ListBillingGroupsWithContext(ctx aws.Context, input *ListBillingGr return out, req.Send() } +// ListBillingGroupsPages iterates over the pages of a ListBillingGroups operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListBillingGroups 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 ListBillingGroups operation. +// pageNum := 0 +// err := client.ListBillingGroupsPages(params, +// func(page *iot.ListBillingGroupsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListBillingGroupsPages(input *ListBillingGroupsInput, fn func(*ListBillingGroupsOutput, bool) bool) error { + return c.ListBillingGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListBillingGroupsPagesWithContext same as ListBillingGroupsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListBillingGroupsPagesWithContext(ctx aws.Context, input *ListBillingGroupsInput, fn func(*ListBillingGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListBillingGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListBillingGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListBillingGroupsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListCACertificates = "ListCACertificates" // ListCACertificatesRequest generates a "aws/request.Request" representing the @@ -11177,6 +12040,12 @@ func (c *IoT) ListCACertificatesRequest(input *ListCACertificatesInput) (req *re Name: opListCACertificates, HTTPMethod: "GET", HTTPPath: "/cacertificates", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -11239,6 +12108,58 @@ func (c *IoT) ListCACertificatesWithContext(ctx aws.Context, input *ListCACertif return out, req.Send() } +// ListCACertificatesPages iterates over the pages of a ListCACertificates operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListCACertificates 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 ListCACertificates operation. +// pageNum := 0 +// err := client.ListCACertificatesPages(params, +// func(page *iot.ListCACertificatesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListCACertificatesPages(input *ListCACertificatesInput, fn func(*ListCACertificatesOutput, bool) bool) error { + return c.ListCACertificatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListCACertificatesPagesWithContext same as ListCACertificatesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListCACertificatesPagesWithContext(ctx aws.Context, input *ListCACertificatesInput, fn func(*ListCACertificatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListCACertificatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListCACertificatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListCACertificatesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListCertificates = "ListCertificates" // ListCertificatesRequest generates a "aws/request.Request" representing the @@ -11268,6 +12189,12 @@ func (c *IoT) ListCertificatesRequest(input *ListCertificatesInput) (req *reques Name: opListCertificates, HTTPMethod: "GET", HTTPPath: "/certificates", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -11330,6 +12257,58 @@ func (c *IoT) ListCertificatesWithContext(ctx aws.Context, input *ListCertificat return out, req.Send() } +// ListCertificatesPages iterates over the pages of a ListCertificates operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListCertificates 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 ListCertificates operation. +// pageNum := 0 +// err := client.ListCertificatesPages(params, +// func(page *iot.ListCertificatesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) 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 *IoT) 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 + }, + } + + for p.Next() { + if !fn(p.Page().(*ListCertificatesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListCertificatesByCA = "ListCertificatesByCA" // ListCertificatesByCARequest generates a "aws/request.Request" representing the @@ -11359,6 +12338,12 @@ func (c *IoT) ListCertificatesByCARequest(input *ListCertificatesByCAInput) (req Name: opListCertificatesByCA, HTTPMethod: "GET", HTTPPath: "/certificates-by-ca/{caCertificateId}", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -11418,6 +12403,58 @@ func (c *IoT) ListCertificatesByCAWithContext(ctx aws.Context, input *ListCertif return out, req.Send() } +// ListCertificatesByCAPages iterates over the pages of a ListCertificatesByCA operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListCertificatesByCA 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 ListCertificatesByCA operation. +// pageNum := 0 +// err := client.ListCertificatesByCAPages(params, +// func(page *iot.ListCertificatesByCAOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListCertificatesByCAPages(input *ListCertificatesByCAInput, fn func(*ListCertificatesByCAOutput, bool) bool) error { + return c.ListCertificatesByCAPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListCertificatesByCAPagesWithContext same as ListCertificatesByCAPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListCertificatesByCAPagesWithContext(ctx aws.Context, input *ListCertificatesByCAInput, fn func(*ListCertificatesByCAOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListCertificatesByCAInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListCertificatesByCARequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListCertificatesByCAOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListDimensions = "ListDimensions" // ListDimensionsRequest generates a "aws/request.Request" representing the @@ -11447,6 +12484,12 @@ func (c *IoT) ListDimensionsRequest(input *ListDimensionsInput) (req *request.Re Name: opListDimensions, HTTPMethod: "GET", HTTPPath: "/dimensions", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -11500,6 +12543,58 @@ func (c *IoT) ListDimensionsWithContext(ctx aws.Context, input *ListDimensionsIn return out, req.Send() } +// ListDimensionsPages iterates over the pages of a ListDimensions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListDimensions 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 ListDimensions operation. +// pageNum := 0 +// err := client.ListDimensionsPages(params, +// func(page *iot.ListDimensionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListDimensionsPages(input *ListDimensionsInput, fn func(*ListDimensionsOutput, bool) bool) error { + return c.ListDimensionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDimensionsPagesWithContext same as ListDimensionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListDimensionsPagesWithContext(ctx aws.Context, input *ListDimensionsInput, fn func(*ListDimensionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDimensionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDimensionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListDimensionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListDomainConfigurations = "ListDomainConfigurations" // ListDomainConfigurationsRequest generates a "aws/request.Request" representing the @@ -11529,6 +12624,12 @@ func (c *IoT) ListDomainConfigurationsRequest(input *ListDomainConfigurationsInp Name: opListDomainConfigurations, HTTPMethod: "GET", HTTPPath: "/domainConfigurations", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -11591,6 +12692,58 @@ func (c *IoT) ListDomainConfigurationsWithContext(ctx aws.Context, input *ListDo return out, req.Send() } +// ListDomainConfigurationsPages iterates over the pages of a ListDomainConfigurations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListDomainConfigurations 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 ListDomainConfigurations operation. +// pageNum := 0 +// err := client.ListDomainConfigurationsPages(params, +// func(page *iot.ListDomainConfigurationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListDomainConfigurationsPages(input *ListDomainConfigurationsInput, fn func(*ListDomainConfigurationsOutput, bool) bool) error { + return c.ListDomainConfigurationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDomainConfigurationsPagesWithContext same as ListDomainConfigurationsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListDomainConfigurationsPagesWithContext(ctx aws.Context, input *ListDomainConfigurationsInput, fn func(*ListDomainConfigurationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDomainConfigurationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDomainConfigurationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListDomainConfigurationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListIndices = "ListIndices" // ListIndicesRequest generates a "aws/request.Request" representing the @@ -11620,6 +12773,12 @@ func (c *IoT) ListIndicesRequest(input *ListIndicesInput) (req *request.Request, Name: opListIndices, HTTPMethod: "GET", HTTPPath: "/indices", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -11679,6 +12838,58 @@ func (c *IoT) ListIndicesWithContext(ctx aws.Context, input *ListIndicesInput, o return out, req.Send() } +// ListIndicesPages iterates over the pages of a ListIndices operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListIndices 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 ListIndices operation. +// pageNum := 0 +// err := client.ListIndicesPages(params, +// func(page *iot.ListIndicesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListIndicesPages(input *ListIndicesInput, fn func(*ListIndicesOutput, bool) bool) error { + return c.ListIndicesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListIndicesPagesWithContext same as ListIndicesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListIndicesPagesWithContext(ctx aws.Context, input *ListIndicesInput, fn func(*ListIndicesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListIndicesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListIndicesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListIndicesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListJobExecutionsForJob = "ListJobExecutionsForJob" // ListJobExecutionsForJobRequest generates a "aws/request.Request" representing the @@ -11708,6 +12919,12 @@ func (c *IoT) ListJobExecutionsForJobRequest(input *ListJobExecutionsForJobInput Name: opListJobExecutionsForJob, HTTPMethod: "GET", HTTPPath: "/jobs/{jobId}/things", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -11764,6 +12981,58 @@ func (c *IoT) ListJobExecutionsForJobWithContext(ctx aws.Context, input *ListJob return out, req.Send() } +// ListJobExecutionsForJobPages iterates over the pages of a ListJobExecutionsForJob operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListJobExecutionsForJob 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 ListJobExecutionsForJob operation. +// pageNum := 0 +// err := client.ListJobExecutionsForJobPages(params, +// func(page *iot.ListJobExecutionsForJobOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListJobExecutionsForJobPages(input *ListJobExecutionsForJobInput, fn func(*ListJobExecutionsForJobOutput, bool) bool) error { + return c.ListJobExecutionsForJobPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListJobExecutionsForJobPagesWithContext same as ListJobExecutionsForJobPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListJobExecutionsForJobPagesWithContext(ctx aws.Context, input *ListJobExecutionsForJobInput, fn func(*ListJobExecutionsForJobOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListJobExecutionsForJobInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListJobExecutionsForJobRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListJobExecutionsForJobOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListJobExecutionsForThing = "ListJobExecutionsForThing" // ListJobExecutionsForThingRequest generates a "aws/request.Request" representing the @@ -11793,6 +13062,12 @@ func (c *IoT) ListJobExecutionsForThingRequest(input *ListJobExecutionsForThingI Name: opListJobExecutionsForThing, HTTPMethod: "GET", HTTPPath: "/things/{thingName}/jobs", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -11849,6 +13124,58 @@ func (c *IoT) ListJobExecutionsForThingWithContext(ctx aws.Context, input *ListJ return out, req.Send() } +// ListJobExecutionsForThingPages iterates over the pages of a ListJobExecutionsForThing operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListJobExecutionsForThing 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 ListJobExecutionsForThing operation. +// pageNum := 0 +// err := client.ListJobExecutionsForThingPages(params, +// func(page *iot.ListJobExecutionsForThingOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListJobExecutionsForThingPages(input *ListJobExecutionsForThingInput, fn func(*ListJobExecutionsForThingOutput, bool) bool) error { + return c.ListJobExecutionsForThingPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListJobExecutionsForThingPagesWithContext same as ListJobExecutionsForThingPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListJobExecutionsForThingPagesWithContext(ctx aws.Context, input *ListJobExecutionsForThingInput, fn func(*ListJobExecutionsForThingOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListJobExecutionsForThingInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListJobExecutionsForThingRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListJobExecutionsForThingOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListJobs = "ListJobs" // ListJobsRequest generates a "aws/request.Request" representing the @@ -11878,6 +13205,12 @@ func (c *IoT) ListJobsRequest(input *ListJobsInput) (req *request.Request, outpu Name: opListJobs, HTTPMethod: "GET", HTTPPath: "/jobs", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -11934,6 +13267,58 @@ func (c *IoT) ListJobsWithContext(ctx aws.Context, input *ListJobsInput, 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 *iot.ListJobsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) 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 *IoT) 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 + }, + } + + for p.Next() { + if !fn(p.Page().(*ListJobsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListMitigationActions = "ListMitigationActions" // ListMitigationActionsRequest generates a "aws/request.Request" representing the @@ -11963,6 +13348,12 @@ func (c *IoT) ListMitigationActionsRequest(input *ListMitigationActionsInput) (r Name: opListMitigationActions, HTTPMethod: "GET", HTTPPath: "/mitigationactions/actions", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -12016,6 +13407,58 @@ func (c *IoT) ListMitigationActionsWithContext(ctx aws.Context, input *ListMitig return out, req.Send() } +// ListMitigationActionsPages iterates over the pages of a ListMitigationActions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListMitigationActions 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 ListMitigationActions operation. +// pageNum := 0 +// err := client.ListMitigationActionsPages(params, +// func(page *iot.ListMitigationActionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListMitigationActionsPages(input *ListMitigationActionsInput, fn func(*ListMitigationActionsOutput, bool) bool) error { + return c.ListMitigationActionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListMitigationActionsPagesWithContext same as ListMitigationActionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListMitigationActionsPagesWithContext(ctx aws.Context, input *ListMitigationActionsInput, fn func(*ListMitigationActionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListMitigationActionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListMitigationActionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListMitigationActionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListOTAUpdates = "ListOTAUpdates" // ListOTAUpdatesRequest generates a "aws/request.Request" representing the @@ -12045,6 +13488,12 @@ func (c *IoT) ListOTAUpdatesRequest(input *ListOTAUpdatesInput) (req *request.Re Name: opListOTAUpdates, HTTPMethod: "GET", HTTPPath: "/otaUpdates", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -12104,6 +13553,58 @@ func (c *IoT) ListOTAUpdatesWithContext(ctx aws.Context, input *ListOTAUpdatesIn return out, req.Send() } +// ListOTAUpdatesPages iterates over the pages of a ListOTAUpdates operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListOTAUpdates 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 ListOTAUpdates operation. +// pageNum := 0 +// err := client.ListOTAUpdatesPages(params, +// func(page *iot.ListOTAUpdatesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListOTAUpdatesPages(input *ListOTAUpdatesInput, fn func(*ListOTAUpdatesOutput, bool) bool) error { + return c.ListOTAUpdatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListOTAUpdatesPagesWithContext same as ListOTAUpdatesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListOTAUpdatesPagesWithContext(ctx aws.Context, input *ListOTAUpdatesInput, fn func(*ListOTAUpdatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListOTAUpdatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListOTAUpdatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListOTAUpdatesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListOutgoingCertificates = "ListOutgoingCertificates" // ListOutgoingCertificatesRequest generates a "aws/request.Request" representing the @@ -12133,6 +13634,12 @@ func (c *IoT) ListOutgoingCertificatesRequest(input *ListOutgoingCertificatesInp Name: opListOutgoingCertificates, HTTPMethod: "GET", HTTPPath: "/certificates-out-going", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -12192,6 +13699,58 @@ func (c *IoT) ListOutgoingCertificatesWithContext(ctx aws.Context, input *ListOu return out, req.Send() } +// ListOutgoingCertificatesPages iterates over the pages of a ListOutgoingCertificates operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListOutgoingCertificates 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 ListOutgoingCertificates operation. +// pageNum := 0 +// err := client.ListOutgoingCertificatesPages(params, +// func(page *iot.ListOutgoingCertificatesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListOutgoingCertificatesPages(input *ListOutgoingCertificatesInput, fn func(*ListOutgoingCertificatesOutput, bool) bool) error { + return c.ListOutgoingCertificatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListOutgoingCertificatesPagesWithContext same as ListOutgoingCertificatesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListOutgoingCertificatesPagesWithContext(ctx aws.Context, input *ListOutgoingCertificatesInput, fn func(*ListOutgoingCertificatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListOutgoingCertificatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListOutgoingCertificatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListOutgoingCertificatesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListPolicies = "ListPolicies" // ListPoliciesRequest generates a "aws/request.Request" representing the @@ -12221,6 +13780,12 @@ func (c *IoT) ListPoliciesRequest(input *ListPoliciesInput) (req *request.Reques Name: opListPolicies, HTTPMethod: "GET", HTTPPath: "/policies", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -12280,6 +13845,58 @@ func (c *IoT) ListPoliciesWithContext(ctx aws.Context, input *ListPoliciesInput, return out, req.Send() } +// ListPoliciesPages iterates over the pages of a ListPolicies operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListPolicies 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 ListPolicies operation. +// pageNum := 0 +// err := client.ListPoliciesPages(params, +// func(page *iot.ListPoliciesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) 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 *IoT) 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 + }, + } + + for p.Next() { + if !fn(p.Page().(*ListPoliciesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListPolicyPrincipals = "ListPolicyPrincipals" // ListPolicyPrincipalsRequest generates a "aws/request.Request" representing the @@ -12314,6 +13931,12 @@ func (c *IoT) ListPolicyPrincipalsRequest(input *ListPolicyPrincipalsInput) (req Name: opListPolicyPrincipals, HTTPMethod: "GET", HTTPPath: "/policy-principals", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -12382,6 +14005,62 @@ func (c *IoT) ListPolicyPrincipalsWithContext(ctx aws.Context, input *ListPolicy return out, req.Send() } +// ListPolicyPrincipalsPages iterates over the pages of a ListPolicyPrincipals operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListPolicyPrincipals 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 ListPolicyPrincipals operation. +// pageNum := 0 +// err := client.ListPolicyPrincipalsPages(params, +// func(page *iot.ListPolicyPrincipalsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +// +// Deprecated: ListPolicyPrincipalsPages has been deprecated +func (c *IoT) ListPolicyPrincipalsPages(input *ListPolicyPrincipalsInput, fn func(*ListPolicyPrincipalsOutput, bool) bool) error { + return c.ListPolicyPrincipalsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPolicyPrincipalsPagesWithContext same as ListPolicyPrincipalsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +// +// Deprecated: ListPolicyPrincipalsPagesWithContext has been deprecated +func (c *IoT) ListPolicyPrincipalsPagesWithContext(ctx aws.Context, input *ListPolicyPrincipalsInput, fn func(*ListPolicyPrincipalsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPolicyPrincipalsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPolicyPrincipalsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListPolicyPrincipalsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListPolicyVersions = "ListPolicyVersions" // ListPolicyVersionsRequest generates a "aws/request.Request" representing the @@ -12507,6 +14186,12 @@ func (c *IoT) ListPrincipalPoliciesRequest(input *ListPrincipalPoliciesInput) (r Name: opListPrincipalPolicies, HTTPMethod: "GET", HTTPPath: "/principal-policies", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -12576,6 +14261,62 @@ func (c *IoT) ListPrincipalPoliciesWithContext(ctx aws.Context, input *ListPrinc return out, req.Send() } +// ListPrincipalPoliciesPages iterates over the pages of a ListPrincipalPolicies operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListPrincipalPolicies 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 ListPrincipalPolicies operation. +// pageNum := 0 +// err := client.ListPrincipalPoliciesPages(params, +// func(page *iot.ListPrincipalPoliciesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +// +// Deprecated: ListPrincipalPoliciesPages has been deprecated +func (c *IoT) ListPrincipalPoliciesPages(input *ListPrincipalPoliciesInput, fn func(*ListPrincipalPoliciesOutput, bool) bool) error { + return c.ListPrincipalPoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPrincipalPoliciesPagesWithContext same as ListPrincipalPoliciesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +// +// Deprecated: ListPrincipalPoliciesPagesWithContext has been deprecated +func (c *IoT) ListPrincipalPoliciesPagesWithContext(ctx aws.Context, input *ListPrincipalPoliciesInput, fn func(*ListPrincipalPoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPrincipalPoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPrincipalPoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListPrincipalPoliciesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListPrincipalThings = "ListPrincipalThings" // ListPrincipalThingsRequest generates a "aws/request.Request" representing the @@ -12605,6 +14346,12 @@ func (c *IoT) ListPrincipalThingsRequest(input *ListPrincipalThingsInput) (req * Name: opListPrincipalThings, HTTPMethod: "GET", HTTPPath: "/principals/things", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -12669,6 +14416,58 @@ func (c *IoT) ListPrincipalThingsWithContext(ctx aws.Context, input *ListPrincip return out, req.Send() } +// ListPrincipalThingsPages iterates over the pages of a ListPrincipalThings operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListPrincipalThings 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 ListPrincipalThings operation. +// pageNum := 0 +// err := client.ListPrincipalThingsPages(params, +// func(page *iot.ListPrincipalThingsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListPrincipalThingsPages(input *ListPrincipalThingsInput, fn func(*ListPrincipalThingsOutput, bool) bool) error { + return c.ListPrincipalThingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPrincipalThingsPagesWithContext same as ListPrincipalThingsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListPrincipalThingsPagesWithContext(ctx aws.Context, input *ListPrincipalThingsInput, fn func(*ListPrincipalThingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPrincipalThingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPrincipalThingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListPrincipalThingsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListProvisioningTemplateVersions = "ListProvisioningTemplateVersions" // ListProvisioningTemplateVersionsRequest generates a "aws/request.Request" representing the @@ -12698,6 +14497,12 @@ func (c *IoT) ListProvisioningTemplateVersionsRequest(input *ListProvisioningTem Name: opListProvisioningTemplateVersions, HTTPMethod: "GET", HTTPPath: "/provisioning-templates/{templateName}/versions", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -12757,6 +14562,58 @@ func (c *IoT) ListProvisioningTemplateVersionsWithContext(ctx aws.Context, input return out, req.Send() } +// ListProvisioningTemplateVersionsPages iterates over the pages of a ListProvisioningTemplateVersions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListProvisioningTemplateVersions 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 ListProvisioningTemplateVersions operation. +// pageNum := 0 +// err := client.ListProvisioningTemplateVersionsPages(params, +// func(page *iot.ListProvisioningTemplateVersionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListProvisioningTemplateVersionsPages(input *ListProvisioningTemplateVersionsInput, fn func(*ListProvisioningTemplateVersionsOutput, bool) bool) error { + return c.ListProvisioningTemplateVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListProvisioningTemplateVersionsPagesWithContext same as ListProvisioningTemplateVersionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListProvisioningTemplateVersionsPagesWithContext(ctx aws.Context, input *ListProvisioningTemplateVersionsInput, fn func(*ListProvisioningTemplateVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListProvisioningTemplateVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListProvisioningTemplateVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListProvisioningTemplateVersionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListProvisioningTemplates = "ListProvisioningTemplates" // ListProvisioningTemplatesRequest generates a "aws/request.Request" representing the @@ -12786,6 +14643,12 @@ func (c *IoT) ListProvisioningTemplatesRequest(input *ListProvisioningTemplatesI Name: opListProvisioningTemplates, HTTPMethod: "GET", HTTPPath: "/provisioning-templates", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -12842,6 +14705,58 @@ func (c *IoT) ListProvisioningTemplatesWithContext(ctx aws.Context, input *ListP return out, req.Send() } +// ListProvisioningTemplatesPages iterates over the pages of a ListProvisioningTemplates operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListProvisioningTemplates 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 ListProvisioningTemplates operation. +// pageNum := 0 +// err := client.ListProvisioningTemplatesPages(params, +// func(page *iot.ListProvisioningTemplatesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListProvisioningTemplatesPages(input *ListProvisioningTemplatesInput, fn func(*ListProvisioningTemplatesOutput, bool) bool) error { + return c.ListProvisioningTemplatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListProvisioningTemplatesPagesWithContext same as ListProvisioningTemplatesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListProvisioningTemplatesPagesWithContext(ctx aws.Context, input *ListProvisioningTemplatesInput, fn func(*ListProvisioningTemplatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListProvisioningTemplatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListProvisioningTemplatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListProvisioningTemplatesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListRoleAliases = "ListRoleAliases" // ListRoleAliasesRequest generates a "aws/request.Request" representing the @@ -12871,6 +14786,12 @@ func (c *IoT) ListRoleAliasesRequest(input *ListRoleAliasesInput) (req *request. Name: opListRoleAliases, HTTPMethod: "GET", HTTPPath: "/role-aliases", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -12930,6 +14851,58 @@ func (c *IoT) ListRoleAliasesWithContext(ctx aws.Context, input *ListRoleAliases return out, req.Send() } +// ListRoleAliasesPages iterates over the pages of a ListRoleAliases operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListRoleAliases 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 ListRoleAliases operation. +// pageNum := 0 +// err := client.ListRoleAliasesPages(params, +// func(page *iot.ListRoleAliasesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListRoleAliasesPages(input *ListRoleAliasesInput, fn func(*ListRoleAliasesOutput, bool) bool) error { + return c.ListRoleAliasesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListRoleAliasesPagesWithContext same as ListRoleAliasesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListRoleAliasesPagesWithContext(ctx aws.Context, input *ListRoleAliasesInput, fn func(*ListRoleAliasesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListRoleAliasesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListRoleAliasesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListRoleAliasesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListScheduledAudits = "ListScheduledAudits" // ListScheduledAuditsRequest generates a "aws/request.Request" representing the @@ -12959,6 +14932,12 @@ func (c *IoT) ListScheduledAuditsRequest(input *ListScheduledAuditsInput) (req * Name: opListScheduledAudits, HTTPMethod: "GET", HTTPPath: "/audit/scheduledaudits", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -13012,6 +14991,58 @@ func (c *IoT) ListScheduledAuditsWithContext(ctx aws.Context, input *ListSchedul return out, req.Send() } +// ListScheduledAuditsPages iterates over the pages of a ListScheduledAudits operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListScheduledAudits 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 ListScheduledAudits operation. +// pageNum := 0 +// err := client.ListScheduledAuditsPages(params, +// func(page *iot.ListScheduledAuditsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListScheduledAuditsPages(input *ListScheduledAuditsInput, fn func(*ListScheduledAuditsOutput, bool) bool) error { + return c.ListScheduledAuditsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListScheduledAuditsPagesWithContext same as ListScheduledAuditsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListScheduledAuditsPagesWithContext(ctx aws.Context, input *ListScheduledAuditsInput, fn func(*ListScheduledAuditsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListScheduledAuditsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListScheduledAuditsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListScheduledAuditsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListSecurityProfiles = "ListSecurityProfiles" // ListSecurityProfilesRequest generates a "aws/request.Request" representing the @@ -13041,6 +15072,12 @@ func (c *IoT) ListSecurityProfilesRequest(input *ListSecurityProfilesInput) (req Name: opListSecurityProfiles, HTTPMethod: "GET", HTTPPath: "/security-profiles", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -13099,6 +15136,58 @@ func (c *IoT) ListSecurityProfilesWithContext(ctx aws.Context, input *ListSecuri return out, req.Send() } +// ListSecurityProfilesPages iterates over the pages of a ListSecurityProfiles operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListSecurityProfiles 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 ListSecurityProfiles operation. +// pageNum := 0 +// err := client.ListSecurityProfilesPages(params, +// func(page *iot.ListSecurityProfilesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListSecurityProfilesPages(input *ListSecurityProfilesInput, fn func(*ListSecurityProfilesOutput, bool) bool) error { + return c.ListSecurityProfilesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSecurityProfilesPagesWithContext same as ListSecurityProfilesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListSecurityProfilesPagesWithContext(ctx aws.Context, input *ListSecurityProfilesInput, fn func(*ListSecurityProfilesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSecurityProfilesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSecurityProfilesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListSecurityProfilesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListSecurityProfilesForTarget = "ListSecurityProfilesForTarget" // ListSecurityProfilesForTargetRequest generates a "aws/request.Request" representing the @@ -13128,6 +15217,12 @@ func (c *IoT) ListSecurityProfilesForTargetRequest(input *ListSecurityProfilesFo Name: opListSecurityProfilesForTarget, HTTPMethod: "GET", HTTPPath: "/security-profiles-for-target", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -13184,6 +15279,58 @@ func (c *IoT) ListSecurityProfilesForTargetWithContext(ctx aws.Context, input *L return out, req.Send() } +// ListSecurityProfilesForTargetPages iterates over the pages of a ListSecurityProfilesForTarget operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListSecurityProfilesForTarget 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 ListSecurityProfilesForTarget operation. +// pageNum := 0 +// err := client.ListSecurityProfilesForTargetPages(params, +// func(page *iot.ListSecurityProfilesForTargetOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListSecurityProfilesForTargetPages(input *ListSecurityProfilesForTargetInput, fn func(*ListSecurityProfilesForTargetOutput, bool) bool) error { + return c.ListSecurityProfilesForTargetPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSecurityProfilesForTargetPagesWithContext same as ListSecurityProfilesForTargetPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListSecurityProfilesForTargetPagesWithContext(ctx aws.Context, input *ListSecurityProfilesForTargetInput, fn func(*ListSecurityProfilesForTargetOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSecurityProfilesForTargetInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSecurityProfilesForTargetRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListSecurityProfilesForTargetOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListStreams = "ListStreams" // ListStreamsRequest generates a "aws/request.Request" representing the @@ -13213,6 +15360,12 @@ func (c *IoT) ListStreamsRequest(input *ListStreamsInput) (req *request.Request, Name: opListStreams, HTTPMethod: "GET", HTTPPath: "/streams", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -13272,6 +15425,58 @@ func (c *IoT) ListStreamsWithContext(ctx aws.Context, input *ListStreamsInput, o return out, req.Send() } +// ListStreamsPages iterates over the pages of a ListStreams operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListStreams 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 ListStreams operation. +// pageNum := 0 +// err := client.ListStreamsPages(params, +// func(page *iot.ListStreamsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) 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 *IoT) 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 + }, + } + + for p.Next() { + if !fn(p.Page().(*ListStreamsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListTagsForResource = "ListTagsForResource" // ListTagsForResourceRequest generates a "aws/request.Request" representing the @@ -13301,6 +15506,12 @@ func (c *IoT) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req * Name: opListTagsForResource, HTTPMethod: "GET", HTTPPath: "/tags", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "", + TruncationToken: "", + }, } if input == nil { @@ -13357,6 +15568,58 @@ func (c *IoT) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsFor return out, req.Send() } +// ListTagsForResourcePages iterates over the pages of a ListTagsForResource operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListTagsForResource 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 ListTagsForResource operation. +// pageNum := 0 +// err := client.ListTagsForResourcePages(params, +// func(page *iot.ListTagsForResourceOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListTagsForResourcePages(input *ListTagsForResourceInput, fn func(*ListTagsForResourceOutput, bool) bool) error { + return c.ListTagsForResourcePagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTagsForResourcePagesWithContext same as ListTagsForResourcePages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListTagsForResourcePagesWithContext(ctx aws.Context, input *ListTagsForResourceInput, fn func(*ListTagsForResourceOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTagsForResourceInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTagsForResourceRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListTagsForResourceOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListTargetsForPolicy = "ListTargetsForPolicy" // ListTargetsForPolicyRequest generates a "aws/request.Request" representing the @@ -13386,6 +15649,12 @@ func (c *IoT) ListTargetsForPolicyRequest(input *ListTargetsForPolicyInput) (req Name: opListTargetsForPolicy, HTTPMethod: "POST", HTTPPath: "/policy-targets/{policyName}", + Paginator: &request.Paginator{ + InputTokens: []string{"marker"}, + OutputTokens: []string{"nextMarker"}, + LimitToken: "pageSize", + TruncationToken: "", + }, } if input == nil { @@ -13451,6 +15720,58 @@ func (c *IoT) ListTargetsForPolicyWithContext(ctx aws.Context, input *ListTarget return out, req.Send() } +// ListTargetsForPolicyPages iterates over the pages of a ListTargetsForPolicy operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListTargetsForPolicy 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 ListTargetsForPolicy operation. +// pageNum := 0 +// err := client.ListTargetsForPolicyPages(params, +// func(page *iot.ListTargetsForPolicyOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListTargetsForPolicyPages(input *ListTargetsForPolicyInput, fn func(*ListTargetsForPolicyOutput, bool) bool) error { + return c.ListTargetsForPolicyPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTargetsForPolicyPagesWithContext same as ListTargetsForPolicyPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListTargetsForPolicyPagesWithContext(ctx aws.Context, input *ListTargetsForPolicyInput, fn func(*ListTargetsForPolicyOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTargetsForPolicyInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTargetsForPolicyRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListTargetsForPolicyOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListTargetsForSecurityProfile = "ListTargetsForSecurityProfile" // ListTargetsForSecurityProfileRequest generates a "aws/request.Request" representing the @@ -13480,6 +15801,12 @@ func (c *IoT) ListTargetsForSecurityProfileRequest(input *ListTargetsForSecurity Name: opListTargetsForSecurityProfile, HTTPMethod: "GET", HTTPPath: "/security-profiles/{securityProfileName}/targets", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -13537,6 +15864,58 @@ func (c *IoT) ListTargetsForSecurityProfileWithContext(ctx aws.Context, input *L return out, req.Send() } +// ListTargetsForSecurityProfilePages iterates over the pages of a ListTargetsForSecurityProfile operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListTargetsForSecurityProfile 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 ListTargetsForSecurityProfile operation. +// pageNum := 0 +// err := client.ListTargetsForSecurityProfilePages(params, +// func(page *iot.ListTargetsForSecurityProfileOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListTargetsForSecurityProfilePages(input *ListTargetsForSecurityProfileInput, fn func(*ListTargetsForSecurityProfileOutput, bool) bool) error { + return c.ListTargetsForSecurityProfilePagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTargetsForSecurityProfilePagesWithContext same as ListTargetsForSecurityProfilePages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListTargetsForSecurityProfilePagesWithContext(ctx aws.Context, input *ListTargetsForSecurityProfileInput, fn func(*ListTargetsForSecurityProfileOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTargetsForSecurityProfileInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTargetsForSecurityProfileRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListTargetsForSecurityProfileOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListThingGroups = "ListThingGroups" // ListThingGroupsRequest generates a "aws/request.Request" representing the @@ -13566,6 +15945,12 @@ func (c *IoT) ListThingGroupsRequest(input *ListThingGroupsInput) (req *request. Name: opListThingGroups, HTTPMethod: "GET", HTTPPath: "/thing-groups", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -13619,6 +16004,58 @@ func (c *IoT) ListThingGroupsWithContext(ctx aws.Context, input *ListThingGroups return out, req.Send() } +// ListThingGroupsPages iterates over the pages of a ListThingGroups operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListThingGroups 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 ListThingGroups operation. +// pageNum := 0 +// err := client.ListThingGroupsPages(params, +// func(page *iot.ListThingGroupsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListThingGroupsPages(input *ListThingGroupsInput, fn func(*ListThingGroupsOutput, bool) bool) error { + return c.ListThingGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListThingGroupsPagesWithContext same as ListThingGroupsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListThingGroupsPagesWithContext(ctx aws.Context, input *ListThingGroupsInput, fn func(*ListThingGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListThingGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListThingGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListThingGroupsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListThingGroupsForThing = "ListThingGroupsForThing" // ListThingGroupsForThingRequest generates a "aws/request.Request" representing the @@ -13648,6 +16085,12 @@ func (c *IoT) ListThingGroupsForThingRequest(input *ListThingGroupsForThingInput Name: opListThingGroupsForThing, HTTPMethod: "GET", HTTPPath: "/things/{thingName}/thing-groups", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -13701,6 +16144,58 @@ func (c *IoT) ListThingGroupsForThingWithContext(ctx aws.Context, input *ListThi return out, req.Send() } +// ListThingGroupsForThingPages iterates over the pages of a ListThingGroupsForThing operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListThingGroupsForThing 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 ListThingGroupsForThing operation. +// pageNum := 0 +// err := client.ListThingGroupsForThingPages(params, +// func(page *iot.ListThingGroupsForThingOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListThingGroupsForThingPages(input *ListThingGroupsForThingInput, fn func(*ListThingGroupsForThingOutput, bool) bool) error { + return c.ListThingGroupsForThingPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListThingGroupsForThingPagesWithContext same as ListThingGroupsForThingPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListThingGroupsForThingPagesWithContext(ctx aws.Context, input *ListThingGroupsForThingInput, fn func(*ListThingGroupsForThingOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListThingGroupsForThingInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListThingGroupsForThingRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListThingGroupsForThingOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListThingPrincipals = "ListThingPrincipals" // ListThingPrincipalsRequest generates a "aws/request.Request" representing the @@ -13823,6 +16318,12 @@ func (c *IoT) ListThingRegistrationTaskReportsRequest(input *ListThingRegistrati Name: opListThingRegistrationTaskReports, HTTPMethod: "GET", HTTPPath: "/thing-registration-tasks/{taskId}/reports", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -13879,6 +16380,58 @@ func (c *IoT) ListThingRegistrationTaskReportsWithContext(ctx aws.Context, input return out, req.Send() } +// ListThingRegistrationTaskReportsPages iterates over the pages of a ListThingRegistrationTaskReports operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListThingRegistrationTaskReports 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 ListThingRegistrationTaskReports operation. +// pageNum := 0 +// err := client.ListThingRegistrationTaskReportsPages(params, +// func(page *iot.ListThingRegistrationTaskReportsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListThingRegistrationTaskReportsPages(input *ListThingRegistrationTaskReportsInput, fn func(*ListThingRegistrationTaskReportsOutput, bool) bool) error { + return c.ListThingRegistrationTaskReportsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListThingRegistrationTaskReportsPagesWithContext same as ListThingRegistrationTaskReportsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListThingRegistrationTaskReportsPagesWithContext(ctx aws.Context, input *ListThingRegistrationTaskReportsInput, fn func(*ListThingRegistrationTaskReportsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListThingRegistrationTaskReportsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListThingRegistrationTaskReportsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListThingRegistrationTaskReportsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListThingRegistrationTasks = "ListThingRegistrationTasks" // ListThingRegistrationTasksRequest generates a "aws/request.Request" representing the @@ -13908,6 +16461,12 @@ func (c *IoT) ListThingRegistrationTasksRequest(input *ListThingRegistrationTask Name: opListThingRegistrationTasks, HTTPMethod: "GET", HTTPPath: "/thing-registration-tasks", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -13964,6 +16523,58 @@ func (c *IoT) ListThingRegistrationTasksWithContext(ctx aws.Context, input *List return out, req.Send() } +// ListThingRegistrationTasksPages iterates over the pages of a ListThingRegistrationTasks operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListThingRegistrationTasks 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 ListThingRegistrationTasks operation. +// pageNum := 0 +// err := client.ListThingRegistrationTasksPages(params, +// func(page *iot.ListThingRegistrationTasksOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListThingRegistrationTasksPages(input *ListThingRegistrationTasksInput, fn func(*ListThingRegistrationTasksOutput, bool) bool) error { + return c.ListThingRegistrationTasksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListThingRegistrationTasksPagesWithContext same as ListThingRegistrationTasksPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListThingRegistrationTasksPagesWithContext(ctx aws.Context, input *ListThingRegistrationTasksInput, fn func(*ListThingRegistrationTasksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListThingRegistrationTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListThingRegistrationTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListThingRegistrationTasksOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListThingTypes = "ListThingTypes" // ListThingTypesRequest generates a "aws/request.Request" representing the @@ -13993,6 +16604,12 @@ func (c *IoT) ListThingTypesRequest(input *ListThingTypesInput) (req *request.Re Name: opListThingTypes, HTTPMethod: "GET", HTTPPath: "/thing-types", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -14052,6 +16669,58 @@ func (c *IoT) ListThingTypesWithContext(ctx aws.Context, input *ListThingTypesIn return out, req.Send() } +// ListThingTypesPages iterates over the pages of a ListThingTypes operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListThingTypes 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 ListThingTypes operation. +// pageNum := 0 +// err := client.ListThingTypesPages(params, +// func(page *iot.ListThingTypesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListThingTypesPages(input *ListThingTypesInput, fn func(*ListThingTypesOutput, bool) bool) error { + return c.ListThingTypesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListThingTypesPagesWithContext same as ListThingTypesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListThingTypesPagesWithContext(ctx aws.Context, input *ListThingTypesInput, fn func(*ListThingTypesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListThingTypesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListThingTypesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListThingTypesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListThings = "ListThings" // ListThingsRequest generates a "aws/request.Request" representing the @@ -14081,6 +16750,12 @@ func (c *IoT) ListThingsRequest(input *ListThingsInput) (req *request.Request, o Name: opListThings, HTTPMethod: "GET", HTTPPath: "/things", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -14099,6 +16774,10 @@ func (c *IoT) ListThingsRequest(input *ListThingsInput) (req *request.Request, o // and attributeValue=Red retrieves all things in the registry that contain // an attribute Color with the value Red. // +// You will not be charged for calling this API if an Access denied error is +// returned. You will also not be charged if no attributes or pagination token +// was provided in request and no pagination token and no results were returned. +// // Returns awserr.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. @@ -14143,6 +16822,58 @@ func (c *IoT) ListThingsWithContext(ctx aws.Context, input *ListThingsInput, opt return out, req.Send() } +// ListThingsPages iterates over the pages of a ListThings operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListThings 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 ListThings operation. +// pageNum := 0 +// err := client.ListThingsPages(params, +// func(page *iot.ListThingsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListThingsPages(input *ListThingsInput, fn func(*ListThingsOutput, bool) bool) error { + return c.ListThingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListThingsPagesWithContext same as ListThingsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListThingsPagesWithContext(ctx aws.Context, input *ListThingsInput, fn func(*ListThingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListThingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListThingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListThingsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListThingsInBillingGroup = "ListThingsInBillingGroup" // ListThingsInBillingGroupRequest generates a "aws/request.Request" representing the @@ -14172,6 +16903,12 @@ func (c *IoT) ListThingsInBillingGroupRequest(input *ListThingsInBillingGroupInp Name: opListThingsInBillingGroup, HTTPMethod: "GET", HTTPPath: "/billing-groups/{billingGroupName}/things", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -14228,6 +16965,58 @@ func (c *IoT) ListThingsInBillingGroupWithContext(ctx aws.Context, input *ListTh return out, req.Send() } +// ListThingsInBillingGroupPages iterates over the pages of a ListThingsInBillingGroup operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListThingsInBillingGroup 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 ListThingsInBillingGroup operation. +// pageNum := 0 +// err := client.ListThingsInBillingGroupPages(params, +// func(page *iot.ListThingsInBillingGroupOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListThingsInBillingGroupPages(input *ListThingsInBillingGroupInput, fn func(*ListThingsInBillingGroupOutput, bool) bool) error { + return c.ListThingsInBillingGroupPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListThingsInBillingGroupPagesWithContext same as ListThingsInBillingGroupPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListThingsInBillingGroupPagesWithContext(ctx aws.Context, input *ListThingsInBillingGroupInput, fn func(*ListThingsInBillingGroupOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListThingsInBillingGroupInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListThingsInBillingGroupRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListThingsInBillingGroupOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListThingsInThingGroup = "ListThingsInThingGroup" // ListThingsInThingGroupRequest generates a "aws/request.Request" representing the @@ -14257,6 +17046,12 @@ func (c *IoT) ListThingsInThingGroupRequest(input *ListThingsInThingGroupInput) Name: opListThingsInThingGroup, HTTPMethod: "GET", HTTPPath: "/thing-groups/{thingGroupName}/things", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -14310,6 +17105,58 @@ func (c *IoT) ListThingsInThingGroupWithContext(ctx aws.Context, input *ListThin return out, req.Send() } +// ListThingsInThingGroupPages iterates over the pages of a ListThingsInThingGroup operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListThingsInThingGroup 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 ListThingsInThingGroup operation. +// pageNum := 0 +// err := client.ListThingsInThingGroupPages(params, +// func(page *iot.ListThingsInThingGroupOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListThingsInThingGroupPages(input *ListThingsInThingGroupInput, fn func(*ListThingsInThingGroupOutput, bool) bool) error { + return c.ListThingsInThingGroupPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListThingsInThingGroupPagesWithContext same as ListThingsInThingGroupPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListThingsInThingGroupPagesWithContext(ctx aws.Context, input *ListThingsInThingGroupInput, fn func(*ListThingsInThingGroupOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListThingsInThingGroupInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListThingsInThingGroupRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListThingsInThingGroupOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListTopicRuleDestinations = "ListTopicRuleDestinations" // ListTopicRuleDestinationsRequest generates a "aws/request.Request" representing the @@ -14339,6 +17186,12 @@ func (c *IoT) ListTopicRuleDestinationsRequest(input *ListTopicRuleDestinationsI Name: opListTopicRuleDestinations, HTTPMethod: "GET", HTTPPath: "/destinations", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -14395,6 +17248,58 @@ func (c *IoT) ListTopicRuleDestinationsWithContext(ctx aws.Context, input *ListT return out, req.Send() } +// ListTopicRuleDestinationsPages iterates over the pages of a ListTopicRuleDestinations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListTopicRuleDestinations 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 ListTopicRuleDestinations operation. +// pageNum := 0 +// err := client.ListTopicRuleDestinationsPages(params, +// func(page *iot.ListTopicRuleDestinationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListTopicRuleDestinationsPages(input *ListTopicRuleDestinationsInput, fn func(*ListTopicRuleDestinationsOutput, bool) bool) error { + return c.ListTopicRuleDestinationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTopicRuleDestinationsPagesWithContext same as ListTopicRuleDestinationsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListTopicRuleDestinationsPagesWithContext(ctx aws.Context, input *ListTopicRuleDestinationsInput, fn func(*ListTopicRuleDestinationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTopicRuleDestinationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTopicRuleDestinationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListTopicRuleDestinationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListTopicRules = "ListTopicRules" // ListTopicRulesRequest generates a "aws/request.Request" representing the @@ -14424,6 +17329,12 @@ func (c *IoT) ListTopicRulesRequest(input *ListTopicRulesInput) (req *request.Re Name: opListTopicRules, HTTPMethod: "GET", HTTPPath: "/rules", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -14477,6 +17388,58 @@ func (c *IoT) ListTopicRulesWithContext(ctx aws.Context, input *ListTopicRulesIn return out, req.Send() } +// ListTopicRulesPages iterates over the pages of a ListTopicRules operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListTopicRules 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 ListTopicRules operation. +// pageNum := 0 +// err := client.ListTopicRulesPages(params, +// func(page *iot.ListTopicRulesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListTopicRulesPages(input *ListTopicRulesInput, fn func(*ListTopicRulesOutput, bool) bool) error { + return c.ListTopicRulesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTopicRulesPagesWithContext same as ListTopicRulesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListTopicRulesPagesWithContext(ctx aws.Context, input *ListTopicRulesInput, fn func(*ListTopicRulesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTopicRulesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTopicRulesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListTopicRulesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListV2LoggingLevels = "ListV2LoggingLevels" // ListV2LoggingLevelsRequest generates a "aws/request.Request" representing the @@ -14506,6 +17469,12 @@ func (c *IoT) ListV2LoggingLevelsRequest(input *ListV2LoggingLevelsInput) (req * Name: opListV2LoggingLevels, HTTPMethod: "GET", HTTPPath: "/v2LoggingLevel", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -14562,6 +17531,58 @@ func (c *IoT) ListV2LoggingLevelsWithContext(ctx aws.Context, input *ListV2Loggi return out, req.Send() } +// ListV2LoggingLevelsPages iterates over the pages of a ListV2LoggingLevels operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListV2LoggingLevels 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 ListV2LoggingLevels operation. +// pageNum := 0 +// err := client.ListV2LoggingLevelsPages(params, +// func(page *iot.ListV2LoggingLevelsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListV2LoggingLevelsPages(input *ListV2LoggingLevelsInput, fn func(*ListV2LoggingLevelsOutput, bool) bool) error { + return c.ListV2LoggingLevelsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListV2LoggingLevelsPagesWithContext same as ListV2LoggingLevelsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListV2LoggingLevelsPagesWithContext(ctx aws.Context, input *ListV2LoggingLevelsInput, fn func(*ListV2LoggingLevelsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListV2LoggingLevelsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListV2LoggingLevelsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListV2LoggingLevelsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListViolationEvents = "ListViolationEvents" // ListViolationEventsRequest generates a "aws/request.Request" representing the @@ -14591,6 +17612,12 @@ func (c *IoT) ListViolationEventsRequest(input *ListViolationEventsInput) (req * Name: opListViolationEvents, HTTPMethod: "GET", HTTPPath: "/violation-events", + Paginator: &request.Paginator{ + InputTokens: []string{"nextToken"}, + OutputTokens: []string{"nextToken"}, + LimitToken: "maxResults", + TruncationToken: "", + }, } if input == nil { @@ -14646,6 +17673,58 @@ func (c *IoT) ListViolationEventsWithContext(ctx aws.Context, input *ListViolati return out, req.Send() } +// ListViolationEventsPages iterates over the pages of a ListViolationEvents operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListViolationEvents 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 ListViolationEvents operation. +// pageNum := 0 +// err := client.ListViolationEventsPages(params, +// func(page *iot.ListViolationEventsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *IoT) ListViolationEventsPages(input *ListViolationEventsInput, fn func(*ListViolationEventsOutput, bool) bool) error { + return c.ListViolationEventsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListViolationEventsPagesWithContext same as ListViolationEventsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) ListViolationEventsPagesWithContext(ctx aws.Context, input *ListViolationEventsInput, fn func(*ListViolationEventsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListViolationEventsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListViolationEventsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListViolationEventsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opRegisterCACertificate = "RegisterCACertificate" // RegisterCACertificateRequest generates a "aws/request.Request" representing the @@ -15287,6 +18366,10 @@ func (c *IoT) RemoveThingFromThingGroupRequest(input *RemoveThingFromThingGroupI // // Remove the specified thing from the specified group. // +// You must specify either a thingGroupArn or a thingGroupName to identify the +// thing group and either a thingArn or a thingName to identify the thing to +// remove from the thing group. +// // Returns awserr.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. @@ -16874,6 +19957,92 @@ func (c *IoT) UpdateAccountAuditConfigurationWithContext(ctx aws.Context, input return out, req.Send() } +const opUpdateAuditSuppression = "UpdateAuditSuppression" + +// UpdateAuditSuppressionRequest generates a "aws/request.Request" representing the +// client's request for the UpdateAuditSuppression operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateAuditSuppression for more information on using the UpdateAuditSuppression +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateAuditSuppressionRequest method. +// req, resp := client.UpdateAuditSuppressionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +func (c *IoT) UpdateAuditSuppressionRequest(input *UpdateAuditSuppressionInput) (req *request.Request, output *UpdateAuditSuppressionOutput) { + op := &request.Operation{ + Name: opUpdateAuditSuppression, + HTTPMethod: "PATCH", + HTTPPath: "/audit/suppressions/update", + } + + if input == nil { + input = &UpdateAuditSuppressionInput{} + } + + output = &UpdateAuditSuppressionOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UpdateAuditSuppression API operation for AWS IoT. +// +// Updates a Device Defender audit suppression. +// +// Returns awserr.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 IoT's +// API operation UpdateAuditSuppression for usage and error information. +// +// Returned Error Types: +// * InvalidRequestException +// The request is not valid. +// +// * ResourceNotFoundException +// The specified resource does not exist. +// +// * ThrottlingException +// The rate exceeds the limit. +// +// * InternalFailureException +// An unexpected error has occurred. +// +func (c *IoT) UpdateAuditSuppression(input *UpdateAuditSuppressionInput) (*UpdateAuditSuppressionOutput, error) { + req, out := c.UpdateAuditSuppressionRequest(input) + return out, req.Send() +} + +// UpdateAuditSuppressionWithContext is the same as UpdateAuditSuppression with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAuditSuppression for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *IoT) UpdateAuditSuppressionWithContext(ctx aws.Context, input *UpdateAuditSuppressionInput, opts ...request.Option) (*UpdateAuditSuppressionOutput, error) { + req, out := c.UpdateAuditSuppressionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opUpdateAuthorizer = "UpdateAuthorizer" // UpdateAuthorizerRequest generates a "aws/request.Request" representing the @@ -17194,11 +20363,13 @@ func (c *IoT) UpdateCertificateRequest(input *UpdateCertificateInput) (req *requ // // Updates the status of the specified certificate. This operation is idempotent. // -// Moving a certificate from the ACTIVE state (including REVOKED) will not disconnect -// currently connected devices, but these devices will be unable to reconnect. +// Certificates must be in the ACTIVE state to authenticate devices that use +// a certificate to connect to AWS IoT. // -// The ACTIVE state is required to authenticate devices connecting to AWS IoT -// using a certificate. +// Within a few minutes of updating a certificate from the ACTIVE state to any +// other state, AWS IoT disconnects all devices that used that certificate to +// connect. Devices cannot use a certificate that is not in the ACTIVE state +// to reconnect. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -18759,11 +21930,11 @@ func (c *IoT) ValidateSecurityProfileBehaviorsWithContext(ctx aws.Context, input return out, req.Send() } -// Details of abort criteria to abort the job. +// The criteria that determine when and how a job abort takes place. type AbortConfig struct { _ struct{} `type:"structure"` - // The list of abort criteria to define rules to abort the job. + // The list of criteria that determine when and how to abort the job. // // CriteriaList is a required field CriteriaList []*AbortCriteria `locationName:"criteriaList" min:"1" type:"list" required:"true"` @@ -18811,27 +21982,28 @@ func (s *AbortConfig) SetCriteriaList(v []*AbortCriteria) *AbortConfig { return s } -// Details of abort criteria to define rules to abort the job. +// The criteria that determine when and how a job abort takes place. type AbortCriteria struct { _ struct{} `type:"structure"` - // The type of abort action to initiate a job abort. + // The type of job action to take to initiate the job abort. // // Action is a required field Action *string `locationName:"action" type:"string" required:"true" enum:"AbortAction"` - // The type of job execution failure to define a rule to initiate a job abort. + // The type of job execution failures that can initiate a job abort. // // FailureType is a required field FailureType *string `locationName:"failureType" type:"string" required:"true" enum:"JobExecutionFailureType"` - // Minimum number of executed things before evaluating an abort rule. + // The minimum number of things which must receive job execution notifications + // before the job can be aborted. // // MinNumberOfExecutedThings is a required field MinNumberOfExecutedThings *int64 `locationName:"minNumberOfExecutedThings" min:"1" type:"integer" required:"true"` - // The threshold as a percentage of the total number of executed things that - // will initiate a job abort. + // The minimum percentage of job execution failures that must occur to initiate + // the job abort. // // AWS IoT supports up to two digits after the decimal (for example, 10.9 and // 10.99, but not 10.999). @@ -19947,7 +23119,7 @@ type AttachPolicyInput struct { // PolicyName is a required field PolicyName *string `location:"uri" locationName:"policyName" min:"1" type:"string" required:"true"` - // The identity (https://docs.aws.amazon.com/iot/latest/developerguide/iot-security-identity.html) + // The identity (https://docs.aws.amazon.com/iot/latest/developerguide/security-iam.html) // to which the policy is attached. // // Target is a required field @@ -20308,6 +23480,10 @@ type AuditCheckDetails struct { // The number of resources that were found noncompliant during the check. NonCompliantResourcesCount *int64 `locationName:"nonCompliantResourcesCount" type:"long"` + // Describes how many of the non-compliant resources created during the evaluation + // of an audit check were marked as suppressed. + SuppressedNonCompliantResourcesCount *int64 `locationName:"suppressedNonCompliantResourcesCount" type:"long"` + // The number of resources on which the check was performed. TotalResourcesCount *int64 `locationName:"totalResourcesCount" type:"long"` } @@ -20352,6 +23528,12 @@ func (s *AuditCheckDetails) SetNonCompliantResourcesCount(v int64) *AuditCheckDe return s } +// SetSuppressedNonCompliantResourcesCount sets the SuppressedNonCompliantResourcesCount field's value. +func (s *AuditCheckDetails) SetSuppressedNonCompliantResourcesCount(v int64) *AuditCheckDetails { + s.SuppressedNonCompliantResourcesCount = &v + return s +} + // SetTotalResourcesCount sets the TotalResourcesCount field's value. func (s *AuditCheckDetails) SetTotalResourcesCount(v int64) *AuditCheckDetails { s.TotalResourcesCount = &v @@ -20372,6 +23554,9 @@ type AuditFinding struct { // The time the result (finding) was discovered. FindingTime *time.Time `locationName:"findingTime" type:"timestamp"` + // Indicates whether the audit finding was suppressed or not during reporting. + IsSuppressed *bool `locationName:"isSuppressed" type:"boolean"` + // The resource that was found to be noncompliant with the audit check. NonCompliantResource *NonCompliantResource `locationName:"nonCompliantResource" type:"structure"` @@ -20422,6 +23607,12 @@ func (s *AuditFinding) SetFindingTime(v time.Time) *AuditFinding { return s } +// SetIsSuppressed sets the IsSuppressed field's value. +func (s *AuditFinding) SetIsSuppressed(v bool) *AuditFinding { + s.IsSuppressed = &v + return s +} + // SetNonCompliantResource sets the NonCompliantResource field's value. func (s *AuditFinding) SetNonCompliantResource(v *NonCompliantResource) *AuditFinding { s.NonCompliantResource = v @@ -20723,6 +23914,73 @@ func (s *AuditNotificationTarget) SetTargetArn(v string) *AuditNotificationTarge return s } +// Filters out specific findings of a Device Defender audit. +type AuditSuppression struct { + _ struct{} `type:"structure"` + + // An audit check name. Checks must be enabled for your account. (Use DescribeAccountAuditConfiguration + // to see the list of all checks, including those that are enabled or use UpdateAccountAuditConfiguration + // to select which checks are enabled.) + // + // CheckName is a required field + CheckName *string `locationName:"checkName" type:"string" required:"true"` + + // The description of the audit suppression. + Description *string `locationName:"description" type:"string"` + + // The expiration date (epoch timestamp in seconds) that you want the suppression + // to adhere to. + ExpirationDate *time.Time `locationName:"expirationDate" type:"timestamp"` + + // Information that identifies the noncompliant resource. + // + // ResourceIdentifier is a required field + ResourceIdentifier *ResourceIdentifier `locationName:"resourceIdentifier" type:"structure" required:"true"` + + // Indicates whether a suppression should exist indefinitely or not. + SuppressIndefinitely *bool `locationName:"suppressIndefinitely" type:"boolean"` +} + +// String returns the string representation +func (s AuditSuppression) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AuditSuppression) GoString() string { + return s.String() +} + +// SetCheckName sets the CheckName field's value. +func (s *AuditSuppression) SetCheckName(v string) *AuditSuppression { + s.CheckName = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *AuditSuppression) SetDescription(v string) *AuditSuppression { + s.Description = &v + return s +} + +// SetExpirationDate sets the ExpirationDate field's value. +func (s *AuditSuppression) SetExpirationDate(v time.Time) *AuditSuppression { + s.ExpirationDate = &v + return s +} + +// SetResourceIdentifier sets the ResourceIdentifier field's value. +func (s *AuditSuppression) SetResourceIdentifier(v *ResourceIdentifier) *AuditSuppression { + s.ResourceIdentifier = v + return s +} + +// SetSuppressIndefinitely sets the SuppressIndefinitely field's value. +func (s *AuditSuppression) SetSuppressIndefinitely(v bool) *AuditSuppression { + s.SuppressIndefinitely = &v + return s +} + // The audits that were performed. type AuditTaskMetadata struct { _ struct{} `type:"structure"` @@ -21055,10 +24313,155 @@ func (s *AuthorizerSummary) SetAuthorizerName(v string) *AuthorizerSummary { return s } +// The criteria that determine when and how a job abort takes place. +type AwsJobAbortConfig struct { + _ struct{} `type:"structure"` + + // The list of criteria that determine when and how to abort the job. + // + // AbortCriteriaList is a required field + AbortCriteriaList []*AwsJobAbortCriteria `locationName:"abortCriteriaList" min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s AwsJobAbortConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsJobAbortConfig) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AwsJobAbortConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AwsJobAbortConfig"} + if s.AbortCriteriaList == nil { + invalidParams.Add(request.NewErrParamRequired("AbortCriteriaList")) + } + if s.AbortCriteriaList != nil && len(s.AbortCriteriaList) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AbortCriteriaList", 1)) + } + if s.AbortCriteriaList != nil { + for i, v := range s.AbortCriteriaList { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "AbortCriteriaList", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAbortCriteriaList sets the AbortCriteriaList field's value. +func (s *AwsJobAbortConfig) SetAbortCriteriaList(v []*AwsJobAbortCriteria) *AwsJobAbortConfig { + s.AbortCriteriaList = v + return s +} + +// The criteria that determine when and how a job abort takes place. +type AwsJobAbortCriteria struct { + _ struct{} `type:"structure"` + + // The type of job action to take to initiate the job abort. + // + // Action is a required field + Action *string `locationName:"action" type:"string" required:"true" enum:"AwsJobAbortCriteriaAbortAction"` + + // The type of job execution failures that can initiate a job abort. + // + // FailureType is a required field + FailureType *string `locationName:"failureType" type:"string" required:"true" enum:"AwsJobAbortCriteriaFailureType"` + + // The minimum number of things which must receive job execution notifications + // before the job can be aborted. + // + // MinNumberOfExecutedThings is a required field + MinNumberOfExecutedThings *int64 `locationName:"minNumberOfExecutedThings" min:"1" type:"integer" required:"true"` + + // The minimum percentage of job execution failures that must occur to initiate + // the job abort. + // + // AWS IoT supports up to two digits after the decimal (for example, 10.9 and + // 10.99, but not 10.999). + // + // ThresholdPercentage is a required field + ThresholdPercentage *float64 `locationName:"thresholdPercentage" type:"double" required:"true"` +} + +// String returns the string representation +func (s AwsJobAbortCriteria) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsJobAbortCriteria) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AwsJobAbortCriteria) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AwsJobAbortCriteria"} + if s.Action == nil { + invalidParams.Add(request.NewErrParamRequired("Action")) + } + if s.FailureType == nil { + invalidParams.Add(request.NewErrParamRequired("FailureType")) + } + if s.MinNumberOfExecutedThings == nil { + invalidParams.Add(request.NewErrParamRequired("MinNumberOfExecutedThings")) + } + if s.MinNumberOfExecutedThings != nil && *s.MinNumberOfExecutedThings < 1 { + invalidParams.Add(request.NewErrParamMinValue("MinNumberOfExecutedThings", 1)) + } + if s.ThresholdPercentage == nil { + invalidParams.Add(request.NewErrParamRequired("ThresholdPercentage")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAction sets the Action field's value. +func (s *AwsJobAbortCriteria) SetAction(v string) *AwsJobAbortCriteria { + s.Action = &v + return s +} + +// SetFailureType sets the FailureType field's value. +func (s *AwsJobAbortCriteria) SetFailureType(v string) *AwsJobAbortCriteria { + s.FailureType = &v + return s +} + +// SetMinNumberOfExecutedThings sets the MinNumberOfExecutedThings field's value. +func (s *AwsJobAbortCriteria) SetMinNumberOfExecutedThings(v int64) *AwsJobAbortCriteria { + s.MinNumberOfExecutedThings = &v + return s +} + +// SetThresholdPercentage sets the ThresholdPercentage field's value. +func (s *AwsJobAbortCriteria) SetThresholdPercentage(v float64) *AwsJobAbortCriteria { + s.ThresholdPercentage = &v + return s +} + // Configuration for the rollout of OTA updates. type AwsJobExecutionsRolloutConfig struct { _ struct{} `type:"structure"` + // The rate of increase for a job rollout. This parameter allows you to define + // an exponential rate increase for a job rollout. + ExponentialRate *AwsJobExponentialRolloutRate `locationName:"exponentialRate" type:"structure"` + // The maximum number of OTA update job executions started per minute. MaximumPerMinute *int64 `locationName:"maximumPerMinute" min:"1" type:"integer"` } @@ -21079,6 +24482,11 @@ func (s *AwsJobExecutionsRolloutConfig) Validate() error { if s.MaximumPerMinute != nil && *s.MaximumPerMinute < 1 { invalidParams.Add(request.NewErrParamMinValue("MaximumPerMinute", 1)) } + if s.ExponentialRate != nil { + if err := s.ExponentialRate.Validate(); err != nil { + invalidParams.AddNested("ExponentialRate", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -21086,12 +24494,100 @@ func (s *AwsJobExecutionsRolloutConfig) Validate() error { return nil } +// SetExponentialRate sets the ExponentialRate field's value. +func (s *AwsJobExecutionsRolloutConfig) SetExponentialRate(v *AwsJobExponentialRolloutRate) *AwsJobExecutionsRolloutConfig { + s.ExponentialRate = v + return s +} + // SetMaximumPerMinute sets the MaximumPerMinute field's value. func (s *AwsJobExecutionsRolloutConfig) SetMaximumPerMinute(v int64) *AwsJobExecutionsRolloutConfig { s.MaximumPerMinute = &v return s } +// The rate of increase for a job rollout. This parameter allows you to define +// an exponential rate increase for a job rollout. +type AwsJobExponentialRolloutRate struct { + _ struct{} `type:"structure"` + + // The minimum number of things that will be notified of a pending job, per + // minute, at the start of the job rollout. This is the initial rate of the + // rollout. + // + // BaseRatePerMinute is a required field + BaseRatePerMinute *int64 `locationName:"baseRatePerMinute" min:"1" type:"integer" required:"true"` + + // The rate of increase for a job rollout. The number of things notified is + // multiplied by this factor. + // + // IncrementFactor is a required field + IncrementFactor *float64 `locationName:"incrementFactor" type:"double" required:"true"` + + // The criteria to initiate the increase in rate of rollout for a job. + // + // AWS IoT supports up to one digit after the decimal (for example, 1.5, but + // not 1.55). + // + // RateIncreaseCriteria is a required field + RateIncreaseCriteria *AwsJobRateIncreaseCriteria `locationName:"rateIncreaseCriteria" type:"structure" required:"true"` +} + +// String returns the string representation +func (s AwsJobExponentialRolloutRate) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsJobExponentialRolloutRate) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AwsJobExponentialRolloutRate) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AwsJobExponentialRolloutRate"} + if s.BaseRatePerMinute == nil { + invalidParams.Add(request.NewErrParamRequired("BaseRatePerMinute")) + } + if s.BaseRatePerMinute != nil && *s.BaseRatePerMinute < 1 { + invalidParams.Add(request.NewErrParamMinValue("BaseRatePerMinute", 1)) + } + if s.IncrementFactor == nil { + invalidParams.Add(request.NewErrParamRequired("IncrementFactor")) + } + if s.RateIncreaseCriteria == nil { + invalidParams.Add(request.NewErrParamRequired("RateIncreaseCriteria")) + } + if s.RateIncreaseCriteria != nil { + if err := s.RateIncreaseCriteria.Validate(); err != nil { + invalidParams.AddNested("RateIncreaseCriteria", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBaseRatePerMinute sets the BaseRatePerMinute field's value. +func (s *AwsJobExponentialRolloutRate) SetBaseRatePerMinute(v int64) *AwsJobExponentialRolloutRate { + s.BaseRatePerMinute = &v + return s +} + +// SetIncrementFactor sets the IncrementFactor field's value. +func (s *AwsJobExponentialRolloutRate) SetIncrementFactor(v float64) *AwsJobExponentialRolloutRate { + s.IncrementFactor = &v + return s +} + +// SetRateIncreaseCriteria sets the RateIncreaseCriteria field's value. +func (s *AwsJobExponentialRolloutRate) SetRateIncreaseCriteria(v *AwsJobRateIncreaseCriteria) *AwsJobExponentialRolloutRate { + s.RateIncreaseCriteria = v + return s +} + // Configuration information for pre-signed URLs. Valid when protocols contains // HTTP. type AwsJobPresignedUrlConfig struct { @@ -21119,6 +24615,89 @@ func (s *AwsJobPresignedUrlConfig) SetExpiresInSec(v int64) *AwsJobPresignedUrlC return s } +// The criteria to initiate the increase in rate of rollout for a job. +type AwsJobRateIncreaseCriteria struct { + _ struct{} `type:"structure"` + + // When this number of things have been notified, it will initiate an increase + // in the rollout rate. + NumberOfNotifiedThings *int64 `locationName:"numberOfNotifiedThings" min:"1" type:"integer"` + + // When this number of things have succeeded in their job execution, it will + // initiate an increase in the rollout rate. + NumberOfSucceededThings *int64 `locationName:"numberOfSucceededThings" min:"1" type:"integer"` +} + +// String returns the string representation +func (s AwsJobRateIncreaseCriteria) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsJobRateIncreaseCriteria) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AwsJobRateIncreaseCriteria) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AwsJobRateIncreaseCriteria"} + if s.NumberOfNotifiedThings != nil && *s.NumberOfNotifiedThings < 1 { + invalidParams.Add(request.NewErrParamMinValue("NumberOfNotifiedThings", 1)) + } + if s.NumberOfSucceededThings != nil && *s.NumberOfSucceededThings < 1 { + invalidParams.Add(request.NewErrParamMinValue("NumberOfSucceededThings", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetNumberOfNotifiedThings sets the NumberOfNotifiedThings field's value. +func (s *AwsJobRateIncreaseCriteria) SetNumberOfNotifiedThings(v int64) *AwsJobRateIncreaseCriteria { + s.NumberOfNotifiedThings = &v + return s +} + +// SetNumberOfSucceededThings sets the NumberOfSucceededThings field's value. +func (s *AwsJobRateIncreaseCriteria) SetNumberOfSucceededThings(v int64) *AwsJobRateIncreaseCriteria { + s.NumberOfSucceededThings = &v + return s +} + +// Specifies the amount of time each device has to finish its execution of the +// job. A timer is started when the job execution status is set to IN_PROGRESS. +// If the job execution status is not set to another terminal state before the +// timer expires, it will be automatically set to TIMED_OUT. +type AwsJobTimeoutConfig struct { + _ struct{} `type:"structure"` + + // Specifies the amount of time, in minutes, this device has to finish execution + // of this job. The timeout interval can be anywhere between 1 minute and 7 + // days (1 to 10080 minutes). The in progress timer can't be updated and will + // apply to all job executions for the job. Whenever a job execution remains + // in the IN_PROGRESS status for longer than this interval, the job execution + // will fail and switch to the terminal TIMED_OUT status. + InProgressTimeoutInMinutes *int64 `locationName:"inProgressTimeoutInMinutes" type:"long"` +} + +// String returns the string representation +func (s AwsJobTimeoutConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsJobTimeoutConfig) GoString() string { + return s.String() +} + +// SetInProgressTimeoutInMinutes sets the InProgressTimeoutInMinutes field's value. +func (s *AwsJobTimeoutConfig) SetInProgressTimeoutInMinutes(v int64) *AwsJobTimeoutConfig { + s.InProgressTimeoutInMinutes = &v + return s +} + // A Device Defender security profile behavior. type Behavior struct { _ struct{} `type:"structure"` @@ -22842,6 +26421,118 @@ func (s *ConflictingResourceUpdateException) RequestID() string { return s.RespMetadata.RequestID } +type CreateAuditSuppressionInput struct { + _ struct{} `type:"structure"` + + // An audit check name. Checks must be enabled for your account. (Use DescribeAccountAuditConfiguration + // to see the list of all checks, including those that are enabled or use UpdateAccountAuditConfiguration + // to select which checks are enabled.) + // + // CheckName is a required field + CheckName *string `locationName:"checkName" type:"string" required:"true"` + + // The epoch timestamp in seconds at which this suppression expires. + ClientRequestToken *string `locationName:"clientRequestToken" min:"1" type:"string" idempotencyToken:"true"` + + // The description of the audit suppression. + Description *string `locationName:"description" type:"string"` + + // The epoch timestamp in seconds at which this suppression expires. + ExpirationDate *time.Time `locationName:"expirationDate" type:"timestamp"` + + // Information that identifies the noncompliant resource. + // + // ResourceIdentifier is a required field + ResourceIdentifier *ResourceIdentifier `locationName:"resourceIdentifier" type:"structure" required:"true"` + + // Indicates whether a suppression should exist indefinitely or not. + SuppressIndefinitely *bool `locationName:"suppressIndefinitely" type:"boolean"` +} + +// String returns the string representation +func (s CreateAuditSuppressionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateAuditSuppressionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateAuditSuppressionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateAuditSuppressionInput"} + if s.CheckName == nil { + invalidParams.Add(request.NewErrParamRequired("CheckName")) + } + if s.ClientRequestToken != nil && len(*s.ClientRequestToken) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClientRequestToken", 1)) + } + if s.ResourceIdentifier == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceIdentifier")) + } + if s.ResourceIdentifier != nil { + if err := s.ResourceIdentifier.Validate(); err != nil { + invalidParams.AddNested("ResourceIdentifier", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCheckName sets the CheckName field's value. +func (s *CreateAuditSuppressionInput) SetCheckName(v string) *CreateAuditSuppressionInput { + s.CheckName = &v + return s +} + +// SetClientRequestToken sets the ClientRequestToken field's value. +func (s *CreateAuditSuppressionInput) SetClientRequestToken(v string) *CreateAuditSuppressionInput { + s.ClientRequestToken = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *CreateAuditSuppressionInput) SetDescription(v string) *CreateAuditSuppressionInput { + s.Description = &v + return s +} + +// SetExpirationDate sets the ExpirationDate field's value. +func (s *CreateAuditSuppressionInput) SetExpirationDate(v time.Time) *CreateAuditSuppressionInput { + s.ExpirationDate = &v + return s +} + +// SetResourceIdentifier sets the ResourceIdentifier field's value. +func (s *CreateAuditSuppressionInput) SetResourceIdentifier(v *ResourceIdentifier) *CreateAuditSuppressionInput { + s.ResourceIdentifier = v + return s +} + +// SetSuppressIndefinitely sets the SuppressIndefinitely field's value. +func (s *CreateAuditSuppressionInput) SetSuppressIndefinitely(v bool) *CreateAuditSuppressionInput { + s.SuppressIndefinitely = &v + return s +} + +type CreateAuditSuppressionOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s CreateAuditSuppressionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateAuditSuppressionOutput) GoString() string { + return s.String() +} + type CreateAuthorizerInput struct { _ struct{} `type:"structure"` @@ -24122,12 +27813,21 @@ type CreateOTAUpdateInput struct { // A list of additional OTA update parameters which are name-value pairs. AdditionalParameters map[string]*string `locationName:"additionalParameters" type:"map"` + // The criteria that determine when and how a job abort takes place. + AwsJobAbortConfig *AwsJobAbortConfig `locationName:"awsJobAbortConfig" type:"structure"` + // Configuration for the rollout of OTA updates. AwsJobExecutionsRolloutConfig *AwsJobExecutionsRolloutConfig `locationName:"awsJobExecutionsRolloutConfig" type:"structure"` // Configuration information for pre-signed URLs. AwsJobPresignedUrlConfig *AwsJobPresignedUrlConfig `locationName:"awsJobPresignedUrlConfig" type:"structure"` + // Specifies the amount of time each device has to finish its execution of the + // job. A timer is started when the job execution status is set to IN_PROGRESS. + // If the job execution status is not set to another terminal state before the + // timer expires, it will be automatically set to TIMED_OUT. + AwsJobTimeoutConfig *AwsJobTimeoutConfig `locationName:"awsJobTimeoutConfig" type:"structure"` + // The description of the OTA update. Description *string `locationName:"description" type:"string"` @@ -24146,7 +27846,8 @@ type CreateOTAUpdateInput struct { // can choose the protocol. Protocols []*string `locationName:"protocols" min:"1" type:"list"` - // The IAM role that allows access to the AWS IoT Jobs service. + // The IAM role that grants AWS IoT access to the Amazon S3, AWS IoT jobs and + // AWS Code Signing resources to create an OTA update job. // // RoleArn is a required field RoleArn *string `locationName:"roleArn" min:"20" type:"string" required:"true"` @@ -24162,7 +27863,7 @@ type CreateOTAUpdateInput struct { // by all things originally in the group. Valid values: CONTINUOUS | SNAPSHOT. TargetSelection *string `locationName:"targetSelection" type:"string" enum:"TargetSelection"` - // The targeted devices to receive OTA updates. + // The devices targeted to receive OTA updates. // // Targets is a required field Targets []*string `locationName:"targets" min:"1" type:"list" required:"true"` @@ -24208,6 +27909,11 @@ func (s *CreateOTAUpdateInput) Validate() error { if s.Targets != nil && len(s.Targets) < 1 { invalidParams.Add(request.NewErrParamMinLen("Targets", 1)) } + if s.AwsJobAbortConfig != nil { + if err := s.AwsJobAbortConfig.Validate(); err != nil { + invalidParams.AddNested("AwsJobAbortConfig", err.(request.ErrInvalidParams)) + } + } if s.AwsJobExecutionsRolloutConfig != nil { if err := s.AwsJobExecutionsRolloutConfig.Validate(); err != nil { invalidParams.AddNested("AwsJobExecutionsRolloutConfig", err.(request.ErrInvalidParams)) @@ -24246,6 +27952,12 @@ func (s *CreateOTAUpdateInput) SetAdditionalParameters(v map[string]*string) *Cr return s } +// SetAwsJobAbortConfig sets the AwsJobAbortConfig field's value. +func (s *CreateOTAUpdateInput) SetAwsJobAbortConfig(v *AwsJobAbortConfig) *CreateOTAUpdateInput { + s.AwsJobAbortConfig = v + return s +} + // SetAwsJobExecutionsRolloutConfig sets the AwsJobExecutionsRolloutConfig field's value. func (s *CreateOTAUpdateInput) SetAwsJobExecutionsRolloutConfig(v *AwsJobExecutionsRolloutConfig) *CreateOTAUpdateInput { s.AwsJobExecutionsRolloutConfig = v @@ -24258,6 +27970,12 @@ func (s *CreateOTAUpdateInput) SetAwsJobPresignedUrlConfig(v *AwsJobPresignedUrl return s } +// SetAwsJobTimeoutConfig sets the AwsJobTimeoutConfig field's value. +func (s *CreateOTAUpdateInput) SetAwsJobTimeoutConfig(v *AwsJobTimeoutConfig) *CreateOTAUpdateInput { + s.AwsJobTimeoutConfig = v + return s +} + // SetDescription sets the Description field's value. func (s *CreateOTAUpdateInput) SetDescription(v string) *CreateOTAUpdateInput { s.Description = &v @@ -26207,6 +29925,79 @@ func (s DeleteAccountAuditConfigurationOutput) GoString() string { return s.String() } +type DeleteAuditSuppressionInput struct { + _ struct{} `type:"structure"` + + // An audit check name. Checks must be enabled for your account. (Use DescribeAccountAuditConfiguration + // to see the list of all checks, including those that are enabled or use UpdateAccountAuditConfiguration + // to select which checks are enabled.) + // + // CheckName is a required field + CheckName *string `locationName:"checkName" type:"string" required:"true"` + + // Information that identifies the noncompliant resource. + // + // ResourceIdentifier is a required field + ResourceIdentifier *ResourceIdentifier `locationName:"resourceIdentifier" type:"structure" required:"true"` +} + +// String returns the string representation +func (s DeleteAuditSuppressionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteAuditSuppressionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteAuditSuppressionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteAuditSuppressionInput"} + if s.CheckName == nil { + invalidParams.Add(request.NewErrParamRequired("CheckName")) + } + if s.ResourceIdentifier == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceIdentifier")) + } + if s.ResourceIdentifier != nil { + if err := s.ResourceIdentifier.Validate(); err != nil { + invalidParams.AddNested("ResourceIdentifier", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCheckName sets the CheckName field's value. +func (s *DeleteAuditSuppressionInput) SetCheckName(v string) *DeleteAuditSuppressionInput { + s.CheckName = &v + return s +} + +// SetResourceIdentifier sets the ResourceIdentifier field's value. +func (s *DeleteAuditSuppressionInput) SetResourceIdentifier(v *ResourceIdentifier) *DeleteAuditSuppressionInput { + s.ResourceIdentifier = v + return s +} + +type DeleteAuditSuppressionOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteAuditSuppressionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteAuditSuppressionOutput) GoString() string { + return s.String() +} + type DeleteAuthorizerInput struct { _ struct{} `type:"structure"` @@ -26928,10 +30719,10 @@ type DeleteOTAUpdateInput struct { DeleteStream *bool `location:"querystring" locationName:"deleteStream" type:"boolean"` // Specifies if the AWS Job associated with the OTA update should be deleted - // with the OTA update is deleted. + // when the OTA update is deleted. ForceDeleteAWSJob *bool `location:"querystring" locationName:"forceDeleteAWSJob" type:"boolean"` - // The OTA update ID to delete. + // The ID of the OTA update to delete. // // OtaUpdateId is a required field OtaUpdateId *string `location:"uri" locationName:"otaUpdateId" min:"1" type:"string" required:"true"` @@ -28224,6 +32015,126 @@ func (s *DescribeAuditMitigationActionsTaskOutput) SetTaskStatus(v string) *Desc return s } +type DescribeAuditSuppressionInput struct { + _ struct{} `type:"structure"` + + // An audit check name. Checks must be enabled for your account. (Use DescribeAccountAuditConfiguration + // to see the list of all checks, including those that are enabled or use UpdateAccountAuditConfiguration + // to select which checks are enabled.) + // + // CheckName is a required field + CheckName *string `locationName:"checkName" type:"string" required:"true"` + + // Information that identifies the noncompliant resource. + // + // ResourceIdentifier is a required field + ResourceIdentifier *ResourceIdentifier `locationName:"resourceIdentifier" type:"structure" required:"true"` +} + +// String returns the string representation +func (s DescribeAuditSuppressionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeAuditSuppressionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeAuditSuppressionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeAuditSuppressionInput"} + if s.CheckName == nil { + invalidParams.Add(request.NewErrParamRequired("CheckName")) + } + if s.ResourceIdentifier == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceIdentifier")) + } + if s.ResourceIdentifier != nil { + if err := s.ResourceIdentifier.Validate(); err != nil { + invalidParams.AddNested("ResourceIdentifier", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCheckName sets the CheckName field's value. +func (s *DescribeAuditSuppressionInput) SetCheckName(v string) *DescribeAuditSuppressionInput { + s.CheckName = &v + return s +} + +// SetResourceIdentifier sets the ResourceIdentifier field's value. +func (s *DescribeAuditSuppressionInput) SetResourceIdentifier(v *ResourceIdentifier) *DescribeAuditSuppressionInput { + s.ResourceIdentifier = v + return s +} + +type DescribeAuditSuppressionOutput struct { + _ struct{} `type:"structure"` + + // An audit check name. Checks must be enabled for your account. (Use DescribeAccountAuditConfiguration + // to see the list of all checks, including those that are enabled or use UpdateAccountAuditConfiguration + // to select which checks are enabled.) + CheckName *string `locationName:"checkName" type:"string"` + + // The description of the audit suppression. + Description *string `locationName:"description" type:"string"` + + // The epoch timestamp in seconds at which this suppression expires. + ExpirationDate *time.Time `locationName:"expirationDate" type:"timestamp"` + + // Information that identifies the noncompliant resource. + ResourceIdentifier *ResourceIdentifier `locationName:"resourceIdentifier" type:"structure"` + + // Indicates whether a suppression should exist indefinitely or not. + SuppressIndefinitely *bool `locationName:"suppressIndefinitely" type:"boolean"` +} + +// String returns the string representation +func (s DescribeAuditSuppressionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeAuditSuppressionOutput) GoString() string { + return s.String() +} + +// SetCheckName sets the CheckName field's value. +func (s *DescribeAuditSuppressionOutput) SetCheckName(v string) *DescribeAuditSuppressionOutput { + s.CheckName = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *DescribeAuditSuppressionOutput) SetDescription(v string) *DescribeAuditSuppressionOutput { + s.Description = &v + return s +} + +// SetExpirationDate sets the ExpirationDate field's value. +func (s *DescribeAuditSuppressionOutput) SetExpirationDate(v time.Time) *DescribeAuditSuppressionOutput { + s.ExpirationDate = &v + return s +} + +// SetResourceIdentifier sets the ResourceIdentifier field's value. +func (s *DescribeAuditSuppressionOutput) SetResourceIdentifier(v *ResourceIdentifier) *DescribeAuditSuppressionOutput { + s.ResourceIdentifier = v + return s +} + +// SetSuppressIndefinitely sets the SuppressIndefinitely field's value. +func (s *DescribeAuditSuppressionOutput) SetSuppressIndefinitely(v bool) *DescribeAuditSuppressionOutput { + s.SuppressIndefinitely = &v + return s +} + type DescribeAuditTaskInput struct { _ struct{} `type:"structure"` @@ -30750,8 +34661,9 @@ type DetachPrincipalPolicyInput struct { // The principal. // - // If the principal is a certificate, specify the certificate ARN. If the principal - // is an Amazon Cognito identity, specify the identity ID. + // Valid principals are CertificateArn (arn:aws:iot:region:accountId:cert/certificateId), + // thingGroupArn (arn:aws:iot:region:accountId:thinggroup/groupName) and CognitoId + // (region:id). // // Principal is a required field Principal *string `location:"header" locationName:"x-amzn-iot-principal" type:"string" required:"true"` @@ -31926,7 +35838,9 @@ type GetEffectivePoliciesInput struct { // The Cognito identity pool ID. CognitoIdentityPoolId *string `locationName:"cognitoIdentityPoolId" type:"string"` - // The principal. + // The principal. Valid principals are CertificateArn (arn:aws:iot:region:accountId:cert/certificateId), + // thingGroupArn (arn:aws:iot:region:accountId:thinggroup/groupName) and CognitoId + // (region:id). Principal *string `locationName:"principal" type:"string"` // The thing name. @@ -34943,7 +38857,9 @@ type ListAttachedPoliciesInput struct { // When true, recursively list attached policies. Recursive *bool `location:"querystring" locationName:"recursive" type:"boolean"` - // The group or principal for which the policies will be listed. + // The group or principal for which the policies will be listed. Valid principals + // are CertificateArn (arn:aws:iot:region:accountId:cert/certificateId), thingGroupArn + // (arn:aws:iot:region:accountId:thinggroup/groupName) and CognitoId (region:id). // // Target is a required field Target *string `location:"uri" locationName:"target" type:"string" required:"true"` @@ -35045,6 +38961,11 @@ type ListAuditFindingsInput struct { // specify either the startTime and endTime or the taskId, but not both. EndTime *time.Time `locationName:"endTime" type:"timestamp"` + // Boolean flag indicating whether only the suppressed findings or the unsuppressed + // findings should be listed. If this parameter isn't provided, the response + // will list both suppressed and unsuppressed findings. + ListSuppressedFindings *bool `locationName:"listSuppressedFindings" type:"boolean"` + // The maximum number of results to return at one time. The default is 25. MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` @@ -35106,6 +39027,12 @@ func (s *ListAuditFindingsInput) SetEndTime(v time.Time) *ListAuditFindingsInput return s } +// SetListSuppressedFindings sets the ListSuppressedFindings field's value. +func (s *ListAuditFindingsInput) SetListSuppressedFindings(v bool) *ListAuditFindingsInput { + s.ListSuppressedFindings = &v + return s +} + // SetMaxResults sets the MaxResults field's value. func (s *ListAuditFindingsInput) SetMaxResults(v int64) *ListAuditFindingsInput { s.MaxResults = &v @@ -35434,6 +39361,119 @@ func (s *ListAuditMitigationActionsTasksOutput) SetTasks(v []*AuditMitigationAct return s } +type ListAuditSuppressionsInput struct { + _ struct{} `type:"structure"` + + // Determines whether suppressions are listed in ascending order by expiration + // date or not. If parameter isn't provided, ascendingOrder=true. + AscendingOrder *bool `locationName:"ascendingOrder" type:"boolean"` + + // An audit check name. Checks must be enabled for your account. (Use DescribeAccountAuditConfiguration + // to see the list of all checks, including those that are enabled or use UpdateAccountAuditConfiguration + // to select which checks are enabled.) + CheckName *string `locationName:"checkName" type:"string"` + + // The maximum number of results to return at one time. The default is 25. + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` + + // The token for the next set of results. + NextToken *string `locationName:"nextToken" type:"string"` + + // Information that identifies the noncompliant resource. + ResourceIdentifier *ResourceIdentifier `locationName:"resourceIdentifier" type:"structure"` +} + +// String returns the string representation +func (s ListAuditSuppressionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListAuditSuppressionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListAuditSuppressionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListAuditSuppressionsInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.ResourceIdentifier != nil { + if err := s.ResourceIdentifier.Validate(); err != nil { + invalidParams.AddNested("ResourceIdentifier", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAscendingOrder sets the AscendingOrder field's value. +func (s *ListAuditSuppressionsInput) SetAscendingOrder(v bool) *ListAuditSuppressionsInput { + s.AscendingOrder = &v + return s +} + +// SetCheckName sets the CheckName field's value. +func (s *ListAuditSuppressionsInput) SetCheckName(v string) *ListAuditSuppressionsInput { + s.CheckName = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListAuditSuppressionsInput) SetMaxResults(v int64) *ListAuditSuppressionsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListAuditSuppressionsInput) SetNextToken(v string) *ListAuditSuppressionsInput { + s.NextToken = &v + return s +} + +// SetResourceIdentifier sets the ResourceIdentifier field's value. +func (s *ListAuditSuppressionsInput) SetResourceIdentifier(v *ResourceIdentifier) *ListAuditSuppressionsInput { + s.ResourceIdentifier = v + return s +} + +type ListAuditSuppressionsOutput struct { + _ struct{} `type:"structure"` + + // A token that can be used to retrieve the next set of results, or null if + // there are no additional results. + NextToken *string `locationName:"nextToken" type:"string"` + + // List of audit suppressions. + Suppressions []*AuditSuppression `locationName:"suppressions" type:"list"` +} + +// String returns the string representation +func (s ListAuditSuppressionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListAuditSuppressionsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListAuditSuppressionsOutput) SetNextToken(v string) *ListAuditSuppressionsOutput { + s.NextToken = &v + return s +} + +// SetSuppressions sets the Suppressions field's value. +func (s *ListAuditSuppressionsOutput) SetSuppressions(v []*AuditSuppression) *ListAuditSuppressionsOutput { + s.Suppressions = v + return s +} + type ListAuditTasksInput struct { _ struct{} `type:"structure"` @@ -37152,7 +41192,9 @@ type ListPrincipalPoliciesInput struct { // The result page size. PageSize *int64 `location:"querystring" locationName:"pageSize" min:"1" type:"integer"` - // The principal. + // The principal. Valid principals are CertificateArn (arn:aws:iot:region:accountId:cert/certificateId), + // thingGroupArn (arn:aws:iot:region:accountId:thinggroup/groupName) and CognitoId + // (region:id). // // Principal is a required field Principal *string `location:"header" locationName:"x-amzn-iot-principal" type:"string" required:"true"` @@ -38394,8 +42436,8 @@ func (s *ListThingGroupsInput) SetRecursive(v bool) *ListThingGroupsInput { type ListThingGroupsOutput struct { _ struct{} `type:"structure"` - // The token used to get the next set of results, or null if there are no additional - // results. + // The token used to get the next set of results. Will not be returned if operation + // has returned all results. NextToken *string `locationName:"nextToken" type:"string"` // The thing groups. @@ -38757,8 +42799,8 @@ func (s *ListThingTypesInput) SetThingTypeName(v string) *ListThingTypesInput { type ListThingTypesOutput struct { _ struct{} `type:"structure"` - // The token for the next set of results, or null if there are no additional - // results. + // The token for the next set of results. Will not be returned if operation + // has returned all results. NextToken *string `locationName:"nextToken" type:"string"` // The thing types. @@ -38852,8 +42894,8 @@ func (s *ListThingsInBillingGroupInput) SetNextToken(v string) *ListThingsInBill type ListThingsInBillingGroupOutput struct { _ struct{} `type:"structure"` - // The token used to get the next set of results, or null if there are no additional - // results. + // The token used to get the next set of results. Will not be returned if operation + // has returned all results. NextToken *string `locationName:"nextToken" type:"string"` // A list of things in the billing group. @@ -39066,8 +43108,8 @@ func (s *ListThingsInput) SetThingTypeName(v string) *ListThingsInput { type ListThingsOutput struct { _ struct{} `type:"structure"` - // The token used to get the next set of results, or null if there are no additional - // results. + // The token used to get the next set of results. Will not be returned if operation + // has returned all results. NextToken *string `locationName:"nextToken" type:"string"` // The things. @@ -44936,7 +48978,9 @@ type TestAuthorizationInput struct { // as if they are not attached to the principal being authorized. PolicyNamesToSkip []*string `locationName:"policyNamesToSkip" type:"list"` - // The principal. + // The principal. Valid principals are CertificateArn (arn:aws:iot:region:accountId:cert/certificateId), + // thingGroupArn (arn:aws:iot:region:accountId:thinggroup/groupName) and CognitoId + // (region:id). Principal *string `locationName:"principal" type:"string"` } @@ -46842,6 +50886,107 @@ func (s UpdateAccountAuditConfigurationOutput) GoString() string { return s.String() } +type UpdateAuditSuppressionInput struct { + _ struct{} `type:"structure"` + + // An audit check name. Checks must be enabled for your account. (Use DescribeAccountAuditConfiguration + // to see the list of all checks, including those that are enabled or use UpdateAccountAuditConfiguration + // to select which checks are enabled.) + // + // CheckName is a required field + CheckName *string `locationName:"checkName" type:"string" required:"true"` + + // The description of the audit suppression. + Description *string `locationName:"description" type:"string"` + + // The expiration date (epoch timestamp in seconds) that you want the suppression + // to adhere to. + ExpirationDate *time.Time `locationName:"expirationDate" type:"timestamp"` + + // Information that identifies the noncompliant resource. + // + // ResourceIdentifier is a required field + ResourceIdentifier *ResourceIdentifier `locationName:"resourceIdentifier" type:"structure" required:"true"` + + // Indicates whether a suppression should exist indefinitely or not. + SuppressIndefinitely *bool `locationName:"suppressIndefinitely" type:"boolean"` +} + +// String returns the string representation +func (s UpdateAuditSuppressionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateAuditSuppressionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateAuditSuppressionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateAuditSuppressionInput"} + if s.CheckName == nil { + invalidParams.Add(request.NewErrParamRequired("CheckName")) + } + if s.ResourceIdentifier == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceIdentifier")) + } + if s.ResourceIdentifier != nil { + if err := s.ResourceIdentifier.Validate(); err != nil { + invalidParams.AddNested("ResourceIdentifier", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCheckName sets the CheckName field's value. +func (s *UpdateAuditSuppressionInput) SetCheckName(v string) *UpdateAuditSuppressionInput { + s.CheckName = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *UpdateAuditSuppressionInput) SetDescription(v string) *UpdateAuditSuppressionInput { + s.Description = &v + return s +} + +// SetExpirationDate sets the ExpirationDate field's value. +func (s *UpdateAuditSuppressionInput) SetExpirationDate(v time.Time) *UpdateAuditSuppressionInput { + s.ExpirationDate = &v + return s +} + +// SetResourceIdentifier sets the ResourceIdentifier field's value. +func (s *UpdateAuditSuppressionInput) SetResourceIdentifier(v *ResourceIdentifier) *UpdateAuditSuppressionInput { + s.ResourceIdentifier = v + return s +} + +// SetSuppressIndefinitely sets the SuppressIndefinitely field's value. +func (s *UpdateAuditSuppressionInput) SetSuppressIndefinitely(v bool) *UpdateAuditSuppressionInput { + s.SuppressIndefinitely = &v + return s +} + +type UpdateAuditSuppressionOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UpdateAuditSuppressionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateAuditSuppressionOutput) GoString() string { + return s.String() +} + type UpdateAuthorizerInput struct { _ struct{} `type:"structure"` @@ -49399,6 +53544,13 @@ const ( AbortActionCancel = "CANCEL" ) +// AbortAction_Values returns all elements of the AbortAction enum +func AbortAction_Values() []string { + return []string{ + AbortActionCancel, + } +} + const ( // ActionTypePublish is a ActionType enum value ActionTypePublish = "PUBLISH" @@ -49413,12 +53565,29 @@ const ( ActionTypeConnect = "CONNECT" ) +// ActionType_Values returns all elements of the ActionType enum +func ActionType_Values() []string { + return []string{ + ActionTypePublish, + ActionTypeSubscribe, + ActionTypeReceive, + ActionTypeConnect, + } +} + // The type of alert target: one of "SNS". const ( // AlertTargetTypeSns is a AlertTargetType enum value AlertTargetTypeSns = "SNS" ) +// AlertTargetType_Values returns all elements of the AlertTargetType enum +func AlertTargetType_Values() []string { + return []string{ + AlertTargetTypeSns, + } +} + const ( // AuditCheckRunStatusInProgress is a AuditCheckRunStatus enum value AuditCheckRunStatusInProgress = "IN_PROGRESS" @@ -49439,6 +53608,18 @@ const ( AuditCheckRunStatusFailed = "FAILED" ) +// AuditCheckRunStatus_Values returns all elements of the AuditCheckRunStatus enum +func AuditCheckRunStatus_Values() []string { + return []string{ + AuditCheckRunStatusInProgress, + AuditCheckRunStatusWaitingForDataCollection, + AuditCheckRunStatusCanceled, + AuditCheckRunStatusCompletedCompliant, + AuditCheckRunStatusCompletedNonCompliant, + AuditCheckRunStatusFailed, + } +} + const ( // AuditFindingSeverityCritical is a AuditFindingSeverity enum value AuditFindingSeverityCritical = "CRITICAL" @@ -49453,6 +53634,16 @@ const ( AuditFindingSeverityLow = "LOW" ) +// AuditFindingSeverity_Values returns all elements of the AuditFindingSeverity enum +func AuditFindingSeverity_Values() []string { + return []string{ + AuditFindingSeverityCritical, + AuditFindingSeverityHigh, + AuditFindingSeverityMedium, + AuditFindingSeverityLow, + } +} + const ( // AuditFrequencyDaily is a AuditFrequency enum value AuditFrequencyDaily = "DAILY" @@ -49467,6 +53658,16 @@ const ( AuditFrequencyMonthly = "MONTHLY" ) +// AuditFrequency_Values returns all elements of the AuditFrequency enum +func AuditFrequency_Values() []string { + return []string{ + AuditFrequencyDaily, + AuditFrequencyWeekly, + AuditFrequencyBiweekly, + AuditFrequencyMonthly, + } +} + const ( // AuditMitigationActionsExecutionStatusInProgress is a AuditMitigationActionsExecutionStatus enum value AuditMitigationActionsExecutionStatusInProgress = "IN_PROGRESS" @@ -49487,6 +53688,18 @@ const ( AuditMitigationActionsExecutionStatusPending = "PENDING" ) +// AuditMitigationActionsExecutionStatus_Values returns all elements of the AuditMitigationActionsExecutionStatus enum +func AuditMitigationActionsExecutionStatus_Values() []string { + return []string{ + AuditMitigationActionsExecutionStatusInProgress, + AuditMitigationActionsExecutionStatusCompleted, + AuditMitigationActionsExecutionStatusFailed, + AuditMitigationActionsExecutionStatusCanceled, + AuditMitigationActionsExecutionStatusSkipped, + AuditMitigationActionsExecutionStatusPending, + } +} + const ( // AuditMitigationActionsTaskStatusInProgress is a AuditMitigationActionsTaskStatus enum value AuditMitigationActionsTaskStatusInProgress = "IN_PROGRESS" @@ -49501,11 +53714,28 @@ const ( AuditMitigationActionsTaskStatusCanceled = "CANCELED" ) +// AuditMitigationActionsTaskStatus_Values returns all elements of the AuditMitigationActionsTaskStatus enum +func AuditMitigationActionsTaskStatus_Values() []string { + return []string{ + AuditMitigationActionsTaskStatusInProgress, + AuditMitigationActionsTaskStatusCompleted, + AuditMitigationActionsTaskStatusFailed, + AuditMitigationActionsTaskStatusCanceled, + } +} + const ( // AuditNotificationTypeSns is a AuditNotificationType enum value AuditNotificationTypeSns = "SNS" ) +// AuditNotificationType_Values returns all elements of the AuditNotificationType enum +func AuditNotificationType_Values() []string { + return []string{ + AuditNotificationTypeSns, + } +} + const ( // AuditTaskStatusInProgress is a AuditTaskStatus enum value AuditTaskStatusInProgress = "IN_PROGRESS" @@ -49520,6 +53750,16 @@ const ( AuditTaskStatusCanceled = "CANCELED" ) +// AuditTaskStatus_Values returns all elements of the AuditTaskStatus enum +func AuditTaskStatus_Values() []string { + return []string{ + AuditTaskStatusInProgress, + AuditTaskStatusCompleted, + AuditTaskStatusFailed, + AuditTaskStatusCanceled, + } +} + const ( // AuditTaskTypeOnDemandAuditTask is a AuditTaskType enum value AuditTaskTypeOnDemandAuditTask = "ON_DEMAND_AUDIT_TASK" @@ -49528,6 +53768,14 @@ const ( AuditTaskTypeScheduledAuditTask = "SCHEDULED_AUDIT_TASK" ) +// AuditTaskType_Values returns all elements of the AuditTaskType enum +func AuditTaskType_Values() []string { + return []string{ + AuditTaskTypeOnDemandAuditTask, + AuditTaskTypeScheduledAuditTask, + } +} + const ( // AuthDecisionAllowed is a AuthDecision enum value AuthDecisionAllowed = "ALLOWED" @@ -49539,6 +53787,15 @@ const ( AuthDecisionImplicitDeny = "IMPLICIT_DENY" ) +// AuthDecision_Values returns all elements of the AuthDecision enum +func AuthDecision_Values() []string { + return []string{ + AuthDecisionAllowed, + AuthDecisionExplicitDeny, + AuthDecisionImplicitDeny, + } +} + const ( // AuthorizerStatusActive is a AuthorizerStatus enum value AuthorizerStatusActive = "ACTIVE" @@ -49547,6 +53804,14 @@ const ( AuthorizerStatusInactive = "INACTIVE" ) +// AuthorizerStatus_Values returns all elements of the AuthorizerStatus enum +func AuthorizerStatus_Values() []string { + return []string{ + AuthorizerStatusActive, + AuthorizerStatusInactive, + } +} + const ( // AutoRegistrationStatusEnable is a AutoRegistrationStatus enum value AutoRegistrationStatusEnable = "ENABLE" @@ -49555,6 +53820,50 @@ const ( AutoRegistrationStatusDisable = "DISABLE" ) +// AutoRegistrationStatus_Values returns all elements of the AutoRegistrationStatus enum +func AutoRegistrationStatus_Values() []string { + return []string{ + AutoRegistrationStatusEnable, + AutoRegistrationStatusDisable, + } +} + +const ( + // AwsJobAbortCriteriaAbortActionCancel is a AwsJobAbortCriteriaAbortAction enum value + AwsJobAbortCriteriaAbortActionCancel = "CANCEL" +) + +// AwsJobAbortCriteriaAbortAction_Values returns all elements of the AwsJobAbortCriteriaAbortAction enum +func AwsJobAbortCriteriaAbortAction_Values() []string { + return []string{ + AwsJobAbortCriteriaAbortActionCancel, + } +} + +const ( + // AwsJobAbortCriteriaFailureTypeFailed is a AwsJobAbortCriteriaFailureType enum value + AwsJobAbortCriteriaFailureTypeFailed = "FAILED" + + // AwsJobAbortCriteriaFailureTypeRejected is a AwsJobAbortCriteriaFailureType enum value + AwsJobAbortCriteriaFailureTypeRejected = "REJECTED" + + // AwsJobAbortCriteriaFailureTypeTimedOut is a AwsJobAbortCriteriaFailureType enum value + AwsJobAbortCriteriaFailureTypeTimedOut = "TIMED_OUT" + + // AwsJobAbortCriteriaFailureTypeAll is a AwsJobAbortCriteriaFailureType enum value + AwsJobAbortCriteriaFailureTypeAll = "ALL" +) + +// AwsJobAbortCriteriaFailureType_Values returns all elements of the AwsJobAbortCriteriaFailureType enum +func AwsJobAbortCriteriaFailureType_Values() []string { + return []string{ + AwsJobAbortCriteriaFailureTypeFailed, + AwsJobAbortCriteriaFailureTypeRejected, + AwsJobAbortCriteriaFailureTypeTimedOut, + AwsJobAbortCriteriaFailureTypeAll, + } +} + const ( // CACertificateStatusActive is a CACertificateStatus enum value CACertificateStatusActive = "ACTIVE" @@ -49563,11 +53872,26 @@ const ( CACertificateStatusInactive = "INACTIVE" ) +// CACertificateStatus_Values returns all elements of the CACertificateStatus enum +func CACertificateStatus_Values() []string { + return []string{ + CACertificateStatusActive, + CACertificateStatusInactive, + } +} + const ( // CACertificateUpdateActionDeactivate is a CACertificateUpdateAction enum value CACertificateUpdateActionDeactivate = "DEACTIVATE" ) +// CACertificateUpdateAction_Values returns all elements of the CACertificateUpdateAction enum +func CACertificateUpdateAction_Values() []string { + return []string{ + CACertificateUpdateActionDeactivate, + } +} + const ( // CannedAccessControlListPrivate is a CannedAccessControlList enum value CannedAccessControlListPrivate = "private" @@ -49594,6 +53918,20 @@ const ( CannedAccessControlListLogDeliveryWrite = "log-delivery-write" ) +// CannedAccessControlList_Values returns all elements of the CannedAccessControlList enum +func CannedAccessControlList_Values() []string { + return []string{ + CannedAccessControlListPrivate, + CannedAccessControlListPublicRead, + CannedAccessControlListPublicReadWrite, + CannedAccessControlListAwsExecRead, + CannedAccessControlListAuthenticatedRead, + CannedAccessControlListBucketOwnerRead, + CannedAccessControlListBucketOwnerFullControl, + CannedAccessControlListLogDeliveryWrite, + } +} + const ( // CertificateModeDefault is a CertificateMode enum value CertificateModeDefault = "DEFAULT" @@ -49602,6 +53940,14 @@ const ( CertificateModeSniOnly = "SNI_ONLY" ) +// CertificateMode_Values returns all elements of the CertificateMode enum +func CertificateMode_Values() []string { + return []string{ + CertificateModeDefault, + CertificateModeSniOnly, + } +} + const ( // CertificateStatusActive is a CertificateStatus enum value CertificateStatusActive = "ACTIVE" @@ -49622,6 +53968,18 @@ const ( CertificateStatusPendingActivation = "PENDING_ACTIVATION" ) +// CertificateStatus_Values returns all elements of the CertificateStatus enum +func CertificateStatus_Values() []string { + return []string{ + CertificateStatusActive, + CertificateStatusInactive, + CertificateStatusRevoked, + CertificateStatusPendingTransfer, + CertificateStatusRegisterInactive, + CertificateStatusPendingActivation, + } +} + const ( // ComparisonOperatorLessThan is a ComparisonOperator enum value ComparisonOperatorLessThan = "less-than" @@ -49648,6 +54006,20 @@ const ( ComparisonOperatorNotInPortSet = "not-in-port-set" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorLessThan, + ComparisonOperatorLessThanEquals, + ComparisonOperatorGreaterThan, + ComparisonOperatorGreaterThanEquals, + ComparisonOperatorInCidrSet, + ComparisonOperatorNotInCidrSet, + ComparisonOperatorInPortSet, + ComparisonOperatorNotInPortSet, + } +} + const ( // DayOfWeekSun is a DayOfWeek enum value DayOfWeekSun = "SUN" @@ -49671,16 +54043,43 @@ const ( DayOfWeekSat = "SAT" ) +// DayOfWeek_Values returns all elements of the DayOfWeek enum +func DayOfWeek_Values() []string { + return []string{ + DayOfWeekSun, + DayOfWeekMon, + DayOfWeekTue, + DayOfWeekWed, + DayOfWeekThu, + DayOfWeekFri, + DayOfWeekSat, + } +} + const ( // DeviceCertificateUpdateActionDeactivate is a DeviceCertificateUpdateAction enum value DeviceCertificateUpdateActionDeactivate = "DEACTIVATE" ) +// DeviceCertificateUpdateAction_Values returns all elements of the DeviceCertificateUpdateAction enum +func DeviceCertificateUpdateAction_Values() []string { + return []string{ + DeviceCertificateUpdateActionDeactivate, + } +} + const ( // DimensionTypeTopicFilter is a DimensionType enum value DimensionTypeTopicFilter = "TOPIC_FILTER" ) +// DimensionType_Values returns all elements of the DimensionType enum +func DimensionType_Values() []string { + return []string{ + DimensionTypeTopicFilter, + } +} + const ( // DimensionValueOperatorIn is a DimensionValueOperator enum value DimensionValueOperatorIn = "IN" @@ -49689,6 +54088,14 @@ const ( DimensionValueOperatorNotIn = "NOT_IN" ) +// DimensionValueOperator_Values returns all elements of the DimensionValueOperator enum +func DimensionValueOperator_Values() []string { + return []string{ + DimensionValueOperatorIn, + DimensionValueOperatorNotIn, + } +} + const ( // DomainConfigurationStatusEnabled is a DomainConfigurationStatus enum value DomainConfigurationStatusEnabled = "ENABLED" @@ -49697,6 +54104,14 @@ const ( DomainConfigurationStatusDisabled = "DISABLED" ) +// DomainConfigurationStatus_Values returns all elements of the DomainConfigurationStatus enum +func DomainConfigurationStatus_Values() []string { + return []string{ + DomainConfigurationStatusEnabled, + DomainConfigurationStatusDisabled, + } +} + const ( // DomainTypeEndpoint is a DomainType enum value DomainTypeEndpoint = "ENDPOINT" @@ -49708,6 +54123,15 @@ const ( DomainTypeCustomerManaged = "CUSTOMER_MANAGED" ) +// DomainType_Values returns all elements of the DomainType enum +func DomainType_Values() []string { + return []string{ + DomainTypeEndpoint, + DomainTypeAwsManaged, + DomainTypeCustomerManaged, + } +} + const ( // DynamicGroupStatusActive is a DynamicGroupStatus enum value DynamicGroupStatusActive = "ACTIVE" @@ -49719,6 +54143,15 @@ const ( DynamicGroupStatusRebuilding = "REBUILDING" ) +// DynamicGroupStatus_Values returns all elements of the DynamicGroupStatus enum +func DynamicGroupStatus_Values() []string { + return []string{ + DynamicGroupStatusActive, + DynamicGroupStatusBuilding, + DynamicGroupStatusRebuilding, + } +} + const ( // DynamoKeyTypeString is a DynamoKeyType enum value DynamoKeyTypeString = "STRING" @@ -49727,6 +54160,14 @@ const ( DynamoKeyTypeNumber = "NUMBER" ) +// DynamoKeyType_Values returns all elements of the DynamoKeyType enum +func DynamoKeyType_Values() []string { + return []string{ + DynamoKeyTypeString, + DynamoKeyTypeNumber, + } +} + const ( // EventTypeThing is a EventType enum value EventTypeThing = "THING" @@ -49762,6 +54203,23 @@ const ( EventTypeCaCertificate = "CA_CERTIFICATE" ) +// EventType_Values returns all elements of the EventType enum +func EventType_Values() []string { + return []string{ + EventTypeThing, + EventTypeThingGroup, + EventTypeThingType, + EventTypeThingGroupMembership, + EventTypeThingGroupHierarchy, + EventTypeThingTypeAssociation, + EventTypeJob, + EventTypeJobExecution, + EventTypePolicy, + EventTypeCertificate, + EventTypeCaCertificate, + } +} + const ( // FieldTypeNumber is a FieldType enum value FieldTypeNumber = "Number" @@ -49773,6 +54231,15 @@ const ( FieldTypeBoolean = "Boolean" ) +// FieldType_Values returns all elements of the FieldType enum +func FieldType_Values() []string { + return []string{ + FieldTypeNumber, + FieldTypeString, + FieldTypeBoolean, + } +} + const ( // IndexStatusActive is a IndexStatus enum value IndexStatusActive = "ACTIVE" @@ -49784,6 +54251,15 @@ const ( IndexStatusRebuilding = "REBUILDING" ) +// IndexStatus_Values returns all elements of the IndexStatus enum +func IndexStatus_Values() []string { + return []string{ + IndexStatusActive, + IndexStatusBuilding, + IndexStatusRebuilding, + } +} + const ( // JobExecutionFailureTypeFailed is a JobExecutionFailureType enum value JobExecutionFailureTypeFailed = "FAILED" @@ -49798,6 +54274,16 @@ const ( JobExecutionFailureTypeAll = "ALL" ) +// JobExecutionFailureType_Values returns all elements of the JobExecutionFailureType enum +func JobExecutionFailureType_Values() []string { + return []string{ + JobExecutionFailureTypeFailed, + JobExecutionFailureTypeRejected, + JobExecutionFailureTypeTimedOut, + JobExecutionFailureTypeAll, + } +} + const ( // JobExecutionStatusQueued is a JobExecutionStatus enum value JobExecutionStatusQueued = "QUEUED" @@ -49824,6 +54310,20 @@ const ( JobExecutionStatusCanceled = "CANCELED" ) +// JobExecutionStatus_Values returns all elements of the JobExecutionStatus enum +func JobExecutionStatus_Values() []string { + return []string{ + JobExecutionStatusQueued, + JobExecutionStatusInProgress, + JobExecutionStatusSucceeded, + JobExecutionStatusFailed, + JobExecutionStatusTimedOut, + JobExecutionStatusRejected, + JobExecutionStatusRemoved, + JobExecutionStatusCanceled, + } +} + const ( // JobStatusInProgress is a JobStatus enum value JobStatusInProgress = "IN_PROGRESS" @@ -49838,6 +54338,16 @@ const ( JobStatusDeletionInProgress = "DELETION_IN_PROGRESS" ) +// JobStatus_Values returns all elements of the JobStatus enum +func JobStatus_Values() []string { + return []string{ + JobStatusInProgress, + JobStatusCanceled, + JobStatusCompleted, + JobStatusDeletionInProgress, + } +} + const ( // LogLevelDebug is a LogLevel enum value LogLevelDebug = "DEBUG" @@ -49855,6 +54365,17 @@ const ( LogLevelDisabled = "DISABLED" ) +// LogLevel_Values returns all elements of the LogLevel enum +func LogLevel_Values() []string { + return []string{ + LogLevelDebug, + LogLevelInfo, + LogLevelError, + LogLevelWarn, + LogLevelDisabled, + } +} + const ( // LogTargetTypeDefault is a LogTargetType enum value LogTargetTypeDefault = "DEFAULT" @@ -49863,6 +54384,14 @@ const ( LogTargetTypeThingGroup = "THING_GROUP" ) +// LogTargetType_Values returns all elements of the LogTargetType enum +func LogTargetType_Values() []string { + return []string{ + LogTargetTypeDefault, + LogTargetTypeThingGroup, + } +} + const ( // MessageFormatRaw is a MessageFormat enum value MessageFormatRaw = "RAW" @@ -49871,6 +54400,14 @@ const ( MessageFormatJson = "JSON" ) +// MessageFormat_Values returns all elements of the MessageFormat enum +func MessageFormat_Values() []string { + return []string{ + MessageFormatRaw, + MessageFormatJson, + } +} + const ( // MitigationActionTypeUpdateDeviceCertificate is a MitigationActionType enum value MitigationActionTypeUpdateDeviceCertificate = "UPDATE_DEVICE_CERTIFICATE" @@ -49891,6 +54428,18 @@ const ( MitigationActionTypePublishFindingToSns = "PUBLISH_FINDING_TO_SNS" ) +// MitigationActionType_Values returns all elements of the MitigationActionType enum +func MitigationActionType_Values() []string { + return []string{ + MitigationActionTypeUpdateDeviceCertificate, + MitigationActionTypeUpdateCaCertificate, + MitigationActionTypeAddThingsToThingGroup, + MitigationActionTypeReplaceDefaultPolicyVersion, + MitigationActionTypeEnableIotLogging, + MitigationActionTypePublishFindingToSns, + } +} + const ( // OTAUpdateStatusCreatePending is a OTAUpdateStatus enum value OTAUpdateStatusCreatePending = "CREATE_PENDING" @@ -49905,11 +54454,28 @@ const ( OTAUpdateStatusCreateFailed = "CREATE_FAILED" ) +// OTAUpdateStatus_Values returns all elements of the OTAUpdateStatus enum +func OTAUpdateStatus_Values() []string { + return []string{ + OTAUpdateStatusCreatePending, + OTAUpdateStatusCreateInProgress, + OTAUpdateStatusCreateComplete, + OTAUpdateStatusCreateFailed, + } +} + const ( // PolicyTemplateNameBlankPolicy is a PolicyTemplateName enum value PolicyTemplateNameBlankPolicy = "BLANK_POLICY" ) +// PolicyTemplateName_Values returns all elements of the PolicyTemplateName enum +func PolicyTemplateName_Values() []string { + return []string{ + PolicyTemplateNameBlankPolicy, + } +} + const ( // ProtocolMqtt is a Protocol enum value ProtocolMqtt = "MQTT" @@ -49918,6 +54484,14 @@ const ( ProtocolHttp = "HTTP" ) +// Protocol_Values returns all elements of the Protocol enum +func Protocol_Values() []string { + return []string{ + ProtocolMqtt, + ProtocolHttp, + } +} + const ( // ReportTypeErrors is a ReportType enum value ReportTypeErrors = "ERRORS" @@ -49926,6 +54500,14 @@ const ( ReportTypeResults = "RESULTS" ) +// ReportType_Values returns all elements of the ReportType enum +func ReportType_Values() []string { + return []string{ + ReportTypeErrors, + ReportTypeResults, + } +} + const ( // ResourceTypeDeviceCertificate is a ResourceType enum value ResourceTypeDeviceCertificate = "DEVICE_CERTIFICATE" @@ -49952,6 +54534,20 @@ const ( ResourceTypeIamRole = "IAM_ROLE" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeDeviceCertificate, + ResourceTypeCaCertificate, + ResourceTypeIotPolicy, + ResourceTypeCognitoIdentityPool, + ResourceTypeClientId, + ResourceTypeAccountSettings, + ResourceTypeRoleAlias, + ResourceTypeIamRole, + } +} + const ( // ServerCertificateStatusInvalid is a ServerCertificateStatus enum value ServerCertificateStatusInvalid = "INVALID" @@ -49960,6 +54556,14 @@ const ( ServerCertificateStatusValid = "VALID" ) +// ServerCertificateStatus_Values returns all elements of the ServerCertificateStatus enum +func ServerCertificateStatus_Values() []string { + return []string{ + ServerCertificateStatusInvalid, + ServerCertificateStatusValid, + } +} + const ( // ServiceTypeData is a ServiceType enum value ServiceTypeData = "DATA" @@ -49971,6 +54575,15 @@ const ( ServiceTypeJobs = "JOBS" ) +// ServiceType_Values returns all elements of the ServiceType enum +func ServiceType_Values() []string { + return []string{ + ServiceTypeData, + ServiceTypeCredentialProvider, + ServiceTypeJobs, + } +} + const ( // StatusInProgress is a Status enum value StatusInProgress = "InProgress" @@ -49988,6 +54601,17 @@ const ( StatusCancelling = "Cancelling" ) +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusInProgress, + StatusCompleted, + StatusFailed, + StatusCancelled, + StatusCancelling, + } +} + const ( // TargetSelectionContinuous is a TargetSelection enum value TargetSelectionContinuous = "CONTINUOUS" @@ -49996,6 +54620,14 @@ const ( TargetSelectionSnapshot = "SNAPSHOT" ) +// TargetSelection_Values returns all elements of the TargetSelection enum +func TargetSelection_Values() []string { + return []string{ + TargetSelectionContinuous, + TargetSelectionSnapshot, + } +} + const ( // ThingConnectivityIndexingModeOff is a ThingConnectivityIndexingMode enum value ThingConnectivityIndexingModeOff = "OFF" @@ -50004,6 +54636,14 @@ const ( ThingConnectivityIndexingModeStatus = "STATUS" ) +// ThingConnectivityIndexingMode_Values returns all elements of the ThingConnectivityIndexingMode enum +func ThingConnectivityIndexingMode_Values() []string { + return []string{ + ThingConnectivityIndexingModeOff, + ThingConnectivityIndexingModeStatus, + } +} + const ( // ThingGroupIndexingModeOff is a ThingGroupIndexingMode enum value ThingGroupIndexingModeOff = "OFF" @@ -50012,6 +54652,14 @@ const ( ThingGroupIndexingModeOn = "ON" ) +// ThingGroupIndexingMode_Values returns all elements of the ThingGroupIndexingMode enum +func ThingGroupIndexingMode_Values() []string { + return []string{ + ThingGroupIndexingModeOff, + ThingGroupIndexingModeOn, + } +} + const ( // ThingIndexingModeOff is a ThingIndexingMode enum value ThingIndexingModeOff = "OFF" @@ -50023,6 +54671,15 @@ const ( ThingIndexingModeRegistryAndShadow = "REGISTRY_AND_SHADOW" ) +// ThingIndexingMode_Values returns all elements of the ThingIndexingMode enum +func ThingIndexingMode_Values() []string { + return []string{ + ThingIndexingModeOff, + ThingIndexingModeRegistry, + ThingIndexingModeRegistryAndShadow, + } +} + const ( // TopicRuleDestinationStatusEnabled is a TopicRuleDestinationStatus enum value TopicRuleDestinationStatusEnabled = "ENABLED" @@ -50037,6 +54694,16 @@ const ( TopicRuleDestinationStatusError = "ERROR" ) +// TopicRuleDestinationStatus_Values returns all elements of the TopicRuleDestinationStatus enum +func TopicRuleDestinationStatus_Values() []string { + return []string{ + TopicRuleDestinationStatusEnabled, + TopicRuleDestinationStatusInProgress, + TopicRuleDestinationStatusDisabled, + TopicRuleDestinationStatusError, + } +} + const ( // ViolationEventTypeInAlarm is a ViolationEventType enum value ViolationEventTypeInAlarm = "in-alarm" @@ -50047,3 +54714,12 @@ const ( // ViolationEventTypeAlarmInvalidated is a ViolationEventType enum value ViolationEventTypeAlarmInvalidated = "alarm-invalidated" ) + +// ViolationEventType_Values returns all elements of the ViolationEventType enum +func ViolationEventType_Values() []string { + return []string{ + ViolationEventTypeInAlarm, + ViolationEventTypeAlarmCleared, + ViolationEventTypeAlarmInvalidated, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/iotanalytics/api.go b/vendor/github.com/aws/aws-sdk-go/service/iotanalytics/api.go index 02cec6c4758..a0c0e800da6 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iotanalytics/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iotanalytics/api.go @@ -10521,6 +10521,15 @@ const ( ChannelStatusDeleting = "DELETING" ) +// ChannelStatus_Values returns all elements of the ChannelStatus enum +func ChannelStatus_Values() []string { + return []string{ + ChannelStatusCreating, + ChannelStatusActive, + ChannelStatusDeleting, + } +} + const ( // ComputeTypeAcu1 is a ComputeType enum value ComputeTypeAcu1 = "ACU_1" @@ -10529,6 +10538,14 @@ const ( ComputeTypeAcu2 = "ACU_2" ) +// ComputeType_Values returns all elements of the ComputeType enum +func ComputeType_Values() []string { + return []string{ + ComputeTypeAcu1, + ComputeTypeAcu2, + } +} + const ( // DatasetActionTypeQuery is a DatasetActionType enum value DatasetActionTypeQuery = "QUERY" @@ -10537,6 +10554,14 @@ const ( DatasetActionTypeContainer = "CONTAINER" ) +// DatasetActionType_Values returns all elements of the DatasetActionType enum +func DatasetActionType_Values() []string { + return []string{ + DatasetActionTypeQuery, + DatasetActionTypeContainer, + } +} + const ( // DatasetContentStateCreating is a DatasetContentState enum value DatasetContentStateCreating = "CREATING" @@ -10548,6 +10573,15 @@ const ( DatasetContentStateFailed = "FAILED" ) +// DatasetContentState_Values returns all elements of the DatasetContentState enum +func DatasetContentState_Values() []string { + return []string{ + DatasetContentStateCreating, + DatasetContentStateSucceeded, + DatasetContentStateFailed, + } +} + const ( // DatasetStatusCreating is a DatasetStatus enum value DatasetStatusCreating = "CREATING" @@ -10559,6 +10593,15 @@ const ( DatasetStatusDeleting = "DELETING" ) +// DatasetStatus_Values returns all elements of the DatasetStatus enum +func DatasetStatus_Values() []string { + return []string{ + DatasetStatusCreating, + DatasetStatusActive, + DatasetStatusDeleting, + } +} + const ( // DatastoreStatusCreating is a DatastoreStatus enum value DatastoreStatusCreating = "CREATING" @@ -10570,11 +10613,27 @@ const ( DatastoreStatusDeleting = "DELETING" ) +// DatastoreStatus_Values returns all elements of the DatastoreStatus enum +func DatastoreStatus_Values() []string { + return []string{ + DatastoreStatusCreating, + DatastoreStatusActive, + DatastoreStatusDeleting, + } +} + const ( // LoggingLevelError is a LoggingLevel enum value LoggingLevelError = "ERROR" ) +// LoggingLevel_Values returns all elements of the LoggingLevel enum +func LoggingLevel_Values() []string { + return []string{ + LoggingLevelError, + } +} + const ( // ReprocessingStatusRunning is a ReprocessingStatus enum value ReprocessingStatusRunning = "RUNNING" @@ -10588,3 +10647,13 @@ const ( // ReprocessingStatusFailed is a ReprocessingStatus enum value ReprocessingStatusFailed = "FAILED" ) + +// ReprocessingStatus_Values returns all elements of the ReprocessingStatus enum +func ReprocessingStatus_Values() []string { + return []string{ + ReprocessingStatusRunning, + ReprocessingStatusSucceeded, + ReprocessingStatusCancelled, + ReprocessingStatusFailed, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/iotevents/api.go b/vendor/github.com/aws/aws-sdk-go/service/iotevents/api.go index 3b5ecfef2bf..74e06e25308 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iotevents/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iotevents/api.go @@ -6010,6 +6010,19 @@ const ( DetectorModelVersionStatusFailed = "FAILED" ) +// DetectorModelVersionStatus_Values returns all elements of the DetectorModelVersionStatus enum +func DetectorModelVersionStatus_Values() []string { + return []string{ + DetectorModelVersionStatusActive, + DetectorModelVersionStatusActivating, + DetectorModelVersionStatusInactive, + DetectorModelVersionStatusDeprecated, + DetectorModelVersionStatusDraft, + DetectorModelVersionStatusPaused, + DetectorModelVersionStatusFailed, + } +} + const ( // EvaluationMethodBatch is a EvaluationMethod enum value EvaluationMethodBatch = "BATCH" @@ -6018,6 +6031,14 @@ const ( EvaluationMethodSerial = "SERIAL" ) +// EvaluationMethod_Values returns all elements of the EvaluationMethod enum +func EvaluationMethod_Values() []string { + return []string{ + EvaluationMethodBatch, + EvaluationMethodSerial, + } +} + const ( // InputStatusCreating is a InputStatus enum value InputStatusCreating = "CREATING" @@ -6032,6 +6053,16 @@ const ( InputStatusDeleting = "DELETING" ) +// InputStatus_Values returns all elements of the InputStatus enum +func InputStatus_Values() []string { + return []string{ + InputStatusCreating, + InputStatusUpdating, + InputStatusActive, + InputStatusDeleting, + } +} + const ( // LoggingLevelError is a LoggingLevel enum value LoggingLevelError = "ERROR" @@ -6043,6 +6074,15 @@ const ( LoggingLevelDebug = "DEBUG" ) +// LoggingLevel_Values returns all elements of the LoggingLevel enum +func LoggingLevel_Values() []string { + return []string{ + LoggingLevelError, + LoggingLevelInfo, + LoggingLevelDebug, + } +} + const ( // PayloadTypeString is a PayloadType enum value PayloadTypeString = "STRING" @@ -6050,3 +6090,11 @@ const ( // PayloadTypeJson is a PayloadType enum value PayloadTypeJson = "JSON" ) + +// PayloadType_Values returns all elements of the PayloadType enum +func PayloadType_Values() []string { + return []string{ + PayloadTypeString, + PayloadTypeJson, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/kafka/api.go b/vendor/github.com/aws/aws-sdk-go/service/kafka/api.go index 07f1aab901f..bbc5a77e50f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kafka/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kafka/api.go @@ -758,6 +758,103 @@ func (c *Kafka) GetBootstrapBrokersWithContext(ctx aws.Context, input *GetBootst return out, req.Send() } +const opGetCompatibleKafkaVersions = "GetCompatibleKafkaVersions" + +// GetCompatibleKafkaVersionsRequest generates a "aws/request.Request" representing the +// client's request for the GetCompatibleKafkaVersions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetCompatibleKafkaVersions for more information on using the GetCompatibleKafkaVersions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetCompatibleKafkaVersionsRequest method. +// req, resp := client.GetCompatibleKafkaVersionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/kafka-2018-11-14/GetCompatibleKafkaVersions +func (c *Kafka) GetCompatibleKafkaVersionsRequest(input *GetCompatibleKafkaVersionsInput) (req *request.Request, output *GetCompatibleKafkaVersionsOutput) { + op := &request.Operation{ + Name: opGetCompatibleKafkaVersions, + HTTPMethod: "GET", + HTTPPath: "/v1/compatible-kafka-versions", + } + + if input == nil { + input = &GetCompatibleKafkaVersionsInput{} + } + + output = &GetCompatibleKafkaVersionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetCompatibleKafkaVersions API operation for Managed Streaming for Kafka. +// +// Gets the Apache Kafka versions to which you can update the MSK cluster. +// +// Returns awserr.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 Managed Streaming for Kafka's +// API operation GetCompatibleKafkaVersions for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// Returns information about an error. +// +// * UnauthorizedException +// Returns information about an error. +// +// * InternalServerErrorException +// Returns information about an error. +// +// * ForbiddenException +// Returns information about an error. +// +// * NotFoundException +// Returns information about an error. +// +// * ServiceUnavailableException +// Returns information about an error. +// +// * TooManyRequestsException +// Returns information about an error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/kafka-2018-11-14/GetCompatibleKafkaVersions +func (c *Kafka) GetCompatibleKafkaVersions(input *GetCompatibleKafkaVersionsInput) (*GetCompatibleKafkaVersionsOutput, error) { + req, out := c.GetCompatibleKafkaVersionsRequest(input) + return out, req.Send() +} + +// GetCompatibleKafkaVersionsWithContext is the same as GetCompatibleKafkaVersions with the addition of +// the ability to pass a context and additional request options. +// +// See GetCompatibleKafkaVersions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Kafka) GetCompatibleKafkaVersionsWithContext(ctx aws.Context, input *GetCompatibleKafkaVersionsInput, opts ...request.Option) (*GetCompatibleKafkaVersionsOutput, error) { + req, out := c.GetCompatibleKafkaVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opListClusterOperations = "ListClusterOperations" // ListClusterOperationsRequest generates a "aws/request.Request" representing the @@ -1729,6 +1826,103 @@ func (c *Kafka) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsF return out, req.Send() } +const opRebootBroker = "RebootBroker" + +// RebootBrokerRequest generates a "aws/request.Request" representing the +// client's request for the RebootBroker operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See RebootBroker for more information on using the RebootBroker +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the RebootBrokerRequest method. +// req, resp := client.RebootBrokerRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/kafka-2018-11-14/RebootBroker +func (c *Kafka) RebootBrokerRequest(input *RebootBrokerInput) (req *request.Request, output *RebootBrokerOutput) { + op := &request.Operation{ + Name: opRebootBroker, + HTTPMethod: "PUT", + HTTPPath: "/v1/clusters/{clusterArn}/reboot-broker", + } + + if input == nil { + input = &RebootBrokerInput{} + } + + output = &RebootBrokerOutput{} + req = c.newRequest(op, input, output) + return +} + +// RebootBroker API operation for Managed Streaming for Kafka. +// +// Executes a reboot on a broker. +// +// Returns awserr.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 Managed Streaming for Kafka's +// API operation RebootBroker for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// Returns information about an error. +// +// * UnauthorizedException +// Returns information about an error. +// +// * InternalServerErrorException +// Returns information about an error. +// +// * ForbiddenException +// Returns information about an error. +// +// * NotFoundException +// Returns information about an error. +// +// * ServiceUnavailableException +// Returns information about an error. +// +// * TooManyRequestsException +// Returns information about an error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/kafka-2018-11-14/RebootBroker +func (c *Kafka) RebootBroker(input *RebootBrokerInput) (*RebootBrokerOutput, error) { + req, out := c.RebootBrokerRequest(input) + return out, req.Send() +} + +// RebootBrokerWithContext is the same as RebootBroker with the addition of +// the ability to pass a context and additional request options. +// +// See RebootBroker for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Kafka) RebootBrokerWithContext(ctx aws.Context, input *RebootBrokerInput, opts ...request.Option) (*RebootBrokerOutput, error) { + req, out := c.RebootBrokerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opTagResource = "TagResource" // TagResourceRequest generates a "aws/request.Request" representing the @@ -2180,6 +2374,103 @@ func (c *Kafka) UpdateClusterConfigurationWithContext(ctx aws.Context, input *Up return out, req.Send() } +const opUpdateClusterKafkaVersion = "UpdateClusterKafkaVersion" + +// UpdateClusterKafkaVersionRequest generates a "aws/request.Request" representing the +// client's request for the UpdateClusterKafkaVersion operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateClusterKafkaVersion for more information on using the UpdateClusterKafkaVersion +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateClusterKafkaVersionRequest method. +// req, resp := client.UpdateClusterKafkaVersionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/kafka-2018-11-14/UpdateClusterKafkaVersion +func (c *Kafka) UpdateClusterKafkaVersionRequest(input *UpdateClusterKafkaVersionInput) (req *request.Request, output *UpdateClusterKafkaVersionOutput) { + op := &request.Operation{ + Name: opUpdateClusterKafkaVersion, + HTTPMethod: "PUT", + HTTPPath: "/v1/clusters/{clusterArn}/version", + } + + if input == nil { + input = &UpdateClusterKafkaVersionInput{} + } + + output = &UpdateClusterKafkaVersionOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateClusterKafkaVersion API operation for Managed Streaming for Kafka. +// +// Updates the Apache Kafka version for the cluster. +// +// Returns awserr.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 Managed Streaming for Kafka's +// API operation UpdateClusterKafkaVersion for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// Returns information about an error. +// +// * UnauthorizedException +// Returns information about an error. +// +// * InternalServerErrorException +// Returns information about an error. +// +// * ForbiddenException +// Returns information about an error. +// +// * NotFoundException +// Returns information about an error. +// +// * ServiceUnavailableException +// Returns information about an error. +// +// * TooManyRequestsException +// Returns information about an error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/kafka-2018-11-14/UpdateClusterKafkaVersion +func (c *Kafka) UpdateClusterKafkaVersion(input *UpdateClusterKafkaVersionInput) (*UpdateClusterKafkaVersionOutput, error) { + req, out := c.UpdateClusterKafkaVersionRequest(input) + return out, req.Send() +} + +// UpdateClusterKafkaVersionWithContext is the same as UpdateClusterKafkaVersion with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateClusterKafkaVersion for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Kafka) UpdateClusterKafkaVersionWithContext(ctx aws.Context, input *UpdateClusterKafkaVersionInput, opts ...request.Option) (*UpdateClusterKafkaVersionOutput, error) { + req, out := c.UpdateClusterKafkaVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opUpdateMonitoring = "UpdateMonitoring" // UpdateMonitoringRequest generates a "aws/request.Request" representing the @@ -2930,6 +3221,9 @@ type ClusterOperationInfo struct { // State of the cluster operation. OperationState *string `locationName:"operationState" type:"string"` + // Steps completed during the operation. + OperationSteps []*ClusterOperationStep `locationName:"operationSteps" type:"list"` + // Type of the cluster operation. OperationType *string `locationName:"operationType" type:"string"` @@ -2992,6 +3286,12 @@ func (s *ClusterOperationInfo) SetOperationState(v string) *ClusterOperationInfo return s } +// SetOperationSteps sets the OperationSteps field's value. +func (s *ClusterOperationInfo) SetOperationSteps(v []*ClusterOperationStep) *ClusterOperationInfo { + s.OperationSteps = v + return s +} + // SetOperationType sets the OperationType field's value. func (s *ClusterOperationInfo) SetOperationType(v string) *ClusterOperationInfo { s.OperationType = &v @@ -3010,6 +3310,94 @@ func (s *ClusterOperationInfo) SetTargetClusterInfo(v *MutableClusterInfo) *Clus return s } +// Step taken during a cluster operation. +type ClusterOperationStep struct { + _ struct{} `type:"structure"` + + // Information about the step and its status. + StepInfo *ClusterOperationStepInfo `locationName:"stepInfo" type:"structure"` + + // The name of the step. + StepName *string `locationName:"stepName" type:"string"` +} + +// String returns the string representation +func (s ClusterOperationStep) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ClusterOperationStep) GoString() string { + return s.String() +} + +// SetStepInfo sets the StepInfo field's value. +func (s *ClusterOperationStep) SetStepInfo(v *ClusterOperationStepInfo) *ClusterOperationStep { + s.StepInfo = v + return s +} + +// SetStepName sets the StepName field's value. +func (s *ClusterOperationStep) SetStepName(v string) *ClusterOperationStep { + s.StepName = &v + return s +} + +// State information about the operation step. +type ClusterOperationStepInfo struct { + _ struct{} `type:"structure"` + + // The steps current status. + StepStatus *string `locationName:"stepStatus" type:"string"` +} + +// String returns the string representation +func (s ClusterOperationStepInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ClusterOperationStepInfo) GoString() string { + return s.String() +} + +// SetStepStatus sets the StepStatus field's value. +func (s *ClusterOperationStepInfo) SetStepStatus(v string) *ClusterOperationStepInfo { + s.StepStatus = &v + return s +} + +// Contains source Kafka versions and compatible target Kafka versions. +type CompatibleKafkaVersion struct { + _ struct{} `type:"structure"` + + SourceVersion *string `locationName:"sourceVersion" type:"string"` + + TargetVersions []*string `locationName:"targetVersions" type:"list"` +} + +// String returns the string representation +func (s CompatibleKafkaVersion) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CompatibleKafkaVersion) GoString() string { + return s.String() +} + +// SetSourceVersion sets the SourceVersion field's value. +func (s *CompatibleKafkaVersion) SetSourceVersion(v string) *CompatibleKafkaVersion { + s.SourceVersion = &v + return s +} + +// SetTargetVersions sets the TargetVersions field's value. +func (s *CompatibleKafkaVersion) SetTargetVersions(v []*string) *CompatibleKafkaVersion { + s.TargetVersions = v + return s +} + // Represents an MSK Configuration. type Configuration struct { _ struct{} `type:"structure"` @@ -3478,9 +3866,7 @@ type CreateConfigurationInput struct { Description *string `locationName:"description" type:"string"` // The versions of Apache Kafka with which you can use this MSK configuration. - // - // KafkaVersions is a required field - KafkaVersions []*string `locationName:"kafkaVersions" type:"list" required:"true"` + KafkaVersions []*string `locationName:"kafkaVersions" type:"list"` // The name of the configuration. Configuration names are strings that match // the regex "^[0-9A-Za-z-]+$". @@ -3507,9 +3893,6 @@ func (s CreateConfigurationInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *CreateConfigurationInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "CreateConfigurationInput"} - if s.KafkaVersions == nil { - invalidParams.Add(request.NewErrParamRequired("KafkaVersions")) - } if s.Name == nil { invalidParams.Add(request.NewErrParamRequired("Name")) } @@ -4416,6 +4799,52 @@ func (s *GetBootstrapBrokersOutput) SetBootstrapBrokerStringTls(v string) *GetBo return s } +type GetCompatibleKafkaVersionsInput struct { + _ struct{} `type:"structure"` + + ClusterArn *string `location:"querystring" locationName:"clusterArn" type:"string"` +} + +// String returns the string representation +func (s GetCompatibleKafkaVersionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCompatibleKafkaVersionsInput) GoString() string { + return s.String() +} + +// SetClusterArn sets the ClusterArn field's value. +func (s *GetCompatibleKafkaVersionsInput) SetClusterArn(v string) *GetCompatibleKafkaVersionsInput { + s.ClusterArn = &v + return s +} + +// Response body for GetCompatibleKafkaVersions. +type GetCompatibleKafkaVersionsOutput struct { + _ struct{} `type:"structure"` + + // A list of CompatibleKafkaVersion objects. + CompatibleKafkaVersions []*CompatibleKafkaVersion `locationName:"compatibleKafkaVersions" type:"list"` +} + +// String returns the string representation +func (s GetCompatibleKafkaVersionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCompatibleKafkaVersionsOutput) GoString() string { + return s.String() +} + +// SetCompatibleKafkaVersions sets the CompatibleKafkaVersions field's value. +func (s *GetCompatibleKafkaVersionsOutput) SetCompatibleKafkaVersions(v []*CompatibleKafkaVersion) *GetCompatibleKafkaVersionsOutput { + s.CompatibleKafkaVersions = v + return s +} + // Returns information about an error. type InternalServerErrorException struct { _ struct{} `type:"structure"` @@ -5216,6 +5645,8 @@ type MutableClusterInfo struct { // CloudWatch for this cluster. EnhancedMonitoring *string `locationName:"enhancedMonitoring" type:"string" enum:"EnhancedMonitoring"` + KafkaVersion *string `locationName:"kafkaVersion" type:"string"` + // LoggingInfo details. LoggingInfo *LoggingInfo `locationName:"loggingInfo" type:"structure"` @@ -5254,6 +5685,12 @@ func (s *MutableClusterInfo) SetEnhancedMonitoring(v string) *MutableClusterInfo return s } +// SetKafkaVersion sets the KafkaVersion field's value. +func (s *MutableClusterInfo) SetKafkaVersion(v string) *MutableClusterInfo { + s.KafkaVersion = &v + return s +} + // SetLoggingInfo sets the LoggingInfo field's value. func (s *MutableClusterInfo) SetLoggingInfo(v *LoggingInfo) *MutableClusterInfo { s.LoggingInfo = v @@ -5620,6 +6057,93 @@ func (s *PrometheusInfo) SetNodeExporter(v *NodeExporterInfo) *PrometheusInfo { return s } +// Request body for RebootBrokerNode action. +type RebootBrokerInput struct { + _ struct{} `type:"structure"` + + // The list of broker ids to be rebooted. + // + // BrokerIds is a required field + BrokerIds []*string `locationName:"brokerIds" type:"list" required:"true"` + + // ClusterArn is a required field + ClusterArn *string `location:"uri" locationName:"clusterArn" type:"string" required:"true"` +} + +// String returns the string representation +func (s RebootBrokerInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RebootBrokerInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RebootBrokerInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RebootBrokerInput"} + if s.BrokerIds == nil { + invalidParams.Add(request.NewErrParamRequired("BrokerIds")) + } + if s.ClusterArn == nil { + invalidParams.Add(request.NewErrParamRequired("ClusterArn")) + } + if s.ClusterArn != nil && len(*s.ClusterArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClusterArn", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBrokerIds sets the BrokerIds field's value. +func (s *RebootBrokerInput) SetBrokerIds(v []*string) *RebootBrokerInput { + s.BrokerIds = v + return s +} + +// SetClusterArn sets the ClusterArn field's value. +func (s *RebootBrokerInput) SetClusterArn(v string) *RebootBrokerInput { + s.ClusterArn = &v + return s +} + +// Response body for RebootBrokers action. +type RebootBrokerOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the cluster. + ClusterArn *string `locationName:"clusterArn" type:"string"` + + // The Amazon Resource Name (ARN) of the cluster operation. + ClusterOperationArn *string `locationName:"clusterOperationArn" type:"string"` +} + +// String returns the string representation +func (s RebootBrokerOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RebootBrokerOutput) GoString() string { + return s.String() +} + +// SetClusterArn sets the ClusterArn field's value. +func (s *RebootBrokerOutput) SetClusterArn(v string) *RebootBrokerOutput { + s.ClusterArn = &v + return s +} + +// SetClusterOperationArn sets the ClusterOperationArn field's value. +func (s *RebootBrokerOutput) SetClusterOperationArn(v string) *RebootBrokerOutput { + s.ClusterOperationArn = &v + return s +} + // The details of the Amazon S3 destination for broker logs. type S3 struct { _ struct{} `type:"structure"` @@ -6376,6 +6900,121 @@ func (s *UpdateClusterConfigurationOutput) SetClusterOperationArn(v string) *Upd return s } +// Request body for UpdateClusterKafkaVersion. +type UpdateClusterKafkaVersionInput struct { + _ struct{} `type:"structure"` + + // ClusterArn is a required field + ClusterArn *string `location:"uri" locationName:"clusterArn" type:"string" required:"true"` + + // Specifies the configuration to use for the brokers. + ConfigurationInfo *ConfigurationInfo `locationName:"configurationInfo" type:"structure"` + + // Current cluster version. + // + // CurrentVersion is a required field + CurrentVersion *string `locationName:"currentVersion" type:"string" required:"true"` + + // Target Kafka version. + // + // TargetKafkaVersion is a required field + TargetKafkaVersion *string `locationName:"targetKafkaVersion" type:"string" required:"true"` +} + +// String returns the string representation +func (s UpdateClusterKafkaVersionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateClusterKafkaVersionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateClusterKafkaVersionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateClusterKafkaVersionInput"} + if s.ClusterArn == nil { + invalidParams.Add(request.NewErrParamRequired("ClusterArn")) + } + if s.ClusterArn != nil && len(*s.ClusterArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClusterArn", 1)) + } + if s.CurrentVersion == nil { + invalidParams.Add(request.NewErrParamRequired("CurrentVersion")) + } + if s.TargetKafkaVersion == nil { + invalidParams.Add(request.NewErrParamRequired("TargetKafkaVersion")) + } + if s.ConfigurationInfo != nil { + if err := s.ConfigurationInfo.Validate(); err != nil { + invalidParams.AddNested("ConfigurationInfo", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClusterArn sets the ClusterArn field's value. +func (s *UpdateClusterKafkaVersionInput) SetClusterArn(v string) *UpdateClusterKafkaVersionInput { + s.ClusterArn = &v + return s +} + +// SetConfigurationInfo sets the ConfigurationInfo field's value. +func (s *UpdateClusterKafkaVersionInput) SetConfigurationInfo(v *ConfigurationInfo) *UpdateClusterKafkaVersionInput { + s.ConfigurationInfo = v + return s +} + +// SetCurrentVersion sets the CurrentVersion field's value. +func (s *UpdateClusterKafkaVersionInput) SetCurrentVersion(v string) *UpdateClusterKafkaVersionInput { + s.CurrentVersion = &v + return s +} + +// SetTargetKafkaVersion sets the TargetKafkaVersion field's value. +func (s *UpdateClusterKafkaVersionInput) SetTargetKafkaVersion(v string) *UpdateClusterKafkaVersionInput { + s.TargetKafkaVersion = &v + return s +} + +// Response body for UpdateClusterKafkaVersion. +type UpdateClusterKafkaVersionOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the cluster. + ClusterArn *string `locationName:"clusterArn" type:"string"` + + // The Amazon Resource Name (ARN) of the cluster operation. + ClusterOperationArn *string `locationName:"clusterOperationArn" type:"string"` +} + +// String returns the string representation +func (s UpdateClusterKafkaVersionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateClusterKafkaVersionOutput) GoString() string { + return s.String() +} + +// SetClusterArn sets the ClusterArn field's value. +func (s *UpdateClusterKafkaVersionOutput) SetClusterArn(v string) *UpdateClusterKafkaVersionOutput { + s.ClusterArn = &v + return s +} + +// SetClusterOperationArn sets the ClusterOperationArn field's value. +func (s *UpdateClusterKafkaVersionOutput) SetClusterOperationArn(v string) *UpdateClusterKafkaVersionOutput { + s.ClusterOperationArn = &v + return s +} + // Request body for UpdateMonitoring. type UpdateMonitoringInput struct { _ struct{} `type:"structure"` @@ -6571,6 +7210,13 @@ const ( BrokerAZDistributionDefault = "DEFAULT" ) +// BrokerAZDistribution_Values returns all elements of the BrokerAZDistribution enum +func BrokerAZDistribution_Values() []string { + return []string{ + BrokerAZDistributionDefault, + } +} + // Client-broker encryption in transit setting. const ( // ClientBrokerTls is a ClientBroker enum value @@ -6583,6 +7229,15 @@ const ( ClientBrokerPlaintext = "PLAINTEXT" ) +// ClientBroker_Values returns all elements of the ClientBroker enum +func ClientBroker_Values() []string { + return []string{ + ClientBrokerTls, + ClientBrokerTlsPlaintext, + ClientBrokerPlaintext, + } +} + // The state of a Kafka cluster. const ( // ClusterStateActive is a ClusterState enum value @@ -6601,6 +7256,17 @@ const ( ClusterStateFailed = "FAILED" ) +// ClusterState_Values returns all elements of the ClusterState enum +func ClusterState_Values() []string { + return []string{ + ClusterStateActive, + ClusterStateCreating, + ClusterStateUpdating, + ClusterStateDeleting, + ClusterStateFailed, + } +} + // Specifies which metrics are gathered for the MSK cluster. This property has // three possible values: DEFAULT, PER_BROKER, and PER_TOPIC_PER_BROKER. For // a list of the metrics associated with each of these three levels of monitoring, @@ -6616,6 +7282,15 @@ const ( EnhancedMonitoringPerTopicPerBroker = "PER_TOPIC_PER_BROKER" ) +// EnhancedMonitoring_Values returns all elements of the EnhancedMonitoring enum +func EnhancedMonitoring_Values() []string { + return []string{ + EnhancedMonitoringDefault, + EnhancedMonitoringPerBroker, + EnhancedMonitoringPerTopicPerBroker, + } +} + // The status of a Kafka version. const ( // KafkaVersionStatusActive is a KafkaVersionStatus enum value @@ -6625,8 +7300,23 @@ const ( KafkaVersionStatusDeprecated = "DEPRECATED" ) +// KafkaVersionStatus_Values returns all elements of the KafkaVersionStatus enum +func KafkaVersionStatus_Values() []string { + return []string{ + KafkaVersionStatusActive, + KafkaVersionStatusDeprecated, + } +} + // The broker or Zookeeper node. const ( // NodeTypeBroker is a NodeType enum value NodeTypeBroker = "BROKER" ) + +// NodeType_Values returns all elements of the NodeType enum +func NodeType_Values() []string { + return []string{ + NodeTypeBroker, + } +} 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 9ebd449de56..c954dd11160 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 @@ -3160,7 +3160,7 @@ func (c *Kinesis) SubscribeToShardRequest(input *SubscribeToShardInput) (req *re output = &SubscribeToShardOutput{} req = c.newRequest(op, input, output) - es := newSubscribeToShardEventStream() + es := NewSubscribeToShardEventStream() req.Handlers.Unmarshal.PushBack(es.setStreamCloser) output.EventStream = es @@ -3233,7 +3233,13 @@ func (c *Kinesis) SubscribeToShardWithContext(ctx aws.Context, input *SubscribeT return out, req.Send() } +var _ awserr.Error + // SubscribeToShardEventStream provides the event stream handling for the SubscribeToShard. +// +// For testing and mocking the event stream this type should be initialized via +// the NewSubscribeToShardEventStream constructor function. Using the functional options +// to pass in nested mock behavior. type SubscribeToShardEventStream struct { // Reader is the EventStream reader for the SubscribeToShardEventStream @@ -3257,11 +3263,31 @@ type SubscribeToShardEventStream struct { err *eventstreamapi.OnceError } -func newSubscribeToShardEventStream() *SubscribeToShardEventStream { - return &SubscribeToShardEventStream{ +// NewSubscribeToShardEventStream initializes an SubscribeToShardEventStream. +// This function should only be used for testing and mocking the SubscribeToShardEventStream +// stream within your application. +// +// The Reader member must be set before reading events from the stream. +// +// The StreamCloser member should be set to the underlying io.Closer, +// (e.g. http.Response.Body), that will be closed when the stream Close method +// is called. +// +// es := NewSubscribeToShardEventStream(func(o *SubscribeToShardEventStream{ +// es.Reader = myMockStreamReader +// es.StreamCloser = myMockStreamCloser +// }) +func NewSubscribeToShardEventStream(opts ...func(*SubscribeToShardEventStream)) *SubscribeToShardEventStream { + es := &SubscribeToShardEventStream{ done: make(chan struct{}), err: eventstreamapi.NewOnceError(), } + + for _, fn := range opts { + fn(es) + } + + return es } func (es *SubscribeToShardEventStream) setStreamCloser(r *request.Request) { @@ -3316,6 +3342,7 @@ func (e eventTypeForSubscribeToShardEventStreamOutputEvent) UnmarshalerForEventN // These events are: // // * SubscribeToShardEvent +// * SubscribeToShardEventStreamUnknownEvent func (es *SubscribeToShardEventStream) Events() <-chan SubscribeToShardEventStreamEvent { return es.Reader.Events() } @@ -5108,6 +5135,8 @@ func (s *InternalFailureException) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *InternalFailureException) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType)) var buf bytes.Buffer @@ -5251,6 +5280,8 @@ func (s *KMSAccessDeniedException) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *KMSAccessDeniedException) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType)) var buf bytes.Buffer @@ -5336,6 +5367,8 @@ func (s *KMSDisabledException) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *KMSDisabledException) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType)) var buf bytes.Buffer @@ -5423,6 +5456,8 @@ func (s *KMSInvalidStateException) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *KMSInvalidStateException) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType)) var buf bytes.Buffer @@ -5508,6 +5543,8 @@ func (s *KMSNotFoundException) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *KMSNotFoundException) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType)) var buf bytes.Buffer @@ -5592,6 +5629,8 @@ func (s *KMSOptInRequired) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *KMSOptInRequired) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType)) var buf bytes.Buffer @@ -5678,6 +5717,8 @@ func (s *KMSThrottlingException) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *KMSThrottlingException) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType)) var buf bytes.Buffer @@ -7141,6 +7182,8 @@ func (s *ResourceInUseException) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *ResourceInUseException) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType)) var buf bytes.Buffer @@ -7226,6 +7269,8 @@ func (s *ResourceNotFoundException) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *ResourceNotFoundException) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.ExceptionMessageType)) var buf bytes.Buffer @@ -8095,6 +8140,8 @@ func (s *SubscribeToShardEvent) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *SubscribeToShardEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) var buf bytes.Buffer @@ -8125,6 +8172,7 @@ type SubscribeToShardEventStreamEvent interface { // These events are: // // * SubscribeToShardEvent +// * SubscribeToShardEventStreamUnknownEvent type SubscribeToShardEventStreamReader interface { // Returns a channel of events as they are read from the event stream. Events() <-chan SubscribeToShardEventStreamEvent @@ -8199,6 +8247,9 @@ func (r *readSubscribeToShardEventStream) readEventStream() { return default: } + if _, ok := err.(*eventstreamapi.UnknownMessageTypeError); ok { + continue + } r.err.SetError(err) return } @@ -8238,14 +8289,39 @@ func (u unmarshalerForSubscribeToShardEventStreamEvent) UnmarshalerForEventName( case "ResourceNotFoundException": return newErrorResourceNotFoundException(u.metadata).(eventstreamapi.Unmarshaler), nil default: - return nil, awserr.New( - request.ErrCodeSerialization, - fmt.Sprintf("unknown event type name, %s, for SubscribeToShardEventStream", eventType), - nil, - ) + return &SubscribeToShardEventStreamUnknownEvent{Type: eventType}, nil } } +// SubscribeToShardEventStreamUnknownEvent provides a failsafe event for the +// SubscribeToShardEventStream group of events when an unknown event is received. +type SubscribeToShardEventStreamUnknownEvent struct { + Type string + Message eventstream.Message +} + +// The SubscribeToShardEventStreamUnknownEvent is and event in the SubscribeToShardEventStream +// group of events. +func (s *SubscribeToShardEventStreamUnknownEvent) eventSubscribeToShardEventStream() {} + +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. +func (e *SubscribeToShardEventStreamUnknownEvent) MarshalEvent(pm protocol.PayloadMarshaler) ( + msg eventstream.Message, err error, +) { + return e.Message.Clone(), nil +} + +// UnmarshalEvent unmarshals the EventStream Message into the SubscribeToShardEventStreamData value. +// This method is only used internally within the SDK's EventStream handling. +func (e *SubscribeToShardEventStreamUnknownEvent) UnmarshalEvent( + payloadUnmarshaler protocol.PayloadUnmarshaler, + msg eventstream.Message, +) error { + e.Message = msg.Clone() + return nil +} + type SubscribeToShardInput struct { _ struct{} `type:"structure"` @@ -8368,6 +8444,8 @@ func (s *SubscribeToShardOutput) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *SubscribeToShardOutput) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) var buf bytes.Buffer @@ -8540,6 +8618,15 @@ const ( ConsumerStatusActive = "ACTIVE" ) +// ConsumerStatus_Values returns all elements of the ConsumerStatus enum +func ConsumerStatus_Values() []string { + return []string{ + ConsumerStatusCreating, + ConsumerStatusDeleting, + ConsumerStatusActive, + } +} + const ( // EncryptionTypeNone is a EncryptionType enum value EncryptionTypeNone = "NONE" @@ -8548,6 +8635,14 @@ const ( EncryptionTypeKms = "KMS" ) +// EncryptionType_Values returns all elements of the EncryptionType enum +func EncryptionType_Values() []string { + return []string{ + EncryptionTypeNone, + EncryptionTypeKms, + } +} + const ( // MetricsNameIncomingBytes is a MetricsName enum value MetricsNameIncomingBytes = "IncomingBytes" @@ -8574,11 +8669,32 @@ const ( MetricsNameAll = "ALL" ) +// MetricsName_Values returns all elements of the MetricsName enum +func MetricsName_Values() []string { + return []string{ + MetricsNameIncomingBytes, + MetricsNameIncomingRecords, + MetricsNameOutgoingBytes, + MetricsNameOutgoingRecords, + MetricsNameWriteProvisionedThroughputExceeded, + MetricsNameReadProvisionedThroughputExceeded, + MetricsNameIteratorAgeMilliseconds, + MetricsNameAll, + } +} + const ( // ScalingTypeUniformScaling is a ScalingType enum value ScalingTypeUniformScaling = "UNIFORM_SCALING" ) +// ScalingType_Values returns all elements of the ScalingType enum +func ScalingType_Values() []string { + return []string{ + ScalingTypeUniformScaling, + } +} + const ( // ShardIteratorTypeAtSequenceNumber is a ShardIteratorType enum value ShardIteratorTypeAtSequenceNumber = "AT_SEQUENCE_NUMBER" @@ -8596,6 +8712,17 @@ const ( ShardIteratorTypeAtTimestamp = "AT_TIMESTAMP" ) +// ShardIteratorType_Values returns all elements of the ShardIteratorType enum +func ShardIteratorType_Values() []string { + return []string{ + ShardIteratorTypeAtSequenceNumber, + ShardIteratorTypeAfterSequenceNumber, + ShardIteratorTypeTrimHorizon, + ShardIteratorTypeLatest, + ShardIteratorTypeAtTimestamp, + } +} + const ( // StreamStatusCreating is a StreamStatus enum value StreamStatusCreating = "CREATING" @@ -8609,3 +8736,13 @@ const ( // StreamStatusUpdating is a StreamStatus enum value StreamStatusUpdating = "UPDATING" ) + +// StreamStatus_Values returns all elements of the StreamStatus enum +func StreamStatus_Values() []string { + return []string{ + StreamStatusCreating, + StreamStatusDeleting, + StreamStatusActive, + StreamStatusUpdating, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/kinesisanalytics/api.go b/vendor/github.com/aws/aws-sdk-go/service/kinesisanalytics/api.go index 7e877a1927c..f527facda44 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kinesisanalytics/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kinesisanalytics/api.go @@ -8195,6 +8195,18 @@ const ( ApplicationStatusUpdating = "UPDATING" ) +// ApplicationStatus_Values returns all elements of the ApplicationStatus enum +func ApplicationStatus_Values() []string { + return []string{ + ApplicationStatusDeleting, + ApplicationStatusStarting, + ApplicationStatusStopping, + ApplicationStatusReady, + ApplicationStatusRunning, + ApplicationStatusUpdating, + } +} + const ( // InputStartingPositionNow is a InputStartingPosition enum value InputStartingPositionNow = "NOW" @@ -8206,6 +8218,15 @@ const ( InputStartingPositionLastStoppedPoint = "LAST_STOPPED_POINT" ) +// InputStartingPosition_Values returns all elements of the InputStartingPosition enum +func InputStartingPosition_Values() []string { + return []string{ + InputStartingPositionNow, + InputStartingPositionTrimHorizon, + InputStartingPositionLastStoppedPoint, + } +} + const ( // RecordFormatTypeJson is a RecordFormatType enum value RecordFormatTypeJson = "JSON" @@ -8213,3 +8234,11 @@ const ( // RecordFormatTypeCsv is a RecordFormatType enum value RecordFormatTypeCsv = "CSV" ) + +// RecordFormatType_Values returns all elements of the RecordFormatType enum +func RecordFormatType_Values() []string { + return []string{ + RecordFormatTypeJson, + RecordFormatTypeCsv, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/kinesisanalyticsv2/api.go b/vendor/github.com/aws/aws-sdk-go/service/kinesisanalyticsv2/api.go index 18315c28b01..bba8826ab65 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kinesisanalyticsv2/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kinesisanalyticsv2/api.go @@ -11739,6 +11739,15 @@ const ( ApplicationRestoreTypeRestoreFromCustomSnapshot = "RESTORE_FROM_CUSTOM_SNAPSHOT" ) +// ApplicationRestoreType_Values returns all elements of the ApplicationRestoreType enum +func ApplicationRestoreType_Values() []string { + return []string{ + ApplicationRestoreTypeSkipRestoreFromSnapshot, + ApplicationRestoreTypeRestoreFromLatestSnapshot, + ApplicationRestoreTypeRestoreFromCustomSnapshot, + } +} + const ( // ApplicationStatusDeleting is a ApplicationStatus enum value ApplicationStatusDeleting = "DELETING" @@ -11759,6 +11768,18 @@ const ( ApplicationStatusUpdating = "UPDATING" ) +// ApplicationStatus_Values returns all elements of the ApplicationStatus enum +func ApplicationStatus_Values() []string { + return []string{ + ApplicationStatusDeleting, + ApplicationStatusStarting, + ApplicationStatusStopping, + ApplicationStatusReady, + ApplicationStatusRunning, + ApplicationStatusUpdating, + } +} + const ( // CodeContentTypePlaintext is a CodeContentType enum value CodeContentTypePlaintext = "PLAINTEXT" @@ -11767,6 +11788,14 @@ const ( CodeContentTypeZipfile = "ZIPFILE" ) +// CodeContentType_Values returns all elements of the CodeContentType enum +func CodeContentType_Values() []string { + return []string{ + CodeContentTypePlaintext, + CodeContentTypeZipfile, + } +} + const ( // ConfigurationTypeDefault is a ConfigurationType enum value ConfigurationTypeDefault = "DEFAULT" @@ -11775,6 +11804,14 @@ const ( ConfigurationTypeCustom = "CUSTOM" ) +// ConfigurationType_Values returns all elements of the ConfigurationType enum +func ConfigurationType_Values() []string { + return []string{ + ConfigurationTypeDefault, + ConfigurationTypeCustom, + } +} + const ( // InputStartingPositionNow is a InputStartingPosition enum value InputStartingPositionNow = "NOW" @@ -11786,6 +11823,15 @@ const ( InputStartingPositionLastStoppedPoint = "LAST_STOPPED_POINT" ) +// InputStartingPosition_Values returns all elements of the InputStartingPosition enum +func InputStartingPosition_Values() []string { + return []string{ + InputStartingPositionNow, + InputStartingPositionTrimHorizon, + InputStartingPositionLastStoppedPoint, + } +} + const ( // LogLevelInfo is a LogLevel enum value LogLevelInfo = "INFO" @@ -11800,6 +11846,16 @@ const ( LogLevelDebug = "DEBUG" ) +// LogLevel_Values returns all elements of the LogLevel enum +func LogLevel_Values() []string { + return []string{ + LogLevelInfo, + LogLevelWarn, + LogLevelError, + LogLevelDebug, + } +} + const ( // MetricsLevelApplication is a MetricsLevel enum value MetricsLevelApplication = "APPLICATION" @@ -11814,6 +11870,16 @@ const ( MetricsLevelParallelism = "PARALLELISM" ) +// MetricsLevel_Values returns all elements of the MetricsLevel enum +func MetricsLevel_Values() []string { + return []string{ + MetricsLevelApplication, + MetricsLevelTask, + MetricsLevelOperator, + MetricsLevelParallelism, + } +} + const ( // RecordFormatTypeJson is a RecordFormatType enum value RecordFormatTypeJson = "JSON" @@ -11822,6 +11888,14 @@ const ( RecordFormatTypeCsv = "CSV" ) +// RecordFormatType_Values returns all elements of the RecordFormatType enum +func RecordFormatType_Values() []string { + return []string{ + RecordFormatTypeJson, + RecordFormatTypeCsv, + } +} + const ( // RuntimeEnvironmentSql10 is a RuntimeEnvironment enum value RuntimeEnvironmentSql10 = "SQL-1_0" @@ -11833,6 +11907,15 @@ const ( RuntimeEnvironmentFlink18 = "FLINK-1_8" ) +// RuntimeEnvironment_Values returns all elements of the RuntimeEnvironment enum +func RuntimeEnvironment_Values() []string { + return []string{ + RuntimeEnvironmentSql10, + RuntimeEnvironmentFlink16, + RuntimeEnvironmentFlink18, + } +} + const ( // SnapshotStatusCreating is a SnapshotStatus enum value SnapshotStatusCreating = "CREATING" @@ -11846,3 +11929,13 @@ const ( // SnapshotStatusFailed is a SnapshotStatus enum value SnapshotStatusFailed = "FAILED" ) + +// SnapshotStatus_Values returns all elements of the SnapshotStatus enum +func SnapshotStatus_Values() []string { + return []string{ + SnapshotStatusCreating, + SnapshotStatusReady, + SnapshotStatusDeleting, + SnapshotStatusFailed, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/kinesisvideo/api.go b/vendor/github.com/aws/aws-sdk-go/service/kinesisvideo/api.go index 85c26e01502..facd06f1031 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kinesisvideo/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kinesisvideo/api.go @@ -4941,6 +4941,19 @@ const ( APINameGetClip = "GET_CLIP" ) +// APIName_Values returns all elements of the APIName enum +func APIName_Values() []string { + return []string{ + APINamePutMedia, + APINameGetMedia, + APINameListFragments, + APINameGetMediaForFragmentList, + APINameGetHlsStreamingSessionUrl, + APINameGetDashStreamingSessionUrl, + APINameGetClip, + } +} + const ( // ChannelProtocolWss is a ChannelProtocol enum value ChannelProtocolWss = "WSS" @@ -4949,6 +4962,14 @@ const ( ChannelProtocolHttps = "HTTPS" ) +// ChannelProtocol_Values returns all elements of the ChannelProtocol enum +func ChannelProtocol_Values() []string { + return []string{ + ChannelProtocolWss, + ChannelProtocolHttps, + } +} + const ( // ChannelRoleMaster is a ChannelRole enum value ChannelRoleMaster = "MASTER" @@ -4957,16 +4978,38 @@ const ( ChannelRoleViewer = "VIEWER" ) +// ChannelRole_Values returns all elements of the ChannelRole enum +func ChannelRole_Values() []string { + return []string{ + ChannelRoleMaster, + ChannelRoleViewer, + } +} + const ( // ChannelTypeSingleMaster is a ChannelType enum value ChannelTypeSingleMaster = "SINGLE_MASTER" ) +// ChannelType_Values returns all elements of the ChannelType enum +func ChannelType_Values() []string { + return []string{ + ChannelTypeSingleMaster, + } +} + const ( // ComparisonOperatorBeginsWith is a ComparisonOperator enum value ComparisonOperatorBeginsWith = "BEGINS_WITH" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorBeginsWith, + } +} + const ( // StatusCreating is a Status enum value StatusCreating = "CREATING" @@ -4981,6 +5024,16 @@ const ( StatusDeleting = "DELETING" ) +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusCreating, + StatusActive, + StatusUpdating, + StatusDeleting, + } +} + const ( // UpdateDataRetentionOperationIncreaseDataRetention is a UpdateDataRetentionOperation enum value UpdateDataRetentionOperationIncreaseDataRetention = "INCREASE_DATA_RETENTION" @@ -4988,3 +5041,11 @@ const ( // UpdateDataRetentionOperationDecreaseDataRetention is a UpdateDataRetentionOperation enum value UpdateDataRetentionOperationDecreaseDataRetention = "DECREASE_DATA_RETENTION" ) + +// UpdateDataRetentionOperation_Values returns all elements of the UpdateDataRetentionOperation enum +func UpdateDataRetentionOperation_Values() []string { + return []string{ + UpdateDataRetentionOperationIncreaseDataRetention, + UpdateDataRetentionOperationDecreaseDataRetention, + } +} 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 efbc44ebcbf..8e2aae8e5d6 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 @@ -350,9 +350,9 @@ func (c *KMS) CreateAliasRequest(input *CreateAliasInput) (req *request.Request, // CreateAlias API operation for AWS Key Management Service. // // Creates a display name for a customer managed customer master key (CMK). -// You can use an alias to identify a CMK in cryptographic operations, such -// as Encrypt and GenerateDataKey. You can change the CMK associated with the -// alias at any time. +// You can use an alias to identify a CMK in cryptographic operations (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations), +// such as Encrypt and GenerateDataKey. You can change the CMK associated with +// the alias at any time. // // Aliases are easier to remember than key IDs. They can also help to simplify // your applications. For example, if you use an alias in your code, you can @@ -399,11 +399,12 @@ func (c *KMS) CreateAliasRequest(input *CreateAliasInput) (req *request.Request, // a new alias with the desired name. // // * You can use an alias name or alias ARN to identify a CMK in AWS KMS -// cryptographic operations and in the DescribeKey operation. However, you -// cannot use alias names or alias ARNs in API operations that manage CMKs, -// such as DisableKey or GetKeyPolicy. For information about the valid CMK -// identifiers for each AWS KMS API operation, see the descriptions of the -// KeyId parameter in the API operation documentation. +// cryptographic operations (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations) +// and in the DescribeKey operation. However, you cannot use alias names +// or alias ARNs in API operations that manage CMKs, such as DisableKey or +// GetKeyPolicy. For information about the valid CMK identifiers for each +// AWS KMS API operation, see the descriptions of the KeyId parameter in +// the API operation documentation. // // Because an alias is not a property of a CMK, you can delete and change the // aliases of a CMK without affecting the CMK. Also, aliases do not appear in @@ -693,8 +694,8 @@ func (c *KMS) CreateGrantRequest(input *CreateGrantInput) (req *request.Request, // principal to use the CMK when the conditions specified in the grant are met. // When setting permissions, grants are an alternative to key policies. // -// To create a grant that allows a cryptographic operation only when the request -// includes a particular encryption context (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#encrypt_context), +// To create a grant that allows a cryptographic operation (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations) +// only when the request includes a particular encryption context (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#encrypt_context), // use the Constraints parameter. For details, see GrantConstraints. // // You can create grants on symmetric and asymmetric CMKs. However, if the grant @@ -1357,12 +1358,12 @@ func (c *KMS) DeleteCustomKeyStoreRequest(input *DeleteCustomKeyStoreInput) (req // The custom key store that you delete cannot contain any AWS KMS customer // master keys (CMKs) (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#master_keys). // Before deleting the key store, verify that you will never need to use any -// of the CMKs in the key store for any cryptographic operations. Then, use -// ScheduleKeyDeletion to delete the AWS KMS customer master keys (CMKs) from -// the key store. When the scheduled waiting period expires, the ScheduleKeyDeletion -// operation deletes the CMKs. Then it makes a best effort to delete the key -// material from the associated cluster. However, you might need to manually -// delete the orphaned key material (https://docs.aws.amazon.com/kms/latest/developerguide/fix-keystore.html#fix-keystore-orphaned-key) +// of the CMKs in the key store for any cryptographic operations (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations). +// Then, use ScheduleKeyDeletion to delete the AWS KMS customer master keys +// (CMKs) from the key store. When the scheduled waiting period expires, the +// ScheduleKeyDeletion operation deletes the CMKs. Then it makes a best effort +// to delete the key material from the associated cluster. However, you might +// need to manually delete the orphaned key material (https://docs.aws.amazon.com/kms/latest/developerguide/fix-keystore.html#fix-keystore-orphaned-key) // from the cluster and its backups. // // After all CMKs are deleted from AWS KMS, use DisconnectCustomKeyStore to @@ -1844,8 +1845,8 @@ func (c *KMS) DisableKeyRequest(input *DisableKeyInput) (req *request.Request, o // DisableKey API operation for AWS Key Management Service. // // Sets the state of a customer master key (CMK) to disabled, thereby preventing -// its use for cryptographic operations. You cannot perform this operation on -// a CMK in a different AWS account. +// its use for cryptographic operations (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations). +// You cannot perform this operation on a CMK in a different AWS account. // // For more information about how key state affects the use of a CMK, see How // Key State Affects the Use of a Customer Master Key (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) @@ -2079,8 +2080,9 @@ func (c *KMS) DisconnectCustomKeyStoreRequest(input *DisconnectCustomKeyStoreInp // // While a custom key store is disconnected, all attempts to create customer // master keys (CMKs) in the custom key store or to use existing CMKs in cryptographic -// operations will fail. This action can prevent users from storing and accessing -// sensitive data. +// operations (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations) +// will fail. This action can prevent users from storing and accessing sensitive +// data. // // To find the connection state of a custom key store, use the DescribeCustomKeyStores // operation. To reconnect a custom key store, use the ConnectCustomKeyStore @@ -2195,8 +2197,8 @@ func (c *KMS) EnableKeyRequest(input *EnableKeyInput) (req *request.Request, out // EnableKey API operation for AWS Key Management Service. // // Sets the key state of a customer master key (CMK) to enabled. This allows -// you to use the CMK for cryptographic operations. You cannot perform this -// operation on a CMK in a different AWS account. +// you to use the CMK for cryptographic operations (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations). +// You cannot perform this operation on a CMK in a different AWS account. // // The CMK that you use for this operation must be in a compatible key state. // For details, see How Key State Affects Use of a Customer Master Key (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) @@ -2429,11 +2431,12 @@ func (c *KMS) EncryptRequest(input *EncryptInput) (req *request.Request, output // identifier or database password, or other sensitive information. // // * You can use the Encrypt operation to move encrypted data from one AWS -// region to another. In the first region, generate a data key and use the -// plaintext key to encrypt the data. Then, in the new region, call the Encrypt -// method on same plaintext data key. Now, you can safely move the encrypted -// data and encrypted data key to the new region, and decrypt in the new -// region when necessary. +// Region to another. For example, in Region A, generate a data key and use +// the plaintext key to encrypt your data. Then, in Region A, use the Encrypt +// operation to encrypt the plaintext data key under a CMK in Region B. Now, +// you can move the encrypted data and the encrypted data key to Region B. +// When necessary, you can decrypt the encrypted data key and the encrypted +// data entirely within in Region B. // // You don't need to use the Encrypt operation to encrypt a data key. The GenerateDataKey // and GenerateDataKeyPair operations return a plaintext data key and an encrypted @@ -2603,27 +2606,20 @@ func (c *KMS) GenerateDataKeyRequest(input *GenerateDataKeyInput) (req *request. // GenerateDataKey API operation for AWS Key Management Service. // -// Generates a unique symmetric data key. This operation returns a plaintext -// copy of the data key and a copy that is encrypted under a customer master -// key (CMK) that you specify. You can use the plaintext key to encrypt your -// data outside of AWS KMS and store the encrypted data key with the encrypted -// data. +// Generates a unique symmetric data key for client-side encryption. This operation +// returns a plaintext copy of the data key and a copy that is encrypted under +// a customer master key (CMK) that you specify. You can use the plaintext key +// to encrypt your data outside of AWS KMS and store the encrypted data key +// with the encrypted data. // // GenerateDataKey returns a unique data key for each request. The bytes in -// the key are not related to the caller or CMK that is used to encrypt the -// data key. +// the plaintext key are not related to the caller or the CMK. // // To generate a data key, specify the symmetric CMK that will be used to encrypt // the data key. You cannot use an asymmetric CMK to generate data keys. To -// get the type of your CMK, use the DescribeKey operation. -// -// You must also specify the length of the data key. Use either the KeySpec -// or NumberOfBytes parameters (but not both). For 128-bit and 256-bit data -// keys, use the KeySpec parameter. -// -// If the operation succeeds, the plaintext copy of the data key is in the Plaintext -// field of the response, and the encrypted copy of the data key in the CiphertextBlob -// field. +// get the type of your CMK, use the DescribeKey operation. You must also specify +// the length of the data key. Use either the KeySpec or NumberOfBytes parameters +// (but not both). For 128-bit and 256-bit data keys, use the KeySpec parameter. // // To get only an encrypted copy of the data key, use GenerateDataKeyWithoutPlaintext. // To generate an asymmetric data key pair, use the GenerateDataKeyPair or GenerateDataKeyPairWithoutPlaintext @@ -2640,24 +2636,32 @@ func (c *KMS) GenerateDataKeyRequest(input *GenerateDataKeyInput) (req *request. // For details, see How Key State Affects Use of a Customer Master Key (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) // in the AWS Key Management Service Developer Guide. // +// How to use your data key +// // We recommend that you use the following pattern to encrypt data locally in -// your application: +// your application. You can write your own code or use a client-side encryption +// library, such as the AWS Encryption SDK (https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/), +// the Amazon DynamoDB Encryption Client (https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/), +// or Amazon S3 client-side encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingClientSideEncryption.html) +// to do these tasks for you. // -// Use the GenerateDataKey operation to get a data encryption key. +// To encrypt data outside of AWS KMS: // -// Use the plaintext data key (returned in the Plaintext field of the response) -// to encrypt data locally, then erase the plaintext data key from memory. +// Use the GenerateDataKey operation to get a data key. // -// Store the encrypted data key (returned in the CiphertextBlob field of the -// response) alongside the locally encrypted data. +// Use the plaintext data key (in the Plaintext field of the response) to encrypt +// your data outside of AWS KMS. Then erase the plaintext data key from memory. // -// To decrypt data locally: +// Store the encrypted data key (in the CiphertextBlob field of the response) +// with the encrypted data. +// +// To decrypt data outside of AWS KMS: // // Use the Decrypt operation to decrypt the encrypted data key. The operation // returns a plaintext copy of the data key. // -// Use the plaintext data key to decrypt data locally, then erase the plaintext -// data key from memory. +// Use the plaintext data key to decrypt data outside of AWS KMS, then erase +// the plaintext data key from memory. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2794,7 +2798,8 @@ func (c *KMS) GenerateDataKeyPairRequest(input *GenerateDataKeyPairInput) (req * // // To generate a data key pair, you must specify a symmetric customer master // key (CMK) to encrypt the private key in a data key pair. You cannot use an -// asymmetric CMK. To get the type of your CMK, use the DescribeKey operation. +// asymmetric CMK or a CMK in a custom key store. To get the type and origin +// of your CMK, use the DescribeKey operation. // // If you are using the data key pair to encrypt data, or for any operation // where you don't immediately need a private key, consider using the GenerateDataKeyPairWithoutPlaintext @@ -2868,6 +2873,10 @@ func (c *KMS) GenerateDataKeyPairRequest(input *GenerateDataKeyPairInput) (req * // Key State Affects Use of a Customer Master Key (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) // in the AWS Key Management Service Developer Guide . // +// * UnsupportedOperationException +// The request was rejected because a specified parameter is not supported or +// a specified resource is not valid for this operation. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GenerateDataKeyPair func (c *KMS) GenerateDataKeyPair(input *GenerateDataKeyPairInput) (*GenerateDataKeyPairOutput, error) { req, out := c.GenerateDataKeyPairRequest(input) @@ -2941,8 +2950,8 @@ func (c *KMS) GenerateDataKeyPairWithoutPlaintextRequest(input *GenerateDataKeyP // // To generate a data key pair, you must specify a symmetric customer master // key (CMK) to encrypt the private key in the data key pair. You cannot use -// an asymmetric CMK. To get the type of your CMK, use the KeySpec field in -// the DescribeKey response. +// an asymmetric CMK or a CMK in a custom key store. To get the type and origin +// of your CMK, use the KeySpec field in the DescribeKey response. // // You can use the public key that GenerateDataKeyPairWithoutPlaintext returns // to encrypt data or verify a signature outside of AWS KMS. Then, store the @@ -3018,6 +3027,10 @@ func (c *KMS) GenerateDataKeyPairWithoutPlaintextRequest(input *GenerateDataKeyP // Key State Affects Use of a Customer Master Key (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) // in the AWS Key Management Service Developer Guide . // +// * UnsupportedOperationException +// The request was rejected because a specified parameter is not supported or +// a specified resource is not valid for this operation. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GenerateDataKeyPairWithoutPlaintext func (c *KMS) GenerateDataKeyPairWithoutPlaintext(input *GenerateDataKeyPairWithoutPlaintextInput) (*GenerateDataKeyPairWithoutPlaintextOutput, error) { req, out := c.GenerateDataKeyPairWithoutPlaintextRequest(input) @@ -4237,6 +4250,12 @@ func (c *KMS) ListGrantsRequest(input *ListGrantsInput) (req *request.Request, o // To perform this operation on a CMK in a different AWS account, specify the // key ARN in the value of the KeyId parameter. // +// The GranteePrincipal field in the ListGrants response usually contains the +// user or role designated as the grantee principal in the grant. However, when +// the grantee principal in the grant is an AWS service, the GranteePrincipal +// field contains the service principal (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html#principal-services), +// which might represent several different grantee principals. +// // Returns awserr.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. @@ -5016,13 +5035,15 @@ func (c *KMS) ReEncryptRequest(input *ReEncryptInput) (req *request.Request, out // is encrypted, such as when you manually rotate (https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html#rotate-keys-manually) // a CMK or change the CMK that protects a ciphertext. You can also use it to // reencrypt ciphertext under the same CMK, such as to change the encryption -// context of a ciphertext. +// context (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#encrypt_context) +// of a ciphertext. // // The ReEncrypt operation can decrypt ciphertext that was encrypted by using // an AWS KMS CMK in an AWS KMS operation, such as Encrypt or GenerateDataKey. // It can also decrypt ciphertext that was encrypted by using the public key -// of an asymmetric CMK outside of AWS KMS. However, it cannot decrypt ciphertext -// produced by other libraries, such as the AWS Encryption SDK (https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/) +// of an asymmetric CMK (https://docs.aws.amazon.com/kms/latest/developerguide/symm-asymm-concepts.html#asymmetric-cmks) +// outside of AWS KMS. However, it cannot decrypt ciphertext produced by other +// libraries, such as the AWS Encryption SDK (https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/) // or Amazon S3 client-side encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingClientSideEncryption.html). // These libraries return a ciphertext format that is incompatible with AWS // KMS. @@ -5057,17 +5078,16 @@ func (c *KMS) ReEncryptRequest(input *ReEncryptInput) (req *request.Request, out // // Unlike other AWS KMS API operations, ReEncrypt callers must have two permissions: // -// * kms:EncryptFrom permission on the source CMK +// * kms:ReEncryptFrom permission on the source CMK // -// * kms:EncryptTo permission on the destination CMK +// * kms:ReEncryptTo permission on the destination CMK // -// To permit reencryption from -// -// or to a CMK, include the "kms:ReEncrypt*" permission in your key policy (https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html). +// To permit reencryption from or to a CMK, include the "kms:ReEncrypt*" permission +// in your key policy (https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html). // This permission is automatically included in the key policy when you use // the console to create a CMK. But you must include it manually when you create -// a CMK programmatically or when you use the PutKeyPolicy operation set a key -// policy. +// a CMK programmatically or when you use the PutKeyPolicy operation to set +// a key policy. // // The CMK that you use for this operation must be in a compatible key state. // For details, see How Key State Affects Use of a Customer Master Key (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) @@ -5995,6 +6015,11 @@ func (c *KMS) UpdateAliasRequest(input *UpdateAliasInput) (req *request.Request, // The request was rejected because an internal exception occurred. The request // can be retried. // +// * LimitExceededException +// The request was rejected because a quota was exceeded. For more information, +// see Quotas (https://docs.aws.amazon.com/kms/latest/developerguide/limits.html) +// in the AWS Key Management Service Developer Guide. +// // * InvalidStateException // The request was rejected because the state of the specified resource is not // valid for this request. @@ -6642,7 +6667,8 @@ func (s *CancelKeyDeletionInput) SetKeyId(v string) *CancelKeyDeletionInput { type CancelKeyDeletionOutput struct { _ struct{} `type:"structure"` - // The unique identifier of the master key for which deletion is canceled. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the CMK whose deletion is canceled. KeyId *string `min:"1" type:"string"` } @@ -7259,9 +7285,10 @@ func (s *CreateCustomKeyStoreOutput) SetCustomKeyStoreId(v string) *CreateCustom type CreateGrantInput struct { _ struct{} `type:"structure"` - // Allows a cryptographic operation only when the encryption context matches - // or includes the encryption context specified in this structure. For more - // information about encryption context, see Encryption Context (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#encrypt_context) + // Allows a cryptographic operation (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations) + // only when the encryption context matches or includes the encryption context + // specified in this structure. For more information about encryption context, + // see Encryption Context (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#encrypt_context) // in the AWS Key Management Service Developer Guide . Constraints *GrantConstraints `type:"structure"` @@ -7530,9 +7557,10 @@ type CreateKeyInput struct { // a task. Description *string `type:"string"` - // Determines the cryptographic operations for which you can use the CMK. The - // default value is ENCRYPT_DECRYPT. This parameter is required only for asymmetric - // CMKs. You can't change the KeyUsage value after the CMK is created. + // Determines the cryptographic operations (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations) + // for which you can use the CMK. The default value is ENCRYPT_DECRYPT. This + // parameter is required only for asymmetric CMKs. You can't change the KeyUsage + // value after the CMK is created. // // Select only one valid value. // @@ -7992,11 +8020,12 @@ type CustomKeyStoresListEntry struct { // to the custom key store. // // * SUBNET_NOT_FOUND - A subnet in the AWS CloudHSM cluster configuration - // was deleted. If AWS KMS cannot find all of the subnets that were configured - // for the cluster when the custom key store was created, attempts to connect - // fail. To fix this error, create a cluster from a backup and associate - // it with your custom key store. This process includes selecting a VPC and - // subnets. For details, see How to Fix a Connection Failure (https://docs.aws.amazon.com/kms/latest/developerguide/fix-keystore.html#fix-keystore-failed) + // was deleted. If AWS KMS cannot find all of the subnets in the cluster + // configuration, attempts to connect the custom key store to the AWS CloudHSM + // cluster fail. To fix this error, create a cluster from a recent backup + // and associate it with your custom key store. (This process creates a new + // cluster configuration with a VPC and private subnets.) For details, see + // How to Fix a Connection Failure (https://docs.aws.amazon.com/kms/latest/developerguide/fix-keystore.html#fix-keystore-failed) // in the AWS Key Management Service Developer Guide. // // * USER_LOCKED_OUT - The kmsuser CU account is locked out of the associated @@ -8126,9 +8155,9 @@ type DecryptInput struct { EncryptionAlgorithm *string `type:"string" enum:"EncryptionAlgorithmSpec"` // Specifies the encryption context to use when decrypting the data. An encryption - // context is valid only for cryptographic operations with a symmetric CMK. - // The standard asymmetric encryption algorithms that AWS KMS uses do not support - // an encryption context. + // context is valid only for cryptographic operations (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations) + // with a symmetric CMK. The standard asymmetric encryption algorithms that + // AWS KMS uses do not support an encryption context. // // An encryption context is a collection of non-secret key-value pairs that // represents additional authenticated data. When you use an encryption context @@ -8241,7 +8270,8 @@ type DecryptOutput struct { // The encryption algorithm that was used to decrypt the ciphertext. EncryptionAlgorithm *string `type:"string" enum:"EncryptionAlgorithmSpec"` - // The ARN of the customer master key that was used to perform the decryption. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the CMK that was used to decrypt the ciphertext. KeyId *string `min:"1" type:"string"` // Decrypted plaintext data. When you use the HTTP API or the AWS CLI, the value @@ -9133,9 +9163,9 @@ type EncryptInput struct { EncryptionAlgorithm *string `type:"string" enum:"EncryptionAlgorithmSpec"` // Specifies the encryption context that will be used to encrypt the data. An - // encryption context is valid only for cryptographic operations with a symmetric - // CMK. The standard asymmetric encryption algorithms that AWS KMS uses do not - // support an encryption context. + // encryption context is valid only for cryptographic operations (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations) + // with a symmetric CMK. The standard asymmetric encryption algorithms that + // AWS KMS uses do not support an encryption context. // // An encryption context is a collection of non-secret key-value pairs that // represents additional authenticated data. When you use an encryption context @@ -9257,7 +9287,8 @@ type EncryptOutput struct { // The encryption algorithm that was used to encrypt the plaintext. EncryptionAlgorithm *string `type:"string" enum:"EncryptionAlgorithmSpec"` - // The ID of the key used during encryption. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the CMK that was used to encrypt the plaintext. KeyId *string `min:"1" type:"string"` } @@ -9475,7 +9506,8 @@ type GenerateDataKeyOutput struct { // CiphertextBlob is automatically base64 encoded/decoded by the SDK. CiphertextBlob []byte `min:"1" type:"blob"` - // The identifier of the CMK that encrypted the data key. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the CMK that encrypted the data key. KeyId *string `min:"1" type:"string"` // The plaintext data key. When you use the HTTP API or the AWS CLI, the value @@ -9538,7 +9570,8 @@ type GenerateDataKeyPairInput struct { GrantTokens []*string `type:"list"` // Specifies the symmetric CMK that encrypts the private key in the data key - // pair. You cannot specify an asymmetric CMKs. + // pair. You cannot specify an asymmetric CMK or a CMK in a custom key store. + // To get the type and origin of your CMK, use the DescribeKey operation. // // To specify a CMK, use its key ID, Amazon Resource Name (ARN), alias name, // or alias ARN. When using an alias name, prefix it with "alias/". To specify @@ -9627,7 +9660,8 @@ func (s *GenerateDataKeyPairInput) SetKeyPairSpec(v string) *GenerateDataKeyPair type GenerateDataKeyPairOutput struct { _ struct{} `type:"structure"` - // The identifier of the CMK that encrypted the private key. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the CMK that encrypted the private key. KeyId *string `min:"1" type:"string"` // The type of data key pair that was generated. @@ -9714,8 +9748,9 @@ type GenerateDataKeyPairWithoutPlaintextInput struct { GrantTokens []*string `type:"list"` // Specifies the CMK that encrypts the private key in the data key pair. You - // must specify a symmetric CMK. You cannot use an asymmetric CMK. To get the - // type of your CMK, use the DescribeKey operation. + // must specify a symmetric CMK. You cannot use an asymmetric CMK or a CMK in + // a custom key store. To get the type and origin of your CMK, use the DescribeKey + // operation. // // To specify a CMK, use its key ID, Amazon Resource Name (ARN), alias name, // or alias ARN. When using an alias name, prefix it with "alias/". @@ -9803,25 +9838,8 @@ func (s *GenerateDataKeyPairWithoutPlaintextInput) SetKeyPairSpec(v string) *Gen type GenerateDataKeyPairWithoutPlaintextOutput struct { _ struct{} `type:"structure"` - // Specifies the CMK that encrypted the private key in the data key pair. You - // must specify a symmetric CMK. You cannot use an asymmetric CMK. To get the - // type of your CMK, use the DescribeKey operation. - // - // To specify a CMK, use its key ID, Amazon Resource Name (ARN), alias name, - // or alias ARN. When using an alias name, prefix it with "alias/". - // - // For example: - // - // * Key ID: 1234abcd-12ab-34cd-56ef-1234567890ab - // - // * Key ARN: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab - // - // * Alias name: alias/ExampleAlias - // - // * Alias ARN: arn:aws:kms:us-east-2:111122223333:alias/ExampleAlias - // - // To get the key ID and key ARN for a CMK, use ListKeys or DescribeKey. To - // get the alias name and alias ARN, use ListAliases. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the CMK that encrypted the private key. KeyId *string `min:"1" type:"string"` // The type of data key pair that was generated. @@ -9997,7 +10015,8 @@ type GenerateDataKeyWithoutPlaintextOutput struct { // CiphertextBlob is automatically base64 encoded/decoded by the SDK. CiphertextBlob []byte `min:"1" type:"blob"` - // The identifier of the CMK that encrypted the data key. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the CMK that encrypted the data key. KeyId *string `min:"1" type:"string"` } @@ -10358,8 +10377,9 @@ type GetParametersForImportOutput struct { // ImportToken is automatically base64 encoded/decoded by the SDK. ImportToken []byte `min:"1" type:"blob"` - // The identifier of the CMK to use in a subsequent ImportKeyMaterial request. - // This is the same CMK specified in the GetParametersForImport request. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the CMK to use in a subsequent ImportKeyMaterial request. This is the + // same CMK specified in the GetParametersForImport request. KeyId *string `min:"1" type:"string"` // The time at which the import token and public key are no longer valid. After @@ -10494,7 +10514,8 @@ type GetPublicKeyOutput struct { // is ENCRYPT_DECRYPT. EncryptionAlgorithms []*string `type:"list"` - // The identifier of the asymmetric CMK from which the public key was downloaded. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the asymmetric CMK from which the public key was downloaded. KeyId *string `min:"1" type:"string"` // The permitted use of the public key. Valid values are ENCRYPT_DECRYPT or @@ -10567,24 +10588,16 @@ func (s *GetPublicKeyOutput) SetSigningAlgorithms(v []*string) *GetPublicKeyOutp return s } -// Use this structure to allow cryptographic operations in the grant only when -// the operation request includes the specified encryption context (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#encrypt_context). -// -// AWS KMS applies the grant constraints only when the grant allows a cryptographic -// operation that accepts an encryption context as input, such as the following. -// -// * Encrypt -// -// * Decrypt -// -// * GenerateDataKey -// -// * GenerateDataKeyWithoutPlaintext +// Use this structure to allow cryptographic operations (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations) +// in the grant only when the operation request includes the specified encryption +// context (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#encrypt_context). // -// * ReEncrypt -// -// AWS KMS does not apply the grant constraints to other operations, such as -// DescribeKey or ScheduleKeyDeletion. +// AWS KMS applies the grant constraints only to cryptographic operations that +// support an encryption context, that is, all cryptographic operations with +// a symmetric CMK (https://docs.aws.amazon.com/kms/latest/developerguide/symm-asymm-concepts.html#symmetric-cmks). +// Grant constraints are not applied to operations that do not support an encryption +// context, such as cryptographic operations with asymmetric CMKs and management +// operations, such as DescribeKey or ScheduleKeyDeletion. // // In a cryptographic operation, the encryption context in the decryption operation // must be an exact, case-sensitive match for the keys and values in the encryption @@ -10602,16 +10615,16 @@ type GrantConstraints struct { _ struct{} `type:"structure"` // A list of key-value pairs that must match the encryption context in the cryptographic - // operation request. The grant allows the operation only when the encryption - // context in the request is the same as the encryption context specified in - // this constraint. + // operation (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations) + // request. The grant allows the operation only when the encryption context + // in the request is the same as the encryption context specified in this constraint. EncryptionContextEquals map[string]*string `type:"map"` // A list of key-value pairs that must be included in the encryption context - // of the cryptographic operation request. The grant allows the cryptographic - // operation only when the encryption context in the request includes the key-value - // pairs specified in this constraint, although it can include additional key-value - // pairs. + // of the cryptographic operation (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations) + // request. The grant allows the cryptographic operation only when the encryption + // context in the request includes the key-value pairs specified in this constraint, + // although it can include additional key-value pairs. EncryptionContextSubset map[string]*string `type:"map"` } @@ -10637,7 +10650,7 @@ func (s *GrantConstraints) SetEncryptionContextSubset(v map[string]*string) *Gra return s } -// Contains information about an entry in a list of grants. +// Contains information about a grant. type GrantListEntry struct { _ struct{} `type:"structure"` @@ -10651,7 +10664,13 @@ type GrantListEntry struct { // The unique identifier for the grant. GrantId *string `min:"1" type:"string"` - // The principal that receives the grant's permissions. + // The identity that gets the permissions in the grant. + // + // The GranteePrincipal field in the ListGrants response usually contains the + // user or role designated as the grantee principal in the grant. However, when + // the grantee principal in the grant is an AWS service, the GranteePrincipal + // field contains the service principal (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html#principal-services), + // which might represent several different grantee principals. GranteePrincipal *string `min:"1" type:"string"` // The AWS account under which the grant was issued. @@ -11768,8 +11787,8 @@ type KeyMetadata struct { // is true, otherwise it is false. Enabled *bool `type:"boolean"` - // A list of encryption algorithms that the CMK supports. You cannot use the - // CMK with other encryption algorithms within AWS KMS. + // The encryption algorithms that the CMK supports. You cannot use the CMK with + // other encryption algorithms within AWS KMS. // // This field appears only when the KeyUsage of the CMK is ENCRYPT_DECRYPT. EncryptionAlgorithms []*string `type:"list"` @@ -11789,14 +11808,15 @@ type KeyMetadata struct { // in the AWS Key Management Service Developer Guide. KeyManager *string `type:"string" enum:"KeyManagerType"` - // The state of the CMK. + // The current status of the CMK. // - // For more information about how key state affects the use of a CMK, see How - // Key State Affects the Use of a Customer Master Key (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) + // For more information about how key state affects the use of a CMK, see Key + // state: Effect on your CMK (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) // in the AWS Key Management Service Developer Guide. KeyState *string `type:"string" enum:"KeyState"` - // The cryptographic operations for which you can use the CMK. + // The cryptographic operations (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#cryptographic-operations) + // for which you can use the CMK. KeyUsage *string `type:"string" enum:"KeyUsageType"` // The source of the CMK's key material. When this value is AWS_KMS, AWS KMS @@ -11806,8 +11826,8 @@ type KeyMetadata struct { // in the AWS CloudHSM cluster associated with a custom key store. Origin *string `type:"string" enum:"OriginType"` - // A list of signing algorithms that the CMK supports. You cannot use the CMK - // with other signing algorithms within AWS KMS. + // The signing algorithms that the CMK supports. You cannot use the CMK with + // other signing algorithms within AWS KMS. // // This field appears only when the KeyUsage of the CMK is SIGN_VERIFY. SigningAlgorithms []*string `type:"list"` @@ -13205,7 +13225,8 @@ type ReEncryptOutput struct { // The encryption algorithm that was used to reencrypt the data. DestinationEncryptionAlgorithm *string `type:"string" enum:"EncryptionAlgorithmSpec"` - // Unique identifier of the CMK used to reencrypt the data. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the CMK that was used to reencrypt the data. KeyId *string `min:"1" type:"string"` // The encryption algorithm that was used to decrypt the ciphertext before it @@ -13491,8 +13512,8 @@ type ScheduleKeyDeletionOutput struct { // The date and time after which AWS KMS deletes the customer master key (CMK). DeletionDate *time.Time `type:"timestamp"` - // The unique identifier of the customer master key (CMK) for which deletion - // is scheduled. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the CMK whose deletion is scheduled. KeyId *string `min:"1" type:"string"` } @@ -13644,8 +13665,8 @@ func (s *SignInput) SetSigningAlgorithm(v string) *SignInput { type SignOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the asymmetric CMK that was used to sign - // the message. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the asymmetric CMK that was used to sign the message. KeyId *string `min:"1" type:"string"` // The cryptographic signature that was generated for the message. @@ -14466,8 +14487,8 @@ func (s *VerifyInput) SetSigningAlgorithm(v string) *VerifyInput { type VerifyOutput struct { _ struct{} `type:"structure"` - // The unique identifier for the asymmetric CMK that was used to verify the - // signature. + // The Amazon Resource Name (key ARN (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)) + // of the asymmetric CMK that was used to verify the signature. KeyId *string `min:"1" type:"string"` // A Boolean value that indicates whether the signature was verified. A value @@ -14519,6 +14540,15 @@ const ( AlgorithmSpecRsaesOaepSha256 = "RSAES_OAEP_SHA_256" ) +// AlgorithmSpec_Values returns all elements of the AlgorithmSpec enum +func AlgorithmSpec_Values() []string { + return []string{ + AlgorithmSpecRsaesPkcs1V15, + AlgorithmSpecRsaesOaepSha1, + AlgorithmSpecRsaesOaepSha256, + } +} + const ( // ConnectionErrorCodeTypeInvalidCredentials is a ConnectionErrorCodeType enum value ConnectionErrorCodeTypeInvalidCredentials = "INVALID_CREDENTIALS" @@ -14548,6 +14578,21 @@ const ( ConnectionErrorCodeTypeSubnetNotFound = "SUBNET_NOT_FOUND" ) +// ConnectionErrorCodeType_Values returns all elements of the ConnectionErrorCodeType enum +func ConnectionErrorCodeType_Values() []string { + return []string{ + ConnectionErrorCodeTypeInvalidCredentials, + ConnectionErrorCodeTypeClusterNotFound, + ConnectionErrorCodeTypeNetworkErrors, + ConnectionErrorCodeTypeInternalError, + ConnectionErrorCodeTypeInsufficientCloudhsmHsms, + ConnectionErrorCodeTypeUserLockedOut, + ConnectionErrorCodeTypeUserNotFound, + ConnectionErrorCodeTypeUserLoggedIn, + ConnectionErrorCodeTypeSubnetNotFound, + } +} + const ( // ConnectionStateTypeConnected is a ConnectionStateType enum value ConnectionStateTypeConnected = "CONNECTED" @@ -14565,6 +14610,17 @@ const ( ConnectionStateTypeDisconnecting = "DISCONNECTING" ) +// ConnectionStateType_Values returns all elements of the ConnectionStateType enum +func ConnectionStateType_Values() []string { + return []string{ + ConnectionStateTypeConnected, + ConnectionStateTypeConnecting, + ConnectionStateTypeFailed, + ConnectionStateTypeDisconnected, + ConnectionStateTypeDisconnecting, + } +} + const ( // CustomerMasterKeySpecRsa2048 is a CustomerMasterKeySpec enum value CustomerMasterKeySpecRsa2048 = "RSA_2048" @@ -14591,6 +14647,20 @@ const ( CustomerMasterKeySpecSymmetricDefault = "SYMMETRIC_DEFAULT" ) +// CustomerMasterKeySpec_Values returns all elements of the CustomerMasterKeySpec enum +func CustomerMasterKeySpec_Values() []string { + return []string{ + CustomerMasterKeySpecRsa2048, + CustomerMasterKeySpecRsa3072, + CustomerMasterKeySpecRsa4096, + CustomerMasterKeySpecEccNistP256, + CustomerMasterKeySpecEccNistP384, + CustomerMasterKeySpecEccNistP521, + CustomerMasterKeySpecEccSecgP256k1, + CustomerMasterKeySpecSymmetricDefault, + } +} + const ( // DataKeyPairSpecRsa2048 is a DataKeyPairSpec enum value DataKeyPairSpecRsa2048 = "RSA_2048" @@ -14614,6 +14684,19 @@ const ( DataKeyPairSpecEccSecgP256k1 = "ECC_SECG_P256K1" ) +// DataKeyPairSpec_Values returns all elements of the DataKeyPairSpec enum +func DataKeyPairSpec_Values() []string { + return []string{ + DataKeyPairSpecRsa2048, + DataKeyPairSpecRsa3072, + DataKeyPairSpecRsa4096, + DataKeyPairSpecEccNistP256, + DataKeyPairSpecEccNistP384, + DataKeyPairSpecEccNistP521, + DataKeyPairSpecEccSecgP256k1, + } +} + const ( // DataKeySpecAes256 is a DataKeySpec enum value DataKeySpecAes256 = "AES_256" @@ -14622,6 +14705,14 @@ const ( DataKeySpecAes128 = "AES_128" ) +// DataKeySpec_Values returns all elements of the DataKeySpec enum +func DataKeySpec_Values() []string { + return []string{ + DataKeySpecAes256, + DataKeySpecAes128, + } +} + const ( // EncryptionAlgorithmSpecSymmetricDefault is a EncryptionAlgorithmSpec enum value EncryptionAlgorithmSpecSymmetricDefault = "SYMMETRIC_DEFAULT" @@ -14633,6 +14724,15 @@ const ( EncryptionAlgorithmSpecRsaesOaepSha256 = "RSAES_OAEP_SHA_256" ) +// EncryptionAlgorithmSpec_Values returns all elements of the EncryptionAlgorithmSpec enum +func EncryptionAlgorithmSpec_Values() []string { + return []string{ + EncryptionAlgorithmSpecSymmetricDefault, + EncryptionAlgorithmSpecRsaesOaepSha1, + EncryptionAlgorithmSpecRsaesOaepSha256, + } +} + const ( // ExpirationModelTypeKeyMaterialExpires is a ExpirationModelType enum value ExpirationModelTypeKeyMaterialExpires = "KEY_MATERIAL_EXPIRES" @@ -14641,6 +14741,14 @@ const ( ExpirationModelTypeKeyMaterialDoesNotExpire = "KEY_MATERIAL_DOES_NOT_EXPIRE" ) +// ExpirationModelType_Values returns all elements of the ExpirationModelType enum +func ExpirationModelType_Values() []string { + return []string{ + ExpirationModelTypeKeyMaterialExpires, + ExpirationModelTypeKeyMaterialDoesNotExpire, + } +} + const ( // GrantOperationDecrypt is a GrantOperation enum value GrantOperationDecrypt = "Decrypt" @@ -14685,6 +14793,26 @@ const ( GrantOperationGenerateDataKeyPairWithoutPlaintext = "GenerateDataKeyPairWithoutPlaintext" ) +// GrantOperation_Values returns all elements of the GrantOperation enum +func GrantOperation_Values() []string { + return []string{ + GrantOperationDecrypt, + GrantOperationEncrypt, + GrantOperationGenerateDataKey, + GrantOperationGenerateDataKeyWithoutPlaintext, + GrantOperationReEncryptFrom, + GrantOperationReEncryptTo, + GrantOperationSign, + GrantOperationVerify, + GrantOperationGetPublicKey, + GrantOperationCreateGrant, + GrantOperationRetireGrant, + GrantOperationDescribeKey, + GrantOperationGenerateDataKeyPair, + GrantOperationGenerateDataKeyPairWithoutPlaintext, + } +} + const ( // KeyManagerTypeAws is a KeyManagerType enum value KeyManagerTypeAws = "AWS" @@ -14693,6 +14821,14 @@ const ( KeyManagerTypeCustomer = "CUSTOMER" ) +// KeyManagerType_Values returns all elements of the KeyManagerType enum +func KeyManagerType_Values() []string { + return []string{ + KeyManagerTypeAws, + KeyManagerTypeCustomer, + } +} + const ( // KeyStateEnabled is a KeyState enum value KeyStateEnabled = "Enabled" @@ -14710,6 +14846,17 @@ const ( KeyStateUnavailable = "Unavailable" ) +// KeyState_Values returns all elements of the KeyState enum +func KeyState_Values() []string { + return []string{ + KeyStateEnabled, + KeyStateDisabled, + KeyStatePendingDeletion, + KeyStatePendingImport, + KeyStateUnavailable, + } +} + const ( // KeyUsageTypeSignVerify is a KeyUsageType enum value KeyUsageTypeSignVerify = "SIGN_VERIFY" @@ -14718,6 +14865,14 @@ const ( KeyUsageTypeEncryptDecrypt = "ENCRYPT_DECRYPT" ) +// KeyUsageType_Values returns all elements of the KeyUsageType enum +func KeyUsageType_Values() []string { + return []string{ + KeyUsageTypeSignVerify, + KeyUsageTypeEncryptDecrypt, + } +} + const ( // MessageTypeRaw is a MessageType enum value MessageTypeRaw = "RAW" @@ -14726,6 +14881,14 @@ const ( MessageTypeDigest = "DIGEST" ) +// MessageType_Values returns all elements of the MessageType enum +func MessageType_Values() []string { + return []string{ + MessageTypeRaw, + MessageTypeDigest, + } +} + const ( // OriginTypeAwsKms is a OriginType enum value OriginTypeAwsKms = "AWS_KMS" @@ -14737,6 +14900,15 @@ const ( OriginTypeAwsCloudhsm = "AWS_CLOUDHSM" ) +// OriginType_Values returns all elements of the OriginType enum +func OriginType_Values() []string { + return []string{ + OriginTypeAwsKms, + OriginTypeExternal, + OriginTypeAwsCloudhsm, + } +} + const ( // SigningAlgorithmSpecRsassaPssSha256 is a SigningAlgorithmSpec enum value SigningAlgorithmSpecRsassaPssSha256 = "RSASSA_PSS_SHA_256" @@ -14766,7 +14938,29 @@ const ( SigningAlgorithmSpecEcdsaSha512 = "ECDSA_SHA_512" ) +// SigningAlgorithmSpec_Values returns all elements of the SigningAlgorithmSpec enum +func SigningAlgorithmSpec_Values() []string { + return []string{ + SigningAlgorithmSpecRsassaPssSha256, + SigningAlgorithmSpecRsassaPssSha384, + SigningAlgorithmSpecRsassaPssSha512, + SigningAlgorithmSpecRsassaPkcs1V15Sha256, + SigningAlgorithmSpecRsassaPkcs1V15Sha384, + SigningAlgorithmSpecRsassaPkcs1V15Sha512, + SigningAlgorithmSpecEcdsaSha256, + SigningAlgorithmSpecEcdsaSha384, + SigningAlgorithmSpecEcdsaSha512, + } +} + const ( // WrappingKeySpecRsa2048 is a WrappingKeySpec enum value WrappingKeySpecRsa2048 = "RSA_2048" ) + +// WrappingKeySpec_Values returns all elements of the WrappingKeySpec enum +func WrappingKeySpec_Values() []string { + return []string{ + WrappingKeySpecRsa2048, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/lakeformation/api.go b/vendor/github.com/aws/aws-sdk-go/service/lakeformation/api.go index fe19b68cbf5..2f21037627f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/lakeformation/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/lakeformation/api.go @@ -402,7 +402,8 @@ func (c *LakeFormation) GetDataLakeSettingsRequest(input *GetDataLakeSettingsInp // GetDataLakeSettings API operation for AWS Lake Formation. // -// The AWS Lake Formation principal. +// Retrieves the list of the data lake administrators of a Lake Formation-managed +// data lake. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -493,8 +494,9 @@ func (c *LakeFormation) GetEffectivePermissionsForPathRequest(input *GetEffectiv // GetEffectivePermissionsForPath API operation for AWS Lake Formation. // -// Returns the permissions for a specified table or database resource located -// at a path in Amazon S3. +// Returns the Lake Formation permissions for a specified table or database +// resource located at a path in Amazon S3. GetEffectivePermissionsForPath will +// not return databases and tables if the catalog is encrypted. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -639,7 +641,7 @@ func (c *LakeFormation) GrantPermissionsRequest(input *GrantPermissionsInput) (r // and data organized in underlying data storage such as Amazon S3. // // For information about permissions, see Security and Access Control to Metadata -// and Data (https://docs-aws.amazon.com/michigan/latest/dg/security-data-access.html). +// and Data (https://docs-aws.amazon.com/lake-formation/latest/dg/security-data-access.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 @@ -737,7 +739,7 @@ func (c *LakeFormation) ListPermissionsRequest(input *ListPermissionsInput) (req // This operation returns only those permissions that have been explicitly granted. // // For information about permissions, see Security and Access Control to Metadata -// and Data (https://docs-aws.amazon.com/michigan/latest/dg/security-data-access.html). +// and Data (https://docs-aws.amazon.com/lake-formation/latest/dg/security-data-access.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 @@ -1018,7 +1020,13 @@ func (c *LakeFormation) PutDataLakeSettingsRequest(input *PutDataLakeSettingsInp // PutDataLakeSettings API operation for AWS Lake Formation. // -// The AWS Lake Formation principal. +// Sets the list of data lake administrators who have admin privileges on all +// resources managed by Lake Formation. For more information on admin privileges, +// see Granting Lake Formation Permissions (https://docs.aws.amazon.com/lake-formation/latest/dg/lake-formation-permissions.html). +// +// This API replaces the current list of data lake admins with the new list +// being passed. To add an admin, fetch the current list and add the new admin +// to that list and pass that list in 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 @@ -1112,6 +1120,15 @@ func (c *LakeFormation) RegisterResourceRequest(input *RegisterResourceInput) (r // you register subsequent paths, Lake Formation adds the path to the existing // policy. // +// The following request registers a new location and gives AWS Lake Formation +// permission to use the service-linked role to access that location. +// +// ResourceArn = arn:aws:s3:::my-bucket UseServiceLinkedRole = true +// +// If UseServiceLinkedRole is not set to true, you must provide or set the RoleArn: +// +// arn:aws:iam::12345:role/my-data-access-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. @@ -1780,7 +1797,8 @@ func (s *ConcurrentModificationException) RequestID() string { return s.RespMetadata.RequestID } -// The AWS Lake Formation principal. +// The AWS Lake Formation principal. Supported principals are IAM users or IAM +// roles. type DataLakePrincipal struct { _ struct{} `type:"structure"` @@ -1817,20 +1835,31 @@ func (s *DataLakePrincipal) SetDataLakePrincipalIdentifier(v string) *DataLakePr return s } -// The AWS Lake Formation principal. +// A structure representing a list of AWS Lake Formation principals designated +// as data lake administrators and lists of principal permission entries for +// default create database and default create table permissions. type DataLakeSettings struct { _ struct{} `type:"structure"` - // A list of up to three principal permissions entries for default create database - // permissions. + // A structure representing a list of up to three principal permissions entries + // for default create database permissions. CreateDatabaseDefaultPermissions []*PrincipalPermissions `type:"list"` - // A list of up to three principal permissions entries for default create table - // permissions. + // A structure representing a list of up to three principal permissions entries + // for default create table permissions. CreateTableDefaultPermissions []*PrincipalPermissions `type:"list"` - // A list of AWS Lake Formation principals. + // A list of AWS Lake Formation principals. Supported principals are IAM users + // or IAM roles. DataLakeAdmins []*DataLakePrincipal `type:"list"` + + // A list of the resource-owning account IDs that the caller's account can use + // to share their user access details (user ARNs). The user ARNs can be logged + // in the resource owner's AWS CloudTrail log. + // + // You may want to specify this property when you are in a high-trust boundary, + // such as the same team or company. + TrustedResourceOwners []*string `type:"list"` } // String returns the string representation @@ -1901,10 +1930,20 @@ func (s *DataLakeSettings) SetDataLakeAdmins(v []*DataLakePrincipal) *DataLakeSe return s } +// SetTrustedResourceOwners sets the TrustedResourceOwners field's value. +func (s *DataLakeSettings) SetTrustedResourceOwners(v []*string) *DataLakeSettings { + s.TrustedResourceOwners = v + return s +} + // A structure for a data location object where permissions are granted or revoked. type DataLocationResource struct { _ struct{} `type:"structure"` + // The identifier for the Data Catalog where the location is registered with + // AWS Lake Formation. By default, it is the account ID of the caller. + CatalogId *string `min:"1" type:"string"` + // The Amazon Resource Name (ARN) that uniquely identifies the data location // resource. // @@ -1925,6 +1964,9 @@ func (s DataLocationResource) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *DataLocationResource) Validate() error { invalidParams := request.ErrInvalidParams{Context: "DataLocationResource"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } if s.ResourceArn == nil { invalidParams.Add(request.NewErrParamRequired("ResourceArn")) } @@ -1935,6 +1977,12 @@ func (s *DataLocationResource) Validate() error { return nil } +// SetCatalogId sets the CatalogId field's value. +func (s *DataLocationResource) SetCatalogId(v string) *DataLocationResource { + s.CatalogId = &v + return s +} + // SetResourceArn sets the ResourceArn field's value. func (s *DataLocationResource) SetResourceArn(v string) *DataLocationResource { s.ResourceArn = &v @@ -1945,6 +1993,10 @@ func (s *DataLocationResource) SetResourceArn(v string) *DataLocationResource { type DatabaseResource struct { _ struct{} `type:"structure"` + // The identifier for the Data Catalog. By default, it is the account ID of + // the caller. + CatalogId *string `min:"1" type:"string"` + // The name of the database resource. Unique to the Data Catalog. // // Name is a required field @@ -1964,6 +2016,9 @@ func (s DatabaseResource) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *DatabaseResource) Validate() error { invalidParams := request.ErrInvalidParams{Context: "DatabaseResource"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } if s.Name == nil { invalidParams.Add(request.NewErrParamRequired("Name")) } @@ -1977,6 +2032,12 @@ func (s *DatabaseResource) Validate() error { return nil } +// SetCatalogId sets the CatalogId field's value. +func (s *DatabaseResource) SetCatalogId(v string) *DatabaseResource { + s.CatalogId = &v + return s +} + // SetName sets the Name field's value. func (s *DatabaseResource) SetName(v string) *DatabaseResource { s.Name = &v @@ -2271,7 +2332,8 @@ func (s *GetDataLakeSettingsInput) SetCatalogId(v string) *GetDataLakeSettingsIn type GetDataLakeSettingsOutput struct { _ struct{} `type:"structure"` - // A list of AWS Lake Formation principals. + // A structure representing a list of AWS Lake Formation principals designated + // as data lake administrators. DataLakeSettings *DataLakeSettings `type:"structure"` } @@ -3030,7 +3092,8 @@ type PutDataLakeSettingsInput struct { // Formation environment. CatalogId *string `min:"1" type:"string"` - // A list of AWS Lake Formation principals. + // A structure representing a list of AWS Lake Formation principals designated + // as data lake administrators. // // DataLakeSettings is a required field DataLakeSettings *DataLakeSettings `type:"structure" required:"true"` @@ -3101,11 +3164,14 @@ type RegisterResourceInput struct { // ResourceArn is a required field ResourceArn *string `type:"string" required:"true"` - // The identifier for the role. + // The identifier for the role that registers the resource. RoleArn *string `type:"string"` - // Designates a trusted caller, an IAM principal, by registering this caller - // with the Data Catalog. + // Designates an AWS Identity and Access Management (IAM) service-linked role + // by registering this role with the Data Catalog. A service-linked role is + // a unique type of IAM role that is linked directly to Lake Formation. + // + // For more information, see Using Service-Linked Roles for Lake Formation (https://docs-aws.amazon.com/lake-formation/latest/dg/service-linked-roles.html). UseServiceLinkedRole *bool `type:"boolean"` } @@ -3314,7 +3380,7 @@ type RevokePermissionsInput struct { CatalogId *string `min:"1" type:"string"` // The permissions revoked to the principal on the resource. For information - // about permissions, see Security and Access Control to Metadata and Data (https://docs-aws.amazon.com/michigan/latest/dg/security-data-access.html). + // about permissions, see Security and Access Control to Metadata and Data (https://docs-aws.amazon.com/lake-formation/latest/dg/security-data-access.html). // // Permissions is a required field Permissions []*string `type:"list" required:"true"` @@ -3425,6 +3491,10 @@ func (s RevokePermissionsOutput) GoString() string { type TableResource struct { _ struct{} `type:"structure"` + // The identifier for the Data Catalog. By default, it is the account ID of + // the caller. + CatalogId *string `min:"1" type:"string"` + // The name of the database for the table. Unique to a Data Catalog. A database // is a set of associated table definitions organized into a logical group. // You can Grant and Revoke database privileges to a principal. @@ -3433,9 +3503,12 @@ type TableResource struct { DatabaseName *string `min:"1" type:"string" required:"true"` // The name of the table. + Name *string `min:"1" type:"string"` + + // A wildcard object representing every table under a database. // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` + // At least one of TableResource$Name or TableResource$TableWildcard is required. + TableWildcard *TableWildcard `type:"structure"` } // String returns the string representation @@ -3451,15 +3524,15 @@ func (s TableResource) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *TableResource) Validate() error { invalidParams := request.ErrInvalidParams{Context: "TableResource"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } if s.DatabaseName == nil { invalidParams.Add(request.NewErrParamRequired("DatabaseName")) } if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } @@ -3470,6 +3543,12 @@ func (s *TableResource) Validate() error { return nil } +// SetCatalogId sets the CatalogId field's value. +func (s *TableResource) SetCatalogId(v string) *TableResource { + s.CatalogId = &v + return s +} + // SetDatabaseName sets the DatabaseName field's value. func (s *TableResource) SetDatabaseName(v string) *TableResource { s.DatabaseName = &v @@ -3482,6 +3561,27 @@ func (s *TableResource) SetName(v string) *TableResource { return s } +// SetTableWildcard sets the TableWildcard field's value. +func (s *TableResource) SetTableWildcard(v *TableWildcard) *TableResource { + s.TableWildcard = v + return s +} + +// A wildcard object representing every table under a database. +type TableWildcard struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s TableWildcard) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TableWildcard) GoString() string { + return s.String() +} + // A structure for a table with columns object. This object is only used when // granting a SELECT permission. // @@ -3490,6 +3590,10 @@ func (s *TableResource) SetName(v string) *TableResource { type TableWithColumnsResource struct { _ struct{} `type:"structure"` + // The identifier for the Data Catalog. By default, it is the account ID of + // the caller. + CatalogId *string `min:"1" type:"string"` + // The list of column names for the table. At least one of ColumnNames or ColumnWildcard // is required. ColumnNames []*string `type:"list"` @@ -3501,11 +3605,15 @@ type TableWithColumnsResource struct { // The name of the database for the table with columns resource. Unique to the // Data Catalog. A database is a set of associated table definitions organized // into a logical group. You can Grant and Revoke database privileges to a principal. - DatabaseName *string `min:"1" type:"string"` + // + // DatabaseName is a required field + DatabaseName *string `min:"1" type:"string" required:"true"` // The name of the table resource. A table is a metadata definition that represents // your data. You can Grant and Revoke table privileges to a principal. - Name *string `min:"1" type:"string"` + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` } // String returns the string representation @@ -3521,9 +3629,18 @@ func (s TableWithColumnsResource) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *TableWithColumnsResource) Validate() error { invalidParams := request.ErrInvalidParams{Context: "TableWithColumnsResource"} + if s.CatalogId != nil && len(*s.CatalogId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CatalogId", 1)) + } + if s.DatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("DatabaseName")) + } if s.DatabaseName != nil && len(*s.DatabaseName) < 1 { invalidParams.Add(request.NewErrParamMinLen("DatabaseName", 1)) } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } @@ -3534,6 +3651,12 @@ func (s *TableWithColumnsResource) Validate() error { return nil } +// SetCatalogId sets the CatalogId field's value. +func (s *TableWithColumnsResource) SetCatalogId(v string) *TableWithColumnsResource { + s.CatalogId = &v + return s +} + // SetColumnNames sets the ColumnNames field's value. func (s *TableWithColumnsResource) SetColumnNames(v []*string) *TableWithColumnsResource { s.ColumnNames = v @@ -3659,6 +3782,23 @@ const ( ComparisonOperatorBetween = "BETWEEN" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorEq, + ComparisonOperatorNe, + ComparisonOperatorLe, + ComparisonOperatorLt, + ComparisonOperatorGe, + ComparisonOperatorGt, + ComparisonOperatorContains, + ComparisonOperatorNotContains, + ComparisonOperatorBeginsWith, + ComparisonOperatorIn, + ComparisonOperatorBetween, + } +} + const ( // DataLakeResourceTypeCatalog is a DataLakeResourceType enum value DataLakeResourceTypeCatalog = "CATALOG" @@ -3673,6 +3813,16 @@ const ( DataLakeResourceTypeDataLocation = "DATA_LOCATION" ) +// DataLakeResourceType_Values returns all elements of the DataLakeResourceType enum +func DataLakeResourceType_Values() []string { + return []string{ + DataLakeResourceTypeCatalog, + DataLakeResourceTypeDatabase, + DataLakeResourceTypeTable, + DataLakeResourceTypeDataLocation, + } +} + const ( // FieldNameStringResourceArn is a FieldNameString enum value FieldNameStringResourceArn = "RESOURCE_ARN" @@ -3684,6 +3834,15 @@ const ( FieldNameStringLastModified = "LAST_MODIFIED" ) +// FieldNameString_Values returns all elements of the FieldNameString enum +func FieldNameString_Values() []string { + return []string{ + FieldNameStringResourceArn, + FieldNameStringRoleArn, + FieldNameStringLastModified, + } +} + const ( // PermissionAll is a Permission enum value PermissionAll = "ALL" @@ -3703,6 +3862,9 @@ const ( // PermissionInsert is a Permission enum value PermissionInsert = "INSERT" + // PermissionDescribe is a Permission enum value + PermissionDescribe = "DESCRIBE" + // PermissionCreateDatabase is a Permission enum value PermissionCreateDatabase = "CREATE_DATABASE" @@ -3712,3 +3874,19 @@ const ( // PermissionDataLocationAccess is a Permission enum value PermissionDataLocationAccess = "DATA_LOCATION_ACCESS" ) + +// Permission_Values returns all elements of the Permission enum +func Permission_Values() []string { + return []string{ + PermissionAll, + PermissionSelect, + PermissionAlter, + PermissionDrop, + PermissionDelete, + PermissionInsert, + PermissionDescribe, + PermissionCreateDatabase, + PermissionCreateTable, + PermissionDataLocationAccess, + } +} 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 e1495de85c5..5a3d5002371 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 @@ -387,6 +387,8 @@ func (c *Lambda) CreateEventSourceMappingRequest(input *CreateEventSourceMapping // // * Using AWS Lambda with Amazon SQS (https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html) // +// * Using AWS Lambda with Amazon MSK (https://docs.aws.amazon.com/lambda/latest/dg/with-msk.html) +// // The following error handling options are only available for stream sources // (DynamoDB and Kinesis): // @@ -397,10 +399,11 @@ func (c *Lambda) CreateEventSourceMappingRequest(input *CreateEventSourceMapping // Amazon SNS topic. // // * MaximumRecordAgeInSeconds - Discard records older than the specified -// age. +// age. Default -1 (infinite). Minimum 60. Maximum 604800. // // * MaximumRetryAttempts - Discard records after the specified number of -// retries. +// retries. Default -1 (infinite). Minimum 0. Maximum 10000. When infinite, +// failed records will be retried until the record expires. // // * ParallelizationFactor - Process multiple batches from each shard concurrently. // @@ -2420,6 +2423,20 @@ func (c *Lambda) InvokeRequest(input *InvokeInput) (req *request.Request, output // specified as part of Lambda function configuration, because the limit for // network interfaces has been reached. // +// * EFSMountConnectivityException +// The function couldn't make a network connection to the configured file system. +// +// * EFSMountFailureException +// The function couldn't mount the configured file system due to a permission +// or configuration issue. +// +// * EFSMountTimeoutException +// The function was able to make a network connection to the configured file +// system, but the mount operation timed out. +// +// * EFSIOException +// An error occured when reading from or writing to a connected file system. +// // * EC2ThrottledException // AWS Lambda was throttled by Amazon EC2 during Lambda function initialization // using the execution role provided for the Lambda function. @@ -4211,7 +4228,7 @@ func (c *Lambda) PutFunctionEventInvokeConfigRequest(input *PutFunctionEventInvo // on a function, version, or alias. If a configuration already exists for a // function, version, or alias, this operation overwrites it. If you exclude // any settings, they are removed. To set one option without affecting existing -// settings for other options, use PutFunctionEventInvokeConfig. +// settings for other options, use UpdateFunctionEventInvokeConfig. // // By default, Lambda retries an asynchronous invocation twice if the function // returns an error. It retains events in a queue for up to six hours. When @@ -4888,10 +4905,11 @@ func (c *Lambda) UpdateEventSourceMappingRequest(input *UpdateEventSourceMapping // Amazon SNS topic. // // * MaximumRecordAgeInSeconds - Discard records older than the specified -// age. +// age. Default -1 (infinite). Minimum 60. Maximum 604800. // // * MaximumRetryAttempts - Discard records after the specified number of -// retries. +// retries. Default -1 (infinite). Minimum 0. Maximum 10000. When infinite, +// failed records will be retried until the record expires. // // * ParallelizationFactor - Process multiple batches from each shard concurrently. // @@ -5756,8 +5774,7 @@ func (s *AliasConfiguration) SetRoutingConfig(v *AliasRoutingConfiguration) *Ali type AliasRoutingConfiguration struct { _ struct{} `type:"structure"` - // The name of the second alias, and the percentage of traffic that's routed - // to it. + // The second version, and the percentage of traffic that's routed to it. AdditionalVersionWeights map[string]*float64 `type:"map"` } @@ -5868,7 +5885,7 @@ type CreateAliasInput struct { // Name is a required field Name *string `min:"1" type:"string" required:"true"` - // The routing configuration (https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) + // The routing configuration (https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html#configuring-alias-routing) // of the alias. RoutingConfig *AliasRoutingConfiguration `type:"structure"` } @@ -5951,6 +5968,8 @@ type CreateEventSourceMappingInput struct { // * Amazon DynamoDB Streams - Default 100. Max 1,000. // // * Amazon Simple Queue Service - Default 10. Max 10. + // + // * Amazon Managed Streaming for Apache Kafka - Default 100. Max 10,000. BatchSize *int64 `min:"1" type:"integer"` // (Streams) If the function returns an error, split the batch in two and retry. @@ -5960,7 +5979,8 @@ type CreateEventSourceMappingInput struct { // records. DestinationConfig *DestinationConfig `type:"structure"` - // Disables the event source mapping to pause polling and invocation. + // If true, the event source mapping is active. Set to false to pause polling + // and invocation. Enabled *bool `type:"boolean"` // The Amazon Resource Name (ARN) of the event source. @@ -5971,6 +5991,8 @@ type CreateEventSourceMappingInput struct { // // * Amazon Simple Queue Service - The ARN of the queue. // + // * Amazon Managed Streaming for Apache Kafka - The ARN of the cluster. + // // EventSourceArn is a required field EventSourceArn *string `type:"string" required:"true"` @@ -5996,24 +6018,28 @@ type CreateEventSourceMappingInput struct { // function, in seconds. MaximumBatchingWindowInSeconds *int64 `type:"integer"` - // (Streams) The maximum age of a record that Lambda sends to a function for - // processing. - MaximumRecordAgeInSeconds *int64 `min:"60" type:"integer"` + // (Streams) Discard records older than the specified age. The default value + // is infinite (-1). + MaximumRecordAgeInSeconds *int64 `type:"integer"` - // (Streams) The maximum number of times to retry when the function returns - // an error. + // (Streams) Discard records after the specified number of retries. The default + // value is infinite (-1). When set to infinite (-1), failed records will be + // retried until the record expires. MaximumRetryAttempts *int64 `type:"integer"` // (Streams) The number of batches to process from each shard concurrently. ParallelizationFactor *int64 `min:"1" type:"integer"` // The position in a stream from which to start reading. Required for Amazon - // Kinesis and Amazon DynamoDB Streams sources. AT_TIMESTAMP is only supported - // for Amazon Kinesis streams. + // Kinesis, Amazon DynamoDB, and Amazon MSK Streams sources. AT_TIMESTAMP is + // only supported for Amazon Kinesis streams. StartingPosition *string `type:"string" enum:"EventSourcePosition"` // With StartingPosition set to AT_TIMESTAMP, the time from which to start reading. StartingPositionTimestamp *time.Time `type:"timestamp"` + + // (MSK) The name of the Kafka topic. + Topics []*string `min:"1" type:"list"` } // String returns the string representation @@ -6041,12 +6067,18 @@ func (s *CreateEventSourceMappingInput) Validate() error { if s.FunctionName != nil && len(*s.FunctionName) < 1 { invalidParams.Add(request.NewErrParamMinLen("FunctionName", 1)) } - if s.MaximumRecordAgeInSeconds != nil && *s.MaximumRecordAgeInSeconds < 60 { - invalidParams.Add(request.NewErrParamMinValue("MaximumRecordAgeInSeconds", 60)) + if s.MaximumRecordAgeInSeconds != nil && *s.MaximumRecordAgeInSeconds < -1 { + invalidParams.Add(request.NewErrParamMinValue("MaximumRecordAgeInSeconds", -1)) + } + if s.MaximumRetryAttempts != nil && *s.MaximumRetryAttempts < -1 { + invalidParams.Add(request.NewErrParamMinValue("MaximumRetryAttempts", -1)) } if s.ParallelizationFactor != nil && *s.ParallelizationFactor < 1 { invalidParams.Add(request.NewErrParamMinValue("ParallelizationFactor", 1)) } + if s.Topics != nil && len(s.Topics) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Topics", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -6126,6 +6158,12 @@ func (s *CreateEventSourceMappingInput) SetStartingPositionTimestamp(v time.Time return s } +// SetTopics sets the Topics field's value. +func (s *CreateEventSourceMappingInput) SetTopics(v []*string) *CreateEventSourceMappingInput { + s.Topics = v + return s +} + type CreateFunctionInput struct { _ struct{} `type:"structure"` @@ -6145,6 +6183,9 @@ type CreateFunctionInput struct { // Environment variables that are accessible from function code during execution. Environment *Environment `type:"structure"` + // Connection settings for an Amazon EFS file system. + FileSystemConfigs []*FileSystemConfig `type:"list"` + // The name of the Lambda function. // // Name formats @@ -6258,6 +6299,16 @@ func (s *CreateFunctionInput) Validate() error { invalidParams.AddNested("Code", err.(request.ErrInvalidParams)) } } + if s.FileSystemConfigs != nil { + for i, v := range s.FileSystemConfigs { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "FileSystemConfigs", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -6289,6 +6340,12 @@ func (s *CreateFunctionInput) SetEnvironment(v *Environment) *CreateFunctionInpu return s } +// SetFileSystemConfigs sets the FileSystemConfigs field's value. +func (s *CreateFunctionInput) SetFileSystemConfigs(v []*FileSystemConfig) *CreateFunctionInput { + s.FileSystemConfigs = v + return s +} + // SetFunctionName sets the FunctionName field's value. func (s *CreateFunctionInput) SetFunctionName(v string) *CreateFunctionInput { s.FunctionName = &v @@ -7099,6 +7156,240 @@ func (s *EC2UnexpectedException) RequestID() string { return s.RespMetadata.RequestID } +// An error occured when reading from or writing to a connected file system. +type EFSIOException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + Type *string `type:"string"` +} + +// String returns the string representation +func (s EFSIOException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EFSIOException) GoString() string { + return s.String() +} + +func newErrorEFSIOException(v protocol.ResponseMetadata) error { + return &EFSIOException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *EFSIOException) Code() string { + return "EFSIOException" +} + +// Message returns the exception's message. +func (s *EFSIOException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *EFSIOException) OrigErr() error { + return nil +} + +func (s *EFSIOException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *EFSIOException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *EFSIOException) RequestID() string { + return s.RespMetadata.RequestID +} + +// The function couldn't make a network connection to the configured file system. +type EFSMountConnectivityException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + Type *string `type:"string"` +} + +// String returns the string representation +func (s EFSMountConnectivityException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EFSMountConnectivityException) GoString() string { + return s.String() +} + +func newErrorEFSMountConnectivityException(v protocol.ResponseMetadata) error { + return &EFSMountConnectivityException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *EFSMountConnectivityException) Code() string { + return "EFSMountConnectivityException" +} + +// Message returns the exception's message. +func (s *EFSMountConnectivityException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *EFSMountConnectivityException) OrigErr() error { + return nil +} + +func (s *EFSMountConnectivityException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *EFSMountConnectivityException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *EFSMountConnectivityException) RequestID() string { + return s.RespMetadata.RequestID +} + +// The function couldn't mount the configured file system due to a permission +// or configuration issue. +type EFSMountFailureException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + Type *string `type:"string"` +} + +// String returns the string representation +func (s EFSMountFailureException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EFSMountFailureException) GoString() string { + return s.String() +} + +func newErrorEFSMountFailureException(v protocol.ResponseMetadata) error { + return &EFSMountFailureException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *EFSMountFailureException) Code() string { + return "EFSMountFailureException" +} + +// Message returns the exception's message. +func (s *EFSMountFailureException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *EFSMountFailureException) OrigErr() error { + return nil +} + +func (s *EFSMountFailureException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *EFSMountFailureException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *EFSMountFailureException) RequestID() string { + return s.RespMetadata.RequestID +} + +// The function was able to make a network connection to the configured file +// system, but the mount operation timed out. +type EFSMountTimeoutException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + Type *string `type:"string"` +} + +// String returns the string representation +func (s EFSMountTimeoutException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EFSMountTimeoutException) GoString() string { + return s.String() +} + +func newErrorEFSMountTimeoutException(v protocol.ResponseMetadata) error { + return &EFSMountTimeoutException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *EFSMountTimeoutException) Code() string { + return "EFSMountTimeoutException" +} + +// Message returns the exception's message. +func (s *EFSMountTimeoutException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *EFSMountTimeoutException) OrigErr() error { + return nil +} + +func (s *EFSMountTimeoutException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *EFSMountTimeoutException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *EFSMountTimeoutException) RequestID() string { + return s.RespMetadata.RequestID +} + // AWS Lambda was not able to create an elastic network interface in the VPC, // specified as part of Lambda function configuration, because the limit for // network interfaces has been reached. @@ -7284,7 +7575,7 @@ type EventSourceMappingConfiguration struct { // (Streams) The maximum age of a record that Lambda sends to a function for // processing. - MaximumRecordAgeInSeconds *int64 `min:"60" type:"integer"` + MaximumRecordAgeInSeconds *int64 `type:"integer"` // (Streams) The maximum number of times to retry when the function returns // an error. @@ -7301,6 +7592,9 @@ type EventSourceMappingConfiguration struct { // a user, or by the Lambda service. StateTransitionReason *string `type:"string"` + // (MSK) The name of the Kafka topic. + Topics []*string `min:"1" type:"list"` + // The identifier of the event source mapping. UUID *string `type:"string"` } @@ -7393,12 +7687,73 @@ func (s *EventSourceMappingConfiguration) SetStateTransitionReason(v string) *Ev return s } +// SetTopics sets the Topics field's value. +func (s *EventSourceMappingConfiguration) SetTopics(v []*string) *EventSourceMappingConfiguration { + s.Topics = v + return s +} + // SetUUID sets the UUID field's value. func (s *EventSourceMappingConfiguration) SetUUID(v string) *EventSourceMappingConfiguration { s.UUID = &v return s } +// Details about the connection between a Lambda function and an Amazon EFS +// file system. +type FileSystemConfig struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the Amazon EFS access point that provides + // access to the file system. + // + // Arn is a required field + Arn *string `type:"string" required:"true"` + + // The path where the function can access the file system, starting with /mnt/. + // + // LocalMountPath is a required field + LocalMountPath *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s FileSystemConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FileSystemConfig) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *FileSystemConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "FileSystemConfig"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.LocalMountPath == nil { + invalidParams.Add(request.NewErrParamRequired("LocalMountPath")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *FileSystemConfig) SetArn(v string) *FileSystemConfig { + s.Arn = &v + return s +} + +// SetLocalMountPath sets the LocalMountPath field's value. +func (s *FileSystemConfig) SetLocalMountPath(v string) *FileSystemConfig { + s.LocalMountPath = &v + return s +} + // The code for the Lambda function. You can specify either an object in Amazon // S3, or upload a deployment package directly. type FunctionCode struct { @@ -7526,6 +7881,9 @@ type FunctionConfiguration struct { // The function's environment variables. Environment *EnvironmentResponse `type:"structure"` + // Connection settings for an Amazon EFS file system. + FileSystemConfigs []*FileSystemConfig `type:"list"` + // The function's Amazon Resource Name (ARN). FunctionArn *string `type:"string"` @@ -7636,6 +7994,12 @@ func (s *FunctionConfiguration) SetEnvironment(v *EnvironmentResponse) *Function return s } +// SetFileSystemConfigs sets the FileSystemConfigs field's value. +func (s *FunctionConfiguration) SetFileSystemConfigs(v []*FileSystemConfig) *FunctionConfiguration { + s.FileSystemConfigs = v + return s +} + // SetFunctionArn sets the FunctionArn field's value. func (s *FunctionConfiguration) SetFunctionArn(v string) *FunctionConfiguration { s.FunctionArn = &v @@ -10219,6 +10583,8 @@ type ListEventSourceMappingsInput struct { // * Amazon DynamoDB Streams - The ARN of the stream. // // * Amazon Simple Queue Service - The ARN of the queue. + // + // * Amazon Managed Streaming for Apache Kafka - The ARN of the cluster. EventSourceArn *string `location:"querystring" locationName:"EventSourceArn" type:"string"` // The name of the Lambda function. @@ -12954,7 +13320,7 @@ type UpdateAliasInput struct { // read it. RevisionId *string `type:"string"` - // The routing configuration (https://docs.aws.amazon.com/lambda/latest/dg/lambda-traffic-shifting-using-aliases.html) + // The routing configuration (https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html#configuring-alias-routing) // of the alias. RoutingConfig *AliasRoutingConfiguration `type:"structure"` } @@ -13040,6 +13406,8 @@ type UpdateEventSourceMappingInput struct { // * Amazon DynamoDB Streams - Default 100. Max 1,000. // // * Amazon Simple Queue Service - Default 10. Max 10. + // + // * Amazon Managed Streaming for Apache Kafka - Default 100. Max 10,000. BatchSize *int64 `min:"1" type:"integer"` // (Streams) If the function returns an error, split the batch in two and retry. @@ -13049,7 +13417,8 @@ type UpdateEventSourceMappingInput struct { // records. DestinationConfig *DestinationConfig `type:"structure"` - // Disables the event source mapping to pause polling and invocation. + // If true, the event source mapping is active. Set to false to pause polling + // and invocation. Enabled *bool `type:"boolean"` // The name of the Lambda function. @@ -13072,12 +13441,13 @@ type UpdateEventSourceMappingInput struct { // function, in seconds. MaximumBatchingWindowInSeconds *int64 `type:"integer"` - // (Streams) The maximum age of a record that Lambda sends to a function for - // processing. - MaximumRecordAgeInSeconds *int64 `min:"60" type:"integer"` + // (Streams) Discard records older than the specified age. The default value + // is infinite (-1). + MaximumRecordAgeInSeconds *int64 `type:"integer"` - // (Streams) The maximum number of times to retry when the function returns - // an error. + // (Streams) Discard records after the specified number of retries. The default + // value is infinite (-1). When set to infinite (-1), failed records will be + // retried until the record expires. MaximumRetryAttempts *int64 `type:"integer"` // (Streams) The number of batches to process from each shard concurrently. @@ -13108,8 +13478,11 @@ func (s *UpdateEventSourceMappingInput) Validate() error { if s.FunctionName != nil && len(*s.FunctionName) < 1 { invalidParams.Add(request.NewErrParamMinLen("FunctionName", 1)) } - if s.MaximumRecordAgeInSeconds != nil && *s.MaximumRecordAgeInSeconds < 60 { - invalidParams.Add(request.NewErrParamMinValue("MaximumRecordAgeInSeconds", 60)) + if s.MaximumRecordAgeInSeconds != nil && *s.MaximumRecordAgeInSeconds < -1 { + invalidParams.Add(request.NewErrParamMinValue("MaximumRecordAgeInSeconds", -1)) + } + if s.MaximumRetryAttempts != nil && *s.MaximumRetryAttempts < -1 { + invalidParams.Add(request.NewErrParamMinValue("MaximumRetryAttempts", -1)) } if s.ParallelizationFactor != nil && *s.ParallelizationFactor < 1 { invalidParams.Add(request.NewErrParamMinValue("ParallelizationFactor", 1)) @@ -13333,6 +13706,9 @@ type UpdateFunctionConfigurationInput struct { // Environment variables that are accessible from function code during execution. Environment *Environment `type:"structure"` + // Connection settings for an Amazon EFS file system. + FileSystemConfigs []*FileSystemConfig `type:"list"` + // The name of the Lambda function. // // Name formats @@ -13421,6 +13797,16 @@ func (s *UpdateFunctionConfigurationInput) Validate() error { if s.Timeout != nil && *s.Timeout < 1 { invalidParams.Add(request.NewErrParamMinValue("Timeout", 1)) } + if s.FileSystemConfigs != nil { + for i, v := range s.FileSystemConfigs { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "FileSystemConfigs", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -13446,6 +13832,12 @@ func (s *UpdateFunctionConfigurationInput) SetEnvironment(v *Environment) *Updat return s } +// SetFileSystemConfigs sets the FileSystemConfigs field's value. +func (s *UpdateFunctionConfigurationInput) SetFileSystemConfigs(v []*FileSystemConfig) *UpdateFunctionConfigurationInput { + s.FileSystemConfigs = v + return s +} + // SetFunctionName sets the FunctionName field's value. func (s *UpdateFunctionConfigurationInput) SetFunctionName(v string) *UpdateFunctionConfigurationInput { s.FunctionName = &v @@ -13773,11 +14165,27 @@ const ( EventSourcePositionAtTimestamp = "AT_TIMESTAMP" ) +// EventSourcePosition_Values returns all elements of the EventSourcePosition enum +func EventSourcePosition_Values() []string { + return []string{ + EventSourcePositionTrimHorizon, + EventSourcePositionLatest, + EventSourcePositionAtTimestamp, + } +} + const ( // FunctionVersionAll is a FunctionVersion enum value FunctionVersionAll = "ALL" ) +// FunctionVersion_Values returns all elements of the FunctionVersion enum +func FunctionVersion_Values() []string { + return []string{ + FunctionVersionAll, + } +} + const ( // InvocationTypeEvent is a InvocationType enum value InvocationTypeEvent = "Event" @@ -13789,6 +14197,15 @@ const ( InvocationTypeDryRun = "DryRun" ) +// InvocationType_Values returns all elements of the InvocationType enum +func InvocationType_Values() []string { + return []string{ + InvocationTypeEvent, + InvocationTypeRequestResponse, + InvocationTypeDryRun, + } +} + const ( // LastUpdateStatusSuccessful is a LastUpdateStatus enum value LastUpdateStatusSuccessful = "Successful" @@ -13800,6 +14217,15 @@ const ( LastUpdateStatusInProgress = "InProgress" ) +// LastUpdateStatus_Values returns all elements of the LastUpdateStatus enum +func LastUpdateStatus_Values() []string { + return []string{ + LastUpdateStatusSuccessful, + LastUpdateStatusFailed, + LastUpdateStatusInProgress, + } +} + const ( // LastUpdateStatusReasonCodeEniLimitExceeded is a LastUpdateStatusReasonCode enum value LastUpdateStatusReasonCodeEniLimitExceeded = "EniLimitExceeded" @@ -13823,6 +14249,19 @@ const ( LastUpdateStatusReasonCodeInvalidSecurityGroup = "InvalidSecurityGroup" ) +// LastUpdateStatusReasonCode_Values returns all elements of the LastUpdateStatusReasonCode enum +func LastUpdateStatusReasonCode_Values() []string { + return []string{ + LastUpdateStatusReasonCodeEniLimitExceeded, + LastUpdateStatusReasonCodeInsufficientRolePermissions, + LastUpdateStatusReasonCodeInvalidConfiguration, + LastUpdateStatusReasonCodeInternalError, + LastUpdateStatusReasonCodeSubnetOutOfIpaddresses, + LastUpdateStatusReasonCodeInvalidSubnet, + LastUpdateStatusReasonCodeInvalidSecurityGroup, + } +} + const ( // LogTypeNone is a LogType enum value LogTypeNone = "None" @@ -13831,6 +14270,14 @@ const ( LogTypeTail = "Tail" ) +// LogType_Values returns all elements of the LogType enum +func LogType_Values() []string { + return []string{ + LogTypeNone, + LogTypeTail, + } +} + const ( // ProvisionedConcurrencyStatusEnumInProgress is a ProvisionedConcurrencyStatusEnum enum value ProvisionedConcurrencyStatusEnumInProgress = "IN_PROGRESS" @@ -13842,6 +14289,15 @@ const ( ProvisionedConcurrencyStatusEnumFailed = "FAILED" ) +// ProvisionedConcurrencyStatusEnum_Values returns all elements of the ProvisionedConcurrencyStatusEnum enum +func ProvisionedConcurrencyStatusEnum_Values() []string { + return []string{ + ProvisionedConcurrencyStatusEnumInProgress, + ProvisionedConcurrencyStatusEnumReady, + ProvisionedConcurrencyStatusEnumFailed, + } +} + const ( // RuntimeNodejs is a Runtime enum value RuntimeNodejs = "nodejs" @@ -13864,6 +14320,9 @@ const ( // RuntimeJava8 is a Runtime enum value RuntimeJava8 = "java8" + // RuntimeJava8Al2 is a Runtime enum value + RuntimeJava8Al2 = "java8.al2" + // RuntimeJava11 is a Runtime enum value RuntimeJava11 = "java11" @@ -13905,8 +14364,40 @@ const ( // RuntimeProvided is a Runtime enum value RuntimeProvided = "provided" + + // RuntimeProvidedAl2 is a Runtime enum value + RuntimeProvidedAl2 = "provided.al2" ) +// Runtime_Values returns all elements of the Runtime enum +func Runtime_Values() []string { + return []string{ + RuntimeNodejs, + RuntimeNodejs43, + RuntimeNodejs610, + RuntimeNodejs810, + RuntimeNodejs10X, + RuntimeNodejs12X, + RuntimeJava8, + RuntimeJava8Al2, + RuntimeJava11, + RuntimePython27, + RuntimePython36, + RuntimePython37, + RuntimePython38, + RuntimeDotnetcore10, + RuntimeDotnetcore20, + RuntimeDotnetcore21, + RuntimeDotnetcore31, + RuntimeNodejs43Edge, + RuntimeGo1X, + RuntimeRuby25, + RuntimeRuby27, + RuntimeProvided, + RuntimeProvidedAl2, + } +} + const ( // StatePending is a State enum value StatePending = "Pending" @@ -13921,6 +14412,16 @@ const ( StateFailed = "Failed" ) +// State_Values returns all elements of the State enum +func State_Values() []string { + return []string{ + StatePending, + StateActive, + StateInactive, + StateFailed, + } +} + const ( // StateReasonCodeIdle is a StateReasonCode enum value StateReasonCodeIdle = "Idle" @@ -13953,6 +14454,22 @@ const ( StateReasonCodeInvalidSecurityGroup = "InvalidSecurityGroup" ) +// StateReasonCode_Values returns all elements of the StateReasonCode enum +func StateReasonCode_Values() []string { + return []string{ + StateReasonCodeIdle, + StateReasonCodeCreating, + StateReasonCodeRestoring, + StateReasonCodeEniLimitExceeded, + StateReasonCodeInsufficientRolePermissions, + StateReasonCodeInvalidConfiguration, + StateReasonCodeInternalError, + StateReasonCodeSubnetOutOfIpaddresses, + StateReasonCodeInvalidSubnet, + StateReasonCodeInvalidSecurityGroup, + } +} + const ( // ThrottleReasonConcurrentInvocationLimitExceeded is a ThrottleReason enum value ThrottleReasonConcurrentInvocationLimitExceeded = "ConcurrentInvocationLimitExceeded" @@ -13970,6 +14487,17 @@ const ( ThrottleReasonCallerRateLimitExceeded = "CallerRateLimitExceeded" ) +// ThrottleReason_Values returns all elements of the ThrottleReason enum +func ThrottleReason_Values() []string { + return []string{ + ThrottleReasonConcurrentInvocationLimitExceeded, + ThrottleReasonFunctionInvocationRateLimitExceeded, + ThrottleReasonReservedFunctionConcurrentInvocationLimitExceeded, + ThrottleReasonReservedFunctionInvocationRateLimitExceeded, + ThrottleReasonCallerRateLimitExceeded, + } +} + const ( // TracingModeActive is a TracingMode enum value TracingModeActive = "Active" @@ -13977,3 +14505,11 @@ const ( // TracingModePassThrough is a TracingMode enum value TracingModePassThrough = "PassThrough" ) + +// TracingMode_Values returns all elements of the TracingMode enum +func TracingMode_Values() []string { + return []string{ + TracingModeActive, + TracingModePassThrough, + } +} 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 739daeca0a5..4cee20127ed 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 @@ -34,6 +34,32 @@ const ( // the Lambda function. ErrCodeEC2UnexpectedException = "EC2UnexpectedException" + // ErrCodeEFSIOException for service response error code + // "EFSIOException". + // + // An error occured when reading from or writing to a connected file system. + ErrCodeEFSIOException = "EFSIOException" + + // ErrCodeEFSMountConnectivityException for service response error code + // "EFSMountConnectivityException". + // + // The function couldn't make a network connection to the configured file system. + ErrCodeEFSMountConnectivityException = "EFSMountConnectivityException" + + // ErrCodeEFSMountFailureException for service response error code + // "EFSMountFailureException". + // + // The function couldn't mount the configured file system due to a permission + // or configuration issue. + ErrCodeEFSMountFailureException = "EFSMountFailureException" + + // ErrCodeEFSMountTimeoutException for service response error code + // "EFSMountTimeoutException". + // + // The function was able to make a network connection to the configured file + // system, but the mount operation timed out. + ErrCodeEFSMountTimeoutException = "EFSMountTimeoutException" + // ErrCodeENILimitReachedException for service response error code // "ENILimitReachedException". // @@ -192,6 +218,10 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "EC2AccessDeniedException": newErrorEC2AccessDeniedException, "EC2ThrottledException": newErrorEC2ThrottledException, "EC2UnexpectedException": newErrorEC2UnexpectedException, + "EFSIOException": newErrorEFSIOException, + "EFSMountConnectivityException": newErrorEFSMountConnectivityException, + "EFSMountFailureException": newErrorEFSMountFailureException, + "EFSMountTimeoutException": newErrorEFSMountTimeoutException, "ENILimitReachedException": newErrorENILimitReachedException, "InvalidParameterValueException": newErrorInvalidParameterValueException, "InvalidRequestContentException": newErrorInvalidRequestContentException, diff --git a/vendor/github.com/aws/aws-sdk-go/service/lexmodelbuildingservice/api.go b/vendor/github.com/aws/aws-sdk-go/service/lexmodelbuildingservice/api.go index 5f334ee6141..6ccc81bf6bf 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/lexmodelbuildingservice/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/lexmodelbuildingservice/api.go @@ -5288,6 +5288,11 @@ type CreateBotVersionOutput struct { // Comprehend for sentiment analysis. DetectSentiment *bool `locationName:"detectSentiment" type:"boolean"` + // Indicates whether the bot uses the new natural language understanding (NLU) + // model or the original NLU. True indicates that the bot is using the new model, + // otherwise, false. + EnableModelImprovements *bool `locationName:"enableModelImprovements" type:"boolean"` + // If status is FAILED, Amazon Lex provides the reason that it failed to build // the bot. FailureReason *string `locationName:"failureReason" type:"string"` @@ -5374,6 +5379,12 @@ func (s *CreateBotVersionOutput) SetDetectSentiment(v bool) *CreateBotVersionOut return s } +// SetEnableModelImprovements sets the EnableModelImprovements field's value. +func (s *CreateBotVersionOutput) SetEnableModelImprovements(v bool) *CreateBotVersionOutput { + s.EnableModelImprovements = &v + return s +} + // SetFailureReason sets the FailureReason field's value. func (s *CreateBotVersionOutput) SetFailureReason(v string) *CreateBotVersionOutput { s.FailureReason = &v @@ -5513,6 +5524,10 @@ type CreateIntentVersionOutput struct { // Describes how the intent is fulfilled. FulfillmentActivity *FulfillmentActivity `locationName:"fulfillmentActivity" type:"structure"` + // Configuration information, if any, for connectin an Amazon Kendra index with + // the AMAZON.KendraSearchIntent intent. + KendraConfiguration *KendraConfiguration `locationName:"kendraConfiguration" type:"structure"` + // The date that the intent was updated. LastUpdatedDate *time.Time `locationName:"lastUpdatedDate" type:"timestamp"` @@ -5595,6 +5610,12 @@ func (s *CreateIntentVersionOutput) SetFulfillmentActivity(v *FulfillmentActivit return s } +// SetKendraConfiguration sets the KendraConfiguration field's value. +func (s *CreateIntentVersionOutput) SetKendraConfiguration(v *KendraConfiguration) *CreateIntentVersionOutput { + s.KendraConfiguration = v + return s +} + // SetLastUpdatedDate sets the LastUpdatedDate field's value. func (s *CreateIntentVersionOutput) SetLastUpdatedDate(v time.Time) *CreateIntentVersionOutput { s.LastUpdatedDate = &v @@ -7304,6 +7325,11 @@ type GetBotOutput struct { // sentiment analysis. DetectSentiment *bool `locationName:"detectSentiment" type:"boolean"` + // Indicates whether the bot uses the new natural language understanding (NLU) + // model or the original NLU. True indicates that the bot is using the new model, + // otherwise, false. + EnableModelImprovements *bool `locationName:"enableModelImprovements" type:"boolean"` + // If status is FAILED, Amazon Lex explains why it failed to build the bot. FailureReason *string `locationName:"failureReason" type:"string"` @@ -7324,6 +7350,14 @@ type GetBotOutput struct { // The name of the bot. Name *string `locationName:"name" min:"2" type:"string"` + // The score that determines where Amazon Lex inserts the AMAZON.FallbackIntent, + // AMAZON.KendraSearchIntent, or both when returning alternative intents in + // a PostContent (https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostContent.html) + // or PostText (https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostText.html) + // response. AMAZON.FallbackIntent and AMAZON.KendraSearchIntent are only inserted + // if they are configured for the bot. + NluIntentConfidenceThreshold *float64 `locationName:"nluIntentConfidenceThreshold" type:"double"` + // The status of the bot. // // When the status is BUILDING Amazon Lex is building the bot for testing and @@ -7399,6 +7433,12 @@ func (s *GetBotOutput) SetDetectSentiment(v bool) *GetBotOutput { return s } +// SetEnableModelImprovements sets the EnableModelImprovements field's value. +func (s *GetBotOutput) SetEnableModelImprovements(v bool) *GetBotOutput { + s.EnableModelImprovements = &v + return s +} + // SetFailureReason sets the FailureReason field's value. func (s *GetBotOutput) SetFailureReason(v string) *GetBotOutput { s.FailureReason = &v @@ -7435,6 +7475,12 @@ func (s *GetBotOutput) SetName(v string) *GetBotOutput { return s } +// SetNluIntentConfidenceThreshold sets the NluIntentConfidenceThreshold field's value. +func (s *GetBotOutput) SetNluIntentConfidenceThreshold(v float64) *GetBotOutput { + s.NluIntentConfidenceThreshold = &v + return s +} + // SetStatus sets the Status field's value. func (s *GetBotOutput) SetStatus(v string) *GetBotOutput { s.Status = &v @@ -8325,6 +8371,10 @@ type GetIntentOutput struct { // Describes how the intent is fulfilled. For more information, see PutIntent. FulfillmentActivity *FulfillmentActivity `locationName:"fulfillmentActivity" type:"structure"` + // Configuration information, if any, to connect to an Amazon Kendra index with + // the AMAZON.KendraSearchIntent intent. + KendraConfiguration *KendraConfiguration `locationName:"kendraConfiguration" type:"structure"` + // The date that the intent was updated. When you create a resource, the creation // date and the last updated date are the same. LastUpdatedDate *time.Time `locationName:"lastUpdatedDate" type:"timestamp"` @@ -8407,6 +8457,12 @@ func (s *GetIntentOutput) SetFulfillmentActivity(v *FulfillmentActivity) *GetInt return s } +// SetKendraConfiguration sets the KendraConfiguration field's value. +func (s *GetIntentOutput) SetKendraConfiguration(v *KendraConfiguration) *GetIntentOutput { + s.KendraConfiguration = v + return s +} + // SetLastUpdatedDate sets the LastUpdatedDate field's value. func (s *GetIntentOutput) SetLastUpdatedDate(v time.Time) *GetIntentOutput { s.LastUpdatedDate = &v @@ -9296,6 +9352,87 @@ func (s *InternalFailureException) RequestID() string { return s.RespMetadata.RequestID } +// Provides configuration information for the AMAZON.KendraSearchIntent intent. +// When you use this intent, Amazon Lex searches the specified Amazon Kendra +// index and returns documents from the index that match the user's utterance. +// For more information, see AMAZON.KendraSearchIntent (http://docs.aws.amazon.com/lex/latest/dg/built-in-intent-kendra-search.html). +type KendraConfiguration struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the Amazon Kendra index that you want the + // AMAZON.KendraSearchIntent intent to search. The index must be in the same + // account and Region as the Amazon Lex bot. If the Amazon Kendra index does + // not exist, you get an exception when you call the PutIntent operation. + // + // KendraIndex is a required field + KendraIndex *string `locationName:"kendraIndex" min:"20" type:"string" required:"true"` + + // A query filter that Amazon Lex sends to Amazon Kendra to filter the response + // from the query. The filter is in the format defined by Amazon Kendra. For + // more information, see Filtering queries (http://docs.aws.amazon.com/kendra/latest/dg/filtering.html). + // + // You can override this filter string with a new filter string at runtime. + QueryFilterString *string `locationName:"queryFilterString" type:"string"` + + // The Amazon Resource Name (ARN) of an IAM role that has permission to search + // the Amazon Kendra index. The role must be in the same account and Region + // as the Amazon Lex bot. If the role does not exist, you get an exception when + // you call the PutIntent operation. + // + // Role is a required field + Role *string `locationName:"role" min:"20" type:"string" required:"true"` +} + +// String returns the string representation +func (s KendraConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s KendraConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *KendraConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "KendraConfiguration"} + if s.KendraIndex == nil { + invalidParams.Add(request.NewErrParamRequired("KendraIndex")) + } + if s.KendraIndex != nil && len(*s.KendraIndex) < 20 { + invalidParams.Add(request.NewErrParamMinLen("KendraIndex", 20)) + } + if s.Role == nil { + invalidParams.Add(request.NewErrParamRequired("Role")) + } + if s.Role != nil && len(*s.Role) < 20 { + invalidParams.Add(request.NewErrParamMinLen("Role", 20)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKendraIndex sets the KendraIndex field's value. +func (s *KendraConfiguration) SetKendraIndex(v string) *KendraConfiguration { + s.KendraIndex = &v + return s +} + +// SetQueryFilterString sets the QueryFilterString field's value. +func (s *KendraConfiguration) SetQueryFilterString(v string) *KendraConfiguration { + s.QueryFilterString = &v + return s +} + +// SetRole sets the Role field's value. +func (s *KendraConfiguration) SetRole(v string) *KendraConfiguration { + s.Role = &v + return s +} + // The request exceeded a limit. Try your request again. type LimitExceededException struct { _ struct{} `type:"structure"` @@ -10180,6 +10317,43 @@ type PutBotInput struct { // analysis. If you don't specify detectSentiment, the default is false. DetectSentiment *bool `locationName:"detectSentiment" type:"boolean"` + // Set to true to enable the use of a new natural language understanding (NLU) + // model. Using the new NLU may improve the performance of your bot. + // + // When you set the enableModelImprovements parameter to true you can use the + // nluIntentConfidenceThreshold parameter to configure confidence scores. For + // more information, see Confidence Scores (https://docs.aws.amazon.com/lex/latest/dg/confidence-scores.html). + // + // You can only set the enableModelImprovements parameter in certain Regions. + // If you set the parameter to true, your bot will use the new NLU. If you set + // the parameter to false, your bot will continue to use the original NLU. If + // you set the parameter to false after setting it to true, your bot will return + // to the original NLU. + // + // The Regions where you can set the enableModelImprovements parameter to true + // are: + // + // * US East (N. Virginia) (us-east-1) + // + // * US West (Oregon) (us-west-2) + // + // * Asia Pacific (Sydney) (ap-southeast-2) + // + // * EU (Ireland) (eu-west-1) + // + // In other Regions, the enableModelImprovements parameter is set to true by + // default. In these Regions setting the parameter to false throws a ValidationException + // exception. + // + // * Asia Pacific (Singapore) (ap-southeast-1) + // + // * Asia Pacific (Tokyo) (ap-northeast-1) + // + // * EU (Frankfurt) (eu-central-1) + // + // * EU (London) (eu-west-2) + EnableModelImprovements *bool `locationName:"enableModelImprovements" type:"boolean"` + // The maximum time in seconds that Amazon Lex retains the data gathered in // a conversation. // @@ -10217,6 +10391,30 @@ type PutBotInput struct { // Name is a required field Name *string `location:"uri" locationName:"name" min:"2" type:"string" required:"true"` + // Determines the threshold where Amazon Lex will insert the AMAZON.FallbackIntent, + // AMAZON.KendraSearchIntent, or both when returning alternative intents in + // a PostContent (https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostContent.html) + // or PostText (https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostText.html) + // response. AMAZON.FallbackIntent and AMAZON.KendraSearchIntent are only inserted + // if they are configured for the bot. + // + // You must set the enableModelImprovements parameter to true to use confidence + // scores. + // + // For example, suppose a bot is configured with the confidence threshold of + // 0.80 and the AMAZON.FallbackIntent. Amazon Lex returns three alternative + // intents with the following confidence scores: IntentA (0.70), IntentB (0.60), + // IntentC (0.50). The response from the PostText operation would be: + // + // * AMAZON.FallbackIntent + // + // * IntentA + // + // * IntentB + // + // * IntentC + NluIntentConfidenceThreshold *float64 `locationName:"nluIntentConfidenceThreshold" type:"double"` + // If you set the processBehavior element to BUILD, Amazon Lex builds the bot // so that it can be run. If you set the element to SAVE Amazon Lex saves the // bot, but doesn't build it. @@ -10343,6 +10541,12 @@ func (s *PutBotInput) SetDetectSentiment(v bool) *PutBotInput { return s } +// SetEnableModelImprovements sets the EnableModelImprovements field's value. +func (s *PutBotInput) SetEnableModelImprovements(v bool) *PutBotInput { + s.EnableModelImprovements = &v + return s +} + // SetIdleSessionTTLInSeconds sets the IdleSessionTTLInSeconds field's value. func (s *PutBotInput) SetIdleSessionTTLInSeconds(v int64) *PutBotInput { s.IdleSessionTTLInSeconds = &v @@ -10367,6 +10571,12 @@ func (s *PutBotInput) SetName(v string) *PutBotInput { return s } +// SetNluIntentConfidenceThreshold sets the NluIntentConfidenceThreshold field's value. +func (s *PutBotInput) SetNluIntentConfidenceThreshold(v float64) *PutBotInput { + s.NluIntentConfidenceThreshold = &v + return s +} + // SetProcessBehavior sets the ProcessBehavior field's value. func (s *PutBotInput) SetProcessBehavior(v string) *PutBotInput { s.ProcessBehavior = &v @@ -10440,6 +10650,11 @@ type PutBotOutput struct { // the request, the detectSentiment field is false in the response. DetectSentiment *bool `locationName:"detectSentiment" type:"boolean"` + // Indicates whether the bot uses the new natural language understanding (NLU) + // model or the original NLU. True indicates that the bot is using the new model, + // otherwise, false. + EnableModelImprovements *bool `locationName:"enableModelImprovements" type:"boolean"` + // If status is FAILED, Amazon Lex provides the reason that it failed to build // the bot. FailureReason *string `locationName:"failureReason" type:"string"` @@ -10461,6 +10676,14 @@ type PutBotOutput struct { // The name of the bot. Name *string `locationName:"name" min:"2" type:"string"` + // The score that determines where Amazon Lex inserts the AMAZON.FallbackIntent, + // AMAZON.KendraSearchIntent, or both when returning alternative intents in + // a PostContent (https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostContent.html) + // or PostText (https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostText.html) + // response. AMAZON.FallbackIntent and AMAZON.KendraSearchIntent are only inserted + // if they are configured for the bot. + NluIntentConfidenceThreshold *float64 `locationName:"nluIntentConfidenceThreshold" type:"double"` + // When you send a request to create a bot with processBehavior set to BUILD, // Amazon Lex sets the status response element to BUILDING. // @@ -10546,6 +10769,12 @@ func (s *PutBotOutput) SetDetectSentiment(v bool) *PutBotOutput { return s } +// SetEnableModelImprovements sets the EnableModelImprovements field's value. +func (s *PutBotOutput) SetEnableModelImprovements(v bool) *PutBotOutput { + s.EnableModelImprovements = &v + return s +} + // SetFailureReason sets the FailureReason field's value. func (s *PutBotOutput) SetFailureReason(v string) *PutBotOutput { s.FailureReason = &v @@ -10582,6 +10811,12 @@ func (s *PutBotOutput) SetName(v string) *PutBotOutput { return s } +// SetNluIntentConfidenceThreshold sets the NluIntentConfidenceThreshold field's value. +func (s *PutBotOutput) SetNluIntentConfidenceThreshold(v float64) *PutBotOutput { + s.NluIntentConfidenceThreshold = &v + return s +} + // SetStatus sets the Status field's value. func (s *PutBotOutput) SetStatus(v string) *PutBotOutput { s.Status = &v @@ -10693,6 +10928,11 @@ type PutIntentInput struct { // process the intent (for example, place an order with a pizzeria). FulfillmentActivity *FulfillmentActivity `locationName:"fulfillmentActivity" type:"structure"` + // Configuration information required to use the AMAZON.KendraSearchIntent intent + // to connect to an Amazon Kendra index. For more information, see AMAZON.KendraSearchIntent + // (http://docs.aws.amazon.com/lex/latest/dg/built-in-intent-kendra-search.html). + KendraConfiguration *KendraConfiguration `locationName:"kendraConfiguration" type:"structure"` + // The name of the intent. The name is not case sensitive. // // The name can't match a built-in intent name, or a built-in intent name with @@ -10774,6 +11014,11 @@ func (s *PutIntentInput) Validate() error { invalidParams.AddNested("FulfillmentActivity", err.(request.ErrInvalidParams)) } } + if s.KendraConfiguration != nil { + if err := s.KendraConfiguration.Validate(); err != nil { + invalidParams.AddNested("KendraConfiguration", err.(request.ErrInvalidParams)) + } + } if s.RejectionStatement != nil { if err := s.RejectionStatement.Validate(); err != nil { invalidParams.AddNested("RejectionStatement", err.(request.ErrInvalidParams)) @@ -10844,6 +11089,12 @@ func (s *PutIntentInput) SetFulfillmentActivity(v *FulfillmentActivity) *PutInte return s } +// SetKendraConfiguration sets the KendraConfiguration field's value. +func (s *PutIntentInput) SetKendraConfiguration(v *KendraConfiguration) *PutIntentInput { + s.KendraConfiguration = v + return s +} + // SetName sets the Name field's value. func (s *PutIntentInput) SetName(v string) *PutIntentInput { s.Name = &v @@ -10912,6 +11163,10 @@ type PutIntentOutput struct { // intent. FulfillmentActivity *FulfillmentActivity `locationName:"fulfillmentActivity" type:"structure"` + // Configuration information, if any, required to connect to an Amazon Kendra + // index and use the AMAZON.KendraSearchIntent intent. + KendraConfiguration *KendraConfiguration `locationName:"kendraConfiguration" type:"structure"` + // The date that the intent was updated. When you create a resource, the creation // date and last update dates are the same. LastUpdatedDate *time.Time `locationName:"lastUpdatedDate" type:"timestamp"` @@ -11000,6 +11255,12 @@ func (s *PutIntentOutput) SetFulfillmentActivity(v *FulfillmentActivity) *PutInt return s } +// SetKendraConfiguration sets the KendraConfiguration field's value. +func (s *PutIntentOutput) SetKendraConfiguration(v *KendraConfiguration) *PutIntentOutput { + s.KendraConfiguration = v + return s +} + // SetLastUpdatedDate sets the LastUpdatedDate field's value. func (s *PutIntentOutput) SetLastUpdatedDate(v time.Time) *PutIntentOutput { s.LastUpdatedDate = &v @@ -11459,12 +11720,12 @@ type Slot struct { // (https://docs.aws.amazon.com/lex/latest/dg/how-obfuscate.html). ObfuscationSetting *string `locationName:"obfuscationSetting" type:"string" enum:"ObfuscationSetting"` - // Directs Lex the order in which to elicit this slot value from the user. For - // example, if the intent has two slots with priorities 1 and 2, AWS Lex first - // elicits a value for the slot with priority 1. + // Directs Amazon Lex the order in which to elicit this slot value from the + // user. For example, if the intent has two slots with priorities 1 and 2, AWS + // Amazon Lex first elicits a value for the slot with priority 1. // - // If multiple slots share the same priority, the order in which Lex elicits - // values is arbitrary. + // If multiple slots share the same priority, the order in which Amazon Lex + // elicits values is arbitrary. Priority *int64 `locationName:"priority" type:"integer"` // A set of possible responses for the slot type used by text-based clients. @@ -12322,6 +12583,15 @@ const ( ChannelStatusFailed = "FAILED" ) +// ChannelStatus_Values returns all elements of the ChannelStatus enum +func ChannelStatus_Values() []string { + return []string{ + ChannelStatusInProgress, + ChannelStatusCreated, + ChannelStatusFailed, + } +} + const ( // ChannelTypeFacebook is a ChannelType enum value ChannelTypeFacebook = "Facebook" @@ -12336,6 +12606,16 @@ const ( ChannelTypeKik = "Kik" ) +// ChannelType_Values returns all elements of the ChannelType enum +func ChannelType_Values() []string { + return []string{ + ChannelTypeFacebook, + ChannelTypeSlack, + ChannelTypeTwilioSms, + ChannelTypeKik, + } +} + const ( // ContentTypePlainText is a ContentType enum value ContentTypePlainText = "PlainText" @@ -12347,6 +12627,15 @@ const ( ContentTypeCustomPayload = "CustomPayload" ) +// ContentType_Values returns all elements of the ContentType enum +func ContentType_Values() []string { + return []string{ + ContentTypePlainText, + ContentTypeSsml, + ContentTypeCustomPayload, + } +} + const ( // DestinationCloudwatchLogs is a Destination enum value DestinationCloudwatchLogs = "CLOUDWATCH_LOGS" @@ -12355,6 +12644,14 @@ const ( DestinationS3 = "S3" ) +// Destination_Values returns all elements of the Destination enum +func Destination_Values() []string { + return []string{ + DestinationCloudwatchLogs, + DestinationS3, + } +} + const ( // ExportStatusInProgress is a ExportStatus enum value ExportStatusInProgress = "IN_PROGRESS" @@ -12366,6 +12663,15 @@ const ( ExportStatusFailed = "FAILED" ) +// ExportStatus_Values returns all elements of the ExportStatus enum +func ExportStatus_Values() []string { + return []string{ + ExportStatusInProgress, + ExportStatusReady, + ExportStatusFailed, + } +} + const ( // ExportTypeAlexaSkillsKit is a ExportType enum value ExportTypeAlexaSkillsKit = "ALEXA_SKILLS_KIT" @@ -12374,6 +12680,14 @@ const ( ExportTypeLex = "LEX" ) +// ExportType_Values returns all elements of the ExportType enum +func ExportType_Values() []string { + return []string{ + ExportTypeAlexaSkillsKit, + ExportTypeLex, + } +} + const ( // FulfillmentActivityTypeReturnIntent is a FulfillmentActivityType enum value FulfillmentActivityTypeReturnIntent = "ReturnIntent" @@ -12382,6 +12696,14 @@ const ( FulfillmentActivityTypeCodeHook = "CodeHook" ) +// FulfillmentActivityType_Values returns all elements of the FulfillmentActivityType enum +func FulfillmentActivityType_Values() []string { + return []string{ + FulfillmentActivityTypeReturnIntent, + FulfillmentActivityTypeCodeHook, + } +} + const ( // ImportStatusInProgress is a ImportStatus enum value ImportStatusInProgress = "IN_PROGRESS" @@ -12393,6 +12715,15 @@ const ( ImportStatusFailed = "FAILED" ) +// ImportStatus_Values returns all elements of the ImportStatus enum +func ImportStatus_Values() []string { + return []string{ + ImportStatusInProgress, + ImportStatusComplete, + ImportStatusFailed, + } +} + const ( // LocaleEnUs is a Locale enum value LocaleEnUs = "en-US" @@ -12404,6 +12735,15 @@ const ( LocaleDeDe = "de-DE" ) +// Locale_Values returns all elements of the Locale enum +func Locale_Values() []string { + return []string{ + LocaleEnUs, + LocaleEnGb, + LocaleDeDe, + } +} + const ( // LogTypeAudio is a LogType enum value LogTypeAudio = "AUDIO" @@ -12412,6 +12752,14 @@ const ( LogTypeText = "TEXT" ) +// LogType_Values returns all elements of the LogType enum +func LogType_Values() []string { + return []string{ + LogTypeAudio, + LogTypeText, + } +} + const ( // MergeStrategyOverwriteLatest is a MergeStrategy enum value MergeStrategyOverwriteLatest = "OVERWRITE_LATEST" @@ -12420,6 +12768,14 @@ const ( MergeStrategyFailOnConflict = "FAIL_ON_CONFLICT" ) +// MergeStrategy_Values returns all elements of the MergeStrategy enum +func MergeStrategy_Values() []string { + return []string{ + MergeStrategyOverwriteLatest, + MergeStrategyFailOnConflict, + } +} + const ( // ObfuscationSettingNone is a ObfuscationSetting enum value ObfuscationSettingNone = "NONE" @@ -12428,6 +12784,14 @@ const ( ObfuscationSettingDefaultObfuscation = "DEFAULT_OBFUSCATION" ) +// ObfuscationSetting_Values returns all elements of the ObfuscationSetting enum +func ObfuscationSetting_Values() []string { + return []string{ + ObfuscationSettingNone, + ObfuscationSettingDefaultObfuscation, + } +} + const ( // ProcessBehaviorSave is a ProcessBehavior enum value ProcessBehaviorSave = "SAVE" @@ -12436,6 +12800,14 @@ const ( ProcessBehaviorBuild = "BUILD" ) +// ProcessBehavior_Values returns all elements of the ProcessBehavior enum +func ProcessBehavior_Values() []string { + return []string{ + ProcessBehaviorSave, + ProcessBehaviorBuild, + } +} + const ( // ReferenceTypeIntent is a ReferenceType enum value ReferenceTypeIntent = "Intent" @@ -12450,6 +12822,16 @@ const ( ReferenceTypeBotChannel = "BotChannel" ) +// ReferenceType_Values returns all elements of the ReferenceType enum +func ReferenceType_Values() []string { + return []string{ + ReferenceTypeIntent, + ReferenceTypeBot, + ReferenceTypeBotAlias, + ReferenceTypeBotChannel, + } +} + const ( // ResourceTypeBot is a ResourceType enum value ResourceTypeBot = "BOT" @@ -12461,6 +12843,15 @@ const ( ResourceTypeSlotType = "SLOT_TYPE" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeBot, + ResourceTypeIntent, + ResourceTypeSlotType, + } +} + const ( // SlotConstraintRequired is a SlotConstraint enum value SlotConstraintRequired = "Required" @@ -12469,6 +12860,14 @@ const ( SlotConstraintOptional = "Optional" ) +// SlotConstraint_Values returns all elements of the SlotConstraint enum +func SlotConstraint_Values() []string { + return []string{ + SlotConstraintRequired, + SlotConstraintOptional, + } +} + const ( // SlotValueSelectionStrategyOriginalValue is a SlotValueSelectionStrategy enum value SlotValueSelectionStrategyOriginalValue = "ORIGINAL_VALUE" @@ -12477,6 +12876,14 @@ const ( SlotValueSelectionStrategyTopResolution = "TOP_RESOLUTION" ) +// SlotValueSelectionStrategy_Values returns all elements of the SlotValueSelectionStrategy enum +func SlotValueSelectionStrategy_Values() []string { + return []string{ + SlotValueSelectionStrategyOriginalValue, + SlotValueSelectionStrategyTopResolution, + } +} + const ( // StatusBuilding is a Status enum value StatusBuilding = "BUILDING" @@ -12494,6 +12901,17 @@ const ( StatusNotBuilt = "NOT_BUILT" ) +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusBuilding, + StatusReady, + StatusReadyBasicTesting, + StatusFailed, + StatusNotBuilt, + } +} + const ( // StatusTypeDetected is a StatusType enum value StatusTypeDetected = "Detected" @@ -12501,3 +12919,11 @@ const ( // StatusTypeMissed is a StatusType enum value StatusTypeMissed = "Missed" ) + +// StatusType_Values returns all elements of the StatusType enum +func StatusType_Values() []string { + return []string{ + StatusTypeDetected, + StatusTypeMissed, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/licensemanager/api.go b/vendor/github.com/aws/aws-sdk-go/service/licensemanager/api.go index 1207a082be2..be0f32c7a10 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/licensemanager/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/licensemanager/api.go @@ -4568,6 +4568,16 @@ const ( InventoryFilterConditionContains = "CONTAINS" ) +// InventoryFilterCondition_Values returns all elements of the InventoryFilterCondition enum +func InventoryFilterCondition_Values() []string { + return []string{ + InventoryFilterConditionEquals, + InventoryFilterConditionNotEquals, + InventoryFilterConditionBeginsWith, + InventoryFilterConditionContains, + } +} + const ( // LicenseConfigurationStatusAvailable is a LicenseConfigurationStatus enum value LicenseConfigurationStatusAvailable = "AVAILABLE" @@ -4576,6 +4586,14 @@ const ( LicenseConfigurationStatusDisabled = "DISABLED" ) +// LicenseConfigurationStatus_Values returns all elements of the LicenseConfigurationStatus enum +func LicenseConfigurationStatus_Values() []string { + return []string{ + LicenseConfigurationStatusAvailable, + LicenseConfigurationStatusDisabled, + } +} + const ( // LicenseCountingTypeVCpu is a LicenseCountingType enum value LicenseCountingTypeVCpu = "vCPU" @@ -4590,6 +4608,16 @@ const ( LicenseCountingTypeSocket = "Socket" ) +// LicenseCountingType_Values returns all elements of the LicenseCountingType enum +func LicenseCountingType_Values() []string { + return []string{ + LicenseCountingTypeVCpu, + LicenseCountingTypeInstance, + LicenseCountingTypeCore, + LicenseCountingTypeSocket, + } +} + const ( // ResourceTypeEc2Instance is a ResourceType enum value ResourceTypeEc2Instance = "EC2_INSTANCE" @@ -4606,3 +4634,14 @@ const ( // ResourceTypeSystemsManagerManagedInstance is a ResourceType enum value ResourceTypeSystemsManagerManagedInstance = "SYSTEMS_MANAGER_MANAGED_INSTANCE" ) + +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeEc2Instance, + ResourceTypeEc2Host, + ResourceTypeEc2Ami, + ResourceTypeRds, + ResourceTypeSystemsManagerManagedInstance, + } +} 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 1aacad6e2d3..d9ff1c079c9 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 @@ -116,6 +116,118 @@ func (c *Lightsail) AllocateStaticIpWithContext(ctx aws.Context, input *Allocate return out, req.Send() } +const opAttachCertificateToDistribution = "AttachCertificateToDistribution" + +// AttachCertificateToDistributionRequest generates a "aws/request.Request" representing the +// client's request for the AttachCertificateToDistribution operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See AttachCertificateToDistribution for more information on using the AttachCertificateToDistribution +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the AttachCertificateToDistributionRequest method. +// req, resp := client.AttachCertificateToDistributionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachCertificateToDistribution +func (c *Lightsail) AttachCertificateToDistributionRequest(input *AttachCertificateToDistributionInput) (req *request.Request, output *AttachCertificateToDistributionOutput) { + op := &request.Operation{ + Name: opAttachCertificateToDistribution, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &AttachCertificateToDistributionInput{} + } + + output = &AttachCertificateToDistributionOutput{} + req = c.newRequest(op, input, output) + return +} + +// AttachCertificateToDistribution API operation for Amazon Lightsail. +// +// Attaches an SSL/TLS certificate to your Amazon Lightsail content delivery +// network (CDN) distribution. +// +// After the certificate is attached, your distribution accepts HTTPS traffic +// for all of the domains that are associated with the certificate. +// +// Use the CreateCertificate action to create a certificate that you can attach +// to your distribution. +// +// Only certificates created in the us-east-1 AWS Region can be attached to +// Lightsail distributions. Lightsail distributions are global resources that +// can reference an origin in any AWS Region, and distribute its content globally. +// However, all distributions are located in the us-east-1 Region. +// +// Returns awserr.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 Lightsail's +// API operation AttachCertificateToDistribution for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * OperationFailureException +// Lightsail throws this exception when an operation fails to execute. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachCertificateToDistribution +func (c *Lightsail) AttachCertificateToDistribution(input *AttachCertificateToDistributionInput) (*AttachCertificateToDistributionOutput, error) { + req, out := c.AttachCertificateToDistributionRequest(input) + return out, req.Send() +} + +// AttachCertificateToDistributionWithContext is the same as AttachCertificateToDistribution with the addition of +// the ability to pass a context and additional request options. +// +// See AttachCertificateToDistribution for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) AttachCertificateToDistributionWithContext(ctx aws.Context, input *AttachCertificateToDistributionInput, opts ...request.Option) (*AttachCertificateToDistributionOutput, error) { + req, out := c.AttachCertificateToDistributionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opAttachDisk = "AttachDisk" // AttachDiskRequest generates a "aws/request.Request" representing the @@ -599,11 +711,11 @@ func (c *Lightsail) CloseInstancePublicPortsRequest(input *CloseInstancePublicPo // CloseInstancePublicPorts API operation for Amazon Lightsail. // -// Closes the public ports on a specific Amazon Lightsail instance. +// Closes ports for a specific Amazon Lightsail instance. // -// The close instance public ports operation supports tag-based access control -// via resource tags applied to the resource identified by instance name. For -// more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// The CloseInstancePublicPorts action supports tag-based access control via +// resource tags applied to the resource identified by instanceName. For more +// information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -777,6 +889,112 @@ func (c *Lightsail) CopySnapshotWithContext(ctx aws.Context, input *CopySnapshot return out, req.Send() } +const opCreateCertificate = "CreateCertificate" + +// CreateCertificateRequest generates a "aws/request.Request" representing the +// client's request for the CreateCertificate operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateCertificate for more information on using the CreateCertificate +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateCertificateRequest method. +// req, resp := client.CreateCertificateRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateCertificate +func (c *Lightsail) CreateCertificateRequest(input *CreateCertificateInput) (req *request.Request, output *CreateCertificateOutput) { + op := &request.Operation{ + Name: opCreateCertificate, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateCertificateInput{} + } + + output = &CreateCertificateOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateCertificate API operation for Amazon Lightsail. +// +// Creates an SSL/TLS certificate for a Amazon Lightsail content delivery network +// (CDN) distribution. +// +// After the certificate is created, use the AttachCertificateToDistribution +// action to attach the certificate to your distribution. +// +// Only certificates created in the us-east-1 AWS Region can be attached to +// Lightsail distributions. Lightsail distributions are global resources that +// can reference an origin in any AWS Region, and distribute its content globally. +// However, all distributions are located in the us-east-1 Region. +// +// Returns awserr.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 Lightsail's +// API operation CreateCertificate for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateCertificate +func (c *Lightsail) CreateCertificate(input *CreateCertificateInput) (*CreateCertificateOutput, error) { + req, out := c.CreateCertificateRequest(input) + return out, req.Send() +} + +// CreateCertificateWithContext is the same as CreateCertificate with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCertificate for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) CreateCertificateWithContext(ctx aws.Context, input *CreateCertificateInput, opts ...request.Option) (*CreateCertificateOutput, error) { + req, out := c.CreateCertificateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateCloudFormationStack = "CreateCloudFormationStack" // CreateCloudFormationStackRequest generates a "aws/request.Request" representing the @@ -1343,6 +1561,111 @@ func (c *Lightsail) CreateDiskSnapshotWithContext(ctx aws.Context, input *Create return out, req.Send() } +const opCreateDistribution = "CreateDistribution" + +// CreateDistributionRequest generates a "aws/request.Request" representing the +// client's request for the CreateDistribution operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateDistribution for more information on using the CreateDistribution +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateDistributionRequest method. +// req, resp := client.CreateDistributionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDistribution +func (c *Lightsail) CreateDistributionRequest(input *CreateDistributionInput) (req *request.Request, output *CreateDistributionOutput) { + op := &request.Operation{ + Name: opCreateDistribution, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateDistributionInput{} + } + + output = &CreateDistributionOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateDistribution API operation for Amazon Lightsail. +// +// Creates an Amazon Lightsail content delivery network (CDN) distribution. +// +// A distribution is a globally distributed network of caching servers that +// improve the performance of your website or web application hosted on a Lightsail +// instance. For more information, see Content delivery networks in Amazon Lightsail +// (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-content-delivery-networks). +// +// Returns awserr.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 Lightsail's +// API operation CreateDistribution for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * OperationFailureException +// Lightsail throws this exception when an operation fails to execute. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDistribution +func (c *Lightsail) CreateDistribution(input *CreateDistributionInput) (*CreateDistributionOutput, error) { + req, out := c.CreateDistributionRequest(input) + return out, req.Send() +} + +// 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 *Lightsail) 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 opCreateDomain = "CreateDomain" // CreateDomainRequest generates a "aws/request.Request" representing the @@ -2752,51 +3075,153 @@ func (c *Lightsail) DeleteAutoSnapshotWithContext(ctx aws.Context, input *Delete return out, req.Send() } -const opDeleteContactMethod = "DeleteContactMethod" +const opDeleteCertificate = "DeleteCertificate" -// DeleteContactMethodRequest generates a "aws/request.Request" representing the -// client's request for the DeleteContactMethod operation. The "output" return +// DeleteCertificateRequest generates a "aws/request.Request" representing the +// client's request for the DeleteCertificate operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteContactMethod for more information on using the DeleteContactMethod +// See DeleteCertificate for more information on using the DeleteCertificate // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteContactMethodRequest method. -// req, resp := client.DeleteContactMethodRequest(params) +// // Example sending a request using the DeleteCertificateRequest method. +// req, resp := client.DeleteCertificateRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteContactMethod -func (c *Lightsail) DeleteContactMethodRequest(input *DeleteContactMethodInput) (req *request.Request, output *DeleteContactMethodOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteCertificate +func (c *Lightsail) DeleteCertificateRequest(input *DeleteCertificateInput) (req *request.Request, output *DeleteCertificateOutput) { op := &request.Operation{ - Name: opDeleteContactMethod, + Name: opDeleteCertificate, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &DeleteContactMethodInput{} + input = &DeleteCertificateInput{} } - output = &DeleteContactMethodOutput{} + output = &DeleteCertificateOutput{} req = c.newRequest(op, input, output) return } -// DeleteContactMethod API operation for Amazon Lightsail. +// DeleteCertificate API operation for Amazon Lightsail. // -// Deletes a contact method. +// Deletes an SSL/TLS certificate for your Amazon Lightsail content delivery +// network (CDN) distribution. +// +// Certificates that are currently attached to a distribution cannot be deleted. +// Use the DetachCertificateFromDistribution action to detach a certificate +// from a distribution. +// +// Returns awserr.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 Lightsail's +// API operation DeleteCertificate for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteCertificate +func (c *Lightsail) DeleteCertificate(input *DeleteCertificateInput) (*DeleteCertificateOutput, error) { + req, out := c.DeleteCertificateRequest(input) + 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 *Lightsail) 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 opDeleteContactMethod = "DeleteContactMethod" + +// DeleteContactMethodRequest generates a "aws/request.Request" representing the +// client's request for the DeleteContactMethod operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteContactMethod for more information on using the DeleteContactMethod +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteContactMethodRequest method. +// req, resp := client.DeleteContactMethodRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteContactMethod +func (c *Lightsail) DeleteContactMethodRequest(input *DeleteContactMethodInput) (req *request.Request, output *DeleteContactMethodOutput) { + op := &request.Operation{ + Name: opDeleteContactMethod, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteContactMethodInput{} + } + + output = &DeleteContactMethodOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteContactMethod API operation for Amazon Lightsail. +// +// Deletes a contact method. // // A contact method is used to send you notifications about your Amazon Lightsail // resources. You can add one email address and one mobile phone number contact @@ -3084,6 +3509,106 @@ func (c *Lightsail) DeleteDiskSnapshotWithContext(ctx aws.Context, input *Delete return out, req.Send() } +const opDeleteDistribution = "DeleteDistribution" + +// DeleteDistributionRequest generates a "aws/request.Request" representing the +// client's request for the DeleteDistribution operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteDistribution for more information on using the DeleteDistribution +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteDistributionRequest method. +// req, resp := client.DeleteDistributionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDistribution +func (c *Lightsail) DeleteDistributionRequest(input *DeleteDistributionInput) (req *request.Request, output *DeleteDistributionOutput) { + op := &request.Operation{ + Name: opDeleteDistribution, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteDistributionInput{} + } + + output = &DeleteDistributionOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteDistribution API operation for Amazon Lightsail. +// +// Deletes your Amazon Lightsail content delivery network (CDN) distribution. +// +// Returns awserr.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 Lightsail's +// API operation DeleteDistribution for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * OperationFailureException +// Lightsail throws this exception when an operation fails to execute. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDistribution +func (c *Lightsail) DeleteDistribution(input *DeleteDistributionInput) (*DeleteDistributionOutput, error) { + req, out := c.DeleteDistributionRequest(input) + return out, req.Send() +} + +// 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 *Lightsail) 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 opDeleteDomain = "DeleteDomain" // DeleteDomainRequest generates a "aws/request.Request" representing the @@ -4170,6 +4695,110 @@ func (c *Lightsail) DeleteRelationalDatabaseSnapshotWithContext(ctx aws.Context, return out, req.Send() } +const opDetachCertificateFromDistribution = "DetachCertificateFromDistribution" + +// DetachCertificateFromDistributionRequest generates a "aws/request.Request" representing the +// client's request for the DetachCertificateFromDistribution operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DetachCertificateFromDistribution for more information on using the DetachCertificateFromDistribution +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DetachCertificateFromDistributionRequest method. +// req, resp := client.DetachCertificateFromDistributionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachCertificateFromDistribution +func (c *Lightsail) DetachCertificateFromDistributionRequest(input *DetachCertificateFromDistributionInput) (req *request.Request, output *DetachCertificateFromDistributionOutput) { + op := &request.Operation{ + Name: opDetachCertificateFromDistribution, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DetachCertificateFromDistributionInput{} + } + + output = &DetachCertificateFromDistributionOutput{} + req = c.newRequest(op, input, output) + return +} + +// DetachCertificateFromDistribution API operation for Amazon Lightsail. +// +// Detaches an SSL/TLS certificate from your Amazon Lightsail content delivery +// network (CDN) distribution. +// +// After the certificate is detached, your distribution stops accepting traffic +// for all of the domains that are associated with the 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 +// the error. +// +// See the AWS API reference guide for Amazon Lightsail's +// API operation DetachCertificateFromDistribution for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * OperationFailureException +// Lightsail throws this exception when an operation fails to execute. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachCertificateFromDistribution +func (c *Lightsail) DetachCertificateFromDistribution(input *DetachCertificateFromDistributionInput) (*DetachCertificateFromDistributionOutput, error) { + req, out := c.DetachCertificateFromDistributionRequest(input) + return out, req.Send() +} + +// DetachCertificateFromDistributionWithContext is the same as DetachCertificateFromDistribution with the addition of +// the ability to pass a context and additional request options. +// +// See DetachCertificateFromDistribution for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DetachCertificateFromDistributionWithContext(ctx aws.Context, input *DetachCertificateFromDistributionInput, opts ...request.Option) (*DetachCertificateFromDistributionOutput, error) { + req, out := c.DetachCertificateFromDistributionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDetachDisk = "DetachDisk" // DetachDiskRequest generates a "aws/request.Request" representing the @@ -5450,32 +6079,133 @@ func (c *Lightsail) GetBundlesWithContext(ctx aws.Context, input *GetBundlesInpu return out, req.Send() } -const opGetCloudFormationStackRecords = "GetCloudFormationStackRecords" +const opGetCertificates = "GetCertificates" -// GetCloudFormationStackRecordsRequest generates a "aws/request.Request" representing the -// client's request for the GetCloudFormationStackRecords operation. The "output" return +// GetCertificatesRequest generates a "aws/request.Request" representing the +// client's request for the GetCertificates operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetCloudFormationStackRecords for more information on using the GetCloudFormationStackRecords +// See GetCertificates for more information on using the GetCertificates // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetCloudFormationStackRecordsRequest method. -// req, resp := client.GetCloudFormationStackRecordsRequest(params) +// // Example sending a request using the GetCertificatesRequest method. +// req, resp := client.GetCertificatesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetCloudFormationStackRecords +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetCertificates +func (c *Lightsail) GetCertificatesRequest(input *GetCertificatesInput) (req *request.Request, output *GetCertificatesOutput) { + op := &request.Operation{ + Name: opGetCertificates, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetCertificatesInput{} + } + + output = &GetCertificatesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetCertificates API operation for Amazon Lightsail. +// +// Returns information about one or more Amazon Lightsail SSL/TLS certificates. +// +// To get a summary of a certificate, ommit includeCertificateDetails from your +// request. The response will include only the certificate Amazon Resource Name +// (ARN), certificate name, domain name, and tags. +// +// Returns awserr.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 Lightsail's +// API operation GetCertificates for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetCertificates +func (c *Lightsail) GetCertificates(input *GetCertificatesInput) (*GetCertificatesOutput, error) { + req, out := c.GetCertificatesRequest(input) + return out, req.Send() +} + +// GetCertificatesWithContext is the same as GetCertificates with the addition of +// the ability to pass a context and additional request options. +// +// See GetCertificates for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) GetCertificatesWithContext(ctx aws.Context, input *GetCertificatesInput, opts ...request.Option) (*GetCertificatesOutput, error) { + req, out := c.GetCertificatesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetCloudFormationStackRecords = "GetCloudFormationStackRecords" + +// GetCloudFormationStackRecordsRequest generates a "aws/request.Request" representing the +// client's request for the GetCloudFormationStackRecords operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetCloudFormationStackRecords for more information on using the GetCloudFormationStackRecords +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetCloudFormationStackRecordsRequest method. +// req, resp := client.GetCloudFormationStackRecordsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetCloudFormationStackRecords func (c *Lightsail) GetCloudFormationStackRecordsRequest(input *GetCloudFormationStackRecordsInput) (req *request.Request, output *GetCloudFormationStackRecordsOutput) { op := &request.Operation{ Name: opGetCloudFormationStackRecords, @@ -6083,58 +6813,62 @@ func (c *Lightsail) GetDisksWithContext(ctx aws.Context, input *GetDisksInput, o return out, req.Send() } -const opGetDomain = "GetDomain" +const opGetDistributionBundles = "GetDistributionBundles" -// GetDomainRequest generates a "aws/request.Request" representing the -// client's request for the GetDomain operation. The "output" return +// GetDistributionBundlesRequest generates a "aws/request.Request" representing the +// client's request for the GetDistributionBundles operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetDomain for more information on using the GetDomain +// See GetDistributionBundles for more information on using the GetDistributionBundles // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetDomainRequest method. -// req, resp := client.GetDomainRequest(params) +// // Example sending a request using the GetDistributionBundlesRequest method. +// req, resp := client.GetDistributionBundlesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomain -func (c *Lightsail) GetDomainRequest(input *GetDomainInput) (req *request.Request, output *GetDomainOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDistributionBundles +func (c *Lightsail) GetDistributionBundlesRequest(input *GetDistributionBundlesInput) (req *request.Request, output *GetDistributionBundlesOutput) { op := &request.Operation{ - Name: opGetDomain, + Name: opGetDistributionBundles, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetDomainInput{} + input = &GetDistributionBundlesInput{} } - output = &GetDomainOutput{} + output = &GetDistributionBundlesOutput{} req = c.newRequest(op, input, output) return } -// GetDomain API operation for Amazon Lightsail. +// GetDistributionBundles API operation for Amazon Lightsail. // -// Returns information about a specific domain recordset. +// Returns the list bundles that can be applied to you Amazon Lightsail content +// delivery network (CDN) distributions. +// +// A distribution bundle specifies the monthly network transfer quota and monthly +// cost of your dsitribution. // // Returns awserr.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 Lightsail's -// API operation GetDomain for usage and error information. +// API operation GetDistributionBundles for usage and error information. // // Returned Error Types: // * ServiceException @@ -6158,87 +6892,84 @@ func (c *Lightsail) GetDomainRequest(input *GetDomainInput) (req *request.Reques // Lightsail throws this exception when the user cannot be authenticated or // uses invalid credentials to access a resource. // -// * AccountSetupInProgressException -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDistributionBundles +func (c *Lightsail) GetDistributionBundles(input *GetDistributionBundlesInput) (*GetDistributionBundlesOutput, error) { + req, out := c.GetDistributionBundlesRequest(input) return out, req.Send() } -// GetDomainWithContext is the same as GetDomain with the addition of +// GetDistributionBundlesWithContext is the same as GetDistributionBundles 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. +// See GetDistributionBundles for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetDistributionBundlesWithContext(ctx aws.Context, input *GetDistributionBundlesInput, opts ...request.Option) (*GetDistributionBundlesOutput, error) { + req, out := c.GetDistributionBundlesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetDomains = "GetDomains" +const opGetDistributionLatestCacheReset = "GetDistributionLatestCacheReset" -// GetDomainsRequest generates a "aws/request.Request" representing the -// client's request for the GetDomains operation. The "output" return +// GetDistributionLatestCacheResetRequest generates a "aws/request.Request" representing the +// client's request for the GetDistributionLatestCacheReset operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetDomains for more information on using the GetDomains +// See GetDistributionLatestCacheReset for more information on using the GetDistributionLatestCacheReset // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetDomainsRequest method. -// req, resp := client.GetDomainsRequest(params) +// // Example sending a request using the GetDistributionLatestCacheResetRequest method. +// req, resp := client.GetDistributionLatestCacheResetRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomains -func (c *Lightsail) GetDomainsRequest(input *GetDomainsInput) (req *request.Request, output *GetDomainsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDistributionLatestCacheReset +func (c *Lightsail) GetDistributionLatestCacheResetRequest(input *GetDistributionLatestCacheResetInput) (req *request.Request, output *GetDistributionLatestCacheResetOutput) { op := &request.Operation{ - Name: opGetDomains, + Name: opGetDistributionLatestCacheReset, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetDomainsInput{} + input = &GetDistributionLatestCacheResetInput{} } - output = &GetDomainsOutput{} + output = &GetDistributionLatestCacheResetOutput{} req = c.newRequest(op, input, output) return } -// GetDomains API operation for Amazon Lightsail. +// GetDistributionLatestCacheReset API operation for Amazon Lightsail. // -// Returns a list of all domains in the user's account. +// Returns the timestamp and status of the last cache reset of a specific Amazon +// Lightsail content delivery network (CDN) distribution. // // Returns awserr.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 Lightsail's -// API operation GetDomains for usage and error information. +// API operation GetDistributionLatestCacheReset for usage and error information. // // Returned Error Types: // * ServiceException @@ -6262,91 +6993,88 @@ func (c *Lightsail) GetDomainsRequest(input *GetDomainsInput) (req *request.Requ // Lightsail throws this exception when the user cannot be authenticated or // uses invalid credentials to access a resource. // -// * AccountSetupInProgressException -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDistributionLatestCacheReset +func (c *Lightsail) GetDistributionLatestCacheReset(input *GetDistributionLatestCacheResetInput) (*GetDistributionLatestCacheResetOutput, error) { + req, out := c.GetDistributionLatestCacheResetRequest(input) return out, req.Send() } -// GetDomainsWithContext is the same as GetDomains with the addition of +// GetDistributionLatestCacheResetWithContext is the same as GetDistributionLatestCacheReset 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. +// See GetDistributionLatestCacheReset for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetDistributionLatestCacheResetWithContext(ctx aws.Context, input *GetDistributionLatestCacheResetInput, opts ...request.Option) (*GetDistributionLatestCacheResetOutput, error) { + req, out := c.GetDistributionLatestCacheResetRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetExportSnapshotRecords = "GetExportSnapshotRecords" +const opGetDistributionMetricData = "GetDistributionMetricData" -// GetExportSnapshotRecordsRequest generates a "aws/request.Request" representing the -// client's request for the GetExportSnapshotRecords operation. The "output" return +// GetDistributionMetricDataRequest generates a "aws/request.Request" representing the +// client's request for the GetDistributionMetricData operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetExportSnapshotRecords for more information on using the GetExportSnapshotRecords +// See GetDistributionMetricData for more information on using the GetDistributionMetricData // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetExportSnapshotRecordsRequest method. -// req, resp := client.GetExportSnapshotRecordsRequest(params) +// // Example sending a request using the GetDistributionMetricDataRequest method. +// req, resp := client.GetDistributionMetricDataRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetExportSnapshotRecords -func (c *Lightsail) GetExportSnapshotRecordsRequest(input *GetExportSnapshotRecordsInput) (req *request.Request, output *GetExportSnapshotRecordsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDistributionMetricData +func (c *Lightsail) GetDistributionMetricDataRequest(input *GetDistributionMetricDataInput) (req *request.Request, output *GetDistributionMetricDataOutput) { op := &request.Operation{ - Name: opGetExportSnapshotRecords, + Name: opGetDistributionMetricData, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetExportSnapshotRecordsInput{} + input = &GetDistributionMetricDataInput{} } - output = &GetExportSnapshotRecordsOutput{} + output = &GetDistributionMetricDataOutput{} req = c.newRequest(op, input, output) return } -// GetExportSnapshotRecords API operation for Amazon Lightsail. +// GetDistributionMetricData API operation for Amazon Lightsail. // -// Returns the export snapshot record created as a result of the export snapshot -// operation. +// Returns the data points of a specific metric for an Amazon Lightsail content +// delivery network (CDN) distribution. // -// An export snapshot record can be used to create a new Amazon EC2 instance -// and its related resources with the create cloud formation stack operation. +// Metrics report the utilization of your resources, and the error counts generated +// by them. Monitor and collect metric data regularly to maintain the reliability, +// availability, and performance of your resources. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Lightsail's -// API operation GetExportSnapshotRecords for usage and error information. +// API operation GetDistributionMetricData for usage and error information. // // Returned Error Types: // * ServiceException @@ -6370,88 +7098,84 @@ func (c *Lightsail) GetExportSnapshotRecordsRequest(input *GetExportSnapshotReco // Lightsail throws this exception when the user cannot be authenticated or // uses invalid credentials to access a resource. // -// * AccountSetupInProgressException -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetExportSnapshotRecords -func (c *Lightsail) GetExportSnapshotRecords(input *GetExportSnapshotRecordsInput) (*GetExportSnapshotRecordsOutput, error) { - req, out := c.GetExportSnapshotRecordsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDistributionMetricData +func (c *Lightsail) GetDistributionMetricData(input *GetDistributionMetricDataInput) (*GetDistributionMetricDataOutput, error) { + req, out := c.GetDistributionMetricDataRequest(input) return out, req.Send() } -// GetExportSnapshotRecordsWithContext is the same as GetExportSnapshotRecords with the addition of +// GetDistributionMetricDataWithContext is the same as GetDistributionMetricData with the addition of // the ability to pass a context and additional request options. // -// See GetExportSnapshotRecords for details on how to use this API operation. +// See GetDistributionMetricData for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) GetExportSnapshotRecordsWithContext(ctx aws.Context, input *GetExportSnapshotRecordsInput, opts ...request.Option) (*GetExportSnapshotRecordsOutput, error) { - req, out := c.GetExportSnapshotRecordsRequest(input) +func (c *Lightsail) GetDistributionMetricDataWithContext(ctx aws.Context, input *GetDistributionMetricDataInput, opts ...request.Option) (*GetDistributionMetricDataOutput, error) { + req, out := c.GetDistributionMetricDataRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetInstance = "GetInstance" +const opGetDistributions = "GetDistributions" -// GetInstanceRequest generates a "aws/request.Request" representing the -// client's request for the GetInstance operation. The "output" return +// GetDistributionsRequest generates a "aws/request.Request" representing the +// client's request for the GetDistributions operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetInstance for more information on using the GetInstance +// See GetDistributions for more information on using the GetDistributions // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetInstanceRequest method. -// req, resp := client.GetInstanceRequest(params) +// // Example sending a request using the GetDistributionsRequest method. +// req, resp := client.GetDistributionsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstance -func (c *Lightsail) GetInstanceRequest(input *GetInstanceInput) (req *request.Request, output *GetInstanceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDistributions +func (c *Lightsail) GetDistributionsRequest(input *GetDistributionsInput) (req *request.Request, output *GetDistributionsOutput) { op := &request.Operation{ - Name: opGetInstance, + Name: opGetDistributions, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetInstanceInput{} + input = &GetDistributionsInput{} } - output = &GetInstanceOutput{} + output = &GetDistributionsOutput{} req = c.newRequest(op, input, output) return } -// GetInstance API operation for Amazon Lightsail. +// GetDistributions API operation for Amazon Lightsail. // -// Returns information about a specific Amazon Lightsail instance, which is -// a virtual private server. +// Returns information about one or more of your Amazon Lightsail content delivery +// network (CDN) distributions. // // Returns awserr.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 Lightsail's -// API operation GetInstance for usage and error information. +// API operation GetDistributions for usage and error information. // // Returned Error Types: // * ServiceException @@ -6475,92 +7199,83 @@ func (c *Lightsail) GetInstanceRequest(input *GetInstanceInput) (req *request.Re // Lightsail throws this exception when the user cannot be authenticated or // uses invalid credentials to access a resource. // -// * AccountSetupInProgressException -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDistributions +func (c *Lightsail) GetDistributions(input *GetDistributionsInput) (*GetDistributionsOutput, error) { + req, out := c.GetDistributionsRequest(input) return out, req.Send() } -// GetInstanceWithContext is the same as GetInstance with the addition of +// GetDistributionsWithContext is the same as GetDistributions 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. +// See GetDistributions for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetDistributionsWithContext(ctx aws.Context, input *GetDistributionsInput, opts ...request.Option) (*GetDistributionsOutput, error) { + req, out := c.GetDistributionsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetInstanceAccessDetails = "GetInstanceAccessDetails" +const opGetDomain = "GetDomain" -// GetInstanceAccessDetailsRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceAccessDetails operation. The "output" return +// GetDomainRequest generates a "aws/request.Request" representing the +// client's request for the GetDomain operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetInstanceAccessDetails for more information on using the GetInstanceAccessDetails +// See GetDomain for more information on using the GetDomain // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetInstanceAccessDetailsRequest method. -// req, resp := client.GetInstanceAccessDetailsRequest(params) +// // Example sending a request using the GetDomainRequest method. +// req, resp := client.GetDomainRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceAccessDetails -func (c *Lightsail) GetInstanceAccessDetailsRequest(input *GetInstanceAccessDetailsInput) (req *request.Request, output *GetInstanceAccessDetailsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomain +func (c *Lightsail) GetDomainRequest(input *GetDomainInput) (req *request.Request, output *GetDomainOutput) { op := &request.Operation{ - Name: opGetInstanceAccessDetails, + Name: opGetDomain, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetInstanceAccessDetailsInput{} + input = &GetDomainInput{} } - output = &GetInstanceAccessDetailsOutput{} + output = &GetDomainOutput{} req = c.newRequest(op, input, output) return } -// GetInstanceAccessDetails API operation for Amazon Lightsail. -// -// Returns temporary SSH keys you can use to connect to a specific virtual private -// server, or instance. +// GetDomain API operation for Amazon Lightsail. // -// The get instance access details operation supports tag-based access control -// via resource tags applied to the resource identified by instance name. For -// more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// Returns information about a specific domain recordset. // // Returns awserr.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 Lightsail's -// API operation GetInstanceAccessDetails for usage and error information. +// API operation GetDomain for usage and error information. // // Returned Error Types: // * ServiceException @@ -6591,81 +7306,80 @@ func (c *Lightsail) GetInstanceAccessDetailsRequest(input *GetInstanceAccessDeta // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// GetInstanceAccessDetailsWithContext is the same as GetInstanceAccessDetails with the addition of +// GetDomainWithContext is the same as GetDomain 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. +// 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) GetInstanceAccessDetailsWithContext(ctx aws.Context, input *GetInstanceAccessDetailsInput, opts ...request.Option) (*GetInstanceAccessDetailsOutput, error) { - req, out := c.GetInstanceAccessDetailsRequest(input) +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 opGetInstanceMetricData = "GetInstanceMetricData" +const opGetDomains = "GetDomains" -// GetInstanceMetricDataRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceMetricData operation. The "output" return +// GetDomainsRequest generates a "aws/request.Request" representing the +// client's request for the GetDomains operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetInstanceMetricData for more information on using the GetInstanceMetricData +// See GetDomains for more information on using the GetDomains // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetInstanceMetricDataRequest method. -// req, resp := client.GetInstanceMetricDataRequest(params) +// // Example sending a request using the GetDomainsRequest method. +// req, resp := client.GetDomainsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceMetricData -func (c *Lightsail) GetInstanceMetricDataRequest(input *GetInstanceMetricDataInput) (req *request.Request, output *GetInstanceMetricDataOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomains +func (c *Lightsail) GetDomainsRequest(input *GetDomainsInput) (req *request.Request, output *GetDomainsOutput) { op := &request.Operation{ - Name: opGetInstanceMetricData, + Name: opGetDomains, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetInstanceMetricDataInput{} + input = &GetDomainsInput{} } - output = &GetInstanceMetricDataOutput{} + output = &GetDomainsOutput{} req = c.newRequest(op, input, output) return } -// GetInstanceMetricData API operation for Amazon Lightsail. +// GetDomains API operation for Amazon Lightsail. // -// Returns the data points for the specified Amazon Lightsail instance metric, -// given an instance name. +// Returns a list of all domains in the user's 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 Amazon Lightsail's -// API operation GetInstanceMetricData for usage and error information. +// API operation GetDomains for usage and error information. // // Returned Error Types: // * ServiceException @@ -6696,80 +7410,84 @@ func (c *Lightsail) GetInstanceMetricDataRequest(input *GetInstanceMetricDataInp // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// GetInstanceMetricDataWithContext is the same as GetInstanceMetricData with the addition of +// GetDomainsWithContext is the same as GetDomains 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. +// 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) GetInstanceMetricDataWithContext(ctx aws.Context, input *GetInstanceMetricDataInput, opts ...request.Option) (*GetInstanceMetricDataOutput, error) { - req, out := c.GetInstanceMetricDataRequest(input) +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 opGetInstancePortStates = "GetInstancePortStates" +const opGetExportSnapshotRecords = "GetExportSnapshotRecords" -// GetInstancePortStatesRequest generates a "aws/request.Request" representing the -// client's request for the GetInstancePortStates operation. The "output" return +// GetExportSnapshotRecordsRequest generates a "aws/request.Request" representing the +// client's request for the GetExportSnapshotRecords operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetInstancePortStates for more information on using the GetInstancePortStates +// See GetExportSnapshotRecords for more information on using the GetExportSnapshotRecords // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetInstancePortStatesRequest method. -// req, resp := client.GetInstancePortStatesRequest(params) +// // Example sending a request using the GetExportSnapshotRecordsRequest method. +// req, resp := client.GetExportSnapshotRecordsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstancePortStates -func (c *Lightsail) GetInstancePortStatesRequest(input *GetInstancePortStatesInput) (req *request.Request, output *GetInstancePortStatesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetExportSnapshotRecords +func (c *Lightsail) GetExportSnapshotRecordsRequest(input *GetExportSnapshotRecordsInput) (req *request.Request, output *GetExportSnapshotRecordsOutput) { op := &request.Operation{ - Name: opGetInstancePortStates, + Name: opGetExportSnapshotRecords, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetInstancePortStatesInput{} + input = &GetExportSnapshotRecordsInput{} } - output = &GetInstancePortStatesOutput{} + output = &GetExportSnapshotRecordsOutput{} req = c.newRequest(op, input, output) return } -// GetInstancePortStates API operation for Amazon Lightsail. +// GetExportSnapshotRecords API operation for Amazon Lightsail. +// +// Returns the export snapshot record created as a result of the export snapshot +// operation. // -// Returns the port states for a specific virtual private server, or instance. +// An export snapshot record can be used to create a new Amazon EC2 instance +// and its related resources with the create cloud formation stack 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 Amazon Lightsail's -// API operation GetInstancePortStates for usage and error information. +// API operation GetExportSnapshotRecords for usage and error information. // // Returned Error Types: // * ServiceException @@ -6800,80 +7518,81 @@ func (c *Lightsail) GetInstancePortStatesRequest(input *GetInstancePortStatesInp // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetExportSnapshotRecords +func (c *Lightsail) GetExportSnapshotRecords(input *GetExportSnapshotRecordsInput) (*GetExportSnapshotRecordsOutput, error) { + req, out := c.GetExportSnapshotRecordsRequest(input) return out, req.Send() } -// GetInstancePortStatesWithContext is the same as GetInstancePortStates with the addition of +// GetExportSnapshotRecordsWithContext is the same as GetExportSnapshotRecords 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. +// See GetExportSnapshotRecords for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetExportSnapshotRecordsWithContext(ctx aws.Context, input *GetExportSnapshotRecordsInput, opts ...request.Option) (*GetExportSnapshotRecordsOutput, error) { + req, out := c.GetExportSnapshotRecordsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetInstanceSnapshot = "GetInstanceSnapshot" +const opGetInstance = "GetInstance" -// GetInstanceSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceSnapshot operation. The "output" return +// GetInstanceRequest generates a "aws/request.Request" representing the +// client's request for the GetInstance operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetInstanceSnapshot for more information on using the GetInstanceSnapshot +// See GetInstance for more information on using the GetInstance // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetInstanceSnapshotRequest method. -// req, resp := client.GetInstanceSnapshotRequest(params) +// // Example sending a request using the GetInstanceRequest method. +// req, resp := client.GetInstanceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshot -func (c *Lightsail) GetInstanceSnapshotRequest(input *GetInstanceSnapshotInput) (req *request.Request, output *GetInstanceSnapshotOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstance +func (c *Lightsail) GetInstanceRequest(input *GetInstanceInput) (req *request.Request, output *GetInstanceOutput) { op := &request.Operation{ - Name: opGetInstanceSnapshot, + Name: opGetInstance, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetInstanceSnapshotInput{} + input = &GetInstanceInput{} } - output = &GetInstanceSnapshotOutput{} + output = &GetInstanceOutput{} req = c.newRequest(op, input, output) return } -// GetInstanceSnapshot API operation for Amazon Lightsail. +// GetInstance API operation for Amazon Lightsail. // -// Returns information about a specific instance snapshot. +// Returns information about a specific Amazon Lightsail instance, which is +// a virtual private server. // // Returns awserr.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 Lightsail's -// API operation GetInstanceSnapshot for usage and error information. +// API operation GetInstance for usage and error information. // // Returned Error Types: // * ServiceException @@ -6904,80 +7623,85 @@ func (c *Lightsail) GetInstanceSnapshotRequest(input *GetInstanceSnapshotInput) // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// GetInstanceSnapshotWithContext is the same as GetInstanceSnapshot with the addition of +// GetInstanceWithContext is the same as GetInstance 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. +// 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) GetInstanceSnapshotWithContext(ctx aws.Context, input *GetInstanceSnapshotInput, opts ...request.Option) (*GetInstanceSnapshotOutput, error) { - req, out := c.GetInstanceSnapshotRequest(input) +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 opGetInstanceSnapshots = "GetInstanceSnapshots" +const opGetInstanceAccessDetails = "GetInstanceAccessDetails" -// GetInstanceSnapshotsRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceSnapshots operation. The "output" return +// GetInstanceAccessDetailsRequest generates a "aws/request.Request" representing the +// client's request for the GetInstanceAccessDetails operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetInstanceSnapshots for more information on using the GetInstanceSnapshots +// See GetInstanceAccessDetails for more information on using the GetInstanceAccessDetails // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetInstanceSnapshotsRequest method. -// req, resp := client.GetInstanceSnapshotsRequest(params) +// // Example sending a request using the GetInstanceAccessDetailsRequest method. +// req, resp := client.GetInstanceAccessDetailsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshots -func (c *Lightsail) GetInstanceSnapshotsRequest(input *GetInstanceSnapshotsInput) (req *request.Request, output *GetInstanceSnapshotsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceAccessDetails +func (c *Lightsail) GetInstanceAccessDetailsRequest(input *GetInstanceAccessDetailsInput) (req *request.Request, output *GetInstanceAccessDetailsOutput) { op := &request.Operation{ - Name: opGetInstanceSnapshots, + Name: opGetInstanceAccessDetails, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetInstanceSnapshotsInput{} + input = &GetInstanceAccessDetailsInput{} } - output = &GetInstanceSnapshotsOutput{} + output = &GetInstanceAccessDetailsOutput{} req = c.newRequest(op, input, output) return } -// GetInstanceSnapshots API operation for Amazon Lightsail. +// GetInstanceAccessDetails API operation for Amazon Lightsail. // -// Returns all instance snapshots for the user's account. +// Returns temporary SSH keys you can use to connect to a specific virtual private +// server, or instance. +// +// The get instance access details operation supports tag-based access control +// via resource tags applied to the resource identified by instance name. For +// more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // // Returns awserr.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 Lightsail's -// API operation GetInstanceSnapshots for usage and error information. +// API operation GetInstanceAccessDetails for usage and error information. // // Returned Error Types: // * ServiceException @@ -7008,80 +7732,85 @@ func (c *Lightsail) GetInstanceSnapshotsRequest(input *GetInstanceSnapshotsInput // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// GetInstanceSnapshotsWithContext is the same as GetInstanceSnapshots with the addition of +// GetInstanceAccessDetailsWithContext is the same as GetInstanceAccessDetails 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. +// 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) GetInstanceSnapshotsWithContext(ctx aws.Context, input *GetInstanceSnapshotsInput, opts ...request.Option) (*GetInstanceSnapshotsOutput, error) { - req, out := c.GetInstanceSnapshotsRequest(input) +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 opGetInstanceState = "GetInstanceState" +const opGetInstanceMetricData = "GetInstanceMetricData" -// GetInstanceStateRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceState operation. The "output" return +// GetInstanceMetricDataRequest generates a "aws/request.Request" representing the +// client's request for the GetInstanceMetricData operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetInstanceState for more information on using the GetInstanceState +// See GetInstanceMetricData for more information on using the GetInstanceMetricData // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetInstanceStateRequest method. -// req, resp := client.GetInstanceStateRequest(params) +// // Example sending a request using the GetInstanceMetricDataRequest method. +// req, resp := client.GetInstanceMetricDataRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceState -func (c *Lightsail) GetInstanceStateRequest(input *GetInstanceStateInput) (req *request.Request, output *GetInstanceStateOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceMetricData +func (c *Lightsail) GetInstanceMetricDataRequest(input *GetInstanceMetricDataInput) (req *request.Request, output *GetInstanceMetricDataOutput) { op := &request.Operation{ - Name: opGetInstanceState, + Name: opGetInstanceMetricData, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetInstanceStateInput{} + input = &GetInstanceMetricDataInput{} } - output = &GetInstanceStateOutput{} + output = &GetInstanceMetricDataOutput{} req = c.newRequest(op, input, output) return } -// GetInstanceState API operation for Amazon Lightsail. +// GetInstanceMetricData API operation for Amazon Lightsail. // -// Returns the state of a specific instance. Works on one instance at a time. +// Returns the data points for the specified Amazon Lightsail instance metric, +// given an instance name. +// +// Metrics report the utilization of your resources, and the error counts generated +// by them. Monitor and collect metric data regularly to maintain the reliability, +// availability, and performance of your resources. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstanceState for usage and error information. +// API operation GetInstanceMetricData for usage and error information. // // Returned Error Types: // * ServiceException @@ -7112,81 +7841,82 @@ func (c *Lightsail) GetInstanceStateRequest(input *GetInstanceStateInput) (req * // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// GetInstanceStateWithContext is the same as GetInstanceState with the addition of +// GetInstanceMetricDataWithContext is the same as GetInstanceMetricData 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. +// 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) GetInstanceStateWithContext(ctx aws.Context, input *GetInstanceStateInput, opts ...request.Option) (*GetInstanceStateOutput, error) { - req, out := c.GetInstanceStateRequest(input) +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 opGetInstances = "GetInstances" +const opGetInstancePortStates = "GetInstancePortStates" -// GetInstancesRequest generates a "aws/request.Request" representing the -// client's request for the GetInstances operation. The "output" return +// GetInstancePortStatesRequest generates a "aws/request.Request" representing the +// client's request for the GetInstancePortStates operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetInstances for more information on using the GetInstances +// See GetInstancePortStates for more information on using the GetInstancePortStates // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetInstancesRequest method. -// req, resp := client.GetInstancesRequest(params) +// // Example sending a request using the GetInstancePortStatesRequest method. +// req, resp := client.GetInstancePortStatesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstances -func (c *Lightsail) GetInstancesRequest(input *GetInstancesInput) (req *request.Request, output *GetInstancesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstancePortStates +func (c *Lightsail) GetInstancePortStatesRequest(input *GetInstancePortStatesInput) (req *request.Request, output *GetInstancePortStatesOutput) { op := &request.Operation{ - Name: opGetInstances, + Name: opGetInstancePortStates, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetInstancesInput{} + input = &GetInstancePortStatesInput{} } - output = &GetInstancesOutput{} + output = &GetInstancePortStatesOutput{} req = c.newRequest(op, input, output) return } -// GetInstances API operation for Amazon Lightsail. +// GetInstancePortStates API operation for Amazon Lightsail. // -// Returns information about all Amazon Lightsail virtual private servers, or -// instances. +// Returns the firewall port states for a specific Amazon Lightsail instance, +// the IP addresses allowed to connect to the instance through the ports, and +// the protocol. // // Returns awserr.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 Lightsail's -// API operation GetInstances for usage and error information. +// API operation GetInstancePortStates for usage and error information. // // Returned Error Types: // * ServiceException @@ -7217,80 +7947,80 @@ func (c *Lightsail) GetInstancesRequest(input *GetInstancesInput) (req *request. // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// GetInstancesWithContext is the same as GetInstances with the addition of +// GetInstancePortStatesWithContext is the same as GetInstancePortStates 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. +// 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) GetInstancesWithContext(ctx aws.Context, input *GetInstancesInput, opts ...request.Option) (*GetInstancesOutput, error) { - req, out := c.GetInstancesRequest(input) +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 opGetKeyPair = "GetKeyPair" +const opGetInstanceSnapshot = "GetInstanceSnapshot" -// GetKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the GetKeyPair operation. The "output" return +// GetInstanceSnapshotRequest generates a "aws/request.Request" representing the +// client's request for the GetInstanceSnapshot operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetKeyPair for more information on using the GetKeyPair +// See GetInstanceSnapshot for more information on using the GetInstanceSnapshot // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetKeyPairRequest method. -// req, resp := client.GetKeyPairRequest(params) +// // Example sending a request using the GetInstanceSnapshotRequest method. +// req, resp := client.GetInstanceSnapshotRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPair -func (c *Lightsail) GetKeyPairRequest(input *GetKeyPairInput) (req *request.Request, output *GetKeyPairOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshot +func (c *Lightsail) GetInstanceSnapshotRequest(input *GetInstanceSnapshotInput) (req *request.Request, output *GetInstanceSnapshotOutput) { op := &request.Operation{ - Name: opGetKeyPair, + Name: opGetInstanceSnapshot, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetKeyPairInput{} + input = &GetInstanceSnapshotInput{} } - output = &GetKeyPairOutput{} + output = &GetInstanceSnapshotOutput{} req = c.newRequest(op, input, output) return } -// GetKeyPair API operation for Amazon Lightsail. +// GetInstanceSnapshot API operation for Amazon Lightsail. // -// Returns information about a specific key pair. +// Returns information about a specific instance snapshot. // // Returns awserr.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 Lightsail's -// API operation GetKeyPair for usage and error information. +// API operation GetInstanceSnapshot for usage and error information. // // Returned Error Types: // * ServiceException @@ -7321,80 +8051,80 @@ func (c *Lightsail) GetKeyPairRequest(input *GetKeyPairInput) (req *request.Requ // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// GetKeyPairWithContext is the same as GetKeyPair with the addition of +// GetInstanceSnapshotWithContext is the same as GetInstanceSnapshot 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. +// 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) GetKeyPairWithContext(ctx aws.Context, input *GetKeyPairInput, opts ...request.Option) (*GetKeyPairOutput, error) { - req, out := c.GetKeyPairRequest(input) +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 opGetKeyPairs = "GetKeyPairs" +const opGetInstanceSnapshots = "GetInstanceSnapshots" -// GetKeyPairsRequest generates a "aws/request.Request" representing the -// client's request for the GetKeyPairs operation. The "output" return +// GetInstanceSnapshotsRequest generates a "aws/request.Request" representing the +// client's request for the GetInstanceSnapshots operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetKeyPairs for more information on using the GetKeyPairs +// See GetInstanceSnapshots for more information on using the GetInstanceSnapshots // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetKeyPairsRequest method. -// req, resp := client.GetKeyPairsRequest(params) +// // Example sending a request using the GetInstanceSnapshotsRequest method. +// req, resp := client.GetInstanceSnapshotsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPairs -func (c *Lightsail) GetKeyPairsRequest(input *GetKeyPairsInput) (req *request.Request, output *GetKeyPairsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshots +func (c *Lightsail) GetInstanceSnapshotsRequest(input *GetInstanceSnapshotsInput) (req *request.Request, output *GetInstanceSnapshotsOutput) { op := &request.Operation{ - Name: opGetKeyPairs, + Name: opGetInstanceSnapshots, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetKeyPairsInput{} + input = &GetInstanceSnapshotsInput{} } - output = &GetKeyPairsOutput{} + output = &GetInstanceSnapshotsOutput{} req = c.newRequest(op, input, output) return } -// GetKeyPairs API operation for Amazon Lightsail. +// GetInstanceSnapshots API operation for Amazon Lightsail. // -// Returns information about all key pairs in the user's account. +// Returns all instance snapshots for the user's 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 Amazon Lightsail's -// API operation GetKeyPairs for usage and error information. +// API operation GetInstanceSnapshots for usage and error information. // // Returned Error Types: // * ServiceException @@ -7425,80 +8155,80 @@ func (c *Lightsail) GetKeyPairsRequest(input *GetKeyPairsInput) (req *request.Re // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// GetKeyPairsWithContext is the same as GetKeyPairs with the addition of +// GetInstanceSnapshotsWithContext is the same as GetInstanceSnapshots 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. +// 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) GetKeyPairsWithContext(ctx aws.Context, input *GetKeyPairsInput, opts ...request.Option) (*GetKeyPairsOutput, error) { - req, out := c.GetKeyPairsRequest(input) +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 opGetLoadBalancer = "GetLoadBalancer" +const opGetInstanceState = "GetInstanceState" -// GetLoadBalancerRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancer operation. The "output" return +// GetInstanceStateRequest generates a "aws/request.Request" representing the +// client's request for the GetInstanceState operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetLoadBalancer for more information on using the GetLoadBalancer +// See GetInstanceState for more information on using the GetInstanceState // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetLoadBalancerRequest method. -// req, resp := client.GetLoadBalancerRequest(params) +// // Example sending a request using the GetInstanceStateRequest method. +// req, resp := client.GetInstanceStateRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancer -func (c *Lightsail) GetLoadBalancerRequest(input *GetLoadBalancerInput) (req *request.Request, output *GetLoadBalancerOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceState +func (c *Lightsail) GetInstanceStateRequest(input *GetInstanceStateInput) (req *request.Request, output *GetInstanceStateOutput) { op := &request.Operation{ - Name: opGetLoadBalancer, + Name: opGetInstanceState, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetLoadBalancerInput{} + input = &GetInstanceStateInput{} } - output = &GetLoadBalancerOutput{} + output = &GetInstanceStateOutput{} req = c.newRequest(op, input, output) return } -// GetLoadBalancer API operation for Amazon Lightsail. +// GetInstanceState API operation for Amazon Lightsail. // -// Returns information about the specified Lightsail load balancer. +// Returns the state of a specific instance. Works on one instance at a time. // // Returns awserr.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 Lightsail's -// API operation GetLoadBalancer for usage and error information. +// API operation GetInstanceState for usage and error information. // // Returned Error Types: // * ServiceException @@ -7529,80 +8259,81 @@ func (c *Lightsail) GetLoadBalancerRequest(input *GetLoadBalancerInput) (req *re // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancer -func (c *Lightsail) GetLoadBalancer(input *GetLoadBalancerInput) (*GetLoadBalancerOutput, error) { - req, out := c.GetLoadBalancerRequest(input) +// See also, 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) return out, req.Send() } -// GetLoadBalancerWithContext is the same as GetLoadBalancer with the addition of +// GetInstanceStateWithContext is the same as GetInstanceState with the addition of // the ability to pass a context and additional request options. // -// See GetLoadBalancer for details on how to use this API operation. +// 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) GetLoadBalancerWithContext(ctx aws.Context, input *GetLoadBalancerInput, opts ...request.Option) (*GetLoadBalancerOutput, error) { - req, out := c.GetLoadBalancerRequest(input) +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 opGetLoadBalancerMetricData = "GetLoadBalancerMetricData" +const opGetInstances = "GetInstances" -// GetLoadBalancerMetricDataRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancerMetricData operation. The "output" return +// GetInstancesRequest generates a "aws/request.Request" representing the +// client's request for the GetInstances operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetLoadBalancerMetricData for more information on using the GetLoadBalancerMetricData +// See GetInstances for more information on using the GetInstances // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetLoadBalancerMetricDataRequest method. -// req, resp := client.GetLoadBalancerMetricDataRequest(params) +// // Example sending a request using the GetInstancesRequest method. +// req, resp := client.GetInstancesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerMetricData -func (c *Lightsail) GetLoadBalancerMetricDataRequest(input *GetLoadBalancerMetricDataInput) (req *request.Request, output *GetLoadBalancerMetricDataOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstances +func (c *Lightsail) GetInstancesRequest(input *GetInstancesInput) (req *request.Request, output *GetInstancesOutput) { op := &request.Operation{ - Name: opGetLoadBalancerMetricData, + Name: opGetInstances, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetLoadBalancerMetricDataInput{} + input = &GetInstancesInput{} } - output = &GetLoadBalancerMetricDataOutput{} + output = &GetInstancesOutput{} req = c.newRequest(op, input, output) return } -// GetLoadBalancerMetricData API operation for Amazon Lightsail. +// GetInstances API operation for Amazon Lightsail. // -// Returns information about health metrics for your Lightsail load balancer. +// Returns information about all Amazon Lightsail virtual private servers, or +// 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 // the error. // // See the AWS API reference guide for Amazon Lightsail's -// API operation GetLoadBalancerMetricData for usage and error information. +// API operation GetInstances for usage and error information. // // Returned Error Types: // * ServiceException @@ -7633,86 +8364,80 @@ func (c *Lightsail) GetLoadBalancerMetricDataRequest(input *GetLoadBalancerMetri // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerMetricData -func (c *Lightsail) GetLoadBalancerMetricData(input *GetLoadBalancerMetricDataInput) (*GetLoadBalancerMetricDataOutput, error) { - req, out := c.GetLoadBalancerMetricDataRequest(input) +// See also, 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) return out, req.Send() } -// GetLoadBalancerMetricDataWithContext is the same as GetLoadBalancerMetricData with the addition of +// GetInstancesWithContext is the same as GetInstances with the addition of // the ability to pass a context and additional request options. // -// See GetLoadBalancerMetricData for details on how to use this API operation. +// 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) GetLoadBalancerMetricDataWithContext(ctx aws.Context, input *GetLoadBalancerMetricDataInput, opts ...request.Option) (*GetLoadBalancerMetricDataOutput, error) { - req, out := c.GetLoadBalancerMetricDataRequest(input) +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 opGetLoadBalancerTlsCertificates = "GetLoadBalancerTlsCertificates" +const opGetKeyPair = "GetKeyPair" -// GetLoadBalancerTlsCertificatesRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancerTlsCertificates operation. The "output" return +// GetKeyPairRequest generates a "aws/request.Request" representing the +// client's request for the GetKeyPair operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetLoadBalancerTlsCertificates for more information on using the GetLoadBalancerTlsCertificates +// See GetKeyPair for more information on using the GetKeyPair // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetLoadBalancerTlsCertificatesRequest method. -// req, resp := client.GetLoadBalancerTlsCertificatesRequest(params) +// // Example sending a request using the GetKeyPairRequest method. +// req, resp := client.GetKeyPairRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerTlsCertificates -func (c *Lightsail) GetLoadBalancerTlsCertificatesRequest(input *GetLoadBalancerTlsCertificatesInput) (req *request.Request, output *GetLoadBalancerTlsCertificatesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPair +func (c *Lightsail) GetKeyPairRequest(input *GetKeyPairInput) (req *request.Request, output *GetKeyPairOutput) { op := &request.Operation{ - Name: opGetLoadBalancerTlsCertificates, + Name: opGetKeyPair, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetLoadBalancerTlsCertificatesInput{} + input = &GetKeyPairInput{} } - output = &GetLoadBalancerTlsCertificatesOutput{} + output = &GetKeyPairOutput{} req = c.newRequest(op, input, output) return } -// GetLoadBalancerTlsCertificates API operation for Amazon Lightsail. -// -// Returns information about the TLS certificates that are associated with the -// specified Lightsail load balancer. -// -// TLS is just an updated, more secure version of Secure Socket Layer (SSL). +// GetKeyPair API operation for Amazon Lightsail. // -// You can have a maximum of 2 certificates associated with a Lightsail load -// balancer. One is active and the other is inactive. +// Returns information about a specific key pair. // // Returns awserr.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 Lightsail's -// API operation GetLoadBalancerTlsCertificates for usage and error information. +// API operation GetKeyPair for usage and error information. // // Returned Error Types: // * ServiceException @@ -7743,80 +8468,80 @@ func (c *Lightsail) GetLoadBalancerTlsCertificatesRequest(input *GetLoadBalancer // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerTlsCertificates -func (c *Lightsail) GetLoadBalancerTlsCertificates(input *GetLoadBalancerTlsCertificatesInput) (*GetLoadBalancerTlsCertificatesOutput, error) { - req, out := c.GetLoadBalancerTlsCertificatesRequest(input) +// See also, 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) return out, req.Send() } -// GetLoadBalancerTlsCertificatesWithContext is the same as GetLoadBalancerTlsCertificates with the addition of +// GetKeyPairWithContext is the same as GetKeyPair with the addition of // the ability to pass a context and additional request options. // -// See GetLoadBalancerTlsCertificates for details on how to use this API operation. +// 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) GetLoadBalancerTlsCertificatesWithContext(ctx aws.Context, input *GetLoadBalancerTlsCertificatesInput, opts ...request.Option) (*GetLoadBalancerTlsCertificatesOutput, error) { - req, out := c.GetLoadBalancerTlsCertificatesRequest(input) +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 opGetLoadBalancers = "GetLoadBalancers" +const opGetKeyPairs = "GetKeyPairs" -// GetLoadBalancersRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancers operation. The "output" return +// GetKeyPairsRequest generates a "aws/request.Request" representing the +// client's request for the GetKeyPairs operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetLoadBalancers for more information on using the GetLoadBalancers +// See GetKeyPairs for more information on using the GetKeyPairs // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetLoadBalancersRequest method. -// req, resp := client.GetLoadBalancersRequest(params) +// // Example sending a request using the GetKeyPairsRequest method. +// req, resp := client.GetKeyPairsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancers -func (c *Lightsail) GetLoadBalancersRequest(input *GetLoadBalancersInput) (req *request.Request, output *GetLoadBalancersOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPairs +func (c *Lightsail) GetKeyPairsRequest(input *GetKeyPairsInput) (req *request.Request, output *GetKeyPairsOutput) { op := &request.Operation{ - Name: opGetLoadBalancers, + Name: opGetKeyPairs, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetLoadBalancersInput{} + input = &GetKeyPairsInput{} } - output = &GetLoadBalancersOutput{} + output = &GetKeyPairsOutput{} req = c.newRequest(op, input, output) return } -// GetLoadBalancers API operation for Amazon Lightsail. +// GetKeyPairs API operation for Amazon Lightsail. // -// Returns information about all load balancers in an account. +// Returns information about all key pairs in the user's 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 Amazon Lightsail's -// API operation GetLoadBalancers for usage and error information. +// API operation GetKeyPairs for usage and error information. // // Returned Error Types: // * ServiceException @@ -7847,82 +8572,80 @@ func (c *Lightsail) GetLoadBalancersRequest(input *GetLoadBalancersInput) (req * // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancers -func (c *Lightsail) GetLoadBalancers(input *GetLoadBalancersInput) (*GetLoadBalancersOutput, error) { - req, out := c.GetLoadBalancersRequest(input) +// See also, 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) return out, req.Send() } -// GetLoadBalancersWithContext is the same as GetLoadBalancers with the addition of +// GetKeyPairsWithContext is the same as GetKeyPairs with the addition of // the ability to pass a context and additional request options. // -// See GetLoadBalancers for details on how to use this API operation. +// 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) GetLoadBalancersWithContext(ctx aws.Context, input *GetLoadBalancersInput, opts ...request.Option) (*GetLoadBalancersOutput, error) { - req, out := c.GetLoadBalancersRequest(input) +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" +const opGetLoadBalancer = "GetLoadBalancer" -// GetOperationRequest generates a "aws/request.Request" representing the -// client's request for the GetOperation operation. The "output" return +// GetLoadBalancerRequest generates a "aws/request.Request" representing the +// client's request for the GetLoadBalancer operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetOperation for more information on using the GetOperation +// See GetLoadBalancer for more information on using the GetLoadBalancer // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetOperationRequest method. -// req, resp := client.GetOperationRequest(params) +// // Example sending a request using the GetLoadBalancerRequest method. +// req, resp := client.GetLoadBalancerRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperation -func (c *Lightsail) GetOperationRequest(input *GetOperationInput) (req *request.Request, output *GetOperationOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancer +func (c *Lightsail) GetLoadBalancerRequest(input *GetLoadBalancerInput) (req *request.Request, output *GetLoadBalancerOutput) { op := &request.Operation{ - Name: opGetOperation, + Name: opGetLoadBalancer, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetOperationInput{} + input = &GetLoadBalancerInput{} } - output = &GetOperationOutput{} + output = &GetLoadBalancerOutput{} req = c.newRequest(op, input, output) return } -// GetOperation API operation for Amazon Lightsail. +// GetLoadBalancer API operation for Amazon Lightsail. // -// Returns information about a specific operation. Operations include events -// such as when you create an instance, allocate a static IP, attach a static -// IP, and so on. +// Returns information about the specified Lightsail load balancer. // // Returns awserr.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 Lightsail's -// API operation GetOperation for usage and error information. +// API operation GetLoadBalancer for usage and error information. // // Returned Error Types: // * ServiceException @@ -7953,84 +8676,84 @@ func (c *Lightsail) GetOperationRequest(input *GetOperationInput) (req *request. // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancer +func (c *Lightsail) GetLoadBalancer(input *GetLoadBalancerInput) (*GetLoadBalancerOutput, error) { + req, out := c.GetLoadBalancerRequest(input) return out, req.Send() } -// GetOperationWithContext is the same as GetOperation with the addition of +// GetLoadBalancerWithContext is the same as GetLoadBalancer 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. +// See GetLoadBalancer for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetLoadBalancerWithContext(ctx aws.Context, input *GetLoadBalancerInput, opts ...request.Option) (*GetLoadBalancerOutput, error) { + req, out := c.GetLoadBalancerRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetOperations = "GetOperations" +const opGetLoadBalancerMetricData = "GetLoadBalancerMetricData" -// GetOperationsRequest generates a "aws/request.Request" representing the -// client's request for the GetOperations operation. The "output" return +// GetLoadBalancerMetricDataRequest generates a "aws/request.Request" representing the +// client's request for the GetLoadBalancerMetricData operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetOperations for more information on using the GetOperations +// See GetLoadBalancerMetricData for more information on using the GetLoadBalancerMetricData // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetOperationsRequest method. -// req, resp := client.GetOperationsRequest(params) +// // Example sending a request using the GetLoadBalancerMetricDataRequest method. +// req, resp := client.GetLoadBalancerMetricDataRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperations -func (c *Lightsail) GetOperationsRequest(input *GetOperationsInput) (req *request.Request, output *GetOperationsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerMetricData +func (c *Lightsail) GetLoadBalancerMetricDataRequest(input *GetLoadBalancerMetricDataInput) (req *request.Request, output *GetLoadBalancerMetricDataOutput) { op := &request.Operation{ - Name: opGetOperations, + Name: opGetLoadBalancerMetricData, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetOperationsInput{} + input = &GetLoadBalancerMetricDataInput{} } - output = &GetOperationsOutput{} + output = &GetLoadBalancerMetricDataOutput{} req = c.newRequest(op, input, output) return } -// GetOperations API operation for Amazon Lightsail. +// GetLoadBalancerMetricData API operation for Amazon Lightsail. // -// Returns information about all operations. +// Returns information about health metrics for your Lightsail load balancer. // -// Results are returned from oldest to newest, up to a maximum of 200. Results -// can be paged by making each subsequent call to GetOperations use the maximum -// (last) statusChangedAt value from the previous request. +// Metrics report the utilization of your resources, and the error counts generated +// by them. Monitor and collect metric data regularly to maintain the reliability, +// availability, and performance of your resources. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Lightsail's -// API operation GetOperations for usage and error information. +// API operation GetLoadBalancerMetricData for usage and error information. // // Returned Error Types: // * ServiceException @@ -8061,80 +8784,86 @@ func (c *Lightsail) GetOperationsRequest(input *GetOperationsInput) (req *reques // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerMetricData +func (c *Lightsail) GetLoadBalancerMetricData(input *GetLoadBalancerMetricDataInput) (*GetLoadBalancerMetricDataOutput, error) { + req, out := c.GetLoadBalancerMetricDataRequest(input) return out, req.Send() } -// GetOperationsWithContext is the same as GetOperations with the addition of +// GetLoadBalancerMetricDataWithContext is the same as GetLoadBalancerMetricData 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. +// See GetLoadBalancerMetricData for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetLoadBalancerMetricDataWithContext(ctx aws.Context, input *GetLoadBalancerMetricDataInput, opts ...request.Option) (*GetLoadBalancerMetricDataOutput, error) { + req, out := c.GetLoadBalancerMetricDataRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetOperationsForResource = "GetOperationsForResource" +const opGetLoadBalancerTlsCertificates = "GetLoadBalancerTlsCertificates" -// GetOperationsForResourceRequest generates a "aws/request.Request" representing the -// client's request for the GetOperationsForResource operation. The "output" return +// GetLoadBalancerTlsCertificatesRequest generates a "aws/request.Request" representing the +// client's request for the GetLoadBalancerTlsCertificates operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetOperationsForResource for more information on using the GetOperationsForResource +// See GetLoadBalancerTlsCertificates for more information on using the GetLoadBalancerTlsCertificates // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetOperationsForResourceRequest method. -// req, resp := client.GetOperationsForResourceRequest(params) +// // Example sending a request using the GetLoadBalancerTlsCertificatesRequest method. +// req, resp := client.GetLoadBalancerTlsCertificatesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperationsForResource -func (c *Lightsail) GetOperationsForResourceRequest(input *GetOperationsForResourceInput) (req *request.Request, output *GetOperationsForResourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerTlsCertificates +func (c *Lightsail) GetLoadBalancerTlsCertificatesRequest(input *GetLoadBalancerTlsCertificatesInput) (req *request.Request, output *GetLoadBalancerTlsCertificatesOutput) { op := &request.Operation{ - Name: opGetOperationsForResource, + Name: opGetLoadBalancerTlsCertificates, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetOperationsForResourceInput{} + input = &GetLoadBalancerTlsCertificatesInput{} } - output = &GetOperationsForResourceOutput{} + output = &GetLoadBalancerTlsCertificatesOutput{} req = c.newRequest(op, input, output) return } -// GetOperationsForResource API operation for Amazon Lightsail. +// GetLoadBalancerTlsCertificates API operation for Amazon Lightsail. // -// Gets operations for a specific resource (e.g., an instance or a static IP). +// Returns information about the TLS certificates that are associated with the +// specified Lightsail load balancer. +// +// TLS is just an updated, more secure version of Secure Socket Layer (SSL). +// +// You can have a maximum of 2 certificates associated with a Lightsail load +// balancer. One is active and the other is inactive. // // Returns awserr.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 Lightsail's -// API operation GetOperationsForResource for usage and error information. +// API operation GetLoadBalancerTlsCertificates for usage and error information. // // Returned Error Types: // * ServiceException @@ -8165,81 +8894,80 @@ func (c *Lightsail) GetOperationsForResourceRequest(input *GetOperationsForResou // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerTlsCertificates +func (c *Lightsail) GetLoadBalancerTlsCertificates(input *GetLoadBalancerTlsCertificatesInput) (*GetLoadBalancerTlsCertificatesOutput, error) { + req, out := c.GetLoadBalancerTlsCertificatesRequest(input) return out, req.Send() } -// GetOperationsForResourceWithContext is the same as GetOperationsForResource with the addition of +// GetLoadBalancerTlsCertificatesWithContext is the same as GetLoadBalancerTlsCertificates 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. +// See GetLoadBalancerTlsCertificates for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetLoadBalancerTlsCertificatesWithContext(ctx aws.Context, input *GetLoadBalancerTlsCertificatesInput, opts ...request.Option) (*GetLoadBalancerTlsCertificatesOutput, error) { + req, out := c.GetLoadBalancerTlsCertificatesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetRegions = "GetRegions" +const opGetLoadBalancers = "GetLoadBalancers" -// GetRegionsRequest generates a "aws/request.Request" representing the -// client's request for the GetRegions operation. The "output" return +// GetLoadBalancersRequest generates a "aws/request.Request" representing the +// client's request for the GetLoadBalancers operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRegions for more information on using the GetRegions +// See GetLoadBalancers for more information on using the GetLoadBalancers // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRegionsRequest method. -// req, resp := client.GetRegionsRequest(params) +// // Example sending a request using the GetLoadBalancersRequest method. +// req, resp := client.GetLoadBalancersRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRegions -func (c *Lightsail) GetRegionsRequest(input *GetRegionsInput) (req *request.Request, output *GetRegionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancers +func (c *Lightsail) GetLoadBalancersRequest(input *GetLoadBalancersInput) (req *request.Request, output *GetLoadBalancersOutput) { op := &request.Operation{ - Name: opGetRegions, + Name: opGetLoadBalancers, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRegionsInput{} + input = &GetLoadBalancersInput{} } - output = &GetRegionsOutput{} + output = &GetLoadBalancersOutput{} req = c.newRequest(op, input, output) return } -// GetRegions API operation for Amazon Lightsail. +// GetLoadBalancers API operation for Amazon Lightsail. // -// Returns a list of all valid regions for Amazon Lightsail. Use the include -// availability zones parameter to also return the Availability Zones in a region. +// Returns information about all load balancers in an 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 Amazon Lightsail's -// API operation GetRegions for usage and error information. +// API operation GetLoadBalancers for usage and error information. // // Returned Error Types: // * ServiceException @@ -8270,80 +8998,82 @@ func (c *Lightsail) GetRegionsRequest(input *GetRegionsInput) (req *request.Requ // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancers +func (c *Lightsail) GetLoadBalancers(input *GetLoadBalancersInput) (*GetLoadBalancersOutput, error) { + req, out := c.GetLoadBalancersRequest(input) return out, req.Send() } -// GetRegionsWithContext is the same as GetRegions with the addition of +// GetLoadBalancersWithContext is the same as GetLoadBalancers 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. +// See GetLoadBalancers for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetLoadBalancersWithContext(ctx aws.Context, input *GetLoadBalancersInput, opts ...request.Option) (*GetLoadBalancersOutput, error) { + req, out := c.GetLoadBalancersRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetRelationalDatabase = "GetRelationalDatabase" +const opGetOperation = "GetOperation" -// GetRelationalDatabaseRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabase operation. The "output" return +// GetOperationRequest generates a "aws/request.Request" representing the +// client's request for the GetOperation operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabase for more information on using the GetRelationalDatabase +// See GetOperation for more information on using the GetOperation // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabaseRequest method. -// req, resp := client.GetRelationalDatabaseRequest(params) +// // Example sending a request using the GetOperationRequest method. +// req, resp := client.GetOperationRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabase -func (c *Lightsail) GetRelationalDatabaseRequest(input *GetRelationalDatabaseInput) (req *request.Request, output *GetRelationalDatabaseOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperation +func (c *Lightsail) GetOperationRequest(input *GetOperationInput) (req *request.Request, output *GetOperationOutput) { op := &request.Operation{ - Name: opGetRelationalDatabase, + Name: opGetOperation, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabaseInput{} + input = &GetOperationInput{} } - output = &GetRelationalDatabaseOutput{} + output = &GetOperationOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabase API operation for Amazon Lightsail. +// GetOperation API operation for Amazon Lightsail. // -// Returns information about a specific database in Amazon Lightsail. +// Returns information about a specific operation. Operations include events +// such as when you create an instance, allocate a static IP, attach a static +// IP, and so on. // // Returns awserr.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 Lightsail's -// API operation GetRelationalDatabase for usage and error information. +// API operation GetOperation for usage and error information. // // Returned Error Types: // * ServiceException @@ -8374,84 +9104,84 @@ func (c *Lightsail) GetRelationalDatabaseRequest(input *GetRelationalDatabaseInp // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabase -func (c *Lightsail) GetRelationalDatabase(input *GetRelationalDatabaseInput) (*GetRelationalDatabaseOutput, error) { - req, out := c.GetRelationalDatabaseRequest(input) +// See also, 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) return out, req.Send() } -// GetRelationalDatabaseWithContext is the same as GetRelationalDatabase with the addition of +// GetOperationWithContext is the same as GetOperation with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabase for details on how to use this API operation. +// 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) GetRelationalDatabaseWithContext(ctx aws.Context, input *GetRelationalDatabaseInput, opts ...request.Option) (*GetRelationalDatabaseOutput, error) { - req, out := c.GetRelationalDatabaseRequest(input) +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 opGetRelationalDatabaseBlueprints = "GetRelationalDatabaseBlueprints" +const opGetOperations = "GetOperations" -// GetRelationalDatabaseBlueprintsRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabaseBlueprints operation. The "output" return +// GetOperationsRequest generates a "aws/request.Request" representing the +// client's request for the GetOperations operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabaseBlueprints for more information on using the GetRelationalDatabaseBlueprints +// See GetOperations for more information on using the GetOperations // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabaseBlueprintsRequest method. -// req, resp := client.GetRelationalDatabaseBlueprintsRequest(params) +// // Example sending a request using the GetOperationsRequest method. +// req, resp := client.GetOperationsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseBlueprints -func (c *Lightsail) GetRelationalDatabaseBlueprintsRequest(input *GetRelationalDatabaseBlueprintsInput) (req *request.Request, output *GetRelationalDatabaseBlueprintsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperations +func (c *Lightsail) GetOperationsRequest(input *GetOperationsInput) (req *request.Request, output *GetOperationsOutput) { op := &request.Operation{ - Name: opGetRelationalDatabaseBlueprints, + Name: opGetOperations, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabaseBlueprintsInput{} + input = &GetOperationsInput{} } - output = &GetRelationalDatabaseBlueprintsOutput{} + output = &GetOperationsOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabaseBlueprints API operation for Amazon Lightsail. +// GetOperations API operation for Amazon Lightsail. // -// Returns a list of available database blueprints in Amazon Lightsail. A blueprint -// describes the major engine version of a database. +// Returns information about all operations. // -// You can use a blueprint ID to create a new database that runs a specific -// database engine. +// Results are returned from oldest to newest, up to a maximum of 200. Results +// can be paged by making each subsequent call to GetOperations use the maximum +// (last) statusChangedAt value from the previous 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 Amazon Lightsail's -// API operation GetRelationalDatabaseBlueprints for usage and error information. +// API operation GetOperations for usage and error information. // // Returned Error Types: // * ServiceException @@ -8482,84 +9212,80 @@ func (c *Lightsail) GetRelationalDatabaseBlueprintsRequest(input *GetRelationalD // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseBlueprints -func (c *Lightsail) GetRelationalDatabaseBlueprints(input *GetRelationalDatabaseBlueprintsInput) (*GetRelationalDatabaseBlueprintsOutput, error) { - req, out := c.GetRelationalDatabaseBlueprintsRequest(input) +// See also, 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) return out, req.Send() } -// GetRelationalDatabaseBlueprintsWithContext is the same as GetRelationalDatabaseBlueprints with the addition of +// GetOperationsWithContext is the same as GetOperations with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabaseBlueprints for details on how to use this API operation. +// 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) GetRelationalDatabaseBlueprintsWithContext(ctx aws.Context, input *GetRelationalDatabaseBlueprintsInput, opts ...request.Option) (*GetRelationalDatabaseBlueprintsOutput, error) { - req, out := c.GetRelationalDatabaseBlueprintsRequest(input) +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 opGetRelationalDatabaseBundles = "GetRelationalDatabaseBundles" +const opGetOperationsForResource = "GetOperationsForResource" -// GetRelationalDatabaseBundlesRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabaseBundles operation. The "output" return +// GetOperationsForResourceRequest generates a "aws/request.Request" representing the +// client's request for the GetOperationsForResource operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabaseBundles for more information on using the GetRelationalDatabaseBundles +// See GetOperationsForResource for more information on using the GetOperationsForResource // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabaseBundlesRequest method. -// req, resp := client.GetRelationalDatabaseBundlesRequest(params) +// // Example sending a request using the GetOperationsForResourceRequest method. +// req, resp := client.GetOperationsForResourceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseBundles -func (c *Lightsail) GetRelationalDatabaseBundlesRequest(input *GetRelationalDatabaseBundlesInput) (req *request.Request, output *GetRelationalDatabaseBundlesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperationsForResource +func (c *Lightsail) GetOperationsForResourceRequest(input *GetOperationsForResourceInput) (req *request.Request, output *GetOperationsForResourceOutput) { op := &request.Operation{ - Name: opGetRelationalDatabaseBundles, + Name: opGetOperationsForResource, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabaseBundlesInput{} + input = &GetOperationsForResourceInput{} } - output = &GetRelationalDatabaseBundlesOutput{} + output = &GetOperationsForResourceOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabaseBundles API operation for Amazon Lightsail. -// -// Returns the list of bundles that are available in Amazon Lightsail. A bundle -// describes the performance specifications for a database. +// GetOperationsForResource API operation for Amazon Lightsail. // -// You can use a bundle ID to create a new database with explicit performance -// specifications. +// Gets operations for a specific resource (e.g., an instance or a static IP). // // Returns awserr.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 Lightsail's -// API operation GetRelationalDatabaseBundles for usage and error information. +// API operation GetOperationsForResource for usage and error information. // // Returned Error Types: // * ServiceException @@ -8590,80 +9316,81 @@ func (c *Lightsail) GetRelationalDatabaseBundlesRequest(input *GetRelationalData // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseBundles -func (c *Lightsail) GetRelationalDatabaseBundles(input *GetRelationalDatabaseBundlesInput) (*GetRelationalDatabaseBundlesOutput, error) { - req, out := c.GetRelationalDatabaseBundlesRequest(input) +// See also, 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) return out, req.Send() } -// GetRelationalDatabaseBundlesWithContext is the same as GetRelationalDatabaseBundles with the addition of +// GetOperationsForResourceWithContext is the same as GetOperationsForResource with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabaseBundles for details on how to use this API operation. +// 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) GetRelationalDatabaseBundlesWithContext(ctx aws.Context, input *GetRelationalDatabaseBundlesInput, opts ...request.Option) (*GetRelationalDatabaseBundlesOutput, error) { - req, out := c.GetRelationalDatabaseBundlesRequest(input) +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 opGetRelationalDatabaseEvents = "GetRelationalDatabaseEvents" +const opGetRegions = "GetRegions" -// GetRelationalDatabaseEventsRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabaseEvents operation. The "output" return +// GetRegionsRequest generates a "aws/request.Request" representing the +// client's request for the GetRegions operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabaseEvents for more information on using the GetRelationalDatabaseEvents +// See GetRegions for more information on using the GetRegions // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabaseEventsRequest method. -// req, resp := client.GetRelationalDatabaseEventsRequest(params) +// // Example sending a request using the GetRegionsRequest method. +// req, resp := client.GetRegionsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseEvents -func (c *Lightsail) GetRelationalDatabaseEventsRequest(input *GetRelationalDatabaseEventsInput) (req *request.Request, output *GetRelationalDatabaseEventsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRegions +func (c *Lightsail) GetRegionsRequest(input *GetRegionsInput) (req *request.Request, output *GetRegionsOutput) { op := &request.Operation{ - Name: opGetRelationalDatabaseEvents, + Name: opGetRegions, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabaseEventsInput{} + input = &GetRegionsInput{} } - output = &GetRelationalDatabaseEventsOutput{} + output = &GetRegionsOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabaseEvents API operation for Amazon Lightsail. +// GetRegions API operation for Amazon Lightsail. // -// Returns a list of events for a specific database in Amazon Lightsail. +// Returns a list of all valid regions for Amazon Lightsail. Use the include +// availability zones parameter to also return the Availability Zones in a region. // // Returns awserr.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 Lightsail's -// API operation GetRelationalDatabaseEvents for usage and error information. +// API operation GetRegions for usage and error information. // // Returned Error Types: // * ServiceException @@ -8694,80 +9421,80 @@ func (c *Lightsail) GetRelationalDatabaseEventsRequest(input *GetRelationalDatab // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseEvents -func (c *Lightsail) GetRelationalDatabaseEvents(input *GetRelationalDatabaseEventsInput) (*GetRelationalDatabaseEventsOutput, error) { - req, out := c.GetRelationalDatabaseEventsRequest(input) +// See also, 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) return out, req.Send() } -// GetRelationalDatabaseEventsWithContext is the same as GetRelationalDatabaseEvents with the addition of +// GetRegionsWithContext is the same as GetRegions with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabaseEvents for details on how to use this API operation. +// 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) GetRelationalDatabaseEventsWithContext(ctx aws.Context, input *GetRelationalDatabaseEventsInput, opts ...request.Option) (*GetRelationalDatabaseEventsOutput, error) { - req, out := c.GetRelationalDatabaseEventsRequest(input) +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 opGetRelationalDatabaseLogEvents = "GetRelationalDatabaseLogEvents" +const opGetRelationalDatabase = "GetRelationalDatabase" -// GetRelationalDatabaseLogEventsRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabaseLogEvents operation. The "output" return +// GetRelationalDatabaseRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabase operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabaseLogEvents for more information on using the GetRelationalDatabaseLogEvents +// See GetRelationalDatabase for more information on using the GetRelationalDatabase // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabaseLogEventsRequest method. -// req, resp := client.GetRelationalDatabaseLogEventsRequest(params) +// // Example sending a request using the GetRelationalDatabaseRequest method. +// req, resp := client.GetRelationalDatabaseRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseLogEvents -func (c *Lightsail) GetRelationalDatabaseLogEventsRequest(input *GetRelationalDatabaseLogEventsInput) (req *request.Request, output *GetRelationalDatabaseLogEventsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabase +func (c *Lightsail) GetRelationalDatabaseRequest(input *GetRelationalDatabaseInput) (req *request.Request, output *GetRelationalDatabaseOutput) { op := &request.Operation{ - Name: opGetRelationalDatabaseLogEvents, + Name: opGetRelationalDatabase, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabaseLogEventsInput{} + input = &GetRelationalDatabaseInput{} } - output = &GetRelationalDatabaseLogEventsOutput{} + output = &GetRelationalDatabaseOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabaseLogEvents API operation for Amazon Lightsail. +// GetRelationalDatabase API operation for Amazon Lightsail. // -// Returns a list of log events for a database in Amazon Lightsail. +// Returns information about a specific database in Amazon Lightsail. // // Returns awserr.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 Lightsail's -// API operation GetRelationalDatabaseLogEvents for usage and error information. +// API operation GetRelationalDatabase for usage and error information. // // Returned Error Types: // * ServiceException @@ -8798,81 +9525,84 @@ func (c *Lightsail) GetRelationalDatabaseLogEventsRequest(input *GetRelationalDa // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseLogEvents -func (c *Lightsail) GetRelationalDatabaseLogEvents(input *GetRelationalDatabaseLogEventsInput) (*GetRelationalDatabaseLogEventsOutput, error) { - req, out := c.GetRelationalDatabaseLogEventsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabase +func (c *Lightsail) GetRelationalDatabase(input *GetRelationalDatabaseInput) (*GetRelationalDatabaseOutput, error) { + req, out := c.GetRelationalDatabaseRequest(input) return out, req.Send() } -// GetRelationalDatabaseLogEventsWithContext is the same as GetRelationalDatabaseLogEvents with the addition of +// GetRelationalDatabaseWithContext is the same as GetRelationalDatabase with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabaseLogEvents for details on how to use this API operation. +// See GetRelationalDatabase for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) GetRelationalDatabaseLogEventsWithContext(ctx aws.Context, input *GetRelationalDatabaseLogEventsInput, opts ...request.Option) (*GetRelationalDatabaseLogEventsOutput, error) { - req, out := c.GetRelationalDatabaseLogEventsRequest(input) +func (c *Lightsail) GetRelationalDatabaseWithContext(ctx aws.Context, input *GetRelationalDatabaseInput, opts ...request.Option) (*GetRelationalDatabaseOutput, error) { + req, out := c.GetRelationalDatabaseRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetRelationalDatabaseLogStreams = "GetRelationalDatabaseLogStreams" +const opGetRelationalDatabaseBlueprints = "GetRelationalDatabaseBlueprints" -// GetRelationalDatabaseLogStreamsRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabaseLogStreams operation. The "output" return +// GetRelationalDatabaseBlueprintsRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabaseBlueprints operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabaseLogStreams for more information on using the GetRelationalDatabaseLogStreams +// See GetRelationalDatabaseBlueprints for more information on using the GetRelationalDatabaseBlueprints // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabaseLogStreamsRequest method. -// req, resp := client.GetRelationalDatabaseLogStreamsRequest(params) +// // Example sending a request using the GetRelationalDatabaseBlueprintsRequest method. +// req, resp := client.GetRelationalDatabaseBlueprintsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseLogStreams -func (c *Lightsail) GetRelationalDatabaseLogStreamsRequest(input *GetRelationalDatabaseLogStreamsInput) (req *request.Request, output *GetRelationalDatabaseLogStreamsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseBlueprints +func (c *Lightsail) GetRelationalDatabaseBlueprintsRequest(input *GetRelationalDatabaseBlueprintsInput) (req *request.Request, output *GetRelationalDatabaseBlueprintsOutput) { op := &request.Operation{ - Name: opGetRelationalDatabaseLogStreams, + Name: opGetRelationalDatabaseBlueprints, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabaseLogStreamsInput{} + input = &GetRelationalDatabaseBlueprintsInput{} } - output = &GetRelationalDatabaseLogStreamsOutput{} + output = &GetRelationalDatabaseBlueprintsOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabaseLogStreams API operation for Amazon Lightsail. +// GetRelationalDatabaseBlueprints API operation for Amazon Lightsail. // -// Returns a list of available log streams for a specific database in Amazon -// Lightsail. +// Returns a list of available database blueprints in Amazon Lightsail. A blueprint +// describes the major engine version of a database. +// +// You can use a blueprint ID to create a new database that runs a specific +// database engine. // // Returns awserr.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 Lightsail's -// API operation GetRelationalDatabaseLogStreams for usage and error information. +// API operation GetRelationalDatabaseBlueprints for usage and error information. // // Returned Error Types: // * ServiceException @@ -8903,84 +9633,84 @@ func (c *Lightsail) GetRelationalDatabaseLogStreamsRequest(input *GetRelationalD // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseLogStreams -func (c *Lightsail) GetRelationalDatabaseLogStreams(input *GetRelationalDatabaseLogStreamsInput) (*GetRelationalDatabaseLogStreamsOutput, error) { - req, out := c.GetRelationalDatabaseLogStreamsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseBlueprints +func (c *Lightsail) GetRelationalDatabaseBlueprints(input *GetRelationalDatabaseBlueprintsInput) (*GetRelationalDatabaseBlueprintsOutput, error) { + req, out := c.GetRelationalDatabaseBlueprintsRequest(input) return out, req.Send() } -// GetRelationalDatabaseLogStreamsWithContext is the same as GetRelationalDatabaseLogStreams with the addition of +// GetRelationalDatabaseBlueprintsWithContext is the same as GetRelationalDatabaseBlueprints with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabaseLogStreams for details on how to use this API operation. +// See GetRelationalDatabaseBlueprints for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) GetRelationalDatabaseLogStreamsWithContext(ctx aws.Context, input *GetRelationalDatabaseLogStreamsInput, opts ...request.Option) (*GetRelationalDatabaseLogStreamsOutput, error) { - req, out := c.GetRelationalDatabaseLogStreamsRequest(input) +func (c *Lightsail) GetRelationalDatabaseBlueprintsWithContext(ctx aws.Context, input *GetRelationalDatabaseBlueprintsInput, opts ...request.Option) (*GetRelationalDatabaseBlueprintsOutput, error) { + req, out := c.GetRelationalDatabaseBlueprintsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetRelationalDatabaseMasterUserPassword = "GetRelationalDatabaseMasterUserPassword" +const opGetRelationalDatabaseBundles = "GetRelationalDatabaseBundles" -// GetRelationalDatabaseMasterUserPasswordRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabaseMasterUserPassword operation. The "output" return +// GetRelationalDatabaseBundlesRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabaseBundles operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabaseMasterUserPassword for more information on using the GetRelationalDatabaseMasterUserPassword +// See GetRelationalDatabaseBundles for more information on using the GetRelationalDatabaseBundles // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabaseMasterUserPasswordRequest method. -// req, resp := client.GetRelationalDatabaseMasterUserPasswordRequest(params) +// // Example sending a request using the GetRelationalDatabaseBundlesRequest method. +// req, resp := client.GetRelationalDatabaseBundlesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseMasterUserPassword -func (c *Lightsail) GetRelationalDatabaseMasterUserPasswordRequest(input *GetRelationalDatabaseMasterUserPasswordInput) (req *request.Request, output *GetRelationalDatabaseMasterUserPasswordOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseBundles +func (c *Lightsail) GetRelationalDatabaseBundlesRequest(input *GetRelationalDatabaseBundlesInput) (req *request.Request, output *GetRelationalDatabaseBundlesOutput) { op := &request.Operation{ - Name: opGetRelationalDatabaseMasterUserPassword, + Name: opGetRelationalDatabaseBundles, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabaseMasterUserPasswordInput{} + input = &GetRelationalDatabaseBundlesInput{} } - output = &GetRelationalDatabaseMasterUserPasswordOutput{} + output = &GetRelationalDatabaseBundlesOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabaseMasterUserPassword API operation for Amazon Lightsail. +// GetRelationalDatabaseBundles API operation for Amazon Lightsail. // -// Returns the current, previous, or pending versions of the master user password -// for a Lightsail database. +// Returns the list of bundles that are available in Amazon Lightsail. A bundle +// describes the performance specifications for a database. // -// The GetRelationalDatabaseMasterUserPassword operation supports tag-based -// access control via resource tags applied to the resource identified by relationalDatabaseName. +// You can use a bundle ID to create a new database with explicit performance +// specifications. // // Returns awserr.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 Lightsail's -// API operation GetRelationalDatabaseMasterUserPassword for usage and error information. +// API operation GetRelationalDatabaseBundles for usage and error information. // // Returned Error Types: // * ServiceException @@ -9011,81 +9741,80 @@ func (c *Lightsail) GetRelationalDatabaseMasterUserPasswordRequest(input *GetRel // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseMasterUserPassword -func (c *Lightsail) GetRelationalDatabaseMasterUserPassword(input *GetRelationalDatabaseMasterUserPasswordInput) (*GetRelationalDatabaseMasterUserPasswordOutput, error) { - req, out := c.GetRelationalDatabaseMasterUserPasswordRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseBundles +func (c *Lightsail) GetRelationalDatabaseBundles(input *GetRelationalDatabaseBundlesInput) (*GetRelationalDatabaseBundlesOutput, error) { + req, out := c.GetRelationalDatabaseBundlesRequest(input) return out, req.Send() } -// GetRelationalDatabaseMasterUserPasswordWithContext is the same as GetRelationalDatabaseMasterUserPassword with the addition of +// GetRelationalDatabaseBundlesWithContext is the same as GetRelationalDatabaseBundles with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabaseMasterUserPassword for details on how to use this API operation. +// See GetRelationalDatabaseBundles for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) GetRelationalDatabaseMasterUserPasswordWithContext(ctx aws.Context, input *GetRelationalDatabaseMasterUserPasswordInput, opts ...request.Option) (*GetRelationalDatabaseMasterUserPasswordOutput, error) { - req, out := c.GetRelationalDatabaseMasterUserPasswordRequest(input) +func (c *Lightsail) GetRelationalDatabaseBundlesWithContext(ctx aws.Context, input *GetRelationalDatabaseBundlesInput, opts ...request.Option) (*GetRelationalDatabaseBundlesOutput, error) { + req, out := c.GetRelationalDatabaseBundlesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetRelationalDatabaseMetricData = "GetRelationalDatabaseMetricData" +const opGetRelationalDatabaseEvents = "GetRelationalDatabaseEvents" -// GetRelationalDatabaseMetricDataRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabaseMetricData operation. The "output" return +// GetRelationalDatabaseEventsRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabaseEvents operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabaseMetricData for more information on using the GetRelationalDatabaseMetricData +// See GetRelationalDatabaseEvents for more information on using the GetRelationalDatabaseEvents // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabaseMetricDataRequest method. -// req, resp := client.GetRelationalDatabaseMetricDataRequest(params) +// // Example sending a request using the GetRelationalDatabaseEventsRequest method. +// req, resp := client.GetRelationalDatabaseEventsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseMetricData -func (c *Lightsail) GetRelationalDatabaseMetricDataRequest(input *GetRelationalDatabaseMetricDataInput) (req *request.Request, output *GetRelationalDatabaseMetricDataOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseEvents +func (c *Lightsail) GetRelationalDatabaseEventsRequest(input *GetRelationalDatabaseEventsInput) (req *request.Request, output *GetRelationalDatabaseEventsOutput) { op := &request.Operation{ - Name: opGetRelationalDatabaseMetricData, + Name: opGetRelationalDatabaseEvents, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabaseMetricDataInput{} + input = &GetRelationalDatabaseEventsInput{} } - output = &GetRelationalDatabaseMetricDataOutput{} + output = &GetRelationalDatabaseEventsOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabaseMetricData API operation for Amazon Lightsail. +// GetRelationalDatabaseEvents API operation for Amazon Lightsail. // -// Returns the data points of the specified metric for a database in Amazon -// Lightsail. +// Returns a list of events for a specific database in Amazon Lightsail. // // Returns awserr.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 Lightsail's -// API operation GetRelationalDatabaseMetricData for usage and error information. +// API operation GetRelationalDatabaseEvents for usage and error information. // // Returned Error Types: // * ServiceException @@ -9116,86 +9845,80 @@ func (c *Lightsail) GetRelationalDatabaseMetricDataRequest(input *GetRelationalD // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseMetricData -func (c *Lightsail) GetRelationalDatabaseMetricData(input *GetRelationalDatabaseMetricDataInput) (*GetRelationalDatabaseMetricDataOutput, error) { - req, out := c.GetRelationalDatabaseMetricDataRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseEvents +func (c *Lightsail) GetRelationalDatabaseEvents(input *GetRelationalDatabaseEventsInput) (*GetRelationalDatabaseEventsOutput, error) { + req, out := c.GetRelationalDatabaseEventsRequest(input) return out, req.Send() } -// GetRelationalDatabaseMetricDataWithContext is the same as GetRelationalDatabaseMetricData with the addition of +// GetRelationalDatabaseEventsWithContext is the same as GetRelationalDatabaseEvents with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabaseMetricData for details on how to use this API operation. +// See GetRelationalDatabaseEvents for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) GetRelationalDatabaseMetricDataWithContext(ctx aws.Context, input *GetRelationalDatabaseMetricDataInput, opts ...request.Option) (*GetRelationalDatabaseMetricDataOutput, error) { - req, out := c.GetRelationalDatabaseMetricDataRequest(input) +func (c *Lightsail) GetRelationalDatabaseEventsWithContext(ctx aws.Context, input *GetRelationalDatabaseEventsInput, opts ...request.Option) (*GetRelationalDatabaseEventsOutput, error) { + req, out := c.GetRelationalDatabaseEventsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetRelationalDatabaseParameters = "GetRelationalDatabaseParameters" +const opGetRelationalDatabaseLogEvents = "GetRelationalDatabaseLogEvents" -// GetRelationalDatabaseParametersRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabaseParameters operation. The "output" return +// GetRelationalDatabaseLogEventsRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabaseLogEvents operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabaseParameters for more information on using the GetRelationalDatabaseParameters +// See GetRelationalDatabaseLogEvents for more information on using the GetRelationalDatabaseLogEvents // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabaseParametersRequest method. -// req, resp := client.GetRelationalDatabaseParametersRequest(params) +// // Example sending a request using the GetRelationalDatabaseLogEventsRequest method. +// req, resp := client.GetRelationalDatabaseLogEventsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseParameters -func (c *Lightsail) GetRelationalDatabaseParametersRequest(input *GetRelationalDatabaseParametersInput) (req *request.Request, output *GetRelationalDatabaseParametersOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseLogEvents +func (c *Lightsail) GetRelationalDatabaseLogEventsRequest(input *GetRelationalDatabaseLogEventsInput) (req *request.Request, output *GetRelationalDatabaseLogEventsOutput) { op := &request.Operation{ - Name: opGetRelationalDatabaseParameters, + Name: opGetRelationalDatabaseLogEvents, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabaseParametersInput{} + input = &GetRelationalDatabaseLogEventsInput{} } - output = &GetRelationalDatabaseParametersOutput{} + output = &GetRelationalDatabaseLogEventsOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabaseParameters API operation for Amazon Lightsail. -// -// Returns all of the runtime parameters offered by the underlying database -// software, or engine, for a specific database in Amazon Lightsail. +// GetRelationalDatabaseLogEvents API operation for Amazon Lightsail. // -// In addition to the parameter names and values, this operation returns other -// information about each parameter. This information includes whether changes -// require a reboot, whether the parameter is modifiable, the allowed values, -// and the data types. +// Returns a list of log events for a database in Amazon Lightsail. // // Returns awserr.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 Lightsail's -// API operation GetRelationalDatabaseParameters for usage and error information. +// API operation GetRelationalDatabaseLogEvents for usage and error information. // // Returned Error Types: // * ServiceException @@ -9226,80 +9949,81 @@ func (c *Lightsail) GetRelationalDatabaseParametersRequest(input *GetRelationalD // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseParameters -func (c *Lightsail) GetRelationalDatabaseParameters(input *GetRelationalDatabaseParametersInput) (*GetRelationalDatabaseParametersOutput, error) { - req, out := c.GetRelationalDatabaseParametersRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseLogEvents +func (c *Lightsail) GetRelationalDatabaseLogEvents(input *GetRelationalDatabaseLogEventsInput) (*GetRelationalDatabaseLogEventsOutput, error) { + req, out := c.GetRelationalDatabaseLogEventsRequest(input) return out, req.Send() } -// GetRelationalDatabaseParametersWithContext is the same as GetRelationalDatabaseParameters with the addition of +// GetRelationalDatabaseLogEventsWithContext is the same as GetRelationalDatabaseLogEvents with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabaseParameters for details on how to use this API operation. +// See GetRelationalDatabaseLogEvents for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) GetRelationalDatabaseParametersWithContext(ctx aws.Context, input *GetRelationalDatabaseParametersInput, opts ...request.Option) (*GetRelationalDatabaseParametersOutput, error) { - req, out := c.GetRelationalDatabaseParametersRequest(input) +func (c *Lightsail) GetRelationalDatabaseLogEventsWithContext(ctx aws.Context, input *GetRelationalDatabaseLogEventsInput, opts ...request.Option) (*GetRelationalDatabaseLogEventsOutput, error) { + req, out := c.GetRelationalDatabaseLogEventsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetRelationalDatabaseSnapshot = "GetRelationalDatabaseSnapshot" +const opGetRelationalDatabaseLogStreams = "GetRelationalDatabaseLogStreams" -// GetRelationalDatabaseSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabaseSnapshot operation. The "output" return +// GetRelationalDatabaseLogStreamsRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabaseLogStreams operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabaseSnapshot for more information on using the GetRelationalDatabaseSnapshot +// See GetRelationalDatabaseLogStreams for more information on using the GetRelationalDatabaseLogStreams // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabaseSnapshotRequest method. -// req, resp := client.GetRelationalDatabaseSnapshotRequest(params) +// // Example sending a request using the GetRelationalDatabaseLogStreamsRequest method. +// req, resp := client.GetRelationalDatabaseLogStreamsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseSnapshot -func (c *Lightsail) GetRelationalDatabaseSnapshotRequest(input *GetRelationalDatabaseSnapshotInput) (req *request.Request, output *GetRelationalDatabaseSnapshotOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseLogStreams +func (c *Lightsail) GetRelationalDatabaseLogStreamsRequest(input *GetRelationalDatabaseLogStreamsInput) (req *request.Request, output *GetRelationalDatabaseLogStreamsOutput) { op := &request.Operation{ - Name: opGetRelationalDatabaseSnapshot, + Name: opGetRelationalDatabaseLogStreams, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabaseSnapshotInput{} + input = &GetRelationalDatabaseLogStreamsInput{} } - output = &GetRelationalDatabaseSnapshotOutput{} + output = &GetRelationalDatabaseLogStreamsOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabaseSnapshot API operation for Amazon Lightsail. +// GetRelationalDatabaseLogStreams API operation for Amazon Lightsail. // -// Returns information about a specific database snapshot in Amazon Lightsail. +// Returns a list of available log streams for a specific database in Amazon +// Lightsail. // // Returns awserr.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 Lightsail's -// API operation GetRelationalDatabaseSnapshot for usage and error information. +// API operation GetRelationalDatabaseLogStreams for usage and error information. // // Returned Error Types: // * ServiceException @@ -9330,80 +10054,84 @@ func (c *Lightsail) GetRelationalDatabaseSnapshotRequest(input *GetRelationalDat // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseSnapshot -func (c *Lightsail) GetRelationalDatabaseSnapshot(input *GetRelationalDatabaseSnapshotInput) (*GetRelationalDatabaseSnapshotOutput, error) { - req, out := c.GetRelationalDatabaseSnapshotRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseLogStreams +func (c *Lightsail) GetRelationalDatabaseLogStreams(input *GetRelationalDatabaseLogStreamsInput) (*GetRelationalDatabaseLogStreamsOutput, error) { + req, out := c.GetRelationalDatabaseLogStreamsRequest(input) return out, req.Send() } -// GetRelationalDatabaseSnapshotWithContext is the same as GetRelationalDatabaseSnapshot with the addition of +// GetRelationalDatabaseLogStreamsWithContext is the same as GetRelationalDatabaseLogStreams with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabaseSnapshot for details on how to use this API operation. +// See GetRelationalDatabaseLogStreams for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) GetRelationalDatabaseSnapshotWithContext(ctx aws.Context, input *GetRelationalDatabaseSnapshotInput, opts ...request.Option) (*GetRelationalDatabaseSnapshotOutput, error) { - req, out := c.GetRelationalDatabaseSnapshotRequest(input) +func (c *Lightsail) GetRelationalDatabaseLogStreamsWithContext(ctx aws.Context, input *GetRelationalDatabaseLogStreamsInput, opts ...request.Option) (*GetRelationalDatabaseLogStreamsOutput, error) { + req, out := c.GetRelationalDatabaseLogStreamsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetRelationalDatabaseSnapshots = "GetRelationalDatabaseSnapshots" +const opGetRelationalDatabaseMasterUserPassword = "GetRelationalDatabaseMasterUserPassword" -// GetRelationalDatabaseSnapshotsRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabaseSnapshots operation. The "output" return +// GetRelationalDatabaseMasterUserPasswordRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabaseMasterUserPassword operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabaseSnapshots for more information on using the GetRelationalDatabaseSnapshots +// See GetRelationalDatabaseMasterUserPassword for more information on using the GetRelationalDatabaseMasterUserPassword // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabaseSnapshotsRequest method. -// req, resp := client.GetRelationalDatabaseSnapshotsRequest(params) +// // Example sending a request using the GetRelationalDatabaseMasterUserPasswordRequest method. +// req, resp := client.GetRelationalDatabaseMasterUserPasswordRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseSnapshots -func (c *Lightsail) GetRelationalDatabaseSnapshotsRequest(input *GetRelationalDatabaseSnapshotsInput) (req *request.Request, output *GetRelationalDatabaseSnapshotsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseMasterUserPassword +func (c *Lightsail) GetRelationalDatabaseMasterUserPasswordRequest(input *GetRelationalDatabaseMasterUserPasswordInput) (req *request.Request, output *GetRelationalDatabaseMasterUserPasswordOutput) { op := &request.Operation{ - Name: opGetRelationalDatabaseSnapshots, + Name: opGetRelationalDatabaseMasterUserPassword, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabaseSnapshotsInput{} + input = &GetRelationalDatabaseMasterUserPasswordInput{} } - output = &GetRelationalDatabaseSnapshotsOutput{} + output = &GetRelationalDatabaseMasterUserPasswordOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabaseSnapshots API operation for Amazon Lightsail. +// GetRelationalDatabaseMasterUserPassword API operation for Amazon Lightsail. // -// Returns information about all of your database snapshots in Amazon Lightsail. +// Returns the current, previous, or pending versions of the master user password +// for a Lightsail database. +// +// The GetRelationalDatabaseMasterUserPassword operation supports tag-based +// access control via resource tags applied to the resource identified by relationalDatabaseName. // // Returns awserr.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 Lightsail's -// API operation GetRelationalDatabaseSnapshots for usage and error information. +// API operation GetRelationalDatabaseMasterUserPassword for usage and error information. // // Returned Error Types: // * ServiceException @@ -9434,80 +10162,85 @@ func (c *Lightsail) GetRelationalDatabaseSnapshotsRequest(input *GetRelationalDa // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseSnapshots -func (c *Lightsail) GetRelationalDatabaseSnapshots(input *GetRelationalDatabaseSnapshotsInput) (*GetRelationalDatabaseSnapshotsOutput, error) { - req, out := c.GetRelationalDatabaseSnapshotsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseMasterUserPassword +func (c *Lightsail) GetRelationalDatabaseMasterUserPassword(input *GetRelationalDatabaseMasterUserPasswordInput) (*GetRelationalDatabaseMasterUserPasswordOutput, error) { + req, out := c.GetRelationalDatabaseMasterUserPasswordRequest(input) return out, req.Send() } -// GetRelationalDatabaseSnapshotsWithContext is the same as GetRelationalDatabaseSnapshots with the addition of +// GetRelationalDatabaseMasterUserPasswordWithContext is the same as GetRelationalDatabaseMasterUserPassword with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabaseSnapshots for details on how to use this API operation. +// See GetRelationalDatabaseMasterUserPassword for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) GetRelationalDatabaseSnapshotsWithContext(ctx aws.Context, input *GetRelationalDatabaseSnapshotsInput, opts ...request.Option) (*GetRelationalDatabaseSnapshotsOutput, error) { - req, out := c.GetRelationalDatabaseSnapshotsRequest(input) +func (c *Lightsail) GetRelationalDatabaseMasterUserPasswordWithContext(ctx aws.Context, input *GetRelationalDatabaseMasterUserPasswordInput, opts ...request.Option) (*GetRelationalDatabaseMasterUserPasswordOutput, error) { + req, out := c.GetRelationalDatabaseMasterUserPasswordRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetRelationalDatabases = "GetRelationalDatabases" +const opGetRelationalDatabaseMetricData = "GetRelationalDatabaseMetricData" -// GetRelationalDatabasesRequest generates a "aws/request.Request" representing the -// client's request for the GetRelationalDatabases operation. The "output" return +// GetRelationalDatabaseMetricDataRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabaseMetricData operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetRelationalDatabases for more information on using the GetRelationalDatabases +// See GetRelationalDatabaseMetricData for more information on using the GetRelationalDatabaseMetricData // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetRelationalDatabasesRequest method. -// req, resp := client.GetRelationalDatabasesRequest(params) +// // Example sending a request using the GetRelationalDatabaseMetricDataRequest method. +// req, resp := client.GetRelationalDatabaseMetricDataRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabases -func (c *Lightsail) GetRelationalDatabasesRequest(input *GetRelationalDatabasesInput) (req *request.Request, output *GetRelationalDatabasesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseMetricData +func (c *Lightsail) GetRelationalDatabaseMetricDataRequest(input *GetRelationalDatabaseMetricDataInput) (req *request.Request, output *GetRelationalDatabaseMetricDataOutput) { op := &request.Operation{ - Name: opGetRelationalDatabases, + Name: opGetRelationalDatabaseMetricData, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetRelationalDatabasesInput{} + input = &GetRelationalDatabaseMetricDataInput{} } - output = &GetRelationalDatabasesOutput{} + output = &GetRelationalDatabaseMetricDataOutput{} req = c.newRequest(op, input, output) return } -// GetRelationalDatabases API operation for Amazon Lightsail. +// GetRelationalDatabaseMetricData API operation for Amazon Lightsail. // -// Returns information about all of your databases in Amazon Lightsail. +// Returns the data points of the specified metric for a database in Amazon +// Lightsail. +// +// Metrics report the utilization of your resources, and the error counts generated +// by them. Monitor and collect metric data regularly to maintain the reliability, +// availability, and performance of your resources. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Lightsail's -// API operation GetRelationalDatabases for usage and error information. +// API operation GetRelationalDatabaseMetricData for usage and error information. // // Returned Error Types: // * ServiceException @@ -9538,80 +10271,86 @@ func (c *Lightsail) GetRelationalDatabasesRequest(input *GetRelationalDatabasesI // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabases -func (c *Lightsail) GetRelationalDatabases(input *GetRelationalDatabasesInput) (*GetRelationalDatabasesOutput, error) { - req, out := c.GetRelationalDatabasesRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseMetricData +func (c *Lightsail) GetRelationalDatabaseMetricData(input *GetRelationalDatabaseMetricDataInput) (*GetRelationalDatabaseMetricDataOutput, error) { + req, out := c.GetRelationalDatabaseMetricDataRequest(input) return out, req.Send() } -// GetRelationalDatabasesWithContext is the same as GetRelationalDatabases with the addition of +// GetRelationalDatabaseMetricDataWithContext is the same as GetRelationalDatabaseMetricData with the addition of // the ability to pass a context and additional request options. // -// See GetRelationalDatabases for details on how to use this API operation. +// See GetRelationalDatabaseMetricData for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) GetRelationalDatabasesWithContext(ctx aws.Context, input *GetRelationalDatabasesInput, opts ...request.Option) (*GetRelationalDatabasesOutput, error) { - req, out := c.GetRelationalDatabasesRequest(input) +func (c *Lightsail) GetRelationalDatabaseMetricDataWithContext(ctx aws.Context, input *GetRelationalDatabaseMetricDataInput, opts ...request.Option) (*GetRelationalDatabaseMetricDataOutput, error) { + req, out := c.GetRelationalDatabaseMetricDataRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetStaticIp = "GetStaticIp" +const opGetRelationalDatabaseParameters = "GetRelationalDatabaseParameters" -// GetStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the GetStaticIp operation. The "output" return +// GetRelationalDatabaseParametersRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabaseParameters operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetStaticIp for more information on using the GetStaticIp +// See GetRelationalDatabaseParameters for more information on using the GetRelationalDatabaseParameters // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetStaticIpRequest method. -// req, resp := client.GetStaticIpRequest(params) +// // Example sending a request using the GetRelationalDatabaseParametersRequest method. +// req, resp := client.GetRelationalDatabaseParametersRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIp -func (c *Lightsail) GetStaticIpRequest(input *GetStaticIpInput) (req *request.Request, output *GetStaticIpOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseParameters +func (c *Lightsail) GetRelationalDatabaseParametersRequest(input *GetRelationalDatabaseParametersInput) (req *request.Request, output *GetRelationalDatabaseParametersOutput) { op := &request.Operation{ - Name: opGetStaticIp, + Name: opGetRelationalDatabaseParameters, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetStaticIpInput{} + input = &GetRelationalDatabaseParametersInput{} } - output = &GetStaticIpOutput{} + output = &GetRelationalDatabaseParametersOutput{} req = c.newRequest(op, input, output) return } -// GetStaticIp API operation for Amazon Lightsail. +// GetRelationalDatabaseParameters API operation for Amazon Lightsail. // -// Returns information about a specific static IP. +// Returns all of the runtime parameters offered by the underlying database +// software, or engine, for a specific database in Amazon Lightsail. +// +// In addition to the parameter names and values, this operation returns other +// information about each parameter. This information includes whether changes +// require a reboot, whether the parameter is modifiable, the allowed values, +// and the data 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 Amazon Lightsail's -// API operation GetStaticIp for usage and error information. +// API operation GetRelationalDatabaseParameters for usage and error information. // // Returned Error Types: // * ServiceException @@ -9642,80 +10381,80 @@ func (c *Lightsail) GetStaticIpRequest(input *GetStaticIpInput) (req *request.Re // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseParameters +func (c *Lightsail) GetRelationalDatabaseParameters(input *GetRelationalDatabaseParametersInput) (*GetRelationalDatabaseParametersOutput, error) { + req, out := c.GetRelationalDatabaseParametersRequest(input) return out, req.Send() } -// GetStaticIpWithContext is the same as GetStaticIp with the addition of +// GetRelationalDatabaseParametersWithContext is the same as GetRelationalDatabaseParameters 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. +// See GetRelationalDatabaseParameters for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetRelationalDatabaseParametersWithContext(ctx aws.Context, input *GetRelationalDatabaseParametersInput, opts ...request.Option) (*GetRelationalDatabaseParametersOutput, error) { + req, out := c.GetRelationalDatabaseParametersRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetStaticIps = "GetStaticIps" +const opGetRelationalDatabaseSnapshot = "GetRelationalDatabaseSnapshot" -// GetStaticIpsRequest generates a "aws/request.Request" representing the -// client's request for the GetStaticIps operation. The "output" return +// GetRelationalDatabaseSnapshotRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabaseSnapshot operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetStaticIps for more information on using the GetStaticIps +// See GetRelationalDatabaseSnapshot for more information on using the GetRelationalDatabaseSnapshot // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetStaticIpsRequest method. -// req, resp := client.GetStaticIpsRequest(params) +// // Example sending a request using the GetRelationalDatabaseSnapshotRequest method. +// req, resp := client.GetRelationalDatabaseSnapshotRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIps -func (c *Lightsail) GetStaticIpsRequest(input *GetStaticIpsInput) (req *request.Request, output *GetStaticIpsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseSnapshot +func (c *Lightsail) GetRelationalDatabaseSnapshotRequest(input *GetRelationalDatabaseSnapshotInput) (req *request.Request, output *GetRelationalDatabaseSnapshotOutput) { op := &request.Operation{ - Name: opGetStaticIps, + Name: opGetRelationalDatabaseSnapshot, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &GetStaticIpsInput{} + input = &GetRelationalDatabaseSnapshotInput{} } - output = &GetStaticIpsOutput{} + output = &GetRelationalDatabaseSnapshotOutput{} req = c.newRequest(op, input, output) return } -// GetStaticIps API operation for Amazon Lightsail. +// GetRelationalDatabaseSnapshot API operation for Amazon Lightsail. // -// Returns information about all static IPs in the user's account. +// Returns information about a specific database snapshot in Amazon Lightsail. // // Returns awserr.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 Lightsail's -// API operation GetStaticIps for usage and error information. +// API operation GetRelationalDatabaseSnapshot for usage and error information. // // Returned Error Types: // * ServiceException @@ -9746,80 +10485,80 @@ func (c *Lightsail) GetStaticIpsRequest(input *GetStaticIpsInput) (req *request. // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseSnapshot +func (c *Lightsail) GetRelationalDatabaseSnapshot(input *GetRelationalDatabaseSnapshotInput) (*GetRelationalDatabaseSnapshotOutput, error) { + req, out := c.GetRelationalDatabaseSnapshotRequest(input) return out, req.Send() } -// GetStaticIpsWithContext is the same as GetStaticIps with the addition of +// GetRelationalDatabaseSnapshotWithContext is the same as GetRelationalDatabaseSnapshot 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. +// See GetRelationalDatabaseSnapshot for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetRelationalDatabaseSnapshotWithContext(ctx aws.Context, input *GetRelationalDatabaseSnapshotInput, opts ...request.Option) (*GetRelationalDatabaseSnapshotOutput, error) { + req, out := c.GetRelationalDatabaseSnapshotRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opImportKeyPair = "ImportKeyPair" +const opGetRelationalDatabaseSnapshots = "GetRelationalDatabaseSnapshots" -// ImportKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the ImportKeyPair operation. The "output" return +// GetRelationalDatabaseSnapshotsRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabaseSnapshots operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ImportKeyPair for more information on using the ImportKeyPair +// See GetRelationalDatabaseSnapshots for more information on using the GetRelationalDatabaseSnapshots // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ImportKeyPairRequest method. -// req, resp := client.ImportKeyPairRequest(params) +// // Example sending a request using the GetRelationalDatabaseSnapshotsRequest method. +// req, resp := client.GetRelationalDatabaseSnapshotsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ImportKeyPair -func (c *Lightsail) ImportKeyPairRequest(input *ImportKeyPairInput) (req *request.Request, output *ImportKeyPairOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseSnapshots +func (c *Lightsail) GetRelationalDatabaseSnapshotsRequest(input *GetRelationalDatabaseSnapshotsInput) (req *request.Request, output *GetRelationalDatabaseSnapshotsOutput) { op := &request.Operation{ - Name: opImportKeyPair, + Name: opGetRelationalDatabaseSnapshots, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &ImportKeyPairInput{} + input = &GetRelationalDatabaseSnapshotsInput{} } - output = &ImportKeyPairOutput{} + output = &GetRelationalDatabaseSnapshotsOutput{} req = c.newRequest(op, input, output) return } -// ImportKeyPair API operation for Amazon Lightsail. +// GetRelationalDatabaseSnapshots API operation for Amazon Lightsail. // -// Imports a public SSH key from a specific key pair. +// Returns information about all of your database snapshots in Amazon Lightsail. // // Returns awserr.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 Lightsail's -// API operation ImportKeyPair for usage and error information. +// API operation GetRelationalDatabaseSnapshots for usage and error information. // // Returned Error Types: // * ServiceException @@ -9850,80 +10589,80 @@ func (c *Lightsail) ImportKeyPairRequest(input *ImportKeyPairInput) (req *reques // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabaseSnapshots +func (c *Lightsail) GetRelationalDatabaseSnapshots(input *GetRelationalDatabaseSnapshotsInput) (*GetRelationalDatabaseSnapshotsOutput, error) { + req, out := c.GetRelationalDatabaseSnapshotsRequest(input) return out, req.Send() } -// ImportKeyPairWithContext is the same as ImportKeyPair with the addition of +// GetRelationalDatabaseSnapshotsWithContext is the same as GetRelationalDatabaseSnapshots 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. +// See GetRelationalDatabaseSnapshots for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetRelationalDatabaseSnapshotsWithContext(ctx aws.Context, input *GetRelationalDatabaseSnapshotsInput, opts ...request.Option) (*GetRelationalDatabaseSnapshotsOutput, error) { + req, out := c.GetRelationalDatabaseSnapshotsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opIsVpcPeered = "IsVpcPeered" +const opGetRelationalDatabases = "GetRelationalDatabases" -// IsVpcPeeredRequest generates a "aws/request.Request" representing the -// client's request for the IsVpcPeered operation. The "output" return +// GetRelationalDatabasesRequest generates a "aws/request.Request" representing the +// client's request for the GetRelationalDatabases operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See IsVpcPeered for more information on using the IsVpcPeered +// See GetRelationalDatabases for more information on using the GetRelationalDatabases // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the IsVpcPeeredRequest method. -// req, resp := client.IsVpcPeeredRequest(params) +// // Example sending a request using the GetRelationalDatabasesRequest method. +// req, resp := client.GetRelationalDatabasesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/IsVpcPeered -func (c *Lightsail) IsVpcPeeredRequest(input *IsVpcPeeredInput) (req *request.Request, output *IsVpcPeeredOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabases +func (c *Lightsail) GetRelationalDatabasesRequest(input *GetRelationalDatabasesInput) (req *request.Request, output *GetRelationalDatabasesOutput) { op := &request.Operation{ - Name: opIsVpcPeered, + Name: opGetRelationalDatabases, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &IsVpcPeeredInput{} + input = &GetRelationalDatabasesInput{} } - output = &IsVpcPeeredOutput{} + output = &GetRelationalDatabasesOutput{} req = c.newRequest(op, input, output) return } -// IsVpcPeered API operation for Amazon Lightsail. +// GetRelationalDatabases API operation for Amazon Lightsail. // -// Returns a Boolean value indicating whether your Lightsail VPC is peered. +// Returns information about all of your databases in Amazon Lightsail. // // Returns awserr.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 Lightsail's -// API operation IsVpcPeered for usage and error information. +// API operation GetRelationalDatabases for usage and error information. // // Returned Error Types: // * ServiceException @@ -9954,84 +10693,80 @@ func (c *Lightsail) IsVpcPeeredRequest(input *IsVpcPeeredInput) (req *request.Re // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRelationalDatabases +func (c *Lightsail) GetRelationalDatabases(input *GetRelationalDatabasesInput) (*GetRelationalDatabasesOutput, error) { + req, out := c.GetRelationalDatabasesRequest(input) return out, req.Send() } -// IsVpcPeeredWithContext is the same as IsVpcPeered with the addition of +// GetRelationalDatabasesWithContext is the same as GetRelationalDatabases 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. +// See GetRelationalDatabases for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) GetRelationalDatabasesWithContext(ctx aws.Context, input *GetRelationalDatabasesInput, opts ...request.Option) (*GetRelationalDatabasesOutput, error) { + req, out := c.GetRelationalDatabasesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opOpenInstancePublicPorts = "OpenInstancePublicPorts" +const opGetStaticIp = "GetStaticIp" -// OpenInstancePublicPortsRequest generates a "aws/request.Request" representing the -// client's request for the OpenInstancePublicPorts operation. The "output" return +// GetStaticIpRequest generates a "aws/request.Request" representing the +// client's request for the GetStaticIp operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See OpenInstancePublicPorts for more information on using the OpenInstancePublicPorts +// See GetStaticIp for more information on using the GetStaticIp // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the OpenInstancePublicPortsRequest method. -// req, resp := client.OpenInstancePublicPortsRequest(params) +// // Example sending a request using the GetStaticIpRequest method. +// req, resp := client.GetStaticIpRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/OpenInstancePublicPorts -func (c *Lightsail) OpenInstancePublicPortsRequest(input *OpenInstancePublicPortsInput) (req *request.Request, output *OpenInstancePublicPortsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIp +func (c *Lightsail) GetStaticIpRequest(input *GetStaticIpInput) (req *request.Request, output *GetStaticIpOutput) { op := &request.Operation{ - Name: opOpenInstancePublicPorts, + Name: opGetStaticIp, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &OpenInstancePublicPortsInput{} + input = &GetStaticIpInput{} } - output = &OpenInstancePublicPortsOutput{} + output = &GetStaticIpOutput{} req = c.newRequest(op, input, output) return } -// OpenInstancePublicPorts API operation for Amazon Lightsail. -// -// Adds public ports to an Amazon Lightsail instance. +// GetStaticIp API operation for Amazon Lightsail. // -// The open instance public ports operation supports tag-based access control -// via resource tags applied to the resource identified by instance name. For -// more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// Returns information about a specific static IP. // // Returns awserr.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 Lightsail's -// API operation OpenInstancePublicPorts for usage and error information. +// API operation GetStaticIp for usage and error information. // // Returned Error Types: // * ServiceException @@ -10062,80 +10797,80 @@ func (c *Lightsail) OpenInstancePublicPortsRequest(input *OpenInstancePublicPort // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// OpenInstancePublicPortsWithContext is the same as OpenInstancePublicPorts with the addition of +// GetStaticIpWithContext is the same as GetStaticIp 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. +// 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) OpenInstancePublicPortsWithContext(ctx aws.Context, input *OpenInstancePublicPortsInput, opts ...request.Option) (*OpenInstancePublicPortsOutput, error) { - req, out := c.OpenInstancePublicPortsRequest(input) +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 opPeerVpc = "PeerVpc" +const opGetStaticIps = "GetStaticIps" -// PeerVpcRequest generates a "aws/request.Request" representing the -// client's request for the PeerVpc operation. The "output" return +// GetStaticIpsRequest generates a "aws/request.Request" representing the +// client's request for the GetStaticIps operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See PeerVpc for more information on using the PeerVpc +// See GetStaticIps for more information on using the GetStaticIps // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the PeerVpcRequest method. -// req, resp := client.PeerVpcRequest(params) +// // Example sending a request using the GetStaticIpsRequest method. +// req, resp := client.GetStaticIpsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PeerVpc -func (c *Lightsail) PeerVpcRequest(input *PeerVpcInput) (req *request.Request, output *PeerVpcOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIps +func (c *Lightsail) GetStaticIpsRequest(input *GetStaticIpsInput) (req *request.Request, output *GetStaticIpsOutput) { op := &request.Operation{ - Name: opPeerVpc, + Name: opGetStaticIps, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &PeerVpcInput{} + input = &GetStaticIpsInput{} } - output = &PeerVpcOutput{} + output = &GetStaticIpsOutput{} req = c.newRequest(op, input, output) return } -// PeerVpc API operation for Amazon Lightsail. +// GetStaticIps API operation for Amazon Lightsail. // -// Tries to peer the Lightsail VPC with the user's default VPC. +// Returns information about all static IPs in the user's 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 Amazon Lightsail's -// API operation PeerVpc for usage and error information. +// API operation GetStaticIps for usage and error information. // // Returned Error Types: // * ServiceException @@ -10166,93 +10901,80 @@ func (c *Lightsail) PeerVpcRequest(input *PeerVpcInput) (req *request.Request, o // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// PeerVpcWithContext is the same as PeerVpc with the addition of +// GetStaticIpsWithContext is the same as GetStaticIps 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. +// 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) PeerVpcWithContext(ctx aws.Context, input *PeerVpcInput, opts ...request.Option) (*PeerVpcOutput, error) { - req, out := c.PeerVpcRequest(input) +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 opPutAlarm = "PutAlarm" +const opImportKeyPair = "ImportKeyPair" -// PutAlarmRequest generates a "aws/request.Request" representing the -// client's request for the PutAlarm operation. The "output" return +// ImportKeyPairRequest generates a "aws/request.Request" representing the +// client's request for the ImportKeyPair operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See PutAlarm for more information on using the PutAlarm +// See ImportKeyPair for more information on using the ImportKeyPair // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the PutAlarmRequest method. -// req, resp := client.PutAlarmRequest(params) +// // Example sending a request using the ImportKeyPairRequest method. +// req, resp := client.ImportKeyPairRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutAlarm -func (c *Lightsail) PutAlarmRequest(input *PutAlarmInput) (req *request.Request, output *PutAlarmOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ImportKeyPair +func (c *Lightsail) ImportKeyPairRequest(input *ImportKeyPairInput) (req *request.Request, output *ImportKeyPairOutput) { op := &request.Operation{ - Name: opPutAlarm, + Name: opImportKeyPair, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &PutAlarmInput{} + input = &ImportKeyPairInput{} } - output = &PutAlarmOutput{} + output = &ImportKeyPairOutput{} req = c.newRequest(op, input, output) return } -// PutAlarm API operation for Amazon Lightsail. -// -// Creates or updates an alarm, and associates it with the specified metric. -// -// An alarm is used to monitor a single metric for one of your resources. When -// a metric condition is met, the alarm can notify you by email, SMS text message, -// and a banner displayed on the Amazon Lightsail console. For more information, -// see Alarms in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-alarms). -// -// When this action creates an alarm, the alarm state is immediately set to -// INSUFFICIENT_DATA. The alarm is then evaluated and its state is set appropriately. -// Any actions associated with the new state are then executed. +// ImportKeyPair API operation for Amazon Lightsail. // -// When you update an existing alarm, its state is left unchanged, but the update -// completely overwrites the previous configuration of the alarm. The alarm -// is then evaluated with the updated configuration. +// Imports a public SSH key from a specific key pair. // // Returns awserr.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 Lightsail's -// API operation PutAlarm for usage and error information. +// API operation ImportKeyPair for usage and error information. // // Returned Error Types: // * ServiceException @@ -10266,6 +10988,9 @@ func (c *Lightsail) PutAlarmRequest(input *PutAlarmInput) (req *request.Request, // Please set your AWS Region configuration to us-east-1 to create, view, or // edit these resources. // +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// // * OperationFailureException // Lightsail throws this exception when an operation fails to execute. // @@ -10273,91 +10998,87 @@ func (c *Lightsail) PutAlarmRequest(input *PutAlarmInput) (req *request.Request, // Lightsail throws this exception when the user cannot be authenticated or // uses invalid credentials to access a resource. // +// * AccountSetupInProgressException +// Lightsail throws this exception when an account is still in the setup in +// progress state. +// // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// * NotFoundException -// Lightsail throws this exception when it cannot find a resource. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutAlarm -func (c *Lightsail) PutAlarm(input *PutAlarmInput) (*PutAlarmOutput, error) { - req, out := c.PutAlarmRequest(input) +// See also, 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) return out, req.Send() } -// PutAlarmWithContext is the same as PutAlarm with the addition of +// ImportKeyPairWithContext is the same as ImportKeyPair with the addition of // the ability to pass a context and additional request options. // -// See PutAlarm for details on how to use this API operation. +// 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) PutAlarmWithContext(ctx aws.Context, input *PutAlarmInput, opts ...request.Option) (*PutAlarmOutput, error) { - req, out := c.PutAlarmRequest(input) +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 opPutInstancePublicPorts = "PutInstancePublicPorts" +const opIsVpcPeered = "IsVpcPeered" -// PutInstancePublicPortsRequest generates a "aws/request.Request" representing the -// client's request for the PutInstancePublicPorts operation. The "output" return +// IsVpcPeeredRequest generates a "aws/request.Request" representing the +// client's request for the IsVpcPeered operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See PutInstancePublicPorts for more information on using the PutInstancePublicPorts +// See IsVpcPeered for more information on using the IsVpcPeered // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the PutInstancePublicPortsRequest method. -// req, resp := client.PutInstancePublicPortsRequest(params) +// // Example sending a request using the IsVpcPeeredRequest method. +// req, resp := client.IsVpcPeeredRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutInstancePublicPorts -func (c *Lightsail) PutInstancePublicPortsRequest(input *PutInstancePublicPortsInput) (req *request.Request, output *PutInstancePublicPortsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/IsVpcPeered +func (c *Lightsail) IsVpcPeeredRequest(input *IsVpcPeeredInput) (req *request.Request, output *IsVpcPeeredOutput) { op := &request.Operation{ - Name: opPutInstancePublicPorts, + Name: opIsVpcPeered, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &PutInstancePublicPortsInput{} + input = &IsVpcPeeredInput{} } - output = &PutInstancePublicPortsOutput{} + output = &IsVpcPeeredOutput{} req = c.newRequest(op, input, output) return } -// PutInstancePublicPorts API operation for Amazon Lightsail. -// -// Sets the specified open ports for an Amazon Lightsail instance, and closes -// all ports for every protocol not included in the current request. +// IsVpcPeered API operation for Amazon Lightsail. // -// The put instance public ports operation supports tag-based access control -// via resource tags applied to the resource identified by instance name. For -// more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// Returns a Boolean value indicating whether your Lightsail VPC is peered. // // Returns awserr.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 Lightsail's -// API operation PutInstancePublicPorts for usage and error information. +// API operation IsVpcPeered for usage and error information. // // Returned Error Types: // * ServiceException @@ -10388,84 +11109,85 @@ func (c *Lightsail) PutInstancePublicPortsRequest(input *PutInstancePublicPortsI // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutInstancePublicPorts -func (c *Lightsail) PutInstancePublicPorts(input *PutInstancePublicPortsInput) (*PutInstancePublicPortsOutput, error) { - req, out := c.PutInstancePublicPortsRequest(input) +// See also, 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) return out, req.Send() } -// PutInstancePublicPortsWithContext is the same as PutInstancePublicPorts with the addition of +// IsVpcPeeredWithContext is the same as IsVpcPeered with the addition of // the ability to pass a context and additional request options. // -// See PutInstancePublicPorts for details on how to use this API operation. +// 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) PutInstancePublicPortsWithContext(ctx aws.Context, input *PutInstancePublicPortsInput, opts ...request.Option) (*PutInstancePublicPortsOutput, error) { - req, out := c.PutInstancePublicPortsRequest(input) +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 opRebootInstance = "RebootInstance" +const opOpenInstancePublicPorts = "OpenInstancePublicPorts" -// RebootInstanceRequest generates a "aws/request.Request" representing the -// client's request for the RebootInstance operation. The "output" return +// OpenInstancePublicPortsRequest generates a "aws/request.Request" representing the +// client's request for the OpenInstancePublicPorts operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See RebootInstance for more information on using the RebootInstance +// See OpenInstancePublicPorts for more information on using the OpenInstancePublicPorts // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the RebootInstanceRequest method. -// req, resp := client.RebootInstanceRequest(params) +// // Example sending a request using the OpenInstancePublicPortsRequest method. +// req, resp := client.OpenInstancePublicPortsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/RebootInstance -func (c *Lightsail) RebootInstanceRequest(input *RebootInstanceInput) (req *request.Request, output *RebootInstanceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/OpenInstancePublicPorts +func (c *Lightsail) OpenInstancePublicPortsRequest(input *OpenInstancePublicPortsInput) (req *request.Request, output *OpenInstancePublicPortsOutput) { op := &request.Operation{ - Name: opRebootInstance, + Name: opOpenInstancePublicPorts, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &RebootInstanceInput{} + input = &OpenInstancePublicPortsInput{} } - output = &RebootInstanceOutput{} + output = &OpenInstancePublicPortsOutput{} req = c.newRequest(op, input, output) return } -// RebootInstance API operation for Amazon Lightsail. +// OpenInstancePublicPorts API operation for Amazon Lightsail. // -// Restarts a specific instance. +// Opens ports for a specific Amazon Lightsail instance, and specifies the IP +// addresses allowed to connect to the instance through the ports, and the protocol. // -// The reboot instance operation supports tag-based access control via resource -// tags applied to the resource identified by instance name. For more information, -// see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// The OpenInstancePublicPorts action supports tag-based access control via +// resource tags applied to the resource identified by instanceName. For more +// information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // // Returns awserr.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 Lightsail's -// API operation RebootInstance for usage and error information. +// API operation OpenInstancePublicPorts for usage and error information. // // Returned Error Types: // * ServiceException @@ -10496,84 +11218,80 @@ func (c *Lightsail) RebootInstanceRequest(input *RebootInstanceInput) (req *requ // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// RebootInstanceWithContext is the same as RebootInstance with the addition of +// OpenInstancePublicPortsWithContext is the same as OpenInstancePublicPorts 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. +// 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) RebootInstanceWithContext(ctx aws.Context, input *RebootInstanceInput, opts ...request.Option) (*RebootInstanceOutput, error) { - req, out := c.RebootInstanceRequest(input) +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 opRebootRelationalDatabase = "RebootRelationalDatabase" +const opPeerVpc = "PeerVpc" -// RebootRelationalDatabaseRequest generates a "aws/request.Request" representing the -// client's request for the RebootRelationalDatabase operation. The "output" return +// PeerVpcRequest generates a "aws/request.Request" representing the +// client's request for the PeerVpc operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See RebootRelationalDatabase for more information on using the RebootRelationalDatabase +// See PeerVpc for more information on using the PeerVpc // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the RebootRelationalDatabaseRequest method. -// req, resp := client.RebootRelationalDatabaseRequest(params) +// // Example sending a request using the PeerVpcRequest method. +// req, resp := client.PeerVpcRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/RebootRelationalDatabase -func (c *Lightsail) RebootRelationalDatabaseRequest(input *RebootRelationalDatabaseInput) (req *request.Request, output *RebootRelationalDatabaseOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PeerVpc +func (c *Lightsail) PeerVpcRequest(input *PeerVpcInput) (req *request.Request, output *PeerVpcOutput) { op := &request.Operation{ - Name: opRebootRelationalDatabase, + Name: opPeerVpc, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &RebootRelationalDatabaseInput{} + input = &PeerVpcInput{} } - output = &RebootRelationalDatabaseOutput{} + output = &PeerVpcOutput{} req = c.newRequest(op, input, output) return } -// RebootRelationalDatabase API operation for Amazon Lightsail. -// -// Restarts a specific database in Amazon Lightsail. +// PeerVpc API operation for Amazon Lightsail. // -// The reboot relational database operation supports tag-based access control -// via resource tags applied to the resource identified by relationalDatabaseName. -// For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// Tries to peer the Lightsail VPC with the user's default VPC. // // Returns awserr.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 Lightsail's -// API operation RebootRelationalDatabase for usage and error information. +// API operation PeerVpc for usage and error information. // // Returned Error Types: // * ServiceException @@ -10604,80 +11322,93 @@ func (c *Lightsail) RebootRelationalDatabaseRequest(input *RebootRelationalDatab // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/RebootRelationalDatabase -func (c *Lightsail) RebootRelationalDatabase(input *RebootRelationalDatabaseInput) (*RebootRelationalDatabaseOutput, error) { - req, out := c.RebootRelationalDatabaseRequest(input) +// See also, 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) return out, req.Send() } -// RebootRelationalDatabaseWithContext is the same as RebootRelationalDatabase with the addition of +// PeerVpcWithContext is the same as PeerVpc with the addition of // the ability to pass a context and additional request options. // -// See RebootRelationalDatabase for details on how to use this API operation. +// 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) RebootRelationalDatabaseWithContext(ctx aws.Context, input *RebootRelationalDatabaseInput, opts ...request.Option) (*RebootRelationalDatabaseOutput, error) { - req, out := c.RebootRelationalDatabaseRequest(input) +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 opReleaseStaticIp = "ReleaseStaticIp" +const opPutAlarm = "PutAlarm" -// ReleaseStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the ReleaseStaticIp operation. The "output" return +// PutAlarmRequest generates a "aws/request.Request" representing the +// client's request for the PutAlarm operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ReleaseStaticIp for more information on using the ReleaseStaticIp +// See PutAlarm for more information on using the PutAlarm // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ReleaseStaticIpRequest method. -// req, resp := client.ReleaseStaticIpRequest(params) +// // Example sending a request using the PutAlarmRequest method. +// req, resp := client.PutAlarmRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ReleaseStaticIp -func (c *Lightsail) ReleaseStaticIpRequest(input *ReleaseStaticIpInput) (req *request.Request, output *ReleaseStaticIpOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutAlarm +func (c *Lightsail) PutAlarmRequest(input *PutAlarmInput) (req *request.Request, output *PutAlarmOutput) { op := &request.Operation{ - Name: opReleaseStaticIp, + Name: opPutAlarm, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &ReleaseStaticIpInput{} + input = &PutAlarmInput{} } - output = &ReleaseStaticIpOutput{} + output = &PutAlarmOutput{} req = c.newRequest(op, input, output) return } -// ReleaseStaticIp API operation for Amazon Lightsail. +// PutAlarm API operation for Amazon Lightsail. // -// Deletes a specific static IP from your account. +// Creates or updates an alarm, and associates it with the specified metric. +// +// An alarm is used to monitor a single metric for one of your resources. When +// a metric condition is met, the alarm can notify you by email, SMS text message, +// and a banner displayed on the Amazon Lightsail console. For more information, +// see Alarms in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-alarms). +// +// When this action creates an alarm, the alarm state is immediately set to +// INSUFFICIENT_DATA. The alarm is then evaluated and its state is set appropriately. +// Any actions associated with the new state are then executed. +// +// When you update an existing alarm, its state is left unchanged, but the update +// completely overwrites the previous configuration of the alarm. The alarm +// is then evaluated with the updated configuration. // // Returns awserr.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 Lightsail's -// API operation ReleaseStaticIp for usage and error information. +// API operation PutAlarm for usage and error information. // // Returned Error Types: // * ServiceException @@ -10691,9 +11422,6 @@ func (c *Lightsail) ReleaseStaticIpRequest(input *ReleaseStaticIpInput) (req *re // Please set your AWS Region configuration to us-east-1 to create, view, or // edit these resources. // -// * NotFoundException -// Lightsail throws this exception when it cannot find a resource. -// // * OperationFailureException // Lightsail throws this exception when an operation fails to execute. // @@ -10701,101 +11429,95 @@ func (c *Lightsail) ReleaseStaticIpRequest(input *ReleaseStaticIpInput) (req *re // Lightsail throws this exception when the user cannot be authenticated or // uses invalid credentials to access a resource. // -// * AccountSetupInProgressException -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutAlarm +func (c *Lightsail) PutAlarm(input *PutAlarmInput) (*PutAlarmOutput, error) { + req, out := c.PutAlarmRequest(input) return out, req.Send() } -// ReleaseStaticIpWithContext is the same as ReleaseStaticIp with the addition of +// PutAlarmWithContext is the same as PutAlarm 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. +// See PutAlarm for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) PutAlarmWithContext(ctx aws.Context, input *PutAlarmInput, opts ...request.Option) (*PutAlarmOutput, error) { + req, out := c.PutAlarmRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opSendContactMethodVerification = "SendContactMethodVerification" +const opPutInstancePublicPorts = "PutInstancePublicPorts" -// SendContactMethodVerificationRequest generates a "aws/request.Request" representing the -// client's request for the SendContactMethodVerification operation. The "output" return +// PutInstancePublicPortsRequest generates a "aws/request.Request" representing the +// client's request for the PutInstancePublicPorts operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See SendContactMethodVerification for more information on using the SendContactMethodVerification +// See PutInstancePublicPorts for more information on using the PutInstancePublicPorts // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the SendContactMethodVerificationRequest method. -// req, resp := client.SendContactMethodVerificationRequest(params) +// // Example sending a request using the PutInstancePublicPortsRequest method. +// req, resp := client.PutInstancePublicPortsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/SendContactMethodVerification -func (c *Lightsail) SendContactMethodVerificationRequest(input *SendContactMethodVerificationInput) (req *request.Request, output *SendContactMethodVerificationOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutInstancePublicPorts +func (c *Lightsail) PutInstancePublicPortsRequest(input *PutInstancePublicPortsInput) (req *request.Request, output *PutInstancePublicPortsOutput) { op := &request.Operation{ - Name: opSendContactMethodVerification, + Name: opPutInstancePublicPorts, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &SendContactMethodVerificationInput{} + input = &PutInstancePublicPortsInput{} } - output = &SendContactMethodVerificationOutput{} + output = &PutInstancePublicPortsOutput{} req = c.newRequest(op, input, output) return } -// SendContactMethodVerification API operation for Amazon Lightsail. -// -// Sends a verification request to an email contact method to ensure it’s -// owned by the requester. SMS contact methods don’t need to be verified. -// -// A contact method is used to send you notifications about your Amazon Lightsail -// resources. You can add one email address and one mobile phone number contact -// method in each AWS Region. However, SMS text messaging is not supported in -// some AWS Regions, and SMS text messages cannot be sent to some countries/regions. -// For more information, see Notifications in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-notifications). +// PutInstancePublicPorts API operation for Amazon Lightsail. // -// A verification request is sent to the contact method when you initially create -// it. Use this action to send another verification request if a previous verification -// request was deleted, or has expired. +// Opens ports for a specific Amazon Lightsail instance, and specifies the IP +// addresses allowed to connect to the instance through the ports, and the protocol. +// This action also closes all currently open ports that are not included in +// the request. Include all of the ports and the protocols you want to open +// in your PutInstancePublicPortsrequest. Or use the OpenInstancePublicPorts +// action to open ports without closing currently open ports. // -// Notifications are not sent to an email contact method until after it is verified, -// and confirmed as valid. +// The PutInstancePublicPorts action supports tag-based access control via resource +// tags applied to the resource identified by instanceName. For more information, +// see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // // Returns awserr.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 Lightsail's -// API operation SendContactMethodVerification for usage and error information. +// API operation PutInstancePublicPorts for usage and error information. // // Returned Error Types: // * ServiceException @@ -10809,94 +11531,92 @@ func (c *Lightsail) SendContactMethodVerificationRequest(input *SendContactMetho // Please set your AWS Region configuration to us-east-1 to create, view, or // edit these resources. // +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// // * OperationFailureException // Lightsail throws this exception when an operation fails to execute. // -// * UnauthenticatedException -// Lightsail throws this exception when the user has not been authenticated. -// // * AccessDeniedException // Lightsail throws this exception when the user cannot be authenticated or // uses invalid credentials to access a resource. // -// * NotFoundException -// Lightsail throws this exception when it cannot find a resource. +// * AccountSetupInProgressException +// Lightsail throws this exception when an account is still in the setup in +// progress state. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/SendContactMethodVerification -func (c *Lightsail) SendContactMethodVerification(input *SendContactMethodVerificationInput) (*SendContactMethodVerificationOutput, error) { - req, out := c.SendContactMethodVerificationRequest(input) +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutInstancePublicPorts +func (c *Lightsail) PutInstancePublicPorts(input *PutInstancePublicPortsInput) (*PutInstancePublicPortsOutput, error) { + req, out := c.PutInstancePublicPortsRequest(input) return out, req.Send() } -// SendContactMethodVerificationWithContext is the same as SendContactMethodVerification with the addition of +// PutInstancePublicPortsWithContext is the same as PutInstancePublicPorts with the addition of // the ability to pass a context and additional request options. // -// See SendContactMethodVerification for details on how to use this API operation. +// See PutInstancePublicPorts for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) SendContactMethodVerificationWithContext(ctx aws.Context, input *SendContactMethodVerificationInput, opts ...request.Option) (*SendContactMethodVerificationOutput, error) { - req, out := c.SendContactMethodVerificationRequest(input) +func (c *Lightsail) PutInstancePublicPortsWithContext(ctx aws.Context, input *PutInstancePublicPortsInput, opts ...request.Option) (*PutInstancePublicPortsOutput, error) { + req, out := c.PutInstancePublicPortsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opStartInstance = "StartInstance" +const opRebootInstance = "RebootInstance" -// StartInstanceRequest generates a "aws/request.Request" representing the -// client's request for the StartInstance operation. The "output" return +// RebootInstanceRequest generates a "aws/request.Request" representing the +// client's request for the RebootInstance operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See StartInstance for more information on using the StartInstance +// See RebootInstance for more information on using the RebootInstance // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the StartInstanceRequest method. -// req, resp := client.StartInstanceRequest(params) +// // Example sending a request using the RebootInstanceRequest method. +// req, resp := client.RebootInstanceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StartInstance -func (c *Lightsail) StartInstanceRequest(input *StartInstanceInput) (req *request.Request, output *StartInstanceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/RebootInstance +func (c *Lightsail) RebootInstanceRequest(input *RebootInstanceInput) (req *request.Request, output *RebootInstanceOutput) { op := &request.Operation{ - Name: opStartInstance, + Name: opRebootInstance, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &StartInstanceInput{} + input = &RebootInstanceInput{} } - output = &StartInstanceOutput{} + output = &RebootInstanceOutput{} req = c.newRequest(op, input, output) return } -// StartInstance API operation for Amazon Lightsail. -// -// Starts a specific Amazon Lightsail instance from a stopped state. To restart -// an instance, use the reboot instance operation. +// RebootInstance API operation for Amazon Lightsail. // -// When you start a stopped instance, Lightsail assigns a new public IP address -// to the instance. To use the same IP address after stopping and starting an -// instance, create a static IP address and attach it to the instance. For more -// information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/lightsail-create-static-ip). +// Restarts a specific instance. // -// The start instance operation supports tag-based access control via resource +// The reboot instance operation supports tag-based access control via resource // tags applied to the resource identified by instance name. For more information, // see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // @@ -10905,7 +11625,7 @@ func (c *Lightsail) StartInstanceRequest(input *StartInstanceInput) (req *reques // the error. // // See the AWS API reference guide for Amazon Lightsail's -// API operation StartInstance for usage and error information. +// API operation RebootInstance for usage and error information. // // Returned Error Types: // * ServiceException @@ -10936,76 +11656,75 @@ func (c *Lightsail) StartInstanceRequest(input *StartInstanceInput) (req *reques // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// StartInstanceWithContext is the same as StartInstance with the addition of +// RebootInstanceWithContext is the same as RebootInstance 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. +// 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) StartInstanceWithContext(ctx aws.Context, input *StartInstanceInput, opts ...request.Option) (*StartInstanceOutput, error) { - req, out := c.StartInstanceRequest(input) +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 opStartRelationalDatabase = "StartRelationalDatabase" +const opRebootRelationalDatabase = "RebootRelationalDatabase" -// StartRelationalDatabaseRequest generates a "aws/request.Request" representing the -// client's request for the StartRelationalDatabase operation. The "output" return +// RebootRelationalDatabaseRequest generates a "aws/request.Request" representing the +// client's request for the RebootRelationalDatabase operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See StartRelationalDatabase for more information on using the StartRelationalDatabase +// See RebootRelationalDatabase for more information on using the RebootRelationalDatabase // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the StartRelationalDatabaseRequest method. -// req, resp := client.StartRelationalDatabaseRequest(params) +// // Example sending a request using the RebootRelationalDatabaseRequest method. +// req, resp := client.RebootRelationalDatabaseRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StartRelationalDatabase -func (c *Lightsail) StartRelationalDatabaseRequest(input *StartRelationalDatabaseInput) (req *request.Request, output *StartRelationalDatabaseOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/RebootRelationalDatabase +func (c *Lightsail) RebootRelationalDatabaseRequest(input *RebootRelationalDatabaseInput) (req *request.Request, output *RebootRelationalDatabaseOutput) { op := &request.Operation{ - Name: opStartRelationalDatabase, + Name: opRebootRelationalDatabase, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &StartRelationalDatabaseInput{} + input = &RebootRelationalDatabaseInput{} } - output = &StartRelationalDatabaseOutput{} + output = &RebootRelationalDatabaseOutput{} req = c.newRequest(op, input, output) return } -// StartRelationalDatabase API operation for Amazon Lightsail. +// RebootRelationalDatabase API operation for Amazon Lightsail. // -// Starts a specific database from a stopped state in Amazon Lightsail. To restart -// a database, use the reboot relational database operation. +// Restarts a specific database in Amazon Lightsail. // -// The start relational database operation supports tag-based access control +// The reboot relational database operation supports tag-based access control // via resource tags applied to the resource identified by relationalDatabaseName. // For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // @@ -11014,7 +11733,7 @@ func (c *Lightsail) StartRelationalDatabaseRequest(input *StartRelationalDatabas // the error. // // See the AWS API reference guide for Amazon Lightsail's -// API operation StartRelationalDatabase for usage and error information. +// API operation RebootRelationalDatabase for usage and error information. // // Returned Error Types: // * ServiceException @@ -11045,89 +11764,80 @@ func (c *Lightsail) StartRelationalDatabaseRequest(input *StartRelationalDatabas // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StartRelationalDatabase -func (c *Lightsail) StartRelationalDatabase(input *StartRelationalDatabaseInput) (*StartRelationalDatabaseOutput, error) { - req, out := c.StartRelationalDatabaseRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/RebootRelationalDatabase +func (c *Lightsail) RebootRelationalDatabase(input *RebootRelationalDatabaseInput) (*RebootRelationalDatabaseOutput, error) { + req, out := c.RebootRelationalDatabaseRequest(input) return out, req.Send() } -// StartRelationalDatabaseWithContext is the same as StartRelationalDatabase with the addition of +// RebootRelationalDatabaseWithContext is the same as RebootRelationalDatabase with the addition of // the ability to pass a context and additional request options. // -// See StartRelationalDatabase for details on how to use this API operation. +// See RebootRelationalDatabase for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) StartRelationalDatabaseWithContext(ctx aws.Context, input *StartRelationalDatabaseInput, opts ...request.Option) (*StartRelationalDatabaseOutput, error) { - req, out := c.StartRelationalDatabaseRequest(input) +func (c *Lightsail) RebootRelationalDatabaseWithContext(ctx aws.Context, input *RebootRelationalDatabaseInput, opts ...request.Option) (*RebootRelationalDatabaseOutput, error) { + req, out := c.RebootRelationalDatabaseRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opStopInstance = "StopInstance" +const opReleaseStaticIp = "ReleaseStaticIp" -// StopInstanceRequest generates a "aws/request.Request" representing the -// client's request for the StopInstance operation. The "output" return +// ReleaseStaticIpRequest generates a "aws/request.Request" representing the +// client's request for the ReleaseStaticIp operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See StopInstance for more information on using the StopInstance +// See ReleaseStaticIp for more information on using the ReleaseStaticIp // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the StopInstanceRequest method. -// req, resp := client.StopInstanceRequest(params) +// // Example sending a request using the ReleaseStaticIpRequest method. +// req, resp := client.ReleaseStaticIpRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StopInstance -func (c *Lightsail) StopInstanceRequest(input *StopInstanceInput) (req *request.Request, output *StopInstanceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ReleaseStaticIp +func (c *Lightsail) ReleaseStaticIpRequest(input *ReleaseStaticIpInput) (req *request.Request, output *ReleaseStaticIpOutput) { op := &request.Operation{ - Name: opStopInstance, + Name: opReleaseStaticIp, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &StopInstanceInput{} + input = &ReleaseStaticIpInput{} } - output = &StopInstanceOutput{} + output = &ReleaseStaticIpOutput{} req = c.newRequest(op, input, output) return } -// StopInstance API operation for Amazon Lightsail. -// -// Stops a specific Amazon Lightsail instance that is currently running. -// -// When you start a stopped instance, Lightsail assigns a new public IP address -// to the instance. To use the same IP address after stopping and starting an -// instance, create a static IP address and attach it to the instance. For more -// information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/lightsail-create-static-ip). +// ReleaseStaticIp API operation for Amazon Lightsail. // -// The stop instance operation supports tag-based access control via resource -// tags applied to the resource identified by instance name. For more information, -// see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// Deletes a specific static IP from your account. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon Lightsail's -// API operation StopInstance for usage and error information. +// API operation ReleaseStaticIp for usage and error information. // // Returned Error Types: // * ServiceException @@ -11158,84 +11868,84 @@ func (c *Lightsail) StopInstanceRequest(input *StopInstanceInput) (req *request. // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, 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) return out, req.Send() } -// StopInstanceWithContext is the same as StopInstance with the addition of +// ReleaseStaticIpWithContext is the same as ReleaseStaticIp 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. +// 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) StopInstanceWithContext(ctx aws.Context, input *StopInstanceInput, opts ...request.Option) (*StopInstanceOutput, error) { - req, out := c.StopInstanceRequest(input) +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 opStopRelationalDatabase = "StopRelationalDatabase" +const opResetDistributionCache = "ResetDistributionCache" -// StopRelationalDatabaseRequest generates a "aws/request.Request" representing the -// client's request for the StopRelationalDatabase operation. The "output" return +// ResetDistributionCacheRequest generates a "aws/request.Request" representing the +// client's request for the ResetDistributionCache operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See StopRelationalDatabase for more information on using the StopRelationalDatabase +// See ResetDistributionCache for more information on using the ResetDistributionCache // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the StopRelationalDatabaseRequest method. -// req, resp := client.StopRelationalDatabaseRequest(params) +// // Example sending a request using the ResetDistributionCacheRequest method. +// req, resp := client.ResetDistributionCacheRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StopRelationalDatabase -func (c *Lightsail) StopRelationalDatabaseRequest(input *StopRelationalDatabaseInput) (req *request.Request, output *StopRelationalDatabaseOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ResetDistributionCache +func (c *Lightsail) ResetDistributionCacheRequest(input *ResetDistributionCacheInput) (req *request.Request, output *ResetDistributionCacheOutput) { op := &request.Operation{ - Name: opStopRelationalDatabase, + Name: opResetDistributionCache, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &StopRelationalDatabaseInput{} + input = &ResetDistributionCacheInput{} } - output = &StopRelationalDatabaseOutput{} + output = &ResetDistributionCacheOutput{} req = c.newRequest(op, input, output) return } -// StopRelationalDatabase API operation for Amazon Lightsail. +// ResetDistributionCache API operation for Amazon Lightsail. // -// Stops a specific database that is currently running in Amazon Lightsail. +// Deletes currently cached content from your Amazon Lightsail content delivery +// network (CDN) distribution. // -// The stop relational database operation supports tag-based access control -// via resource tags applied to the resource identified by relationalDatabaseName. -// For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// After resetting the cache, the next time a content request is made, your +// distribution pulls, serves, and caches it from the origin. // // Returns awserr.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 Lightsail's -// API operation StopRelationalDatabase for usage and error information. +// API operation ResetDistributionCache for usage and error information. // // Returned Error Types: // * ServiceException @@ -11259,94 +11969,97 @@ func (c *Lightsail) StopRelationalDatabaseRequest(input *StopRelationalDatabaseI // Lightsail throws this exception when the user cannot be authenticated or // uses invalid credentials to access a resource. // -// * AccountSetupInProgressException -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StopRelationalDatabase -func (c *Lightsail) StopRelationalDatabase(input *StopRelationalDatabaseInput) (*StopRelationalDatabaseOutput, error) { - req, out := c.StopRelationalDatabaseRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ResetDistributionCache +func (c *Lightsail) ResetDistributionCache(input *ResetDistributionCacheInput) (*ResetDistributionCacheOutput, error) { + req, out := c.ResetDistributionCacheRequest(input) return out, req.Send() } -// StopRelationalDatabaseWithContext is the same as StopRelationalDatabase with the addition of +// ResetDistributionCacheWithContext is the same as ResetDistributionCache with the addition of // the ability to pass a context and additional request options. // -// See StopRelationalDatabase for details on how to use this API operation. +// See ResetDistributionCache for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) StopRelationalDatabaseWithContext(ctx aws.Context, input *StopRelationalDatabaseInput, opts ...request.Option) (*StopRelationalDatabaseOutput, error) { - req, out := c.StopRelationalDatabaseRequest(input) +func (c *Lightsail) ResetDistributionCacheWithContext(ctx aws.Context, input *ResetDistributionCacheInput, opts ...request.Option) (*ResetDistributionCacheOutput, error) { + req, out := c.ResetDistributionCacheRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opTagResource = "TagResource" +const opSendContactMethodVerification = "SendContactMethodVerification" -// TagResourceRequest generates a "aws/request.Request" representing the -// client's request for the TagResource operation. The "output" return +// SendContactMethodVerificationRequest generates a "aws/request.Request" representing the +// client's request for the SendContactMethodVerification operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See TagResource for more information on using the TagResource +// See SendContactMethodVerification for more information on using the SendContactMethodVerification // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the TagResourceRequest method. -// req, resp := client.TagResourceRequest(params) +// // Example sending a request using the SendContactMethodVerificationRequest method. +// req, resp := client.SendContactMethodVerificationRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/TagResource -func (c *Lightsail) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/SendContactMethodVerification +func (c *Lightsail) SendContactMethodVerificationRequest(input *SendContactMethodVerificationInput) (req *request.Request, output *SendContactMethodVerificationOutput) { op := &request.Operation{ - Name: opTagResource, + Name: opSendContactMethodVerification, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &TagResourceInput{} + input = &SendContactMethodVerificationInput{} } - output = &TagResourceOutput{} + output = &SendContactMethodVerificationOutput{} req = c.newRequest(op, input, output) return } -// TagResource API operation for Amazon Lightsail. +// SendContactMethodVerification API operation for Amazon Lightsail. // -// Adds one or more tags to the specified Amazon Lightsail resource. Each resource -// can have a maximum of 50 tags. Each tag consists of a key and an optional -// value. Tag keys must be unique per resource. For more information about tags, -// see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags). +// Sends a verification request to an email contact method to ensure it's owned +// by the requester. SMS contact methods don't need to be verified. // -// The tag resource operation supports tag-based access control via request -// tags and resource tags applied to the resource identified by resource name. -// For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// A contact method is used to send you notifications about your Amazon Lightsail +// resources. You can add one email address and one mobile phone number contact +// method in each AWS Region. However, SMS text messaging is not supported in +// some AWS Regions, and SMS text messages cannot be sent to some countries/regions. +// For more information, see Notifications in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-notifications). +// +// A verification request is sent to the contact method when you initially create +// it. Use this action to send another verification request if a previous verification +// request was deleted, or has expired. +// +// Notifications are not sent to an email contact method until after it is verified, +// and confirmed as valid. // // Returns awserr.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 Lightsail's -// API operation TagResource for usage and error information. +// API operation SendContactMethodVerification for usage and error information. // // Returned Error Types: // * ServiceException @@ -11360,105 +12073,103 @@ func (c *Lightsail) TagResourceRequest(input *TagResourceInput) (req *request.Re // Please set your AWS Region configuration to us-east-1 to create, view, or // edit these resources. // -// * NotFoundException -// Lightsail throws this exception when it cannot find a resource. -// // * OperationFailureException // Lightsail throws this exception when an operation fails to execute. // +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// // * AccessDeniedException // Lightsail throws this exception when the user cannot be authenticated or // uses invalid credentials to access a resource. // -// * AccountSetupInProgressException -// Lightsail throws this exception when an account is still in the setup in -// progress state. +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. // -// * UnauthenticatedException -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/TagResource -func (c *Lightsail) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { - req, out := c.TagResourceRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/SendContactMethodVerification +func (c *Lightsail) SendContactMethodVerification(input *SendContactMethodVerificationInput) (*SendContactMethodVerificationOutput, error) { + req, out := c.SendContactMethodVerificationRequest(input) return out, req.Send() } -// TagResourceWithContext is the same as TagResource with the addition of +// SendContactMethodVerificationWithContext is the same as SendContactMethodVerification 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. +// See SendContactMethodVerification for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) TagResourceWithContext(ctx aws.Context, input *TagResourceInput, opts ...request.Option) (*TagResourceOutput, error) { - req, out := c.TagResourceRequest(input) +func (c *Lightsail) SendContactMethodVerificationWithContext(ctx aws.Context, input *SendContactMethodVerificationInput, opts ...request.Option) (*SendContactMethodVerificationOutput, error) { + req, out := c.SendContactMethodVerificationRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opTestAlarm = "TestAlarm" +const opStartInstance = "StartInstance" -// TestAlarmRequest generates a "aws/request.Request" representing the -// client's request for the TestAlarm operation. The "output" return +// StartInstanceRequest generates a "aws/request.Request" representing the +// client's request for the StartInstance operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See TestAlarm for more information on using the TestAlarm +// See StartInstance for more information on using the StartInstance // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the TestAlarmRequest method. -// req, resp := client.TestAlarmRequest(params) +// // Example sending a request using the StartInstanceRequest method. +// req, resp := client.StartInstanceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/TestAlarm -func (c *Lightsail) TestAlarmRequest(input *TestAlarmInput) (req *request.Request, output *TestAlarmOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StartInstance +func (c *Lightsail) StartInstanceRequest(input *StartInstanceInput) (req *request.Request, output *StartInstanceOutput) { op := &request.Operation{ - Name: opTestAlarm, + Name: opStartInstance, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &TestAlarmInput{} + input = &StartInstanceInput{} } - output = &TestAlarmOutput{} + output = &StartInstanceOutput{} req = c.newRequest(op, input, output) return } -// TestAlarm API operation for Amazon Lightsail. +// StartInstance API operation for Amazon Lightsail. // -// Tests an alarm by displaying a banner on the Amazon Lightsail console. If -// a notification trigger is configured for the specified alarm, the test also -// sends a notification to the notification protocol (Email and/or SMS) configured -// for the alarm. +// Starts a specific Amazon Lightsail instance from a stopped state. To restart +// an instance, use the reboot instance operation. // -// An alarm is used to monitor a single metric for one of your resources. When -// a metric condition is met, the alarm can notify you by email, SMS text message, -// and a banner displayed on the Amazon Lightsail console. For more information, -// see Alarms in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-alarms). +// When you start a stopped instance, Lightsail assigns a new public IP address +// to the instance. To use the same IP address after stopping and starting an +// instance, create a static IP address and attach it to the instance. For more +// information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/lightsail-create-static-ip). +// +// The start instance operation supports tag-based access control via resource +// tags applied to the resource identified by instance name. For more information, +// see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // // Returns awserr.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 Lightsail's -// API operation TestAlarm for usage and error information. +// API operation StartInstance for usage and error information. // // Returned Error Types: // * ServiceException @@ -11472,93 +12183,102 @@ func (c *Lightsail) TestAlarmRequest(input *TestAlarmInput) (req *request.Reques // Please set your AWS Region configuration to us-east-1 to create, view, or // edit these resources. // +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// // * OperationFailureException // Lightsail throws this exception when an operation fails to execute. // -// * UnauthenticatedException -// Lightsail throws this exception when the user has not been authenticated. -// // * AccessDeniedException // Lightsail throws this exception when the user cannot be authenticated or // uses invalid credentials to access a resource. // -// * NotFoundException -// Lightsail throws this exception when it cannot find a resource. +// * AccountSetupInProgressException +// Lightsail throws this exception when an account is still in the setup in +// progress state. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/TestAlarm -func (c *Lightsail) TestAlarm(input *TestAlarmInput) (*TestAlarmOutput, error) { - req, out := c.TestAlarmRequest(input) +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, 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) return out, req.Send() } -// TestAlarmWithContext is the same as TestAlarm with the addition of +// StartInstanceWithContext is the same as StartInstance with the addition of // the ability to pass a context and additional request options. // -// See TestAlarm for details on how to use this API operation. +// 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) TestAlarmWithContext(ctx aws.Context, input *TestAlarmInput, opts ...request.Option) (*TestAlarmOutput, error) { - req, out := c.TestAlarmRequest(input) +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 opUnpeerVpc = "UnpeerVpc" +const opStartRelationalDatabase = "StartRelationalDatabase" -// UnpeerVpcRequest generates a "aws/request.Request" representing the -// client's request for the UnpeerVpc operation. The "output" return +// StartRelationalDatabaseRequest generates a "aws/request.Request" representing the +// client's request for the StartRelationalDatabase operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UnpeerVpc for more information on using the UnpeerVpc +// See StartRelationalDatabase for more information on using the StartRelationalDatabase // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UnpeerVpcRequest method. -// req, resp := client.UnpeerVpcRequest(params) +// // Example sending a request using the StartRelationalDatabaseRequest method. +// req, resp := client.StartRelationalDatabaseRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UnpeerVpc -func (c *Lightsail) UnpeerVpcRequest(input *UnpeerVpcInput) (req *request.Request, output *UnpeerVpcOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StartRelationalDatabase +func (c *Lightsail) StartRelationalDatabaseRequest(input *StartRelationalDatabaseInput) (req *request.Request, output *StartRelationalDatabaseOutput) { op := &request.Operation{ - Name: opUnpeerVpc, + Name: opStartRelationalDatabase, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UnpeerVpcInput{} + input = &StartRelationalDatabaseInput{} } - output = &UnpeerVpcOutput{} + output = &StartRelationalDatabaseOutput{} req = c.newRequest(op, input, output) return } -// UnpeerVpc API operation for Amazon Lightsail. +// StartRelationalDatabase API operation for Amazon Lightsail. // -// Attempts to unpeer the Lightsail VPC from the user's default VPC. +// Starts a specific database from a stopped state in Amazon Lightsail. To restart +// a database, use the reboot relational database operation. +// +// The start relational database operation supports tag-based access control +// via resource tags applied to the resource identified by relationalDatabaseName. +// For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // // Returns awserr.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 Lightsail's -// API operation UnpeerVpc for usage and error information. +// API operation StartRelationalDatabase for usage and error information. // // Returned Error Types: // * ServiceException @@ -11589,85 +12309,89 @@ func (c *Lightsail) UnpeerVpcRequest(input *UnpeerVpcInput) (req *request.Reques // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StartRelationalDatabase +func (c *Lightsail) StartRelationalDatabase(input *StartRelationalDatabaseInput) (*StartRelationalDatabaseOutput, error) { + req, out := c.StartRelationalDatabaseRequest(input) return out, req.Send() } -// UnpeerVpcWithContext is the same as UnpeerVpc with the addition of +// StartRelationalDatabaseWithContext is the same as StartRelationalDatabase 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. +// See StartRelationalDatabase for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) StartRelationalDatabaseWithContext(ctx aws.Context, input *StartRelationalDatabaseInput, opts ...request.Option) (*StartRelationalDatabaseOutput, error) { + req, out := c.StartRelationalDatabaseRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUntagResource = "UntagResource" +const opStopInstance = "StopInstance" -// UntagResourceRequest generates a "aws/request.Request" representing the -// client's request for the UntagResource operation. The "output" return +// StopInstanceRequest generates a "aws/request.Request" representing the +// client's request for the StopInstance operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UntagResource for more information on using the UntagResource +// See StopInstance for more information on using the StopInstance // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UntagResourceRequest method. -// req, resp := client.UntagResourceRequest(params) +// // Example sending a request using the StopInstanceRequest method. +// req, resp := client.StopInstanceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UntagResource -func (c *Lightsail) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StopInstance +func (c *Lightsail) StopInstanceRequest(input *StopInstanceInput) (req *request.Request, output *StopInstanceOutput) { op := &request.Operation{ - Name: opUntagResource, + Name: opStopInstance, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UntagResourceInput{} + input = &StopInstanceInput{} } - output = &UntagResourceOutput{} + output = &StopInstanceOutput{} req = c.newRequest(op, input, output) return } -// UntagResource API operation for Amazon Lightsail. +// StopInstance API operation for Amazon Lightsail. // -// Deletes the specified set of tag keys and their values from the specified -// Amazon Lightsail resource. +// Stops a specific Amazon Lightsail instance that is currently running. // -// The untag resource operation supports tag-based access control via request -// tags and resource tags applied to the resource identified by resource name. -// For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// When you start a stopped instance, Lightsail assigns a new public IP address +// to the instance. To use the same IP address after stopping and starting an +// instance, create a static IP address and attach it to the instance. For more +// information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/lightsail-create-static-ip). +// +// The stop instance operation supports tag-based access control via resource +// tags applied to the resource identified by instance name. For more information, +// see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // // Returns awserr.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 Lightsail's -// API operation UntagResource for usage and error information. +// API operation StopInstance for usage and error information. // // Returned Error Types: // * ServiceException @@ -11698,84 +12422,84 @@ func (c *Lightsail) UntagResourceRequest(input *UntagResourceInput) (req *reques // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UntagResource -func (c *Lightsail) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { - req, out := c.UntagResourceRequest(input) +// See also, 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) return out, req.Send() } -// UntagResourceWithContext is the same as UntagResource with the addition of +// StopInstanceWithContext is the same as StopInstance 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. +// 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) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) { - req, out := c.UntagResourceRequest(input) +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 opUpdateDomainEntry = "UpdateDomainEntry" +const opStopRelationalDatabase = "StopRelationalDatabase" -// UpdateDomainEntryRequest generates a "aws/request.Request" representing the -// client's request for the UpdateDomainEntry operation. The "output" return +// StopRelationalDatabaseRequest generates a "aws/request.Request" representing the +// client's request for the StopRelationalDatabase operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateDomainEntry for more information on using the UpdateDomainEntry +// See StopRelationalDatabase for more information on using the StopRelationalDatabase // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateDomainEntryRequest method. -// req, resp := client.UpdateDomainEntryRequest(params) +// // Example sending a request using the StopRelationalDatabaseRequest method. +// req, resp := client.StopRelationalDatabaseRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateDomainEntry -func (c *Lightsail) UpdateDomainEntryRequest(input *UpdateDomainEntryInput) (req *request.Request, output *UpdateDomainEntryOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StopRelationalDatabase +func (c *Lightsail) StopRelationalDatabaseRequest(input *StopRelationalDatabaseInput) (req *request.Request, output *StopRelationalDatabaseOutput) { op := &request.Operation{ - Name: opUpdateDomainEntry, + Name: opStopRelationalDatabase, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateDomainEntryInput{} + input = &StopRelationalDatabaseInput{} } - output = &UpdateDomainEntryOutput{} + output = &StopRelationalDatabaseOutput{} req = c.newRequest(op, input, output) return } -// UpdateDomainEntry API operation for Amazon Lightsail. +// StopRelationalDatabase API operation for Amazon Lightsail. // -// Updates a domain recordset after it is created. +// Stops a specific database that is currently running in Amazon Lightsail. // -// The update domain entry operation supports tag-based access control via resource -// tags applied to the resource identified by domain name. For more information, -// see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// The stop relational database operation supports tag-based access control +// via resource tags applied to the resource identified by relationalDatabaseName. +// For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // // Returns awserr.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 Lightsail's -// API operation UpdateDomainEntry for usage and error information. +// API operation StopRelationalDatabase for usage and error information. // // Returned Error Types: // * ServiceException @@ -11806,77 +12530,79 @@ func (c *Lightsail) UpdateDomainEntryRequest(input *UpdateDomainEntryInput) (req // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, 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) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StopRelationalDatabase +func (c *Lightsail) StopRelationalDatabase(input *StopRelationalDatabaseInput) (*StopRelationalDatabaseOutput, error) { + req, out := c.StopRelationalDatabaseRequest(input) return out, req.Send() } -// UpdateDomainEntryWithContext is the same as UpdateDomainEntry with the addition of +// StopRelationalDatabaseWithContext is the same as StopRelationalDatabase 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. +// See StopRelationalDatabase for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the 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) +func (c *Lightsail) StopRelationalDatabaseWithContext(ctx aws.Context, input *StopRelationalDatabaseInput, opts ...request.Option) (*StopRelationalDatabaseOutput, error) { + req, out := c.StopRelationalDatabaseRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateLoadBalancerAttribute = "UpdateLoadBalancerAttribute" +const opTagResource = "TagResource" -// UpdateLoadBalancerAttributeRequest generates a "aws/request.Request" representing the -// client's request for the UpdateLoadBalancerAttribute operation. The "output" return +// TagResourceRequest generates a "aws/request.Request" representing the +// client's request for the TagResource operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateLoadBalancerAttribute for more information on using the UpdateLoadBalancerAttribute +// See TagResource for more information on using the TagResource // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateLoadBalancerAttributeRequest method. -// req, resp := client.UpdateLoadBalancerAttributeRequest(params) +// // Example sending a request using the TagResourceRequest method. +// req, resp := client.TagResourceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateLoadBalancerAttribute -func (c *Lightsail) UpdateLoadBalancerAttributeRequest(input *UpdateLoadBalancerAttributeInput) (req *request.Request, output *UpdateLoadBalancerAttributeOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/TagResource +func (c *Lightsail) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { op := &request.Operation{ - Name: opUpdateLoadBalancerAttribute, + Name: opTagResource, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateLoadBalancerAttributeInput{} + input = &TagResourceInput{} } - output = &UpdateLoadBalancerAttributeOutput{} + output = &TagResourceOutput{} req = c.newRequest(op, input, output) return } -// UpdateLoadBalancerAttribute API operation for Amazon Lightsail. +// TagResource API operation for Amazon Lightsail. // -// Updates the specified attribute for a load balancer. You can only update -// one attribute at a time. +// Adds one or more tags to the specified Amazon Lightsail resource. Each resource +// can have a maximum of 50 tags. Each tag consists of a key and an optional +// value. Tag keys must be unique per resource. For more information about tags, +// see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags). // -// The update load balancer attribute operation supports tag-based access control -// via resource tags applied to the resource identified by load balancer name. +// The tag resource operation supports tag-based access control via request +// tags and resource tags applied to the resource identified by resource name. // For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -11884,7 +12610,7 @@ func (c *Lightsail) UpdateLoadBalancerAttributeRequest(input *UpdateLoadBalancer // the error. // // See the AWS API reference guide for Amazon Lightsail's -// API operation UpdateLoadBalancerAttribute for usage and error information. +// API operation TagResource for usage and error information. // // Returned Error Types: // * ServiceException @@ -11915,87 +12641,188 @@ func (c *Lightsail) UpdateLoadBalancerAttributeRequest(input *UpdateLoadBalancer // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateLoadBalancerAttribute -func (c *Lightsail) UpdateLoadBalancerAttribute(input *UpdateLoadBalancerAttributeInput) (*UpdateLoadBalancerAttributeOutput, error) { - req, out := c.UpdateLoadBalancerAttributeRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/TagResource +func (c *Lightsail) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { + req, out := c.TagResourceRequest(input) return out, req.Send() } -// UpdateLoadBalancerAttributeWithContext is the same as UpdateLoadBalancerAttribute with the addition of +// TagResourceWithContext is the same as TagResource with the addition of // the ability to pass a context and additional request options. // -// See UpdateLoadBalancerAttribute for details on how to use this API operation. +// 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 *Lightsail) UpdateLoadBalancerAttributeWithContext(ctx aws.Context, input *UpdateLoadBalancerAttributeInput, opts ...request.Option) (*UpdateLoadBalancerAttributeOutput, error) { - req, out := c.UpdateLoadBalancerAttributeRequest(input) +func (c *Lightsail) 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 opUpdateRelationalDatabase = "UpdateRelationalDatabase" +const opTestAlarm = "TestAlarm" -// UpdateRelationalDatabaseRequest generates a "aws/request.Request" representing the -// client's request for the UpdateRelationalDatabase operation. The "output" return +// TestAlarmRequest generates a "aws/request.Request" representing the +// client's request for the TestAlarm operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateRelationalDatabase for more information on using the UpdateRelationalDatabase +// See TestAlarm for more information on using the TestAlarm // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateRelationalDatabaseRequest method. -// req, resp := client.UpdateRelationalDatabaseRequest(params) +// // Example sending a request using the TestAlarmRequest method. +// req, resp := client.TestAlarmRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateRelationalDatabase -func (c *Lightsail) UpdateRelationalDatabaseRequest(input *UpdateRelationalDatabaseInput) (req *request.Request, output *UpdateRelationalDatabaseOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/TestAlarm +func (c *Lightsail) TestAlarmRequest(input *TestAlarmInput) (req *request.Request, output *TestAlarmOutput) { op := &request.Operation{ - Name: opUpdateRelationalDatabase, + Name: opTestAlarm, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateRelationalDatabaseInput{} + input = &TestAlarmInput{} } - output = &UpdateRelationalDatabaseOutput{} + output = &TestAlarmOutput{} req = c.newRequest(op, input, output) return } -// UpdateRelationalDatabase API operation for Amazon Lightsail. +// TestAlarm API operation for Amazon Lightsail. // -// Allows the update of one or more attributes of a database in Amazon Lightsail. +// Tests an alarm by displaying a banner on the Amazon Lightsail console. If +// a notification trigger is configured for the specified alarm, the test also +// sends a notification to the notification protocol (Email and/or SMS) configured +// for the alarm. // -// Updates are applied immediately, or in cases where the updates could result -// in an outage, are applied during the database's predefined maintenance window. +// An alarm is used to monitor a single metric for one of your resources. When +// a metric condition is met, the alarm can notify you by email, SMS text message, +// and a banner displayed on the Amazon Lightsail console. For more information, +// see Alarms in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-alarms). // -// The update relational database operation supports tag-based access control -// via resource tags applied to the resource identified by relationalDatabaseName. -// For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// Returns awserr.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 Lightsail's +// API operation TestAlarm for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * OperationFailureException +// Lightsail throws this exception when an operation fails to execute. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/TestAlarm +func (c *Lightsail) TestAlarm(input *TestAlarmInput) (*TestAlarmOutput, error) { + req, out := c.TestAlarmRequest(input) + return out, req.Send() +} + +// TestAlarmWithContext is the same as TestAlarm with the addition of +// the ability to pass a context and additional request options. +// +// See TestAlarm for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) TestAlarmWithContext(ctx aws.Context, input *TestAlarmInput, opts ...request.Option) (*TestAlarmOutput, error) { + req, out := c.TestAlarmRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUnpeerVpc = "UnpeerVpc" + +// UnpeerVpcRequest generates a "aws/request.Request" representing the +// client's request for the UnpeerVpc operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UnpeerVpc for more information on using the UnpeerVpc +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UnpeerVpcRequest method. +// req, resp := client.UnpeerVpcRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UnpeerVpc +func (c *Lightsail) UnpeerVpcRequest(input *UnpeerVpcInput) (req *request.Request, output *UnpeerVpcOutput) { + op := &request.Operation{ + Name: opUnpeerVpc, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UnpeerVpcInput{} + } + + output = &UnpeerVpcOutput{} + req = c.newRequest(op, input, output) + return +} + +// UnpeerVpc API operation for Amazon Lightsail. +// +// Attempts to unpeer the Lightsail VPC from the user's default VPC. // // Returns awserr.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 Lightsail's -// API operation UpdateRelationalDatabase for usage and error information. +// API operation UnpeerVpc for usage and error information. // // Returned Error Types: // * ServiceException @@ -12026,83 +12853,77 @@ func (c *Lightsail) UpdateRelationalDatabaseRequest(input *UpdateRelationalDatab // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateRelationalDatabase -func (c *Lightsail) UpdateRelationalDatabase(input *UpdateRelationalDatabaseInput) (*UpdateRelationalDatabaseOutput, error) { - req, out := c.UpdateRelationalDatabaseRequest(input) +// See also, 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) return out, req.Send() } -// UpdateRelationalDatabaseWithContext is the same as UpdateRelationalDatabase with the addition of +// UnpeerVpcWithContext is the same as UnpeerVpc with the addition of // the ability to pass a context and additional request options. // -// See UpdateRelationalDatabase for details on how to use this API operation. +// 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) UpdateRelationalDatabaseWithContext(ctx aws.Context, input *UpdateRelationalDatabaseInput, opts ...request.Option) (*UpdateRelationalDatabaseOutput, error) { - req, out := c.UpdateRelationalDatabaseRequest(input) +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 opUpdateRelationalDatabaseParameters = "UpdateRelationalDatabaseParameters" +const opUntagResource = "UntagResource" -// UpdateRelationalDatabaseParametersRequest generates a "aws/request.Request" representing the -// client's request for the UpdateRelationalDatabaseParameters operation. The "output" return +// UntagResourceRequest generates a "aws/request.Request" representing the +// client's request for the UntagResource operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateRelationalDatabaseParameters for more information on using the UpdateRelationalDatabaseParameters +// See UntagResource for more information on using the UntagResource // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateRelationalDatabaseParametersRequest method. -// req, resp := client.UpdateRelationalDatabaseParametersRequest(params) +// // 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) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateRelationalDatabaseParameters -func (c *Lightsail) UpdateRelationalDatabaseParametersRequest(input *UpdateRelationalDatabaseParametersInput) (req *request.Request, output *UpdateRelationalDatabaseParametersOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UntagResource +func (c *Lightsail) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { op := &request.Operation{ - Name: opUpdateRelationalDatabaseParameters, + Name: opUntagResource, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateRelationalDatabaseParametersInput{} + input = &UntagResourceInput{} } - output = &UpdateRelationalDatabaseParametersOutput{} + output = &UntagResourceOutput{} req = c.newRequest(op, input, output) return } -// UpdateRelationalDatabaseParameters API operation for Amazon Lightsail. -// -// Allows the update of one or more parameters of a database in Amazon Lightsail. +// UntagResource API operation for Amazon Lightsail. // -// Parameter updates don't cause outages; therefore, their application is not -// subject to the preferred maintenance window. However, there are two ways -// in which parameter updates are applied: dynamic or pending-reboot. Parameters -// marked with a dynamic apply type are applied immediately. Parameters marked -// with a pending-reboot apply type are applied only after the database is rebooted -// using the reboot relational database operation. +// Deletes the specified set of tag keys and their values from the specified +// Amazon Lightsail resource. // -// The update relational database parameters operation supports tag-based access -// control via resource tags applied to the resource identified by relationalDatabaseName. +// The untag resource operation supports tag-based access control via request +// tags and resource tags applied to the resource identified by resource name. // For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -12110,7 +12931,7 @@ func (c *Lightsail) UpdateRelationalDatabaseParametersRequest(input *UpdateRelat // the error. // // See the AWS API reference guide for Amazon Lightsail's -// API operation UpdateRelationalDatabaseParameters for usage and error information. +// API operation UntagResource for usage and error information. // // Returned Error Types: // * ServiceException @@ -12141,538 +12962,2689 @@ func (c *Lightsail) UpdateRelationalDatabaseParametersRequest(input *UpdateRelat // * UnauthenticatedException // Lightsail throws this exception when the user has not been authenticated. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateRelationalDatabaseParameters -func (c *Lightsail) UpdateRelationalDatabaseParameters(input *UpdateRelationalDatabaseParametersInput) (*UpdateRelationalDatabaseParametersOutput, error) { - req, out := c.UpdateRelationalDatabaseParametersRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UntagResource +func (c *Lightsail) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { + req, out := c.UntagResourceRequest(input) return out, req.Send() } -// UpdateRelationalDatabaseParametersWithContext is the same as UpdateRelationalDatabaseParameters with the addition of +// UntagResourceWithContext is the same as UntagResource with the addition of // the ability to pass a context and additional request options. // -// See UpdateRelationalDatabaseParameters for details on how to use this API operation. +// 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 *Lightsail) UpdateRelationalDatabaseParametersWithContext(ctx aws.Context, input *UpdateRelationalDatabaseParametersInput, opts ...request.Option) (*UpdateRelationalDatabaseParametersOutput, error) { - req, out := c.UpdateRelationalDatabaseParametersRequest(input) +func (c *Lightsail) 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() } -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -type AccessDeniedException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Code_ *string `locationName:"code" type:"string"` - - Docs *string `locationName:"docs" type:"string"` - - Message_ *string `locationName:"message" type:"string"` - - Tip *string `locationName:"tip" type:"string"` -} +const opUpdateDistribution = "UpdateDistribution" -// String returns the string representation -func (s AccessDeniedException) String() string { - return awsutil.Prettify(s) -} +// UpdateDistributionRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDistribution operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDistribution for more information on using the UpdateDistribution +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateDistributionRequest method. +// req, resp := client.UpdateDistributionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateDistribution +func (c *Lightsail) UpdateDistributionRequest(input *UpdateDistributionInput) (req *request.Request, output *UpdateDistributionOutput) { + op := &request.Operation{ + Name: opUpdateDistribution, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateDistributionInput{} + } + + output = &UpdateDistributionOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDistribution API operation for Amazon Lightsail. +// +// Updates an existing Amazon Lightsail content delivery network (CDN) distribution. +// +// Use this action to update the configuration of your existing distribution +// +// Returns awserr.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 Lightsail's +// API operation UpdateDistribution for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * OperationFailureException +// Lightsail throws this exception when an operation fails to execute. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateDistribution +func (c *Lightsail) UpdateDistribution(input *UpdateDistributionInput) (*UpdateDistributionOutput, error) { + req, out := c.UpdateDistributionRequest(input) + return out, req.Send() +} + +// 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 *Lightsail) 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 opUpdateDistributionBundle = "UpdateDistributionBundle" + +// UpdateDistributionBundleRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDistributionBundle operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDistributionBundle for more information on using the UpdateDistributionBundle +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateDistributionBundleRequest method. +// req, resp := client.UpdateDistributionBundleRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateDistributionBundle +func (c *Lightsail) UpdateDistributionBundleRequest(input *UpdateDistributionBundleInput) (req *request.Request, output *UpdateDistributionBundleOutput) { + op := &request.Operation{ + Name: opUpdateDistributionBundle, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateDistributionBundleInput{} + } + + output = &UpdateDistributionBundleOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDistributionBundle API operation for Amazon Lightsail. +// +// Updates the bundle of your Amazon Lightsail content delivery network (CDN) +// distribution. +// +// A distribution bundle specifies the monthly network transfer quota and monthly +// cost of your dsitribution. +// +// Update your distribution's bundle if your distribution is going over its +// monthly network transfer quota and is incurring an overage fee. +// +// You can update your distribution's bundle only one time within your monthly +// AWS billing cycle. To determine if you can update your distribution's bundle, +// use the GetDistributions action. The ableToUpdateBundle parameter in the +// result will indicate whether you can currently update your distribution's +// bundle. +// +// Returns awserr.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 Lightsail's +// API operation UpdateDistributionBundle for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * OperationFailureException +// Lightsail throws this exception when an operation fails to execute. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateDistributionBundle +func (c *Lightsail) UpdateDistributionBundle(input *UpdateDistributionBundleInput) (*UpdateDistributionBundleOutput, error) { + req, out := c.UpdateDistributionBundleRequest(input) + return out, req.Send() +} + +// UpdateDistributionBundleWithContext is the same as UpdateDistributionBundle with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDistributionBundle for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) UpdateDistributionBundleWithContext(ctx aws.Context, input *UpdateDistributionBundleInput, opts ...request.Option) (*UpdateDistributionBundleOutput, error) { + req, out := c.UpdateDistributionBundleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateDomainEntry = "UpdateDomainEntry" + +// UpdateDomainEntryRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDomainEntry operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDomainEntry for more information on using the UpdateDomainEntry +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateDomainEntryRequest method. +// req, resp := client.UpdateDomainEntryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateDomainEntry +func (c *Lightsail) UpdateDomainEntryRequest(input *UpdateDomainEntryInput) (req *request.Request, output *UpdateDomainEntryOutput) { + op := &request.Operation{ + Name: opUpdateDomainEntry, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateDomainEntryInput{} + } + + output = &UpdateDomainEntryOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDomainEntry API operation for Amazon Lightsail. +// +// Updates a domain recordset after it is created. +// +// The update domain entry operation supports tag-based access control via resource +// tags applied to the resource identified by domain name. For more information, +// see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// +// Returns awserr.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 Lightsail's +// API operation UpdateDomainEntry for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * OperationFailureException +// Lightsail throws this exception when an operation fails to execute. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * AccountSetupInProgressException +// Lightsail throws this exception when an account is still in the setup in +// progress state. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, 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) + 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() +} + +const opUpdateLoadBalancerAttribute = "UpdateLoadBalancerAttribute" + +// UpdateLoadBalancerAttributeRequest generates a "aws/request.Request" representing the +// client's request for the UpdateLoadBalancerAttribute operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateLoadBalancerAttribute for more information on using the UpdateLoadBalancerAttribute +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateLoadBalancerAttributeRequest method. +// req, resp := client.UpdateLoadBalancerAttributeRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateLoadBalancerAttribute +func (c *Lightsail) UpdateLoadBalancerAttributeRequest(input *UpdateLoadBalancerAttributeInput) (req *request.Request, output *UpdateLoadBalancerAttributeOutput) { + op := &request.Operation{ + Name: opUpdateLoadBalancerAttribute, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateLoadBalancerAttributeInput{} + } + + output = &UpdateLoadBalancerAttributeOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateLoadBalancerAttribute API operation for Amazon Lightsail. +// +// Updates the specified attribute for a load balancer. You can only update +// one attribute at a time. +// +// The update load balancer attribute operation supports tag-based access control +// via resource tags applied to the resource identified by load balancer name. +// For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// +// Returns awserr.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 Lightsail's +// API operation UpdateLoadBalancerAttribute for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * OperationFailureException +// Lightsail throws this exception when an operation fails to execute. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * AccountSetupInProgressException +// Lightsail throws this exception when an account is still in the setup in +// progress state. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateLoadBalancerAttribute +func (c *Lightsail) UpdateLoadBalancerAttribute(input *UpdateLoadBalancerAttributeInput) (*UpdateLoadBalancerAttributeOutput, error) { + req, out := c.UpdateLoadBalancerAttributeRequest(input) + return out, req.Send() +} + +// UpdateLoadBalancerAttributeWithContext is the same as UpdateLoadBalancerAttribute with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateLoadBalancerAttribute for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) UpdateLoadBalancerAttributeWithContext(ctx aws.Context, input *UpdateLoadBalancerAttributeInput, opts ...request.Option) (*UpdateLoadBalancerAttributeOutput, error) { + req, out := c.UpdateLoadBalancerAttributeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateRelationalDatabase = "UpdateRelationalDatabase" + +// UpdateRelationalDatabaseRequest generates a "aws/request.Request" representing the +// client's request for the UpdateRelationalDatabase operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateRelationalDatabase for more information on using the UpdateRelationalDatabase +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateRelationalDatabaseRequest method. +// req, resp := client.UpdateRelationalDatabaseRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateRelationalDatabase +func (c *Lightsail) UpdateRelationalDatabaseRequest(input *UpdateRelationalDatabaseInput) (req *request.Request, output *UpdateRelationalDatabaseOutput) { + op := &request.Operation{ + Name: opUpdateRelationalDatabase, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateRelationalDatabaseInput{} + } + + output = &UpdateRelationalDatabaseOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateRelationalDatabase API operation for Amazon Lightsail. +// +// Allows the update of one or more attributes of a database in Amazon Lightsail. +// +// Updates are applied immediately, or in cases where the updates could result +// in an outage, are applied during the database's predefined maintenance window. +// +// The update relational database operation supports tag-based access control +// via resource tags applied to the resource identified by relationalDatabaseName. +// For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// +// Returns awserr.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 Lightsail's +// API operation UpdateRelationalDatabase for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * OperationFailureException +// Lightsail throws this exception when an operation fails to execute. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * AccountSetupInProgressException +// Lightsail throws this exception when an account is still in the setup in +// progress state. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateRelationalDatabase +func (c *Lightsail) UpdateRelationalDatabase(input *UpdateRelationalDatabaseInput) (*UpdateRelationalDatabaseOutput, error) { + req, out := c.UpdateRelationalDatabaseRequest(input) + return out, req.Send() +} + +// UpdateRelationalDatabaseWithContext is the same as UpdateRelationalDatabase with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRelationalDatabase for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) UpdateRelationalDatabaseWithContext(ctx aws.Context, input *UpdateRelationalDatabaseInput, opts ...request.Option) (*UpdateRelationalDatabaseOutput, error) { + req, out := c.UpdateRelationalDatabaseRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateRelationalDatabaseParameters = "UpdateRelationalDatabaseParameters" + +// UpdateRelationalDatabaseParametersRequest generates a "aws/request.Request" representing the +// client's request for the UpdateRelationalDatabaseParameters operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateRelationalDatabaseParameters for more information on using the UpdateRelationalDatabaseParameters +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateRelationalDatabaseParametersRequest method. +// req, resp := client.UpdateRelationalDatabaseParametersRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateRelationalDatabaseParameters +func (c *Lightsail) UpdateRelationalDatabaseParametersRequest(input *UpdateRelationalDatabaseParametersInput) (req *request.Request, output *UpdateRelationalDatabaseParametersOutput) { + op := &request.Operation{ + Name: opUpdateRelationalDatabaseParameters, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateRelationalDatabaseParametersInput{} + } + + output = &UpdateRelationalDatabaseParametersOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateRelationalDatabaseParameters API operation for Amazon Lightsail. +// +// Allows the update of one or more parameters of a database in Amazon Lightsail. +// +// Parameter updates don't cause outages; therefore, their application is not +// subject to the preferred maintenance window. However, there are two ways +// in which parameter updates are applied: dynamic or pending-reboot. Parameters +// marked with a dynamic apply type are applied immediately. Parameters marked +// with a pending-reboot apply type are applied only after the database is rebooted +// using the reboot relational database operation. +// +// The update relational database parameters operation supports tag-based access +// control via resource tags applied to the resource identified by relationalDatabaseName. +// For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags). +// +// Returns awserr.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 Lightsail's +// API operation UpdateRelationalDatabaseParameters for usage and error information. +// +// Returned Error Types: +// * ServiceException +// A general service exception. +// +// * InvalidInputException +// Lightsail throws this exception when user input does not conform to the validation +// rules of an input field. +// +// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. +// Please set your AWS Region configuration to us-east-1 to create, view, or +// edit these resources. +// +// * NotFoundException +// Lightsail throws this exception when it cannot find a resource. +// +// * OperationFailureException +// Lightsail throws this exception when an operation fails to execute. +// +// * AccessDeniedException +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +// +// * AccountSetupInProgressException +// Lightsail throws this exception when an account is still in the setup in +// progress state. +// +// * UnauthenticatedException +// Lightsail throws this exception when the user has not been authenticated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateRelationalDatabaseParameters +func (c *Lightsail) UpdateRelationalDatabaseParameters(input *UpdateRelationalDatabaseParametersInput) (*UpdateRelationalDatabaseParametersOutput, error) { + req, out := c.UpdateRelationalDatabaseParametersRequest(input) + return out, req.Send() +} + +// UpdateRelationalDatabaseParametersWithContext is the same as UpdateRelationalDatabaseParameters with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateRelationalDatabaseParameters for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) UpdateRelationalDatabaseParametersWithContext(ctx aws.Context, input *UpdateRelationalDatabaseParametersInput, opts ...request.Option) (*UpdateRelationalDatabaseParametersOutput, error) { + req, out := c.UpdateRelationalDatabaseParametersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// Lightsail throws this exception when the user cannot be authenticated or +// uses invalid credentials to access a resource. +type AccessDeniedException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Code_ *string `locationName:"code" type:"string"` + + Docs *string `locationName:"docs" type:"string"` + + Message_ *string `locationName:"message" type:"string"` + + Tip *string `locationName:"tip" type:"string"` +} + +// String returns the string representation +func (s AccessDeniedException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccessDeniedException) GoString() string { + return s.String() +} + +func newErrorAccessDeniedException(v protocol.ResponseMetadata) error { + return &AccessDeniedException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *AccessDeniedException) Code() string { + return "AccessDeniedException" +} + +// Message returns the exception's message. +func (s *AccessDeniedException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *AccessDeniedException) OrigErr() error { + return nil +} + +func (s *AccessDeniedException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *AccessDeniedException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *AccessDeniedException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Lightsail throws this exception when an account is still in the setup in +// progress state. +type AccountSetupInProgressException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Code_ *string `locationName:"code" type:"string"` + + Docs *string `locationName:"docs" type:"string"` + + Message_ *string `locationName:"message" type:"string"` + + Tip *string `locationName:"tip" type:"string"` +} + +// String returns the string representation +func (s AccountSetupInProgressException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccountSetupInProgressException) GoString() string { + return s.String() +} + +func newErrorAccountSetupInProgressException(v protocol.ResponseMetadata) error { + return &AccountSetupInProgressException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *AccountSetupInProgressException) Code() string { + return "AccountSetupInProgressException" +} + +// Message returns the exception's message. +func (s *AccountSetupInProgressException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *AccountSetupInProgressException) OrigErr() error { + return nil +} + +func (s *AccountSetupInProgressException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *AccountSetupInProgressException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *AccountSetupInProgressException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Describes an add-on that is enabled for an Amazon Lightsail resource. +type AddOn struct { + _ struct{} `type:"structure"` + + // The name of the add-on. + Name *string `locationName:"name" type:"string"` + + // The next daily time an automatic snapshot will be created. + // + // The time shown is in HH:00 format, and in Coordinated Universal Time (UTC). + // + // The snapshot is automatically created between the time shown and up to 45 + // minutes after. + NextSnapshotTimeOfDay *string `locationName:"nextSnapshotTimeOfDay" type:"string"` + + // The daily time when an automatic snapshot is created. + // + // The time shown is in HH:00 format, and in Coordinated Universal Time (UTC). + // + // The snapshot is automatically created between the time shown and up to 45 + // minutes after. + SnapshotTimeOfDay *string `locationName:"snapshotTimeOfDay" type:"string"` + + // The status of the add-on. + Status *string `locationName:"status" type:"string"` +} + +// String returns the string representation +func (s AddOn) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AddOn) GoString() string { + return s.String() +} + +// SetName sets the Name field's value. +func (s *AddOn) SetName(v string) *AddOn { + s.Name = &v + return s +} + +// SetNextSnapshotTimeOfDay sets the NextSnapshotTimeOfDay field's value. +func (s *AddOn) SetNextSnapshotTimeOfDay(v string) *AddOn { + s.NextSnapshotTimeOfDay = &v + return s +} + +// SetSnapshotTimeOfDay sets the SnapshotTimeOfDay field's value. +func (s *AddOn) SetSnapshotTimeOfDay(v string) *AddOn { + s.SnapshotTimeOfDay = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *AddOn) SetStatus(v string) *AddOn { + s.Status = &v + return s +} + +// Describes a request to enable, modify, or disable an add-on for an Amazon +// Lightsail resource. +// +// An additional cost may be associated with enabling add-ons. For more information, +// see the Lightsail pricing page (https://aws.amazon.com/lightsail/pricing/). +type AddOnRequest struct { + _ struct{} `type:"structure"` + + // The add-on type. + // + // AddOnType is a required field + AddOnType *string `locationName:"addOnType" type:"string" required:"true" enum:"AddOnType"` + + // An object that represents additional parameters when enabling or modifying + // the automatic snapshot add-on. + AutoSnapshotAddOnRequest *AutoSnapshotAddOnRequest `locationName:"autoSnapshotAddOnRequest" type:"structure"` +} + +// String returns the string representation +func (s AddOnRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AddOnRequest) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AddOnRequest) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AddOnRequest"} + if s.AddOnType == nil { + invalidParams.Add(request.NewErrParamRequired("AddOnType")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAddOnType sets the AddOnType field's value. +func (s *AddOnRequest) SetAddOnType(v string) *AddOnRequest { + s.AddOnType = &v + return s +} + +// SetAutoSnapshotAddOnRequest sets the AutoSnapshotAddOnRequest field's value. +func (s *AddOnRequest) SetAutoSnapshotAddOnRequest(v *AutoSnapshotAddOnRequest) *AddOnRequest { + s.AutoSnapshotAddOnRequest = v + return s +} + +// Describes an alarm. +// +// An alarm is a way to monitor your Amazon Lightsail resource metrics. For +// more information, see Alarms in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-alarms). +type Alarm struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the alarm. + Arn *string `locationName:"arn" type:"string"` + + // The arithmetic operation used when comparing the specified statistic and + // threshold. + ComparisonOperator *string `locationName:"comparisonOperator" type:"string" enum:"ComparisonOperator"` + + // The contact protocols for the alarm, such as Email, SMS (text messaging), + // or both. + ContactProtocols []*string `locationName:"contactProtocols" type:"list"` + + // The timestamp when the alarm was created. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + + // The number of data points that must not within the specified threshold to + // trigger the alarm. + DatapointsToAlarm *int64 `locationName:"datapointsToAlarm" type:"integer"` + + // The number of periods over which data is compared to the specified threshold. + EvaluationPeriods *int64 `locationName:"evaluationPeriods" type:"integer"` + + // An object that lists information about the location of the alarm. + Location *ResourceLocation `locationName:"location" type:"structure"` + + // The name of the metric associated with the alarm. + MetricName *string `locationName:"metricName" type:"string" enum:"MetricName"` + + // An object that lists information about the resource monitored by the alarm. + MonitoredResourceInfo *MonitoredResourceInfo `locationName:"monitoredResourceInfo" type:"structure"` + + // The name of the alarm. + Name *string `locationName:"name" type:"string"` + + // Indicates whether the alarm is enabled. + NotificationEnabled *bool `locationName:"notificationEnabled" type:"boolean"` + + // The alarm states that trigger a notification. + NotificationTriggers []*string `locationName:"notificationTriggers" type:"list"` + + // The period, in seconds, over which the statistic is applied. + Period *int64 `locationName:"period" min:"60" type:"integer"` + + // The Lightsail resource type (e.g., Alarm). + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + + // The current state of the alarm. + // + // An alarm has the following possible states: + // + // * ALARM - The metric is outside of the defined threshold. + // + // * INSUFFICIENT_DATA - The alarm has just started, the metric is not available, + // or not enough data is available for the metric to determine the alarm + // state. + // + // * OK - The metric is within the defined threshold. + State *string `locationName:"state" type:"string" enum:"AlarmState"` + + // The statistic for the metric associated with the alarm. + // + // The following statistics are available: + // + // * Minimum - The lowest value observed during the specified period. Use + // this value to determine low volumes of activity for your application. + // + // * Maximum - The highest value observed during the specified period. Use + // this value to determine high volumes of activity for your application. + // + // * Sum - All values submitted for the matching metric added together. You + // can use this statistic to determine the total volume of a metric. + // + // * Average - The value of Sum / SampleCount during the specified period. + // By comparing this statistic with the Minimum and Maximum values, you can + // determine the full scope of a metric and how close the average use is + // to the Minimum and Maximum values. This comparison helps you to know when + // to increase or decrease your resources. + // + // * SampleCount - The count, or number, of data points used for the statistical + // calculation. + Statistic *string `locationName:"statistic" type:"string" enum:"MetricStatistic"` + + // The support code. Include this code in your email to support when you have + // questions about your Lightsail alarm. This code enables our support team + // to look up your Lightsail information more easily. + SupportCode *string `locationName:"supportCode" type:"string"` + + // The value against which the specified statistic is compared. + Threshold *float64 `locationName:"threshold" type:"double"` + + // Specifies how the alarm handles missing data points. + // + // An alarm can treat missing data in the following ways: + // + // * breaching - Assume the missing data is not within the threshold. Missing + // data counts towards the number of times the metric is not within the threshold. + // + // * notBreaching - Assume the missing data is within the threshold. Missing + // data does not count towards the number of times the metric is not within + // the threshold. + // + // * ignore - Ignore the missing data. Maintains the current alarm state. + // + // * missing - Missing data is treated as missing. + TreatMissingData *string `locationName:"treatMissingData" type:"string" enum:"TreatMissingData"` + + // The unit of the metric associated with the alarm. + Unit *string `locationName:"unit" type:"string" enum:"MetricUnit"` +} + +// String returns the string representation +func (s Alarm) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Alarm) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Alarm) SetArn(v string) *Alarm { + s.Arn = &v + return s +} + +// SetComparisonOperator sets the ComparisonOperator field's value. +func (s *Alarm) SetComparisonOperator(v string) *Alarm { + s.ComparisonOperator = &v + return s +} + +// SetContactProtocols sets the ContactProtocols field's value. +func (s *Alarm) SetContactProtocols(v []*string) *Alarm { + s.ContactProtocols = v + return s +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *Alarm) SetCreatedAt(v time.Time) *Alarm { + s.CreatedAt = &v + return s +} + +// SetDatapointsToAlarm sets the DatapointsToAlarm field's value. +func (s *Alarm) SetDatapointsToAlarm(v int64) *Alarm { + s.DatapointsToAlarm = &v + return s +} + +// SetEvaluationPeriods sets the EvaluationPeriods field's value. +func (s *Alarm) SetEvaluationPeriods(v int64) *Alarm { + s.EvaluationPeriods = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *Alarm) SetLocation(v *ResourceLocation) *Alarm { + s.Location = v + return s +} + +// SetMetricName sets the MetricName field's value. +func (s *Alarm) SetMetricName(v string) *Alarm { + s.MetricName = &v + return s +} + +// SetMonitoredResourceInfo sets the MonitoredResourceInfo field's value. +func (s *Alarm) SetMonitoredResourceInfo(v *MonitoredResourceInfo) *Alarm { + s.MonitoredResourceInfo = v + return s +} + +// SetName sets the Name field's value. +func (s *Alarm) SetName(v string) *Alarm { + s.Name = &v + return s +} + +// SetNotificationEnabled sets the NotificationEnabled field's value. +func (s *Alarm) SetNotificationEnabled(v bool) *Alarm { + s.NotificationEnabled = &v + return s +} + +// SetNotificationTriggers sets the NotificationTriggers field's value. +func (s *Alarm) SetNotificationTriggers(v []*string) *Alarm { + s.NotificationTriggers = v + return s +} + +// SetPeriod sets the Period field's value. +func (s *Alarm) SetPeriod(v int64) *Alarm { + s.Period = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *Alarm) SetResourceType(v string) *Alarm { + s.ResourceType = &v + return s +} + +// SetState sets the State field's value. +func (s *Alarm) SetState(v string) *Alarm { + s.State = &v + return s +} + +// SetStatistic sets the Statistic field's value. +func (s *Alarm) SetStatistic(v string) *Alarm { + s.Statistic = &v + return s +} + +// SetSupportCode sets the SupportCode field's value. +func (s *Alarm) SetSupportCode(v string) *Alarm { + s.SupportCode = &v + return s +} + +// SetThreshold sets the Threshold field's value. +func (s *Alarm) SetThreshold(v float64) *Alarm { + s.Threshold = &v + return s +} + +// SetTreatMissingData sets the TreatMissingData field's value. +func (s *Alarm) SetTreatMissingData(v string) *Alarm { + s.TreatMissingData = &v + return s +} + +// SetUnit sets the Unit field's value. +func (s *Alarm) SetUnit(v string) *Alarm { + s.Unit = &v + return s +} + +type AllocateStaticIpInput struct { + _ struct{} `type:"structure"` + + // The name of the static IP address. + // + // StaticIpName is a required field + StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` +} + +// String returns the string representation +func (s AllocateStaticIpInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AllocateStaticIpInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AllocateStaticIpInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AllocateStaticIpInput"} + if s.StaticIpName == nil { + invalidParams.Add(request.NewErrParamRequired("StaticIpName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetStaticIpName sets the StaticIpName field's value. +func (s *AllocateStaticIpInput) SetStaticIpName(v string) *AllocateStaticIpInput { + s.StaticIpName = &v + return s +} + +type AllocateStaticIpOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` +} + +// String returns the string representation +func (s AllocateStaticIpOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AllocateStaticIpOutput) GoString() string { + return s.String() +} + +// SetOperations sets the Operations field's value. +func (s *AllocateStaticIpOutput) SetOperations(v []*Operation) *AllocateStaticIpOutput { + s.Operations = v + return s +} + +type AttachCertificateToDistributionInput struct { + _ struct{} `type:"structure"` + + // The name of the certificate to attach to a distribution. + // + // Only certificates with a status of ISSUED can be attached to a distribution. + // + // Use the GetCertificates action to get a list of certificate names that you + // can specify. + // + // This is the name of the certificate resource type and is used only to reference + // the certificate in other API actions. It can be different than the domain + // name of the certificate. For example, your certificate name might be WordPress-Blog-Certificate + // and the domain name of the certificate might be example.com. + // + // CertificateName is a required field + CertificateName *string `locationName:"certificateName" type:"string" required:"true"` + + // The name of the distribution that the certificate will be attached to. + // + // Use the GetDistributions action to get a list of distribution names that + // you can specify. + // + // DistributionName is a required field + DistributionName *string `locationName:"distributionName" type:"string" required:"true"` +} + +// String returns the string representation +func (s AttachCertificateToDistributionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachCertificateToDistributionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AttachCertificateToDistributionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AttachCertificateToDistributionInput"} + if s.CertificateName == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateName")) + } + if s.DistributionName == nil { + invalidParams.Add(request.NewErrParamRequired("DistributionName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCertificateName sets the CertificateName field's value. +func (s *AttachCertificateToDistributionInput) SetCertificateName(v string) *AttachCertificateToDistributionInput { + s.CertificateName = &v + return s +} + +// SetDistributionName sets the DistributionName field's value. +func (s *AttachCertificateToDistributionInput) SetDistributionName(v string) *AttachCertificateToDistributionInput { + s.DistributionName = &v + return s +} + +type AttachCertificateToDistributionOutput struct { + _ struct{} `type:"structure"` + + // An object that describes the result of the action, such as the status of + // the request, the timestamp of the request, and the resources affected by + // the request. + Operation *Operation `locationName:"operation" type:"structure"` +} + +// String returns the string representation +func (s AttachCertificateToDistributionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachCertificateToDistributionOutput) GoString() string { + return s.String() +} + +// SetOperation sets the Operation field's value. +func (s *AttachCertificateToDistributionOutput) SetOperation(v *Operation) *AttachCertificateToDistributionOutput { + s.Operation = v + return s +} + +type AttachDiskInput struct { + _ struct{} `type:"structure"` + + // The unique Lightsail disk name (e.g., my-disk). + // + // DiskName is a required field + DiskName *string `locationName:"diskName" type:"string" required:"true"` + + // The disk path to expose to the instance (e.g., /dev/xvdf). + // + // DiskPath is a required field + DiskPath *string `locationName:"diskPath" type:"string" required:"true"` + + // The name of the Lightsail instance where you want to utilize the storage + // disk. + // + // InstanceName is a required field + InstanceName *string `locationName:"instanceName" type:"string" required:"true"` +} + +// String returns the string representation +func (s AttachDiskInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachDiskInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AttachDiskInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AttachDiskInput"} + if s.DiskName == nil { + invalidParams.Add(request.NewErrParamRequired("DiskName")) + } + if s.DiskPath == nil { + invalidParams.Add(request.NewErrParamRequired("DiskPath")) + } + if s.InstanceName == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDiskName sets the DiskName field's value. +func (s *AttachDiskInput) SetDiskName(v string) *AttachDiskInput { + s.DiskName = &v + return s +} + +// SetDiskPath sets the DiskPath field's value. +func (s *AttachDiskInput) SetDiskPath(v string) *AttachDiskInput { + s.DiskPath = &v + return s +} + +// SetInstanceName sets the InstanceName field's value. +func (s *AttachDiskInput) SetInstanceName(v string) *AttachDiskInput { + s.InstanceName = &v + return s +} + +type AttachDiskOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` +} + +// String returns the string representation +func (s AttachDiskOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachDiskOutput) GoString() string { + return s.String() +} + +// SetOperations sets the Operations field's value. +func (s *AttachDiskOutput) SetOperations(v []*Operation) *AttachDiskOutput { + s.Operations = v + return s +} + +type AttachInstancesToLoadBalancerInput struct { + _ struct{} `type:"structure"` + + // An array of strings representing the instance name(s) you want to attach + // to your load balancer. + // + // An instance must be running before you can attach it to your load balancer. + // + // There are no additional limits on the number of instances you can attach + // to your load balancer, aside from the limit of Lightsail instances you can + // create in your account (20). + // + // InstanceNames is a required field + InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` + + // The name of the load balancer. + // + // LoadBalancerName is a required field + LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` +} + +// String returns the string representation +func (s AttachInstancesToLoadBalancerInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachInstancesToLoadBalancerInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AttachInstancesToLoadBalancerInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AttachInstancesToLoadBalancerInput"} + if s.InstanceNames == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceNames")) + } + if s.LoadBalancerName == nil { + invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetInstanceNames sets the InstanceNames field's value. +func (s *AttachInstancesToLoadBalancerInput) SetInstanceNames(v []*string) *AttachInstancesToLoadBalancerInput { + s.InstanceNames = v + return s +} + +// SetLoadBalancerName sets the LoadBalancerName field's value. +func (s *AttachInstancesToLoadBalancerInput) SetLoadBalancerName(v string) *AttachInstancesToLoadBalancerInput { + s.LoadBalancerName = &v + return s +} + +type AttachInstancesToLoadBalancerOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` +} + +// String returns the string representation +func (s AttachInstancesToLoadBalancerOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachInstancesToLoadBalancerOutput) GoString() string { + return s.String() +} + +// SetOperations sets the Operations field's value. +func (s *AttachInstancesToLoadBalancerOutput) SetOperations(v []*Operation) *AttachInstancesToLoadBalancerOutput { + s.Operations = v + return s +} + +type AttachLoadBalancerTlsCertificateInput struct { + _ struct{} `type:"structure"` + + // The name of your SSL/TLS certificate. + // + // CertificateName is a required field + CertificateName *string `locationName:"certificateName" type:"string" required:"true"` + + // The name of the load balancer to which you want to associate the SSL/TLS + // certificate. + // + // LoadBalancerName is a required field + LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` +} + +// String returns the string representation +func (s AttachLoadBalancerTlsCertificateInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachLoadBalancerTlsCertificateInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AttachLoadBalancerTlsCertificateInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AttachLoadBalancerTlsCertificateInput"} + if s.CertificateName == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateName")) + } + if s.LoadBalancerName == nil { + invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCertificateName sets the CertificateName field's value. +func (s *AttachLoadBalancerTlsCertificateInput) SetCertificateName(v string) *AttachLoadBalancerTlsCertificateInput { + s.CertificateName = &v + return s +} + +// SetLoadBalancerName sets the LoadBalancerName field's value. +func (s *AttachLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *AttachLoadBalancerTlsCertificateInput { + s.LoadBalancerName = &v + return s +} + +type AttachLoadBalancerTlsCertificateOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + // + // These SSL/TLS certificates are only usable by Lightsail load balancers. You + // can't get the certificate and use it for another purpose. + Operations []*Operation `locationName:"operations" type:"list"` +} + +// String returns the string representation +func (s AttachLoadBalancerTlsCertificateOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachLoadBalancerTlsCertificateOutput) GoString() string { + return s.String() +} + +// SetOperations sets the Operations field's value. +func (s *AttachLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *AttachLoadBalancerTlsCertificateOutput { + s.Operations = v + return s +} + +type AttachStaticIpInput struct { + _ struct{} `type:"structure"` + + // The instance name to which you want to attach the static IP address. + // + // InstanceName is a required field + InstanceName *string `locationName:"instanceName" type:"string" required:"true"` + + // The name of the static IP. + // + // StaticIpName is a required field + StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` +} + +// String returns the string representation +func (s AttachStaticIpInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachStaticIpInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AttachStaticIpInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AttachStaticIpInput"} + if s.InstanceName == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceName")) + } + if s.StaticIpName == nil { + invalidParams.Add(request.NewErrParamRequired("StaticIpName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetInstanceName sets the InstanceName field's value. +func (s *AttachStaticIpInput) SetInstanceName(v string) *AttachStaticIpInput { + s.InstanceName = &v + return s +} + +// SetStaticIpName sets the StaticIpName field's value. +func (s *AttachStaticIpInput) SetStaticIpName(v string) *AttachStaticIpInput { + s.StaticIpName = &v + return s +} + +type AttachStaticIpOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` +} + +// String returns the string representation +func (s AttachStaticIpOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachStaticIpOutput) GoString() string { + return s.String() +} + +// SetOperations sets the Operations field's value. +func (s *AttachStaticIpOutput) SetOperations(v []*Operation) *AttachStaticIpOutput { + s.Operations = v + return s +} + +// Describes a block storage disk that is attached to an instance, and is included +// in an automatic snapshot. +type AttachedDisk struct { + _ struct{} `type:"structure"` + + // The path of the disk (e.g., /dev/xvdf). + Path *string `locationName:"path" type:"string"` + + // The size of the disk in GB. + SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` +} + +// String returns the string representation +func (s AttachedDisk) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AttachedDisk) GoString() string { + return s.String() +} + +// SetPath sets the Path field's value. +func (s *AttachedDisk) SetPath(v string) *AttachedDisk { + s.Path = &v + return s +} + +// SetSizeInGb sets the SizeInGb field's value. +func (s *AttachedDisk) SetSizeInGb(v int64) *AttachedDisk { + s.SizeInGb = &v + return s +} + +// Describes a request to enable or modify the automatic snapshot add-on for +// an Amazon Lightsail instance or disk. +// +// When you modify the automatic snapshot time for a resource, it is typically +// effective immediately except under the following conditions: +// +// * If an automatic snapshot has been created for the current day, and you +// change the snapshot time to a later time of day, then the new snapshot +// time will be effective the following day. This ensures that two snapshots +// are not created for the current day. +// +// * If an automatic snapshot has not yet been created for the current day, +// and you change the snapshot time to an earlier time of day, then the new +// snapshot time will be effective the following day and a snapshot is automatically +// created at the previously set time for the current day. This ensures that +// a snapshot is created for the current day. +// +// * If an automatic snapshot has not yet been created for the current day, +// and you change the snapshot time to a time that is within 30 minutes from +// your current time, then the new snapshot time will be effective the following +// day and a snapshot is automatically created at the previously set time +// for the current day. This ensures that a snapshot is created for the current +// day, because 30 minutes is required between your current time and the +// new snapshot time that you specify. +// +// * If an automatic snapshot is scheduled to be created within 30 minutes +// from your current time and you change the snapshot time, then the new +// snapshot time will be effective the following day and a snapshot is automatically +// created at the previously set time for the current day. This ensures that +// a snapshot is created for the current day, because 30 minutes is required +// between your current time and the new snapshot time that you specify. +type AutoSnapshotAddOnRequest struct { + _ struct{} `type:"structure"` + + // The daily time when an automatic snapshot will be created. + // + // Constraints: + // + // * Must be in HH:00 format, and in an hourly increment. + // + // * Specified in Coordinated Universal Time (UTC). + // + // * The snapshot will be automatically created between the time specified + // and up to 45 minutes after. + SnapshotTimeOfDay *string `locationName:"snapshotTimeOfDay" type:"string"` +} + +// String returns the string representation +func (s AutoSnapshotAddOnRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AutoSnapshotAddOnRequest) GoString() string { + return s.String() +} + +// SetSnapshotTimeOfDay sets the SnapshotTimeOfDay field's value. +func (s *AutoSnapshotAddOnRequest) SetSnapshotTimeOfDay(v string) *AutoSnapshotAddOnRequest { + s.SnapshotTimeOfDay = &v + return s +} + +// Describes an automatic snapshot. +type AutoSnapshotDetails struct { + _ struct{} `type:"structure"` + + // The timestamp when the automatic snapshot was created. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + + // The date of the automatic snapshot in YYYY-MM-DD format. + Date *string `locationName:"date" type:"string"` + + // An array of objects that describe the block storage disks attached to the + // instance when the automatic snapshot was created. + FromAttachedDisks []*AttachedDisk `locationName:"fromAttachedDisks" type:"list"` + + // The status of the automatic snapshot. + Status *string `locationName:"status" type:"string" enum:"AutoSnapshotStatus"` +} + +// String returns the string representation +func (s AutoSnapshotDetails) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AutoSnapshotDetails) GoString() string { + return s.String() +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *AutoSnapshotDetails) SetCreatedAt(v time.Time) *AutoSnapshotDetails { + s.CreatedAt = &v + return s +} + +// SetDate sets the Date field's value. +func (s *AutoSnapshotDetails) SetDate(v string) *AutoSnapshotDetails { + s.Date = &v + return s +} + +// SetFromAttachedDisks sets the FromAttachedDisks field's value. +func (s *AutoSnapshotDetails) SetFromAttachedDisks(v []*AttachedDisk) *AutoSnapshotDetails { + s.FromAttachedDisks = v + return s +} + +// SetStatus sets the Status field's value. +func (s *AutoSnapshotDetails) SetStatus(v string) *AutoSnapshotDetails { + s.Status = &v + return s +} + +// Describes an Availability Zone. +type AvailabilityZone struct { + _ struct{} `type:"structure"` + + // The state of the Availability Zone. + State *string `locationName:"state" type:"string"` + + // The name of the Availability Zone. The format is us-east-2a (case-sensitive). + ZoneName *string `locationName:"zoneName" type:"string"` +} + +// String returns the string representation +func (s AvailabilityZone) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AvailabilityZone) GoString() string { + return s.String() +} + +// SetState sets the State field's value. +func (s *AvailabilityZone) SetState(v string) *AvailabilityZone { + s.State = &v + return s +} + +// SetZoneName sets the ZoneName field's value. +func (s *AvailabilityZone) SetZoneName(v string) *AvailabilityZone { + s.ZoneName = &v + return s +} + +// Describes a blueprint (a virtual private server image). +type Blueprint struct { + _ struct{} `type:"structure"` + + // The ID for the virtual private server image (e.g., app_wordpress_4_4 or app_lamp_7_0). + BlueprintId *string `locationName:"blueprintId" type:"string"` + + // The description of the blueprint. + Description *string `locationName:"description" type:"string"` + + // The group name of the blueprint (e.g., amazon-linux). + Group *string `locationName:"group" type:"string"` + + // A Boolean value indicating whether the blueprint is active. Inactive blueprints + // are listed to support customers with existing instances but are not necessarily + // available for launch of new instances. Blueprints are marked inactive when + // they become outdated due to operating system updates or new application releases. + IsActive *bool `locationName:"isActive" type:"boolean"` + + // The end-user license agreement URL for the image or blueprint. + LicenseUrl *string `locationName:"licenseUrl" type:"string"` + + // The minimum bundle power required to run this blueprint. For example, you + // need a bundle with a power value of 500 or more to create an instance that + // uses a blueprint with a minimum power value of 500. 0 indicates that the + // blueprint runs on all instance sizes. + MinPower *int64 `locationName:"minPower" type:"integer"` + + // The friendly name of the blueprint (e.g., Amazon Linux). + Name *string `locationName:"name" type:"string"` + + // The operating system platform (either Linux/Unix-based or Windows Server-based) + // of the blueprint. + Platform *string `locationName:"platform" type:"string" enum:"InstancePlatform"` + + // The product URL to learn more about the image or blueprint. + ProductUrl *string `locationName:"productUrl" type:"string"` + + // The type of the blueprint (e.g., os or app). + Type *string `locationName:"type" type:"string" enum:"BlueprintType"` + + // The version number of the operating system, application, or stack (e.g., + // 2016.03.0). + Version *string `locationName:"version" type:"string"` + + // The version code. + VersionCode *string `locationName:"versionCode" type:"string"` +} + +// String returns the string representation +func (s Blueprint) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Blueprint) GoString() string { + return s.String() +} + +// SetBlueprintId sets the BlueprintId field's value. +func (s *Blueprint) SetBlueprintId(v string) *Blueprint { + s.BlueprintId = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *Blueprint) SetDescription(v string) *Blueprint { + s.Description = &v + return s +} + +// SetGroup sets the Group field's value. +func (s *Blueprint) SetGroup(v string) *Blueprint { + s.Group = &v + return s +} + +// SetIsActive sets the IsActive field's value. +func (s *Blueprint) SetIsActive(v bool) *Blueprint { + s.IsActive = &v + return s +} + +// SetLicenseUrl sets the LicenseUrl field's value. +func (s *Blueprint) SetLicenseUrl(v string) *Blueprint { + s.LicenseUrl = &v + return s +} + +// SetMinPower sets the MinPower field's value. +func (s *Blueprint) SetMinPower(v int64) *Blueprint { + s.MinPower = &v + return s +} + +// SetName sets the Name field's value. +func (s *Blueprint) SetName(v string) *Blueprint { + s.Name = &v + return s +} + +// SetPlatform sets the Platform field's value. +func (s *Blueprint) SetPlatform(v string) *Blueprint { + s.Platform = &v + return s +} + +// SetProductUrl sets the ProductUrl field's value. +func (s *Blueprint) SetProductUrl(v string) *Blueprint { + s.ProductUrl = &v + return s +} + +// SetType sets the Type field's value. +func (s *Blueprint) SetType(v string) *Blueprint { + s.Type = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *Blueprint) SetVersion(v string) *Blueprint { + s.Version = &v + return s +} + +// SetVersionCode sets the VersionCode field's value. +func (s *Blueprint) SetVersionCode(v string) *Blueprint { + s.VersionCode = &v + return s +} + +// Describes a bundle, which is a set of specs describing your virtual private +// server (or instance). +type Bundle struct { + _ struct{} `type:"structure"` + + // The bundle ID (e.g., micro_1_0). + BundleId *string `locationName:"bundleId" type:"string"` + + // The number of vCPUs included in the bundle (e.g., 2). + CpuCount *int64 `locationName:"cpuCount" type:"integer"` + + // The size of the SSD (e.g., 30). + DiskSizeInGb *int64 `locationName:"diskSizeInGb" type:"integer"` + + // The Amazon EC2 instance type (e.g., t2.micro). + InstanceType *string `locationName:"instanceType" type:"string"` + + // A Boolean value indicating whether the bundle is active. + IsActive *bool `locationName:"isActive" type:"boolean"` + + // A friendly name for the bundle (e.g., Micro). + Name *string `locationName:"name" type:"string"` + + // A numeric value that represents the power of the bundle (e.g., 500). You + // can use the bundle's power value in conjunction with a blueprint's minimum + // power value to determine whether the blueprint will run on the bundle. For + // example, you need a bundle with a power value of 500 or more to create an + // instance that uses a blueprint with a minimum power value of 500. + Power *int64 `locationName:"power" type:"integer"` + + // The price in US dollars (e.g., 5.0) of the bundle. + Price *float64 `locationName:"price" type:"float"` + + // The amount of RAM in GB (e.g., 2.0). + RamSizeInGb *float64 `locationName:"ramSizeInGb" type:"float"` + + // The operating system platform (Linux/Unix-based or Windows Server-based) + // that the bundle supports. You can only launch a WINDOWS bundle on a blueprint + // that supports the WINDOWS platform. LINUX_UNIX blueprints require a LINUX_UNIX + // bundle. + SupportedPlatforms []*string `locationName:"supportedPlatforms" type:"list"` + + // The data transfer rate per month in GB (e.g., 2000). + TransferPerMonthInGb *int64 `locationName:"transferPerMonthInGb" type:"integer"` +} + +// String returns the string representation +func (s Bundle) String() string { + return awsutil.Prettify(s) +} // GoString returns the string representation -func (s AccessDeniedException) GoString() string { +func (s Bundle) GoString() string { return s.String() } -func newErrorAccessDeniedException(v protocol.ResponseMetadata) error { - return &AccessDeniedException{ - RespMetadata: v, - } +// SetBundleId sets the BundleId field's value. +func (s *Bundle) SetBundleId(v string) *Bundle { + s.BundleId = &v + return s } -// Code returns the exception type name. -func (s *AccessDeniedException) Code() string { - return "AccessDeniedException" +// SetCpuCount sets the CpuCount field's value. +func (s *Bundle) SetCpuCount(v int64) *Bundle { + s.CpuCount = &v + return s } -// Message returns the exception's message. -func (s *AccessDeniedException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" +// SetDiskSizeInGb sets the DiskSizeInGb field's value. +func (s *Bundle) SetDiskSizeInGb(v int64) *Bundle { + s.DiskSizeInGb = &v + return s } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *AccessDeniedException) OrigErr() error { - return nil +// SetInstanceType sets the InstanceType field's value. +func (s *Bundle) SetInstanceType(v string) *Bundle { + s.InstanceType = &v + return s } -func (s *AccessDeniedException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetIsActive sets the IsActive field's value. +func (s *Bundle) SetIsActive(v bool) *Bundle { + s.IsActive = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *AccessDeniedException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetName sets the Name field's value. +func (s *Bundle) SetName(v string) *Bundle { + s.Name = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *AccessDeniedException) RequestID() string { - return s.RespMetadata.RequestID +// SetPower sets the Power field's value. +func (s *Bundle) SetPower(v int64) *Bundle { + s.Power = &v + return s } -// Lightsail throws this exception when an account is still in the setup in -// progress state. -type AccountSetupInProgressException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +// SetPrice sets the Price field's value. +func (s *Bundle) SetPrice(v float64) *Bundle { + s.Price = &v + return s +} - Code_ *string `locationName:"code" type:"string"` +// SetRamSizeInGb sets the RamSizeInGb field's value. +func (s *Bundle) SetRamSizeInGb(v float64) *Bundle { + s.RamSizeInGb = &v + return s +} - Docs *string `locationName:"docs" type:"string"` +// SetSupportedPlatforms sets the SupportedPlatforms field's value. +func (s *Bundle) SetSupportedPlatforms(v []*string) *Bundle { + s.SupportedPlatforms = v + return s +} - Message_ *string `locationName:"message" type:"string"` +// SetTransferPerMonthInGb sets the TransferPerMonthInGb field's value. +func (s *Bundle) SetTransferPerMonthInGb(v int64) *Bundle { + s.TransferPerMonthInGb = &v + return s +} - Tip *string `locationName:"tip" type:"string"` +// Describes the default cache behavior of an Amazon Lightsail content delivery +// network (CDN) distribution. +type CacheBehavior struct { + _ struct{} `type:"structure"` + + // The cache behavior of the distribution. + // + // The following cache behaviors can be specified: + // + // * cache - This option is best for static sites. When specified, your distribution + // caches and serves your entire website as static content. This behavior + // is ideal for websites with static content that doesn't change depending + // on who views it, or for websites that don't use cookies, headers, or query + // strings to personalize content. + // + // * dont-cache - This option is best for sites that serve a mix of static + // and dynamic content. When specified, your distribution caches and serve + // only the content that is specified in the distribution's CacheBehaviorPerPath + // parameter. This behavior is ideal for websites or web applications that + // use cookies, headers, and query strings to personalize content for individual + // users. + Behavior *string `locationName:"behavior" type:"string" enum:"BehaviorEnum"` } // String returns the string representation -func (s AccountSetupInProgressException) String() string { +func (s CacheBehavior) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AccountSetupInProgressException) GoString() string { +func (s CacheBehavior) GoString() string { return s.String() } -func newErrorAccountSetupInProgressException(v protocol.ResponseMetadata) error { - return &AccountSetupInProgressException{ - RespMetadata: v, - } +// SetBehavior sets the Behavior field's value. +func (s *CacheBehavior) SetBehavior(v string) *CacheBehavior { + s.Behavior = &v + return s } -// Code returns the exception type name. -func (s *AccountSetupInProgressException) Code() string { - return "AccountSetupInProgressException" -} +// Describes the per-path cache behavior of an Amazon Lightsail content delivery +// network (CDN) distribution. +// +// A per-path cache behavior is used to override, or add an exception to, the +// default cache behavior of a distribution. For example, if the cacheBehavior +// is set to cache, then a per-path cache behavior can be used to specify a +// directory, file, or file type that your distribution will cache. Alternately, +// if the distribution's cacheBehavior is dont-cache, then a per-path cache +// behavior can be used to specify a directory, file, or file type that your +// distribution will not cache. +// +// if the cacheBehavior's behavior is set to 'cache', then +type CacheBehaviorPerPath struct { + _ struct{} `type:"structure"` -// Message returns the exception's message. -func (s *AccountSetupInProgressException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" + // The cache behavior for the specified path. + // + // You can specify one of the following per-path cache behaviors: + // + // * cache - This behavior caches the specified path. + // + // * dont-cache - This behavior doesn't cache the specified path. + Behavior *string `locationName:"behavior" type:"string" enum:"BehaviorEnum"` + + // The path to a directory or file to cached, or not cache. Use an asterisk + // symbol to specify wildcard directories (path/to/assets/*), and file types + // (*.html, *jpg, *js). Directories and file paths are case-sensitive. + // + // Examples: + // + // * Specify the following to cache all files in the document root of an + // Apache web server running on a Lightsail instance. var/www/html/ + // + // * Specify the following file to cache only the index page in the document + // root of an Apache web server. var/www/html/index.html + // + // * Specify the following to cache only the .html files in the document + // root of an Apache web server. var/www/html/*.html + // + // * Specify the following to cache only the .jpg, .png, and .gif files in + // the images sub-directory of the document root of an Apache web server. + // var/www/html/images/*.jpg var/www/html/images/*.png var/www/html/images/*.gif + // Specify the following to cache all files in the images sub-directory of + // the document root of an Apache web server. var/www/html/images/ + Path *string `locationName:"path" type:"string"` } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *AccountSetupInProgressException) OrigErr() error { - return nil +// String returns the string representation +func (s CacheBehaviorPerPath) String() string { + return awsutil.Prettify(s) } -func (s *AccountSetupInProgressException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// GoString returns the string representation +func (s CacheBehaviorPerPath) GoString() string { + return s.String() } -// Status code returns the HTTP status code for the request's response error. -func (s *AccountSetupInProgressException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetBehavior sets the Behavior field's value. +func (s *CacheBehaviorPerPath) SetBehavior(v string) *CacheBehaviorPerPath { + s.Behavior = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *AccountSetupInProgressException) RequestID() string { - return s.RespMetadata.RequestID +// SetPath sets the Path field's value. +func (s *CacheBehaviorPerPath) SetPath(v string) *CacheBehaviorPerPath { + s.Path = &v + return s } -// Describes an add-on that is enabled for an Amazon Lightsail resource. -type AddOn struct { +// Describes the cache settings of an Amazon Lightsail content delivery network +// (CDN) distribution. +// +// These settings apply only to your distribution's cacheBehaviors (including +// the defaultCacheBehavior) that have a behavior of cache. +type CacheSettings struct { _ struct{} `type:"structure"` - // The name of the add-on. - Name *string `locationName:"name" type:"string"` + // The HTTP methods that are processed and forwarded to the distribution's origin. + // + // You can specify the following options: + // + // * GET,HEAD - The distribution forwards the GET and HEAD methods. + // + // * GET,HEAD,OPTIONS - The distribution forwards the GET, HEAD, and OPTIONS + // methods. + // + // * GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE - The distribution forwards the + // GET, HEAD, OPTIONS, PUT, PATCH, POST, and DELETE methods. + // + // If you specify the third option, you might need to restrict access to your + // distribution's origin so users can't perform operations that you don't want + // them to. For example, you might not want users to have permission to delete + // objects from your origin. + AllowedHTTPMethods *string `locationName:"allowedHTTPMethods" type:"string"` - // The next daily time an automatic snapshot will be created. + // The HTTP method responses that are cached by your distribution. + // + // You can specify the following options: // - // The time shown is in HH:00 format, and in Coordinated Universal Time (UTC). + // * GET,HEAD - The distribution caches responses to the GET and HEAD methods. // - // The snapshot is automatically created between the time shown and up to 45 - // minutes after. - NextSnapshotTimeOfDay *string `locationName:"nextSnapshotTimeOfDay" type:"string"` + // * GET,HEAD,OPTIONS - The distribution caches responses to the GET, HEAD, + // and OPTIONS methods. + CachedHTTPMethods *string `locationName:"cachedHTTPMethods" type:"string"` - // The daily time when an automatic snapshot is created. + // The default amount of time that objects stay in the distribution's cache + // before the distribution forwards another request to the origin to determine + // whether the content has been updated. // - // The time shown is in HH:00 format, and in Coordinated Universal Time (UTC). + // The value specified applies only when the origin does not add HTTP headers + // such as Cache-Control max-age, Cache-Control s-maxage, and Expires to objects. + DefaultTTL *int64 `locationName:"defaultTTL" type:"long"` + + // An object that describes the cookies that are forwarded to the origin. Your + // content is cached based on the cookies that are forwarded. + ForwardedCookies *CookieObject `locationName:"forwardedCookies" type:"structure"` + + // An object that describes the headers that are forwarded to the origin. Your + // content is cached based on the headers that are forwarded. + ForwardedHeaders *HeaderObject `locationName:"forwardedHeaders" type:"structure"` + + // An object that describes the query strings that are forwarded to the origin. + // Your content is cached based on the query strings that are forwarded. + ForwardedQueryStrings *QueryStringObject `locationName:"forwardedQueryStrings" type:"structure"` + + // The maximum amount of time that objects stay in the distribution's cache + // before the distribution forwards another request to the origin to determine + // whether the object has been updated. // - // The snapshot is automatically created between the time shown and up to 45 - // minutes after. - SnapshotTimeOfDay *string `locationName:"snapshotTimeOfDay" type:"string"` + // The value specified applies only when the origin adds HTTP headers such as + // Cache-Control max-age, Cache-Control s-maxage, and Expires to objects. + MaximumTTL *int64 `locationName:"maximumTTL" type:"long"` - // The status of the add-on. - Status *string `locationName:"status" type:"string"` + // The minimum amount of time that objects stay in the distribution's cache + // before the distribution forwards another request to the origin to determine + // whether the object has been updated. + // + // A value of 0 must be specified for minimumTTL if the distribution is configured + // to forward all headers to the origin. + MinimumTTL *int64 `locationName:"minimumTTL" type:"long"` } // String returns the string representation -func (s AddOn) String() string { +func (s CacheSettings) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AddOn) GoString() string { +func (s CacheSettings) GoString() string { return s.String() } -// SetName sets the Name field's value. -func (s *AddOn) SetName(v string) *AddOn { - s.Name = &v +// SetAllowedHTTPMethods sets the AllowedHTTPMethods field's value. +func (s *CacheSettings) SetAllowedHTTPMethods(v string) *CacheSettings { + s.AllowedHTTPMethods = &v return s } -// SetNextSnapshotTimeOfDay sets the NextSnapshotTimeOfDay field's value. -func (s *AddOn) SetNextSnapshotTimeOfDay(v string) *AddOn { - s.NextSnapshotTimeOfDay = &v +// SetCachedHTTPMethods sets the CachedHTTPMethods field's value. +func (s *CacheSettings) SetCachedHTTPMethods(v string) *CacheSettings { + s.CachedHTTPMethods = &v return s } -// SetSnapshotTimeOfDay sets the SnapshotTimeOfDay field's value. -func (s *AddOn) SetSnapshotTimeOfDay(v string) *AddOn { - s.SnapshotTimeOfDay = &v +// SetDefaultTTL sets the DefaultTTL field's value. +func (s *CacheSettings) SetDefaultTTL(v int64) *CacheSettings { + s.DefaultTTL = &v return s } -// SetStatus sets the Status field's value. -func (s *AddOn) SetStatus(v string) *AddOn { - s.Status = &v +// SetForwardedCookies sets the ForwardedCookies field's value. +func (s *CacheSettings) SetForwardedCookies(v *CookieObject) *CacheSettings { + s.ForwardedCookies = v return s } -// Describes a request to enable, modify, or disable an add-on for an Amazon -// Lightsail resource. -// -// An additional cost may be associated with enabling add-ons. For more information, -// see the Lightsail pricing page (https://aws.amazon.com/lightsail/pricing/). -type AddOnRequest struct { - _ struct{} `type:"structure"` - - // The add-on type. - // - // AddOnType is a required field - AddOnType *string `locationName:"addOnType" type:"string" required:"true" enum:"AddOnType"` - - // An object that represents additional parameters when enabling or modifying - // the automatic snapshot add-on. - AutoSnapshotAddOnRequest *AutoSnapshotAddOnRequest `locationName:"autoSnapshotAddOnRequest" type:"structure"` -} - -// String returns the string representation -func (s AddOnRequest) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AddOnRequest) GoString() string { - return s.String() +// SetForwardedHeaders sets the ForwardedHeaders field's value. +func (s *CacheSettings) SetForwardedHeaders(v *HeaderObject) *CacheSettings { + s.ForwardedHeaders = v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AddOnRequest) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AddOnRequest"} - if s.AddOnType == nil { - invalidParams.Add(request.NewErrParamRequired("AddOnType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetForwardedQueryStrings sets the ForwardedQueryStrings field's value. +func (s *CacheSettings) SetForwardedQueryStrings(v *QueryStringObject) *CacheSettings { + s.ForwardedQueryStrings = v + return s } -// SetAddOnType sets the AddOnType field's value. -func (s *AddOnRequest) SetAddOnType(v string) *AddOnRequest { - s.AddOnType = &v +// SetMaximumTTL sets the MaximumTTL field's value. +func (s *CacheSettings) SetMaximumTTL(v int64) *CacheSettings { + s.MaximumTTL = &v return s } -// SetAutoSnapshotAddOnRequest sets the AutoSnapshotAddOnRequest field's value. -func (s *AddOnRequest) SetAutoSnapshotAddOnRequest(v *AutoSnapshotAddOnRequest) *AddOnRequest { - s.AutoSnapshotAddOnRequest = v +// SetMinimumTTL sets the MinimumTTL field's value. +func (s *CacheSettings) SetMinimumTTL(v int64) *CacheSettings { + s.MinimumTTL = &v return s } -// Describes an alarm. +// Describes the full details of an Amazon Lightsail SSL/TLS certificate. // -// An alarm is a way to monitor your Amazon Lightsail resource metrics. For -// more information, see Alarms in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-alarms). -type Alarm struct { +// To get a summary of a certificate, use the GetCertificates action and ommit +// includeCertificateDetails from your request. The response will include only +// the certificate Amazon Resource Name (ARN), certificate name, domain name, +// and tags. +type Certificate struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the alarm. + // The Amazon Resource Name (ARN) of the certificate. Arn *string `locationName:"arn" type:"string"` - // The arithmetic operation used when comparing the specified statistic and - // threshold. - ComparisonOperator *string `locationName:"comparisonOperator" type:"string" enum:"ComparisonOperator"` + // The timestamp when the certificate was created. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - // The contact protocols for the alarm, such as Email, SMS (text messaging), - // or both. - ContactProtocols []*string `locationName:"contactProtocols" type:"list"` + // The domain name of the certificate. + DomainName *string `locationName:"domainName" type:"string"` - // The timestamp when the alarm was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + // An array of objects that describe the domain validation records of the certificate. + DomainValidationRecords []*DomainValidationRecord `locationName:"domainValidationRecords" type:"list"` - // The number of data points that must not within the specified threshold to - // trigger the alarm. - DatapointsToAlarm *int64 `locationName:"datapointsToAlarm" type:"integer"` + // The renewal eligibility of the certificate. + EligibleToRenew *string `locationName:"eligibleToRenew" type:"string"` - // The number of periods over which data is compared to the specified threshold. - EvaluationPeriods *int64 `locationName:"evaluationPeriods" type:"integer"` + // The number of Lightsail resources that the certificate is attached to. + InUseResourceCount *int64 `locationName:"inUseResourceCount" type:"integer"` - // An object that lists information about the location of the alarm. - Location *ResourceLocation `locationName:"location" type:"structure"` + // The timestamp when the certificate was issued. + IssuedAt *time.Time `locationName:"issuedAt" type:"timestamp"` - // The name of the metric associated with the alarm. - MetricName *string `locationName:"metricName" type:"string" enum:"MetricName"` + // The certificate authority that issued the certificate. + IssuerCA *string `locationName:"issuerCA" type:"string"` - // An object that lists information about the resource monitored by the alarm. - MonitoredResourceInfo *MonitoredResourceInfo `locationName:"monitoredResourceInfo" type:"structure"` + // The algorithm used to generate the key pair (the public and private key) + // of the certificate. + KeyAlgorithm *string `locationName:"keyAlgorithm" type:"string"` - // The name of the alarm. + // The name of the certificate (e.g., my-certificate). Name *string `locationName:"name" type:"string"` - // Indicates whether the alarm is enabled. - NotificationEnabled *bool `locationName:"notificationEnabled" type:"boolean"` + // The timestamp when the certificate expires. + NotAfter *time.Time `locationName:"notAfter" type:"timestamp"` - // The alarm states that trigger a notification. - NotificationTriggers []*string `locationName:"notificationTriggers" type:"list"` + // The timestamp when the certificate is first valid. + NotBefore *time.Time `locationName:"notBefore" type:"timestamp"` - // The period, in seconds, over which the statistic is applied. - Period *int64 `locationName:"period" min:"60" type:"integer"` + // An object that describes the status of the certificate renewal managed by + // Lightsail. + RenewalSummary *RenewalSummary `locationName:"renewalSummary" type:"structure"` + + // The validation failure reason, if any, of the certificate. + // + // The following failure reasons are possible: + // + // * NO_AVAILABLE_CONTACTS - This failure applies to email validation, which + // is not available for Lightsail certificates. + // + // * ADDITIONAL_VERIFICATION_REQUIRED - Lightsail requires additional information + // to process this certificate request. This can happen as a fraud-protection + // measure, such as when the domain ranks within the Alexa top 1000 websites. + // To provide the required information, use the AWS Support Center (https://console.aws.amazon.com/support/home) + // to contact AWS Support. You cannot request a certificate for Amazon-owned + // domain names such as those ending in amazonaws.com, cloudfront.net, or + // elasticbeanstalk.com. + // + // * DOMAIN_NOT_ALLOWED - One or more of the domain names in the certificate + // request was reported as an unsafe domain by VirusTotal (https://www.virustotal.com/gui/home/url). + // To correct the problem, search for your domain name on the VirusTotal + // (https://www.virustotal.com/gui/home/url) website. If your domain is reported + // as suspicious, see Google Help for Hacked Websites (https://www.google.com/webmasters/hacked/?hl=en) + // to learn what you can do. If you believe that the result is a false positive, + // notify the organization that is reporting the domain. VirusTotal is an + // aggregate of several antivirus and URL scanners and cannot remove your + // domain from a block list itself. After you correct the problem and the + // VirusTotal registry has been updated, request a new certificate. If you + // see this error and your domain is not included in the VirusTotal list, + // visit the AWS Support Center (https://console.aws.amazon.com/support/home) + // and create a case. + // + // * INVALID_PUBLIC_DOMAIN - One or more of the domain names in the certificate + // request is not valid. Typically, this is because a domain name in the + // request is not a valid top-level domain. Try to request a certificate + // again, correcting any spelling errors or typos that were in the failed + // request, and ensure that all domain names in the request are for valid + // top-level domains. For example, you cannot request a certificate for example.invalidpublicdomain + // because invalidpublicdomain is not a valid top-level domain. + // + // * OTHER - Typically, this failure occurs when there is a typographical + // error in one or more of the domain names in the certificate request. Try + // to request a certificate again, correcting any spelling errors or typos + // that were in the failed request. + RequestFailureReason *string `locationName:"requestFailureReason" type:"string"` + + // The reason the certificate was revoked. This value is present only when the + // certificate status is REVOKED. + RevocationReason *string `locationName:"revocationReason" type:"string"` + + // The timestamp when the certificate was revoked. This value is present only + // when the certificate status is REVOKED. + RevokedAt *time.Time `locationName:"revokedAt" type:"timestamp"` - // The Lightsail resource type (e.g., Alarm). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + // The serial number of the certificate. + SerialNumber *string `locationName:"serialNumber" type:"string"` - // The current state of the alarm. - // - // An alarm has the following possible states: - // - // * ALARM — The metric is outside of the defined threshold. - // - // * INSUFFICIENT_DATA — The alarm has just started, the metric is not - // available, or not enough data is available for the metric to determine - // the alarm state. - // - // * OK — The metric is within the defined threshold. - State *string `locationName:"state" type:"string" enum:"AlarmState"` + // The validation status of the certificate. + Status *string `locationName:"status" type:"string" enum:"CertificateStatus"` - // The statistic for the metric associated with the alarm. - // - // The following statistics are available: - // - // * Minimum — The lowest value observed during the specified period. Use - // this value to determine low volumes of activity for your application. - // - // * Maximum — The highest value observed during the specified period. - // Use this value to determine high volumes of activity for your application. - // - // * Sum — All values submitted for the matching metric added together. - // You can use this statistic to determine the total volume of a metric. - // - // * Average — The value of Sum / SampleCount during the specified period. - // By comparing this statistic with the Minimum and Maximum values, you can - // determine the full scope of a metric and how close the average use is - // to the Minimum and Maximum values. This comparison helps you to know when - // to increase or decrease your resources. - // - // * SampleCount — The count, or number, of data points used for the statistical - // calculation. - Statistic *string `locationName:"statistic" type:"string" enum:"MetricStatistic"` + // An array of strings that specify the alternate domains (e.g., example2.com) + // and subdomains (e.g., blog.example.com) of the certificate. + SubjectAlternativeNames []*string `locationName:"subjectAlternativeNames" type:"list"` // The support code. Include this code in your email to support when you have - // questions about your Lightsail alarm. This code enables our support team - // to look up your Lightsail information more easily. + // questions about your Lightsail certificate. This code enables our support + // team to look up your Lightsail information more easily. SupportCode *string `locationName:"supportCode" type:"string"` - // The value against which the specified statistic is compared. - Threshold *float64 `locationName:"threshold" type:"double"` - - // Specifies how the alarm handles missing data points. - // - // An alarm can treat missing data in the following ways: - // - // * breaching — Assume the missing data is not within the threshold. Missing - // data counts towards the number of times the metric is not within the threshold. - // - // * notBreaching — Assume the missing data is within the threshold. Missing - // data does not count towards the number of times the metric is not within - // the threshold. - // - // * ignore — Ignore the missing data. Maintains the current alarm state. - // - // * missing — Missing data is treated as missing. - TreatMissingData *string `locationName:"treatMissingData" type:"string" enum:"TreatMissingData"` - - // The unit of the metric associated with the alarm. - Unit *string `locationName:"unit" type:"string" enum:"MetricUnit"` + // The tag keys and optional values for the resource. For more information about + // tags in Lightsail, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags). + Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s Alarm) String() string { +func (s Certificate) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Alarm) GoString() string { +func (s Certificate) GoString() string { return s.String() } // SetArn sets the Arn field's value. -func (s *Alarm) SetArn(v string) *Alarm { +func (s *Certificate) SetArn(v string) *Certificate { s.Arn = &v return s } -// SetComparisonOperator sets the ComparisonOperator field's value. -func (s *Alarm) SetComparisonOperator(v string) *Alarm { - s.ComparisonOperator = &v +// SetCreatedAt sets the CreatedAt field's value. +func (s *Certificate) SetCreatedAt(v time.Time) *Certificate { + s.CreatedAt = &v return s } -// SetContactProtocols sets the ContactProtocols field's value. -func (s *Alarm) SetContactProtocols(v []*string) *Alarm { - s.ContactProtocols = v +// SetDomainName sets the DomainName field's value. +func (s *Certificate) SetDomainName(v string) *Certificate { + s.DomainName = &v return s } -// SetCreatedAt sets the CreatedAt field's value. -func (s *Alarm) SetCreatedAt(v time.Time) *Alarm { - s.CreatedAt = &v +// SetDomainValidationRecords sets the DomainValidationRecords field's value. +func (s *Certificate) SetDomainValidationRecords(v []*DomainValidationRecord) *Certificate { + s.DomainValidationRecords = v return s } -// SetDatapointsToAlarm sets the DatapointsToAlarm field's value. -func (s *Alarm) SetDatapointsToAlarm(v int64) *Alarm { - s.DatapointsToAlarm = &v +// SetEligibleToRenew sets the EligibleToRenew field's value. +func (s *Certificate) SetEligibleToRenew(v string) *Certificate { + s.EligibleToRenew = &v return s } -// SetEvaluationPeriods sets the EvaluationPeriods field's value. -func (s *Alarm) SetEvaluationPeriods(v int64) *Alarm { - s.EvaluationPeriods = &v +// SetInUseResourceCount sets the InUseResourceCount field's value. +func (s *Certificate) SetInUseResourceCount(v int64) *Certificate { + s.InUseResourceCount = &v return s } -// SetLocation sets the Location field's value. -func (s *Alarm) SetLocation(v *ResourceLocation) *Alarm { - s.Location = v +// SetIssuedAt sets the IssuedAt field's value. +func (s *Certificate) SetIssuedAt(v time.Time) *Certificate { + s.IssuedAt = &v return s } -// SetMetricName sets the MetricName field's value. -func (s *Alarm) SetMetricName(v string) *Alarm { - s.MetricName = &v +// SetIssuerCA sets the IssuerCA field's value. +func (s *Certificate) SetIssuerCA(v string) *Certificate { + s.IssuerCA = &v return s } -// SetMonitoredResourceInfo sets the MonitoredResourceInfo field's value. -func (s *Alarm) SetMonitoredResourceInfo(v *MonitoredResourceInfo) *Alarm { - s.MonitoredResourceInfo = v +// SetKeyAlgorithm sets the KeyAlgorithm field's value. +func (s *Certificate) SetKeyAlgorithm(v string) *Certificate { + s.KeyAlgorithm = &v return s } // SetName sets the Name field's value. -func (s *Alarm) SetName(v string) *Alarm { +func (s *Certificate) SetName(v string) *Certificate { s.Name = &v return s } -// SetNotificationEnabled sets the NotificationEnabled field's value. -func (s *Alarm) SetNotificationEnabled(v bool) *Alarm { - s.NotificationEnabled = &v +// SetNotAfter sets the NotAfter field's value. +func (s *Certificate) SetNotAfter(v time.Time) *Certificate { + s.NotAfter = &v + return s +} + +// SetNotBefore sets the NotBefore field's value. +func (s *Certificate) SetNotBefore(v time.Time) *Certificate { + s.NotBefore = &v + return s +} + +// SetRenewalSummary sets the RenewalSummary field's value. +func (s *Certificate) SetRenewalSummary(v *RenewalSummary) *Certificate { + s.RenewalSummary = v + return s +} + +// SetRequestFailureReason sets the RequestFailureReason field's value. +func (s *Certificate) SetRequestFailureReason(v string) *Certificate { + s.RequestFailureReason = &v + return s +} + +// SetRevocationReason sets the RevocationReason field's value. +func (s *Certificate) SetRevocationReason(v string) *Certificate { + s.RevocationReason = &v + return s +} + +// SetRevokedAt sets the RevokedAt field's value. +func (s *Certificate) SetRevokedAt(v time.Time) *Certificate { + s.RevokedAt = &v + return s +} + +// SetSerialNumber sets the SerialNumber field's value. +func (s *Certificate) SetSerialNumber(v string) *Certificate { + s.SerialNumber = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *Certificate) SetStatus(v string) *Certificate { + s.Status = &v + return s +} + +// SetSubjectAlternativeNames sets the SubjectAlternativeNames field's value. +func (s *Certificate) SetSubjectAlternativeNames(v []*string) *Certificate { + s.SubjectAlternativeNames = v + return s +} + +// SetSupportCode sets the SupportCode field's value. +func (s *Certificate) SetSupportCode(v string) *Certificate { + s.SupportCode = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *Certificate) SetTags(v []*Tag) *Certificate { + s.Tags = v return s } -// SetNotificationTriggers sets the NotificationTriggers field's value. -func (s *Alarm) SetNotificationTriggers(v []*string) *Alarm { - s.NotificationTriggers = v - return s -} +// Describes an Amazon Lightsail SSL/TLS certificate. +type CertificateSummary struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the certificate. + CertificateArn *string `locationName:"certificateArn" type:"string"` + + // An object that describes a certificate in detail. + CertificateDetail *Certificate `locationName:"certificateDetail" type:"structure"` + + // The name of the certificate. + CertificateName *string `locationName:"certificateName" type:"string"` + + // The domain name of the certificate. + DomainName *string `locationName:"domainName" type:"string"` -// SetPeriod sets the Period field's value. -func (s *Alarm) SetPeriod(v int64) *Alarm { - s.Period = &v - return s + // The tag keys and optional values for the resource. For more information about + // tags in Lightsail, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags). + Tags []*Tag `locationName:"tags" type:"list"` } -// SetResourceType sets the ResourceType field's value. -func (s *Alarm) SetResourceType(v string) *Alarm { - s.ResourceType = &v - return s +// String returns the string representation +func (s CertificateSummary) String() string { + return awsutil.Prettify(s) } -// SetState sets the State field's value. -func (s *Alarm) SetState(v string) *Alarm { - s.State = &v - return s +// GoString returns the string representation +func (s CertificateSummary) GoString() string { + return s.String() } -// SetStatistic sets the Statistic field's value. -func (s *Alarm) SetStatistic(v string) *Alarm { - s.Statistic = &v +// SetCertificateArn sets the CertificateArn field's value. +func (s *CertificateSummary) SetCertificateArn(v string) *CertificateSummary { + s.CertificateArn = &v return s } -// SetSupportCode sets the SupportCode field's value. -func (s *Alarm) SetSupportCode(v string) *Alarm { - s.SupportCode = &v +// SetCertificateDetail sets the CertificateDetail field's value. +func (s *CertificateSummary) SetCertificateDetail(v *Certificate) *CertificateSummary { + s.CertificateDetail = v return s } -// SetThreshold sets the Threshold field's value. -func (s *Alarm) SetThreshold(v float64) *Alarm { - s.Threshold = &v +// SetCertificateName sets the CertificateName field's value. +func (s *CertificateSummary) SetCertificateName(v string) *CertificateSummary { + s.CertificateName = &v return s } -// SetTreatMissingData sets the TreatMissingData field's value. -func (s *Alarm) SetTreatMissingData(v string) *Alarm { - s.TreatMissingData = &v +// SetDomainName sets the DomainName field's value. +func (s *CertificateSummary) SetDomainName(v string) *CertificateSummary { + s.DomainName = &v return s } -// SetUnit sets the Unit field's value. -func (s *Alarm) SetUnit(v string) *Alarm { - s.Unit = &v +// SetTags sets the Tags field's value. +func (s *CertificateSummary) SetTags(v []*Tag) *CertificateSummary { + s.Tags = v return s } -type AllocateStaticIpInput struct { +type CloseInstancePublicPortsInput struct { _ struct{} `type:"structure"` - // The name of the static IP address. + // The name of the instance for which to close ports. // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` + // InstanceName is a required field + InstanceName *string `locationName:"instanceName" type:"string" required:"true"` + + // An object to describe the ports to close for the specified instance. + // + // PortInfo is a required field + PortInfo *PortInfo `locationName:"portInfo" type:"structure" required:"true"` } // String returns the string representation -func (s AllocateStaticIpInput) String() string { +func (s CloseInstancePublicPortsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AllocateStaticIpInput) GoString() string { +func (s CloseInstancePublicPortsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *AllocateStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AllocateStaticIpInput"} - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) +func (s *CloseInstancePublicPortsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CloseInstancePublicPortsInput"} + if s.InstanceName == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceName")) + } + if s.PortInfo == nil { + invalidParams.Add(request.NewErrParamRequired("PortInfo")) + } + if s.PortInfo != nil { + if err := s.PortInfo.Validate(); err != nil { + invalidParams.AddNested("PortInfo", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -12681,326 +15653,409 @@ func (s *AllocateStaticIpInput) Validate() error { return nil } -// SetStaticIpName sets the StaticIpName field's value. -func (s *AllocateStaticIpInput) SetStaticIpName(v string) *AllocateStaticIpInput { - s.StaticIpName = &v +// SetInstanceName sets the InstanceName field's value. +func (s *CloseInstancePublicPortsInput) SetInstanceName(v string) *CloseInstancePublicPortsInput { + s.InstanceName = &v return s } -type AllocateStaticIpOutput struct { +// SetPortInfo sets the PortInfo field's value. +func (s *CloseInstancePublicPortsInput) SetPortInfo(v *PortInfo) *CloseInstancePublicPortsInput { + s.PortInfo = v + return s +} + +type CloseInstancePublicPortsOutput struct { _ struct{} `type:"structure"` - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` + // An object that describes the result of the action, such as the status of + // the request, the timestamp of the request, and the resources affected by + // the request. + Operation *Operation `locationName:"operation" type:"structure"` } // String returns the string representation -func (s AllocateStaticIpOutput) String() string { +func (s CloseInstancePublicPortsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AllocateStaticIpOutput) GoString() string { +func (s CloseInstancePublicPortsOutput) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *AllocateStaticIpOutput) SetOperations(v []*Operation) *AllocateStaticIpOutput { - s.Operations = v +// SetOperation sets the Operation field's value. +func (s *CloseInstancePublicPortsOutput) SetOperation(v *Operation) *CloseInstancePublicPortsOutput { + s.Operation = v return s } -type AttachDiskInput struct { +// Describes a CloudFormation stack record created as a result of the create +// cloud formation stack operation. +// +// A CloudFormation stack record provides information about the AWS CloudFormation +// stack used to create a new Amazon Elastic Compute Cloud instance from an +// exported Lightsail instance snapshot. +type CloudFormationStackRecord struct { _ struct{} `type:"structure"` - // The unique Lightsail disk name (e.g., my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` + // The Amazon Resource Name (ARN) of the CloudFormation stack record. + Arn *string `locationName:"arn" type:"string"` - // The disk path to expose to the instance (e.g., /dev/xvdf). - // - // DiskPath is a required field - DiskPath *string `locationName:"diskPath" type:"string" required:"true"` + // The date when the CloudFormation stack record was created. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - // The name of the Lightsail instance where you want to utilize the storage - // disk. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` + // A list of objects describing the destination service, which is AWS CloudFormation, + // and the Amazon Resource Name (ARN) of the AWS CloudFormation stack. + DestinationInfo *DestinationInfo `locationName:"destinationInfo" type:"structure"` + + // A list of objects describing the Availability Zone and AWS Region of the + // CloudFormation stack record. + Location *ResourceLocation `locationName:"location" type:"structure"` + + // The name of the CloudFormation stack record. It starts with CloudFormationStackRecord + // followed by a GUID. + Name *string `locationName:"name" type:"string"` + + // The Lightsail resource type (e.g., CloudFormationStackRecord). + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + + // A list of objects describing the source of the CloudFormation stack record. + SourceInfo []*CloudFormationStackRecordSourceInfo `locationName:"sourceInfo" type:"list"` + + // The current state of the CloudFormation stack record. + State *string `locationName:"state" type:"string" enum:"RecordState"` } // String returns the string representation -func (s AttachDiskInput) String() string { +func (s CloudFormationStackRecord) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AttachDiskInput) GoString() string { +func (s CloudFormationStackRecord) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AttachDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - if s.DiskPath == nil { - invalidParams.Add(request.NewErrParamRequired("DiskPath")) - } - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } +// SetArn sets the Arn field's value. +func (s *CloudFormationStackRecord) SetArn(v string) *CloudFormationStackRecord { + s.Arn = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCreatedAt sets the CreatedAt field's value. +func (s *CloudFormationStackRecord) SetCreatedAt(v time.Time) *CloudFormationStackRecord { + s.CreatedAt = &v + return s } -// SetDiskName sets the DiskName field's value. -func (s *AttachDiskInput) SetDiskName(v string) *AttachDiskInput { - s.DiskName = &v +// SetDestinationInfo sets the DestinationInfo field's value. +func (s *CloudFormationStackRecord) SetDestinationInfo(v *DestinationInfo) *CloudFormationStackRecord { + s.DestinationInfo = v return s } -// SetDiskPath sets the DiskPath field's value. -func (s *AttachDiskInput) SetDiskPath(v string) *AttachDiskInput { - s.DiskPath = &v +// SetLocation sets the Location field's value. +func (s *CloudFormationStackRecord) SetLocation(v *ResourceLocation) *CloudFormationStackRecord { + s.Location = v return s } -// SetInstanceName sets the InstanceName field's value. -func (s *AttachDiskInput) SetInstanceName(v string) *AttachDiskInput { - s.InstanceName = &v +// SetName sets the Name field's value. +func (s *CloudFormationStackRecord) SetName(v string) *CloudFormationStackRecord { + s.Name = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *CloudFormationStackRecord) SetResourceType(v string) *CloudFormationStackRecord { + s.ResourceType = &v + return s +} + +// SetSourceInfo sets the SourceInfo field's value. +func (s *CloudFormationStackRecord) SetSourceInfo(v []*CloudFormationStackRecordSourceInfo) *CloudFormationStackRecord { + s.SourceInfo = v + return s +} + +// SetState sets the State field's value. +func (s *CloudFormationStackRecord) SetState(v string) *CloudFormationStackRecord { + s.State = &v + return s +} + +// Describes the source of a CloudFormation stack record (i.e., the export snapshot +// record). +type CloudFormationStackRecordSourceInfo struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the export snapshot record. + Arn *string `locationName:"arn" type:"string"` + + // The name of the record. + Name *string `locationName:"name" type:"string"` + + // The Lightsail resource type (e.g., ExportSnapshotRecord). + ResourceType *string `locationName:"resourceType" type:"string" enum:"CloudFormationStackRecordSourceType"` +} + +// String returns the string representation +func (s CloudFormationStackRecordSourceInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CloudFormationStackRecordSourceInfo) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *CloudFormationStackRecordSourceInfo) SetArn(v string) *CloudFormationStackRecordSourceInfo { + s.Arn = &v + return s +} + +// SetName sets the Name field's value. +func (s *CloudFormationStackRecordSourceInfo) SetName(v string) *CloudFormationStackRecordSourceInfo { + s.Name = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *CloudFormationStackRecordSourceInfo) SetResourceType(v string) *CloudFormationStackRecordSourceInfo { + s.ResourceType = &v return s } -type AttachDiskOutput struct { +// Describes a contact method. +// +// A contact method is a way to send you notifications. For more information, +// see Notifications in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-notifications). +type ContactMethod struct { _ struct{} `type:"structure"` - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` -} + // The Amazon Resource Name (ARN) of the contact method. + Arn *string `locationName:"arn" type:"string"` -// String returns the string representation -func (s AttachDiskOutput) String() string { - return awsutil.Prettify(s) -} + // The destination of the contact method, such as an email address or a mobile + // phone number. + ContactEndpoint *string `locationName:"contactEndpoint" type:"string"` -// GoString returns the string representation -func (s AttachDiskOutput) GoString() string { - return s.String() -} + // The timestamp when the contact method was created. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` -// SetOperations sets the Operations field's value. -func (s *AttachDiskOutput) SetOperations(v []*Operation) *AttachDiskOutput { - s.Operations = v - return s -} + // Describes the resource location. + Location *ResourceLocation `locationName:"location" type:"structure"` -type AttachInstancesToLoadBalancerInput struct { - _ struct{} `type:"structure"` + // The name of the contact method. + Name *string `locationName:"name" type:"string"` - // An array of strings representing the instance name(s) you want to attach - // to your load balancer. + // The protocol of the contact method, such as email or SMS (text messaging). + Protocol *string `locationName:"protocol" type:"string" enum:"ContactProtocol"` + + // The Lightsail resource type (e.g., ContactMethod). + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + + // The current status of the contact method. // - // An instance must be running before you can attach it to your load balancer. + // A contact method has the following possible status: // - // There are no additional limits on the number of instances you can attach - // to your load balancer, aside from the limit of Lightsail instances you can - // create in your account (20). + // * PendingVerification - The contact method has not yet been verified, + // and the verification has not yet expired. // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` - - // The name of the load balancer. + // * Valid - The contact method has been verified. // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` + // * InValid - An attempt was made to verify the contact method, but the + // verification has expired. + Status *string `locationName:"status" type:"string" enum:"ContactMethodStatus"` + + // The support code. Include this code in your email to support when you have + // questions about your Lightsail contact method. This code enables our support + // team to look up your Lightsail information more easily. + SupportCode *string `locationName:"supportCode" type:"string"` } // String returns the string representation -func (s AttachInstancesToLoadBalancerInput) String() string { +func (s ContactMethod) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AttachInstancesToLoadBalancerInput) GoString() string { +func (s ContactMethod) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AttachInstancesToLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachInstancesToLoadBalancerInput"} - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } +// SetArn sets the Arn field's value. +func (s *ContactMethod) SetArn(v string) *ContactMethod { + s.Arn = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetContactEndpoint sets the ContactEndpoint field's value. +func (s *ContactMethod) SetContactEndpoint(v string) *ContactMethod { + s.ContactEndpoint = &v + return s } -// SetInstanceNames sets the InstanceNames field's value. -func (s *AttachInstancesToLoadBalancerInput) SetInstanceNames(v []*string) *AttachInstancesToLoadBalancerInput { - s.InstanceNames = v +// SetCreatedAt sets the CreatedAt field's value. +func (s *ContactMethod) SetCreatedAt(v time.Time) *ContactMethod { + s.CreatedAt = &v return s } -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *AttachInstancesToLoadBalancerInput) SetLoadBalancerName(v string) *AttachInstancesToLoadBalancerInput { - s.LoadBalancerName = &v +// SetLocation sets the Location field's value. +func (s *ContactMethod) SetLocation(v *ResourceLocation) *ContactMethod { + s.Location = v return s } -type AttachInstancesToLoadBalancerOutput struct { - _ struct{} `type:"structure"` +// SetName sets the Name field's value. +func (s *ContactMethod) SetName(v string) *ContactMethod { + s.Name = &v + return s +} - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` +// SetProtocol sets the Protocol field's value. +func (s *ContactMethod) SetProtocol(v string) *ContactMethod { + s.Protocol = &v + return s } -// String returns the string representation -func (s AttachInstancesToLoadBalancerOutput) String() string { - return awsutil.Prettify(s) +// SetResourceType sets the ResourceType field's value. +func (s *ContactMethod) SetResourceType(v string) *ContactMethod { + s.ResourceType = &v + return s } -// GoString returns the string representation -func (s AttachInstancesToLoadBalancerOutput) GoString() string { - return s.String() +// SetStatus sets the Status field's value. +func (s *ContactMethod) SetStatus(v string) *ContactMethod { + s.Status = &v + return s } -// SetOperations sets the Operations field's value. -func (s *AttachInstancesToLoadBalancerOutput) SetOperations(v []*Operation) *AttachInstancesToLoadBalancerOutput { - s.Operations = v +// SetSupportCode sets the SupportCode field's value. +func (s *ContactMethod) SetSupportCode(v string) *ContactMethod { + s.SupportCode = &v return s } -type AttachLoadBalancerTlsCertificateInput struct { +// Describes whether an Amazon Lightsail content delivery network (CDN) distribution +// forwards cookies to the origin and, if so, which ones. +// +// For the cookies that you specify, your distribution caches separate versions +// of the specified content based on the cookie values in viewer requests. +type CookieObject struct { _ struct{} `type:"structure"` - // The name of your SSL/TLS certificate. - // - // CertificateName is a required field - CertificateName *string `locationName:"certificateName" type:"string" required:"true"` + // The specific cookies to forward to your distribution's origin. + CookiesAllowList []*string `locationName:"cookiesAllowList" type:"list"` - // The name of the load balancer to which you want to associate the SSL/TLS - // certificate. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` + // Specifies which cookies to forward to the distribution's origin for a cache + // behavior: all, none, or allow-list to forward only the cookies specified + // in the cookiesAllowList parameter. + Option *string `locationName:"option" type:"string" enum:"ForwardValues"` } // String returns the string representation -func (s AttachLoadBalancerTlsCertificateInput) String() string { +func (s CookieObject) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AttachLoadBalancerTlsCertificateInput) GoString() string { +func (s CookieObject) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AttachLoadBalancerTlsCertificateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachLoadBalancerTlsCertificateInput"} - if s.CertificateName == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateName")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCertificateName sets the CertificateName field's value. -func (s *AttachLoadBalancerTlsCertificateInput) SetCertificateName(v string) *AttachLoadBalancerTlsCertificateInput { - s.CertificateName = &v +// SetCookiesAllowList sets the CookiesAllowList field's value. +func (s *CookieObject) SetCookiesAllowList(v []*string) *CookieObject { + s.CookiesAllowList = v return s } -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *AttachLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *AttachLoadBalancerTlsCertificateInput { - s.LoadBalancerName = &v +// SetOption sets the Option field's value. +func (s *CookieObject) SetOption(v string) *CookieObject { + s.Option = &v return s } -type AttachLoadBalancerTlsCertificateOutput struct { +type CopySnapshotInput struct { _ struct{} `type:"structure"` - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. + // The date of the source automatic snapshot to copy. Use the get auto snapshots + // operation to identify the dates of the available automatic snapshots. // - // These SSL/TLS certificates are only usable by Lightsail load balancers. You - // can't get the certificate and use it for another purpose. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s AttachLoadBalancerTlsCertificateOutput) String() string { - return awsutil.Prettify(s) -} + // Constraints: + // + // * Must be specified in YYYY-MM-DD format. + // + // * This parameter cannot be defined together with the use latest restorable + // auto snapshot parameter. The restore date and use latest restorable auto + // snapshot parameters are mutually exclusive. + // + // * Define this parameter only when copying an automatic snapshot as a manual + // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-keeping-automatic-snapshots). + RestoreDate *string `locationName:"restoreDate" type:"string"` -// GoString returns the string representation -func (s AttachLoadBalancerTlsCertificateOutput) GoString() string { - return s.String() -} + // The AWS Region where the source manual or automatic snapshot is located. + // + // SourceRegion is a required field + SourceRegion *string `locationName:"sourceRegion" type:"string" required:"true" enum:"RegionName"` -// SetOperations sets the Operations field's value. -func (s *AttachLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *AttachLoadBalancerTlsCertificateOutput { - s.Operations = v - return s -} + // The name of the source instance or disk from which the source automatic snapshot + // was created. + // + // Constraint: + // + // * Define this parameter only when copying an automatic snapshot as a manual + // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-keeping-automatic-snapshots). + SourceResourceName *string `locationName:"sourceResourceName" type:"string"` -type AttachStaticIpInput struct { - _ struct{} `type:"structure"` + // The name of the source manual snapshot to copy. + // + // Constraint: + // + // * Define this parameter only when copying a manual snapshot as another + // manual snapshot. + SourceSnapshotName *string `locationName:"sourceSnapshotName" type:"string"` - // The instance name to which you want to attach the static IP address. + // The name of the new manual snapshot to be created as a copy. // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` + // TargetSnapshotName is a required field + TargetSnapshotName *string `locationName:"targetSnapshotName" type:"string" required:"true"` - // The name of the static IP. + // A Boolean value to indicate whether to use the latest available automatic + // snapshot of the specified source instance or disk. // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` + // Constraints: + // + // * This parameter cannot be defined together with the restore date parameter. + // The use latest restorable auto snapshot and restore date parameters are + // mutually exclusive. + // + // * Define this parameter only when copying an automatic snapshot as a manual + // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-keeping-automatic-snapshots). + UseLatestRestorableAutoSnapshot *bool `locationName:"useLatestRestorableAutoSnapshot" type:"boolean"` } // String returns the string representation -func (s AttachStaticIpInput) String() string { +func (s CopySnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AttachStaticIpInput) GoString() string { +func (s CopySnapshotInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *AttachStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachStaticIpInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) +func (s *CopySnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CopySnapshotInput"} + if s.SourceRegion == nil { + invalidParams.Add(request.NewErrParamRequired("SourceRegion")) } - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) + if s.TargetSnapshotName == nil { + invalidParams.Add(request.NewErrParamRequired("TargetSnapshotName")) } if invalidParams.Len() > 0 { @@ -13009,882 +16064,860 @@ func (s *AttachStaticIpInput) Validate() error { return nil } -// SetInstanceName sets the InstanceName field's value. -func (s *AttachStaticIpInput) SetInstanceName(v string) *AttachStaticIpInput { - s.InstanceName = &v +// SetRestoreDate sets the RestoreDate field's value. +func (s *CopySnapshotInput) SetRestoreDate(v string) *CopySnapshotInput { + s.RestoreDate = &v return s } -// SetStaticIpName sets the StaticIpName field's value. -func (s *AttachStaticIpInput) SetStaticIpName(v string) *AttachStaticIpInput { - s.StaticIpName = &v +// SetSourceRegion sets the SourceRegion field's value. +func (s *CopySnapshotInput) SetSourceRegion(v string) *CopySnapshotInput { + s.SourceRegion = &v return s } -type AttachStaticIpOutput struct { - _ struct{} `type:"structure"` - - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` +// SetSourceResourceName sets the SourceResourceName field's value. +func (s *CopySnapshotInput) SetSourceResourceName(v string) *CopySnapshotInput { + s.SourceResourceName = &v + return s } -// String returns the string representation -func (s AttachStaticIpOutput) String() string { - return awsutil.Prettify(s) +// SetSourceSnapshotName sets the SourceSnapshotName field's value. +func (s *CopySnapshotInput) SetSourceSnapshotName(v string) *CopySnapshotInput { + s.SourceSnapshotName = &v + return s } -// GoString returns the string representation -func (s AttachStaticIpOutput) GoString() string { - return s.String() +// SetTargetSnapshotName sets the TargetSnapshotName field's value. +func (s *CopySnapshotInput) SetTargetSnapshotName(v string) *CopySnapshotInput { + s.TargetSnapshotName = &v + return s } -// SetOperations sets the Operations field's value. -func (s *AttachStaticIpOutput) SetOperations(v []*Operation) *AttachStaticIpOutput { - s.Operations = v +// SetUseLatestRestorableAutoSnapshot sets the UseLatestRestorableAutoSnapshot field's value. +func (s *CopySnapshotInput) SetUseLatestRestorableAutoSnapshot(v bool) *CopySnapshotInput { + s.UseLatestRestorableAutoSnapshot = &v return s } -// Describes a block storage disk that is attached to an instance, and is included -// in an automatic snapshot. -type AttachedDisk struct { +type CopySnapshotOutput struct { _ struct{} `type:"structure"` - // The path of the disk (e.g., /dev/xvdf). - Path *string `locationName:"path" type:"string"` - - // The size of the disk in GB. - SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s AttachedDisk) String() string { +func (s CopySnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AttachedDisk) GoString() string { +func (s CopySnapshotOutput) GoString() string { return s.String() } -// SetPath sets the Path field's value. -func (s *AttachedDisk) SetPath(v string) *AttachedDisk { - s.Path = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *AttachedDisk) SetSizeInGb(v int64) *AttachedDisk { - s.SizeInGb = &v +// SetOperations sets the Operations field's value. +func (s *CopySnapshotOutput) SetOperations(v []*Operation) *CopySnapshotOutput { + s.Operations = v return s } -// Describes a request to enable or modify the automatic snapshot add-on for -// an Amazon Lightsail instance or disk. -// -// When you modify the automatic snapshot time for a resource, it is typically -// effective immediately except under the following conditions: -// -// * If an automatic snapshot has been created for the current day, and you -// change the snapshot time to a later time of day, then the new snapshot -// time will be effective the following day. This ensures that two snapshots -// are not created for the current day. -// -// * If an automatic snapshot has not yet been created for the current day, -// and you change the snapshot time to an earlier time of day, then the new -// snapshot time will be effective the following day and a snapshot is automatically -// created at the previously set time for the current day. This ensures that -// a snapshot is created for the current day. -// -// * If an automatic snapshot has not yet been created for the current day, -// and you change the snapshot time to a time that is within 30 minutes from -// your current time, then the new snapshot time will be effective the following -// day and a snapshot is automatically created at the previously set time -// for the current day. This ensures that a snapshot is created for the current -// day, because 30 minutes is required between your current time and the -// new snapshot time that you specify. -// -// * If an automatic snapshot is scheduled to be created within 30 minutes -// from your current time and you change the snapshot time, then the new -// snapshot time will be effective the following day and a snapshot is automatically -// created at the previously set time for the current day. This ensures that -// a snapshot is created for the current day, because 30 minutes is required -// between your current time and the new snapshot time that you specify. -type AutoSnapshotAddOnRequest struct { +type CreateCertificateInput struct { _ struct{} `type:"structure"` - // The daily time when an automatic snapshot will be created. + // The name for the certificate. // - // Constraints: + // CertificateName is a required field + CertificateName *string `locationName:"certificateName" type:"string" required:"true"` + + // The domain name (e.g., example.com) for the certificate. // - // * Must be in HH:00 format, and in an hourly increment. + // DomainName is a required field + DomainName *string `locationName:"domainName" type:"string" required:"true"` + + // An array of strings that specify the alternate domains (e.g., example2.com) + // and subdomains (e.g., blog.example.com) for the certificate. // - // * Specified in Coordinated Universal Time (UTC). + // You can specify a maximum of nine alternate domains (in addition to the primary + // domain name). // - // * The snapshot will be automatically created between the time specified - // and up to 45 minutes after. - SnapshotTimeOfDay *string `locationName:"snapshotTimeOfDay" type:"string"` + // Wildcard domain entries (e.g., *.example.com) are not supported. + SubjectAlternativeNames []*string `locationName:"subjectAlternativeNames" type:"list"` + + // The tag keys and optional values to add to the certificate during create. + // + // Use the TagResource action to tag a resource after it's created. + Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s AutoSnapshotAddOnRequest) String() string { +func (s CreateCertificateInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AutoSnapshotAddOnRequest) GoString() string { +func (s CreateCertificateInput) GoString() string { return s.String() } -// SetSnapshotTimeOfDay sets the SnapshotTimeOfDay field's value. -func (s *AutoSnapshotAddOnRequest) SetSnapshotTimeOfDay(v string) *AutoSnapshotAddOnRequest { - s.SnapshotTimeOfDay = &v - return s -} - -// Describes an automatic snapshot. -type AutoSnapshotDetails struct { - _ struct{} `type:"structure"` - - // The timestamp when the automatic snapshot was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // The date of the automatic snapshot in YYYY-MM-DD format. - Date *string `locationName:"date" type:"string"` - - // An array of objects that describe the block storage disks attached to the - // instance when the automatic snapshot was created. - FromAttachedDisks []*AttachedDisk `locationName:"fromAttachedDisks" type:"list"` - - // The status of the automatic snapshot. - Status *string `locationName:"status" type:"string" enum:"AutoSnapshotStatus"` -} - -// String returns the string representation -func (s AutoSnapshotDetails) String() string { - return awsutil.Prettify(s) -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateCertificateInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateCertificateInput"} + if s.CertificateName == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateName")) + } + if s.DomainName == nil { + invalidParams.Add(request.NewErrParamRequired("DomainName")) + } -// GoString returns the string representation -func (s AutoSnapshotDetails) GoString() string { - return s.String() + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetCreatedAt sets the CreatedAt field's value. -func (s *AutoSnapshotDetails) SetCreatedAt(v time.Time) *AutoSnapshotDetails { - s.CreatedAt = &v +// SetCertificateName sets the CertificateName field's value. +func (s *CreateCertificateInput) SetCertificateName(v string) *CreateCertificateInput { + s.CertificateName = &v return s } -// SetDate sets the Date field's value. -func (s *AutoSnapshotDetails) SetDate(v string) *AutoSnapshotDetails { - s.Date = &v +// SetDomainName sets the DomainName field's value. +func (s *CreateCertificateInput) SetDomainName(v string) *CreateCertificateInput { + s.DomainName = &v return s } -// SetFromAttachedDisks sets the FromAttachedDisks field's value. -func (s *AutoSnapshotDetails) SetFromAttachedDisks(v []*AttachedDisk) *AutoSnapshotDetails { - s.FromAttachedDisks = v +// SetSubjectAlternativeNames sets the SubjectAlternativeNames field's value. +func (s *CreateCertificateInput) SetSubjectAlternativeNames(v []*string) *CreateCertificateInput { + s.SubjectAlternativeNames = v return s } -// SetStatus sets the Status field's value. -func (s *AutoSnapshotDetails) SetStatus(v string) *AutoSnapshotDetails { - s.Status = &v +// SetTags sets the Tags field's value. +func (s *CreateCertificateInput) SetTags(v []*Tag) *CreateCertificateInput { + s.Tags = v return s } -// Describes an Availability Zone. -type AvailabilityZone struct { +type CreateCertificateOutput struct { _ struct{} `type:"structure"` - // The state of the Availability Zone. - State *string `locationName:"state" type:"string"` + // An object that describes the certificate created. + Certificate *CertificateSummary `locationName:"certificate" type:"structure"` - // The name of the Availability Zone. The format is us-east-2a (case-sensitive). - ZoneName *string `locationName:"zoneName" type:"string"` + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s AvailabilityZone) String() string { +func (s CreateCertificateOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AvailabilityZone) GoString() string { +func (s CreateCertificateOutput) GoString() string { return s.String() } -// SetState sets the State field's value. -func (s *AvailabilityZone) SetState(v string) *AvailabilityZone { - s.State = &v +// SetCertificate sets the Certificate field's value. +func (s *CreateCertificateOutput) SetCertificate(v *CertificateSummary) *CreateCertificateOutput { + s.Certificate = v return s } -// SetZoneName sets the ZoneName field's value. -func (s *AvailabilityZone) SetZoneName(v string) *AvailabilityZone { - s.ZoneName = &v +// SetOperations sets the Operations field's value. +func (s *CreateCertificateOutput) SetOperations(v []*Operation) *CreateCertificateOutput { + s.Operations = v return s } -// Describes a blueprint (a virtual private server image). -type Blueprint struct { +type CreateCloudFormationStackInput struct { _ struct{} `type:"structure"` - // The ID for the virtual private server image (e.g., app_wordpress_4_4 or app_lamp_7_0). - BlueprintId *string `locationName:"blueprintId" type:"string"` - - // The description of the blueprint. - Description *string `locationName:"description" type:"string"` - - // The group name of the blueprint (e.g., amazon-linux). - Group *string `locationName:"group" type:"string"` - - // A Boolean value indicating whether the blueprint is active. Inactive blueprints - // are listed to support customers with existing instances but are not necessarily - // available for launch of new instances. Blueprints are marked inactive when - // they become outdated due to operating system updates or new application releases. - IsActive *bool `locationName:"isActive" type:"boolean"` - - // The end-user license agreement URL for the image or blueprint. - LicenseUrl *string `locationName:"licenseUrl" type:"string"` - - // The minimum bundle power required to run this blueprint. For example, you - // need a bundle with a power value of 500 or more to create an instance that - // uses a blueprint with a minimum power value of 500. 0 indicates that the - // blueprint runs on all instance sizes. - MinPower *int64 `locationName:"minPower" type:"integer"` + // An array of parameters that will be used to create the new Amazon EC2 instance. + // You can only pass one instance entry at a time in this array. You will get + // an invalid parameter error if you pass more than one instance entry in this + // array. + // + // Instances is a required field + Instances []*InstanceEntry `locationName:"instances" type:"list" required:"true"` +} - // The friendly name of the blueprint (e.g., Amazon Linux). - Name *string `locationName:"name" type:"string"` +// String returns the string representation +func (s CreateCloudFormationStackInput) String() string { + return awsutil.Prettify(s) +} - // The operating system platform (either Linux/Unix-based or Windows Server-based) - // of the blueprint. - Platform *string `locationName:"platform" type:"string" enum:"InstancePlatform"` +// GoString returns the string representation +func (s CreateCloudFormationStackInput) GoString() string { + return s.String() +} - // The product URL to learn more about the image or blueprint. - ProductUrl *string `locationName:"productUrl" type:"string"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateCloudFormationStackInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateCloudFormationStackInput"} + if s.Instances == nil { + invalidParams.Add(request.NewErrParamRequired("Instances")) + } + if s.Instances != nil { + for i, v := range s.Instances { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Instances", i), err.(request.ErrInvalidParams)) + } + } + } - // The type of the blueprint (e.g., os or app). - Type *string `locationName:"type" type:"string" enum:"BlueprintType"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - // The version number of the operating system, application, or stack (e.g., - // 2016.03.0). - Version *string `locationName:"version" type:"string"` +// SetInstances sets the Instances field's value. +func (s *CreateCloudFormationStackInput) SetInstances(v []*InstanceEntry) *CreateCloudFormationStackInput { + s.Instances = v + return s +} - // The version code. - VersionCode *string `locationName:"versionCode" type:"string"` +type CreateCloudFormationStackOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s Blueprint) String() string { +func (s CreateCloudFormationStackOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Blueprint) GoString() string { +func (s CreateCloudFormationStackOutput) GoString() string { return s.String() } -// SetBlueprintId sets the BlueprintId field's value. -func (s *Blueprint) SetBlueprintId(v string) *Blueprint { - s.BlueprintId = &v +// SetOperations sets the Operations field's value. +func (s *CreateCloudFormationStackOutput) SetOperations(v []*Operation) *CreateCloudFormationStackOutput { + s.Operations = v return s } -// SetDescription sets the Description field's value. -func (s *Blueprint) SetDescription(v string) *Blueprint { - s.Description = &v - return s -} +type CreateContactMethodInput struct { + _ struct{} `type:"structure"` -// SetGroup sets the Group field's value. -func (s *Blueprint) SetGroup(v string) *Blueprint { - s.Group = &v - return s + // The destination of the contact method, such as an email address or a mobile + // phone number. + // + // Use the E.164 format when specifying a mobile phone number. E.164 is a standard + // for the phone number structure used for international telecommunication. + // Phone numbers that follow this format can have a maximum of 15 digits, and + // they are prefixed with the plus character (+) and the country code. For example, + // a U.S. phone number in E.164 format would be specified as +1XXX5550100. For + // more information, see E.164 (https://en.wikipedia.org/wiki/E.164) on Wikipedia. + // + // ContactEndpoint is a required field + ContactEndpoint *string `locationName:"contactEndpoint" min:"1" type:"string" required:"true"` + + // The protocol of the contact method, such as Email or SMS (text messaging). + // + // The SMS protocol is supported only in the following AWS Regions. + // + // * US East (N. Virginia) (us-east-1) + // + // * US West (Oregon) (us-west-2) + // + // * Europe (Ireland) (eu-west-1) + // + // * Asia Pacific (Tokyo) (ap-northeast-1) + // + // * Asia Pacific (Singapore) (ap-southeast-1) + // + // * Asia Pacific (Sydney) (ap-southeast-2) + // + // For a list of countries/regions where SMS text messages can be sent, and + // the latest AWS Regions where SMS text messaging is supported, see Supported + // Regions and Countries (https://docs.aws.amazon.com/sns/latest/dg/sns-supported-regions-countries.html) + // in the Amazon SNS Developer Guide. + // + // For more information about notifications in Amazon Lightsail, see Notifications + // in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-notifications). + // + // Protocol is a required field + Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"ContactProtocol"` } -// SetIsActive sets the IsActive field's value. -func (s *Blueprint) SetIsActive(v bool) *Blueprint { - s.IsActive = &v - return s +// String returns the string representation +func (s CreateContactMethodInput) String() string { + return awsutil.Prettify(s) } -// SetLicenseUrl sets the LicenseUrl field's value. -func (s *Blueprint) SetLicenseUrl(v string) *Blueprint { - s.LicenseUrl = &v - return s +// GoString returns the string representation +func (s CreateContactMethodInput) GoString() string { + return s.String() } -// SetMinPower sets the MinPower field's value. -func (s *Blueprint) SetMinPower(v int64) *Blueprint { - s.MinPower = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateContactMethodInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateContactMethodInput"} + if s.ContactEndpoint == nil { + invalidParams.Add(request.NewErrParamRequired("ContactEndpoint")) + } + if s.ContactEndpoint != nil && len(*s.ContactEndpoint) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ContactEndpoint", 1)) + } + if s.Protocol == nil { + invalidParams.Add(request.NewErrParamRequired("Protocol")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetName sets the Name field's value. -func (s *Blueprint) SetName(v string) *Blueprint { - s.Name = &v +// SetContactEndpoint sets the ContactEndpoint field's value. +func (s *CreateContactMethodInput) SetContactEndpoint(v string) *CreateContactMethodInput { + s.ContactEndpoint = &v return s } -// SetPlatform sets the Platform field's value. -func (s *Blueprint) SetPlatform(v string) *Blueprint { - s.Platform = &v +// SetProtocol sets the Protocol field's value. +func (s *CreateContactMethodInput) SetProtocol(v string) *CreateContactMethodInput { + s.Protocol = &v return s } -// SetProductUrl sets the ProductUrl field's value. -func (s *Blueprint) SetProductUrl(v string) *Blueprint { - s.ProductUrl = &v - return s +type CreateContactMethodOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` } -// SetType sets the Type field's value. -func (s *Blueprint) SetType(v string) *Blueprint { - s.Type = &v - return s +// String returns the string representation +func (s CreateContactMethodOutput) String() string { + return awsutil.Prettify(s) } -// SetVersion sets the Version field's value. -func (s *Blueprint) SetVersion(v string) *Blueprint { - s.Version = &v - return s +// GoString returns the string representation +func (s CreateContactMethodOutput) GoString() string { + return s.String() } -// SetVersionCode sets the VersionCode field's value. -func (s *Blueprint) SetVersionCode(v string) *Blueprint { - s.VersionCode = &v +// SetOperations sets the Operations field's value. +func (s *CreateContactMethodOutput) SetOperations(v []*Operation) *CreateContactMethodOutput { + s.Operations = v return s } -// Describes a bundle, which is a set of specs describing your virtual private -// server (or instance). -type Bundle struct { +type CreateDiskFromSnapshotInput struct { _ struct{} `type:"structure"` - // The bundle ID (e.g., micro_1_0). - BundleId *string `locationName:"bundleId" type:"string"` - - // The number of vCPUs included in the bundle (e.g., 2). - CpuCount *int64 `locationName:"cpuCount" type:"integer"` - - // The size of the SSD (e.g., 30). - DiskSizeInGb *int64 `locationName:"diskSizeInGb" type:"integer"` + // An array of objects that represent the add-ons to enable for the new disk. + AddOns []*AddOnRequest `locationName:"addOns" type:"list"` - // The Amazon EC2 instance type (e.g., t2.micro). - InstanceType *string `locationName:"instanceType" type:"string"` + // The Availability Zone where you want to create the disk (e.g., us-east-2a). + // Choose the same Availability Zone as the Lightsail instance where you want + // to create the disk. + // + // Use the GetRegions operation to list the Availability Zones where Lightsail + // is currently available. + // + // AvailabilityZone is a required field + AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - // A Boolean value indicating whether the bundle is active. - IsActive *bool `locationName:"isActive" type:"boolean"` + // The unique Lightsail disk name (e.g., my-disk). + // + // DiskName is a required field + DiskName *string `locationName:"diskName" type:"string" required:"true"` - // A friendly name for the bundle (e.g., Micro). - Name *string `locationName:"name" type:"string"` + // The name of the disk snapshot (e.g., my-snapshot) from which to create the + // new storage disk. + // + // Constraint: + // + // * This parameter cannot be defined together with the source disk name + // parameter. The disk snapshot name and source disk name parameters are + // mutually exclusive. + DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string"` - // A numeric value that represents the power of the bundle (e.g., 500). You - // can use the bundle's power value in conjunction with a blueprint's minimum - // power value to determine whether the blueprint will run on the bundle. For - // example, you need a bundle with a power value of 500 or more to create an - // instance that uses a blueprint with a minimum power value of 500. - Power *int64 `locationName:"power" type:"integer"` + // The date of the automatic snapshot to use for the new disk. Use the get auto + // snapshots operation to identify the dates of the available automatic snapshots. + // + // Constraints: + // + // * Must be specified in YYYY-MM-DD format. + // + // * This parameter cannot be defined together with the use latest restorable + // auto snapshot parameter. The restore date and use latest restorable auto + // snapshot parameters are mutually exclusive. + // + // * Define this parameter only when creating a new disk from an automatic + // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-configuring-automatic-snapshots). + RestoreDate *string `locationName:"restoreDate" type:"string"` - // The price in US dollars (e.g., 5.0). - Price *float64 `locationName:"price" type:"float"` + // The size of the disk in GB (e.g., 32). + // + // SizeInGb is a required field + SizeInGb *int64 `locationName:"sizeInGb" type:"integer" required:"true"` - // The amount of RAM in GB (e.g., 2.0). - RamSizeInGb *float64 `locationName:"ramSizeInGb" type:"float"` + // The name of the source disk from which the source automatic snapshot was + // created. + // + // Constraints: + // + // * This parameter cannot be defined together with the disk snapshot name + // parameter. The source disk name and disk snapshot name parameters are + // mutually exclusive. + // + // * Define this parameter only when creating a new disk from an automatic + // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-configuring-automatic-snapshots). + SourceDiskName *string `locationName:"sourceDiskName" type:"string"` - // The operating system platform (Linux/Unix-based or Windows Server-based) - // that the bundle supports. You can only launch a WINDOWS bundle on a blueprint - // that supports the WINDOWS platform. LINUX_UNIX blueprints require a LINUX_UNIX - // bundle. - SupportedPlatforms []*string `locationName:"supportedPlatforms" type:"list"` + // The tag keys and optional values to add to the resource during create. + // + // Use the TagResource action to tag a resource after it's created. + Tags []*Tag `locationName:"tags" type:"list"` - // The data transfer rate per month in GB (e.g., 2000). - TransferPerMonthInGb *int64 `locationName:"transferPerMonthInGb" type:"integer"` + // A Boolean value to indicate whether to use the latest available automatic + // snapshot. + // + // Constraints: + // + // * This parameter cannot be defined together with the restore date parameter. + // The use latest restorable auto snapshot and restore date parameters are + // mutually exclusive. + // + // * Define this parameter only when creating a new disk from an automatic + // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-configuring-automatic-snapshots). + UseLatestRestorableAutoSnapshot *bool `locationName:"useLatestRestorableAutoSnapshot" type:"boolean"` } // String returns the string representation -func (s Bundle) String() string { +func (s CreateDiskFromSnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Bundle) GoString() string { +func (s CreateDiskFromSnapshotInput) GoString() string { return s.String() } -// SetBundleId sets the BundleId field's value. -func (s *Bundle) SetBundleId(v string) *Bundle { - s.BundleId = &v - return s -} - -// SetCpuCount sets the CpuCount field's value. -func (s *Bundle) SetCpuCount(v int64) *Bundle { - s.CpuCount = &v - return s -} - -// SetDiskSizeInGb sets the DiskSizeInGb field's value. -func (s *Bundle) SetDiskSizeInGb(v int64) *Bundle { - s.DiskSizeInGb = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateDiskFromSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDiskFromSnapshotInput"} + if s.AvailabilityZone == nil { + invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) + } + if s.DiskName == nil { + invalidParams.Add(request.NewErrParamRequired("DiskName")) + } + if s.SizeInGb == nil { + invalidParams.Add(request.NewErrParamRequired("SizeInGb")) + } + if s.AddOns != nil { + for i, v := range s.AddOns { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "AddOns", i), err.(request.ErrInvalidParams)) + } + } + } -// SetInstanceType sets the InstanceType field's value. -func (s *Bundle) SetInstanceType(v string) *Bundle { - s.InstanceType = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetIsActive sets the IsActive field's value. -func (s *Bundle) SetIsActive(v bool) *Bundle { - s.IsActive = &v +// SetAddOns sets the AddOns field's value. +func (s *CreateDiskFromSnapshotInput) SetAddOns(v []*AddOnRequest) *CreateDiskFromSnapshotInput { + s.AddOns = v return s } -// SetName sets the Name field's value. -func (s *Bundle) SetName(v string) *Bundle { - s.Name = &v +// SetAvailabilityZone sets the AvailabilityZone field's value. +func (s *CreateDiskFromSnapshotInput) SetAvailabilityZone(v string) *CreateDiskFromSnapshotInput { + s.AvailabilityZone = &v return s } -// SetPower sets the Power field's value. -func (s *Bundle) SetPower(v int64) *Bundle { - s.Power = &v +// SetDiskName sets the DiskName field's value. +func (s *CreateDiskFromSnapshotInput) SetDiskName(v string) *CreateDiskFromSnapshotInput { + s.DiskName = &v return s } -// SetPrice sets the Price field's value. -func (s *Bundle) SetPrice(v float64) *Bundle { - s.Price = &v +// SetDiskSnapshotName sets the DiskSnapshotName field's value. +func (s *CreateDiskFromSnapshotInput) SetDiskSnapshotName(v string) *CreateDiskFromSnapshotInput { + s.DiskSnapshotName = &v return s } -// SetRamSizeInGb sets the RamSizeInGb field's value. -func (s *Bundle) SetRamSizeInGb(v float64) *Bundle { - s.RamSizeInGb = &v +// SetRestoreDate sets the RestoreDate field's value. +func (s *CreateDiskFromSnapshotInput) SetRestoreDate(v string) *CreateDiskFromSnapshotInput { + s.RestoreDate = &v return s } -// SetSupportedPlatforms sets the SupportedPlatforms field's value. -func (s *Bundle) SetSupportedPlatforms(v []*string) *Bundle { - s.SupportedPlatforms = v +// SetSizeInGb sets the SizeInGb field's value. +func (s *CreateDiskFromSnapshotInput) SetSizeInGb(v int64) *CreateDiskFromSnapshotInput { + s.SizeInGb = &v return s } -// SetTransferPerMonthInGb sets the TransferPerMonthInGb field's value. -func (s *Bundle) SetTransferPerMonthInGb(v int64) *Bundle { - s.TransferPerMonthInGb = &v +// SetSourceDiskName sets the SourceDiskName field's value. +func (s *CreateDiskFromSnapshotInput) SetSourceDiskName(v string) *CreateDiskFromSnapshotInput { + s.SourceDiskName = &v return s } -type CloseInstancePublicPortsInput struct { - _ struct{} `type:"structure"` - - // The name of the instance on which you're attempting to close the public ports. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // Information about the public port you are trying to close. - // - // PortInfo is a required field - PortInfo *PortInfo `locationName:"portInfo" type:"structure" required:"true"` -} - -// String returns the string representation -func (s CloseInstancePublicPortsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CloseInstancePublicPortsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CloseInstancePublicPortsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CloseInstancePublicPortsInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.PortInfo == nil { - invalidParams.Add(request.NewErrParamRequired("PortInfo")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *CloseInstancePublicPortsInput) SetInstanceName(v string) *CloseInstancePublicPortsInput { - s.InstanceName = &v +// SetTags sets the Tags field's value. +func (s *CreateDiskFromSnapshotInput) SetTags(v []*Tag) *CreateDiskFromSnapshotInput { + s.Tags = v return s } -// SetPortInfo sets the PortInfo field's value. -func (s *CloseInstancePublicPortsInput) SetPortInfo(v *PortInfo) *CloseInstancePublicPortsInput { - s.PortInfo = v +// SetUseLatestRestorableAutoSnapshot sets the UseLatestRestorableAutoSnapshot field's value. +func (s *CreateDiskFromSnapshotInput) SetUseLatestRestorableAutoSnapshot(v bool) *CreateDiskFromSnapshotInput { + s.UseLatestRestorableAutoSnapshot = &v return s } -type CloseInstancePublicPortsOutput struct { +type CreateDiskFromSnapshotOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operation *Operation `locationName:"operation" type:"structure"` + Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CloseInstancePublicPortsOutput) String() string { +func (s CreateDiskFromSnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CloseInstancePublicPortsOutput) GoString() string { +func (s CreateDiskFromSnapshotOutput) GoString() string { return s.String() } -// SetOperation sets the Operation field's value. -func (s *CloseInstancePublicPortsOutput) SetOperation(v *Operation) *CloseInstancePublicPortsOutput { - s.Operation = v +// SetOperations sets the Operations field's value. +func (s *CreateDiskFromSnapshotOutput) SetOperations(v []*Operation) *CreateDiskFromSnapshotOutput { + s.Operations = v return s } -// Describes a CloudFormation stack record created as a result of the create -// cloud formation stack operation. -// -// A CloudFormation stack record provides information about the AWS CloudFormation -// stack used to create a new Amazon Elastic Compute Cloud instance from an -// exported Lightsail instance snapshot. -type CloudFormationStackRecord struct { +type CreateDiskInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the CloudFormation stack record. - Arn *string `locationName:"arn" type:"string"` - - // The date when the CloudFormation stack record was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // A list of objects describing the destination service, which is AWS CloudFormation, - // and the Amazon Resource Name (ARN) of the AWS CloudFormation stack. - DestinationInfo *DestinationInfo `locationName:"destinationInfo" type:"structure"` - - // A list of objects describing the Availability Zone and AWS Region of the - // CloudFormation stack record. - Location *ResourceLocation `locationName:"location" type:"structure"` + // An array of objects that represent the add-ons to enable for the new disk. + AddOns []*AddOnRequest `locationName:"addOns" type:"list"` - // The name of the CloudFormation stack record. It starts with CloudFormationStackRecord - // followed by a GUID. - Name *string `locationName:"name" type:"string"` + // The Availability Zone where you want to create the disk (e.g., us-east-2a). + // Use the same Availability Zone as the Lightsail instance to which you want + // to attach the disk. + // + // Use the get regions operation to list the Availability Zones where Lightsail + // is currently available. + // + // AvailabilityZone is a required field + AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - // The Lightsail resource type (e.g., CloudFormationStackRecord). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + // The unique Lightsail disk name (e.g., my-disk). + // + // DiskName is a required field + DiskName *string `locationName:"diskName" type:"string" required:"true"` - // A list of objects describing the source of the CloudFormation stack record. - SourceInfo []*CloudFormationStackRecordSourceInfo `locationName:"sourceInfo" type:"list"` + // The size of the disk in GB (e.g., 32). + // + // SizeInGb is a required field + SizeInGb *int64 `locationName:"sizeInGb" type:"integer" required:"true"` - // The current state of the CloudFormation stack record. - State *string `locationName:"state" type:"string" enum:"RecordState"` + // The tag keys and optional values to add to the resource during create. + // + // Use the TagResource action to tag a resource after it's created. + Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s CloudFormationStackRecord) String() string { +func (s CreateDiskInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CloudFormationStackRecord) GoString() string { +func (s CreateDiskInput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *CloudFormationStackRecord) SetArn(v string) *CloudFormationStackRecord { - s.Arn = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *CloudFormationStackRecord) SetCreatedAt(v time.Time) *CloudFormationStackRecord { - s.CreatedAt = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateDiskInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDiskInput"} + if s.AvailabilityZone == nil { + invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) + } + if s.DiskName == nil { + invalidParams.Add(request.NewErrParamRequired("DiskName")) + } + if s.SizeInGb == nil { + invalidParams.Add(request.NewErrParamRequired("SizeInGb")) + } + if s.AddOns != nil { + for i, v := range s.AddOns { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "AddOns", i), err.(request.ErrInvalidParams)) + } + } + } -// SetDestinationInfo sets the DestinationInfo field's value. -func (s *CloudFormationStackRecord) SetDestinationInfo(v *DestinationInfo) *CloudFormationStackRecord { - s.DestinationInfo = v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetLocation sets the Location field's value. -func (s *CloudFormationStackRecord) SetLocation(v *ResourceLocation) *CloudFormationStackRecord { - s.Location = v +// SetAddOns sets the AddOns field's value. +func (s *CreateDiskInput) SetAddOns(v []*AddOnRequest) *CreateDiskInput { + s.AddOns = v return s } -// SetName sets the Name field's value. -func (s *CloudFormationStackRecord) SetName(v string) *CloudFormationStackRecord { - s.Name = &v +// SetAvailabilityZone sets the AvailabilityZone field's value. +func (s *CreateDiskInput) SetAvailabilityZone(v string) *CreateDiskInput { + s.AvailabilityZone = &v return s } -// SetResourceType sets the ResourceType field's value. -func (s *CloudFormationStackRecord) SetResourceType(v string) *CloudFormationStackRecord { - s.ResourceType = &v +// SetDiskName sets the DiskName field's value. +func (s *CreateDiskInput) SetDiskName(v string) *CreateDiskInput { + s.DiskName = &v return s } -// SetSourceInfo sets the SourceInfo field's value. -func (s *CloudFormationStackRecord) SetSourceInfo(v []*CloudFormationStackRecordSourceInfo) *CloudFormationStackRecord { - s.SourceInfo = v +// SetSizeInGb sets the SizeInGb field's value. +func (s *CreateDiskInput) SetSizeInGb(v int64) *CreateDiskInput { + s.SizeInGb = &v return s } -// SetState sets the State field's value. -func (s *CloudFormationStackRecord) SetState(v string) *CloudFormationStackRecord { - s.State = &v +// SetTags sets the Tags field's value. +func (s *CreateDiskInput) SetTags(v []*Tag) *CreateDiskInput { + s.Tags = v return s } -// Describes the source of a CloudFormation stack record (i.e., the export snapshot -// record). -type CloudFormationStackRecordSourceInfo struct { +type CreateDiskOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the export snapshot record. - Arn *string `locationName:"arn" type:"string"` - - // The name of the record. - Name *string `locationName:"name" type:"string"` - - // The Lightsail resource type (e.g., ExportSnapshotRecord). - ResourceType *string `locationName:"resourceType" type:"string" enum:"CloudFormationStackRecordSourceType"` + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CloudFormationStackRecordSourceInfo) String() string { +func (s CreateDiskOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CloudFormationStackRecordSourceInfo) GoString() string { +func (s CreateDiskOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *CloudFormationStackRecordSourceInfo) SetArn(v string) *CloudFormationStackRecordSourceInfo { - s.Arn = &v - return s -} - -// SetName sets the Name field's value. -func (s *CloudFormationStackRecordSourceInfo) SetName(v string) *CloudFormationStackRecordSourceInfo { - s.Name = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *CloudFormationStackRecordSourceInfo) SetResourceType(v string) *CloudFormationStackRecordSourceInfo { - s.ResourceType = &v +// SetOperations sets the Operations field's value. +func (s *CreateDiskOutput) SetOperations(v []*Operation) *CreateDiskOutput { + s.Operations = v return s } -// Describes a contact method. -// -// A contact method is a way to send you notifications. For more information, -// see Notifications in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-notifications). -type ContactMethod struct { +type CreateDiskSnapshotInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the contact method. - Arn *string `locationName:"arn" type:"string"` - - // The destination of the contact method, such as an email address or a mobile - // phone number. - ContactEndpoint *string `locationName:"contactEndpoint" type:"string"` - - // The timestamp when the contact method was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // Describes the resource location. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the contact method. - Name *string `locationName:"name" type:"string"` - - // The protocol of the contact method, such as email or SMS (text messaging). - Protocol *string `locationName:"protocol" type:"string" enum:"ContactProtocol"` - - // The Lightsail resource type (e.g., ContactMethod). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The current status of the contact method. - // - // A contact method has the following possible status: + // The unique name of the source disk (e.g., Disk-Virginia-1). // - // * PendingVerification — The contact method has not yet been verified, - // and the verification has not yet expired. + // This parameter cannot be defined together with the instance name parameter. + // The disk name and instance name parameters are mutually exclusive. + DiskName *string `locationName:"diskName" type:"string"` + + // The name of the destination disk snapshot (e.g., my-disk-snapshot) based + // on the source disk. // - // * Valid — The contact method has been verified. + // DiskSnapshotName is a required field + DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` + + // The unique name of the source instance (e.g., Amazon_Linux-512MB-Virginia-1). + // When this is defined, a snapshot of the instance's system volume is created. // - // * InValid — An attempt was made to verify the contact method, but the - // verification has expired. - Status *string `locationName:"status" type:"string" enum:"ContactMethodStatus"` + // This parameter cannot be defined together with the disk name parameter. The + // instance name and disk name parameters are mutually exclusive. + InstanceName *string `locationName:"instanceName" type:"string"` - // The support code. Include this code in your email to support when you have - // questions about your Lightsail contact method. This code enables our support - // team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` + // The tag keys and optional values to add to the resource during create. + // + // Use the TagResource action to tag a resource after it's created. + Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s ContactMethod) String() string { +func (s CreateDiskSnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ContactMethod) GoString() string { +func (s CreateDiskSnapshotInput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *ContactMethod) SetArn(v string) *ContactMethod { - s.Arn = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateDiskSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDiskSnapshotInput"} + if s.DiskSnapshotName == nil { + invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetContactEndpoint sets the ContactEndpoint field's value. -func (s *ContactMethod) SetContactEndpoint(v string) *ContactMethod { - s.ContactEndpoint = &v +// SetDiskName sets the DiskName field's value. +func (s *CreateDiskSnapshotInput) SetDiskName(v string) *CreateDiskSnapshotInput { + s.DiskName = &v return s } -// SetCreatedAt sets the CreatedAt field's value. -func (s *ContactMethod) SetCreatedAt(v time.Time) *ContactMethod { - s.CreatedAt = &v +// SetDiskSnapshotName sets the DiskSnapshotName field's value. +func (s *CreateDiskSnapshotInput) SetDiskSnapshotName(v string) *CreateDiskSnapshotInput { + s.DiskSnapshotName = &v return s } -// SetLocation sets the Location field's value. -func (s *ContactMethod) SetLocation(v *ResourceLocation) *ContactMethod { - s.Location = v +// SetInstanceName sets the InstanceName field's value. +func (s *CreateDiskSnapshotInput) SetInstanceName(v string) *CreateDiskSnapshotInput { + s.InstanceName = &v return s } -// SetName sets the Name field's value. -func (s *ContactMethod) SetName(v string) *ContactMethod { - s.Name = &v +// SetTags sets the Tags field's value. +func (s *CreateDiskSnapshotInput) SetTags(v []*Tag) *CreateDiskSnapshotInput { + s.Tags = v return s } -// SetProtocol sets the Protocol field's value. -func (s *ContactMethod) SetProtocol(v string) *ContactMethod { - s.Protocol = &v - return s +type CreateDiskSnapshotOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` } -// SetResourceType sets the ResourceType field's value. -func (s *ContactMethod) SetResourceType(v string) *ContactMethod { - s.ResourceType = &v - return s +// String returns the string representation +func (s CreateDiskSnapshotOutput) String() string { + return awsutil.Prettify(s) } -// SetStatus sets the Status field's value. -func (s *ContactMethod) SetStatus(v string) *ContactMethod { - s.Status = &v - return s +// GoString returns the string representation +func (s CreateDiskSnapshotOutput) GoString() string { + return s.String() } -// SetSupportCode sets the SupportCode field's value. -func (s *ContactMethod) SetSupportCode(v string) *ContactMethod { - s.SupportCode = &v +// SetOperations sets the Operations field's value. +func (s *CreateDiskSnapshotOutput) SetOperations(v []*Operation) *CreateDiskSnapshotOutput { + s.Operations = v return s } -type CopySnapshotInput struct { +type CreateDistributionInput struct { _ struct{} `type:"structure"` - // The date of the source automatic snapshot to copy. Use the get auto snapshots - // operation to identify the dates of the available automatic snapshots. - // - // Constraints: + // The bundle ID to use for the distribution. // - // * Must be specified in YYYY-MM-DD format. + // A distribution bundle describes the specifications of your distribution, + // such as the monthly cost and monthly network transfer quota. // - // * This parameter cannot be defined together with the use latest restorable - // auto snapshot parameter. The restore date and use latest restorable auto - // snapshot parameters are mutually exclusive. + // Use the GetDistributionBundles action to get a list of distribution bundle + // IDs that you can specify. // - // * Define this parameter only when copying an automatic snapshot as a manual - // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-keeping-automatic-snapshots). - RestoreDate *string `locationName:"restoreDate" type:"string"` + // BundleId is a required field + BundleId *string `locationName:"bundleId" type:"string" required:"true"` - // The AWS Region where the source manual or automatic snapshot is located. - // - // SourceRegion is a required field - SourceRegion *string `locationName:"sourceRegion" type:"string" required:"true" enum:"RegionName"` + // An object that describes the cache behavior settings for the distribution. + CacheBehaviorSettings *CacheSettings `locationName:"cacheBehaviorSettings" type:"structure"` - // The name of the source instance or disk from which the source automatic snapshot - // was created. - // - // Constraint: - // - // * Define this parameter only when copying an automatic snapshot as a manual - // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-keeping-automatic-snapshots). - SourceResourceName *string `locationName:"sourceResourceName" type:"string"` + // An array of objects that describe the per-path cache behavior for the distribution. + CacheBehaviors []*CacheBehaviorPerPath `locationName:"cacheBehaviors" type:"list"` - // The name of the source manual snapshot to copy. - // - // Constraint: + // An object that describes the default cache behavior for the distribution. // - // * Define this parameter only when copying a manual snapshot as another - // manual snapshot. - SourceSnapshotName *string `locationName:"sourceSnapshotName" type:"string"` + // DefaultCacheBehavior is a required field + DefaultCacheBehavior *CacheBehavior `locationName:"defaultCacheBehavior" type:"structure" required:"true"` - // The name of the new manual snapshot to be created as a copy. + // The name for the distribution. // - // TargetSnapshotName is a required field - TargetSnapshotName *string `locationName:"targetSnapshotName" type:"string" required:"true"` - - // A Boolean value to indicate whether to use the latest available automatic - // snapshot of the specified source instance or disk. + // DistributionName is a required field + DistributionName *string `locationName:"distributionName" type:"string" required:"true"` + + // An object that describes the origin resource for the distribution, such as + // a Lightsail instance or load balancer. // - // Constraints: + // The distribution pulls, caches, and serves content from the origin. // - // * This parameter cannot be defined together with the restore date parameter. - // The use latest restorable auto snapshot and restore date parameters are - // mutually exclusive. + // Origin is a required field + Origin *InputOrigin `locationName:"origin" type:"structure" required:"true"` + + // The tag keys and optional values to add to the distribution during create. // - // * Define this parameter only when copying an automatic snapshot as a manual - // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-keeping-automatic-snapshots). - UseLatestRestorableAutoSnapshot *bool `locationName:"useLatestRestorableAutoSnapshot" type:"boolean"` + // Use the TagResource action to tag a resource after it's created. + Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s CopySnapshotInput) String() string { +func (s CreateDistributionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CopySnapshotInput) GoString() string { +func (s CreateDistributionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CopySnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CopySnapshotInput"} - if s.SourceRegion == nil { - invalidParams.Add(request.NewErrParamRequired("SourceRegion")) +func (s *CreateDistributionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDistributionInput"} + if s.BundleId == nil { + invalidParams.Add(request.NewErrParamRequired("BundleId")) } - if s.TargetSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("TargetSnapshotName")) + if s.DefaultCacheBehavior == nil { + invalidParams.Add(request.NewErrParamRequired("DefaultCacheBehavior")) + } + if s.DistributionName == nil { + invalidParams.Add(request.NewErrParamRequired("DistributionName")) + } + if s.Origin == nil { + invalidParams.Add(request.NewErrParamRequired("Origin")) } if invalidParams.Len() > 0 { @@ -13893,104 +16926,116 @@ func (s *CopySnapshotInput) Validate() error { return nil } -// SetRestoreDate sets the RestoreDate field's value. -func (s *CopySnapshotInput) SetRestoreDate(v string) *CopySnapshotInput { - s.RestoreDate = &v +// SetBundleId sets the BundleId field's value. +func (s *CreateDistributionInput) SetBundleId(v string) *CreateDistributionInput { + s.BundleId = &v return s } -// SetSourceRegion sets the SourceRegion field's value. -func (s *CopySnapshotInput) SetSourceRegion(v string) *CopySnapshotInput { - s.SourceRegion = &v +// SetCacheBehaviorSettings sets the CacheBehaviorSettings field's value. +func (s *CreateDistributionInput) SetCacheBehaviorSettings(v *CacheSettings) *CreateDistributionInput { + s.CacheBehaviorSettings = v return s } -// SetSourceResourceName sets the SourceResourceName field's value. -func (s *CopySnapshotInput) SetSourceResourceName(v string) *CopySnapshotInput { - s.SourceResourceName = &v +// SetCacheBehaviors sets the CacheBehaviors field's value. +func (s *CreateDistributionInput) SetCacheBehaviors(v []*CacheBehaviorPerPath) *CreateDistributionInput { + s.CacheBehaviors = v return s } -// SetSourceSnapshotName sets the SourceSnapshotName field's value. -func (s *CopySnapshotInput) SetSourceSnapshotName(v string) *CopySnapshotInput { - s.SourceSnapshotName = &v +// SetDefaultCacheBehavior sets the DefaultCacheBehavior field's value. +func (s *CreateDistributionInput) SetDefaultCacheBehavior(v *CacheBehavior) *CreateDistributionInput { + s.DefaultCacheBehavior = v return s } -// SetTargetSnapshotName sets the TargetSnapshotName field's value. -func (s *CopySnapshotInput) SetTargetSnapshotName(v string) *CopySnapshotInput { - s.TargetSnapshotName = &v +// SetDistributionName sets the DistributionName field's value. +func (s *CreateDistributionInput) SetDistributionName(v string) *CreateDistributionInput { + s.DistributionName = &v return s } -// SetUseLatestRestorableAutoSnapshot sets the UseLatestRestorableAutoSnapshot field's value. -func (s *CopySnapshotInput) SetUseLatestRestorableAutoSnapshot(v bool) *CopySnapshotInput { - s.UseLatestRestorableAutoSnapshot = &v +// SetOrigin sets the Origin field's value. +func (s *CreateDistributionInput) SetOrigin(v *InputOrigin) *CreateDistributionInput { + s.Origin = v return s } -type CopySnapshotOutput struct { +// SetTags sets the Tags field's value. +func (s *CreateDistributionInput) SetTags(v []*Tag) *CreateDistributionInput { + s.Tags = v + return s +} + +type CreateDistributionOutput struct { _ struct{} `type:"structure"` + // An object that describes the distribution created. + Distribution *LightsailDistribution `locationName:"distribution" type:"structure"` + // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operations []*Operation `locationName:"operations" type:"list"` + Operation *Operation `locationName:"operation" type:"structure"` } // String returns the string representation -func (s CopySnapshotOutput) String() string { +func (s CreateDistributionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CopySnapshotOutput) GoString() string { +func (s CreateDistributionOutput) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *CopySnapshotOutput) SetOperations(v []*Operation) *CopySnapshotOutput { - s.Operations = v +// SetDistribution sets the Distribution field's value. +func (s *CreateDistributionOutput) SetDistribution(v *LightsailDistribution) *CreateDistributionOutput { + s.Distribution = v return s } -type CreateCloudFormationStackInput struct { +// SetOperation sets the Operation field's value. +func (s *CreateDistributionOutput) SetOperation(v *Operation) *CreateDistributionOutput { + s.Operation = v + return s +} + +type CreateDomainEntryInput struct { _ struct{} `type:"structure"` - // An array of parameters that will be used to create the new Amazon EC2 instance. - // You can only pass one instance entry at a time in this array. You will get - // an invalid parameter error if you pass more than one instance entry in this - // array. + // An array of key-value pairs containing information about the domain entry + // request. // - // Instances is a required field - Instances []*InstanceEntry `locationName:"instances" type:"list" required:"true"` + // DomainEntry is a required field + DomainEntry *DomainEntry `locationName:"domainEntry" type:"structure" required:"true"` + + // The domain name (e.g., example.com) for which you want to create the domain + // entry. + // + // DomainName is a required field + DomainName *string `locationName:"domainName" type:"string" required:"true"` } // String returns the string representation -func (s CreateCloudFormationStackInput) String() string { +func (s CreateDomainEntryInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateCloudFormationStackInput) GoString() string { +func (s CreateDomainEntryInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateCloudFormationStackInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateCloudFormationStackInput"} - if s.Instances == nil { - invalidParams.Add(request.NewErrParamRequired("Instances")) +func (s *CreateDomainEntryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDomainEntryInput"} + if s.DomainEntry == nil { + invalidParams.Add(request.NewErrParamRequired("DomainEntry")) } - if s.Instances != nil { - for i, v := range s.Instances { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Instances", i), err.(request.ErrInvalidParams)) - } - } + if s.DomainName == nil { + invalidParams.Add(request.NewErrParamRequired("DomainName")) } if invalidParams.Len() > 0 { @@ -13999,102 +17044,159 @@ func (s *CreateCloudFormationStackInput) Validate() error { return nil } -// SetInstances sets the Instances field's value. -func (s *CreateCloudFormationStackInput) SetInstances(v []*InstanceEntry) *CreateCloudFormationStackInput { - s.Instances = v +// SetDomainEntry sets the DomainEntry field's value. +func (s *CreateDomainEntryInput) SetDomainEntry(v *DomainEntry) *CreateDomainEntryInput { + s.DomainEntry = v return s } -type CreateCloudFormationStackOutput struct { +// SetDomainName sets the DomainName field's value. +func (s *CreateDomainEntryInput) SetDomainName(v string) *CreateDomainEntryInput { + s.DomainName = &v + return s +} + +type CreateDomainEntryOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operations []*Operation `locationName:"operations" type:"list"` + Operation *Operation `locationName:"operation" type:"structure"` } // String returns the string representation -func (s CreateCloudFormationStackOutput) String() string { +func (s CreateDomainEntryOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateCloudFormationStackOutput) GoString() string { +func (s CreateDomainEntryOutput) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *CreateCloudFormationStackOutput) SetOperations(v []*Operation) *CreateCloudFormationStackOutput { - s.Operations = v +// SetOperation sets the Operation field's value. +func (s *CreateDomainEntryOutput) SetOperation(v *Operation) *CreateDomainEntryOutput { + s.Operation = v return s } -type CreateContactMethodInput struct { +type CreateDomainInput struct { _ struct{} `type:"structure"` - // The destination of the contact method, such as an email address or a mobile - // phone number. + // The domain name to manage (e.g., example.com). // - // Use the E.164 format when specifying a mobile phone number. E.164 is a standard - // for the phone number structure used for international telecommunication. - // Phone numbers that follow this format can have a maximum of 15 digits, and - // they are prefixed with the plus character (+) and the country code. For example, - // a U.S. phone number in E.164 format would be specified as +1XXX5550100. For - // more information, see E.164 (https://en.wikipedia.org/wiki/E.164) in Wikipedia. + // You cannot register a new domain name using Lightsail. You must register + // a domain name using Amazon Route 53 or another domain name registrar. If + // you have already registered your domain, you can enter its name in this parameter + // to manage the DNS records for that domain. // - // ContactEndpoint is a required field - ContactEndpoint *string `locationName:"contactEndpoint" min:"1" type:"string" required:"true"` + // DomainName is a required field + DomainName *string `locationName:"domainName" type:"string" required:"true"` - // The protocol of the contact method, such as Email or SMS (text messaging). - // - // The SMS protocol is supported only in the following AWS Regions. - // - // * US East (N. Virginia) (us-east-1) - // - // * US West (Oregon) (us-west-2) - // - // * Europe (Ireland) (eu-west-1) - // - // * Asia Pacific (Tokyo) (ap-northeast-1) - // - // * Asia Pacific (Singapore) (ap-southeast-1) + // The tag keys and optional values to add to the resource during create. // - // * Asia Pacific (Sydney) (ap-southeast-2) + // Use the TagResource action to tag a resource after it's created. + Tags []*Tag `locationName:"tags" type:"list"` +} + +// String returns the string representation +func (s CreateDomainInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDomainInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateDomainInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDomainInput"} + if s.DomainName == nil { + invalidParams.Add(request.NewErrParamRequired("DomainName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomainName sets the DomainName field's value. +func (s *CreateDomainInput) SetDomainName(v string) *CreateDomainInput { + s.DomainName = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateDomainInput) SetTags(v []*Tag) *CreateDomainInput { + s.Tags = v + return s +} + +type CreateDomainOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operation *Operation `locationName:"operation" type:"structure"` +} + +// String returns the string representation +func (s CreateDomainOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDomainOutput) GoString() string { + return s.String() +} + +// SetOperation sets the Operation field's value. +func (s *CreateDomainOutput) SetOperation(v *Operation) *CreateDomainOutput { + s.Operation = v + return s +} + +type CreateInstanceSnapshotInput struct { + _ struct{} `type:"structure"` + + // The Lightsail instance on which to base your snapshot. // - // For a list of countries/regions where SMS text messages can be sent, and - // the latest AWS Regions where SMS text messaging is supported, see Supported - // Regions and Countries (https://docs.aws.amazon.com/sns/latest/dg/sns-supported-regions-countries.html) - // in the Amazon SNS Developer Guide. + // InstanceName is a required field + InstanceName *string `locationName:"instanceName" type:"string" required:"true"` + + // The name for your new snapshot. // - // For more information about notifications in Amazon Lightsail, see Notifications - // in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-notifications). + // InstanceSnapshotName is a required field + InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` + + // The tag keys and optional values to add to the resource during create. // - // Protocol is a required field - Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"ContactProtocol"` + // Use the TagResource action to tag a resource after it's created. + Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s CreateContactMethodInput) String() string { +func (s CreateInstanceSnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateContactMethodInput) GoString() string { +func (s CreateInstanceSnapshotInput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateContactMethodInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateContactMethodInput"} - if s.ContactEndpoint == nil { - invalidParams.Add(request.NewErrParamRequired("ContactEndpoint")) - } - if s.ContactEndpoint != nil && len(*s.ContactEndpoint) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ContactEndpoint", 1)) +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateInstanceSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateInstanceSnapshotInput"} + if s.InstanceName == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceName")) } - if s.Protocol == nil { - invalidParams.Add(request.NewErrParamRequired("Protocol")) + if s.InstanceSnapshotName == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) } if invalidParams.Len() > 0 { @@ -14103,76 +17205,95 @@ func (s *CreateContactMethodInput) Validate() error { return nil } -// SetContactEndpoint sets the ContactEndpoint field's value. -func (s *CreateContactMethodInput) SetContactEndpoint(v string) *CreateContactMethodInput { - s.ContactEndpoint = &v +// SetInstanceName sets the InstanceName field's value. +func (s *CreateInstanceSnapshotInput) SetInstanceName(v string) *CreateInstanceSnapshotInput { + s.InstanceName = &v return s } -// SetProtocol sets the Protocol field's value. -func (s *CreateContactMethodInput) SetProtocol(v string) *CreateContactMethodInput { - s.Protocol = &v +// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. +func (s *CreateInstanceSnapshotInput) SetInstanceSnapshotName(v string) *CreateInstanceSnapshotInput { + s.InstanceSnapshotName = &v return s } -type CreateContactMethodOutput struct { +// SetTags sets the Tags field's value. +func (s *CreateInstanceSnapshotInput) SetTags(v []*Tag) *CreateInstanceSnapshotInput { + s.Tags = v + return s +} + +type CreateInstanceSnapshotOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateContactMethodOutput) String() string { +func (s CreateInstanceSnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateContactMethodOutput) GoString() string { +func (s CreateInstanceSnapshotOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *CreateContactMethodOutput) SetOperations(v []*Operation) *CreateContactMethodOutput { +func (s *CreateInstanceSnapshotOutput) SetOperations(v []*Operation) *CreateInstanceSnapshotOutput { s.Operations = v return s } -type CreateDiskFromSnapshotInput struct { +type CreateInstancesFromSnapshotInput struct { _ struct{} `type:"structure"` - // An array of objects that represent the add-ons to enable for the new disk. + // An array of objects representing the add-ons to enable for the new instance. AddOns []*AddOnRequest `locationName:"addOns" type:"list"` - // The Availability Zone where you want to create the disk (e.g., us-east-2a). - // Choose the same Availability Zone as the Lightsail instance where you want - // to create the disk. - // - // Use the GetRegions operation to list the Availability Zones where Lightsail - // is currently available. + // An object containing information about one or more disk mappings. + AttachedDiskMapping map[string][]*DiskMap `locationName:"attachedDiskMapping" type:"map"` + + // The Availability Zone where you want to create your instances. Use the following + // formatting: us-east-2a (case sensitive). You can get a list of Availability + // Zones by using the get regions (http://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRegions.html) + // operation. Be sure to add the include Availability Zones parameter to your + // request. // // AvailabilityZone is a required field AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - // The unique Lightsail disk name (e.g., my-disk). + // The bundle of specification information for your virtual private server (or + // instance), including the pricing plan (e.g., micro_1_0). // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` + // BundleId is a required field + BundleId *string `locationName:"bundleId" type:"string" required:"true"` - // The name of the disk snapshot (e.g., my-snapshot) from which to create the - // new storage disk. + // The names for your new instances. + // + // InstanceNames is a required field + InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` + + // The name of the instance snapshot on which you are basing your new instances. + // Use the get instance snapshots operation to return information about your + // existing snapshots. // // Constraint: // - // * This parameter cannot be defined together with the source disk name - // parameter. The disk snapshot name and source disk name parameters are - // mutually exclusive. - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string"` + // * This parameter cannot be defined together with the source instance name + // parameter. The instance snapshot name and source instance name parameters + // are mutually exclusive. + InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string"` - // The date of the automatic snapshot to use for the new disk. Use the get auto - // snapshots operation to identify the dates of the available automatic snapshots. + // The name for your key pair. + KeyPairName *string `locationName:"keyPairName" type:"string"` + + // The date of the automatic snapshot to use for the new instance. Use the get + // auto snapshots operation to identify the dates of the available automatic + // snapshots. // // Constraints: // @@ -14182,31 +17303,26 @@ type CreateDiskFromSnapshotInput struct { // auto snapshot parameter. The restore date and use latest restorable auto // snapshot parameters are mutually exclusive. // - // * Define this parameter only when creating a new disk from an automatic + // * Define this parameter only when creating a new instance from an automatic // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-configuring-automatic-snapshots). RestoreDate *string `locationName:"restoreDate" type:"string"` - // The size of the disk in GB (e.g., 32). - // - // SizeInGb is a required field - SizeInGb *int64 `locationName:"sizeInGb" type:"integer" required:"true"` - - // The name of the source disk from which the source automatic snapshot was - // created. + // The name of the source instance from which the source automatic snapshot + // was created. // // Constraints: // - // * This parameter cannot be defined together with the disk snapshot name - // parameter. The source disk name and disk snapshot name parameters are - // mutually exclusive. + // * This parameter cannot be defined together with the instance snapshot + // name parameter. The source instance name and instance snapshot name parameters + // are mutually exclusive. // - // * Define this parameter only when creating a new disk from an automatic + // * Define this parameter only when creating a new instance from an automatic // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-configuring-automatic-snapshots). - SourceDiskName *string `locationName:"sourceDiskName" type:"string"` + SourceInstanceName *string `locationName:"sourceInstanceName" type:"string"` // The tag keys and optional values to add to the resource during create. // - // To tag a resource after it has been created, see the tag resource operation. + // Use the TagResource action to tag a resource after it's created. Tags []*Tag `locationName:"tags" type:"list"` // A Boolean value to indicate whether to use the latest available automatic @@ -14218,32 +17334,41 @@ type CreateDiskFromSnapshotInput struct { // The use latest restorable auto snapshot and restore date parameters are // mutually exclusive. // - // * Define this parameter only when creating a new disk from an automatic + // * Define this parameter only when creating a new instance from an automatic // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-configuring-automatic-snapshots). UseLatestRestorableAutoSnapshot *bool `locationName:"useLatestRestorableAutoSnapshot" type:"boolean"` + + // You can create a launch script that configures a server with additional user + // data. For example, apt-get -y update. + // + // Depending on the machine image you choose, the command to get software on + // your instance varies. Amazon Linux and CentOS use yum, Debian and Ubuntu + // use apt-get, and FreeBSD uses pkg. For a complete list, see the Dev Guide + // (https://lightsail.aws.amazon.com/ls/docs/getting-started/article/compare-options-choose-lightsail-instance-image). + UserData *string `locationName:"userData" type:"string"` } // String returns the string representation -func (s CreateDiskFromSnapshotInput) String() string { +func (s CreateInstancesFromSnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDiskFromSnapshotInput) GoString() string { +func (s CreateInstancesFromSnapshotInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDiskFromSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDiskFromSnapshotInput"} +func (s *CreateInstancesFromSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateInstancesFromSnapshotInput"} if s.AvailabilityZone == nil { invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) } - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) + if s.BundleId == nil { + invalidParams.Add(request.NewErrParamRequired("BundleId")) } - if s.SizeInGb == nil { - invalidParams.Add(request.NewErrParamRequired("SizeInGb")) + if s.InstanceNames == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceNames")) } if s.AddOns != nil { for i, v := range s.AddOns { @@ -14263,137 +17388,191 @@ func (s *CreateDiskFromSnapshotInput) Validate() error { } // SetAddOns sets the AddOns field's value. -func (s *CreateDiskFromSnapshotInput) SetAddOns(v []*AddOnRequest) *CreateDiskFromSnapshotInput { +func (s *CreateInstancesFromSnapshotInput) SetAddOns(v []*AddOnRequest) *CreateInstancesFromSnapshotInput { s.AddOns = v return s } +// SetAttachedDiskMapping sets the AttachedDiskMapping field's value. +func (s *CreateInstancesFromSnapshotInput) SetAttachedDiskMapping(v map[string][]*DiskMap) *CreateInstancesFromSnapshotInput { + s.AttachedDiskMapping = v + return s +} + // SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateDiskFromSnapshotInput) SetAvailabilityZone(v string) *CreateDiskFromSnapshotInput { +func (s *CreateInstancesFromSnapshotInput) SetAvailabilityZone(v string) *CreateInstancesFromSnapshotInput { s.AvailabilityZone = &v return s } -// SetDiskName sets the DiskName field's value. -func (s *CreateDiskFromSnapshotInput) SetDiskName(v string) *CreateDiskFromSnapshotInput { - s.DiskName = &v +// SetBundleId sets the BundleId field's value. +func (s *CreateInstancesFromSnapshotInput) SetBundleId(v string) *CreateInstancesFromSnapshotInput { + s.BundleId = &v return s } -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *CreateDiskFromSnapshotInput) SetDiskSnapshotName(v string) *CreateDiskFromSnapshotInput { - s.DiskSnapshotName = &v +// SetInstanceNames sets the InstanceNames field's value. +func (s *CreateInstancesFromSnapshotInput) SetInstanceNames(v []*string) *CreateInstancesFromSnapshotInput { + s.InstanceNames = v return s } -// SetRestoreDate sets the RestoreDate field's value. -func (s *CreateDiskFromSnapshotInput) SetRestoreDate(v string) *CreateDiskFromSnapshotInput { - s.RestoreDate = &v +// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. +func (s *CreateInstancesFromSnapshotInput) SetInstanceSnapshotName(v string) *CreateInstancesFromSnapshotInput { + s.InstanceSnapshotName = &v return s } -// SetSizeInGb sets the SizeInGb field's value. -func (s *CreateDiskFromSnapshotInput) SetSizeInGb(v int64) *CreateDiskFromSnapshotInput { - s.SizeInGb = &v +// SetKeyPairName sets the KeyPairName field's value. +func (s *CreateInstancesFromSnapshotInput) SetKeyPairName(v string) *CreateInstancesFromSnapshotInput { + s.KeyPairName = &v return s } -// SetSourceDiskName sets the SourceDiskName field's value. -func (s *CreateDiskFromSnapshotInput) SetSourceDiskName(v string) *CreateDiskFromSnapshotInput { - s.SourceDiskName = &v +// SetRestoreDate sets the RestoreDate field's value. +func (s *CreateInstancesFromSnapshotInput) SetRestoreDate(v string) *CreateInstancesFromSnapshotInput { + s.RestoreDate = &v + return s +} + +// SetSourceInstanceName sets the SourceInstanceName field's value. +func (s *CreateInstancesFromSnapshotInput) SetSourceInstanceName(v string) *CreateInstancesFromSnapshotInput { + s.SourceInstanceName = &v return s } // SetTags sets the Tags field's value. -func (s *CreateDiskFromSnapshotInput) SetTags(v []*Tag) *CreateDiskFromSnapshotInput { +func (s *CreateInstancesFromSnapshotInput) SetTags(v []*Tag) *CreateInstancesFromSnapshotInput { s.Tags = v return s } // SetUseLatestRestorableAutoSnapshot sets the UseLatestRestorableAutoSnapshot field's value. -func (s *CreateDiskFromSnapshotInput) SetUseLatestRestorableAutoSnapshot(v bool) *CreateDiskFromSnapshotInput { +func (s *CreateInstancesFromSnapshotInput) SetUseLatestRestorableAutoSnapshot(v bool) *CreateInstancesFromSnapshotInput { s.UseLatestRestorableAutoSnapshot = &v return s } -type CreateDiskFromSnapshotOutput struct { +// SetUserData sets the UserData field's value. +func (s *CreateInstancesFromSnapshotInput) SetUserData(v string) *CreateInstancesFromSnapshotInput { + s.UserData = &v + return s +} + +type CreateInstancesFromSnapshotOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateDiskFromSnapshotOutput) String() string { +func (s CreateInstancesFromSnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDiskFromSnapshotOutput) GoString() string { +func (s CreateInstancesFromSnapshotOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *CreateDiskFromSnapshotOutput) SetOperations(v []*Operation) *CreateDiskFromSnapshotOutput { +func (s *CreateInstancesFromSnapshotOutput) SetOperations(v []*Operation) *CreateInstancesFromSnapshotOutput { s.Operations = v return s } -type CreateDiskInput struct { +type CreateInstancesInput struct { _ struct{} `type:"structure"` - // An array of objects that represent the add-ons to enable for the new disk. + // An array of objects representing the add-ons to enable for the new instance. AddOns []*AddOnRequest `locationName:"addOns" type:"list"` - // The Availability Zone where you want to create the disk (e.g., us-east-2a). - // Use the same Availability Zone as the Lightsail instance to which you want - // to attach the disk. - // - // Use the get regions operation to list the Availability Zones where Lightsail - // is currently available. + // The Availability Zone in which to create your instance. Use the following + // format: us-east-2a (case sensitive). You can get a list of Availability Zones + // by using the get regions (http://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRegions.html) + // operation. Be sure to add the include Availability Zones parameter to your + // request. // // AvailabilityZone is a required field AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - // The unique Lightsail disk name (e.g., my-disk). + // The ID for a virtual private server image (e.g., app_wordpress_4_4 or app_lamp_7_0). + // Use the get blueprints operation to return a list of available images (or + // blueprints). // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` + // Use active blueprints when creating new instances. Inactive blueprints are + // listed to support customers with existing instances and are not necessarily + // available to create new instances. Blueprints are marked inactive when they + // become outdated due to operating system updates or new application releases. + // + // BlueprintId is a required field + BlueprintId *string `locationName:"blueprintId" type:"string" required:"true"` - // The size of the disk in GB (e.g., 32). + // The bundle of specification information for your virtual private server (or + // instance), including the pricing plan (e.g., micro_1_0). // - // SizeInGb is a required field - SizeInGb *int64 `locationName:"sizeInGb" type:"integer" required:"true"` + // BundleId is a required field + BundleId *string `locationName:"bundleId" type:"string" required:"true"` + + // (Deprecated) The name for your custom image. + // + // In releases prior to June 12, 2017, this parameter was ignored by the API. + // It is now deprecated. + // + // Deprecated: CustomImageName has been deprecated + CustomImageName *string `locationName:"customImageName" deprecated:"true" type:"string"` + + // The names to use for your new Lightsail instances. Separate multiple values + // using quotation marks and commas, for example: ["MyFirstInstance","MySecondInstance"] + // + // InstanceNames is a required field + InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` + + // The name of your key pair. + KeyPairName *string `locationName:"keyPairName" type:"string"` // The tag keys and optional values to add to the resource during create. // - // To tag a resource after it has been created, see the tag resource operation. + // Use the TagResource action to tag a resource after it's created. Tags []*Tag `locationName:"tags" type:"list"` + + // A launch script you can create that configures a server with additional user + // data. For example, you might want to run apt-get -y update. + // + // Depending on the machine image you choose, the command to get software on + // your instance varies. Amazon Linux and CentOS use yum, Debian and Ubuntu + // use apt-get, and FreeBSD uses pkg. For a complete list, see the Dev Guide + // (https://lightsail.aws.amazon.com/ls/docs/getting-started/article/compare-options-choose-lightsail-instance-image). + UserData *string `locationName:"userData" type:"string"` } // String returns the string representation -func (s CreateDiskInput) String() string { +func (s CreateInstancesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDiskInput) GoString() string { +func (s CreateInstancesInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDiskInput"} +func (s *CreateInstancesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateInstancesInput"} if s.AvailabilityZone == nil { invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) } - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) + if s.BlueprintId == nil { + invalidParams.Add(request.NewErrParamRequired("BlueprintId")) } - if s.SizeInGb == nil { - invalidParams.Add(request.NewErrParamRequired("SizeInGb")) + if s.BundleId == nil { + invalidParams.Add(request.NewErrParamRequired("BundleId")) + } + if s.InstanceNames == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceNames")) } if s.AddOns != nil { for i, v := range s.AddOns { @@ -14413,103 +17592,113 @@ func (s *CreateDiskInput) Validate() error { } // SetAddOns sets the AddOns field's value. -func (s *CreateDiskInput) SetAddOns(v []*AddOnRequest) *CreateDiskInput { +func (s *CreateInstancesInput) SetAddOns(v []*AddOnRequest) *CreateInstancesInput { s.AddOns = v return s } // SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateDiskInput) SetAvailabilityZone(v string) *CreateDiskInput { +func (s *CreateInstancesInput) SetAvailabilityZone(v string) *CreateInstancesInput { s.AvailabilityZone = &v return s } -// SetDiskName sets the DiskName field's value. -func (s *CreateDiskInput) SetDiskName(v string) *CreateDiskInput { - s.DiskName = &v +// SetBlueprintId sets the BlueprintId field's value. +func (s *CreateInstancesInput) SetBlueprintId(v string) *CreateInstancesInput { + s.BlueprintId = &v return s } -// SetSizeInGb sets the SizeInGb field's value. -func (s *CreateDiskInput) SetSizeInGb(v int64) *CreateDiskInput { - s.SizeInGb = &v +// SetBundleId sets the BundleId field's value. +func (s *CreateInstancesInput) SetBundleId(v string) *CreateInstancesInput { + s.BundleId = &v + return s +} + +// SetCustomImageName sets the CustomImageName field's value. +func (s *CreateInstancesInput) SetCustomImageName(v string) *CreateInstancesInput { + s.CustomImageName = &v + return s +} + +// SetInstanceNames sets the InstanceNames field's value. +func (s *CreateInstancesInput) SetInstanceNames(v []*string) *CreateInstancesInput { + s.InstanceNames = v + return s +} + +// SetKeyPairName sets the KeyPairName field's value. +func (s *CreateInstancesInput) SetKeyPairName(v string) *CreateInstancesInput { + s.KeyPairName = &v return s } // SetTags sets the Tags field's value. -func (s *CreateDiskInput) SetTags(v []*Tag) *CreateDiskInput { +func (s *CreateInstancesInput) SetTags(v []*Tag) *CreateInstancesInput { s.Tags = v return s } -type CreateDiskOutput struct { +// SetUserData sets the UserData field's value. +func (s *CreateInstancesInput) SetUserData(v string) *CreateInstancesInput { + s.UserData = &v + return s +} + +type CreateInstancesOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateDiskOutput) String() string { +func (s CreateInstancesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDiskOutput) GoString() string { +func (s CreateInstancesOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *CreateDiskOutput) SetOperations(v []*Operation) *CreateDiskOutput { +func (s *CreateInstancesOutput) SetOperations(v []*Operation) *CreateInstancesOutput { s.Operations = v return s } -type CreateDiskSnapshotInput struct { +type CreateKeyPairInput struct { _ struct{} `type:"structure"` - // The unique name of the source disk (e.g., Disk-Virginia-1). - // - // This parameter cannot be defined together with the instance name parameter. - // The disk name and instance name parameters are mutually exclusive. - DiskName *string `locationName:"diskName" type:"string"` - - // The name of the destination disk snapshot (e.g., my-disk-snapshot) based - // on the source disk. - // - // DiskSnapshotName is a required field - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` - - // The unique name of the source instance (e.g., Amazon_Linux-512MB-Virginia-1). - // When this is defined, a snapshot of the instance's system volume is created. + // The name for your new key pair. // - // This parameter cannot be defined together with the disk name parameter. The - // instance name and disk name parameters are mutually exclusive. - InstanceName *string `locationName:"instanceName" type:"string"` + // KeyPairName is a required field + KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` // The tag keys and optional values to add to the resource during create. // - // To tag a resource after it has been created, see the tag resource operation. + // Use the TagResource action to tag a resource after it's created. Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s CreateDiskSnapshotInput) String() string { +func (s CreateKeyPairInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDiskSnapshotInput) GoString() string { +func (s CreateKeyPairInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDiskSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDiskSnapshotInput"} - if s.DiskSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) +func (s *CreateKeyPairInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateKeyPairInput"} + if s.KeyPairName == nil { + invalidParams.Add(request.NewErrParamRequired("KeyPairName")) } if invalidParams.Len() > 0 { @@ -14518,168 +17707,136 @@ func (s *CreateDiskSnapshotInput) Validate() error { return nil } -// SetDiskName sets the DiskName field's value. -func (s *CreateDiskSnapshotInput) SetDiskName(v string) *CreateDiskSnapshotInput { - s.DiskName = &v - return s -} - -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *CreateDiskSnapshotInput) SetDiskSnapshotName(v string) *CreateDiskSnapshotInput { - s.DiskSnapshotName = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *CreateDiskSnapshotInput) SetInstanceName(v string) *CreateDiskSnapshotInput { - s.InstanceName = &v +// SetKeyPairName sets the KeyPairName field's value. +func (s *CreateKeyPairInput) SetKeyPairName(v string) *CreateKeyPairInput { + s.KeyPairName = &v return s } // SetTags sets the Tags field's value. -func (s *CreateDiskSnapshotInput) SetTags(v []*Tag) *CreateDiskSnapshotInput { +func (s *CreateKeyPairInput) SetTags(v []*Tag) *CreateKeyPairInput { s.Tags = v return s } -type CreateDiskSnapshotOutput struct { +type CreateKeyPairOutput struct { _ struct{} `type:"structure"` + // An array of key-value pairs containing information about the new key pair + // you just created. + KeyPair *KeyPair `locationName:"keyPair" type:"structure"` + // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateDiskSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateDiskSnapshotOutput) SetOperations(v []*Operation) *CreateDiskSnapshotOutput { - s.Operations = v - return s -} - -type CreateDomainEntryInput struct { - _ struct{} `type:"structure"` + Operation *Operation `locationName:"operation" type:"structure"` - // An array of key-value pairs containing information about the domain entry - // request. - // - // DomainEntry is a required field - DomainEntry *DomainEntry `locationName:"domainEntry" type:"structure" required:"true"` + // A base64-encoded RSA private key. + PrivateKeyBase64 *string `locationName:"privateKeyBase64" type:"string"` - // The domain name (e.g., example.com) for which you want to create the domain - // entry. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` + // A base64-encoded public key of the ssh-rsa type. + PublicKeyBase64 *string `locationName:"publicKeyBase64" type:"string"` } // String returns the string representation -func (s CreateDomainEntryInput) String() string { +func (s CreateKeyPairOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDomainEntryInput) GoString() string { +func (s CreateKeyPairOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDomainEntryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDomainEntryInput"} - if s.DomainEntry == nil { - invalidParams.Add(request.NewErrParamRequired("DomainEntry")) - } - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } +// SetKeyPair sets the KeyPair field's value. +func (s *CreateKeyPairOutput) SetKeyPair(v *KeyPair) *CreateKeyPairOutput { + s.KeyPair = v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetOperation sets the Operation field's value. +func (s *CreateKeyPairOutput) SetOperation(v *Operation) *CreateKeyPairOutput { + s.Operation = v + return s } -// SetDomainEntry sets the DomainEntry field's value. -func (s *CreateDomainEntryInput) SetDomainEntry(v *DomainEntry) *CreateDomainEntryInput { - s.DomainEntry = v +// SetPrivateKeyBase64 sets the PrivateKeyBase64 field's value. +func (s *CreateKeyPairOutput) SetPrivateKeyBase64(v string) *CreateKeyPairOutput { + s.PrivateKeyBase64 = &v return s } -// SetDomainName sets the DomainName field's value. -func (s *CreateDomainEntryInput) SetDomainName(v string) *CreateDomainEntryInput { - s.DomainName = &v +// SetPublicKeyBase64 sets the PublicKeyBase64 field's value. +func (s *CreateKeyPairOutput) SetPublicKeyBase64(v string) *CreateKeyPairOutput { + s.PublicKeyBase64 = &v return s } -type CreateDomainEntryOutput struct { +type CreateLoadBalancerInput struct { _ struct{} `type:"structure"` - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s CreateDomainEntryOutput) String() string { - return awsutil.Prettify(s) -} + // The optional alternative domains and subdomains to use with your SSL/TLS + // certificate (e.g., www.example.com, example.com, m.example.com, blog.example.com). + CertificateAlternativeNames []*string `locationName:"certificateAlternativeNames" type:"list"` -// GoString returns the string representation -func (s CreateDomainEntryOutput) GoString() string { - return s.String() -} + // The domain name with which your certificate is associated (e.g., example.com). + // + // If you specify certificateDomainName, then certificateName is required (and + // vice-versa). + CertificateDomainName *string `locationName:"certificateDomainName" type:"string"` -// SetOperation sets the Operation field's value. -func (s *CreateDomainEntryOutput) SetOperation(v *Operation) *CreateDomainEntryOutput { - s.Operation = v - return s -} + // The name of the SSL/TLS certificate. + // + // If you specify certificateName, then certificateDomainName is required (and + // vice-versa). + CertificateName *string `locationName:"certificateName" type:"string"` -type CreateDomainInput struct { - _ struct{} `type:"structure"` + // The path you provided to perform the load balancer health check. If you didn't + // specify a health check path, Lightsail uses the root path of your website + // (e.g., "/"). + // + // You may want to specify a custom health check path other than the root of + // your application if your home page loads slowly or has a lot of media or + // scripting on it. + HealthCheckPath *string `locationName:"healthCheckPath" type:"string"` - // The domain name to manage (e.g., example.com). + // The instance port where you're creating your load balancer. // - // You cannot register a new domain name using Lightsail. You must register - // a domain name using Amazon Route 53 or another domain name registrar. If - // you have already registered your domain, you can enter its name in this parameter - // to manage the DNS records for that domain. + // InstancePort is a required field + InstancePort *int64 `locationName:"instancePort" type:"integer" required:"true"` + + // The name of your load balancer. // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` + // LoadBalancerName is a required field + LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` // The tag keys and optional values to add to the resource during create. // - // To tag a resource after it has been created, see the tag resource operation. + // Use the TagResource action to tag a resource after it's created. Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s CreateDomainInput) String() string { +func (s CreateLoadBalancerInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDomainInput) GoString() string { +func (s CreateLoadBalancerInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDomainInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDomainInput"} - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) +func (s *CreateLoadBalancerInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateLoadBalancerInput"} + if s.InstancePort == nil { + invalidParams.Add(request.NewErrParamRequired("InstancePort")) + } + if s.InstancePort != nil && *s.InstancePort < -1 { + invalidParams.Add(request.NewErrParamMinValue("InstancePort", -1)) + } + if s.LoadBalancerName == nil { + invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) } if invalidParams.Len() > 0 { @@ -14688,80 +17845,129 @@ func (s *CreateDomainInput) Validate() error { return nil } -// SetDomainName sets the DomainName field's value. -func (s *CreateDomainInput) SetDomainName(v string) *CreateDomainInput { - s.DomainName = &v +// SetCertificateAlternativeNames sets the CertificateAlternativeNames field's value. +func (s *CreateLoadBalancerInput) SetCertificateAlternativeNames(v []*string) *CreateLoadBalancerInput { + s.CertificateAlternativeNames = v + return s +} + +// SetCertificateDomainName sets the CertificateDomainName field's value. +func (s *CreateLoadBalancerInput) SetCertificateDomainName(v string) *CreateLoadBalancerInput { + s.CertificateDomainName = &v + return s +} + +// SetCertificateName sets the CertificateName field's value. +func (s *CreateLoadBalancerInput) SetCertificateName(v string) *CreateLoadBalancerInput { + s.CertificateName = &v + return s +} + +// SetHealthCheckPath sets the HealthCheckPath field's value. +func (s *CreateLoadBalancerInput) SetHealthCheckPath(v string) *CreateLoadBalancerInput { + s.HealthCheckPath = &v + return s +} + +// SetInstancePort sets the InstancePort field's value. +func (s *CreateLoadBalancerInput) SetInstancePort(v int64) *CreateLoadBalancerInput { + s.InstancePort = &v + return s +} + +// SetLoadBalancerName sets the LoadBalancerName field's value. +func (s *CreateLoadBalancerInput) SetLoadBalancerName(v string) *CreateLoadBalancerInput { + s.LoadBalancerName = &v return s } // SetTags sets the Tags field's value. -func (s *CreateDomainInput) SetTags(v []*Tag) *CreateDomainInput { +func (s *CreateLoadBalancerInput) SetTags(v []*Tag) *CreateLoadBalancerInput { s.Tags = v return s } -type CreateDomainOutput struct { +type CreateLoadBalancerOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operation *Operation `locationName:"operation" type:"structure"` + Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateDomainOutput) String() string { +func (s CreateLoadBalancerOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDomainOutput) GoString() string { +func (s CreateLoadBalancerOutput) GoString() string { return s.String() } -// SetOperation sets the Operation field's value. -func (s *CreateDomainOutput) SetOperation(v *Operation) *CreateDomainOutput { - s.Operation = v +// SetOperations sets the Operations field's value. +func (s *CreateLoadBalancerOutput) SetOperations(v []*Operation) *CreateLoadBalancerOutput { + s.Operations = v return s } -type CreateInstanceSnapshotInput struct { +type CreateLoadBalancerTlsCertificateInput struct { _ struct{} `type:"structure"` - // The Lightsail instance on which to base your snapshot. + // An array of strings listing alternative domains and subdomains for your SSL/TLS + // certificate. Lightsail will de-dupe the names for you. You can have a maximum + // of 9 alternative names (in addition to the 1 primary domain). We do not support + // wildcards (e.g., *.example.com). + CertificateAlternativeNames []*string `locationName:"certificateAlternativeNames" type:"list"` + + // The domain name (e.g., example.com) for your SSL/TLS certificate. // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` + // CertificateDomainName is a required field + CertificateDomainName *string `locationName:"certificateDomainName" type:"string" required:"true"` - // The name for your new snapshot. + // The SSL/TLS certificate name. // - // InstanceSnapshotName is a required field - InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` + // You can have up to 10 certificates in your account at one time. Each Lightsail + // load balancer can have up to 2 certificates associated with it at one time. + // There is also an overall limit to the number of certificates that can be + // issue in a 365-day period. For more information, see Limits (http://docs.aws.amazon.com/acm/latest/userguide/acm-limits.html). + // + // CertificateName is a required field + CertificateName *string `locationName:"certificateName" type:"string" required:"true"` + + // The load balancer name where you want to create the SSL/TLS certificate. + // + // LoadBalancerName is a required field + LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` // The tag keys and optional values to add to the resource during create. // - // To tag a resource after it has been created, see the tag resource operation. + // Use the TagResource action to tag a resource after it's created. Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s CreateInstanceSnapshotInput) String() string { +func (s CreateLoadBalancerTlsCertificateInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateInstanceSnapshotInput) GoString() string { +func (s CreateLoadBalancerTlsCertificateInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateInstanceSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateInstanceSnapshotInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) +func (s *CreateLoadBalancerTlsCertificateInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateLoadBalancerTlsCertificateInput"} + if s.CertificateDomainName == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateDomainName")) } - if s.InstanceSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) + if s.CertificateName == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateName")) + } + if s.LoadBalancerName == nil { + invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) } if invalidParams.Len() > 0 { @@ -14770,180 +17976,149 @@ func (s *CreateInstanceSnapshotInput) Validate() error { return nil } -// SetInstanceName sets the InstanceName field's value. -func (s *CreateInstanceSnapshotInput) SetInstanceName(v string) *CreateInstanceSnapshotInput { - s.InstanceName = &v +// SetCertificateAlternativeNames sets the CertificateAlternativeNames field's value. +func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateAlternativeNames(v []*string) *CreateLoadBalancerTlsCertificateInput { + s.CertificateAlternativeNames = v return s } -// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. -func (s *CreateInstanceSnapshotInput) SetInstanceSnapshotName(v string) *CreateInstanceSnapshotInput { - s.InstanceSnapshotName = &v +// SetCertificateDomainName sets the CertificateDomainName field's value. +func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateDomainName(v string) *CreateLoadBalancerTlsCertificateInput { + s.CertificateDomainName = &v + return s +} + +// SetCertificateName sets the CertificateName field's value. +func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateName(v string) *CreateLoadBalancerTlsCertificateInput { + s.CertificateName = &v + return s +} + +// SetLoadBalancerName sets the LoadBalancerName field's value. +func (s *CreateLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *CreateLoadBalancerTlsCertificateInput { + s.LoadBalancerName = &v return s } // SetTags sets the Tags field's value. -func (s *CreateInstanceSnapshotInput) SetTags(v []*Tag) *CreateInstanceSnapshotInput { +func (s *CreateLoadBalancerTlsCertificateInput) SetTags(v []*Tag) *CreateLoadBalancerTlsCertificateInput { s.Tags = v return s } -type CreateInstanceSnapshotOutput struct { +type CreateLoadBalancerTlsCertificateOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateInstanceSnapshotOutput) String() string { +func (s CreateLoadBalancerTlsCertificateOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateInstanceSnapshotOutput) GoString() string { +func (s CreateLoadBalancerTlsCertificateOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *CreateInstanceSnapshotOutput) SetOperations(v []*Operation) *CreateInstanceSnapshotOutput { +func (s *CreateLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *CreateLoadBalancerTlsCertificateOutput { s.Operations = v return s } -type CreateInstancesFromSnapshotInput struct { +type CreateRelationalDatabaseFromSnapshotInput struct { _ struct{} `type:"structure"` - // An array of objects representing the add-ons to enable for the new instance. - AddOns []*AddOnRequest `locationName:"addOns" type:"list"` - - // An object containing information about one or more disk mappings. - AttachedDiskMapping map[string][]*DiskMap `locationName:"attachedDiskMapping" type:"map"` - - // The Availability Zone where you want to create your instances. Use the following - // formatting: us-east-2a (case sensitive). You can get a list of Availability - // Zones by using the get regions (http://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRegions.html) - // operation. Be sure to add the include Availability Zones parameter to your - // request. - // - // AvailabilityZone is a required field - AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - - // The bundle of specification information for your virtual private server (or - // instance), including the pricing plan (e.g., micro_1_0). + // The Availability Zone in which to create your new database. Use the us-east-2a + // case-sensitive format. // - // BundleId is a required field - BundleId *string `locationName:"bundleId" type:"string" required:"true"` + // You can get a list of Availability Zones by using the get regions operation. + // Be sure to add the include relational database Availability Zones parameter + // to your request. + AvailabilityZone *string `locationName:"availabilityZone" type:"string"` - // The names for your new instances. - // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` + // Specifies the accessibility options for your new database. A value of true + // specifies a database that is available to resources outside of your Lightsail + // account. A value of false specifies a database that is available only to + // your Lightsail resources in the same region as your database. + PubliclyAccessible *bool `locationName:"publiclyAccessible" type:"boolean"` - // The name of the instance snapshot on which you are basing your new instances. - // Use the get instance snapshots operation to return information about your - // existing snapshots. + // The bundle ID for your new database. A bundle describes the performance specifications + // for your database. // - // Constraint: + // You can get a list of database bundle IDs by using the get relational database + // bundles operation. // - // * This parameter cannot be defined together with the source instance name - // parameter. The instance snapshot name and source instance name parameters - // are mutually exclusive. - InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string"` - - // The name for your key pair. - KeyPairName *string `locationName:"keyPairName" type:"string"` + // When creating a new database from a snapshot, you cannot choose a bundle + // that is smaller than the bundle of the source database. + RelationalDatabaseBundleId *string `locationName:"relationalDatabaseBundleId" type:"string"` - // The date of the automatic snapshot to use for the new instance. Use the get - // auto snapshots operation to identify the dates of the available automatic - // snapshots. + // The name to use for your new database. // // Constraints: // - // * Must be specified in YYYY-MM-DD format. + // * Must contain from 2 to 255 alphanumeric characters, or hyphens. // - // * This parameter cannot be defined together with the use latest restorable - // auto snapshot parameter. The restore date and use latest restorable auto - // snapshot parameters are mutually exclusive. + // * The first and last character must be a letter or number. // - // * Define this parameter only when creating a new instance from an automatic - // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-configuring-automatic-snapshots). - RestoreDate *string `locationName:"restoreDate" type:"string"` + // RelationalDatabaseName is a required field + RelationalDatabaseName *string `locationName:"relationalDatabaseName" type:"string" required:"true"` - // The name of the source instance from which the source automatic snapshot - // was created. + // The name of the database snapshot from which to create your new database. + RelationalDatabaseSnapshotName *string `locationName:"relationalDatabaseSnapshotName" type:"string"` + + // The date and time to restore your database from. // // Constraints: // - // * This parameter cannot be defined together with the instance snapshot - // name parameter. The source instance name and instance snapshot name parameters - // are mutually exclusive. - // - // * Define this parameter only when creating a new instance from an automatic - // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-configuring-automatic-snapshots). - SourceInstanceName *string `locationName:"sourceInstanceName" type:"string"` - - // The tag keys and optional values to add to the resource during create. + // * Must be before the latest restorable time for the database. // - // To tag a resource after it has been created, see the tag resource operation. - Tags []*Tag `locationName:"tags" type:"list"` - - // A Boolean value to indicate whether to use the latest available automatic - // snapshot. + // * Cannot be specified if the use latest restorable time parameter is true. // - // Constraints: + // * Specified in Coordinated Universal Time (UTC). // - // * This parameter cannot be defined together with the restore date parameter. - // The use latest restorable auto snapshot and restore date parameters are - // mutually exclusive. + // * Specified in the Unix time format. For example, if you wish to use a + // restore time of October 1, 2018, at 8 PM UTC, then you input 1538424000 + // as the restore time. + RestoreTime *time.Time `locationName:"restoreTime" type:"timestamp"` + + // The name of the source database. + SourceRelationalDatabaseName *string `locationName:"sourceRelationalDatabaseName" type:"string"` + + // The tag keys and optional values to add to the resource during create. // - // * Define this parameter only when creating a new instance from an automatic - // snapshot. For more information, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-configuring-automatic-snapshots). - UseLatestRestorableAutoSnapshot *bool `locationName:"useLatestRestorableAutoSnapshot" type:"boolean"` + // Use the TagResource action to tag a resource after it's created. + Tags []*Tag `locationName:"tags" type:"list"` - // You can create a launch script that configures a server with additional user - // data. For example, apt-get -y update. + // Specifies whether your database is restored from the latest backup time. + // A value of true restores from the latest backup time. // - // Depending on the machine image you choose, the command to get software on - // your instance varies. Amazon Linux and CentOS use yum, Debian and Ubuntu - // use apt-get, and FreeBSD uses pkg. For a complete list, see the Dev Guide - // (https://lightsail.aws.amazon.com/ls/docs/getting-started/article/compare-options-choose-lightsail-instance-image). - UserData *string `locationName:"userData" type:"string"` + // Default: false + // + // Constraints: Cannot be specified if the restore time parameter is provided. + UseLatestRestorableTime *bool `locationName:"useLatestRestorableTime" type:"boolean"` } // String returns the string representation -func (s CreateInstancesFromSnapshotInput) String() string { +func (s CreateRelationalDatabaseFromSnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateInstancesFromSnapshotInput) GoString() string { +func (s CreateRelationalDatabaseFromSnapshotInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateInstancesFromSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateInstancesFromSnapshotInput"} - if s.AvailabilityZone == nil { - invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) - } - if s.BundleId == nil { - invalidParams.Add(request.NewErrParamRequired("BundleId")) - } - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) - } - if s.AddOns != nil { - for i, v := range s.AddOns { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "AddOns", i), err.(request.ErrInvalidParams)) - } - } +func (s *CreateRelationalDatabaseFromSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateRelationalDatabaseFromSnapshotInput"} + if s.RelationalDatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseName")) } if invalidParams.Len() > 0 { @@ -14952,202 +18127,238 @@ func (s *CreateInstancesFromSnapshotInput) Validate() error { return nil } -// SetAddOns sets the AddOns field's value. -func (s *CreateInstancesFromSnapshotInput) SetAddOns(v []*AddOnRequest) *CreateInstancesFromSnapshotInput { - s.AddOns = v - return s -} - -// SetAttachedDiskMapping sets the AttachedDiskMapping field's value. -func (s *CreateInstancesFromSnapshotInput) SetAttachedDiskMapping(v map[string][]*DiskMap) *CreateInstancesFromSnapshotInput { - s.AttachedDiskMapping = v - return s -} - // SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateInstancesFromSnapshotInput) SetAvailabilityZone(v string) *CreateInstancesFromSnapshotInput { +func (s *CreateRelationalDatabaseFromSnapshotInput) SetAvailabilityZone(v string) *CreateRelationalDatabaseFromSnapshotInput { s.AvailabilityZone = &v return s } -// SetBundleId sets the BundleId field's value. -func (s *CreateInstancesFromSnapshotInput) SetBundleId(v string) *CreateInstancesFromSnapshotInput { - s.BundleId = &v +// SetPubliclyAccessible sets the PubliclyAccessible field's value. +func (s *CreateRelationalDatabaseFromSnapshotInput) SetPubliclyAccessible(v bool) *CreateRelationalDatabaseFromSnapshotInput { + s.PubliclyAccessible = &v return s } -// SetInstanceNames sets the InstanceNames field's value. -func (s *CreateInstancesFromSnapshotInput) SetInstanceNames(v []*string) *CreateInstancesFromSnapshotInput { - s.InstanceNames = v +// SetRelationalDatabaseBundleId sets the RelationalDatabaseBundleId field's value. +func (s *CreateRelationalDatabaseFromSnapshotInput) SetRelationalDatabaseBundleId(v string) *CreateRelationalDatabaseFromSnapshotInput { + s.RelationalDatabaseBundleId = &v return s } -// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. -func (s *CreateInstancesFromSnapshotInput) SetInstanceSnapshotName(v string) *CreateInstancesFromSnapshotInput { - s.InstanceSnapshotName = &v +// SetRelationalDatabaseName sets the RelationalDatabaseName field's value. +func (s *CreateRelationalDatabaseFromSnapshotInput) SetRelationalDatabaseName(v string) *CreateRelationalDatabaseFromSnapshotInput { + s.RelationalDatabaseName = &v return s } -// SetKeyPairName sets the KeyPairName field's value. -func (s *CreateInstancesFromSnapshotInput) SetKeyPairName(v string) *CreateInstancesFromSnapshotInput { - s.KeyPairName = &v +// SetRelationalDatabaseSnapshotName sets the RelationalDatabaseSnapshotName field's value. +func (s *CreateRelationalDatabaseFromSnapshotInput) SetRelationalDatabaseSnapshotName(v string) *CreateRelationalDatabaseFromSnapshotInput { + s.RelationalDatabaseSnapshotName = &v return s } -// SetRestoreDate sets the RestoreDate field's value. -func (s *CreateInstancesFromSnapshotInput) SetRestoreDate(v string) *CreateInstancesFromSnapshotInput { - s.RestoreDate = &v +// SetRestoreTime sets the RestoreTime field's value. +func (s *CreateRelationalDatabaseFromSnapshotInput) SetRestoreTime(v time.Time) *CreateRelationalDatabaseFromSnapshotInput { + s.RestoreTime = &v return s } -// SetSourceInstanceName sets the SourceInstanceName field's value. -func (s *CreateInstancesFromSnapshotInput) SetSourceInstanceName(v string) *CreateInstancesFromSnapshotInput { - s.SourceInstanceName = &v +// SetSourceRelationalDatabaseName sets the SourceRelationalDatabaseName field's value. +func (s *CreateRelationalDatabaseFromSnapshotInput) SetSourceRelationalDatabaseName(v string) *CreateRelationalDatabaseFromSnapshotInput { + s.SourceRelationalDatabaseName = &v return s } // SetTags sets the Tags field's value. -func (s *CreateInstancesFromSnapshotInput) SetTags(v []*Tag) *CreateInstancesFromSnapshotInput { +func (s *CreateRelationalDatabaseFromSnapshotInput) SetTags(v []*Tag) *CreateRelationalDatabaseFromSnapshotInput { s.Tags = v return s } -// SetUseLatestRestorableAutoSnapshot sets the UseLatestRestorableAutoSnapshot field's value. -func (s *CreateInstancesFromSnapshotInput) SetUseLatestRestorableAutoSnapshot(v bool) *CreateInstancesFromSnapshotInput { - s.UseLatestRestorableAutoSnapshot = &v - return s -} - -// SetUserData sets the UserData field's value. -func (s *CreateInstancesFromSnapshotInput) SetUserData(v string) *CreateInstancesFromSnapshotInput { - s.UserData = &v +// SetUseLatestRestorableTime sets the UseLatestRestorableTime field's value. +func (s *CreateRelationalDatabaseFromSnapshotInput) SetUseLatestRestorableTime(v bool) *CreateRelationalDatabaseFromSnapshotInput { + s.UseLatestRestorableTime = &v return s } -type CreateInstancesFromSnapshotOutput struct { +type CreateRelationalDatabaseFromSnapshotOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateInstancesFromSnapshotOutput) String() string { +func (s CreateRelationalDatabaseFromSnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateInstancesFromSnapshotOutput) GoString() string { +func (s CreateRelationalDatabaseFromSnapshotOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *CreateInstancesFromSnapshotOutput) SetOperations(v []*Operation) *CreateInstancesFromSnapshotOutput { +func (s *CreateRelationalDatabaseFromSnapshotOutput) SetOperations(v []*Operation) *CreateRelationalDatabaseFromSnapshotOutput { s.Operations = v return s } -type CreateInstancesInput struct { +type CreateRelationalDatabaseInput struct { _ struct{} `type:"structure"` - // An array of objects representing the add-ons to enable for the new instance. - AddOns []*AddOnRequest `locationName:"addOns" type:"list"` + // The Availability Zone in which to create your new database. Use the us-east-2a + // case-sensitive format. + // + // You can get a list of Availability Zones by using the get regions operation. + // Be sure to add the include relational database Availability Zones parameter + // to your request. + AvailabilityZone *string `locationName:"availabilityZone" type:"string"` - // The Availability Zone in which to create your instance. Use the following - // format: us-east-2a (case sensitive). You can get a list of Availability Zones - // by using the get regions (http://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRegions.html) - // operation. Be sure to add the include Availability Zones parameter to your - // request. + // The name of the master database created when the Lightsail database resource + // is created. // - // AvailabilityZone is a required field - AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` + // Constraints: + // + // * Must contain from 1 to 64 alphanumeric characters. + // + // * Cannot be a word reserved by the specified database engine + // + // MasterDatabaseName is a required field + MasterDatabaseName *string `locationName:"masterDatabaseName" type:"string" required:"true"` - // The ID for a virtual private server image (e.g., app_wordpress_4_4 or app_lamp_7_0). - // Use the get blueprints operation to return a list of available images (or - // blueprints). + // The password for the master user of your new database. The password can include + // any printable ASCII character except "/", """, or "@". // - // Use active blueprints when creating new instances. Inactive blueprints are - // listed to support customers with existing instances and are not necessarily - // available to create new instances. Blueprints are marked inactive when they - // become outdated due to operating system updates or new application releases. + // Constraints: Must contain 8 to 41 characters. + MasterUserPassword *string `locationName:"masterUserPassword" type:"string" sensitive:"true"` + + // The master user name for your new database. // - // BlueprintId is a required field - BlueprintId *string `locationName:"blueprintId" type:"string" required:"true"` + // Constraints: + // + // * Master user name is required. + // + // * Must contain from 1 to 16 alphanumeric characters. + // + // * The first character must be a letter. + // + // * Cannot be a reserved word for the database engine you choose. For more + // information about reserved words in MySQL 5.6 or 5.7, see the Keywords + // and Reserved Words articles for MySQL 5.6 (https://dev.mysql.com/doc/refman/5.6/en/keywords.html) + // or MySQL 5.7 (https://dev.mysql.com/doc/refman/5.7/en/keywords.html) respectively. + // + // MasterUsername is a required field + MasterUsername *string `locationName:"masterUsername" type:"string" required:"true"` - // The bundle of specification information for your virtual private server (or - // instance), including the pricing plan (e.g., micro_1_0). + // The daily time range during which automated backups are created for your + // new database if automated backups are enabled. // - // BundleId is a required field - BundleId *string `locationName:"bundleId" type:"string" required:"true"` + // The default is a 30-minute window selected at random from an 8-hour block + // of time for each AWS Region. For more information about the preferred backup + // window time blocks for each region, see the Working With Backups (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithAutomatedBackups.html#USER_WorkingWithAutomatedBackups.BackupWindow) + // guide in the Amazon Relational Database Service (Amazon RDS) documentation. + // + // Constraints: + // + // * Must be in the hh24:mi-hh24:mi format. Example: 16:00-16:30 + // + // * Specified in Coordinated Universal Time (UTC). + // + // * Must not conflict with the preferred maintenance window. + // + // * Must be at least 30 minutes. + PreferredBackupWindow *string `locationName:"preferredBackupWindow" type:"string"` - // (Deprecated) The name for your custom image. + // The weekly time range during which system maintenance can occur on your new + // database. // - // In releases prior to June 12, 2017, this parameter was ignored by the API. - // It is now deprecated. + // The default is a 30-minute window selected at random from an 8-hour block + // of time for each AWS Region, occurring on a random day of the week. // - // Deprecated: CustomImageName has been deprecated - CustomImageName *string `locationName:"customImageName" deprecated:"true" type:"string"` + // Constraints: + // + // * Must be in the ddd:hh24:mi-ddd:hh24:mi format. + // + // * Valid days: Mon, Tue, Wed, Thu, Fri, Sat, Sun. + // + // * Must be at least 30 minutes. + // + // * Specified in Coordinated Universal Time (UTC). + // + // * Example: Tue:17:00-Tue:17:30 + PreferredMaintenanceWindow *string `locationName:"preferredMaintenanceWindow" type:"string"` - // The names to use for your new Lightsail instances. Separate multiple values - // using quotation marks and commas, for example: ["MyFirstInstance","MySecondInstance"] + // Specifies the accessibility options for your new database. A value of true + // specifies a database that is available to resources outside of your Lightsail + // account. A value of false specifies a database that is available only to + // your Lightsail resources in the same region as your database. + PubliclyAccessible *bool `locationName:"publiclyAccessible" type:"boolean"` + + // The blueprint ID for your new database. A blueprint describes the major engine + // version of a database. + // + // You can get a list of database blueprints IDs by using the get relational + // database blueprints operation. + // + // RelationalDatabaseBlueprintId is a required field + RelationalDatabaseBlueprintId *string `locationName:"relationalDatabaseBlueprintId" type:"string" required:"true"` + + // The bundle ID for your new database. A bundle describes the performance specifications + // for your database. + // + // You can get a list of database bundle IDs by using the get relational database + // bundles operation. + // + // RelationalDatabaseBundleId is a required field + RelationalDatabaseBundleId *string `locationName:"relationalDatabaseBundleId" type:"string" required:"true"` + + // The name to use for your new database. + // + // Constraints: + // + // * Must contain from 2 to 255 alphanumeric characters, or hyphens. + // + // * The first and last character must be a letter or number. // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` - - // The name of your key pair. - KeyPairName *string `locationName:"keyPairName" type:"string"` + // RelationalDatabaseName is a required field + RelationalDatabaseName *string `locationName:"relationalDatabaseName" type:"string" required:"true"` // The tag keys and optional values to add to the resource during create. // - // To tag a resource after it has been created, see the tag resource operation. + // Use the TagResource action to tag a resource after it's created. Tags []*Tag `locationName:"tags" type:"list"` - - // A launch script you can create that configures a server with additional user - // data. For example, you might want to run apt-get -y update. - // - // Depending on the machine image you choose, the command to get software on - // your instance varies. Amazon Linux and CentOS use yum, Debian and Ubuntu - // use apt-get, and FreeBSD uses pkg. For a complete list, see the Dev Guide - // (https://lightsail.aws.amazon.com/ls/docs/getting-started/article/compare-options-choose-lightsail-instance-image). - UserData *string `locationName:"userData" type:"string"` } // String returns the string representation -func (s CreateInstancesInput) String() string { +func (s CreateRelationalDatabaseInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateInstancesInput) GoString() string { +func (s CreateRelationalDatabaseInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateInstancesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateInstancesInput"} - if s.AvailabilityZone == nil { - invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) +func (s *CreateRelationalDatabaseInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateRelationalDatabaseInput"} + if s.MasterDatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("MasterDatabaseName")) } - if s.BlueprintId == nil { - invalidParams.Add(request.NewErrParamRequired("BlueprintId")) + if s.MasterUsername == nil { + invalidParams.Add(request.NewErrParamRequired("MasterUsername")) } - if s.BundleId == nil { - invalidParams.Add(request.NewErrParamRequired("BundleId")) + if s.RelationalDatabaseBlueprintId == nil { + invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseBlueprintId")) } - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) + if s.RelationalDatabaseBundleId == nil { + invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseBundleId")) } - if s.AddOns != nil { - for i, v := range s.AddOns { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "AddOns", i), err.(request.ErrInvalidParams)) - } - } + if s.RelationalDatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseName")) } if invalidParams.Len() > 0 { @@ -15156,114 +18367,140 @@ func (s *CreateInstancesInput) Validate() error { return nil } -// SetAddOns sets the AddOns field's value. -func (s *CreateInstancesInput) SetAddOns(v []*AddOnRequest) *CreateInstancesInput { - s.AddOns = v +// SetAvailabilityZone sets the AvailabilityZone field's value. +func (s *CreateRelationalDatabaseInput) SetAvailabilityZone(v string) *CreateRelationalDatabaseInput { + s.AvailabilityZone = &v return s } -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateInstancesInput) SetAvailabilityZone(v string) *CreateInstancesInput { - s.AvailabilityZone = &v +// SetMasterDatabaseName sets the MasterDatabaseName field's value. +func (s *CreateRelationalDatabaseInput) SetMasterDatabaseName(v string) *CreateRelationalDatabaseInput { + s.MasterDatabaseName = &v return s } -// SetBlueprintId sets the BlueprintId field's value. -func (s *CreateInstancesInput) SetBlueprintId(v string) *CreateInstancesInput { - s.BlueprintId = &v +// SetMasterUserPassword sets the MasterUserPassword field's value. +func (s *CreateRelationalDatabaseInput) SetMasterUserPassword(v string) *CreateRelationalDatabaseInput { + s.MasterUserPassword = &v return s } -// SetBundleId sets the BundleId field's value. -func (s *CreateInstancesInput) SetBundleId(v string) *CreateInstancesInput { - s.BundleId = &v +// SetMasterUsername sets the MasterUsername field's value. +func (s *CreateRelationalDatabaseInput) SetMasterUsername(v string) *CreateRelationalDatabaseInput { + s.MasterUsername = &v return s } -// SetCustomImageName sets the CustomImageName field's value. -func (s *CreateInstancesInput) SetCustomImageName(v string) *CreateInstancesInput { - s.CustomImageName = &v +// SetPreferredBackupWindow sets the PreferredBackupWindow field's value. +func (s *CreateRelationalDatabaseInput) SetPreferredBackupWindow(v string) *CreateRelationalDatabaseInput { + s.PreferredBackupWindow = &v return s } -// SetInstanceNames sets the InstanceNames field's value. -func (s *CreateInstancesInput) SetInstanceNames(v []*string) *CreateInstancesInput { - s.InstanceNames = v +// SetPreferredMaintenanceWindow sets the PreferredMaintenanceWindow field's value. +func (s *CreateRelationalDatabaseInput) SetPreferredMaintenanceWindow(v string) *CreateRelationalDatabaseInput { + s.PreferredMaintenanceWindow = &v return s } -// SetKeyPairName sets the KeyPairName field's value. -func (s *CreateInstancesInput) SetKeyPairName(v string) *CreateInstancesInput { - s.KeyPairName = &v +// SetPubliclyAccessible sets the PubliclyAccessible field's value. +func (s *CreateRelationalDatabaseInput) SetPubliclyAccessible(v bool) *CreateRelationalDatabaseInput { + s.PubliclyAccessible = &v return s } -// SetTags sets the Tags field's value. -func (s *CreateInstancesInput) SetTags(v []*Tag) *CreateInstancesInput { - s.Tags = v +// SetRelationalDatabaseBlueprintId sets the RelationalDatabaseBlueprintId field's value. +func (s *CreateRelationalDatabaseInput) SetRelationalDatabaseBlueprintId(v string) *CreateRelationalDatabaseInput { + s.RelationalDatabaseBlueprintId = &v return s } -// SetUserData sets the UserData field's value. -func (s *CreateInstancesInput) SetUserData(v string) *CreateInstancesInput { - s.UserData = &v +// SetRelationalDatabaseBundleId sets the RelationalDatabaseBundleId field's value. +func (s *CreateRelationalDatabaseInput) SetRelationalDatabaseBundleId(v string) *CreateRelationalDatabaseInput { + s.RelationalDatabaseBundleId = &v return s } -type CreateInstancesOutput struct { +// SetRelationalDatabaseName sets the RelationalDatabaseName field's value. +func (s *CreateRelationalDatabaseInput) SetRelationalDatabaseName(v string) *CreateRelationalDatabaseInput { + s.RelationalDatabaseName = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateRelationalDatabaseInput) SetTags(v []*Tag) *CreateRelationalDatabaseInput { + s.Tags = v + return s +} + +type CreateRelationalDatabaseOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateInstancesOutput) String() string { +func (s CreateRelationalDatabaseOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateInstancesOutput) GoString() string { +func (s CreateRelationalDatabaseOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *CreateInstancesOutput) SetOperations(v []*Operation) *CreateInstancesOutput { +func (s *CreateRelationalDatabaseOutput) SetOperations(v []*Operation) *CreateRelationalDatabaseOutput { s.Operations = v return s } -type CreateKeyPairInput struct { +type CreateRelationalDatabaseSnapshotInput struct { _ struct{} `type:"structure"` - // The name for your new key pair. + // The name of the database on which to base your new snapshot. // - // KeyPairName is a required field - KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` + // RelationalDatabaseName is a required field + RelationalDatabaseName *string `locationName:"relationalDatabaseName" type:"string" required:"true"` + + // The name for your new database snapshot. + // + // Constraints: + // + // * Must contain from 2 to 255 alphanumeric characters, or hyphens. + // + // * The first and last character must be a letter or number. + // + // RelationalDatabaseSnapshotName is a required field + RelationalDatabaseSnapshotName *string `locationName:"relationalDatabaseSnapshotName" type:"string" required:"true"` // The tag keys and optional values to add to the resource during create. // - // To tag a resource after it has been created, see the tag resource operation. + // Use the TagResource action to tag a resource after it's created. Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s CreateKeyPairInput) String() string { +func (s CreateRelationalDatabaseSnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateKeyPairInput) GoString() string { +func (s CreateRelationalDatabaseSnapshotInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateKeyPairInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateKeyPairInput"} - if s.KeyPairName == nil { - invalidParams.Add(request.NewErrParamRequired("KeyPairName")) +func (s *CreateRelationalDatabaseSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateRelationalDatabaseSnapshotInput"} + if s.RelationalDatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseName")) + } + if s.RelationalDatabaseSnapshotName == nil { + invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseSnapshotName")) } if invalidParams.Len() > 0 { @@ -15272,133 +18509,147 @@ func (s *CreateKeyPairInput) Validate() error { return nil } -// SetKeyPairName sets the KeyPairName field's value. -func (s *CreateKeyPairInput) SetKeyPairName(v string) *CreateKeyPairInput { - s.KeyPairName = &v +// SetRelationalDatabaseName sets the RelationalDatabaseName field's value. +func (s *CreateRelationalDatabaseSnapshotInput) SetRelationalDatabaseName(v string) *CreateRelationalDatabaseSnapshotInput { + s.RelationalDatabaseName = &v + return s +} + +// SetRelationalDatabaseSnapshotName sets the RelationalDatabaseSnapshotName field's value. +func (s *CreateRelationalDatabaseSnapshotInput) SetRelationalDatabaseSnapshotName(v string) *CreateRelationalDatabaseSnapshotInput { + s.RelationalDatabaseSnapshotName = &v return s } // SetTags sets the Tags field's value. -func (s *CreateKeyPairInput) SetTags(v []*Tag) *CreateKeyPairInput { +func (s *CreateRelationalDatabaseSnapshotInput) SetTags(v []*Tag) *CreateRelationalDatabaseSnapshotInput { s.Tags = v return s } -type CreateKeyPairOutput struct { +type CreateRelationalDatabaseSnapshotOutput struct { _ struct{} `type:"structure"` - // An array of key-value pairs containing information about the new key pair - // you just created. - KeyPair *KeyPair `locationName:"keyPair" type:"structure"` - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operation *Operation `locationName:"operation" type:"structure"` - - // A base64-encoded RSA private key. - PrivateKeyBase64 *string `locationName:"privateKeyBase64" type:"string"` - - // A base64-encoded public key of the ssh-rsa type. - PublicKeyBase64 *string `locationName:"publicKeyBase64" type:"string"` + Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateKeyPairOutput) String() string { +func (s CreateRelationalDatabaseSnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateKeyPairOutput) GoString() string { +func (s CreateRelationalDatabaseSnapshotOutput) GoString() string { return s.String() } -// SetKeyPair sets the KeyPair field's value. -func (s *CreateKeyPairOutput) SetKeyPair(v *KeyPair) *CreateKeyPairOutput { - s.KeyPair = v +// SetOperations sets the Operations field's value. +func (s *CreateRelationalDatabaseSnapshotOutput) SetOperations(v []*Operation) *CreateRelationalDatabaseSnapshotOutput { + s.Operations = v return s } -// SetOperation sets the Operation field's value. -func (s *CreateKeyPairOutput) SetOperation(v *Operation) *CreateKeyPairOutput { - s.Operation = v - return s +type DeleteAlarmInput struct { + _ struct{} `type:"structure"` + + // The name of the alarm to delete. + // + // AlarmName is a required field + AlarmName *string `locationName:"alarmName" type:"string" required:"true"` } -// SetPrivateKeyBase64 sets the PrivateKeyBase64 field's value. -func (s *CreateKeyPairOutput) SetPrivateKeyBase64(v string) *CreateKeyPairOutput { - s.PrivateKeyBase64 = &v - return s +// String returns the string representation +func (s DeleteAlarmInput) String() string { + return awsutil.Prettify(s) } -// SetPublicKeyBase64 sets the PublicKeyBase64 field's value. -func (s *CreateKeyPairOutput) SetPublicKeyBase64(v string) *CreateKeyPairOutput { - s.PublicKeyBase64 = &v +// GoString returns the string representation +func (s DeleteAlarmInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteAlarmInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteAlarmInput"} + if s.AlarmName == nil { + invalidParams.Add(request.NewErrParamRequired("AlarmName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAlarmName sets the AlarmName field's value. +func (s *DeleteAlarmInput) SetAlarmName(v string) *DeleteAlarmInput { + s.AlarmName = &v return s } -type CreateLoadBalancerInput struct { +type DeleteAlarmOutput struct { _ struct{} `type:"structure"` - // The optional alternative domains and subdomains to use with your SSL/TLS - // certificate (e.g., www.example.com, example.com, m.example.com, blog.example.com). - CertificateAlternativeNames []*string `locationName:"certificateAlternativeNames" type:"list"` + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` +} - // The domain name with which your certificate is associated (e.g., example.com). - // - // If you specify certificateDomainName, then certificateName is required (and - // vice-versa). - CertificateDomainName *string `locationName:"certificateDomainName" type:"string"` +// String returns the string representation +func (s DeleteAlarmOutput) String() string { + return awsutil.Prettify(s) +} - // The name of the SSL/TLS certificate. - // - // If you specify certificateName, then certificateDomainName is required (and - // vice-versa). - CertificateName *string `locationName:"certificateName" type:"string"` +// GoString returns the string representation +func (s DeleteAlarmOutput) GoString() string { + return s.String() +} - // The path you provided to perform the load balancer health check. If you didn't - // specify a health check path, Lightsail uses the root path of your website - // (e.g., "/"). - // - // You may want to specify a custom health check path other than the root of - // your application if your home page loads slowly or has a lot of media or - // scripting on it. - HealthCheckPath *string `locationName:"healthCheckPath" type:"string"` +// SetOperations sets the Operations field's value. +func (s *DeleteAlarmOutput) SetOperations(v []*Operation) *DeleteAlarmOutput { + s.Operations = v + return s +} - // The instance port where you're creating your load balancer. - // - // InstancePort is a required field - InstancePort *int64 `locationName:"instancePort" type:"integer" required:"true"` +type DeleteAutoSnapshotInput struct { + _ struct{} `type:"structure"` - // The name of your load balancer. + // The date of the automatic snapshot to delete in YYYY-MM-DD format. Use the + // get auto snapshots operation to get the available automatic snapshots for + // a resource. // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` + // Date is a required field + Date *string `locationName:"date" type:"string" required:"true"` - // The tag keys and optional values to add to the resource during create. + // The name of the source instance or disk from which to delete the automatic + // snapshot. // - // To tag a resource after it has been created, see the tag resource operation. - Tags []*Tag `locationName:"tags" type:"list"` + // ResourceName is a required field + ResourceName *string `locationName:"resourceName" type:"string" required:"true"` } // String returns the string representation -func (s CreateLoadBalancerInput) String() string { +func (s DeleteAutoSnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateLoadBalancerInput) GoString() string { +func (s DeleteAutoSnapshotInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateLoadBalancerInput"} - if s.InstancePort == nil { - invalidParams.Add(request.NewErrParamRequired("InstancePort")) +func (s *DeleteAutoSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteAutoSnapshotInput"} + if s.Date == nil { + invalidParams.Add(request.NewErrParamRequired("Date")) } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) + if s.ResourceName == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceName")) } if invalidParams.Len() > 0 { @@ -15407,130 +18658,71 @@ func (s *CreateLoadBalancerInput) Validate() error { return nil } -// SetCertificateAlternativeNames sets the CertificateAlternativeNames field's value. -func (s *CreateLoadBalancerInput) SetCertificateAlternativeNames(v []*string) *CreateLoadBalancerInput { - s.CertificateAlternativeNames = v - return s -} - -// SetCertificateDomainName sets the CertificateDomainName field's value. -func (s *CreateLoadBalancerInput) SetCertificateDomainName(v string) *CreateLoadBalancerInput { - s.CertificateDomainName = &v - return s -} - -// SetCertificateName sets the CertificateName field's value. -func (s *CreateLoadBalancerInput) SetCertificateName(v string) *CreateLoadBalancerInput { - s.CertificateName = &v - return s -} - -// SetHealthCheckPath sets the HealthCheckPath field's value. -func (s *CreateLoadBalancerInput) SetHealthCheckPath(v string) *CreateLoadBalancerInput { - s.HealthCheckPath = &v - return s -} - -// SetInstancePort sets the InstancePort field's value. -func (s *CreateLoadBalancerInput) SetInstancePort(v int64) *CreateLoadBalancerInput { - s.InstancePort = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *CreateLoadBalancerInput) SetLoadBalancerName(v string) *CreateLoadBalancerInput { - s.LoadBalancerName = &v +// SetDate sets the Date field's value. +func (s *DeleteAutoSnapshotInput) SetDate(v string) *DeleteAutoSnapshotInput { + s.Date = &v return s } -// SetTags sets the Tags field's value. -func (s *CreateLoadBalancerInput) SetTags(v []*Tag) *CreateLoadBalancerInput { - s.Tags = v +// SetResourceName sets the ResourceName field's value. +func (s *DeleteAutoSnapshotInput) SetResourceName(v string) *DeleteAutoSnapshotInput { + s.ResourceName = &v return s } -type CreateLoadBalancerOutput struct { +type DeleteAutoSnapshotOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateLoadBalancerOutput) String() string { +func (s DeleteAutoSnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateLoadBalancerOutput) GoString() string { +func (s DeleteAutoSnapshotOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *CreateLoadBalancerOutput) SetOperations(v []*Operation) *CreateLoadBalancerOutput { +func (s *DeleteAutoSnapshotOutput) SetOperations(v []*Operation) *DeleteAutoSnapshotOutput { s.Operations = v return s } -type CreateLoadBalancerTlsCertificateInput struct { +type DeleteCertificateInput struct { _ struct{} `type:"structure"` - // An array of strings listing alternative domains and subdomains for your SSL/TLS - // certificate. Lightsail will de-dupe the names for you. You can have a maximum - // of 9 alternative names (in addition to the 1 primary domain). We do not support - // wildcards (e.g., *.example.com). - CertificateAlternativeNames []*string `locationName:"certificateAlternativeNames" type:"list"` - - // The domain name (e.g., example.com) for your SSL/TLS certificate. - // - // CertificateDomainName is a required field - CertificateDomainName *string `locationName:"certificateDomainName" type:"string" required:"true"` - - // The SSL/TLS certificate name. + // The name of the certificate to delete. // - // You can have up to 10 certificates in your account at one time. Each Lightsail - // load balancer can have up to 2 certificates associated with it at one time. - // There is also an overall limit to the number of certificates that can be - // issue in a 365-day period. For more information, see Limits (http://docs.aws.amazon.com/acm/latest/userguide/acm-limits.html). + // Use the GetCertificates action to get a list of certificate names that you + // can specify. // // CertificateName is a required field CertificateName *string `locationName:"certificateName" type:"string" required:"true"` - - // The load balancer name where you want to create the SSL/TLS certificate. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` - - // The tag keys and optional values to add to the resource during create. - // - // To tag a resource after it has been created, see the tag resource operation. - Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s CreateLoadBalancerTlsCertificateInput) String() string { +func (s DeleteCertificateInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateLoadBalancerTlsCertificateInput) GoString() string { +func (s DeleteCertificateInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateLoadBalancerTlsCertificateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateLoadBalancerTlsCertificateInput"} - if s.CertificateDomainName == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateDomainName")) - } +func (s *DeleteCertificateInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteCertificateInput"} if s.CertificateName == nil { invalidParams.Add(request.NewErrParamRequired("CertificateName")) } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } if invalidParams.Len() > 0 { return invalidParams @@ -15538,149 +18730,131 @@ func (s *CreateLoadBalancerTlsCertificateInput) Validate() error { return nil } -// SetCertificateAlternativeNames sets the CertificateAlternativeNames field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateAlternativeNames(v []*string) *CreateLoadBalancerTlsCertificateInput { - s.CertificateAlternativeNames = v - return s -} - -// SetCertificateDomainName sets the CertificateDomainName field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateDomainName(v string) *CreateLoadBalancerTlsCertificateInput { - s.CertificateDomainName = &v - return s -} - // SetCertificateName sets the CertificateName field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateName(v string) *CreateLoadBalancerTlsCertificateInput { +func (s *DeleteCertificateInput) SetCertificateName(v string) *DeleteCertificateInput { s.CertificateName = &v return s } -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *CreateLoadBalancerTlsCertificateInput { - s.LoadBalancerName = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetTags(v []*Tag) *CreateLoadBalancerTlsCertificateInput { - s.Tags = v - return s -} - -type CreateLoadBalancerTlsCertificateOutput struct { +type DeleteCertificateOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateLoadBalancerTlsCertificateOutput) String() string { +func (s DeleteCertificateOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateLoadBalancerTlsCertificateOutput) GoString() string { +func (s DeleteCertificateOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *CreateLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *CreateLoadBalancerTlsCertificateOutput { +func (s *DeleteCertificateOutput) SetOperations(v []*Operation) *DeleteCertificateOutput { s.Operations = v return s } -type CreateRelationalDatabaseFromSnapshotInput struct { +type DeleteContactMethodInput struct { _ struct{} `type:"structure"` - // The Availability Zone in which to create your new database. Use the us-east-2a - // case-sensitive format. + // The protocol that will be deleted, such as Email or SMS (text messaging). // - // You can get a list of Availability Zones by using the get regions operation. - // Be sure to add the include relational database Availability Zones parameter - // to your request. - AvailabilityZone *string `locationName:"availabilityZone" type:"string"` + // To delete an Email and an SMS contact method if you added both, you must + // run separate DeleteContactMethod actions to delete each protocol. + // + // Protocol is a required field + Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"ContactProtocol"` +} - // Specifies the accessibility options for your new database. A value of true - // specifies a database that is available to resources outside of your Lightsail - // account. A value of false specifies a database that is available only to - // your Lightsail resources in the same region as your database. - PubliclyAccessible *bool `locationName:"publiclyAccessible" type:"boolean"` +// String returns the string representation +func (s DeleteContactMethodInput) String() string { + return awsutil.Prettify(s) +} - // The bundle ID for your new database. A bundle describes the performance specifications - // for your database. - // - // You can get a list of database bundle IDs by using the get relational database - // bundles operation. - // - // When creating a new database from a snapshot, you cannot choose a bundle - // that is smaller than the bundle of the source database. - RelationalDatabaseBundleId *string `locationName:"relationalDatabaseBundleId" type:"string"` +// GoString returns the string representation +func (s DeleteContactMethodInput) GoString() string { + return s.String() +} - // The name to use for your new database. - // - // Constraints: - // - // * Must contain from 2 to 255 alphanumeric characters, or hyphens. - // - // * The first and last character must be a letter or number. - // - // RelationalDatabaseName is a required field - RelationalDatabaseName *string `locationName:"relationalDatabaseName" type:"string" required:"true"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteContactMethodInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteContactMethodInput"} + if s.Protocol == nil { + invalidParams.Add(request.NewErrParamRequired("Protocol")) + } - // The name of the database snapshot from which to create your new database. - RelationalDatabaseSnapshotName *string `locationName:"relationalDatabaseSnapshotName" type:"string"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetProtocol sets the Protocol field's value. +func (s *DeleteContactMethodInput) SetProtocol(v string) *DeleteContactMethodInput { + s.Protocol = &v + return s +} + +type DeleteContactMethodOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` +} + +// String returns the string representation +func (s DeleteContactMethodOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteContactMethodOutput) GoString() string { + return s.String() +} - // The date and time to restore your database from. - // - // Constraints: - // - // * Must be before the latest restorable time for the database. - // - // * Cannot be specified if the use latest restorable time parameter is true. - // - // * Specified in Coordinated Universal Time (UTC). - // - // * Specified in the Unix time format. For example, if you wish to use a - // restore time of October 1, 2018, at 8 PM UTC, then you input 1538424000 - // as the restore time. - RestoreTime *time.Time `locationName:"restoreTime" type:"timestamp"` +// SetOperations sets the Operations field's value. +func (s *DeleteContactMethodOutput) SetOperations(v []*Operation) *DeleteContactMethodOutput { + s.Operations = v + return s +} - // The name of the source database. - SourceRelationalDatabaseName *string `locationName:"sourceRelationalDatabaseName" type:"string"` +type DeleteDiskInput struct { + _ struct{} `type:"structure"` - // The tag keys and optional values to add to the resource during create. + // The unique name of the disk you want to delete (e.g., my-disk). // - // To tag a resource after it has been created, see the tag resource operation. - Tags []*Tag `locationName:"tags" type:"list"` + // DiskName is a required field + DiskName *string `locationName:"diskName" type:"string" required:"true"` - // Specifies whether your database is restored from the latest backup time. - // A value of true restores from the latest backup time. - // - // Default: false - // - // Constraints: Cannot be specified if the restore time parameter is provided. - UseLatestRestorableTime *bool `locationName:"useLatestRestorableTime" type:"boolean"` + // A Boolean value to indicate whether to delete the enabled add-ons for the + // disk. + ForceDeleteAddOns *bool `locationName:"forceDeleteAddOns" type:"boolean"` } // String returns the string representation -func (s CreateRelationalDatabaseFromSnapshotInput) String() string { +func (s DeleteDiskInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateRelationalDatabaseFromSnapshotInput) GoString() string { +func (s DeleteDiskInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateRelationalDatabaseFromSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateRelationalDatabaseFromSnapshotInput"} - if s.RelationalDatabaseName == nil { - invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseName")) +func (s *DeleteDiskInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDiskInput"} + if s.DiskName == nil { + invalidParams.Add(request.NewErrParamRequired("DiskName")) } if invalidParams.Len() > 0 { @@ -15689,238 +18863,189 @@ func (s *CreateRelationalDatabaseFromSnapshotInput) Validate() error { return nil } -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateRelationalDatabaseFromSnapshotInput) SetAvailabilityZone(v string) *CreateRelationalDatabaseFromSnapshotInput { - s.AvailabilityZone = &v +// SetDiskName sets the DiskName field's value. +func (s *DeleteDiskInput) SetDiskName(v string) *DeleteDiskInput { + s.DiskName = &v return s } -// SetPubliclyAccessible sets the PubliclyAccessible field's value. -func (s *CreateRelationalDatabaseFromSnapshotInput) SetPubliclyAccessible(v bool) *CreateRelationalDatabaseFromSnapshotInput { - s.PubliclyAccessible = &v +// SetForceDeleteAddOns sets the ForceDeleteAddOns field's value. +func (s *DeleteDiskInput) SetForceDeleteAddOns(v bool) *DeleteDiskInput { + s.ForceDeleteAddOns = &v return s } -// SetRelationalDatabaseBundleId sets the RelationalDatabaseBundleId field's value. -func (s *CreateRelationalDatabaseFromSnapshotInput) SetRelationalDatabaseBundleId(v string) *CreateRelationalDatabaseFromSnapshotInput { - s.RelationalDatabaseBundleId = &v - return s +type DeleteDiskOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` } -// SetRelationalDatabaseName sets the RelationalDatabaseName field's value. -func (s *CreateRelationalDatabaseFromSnapshotInput) SetRelationalDatabaseName(v string) *CreateRelationalDatabaseFromSnapshotInput { - s.RelationalDatabaseName = &v - return s +// String returns the string representation +func (s DeleteDiskOutput) String() string { + return awsutil.Prettify(s) } -// SetRelationalDatabaseSnapshotName sets the RelationalDatabaseSnapshotName field's value. -func (s *CreateRelationalDatabaseFromSnapshotInput) SetRelationalDatabaseSnapshotName(v string) *CreateRelationalDatabaseFromSnapshotInput { - s.RelationalDatabaseSnapshotName = &v - return s +// GoString returns the string representation +func (s DeleteDiskOutput) GoString() string { + return s.String() } -// SetRestoreTime sets the RestoreTime field's value. -func (s *CreateRelationalDatabaseFromSnapshotInput) SetRestoreTime(v time.Time) *CreateRelationalDatabaseFromSnapshotInput { - s.RestoreTime = &v +// SetOperations sets the Operations field's value. +func (s *DeleteDiskOutput) SetOperations(v []*Operation) *DeleteDiskOutput { + s.Operations = v return s } -// SetSourceRelationalDatabaseName sets the SourceRelationalDatabaseName field's value. -func (s *CreateRelationalDatabaseFromSnapshotInput) SetSourceRelationalDatabaseName(v string) *CreateRelationalDatabaseFromSnapshotInput { - s.SourceRelationalDatabaseName = &v - return s +type DeleteDiskSnapshotInput struct { + _ struct{} `type:"structure"` + + // The name of the disk snapshot you want to delete (e.g., my-disk-snapshot). + // + // DiskSnapshotName is a required field + DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` } -// SetTags sets the Tags field's value. -func (s *CreateRelationalDatabaseFromSnapshotInput) SetTags(v []*Tag) *CreateRelationalDatabaseFromSnapshotInput { - s.Tags = v - return s +// String returns the string representation +func (s DeleteDiskSnapshotInput) String() string { + return awsutil.Prettify(s) } -// SetUseLatestRestorableTime sets the UseLatestRestorableTime field's value. -func (s *CreateRelationalDatabaseFromSnapshotInput) SetUseLatestRestorableTime(v bool) *CreateRelationalDatabaseFromSnapshotInput { - s.UseLatestRestorableTime = &v +// GoString returns the string representation +func (s DeleteDiskSnapshotInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteDiskSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDiskSnapshotInput"} + if s.DiskSnapshotName == nil { + invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDiskSnapshotName sets the DiskSnapshotName field's value. +func (s *DeleteDiskSnapshotInput) SetDiskSnapshotName(v string) *DeleteDiskSnapshotInput { + s.DiskSnapshotName = &v return s } -type CreateRelationalDatabaseFromSnapshotOutput struct { +type DeleteDiskSnapshotOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateRelationalDatabaseFromSnapshotOutput) String() string { +func (s DeleteDiskSnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateRelationalDatabaseFromSnapshotOutput) GoString() string { +func (s DeleteDiskSnapshotOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *CreateRelationalDatabaseFromSnapshotOutput) SetOperations(v []*Operation) *CreateRelationalDatabaseFromSnapshotOutput { +func (s *DeleteDiskSnapshotOutput) SetOperations(v []*Operation) *DeleteDiskSnapshotOutput { s.Operations = v return s } -type CreateRelationalDatabaseInput struct { +type DeleteDistributionInput struct { _ struct{} `type:"structure"` - // The Availability Zone in which to create your new database. Use the us-east-2a - // case-sensitive format. + // The name of the distribution to delete. // - // You can get a list of Availability Zones by using the get regions operation. - // Be sure to add the include relational database Availability Zones parameter - // to your request. - AvailabilityZone *string `locationName:"availabilityZone" type:"string"` + // Use the GetDistributions action to get a list of distribution names that + // you can specify. + DistributionName *string `locationName:"distributionName" type:"string"` +} - // The name of the master database created when the Lightsail database resource - // is created. - // - // Constraints: - // - // * Must contain from 1 to 64 alphanumeric characters. - // - // * Cannot be a word reserved by the specified database engine - // - // MasterDatabaseName is a required field - MasterDatabaseName *string `locationName:"masterDatabaseName" type:"string" required:"true"` +// String returns the string representation +func (s DeleteDistributionInput) String() string { + return awsutil.Prettify(s) +} - // The password for the master user of your new database. The password can include - // any printable ASCII character except "/", """, or "@". - // - // Constraints: Must contain 8 to 41 characters. - MasterUserPassword *string `locationName:"masterUserPassword" type:"string" sensitive:"true"` +// GoString returns the string representation +func (s DeleteDistributionInput) GoString() string { + return s.String() +} - // The master user name for your new database. - // - // Constraints: - // - // * Master user name is required. - // - // * Must contain from 1 to 16 alphanumeric characters. - // - // * The first character must be a letter. - // - // * Cannot be a reserved word for the database engine you choose. For more - // information about reserved words in MySQL 5.6 or 5.7, see the Keywords - // and Reserved Words articles for MySQL 5.6 (https://dev.mysql.com/doc/refman/5.6/en/keywords.html) - // or MySQL 5.7 (https://dev.mysql.com/doc/refman/5.7/en/keywords.html) respectively. - // - // MasterUsername is a required field - MasterUsername *string `locationName:"masterUsername" type:"string" required:"true"` +// SetDistributionName sets the DistributionName field's value. +func (s *DeleteDistributionInput) SetDistributionName(v string) *DeleteDistributionInput { + s.DistributionName = &v + return s +} - // The daily time range during which automated backups are created for your - // new database if automated backups are enabled. - // - // The default is a 30-minute window selected at random from an 8-hour block - // of time for each AWS Region. For more information about the preferred backup - // window time blocks for each region, see the Working With Backups (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithAutomatedBackups.html#USER_WorkingWithAutomatedBackups.BackupWindow) - // guide in the Amazon Relational Database Service (Amazon RDS) documentation. - // - // Constraints: - // - // * Must be in the hh24:mi-hh24:mi format. Example: 16:00-16:30 - // - // * Specified in Coordinated Universal Time (UTC). - // - // * Must not conflict with the preferred maintenance window. - // - // * Must be at least 30 minutes. - PreferredBackupWindow *string `locationName:"preferredBackupWindow" type:"string"` +type DeleteDistributionOutput struct { + _ struct{} `type:"structure"` - // The weekly time range during which system maintenance can occur on your new - // database. - // - // The default is a 30-minute window selected at random from an 8-hour block - // of time for each AWS Region, occurring on a random day of the week. - // - // Constraints: - // - // * Must be in the ddd:hh24:mi-ddd:hh24:mi format. - // - // * Valid days: Mon, Tue, Wed, Thu, Fri, Sat, Sun. - // - // * Must be at least 30 minutes. - // - // * Specified in Coordinated Universal Time (UTC). - // - // * Example: Tue:17:00-Tue:17:30 - PreferredMaintenanceWindow *string `locationName:"preferredMaintenanceWindow" type:"string"` + // An object that describes the result of the action, such as the status of + // the request, the timestamp of the request, and the resources affected by + // the request. + Operation *Operation `locationName:"operation" type:"structure"` +} - // Specifies the accessibility options for your new database. A value of true - // specifies a database that is available to resources outside of your Lightsail - // account. A value of false specifies a database that is available only to - // your Lightsail resources in the same region as your database. - PubliclyAccessible *bool `locationName:"publiclyAccessible" type:"boolean"` +// String returns the string representation +func (s DeleteDistributionOutput) String() string { + return awsutil.Prettify(s) +} - // The blueprint ID for your new database. A blueprint describes the major engine - // version of a database. - // - // You can get a list of database blueprints IDs by using the get relational - // database blueprints operation. - // - // RelationalDatabaseBlueprintId is a required field - RelationalDatabaseBlueprintId *string `locationName:"relationalDatabaseBlueprintId" type:"string" required:"true"` +// GoString returns the string representation +func (s DeleteDistributionOutput) GoString() string { + return s.String() +} + +// SetOperation sets the Operation field's value. +func (s *DeleteDistributionOutput) SetOperation(v *Operation) *DeleteDistributionOutput { + s.Operation = v + return s +} - // The bundle ID for your new database. A bundle describes the performance specifications - // for your database. - // - // You can get a list of database bundle IDs by using the get relational database - // bundles operation. - // - // RelationalDatabaseBundleId is a required field - RelationalDatabaseBundleId *string `locationName:"relationalDatabaseBundleId" type:"string" required:"true"` +type DeleteDomainEntryInput struct { + _ struct{} `type:"structure"` - // The name to use for your new database. - // - // Constraints: - // - // * Must contain from 2 to 255 alphanumeric characters, or hyphens. - // - // * The first and last character must be a letter or number. + // An array of key-value pairs containing information about your domain entries. // - // RelationalDatabaseName is a required field - RelationalDatabaseName *string `locationName:"relationalDatabaseName" type:"string" required:"true"` + // DomainEntry is a required field + DomainEntry *DomainEntry `locationName:"domainEntry" type:"structure" required:"true"` - // The tag keys and optional values to add to the resource during create. + // The name of the domain entry to delete. // - // To tag a resource after it has been created, see the tag resource operation. - Tags []*Tag `locationName:"tags" type:"list"` + // DomainName is a required field + DomainName *string `locationName:"domainName" type:"string" required:"true"` } // String returns the string representation -func (s CreateRelationalDatabaseInput) String() string { +func (s DeleteDomainEntryInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateRelationalDatabaseInput) GoString() string { +func (s DeleteDomainEntryInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateRelationalDatabaseInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateRelationalDatabaseInput"} - if s.MasterDatabaseName == nil { - invalidParams.Add(request.NewErrParamRequired("MasterDatabaseName")) - } - if s.MasterUsername == nil { - invalidParams.Add(request.NewErrParamRequired("MasterUsername")) - } - if s.RelationalDatabaseBlueprintId == nil { - invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseBlueprintId")) - } - if s.RelationalDatabaseBundleId == nil { - invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseBundleId")) +func (s *DeleteDomainEntryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDomainEntryInput"} + if s.DomainEntry == nil { + invalidParams.Add(request.NewErrParamRequired("DomainEntry")) } - if s.RelationalDatabaseName == nil { - invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseName")) + if s.DomainName == nil { + invalidParams.Add(request.NewErrParamRequired("DomainName")) } if invalidParams.Len() > 0 { @@ -15929,140 +19054,134 @@ func (s *CreateRelationalDatabaseInput) Validate() error { return nil } -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateRelationalDatabaseInput) SetAvailabilityZone(v string) *CreateRelationalDatabaseInput { - s.AvailabilityZone = &v +// SetDomainEntry sets the DomainEntry field's value. +func (s *DeleteDomainEntryInput) SetDomainEntry(v *DomainEntry) *DeleteDomainEntryInput { + s.DomainEntry = v return s } -// SetMasterDatabaseName sets the MasterDatabaseName field's value. -func (s *CreateRelationalDatabaseInput) SetMasterDatabaseName(v string) *CreateRelationalDatabaseInput { - s.MasterDatabaseName = &v +// SetDomainName sets the DomainName field's value. +func (s *DeleteDomainEntryInput) SetDomainName(v string) *DeleteDomainEntryInput { + s.DomainName = &v return s } -// SetMasterUserPassword sets the MasterUserPassword field's value. -func (s *CreateRelationalDatabaseInput) SetMasterUserPassword(v string) *CreateRelationalDatabaseInput { - s.MasterUserPassword = &v - return s +type DeleteDomainEntryOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operation *Operation `locationName:"operation" type:"structure"` } -// SetMasterUsername sets the MasterUsername field's value. -func (s *CreateRelationalDatabaseInput) SetMasterUsername(v string) *CreateRelationalDatabaseInput { - s.MasterUsername = &v - return s +// String returns the string representation +func (s DeleteDomainEntryOutput) String() string { + return awsutil.Prettify(s) } -// SetPreferredBackupWindow sets the PreferredBackupWindow field's value. -func (s *CreateRelationalDatabaseInput) SetPreferredBackupWindow(v string) *CreateRelationalDatabaseInput { - s.PreferredBackupWindow = &v - return s +// GoString returns the string representation +func (s DeleteDomainEntryOutput) GoString() string { + return s.String() } -// SetPreferredMaintenanceWindow sets the PreferredMaintenanceWindow field's value. -func (s *CreateRelationalDatabaseInput) SetPreferredMaintenanceWindow(v string) *CreateRelationalDatabaseInput { - s.PreferredMaintenanceWindow = &v +// SetOperation sets the Operation field's value. +func (s *DeleteDomainEntryOutput) SetOperation(v *Operation) *DeleteDomainEntryOutput { + s.Operation = v return s } -// SetPubliclyAccessible sets the PubliclyAccessible field's value. -func (s *CreateRelationalDatabaseInput) SetPubliclyAccessible(v bool) *CreateRelationalDatabaseInput { - s.PubliclyAccessible = &v - return s +type DeleteDomainInput struct { + _ struct{} `type:"structure"` + + // The specific domain name to delete. + // + // DomainName is a required field + DomainName *string `locationName:"domainName" type:"string" required:"true"` } -// SetRelationalDatabaseBlueprintId sets the RelationalDatabaseBlueprintId field's value. -func (s *CreateRelationalDatabaseInput) SetRelationalDatabaseBlueprintId(v string) *CreateRelationalDatabaseInput { - s.RelationalDatabaseBlueprintId = &v - return s +// String returns the string representation +func (s DeleteDomainInput) String() string { + return awsutil.Prettify(s) } -// SetRelationalDatabaseBundleId sets the RelationalDatabaseBundleId field's value. -func (s *CreateRelationalDatabaseInput) SetRelationalDatabaseBundleId(v string) *CreateRelationalDatabaseInput { - s.RelationalDatabaseBundleId = &v - return s +// GoString returns the string representation +func (s DeleteDomainInput) GoString() string { + return s.String() } -// SetRelationalDatabaseName sets the RelationalDatabaseName field's value. -func (s *CreateRelationalDatabaseInput) SetRelationalDatabaseName(v string) *CreateRelationalDatabaseInput { - s.RelationalDatabaseName = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteDomainInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDomainInput"} + if s.DomainName == nil { + invalidParams.Add(request.NewErrParamRequired("DomainName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetTags sets the Tags field's value. -func (s *CreateRelationalDatabaseInput) SetTags(v []*Tag) *CreateRelationalDatabaseInput { - s.Tags = v +// SetDomainName sets the DomainName field's value. +func (s *DeleteDomainInput) SetDomainName(v string) *DeleteDomainInput { + s.DomainName = &v return s } -type CreateRelationalDatabaseOutput struct { +type DeleteDomainOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operations []*Operation `locationName:"operations" type:"list"` + Operation *Operation `locationName:"operation" type:"structure"` } // String returns the string representation -func (s CreateRelationalDatabaseOutput) String() string { +func (s DeleteDomainOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateRelationalDatabaseOutput) GoString() string { +func (s DeleteDomainOutput) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *CreateRelationalDatabaseOutput) SetOperations(v []*Operation) *CreateRelationalDatabaseOutput { - s.Operations = v +// SetOperation sets the Operation field's value. +func (s *DeleteDomainOutput) SetOperation(v *Operation) *DeleteDomainOutput { + s.Operation = v return s } -type CreateRelationalDatabaseSnapshotInput struct { +type DeleteInstanceInput struct { _ struct{} `type:"structure"` - // The name of the database on which to base your new snapshot. - // - // RelationalDatabaseName is a required field - RelationalDatabaseName *string `locationName:"relationalDatabaseName" type:"string" required:"true"` - - // The name for your new database snapshot. - // - // Constraints: - // - // * Must contain from 2 to 255 alphanumeric characters, or hyphens. - // - // * The first and last character must be a letter or number. - // - // RelationalDatabaseSnapshotName is a required field - RelationalDatabaseSnapshotName *string `locationName:"relationalDatabaseSnapshotName" type:"string" required:"true"` + // A Boolean value to indicate whether to delete the enabled add-ons for the + // disk. + ForceDeleteAddOns *bool `locationName:"forceDeleteAddOns" type:"boolean"` - // The tag keys and optional values to add to the resource during create. + // The name of the instance to delete. // - // To tag a resource after it has been created, see the tag resource operation. - Tags []*Tag `locationName:"tags" type:"list"` + // InstanceName is a required field + InstanceName *string `locationName:"instanceName" type:"string" required:"true"` } // String returns the string representation -func (s CreateRelationalDatabaseSnapshotInput) String() string { +func (s DeleteInstanceInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateRelationalDatabaseSnapshotInput) GoString() string { +func (s DeleteInstanceInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateRelationalDatabaseSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateRelationalDatabaseSnapshotInput"} - if s.RelationalDatabaseName == nil { - invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseName")) - } - if s.RelationalDatabaseSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseSnapshotName")) +func (s *DeleteInstanceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteInstanceInput"} + if s.InstanceName == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceName")) } if invalidParams.Len() > 0 { @@ -16071,73 +19190,67 @@ func (s *CreateRelationalDatabaseSnapshotInput) Validate() error { return nil } -// SetRelationalDatabaseName sets the RelationalDatabaseName field's value. -func (s *CreateRelationalDatabaseSnapshotInput) SetRelationalDatabaseName(v string) *CreateRelationalDatabaseSnapshotInput { - s.RelationalDatabaseName = &v - return s -} - -// SetRelationalDatabaseSnapshotName sets the RelationalDatabaseSnapshotName field's value. -func (s *CreateRelationalDatabaseSnapshotInput) SetRelationalDatabaseSnapshotName(v string) *CreateRelationalDatabaseSnapshotInput { - s.RelationalDatabaseSnapshotName = &v +// SetForceDeleteAddOns sets the ForceDeleteAddOns field's value. +func (s *DeleteInstanceInput) SetForceDeleteAddOns(v bool) *DeleteInstanceInput { + s.ForceDeleteAddOns = &v return s } -// SetTags sets the Tags field's value. -func (s *CreateRelationalDatabaseSnapshotInput) SetTags(v []*Tag) *CreateRelationalDatabaseSnapshotInput { - s.Tags = v +// SetInstanceName sets the InstanceName field's value. +func (s *DeleteInstanceInput) SetInstanceName(v string) *DeleteInstanceInput { + s.InstanceName = &v return s } -type CreateRelationalDatabaseSnapshotOutput struct { +type DeleteInstanceOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s CreateRelationalDatabaseSnapshotOutput) String() string { +func (s DeleteInstanceOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateRelationalDatabaseSnapshotOutput) GoString() string { +func (s DeleteInstanceOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *CreateRelationalDatabaseSnapshotOutput) SetOperations(v []*Operation) *CreateRelationalDatabaseSnapshotOutput { +func (s *DeleteInstanceOutput) SetOperations(v []*Operation) *DeleteInstanceOutput { s.Operations = v return s } -type DeleteAlarmInput struct { +type DeleteInstanceSnapshotInput struct { _ struct{} `type:"structure"` - // The name of the alarm to delete. + // The name of the snapshot to delete. // - // AlarmName is a required field - AlarmName *string `locationName:"alarmName" type:"string" required:"true"` + // InstanceSnapshotName is a required field + InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` } // String returns the string representation -func (s DeleteAlarmInput) String() string { +func (s DeleteInstanceSnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteAlarmInput) GoString() string { +func (s DeleteInstanceSnapshotInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteAlarmInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteAlarmInput"} - if s.AlarmName == nil { - invalidParams.Add(request.NewErrParamRequired("AlarmName")) +func (s *DeleteInstanceSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteInstanceSnapshotInput"} + if s.InstanceSnapshotName == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) } if invalidParams.Len() > 0 { @@ -16146,72 +19259,61 @@ func (s *DeleteAlarmInput) Validate() error { return nil } -// SetAlarmName sets the AlarmName field's value. -func (s *DeleteAlarmInput) SetAlarmName(v string) *DeleteAlarmInput { - s.AlarmName = &v +// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. +func (s *DeleteInstanceSnapshotInput) SetInstanceSnapshotName(v string) *DeleteInstanceSnapshotInput { + s.InstanceSnapshotName = &v return s } -type DeleteAlarmOutput struct { +type DeleteInstanceSnapshotOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DeleteAlarmOutput) String() string { +func (s DeleteInstanceSnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteAlarmOutput) GoString() string { +func (s DeleteInstanceSnapshotOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *DeleteAlarmOutput) SetOperations(v []*Operation) *DeleteAlarmOutput { +func (s *DeleteInstanceSnapshotOutput) SetOperations(v []*Operation) *DeleteInstanceSnapshotOutput { s.Operations = v return s } -type DeleteAutoSnapshotInput struct { +type DeleteKeyPairInput struct { _ struct{} `type:"structure"` - // The date of the automatic snapshot to delete in YYYY-MM-DD format. Use the - // get auto snapshots operation to get the available automatic snapshots for - // a resource. - // - // Date is a required field - Date *string `locationName:"date" type:"string" required:"true"` - - // The name of the source instance or disk from which to delete the automatic - // snapshot. + // The name of the key pair to delete. // - // ResourceName is a required field - ResourceName *string `locationName:"resourceName" type:"string" required:"true"` + // KeyPairName is a required field + KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` } // String returns the string representation -func (s DeleteAutoSnapshotInput) String() string { +func (s DeleteKeyPairInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteAutoSnapshotInput) GoString() string { +func (s DeleteKeyPairInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteAutoSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteAutoSnapshotInput"} - if s.Date == nil { - invalidParams.Add(request.NewErrParamRequired("Date")) - } - if s.ResourceName == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceName")) +func (s *DeleteKeyPairInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteKeyPairInput"} + if s.KeyPairName == nil { + invalidParams.Add(request.NewErrParamRequired("KeyPairName")) } if invalidParams.Len() > 0 { @@ -16220,70 +19322,61 @@ func (s *DeleteAutoSnapshotInput) Validate() error { return nil } -// SetDate sets the Date field's value. -func (s *DeleteAutoSnapshotInput) SetDate(v string) *DeleteAutoSnapshotInput { - s.Date = &v - return s -} - -// SetResourceName sets the ResourceName field's value. -func (s *DeleteAutoSnapshotInput) SetResourceName(v string) *DeleteAutoSnapshotInput { - s.ResourceName = &v +// SetKeyPairName sets the KeyPairName field's value. +func (s *DeleteKeyPairInput) SetKeyPairName(v string) *DeleteKeyPairInput { + s.KeyPairName = &v return s } -type DeleteAutoSnapshotOutput struct { +type DeleteKeyPairOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operations []*Operation `locationName:"operations" type:"list"` + Operation *Operation `locationName:"operation" type:"structure"` } // String returns the string representation -func (s DeleteAutoSnapshotOutput) String() string { +func (s DeleteKeyPairOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteAutoSnapshotOutput) GoString() string { +func (s DeleteKeyPairOutput) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *DeleteAutoSnapshotOutput) SetOperations(v []*Operation) *DeleteAutoSnapshotOutput { - s.Operations = v +// SetOperation sets the Operation field's value. +func (s *DeleteKeyPairOutput) SetOperation(v *Operation) *DeleteKeyPairOutput { + s.Operation = v return s } -type DeleteContactMethodInput struct { +type DeleteKnownHostKeysInput struct { _ struct{} `type:"structure"` - // The protocol that will be deleted, such as Email or SMS (text messaging). - // - // To delete an Email and an SMS contact method if you added both, you must - // run separate DeleteContactMethod actions to delete each protocol. + // The name of the instance for which you want to reset the host key or certificate. // - // Protocol is a required field - Protocol *string `locationName:"protocol" type:"string" required:"true" enum:"ContactProtocol"` + // InstanceName is a required field + InstanceName *string `locationName:"instanceName" type:"string" required:"true"` } // String returns the string representation -func (s DeleteContactMethodInput) String() string { +func (s DeleteKnownHostKeysInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteContactMethodInput) GoString() string { +func (s DeleteKnownHostKeysInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteContactMethodInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteContactMethodInput"} - if s.Protocol == nil { - invalidParams.Add(request.NewErrParamRequired("Protocol")) +func (s *DeleteKnownHostKeysInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteKnownHostKeysInput"} + if s.InstanceName == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceName")) } if invalidParams.Len() > 0 { @@ -16292,65 +19385,61 @@ func (s *DeleteContactMethodInput) Validate() error { return nil } -// SetProtocol sets the Protocol field's value. -func (s *DeleteContactMethodInput) SetProtocol(v string) *DeleteContactMethodInput { - s.Protocol = &v +// SetInstanceName sets the InstanceName field's value. +func (s *DeleteKnownHostKeysInput) SetInstanceName(v string) *DeleteKnownHostKeysInput { + s.InstanceName = &v return s } -type DeleteContactMethodOutput struct { +type DeleteKnownHostKeysOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DeleteContactMethodOutput) String() string { +func (s DeleteKnownHostKeysOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteContactMethodOutput) GoString() string { +func (s DeleteKnownHostKeysOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *DeleteContactMethodOutput) SetOperations(v []*Operation) *DeleteContactMethodOutput { +func (s *DeleteKnownHostKeysOutput) SetOperations(v []*Operation) *DeleteKnownHostKeysOutput { s.Operations = v return s } -type DeleteDiskInput struct { +type DeleteLoadBalancerInput struct { _ struct{} `type:"structure"` - // The unique name of the disk you want to delete (e.g., my-disk). + // The name of the load balancer you want to delete. // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` - - // A Boolean value to indicate whether to delete the enabled add-ons for the - // disk. - ForceDeleteAddOns *bool `locationName:"forceDeleteAddOns" type:"boolean"` + // LoadBalancerName is a required field + LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` } // String returns the string representation -func (s DeleteDiskInput) String() string { +func (s DeleteLoadBalancerInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDiskInput) GoString() string { +func (s DeleteLoadBalancerInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) +func (s *DeleteLoadBalancerInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteLoadBalancerInput"} + if s.LoadBalancerName == nil { + invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) } if invalidParams.Len() > 0 { @@ -16359,67 +19448,76 @@ func (s *DeleteDiskInput) Validate() error { return nil } -// SetDiskName sets the DiskName field's value. -func (s *DeleteDiskInput) SetDiskName(v string) *DeleteDiskInput { - s.DiskName = &v - return s -} - -// SetForceDeleteAddOns sets the ForceDeleteAddOns field's value. -func (s *DeleteDiskInput) SetForceDeleteAddOns(v bool) *DeleteDiskInput { - s.ForceDeleteAddOns = &v +// SetLoadBalancerName sets the LoadBalancerName field's value. +func (s *DeleteLoadBalancerInput) SetLoadBalancerName(v string) *DeleteLoadBalancerInput { + s.LoadBalancerName = &v return s } -type DeleteDiskOutput struct { +type DeleteLoadBalancerOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DeleteDiskOutput) String() string { +func (s DeleteLoadBalancerOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDiskOutput) GoString() string { +func (s DeleteLoadBalancerOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *DeleteDiskOutput) SetOperations(v []*Operation) *DeleteDiskOutput { +func (s *DeleteLoadBalancerOutput) SetOperations(v []*Operation) *DeleteLoadBalancerOutput { s.Operations = v return s } -type DeleteDiskSnapshotInput struct { +type DeleteLoadBalancerTlsCertificateInput struct { _ struct{} `type:"structure"` - // The name of the disk snapshot you want to delete (e.g., my-disk-snapshot). + // The SSL/TLS certificate name. // - // DiskSnapshotName is a required field - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` + // CertificateName is a required field + CertificateName *string `locationName:"certificateName" type:"string" required:"true"` + + // When true, forces the deletion of an SSL/TLS certificate. + // + // There can be two certificates associated with a Lightsail load balancer: + // the primary and the backup. The force parameter is required when the primary + // SSL/TLS certificate is in use by an instance attached to the load balancer. + Force *bool `locationName:"force" type:"boolean"` + + // The load balancer name. + // + // LoadBalancerName is a required field + LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` } // String returns the string representation -func (s DeleteDiskSnapshotInput) String() string { +func (s DeleteLoadBalancerTlsCertificateInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDiskSnapshotInput) GoString() string { +func (s DeleteLoadBalancerTlsCertificateInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDiskSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDiskSnapshotInput"} - if s.DiskSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) +func (s *DeleteLoadBalancerTlsCertificateInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteLoadBalancerTlsCertificateInput"} + if s.CertificateName == nil { + invalidParams.Add(request.NewErrParamRequired("CertificateName")) + } + if s.LoadBalancerName == nil { + invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) } if invalidParams.Len() > 0 { @@ -16428,69 +19526,96 @@ func (s *DeleteDiskSnapshotInput) Validate() error { return nil } -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *DeleteDiskSnapshotInput) SetDiskSnapshotName(v string) *DeleteDiskSnapshotInput { - s.DiskSnapshotName = &v +// SetCertificateName sets the CertificateName field's value. +func (s *DeleteLoadBalancerTlsCertificateInput) SetCertificateName(v string) *DeleteLoadBalancerTlsCertificateInput { + s.CertificateName = &v return s } -type DeleteDiskSnapshotOutput struct { +// SetForce sets the Force field's value. +func (s *DeleteLoadBalancerTlsCertificateInput) SetForce(v bool) *DeleteLoadBalancerTlsCertificateInput { + s.Force = &v + return s +} + +// SetLoadBalancerName sets the LoadBalancerName field's value. +func (s *DeleteLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *DeleteLoadBalancerTlsCertificateInput { + s.LoadBalancerName = &v + return s +} + +type DeleteLoadBalancerTlsCertificateOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DeleteDiskSnapshotOutput) String() string { +func (s DeleteLoadBalancerTlsCertificateOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDiskSnapshotOutput) GoString() string { +func (s DeleteLoadBalancerTlsCertificateOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *DeleteDiskSnapshotOutput) SetOperations(v []*Operation) *DeleteDiskSnapshotOutput { +func (s *DeleteLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *DeleteLoadBalancerTlsCertificateOutput { s.Operations = v return s } -type DeleteDomainEntryInput struct { +type DeleteRelationalDatabaseInput struct { _ struct{} `type:"structure"` - // An array of key-value pairs containing information about your domain entries. + // The name of the database snapshot created if skip final snapshot is false, + // which is the default value for that parameter. // - // DomainEntry is a required field - DomainEntry *DomainEntry `locationName:"domainEntry" type:"structure" required:"true"` + // Specifying this parameter and also specifying the skip final snapshot parameter + // to true results in an error. + // + // Constraints: + // + // * Must contain from 2 to 255 alphanumeric characters, or hyphens. + // + // * The first and last character must be a letter or number. + FinalRelationalDatabaseSnapshotName *string `locationName:"finalRelationalDatabaseSnapshotName" type:"string"` - // The name of the domain entry to delete. + // The name of the database that you are deleting. // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` + // RelationalDatabaseName is a required field + RelationalDatabaseName *string `locationName:"relationalDatabaseName" type:"string" required:"true"` + + // Determines whether a final database snapshot is created before your database + // is deleted. If true is specified, no database snapshot is created. If false + // is specified, a database snapshot is created before your database is deleted. + // + // You must specify the final relational database snapshot name parameter if + // the skip final snapshot parameter is false. + // + // Default: false + SkipFinalSnapshot *bool `locationName:"skipFinalSnapshot" type:"boolean"` } // String returns the string representation -func (s DeleteDomainEntryInput) String() string { +func (s DeleteRelationalDatabaseInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDomainEntryInput) GoString() string { +func (s DeleteRelationalDatabaseInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDomainEntryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDomainEntryInput"} - if s.DomainEntry == nil { - invalidParams.Add(request.NewErrParamRequired("DomainEntry")) - } - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) +func (s *DeleteRelationalDatabaseInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteRelationalDatabaseInput"} + if s.RelationalDatabaseName == nil { + invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseName")) } if invalidParams.Len() > 0 { @@ -16499,67 +19624,73 @@ func (s *DeleteDomainEntryInput) Validate() error { return nil } -// SetDomainEntry sets the DomainEntry field's value. -func (s *DeleteDomainEntryInput) SetDomainEntry(v *DomainEntry) *DeleteDomainEntryInput { - s.DomainEntry = v +// SetFinalRelationalDatabaseSnapshotName sets the FinalRelationalDatabaseSnapshotName field's value. +func (s *DeleteRelationalDatabaseInput) SetFinalRelationalDatabaseSnapshotName(v string) *DeleteRelationalDatabaseInput { + s.FinalRelationalDatabaseSnapshotName = &v + return s +} + +// SetRelationalDatabaseName sets the RelationalDatabaseName field's value. +func (s *DeleteRelationalDatabaseInput) SetRelationalDatabaseName(v string) *DeleteRelationalDatabaseInput { + s.RelationalDatabaseName = &v return s } -// SetDomainName sets the DomainName field's value. -func (s *DeleteDomainEntryInput) SetDomainName(v string) *DeleteDomainEntryInput { - s.DomainName = &v +// SetSkipFinalSnapshot sets the SkipFinalSnapshot field's value. +func (s *DeleteRelationalDatabaseInput) SetSkipFinalSnapshot(v bool) *DeleteRelationalDatabaseInput { + s.SkipFinalSnapshot = &v return s } -type DeleteDomainEntryOutput struct { +type DeleteRelationalDatabaseOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operation *Operation `locationName:"operation" type:"structure"` + Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DeleteDomainEntryOutput) String() string { +func (s DeleteRelationalDatabaseOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDomainEntryOutput) GoString() string { +func (s DeleteRelationalDatabaseOutput) GoString() string { return s.String() } -// SetOperation sets the Operation field's value. -func (s *DeleteDomainEntryOutput) SetOperation(v *Operation) *DeleteDomainEntryOutput { - s.Operation = v +// SetOperations sets the Operations field's value. +func (s *DeleteRelationalDatabaseOutput) SetOperations(v []*Operation) *DeleteRelationalDatabaseOutput { + s.Operations = v return s } -type DeleteDomainInput struct { +type DeleteRelationalDatabaseSnapshotInput struct { _ struct{} `type:"structure"` - // The specific domain name to delete. + // The name of the database snapshot that you are deleting. // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` + // RelationalDatabaseSnapshotName is a required field + RelationalDatabaseSnapshotName *string `locationName:"relationalDatabaseSnapshotName" type:"string" required:"true"` } // String returns the string representation -func (s DeleteDomainInput) String() string { +func (s DeleteRelationalDatabaseSnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDomainInput) GoString() string { +func (s DeleteRelationalDatabaseSnapshotInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDomainInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDomainInput"} - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) +func (s *DeleteRelationalDatabaseSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteRelationalDatabaseSnapshotInput"} + if s.RelationalDatabaseSnapshotName == nil { + invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseSnapshotName")) } if invalidParams.Len() > 0 { @@ -16568,65 +19699,97 @@ func (s *DeleteDomainInput) Validate() error { return nil } -// SetDomainName sets the DomainName field's value. -func (s *DeleteDomainInput) SetDomainName(v string) *DeleteDomainInput { - s.DomainName = &v +// SetRelationalDatabaseSnapshotName sets the RelationalDatabaseSnapshotName field's value. +func (s *DeleteRelationalDatabaseSnapshotInput) SetRelationalDatabaseSnapshotName(v string) *DeleteRelationalDatabaseSnapshotInput { + s.RelationalDatabaseSnapshotName = &v return s } -type DeleteDomainOutput struct { +type DeleteRelationalDatabaseSnapshotOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operation *Operation `locationName:"operation" type:"structure"` + Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DeleteDomainOutput) String() string { +func (s DeleteRelationalDatabaseSnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDomainOutput) GoString() string { +func (s DeleteRelationalDatabaseSnapshotOutput) GoString() string { return s.String() } -// SetOperation sets the Operation field's value. -func (s *DeleteDomainOutput) SetOperation(v *Operation) *DeleteDomainOutput { - s.Operation = v +// SetOperations sets the Operations field's value. +func (s *DeleteRelationalDatabaseSnapshotOutput) SetOperations(v []*Operation) *DeleteRelationalDatabaseSnapshotOutput { + s.Operations = v return s } -type DeleteInstanceInput struct { +// Describes the destination of a record. +type DestinationInfo struct { _ struct{} `type:"structure"` - // A Boolean value to indicate whether to delete the enabled add-ons for the - // disk. - ForceDeleteAddOns *bool `locationName:"forceDeleteAddOns" type:"boolean"` + // The ID of the resource created at the destination. + Id *string `locationName:"id" type:"string"` - // The name of the instance to delete. + // The destination service of the record. + Service *string `locationName:"service" type:"string"` +} + +// String returns the string representation +func (s DestinationInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DestinationInfo) GoString() string { + return s.String() +} + +// SetId sets the Id field's value. +func (s *DestinationInfo) SetId(v string) *DestinationInfo { + s.Id = &v + return s +} + +// SetService sets the Service field's value. +func (s *DestinationInfo) SetService(v string) *DestinationInfo { + s.Service = &v + return s +} + +type DetachCertificateFromDistributionInput struct { + _ struct{} `type:"structure"` + + // The name of the distribution from which to detach the certificate. // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` + // Use the GetDistributions action to get a list of distribution names that + // you can specify. + // + // DistributionName is a required field + DistributionName *string `locationName:"distributionName" type:"string" required:"true"` } // String returns the string representation -func (s DeleteInstanceInput) String() string { +func (s DetachCertificateFromDistributionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteInstanceInput) GoString() string { +func (s DetachCertificateFromDistributionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteInstanceInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) +func (s *DetachCertificateFromDistributionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DetachCertificateFromDistributionInput"} + if s.DistributionName == nil { + invalidParams.Add(request.NewErrParamRequired("DistributionName")) } if invalidParams.Len() > 0 { @@ -16635,67 +19798,62 @@ func (s *DeleteInstanceInput) Validate() error { return nil } -// SetForceDeleteAddOns sets the ForceDeleteAddOns field's value. -func (s *DeleteInstanceInput) SetForceDeleteAddOns(v bool) *DeleteInstanceInput { - s.ForceDeleteAddOns = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *DeleteInstanceInput) SetInstanceName(v string) *DeleteInstanceInput { - s.InstanceName = &v +// SetDistributionName sets the DistributionName field's value. +func (s *DetachCertificateFromDistributionInput) SetDistributionName(v string) *DetachCertificateFromDistributionInput { + s.DistributionName = &v return s } -type DeleteInstanceOutput struct { +type DetachCertificateFromDistributionOutput struct { _ struct{} `type:"structure"` - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` + // An object that describes the result of the action, such as the status of + // the request, the timestamp of the request, and the resources affected by + // the request. + Operation *Operation `locationName:"operation" type:"structure"` } // String returns the string representation -func (s DeleteInstanceOutput) String() string { +func (s DetachCertificateFromDistributionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteInstanceOutput) GoString() string { +func (s DetachCertificateFromDistributionOutput) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *DeleteInstanceOutput) SetOperations(v []*Operation) *DeleteInstanceOutput { - s.Operations = v +// SetOperation sets the Operation field's value. +func (s *DetachCertificateFromDistributionOutput) SetOperation(v *Operation) *DetachCertificateFromDistributionOutput { + s.Operation = v return s } -type DeleteInstanceSnapshotInput struct { +type DetachDiskInput struct { _ struct{} `type:"structure"` - // The name of the snapshot to delete. + // The unique name of the disk you want to detach from your instance (e.g., + // my-disk). // - // InstanceSnapshotName is a required field - InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` + // DiskName is a required field + DiskName *string `locationName:"diskName" type:"string" required:"true"` } // String returns the string representation -func (s DeleteInstanceSnapshotInput) String() string { +func (s DetachDiskInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteInstanceSnapshotInput) GoString() string { +func (s DetachDiskInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteInstanceSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteInstanceSnapshotInput"} - if s.InstanceSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) +func (s *DetachDiskInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DetachDiskInput"} + if s.DiskName == nil { + invalidParams.Add(request.NewErrParamRequired("DiskName")) } if invalidParams.Len() > 0 { @@ -16704,61 +19862,70 @@ func (s *DeleteInstanceSnapshotInput) Validate() error { return nil } -// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. -func (s *DeleteInstanceSnapshotInput) SetInstanceSnapshotName(v string) *DeleteInstanceSnapshotInput { - s.InstanceSnapshotName = &v +// SetDiskName sets the DiskName field's value. +func (s *DetachDiskInput) SetDiskName(v string) *DetachDiskInput { + s.DiskName = &v return s } -type DeleteInstanceSnapshotOutput struct { +type DetachDiskOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DeleteInstanceSnapshotOutput) String() string { +func (s DetachDiskOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteInstanceSnapshotOutput) GoString() string { +func (s DetachDiskOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *DeleteInstanceSnapshotOutput) SetOperations(v []*Operation) *DeleteInstanceSnapshotOutput { +func (s *DetachDiskOutput) SetOperations(v []*Operation) *DetachDiskOutput { s.Operations = v return s } -type DeleteKeyPairInput struct { +type DetachInstancesFromLoadBalancerInput struct { _ struct{} `type:"structure"` - // The name of the key pair to delete. + // An array of strings containing the names of the instances you want to detach + // from the load balancer. // - // KeyPairName is a required field - KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` + // InstanceNames is a required field + InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` + + // The name of the Lightsail load balancer. + // + // LoadBalancerName is a required field + LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` } // String returns the string representation -func (s DeleteKeyPairInput) String() string { +func (s DetachInstancesFromLoadBalancerInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteKeyPairInput) GoString() string { +func (s DetachInstancesFromLoadBalancerInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteKeyPairInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteKeyPairInput"} - if s.KeyPairName == nil { - invalidParams.Add(request.NewErrParamRequired("KeyPairName")) +func (s *DetachInstancesFromLoadBalancerInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DetachInstancesFromLoadBalancerInput"} + if s.InstanceNames == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceNames")) + } + if s.LoadBalancerName == nil { + invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) } if invalidParams.Len() > 0 { @@ -16767,61 +19934,67 @@ func (s *DeleteKeyPairInput) Validate() error { return nil } -// SetKeyPairName sets the KeyPairName field's value. -func (s *DeleteKeyPairInput) SetKeyPairName(v string) *DeleteKeyPairInput { - s.KeyPairName = &v +// SetInstanceNames sets the InstanceNames field's value. +func (s *DetachInstancesFromLoadBalancerInput) SetInstanceNames(v []*string) *DetachInstancesFromLoadBalancerInput { + s.InstanceNames = v return s } -type DeleteKeyPairOutput struct { +// SetLoadBalancerName sets the LoadBalancerName field's value. +func (s *DetachInstancesFromLoadBalancerInput) SetLoadBalancerName(v string) *DetachInstancesFromLoadBalancerInput { + s.LoadBalancerName = &v + return s +} + +type DetachInstancesFromLoadBalancerOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operation *Operation `locationName:"operation" type:"structure"` + Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DeleteKeyPairOutput) String() string { +func (s DetachInstancesFromLoadBalancerOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteKeyPairOutput) GoString() string { +func (s DetachInstancesFromLoadBalancerOutput) GoString() string { return s.String() } -// SetOperation sets the Operation field's value. -func (s *DeleteKeyPairOutput) SetOperation(v *Operation) *DeleteKeyPairOutput { - s.Operation = v +// SetOperations sets the Operations field's value. +func (s *DetachInstancesFromLoadBalancerOutput) SetOperations(v []*Operation) *DetachInstancesFromLoadBalancerOutput { + s.Operations = v return s } -type DeleteKnownHostKeysInput struct { +type DetachStaticIpInput struct { _ struct{} `type:"structure"` - // The name of the instance for which you want to reset the host key or certificate. + // The name of the static IP to detach from the instance. // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` + // StaticIpName is a required field + StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` } // String returns the string representation -func (s DeleteKnownHostKeysInput) String() string { +func (s DetachStaticIpInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteKnownHostKeysInput) GoString() string { +func (s DetachStaticIpInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteKnownHostKeysInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteKnownHostKeysInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) +func (s *DetachStaticIpInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DetachStaticIpInput"} + if s.StaticIpName == nil { + invalidParams.Add(request.NewErrParamRequired("StaticIpName")) } if invalidParams.Len() > 0 { @@ -16830,61 +20003,69 @@ func (s *DeleteKnownHostKeysInput) Validate() error { return nil } -// SetInstanceName sets the InstanceName field's value. -func (s *DeleteKnownHostKeysInput) SetInstanceName(v string) *DeleteKnownHostKeysInput { - s.InstanceName = &v +// SetStaticIpName sets the StaticIpName field's value. +func (s *DetachStaticIpInput) SetStaticIpName(v string) *DetachStaticIpInput { + s.StaticIpName = &v return s } -type DeleteKnownHostKeysOutput struct { +type DetachStaticIpOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DeleteKnownHostKeysOutput) String() string { +func (s DetachStaticIpOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteKnownHostKeysOutput) GoString() string { +func (s DetachStaticIpOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *DeleteKnownHostKeysOutput) SetOperations(v []*Operation) *DeleteKnownHostKeysOutput { +func (s *DetachStaticIpOutput) SetOperations(v []*Operation) *DetachStaticIpOutput { s.Operations = v return s } -type DeleteLoadBalancerInput struct { +type DisableAddOnInput struct { _ struct{} `type:"structure"` - // The name of the load balancer you want to delete. + // The add-on type to disable. + // + // AddOnType is a required field + AddOnType *string `locationName:"addOnType" type:"string" required:"true" enum:"AddOnType"` + + // The name of the source resource for which to disable the add-on. // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` + // ResourceName is a required field + ResourceName *string `locationName:"resourceName" type:"string" required:"true"` } // String returns the string representation -func (s DeleteLoadBalancerInput) String() string { +func (s DisableAddOnInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteLoadBalancerInput) GoString() string { +func (s DisableAddOnInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteLoadBalancerInput"} - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) +func (s *DisableAddOnInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DisableAddOnInput"} + if s.AddOnType == nil { + invalidParams.Add(request.NewErrParamRequired("AddOnType")) + } + if s.ResourceName == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceName")) } if invalidParams.Len() > 0 { @@ -16893,1325 +20074,1319 @@ func (s *DeleteLoadBalancerInput) Validate() error { return nil } -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *DeleteLoadBalancerInput) SetLoadBalancerName(v string) *DeleteLoadBalancerInput { - s.LoadBalancerName = &v +// SetAddOnType sets the AddOnType field's value. +func (s *DisableAddOnInput) SetAddOnType(v string) *DisableAddOnInput { + s.AddOnType = &v return s } -type DeleteLoadBalancerOutput struct { +// SetResourceName sets the ResourceName field's value. +func (s *DisableAddOnInput) SetResourceName(v string) *DisableAddOnInput { + s.ResourceName = &v + return s +} + +type DisableAddOnOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DeleteLoadBalancerOutput) String() string { +func (s DisableAddOnOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteLoadBalancerOutput) GoString() string { +func (s DisableAddOnOutput) GoString() string { return s.String() } // SetOperations sets the Operations field's value. -func (s *DeleteLoadBalancerOutput) SetOperations(v []*Operation) *DeleteLoadBalancerOutput { +func (s *DisableAddOnOutput) SetOperations(v []*Operation) *DisableAddOnOutput { s.Operations = v return s } -type DeleteLoadBalancerTlsCertificateInput struct { +// Describes a system disk or a block storage disk. +type Disk struct { _ struct{} `type:"structure"` - // The SSL/TLS certificate name. - // - // CertificateName is a required field - CertificateName *string `locationName:"certificateName" type:"string" required:"true"` + // An array of objects representing the add-ons enabled on the disk. + AddOns []*AddOn `locationName:"addOns" type:"list"` - // When true, forces the deletion of an SSL/TLS certificate. + // The Amazon Resource Name (ARN) of the disk. + Arn *string `locationName:"arn" type:"string"` + + // The resources to which the disk is attached. + AttachedTo *string `locationName:"attachedTo" type:"string"` + + // (Deprecated) The attachment state of the disk. // - // There can be two certificates associated with a Lightsail load balancer: - // the primary and the backup. The force parameter is required when the primary - // SSL/TLS certificate is in use by an instance attached to the load balancer. - Force *bool `locationName:"force" type:"boolean"` + // In releases prior to November 14, 2017, this parameter returned attached + // for system disks in the API response. It is now deprecated, but still included + // in the response. Use isAttached instead. + // + // Deprecated: AttachmentState has been deprecated + AttachmentState *string `locationName:"attachmentState" deprecated:"true" type:"string"` - // The load balancer name. + // The date when the disk was created. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + + // (Deprecated) The number of GB in use by the disk. // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` + // In releases prior to November 14, 2017, this parameter was not included in + // the API response. It is now deprecated. + // + // Deprecated: GbInUse has been deprecated + GbInUse *int64 `locationName:"gbInUse" deprecated:"true" type:"integer"` + + // The input/output operations per second (IOPS) of the disk. + Iops *int64 `locationName:"iops" type:"integer"` + + // A Boolean value indicating whether the disk is attached. + IsAttached *bool `locationName:"isAttached" type:"boolean"` + + // A Boolean value indicating whether this disk is a system disk (has an operating + // system loaded on it). + IsSystemDisk *bool `locationName:"isSystemDisk" type:"boolean"` + + // The AWS Region and Availability Zone where the disk is located. + Location *ResourceLocation `locationName:"location" type:"structure"` + + // The unique name of the disk. + Name *string `locationName:"name" type:"string"` + + // The disk path. + Path *string `locationName:"path" type:"string"` + + // The Lightsail resource type (e.g., Disk). + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + + // The size of the disk in GB. + SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` + + // Describes the status of the disk. + State *string `locationName:"state" type:"string" enum:"DiskState"` + + // The support code. Include this code in your email to support when you have + // questions about an instance or another resource in Lightsail. This code enables + // our support team to look up your Lightsail information more easily. + SupportCode *string `locationName:"supportCode" type:"string"` + + // The tag keys and optional values for the resource. For more information about + // tags in Lightsail, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags). + Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s DeleteLoadBalancerTlsCertificateInput) String() string { +func (s Disk) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteLoadBalancerTlsCertificateInput) GoString() string { +func (s Disk) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteLoadBalancerTlsCertificateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteLoadBalancerTlsCertificateInput"} - if s.CertificateName == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateName")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } +// SetAddOns sets the AddOns field's value. +func (s *Disk) SetAddOns(v []*AddOn) *Disk { + s.AddOns = v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetArn sets the Arn field's value. +func (s *Disk) SetArn(v string) *Disk { + s.Arn = &v + return s } -// SetCertificateName sets the CertificateName field's value. -func (s *DeleteLoadBalancerTlsCertificateInput) SetCertificateName(v string) *DeleteLoadBalancerTlsCertificateInput { - s.CertificateName = &v +// SetAttachedTo sets the AttachedTo field's value. +func (s *Disk) SetAttachedTo(v string) *Disk { + s.AttachedTo = &v return s } -// SetForce sets the Force field's value. -func (s *DeleteLoadBalancerTlsCertificateInput) SetForce(v bool) *DeleteLoadBalancerTlsCertificateInput { - s.Force = &v +// SetAttachmentState sets the AttachmentState field's value. +func (s *Disk) SetAttachmentState(v string) *Disk { + s.AttachmentState = &v return s } -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *DeleteLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *DeleteLoadBalancerTlsCertificateInput { - s.LoadBalancerName = &v +// SetCreatedAt sets the CreatedAt field's value. +func (s *Disk) SetCreatedAt(v time.Time) *Disk { + s.CreatedAt = &v return s } -type DeleteLoadBalancerTlsCertificateOutput struct { - _ struct{} `type:"structure"` +// SetGbInUse sets the GbInUse field's value. +func (s *Disk) SetGbInUse(v int64) *Disk { + s.GbInUse = &v + return s +} - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` +// SetIops sets the Iops field's value. +func (s *Disk) SetIops(v int64) *Disk { + s.Iops = &v + return s } -// String returns the string representation -func (s DeleteLoadBalancerTlsCertificateOutput) String() string { - return awsutil.Prettify(s) +// SetIsAttached sets the IsAttached field's value. +func (s *Disk) SetIsAttached(v bool) *Disk { + s.IsAttached = &v + return s } -// GoString returns the string representation -func (s DeleteLoadBalancerTlsCertificateOutput) GoString() string { - return s.String() +// SetIsSystemDisk sets the IsSystemDisk field's value. +func (s *Disk) SetIsSystemDisk(v bool) *Disk { + s.IsSystemDisk = &v + return s } -// SetOperations sets the Operations field's value. -func (s *DeleteLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *DeleteLoadBalancerTlsCertificateOutput { - s.Operations = v +// SetLocation sets the Location field's value. +func (s *Disk) SetLocation(v *ResourceLocation) *Disk { + s.Location = v return s } -type DeleteRelationalDatabaseInput struct { +// SetName sets the Name field's value. +func (s *Disk) SetName(v string) *Disk { + s.Name = &v + return s +} + +// SetPath sets the Path field's value. +func (s *Disk) SetPath(v string) *Disk { + s.Path = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *Disk) SetResourceType(v string) *Disk { + s.ResourceType = &v + return s +} + +// SetSizeInGb sets the SizeInGb field's value. +func (s *Disk) SetSizeInGb(v int64) *Disk { + s.SizeInGb = &v + return s +} + +// SetState sets the State field's value. +func (s *Disk) SetState(v string) *Disk { + s.State = &v + return s +} + +// SetSupportCode sets the SupportCode field's value. +func (s *Disk) SetSupportCode(v string) *Disk { + s.SupportCode = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *Disk) SetTags(v []*Tag) *Disk { + s.Tags = v + return s +} + +// Describes a disk. +type DiskInfo struct { _ struct{} `type:"structure"` - // The name of the database snapshot created if skip final snapshot is false, - // which is the default value for that parameter. - // - // Specifying this parameter and also specifying the skip final snapshot parameter - // to true results in an error. - // - // Constraints: - // - // * Must contain from 2 to 255 alphanumeric characters, or hyphens. - // - // * The first and last character must be a letter or number. - FinalRelationalDatabaseSnapshotName *string `locationName:"finalRelationalDatabaseSnapshotName" type:"string"` + // A Boolean value indicating whether this disk is a system disk (has an operating + // system loaded on it). + IsSystemDisk *bool `locationName:"isSystemDisk" type:"boolean"` - // The name of the database that you are deleting. - // - // RelationalDatabaseName is a required field - RelationalDatabaseName *string `locationName:"relationalDatabaseName" type:"string" required:"true"` + // The disk name. + Name *string `locationName:"name" type:"string"` - // Determines whether a final database snapshot is created before your database - // is deleted. If true is specified, no database snapshot is created. If false - // is specified, a database snapshot is created before your database is deleted. - // - // You must specify the final relational database snapshot name parameter if - // the skip final snapshot parameter is false. - // - // Default: false - SkipFinalSnapshot *bool `locationName:"skipFinalSnapshot" type:"boolean"` + // The disk path. + Path *string `locationName:"path" type:"string"` + + // The size of the disk in GB (e.g., 32). + SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` } // String returns the string representation -func (s DeleteRelationalDatabaseInput) String() string { +func (s DiskInfo) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteRelationalDatabaseInput) GoString() string { +func (s DiskInfo) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteRelationalDatabaseInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteRelationalDatabaseInput"} - if s.RelationalDatabaseName == nil { - invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetIsSystemDisk sets the IsSystemDisk field's value. +func (s *DiskInfo) SetIsSystemDisk(v bool) *DiskInfo { + s.IsSystemDisk = &v + return s } -// SetFinalRelationalDatabaseSnapshotName sets the FinalRelationalDatabaseSnapshotName field's value. -func (s *DeleteRelationalDatabaseInput) SetFinalRelationalDatabaseSnapshotName(v string) *DeleteRelationalDatabaseInput { - s.FinalRelationalDatabaseSnapshotName = &v +// SetName sets the Name field's value. +func (s *DiskInfo) SetName(v string) *DiskInfo { + s.Name = &v return s } -// SetRelationalDatabaseName sets the RelationalDatabaseName field's value. -func (s *DeleteRelationalDatabaseInput) SetRelationalDatabaseName(v string) *DeleteRelationalDatabaseInput { - s.RelationalDatabaseName = &v +// SetPath sets the Path field's value. +func (s *DiskInfo) SetPath(v string) *DiskInfo { + s.Path = &v return s } -// SetSkipFinalSnapshot sets the SkipFinalSnapshot field's value. -func (s *DeleteRelationalDatabaseInput) SetSkipFinalSnapshot(v bool) *DeleteRelationalDatabaseInput { - s.SkipFinalSnapshot = &v +// SetSizeInGb sets the SizeInGb field's value. +func (s *DiskInfo) SetSizeInGb(v int64) *DiskInfo { + s.SizeInGb = &v return s } -type DeleteRelationalDatabaseOutput struct { +// Describes a block storage disk mapping. +type DiskMap struct { _ struct{} `type:"structure"` - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` + // The new disk name (e.g., my-new-disk). + NewDiskName *string `locationName:"newDiskName" type:"string"` + + // The original disk path exposed to the instance (for example, /dev/sdh). + OriginalDiskPath *string `locationName:"originalDiskPath" type:"string"` } // String returns the string representation -func (s DeleteRelationalDatabaseOutput) String() string { +func (s DiskMap) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteRelationalDatabaseOutput) GoString() string { +func (s DiskMap) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *DeleteRelationalDatabaseOutput) SetOperations(v []*Operation) *DeleteRelationalDatabaseOutput { - s.Operations = v +// SetNewDiskName sets the NewDiskName field's value. +func (s *DiskMap) SetNewDiskName(v string) *DiskMap { + s.NewDiskName = &v return s } -type DeleteRelationalDatabaseSnapshotInput struct { +// SetOriginalDiskPath sets the OriginalDiskPath field's value. +func (s *DiskMap) SetOriginalDiskPath(v string) *DiskMap { + s.OriginalDiskPath = &v + return s +} + +// Describes a block storage disk snapshot. +type DiskSnapshot struct { _ struct{} `type:"structure"` - // The name of the database snapshot that you are deleting. - // - // RelationalDatabaseSnapshotName is a required field - RelationalDatabaseSnapshotName *string `locationName:"relationalDatabaseSnapshotName" type:"string" required:"true"` + // The Amazon Resource Name (ARN) of the disk snapshot. + Arn *string `locationName:"arn" type:"string"` + + // The date when the disk snapshot was created. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + + // The Amazon Resource Name (ARN) of the source disk from which the disk snapshot + // was created. + FromDiskArn *string `locationName:"fromDiskArn" type:"string"` + + // The unique name of the source disk from which the disk snapshot was created. + FromDiskName *string `locationName:"fromDiskName" type:"string"` + + // The Amazon Resource Name (ARN) of the source instance from which the disk + // (system volume) snapshot was created. + FromInstanceArn *string `locationName:"fromInstanceArn" type:"string"` + + // The unique name of the source instance from which the disk (system volume) + // snapshot was created. + FromInstanceName *string `locationName:"fromInstanceName" type:"string"` + + // A Boolean value indicating whether the snapshot was created from an automatic + // snapshot. + IsFromAutoSnapshot *bool `locationName:"isFromAutoSnapshot" type:"boolean"` + + // The AWS Region and Availability Zone where the disk snapshot was created. + Location *ResourceLocation `locationName:"location" type:"structure"` + + // The name of the disk snapshot (e.g., my-disk-snapshot). + Name *string `locationName:"name" type:"string"` + + // The progress of the disk snapshot operation. + Progress *string `locationName:"progress" type:"string"` + + // The Lightsail resource type (e.g., DiskSnapshot). + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + + // The size of the disk in GB. + SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` + + // The status of the disk snapshot operation. + State *string `locationName:"state" type:"string" enum:"DiskSnapshotState"` + + // The support code. Include this code in your email to support when you have + // questions about an instance or another resource in Lightsail. This code enables + // our support team to look up your Lightsail information more easily. + SupportCode *string `locationName:"supportCode" type:"string"` + + // The tag keys and optional values for the resource. For more information about + // tags in Lightsail, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags). + Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s DeleteRelationalDatabaseSnapshotInput) String() string { +func (s DiskSnapshot) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteRelationalDatabaseSnapshotInput) GoString() string { +func (s DiskSnapshot) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteRelationalDatabaseSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteRelationalDatabaseSnapshotInput"} - if s.RelationalDatabaseSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("RelationalDatabaseSnapshotName")) - } +// SetArn sets the Arn field's value. +func (s *DiskSnapshot) SetArn(v string) *DiskSnapshot { + s.Arn = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCreatedAt sets the CreatedAt field's value. +func (s *DiskSnapshot) SetCreatedAt(v time.Time) *DiskSnapshot { + s.CreatedAt = &v + return s } -// SetRelationalDatabaseSnapshotName sets the RelationalDatabaseSnapshotName field's value. -func (s *DeleteRelationalDatabaseSnapshotInput) SetRelationalDatabaseSnapshotName(v string) *DeleteRelationalDatabaseSnapshotInput { - s.RelationalDatabaseSnapshotName = &v +// SetFromDiskArn sets the FromDiskArn field's value. +func (s *DiskSnapshot) SetFromDiskArn(v string) *DiskSnapshot { + s.FromDiskArn = &v return s } -type DeleteRelationalDatabaseSnapshotOutput struct { - _ struct{} `type:"structure"` +// SetFromDiskName sets the FromDiskName field's value. +func (s *DiskSnapshot) SetFromDiskName(v string) *DiskSnapshot { + s.FromDiskName = &v + return s +} - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` +// SetFromInstanceArn sets the FromInstanceArn field's value. +func (s *DiskSnapshot) SetFromInstanceArn(v string) *DiskSnapshot { + s.FromInstanceArn = &v + return s } -// String returns the string representation -func (s DeleteRelationalDatabaseSnapshotOutput) String() string { - return awsutil.Prettify(s) +// SetFromInstanceName sets the FromInstanceName field's value. +func (s *DiskSnapshot) SetFromInstanceName(v string) *DiskSnapshot { + s.FromInstanceName = &v + return s } -// GoString returns the string representation -func (s DeleteRelationalDatabaseSnapshotOutput) GoString() string { - return s.String() +// SetIsFromAutoSnapshot sets the IsFromAutoSnapshot field's value. +func (s *DiskSnapshot) SetIsFromAutoSnapshot(v bool) *DiskSnapshot { + s.IsFromAutoSnapshot = &v + return s } -// SetOperations sets the Operations field's value. -func (s *DeleteRelationalDatabaseSnapshotOutput) SetOperations(v []*Operation) *DeleteRelationalDatabaseSnapshotOutput { - s.Operations = v +// SetLocation sets the Location field's value. +func (s *DiskSnapshot) SetLocation(v *ResourceLocation) *DiskSnapshot { + s.Location = v return s } -// Describes the destination of a record. -type DestinationInfo struct { - _ struct{} `type:"structure"` +// SetName sets the Name field's value. +func (s *DiskSnapshot) SetName(v string) *DiskSnapshot { + s.Name = &v + return s +} - // The ID of the resource created at the destination. - Id *string `locationName:"id" type:"string"` +// SetProgress sets the Progress field's value. +func (s *DiskSnapshot) SetProgress(v string) *DiskSnapshot { + s.Progress = &v + return s +} - // The destination service of the record. - Service *string `locationName:"service" type:"string"` +// SetResourceType sets the ResourceType field's value. +func (s *DiskSnapshot) SetResourceType(v string) *DiskSnapshot { + s.ResourceType = &v + return s } -// String returns the string representation -func (s DestinationInfo) String() string { - return awsutil.Prettify(s) +// SetSizeInGb sets the SizeInGb field's value. +func (s *DiskSnapshot) SetSizeInGb(v int64) *DiskSnapshot { + s.SizeInGb = &v + return s } -// GoString returns the string representation -func (s DestinationInfo) GoString() string { - return s.String() +// SetState sets the State field's value. +func (s *DiskSnapshot) SetState(v string) *DiskSnapshot { + s.State = &v + return s } -// SetId sets the Id field's value. -func (s *DestinationInfo) SetId(v string) *DestinationInfo { - s.Id = &v +// SetSupportCode sets the SupportCode field's value. +func (s *DiskSnapshot) SetSupportCode(v string) *DiskSnapshot { + s.SupportCode = &v return s } -// SetService sets the Service field's value. -func (s *DestinationInfo) SetService(v string) *DestinationInfo { - s.Service = &v +// SetTags sets the Tags field's value. +func (s *DiskSnapshot) SetTags(v []*Tag) *DiskSnapshot { + s.Tags = v return s } -type DetachDiskInput struct { +// Describes a disk snapshot. +type DiskSnapshotInfo struct { _ struct{} `type:"structure"` - // The unique name of the disk you want to detach from your instance (e.g., - // my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` + // The size of the disk in GB (e.g., 32). + SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` } // String returns the string representation -func (s DetachDiskInput) String() string { +func (s DiskSnapshotInfo) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DetachDiskInput) GoString() string { +func (s DiskSnapshotInfo) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DetachDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DetachDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *DetachDiskInput) SetDiskName(v string) *DetachDiskInput { - s.DiskName = &v +// SetSizeInGb sets the SizeInGb field's value. +func (s *DiskSnapshotInfo) SetSizeInGb(v int64) *DiskSnapshotInfo { + s.SizeInGb = &v return s } -type DetachDiskOutput struct { +// Describes the specifications of a distribution bundle. +type DistributionBundle struct { _ struct{} `type:"structure"` - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` + // The ID of the bundle. + BundleId *string `locationName:"bundleId" type:"string"` + + // Indicates whether the bundle is active, and can be specified for a new distribution. + IsActive *bool `locationName:"isActive" type:"boolean"` + + // The name of the distribution bundle. + Name *string `locationName:"name" type:"string"` + + // The monthly price, in US dollars, of the bundle. + Price *float64 `locationName:"price" type:"float"` + + // The monthly network transfer quota of the bundle. + TransferPerMonthInGb *int64 `locationName:"transferPerMonthInGb" type:"integer"` } // String returns the string representation -func (s DetachDiskOutput) String() string { +func (s DistributionBundle) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DetachDiskOutput) GoString() string { +func (s DistributionBundle) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *DetachDiskOutput) SetOperations(v []*Operation) *DetachDiskOutput { - s.Operations = v +// SetBundleId sets the BundleId field's value. +func (s *DistributionBundle) SetBundleId(v string) *DistributionBundle { + s.BundleId = &v return s } -type DetachInstancesFromLoadBalancerInput struct { +// SetIsActive sets the IsActive field's value. +func (s *DistributionBundle) SetIsActive(v bool) *DistributionBundle { + s.IsActive = &v + return s +} + +// SetName sets the Name field's value. +func (s *DistributionBundle) SetName(v string) *DistributionBundle { + s.Name = &v + return s +} + +// SetPrice sets the Price field's value. +func (s *DistributionBundle) SetPrice(v float64) *DistributionBundle { + s.Price = &v + return s +} + +// SetTransferPerMonthInGb sets the TransferPerMonthInGb field's value. +func (s *DistributionBundle) SetTransferPerMonthInGb(v int64) *DistributionBundle { + s.TransferPerMonthInGb = &v + return s +} + +// Describes a domain where you are storing recordsets in Lightsail. +type Domain struct { _ struct{} `type:"structure"` - // An array of strings containing the names of the instances you want to detach - // from the load balancer. - // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` + // The Amazon Resource Name (ARN) of the domain recordset (e.g., arn:aws:lightsail:global:123456789101:Domain/824cede0-abc7-4f84-8dbc-12345EXAMPLE). + Arn *string `locationName:"arn" type:"string"` - // The name of the Lightsail load balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` + // The date when the domain recordset was created. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + + // An array of key-value pairs containing information about the domain entries. + DomainEntries []*DomainEntry `locationName:"domainEntries" type:"list"` + + // The AWS Region and Availability Zones where the domain recordset was created. + Location *ResourceLocation `locationName:"location" type:"structure"` + + // The name of the domain. + Name *string `locationName:"name" type:"string"` + + // The resource type. + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + + // The support code. Include this code in your email to support when you have + // questions about an instance or another resource in Lightsail. This code enables + // our support team to look up your Lightsail information more easily. + SupportCode *string `locationName:"supportCode" type:"string"` + + // The tag keys and optional values for the resource. For more information about + // tags in Lightsail, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags). + Tags []*Tag `locationName:"tags" type:"list"` } // String returns the string representation -func (s DetachInstancesFromLoadBalancerInput) String() string { +func (s Domain) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DetachInstancesFromLoadBalancerInput) GoString() string { +func (s Domain) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DetachInstancesFromLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DetachInstancesFromLoadBalancerInput"} - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetArn sets the Arn field's value. +func (s *Domain) SetArn(v string) *Domain { + s.Arn = &v + return s } -// SetInstanceNames sets the InstanceNames field's value. -func (s *DetachInstancesFromLoadBalancerInput) SetInstanceNames(v []*string) *DetachInstancesFromLoadBalancerInput { - s.InstanceNames = v +// SetCreatedAt sets the CreatedAt field's value. +func (s *Domain) SetCreatedAt(v time.Time) *Domain { + s.CreatedAt = &v return s } -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *DetachInstancesFromLoadBalancerInput) SetLoadBalancerName(v string) *DetachInstancesFromLoadBalancerInput { - s.LoadBalancerName = &v +// SetDomainEntries sets the DomainEntries field's value. +func (s *Domain) SetDomainEntries(v []*DomainEntry) *Domain { + s.DomainEntries = v return s } -type DetachInstancesFromLoadBalancerOutput struct { - _ struct{} `type:"structure"` +// SetLocation sets the Location field's value. +func (s *Domain) SetLocation(v *ResourceLocation) *Domain { + s.Location = v + return s +} - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` +// SetName sets the Name field's value. +func (s *Domain) SetName(v string) *Domain { + s.Name = &v + return s } -// String returns the string representation -func (s DetachInstancesFromLoadBalancerOutput) String() string { - return awsutil.Prettify(s) +// SetResourceType sets the ResourceType field's value. +func (s *Domain) SetResourceType(v string) *Domain { + s.ResourceType = &v + return s } -// GoString returns the string representation -func (s DetachInstancesFromLoadBalancerOutput) GoString() string { - return s.String() +// SetSupportCode sets the SupportCode field's value. +func (s *Domain) SetSupportCode(v string) *Domain { + s.SupportCode = &v + return s } -// SetOperations sets the Operations field's value. -func (s *DetachInstancesFromLoadBalancerOutput) SetOperations(v []*Operation) *DetachInstancesFromLoadBalancerOutput { - s.Operations = v +// SetTags sets the Tags field's value. +func (s *Domain) SetTags(v []*Tag) *Domain { + s.Tags = v return s } -type DetachStaticIpInput struct { +// Describes a domain recordset entry. +type DomainEntry struct { _ struct{} `type:"structure"` - // The name of the static IP to detach from the instance. + // The ID of the domain recordset entry. + Id *string `locationName:"id" type:"string"` + + // When true, specifies whether the domain entry is an alias used by the Lightsail + // load balancer. You can include an alias (A type) record in your request, + // which points to a load balancer DNS name and routes traffic to your load + // balancer + IsAlias *bool `locationName:"isAlias" type:"boolean"` + + // The name of the domain. + Name *string `locationName:"name" type:"string"` + + // (Deprecated) The options for the domain entry. // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` + // In releases prior to November 29, 2017, this parameter was not included in + // the API response. It is now deprecated. + // + // Deprecated: Options has been deprecated + Options map[string]*string `locationName:"options" deprecated:"true" type:"map"` + + // The target AWS name server (e.g., ns-111.awsdns-22.com.). + // + // For Lightsail load balancers, the value looks like ab1234c56789c6b86aba6fb203d443bc-123456789.us-east-2.elb.amazonaws.com. + // Be sure to also set isAlias to true when setting up an A record for a load + // balancer. + Target *string `locationName:"target" type:"string"` + + // The type of domain entry, such as address (A), canonical name (CNAME), mail + // exchanger (MX), name server (NS), start of authority (SOA), service locator + // (SRV), or text (TXT). + // + // The following domain entry types can be used: + // + // * A + // + // * CNAME + // + // * MX + // + // * NS + // + // * SOA + // + // * SRV + // + // * TXT + Type *string `locationName:"type" type:"string"` } // String returns the string representation -func (s DetachStaticIpInput) String() string { +func (s DomainEntry) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DetachStaticIpInput) GoString() string { +func (s DomainEntry) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DetachStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DetachStaticIpInput"} - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetStaticIpName sets the StaticIpName field's value. -func (s *DetachStaticIpInput) SetStaticIpName(v string) *DetachStaticIpInput { - s.StaticIpName = &v +// SetId sets the Id field's value. +func (s *DomainEntry) SetId(v string) *DomainEntry { + s.Id = &v return s } -type DetachStaticIpOutput struct { - _ struct{} `type:"structure"` +// SetIsAlias sets the IsAlias field's value. +func (s *DomainEntry) SetIsAlias(v bool) *DomainEntry { + s.IsAlias = &v + return s +} - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` +// SetName sets the Name field's value. +func (s *DomainEntry) SetName(v string) *DomainEntry { + s.Name = &v + return s } -// String returns the string representation -func (s DetachStaticIpOutput) String() string { - return awsutil.Prettify(s) +// SetOptions sets the Options field's value. +func (s *DomainEntry) SetOptions(v map[string]*string) *DomainEntry { + s.Options = v + return s } -// GoString returns the string representation -func (s DetachStaticIpOutput) GoString() string { - return s.String() +// SetTarget sets the Target field's value. +func (s *DomainEntry) SetTarget(v string) *DomainEntry { + s.Target = &v + return s } -// SetOperations sets the Operations field's value. -func (s *DetachStaticIpOutput) SetOperations(v []*Operation) *DetachStaticIpOutput { - s.Operations = v +// SetType sets the Type field's value. +func (s *DomainEntry) SetType(v string) *DomainEntry { + s.Type = &v return s } -type DisableAddOnInput struct { +// Describes the domain validation records of an Amazon Lightsail SSL/TLS certificate. +type DomainValidationRecord struct { _ struct{} `type:"structure"` - // The add-on type to disable. - // - // AddOnType is a required field - AddOnType *string `locationName:"addOnType" type:"string" required:"true" enum:"AddOnType"` + // The domain name of the certificate validation record. For example, example.com + // or www.example.com. + DomainName *string `locationName:"domainName" type:"string"` - // The name of the source resource for which to disable the add-on. - // - // ResourceName is a required field - ResourceName *string `locationName:"resourceName" type:"string" required:"true"` + // An object that describes the DNS records to add to your domain's DNS to validate + // it for the certificate. + ResourceRecord *ResourceRecord `locationName:"resourceRecord" type:"structure"` } // String returns the string representation -func (s DisableAddOnInput) String() string { +func (s DomainValidationRecord) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DisableAddOnInput) GoString() string { +func (s DomainValidationRecord) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DisableAddOnInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DisableAddOnInput"} - if s.AddOnType == nil { - invalidParams.Add(request.NewErrParamRequired("AddOnType")) - } - if s.ResourceName == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAddOnType sets the AddOnType field's value. -func (s *DisableAddOnInput) SetAddOnType(v string) *DisableAddOnInput { - s.AddOnType = &v +// SetDomainName sets the DomainName field's value. +func (s *DomainValidationRecord) SetDomainName(v string) *DomainValidationRecord { + s.DomainName = &v return s } -// SetResourceName sets the ResourceName field's value. -func (s *DisableAddOnInput) SetResourceName(v string) *DisableAddOnInput { - s.ResourceName = &v +// SetResourceRecord sets the ResourceRecord field's value. +func (s *DomainValidationRecord) SetResourceRecord(v *ResourceRecord) *DomainValidationRecord { + s.ResourceRecord = v return s } -type DisableAddOnOutput struct { +type DownloadDefaultKeyPairInput struct { _ struct{} `type:"structure"` - - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DisableAddOnOutput) String() string { +func (s DownloadDefaultKeyPairInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DisableAddOnOutput) GoString() string { +func (s DownloadDefaultKeyPairInput) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *DisableAddOnOutput) SetOperations(v []*Operation) *DisableAddOnOutput { - s.Operations = v - return s -} - -// Describes a system disk or a block storage disk. -type Disk struct { +type DownloadDefaultKeyPairOutput struct { _ struct{} `type:"structure"` - // An array of objects representing the add-ons enabled on the disk. - AddOns []*AddOn `locationName:"addOns" type:"list"` - - // The Amazon Resource Name (ARN) of the disk. - Arn *string `locationName:"arn" type:"string"` - - // The resources to which the disk is attached. - AttachedTo *string `locationName:"attachedTo" type:"string"` - - // (Deprecated) The attachment state of the disk. - // - // In releases prior to November 14, 2017, this parameter returned attached - // for system disks in the API response. It is now deprecated, but still included - // in the response. Use isAttached instead. - // - // Deprecated: AttachmentState has been deprecated - AttachmentState *string `locationName:"attachmentState" deprecated:"true" type:"string"` - - // The date when the disk was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // (Deprecated) The number of GB in use by the disk. - // - // In releases prior to November 14, 2017, this parameter was not included in - // the API response. It is now deprecated. - // - // Deprecated: GbInUse has been deprecated - GbInUse *int64 `locationName:"gbInUse" deprecated:"true" type:"integer"` - - // The input/output operations per second (IOPS) of the disk. - Iops *int64 `locationName:"iops" type:"integer"` - - // A Boolean value indicating whether the disk is attached. - IsAttached *bool `locationName:"isAttached" type:"boolean"` - - // A Boolean value indicating whether this disk is a system disk (has an operating - // system loaded on it). - IsSystemDisk *bool `locationName:"isSystemDisk" type:"boolean"` - - // The AWS Region and Availability Zone where the disk is located. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The unique name of the disk. - Name *string `locationName:"name" type:"string"` - - // The disk path. - Path *string `locationName:"path" type:"string"` - - // The Lightsail resource type (e.g., Disk). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The size of the disk in GB. - SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` - - // Describes the status of the disk. - State *string `locationName:"state" type:"string" enum:"DiskState"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` + // A base64-encoded RSA private key. + PrivateKeyBase64 *string `locationName:"privateKeyBase64" type:"string"` - // The tag keys and optional values for the resource. For more information about - // tags in Lightsail, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags). - Tags []*Tag `locationName:"tags" type:"list"` + // A base64-encoded public key of the ssh-rsa type. + PublicKeyBase64 *string `locationName:"publicKeyBase64" type:"string"` } // String returns the string representation -func (s Disk) String() string { +func (s DownloadDefaultKeyPairOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Disk) GoString() string { +func (s DownloadDefaultKeyPairOutput) GoString() string { return s.String() } -// SetAddOns sets the AddOns field's value. -func (s *Disk) SetAddOns(v []*AddOn) *Disk { - s.AddOns = v - return s -} - -// SetArn sets the Arn field's value. -func (s *Disk) SetArn(v string) *Disk { - s.Arn = &v - return s -} - -// SetAttachedTo sets the AttachedTo field's value. -func (s *Disk) SetAttachedTo(v string) *Disk { - s.AttachedTo = &v - return s -} - -// SetAttachmentState sets the AttachmentState field's value. -func (s *Disk) SetAttachmentState(v string) *Disk { - s.AttachmentState = &v +// SetPrivateKeyBase64 sets the PrivateKeyBase64 field's value. +func (s *DownloadDefaultKeyPairOutput) SetPrivateKeyBase64(v string) *DownloadDefaultKeyPairOutput { + s.PrivateKeyBase64 = &v return s } -// SetCreatedAt sets the CreatedAt field's value. -func (s *Disk) SetCreatedAt(v time.Time) *Disk { - s.CreatedAt = &v +// SetPublicKeyBase64 sets the PublicKeyBase64 field's value. +func (s *DownloadDefaultKeyPairOutput) SetPublicKeyBase64(v string) *DownloadDefaultKeyPairOutput { + s.PublicKeyBase64 = &v return s } -// SetGbInUse sets the GbInUse field's value. -func (s *Disk) SetGbInUse(v int64) *Disk { - s.GbInUse = &v - return s -} +type EnableAddOnInput struct { + _ struct{} `type:"structure"` -// SetIops sets the Iops field's value. -func (s *Disk) SetIops(v int64) *Disk { - s.Iops = &v - return s -} + // An array of strings representing the add-on to enable or modify. + // + // AddOnRequest is a required field + AddOnRequest *AddOnRequest `locationName:"addOnRequest" type:"structure" required:"true"` -// SetIsAttached sets the IsAttached field's value. -func (s *Disk) SetIsAttached(v bool) *Disk { - s.IsAttached = &v - return s + // The name of the source resource for which to enable or modify the add-on. + // + // ResourceName is a required field + ResourceName *string `locationName:"resourceName" type:"string" required:"true"` } -// SetIsSystemDisk sets the IsSystemDisk field's value. -func (s *Disk) SetIsSystemDisk(v bool) *Disk { - s.IsSystemDisk = &v - return s +// String returns the string representation +func (s EnableAddOnInput) String() string { + return awsutil.Prettify(s) } -// SetLocation sets the Location field's value. -func (s *Disk) SetLocation(v *ResourceLocation) *Disk { - s.Location = v - return s +// GoString returns the string representation +func (s EnableAddOnInput) GoString() string { + return s.String() } -// SetName sets the Name field's value. -func (s *Disk) SetName(v string) *Disk { - s.Name = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *EnableAddOnInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "EnableAddOnInput"} + if s.AddOnRequest == nil { + invalidParams.Add(request.NewErrParamRequired("AddOnRequest")) + } + if s.ResourceName == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceName")) + } + if s.AddOnRequest != nil { + if err := s.AddOnRequest.Validate(); err != nil { + invalidParams.AddNested("AddOnRequest", err.(request.ErrInvalidParams)) + } + } -// SetPath sets the Path field's value. -func (s *Disk) SetPath(v string) *Disk { - s.Path = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetResourceType sets the ResourceType field's value. -func (s *Disk) SetResourceType(v string) *Disk { - s.ResourceType = &v +// SetAddOnRequest sets the AddOnRequest field's value. +func (s *EnableAddOnInput) SetAddOnRequest(v *AddOnRequest) *EnableAddOnInput { + s.AddOnRequest = v return s } -// SetSizeInGb sets the SizeInGb field's value. -func (s *Disk) SetSizeInGb(v int64) *Disk { - s.SizeInGb = &v +// SetResourceName sets the ResourceName field's value. +func (s *EnableAddOnInput) SetResourceName(v string) *EnableAddOnInput { + s.ResourceName = &v return s } -// SetState sets the State field's value. -func (s *Disk) SetState(v string) *Disk { - s.State = &v - return s +type EnableAddOnOutput struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` } -// SetSupportCode sets the SupportCode field's value. -func (s *Disk) SetSupportCode(v string) *Disk { - s.SupportCode = &v - return s +// String returns the string representation +func (s EnableAddOnOutput) String() string { + return awsutil.Prettify(s) } -// SetTags sets the Tags field's value. -func (s *Disk) SetTags(v []*Tag) *Disk { - s.Tags = v +// GoString returns the string representation +func (s EnableAddOnOutput) GoString() string { + return s.String() +} + +// SetOperations sets the Operations field's value. +func (s *EnableAddOnOutput) SetOperations(v []*Operation) *EnableAddOnOutput { + s.Operations = v return s } -// Describes a disk. -type DiskInfo struct { +type ExportSnapshotInput struct { _ struct{} `type:"structure"` - // A Boolean value indicating whether this disk is a system disk (has an operating - // system loaded on it). - IsSystemDisk *bool `locationName:"isSystemDisk" type:"boolean"` - - // The disk name. - Name *string `locationName:"name" type:"string"` - - // The disk path. - Path *string `locationName:"path" type:"string"` - - // The size of the disk in GB (e.g., 32). - SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` + // The name of the instance or disk snapshot to be exported to Amazon EC2. + // + // SourceSnapshotName is a required field + SourceSnapshotName *string `locationName:"sourceSnapshotName" type:"string" required:"true"` } // String returns the string representation -func (s DiskInfo) String() string { +func (s ExportSnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DiskInfo) GoString() string { +func (s ExportSnapshotInput) GoString() string { return s.String() } -// SetIsSystemDisk sets the IsSystemDisk field's value. -func (s *DiskInfo) SetIsSystemDisk(v bool) *DiskInfo { - s.IsSystemDisk = &v - return s -} - -// SetName sets the Name field's value. -func (s *DiskInfo) SetName(v string) *DiskInfo { - s.Name = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *ExportSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ExportSnapshotInput"} + if s.SourceSnapshotName == nil { + invalidParams.Add(request.NewErrParamRequired("SourceSnapshotName")) + } -// SetPath sets the Path field's value. -func (s *DiskInfo) SetPath(v string) *DiskInfo { - s.Path = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetSizeInGb sets the SizeInGb field's value. -func (s *DiskInfo) SetSizeInGb(v int64) *DiskInfo { - s.SizeInGb = &v +// SetSourceSnapshotName sets the SourceSnapshotName field's value. +func (s *ExportSnapshotInput) SetSourceSnapshotName(v string) *ExportSnapshotInput { + s.SourceSnapshotName = &v return s } -// Describes a block storage disk mapping. -type DiskMap struct { +type ExportSnapshotOutput struct { _ struct{} `type:"structure"` - // The new disk name (e.g., my-new-disk). - NewDiskName *string `locationName:"newDiskName" type:"string"` - - // The original disk path exposed to the instance (for example, /dev/sdh). - OriginalDiskPath *string `locationName:"originalDiskPath" type:"string"` + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` } // String returns the string representation -func (s DiskMap) String() string { +func (s ExportSnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DiskMap) GoString() string { +func (s ExportSnapshotOutput) GoString() string { return s.String() } -// SetNewDiskName sets the NewDiskName field's value. -func (s *DiskMap) SetNewDiskName(v string) *DiskMap { - s.NewDiskName = &v - return s -} - -// SetOriginalDiskPath sets the OriginalDiskPath field's value. -func (s *DiskMap) SetOriginalDiskPath(v string) *DiskMap { - s.OriginalDiskPath = &v +// SetOperations sets the Operations field's value. +func (s *ExportSnapshotOutput) SetOperations(v []*Operation) *ExportSnapshotOutput { + s.Operations = v return s } -// Describes a block storage disk snapshot. -type DiskSnapshot struct { +// Describes an export snapshot record. +type ExportSnapshotRecord struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the disk snapshot. + // The Amazon Resource Name (ARN) of the export snapshot record. Arn *string `locationName:"arn" type:"string"` - // The date when the disk snapshot was created. + // The date when the export snapshot record was created. CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - // The Amazon Resource Name (ARN) of the source disk from which the disk snapshot - // was created. - FromDiskArn *string `locationName:"fromDiskArn" type:"string"` - - // The unique name of the source disk from which the disk snapshot was created. - FromDiskName *string `locationName:"fromDiskName" type:"string"` - - // The Amazon Resource Name (ARN) of the source instance from which the disk - // (system volume) snapshot was created. - FromInstanceArn *string `locationName:"fromInstanceArn" type:"string"` - - // The unique name of the source instance from which the disk (system volume) - // snapshot was created. - FromInstanceName *string `locationName:"fromInstanceName" type:"string"` - - // A Boolean value indicating whether the snapshot was created from an automatic - // snapshot. - IsFromAutoSnapshot *bool `locationName:"isFromAutoSnapshot" type:"boolean"` + // A list of objects describing the destination of the export snapshot record. + DestinationInfo *DestinationInfo `locationName:"destinationInfo" type:"structure"` - // The AWS Region and Availability Zone where the disk snapshot was created. + // The AWS Region and Availability Zone where the export snapshot record is + // located. Location *ResourceLocation `locationName:"location" type:"structure"` - // The name of the disk snapshot (e.g., my-disk-snapshot). + // The export snapshot record name. Name *string `locationName:"name" type:"string"` - // The progress of the disk snapshot operation. - Progress *string `locationName:"progress" type:"string"` - - // The Lightsail resource type (e.g., DiskSnapshot). + // The Lightsail resource type (e.g., ExportSnapshotRecord). ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - // The size of the disk in GB. - SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` - - // The status of the disk snapshot operation. - State *string `locationName:"state" type:"string" enum:"DiskSnapshotState"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` + // A list of objects describing the source of the export snapshot record. + SourceInfo *ExportSnapshotRecordSourceInfo `locationName:"sourceInfo" type:"structure"` - // The tag keys and optional values for the resource. For more information about - // tags in Lightsail, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags). - Tags []*Tag `locationName:"tags" type:"list"` + // The state of the export snapshot record. + State *string `locationName:"state" type:"string" enum:"RecordState"` } // String returns the string representation -func (s DiskSnapshot) String() string { +func (s ExportSnapshotRecord) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DiskSnapshot) GoString() string { +func (s ExportSnapshotRecord) GoString() string { return s.String() } // SetArn sets the Arn field's value. -func (s *DiskSnapshot) SetArn(v string) *DiskSnapshot { +func (s *ExportSnapshotRecord) SetArn(v string) *ExportSnapshotRecord { s.Arn = &v return s } // SetCreatedAt sets the CreatedAt field's value. -func (s *DiskSnapshot) SetCreatedAt(v time.Time) *DiskSnapshot { +func (s *ExportSnapshotRecord) SetCreatedAt(v time.Time) *ExportSnapshotRecord { s.CreatedAt = &v return s } -// SetFromDiskArn sets the FromDiskArn field's value. -func (s *DiskSnapshot) SetFromDiskArn(v string) *DiskSnapshot { - s.FromDiskArn = &v - return s -} - -// SetFromDiskName sets the FromDiskName field's value. -func (s *DiskSnapshot) SetFromDiskName(v string) *DiskSnapshot { - s.FromDiskName = &v - return s -} - -// SetFromInstanceArn sets the FromInstanceArn field's value. -func (s *DiskSnapshot) SetFromInstanceArn(v string) *DiskSnapshot { - s.FromInstanceArn = &v - return s -} - -// SetFromInstanceName sets the FromInstanceName field's value. -func (s *DiskSnapshot) SetFromInstanceName(v string) *DiskSnapshot { - s.FromInstanceName = &v - return s -} - -// SetIsFromAutoSnapshot sets the IsFromAutoSnapshot field's value. -func (s *DiskSnapshot) SetIsFromAutoSnapshot(v bool) *DiskSnapshot { - s.IsFromAutoSnapshot = &v +// SetDestinationInfo sets the DestinationInfo field's value. +func (s *ExportSnapshotRecord) SetDestinationInfo(v *DestinationInfo) *ExportSnapshotRecord { + s.DestinationInfo = v return s } // SetLocation sets the Location field's value. -func (s *DiskSnapshot) SetLocation(v *ResourceLocation) *DiskSnapshot { +func (s *ExportSnapshotRecord) SetLocation(v *ResourceLocation) *ExportSnapshotRecord { s.Location = v return s } -// SetName sets the Name field's value. -func (s *DiskSnapshot) SetName(v string) *DiskSnapshot { - s.Name = &v - return s -} - -// SetProgress sets the Progress field's value. -func (s *DiskSnapshot) SetProgress(v string) *DiskSnapshot { - s.Progress = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *DiskSnapshot) SetResourceType(v string) *DiskSnapshot { - s.ResourceType = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *DiskSnapshot) SetSizeInGb(v int64) *DiskSnapshot { - s.SizeInGb = &v - return s -} - -// SetState sets the State field's value. -func (s *DiskSnapshot) SetState(v string) *DiskSnapshot { - s.State = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *DiskSnapshot) SetSupportCode(v string) *DiskSnapshot { - s.SupportCode = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *DiskSnapshot) SetTags(v []*Tag) *DiskSnapshot { - s.Tags = v - return s -} - -// Describes a disk snapshot. -type DiskSnapshotInfo struct { - _ struct{} `type:"structure"` - - // The size of the disk in GB (e.g., 32). - SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` +// SetName sets the Name field's value. +func (s *ExportSnapshotRecord) SetName(v string) *ExportSnapshotRecord { + s.Name = &v + return s } -// String returns the string representation -func (s DiskSnapshotInfo) String() string { - return awsutil.Prettify(s) +// SetResourceType sets the ResourceType field's value. +func (s *ExportSnapshotRecord) SetResourceType(v string) *ExportSnapshotRecord { + s.ResourceType = &v + return s } -// GoString returns the string representation -func (s DiskSnapshotInfo) GoString() string { - return s.String() +// SetSourceInfo sets the SourceInfo field's value. +func (s *ExportSnapshotRecord) SetSourceInfo(v *ExportSnapshotRecordSourceInfo) *ExportSnapshotRecord { + s.SourceInfo = v + return s } -// SetSizeInGb sets the SizeInGb field's value. -func (s *DiskSnapshotInfo) SetSizeInGb(v int64) *DiskSnapshotInfo { - s.SizeInGb = &v +// SetState sets the State field's value. +func (s *ExportSnapshotRecord) SetState(v string) *ExportSnapshotRecord { + s.State = &v return s } -// Describes a domain where you are storing recordsets in Lightsail. -type Domain struct { +// Describes the source of an export snapshot record. +type ExportSnapshotRecordSourceInfo struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the domain recordset (e.g., arn:aws:lightsail:global:123456789101:Domain/824cede0-abc7-4f84-8dbc-12345EXAMPLE). + // The Amazon Resource Name (ARN) of the source instance or disk snapshot. Arn *string `locationName:"arn" type:"string"` - // The date when the domain recordset was created. + // The date when the source instance or disk snapshot was created. CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - // An array of key-value pairs containing information about the domain entries. - DomainEntries []*DomainEntry `locationName:"domainEntries" type:"list"` + // A list of objects describing a disk snapshot. + DiskSnapshotInfo *DiskSnapshotInfo `locationName:"diskSnapshotInfo" type:"structure"` - // The AWS Region and Availability Zones where the domain recordset was created. - Location *ResourceLocation `locationName:"location" type:"structure"` + // The Amazon Resource Name (ARN) of the snapshot's source instance or disk. + FromResourceArn *string `locationName:"fromResourceArn" type:"string"` - // The name of the domain. - Name *string `locationName:"name" type:"string"` + // The name of the snapshot's source instance or disk. + FromResourceName *string `locationName:"fromResourceName" type:"string"` - // The resource type. - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + // A list of objects describing an instance snapshot. + InstanceSnapshotInfo *InstanceSnapshotInfo `locationName:"instanceSnapshotInfo" type:"structure"` - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` + // The name of the source instance or disk snapshot. + Name *string `locationName:"name" type:"string"` - // The tag keys and optional values for the resource. For more information about - // tags in Lightsail, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags). - Tags []*Tag `locationName:"tags" type:"list"` + // The Lightsail resource type (e.g., InstanceSnapshot or DiskSnapshot). + ResourceType *string `locationName:"resourceType" type:"string" enum:"ExportSnapshotRecordSourceType"` } // String returns the string representation -func (s Domain) String() string { +func (s ExportSnapshotRecordSourceInfo) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Domain) GoString() string { +func (s ExportSnapshotRecordSourceInfo) GoString() string { return s.String() } // SetArn sets the Arn field's value. -func (s *Domain) SetArn(v string) *Domain { +func (s *ExportSnapshotRecordSourceInfo) SetArn(v string) *ExportSnapshotRecordSourceInfo { s.Arn = &v return s } // SetCreatedAt sets the CreatedAt field's value. -func (s *Domain) SetCreatedAt(v time.Time) *Domain { +func (s *ExportSnapshotRecordSourceInfo) SetCreatedAt(v time.Time) *ExportSnapshotRecordSourceInfo { s.CreatedAt = &v return s } -// SetDomainEntries sets the DomainEntries field's value. -func (s *Domain) SetDomainEntries(v []*DomainEntry) *Domain { - s.DomainEntries = v +// SetDiskSnapshotInfo sets the DiskSnapshotInfo field's value. +func (s *ExportSnapshotRecordSourceInfo) SetDiskSnapshotInfo(v *DiskSnapshotInfo) *ExportSnapshotRecordSourceInfo { + s.DiskSnapshotInfo = v return s } -// SetLocation sets the Location field's value. -func (s *Domain) SetLocation(v *ResourceLocation) *Domain { - s.Location = v +// SetFromResourceArn sets the FromResourceArn field's value. +func (s *ExportSnapshotRecordSourceInfo) SetFromResourceArn(v string) *ExportSnapshotRecordSourceInfo { + s.FromResourceArn = &v return s } -// SetName sets the Name field's value. -func (s *Domain) SetName(v string) *Domain { - s.Name = &v +// SetFromResourceName sets the FromResourceName field's value. +func (s *ExportSnapshotRecordSourceInfo) SetFromResourceName(v string) *ExportSnapshotRecordSourceInfo { + s.FromResourceName = &v return s } -// SetResourceType sets the ResourceType field's value. -func (s *Domain) SetResourceType(v string) *Domain { - s.ResourceType = &v +// SetInstanceSnapshotInfo sets the InstanceSnapshotInfo field's value. +func (s *ExportSnapshotRecordSourceInfo) SetInstanceSnapshotInfo(v *InstanceSnapshotInfo) *ExportSnapshotRecordSourceInfo { + s.InstanceSnapshotInfo = v return s } -// SetSupportCode sets the SupportCode field's value. -func (s *Domain) SetSupportCode(v string) *Domain { - s.SupportCode = &v +// SetName sets the Name field's value. +func (s *ExportSnapshotRecordSourceInfo) SetName(v string) *ExportSnapshotRecordSourceInfo { + s.Name = &v return s } -// SetTags sets the Tags field's value. -func (s *Domain) SetTags(v []*Tag) *Domain { - s.Tags = v +// SetResourceType sets the ResourceType field's value. +func (s *ExportSnapshotRecordSourceInfo) SetResourceType(v string) *ExportSnapshotRecordSourceInfo { + s.ResourceType = &v return s } -// Describes a domain recordset entry. -type DomainEntry struct { +type GetActiveNamesInput struct { _ struct{} `type:"structure"` - // The ID of the domain recordset entry. - Id *string `locationName:"id" type:"string"` - - // When true, specifies whether the domain entry is an alias used by the Lightsail - // load balancer. You can include an alias (A type) record in your request, - // which points to a load balancer DNS name and routes traffic to your load - // balancer - IsAlias *bool `locationName:"isAlias" type:"boolean"` - - // The name of the domain. - Name *string `locationName:"name" type:"string"` - - // (Deprecated) The options for the domain entry. - // - // In releases prior to November 29, 2017, this parameter was not included in - // the API response. It is now deprecated. - // - // Deprecated: Options has been deprecated - Options map[string]*string `locationName:"options" deprecated:"true" type:"map"` - - // The target AWS name server (e.g., ns-111.awsdns-22.com.). - // - // For Lightsail load balancers, the value looks like ab1234c56789c6b86aba6fb203d443bc-123456789.us-east-2.elb.amazonaws.com. - // Be sure to also set isAlias to true when setting up an A record for a load - // balancer. - Target *string `locationName:"target" type:"string"` - - // The type of domain entry, such as address (A), canonical name (CNAME), mail - // exchanger (MX), name server (NS), start of authority (SOA), service locator - // (SRV), or text (TXT). - // - // The following domain entry types can be used: - // - // * A - // - // * CNAME - // - // * MX - // - // * NS - // - // * SOA - // - // * SRV + // The token to advance to the next page of results from your request. // - // * TXT - Type *string `locationName:"type" type:"string"` + // To get a page token, perform an initial GetActiveNames request. If your results + // are paginated, the response will return a next page token that you can specify + // as the page token in a subsequent request. + PageToken *string `locationName:"pageToken" type:"string"` } // String returns the string representation -func (s DomainEntry) String() string { +func (s GetActiveNamesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DomainEntry) GoString() string { +func (s GetActiveNamesInput) GoString() string { return s.String() } -// SetId sets the Id field's value. -func (s *DomainEntry) SetId(v string) *DomainEntry { - s.Id = &v +// SetPageToken sets the PageToken field's value. +func (s *GetActiveNamesInput) SetPageToken(v string) *GetActiveNamesInput { + s.PageToken = &v return s } -// SetIsAlias sets the IsAlias field's value. -func (s *DomainEntry) SetIsAlias(v bool) *DomainEntry { - s.IsAlias = &v - return s +type GetActiveNamesOutput struct { + _ struct{} `type:"structure"` + + // The list of active names returned by the get active names request. + ActiveNames []*string `locationName:"activeNames" type:"list"` + + // The token to advance to the next page of resutls from your request. + // + // A next page token is not returned if there are no more results to display. + // + // To get the next page of results, perform another GetActiveNames request and + // specify the next page token using the pageToken parameter. + NextPageToken *string `locationName:"nextPageToken" type:"string"` } -// SetName sets the Name field's value. -func (s *DomainEntry) SetName(v string) *DomainEntry { - s.Name = &v - return s +// String returns the string representation +func (s GetActiveNamesOutput) String() string { + return awsutil.Prettify(s) } -// SetOptions sets the Options field's value. -func (s *DomainEntry) SetOptions(v map[string]*string) *DomainEntry { - s.Options = v - return s +// GoString returns the string representation +func (s GetActiveNamesOutput) GoString() string { + return s.String() } -// SetTarget sets the Target field's value. -func (s *DomainEntry) SetTarget(v string) *DomainEntry { - s.Target = &v +// SetActiveNames sets the ActiveNames field's value. +func (s *GetActiveNamesOutput) SetActiveNames(v []*string) *GetActiveNamesOutput { + s.ActiveNames = v return s } -// SetType sets the Type field's value. -func (s *DomainEntry) SetType(v string) *DomainEntry { - s.Type = &v +// SetNextPageToken sets the NextPageToken field's value. +func (s *GetActiveNamesOutput) SetNextPageToken(v string) *GetActiveNamesOutput { + s.NextPageToken = &v return s } -type DownloadDefaultKeyPairInput struct { +type GetAlarmsInput struct { _ struct{} `type:"structure"` + + // The name of the alarm. + // + // Specify an alarm name to return information about a specific alarm. + AlarmName *string `locationName:"alarmName" type:"string"` + + // The name of the Lightsail resource being monitored by the alarm. + // + // Specify a monitored resource name to return information about all alarms + // for a specific resource. + MonitoredResourceName *string `locationName:"monitoredResourceName" type:"string"` + + // The token to advance to the next page of results from your request. + // + // To get a page token, perform an initial GetAlarms request. If your results + // are paginated, the response will return a next page token that you can specify + // as the page token in a subsequent request. + PageToken *string `locationName:"pageToken" type:"string"` } // String returns the string representation -func (s DownloadDefaultKeyPairInput) String() string { +func (s GetAlarmsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DownloadDefaultKeyPairInput) GoString() string { +func (s GetAlarmsInput) GoString() string { return s.String() } -type DownloadDefaultKeyPairOutput struct { +// SetAlarmName sets the AlarmName field's value. +func (s *GetAlarmsInput) SetAlarmName(v string) *GetAlarmsInput { + s.AlarmName = &v + return s +} + +// SetMonitoredResourceName sets the MonitoredResourceName field's value. +func (s *GetAlarmsInput) SetMonitoredResourceName(v string) *GetAlarmsInput { + s.MonitoredResourceName = &v + return s +} + +// SetPageToken sets the PageToken field's value. +func (s *GetAlarmsInput) SetPageToken(v string) *GetAlarmsInput { + s.PageToken = &v + return s +} + +type GetAlarmsOutput struct { _ struct{} `type:"structure"` - // A base64-encoded RSA private key. - PrivateKeyBase64 *string `locationName:"privateKeyBase64" type:"string"` + // An array of objects that describe the alarms. + Alarms []*Alarm `locationName:"alarms" type:"list"` - // A base64-encoded public key of the ssh-rsa type. - PublicKeyBase64 *string `locationName:"publicKeyBase64" type:"string"` + // The token to advance to the next page of resutls from your request. + // + // A next page token is not returned if there are no more results to display. + // + // To get the next page of results, perform another GetAlarms request and specify + // the next page token using the pageToken parameter. + NextPageToken *string `locationName:"nextPageToken" type:"string"` } // String returns the string representation -func (s DownloadDefaultKeyPairOutput) String() string { +func (s GetAlarmsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DownloadDefaultKeyPairOutput) GoString() string { +func (s GetAlarmsOutput) GoString() string { return s.String() } -// SetPrivateKeyBase64 sets the PrivateKeyBase64 field's value. -func (s *DownloadDefaultKeyPairOutput) SetPrivateKeyBase64(v string) *DownloadDefaultKeyPairOutput { - s.PrivateKeyBase64 = &v +// SetAlarms sets the Alarms field's value. +func (s *GetAlarmsOutput) SetAlarms(v []*Alarm) *GetAlarmsOutput { + s.Alarms = v return s } -// SetPublicKeyBase64 sets the PublicKeyBase64 field's value. -func (s *DownloadDefaultKeyPairOutput) SetPublicKeyBase64(v string) *DownloadDefaultKeyPairOutput { - s.PublicKeyBase64 = &v +// SetNextPageToken sets the NextPageToken field's value. +func (s *GetAlarmsOutput) SetNextPageToken(v string) *GetAlarmsOutput { + s.NextPageToken = &v return s } -type EnableAddOnInput struct { +type GetAutoSnapshotsInput struct { _ struct{} `type:"structure"` - // An array of strings representing the add-on to enable or modify. - // - // AddOnRequest is a required field - AddOnRequest *AddOnRequest `locationName:"addOnRequest" type:"structure" required:"true"` - - // The name of the source resource for which to enable or modify the add-on. + // The name of the source instance or disk from which to get automatic snapshot + // information. // // ResourceName is a required field ResourceName *string `locationName:"resourceName" type:"string" required:"true"` } // String returns the string representation -func (s EnableAddOnInput) String() string { +func (s GetAutoSnapshotsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s EnableAddOnInput) GoString() string { +func (s GetAutoSnapshotsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *EnableAddOnInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "EnableAddOnInput"} - if s.AddOnRequest == nil { - invalidParams.Add(request.NewErrParamRequired("AddOnRequest")) - } +func (s *GetAutoSnapshotsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetAutoSnapshotsInput"} if s.ResourceName == nil { invalidParams.Add(request.NewErrParamRequired("ResourceName")) } - if s.AddOnRequest != nil { - if err := s.AddOnRequest.Validate(); err != nil { - invalidParams.AddNested("AddOnRequest", err.(request.ErrInvalidParams)) - } - } if invalidParams.Len() > 0 { return invalidParams @@ -18219,457 +21394,416 @@ func (s *EnableAddOnInput) Validate() error { return nil } -// SetAddOnRequest sets the AddOnRequest field's value. -func (s *EnableAddOnInput) SetAddOnRequest(v *AddOnRequest) *EnableAddOnInput { - s.AddOnRequest = v - return s -} - // SetResourceName sets the ResourceName field's value. -func (s *EnableAddOnInput) SetResourceName(v string) *EnableAddOnInput { +func (s *GetAutoSnapshotsInput) SetResourceName(v string) *GetAutoSnapshotsInput { s.ResourceName = &v return s } -type EnableAddOnOutput struct { +type GetAutoSnapshotsOutput struct { _ struct{} `type:"structure"` - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` + // An array of objects that describe the automatic snapshots that are available + // for the specified source instance or disk. + AutoSnapshots []*AutoSnapshotDetails `locationName:"autoSnapshots" type:"list"` + + // The name of the source instance or disk for the automatic snapshots. + ResourceName *string `locationName:"resourceName" type:"string"` + + // The resource type (e.g., Instance or Disk). + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` } // String returns the string representation -func (s EnableAddOnOutput) String() string { +func (s GetAutoSnapshotsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s EnableAddOnOutput) GoString() string { +func (s GetAutoSnapshotsOutput) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *EnableAddOnOutput) SetOperations(v []*Operation) *EnableAddOnOutput { - s.Operations = v +// SetAutoSnapshots sets the AutoSnapshots field's value. +func (s *GetAutoSnapshotsOutput) SetAutoSnapshots(v []*AutoSnapshotDetails) *GetAutoSnapshotsOutput { + s.AutoSnapshots = v return s } -type ExportSnapshotInput struct { +// SetResourceName sets the ResourceName field's value. +func (s *GetAutoSnapshotsOutput) SetResourceName(v string) *GetAutoSnapshotsOutput { + s.ResourceName = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *GetAutoSnapshotsOutput) SetResourceType(v string) *GetAutoSnapshotsOutput { + s.ResourceType = &v + return s +} + +type GetBlueprintsInput struct { _ struct{} `type:"structure"` - // The name of the instance or disk snapshot to be exported to Amazon EC2. + // A Boolean value indicating whether to include inactive results in your request. + IncludeInactive *bool `locationName:"includeInactive" type:"boolean"` + + // The token to advance to the next page of results from your request. // - // SourceSnapshotName is a required field - SourceSnapshotName *string `locationName:"sourceSnapshotName" type:"string" required:"true"` + // To get a page token, perform an initial GetBlueprints request. If your results + // are paginated, the response will return a next page token that you can specify + // as the page token in a subsequent request. + PageToken *string `locationName:"pageToken" type:"string"` } // String returns the string representation -func (s ExportSnapshotInput) String() string { +func (s GetBlueprintsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ExportSnapshotInput) GoString() string { +func (s GetBlueprintsInput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ExportSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ExportSnapshotInput"} - if s.SourceSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("SourceSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetIncludeInactive sets the IncludeInactive field's value. +func (s *GetBlueprintsInput) SetIncludeInactive(v bool) *GetBlueprintsInput { + s.IncludeInactive = &v + return s } -// SetSourceSnapshotName sets the SourceSnapshotName field's value. -func (s *ExportSnapshotInput) SetSourceSnapshotName(v string) *ExportSnapshotInput { - s.SourceSnapshotName = &v +// SetPageToken sets the PageToken field's value. +func (s *GetBlueprintsInput) SetPageToken(v string) *GetBlueprintsInput { + s.PageToken = &v return s } -type ExportSnapshotOutput struct { +type GetBlueprintsOutput struct { _ struct{} `type:"structure"` - // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected - // by the request. - Operations []*Operation `locationName:"operations" type:"list"` + // An array of key-value pairs that contains information about the available + // blueprints. + Blueprints []*Blueprint `locationName:"blueprints" type:"list"` + + // The token to advance to the next page of resutls from your request. + // + // A next page token is not returned if there are no more results to display. + // + // To get the next page of results, perform another GetBlueprints request and + // specify the next page token using the pageToken parameter. + NextPageToken *string `locationName:"nextPageToken" type:"string"` } // String returns the string representation -func (s ExportSnapshotOutput) String() string { +func (s GetBlueprintsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ExportSnapshotOutput) GoString() string { +func (s GetBlueprintsOutput) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *ExportSnapshotOutput) SetOperations(v []*Operation) *ExportSnapshotOutput { - s.Operations = v +// SetBlueprints sets the Blueprints field's value. +func (s *GetBlueprintsOutput) SetBlueprints(v []*Blueprint) *GetBlueprintsOutput { + s.Blueprints = v return s } -// Describes an export snapshot record. -type ExportSnapshotRecord struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the export snapshot record. - Arn *string `locationName:"arn" type:"string"` - - // The date when the export snapshot record was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // A list of objects describing the destination of the export snapshot record. - DestinationInfo *DestinationInfo `locationName:"destinationInfo" type:"structure"` - - // The AWS Region and Availability Zone where the export snapshot record is - // located. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The export snapshot record name. - Name *string `locationName:"name" type:"string"` +// SetNextPageToken sets the NextPageToken field's value. +func (s *GetBlueprintsOutput) SetNextPageToken(v string) *GetBlueprintsOutput { + s.NextPageToken = &v + return s +} - // The Lightsail resource type (e.g., ExportSnapshotRecord). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` +type GetBundlesInput struct { + _ struct{} `type:"structure"` - // A list of objects describing the source of the export snapshot record. - SourceInfo *ExportSnapshotRecordSourceInfo `locationName:"sourceInfo" type:"structure"` + // A Boolean value that indicates whether to include inactive bundle results + // in your request. + IncludeInactive *bool `locationName:"includeInactive" type:"boolean"` - // The state of the export snapshot record. - State *string `locationName:"state" type:"string" enum:"RecordState"` + // The token to advance to the next page of results from your request. + // + // To get a page token, perform an initial GetBundles request. If your results + // are paginated, the response will return a next page token that you can specify + // as the page token in a subsequent request. + PageToken *string `locationName:"pageToken" type:"string"` } // String returns the string representation -func (s ExportSnapshotRecord) String() string { +func (s GetBundlesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ExportSnapshotRecord) GoString() string { +func (s GetBundlesInput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *ExportSnapshotRecord) SetArn(v string) *ExportSnapshotRecord { - s.Arn = &v +// SetIncludeInactive sets the IncludeInactive field's value. +func (s *GetBundlesInput) SetIncludeInactive(v bool) *GetBundlesInput { + s.IncludeInactive = &v return s } -// SetCreatedAt sets the CreatedAt field's value. -func (s *ExportSnapshotRecord) SetCreatedAt(v time.Time) *ExportSnapshotRecord { - s.CreatedAt = &v +// SetPageToken sets the PageToken field's value. +func (s *GetBundlesInput) SetPageToken(v string) *GetBundlesInput { + s.PageToken = &v return s } -// SetDestinationInfo sets the DestinationInfo field's value. -func (s *ExportSnapshotRecord) SetDestinationInfo(v *DestinationInfo) *ExportSnapshotRecord { - s.DestinationInfo = v - return s -} +type GetBundlesOutput struct { + _ struct{} `type:"structure"` -// SetLocation sets the Location field's value. -func (s *ExportSnapshotRecord) SetLocation(v *ResourceLocation) *ExportSnapshotRecord { - s.Location = v - return s + // An array of key-value pairs that contains information about the available + // bundles. + Bundles []*Bundle `locationName:"bundles" type:"list"` + + // The token to advance to the next page of resutls from your request. + // + // A next page token is not returned if there are no more results to display. + // + // To get the next page of results, perform another GetBundles request and specify + // the next page token using the pageToken parameter. + NextPageToken *string `locationName:"nextPageToken" type:"string"` } -// SetName sets the Name field's value. -func (s *ExportSnapshotRecord) SetName(v string) *ExportSnapshotRecord { - s.Name = &v - return s +// String returns the string representation +func (s GetBundlesOutput) String() string { + return awsutil.Prettify(s) } -// SetResourceType sets the ResourceType field's value. -func (s *ExportSnapshotRecord) SetResourceType(v string) *ExportSnapshotRecord { - s.ResourceType = &v - return s +// GoString returns the string representation +func (s GetBundlesOutput) GoString() string { + return s.String() } -// SetSourceInfo sets the SourceInfo field's value. -func (s *ExportSnapshotRecord) SetSourceInfo(v *ExportSnapshotRecordSourceInfo) *ExportSnapshotRecord { - s.SourceInfo = v +// SetBundles sets the Bundles field's value. +func (s *GetBundlesOutput) SetBundles(v []*Bundle) *GetBundlesOutput { + s.Bundles = v return s } -// SetState sets the State field's value. -func (s *ExportSnapshotRecord) SetState(v string) *ExportSnapshotRecord { - s.State = &v +// SetNextPageToken sets the NextPageToken field's value. +func (s *GetBundlesOutput) SetNextPageToken(v string) *GetBundlesOutput { + s.NextPageToken = &v return s } -// Describes the source of an export snapshot record. -type ExportSnapshotRecordSourceInfo struct { +type GetCertificatesInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the source instance or disk snapshot. - Arn *string `locationName:"arn" type:"string"` - - // The date when the source instance or disk snapshot was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` - - // A list of objects describing a disk snapshot. - DiskSnapshotInfo *DiskSnapshotInfo `locationName:"diskSnapshotInfo" type:"structure"` - - // The Amazon Resource Name (ARN) of the snapshot's source instance or disk. - FromResourceArn *string `locationName:"fromResourceArn" type:"string"` - - // The name of the snapshot's source instance or disk. - FromResourceName *string `locationName:"fromResourceName" type:"string"` - - // A list of objects describing an instance snapshot. - InstanceSnapshotInfo *InstanceSnapshotInfo `locationName:"instanceSnapshotInfo" type:"structure"` + // The name for the certificate for which to return information. + // + // When omitted, the response includes all of your certificates in the AWS region + // where the request is made. + CertificateName *string `locationName:"certificateName" type:"string"` - // The name of the source instance or disk snapshot. - Name *string `locationName:"name" type:"string"` + // The status of the certificates for which to return information. + // + // For example, specify ISSUED to return only certificates with an ISSUED status. + // + // When omitted, the response includes all of your certificates in the AWS region + // where the request is made, regardless of their current status. + CertificateStatuses []*string `locationName:"certificateStatuses" type:"list"` - // The Lightsail resource type (e.g., InstanceSnapshot or DiskSnapshot). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ExportSnapshotRecordSourceType"` + // Indicates whether to include detailed information about the certificates + // in the response. + // + // When omitted, the response includes only the certificate names, Amazon Resource + // Names (ARNs), domain names, and tags. + IncludeCertificateDetails *bool `locationName:"includeCertificateDetails" type:"boolean"` } // String returns the string representation -func (s ExportSnapshotRecordSourceInfo) String() string { +func (s GetCertificatesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ExportSnapshotRecordSourceInfo) GoString() string { +func (s GetCertificatesInput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *ExportSnapshotRecordSourceInfo) SetArn(v string) *ExportSnapshotRecordSourceInfo { - s.Arn = &v +// SetCertificateName sets the CertificateName field's value. +func (s *GetCertificatesInput) SetCertificateName(v string) *GetCertificatesInput { + s.CertificateName = &v return s } -// SetCreatedAt sets the CreatedAt field's value. -func (s *ExportSnapshotRecordSourceInfo) SetCreatedAt(v time.Time) *ExportSnapshotRecordSourceInfo { - s.CreatedAt = &v +// SetCertificateStatuses sets the CertificateStatuses field's value. +func (s *GetCertificatesInput) SetCertificateStatuses(v []*string) *GetCertificatesInput { + s.CertificateStatuses = v return s } -// SetDiskSnapshotInfo sets the DiskSnapshotInfo field's value. -func (s *ExportSnapshotRecordSourceInfo) SetDiskSnapshotInfo(v *DiskSnapshotInfo) *ExportSnapshotRecordSourceInfo { - s.DiskSnapshotInfo = v +// SetIncludeCertificateDetails sets the IncludeCertificateDetails field's value. +func (s *GetCertificatesInput) SetIncludeCertificateDetails(v bool) *GetCertificatesInput { + s.IncludeCertificateDetails = &v return s } -// SetFromResourceArn sets the FromResourceArn field's value. -func (s *ExportSnapshotRecordSourceInfo) SetFromResourceArn(v string) *ExportSnapshotRecordSourceInfo { - s.FromResourceArn = &v - return s -} +type GetCertificatesOutput struct { + _ struct{} `type:"structure"` -// SetFromResourceName sets the FromResourceName field's value. -func (s *ExportSnapshotRecordSourceInfo) SetFromResourceName(v string) *ExportSnapshotRecordSourceInfo { - s.FromResourceName = &v - return s + // An object that describes certificates. + Certificates []*CertificateSummary `locationName:"certificates" type:"list"` } -// SetInstanceSnapshotInfo sets the InstanceSnapshotInfo field's value. -func (s *ExportSnapshotRecordSourceInfo) SetInstanceSnapshotInfo(v *InstanceSnapshotInfo) *ExportSnapshotRecordSourceInfo { - s.InstanceSnapshotInfo = v - return s +// String returns the string representation +func (s GetCertificatesOutput) String() string { + return awsutil.Prettify(s) } -// SetName sets the Name field's value. -func (s *ExportSnapshotRecordSourceInfo) SetName(v string) *ExportSnapshotRecordSourceInfo { - s.Name = &v - return s +// GoString returns the string representation +func (s GetCertificatesOutput) GoString() string { + return s.String() } -// SetResourceType sets the ResourceType field's value. -func (s *ExportSnapshotRecordSourceInfo) SetResourceType(v string) *ExportSnapshotRecordSourceInfo { - s.ResourceType = &v +// SetCertificates sets the Certificates field's value. +func (s *GetCertificatesOutput) SetCertificates(v []*CertificateSummary) *GetCertificatesOutput { + s.Certificates = v return s } -type GetActiveNamesInput struct { +type GetCloudFormationStackRecordsInput struct { _ struct{} `type:"structure"` // The token to advance to the next page of results from your request. // - // To get a page token, perform an initial GetActiveNames request. If your results - // are paginated, the response will return a next page token that you can specify - // as the page token in a subsequent request. + // To get a page token, perform an initial GetClouFormationStackRecords request. + // If your results are paginated, the response will return a next page token + // that you can specify as the page token in a subsequent request. PageToken *string `locationName:"pageToken" type:"string"` } // String returns the string representation -func (s GetActiveNamesInput) String() string { +func (s GetCloudFormationStackRecordsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetActiveNamesInput) GoString() string { +func (s GetCloudFormationStackRecordsInput) GoString() string { return s.String() } // SetPageToken sets the PageToken field's value. -func (s *GetActiveNamesInput) SetPageToken(v string) *GetActiveNamesInput { +func (s *GetCloudFormationStackRecordsInput) SetPageToken(v string) *GetCloudFormationStackRecordsInput { s.PageToken = &v return s } -type GetActiveNamesOutput struct { +type GetCloudFormationStackRecordsOutput struct { _ struct{} `type:"structure"` - // The list of active names returned by the get active names request. - ActiveNames []*string `locationName:"activeNames" type:"list"` + // A list of objects describing the CloudFormation stack records. + CloudFormationStackRecords []*CloudFormationStackRecord `locationName:"cloudFormationStackRecords" type:"list"` // The token to advance to the next page of resutls from your request. // // A next page token is not returned if there are no more results to display. // - // To get the next page of results, perform another GetActiveNames request and - // specify the next page token using the pageToken parameter. + // To get the next page of results, perform another GetCloudFormationStackRecords + // request and specify the next page token using the pageToken parameter. NextPageToken *string `locationName:"nextPageToken" type:"string"` } // String returns the string representation -func (s GetActiveNamesOutput) String() string { +func (s GetCloudFormationStackRecordsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetActiveNamesOutput) GoString() string { +func (s GetCloudFormationStackRecordsOutput) GoString() string { return s.String() } -// SetActiveNames sets the ActiveNames field's value. -func (s *GetActiveNamesOutput) SetActiveNames(v []*string) *GetActiveNamesOutput { - s.ActiveNames = v +// SetCloudFormationStackRecords sets the CloudFormationStackRecords field's value. +func (s *GetCloudFormationStackRecordsOutput) SetCloudFormationStackRecords(v []*CloudFormationStackRecord) *GetCloudFormationStackRecordsOutput { + s.CloudFormationStackRecords = v return s } // SetNextPageToken sets the NextPageToken field's value. -func (s *GetActiveNamesOutput) SetNextPageToken(v string) *GetActiveNamesOutput { +func (s *GetCloudFormationStackRecordsOutput) SetNextPageToken(v string) *GetCloudFormationStackRecordsOutput { s.NextPageToken = &v return s } -type GetAlarmsInput struct { +type GetContactMethodsInput struct { _ struct{} `type:"structure"` - // The name of the alarm. - // - // Specify an alarm name to return information about a specific alarm. - AlarmName *string `locationName:"alarmName" type:"string"` - - // The name of the Lightsail resource being monitored by the alarm. - // - // Specify a monitored resource name to return information about all alarms - // for a specific resource. - MonitoredResourceName *string `locationName:"monitoredResourceName" type:"string"` - - // The token to advance to the next page of results from your request. + // The protocols used to send notifications, such as Email, or SMS (text messaging). // - // To get a page token, perform an initial GetAlarms request. If your results - // are paginated, the response will return a next page token that you can specify - // as the page token in a subsequent request. - PageToken *string `locationName:"pageToken" type:"string"` + // Specify a protocol in your request to return information about a specific + // contact method protocol. + Protocols []*string `locationName:"protocols" type:"list"` } // String returns the string representation -func (s GetAlarmsInput) String() string { +func (s GetContactMethodsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetAlarmsInput) GoString() string { +func (s GetContactMethodsInput) GoString() string { return s.String() } -// SetAlarmName sets the AlarmName field's value. -func (s *GetAlarmsInput) SetAlarmName(v string) *GetAlarmsInput { - s.AlarmName = &v - return s -} - -// SetMonitoredResourceName sets the MonitoredResourceName field's value. -func (s *GetAlarmsInput) SetMonitoredResourceName(v string) *GetAlarmsInput { - s.MonitoredResourceName = &v - return s -} - -// SetPageToken sets the PageToken field's value. -func (s *GetAlarmsInput) SetPageToken(v string) *GetAlarmsInput { - s.PageToken = &v +// SetProtocols sets the Protocols field's value. +func (s *GetContactMethodsInput) SetProtocols(v []*string) *GetContactMethodsInput { + s.Protocols = v return s } -type GetAlarmsOutput struct { +type GetContactMethodsOutput struct { _ struct{} `type:"structure"` - // An array of objects that describe the alarms. - Alarms []*Alarm `locationName:"alarms" type:"list"` - - // The token to advance to the next page of resutls from your request. - // - // A next page token is not returned if there are no more results to display. - // - // To get the next page of results, perform another GetAlarms request and specify - // the next page token using the pageToken parameter. - NextPageToken *string `locationName:"nextPageToken" type:"string"` + // An array of objects that describe the contact methods. + ContactMethods []*ContactMethod `locationName:"contactMethods" type:"list"` } // String returns the string representation -func (s GetAlarmsOutput) String() string { +func (s GetContactMethodsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetAlarmsOutput) GoString() string { +func (s GetContactMethodsOutput) GoString() string { return s.String() } -// SetAlarms sets the Alarms field's value. -func (s *GetAlarmsOutput) SetAlarms(v []*Alarm) *GetAlarmsOutput { - s.Alarms = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetAlarmsOutput) SetNextPageToken(v string) *GetAlarmsOutput { - s.NextPageToken = &v +// SetContactMethods sets the ContactMethods field's value. +func (s *GetContactMethodsOutput) SetContactMethods(v []*ContactMethod) *GetContactMethodsOutput { + s.ContactMethods = v return s } -type GetAutoSnapshotsInput struct { +type GetDiskInput struct { _ struct{} `type:"structure"` - // The name of the source instance or disk from which to get automatic snapshot - // information. + // The name of the disk (e.g., my-disk). // - // ResourceName is a required field - ResourceName *string `locationName:"resourceName" type:"string" required:"true"` + // DiskName is a required field + DiskName *string `locationName:"diskName" type:"string" required:"true"` } // String returns the string representation -func (s GetAutoSnapshotsInput) String() string { +func (s GetDiskInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetAutoSnapshotsInput) GoString() string { +func (s GetDiskInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetAutoSnapshotsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetAutoSnapshotsInput"} - if s.ResourceName == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceName")) +func (s *GetDiskInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDiskInput"} + if s.DiskName == nil { + invalidParams.Add(request.NewErrParamRequired("DiskName")) } if invalidParams.Len() > 0 { @@ -18678,401 +21812,479 @@ func (s *GetAutoSnapshotsInput) Validate() error { return nil } -// SetResourceName sets the ResourceName field's value. -func (s *GetAutoSnapshotsInput) SetResourceName(v string) *GetAutoSnapshotsInput { - s.ResourceName = &v +// SetDiskName sets the DiskName field's value. +func (s *GetDiskInput) SetDiskName(v string) *GetDiskInput { + s.DiskName = &v return s } -type GetAutoSnapshotsOutput struct { +type GetDiskOutput struct { _ struct{} `type:"structure"` - // An array of objects that describe the automatic snapshots that are available - // for the specified source instance or disk. - AutoSnapshots []*AutoSnapshotDetails `locationName:"autoSnapshots" type:"list"` - - // The name of the source instance or disk for the automatic snapshots. - ResourceName *string `locationName:"resourceName" type:"string"` - - // The resource type (e.g., Instance or Disk). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + // An object containing information about the disk. + Disk *Disk `locationName:"disk" type:"structure"` } // String returns the string representation -func (s GetAutoSnapshotsOutput) String() string { +func (s GetDiskOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetAutoSnapshotsOutput) GoString() string { +func (s GetDiskOutput) GoString() string { return s.String() } -// SetAutoSnapshots sets the AutoSnapshots field's value. -func (s *GetAutoSnapshotsOutput) SetAutoSnapshots(v []*AutoSnapshotDetails) *GetAutoSnapshotsOutput { - s.AutoSnapshots = v - return s -} - -// SetResourceName sets the ResourceName field's value. -func (s *GetAutoSnapshotsOutput) SetResourceName(v string) *GetAutoSnapshotsOutput { - s.ResourceName = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *GetAutoSnapshotsOutput) SetResourceType(v string) *GetAutoSnapshotsOutput { - s.ResourceType = &v +// SetDisk sets the Disk field's value. +func (s *GetDiskOutput) SetDisk(v *Disk) *GetDiskOutput { + s.Disk = v return s } -type GetBlueprintsInput struct { +type GetDiskSnapshotInput struct { _ struct{} `type:"structure"` - // A Boolean value indicating whether to include inactive results in your request. - IncludeInactive *bool `locationName:"includeInactive" type:"boolean"` - - // The token to advance to the next page of results from your request. + // The name of the disk snapshot (e.g., my-disk-snapshot). // - // To get a page token, perform an initial GetBlueprints request. If your results - // are paginated, the response will return a next page token that you can specify - // as the page token in a subsequent request. - PageToken *string `locationName:"pageToken" type:"string"` + // DiskSnapshotName is a required field + DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` } // String returns the string representation -func (s GetBlueprintsInput) String() string { +func (s GetDiskSnapshotInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBlueprintsInput) GoString() string { +func (s GetDiskSnapshotInput) GoString() string { return s.String() } -// SetIncludeInactive sets the IncludeInactive field's value. -func (s *GetBlueprintsInput) SetIncludeInactive(v bool) *GetBlueprintsInput { - s.IncludeInactive = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetDiskSnapshotInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDiskSnapshotInput"} + if s.DiskSnapshotName == nil { + invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetPageToken sets the PageToken field's value. -func (s *GetBlueprintsInput) SetPageToken(v string) *GetBlueprintsInput { - s.PageToken = &v +// SetDiskSnapshotName sets the DiskSnapshotName field's value. +func (s *GetDiskSnapshotInput) SetDiskSnapshotName(v string) *GetDiskSnapshotInput { + s.DiskSnapshotName = &v return s } -type GetBlueprintsOutput struct { +type GetDiskSnapshotOutput struct { _ struct{} `type:"structure"` - // An array of key-value pairs that contains information about the available - // blueprints. - Blueprints []*Blueprint `locationName:"blueprints" type:"list"` - - // The token to advance to the next page of resutls from your request. - // - // A next page token is not returned if there are no more results to display. - // - // To get the next page of results, perform another GetBlueprints request and - // specify the next page token using the pageToken parameter. - NextPageToken *string `locationName:"nextPageToken" type:"string"` + // An object containing information about the disk snapshot. + DiskSnapshot *DiskSnapshot `locationName:"diskSnapshot" type:"structure"` } // String returns the string representation -func (s GetBlueprintsOutput) String() string { +func (s GetDiskSnapshotOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBlueprintsOutput) GoString() string { +func (s GetDiskSnapshotOutput) GoString() string { return s.String() } -// SetBlueprints sets the Blueprints field's value. -func (s *GetBlueprintsOutput) SetBlueprints(v []*Blueprint) *GetBlueprintsOutput { - s.Blueprints = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetBlueprintsOutput) SetNextPageToken(v string) *GetBlueprintsOutput { - s.NextPageToken = &v +// SetDiskSnapshot sets the DiskSnapshot field's value. +func (s *GetDiskSnapshotOutput) SetDiskSnapshot(v *DiskSnapshot) *GetDiskSnapshotOutput { + s.DiskSnapshot = v return s } -type GetBundlesInput struct { +type GetDiskSnapshotsInput struct { _ struct{} `type:"structure"` - // A Boolean value that indicates whether to include inactive bundle results - // in your request. - IncludeInactive *bool `locationName:"includeInactive" type:"boolean"` - // The token to advance to the next page of results from your request. // - // To get a page token, perform an initial GetBundles request. If your results - // are paginated, the response will return a next page token that you can specify - // as the page token in a subsequent request. + // To get a page token, perform an initial GetDiskSnapshots request. If your + // results are paginated, the response will return a next page token that you + // can specify as the page token in a subsequent request. PageToken *string `locationName:"pageToken" type:"string"` } // String returns the string representation -func (s GetBundlesInput) String() string { +func (s GetDiskSnapshotsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBundlesInput) GoString() string { +func (s GetDiskSnapshotsInput) GoString() string { return s.String() } -// SetIncludeInactive sets the IncludeInactive field's value. -func (s *GetBundlesInput) SetIncludeInactive(v bool) *GetBundlesInput { - s.IncludeInactive = &v - return s -} - // SetPageToken sets the PageToken field's value. -func (s *GetBundlesInput) SetPageToken(v string) *GetBundlesInput { +func (s *GetDiskSnapshotsInput) SetPageToken(v string) *GetDiskSnapshotsInput { s.PageToken = &v return s } -type GetBundlesOutput struct { +type GetDiskSnapshotsOutput struct { _ struct{} `type:"structure"` - // An array of key-value pairs that contains information about the available - // bundles. - Bundles []*Bundle `locationName:"bundles" type:"list"` + // An array of objects containing information about all block storage disk snapshots. + DiskSnapshots []*DiskSnapshot `locationName:"diskSnapshots" type:"list"` // The token to advance to the next page of resutls from your request. // // A next page token is not returned if there are no more results to display. // - // To get the next page of results, perform another GetBundles request and specify - // the next page token using the pageToken parameter. + // To get the next page of results, perform another GetDiskSnapshots request + // and specify the next page token using the pageToken parameter. NextPageToken *string `locationName:"nextPageToken" type:"string"` } // String returns the string representation -func (s GetBundlesOutput) String() string { +func (s GetDiskSnapshotsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetBundlesOutput) GoString() string { +func (s GetDiskSnapshotsOutput) GoString() string { return s.String() } -// SetBundles sets the Bundles field's value. -func (s *GetBundlesOutput) SetBundles(v []*Bundle) *GetBundlesOutput { - s.Bundles = v +// SetDiskSnapshots sets the DiskSnapshots field's value. +func (s *GetDiskSnapshotsOutput) SetDiskSnapshots(v []*DiskSnapshot) *GetDiskSnapshotsOutput { + s.DiskSnapshots = v return s } // SetNextPageToken sets the NextPageToken field's value. -func (s *GetBundlesOutput) SetNextPageToken(v string) *GetBundlesOutput { +func (s *GetDiskSnapshotsOutput) SetNextPageToken(v string) *GetDiskSnapshotsOutput { s.NextPageToken = &v return s } -type GetCloudFormationStackRecordsInput struct { +type GetDisksInput struct { _ struct{} `type:"structure"` // The token to advance to the next page of results from your request. // - // To get a page token, perform an initial GetClouFormationStackRecords request. - // If your results are paginated, the response will return a next page token - // that you can specify as the page token in a subsequent request. + // To get a page token, perform an initial GetDisks request. If your results + // are paginated, the response will return a next page token that you can specify + // as the page token in a subsequent request. PageToken *string `locationName:"pageToken" type:"string"` } // String returns the string representation -func (s GetCloudFormationStackRecordsInput) String() string { +func (s GetDisksInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetCloudFormationStackRecordsInput) GoString() string { +func (s GetDisksInput) GoString() string { return s.String() } // SetPageToken sets the PageToken field's value. -func (s *GetCloudFormationStackRecordsInput) SetPageToken(v string) *GetCloudFormationStackRecordsInput { +func (s *GetDisksInput) SetPageToken(v string) *GetDisksInput { s.PageToken = &v return s } -type GetCloudFormationStackRecordsOutput struct { +type GetDisksOutput struct { _ struct{} `type:"structure"` - // A list of objects describing the CloudFormation stack records. - CloudFormationStackRecords []*CloudFormationStackRecord `locationName:"cloudFormationStackRecords" type:"list"` + // An array of objects containing information about all block storage disks. + Disks []*Disk `locationName:"disks" type:"list"` // The token to advance to the next page of resutls from your request. // // A next page token is not returned if there are no more results to display. // - // To get the next page of results, perform another GetCloudFormationStackRecords - // request and specify the next page token using the pageToken parameter. + // To get the next page of results, perform another GetDisks request and specify + // the next page token using the pageToken parameter. NextPageToken *string `locationName:"nextPageToken" type:"string"` } // String returns the string representation -func (s GetCloudFormationStackRecordsOutput) String() string { +func (s GetDisksOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetCloudFormationStackRecordsOutput) GoString() string { +func (s GetDisksOutput) GoString() string { return s.String() } -// SetCloudFormationStackRecords sets the CloudFormationStackRecords field's value. -func (s *GetCloudFormationStackRecordsOutput) SetCloudFormationStackRecords(v []*CloudFormationStackRecord) *GetCloudFormationStackRecordsOutput { - s.CloudFormationStackRecords = v +// SetDisks sets the Disks field's value. +func (s *GetDisksOutput) SetDisks(v []*Disk) *GetDisksOutput { + s.Disks = v return s } // SetNextPageToken sets the NextPageToken field's value. -func (s *GetCloudFormationStackRecordsOutput) SetNextPageToken(v string) *GetCloudFormationStackRecordsOutput { +func (s *GetDisksOutput) SetNextPageToken(v string) *GetDisksOutput { s.NextPageToken = &v return s } -type GetContactMethodsInput struct { +type GetDistributionBundlesInput struct { _ struct{} `type:"structure"` - - // The protocols used to send notifications, such as Email, or SMS (text messaging). - // - // Specify a protocol in your request to return information about a specific - // contact method protocol. - Protocols []*string `locationName:"protocols" type:"list"` } // String returns the string representation -func (s GetContactMethodsInput) String() string { +func (s GetDistributionBundlesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetContactMethodsInput) GoString() string { +func (s GetDistributionBundlesInput) GoString() string { return s.String() } -// SetProtocols sets the Protocols field's value. -func (s *GetContactMethodsInput) SetProtocols(v []*string) *GetContactMethodsInput { - s.Protocols = v - return s -} - -type GetContactMethodsOutput struct { +type GetDistributionBundlesOutput struct { _ struct{} `type:"structure"` - // An array of objects that describe the contact methods. - ContactMethods []*ContactMethod `locationName:"contactMethods" type:"list"` + // An object that describes a distribution bundle. + Bundles []*DistributionBundle `locationName:"bundles" type:"list"` } // String returns the string representation -func (s GetContactMethodsOutput) String() string { +func (s GetDistributionBundlesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetContactMethodsOutput) GoString() string { +func (s GetDistributionBundlesOutput) GoString() string { return s.String() } -// SetContactMethods sets the ContactMethods field's value. -func (s *GetContactMethodsOutput) SetContactMethods(v []*ContactMethod) *GetContactMethodsOutput { - s.ContactMethods = v +// SetBundles sets the Bundles field's value. +func (s *GetDistributionBundlesOutput) SetBundles(v []*DistributionBundle) *GetDistributionBundlesOutput { + s.Bundles = v return s } -type GetDiskInput struct { +type GetDistributionLatestCacheResetInput struct { _ struct{} `type:"structure"` - // The name of the disk (e.g., my-disk). + // The name of the distribution for which to return the timestamp of the last + // cache reset. // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` + // Use the GetDistributions action to get a list of distribution names that + // you can specify. + // + // When omitted, the response includes the latest cache reset timestamp of all + // your distributions. + DistributionName *string `locationName:"distributionName" type:"string"` } // String returns the string representation -func (s GetDiskInput) String() string { +func (s GetDistributionLatestCacheResetInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDiskInput) GoString() string { +func (s GetDistributionLatestCacheResetInput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *GetDiskInput) SetDiskName(v string) *GetDiskInput { - s.DiskName = &v +// SetDistributionName sets the DistributionName field's value. +func (s *GetDistributionLatestCacheResetInput) SetDistributionName(v string) *GetDistributionLatestCacheResetInput { + s.DistributionName = &v return s } -type GetDiskOutput struct { +type GetDistributionLatestCacheResetOutput struct { _ struct{} `type:"structure"` - // An object containing information about the disk. - Disk *Disk `locationName:"disk" type:"structure"` + // The timestamp of the last cache reset (e.g., 1479734909.17) in Unix time + // format. + CreateTime *time.Time `locationName:"createTime" type:"timestamp"` + + // The status of the last cache reset. + Status *string `locationName:"status" type:"string"` } // String returns the string representation -func (s GetDiskOutput) String() string { +func (s GetDistributionLatestCacheResetOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDiskOutput) GoString() string { +func (s GetDistributionLatestCacheResetOutput) GoString() string { return s.String() } -// SetDisk sets the Disk field's value. -func (s *GetDiskOutput) SetDisk(v *Disk) *GetDiskOutput { - s.Disk = v +// SetCreateTime sets the CreateTime field's value. +func (s *GetDistributionLatestCacheResetOutput) SetCreateTime(v time.Time) *GetDistributionLatestCacheResetOutput { + s.CreateTime = &v return s } -type GetDiskSnapshotInput struct { +// SetStatus sets the Status field's value. +func (s *GetDistributionLatestCacheResetOutput) SetStatus(v string) *GetDistributionLatestCacheResetOutput { + s.Status = &v + return s +} + +type GetDistributionMetricDataInput struct { _ struct{} `type:"structure"` - // The name of the disk snapshot (e.g., my-disk-snapshot). + // The name of the distribution for which to get metric data. + // + // Use the GetDistributions action to get a list of distribution names that + // you can specify. + // + // DistributionName is a required field + DistributionName *string `locationName:"distributionName" type:"string" required:"true"` + + // The end of the time interval for which to get metric data. + // + // Constraints: + // + // * Specified in Coordinated Universal Time (UTC). + // + // * Specified in the Unix time format. For example, if you wish to use an + // end time of October 1, 2018, at 9 PM UTC, specify 1538427600 as the end + // time. + // + // You can convert a human-friendly time to Unix time format using a converter + // like Epoch converter (https://www.epochconverter.com/). + // + // EndTime is a required field + EndTime *time.Time `locationName:"endTime" type:"timestamp" required:"true"` + + // The metric for which you want to return information. + // + // Valid distribution metric names are listed below, along with the most useful + // statistics to include in your request, and the published unit value. + // + // * Requests - The total number of viewer requests received by your Lightsail + // distribution, for all HTTP methods, and for both HTTP and HTTPS requests. + // Statistics: The most useful statistic is Sum. Unit: The published unit + // is None. + // + // * BytesDownloaded - The number of bytes downloaded by viewers for GET, + // HEAD, and OPTIONS requests. Statistics: The most useful statistic is Sum. + // Unit: The published unit is None. + // + // * BytesUploaded - The number of bytes uploaded to your origin by your + // Lightsail distribution, using POST and PUT requests. Statistics: The most + // useful statistic is Sum. Unit: The published unit is None. + // + // * TotalErrorRate - The percentage of all viewer requests for which the + // response's HTTP status code was 4xx or 5xx. Statistics: The most useful + // statistic is Average. Unit: The published unit is Percent. + // + // * 4xxErrorRate - The percentage of all viewer requests for which the response's + // HTTP status cod was 4xx. In these cases, the client or client viewer may + // have made an error. For example, a status code of 404 (Not Found) means + // that the client requested an object that could not be found. Statistics: + // The most useful statistic is Average. Unit: The published unit is Percent. + // + // * 5xxErrorRate - The percentage of all viewer requests for which the response's + // HTTP status code was 5xx. In these cases, the origin server did not satisfy + // the requests. For example, a status code of 503 (Service Unavailable) + // means that the origin server is currently unavailable. Statistics: The + // most useful statistic is Average. Unit: The published unit is Percent. + // + // MetricName is a required field + MetricName *string `locationName:"metricName" type:"string" required:"true" enum:"DistributionMetricName"` + + // The granularity, in seconds, for the metric data points that will be returned. + // + // Period is a required field + Period *int64 `locationName:"period" min:"60" type:"integer" required:"true"` + + // The start of the time interval for which to get metric data. + // + // Constraints: + // + // * Specified in Coordinated Universal Time (UTC). + // + // * Specified in the Unix time format. For example, if you wish to use a + // start time of October 1, 2018, at 8 PM UTC, specify 1538424000 as the + // start time. + // + // You can convert a human-friendly time to Unix time format using a converter + // like Epoch converter (https://www.epochconverter.com/). + // + // StartTime is a required field + StartTime *time.Time `locationName:"startTime" type:"timestamp" required:"true"` + + // The statistic for the metric. + // + // The following statistics are available: + // + // * Minimum - The lowest value observed during the specified period. Use + // this value to determine low volumes of activity for your application. + // + // * Maximum - The highest value observed during the specified period. Use + // this value to determine high volumes of activity for your application. + // + // * Sum - All values submitted for the matching metric added together. You + // can use this statistic to determine the total volume of a metric. + // + // * Average - The value of Sum / SampleCount during the specified period. + // By comparing this statistic with the Minimum and Maximum values, you can + // determine the full scope of a metric and how close the average use is + // to the Minimum and Maximum values. This comparison helps you to know when + // to increase or decrease your resources. + // + // * SampleCount - The count, or number, of data points used for the statistical + // calculation. + // + // Statistics is a required field + Statistics []*string `locationName:"statistics" type:"list" required:"true"` + + // The unit for the metric data request. // - // DiskSnapshotName is a required field - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` + // Valid units depend on the metric data being requested. For the valid units + // with each available metric, see the metricName parameter. + // + // Unit is a required field + Unit *string `locationName:"unit" type:"string" required:"true" enum:"MetricUnit"` } // String returns the string representation -func (s GetDiskSnapshotInput) String() string { +func (s GetDistributionMetricDataInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDiskSnapshotInput) GoString() string { +func (s GetDistributionMetricDataInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetDiskSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDiskSnapshotInput"} - if s.DiskSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) +func (s *GetDistributionMetricDataInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDistributionMetricDataInput"} + if s.DistributionName == nil { + invalidParams.Add(request.NewErrParamRequired("DistributionName")) + } + if s.EndTime == nil { + invalidParams.Add(request.NewErrParamRequired("EndTime")) + } + if s.MetricName == nil { + invalidParams.Add(request.NewErrParamRequired("MetricName")) + } + if s.Period == nil { + invalidParams.Add(request.NewErrParamRequired("Period")) + } + if s.Period != nil && *s.Period < 60 { + invalidParams.Add(request.NewErrParamMinValue("Period", 60)) + } + if s.StartTime == nil { + invalidParams.Add(request.NewErrParamRequired("StartTime")) + } + if s.Statistics == nil { + invalidParams.Add(request.NewErrParamRequired("Statistics")) + } + if s.Unit == nil { + invalidParams.Add(request.NewErrParamRequired("Unit")) } if invalidParams.Len() > 0 { @@ -19081,159 +22293,155 @@ func (s *GetDiskSnapshotInput) Validate() error { return nil } -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *GetDiskSnapshotInput) SetDiskSnapshotName(v string) *GetDiskSnapshotInput { - s.DiskSnapshotName = &v +// SetDistributionName sets the DistributionName field's value. +func (s *GetDistributionMetricDataInput) SetDistributionName(v string) *GetDistributionMetricDataInput { + s.DistributionName = &v return s } -type GetDiskSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An object containing information about the disk snapshot. - DiskSnapshot *DiskSnapshot `locationName:"diskSnapshot" type:"structure"` -} - -// String returns the string representation -func (s GetDiskSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskSnapshotOutput) GoString() string { - return s.String() +// SetEndTime sets the EndTime field's value. +func (s *GetDistributionMetricDataInput) SetEndTime(v time.Time) *GetDistributionMetricDataInput { + s.EndTime = &v + return s } -// SetDiskSnapshot sets the DiskSnapshot field's value. -func (s *GetDiskSnapshotOutput) SetDiskSnapshot(v *DiskSnapshot) *GetDiskSnapshotOutput { - s.DiskSnapshot = v +// SetMetricName sets the MetricName field's value. +func (s *GetDistributionMetricDataInput) SetMetricName(v string) *GetDistributionMetricDataInput { + s.MetricName = &v return s } -type GetDiskSnapshotsInput struct { - _ struct{} `type:"structure"` - - // The token to advance to the next page of results from your request. - // - // To get a page token, perform an initial GetDiskSnapshots request. If your - // results are paginated, the response will return a next page token that you - // can specify as the page token in a subsequent request. - PageToken *string `locationName:"pageToken" type:"string"` +// SetPeriod sets the Period field's value. +func (s *GetDistributionMetricDataInput) SetPeriod(v int64) *GetDistributionMetricDataInput { + s.Period = &v + return s } -// String returns the string representation -func (s GetDiskSnapshotsInput) String() string { - return awsutil.Prettify(s) +// SetStartTime sets the StartTime field's value. +func (s *GetDistributionMetricDataInput) SetStartTime(v time.Time) *GetDistributionMetricDataInput { + s.StartTime = &v + return s } -// GoString returns the string representation -func (s GetDiskSnapshotsInput) GoString() string { - return s.String() +// SetStatistics sets the Statistics field's value. +func (s *GetDistributionMetricDataInput) SetStatistics(v []*string) *GetDistributionMetricDataInput { + s.Statistics = v + return s } -// SetPageToken sets the PageToken field's value. -func (s *GetDiskSnapshotsInput) SetPageToken(v string) *GetDiskSnapshotsInput { - s.PageToken = &v +// SetUnit sets the Unit field's value. +func (s *GetDistributionMetricDataInput) SetUnit(v string) *GetDistributionMetricDataInput { + s.Unit = &v return s } -type GetDiskSnapshotsOutput struct { +type GetDistributionMetricDataOutput struct { _ struct{} `type:"structure"` - // An array of objects containing information about all block storage disk snapshots. - DiskSnapshots []*DiskSnapshot `locationName:"diskSnapshots" type:"list"` + // An array of objects that describe the metric data returned. + MetricData []*MetricDatapoint `locationName:"metricData" type:"list"` - // The token to advance to the next page of resutls from your request. - // - // A next page token is not returned if there are no more results to display. - // - // To get the next page of results, perform another GetDiskSnapshots request - // and specify the next page token using the pageToken parameter. - NextPageToken *string `locationName:"nextPageToken" type:"string"` + // The name of the metric returned. + MetricName *string `locationName:"metricName" type:"string" enum:"DistributionMetricName"` } // String returns the string representation -func (s GetDiskSnapshotsOutput) String() string { +func (s GetDistributionMetricDataOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDiskSnapshotsOutput) GoString() string { +func (s GetDistributionMetricDataOutput) GoString() string { return s.String() } -// SetDiskSnapshots sets the DiskSnapshots field's value. -func (s *GetDiskSnapshotsOutput) SetDiskSnapshots(v []*DiskSnapshot) *GetDiskSnapshotsOutput { - s.DiskSnapshots = v +// SetMetricData sets the MetricData field's value. +func (s *GetDistributionMetricDataOutput) SetMetricData(v []*MetricDatapoint) *GetDistributionMetricDataOutput { + s.MetricData = v return s } -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetDiskSnapshotsOutput) SetNextPageToken(v string) *GetDiskSnapshotsOutput { - s.NextPageToken = &v +// SetMetricName sets the MetricName field's value. +func (s *GetDistributionMetricDataOutput) SetMetricName(v string) *GetDistributionMetricDataOutput { + s.MetricName = &v return s } -type GetDisksInput struct { +type GetDistributionsInput struct { _ struct{} `type:"structure"` + // The name of the distribution for which to return information. + // + // Use the GetDistributions action to get a list of distribution names that + // you can specify. + // + // When omitted, the response includes all of your distributions in the AWS + // Region where the request is made. + DistributionName *string `locationName:"distributionName" type:"string"` + // The token to advance to the next page of results from your request. // - // To get a page token, perform an initial GetDisks request. If your results - // are paginated, the response will return a next page token that you can specify - // as the page token in a subsequent request. + // To get a page token, perform an initial GetDistributions request. If your + // results are paginated, the response will return a next page token that you + // can specify as the page token in a subsequent request. PageToken *string `locationName:"pageToken" type:"string"` } // String returns the string representation -func (s GetDisksInput) String() string { +func (s GetDistributionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDisksInput) GoString() string { +func (s GetDistributionsInput) GoString() string { return s.String() } +// SetDistributionName sets the DistributionName field's value. +func (s *GetDistributionsInput) SetDistributionName(v string) *GetDistributionsInput { + s.DistributionName = &v + return s +} + // SetPageToken sets the PageToken field's value. -func (s *GetDisksInput) SetPageToken(v string) *GetDisksInput { +func (s *GetDistributionsInput) SetPageToken(v string) *GetDistributionsInput { s.PageToken = &v return s } -type GetDisksOutput struct { +type GetDistributionsOutput struct { _ struct{} `type:"structure"` - // An array of objects containing information about all block storage disks. - Disks []*Disk `locationName:"disks" type:"list"` + // An array of objects that describe your distributions. + Distributions []*LightsailDistribution `locationName:"distributions" type:"list"` - // The token to advance to the next page of resutls from your request. + // The token to advance to the next page of results from your request. // // A next page token is not returned if there are no more results to display. // - // To get the next page of results, perform another GetDisks request and specify - // the next page token using the pageToken parameter. + // To get the next page of results, perform another GetDistributions request + // and specify the next page token using the pageToken parameter. NextPageToken *string `locationName:"nextPageToken" type:"string"` } // String returns the string representation -func (s GetDisksOutput) String() string { +func (s GetDistributionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDisksOutput) GoString() string { +func (s GetDistributionsOutput) GoString() string { return s.String() } -// SetDisks sets the Disks field's value. -func (s *GetDisksOutput) SetDisks(v []*Disk) *GetDisksOutput { - s.Disks = v +// SetDistributions sets the Distributions field's value. +func (s *GetDistributionsOutput) SetDistributions(v []*LightsailDistribution) *GetDistributionsOutput { + s.Distributions = v return s } // SetNextPageToken sets the NextPageToken field's value. -func (s *GetDisksOutput) SetNextPageToken(v string) *GetDisksOutput { +func (s *GetDistributionsOutput) SetNextPageToken(v string) *GetDistributionsOutput { s.NextPageToken = &v return s } @@ -19556,44 +22764,65 @@ type GetInstanceMetricDataInput struct { // Valid instance metric names are listed below, along with the most useful // statistics to include in your request, and the published unit value. // - // * CPUUtilization — The percentage of allocated compute units that are + // * BurstCapacityPercentage - The percentage of CPU performance available + // for your instance to burst above its baseline. Your instance continuously + // accrues and consumes burst capacity. Burst capacity stops accruing when + // your instance's BurstCapacityPercentage reaches 100%. For more information, + // see Viewing instance burst capacity in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-viewing-instance-burst-capacity). + // Statistics: The most useful statistics are Maximum and Average. Unit: + // The published unit is Percent. + // + // * BurstCapacityTime - The available amount of time for your instance to + // burst at 100% CPU utilization. Your instance continuously accrues and + // consumes burst capacity. Burst capacity time stops accruing when your + // instance's BurstCapacityPercentage metric reaches 100%. Burst capacity + // time is consumed at the full rate only when your instance operates at + // 100% CPU utilization. For example, if your instance operates at 50% CPU + // utilization in the burstable zone for a 5-minute period, then it consumes + // CPU burst capacity minutes at a 50% rate in that period. Your instance + // consumed 2 minutes and 30 seconds of CPU burst capacity minutes in the + // 5-minute period. For more information, see Viewing instance burst capacity + // in Amazon Lightsail (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-viewing-instance-burst-capacity). + // Statistics: The most useful statistics are Maximum and Average. Unit: + // The published unit is Seconds. + // + // * CPUUtilization - The percentage of allocated compute units that are // currently in use on the instance. This metric identifies the processing // power to run the applications on the instance. Tools in your operating // system can show a lower percentage than Lightsail when the instance is // not allocated a full processor core. Statistics: The most useful statistics // are Maximum and Average. Unit: The published unit is Percent. // - // * NetworkIn — The number of bytes received on all network interfaces - // by the instance. This metric identifies the volume of incoming network - // traffic to the instance. The number reported is the number of bytes received - // during the period. Because this metric is reported in 5-minute intervals, - // divide the reported number by 300 to find Bytes/second. Statistics: The - // most useful statistic is Sum. Unit: The published unit is Bytes. + // * NetworkIn - The number of bytes received on all network interfaces by + // the instance. This metric identifies the volume of incoming network traffic + // to the instance. The number reported is the number of bytes received during + // the period. Because this metric is reported in 5-minute intervals, divide + // the reported number by 300 to find Bytes/second. Statistics: The most + // useful statistic is Sum. Unit: The published unit is Bytes. // - // * NetworkOut — The number of bytes sent out on all network interfaces + // * NetworkOut - The number of bytes sent out on all network interfaces // by the instance. This metric identifies the volume of outgoing network // traffic from the instance. The number reported is the number of bytes // sent during the period. Because this metric is reported in 5-minute intervals, // divide the reported number by 300 to find Bytes/second. Statistics: The // most useful statistic is Sum. Unit: The published unit is Bytes. // - // * StatusCheckFailed — Reports whether the instance passed or failed - // both the instance status check and the system status check. This metric - // can be either 0 (passed) or 1 (failed). This metric data is available - // in 1-minute (60 seconds) granularity. Statistics: The most useful statistic - // is Sum. Unit: The published unit is Count. + // * StatusCheckFailed - Reports whether the instance passed or failed both + // the instance status check and the system status check. This metric can + // be either 0 (passed) or 1 (failed). This metric data is available in 1-minute + // (60 seconds) granularity. Statistics: The most useful statistic is Sum. + // Unit: The published unit is Count. // - // * StatusCheckFailed_Instance — Reports whether the instance passed or + // * StatusCheckFailed_Instance - Reports whether the instance passed or // failed the instance status check. This metric can be either 0 (passed) // or 1 (failed). This metric data is available in 1-minute (60 seconds) // granularity. Statistics: The most useful statistic is Sum. Unit: The published // unit is Count. // - // * StatusCheckFailed_System — Reports whether the instance passed or - // failed the system status check. This metric can be either 0 (passed) or - // 1 (failed). This metric data is available in 1-minute (60 seconds) granularity. - // Statistics: The most useful statistic is Sum. Unit: The published unit - // is Count. + // * StatusCheckFailed_System - Reports whether the instance passed or failed + // the system status check. This metric can be either 0 (passed) or 1 (failed). + // This metric data is available in 1-minute (60 seconds) granularity. Statistics: + // The most useful statistic is Sum. Unit: The published unit is Count. // // MetricName is a required field MetricName *string `locationName:"metricName" type:"string" required:"true" enum:"InstanceMetricName"` @@ -19616,30 +22845,30 @@ type GetInstanceMetricDataInput struct { // // The following statistics are available: // - // * Minimum — The lowest value observed during the specified period. Use + // * Minimum - The lowest value observed during the specified period. Use // this value to determine low volumes of activity for your application. // - // * Maximum — The highest value observed during the specified period. - // Use this value to determine high volumes of activity for your application. + // * Maximum - The highest value observed during the specified period. Use + // this value to determine high volumes of activity for your application. // - // * Sum — All values submitted for the matching metric added together. - // You can use this statistic to determine the total volume of a metric. + // * Sum - All values submitted for the matching metric added together. You + // can use this statistic to determine the total volume of a metric. // - // * Average — The value of Sum / SampleCount during the specified period. + // * Average - The value of Sum / SampleCount during the specified period. // By comparing this statistic with the Minimum and Maximum values, you can // determine the full scope of a metric and how close the average use is // to the Minimum and Maximum values. This comparison helps you to know when // to increase or decrease your resources. // - // * SampleCount — The count, or number, of data points used for the statistical + // * SampleCount - The count, or number, of data points used for the statistical // calculation. // // Statistics is a required field Statistics []*string `locationName:"statistics" type:"list" required:"true"` // The unit for the metric data request. Valid units depend on the metric data - // being required. For the valid units with each available metric, see the metricName - // parameter. + // being requested. For the valid units to specify with each available metric, + // see the metricName parameter. // // Unit is a required field Unit *string `locationName:"unit" type:"string" required:"true" enum:"MetricUnit"` @@ -19734,11 +22963,10 @@ func (s *GetInstanceMetricDataInput) SetUnit(v string) *GetInstanceMetricDataInp type GetInstanceMetricDataOutput struct { _ struct{} `type:"structure"` - // An array of key-value pairs containing information about the results of your - // get instance metric data request. + // An array of objects that describe the metric data returned. MetricData []*MetricDatapoint `locationName:"metricData" type:"list"` - // The metric name to return data for. + // The name of the metric returned. MetricName *string `locationName:"metricName" type:"string" enum:"InstanceMetricName"` } @@ -19790,7 +23018,7 @@ func (s *GetInstanceOutput) SetInstance(v *Instance) *GetInstanceOutput { type GetInstancePortStatesInput struct { _ struct{} `type:"structure"` - // The name of the instance. + // The name of the instance for which to return firewall port states. // // InstanceName is a required field InstanceName *string `locationName:"instanceName" type:"string" required:"true"` @@ -19828,7 +23056,8 @@ func (s *GetInstancePortStatesInput) SetInstanceName(v string) *GetInstancePortS type GetInstancePortStatesOutput struct { _ struct{} `type:"structure"` - // Information about the port states resulting from your request. + // An array of objects that describe the firewall port states for the specified + // instance. PortStates []*InstancePortState `locationName:"portStates" type:"list"` } @@ -20281,73 +23510,73 @@ type GetLoadBalancerMetricDataInput struct { // Valid load balancer metric names are listed below, along with the most useful // statistics to include in your request, and the published unit value. // - // * ClientTLSNegotiationErrorCount — The number of TLS connections initiated + // * ClientTLSNegotiationErrorCount - The number of TLS connections initiated // by the client that did not establish a session with the load balancer // due to a TLS error generated by the load balancer. Possible causes include // a mismatch of ciphers or protocols. Statistics: The most useful statistic // is Sum. Unit: The published unit is Count. // - // * HealthyHostCount — The number of target instances that are considered + // * HealthyHostCount - The number of target instances that are considered // healthy. Statistics: The most useful statistic are Average, Minimum, and // Maximum. Unit: The published unit is Count. // - // * HTTPCode_Instance_2XX_Count — The number of HTTP 2XX response codes + // * HTTPCode_Instance_2XX_Count - The number of HTTP 2XX response codes // generated by the target instances. This does not include any response // codes generated by the load balancer. Statistics: The most useful statistic // is Sum. Note that Minimum, Maximum, and Average all return 1. Unit: The // published unit is Count. // - // * HTTPCode_Instance_3XX_Count — The number of HTTP 3XX response codes + // * HTTPCode_Instance_3XX_Count - The number of HTTP 3XX response codes // generated by the target instances. This does not include any response // codes generated by the load balancer. Statistics: The most useful statistic // is Sum. Note that Minimum, Maximum, and Average all return 1. Unit: The // published unit is Count. // - // * HTTPCode_Instance_4XX_Count — The number of HTTP 4XX response codes + // * HTTPCode_Instance_4XX_Count - The number of HTTP 4XX response codes // generated by the target instances. This does not include any response // codes generated by the load balancer. Statistics: The most useful statistic // is Sum. Note that Minimum, Maximum, and Average all return 1. Unit: The // published unit is Count. // - // * HTTPCode_Instance_5XX_Count — The number of HTTP 5XX response codes + // * HTTPCode_Instance_5XX_Count - The number of HTTP 5XX response codes // generated by the target instances. This does not include any response // codes generated by the load balancer. Statistics: The most useful statistic // is Sum. Note that Minimum, Maximum, and Average all return 1. Unit: The // published unit is Count. // - // * HTTPCode_LB_4XX_Count — The number of HTTP 4XX client error codes - // that originated from the load balancer. Client errors are generated when - // requests are malformed or incomplete. These requests were not received - // by the target instance. This count does not include response codes generated - // by the target instances. Statistics: The most useful statistic is Sum. - // Note that Minimum, Maximum, and Average all return 1. Unit: The published - // unit is Count. + // * HTTPCode_LB_4XX_Count - The number of HTTP 4XX client error codes that + // originated from the load balancer. Client errors are generated when requests + // are malformed or incomplete. These requests were not received by the target + // instance. This count does not include response codes generated by the + // target instances. Statistics: The most useful statistic is Sum. Note that + // Minimum, Maximum, and Average all return 1. Unit: The published unit is + // Count. // - // * HTTPCode_LB_5XX_Count — The number of HTTP 5XX server error codes - // that originated from the load balancer. This does not include any response + // * HTTPCode_LB_5XX_Count - The number of HTTP 5XX server error codes that + // originated from the load balancer. This does not include any response // codes generated by the target instance. This metric is reported if there // are no healthy instances attached to the load balancer, or if the request // rate exceeds the capacity of the instances (spillover) or the load balancer. // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, // and Average all return 1. Unit: The published unit is Count. // - // * InstanceResponseTime — The time elapsed, in seconds, after the request + // * InstanceResponseTime - The time elapsed, in seconds, after the request // leaves the load balancer until a response from the target instance is // received. Statistics: The most useful statistic is Average. Unit: The // published unit is Seconds. // - // * RejectedConnectionCount — The number of connections that were rejected + // * RejectedConnectionCount - The number of connections that were rejected // because the load balancer had reached its maximum number of connections. // Statistics: The most useful statistic is Sum. Unit: The published unit // is Count. // - // * RequestCount — The number of requests processed over IPv4. This count + // * RequestCount - The number of requests processed over IPv4. This count // includes only the requests with a response generated by a target instance // of the load balancer. Statistics: The most useful statistic is Sum. Note // that Minimum, Maximum, and Average all return 1. Unit: The published unit // is Count. // - // * UnhealthyHostCount — The number of target instances that are considered + // * UnhealthyHostCount - The number of target instances that are considered // unhealthy. Statistics: The most useful statistic are Average, Minimum, // and Maximum. Unit: The published unit is Count. // @@ -20368,30 +23597,30 @@ type GetLoadBalancerMetricDataInput struct { // // The following statistics are available: // - // * Minimum — The lowest value observed during the specified period. Use + // * Minimum - The lowest value observed during the specified period. Use // this value to determine low volumes of activity for your application. // - // * Maximum — The highest value observed during the specified period. - // Use this value to determine high volumes of activity for your application. + // * Maximum - The highest value observed during the specified period. Use + // this value to determine high volumes of activity for your application. // - // * Sum — All values submitted for the matching metric added together. - // You can use this statistic to determine the total volume of a metric. + // * Sum - All values submitted for the matching metric added together. You + // can use this statistic to determine the total volume of a metric. // - // * Average — The value of Sum / SampleCount during the specified period. + // * Average - The value of Sum / SampleCount during the specified period. // By comparing this statistic with the Minimum and Maximum values, you can // determine the full scope of a metric and how close the average use is // to the Minimum and Maximum values. This comparison helps you to know when // to increase or decrease your resources. // - // * SampleCount — The count, or number, of data points used for the statistical + // * SampleCount - The count, or number, of data points used for the statistical // calculation. // // Statistics is a required field Statistics []*string `locationName:"statistics" type:"list" required:"true"` // The unit for the metric data request. Valid units depend on the metric data - // being required. For the valid units with each available metric, see the metricName - // parameter. + // being requested. For the valid units with each available metric, see the + // metricName parameter. // // Unit is a required field Unit *string `locationName:"unit" type:"string" required:"true" enum:"MetricUnit"` @@ -20486,70 +23715,10 @@ func (s *GetLoadBalancerMetricDataInput) SetUnit(v string) *GetLoadBalancerMetri type GetLoadBalancerMetricDataOutput struct { _ struct{} `type:"structure"` - // An array of metric datapoint objects. + // An array of objects that describe the metric data returned. MetricData []*MetricDatapoint `locationName:"metricData" type:"list"` - // The metric about which you are receiving information. Valid values are listed - // below, along with the most useful statistics to include in your request. - // - // * ClientTLSNegotiationErrorCount - The number of TLS connections initiated - // by the client that did not establish a session with the load balancer. - // Possible causes include a mismatch of ciphers or protocols. Statistics: - // The most useful statistic is Sum. - // - // * HealthyHostCount - The number of target instances that are considered - // healthy. Statistics: The most useful statistic are Average, Minimum, and - // Maximum. - // - // * UnhealthyHostCount - The number of target instances that are considered - // unhealthy. Statistics: The most useful statistic are Average, Minimum, - // and Maximum. - // - // * HTTPCode_LB_4XX_Count - The number of HTTP 4XX client error codes that - // originate from the load balancer. Client errors are generated when requests - // are malformed or incomplete. These requests have not been received by - // the target instance. This count does not include any response codes generated - // by the target instances. Statistics: The most useful statistic is Sum. - // Note that Minimum, Maximum, and Average all return 1. - // - // * HTTPCode_LB_5XX_Count - The number of HTTP 5XX server error codes that - // originate from the load balancer. This count does not include any response - // codes generated by the target instances. Statistics: The most useful statistic - // is Sum. Note that Minimum, Maximum, and Average all return 1. Note that - // Minimum, Maximum, and Average all return 1. - // - // * HTTPCode_Instance_2XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. Statistics: The most useful statistic is Sum. Note - // that Minimum, Maximum, and Average all return 1. - // - // * HTTPCode_Instance_3XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. Statistics: The most useful statistic is Sum. Note - // that Minimum, Maximum, and Average all return 1. - // - // * HTTPCode_Instance_4XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. Statistics: The most useful statistic is Sum. Note - // that Minimum, Maximum, and Average all return 1. - // - // * HTTPCode_Instance_5XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. Statistics: The most useful statistic is Sum. Note - // that Minimum, Maximum, and Average all return 1. - // - // * InstanceResponseTime - The time elapsed, in seconds, after the request - // leaves the load balancer until a response from the target instance is - // received. Statistics: The most useful statistic is Average. - // - // * RejectedConnectionCount - The number of connections that were rejected - // because the load balancer had reached its maximum number of connections. - // Statistics: The most useful statistic is Sum. - // - // * RequestCount - The number of requests processed over IPv4. This count - // includes only the requests with a response generated by a target instance - // of the load balancer. Statistics: The most useful statistic is Sum. Note - // that Minimum, Maximum, and Average all return 1. + // The name of the metric returned. MetricName *string `locationName:"metricName" type:"string" enum:"LoadBalancerMetricName"` } @@ -20765,7 +23934,7 @@ type GetOperationOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operation *Operation `locationName:"operation" type:"structure"` } @@ -20857,7 +24026,7 @@ type GetOperationsForResourceOutput struct { NextPageToken *string `locationName:"nextPageToken" type:"string"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -20929,7 +24098,7 @@ type GetOperationsOutput struct { NextPageToken *string `locationName:"nextPageToken" type:"string"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -21617,27 +24786,27 @@ type GetRelationalDatabaseMetricDataInput struct { // All relational database metric data is available in 1-minute (60 seconds) // granularity. // - // * CPUUtilization — The percentage of CPU utilization currently in use + // * CPUUtilization - The percentage of CPU utilization currently in use // on the database. Statistics: The most useful statistics are Maximum and // Average. Unit: The published unit is Percent. // - // * DatabaseConnections — The number of database connections in use. Statistics: + // * DatabaseConnections - The number of database connections in use. Statistics: // The most useful statistics are Maximum and Sum. Unit: The published unit // is Count. // - // * DiskQueueDepth — The number of outstanding IOs (read/write requests) + // * DiskQueueDepth - The number of outstanding IOs (read/write requests) // that are waiting to access the disk. Statistics: The most useful statistic // is Sum. Unit: The published unit is Count. // - // * FreeStorageSpace — The amount of available storage space. Statistics: + // * FreeStorageSpace - The amount of available storage space. Statistics: // The most useful statistic is Sum. Unit: The published unit is Bytes. // - // * NetworkReceiveThroughput — The incoming (Receive) network traffic - // on the database, including both customer database traffic and AWS traffic + // * NetworkReceiveThroughput - The incoming (Receive) network traffic on + // the database, including both customer database traffic and AWS traffic // used for monitoring and replication. Statistics: The most useful statistic // is Average. Unit: The published unit is Bytes/Second. // - // * NetworkTransmitThroughput — The outgoing (Transmit) network traffic + // * NetworkTransmitThroughput - The outgoing (Transmit) network traffic // on the database, including both customer database traffic and AWS traffic // used for monitoring and replication. Statistics: The most useful statistic // is Average. Unit: The published unit is Bytes/Second. @@ -21675,30 +24844,30 @@ type GetRelationalDatabaseMetricDataInput struct { // // The following statistics are available: // - // * Minimum — The lowest value observed during the specified period. Use + // * Minimum - The lowest value observed during the specified period. Use // this value to determine low volumes of activity for your application. // - // * Maximum — The highest value observed during the specified period. - // Use this value to determine high volumes of activity for your application. + // * Maximum - The highest value observed during the specified period. Use + // this value to determine high volumes of activity for your application. // - // * Sum — All values submitted for the matching metric added together. - // You can use this statistic to determine the total volume of a metric. + // * Sum - All values submitted for the matching metric added together. You + // can use this statistic to determine the total volume of a metric. // - // * Average — The value of Sum / SampleCount during the specified period. + // * Average - The value of Sum / SampleCount during the specified period. // By comparing this statistic with the Minimum and Maximum values, you can // determine the full scope of a metric and how close the average use is // to the Minimum and Maximum values. This comparison helps you to know when // to increase or decrease your resources. // - // * SampleCount — The count, or number, of data points used for the statistical + // * SampleCount - The count, or number, of data points used for the statistical // calculation. // // Statistics is a required field Statistics []*string `locationName:"statistics" type:"list" required:"true"` // The unit for the metric data request. Valid units depend on the metric data - // being required. For the valid units with each available metric, see the metricName - // parameter. + // being requested. For the valid units with each available metric, see the + // metricName parameter. // // Unit is a required field Unit *string `locationName:"unit" type:"string" required:"true" enum:"MetricUnit"` @@ -21793,11 +24962,10 @@ func (s *GetRelationalDatabaseMetricDataInput) SetUnit(v string) *GetRelationalD type GetRelationalDatabaseMetricDataOutput struct { _ struct{} `type:"structure"` - // An object describing the result of your get relational database metric data - // request. + // An array of objects that describe the metric data returned. MetricData []*MetricDatapoint `locationName:"metricData" type:"list"` - // The name of the metric. + // The name of the metric returned. MetricName *string `locationName:"metricName" type:"string" enum:"RelationalDatabaseMetricName"` } @@ -22252,6 +25420,58 @@ func (s *GetStaticIpsOutput) SetStaticIps(v []*StaticIp) *GetStaticIpsOutput { return s } +// Describes the request headers that a Lightsail distribution bases caching +// on. +// +// For the headers that you specify, your distribution caches separate versions +// of the specified content based on the header values in viewer requests. For +// example, suppose viewer requests for logo.jpg contain a custom product header +// that has a value of either acme or apex, and you configure your distribution +// to cache your content based on values in the product header. Your distribution +// forwards the product header to the origin and caches the response from the +// origin once for each header value. +type HeaderObject struct { + _ struct{} `type:"structure"` + + // The specific headers to forward to your distribution's origin. + HeadersAllowList []*string `locationName:"headersAllowList" type:"list"` + + // The headers that you want your distribution to forward to your origin and + // base caching on. + // + // You can configure your distribution to do one of the following: + // + // * all - Forward all headers to your origin. + // + // * none - Forward only the default headers. + // + // * allow-list - Forward only the headers you specify using the headersAllowList + // parameter. + Option *string `locationName:"option" type:"string" enum:"ForwardValues"` +} + +// String returns the string representation +func (s HeaderObject) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s HeaderObject) GoString() string { + return s.String() +} + +// SetHeadersAllowList sets the HeadersAllowList field's value. +func (s *HeaderObject) SetHeadersAllowList(v []*string) *HeaderObject { + s.HeadersAllowList = v + return s +} + +// SetOption sets the Option field's value. +func (s *HeaderObject) SetOption(v string) *HeaderObject { + s.Option = &v + return s +} + // Describes the public SSH host keys or the RDP certificate. type HostKeyAttributes struct { _ struct{} `type:"structure"` @@ -22401,7 +25621,7 @@ type ImportKeyPairOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operation *Operation `locationName:"operation" type:"structure"` } @@ -22422,6 +25642,54 @@ func (s *ImportKeyPairOutput) SetOperation(v *Operation) *ImportKeyPairOutput { return s } +// Describes the origin resource of an Amazon Lightsail content delivery network +// (CDN) distribution. +// +// An origin can be a Lightsail instance or load balancer. A distribution pulls +// content from an origin, caches it, and serves it to viewers via a worldwide +// network of edge servers. +type InputOrigin struct { + _ struct{} `type:"structure"` + + // The name of the origin resource. + Name *string `locationName:"name" type:"string"` + + // The protocol that your Amazon Lightsail distribution uses when establishing + // a connection with your origin to pull content. + ProtocolPolicy *string `locationName:"protocolPolicy" type:"string" enum:"OriginProtocolPolicyEnum"` + + // The AWS Region name of the origin resource. + RegionName *string `locationName:"regionName" type:"string" enum:"RegionName"` +} + +// String returns the string representation +func (s InputOrigin) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InputOrigin) GoString() string { + return s.String() +} + +// SetName sets the Name field's value. +func (s *InputOrigin) SetName(v string) *InputOrigin { + s.Name = &v + return s +} + +// SetProtocolPolicy sets the ProtocolPolicy field's value. +func (s *InputOrigin) SetProtocolPolicy(v string) *InputOrigin { + s.ProtocolPolicy = &v + return s +} + +// SetRegionName sets the RegionName field's value. +func (s *InputOrigin) SetRegionName(v string) *InputOrigin { + s.RegionName = &v + return s +} + // Describes an instance (a virtual private server). type Instance struct { _ struct{} `type:"structure"` @@ -22441,7 +25709,8 @@ type Instance struct { // The bundle for the instance (e.g., micro_1_0). BundleId *string `locationName:"bundleId" type:"string"` - // The timestamp when the instance was created (e.g., 1479734909.17). + // The timestamp when the instance was created (e.g., 1479734909.17) in Unix + // time format. CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` // The size of the vCPU and the amount of RAM for the instance. @@ -22763,13 +26032,20 @@ type InstanceEntry struct { // // The following configuration options are available: // - // * DEFAULT — Use the default firewall settings from the image. + // * DEFAULT - Use the default firewall settings from the Lightsail instance + // blueprint. + // + // * INSTANCE - Use the configured firewall settings from the source Lightsail + // instance. // - // * INSTANCE — Use the firewall settings from the source Lightsail instance. + // * NONE - Use the default Amazon EC2 security group. // - // * NONE — Default to Amazon EC2. + // * CLOSED - All ports closed. // - // * CLOSED — All ports closed. + // If you configured lightsail-connect as a cidrListAliases on your instance, + // or if you chose to allow the Lightsail browser-based SSH or RDP clients to + // connect to your instance, that configuration is not carried over to your + // new Amazon EC2 instance. // // PortInfoSource is a required field PortInfoSource *string `locationName:"portInfoSource" type:"string" required:"true" enum:"PortInfoSourceType"` @@ -23019,26 +26295,56 @@ func (s *InstanceNetworking) SetPorts(v []*InstancePortInfo) *InstanceNetworking return s } -// Describes information about the instance ports. +// Describes information about ports for an Amazon Lightsail instance. type InstancePortInfo struct { _ struct{} `type:"structure"` // The access direction (inbound or outbound). + // + // Lightsail currently supports only inbound access direction. AccessDirection *string `locationName:"accessDirection" type:"string" enum:"AccessDirection"` - // The location from which access is allowed (e.g., Anywhere (0.0.0.0/0)). + // The location from which access is allowed. For example, Anywhere (0.0.0.0/0), + // or Custom if a specific IP address or range of IP addresses is allowed. AccessFrom *string `locationName:"accessFrom" type:"string"` // The type of access (Public or Private). AccessType *string `locationName:"accessType" type:"string" enum:"PortAccessType"` - // The common name. + // An alias that defines access for a preconfigured range of IP addresses. + // + // The only alias currently supported is lightsail-connect, which allows IP + // addresses of the browser-based RDP/SSH client in the Lightsail console to + // connect to your instance. + CidrListAliases []*string `locationName:"cidrListAliases" type:"list"` + + // The IP address, or range of IP addresses in CIDR notation, that are allowed + // to connect to an instance through the ports, and the protocol. Lightsail + // supports IPv4 addresses. + // + // For more information about CIDR block notation, see Classless Inter-Domain + // Routing (https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation) + // on Wikipedia. + Cidrs []*string `locationName:"cidrs" type:"list"` + + // The common name of the port information. CommonName *string `locationName:"commonName" type:"string"` - // The first port in the range. + // The first port in a range of open ports on an instance. + // + // Allowed ports: + // + // * TCP and UDP - 0 to 65535 + // + // * ICMP - The ICMP type. For example, specify 8 as the fromPort (ICMP type), + // and -1 as the toPort (ICMP code), to enable ICMP Ping. For more information, + // see Control Messages (https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol#Control_messages) + // on Wikipedia. FromPort *int64 `locationName:"fromPort" type:"integer"` - // The protocol being used. Can be one of the following. + // The IP protocol name. + // + // The name can be one of the following: // // * tcp - Transmission Control Protocol (TCP) provides reliable, ordered, // and error-checked delivery of streamed data between applications running @@ -23056,9 +26362,25 @@ type InstancePortInfo struct { // can use UDP, which provides a connectionless datagram service that emphasizes // reduced latency over reliability. If you do require reliable data stream // service, use TCP instead. + // + // * icmp - Internet Control Message Protocol (ICMP) is used to send error + // messages and operational information indicating success or failure when + // communicating with an instance. For example, an error is indicated when + // an instance could not be reached. When you specify icmp as the protocol, + // you must specify the ICMP type using the fromPort parameter, and ICMP + // code using the toPort parameter. Protocol *string `locationName:"protocol" type:"string" enum:"NetworkProtocol"` - // The last port in the range. + // The last port in a range of open ports on an instance. + // + // Allowed ports: + // + // * TCP and UDP - 0 to 65535 + // + // * ICMP - The ICMP code. For example, specify 8 as the fromPort (ICMP type), + // and -1 as the toPort (ICMP code), to enable ICMP Ping. For more information, + // see Control Messages (https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol#Control_messages) + // on Wikipedia. ToPort *int64 `locationName:"toPort" type:"integer"` } @@ -23090,6 +26412,18 @@ func (s *InstancePortInfo) SetAccessType(v string) *InstancePortInfo { return s } +// SetCidrListAliases sets the CidrListAliases field's value. +func (s *InstancePortInfo) SetCidrListAliases(v []*string) *InstancePortInfo { + s.CidrListAliases = v + return s +} + +// SetCidrs sets the Cidrs field's value. +func (s *InstancePortInfo) SetCidrs(v []*string) *InstancePortInfo { + s.Cidrs = v + return s +} + // SetCommonName sets the CommonName field's value. func (s *InstancePortInfo) SetCommonName(v string) *InstancePortInfo { s.CommonName = &v @@ -23114,14 +26448,42 @@ func (s *InstancePortInfo) SetToPort(v int64) *InstancePortInfo { return s } -// Describes the port state. +// Describes open ports on an instance, the IP addresses allowed to connect +// to the instance through the ports, and the protocol. type InstancePortState struct { _ struct{} `type:"structure"` - // The first port in the range. + // An alias that defines access for a preconfigured range of IP addresses. + // + // The only alias currently supported is lightsail-connect, which allows IP + // addresses of the browser-based RDP/SSH client in the Lightsail console to + // connect to your instance. + CidrListAliases []*string `locationName:"cidrListAliases" type:"list"` + + // The IP address, or range of IP addresses in CIDR notation, that are allowed + // to connect to an instance through the ports, and the protocol. Lightsail + // supports IPv4 addresses. + // + // For more information about CIDR block notation, see Classless Inter-Domain + // Routing (https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation) + // on Wikipedia. + Cidrs []*string `locationName:"cidrs" type:"list"` + + // The first port in a range of open ports on an instance. + // + // Allowed ports: + // + // * TCP and UDP - 0 to 65535 + // + // * ICMP - The ICMP type. For example, specify 8 as the fromPort (ICMP type), + // and -1 as the toPort (ICMP code), to enable ICMP Ping. For more information, + // see Control Messages (https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol#Control_messages) + // on Wikipedia. FromPort *int64 `locationName:"fromPort" type:"integer"` - // The protocol being used. Can be one of the following. + // The IP protocol name. + // + // The name can be one of the following: // // * tcp - Transmission Control Protocol (TCP) provides reliable, ordered, // and error-checked delivery of streamed data between applications running @@ -23139,12 +26501,30 @@ type InstancePortState struct { // can use UDP, which provides a connectionless datagram service that emphasizes // reduced latency over reliability. If you do require reliable data stream // service, use TCP instead. + // + // * icmp - Internet Control Message Protocol (ICMP) is used to send error + // messages and operational information indicating success or failure when + // communicating with an instance. For example, an error is indicated when + // an instance could not be reached. When you specify icmp as the protocol, + // you must specify the ICMP type using the fromPort parameter, and ICMP + // code using the toPort parameter. Protocol *string `locationName:"protocol" type:"string" enum:"NetworkProtocol"` // Specifies whether the instance port is open or closed. + // + // The port state for Lightsail instances is always open. State *string `locationName:"state" type:"string" enum:"PortState"` - // The last port in the range. + // The last port in a range of open ports on an instance. + // + // Allowed ports: + // + // * TCP and UDP - 0 to 65535 + // + // * ICMP - The ICMP code. For example, specify 8 as the fromPort (ICMP type), + // and -1 as the toPort (ICMP code), to enable ICMP Ping. For more information, + // see Control Messages (https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol#Control_messages) + // on Wikipedia. ToPort *int64 `locationName:"toPort" type:"integer"` } @@ -23158,6 +26538,18 @@ func (s InstancePortState) GoString() string { return s.String() } +// SetCidrListAliases sets the CidrListAliases field's value. +func (s *InstancePortState) SetCidrListAliases(v []*string) *InstancePortState { + s.CidrListAliases = v + return s +} + +// SetCidrs sets the Cidrs field's value. +func (s *InstancePortState) SetCidrs(v []*string) *InstancePortState { + s.Cidrs = v + return s +} + // SetFromPort sets the FromPort field's value. func (s *InstancePortState) SetFromPort(v int64) *InstancePortState { s.FromPort = &v @@ -23617,6 +27009,207 @@ func (s *KeyPair) SetTags(v []*Tag) *KeyPair { return s } +// Describes an Amazon Lightsail content delivery network (CDN) distribution. +type LightsailDistribution struct { + _ struct{} `type:"structure"` + + // Indicates whether the bundle that is currently applied to your distribution, + // specified using the distributionName parameter, can be changed to another + // bundle. + // + // Use the UpdateDistributionBundle action to change your distribution's bundle. + AbleToUpdateBundle *bool `locationName:"ableToUpdateBundle" type:"boolean"` + + // The alternate domain names of the distribution. + AlternativeDomainNames []*string `locationName:"alternativeDomainNames" type:"list"` + + // The Amazon Resource Name (ARN) of the distribution. + Arn *string `locationName:"arn" type:"string"` + + // The ID of the bundle currently applied to the distribution. + BundleId *string `locationName:"bundleId" type:"string"` + + // An object that describes the cache behavior settings of the distribution. + CacheBehaviorSettings *CacheSettings `locationName:"cacheBehaviorSettings" type:"structure"` + + // An array of objects that describe the per-path cache behavior of the distribution. + CacheBehaviors []*CacheBehaviorPerPath `locationName:"cacheBehaviors" type:"list"` + + // The name of the SSL/TLS certificate attached to the distribution, if any. + CertificateName *string `locationName:"certificateName" type:"string"` + + // The timestamp when the distribution was created. + CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + + // An object that describes the default cache behavior of the distribution. + DefaultCacheBehavior *CacheBehavior `locationName:"defaultCacheBehavior" type:"structure"` + + // The domain name of the distribution. + DomainName *string `locationName:"domainName" type:"string"` + + // Indicates whether the distribution is enabled. + IsEnabled *bool `locationName:"isEnabled" type:"boolean"` + + // An object that describes the location of the distribution, such as the AWS + // Region and Availability Zone. + // + // Lightsail distributions are global resources that can reference an origin + // in any AWS Region, and distribute its content globally. However, all distributions + // are located in the us-east-1 Region. + Location *ResourceLocation `locationName:"location" type:"structure"` + + // The name of the distribution. + Name *string `locationName:"name" type:"string"` + + // An object that describes the origin resource of the distribution, such as + // a Lightsail instance or load balancer. + // + // The distribution pulls, caches, and serves content from the origin. + Origin *Origin `locationName:"origin" type:"structure"` + + // The public DNS of the origin. + OriginPublicDNS *string `locationName:"originPublicDNS" type:"string"` + + // The Lightsail resource type (e.g., Distribution). + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` + + // The status of the distribution. + Status *string `locationName:"status" type:"string"` + + // The support code. Include this code in your email to support when you have + // questions about your Lightsail distribution. This code enables our support + // team to look up your Lightsail information more easily. + SupportCode *string `locationName:"supportCode" type:"string"` + + // The tag keys and optional values for the resource. For more information about + // tags in Lightsail, see the Lightsail Dev Guide (https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-tags). + Tags []*Tag `locationName:"tags" type:"list"` +} + +// String returns the string representation +func (s LightsailDistribution) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s LightsailDistribution) GoString() string { + return s.String() +} + +// SetAbleToUpdateBundle sets the AbleToUpdateBundle field's value. +func (s *LightsailDistribution) SetAbleToUpdateBundle(v bool) *LightsailDistribution { + s.AbleToUpdateBundle = &v + return s +} + +// SetAlternativeDomainNames sets the AlternativeDomainNames field's value. +func (s *LightsailDistribution) SetAlternativeDomainNames(v []*string) *LightsailDistribution { + s.AlternativeDomainNames = v + return s +} + +// SetArn sets the Arn field's value. +func (s *LightsailDistribution) SetArn(v string) *LightsailDistribution { + s.Arn = &v + return s +} + +// SetBundleId sets the BundleId field's value. +func (s *LightsailDistribution) SetBundleId(v string) *LightsailDistribution { + s.BundleId = &v + return s +} + +// SetCacheBehaviorSettings sets the CacheBehaviorSettings field's value. +func (s *LightsailDistribution) SetCacheBehaviorSettings(v *CacheSettings) *LightsailDistribution { + s.CacheBehaviorSettings = v + return s +} + +// SetCacheBehaviors sets the CacheBehaviors field's value. +func (s *LightsailDistribution) SetCacheBehaviors(v []*CacheBehaviorPerPath) *LightsailDistribution { + s.CacheBehaviors = v + return s +} + +// SetCertificateName sets the CertificateName field's value. +func (s *LightsailDistribution) SetCertificateName(v string) *LightsailDistribution { + s.CertificateName = &v + return s +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *LightsailDistribution) SetCreatedAt(v time.Time) *LightsailDistribution { + s.CreatedAt = &v + return s +} + +// SetDefaultCacheBehavior sets the DefaultCacheBehavior field's value. +func (s *LightsailDistribution) SetDefaultCacheBehavior(v *CacheBehavior) *LightsailDistribution { + s.DefaultCacheBehavior = v + return s +} + +// SetDomainName sets the DomainName field's value. +func (s *LightsailDistribution) SetDomainName(v string) *LightsailDistribution { + s.DomainName = &v + return s +} + +// SetIsEnabled sets the IsEnabled field's value. +func (s *LightsailDistribution) SetIsEnabled(v bool) *LightsailDistribution { + s.IsEnabled = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *LightsailDistribution) SetLocation(v *ResourceLocation) *LightsailDistribution { + s.Location = v + return s +} + +// SetName sets the Name field's value. +func (s *LightsailDistribution) SetName(v string) *LightsailDistribution { + s.Name = &v + return s +} + +// SetOrigin sets the Origin field's value. +func (s *LightsailDistribution) SetOrigin(v *Origin) *LightsailDistribution { + s.Origin = v + return s +} + +// SetOriginPublicDNS sets the OriginPublicDNS field's value. +func (s *LightsailDistribution) SetOriginPublicDNS(v string) *LightsailDistribution { + s.OriginPublicDNS = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *LightsailDistribution) SetResourceType(v string) *LightsailDistribution { + s.ResourceType = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *LightsailDistribution) SetStatus(v string) *LightsailDistribution { + s.Status = &v + return s +} + +// SetSupportCode sets the SupportCode field's value. +func (s *LightsailDistribution) SetSupportCode(v string) *LightsailDistribution { + s.SupportCode = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *LightsailDistribution) SetTags(v []*Tag) *LightsailDistribution { + s.Tags = v + return s +} + // Describes the Lightsail load balancer. type LoadBalancer struct { _ struct{} `type:"structure"` @@ -23808,7 +27401,47 @@ type LoadBalancerTlsCertificate struct { // the records. DomainValidationRecords []*LoadBalancerTlsCertificateDomainValidationRecord `locationName:"domainValidationRecords" type:"list"` - // The reason for the SSL/TLS certificate validation failure. + // The validation failure reason, if any, of the certificate. + // + // The following failure reasons are possible: + // + // * NO_AVAILABLE_CONTACTS - This failure applies to email validation, which + // is not available for Lightsail certificates. + // + // * ADDITIONAL_VERIFICATION_REQUIRED - Lightsail requires additional information + // to process this certificate request. This can happen as a fraud-protection + // measure, such as when the domain ranks within the Alexa top 1000 websites. + // To provide the required information, use the AWS Support Center (https://console.aws.amazon.com/support/home) + // to contact AWS Support. You cannot request a certificate for Amazon-owned + // domain names such as those ending in amazonaws.com, cloudfront.net, or + // elasticbeanstalk.com. + // + // * DOMAIN_NOT_ALLOWED - One or more of the domain names in the certificate + // request was reported as an unsafe domain by VirusTotal (https://www.virustotal.com/gui/home/url). + // To correct the problem, search for your domain name on the VirusTotal + // (https://www.virustotal.com/gui/home/url) website. If your domain is reported + // as suspicious, see Google Help for Hacked Websites (https://www.google.com/webmasters/hacked/?hl=en) + // to learn what you can do. If you believe that the result is a false positive, + // notify the organization that is reporting the domain. VirusTotal is an + // aggregate of several antivirus and URL scanners and cannot remove your + // domain from a block list itself. After you correct the problem and the + // VirusTotal registry has been updated, request a new certificate. If you + // see this error and your domain is not included in the VirusTotal list, + // visit the AWS Support Center (https://console.aws.amazon.com/support/home) + // and create a case. + // + // * INVALID_PUBLIC_DOMAIN - One or more of the domain names in the certificate + // request is not valid. Typically, this is because a domain name in the + // request is not a valid top-level domain. Try to request a certificate + // again, correcting any spelling errors or typos that were in the failed + // request, and ensure that all domain names in the request are for valid + // top-level domains. For example, you cannot request a certificate for example.invalidpublicdomain + // because invalidpublicdomain is not a valid top-level domain. + // + // * OTHER - Typically, this failure occurs when there is a typographical + // error in one or more of the domain names in the certificate request. Try + // to request a certificate again, correcting any spelling errors or typos + // that were in the failed request. FailureReason *string `locationName:"failureReason" type:"string" enum:"LoadBalancerTlsCertificateFailureReason"` // When true, the SSL/TLS certificate is attached to the Lightsail load balancer. @@ -23820,8 +27453,7 @@ type LoadBalancerTlsCertificate struct { // The issuer of the certificate. Issuer *string `locationName:"issuer" type:"string"` - // The algorithm that was used to generate the key pair (the public and private - // key). + // The algorithm used to generate the key pair (the public and private key). KeyAlgorithm *string `locationName:"keyAlgorithm" type:"string"` // The load balancer name where your SSL/TLS certificate is attached. @@ -23839,8 +27471,8 @@ type LoadBalancerTlsCertificate struct { // The timestamp when the SSL/TLS certificate is first valid. NotBefore *time.Time `locationName:"notBefore" type:"timestamp"` - // An object containing information about the status of Lightsail's managed - // renewal for the certificate. + // An object that describes the status of the certificate renewal managed by + // Lightsail. RenewalSummary *LoadBalancerTlsCertificateRenewalSummary `locationName:"renewalSummary" type:"structure"` // The resource type (e.g., LoadBalancerTlsCertificate). @@ -23867,10 +27499,12 @@ type LoadBalancerTlsCertificate struct { // * DiskSnapshot - A block storage disk snapshot ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - // The reason the certificate was revoked. Valid values are below. + // The reason the certificate was revoked. This value is present only when the + // certificate status is REVOKED. RevocationReason *string `locationName:"revocationReason" type:"string" enum:"LoadBalancerTlsCertificateRevocationReason"` - // The timestamp when the SSL/TLS certificate was revoked. + // The timestamp when the certificate was revoked. This value is present only + // when the certificate status is REVOKED. RevokedAt *time.Time `locationName:"revokedAt" type:"timestamp"` // The serial number of the certificate. @@ -23879,18 +27513,15 @@ type LoadBalancerTlsCertificate struct { // The algorithm that was used to sign the certificate. SignatureAlgorithm *string `locationName:"signatureAlgorithm" type:"string"` - // The status of the SSL/TLS certificate. Valid values are below. + // The validation status of the SSL/TLS certificate. Valid values are below. Status *string `locationName:"status" type:"string" enum:"LoadBalancerTlsCertificateStatus"` // The name of the entity that is associated with the public key contained in // the certificate. Subject *string `locationName:"subject" type:"string"` - // One or more domains or subdomains included in the certificate. This list - // contains the domain names that are bound to the public key that is contained - // in the certificate. The subject alternative names include the canonical domain - // name (CNAME) of the certificate and additional domain names that can be used - // to connect to the website, such as example.com, www.example.com, or m.example.com. + // An array of strings that specify the alternate domains (e.g., example2.com) + // and subdomains (e.g., blog.example.com) for the certificate. SubjectAlternativeNames []*string `locationName:"subjectAlternativeNames" type:"list"` // The support code. Include this code in your email to support when you have @@ -24160,6 +27791,26 @@ func (s *LoadBalancerTlsCertificateDomainValidationRecord) SetValue(v string) *L // Contains information about the status of Lightsail's managed renewal for // the certificate. +// +// The renewal status of the certificate. +// +// The following renewal status are possible: +// +// * PendingAutoRenewal - Lightsail is attempting to automatically validate +// the domain names in the certificate. No further action is required. +// +// * PendingValidation - Lightsail couldn't automatically validate one or +// more domain names in the certificate. You must take action to validate +// these domain names or the certificate won't be renewed. If you used DNS +// validation, check to make sure your certificate's domain validation records +// exist in your domain's DNS, and that your certificate remains in use. +// +// * Success - All domain names in the certificate are validated, and Lightsail +// renewed the certificate. No further action is required. +// +// * Failed - One or more domain names were not validated before the certificate +// expired, and Lightsail did not renew the certificate. You can request +// a new certificate using the CreateCertificate action. type LoadBalancerTlsCertificateRenewalSummary struct { _ struct{} `type:"structure"` @@ -24168,8 +27819,25 @@ type LoadBalancerTlsCertificateRenewalSummary struct { // initial validation that occurs as a result of the RequestCertificate request. DomainValidationOptions []*LoadBalancerTlsCertificateDomainValidationOption `locationName:"domainValidationOptions" type:"list"` - // The status of Lightsail's managed renewal of the certificate. Valid values - // are listed below. + // The renewal status of the certificate. + // + // The following renewal status are possible: + // + // * PendingAutoRenewal - Lightsail is attempting to automatically validate + // the domain names of the certificate. No further action is required. + // + // * PendingValidation - Lightsail couldn't automatically validate one or + // more domain names of the certificate. You must take action to validate + // these domain names or the certificate won't be renewed. Check to make + // sure your certificate's domain validation records exist in your domain's + // DNS, and that your certificate remains in use. + // + // * Success - All domain names in the certificate are validated, and Lightsail + // renewed the certificate. No further action is required. + // + // * Failed - One or more domain names were not validated before the certificate + // expired, and Lightsail did not renew the certificate. You can request + // a new certificate using the CreateCertificate action. RenewalStatus *string `locationName:"renewalStatus" type:"string" enum:"LoadBalancerTlsCertificateRenewalStatus"` } @@ -24477,12 +28145,12 @@ func (s *NotFoundException) RequestID() string { type OpenInstancePublicPortsInput struct { _ struct{} `type:"structure"` - // The name of the instance for which you want to open the public ports. + // The name of the instance for which to open ports. // // InstanceName is a required field InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - // An array of key-value pairs containing information about the port mappings. + // An object to describe the ports to open for the specified instance. // // PortInfo is a required field PortInfo *PortInfo `locationName:"portInfo" type:"structure" required:"true"` @@ -24507,6 +28175,11 @@ func (s *OpenInstancePublicPortsInput) Validate() error { if s.PortInfo == nil { invalidParams.Add(request.NewErrParamRequired("PortInfo")) } + if s.PortInfo != nil { + if err := s.PortInfo.Validate(); err != nil { + invalidParams.AddNested("PortInfo", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -24530,7 +28203,7 @@ type OpenInstancePublicPortsOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operation *Operation `locationName:"operation" type:"structure"` } @@ -24736,6 +28409,63 @@ func (s *OperationFailureException) RequestID() string { return s.RespMetadata.RequestID } +// Describes the origin resource of an Amazon Lightsail content delivery network +// (CDN) distribution. +// +// An origin can be a Lightsail instance or load balancer. A distribution pulls +// content from an origin, caches it, and serves it to viewers via a worldwide +// network of edge servers. +type Origin struct { + _ struct{} `type:"structure"` + + // The name of the origin resource. + Name *string `locationName:"name" type:"string"` + + // The protocol that your Amazon Lightsail distribution uses when establishing + // a connection with your origin to pull content. + ProtocolPolicy *string `locationName:"protocolPolicy" type:"string" enum:"OriginProtocolPolicyEnum"` + + // The AWS Region name of the origin resource. + RegionName *string `locationName:"regionName" type:"string" enum:"RegionName"` + + // The resource type of the origin resource (e.g., Instance). + ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` +} + +// String returns the string representation +func (s Origin) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Origin) GoString() string { + return s.String() +} + +// SetName sets the Name field's value. +func (s *Origin) SetName(v string) *Origin { + s.Name = &v + return s +} + +// SetProtocolPolicy sets the ProtocolPolicy field's value. +func (s *Origin) SetProtocolPolicy(v string) *Origin { + s.ProtocolPolicy = &v + return s +} + +// SetRegionName sets the RegionName field's value. +func (s *Origin) SetRegionName(v string) *Origin { + s.RegionName = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *Origin) SetResourceType(v string) *Origin { + s.ResourceType = &v + return s +} + // The password data for the Windows Server-based instance, including the ciphertext // and the key pair name. type PasswordData struct { @@ -24806,7 +28536,7 @@ type PeerVpcOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operation *Operation `locationName:"operation" type:"structure"` } @@ -24911,18 +28641,84 @@ func (s *PendingModifiedRelationalDatabaseValues) SetMasterUserPassword(v string return s } -// Describes information about the ports on your virtual private server (or -// instance). +// Describes ports to open on an instance, the IP addresses allowed to connect +// to the instance through the ports, and the protocol. type PortInfo struct { _ struct{} `type:"structure"` - // The first port in the range. + // An alias that defines access for a preconfigured range of IP addresses. + // + // The only alias currently supported is lightsail-connect, which allows IP + // addresses of the browser-based RDP/SSH client in the Lightsail console to + // connect to your instance. + CidrListAliases []*string `locationName:"cidrListAliases" type:"list"` + + // The IP address, or range of IP addresses in CIDR notation, that are allowed + // to connect to an instance through the ports, and the protocol. Lightsail + // supports IPv4 addresses. + // + // Examples: + // + // * To allow the IP address 192.0.2.44, specify 192.0.2.44 or 192.0.2.44/32. + // + // * To allow the IP addresses 192.0.2.0 to 192.0.2.255, specify 192.0.2.0/24. + // + // For more information about CIDR block notation, see Classless Inter-Domain + // Routing (https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation) + // on Wikipedia. + Cidrs []*string `locationName:"cidrs" type:"list"` + + // The first port in a range of open ports on an instance. + // + // Allowed ports: + // + // * TCP and UDP - 0 to 65535 + // + // * ICMP - The ICMP type. For example, specify 8 as the fromPort (ICMP type), + // and -1 as the toPort (ICMP code), to enable ICMP Ping. For more information, + // see Control Messages (https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol#Control_messages) + // on Wikipedia. FromPort *int64 `locationName:"fromPort" type:"integer"` - // The protocol. + // The IP protocol name. + // + // The name can be one of the following: + // + // * tcp - Transmission Control Protocol (TCP) provides reliable, ordered, + // and error-checked delivery of streamed data between applications running + // on hosts communicating by an IP network. If you have an application that + // doesn't require reliable data stream service, use UDP instead. + // + // * all - All transport layer protocol types. For more general information, + // see Transport layer (https://en.wikipedia.org/wiki/Transport_layer) on + // Wikipedia. + // + // * udp - With User Datagram Protocol (UDP), computer applications can send + // messages (or datagrams) to other hosts on an Internet Protocol (IP) network. + // Prior communications are not required to set up transmission channels + // or data paths. Applications that don't require reliable data stream service + // can use UDP, which provides a connectionless datagram service that emphasizes + // reduced latency over reliability. If you do require reliable data stream + // service, use TCP instead. + // + // * icmp - Internet Control Message Protocol (ICMP) is used to send error + // messages and operational information indicating success or failure when + // communicating with an instance. For example, an error is indicated when + // an instance could not be reached. When you specify icmp as the protocol, + // you must specify the ICMP type using the fromPort parameter, and ICMP + // code using the toPort parameter. Protocol *string `locationName:"protocol" type:"string" enum:"NetworkProtocol"` - // The last port in the range. + // The last port in a range of open ports on an instance. + // + // Allowed ports: + // + // * TCP and UDP - 0 to 65535 + // + // * ICMP - The ICMP code. For example, specify 8 as the fromPort (ICMP type), + // and -1 as the toPort (ICMP code), to enable ICMP Ping. For more information, + // see Control Messages (https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol#Control_messages) + // on Wikipedia. ToPort *int64 `locationName:"toPort" type:"integer"` } @@ -24936,6 +28732,34 @@ func (s PortInfo) GoString() string { return s.String() } +// Validate inspects the fields of the type to determine if they are valid. +func (s *PortInfo) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PortInfo"} + if s.FromPort != nil && *s.FromPort < -1 { + invalidParams.Add(request.NewErrParamMinValue("FromPort", -1)) + } + if s.ToPort != nil && *s.ToPort < -1 { + invalidParams.Add(request.NewErrParamMinValue("ToPort", -1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCidrListAliases sets the CidrListAliases field's value. +func (s *PortInfo) SetCidrListAliases(v []*string) *PortInfo { + s.CidrListAliases = v + return s +} + +// SetCidrs sets the Cidrs field's value. +func (s *PortInfo) SetCidrs(v []*string) *PortInfo { + s.Cidrs = v + return s +} + // SetFromPort sets the FromPort field's value. func (s *PortInfo) SetFromPort(v int64) *PortInfo { s.FromPort = &v @@ -25011,8 +28835,9 @@ type PutAlarmInput struct { // // The following metrics are available for each resource type: // - // * Instances: CPUUtilization, NetworkIn, NetworkOut, StatusCheckFailed, - // StatusCheckFailed_Instance, and StatusCheckFailed_System. + // * Instances: BurstCapacityPercentage, BurstCapacityTime, CPUUtilization, + // NetworkIn, NetworkOut, StatusCheckFailed, StatusCheckFailed_Instance, + // and StatusCheckFailed_System. // // * Load balancers: ClientTLSNegotiationErrorCount, HealthyHostCount, UnhealthyHostCount, // HTTPCode_LB_4XX_Count, HTTPCode_LB_5XX_Count, HTTPCode_Instance_2XX_Count, @@ -25022,6 +28847,9 @@ type PutAlarmInput struct { // * Relational databases: CPUUtilization, DatabaseConnections, DiskQueueDepth, // FreeStorageSpace, NetworkReceiveThroughput, and NetworkTransmitThroughput. // + // For more information about these metrics, see Metrics available in Lightsail + // (https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-resource-health-metrics#available-metrics). + // // MetricName is a required field MetricName *string `locationName:"metricName" type:"string" required:"true" enum:"MetricName"` @@ -25042,13 +28870,13 @@ type PutAlarmInput struct { // // An alarm has the following possible states: // - // * ALARM — The metric is outside of the defined threshold. + // * ALARM - The metric is outside of the defined threshold. // - // * INSUFFICIENT_DATA — The alarm has just started, the metric is not - // available, or not enough data is available for the metric to determine - // the alarm state. + // * INSUFFICIENT_DATA - The alarm has just started, the metric is not available, + // or not enough data is available for the metric to determine the alarm + // state. // - // * OK — The metric is within the defined threshold. + // * OK - The metric is within the defined threshold. // // When you specify a notification trigger, the ALARM state must be specified. // The INSUFFICIENT_DATA and OK states can be specified in addition to the ALARM @@ -25074,16 +28902,16 @@ type PutAlarmInput struct { // // An alarm can treat missing data in the following ways: // - // * breaching — Assume the missing data is not within the threshold. Missing + // * breaching - Assume the missing data is not within the threshold. Missing // data counts towards the number of times the metric is not within the threshold. // - // * notBreaching — Assume the missing data is within the threshold. Missing + // * notBreaching - Assume the missing data is within the threshold. Missing // data does not count towards the number of times the metric is not within // the threshold. // - // * ignore — Ignore the missing data. Maintains the current alarm state. + // * ignore - Ignore the missing data. Maintains the current alarm state. // - // * missing — Missing data is treated as missing. + // * missing - Missing data is treated as missing. // // If treatMissingData is not specified, the default behavior of missing is // used. @@ -25198,7 +29026,7 @@ type PutAlarmOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -25222,12 +29050,12 @@ func (s *PutAlarmOutput) SetOperations(v []*Operation) *PutAlarmOutput { type PutInstancePublicPortsInput struct { _ struct{} `type:"structure"` - // The Lightsail instance name of the public port(s) you are setting. + // The name of the instance for which to open ports. // // InstanceName is a required field InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - // Specifies information about the public port(s). + // An array of objects to describe the ports to open for the specified instance. // // PortInfos is a required field PortInfos []*PortInfo `locationName:"portInfos" type:"list" required:"true"` @@ -25252,6 +29080,16 @@ func (s *PutInstancePublicPortsInput) Validate() error { if s.PortInfos == nil { invalidParams.Add(request.NewErrParamRequired("PortInfos")) } + if s.PortInfos != nil { + for i, v := range s.PortInfos { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "PortInfos", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -25275,7 +29113,7 @@ type PutInstancePublicPortsOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operation *Operation `locationName:"operation" type:"structure"` } @@ -25296,6 +29134,49 @@ func (s *PutInstancePublicPortsOutput) SetOperation(v *Operation) *PutInstancePu return s } +// Describes the query string parameters that an Amazon Lightsail content delivery +// network (CDN) distribution to bases caching on. +// +// For the query strings that you specify, your distribution caches separate +// versions of the specified content based on the query string values in viewer +// requests. +type QueryStringObject struct { + _ struct{} `type:"structure"` + + // Indicates whether the distribution forwards and caches based on query strings. + Option *bool `locationName:"option" type:"boolean"` + + // The specific query strings that the distribution forwards to the origin. + // + // Your distribution will cache content based on the specified query strings. + // + // If the option parameter is true, then your distribution forwards all query + // strings, regardless of what you specify using the queryStringsAllowList parameter. + QueryStringsAllowList []*string `locationName:"queryStringsAllowList" type:"list"` +} + +// String returns the string representation +func (s QueryStringObject) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s QueryStringObject) GoString() string { + return s.String() +} + +// SetOption sets the Option field's value. +func (s *QueryStringObject) SetOption(v bool) *QueryStringObject { + s.Option = &v + return s +} + +// SetQueryStringsAllowList sets the QueryStringsAllowList field's value. +func (s *QueryStringObject) SetQueryStringsAllowList(v []*string) *QueryStringObject { + s.QueryStringsAllowList = v + return s +} + type RebootInstanceInput struct { _ struct{} `type:"structure"` @@ -25338,7 +29219,7 @@ type RebootInstanceOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -25401,7 +29282,7 @@ type RebootRelationalDatabaseOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -26336,7 +30217,7 @@ type ReleaseStaticIpOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -26357,6 +30238,145 @@ func (s *ReleaseStaticIpOutput) SetOperations(v []*Operation) *ReleaseStaticIpOu return s } +// Describes the status of a SSL/TLS certificate renewal managed by Amazon Lightsail. +type RenewalSummary struct { + _ struct{} `type:"structure"` + + // An array of objects that describe the domain validation records of the certificate. + DomainValidationRecords []*DomainValidationRecord `locationName:"domainValidationRecords" type:"list"` + + // The renewal status of the certificate. + // + // The following renewal status are possible: + // + // * PendingAutoRenewal - Lightsail is attempting to automatically validate + // the domain names of the certificate. No further action is required. + // + // * PendingValidation - Lightsail couldn't automatically validate one or + // more domain names of the certificate. You must take action to validate + // these domain names or the certificate won't be renewed. Check to make + // sure your certificate's domain validation records exist in your domain's + // DNS, and that your certificate remains in use. + // + // * Success - All domain names in the certificate are validated, and Lightsail + // renewed the certificate. No further action is required. + // + // * Failed - One or more domain names were not validated before the certificate + // expired, and Lightsail did not renew the certificate. You can request + // a new certificate using the CreateCertificate action. + RenewalStatus *string `locationName:"renewalStatus" type:"string" enum:"RenewalStatus"` + + // The reason for the renewal status of the certificate. + RenewalStatusReason *string `locationName:"renewalStatusReason" type:"string"` + + // The timestamp when the certificate was last updated. + UpdatedAt *time.Time `locationName:"updatedAt" type:"timestamp"` +} + +// String returns the string representation +func (s RenewalSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RenewalSummary) GoString() string { + return s.String() +} + +// SetDomainValidationRecords sets the DomainValidationRecords field's value. +func (s *RenewalSummary) SetDomainValidationRecords(v []*DomainValidationRecord) *RenewalSummary { + s.DomainValidationRecords = v + return s +} + +// SetRenewalStatus sets the RenewalStatus field's value. +func (s *RenewalSummary) SetRenewalStatus(v string) *RenewalSummary { + s.RenewalStatus = &v + return s +} + +// SetRenewalStatusReason sets the RenewalStatusReason field's value. +func (s *RenewalSummary) SetRenewalStatusReason(v string) *RenewalSummary { + s.RenewalStatusReason = &v + return s +} + +// SetUpdatedAt sets the UpdatedAt field's value. +func (s *RenewalSummary) SetUpdatedAt(v time.Time) *RenewalSummary { + s.UpdatedAt = &v + return s +} + +type ResetDistributionCacheInput struct { + _ struct{} `type:"structure"` + + // The name of the distribution for which to reset cache. + // + // Use the GetDistributions action to get a list of distribution names that + // you can specify. + DistributionName *string `locationName:"distributionName" type:"string"` +} + +// String returns the string representation +func (s ResetDistributionCacheInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResetDistributionCacheInput) GoString() string { + return s.String() +} + +// SetDistributionName sets the DistributionName field's value. +func (s *ResetDistributionCacheInput) SetDistributionName(v string) *ResetDistributionCacheInput { + s.DistributionName = &v + return s +} + +type ResetDistributionCacheOutput struct { + _ struct{} `type:"structure"` + + // The timestamp of the reset cache request (e.g., 1479734909.17) in Unix time + // format. + CreateTime *time.Time `locationName:"createTime" type:"timestamp"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operation *Operation `locationName:"operation" type:"structure"` + + // The status of the reset cache request. + Status *string `locationName:"status" type:"string"` +} + +// String returns the string representation +func (s ResetDistributionCacheOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResetDistributionCacheOutput) GoString() string { + return s.String() +} + +// SetCreateTime sets the CreateTime field's value. +func (s *ResetDistributionCacheOutput) SetCreateTime(v time.Time) *ResetDistributionCacheOutput { + s.CreateTime = &v + return s +} + +// SetOperation sets the Operation field's value. +func (s *ResetDistributionCacheOutput) SetOperation(v *Operation) *ResetDistributionCacheOutput { + s.Operation = v + return s +} + +// SetStatus sets the Status field's value. +func (s *ResetDistributionCacheOutput) SetStatus(v string) *ResetDistributionCacheOutput { + s.Status = &v + return s +} + // Describes the resource location. type ResourceLocation struct { _ struct{} `type:"structure"` @@ -26390,6 +30410,49 @@ func (s *ResourceLocation) SetRegionName(v string) *ResourceLocation { return s } +// Describes the domain name system (DNS) records to add to your domain's DNS +// to validate it for an Amazon Lightsail certificate. +type ResourceRecord struct { + _ struct{} `type:"structure"` + + // The name of the record. + Name *string `locationName:"name" type:"string"` + + // The DNS record type. + Type *string `locationName:"type" type:"string"` + + // The value for the DNS record. + Value *string `locationName:"value" type:"string"` +} + +// String returns the string representation +func (s ResourceRecord) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResourceRecord) GoString() string { + return s.String() +} + +// SetName sets the Name field's value. +func (s *ResourceRecord) SetName(v string) *ResourceRecord { + s.Name = &v + return s +} + +// SetType sets the Type field's value. +func (s *ResourceRecord) SetType(v string) *ResourceRecord { + s.Type = &v + return s +} + +// SetValue sets the Value field's value. +func (s *ResourceRecord) SetValue(v string) *ResourceRecord { + s.Value = &v + return s +} + type SendContactMethodVerificationInput struct { _ struct{} `type:"structure"` @@ -26432,7 +30495,7 @@ type SendContactMethodVerificationOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -26557,7 +30620,7 @@ type StartInstanceOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -26620,7 +30683,7 @@ type StartRelationalDatabaseOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -26795,7 +30858,7 @@ type StopInstanceOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -26868,7 +30931,7 @@ type StopRelationalDatabaseOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -26997,7 +31060,7 @@ type TagResourceOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -27030,13 +31093,13 @@ type TestAlarmInput struct { // // An alarm has the following possible states that can be tested: // - // * ALARM — The metric is outside of the defined threshold. + // * ALARM - The metric is outside of the defined threshold. // - // * INSUFFICIENT_DATA — The alarm has just started, the metric is not - // available, or not enough data is available for the metric to determine - // the alarm state. + // * INSUFFICIENT_DATA - The alarm has just started, the metric is not available, + // or not enough data is available for the metric to determine the alarm + // state. // - // * OK — The metric is within the defined threshold. + // * OK - The metric is within the defined threshold. // // State is a required field State *string `locationName:"state" type:"string" required:"true" enum:"AlarmState"` @@ -27084,7 +31147,7 @@ type TestAlarmOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -27185,7 +31248,7 @@ type UnpeerVpcOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operation *Operation `locationName:"operation" type:"structure"` } @@ -27250,46 +31313,224 @@ func (s *UntagResourceInput) Validate() error { return nil } -// SetResourceArn sets the ResourceArn field's value. -func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { - s.ResourceArn = &v +// SetResourceArn sets the ResourceArn field's value. +func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { + s.ResourceArn = &v + return s +} + +// SetResourceName sets the ResourceName field's value. +func (s *UntagResourceInput) SetResourceName(v string) *UntagResourceInput { + s.ResourceName = &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"` + + // An array of objects that describe the result of the action, such as the status + // of the request, the timestamp of the request, and the resources affected + // by the request. + Operations []*Operation `locationName:"operations" type:"list"` +} + +// 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() +} + +// SetOperations sets the Operations field's value. +func (s *UntagResourceOutput) SetOperations(v []*Operation) *UntagResourceOutput { + s.Operations = v + return s +} + +type UpdateDistributionBundleInput struct { + _ struct{} `type:"structure"` + + // The bundle ID of the new bundle to apply to your distribution. + // + // Use the GetDistributionBundles action to get a list of distribution bundle + // IDs that you can specify. + BundleId *string `locationName:"bundleId" type:"string"` + + // The name of the distribution for which to update the bundle. + // + // Use the GetDistributions action to get a list of distribution names that + // you can specify. + DistributionName *string `locationName:"distributionName" type:"string"` +} + +// String returns the string representation +func (s UpdateDistributionBundleInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateDistributionBundleInput) GoString() string { + return s.String() +} + +// SetBundleId sets the BundleId field's value. +func (s *UpdateDistributionBundleInput) SetBundleId(v string) *UpdateDistributionBundleInput { + s.BundleId = &v + return s +} + +// SetDistributionName sets the DistributionName field's value. +func (s *UpdateDistributionBundleInput) SetDistributionName(v string) *UpdateDistributionBundleInput { + s.DistributionName = &v + return s +} + +type UpdateDistributionBundleOutput struct { + _ struct{} `type:"structure"` + + // Describes the API operation. + Operation *Operation `locationName:"operation" type:"structure"` +} + +// String returns the string representation +func (s UpdateDistributionBundleOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateDistributionBundleOutput) GoString() string { + return s.String() +} + +// SetOperation sets the Operation field's value. +func (s *UpdateDistributionBundleOutput) SetOperation(v *Operation) *UpdateDistributionBundleOutput { + s.Operation = v + return s +} + +type UpdateDistributionInput struct { + _ struct{} `type:"structure"` + + // An object that describes the cache behavior settings for the distribution. + // + // The cacheBehaviorSettings specified in your UpdateDistributionRequest will + // replace your distribution's existing settings. + CacheBehaviorSettings *CacheSettings `locationName:"cacheBehaviorSettings" type:"structure"` + + // An array of objects that describe the per-path cache behavior for the distribution. + CacheBehaviors []*CacheBehaviorPerPath `locationName:"cacheBehaviors" type:"list"` + + // An object that describes the default cache behavior for the distribution. + DefaultCacheBehavior *CacheBehavior `locationName:"defaultCacheBehavior" type:"structure"` + + // The name of the distribution to update. + // + // Use the GetDistributions action to get a list of distribution names that + // you can specify. + // + // DistributionName is a required field + DistributionName *string `locationName:"distributionName" type:"string" required:"true"` + + // Indicates whether to enable the distribution. + IsEnabled *bool `locationName:"isEnabled" type:"boolean"` + + // An object that describes the origin resource for the distribution, such as + // a Lightsail instance or load balancer. + // + // The distribution pulls, caches, and serves content from the origin. + Origin *InputOrigin `locationName:"origin" type:"structure"` +} + +// String returns the string representation +func (s UpdateDistributionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateDistributionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateDistributionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateDistributionInput"} + if s.DistributionName == nil { + invalidParams.Add(request.NewErrParamRequired("DistributionName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCacheBehaviorSettings sets the CacheBehaviorSettings field's value. +func (s *UpdateDistributionInput) SetCacheBehaviorSettings(v *CacheSettings) *UpdateDistributionInput { + s.CacheBehaviorSettings = v return s } -// SetResourceName sets the ResourceName field's value. -func (s *UntagResourceInput) SetResourceName(v string) *UntagResourceInput { - s.ResourceName = &v +// SetCacheBehaviors sets the CacheBehaviors field's value. +func (s *UpdateDistributionInput) SetCacheBehaviors(v []*CacheBehaviorPerPath) *UpdateDistributionInput { + s.CacheBehaviors = v return s } -// SetTagKeys sets the TagKeys field's value. -func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { - s.TagKeys = v +// SetDefaultCacheBehavior sets the DefaultCacheBehavior field's value. +func (s *UpdateDistributionInput) SetDefaultCacheBehavior(v *CacheBehavior) *UpdateDistributionInput { + s.DefaultCacheBehavior = v return s } -type UntagResourceOutput struct { +// SetDistributionName sets the DistributionName field's value. +func (s *UpdateDistributionInput) SetDistributionName(v string) *UpdateDistributionInput { + s.DistributionName = &v + return s +} + +// SetIsEnabled sets the IsEnabled field's value. +func (s *UpdateDistributionInput) SetIsEnabled(v bool) *UpdateDistributionInput { + s.IsEnabled = &v + return s +} + +// SetOrigin sets the Origin field's value. +func (s *UpdateDistributionInput) SetOrigin(v *InputOrigin) *UpdateDistributionInput { + s.Origin = v + return s +} + +type UpdateDistributionOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. - Operations []*Operation `locationName:"operations" type:"list"` + Operation *Operation `locationName:"operation" type:"structure"` } // String returns the string representation -func (s UntagResourceOutput) String() string { +func (s UpdateDistributionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UntagResourceOutput) GoString() string { +func (s UpdateDistributionOutput) GoString() string { return s.String() } -// SetOperations sets the Operations field's value. -func (s *UntagResourceOutput) SetOperations(v []*Operation) *UntagResourceOutput { - s.Operations = v +// SetOperation sets the Operation field's value. +func (s *UpdateDistributionOutput) SetOperation(v *Operation) *UpdateDistributionOutput { + s.Operation = v return s } @@ -27349,7 +31590,7 @@ type UpdateDomainEntryOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -27443,7 +31684,7 @@ type UpdateLoadBalancerAttributeOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -27636,7 +31877,7 @@ type UpdateRelationalDatabaseOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -27713,7 +31954,7 @@ type UpdateRelationalDatabaseParametersOutput struct { _ struct{} `type:"structure"` // An array of objects that describe the result of the action, such as the status - // of the request, the time stamp of the request, and the resources affected + // of the request, the timestamp of the request, and the resources affected // by the request. Operations []*Operation `locationName:"operations" type:"list"` } @@ -27742,11 +31983,26 @@ const ( AccessDirectionOutbound = "outbound" ) +// AccessDirection_Values returns all elements of the AccessDirection enum +func AccessDirection_Values() []string { + return []string{ + AccessDirectionInbound, + AccessDirectionOutbound, + } +} + const ( // AddOnTypeAutoSnapshot is a AddOnType enum value AddOnTypeAutoSnapshot = "AutoSnapshot" ) +// AddOnType_Values returns all elements of the AddOnType enum +func AddOnType_Values() []string { + return []string{ + AddOnTypeAutoSnapshot, + } +} + const ( // AlarmStateOk is a AlarmState enum value AlarmStateOk = "OK" @@ -27758,6 +32014,15 @@ const ( AlarmStateInsufficientData = "INSUFFICIENT_DATA" ) +// AlarmState_Values returns all elements of the AlarmState enum +func AlarmState_Values() []string { + return []string{ + AlarmStateOk, + AlarmStateAlarm, + AlarmStateInsufficientData, + } +} + const ( // AutoSnapshotStatusSuccess is a AutoSnapshotStatus enum value AutoSnapshotStatusSuccess = "Success" @@ -27772,6 +32037,32 @@ const ( AutoSnapshotStatusNotFound = "NotFound" ) +// AutoSnapshotStatus_Values returns all elements of the AutoSnapshotStatus enum +func AutoSnapshotStatus_Values() []string { + return []string{ + AutoSnapshotStatusSuccess, + AutoSnapshotStatusFailed, + AutoSnapshotStatusInProgress, + AutoSnapshotStatusNotFound, + } +} + +const ( + // BehaviorEnumDontCache is a BehaviorEnum enum value + BehaviorEnumDontCache = "dont-cache" + + // BehaviorEnumCache is a BehaviorEnum enum value + BehaviorEnumCache = "cache" +) + +// BehaviorEnum_Values returns all elements of the BehaviorEnum enum +func BehaviorEnum_Values() []string { + return []string{ + BehaviorEnumDontCache, + BehaviorEnumCache, + } +} + const ( // BlueprintTypeOs is a BlueprintType enum value BlueprintTypeOs = "os" @@ -27780,11 +32071,62 @@ const ( BlueprintTypeApp = "app" ) +// BlueprintType_Values returns all elements of the BlueprintType enum +func BlueprintType_Values() []string { + return []string{ + BlueprintTypeOs, + BlueprintTypeApp, + } +} + +const ( + // CertificateStatusPendingValidation is a CertificateStatus enum value + CertificateStatusPendingValidation = "PENDING_VALIDATION" + + // CertificateStatusIssued is a CertificateStatus enum value + CertificateStatusIssued = "ISSUED" + + // CertificateStatusInactive is a CertificateStatus enum value + CertificateStatusInactive = "INACTIVE" + + // CertificateStatusExpired is a CertificateStatus enum value + CertificateStatusExpired = "EXPIRED" + + // CertificateStatusValidationTimedOut is a CertificateStatus enum value + CertificateStatusValidationTimedOut = "VALIDATION_TIMED_OUT" + + // CertificateStatusRevoked is a CertificateStatus enum value + CertificateStatusRevoked = "REVOKED" + + // CertificateStatusFailed is a CertificateStatus enum value + CertificateStatusFailed = "FAILED" +) + +// CertificateStatus_Values returns all elements of the CertificateStatus enum +func CertificateStatus_Values() []string { + return []string{ + CertificateStatusPendingValidation, + CertificateStatusIssued, + CertificateStatusInactive, + CertificateStatusExpired, + CertificateStatusValidationTimedOut, + CertificateStatusRevoked, + CertificateStatusFailed, + } +} + const ( // CloudFormationStackRecordSourceTypeExportSnapshotRecord is a CloudFormationStackRecordSourceType enum value CloudFormationStackRecordSourceTypeExportSnapshotRecord = "ExportSnapshotRecord" ) +// CloudFormationStackRecordSourceType_Values returns all elements of the CloudFormationStackRecordSourceType enum +func CloudFormationStackRecordSourceType_Values() []string { + return []string{ + CloudFormationStackRecordSourceTypeExportSnapshotRecord, + } +} + const ( // ComparisonOperatorGreaterThanOrEqualToThreshold is a ComparisonOperator enum value ComparisonOperatorGreaterThanOrEqualToThreshold = "GreaterThanOrEqualToThreshold" @@ -27799,6 +32141,16 @@ const ( ComparisonOperatorLessThanOrEqualToThreshold = "LessThanOrEqualToThreshold" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorGreaterThanOrEqualToThreshold, + ComparisonOperatorGreaterThanThreshold, + ComparisonOperatorLessThanThreshold, + ComparisonOperatorLessThanOrEqualToThreshold, + } +} + const ( // ContactMethodStatusPendingVerification is a ContactMethodStatus enum value ContactMethodStatusPendingVerification = "PendingVerification" @@ -27810,11 +32162,27 @@ const ( ContactMethodStatusInvalid = "Invalid" ) +// ContactMethodStatus_Values returns all elements of the ContactMethodStatus enum +func ContactMethodStatus_Values() []string { + return []string{ + ContactMethodStatusPendingVerification, + ContactMethodStatusValid, + ContactMethodStatusInvalid, + } +} + const ( // ContactMethodVerificationProtocolEmail is a ContactMethodVerificationProtocol enum value ContactMethodVerificationProtocolEmail = "Email" ) +// ContactMethodVerificationProtocol_Values returns all elements of the ContactMethodVerificationProtocol enum +func ContactMethodVerificationProtocol_Values() []string { + return []string{ + ContactMethodVerificationProtocolEmail, + } +} + const ( // ContactProtocolEmail is a ContactProtocol enum value ContactProtocolEmail = "Email" @@ -27823,6 +32191,14 @@ const ( ContactProtocolSms = "SMS" ) +// ContactProtocol_Values returns all elements of the ContactProtocol enum +func ContactProtocol_Values() []string { + return []string{ + ContactProtocolEmail, + ContactProtocolSms, + } +} + const ( // DiskSnapshotStatePending is a DiskSnapshotState enum value DiskSnapshotStatePending = "pending" @@ -27837,6 +32213,16 @@ const ( DiskSnapshotStateUnknown = "unknown" ) +// DiskSnapshotState_Values returns all elements of the DiskSnapshotState enum +func DiskSnapshotState_Values() []string { + return []string{ + DiskSnapshotStatePending, + DiskSnapshotStateCompleted, + DiskSnapshotStateError, + DiskSnapshotStateUnknown, + } +} + const ( // DiskStatePending is a DiskState enum value DiskStatePending = "pending" @@ -27854,6 +32240,49 @@ const ( DiskStateUnknown = "unknown" ) +// DiskState_Values returns all elements of the DiskState enum +func DiskState_Values() []string { + return []string{ + DiskStatePending, + DiskStateError, + DiskStateAvailable, + DiskStateInUse, + DiskStateUnknown, + } +} + +const ( + // DistributionMetricNameRequests is a DistributionMetricName enum value + DistributionMetricNameRequests = "Requests" + + // DistributionMetricNameBytesDownloaded is a DistributionMetricName enum value + DistributionMetricNameBytesDownloaded = "BytesDownloaded" + + // DistributionMetricNameBytesUploaded is a DistributionMetricName enum value + DistributionMetricNameBytesUploaded = "BytesUploaded" + + // DistributionMetricNameTotalErrorRate is a DistributionMetricName enum value + DistributionMetricNameTotalErrorRate = "TotalErrorRate" + + // DistributionMetricNameHttp4xxErrorRate is a DistributionMetricName enum value + DistributionMetricNameHttp4xxErrorRate = "Http4xxErrorRate" + + // DistributionMetricNameHttp5xxErrorRate is a DistributionMetricName enum value + DistributionMetricNameHttp5xxErrorRate = "Http5xxErrorRate" +) + +// DistributionMetricName_Values returns all elements of the DistributionMetricName enum +func DistributionMetricName_Values() []string { + return []string{ + DistributionMetricNameRequests, + DistributionMetricNameBytesDownloaded, + DistributionMetricNameBytesUploaded, + DistributionMetricNameTotalErrorRate, + DistributionMetricNameHttp4xxErrorRate, + DistributionMetricNameHttp5xxErrorRate, + } +} + const ( // ExportSnapshotRecordSourceTypeInstanceSnapshot is a ExportSnapshotRecordSourceType enum value ExportSnapshotRecordSourceTypeInstanceSnapshot = "InstanceSnapshot" @@ -27862,6 +32291,102 @@ const ( ExportSnapshotRecordSourceTypeDiskSnapshot = "DiskSnapshot" ) +// ExportSnapshotRecordSourceType_Values returns all elements of the ExportSnapshotRecordSourceType enum +func ExportSnapshotRecordSourceType_Values() []string { + return []string{ + ExportSnapshotRecordSourceTypeInstanceSnapshot, + ExportSnapshotRecordSourceTypeDiskSnapshot, + } +} + +const ( + // ForwardValuesNone is a ForwardValues enum value + ForwardValuesNone = "none" + + // ForwardValuesAllowList is a ForwardValues enum value + ForwardValuesAllowList = "allow-list" + + // ForwardValuesAll is a ForwardValues enum value + ForwardValuesAll = "all" +) + +// ForwardValues_Values returns all elements of the ForwardValues enum +func ForwardValues_Values() []string { + return []string{ + ForwardValuesNone, + ForwardValuesAllowList, + ForwardValuesAll, + } +} + +const ( + // HeaderEnumAccept is a HeaderEnum enum value + HeaderEnumAccept = "Accept" + + // HeaderEnumAcceptCharset is a HeaderEnum enum value + HeaderEnumAcceptCharset = "Accept-Charset" + + // HeaderEnumAcceptDatetime is a HeaderEnum enum value + HeaderEnumAcceptDatetime = "Accept-Datetime" + + // HeaderEnumAcceptEncoding is a HeaderEnum enum value + HeaderEnumAcceptEncoding = "Accept-Encoding" + + // HeaderEnumAcceptLanguage is a HeaderEnum enum value + HeaderEnumAcceptLanguage = "Accept-Language" + + // HeaderEnumAuthorization is a HeaderEnum enum value + HeaderEnumAuthorization = "Authorization" + + // HeaderEnumCloudFrontForwardedProto is a HeaderEnum enum value + HeaderEnumCloudFrontForwardedProto = "CloudFront-Forwarded-Proto" + + // HeaderEnumCloudFrontIsDesktopViewer is a HeaderEnum enum value + HeaderEnumCloudFrontIsDesktopViewer = "CloudFront-Is-Desktop-Viewer" + + // HeaderEnumCloudFrontIsMobileViewer is a HeaderEnum enum value + HeaderEnumCloudFrontIsMobileViewer = "CloudFront-Is-Mobile-Viewer" + + // HeaderEnumCloudFrontIsSmartTvViewer is a HeaderEnum enum value + HeaderEnumCloudFrontIsSmartTvViewer = "CloudFront-Is-SmartTV-Viewer" + + // HeaderEnumCloudFrontIsTabletViewer is a HeaderEnum enum value + HeaderEnumCloudFrontIsTabletViewer = "CloudFront-Is-Tablet-Viewer" + + // HeaderEnumCloudFrontViewerCountry is a HeaderEnum enum value + HeaderEnumCloudFrontViewerCountry = "CloudFront-Viewer-Country" + + // HeaderEnumHost is a HeaderEnum enum value + HeaderEnumHost = "Host" + + // HeaderEnumOrigin is a HeaderEnum enum value + HeaderEnumOrigin = "Origin" + + // HeaderEnumReferer is a HeaderEnum enum value + HeaderEnumReferer = "Referer" +) + +// HeaderEnum_Values returns all elements of the HeaderEnum enum +func HeaderEnum_Values() []string { + return []string{ + HeaderEnumAccept, + HeaderEnumAcceptCharset, + HeaderEnumAcceptDatetime, + HeaderEnumAcceptEncoding, + HeaderEnumAcceptLanguage, + HeaderEnumAuthorization, + HeaderEnumCloudFrontForwardedProto, + HeaderEnumCloudFrontIsDesktopViewer, + HeaderEnumCloudFrontIsMobileViewer, + HeaderEnumCloudFrontIsSmartTvViewer, + HeaderEnumCloudFrontIsTabletViewer, + HeaderEnumCloudFrontViewerCountry, + HeaderEnumHost, + HeaderEnumOrigin, + HeaderEnumReferer, + } +} + const ( // InstanceAccessProtocolSsh is a InstanceAccessProtocol enum value InstanceAccessProtocolSsh = "ssh" @@ -27870,6 +32395,14 @@ const ( InstanceAccessProtocolRdp = "rdp" ) +// InstanceAccessProtocol_Values returns all elements of the InstanceAccessProtocol enum +func InstanceAccessProtocol_Values() []string { + return []string{ + InstanceAccessProtocolSsh, + InstanceAccessProtocolRdp, + } +} + const ( // InstanceHealthReasonLbRegistrationInProgress is a InstanceHealthReason enum value InstanceHealthReasonLbRegistrationInProgress = "Lb.RegistrationInProgress" @@ -27905,6 +32438,23 @@ const ( InstanceHealthReasonInstanceIpUnusable = "Instance.IpUnusable" ) +// InstanceHealthReason_Values returns all elements of the InstanceHealthReason enum +func InstanceHealthReason_Values() []string { + return []string{ + InstanceHealthReasonLbRegistrationInProgress, + InstanceHealthReasonLbInitialHealthChecking, + InstanceHealthReasonLbInternalError, + InstanceHealthReasonInstanceResponseCodeMismatch, + InstanceHealthReasonInstanceTimeout, + InstanceHealthReasonInstanceFailedHealthChecks, + InstanceHealthReasonInstanceNotRegistered, + InstanceHealthReasonInstanceNotInUse, + InstanceHealthReasonInstanceDeregistrationInProgress, + InstanceHealthReasonInstanceInvalidState, + InstanceHealthReasonInstanceIpUnusable, + } +} + const ( // InstanceHealthStateInitial is a InstanceHealthState enum value InstanceHealthStateInitial = "initial" @@ -27925,6 +32475,18 @@ const ( InstanceHealthStateUnavailable = "unavailable" ) +// InstanceHealthState_Values returns all elements of the InstanceHealthState enum +func InstanceHealthState_Values() []string { + return []string{ + InstanceHealthStateInitial, + InstanceHealthStateHealthy, + InstanceHealthStateUnhealthy, + InstanceHealthStateUnused, + InstanceHealthStateDraining, + InstanceHealthStateUnavailable, + } +} + const ( // InstanceMetricNameCpuutilization is a InstanceMetricName enum value InstanceMetricNameCpuutilization = "CPUUtilization" @@ -27943,8 +32505,28 @@ const ( // InstanceMetricNameStatusCheckFailedSystem is a InstanceMetricName enum value InstanceMetricNameStatusCheckFailedSystem = "StatusCheckFailed_System" + + // InstanceMetricNameBurstCapacityTime is a InstanceMetricName enum value + InstanceMetricNameBurstCapacityTime = "BurstCapacityTime" + + // InstanceMetricNameBurstCapacityPercentage is a InstanceMetricName enum value + InstanceMetricNameBurstCapacityPercentage = "BurstCapacityPercentage" ) +// InstanceMetricName_Values returns all elements of the InstanceMetricName enum +func InstanceMetricName_Values() []string { + return []string{ + InstanceMetricNameCpuutilization, + InstanceMetricNameNetworkIn, + InstanceMetricNameNetworkOut, + InstanceMetricNameStatusCheckFailed, + InstanceMetricNameStatusCheckFailedInstance, + InstanceMetricNameStatusCheckFailedSystem, + InstanceMetricNameBurstCapacityTime, + InstanceMetricNameBurstCapacityPercentage, + } +} + const ( // InstancePlatformLinuxUnix is a InstancePlatform enum value InstancePlatformLinuxUnix = "LINUX_UNIX" @@ -27953,6 +32535,14 @@ const ( InstancePlatformWindows = "WINDOWS" ) +// InstancePlatform_Values returns all elements of the InstancePlatform enum +func InstancePlatform_Values() []string { + return []string{ + InstancePlatformLinuxUnix, + InstancePlatformWindows, + } +} + const ( // InstanceSnapshotStatePending is a InstanceSnapshotState enum value InstanceSnapshotStatePending = "pending" @@ -27964,6 +32554,15 @@ const ( InstanceSnapshotStateAvailable = "available" ) +// InstanceSnapshotState_Values returns all elements of the InstanceSnapshotState enum +func InstanceSnapshotState_Values() []string { + return []string{ + InstanceSnapshotStatePending, + InstanceSnapshotStateError, + InstanceSnapshotStateAvailable, + } +} + const ( // LoadBalancerAttributeNameHealthCheckPath is a LoadBalancerAttributeName enum value LoadBalancerAttributeNameHealthCheckPath = "HealthCheckPath" @@ -27975,6 +32574,15 @@ const ( LoadBalancerAttributeNameSessionStickinessLbCookieDurationSeconds = "SessionStickiness_LB_CookieDurationSeconds" ) +// LoadBalancerAttributeName_Values returns all elements of the LoadBalancerAttributeName enum +func LoadBalancerAttributeName_Values() []string { + return []string{ + LoadBalancerAttributeNameHealthCheckPath, + LoadBalancerAttributeNameSessionStickinessEnabled, + LoadBalancerAttributeNameSessionStickinessLbCookieDurationSeconds, + } +} + const ( // LoadBalancerMetricNameClientTlsnegotiationErrorCount is a LoadBalancerMetricName enum value LoadBalancerMetricNameClientTlsnegotiationErrorCount = "ClientTLSNegotiationErrorCount" @@ -28013,6 +32621,24 @@ const ( LoadBalancerMetricNameRequestCount = "RequestCount" ) +// LoadBalancerMetricName_Values returns all elements of the LoadBalancerMetricName enum +func LoadBalancerMetricName_Values() []string { + return []string{ + LoadBalancerMetricNameClientTlsnegotiationErrorCount, + LoadBalancerMetricNameHealthyHostCount, + LoadBalancerMetricNameUnhealthyHostCount, + LoadBalancerMetricNameHttpcodeLb4xxCount, + LoadBalancerMetricNameHttpcodeLb5xxCount, + LoadBalancerMetricNameHttpcodeInstance2xxCount, + LoadBalancerMetricNameHttpcodeInstance3xxCount, + LoadBalancerMetricNameHttpcodeInstance4xxCount, + LoadBalancerMetricNameHttpcodeInstance5xxCount, + LoadBalancerMetricNameInstanceResponseTime, + LoadBalancerMetricNameRejectedConnectionCount, + LoadBalancerMetricNameRequestCount, + } +} + const ( // LoadBalancerProtocolHttpHttps is a LoadBalancerProtocol enum value LoadBalancerProtocolHttpHttps = "HTTP_HTTPS" @@ -28021,6 +32647,14 @@ const ( LoadBalancerProtocolHttp = "HTTP" ) +// LoadBalancerProtocol_Values returns all elements of the LoadBalancerProtocol enum +func LoadBalancerProtocol_Values() []string { + return []string{ + LoadBalancerProtocolHttpHttps, + LoadBalancerProtocolHttp, + } +} + const ( // LoadBalancerStateActive is a LoadBalancerState enum value LoadBalancerStateActive = "active" @@ -28038,6 +32672,17 @@ const ( LoadBalancerStateUnknown = "unknown" ) +// LoadBalancerState_Values returns all elements of the LoadBalancerState enum +func LoadBalancerState_Values() []string { + return []string{ + LoadBalancerStateActive, + LoadBalancerStateProvisioning, + LoadBalancerStateActiveImpaired, + LoadBalancerStateFailed, + LoadBalancerStateUnknown, + } +} + const ( // LoadBalancerTlsCertificateDomainStatusPendingValidation is a LoadBalancerTlsCertificateDomainStatus enum value LoadBalancerTlsCertificateDomainStatusPendingValidation = "PENDING_VALIDATION" @@ -28049,6 +32694,15 @@ const ( LoadBalancerTlsCertificateDomainStatusSuccess = "SUCCESS" ) +// LoadBalancerTlsCertificateDomainStatus_Values returns all elements of the LoadBalancerTlsCertificateDomainStatus enum +func LoadBalancerTlsCertificateDomainStatus_Values() []string { + return []string{ + LoadBalancerTlsCertificateDomainStatusPendingValidation, + LoadBalancerTlsCertificateDomainStatusFailed, + LoadBalancerTlsCertificateDomainStatusSuccess, + } +} + const ( // LoadBalancerTlsCertificateFailureReasonNoAvailableContacts is a LoadBalancerTlsCertificateFailureReason enum value LoadBalancerTlsCertificateFailureReasonNoAvailableContacts = "NO_AVAILABLE_CONTACTS" @@ -28066,6 +32720,17 @@ const ( LoadBalancerTlsCertificateFailureReasonOther = "OTHER" ) +// LoadBalancerTlsCertificateFailureReason_Values returns all elements of the LoadBalancerTlsCertificateFailureReason enum +func LoadBalancerTlsCertificateFailureReason_Values() []string { + return []string{ + LoadBalancerTlsCertificateFailureReasonNoAvailableContacts, + LoadBalancerTlsCertificateFailureReasonAdditionalVerificationRequired, + LoadBalancerTlsCertificateFailureReasonDomainNotAllowed, + LoadBalancerTlsCertificateFailureReasonInvalidPublicDomain, + LoadBalancerTlsCertificateFailureReasonOther, + } +} + const ( // LoadBalancerTlsCertificateRenewalStatusPendingAutoRenewal is a LoadBalancerTlsCertificateRenewalStatus enum value LoadBalancerTlsCertificateRenewalStatusPendingAutoRenewal = "PENDING_AUTO_RENEWAL" @@ -28080,6 +32745,16 @@ const ( LoadBalancerTlsCertificateRenewalStatusFailed = "FAILED" ) +// LoadBalancerTlsCertificateRenewalStatus_Values returns all elements of the LoadBalancerTlsCertificateRenewalStatus enum +func LoadBalancerTlsCertificateRenewalStatus_Values() []string { + return []string{ + LoadBalancerTlsCertificateRenewalStatusPendingAutoRenewal, + LoadBalancerTlsCertificateRenewalStatusPendingValidation, + LoadBalancerTlsCertificateRenewalStatusSuccess, + LoadBalancerTlsCertificateRenewalStatusFailed, + } +} + const ( // LoadBalancerTlsCertificateRevocationReasonUnspecified is a LoadBalancerTlsCertificateRevocationReason enum value LoadBalancerTlsCertificateRevocationReasonUnspecified = "UNSPECIFIED" @@ -28112,6 +32787,22 @@ const ( LoadBalancerTlsCertificateRevocationReasonAACompromise = "A_A_COMPROMISE" ) +// LoadBalancerTlsCertificateRevocationReason_Values returns all elements of the LoadBalancerTlsCertificateRevocationReason enum +func LoadBalancerTlsCertificateRevocationReason_Values() []string { + return []string{ + LoadBalancerTlsCertificateRevocationReasonUnspecified, + LoadBalancerTlsCertificateRevocationReasonKeyCompromise, + LoadBalancerTlsCertificateRevocationReasonCaCompromise, + LoadBalancerTlsCertificateRevocationReasonAffiliationChanged, + LoadBalancerTlsCertificateRevocationReasonSuperceded, + LoadBalancerTlsCertificateRevocationReasonCessationOfOperation, + LoadBalancerTlsCertificateRevocationReasonCertificateHold, + LoadBalancerTlsCertificateRevocationReasonRemoveFromCrl, + LoadBalancerTlsCertificateRevocationReasonPrivilegeWithdrawn, + LoadBalancerTlsCertificateRevocationReasonAACompromise, + } +} + const ( // LoadBalancerTlsCertificateStatusPendingValidation is a LoadBalancerTlsCertificateStatus enum value LoadBalancerTlsCertificateStatusPendingValidation = "PENDING_VALIDATION" @@ -28138,6 +32829,20 @@ const ( LoadBalancerTlsCertificateStatusUnknown = "UNKNOWN" ) +// LoadBalancerTlsCertificateStatus_Values returns all elements of the LoadBalancerTlsCertificateStatus enum +func LoadBalancerTlsCertificateStatus_Values() []string { + return []string{ + LoadBalancerTlsCertificateStatusPendingValidation, + LoadBalancerTlsCertificateStatusIssued, + LoadBalancerTlsCertificateStatusInactive, + LoadBalancerTlsCertificateStatusExpired, + LoadBalancerTlsCertificateStatusValidationTimedOut, + LoadBalancerTlsCertificateStatusRevoked, + LoadBalancerTlsCertificateStatusFailed, + LoadBalancerTlsCertificateStatusUnknown, + } +} + const ( // MetricNameCpuutilization is a MetricName enum value MetricNameCpuutilization = "CPUUtilization" @@ -28207,8 +32912,45 @@ const ( // MetricNameNetworkTransmitThroughput is a MetricName enum value MetricNameNetworkTransmitThroughput = "NetworkTransmitThroughput" + + // MetricNameBurstCapacityTime is a MetricName enum value + MetricNameBurstCapacityTime = "BurstCapacityTime" + + // MetricNameBurstCapacityPercentage is a MetricName enum value + MetricNameBurstCapacityPercentage = "BurstCapacityPercentage" ) +// MetricName_Values returns all elements of the MetricName enum +func MetricName_Values() []string { + return []string{ + MetricNameCpuutilization, + MetricNameNetworkIn, + MetricNameNetworkOut, + MetricNameStatusCheckFailed, + MetricNameStatusCheckFailedInstance, + MetricNameStatusCheckFailedSystem, + MetricNameClientTlsnegotiationErrorCount, + MetricNameHealthyHostCount, + MetricNameUnhealthyHostCount, + MetricNameHttpcodeLb4xxCount, + MetricNameHttpcodeLb5xxCount, + MetricNameHttpcodeInstance2xxCount, + MetricNameHttpcodeInstance3xxCount, + MetricNameHttpcodeInstance4xxCount, + MetricNameHttpcodeInstance5xxCount, + MetricNameInstanceResponseTime, + MetricNameRejectedConnectionCount, + MetricNameRequestCount, + MetricNameDatabaseConnections, + MetricNameDiskQueueDepth, + MetricNameFreeStorageSpace, + MetricNameNetworkReceiveThroughput, + MetricNameNetworkTransmitThroughput, + MetricNameBurstCapacityTime, + MetricNameBurstCapacityPercentage, + } +} + const ( // MetricStatisticMinimum is a MetricStatistic enum value MetricStatisticMinimum = "Minimum" @@ -28226,6 +32968,17 @@ const ( MetricStatisticSampleCount = "SampleCount" ) +// MetricStatistic_Values returns all elements of the MetricStatistic enum +func MetricStatistic_Values() []string { + return []string{ + MetricStatisticMinimum, + MetricStatisticMaximum, + MetricStatisticSum, + MetricStatisticAverage, + MetricStatisticSampleCount, + } +} + const ( // MetricUnitSeconds is a MetricUnit enum value MetricUnitSeconds = "Seconds" @@ -28309,6 +33062,39 @@ const ( MetricUnitNone = "None" ) +// MetricUnit_Values returns all elements of the MetricUnit enum +func MetricUnit_Values() []string { + return []string{ + MetricUnitSeconds, + MetricUnitMicroseconds, + MetricUnitMilliseconds, + MetricUnitBytes, + MetricUnitKilobytes, + MetricUnitMegabytes, + MetricUnitGigabytes, + MetricUnitTerabytes, + MetricUnitBits, + MetricUnitKilobits, + MetricUnitMegabits, + MetricUnitGigabits, + MetricUnitTerabits, + MetricUnitPercent, + MetricUnitCount, + MetricUnitBytesSecond, + MetricUnitKilobytesSecond, + MetricUnitMegabytesSecond, + MetricUnitGigabytesSecond, + MetricUnitTerabytesSecond, + MetricUnitBitsSecond, + MetricUnitKilobitsSecond, + MetricUnitMegabitsSecond, + MetricUnitGigabitsSecond, + MetricUnitTerabitsSecond, + MetricUnitCountSecond, + MetricUnitNone, + } +} + const ( // NetworkProtocolTcp is a NetworkProtocol enum value NetworkProtocolTcp = "tcp" @@ -28318,8 +33104,21 @@ const ( // NetworkProtocolUdp is a NetworkProtocol enum value NetworkProtocolUdp = "udp" + + // NetworkProtocolIcmp is a NetworkProtocol enum value + NetworkProtocolIcmp = "icmp" ) +// NetworkProtocol_Values returns all elements of the NetworkProtocol enum +func NetworkProtocol_Values() []string { + return []string{ + NetworkProtocolTcp, + NetworkProtocolAll, + NetworkProtocolUdp, + NetworkProtocolIcmp, + } +} + const ( // OperationStatusNotStarted is a OperationStatus enum value OperationStatusNotStarted = "NotStarted" @@ -28337,6 +33136,17 @@ const ( OperationStatusSucceeded = "Succeeded" ) +// OperationStatus_Values returns all elements of the OperationStatus enum +func OperationStatus_Values() []string { + return []string{ + OperationStatusNotStarted, + OperationStatusStarted, + OperationStatusFailed, + OperationStatusCompleted, + OperationStatusSucceeded, + } +} + const ( // OperationTypeDeleteKnownHostKeys is a OperationType enum value OperationTypeDeleteKnownHostKeys = "DeleteKnownHostKeys" @@ -28502,8 +33312,121 @@ const ( // OperationTypeDeleteContactMethod is a OperationType enum value OperationTypeDeleteContactMethod = "DeleteContactMethod" + + // OperationTypeCreateDistribution is a OperationType enum value + OperationTypeCreateDistribution = "CreateDistribution" + + // OperationTypeUpdateDistribution is a OperationType enum value + OperationTypeUpdateDistribution = "UpdateDistribution" + + // OperationTypeDeleteDistribution is a OperationType enum value + OperationTypeDeleteDistribution = "DeleteDistribution" + + // OperationTypeResetDistributionCache is a OperationType enum value + OperationTypeResetDistributionCache = "ResetDistributionCache" + + // OperationTypeAttachCertificateToDistribution is a OperationType enum value + OperationTypeAttachCertificateToDistribution = "AttachCertificateToDistribution" + + // OperationTypeDetachCertificateFromDistribution is a OperationType enum value + OperationTypeDetachCertificateFromDistribution = "DetachCertificateFromDistribution" + + // OperationTypeUpdateDistributionBundle is a OperationType enum value + OperationTypeUpdateDistributionBundle = "UpdateDistributionBundle" + + // OperationTypeCreateCertificate is a OperationType enum value + OperationTypeCreateCertificate = "CreateCertificate" + + // OperationTypeDeleteCertificate is a OperationType enum value + OperationTypeDeleteCertificate = "DeleteCertificate" +) + +// OperationType_Values returns all elements of the OperationType enum +func OperationType_Values() []string { + return []string{ + OperationTypeDeleteKnownHostKeys, + OperationTypeDeleteInstance, + OperationTypeCreateInstance, + OperationTypeStopInstance, + OperationTypeStartInstance, + OperationTypeRebootInstance, + OperationTypeOpenInstancePublicPorts, + OperationTypePutInstancePublicPorts, + OperationTypeCloseInstancePublicPorts, + OperationTypeAllocateStaticIp, + OperationTypeReleaseStaticIp, + OperationTypeAttachStaticIp, + OperationTypeDetachStaticIp, + OperationTypeUpdateDomainEntry, + OperationTypeDeleteDomainEntry, + OperationTypeCreateDomain, + OperationTypeDeleteDomain, + OperationTypeCreateInstanceSnapshot, + OperationTypeDeleteInstanceSnapshot, + OperationTypeCreateInstancesFromSnapshot, + OperationTypeCreateLoadBalancer, + OperationTypeDeleteLoadBalancer, + OperationTypeAttachInstancesToLoadBalancer, + OperationTypeDetachInstancesFromLoadBalancer, + OperationTypeUpdateLoadBalancerAttribute, + OperationTypeCreateLoadBalancerTlsCertificate, + OperationTypeDeleteLoadBalancerTlsCertificate, + OperationTypeAttachLoadBalancerTlsCertificate, + OperationTypeCreateDisk, + OperationTypeDeleteDisk, + OperationTypeAttachDisk, + OperationTypeDetachDisk, + OperationTypeCreateDiskSnapshot, + OperationTypeDeleteDiskSnapshot, + OperationTypeCreateDiskFromSnapshot, + OperationTypeCreateRelationalDatabase, + OperationTypeUpdateRelationalDatabase, + OperationTypeDeleteRelationalDatabase, + OperationTypeCreateRelationalDatabaseFromSnapshot, + OperationTypeCreateRelationalDatabaseSnapshot, + OperationTypeDeleteRelationalDatabaseSnapshot, + OperationTypeUpdateRelationalDatabaseParameters, + OperationTypeStartRelationalDatabase, + OperationTypeRebootRelationalDatabase, + OperationTypeStopRelationalDatabase, + OperationTypeEnableAddOn, + OperationTypeDisableAddOn, + OperationTypePutAlarm, + OperationTypeGetAlarms, + OperationTypeDeleteAlarm, + OperationTypeTestAlarm, + OperationTypeCreateContactMethod, + OperationTypeGetContactMethods, + OperationTypeSendContactMethodVerification, + OperationTypeDeleteContactMethod, + OperationTypeCreateDistribution, + OperationTypeUpdateDistribution, + OperationTypeDeleteDistribution, + OperationTypeResetDistributionCache, + OperationTypeAttachCertificateToDistribution, + OperationTypeDetachCertificateFromDistribution, + OperationTypeUpdateDistributionBundle, + OperationTypeCreateCertificate, + OperationTypeDeleteCertificate, + } +} + +const ( + // OriginProtocolPolicyEnumHttpOnly is a OriginProtocolPolicyEnum enum value + OriginProtocolPolicyEnumHttpOnly = "http-only" + + // OriginProtocolPolicyEnumHttpsOnly is a OriginProtocolPolicyEnum enum value + OriginProtocolPolicyEnumHttpsOnly = "https-only" ) +// OriginProtocolPolicyEnum_Values returns all elements of the OriginProtocolPolicyEnum enum +func OriginProtocolPolicyEnum_Values() []string { + return []string{ + OriginProtocolPolicyEnumHttpOnly, + OriginProtocolPolicyEnumHttpsOnly, + } +} + const ( // PortAccessTypePublic is a PortAccessType enum value PortAccessTypePublic = "Public" @@ -28512,6 +33435,14 @@ const ( PortAccessTypePrivate = "Private" ) +// PortAccessType_Values returns all elements of the PortAccessType enum +func PortAccessType_Values() []string { + return []string{ + PortAccessTypePublic, + PortAccessTypePrivate, + } +} + const ( // PortInfoSourceTypeDefault is a PortInfoSourceType enum value PortInfoSourceTypeDefault = "DEFAULT" @@ -28526,6 +33457,16 @@ const ( PortInfoSourceTypeClosed = "CLOSED" ) +// PortInfoSourceType_Values returns all elements of the PortInfoSourceType enum +func PortInfoSourceType_Values() []string { + return []string{ + PortInfoSourceTypeDefault, + PortInfoSourceTypeInstance, + PortInfoSourceTypeNone, + PortInfoSourceTypeClosed, + } +} + const ( // PortStateOpen is a PortState enum value PortStateOpen = "open" @@ -28534,6 +33475,14 @@ const ( PortStateClosed = "closed" ) +// PortState_Values returns all elements of the PortState enum +func PortState_Values() []string { + return []string{ + PortStateOpen, + PortStateClosed, + } +} + const ( // RecordStateStarted is a RecordState enum value RecordStateStarted = "Started" @@ -28545,6 +33494,15 @@ const ( RecordStateFailed = "Failed" ) +// RecordState_Values returns all elements of the RecordState enum +func RecordState_Values() []string { + return []string{ + RecordStateStarted, + RecordStateSucceeded, + RecordStateFailed, + } +} + const ( // RegionNameUsEast1 is a RegionName enum value RegionNameUsEast1 = "us-east-1" @@ -28589,11 +33547,38 @@ const ( RegionNameApNortheast2 = "ap-northeast-2" ) +// RegionName_Values returns all elements of the RegionName enum +func RegionName_Values() []string { + return []string{ + RegionNameUsEast1, + RegionNameUsEast2, + RegionNameUsWest1, + RegionNameUsWest2, + RegionNameEuWest1, + RegionNameEuWest2, + RegionNameEuWest3, + RegionNameEuCentral1, + RegionNameCaCentral1, + RegionNameApSouth1, + RegionNameApSoutheast1, + RegionNameApSoutheast2, + RegionNameApNortheast1, + RegionNameApNortheast2, + } +} + const ( // RelationalDatabaseEngineMysql is a RelationalDatabaseEngine enum value RelationalDatabaseEngineMysql = "mysql" ) +// RelationalDatabaseEngine_Values returns all elements of the RelationalDatabaseEngine enum +func RelationalDatabaseEngine_Values() []string { + return []string{ + RelationalDatabaseEngineMysql, + } +} + const ( // RelationalDatabaseMetricNameCpuutilization is a RelationalDatabaseMetricName enum value RelationalDatabaseMetricNameCpuutilization = "CPUUtilization" @@ -28614,6 +33599,18 @@ const ( RelationalDatabaseMetricNameNetworkTransmitThroughput = "NetworkTransmitThroughput" ) +// RelationalDatabaseMetricName_Values returns all elements of the RelationalDatabaseMetricName enum +func RelationalDatabaseMetricName_Values() []string { + return []string{ + RelationalDatabaseMetricNameCpuutilization, + RelationalDatabaseMetricNameDatabaseConnections, + RelationalDatabaseMetricNameDiskQueueDepth, + RelationalDatabaseMetricNameFreeStorageSpace, + RelationalDatabaseMetricNameNetworkReceiveThroughput, + RelationalDatabaseMetricNameNetworkTransmitThroughput, + } +} + const ( // RelationalDatabasePasswordVersionCurrent is a RelationalDatabasePasswordVersion enum value RelationalDatabasePasswordVersionCurrent = "CURRENT" @@ -28625,6 +33622,39 @@ const ( RelationalDatabasePasswordVersionPending = "PENDING" ) +// RelationalDatabasePasswordVersion_Values returns all elements of the RelationalDatabasePasswordVersion enum +func RelationalDatabasePasswordVersion_Values() []string { + return []string{ + RelationalDatabasePasswordVersionCurrent, + RelationalDatabasePasswordVersionPrevious, + RelationalDatabasePasswordVersionPending, + } +} + +const ( + // RenewalStatusPendingAutoRenewal is a RenewalStatus enum value + RenewalStatusPendingAutoRenewal = "PendingAutoRenewal" + + // RenewalStatusPendingValidation is a RenewalStatus enum value + RenewalStatusPendingValidation = "PendingValidation" + + // RenewalStatusSuccess is a RenewalStatus enum value + RenewalStatusSuccess = "Success" + + // RenewalStatusFailed is a RenewalStatus enum value + RenewalStatusFailed = "Failed" +) + +// RenewalStatus_Values returns all elements of the RenewalStatus enum +func RenewalStatus_Values() []string { + return []string{ + RenewalStatusPendingAutoRenewal, + RenewalStatusPendingValidation, + RenewalStatusSuccess, + RenewalStatusFailed, + } +} + const ( // ResourceTypeInstance is a ResourceType enum value ResourceTypeInstance = "Instance" @@ -28673,8 +33703,38 @@ const ( // ResourceTypeContactMethod is a ResourceType enum value ResourceTypeContactMethod = "ContactMethod" + + // ResourceTypeDistribution is a ResourceType enum value + ResourceTypeDistribution = "Distribution" + + // ResourceTypeCertificate is a ResourceType enum value + ResourceTypeCertificate = "Certificate" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeInstance, + ResourceTypeStaticIp, + ResourceTypeKeyPair, + ResourceTypeInstanceSnapshot, + ResourceTypeDomain, + ResourceTypePeeredVpc, + ResourceTypeLoadBalancer, + ResourceTypeLoadBalancerTlsCertificate, + ResourceTypeDisk, + ResourceTypeDiskSnapshot, + ResourceTypeRelationalDatabase, + ResourceTypeRelationalDatabaseSnapshot, + ResourceTypeExportSnapshotRecord, + ResourceTypeCloudFormationStackRecord, + ResourceTypeAlarm, + ResourceTypeContactMethod, + ResourceTypeDistribution, + ResourceTypeCertificate, + } +} + const ( // TreatMissingDataBreaching is a TreatMissingData enum value TreatMissingDataBreaching = "breaching" @@ -28688,3 +33748,13 @@ const ( // TreatMissingDataMissing is a TreatMissingData enum value TreatMissingDataMissing = "missing" ) + +// TreatMissingData_Values returns all elements of the TreatMissingData enum +func TreatMissingData_Values() []string { + return []string{ + TreatMissingDataBreaching, + TreatMissingDataNotBreaching, + TreatMissingDataIgnore, + TreatMissingDataMissing, + } +} 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 index f806bbf094f..5947ff0d91e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/lightsail/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/lightsail/doc.go @@ -3,19 +3,23 @@ // 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, a managed database, -// 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 (https://lightsail.aws.amazon.com/ls/docs/all). -// -// 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/article/lightsail-how-to-set-up-access-keys-to-use-sdk-api-cli). +// Amazon Lightsail is the easiest way to get started with Amazon Web Services +// (AWS) for developers who need to build websites or web applications. It includes +// everything you need to launch your project quickly – instances (virtual +// private servers), managed databases, SSD-based block storage, static IP addresses, +// load balancers, content delivery network (CDN) distributions, DNS management +// of registered domains, and snapshots (backups) – for a low, predictable +// monthly price. +// +// You can manage your Lightsail resources using the Lightsail console, Lightsail +// API, AWS Command Line Interface (AWS CLI), or SDKs. For more information +// about Lightsail concepts and tasks, see the Lightsail Dev Guide (http://lightsail.aws.amazon.com/ls/docs/how-to/article/lightsail-how-to-set-up-access-keys-to-use-sdk-api-cli). +// +// This API Reference provides detailed information about the actions, data +// types, parameters, and errors of the Lightsail service. For more information +// about the supported AWS Regions, endpoints, and service quotas for the Lightsail +// service, see Amazon Lightsail Endpoints and Quotas (https://docs.aws.amazon.com/general/latest/gr/lightsail.html) +// in the AWS General Reference. // // See https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28 for more information on this service. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/macie/api.go b/vendor/github.com/aws/aws-sdk-go/service/macie/api.go index d6728b8d182..b549dc3fbdd 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/macie/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/macie/api.go @@ -57,7 +57,8 @@ func (c *Macie) AssociateMemberAccountRequest(input *AssociateMemberAccountInput // AssociateMemberAccount API operation for Amazon Macie. // -// Associates a specified AWS account with Amazon Macie as a member account. +// Associates a specified AWS account with Amazon Macie Classic as a member +// 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 @@ -144,11 +145,11 @@ func (c *Macie) AssociateS3ResourcesRequest(input *AssociateS3ResourcesInput) (r // AssociateS3Resources API operation for Amazon Macie. // -// Associates specified S3 resources with Amazon Macie for monitoring and data -// classification. If memberAccountId isn't specified, the action associates -// specified S3 resources with Macie for the current master account. If memberAccountId -// is specified, the action associates specified S3 resources with Macie for -// the specified member account. +// Associates specified S3 resources with Amazon Macie Classic for monitoring +// and data classification. If memberAccountId isn't specified, the action associates +// specified S3 resources with Macie Classic for the current master account. +// If memberAccountId is specified, the action associates specified S3 resources +// with Macie Classic for the specified member 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 @@ -239,7 +240,7 @@ func (c *Macie) DisassociateMemberAccountRequest(input *DisassociateMemberAccoun // DisassociateMemberAccount API operation for Amazon Macie. // -// Removes the specified member account from Amazon Macie. +// Removes the specified member account from Amazon Macie Classic. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -322,10 +323,11 @@ func (c *Macie) DisassociateS3ResourcesRequest(input *DisassociateS3ResourcesInp // DisassociateS3Resources API operation for Amazon Macie. // -// Removes specified S3 resources from being monitored by Amazon Macie. If memberAccountId -// isn't specified, the action removes specified S3 resources from Macie for -// the current master account. If memberAccountId is specified, the action removes -// specified S3 resources from Macie for the specified member account. +// Removes specified S3 resources from being monitored by Amazon Macie Classic. +// If memberAccountId isn't specified, the action removes specified S3 resources +// from Macie Classic for the current master account. If memberAccountId is +// specified, the action removes specified S3 resources from Macie Classic for +// the specified member 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 @@ -417,8 +419,8 @@ func (c *Macie) ListMemberAccountsRequest(input *ListMemberAccountsInput) (req * // ListMemberAccounts API operation for Amazon Macie. // -// Lists all Amazon Macie member accounts for the current Amazon Macie master -// account. +// Lists all Amazon Macie Classic member accounts for the current Amazon Macie +// Classic master 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 @@ -559,11 +561,11 @@ func (c *Macie) ListS3ResourcesRequest(input *ListS3ResourcesInput) (req *reques // ListS3Resources API operation for Amazon Macie. // -// Lists all the S3 resources associated with Amazon Macie. If memberAccountId +// Lists all the S3 resources associated with Amazon Macie Classic. If memberAccountId // isn't specified, the action lists the S3 resources associated with Amazon -// Macie for the current master account. If memberAccountId is specified, the -// action lists the S3 resources associated with Amazon Macie for the specified -// member account. +// Macie Classic for the current master account. If memberAccountId is specified, +// the action lists the S3 resources associated with Amazon Macie Classic for +// the specified member 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 @@ -703,9 +705,9 @@ func (c *Macie) UpdateS3ResourcesRequest(input *UpdateS3ResourcesInput) (req *re // // Updates the classification types for the specified S3 resources. If memberAccountId // isn't specified, the action updates the classification types of the S3 resources -// associated with Amazon Macie for the current master account. If memberAccountId +// associated with Amazon Macie Classic for the current master account. If memberAccountId // is specified, the action updates the classification types of the S3 resources -// associated with Amazon Macie for the specified member account. +// associated with Amazon Macie Classic for the specified member 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 @@ -809,8 +811,8 @@ func (s *AccessDeniedException) RequestID() string { type AssociateMemberAccountInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account that you want to associate with Amazon Macie as - // a member account. + // The ID of the AWS account that you want to associate with Amazon Macie Classic + // as a member account. // // MemberAccountId is a required field MemberAccountId *string `locationName:"memberAccountId" type:"string" required:"true"` @@ -862,12 +864,12 @@ func (s AssociateMemberAccountOutput) GoString() string { type AssociateS3ResourcesInput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Macie member account whose resources you want to associate - // with Macie. + // The ID of the Amazon Macie Classic member account whose resources you want + // to associate with Macie Classic. MemberAccountId *string `locationName:"memberAccountId" type:"string"` - // The S3 resources that you want to associate with Amazon Macie for monitoring - // and data classification. + // The S3 resources that you want to associate with Amazon Macie Classic for + // monitoring and data classification. // // S3Resources is a required field S3Resources []*S3ResourceClassification `locationName:"s3Resources" type:"list" required:"true"` @@ -921,8 +923,8 @@ func (s *AssociateS3ResourcesInput) SetS3Resources(v []*S3ResourceClassification type AssociateS3ResourcesOutput struct { _ struct{} `type:"structure"` - // S3 resources that couldn't be associated with Amazon Macie. An error code - // and an error message are provided for each failed item. + // S3 resources that couldn't be associated with Amazon Macie Classic. An error + // code and an error message are provided for each failed item. FailedS3Resources []*FailedS3Resource `locationName:"failedS3Resources" type:"list"` } @@ -942,13 +944,14 @@ func (s *AssociateS3ResourcesOutput) SetFailedS3Resources(v []*FailedS3Resource) return s } -// The classification type that Amazon Macie applies to the associated S3 resources. +// The classification type that Amazon Macie Classic applies to the associated +// S3 resources. type ClassificationType struct { _ struct{} `type:"structure"` // A continuous classification of the objects that are added to a specified - // S3 bucket. Amazon Macie begins performing continuous classification after - // a bucket is successfully associated with Amazon Macie. + // S3 bucket. Amazon Macie Classic begins performing continuous classification + // after a bucket is successfully associated with Amazon Macie Classic. // // Continuous is a required field Continuous *string `locationName:"continuous" type:"string" required:"true" enum:"S3ContinuousClassificationType"` @@ -998,15 +1001,15 @@ func (s *ClassificationType) SetOneTime(v string) *ClassificationType { return s } -// The classification type that Amazon Macie applies to the associated S3 resources. -// At least one of the classification types (oneTime or continuous) must be -// specified. +// The classification type that Amazon Macie Classic applies to the associated +// S3 resources. At least one of the classification types (oneTime or continuous) +// must be specified. type ClassificationTypeUpdate struct { _ struct{} `type:"structure"` // A continuous classification of the objects that are added to a specified - // S3 bucket. Amazon Macie begins performing continuous classification after - // a bucket is successfully associated with Amazon Macie. + // S3 bucket. Amazon Macie Classic begins performing continuous classification + // after a bucket is successfully associated with Amazon Macie Classic. Continuous *string `locationName:"continuous" type:"string" enum:"S3ContinuousClassificationType"` // A one-time classification of all of the existing objects in a specified S3 @@ -1039,7 +1042,7 @@ func (s *ClassificationTypeUpdate) SetOneTime(v string) *ClassificationTypeUpdat type DisassociateMemberAccountInput struct { _ struct{} `type:"structure"` - // The ID of the member account that you want to remove from Amazon Macie. + // The ID of the member account that you want to remove from Amazon Macie Classic. // // MemberAccountId is a required field MemberAccountId *string `locationName:"memberAccountId" type:"string" required:"true"` @@ -1092,13 +1095,13 @@ type DisassociateS3ResourcesInput struct { _ struct{} `type:"structure"` // The S3 resources (buckets or prefixes) that you want to remove from being - // monitored and classified by Amazon Macie. + // monitored and classified by Amazon Macie Classic. // // AssociatedS3Resources is a required field AssociatedS3Resources []*S3Resource `locationName:"associatedS3Resources" type:"list" required:"true"` - // The ID of the Amazon Macie member account whose resources you want to remove - // from being monitored by Amazon Macie. + // The ID of the Amazon Macie Classic member account whose resources you want + // to remove from being monitored by Amazon Macie Classic. MemberAccountId *string `locationName:"memberAccountId" type:"string"` } @@ -1151,8 +1154,8 @@ type DisassociateS3ResourcesOutput struct { _ struct{} `type:"structure"` // S3 resources that couldn't be removed from being monitored and classified - // by Amazon Macie. An error code and an error message are provided for each - // failed item. + // by Amazon Macie Classic. An error code and an error message are provided + // for each failed item. FailedS3Resources []*FailedS3Resource `locationName:"failedS3Resources" type:"list"` } @@ -1438,8 +1441,8 @@ func (s *ListMemberAccountsInput) SetNextToken(v string) *ListMemberAccountsInpu type ListMemberAccountsOutput struct { _ struct{} `type:"structure"` - // A list of the Amazon Macie member accounts returned by the action. The current - // master account is also included in this list. + // A list of the Amazon Macie Classic member accounts returned by the action. + // The current master account is also included in this list. MemberAccounts []*MemberAccount `locationName:"memberAccounts" type:"list"` // When a response is generated, if there is more data to be listed, this parameter @@ -1478,8 +1481,8 @@ type ListS3ResourcesInput struct { // in the response. The default value is 250. MaxResults *int64 `locationName:"maxResults" type:"integer"` - // The Amazon Macie member account ID whose associated S3 resources you want - // to list. + // The Amazon Macie Classic member account ID whose associated S3 resources + // you want to list. MemberAccountId *string `locationName:"memberAccountId" type:"string"` // Use this parameter when paginating results. Set its value to null on your @@ -1552,11 +1555,11 @@ func (s *ListS3ResourcesOutput) SetS3Resources(v []*S3ResourceClassification) *L return s } -// Contains information about the Amazon Macie member account. +// Contains information about the Amazon Macie Classic member account. type MemberAccount struct { _ struct{} `type:"structure"` - // The AWS account ID of the Amazon Macie member account. + // The AWS account ID of the Amazon Macie Classic member account. AccountId *string `locationName:"accountId" type:"string"` } @@ -1626,25 +1629,26 @@ func (s *S3Resource) SetPrefix(v string) *S3Resource { return s } -// The S3 resources that you want to associate with Amazon Macie for monitoring -// and data classification. This data type is used as a request parameter in -// the AssociateS3Resources action and a response parameter in the ListS3Resources +// The S3 resources that you want to associate with Amazon Macie Classic for +// monitoring and data classification. This data type is used as a request parameter +// in the AssociateS3Resources action and a response parameter in the ListS3Resources // action. type S3ResourceClassification struct { _ struct{} `type:"structure"` - // The name of the S3 bucket that you want to associate with Amazon Macie. + // The name of the S3 bucket that you want to associate with Amazon Macie Classic. // // BucketName is a required field BucketName *string `locationName:"bucketName" type:"string" required:"true"` // The classification type that you want to specify for the resource associated - // with Amazon Macie. + // with Amazon Macie Classic. // // ClassificationType is a required field ClassificationType *ClassificationType `locationName:"classificationType" type:"structure" required:"true"` - // The prefix of the S3 bucket that you want to associate with Amazon Macie. + // The prefix of the S3 bucket that you want to associate with Amazon Macie + // Classic. Prefix *string `locationName:"prefix" type:"string"` } @@ -1708,7 +1712,7 @@ type S3ResourceClassificationUpdate struct { BucketName *string `locationName:"bucketName" type:"string" required:"true"` // The classification type that you want to update for the resource associated - // with Amazon Macie. + // with Amazon Macie Classic. // // ClassificationTypeUpdate is a required field ClassificationTypeUpdate *ClassificationTypeUpdate `locationName:"classificationTypeUpdate" type:"structure" required:"true"` @@ -1764,8 +1768,8 @@ func (s *S3ResourceClassificationUpdate) SetPrefix(v string) *S3ResourceClassifi type UpdateS3ResourcesInput struct { _ struct{} `type:"structure"` - // The AWS ID of the Amazon Macie member account whose S3 resources' classification - // types you want to update. + // The AWS ID of the Amazon Macie Classic member account whose S3 resources' + // classification types you want to update. MemberAccountId *string `locationName:"memberAccountId" type:"string"` // The S3 resources whose classification types you want to update. @@ -1848,6 +1852,13 @@ const ( S3ContinuousClassificationTypeFull = "FULL" ) +// S3ContinuousClassificationType_Values returns all elements of the S3ContinuousClassificationType enum +func S3ContinuousClassificationType_Values() []string { + return []string{ + S3ContinuousClassificationTypeFull, + } +} + const ( // S3OneTimeClassificationTypeFull is a S3OneTimeClassificationType enum value S3OneTimeClassificationTypeFull = "FULL" @@ -1855,3 +1866,11 @@ const ( // S3OneTimeClassificationTypeNone is a S3OneTimeClassificationType enum value S3OneTimeClassificationTypeNone = "NONE" ) + +// S3OneTimeClassificationType_Values returns all elements of the S3OneTimeClassificationType enum +func S3OneTimeClassificationType_Values() []string { + return []string{ + S3OneTimeClassificationTypeFull, + S3OneTimeClassificationTypeNone, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/macie/doc.go b/vendor/github.com/aws/aws-sdk-go/service/macie/doc.go index 1b8f9632f37..1b01c35632c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/macie/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/macie/doc.go @@ -3,12 +3,18 @@ // Package macie provides the client and types for making API // requests to Amazon Macie. // -// Amazon Macie is a security service that uses machine learning to automatically -// discover, classify, and protect sensitive data in AWS. Macie recognizes sensitive -// data such as personally identifiable information (PII) or intellectual property, -// and provides you with dashboards and alerts that give visibility into how -// this data is being accessed or moved. For more information, see the Macie -// User Guide (https://docs.aws.amazon.com/macie/latest/userguide/what-is-macie.html). +// Amazon Macie Classic is a security service that uses machine learning to +// automatically discover, classify, and protect sensitive data in AWS. Macie +// Classic recognizes sensitive data such as personally identifiable information +// (PII) or intellectual property, and provides you with dashboards and alerts +// that give visibility into how this data is being accessed or moved. For more +// information, see the Amazon Macie Classic User Guide (https://docs.aws.amazon.com/macie/latest/userguide/what-is-macie.html). +// +// A new Amazon Macie is now available with significant design improvements +// and additional features, at a lower price and in most AWS Regions. We encourage +// you to explore and use the new and improved features, and benefit from the +// reduced cost. To learn about features and pricing for the new Amazon Macie, +// see Amazon Macie (https://aws.amazon.com/macie/). // // See https://docs.aws.amazon.com/goto/WebAPI/macie-2017-12-19 for more information on this service. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/managedblockchain/api.go b/vendor/github.com/aws/aws-sdk-go/service/managedblockchain/api.go index 01e13126274..b7ea7b8c2c6 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/managedblockchain/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/managedblockchain/api.go @@ -6715,11 +6715,26 @@ const ( EditionStandard = "STANDARD" ) +// Edition_Values returns all elements of the Edition enum +func Edition_Values() []string { + return []string{ + EditionStarter, + EditionStandard, + } +} + const ( // FrameworkHyperledgerFabric is a Framework enum value FrameworkHyperledgerFabric = "HYPERLEDGER_FABRIC" ) +// Framework_Values returns all elements of the Framework enum +func Framework_Values() []string { + return []string{ + FrameworkHyperledgerFabric, + } +} + const ( // InvitationStatusPending is a InvitationStatus enum value InvitationStatusPending = "PENDING" @@ -6737,6 +6752,17 @@ const ( InvitationStatusExpired = "EXPIRED" ) +// InvitationStatus_Values returns all elements of the InvitationStatus enum +func InvitationStatus_Values() []string { + return []string{ + InvitationStatusPending, + InvitationStatusAccepted, + InvitationStatusAccepting, + InvitationStatusRejected, + InvitationStatusExpired, + } +} + const ( // MemberStatusCreating is a MemberStatus enum value MemberStatusCreating = "CREATING" @@ -6757,6 +6783,18 @@ const ( MemberStatusDeleted = "DELETED" ) +// MemberStatus_Values returns all elements of the MemberStatus enum +func MemberStatus_Values() []string { + return []string{ + MemberStatusCreating, + MemberStatusAvailable, + MemberStatusCreateFailed, + MemberStatusUpdating, + MemberStatusDeleting, + MemberStatusDeleted, + } +} + const ( // NetworkStatusCreating is a NetworkStatus enum value NetworkStatusCreating = "CREATING" @@ -6774,6 +6812,17 @@ const ( NetworkStatusDeleted = "DELETED" ) +// NetworkStatus_Values returns all elements of the NetworkStatus enum +func NetworkStatus_Values() []string { + return []string{ + NetworkStatusCreating, + NetworkStatusAvailable, + NetworkStatusCreateFailed, + NetworkStatusDeleting, + NetworkStatusDeleted, + } +} + const ( // NodeStatusCreating is a NodeStatus enum value NodeStatusCreating = "CREATING" @@ -6797,6 +6846,19 @@ const ( NodeStatusFailed = "FAILED" ) +// NodeStatus_Values returns all elements of the NodeStatus enum +func NodeStatus_Values() []string { + return []string{ + NodeStatusCreating, + NodeStatusAvailable, + NodeStatusCreateFailed, + NodeStatusUpdating, + NodeStatusDeleting, + NodeStatusDeleted, + NodeStatusFailed, + } +} + const ( // ProposalStatusInProgress is a ProposalStatus enum value ProposalStatusInProgress = "IN_PROGRESS" @@ -6814,6 +6876,17 @@ const ( ProposalStatusActionFailed = "ACTION_FAILED" ) +// ProposalStatus_Values returns all elements of the ProposalStatus enum +func ProposalStatus_Values() []string { + return []string{ + ProposalStatusInProgress, + ProposalStatusApproved, + ProposalStatusRejected, + ProposalStatusExpired, + ProposalStatusActionFailed, + } +} + const ( // ThresholdComparatorGreaterThan is a ThresholdComparator enum value ThresholdComparatorGreaterThan = "GREATER_THAN" @@ -6822,6 +6895,14 @@ const ( ThresholdComparatorGreaterThanOrEqualTo = "GREATER_THAN_OR_EQUAL_TO" ) +// ThresholdComparator_Values returns all elements of the ThresholdComparator enum +func ThresholdComparator_Values() []string { + return []string{ + ThresholdComparatorGreaterThan, + ThresholdComparatorGreaterThanOrEqualTo, + } +} + const ( // VoteValueYes is a VoteValue enum value VoteValueYes = "YES" @@ -6829,3 +6910,11 @@ const ( // VoteValueNo is a VoteValue enum value VoteValueNo = "NO" ) + +// VoteValue_Values returns all elements of the VoteValue enum +func VoteValue_Values() []string { + return []string{ + VoteValueYes, + VoteValueNo, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/marketplacecatalog/api.go b/vendor/github.com/aws/aws-sdk-go/service/marketplacecatalog/api.go index 5eeb3bc7b0c..e8a698df2c9 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/marketplacecatalog/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/marketplacecatalog/api.go @@ -638,7 +638,17 @@ func (c *MarketplaceCatalog) StartChangeSetRequest(input *StartChangeSetInput) ( // StartChangeSet API operation for AWS Marketplace Catalog Service. // -// This operation allows you to request changes in your entities. +// This operation allows you to request changes for your entities. Within a +// single ChangeSet, you cannot start the same change type against the same +// entity multiple times. Additionally, when a ChangeSet is running, all the +// entities targeted by the different changes are locked until the ChangeSet +// has completed (either succeeded, cancelled, or failed). If you try to start +// a ChangeSet containing a change against an entity that is already locked, +// you will receive a ResourceInUseException. +// +// For example, you cannot start the ChangeSet described in the example (https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/API_StartChangeSet.html#API_StartChangeSet_Examples) +// below because it contains two changes to execute the same change type (AddRevisions) +// against the same entity (entity-id@1). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1011,6 +1021,10 @@ type ChangeSummary struct { // The type of the change. ChangeType *string `min:"1" type:"string"` + // This object contains details specific to the change type of the requested + // change. + Details *string `min:"2" type:"string"` + // The entity to be changed. Entity *Entity `type:"structure"` @@ -1034,6 +1048,12 @@ func (s *ChangeSummary) SetChangeType(v string) *ChangeSummary { return s } +// SetDetails sets the Details field's value. +func (s *ChangeSummary) SetDetails(v string) *ChangeSummary { + s.Details = &v + return s +} + // SetEntity sets the Entity field's value. func (s *ChangeSummary) SetEntity(v *Entity) *ChangeSummary { s.Entity = v @@ -1388,13 +1408,13 @@ type EntitySummary struct { // The last time the entity was published, using ISO 8601 format (2018-02-27T13:45:22Z). LastModifiedDate *string `type:"string"` - // The name for the entity. This value is not unique. It is defined by the provider. + // The name for the entity. This value is not unique. It is defined by the seller. Name *string `type:"string"` - // The visibility status of the entity to subscribers. This value can be Public - // (everyone can view the entity), Limited (the entity is visible to limited - // accounts only), or Restricted (the entity was published and then unpublished - // and only existing subscribers can view it). + // The visibility status of the entity to buyers. This value can be Public (everyone + // can view the entity), Limited (the entity is visible to limited accounts + // only), or Restricted (the entity was published and then unpublished and only + // existing buyers can view it). Visibility *string `type:"string"` } @@ -1628,7 +1648,7 @@ type ListChangeSetsInput struct { // results. NextToken *string `min:"1" type:"string"` - // An object that contains two attributes, sortBy and sortOrder. + // An object that contains two attributes, SortBy and SortOrder. Sort *Sort `type:"structure"` } @@ -1768,7 +1788,7 @@ type ListEntitiesInput struct { // The value of the next token, if it exists. Null if there are no more results. NextToken *string `min:"1" type:"string"` - // An object that contains two attributes, sortBy and sortOrder. + // An object that contains two attributes, SortBy and SortOrder. Sort *Sort `type:"structure"` } @@ -2120,7 +2140,7 @@ func (s *ServiceQuotaExceededException) RequestID() string { return s.RespMetadata.RequestID } -// An object that contains two attributes, sortBy and sortOrder. +// An object that contains two attributes, SortBy and SortOrder. type Sort struct { _ struct{} `type:"structure"` @@ -2423,6 +2443,17 @@ const ( ChangeStatusFailed = "FAILED" ) +// ChangeStatus_Values returns all elements of the ChangeStatus enum +func ChangeStatus_Values() []string { + return []string{ + ChangeStatusPreparing, + ChangeStatusApplying, + ChangeStatusSucceeded, + ChangeStatusCancelled, + ChangeStatusFailed, + } +} + const ( // SortOrderAscending is a SortOrder enum value SortOrderAscending = "ASCENDING" @@ -2430,3 +2461,11 @@ const ( // SortOrderDescending is a SortOrder enum value SortOrderDescending = "DESCENDING" ) + +// SortOrder_Values returns all elements of the SortOrder enum +func SortOrder_Values() []string { + return []string{ + SortOrderAscending, + SortOrderDescending, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/marketplacecatalog/doc.go b/vendor/github.com/aws/aws-sdk-go/service/marketplacecatalog/doc.go index debadb7b02f..4b61f907021 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/marketplacecatalog/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/marketplacecatalog/doc.go @@ -3,8 +3,8 @@ // Package marketplacecatalog provides the client and types for making API // requests to AWS Marketplace Catalog Service. // -// Catalog API actions allow you to create, describe, list, and delete changes -// to your published entities. An entity is a product or an offer on AWS Marketplace. +// Catalog API actions allow you to manage your entities through list, describe, +// and update capabilities. An entity can be a product or an offer on AWS Marketplace. // // You can automate your entity update process by integrating the AWS Marketplace // Catalog API with your AWS Marketplace product build or deployment pipelines. diff --git a/vendor/github.com/aws/aws-sdk-go/service/mediaconnect/api.go b/vendor/github.com/aws/aws-sdk-go/service/mediaconnect/api.go index 789b705c351..294dc80690d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/mediaconnect/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/mediaconnect/api.go @@ -3508,6 +3508,9 @@ type Entitlement struct { // EntitlementArn is a required field EntitlementArn *string `locationName:"entitlementArn" type:"string" required:"true"` + // An indication of whether the entitlement is enabled. + EntitlementStatus *string `locationName:"entitlementStatus" type:"string" enum:"EntitlementStatus"` + // The name of the entitlement. // // Name is a required field @@ -3555,6 +3558,12 @@ func (s *Entitlement) SetEntitlementArn(v string) *Entitlement { return s } +// SetEntitlementStatus sets the EntitlementStatus field's value. +func (s *Entitlement) SetEntitlementStatus(v string) *Entitlement { + s.EntitlementStatus = &v + return s +} + // SetName sets the Name field's value. func (s *Entitlement) SetName(v string) *Entitlement { s.Name = &v @@ -3812,6 +3821,11 @@ type GrantEntitlementRequest struct { // with this entitlement. Encryption *Encryption `locationName:"encryption" type:"structure"` + // An indication of whether the new entitlement should be enabled or disabled + // as soon as it is created. If you don’t specify the entitlementStatus field + // in your request, MediaConnect sets it to ENABLED. + EntitlementStatus *string `locationName:"entitlementStatus" type:"string" enum:"EntitlementStatus"` + // The name of the entitlement. This value must be unique within the current // flow. Name *string `locationName:"name" type:"string"` @@ -3870,6 +3884,12 @@ func (s *GrantEntitlementRequest) SetEncryption(v *Encryption) *GrantEntitlement return s } +// SetEntitlementStatus sets the EntitlementStatus field's value. +func (s *GrantEntitlementRequest) SetEntitlementStatus(v string) *GrantEntitlementRequest { + s.EntitlementStatus = &v + return s +} + // SetName sets the Name field's value. func (s *GrantEntitlementRequest) SetName(v string) *GrantEntitlementRequest { s.Name = &v @@ -5918,6 +5938,12 @@ type UpdateFlowEntitlementInput struct { // EntitlementArn is a required field EntitlementArn *string `location:"uri" locationName:"entitlementArn" type:"string" required:"true"` + // An indication of whether you want to enable the entitlement to allow access, + // or disable it to stop streaming content to the subscriber’s flow temporarily. + // If you don’t specify the entitlementStatus field in your request, MediaConnect + // leaves the value unchanged. + EntitlementStatus *string `locationName:"entitlementStatus" type:"string" enum:"EntitlementStatus"` + // FlowArn is a required field FlowArn *string `location:"uri" locationName:"flowArn" type:"string" required:"true"` @@ -5977,6 +6003,12 @@ func (s *UpdateFlowEntitlementInput) SetEntitlementArn(v string) *UpdateFlowEnti return s } +// SetEntitlementStatus sets the EntitlementStatus field's value. +func (s *UpdateFlowEntitlementInput) SetEntitlementStatus(v string) *UpdateFlowEntitlementInput { + s.EntitlementStatus = &v + return s +} + // SetFlowArn sets the FlowArn field's value. func (s *UpdateFlowEntitlementInput) SetFlowArn(v string) *UpdateFlowEntitlementInput { s.FlowArn = &v @@ -6662,6 +6694,31 @@ const ( AlgorithmAes256 = "aes256" ) +// Algorithm_Values returns all elements of the Algorithm enum +func Algorithm_Values() []string { + return []string{ + AlgorithmAes128, + AlgorithmAes192, + AlgorithmAes256, + } +} + +const ( + // EntitlementStatusEnabled is a EntitlementStatus enum value + EntitlementStatusEnabled = "ENABLED" + + // EntitlementStatusDisabled is a EntitlementStatus enum value + EntitlementStatusDisabled = "DISABLED" +) + +// EntitlementStatus_Values returns all elements of the EntitlementStatus enum +func EntitlementStatus_Values() []string { + return []string{ + EntitlementStatusEnabled, + EntitlementStatusDisabled, + } +} + const ( // KeyTypeSpeke is a KeyType enum value KeyTypeSpeke = "speke" @@ -6670,6 +6727,14 @@ const ( KeyTypeStaticKey = "static-key" ) +// KeyType_Values returns all elements of the KeyType enum +func KeyType_Values() []string { + return []string{ + KeyTypeSpeke, + KeyTypeStaticKey, + } +} + const ( // ProtocolZixiPush is a Protocol enum value ProtocolZixiPush = "zixi-push" @@ -6687,6 +6752,17 @@ const ( ProtocolRist = "rist" ) +// Protocol_Values returns all elements of the Protocol enum +func Protocol_Values() []string { + return []string{ + ProtocolZixiPush, + ProtocolRtpFec, + ProtocolRtp, + ProtocolZixiPull, + ProtocolRist, + } +} + const ( // SourceTypeOwned is a SourceType enum value SourceTypeOwned = "OWNED" @@ -6695,6 +6771,14 @@ const ( SourceTypeEntitled = "ENTITLED" ) +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeOwned, + SourceTypeEntitled, + } +} + const ( // StateEnabled is a State enum value StateEnabled = "ENABLED" @@ -6703,6 +6787,14 @@ const ( StateDisabled = "DISABLED" ) +// State_Values returns all elements of the State enum +func State_Values() []string { + return []string{ + StateEnabled, + StateDisabled, + } +} + const ( // StatusStandby is a Status enum value StatusStandby = "STANDBY" @@ -6725,3 +6817,16 @@ const ( // StatusError is a Status enum value StatusError = "ERROR" ) + +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusStandby, + StatusActive, + StatusUpdating, + StatusDeleting, + StatusStarting, + StatusStopping, + StatusError, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/mediaconvert/api.go b/vendor/github.com/aws/aws-sdk-go/service/mediaconvert/api.go index 3e7bff6c792..d1ef1116776 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/mediaconvert/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/mediaconvert/api.go @@ -3014,7 +3014,8 @@ func (s AssociateCertificateOutput) GoString() string { // codec enum that you choose, define the corresponding settings object. The // following lists the codec enum, settings object pairs. * AAC, AacSettings // * MP2, Mp2Settings * MP3, Mp3Settings * WAV, WavSettings * AIFF, AiffSettings -// * AC3, Ac3Settings * EAC3, Eac3Settings * EAC3_ATMOS, Eac3AtmosSettings +// * AC3, Ac3Settings * EAC3, Eac3Settings * EAC3_ATMOS, Eac3AtmosSettings * +// VORBIS, VorbisSettings * OPUS, OpusSettings type AudioCodecSettings struct { _ struct{} `type:"structure"` @@ -3054,6 +3055,14 @@ type AudioCodecSettings struct { // value MP3. Mp3Settings *Mp3Settings `locationName:"mp3Settings" type:"structure"` + // Required when you set Codec, under AudioDescriptions>CodecSettings, to the + // value OPUS. + OpusSettings *OpusSettings `locationName:"opusSettings" type:"structure"` + + // Required when you set Codec, under AudioDescriptions>CodecSettings, to the + // value Vorbis. + VorbisSettings *VorbisSettings `locationName:"vorbisSettings" type:"structure"` + // Required when you set (Codec) under (AudioDescriptions)>(CodecSettings) to // the value WAV. WavSettings *WavSettings `locationName:"wavSettings" type:"structure"` @@ -3107,6 +3116,16 @@ func (s *AudioCodecSettings) Validate() error { invalidParams.AddNested("Mp3Settings", err.(request.ErrInvalidParams)) } } + if s.OpusSettings != nil { + if err := s.OpusSettings.Validate(); err != nil { + invalidParams.AddNested("OpusSettings", err.(request.ErrInvalidParams)) + } + } + if s.VorbisSettings != nil { + if err := s.VorbisSettings.Validate(); err != nil { + invalidParams.AddNested("VorbisSettings", err.(request.ErrInvalidParams)) + } + } if s.WavSettings != nil { if err := s.WavSettings.Validate(); err != nil { invalidParams.AddNested("WavSettings", err.(request.ErrInvalidParams)) @@ -3167,6 +3186,18 @@ func (s *AudioCodecSettings) SetMp3Settings(v *Mp3Settings) *AudioCodecSettings return s } +// SetOpusSettings sets the OpusSettings field's value. +func (s *AudioCodecSettings) SetOpusSettings(v *OpusSettings) *AudioCodecSettings { + s.OpusSettings = v + return s +} + +// SetVorbisSettings sets the VorbisSettings field's value. +func (s *AudioCodecSettings) SetVorbisSettings(v *VorbisSettings) *AudioCodecSettings { + s.VorbisSettings = v + return s +} + // SetWavSettings sets the WavSettings field's value. func (s *AudioCodecSettings) SetWavSettings(v *WavSettings) *AudioCodecSettings { s.WavSettings = v @@ -3212,7 +3243,8 @@ type AudioDescription struct { // codec enum that you choose, define the corresponding settings object. The // following lists the codec enum, settings object pairs. * AAC, AacSettings // * MP2, Mp2Settings * MP3, Mp3Settings * WAV, WavSettings * AIFF, AiffSettings - // * AC3, Ac3Settings * EAC3, Eac3Settings * EAC3_ATMOS, Eac3AtmosSettings + // * AC3, Ac3Settings * EAC3, Eac3Settings * EAC3_ATMOS, Eac3AtmosSettings * + // VORBIS, VorbisSettings * OPUS, OpusSettings CodecSettings *AudioCodecSettings `locationName:"codecSettings" type:"structure"` // Specify the language for this audio output track. The service puts this language @@ -3700,7 +3732,8 @@ type Av1Settings struct { // rate you specify in the settings FramerateNumerator and FramerateDenominator. FramerateControl *string `locationName:"framerateControl" type:"string" enum:"Av1FramerateControl"` - // When set to INTERPOLATE, produces smoother motion during frame rate conversion. + // Optional. Specify how the transcoder performs framerate conversion. The default + // behavior is to use duplicate drop conversion. FramerateConversionAlgorithm *string `locationName:"framerateConversionAlgorithm" type:"string" enum:"Av1FramerateConversionAlgorithm"` // When you use the API for transcode jobs that use frame rate conversion, specify @@ -4632,23 +4665,23 @@ func (s *CaptionSelector) SetSourceSettings(v *CaptionSourceSettings) *CaptionSe } // Ignore this setting unless your input captions format is SCC. To have the -// service compensate for differing framerates between your input captions and -// input video, specify the framerate of the captions file. Specify this value -// as a fraction, using the settings Framerate numerator (framerateNumerator) +// service compensate for differing frame rates between your input captions +// and input video, specify the frame rate of the captions file. Specify this +// value as a fraction, using the settings Framerate numerator (framerateNumerator) // and Framerate denominator (framerateDenominator). For example, you might // specify 24 / 1 for 24 fps, 25 / 1 for 25 fps, 24000 / 1001 for 23.976 fps, // or 30000 / 1001 for 29.97 fps. type CaptionSourceFramerate struct { _ struct{} `type:"structure"` - // Specify the denominator of the fraction that represents the framerate for - // the setting Caption source framerate (CaptionSourceFramerate). Use this setting - // along with the setting Framerate numerator (framerateNumerator). + // Specify the denominator of the fraction that represents the frame rate for + // the setting Caption source frame rate (CaptionSourceFramerate). Use this + // setting along with the setting Framerate numerator (framerateNumerator). FramerateDenominator *int64 `locationName:"framerateDenominator" min:"1" type:"integer"` - // Specify the numerator of the fraction that represents the framerate for the - // setting Caption source framerate (CaptionSourceFramerate). Use this setting - // along with the setting Framerate denominator (framerateDenominator). + // Specify the numerator of the fraction that represents the frame rate for + // the setting Caption source frame rate (CaptionSourceFramerate). Use this + // setting along with the setting Framerate denominator (framerateDenominator). FramerateNumerator *int64 `locationName:"framerateNumerator" min:"1" type:"integer"` } @@ -8275,9 +8308,9 @@ type FileSourceSettings struct { Convert608To708 *string `locationName:"convert608To708" type:"string" enum:"FileSourceConvert608To708"` // Ignore this setting unless your input captions format is SCC. To have the - // service compensate for differing framerates between your input captions and - // input video, specify the framerate of the captions file. Specify this value - // as a fraction, using the settings Framerate numerator (framerateNumerator) + // service compensate for differing frame rates between your input captions + // and input video, specify the frame rate of the captions file. Specify this + // value as a fraction, using the settings Framerate numerator (framerateNumerator) // and Framerate denominator (framerateDenominator). For example, you might // specify 24 / 1 for 24 fps, 25 / 1 for 25 fps, 24000 / 1001 for 23.976 fps, // or 30000 / 1001 for 29.97 fps. @@ -8887,7 +8920,8 @@ type H264Settings struct { // rate you specify in the settings FramerateNumerator and FramerateDenominator. FramerateControl *string `locationName:"framerateControl" type:"string" enum:"H264FramerateControl"` - // When set to INTERPOLATE, produces smoother motion during frame rate conversion. + // Optional. Specify how the transcoder performs framerate conversion. The default + // behavior is to use duplicate drop conversion. FramerateConversionAlgorithm *string `locationName:"framerateConversionAlgorithm" type:"string" enum:"H264FramerateConversionAlgorithm"` // When you use the API for transcode jobs that use frame rate conversion, specify @@ -8959,20 +8993,34 @@ type H264Settings struct { // if using B-frames and/or interlaced encoding. NumberReferenceFrames *int64 `locationName:"numberReferenceFrames" min:"1" type:"integer"` - // Using the API, enable ParFollowSource if you want the service to use the - // pixel aspect ratio from the input. Using the console, do this by choosing - // Follow source for Pixel aspect ratio. + // Optional. Specify how the service determines the pixel aspect ratio (PAR) + // for this output. The default behavior, Follow source (INITIALIZE_FROM_SOURCE), + // uses the PAR from your input video for your output. To specify a different + // PAR in the console, choose any value other than Follow source. To specify + // a different PAR by editing the JSON job specification, choose SPECIFIED. + // When you choose SPECIFIED for this setting, you must also specify values + // for the parNumerator and parDenominator settings. ParControl *string `locationName:"parControl" type:"string" enum:"H264ParControl"` - // Pixel Aspect Ratio denominator. + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parDenominator is 33. ParDenominator *int64 `locationName:"parDenominator" min:"1" type:"integer"` - // Pixel Aspect Ratio numerator. + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parNumerator is 40. ParNumerator *int64 `locationName:"parNumerator" min:"1" type:"integer"` - // Use Quality tuning level (H264QualityTuningLevel) to specifiy whether to - // use fast single-pass, high-quality singlepass, or high-quality multipass - // video encoding. + // Optional. Use Quality tuning level (qualityTuningLevel) to choose how you + // want to trade off encoding speed for output video quality. The default behavior + // is faster, lower quality, single-pass encoding. QualityTuningLevel *string `locationName:"qualityTuningLevel" type:"string" enum:"H264QualityTuningLevel"` // Settings for quality-defined variable bitrate encoding with the H.264 codec. @@ -9434,14 +9482,15 @@ type H265Settings struct { // a frame rate from the dropdown list or choose Custom. The framerates shown // in the dropdown list are decimal approximations of fractions. If you choose // Custom, specify your frame rate as a fraction. If you are creating your transcoding - // job sepecification as a JSON file without the console, use FramerateControl + // job specification as a JSON file without the console, use FramerateControl // to specify which value the service uses for the frame rate for this output. // Choose INITIALIZE_FROM_SOURCE if you want the service to use the frame rate // from the input. Choose SPECIFIED if you want the service to use the frame // rate you specify in the settings FramerateNumerator and FramerateDenominator. FramerateControl *string `locationName:"framerateControl" type:"string" enum:"H265FramerateControl"` - // When set to INTERPOLATE, produces smoother motion during frame rate conversion. + // Optional. Specify how the transcoder performs framerate conversion. The default + // behavior is to use duplicate drop conversion. FramerateConversionAlgorithm *string `locationName:"framerateConversionAlgorithm" type:"string" enum:"H265FramerateConversionAlgorithm"` // Frame rate denominator. @@ -9509,20 +9558,34 @@ type H265Settings struct { // if using B-frames and/or interlaced encoding. NumberReferenceFrames *int64 `locationName:"numberReferenceFrames" min:"1" type:"integer"` - // Using the API, enable ParFollowSource if you want the service to use the - // pixel aspect ratio from the input. Using the console, do this by choosing - // Follow source for Pixel aspect ratio. + // Optional. Specify how the service determines the pixel aspect ratio (PAR) + // for this output. The default behavior, Follow source (INITIALIZE_FROM_SOURCE), + // uses the PAR from your input video for your output. To specify a different + // PAR in the console, choose any value other than Follow source. To specify + // a different PAR by editing the JSON job specification, choose SPECIFIED. + // When you choose SPECIFIED for this setting, you must also specify values + // for the parNumerator and parDenominator settings. ParControl *string `locationName:"parControl" type:"string" enum:"H265ParControl"` - // Pixel Aspect Ratio denominator. + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parDenominator is 33. ParDenominator *int64 `locationName:"parDenominator" min:"1" type:"integer"` - // Pixel Aspect Ratio numerator. + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parNumerator is 40. ParNumerator *int64 `locationName:"parNumerator" min:"1" type:"integer"` - // Use Quality tuning level (H265QualityTuningLevel) to specifiy whether to - // use fast single-pass, high-quality singlepass, or high-quality multipass - // video encoding. + // Optional. Use Quality tuning level (qualityTuningLevel) to choose how you + // want to trade off encoding speed for output video quality. The default behavior + // is faster, lower quality, single-pass encoding. QualityTuningLevel *string `locationName:"qualityTuningLevel" type:"string" enum:"H265QualityTuningLevel"` // Settings for quality-defined variable bitrate encoding with the H.265 codec. @@ -10862,13 +10925,12 @@ type Input struct { AudioSelectorGroups map[string]*AudioSelectorGroup `locationName:"audioSelectorGroups" type:"map"` // Use Audio selectors (AudioSelectors) to specify a track or set of tracks - // from the input that you will use in your outputs. You can use mutiple Audio + // from the input that you will use in your outputs. You can use multiple Audio // selectors per input. AudioSelectors map[string]*AudioSelector `locationName:"audioSelectors" type:"map"` - // Use Captions selectors (CaptionSelectors) to specify the captions data from - // the input that you will use in your outputs. You can use mutiple captions - // selectors per input. + // Use captions selectors to specify the captions data from your input that + // you use in your outputs. You can use up to 20 captions selectors per input. CaptionSelectors map[string]*CaptionSelector `locationName:"captionSelectors" type:"map"` // Use Cropping selection (crop) to specify the video area that the service @@ -10878,7 +10940,7 @@ type Input struct { Crop *Rectangle `locationName:"crop" type:"structure"` // Enable Deblock (InputDeblockFilter) to produce smoother motion in the output. - // Default is disabled. Only manaully controllable for MPEG2 and uncompressed + // Default is disabled. Only manually controllable for MPEG2 and uncompressed // video inputs. DeblockFilter *string `locationName:"deblockFilter" type:"string" enum:"InputDeblockFilter"` @@ -11310,13 +11372,12 @@ type InputTemplate struct { AudioSelectorGroups map[string]*AudioSelectorGroup `locationName:"audioSelectorGroups" type:"map"` // Use Audio selectors (AudioSelectors) to specify a track or set of tracks - // from the input that you will use in your outputs. You can use mutiple Audio + // from the input that you will use in your outputs. You can use multiple Audio // selectors per input. AudioSelectors map[string]*AudioSelector `locationName:"audioSelectors" type:"map"` - // Use Captions selectors (CaptionSelectors) to specify the captions data from - // the input that you will use in your outputs. You can use mutiple captions - // selectors per input. + // Use captions selectors to specify the captions data from your input that + // you use in your outputs. You can use up to 20 captions selectors per input. CaptionSelectors map[string]*CaptionSelector `locationName:"captionSelectors" type:"map"` // Use Cropping selection (crop) to specify the video area that the service @@ -11326,7 +11387,7 @@ type InputTemplate struct { Crop *Rectangle `locationName:"crop" type:"structure"` // Enable Deblock (InputDeblockFilter) to produce smoother motion in the output. - // Default is disabled. Only manaully controllable for MPEG2 and uncompressed + // Default is disabled. Only manually controllable for MPEG2 and uncompressed // video inputs. DeblockFilter *string `locationName:"deblockFilter" type:"string" enum:"InputDeblockFilter"` @@ -14373,14 +14434,15 @@ type Mpeg2Settings struct { // a frame rate from the dropdown list or choose Custom. The framerates shown // in the dropdown list are decimal approximations of fractions. If you choose // Custom, specify your frame rate as a fraction. If you are creating your transcoding - // job sepecification as a JSON file without the console, use FramerateControl + // job specification as a JSON file without the console, use FramerateControl // to specify which value the service uses for the frame rate for this output. // Choose INITIALIZE_FROM_SOURCE if you want the service to use the frame rate // from the input. Choose SPECIFIED if you want the service to use the frame // rate you specify in the settings FramerateNumerator and FramerateDenominator. FramerateControl *string `locationName:"framerateControl" type:"string" enum:"Mpeg2FramerateControl"` - // When set to INTERPOLATE, produces smoother motion during frame rate conversion. + // Optional. Specify how the transcoder performs framerate conversion. The default + // behavior is to use duplicate drop conversion. FramerateConversionAlgorithm *string `locationName:"framerateConversionAlgorithm" type:"string" enum:"Mpeg2FramerateConversionAlgorithm"` // Frame rate denominator. @@ -14445,19 +14507,34 @@ type Mpeg2Settings struct { // Number of B-frames between reference frames. NumberBFramesBetweenReferenceFrames *int64 `locationName:"numberBFramesBetweenReferenceFrames" type:"integer"` - // Using the API, enable ParFollowSource if you want the service to use the - // pixel aspect ratio from the input. Using the console, do this by choosing - // Follow source for Pixel aspect ratio. + // Optional. Specify how the service determines the pixel aspect ratio (PAR) + // for this output. The default behavior, Follow source (INITIALIZE_FROM_SOURCE), + // uses the PAR from your input video for your output. To specify a different + // PAR in the console, choose any value other than Follow source. To specify + // a different PAR by editing the JSON job specification, choose SPECIFIED. + // When you choose SPECIFIED for this setting, you must also specify values + // for the parNumerator and parDenominator settings. ParControl *string `locationName:"parControl" type:"string" enum:"Mpeg2ParControl"` - // Pixel Aspect Ratio denominator. + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parDenominator is 33. ParDenominator *int64 `locationName:"parDenominator" min:"1" type:"integer"` - // Pixel Aspect Ratio numerator. + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parNumerator is 40. ParNumerator *int64 `locationName:"parNumerator" min:"1" type:"integer"` - // Use Quality tuning level (Mpeg2QualityTuningLevel) to specifiy whether to - // use single-pass or multipass video encoding. + // Optional. Use Quality tuning level (qualityTuningLevel) to choose how you + // want to trade off encoding speed for output video quality. The default behavior + // is faster, lower quality, single-pass encoding. QualityTuningLevel *string `locationName:"qualityTuningLevel" type:"string" enum:"Mpeg2QualityTuningLevel"` // Use Rate control mode (Mpeg2RateControlMode) to specifiy whether the bitrate @@ -14944,6 +15021,92 @@ func (s *MxfSettings) SetAfdSignaling(v string) *MxfSettings { return s } +// For forensic video watermarking, MediaConvert supports Nagra NexGuard File +// Marker watermarking. MediaConvert supports both PreRelease Content (NGPR/G2) +// and OTT Streaming workflows. +type NexGuardFileMarkerSettings struct { + _ struct{} `type:"structure"` + + // Use the base64 license string that Nagra provides you. Enter it directly + // in your JSON job specification or in the console. Required when you include + // Nagra NexGuard File Marker watermarking (NexGuardWatermarkingSettings) in + // your job. + License *string `locationName:"license" min:"1" type:"string"` + + // Specify the payload ID that you want associated with this output. Valid values + // vary depending on your Nagra NexGuard forensic watermarking workflow. Required + // when you include Nagra NexGuard File Marker watermarking (NexGuardWatermarkingSettings) + // in your job. For PreRelease Content (NGPR/G2), specify an integer from 1 + // through 4,194,303. You must generate a unique ID for each asset you watermark, + // and keep a record of which ID you have assigned to each asset. Neither Nagra + // nor MediaConvert keep track of the relationship between output files and + // your IDs. For OTT Streaming, create two adaptive bitrate (ABR) stacks for + // each asset. Do this by setting up two output groups. For one output group, + // set the value of Payload ID (payload) to 0 in every output. For the other + // output group, set Payload ID (payload) to 1 in every output. + Payload *int64 `locationName:"payload" type:"integer"` + + // Enter one of the watermarking preset strings that Nagra provides you. Required + // when you include Nagra NexGuard File Marker watermarking (NexGuardWatermarkingSettings) + // in your job. + Preset *string `locationName:"preset" min:"1" type:"string"` + + // Optional. Ignore this setting unless Nagra support directs you to specify + // a value. When you don't specify a value here, the Nagra NexGuard library + // uses its default value. + Strength *string `locationName:"strength" type:"string" enum:"WatermarkingStrength"` +} + +// String returns the string representation +func (s NexGuardFileMarkerSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s NexGuardFileMarkerSettings) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *NexGuardFileMarkerSettings) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "NexGuardFileMarkerSettings"} + if s.License != nil && len(*s.License) < 1 { + invalidParams.Add(request.NewErrParamMinLen("License", 1)) + } + if s.Preset != nil && len(*s.Preset) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Preset", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLicense sets the License field's value. +func (s *NexGuardFileMarkerSettings) SetLicense(v string) *NexGuardFileMarkerSettings { + s.License = &v + return s +} + +// SetPayload sets the Payload field's value. +func (s *NexGuardFileMarkerSettings) SetPayload(v int64) *NexGuardFileMarkerSettings { + s.Payload = &v + return s +} + +// SetPreset sets the Preset field's value. +func (s *NexGuardFileMarkerSettings) SetPreset(v string) *NexGuardFileMarkerSettings { + s.Preset = &v + return s +} + +// SetStrength sets the Strength field's value. +func (s *NexGuardFileMarkerSettings) SetStrength(v string) *NexGuardFileMarkerSettings { + s.Strength = &v + return s +} + // Settings for your Nielsen configuration. If you don't do Nielsen measurement // and analytics, ignore these settings. When you enable Nielsen configuration // (nielsenConfiguration), MediaConvert enables PCM to ID3 tagging for all outputs @@ -15158,6 +15321,12 @@ type NoiseReducerTemporalFilterSettings struct { // and creates better VQ for low bitrate outputs. AggressiveMode *int64 `locationName:"aggressiveMode" type:"integer"` + // Optional. When you set Noise reducer (noiseReducer) to Temporal (TEMPORAL), + // you can optionally use this setting to apply additional sharpening. The default + // behavior, Auto (AUTO) allows the transcoder to determine whether to apply + // filtering, depending on input type and quality. + PostTemporalSharpening *string `locationName:"postTemporalSharpening" type:"string" enum:"NoiseFilterPostTemporalSharpening"` + // The speed of the filter (higher number is faster). Low setting reduces bit // rate at the cost of transcode time, high setting improves transcode time // at the cost of bit rate. @@ -15200,6 +15369,12 @@ func (s *NoiseReducerTemporalFilterSettings) SetAggressiveMode(v int64) *NoiseRe return s } +// SetPostTemporalSharpening sets the PostTemporalSharpening field's value. +func (s *NoiseReducerTemporalFilterSettings) SetPostTemporalSharpening(v string) *NoiseReducerTemporalFilterSettings { + s.PostTemporalSharpening = &v + return s +} + // SetSpeed sets the Speed field's value. func (s *NoiseReducerTemporalFilterSettings) SetSpeed(v int64) *NoiseReducerTemporalFilterSettings { s.Speed = &v @@ -15267,6 +15442,73 @@ func (s *NotFoundException) RequestID() string { return s.RespMetadata.RequestID } +// Required when you set Codec, under AudioDescriptions>CodecSettings, to the +// value OPUS. +type OpusSettings struct { + _ struct{} `type:"structure"` + + // Optional. Specify the average bitrate in bits per second. Valid values are + // multiples of 8000, from 32000 through 192000. The default value is 96000, + // which we recommend for quality and bandwidth. + Bitrate *int64 `locationName:"bitrate" min:"32000" type:"integer"` + + // Specify the number of channels in this output audio track. Choosing Mono + // on the console gives you 1 output channel; choosing Stereo gives you 2. In + // the API, valid values are 1 and 2. + Channels *int64 `locationName:"channels" min:"1" type:"integer"` + + // Optional. Sample rate in hz. Valid values are 16000, 24000, and 48000. The + // default value is 48000. + SampleRate *int64 `locationName:"sampleRate" min:"16000" type:"integer"` +} + +// String returns the string representation +func (s OpusSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OpusSettings) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *OpusSettings) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OpusSettings"} + if s.Bitrate != nil && *s.Bitrate < 32000 { + invalidParams.Add(request.NewErrParamMinValue("Bitrate", 32000)) + } + if s.Channels != nil && *s.Channels < 1 { + invalidParams.Add(request.NewErrParamMinValue("Channels", 1)) + } + if s.SampleRate != nil && *s.SampleRate < 16000 { + invalidParams.Add(request.NewErrParamMinValue("SampleRate", 16000)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBitrate sets the Bitrate field's value. +func (s *OpusSettings) SetBitrate(v int64) *OpusSettings { + s.Bitrate = &v + return s +} + +// SetChannels sets the Channels field's value. +func (s *OpusSettings) SetChannels(v int64) *OpusSettings { + s.Channels = &v + return s +} + +// SetSampleRate sets the SampleRate field's value. +func (s *OpusSettings) SetSampleRate(v int64) *OpusSettings { + s.SampleRate = &v + return s +} + // An output object describes the settings for a single output file or stream // in an output group. type Output struct { @@ -15288,8 +15530,9 @@ type Output struct { // Use Extension (Extension) to specify the file extension for outputs in File // output groups. If you do not specify a value, the service will use default // extensions by container type as follows * MPEG-2 transport stream, m2ts * - // Quicktime, mov * MXF container, mxf * MPEG-4 container, mp4 * No Container, - // the service will use codec extensions (e.g. AAC, H265, H265, AC3) + // Quicktime, mov * MXF container, mxf * MPEG-4 container, mp4 * WebM container, + // webm * No Container, the service will use codec extensions (e.g. AAC, H265, + // H265, AC3) Extension *string `locationName:"extension" type:"string"` // Use Name modifier (NameModifier) to have the service add a string to the @@ -15708,6 +15951,49 @@ func (s *OutputSettings) SetHlsSettings(v *HlsSettings) *OutputSettings { return s } +// If you work with a third party video watermarking partner, use the group +// of settings that correspond with your watermarking partner to include watermarks +// in your output. +type PartnerWatermarking struct { + _ struct{} `type:"structure"` + + // For forensic video watermarking, MediaConvert supports Nagra NexGuard File + // Marker watermarking. MediaConvert supports both PreRelease Content (NGPR/G2) + // and OTT Streaming workflows. + NexguardFileMarkerSettings *NexGuardFileMarkerSettings `locationName:"nexguardFileMarkerSettings" type:"structure"` +} + +// String returns the string representation +func (s PartnerWatermarking) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PartnerWatermarking) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PartnerWatermarking) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PartnerWatermarking"} + if s.NexguardFileMarkerSettings != nil { + if err := s.NexguardFileMarkerSettings.Validate(); err != nil { + invalidParams.AddNested("NexguardFileMarkerSettings", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetNexguardFileMarkerSettings sets the NexguardFileMarkerSettings field's value. +func (s *PartnerWatermarking) SetNexguardFileMarkerSettings(v *NexGuardFileMarkerSettings) *PartnerWatermarking { + s.NexguardFileMarkerSettings = v + return s +} + // A preset is a collection of preconfigured media conversion settings that // you want MediaConvert to apply to the output during the conversion process. type Preset struct { @@ -15913,14 +16199,15 @@ type ProresSettings struct { // a frame rate from the dropdown list or choose Custom. The framerates shown // in the dropdown list are decimal approximations of fractions. If you choose // Custom, specify your frame rate as a fraction. If you are creating your transcoding - // job sepecification as a JSON file without the console, use FramerateControl + // job specification as a JSON file without the console, use FramerateControl // to specify which value the service uses for the frame rate for this output. // Choose INITIALIZE_FROM_SOURCE if you want the service to use the frame rate // from the input. Choose SPECIFIED if you want the service to use the frame // rate you specify in the settings FramerateNumerator and FramerateDenominator. FramerateControl *string `locationName:"framerateControl" type:"string" enum:"ProresFramerateControl"` - // When set to INTERPOLATE, produces smoother motion during frame rate conversion. + // Optional. Specify how the transcoder performs framerate conversion. The default + // behavior is to use duplicate drop conversion. FramerateConversionAlgorithm *string `locationName:"framerateConversionAlgorithm" type:"string" enum:"ProresFramerateConversionAlgorithm"` // Frame rate denominator. @@ -15945,17 +16232,29 @@ type ProresSettings struct { // on which of the Follow options you chose. InterlaceMode *string `locationName:"interlaceMode" type:"string" enum:"ProresInterlaceMode"` - // Use (ProresParControl) to specify how the service determines the pixel aspect - // ratio. Set to Follow source (INITIALIZE_FROM_SOURCE) to use the pixel aspect - // ratio from the input. To specify a different pixel aspect ratio: Using the - // console, choose it from the dropdown menu. Using the API, set ProresParControl - // to (SPECIFIED) and provide for (ParNumerator) and (ParDenominator). + // Optional. Specify how the service determines the pixel aspect ratio (PAR) + // for this output. The default behavior, Follow source (INITIALIZE_FROM_SOURCE), + // uses the PAR from your input video for your output. To specify a different + // PAR in the console, choose any value other than Follow source. To specify + // a different PAR by editing the JSON job specification, choose SPECIFIED. + // When you choose SPECIFIED for this setting, you must also specify values + // for the parNumerator and parDenominator settings. ParControl *string `locationName:"parControl" type:"string" enum:"ProresParControl"` - // Pixel Aspect Ratio denominator. + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parDenominator is 33. ParDenominator *int64 `locationName:"parDenominator" min:"1" type:"integer"` - // Pixel Aspect Ratio numerator. + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parNumerator is 40. ParNumerator *int64 `locationName:"parNumerator" min:"1" type:"integer"` // Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled @@ -17853,7 +18152,8 @@ func (s *UpdateQueueOutput) SetQueue(v *Queue) *UpdateQueueOutput { // each codec enum that you choose, define the corresponding settings object. // The following lists the codec enum, settings object pairs. * FRAME_CAPTURE, // FrameCaptureSettings * AV1, Av1Settings * H_264, H264Settings * H_265, H265Settings -// * MPEG2, Mpeg2Settings * PRORES, ProresSettings +// * MPEG2, Mpeg2Settings * PRORES, ProresSettings * VP8, Vp8Settings * VP9, +// Vp9Settings type VideoCodecSettings struct { _ struct{} `type:"structure"` @@ -17883,6 +18183,14 @@ type VideoCodecSettings struct { // Required when you set (Codec) under (VideoDescription)>(CodecSettings) to // the value PRORES. ProresSettings *ProresSettings `locationName:"proresSettings" type:"structure"` + + // Required when you set (Codec) under (VideoDescription)>(CodecSettings) to + // the value VP8. + Vp8Settings *Vp8Settings `locationName:"vp8Settings" type:"structure"` + + // Required when you set (Codec) under (VideoDescription)>(CodecSettings) to + // the value VP9. + Vp9Settings *Vp9Settings `locationName:"vp9Settings" type:"structure"` } // String returns the string representation @@ -17928,6 +18236,16 @@ func (s *VideoCodecSettings) Validate() error { invalidParams.AddNested("ProresSettings", err.(request.ErrInvalidParams)) } } + if s.Vp8Settings != nil { + if err := s.Vp8Settings.Validate(); err != nil { + invalidParams.AddNested("Vp8Settings", err.(request.ErrInvalidParams)) + } + } + if s.Vp9Settings != nil { + if err := s.Vp9Settings.Validate(); err != nil { + invalidParams.AddNested("Vp9Settings", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -17977,6 +18295,18 @@ func (s *VideoCodecSettings) SetProresSettings(v *ProresSettings) *VideoCodecSet return s } +// SetVp8Settings sets the Vp8Settings field's value. +func (s *VideoCodecSettings) SetVp8Settings(v *Vp8Settings) *VideoCodecSettings { + s.Vp8Settings = v + return s +} + +// SetVp9Settings sets the Vp9Settings field's value. +func (s *VideoCodecSettings) SetVp9Settings(v *Vp9Settings) *VideoCodecSettings { + s.Vp9Settings = v + return s +} + // Settings for video outputs type VideoDescription struct { _ struct{} `type:"structure"` @@ -18000,7 +18330,8 @@ type VideoDescription struct { // each codec enum that you choose, define the corresponding settings object. // The following lists the codec enum, settings object pairs. * FRAME_CAPTURE, // FrameCaptureSettings * AV1, Av1Settings * H_264, H264Settings * H_265, H265Settings - // * MPEG2, Mpeg2Settings * PRORES, ProresSettings + // * MPEG2, Mpeg2Settings * PRORES, ProresSettings * VP8, Vp8Settings * VP9, + // Vp9Settings CodecSettings *VideoCodecSettings `locationName:"codecSettings" type:"structure"` // Choose Insert (INSERT) for this setting to include color metadata in this @@ -18279,6 +18610,11 @@ type VideoPreprocessor struct { // individually. This setting is disabled by default. NoiseReducer *NoiseReducer `locationName:"noiseReducer" type:"structure"` + // If you work with a third party video watermarking partner, use the group + // of settings that correspond with your watermarking partner to include watermarks + // in your output. + PartnerWatermarking *PartnerWatermarking `locationName:"partnerWatermarking" type:"structure"` + // Timecode burn-in (TimecodeBurnIn)--Burns the output timecode and specified // prefix into the output. TimecodeBurnin *TimecodeBurnin `locationName:"timecodeBurnin" type:"structure"` @@ -18312,6 +18648,11 @@ func (s *VideoPreprocessor) Validate() error { invalidParams.AddNested("NoiseReducer", err.(request.ErrInvalidParams)) } } + if s.PartnerWatermarking != nil { + if err := s.PartnerWatermarking.Validate(); err != nil { + invalidParams.AddNested("PartnerWatermarking", err.(request.ErrInvalidParams)) + } + } if s.TimecodeBurnin != nil { if err := s.TimecodeBurnin.Validate(); err != nil { invalidParams.AddNested("TimecodeBurnin", err.(request.ErrInvalidParams)) @@ -18354,6 +18695,12 @@ func (s *VideoPreprocessor) SetNoiseReducer(v *NoiseReducer) *VideoPreprocessor return s } +// SetPartnerWatermarking sets the PartnerWatermarking field's value. +func (s *VideoPreprocessor) SetPartnerWatermarking(v *PartnerWatermarking) *VideoPreprocessor { + s.PartnerWatermarking = v + return s +} + // SetTimecodeBurnin sets the TimecodeBurnin field's value. func (s *VideoPreprocessor) SetTimecodeBurnin(v *TimecodeBurnin) *VideoPreprocessor { s.TimecodeBurnin = v @@ -18497,49 +18844,48 @@ func (s *VideoSelector) SetRotate(v string) *VideoSelector { return s } -// Required when you set (Codec) under (AudioDescriptions)>(CodecSettings) to -// the value WAV. -type WavSettings struct { +// Required when you set Codec, under AudioDescriptions>CodecSettings, to the +// value Vorbis. +type VorbisSettings struct { _ struct{} `type:"structure"` - // Specify Bit depth (BitDepth), in bits per sample, to choose the encoding - // quality for this audio track. - BitDepth *int64 `locationName:"bitDepth" min:"16" type:"integer"` - - // Specify the number of channels in this output audio track. Valid values are - // 1 and even numbers up to 64. For example, 1, 2, 4, 6, and so on, up to 64. + // Optional. Specify the number of channels in this output audio track. Choosing + // Mono on the console gives you 1 output channel; choosing Stereo gives you + // 2. In the API, valid values are 1 and 2. The default value is 2. Channels *int64 `locationName:"channels" min:"1" type:"integer"` - // The service defaults to using RIFF for WAV outputs. If your output audio - // is likely to exceed 4 GB in file size, or if you otherwise need the extended - // support of the RF64 format, set your output WAV file format to RF64. - Format *string `locationName:"format" type:"string" enum:"WavFormat"` + // Optional. Specify the audio sample rate in Hz. Valid values are 22050, 32000, + // 44100, and 48000. The default value is 48000. + SampleRate *int64 `locationName:"sampleRate" min:"22050" type:"integer"` - // Sample rate in Hz. - SampleRate *int64 `locationName:"sampleRate" min:"8000" type:"integer"` + // Optional. Specify the variable audio quality of this Vorbis output from -1 + // (lowest quality, ~45 kbit/s) to 10 (highest quality, ~500 kbit/s). The default + // value is 4 (~128 kbit/s). Values 5 and 6 are approximately 160 and 192 kbit/s, + // respectively. + VbrQuality *int64 `locationName:"vbrQuality" type:"integer"` } // String returns the string representation -func (s WavSettings) String() string { +func (s VorbisSettings) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s WavSettings) GoString() string { +func (s VorbisSettings) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *WavSettings) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "WavSettings"} - if s.BitDepth != nil && *s.BitDepth < 16 { - invalidParams.Add(request.NewErrParamMinValue("BitDepth", 16)) - } +func (s *VorbisSettings) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VorbisSettings"} if s.Channels != nil && *s.Channels < 1 { invalidParams.Add(request.NewErrParamMinValue("Channels", 1)) } - if s.SampleRate != nil && *s.SampleRate < 8000 { - invalidParams.Add(request.NewErrParamMinValue("SampleRate", 8000)) + if s.SampleRate != nil && *s.SampleRate < 22050 { + invalidParams.Add(request.NewErrParamMinValue("SampleRate", 22050)) + } + if s.VbrQuality != nil && *s.VbrQuality < -1 { + invalidParams.Add(request.NewErrParamMinValue("VbrQuality", -1)) } if invalidParams.Len() > 0 { @@ -18548,66 +18894,562 @@ func (s *WavSettings) Validate() error { return nil } -// SetBitDepth sets the BitDepth field's value. -func (s *WavSettings) SetBitDepth(v int64) *WavSettings { - s.BitDepth = &v - return s -} - // SetChannels sets the Channels field's value. -func (s *WavSettings) SetChannels(v int64) *WavSettings { +func (s *VorbisSettings) SetChannels(v int64) *VorbisSettings { s.Channels = &v return s } -// SetFormat sets the Format field's value. -func (s *WavSettings) SetFormat(v string) *WavSettings { - s.Format = &v +// SetSampleRate sets the SampleRate field's value. +func (s *VorbisSettings) SetSampleRate(v int64) *VorbisSettings { + s.SampleRate = &v return s } -// SetSampleRate sets the SampleRate field's value. -func (s *WavSettings) SetSampleRate(v int64) *WavSettings { - s.SampleRate = &v +// SetVbrQuality sets the VbrQuality field's value. +func (s *VorbisSettings) SetVbrQuality(v int64) *VorbisSettings { + s.VbrQuality = &v return s } -// Choose BROADCASTER_MIXED_AD when the input contains pre-mixed main audio -// + audio description (AD) as a stereo pair. The value for AudioType will be -// set to 3, which signals to downstream systems that this stream contains "broadcaster -// mixed AD". Note that the input received by the encoder must contain pre-mixed -// audio; the encoder does not perform the mixing. When you choose BROADCASTER_MIXED_AD, -// the encoder ignores any values you provide in AudioType and FollowInputAudioType. -// Choose NORMAL when the input does not contain pre-mixed audio + audio description -// (AD). In this case, the encoder will use any values you provide for AudioType -// and FollowInputAudioType. -const ( - // AacAudioDescriptionBroadcasterMixBroadcasterMixedAd is a AacAudioDescriptionBroadcasterMix enum value - AacAudioDescriptionBroadcasterMixBroadcasterMixedAd = "BROADCASTER_MIXED_AD" +// Required when you set (Codec) under (VideoDescription)>(CodecSettings) to +// the value VP8. +type Vp8Settings struct { + _ struct{} `type:"structure"` - // AacAudioDescriptionBroadcasterMixNormal is a AacAudioDescriptionBroadcasterMix enum value - AacAudioDescriptionBroadcasterMixNormal = "NORMAL" -) + // Target bitrate in bits/second. For example, enter five megabits per second + // as 5000000. + Bitrate *int64 `locationName:"bitrate" min:"1000" type:"integer"` -// AAC Profile. -const ( - // AacCodecProfileLc is a AacCodecProfile enum value - AacCodecProfileLc = "LC" + // If you are using the console, use the Framerate setting to specify the frame + // rate for this output. If you want to keep the same frame rate as the input + // video, choose Follow source. If you want to do frame rate conversion, choose + // a frame rate from the dropdown list or choose Custom. The framerates shown + // in the dropdown list are decimal approximations of fractions. If you choose + // Custom, specify your frame rate as a fraction. If you are creating your transcoding + // job specification as a JSON file without the console, use FramerateControl + // to specify which value the service uses for the frame rate for this output. + // Choose INITIALIZE_FROM_SOURCE if you want the service to use the frame rate + // from the input. Choose SPECIFIED if you want the service to use the frame + // rate you specify in the settings FramerateNumerator and FramerateDenominator. + FramerateControl *string `locationName:"framerateControl" type:"string" enum:"Vp8FramerateControl"` - // AacCodecProfileHev1 is a AacCodecProfile enum value - AacCodecProfileHev1 = "HEV1" + // Optional. Specify how the transcoder performs framerate conversion. The default + // behavior is to use Drop duplicate (DUPLICATE_DROP) conversion. When you choose + // Interpolate (INTERPOLATE) instead, the conversion produces smoother motion. + FramerateConversionAlgorithm *string `locationName:"framerateConversionAlgorithm" type:"string" enum:"Vp8FramerateConversionAlgorithm"` - // AacCodecProfileHev2 is a AacCodecProfile enum value - AacCodecProfileHev2 = "HEV2" -) + // When you use the API for transcode jobs that use frame rate conversion, specify + // the frame rate as a fraction. For example, 24000 / 1001 = 23.976 fps. Use + // FramerateDenominator to specify the denominator of this fraction. In this + // example, use 1001 for the value of FramerateDenominator. When you use the + // console for transcode jobs that use frame rate conversion, provide the value + // as a decimal number for Framerate. In this example, specify 23.976. + FramerateDenominator *int64 `locationName:"framerateDenominator" min:"1" type:"integer"` -// Mono (Audio Description), Mono, Stereo, or 5.1 channel layout. Valid values -// depend on rate control mode and profile. "1.0 - Audio Description (Receiver -// Mix)" setting receives a stereo description plus control track and emits -// a mono AAC encode of the description track, with control data emitted in -// the PES header as per ETSI TS 101 154 Annex E. -const ( - // AacCodingModeAdReceiverMix is a AacCodingMode enum value + // When you use the API for transcode jobs that use frame rate conversion, specify + // the frame rate as a fraction. For example, 24000 / 1001 = 23.976 fps. Use + // FramerateNumerator to specify the numerator of this fraction. In this example, + // use 24000 for the value of FramerateNumerator. When you use the console for + // transcode jobs that use frame rate conversion, provide the value as a decimal + // number for Framerate. In this example, specify 23.976. + FramerateNumerator *int64 `locationName:"framerateNumerator" min:"1" type:"integer"` + + // GOP Length (keyframe interval) in frames. Must be greater than zero. + GopSize *float64 `locationName:"gopSize" type:"double"` + + // Optional. Size of buffer (HRD buffer model) in bits. For example, enter five + // megabits as 5000000. + HrdBufferSize *int64 `locationName:"hrdBufferSize" type:"integer"` + + // Ignore this setting unless you set qualityTuningLevel to MULTI_PASS. Optional. + // Specify the maximum bitrate in bits/second. For example, enter five megabits + // per second as 5000000. The default behavior uses twice the target bitrate + // as the maximum bitrate. + MaxBitrate *int64 `locationName:"maxBitrate" min:"1000" type:"integer"` + + // Optional. Specify how the service determines the pixel aspect ratio (PAR) + // for this output. The default behavior, Follow source (INITIALIZE_FROM_SOURCE), + // uses the PAR from your input video for your output. To specify a different + // PAR in the console, choose any value other than Follow source. To specify + // a different PAR by editing the JSON job specification, choose SPECIFIED. + // When you choose SPECIFIED for this setting, you must also specify values + // for the parNumerator and parDenominator settings. + ParControl *string `locationName:"parControl" type:"string" enum:"Vp8ParControl"` + + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parDenominator is 33. + ParDenominator *int64 `locationName:"parDenominator" min:"1" type:"integer"` + + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parNumerator is 40. + ParNumerator *int64 `locationName:"parNumerator" min:"1" type:"integer"` + + // Optional. Use Quality tuning level (qualityTuningLevel) to choose how you + // want to trade off encoding speed for output video quality. The default behavior + // is faster, lower quality, multi-pass encoding. + QualityTuningLevel *string `locationName:"qualityTuningLevel" type:"string" enum:"Vp8QualityTuningLevel"` + + // With the VP8 codec, you can use only the variable bitrate (VBR) rate control + // mode. + RateControlMode *string `locationName:"rateControlMode" type:"string" enum:"Vp8RateControlMode"` +} + +// String returns the string representation +func (s Vp8Settings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Vp8Settings) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Vp8Settings) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Vp8Settings"} + if s.Bitrate != nil && *s.Bitrate < 1000 { + invalidParams.Add(request.NewErrParamMinValue("Bitrate", 1000)) + } + if s.FramerateDenominator != nil && *s.FramerateDenominator < 1 { + invalidParams.Add(request.NewErrParamMinValue("FramerateDenominator", 1)) + } + if s.FramerateNumerator != nil && *s.FramerateNumerator < 1 { + invalidParams.Add(request.NewErrParamMinValue("FramerateNumerator", 1)) + } + if s.MaxBitrate != nil && *s.MaxBitrate < 1000 { + invalidParams.Add(request.NewErrParamMinValue("MaxBitrate", 1000)) + } + if s.ParDenominator != nil && *s.ParDenominator < 1 { + invalidParams.Add(request.NewErrParamMinValue("ParDenominator", 1)) + } + if s.ParNumerator != nil && *s.ParNumerator < 1 { + invalidParams.Add(request.NewErrParamMinValue("ParNumerator", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBitrate sets the Bitrate field's value. +func (s *Vp8Settings) SetBitrate(v int64) *Vp8Settings { + s.Bitrate = &v + return s +} + +// SetFramerateControl sets the FramerateControl field's value. +func (s *Vp8Settings) SetFramerateControl(v string) *Vp8Settings { + s.FramerateControl = &v + return s +} + +// SetFramerateConversionAlgorithm sets the FramerateConversionAlgorithm field's value. +func (s *Vp8Settings) SetFramerateConversionAlgorithm(v string) *Vp8Settings { + s.FramerateConversionAlgorithm = &v + return s +} + +// SetFramerateDenominator sets the FramerateDenominator field's value. +func (s *Vp8Settings) SetFramerateDenominator(v int64) *Vp8Settings { + s.FramerateDenominator = &v + return s +} + +// SetFramerateNumerator sets the FramerateNumerator field's value. +func (s *Vp8Settings) SetFramerateNumerator(v int64) *Vp8Settings { + s.FramerateNumerator = &v + return s +} + +// SetGopSize sets the GopSize field's value. +func (s *Vp8Settings) SetGopSize(v float64) *Vp8Settings { + s.GopSize = &v + return s +} + +// SetHrdBufferSize sets the HrdBufferSize field's value. +func (s *Vp8Settings) SetHrdBufferSize(v int64) *Vp8Settings { + s.HrdBufferSize = &v + return s +} + +// SetMaxBitrate sets the MaxBitrate field's value. +func (s *Vp8Settings) SetMaxBitrate(v int64) *Vp8Settings { + s.MaxBitrate = &v + return s +} + +// SetParControl sets the ParControl field's value. +func (s *Vp8Settings) SetParControl(v string) *Vp8Settings { + s.ParControl = &v + return s +} + +// SetParDenominator sets the ParDenominator field's value. +func (s *Vp8Settings) SetParDenominator(v int64) *Vp8Settings { + s.ParDenominator = &v + return s +} + +// SetParNumerator sets the ParNumerator field's value. +func (s *Vp8Settings) SetParNumerator(v int64) *Vp8Settings { + s.ParNumerator = &v + return s +} + +// SetQualityTuningLevel sets the QualityTuningLevel field's value. +func (s *Vp8Settings) SetQualityTuningLevel(v string) *Vp8Settings { + s.QualityTuningLevel = &v + return s +} + +// SetRateControlMode sets the RateControlMode field's value. +func (s *Vp8Settings) SetRateControlMode(v string) *Vp8Settings { + s.RateControlMode = &v + return s +} + +// Required when you set (Codec) under (VideoDescription)>(CodecSettings) to +// the value VP9. +type Vp9Settings struct { + _ struct{} `type:"structure"` + + // Target bitrate in bits/second. For example, enter five megabits per second + // as 5000000. + Bitrate *int64 `locationName:"bitrate" min:"1000" type:"integer"` + + // If you are using the console, use the Framerate setting to specify the frame + // rate for this output. If you want to keep the same frame rate as the input + // video, choose Follow source. If you want to do frame rate conversion, choose + // a frame rate from the dropdown list or choose Custom. The framerates shown + // in the dropdown list are decimal approximations of fractions. If you choose + // Custom, specify your frame rate as a fraction. If you are creating your transcoding + // job specification as a JSON file without the console, use FramerateControl + // to specify which value the service uses for the frame rate for this output. + // Choose INITIALIZE_FROM_SOURCE if you want the service to use the frame rate + // from the input. Choose SPECIFIED if you want the service to use the frame + // rate you specify in the settings FramerateNumerator and FramerateDenominator. + FramerateControl *string `locationName:"framerateControl" type:"string" enum:"Vp9FramerateControl"` + + // Optional. Specify how the transcoder performs framerate conversion. The default + // behavior is to use Drop duplicate (DUPLICATE_DROP) conversion. When you choose + // Interpolate (INTERPOLATE) instead, the conversion produces smoother motion. + FramerateConversionAlgorithm *string `locationName:"framerateConversionAlgorithm" type:"string" enum:"Vp9FramerateConversionAlgorithm"` + + // When you use the API for transcode jobs that use frame rate conversion, specify + // the frame rate as a fraction. For example, 24000 / 1001 = 23.976 fps. Use + // FramerateDenominator to specify the denominator of this fraction. In this + // example, use 1001 for the value of FramerateDenominator. When you use the + // console for transcode jobs that use frame rate conversion, provide the value + // as a decimal number for Framerate. In this example, specify 23.976. + FramerateDenominator *int64 `locationName:"framerateDenominator" min:"1" type:"integer"` + + // When you use the API for transcode jobs that use frame rate conversion, specify + // the frame rate as a fraction. For example, 24000 / 1001 = 23.976 fps. Use + // FramerateNumerator to specify the numerator of this fraction. In this example, + // use 24000 for the value of FramerateNumerator. When you use the console for + // transcode jobs that use frame rate conversion, provide the value as a decimal + // number for Framerate. In this example, specify 23.976. + FramerateNumerator *int64 `locationName:"framerateNumerator" min:"1" type:"integer"` + + // GOP Length (keyframe interval) in frames. Must be greater than zero. + GopSize *float64 `locationName:"gopSize" type:"double"` + + // Size of buffer (HRD buffer model) in bits. For example, enter five megabits + // as 5000000. + HrdBufferSize *int64 `locationName:"hrdBufferSize" type:"integer"` + + // Ignore this setting unless you set qualityTuningLevel to MULTI_PASS. Optional. + // Specify the maximum bitrate in bits/second. For example, enter five megabits + // per second as 5000000. The default behavior uses twice the target bitrate + // as the maximum bitrate. + MaxBitrate *int64 `locationName:"maxBitrate" min:"1000" type:"integer"` + + // Optional. Specify how the service determines the pixel aspect ratio for this + // output. The default behavior is to use the same pixel aspect ratio as your + // input video. + ParControl *string `locationName:"parControl" type:"string" enum:"Vp9ParControl"` + + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parDenominator is 33. + ParDenominator *int64 `locationName:"parDenominator" min:"1" type:"integer"` + + // Required when you set Pixel aspect ratio (parControl) to SPECIFIED. On the + // console, this corresponds to any value other than Follow source. When you + // specify an output pixel aspect ratio (PAR) that is different from your input + // video PAR, provide your output PAR as a ratio. For example, for D1/DV NTSC + // widescreen, you would specify the ratio 40:33. In this example, the value + // for parNumerator is 40. + ParNumerator *int64 `locationName:"parNumerator" min:"1" type:"integer"` + + // Optional. Use Quality tuning level (qualityTuningLevel) to choose how you + // want to trade off encoding speed for output video quality. The default behavior + // is faster, lower quality, multi-pass encoding. + QualityTuningLevel *string `locationName:"qualityTuningLevel" type:"string" enum:"Vp9QualityTuningLevel"` + + // With the VP9 codec, you can use only the variable bitrate (VBR) rate control + // mode. + RateControlMode *string `locationName:"rateControlMode" type:"string" enum:"Vp9RateControlMode"` +} + +// String returns the string representation +func (s Vp9Settings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Vp9Settings) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Vp9Settings) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Vp9Settings"} + if s.Bitrate != nil && *s.Bitrate < 1000 { + invalidParams.Add(request.NewErrParamMinValue("Bitrate", 1000)) + } + if s.FramerateDenominator != nil && *s.FramerateDenominator < 1 { + invalidParams.Add(request.NewErrParamMinValue("FramerateDenominator", 1)) + } + if s.FramerateNumerator != nil && *s.FramerateNumerator < 1 { + invalidParams.Add(request.NewErrParamMinValue("FramerateNumerator", 1)) + } + if s.MaxBitrate != nil && *s.MaxBitrate < 1000 { + invalidParams.Add(request.NewErrParamMinValue("MaxBitrate", 1000)) + } + if s.ParDenominator != nil && *s.ParDenominator < 1 { + invalidParams.Add(request.NewErrParamMinValue("ParDenominator", 1)) + } + if s.ParNumerator != nil && *s.ParNumerator < 1 { + invalidParams.Add(request.NewErrParamMinValue("ParNumerator", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBitrate sets the Bitrate field's value. +func (s *Vp9Settings) SetBitrate(v int64) *Vp9Settings { + s.Bitrate = &v + return s +} + +// SetFramerateControl sets the FramerateControl field's value. +func (s *Vp9Settings) SetFramerateControl(v string) *Vp9Settings { + s.FramerateControl = &v + return s +} + +// SetFramerateConversionAlgorithm sets the FramerateConversionAlgorithm field's value. +func (s *Vp9Settings) SetFramerateConversionAlgorithm(v string) *Vp9Settings { + s.FramerateConversionAlgorithm = &v + return s +} + +// SetFramerateDenominator sets the FramerateDenominator field's value. +func (s *Vp9Settings) SetFramerateDenominator(v int64) *Vp9Settings { + s.FramerateDenominator = &v + return s +} + +// SetFramerateNumerator sets the FramerateNumerator field's value. +func (s *Vp9Settings) SetFramerateNumerator(v int64) *Vp9Settings { + s.FramerateNumerator = &v + return s +} + +// SetGopSize sets the GopSize field's value. +func (s *Vp9Settings) SetGopSize(v float64) *Vp9Settings { + s.GopSize = &v + return s +} + +// SetHrdBufferSize sets the HrdBufferSize field's value. +func (s *Vp9Settings) SetHrdBufferSize(v int64) *Vp9Settings { + s.HrdBufferSize = &v + return s +} + +// SetMaxBitrate sets the MaxBitrate field's value. +func (s *Vp9Settings) SetMaxBitrate(v int64) *Vp9Settings { + s.MaxBitrate = &v + return s +} + +// SetParControl sets the ParControl field's value. +func (s *Vp9Settings) SetParControl(v string) *Vp9Settings { + s.ParControl = &v + return s +} + +// SetParDenominator sets the ParDenominator field's value. +func (s *Vp9Settings) SetParDenominator(v int64) *Vp9Settings { + s.ParDenominator = &v + return s +} + +// SetParNumerator sets the ParNumerator field's value. +func (s *Vp9Settings) SetParNumerator(v int64) *Vp9Settings { + s.ParNumerator = &v + return s +} + +// SetQualityTuningLevel sets the QualityTuningLevel field's value. +func (s *Vp9Settings) SetQualityTuningLevel(v string) *Vp9Settings { + s.QualityTuningLevel = &v + return s +} + +// SetRateControlMode sets the RateControlMode field's value. +func (s *Vp9Settings) SetRateControlMode(v string) *Vp9Settings { + s.RateControlMode = &v + return s +} + +// Required when you set (Codec) under (AudioDescriptions)>(CodecSettings) to +// the value WAV. +type WavSettings struct { + _ struct{} `type:"structure"` + + // Specify Bit depth (BitDepth), in bits per sample, to choose the encoding + // quality for this audio track. + BitDepth *int64 `locationName:"bitDepth" min:"16" type:"integer"` + + // Specify the number of channels in this output audio track. Valid values are + // 1 and even numbers up to 64. For example, 1, 2, 4, 6, and so on, up to 64. + Channels *int64 `locationName:"channels" min:"1" type:"integer"` + + // The service defaults to using RIFF for WAV outputs. If your output audio + // is likely to exceed 4 GB in file size, or if you otherwise need the extended + // support of the RF64 format, set your output WAV file format to RF64. + Format *string `locationName:"format" type:"string" enum:"WavFormat"` + + // Sample rate in Hz. + SampleRate *int64 `locationName:"sampleRate" min:"8000" type:"integer"` +} + +// String returns the string representation +func (s WavSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s WavSettings) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *WavSettings) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "WavSettings"} + if s.BitDepth != nil && *s.BitDepth < 16 { + invalidParams.Add(request.NewErrParamMinValue("BitDepth", 16)) + } + if s.Channels != nil && *s.Channels < 1 { + invalidParams.Add(request.NewErrParamMinValue("Channels", 1)) + } + if s.SampleRate != nil && *s.SampleRate < 8000 { + invalidParams.Add(request.NewErrParamMinValue("SampleRate", 8000)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBitDepth sets the BitDepth field's value. +func (s *WavSettings) SetBitDepth(v int64) *WavSettings { + s.BitDepth = &v + return s +} + +// SetChannels sets the Channels field's value. +func (s *WavSettings) SetChannels(v int64) *WavSettings { + s.Channels = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *WavSettings) SetFormat(v string) *WavSettings { + s.Format = &v + return s +} + +// SetSampleRate sets the SampleRate field's value. +func (s *WavSettings) SetSampleRate(v int64) *WavSettings { + s.SampleRate = &v + return s +} + +// Choose BROADCASTER_MIXED_AD when the input contains pre-mixed main audio +// + audio description (AD) as a stereo pair. The value for AudioType will be +// set to 3, which signals to downstream systems that this stream contains "broadcaster +// mixed AD". Note that the input received by the encoder must contain pre-mixed +// audio; the encoder does not perform the mixing. When you choose BROADCASTER_MIXED_AD, +// the encoder ignores any values you provide in AudioType and FollowInputAudioType. +// Choose NORMAL when the input does not contain pre-mixed audio + audio description +// (AD). In this case, the encoder will use any values you provide for AudioType +// and FollowInputAudioType. +const ( + // AacAudioDescriptionBroadcasterMixBroadcasterMixedAd is a AacAudioDescriptionBroadcasterMix enum value + AacAudioDescriptionBroadcasterMixBroadcasterMixedAd = "BROADCASTER_MIXED_AD" + + // AacAudioDescriptionBroadcasterMixNormal is a AacAudioDescriptionBroadcasterMix enum value + AacAudioDescriptionBroadcasterMixNormal = "NORMAL" +) + +// AacAudioDescriptionBroadcasterMix_Values returns all elements of the AacAudioDescriptionBroadcasterMix enum +func AacAudioDescriptionBroadcasterMix_Values() []string { + return []string{ + AacAudioDescriptionBroadcasterMixBroadcasterMixedAd, + AacAudioDescriptionBroadcasterMixNormal, + } +} + +// AAC Profile. +const ( + // AacCodecProfileLc is a AacCodecProfile enum value + AacCodecProfileLc = "LC" + + // AacCodecProfileHev1 is a AacCodecProfile enum value + AacCodecProfileHev1 = "HEV1" + + // AacCodecProfileHev2 is a AacCodecProfile enum value + AacCodecProfileHev2 = "HEV2" +) + +// AacCodecProfile_Values returns all elements of the AacCodecProfile enum +func AacCodecProfile_Values() []string { + return []string{ + AacCodecProfileLc, + AacCodecProfileHev1, + AacCodecProfileHev2, + } +} + +// Mono (Audio Description), Mono, Stereo, or 5.1 channel layout. Valid values +// depend on rate control mode and profile. "1.0 - Audio Description (Receiver +// Mix)" setting receives a stereo description plus control track and emits +// a mono AAC encode of the description track, with control data emitted in +// the PES header as per ETSI TS 101 154 Annex E. +const ( + // AacCodingModeAdReceiverMix is a AacCodingMode enum value AacCodingModeAdReceiverMix = "AD_RECEIVER_MIX" // AacCodingModeCodingMode10 is a AacCodingMode enum value @@ -18623,6 +19465,17 @@ const ( AacCodingModeCodingMode51 = "CODING_MODE_5_1" ) +// AacCodingMode_Values returns all elements of the AacCodingMode enum +func AacCodingMode_Values() []string { + return []string{ + AacCodingModeAdReceiverMix, + AacCodingModeCodingMode10, + AacCodingModeCodingMode11, + AacCodingModeCodingMode20, + AacCodingModeCodingMode51, + } +} + // Rate Control Mode. const ( // AacRateControlModeCbr is a AacRateControlMode enum value @@ -18632,6 +19485,14 @@ const ( AacRateControlModeVbr = "VBR" ) +// AacRateControlMode_Values returns all elements of the AacRateControlMode enum +func AacRateControlMode_Values() []string { + return []string{ + AacRateControlModeCbr, + AacRateControlModeVbr, + } +} + // Enables LATM/LOAS AAC output. Note that if you use LATM/LOAS AAC in an output, // you must choose "No container" for the output container. const ( @@ -18642,6 +19503,14 @@ const ( AacRawFormatNone = "NONE" ) +// AacRawFormat_Values returns all elements of the AacRawFormat enum +func AacRawFormat_Values() []string { + return []string{ + AacRawFormatLatmLoas, + AacRawFormatNone, + } +} + // Use MPEG-2 AAC instead of MPEG-4 AAC audio for raw or MPEG-2 Transport Stream // containers. const ( @@ -18652,6 +19521,14 @@ const ( AacSpecificationMpeg4 = "MPEG4" ) +// AacSpecification_Values returns all elements of the AacSpecification enum +func AacSpecification_Values() []string { + return []string{ + AacSpecificationMpeg2, + AacSpecificationMpeg4, + } +} + // VBR Quality Level - Only used if rate_control_mode is VBR. const ( // AacVbrQualityLow is a AacVbrQuality enum value @@ -18667,6 +19544,16 @@ const ( AacVbrQualityHigh = "HIGH" ) +// AacVbrQuality_Values returns all elements of the AacVbrQuality enum +func AacVbrQuality_Values() []string { + return []string{ + AacVbrQualityLow, + AacVbrQualityMediumLow, + AacVbrQualityMediumHigh, + AacVbrQualityHigh, + } +} + // Specify the bitstream mode for the AC-3 stream that the encoder emits. For // more information about the AC3 bitstream mode, see ATSC A/52-2012 (Annex // E). @@ -18696,6 +19583,20 @@ const ( Ac3BitstreamModeVoiceOver = "VOICE_OVER" ) +// Ac3BitstreamMode_Values returns all elements of the Ac3BitstreamMode enum +func Ac3BitstreamMode_Values() []string { + return []string{ + Ac3BitstreamModeCompleteMain, + Ac3BitstreamModeCommentary, + Ac3BitstreamModeDialogue, + Ac3BitstreamModeEmergency, + Ac3BitstreamModeHearingImpaired, + Ac3BitstreamModeMusicAndEffects, + Ac3BitstreamModeVisuallyImpaired, + Ac3BitstreamModeVoiceOver, + } +} + // Dolby Digital coding mode. Determines number of channels. const ( // Ac3CodingModeCodingMode10 is a Ac3CodingMode enum value @@ -18711,6 +19612,16 @@ const ( Ac3CodingModeCodingMode32Lfe = "CODING_MODE_3_2_LFE" ) +// Ac3CodingMode_Values returns all elements of the Ac3CodingMode enum +func Ac3CodingMode_Values() []string { + return []string{ + Ac3CodingModeCodingMode10, + Ac3CodingModeCodingMode11, + Ac3CodingModeCodingMode20, + Ac3CodingModeCodingMode32Lfe, + } +} + // If set to FILM_STANDARD, adds dynamic range compression signaling to the // output bitstream as defined in the Dolby Digital specification. const ( @@ -18721,6 +19632,14 @@ const ( Ac3DynamicRangeCompressionProfileNone = "NONE" ) +// Ac3DynamicRangeCompressionProfile_Values returns all elements of the Ac3DynamicRangeCompressionProfile enum +func Ac3DynamicRangeCompressionProfile_Values() []string { + return []string{ + Ac3DynamicRangeCompressionProfileFilmStandard, + Ac3DynamicRangeCompressionProfileNone, + } +} + // Applies a 120Hz lowpass filter to the LFE channel prior to encoding. Only // valid with 3_2_LFE coding mode. const ( @@ -18731,6 +19650,14 @@ const ( Ac3LfeFilterDisabled = "DISABLED" ) +// Ac3LfeFilter_Values returns all elements of the Ac3LfeFilter enum +func Ac3LfeFilter_Values() []string { + return []string{ + Ac3LfeFilterEnabled, + Ac3LfeFilterDisabled, + } +} + // When set to FOLLOW_INPUT, encoder metadata will be sourced from the DD, DD+, // or DolbyE decoder that supplied this audio data. If audio was not supplied // from one of these streams, then the static metadata settings will be used. @@ -18742,6 +19669,14 @@ const ( Ac3MetadataControlUseConfigured = "USE_CONFIGURED" ) +// Ac3MetadataControl_Values returns all elements of the Ac3MetadataControl enum +func Ac3MetadataControl_Values() []string { + return []string{ + Ac3MetadataControlFollowInput, + Ac3MetadataControlUseConfigured, + } +} + // Specify whether the service runs your job with accelerated transcoding. Choose // DISABLED if you don't want accelerated transcoding. Choose ENABLED if you // want your job to run with accelerated transcoding and to fail if your input @@ -18760,6 +19695,15 @@ const ( AccelerationModePreferred = "PREFERRED" ) +// AccelerationMode_Values returns all elements of the AccelerationMode enum +func AccelerationMode_Values() []string { + return []string{ + AccelerationModeDisabled, + AccelerationModeEnabled, + AccelerationModePreferred, + } +} + // Describes whether the current job is running with accelerated transcoding. // For jobs that have Acceleration (AccelerationMode) set to DISABLED, AccelerationStatus // is always NOT_APPLICABLE. For jobs that have Acceleration (AccelerationMode) @@ -18785,6 +19729,16 @@ const ( AccelerationStatusNotAccelerated = "NOT_ACCELERATED" ) +// AccelerationStatus_Values returns all elements of the AccelerationStatus enum +func AccelerationStatus_Values() []string { + return []string{ + AccelerationStatusNotApplicable, + AccelerationStatusInProgress, + AccelerationStatusAccelerated, + AccelerationStatusNotAccelerated, + } +} + // This setting only applies to H.264, H.265, and MPEG2 outputs. Use Insert // AFD signaling (AfdSignaling) to specify whether the service includes AFD // values in the output video data and what those values are. * Choose None @@ -18802,6 +19756,15 @@ const ( AfdSignalingFixed = "FIXED" ) +// AfdSignaling_Values returns all elements of the AfdSignaling enum +func AfdSignaling_Values() []string { + return []string{ + AfdSignalingNone, + AfdSignalingAuto, + AfdSignalingFixed, + } +} + // Ignore this setting unless this input is a QuickTime animation with an alpha // channel. Use this setting to create separate Key and Fill outputs. In each // output, specify which part of the input MediaConvert uses. Leave this setting @@ -18816,6 +19779,14 @@ const ( AlphaBehaviorRemapToLuma = "REMAP_TO_LUMA" ) +// AlphaBehavior_Values returns all elements of the AlphaBehavior enum +func AlphaBehavior_Values() []string { + return []string{ + AlphaBehaviorDiscard, + AlphaBehaviorRemapToLuma, + } +} + // Specify whether this set of input captions appears in your outputs in both // 608 and 708 format. If you choose Upconvert (UPCONVERT), MediaConvert includes // the captions data in two ways: it passes the 608 data through using the 608 @@ -18829,6 +19800,14 @@ const ( AncillaryConvert608To708Disabled = "DISABLED" ) +// AncillaryConvert608To708_Values returns all elements of the AncillaryConvert608To708 enum +func AncillaryConvert608To708_Values() []string { + return []string{ + AncillaryConvert608To708Upconvert, + AncillaryConvert608To708Disabled, + } +} + // By default, the service terminates any unterminated captions at the end of // each input. If you want the caption to continue onto your next input, disable // this setting. @@ -18840,6 +19819,14 @@ const ( AncillaryTerminateCaptionsDisabled = "DISABLED" ) +// AncillaryTerminateCaptions_Values returns all elements of the AncillaryTerminateCaptions enum +func AncillaryTerminateCaptions_Values() []string { + return []string{ + AncillaryTerminateCaptionsEndOfInput, + AncillaryTerminateCaptionsDisabled, + } +} + // The anti-alias filter is automatically applied to all outputs. The service // no longer accepts the value DISABLED for AntiAlias. If you specify that in // your job, the service will ignore the setting. @@ -18851,6 +19838,14 @@ const ( AntiAliasEnabled = "ENABLED" ) +// AntiAlias_Values returns all elements of the AntiAlias enum +func AntiAlias_Values() []string { + return []string{ + AntiAliasDisabled, + AntiAliasEnabled, + } +} + // Type of Audio codec. const ( // AudioCodecAac is a AudioCodec enum value @@ -18877,10 +19872,33 @@ const ( // AudioCodecEac3Atmos is a AudioCodec enum value AudioCodecEac3Atmos = "EAC3_ATMOS" + // AudioCodecVorbis is a AudioCodec enum value + AudioCodecVorbis = "VORBIS" + + // AudioCodecOpus is a AudioCodec enum value + AudioCodecOpus = "OPUS" + // AudioCodecPassthrough is a AudioCodec enum value AudioCodecPassthrough = "PASSTHROUGH" ) +// AudioCodec_Values returns all elements of the AudioCodec enum +func AudioCodec_Values() []string { + return []string{ + AudioCodecAac, + AudioCodecMp2, + AudioCodecMp3, + AudioCodecWav, + AudioCodecAiff, + AudioCodecAc3, + AudioCodecEac3, + AudioCodecEac3Atmos, + AudioCodecVorbis, + AudioCodecOpus, + AudioCodecPassthrough, + } +} + // Enable this setting on one audio selector to set it as the default for the // job. The service uses this default for outputs where it can't find the specified // input audio. If you don't set a default, those outputs have no audio. @@ -18892,6 +19910,14 @@ const ( AudioDefaultSelectionNotDefault = "NOT_DEFAULT" ) +// AudioDefaultSelection_Values returns all elements of the AudioDefaultSelection enum +func AudioDefaultSelection_Values() []string { + return []string{ + AudioDefaultSelectionDefault, + AudioDefaultSelectionNotDefault, + } +} + // Specify which source for language code takes precedence for this audio track. // When you choose Follow input (FOLLOW_INPUT), the service uses the language // code from the input track if it's present. If there's no languge code on @@ -18906,6 +19932,14 @@ const ( AudioLanguageCodeControlUseConfigured = "USE_CONFIGURED" ) +// AudioLanguageCodeControl_Values returns all elements of the AudioLanguageCodeControl enum +func AudioLanguageCodeControl_Values() []string { + return []string{ + AudioLanguageCodeControlFollowInput, + AudioLanguageCodeControlUseConfigured, + } +} + // Choose one of the following audio normalization algorithms: ITU-R BS.1770-1: // Ungated loudness. A measurement of ungated average loudness for an entire // piece of content, suitable for measurement of short-form content under ATSC @@ -18930,6 +19964,16 @@ const ( AudioNormalizationAlgorithmItuBs17704 = "ITU_BS_1770_4" ) +// AudioNormalizationAlgorithm_Values returns all elements of the AudioNormalizationAlgorithm enum +func AudioNormalizationAlgorithm_Values() []string { + return []string{ + AudioNormalizationAlgorithmItuBs17701, + AudioNormalizationAlgorithmItuBs17702, + AudioNormalizationAlgorithmItuBs17703, + AudioNormalizationAlgorithmItuBs17704, + } +} + // When enabled the output audio is corrected using the chosen algorithm. If // disabled, the audio will be measured but not adjusted. const ( @@ -18940,6 +19984,14 @@ const ( AudioNormalizationAlgorithmControlMeasureOnly = "MEASURE_ONLY" ) +// AudioNormalizationAlgorithmControl_Values returns all elements of the AudioNormalizationAlgorithmControl enum +func AudioNormalizationAlgorithmControl_Values() []string { + return []string{ + AudioNormalizationAlgorithmControlCorrectAudio, + AudioNormalizationAlgorithmControlMeasureOnly, + } +} + // If set to LOG, log each output's audio track loudness to a CSV file. const ( // AudioNormalizationLoudnessLoggingLog is a AudioNormalizationLoudnessLogging enum value @@ -18949,6 +20001,14 @@ const ( AudioNormalizationLoudnessLoggingDontLog = "DONT_LOG" ) +// AudioNormalizationLoudnessLogging_Values returns all elements of the AudioNormalizationLoudnessLogging enum +func AudioNormalizationLoudnessLogging_Values() []string { + return []string{ + AudioNormalizationLoudnessLoggingLog, + AudioNormalizationLoudnessLoggingDontLog, + } +} + // If set to TRUE_PEAK, calculate and log the TruePeak for each output's audio // track loudness. const ( @@ -18959,6 +20019,14 @@ const ( AudioNormalizationPeakCalculationNone = "NONE" ) +// AudioNormalizationPeakCalculation_Values returns all elements of the AudioNormalizationPeakCalculation enum +func AudioNormalizationPeakCalculation_Values() []string { + return []string{ + AudioNormalizationPeakCalculationTruePeak, + AudioNormalizationPeakCalculationNone, + } +} + // Specifies the type of the audio selector. const ( // AudioSelectorTypePid is a AudioSelectorType enum value @@ -18971,6 +20039,15 @@ const ( AudioSelectorTypeLanguageCode = "LANGUAGE_CODE" ) +// AudioSelectorType_Values returns all elements of the AudioSelectorType enum +func AudioSelectorType_Values() []string { + return []string{ + AudioSelectorTypePid, + AudioSelectorTypeTrack, + AudioSelectorTypeLanguageCode, + } +} + // When set to FOLLOW_INPUT, if the input contains an ISO 639 audio_type, then // that value is passed through to the output. If the input contains no ISO // 639 audio_type, the value in Audio Type is included in the output. Otherwise @@ -18984,6 +20061,14 @@ const ( AudioTypeControlUseConfigured = "USE_CONFIGURED" ) +// AudioTypeControl_Values returns all elements of the AudioTypeControl enum +func AudioTypeControl_Values() []string { + return []string{ + AudioTypeControlFollowInput, + AudioTypeControlUseConfigured, + } +} + // Adaptive quantization. Allows intra-frame quantizers to vary to improve visual // quality. const ( @@ -19006,6 +20091,18 @@ const ( Av1AdaptiveQuantizationMax = "MAX" ) +// Av1AdaptiveQuantization_Values returns all elements of the Av1AdaptiveQuantization enum +func Av1AdaptiveQuantization_Values() []string { + return []string{ + Av1AdaptiveQuantizationOff, + Av1AdaptiveQuantizationLow, + Av1AdaptiveQuantizationMedium, + Av1AdaptiveQuantizationHigh, + Av1AdaptiveQuantizationHigher, + Av1AdaptiveQuantizationMax, + } +} + // If you are using the console, use the Framerate setting to specify the frame // rate for this output. If you want to keep the same frame rate as the input // video, choose Follow source. If you want to do frame rate conversion, choose @@ -19025,7 +20122,16 @@ const ( Av1FramerateControlSpecified = "SPECIFIED" ) -// When set to INTERPOLATE, produces smoother motion during frame rate conversion. +// Av1FramerateControl_Values returns all elements of the Av1FramerateControl enum +func Av1FramerateControl_Values() []string { + return []string{ + Av1FramerateControlInitializeFromSource, + Av1FramerateControlSpecified, + } +} + +// Optional. Specify how the transcoder performs framerate conversion. The default +// behavior is to use duplicate drop conversion. const ( // Av1FramerateConversionAlgorithmDuplicateDrop is a Av1FramerateConversionAlgorithm enum value Av1FramerateConversionAlgorithmDuplicateDrop = "DUPLICATE_DROP" @@ -19034,6 +20140,14 @@ const ( Av1FramerateConversionAlgorithmInterpolate = "INTERPOLATE" ) +// Av1FramerateConversionAlgorithm_Values returns all elements of the Av1FramerateConversionAlgorithm enum +func Av1FramerateConversionAlgorithm_Values() []string { + return []string{ + Av1FramerateConversionAlgorithmDuplicateDrop, + Av1FramerateConversionAlgorithmInterpolate, + } +} + // 'With AV1 outputs, for rate control mode, MediaConvert supports only quality-defined // variable bitrate (QVBR). You can''t use CBR or VBR.' const ( @@ -19041,6 +20155,13 @@ const ( Av1RateControlModeQvbr = "QVBR" ) +// Av1RateControlMode_Values returns all elements of the Av1RateControlMode enum +func Av1RateControlMode_Values() []string { + return []string{ + Av1RateControlModeQvbr, + } +} + // Adjust quantization within each frame based on spatial variation of content // complexity. const ( @@ -19051,6 +20172,14 @@ const ( Av1SpatialAdaptiveQuantizationEnabled = "ENABLED" ) +// Av1SpatialAdaptiveQuantization_Values returns all elements of the Av1SpatialAdaptiveQuantization enum +func Av1SpatialAdaptiveQuantization_Values() []string { + return []string{ + Av1SpatialAdaptiveQuantizationDisabled, + Av1SpatialAdaptiveQuantizationEnabled, + } +} + // The tag type that AWS Billing and Cost Management will use to sort your AWS // Elemental MediaConvert costs on any billing report that you set up. const ( @@ -19067,6 +20196,16 @@ const ( BillingTagsSourceJob = "JOB" ) +// BillingTagsSource_Values returns all elements of the BillingTagsSource enum +func BillingTagsSource_Values() []string { + return []string{ + BillingTagsSourceQueue, + BillingTagsSourcePreset, + BillingTagsSourceJobTemplate, + BillingTagsSourceJob, + } +} + // If no explicit x_position or y_position is provided, setting alignment to // centered will place the captions at the bottom center of the output. Similarly, // setting a left alignment will align captions to the bottom left of the output. @@ -19083,6 +20222,14 @@ const ( BurninSubtitleAlignmentLeft = "LEFT" ) +// BurninSubtitleAlignment_Values returns all elements of the BurninSubtitleAlignment enum +func BurninSubtitleAlignment_Values() []string { + return []string{ + BurninSubtitleAlignmentCentered, + BurninSubtitleAlignmentLeft, + } +} + // Specifies the color of the rectangle behind the captions.All burn-in and // DVB-Sub font settings must match. const ( @@ -19096,6 +20243,15 @@ const ( BurninSubtitleBackgroundColorWhite = "WHITE" ) +// BurninSubtitleBackgroundColor_Values returns all elements of the BurninSubtitleBackgroundColor enum +func BurninSubtitleBackgroundColor_Values() []string { + return []string{ + BurninSubtitleBackgroundColorNone, + BurninSubtitleBackgroundColorBlack, + BurninSubtitleBackgroundColorWhite, + } +} + // Specifies the color of the burned-in captions. This option is not valid for // source captions that are STL, 608/embedded or teletext. These source settings // are already pre-defined by the caption stream. All burn-in and DVB-Sub font @@ -19120,6 +20276,18 @@ const ( BurninSubtitleFontColorBlue = "BLUE" ) +// BurninSubtitleFontColor_Values returns all elements of the BurninSubtitleFontColor enum +func BurninSubtitleFontColor_Values() []string { + return []string{ + BurninSubtitleFontColorWhite, + BurninSubtitleFontColorBlack, + BurninSubtitleFontColorYellow, + BurninSubtitleFontColorRed, + BurninSubtitleFontColorGreen, + BurninSubtitleFontColorBlue, + } +} + // Specifies font outline color. This option is not valid for source captions // that are either 608/embedded or teletext. These source settings are already // pre-defined by the caption stream. All burn-in and DVB-Sub font settings @@ -19144,6 +20312,18 @@ const ( BurninSubtitleOutlineColorBlue = "BLUE" ) +// BurninSubtitleOutlineColor_Values returns all elements of the BurninSubtitleOutlineColor enum +func BurninSubtitleOutlineColor_Values() []string { + return []string{ + BurninSubtitleOutlineColorBlack, + BurninSubtitleOutlineColorWhite, + BurninSubtitleOutlineColorYellow, + BurninSubtitleOutlineColorRed, + BurninSubtitleOutlineColorGreen, + BurninSubtitleOutlineColorBlue, + } +} + // Specifies the color of the shadow cast by the captions.All burn-in and DVB-Sub // font settings must match. const ( @@ -19157,6 +20337,15 @@ const ( BurninSubtitleShadowColorWhite = "WHITE" ) +// BurninSubtitleShadowColor_Values returns all elements of the BurninSubtitleShadowColor enum +func BurninSubtitleShadowColor_Values() []string { + return []string{ + BurninSubtitleShadowColorNone, + BurninSubtitleShadowColorBlack, + BurninSubtitleShadowColorWhite, + } +} + // Only applies to jobs with input captions in Teletext or STL formats. Specify // whether the spacing between letters in your captions is set by the captions // grid or varies depending on letter width. Choose fixed grid to conform to @@ -19170,6 +20359,14 @@ const ( BurninSubtitleTeletextSpacingProportional = "PROPORTIONAL" ) +// BurninSubtitleTeletextSpacing_Values returns all elements of the BurninSubtitleTeletextSpacing enum +func BurninSubtitleTeletextSpacing_Values() []string { + return []string{ + BurninSubtitleTeletextSpacingFixedGrid, + BurninSubtitleTeletextSpacingProportional, + } +} + // Specify the format for this set of captions on this output. The default format // is embedded without SCTE-20. Other options are embedded with SCTE-20, burn-in, // DVB-sub, IMSC, SCC, SRT, teletext, TTML, and web-VTT. If you are using SCTE-20, @@ -19214,6 +20411,24 @@ const ( CaptionDestinationTypeWebvtt = "WEBVTT" ) +// CaptionDestinationType_Values returns all elements of the CaptionDestinationType enum +func CaptionDestinationType_Values() []string { + return []string{ + CaptionDestinationTypeBurnIn, + CaptionDestinationTypeDvbSub, + CaptionDestinationTypeEmbedded, + CaptionDestinationTypeEmbeddedPlusScte20, + CaptionDestinationTypeImsc, + CaptionDestinationTypeScte20PlusEmbedded, + CaptionDestinationTypeScc, + CaptionDestinationTypeSrt, + CaptionDestinationTypeSmi, + CaptionDestinationTypeTeletext, + CaptionDestinationTypeTtml, + CaptionDestinationTypeWebvtt, + } +} + // Use Source (SourceType) to identify the format of your input captions. The // service cannot auto-detect caption format. const ( @@ -19254,6 +20469,24 @@ const ( CaptionSourceTypeImsc = "IMSC" ) +// CaptionSourceType_Values returns all elements of the CaptionSourceType enum +func CaptionSourceType_Values() []string { + return []string{ + CaptionSourceTypeAncillary, + CaptionSourceTypeDvbSub, + CaptionSourceTypeEmbedded, + CaptionSourceTypeScte20, + CaptionSourceTypeScc, + CaptionSourceTypeTtml, + CaptionSourceTypeStl, + CaptionSourceTypeSrt, + CaptionSourceTypeSmi, + CaptionSourceTypeTeletext, + CaptionSourceTypeNullSource, + CaptionSourceTypeImsc, + } +} + // When set to ENABLED, sets #EXT-X-ALLOW-CACHE:no tag, which prevents client // from saving media segments for later replay. const ( @@ -19264,6 +20497,14 @@ const ( CmafClientCacheEnabled = "ENABLED" ) +// CmafClientCache_Values returns all elements of the CmafClientCache enum +func CmafClientCache_Values() []string { + return []string{ + CmafClientCacheDisabled, + CmafClientCacheEnabled, + } +} + // Specification to use (RFC-6381 or the default RFC-4281) during m3u8 playlist // generation. const ( @@ -19274,6 +20515,14 @@ const ( CmafCodecSpecificationRfc4281 = "RFC_4281" ) +// CmafCodecSpecification_Values returns all elements of the CmafCodecSpecification enum +func CmafCodecSpecification_Values() []string { + return []string{ + CmafCodecSpecificationRfc6381, + CmafCodecSpecificationRfc4281, + } +} + // Specify the encryption scheme that you want the service to use when encrypting // your CMAF segments. Choose AES-CBC subsample (SAMPLE-AES) or AES_CTR (AES-CTR). const ( @@ -19284,6 +20533,14 @@ const ( CmafEncryptionTypeAesCtr = "AES_CTR" ) +// CmafEncryptionType_Values returns all elements of the CmafEncryptionType enum +func CmafEncryptionType_Values() []string { + return []string{ + CmafEncryptionTypeSampleAes, + CmafEncryptionTypeAesCtr, + } +} + // When you use DRM with CMAF outputs, choose whether the service writes the // 128-bit encryption initialization vector in the HLS and DASH manifests. const ( @@ -19294,6 +20551,14 @@ const ( CmafInitializationVectorInManifestExclude = "EXCLUDE" ) +// CmafInitializationVectorInManifest_Values returns all elements of the CmafInitializationVectorInManifest enum +func CmafInitializationVectorInManifest_Values() []string { + return []string{ + CmafInitializationVectorInManifestInclude, + CmafInitializationVectorInManifestExclude, + } +} + // Specify whether your DRM encryption key is static or from a key provider // that follows the SPEKE standard. For more information about SPEKE, see https://docs.aws.amazon.com/speke/latest/documentation/what-is-speke.html. const ( @@ -19304,6 +20569,14 @@ const ( CmafKeyProviderTypeStaticKey = "STATIC_KEY" ) +// CmafKeyProviderType_Values returns all elements of the CmafKeyProviderType enum +func CmafKeyProviderType_Values() []string { + return []string{ + CmafKeyProviderTypeSpeke, + CmafKeyProviderTypeStaticKey, + } +} + // When set to GZIP, compresses HLS playlist. const ( // CmafManifestCompressionGzip is a CmafManifestCompression enum value @@ -19313,6 +20586,14 @@ const ( CmafManifestCompressionNone = "NONE" ) +// CmafManifestCompression_Values returns all elements of the CmafManifestCompression enum +func CmafManifestCompression_Values() []string { + return []string{ + CmafManifestCompressionGzip, + CmafManifestCompressionNone, + } +} + // Indicates whether the output manifest should use floating point values for // segment duration. const ( @@ -19323,6 +20604,14 @@ const ( CmafManifestDurationFormatInteger = "INTEGER" ) +// CmafManifestDurationFormat_Values returns all elements of the CmafManifestDurationFormat enum +func CmafManifestDurationFormat_Values() []string { + return []string{ + CmafManifestDurationFormatFloatingPoint, + CmafManifestDurationFormatInteger, + } +} + // Specify whether your DASH profile is on-demand or main. When you choose Main // profile (MAIN_PROFILE), the service signals urn:mpeg:dash:profile:isoff-main:2011 // in your .mpd DASH manifest. When you choose On-demand (ON_DEMAND_PROFILE), @@ -19337,6 +20626,14 @@ const ( CmafMpdProfileOnDemandProfile = "ON_DEMAND_PROFILE" ) +// CmafMpdProfile_Values returns all elements of the CmafMpdProfile enum +func CmafMpdProfile_Values() []string { + return []string{ + CmafMpdProfileMainProfile, + CmafMpdProfileOnDemandProfile, + } +} + // When set to SINGLE_FILE, a single output file is generated, which is internally // segmented using the Fragment Length and Segment Length. When set to SEGMENTED_FILES, // separate segment files will be created. @@ -19348,6 +20645,14 @@ const ( CmafSegmentControlSegmentedFiles = "SEGMENTED_FILES" ) +// CmafSegmentControl_Values returns all elements of the CmafSegmentControl enum +func CmafSegmentControl_Values() []string { + return []string{ + CmafSegmentControlSingleFile, + CmafSegmentControlSegmentedFiles, + } +} + // Include or exclude RESOLUTION attribute for video in EXT-X-STREAM-INF tag // of variant manifest. const ( @@ -19358,6 +20663,14 @@ const ( CmafStreamInfResolutionExclude = "EXCLUDE" ) +// CmafStreamInfResolution_Values returns all elements of the CmafStreamInfResolution enum +func CmafStreamInfResolution_Values() []string { + return []string{ + CmafStreamInfResolutionInclude, + CmafStreamInfResolutionExclude, + } +} + // When set to ENABLED, a DASH MPD manifest will be generated for this output. const ( // CmafWriteDASHManifestDisabled is a CmafWriteDASHManifest enum value @@ -19367,6 +20680,14 @@ const ( CmafWriteDASHManifestEnabled = "ENABLED" ) +// CmafWriteDASHManifest_Values returns all elements of the CmafWriteDASHManifest enum +func CmafWriteDASHManifest_Values() []string { + return []string{ + CmafWriteDASHManifestDisabled, + CmafWriteDASHManifestEnabled, + } +} + // When set to ENABLED, an Apple HLS manifest will be generated for this output. const ( // CmafWriteHLSManifestDisabled is a CmafWriteHLSManifest enum value @@ -19376,6 +20697,14 @@ const ( CmafWriteHLSManifestEnabled = "ENABLED" ) +// CmafWriteHLSManifest_Values returns all elements of the CmafWriteHLSManifest enum +func CmafWriteHLSManifest_Values() []string { + return []string{ + CmafWriteHLSManifestDisabled, + CmafWriteHLSManifestEnabled, + } +} + // When you enable Precise segment duration in DASH manifests (writeSegmentTimelineInRepresentation), // your DASH manifest shows precise segment durations. The segment duration // information appears inside the SegmentTimeline element, inside SegmentTemplate @@ -19390,6 +20719,14 @@ const ( CmafWriteSegmentTimelineInRepresentationDisabled = "DISABLED" ) +// CmafWriteSegmentTimelineInRepresentation_Values returns all elements of the CmafWriteSegmentTimelineInRepresentation enum +func CmafWriteSegmentTimelineInRepresentation_Values() []string { + return []string{ + CmafWriteSegmentTimelineInRepresentationEnabled, + CmafWriteSegmentTimelineInRepresentationDisabled, + } +} + // Use this setting only when you specify SCTE-35 markers from ESAM. Choose // INSERT to put SCTE-35 markers in this output at the insertion points that // you specify in an ESAM XML document. Provide the document in the setting @@ -19402,6 +20739,14 @@ const ( CmfcScte35EsamNone = "NONE" ) +// CmfcScte35Esam_Values returns all elements of the CmfcScte35Esam enum +func CmfcScte35Esam_Values() []string { + return []string{ + CmfcScte35EsamInsert, + CmfcScte35EsamNone, + } +} + // Ignore this setting unless you have SCTE-35 markers in your input video file. // Choose Passthrough (PASSTHROUGH) if you want SCTE-35 markers that appear // in your input to also appear in this output. Choose None (NONE) if you don't @@ -19414,6 +20759,14 @@ const ( CmfcScte35SourceNone = "NONE" ) +// CmfcScte35Source_Values returns all elements of the CmfcScte35Source enum +func CmfcScte35Source_Values() []string { + return []string{ + CmfcScte35SourcePassthrough, + CmfcScte35SourceNone, + } +} + // Choose Insert (INSERT) for this setting to include color metadata in this // output. Choose Ignore (IGNORE) to exclude color metadata from this output. // If you don't specify a value, the service sets this to Insert by default. @@ -19425,6 +20778,14 @@ const ( ColorMetadataInsert = "INSERT" ) +// ColorMetadata_Values returns all elements of the ColorMetadata enum +func ColorMetadata_Values() []string { + return []string{ + ColorMetadataIgnore, + ColorMetadataInsert, + } +} + // If your input video has accurate color space metadata, or if you don't know // about color space, leave this set to the default value Follow (FOLLOW). The // service will automatically detect your input color space. If your input video @@ -19451,6 +20812,17 @@ const ( ColorSpaceHlg2020 = "HLG_2020" ) +// ColorSpace_Values returns all elements of the ColorSpace enum +func ColorSpace_Values() []string { + return []string{ + ColorSpaceFollow, + ColorSpaceRec601, + ColorSpaceRec709, + ColorSpaceHdr10, + ColorSpaceHlg2020, + } +} + // Specify the color space you want for this output. The service supports conversion // between HDR formats, between SDR formats, from SDR to HDR, and from HDR to // SDR. SDR to HDR conversion doesn't upgrade the dynamic range. The converted @@ -19474,6 +20846,17 @@ const ( ColorSpaceConversionForceHlg2020 = "FORCE_HLG_2020" ) +// ColorSpaceConversion_Values returns all elements of the ColorSpaceConversion enum +func ColorSpaceConversion_Values() []string { + return []string{ + ColorSpaceConversionNone, + ColorSpaceConversionForce601, + ColorSpaceConversionForce709, + ColorSpaceConversionForceHdr10, + ColorSpaceConversionForceHlg2020, + } +} + // There are two sources for color metadata, the input file and the job input // settings Color space (ColorSpace) and HDR master display information settings(Hdr10Metadata). // The Color space usage setting determines which takes precedence. Choose Force @@ -19490,12 +20873,27 @@ const ( ColorSpaceUsageFallback = "FALLBACK" ) +// ColorSpaceUsage_Values returns all elements of the ColorSpaceUsage enum +func ColorSpaceUsage_Values() []string { + return []string{ + ColorSpaceUsageForce, + ColorSpaceUsageFallback, + } +} + // The length of the term of your reserved queue pricing plan commitment. const ( // CommitmentOneYear is a Commitment enum value CommitmentOneYear = "ONE_YEAR" ) +// Commitment_Values returns all elements of the Commitment enum +func Commitment_Values() []string { + return []string{ + CommitmentOneYear, + } +} + // Container for this output. Some containers require a container settings object. // If not specified, the default object will be created. const ( @@ -19526,10 +20924,30 @@ const ( // ContainerTypeMxf is a ContainerType enum value ContainerTypeMxf = "MXF" + // ContainerTypeWebm is a ContainerType enum value + ContainerTypeWebm = "WEBM" + // ContainerTypeRaw is a ContainerType enum value ContainerTypeRaw = "RAW" ) +// ContainerType_Values returns all elements of the ContainerType enum +func ContainerType_Values() []string { + return []string{ + ContainerTypeF4v, + ContainerTypeIsmv, + ContainerTypeM2ts, + ContainerTypeM3u8, + ContainerTypeCmfc, + ContainerTypeMov, + ContainerTypeMp4, + ContainerTypeMpd, + ContainerTypeMxf, + ContainerTypeWebm, + ContainerTypeRaw, + } +} + // Supports HbbTV specification as indicated const ( // DashIsoHbbtvComplianceHbbtv15 is a DashIsoHbbtvCompliance enum value @@ -19539,6 +20957,14 @@ const ( DashIsoHbbtvComplianceNone = "NONE" ) +// DashIsoHbbtvCompliance_Values returns all elements of the DashIsoHbbtvCompliance enum +func DashIsoHbbtvCompliance_Values() []string { + return []string{ + DashIsoHbbtvComplianceHbbtv15, + DashIsoHbbtvComplianceNone, + } +} + // Specify whether your DASH profile is on-demand or main. When you choose Main // profile (MAIN_PROFILE), the service signals urn:mpeg:dash:profile:isoff-main:2011 // in your .mpd DASH manifest. When you choose On-demand (ON_DEMAND_PROFILE), @@ -19553,6 +20979,14 @@ const ( DashIsoMpdProfileOnDemandProfile = "ON_DEMAND_PROFILE" ) +// DashIsoMpdProfile_Values returns all elements of the DashIsoMpdProfile enum +func DashIsoMpdProfile_Values() []string { + return []string{ + DashIsoMpdProfileMainProfile, + DashIsoMpdProfileOnDemandProfile, + } +} + // This setting can improve the compatibility of your output with video players // on obsolete devices. It applies only to DASH H.264 outputs with DRM encryption. // Choose Unencrypted SEI (UNENCRYPTED_SEI) only to correct problems with playback @@ -19567,6 +21001,14 @@ const ( DashIsoPlaybackDeviceCompatibilityUnencryptedSei = "UNENCRYPTED_SEI" ) +// DashIsoPlaybackDeviceCompatibility_Values returns all elements of the DashIsoPlaybackDeviceCompatibility enum +func DashIsoPlaybackDeviceCompatibility_Values() []string { + return []string{ + DashIsoPlaybackDeviceCompatibilityCencV1, + DashIsoPlaybackDeviceCompatibilityUnencryptedSei, + } +} + // When set to SINGLE_FILE, a single output file is generated, which is internally // segmented using the Fragment Length and Segment Length. When set to SEGMENTED_FILES, // separate segment files will be created. @@ -19578,6 +21020,14 @@ const ( DashIsoSegmentControlSegmentedFiles = "SEGMENTED_FILES" ) +// DashIsoSegmentControl_Values returns all elements of the DashIsoSegmentControl enum +func DashIsoSegmentControl_Values() []string { + return []string{ + DashIsoSegmentControlSingleFile, + DashIsoSegmentControlSegmentedFiles, + } +} + // When you enable Precise segment duration in manifests (writeSegmentTimelineInRepresentation), // your DASH manifest shows precise segment durations. The segment duration // information appears inside the SegmentTimeline element, inside SegmentTemplate @@ -19592,6 +21042,14 @@ const ( DashIsoWriteSegmentTimelineInRepresentationDisabled = "DISABLED" ) +// DashIsoWriteSegmentTimelineInRepresentation_Values returns all elements of the DashIsoWriteSegmentTimelineInRepresentation enum +func DashIsoWriteSegmentTimelineInRepresentation_Values() []string { + return []string{ + DashIsoWriteSegmentTimelineInRepresentationEnabled, + DashIsoWriteSegmentTimelineInRepresentationDisabled, + } +} + // Specify the encryption mode that you used to encrypt your input files. const ( // DecryptionModeAesCtr is a DecryptionMode enum value @@ -19604,6 +21062,15 @@ const ( DecryptionModeAesGcm = "AES_GCM" ) +// DecryptionMode_Values returns all elements of the DecryptionMode enum +func DecryptionMode_Values() []string { + return []string{ + DecryptionModeAesCtr, + DecryptionModeAesCbc, + DecryptionModeAesGcm, + } +} + // Only applies when you set Deinterlacer (DeinterlaceMode) to Deinterlace (DEINTERLACE) // or Adaptive (ADAPTIVE). Motion adaptive interpolate (INTERPOLATE) produces // sharper pictures, while blend (BLEND) produces smoother motion. Use (INTERPOLATE_TICKER) @@ -19623,6 +21090,16 @@ const ( DeinterlaceAlgorithmBlendTicker = "BLEND_TICKER" ) +// DeinterlaceAlgorithm_Values returns all elements of the DeinterlaceAlgorithm enum +func DeinterlaceAlgorithm_Values() []string { + return []string{ + DeinterlaceAlgorithmInterpolate, + DeinterlaceAlgorithmInterpolateTicker, + DeinterlaceAlgorithmBlend, + DeinterlaceAlgorithmBlendTicker, + } +} + // - When set to NORMAL (default), the deinterlacer does not convert frames // that are tagged in metadata as progressive. It will only convert those that // are tagged as some other type. - When set to FORCE_ALL_FRAMES, the deinterlacer @@ -19639,6 +21116,14 @@ const ( DeinterlacerControlNormal = "NORMAL" ) +// DeinterlacerControl_Values returns all elements of the DeinterlacerControl enum +func DeinterlacerControl_Values() []string { + return []string{ + DeinterlacerControlForceAllFrames, + DeinterlacerControlNormal, + } +} + // Use Deinterlacer (DeinterlaceMode) to choose how the service will do deinterlacing. // Default is Deinterlace. - Deinterlace converts interlaced to progressive. // - Inverse telecine converts Hard Telecine 29.97i to progressive 23.976p. @@ -19654,6 +21139,15 @@ const ( DeinterlacerModeAdaptive = "ADAPTIVE" ) +// DeinterlacerMode_Values returns all elements of the DeinterlacerMode enum +func DeinterlacerMode_Values() []string { + return []string{ + DeinterlacerModeDeinterlace, + DeinterlacerModeInverseTelecine, + DeinterlacerModeAdaptive, + } +} + // Optional field, defaults to DEFAULT. Specify DEFAULT for this operation to // return your endpoints if any exist, or to create an endpoint for you and // return it if one doesn't already exist. Specify GET_ONLY to return your endpoints @@ -19666,6 +21160,14 @@ const ( DescribeEndpointsModeGetOnly = "GET_ONLY" ) +// DescribeEndpointsMode_Values returns all elements of the DescribeEndpointsMode enum +func DescribeEndpointsMode_Values() []string { + return []string{ + DescribeEndpointsModeDefault, + DescribeEndpointsModeGetOnly, + } +} + // Use Dolby Vision Mode to choose how the service will handle Dolby Vision // MaxCLL and MaxFALL properies. const ( @@ -19679,6 +21181,15 @@ const ( DolbyVisionLevel6ModeSpecify = "SPECIFY" ) +// DolbyVisionLevel6Mode_Values returns all elements of the DolbyVisionLevel6Mode enum +func DolbyVisionLevel6Mode_Values() []string { + return []string{ + DolbyVisionLevel6ModePassthrough, + DolbyVisionLevel6ModeRecalculate, + DolbyVisionLevel6ModeSpecify, + } +} + // In the current MediaConvert implementation, the Dolby Vision profile is always // 5 (PROFILE_5). Therefore, all of your inputs must contain Dolby Vision frame // interleaved data. @@ -19687,6 +21198,13 @@ const ( DolbyVisionProfileProfile5 = "PROFILE_5" ) +// DolbyVisionProfile_Values returns all elements of the DolbyVisionProfile enum +func DolbyVisionProfile_Values() []string { + return []string{ + DolbyVisionProfileProfile5, + } +} + // Applies only to 29.97 fps outputs. When this feature is enabled, the service // will use drop-frame timecode on outputs. If it is not possible to use drop-frame // timecode, the system will fall back to non-drop-frame. This setting is enabled @@ -19699,6 +21217,14 @@ const ( DropFrameTimecodeEnabled = "ENABLED" ) +// DropFrameTimecode_Values returns all elements of the DropFrameTimecode enum +func DropFrameTimecode_Values() []string { + return []string{ + DropFrameTimecodeDisabled, + DropFrameTimecodeEnabled, + } +} + // If no explicit x_position or y_position is provided, setting alignment to // centered will place the captions at the bottom center of the output. Similarly, // setting a left alignment will align captions to the bottom left of the output. @@ -19715,6 +21241,14 @@ const ( DvbSubtitleAlignmentLeft = "LEFT" ) +// DvbSubtitleAlignment_Values returns all elements of the DvbSubtitleAlignment enum +func DvbSubtitleAlignment_Values() []string { + return []string{ + DvbSubtitleAlignmentCentered, + DvbSubtitleAlignmentLeft, + } +} + // Specifies the color of the rectangle behind the captions.All burn-in and // DVB-Sub font settings must match. const ( @@ -19728,6 +21262,15 @@ const ( DvbSubtitleBackgroundColorWhite = "WHITE" ) +// DvbSubtitleBackgroundColor_Values returns all elements of the DvbSubtitleBackgroundColor enum +func DvbSubtitleBackgroundColor_Values() []string { + return []string{ + DvbSubtitleBackgroundColorNone, + DvbSubtitleBackgroundColorBlack, + DvbSubtitleBackgroundColorWhite, + } +} + // Specifies the color of the burned-in captions. This option is not valid for // source captions that are STL, 608/embedded or teletext. These source settings // are already pre-defined by the caption stream. All burn-in and DVB-Sub font @@ -19752,6 +21295,18 @@ const ( DvbSubtitleFontColorBlue = "BLUE" ) +// DvbSubtitleFontColor_Values returns all elements of the DvbSubtitleFontColor enum +func DvbSubtitleFontColor_Values() []string { + return []string{ + DvbSubtitleFontColorWhite, + DvbSubtitleFontColorBlack, + DvbSubtitleFontColorYellow, + DvbSubtitleFontColorRed, + DvbSubtitleFontColorGreen, + DvbSubtitleFontColorBlue, + } +} + // Specifies font outline color. This option is not valid for source captions // that are either 608/embedded or teletext. These source settings are already // pre-defined by the caption stream. All burn-in and DVB-Sub font settings @@ -19776,6 +21331,18 @@ const ( DvbSubtitleOutlineColorBlue = "BLUE" ) +// DvbSubtitleOutlineColor_Values returns all elements of the DvbSubtitleOutlineColor enum +func DvbSubtitleOutlineColor_Values() []string { + return []string{ + DvbSubtitleOutlineColorBlack, + DvbSubtitleOutlineColorWhite, + DvbSubtitleOutlineColorYellow, + DvbSubtitleOutlineColorRed, + DvbSubtitleOutlineColorGreen, + DvbSubtitleOutlineColorBlue, + } +} + // Specifies the color of the shadow cast by the captions.All burn-in and DVB-Sub // font settings must match. const ( @@ -19789,6 +21356,15 @@ const ( DvbSubtitleShadowColorWhite = "WHITE" ) +// DvbSubtitleShadowColor_Values returns all elements of the DvbSubtitleShadowColor enum +func DvbSubtitleShadowColor_Values() []string { + return []string{ + DvbSubtitleShadowColorNone, + DvbSubtitleShadowColorBlack, + DvbSubtitleShadowColorWhite, + } +} + // Only applies to jobs with input captions in Teletext or STL formats. Specify // whether the spacing between letters in your captions is set by the captions // grid or varies depending on letter width. Choose fixed grid to conform to @@ -19802,6 +21378,14 @@ const ( DvbSubtitleTeletextSpacingProportional = "PROPORTIONAL" ) +// DvbSubtitleTeletextSpacing_Values returns all elements of the DvbSubtitleTeletextSpacing enum +func DvbSubtitleTeletextSpacing_Values() []string { + return []string{ + DvbSubtitleTeletextSpacingFixedGrid, + DvbSubtitleTeletextSpacingProportional, + } +} + // Specify whether your DVB subtitles are standard or for hearing impaired. // Choose hearing impaired if your subtitles include audio descriptions and // dialogue. Choose standard if your subtitles include only dialogue. @@ -19813,6 +21397,14 @@ const ( DvbSubtitlingTypeStandard = "STANDARD" ) +// DvbSubtitlingType_Values returns all elements of the DvbSubtitlingType enum +func DvbSubtitlingType_Values() []string { + return []string{ + DvbSubtitlingTypeHearingImpaired, + DvbSubtitlingTypeStandard, + } +} + // Specify the bitstream mode for the E-AC-3 stream that the encoder emits. // For more information about the EAC3 bitstream mode, see ATSC A/52-2012 (Annex // E). @@ -19821,12 +21413,26 @@ const ( Eac3AtmosBitstreamModeCompleteMain = "COMPLETE_MAIN" ) +// Eac3AtmosBitstreamMode_Values returns all elements of the Eac3AtmosBitstreamMode enum +func Eac3AtmosBitstreamMode_Values() []string { + return []string{ + Eac3AtmosBitstreamModeCompleteMain, + } +} + // The coding mode for Dolby Digital Plus JOC (Atmos) is always 9.1.6 (CODING_MODE_9_1_6). const ( // Eac3AtmosCodingModeCodingMode916 is a Eac3AtmosCodingMode enum value Eac3AtmosCodingModeCodingMode916 = "CODING_MODE_9_1_6" ) +// Eac3AtmosCodingMode_Values returns all elements of the Eac3AtmosCodingMode enum +func Eac3AtmosCodingMode_Values() []string { + return []string{ + Eac3AtmosCodingModeCodingMode916, + } +} + // Enable Dolby Dialogue Intelligence to adjust loudness based on dialogue analysis. const ( // Eac3AtmosDialogueIntelligenceEnabled is a Eac3AtmosDialogueIntelligence enum value @@ -19836,6 +21442,14 @@ const ( Eac3AtmosDialogueIntelligenceDisabled = "DISABLED" ) +// Eac3AtmosDialogueIntelligence_Values returns all elements of the Eac3AtmosDialogueIntelligence enum +func Eac3AtmosDialogueIntelligence_Values() []string { + return []string{ + Eac3AtmosDialogueIntelligenceEnabled, + Eac3AtmosDialogueIntelligenceDisabled, + } +} + // Specify the absolute peak level for a signal with dynamic range compression. const ( // Eac3AtmosDynamicRangeCompressionLineNone is a Eac3AtmosDynamicRangeCompressionLine enum value @@ -19857,6 +21471,18 @@ const ( Eac3AtmosDynamicRangeCompressionLineSpeech = "SPEECH" ) +// Eac3AtmosDynamicRangeCompressionLine_Values returns all elements of the Eac3AtmosDynamicRangeCompressionLine enum +func Eac3AtmosDynamicRangeCompressionLine_Values() []string { + return []string{ + Eac3AtmosDynamicRangeCompressionLineNone, + Eac3AtmosDynamicRangeCompressionLineFilmStandard, + Eac3AtmosDynamicRangeCompressionLineFilmLight, + Eac3AtmosDynamicRangeCompressionLineMusicStandard, + Eac3AtmosDynamicRangeCompressionLineMusicLight, + Eac3AtmosDynamicRangeCompressionLineSpeech, + } +} + // Specify how the service limits the audio dynamic range when compressing the // audio. const ( @@ -19879,6 +21505,18 @@ const ( Eac3AtmosDynamicRangeCompressionRfSpeech = "SPEECH" ) +// Eac3AtmosDynamicRangeCompressionRf_Values returns all elements of the Eac3AtmosDynamicRangeCompressionRf enum +func Eac3AtmosDynamicRangeCompressionRf_Values() []string { + return []string{ + Eac3AtmosDynamicRangeCompressionRfNone, + Eac3AtmosDynamicRangeCompressionRfFilmStandard, + Eac3AtmosDynamicRangeCompressionRfFilmLight, + Eac3AtmosDynamicRangeCompressionRfMusicStandard, + Eac3AtmosDynamicRangeCompressionRfMusicLight, + Eac3AtmosDynamicRangeCompressionRfSpeech, + } +} + // Choose how the service meters the loudness of your audio. const ( // Eac3AtmosMeteringModeLeqA is a Eac3AtmosMeteringMode enum value @@ -19897,6 +21535,17 @@ const ( Eac3AtmosMeteringModeItuBs17704 = "ITU_BS_1770_4" ) +// Eac3AtmosMeteringMode_Values returns all elements of the Eac3AtmosMeteringMode enum +func Eac3AtmosMeteringMode_Values() []string { + return []string{ + Eac3AtmosMeteringModeLeqA, + Eac3AtmosMeteringModeItuBs17701, + Eac3AtmosMeteringModeItuBs17702, + Eac3AtmosMeteringModeItuBs17703, + Eac3AtmosMeteringModeItuBs17704, + } +} + // Choose how the service does stereo downmixing. const ( // Eac3AtmosStereoDownmixNotIndicated is a Eac3AtmosStereoDownmix enum value @@ -19912,6 +21561,16 @@ const ( Eac3AtmosStereoDownmixDpl2 = "DPL2" ) +// Eac3AtmosStereoDownmix_Values returns all elements of the Eac3AtmosStereoDownmix enum +func Eac3AtmosStereoDownmix_Values() []string { + return []string{ + Eac3AtmosStereoDownmixNotIndicated, + Eac3AtmosStereoDownmixStereo, + Eac3AtmosStereoDownmixSurround, + Eac3AtmosStereoDownmixDpl2, + } +} + // Specify whether your input audio has an additional center rear surround channel // matrix encoded into your left and right surround channels. const ( @@ -19925,6 +21584,15 @@ const ( Eac3AtmosSurroundExModeDisabled = "DISABLED" ) +// Eac3AtmosSurroundExMode_Values returns all elements of the Eac3AtmosSurroundExMode enum +func Eac3AtmosSurroundExMode_Values() []string { + return []string{ + Eac3AtmosSurroundExModeNotIndicated, + Eac3AtmosSurroundExModeEnabled, + Eac3AtmosSurroundExModeDisabled, + } +} + // If set to ATTENUATE_3_DB, applies a 3 dB attenuation to the surround channels. // Only used for 3/2 coding mode. const ( @@ -19935,6 +21603,14 @@ const ( Eac3AttenuationControlNone = "NONE" ) +// Eac3AttenuationControl_Values returns all elements of the Eac3AttenuationControl enum +func Eac3AttenuationControl_Values() []string { + return []string{ + Eac3AttenuationControlAttenuate3Db, + Eac3AttenuationControlNone, + } +} + // Specify the bitstream mode for the E-AC-3 stream that the encoder emits. // For more information about the EAC3 bitstream mode, see ATSC A/52-2012 (Annex // E). @@ -19955,6 +21631,17 @@ const ( Eac3BitstreamModeVisuallyImpaired = "VISUALLY_IMPAIRED" ) +// Eac3BitstreamMode_Values returns all elements of the Eac3BitstreamMode enum +func Eac3BitstreamMode_Values() []string { + return []string{ + Eac3BitstreamModeCompleteMain, + Eac3BitstreamModeCommentary, + Eac3BitstreamModeEmergency, + Eac3BitstreamModeHearingImpaired, + Eac3BitstreamModeVisuallyImpaired, + } +} + // Dolby Digital Plus coding mode. Determines number of channels. const ( // Eac3CodingModeCodingMode10 is a Eac3CodingMode enum value @@ -19967,6 +21654,15 @@ const ( Eac3CodingModeCodingMode32 = "CODING_MODE_3_2" ) +// Eac3CodingMode_Values returns all elements of the Eac3CodingMode enum +func Eac3CodingMode_Values() []string { + return []string{ + Eac3CodingModeCodingMode10, + Eac3CodingModeCodingMode20, + Eac3CodingModeCodingMode32, + } +} + // Activates a DC highpass filter for all input channels. const ( // Eac3DcFilterEnabled is a Eac3DcFilter enum value @@ -19976,6 +21672,14 @@ const ( Eac3DcFilterDisabled = "DISABLED" ) +// Eac3DcFilter_Values returns all elements of the Eac3DcFilter enum +func Eac3DcFilter_Values() []string { + return []string{ + Eac3DcFilterEnabled, + Eac3DcFilterDisabled, + } +} + // Specify the absolute peak level for a signal with dynamic range compression. const ( // Eac3DynamicRangeCompressionLineNone is a Eac3DynamicRangeCompressionLine enum value @@ -19997,6 +21701,18 @@ const ( Eac3DynamicRangeCompressionLineSpeech = "SPEECH" ) +// Eac3DynamicRangeCompressionLine_Values returns all elements of the Eac3DynamicRangeCompressionLine enum +func Eac3DynamicRangeCompressionLine_Values() []string { + return []string{ + Eac3DynamicRangeCompressionLineNone, + Eac3DynamicRangeCompressionLineFilmStandard, + Eac3DynamicRangeCompressionLineFilmLight, + Eac3DynamicRangeCompressionLineMusicStandard, + Eac3DynamicRangeCompressionLineMusicLight, + Eac3DynamicRangeCompressionLineSpeech, + } +} + // Specify how the service limits the audio dynamic range when compressing the // audio. const ( @@ -20019,6 +21735,18 @@ const ( Eac3DynamicRangeCompressionRfSpeech = "SPEECH" ) +// Eac3DynamicRangeCompressionRf_Values returns all elements of the Eac3DynamicRangeCompressionRf enum +func Eac3DynamicRangeCompressionRf_Values() []string { + return []string{ + Eac3DynamicRangeCompressionRfNone, + Eac3DynamicRangeCompressionRfFilmStandard, + Eac3DynamicRangeCompressionRfFilmLight, + Eac3DynamicRangeCompressionRfMusicStandard, + Eac3DynamicRangeCompressionRfMusicLight, + Eac3DynamicRangeCompressionRfSpeech, + } +} + // When encoding 3/2 audio, controls whether the LFE channel is enabled const ( // Eac3LfeControlLfe is a Eac3LfeControl enum value @@ -20028,6 +21756,14 @@ const ( Eac3LfeControlNoLfe = "NO_LFE" ) +// Eac3LfeControl_Values returns all elements of the Eac3LfeControl enum +func Eac3LfeControl_Values() []string { + return []string{ + Eac3LfeControlLfe, + Eac3LfeControlNoLfe, + } +} + // Applies a 120Hz lowpass filter to the LFE channel prior to encoding. Only // valid with 3_2_LFE coding mode. const ( @@ -20038,6 +21774,14 @@ const ( Eac3LfeFilterDisabled = "DISABLED" ) +// Eac3LfeFilter_Values returns all elements of the Eac3LfeFilter enum +func Eac3LfeFilter_Values() []string { + return []string{ + Eac3LfeFilterEnabled, + Eac3LfeFilterDisabled, + } +} + // When set to FOLLOW_INPUT, encoder metadata will be sourced from the DD, DD+, // or DolbyE decoder that supplied this audio data. If audio was not supplied // from one of these streams, then the static metadata settings will be used. @@ -20049,6 +21793,14 @@ const ( Eac3MetadataControlUseConfigured = "USE_CONFIGURED" ) +// Eac3MetadataControl_Values returns all elements of the Eac3MetadataControl enum +func Eac3MetadataControl_Values() []string { + return []string{ + Eac3MetadataControlFollowInput, + Eac3MetadataControlUseConfigured, + } +} + // When set to WHEN_POSSIBLE, input DD+ audio will be passed through if it is // present on the input. this detection is dynamic over the life of the transcode. // Inputs that alternate between DD+ and non-DD+ content will have a consistent @@ -20061,6 +21813,14 @@ const ( Eac3PassthroughControlNoPassthrough = "NO_PASSTHROUGH" ) +// Eac3PassthroughControl_Values returns all elements of the Eac3PassthroughControl enum +func Eac3PassthroughControl_Values() []string { + return []string{ + Eac3PassthroughControlWhenPossible, + Eac3PassthroughControlNoPassthrough, + } +} + // Controls the amount of phase-shift applied to the surround channels. Only // used for 3/2 coding mode. const ( @@ -20071,6 +21831,14 @@ const ( Eac3PhaseControlNoShift = "NO_SHIFT" ) +// Eac3PhaseControl_Values returns all elements of the Eac3PhaseControl enum +func Eac3PhaseControl_Values() []string { + return []string{ + Eac3PhaseControlShift90Degrees, + Eac3PhaseControlNoShift, + } +} + // Choose how the service does stereo downmixing. This setting only applies // if you keep the default value of 3/2 - L, R, C, Ls, Rs (CODING_MODE_3_2) // for the setting Coding mode (Eac3CodingMode). If you choose a different value @@ -20089,6 +21857,16 @@ const ( Eac3StereoDownmixDpl2 = "DPL2" ) +// Eac3StereoDownmix_Values returns all elements of the Eac3StereoDownmix enum +func Eac3StereoDownmix_Values() []string { + return []string{ + Eac3StereoDownmixNotIndicated, + Eac3StereoDownmixLoRo, + Eac3StereoDownmixLtRt, + Eac3StereoDownmixDpl2, + } +} + // When encoding 3/2 audio, sets whether an extra center back surround channel // is matrix encoded into the left and right surround channels. const ( @@ -20102,6 +21880,15 @@ const ( Eac3SurroundExModeDisabled = "DISABLED" ) +// Eac3SurroundExMode_Values returns all elements of the Eac3SurroundExMode enum +func Eac3SurroundExMode_Values() []string { + return []string{ + Eac3SurroundExModeNotIndicated, + Eac3SurroundExModeEnabled, + Eac3SurroundExModeDisabled, + } +} + // When encoding 2/0 audio, sets whether Dolby Surround is matrix encoded into // the two channels. const ( @@ -20115,6 +21902,15 @@ const ( Eac3SurroundModeDisabled = "DISABLED" ) +// Eac3SurroundMode_Values returns all elements of the Eac3SurroundMode enum +func Eac3SurroundMode_Values() []string { + return []string{ + Eac3SurroundModeNotIndicated, + Eac3SurroundModeEnabled, + Eac3SurroundModeDisabled, + } +} + // Specify whether this set of input captions appears in your outputs in both // 608 and 708 format. If you choose Upconvert (UPCONVERT), MediaConvert includes // the captions data in two ways: it passes the 608 data through using the 608 @@ -20128,6 +21924,14 @@ const ( EmbeddedConvert608To708Disabled = "DISABLED" ) +// EmbeddedConvert608To708_Values returns all elements of the EmbeddedConvert608To708 enum +func EmbeddedConvert608To708_Values() []string { + return []string{ + EmbeddedConvert608To708Upconvert, + EmbeddedConvert608To708Disabled, + } +} + // By default, the service terminates any unterminated captions at the end of // each input. If you want the caption to continue onto your next input, disable // this setting. @@ -20139,6 +21943,14 @@ const ( EmbeddedTerminateCaptionsDisabled = "DISABLED" ) +// EmbeddedTerminateCaptions_Values returns all elements of the EmbeddedTerminateCaptions enum +func EmbeddedTerminateCaptions_Values() []string { + return []string{ + EmbeddedTerminateCaptionsEndOfInput, + EmbeddedTerminateCaptionsDisabled, + } +} + // If set to PROGRESSIVE_DOWNLOAD, the MOOV atom is relocated to the beginning // of the archive as required for progressive downloading. Otherwise it is placed // normally at the end. @@ -20150,6 +21962,14 @@ const ( F4vMoovPlacementNormal = "NORMAL" ) +// F4vMoovPlacement_Values returns all elements of the F4vMoovPlacement enum +func F4vMoovPlacement_Values() []string { + return []string{ + F4vMoovPlacementProgressiveDownload, + F4vMoovPlacementNormal, + } +} + // Specify whether this set of input captions appears in your outputs in both // 608 and 708 format. If you choose Upconvert (UPCONVERT), MediaConvert includes // the captions data in two ways: it passes the 608 data through using the 608 @@ -20163,6 +21983,14 @@ const ( FileSourceConvert608To708Disabled = "DISABLED" ) +// FileSourceConvert608To708_Values returns all elements of the FileSourceConvert608To708 enum +func FileSourceConvert608To708_Values() []string { + return []string{ + FileSourceConvert608To708Upconvert, + FileSourceConvert608To708Disabled, + } +} + // Provide the font script, using an ISO 15924 script code, if the LanguageCode // is not sufficient for determining the script type. Where LanguageCode or // CustomLanguageCode is sufficient, use "AUTOMATIC" or leave unset. @@ -20177,6 +22005,15 @@ const ( FontScriptHant = "HANT" ) +// FontScript_Values returns all elements of the FontScript enum +func FontScript_Values() []string { + return []string{ + FontScriptAutomatic, + FontScriptHans, + FontScriptHant, + } +} + // Adaptive quantization. Allows intra-frame quantizers to vary to improve visual // quality. const ( @@ -20199,6 +22036,18 @@ const ( H264AdaptiveQuantizationMax = "MAX" ) +// H264AdaptiveQuantization_Values returns all elements of the H264AdaptiveQuantization enum +func H264AdaptiveQuantization_Values() []string { + return []string{ + H264AdaptiveQuantizationOff, + H264AdaptiveQuantizationLow, + H264AdaptiveQuantizationMedium, + H264AdaptiveQuantizationHigh, + H264AdaptiveQuantizationHigher, + H264AdaptiveQuantizationMax, + } +} + // Specify an H.264 level that is consistent with your output video settings. // If you aren't sure what level to specify, choose Auto (AUTO). const ( @@ -20254,6 +22103,29 @@ const ( H264CodecLevelLevel52 = "LEVEL_5_2" ) +// H264CodecLevel_Values returns all elements of the H264CodecLevel enum +func H264CodecLevel_Values() []string { + return []string{ + H264CodecLevelAuto, + H264CodecLevelLevel1, + H264CodecLevelLevel11, + H264CodecLevelLevel12, + H264CodecLevelLevel13, + H264CodecLevelLevel2, + H264CodecLevelLevel21, + H264CodecLevelLevel22, + H264CodecLevelLevel3, + H264CodecLevelLevel31, + H264CodecLevelLevel32, + H264CodecLevelLevel4, + H264CodecLevelLevel41, + H264CodecLevelLevel42, + H264CodecLevelLevel5, + H264CodecLevelLevel51, + H264CodecLevelLevel52, + } +} + // H.264 Profile. High 4:2:2 and 10-bit profiles are only available with the // AVC-I License. const ( @@ -20276,6 +22148,18 @@ const ( H264CodecProfileMain = "MAIN" ) +// H264CodecProfile_Values returns all elements of the H264CodecProfile enum +func H264CodecProfile_Values() []string { + return []string{ + H264CodecProfileBaseline, + H264CodecProfileHigh, + H264CodecProfileHigh10bit, + H264CodecProfileHigh422, + H264CodecProfileHigh42210bit, + H264CodecProfileMain, + } +} + // Choose Adaptive to improve subjective video quality for high-motion content. // This will cause the service to use fewer B-frames (which infer information // based on other frames) for high-motion portions of the video and more B-frames @@ -20289,6 +22173,14 @@ const ( H264DynamicSubGopStatic = "STATIC" ) +// H264DynamicSubGop_Values returns all elements of the H264DynamicSubGop enum +func H264DynamicSubGop_Values() []string { + return []string{ + H264DynamicSubGopAdaptive, + H264DynamicSubGopStatic, + } +} + // Entropy encoding mode. Use CABAC (must be in Main or High profile) or CAVLC. const ( // H264EntropyEncodingCabac is a H264EntropyEncoding enum value @@ -20298,6 +22190,14 @@ const ( H264EntropyEncodingCavlc = "CAVLC" ) +// H264EntropyEncoding_Values returns all elements of the H264EntropyEncoding enum +func H264EntropyEncoding_Values() []string { + return []string{ + H264EntropyEncodingCabac, + H264EntropyEncodingCavlc, + } +} + // Choosing FORCE_FIELD disables PAFF encoding for interlaced outputs. const ( // H264FieldEncodingPaff is a H264FieldEncoding enum value @@ -20307,6 +22207,14 @@ const ( H264FieldEncodingForceField = "FORCE_FIELD" ) +// H264FieldEncoding_Values returns all elements of the H264FieldEncoding enum +func H264FieldEncoding_Values() []string { + return []string{ + H264FieldEncodingPaff, + H264FieldEncodingForceField, + } +} + // Adjust quantization within each frame to reduce flicker or 'pop' on I-frames. const ( // H264FlickerAdaptiveQuantizationDisabled is a H264FlickerAdaptiveQuantization enum value @@ -20316,6 +22224,14 @@ const ( H264FlickerAdaptiveQuantizationEnabled = "ENABLED" ) +// H264FlickerAdaptiveQuantization_Values returns all elements of the H264FlickerAdaptiveQuantization enum +func H264FlickerAdaptiveQuantization_Values() []string { + return []string{ + H264FlickerAdaptiveQuantizationDisabled, + H264FlickerAdaptiveQuantizationEnabled, + } +} + // If you are using the console, use the Framerate setting to specify the frame // rate for this output. If you want to keep the same frame rate as the input // video, choose Follow source. If you want to do frame rate conversion, choose @@ -20335,7 +22251,16 @@ const ( H264FramerateControlSpecified = "SPECIFIED" ) -// When set to INTERPOLATE, produces smoother motion during frame rate conversion. +// H264FramerateControl_Values returns all elements of the H264FramerateControl enum +func H264FramerateControl_Values() []string { + return []string{ + H264FramerateControlInitializeFromSource, + H264FramerateControlSpecified, + } +} + +// Optional. Specify how the transcoder performs framerate conversion. The default +// behavior is to use duplicate drop conversion. const ( // H264FramerateConversionAlgorithmDuplicateDrop is a H264FramerateConversionAlgorithm enum value H264FramerateConversionAlgorithmDuplicateDrop = "DUPLICATE_DROP" @@ -20344,6 +22269,14 @@ const ( H264FramerateConversionAlgorithmInterpolate = "INTERPOLATE" ) +// H264FramerateConversionAlgorithm_Values returns all elements of the H264FramerateConversionAlgorithm enum +func H264FramerateConversionAlgorithm_Values() []string { + return []string{ + H264FramerateConversionAlgorithmDuplicateDrop, + H264FramerateConversionAlgorithmInterpolate, + } +} + // If enable, use reference B frames for GOP structures that have B frames > // 1. const ( @@ -20354,6 +22287,14 @@ const ( H264GopBReferenceEnabled = "ENABLED" ) +// H264GopBReference_Values returns all elements of the H264GopBReference enum +func H264GopBReference_Values() []string { + return []string{ + H264GopBReferenceDisabled, + H264GopBReferenceEnabled, + } +} + // Indicates if the GOP Size in H264 is specified in frames or seconds. If seconds // the system will convert the GOP Size into a frame count at run time. const ( @@ -20364,6 +22305,14 @@ const ( H264GopSizeUnitsSeconds = "SECONDS" ) +// H264GopSizeUnits_Values returns all elements of the H264GopSizeUnits enum +func H264GopSizeUnits_Values() []string { + return []string{ + H264GopSizeUnitsFrames, + H264GopSizeUnitsSeconds, + } +} + // Use Interlace mode (InterlaceMode) to choose the scan line type for the output. // * Top Field First (TOP_FIELD) and Bottom Field First (BOTTOM_FIELD) produce // interlaced output with the entire output having the same field polarity (top @@ -20392,9 +22341,24 @@ const ( H264InterlaceModeFollowBottomField = "FOLLOW_BOTTOM_FIELD" ) -// Using the API, enable ParFollowSource if you want the service to use the -// pixel aspect ratio from the input. Using the console, do this by choosing -// Follow source for Pixel aspect ratio. +// H264InterlaceMode_Values returns all elements of the H264InterlaceMode enum +func H264InterlaceMode_Values() []string { + return []string{ + H264InterlaceModeProgressive, + H264InterlaceModeTopField, + H264InterlaceModeBottomField, + H264InterlaceModeFollowTopField, + H264InterlaceModeFollowBottomField, + } +} + +// Optional. Specify how the service determines the pixel aspect ratio (PAR) +// for this output. The default behavior, Follow source (INITIALIZE_FROM_SOURCE), +// uses the PAR from your input video for your output. To specify a different +// PAR in the console, choose any value other than Follow source. To specify +// a different PAR by editing the JSON job specification, choose SPECIFIED. +// When you choose SPECIFIED for this setting, you must also specify values +// for the parNumerator and parDenominator settings. const ( // H264ParControlInitializeFromSource is a H264ParControl enum value H264ParControlInitializeFromSource = "INITIALIZE_FROM_SOURCE" @@ -20403,9 +22367,17 @@ const ( H264ParControlSpecified = "SPECIFIED" ) -// Use Quality tuning level (H264QualityTuningLevel) to specifiy whether to -// use fast single-pass, high-quality singlepass, or high-quality multipass -// video encoding. +// H264ParControl_Values returns all elements of the H264ParControl enum +func H264ParControl_Values() []string { + return []string{ + H264ParControlInitializeFromSource, + H264ParControlSpecified, + } +} + +// Optional. Use Quality tuning level (qualityTuningLevel) to choose how you +// want to trade off encoding speed for output video quality. The default behavior +// is faster, lower quality, single-pass encoding. const ( // H264QualityTuningLevelSinglePass is a H264QualityTuningLevel enum value H264QualityTuningLevelSinglePass = "SINGLE_PASS" @@ -20417,6 +22389,15 @@ const ( H264QualityTuningLevelMultiPassHq = "MULTI_PASS_HQ" ) +// H264QualityTuningLevel_Values returns all elements of the H264QualityTuningLevel enum +func H264QualityTuningLevel_Values() []string { + return []string{ + H264QualityTuningLevelSinglePass, + H264QualityTuningLevelSinglePassHq, + H264QualityTuningLevelMultiPassHq, + } +} + // Use this setting to specify whether this output has a variable bitrate (VBR), // constant bitrate (CBR) or quality-defined variable bitrate (QVBR). const ( @@ -20430,6 +22411,15 @@ const ( H264RateControlModeQvbr = "QVBR" ) +// H264RateControlMode_Values returns all elements of the H264RateControlMode enum +func H264RateControlMode_Values() []string { + return []string{ + H264RateControlModeVbr, + H264RateControlModeCbr, + H264RateControlModeQvbr, + } +} + // Places a PPS header on each encoded picture, even if repeated. const ( // H264RepeatPpsDisabled is a H264RepeatPps enum value @@ -20439,6 +22429,14 @@ const ( H264RepeatPpsEnabled = "ENABLED" ) +// H264RepeatPps_Values returns all elements of the H264RepeatPps enum +func H264RepeatPps_Values() []string { + return []string{ + H264RepeatPpsDisabled, + H264RepeatPpsEnabled, + } +} + // Enable this setting to insert I-frames at scene changes that the service // automatically detects. This improves video quality and is enabled by default. // If this output uses QVBR, choose Transition detection (TRANSITION_DETECTION) @@ -20455,6 +22453,15 @@ const ( H264SceneChangeDetectTransitionDetection = "TRANSITION_DETECTION" ) +// H264SceneChangeDetect_Values returns all elements of the H264SceneChangeDetect enum +func H264SceneChangeDetect_Values() []string { + return []string{ + H264SceneChangeDetectDisabled, + H264SceneChangeDetectEnabled, + H264SceneChangeDetectTransitionDetection, + } +} + // Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled // as 25fps, and audio is sped up correspondingly. const ( @@ -20465,6 +22472,14 @@ const ( H264SlowPalEnabled = "ENABLED" ) +// H264SlowPal_Values returns all elements of the H264SlowPal enum +func H264SlowPal_Values() []string { + return []string{ + H264SlowPalDisabled, + H264SlowPalEnabled, + } +} + // Adjust quantization within each frame based on spatial variation of content // complexity. const ( @@ -20475,6 +22490,14 @@ const ( H264SpatialAdaptiveQuantizationEnabled = "ENABLED" ) +// H264SpatialAdaptiveQuantization_Values returns all elements of the H264SpatialAdaptiveQuantization enum +func H264SpatialAdaptiveQuantization_Values() []string { + return []string{ + H264SpatialAdaptiveQuantizationDisabled, + H264SpatialAdaptiveQuantizationEnabled, + } +} + // Produces a bitstream compliant with SMPTE RP-2027. const ( // H264SyntaxDefault is a H264Syntax enum value @@ -20484,6 +22507,14 @@ const ( H264SyntaxRp2027 = "RP2027" ) +// H264Syntax_Values returns all elements of the H264Syntax enum +func H264Syntax_Values() []string { + return []string{ + H264SyntaxDefault, + H264SyntaxRp2027, + } +} + // This field applies only if the Streams > Advanced > Framerate (framerate) // field is set to 29.970. This field works with the Streams > Advanced > Preprocessors // > Deinterlacer field (deinterlace_mode) and the Streams > Advanced > Interlaced @@ -20502,6 +22533,15 @@ const ( H264TelecineHard = "HARD" ) +// H264Telecine_Values returns all elements of the H264Telecine enum +func H264Telecine_Values() []string { + return []string{ + H264TelecineNone, + H264TelecineSoft, + H264TelecineHard, + } +} + // Adjust quantization within each frame based on temporal variation of content // complexity. const ( @@ -20512,6 +22552,14 @@ const ( H264TemporalAdaptiveQuantizationEnabled = "ENABLED" ) +// H264TemporalAdaptiveQuantization_Values returns all elements of the H264TemporalAdaptiveQuantization enum +func H264TemporalAdaptiveQuantization_Values() []string { + return []string{ + H264TemporalAdaptiveQuantizationDisabled, + H264TemporalAdaptiveQuantizationEnabled, + } +} + // Inserts timecode for each frame as 4 bytes of an unregistered SEI message. const ( // H264UnregisteredSeiTimecodeDisabled is a H264UnregisteredSeiTimecode enum value @@ -20521,6 +22569,14 @@ const ( H264UnregisteredSeiTimecodeEnabled = "ENABLED" ) +// H264UnregisteredSeiTimecode_Values returns all elements of the H264UnregisteredSeiTimecode enum +func H264UnregisteredSeiTimecode_Values() []string { + return []string{ + H264UnregisteredSeiTimecodeDisabled, + H264UnregisteredSeiTimecodeEnabled, + } +} + // Adaptive quantization. Allows intra-frame quantizers to vary to improve visual // quality. const ( @@ -20543,6 +22599,18 @@ const ( H265AdaptiveQuantizationMax = "MAX" ) +// H265AdaptiveQuantization_Values returns all elements of the H265AdaptiveQuantization enum +func H265AdaptiveQuantization_Values() []string { + return []string{ + H265AdaptiveQuantizationOff, + H265AdaptiveQuantizationLow, + H265AdaptiveQuantizationMedium, + H265AdaptiveQuantizationHigh, + H265AdaptiveQuantizationHigher, + H265AdaptiveQuantizationMax, + } +} + // Enables Alternate Transfer Function SEI message for outputs using Hybrid // Log Gamma (HLG) Electro-Optical Transfer Function (EOTF). const ( @@ -20553,6 +22621,14 @@ const ( H265AlternateTransferFunctionSeiEnabled = "ENABLED" ) +// H265AlternateTransferFunctionSei_Values returns all elements of the H265AlternateTransferFunctionSei enum +func H265AlternateTransferFunctionSei_Values() []string { + return []string{ + H265AlternateTransferFunctionSeiDisabled, + H265AlternateTransferFunctionSeiEnabled, + } +} + // H.265 Level. const ( // H265CodecLevelAuto is a H265CodecLevel enum value @@ -20598,6 +22674,26 @@ const ( H265CodecLevelLevel62 = "LEVEL_6_2" ) +// H265CodecLevel_Values returns all elements of the H265CodecLevel enum +func H265CodecLevel_Values() []string { + return []string{ + H265CodecLevelAuto, + H265CodecLevelLevel1, + H265CodecLevelLevel2, + H265CodecLevelLevel21, + H265CodecLevelLevel3, + H265CodecLevelLevel31, + H265CodecLevelLevel4, + H265CodecLevelLevel41, + H265CodecLevelLevel5, + H265CodecLevelLevel51, + H265CodecLevelLevel52, + H265CodecLevelLevel6, + H265CodecLevelLevel61, + H265CodecLevelLevel62, + } +} + // Represents the Profile and Tier, per the HEVC (H.265) specification. Selections // are grouped as [Profile] / [Tier], so "Main/High" represents Main Profile // with High Tier. 4:2:2 profiles are only available with the HEVC 4:2:2 License. @@ -20627,6 +22723,20 @@ const ( H265CodecProfileMain42210bitHigh = "MAIN_422_10BIT_HIGH" ) +// H265CodecProfile_Values returns all elements of the H265CodecProfile enum +func H265CodecProfile_Values() []string { + return []string{ + H265CodecProfileMainMain, + H265CodecProfileMainHigh, + H265CodecProfileMain10Main, + H265CodecProfileMain10High, + H265CodecProfileMain4228bitMain, + H265CodecProfileMain4228bitHigh, + H265CodecProfileMain42210bitMain, + H265CodecProfileMain42210bitHigh, + } +} + // Choose Adaptive to improve subjective video quality for high-motion content. // This will cause the service to use fewer B-frames (which infer information // based on other frames) for high-motion portions of the video and more B-frames @@ -20640,6 +22750,14 @@ const ( H265DynamicSubGopStatic = "STATIC" ) +// H265DynamicSubGop_Values returns all elements of the H265DynamicSubGop enum +func H265DynamicSubGop_Values() []string { + return []string{ + H265DynamicSubGopAdaptive, + H265DynamicSubGopStatic, + } +} + // Adjust quantization within each frame to reduce flicker or 'pop' on I-frames. const ( // H265FlickerAdaptiveQuantizationDisabled is a H265FlickerAdaptiveQuantization enum value @@ -20649,13 +22767,21 @@ const ( H265FlickerAdaptiveQuantizationEnabled = "ENABLED" ) +// H265FlickerAdaptiveQuantization_Values returns all elements of the H265FlickerAdaptiveQuantization enum +func H265FlickerAdaptiveQuantization_Values() []string { + return []string{ + H265FlickerAdaptiveQuantizationDisabled, + H265FlickerAdaptiveQuantizationEnabled, + } +} + // If you are using the console, use the Framerate setting to specify the frame // rate for this output. If you want to keep the same frame rate as the input // video, choose Follow source. If you want to do frame rate conversion, choose // a frame rate from the dropdown list or choose Custom. The framerates shown // in the dropdown list are decimal approximations of fractions. If you choose // Custom, specify your frame rate as a fraction. If you are creating your transcoding -// job sepecification as a JSON file without the console, use FramerateControl +// job specification as a JSON file without the console, use FramerateControl // to specify which value the service uses for the frame rate for this output. // Choose INITIALIZE_FROM_SOURCE if you want the service to use the frame rate // from the input. Choose SPECIFIED if you want the service to use the frame @@ -20668,7 +22794,16 @@ const ( H265FramerateControlSpecified = "SPECIFIED" ) -// When set to INTERPOLATE, produces smoother motion during frame rate conversion. +// H265FramerateControl_Values returns all elements of the H265FramerateControl enum +func H265FramerateControl_Values() []string { + return []string{ + H265FramerateControlInitializeFromSource, + H265FramerateControlSpecified, + } +} + +// Optional. Specify how the transcoder performs framerate conversion. The default +// behavior is to use duplicate drop conversion. const ( // H265FramerateConversionAlgorithmDuplicateDrop is a H265FramerateConversionAlgorithm enum value H265FramerateConversionAlgorithmDuplicateDrop = "DUPLICATE_DROP" @@ -20677,6 +22812,14 @@ const ( H265FramerateConversionAlgorithmInterpolate = "INTERPOLATE" ) +// H265FramerateConversionAlgorithm_Values returns all elements of the H265FramerateConversionAlgorithm enum +func H265FramerateConversionAlgorithm_Values() []string { + return []string{ + H265FramerateConversionAlgorithmDuplicateDrop, + H265FramerateConversionAlgorithmInterpolate, + } +} + // If enable, use reference B frames for GOP structures that have B frames > // 1. const ( @@ -20687,6 +22830,14 @@ const ( H265GopBReferenceEnabled = "ENABLED" ) +// H265GopBReference_Values returns all elements of the H265GopBReference enum +func H265GopBReference_Values() []string { + return []string{ + H265GopBReferenceDisabled, + H265GopBReferenceEnabled, + } +} + // Indicates if the GOP Size in H265 is specified in frames or seconds. If seconds // the system will convert the GOP Size into a frame count at run time. const ( @@ -20697,6 +22848,14 @@ const ( H265GopSizeUnitsSeconds = "SECONDS" ) +// H265GopSizeUnits_Values returns all elements of the H265GopSizeUnits enum +func H265GopSizeUnits_Values() []string { + return []string{ + H265GopSizeUnitsFrames, + H265GopSizeUnitsSeconds, + } +} + // Choose the scan line type for the output. Choose Progressive (PROGRESSIVE) // to create a progressive output, regardless of the scan type of your input. // Choose Top Field First (TOP_FIELD) or Bottom Field First (BOTTOM_FIELD) to @@ -20726,9 +22885,24 @@ const ( H265InterlaceModeFollowBottomField = "FOLLOW_BOTTOM_FIELD" ) -// Using the API, enable ParFollowSource if you want the service to use the -// pixel aspect ratio from the input. Using the console, do this by choosing -// Follow source for Pixel aspect ratio. +// H265InterlaceMode_Values returns all elements of the H265InterlaceMode enum +func H265InterlaceMode_Values() []string { + return []string{ + H265InterlaceModeProgressive, + H265InterlaceModeTopField, + H265InterlaceModeBottomField, + H265InterlaceModeFollowTopField, + H265InterlaceModeFollowBottomField, + } +} + +// Optional. Specify how the service determines the pixel aspect ratio (PAR) +// for this output. The default behavior, Follow source (INITIALIZE_FROM_SOURCE), +// uses the PAR from your input video for your output. To specify a different +// PAR in the console, choose any value other than Follow source. To specify +// a different PAR by editing the JSON job specification, choose SPECIFIED. +// When you choose SPECIFIED for this setting, you must also specify values +// for the parNumerator and parDenominator settings. const ( // H265ParControlInitializeFromSource is a H265ParControl enum value H265ParControlInitializeFromSource = "INITIALIZE_FROM_SOURCE" @@ -20737,9 +22911,17 @@ const ( H265ParControlSpecified = "SPECIFIED" ) -// Use Quality tuning level (H265QualityTuningLevel) to specifiy whether to -// use fast single-pass, high-quality singlepass, or high-quality multipass -// video encoding. +// H265ParControl_Values returns all elements of the H265ParControl enum +func H265ParControl_Values() []string { + return []string{ + H265ParControlInitializeFromSource, + H265ParControlSpecified, + } +} + +// Optional. Use Quality tuning level (qualityTuningLevel) to choose how you +// want to trade off encoding speed for output video quality. The default behavior +// is faster, lower quality, single-pass encoding. const ( // H265QualityTuningLevelSinglePass is a H265QualityTuningLevel enum value H265QualityTuningLevelSinglePass = "SINGLE_PASS" @@ -20751,6 +22933,15 @@ const ( H265QualityTuningLevelMultiPassHq = "MULTI_PASS_HQ" ) +// H265QualityTuningLevel_Values returns all elements of the H265QualityTuningLevel enum +func H265QualityTuningLevel_Values() []string { + return []string{ + H265QualityTuningLevelSinglePass, + H265QualityTuningLevelSinglePassHq, + H265QualityTuningLevelMultiPassHq, + } +} + // Use this setting to specify whether this output has a variable bitrate (VBR), // constant bitrate (CBR) or quality-defined variable bitrate (QVBR). const ( @@ -20764,6 +22955,15 @@ const ( H265RateControlModeQvbr = "QVBR" ) +// H265RateControlMode_Values returns all elements of the H265RateControlMode enum +func H265RateControlMode_Values() []string { + return []string{ + H265RateControlModeVbr, + H265RateControlModeCbr, + H265RateControlModeQvbr, + } +} + // Specify Sample Adaptive Offset (SAO) filter strength. Adaptive mode dynamically // selects best strength based on content const ( @@ -20777,6 +22977,15 @@ const ( H265SampleAdaptiveOffsetFilterModeOff = "OFF" ) +// H265SampleAdaptiveOffsetFilterMode_Values returns all elements of the H265SampleAdaptiveOffsetFilterMode enum +func H265SampleAdaptiveOffsetFilterMode_Values() []string { + return []string{ + H265SampleAdaptiveOffsetFilterModeDefault, + H265SampleAdaptiveOffsetFilterModeAdaptive, + H265SampleAdaptiveOffsetFilterModeOff, + } +} + // Enable this setting to insert I-frames at scene changes that the service // automatically detects. This improves video quality and is enabled by default. // If this output uses QVBR, choose Transition detection (TRANSITION_DETECTION) @@ -20793,6 +23002,15 @@ const ( H265SceneChangeDetectTransitionDetection = "TRANSITION_DETECTION" ) +// H265SceneChangeDetect_Values returns all elements of the H265SceneChangeDetect enum +func H265SceneChangeDetect_Values() []string { + return []string{ + H265SceneChangeDetectDisabled, + H265SceneChangeDetectEnabled, + H265SceneChangeDetectTransitionDetection, + } +} + // Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled // as 25fps, and audio is sped up correspondingly. const ( @@ -20803,6 +23021,14 @@ const ( H265SlowPalEnabled = "ENABLED" ) +// H265SlowPal_Values returns all elements of the H265SlowPal enum +func H265SlowPal_Values() []string { + return []string{ + H265SlowPalDisabled, + H265SlowPalEnabled, + } +} + // Adjust quantization within each frame based on spatial variation of content // complexity. const ( @@ -20813,6 +23039,14 @@ const ( H265SpatialAdaptiveQuantizationEnabled = "ENABLED" ) +// H265SpatialAdaptiveQuantization_Values returns all elements of the H265SpatialAdaptiveQuantization enum +func H265SpatialAdaptiveQuantization_Values() []string { + return []string{ + H265SpatialAdaptiveQuantizationDisabled, + H265SpatialAdaptiveQuantizationEnabled, + } +} + // This field applies only if the Streams > Advanced > Framerate (framerate) // field is set to 29.970. This field works with the Streams > Advanced > Preprocessors // > Deinterlacer field (deinterlace_mode) and the Streams > Advanced > Interlaced @@ -20831,6 +23065,15 @@ const ( H265TelecineHard = "HARD" ) +// H265Telecine_Values returns all elements of the H265Telecine enum +func H265Telecine_Values() []string { + return []string{ + H265TelecineNone, + H265TelecineSoft, + H265TelecineHard, + } +} + // Adjust quantization within each frame based on temporal variation of content // complexity. const ( @@ -20841,6 +23084,14 @@ const ( H265TemporalAdaptiveQuantizationEnabled = "ENABLED" ) +// H265TemporalAdaptiveQuantization_Values returns all elements of the H265TemporalAdaptiveQuantization enum +func H265TemporalAdaptiveQuantization_Values() []string { + return []string{ + H265TemporalAdaptiveQuantizationDisabled, + H265TemporalAdaptiveQuantizationEnabled, + } +} + // Enables temporal layer identifiers in the encoded bitstream. Up to 3 layers // are supported depending on GOP structure: I- and P-frames form one layer, // reference B-frames can form a second layer and non-reference b-frames can @@ -20857,6 +23108,14 @@ const ( H265TemporalIdsEnabled = "ENABLED" ) +// H265TemporalIds_Values returns all elements of the H265TemporalIds enum +func H265TemporalIds_Values() []string { + return []string{ + H265TemporalIdsDisabled, + H265TemporalIdsEnabled, + } +} + // Enable use of tiles, allowing horizontal as well as vertical subdivision // of the encoded pictures. const ( @@ -20867,6 +23126,14 @@ const ( H265TilesEnabled = "ENABLED" ) +// H265Tiles_Values returns all elements of the H265Tiles enum +func H265Tiles_Values() []string { + return []string{ + H265TilesDisabled, + H265TilesEnabled, + } +} + // Inserts timecode for each frame as 4 bytes of an unregistered SEI message. const ( // H265UnregisteredSeiTimecodeDisabled is a H265UnregisteredSeiTimecode enum value @@ -20876,6 +23143,14 @@ const ( H265UnregisteredSeiTimecodeEnabled = "ENABLED" ) +// H265UnregisteredSeiTimecode_Values returns all elements of the H265UnregisteredSeiTimecode enum +func H265UnregisteredSeiTimecode_Values() []string { + return []string{ + H265UnregisteredSeiTimecodeDisabled, + H265UnregisteredSeiTimecodeEnabled, + } +} + // If the location of parameter set NAL units doesn't matter in your workflow, // ignore this setting. Use this setting only with CMAF or DASH outputs, or // with standalone file outputs in an MPEG-4 container (MP4 outputs). Choose @@ -20895,6 +23170,14 @@ const ( H265WriteMp4PackagingTypeHev1 = "HEV1" ) +// H265WriteMp4PackagingType_Values returns all elements of the H265WriteMp4PackagingType enum +func H265WriteMp4PackagingType_Values() []string { + return []string{ + H265WriteMp4PackagingTypeHvc1, + H265WriteMp4PackagingTypeHev1, + } +} + const ( // HlsAdMarkersElemental is a HlsAdMarkers enum value HlsAdMarkersElemental = "ELEMENTAL" @@ -20903,6 +23186,14 @@ const ( HlsAdMarkersElementalScte35 = "ELEMENTAL_SCTE35" ) +// HlsAdMarkers_Values returns all elements of the HlsAdMarkers enum +func HlsAdMarkers_Values() []string { + return []string{ + HlsAdMarkersElemental, + HlsAdMarkersElementalScte35, + } +} + // Use this setting only in audio-only outputs. Choose MPEG-2 Transport Stream // (M2TS) to create a file in an MPEG2-TS container. Keep the default value // Automatic (AUTOMATIC) to create a raw audio-only file with no container. @@ -20916,6 +23207,14 @@ const ( HlsAudioOnlyContainerM2ts = "M2TS" ) +// HlsAudioOnlyContainer_Values returns all elements of the HlsAudioOnlyContainer enum +func HlsAudioOnlyContainer_Values() []string { + return []string{ + HlsAudioOnlyContainerAutomatic, + HlsAudioOnlyContainerM2ts, + } +} + // Four types of audio-only tracks are supported: Audio-Only Variant Stream // The client can play back this audio-only stream instead of video in low-bandwidth // scenarios. Represented as an EXT-X-STREAM-INF in the HLS manifest. Alternate @@ -20941,6 +23240,16 @@ const ( HlsAudioTrackTypeAudioOnlyVariantStream = "AUDIO_ONLY_VARIANT_STREAM" ) +// HlsAudioTrackType_Values returns all elements of the HlsAudioTrackType enum +func HlsAudioTrackType_Values() []string { + return []string{ + HlsAudioTrackTypeAlternateAudioAutoSelectDefault, + HlsAudioTrackTypeAlternateAudioAutoSelect, + HlsAudioTrackTypeAlternateAudioNotAutoSelect, + HlsAudioTrackTypeAudioOnlyVariantStream, + } +} + // Applies only to 608 Embedded output captions. Insert: Include CLOSED-CAPTIONS // lines in the manifest. Specify at least one language in the CC1 Language // Code field. One CLOSED-CAPTION line is added for each Language Code you specify. @@ -20961,6 +23270,15 @@ const ( HlsCaptionLanguageSettingNone = "NONE" ) +// HlsCaptionLanguageSetting_Values returns all elements of the HlsCaptionLanguageSetting enum +func HlsCaptionLanguageSetting_Values() []string { + return []string{ + HlsCaptionLanguageSettingInsert, + HlsCaptionLanguageSettingOmit, + HlsCaptionLanguageSettingNone, + } +} + // When set to ENABLED, sets #EXT-X-ALLOW-CACHE:no tag, which prevents client // from saving media segments for later replay. const ( @@ -20971,6 +23289,14 @@ const ( HlsClientCacheEnabled = "ENABLED" ) +// HlsClientCache_Values returns all elements of the HlsClientCache enum +func HlsClientCache_Values() []string { + return []string{ + HlsClientCacheDisabled, + HlsClientCacheEnabled, + } +} + // Specification to use (RFC-6381 or the default RFC-4281) during m3u8 playlist // generation. const ( @@ -20981,6 +23307,14 @@ const ( HlsCodecSpecificationRfc4281 = "RFC_4281" ) +// HlsCodecSpecification_Values returns all elements of the HlsCodecSpecification enum +func HlsCodecSpecification_Values() []string { + return []string{ + HlsCodecSpecificationRfc6381, + HlsCodecSpecificationRfc4281, + } +} + // Indicates whether segments should be placed in subdirectories. const ( // HlsDirectoryStructureSingleDirectory is a HlsDirectoryStructure enum value @@ -20990,6 +23324,14 @@ const ( HlsDirectoryStructureSubdirectoryPerStream = "SUBDIRECTORY_PER_STREAM" ) +// HlsDirectoryStructure_Values returns all elements of the HlsDirectoryStructure enum +func HlsDirectoryStructure_Values() []string { + return []string{ + HlsDirectoryStructureSingleDirectory, + HlsDirectoryStructureSubdirectoryPerStream, + } +} + // Encrypts the segments with the given encryption scheme. Leave blank to disable. // Selecting 'Disabled' in the web interface also disables encryption. const ( @@ -21000,6 +23342,14 @@ const ( HlsEncryptionTypeSampleAes = "SAMPLE_AES" ) +// HlsEncryptionType_Values returns all elements of the HlsEncryptionType enum +func HlsEncryptionType_Values() []string { + return []string{ + HlsEncryptionTypeAes128, + HlsEncryptionTypeSampleAes, + } +} + // When set to INCLUDE, writes I-Frame Only Manifest in addition to the HLS // manifest const ( @@ -21010,6 +23360,14 @@ const ( HlsIFrameOnlyManifestExclude = "EXCLUDE" ) +// HlsIFrameOnlyManifest_Values returns all elements of the HlsIFrameOnlyManifest enum +func HlsIFrameOnlyManifest_Values() []string { + return []string{ + HlsIFrameOnlyManifestInclude, + HlsIFrameOnlyManifestExclude, + } +} + // The Initialization Vector is a 128-bit number used in conjunction with the // key for encrypting blocks. If set to INCLUDE, Initialization Vector is listed // in the manifest. Otherwise Initialization Vector is not in the manifest. @@ -21021,6 +23379,14 @@ const ( HlsInitializationVectorInManifestExclude = "EXCLUDE" ) +// HlsInitializationVectorInManifest_Values returns all elements of the HlsInitializationVectorInManifest enum +func HlsInitializationVectorInManifest_Values() []string { + return []string{ + HlsInitializationVectorInManifestInclude, + HlsInitializationVectorInManifestExclude, + } +} + // Specify whether your DRM encryption key is static or from a key provider // that follows the SPEKE standard. For more information about SPEKE, see https://docs.aws.amazon.com/speke/latest/documentation/what-is-speke.html. const ( @@ -21031,6 +23397,14 @@ const ( HlsKeyProviderTypeStaticKey = "STATIC_KEY" ) +// HlsKeyProviderType_Values returns all elements of the HlsKeyProviderType enum +func HlsKeyProviderType_Values() []string { + return []string{ + HlsKeyProviderTypeSpeke, + HlsKeyProviderTypeStaticKey, + } +} + // When set to GZIP, compresses HLS playlist. const ( // HlsManifestCompressionGzip is a HlsManifestCompression enum value @@ -21040,6 +23414,14 @@ const ( HlsManifestCompressionNone = "NONE" ) +// HlsManifestCompression_Values returns all elements of the HlsManifestCompression enum +func HlsManifestCompression_Values() []string { + return []string{ + HlsManifestCompressionGzip, + HlsManifestCompressionNone, + } +} + // Indicates whether the output manifest should use floating point values for // segment duration. const ( @@ -21050,6 +23432,14 @@ const ( HlsManifestDurationFormatInteger = "INTEGER" ) +// HlsManifestDurationFormat_Values returns all elements of the HlsManifestDurationFormat enum +func HlsManifestDurationFormat_Values() []string { + return []string{ + HlsManifestDurationFormatFloatingPoint, + HlsManifestDurationFormatInteger, + } +} + // Enable this setting to insert the EXT-X-SESSION-KEY element into the master // playlist. This allows for offline Apple HLS FairPlay content protection. const ( @@ -21060,6 +23450,14 @@ const ( HlsOfflineEncryptedDisabled = "DISABLED" ) +// HlsOfflineEncrypted_Values returns all elements of the HlsOfflineEncrypted enum +func HlsOfflineEncrypted_Values() []string { + return []string{ + HlsOfflineEncryptedEnabled, + HlsOfflineEncryptedDisabled, + } +} + // Indicates whether the .m3u8 manifest file should be generated for this HLS // output group. const ( @@ -21070,6 +23468,14 @@ const ( HlsOutputSelectionSegmentsOnly = "SEGMENTS_ONLY" ) +// HlsOutputSelection_Values returns all elements of the HlsOutputSelection enum +func HlsOutputSelection_Values() []string { + return []string{ + HlsOutputSelectionManifestsAndSegments, + HlsOutputSelectionSegmentsOnly, + } +} + // Includes or excludes EXT-X-PROGRAM-DATE-TIME tag in .m3u8 manifest files. // The value is calculated as follows: either the program date and time are // initialized using the input timecode source, or the time is initialized using @@ -21082,6 +23488,14 @@ const ( HlsProgramDateTimeExclude = "EXCLUDE" ) +// HlsProgramDateTime_Values returns all elements of the HlsProgramDateTime enum +func HlsProgramDateTime_Values() []string { + return []string{ + HlsProgramDateTimeInclude, + HlsProgramDateTimeExclude, + } +} + // When set to SINGLE_FILE, emits program as a single media resource (.ts) file, // uses #EXT-X-BYTERANGE tags to index segment for playback. const ( @@ -21092,6 +23506,14 @@ const ( HlsSegmentControlSegmentedFiles = "SEGMENTED_FILES" ) +// HlsSegmentControl_Values returns all elements of the HlsSegmentControl enum +func HlsSegmentControl_Values() []string { + return []string{ + HlsSegmentControlSingleFile, + HlsSegmentControlSegmentedFiles, + } +} + // Include or exclude RESOLUTION attribute for video in EXT-X-STREAM-INF tag // of variant manifest. const ( @@ -21102,6 +23524,14 @@ const ( HlsStreamInfResolutionExclude = "EXCLUDE" ) +// HlsStreamInfResolution_Values returns all elements of the HlsStreamInfResolution enum +func HlsStreamInfResolution_Values() []string { + return []string{ + HlsStreamInfResolutionInclude, + HlsStreamInfResolutionExclude, + } +} + // Indicates ID3 frame that has the timecode. const ( // HlsTimedMetadataId3FrameNone is a HlsTimedMetadataId3Frame enum value @@ -21114,6 +23544,15 @@ const ( HlsTimedMetadataId3FrameTdrl = "TDRL" ) +// HlsTimedMetadataId3Frame_Values returns all elements of the HlsTimedMetadataId3Frame enum +func HlsTimedMetadataId3Frame_Values() []string { + return []string{ + HlsTimedMetadataId3FrameNone, + HlsTimedMetadataId3FramePriv, + HlsTimedMetadataId3FrameTdrl, + } +} + // Keep this setting enabled to have MediaConvert use the font style and position // information from the captions source in the output. This option is available // only when your input captions are IMSC, SMPTE-TT, or TTML. Disable this setting @@ -21126,8 +23565,16 @@ const ( ImscStylePassthroughDisabled = "DISABLED" ) +// ImscStylePassthrough_Values returns all elements of the ImscStylePassthrough enum +func ImscStylePassthrough_Values() []string { + return []string{ + ImscStylePassthroughEnabled, + ImscStylePassthroughDisabled, + } +} + // Enable Deblock (InputDeblockFilter) to produce smoother motion in the output. -// Default is disabled. Only manaully controllable for MPEG2 and uncompressed +// Default is disabled. Only manually controllable for MPEG2 and uncompressed // video inputs. const ( // InputDeblockFilterEnabled is a InputDeblockFilter enum value @@ -21137,6 +23584,14 @@ const ( InputDeblockFilterDisabled = "DISABLED" ) +// InputDeblockFilter_Values returns all elements of the InputDeblockFilter enum +func InputDeblockFilter_Values() []string { + return []string{ + InputDeblockFilterEnabled, + InputDeblockFilterDisabled, + } +} + // Enable Denoise (InputDenoiseFilter) to filter noise from the input. Default // is disabled. Only applicable to MPEG2, H.264, H.265, and uncompressed video // inputs. @@ -21148,6 +23603,14 @@ const ( InputDenoiseFilterDisabled = "DISABLED" ) +// InputDenoiseFilter_Values returns all elements of the InputDenoiseFilter enum +func InputDenoiseFilter_Values() []string { + return []string{ + InputDenoiseFilterEnabled, + InputDenoiseFilterDisabled, + } +} + // Use Filter enable (InputFilterEnable) to specify how the transcoding service // applies the denoise and deblock filters. You must also enable the filters // separately, with Denoise (InputDenoiseFilter) and Deblock (InputDeblockFilter). @@ -21166,6 +23629,15 @@ const ( InputFilterEnableForce = "FORCE" ) +// InputFilterEnable_Values returns all elements of the InputFilterEnable enum +func InputFilterEnable_Values() []string { + return []string{ + InputFilterEnableAuto, + InputFilterEnableDisable, + InputFilterEnableForce, + } +} + // Set PSI control (InputPsiControl) for transport stream inputs to specify // which data the demux process to scans. * Ignore PSI - Scan all PIDs for audio // and video. * Use PSI - Scan only PSI data. @@ -21177,6 +23649,14 @@ const ( InputPsiControlUsePsi = "USE_PSI" ) +// InputPsiControl_Values returns all elements of the InputPsiControl enum +func InputPsiControl_Values() []string { + return []string{ + InputPsiControlIgnorePsi, + InputPsiControlUsePsi, + } +} + // Use Rotate (InputRotate) to specify how the service rotates your video. You // can choose automatic rotation or specify a rotation. You can specify a clockwise // rotation of 0, 90, 180, or 270 degrees. If your input video container is @@ -21204,6 +23684,17 @@ const ( InputRotateAuto = "AUTO" ) +// InputRotate_Values returns all elements of the InputRotate enum +func InputRotate_Values() []string { + return []string{ + InputRotateDegree0, + InputRotateDegrees90, + InputRotateDegrees180, + InputRotateDegrees270, + InputRotateAuto, + } +} + // Use this Timecode source setting, located under the input settings (InputTimecodeSource), // to specify how the service counts input video frames. This input frame count // affects only the behavior of features that apply to a single input at a time, @@ -21225,6 +23716,15 @@ const ( InputTimecodeSourceSpecifiedstart = "SPECIFIEDSTART" ) +// InputTimecodeSource_Values returns all elements of the InputTimecodeSource enum +func InputTimecodeSource_Values() []string { + return []string{ + InputTimecodeSourceEmbedded, + InputTimecodeSourceZerobased, + InputTimecodeSourceSpecifiedstart, + } +} + // A job's phase can be PROBING, TRANSCODING OR UPLOADING const ( // JobPhaseProbing is a JobPhase enum value @@ -21237,6 +23737,15 @@ const ( JobPhaseUploading = "UPLOADING" ) +// JobPhase_Values returns all elements of the JobPhase enum +func JobPhase_Values() []string { + return []string{ + JobPhaseProbing, + JobPhaseTranscoding, + JobPhaseUploading, + } +} + // A job's status can be SUBMITTED, PROGRESSING, COMPLETE, CANCELED, or ERROR. const ( // JobStatusSubmitted is a JobStatus enum value @@ -21255,6 +23764,17 @@ const ( JobStatusError = "ERROR" ) +// JobStatus_Values returns all elements of the JobStatus enum +func JobStatus_Values() []string { + return []string{ + JobStatusSubmitted, + JobStatusProgressing, + JobStatusComplete, + JobStatusCanceled, + JobStatusError, + } +} + // Optional. When you request a list of job templates, you can choose to list // them alphabetically by NAME or chronologically by CREATION_DATE. If you don't // specify, the service will list them by name. @@ -21269,6 +23789,15 @@ const ( JobTemplateListBySystem = "SYSTEM" ) +// JobTemplateListBy_Values returns all elements of the JobTemplateListBy enum +func JobTemplateListBy_Values() []string { + return []string{ + JobTemplateListByName, + JobTemplateListByCreationDate, + JobTemplateListBySystem, + } +} + // Specify the language, using the ISO 639-2 three-letter code listed at https://www.loc.gov/standards/iso639-2/php/code_list.php. const ( // LanguageCodeEng is a LanguageCode enum value @@ -21845,6 +24374,203 @@ const ( LanguageCodeTng = "TNG" ) +// LanguageCode_Values returns all elements of the LanguageCode enum +func LanguageCode_Values() []string { + return []string{ + LanguageCodeEng, + LanguageCodeSpa, + LanguageCodeFra, + LanguageCodeDeu, + LanguageCodeGer, + LanguageCodeZho, + LanguageCodeAra, + LanguageCodeHin, + LanguageCodeJpn, + LanguageCodeRus, + LanguageCodePor, + LanguageCodeIta, + LanguageCodeUrd, + LanguageCodeVie, + LanguageCodeKor, + LanguageCodePan, + LanguageCodeAbk, + LanguageCodeAar, + LanguageCodeAfr, + LanguageCodeAka, + LanguageCodeSqi, + LanguageCodeAmh, + LanguageCodeArg, + LanguageCodeHye, + LanguageCodeAsm, + LanguageCodeAva, + LanguageCodeAve, + LanguageCodeAym, + LanguageCodeAze, + LanguageCodeBam, + LanguageCodeBak, + LanguageCodeEus, + LanguageCodeBel, + LanguageCodeBen, + LanguageCodeBih, + LanguageCodeBis, + LanguageCodeBos, + LanguageCodeBre, + LanguageCodeBul, + LanguageCodeMya, + LanguageCodeCat, + LanguageCodeKhm, + LanguageCodeCha, + LanguageCodeChe, + LanguageCodeNya, + LanguageCodeChu, + LanguageCodeChv, + LanguageCodeCor, + LanguageCodeCos, + LanguageCodeCre, + LanguageCodeHrv, + LanguageCodeCes, + LanguageCodeDan, + LanguageCodeDiv, + LanguageCodeNld, + LanguageCodeDzo, + LanguageCodeEnm, + LanguageCodeEpo, + LanguageCodeEst, + LanguageCodeEwe, + LanguageCodeFao, + LanguageCodeFij, + LanguageCodeFin, + LanguageCodeFrm, + LanguageCodeFul, + LanguageCodeGla, + LanguageCodeGlg, + LanguageCodeLug, + LanguageCodeKat, + LanguageCodeEll, + LanguageCodeGrn, + LanguageCodeGuj, + LanguageCodeHat, + LanguageCodeHau, + LanguageCodeHeb, + LanguageCodeHer, + LanguageCodeHmo, + LanguageCodeHun, + LanguageCodeIsl, + LanguageCodeIdo, + LanguageCodeIbo, + LanguageCodeInd, + LanguageCodeIna, + LanguageCodeIle, + LanguageCodeIku, + LanguageCodeIpk, + LanguageCodeGle, + LanguageCodeJav, + LanguageCodeKal, + LanguageCodeKan, + LanguageCodeKau, + LanguageCodeKas, + LanguageCodeKaz, + LanguageCodeKik, + LanguageCodeKin, + LanguageCodeKir, + LanguageCodeKom, + LanguageCodeKon, + LanguageCodeKua, + LanguageCodeKur, + LanguageCodeLao, + LanguageCodeLat, + LanguageCodeLav, + LanguageCodeLim, + LanguageCodeLin, + LanguageCodeLit, + LanguageCodeLub, + LanguageCodeLtz, + LanguageCodeMkd, + LanguageCodeMlg, + LanguageCodeMsa, + LanguageCodeMal, + LanguageCodeMlt, + LanguageCodeGlv, + LanguageCodeMri, + LanguageCodeMar, + LanguageCodeMah, + LanguageCodeMon, + LanguageCodeNau, + LanguageCodeNav, + LanguageCodeNde, + LanguageCodeNbl, + LanguageCodeNdo, + LanguageCodeNep, + LanguageCodeSme, + LanguageCodeNor, + LanguageCodeNob, + LanguageCodeNno, + LanguageCodeOci, + LanguageCodeOji, + LanguageCodeOri, + LanguageCodeOrm, + LanguageCodeOss, + LanguageCodePli, + LanguageCodeFas, + LanguageCodePol, + LanguageCodePus, + LanguageCodeQue, + LanguageCodeQaa, + LanguageCodeRon, + LanguageCodeRoh, + LanguageCodeRun, + LanguageCodeSmo, + LanguageCodeSag, + LanguageCodeSan, + LanguageCodeSrd, + LanguageCodeSrb, + LanguageCodeSna, + LanguageCodeIii, + LanguageCodeSnd, + LanguageCodeSin, + LanguageCodeSlk, + LanguageCodeSlv, + LanguageCodeSom, + LanguageCodeSot, + LanguageCodeSun, + LanguageCodeSwa, + LanguageCodeSsw, + LanguageCodeSwe, + LanguageCodeTgl, + LanguageCodeTah, + LanguageCodeTgk, + LanguageCodeTam, + LanguageCodeTat, + LanguageCodeTel, + LanguageCodeTha, + LanguageCodeBod, + LanguageCodeTir, + LanguageCodeTon, + LanguageCodeTso, + LanguageCodeTsn, + LanguageCodeTur, + LanguageCodeTuk, + LanguageCodeTwi, + LanguageCodeUig, + LanguageCodeUkr, + LanguageCodeUzb, + LanguageCodeVen, + LanguageCodeVol, + LanguageCodeWln, + LanguageCodeCym, + LanguageCodeFry, + LanguageCodeWol, + LanguageCodeXho, + LanguageCodeYid, + LanguageCodeYor, + LanguageCodeZha, + LanguageCodeZul, + LanguageCodeOrj, + LanguageCodeQpc, + LanguageCodeTng, + } +} + // Selects between the DVB and ATSC buffer models for Dolby Digital audio. const ( // M2tsAudioBufferModelDvb is a M2tsAudioBufferModel enum value @@ -21854,6 +24580,14 @@ const ( M2tsAudioBufferModelAtsc = "ATSC" ) +// M2tsAudioBufferModel_Values returns all elements of the M2tsAudioBufferModel enum +func M2tsAudioBufferModel_Values() []string { + return []string{ + M2tsAudioBufferModelDvb, + M2tsAudioBufferModelAtsc, + } +} + // Controls what buffer model to use for accurate interleaving. If set to MULTIPLEX, // use multiplex buffer model. If set to NONE, this can lead to lower latency, // but low-memory devices may not be able to play back the stream without interruptions. @@ -21865,6 +24599,14 @@ const ( M2tsBufferModelNone = "NONE" ) +// M2tsBufferModel_Values returns all elements of the M2tsBufferModel enum +func M2tsBufferModel_Values() []string { + return []string{ + M2tsBufferModelMultiplex, + M2tsBufferModelNone, + } +} + // When set to VIDEO_AND_FIXED_INTERVALS, audio EBP markers will be added to // partitions 3 and 4. The interval between these additional markers will be // fixed, and will be slightly shorter than the video EBP marker interval. When @@ -21879,6 +24621,14 @@ const ( M2tsEbpAudioIntervalVideoInterval = "VIDEO_INTERVAL" ) +// M2tsEbpAudioInterval_Values returns all elements of the M2tsEbpAudioInterval enum +func M2tsEbpAudioInterval_Values() []string { + return []string{ + M2tsEbpAudioIntervalVideoAndFixedIntervals, + M2tsEbpAudioIntervalVideoInterval, + } +} + // Selects which PIDs to place EBP markers on. They can either be placed only // on the video PID, or on both the video PID and all audio PIDs. Only applicable // when EBP segmentation markers are is selected (segmentationMarkers is EBP @@ -21891,6 +24641,14 @@ const ( M2tsEbpPlacementVideoPid = "VIDEO_PID" ) +// M2tsEbpPlacement_Values returns all elements of the M2tsEbpPlacement enum +func M2tsEbpPlacement_Values() []string { + return []string{ + M2tsEbpPlacementVideoAndAudioPids, + M2tsEbpPlacementVideoPid, + } +} + // Controls whether to include the ES Rate field in the PES header. const ( // M2tsEsRateInPesInclude is a M2tsEsRateInPes enum value @@ -21900,6 +24658,14 @@ const ( M2tsEsRateInPesExclude = "EXCLUDE" ) +// M2tsEsRateInPes_Values returns all elements of the M2tsEsRateInPes enum +func M2tsEsRateInPes_Values() []string { + return []string{ + M2tsEsRateInPesInclude, + M2tsEsRateInPesExclude, + } +} + // Keep the default value (DEFAULT) unless you know that your audio EBP markers // are incorrectly appearing before your video EBP markers. To correct this // problem, set this value to Force (FORCE). @@ -21911,6 +24677,14 @@ const ( M2tsForceTsVideoEbpOrderDefault = "DEFAULT" ) +// M2tsForceTsVideoEbpOrder_Values returns all elements of the M2tsForceTsVideoEbpOrder enum +func M2tsForceTsVideoEbpOrder_Values() []string { + return []string{ + M2tsForceTsVideoEbpOrderForce, + M2tsForceTsVideoEbpOrderDefault, + } +} + // If INSERT, Nielsen inaudible tones for media tracking will be detected in // the input audio and an equivalent ID3 tag will be inserted in the output. const ( @@ -21921,6 +24695,14 @@ const ( M2tsNielsenId3None = "NONE" ) +// M2tsNielsenId3_Values returns all elements of the M2tsNielsenId3 enum +func M2tsNielsenId3_Values() []string { + return []string{ + M2tsNielsenId3Insert, + M2tsNielsenId3None, + } +} + // When set to PCR_EVERY_PES_PACKET, a Program Clock Reference value is inserted // for every Packetized Elementary Stream (PES) header. This is effective only // when the PCR PID is the same as the video or audio elementary stream. @@ -21932,6 +24714,14 @@ const ( M2tsPcrControlConfiguredPcrPeriod = "CONFIGURED_PCR_PERIOD" ) +// M2tsPcrControl_Values returns all elements of the M2tsPcrControl enum +func M2tsPcrControl_Values() []string { + return []string{ + M2tsPcrControlPcrEveryPesPacket, + M2tsPcrControlConfiguredPcrPeriod, + } +} + // When set to CBR, inserts null packets into transport stream to fill specified // bitrate. When set to VBR, the bitrate setting acts as the maximum bitrate, // but the output will not be padded up to that bitrate. @@ -21943,6 +24733,14 @@ const ( M2tsRateModeCbr = "CBR" ) +// M2tsRateMode_Values returns all elements of the M2tsRateMode enum +func M2tsRateMode_Values() []string { + return []string{ + M2tsRateModeVbr, + M2tsRateModeCbr, + } +} + // For SCTE-35 markers from your input-- Choose Passthrough (PASSTHROUGH) if // you want SCTE-35 markers that appear in your input to also appear in this // output. Choose None (NONE) if you don't want SCTE-35 markers in this output. @@ -21957,6 +24755,14 @@ const ( M2tsScte35SourceNone = "NONE" ) +// M2tsScte35Source_Values returns all elements of the M2tsScte35Source enum +func M2tsScte35Source_Values() []string { + return []string{ + M2tsScte35SourcePassthrough, + M2tsScte35SourceNone, + } +} + // Inserts segmentation markers at each segmentation_time period. rai_segstart // sets the Random Access Indicator bit in the adaptation field. rai_adapt sets // the RAI bit and adds the current timecode in the private data bytes. psi_segstart @@ -21984,6 +24790,18 @@ const ( M2tsSegmentationMarkersEbpLegacy = "EBP_LEGACY" ) +// M2tsSegmentationMarkers_Values returns all elements of the M2tsSegmentationMarkers enum +func M2tsSegmentationMarkers_Values() []string { + return []string{ + M2tsSegmentationMarkersNone, + M2tsSegmentationMarkersRaiSegstart, + M2tsSegmentationMarkersRaiAdapt, + M2tsSegmentationMarkersPsiSegstart, + M2tsSegmentationMarkersEbp, + M2tsSegmentationMarkersEbpLegacy, + } +} + // The segmentation style parameter controls how segmentation markers are inserted // into the transport stream. With avails, it is possible that segments may // be truncated, which can influence where future segmentation markers are inserted. @@ -22003,6 +24821,14 @@ const ( M2tsSegmentationStyleResetCadence = "RESET_CADENCE" ) +// M2tsSegmentationStyle_Values returns all elements of the M2tsSegmentationStyle enum +func M2tsSegmentationStyle_Values() []string { + return []string{ + M2tsSegmentationStyleMaintainCadence, + M2tsSegmentationStyleResetCadence, + } +} + // If INSERT, Nielsen inaudible tones for media tracking will be detected in // the input audio and an equivalent ID3 tag will be inserted in the output. const ( @@ -22013,6 +24839,14 @@ const ( M3u8NielsenId3None = "NONE" ) +// M3u8NielsenId3_Values returns all elements of the M3u8NielsenId3 enum +func M3u8NielsenId3_Values() []string { + return []string{ + M3u8NielsenId3Insert, + M3u8NielsenId3None, + } +} + // When set to PCR_EVERY_PES_PACKET a Program Clock Reference value is inserted // for every Packetized Elementary Stream (PES) header. This parameter is effective // only when the PCR PID is the same as the video or audio elementary stream. @@ -22024,6 +24858,14 @@ const ( M3u8PcrControlConfiguredPcrPeriod = "CONFIGURED_PCR_PERIOD" ) +// M3u8PcrControl_Values returns all elements of the M3u8PcrControl enum +func M3u8PcrControl_Values() []string { + return []string{ + M3u8PcrControlPcrEveryPesPacket, + M3u8PcrControlConfiguredPcrPeriod, + } +} + // For SCTE-35 markers from your input-- Choose Passthrough (PASSTHROUGH) if // you want SCTE-35 markers that appear in your input to also appear in this // output. Choose None (NONE) if you don't want SCTE-35 markers in this output. @@ -22040,6 +24882,14 @@ const ( M3u8Scte35SourceNone = "NONE" ) +// M3u8Scte35Source_Values returns all elements of the M3u8Scte35Source enum +func M3u8Scte35Source_Values() []string { + return []string{ + M3u8Scte35SourcePassthrough, + M3u8Scte35SourceNone, + } +} + // Choose the type of motion graphic asset that you are providing for your overlay. // You can choose either a .mov file or a series of .png files. const ( @@ -22050,6 +24900,14 @@ const ( MotionImageInsertionModePng = "PNG" ) +// MotionImageInsertionMode_Values returns all elements of the MotionImageInsertionMode enum +func MotionImageInsertionMode_Values() []string { + return []string{ + MotionImageInsertionModeMov, + MotionImageInsertionModePng, + } +} + // Specify whether your motion graphic overlay repeats on a loop or plays only // once. const ( @@ -22060,6 +24918,14 @@ const ( MotionImagePlaybackRepeat = "REPEAT" ) +// MotionImagePlayback_Values returns all elements of the MotionImagePlayback enum +func MotionImagePlayback_Values() []string { + return []string{ + MotionImagePlaybackOnce, + MotionImagePlaybackRepeat, + } +} + // When enabled, include 'clap' atom if appropriate for the video output settings. const ( // MovClapAtomInclude is a MovClapAtom enum value @@ -22069,6 +24935,14 @@ const ( MovClapAtomExclude = "EXCLUDE" ) +// MovClapAtom_Values returns all elements of the MovClapAtom enum +func MovClapAtom_Values() []string { + return []string{ + MovClapAtomInclude, + MovClapAtomExclude, + } +} + // When enabled, file composition times will start at zero, composition times // in the 'ctts' (composition time to sample) box for B-frames will be negative, // and a 'cslg' (composition shift least greatest) box will be included per @@ -22081,6 +24955,14 @@ const ( MovCslgAtomExclude = "EXCLUDE" ) +// MovCslgAtom_Values returns all elements of the MovCslgAtom enum +func MovCslgAtom_Values() []string { + return []string{ + MovCslgAtomInclude, + MovCslgAtomExclude, + } +} + // When set to XDCAM, writes MPEG2 video streams into the QuickTime file using // XDCAM fourcc codes. This increases compatibility with Apple editors and players, // but may decrease compatibility with other players. Only applicable when the @@ -22093,6 +24975,14 @@ const ( MovMpeg2FourCCControlMpeg = "MPEG" ) +// MovMpeg2FourCCControl_Values returns all elements of the MovMpeg2FourCCControl enum +func MovMpeg2FourCCControl_Values() []string { + return []string{ + MovMpeg2FourCCControlXdcam, + MovMpeg2FourCCControlMpeg, + } +} + // If set to OMNEON, inserts Omneon-compatible padding const ( // MovPaddingControlOmneon is a MovPaddingControl enum value @@ -22102,6 +24992,14 @@ const ( MovPaddingControlNone = "NONE" ) +// MovPaddingControl_Values returns all elements of the MovPaddingControl enum +func MovPaddingControl_Values() []string { + return []string{ + MovPaddingControlOmneon, + MovPaddingControlNone, + } +} + // Always keep the default value (SELF_CONTAINED) for this setting. const ( // MovReferenceSelfContained is a MovReference enum value @@ -22111,6 +25009,14 @@ const ( MovReferenceExternal = "EXTERNAL" ) +// MovReference_Values returns all elements of the MovReference enum +func MovReference_Values() []string { + return []string{ + MovReferenceSelfContained, + MovReferenceExternal, + } +} + // Specify whether the service encodes this MP3 audio output with a constant // bitrate (CBR) or a variable bitrate (VBR). const ( @@ -22121,6 +25027,14 @@ const ( Mp3RateControlModeVbr = "VBR" ) +// Mp3RateControlMode_Values returns all elements of the Mp3RateControlMode enum +func Mp3RateControlMode_Values() []string { + return []string{ + Mp3RateControlModeCbr, + Mp3RateControlModeVbr, + } +} + // When enabled, file composition times will start at zero, composition times // in the 'ctts' (composition time to sample) box for B-frames will be negative, // and a 'cslg' (composition shift least greatest) box will be included per @@ -22133,6 +25047,14 @@ const ( Mp4CslgAtomExclude = "EXCLUDE" ) +// Mp4CslgAtom_Values returns all elements of the Mp4CslgAtom enum +func Mp4CslgAtom_Values() []string { + return []string{ + Mp4CslgAtomInclude, + Mp4CslgAtomExclude, + } +} + // Inserts a free-space box immediately after the moov box. const ( // Mp4FreeSpaceBoxInclude is a Mp4FreeSpaceBox enum value @@ -22142,6 +25064,14 @@ const ( Mp4FreeSpaceBoxExclude = "EXCLUDE" ) +// Mp4FreeSpaceBox_Values returns all elements of the Mp4FreeSpaceBox enum +func Mp4FreeSpaceBox_Values() []string { + return []string{ + Mp4FreeSpaceBoxInclude, + Mp4FreeSpaceBoxExclude, + } +} + // If set to PROGRESSIVE_DOWNLOAD, the MOOV atom is relocated to the beginning // of the archive as required for progressive downloading. Otherwise it is placed // normally at the end. @@ -22153,6 +25083,14 @@ const ( Mp4MoovPlacementNormal = "NORMAL" ) +// Mp4MoovPlacement_Values returns all elements of the Mp4MoovPlacement enum +func Mp4MoovPlacement_Values() []string { + return []string{ + Mp4MoovPlacementProgressiveDownload, + Mp4MoovPlacementNormal, + } +} + // Use this setting only in DASH output groups that include sidecar TTML or // IMSC captions. You specify sidecar captions in a separate output from your // audio and video. Choose Raw (RAW) for captions in a single XML file in a @@ -22167,6 +25105,14 @@ const ( MpdCaptionContainerTypeFragmentedMp4 = "FRAGMENTED_MP4" ) +// MpdCaptionContainerType_Values returns all elements of the MpdCaptionContainerType enum +func MpdCaptionContainerType_Values() []string { + return []string{ + MpdCaptionContainerTypeRaw, + MpdCaptionContainerTypeFragmentedMp4, + } +} + // Use this setting only when you specify SCTE-35 markers from ESAM. Choose // INSERT to put SCTE-35 markers in this output at the insertion points that // you specify in an ESAM XML document. Provide the document in the setting @@ -22179,6 +25125,14 @@ const ( MpdScte35EsamNone = "NONE" ) +// MpdScte35Esam_Values returns all elements of the MpdScte35Esam enum +func MpdScte35Esam_Values() []string { + return []string{ + MpdScte35EsamInsert, + MpdScte35EsamNone, + } +} + // Ignore this setting unless you have SCTE-35 markers in your input video file. // Choose Passthrough (PASSTHROUGH) if you want SCTE-35 markers that appear // in your input to also appear in this output. Choose None (NONE) if you don't @@ -22191,6 +25145,14 @@ const ( MpdScte35SourceNone = "NONE" ) +// MpdScte35Source_Values returns all elements of the MpdScte35Source enum +func MpdScte35Source_Values() []string { + return []string{ + MpdScte35SourcePassthrough, + MpdScte35SourceNone, + } +} + // Adaptive quantization. Allows intra-frame quantizers to vary to improve visual // quality. const ( @@ -22207,6 +25169,16 @@ const ( Mpeg2AdaptiveQuantizationHigh = "HIGH" ) +// Mpeg2AdaptiveQuantization_Values returns all elements of the Mpeg2AdaptiveQuantization enum +func Mpeg2AdaptiveQuantization_Values() []string { + return []string{ + Mpeg2AdaptiveQuantizationOff, + Mpeg2AdaptiveQuantizationLow, + Mpeg2AdaptiveQuantizationMedium, + Mpeg2AdaptiveQuantizationHigh, + } +} + // Use Level (Mpeg2CodecLevel) to set the MPEG-2 level for the video output. const ( // Mpeg2CodecLevelAuto is a Mpeg2CodecLevel enum value @@ -22225,6 +25197,17 @@ const ( Mpeg2CodecLevelHigh = "HIGH" ) +// Mpeg2CodecLevel_Values returns all elements of the Mpeg2CodecLevel enum +func Mpeg2CodecLevel_Values() []string { + return []string{ + Mpeg2CodecLevelAuto, + Mpeg2CodecLevelLow, + Mpeg2CodecLevelMain, + Mpeg2CodecLevelHigh1440, + Mpeg2CodecLevelHigh, + } +} + // Use Profile (Mpeg2CodecProfile) to set the MPEG-2 profile for the video output. const ( // Mpeg2CodecProfileMain is a Mpeg2CodecProfile enum value @@ -22234,6 +25217,14 @@ const ( Mpeg2CodecProfileProfile422 = "PROFILE_422" ) +// Mpeg2CodecProfile_Values returns all elements of the Mpeg2CodecProfile enum +func Mpeg2CodecProfile_Values() []string { + return []string{ + Mpeg2CodecProfileMain, + Mpeg2CodecProfileProfile422, + } +} + // Choose Adaptive to improve subjective video quality for high-motion content. // This will cause the service to use fewer B-frames (which infer information // based on other frames) for high-motion portions of the video and more B-frames @@ -22247,13 +25238,21 @@ const ( Mpeg2DynamicSubGopStatic = "STATIC" ) +// Mpeg2DynamicSubGop_Values returns all elements of the Mpeg2DynamicSubGop enum +func Mpeg2DynamicSubGop_Values() []string { + return []string{ + Mpeg2DynamicSubGopAdaptive, + Mpeg2DynamicSubGopStatic, + } +} + // If you are using the console, use the Framerate setting to specify the frame // rate for this output. If you want to keep the same frame rate as the input // video, choose Follow source. If you want to do frame rate conversion, choose // a frame rate from the dropdown list or choose Custom. The framerates shown // in the dropdown list are decimal approximations of fractions. If you choose // Custom, specify your frame rate as a fraction. If you are creating your transcoding -// job sepecification as a JSON file without the console, use FramerateControl +// job specification as a JSON file without the console, use FramerateControl // to specify which value the service uses for the frame rate for this output. // Choose INITIALIZE_FROM_SOURCE if you want the service to use the frame rate // from the input. Choose SPECIFIED if you want the service to use the frame @@ -22266,7 +25265,16 @@ const ( Mpeg2FramerateControlSpecified = "SPECIFIED" ) -// When set to INTERPOLATE, produces smoother motion during frame rate conversion. +// Mpeg2FramerateControl_Values returns all elements of the Mpeg2FramerateControl enum +func Mpeg2FramerateControl_Values() []string { + return []string{ + Mpeg2FramerateControlInitializeFromSource, + Mpeg2FramerateControlSpecified, + } +} + +// Optional. Specify how the transcoder performs framerate conversion. The default +// behavior is to use duplicate drop conversion. const ( // Mpeg2FramerateConversionAlgorithmDuplicateDrop is a Mpeg2FramerateConversionAlgorithm enum value Mpeg2FramerateConversionAlgorithmDuplicateDrop = "DUPLICATE_DROP" @@ -22275,6 +25283,14 @@ const ( Mpeg2FramerateConversionAlgorithmInterpolate = "INTERPOLATE" ) +// Mpeg2FramerateConversionAlgorithm_Values returns all elements of the Mpeg2FramerateConversionAlgorithm enum +func Mpeg2FramerateConversionAlgorithm_Values() []string { + return []string{ + Mpeg2FramerateConversionAlgorithmDuplicateDrop, + Mpeg2FramerateConversionAlgorithmInterpolate, + } +} + // Indicates if the GOP Size in MPEG2 is specified in frames or seconds. If // seconds the system will convert the GOP Size into a frame count at run time. const ( @@ -22285,6 +25301,14 @@ const ( Mpeg2GopSizeUnitsSeconds = "SECONDS" ) +// Mpeg2GopSizeUnits_Values returns all elements of the Mpeg2GopSizeUnits enum +func Mpeg2GopSizeUnits_Values() []string { + return []string{ + Mpeg2GopSizeUnitsFrames, + Mpeg2GopSizeUnitsSeconds, + } +} + // Use Interlace mode (InterlaceMode) to choose the scan line type for the output. // * Top Field First (TOP_FIELD) and Bottom Field First (BOTTOM_FIELD) produce // interlaced output with the entire output having the same field polarity (top @@ -22313,6 +25337,17 @@ const ( Mpeg2InterlaceModeFollowBottomField = "FOLLOW_BOTTOM_FIELD" ) +// Mpeg2InterlaceMode_Values returns all elements of the Mpeg2InterlaceMode enum +func Mpeg2InterlaceMode_Values() []string { + return []string{ + Mpeg2InterlaceModeProgressive, + Mpeg2InterlaceModeTopField, + Mpeg2InterlaceModeBottomField, + Mpeg2InterlaceModeFollowTopField, + Mpeg2InterlaceModeFollowBottomField, + } +} + // Use Intra DC precision (Mpeg2IntraDcPrecision) to set quantization precision // for intra-block DC coefficients. If you choose the value auto, the service // will automatically select the precision based on the per-frame compression @@ -22334,9 +25369,24 @@ const ( Mpeg2IntraDcPrecisionIntraDcPrecision11 = "INTRA_DC_PRECISION_11" ) -// Using the API, enable ParFollowSource if you want the service to use the -// pixel aspect ratio from the input. Using the console, do this by choosing -// Follow source for Pixel aspect ratio. +// Mpeg2IntraDcPrecision_Values returns all elements of the Mpeg2IntraDcPrecision enum +func Mpeg2IntraDcPrecision_Values() []string { + return []string{ + Mpeg2IntraDcPrecisionAuto, + Mpeg2IntraDcPrecisionIntraDcPrecision8, + Mpeg2IntraDcPrecisionIntraDcPrecision9, + Mpeg2IntraDcPrecisionIntraDcPrecision10, + Mpeg2IntraDcPrecisionIntraDcPrecision11, + } +} + +// Optional. Specify how the service determines the pixel aspect ratio (PAR) +// for this output. The default behavior, Follow source (INITIALIZE_FROM_SOURCE), +// uses the PAR from your input video for your output. To specify a different +// PAR in the console, choose any value other than Follow source. To specify +// a different PAR by editing the JSON job specification, choose SPECIFIED. +// When you choose SPECIFIED for this setting, you must also specify values +// for the parNumerator and parDenominator settings. const ( // Mpeg2ParControlInitializeFromSource is a Mpeg2ParControl enum value Mpeg2ParControlInitializeFromSource = "INITIALIZE_FROM_SOURCE" @@ -22345,8 +25395,17 @@ const ( Mpeg2ParControlSpecified = "SPECIFIED" ) -// Use Quality tuning level (Mpeg2QualityTuningLevel) to specifiy whether to -// use single-pass or multipass video encoding. +// Mpeg2ParControl_Values returns all elements of the Mpeg2ParControl enum +func Mpeg2ParControl_Values() []string { + return []string{ + Mpeg2ParControlInitializeFromSource, + Mpeg2ParControlSpecified, + } +} + +// Optional. Use Quality tuning level (qualityTuningLevel) to choose how you +// want to trade off encoding speed for output video quality. The default behavior +// is faster, lower quality, single-pass encoding. const ( // Mpeg2QualityTuningLevelSinglePass is a Mpeg2QualityTuningLevel enum value Mpeg2QualityTuningLevelSinglePass = "SINGLE_PASS" @@ -22355,6 +25414,14 @@ const ( Mpeg2QualityTuningLevelMultiPass = "MULTI_PASS" ) +// Mpeg2QualityTuningLevel_Values returns all elements of the Mpeg2QualityTuningLevel enum +func Mpeg2QualityTuningLevel_Values() []string { + return []string{ + Mpeg2QualityTuningLevelSinglePass, + Mpeg2QualityTuningLevelMultiPass, + } +} + // Use Rate control mode (Mpeg2RateControlMode) to specifiy whether the bitrate // is variable (vbr) or constant (cbr). const ( @@ -22365,6 +25432,14 @@ const ( Mpeg2RateControlModeCbr = "CBR" ) +// Mpeg2RateControlMode_Values returns all elements of the Mpeg2RateControlMode enum +func Mpeg2RateControlMode_Values() []string { + return []string{ + Mpeg2RateControlModeVbr, + Mpeg2RateControlModeCbr, + } +} + // Enable this setting to insert I-frames at scene changes that the service // automatically detects. This improves video quality and is enabled by default. const ( @@ -22375,6 +25450,14 @@ const ( Mpeg2SceneChangeDetectEnabled = "ENABLED" ) +// Mpeg2SceneChangeDetect_Values returns all elements of the Mpeg2SceneChangeDetect enum +func Mpeg2SceneChangeDetect_Values() []string { + return []string{ + Mpeg2SceneChangeDetectDisabled, + Mpeg2SceneChangeDetectEnabled, + } +} + // Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled // as 25fps, and audio is sped up correspondingly. const ( @@ -22385,6 +25468,14 @@ const ( Mpeg2SlowPalEnabled = "ENABLED" ) +// Mpeg2SlowPal_Values returns all elements of the Mpeg2SlowPal enum +func Mpeg2SlowPal_Values() []string { + return []string{ + Mpeg2SlowPalDisabled, + Mpeg2SlowPalEnabled, + } +} + // Adjust quantization within each frame based on spatial variation of content // complexity. const ( @@ -22395,6 +25486,14 @@ const ( Mpeg2SpatialAdaptiveQuantizationEnabled = "ENABLED" ) +// Mpeg2SpatialAdaptiveQuantization_Values returns all elements of the Mpeg2SpatialAdaptiveQuantization enum +func Mpeg2SpatialAdaptiveQuantization_Values() []string { + return []string{ + Mpeg2SpatialAdaptiveQuantizationDisabled, + Mpeg2SpatialAdaptiveQuantizationEnabled, + } +} + // Produces a Type D-10 compatible bitstream (SMPTE 356M-2001). const ( // Mpeg2SyntaxDefault is a Mpeg2Syntax enum value @@ -22404,6 +25503,14 @@ const ( Mpeg2SyntaxD10 = "D_10" ) +// Mpeg2Syntax_Values returns all elements of the Mpeg2Syntax enum +func Mpeg2Syntax_Values() []string { + return []string{ + Mpeg2SyntaxDefault, + Mpeg2SyntaxD10, + } +} + // Only use Telecine (Mpeg2Telecine) when you set Framerate (Framerate) to 29.970. // Set Telecine (Mpeg2Telecine) to Hard (hard) to produce a 29.97i output from // a 23.976 input. Set it to Soft (soft) to produce 23.976 output and leave @@ -22419,6 +25526,15 @@ const ( Mpeg2TelecineHard = "HARD" ) +// Mpeg2Telecine_Values returns all elements of the Mpeg2Telecine enum +func Mpeg2Telecine_Values() []string { + return []string{ + Mpeg2TelecineNone, + Mpeg2TelecineSoft, + Mpeg2TelecineHard, + } +} + // Adjust quantization within each frame based on temporal variation of content // complexity. const ( @@ -22429,6 +25545,14 @@ const ( Mpeg2TemporalAdaptiveQuantizationEnabled = "ENABLED" ) +// Mpeg2TemporalAdaptiveQuantization_Values returns all elements of the Mpeg2TemporalAdaptiveQuantization enum +func Mpeg2TemporalAdaptiveQuantization_Values() []string { + return []string{ + Mpeg2TemporalAdaptiveQuantizationDisabled, + Mpeg2TemporalAdaptiveQuantizationEnabled, + } +} + // COMBINE_DUPLICATE_STREAMS combines identical audio encoding settings across // a Microsoft Smooth output group into a single audio stream. const ( @@ -22439,6 +25563,14 @@ const ( MsSmoothAudioDeduplicationNone = "NONE" ) +// MsSmoothAudioDeduplication_Values returns all elements of the MsSmoothAudioDeduplication enum +func MsSmoothAudioDeduplication_Values() []string { + return []string{ + MsSmoothAudioDeduplicationCombineDuplicateStreams, + MsSmoothAudioDeduplicationNone, + } +} + // Use Manifest encoding (MsSmoothManifestEncoding) to specify the encoding // format for the server and client manifest. Valid options are utf8 and utf16. const ( @@ -22449,6 +25581,14 @@ const ( MsSmoothManifestEncodingUtf16 = "UTF16" ) +// MsSmoothManifestEncoding_Values returns all elements of the MsSmoothManifestEncoding enum +func MsSmoothManifestEncoding_Values() []string { + return []string{ + MsSmoothManifestEncodingUtf8, + MsSmoothManifestEncodingUtf16, + } +} + // Optional. When you have AFD signaling set up in your output video stream, // use this setting to choose whether to also include it in the MXF wrapper. // Choose Don't copy (NO_COPY) to exclude AFD signaling from the MXF wrapper. @@ -22466,6 +25606,38 @@ const ( MxfAfdSignalingCopyFromVideo = "COPY_FROM_VIDEO" ) +// MxfAfdSignaling_Values returns all elements of the MxfAfdSignaling enum +func MxfAfdSignaling_Values() []string { + return []string{ + MxfAfdSignalingNoCopy, + MxfAfdSignalingCopyFromVideo, + } +} + +// Optional. When you set Noise reducer (noiseReducer) to Temporal (TEMPORAL), +// you can optionally use this setting to apply additional sharpening. The default +// behavior, Auto (AUTO) allows the transcoder to determine whether to apply +// filtering, depending on input type and quality. +const ( + // NoiseFilterPostTemporalSharpeningDisabled is a NoiseFilterPostTemporalSharpening enum value + NoiseFilterPostTemporalSharpeningDisabled = "DISABLED" + + // NoiseFilterPostTemporalSharpeningEnabled is a NoiseFilterPostTemporalSharpening enum value + NoiseFilterPostTemporalSharpeningEnabled = "ENABLED" + + // NoiseFilterPostTemporalSharpeningAuto is a NoiseFilterPostTemporalSharpening enum value + NoiseFilterPostTemporalSharpeningAuto = "AUTO" +) + +// NoiseFilterPostTemporalSharpening_Values returns all elements of the NoiseFilterPostTemporalSharpening enum +func NoiseFilterPostTemporalSharpening_Values() []string { + return []string{ + NoiseFilterPostTemporalSharpeningDisabled, + NoiseFilterPostTemporalSharpeningEnabled, + NoiseFilterPostTemporalSharpeningAuto, + } +} + // Use Noise reducer filter (NoiseReducerFilter) to select one of the following // spatial image filtering functions. To use this setting, you must also enable // Noise reducer (NoiseReducer). * Bilateral preserves edges while reducing @@ -22499,6 +25671,20 @@ const ( NoiseReducerFilterTemporal = "TEMPORAL" ) +// NoiseReducerFilter_Values returns all elements of the NoiseReducerFilter enum +func NoiseReducerFilter_Values() []string { + return []string{ + NoiseReducerFilterBilateral, + NoiseReducerFilterMean, + NoiseReducerFilterGaussian, + NoiseReducerFilterLanczos, + NoiseReducerFilterSharpen, + NoiseReducerFilterConserve, + NoiseReducerFilterSpatial, + NoiseReducerFilterTemporal, + } +} + // Optional. When you request lists of resources, you can specify whether they // are sorted in ASCENDING or DESCENDING order. Default varies by resource. const ( @@ -22509,6 +25695,14 @@ const ( OrderDescending = "DESCENDING" ) +// Order_Values returns all elements of the Order enum +func Order_Values() []string { + return []string{ + OrderAscending, + OrderDescending, + } +} + // Type of output group (File group, Apple HLS, DASH ISO, Microsoft Smooth Streaming, // CMAF) const ( @@ -22528,6 +25722,17 @@ const ( OutputGroupTypeCmafGroupSettings = "CMAF_GROUP_SETTINGS" ) +// OutputGroupType_Values returns all elements of the OutputGroupType enum +func OutputGroupType_Values() []string { + return []string{ + OutputGroupTypeHlsGroupSettings, + OutputGroupTypeDashIsoGroupSettings, + OutputGroupTypeFileGroupSettings, + OutputGroupTypeMsSmoothGroupSettings, + OutputGroupTypeCmafGroupSettings, + } +} + // Selects method of inserting SDT information into output stream. "Follow input // SDT" copies SDT information from input stream to output stream. "Follow input // SDT if present" copies SDT information from input stream to output stream @@ -22548,6 +25753,16 @@ const ( OutputSdtSdtNone = "SDT_NONE" ) +// OutputSdt_Values returns all elements of the OutputSdt enum +func OutputSdt_Values() []string { + return []string{ + OutputSdtSdtFollow, + OutputSdtSdtFollowIfPresent, + OutputSdtSdtManual, + OutputSdtSdtNone, + } +} + // Optional. When you request a list of presets, you can choose to list them // alphabetically by NAME or chronologically by CREATION_DATE. If you don't // specify, the service will list them by name. @@ -22562,6 +25777,15 @@ const ( PresetListBySystem = "SYSTEM" ) +// PresetListBy_Values returns all elements of the PresetListBy enum +func PresetListBy_Values() []string { + return []string{ + PresetListByName, + PresetListByCreationDate, + PresetListBySystem, + } +} + // Specifies whether the pricing plan for the queue is on-demand or reserved. // For on-demand, you pay per minute, billed in increments of .01 minute. For // reserved, you pay for the transcoding capacity of the entire queue, regardless @@ -22575,6 +25799,14 @@ const ( PricingPlanReserved = "RESERVED" ) +// PricingPlan_Values returns all elements of the PricingPlan enum +func PricingPlan_Values() []string { + return []string{ + PricingPlanOnDemand, + PricingPlanReserved, + } +} + // Use Profile (ProResCodecProfile) to specifiy the type of Apple ProRes codec // to use for this output. const ( @@ -22591,13 +25823,23 @@ const ( ProresCodecProfileAppleProres422Proxy = "APPLE_PRORES_422_PROXY" ) +// ProresCodecProfile_Values returns all elements of the ProresCodecProfile enum +func ProresCodecProfile_Values() []string { + return []string{ + ProresCodecProfileAppleProres422, + ProresCodecProfileAppleProres422Hq, + ProresCodecProfileAppleProres422Lt, + ProresCodecProfileAppleProres422Proxy, + } +} + // If you are using the console, use the Framerate setting to specify the frame // rate for this output. If you want to keep the same frame rate as the input // video, choose Follow source. If you want to do frame rate conversion, choose // a frame rate from the dropdown list or choose Custom. The framerates shown // in the dropdown list are decimal approximations of fractions. If you choose // Custom, specify your frame rate as a fraction. If you are creating your transcoding -// job sepecification as a JSON file without the console, use FramerateControl +// job specification as a JSON file without the console, use FramerateControl // to specify which value the service uses for the frame rate for this output. // Choose INITIALIZE_FROM_SOURCE if you want the service to use the frame rate // from the input. Choose SPECIFIED if you want the service to use the frame @@ -22610,7 +25852,16 @@ const ( ProresFramerateControlSpecified = "SPECIFIED" ) -// When set to INTERPOLATE, produces smoother motion during frame rate conversion. +// ProresFramerateControl_Values returns all elements of the ProresFramerateControl enum +func ProresFramerateControl_Values() []string { + return []string{ + ProresFramerateControlInitializeFromSource, + ProresFramerateControlSpecified, + } +} + +// Optional. Specify how the transcoder performs framerate conversion. The default +// behavior is to use duplicate drop conversion. const ( // ProresFramerateConversionAlgorithmDuplicateDrop is a ProresFramerateConversionAlgorithm enum value ProresFramerateConversionAlgorithmDuplicateDrop = "DUPLICATE_DROP" @@ -22619,6 +25870,14 @@ const ( ProresFramerateConversionAlgorithmInterpolate = "INTERPOLATE" ) +// ProresFramerateConversionAlgorithm_Values returns all elements of the ProresFramerateConversionAlgorithm enum +func ProresFramerateConversionAlgorithm_Values() []string { + return []string{ + ProresFramerateConversionAlgorithmDuplicateDrop, + ProresFramerateConversionAlgorithmInterpolate, + } +} + // Use Interlace mode (InterlaceMode) to choose the scan line type for the output. // * Top Field First (TOP_FIELD) and Bottom Field First (BOTTOM_FIELD) produce // interlaced output with the entire output having the same field polarity (top @@ -22647,11 +25906,24 @@ const ( ProresInterlaceModeFollowBottomField = "FOLLOW_BOTTOM_FIELD" ) -// Use (ProresParControl) to specify how the service determines the pixel aspect -// ratio. Set to Follow source (INITIALIZE_FROM_SOURCE) to use the pixel aspect -// ratio from the input. To specify a different pixel aspect ratio: Using the -// console, choose it from the dropdown menu. Using the API, set ProresParControl -// to (SPECIFIED) and provide for (ParNumerator) and (ParDenominator). +// ProresInterlaceMode_Values returns all elements of the ProresInterlaceMode enum +func ProresInterlaceMode_Values() []string { + return []string{ + ProresInterlaceModeProgressive, + ProresInterlaceModeTopField, + ProresInterlaceModeBottomField, + ProresInterlaceModeFollowTopField, + ProresInterlaceModeFollowBottomField, + } +} + +// Optional. Specify how the service determines the pixel aspect ratio (PAR) +// for this output. The default behavior, Follow source (INITIALIZE_FROM_SOURCE), +// uses the PAR from your input video for your output. To specify a different +// PAR in the console, choose any value other than Follow source. To specify +// a different PAR by editing the JSON job specification, choose SPECIFIED. +// When you choose SPECIFIED for this setting, you must also specify values +// for the parNumerator and parDenominator settings. const ( // ProresParControlInitializeFromSource is a ProresParControl enum value ProresParControlInitializeFromSource = "INITIALIZE_FROM_SOURCE" @@ -22660,6 +25932,14 @@ const ( ProresParControlSpecified = "SPECIFIED" ) +// ProresParControl_Values returns all elements of the ProresParControl enum +func ProresParControl_Values() []string { + return []string{ + ProresParControlInitializeFromSource, + ProresParControlSpecified, + } +} + // Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled // as 25fps, and audio is sped up correspondingly. const ( @@ -22670,6 +25950,14 @@ const ( ProresSlowPalEnabled = "ENABLED" ) +// ProresSlowPal_Values returns all elements of the ProresSlowPal enum +func ProresSlowPal_Values() []string { + return []string{ + ProresSlowPalDisabled, + ProresSlowPalEnabled, + } +} + // Only use Telecine (ProresTelecine) when you set Framerate (Framerate) to // 29.970. Set Telecine (ProresTelecine) to Hard (hard) to produce a 29.97i // output from a 23.976 input. Set it to Soft (soft) to produce 23.976 output @@ -22682,6 +25970,14 @@ const ( ProresTelecineHard = "HARD" ) +// ProresTelecine_Values returns all elements of the ProresTelecine enum +func ProresTelecine_Values() []string { + return []string{ + ProresTelecineNone, + ProresTelecineHard, + } +} + // Optional. When you request a list of queues, you can choose to list them // alphabetically by NAME or chronologically by CREATION_DATE. If you don't // specify, the service will list them by creation date. @@ -22693,6 +25989,14 @@ const ( QueueListByCreationDate = "CREATION_DATE" ) +// QueueListBy_Values returns all elements of the QueueListBy enum +func QueueListBy_Values() []string { + return []string{ + QueueListByName, + QueueListByCreationDate, + } +} + // Queues can be ACTIVE or PAUSED. If you pause a queue, jobs in that queue // won't begin. Jobs that are running when you pause a queue continue to run // until they finish or result in an error. @@ -22704,6 +26008,14 @@ const ( QueueStatusPaused = "PAUSED" ) +// QueueStatus_Values returns all elements of the QueueStatus enum +func QueueStatus_Values() []string { + return []string{ + QueueStatusActive, + QueueStatusPaused, + } +} + // Specifies whether the term of your reserved queue pricing plan is automatically // extended (AUTO_RENEW) or expires (EXPIRE) at the end of the term. const ( @@ -22714,6 +26026,14 @@ const ( RenewalTypeExpire = "EXPIRE" ) +// RenewalType_Values returns all elements of the RenewalType enum +func RenewalType_Values() []string { + return []string{ + RenewalTypeAutoRenew, + RenewalTypeExpire, + } +} + // Specifies whether the pricing plan for your reserved queue is ACTIVE or EXPIRED. const ( // ReservationPlanStatusActive is a ReservationPlanStatus enum value @@ -22723,6 +26043,14 @@ const ( ReservationPlanStatusExpired = "EXPIRED" ) +// ReservationPlanStatus_Values returns all elements of the ReservationPlanStatus enum +func ReservationPlanStatus_Values() []string { + return []string{ + ReservationPlanStatusActive, + ReservationPlanStatusExpired, + } +} + // Use Respond to AFD (RespondToAfd) to specify how the service changes the // video itself in response to AFD values in the input. * Choose Respond to // clip the input video frame according to the AFD value, input display aspect @@ -22742,6 +26070,15 @@ const ( RespondToAfdPassthrough = "PASSTHROUGH" ) +// RespondToAfd_Values returns all elements of the RespondToAfd enum +func RespondToAfd_Values() []string { + return []string{ + RespondToAfdNone, + RespondToAfdRespond, + RespondToAfdPassthrough, + } +} + // Choose an Amazon S3 canned ACL for MediaConvert to apply to this output. const ( // S3ObjectCannedAclPublicRead is a S3ObjectCannedAcl enum value @@ -22757,6 +26094,16 @@ const ( S3ObjectCannedAclBucketOwnerFullControl = "BUCKET_OWNER_FULL_CONTROL" ) +// S3ObjectCannedAcl_Values returns all elements of the S3ObjectCannedAcl enum +func S3ObjectCannedAcl_Values() []string { + return []string{ + S3ObjectCannedAclPublicRead, + S3ObjectCannedAclAuthenticatedRead, + S3ObjectCannedAclBucketOwnerRead, + S3ObjectCannedAclBucketOwnerFullControl, + } +} + // Specify how you want your data keys managed. AWS uses data keys to encrypt // your content. AWS also encrypts the data keys themselves, using a customer // master key (CMK), and then stores the encrypted data keys alongside your @@ -22776,6 +26123,14 @@ const ( S3ServerSideEncryptionTypeServerSideEncryptionKms = "SERVER_SIDE_ENCRYPTION_KMS" ) +// S3ServerSideEncryptionType_Values returns all elements of the S3ServerSideEncryptionType enum +func S3ServerSideEncryptionType_Values() []string { + return []string{ + S3ServerSideEncryptionTypeServerSideEncryptionS3, + S3ServerSideEncryptionTypeServerSideEncryptionKms, + } +} + // Specify how the service handles outputs that have a different aspect ratio // from the input aspect ratio. Choose Stretch to output (STRETCH_TO_OUTPUT) // to have the service stretch your video image to fit. Keep the setting Default @@ -22790,6 +26145,14 @@ const ( ScalingBehaviorStretchToOutput = "STRETCH_TO_OUTPUT" ) +// ScalingBehavior_Values returns all elements of the ScalingBehavior enum +func ScalingBehavior_Values() []string { + return []string{ + ScalingBehaviorDefault, + ScalingBehaviorStretchToOutput, + } +} + // Set Framerate (SccDestinationFramerate) to make sure that the captions and // the video are synchronized in the output. Specify a frame rate that matches // the frame rate of the associated video. If the video frame rate is 29.97, @@ -22813,6 +26176,17 @@ const ( SccDestinationFramerateFramerate2997NonDropframe = "FRAMERATE_29_97_NON_DROPFRAME" ) +// SccDestinationFramerate_Values returns all elements of the SccDestinationFramerate enum +func SccDestinationFramerate_Values() []string { + return []string{ + SccDestinationFramerateFramerate2397, + SccDestinationFramerateFramerate24, + SccDestinationFramerateFramerate25, + SccDestinationFramerateFramerate2997Dropframe, + SccDestinationFramerateFramerate2997NonDropframe, + } +} + // Enable this setting when you run a test job to estimate how many reserved // transcoding slots (RTS) you need. When this is enabled, MediaConvert runs // your job from an on-demand queue with similar performance to what you will @@ -22825,6 +26199,14 @@ const ( SimulateReservedQueueEnabled = "ENABLED" ) +// SimulateReservedQueue_Values returns all elements of the SimulateReservedQueue enum +func SimulateReservedQueue_Values() []string { + return []string{ + SimulateReservedQueueDisabled, + SimulateReservedQueueEnabled, + } +} + // Specify how often MediaConvert sends STATUS_UPDATE events to Amazon CloudWatch // Events. Set the interval, in seconds, between status updates. MediaConvert // sends an update at this interval from the time the service begins processing @@ -22876,6 +26258,27 @@ const ( StatusUpdateIntervalSeconds600 = "SECONDS_600" ) +// StatusUpdateInterval_Values returns all elements of the StatusUpdateInterval enum +func StatusUpdateInterval_Values() []string { + return []string{ + StatusUpdateIntervalSeconds10, + StatusUpdateIntervalSeconds12, + StatusUpdateIntervalSeconds15, + StatusUpdateIntervalSeconds20, + StatusUpdateIntervalSeconds30, + StatusUpdateIntervalSeconds60, + StatusUpdateIntervalSeconds120, + StatusUpdateIntervalSeconds180, + StatusUpdateIntervalSeconds240, + StatusUpdateIntervalSeconds300, + StatusUpdateIntervalSeconds360, + StatusUpdateIntervalSeconds420, + StatusUpdateIntervalSeconds480, + StatusUpdateIntervalSeconds540, + StatusUpdateIntervalSeconds600, + } +} + // A page type as defined in the standard ETSI EN 300 468, Table 94 const ( // TeletextPageTypePageTypeInitial is a TeletextPageType enum value @@ -22894,6 +26297,17 @@ const ( TeletextPageTypePageTypeHearingImpairedSubtitle = "PAGE_TYPE_HEARING_IMPAIRED_SUBTITLE" ) +// TeletextPageType_Values returns all elements of the TeletextPageType enum +func TeletextPageType_Values() []string { + return []string{ + TeletextPageTypePageTypeInitial, + TeletextPageTypePageTypeSubtitle, + TeletextPageTypePageTypeAddlInfo, + TeletextPageTypePageTypeProgramSchedule, + TeletextPageTypePageTypeHearingImpairedSubtitle, + } +} + // Use Position (Position) under under Timecode burn-in (TimecodeBurnIn) to // specify the location the burned-in timecode on output video. const ( @@ -22925,6 +26339,21 @@ const ( TimecodeBurninPositionBottomRight = "BOTTOM_RIGHT" ) +// TimecodeBurninPosition_Values returns all elements of the TimecodeBurninPosition enum +func TimecodeBurninPosition_Values() []string { + return []string{ + TimecodeBurninPositionTopCenter, + TimecodeBurninPositionTopLeft, + TimecodeBurninPositionTopRight, + TimecodeBurninPositionMiddleLeft, + TimecodeBurninPositionMiddleCenter, + TimecodeBurninPositionMiddleRight, + TimecodeBurninPositionBottomLeft, + TimecodeBurninPositionBottomCenter, + TimecodeBurninPositionBottomRight, + } +} + // Use Source (TimecodeSource) to set how timecodes are handled within this // job. To make sure that your video, audio, captions, and markers are synchronized // and that time-based features, such as image inserter, work correctly, choose @@ -22947,6 +26376,15 @@ const ( TimecodeSourceSpecifiedstart = "SPECIFIEDSTART" ) +// TimecodeSource_Values returns all elements of the TimecodeSource enum +func TimecodeSource_Values() []string { + return []string{ + TimecodeSourceEmbedded, + TimecodeSourceZerobased, + TimecodeSourceSpecifiedstart, + } +} + // Applies only to HLS outputs. Use this setting to specify whether the service // inserts the ID3 timed metadata from the input in this output. const ( @@ -22957,6 +26395,14 @@ const ( TimedMetadataNone = "NONE" ) +// TimedMetadata_Values returns all elements of the TimedMetadata enum +func TimedMetadata_Values() []string { + return []string{ + TimedMetadataPassthrough, + TimedMetadataNone, + } +} + // Pass through style and position information from a TTML-like input source // (TTML, SMPTE-TT) to the TTML output. const ( @@ -22967,6 +26413,14 @@ const ( TtmlStylePassthroughDisabled = "DISABLED" ) +// TtmlStylePassthrough_Values returns all elements of the TtmlStylePassthrough enum +func TtmlStylePassthrough_Values() []string { + return []string{ + TtmlStylePassthroughEnabled, + TtmlStylePassthroughDisabled, + } +} + const ( // TypeSystem is a Type enum value TypeSystem = "SYSTEM" @@ -22975,6 +26429,14 @@ const ( TypeCustom = "CUSTOM" ) +// Type_Values returns all elements of the Type enum +func Type_Values() []string { + return []string{ + TypeSystem, + TypeCustom, + } +} + // Type of video codec const ( // VideoCodecFrameCapture is a VideoCodec enum value @@ -22994,8 +26456,28 @@ const ( // VideoCodecProres is a VideoCodec enum value VideoCodecProres = "PRORES" + + // VideoCodecVp8 is a VideoCodec enum value + VideoCodecVp8 = "VP8" + + // VideoCodecVp9 is a VideoCodec enum value + VideoCodecVp9 = "VP9" ) +// VideoCodec_Values returns all elements of the VideoCodec enum +func VideoCodec_Values() []string { + return []string{ + VideoCodecFrameCapture, + VideoCodecAv1, + VideoCodecH264, + VideoCodecH265, + VideoCodecMpeg2, + VideoCodecProres, + VideoCodecVp8, + VideoCodecVp9, + } +} + // Applies only to H.264, H.265, MPEG2, and ProRes outputs. Only enable Timecode // insertion when the input frame rate is identical to the output frame rate. // To include timecodes in this output, set Timecode insertion (VideoTimecodeInsertion) @@ -23016,6 +26498,249 @@ const ( VideoTimecodeInsertionPicTimingSei = "PIC_TIMING_SEI" ) +// VideoTimecodeInsertion_Values returns all elements of the VideoTimecodeInsertion enum +func VideoTimecodeInsertion_Values() []string { + return []string{ + VideoTimecodeInsertionDisabled, + VideoTimecodeInsertionPicTimingSei, + } +} + +// If you are using the console, use the Framerate setting to specify the frame +// rate for this output. If you want to keep the same frame rate as the input +// video, choose Follow source. If you want to do frame rate conversion, choose +// a frame rate from the dropdown list or choose Custom. The framerates shown +// in the dropdown list are decimal approximations of fractions. If you choose +// Custom, specify your frame rate as a fraction. If you are creating your transcoding +// job specification as a JSON file without the console, use FramerateControl +// to specify which value the service uses for the frame rate for this output. +// Choose INITIALIZE_FROM_SOURCE if you want the service to use the frame rate +// from the input. Choose SPECIFIED if you want the service to use the frame +// rate you specify in the settings FramerateNumerator and FramerateDenominator. +const ( + // Vp8FramerateControlInitializeFromSource is a Vp8FramerateControl enum value + Vp8FramerateControlInitializeFromSource = "INITIALIZE_FROM_SOURCE" + + // Vp8FramerateControlSpecified is a Vp8FramerateControl enum value + Vp8FramerateControlSpecified = "SPECIFIED" +) + +// Vp8FramerateControl_Values returns all elements of the Vp8FramerateControl enum +func Vp8FramerateControl_Values() []string { + return []string{ + Vp8FramerateControlInitializeFromSource, + Vp8FramerateControlSpecified, + } +} + +// Optional. Specify how the transcoder performs framerate conversion. The default +// behavior is to use Drop duplicate (DUPLICATE_DROP) conversion. When you choose +// Interpolate (INTERPOLATE) instead, the conversion produces smoother motion. +const ( + // Vp8FramerateConversionAlgorithmDuplicateDrop is a Vp8FramerateConversionAlgorithm enum value + Vp8FramerateConversionAlgorithmDuplicateDrop = "DUPLICATE_DROP" + + // Vp8FramerateConversionAlgorithmInterpolate is a Vp8FramerateConversionAlgorithm enum value + Vp8FramerateConversionAlgorithmInterpolate = "INTERPOLATE" +) + +// Vp8FramerateConversionAlgorithm_Values returns all elements of the Vp8FramerateConversionAlgorithm enum +func Vp8FramerateConversionAlgorithm_Values() []string { + return []string{ + Vp8FramerateConversionAlgorithmDuplicateDrop, + Vp8FramerateConversionAlgorithmInterpolate, + } +} + +// Optional. Specify how the service determines the pixel aspect ratio (PAR) +// for this output. The default behavior, Follow source (INITIALIZE_FROM_SOURCE), +// uses the PAR from your input video for your output. To specify a different +// PAR in the console, choose any value other than Follow source. To specify +// a different PAR by editing the JSON job specification, choose SPECIFIED. +// When you choose SPECIFIED for this setting, you must also specify values +// for the parNumerator and parDenominator settings. +const ( + // Vp8ParControlInitializeFromSource is a Vp8ParControl enum value + Vp8ParControlInitializeFromSource = "INITIALIZE_FROM_SOURCE" + + // Vp8ParControlSpecified is a Vp8ParControl enum value + Vp8ParControlSpecified = "SPECIFIED" +) + +// Vp8ParControl_Values returns all elements of the Vp8ParControl enum +func Vp8ParControl_Values() []string { + return []string{ + Vp8ParControlInitializeFromSource, + Vp8ParControlSpecified, + } +} + +// Optional. Use Quality tuning level (qualityTuningLevel) to choose how you +// want to trade off encoding speed for output video quality. The default behavior +// is faster, lower quality, multi-pass encoding. +const ( + // Vp8QualityTuningLevelMultiPass is a Vp8QualityTuningLevel enum value + Vp8QualityTuningLevelMultiPass = "MULTI_PASS" + + // Vp8QualityTuningLevelMultiPassHq is a Vp8QualityTuningLevel enum value + Vp8QualityTuningLevelMultiPassHq = "MULTI_PASS_HQ" +) + +// Vp8QualityTuningLevel_Values returns all elements of the Vp8QualityTuningLevel enum +func Vp8QualityTuningLevel_Values() []string { + return []string{ + Vp8QualityTuningLevelMultiPass, + Vp8QualityTuningLevelMultiPassHq, + } +} + +// With the VP8 codec, you can use only the variable bitrate (VBR) rate control +// mode. +const ( + // Vp8RateControlModeVbr is a Vp8RateControlMode enum value + Vp8RateControlModeVbr = "VBR" +) + +// Vp8RateControlMode_Values returns all elements of the Vp8RateControlMode enum +func Vp8RateControlMode_Values() []string { + return []string{ + Vp8RateControlModeVbr, + } +} + +// If you are using the console, use the Framerate setting to specify the frame +// rate for this output. If you want to keep the same frame rate as the input +// video, choose Follow source. If you want to do frame rate conversion, choose +// a frame rate from the dropdown list or choose Custom. The framerates shown +// in the dropdown list are decimal approximations of fractions. If you choose +// Custom, specify your frame rate as a fraction. If you are creating your transcoding +// job specification as a JSON file without the console, use FramerateControl +// to specify which value the service uses for the frame rate for this output. +// Choose INITIALIZE_FROM_SOURCE if you want the service to use the frame rate +// from the input. Choose SPECIFIED if you want the service to use the frame +// rate you specify in the settings FramerateNumerator and FramerateDenominator. +const ( + // Vp9FramerateControlInitializeFromSource is a Vp9FramerateControl enum value + Vp9FramerateControlInitializeFromSource = "INITIALIZE_FROM_SOURCE" + + // Vp9FramerateControlSpecified is a Vp9FramerateControl enum value + Vp9FramerateControlSpecified = "SPECIFIED" +) + +// Vp9FramerateControl_Values returns all elements of the Vp9FramerateControl enum +func Vp9FramerateControl_Values() []string { + return []string{ + Vp9FramerateControlInitializeFromSource, + Vp9FramerateControlSpecified, + } +} + +// Optional. Specify how the transcoder performs framerate conversion. The default +// behavior is to use Drop duplicate (DUPLICATE_DROP) conversion. When you choose +// Interpolate (INTERPOLATE) instead, the conversion produces smoother motion. +const ( + // Vp9FramerateConversionAlgorithmDuplicateDrop is a Vp9FramerateConversionAlgorithm enum value + Vp9FramerateConversionAlgorithmDuplicateDrop = "DUPLICATE_DROP" + + // Vp9FramerateConversionAlgorithmInterpolate is a Vp9FramerateConversionAlgorithm enum value + Vp9FramerateConversionAlgorithmInterpolate = "INTERPOLATE" +) + +// Vp9FramerateConversionAlgorithm_Values returns all elements of the Vp9FramerateConversionAlgorithm enum +func Vp9FramerateConversionAlgorithm_Values() []string { + return []string{ + Vp9FramerateConversionAlgorithmDuplicateDrop, + Vp9FramerateConversionAlgorithmInterpolate, + } +} + +// Optional. Specify how the service determines the pixel aspect ratio (PAR) +// for this output. The default behavior, Follow source (INITIALIZE_FROM_SOURCE), +// uses the PAR from your input video for your output. To specify a different +// PAR in the console, choose any value other than Follow source. To specify +// a different PAR by editing the JSON job specification, choose SPECIFIED. +// When you choose SPECIFIED for this setting, you must also specify values +// for the parNumerator and parDenominator settings. +const ( + // Vp9ParControlInitializeFromSource is a Vp9ParControl enum value + Vp9ParControlInitializeFromSource = "INITIALIZE_FROM_SOURCE" + + // Vp9ParControlSpecified is a Vp9ParControl enum value + Vp9ParControlSpecified = "SPECIFIED" +) + +// Vp9ParControl_Values returns all elements of the Vp9ParControl enum +func Vp9ParControl_Values() []string { + return []string{ + Vp9ParControlInitializeFromSource, + Vp9ParControlSpecified, + } +} + +// Optional. Use Quality tuning level (qualityTuningLevel) to choose how you +// want to trade off encoding speed for output video quality. The default behavior +// is faster, lower quality, multi-pass encoding. +const ( + // Vp9QualityTuningLevelMultiPass is a Vp9QualityTuningLevel enum value + Vp9QualityTuningLevelMultiPass = "MULTI_PASS" + + // Vp9QualityTuningLevelMultiPassHq is a Vp9QualityTuningLevel enum value + Vp9QualityTuningLevelMultiPassHq = "MULTI_PASS_HQ" +) + +// Vp9QualityTuningLevel_Values returns all elements of the Vp9QualityTuningLevel enum +func Vp9QualityTuningLevel_Values() []string { + return []string{ + Vp9QualityTuningLevelMultiPass, + Vp9QualityTuningLevelMultiPassHq, + } +} + +// With the VP9 codec, you can use only the variable bitrate (VBR) rate control +// mode. +const ( + // Vp9RateControlModeVbr is a Vp9RateControlMode enum value + Vp9RateControlModeVbr = "VBR" +) + +// Vp9RateControlMode_Values returns all elements of the Vp9RateControlMode enum +func Vp9RateControlMode_Values() []string { + return []string{ + Vp9RateControlModeVbr, + } +} + +// Optional. Ignore this setting unless Nagra support directs you to specify +// a value. When you don't specify a value here, the Nagra NexGuard library +// uses its default value. +const ( + // WatermarkingStrengthLightest is a WatermarkingStrength enum value + WatermarkingStrengthLightest = "LIGHTEST" + + // WatermarkingStrengthLighter is a WatermarkingStrength enum value + WatermarkingStrengthLighter = "LIGHTER" + + // WatermarkingStrengthDefault is a WatermarkingStrength enum value + WatermarkingStrengthDefault = "DEFAULT" + + // WatermarkingStrengthStronger is a WatermarkingStrength enum value + WatermarkingStrengthStronger = "STRONGER" + + // WatermarkingStrengthStrongest is a WatermarkingStrength enum value + WatermarkingStrengthStrongest = "STRONGEST" +) + +// WatermarkingStrength_Values returns all elements of the WatermarkingStrength enum +func WatermarkingStrength_Values() []string { + return []string{ + WatermarkingStrengthLightest, + WatermarkingStrengthLighter, + WatermarkingStrengthDefault, + WatermarkingStrengthStronger, + WatermarkingStrengthStrongest, + } +} + // The service defaults to using RIFF for WAV outputs. If your output audio // is likely to exceed 4 GB in file size, or if you otherwise need the extended // support of the RF64 format, set your output WAV file format to RF64. @@ -23026,3 +26751,11 @@ const ( // WavFormatRf64 is a WavFormat enum value WavFormatRf64 = "RF64" ) + +// WavFormat_Values returns all elements of the WavFormat enum +func WavFormat_Values() []string { + return []string{ + WavFormatRiff, + WavFormatRf64, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/medialive/api.go b/vendor/github.com/aws/aws-sdk-go/service/medialive/api.go index 5683e77eeb6..727f7aa9dfa 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/medialive/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/medialive/api.go @@ -4,6 +4,8 @@ package medialive import ( "fmt" + "io" + "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" @@ -1549,6 +1551,186 @@ func (c *MediaLive) DescribeInputWithContext(ctx aws.Context, input *DescribeInp return out, req.Send() } +const opDescribeInputDevice = "DescribeInputDevice" + +// DescribeInputDeviceRequest generates a "aws/request.Request" representing the +// client's request for the DescribeInputDevice operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeInputDevice for more information on using the DescribeInputDevice +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeInputDeviceRequest method. +// req, resp := client.DescribeInputDeviceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/DescribeInputDevice +func (c *MediaLive) DescribeInputDeviceRequest(input *DescribeInputDeviceInput) (req *request.Request, output *DescribeInputDeviceOutput) { + op := &request.Operation{ + Name: opDescribeInputDevice, + HTTPMethod: "GET", + HTTPPath: "/prod/inputDevices/{inputDeviceId}", + } + + if input == nil { + input = &DescribeInputDeviceInput{} + } + + output = &DescribeInputDeviceOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeInputDevice API operation for AWS Elemental MediaLive. +// +// Gets the details for the input device +// +// Returns awserr.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 Elemental MediaLive's +// API operation DescribeInputDevice for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// +// * InternalServerErrorException +// +// * ForbiddenException +// +// * BadGatewayException +// +// * NotFoundException +// +// * GatewayTimeoutException +// +// * TooManyRequestsException +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/DescribeInputDevice +func (c *MediaLive) DescribeInputDevice(input *DescribeInputDeviceInput) (*DescribeInputDeviceOutput, error) { + req, out := c.DescribeInputDeviceRequest(input) + return out, req.Send() +} + +// DescribeInputDeviceWithContext is the same as DescribeInputDevice with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInputDevice for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *MediaLive) DescribeInputDeviceWithContext(ctx aws.Context, input *DescribeInputDeviceInput, opts ...request.Option) (*DescribeInputDeviceOutput, error) { + req, out := c.DescribeInputDeviceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDescribeInputDeviceThumbnail = "DescribeInputDeviceThumbnail" + +// DescribeInputDeviceThumbnailRequest generates a "aws/request.Request" representing the +// client's request for the DescribeInputDeviceThumbnail operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeInputDeviceThumbnail for more information on using the DescribeInputDeviceThumbnail +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeInputDeviceThumbnailRequest method. +// req, resp := client.DescribeInputDeviceThumbnailRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/DescribeInputDeviceThumbnail +func (c *MediaLive) DescribeInputDeviceThumbnailRequest(input *DescribeInputDeviceThumbnailInput) (req *request.Request, output *DescribeInputDeviceThumbnailOutput) { + op := &request.Operation{ + Name: opDescribeInputDeviceThumbnail, + HTTPMethod: "GET", + HTTPPath: "/prod/inputDevices/{inputDeviceId}/thumbnailData", + } + + if input == nil { + input = &DescribeInputDeviceThumbnailInput{} + } + + output = &DescribeInputDeviceThumbnailOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeInputDeviceThumbnail API operation for AWS Elemental MediaLive. +// +// Get the latest thumbnail data for the input device. +// +// Returns awserr.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 Elemental MediaLive's +// API operation DescribeInputDeviceThumbnail for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// +// * InternalServerErrorException +// +// * ForbiddenException +// +// * BadGatewayException +// +// * NotFoundException +// +// * GatewayTimeoutException +// +// * TooManyRequestsException +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/DescribeInputDeviceThumbnail +func (c *MediaLive) DescribeInputDeviceThumbnail(input *DescribeInputDeviceThumbnailInput) (*DescribeInputDeviceThumbnailOutput, error) { + req, out := c.DescribeInputDeviceThumbnailRequest(input) + return out, req.Send() +} + +// DescribeInputDeviceThumbnailWithContext is the same as DescribeInputDeviceThumbnail with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeInputDeviceThumbnail for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *MediaLive) DescribeInputDeviceThumbnailWithContext(ctx aws.Context, input *DescribeInputDeviceThumbnailInput, opts ...request.Option) (*DescribeInputDeviceThumbnailOutput, error) { + req, out := c.DescribeInputDeviceThumbnailRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeInputSecurityGroup = "DescribeInputSecurityGroup" // DescribeInputSecurityGroupRequest generates a "aws/request.Request" representing the @@ -2293,6 +2475,152 @@ func (c *MediaLive) ListChannelsPagesWithContext(ctx aws.Context, input *ListCha return p.Err() } +const opListInputDevices = "ListInputDevices" + +// ListInputDevicesRequest generates a "aws/request.Request" representing the +// client's request for the ListInputDevices operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListInputDevices for more information on using the ListInputDevices +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListInputDevicesRequest method. +// req, resp := client.ListInputDevicesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/ListInputDevices +func (c *MediaLive) ListInputDevicesRequest(input *ListInputDevicesInput) (req *request.Request, output *ListInputDevicesOutput) { + op := &request.Operation{ + Name: opListInputDevices, + HTTPMethod: "GET", + HTTPPath: "/prod/inputDevices", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListInputDevicesInput{} + } + + output = &ListInputDevicesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListInputDevices API operation for AWS Elemental MediaLive. +// +// List input devices +// +// Returns awserr.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 Elemental MediaLive's +// API operation ListInputDevices for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// +// * InternalServerErrorException +// +// * ForbiddenException +// +// * BadGatewayException +// +// * GatewayTimeoutException +// +// * TooManyRequestsException +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/ListInputDevices +func (c *MediaLive) ListInputDevices(input *ListInputDevicesInput) (*ListInputDevicesOutput, error) { + req, out := c.ListInputDevicesRequest(input) + return out, req.Send() +} + +// ListInputDevicesWithContext is the same as ListInputDevices with the addition of +// the ability to pass a context and additional request options. +// +// See ListInputDevices for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *MediaLive) ListInputDevicesWithContext(ctx aws.Context, input *ListInputDevicesInput, opts ...request.Option) (*ListInputDevicesOutput, error) { + req, out := c.ListInputDevicesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListInputDevicesPages iterates over the pages of a ListInputDevices operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListInputDevices 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 ListInputDevices operation. +// pageNum := 0 +// err := client.ListInputDevicesPages(params, +// func(page *medialive.ListInputDevicesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *MediaLive) ListInputDevicesPages(input *ListInputDevicesInput, fn func(*ListInputDevicesOutput, bool) bool) error { + return c.ListInputDevicesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListInputDevicesPagesWithContext same as ListInputDevicesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *MediaLive) ListInputDevicesPagesWithContext(ctx aws.Context, input *ListInputDevicesInput, fn func(*ListInputDevicesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListInputDevicesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListInputDevicesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListInputDevicesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListInputSecurityGroups = "ListInputSecurityGroups" // ListInputSecurityGroupsRequest generates a "aws/request.Request" representing the @@ -3991,33 +4319,125 @@ func (c *MediaLive) UpdateInputWithContext(ctx aws.Context, input *UpdateInputIn return out, req.Send() } -const opUpdateInputSecurityGroup = "UpdateInputSecurityGroup" +const opUpdateInputDevice = "UpdateInputDevice" -// UpdateInputSecurityGroupRequest generates a "aws/request.Request" representing the -// client's request for the UpdateInputSecurityGroup operation. The "output" return +// UpdateInputDeviceRequest generates a "aws/request.Request" representing the +// client's request for the UpdateInputDevice operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateInputSecurityGroup for more information on using the UpdateInputSecurityGroup +// See UpdateInputDevice for more information on using the UpdateInputDevice // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateInputSecurityGroupRequest method. -// req, resp := client.UpdateInputSecurityGroupRequest(params) +// // Example sending a request using the UpdateInputDeviceRequest method. +// req, resp := client.UpdateInputDeviceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/UpdateInputSecurityGroup -func (c *MediaLive) UpdateInputSecurityGroupRequest(input *UpdateInputSecurityGroupInput) (req *request.Request, output *UpdateInputSecurityGroupOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/UpdateInputDevice +func (c *MediaLive) UpdateInputDeviceRequest(input *UpdateInputDeviceInput) (req *request.Request, output *UpdateInputDeviceOutput) { + op := &request.Operation{ + Name: opUpdateInputDevice, + HTTPMethod: "PUT", + HTTPPath: "/prod/inputDevices/{inputDeviceId}", + } + + if input == nil { + input = &UpdateInputDeviceInput{} + } + + output = &UpdateInputDeviceOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateInputDevice API operation for AWS Elemental MediaLive. +// +// Updates the parameters for the input device. +// +// Returns awserr.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 Elemental MediaLive's +// API operation UpdateInputDevice for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// +// * UnprocessableEntityException +// +// * InternalServerErrorException +// +// * ForbiddenException +// +// * BadGatewayException +// +// * NotFoundException +// +// * GatewayTimeoutException +// +// * TooManyRequestsException +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/UpdateInputDevice +func (c *MediaLive) UpdateInputDevice(input *UpdateInputDeviceInput) (*UpdateInputDeviceOutput, error) { + req, out := c.UpdateInputDeviceRequest(input) + return out, req.Send() +} + +// UpdateInputDeviceWithContext is the same as UpdateInputDevice with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateInputDevice for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *MediaLive) UpdateInputDeviceWithContext(ctx aws.Context, input *UpdateInputDeviceInput, opts ...request.Option) (*UpdateInputDeviceOutput, error) { + req, out := c.UpdateInputDeviceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateInputSecurityGroup = "UpdateInputSecurityGroup" + +// UpdateInputSecurityGroupRequest generates a "aws/request.Request" representing the +// client's request for the UpdateInputSecurityGroup operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateInputSecurityGroup for more information on using the UpdateInputSecurityGroup +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateInputSecurityGroupRequest method. +// req, resp := client.UpdateInputSecurityGroupRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/UpdateInputSecurityGroup +func (c *MediaLive) UpdateInputSecurityGroupRequest(input *UpdateInputSecurityGroupInput) (req *request.Request, output *UpdateInputSecurityGroupOutput) { op := &request.Operation{ Name: opUpdateInputSecurityGroup, HTTPMethod: "PUT", @@ -4918,9 +5338,10 @@ type AudioDescription struct { // Audio codec settings. CodecSettings *AudioCodecSettings `locationName:"codecSettings" type:"structure"` - // Indicates the language of the audio output track. Only used if languageControlMode - // is useConfigured, or there is no ISO 639 language code specified in the input. - LanguageCode *string `locationName:"languageCode" min:"3" type:"string"` + // RFC 5646 language code representing the language of the audio output track. + // Only used if languageControlMode is useConfigured, or there is no ISO 639 + // language code specified in the input. + LanguageCode *string `locationName:"languageCode" min:"1" type:"string"` // Choosing followInput will cause the ISO 639 language code of the output to // follow the ISO 639 language code of the input. The languageCode will be used @@ -4960,8 +5381,8 @@ func (s *AudioDescription) Validate() error { if s.AudioSelectorName == nil { invalidParams.Add(request.NewErrParamRequired("AudioSelectorName")) } - if s.LanguageCode != nil && len(*s.LanguageCode) < 3 { - invalidParams.Add(request.NewErrParamMinLen("LanguageCode", 3)) + if s.LanguageCode != nil && len(*s.LanguageCode) < 1 { + invalidParams.Add(request.NewErrParamMinLen("LanguageCode", 1)) } if s.Name == nil { invalidParams.Add(request.NewErrParamRequired("Name")) @@ -6441,6 +6862,9 @@ type CaptionDestinationSettings struct { // Dvb Sub Destination Settings DvbSubDestinationSettings *DvbSubDestinationSettings `locationName:"dvbSubDestinationSettings" type:"structure"` + // Ebu Tt DDestination Settings + EbuTtDDestinationSettings *EbuTtDDestinationSettings `locationName:"ebuTtDDestinationSettings" type:"structure"` + // Embedded Destination Settings EmbeddedDestinationSettings *EmbeddedDestinationSettings `locationName:"embeddedDestinationSettings" type:"structure"` @@ -6517,6 +6941,12 @@ func (s *CaptionDestinationSettings) SetDvbSubDestinationSettings(v *DvbSubDesti return s } +// SetEbuTtDDestinationSettings sets the EbuTtDDestinationSettings field's value. +func (s *CaptionDestinationSettings) SetEbuTtDDestinationSettings(v *EbuTtDDestinationSettings) *CaptionDestinationSettings { + s.EbuTtDDestinationSettings = v + return s +} + // SetEmbeddedDestinationSettings sets the EmbeddedDestinationSettings field's value. func (s *CaptionDestinationSettings) SetEmbeddedDestinationSettings(v *EmbeddedDestinationSettings) *CaptionDestinationSettings { s.EmbeddedDestinationSettings = v @@ -7360,6 +7790,8 @@ type CreateInputInput struct { Destinations []*InputDestinationRequest `locationName:"destinations" type:"list"` + InputDevices []*InputDeviceSettings `locationName:"inputDevices" type:"list"` + InputSecurityGroups []*string `locationName:"inputSecurityGroups" type:"list"` MediaConnectFlows []*MediaConnectFlowRequest `locationName:"mediaConnectFlows" type:"list"` @@ -7414,6 +7846,12 @@ func (s *CreateInputInput) SetDestinations(v []*InputDestinationRequest) *Create return s } +// SetInputDevices sets the InputDevices field's value. +func (s *CreateInputInput) SetInputDevices(v []*InputDeviceSettings) *CreateInputInput { + s.InputDevices = v + return s +} + // SetInputSecurityGroups sets the InputSecurityGroups field's value. func (s *CreateInputInput) SetInputSecurityGroups(v []*string) *CreateInputInput { s.InputSecurityGroups = v @@ -8827,6 +9265,257 @@ func (s *DescribeChannelOutput) SetTags(v map[string]*string) *DescribeChannelOu return s } +type DescribeInputDeviceInput struct { + _ struct{} `type:"structure"` + + // InputDeviceId is a required field + InputDeviceId *string `location:"uri" locationName:"inputDeviceId" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeInputDeviceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeInputDeviceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeInputDeviceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeInputDeviceInput"} + if s.InputDeviceId == nil { + invalidParams.Add(request.NewErrParamRequired("InputDeviceId")) + } + if s.InputDeviceId != nil && len(*s.InputDeviceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("InputDeviceId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetInputDeviceId sets the InputDeviceId field's value. +func (s *DescribeInputDeviceInput) SetInputDeviceId(v string) *DescribeInputDeviceInput { + s.InputDeviceId = &v + return s +} + +type DescribeInputDeviceOutput struct { + _ struct{} `type:"structure"` + + Arn *string `locationName:"arn" type:"string"` + + // The state of the connection between the input device and AWS. + ConnectionState *string `locationName:"connectionState" type:"string" enum:"InputDeviceConnectionState"` + + // The status of the action to synchronize the device configuration. If you + // change the configuration of the input device (for example, the maximum bitrate), + // MediaLive sends the new data to the device. The device might not update itself + // immediately. SYNCED means the device has updated its configuration. SYNCING + // means that it has not updated its configuration. + DeviceSettingsSyncState *string `locationName:"deviceSettingsSyncState" type:"string" enum:"DeviceSettingsSyncState"` + + // Settings that describe the active source from the input device, and the video + // characteristics of that source. + HdDeviceSettings *InputDeviceHdSettings `locationName:"hdDeviceSettings" type:"structure"` + + Id *string `locationName:"id" type:"string"` + + MacAddress *string `locationName:"macAddress" type:"string"` + + Name *string `locationName:"name" type:"string"` + + // The network settings for the input device. + NetworkSettings *InputDeviceNetworkSettings `locationName:"networkSettings" type:"structure"` + + SerialNumber *string `locationName:"serialNumber" type:"string"` + + // The type of the input device. For an AWS Elemental Link device that outputs + // resolutions up to 1080, choose "HD". + Type *string `locationName:"type" type:"string" enum:"InputDeviceType"` +} + +// String returns the string representation +func (s DescribeInputDeviceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeInputDeviceOutput) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *DescribeInputDeviceOutput) SetArn(v string) *DescribeInputDeviceOutput { + s.Arn = &v + return s +} + +// SetConnectionState sets the ConnectionState field's value. +func (s *DescribeInputDeviceOutput) SetConnectionState(v string) *DescribeInputDeviceOutput { + s.ConnectionState = &v + return s +} + +// SetDeviceSettingsSyncState sets the DeviceSettingsSyncState field's value. +func (s *DescribeInputDeviceOutput) SetDeviceSettingsSyncState(v string) *DescribeInputDeviceOutput { + s.DeviceSettingsSyncState = &v + return s +} + +// SetHdDeviceSettings sets the HdDeviceSettings field's value. +func (s *DescribeInputDeviceOutput) SetHdDeviceSettings(v *InputDeviceHdSettings) *DescribeInputDeviceOutput { + s.HdDeviceSettings = v + return s +} + +// SetId sets the Id field's value. +func (s *DescribeInputDeviceOutput) SetId(v string) *DescribeInputDeviceOutput { + s.Id = &v + return s +} + +// SetMacAddress sets the MacAddress field's value. +func (s *DescribeInputDeviceOutput) SetMacAddress(v string) *DescribeInputDeviceOutput { + s.MacAddress = &v + return s +} + +// SetName sets the Name field's value. +func (s *DescribeInputDeviceOutput) SetName(v string) *DescribeInputDeviceOutput { + s.Name = &v + return s +} + +// SetNetworkSettings sets the NetworkSettings field's value. +func (s *DescribeInputDeviceOutput) SetNetworkSettings(v *InputDeviceNetworkSettings) *DescribeInputDeviceOutput { + s.NetworkSettings = v + return s +} + +// SetSerialNumber sets the SerialNumber field's value. +func (s *DescribeInputDeviceOutput) SetSerialNumber(v string) *DescribeInputDeviceOutput { + s.SerialNumber = &v + return s +} + +// SetType sets the Type field's value. +func (s *DescribeInputDeviceOutput) SetType(v string) *DescribeInputDeviceOutput { + s.Type = &v + return s +} + +type DescribeInputDeviceThumbnailInput struct { + _ struct{} `type:"structure"` + + // Accept Header + // + // Accept is a required field + Accept *string `location:"header" locationName:"accept" type:"string" required:"true" enum:"AcceptHeader"` + + // InputDeviceId is a required field + InputDeviceId *string `location:"uri" locationName:"inputDeviceId" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeInputDeviceThumbnailInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeInputDeviceThumbnailInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeInputDeviceThumbnailInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeInputDeviceThumbnailInput"} + if s.Accept == nil { + invalidParams.Add(request.NewErrParamRequired("Accept")) + } + if s.InputDeviceId == nil { + invalidParams.Add(request.NewErrParamRequired("InputDeviceId")) + } + if s.InputDeviceId != nil && len(*s.InputDeviceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("InputDeviceId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAccept sets the Accept field's value. +func (s *DescribeInputDeviceThumbnailInput) SetAccept(v string) *DescribeInputDeviceThumbnailInput { + s.Accept = &v + return s +} + +// SetInputDeviceId sets the InputDeviceId field's value. +func (s *DescribeInputDeviceThumbnailInput) SetInputDeviceId(v string) *DescribeInputDeviceThumbnailInput { + s.InputDeviceId = &v + return s +} + +type DescribeInputDeviceThumbnailOutput struct { + _ struct{} `type:"structure" payload:"Body"` + + Body io.ReadCloser `locationName:"body" type:"blob"` + + ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` + + ContentType *string `location:"header" locationName:"Content-Type" type:"string" enum:"ContentType"` + + ETag *string `location:"header" locationName:"ETag" type:"string"` + + LastModified *time.Time `location:"header" locationName:"Last-Modified" type:"timestamp"` +} + +// String returns the string representation +func (s DescribeInputDeviceThumbnailOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeInputDeviceThumbnailOutput) GoString() string { + return s.String() +} + +// SetBody sets the Body field's value. +func (s *DescribeInputDeviceThumbnailOutput) SetBody(v io.ReadCloser) *DescribeInputDeviceThumbnailOutput { + s.Body = v + return s +} + +// SetContentLength sets the ContentLength field's value. +func (s *DescribeInputDeviceThumbnailOutput) SetContentLength(v int64) *DescribeInputDeviceThumbnailOutput { + s.ContentLength = &v + return s +} + +// SetContentType sets the ContentType field's value. +func (s *DescribeInputDeviceThumbnailOutput) SetContentType(v string) *DescribeInputDeviceThumbnailOutput { + s.ContentType = &v + return s +} + +// SetETag sets the ETag field's value. +func (s *DescribeInputDeviceThumbnailOutput) SetETag(v string) *DescribeInputDeviceThumbnailOutput { + s.ETag = &v + return s +} + +// SetLastModified sets the LastModified field's value. +func (s *DescribeInputDeviceThumbnailOutput) SetLastModified(v time.Time) *DescribeInputDeviceThumbnailOutput { + s.LastModified = &v + return s +} + type DescribeInputInput struct { _ struct{} `type:"structure"` @@ -8880,6 +9569,8 @@ type DescribeInputOutput struct { // A standard input has two sources and a single pipeline input only has one. InputClass *string `locationName:"inputClass" type:"string" enum:"InputClass"` + InputDevices []*InputDeviceSettings `locationName:"inputDevices" type:"list"` + // There are two types of input sources, static and dynamic. If an input source // is dynamic you canchange the source url of the input dynamically using an // input switch action. However, the only input typeto support a dynamic url @@ -8943,6 +9634,12 @@ func (s *DescribeInputOutput) SetInputClass(v string) *DescribeInputOutput { return s } +// SetInputDevices sets the InputDevices field's value. +func (s *DescribeInputOutput) SetInputDevices(v []*InputDeviceSettings) *DescribeInputOutput { + s.InputDevices = v + return s +} + // SetInputSourceType sets the InputSourceType field's value. func (s *DescribeInputOutput) SetInputSourceType(v string) *DescribeInputOutput { s.InputSourceType = &v @@ -10448,32 +11145,92 @@ func (s *Eac3Settings) SetSurroundMode(v string) *Eac3Settings { return s } -// Embedded Destination Settings -type EmbeddedDestinationSettings struct { +// Ebu Tt DDestination Settings +type EbuTtDDestinationSettings struct { _ struct{} `type:"structure"` + + // Specifies how to handle the gap between the lines (in multi-line captions).- + // enabled: Fill with the captions background color (as specified in the input + // captions).- disabled: Leave the gap unfilled. + FillLineGap *string `locationName:"fillLineGap" type:"string" enum:"EbuTtDFillLineGapControl"` + + // Specifies the font family to include in the font data attached to the EBU-TT + // captions. Valid only if styleControl is set to include. If you leave this + // field empty, the font family is set to "monospaced". (If styleControl is + // set to exclude, the font family is always set to "monospaced".)You specify + // only the font family. All other style information (color, bold, position + // and so on) is copied from the input captions. The size is always set to 100% + // to allow the downstream player to choose the size.- Enter a list of font + // families, as a comma-separated list of font names, in order of preference. + // The name can be a font family (such as “Arial”), or a generic font family + // (such as “serif”), or “default” (to let the downstream player choose + // the font).- Leave blank to set the family to “monospace”. + FontFamily *string `locationName:"fontFamily" type:"string"` + + // Specifies the style information (font color, font position, and so on) to + // include in the font data that is attached to the EBU-TT captions.- include: + // Take the style information (font color, font position, and so on) from the + // source captions and include that information in the font data attached to + // the EBU-TT captions. This option is valid only if the source captions are + // Embedded or Teletext.- exclude: In the font data attached to the EBU-TT captions, + // set the font family to "monospaced". Do not include any other style information. + StyleControl *string `locationName:"styleControl" type:"string" enum:"EbuTtDDestinationStyleControl"` } // String returns the string representation -func (s EmbeddedDestinationSettings) String() string { +func (s EbuTtDDestinationSettings) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s EmbeddedDestinationSettings) GoString() string { +func (s EbuTtDDestinationSettings) GoString() string { return s.String() } -// Embedded Plus Scte20 Destination Settings -type EmbeddedPlusScte20DestinationSettings struct { - _ struct{} `type:"structure"` +// SetFillLineGap sets the FillLineGap field's value. +func (s *EbuTtDDestinationSettings) SetFillLineGap(v string) *EbuTtDDestinationSettings { + s.FillLineGap = &v + return s } -// String returns the string representation -func (s EmbeddedPlusScte20DestinationSettings) String() string { - return awsutil.Prettify(s) +// SetFontFamily sets the FontFamily field's value. +func (s *EbuTtDDestinationSettings) SetFontFamily(v string) *EbuTtDDestinationSettings { + s.FontFamily = &v + return s } -// GoString returns the string representation +// SetStyleControl sets the StyleControl field's value. +func (s *EbuTtDDestinationSettings) SetStyleControl(v string) *EbuTtDDestinationSettings { + s.StyleControl = &v + return s +} + +// Embedded Destination Settings +type EmbeddedDestinationSettings struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s EmbeddedDestinationSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EmbeddedDestinationSettings) GoString() string { + return s.String() +} + +// Embedded Plus Scte20 Destination Settings +type EmbeddedPlusScte20DestinationSettings struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s EmbeddedPlusScte20DestinationSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation func (s EmbeddedPlusScte20DestinationSettings) GoString() string { return s.String() } @@ -10568,6 +11325,9 @@ type EncoderSettings struct { // Settings for caption decriptions CaptionDescriptions []*CaptionDescription `locationName:"captionDescriptions" type:"list"` + // Feature Activations + FeatureActivations *FeatureActivations `locationName:"featureActivations" type:"structure"` + // Configuration settings that apply to the event as a whole. GlobalConfiguration *GlobalConfiguration `locationName:"globalConfiguration" type:"structure"` @@ -10713,6 +11473,12 @@ func (s *EncoderSettings) SetCaptionDescriptions(v []*CaptionDescription) *Encod return s } +// SetFeatureActivations sets the FeatureActivations field's value. +func (s *EncoderSettings) SetFeatureActivations(v *FeatureActivations) *EncoderSettings { + s.FeatureActivations = v + return s +} + // SetGlobalConfiguration sets the GlobalConfiguration field's value. func (s *EncoderSettings) SetGlobalConfiguration(v *GlobalConfiguration) *EncoderSettings { s.GlobalConfiguration = v @@ -10743,6 +11509,33 @@ func (s *EncoderSettings) SetVideoDescriptions(v []*VideoDescription) *EncoderSe return s } +// Feature Activations +type FeatureActivations struct { + _ struct{} `type:"structure"` + + // Enables the Input Prepare feature. You can create Input Prepare actions in + // the schedule only if this feature is enabled.If you disable the feature on + // an existing schedule, make sure that you first delete all input prepare actions + // from the schedule. + InputPrepareScheduleActions *string `locationName:"inputPrepareScheduleActions" type:"string" enum:"FeatureActivationsInputPrepareScheduleActions"` +} + +// String returns the string representation +func (s FeatureActivations) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FeatureActivations) GoString() string { + return s.String() +} + +// SetInputPrepareScheduleActions sets the InputPrepareScheduleActions field's value. +func (s *FeatureActivations) SetInputPrepareScheduleActions(v string) *FeatureActivations { + s.InputPrepareScheduleActions = &v + return s +} + // Fec Output Settings type FecOutputSettings struct { _ struct{} `type:"structure"` @@ -11200,8 +11993,8 @@ type GlobalConfiguration struct { // Settings for system actions when input is lost. InputLossBehavior *InputLossBehavior `locationName:"inputLossBehavior" type:"structure"` - // Indicates how MediaLive pipelines are synchronized.PIPELINELOCKING - MediaLive - // will attempt to synchronize the output of each pipeline to the other.EPOCHLOCKING + // Indicates how MediaLive pipelines are synchronized.PIPELINE_LOCKING - MediaLive + // will attempt to synchronize the output of each pipeline to the other.EPOCH_LOCKING // - MediaLive will attempt to synchronize the output of each pipeline to the // Unix epoch. OutputLockingMode *string `locationName:"outputLockingMode" type:"string" enum:"GlobalConfigurationOutputLockingMode"` @@ -11383,7 +12176,7 @@ type H264Settings struct { // Entropy encoding mode. Use cabac (must be in Main or High profile) or cavlc. EntropyEncoding *string `locationName:"entropyEncoding" type:"string" enum:"H264EntropyEncoding"` - // Settings associated with the specified filter. + // Optional filters that you can apply to an encode. FilterSettings *H264FilterSettings `locationName:"filterSettings" type:"structure"` // Four bit AFD value to write on all frames of video in the output stream. @@ -11474,14 +12267,17 @@ type H264Settings struct { ParDenominator *int64 `locationName:"parDenominator" min:"1" type:"integer"` // Pixel Aspect Ratio numerator. - ParNumerator *int64 `locationName:"parNumerator" type:"integer"` + ParNumerator *int64 `locationName:"parNumerator" min:"1" type:"integer"` // H.264 Profile. Profile *string `locationName:"profile" type:"string" enum:"H264Profile"` - // If set to "ENHANCEDQUALITY," improves visual quality at an increased output - // cost. If this video is being delivered to a MediaLive Multiplex, "ENHANCEDQUALITY" - // is always used. + // Leave as STANDARD_QUALITY or choose a different value (which might result + // in additional costs to run the channel).- ENHANCED_QUALITY: Produces a slightly + // better video quality without an increase in the bitrate. Has an effect only + // when the Rate control mode is QVBR or CBR. If this channel is in a MediaLive + // multiplex, the value must be ENHANCED_QUALITY.- STANDARD_QUALITY: Valid for + // any Rate control mode. QualityLevel *string `locationName:"qualityLevel" type:"string" enum:"H264QualityLevel"` // Controls the target quality for the video encode. Applies only when the rate @@ -11574,6 +12370,9 @@ func (s *H264Settings) Validate() error { if s.ParDenominator != nil && *s.ParDenominator < 1 { invalidParams.Add(request.NewErrParamMinValue("ParDenominator", 1)) } + if s.ParNumerator != nil && *s.ParNumerator < 1 { + invalidParams.Add(request.NewErrParamMinValue("ParNumerator", 1)) + } if s.QvbrQualityLevel != nil && *s.QvbrQualityLevel < 1 { invalidParams.Add(request.NewErrParamMinValue("QvbrQualityLevel", 1)) } @@ -11884,6 +12683,30 @@ func (s *H265ColorSpaceSettings) SetRec709Settings(v *Rec709Settings) *H265Color return s } +// H265 Filter Settings +type H265FilterSettings struct { + _ struct{} `type:"structure"` + + // Temporal Filter Settings + TemporalFilterSettings *TemporalFilterSettings `locationName:"temporalFilterSettings" type:"structure"` +} + +// String returns the string representation +func (s H265FilterSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s H265FilterSettings) GoString() string { + return s.String() +} + +// SetTemporalFilterSettings sets the TemporalFilterSettings field's value. +func (s *H265FilterSettings) SetTemporalFilterSettings(v *TemporalFilterSettings) *H265FilterSettings { + s.TemporalFilterSettings = v + return s +} + // H265 Settings type H265Settings struct { _ struct{} `type:"structure"` @@ -11917,6 +12740,9 @@ type H265Settings struct { // Color Space settings ColorSpaceSettings *H265ColorSpaceSettings `locationName:"colorSpaceSettings" type:"structure"` + // Optional filters that you can apply to an encode. + FilterSettings *H265FilterSettings `locationName:"filterSettings" type:"structure"` + // Four bit AFD value to write on all frames of video in the output stream. // Only valid when afdSignaling is set to 'Fixed'. FixedAfd *string `locationName:"fixedAfd" type:"string" enum:"FixedAfd"` @@ -11991,7 +12817,10 @@ type H265Settings struct { // when it is constrained by themaximum bitrate. Recommended if you or your // viewers pay for bandwidth.CBR: Quality varies, depending on the video complexity. // Recommended only if you distributeyour assets to devices that cannot handle - // variable bitrates. + // variable bitrates.Multiplex: This rate control mode is only supported (and + // is required) when the video is beingdelivered to a MediaLive Multiplex in + // which case the rate control configuration is controlledby the properties + // within the Multiplex Program. RateControlMode *string `locationName:"rateControlMode" type:"string" enum:"H265RateControlMode"` // Sets the scan type of the output to progressive or top-field-first interlaced. @@ -12111,6 +12940,12 @@ func (s *H265Settings) SetColorSpaceSettings(v *H265ColorSpaceSettings) *H265Set return s } +// SetFilterSettings sets the FilterSettings field's value. +func (s *H265Settings) SetFilterSettings(v *H265FilterSettings) *H265Settings { + s.FilterSettings = v + return s +} + // SetFixedAfd sets the FixedAfd field's value. func (s *H265Settings) SetFixedAfd(v string) *H265Settings { s.FixedAfd = &v @@ -12604,9 +13439,9 @@ type HlsGroupSettings struct { // converting it to a "VOD" type manifest on completion of the stream. Mode *string `locationName:"mode" type:"string" enum:"HlsMode"` - // MANIFESTSANDSEGMENTS: Generates manifests (master manifest, if applicable, - // and media manifests) for this output group.VARIANTMANIFESTSANDSEGMENTS: Generates - // media manifests for this output group, but not a master manifest.SEGMENTSONLY: + // MANIFESTS_AND_SEGMENTS: Generates manifests (master manifest, if applicable, + // and media manifests) for this output group.VARIANT_MANIFESTS_AND_SEGMENTS: + // Generates media manifests for this output group, but not a master manifest.SEGMENTS_ONLY: // Does not generate any manifests for this output group. OutputSelection *string `locationName:"outputSelection" type:"string" enum:"HlsOutputSelection"` @@ -12659,7 +13494,7 @@ type HlsGroupSettings struct { // Provides an extra millisecond delta offset to fine tune the timestamps. TimestampDeltaMilliseconds *int64 `locationName:"timestampDeltaMilliseconds" type:"integer"` - // SEGMENTEDFILES: Emit the program as segments - multiple .ts media files.SINGLEFILE: + // SEGMENTED_FILES: Emit the program as segments - multiple .ts media files.SINGLE_FILE: // Applies only if Mode field is VOD. Emit the program as a single .ts media // file. The media manifest includes #EXT-X-BYTERANGE tags to index segments // for playback. A typical use for this value is when sending the output to @@ -13405,6 +14240,9 @@ type Input struct { // value is not valid because the channel requires two sources in the input. InputClass *string `locationName:"inputClass" type:"string" enum:"InputClass"` + // Settings for the input devices. + InputDevices []*InputDeviceSettings `locationName:"inputDevices" type:"list"` + // Certain pull input sources can be dynamic, meaning that they can have their // URL's dynamically changesduring input switch actions. Presently, this functionality // only works with MP4_FILE inputs. @@ -13474,6 +14312,12 @@ func (s *Input) SetInputClass(v string) *Input { return s } +// SetInputDevices sets the InputDevices field's value. +func (s *Input) SetInputDevices(v []*InputDeviceSettings) *Input { + s.InputDevices = v + return s +} + // SetInputSourceType sets the InputSourceType field's value. func (s *Input) SetInputSourceType(v string) *Input { s.InputSourceType = &v @@ -13824,230 +14668,639 @@ func (s *InputDestinationVpc) SetNetworkInterfaceId(v string) *InputDestinationV return s } -// Input Location -type InputLocation struct { +// Configurable settings for the input device. +type InputDeviceConfigurableSettings struct { _ struct{} `type:"structure"` - // key used to extract the password from EC2 Parameter store - PasswordParam *string `locationName:"passwordParam" type:"string"` - - // Uniform Resource Identifier - This should be a path to a file accessible - // to the Live system (eg. a http:// URI) depending on the output type. For - // example, a RTMP destination should have a uri simliar to: "rtmp://fmsserver/live". - // - // Uri is a required field - Uri *string `locationName:"uri" type:"string" required:"true"` + // The input source that you want to use. If the device has a source connected + // to only one of its input ports, or if you don't care which source the device + // sends, specify Auto. If the device has sources connected to both its input + // ports, and you want to use a specific source, specify the source. + ConfiguredInput *string `locationName:"configuredInput" type:"string" enum:"InputDeviceConfiguredInput"` - // Username if credentials are required to access a file or publishing point. - // This can be either a plaintext username, or a reference to an AWS parameter - // store name from which the username can be retrieved. AWS Parameter store - // format: "ssm://" - Username *string `locationName:"username" type:"string"` + // The maximum bitrate in bits per second. Set a value here to throttle the + // bitrate of the source video. + MaxBitrate *int64 `locationName:"maxBitrate" type:"integer"` } // String returns the string representation -func (s InputLocation) String() string { +func (s InputDeviceConfigurableSettings) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InputLocation) GoString() string { +func (s InputDeviceConfigurableSettings) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *InputLocation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InputLocation"} - if s.Uri == nil { - invalidParams.Add(request.NewErrParamRequired("Uri")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPasswordParam sets the PasswordParam field's value. -func (s *InputLocation) SetPasswordParam(v string) *InputLocation { - s.PasswordParam = &v - return s -} - -// SetUri sets the Uri field's value. -func (s *InputLocation) SetUri(v string) *InputLocation { - s.Uri = &v +// SetConfiguredInput sets the ConfiguredInput field's value. +func (s *InputDeviceConfigurableSettings) SetConfiguredInput(v string) *InputDeviceConfigurableSettings { + s.ConfiguredInput = &v return s } -// SetUsername sets the Username field's value. -func (s *InputLocation) SetUsername(v string) *InputLocation { - s.Username = &v +// SetMaxBitrate sets the MaxBitrate field's value. +func (s *InputDeviceConfigurableSettings) SetMaxBitrate(v int64) *InputDeviceConfigurableSettings { + s.MaxBitrate = &v return s } -// Input Loss Behavior -type InputLossBehavior struct { +// Settings that describe the active source from the input device, and the video +// characteristics of that source. +type InputDeviceHdSettings struct { _ struct{} `type:"structure"` - // On input loss, the number of milliseconds to substitute black into the output - // before switching to the frame specified by inputLossImageType. A value x, - // where 0 <= x <= 1,000,000 and a value of 1,000,000 will be interpreted as - // infinite. - BlackFrameMsec *int64 `locationName:"blackFrameMsec" type:"integer"` + // If you specified Auto as the configured input, specifies which of the sources + // is currently active (SDI or HDMI). + ActiveInput *string `locationName:"activeInput" type:"string" enum:"InputDeviceActiveInput"` - // When input loss image type is "color" this field specifies the color to use. - // Value: 6 hex characters representing the values of RGB. - InputLossImageColor *string `locationName:"inputLossImageColor" min:"6" type:"string"` + // The source at the input device that is currently active. You can specify + // this source. + ConfiguredInput *string `locationName:"configuredInput" type:"string" enum:"InputDeviceConfiguredInput"` - // When input loss image type is "slate" these fields specify the parameters - // for accessing the slate. - InputLossImageSlate *InputLocation `locationName:"inputLossImageSlate" type:"structure"` + // The state of the input device. + DeviceState *string `locationName:"deviceState" type:"string" enum:"InputDeviceState"` - // Indicates whether to substitute a solid color or a slate into the output - // after input loss exceeds blackFrameMsec. - InputLossImageType *string `locationName:"inputLossImageType" type:"string" enum:"InputLossImageType"` + // The frame rate of the video source. + Framerate *float64 `locationName:"framerate" type:"double"` - // On input loss, the number of milliseconds to repeat the previous picture - // before substituting black into the output. A value x, where 0 <= x <= 1,000,000 - // and a value of 1,000,000 will be interpreted as infinite. - RepeatFrameMsec *int64 `locationName:"repeatFrameMsec" type:"integer"` + // The height of the video source, in pixels. + Height *int64 `locationName:"height" type:"integer"` + + // The current maximum bitrate for ingesting this source, in bits per second. + // You can specify this maximum. + MaxBitrate *int64 `locationName:"maxBitrate" type:"integer"` + + // The scan type of the video source. + ScanType *string `locationName:"scanType" type:"string" enum:"InputDeviceScanType"` + + // The width of the video source, in pixels. + Width *int64 `locationName:"width" type:"integer"` } // String returns the string representation -func (s InputLossBehavior) String() string { +func (s InputDeviceHdSettings) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InputLossBehavior) GoString() string { +func (s InputDeviceHdSettings) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *InputLossBehavior) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InputLossBehavior"} - if s.InputLossImageColor != nil && len(*s.InputLossImageColor) < 6 { - invalidParams.Add(request.NewErrParamMinLen("InputLossImageColor", 6)) - } - if s.InputLossImageSlate != nil { - if err := s.InputLossImageSlate.Validate(); err != nil { - invalidParams.AddNested("InputLossImageSlate", err.(request.ErrInvalidParams)) - } - } +// SetActiveInput sets the ActiveInput field's value. +func (s *InputDeviceHdSettings) SetActiveInput(v string) *InputDeviceHdSettings { + s.ActiveInput = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetConfiguredInput sets the ConfiguredInput field's value. +func (s *InputDeviceHdSettings) SetConfiguredInput(v string) *InputDeviceHdSettings { + s.ConfiguredInput = &v + return s } -// SetBlackFrameMsec sets the BlackFrameMsec field's value. -func (s *InputLossBehavior) SetBlackFrameMsec(v int64) *InputLossBehavior { - s.BlackFrameMsec = &v +// SetDeviceState sets the DeviceState field's value. +func (s *InputDeviceHdSettings) SetDeviceState(v string) *InputDeviceHdSettings { + s.DeviceState = &v return s } -// SetInputLossImageColor sets the InputLossImageColor field's value. -func (s *InputLossBehavior) SetInputLossImageColor(v string) *InputLossBehavior { - s.InputLossImageColor = &v +// SetFramerate sets the Framerate field's value. +func (s *InputDeviceHdSettings) SetFramerate(v float64) *InputDeviceHdSettings { + s.Framerate = &v return s } -// SetInputLossImageSlate sets the InputLossImageSlate field's value. -func (s *InputLossBehavior) SetInputLossImageSlate(v *InputLocation) *InputLossBehavior { - s.InputLossImageSlate = v +// SetHeight sets the Height field's value. +func (s *InputDeviceHdSettings) SetHeight(v int64) *InputDeviceHdSettings { + s.Height = &v return s } -// SetInputLossImageType sets the InputLossImageType field's value. -func (s *InputLossBehavior) SetInputLossImageType(v string) *InputLossBehavior { - s.InputLossImageType = &v +// SetMaxBitrate sets the MaxBitrate field's value. +func (s *InputDeviceHdSettings) SetMaxBitrate(v int64) *InputDeviceHdSettings { + s.MaxBitrate = &v return s } -// SetRepeatFrameMsec sets the RepeatFrameMsec field's value. -func (s *InputLossBehavior) SetRepeatFrameMsec(v int64) *InputLossBehavior { - s.RepeatFrameMsec = &v +// SetScanType sets the ScanType field's value. +func (s *InputDeviceHdSettings) SetScanType(v string) *InputDeviceHdSettings { + s.ScanType = &v return s } -// An Input Security Group -type InputSecurityGroup struct { - _ struct{} `type:"structure"` +// SetWidth sets the Width field's value. +func (s *InputDeviceHdSettings) SetWidth(v int64) *InputDeviceHdSettings { + s.Width = &v + return s +} - // Unique ARN of Input Security Group - Arn *string `locationName:"arn" type:"string"` +// The network settings for the input device. +type InputDeviceNetworkSettings struct { + _ struct{} `type:"structure"` - // The Id of the Input Security Group - Id *string `locationName:"id" type:"string"` + // The DNS addresses of the input device. + DnsAddresses []*string `locationName:"dnsAddresses" type:"list"` - // The list of inputs currently using this Input Security Group. - Inputs []*string `locationName:"inputs" type:"list"` + // The network gateway IP address. + Gateway *string `locationName:"gateway" type:"string"` - // The current state of the Input Security Group. - State *string `locationName:"state" type:"string" enum:"InputSecurityGroupState"` + // The IP address of the input device. + IpAddress *string `locationName:"ipAddress" type:"string"` - // A collection of key-value pairs. - Tags map[string]*string `locationName:"tags" type:"map"` + // Specifies whether the input device has been configured (outside of MediaLive) + // to use a dynamic IP address assignment (DHCP) or a static IP address. + IpScheme *string `locationName:"ipScheme" type:"string" enum:"InputDeviceIpScheme"` - // Whitelist rules and their sync status - WhitelistRules []*InputWhitelistRule `locationName:"whitelistRules" type:"list"` + // The subnet mask of the input device. + SubnetMask *string `locationName:"subnetMask" type:"string"` } // String returns the string representation -func (s InputSecurityGroup) String() string { +func (s InputDeviceNetworkSettings) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InputSecurityGroup) GoString() string { +func (s InputDeviceNetworkSettings) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *InputSecurityGroup) SetArn(v string) *InputSecurityGroup { - s.Arn = &v +// SetDnsAddresses sets the DnsAddresses field's value. +func (s *InputDeviceNetworkSettings) SetDnsAddresses(v []*string) *InputDeviceNetworkSettings { + s.DnsAddresses = v return s } -// SetId sets the Id field's value. -func (s *InputSecurityGroup) SetId(v string) *InputSecurityGroup { - s.Id = &v +// SetGateway sets the Gateway field's value. +func (s *InputDeviceNetworkSettings) SetGateway(v string) *InputDeviceNetworkSettings { + s.Gateway = &v return s } -// SetInputs sets the Inputs field's value. -func (s *InputSecurityGroup) SetInputs(v []*string) *InputSecurityGroup { - s.Inputs = v +// SetIpAddress sets the IpAddress field's value. +func (s *InputDeviceNetworkSettings) SetIpAddress(v string) *InputDeviceNetworkSettings { + s.IpAddress = &v return s } -// SetState sets the State field's value. -func (s *InputSecurityGroup) SetState(v string) *InputSecurityGroup { - s.State = &v +// SetIpScheme sets the IpScheme field's value. +func (s *InputDeviceNetworkSettings) SetIpScheme(v string) *InputDeviceNetworkSettings { + s.IpScheme = &v return s } -// SetTags sets the Tags field's value. -func (s *InputSecurityGroup) SetTags(v map[string]*string) *InputSecurityGroup { - s.Tags = v +// SetSubnetMask sets the SubnetMask field's value. +func (s *InputDeviceNetworkSettings) SetSubnetMask(v string) *InputDeviceNetworkSettings { + s.SubnetMask = &v return s } -// SetWhitelistRules sets the WhitelistRules field's value. -func (s *InputSecurityGroup) SetWhitelistRules(v []*InputWhitelistRule) *InputSecurityGroup { - s.WhitelistRules = v +// Settings for an input device. +type InputDeviceRequest struct { + _ struct{} `type:"structure"` + + // The unique ID for the device. + Id *string `locationName:"id" type:"string"` +} + +// String returns the string representation +func (s InputDeviceRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InputDeviceRequest) GoString() string { + return s.String() +} + +// SetId sets the Id field's value. +func (s *InputDeviceRequest) SetId(v string) *InputDeviceRequest { + s.Id = &v return s } -// Live Event input parameters. There can be multiple inputs in a single Live -// Event. -type InputSettings struct { +// Settings for an input device. +type InputDeviceSettings struct { _ struct{} `type:"structure"` - // Used to select the audio stream to decode for inputs that have multiple available. - AudioSelectors []*AudioSelector `locationName:"audioSelectors" type:"list"` + // The unique ID for the device. + Id *string `locationName:"id" type:"string"` +} + +// String returns the string representation +func (s InputDeviceSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InputDeviceSettings) GoString() string { + return s.String() +} + +// SetId sets the Id field's value. +func (s *InputDeviceSettings) SetId(v string) *InputDeviceSettings { + s.Id = &v + return s +} + +// Details of the input device. +type InputDeviceSummary struct { + _ struct{} `type:"structure"` + + // The unique ARN of the input device. + Arn *string `locationName:"arn" type:"string"` + + // The state of the connection between the input device and AWS. + ConnectionState *string `locationName:"connectionState" type:"string" enum:"InputDeviceConnectionState"` + + // The status of the action to synchronize the device configuration. If you + // change the configuration of the input device (for example, the maximum bitrate), + // MediaLive sends the new data to the device. The device might not update itself + // immediately. SYNCED means the device has updated its configuration. SYNCING + // means that it has not updated its configuration. + DeviceSettingsSyncState *string `locationName:"deviceSettingsSyncState" type:"string" enum:"DeviceSettingsSyncState"` + + // Settings that describe an input device that is type HD. + HdDeviceSettings *InputDeviceHdSettings `locationName:"hdDeviceSettings" type:"structure"` + + // The unique ID of the input device. + Id *string `locationName:"id" type:"string"` + + // The network MAC address of the input device. + MacAddress *string `locationName:"macAddress" type:"string"` + + // A name that you specify for the input device. + Name *string `locationName:"name" type:"string"` + + // Network settings for the input device. + NetworkSettings *InputDeviceNetworkSettings `locationName:"networkSettings" type:"structure"` + + // The unique serial number of the input device. + SerialNumber *string `locationName:"serialNumber" type:"string"` + + // The type of the input device. + Type *string `locationName:"type" type:"string" enum:"InputDeviceType"` +} + +// String returns the string representation +func (s InputDeviceSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InputDeviceSummary) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *InputDeviceSummary) SetArn(v string) *InputDeviceSummary { + s.Arn = &v + return s +} + +// SetConnectionState sets the ConnectionState field's value. +func (s *InputDeviceSummary) SetConnectionState(v string) *InputDeviceSummary { + s.ConnectionState = &v + return s +} + +// SetDeviceSettingsSyncState sets the DeviceSettingsSyncState field's value. +func (s *InputDeviceSummary) SetDeviceSettingsSyncState(v string) *InputDeviceSummary { + s.DeviceSettingsSyncState = &v + return s +} + +// SetHdDeviceSettings sets the HdDeviceSettings field's value. +func (s *InputDeviceSummary) SetHdDeviceSettings(v *InputDeviceHdSettings) *InputDeviceSummary { + s.HdDeviceSettings = v + return s +} + +// SetId sets the Id field's value. +func (s *InputDeviceSummary) SetId(v string) *InputDeviceSummary { + s.Id = &v + return s +} + +// SetMacAddress sets the MacAddress field's value. +func (s *InputDeviceSummary) SetMacAddress(v string) *InputDeviceSummary { + s.MacAddress = &v + return s +} + +// SetName sets the Name field's value. +func (s *InputDeviceSummary) SetName(v string) *InputDeviceSummary { + s.Name = &v + return s +} + +// SetNetworkSettings sets the NetworkSettings field's value. +func (s *InputDeviceSummary) SetNetworkSettings(v *InputDeviceNetworkSettings) *InputDeviceSummary { + s.NetworkSettings = v + return s +} + +// SetSerialNumber sets the SerialNumber field's value. +func (s *InputDeviceSummary) SetSerialNumber(v string) *InputDeviceSummary { + s.SerialNumber = &v + return s +} + +// SetType sets the Type field's value. +func (s *InputDeviceSummary) SetType(v string) *InputDeviceSummary { + s.Type = &v + return s +} + +// Input Location +type InputLocation struct { + _ struct{} `type:"structure"` + + // key used to extract the password from EC2 Parameter store + PasswordParam *string `locationName:"passwordParam" type:"string"` + + // Uniform Resource Identifier - This should be a path to a file accessible + // to the Live system (eg. a http:// URI) depending on the output type. For + // example, a RTMP destination should have a uri simliar to: "rtmp://fmsserver/live". + // + // Uri is a required field + Uri *string `locationName:"uri" type:"string" required:"true"` + + // Username if credentials are required to access a file or publishing point. + // This can be either a plaintext username, or a reference to an AWS parameter + // store name from which the username can be retrieved. AWS Parameter store + // format: "ssm://" + Username *string `locationName:"username" type:"string"` +} + +// String returns the string representation +func (s InputLocation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InputLocation) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *InputLocation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InputLocation"} + if s.Uri == nil { + invalidParams.Add(request.NewErrParamRequired("Uri")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetPasswordParam sets the PasswordParam field's value. +func (s *InputLocation) SetPasswordParam(v string) *InputLocation { + s.PasswordParam = &v + return s +} + +// SetUri sets the Uri field's value. +func (s *InputLocation) SetUri(v string) *InputLocation { + s.Uri = &v + return s +} + +// SetUsername sets the Username field's value. +func (s *InputLocation) SetUsername(v string) *InputLocation { + s.Username = &v + return s +} + +// Input Loss Behavior +type InputLossBehavior struct { + _ struct{} `type:"structure"` + + // On input loss, the number of milliseconds to substitute black into the output + // before switching to the frame specified by inputLossImageType. A value x, + // where 0 <= x <= 1,000,000 and a value of 1,000,000 will be interpreted as + // infinite. + BlackFrameMsec *int64 `locationName:"blackFrameMsec" type:"integer"` + + // When input loss image type is "color" this field specifies the color to use. + // Value: 6 hex characters representing the values of RGB. + InputLossImageColor *string `locationName:"inputLossImageColor" min:"6" type:"string"` + + // When input loss image type is "slate" these fields specify the parameters + // for accessing the slate. + InputLossImageSlate *InputLocation `locationName:"inputLossImageSlate" type:"structure"` + + // Indicates whether to substitute a solid color or a slate into the output + // after input loss exceeds blackFrameMsec. + InputLossImageType *string `locationName:"inputLossImageType" type:"string" enum:"InputLossImageType"` + + // On input loss, the number of milliseconds to repeat the previous picture + // before substituting black into the output. A value x, where 0 <= x <= 1,000,000 + // and a value of 1,000,000 will be interpreted as infinite. + RepeatFrameMsec *int64 `locationName:"repeatFrameMsec" type:"integer"` +} + +// String returns the string representation +func (s InputLossBehavior) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InputLossBehavior) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *InputLossBehavior) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InputLossBehavior"} + if s.InputLossImageColor != nil && len(*s.InputLossImageColor) < 6 { + invalidParams.Add(request.NewErrParamMinLen("InputLossImageColor", 6)) + } + if s.InputLossImageSlate != nil { + if err := s.InputLossImageSlate.Validate(); err != nil { + invalidParams.AddNested("InputLossImageSlate", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBlackFrameMsec sets the BlackFrameMsec field's value. +func (s *InputLossBehavior) SetBlackFrameMsec(v int64) *InputLossBehavior { + s.BlackFrameMsec = &v + return s +} + +// SetInputLossImageColor sets the InputLossImageColor field's value. +func (s *InputLossBehavior) SetInputLossImageColor(v string) *InputLossBehavior { + s.InputLossImageColor = &v + return s +} + +// SetInputLossImageSlate sets the InputLossImageSlate field's value. +func (s *InputLossBehavior) SetInputLossImageSlate(v *InputLocation) *InputLossBehavior { + s.InputLossImageSlate = v + return s +} + +// SetInputLossImageType sets the InputLossImageType field's value. +func (s *InputLossBehavior) SetInputLossImageType(v string) *InputLossBehavior { + s.InputLossImageType = &v + return s +} + +// SetRepeatFrameMsec sets the RepeatFrameMsec field's value. +func (s *InputLossBehavior) SetRepeatFrameMsec(v int64) *InputLossBehavior { + s.RepeatFrameMsec = &v + return s +} + +// Action to prepare an input for a future immediate input switch. +type InputPrepareScheduleActionSettings struct { + _ struct{} `type:"structure"` + + // The name of the input attachment that should be prepared by this action. + // If no name is provided, the action will stop the most recent prepare (if + // any) when activated. + InputAttachmentNameReference *string `locationName:"inputAttachmentNameReference" type:"string"` + + // Settings to let you create a clip of the file input, in order to set up the + // input to ingest only a portion of the file. + InputClippingSettings *InputClippingSettings `locationName:"inputClippingSettings" type:"structure"` + + // The value for the variable portion of the URL for the dynamic input, for + // this instance of the input. Each time you use the same dynamic input in an + // input switch action, you can provide a different value, in order to connect + // the input to a different content source. + UrlPath []*string `locationName:"urlPath" type:"list"` +} + +// String returns the string representation +func (s InputPrepareScheduleActionSettings) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InputPrepareScheduleActionSettings) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *InputPrepareScheduleActionSettings) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InputPrepareScheduleActionSettings"} + if s.InputClippingSettings != nil { + if err := s.InputClippingSettings.Validate(); err != nil { + invalidParams.AddNested("InputClippingSettings", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetInputAttachmentNameReference sets the InputAttachmentNameReference field's value. +func (s *InputPrepareScheduleActionSettings) SetInputAttachmentNameReference(v string) *InputPrepareScheduleActionSettings { + s.InputAttachmentNameReference = &v + return s +} + +// SetInputClippingSettings sets the InputClippingSettings field's value. +func (s *InputPrepareScheduleActionSettings) SetInputClippingSettings(v *InputClippingSettings) *InputPrepareScheduleActionSettings { + s.InputClippingSettings = v + return s +} + +// SetUrlPath sets the UrlPath field's value. +func (s *InputPrepareScheduleActionSettings) SetUrlPath(v []*string) *InputPrepareScheduleActionSettings { + s.UrlPath = v + return s +} + +// An Input Security Group +type InputSecurityGroup struct { + _ struct{} `type:"structure"` + + // Unique ARN of Input Security Group + Arn *string `locationName:"arn" type:"string"` + + // The Id of the Input Security Group + Id *string `locationName:"id" type:"string"` + + // The list of inputs currently using this Input Security Group. + Inputs []*string `locationName:"inputs" type:"list"` + + // The current state of the Input Security Group. + State *string `locationName:"state" type:"string" enum:"InputSecurityGroupState"` + + // A collection of key-value pairs. + Tags map[string]*string `locationName:"tags" type:"map"` + + // Whitelist rules and their sync status + WhitelistRules []*InputWhitelistRule `locationName:"whitelistRules" type:"list"` +} + +// String returns the string representation +func (s InputSecurityGroup) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InputSecurityGroup) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *InputSecurityGroup) SetArn(v string) *InputSecurityGroup { + s.Arn = &v + return s +} + +// SetId sets the Id field's value. +func (s *InputSecurityGroup) SetId(v string) *InputSecurityGroup { + s.Id = &v + return s +} + +// SetInputs sets the Inputs field's value. +func (s *InputSecurityGroup) SetInputs(v []*string) *InputSecurityGroup { + s.Inputs = v + return s +} + +// SetState sets the State field's value. +func (s *InputSecurityGroup) SetState(v string) *InputSecurityGroup { + s.State = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *InputSecurityGroup) SetTags(v map[string]*string) *InputSecurityGroup { + s.Tags = v + return s +} + +// SetWhitelistRules sets the WhitelistRules field's value. +func (s *InputSecurityGroup) SetWhitelistRules(v []*InputWhitelistRule) *InputSecurityGroup { + s.WhitelistRules = v + return s +} + +// Live Event input parameters. There can be multiple inputs in a single Live +// Event. +type InputSettings struct { + _ struct{} `type:"structure"` + + // Used to select the audio stream to decode for inputs that have multiple available. + AudioSelectors []*AudioSelector `locationName:"audioSelectors" type:"list"` // Used to select the caption input to use for inputs that have multiple available. CaptionSelectors []*CaptionSelector `locationName:"captionSelectors" type:"list"` @@ -14070,6 +15323,13 @@ type InputSettings struct { // Input settings. NetworkInputSettings *NetworkInputSettings `locationName:"networkInputSettings" type:"structure"` + // Specifies whether to extract applicable ancillary data from a SMPTE-2038 + // source in this input. Applicable data types are captions, timecode, AFD, + // and SCTE-104 messages.- PREFER: Extract from SMPTE-2038 if present in this + // input, otherwise extract from another source (if any).- IGNORE: Never extract + // any ancillary data from SMPTE-2038. + Smpte2038DataPreference *string `locationName:"smpte2038DataPreference" type:"string" enum:"Smpte2038DataPreference"` + // Loop input if it is a file. This allows a file input to be streamed indefinitely. SourceEndBehavior *string `locationName:"sourceEndBehavior" type:"string" enum:"InputSourceEndBehavior"` @@ -14163,6 +15423,12 @@ func (s *InputSettings) SetNetworkInputSettings(v *NetworkInputSettings) *InputS return s } +// SetSmpte2038DataPreference sets the Smpte2038DataPreference field's value. +func (s *InputSettings) SetSmpte2038DataPreference(v string) *InputSettings { + s.Smpte2038DataPreference = &v + return s +} + // SetSourceEndBehavior sets the SourceEndBehavior field's value. func (s *InputSettings) SetSourceEndBehavior(v string) *InputSettings { s.SourceEndBehavior = &v @@ -14637,6 +15903,79 @@ func (s *ListChannelsOutput) SetNextToken(v string) *ListChannelsOutput { return s } +type ListInputDevicesInput struct { + _ struct{} `type:"structure"` + + MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` + + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s ListInputDevicesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListInputDevicesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListInputDevicesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListInputDevicesInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListInputDevicesInput) SetMaxResults(v int64) *ListInputDevicesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListInputDevicesInput) SetNextToken(v string) *ListInputDevicesInput { + s.NextToken = &v + return s +} + +type ListInputDevicesOutput struct { + _ struct{} `type:"structure"` + + InputDevices []*InputDeviceSummary `locationName:"inputDevices" type:"list"` + + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s ListInputDevicesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListInputDevicesOutput) GoString() string { + return s.String() +} + +// SetInputDevices sets the InputDevices field's value. +func (s *ListInputDevicesOutput) SetInputDevices(v []*InputDeviceSummary) *ListInputDevicesOutput { + s.InputDevices = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListInputDevicesOutput) SetNextToken(v string) *ListInputDevicesOutput { + s.NextToken = &v + return s +} + type ListInputSecurityGroupsInput struct { _ struct{} `type:"structure"` @@ -15505,7 +16844,7 @@ type M2tsSettings struct { SegmentationStyle *string `locationName:"segmentationStyle" type:"string" enum:"M2tsSegmentationStyle"` // The length in seconds of each segment. Required unless markers is set to - // None_. + // _none_. SegmentationTime *float64 `locationName:"segmentationTime" type:"double"` // When set to passthrough, timed metadata will be passed through from input @@ -16218,8 +17557,8 @@ func (s *Mp2Settings) SetSampleRate(v float64) *Mp2Settings { type MsSmoothGroupSettings struct { _ struct{} `type:"structure"` - // The value of the "Acquisition Point Identity" element used in each message - // placed in the sparse track. Only enabled if sparseTrackType is not "none". + // The ID to include in each message in the sparse track. Ignored if sparseTrackType + // is NONE. AcquisitionPointId *string `locationName:"acquisitionPointId" type:"string"` // If set to passthrough for an audio-only MS Smooth output, the fragment absolute @@ -16282,10 +17621,12 @@ type MsSmoothGroupSettings struct { // Number of milliseconds to delay the output from the second pipeline. SendDelayMs *int64 `locationName:"sendDelayMs" type:"integer"` - // If set to scte35, use incoming SCTE-35 messages to generate a sparse track - // in this group of MS-Smooth outputs. scte35WithoutSegmentation is the same - // as scte35, except EML will not start a new segment at a SCTE-35 marker. It - // will still encode an IDR frame at a SCTE-35 marker. + // Identifies the type of data to place in the sparse track:- SCTE35: Insert + // SCTE-35 messages from the source content. With each message, insert an IDR + // frame to start a new segment.- SCTE35_WITHOUT_SEGMENTATION: Insert SCTE-35 + // messages from the source content. With each message, insert an IDR frame + // but don't start a new segment.- NONE: Don't generate a sparse track for any + // outputs in this output group. SparseTrackType *string `locationName:"sparseTrackType" type:"string" enum:"SmoothGroupSparseTrackType"` // When set to send, send stream manifest so publishing point doesn't start @@ -19062,6 +20403,9 @@ type ScheduleActionSettings struct { // Action to insert HLS metadata HlsTimedMetadataSettings *HlsTimedMetadataScheduleActionSettings `locationName:"hlsTimedMetadataSettings" type:"structure"` + // Action to prepare an input for a future immediate input switch + InputPrepareSettings *InputPrepareScheduleActionSettings `locationName:"inputPrepareSettings" type:"structure"` + // Action to switch the input InputSwitchSettings *InputSwitchScheduleActionSettings `locationName:"inputSwitchSettings" type:"structure"` @@ -19107,6 +20451,11 @@ func (s *ScheduleActionSettings) Validate() error { invalidParams.AddNested("HlsTimedMetadataSettings", err.(request.ErrInvalidParams)) } } + if s.InputPrepareSettings != nil { + if err := s.InputPrepareSettings.Validate(); err != nil { + invalidParams.AddNested("InputPrepareSettings", err.(request.ErrInvalidParams)) + } + } if s.InputSwitchSettings != nil { if err := s.InputSwitchSettings.Validate(); err != nil { invalidParams.AddNested("InputSwitchSettings", err.(request.ErrInvalidParams)) @@ -19156,6 +20505,12 @@ func (s *ScheduleActionSettings) SetHlsTimedMetadataSettings(v *HlsTimedMetadata return s } +// SetInputPrepareSettings sets the InputPrepareSettings field's value. +func (s *ScheduleActionSettings) SetInputPrepareSettings(v *InputPrepareScheduleActionSettings) *ScheduleActionSettings { + s.InputPrepareSettings = v + return s +} + // SetInputSwitchSettings sets the InputSwitchSettings field's value. func (s *ScheduleActionSettings) SetInputSwitchSettings(v *InputSwitchScheduleActionSettings) *ScheduleActionSettings { s.InputSwitchSettings = v @@ -21008,12 +22363,14 @@ func (s *TeletextSourceSettings) SetPageNumber(v string) *TeletextSourceSettings type TemporalFilterSettings struct { _ struct{} `type:"structure"` - // If set to "ENABLED," applies post-filter sharpening to improve visual quality. - // This is most beneficial when using a noisy or compressed input source and - // low output bitrates. + // If you enable this filter, the results are the following:- If the source + // content is noisy (it contains excessive digital artifacts), the filter cleans + // up the source.- If the source content is already clean, the filter tends + // to decrease the bitrate, especially when the rate control mode is QVBR. PostFilterSharpening *string `locationName:"postFilterSharpening" type:"string" enum:"TemporalFilterPostFilterSharpening"` - // Filter strength. A higher value produces stronger filtering. + // Choose a filter strength. We recommend a strength of 1 or 2. A higher strength + // might take out good information, resulting in an image that is overly soft. Strength *string `locationName:"strength" type:"string" enum:"TemporalFilterStrength"` } @@ -21646,11 +23003,174 @@ func (s *UpdateChannelOutput) SetChannel(v *Channel) *UpdateChannelOutput { return s } +type UpdateInputDeviceInput struct { + _ struct{} `type:"structure"` + + // Configurable settings for the input device. + HdDeviceSettings *InputDeviceConfigurableSettings `locationName:"hdDeviceSettings" type:"structure"` + + // InputDeviceId is a required field + InputDeviceId *string `location:"uri" locationName:"inputDeviceId" type:"string" required:"true"` + + Name *string `locationName:"name" type:"string"` +} + +// String returns the string representation +func (s UpdateInputDeviceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateInputDeviceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateInputDeviceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateInputDeviceInput"} + if s.InputDeviceId == nil { + invalidParams.Add(request.NewErrParamRequired("InputDeviceId")) + } + if s.InputDeviceId != nil && len(*s.InputDeviceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("InputDeviceId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetHdDeviceSettings sets the HdDeviceSettings field's value. +func (s *UpdateInputDeviceInput) SetHdDeviceSettings(v *InputDeviceConfigurableSettings) *UpdateInputDeviceInput { + s.HdDeviceSettings = v + return s +} + +// SetInputDeviceId sets the InputDeviceId field's value. +func (s *UpdateInputDeviceInput) SetInputDeviceId(v string) *UpdateInputDeviceInput { + s.InputDeviceId = &v + return s +} + +// SetName sets the Name field's value. +func (s *UpdateInputDeviceInput) SetName(v string) *UpdateInputDeviceInput { + s.Name = &v + return s +} + +type UpdateInputDeviceOutput struct { + _ struct{} `type:"structure"` + + Arn *string `locationName:"arn" type:"string"` + + // The state of the connection between the input device and AWS. + ConnectionState *string `locationName:"connectionState" type:"string" enum:"InputDeviceConnectionState"` + + // The status of the action to synchronize the device configuration. If you + // change the configuration of the input device (for example, the maximum bitrate), + // MediaLive sends the new data to the device. The device might not update itself + // immediately. SYNCED means the device has updated its configuration. SYNCING + // means that it has not updated its configuration. + DeviceSettingsSyncState *string `locationName:"deviceSettingsSyncState" type:"string" enum:"DeviceSettingsSyncState"` + + // Settings that describe the active source from the input device, and the video + // characteristics of that source. + HdDeviceSettings *InputDeviceHdSettings `locationName:"hdDeviceSettings" type:"structure"` + + Id *string `locationName:"id" type:"string"` + + MacAddress *string `locationName:"macAddress" type:"string"` + + Name *string `locationName:"name" type:"string"` + + // The network settings for the input device. + NetworkSettings *InputDeviceNetworkSettings `locationName:"networkSettings" type:"structure"` + + SerialNumber *string `locationName:"serialNumber" type:"string"` + + // The type of the input device. For an AWS Elemental Link device that outputs + // resolutions up to 1080, choose "HD". + Type *string `locationName:"type" type:"string" enum:"InputDeviceType"` +} + +// String returns the string representation +func (s UpdateInputDeviceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateInputDeviceOutput) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *UpdateInputDeviceOutput) SetArn(v string) *UpdateInputDeviceOutput { + s.Arn = &v + return s +} + +// SetConnectionState sets the ConnectionState field's value. +func (s *UpdateInputDeviceOutput) SetConnectionState(v string) *UpdateInputDeviceOutput { + s.ConnectionState = &v + return s +} + +// SetDeviceSettingsSyncState sets the DeviceSettingsSyncState field's value. +func (s *UpdateInputDeviceOutput) SetDeviceSettingsSyncState(v string) *UpdateInputDeviceOutput { + s.DeviceSettingsSyncState = &v + return s +} + +// SetHdDeviceSettings sets the HdDeviceSettings field's value. +func (s *UpdateInputDeviceOutput) SetHdDeviceSettings(v *InputDeviceHdSettings) *UpdateInputDeviceOutput { + s.HdDeviceSettings = v + return s +} + +// SetId sets the Id field's value. +func (s *UpdateInputDeviceOutput) SetId(v string) *UpdateInputDeviceOutput { + s.Id = &v + return s +} + +// SetMacAddress sets the MacAddress field's value. +func (s *UpdateInputDeviceOutput) SetMacAddress(v string) *UpdateInputDeviceOutput { + s.MacAddress = &v + return s +} + +// SetName sets the Name field's value. +func (s *UpdateInputDeviceOutput) SetName(v string) *UpdateInputDeviceOutput { + s.Name = &v + return s +} + +// SetNetworkSettings sets the NetworkSettings field's value. +func (s *UpdateInputDeviceOutput) SetNetworkSettings(v *InputDeviceNetworkSettings) *UpdateInputDeviceOutput { + s.NetworkSettings = v + return s +} + +// SetSerialNumber sets the SerialNumber field's value. +func (s *UpdateInputDeviceOutput) SetSerialNumber(v string) *UpdateInputDeviceOutput { + s.SerialNumber = &v + return s +} + +// SetType sets the Type field's value. +func (s *UpdateInputDeviceOutput) SetType(v string) *UpdateInputDeviceOutput { + s.Type = &v + return s +} + type UpdateInputInput struct { _ struct{} `type:"structure"` Destinations []*InputDestinationRequest `locationName:"destinations" type:"list"` + InputDevices []*InputDeviceRequest `locationName:"inputDevices" type:"list"` + // InputId is a required field InputId *string `location:"uri" locationName:"inputId" type:"string" required:"true"` @@ -21697,6 +23217,12 @@ func (s *UpdateInputInput) SetDestinations(v []*InputDestinationRequest) *Update return s } +// SetInputDevices sets the InputDevices field's value. +func (s *UpdateInputInput) SetInputDevices(v []*InputDeviceRequest) *UpdateInputInput { + s.InputDevices = v + return s +} + // SetInputId sets the InputId field's value. func (s *UpdateInputInput) SetInputId(v string) *UpdateInputInput { s.InputId = &v @@ -22081,8 +23607,10 @@ func (s *UpdateReservationOutput) SetReservation(v *Reservation) *UpdateReservat type ValidationError struct { _ struct{} `type:"structure"` + // Path to the source of the error. ElementPath *string `locationName:"elementPath" type:"string"` + // The error message. ErrorMessage *string `locationName:"errorMessage" type:"string"` } @@ -22197,15 +23725,15 @@ type VideoDescription struct { // Indicates how to respond to the AFD values in the input stream. RESPOND causes // input video to be clipped, depending on the AFD value, input display aspect - // ratio, and output display aspect ratio, and (except for FRAMECAPTURE codec) - // includes the values in the output. PASSTHROUGH (does not apply to FRAMECAPTURE + // ratio, and output display aspect ratio, and (except for FRAME_CAPTURE codec) + // includes the values in the output. PASSTHROUGH (does not apply to FRAME_CAPTURE // codec) ignores the AFD values and includes the values in the output, so input // video is not clipped. NONE ignores the AFD values and does not include the // values through to the output, so input video is not clipped. RespondToAfd *string `locationName:"respondToAfd" type:"string" enum:"VideoDescriptionRespondToAfd"` - // STRETCHTOOUTPUT configures the output position to stretch the video to the - // specified output resolution (height and width). This option will override + // STRETCH_TO_OUTPUT configures the output position to stretch the video to + // the specified output resolution (height and width). This option will override // any position value. DEFAULT may insert black boxes (pillar boxes or letter // boxes) around the video to provide the specified output resolution. ScalingBehavior *string `locationName:"scalingBehavior" type:"string" enum:"VideoDescriptionScalingBehavior"` @@ -22460,6 +23988,17 @@ const ( AacCodingModeCodingMode51 = "CODING_MODE_5_1" ) +// AacCodingMode_Values returns all elements of the AacCodingMode enum +func AacCodingMode_Values() []string { + return []string{ + AacCodingModeAdReceiverMix, + AacCodingModeCodingMode10, + AacCodingModeCodingMode11, + AacCodingModeCodingMode20, + AacCodingModeCodingMode51, + } +} + // Aac Input Type const ( // AacInputTypeBroadcasterMixedAd is a AacInputType enum value @@ -22469,6 +24008,14 @@ const ( AacInputTypeNormal = "NORMAL" ) +// AacInputType_Values returns all elements of the AacInputType enum +func AacInputType_Values() []string { + return []string{ + AacInputTypeBroadcasterMixedAd, + AacInputTypeNormal, + } +} + // Aac Profile const ( // AacProfileHev1 is a AacProfile enum value @@ -22481,6 +24028,15 @@ const ( AacProfileLc = "LC" ) +// AacProfile_Values returns all elements of the AacProfile enum +func AacProfile_Values() []string { + return []string{ + AacProfileHev1, + AacProfileHev2, + AacProfileLc, + } +} + // Aac Rate Control Mode const ( // AacRateControlModeCbr is a AacRateControlMode enum value @@ -22490,6 +24046,14 @@ const ( AacRateControlModeVbr = "VBR" ) +// AacRateControlMode_Values returns all elements of the AacRateControlMode enum +func AacRateControlMode_Values() []string { + return []string{ + AacRateControlModeCbr, + AacRateControlModeVbr, + } +} + // Aac Raw Format const ( // AacRawFormatLatmLoas is a AacRawFormat enum value @@ -22499,6 +24063,14 @@ const ( AacRawFormatNone = "NONE" ) +// AacRawFormat_Values returns all elements of the AacRawFormat enum +func AacRawFormat_Values() []string { + return []string{ + AacRawFormatLatmLoas, + AacRawFormatNone, + } +} + // Aac Spec const ( // AacSpecMpeg2 is a AacSpec enum value @@ -22508,6 +24080,14 @@ const ( AacSpecMpeg4 = "MPEG4" ) +// AacSpec_Values returns all elements of the AacSpec enum +func AacSpec_Values() []string { + return []string{ + AacSpecMpeg2, + AacSpecMpeg4, + } +} + // Aac Vbr Quality const ( // AacVbrQualityHigh is a AacVbrQuality enum value @@ -22523,6 +24103,16 @@ const ( AacVbrQualityMediumLow = "MEDIUM_LOW" ) +// AacVbrQuality_Values returns all elements of the AacVbrQuality enum +func AacVbrQuality_Values() []string { + return []string{ + AacVbrQualityHigh, + AacVbrQualityLow, + AacVbrQualityMediumHigh, + AacVbrQualityMediumLow, + } +} + // Ac3 Bitstream Mode const ( // Ac3BitstreamModeCommentary is a Ac3BitstreamMode enum value @@ -22550,6 +24140,20 @@ const ( Ac3BitstreamModeVoiceOver = "VOICE_OVER" ) +// Ac3BitstreamMode_Values returns all elements of the Ac3BitstreamMode enum +func Ac3BitstreamMode_Values() []string { + return []string{ + Ac3BitstreamModeCommentary, + Ac3BitstreamModeCompleteMain, + Ac3BitstreamModeDialogue, + Ac3BitstreamModeEmergency, + Ac3BitstreamModeHearingImpaired, + Ac3BitstreamModeMusicAndEffects, + Ac3BitstreamModeVisuallyImpaired, + Ac3BitstreamModeVoiceOver, + } +} + // Ac3 Coding Mode const ( // Ac3CodingModeCodingMode10 is a Ac3CodingMode enum value @@ -22565,6 +24169,16 @@ const ( Ac3CodingModeCodingMode32Lfe = "CODING_MODE_3_2_LFE" ) +// Ac3CodingMode_Values returns all elements of the Ac3CodingMode enum +func Ac3CodingMode_Values() []string { + return []string{ + Ac3CodingModeCodingMode10, + Ac3CodingModeCodingMode11, + Ac3CodingModeCodingMode20, + Ac3CodingModeCodingMode32Lfe, + } +} + // Ac3 Drc Profile const ( // Ac3DrcProfileFilmStandard is a Ac3DrcProfile enum value @@ -22574,6 +24188,14 @@ const ( Ac3DrcProfileNone = "NONE" ) +// Ac3DrcProfile_Values returns all elements of the Ac3DrcProfile enum +func Ac3DrcProfile_Values() []string { + return []string{ + Ac3DrcProfileFilmStandard, + Ac3DrcProfileNone, + } +} + // Ac3 Lfe Filter const ( // Ac3LfeFilterDisabled is a Ac3LfeFilter enum value @@ -22583,6 +24205,14 @@ const ( Ac3LfeFilterEnabled = "ENABLED" ) +// Ac3LfeFilter_Values returns all elements of the Ac3LfeFilter enum +func Ac3LfeFilter_Values() []string { + return []string{ + Ac3LfeFilterDisabled, + Ac3LfeFilterEnabled, + } +} + // Ac3 Metadata Control const ( // Ac3MetadataControlFollowInput is a Ac3MetadataControl enum value @@ -22592,6 +24222,27 @@ const ( Ac3MetadataControlUseConfigured = "USE_CONFIGURED" ) +// Ac3MetadataControl_Values returns all elements of the Ac3MetadataControl enum +func Ac3MetadataControl_Values() []string { + return []string{ + Ac3MetadataControlFollowInput, + Ac3MetadataControlUseConfigured, + } +} + +// Accept Header +const ( + // AcceptHeaderImageJpeg is a AcceptHeader enum value + AcceptHeaderImageJpeg = "image/jpeg" +) + +// AcceptHeader_Values returns all elements of the AcceptHeader enum +func AcceptHeader_Values() []string { + return []string{ + AcceptHeaderImageJpeg, + } +} + // Afd Signaling const ( // AfdSignalingAuto is a AfdSignaling enum value @@ -22604,6 +24255,15 @@ const ( AfdSignalingNone = "NONE" ) +// AfdSignaling_Values returns all elements of the AfdSignaling enum +func AfdSignaling_Values() []string { + return []string{ + AfdSignalingAuto, + AfdSignalingFixed, + AfdSignalingNone, + } +} + // Audio Description Audio Type Control const ( // AudioDescriptionAudioTypeControlFollowInput is a AudioDescriptionAudioTypeControl enum value @@ -22613,6 +24273,14 @@ const ( AudioDescriptionAudioTypeControlUseConfigured = "USE_CONFIGURED" ) +// AudioDescriptionAudioTypeControl_Values returns all elements of the AudioDescriptionAudioTypeControl enum +func AudioDescriptionAudioTypeControl_Values() []string { + return []string{ + AudioDescriptionAudioTypeControlFollowInput, + AudioDescriptionAudioTypeControlUseConfigured, + } +} + // Audio Description Language Code Control const ( // AudioDescriptionLanguageCodeControlFollowInput is a AudioDescriptionLanguageCodeControl enum value @@ -22622,6 +24290,14 @@ const ( AudioDescriptionLanguageCodeControlUseConfigured = "USE_CONFIGURED" ) +// AudioDescriptionLanguageCodeControl_Values returns all elements of the AudioDescriptionLanguageCodeControl enum +func AudioDescriptionLanguageCodeControl_Values() []string { + return []string{ + AudioDescriptionLanguageCodeControlFollowInput, + AudioDescriptionLanguageCodeControlUseConfigured, + } +} + // Audio Language Selection Policy const ( // AudioLanguageSelectionPolicyLoose is a AudioLanguageSelectionPolicy enum value @@ -22631,6 +24307,14 @@ const ( AudioLanguageSelectionPolicyStrict = "STRICT" ) +// AudioLanguageSelectionPolicy_Values returns all elements of the AudioLanguageSelectionPolicy enum +func AudioLanguageSelectionPolicy_Values() []string { + return []string{ + AudioLanguageSelectionPolicyLoose, + AudioLanguageSelectionPolicyStrict, + } +} + // Audio Normalization Algorithm const ( // AudioNormalizationAlgorithmItu17701 is a AudioNormalizationAlgorithm enum value @@ -22640,12 +24324,27 @@ const ( AudioNormalizationAlgorithmItu17702 = "ITU_1770_2" ) +// AudioNormalizationAlgorithm_Values returns all elements of the AudioNormalizationAlgorithm enum +func AudioNormalizationAlgorithm_Values() []string { + return []string{ + AudioNormalizationAlgorithmItu17701, + AudioNormalizationAlgorithmItu17702, + } +} + // Audio Normalization Algorithm Control const ( // AudioNormalizationAlgorithmControlCorrectAudio is a AudioNormalizationAlgorithmControl enum value AudioNormalizationAlgorithmControlCorrectAudio = "CORRECT_AUDIO" ) +// AudioNormalizationAlgorithmControl_Values returns all elements of the AudioNormalizationAlgorithmControl enum +func AudioNormalizationAlgorithmControl_Values() []string { + return []string{ + AudioNormalizationAlgorithmControlCorrectAudio, + } +} + // Audio Only Hls Segment Type const ( // AudioOnlyHlsSegmentTypeAac is a AudioOnlyHlsSegmentType enum value @@ -22655,6 +24354,14 @@ const ( AudioOnlyHlsSegmentTypeFmp4 = "FMP4" ) +// AudioOnlyHlsSegmentType_Values returns all elements of the AudioOnlyHlsSegmentType enum +func AudioOnlyHlsSegmentType_Values() []string { + return []string{ + AudioOnlyHlsSegmentTypeAac, + AudioOnlyHlsSegmentTypeFmp4, + } +} + // Audio Only Hls Track Type const ( // AudioOnlyHlsTrackTypeAlternateAudioAutoSelect is a AudioOnlyHlsTrackType enum value @@ -22670,6 +24377,16 @@ const ( AudioOnlyHlsTrackTypeAudioOnlyVariantStream = "AUDIO_ONLY_VARIANT_STREAM" ) +// AudioOnlyHlsTrackType_Values returns all elements of the AudioOnlyHlsTrackType enum +func AudioOnlyHlsTrackType_Values() []string { + return []string{ + AudioOnlyHlsTrackTypeAlternateAudioAutoSelect, + AudioOnlyHlsTrackTypeAlternateAudioAutoSelectDefault, + AudioOnlyHlsTrackTypeAlternateAudioNotAutoSelect, + AudioOnlyHlsTrackTypeAudioOnlyVariantStream, + } +} + // Audio Type const ( // AudioTypeCleanEffects is a AudioType enum value @@ -22685,6 +24402,16 @@ const ( AudioTypeVisualImpairedCommentary = "VISUAL_IMPAIRED_COMMENTARY" ) +// AudioType_Values returns all elements of the AudioType enum +func AudioType_Values() []string { + return []string{ + AudioTypeCleanEffects, + AudioTypeHearingImpaired, + AudioTypeUndefined, + AudioTypeVisualImpairedCommentary, + } +} + // Authentication Scheme const ( // AuthenticationSchemeAkamai is a AuthenticationScheme enum value @@ -22694,6 +24421,14 @@ const ( AuthenticationSchemeCommon = "COMMON" ) +// AuthenticationScheme_Values returns all elements of the AuthenticationScheme enum +func AuthenticationScheme_Values() []string { + return []string{ + AuthenticationSchemeAkamai, + AuthenticationSchemeCommon, + } +} + // Avail Blanking State const ( // AvailBlankingStateDisabled is a AvailBlankingState enum value @@ -22703,6 +24438,14 @@ const ( AvailBlankingStateEnabled = "ENABLED" ) +// AvailBlankingState_Values returns all elements of the AvailBlankingState enum +func AvailBlankingState_Values() []string { + return []string{ + AvailBlankingStateDisabled, + AvailBlankingStateEnabled, + } +} + // Blackout Slate Network End Blackout const ( // BlackoutSlateNetworkEndBlackoutDisabled is a BlackoutSlateNetworkEndBlackout enum value @@ -22712,6 +24455,14 @@ const ( BlackoutSlateNetworkEndBlackoutEnabled = "ENABLED" ) +// BlackoutSlateNetworkEndBlackout_Values returns all elements of the BlackoutSlateNetworkEndBlackout enum +func BlackoutSlateNetworkEndBlackout_Values() []string { + return []string{ + BlackoutSlateNetworkEndBlackoutDisabled, + BlackoutSlateNetworkEndBlackoutEnabled, + } +} + // Blackout Slate State const ( // BlackoutSlateStateDisabled is a BlackoutSlateState enum value @@ -22721,6 +24472,14 @@ const ( BlackoutSlateStateEnabled = "ENABLED" ) +// BlackoutSlateState_Values returns all elements of the BlackoutSlateState enum +func BlackoutSlateState_Values() []string { + return []string{ + BlackoutSlateStateDisabled, + BlackoutSlateStateEnabled, + } +} + // Burn In Alignment const ( // BurnInAlignmentCentered is a BurnInAlignment enum value @@ -22733,6 +24492,15 @@ const ( BurnInAlignmentSmart = "SMART" ) +// BurnInAlignment_Values returns all elements of the BurnInAlignment enum +func BurnInAlignment_Values() []string { + return []string{ + BurnInAlignmentCentered, + BurnInAlignmentLeft, + BurnInAlignmentSmart, + } +} + // Burn In Background Color const ( // BurnInBackgroundColorBlack is a BurnInBackgroundColor enum value @@ -22745,6 +24513,15 @@ const ( BurnInBackgroundColorWhite = "WHITE" ) +// BurnInBackgroundColor_Values returns all elements of the BurnInBackgroundColor enum +func BurnInBackgroundColor_Values() []string { + return []string{ + BurnInBackgroundColorBlack, + BurnInBackgroundColorNone, + BurnInBackgroundColorWhite, + } +} + // Burn In Font Color const ( // BurnInFontColorBlack is a BurnInFontColor enum value @@ -22766,6 +24543,18 @@ const ( BurnInFontColorYellow = "YELLOW" ) +// BurnInFontColor_Values returns all elements of the BurnInFontColor enum +func BurnInFontColor_Values() []string { + return []string{ + BurnInFontColorBlack, + BurnInFontColorBlue, + BurnInFontColorGreen, + BurnInFontColorRed, + BurnInFontColorWhite, + BurnInFontColorYellow, + } +} + // Burn In Outline Color const ( // BurnInOutlineColorBlack is a BurnInOutlineColor enum value @@ -22787,6 +24576,18 @@ const ( BurnInOutlineColorYellow = "YELLOW" ) +// BurnInOutlineColor_Values returns all elements of the BurnInOutlineColor enum +func BurnInOutlineColor_Values() []string { + return []string{ + BurnInOutlineColorBlack, + BurnInOutlineColorBlue, + BurnInOutlineColorGreen, + BurnInOutlineColorRed, + BurnInOutlineColorWhite, + BurnInOutlineColorYellow, + } +} + // Burn In Shadow Color const ( // BurnInShadowColorBlack is a BurnInShadowColor enum value @@ -22799,6 +24600,15 @@ const ( BurnInShadowColorWhite = "WHITE" ) +// BurnInShadowColor_Values returns all elements of the BurnInShadowColor enum +func BurnInShadowColor_Values() []string { + return []string{ + BurnInShadowColorBlack, + BurnInShadowColorNone, + BurnInShadowColorWhite, + } +} + // Burn In Teletext Grid Control const ( // BurnInTeletextGridControlFixed is a BurnInTeletextGridControl enum value @@ -22808,6 +24618,14 @@ const ( BurnInTeletextGridControlScaled = "SCALED" ) +// BurnInTeletextGridControl_Values returns all elements of the BurnInTeletextGridControl enum +func BurnInTeletextGridControl_Values() []string { + return []string{ + BurnInTeletextGridControlFixed, + BurnInTeletextGridControlScaled, + } +} + // A standard channel has two encoding pipelines and a single pipeline channel // only has one. const ( @@ -22818,6 +24636,14 @@ const ( ChannelClassSinglePipeline = "SINGLE_PIPELINE" ) +// ChannelClass_Values returns all elements of the ChannelClass enum +func ChannelClass_Values() []string { + return []string{ + ChannelClassStandard, + ChannelClassSinglePipeline, + } +} + const ( // ChannelStateCreating is a ChannelState enum value ChannelStateCreating = "CREATING" @@ -22853,6 +24679,56 @@ const ( ChannelStateUpdateFailed = "UPDATE_FAILED" ) +// ChannelState_Values returns all elements of the ChannelState enum +func ChannelState_Values() []string { + return []string{ + ChannelStateCreating, + ChannelStateCreateFailed, + ChannelStateIdle, + ChannelStateStarting, + ChannelStateRunning, + ChannelStateRecovering, + ChannelStateStopping, + ChannelStateDeleting, + ChannelStateDeleted, + ChannelStateUpdating, + ChannelStateUpdateFailed, + } +} + +const ( + // ContentTypeImageJpeg is a ContentType enum value + ContentTypeImageJpeg = "image/jpeg" +) + +// ContentType_Values returns all elements of the ContentType enum +func ContentType_Values() []string { + return []string{ + ContentTypeImageJpeg, + } +} + +// The status of the action to synchronize the device configuration. If you +// change the configuration of the input device (for example, the maximum bitrate), +// MediaLive sends the new data to the device. The device might not update itself +// immediately. SYNCED means the device has updated its configuration. SYNCING +// means that it has not updated its configuration. +const ( + // DeviceSettingsSyncStateSynced is a DeviceSettingsSyncState enum value + DeviceSettingsSyncStateSynced = "SYNCED" + + // DeviceSettingsSyncStateSyncing is a DeviceSettingsSyncState enum value + DeviceSettingsSyncStateSyncing = "SYNCING" +) + +// DeviceSettingsSyncState_Values returns all elements of the DeviceSettingsSyncState enum +func DeviceSettingsSyncState_Values() []string { + return []string{ + DeviceSettingsSyncStateSynced, + DeviceSettingsSyncStateSyncing, + } +} + // Dvb Sdt Output Sdt const ( // DvbSdtOutputSdtSdtFollow is a DvbSdtOutputSdt enum value @@ -22868,6 +24744,16 @@ const ( DvbSdtOutputSdtSdtNone = "SDT_NONE" ) +// DvbSdtOutputSdt_Values returns all elements of the DvbSdtOutputSdt enum +func DvbSdtOutputSdt_Values() []string { + return []string{ + DvbSdtOutputSdtSdtFollow, + DvbSdtOutputSdtSdtFollowIfPresent, + DvbSdtOutputSdtSdtManual, + DvbSdtOutputSdtSdtNone, + } +} + // Dvb Sub Destination Alignment const ( // DvbSubDestinationAlignmentCentered is a DvbSubDestinationAlignment enum value @@ -22880,6 +24766,15 @@ const ( DvbSubDestinationAlignmentSmart = "SMART" ) +// DvbSubDestinationAlignment_Values returns all elements of the DvbSubDestinationAlignment enum +func DvbSubDestinationAlignment_Values() []string { + return []string{ + DvbSubDestinationAlignmentCentered, + DvbSubDestinationAlignmentLeft, + DvbSubDestinationAlignmentSmart, + } +} + // Dvb Sub Destination Background Color const ( // DvbSubDestinationBackgroundColorBlack is a DvbSubDestinationBackgroundColor enum value @@ -22892,6 +24787,15 @@ const ( DvbSubDestinationBackgroundColorWhite = "WHITE" ) +// DvbSubDestinationBackgroundColor_Values returns all elements of the DvbSubDestinationBackgroundColor enum +func DvbSubDestinationBackgroundColor_Values() []string { + return []string{ + DvbSubDestinationBackgroundColorBlack, + DvbSubDestinationBackgroundColorNone, + DvbSubDestinationBackgroundColorWhite, + } +} + // Dvb Sub Destination Font Color const ( // DvbSubDestinationFontColorBlack is a DvbSubDestinationFontColor enum value @@ -22913,6 +24817,18 @@ const ( DvbSubDestinationFontColorYellow = "YELLOW" ) +// DvbSubDestinationFontColor_Values returns all elements of the DvbSubDestinationFontColor enum +func DvbSubDestinationFontColor_Values() []string { + return []string{ + DvbSubDestinationFontColorBlack, + DvbSubDestinationFontColorBlue, + DvbSubDestinationFontColorGreen, + DvbSubDestinationFontColorRed, + DvbSubDestinationFontColorWhite, + DvbSubDestinationFontColorYellow, + } +} + // Dvb Sub Destination Outline Color const ( // DvbSubDestinationOutlineColorBlack is a DvbSubDestinationOutlineColor enum value @@ -22934,6 +24850,18 @@ const ( DvbSubDestinationOutlineColorYellow = "YELLOW" ) +// DvbSubDestinationOutlineColor_Values returns all elements of the DvbSubDestinationOutlineColor enum +func DvbSubDestinationOutlineColor_Values() []string { + return []string{ + DvbSubDestinationOutlineColorBlack, + DvbSubDestinationOutlineColorBlue, + DvbSubDestinationOutlineColorGreen, + DvbSubDestinationOutlineColorRed, + DvbSubDestinationOutlineColorWhite, + DvbSubDestinationOutlineColorYellow, + } +} + // Dvb Sub Destination Shadow Color const ( // DvbSubDestinationShadowColorBlack is a DvbSubDestinationShadowColor enum value @@ -22946,6 +24874,15 @@ const ( DvbSubDestinationShadowColorWhite = "WHITE" ) +// DvbSubDestinationShadowColor_Values returns all elements of the DvbSubDestinationShadowColor enum +func DvbSubDestinationShadowColor_Values() []string { + return []string{ + DvbSubDestinationShadowColorBlack, + DvbSubDestinationShadowColorNone, + DvbSubDestinationShadowColorWhite, + } +} + // Dvb Sub Destination Teletext Grid Control const ( // DvbSubDestinationTeletextGridControlFixed is a DvbSubDestinationTeletextGridControl enum value @@ -22955,6 +24892,14 @@ const ( DvbSubDestinationTeletextGridControlScaled = "SCALED" ) +// DvbSubDestinationTeletextGridControl_Values returns all elements of the DvbSubDestinationTeletextGridControl enum +func DvbSubDestinationTeletextGridControl_Values() []string { + return []string{ + DvbSubDestinationTeletextGridControlFixed, + DvbSubDestinationTeletextGridControlScaled, + } +} + // Eac3 Attenuation Control const ( // Eac3AttenuationControlAttenuate3Db is a Eac3AttenuationControl enum value @@ -22964,6 +24909,14 @@ const ( Eac3AttenuationControlNone = "NONE" ) +// Eac3AttenuationControl_Values returns all elements of the Eac3AttenuationControl enum +func Eac3AttenuationControl_Values() []string { + return []string{ + Eac3AttenuationControlAttenuate3Db, + Eac3AttenuationControlNone, + } +} + // Eac3 Bitstream Mode const ( // Eac3BitstreamModeCommentary is a Eac3BitstreamMode enum value @@ -22982,6 +24935,17 @@ const ( Eac3BitstreamModeVisuallyImpaired = "VISUALLY_IMPAIRED" ) +// Eac3BitstreamMode_Values returns all elements of the Eac3BitstreamMode enum +func Eac3BitstreamMode_Values() []string { + return []string{ + Eac3BitstreamModeCommentary, + Eac3BitstreamModeCompleteMain, + Eac3BitstreamModeEmergency, + Eac3BitstreamModeHearingImpaired, + Eac3BitstreamModeVisuallyImpaired, + } +} + // Eac3 Coding Mode const ( // Eac3CodingModeCodingMode10 is a Eac3CodingMode enum value @@ -22994,6 +24958,15 @@ const ( Eac3CodingModeCodingMode32 = "CODING_MODE_3_2" ) +// Eac3CodingMode_Values returns all elements of the Eac3CodingMode enum +func Eac3CodingMode_Values() []string { + return []string{ + Eac3CodingModeCodingMode10, + Eac3CodingModeCodingMode20, + Eac3CodingModeCodingMode32, + } +} + // Eac3 Dc Filter const ( // Eac3DcFilterDisabled is a Eac3DcFilter enum value @@ -23003,6 +24976,14 @@ const ( Eac3DcFilterEnabled = "ENABLED" ) +// Eac3DcFilter_Values returns all elements of the Eac3DcFilter enum +func Eac3DcFilter_Values() []string { + return []string{ + Eac3DcFilterDisabled, + Eac3DcFilterEnabled, + } +} + // Eac3 Drc Line const ( // Eac3DrcLineFilmLight is a Eac3DrcLine enum value @@ -23024,6 +25005,18 @@ const ( Eac3DrcLineSpeech = "SPEECH" ) +// Eac3DrcLine_Values returns all elements of the Eac3DrcLine enum +func Eac3DrcLine_Values() []string { + return []string{ + Eac3DrcLineFilmLight, + Eac3DrcLineFilmStandard, + Eac3DrcLineMusicLight, + Eac3DrcLineMusicStandard, + Eac3DrcLineNone, + Eac3DrcLineSpeech, + } +} + // Eac3 Drc Rf const ( // Eac3DrcRfFilmLight is a Eac3DrcRf enum value @@ -23045,6 +25038,18 @@ const ( Eac3DrcRfSpeech = "SPEECH" ) +// Eac3DrcRf_Values returns all elements of the Eac3DrcRf enum +func Eac3DrcRf_Values() []string { + return []string{ + Eac3DrcRfFilmLight, + Eac3DrcRfFilmStandard, + Eac3DrcRfMusicLight, + Eac3DrcRfMusicStandard, + Eac3DrcRfNone, + Eac3DrcRfSpeech, + } +} + // Eac3 Lfe Control const ( // Eac3LfeControlLfe is a Eac3LfeControl enum value @@ -23054,6 +25059,14 @@ const ( Eac3LfeControlNoLfe = "NO_LFE" ) +// Eac3LfeControl_Values returns all elements of the Eac3LfeControl enum +func Eac3LfeControl_Values() []string { + return []string{ + Eac3LfeControlLfe, + Eac3LfeControlNoLfe, + } +} + // Eac3 Lfe Filter const ( // Eac3LfeFilterDisabled is a Eac3LfeFilter enum value @@ -23063,6 +25076,14 @@ const ( Eac3LfeFilterEnabled = "ENABLED" ) +// Eac3LfeFilter_Values returns all elements of the Eac3LfeFilter enum +func Eac3LfeFilter_Values() []string { + return []string{ + Eac3LfeFilterDisabled, + Eac3LfeFilterEnabled, + } +} + // Eac3 Metadata Control const ( // Eac3MetadataControlFollowInput is a Eac3MetadataControl enum value @@ -23072,6 +25093,14 @@ const ( Eac3MetadataControlUseConfigured = "USE_CONFIGURED" ) +// Eac3MetadataControl_Values returns all elements of the Eac3MetadataControl enum +func Eac3MetadataControl_Values() []string { + return []string{ + Eac3MetadataControlFollowInput, + Eac3MetadataControlUseConfigured, + } +} + // Eac3 Passthrough Control const ( // Eac3PassthroughControlNoPassthrough is a Eac3PassthroughControl enum value @@ -23081,6 +25110,14 @@ const ( Eac3PassthroughControlWhenPossible = "WHEN_POSSIBLE" ) +// Eac3PassthroughControl_Values returns all elements of the Eac3PassthroughControl enum +func Eac3PassthroughControl_Values() []string { + return []string{ + Eac3PassthroughControlNoPassthrough, + Eac3PassthroughControlWhenPossible, + } +} + // Eac3 Phase Control const ( // Eac3PhaseControlNoShift is a Eac3PhaseControl enum value @@ -23090,6 +25127,14 @@ const ( Eac3PhaseControlShift90Degrees = "SHIFT_90_DEGREES" ) +// Eac3PhaseControl_Values returns all elements of the Eac3PhaseControl enum +func Eac3PhaseControl_Values() []string { + return []string{ + Eac3PhaseControlNoShift, + Eac3PhaseControlShift90Degrees, + } +} + // Eac3 Stereo Downmix const ( // Eac3StereoDownmixDpl2 is a Eac3StereoDownmix enum value @@ -23105,6 +25150,16 @@ const ( Eac3StereoDownmixNotIndicated = "NOT_INDICATED" ) +// Eac3StereoDownmix_Values returns all elements of the Eac3StereoDownmix enum +func Eac3StereoDownmix_Values() []string { + return []string{ + Eac3StereoDownmixDpl2, + Eac3StereoDownmixLoRo, + Eac3StereoDownmixLtRt, + Eac3StereoDownmixNotIndicated, + } +} + // Eac3 Surround Ex Mode const ( // Eac3SurroundExModeDisabled is a Eac3SurroundExMode enum value @@ -23117,6 +25172,15 @@ const ( Eac3SurroundExModeNotIndicated = "NOT_INDICATED" ) +// Eac3SurroundExMode_Values returns all elements of the Eac3SurroundExMode enum +func Eac3SurroundExMode_Values() []string { + return []string{ + Eac3SurroundExModeDisabled, + Eac3SurroundExModeEnabled, + Eac3SurroundExModeNotIndicated, + } +} + // Eac3 Surround Mode const ( // Eac3SurroundModeDisabled is a Eac3SurroundMode enum value @@ -23129,6 +25193,49 @@ const ( Eac3SurroundModeNotIndicated = "NOT_INDICATED" ) +// Eac3SurroundMode_Values returns all elements of the Eac3SurroundMode enum +func Eac3SurroundMode_Values() []string { + return []string{ + Eac3SurroundModeDisabled, + Eac3SurroundModeEnabled, + Eac3SurroundModeNotIndicated, + } +} + +// Ebu Tt DDestination Style Control +const ( + // EbuTtDDestinationStyleControlExclude is a EbuTtDDestinationStyleControl enum value + EbuTtDDestinationStyleControlExclude = "EXCLUDE" + + // EbuTtDDestinationStyleControlInclude is a EbuTtDDestinationStyleControl enum value + EbuTtDDestinationStyleControlInclude = "INCLUDE" +) + +// EbuTtDDestinationStyleControl_Values returns all elements of the EbuTtDDestinationStyleControl enum +func EbuTtDDestinationStyleControl_Values() []string { + return []string{ + EbuTtDDestinationStyleControlExclude, + EbuTtDDestinationStyleControlInclude, + } +} + +// Ebu Tt DFill Line Gap Control +const ( + // EbuTtDFillLineGapControlDisabled is a EbuTtDFillLineGapControl enum value + EbuTtDFillLineGapControlDisabled = "DISABLED" + + // EbuTtDFillLineGapControlEnabled is a EbuTtDFillLineGapControl enum value + EbuTtDFillLineGapControlEnabled = "ENABLED" +) + +// EbuTtDFillLineGapControl_Values returns all elements of the EbuTtDFillLineGapControl enum +func EbuTtDFillLineGapControl_Values() []string { + return []string{ + EbuTtDFillLineGapControlDisabled, + EbuTtDFillLineGapControlEnabled, + } +} + // Embedded Convert608 To708 const ( // EmbeddedConvert608To708Disabled is a EmbeddedConvert608To708 enum value @@ -23138,6 +25245,14 @@ const ( EmbeddedConvert608To708Upconvert = "UPCONVERT" ) +// EmbeddedConvert608To708_Values returns all elements of the EmbeddedConvert608To708 enum +func EmbeddedConvert608To708_Values() []string { + return []string{ + EmbeddedConvert608To708Disabled, + EmbeddedConvert608To708Upconvert, + } +} + // Embedded Scte20 Detection const ( // EmbeddedScte20DetectionAuto is a EmbeddedScte20Detection enum value @@ -23147,6 +25262,31 @@ const ( EmbeddedScte20DetectionOff = "OFF" ) +// EmbeddedScte20Detection_Values returns all elements of the EmbeddedScte20Detection enum +func EmbeddedScte20Detection_Values() []string { + return []string{ + EmbeddedScte20DetectionAuto, + EmbeddedScte20DetectionOff, + } +} + +// Feature Activations Input Prepare Schedule Actions +const ( + // FeatureActivationsInputPrepareScheduleActionsDisabled is a FeatureActivationsInputPrepareScheduleActions enum value + FeatureActivationsInputPrepareScheduleActionsDisabled = "DISABLED" + + // FeatureActivationsInputPrepareScheduleActionsEnabled is a FeatureActivationsInputPrepareScheduleActions enum value + FeatureActivationsInputPrepareScheduleActionsEnabled = "ENABLED" +) + +// FeatureActivationsInputPrepareScheduleActions_Values returns all elements of the FeatureActivationsInputPrepareScheduleActions enum +func FeatureActivationsInputPrepareScheduleActions_Values() []string { + return []string{ + FeatureActivationsInputPrepareScheduleActionsDisabled, + FeatureActivationsInputPrepareScheduleActionsEnabled, + } +} + // Fec Output Include Fec const ( // FecOutputIncludeFecColumn is a FecOutputIncludeFec enum value @@ -23156,6 +25296,14 @@ const ( FecOutputIncludeFecColumnAndRow = "COLUMN_AND_ROW" ) +// FecOutputIncludeFec_Values returns all elements of the FecOutputIncludeFec enum +func FecOutputIncludeFec_Values() []string { + return []string{ + FecOutputIncludeFecColumn, + FecOutputIncludeFecColumnAndRow, + } +} + // Fixed Afd const ( // FixedAfdAfd0000 is a FixedAfd enum value @@ -23192,6 +25340,23 @@ const ( FixedAfdAfd1111 = "AFD_1111" ) +// FixedAfd_Values returns all elements of the FixedAfd enum +func FixedAfd_Values() []string { + return []string{ + FixedAfdAfd0000, + FixedAfdAfd0010, + FixedAfdAfd0011, + FixedAfdAfd0100, + FixedAfdAfd1000, + FixedAfdAfd1001, + FixedAfdAfd1010, + FixedAfdAfd1011, + FixedAfdAfd1101, + FixedAfdAfd1110, + FixedAfdAfd1111, + } +} + // Fmp4 Nielsen Id3 Behavior const ( // Fmp4NielsenId3BehaviorNoPassthrough is a Fmp4NielsenId3Behavior enum value @@ -23201,6 +25366,14 @@ const ( Fmp4NielsenId3BehaviorPassthrough = "PASSTHROUGH" ) +// Fmp4NielsenId3Behavior_Values returns all elements of the Fmp4NielsenId3Behavior enum +func Fmp4NielsenId3Behavior_Values() []string { + return []string{ + Fmp4NielsenId3BehaviorNoPassthrough, + Fmp4NielsenId3BehaviorPassthrough, + } +} + // Fmp4 Timed Metadata Behavior const ( // Fmp4TimedMetadataBehaviorNoPassthrough is a Fmp4TimedMetadataBehavior enum value @@ -23210,6 +25383,14 @@ const ( Fmp4TimedMetadataBehaviorPassthrough = "PASSTHROUGH" ) +// Fmp4TimedMetadataBehavior_Values returns all elements of the Fmp4TimedMetadataBehavior enum +func Fmp4TimedMetadataBehavior_Values() []string { + return []string{ + Fmp4TimedMetadataBehaviorNoPassthrough, + Fmp4TimedMetadataBehaviorPassthrough, + } +} + // Follow reference point. const ( // FollowPointEnd is a FollowPoint enum value @@ -23219,6 +25400,14 @@ const ( FollowPointStart = "START" ) +// FollowPoint_Values returns all elements of the FollowPoint enum +func FollowPoint_Values() []string { + return []string{ + FollowPointEnd, + FollowPointStart, + } +} + // Frame Capture Interval Unit const ( // FrameCaptureIntervalUnitMilliseconds is a FrameCaptureIntervalUnit enum value @@ -23228,6 +25417,14 @@ const ( FrameCaptureIntervalUnitSeconds = "SECONDS" ) +// FrameCaptureIntervalUnit_Values returns all elements of the FrameCaptureIntervalUnit enum +func FrameCaptureIntervalUnit_Values() []string { + return []string{ + FrameCaptureIntervalUnitMilliseconds, + FrameCaptureIntervalUnitSeconds, + } +} + // Global Configuration Input End Action const ( // GlobalConfigurationInputEndActionNone is a GlobalConfigurationInputEndAction enum value @@ -23237,6 +25434,14 @@ const ( GlobalConfigurationInputEndActionSwitchAndLoopInputs = "SWITCH_AND_LOOP_INPUTS" ) +// GlobalConfigurationInputEndAction_Values returns all elements of the GlobalConfigurationInputEndAction enum +func GlobalConfigurationInputEndAction_Values() []string { + return []string{ + GlobalConfigurationInputEndActionNone, + GlobalConfigurationInputEndActionSwitchAndLoopInputs, + } +} + // Global Configuration Low Framerate Inputs const ( // GlobalConfigurationLowFramerateInputsDisabled is a GlobalConfigurationLowFramerateInputs enum value @@ -23246,6 +25451,14 @@ const ( GlobalConfigurationLowFramerateInputsEnabled = "ENABLED" ) +// GlobalConfigurationLowFramerateInputs_Values returns all elements of the GlobalConfigurationLowFramerateInputs enum +func GlobalConfigurationLowFramerateInputs_Values() []string { + return []string{ + GlobalConfigurationLowFramerateInputsDisabled, + GlobalConfigurationLowFramerateInputsEnabled, + } +} + // Global Configuration Output Locking Mode const ( // GlobalConfigurationOutputLockingModeEpochLocking is a GlobalConfigurationOutputLockingMode enum value @@ -23255,6 +25468,14 @@ const ( GlobalConfigurationOutputLockingModePipelineLocking = "PIPELINE_LOCKING" ) +// GlobalConfigurationOutputLockingMode_Values returns all elements of the GlobalConfigurationOutputLockingMode enum +func GlobalConfigurationOutputLockingMode_Values() []string { + return []string{ + GlobalConfigurationOutputLockingModeEpochLocking, + GlobalConfigurationOutputLockingModePipelineLocking, + } +} + // Global Configuration Output Timing Source const ( // GlobalConfigurationOutputTimingSourceInputClock is a GlobalConfigurationOutputTimingSource enum value @@ -23264,6 +25485,14 @@ const ( GlobalConfigurationOutputTimingSourceSystemClock = "SYSTEM_CLOCK" ) +// GlobalConfigurationOutputTimingSource_Values returns all elements of the GlobalConfigurationOutputTimingSource enum +func GlobalConfigurationOutputTimingSource_Values() []string { + return []string{ + GlobalConfigurationOutputTimingSourceInputClock, + GlobalConfigurationOutputTimingSourceSystemClock, + } +} + // H264 Adaptive Quantization const ( // H264AdaptiveQuantizationHigh is a H264AdaptiveQuantization enum value @@ -23285,6 +25514,18 @@ const ( H264AdaptiveQuantizationOff = "OFF" ) +// H264AdaptiveQuantization_Values returns all elements of the H264AdaptiveQuantization enum +func H264AdaptiveQuantization_Values() []string { + return []string{ + H264AdaptiveQuantizationHigh, + H264AdaptiveQuantizationHigher, + H264AdaptiveQuantizationLow, + H264AdaptiveQuantizationMax, + H264AdaptiveQuantizationMedium, + H264AdaptiveQuantizationOff, + } +} + // H264 Color Metadata const ( // H264ColorMetadataIgnore is a H264ColorMetadata enum value @@ -23294,6 +25535,14 @@ const ( H264ColorMetadataInsert = "INSERT" ) +// H264ColorMetadata_Values returns all elements of the H264ColorMetadata enum +func H264ColorMetadata_Values() []string { + return []string{ + H264ColorMetadataIgnore, + H264ColorMetadataInsert, + } +} + // H264 Entropy Encoding const ( // H264EntropyEncodingCabac is a H264EntropyEncoding enum value @@ -23303,6 +25552,14 @@ const ( H264EntropyEncodingCavlc = "CAVLC" ) +// H264EntropyEncoding_Values returns all elements of the H264EntropyEncoding enum +func H264EntropyEncoding_Values() []string { + return []string{ + H264EntropyEncodingCabac, + H264EntropyEncodingCavlc, + } +} + // H264 Flicker Aq const ( // H264FlickerAqDisabled is a H264FlickerAq enum value @@ -23312,6 +25569,14 @@ const ( H264FlickerAqEnabled = "ENABLED" ) +// H264FlickerAq_Values returns all elements of the H264FlickerAq enum +func H264FlickerAq_Values() []string { + return []string{ + H264FlickerAqDisabled, + H264FlickerAqEnabled, + } +} + // H264 Force Field Pictures const ( // H264ForceFieldPicturesDisabled is a H264ForceFieldPictures enum value @@ -23321,6 +25586,14 @@ const ( H264ForceFieldPicturesEnabled = "ENABLED" ) +// H264ForceFieldPictures_Values returns all elements of the H264ForceFieldPictures enum +func H264ForceFieldPictures_Values() []string { + return []string{ + H264ForceFieldPicturesDisabled, + H264ForceFieldPicturesEnabled, + } +} + // H264 Framerate Control const ( // H264FramerateControlInitializeFromSource is a H264FramerateControl enum value @@ -23330,6 +25603,14 @@ const ( H264FramerateControlSpecified = "SPECIFIED" ) +// H264FramerateControl_Values returns all elements of the H264FramerateControl enum +func H264FramerateControl_Values() []string { + return []string{ + H264FramerateControlInitializeFromSource, + H264FramerateControlSpecified, + } +} + // H264 Gop BReference const ( // H264GopBReferenceDisabled is a H264GopBReference enum value @@ -23339,6 +25620,14 @@ const ( H264GopBReferenceEnabled = "ENABLED" ) +// H264GopBReference_Values returns all elements of the H264GopBReference enum +func H264GopBReference_Values() []string { + return []string{ + H264GopBReferenceDisabled, + H264GopBReferenceEnabled, + } +} + // H264 Gop Size Units const ( // H264GopSizeUnitsFrames is a H264GopSizeUnits enum value @@ -23348,6 +25637,14 @@ const ( H264GopSizeUnitsSeconds = "SECONDS" ) +// H264GopSizeUnits_Values returns all elements of the H264GopSizeUnits enum +func H264GopSizeUnits_Values() []string { + return []string{ + H264GopSizeUnitsFrames, + H264GopSizeUnitsSeconds, + } +} + // H264 Level const ( // H264LevelH264Level1 is a H264Level enum value @@ -23402,6 +25699,29 @@ const ( H264LevelH264LevelAuto = "H264_LEVEL_AUTO" ) +// H264Level_Values returns all elements of the H264Level enum +func H264Level_Values() []string { + return []string{ + H264LevelH264Level1, + H264LevelH264Level11, + H264LevelH264Level12, + H264LevelH264Level13, + H264LevelH264Level2, + H264LevelH264Level21, + H264LevelH264Level22, + H264LevelH264Level3, + H264LevelH264Level31, + H264LevelH264Level32, + H264LevelH264Level4, + H264LevelH264Level41, + H264LevelH264Level42, + H264LevelH264Level5, + H264LevelH264Level51, + H264LevelH264Level52, + H264LevelH264LevelAuto, + } +} + // H264 Look Ahead Rate Control const ( // H264LookAheadRateControlHigh is a H264LookAheadRateControl enum value @@ -23414,6 +25734,15 @@ const ( H264LookAheadRateControlMedium = "MEDIUM" ) +// H264LookAheadRateControl_Values returns all elements of the H264LookAheadRateControl enum +func H264LookAheadRateControl_Values() []string { + return []string{ + H264LookAheadRateControlHigh, + H264LookAheadRateControlLow, + H264LookAheadRateControlMedium, + } +} + // H264 Par Control const ( // H264ParControlInitializeFromSource is a H264ParControl enum value @@ -23423,6 +25752,14 @@ const ( H264ParControlSpecified = "SPECIFIED" ) +// H264ParControl_Values returns all elements of the H264ParControl enum +func H264ParControl_Values() []string { + return []string{ + H264ParControlInitializeFromSource, + H264ParControlSpecified, + } +} + // H264 Profile const ( // H264ProfileBaseline is a H264Profile enum value @@ -23444,6 +25781,18 @@ const ( H264ProfileMain = "MAIN" ) +// H264Profile_Values returns all elements of the H264Profile enum +func H264Profile_Values() []string { + return []string{ + H264ProfileBaseline, + H264ProfileHigh, + H264ProfileHigh10bit, + H264ProfileHigh422, + H264ProfileHigh42210bit, + H264ProfileMain, + } +} + // H264 Quality Level const ( // H264QualityLevelEnhancedQuality is a H264QualityLevel enum value @@ -23453,6 +25802,14 @@ const ( H264QualityLevelStandardQuality = "STANDARD_QUALITY" ) +// H264QualityLevel_Values returns all elements of the H264QualityLevel enum +func H264QualityLevel_Values() []string { + return []string{ + H264QualityLevelEnhancedQuality, + H264QualityLevelStandardQuality, + } +} + // H264 Rate Control Mode const ( // H264RateControlModeCbr is a H264RateControlMode enum value @@ -23468,6 +25825,16 @@ const ( H264RateControlModeVbr = "VBR" ) +// H264RateControlMode_Values returns all elements of the H264RateControlMode enum +func H264RateControlMode_Values() []string { + return []string{ + H264RateControlModeCbr, + H264RateControlModeMultiplex, + H264RateControlModeQvbr, + H264RateControlModeVbr, + } +} + // H264 Scan Type const ( // H264ScanTypeInterlaced is a H264ScanType enum value @@ -23477,6 +25844,14 @@ const ( H264ScanTypeProgressive = "PROGRESSIVE" ) +// H264ScanType_Values returns all elements of the H264ScanType enum +func H264ScanType_Values() []string { + return []string{ + H264ScanTypeInterlaced, + H264ScanTypeProgressive, + } +} + // H264 Scene Change Detect const ( // H264SceneChangeDetectDisabled is a H264SceneChangeDetect enum value @@ -23486,6 +25861,14 @@ const ( H264SceneChangeDetectEnabled = "ENABLED" ) +// H264SceneChangeDetect_Values returns all elements of the H264SceneChangeDetect enum +func H264SceneChangeDetect_Values() []string { + return []string{ + H264SceneChangeDetectDisabled, + H264SceneChangeDetectEnabled, + } +} + // H264 Spatial Aq const ( // H264SpatialAqDisabled is a H264SpatialAq enum value @@ -23495,6 +25878,14 @@ const ( H264SpatialAqEnabled = "ENABLED" ) +// H264SpatialAq_Values returns all elements of the H264SpatialAq enum +func H264SpatialAq_Values() []string { + return []string{ + H264SpatialAqDisabled, + H264SpatialAqEnabled, + } +} + // H264 Sub Gop Length const ( // H264SubGopLengthDynamic is a H264SubGopLength enum value @@ -23504,6 +25895,14 @@ const ( H264SubGopLengthFixed = "FIXED" ) +// H264SubGopLength_Values returns all elements of the H264SubGopLength enum +func H264SubGopLength_Values() []string { + return []string{ + H264SubGopLengthDynamic, + H264SubGopLengthFixed, + } +} + // H264 Syntax const ( // H264SyntaxDefault is a H264Syntax enum value @@ -23513,6 +25912,14 @@ const ( H264SyntaxRp2027 = "RP2027" ) +// H264Syntax_Values returns all elements of the H264Syntax enum +func H264Syntax_Values() []string { + return []string{ + H264SyntaxDefault, + H264SyntaxRp2027, + } +} + // H264 Temporal Aq const ( // H264TemporalAqDisabled is a H264TemporalAq enum value @@ -23522,6 +25929,14 @@ const ( H264TemporalAqEnabled = "ENABLED" ) +// H264TemporalAq_Values returns all elements of the H264TemporalAq enum +func H264TemporalAq_Values() []string { + return []string{ + H264TemporalAqDisabled, + H264TemporalAqEnabled, + } +} + // H264 Timecode Insertion Behavior const ( // H264TimecodeInsertionBehaviorDisabled is a H264TimecodeInsertionBehavior enum value @@ -23531,6 +25946,14 @@ const ( H264TimecodeInsertionBehaviorPicTimingSei = "PIC_TIMING_SEI" ) +// H264TimecodeInsertionBehavior_Values returns all elements of the H264TimecodeInsertionBehavior enum +func H264TimecodeInsertionBehavior_Values() []string { + return []string{ + H264TimecodeInsertionBehaviorDisabled, + H264TimecodeInsertionBehaviorPicTimingSei, + } +} + // H265 Adaptive Quantization const ( // H265AdaptiveQuantizationHigh is a H265AdaptiveQuantization enum value @@ -23552,6 +25975,18 @@ const ( H265AdaptiveQuantizationOff = "OFF" ) +// H265AdaptiveQuantization_Values returns all elements of the H265AdaptiveQuantization enum +func H265AdaptiveQuantization_Values() []string { + return []string{ + H265AdaptiveQuantizationHigh, + H265AdaptiveQuantizationHigher, + H265AdaptiveQuantizationLow, + H265AdaptiveQuantizationMax, + H265AdaptiveQuantizationMedium, + H265AdaptiveQuantizationOff, + } +} + // H265 Alternative Transfer Function const ( // H265AlternativeTransferFunctionInsert is a H265AlternativeTransferFunction enum value @@ -23561,6 +25996,14 @@ const ( H265AlternativeTransferFunctionOmit = "OMIT" ) +// H265AlternativeTransferFunction_Values returns all elements of the H265AlternativeTransferFunction enum +func H265AlternativeTransferFunction_Values() []string { + return []string{ + H265AlternativeTransferFunctionInsert, + H265AlternativeTransferFunctionOmit, + } +} + // H265 Color Metadata const ( // H265ColorMetadataIgnore is a H265ColorMetadata enum value @@ -23570,6 +26013,14 @@ const ( H265ColorMetadataInsert = "INSERT" ) +// H265ColorMetadata_Values returns all elements of the H265ColorMetadata enum +func H265ColorMetadata_Values() []string { + return []string{ + H265ColorMetadataIgnore, + H265ColorMetadataInsert, + } +} + // H265 Flicker Aq const ( // H265FlickerAqDisabled is a H265FlickerAq enum value @@ -23579,6 +26030,14 @@ const ( H265FlickerAqEnabled = "ENABLED" ) +// H265FlickerAq_Values returns all elements of the H265FlickerAq enum +func H265FlickerAq_Values() []string { + return []string{ + H265FlickerAqDisabled, + H265FlickerAqEnabled, + } +} + // H265 Gop Size Units const ( // H265GopSizeUnitsFrames is a H265GopSizeUnits enum value @@ -23588,6 +26047,14 @@ const ( H265GopSizeUnitsSeconds = "SECONDS" ) +// H265GopSizeUnits_Values returns all elements of the H265GopSizeUnits enum +func H265GopSizeUnits_Values() []string { + return []string{ + H265GopSizeUnitsFrames, + H265GopSizeUnitsSeconds, + } +} + // H265 Level const ( // H265LevelH265Level1 is a H265Level enum value @@ -23633,6 +26100,26 @@ const ( H265LevelH265LevelAuto = "H265_LEVEL_AUTO" ) +// H265Level_Values returns all elements of the H265Level enum +func H265Level_Values() []string { + return []string{ + H265LevelH265Level1, + H265LevelH265Level2, + H265LevelH265Level21, + H265LevelH265Level3, + H265LevelH265Level31, + H265LevelH265Level4, + H265LevelH265Level41, + H265LevelH265Level5, + H265LevelH265Level51, + H265LevelH265Level52, + H265LevelH265Level6, + H265LevelH265Level61, + H265LevelH265Level62, + H265LevelH265LevelAuto, + } +} + // H265 Look Ahead Rate Control const ( // H265LookAheadRateControlHigh is a H265LookAheadRateControl enum value @@ -23645,6 +26132,15 @@ const ( H265LookAheadRateControlMedium = "MEDIUM" ) +// H265LookAheadRateControl_Values returns all elements of the H265LookAheadRateControl enum +func H265LookAheadRateControl_Values() []string { + return []string{ + H265LookAheadRateControlHigh, + H265LookAheadRateControlLow, + H265LookAheadRateControlMedium, + } +} + // H265 Profile const ( // H265ProfileMain is a H265Profile enum value @@ -23654,6 +26150,14 @@ const ( H265ProfileMain10bit = "MAIN_10BIT" ) +// H265Profile_Values returns all elements of the H265Profile enum +func H265Profile_Values() []string { + return []string{ + H265ProfileMain, + H265ProfileMain10bit, + } +} + // H265 Rate Control Mode const ( // H265RateControlModeCbr is a H265RateControlMode enum value @@ -23666,12 +26170,32 @@ const ( H265RateControlModeQvbr = "QVBR" ) +// H265RateControlMode_Values returns all elements of the H265RateControlMode enum +func H265RateControlMode_Values() []string { + return []string{ + H265RateControlModeCbr, + H265RateControlModeMultiplex, + H265RateControlModeQvbr, + } +} + // H265 Scan Type const ( + // H265ScanTypeInterlaced is a H265ScanType enum value + H265ScanTypeInterlaced = "INTERLACED" + // H265ScanTypeProgressive is a H265ScanType enum value H265ScanTypeProgressive = "PROGRESSIVE" ) +// H265ScanType_Values returns all elements of the H265ScanType enum +func H265ScanType_Values() []string { + return []string{ + H265ScanTypeInterlaced, + H265ScanTypeProgressive, + } +} + // H265 Scene Change Detect const ( // H265SceneChangeDetectDisabled is a H265SceneChangeDetect enum value @@ -23681,6 +26205,14 @@ const ( H265SceneChangeDetectEnabled = "ENABLED" ) +// H265SceneChangeDetect_Values returns all elements of the H265SceneChangeDetect enum +func H265SceneChangeDetect_Values() []string { + return []string{ + H265SceneChangeDetectDisabled, + H265SceneChangeDetectEnabled, + } +} + // H265 Tier const ( // H265TierHigh is a H265Tier enum value @@ -23690,6 +26222,14 @@ const ( H265TierMain = "MAIN" ) +// H265Tier_Values returns all elements of the H265Tier enum +func H265Tier_Values() []string { + return []string{ + H265TierHigh, + H265TierMain, + } +} + // H265 Timecode Insertion Behavior const ( // H265TimecodeInsertionBehaviorDisabled is a H265TimecodeInsertionBehavior enum value @@ -23699,6 +26239,14 @@ const ( H265TimecodeInsertionBehaviorPicTimingSei = "PIC_TIMING_SEI" ) +// H265TimecodeInsertionBehavior_Values returns all elements of the H265TimecodeInsertionBehavior enum +func H265TimecodeInsertionBehavior_Values() []string { + return []string{ + H265TimecodeInsertionBehaviorDisabled, + H265TimecodeInsertionBehaviorPicTimingSei, + } +} + // Hls Ad Markers const ( // HlsAdMarkersAdobe is a HlsAdMarkers enum value @@ -23711,6 +26259,15 @@ const ( HlsAdMarkersElementalScte35 = "ELEMENTAL_SCTE35" ) +// HlsAdMarkers_Values returns all elements of the HlsAdMarkers enum +func HlsAdMarkers_Values() []string { + return []string{ + HlsAdMarkersAdobe, + HlsAdMarkersElemental, + HlsAdMarkersElementalScte35, + } +} + // Hls Akamai Http Transfer Mode const ( // HlsAkamaiHttpTransferModeChunked is a HlsAkamaiHttpTransferMode enum value @@ -23720,6 +26277,14 @@ const ( HlsAkamaiHttpTransferModeNonChunked = "NON_CHUNKED" ) +// HlsAkamaiHttpTransferMode_Values returns all elements of the HlsAkamaiHttpTransferMode enum +func HlsAkamaiHttpTransferMode_Values() []string { + return []string{ + HlsAkamaiHttpTransferModeChunked, + HlsAkamaiHttpTransferModeNonChunked, + } +} + // Hls Caption Language Setting const ( // HlsCaptionLanguageSettingInsert is a HlsCaptionLanguageSetting enum value @@ -23732,6 +26297,15 @@ const ( HlsCaptionLanguageSettingOmit = "OMIT" ) +// HlsCaptionLanguageSetting_Values returns all elements of the HlsCaptionLanguageSetting enum +func HlsCaptionLanguageSetting_Values() []string { + return []string{ + HlsCaptionLanguageSettingInsert, + HlsCaptionLanguageSettingNone, + HlsCaptionLanguageSettingOmit, + } +} + // Hls Client Cache const ( // HlsClientCacheDisabled is a HlsClientCache enum value @@ -23741,6 +26315,14 @@ const ( HlsClientCacheEnabled = "ENABLED" ) +// HlsClientCache_Values returns all elements of the HlsClientCache enum +func HlsClientCache_Values() []string { + return []string{ + HlsClientCacheDisabled, + HlsClientCacheEnabled, + } +} + // Hls Codec Specification const ( // HlsCodecSpecificationRfc4281 is a HlsCodecSpecification enum value @@ -23750,6 +26332,14 @@ const ( HlsCodecSpecificationRfc6381 = "RFC_6381" ) +// HlsCodecSpecification_Values returns all elements of the HlsCodecSpecification enum +func HlsCodecSpecification_Values() []string { + return []string{ + HlsCodecSpecificationRfc4281, + HlsCodecSpecificationRfc6381, + } +} + // Hls Directory Structure const ( // HlsDirectoryStructureSingleDirectory is a HlsDirectoryStructure enum value @@ -23759,6 +26349,14 @@ const ( HlsDirectoryStructureSubdirectoryPerStream = "SUBDIRECTORY_PER_STREAM" ) +// HlsDirectoryStructure_Values returns all elements of the HlsDirectoryStructure enum +func HlsDirectoryStructure_Values() []string { + return []string{ + HlsDirectoryStructureSingleDirectory, + HlsDirectoryStructureSubdirectoryPerStream, + } +} + // Hls Encryption Type const ( // HlsEncryptionTypeAes128 is a HlsEncryptionType enum value @@ -23768,6 +26366,14 @@ const ( HlsEncryptionTypeSampleAes = "SAMPLE_AES" ) +// HlsEncryptionType_Values returns all elements of the HlsEncryptionType enum +func HlsEncryptionType_Values() []string { + return []string{ + HlsEncryptionTypeAes128, + HlsEncryptionTypeSampleAes, + } +} + // Hls H265 Packaging Type const ( // HlsH265PackagingTypeHev1 is a HlsH265PackagingType enum value @@ -23777,6 +26383,14 @@ const ( HlsH265PackagingTypeHvc1 = "HVC1" ) +// HlsH265PackagingType_Values returns all elements of the HlsH265PackagingType enum +func HlsH265PackagingType_Values() []string { + return []string{ + HlsH265PackagingTypeHev1, + HlsH265PackagingTypeHvc1, + } +} + // State of HLS ID3 Segment Tagging const ( // HlsId3SegmentTaggingStateDisabled is a HlsId3SegmentTaggingState enum value @@ -23786,6 +26400,14 @@ const ( HlsId3SegmentTaggingStateEnabled = "ENABLED" ) +// HlsId3SegmentTaggingState_Values returns all elements of the HlsId3SegmentTaggingState enum +func HlsId3SegmentTaggingState_Values() []string { + return []string{ + HlsId3SegmentTaggingStateDisabled, + HlsId3SegmentTaggingStateEnabled, + } +} + // Hls Iv In Manifest const ( // HlsIvInManifestExclude is a HlsIvInManifest enum value @@ -23795,6 +26417,14 @@ const ( HlsIvInManifestInclude = "INCLUDE" ) +// HlsIvInManifest_Values returns all elements of the HlsIvInManifest enum +func HlsIvInManifest_Values() []string { + return []string{ + HlsIvInManifestExclude, + HlsIvInManifestInclude, + } +} + // Hls Iv Source const ( // HlsIvSourceExplicit is a HlsIvSource enum value @@ -23804,6 +26434,14 @@ const ( HlsIvSourceFollowsSegmentNumber = "FOLLOWS_SEGMENT_NUMBER" ) +// HlsIvSource_Values returns all elements of the HlsIvSource enum +func HlsIvSource_Values() []string { + return []string{ + HlsIvSourceExplicit, + HlsIvSourceFollowsSegmentNumber, + } +} + // Hls Manifest Compression const ( // HlsManifestCompressionGzip is a HlsManifestCompression enum value @@ -23813,6 +26451,14 @@ const ( HlsManifestCompressionNone = "NONE" ) +// HlsManifestCompression_Values returns all elements of the HlsManifestCompression enum +func HlsManifestCompression_Values() []string { + return []string{ + HlsManifestCompressionGzip, + HlsManifestCompressionNone, + } +} + // Hls Manifest Duration Format const ( // HlsManifestDurationFormatFloatingPoint is a HlsManifestDurationFormat enum value @@ -23822,12 +26468,27 @@ const ( HlsManifestDurationFormatInteger = "INTEGER" ) +// HlsManifestDurationFormat_Values returns all elements of the HlsManifestDurationFormat enum +func HlsManifestDurationFormat_Values() []string { + return []string{ + HlsManifestDurationFormatFloatingPoint, + HlsManifestDurationFormatInteger, + } +} + // Hls Media Store Storage Class const ( // HlsMediaStoreStorageClassTemporal is a HlsMediaStoreStorageClass enum value HlsMediaStoreStorageClassTemporal = "TEMPORAL" ) +// HlsMediaStoreStorageClass_Values returns all elements of the HlsMediaStoreStorageClass enum +func HlsMediaStoreStorageClass_Values() []string { + return []string{ + HlsMediaStoreStorageClassTemporal, + } +} + // Hls Mode const ( // HlsModeLive is a HlsMode enum value @@ -23837,6 +26498,14 @@ const ( HlsModeVod = "VOD" ) +// HlsMode_Values returns all elements of the HlsMode enum +func HlsMode_Values() []string { + return []string{ + HlsModeLive, + HlsModeVod, + } +} + // Hls Output Selection const ( // HlsOutputSelectionManifestsAndSegments is a HlsOutputSelection enum value @@ -23844,8 +26513,20 @@ const ( // HlsOutputSelectionSegmentsOnly is a HlsOutputSelection enum value HlsOutputSelectionSegmentsOnly = "SEGMENTS_ONLY" + + // HlsOutputSelectionVariantManifestsAndSegments is a HlsOutputSelection enum value + HlsOutputSelectionVariantManifestsAndSegments = "VARIANT_MANIFESTS_AND_SEGMENTS" ) +// HlsOutputSelection_Values returns all elements of the HlsOutputSelection enum +func HlsOutputSelection_Values() []string { + return []string{ + HlsOutputSelectionManifestsAndSegments, + HlsOutputSelectionSegmentsOnly, + HlsOutputSelectionVariantManifestsAndSegments, + } +} + // Hls Program Date Time const ( // HlsProgramDateTimeExclude is a HlsProgramDateTime enum value @@ -23855,6 +26536,14 @@ const ( HlsProgramDateTimeInclude = "INCLUDE" ) +// HlsProgramDateTime_Values returns all elements of the HlsProgramDateTime enum +func HlsProgramDateTime_Values() []string { + return []string{ + HlsProgramDateTimeExclude, + HlsProgramDateTimeInclude, + } +} + // Hls Redundant Manifest const ( // HlsRedundantManifestDisabled is a HlsRedundantManifest enum value @@ -23864,6 +26553,14 @@ const ( HlsRedundantManifestEnabled = "ENABLED" ) +// HlsRedundantManifest_Values returns all elements of the HlsRedundantManifest enum +func HlsRedundantManifest_Values() []string { + return []string{ + HlsRedundantManifestDisabled, + HlsRedundantManifestEnabled, + } +} + // Hls Segmentation Mode const ( // HlsSegmentationModeUseInputSegmentation is a HlsSegmentationMode enum value @@ -23873,6 +26570,14 @@ const ( HlsSegmentationModeUseSegmentDuration = "USE_SEGMENT_DURATION" ) +// HlsSegmentationMode_Values returns all elements of the HlsSegmentationMode enum +func HlsSegmentationMode_Values() []string { + return []string{ + HlsSegmentationModeUseInputSegmentation, + HlsSegmentationModeUseSegmentDuration, + } +} + // Hls Stream Inf Resolution const ( // HlsStreamInfResolutionExclude is a HlsStreamInfResolution enum value @@ -23882,6 +26587,14 @@ const ( HlsStreamInfResolutionInclude = "INCLUDE" ) +// HlsStreamInfResolution_Values returns all elements of the HlsStreamInfResolution enum +func HlsStreamInfResolution_Values() []string { + return []string{ + HlsStreamInfResolutionExclude, + HlsStreamInfResolutionInclude, + } +} + // Hls Timed Metadata Id3 Frame const ( // HlsTimedMetadataId3FrameNone is a HlsTimedMetadataId3Frame enum value @@ -23894,6 +26607,15 @@ const ( HlsTimedMetadataId3FrameTdrl = "TDRL" ) +// HlsTimedMetadataId3Frame_Values returns all elements of the HlsTimedMetadataId3Frame enum +func HlsTimedMetadataId3Frame_Values() []string { + return []string{ + HlsTimedMetadataId3FrameNone, + HlsTimedMetadataId3FramePriv, + HlsTimedMetadataId3FrameTdrl, + } +} + // Hls Ts File Mode const ( // HlsTsFileModeSegmentedFiles is a HlsTsFileMode enum value @@ -23903,6 +26625,14 @@ const ( HlsTsFileModeSingleFile = "SINGLE_FILE" ) +// HlsTsFileMode_Values returns all elements of the HlsTsFileMode enum +func HlsTsFileMode_Values() []string { + return []string{ + HlsTsFileModeSegmentedFiles, + HlsTsFileModeSingleFile, + } +} + // Hls Webdav Http Transfer Mode const ( // HlsWebdavHttpTransferModeChunked is a HlsWebdavHttpTransferMode enum value @@ -23912,6 +26642,14 @@ const ( HlsWebdavHttpTransferModeNonChunked = "NON_CHUNKED" ) +// HlsWebdavHttpTransferMode_Values returns all elements of the HlsWebdavHttpTransferMode enum +func HlsWebdavHttpTransferMode_Values() []string { + return []string{ + HlsWebdavHttpTransferModeChunked, + HlsWebdavHttpTransferModeNonChunked, + } +} + // When set to "standard", an I-Frame only playlist will be written out for // each video output in the output group. This I-Frame only playlist will contain // byte range offsets pointing to the I-frame(s) in each segment. @@ -23923,6 +26661,14 @@ const ( IFrameOnlyPlaylistTypeStandard = "STANDARD" ) +// IFrameOnlyPlaylistType_Values returns all elements of the IFrameOnlyPlaylistType enum +func IFrameOnlyPlaylistType_Values() []string { + return []string{ + IFrameOnlyPlaylistTypeDisabled, + IFrameOnlyPlaylistTypeStandard, + } +} + // A standard input has two sources and a single pipeline input only has one. const ( // InputClassStandard is a InputClass enum value @@ -23932,6 +26678,14 @@ const ( InputClassSinglePipeline = "SINGLE_PIPELINE" ) +// InputClass_Values returns all elements of the InputClass enum +func InputClass_Values() []string { + return []string{ + InputClassStandard, + InputClassSinglePipeline, + } +} + // codec in increasing order of complexity const ( // InputCodecMpeg2 is a InputCodec enum value @@ -23944,6 +26698,15 @@ const ( InputCodecHevc = "HEVC" ) +// InputCodec_Values returns all elements of the InputCodec enum +func InputCodec_Values() []string { + return []string{ + InputCodecMpeg2, + InputCodecAvc, + InputCodecHevc, + } +} + // Input Deblock Filter const ( // InputDeblockFilterDisabled is a InputDeblockFilter enum value @@ -23953,6 +26716,14 @@ const ( InputDeblockFilterEnabled = "ENABLED" ) +// InputDeblockFilter_Values returns all elements of the InputDeblockFilter enum +func InputDeblockFilter_Values() []string { + return []string{ + InputDeblockFilterDisabled, + InputDeblockFilterEnabled, + } +} + // Input Denoise Filter const ( // InputDenoiseFilterDisabled is a InputDenoiseFilter enum value @@ -23962,6 +26733,135 @@ const ( InputDenoiseFilterEnabled = "ENABLED" ) +// InputDenoiseFilter_Values returns all elements of the InputDenoiseFilter enum +func InputDenoiseFilter_Values() []string { + return []string{ + InputDenoiseFilterDisabled, + InputDenoiseFilterEnabled, + } +} + +// The source at the input device that is currently active. +const ( + // InputDeviceActiveInputHdmi is a InputDeviceActiveInput enum value + InputDeviceActiveInputHdmi = "HDMI" + + // InputDeviceActiveInputSdi is a InputDeviceActiveInput enum value + InputDeviceActiveInputSdi = "SDI" +) + +// InputDeviceActiveInput_Values returns all elements of the InputDeviceActiveInput enum +func InputDeviceActiveInput_Values() []string { + return []string{ + InputDeviceActiveInputHdmi, + InputDeviceActiveInputSdi, + } +} + +// The source to activate (use) from the input device. +const ( + // InputDeviceConfiguredInputAuto is a InputDeviceConfiguredInput enum value + InputDeviceConfiguredInputAuto = "AUTO" + + // InputDeviceConfiguredInputHdmi is a InputDeviceConfiguredInput enum value + InputDeviceConfiguredInputHdmi = "HDMI" + + // InputDeviceConfiguredInputSdi is a InputDeviceConfiguredInput enum value + InputDeviceConfiguredInputSdi = "SDI" +) + +// InputDeviceConfiguredInput_Values returns all elements of the InputDeviceConfiguredInput enum +func InputDeviceConfiguredInput_Values() []string { + return []string{ + InputDeviceConfiguredInputAuto, + InputDeviceConfiguredInputHdmi, + InputDeviceConfiguredInputSdi, + } +} + +// The state of the connection between the input device and AWS. +const ( + // InputDeviceConnectionStateDisconnected is a InputDeviceConnectionState enum value + InputDeviceConnectionStateDisconnected = "DISCONNECTED" + + // InputDeviceConnectionStateConnected is a InputDeviceConnectionState enum value + InputDeviceConnectionStateConnected = "CONNECTED" +) + +// InputDeviceConnectionState_Values returns all elements of the InputDeviceConnectionState enum +func InputDeviceConnectionState_Values() []string { + return []string{ + InputDeviceConnectionStateDisconnected, + InputDeviceConnectionStateConnected, + } +} + +// Specifies whether the input device has been configured (outside of MediaLive) +// to use a dynamic IP address assignment (DHCP) or a static IP address. +const ( + // InputDeviceIpSchemeStatic is a InputDeviceIpScheme enum value + InputDeviceIpSchemeStatic = "STATIC" + + // InputDeviceIpSchemeDhcp is a InputDeviceIpScheme enum value + InputDeviceIpSchemeDhcp = "DHCP" +) + +// InputDeviceIpScheme_Values returns all elements of the InputDeviceIpScheme enum +func InputDeviceIpScheme_Values() []string { + return []string{ + InputDeviceIpSchemeStatic, + InputDeviceIpSchemeDhcp, + } +} + +// The scan type of the video source. +const ( + // InputDeviceScanTypeInterlaced is a InputDeviceScanType enum value + InputDeviceScanTypeInterlaced = "INTERLACED" + + // InputDeviceScanTypeProgressive is a InputDeviceScanType enum value + InputDeviceScanTypeProgressive = "PROGRESSIVE" +) + +// InputDeviceScanType_Values returns all elements of the InputDeviceScanType enum +func InputDeviceScanType_Values() []string { + return []string{ + InputDeviceScanTypeInterlaced, + InputDeviceScanTypeProgressive, + } +} + +// The state of the input device. +const ( + // InputDeviceStateIdle is a InputDeviceState enum value + InputDeviceStateIdle = "IDLE" + + // InputDeviceStateStreaming is a InputDeviceState enum value + InputDeviceStateStreaming = "STREAMING" +) + +// InputDeviceState_Values returns all elements of the InputDeviceState enum +func InputDeviceState_Values() []string { + return []string{ + InputDeviceStateIdle, + InputDeviceStateStreaming, + } +} + +// The type of the input device. For an AWS Elemental Link device that outputs +// resolutions up to 1080, choose "HD". +const ( + // InputDeviceTypeHd is a InputDeviceType enum value + InputDeviceTypeHd = "HD" +) + +// InputDeviceType_Values returns all elements of the InputDeviceType enum +func InputDeviceType_Values() []string { + return []string{ + InputDeviceTypeHd, + } +} + // Input Filter const ( // InputFilterAuto is a InputFilter enum value @@ -23974,6 +26874,15 @@ const ( InputFilterForced = "FORCED" ) +// InputFilter_Values returns all elements of the InputFilter enum +func InputFilter_Values() []string { + return []string{ + InputFilterAuto, + InputFilterDisabled, + InputFilterForced, + } +} + // Input Loss Action For Hls Out const ( // InputLossActionForHlsOutEmitOutput is a InputLossActionForHlsOut enum value @@ -23983,6 +26892,14 @@ const ( InputLossActionForHlsOutPauseOutput = "PAUSE_OUTPUT" ) +// InputLossActionForHlsOut_Values returns all elements of the InputLossActionForHlsOut enum +func InputLossActionForHlsOut_Values() []string { + return []string{ + InputLossActionForHlsOutEmitOutput, + InputLossActionForHlsOutPauseOutput, + } +} + // Input Loss Action For Ms Smooth Out const ( // InputLossActionForMsSmoothOutEmitOutput is a InputLossActionForMsSmoothOut enum value @@ -23992,6 +26909,14 @@ const ( InputLossActionForMsSmoothOutPauseOutput = "PAUSE_OUTPUT" ) +// InputLossActionForMsSmoothOut_Values returns all elements of the InputLossActionForMsSmoothOut enum +func InputLossActionForMsSmoothOut_Values() []string { + return []string{ + InputLossActionForMsSmoothOutEmitOutput, + InputLossActionForMsSmoothOutPauseOutput, + } +} + // Input Loss Action For Rtmp Out const ( // InputLossActionForRtmpOutEmitOutput is a InputLossActionForRtmpOut enum value @@ -24001,6 +26926,14 @@ const ( InputLossActionForRtmpOutPauseOutput = "PAUSE_OUTPUT" ) +// InputLossActionForRtmpOut_Values returns all elements of the InputLossActionForRtmpOut enum +func InputLossActionForRtmpOut_Values() []string { + return []string{ + InputLossActionForRtmpOutEmitOutput, + InputLossActionForRtmpOutPauseOutput, + } +} + // Input Loss Action For Udp Out const ( // InputLossActionForUdpOutDropProgram is a InputLossActionForUdpOut enum value @@ -24013,6 +26946,15 @@ const ( InputLossActionForUdpOutEmitProgram = "EMIT_PROGRAM" ) +// InputLossActionForUdpOut_Values returns all elements of the InputLossActionForUdpOut enum +func InputLossActionForUdpOut_Values() []string { + return []string{ + InputLossActionForUdpOutDropProgram, + InputLossActionForUdpOutDropTs, + InputLossActionForUdpOutEmitProgram, + } +} + // Input Loss Image Type const ( // InputLossImageTypeColor is a InputLossImageType enum value @@ -24022,6 +26964,14 @@ const ( InputLossImageTypeSlate = "SLATE" ) +// InputLossImageType_Values returns all elements of the InputLossImageType enum +func InputLossImageType_Values() []string { + return []string{ + InputLossImageTypeColor, + InputLossImageTypeSlate, + } +} + // Maximum input bitrate in megabits per second. Bitrates up to 50 Mbps are // supported currently. const ( @@ -24035,6 +26985,15 @@ const ( InputMaximumBitrateMax50Mbps = "MAX_50_MBPS" ) +// InputMaximumBitrate_Values returns all elements of the InputMaximumBitrate enum +func InputMaximumBitrate_Values() []string { + return []string{ + InputMaximumBitrateMax10Mbps, + InputMaximumBitrateMax20Mbps, + InputMaximumBitrateMax50Mbps, + } +} + // Input preference when deciding which input to make active when a previously // failed input has recovered.If \"EQUAL_INPUT_PREFERENCE\", then the active // input will stay active as long as it is healthy.If \"PRIMARY_INPUT_PREFERRED\", @@ -24047,6 +27006,14 @@ const ( InputPreferencePrimaryInputPreferred = "PRIMARY_INPUT_PREFERRED" ) +// InputPreference_Values returns all elements of the InputPreference enum +func InputPreference_Values() []string { + return []string{ + InputPreferenceEqualInputPreference, + InputPreferencePrimaryInputPreferred, + } +} + // Input resolution based on lines of vertical resolution in the input; SD is // less than 720 lines, HD is 720 to 1080 lines, UHD is greater than 1080 lines const ( @@ -24060,6 +27027,15 @@ const ( InputResolutionUhd = "UHD" ) +// InputResolution_Values returns all elements of the InputResolution enum +func InputResolution_Values() []string { + return []string{ + InputResolutionSd, + InputResolutionHd, + InputResolutionUhd, + } +} + const ( // InputSecurityGroupStateIdle is a InputSecurityGroupState enum value InputSecurityGroupStateIdle = "IDLE" @@ -24074,6 +27050,16 @@ const ( InputSecurityGroupStateDeleted = "DELETED" ) +// InputSecurityGroupState_Values returns all elements of the InputSecurityGroupState enum +func InputSecurityGroupState_Values() []string { + return []string{ + InputSecurityGroupStateIdle, + InputSecurityGroupStateInUse, + InputSecurityGroupStateUpdating, + InputSecurityGroupStateDeleted, + } +} + // Input Source End Behavior const ( // InputSourceEndBehaviorContinue is a InputSourceEndBehavior enum value @@ -24083,6 +27069,14 @@ const ( InputSourceEndBehaviorLoop = "LOOP" ) +// InputSourceEndBehavior_Values returns all elements of the InputSourceEndBehavior enum +func InputSourceEndBehavior_Values() []string { + return []string{ + InputSourceEndBehaviorContinue, + InputSourceEndBehaviorLoop, + } +} + // There are two types of input sources, static and dynamic. If an input source // is dynamic you canchange the source url of the input dynamically using an // input switch action. However, the only input typeto support a dynamic url @@ -24095,6 +27089,14 @@ const ( InputSourceTypeDynamic = "DYNAMIC" ) +// InputSourceType_Values returns all elements of the InputSourceType enum +func InputSourceType_Values() []string { + return []string{ + InputSourceTypeStatic, + InputSourceTypeDynamic, + } +} + const ( // InputStateCreating is a InputState enum value InputStateCreating = "CREATING" @@ -24112,6 +27114,17 @@ const ( InputStateDeleted = "DELETED" ) +// InputState_Values returns all elements of the InputState enum +func InputState_Values() []string { + return []string{ + InputStateCreating, + InputStateDetached, + InputStateAttached, + InputStateDeleting, + InputStateDeleted, + } +} + // To clip the file, you must specify the timecode for the start and end of // the clip. Specify EMBEDDED to use the timecode embedded in the source content. // The embedded timecode must exist in the source content, otherwise MediaLive @@ -24127,6 +27140,14 @@ const ( InputTimecodeSourceEmbedded = "EMBEDDED" ) +// InputTimecodeSource_Values returns all elements of the InputTimecodeSource enum +func InputTimecodeSource_Values() []string { + return []string{ + InputTimecodeSourceZerobased, + InputTimecodeSourceEmbedded, + } +} + const ( // InputTypeUdpPush is a InputType enum value InputTypeUdpPush = "UDP_PUSH" @@ -24148,8 +27169,25 @@ const ( // InputTypeMediaconnect is a InputType enum value InputTypeMediaconnect = "MEDIACONNECT" + + // InputTypeInputDevice is a InputType enum value + InputTypeInputDevice = "INPUT_DEVICE" ) +// InputType_Values returns all elements of the InputType enum +func InputType_Values() []string { + return []string{ + InputTypeUdpPush, + InputTypeRtpPush, + InputTypeRtmpPush, + InputTypeRtmpPull, + InputTypeUrlPull, + InputTypeMp4File, + InputTypeMediaconnect, + InputTypeInputDevice, + } +} + // If you specify a StopTimecode in an input (in order to clip the file), you // can specify if you want the clip to exclude (the default) or include the // frame specified by the timecode. @@ -24161,6 +27199,14 @@ const ( LastFrameClippingBehaviorIncludeLastFrame = "INCLUDE_LAST_FRAME" ) +// LastFrameClippingBehavior_Values returns all elements of the LastFrameClippingBehavior enum +func LastFrameClippingBehavior_Values() []string { + return []string{ + LastFrameClippingBehaviorExcludeLastFrame, + LastFrameClippingBehaviorIncludeLastFrame, + } +} + // The log level the user wants for their channel. const ( // LogLevelError is a LogLevel enum value @@ -24179,6 +27225,17 @@ const ( LogLevelDisabled = "DISABLED" ) +// LogLevel_Values returns all elements of the LogLevel enum +func LogLevel_Values() []string { + return []string{ + LogLevelError, + LogLevelWarning, + LogLevelInfo, + LogLevelDebug, + LogLevelDisabled, + } +} + // M2ts Absent Input Audio Behavior const ( // M2tsAbsentInputAudioBehaviorDrop is a M2tsAbsentInputAudioBehavior enum value @@ -24188,6 +27245,14 @@ const ( M2tsAbsentInputAudioBehaviorEncodeSilence = "ENCODE_SILENCE" ) +// M2tsAbsentInputAudioBehavior_Values returns all elements of the M2tsAbsentInputAudioBehavior enum +func M2tsAbsentInputAudioBehavior_Values() []string { + return []string{ + M2tsAbsentInputAudioBehaviorDrop, + M2tsAbsentInputAudioBehaviorEncodeSilence, + } +} + // M2ts Arib const ( // M2tsAribDisabled is a M2tsArib enum value @@ -24197,6 +27262,14 @@ const ( M2tsAribEnabled = "ENABLED" ) +// M2tsArib_Values returns all elements of the M2tsArib enum +func M2tsArib_Values() []string { + return []string{ + M2tsAribDisabled, + M2tsAribEnabled, + } +} + // M2ts Arib Captions Pid Control const ( // M2tsAribCaptionsPidControlAuto is a M2tsAribCaptionsPidControl enum value @@ -24206,6 +27279,14 @@ const ( M2tsAribCaptionsPidControlUseConfigured = "USE_CONFIGURED" ) +// M2tsAribCaptionsPidControl_Values returns all elements of the M2tsAribCaptionsPidControl enum +func M2tsAribCaptionsPidControl_Values() []string { + return []string{ + M2tsAribCaptionsPidControlAuto, + M2tsAribCaptionsPidControlUseConfigured, + } +} + // M2ts Audio Buffer Model const ( // M2tsAudioBufferModelAtsc is a M2tsAudioBufferModel enum value @@ -24215,6 +27296,14 @@ const ( M2tsAudioBufferModelDvb = "DVB" ) +// M2tsAudioBufferModel_Values returns all elements of the M2tsAudioBufferModel enum +func M2tsAudioBufferModel_Values() []string { + return []string{ + M2tsAudioBufferModelAtsc, + M2tsAudioBufferModelDvb, + } +} + // M2ts Audio Interval const ( // M2tsAudioIntervalVideoAndFixedIntervals is a M2tsAudioInterval enum value @@ -24224,6 +27313,14 @@ const ( M2tsAudioIntervalVideoInterval = "VIDEO_INTERVAL" ) +// M2tsAudioInterval_Values returns all elements of the M2tsAudioInterval enum +func M2tsAudioInterval_Values() []string { + return []string{ + M2tsAudioIntervalVideoAndFixedIntervals, + M2tsAudioIntervalVideoInterval, + } +} + // M2ts Audio Stream Type const ( // M2tsAudioStreamTypeAtsc is a M2tsAudioStreamType enum value @@ -24233,6 +27330,14 @@ const ( M2tsAudioStreamTypeDvb = "DVB" ) +// M2tsAudioStreamType_Values returns all elements of the M2tsAudioStreamType enum +func M2tsAudioStreamType_Values() []string { + return []string{ + M2tsAudioStreamTypeAtsc, + M2tsAudioStreamTypeDvb, + } +} + // M2ts Buffer Model const ( // M2tsBufferModelMultiplex is a M2tsBufferModel enum value @@ -24242,6 +27347,14 @@ const ( M2tsBufferModelNone = "NONE" ) +// M2tsBufferModel_Values returns all elements of the M2tsBufferModel enum +func M2tsBufferModel_Values() []string { + return []string{ + M2tsBufferModelMultiplex, + M2tsBufferModelNone, + } +} + // M2ts Cc Descriptor const ( // M2tsCcDescriptorDisabled is a M2tsCcDescriptor enum value @@ -24251,6 +27364,14 @@ const ( M2tsCcDescriptorEnabled = "ENABLED" ) +// M2tsCcDescriptor_Values returns all elements of the M2tsCcDescriptor enum +func M2tsCcDescriptor_Values() []string { + return []string{ + M2tsCcDescriptorDisabled, + M2tsCcDescriptorEnabled, + } +} + // M2ts Ebif Control const ( // M2tsEbifControlNone is a M2tsEbifControl enum value @@ -24260,6 +27381,14 @@ const ( M2tsEbifControlPassthrough = "PASSTHROUGH" ) +// M2tsEbifControl_Values returns all elements of the M2tsEbifControl enum +func M2tsEbifControl_Values() []string { + return []string{ + M2tsEbifControlNone, + M2tsEbifControlPassthrough, + } +} + // M2ts Ebp Placement const ( // M2tsEbpPlacementVideoAndAudioPids is a M2tsEbpPlacement enum value @@ -24269,6 +27398,14 @@ const ( M2tsEbpPlacementVideoPid = "VIDEO_PID" ) +// M2tsEbpPlacement_Values returns all elements of the M2tsEbpPlacement enum +func M2tsEbpPlacement_Values() []string { + return []string{ + M2tsEbpPlacementVideoAndAudioPids, + M2tsEbpPlacementVideoPid, + } +} + // M2ts Es Rate In Pes const ( // M2tsEsRateInPesExclude is a M2tsEsRateInPes enum value @@ -24278,6 +27415,14 @@ const ( M2tsEsRateInPesInclude = "INCLUDE" ) +// M2tsEsRateInPes_Values returns all elements of the M2tsEsRateInPes enum +func M2tsEsRateInPes_Values() []string { + return []string{ + M2tsEsRateInPesExclude, + M2tsEsRateInPesInclude, + } +} + // M2ts Klv const ( // M2tsKlvNone is a M2tsKlv enum value @@ -24287,6 +27432,14 @@ const ( M2tsKlvPassthrough = "PASSTHROUGH" ) +// M2tsKlv_Values returns all elements of the M2tsKlv enum +func M2tsKlv_Values() []string { + return []string{ + M2tsKlvNone, + M2tsKlvPassthrough, + } +} + // M2ts Nielsen Id3 Behavior const ( // M2tsNielsenId3BehaviorNoPassthrough is a M2tsNielsenId3Behavior enum value @@ -24296,6 +27449,14 @@ const ( M2tsNielsenId3BehaviorPassthrough = "PASSTHROUGH" ) +// M2tsNielsenId3Behavior_Values returns all elements of the M2tsNielsenId3Behavior enum +func M2tsNielsenId3Behavior_Values() []string { + return []string{ + M2tsNielsenId3BehaviorNoPassthrough, + M2tsNielsenId3BehaviorPassthrough, + } +} + // M2ts Pcr Control const ( // M2tsPcrControlConfiguredPcrPeriod is a M2tsPcrControl enum value @@ -24305,6 +27466,14 @@ const ( M2tsPcrControlPcrEveryPesPacket = "PCR_EVERY_PES_PACKET" ) +// M2tsPcrControl_Values returns all elements of the M2tsPcrControl enum +func M2tsPcrControl_Values() []string { + return []string{ + M2tsPcrControlConfiguredPcrPeriod, + M2tsPcrControlPcrEveryPesPacket, + } +} + // M2ts Rate Mode const ( // M2tsRateModeCbr is a M2tsRateMode enum value @@ -24314,6 +27483,14 @@ const ( M2tsRateModeVbr = "VBR" ) +// M2tsRateMode_Values returns all elements of the M2tsRateMode enum +func M2tsRateMode_Values() []string { + return []string{ + M2tsRateModeCbr, + M2tsRateModeVbr, + } +} + // M2ts Scte35 Control const ( // M2tsScte35ControlNone is a M2tsScte35Control enum value @@ -24323,6 +27500,14 @@ const ( M2tsScte35ControlPassthrough = "PASSTHROUGH" ) +// M2tsScte35Control_Values returns all elements of the M2tsScte35Control enum +func M2tsScte35Control_Values() []string { + return []string{ + M2tsScte35ControlNone, + M2tsScte35ControlPassthrough, + } +} + // M2ts Segmentation Markers const ( // M2tsSegmentationMarkersEbp is a M2tsSegmentationMarkers enum value @@ -24344,6 +27529,18 @@ const ( M2tsSegmentationMarkersRaiSegstart = "RAI_SEGSTART" ) +// M2tsSegmentationMarkers_Values returns all elements of the M2tsSegmentationMarkers enum +func M2tsSegmentationMarkers_Values() []string { + return []string{ + M2tsSegmentationMarkersEbp, + M2tsSegmentationMarkersEbpLegacy, + M2tsSegmentationMarkersNone, + M2tsSegmentationMarkersPsiSegstart, + M2tsSegmentationMarkersRaiAdapt, + M2tsSegmentationMarkersRaiSegstart, + } +} + // M2ts Segmentation Style const ( // M2tsSegmentationStyleMaintainCadence is a M2tsSegmentationStyle enum value @@ -24353,6 +27550,14 @@ const ( M2tsSegmentationStyleResetCadence = "RESET_CADENCE" ) +// M2tsSegmentationStyle_Values returns all elements of the M2tsSegmentationStyle enum +func M2tsSegmentationStyle_Values() []string { + return []string{ + M2tsSegmentationStyleMaintainCadence, + M2tsSegmentationStyleResetCadence, + } +} + // M2ts Timed Metadata Behavior const ( // M2tsTimedMetadataBehaviorNoPassthrough is a M2tsTimedMetadataBehavior enum value @@ -24362,6 +27567,14 @@ const ( M2tsTimedMetadataBehaviorPassthrough = "PASSTHROUGH" ) +// M2tsTimedMetadataBehavior_Values returns all elements of the M2tsTimedMetadataBehavior enum +func M2tsTimedMetadataBehavior_Values() []string { + return []string{ + M2tsTimedMetadataBehaviorNoPassthrough, + M2tsTimedMetadataBehaviorPassthrough, + } +} + // M3u8 Nielsen Id3 Behavior const ( // M3u8NielsenId3BehaviorNoPassthrough is a M3u8NielsenId3Behavior enum value @@ -24371,6 +27584,14 @@ const ( M3u8NielsenId3BehaviorPassthrough = "PASSTHROUGH" ) +// M3u8NielsenId3Behavior_Values returns all elements of the M3u8NielsenId3Behavior enum +func M3u8NielsenId3Behavior_Values() []string { + return []string{ + M3u8NielsenId3BehaviorNoPassthrough, + M3u8NielsenId3BehaviorPassthrough, + } +} + // M3u8 Pcr Control const ( // M3u8PcrControlConfiguredPcrPeriod is a M3u8PcrControl enum value @@ -24380,6 +27601,14 @@ const ( M3u8PcrControlPcrEveryPesPacket = "PCR_EVERY_PES_PACKET" ) +// M3u8PcrControl_Values returns all elements of the M3u8PcrControl enum +func M3u8PcrControl_Values() []string { + return []string{ + M3u8PcrControlConfiguredPcrPeriod, + M3u8PcrControlPcrEveryPesPacket, + } +} + // M3u8 Scte35 Behavior const ( // M3u8Scte35BehaviorNoPassthrough is a M3u8Scte35Behavior enum value @@ -24389,6 +27618,14 @@ const ( M3u8Scte35BehaviorPassthrough = "PASSTHROUGH" ) +// M3u8Scte35Behavior_Values returns all elements of the M3u8Scte35Behavior enum +func M3u8Scte35Behavior_Values() []string { + return []string{ + M3u8Scte35BehaviorNoPassthrough, + M3u8Scte35BehaviorPassthrough, + } +} + // M3u8 Timed Metadata Behavior const ( // M3u8TimedMetadataBehaviorNoPassthrough is a M3u8TimedMetadataBehavior enum value @@ -24398,6 +27635,14 @@ const ( M3u8TimedMetadataBehaviorPassthrough = "PASSTHROUGH" ) +// M3u8TimedMetadataBehavior_Values returns all elements of the M3u8TimedMetadataBehavior enum +func M3u8TimedMetadataBehavior_Values() []string { + return []string{ + M3u8TimedMetadataBehaviorNoPassthrough, + M3u8TimedMetadataBehaviorPassthrough, + } +} + // Mp2 Coding Mode const ( // Mp2CodingModeCodingMode10 is a Mp2CodingMode enum value @@ -24407,6 +27652,14 @@ const ( Mp2CodingModeCodingMode20 = "CODING_MODE_2_0" ) +// Mp2CodingMode_Values returns all elements of the Mp2CodingMode enum +func Mp2CodingMode_Values() []string { + return []string{ + Mp2CodingModeCodingMode10, + Mp2CodingModeCodingMode20, + } +} + // Ms Smooth H265 Packaging Type const ( // MsSmoothH265PackagingTypeHev1 is a MsSmoothH265PackagingType enum value @@ -24416,6 +27669,14 @@ const ( MsSmoothH265PackagingTypeHvc1 = "HVC1" ) +// MsSmoothH265PackagingType_Values returns all elements of the MsSmoothH265PackagingType enum +func MsSmoothH265PackagingType_Values() []string { + return []string{ + MsSmoothH265PackagingTypeHev1, + MsSmoothH265PackagingTypeHvc1, + } +} + // The current state of the multiplex. const ( // MultiplexStateCreating is a MultiplexState enum value @@ -24446,6 +27707,21 @@ const ( MultiplexStateDeleted = "DELETED" ) +// MultiplexState_Values returns all elements of the MultiplexState enum +func MultiplexState_Values() []string { + return []string{ + MultiplexStateCreating, + MultiplexStateCreateFailed, + MultiplexStateIdle, + MultiplexStateStarting, + MultiplexStateRunning, + MultiplexStateRecovering, + MultiplexStateStopping, + MultiplexStateDeleting, + MultiplexStateDeleted, + } +} + // Network Input Server Validation const ( // NetworkInputServerValidationCheckCryptographyAndValidateName is a NetworkInputServerValidation enum value @@ -24455,6 +27731,14 @@ const ( NetworkInputServerValidationCheckCryptographyOnly = "CHECK_CRYPTOGRAPHY_ONLY" ) +// NetworkInputServerValidation_Values returns all elements of the NetworkInputServerValidation enum +func NetworkInputServerValidation_Values() []string { + return []string{ + NetworkInputServerValidationCheckCryptographyAndValidateName, + NetworkInputServerValidationCheckCryptographyOnly, + } +} + // State of Nielsen PCM to ID3 tagging const ( // NielsenPcmToId3TaggingStateDisabled is a NielsenPcmToId3TaggingState enum value @@ -24464,18 +27748,40 @@ const ( NielsenPcmToId3TaggingStateEnabled = "ENABLED" ) +// NielsenPcmToId3TaggingState_Values returns all elements of the NielsenPcmToId3TaggingState enum +func NielsenPcmToId3TaggingState_Values() []string { + return []string{ + NielsenPcmToId3TaggingStateDisabled, + NielsenPcmToId3TaggingStateEnabled, + } +} + // Units for duration, e.g. 'MONTHS' const ( // OfferingDurationUnitsMonths is a OfferingDurationUnits enum value OfferingDurationUnitsMonths = "MONTHS" ) +// OfferingDurationUnits_Values returns all elements of the OfferingDurationUnits enum +func OfferingDurationUnits_Values() []string { + return []string{ + OfferingDurationUnitsMonths, + } +} + // Offering type, e.g. 'NO_UPFRONT' const ( // OfferingTypeNoUpfront is a OfferingType enum value OfferingTypeNoUpfront = "NO_UPFRONT" ) +// OfferingType_Values returns all elements of the OfferingType enum +func OfferingType_Values() []string { + return []string{ + OfferingTypeNoUpfront, + } +} + // Pipeline ID const ( // PipelineIdPipeline0 is a PipelineId enum value @@ -24485,6 +27791,14 @@ const ( PipelineIdPipeline1 = "PIPELINE_1" ) +// PipelineId_Values returns all elements of the PipelineId enum +func PipelineId_Values() []string { + return []string{ + PipelineIdPipeline0, + PipelineIdPipeline1, + } +} + // Indicates which pipeline is preferred by the multiplex for program ingest.If // set to \"PIPELINE_0\" or \"PIPELINE_1\" and an unhealthy ingest causes the // multiplex to switch to the non-preferred pipeline,it will switch back once @@ -24502,6 +27816,15 @@ const ( PreferredChannelPipelinePipeline1 = "PIPELINE_1" ) +// PreferredChannelPipeline_Values returns all elements of the PreferredChannelPipeline enum +func PreferredChannelPipeline_Values() []string { + return []string{ + PreferredChannelPipelineCurrentlyActive, + PreferredChannelPipelinePipeline0, + PreferredChannelPipelinePipeline1, + } +} + // Codec, 'MPEG2', 'AVC', 'HEVC', or 'AUDIO' const ( // ReservationCodecMpeg2 is a ReservationCodec enum value @@ -24517,6 +27840,16 @@ const ( ReservationCodecAudio = "AUDIO" ) +// ReservationCodec_Values returns all elements of the ReservationCodec enum +func ReservationCodec_Values() []string { + return []string{ + ReservationCodecMpeg2, + ReservationCodecAvc, + ReservationCodecHevc, + ReservationCodecAudio, + } +} + // Maximum bitrate in megabits per second const ( // ReservationMaximumBitrateMax10Mbps is a ReservationMaximumBitrate enum value @@ -24529,6 +27862,15 @@ const ( ReservationMaximumBitrateMax50Mbps = "MAX_50_MBPS" ) +// ReservationMaximumBitrate_Values returns all elements of the ReservationMaximumBitrate enum +func ReservationMaximumBitrate_Values() []string { + return []string{ + ReservationMaximumBitrateMax10Mbps, + ReservationMaximumBitrateMax20Mbps, + ReservationMaximumBitrateMax50Mbps, + } +} + // Maximum framerate in frames per second (Outputs only) const ( // ReservationMaximumFramerateMax30Fps is a ReservationMaximumFramerate enum value @@ -24538,6 +27880,14 @@ const ( ReservationMaximumFramerateMax60Fps = "MAX_60_FPS" ) +// ReservationMaximumFramerate_Values returns all elements of the ReservationMaximumFramerate enum +func ReservationMaximumFramerate_Values() []string { + return []string{ + ReservationMaximumFramerateMax30Fps, + ReservationMaximumFramerateMax60Fps, + } +} + // Resolution based on lines of vertical resolution; SD is less than 720 lines, // HD is 720 to 1080 lines, FHD is 1080 lines, UHD is greater than 1080 lines const ( @@ -24554,6 +27904,16 @@ const ( ReservationResolutionUhd = "UHD" ) +// ReservationResolution_Values returns all elements of the ReservationResolution enum +func ReservationResolution_Values() []string { + return []string{ + ReservationResolutionSd, + ReservationResolutionHd, + ReservationResolutionFhd, + ReservationResolutionUhd, + } +} + // Resource type, 'INPUT', 'OUTPUT', 'MULTIPLEX', or 'CHANNEL' const ( // ReservationResourceTypeInput is a ReservationResourceType enum value @@ -24569,6 +27929,16 @@ const ( ReservationResourceTypeChannel = "CHANNEL" ) +// ReservationResourceType_Values returns all elements of the ReservationResourceType enum +func ReservationResourceType_Values() []string { + return []string{ + ReservationResourceTypeInput, + ReservationResourceTypeOutput, + ReservationResourceTypeMultiplex, + ReservationResourceTypeChannel, + } +} + // Special features, 'ADVANCED_AUDIO' or 'AUDIO_NORMALIZATION' const ( // ReservationSpecialFeatureAdvancedAudio is a ReservationSpecialFeature enum value @@ -24578,6 +27948,14 @@ const ( ReservationSpecialFeatureAudioNormalization = "AUDIO_NORMALIZATION" ) +// ReservationSpecialFeature_Values returns all elements of the ReservationSpecialFeature enum +func ReservationSpecialFeature_Values() []string { + return []string{ + ReservationSpecialFeatureAdvancedAudio, + ReservationSpecialFeatureAudioNormalization, + } +} + // Current reservation state const ( // ReservationStateActive is a ReservationState enum value @@ -24593,6 +27971,16 @@ const ( ReservationStateDeleted = "DELETED" ) +// ReservationState_Values returns all elements of the ReservationState enum +func ReservationState_Values() []string { + return []string{ + ReservationStateActive, + ReservationStateExpired, + ReservationStateCanceled, + ReservationStateDeleted, + } +} + // Video quality, e.g. 'STANDARD' (Outputs only) const ( // ReservationVideoQualityStandard is a ReservationVideoQuality enum value @@ -24605,6 +27993,15 @@ const ( ReservationVideoQualityPremium = "PREMIUM" ) +// ReservationVideoQuality_Values returns all elements of the ReservationVideoQuality enum +func ReservationVideoQuality_Values() []string { + return []string{ + ReservationVideoQualityStandard, + ReservationVideoQualityEnhanced, + ReservationVideoQualityPremium, + } +} + // Rtmp Cache Full Behavior const ( // RtmpCacheFullBehaviorDisconnectImmediately is a RtmpCacheFullBehavior enum value @@ -24614,6 +28011,14 @@ const ( RtmpCacheFullBehaviorWaitForServer = "WAIT_FOR_SERVER" ) +// RtmpCacheFullBehavior_Values returns all elements of the RtmpCacheFullBehavior enum +func RtmpCacheFullBehavior_Values() []string { + return []string{ + RtmpCacheFullBehaviorDisconnectImmediately, + RtmpCacheFullBehaviorWaitForServer, + } +} + // Rtmp Caption Data const ( // RtmpCaptionDataAll is a RtmpCaptionData enum value @@ -24626,6 +28031,15 @@ const ( RtmpCaptionDataField1AndField2608 = "FIELD1_AND_FIELD2_608" ) +// RtmpCaptionData_Values returns all elements of the RtmpCaptionData enum +func RtmpCaptionData_Values() []string { + return []string{ + RtmpCaptionDataAll, + RtmpCaptionDataField1608, + RtmpCaptionDataField1AndField2608, + } +} + // Rtmp Output Certificate Mode const ( // RtmpOutputCertificateModeSelfSigned is a RtmpOutputCertificateMode enum value @@ -24635,6 +28049,14 @@ const ( RtmpOutputCertificateModeVerifyAuthenticity = "VERIFY_AUTHENTICITY" ) +// RtmpOutputCertificateMode_Values returns all elements of the RtmpOutputCertificateMode enum +func RtmpOutputCertificateMode_Values() []string { + return []string{ + RtmpOutputCertificateModeSelfSigned, + RtmpOutputCertificateModeVerifyAuthenticity, + } +} + // Scte20 Convert608 To708 const ( // Scte20Convert608To708Disabled is a Scte20Convert608To708 enum value @@ -24644,6 +28066,14 @@ const ( Scte20Convert608To708Upconvert = "UPCONVERT" ) +// Scte20Convert608To708_Values returns all elements of the Scte20Convert608To708 enum +func Scte20Convert608To708_Values() []string { + return []string{ + Scte20Convert608To708Disabled, + Scte20Convert608To708Upconvert, + } +} + // Scte35 Apos No Regional Blackout Behavior const ( // Scte35AposNoRegionalBlackoutBehaviorFollow is a Scte35AposNoRegionalBlackoutBehavior enum value @@ -24653,6 +28083,14 @@ const ( Scte35AposNoRegionalBlackoutBehaviorIgnore = "IGNORE" ) +// Scte35AposNoRegionalBlackoutBehavior_Values returns all elements of the Scte35AposNoRegionalBlackoutBehavior enum +func Scte35AposNoRegionalBlackoutBehavior_Values() []string { + return []string{ + Scte35AposNoRegionalBlackoutBehaviorFollow, + Scte35AposNoRegionalBlackoutBehaviorIgnore, + } +} + // Scte35 Apos Web Delivery Allowed Behavior const ( // Scte35AposWebDeliveryAllowedBehaviorFollow is a Scte35AposWebDeliveryAllowedBehavior enum value @@ -24662,6 +28100,14 @@ const ( Scte35AposWebDeliveryAllowedBehaviorIgnore = "IGNORE" ) +// Scte35AposWebDeliveryAllowedBehavior_Values returns all elements of the Scte35AposWebDeliveryAllowedBehavior enum +func Scte35AposWebDeliveryAllowedBehavior_Values() []string { + return []string{ + Scte35AposWebDeliveryAllowedBehaviorFollow, + Scte35AposWebDeliveryAllowedBehaviorIgnore, + } +} + // Corresponds to the archive_allowed parameter. A value of ARCHIVE_NOT_ALLOWED // corresponds to 0 (false) in the SCTE-35 specification. If you include one // of the "restriction" flags then you must include all four of them. @@ -24673,6 +28119,14 @@ const ( Scte35ArchiveAllowedFlagArchiveAllowed = "ARCHIVE_ALLOWED" ) +// Scte35ArchiveAllowedFlag_Values returns all elements of the Scte35ArchiveAllowedFlag enum +func Scte35ArchiveAllowedFlag_Values() []string { + return []string{ + Scte35ArchiveAllowedFlagArchiveNotAllowed, + Scte35ArchiveAllowedFlagArchiveAllowed, + } +} + // Corresponds to the device_restrictions parameter in a segmentation_descriptor. // If you include one of the "restriction" flags then you must include all four // of them. @@ -24690,6 +28144,16 @@ const ( Scte35DeviceRestrictionsRestrictGroup2 = "RESTRICT_GROUP2" ) +// Scte35DeviceRestrictions_Values returns all elements of the Scte35DeviceRestrictions enum +func Scte35DeviceRestrictions_Values() []string { + return []string{ + Scte35DeviceRestrictionsNone, + Scte35DeviceRestrictionsRestrictGroup0, + Scte35DeviceRestrictionsRestrictGroup1, + Scte35DeviceRestrictionsRestrictGroup2, + } +} + // Corresponds to the no_regional_blackout_flag parameter. A value of REGIONAL_BLACKOUT // corresponds to 0 (false) in the SCTE-35 specification. If you include one // of the "restriction" flags then you must include all four of them. @@ -24701,6 +28165,14 @@ const ( Scte35NoRegionalBlackoutFlagNoRegionalBlackout = "NO_REGIONAL_BLACKOUT" ) +// Scte35NoRegionalBlackoutFlag_Values returns all elements of the Scte35NoRegionalBlackoutFlag enum +func Scte35NoRegionalBlackoutFlag_Values() []string { + return []string{ + Scte35NoRegionalBlackoutFlagRegionalBlackout, + Scte35NoRegionalBlackoutFlagNoRegionalBlackout, + } +} + // Corresponds to SCTE-35 segmentation_event_cancel_indicator. SEGMENTATION_EVENT_NOT_CANCELED // corresponds to 0 in the SCTE-35 specification and indicates that this is // an insertion request. SEGMENTATION_EVENT_CANCELED corresponds to 1 in the @@ -24714,6 +28186,14 @@ const ( Scte35SegmentationCancelIndicatorSegmentationEventCanceled = "SEGMENTATION_EVENT_CANCELED" ) +// Scte35SegmentationCancelIndicator_Values returns all elements of the Scte35SegmentationCancelIndicator enum +func Scte35SegmentationCancelIndicator_Values() []string { + return []string{ + Scte35SegmentationCancelIndicatorSegmentationEventNotCanceled, + Scte35SegmentationCancelIndicatorSegmentationEventCanceled, + } +} + // Scte35 Splice Insert No Regional Blackout Behavior const ( // Scte35SpliceInsertNoRegionalBlackoutBehaviorFollow is a Scte35SpliceInsertNoRegionalBlackoutBehavior enum value @@ -24723,6 +28203,14 @@ const ( Scte35SpliceInsertNoRegionalBlackoutBehaviorIgnore = "IGNORE" ) +// Scte35SpliceInsertNoRegionalBlackoutBehavior_Values returns all elements of the Scte35SpliceInsertNoRegionalBlackoutBehavior enum +func Scte35SpliceInsertNoRegionalBlackoutBehavior_Values() []string { + return []string{ + Scte35SpliceInsertNoRegionalBlackoutBehaviorFollow, + Scte35SpliceInsertNoRegionalBlackoutBehaviorIgnore, + } +} + // Scte35 Splice Insert Web Delivery Allowed Behavior const ( // Scte35SpliceInsertWebDeliveryAllowedBehaviorFollow is a Scte35SpliceInsertWebDeliveryAllowedBehavior enum value @@ -24732,6 +28220,14 @@ const ( Scte35SpliceInsertWebDeliveryAllowedBehaviorIgnore = "IGNORE" ) +// Scte35SpliceInsertWebDeliveryAllowedBehavior_Values returns all elements of the Scte35SpliceInsertWebDeliveryAllowedBehavior enum +func Scte35SpliceInsertWebDeliveryAllowedBehavior_Values() []string { + return []string{ + Scte35SpliceInsertWebDeliveryAllowedBehaviorFollow, + Scte35SpliceInsertWebDeliveryAllowedBehaviorIgnore, + } +} + // Corresponds to the web_delivery_allowed_flag parameter. A value of WEB_DELIVERY_NOT_ALLOWED // corresponds to 0 (false) in the SCTE-35 specification. If you include one // of the "restriction" flags then you must include all four of them. @@ -24743,6 +28239,14 @@ const ( Scte35WebDeliveryAllowedFlagWebDeliveryAllowed = "WEB_DELIVERY_ALLOWED" ) +// Scte35WebDeliveryAllowedFlag_Values returns all elements of the Scte35WebDeliveryAllowedFlag enum +func Scte35WebDeliveryAllowedFlag_Values() []string { + return []string{ + Scte35WebDeliveryAllowedFlagWebDeliveryNotAllowed, + Scte35WebDeliveryAllowedFlagWebDeliveryAllowed, + } +} + // Smooth Group Audio Only Timecode Control const ( // SmoothGroupAudioOnlyTimecodeControlPassthrough is a SmoothGroupAudioOnlyTimecodeControl enum value @@ -24752,6 +28256,14 @@ const ( SmoothGroupAudioOnlyTimecodeControlUseConfiguredClock = "USE_CONFIGURED_CLOCK" ) +// SmoothGroupAudioOnlyTimecodeControl_Values returns all elements of the SmoothGroupAudioOnlyTimecodeControl enum +func SmoothGroupAudioOnlyTimecodeControl_Values() []string { + return []string{ + SmoothGroupAudioOnlyTimecodeControlPassthrough, + SmoothGroupAudioOnlyTimecodeControlUseConfiguredClock, + } +} + // Smooth Group Certificate Mode const ( // SmoothGroupCertificateModeSelfSigned is a SmoothGroupCertificateMode enum value @@ -24761,6 +28273,14 @@ const ( SmoothGroupCertificateModeVerifyAuthenticity = "VERIFY_AUTHENTICITY" ) +// SmoothGroupCertificateMode_Values returns all elements of the SmoothGroupCertificateMode enum +func SmoothGroupCertificateMode_Values() []string { + return []string{ + SmoothGroupCertificateModeSelfSigned, + SmoothGroupCertificateModeVerifyAuthenticity, + } +} + // Smooth Group Event Id Mode const ( // SmoothGroupEventIdModeNoEventId is a SmoothGroupEventIdMode enum value @@ -24773,6 +28293,15 @@ const ( SmoothGroupEventIdModeUseTimestamp = "USE_TIMESTAMP" ) +// SmoothGroupEventIdMode_Values returns all elements of the SmoothGroupEventIdMode enum +func SmoothGroupEventIdMode_Values() []string { + return []string{ + SmoothGroupEventIdModeNoEventId, + SmoothGroupEventIdModeUseConfigured, + SmoothGroupEventIdModeUseTimestamp, + } +} + // Smooth Group Event Stop Behavior const ( // SmoothGroupEventStopBehaviorNone is a SmoothGroupEventStopBehavior enum value @@ -24782,6 +28311,14 @@ const ( SmoothGroupEventStopBehaviorSendEos = "SEND_EOS" ) +// SmoothGroupEventStopBehavior_Values returns all elements of the SmoothGroupEventStopBehavior enum +func SmoothGroupEventStopBehavior_Values() []string { + return []string{ + SmoothGroupEventStopBehaviorNone, + SmoothGroupEventStopBehaviorSendEos, + } +} + // Smooth Group Segmentation Mode const ( // SmoothGroupSegmentationModeUseInputSegmentation is a SmoothGroupSegmentationMode enum value @@ -24791,6 +28328,14 @@ const ( SmoothGroupSegmentationModeUseSegmentDuration = "USE_SEGMENT_DURATION" ) +// SmoothGroupSegmentationMode_Values returns all elements of the SmoothGroupSegmentationMode enum +func SmoothGroupSegmentationMode_Values() []string { + return []string{ + SmoothGroupSegmentationModeUseInputSegmentation, + SmoothGroupSegmentationModeUseSegmentDuration, + } +} + // Smooth Group Sparse Track Type const ( // SmoothGroupSparseTrackTypeNone is a SmoothGroupSparseTrackType enum value @@ -24803,6 +28348,15 @@ const ( SmoothGroupSparseTrackTypeScte35WithoutSegmentation = "SCTE_35_WITHOUT_SEGMENTATION" ) +// SmoothGroupSparseTrackType_Values returns all elements of the SmoothGroupSparseTrackType enum +func SmoothGroupSparseTrackType_Values() []string { + return []string{ + SmoothGroupSparseTrackTypeNone, + SmoothGroupSparseTrackTypeScte35, + SmoothGroupSparseTrackTypeScte35WithoutSegmentation, + } +} + // Smooth Group Stream Manifest Behavior const ( // SmoothGroupStreamManifestBehaviorDoNotSend is a SmoothGroupStreamManifestBehavior enum value @@ -24812,6 +28366,14 @@ const ( SmoothGroupStreamManifestBehaviorSend = "SEND" ) +// SmoothGroupStreamManifestBehavior_Values returns all elements of the SmoothGroupStreamManifestBehavior enum +func SmoothGroupStreamManifestBehavior_Values() []string { + return []string{ + SmoothGroupStreamManifestBehaviorDoNotSend, + SmoothGroupStreamManifestBehaviorSend, + } +} + // Smooth Group Timestamp Offset Mode const ( // SmoothGroupTimestampOffsetModeUseConfiguredOffset is a SmoothGroupTimestampOffsetMode enum value @@ -24821,6 +28383,31 @@ const ( SmoothGroupTimestampOffsetModeUseEventStartDate = "USE_EVENT_START_DATE" ) +// SmoothGroupTimestampOffsetMode_Values returns all elements of the SmoothGroupTimestampOffsetMode enum +func SmoothGroupTimestampOffsetMode_Values() []string { + return []string{ + SmoothGroupTimestampOffsetModeUseConfiguredOffset, + SmoothGroupTimestampOffsetModeUseEventStartDate, + } +} + +// Smpte2038 Data Preference +const ( + // Smpte2038DataPreferenceIgnore is a Smpte2038DataPreference enum value + Smpte2038DataPreferenceIgnore = "IGNORE" + + // Smpte2038DataPreferencePrefer is a Smpte2038DataPreference enum value + Smpte2038DataPreferencePrefer = "PREFER" +) + +// Smpte2038DataPreference_Values returns all elements of the Smpte2038DataPreference enum +func Smpte2038DataPreference_Values() []string { + return []string{ + Smpte2038DataPreferenceIgnore, + Smpte2038DataPreferencePrefer, + } +} + // Temporal Filter Post Filter Sharpening const ( // TemporalFilterPostFilterSharpeningAuto is a TemporalFilterPostFilterSharpening enum value @@ -24833,6 +28420,15 @@ const ( TemporalFilterPostFilterSharpeningEnabled = "ENABLED" ) +// TemporalFilterPostFilterSharpening_Values returns all elements of the TemporalFilterPostFilterSharpening enum +func TemporalFilterPostFilterSharpening_Values() []string { + return []string{ + TemporalFilterPostFilterSharpeningAuto, + TemporalFilterPostFilterSharpeningDisabled, + TemporalFilterPostFilterSharpeningEnabled, + } +} + // Temporal Filter Strength const ( // TemporalFilterStrengthAuto is a TemporalFilterStrength enum value @@ -24841,27 +28437,6 @@ const ( // TemporalFilterStrengthStrength1 is a TemporalFilterStrength enum value TemporalFilterStrengthStrength1 = "STRENGTH_1" - // TemporalFilterStrengthStrength10 is a TemporalFilterStrength enum value - TemporalFilterStrengthStrength10 = "STRENGTH_10" - - // TemporalFilterStrengthStrength11 is a TemporalFilterStrength enum value - TemporalFilterStrengthStrength11 = "STRENGTH_11" - - // TemporalFilterStrengthStrength12 is a TemporalFilterStrength enum value - TemporalFilterStrengthStrength12 = "STRENGTH_12" - - // TemporalFilterStrengthStrength13 is a TemporalFilterStrength enum value - TemporalFilterStrengthStrength13 = "STRENGTH_13" - - // TemporalFilterStrengthStrength14 is a TemporalFilterStrength enum value - TemporalFilterStrengthStrength14 = "STRENGTH_14" - - // TemporalFilterStrengthStrength15 is a TemporalFilterStrength enum value - TemporalFilterStrengthStrength15 = "STRENGTH_15" - - // TemporalFilterStrengthStrength16 is a TemporalFilterStrength enum value - TemporalFilterStrengthStrength16 = "STRENGTH_16" - // TemporalFilterStrengthStrength2 is a TemporalFilterStrength enum value TemporalFilterStrengthStrength2 = "STRENGTH_2" @@ -24885,8 +28460,52 @@ const ( // TemporalFilterStrengthStrength9 is a TemporalFilterStrength enum value TemporalFilterStrengthStrength9 = "STRENGTH_9" + + // TemporalFilterStrengthStrength10 is a TemporalFilterStrength enum value + TemporalFilterStrengthStrength10 = "STRENGTH_10" + + // TemporalFilterStrengthStrength11 is a TemporalFilterStrength enum value + TemporalFilterStrengthStrength11 = "STRENGTH_11" + + // TemporalFilterStrengthStrength12 is a TemporalFilterStrength enum value + TemporalFilterStrengthStrength12 = "STRENGTH_12" + + // TemporalFilterStrengthStrength13 is a TemporalFilterStrength enum value + TemporalFilterStrengthStrength13 = "STRENGTH_13" + + // TemporalFilterStrengthStrength14 is a TemporalFilterStrength enum value + TemporalFilterStrengthStrength14 = "STRENGTH_14" + + // TemporalFilterStrengthStrength15 is a TemporalFilterStrength enum value + TemporalFilterStrengthStrength15 = "STRENGTH_15" + + // TemporalFilterStrengthStrength16 is a TemporalFilterStrength enum value + TemporalFilterStrengthStrength16 = "STRENGTH_16" ) +// TemporalFilterStrength_Values returns all elements of the TemporalFilterStrength enum +func TemporalFilterStrength_Values() []string { + return []string{ + TemporalFilterStrengthAuto, + TemporalFilterStrengthStrength1, + TemporalFilterStrengthStrength2, + TemporalFilterStrengthStrength3, + TemporalFilterStrengthStrength4, + TemporalFilterStrengthStrength5, + TemporalFilterStrengthStrength6, + TemporalFilterStrengthStrength7, + TemporalFilterStrengthStrength8, + TemporalFilterStrengthStrength9, + TemporalFilterStrengthStrength10, + TemporalFilterStrengthStrength11, + TemporalFilterStrengthStrength12, + TemporalFilterStrengthStrength13, + TemporalFilterStrengthStrength14, + TemporalFilterStrengthStrength15, + TemporalFilterStrengthStrength16, + } +} + // Timecode Config Source const ( // TimecodeConfigSourceEmbedded is a TimecodeConfigSource enum value @@ -24899,6 +28518,15 @@ const ( TimecodeConfigSourceZerobased = "ZEROBASED" ) +// TimecodeConfigSource_Values returns all elements of the TimecodeConfigSource enum +func TimecodeConfigSource_Values() []string { + return []string{ + TimecodeConfigSourceEmbedded, + TimecodeConfigSourceSystemclock, + TimecodeConfigSourceZerobased, + } +} + // Ttml Destination Style Control const ( // TtmlDestinationStyleControlPassthrough is a TtmlDestinationStyleControl enum value @@ -24908,6 +28536,14 @@ const ( TtmlDestinationStyleControlUseConfigured = "USE_CONFIGURED" ) +// TtmlDestinationStyleControl_Values returns all elements of the TtmlDestinationStyleControl enum +func TtmlDestinationStyleControl_Values() []string { + return []string{ + TtmlDestinationStyleControlPassthrough, + TtmlDestinationStyleControlUseConfigured, + } +} + // Udp Timed Metadata Id3 Frame const ( // UdpTimedMetadataId3FrameNone is a UdpTimedMetadataId3Frame enum value @@ -24920,6 +28556,15 @@ const ( UdpTimedMetadataId3FrameTdrl = "TDRL" ) +// UdpTimedMetadataId3Frame_Values returns all elements of the UdpTimedMetadataId3Frame enum +func UdpTimedMetadataId3Frame_Values() []string { + return []string{ + UdpTimedMetadataId3FrameNone, + UdpTimedMetadataId3FramePriv, + UdpTimedMetadataId3FrameTdrl, + } +} + // Video Description Respond To Afd const ( // VideoDescriptionRespondToAfdNone is a VideoDescriptionRespondToAfd enum value @@ -24932,6 +28577,15 @@ const ( VideoDescriptionRespondToAfdRespond = "RESPOND" ) +// VideoDescriptionRespondToAfd_Values returns all elements of the VideoDescriptionRespondToAfd enum +func VideoDescriptionRespondToAfd_Values() []string { + return []string{ + VideoDescriptionRespondToAfdNone, + VideoDescriptionRespondToAfdPassthrough, + VideoDescriptionRespondToAfdRespond, + } +} + // Video Description Scaling Behavior const ( // VideoDescriptionScalingBehaviorDefault is a VideoDescriptionScalingBehavior enum value @@ -24941,6 +28595,14 @@ const ( VideoDescriptionScalingBehaviorStretchToOutput = "STRETCH_TO_OUTPUT" ) +// VideoDescriptionScalingBehavior_Values returns all elements of the VideoDescriptionScalingBehavior enum +func VideoDescriptionScalingBehavior_Values() []string { + return []string{ + VideoDescriptionScalingBehaviorDefault, + VideoDescriptionScalingBehaviorStretchToOutput, + } +} + // Video Selector Color Space const ( // VideoSelectorColorSpaceFollow is a VideoSelectorColorSpace enum value @@ -24953,6 +28615,15 @@ const ( VideoSelectorColorSpaceRec709 = "REC_709" ) +// VideoSelectorColorSpace_Values returns all elements of the VideoSelectorColorSpace enum +func VideoSelectorColorSpace_Values() []string { + return []string{ + VideoSelectorColorSpaceFollow, + VideoSelectorColorSpaceRec601, + VideoSelectorColorSpaceRec709, + } +} + // Video Selector Color Space Usage const ( // VideoSelectorColorSpaceUsageFallback is a VideoSelectorColorSpaceUsage enum value @@ -24961,3 +28632,11 @@ const ( // VideoSelectorColorSpaceUsageForce is a VideoSelectorColorSpaceUsage enum value VideoSelectorColorSpaceUsageForce = "FORCE" ) + +// VideoSelectorColorSpaceUsage_Values returns all elements of the VideoSelectorColorSpaceUsage enum +func VideoSelectorColorSpaceUsage_Values() []string { + return []string{ + VideoSelectorColorSpaceUsageFallback, + VideoSelectorColorSpaceUsageForce, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/medialive/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/medialive/waiters.go index 0ad1f21b249..88b51e2ab9e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/medialive/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/medialive/waiters.go @@ -238,6 +238,179 @@ func (c *MediaLive) WaitUntilChannelStoppedWithContext(ctx aws.Context, input *D return w.WaitWithContext(ctx) } +// WaitUntilInputAttached uses the MediaLive API operation +// DescribeInput to wait for a condition to be met before returning. +// If the condition is not met within the max attempt window, an error will +// be returned. +func (c *MediaLive) WaitUntilInputAttached(input *DescribeInputInput) error { + return c.WaitUntilInputAttachedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInputAttachedWithContext is an extended version of WaitUntilInputAttached. +// 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 *MediaLive) WaitUntilInputAttachedWithContext(ctx aws.Context, input *DescribeInputInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInputAttached", + MaxAttempts: 20, + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "State", + Expected: "ATTACHED", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "State", + Expected: "DETACHED", + }, + { + State: request.RetryWaiterState, + Matcher: request.StatusWaiterMatch, + Expected: 500, + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInputInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInputRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} + +// WaitUntilInputDeleted uses the MediaLive API operation +// DescribeInput to wait for a condition to be met before returning. +// If the condition is not met within the max attempt window, an error will +// be returned. +func (c *MediaLive) WaitUntilInputDeleted(input *DescribeInputInput) error { + return c.WaitUntilInputDeletedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInputDeletedWithContext is an extended version of WaitUntilInputDeleted. +// 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 *MediaLive) WaitUntilInputDeletedWithContext(ctx aws.Context, input *DescribeInputInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInputDeleted", + MaxAttempts: 20, + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "State", + Expected: "DELETED", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "State", + Expected: "DELETING", + }, + { + State: request.RetryWaiterState, + Matcher: request.StatusWaiterMatch, + Expected: 500, + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInputInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInputRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} + +// WaitUntilInputDetached uses the MediaLive API operation +// DescribeInput to wait for a condition to be met before returning. +// If the condition is not met within the max attempt window, an error will +// be returned. +func (c *MediaLive) WaitUntilInputDetached(input *DescribeInputInput) error { + return c.WaitUntilInputDetachedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilInputDetachedWithContext is an extended version of WaitUntilInputDetached. +// 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 *MediaLive) WaitUntilInputDetachedWithContext(ctx aws.Context, input *DescribeInputInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilInputDetached", + MaxAttempts: 84, + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "State", + Expected: "DETACHED", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "State", + Expected: "CREATING", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "State", + Expected: "ATTACHED", + }, + { + State: request.RetryWaiterState, + Matcher: request.StatusWaiterMatch, + Expected: 500, + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeInputInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInputRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} + // WaitUntilMultiplexCreated uses the MediaLive API operation // DescribeMultiplex to wait for a condition to be met before returning. // If the condition is not met within the max attempt window, an error will diff --git a/vendor/github.com/aws/aws-sdk-go/service/mediapackage/api.go b/vendor/github.com/aws/aws-sdk-go/service/mediapackage/api.go index 23f6d0237c8..6a2f30f2a36 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/mediapackage/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/mediapackage/api.go @@ -3681,7 +3681,10 @@ type HlsManifest struct { // will omit all SCTE-35 ad markers from the output."PASSTHROUGH" causes the // manifest to contain a copy of the SCTE-35 admarkers (comments) taken directly // from the input HTTP Live Streaming (HLS) manifest."SCTE35_ENHANCED" generates - // ad markers and blackout tags based on SCTE-35messages in the input source. + // ad markers and blackout tags based on SCTE-35messages in the input source."DATERANGE" + // inserts EXT-X-DATERANGE tags to signal ad and program transition events in + // HLS and CMAF manifests. For this option, you must set a programDateTimeIntervalSeconds + // value that is greater than 0. AdMarkers *string `locationName:"adMarkers" type:"string" enum:"AdMarkers"` // The ID of the manifest. The ID must be unique within the OriginEndpoint and @@ -3785,7 +3788,10 @@ type HlsManifestCreateOrUpdateParameters struct { // will omit all SCTE-35 ad markers from the output."PASSTHROUGH" causes the // manifest to contain a copy of the SCTE-35 admarkers (comments) taken directly // from the input HTTP Live Streaming (HLS) manifest."SCTE35_ENHANCED" generates - // ad markers and blackout tags based on SCTE-35messages in the input source. + // ad markers and blackout tags based on SCTE-35messages in the input source."DATERANGE" + // inserts EXT-X-DATERANGE tags to signal ad and program transition events in + // HLS and CMAF manifests. For this option, you must set a programDateTimeIntervalSeconds + // value that is greater than 0. AdMarkers *string `locationName:"adMarkers" type:"string" enum:"AdMarkers"` // A list of SCTE-35 message types that are treated as ad markers in the output. @@ -3922,7 +3928,10 @@ type HlsPackage struct { // will omit all SCTE-35 ad markers from the output."PASSTHROUGH" causes the // manifest to contain a copy of the SCTE-35 admarkers (comments) taken directly // from the input HTTP Live Streaming (HLS) manifest."SCTE35_ENHANCED" generates - // ad markers and blackout tags based on SCTE-35messages in the input source. + // ad markers and blackout tags based on SCTE-35messages in the input source."DATERANGE" + // inserts EXT-X-DATERANGE tags to signal ad and program transition events in + // HLS and CMAF manifests. For this option, you must set a programDateTimeIntervalSeconds + // value that is greater than 0. AdMarkers *string `locationName:"adMarkers" type:"string" enum:"AdMarkers"` // A list of SCTE-35 message types that are treated as ad markers in the output. @@ -5933,8 +5942,21 @@ const ( // AdMarkersPassthrough is a AdMarkers enum value AdMarkersPassthrough = "PASSTHROUGH" + + // AdMarkersDaterange is a AdMarkers enum value + AdMarkersDaterange = "DATERANGE" ) +// AdMarkers_Values returns all elements of the AdMarkers enum +func AdMarkers_Values() []string { + return []string{ + AdMarkersNone, + AdMarkersScte35Enhanced, + AdMarkersPassthrough, + AdMarkersDaterange, + } +} + // This setting allows the delivery restriction flags on SCTE-35 segmentation // descriptors todetermine whether a message signals an ad. Choosing "NONE" // means no SCTE-35 messages becomeads. Choosing "RESTRICTED" means SCTE-35 @@ -5959,6 +5981,16 @@ const ( AdsOnDeliveryRestrictionsBoth = "BOTH" ) +// AdsOnDeliveryRestrictions_Values returns all elements of the AdsOnDeliveryRestrictions enum +func AdsOnDeliveryRestrictions_Values() []string { + return []string{ + AdsOnDeliveryRestrictionsNone, + AdsOnDeliveryRestrictionsRestricted, + AdsOnDeliveryRestrictionsUnrestricted, + AdsOnDeliveryRestrictionsBoth, + } +} + const ( // EncryptionMethodAes128 is a EncryptionMethod enum value EncryptionMethodAes128 = "AES_128" @@ -5967,6 +5999,14 @@ const ( EncryptionMethodSampleAes = "SAMPLE_AES" ) +// EncryptionMethod_Values returns all elements of the EncryptionMethod enum +func EncryptionMethod_Values() []string { + return []string{ + EncryptionMethodAes128, + EncryptionMethodSampleAes, + } +} + const ( // ManifestLayoutFull is a ManifestLayout enum value ManifestLayoutFull = "FULL" @@ -5975,6 +6015,14 @@ const ( ManifestLayoutCompact = "COMPACT" ) +// ManifestLayout_Values returns all elements of the ManifestLayout enum +func ManifestLayout_Values() []string { + return []string{ + ManifestLayoutFull, + ManifestLayoutCompact, + } +} + const ( // OriginationAllow is a Origination enum value OriginationAllow = "ALLOW" @@ -5983,6 +6031,14 @@ const ( OriginationDeny = "DENY" ) +// Origination_Values returns all elements of the Origination enum +func Origination_Values() []string { + return []string{ + OriginationAllow, + OriginationDeny, + } +} + const ( // PlaylistTypeNone is a PlaylistType enum value PlaylistTypeNone = "NONE" @@ -5994,6 +6050,15 @@ const ( PlaylistTypeVod = "VOD" ) +// PlaylistType_Values returns all elements of the PlaylistType enum +func PlaylistType_Values() []string { + return []string{ + PlaylistTypeNone, + PlaylistTypeEvent, + PlaylistTypeVod, + } +} + const ( // ProfileNone is a Profile enum value ProfileNone = "NONE" @@ -6002,6 +6067,14 @@ const ( ProfileHbbtv15 = "HBBTV_1_5" ) +// Profile_Values returns all elements of the Profile enum +func Profile_Values() []string { + return []string{ + ProfileNone, + ProfileHbbtv15, + } +} + const ( // SegmentTemplateFormatNumberWithTimeline is a SegmentTemplateFormat enum value SegmentTemplateFormatNumberWithTimeline = "NUMBER_WITH_TIMELINE" @@ -6013,6 +6086,15 @@ const ( SegmentTemplateFormatNumberWithDuration = "NUMBER_WITH_DURATION" ) +// SegmentTemplateFormat_Values returns all elements of the SegmentTemplateFormat enum +func SegmentTemplateFormat_Values() []string { + return []string{ + SegmentTemplateFormatNumberWithTimeline, + SegmentTemplateFormatTimeWithTimeline, + SegmentTemplateFormatNumberWithDuration, + } +} + const ( // StatusInProgress is a Status enum value StatusInProgress = "IN_PROGRESS" @@ -6024,6 +6106,15 @@ const ( StatusFailed = "FAILED" ) +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusInProgress, + StatusSucceeded, + StatusFailed, + } +} + const ( // StreamOrderOriginal is a StreamOrder enum value StreamOrderOriginal = "ORIGINAL" @@ -6035,6 +6126,15 @@ const ( StreamOrderVideoBitrateDescending = "VIDEO_BITRATE_DESCENDING" ) +// StreamOrder_Values returns all elements of the StreamOrder enum +func StreamOrder_Values() []string { + return []string{ + StreamOrderOriginal, + StreamOrderVideoBitrateAscending, + StreamOrderVideoBitrateDescending, + } +} + const ( // __AdTriggersElementSpliceInsert is a __AdTriggersElement enum value __AdTriggersElementSpliceInsert = "SPLICE_INSERT" @@ -6061,7 +6161,28 @@ const ( __AdTriggersElementDistributorOverlayPlacementOpportunity = "DISTRIBUTOR_OVERLAY_PLACEMENT_OPPORTUNITY" ) +// __AdTriggersElement_Values returns all elements of the __AdTriggersElement enum +func __AdTriggersElement_Values() []string { + return []string{ + __AdTriggersElementSpliceInsert, + __AdTriggersElementBreak, + __AdTriggersElementProviderAdvertisement, + __AdTriggersElementDistributorAdvertisement, + __AdTriggersElementProviderPlacementOpportunity, + __AdTriggersElementDistributorPlacementOpportunity, + __AdTriggersElementProviderOverlayPlacementOpportunity, + __AdTriggersElementDistributorOverlayPlacementOpportunity, + } +} + const ( // __PeriodTriggersElementAds is a __PeriodTriggersElement enum value __PeriodTriggersElementAds = "ADS" ) + +// __PeriodTriggersElement_Values returns all elements of the __PeriodTriggersElement enum +func __PeriodTriggersElement_Values() []string { + return []string{ + __PeriodTriggersElementAds, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/mediastore/api.go b/vendor/github.com/aws/aws-sdk-go/service/mediastore/api.go index 1eac3f1834d..edee10620ec 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/mediastore/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/mediastore/api.go @@ -4153,6 +4153,14 @@ const ( ContainerLevelMetricsDisabled = "DISABLED" ) +// ContainerLevelMetrics_Values returns all elements of the ContainerLevelMetrics enum +func ContainerLevelMetrics_Values() []string { + return []string{ + ContainerLevelMetricsEnabled, + ContainerLevelMetricsDisabled, + } +} + const ( // ContainerStatusActive is a ContainerStatus enum value ContainerStatusActive = "ACTIVE" @@ -4164,6 +4172,15 @@ const ( ContainerStatusDeleting = "DELETING" ) +// ContainerStatus_Values returns all elements of the ContainerStatus enum +func ContainerStatus_Values() []string { + return []string{ + ContainerStatusActive, + ContainerStatusCreating, + ContainerStatusDeleting, + } +} + const ( // MethodNamePut is a MethodName enum value MethodNamePut = "PUT" @@ -4177,3 +4194,13 @@ const ( // MethodNameHead is a MethodName enum value MethodNameHead = "HEAD" ) + +// MethodName_Values returns all elements of the MethodName enum +func MethodName_Values() []string { + return []string{ + MethodNamePut, + MethodNameGet, + MethodNameDelete, + MethodNameHead, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/mediastoredata/api.go b/vendor/github.com/aws/aws-sdk-go/service/mediastoredata/api.go index 6c8cc748d64..e7f45d8098a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/mediastoredata/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/mediastoredata/api.go @@ -1418,11 +1418,26 @@ const ( ItemTypeFolder = "FOLDER" ) +// ItemType_Values returns all elements of the ItemType enum +func ItemType_Values() []string { + return []string{ + ItemTypeObject, + ItemTypeFolder, + } +} + const ( // StorageClassTemporal is a StorageClass enum value StorageClassTemporal = "TEMPORAL" ) +// StorageClass_Values returns all elements of the StorageClass enum +func StorageClass_Values() []string { + return []string{ + StorageClassTemporal, + } +} + const ( // UploadAvailabilityStandard is a UploadAvailability enum value UploadAvailabilityStandard = "STANDARD" @@ -1430,3 +1445,11 @@ const ( // UploadAvailabilityStreaming is a UploadAvailability enum value UploadAvailabilityStreaming = "STREAMING" ) + +// UploadAvailability_Values returns all elements of the UploadAvailability enum +func UploadAvailability_Values() []string { + return []string{ + UploadAvailabilityStandard, + UploadAvailabilityStreaming, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/mq/api.go b/vendor/github.com/aws/aws-sdk-go/service/mq/api.go index 21df17b378d..1b64630866e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/mq/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/mq/api.go @@ -1193,6 +1193,12 @@ func (c *MQ) ListBrokersRequest(input *ListBrokersInput) (req *request.Request, Name: opListBrokers, HTTPMethod: "GET", HTTPPath: "/v1/brokers", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -1247,6 +1253,58 @@ func (c *MQ) ListBrokersWithContext(ctx aws.Context, input *ListBrokersInput, op return out, req.Send() } +// ListBrokersPages iterates over the pages of a ListBrokers operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListBrokers 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 ListBrokers operation. +// pageNum := 0 +// err := client.ListBrokersPages(params, +// func(page *mq.ListBrokersResponse, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *MQ) ListBrokersPages(input *ListBrokersInput, fn func(*ListBrokersResponse, bool) bool) error { + return c.ListBrokersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListBrokersPagesWithContext same as ListBrokersPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *MQ) ListBrokersPagesWithContext(ctx aws.Context, input *ListBrokersInput, fn func(*ListBrokersResponse, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListBrokersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListBrokersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListBrokersResponse), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListConfigurationRevisions = "ListConfigurationRevisions" // ListConfigurationRevisionsRequest generates a "aws/request.Request" representing the @@ -2273,6 +2331,9 @@ type Configuration struct { // Required. The ARN of the configuration. Arn *string `locationName:"arn" type:"string"` + // The authentication strategy associated with the configuration. + AuthenticationStrategy *string `locationName:"authenticationStrategy" type:"string" enum:"AuthenticationStrategy"` + // Required. The date and time of the configuration revision. Created *time.Time `locationName:"created" type:"timestamp" timestampFormat:"iso8601"` @@ -2318,6 +2379,12 @@ func (s *Configuration) SetArn(v string) *Configuration { return s } +// SetAuthenticationStrategy sets the AuthenticationStrategy field's value. +func (s *Configuration) SetAuthenticationStrategy(v string) *Configuration { + s.AuthenticationStrategy = &v + return s +} + // SetCreated sets the Created field's value. func (s *Configuration) SetCreated(v time.Time) *Configuration { s.Created = &v @@ -2544,6 +2611,9 @@ func (s *ConflictException) RequestID() string { type CreateBrokerRequest struct { _ struct{} `type:"structure"` + // The authentication strategy used to secure the broker. + AuthenticationStrategy *string `locationName:"authenticationStrategy" type:"string" enum:"AuthenticationStrategy"` + AutoMinorVersionUpgrade *bool `locationName:"autoMinorVersionUpgrade" type:"boolean"` BrokerName *string `locationName:"brokerName" type:"string"` @@ -2566,6 +2636,10 @@ type CreateBrokerRequest struct { HostInstanceType *string `locationName:"hostInstanceType" type:"string"` + // The metadata of the LDAP server used to authenticate and authorize connections + // to the broker. + LdapServerMetadata *LdapServerMetadataInput `locationName:"ldapServerMetadata" type:"structure"` + // The list of information about logs to be enabled for the specified broker. Logs *Logs `locationName:"logs" type:"structure"` @@ -2612,6 +2686,12 @@ func (s *CreateBrokerRequest) Validate() error { return nil } +// SetAuthenticationStrategy sets the AuthenticationStrategy field's value. +func (s *CreateBrokerRequest) SetAuthenticationStrategy(v string) *CreateBrokerRequest { + s.AuthenticationStrategy = &v + return s +} + // SetAutoMinorVersionUpgrade sets the AutoMinorVersionUpgrade field's value. func (s *CreateBrokerRequest) SetAutoMinorVersionUpgrade(v bool) *CreateBrokerRequest { s.AutoMinorVersionUpgrade = &v @@ -2666,6 +2746,12 @@ func (s *CreateBrokerRequest) SetHostInstanceType(v string) *CreateBrokerRequest return s } +// SetLdapServerMetadata sets the LdapServerMetadata field's value. +func (s *CreateBrokerRequest) SetLdapServerMetadata(v *LdapServerMetadataInput) *CreateBrokerRequest { + s.LdapServerMetadata = v + return s +} + // SetLogs sets the Logs field's value. func (s *CreateBrokerRequest) SetLogs(v *Logs) *CreateBrokerRequest { s.Logs = v @@ -2747,6 +2833,9 @@ func (s *CreateBrokerResponse) SetBrokerId(v string) *CreateBrokerResponse { type CreateConfigurationRequest struct { _ struct{} `type:"structure"` + // The authentication strategy used to secure the broker. + AuthenticationStrategy *string `locationName:"authenticationStrategy" type:"string" enum:"AuthenticationStrategy"` + // The type of broker engine. Note: Currently, Amazon MQ supports only ActiveMQ. EngineType *string `locationName:"engineType" type:"string" enum:"EngineType"` @@ -2767,6 +2856,12 @@ func (s CreateConfigurationRequest) GoString() string { return s.String() } +// SetAuthenticationStrategy sets the AuthenticationStrategy field's value. +func (s *CreateConfigurationRequest) SetAuthenticationStrategy(v string) *CreateConfigurationRequest { + s.AuthenticationStrategy = &v + return s +} + // SetEngineType sets the EngineType field's value. func (s *CreateConfigurationRequest) SetEngineType(v string) *CreateConfigurationRequest { s.EngineType = &v @@ -2796,6 +2891,9 @@ type CreateConfigurationResponse struct { Arn *string `locationName:"arn" type:"string"` + // The authentication strategy used to secure the broker. + AuthenticationStrategy *string `locationName:"authenticationStrategy" type:"string" enum:"AuthenticationStrategy"` + Created *time.Time `locationName:"created" type:"timestamp" timestampFormat:"iso8601"` Id *string `locationName:"id" type:"string"` @@ -2822,6 +2920,12 @@ func (s *CreateConfigurationResponse) SetArn(v string) *CreateConfigurationRespo return s } +// SetAuthenticationStrategy sets the AuthenticationStrategy field's value. +func (s *CreateConfigurationResponse) SetAuthenticationStrategy(v string) *CreateConfigurationResponse { + s.AuthenticationStrategy = &v + return s +} + // SetCreated sets the Created field's value. func (s *CreateConfigurationResponse) SetCreated(v time.Time) *CreateConfigurationResponse { s.Created = &v @@ -3429,6 +3533,9 @@ func (s *DescribeBrokerInstanceOptionsOutput) SetNextToken(v string) *DescribeBr type DescribeBrokerResponse struct { _ struct{} `type:"structure"` + // The authentication strategy used to secure the broker. + AuthenticationStrategy *string `locationName:"authenticationStrategy" type:"string" enum:"AuthenticationStrategy"` + AutoMinorVersionUpgrade *bool `locationName:"autoMinorVersionUpgrade" type:"boolean"` BrokerArn *string `locationName:"brokerArn" type:"string"` @@ -3460,6 +3567,10 @@ type DescribeBrokerResponse struct { HostInstanceType *string `locationName:"hostInstanceType" type:"string"` + // The metadata of the LDAP server used to authenticate and authorize connections + // to the broker. + LdapServerMetadata *LdapServerMetadataOutput `locationName:"ldapServerMetadata" type:"structure"` + // The list of information about logs currently enabled and pending to be deployed // for the specified broker. Logs *LogsSummary `locationName:"logs" type:"structure"` @@ -3468,10 +3579,17 @@ type DescribeBrokerResponse struct { // apply pending updates or patches to the broker. MaintenanceWindowStartTime *WeeklyStartTime `locationName:"maintenanceWindowStartTime" type:"structure"` + // The authentication strategy used to secure the broker. + PendingAuthenticationStrategy *string `locationName:"pendingAuthenticationStrategy" type:"string" enum:"AuthenticationStrategy"` + PendingEngineVersion *string `locationName:"pendingEngineVersion" type:"string"` PendingHostInstanceType *string `locationName:"pendingHostInstanceType" type:"string"` + // The metadata of the LDAP server used to authenticate and authorize connections + // to the broker. + PendingLdapServerMetadata *LdapServerMetadataOutput `locationName:"pendingLdapServerMetadata" type:"structure"` + PendingSecurityGroups []*string `locationName:"pendingSecurityGroups" type:"list"` PubliclyAccessible *bool `locationName:"publiclyAccessible" type:"boolean"` @@ -3498,6 +3616,12 @@ func (s DescribeBrokerResponse) GoString() string { return s.String() } +// SetAuthenticationStrategy sets the AuthenticationStrategy field's value. +func (s *DescribeBrokerResponse) SetAuthenticationStrategy(v string) *DescribeBrokerResponse { + s.AuthenticationStrategy = &v + return s +} + // SetAutoMinorVersionUpgrade sets the AutoMinorVersionUpgrade field's value. func (s *DescribeBrokerResponse) SetAutoMinorVersionUpgrade(v bool) *DescribeBrokerResponse { s.AutoMinorVersionUpgrade = &v @@ -3576,6 +3700,12 @@ func (s *DescribeBrokerResponse) SetHostInstanceType(v string) *DescribeBrokerRe return s } +// SetLdapServerMetadata sets the LdapServerMetadata field's value. +func (s *DescribeBrokerResponse) SetLdapServerMetadata(v *LdapServerMetadataOutput) *DescribeBrokerResponse { + s.LdapServerMetadata = v + return s +} + // SetLogs sets the Logs field's value. func (s *DescribeBrokerResponse) SetLogs(v *LogsSummary) *DescribeBrokerResponse { s.Logs = v @@ -3588,6 +3718,12 @@ func (s *DescribeBrokerResponse) SetMaintenanceWindowStartTime(v *WeeklyStartTim return s } +// SetPendingAuthenticationStrategy sets the PendingAuthenticationStrategy field's value. +func (s *DescribeBrokerResponse) SetPendingAuthenticationStrategy(v string) *DescribeBrokerResponse { + s.PendingAuthenticationStrategy = &v + return s +} + // SetPendingEngineVersion sets the PendingEngineVersion field's value. func (s *DescribeBrokerResponse) SetPendingEngineVersion(v string) *DescribeBrokerResponse { s.PendingEngineVersion = &v @@ -3600,6 +3736,12 @@ func (s *DescribeBrokerResponse) SetPendingHostInstanceType(v string) *DescribeB return s } +// SetPendingLdapServerMetadata sets the PendingLdapServerMetadata field's value. +func (s *DescribeBrokerResponse) SetPendingLdapServerMetadata(v *LdapServerMetadataOutput) *DescribeBrokerResponse { + s.PendingLdapServerMetadata = v + return s +} + // SetPendingSecurityGroups sets the PendingSecurityGroups field's value. func (s *DescribeBrokerResponse) SetPendingSecurityGroups(v []*string) *DescribeBrokerResponse { s.PendingSecurityGroups = v @@ -3686,6 +3828,9 @@ type DescribeConfigurationOutput struct { Arn *string `locationName:"arn" type:"string"` + // The authentication strategy used to secure the broker. + AuthenticationStrategy *string `locationName:"authenticationStrategy" type:"string" enum:"AuthenticationStrategy"` + Created *time.Time `locationName:"created" type:"timestamp" timestampFormat:"iso8601"` Description *string `locationName:"description" type:"string"` @@ -3721,6 +3866,12 @@ func (s *DescribeConfigurationOutput) SetArn(v string) *DescribeConfigurationOut return s } +// SetAuthenticationStrategy sets the AuthenticationStrategy field's value. +func (s *DescribeConfigurationOutput) SetAuthenticationStrategy(v string) *DescribeConfigurationOutput { + s.AuthenticationStrategy = &v + return s +} + // SetCreated sets the Created field's value. func (s *DescribeConfigurationOutput) SetCreated(v time.Time) *DescribeConfigurationOutput { s.Created = &v @@ -3983,9 +4134,9 @@ func (s *DescribeUserResponse) SetUsername(v string) *DescribeUserResponse { type EncryptionOptions struct { _ struct{} `type:"structure"` - // The customer master key (CMK) to use for the AWS Key Management Service (KMS). - // This key is used to encrypt your data at rest. If not provided, Amazon MQ - // will use a default CMK to encrypt your data. + // The symmetric customer master key (CMK) to use for the AWS Key Management + // Service (KMS). This key is used to encrypt your data at rest. If not provided, + // Amazon MQ will use a default CMK to encrypt your data. KmsKeyId *string `locationName:"kmsKeyId" type:"string"` // Enables the use of an AWS owned CMK using AWS Key Management Service (KMS). @@ -4169,6 +4320,233 @@ func (s *InternalServerErrorException) RequestID() string { return s.RespMetadata.RequestID } +// The metadata of the LDAP server used to authenticate and authorize connections +// to the broker. +type LdapServerMetadataInput struct { + _ struct{} `type:"structure"` + + // Fully qualified domain name of the LDAP server. Optional failover server. + Hosts []*string `locationName:"hosts" type:"list"` + + // Fully qualified name of the directory to search for a user’s groups. + RoleBase *string `locationName:"roleBase" type:"string"` + + // Specifies the LDAP attribute that identifies the group name attribute in + // the object returned from the group membership query. + RoleName *string `locationName:"roleName" type:"string"` + + // The search criteria for groups. + RoleSearchMatching *string `locationName:"roleSearchMatching" type:"string"` + + // The directory search scope for the role. If set to true, scope is to search + // the entire sub-tree. + RoleSearchSubtree *bool `locationName:"roleSearchSubtree" type:"boolean"` + + // Service account password. + ServiceAccountPassword *string `locationName:"serviceAccountPassword" type:"string"` + + // Service account username. + ServiceAccountUsername *string `locationName:"serviceAccountUsername" type:"string"` + + // Fully qualified name of the directory where you want to search for users. + UserBase *string `locationName:"userBase" type:"string"` + + // Specifies the name of the LDAP attribute for the user group membership. + UserRoleName *string `locationName:"userRoleName" type:"string"` + + // The search criteria for users. + UserSearchMatching *string `locationName:"userSearchMatching" type:"string"` + + // The directory search scope for the user. If set to true, scope is to search + // the entire sub-tree. + UserSearchSubtree *bool `locationName:"userSearchSubtree" type:"boolean"` +} + +// String returns the string representation +func (s LdapServerMetadataInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s LdapServerMetadataInput) GoString() string { + return s.String() +} + +// SetHosts sets the Hosts field's value. +func (s *LdapServerMetadataInput) SetHosts(v []*string) *LdapServerMetadataInput { + s.Hosts = v + return s +} + +// SetRoleBase sets the RoleBase field's value. +func (s *LdapServerMetadataInput) SetRoleBase(v string) *LdapServerMetadataInput { + s.RoleBase = &v + return s +} + +// SetRoleName sets the RoleName field's value. +func (s *LdapServerMetadataInput) SetRoleName(v string) *LdapServerMetadataInput { + s.RoleName = &v + return s +} + +// SetRoleSearchMatching sets the RoleSearchMatching field's value. +func (s *LdapServerMetadataInput) SetRoleSearchMatching(v string) *LdapServerMetadataInput { + s.RoleSearchMatching = &v + return s +} + +// SetRoleSearchSubtree sets the RoleSearchSubtree field's value. +func (s *LdapServerMetadataInput) SetRoleSearchSubtree(v bool) *LdapServerMetadataInput { + s.RoleSearchSubtree = &v + return s +} + +// SetServiceAccountPassword sets the ServiceAccountPassword field's value. +func (s *LdapServerMetadataInput) SetServiceAccountPassword(v string) *LdapServerMetadataInput { + s.ServiceAccountPassword = &v + return s +} + +// SetServiceAccountUsername sets the ServiceAccountUsername field's value. +func (s *LdapServerMetadataInput) SetServiceAccountUsername(v string) *LdapServerMetadataInput { + s.ServiceAccountUsername = &v + return s +} + +// SetUserBase sets the UserBase field's value. +func (s *LdapServerMetadataInput) SetUserBase(v string) *LdapServerMetadataInput { + s.UserBase = &v + return s +} + +// SetUserRoleName sets the UserRoleName field's value. +func (s *LdapServerMetadataInput) SetUserRoleName(v string) *LdapServerMetadataInput { + s.UserRoleName = &v + return s +} + +// SetUserSearchMatching sets the UserSearchMatching field's value. +func (s *LdapServerMetadataInput) SetUserSearchMatching(v string) *LdapServerMetadataInput { + s.UserSearchMatching = &v + return s +} + +// SetUserSearchSubtree sets the UserSearchSubtree field's value. +func (s *LdapServerMetadataInput) SetUserSearchSubtree(v bool) *LdapServerMetadataInput { + s.UserSearchSubtree = &v + return s +} + +// The metadata of the LDAP server used to authenticate and authorize connections +// to the broker. +type LdapServerMetadataOutput struct { + _ struct{} `type:"structure"` + + // Fully qualified domain name of the LDAP server. Optional failover server. + Hosts []*string `locationName:"hosts" type:"list"` + + // Fully qualified name of the directory to search for a user’s groups. + RoleBase *string `locationName:"roleBase" type:"string"` + + // Specifies the LDAP attribute that identifies the group name attribute in + // the object returned from the group membership query. + RoleName *string `locationName:"roleName" type:"string"` + + // The search criteria for groups. + RoleSearchMatching *string `locationName:"roleSearchMatching" type:"string"` + + // The directory search scope for the role. If set to true, scope is to search + // the entire sub-tree. + RoleSearchSubtree *bool `locationName:"roleSearchSubtree" type:"boolean"` + + // Service account username. + ServiceAccountUsername *string `locationName:"serviceAccountUsername" type:"string"` + + // Fully qualified name of the directory where you want to search for users. + UserBase *string `locationName:"userBase" type:"string"` + + // Specifies the name of the LDAP attribute for the user group membership. + UserRoleName *string `locationName:"userRoleName" type:"string"` + + // The search criteria for users. + UserSearchMatching *string `locationName:"userSearchMatching" type:"string"` + + // The directory search scope for the user. If set to true, scope is to search + // the entire sub-tree. + UserSearchSubtree *bool `locationName:"userSearchSubtree" type:"boolean"` +} + +// String returns the string representation +func (s LdapServerMetadataOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s LdapServerMetadataOutput) GoString() string { + return s.String() +} + +// SetHosts sets the Hosts field's value. +func (s *LdapServerMetadataOutput) SetHosts(v []*string) *LdapServerMetadataOutput { + s.Hosts = v + return s +} + +// SetRoleBase sets the RoleBase field's value. +func (s *LdapServerMetadataOutput) SetRoleBase(v string) *LdapServerMetadataOutput { + s.RoleBase = &v + return s +} + +// SetRoleName sets the RoleName field's value. +func (s *LdapServerMetadataOutput) SetRoleName(v string) *LdapServerMetadataOutput { + s.RoleName = &v + return s +} + +// SetRoleSearchMatching sets the RoleSearchMatching field's value. +func (s *LdapServerMetadataOutput) SetRoleSearchMatching(v string) *LdapServerMetadataOutput { + s.RoleSearchMatching = &v + return s +} + +// SetRoleSearchSubtree sets the RoleSearchSubtree field's value. +func (s *LdapServerMetadataOutput) SetRoleSearchSubtree(v bool) *LdapServerMetadataOutput { + s.RoleSearchSubtree = &v + return s +} + +// SetServiceAccountUsername sets the ServiceAccountUsername field's value. +func (s *LdapServerMetadataOutput) SetServiceAccountUsername(v string) *LdapServerMetadataOutput { + s.ServiceAccountUsername = &v + return s +} + +// SetUserBase sets the UserBase field's value. +func (s *LdapServerMetadataOutput) SetUserBase(v string) *LdapServerMetadataOutput { + s.UserBase = &v + return s +} + +// SetUserRoleName sets the UserRoleName field's value. +func (s *LdapServerMetadataOutput) SetUserRoleName(v string) *LdapServerMetadataOutput { + s.UserRoleName = &v + return s +} + +// SetUserSearchMatching sets the UserSearchMatching field's value. +func (s *LdapServerMetadataOutput) SetUserSearchMatching(v string) *LdapServerMetadataOutput { + s.UserSearchMatching = &v + return s +} + +// SetUserSearchSubtree sets the UserSearchSubtree field's value. +func (s *LdapServerMetadataOutput) SetUserSearchSubtree(v bool) *LdapServerMetadataOutput { + s.UserSearchSubtree = &v + return s +} + type ListBrokersInput struct { _ struct{} `type:"structure"` @@ -4938,6 +5316,9 @@ func (s *UnauthorizedException) RequestID() string { type UpdateBrokerRequest struct { _ struct{} `type:"structure"` + // The authentication strategy used to secure the broker. + AuthenticationStrategy *string `locationName:"authenticationStrategy" type:"string" enum:"AuthenticationStrategy"` + AutoMinorVersionUpgrade *bool `locationName:"autoMinorVersionUpgrade" type:"boolean"` // BrokerId is a required field @@ -4950,6 +5331,10 @@ type UpdateBrokerRequest struct { HostInstanceType *string `locationName:"hostInstanceType" type:"string"` + // The metadata of the LDAP server used to authenticate and authorize connections + // to the broker. + LdapServerMetadata *LdapServerMetadataInput `locationName:"ldapServerMetadata" type:"structure"` + // The list of information about logs to be enabled for the specified broker. Logs *Logs `locationName:"logs" type:"structure"` @@ -4982,6 +5367,12 @@ func (s *UpdateBrokerRequest) Validate() error { return nil } +// SetAuthenticationStrategy sets the AuthenticationStrategy field's value. +func (s *UpdateBrokerRequest) SetAuthenticationStrategy(v string) *UpdateBrokerRequest { + s.AuthenticationStrategy = &v + return s +} + // SetAutoMinorVersionUpgrade sets the AutoMinorVersionUpgrade field's value. func (s *UpdateBrokerRequest) SetAutoMinorVersionUpgrade(v bool) *UpdateBrokerRequest { s.AutoMinorVersionUpgrade = &v @@ -5012,6 +5403,12 @@ func (s *UpdateBrokerRequest) SetHostInstanceType(v string) *UpdateBrokerRequest return s } +// SetLdapServerMetadata sets the LdapServerMetadata field's value. +func (s *UpdateBrokerRequest) SetLdapServerMetadata(v *LdapServerMetadataInput) *UpdateBrokerRequest { + s.LdapServerMetadata = v + return s +} + // SetLogs sets the Logs field's value. func (s *UpdateBrokerRequest) SetLogs(v *Logs) *UpdateBrokerRequest { s.Logs = v @@ -5027,6 +5424,9 @@ func (s *UpdateBrokerRequest) SetSecurityGroups(v []*string) *UpdateBrokerReques type UpdateBrokerResponse struct { _ struct{} `type:"structure"` + // The authentication strategy used to secure the broker. + AuthenticationStrategy *string `locationName:"authenticationStrategy" type:"string" enum:"AuthenticationStrategy"` + AutoMinorVersionUpgrade *bool `locationName:"autoMinorVersionUpgrade" type:"boolean"` BrokerId *string `locationName:"brokerId" type:"string"` @@ -5038,6 +5438,10 @@ type UpdateBrokerResponse struct { HostInstanceType *string `locationName:"hostInstanceType" type:"string"` + // The metadata of the LDAP server used to authenticate and authorize connections + // to the broker. + LdapServerMetadata *LdapServerMetadataOutput `locationName:"ldapServerMetadata" type:"structure"` + // The list of information about logs to be enabled for the specified broker. Logs *Logs `locationName:"logs" type:"structure"` @@ -5054,6 +5458,12 @@ func (s UpdateBrokerResponse) GoString() string { return s.String() } +// SetAuthenticationStrategy sets the AuthenticationStrategy field's value. +func (s *UpdateBrokerResponse) SetAuthenticationStrategy(v string) *UpdateBrokerResponse { + s.AuthenticationStrategy = &v + return s +} + // SetAutoMinorVersionUpgrade sets the AutoMinorVersionUpgrade field's value. func (s *UpdateBrokerResponse) SetAutoMinorVersionUpgrade(v bool) *UpdateBrokerResponse { s.AutoMinorVersionUpgrade = &v @@ -5084,6 +5494,12 @@ func (s *UpdateBrokerResponse) SetHostInstanceType(v string) *UpdateBrokerRespon return s } +// SetLdapServerMetadata sets the LdapServerMetadata field's value. +func (s *UpdateBrokerResponse) SetLdapServerMetadata(v *LdapServerMetadataOutput) *UpdateBrokerResponse { + s.LdapServerMetadata = v + return s +} + // SetLogs sets the Logs field's value. func (s *UpdateBrokerResponse) SetLogs(v *Logs) *UpdateBrokerResponse { s.Logs = v @@ -5487,6 +5903,23 @@ func (s *WeeklyStartTime) SetTimeZone(v string) *WeeklyStartTime { return s } +// The authentication strategy used to secure the broker. +const ( + // AuthenticationStrategySimple is a AuthenticationStrategy enum value + AuthenticationStrategySimple = "SIMPLE" + + // AuthenticationStrategyLdap is a AuthenticationStrategy enum value + AuthenticationStrategyLdap = "LDAP" +) + +// AuthenticationStrategy_Values returns all elements of the AuthenticationStrategy enum +func AuthenticationStrategy_Values() []string { + return []string{ + AuthenticationStrategySimple, + AuthenticationStrategyLdap, + } +} + // The status of the broker. const ( // BrokerStateCreationInProgress is a BrokerState enum value @@ -5505,6 +5938,17 @@ const ( BrokerStateRebootInProgress = "REBOOT_IN_PROGRESS" ) +// BrokerState_Values returns all elements of the BrokerState enum +func BrokerState_Values() []string { + return []string{ + BrokerStateCreationInProgress, + BrokerStateCreationFailed, + BrokerStateDeletionInProgress, + BrokerStateRunning, + BrokerStateRebootInProgress, + } +} + // The storage type of the broker. const ( // BrokerStorageTypeEbs is a BrokerStorageType enum value @@ -5514,6 +5958,14 @@ const ( BrokerStorageTypeEfs = "EFS" ) +// BrokerStorageType_Values returns all elements of the BrokerStorageType enum +func BrokerStorageType_Values() []string { + return []string{ + BrokerStorageTypeEbs, + BrokerStorageTypeEfs, + } +} + // The type of change pending for the ActiveMQ user. const ( // ChangeTypeCreate is a ChangeType enum value @@ -5526,6 +5978,15 @@ const ( ChangeTypeDelete = "DELETE" ) +// ChangeType_Values returns all elements of the ChangeType enum +func ChangeType_Values() []string { + return []string{ + ChangeTypeCreate, + ChangeTypeUpdate, + ChangeTypeDelete, + } +} + const ( // DayOfWeekMonday is a DayOfWeek enum value DayOfWeekMonday = "MONDAY" @@ -5549,6 +6010,19 @@ const ( DayOfWeekSunday = "SUNDAY" ) +// DayOfWeek_Values returns all elements of the DayOfWeek enum +func DayOfWeek_Values() []string { + return []string{ + DayOfWeekMonday, + DayOfWeekTuesday, + DayOfWeekWednesday, + DayOfWeekThursday, + DayOfWeekFriday, + DayOfWeekSaturday, + DayOfWeekSunday, + } +} + // The deployment mode of the broker. const ( // DeploymentModeSingleInstance is a DeploymentMode enum value @@ -5558,12 +6032,27 @@ const ( DeploymentModeActiveStandbyMultiAz = "ACTIVE_STANDBY_MULTI_AZ" ) +// DeploymentMode_Values returns all elements of the DeploymentMode enum +func DeploymentMode_Values() []string { + return []string{ + DeploymentModeSingleInstance, + DeploymentModeActiveStandbyMultiAz, + } +} + // The type of broker engine. Note: Currently, Amazon MQ supports only ActiveMQ. const ( // EngineTypeActivemq is a EngineType enum value EngineTypeActivemq = "ACTIVEMQ" ) +// EngineType_Values returns all elements of the EngineType enum +func EngineType_Values() []string { + return []string{ + EngineTypeActivemq, + } +} + // The reason for which the XML elements or attributes were sanitized. const ( // SanitizationWarningReasonDisallowedElementRemoved is a SanitizationWarningReason enum value @@ -5575,3 +6064,12 @@ const ( // SanitizationWarningReasonInvalidAttributeValueRemoved is a SanitizationWarningReason enum value SanitizationWarningReasonInvalidAttributeValueRemoved = "INVALID_ATTRIBUTE_VALUE_REMOVED" ) + +// SanitizationWarningReason_Values returns all elements of the SanitizationWarningReason enum +func SanitizationWarningReason_Values() []string { + return []string{ + SanitizationWarningReasonDisallowedElementRemoved, + SanitizationWarningReasonDisallowedAttributeRemoved, + SanitizationWarningReasonInvalidAttributeValueRemoved, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/neptune/api.go b/vendor/github.com/aws/aws-sdk-go/service/neptune/api.go index 938839b0c04..b764c829512 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/neptune/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/neptune/api.go @@ -16953,6 +16953,14 @@ const ( ApplyMethodPendingReboot = "pending-reboot" ) +// ApplyMethod_Values returns all elements of the ApplyMethod enum +func ApplyMethod_Values() []string { + return []string{ + ApplyMethodImmediate, + ApplyMethodPendingReboot, + } +} + const ( // SourceTypeDbInstance is a SourceType enum value SourceTypeDbInstance = "db-instance" @@ -16972,3 +16980,15 @@ const ( // SourceTypeDbClusterSnapshot is a SourceType enum value SourceTypeDbClusterSnapshot = "db-cluster-snapshot" ) + +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeDbInstance, + SourceTypeDbParameterGroup, + SourceTypeDbSecurityGroup, + SourceTypeDbSnapshot, + SourceTypeDbCluster, + SourceTypeDbClusterSnapshot, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/networkmanager/api.go b/vendor/github.com/aws/aws-sdk-go/service/networkmanager/api.go new file mode 100644 index 00000000000..50655967e66 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/networkmanager/api.go @@ -0,0 +1,7174 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package networkmanager + +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/restjson" +) + +const opAssociateCustomerGateway = "AssociateCustomerGateway" + +// AssociateCustomerGatewayRequest generates a "aws/request.Request" representing the +// client's request for the AssociateCustomerGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See AssociateCustomerGateway for more information on using the AssociateCustomerGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the AssociateCustomerGatewayRequest method. +// req, resp := client.AssociateCustomerGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/AssociateCustomerGateway +func (c *NetworkManager) AssociateCustomerGatewayRequest(input *AssociateCustomerGatewayInput) (req *request.Request, output *AssociateCustomerGatewayOutput) { + op := &request.Operation{ + Name: opAssociateCustomerGateway, + HTTPMethod: "POST", + HTTPPath: "/global-networks/{globalNetworkId}/customer-gateway-associations", + } + + if input == nil { + input = &AssociateCustomerGatewayInput{} + } + + output = &AssociateCustomerGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// AssociateCustomerGateway API operation for AWS Network Manager. +// +// Associates a customer gateway with a device and optionally, with a link. +// If you specify a link, it must be associated with the specified device. +// +// You can only associate customer gateways that are connected to a VPN attachment +// on a transit gateway. The transit gateway must be registered in your global +// network. When you register a transit gateway, customer gateways that are +// connected to the transit gateway are automatically included in the global +// network. To list customer gateways that are connected to a transit gateway, +// use the DescribeVpnConnections (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVpnConnections.html) +// EC2 API and filter by transit-gateway-id. +// +// You cannot associate a customer gateway with more than one device and link. +// +// Returns awserr.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 Network Manager's +// API operation AssociateCustomerGateway for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * ServiceQuotaExceededException +// A service limit was exceeded. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/AssociateCustomerGateway +func (c *NetworkManager) AssociateCustomerGateway(input *AssociateCustomerGatewayInput) (*AssociateCustomerGatewayOutput, error) { + req, out := c.AssociateCustomerGatewayRequest(input) + return out, req.Send() +} + +// AssociateCustomerGatewayWithContext is the same as AssociateCustomerGateway with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateCustomerGateway for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) AssociateCustomerGatewayWithContext(ctx aws.Context, input *AssociateCustomerGatewayInput, opts ...request.Option) (*AssociateCustomerGatewayOutput, error) { + req, out := c.AssociateCustomerGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opAssociateLink = "AssociateLink" + +// AssociateLinkRequest generates a "aws/request.Request" representing the +// client's request for the AssociateLink operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See AssociateLink for more information on using the AssociateLink +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the AssociateLinkRequest method. +// req, resp := client.AssociateLinkRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/AssociateLink +func (c *NetworkManager) AssociateLinkRequest(input *AssociateLinkInput) (req *request.Request, output *AssociateLinkOutput) { + op := &request.Operation{ + Name: opAssociateLink, + HTTPMethod: "POST", + HTTPPath: "/global-networks/{globalNetworkId}/link-associations", + } + + if input == nil { + input = &AssociateLinkInput{} + } + + output = &AssociateLinkOutput{} + req = c.newRequest(op, input, output) + return +} + +// AssociateLink API operation for AWS Network Manager. +// +// Associates a link to a device. A device can be associated to multiple links +// and a link can be associated to multiple devices. The device and link must +// be in the same global network and the same site. +// +// Returns awserr.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 Network Manager's +// API operation AssociateLink for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * ServiceQuotaExceededException +// A service limit was exceeded. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/AssociateLink +func (c *NetworkManager) AssociateLink(input *AssociateLinkInput) (*AssociateLinkOutput, error) { + req, out := c.AssociateLinkRequest(input) + return out, req.Send() +} + +// AssociateLinkWithContext is the same as AssociateLink with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateLink for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) AssociateLinkWithContext(ctx aws.Context, input *AssociateLinkInput, opts ...request.Option) (*AssociateLinkOutput, error) { + req, out := c.AssociateLinkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateDevice = "CreateDevice" + +// CreateDeviceRequest generates a "aws/request.Request" representing the +// client's request for the CreateDevice operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateDevice for more information on using the CreateDevice +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateDeviceRequest method. +// req, resp := client.CreateDeviceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateDevice +func (c *NetworkManager) CreateDeviceRequest(input *CreateDeviceInput) (req *request.Request, output *CreateDeviceOutput) { + op := &request.Operation{ + Name: opCreateDevice, + HTTPMethod: "POST", + HTTPPath: "/global-networks/{globalNetworkId}/devices", + } + + if input == nil { + input = &CreateDeviceInput{} + } + + output = &CreateDeviceOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateDevice API operation for AWS Network Manager. +// +// Creates a new device in a global network. If you specify both a site ID and +// a location, the location of the site is used for visualization in the Network +// Manager console. +// +// Returns awserr.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 Network Manager's +// API operation CreateDevice for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * ServiceQuotaExceededException +// A service limit was exceeded. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateDevice +func (c *NetworkManager) CreateDevice(input *CreateDeviceInput) (*CreateDeviceOutput, error) { + req, out := c.CreateDeviceRequest(input) + return out, req.Send() +} + +// CreateDeviceWithContext is the same as CreateDevice with the addition of +// the ability to pass a context and additional request options. +// +// See CreateDevice for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) CreateDeviceWithContext(ctx aws.Context, input *CreateDeviceInput, opts ...request.Option) (*CreateDeviceOutput, error) { + req, out := c.CreateDeviceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateGlobalNetwork = "CreateGlobalNetwork" + +// CreateGlobalNetworkRequest generates a "aws/request.Request" representing the +// client's request for the CreateGlobalNetwork operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateGlobalNetwork for more information on using the CreateGlobalNetwork +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateGlobalNetworkRequest method. +// req, resp := client.CreateGlobalNetworkRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateGlobalNetwork +func (c *NetworkManager) CreateGlobalNetworkRequest(input *CreateGlobalNetworkInput) (req *request.Request, output *CreateGlobalNetworkOutput) { + op := &request.Operation{ + Name: opCreateGlobalNetwork, + HTTPMethod: "POST", + HTTPPath: "/global-networks", + } + + if input == nil { + input = &CreateGlobalNetworkInput{} + } + + output = &CreateGlobalNetworkOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateGlobalNetwork API operation for AWS Network Manager. +// +// Creates a new, empty global network. +// +// Returns awserr.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 Network Manager's +// API operation CreateGlobalNetwork for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * ServiceQuotaExceededException +// A service limit was exceeded. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateGlobalNetwork +func (c *NetworkManager) CreateGlobalNetwork(input *CreateGlobalNetworkInput) (*CreateGlobalNetworkOutput, error) { + req, out := c.CreateGlobalNetworkRequest(input) + return out, req.Send() +} + +// CreateGlobalNetworkWithContext is the same as CreateGlobalNetwork with the addition of +// the ability to pass a context and additional request options. +// +// See CreateGlobalNetwork for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) CreateGlobalNetworkWithContext(ctx aws.Context, input *CreateGlobalNetworkInput, opts ...request.Option) (*CreateGlobalNetworkOutput, error) { + req, out := c.CreateGlobalNetworkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateLink = "CreateLink" + +// CreateLinkRequest generates a "aws/request.Request" representing the +// client's request for the CreateLink operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateLink for more information on using the CreateLink +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateLinkRequest method. +// req, resp := client.CreateLinkRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateLink +func (c *NetworkManager) CreateLinkRequest(input *CreateLinkInput) (req *request.Request, output *CreateLinkOutput) { + op := &request.Operation{ + Name: opCreateLink, + HTTPMethod: "POST", + HTTPPath: "/global-networks/{globalNetworkId}/links", + } + + if input == nil { + input = &CreateLinkInput{} + } + + output = &CreateLinkOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateLink API operation for AWS Network Manager. +// +// Creates a new link for a specified site. +// +// Returns awserr.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 Network Manager's +// API operation CreateLink for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * ServiceQuotaExceededException +// A service limit was exceeded. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateLink +func (c *NetworkManager) CreateLink(input *CreateLinkInput) (*CreateLinkOutput, error) { + req, out := c.CreateLinkRequest(input) + return out, req.Send() +} + +// CreateLinkWithContext is the same as CreateLink with the addition of +// the ability to pass a context and additional request options. +// +// See CreateLink for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) CreateLinkWithContext(ctx aws.Context, input *CreateLinkInput, opts ...request.Option) (*CreateLinkOutput, error) { + req, out := c.CreateLinkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opCreateSite = "CreateSite" + +// CreateSiteRequest generates a "aws/request.Request" representing the +// client's request for the CreateSite operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateSite for more information on using the CreateSite +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateSiteRequest method. +// req, resp := client.CreateSiteRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateSite +func (c *NetworkManager) CreateSiteRequest(input *CreateSiteInput) (req *request.Request, output *CreateSiteOutput) { + op := &request.Operation{ + Name: opCreateSite, + HTTPMethod: "POST", + HTTPPath: "/global-networks/{globalNetworkId}/sites", + } + + if input == nil { + input = &CreateSiteInput{} + } + + output = &CreateSiteOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateSite API operation for AWS Network Manager. +// +// Creates a new site in a global network. +// +// Returns awserr.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 Network Manager's +// API operation CreateSite for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * ServiceQuotaExceededException +// A service limit was exceeded. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateSite +func (c *NetworkManager) CreateSite(input *CreateSiteInput) (*CreateSiteOutput, error) { + req, out := c.CreateSiteRequest(input) + return out, req.Send() +} + +// CreateSiteWithContext is the same as CreateSite with the addition of +// the ability to pass a context and additional request options. +// +// See CreateSite for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) CreateSiteWithContext(ctx aws.Context, input *CreateSiteInput, opts ...request.Option) (*CreateSiteOutput, error) { + req, out := c.CreateSiteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteDevice = "DeleteDevice" + +// DeleteDeviceRequest generates a "aws/request.Request" representing the +// client's request for the DeleteDevice operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteDevice for more information on using the DeleteDevice +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteDeviceRequest method. +// req, resp := client.DeleteDeviceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteDevice +func (c *NetworkManager) DeleteDeviceRequest(input *DeleteDeviceInput) (req *request.Request, output *DeleteDeviceOutput) { + op := &request.Operation{ + Name: opDeleteDevice, + HTTPMethod: "DELETE", + HTTPPath: "/global-networks/{globalNetworkId}/devices/{deviceId}", + } + + if input == nil { + input = &DeleteDeviceInput{} + } + + output = &DeleteDeviceOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteDevice API operation for AWS Network Manager. +// +// Deletes an existing device. You must first disassociate the device from any +// links and customer gateways. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Network Manager's +// API operation DeleteDevice for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteDevice +func (c *NetworkManager) DeleteDevice(input *DeleteDeviceInput) (*DeleteDeviceOutput, error) { + req, out := c.DeleteDeviceRequest(input) + return out, req.Send() +} + +// DeleteDeviceWithContext is the same as DeleteDevice with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteDevice for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) DeleteDeviceWithContext(ctx aws.Context, input *DeleteDeviceInput, opts ...request.Option) (*DeleteDeviceOutput, error) { + req, out := c.DeleteDeviceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteGlobalNetwork = "DeleteGlobalNetwork" + +// DeleteGlobalNetworkRequest generates a "aws/request.Request" representing the +// client's request for the DeleteGlobalNetwork operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteGlobalNetwork for more information on using the DeleteGlobalNetwork +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteGlobalNetworkRequest method. +// req, resp := client.DeleteGlobalNetworkRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteGlobalNetwork +func (c *NetworkManager) DeleteGlobalNetworkRequest(input *DeleteGlobalNetworkInput) (req *request.Request, output *DeleteGlobalNetworkOutput) { + op := &request.Operation{ + Name: opDeleteGlobalNetwork, + HTTPMethod: "DELETE", + HTTPPath: "/global-networks/{globalNetworkId}", + } + + if input == nil { + input = &DeleteGlobalNetworkInput{} + } + + output = &DeleteGlobalNetworkOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteGlobalNetwork API operation for AWS Network Manager. +// +// Deletes an existing global network. You must first delete all global network +// objects (devices, links, and sites) and deregister all transit gateways. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Network Manager's +// API operation DeleteGlobalNetwork for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteGlobalNetwork +func (c *NetworkManager) DeleteGlobalNetwork(input *DeleteGlobalNetworkInput) (*DeleteGlobalNetworkOutput, error) { + req, out := c.DeleteGlobalNetworkRequest(input) + return out, req.Send() +} + +// DeleteGlobalNetworkWithContext is the same as DeleteGlobalNetwork with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteGlobalNetwork for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) DeleteGlobalNetworkWithContext(ctx aws.Context, input *DeleteGlobalNetworkInput, opts ...request.Option) (*DeleteGlobalNetworkOutput, error) { + req, out := c.DeleteGlobalNetworkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteLink = "DeleteLink" + +// DeleteLinkRequest generates a "aws/request.Request" representing the +// client's request for the DeleteLink operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteLink for more information on using the DeleteLink +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteLinkRequest method. +// req, resp := client.DeleteLinkRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteLink +func (c *NetworkManager) DeleteLinkRequest(input *DeleteLinkInput) (req *request.Request, output *DeleteLinkOutput) { + op := &request.Operation{ + Name: opDeleteLink, + HTTPMethod: "DELETE", + HTTPPath: "/global-networks/{globalNetworkId}/links/{linkId}", + } + + if input == nil { + input = &DeleteLinkInput{} + } + + output = &DeleteLinkOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteLink API operation for AWS Network Manager. +// +// Deletes an existing link. You must first disassociate the link from any devices +// and customer gateways. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Network Manager's +// API operation DeleteLink for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteLink +func (c *NetworkManager) DeleteLink(input *DeleteLinkInput) (*DeleteLinkOutput, error) { + req, out := c.DeleteLinkRequest(input) + return out, req.Send() +} + +// DeleteLinkWithContext is the same as DeleteLink with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteLink for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) DeleteLinkWithContext(ctx aws.Context, input *DeleteLinkInput, opts ...request.Option) (*DeleteLinkOutput, error) { + req, out := c.DeleteLinkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteSite = "DeleteSite" + +// DeleteSiteRequest generates a "aws/request.Request" representing the +// client's request for the DeleteSite operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteSite for more information on using the DeleteSite +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteSiteRequest method. +// req, resp := client.DeleteSiteRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteSite +func (c *NetworkManager) DeleteSiteRequest(input *DeleteSiteInput) (req *request.Request, output *DeleteSiteOutput) { + op := &request.Operation{ + Name: opDeleteSite, + HTTPMethod: "DELETE", + HTTPPath: "/global-networks/{globalNetworkId}/sites/{siteId}", + } + + if input == nil { + input = &DeleteSiteInput{} + } + + output = &DeleteSiteOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteSite API operation for AWS Network Manager. +// +// Deletes an existing site. The site cannot be associated with any device or +// link. +// +// Returns awserr.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 Network Manager's +// API operation DeleteSite for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteSite +func (c *NetworkManager) DeleteSite(input *DeleteSiteInput) (*DeleteSiteOutput, error) { + req, out := c.DeleteSiteRequest(input) + return out, req.Send() +} + +// DeleteSiteWithContext is the same as DeleteSite with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSite for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) DeleteSiteWithContext(ctx aws.Context, input *DeleteSiteInput, opts ...request.Option) (*DeleteSiteOutput, error) { + req, out := c.DeleteSiteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeregisterTransitGateway = "DeregisterTransitGateway" + +// DeregisterTransitGatewayRequest generates a "aws/request.Request" representing the +// client's request for the DeregisterTransitGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeregisterTransitGateway for more information on using the DeregisterTransitGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeregisterTransitGatewayRequest method. +// req, resp := client.DeregisterTransitGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeregisterTransitGateway +func (c *NetworkManager) DeregisterTransitGatewayRequest(input *DeregisterTransitGatewayInput) (req *request.Request, output *DeregisterTransitGatewayOutput) { + op := &request.Operation{ + Name: opDeregisterTransitGateway, + HTTPMethod: "DELETE", + HTTPPath: "/global-networks/{globalNetworkId}/transit-gateway-registrations/{transitGatewayArn}", + } + + if input == nil { + input = &DeregisterTransitGatewayInput{} + } + + output = &DeregisterTransitGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeregisterTransitGateway API operation for AWS Network Manager. +// +// Deregisters a transit gateway from your global network. This action does +// not delete your transit gateway, or modify any of its attachments. This action +// removes any customer gateway associations. +// +// Returns awserr.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 Network Manager's +// API operation DeregisterTransitGateway for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeregisterTransitGateway +func (c *NetworkManager) DeregisterTransitGateway(input *DeregisterTransitGatewayInput) (*DeregisterTransitGatewayOutput, error) { + req, out := c.DeregisterTransitGatewayRequest(input) + return out, req.Send() +} + +// DeregisterTransitGatewayWithContext is the same as DeregisterTransitGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DeregisterTransitGateway for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) DeregisterTransitGatewayWithContext(ctx aws.Context, input *DeregisterTransitGatewayInput, opts ...request.Option) (*DeregisterTransitGatewayOutput, error) { + req, out := c.DeregisterTransitGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDescribeGlobalNetworks = "DescribeGlobalNetworks" + +// DescribeGlobalNetworksRequest generates a "aws/request.Request" representing the +// client's request for the DescribeGlobalNetworks operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeGlobalNetworks for more information on using the DescribeGlobalNetworks +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeGlobalNetworksRequest method. +// req, resp := client.DescribeGlobalNetworksRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DescribeGlobalNetworks +func (c *NetworkManager) DescribeGlobalNetworksRequest(input *DescribeGlobalNetworksInput) (req *request.Request, output *DescribeGlobalNetworksOutput) { + op := &request.Operation{ + Name: opDescribeGlobalNetworks, + HTTPMethod: "GET", + HTTPPath: "/global-networks", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeGlobalNetworksInput{} + } + + output = &DescribeGlobalNetworksOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeGlobalNetworks API operation for AWS Network Manager. +// +// Describes one or more global networks. By default, all global networks are +// described. To describe the objects in your global network, you must use the +// appropriate Get* action. For example, to list the transit gateways in your +// global network, use GetTransitGatewayRegistrations. +// +// Returns awserr.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 Network Manager's +// API operation DescribeGlobalNetworks for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DescribeGlobalNetworks +func (c *NetworkManager) DescribeGlobalNetworks(input *DescribeGlobalNetworksInput) (*DescribeGlobalNetworksOutput, error) { + req, out := c.DescribeGlobalNetworksRequest(input) + return out, req.Send() +} + +// DescribeGlobalNetworksWithContext is the same as DescribeGlobalNetworks with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeGlobalNetworks for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) DescribeGlobalNetworksWithContext(ctx aws.Context, input *DescribeGlobalNetworksInput, opts ...request.Option) (*DescribeGlobalNetworksOutput, error) { + req, out := c.DescribeGlobalNetworksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeGlobalNetworksPages iterates over the pages of a DescribeGlobalNetworks operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeGlobalNetworks 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 DescribeGlobalNetworks operation. +// pageNum := 0 +// err := client.DescribeGlobalNetworksPages(params, +// func(page *networkmanager.DescribeGlobalNetworksOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *NetworkManager) DescribeGlobalNetworksPages(input *DescribeGlobalNetworksInput, fn func(*DescribeGlobalNetworksOutput, bool) bool) error { + return c.DescribeGlobalNetworksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeGlobalNetworksPagesWithContext same as DescribeGlobalNetworksPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) DescribeGlobalNetworksPagesWithContext(ctx aws.Context, input *DescribeGlobalNetworksInput, fn func(*DescribeGlobalNetworksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeGlobalNetworksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeGlobalNetworksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeGlobalNetworksOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opDisassociateCustomerGateway = "DisassociateCustomerGateway" + +// DisassociateCustomerGatewayRequest generates a "aws/request.Request" representing the +// client's request for the DisassociateCustomerGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DisassociateCustomerGateway for more information on using the DisassociateCustomerGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DisassociateCustomerGatewayRequest method. +// req, resp := client.DisassociateCustomerGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DisassociateCustomerGateway +func (c *NetworkManager) DisassociateCustomerGatewayRequest(input *DisassociateCustomerGatewayInput) (req *request.Request, output *DisassociateCustomerGatewayOutput) { + op := &request.Operation{ + Name: opDisassociateCustomerGateway, + HTTPMethod: "DELETE", + HTTPPath: "/global-networks/{globalNetworkId}/customer-gateway-associations/{customerGatewayArn}", + } + + if input == nil { + input = &DisassociateCustomerGatewayInput{} + } + + output = &DisassociateCustomerGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// DisassociateCustomerGateway API operation for AWS Network Manager. +// +// Disassociates a customer gateway from a device and a link. +// +// Returns awserr.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 Network Manager's +// API operation DisassociateCustomerGateway for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DisassociateCustomerGateway +func (c *NetworkManager) DisassociateCustomerGateway(input *DisassociateCustomerGatewayInput) (*DisassociateCustomerGatewayOutput, error) { + req, out := c.DisassociateCustomerGatewayRequest(input) + return out, req.Send() +} + +// DisassociateCustomerGatewayWithContext is the same as DisassociateCustomerGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateCustomerGateway for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) DisassociateCustomerGatewayWithContext(ctx aws.Context, input *DisassociateCustomerGatewayInput, opts ...request.Option) (*DisassociateCustomerGatewayOutput, error) { + req, out := c.DisassociateCustomerGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDisassociateLink = "DisassociateLink" + +// DisassociateLinkRequest generates a "aws/request.Request" representing the +// client's request for the DisassociateLink operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DisassociateLink for more information on using the DisassociateLink +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DisassociateLinkRequest method. +// req, resp := client.DisassociateLinkRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DisassociateLink +func (c *NetworkManager) DisassociateLinkRequest(input *DisassociateLinkInput) (req *request.Request, output *DisassociateLinkOutput) { + op := &request.Operation{ + Name: opDisassociateLink, + HTTPMethod: "DELETE", + HTTPPath: "/global-networks/{globalNetworkId}/link-associations", + } + + if input == nil { + input = &DisassociateLinkInput{} + } + + output = &DisassociateLinkOutput{} + req = c.newRequest(op, input, output) + return +} + +// DisassociateLink API operation for AWS Network Manager. +// +// Disassociates an existing device from a link. You must first disassociate +// any customer gateways that are associated with the link. +// +// Returns awserr.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 Network Manager's +// API operation DisassociateLink for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DisassociateLink +func (c *NetworkManager) DisassociateLink(input *DisassociateLinkInput) (*DisassociateLinkOutput, error) { + req, out := c.DisassociateLinkRequest(input) + return out, req.Send() +} + +// DisassociateLinkWithContext is the same as DisassociateLink with the addition of +// the ability to pass a context and additional request options. +// +// See DisassociateLink for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) DisassociateLinkWithContext(ctx aws.Context, input *DisassociateLinkInput, opts ...request.Option) (*DisassociateLinkOutput, error) { + req, out := c.DisassociateLinkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetCustomerGatewayAssociations = "GetCustomerGatewayAssociations" + +// GetCustomerGatewayAssociationsRequest generates a "aws/request.Request" representing the +// client's request for the GetCustomerGatewayAssociations operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetCustomerGatewayAssociations for more information on using the GetCustomerGatewayAssociations +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetCustomerGatewayAssociationsRequest method. +// req, resp := client.GetCustomerGatewayAssociationsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetCustomerGatewayAssociations +func (c *NetworkManager) GetCustomerGatewayAssociationsRequest(input *GetCustomerGatewayAssociationsInput) (req *request.Request, output *GetCustomerGatewayAssociationsOutput) { + op := &request.Operation{ + Name: opGetCustomerGatewayAssociations, + HTTPMethod: "GET", + HTTPPath: "/global-networks/{globalNetworkId}/customer-gateway-associations", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetCustomerGatewayAssociationsInput{} + } + + output = &GetCustomerGatewayAssociationsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetCustomerGatewayAssociations API operation for AWS Network Manager. +// +// Gets the association information for customer gateways that are associated +// with devices and links in your global network. +// +// Returns awserr.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 Network Manager's +// API operation GetCustomerGatewayAssociations for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetCustomerGatewayAssociations +func (c *NetworkManager) GetCustomerGatewayAssociations(input *GetCustomerGatewayAssociationsInput) (*GetCustomerGatewayAssociationsOutput, error) { + req, out := c.GetCustomerGatewayAssociationsRequest(input) + return out, req.Send() +} + +// GetCustomerGatewayAssociationsWithContext is the same as GetCustomerGatewayAssociations with the addition of +// the ability to pass a context and additional request options. +// +// See GetCustomerGatewayAssociations for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetCustomerGatewayAssociationsWithContext(ctx aws.Context, input *GetCustomerGatewayAssociationsInput, opts ...request.Option) (*GetCustomerGatewayAssociationsOutput, error) { + req, out := c.GetCustomerGatewayAssociationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetCustomerGatewayAssociationsPages iterates over the pages of a GetCustomerGatewayAssociations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetCustomerGatewayAssociations 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 GetCustomerGatewayAssociations operation. +// pageNum := 0 +// err := client.GetCustomerGatewayAssociationsPages(params, +// func(page *networkmanager.GetCustomerGatewayAssociationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *NetworkManager) GetCustomerGatewayAssociationsPages(input *GetCustomerGatewayAssociationsInput, fn func(*GetCustomerGatewayAssociationsOutput, bool) bool) error { + return c.GetCustomerGatewayAssociationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetCustomerGatewayAssociationsPagesWithContext same as GetCustomerGatewayAssociationsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetCustomerGatewayAssociationsPagesWithContext(ctx aws.Context, input *GetCustomerGatewayAssociationsInput, fn func(*GetCustomerGatewayAssociationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetCustomerGatewayAssociationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetCustomerGatewayAssociationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetCustomerGatewayAssociationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opGetDevices = "GetDevices" + +// GetDevicesRequest generates a "aws/request.Request" representing the +// client's request for the GetDevices operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetDevices for more information on using the GetDevices +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetDevicesRequest method. +// req, resp := client.GetDevicesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetDevices +func (c *NetworkManager) GetDevicesRequest(input *GetDevicesInput) (req *request.Request, output *GetDevicesOutput) { + op := &request.Operation{ + Name: opGetDevices, + HTTPMethod: "GET", + HTTPPath: "/global-networks/{globalNetworkId}/devices", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetDevicesInput{} + } + + output = &GetDevicesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetDevices API operation for AWS Network Manager. +// +// Gets information about one or more of your devices in a global network. +// +// Returns awserr.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 Network Manager's +// API operation GetDevices for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetDevices +func (c *NetworkManager) GetDevices(input *GetDevicesInput) (*GetDevicesOutput, error) { + req, out := c.GetDevicesRequest(input) + return out, req.Send() +} + +// GetDevicesWithContext is the same as GetDevices with the addition of +// the ability to pass a context and additional request options. +// +// See GetDevices for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetDevicesWithContext(ctx aws.Context, input *GetDevicesInput, opts ...request.Option) (*GetDevicesOutput, error) { + req, out := c.GetDevicesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetDevicesPages iterates over the pages of a GetDevices operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetDevices 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 GetDevices operation. +// pageNum := 0 +// err := client.GetDevicesPages(params, +// func(page *networkmanager.GetDevicesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *NetworkManager) GetDevicesPages(input *GetDevicesInput, fn func(*GetDevicesOutput, bool) bool) error { + return c.GetDevicesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetDevicesPagesWithContext same as GetDevicesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetDevicesPagesWithContext(ctx aws.Context, input *GetDevicesInput, fn func(*GetDevicesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetDevicesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetDevicesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetDevicesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opGetLinkAssociations = "GetLinkAssociations" + +// GetLinkAssociationsRequest generates a "aws/request.Request" representing the +// client's request for the GetLinkAssociations operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetLinkAssociations for more information on using the GetLinkAssociations +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetLinkAssociationsRequest method. +// req, resp := client.GetLinkAssociationsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetLinkAssociations +func (c *NetworkManager) GetLinkAssociationsRequest(input *GetLinkAssociationsInput) (req *request.Request, output *GetLinkAssociationsOutput) { + op := &request.Operation{ + Name: opGetLinkAssociations, + HTTPMethod: "GET", + HTTPPath: "/global-networks/{globalNetworkId}/link-associations", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetLinkAssociationsInput{} + } + + output = &GetLinkAssociationsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetLinkAssociations API operation for AWS Network Manager. +// +// Gets the link associations for a device or a link. Either the device ID or +// the link ID must be specified. +// +// Returns awserr.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 Network Manager's +// API operation GetLinkAssociations for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetLinkAssociations +func (c *NetworkManager) GetLinkAssociations(input *GetLinkAssociationsInput) (*GetLinkAssociationsOutput, error) { + req, out := c.GetLinkAssociationsRequest(input) + return out, req.Send() +} + +// GetLinkAssociationsWithContext is the same as GetLinkAssociations with the addition of +// the ability to pass a context and additional request options. +// +// See GetLinkAssociations for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetLinkAssociationsWithContext(ctx aws.Context, input *GetLinkAssociationsInput, opts ...request.Option) (*GetLinkAssociationsOutput, error) { + req, out := c.GetLinkAssociationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetLinkAssociationsPages iterates over the pages of a GetLinkAssociations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetLinkAssociations 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 GetLinkAssociations operation. +// pageNum := 0 +// err := client.GetLinkAssociationsPages(params, +// func(page *networkmanager.GetLinkAssociationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *NetworkManager) GetLinkAssociationsPages(input *GetLinkAssociationsInput, fn func(*GetLinkAssociationsOutput, bool) bool) error { + return c.GetLinkAssociationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetLinkAssociationsPagesWithContext same as GetLinkAssociationsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetLinkAssociationsPagesWithContext(ctx aws.Context, input *GetLinkAssociationsInput, fn func(*GetLinkAssociationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetLinkAssociationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetLinkAssociationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetLinkAssociationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opGetLinks = "GetLinks" + +// GetLinksRequest generates a "aws/request.Request" representing the +// client's request for the GetLinks operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetLinks for more information on using the GetLinks +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetLinksRequest method. +// req, resp := client.GetLinksRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetLinks +func (c *NetworkManager) GetLinksRequest(input *GetLinksInput) (req *request.Request, output *GetLinksOutput) { + op := &request.Operation{ + Name: opGetLinks, + HTTPMethod: "GET", + HTTPPath: "/global-networks/{globalNetworkId}/links", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetLinksInput{} + } + + output = &GetLinksOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetLinks API operation for AWS Network Manager. +// +// Gets information about one or more links in a specified global network. +// +// If you specify the site ID, you cannot specify the type or provider in the +// same request. You can specify the type and provider in the same 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 Network Manager's +// API operation GetLinks for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetLinks +func (c *NetworkManager) GetLinks(input *GetLinksInput) (*GetLinksOutput, error) { + req, out := c.GetLinksRequest(input) + return out, req.Send() +} + +// GetLinksWithContext is the same as GetLinks with the addition of +// the ability to pass a context and additional request options. +// +// See GetLinks for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetLinksWithContext(ctx aws.Context, input *GetLinksInput, opts ...request.Option) (*GetLinksOutput, error) { + req, out := c.GetLinksRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetLinksPages iterates over the pages of a GetLinks operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetLinks 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 GetLinks operation. +// pageNum := 0 +// err := client.GetLinksPages(params, +// func(page *networkmanager.GetLinksOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *NetworkManager) GetLinksPages(input *GetLinksInput, fn func(*GetLinksOutput, bool) bool) error { + return c.GetLinksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetLinksPagesWithContext same as GetLinksPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetLinksPagesWithContext(ctx aws.Context, input *GetLinksInput, fn func(*GetLinksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetLinksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetLinksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetLinksOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opGetSites = "GetSites" + +// GetSitesRequest generates a "aws/request.Request" representing the +// client's request for the GetSites operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetSites for more information on using the GetSites +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetSitesRequest method. +// req, resp := client.GetSitesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetSites +func (c *NetworkManager) GetSitesRequest(input *GetSitesInput) (req *request.Request, output *GetSitesOutput) { + op := &request.Operation{ + Name: opGetSites, + HTTPMethod: "GET", + HTTPPath: "/global-networks/{globalNetworkId}/sites", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetSitesInput{} + } + + output = &GetSitesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetSites API operation for AWS Network Manager. +// +// Gets information about one or more of your sites in a global network. +// +// Returns awserr.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 Network Manager's +// API operation GetSites for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetSites +func (c *NetworkManager) GetSites(input *GetSitesInput) (*GetSitesOutput, error) { + req, out := c.GetSitesRequest(input) + return out, req.Send() +} + +// GetSitesWithContext is the same as GetSites with the addition of +// the ability to pass a context and additional request options. +// +// See GetSites for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetSitesWithContext(ctx aws.Context, input *GetSitesInput, opts ...request.Option) (*GetSitesOutput, error) { + req, out := c.GetSitesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetSitesPages iterates over the pages of a GetSites operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetSites 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 GetSites operation. +// pageNum := 0 +// err := client.GetSitesPages(params, +// func(page *networkmanager.GetSitesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *NetworkManager) GetSitesPages(input *GetSitesInput, fn func(*GetSitesOutput, bool) bool) error { + return c.GetSitesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetSitesPagesWithContext same as GetSitesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetSitesPagesWithContext(ctx aws.Context, input *GetSitesInput, fn func(*GetSitesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetSitesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetSitesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetSitesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opGetTransitGatewayRegistrations = "GetTransitGatewayRegistrations" + +// GetTransitGatewayRegistrationsRequest generates a "aws/request.Request" representing the +// client's request for the GetTransitGatewayRegistrations operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetTransitGatewayRegistrations for more information on using the GetTransitGatewayRegistrations +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetTransitGatewayRegistrationsRequest method. +// req, resp := client.GetTransitGatewayRegistrationsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetTransitGatewayRegistrations +func (c *NetworkManager) GetTransitGatewayRegistrationsRequest(input *GetTransitGatewayRegistrationsInput) (req *request.Request, output *GetTransitGatewayRegistrationsOutput) { + op := &request.Operation{ + Name: opGetTransitGatewayRegistrations, + HTTPMethod: "GET", + HTTPPath: "/global-networks/{globalNetworkId}/transit-gateway-registrations", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetTransitGatewayRegistrationsInput{} + } + + output = &GetTransitGatewayRegistrationsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetTransitGatewayRegistrations API operation for AWS Network Manager. +// +// Gets information about the transit gateway registrations in a specified global +// network. +// +// Returns awserr.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 Network Manager's +// API operation GetTransitGatewayRegistrations for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetTransitGatewayRegistrations +func (c *NetworkManager) GetTransitGatewayRegistrations(input *GetTransitGatewayRegistrationsInput) (*GetTransitGatewayRegistrationsOutput, error) { + req, out := c.GetTransitGatewayRegistrationsRequest(input) + return out, req.Send() +} + +// GetTransitGatewayRegistrationsWithContext is the same as GetTransitGatewayRegistrations with the addition of +// the ability to pass a context and additional request options. +// +// See GetTransitGatewayRegistrations for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetTransitGatewayRegistrationsWithContext(ctx aws.Context, input *GetTransitGatewayRegistrationsInput, opts ...request.Option) (*GetTransitGatewayRegistrationsOutput, error) { + req, out := c.GetTransitGatewayRegistrationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetTransitGatewayRegistrationsPages iterates over the pages of a GetTransitGatewayRegistrations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetTransitGatewayRegistrations 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 GetTransitGatewayRegistrations operation. +// pageNum := 0 +// err := client.GetTransitGatewayRegistrationsPages(params, +// func(page *networkmanager.GetTransitGatewayRegistrationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *NetworkManager) GetTransitGatewayRegistrationsPages(input *GetTransitGatewayRegistrationsInput, fn func(*GetTransitGatewayRegistrationsOutput, bool) bool) error { + return c.GetTransitGatewayRegistrationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetTransitGatewayRegistrationsPagesWithContext same as GetTransitGatewayRegistrationsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) GetTransitGatewayRegistrationsPagesWithContext(ctx aws.Context, input *GetTransitGatewayRegistrationsInput, fn func(*GetTransitGatewayRegistrationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetTransitGatewayRegistrationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetTransitGatewayRegistrationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetTransitGatewayRegistrationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListTagsForResource = "ListTagsForResource" + +// ListTagsForResourceRequest generates a "aws/request.Request" representing the +// client's request for the ListTagsForResource operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListTagsForResource for more information on using the ListTagsForResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListTagsForResourceRequest method. +// req, resp := client.ListTagsForResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/ListTagsForResource +func (c *NetworkManager) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { + op := &request.Operation{ + Name: opListTagsForResource, + HTTPMethod: "GET", + HTTPPath: "/tags/{resourceArn}", + } + + if input == nil { + input = &ListTagsForResourceInput{} + } + + output = &ListTagsForResourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListTagsForResource API operation for AWS Network Manager. +// +// Lists the tags for a 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 Network Manager's +// API operation ListTagsForResource for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/ListTagsForResource +func (c *NetworkManager) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + 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 *NetworkManager) 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 opRegisterTransitGateway = "RegisterTransitGateway" + +// RegisterTransitGatewayRequest generates a "aws/request.Request" representing the +// client's request for the RegisterTransitGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See RegisterTransitGateway for more information on using the RegisterTransitGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the RegisterTransitGatewayRequest method. +// req, resp := client.RegisterTransitGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/RegisterTransitGateway +func (c *NetworkManager) RegisterTransitGatewayRequest(input *RegisterTransitGatewayInput) (req *request.Request, output *RegisterTransitGatewayOutput) { + op := &request.Operation{ + Name: opRegisterTransitGateway, + HTTPMethod: "POST", + HTTPPath: "/global-networks/{globalNetworkId}/transit-gateway-registrations", + } + + if input == nil { + input = &RegisterTransitGatewayInput{} + } + + output = &RegisterTransitGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// RegisterTransitGateway API operation for AWS Network Manager. +// +// Registers a transit gateway in your global network. The transit gateway can +// be in any AWS Region, but it must be owned by the same AWS account that owns +// the global network. You cannot register a transit gateway in more than one +// global network. +// +// Returns awserr.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 Network Manager's +// API operation RegisterTransitGateway for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/RegisterTransitGateway +func (c *NetworkManager) RegisterTransitGateway(input *RegisterTransitGatewayInput) (*RegisterTransitGatewayOutput, error) { + req, out := c.RegisterTransitGatewayRequest(input) + return out, req.Send() +} + +// RegisterTransitGatewayWithContext is the same as RegisterTransitGateway with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterTransitGateway for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) RegisterTransitGatewayWithContext(ctx aws.Context, input *RegisterTransitGatewayInput, opts ...request.Option) (*RegisterTransitGatewayOutput, error) { + req, out := c.RegisterTransitGatewayRequest(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 will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See TagResource for more information on using the TagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the TagResourceRequest method. +// req, resp := client.TagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/TagResource +func (c *NetworkManager) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { + op := &request.Operation{ + Name: opTagResource, + HTTPMethod: "POST", + HTTPPath: "/tags/{resourceArn}", + } + + if input == nil { + input = &TagResourceInput{} + } + + output = &TagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// TagResource API operation for AWS Network Manager. +// +// Tags a 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 Network Manager's +// API operation TagResource for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * ServiceQuotaExceededException +// A service limit was exceeded. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/TagResource +func (c *NetworkManager) 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 *NetworkManager) 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 will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UntagResource for more information on using the UntagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UntagResourceRequest method. +// req, resp := client.UntagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UntagResource +func (c *NetworkManager) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { + op := &request.Operation{ + Name: opUntagResource, + HTTPMethod: "DELETE", + HTTPPath: "/tags/{resourceArn}", + } + + if input == nil { + input = &UntagResourceInput{} + } + + output = &UntagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UntagResource API operation for AWS Network Manager. +// +// Removes tags from a 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 Network Manager's +// API operation UntagResource for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UntagResource +func (c *NetworkManager) 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 *NetworkManager) 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 opUpdateDevice = "UpdateDevice" + +// UpdateDeviceRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDevice operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDevice for more information on using the UpdateDevice +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateDeviceRequest method. +// req, resp := client.UpdateDeviceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateDevice +func (c *NetworkManager) UpdateDeviceRequest(input *UpdateDeviceInput) (req *request.Request, output *UpdateDeviceOutput) { + op := &request.Operation{ + Name: opUpdateDevice, + HTTPMethod: "PATCH", + HTTPPath: "/global-networks/{globalNetworkId}/devices/{deviceId}", + } + + if input == nil { + input = &UpdateDeviceInput{} + } + + output = &UpdateDeviceOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDevice API operation for AWS Network Manager. +// +// Updates the details for an existing device. To remove information for any +// of the parameters, specify an empty string. +// +// Returns awserr.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 Network Manager's +// API operation UpdateDevice for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateDevice +func (c *NetworkManager) UpdateDevice(input *UpdateDeviceInput) (*UpdateDeviceOutput, error) { + req, out := c.UpdateDeviceRequest(input) + return out, req.Send() +} + +// UpdateDeviceWithContext is the same as UpdateDevice with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDevice for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) UpdateDeviceWithContext(ctx aws.Context, input *UpdateDeviceInput, opts ...request.Option) (*UpdateDeviceOutput, error) { + req, out := c.UpdateDeviceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateGlobalNetwork = "UpdateGlobalNetwork" + +// UpdateGlobalNetworkRequest generates a "aws/request.Request" representing the +// client's request for the UpdateGlobalNetwork operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateGlobalNetwork for more information on using the UpdateGlobalNetwork +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateGlobalNetworkRequest method. +// req, resp := client.UpdateGlobalNetworkRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateGlobalNetwork +func (c *NetworkManager) UpdateGlobalNetworkRequest(input *UpdateGlobalNetworkInput) (req *request.Request, output *UpdateGlobalNetworkOutput) { + op := &request.Operation{ + Name: opUpdateGlobalNetwork, + HTTPMethod: "PATCH", + HTTPPath: "/global-networks/{globalNetworkId}", + } + + if input == nil { + input = &UpdateGlobalNetworkInput{} + } + + output = &UpdateGlobalNetworkOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateGlobalNetwork API operation for AWS Network Manager. +// +// Updates an existing global network. To remove information for any of the +// parameters, specify an empty string. +// +// Returns awserr.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 Network Manager's +// API operation UpdateGlobalNetwork for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateGlobalNetwork +func (c *NetworkManager) UpdateGlobalNetwork(input *UpdateGlobalNetworkInput) (*UpdateGlobalNetworkOutput, error) { + req, out := c.UpdateGlobalNetworkRequest(input) + return out, req.Send() +} + +// UpdateGlobalNetworkWithContext is the same as UpdateGlobalNetwork with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateGlobalNetwork for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) UpdateGlobalNetworkWithContext(ctx aws.Context, input *UpdateGlobalNetworkInput, opts ...request.Option) (*UpdateGlobalNetworkOutput, error) { + req, out := c.UpdateGlobalNetworkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateLink = "UpdateLink" + +// UpdateLinkRequest generates a "aws/request.Request" representing the +// client's request for the UpdateLink operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateLink for more information on using the UpdateLink +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateLinkRequest method. +// req, resp := client.UpdateLinkRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateLink +func (c *NetworkManager) UpdateLinkRequest(input *UpdateLinkInput) (req *request.Request, output *UpdateLinkOutput) { + op := &request.Operation{ + Name: opUpdateLink, + HTTPMethod: "PATCH", + HTTPPath: "/global-networks/{globalNetworkId}/links/{linkId}", + } + + if input == nil { + input = &UpdateLinkInput{} + } + + output = &UpdateLinkOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateLink API operation for AWS Network Manager. +// +// Updates the details for an existing link. To remove information for any of +// the parameters, specify an empty string. +// +// Returns awserr.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 Network Manager's +// API operation UpdateLink for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * ServiceQuotaExceededException +// A service limit was exceeded. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateLink +func (c *NetworkManager) UpdateLink(input *UpdateLinkInput) (*UpdateLinkOutput, error) { + req, out := c.UpdateLinkRequest(input) + return out, req.Send() +} + +// UpdateLinkWithContext is the same as UpdateLink with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateLink for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) UpdateLinkWithContext(ctx aws.Context, input *UpdateLinkInput, opts ...request.Option) (*UpdateLinkOutput, error) { + req, out := c.UpdateLinkRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateSite = "UpdateSite" + +// UpdateSiteRequest generates a "aws/request.Request" representing the +// client's request for the UpdateSite operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateSite for more information on using the UpdateSite +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateSiteRequest method. +// req, resp := client.UpdateSiteRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateSite +func (c *NetworkManager) UpdateSiteRequest(input *UpdateSiteInput) (req *request.Request, output *UpdateSiteOutput) { + op := &request.Operation{ + Name: opUpdateSite, + HTTPMethod: "PATCH", + HTTPPath: "/global-networks/{globalNetworkId}/sites/{siteId}", + } + + if input == nil { + input = &UpdateSiteInput{} + } + + output = &UpdateSiteOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateSite API operation for AWS Network Manager. +// +// Updates the information for an existing site. To remove information for any +// of the parameters, specify an empty string. +// +// Returns awserr.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 Network Manager's +// API operation UpdateSite for usage and error information. +// +// Returned Error Types: +// * ValidationException +// The input fails to satisfy the constraints. +// +// * AccessDeniedException +// You do not have sufficient access to perform this action. +// +// * ResourceNotFoundException +// The specified resource could not be found. +// +// * ConflictException +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +// +// * ThrottlingException +// The request was denied due to request throttling. +// +// * InternalServerException +// The request has failed due to an internal error. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateSite +func (c *NetworkManager) UpdateSite(input *UpdateSiteInput) (*UpdateSiteOutput, error) { + req, out := c.UpdateSiteRequest(input) + return out, req.Send() +} + +// UpdateSiteWithContext is the same as UpdateSite with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateSite for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *NetworkManager) UpdateSiteWithContext(ctx aws.Context, input *UpdateSiteInput, opts ...request.Option) (*UpdateSiteOutput, error) { + req, out := c.UpdateSiteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// You do not have sufficient access to perform this action. +type AccessDeniedException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s AccessDeniedException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccessDeniedException) GoString() string { + return s.String() +} + +func newErrorAccessDeniedException(v protocol.ResponseMetadata) error { + return &AccessDeniedException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *AccessDeniedException) Code() string { + return "AccessDeniedException" +} + +// Message returns the exception's message. +func (s *AccessDeniedException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *AccessDeniedException) OrigErr() error { + return nil +} + +func (s *AccessDeniedException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *AccessDeniedException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *AccessDeniedException) RequestID() string { + return s.RespMetadata.RequestID +} + +type AssociateCustomerGatewayInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the customer gateway. For more information, + // see Resources Defined by Amazon EC2 (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html#amazonec2-resources-for-iam-policies). + // + // CustomerGatewayArn is a required field + CustomerGatewayArn *string `type:"string" required:"true"` + + // The ID of the device. + // + // DeviceId is a required field + DeviceId *string `type:"string" required:"true"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The ID of the link. + LinkId *string `type:"string"` +} + +// String returns the string representation +func (s AssociateCustomerGatewayInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateCustomerGatewayInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AssociateCustomerGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AssociateCustomerGatewayInput"} + if s.CustomerGatewayArn == nil { + invalidParams.Add(request.NewErrParamRequired("CustomerGatewayArn")) + } + if s.DeviceId == nil { + invalidParams.Add(request.NewErrParamRequired("DeviceId")) + } + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCustomerGatewayArn sets the CustomerGatewayArn field's value. +func (s *AssociateCustomerGatewayInput) SetCustomerGatewayArn(v string) *AssociateCustomerGatewayInput { + s.CustomerGatewayArn = &v + return s +} + +// SetDeviceId sets the DeviceId field's value. +func (s *AssociateCustomerGatewayInput) SetDeviceId(v string) *AssociateCustomerGatewayInput { + s.DeviceId = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *AssociateCustomerGatewayInput) SetGlobalNetworkId(v string) *AssociateCustomerGatewayInput { + s.GlobalNetworkId = &v + return s +} + +// SetLinkId sets the LinkId field's value. +func (s *AssociateCustomerGatewayInput) SetLinkId(v string) *AssociateCustomerGatewayInput { + s.LinkId = &v + return s +} + +type AssociateCustomerGatewayOutput struct { + _ struct{} `type:"structure"` + + // The customer gateway association. + CustomerGatewayAssociation *CustomerGatewayAssociation `type:"structure"` +} + +// String returns the string representation +func (s AssociateCustomerGatewayOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateCustomerGatewayOutput) GoString() string { + return s.String() +} + +// SetCustomerGatewayAssociation sets the CustomerGatewayAssociation field's value. +func (s *AssociateCustomerGatewayOutput) SetCustomerGatewayAssociation(v *CustomerGatewayAssociation) *AssociateCustomerGatewayOutput { + s.CustomerGatewayAssociation = v + return s +} + +type AssociateLinkInput struct { + _ struct{} `type:"structure"` + + // The ID of the device. + // + // DeviceId is a required field + DeviceId *string `type:"string" required:"true"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The ID of the link. + // + // LinkId is a required field + LinkId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s AssociateLinkInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateLinkInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AssociateLinkInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AssociateLinkInput"} + if s.DeviceId == nil { + invalidParams.Add(request.NewErrParamRequired("DeviceId")) + } + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.LinkId == nil { + invalidParams.Add(request.NewErrParamRequired("LinkId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDeviceId sets the DeviceId field's value. +func (s *AssociateLinkInput) SetDeviceId(v string) *AssociateLinkInput { + s.DeviceId = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *AssociateLinkInput) SetGlobalNetworkId(v string) *AssociateLinkInput { + s.GlobalNetworkId = &v + return s +} + +// SetLinkId sets the LinkId field's value. +func (s *AssociateLinkInput) SetLinkId(v string) *AssociateLinkInput { + s.LinkId = &v + return s +} + +type AssociateLinkOutput struct { + _ struct{} `type:"structure"` + + // The link association. + LinkAssociation *LinkAssociation `type:"structure"` +} + +// String returns the string representation +func (s AssociateLinkOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateLinkOutput) GoString() string { + return s.String() +} + +// SetLinkAssociation sets the LinkAssociation field's value. +func (s *AssociateLinkOutput) SetLinkAssociation(v *LinkAssociation) *AssociateLinkOutput { + s.LinkAssociation = v + return s +} + +// Describes bandwidth information. +type Bandwidth struct { + _ struct{} `type:"structure"` + + // Download speed in Mbps. + DownloadSpeed *int64 `type:"integer"` + + // Upload speed in Mbps. + UploadSpeed *int64 `type:"integer"` +} + +// String returns the string representation +func (s Bandwidth) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Bandwidth) GoString() string { + return s.String() +} + +// SetDownloadSpeed sets the DownloadSpeed field's value. +func (s *Bandwidth) SetDownloadSpeed(v int64) *Bandwidth { + s.DownloadSpeed = &v + return s +} + +// SetUploadSpeed sets the UploadSpeed field's value. +func (s *Bandwidth) SetUploadSpeed(v int64) *Bandwidth { + s.UploadSpeed = &v + return s +} + +// There was a conflict processing the request. Updating or deleting the resource +// can cause an inconsistent state. +type ConflictException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + // The ID of the resource. + // + // ResourceId is a required field + ResourceId *string `type:"string" required:"true"` + + // The resource type. + // + // ResourceType is a required field + ResourceType *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s ConflictException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ConflictException) GoString() string { + return s.String() +} + +func newErrorConflictException(v protocol.ResponseMetadata) error { + return &ConflictException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ConflictException) Code() string { + return "ConflictException" +} + +// Message returns the exception's message. +func (s *ConflictException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ConflictException) OrigErr() error { + return nil +} + +func (s *ConflictException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ConflictException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ConflictException) RequestID() string { + return s.RespMetadata.RequestID +} + +type CreateDeviceInput struct { + _ struct{} `type:"structure"` + + // A description of the device. + // + // Length Constraints: Maximum length of 256 characters. + Description *string `type:"string"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The location of the device. + Location *Location `type:"structure"` + + // The model of the device. + // + // Length Constraints: Maximum length of 128 characters. + Model *string `type:"string"` + + // The serial number of the device. + // + // Length Constraints: Maximum length of 128 characters. + SerialNumber *string `type:"string"` + + // The ID of the site. + SiteId *string `type:"string"` + + // The tags to apply to the resource during creation. + Tags []*Tag `type:"list"` + + // The type of the device. + Type *string `type:"string"` + + // The vendor of the device. + // + // Length Constraints: Maximum length of 128 characters. + Vendor *string `type:"string"` +} + +// String returns the string representation +func (s CreateDeviceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDeviceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateDeviceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDeviceInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *CreateDeviceInput) SetDescription(v string) *CreateDeviceInput { + s.Description = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *CreateDeviceInput) SetGlobalNetworkId(v string) *CreateDeviceInput { + s.GlobalNetworkId = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *CreateDeviceInput) SetLocation(v *Location) *CreateDeviceInput { + s.Location = v + return s +} + +// SetModel sets the Model field's value. +func (s *CreateDeviceInput) SetModel(v string) *CreateDeviceInput { + s.Model = &v + return s +} + +// SetSerialNumber sets the SerialNumber field's value. +func (s *CreateDeviceInput) SetSerialNumber(v string) *CreateDeviceInput { + s.SerialNumber = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *CreateDeviceInput) SetSiteId(v string) *CreateDeviceInput { + s.SiteId = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateDeviceInput) SetTags(v []*Tag) *CreateDeviceInput { + s.Tags = v + return s +} + +// SetType sets the Type field's value. +func (s *CreateDeviceInput) SetType(v string) *CreateDeviceInput { + s.Type = &v + return s +} + +// SetVendor sets the Vendor field's value. +func (s *CreateDeviceInput) SetVendor(v string) *CreateDeviceInput { + s.Vendor = &v + return s +} + +type CreateDeviceOutput struct { + _ struct{} `type:"structure"` + + // Information about the device. + Device *Device `type:"structure"` +} + +// String returns the string representation +func (s CreateDeviceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDeviceOutput) GoString() string { + return s.String() +} + +// SetDevice sets the Device field's value. +func (s *CreateDeviceOutput) SetDevice(v *Device) *CreateDeviceOutput { + s.Device = v + return s +} + +type CreateGlobalNetworkInput struct { + _ struct{} `type:"structure"` + + // A description of the global network. + // + // Length Constraints: Maximum length of 256 characters. + Description *string `type:"string"` + + // The tags to apply to the resource during creation. + Tags []*Tag `type:"list"` +} + +// String returns the string representation +func (s CreateGlobalNetworkInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateGlobalNetworkInput) GoString() string { + return s.String() +} + +// SetDescription sets the Description field's value. +func (s *CreateGlobalNetworkInput) SetDescription(v string) *CreateGlobalNetworkInput { + s.Description = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateGlobalNetworkInput) SetTags(v []*Tag) *CreateGlobalNetworkInput { + s.Tags = v + return s +} + +type CreateGlobalNetworkOutput struct { + _ struct{} `type:"structure"` + + // Information about the global network object. + GlobalNetwork *GlobalNetwork `type:"structure"` +} + +// String returns the string representation +func (s CreateGlobalNetworkOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateGlobalNetworkOutput) GoString() string { + return s.String() +} + +// SetGlobalNetwork sets the GlobalNetwork field's value. +func (s *CreateGlobalNetworkOutput) SetGlobalNetwork(v *GlobalNetwork) *CreateGlobalNetworkOutput { + s.GlobalNetwork = v + return s +} + +type CreateLinkInput struct { + _ struct{} `type:"structure"` + + // The upload speed and download speed in Mbps. + // + // Bandwidth is a required field + Bandwidth *Bandwidth `type:"structure" required:"true"` + + // A description of the link. + // + // Length Constraints: Maximum length of 256 characters. + Description *string `type:"string"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The provider of the link. + // + // Constraints: Cannot include the following characters: | \ ^ + // + // Length Constraints: Maximum length of 128 characters. + Provider *string `type:"string"` + + // The ID of the site. + // + // SiteId is a required field + SiteId *string `type:"string" required:"true"` + + // The tags to apply to the resource during creation. + Tags []*Tag `type:"list"` + + // The type of the link. + // + // Constraints: Cannot include the following characters: | \ ^ + // + // Length Constraints: Maximum length of 128 characters. + Type *string `type:"string"` +} + +// String returns the string representation +func (s CreateLinkInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateLinkInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateLinkInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateLinkInput"} + if s.Bandwidth == nil { + invalidParams.Add(request.NewErrParamRequired("Bandwidth")) + } + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.SiteId == nil { + invalidParams.Add(request.NewErrParamRequired("SiteId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBandwidth sets the Bandwidth field's value. +func (s *CreateLinkInput) SetBandwidth(v *Bandwidth) *CreateLinkInput { + s.Bandwidth = v + return s +} + +// SetDescription sets the Description field's value. +func (s *CreateLinkInput) SetDescription(v string) *CreateLinkInput { + s.Description = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *CreateLinkInput) SetGlobalNetworkId(v string) *CreateLinkInput { + s.GlobalNetworkId = &v + return s +} + +// SetProvider sets the Provider field's value. +func (s *CreateLinkInput) SetProvider(v string) *CreateLinkInput { + s.Provider = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *CreateLinkInput) SetSiteId(v string) *CreateLinkInput { + s.SiteId = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateLinkInput) SetTags(v []*Tag) *CreateLinkInput { + s.Tags = v + return s +} + +// SetType sets the Type field's value. +func (s *CreateLinkInput) SetType(v string) *CreateLinkInput { + s.Type = &v + return s +} + +type CreateLinkOutput struct { + _ struct{} `type:"structure"` + + // Information about the link. + Link *Link `type:"structure"` +} + +// String returns the string representation +func (s CreateLinkOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateLinkOutput) GoString() string { + return s.String() +} + +// SetLink sets the Link field's value. +func (s *CreateLinkOutput) SetLink(v *Link) *CreateLinkOutput { + s.Link = v + return s +} + +type CreateSiteInput struct { + _ struct{} `type:"structure"` + + // A description of your site. + // + // Length Constraints: Maximum length of 256 characters. + Description *string `type:"string"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The site location. This information is used for visualization in the Network + // Manager console. If you specify the address, the latitude and longitude are + // automatically calculated. + // + // * Address: The physical address of the site. + // + // * Latitude: The latitude of the site. + // + // * Longitude: The longitude of the site. + Location *Location `type:"structure"` + + // The tags to apply to the resource during creation. + Tags []*Tag `type:"list"` +} + +// String returns the string representation +func (s CreateSiteInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateSiteInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateSiteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateSiteInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *CreateSiteInput) SetDescription(v string) *CreateSiteInput { + s.Description = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *CreateSiteInput) SetGlobalNetworkId(v string) *CreateSiteInput { + s.GlobalNetworkId = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *CreateSiteInput) SetLocation(v *Location) *CreateSiteInput { + s.Location = v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateSiteInput) SetTags(v []*Tag) *CreateSiteInput { + s.Tags = v + return s +} + +type CreateSiteOutput struct { + _ struct{} `type:"structure"` + + // Information about the site. + Site *Site `type:"structure"` +} + +// String returns the string representation +func (s CreateSiteOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateSiteOutput) GoString() string { + return s.String() +} + +// SetSite sets the Site field's value. +func (s *CreateSiteOutput) SetSite(v *Site) *CreateSiteOutput { + s.Site = v + return s +} + +// Describes the association between a customer gateway, a device, and a link. +type CustomerGatewayAssociation struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the customer gateway. + CustomerGatewayArn *string `type:"string"` + + // The ID of the device. + DeviceId *string `type:"string"` + + // The ID of the global network. + GlobalNetworkId *string `type:"string"` + + // The ID of the link. + LinkId *string `type:"string"` + + // The association state. + State *string `type:"string" enum:"CustomerGatewayAssociationState"` +} + +// String returns the string representation +func (s CustomerGatewayAssociation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CustomerGatewayAssociation) GoString() string { + return s.String() +} + +// SetCustomerGatewayArn sets the CustomerGatewayArn field's value. +func (s *CustomerGatewayAssociation) SetCustomerGatewayArn(v string) *CustomerGatewayAssociation { + s.CustomerGatewayArn = &v + return s +} + +// SetDeviceId sets the DeviceId field's value. +func (s *CustomerGatewayAssociation) SetDeviceId(v string) *CustomerGatewayAssociation { + s.DeviceId = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *CustomerGatewayAssociation) SetGlobalNetworkId(v string) *CustomerGatewayAssociation { + s.GlobalNetworkId = &v + return s +} + +// SetLinkId sets the LinkId field's value. +func (s *CustomerGatewayAssociation) SetLinkId(v string) *CustomerGatewayAssociation { + s.LinkId = &v + return s +} + +// SetState sets the State field's value. +func (s *CustomerGatewayAssociation) SetState(v string) *CustomerGatewayAssociation { + s.State = &v + return s +} + +type DeleteDeviceInput struct { + _ struct{} `type:"structure"` + + // The ID of the device. + // + // DeviceId is a required field + DeviceId *string `location:"uri" locationName:"deviceId" type:"string" required:"true"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteDeviceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDeviceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteDeviceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDeviceInput"} + if s.DeviceId == nil { + invalidParams.Add(request.NewErrParamRequired("DeviceId")) + } + if s.DeviceId != nil && len(*s.DeviceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DeviceId", 1)) + } + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDeviceId sets the DeviceId field's value. +func (s *DeleteDeviceInput) SetDeviceId(v string) *DeleteDeviceInput { + s.DeviceId = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *DeleteDeviceInput) SetGlobalNetworkId(v string) *DeleteDeviceInput { + s.GlobalNetworkId = &v + return s +} + +type DeleteDeviceOutput struct { + _ struct{} `type:"structure"` + + // Information about the device. + Device *Device `type:"structure"` +} + +// String returns the string representation +func (s DeleteDeviceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDeviceOutput) GoString() string { + return s.String() +} + +// SetDevice sets the Device field's value. +func (s *DeleteDeviceOutput) SetDevice(v *Device) *DeleteDeviceOutput { + s.Device = v + return s +} + +type DeleteGlobalNetworkInput struct { + _ struct{} `type:"structure"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteGlobalNetworkInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteGlobalNetworkInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteGlobalNetworkInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteGlobalNetworkInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *DeleteGlobalNetworkInput) SetGlobalNetworkId(v string) *DeleteGlobalNetworkInput { + s.GlobalNetworkId = &v + return s +} + +type DeleteGlobalNetworkOutput struct { + _ struct{} `type:"structure"` + + // Information about the global network. + GlobalNetwork *GlobalNetwork `type:"structure"` +} + +// String returns the string representation +func (s DeleteGlobalNetworkOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteGlobalNetworkOutput) GoString() string { + return s.String() +} + +// SetGlobalNetwork sets the GlobalNetwork field's value. +func (s *DeleteGlobalNetworkOutput) SetGlobalNetwork(v *GlobalNetwork) *DeleteGlobalNetworkOutput { + s.GlobalNetwork = v + return s +} + +type DeleteLinkInput struct { + _ struct{} `type:"structure"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The ID of the link. + // + // LinkId is a required field + LinkId *string `location:"uri" locationName:"linkId" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteLinkInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteLinkInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteLinkInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteLinkInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.LinkId == nil { + invalidParams.Add(request.NewErrParamRequired("LinkId")) + } + if s.LinkId != nil && len(*s.LinkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("LinkId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *DeleteLinkInput) SetGlobalNetworkId(v string) *DeleteLinkInput { + s.GlobalNetworkId = &v + return s +} + +// SetLinkId sets the LinkId field's value. +func (s *DeleteLinkInput) SetLinkId(v string) *DeleteLinkInput { + s.LinkId = &v + return s +} + +type DeleteLinkOutput struct { + _ struct{} `type:"structure"` + + // Information about the link. + Link *Link `type:"structure"` +} + +// String returns the string representation +func (s DeleteLinkOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteLinkOutput) GoString() string { + return s.String() +} + +// SetLink sets the Link field's value. +func (s *DeleteLinkOutput) SetLink(v *Link) *DeleteLinkOutput { + s.Link = v + return s +} + +type DeleteSiteInput struct { + _ struct{} `type:"structure"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The ID of the site. + // + // SiteId is a required field + SiteId *string `location:"uri" locationName:"siteId" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteSiteInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteSiteInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteSiteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteSiteInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.SiteId == nil { + invalidParams.Add(request.NewErrParamRequired("SiteId")) + } + if s.SiteId != nil && len(*s.SiteId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("SiteId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *DeleteSiteInput) SetGlobalNetworkId(v string) *DeleteSiteInput { + s.GlobalNetworkId = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *DeleteSiteInput) SetSiteId(v string) *DeleteSiteInput { + s.SiteId = &v + return s +} + +type DeleteSiteOutput struct { + _ struct{} `type:"structure"` + + // Information about the site. + Site *Site `type:"structure"` +} + +// String returns the string representation +func (s DeleteSiteOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteSiteOutput) GoString() string { + return s.String() +} + +// SetSite sets the Site field's value. +func (s *DeleteSiteOutput) SetSite(v *Site) *DeleteSiteOutput { + s.Site = v + return s +} + +type DeregisterTransitGatewayInput struct { + _ struct{} `type:"structure"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The Amazon Resource Name (ARN) of the transit gateway. + // + // TransitGatewayArn is a required field + TransitGatewayArn *string `location:"uri" locationName:"transitGatewayArn" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeregisterTransitGatewayInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeregisterTransitGatewayInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeregisterTransitGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeregisterTransitGatewayInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.TransitGatewayArn == nil { + invalidParams.Add(request.NewErrParamRequired("TransitGatewayArn")) + } + if s.TransitGatewayArn != nil && len(*s.TransitGatewayArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TransitGatewayArn", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *DeregisterTransitGatewayInput) SetGlobalNetworkId(v string) *DeregisterTransitGatewayInput { + s.GlobalNetworkId = &v + return s +} + +// SetTransitGatewayArn sets the TransitGatewayArn field's value. +func (s *DeregisterTransitGatewayInput) SetTransitGatewayArn(v string) *DeregisterTransitGatewayInput { + s.TransitGatewayArn = &v + return s +} + +type DeregisterTransitGatewayOutput struct { + _ struct{} `type:"structure"` + + // The transit gateway registration information. + TransitGatewayRegistration *TransitGatewayRegistration `type:"structure"` +} + +// String returns the string representation +func (s DeregisterTransitGatewayOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeregisterTransitGatewayOutput) GoString() string { + return s.String() +} + +// SetTransitGatewayRegistration sets the TransitGatewayRegistration field's value. +func (s *DeregisterTransitGatewayOutput) SetTransitGatewayRegistration(v *TransitGatewayRegistration) *DeregisterTransitGatewayOutput { + s.TransitGatewayRegistration = v + return s +} + +type DescribeGlobalNetworksInput struct { + _ struct{} `type:"structure"` + + // The IDs of one or more global networks. The maximum is 10. + GlobalNetworkIds []*string `location:"querystring" locationName:"globalNetworkIds" type:"list"` + + // The maximum number of results to return. + MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s DescribeGlobalNetworksInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeGlobalNetworksInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeGlobalNetworksInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeGlobalNetworksInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGlobalNetworkIds sets the GlobalNetworkIds field's value. +func (s *DescribeGlobalNetworksInput) SetGlobalNetworkIds(v []*string) *DescribeGlobalNetworksInput { + s.GlobalNetworkIds = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeGlobalNetworksInput) SetMaxResults(v int64) *DescribeGlobalNetworksInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeGlobalNetworksInput) SetNextToken(v string) *DescribeGlobalNetworksInput { + s.NextToken = &v + return s +} + +type DescribeGlobalNetworksOutput struct { + _ struct{} `type:"structure"` + + // Information about the global networks. + GlobalNetworks []*GlobalNetwork `type:"list"` + + // The token for the next page of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeGlobalNetworksOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeGlobalNetworksOutput) GoString() string { + return s.String() +} + +// SetGlobalNetworks sets the GlobalNetworks field's value. +func (s *DescribeGlobalNetworksOutput) SetGlobalNetworks(v []*GlobalNetwork) *DescribeGlobalNetworksOutput { + s.GlobalNetworks = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeGlobalNetworksOutput) SetNextToken(v string) *DescribeGlobalNetworksOutput { + s.NextToken = &v + return s +} + +// Describes a device. +type Device struct { + _ struct{} `type:"structure"` + + // The date and time that the site was created. + CreatedAt *time.Time `type:"timestamp"` + + // The description of the device. + Description *string `type:"string"` + + // The Amazon Resource Name (ARN) of the device. + DeviceArn *string `type:"string"` + + // The ID of the device. + DeviceId *string `type:"string"` + + // The ID of the global network. + GlobalNetworkId *string `type:"string"` + + // The site location. + Location *Location `type:"structure"` + + // The device model. + Model *string `type:"string"` + + // The device serial number. + SerialNumber *string `type:"string"` + + // The site ID. + SiteId *string `type:"string"` + + // The device state. + State *string `type:"string" enum:"DeviceState"` + + // The tags for the device. + Tags []*Tag `type:"list"` + + // The device type. + Type *string `type:"string"` + + // The device vendor. + Vendor *string `type:"string"` +} + +// 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() +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *Device) SetCreatedAt(v time.Time) *Device { + s.CreatedAt = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *Device) SetDescription(v string) *Device { + s.Description = &v + return s +} + +// SetDeviceArn sets the DeviceArn field's value. +func (s *Device) SetDeviceArn(v string) *Device { + s.DeviceArn = &v + return s +} + +// SetDeviceId sets the DeviceId field's value. +func (s *Device) SetDeviceId(v string) *Device { + s.DeviceId = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *Device) SetGlobalNetworkId(v string) *Device { + s.GlobalNetworkId = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *Device) SetLocation(v *Location) *Device { + s.Location = v + return s +} + +// SetModel sets the Model field's value. +func (s *Device) SetModel(v string) *Device { + s.Model = &v + return s +} + +// SetSerialNumber sets the SerialNumber field's value. +func (s *Device) SetSerialNumber(v string) *Device { + s.SerialNumber = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *Device) SetSiteId(v string) *Device { + s.SiteId = &v + return s +} + +// SetState sets the State field's value. +func (s *Device) SetState(v string) *Device { + s.State = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *Device) SetTags(v []*Tag) *Device { + s.Tags = v + return s +} + +// SetType sets the Type field's value. +func (s *Device) SetType(v string) *Device { + s.Type = &v + return s +} + +// SetVendor sets the Vendor field's value. +func (s *Device) SetVendor(v string) *Device { + s.Vendor = &v + return s +} + +type DisassociateCustomerGatewayInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the customer gateway. For more information, + // see Resources Defined by Amazon EC2 (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html#amazonec2-resources-for-iam-policies). + // + // CustomerGatewayArn is a required field + CustomerGatewayArn *string `location:"uri" locationName:"customerGatewayArn" type:"string" required:"true"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` +} + +// String returns the string representation +func (s DisassociateCustomerGatewayInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisassociateCustomerGatewayInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DisassociateCustomerGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DisassociateCustomerGatewayInput"} + if s.CustomerGatewayArn == nil { + invalidParams.Add(request.NewErrParamRequired("CustomerGatewayArn")) + } + if s.CustomerGatewayArn != nil && len(*s.CustomerGatewayArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CustomerGatewayArn", 1)) + } + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCustomerGatewayArn sets the CustomerGatewayArn field's value. +func (s *DisassociateCustomerGatewayInput) SetCustomerGatewayArn(v string) *DisassociateCustomerGatewayInput { + s.CustomerGatewayArn = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *DisassociateCustomerGatewayInput) SetGlobalNetworkId(v string) *DisassociateCustomerGatewayInput { + s.GlobalNetworkId = &v + return s +} + +type DisassociateCustomerGatewayOutput struct { + _ struct{} `type:"structure"` + + // Information about the customer gateway association. + CustomerGatewayAssociation *CustomerGatewayAssociation `type:"structure"` +} + +// String returns the string representation +func (s DisassociateCustomerGatewayOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisassociateCustomerGatewayOutput) GoString() string { + return s.String() +} + +// SetCustomerGatewayAssociation sets the CustomerGatewayAssociation field's value. +func (s *DisassociateCustomerGatewayOutput) SetCustomerGatewayAssociation(v *CustomerGatewayAssociation) *DisassociateCustomerGatewayOutput { + s.CustomerGatewayAssociation = v + return s +} + +type DisassociateLinkInput struct { + _ struct{} `type:"structure"` + + // The ID of the device. + // + // DeviceId is a required field + DeviceId *string `location:"querystring" locationName:"deviceId" type:"string" required:"true"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The ID of the link. + // + // LinkId is a required field + LinkId *string `location:"querystring" locationName:"linkId" type:"string" required:"true"` +} + +// String returns the string representation +func (s DisassociateLinkInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisassociateLinkInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DisassociateLinkInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DisassociateLinkInput"} + if s.DeviceId == nil { + invalidParams.Add(request.NewErrParamRequired("DeviceId")) + } + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.LinkId == nil { + invalidParams.Add(request.NewErrParamRequired("LinkId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDeviceId sets the DeviceId field's value. +func (s *DisassociateLinkInput) SetDeviceId(v string) *DisassociateLinkInput { + s.DeviceId = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *DisassociateLinkInput) SetGlobalNetworkId(v string) *DisassociateLinkInput { + s.GlobalNetworkId = &v + return s +} + +// SetLinkId sets the LinkId field's value. +func (s *DisassociateLinkInput) SetLinkId(v string) *DisassociateLinkInput { + s.LinkId = &v + return s +} + +type DisassociateLinkOutput struct { + _ struct{} `type:"structure"` + + // Information about the link association. + LinkAssociation *LinkAssociation `type:"structure"` +} + +// String returns the string representation +func (s DisassociateLinkOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisassociateLinkOutput) GoString() string { + return s.String() +} + +// SetLinkAssociation sets the LinkAssociation field's value. +func (s *DisassociateLinkOutput) SetLinkAssociation(v *LinkAssociation) *DisassociateLinkOutput { + s.LinkAssociation = v + return s +} + +type GetCustomerGatewayAssociationsInput struct { + _ struct{} `type:"structure"` + + // One or more customer gateway Amazon Resource Names (ARNs). For more information, + // see Resources Defined by Amazon EC2 (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html#amazonec2-resources-for-iam-policies). + // The maximum is 10. + CustomerGatewayArns []*string `location:"querystring" locationName:"customerGatewayArns" type:"list"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The maximum number of results to return. + MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s GetCustomerGatewayAssociationsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCustomerGatewayAssociationsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetCustomerGatewayAssociationsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetCustomerGatewayAssociationsInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCustomerGatewayArns sets the CustomerGatewayArns field's value. +func (s *GetCustomerGatewayAssociationsInput) SetCustomerGatewayArns(v []*string) *GetCustomerGatewayAssociationsInput { + s.CustomerGatewayArns = v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *GetCustomerGatewayAssociationsInput) SetGlobalNetworkId(v string) *GetCustomerGatewayAssociationsInput { + s.GlobalNetworkId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetCustomerGatewayAssociationsInput) SetMaxResults(v int64) *GetCustomerGatewayAssociationsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetCustomerGatewayAssociationsInput) SetNextToken(v string) *GetCustomerGatewayAssociationsInput { + s.NextToken = &v + return s +} + +type GetCustomerGatewayAssociationsOutput struct { + _ struct{} `type:"structure"` + + // The customer gateway associations. + CustomerGatewayAssociations []*CustomerGatewayAssociation `type:"list"` + + // The token for the next page of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s GetCustomerGatewayAssociationsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCustomerGatewayAssociationsOutput) GoString() string { + return s.String() +} + +// SetCustomerGatewayAssociations sets the CustomerGatewayAssociations field's value. +func (s *GetCustomerGatewayAssociationsOutput) SetCustomerGatewayAssociations(v []*CustomerGatewayAssociation) *GetCustomerGatewayAssociationsOutput { + s.CustomerGatewayAssociations = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetCustomerGatewayAssociationsOutput) SetNextToken(v string) *GetCustomerGatewayAssociationsOutput { + s.NextToken = &v + return s +} + +type GetDevicesInput struct { + _ struct{} `type:"structure"` + + // One or more device IDs. The maximum is 10. + DeviceIds []*string `location:"querystring" locationName:"deviceIds" type:"list"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The maximum number of results to return. + MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` + + // The ID of the site. + SiteId *string `location:"querystring" locationName:"siteId" type:"string"` +} + +// String returns the string representation +func (s GetDevicesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDevicesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetDevicesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDevicesInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDeviceIds sets the DeviceIds field's value. +func (s *GetDevicesInput) SetDeviceIds(v []*string) *GetDevicesInput { + s.DeviceIds = v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *GetDevicesInput) SetGlobalNetworkId(v string) *GetDevicesInput { + s.GlobalNetworkId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetDevicesInput) SetMaxResults(v int64) *GetDevicesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetDevicesInput) SetNextToken(v string) *GetDevicesInput { + s.NextToken = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *GetDevicesInput) SetSiteId(v string) *GetDevicesInput { + s.SiteId = &v + return s +} + +type GetDevicesOutput struct { + _ struct{} `type:"structure"` + + // The devices. + Devices []*Device `type:"list"` + + // The token for the next page of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s GetDevicesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDevicesOutput) GoString() string { + return s.String() +} + +// SetDevices sets the Devices field's value. +func (s *GetDevicesOutput) SetDevices(v []*Device) *GetDevicesOutput { + s.Devices = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetDevicesOutput) SetNextToken(v string) *GetDevicesOutput { + s.NextToken = &v + return s +} + +type GetLinkAssociationsInput struct { + _ struct{} `type:"structure"` + + // The ID of the device. + DeviceId *string `location:"querystring" locationName:"deviceId" type:"string"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The ID of the link. + LinkId *string `location:"querystring" locationName:"linkId" type:"string"` + + // The maximum number of results to return. + MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s GetLinkAssociationsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetLinkAssociationsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetLinkAssociationsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetLinkAssociationsInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDeviceId sets the DeviceId field's value. +func (s *GetLinkAssociationsInput) SetDeviceId(v string) *GetLinkAssociationsInput { + s.DeviceId = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *GetLinkAssociationsInput) SetGlobalNetworkId(v string) *GetLinkAssociationsInput { + s.GlobalNetworkId = &v + return s +} + +// SetLinkId sets the LinkId field's value. +func (s *GetLinkAssociationsInput) SetLinkId(v string) *GetLinkAssociationsInput { + s.LinkId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetLinkAssociationsInput) SetMaxResults(v int64) *GetLinkAssociationsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetLinkAssociationsInput) SetNextToken(v string) *GetLinkAssociationsInput { + s.NextToken = &v + return s +} + +type GetLinkAssociationsOutput struct { + _ struct{} `type:"structure"` + + // The link associations. + LinkAssociations []*LinkAssociation `type:"list"` + + // The token for the next page of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s GetLinkAssociationsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetLinkAssociationsOutput) GoString() string { + return s.String() +} + +// SetLinkAssociations sets the LinkAssociations field's value. +func (s *GetLinkAssociationsOutput) SetLinkAssociations(v []*LinkAssociation) *GetLinkAssociationsOutput { + s.LinkAssociations = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetLinkAssociationsOutput) SetNextToken(v string) *GetLinkAssociationsOutput { + s.NextToken = &v + return s +} + +type GetLinksInput struct { + _ struct{} `type:"structure"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // One or more link IDs. The maximum is 10. + LinkIds []*string `location:"querystring" locationName:"linkIds" type:"list"` + + // The maximum number of results to return. + MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` + + // The link provider. + Provider *string `location:"querystring" locationName:"provider" type:"string"` + + // The ID of the site. + SiteId *string `location:"querystring" locationName:"siteId" type:"string"` + + // The link type. + Type *string `location:"querystring" locationName:"type" type:"string"` +} + +// String returns the string representation +func (s GetLinksInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetLinksInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetLinksInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetLinksInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *GetLinksInput) SetGlobalNetworkId(v string) *GetLinksInput { + s.GlobalNetworkId = &v + return s +} + +// SetLinkIds sets the LinkIds field's value. +func (s *GetLinksInput) SetLinkIds(v []*string) *GetLinksInput { + s.LinkIds = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetLinksInput) SetMaxResults(v int64) *GetLinksInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetLinksInput) SetNextToken(v string) *GetLinksInput { + s.NextToken = &v + return s +} + +// SetProvider sets the Provider field's value. +func (s *GetLinksInput) SetProvider(v string) *GetLinksInput { + s.Provider = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *GetLinksInput) SetSiteId(v string) *GetLinksInput { + s.SiteId = &v + return s +} + +// SetType sets the Type field's value. +func (s *GetLinksInput) SetType(v string) *GetLinksInput { + s.Type = &v + return s +} + +type GetLinksOutput struct { + _ struct{} `type:"structure"` + + // The links. + Links []*Link `type:"list"` + + // The token for the next page of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s GetLinksOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetLinksOutput) GoString() string { + return s.String() +} + +// SetLinks sets the Links field's value. +func (s *GetLinksOutput) SetLinks(v []*Link) *GetLinksOutput { + s.Links = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetLinksOutput) SetNextToken(v string) *GetLinksOutput { + s.NextToken = &v + return s +} + +type GetSitesInput struct { + _ struct{} `type:"structure"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The maximum number of results to return. + MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` + + // One or more site IDs. The maximum is 10. + SiteIds []*string `location:"querystring" locationName:"siteIds" type:"list"` +} + +// String returns the string representation +func (s GetSitesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetSitesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetSitesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetSitesInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *GetSitesInput) SetGlobalNetworkId(v string) *GetSitesInput { + s.GlobalNetworkId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetSitesInput) SetMaxResults(v int64) *GetSitesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetSitesInput) SetNextToken(v string) *GetSitesInput { + s.NextToken = &v + return s +} + +// SetSiteIds sets the SiteIds field's value. +func (s *GetSitesInput) SetSiteIds(v []*string) *GetSitesInput { + s.SiteIds = v + return s +} + +type GetSitesOutput struct { + _ struct{} `type:"structure"` + + // The token for the next page of results. + NextToken *string `type:"string"` + + // The sites. + Sites []*Site `type:"list"` +} + +// String returns the string representation +func (s GetSitesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetSitesOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *GetSitesOutput) SetNextToken(v string) *GetSitesOutput { + s.NextToken = &v + return s +} + +// SetSites sets the Sites field's value. +func (s *GetSitesOutput) SetSites(v []*Site) *GetSitesOutput { + s.Sites = v + return s +} + +type GetTransitGatewayRegistrationsInput struct { + _ struct{} `type:"structure"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The maximum number of results to return. + MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` + + // The Amazon Resource Names (ARNs) of one or more transit gateways. The maximum + // is 10. + TransitGatewayArns []*string `location:"querystring" locationName:"transitGatewayArns" type:"list"` +} + +// String returns the string representation +func (s GetTransitGatewayRegistrationsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetTransitGatewayRegistrationsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetTransitGatewayRegistrationsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetTransitGatewayRegistrationsInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *GetTransitGatewayRegistrationsInput) SetGlobalNetworkId(v string) *GetTransitGatewayRegistrationsInput { + s.GlobalNetworkId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetTransitGatewayRegistrationsInput) SetMaxResults(v int64) *GetTransitGatewayRegistrationsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetTransitGatewayRegistrationsInput) SetNextToken(v string) *GetTransitGatewayRegistrationsInput { + s.NextToken = &v + return s +} + +// SetTransitGatewayArns sets the TransitGatewayArns field's value. +func (s *GetTransitGatewayRegistrationsInput) SetTransitGatewayArns(v []*string) *GetTransitGatewayRegistrationsInput { + s.TransitGatewayArns = v + return s +} + +type GetTransitGatewayRegistrationsOutput struct { + _ struct{} `type:"structure"` + + // The token for the next page of results. + NextToken *string `type:"string"` + + // The transit gateway registrations. + TransitGatewayRegistrations []*TransitGatewayRegistration `type:"list"` +} + +// String returns the string representation +func (s GetTransitGatewayRegistrationsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetTransitGatewayRegistrationsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *GetTransitGatewayRegistrationsOutput) SetNextToken(v string) *GetTransitGatewayRegistrationsOutput { + s.NextToken = &v + return s +} + +// SetTransitGatewayRegistrations sets the TransitGatewayRegistrations field's value. +func (s *GetTransitGatewayRegistrationsOutput) SetTransitGatewayRegistrations(v []*TransitGatewayRegistration) *GetTransitGatewayRegistrationsOutput { + s.TransitGatewayRegistrations = v + return s +} + +// Describes a global network. +type GlobalNetwork struct { + _ struct{} `type:"structure"` + + // The date and time that the global network was created. + CreatedAt *time.Time `type:"timestamp"` + + // The description of the global network. + Description *string `type:"string"` + + // The Amazon Resource Name (ARN) of the global network. + GlobalNetworkArn *string `type:"string"` + + // The ID of the global network. + GlobalNetworkId *string `type:"string"` + + // The state of the global network. + State *string `type:"string" enum:"GlobalNetworkState"` + + // The tags for the global network. + Tags []*Tag `type:"list"` +} + +// String returns the string representation +func (s GlobalNetwork) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GlobalNetwork) GoString() string { + return s.String() +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *GlobalNetwork) SetCreatedAt(v time.Time) *GlobalNetwork { + s.CreatedAt = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *GlobalNetwork) SetDescription(v string) *GlobalNetwork { + s.Description = &v + return s +} + +// SetGlobalNetworkArn sets the GlobalNetworkArn field's value. +func (s *GlobalNetwork) SetGlobalNetworkArn(v string) *GlobalNetwork { + s.GlobalNetworkArn = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *GlobalNetwork) SetGlobalNetworkId(v string) *GlobalNetwork { + s.GlobalNetworkId = &v + return s +} + +// SetState sets the State field's value. +func (s *GlobalNetwork) SetState(v string) *GlobalNetwork { + s.State = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *GlobalNetwork) SetTags(v []*Tag) *GlobalNetwork { + s.Tags = v + return s +} + +// The request has failed due to an internal error. +type InternalServerException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + // Indicates when to retry the request. + RetryAfterSeconds *int64 `location:"header" locationName:"Retry-After" type:"integer"` +} + +// String returns the string representation +func (s InternalServerException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InternalServerException) GoString() string { + return s.String() +} + +func newErrorInternalServerException(v protocol.ResponseMetadata) error { + return &InternalServerException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InternalServerException) Code() string { + return "InternalServerException" +} + +// Message returns the exception's message. +func (s *InternalServerException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InternalServerException) OrigErr() error { + return nil +} + +func (s *InternalServerException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InternalServerException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InternalServerException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Describes a link. +type Link struct { + _ struct{} `type:"structure"` + + // The bandwidth for the link. + Bandwidth *Bandwidth `type:"structure"` + + // The date and time that the link was created. + CreatedAt *time.Time `type:"timestamp"` + + // The description of the link. + Description *string `type:"string"` + + // The ID of the global network. + GlobalNetworkId *string `type:"string"` + + // The Amazon Resource Name (ARN) of the link. + LinkArn *string `type:"string"` + + // The ID of the link. + LinkId *string `type:"string"` + + // The provider of the link. + Provider *string `type:"string"` + + // The ID of the site. + SiteId *string `type:"string"` + + // The state of the link. + State *string `type:"string" enum:"LinkState"` + + // The tags for the link. + Tags []*Tag `type:"list"` + + // The type of the link. + Type *string `type:"string"` +} + +// String returns the string representation +func (s Link) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Link) GoString() string { + return s.String() +} + +// SetBandwidth sets the Bandwidth field's value. +func (s *Link) SetBandwidth(v *Bandwidth) *Link { + s.Bandwidth = v + return s +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *Link) SetCreatedAt(v time.Time) *Link { + s.CreatedAt = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *Link) SetDescription(v string) *Link { + s.Description = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *Link) SetGlobalNetworkId(v string) *Link { + s.GlobalNetworkId = &v + return s +} + +// SetLinkArn sets the LinkArn field's value. +func (s *Link) SetLinkArn(v string) *Link { + s.LinkArn = &v + return s +} + +// SetLinkId sets the LinkId field's value. +func (s *Link) SetLinkId(v string) *Link { + s.LinkId = &v + return s +} + +// SetProvider sets the Provider field's value. +func (s *Link) SetProvider(v string) *Link { + s.Provider = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *Link) SetSiteId(v string) *Link { + s.SiteId = &v + return s +} + +// SetState sets the State field's value. +func (s *Link) SetState(v string) *Link { + s.State = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *Link) SetTags(v []*Tag) *Link { + s.Tags = v + return s +} + +// SetType sets the Type field's value. +func (s *Link) SetType(v string) *Link { + s.Type = &v + return s +} + +// Describes the association between a device and a link. +type LinkAssociation struct { + _ struct{} `type:"structure"` + + // The device ID for the link association. + DeviceId *string `type:"string"` + + // The ID of the global network. + GlobalNetworkId *string `type:"string"` + + // The state of the association. + LinkAssociationState *string `type:"string" enum:"LinkAssociationState"` + + // The ID of the link. + LinkId *string `type:"string"` +} + +// String returns the string representation +func (s LinkAssociation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s LinkAssociation) GoString() string { + return s.String() +} + +// SetDeviceId sets the DeviceId field's value. +func (s *LinkAssociation) SetDeviceId(v string) *LinkAssociation { + s.DeviceId = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *LinkAssociation) SetGlobalNetworkId(v string) *LinkAssociation { + s.GlobalNetworkId = &v + return s +} + +// SetLinkAssociationState sets the LinkAssociationState field's value. +func (s *LinkAssociation) SetLinkAssociationState(v string) *LinkAssociation { + s.LinkAssociationState = &v + return s +} + +// SetLinkId sets the LinkId field's value. +func (s *LinkAssociation) SetLinkId(v string) *LinkAssociation { + s.LinkId = &v + return s +} + +type ListTagsForResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource. + // + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"resourceArn" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListTagsForResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsForResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTagsForResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} + 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 *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResourceInput { + s.ResourceArn = &v + return s +} + +type ListTagsForResourceOutput struct { + _ struct{} `type:"structure"` + + // The list of tags. + TagList []*Tag `type:"list"` +} + +// String returns the string representation +func (s ListTagsForResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsForResourceOutput) GoString() string { + return s.String() +} + +// SetTagList sets the TagList field's value. +func (s *ListTagsForResourceOutput) SetTagList(v []*Tag) *ListTagsForResourceOutput { + s.TagList = v + return s +} + +// Describes a location. +type Location struct { + _ struct{} `type:"structure"` + + // The physical address. + Address *string `type:"string"` + + // The latitude. + Latitude *string `type:"string"` + + // The longitude. + Longitude *string `type:"string"` +} + +// 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() +} + +// SetAddress sets the Address field's value. +func (s *Location) SetAddress(v string) *Location { + s.Address = &v + return s +} + +// SetLatitude sets the Latitude field's value. +func (s *Location) SetLatitude(v string) *Location { + s.Latitude = &v + return s +} + +// SetLongitude sets the Longitude field's value. +func (s *Location) SetLongitude(v string) *Location { + s.Longitude = &v + return s +} + +type RegisterTransitGatewayInput struct { + _ struct{} `type:"structure"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The Amazon Resource Name (ARN) of the transit gateway. For more information, + // see Resources Defined by Amazon EC2 (https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html#amazonec2-resources-for-iam-policies). + // + // TransitGatewayArn is a required field + TransitGatewayArn *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s RegisterTransitGatewayInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RegisterTransitGatewayInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RegisterTransitGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RegisterTransitGatewayInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.TransitGatewayArn == nil { + invalidParams.Add(request.NewErrParamRequired("TransitGatewayArn")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *RegisterTransitGatewayInput) SetGlobalNetworkId(v string) *RegisterTransitGatewayInput { + s.GlobalNetworkId = &v + return s +} + +// SetTransitGatewayArn sets the TransitGatewayArn field's value. +func (s *RegisterTransitGatewayInput) SetTransitGatewayArn(v string) *RegisterTransitGatewayInput { + s.TransitGatewayArn = &v + return s +} + +type RegisterTransitGatewayOutput struct { + _ struct{} `type:"structure"` + + // Information about the transit gateway registration. + TransitGatewayRegistration *TransitGatewayRegistration `type:"structure"` +} + +// String returns the string representation +func (s RegisterTransitGatewayOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RegisterTransitGatewayOutput) GoString() string { + return s.String() +} + +// SetTransitGatewayRegistration sets the TransitGatewayRegistration field's value. +func (s *RegisterTransitGatewayOutput) SetTransitGatewayRegistration(v *TransitGatewayRegistration) *RegisterTransitGatewayOutput { + s.TransitGatewayRegistration = v + return s +} + +// The specified resource could not be found. +type ResourceNotFoundException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + // The ID of the resource. + // + // ResourceId is a required field + ResourceId *string `type:"string" required:"true"` + + // The resource type. + // + // ResourceType is a required field + ResourceType *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s ResourceNotFoundException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResourceNotFoundException) GoString() string { + return s.String() +} + +func newErrorResourceNotFoundException(v protocol.ResponseMetadata) error { + return &ResourceNotFoundException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ResourceNotFoundException) Code() string { + return "ResourceNotFoundException" +} + +// Message returns the exception's message. +func (s *ResourceNotFoundException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ResourceNotFoundException) OrigErr() error { + return nil +} + +func (s *ResourceNotFoundException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ResourceNotFoundException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ResourceNotFoundException) RequestID() string { + return s.RespMetadata.RequestID +} + +// A service limit was exceeded. +type ServiceQuotaExceededException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // The limit code. + // + // LimitCode is a required field + LimitCode *string `type:"string" required:"true"` + + // The error message. + Message_ *string `locationName:"Message" type:"string"` + + // The ID of the resource. + ResourceId *string `type:"string"` + + // The resource type. + ResourceType *string `type:"string"` + + // The service code. + // + // ServiceCode is a required field + ServiceCode *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s ServiceQuotaExceededException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ServiceQuotaExceededException) GoString() string { + return s.String() +} + +func newErrorServiceQuotaExceededException(v protocol.ResponseMetadata) error { + return &ServiceQuotaExceededException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ServiceQuotaExceededException) Code() string { + return "ServiceQuotaExceededException" +} + +// Message returns the exception's message. +func (s *ServiceQuotaExceededException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ServiceQuotaExceededException) OrigErr() error { + return nil +} + +func (s *ServiceQuotaExceededException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ServiceQuotaExceededException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ServiceQuotaExceededException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Describes a site. +type Site struct { + _ struct{} `type:"structure"` + + // The date and time that the site was created. + CreatedAt *time.Time `type:"timestamp"` + + // The description of the site. + Description *string `type:"string"` + + // The ID of the global network. + GlobalNetworkId *string `type:"string"` + + // The location of the site. + Location *Location `type:"structure"` + + // The Amazon Resource Name (ARN) of the site. + SiteArn *string `type:"string"` + + // The ID of the site. + SiteId *string `type:"string"` + + // The state of the site. + State *string `type:"string" enum:"SiteState"` + + // The tags for the site. + Tags []*Tag `type:"list"` +} + +// String returns the string representation +func (s Site) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Site) GoString() string { + return s.String() +} + +// SetCreatedAt sets the CreatedAt field's value. +func (s *Site) SetCreatedAt(v time.Time) *Site { + s.CreatedAt = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *Site) SetDescription(v string) *Site { + s.Description = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *Site) SetGlobalNetworkId(v string) *Site { + s.GlobalNetworkId = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *Site) SetLocation(v *Location) *Site { + s.Location = v + return s +} + +// SetSiteArn sets the SiteArn field's value. +func (s *Site) SetSiteArn(v string) *Site { + s.SiteArn = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *Site) SetSiteId(v string) *Site { + s.SiteId = &v + return s +} + +// SetState sets the State field's value. +func (s *Site) SetState(v string) *Site { + s.State = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *Site) SetTags(v []*Tag) *Site { + s.Tags = v + return s +} + +// Describes a tag. +type Tag struct { + _ struct{} `type:"structure"` + + // The tag key. + // + // Length Constraints: Maximum length of 128 characters. + Key *string `type:"string"` + + // The tag value. + // + // Length Constraints: Maximum length of 256 characters. + Value *string `type:"string"` +} + +// String returns the string representation +func (s Tag) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Tag) GoString() string { + return s.String() +} + +// SetKey sets the Key field's value. +func (s *Tag) SetKey(v string) *Tag { + s.Key = &v + return s +} + +// SetValue sets the Value field's value. +func (s *Tag) SetValue(v string) *Tag { + s.Value = &v + return s +} + +type TagResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource. + // + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"resourceArn" type:"string" required:"true"` + + // The tags to apply to the specified resource. + // + // Tags is a required field + Tags []*Tag `type:"list" required:"true"` +} + +// String returns the string representation +func (s TagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *TagResourceInput) SetTags(v []*Tag) *TagResourceInput { + s.Tags = v + return s +} + +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 request was denied due to request throttling. +type ThrottlingException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + // Indicates when to retry the request. + RetryAfterSeconds *int64 `location:"header" locationName:"Retry-After" type:"integer"` +} + +// String returns the string representation +func (s ThrottlingException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ThrottlingException) GoString() string { + return s.String() +} + +func newErrorThrottlingException(v protocol.ResponseMetadata) error { + return &ThrottlingException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ThrottlingException) Code() string { + return "ThrottlingException" +} + +// Message returns the exception's message. +func (s *ThrottlingException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ThrottlingException) OrigErr() error { + return nil +} + +func (s *ThrottlingException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ThrottlingException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ThrottlingException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Describes the registration of a transit gateway to a global network. +type TransitGatewayRegistration struct { + _ struct{} `type:"structure"` + + // The ID of the global network. + GlobalNetworkId *string `type:"string"` + + // The state of the transit gateway registration. + State *TransitGatewayRegistrationStateReason `type:"structure"` + + // The Amazon Resource Name (ARN) of the transit gateway. + TransitGatewayArn *string `type:"string"` +} + +// String returns the string representation +func (s TransitGatewayRegistration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TransitGatewayRegistration) GoString() string { + return s.String() +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *TransitGatewayRegistration) SetGlobalNetworkId(v string) *TransitGatewayRegistration { + s.GlobalNetworkId = &v + return s +} + +// SetState sets the State field's value. +func (s *TransitGatewayRegistration) SetState(v *TransitGatewayRegistrationStateReason) *TransitGatewayRegistration { + s.State = v + return s +} + +// SetTransitGatewayArn sets the TransitGatewayArn field's value. +func (s *TransitGatewayRegistration) SetTransitGatewayArn(v string) *TransitGatewayRegistration { + s.TransitGatewayArn = &v + return s +} + +// Describes the status of a transit gateway registration. +type TransitGatewayRegistrationStateReason struct { + _ struct{} `type:"structure"` + + // The code for the state reason. + Code *string `type:"string" enum:"TransitGatewayRegistrationState"` + + // The message for the state reason. + Message *string `type:"string"` +} + +// String returns the string representation +func (s TransitGatewayRegistrationStateReason) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TransitGatewayRegistrationStateReason) GoString() string { + return s.String() +} + +// SetCode sets the Code field's value. +func (s *TransitGatewayRegistrationStateReason) SetCode(v string) *TransitGatewayRegistrationStateReason { + s.Code = &v + return s +} + +// SetMessage sets the Message field's value. +func (s *TransitGatewayRegistrationStateReason) SetMessage(v string) *TransitGatewayRegistrationStateReason { + s.Message = &v + return s +} + +type UntagResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource. + // + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"resourceArn" type:"string" required:"true"` + + // The tag keys to remove from the specified resource. + // + // 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.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTagKeys sets the TagKeys field's value. +func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { + s.TagKeys = v + return s +} + +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 UpdateDeviceInput struct { + _ struct{} `type:"structure"` + + // A description of the device. + // + // Length Constraints: Maximum length of 256 characters. + Description *string `type:"string"` + + // The ID of the device. + // + // DeviceId is a required field + DeviceId *string `location:"uri" locationName:"deviceId" type:"string" required:"true"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // Describes a location. + Location *Location `type:"structure"` + + // The model of the device. + // + // Length Constraints: Maximum length of 128 characters. + Model *string `type:"string"` + + // The serial number of the device. + // + // Length Constraints: Maximum length of 128 characters. + SerialNumber *string `type:"string"` + + // The ID of the site. + SiteId *string `type:"string"` + + // The type of the device. + Type *string `type:"string"` + + // The vendor of the device. + // + // Length Constraints: Maximum length of 128 characters. + Vendor *string `type:"string"` +} + +// String returns the string representation +func (s UpdateDeviceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateDeviceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateDeviceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateDeviceInput"} + if s.DeviceId == nil { + invalidParams.Add(request.NewErrParamRequired("DeviceId")) + } + if s.DeviceId != nil && len(*s.DeviceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DeviceId", 1)) + } + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *UpdateDeviceInput) SetDescription(v string) *UpdateDeviceInput { + s.Description = &v + return s +} + +// SetDeviceId sets the DeviceId field's value. +func (s *UpdateDeviceInput) SetDeviceId(v string) *UpdateDeviceInput { + s.DeviceId = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *UpdateDeviceInput) SetGlobalNetworkId(v string) *UpdateDeviceInput { + s.GlobalNetworkId = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *UpdateDeviceInput) SetLocation(v *Location) *UpdateDeviceInput { + s.Location = v + return s +} + +// SetModel sets the Model field's value. +func (s *UpdateDeviceInput) SetModel(v string) *UpdateDeviceInput { + s.Model = &v + return s +} + +// SetSerialNumber sets the SerialNumber field's value. +func (s *UpdateDeviceInput) SetSerialNumber(v string) *UpdateDeviceInput { + s.SerialNumber = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *UpdateDeviceInput) SetSiteId(v string) *UpdateDeviceInput { + s.SiteId = &v + return s +} + +// SetType sets the Type field's value. +func (s *UpdateDeviceInput) SetType(v string) *UpdateDeviceInput { + s.Type = &v + return s +} + +// SetVendor sets the Vendor field's value. +func (s *UpdateDeviceInput) SetVendor(v string) *UpdateDeviceInput { + s.Vendor = &v + return s +} + +type UpdateDeviceOutput struct { + _ struct{} `type:"structure"` + + // Information about the device. + Device *Device `type:"structure"` +} + +// String returns the string representation +func (s UpdateDeviceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateDeviceOutput) GoString() string { + return s.String() +} + +// SetDevice sets the Device field's value. +func (s *UpdateDeviceOutput) SetDevice(v *Device) *UpdateDeviceOutput { + s.Device = v + return s +} + +type UpdateGlobalNetworkInput struct { + _ struct{} `type:"structure"` + + // A description of the global network. + // + // Length Constraints: Maximum length of 256 characters. + Description *string `type:"string"` + + // The ID of your global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` +} + +// String returns the string representation +func (s UpdateGlobalNetworkInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateGlobalNetworkInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateGlobalNetworkInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateGlobalNetworkInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *UpdateGlobalNetworkInput) SetDescription(v string) *UpdateGlobalNetworkInput { + s.Description = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *UpdateGlobalNetworkInput) SetGlobalNetworkId(v string) *UpdateGlobalNetworkInput { + s.GlobalNetworkId = &v + return s +} + +type UpdateGlobalNetworkOutput struct { + _ struct{} `type:"structure"` + + // Information about the global network object. + GlobalNetwork *GlobalNetwork `type:"structure"` +} + +// String returns the string representation +func (s UpdateGlobalNetworkOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateGlobalNetworkOutput) GoString() string { + return s.String() +} + +// SetGlobalNetwork sets the GlobalNetwork field's value. +func (s *UpdateGlobalNetworkOutput) SetGlobalNetwork(v *GlobalNetwork) *UpdateGlobalNetworkOutput { + s.GlobalNetwork = v + return s +} + +type UpdateLinkInput struct { + _ struct{} `type:"structure"` + + // The upload and download speed in Mbps. + Bandwidth *Bandwidth `type:"structure"` + + // A description of the link. + // + // Length Constraints: Maximum length of 256 characters. + Description *string `type:"string"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The ID of the link. + // + // LinkId is a required field + LinkId *string `location:"uri" locationName:"linkId" type:"string" required:"true"` + + // The provider of the link. + // + // Length Constraints: Maximum length of 128 characters. + Provider *string `type:"string"` + + // The type of the link. + // + // Length Constraints: Maximum length of 128 characters. + Type *string `type:"string"` +} + +// String returns the string representation +func (s UpdateLinkInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateLinkInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateLinkInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateLinkInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.LinkId == nil { + invalidParams.Add(request.NewErrParamRequired("LinkId")) + } + if s.LinkId != nil && len(*s.LinkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("LinkId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBandwidth sets the Bandwidth field's value. +func (s *UpdateLinkInput) SetBandwidth(v *Bandwidth) *UpdateLinkInput { + s.Bandwidth = v + return s +} + +// SetDescription sets the Description field's value. +func (s *UpdateLinkInput) SetDescription(v string) *UpdateLinkInput { + s.Description = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *UpdateLinkInput) SetGlobalNetworkId(v string) *UpdateLinkInput { + s.GlobalNetworkId = &v + return s +} + +// SetLinkId sets the LinkId field's value. +func (s *UpdateLinkInput) SetLinkId(v string) *UpdateLinkInput { + s.LinkId = &v + return s +} + +// SetProvider sets the Provider field's value. +func (s *UpdateLinkInput) SetProvider(v string) *UpdateLinkInput { + s.Provider = &v + return s +} + +// SetType sets the Type field's value. +func (s *UpdateLinkInput) SetType(v string) *UpdateLinkInput { + s.Type = &v + return s +} + +type UpdateLinkOutput struct { + _ struct{} `type:"structure"` + + // Information about the link. + Link *Link `type:"structure"` +} + +// String returns the string representation +func (s UpdateLinkOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateLinkOutput) GoString() string { + return s.String() +} + +// SetLink sets the Link field's value. +func (s *UpdateLinkOutput) SetLink(v *Link) *UpdateLinkOutput { + s.Link = v + return s +} + +type UpdateSiteInput struct { + _ struct{} `type:"structure"` + + // A description of your site. + // + // Length Constraints: Maximum length of 256 characters. + Description *string `type:"string"` + + // The ID of the global network. + // + // GlobalNetworkId is a required field + GlobalNetworkId *string `location:"uri" locationName:"globalNetworkId" type:"string" required:"true"` + + // The site location: + // + // * Address: The physical address of the site. + // + // * Latitude: The latitude of the site. + // + // * Longitude: The longitude of the site. + Location *Location `type:"structure"` + + // The ID of your site. + // + // SiteId is a required field + SiteId *string `location:"uri" locationName:"siteId" type:"string" required:"true"` +} + +// String returns the string representation +func (s UpdateSiteInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateSiteInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateSiteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateSiteInput"} + if s.GlobalNetworkId == nil { + invalidParams.Add(request.NewErrParamRequired("GlobalNetworkId")) + } + if s.GlobalNetworkId != nil && len(*s.GlobalNetworkId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GlobalNetworkId", 1)) + } + if s.SiteId == nil { + invalidParams.Add(request.NewErrParamRequired("SiteId")) + } + if s.SiteId != nil && len(*s.SiteId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("SiteId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *UpdateSiteInput) SetDescription(v string) *UpdateSiteInput { + s.Description = &v + return s +} + +// SetGlobalNetworkId sets the GlobalNetworkId field's value. +func (s *UpdateSiteInput) SetGlobalNetworkId(v string) *UpdateSiteInput { + s.GlobalNetworkId = &v + return s +} + +// SetLocation sets the Location field's value. +func (s *UpdateSiteInput) SetLocation(v *Location) *UpdateSiteInput { + s.Location = v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *UpdateSiteInput) SetSiteId(v string) *UpdateSiteInput { + s.SiteId = &v + return s +} + +type UpdateSiteOutput struct { + _ struct{} `type:"structure"` + + // Information about the site. + Site *Site `type:"structure"` +} + +// String returns the string representation +func (s UpdateSiteOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateSiteOutput) GoString() string { + return s.String() +} + +// SetSite sets the Site field's value. +func (s *UpdateSiteOutput) SetSite(v *Site) *UpdateSiteOutput { + s.Site = v + return s +} + +// The input fails to satisfy the constraints. +type ValidationException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // The fields that caused the error, if applicable. + Fields []*ValidationExceptionField `type:"list"` + + Message_ *string `locationName:"Message" type:"string"` + + // The reason for the error. + Reason *string `type:"string" enum:"ValidationExceptionReason"` +} + +// String returns the string representation +func (s ValidationException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationException) GoString() string { + return s.String() +} + +func newErrorValidationException(v protocol.ResponseMetadata) error { + return &ValidationException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ValidationException) Code() string { + return "ValidationException" +} + +// Message returns the exception's message. +func (s *ValidationException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ValidationException) OrigErr() error { + return nil +} + +func (s *ValidationException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ValidationException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ValidationException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Describes a validation exception for a field. +type ValidationExceptionField struct { + _ struct{} `type:"structure"` + + // The message for the field. + // + // Message is a required field + Message *string `type:"string" required:"true"` + + // The name of the field. + // + // Name is a required field + Name *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s ValidationExceptionField) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationExceptionField) GoString() string { + return s.String() +} + +// SetMessage sets the Message field's value. +func (s *ValidationExceptionField) SetMessage(v string) *ValidationExceptionField { + s.Message = &v + return s +} + +// SetName sets the Name field's value. +func (s *ValidationExceptionField) SetName(v string) *ValidationExceptionField { + s.Name = &v + return s +} + +const ( + // CustomerGatewayAssociationStatePending is a CustomerGatewayAssociationState enum value + CustomerGatewayAssociationStatePending = "PENDING" + + // CustomerGatewayAssociationStateAvailable is a CustomerGatewayAssociationState enum value + CustomerGatewayAssociationStateAvailable = "AVAILABLE" + + // CustomerGatewayAssociationStateDeleting is a CustomerGatewayAssociationState enum value + CustomerGatewayAssociationStateDeleting = "DELETING" + + // CustomerGatewayAssociationStateDeleted is a CustomerGatewayAssociationState enum value + CustomerGatewayAssociationStateDeleted = "DELETED" +) + +// CustomerGatewayAssociationState_Values returns all elements of the CustomerGatewayAssociationState enum +func CustomerGatewayAssociationState_Values() []string { + return []string{ + CustomerGatewayAssociationStatePending, + CustomerGatewayAssociationStateAvailable, + CustomerGatewayAssociationStateDeleting, + CustomerGatewayAssociationStateDeleted, + } +} + +const ( + // DeviceStatePending is a DeviceState enum value + DeviceStatePending = "PENDING" + + // DeviceStateAvailable is a DeviceState enum value + DeviceStateAvailable = "AVAILABLE" + + // DeviceStateDeleting is a DeviceState enum value + DeviceStateDeleting = "DELETING" + + // DeviceStateUpdating is a DeviceState enum value + DeviceStateUpdating = "UPDATING" +) + +// DeviceState_Values returns all elements of the DeviceState enum +func DeviceState_Values() []string { + return []string{ + DeviceStatePending, + DeviceStateAvailable, + DeviceStateDeleting, + DeviceStateUpdating, + } +} + +const ( + // GlobalNetworkStatePending is a GlobalNetworkState enum value + GlobalNetworkStatePending = "PENDING" + + // GlobalNetworkStateAvailable is a GlobalNetworkState enum value + GlobalNetworkStateAvailable = "AVAILABLE" + + // GlobalNetworkStateDeleting is a GlobalNetworkState enum value + GlobalNetworkStateDeleting = "DELETING" + + // GlobalNetworkStateUpdating is a GlobalNetworkState enum value + GlobalNetworkStateUpdating = "UPDATING" +) + +// GlobalNetworkState_Values returns all elements of the GlobalNetworkState enum +func GlobalNetworkState_Values() []string { + return []string{ + GlobalNetworkStatePending, + GlobalNetworkStateAvailable, + GlobalNetworkStateDeleting, + GlobalNetworkStateUpdating, + } +} + +const ( + // LinkAssociationStatePending is a LinkAssociationState enum value + LinkAssociationStatePending = "PENDING" + + // LinkAssociationStateAvailable is a LinkAssociationState enum value + LinkAssociationStateAvailable = "AVAILABLE" + + // LinkAssociationStateDeleting is a LinkAssociationState enum value + LinkAssociationStateDeleting = "DELETING" + + // LinkAssociationStateDeleted is a LinkAssociationState enum value + LinkAssociationStateDeleted = "DELETED" +) + +// LinkAssociationState_Values returns all elements of the LinkAssociationState enum +func LinkAssociationState_Values() []string { + return []string{ + LinkAssociationStatePending, + LinkAssociationStateAvailable, + LinkAssociationStateDeleting, + LinkAssociationStateDeleted, + } +} + +const ( + // LinkStatePending is a LinkState enum value + LinkStatePending = "PENDING" + + // LinkStateAvailable is a LinkState enum value + LinkStateAvailable = "AVAILABLE" + + // LinkStateDeleting is a LinkState enum value + LinkStateDeleting = "DELETING" + + // LinkStateUpdating is a LinkState enum value + LinkStateUpdating = "UPDATING" +) + +// LinkState_Values returns all elements of the LinkState enum +func LinkState_Values() []string { + return []string{ + LinkStatePending, + LinkStateAvailable, + LinkStateDeleting, + LinkStateUpdating, + } +} + +const ( + // SiteStatePending is a SiteState enum value + SiteStatePending = "PENDING" + + // SiteStateAvailable is a SiteState enum value + SiteStateAvailable = "AVAILABLE" + + // SiteStateDeleting is a SiteState enum value + SiteStateDeleting = "DELETING" + + // SiteStateUpdating is a SiteState enum value + SiteStateUpdating = "UPDATING" +) + +// SiteState_Values returns all elements of the SiteState enum +func SiteState_Values() []string { + return []string{ + SiteStatePending, + SiteStateAvailable, + SiteStateDeleting, + SiteStateUpdating, + } +} + +const ( + // TransitGatewayRegistrationStatePending is a TransitGatewayRegistrationState enum value + TransitGatewayRegistrationStatePending = "PENDING" + + // TransitGatewayRegistrationStateAvailable is a TransitGatewayRegistrationState enum value + TransitGatewayRegistrationStateAvailable = "AVAILABLE" + + // TransitGatewayRegistrationStateDeleting is a TransitGatewayRegistrationState enum value + TransitGatewayRegistrationStateDeleting = "DELETING" + + // TransitGatewayRegistrationStateDeleted is a TransitGatewayRegistrationState enum value + TransitGatewayRegistrationStateDeleted = "DELETED" + + // TransitGatewayRegistrationStateFailed is a TransitGatewayRegistrationState enum value + TransitGatewayRegistrationStateFailed = "FAILED" +) + +// TransitGatewayRegistrationState_Values returns all elements of the TransitGatewayRegistrationState enum +func TransitGatewayRegistrationState_Values() []string { + return []string{ + TransitGatewayRegistrationStatePending, + TransitGatewayRegistrationStateAvailable, + TransitGatewayRegistrationStateDeleting, + TransitGatewayRegistrationStateDeleted, + TransitGatewayRegistrationStateFailed, + } +} + +const ( + // ValidationExceptionReasonUnknownOperation is a ValidationExceptionReason enum value + ValidationExceptionReasonUnknownOperation = "UnknownOperation" + + // ValidationExceptionReasonCannotParse is a ValidationExceptionReason enum value + ValidationExceptionReasonCannotParse = "CannotParse" + + // ValidationExceptionReasonFieldValidationFailed is a ValidationExceptionReason enum value + ValidationExceptionReasonFieldValidationFailed = "FieldValidationFailed" + + // ValidationExceptionReasonOther is a ValidationExceptionReason enum value + ValidationExceptionReasonOther = "Other" +) + +// ValidationExceptionReason_Values returns all elements of the ValidationExceptionReason enum +func ValidationExceptionReason_Values() []string { + return []string{ + ValidationExceptionReasonUnknownOperation, + ValidationExceptionReasonCannotParse, + ValidationExceptionReasonFieldValidationFailed, + ValidationExceptionReasonOther, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/networkmanager/doc.go b/vendor/github.com/aws/aws-sdk-go/service/networkmanager/doc.go new file mode 100644 index 00000000000..65cd8cb7a9e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/networkmanager/doc.go @@ -0,0 +1,30 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package networkmanager provides the client and types for making API +// requests to AWS Network Manager. +// +// Transit Gateway Network Manager (Network Manager) enables you to create a +// global network, in which you can monitor your AWS and on-premises networks +// that are built around transit gateways. +// +// See https://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05 for more information on this service. +// +// See networkmanager package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/networkmanager/ +// +// Using the Client +// +// To contact AWS Network Manager with the SDK use the New function to create +// a new service client. With that client you can make API requests to the service. +// These clients are safe to use concurrently. +// +// See the SDK's documentation for more information on how to use the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws.Config documentation for more information on configuring SDK clients. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Network Manager client NetworkManager for more +// information on creating client for this service. +// https://docs.aws.amazon.com/sdk-for-go/api/service/networkmanager/#New +package networkmanager diff --git a/vendor/github.com/aws/aws-sdk-go/service/networkmanager/errors.go b/vendor/github.com/aws/aws-sdk-go/service/networkmanager/errors.go new file mode 100644 index 00000000000..9e9c2bf05e6 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/networkmanager/errors.go @@ -0,0 +1,63 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package networkmanager + +import ( + "github.com/aws/aws-sdk-go/private/protocol" +) + +const ( + + // ErrCodeAccessDeniedException for service response error code + // "AccessDeniedException". + // + // You do not have sufficient access to perform this action. + ErrCodeAccessDeniedException = "AccessDeniedException" + + // ErrCodeConflictException for service response error code + // "ConflictException". + // + // There was a conflict processing the request. Updating or deleting the resource + // can cause an inconsistent state. + ErrCodeConflictException = "ConflictException" + + // ErrCodeInternalServerException for service response error code + // "InternalServerException". + // + // The request has failed due to an internal error. + ErrCodeInternalServerException = "InternalServerException" + + // ErrCodeResourceNotFoundException for service response error code + // "ResourceNotFoundException". + // + // The specified resource could not be found. + ErrCodeResourceNotFoundException = "ResourceNotFoundException" + + // ErrCodeServiceQuotaExceededException for service response error code + // "ServiceQuotaExceededException". + // + // A service limit was exceeded. + ErrCodeServiceQuotaExceededException = "ServiceQuotaExceededException" + + // ErrCodeThrottlingException for service response error code + // "ThrottlingException". + // + // The request was denied due to request throttling. + ErrCodeThrottlingException = "ThrottlingException" + + // ErrCodeValidationException for service response error code + // "ValidationException". + // + // The input fails to satisfy the constraints. + ErrCodeValidationException = "ValidationException" +) + +var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ + "AccessDeniedException": newErrorAccessDeniedException, + "ConflictException": newErrorConflictException, + "InternalServerException": newErrorInternalServerException, + "ResourceNotFoundException": newErrorResourceNotFoundException, + "ServiceQuotaExceededException": newErrorServiceQuotaExceededException, + "ThrottlingException": newErrorThrottlingException, + "ValidationException": newErrorValidationException, +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/networkmanager/service.go b/vendor/github.com/aws/aws-sdk-go/service/networkmanager/service.go new file mode 100644 index 00000000000..56ce4f413be --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/networkmanager/service.go @@ -0,0 +1,104 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package networkmanager + +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" + "github.com/aws/aws-sdk-go/private/protocol/restjson" +) + +// NetworkManager provides the API operation methods for making requests to +// AWS Network Manager. See this package's package overview docs +// for details on the service. +// +// NetworkManager methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. +type NetworkManager 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 = "NetworkManager" // Name of service. + EndpointsID = "networkmanager" // ID to lookup a service endpoint with. + ServiceID = "NetworkManager" // ServiceID is a unique identifier of a specific service. +) + +// New creates a new instance of the NetworkManager 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: +// mySession := session.Must(session.NewSession()) +// +// // Create a NetworkManager client from just a session. +// svc := networkmanager.New(mySession) +// +// // Create a NetworkManager client with additional configuration +// svc := networkmanager.New(mySession, aws.NewConfig().WithRegion("us-west-2")) +func New(p client.ConfigProvider, cfgs ...*aws.Config) *NetworkManager { + c := p.ClientConfig(EndpointsID, cfgs...) + if c.SigningNameDerived || len(c.SigningName) == 0 { + c.SigningName = "networkmanager" + } + return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) +} + +// newClient creates, initializes and returns a new service client instance. +func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *NetworkManager { + svc := &NetworkManager{ + Client: client.New( + cfg, + metadata.ClientInfo{ + ServiceName: ServiceName, + ServiceID: ServiceID, + SigningName: signingName, + SigningRegion: signingRegion, + PartitionID: partitionID, + Endpoint: endpoint, + APIVersion: "2019-07-05", + }, + handlers, + ), + } + + // Handlers + svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) + svc.Handlers.Build.PushBackNamed(restjson.BuildHandler) + svc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler) + svc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler) + svc.Handlers.UnmarshalError.PushBackNamed( + protocol.NewUnmarshalErrorHandler(restjson.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(), + ) + + // Run custom client initialization if present + if initClient != nil { + initClient(svc.Client) + } + + return svc +} + +// newRequest creates a new request for a NetworkManager operation and runs any +// custom request initialization. +func (c *NetworkManager) 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/opsworks/api.go b/vendor/github.com/aws/aws-sdk-go/service/opsworks/api.go index 27ef9e81218..c16c0012801 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 @@ -17616,6 +17616,16 @@ const ( AppAttributesKeysAwsFlowRubySettings = "AwsFlowRubySettings" ) +// AppAttributesKeys_Values returns all elements of the AppAttributesKeys enum +func AppAttributesKeys_Values() []string { + return []string{ + AppAttributesKeysDocumentRoot, + AppAttributesKeysRailsEnv, + AppAttributesKeysAutoBundleOnDeploy, + AppAttributesKeysAwsFlowRubySettings, + } +} + const ( // AppTypeAwsFlowRuby is a AppType enum value AppTypeAwsFlowRuby = "aws-flow-ruby" @@ -17639,6 +17649,19 @@ const ( AppTypeOther = "other" ) +// AppType_Values returns all elements of the AppType enum +func AppType_Values() []string { + return []string{ + AppTypeAwsFlowRuby, + AppTypeJava, + AppTypeRails, + AppTypePhp, + AppTypeNodejs, + AppTypeStatic, + AppTypeOther, + } +} + const ( // ArchitectureX8664 is a Architecture enum value ArchitectureX8664 = "x86_64" @@ -17647,6 +17670,14 @@ const ( ArchitectureI386 = "i386" ) +// Architecture_Values returns all elements of the Architecture enum +func Architecture_Values() []string { + return []string{ + ArchitectureX8664, + ArchitectureI386, + } +} + const ( // AutoScalingTypeLoad is a AutoScalingType enum value AutoScalingTypeLoad = "load" @@ -17655,6 +17686,14 @@ const ( AutoScalingTypeTimer = "timer" ) +// AutoScalingType_Values returns all elements of the AutoScalingType enum +func AutoScalingType_Values() []string { + return []string{ + AutoScalingTypeLoad, + AutoScalingTypeTimer, + } +} + // 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. @@ -17936,6 +17975,104 @@ const ( CloudWatchLogsEncodingUtf8Sig = "utf_8_sig" ) +// CloudWatchLogsEncoding_Values returns all elements of the CloudWatchLogsEncoding enum +func CloudWatchLogsEncoding_Values() []string { + return []string{ + CloudWatchLogsEncodingAscii, + CloudWatchLogsEncodingBig5, + CloudWatchLogsEncodingBig5hkscs, + CloudWatchLogsEncodingCp037, + CloudWatchLogsEncodingCp424, + CloudWatchLogsEncodingCp437, + CloudWatchLogsEncodingCp500, + CloudWatchLogsEncodingCp720, + CloudWatchLogsEncodingCp737, + CloudWatchLogsEncodingCp775, + CloudWatchLogsEncodingCp850, + CloudWatchLogsEncodingCp852, + CloudWatchLogsEncodingCp855, + CloudWatchLogsEncodingCp856, + CloudWatchLogsEncodingCp857, + CloudWatchLogsEncodingCp858, + CloudWatchLogsEncodingCp860, + CloudWatchLogsEncodingCp861, + CloudWatchLogsEncodingCp862, + CloudWatchLogsEncodingCp863, + CloudWatchLogsEncodingCp864, + CloudWatchLogsEncodingCp865, + CloudWatchLogsEncodingCp866, + CloudWatchLogsEncodingCp869, + CloudWatchLogsEncodingCp874, + CloudWatchLogsEncodingCp875, + CloudWatchLogsEncodingCp932, + CloudWatchLogsEncodingCp949, + CloudWatchLogsEncodingCp950, + CloudWatchLogsEncodingCp1006, + CloudWatchLogsEncodingCp1026, + CloudWatchLogsEncodingCp1140, + CloudWatchLogsEncodingCp1250, + CloudWatchLogsEncodingCp1251, + CloudWatchLogsEncodingCp1252, + CloudWatchLogsEncodingCp1253, + CloudWatchLogsEncodingCp1254, + CloudWatchLogsEncodingCp1255, + CloudWatchLogsEncodingCp1256, + CloudWatchLogsEncodingCp1257, + CloudWatchLogsEncodingCp1258, + CloudWatchLogsEncodingEucJp, + CloudWatchLogsEncodingEucJis2004, + CloudWatchLogsEncodingEucJisx0213, + CloudWatchLogsEncodingEucKr, + CloudWatchLogsEncodingGb2312, + CloudWatchLogsEncodingGbk, + CloudWatchLogsEncodingGb18030, + CloudWatchLogsEncodingHz, + CloudWatchLogsEncodingIso2022Jp, + CloudWatchLogsEncodingIso2022Jp1, + CloudWatchLogsEncodingIso2022Jp2, + CloudWatchLogsEncodingIso2022Jp2004, + CloudWatchLogsEncodingIso2022Jp3, + CloudWatchLogsEncodingIso2022JpExt, + CloudWatchLogsEncodingIso2022Kr, + CloudWatchLogsEncodingLatin1, + CloudWatchLogsEncodingIso88592, + CloudWatchLogsEncodingIso88593, + CloudWatchLogsEncodingIso88594, + CloudWatchLogsEncodingIso88595, + CloudWatchLogsEncodingIso88596, + CloudWatchLogsEncodingIso88597, + CloudWatchLogsEncodingIso88598, + CloudWatchLogsEncodingIso88599, + CloudWatchLogsEncodingIso885910, + CloudWatchLogsEncodingIso885913, + CloudWatchLogsEncodingIso885914, + CloudWatchLogsEncodingIso885915, + CloudWatchLogsEncodingIso885916, + CloudWatchLogsEncodingJohab, + CloudWatchLogsEncodingKoi8R, + CloudWatchLogsEncodingKoi8U, + CloudWatchLogsEncodingMacCyrillic, + CloudWatchLogsEncodingMacGreek, + CloudWatchLogsEncodingMacIceland, + CloudWatchLogsEncodingMacLatin2, + CloudWatchLogsEncodingMacRoman, + CloudWatchLogsEncodingMacTurkish, + CloudWatchLogsEncodingPtcp154, + CloudWatchLogsEncodingShiftJis, + CloudWatchLogsEncodingShiftJis2004, + CloudWatchLogsEncodingShiftJisx0213, + CloudWatchLogsEncodingUtf32, + CloudWatchLogsEncodingUtf32Be, + CloudWatchLogsEncodingUtf32Le, + CloudWatchLogsEncodingUtf16, + CloudWatchLogsEncodingUtf16Be, + CloudWatchLogsEncodingUtf16Le, + CloudWatchLogsEncodingUtf7, + CloudWatchLogsEncodingUtf8, + CloudWatchLogsEncodingUtf8Sig, + } +} + // 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. @@ -17947,6 +18084,14 @@ const ( CloudWatchLogsInitialPositionEndOfFile = "end_of_file" ) +// CloudWatchLogsInitialPosition_Values returns all elements of the CloudWatchLogsInitialPosition enum +func CloudWatchLogsInitialPosition_Values() []string { + return []string{ + CloudWatchLogsInitialPositionStartOfFile, + CloudWatchLogsInitialPositionEndOfFile, + } +} + // The preferred time zone for logs streamed to CloudWatch Logs. Valid values // are LOCAL and UTC, for Coordinated Universal Time. const ( @@ -17957,6 +18102,14 @@ const ( CloudWatchLogsTimeZoneUtc = "UTC" ) +// CloudWatchLogsTimeZone_Values returns all elements of the CloudWatchLogsTimeZone enum +func CloudWatchLogsTimeZone_Values() []string { + return []string{ + CloudWatchLogsTimeZoneLocal, + CloudWatchLogsTimeZoneUtc, + } +} + const ( // DeploymentCommandNameInstallDependencies is a DeploymentCommandName enum value DeploymentCommandNameInstallDependencies = "install_dependencies" @@ -17995,6 +18148,24 @@ const ( DeploymentCommandNameUndeploy = "undeploy" ) +// DeploymentCommandName_Values returns all elements of the DeploymentCommandName enum +func DeploymentCommandName_Values() []string { + return []string{ + DeploymentCommandNameInstallDependencies, + DeploymentCommandNameUpdateDependencies, + DeploymentCommandNameUpdateCustomCookbooks, + DeploymentCommandNameExecuteRecipes, + DeploymentCommandNameConfigure, + DeploymentCommandNameSetup, + DeploymentCommandNameDeploy, + DeploymentCommandNameRollback, + DeploymentCommandNameStart, + DeploymentCommandNameStop, + DeploymentCommandNameRestart, + DeploymentCommandNameUndeploy, + } +} + const ( // LayerAttributesKeysEcsClusterArn is a LayerAttributesKeys enum value LayerAttributesKeysEcsClusterArn = "EcsClusterArn" @@ -18072,6 +18243,37 @@ const ( LayerAttributesKeysJavaAppServerVersion = "JavaAppServerVersion" ) +// LayerAttributesKeys_Values returns all elements of the LayerAttributesKeys enum +func LayerAttributesKeys_Values() []string { + return []string{ + LayerAttributesKeysEcsClusterArn, + LayerAttributesKeysEnableHaproxyStats, + LayerAttributesKeysHaproxyStatsUrl, + LayerAttributesKeysHaproxyStatsUser, + LayerAttributesKeysHaproxyStatsPassword, + LayerAttributesKeysHaproxyHealthCheckUrl, + LayerAttributesKeysHaproxyHealthCheckMethod, + LayerAttributesKeysMysqlRootPassword, + LayerAttributesKeysMysqlRootPasswordUbiquitous, + LayerAttributesKeysGangliaUrl, + LayerAttributesKeysGangliaUser, + LayerAttributesKeysGangliaPassword, + LayerAttributesKeysMemcachedMemory, + LayerAttributesKeysNodejsVersion, + LayerAttributesKeysRubyVersion, + LayerAttributesKeysRubygemsVersion, + LayerAttributesKeysManageBundler, + LayerAttributesKeysBundlerVersion, + LayerAttributesKeysRailsStack, + LayerAttributesKeysPassengerVersion, + LayerAttributesKeysJvm, + LayerAttributesKeysJvmVersion, + LayerAttributesKeysJvmOptions, + LayerAttributesKeysJavaAppServer, + LayerAttributesKeysJavaAppServerVersion, + } +} + const ( // LayerTypeAwsFlowRuby is a LayerType enum value LayerTypeAwsFlowRuby = "aws-flow-ruby" @@ -18110,6 +18312,24 @@ const ( LayerTypeCustom = "custom" ) +// LayerType_Values returns all elements of the LayerType enum +func LayerType_Values() []string { + return []string{ + LayerTypeAwsFlowRuby, + LayerTypeEcsCluster, + LayerTypeJavaApp, + LayerTypeLb, + LayerTypeWeb, + LayerTypePhpApp, + LayerTypeRailsApp, + LayerTypeNodejsApp, + LayerTypeMemcached, + LayerTypeDbMaster, + LayerTypeMonitoringMaster, + LayerTypeCustom, + } +} + const ( // RootDeviceTypeEbs is a RootDeviceType enum value RootDeviceTypeEbs = "ebs" @@ -18118,6 +18338,14 @@ const ( RootDeviceTypeInstanceStore = "instance-store" ) +// RootDeviceType_Values returns all elements of the RootDeviceType enum +func RootDeviceType_Values() []string { + return []string{ + RootDeviceTypeEbs, + RootDeviceTypeInstanceStore, + } +} + const ( // SourceTypeGit is a SourceType enum value SourceTypeGit = "git" @@ -18132,11 +18360,28 @@ const ( SourceTypeS3 = "s3" ) +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeGit, + SourceTypeSvn, + SourceTypeArchive, + SourceTypeS3, + } +} + const ( // StackAttributesKeysColor is a StackAttributesKeys enum value StackAttributesKeysColor = "Color" ) +// StackAttributesKeys_Values returns all elements of the StackAttributesKeys enum +func StackAttributesKeys_Values() []string { + return []string{ + StackAttributesKeysColor, + } +} + const ( // VirtualizationTypeParavirtual is a VirtualizationType enum value VirtualizationTypeParavirtual = "paravirtual" @@ -18145,6 +18390,14 @@ const ( VirtualizationTypeHvm = "hvm" ) +// VirtualizationType_Values returns all elements of the VirtualizationType enum +func VirtualizationType_Values() []string { + return []string{ + VirtualizationTypeParavirtual, + VirtualizationTypeHvm, + } +} + const ( // VolumeTypeGp2 is a VolumeType enum value VolumeTypeGp2 = "gp2" @@ -18155,3 +18408,12 @@ const ( // VolumeTypeStandard is a VolumeType enum value VolumeTypeStandard = "standard" ) + +// VolumeType_Values returns all elements of the VolumeType enum +func VolumeType_Values() []string { + return []string{ + VolumeTypeGp2, + VolumeTypeIo1, + VolumeTypeStandard, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/organizations/api.go b/vendor/github.com/aws/aws-sdk-go/service/organizations/api.go index 627e054c1f2..d58292ed2f1 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/organizations/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/organizations/api.go @@ -160,7 +160,7 @@ func (c *Organizations) AcceptHandshakeRequest(input *AcceptHandshakeInput) (req // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -227,12 +227,12 @@ func (c *Organizations) AcceptHandshakeRequest(input *AcceptHandshakeInput) (req // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * AccessDeniedForDependencyException // The operation that you attempted requires you to have the iam:CreateServiceLinkedRole @@ -307,35 +307,16 @@ func (c *Organizations) AttachPolicyRequest(input *AttachPolicyInput) (req *requ // AttachPolicy API operation for AWS Organizations. // // Attaches a policy to a root, an organizational unit (OU), or an individual -// account. How the policy affects accounts depends on the type of policy: -// -// * Service control policy (SCP) - An SCP specifies what permissions can -// be delegated to users in affected member accounts. The scope of influence -// for a policy depends on what you attach the policy to: If you attach an -// SCP to a root, it affects all accounts in the organization. If you attach -// an SCP to an OU, it affects all accounts in that OU and in any child OUs. -// If you attach the policy directly to an account, it affects only that -// account. SCPs are JSON policies that specify the maximum permissions for -// an organization or organizational unit (OU). You can attach one SCP to -// a higher level root or OU, and a different SCP to a child OU or to an -// account. The child policy can further restrict only the permissions that -// pass through the parent filter and are available to the child. An SCP -// that is attached to a child can't grant a permission that the parent hasn't -// already granted. For example, imagine that the parent SCP allows permissions -// A, B, C, D, and E. The child SCP allows C, D, E, F, and G. The result -// is that the accounts affected by the child SCP are allowed to use only -// C, D, and E. They can't use A or B because the child OU filtered them -// out. They also can't use F and G because the parent OU filtered them out. -// They can't be granted back by the child SCP; child SCPs can only filter -// the permissions they receive from the parent SCP. AWS Organizations attaches -// a default SCP named "FullAWSAccess to every root, OU, and account. This -// default SCP allows all services and actions, enabling any new child OU -// or account to inherit the permissions of the parent root or OU. If you -// detach the default policy, you must replace it with a policy that specifies -// the permissions that you want to allow in that OU or account. For more -// information about how AWS Organizations policies permissions work, see -// Using Service Control Policies (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scp.html) -// in the AWS Organizations User Guide. +// account. How the policy affects accounts depends on the type of policy. Refer +// to the AWS Organizations User Guide for information about each policy type: +// +// * AISERVICES_OPT_OUT_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html) +// +// * BACKUP_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_backup.html) +// +// * SERVICE_CONTROL_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scp.html) +// +// * TAG_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) // // This operation can be called only from the organization's master account. // @@ -368,23 +349,27 @@ func (c *Organizations) AttachPolicyRequest(input *AttachPolicyInput) (req *requ // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -397,19 +382,32 @@ func (c *Organizations) AttachPolicyRequest(input *AttachPolicyInput) (req *requ // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. +// +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -421,8 +419,12 @@ func (c *Organizations) AttachPolicyRequest(input *AttachPolicyInput) (req *requ // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -459,20 +461,27 @@ func (c *Organizations) AttachPolicyRequest(input *AttachPolicyInput) (req *requ // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * DuplicatePolicyAttachmentException // The selected policy is already attached to the specified target. // @@ -482,7 +491,7 @@ func (c *Organizations) AttachPolicyRequest(input *AttachPolicyInput) (req *requ // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -558,15 +567,15 @@ func (c *Organizations) AttachPolicyRequest(input *AttachPolicyInput) (req *requ // We can't find a root, OU, or account with the TargetId that you specified. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // * PolicyChangesInProgressException // Changes to the effective policy are in progress, and its contents can't be @@ -685,7 +694,7 @@ func (c *Organizations) CancelHandshakeRequest(input *CancelHandshakeInput) (req // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -748,12 +757,12 @@ func (c *Organizations) CancelHandshakeRequest(input *CancelHandshakeInput) (req // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/CancelHandshake func (c *Organizations) CancelHandshake(input *CancelHandshakeInput) (*CancelHandshakeOutput, error) { @@ -915,23 +924,27 @@ func (c *Organizations) CreateAccountRequest(input *CreateAccountInput) (req *re // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -944,19 +957,32 @@ func (c *Organizations) CreateAccountRequest(input *CreateAccountInput) (req *re // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. +// +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -968,8 +994,12 @@ func (c *Organizations) CreateAccountRequest(input *CreateAccountInput) (req *re // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -1006,27 +1036,34 @@ func (c *Organizations) CreateAccountRequest(input *CreateAccountInput) (req *re // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -1095,15 +1132,15 @@ func (c *Organizations) CreateAccountRequest(input *CreateAccountInput) (req *re // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/CreateAccount func (c *Organizations) CreateAccount(input *CreateAccountInput) (*CreateAccountOutput, error) { @@ -1243,8 +1280,8 @@ func (c *Organizations) CreateGovCloudAccountRequest(input *CreateGovCloudAccoun // // * When you create an account in an organization using the AWS Organizations // console, API, or CLI commands, the information required for the account -// to operate as a standalone account, such as a payment method and signing -// the end user license agreement (EULA) is not automatically collected. +// to operate as a standalone account is not automatically collected. This +// includes a payment method and signing the end user license agreement (EULA). // If you must remove an account from your organization later, you can do // so only after you provide the missing information. Follow the steps at // To leave an organization as a member account (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) @@ -1301,23 +1338,27 @@ func (c *Organizations) CreateGovCloudAccountRequest(input *CreateGovCloudAccoun // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -1330,19 +1371,32 @@ func (c *Organizations) CreateGovCloudAccountRequest(input *CreateGovCloudAccoun // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. +// +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -1354,8 +1408,12 @@ func (c *Organizations) CreateGovCloudAccountRequest(input *CreateGovCloudAccoun // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -1392,27 +1450,34 @@ func (c *Organizations) CreateGovCloudAccountRequest(input *CreateGovCloudAccoun // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -1481,15 +1546,15 @@ func (c *Organizations) CreateGovCloudAccountRequest(input *CreateGovCloudAccoun // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/CreateGovCloudAccount func (c *Organizations) CreateGovCloudAccount(input *CreateGovCloudAccountInput) (*CreateGovCloudAccountOutput, error) { @@ -1601,23 +1666,27 @@ func (c *Organizations) CreateOrganizationRequest(input *CreateOrganizationInput // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -1630,19 +1699,32 @@ func (c *Organizations) CreateOrganizationRequest(input *CreateOrganizationInput // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -1654,8 +1736,12 @@ func (c *Organizations) CreateOrganizationRequest(input *CreateOrganizationInput // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -1692,27 +1778,34 @@ func (c *Organizations) CreateOrganizationRequest(input *CreateOrganizationInput // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -1775,12 +1868,12 @@ func (c *Organizations) CreateOrganizationRequest(input *CreateOrganizationInput // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * AccessDeniedForDependencyException // The operation that you attempted requires you to have the iam:CreateServiceLinkedRole @@ -1893,23 +1986,27 @@ func (c *Organizations) CreateOrganizationalUnitRequest(input *CreateOrganizatio // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -1922,19 +2019,32 @@ func (c *Organizations) CreateOrganizationalUnitRequest(input *CreateOrganizatio // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -1946,8 +2056,12 @@ func (c *Organizations) CreateOrganizationalUnitRequest(input *CreateOrganizatio // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -1984,20 +2098,27 @@ func (c *Organizations) CreateOrganizationalUnitRequest(input *CreateOrganizatio // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * DuplicateOrganizationalUnitException // An OU with the same name already exists. // @@ -2007,7 +2128,7 @@ func (c *Organizations) CreateOrganizationalUnitRequest(input *CreateOrganizatio // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -2073,12 +2194,12 @@ func (c *Organizations) CreateOrganizationalUnitRequest(input *CreateOrganizatio // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/CreateOrganizationalUnit func (c *Organizations) CreateOrganizationalUnit(input *CreateOrganizationalUnitInput) (*CreateOrganizationalUnitOutput, error) { @@ -2183,23 +2304,27 @@ func (c *Organizations) CreatePolicyRequest(input *CreatePolicyInput) (req *requ // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -2212,19 +2337,32 @@ func (c *Organizations) CreatePolicyRequest(input *CreatePolicyInput) (req *requ // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -2236,8 +2374,12 @@ func (c *Organizations) CreatePolicyRequest(input *CreatePolicyInput) (req *requ // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -2274,20 +2416,27 @@ func (c *Organizations) CreatePolicyRequest(input *CreatePolicyInput) (req *requ // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * DuplicatePolicyException // A policy with the same name already exists. // @@ -2297,7 +2446,7 @@ func (c *Organizations) CreatePolicyRequest(input *CreatePolicyInput) (req *requ // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -2364,24 +2513,24 @@ func (c *Organizations) CreatePolicyRequest(input *CreatePolicyInput) (req *requ // * PolicyTypeNotAvailableForOrganizationException // You can't use the specified policy type with the feature set currently enabled // for this organization. For example, you can enable SCPs only after you enable -// all features in the organization. For more information, see Enabling and -// Disabling a Policy Type on a Root (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html#enable_policies_on_root) -// in the AWS Organizations User Guide. +// all features in the organization. For more information, see Managing AWS +// Organizations Policies (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html#enable_policies_on_root)in +// the AWS Organizations User Guide. // // * ServiceException // AWS Organizations can't complete your request because of an internal service // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/CreatePolicy func (c *Organizations) CreatePolicy(input *CreatePolicyInput) (*CreatePolicyOutput, error) { @@ -2497,7 +2646,7 @@ func (c *Organizations) DeclineHandshakeRequest(input *DeclineHandshakeInput) (r // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -2560,12 +2709,12 @@ func (c *Organizations) DeclineHandshakeRequest(input *DeclineHandshakeInput) (r // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DeclineHandshake func (c *Organizations) DeclineHandshake(input *DeclineHandshakeInput) (*DeclineHandshakeOutput, error) { @@ -2666,7 +2815,7 @@ func (c *Organizations) DeleteOrganizationRequest(input *DeleteOrganizationInput // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -2733,12 +2882,12 @@ func (c *Organizations) DeleteOrganizationRequest(input *DeleteOrganizationInput // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DeleteOrganization func (c *Organizations) DeleteOrganization(input *DeleteOrganizationInput) (*DeleteOrganizationOutput, error) { @@ -2841,7 +2990,7 @@ func (c *Organizations) DeleteOrganizationalUnitRequest(input *DeleteOrganizatio // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -2911,12 +3060,12 @@ func (c *Organizations) DeleteOrganizationalUnitRequest(input *DeleteOrganizatio // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DeleteOrganizationalUnit func (c *Organizations) DeleteOrganizationalUnit(input *DeleteOrganizationalUnitInput) (*DeleteOrganizationalUnitOutput, error) { @@ -3020,7 +3169,7 @@ func (c *Organizations) DeletePolicyRequest(input *DeletePolicyInput) (req *requ // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -3090,15 +3239,15 @@ func (c *Organizations) DeletePolicyRequest(input *DeletePolicyInput) (req *requ // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DeletePolicy func (c *Organizations) DeletePolicy(input *DeletePolicyInput) (*DeletePolicyOutput, error) { @@ -3170,6 +3319,11 @@ func (c *Organizations) DeregisterDelegatedAdministratorRequest(input *Deregiste // Removes the specified member AWS account as a delegated administrator for // the specified AWS service. // +// Deregistering a delegated administrator can have unintended impacts on the +// functionality of the enabled AWS service. See the documentation for the enabled +// service before you deregister a delegated administrator so that you understand +// any potential impacts. +// // You can run this action only for AWS services that support this feature. // For a current list of services that support it, see the column Supports Delegated // Administrator in the table at AWS Services that you can use with AWS Organizations @@ -3215,23 +3369,27 @@ func (c *Organizations) DeregisterDelegatedAdministratorRequest(input *Deregiste // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -3244,19 +3402,32 @@ func (c *Organizations) DeregisterDelegatedAdministratorRequest(input *Deregiste // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. +// +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -3268,8 +3439,12 @@ func (c *Organizations) DeregisterDelegatedAdministratorRequest(input *Deregiste // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -3306,27 +3481,34 @@ func (c *Organizations) DeregisterDelegatedAdministratorRequest(input *Deregiste // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -3385,19 +3567,19 @@ func (c *Organizations) DeregisterDelegatedAdministratorRequest(input *Deregiste // between entities in the same root. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * ServiceException // AWS Organizations can't complete your request because of an internal service // error. Try again later. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DeregisterDelegatedAdministrator func (c *Organizations) DeregisterDelegatedAdministrator(input *DeregisterDelegatedAdministratorInput) (*DeregisterDelegatedAdministratorOutput, error) { @@ -3500,7 +3682,7 @@ func (c *Organizations) DescribeAccountRequest(input *DescribeAccountInput) (req // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -3563,12 +3745,12 @@ func (c *Organizations) DescribeAccountRequest(input *DescribeAccountInput) (req // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DescribeAccount func (c *Organizations) DescribeAccount(input *DescribeAccountInput) (*DescribeAccountOutput, error) { @@ -3670,7 +3852,7 @@ func (c *Organizations) DescribeCreateAccountStatusRequest(input *DescribeCreate // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -3733,15 +3915,15 @@ func (c *Organizations) DescribeCreateAccountStatusRequest(input *DescribeCreate // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DescribeCreateAccountStatus func (c *Organizations) DescribeCreateAccountStatus(input *DescribeCreateAccountStatusInput) (*DescribeCreateAccountStatusOutput, error) { @@ -3809,14 +3991,16 @@ func (c *Organizations) DescribeEffectivePolicyRequest(input *DescribeEffectiveP // DescribeEffectivePolicy API operation for AWS Organizations. // -// Returns the contents of the effective tag policy for the account. The effective -// tag policy is the aggregation of any tag policies the account inherits, plus -// any policy directly that is attached to the account. +// Returns the contents of the effective policy for specified policy type and +// account. The effective policy is the aggregation of any policies of the specified +// type that the account inherits, plus any policy of that type that is directly +// attached to the account. // -// This action returns information on tag policies only. +// This operation applies only to policy types other than service control policies +// (SCPs). // -// For more information on policy inheritance, see How Policy Inheritance Works -// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies-inheritance.html) +// For more information about policy inheritance, see How Policy Inheritance +// Works (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies-inheritance.html) // in the AWS Organizations User Guide. // // This operation can be called only from the organization's master account @@ -3847,23 +4031,27 @@ func (c *Organizations) DescribeEffectivePolicyRequest(input *DescribeEffectiveP // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -3876,19 +4064,32 @@ func (c *Organizations) DescribeEffectivePolicyRequest(input *DescribeEffectiveP // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. +// +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -3900,8 +4101,12 @@ func (c *Organizations) DescribeEffectivePolicyRequest(input *DescribeEffectiveP // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -3938,31 +4143,38 @@ func (c *Organizations) DescribeEffectivePolicyRequest(input *DescribeEffectiveP // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * ServiceException // AWS Organizations can't complete your request because of an internal service // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * TargetNotFoundException // We can't find a root, OU, or account with the TargetId that you specified. @@ -3979,7 +4191,7 @@ func (c *Organizations) DescribeEffectivePolicyRequest(input *DescribeEffectiveP // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -4038,7 +4250,7 @@ func (c *Organizations) DescribeEffectivePolicyRequest(input *DescribeEffectiveP // between entities in the same root. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DescribeEffectivePolicy func (c *Organizations) DescribeEffectivePolicy(input *DescribeEffectivePolicyInput) (*DescribeEffectivePolicyOutput, error) { @@ -4144,7 +4356,7 @@ func (c *Organizations) DescribeHandshakeRequest(input *DescribeHandshakeInput) // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -4207,12 +4419,12 @@ func (c *Organizations) DescribeHandshakeRequest(input *DescribeHandshakeInput) // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DescribeHandshake func (c *Organizations) DescribeHandshake(input *DescribeHandshakeInput) (*DescribeHandshakeOutput, error) { @@ -4317,12 +4529,12 @@ func (c *Organizations) DescribeOrganizationRequest(input *DescribeOrganizationI // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DescribeOrganization func (c *Organizations) DescribeOrganization(input *DescribeOrganizationInput) (*DescribeOrganizationOutput, error) { @@ -4420,7 +4632,7 @@ func (c *Organizations) DescribeOrganizationalUnitRequest(input *DescribeOrganiz // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -4486,12 +4698,12 @@ func (c *Organizations) DescribeOrganizationalUnitRequest(input *DescribeOrganiz // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DescribeOrganizationalUnit func (c *Organizations) DescribeOrganizationalUnit(input *DescribeOrganizationalUnitInput) (*DescribeOrganizationalUnitOutput, error) { @@ -4589,7 +4801,7 @@ func (c *Organizations) DescribePolicyRequest(input *DescribePolicyInput) (req * // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -4655,15 +4867,15 @@ func (c *Organizations) DescribePolicyRequest(input *DescribePolicyInput) (req * // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DescribePolicy func (c *Organizations) DescribePolicy(input *DescribePolicyInput) (*DescribePolicyOutput, error) { @@ -4733,18 +4945,20 @@ func (c *Organizations) DetachPolicyRequest(input *DetachPolicyInput) (req *requ // DetachPolicy API operation for AWS Organizations. // // Detaches a policy from a target root, organizational unit (OU), or account. -// If the policy being detached is a service control policy (SCP), the changes -// to permissions for IAM users and roles in affected accounts are immediate. // -// Note: Every root, OU, and account must have at least one SCP attached. If -// you want to replace the default FullAWSAccess policy with one that limits -// the permissions that can be delegated, you must attach the replacement policy -// before you can remove the default one. This is the authorization strategy -// of an "allow list (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_about-scps.html#orgs_policies_whitelist)". +// If the policy being detached is a service control policy (SCP), the changes +// to permissions for AWS Identity and Access Management (IAM) users and roles +// in affected accounts are immediate. +// +// Every root, OU, and account must have at least one SCP attached. If you want +// to replace the default FullAWSAccess policy with an SCP that limits the permissions +// that can be delegated, you must attach the replacement SCP before you can +// remove the default SCP. This is the authorization strategy of an "allow list +// (https://docs.aws.amazon.com/organizations/latest/userguide/SCP_strategies.html#orgs_policies_allowlist)". // If you instead attach a second SCP and leave the FullAWSAccess SCP still // attached, and specify "Effect": "Deny" in the second SCP to override the // "Effect": "Allow" in the FullAWSAccess policy (or any other attached SCP), -// you're using the authorization strategy of a "deny list (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_about-scps.html#orgs_policies_blacklist)". +// you're using the authorization strategy of a "deny list (https://docs.aws.amazon.com/organizations/latest/userguide/SCP_strategies.html#orgs_policies_denylist)". // // This operation can be called only from the organization's master account. // @@ -4777,23 +4991,27 @@ func (c *Organizations) DetachPolicyRequest(input *DetachPolicyInput) (req *requ // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -4806,19 +5024,32 @@ func (c *Organizations) DetachPolicyRequest(input *DetachPolicyInput) (req *requ // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. +// +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -4830,8 +5061,12 @@ func (c *Organizations) DetachPolicyRequest(input *DetachPolicyInput) (req *requ // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -4868,27 +5103,34 @@ func (c *Organizations) DetachPolicyRequest(input *DetachPolicyInput) (req *requ // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -4960,15 +5202,15 @@ func (c *Organizations) DetachPolicyRequest(input *DetachPolicyInput) (req *requ // We can't find a root, OU, or account with the TargetId that you specified. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // * PolicyChangesInProgressException // Changes to the effective policy are in progress, and its contents can't be @@ -5098,23 +5340,27 @@ func (c *Organizations) DisableAWSServiceAccessRequest(input *DisableAWSServiceA // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -5127,19 +5373,32 @@ func (c *Organizations) DisableAWSServiceAccessRequest(input *DisableAWSServiceA // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. +// +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -5151,8 +5410,12 @@ func (c *Organizations) DisableAWSServiceAccessRequest(input *DisableAWSServiceA // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -5189,27 +5452,34 @@ func (c *Organizations) DisableAWSServiceAccessRequest(input *DisableAWSServiceA // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -5272,12 +5542,15 @@ func (c *Organizations) DisableAWSServiceAccessRequest(input *DisableAWSServiceA // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. +// +// * UnsupportedAPIEndpointException +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/DisableAWSServiceAccess func (c *Organizations) DisableAWSServiceAccess(input *DisableAWSServiceAccessInput) (*DisableAWSServiceAccessOutput, error) { @@ -5345,14 +5618,14 @@ func (c *Organizations) DisablePolicyTypeRequest(input *DisablePolicyTypeInput) // DisablePolicyType API operation for AWS Organizations. // -// Disables an organizational control policy type in a root. A policy of a certain -// type can be attached to entities in a root only if that type is enabled in -// the root. After you perform this operation, you no longer can attach policies +// Disables an organizational policy type in a root. A policy of a certain type +// can be attached to entities in a root only if that type is enabled in the +// root. After you perform this operation, you no longer can attach policies // of the specified type to that root or to any organizational unit (OU) or // account in that root. You can undo this by using the EnablePolicyType operation. // // This is an asynchronous request that AWS performs in the background. If you -// disable a policy for a root, it still appears enabled for the organization +// disable a policy type for a root, it still appears enabled for the organization // if all features (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html) // are enabled for the organization. AWS recommends that you first use ListRoots // to see the status of policy types for a specified root, and then use this @@ -5391,23 +5664,27 @@ func (c *Organizations) DisablePolicyTypeRequest(input *DisablePolicyTypeInput) // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -5420,19 +5697,32 @@ func (c *Organizations) DisablePolicyTypeRequest(input *DisablePolicyTypeInput) // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. +// +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -5444,8 +5734,12 @@ func (c *Organizations) DisablePolicyTypeRequest(input *DisablePolicyTypeInput) // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -5482,27 +5776,34 @@ func (c *Organizations) DisablePolicyTypeRequest(input *DisablePolicyTypeInput) // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -5575,15 +5876,15 @@ func (c *Organizations) DisablePolicyTypeRequest(input *DisablePolicyTypeInput) // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // * PolicyChangesInProgressException // Changes to the effective policy are in progress, and its contents can't be @@ -5706,23 +6007,27 @@ func (c *Organizations) EnableAWSServiceAccessRequest(input *EnableAWSServiceAcc // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -5735,19 +6040,32 @@ func (c *Organizations) EnableAWSServiceAccessRequest(input *EnableAWSServiceAcc // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -5759,8 +6077,12 @@ func (c *Organizations) EnableAWSServiceAccessRequest(input *EnableAWSServiceAcc // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -5797,27 +6119,34 @@ func (c *Organizations) EnableAWSServiceAccessRequest(input *EnableAWSServiceAcc // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -5880,12 +6209,15 @@ func (c *Organizations) EnableAWSServiceAccessRequest(input *EnableAWSServiceAcc // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. +// +// * UnsupportedAPIEndpointException +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/EnableAWSServiceAccess func (c *Organizations) EnableAWSServiceAccess(input *EnableAWSServiceAccessInput) (*EnableAWSServiceAccessOutput, error) { @@ -6053,7 +6385,7 @@ func (c *Organizations) EnableAllFeaturesRequest(input *EnableAllFeaturesInput) // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -6116,12 +6448,12 @@ func (c *Organizations) EnableAllFeaturesRequest(input *EnableAllFeaturesInput) // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/EnableAllFeatures func (c *Organizations) EnableAllFeatures(input *EnableAllFeaturesInput) (*EnableAllFeaturesOutput, error) { @@ -6233,23 +6565,27 @@ func (c *Organizations) EnablePolicyTypeRequest(input *EnablePolicyTypeInput) (r // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -6262,19 +6598,32 @@ func (c *Organizations) EnablePolicyTypeRequest(input *EnablePolicyTypeInput) (r // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. +// +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -6286,8 +6635,12 @@ func (c *Organizations) EnablePolicyTypeRequest(input *EnablePolicyTypeInput) (r // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -6324,27 +6677,34 @@ func (c *Organizations) EnablePolicyTypeRequest(input *EnablePolicyTypeInput) (r // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -6413,22 +6773,22 @@ func (c *Organizations) EnablePolicyTypeRequest(input *EnablePolicyTypeInput) (r // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * PolicyTypeNotAvailableForOrganizationException // You can't use the specified policy type with the feature set currently enabled // for this organization. For example, you can enable SCPs only after you enable -// all features in the organization. For more information, see Enabling and -// Disabling a Policy Type on a Root (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html#enable_policies_on_root) -// in the AWS Organizations User Guide. +// all features in the organization. For more information, see Managing AWS +// Organizations Policies (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html#enable_policies_on_root)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // * PolicyChangesInProgressException // Changes to the effective policy are in progress, and its contents can't be @@ -6601,7 +6961,7 @@ func (c *Organizations) InviteAccountToOrganizationRequest(input *InviteAccountT // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -6670,12 +7030,12 @@ func (c *Organizations) InviteAccountToOrganizationRequest(input *InviteAccountT // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/InviteAccountToOrganization func (c *Organizations) InviteAccountToOrganization(input *InviteAccountToOrganizationInput) (*InviteAccountToOrganizationOutput, error) { @@ -6809,23 +7169,27 @@ func (c *Organizations) LeaveOrganizationRequest(input *LeaveOrganizationInput) // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -6838,19 +7202,32 @@ func (c *Organizations) LeaveOrganizationRequest(input *LeaveOrganizationInput) // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -6862,8 +7239,12 @@ func (c *Organizations) LeaveOrganizationRequest(input *LeaveOrganizationInput) // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -6900,27 +7281,34 @@ func (c *Organizations) LeaveOrganizationRequest(input *LeaveOrganizationInput) // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -6988,12 +7376,12 @@ func (c *Organizations) LeaveOrganizationRequest(input *LeaveOrganizationInput) // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/LeaveOrganization func (c *Organizations) LeaveOrganization(input *LeaveOrganizationInput) (*LeaveOrganizationOutput, error) { @@ -7105,23 +7493,27 @@ func (c *Organizations) ListAWSServiceAccessForOrganizationRequest(input *ListAW // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -7134,19 +7526,32 @@ func (c *Organizations) ListAWSServiceAccessForOrganizationRequest(input *ListAW // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. +// +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -7158,8 +7563,12 @@ func (c *Organizations) ListAWSServiceAccessForOrganizationRequest(input *ListAW // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -7196,27 +7605,34 @@ func (c *Organizations) ListAWSServiceAccessForOrganizationRequest(input *ListAW // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -7279,12 +7695,15 @@ func (c *Organizations) ListAWSServiceAccessForOrganizationRequest(input *ListAW // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. +// +// * UnsupportedAPIEndpointException +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListAWSServiceAccessForOrganization func (c *Organizations) ListAWSServiceAccessForOrganization(input *ListAWSServiceAccessForOrganizationInput) (*ListAWSServiceAccessForOrganizationOutput, error) { @@ -7447,7 +7866,7 @@ func (c *Organizations) ListAccountsRequest(input *ListAccountsInput) (req *requ // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -7510,12 +7929,12 @@ func (c *Organizations) ListAccountsRequest(input *ListAccountsInput) (req *requ // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListAccounts func (c *Organizations) ListAccounts(input *ListAccountsInput) (*ListAccountsOutput, error) { @@ -7680,7 +8099,7 @@ func (c *Organizations) ListAccountsForParentRequest(input *ListAccountsForParen // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -7746,12 +8165,12 @@ func (c *Organizations) ListAccountsForParentRequest(input *ListAccountsForParen // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListAccountsForParent func (c *Organizations) ListAccountsForParent(input *ListAccountsForParentInput) (*ListAccountsForParentOutput, error) { @@ -7914,7 +8333,7 @@ func (c *Organizations) ListChildrenRequest(input *ListChildrenInput) (req *requ // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -7980,12 +8399,12 @@ func (c *Organizations) ListChildrenRequest(input *ListChildrenInput) (req *requ // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListChildren func (c *Organizations) ListChildren(input *ListChildrenInput) (*ListChildrenOutput, error) { @@ -8147,7 +8566,7 @@ func (c *Organizations) ListCreateAccountStatusRequest(input *ListCreateAccountS // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -8210,15 +8629,15 @@ func (c *Organizations) ListCreateAccountStatusRequest(input *ListCreateAccountS // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListCreateAccountStatus func (c *Organizations) ListCreateAccountStatus(input *ListCreateAccountStatusInput) (*ListCreateAccountStatusOutput, error) { @@ -8375,23 +8794,27 @@ func (c *Organizations) ListDelegatedAdministratorsRequest(input *ListDelegatedA // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -8404,19 +8827,32 @@ func (c *Organizations) ListDelegatedAdministratorsRequest(input *ListDelegatedA // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. +// +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -8428,8 +8864,12 @@ func (c *Organizations) ListDelegatedAdministratorsRequest(input *ListDelegatedA // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -8466,27 +8906,34 @@ func (c *Organizations) ListDelegatedAdministratorsRequest(input *ListDelegatedA // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -8545,19 +8992,19 @@ func (c *Organizations) ListDelegatedAdministratorsRequest(input *ListDelegatedA // between entities in the same root. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * ServiceException // AWS Organizations can't complete your request because of an internal service // error. Try again later. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListDelegatedAdministrators func (c *Organizations) ListDelegatedAdministrators(input *ListDelegatedAdministratorsInput) (*ListDelegatedAdministratorsOutput, error) { @@ -8721,23 +9168,27 @@ func (c *Organizations) ListDelegatedServicesForAccountRequest(input *ListDelega // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -8750,19 +9201,32 @@ func (c *Organizations) ListDelegatedServicesForAccountRequest(input *ListDelega // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. +// +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -8774,8 +9238,12 @@ func (c *Organizations) ListDelegatedServicesForAccountRequest(input *ListDelega // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -8812,27 +9280,34 @@ func (c *Organizations) ListDelegatedServicesForAccountRequest(input *ListDelega // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -8891,19 +9366,19 @@ func (c *Organizations) ListDelegatedServicesForAccountRequest(input *ListDelega // between entities in the same root. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * ServiceException // AWS Organizations can't complete your request because of an internal service // error. Try again later. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListDelegatedServicesForAccount func (c *Organizations) ListDelegatedServicesForAccount(input *ListDelegatedServicesForAccountInput) (*ListDelegatedServicesForAccountOutput, error) { @@ -9041,8 +9516,7 @@ func (c *Organizations) ListHandshakesForAccountRequest(input *ListHandshakesFor // of results even when there are more results available. The NextToken response // parameter value is null only when there are no more results to display. // -// This operation can be called only from the organization's master account -// or by a member account that is a delegated administrator for an AWS service. +// This operation can be called from any account in the organization. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -9069,7 +9543,7 @@ func (c *Organizations) ListHandshakesForAccountRequest(input *ListHandshakesFor // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -9132,12 +9606,12 @@ func (c *Organizations) ListHandshakesForAccountRequest(input *ListHandshakesFor // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListHandshakesForAccount func (c *Organizations) ListHandshakesForAccount(input *ListHandshakesForAccountInput) (*ListHandshakesForAccountOutput, error) { @@ -9309,7 +9783,7 @@ func (c *Organizations) ListHandshakesForOrganizationRequest(input *ListHandshak // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -9372,12 +9846,12 @@ func (c *Organizations) ListHandshakesForOrganizationRequest(input *ListHandshak // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListHandshakesForOrganization func (c *Organizations) ListHandshakesForOrganization(input *ListHandshakesForOrganizationInput) (*ListHandshakesForOrganizationOutput, error) { @@ -9538,7 +10012,7 @@ func (c *Organizations) ListOrganizationalUnitsForParentRequest(input *ListOrgan // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -9604,12 +10078,12 @@ func (c *Organizations) ListOrganizationalUnitsForParentRequest(input *ListOrgan // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListOrganizationalUnitsForParent func (c *Organizations) ListOrganizationalUnitsForParent(input *ListOrganizationalUnitsForParentInput) (*ListOrganizationalUnitsForParentOutput, error) { @@ -9778,7 +10252,7 @@ func (c *Organizations) ListParentsRequest(input *ListParentsInput) (req *reques // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -9841,12 +10315,12 @@ func (c *Organizations) ListParentsRequest(input *ListParentsInput) (req *reques // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListParents func (c *Organizations) ListParents(input *ListParentsInput) (*ListParentsOutput, error) { @@ -10007,7 +10481,7 @@ func (c *Organizations) ListPoliciesRequest(input *ListPoliciesInput) (req *requ // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -10070,15 +10544,15 @@ func (c *Organizations) ListPoliciesRequest(input *ListPoliciesInput) (req *requ // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListPolicies func (c *Organizations) ListPolicies(input *ListPoliciesInput) (*ListPoliciesOutput, error) { @@ -10241,7 +10715,7 @@ func (c *Organizations) ListPoliciesForTargetRequest(input *ListPoliciesForTarge // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -10307,15 +10781,15 @@ func (c *Organizations) ListPoliciesForTargetRequest(input *ListPoliciesForTarge // We can't find a root, OU, or account with the TargetId that you specified. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListPoliciesForTarget func (c *Organizations) ListPoliciesForTarget(input *ListPoliciesForTargetInput) (*ListPoliciesForTargetOutput, error) { @@ -10482,7 +10956,7 @@ func (c *Organizations) ListRootsRequest(input *ListRootsInput) (req *request.Re // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -10545,12 +11019,12 @@ func (c *Organizations) ListRootsRequest(input *ListRootsInput) (req *request.Re // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListRoots func (c *Organizations) ListRoots(input *ListRootsInput) (*ListRootsOutput, error) { @@ -10711,7 +11185,7 @@ func (c *Organizations) ListTagsForResourceRequest(input *ListTagsForResourceInp // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -10774,12 +11248,12 @@ func (c *Organizations) ListTagsForResourceRequest(input *ListTagsForResourceInp // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListTagsForResource func (c *Organizations) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { @@ -10941,7 +11415,7 @@ func (c *Organizations) ListTargetsForPolicyRequest(input *ListTargetsForPolicyI // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -11007,15 +11481,15 @@ func (c *Organizations) ListTargetsForPolicyRequest(input *ListTargetsForPolicyI // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/ListTargetsForPolicy func (c *Organizations) ListTargetsForPolicy(input *ListTargetsForPolicyInput) (*ListTargetsForPolicyOutput, error) { @@ -11162,7 +11636,7 @@ func (c *Organizations) MoveAccountRequest(input *MoveAccountInput) (req *reques // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -11236,12 +11710,12 @@ func (c *Organizations) MoveAccountRequest(input *MoveAccountInput) (req *reques // an organization. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * ConcurrentModificationException // The target of the operation is currently being modified by a different request. @@ -11372,23 +11846,27 @@ func (c *Organizations) RegisterDelegatedAdministratorRequest(input *RegisterDel // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -11401,19 +11879,32 @@ func (c *Organizations) RegisterDelegatedAdministratorRequest(input *RegisterDel // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -11425,8 +11916,12 @@ func (c *Organizations) RegisterDelegatedAdministratorRequest(input *RegisterDel // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -11463,27 +11958,34 @@ func (c *Organizations) RegisterDelegatedAdministratorRequest(input *RegisterDel // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -11542,19 +12044,19 @@ func (c *Organizations) RegisterDelegatedAdministratorRequest(input *RegisterDel // between entities in the same root. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * ServiceException // AWS Organizations can't complete your request because of an internal service // error. Try again later. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/RegisterDelegatedAdministrator func (c *Organizations) RegisterDelegatedAdministrator(input *RegisterDelegatedAdministratorInput) (*RegisterDelegatedAdministratorOutput, error) { @@ -11683,23 +12185,27 @@ func (c *Organizations) RemoveAccountFromOrganizationRequest(input *RemoveAccoun // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -11712,19 +12218,32 @@ func (c *Organizations) RemoveAccountFromOrganizationRequest(input *RemoveAccoun // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -11736,8 +12255,12 @@ func (c *Organizations) RemoveAccountFromOrganizationRequest(input *RemoveAccoun // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -11774,27 +12297,34 @@ func (c *Organizations) RemoveAccountFromOrganizationRequest(input *RemoveAccoun // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -11862,12 +12392,12 @@ func (c *Organizations) RemoveAccountFromOrganizationRequest(input *RemoveAccoun // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/RemoveAccountFromOrganization func (c *Organizations) RemoveAccountFromOrganization(input *RemoveAccountFromOrganizationInput) (*RemoveAccountFromOrganizationOutput, error) { @@ -11974,23 +12504,27 @@ func (c *Organizations) TagResourceRequest(input *TagResourceInput) (req *reques // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -12003,19 +12537,32 @@ func (c *Organizations) TagResourceRequest(input *TagResourceInput) (req *reques // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -12027,8 +12574,12 @@ func (c *Organizations) TagResourceRequest(input *TagResourceInput) (req *reques // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -12065,27 +12616,34 @@ func (c *Organizations) TagResourceRequest(input *TagResourceInput) (req *reques // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -12148,12 +12706,12 @@ func (c *Organizations) TagResourceRequest(input *TagResourceInput) (req *reques // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/TagResource func (c *Organizations) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { @@ -12260,23 +12818,27 @@ func (c *Organizations) UntagResourceRequest(input *UntagResourceInput) (req *re // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -12289,19 +12851,32 @@ func (c *Organizations) UntagResourceRequest(input *UntagResourceInput) (req *re // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -12313,8 +12888,12 @@ func (c *Organizations) UntagResourceRequest(input *UntagResourceInput) (req *re // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -12351,27 +12930,34 @@ func (c *Organizations) UntagResourceRequest(input *UntagResourceInput) (req *re // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * InvalidInputException // The requested operation failed because you provided invalid values for one // or more of the request parameters. This exception includes a reason that // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -12434,12 +13020,12 @@ func (c *Organizations) UntagResourceRequest(input *UntagResourceInput) (req *re // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/UntagResource func (c *Organizations) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { @@ -12545,7 +13131,7 @@ func (c *Organizations) UpdateOrganizationalUnitRequest(input *UpdateOrganizatio // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -12611,12 +13197,12 @@ func (c *Organizations) UpdateOrganizationalUnitRequest(input *UpdateOrganizatio // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/organizations-2016-11-28/UpdateOrganizationalUnit func (c *Organizations) UpdateOrganizationalUnit(input *UpdateOrganizationalUnitInput) (*UpdateOrganizationalUnitOutput, error) { @@ -12719,23 +13305,27 @@ func (c *Organizations) UpdatePolicyRequest(input *UpdatePolicyInput) (req *requ // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -12748,19 +13338,32 @@ func (c *Organizations) UpdatePolicyRequest(input *UpdatePolicyInput) (req *requ // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -12772,8 +13375,12 @@ func (c *Organizations) UpdatePolicyRequest(input *UpdatePolicyInput) (req *requ // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -12810,20 +13417,27 @@ func (c *Organizations) UpdatePolicyRequest(input *UpdatePolicyInput) (req *requ // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. // +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. +// // * DuplicatePolicyException // A policy with the same name already exists. // @@ -12833,7 +13447,7 @@ func (c *Organizations) UpdatePolicyRequest(input *UpdatePolicyInput) (req *requ // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -12905,15 +13519,15 @@ func (c *Organizations) UpdatePolicyRequest(input *UpdatePolicyInput) (req *requ // error. Try again later. // // * TooManyRequestsException -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. // // * UnsupportedAPIEndpointException -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. // // * PolicyChangesInProgressException // Changes to the effective policy are in progress, and its contents can't be @@ -13873,23 +14487,27 @@ func (s *ConcurrentModificationException) RequestID() string { // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated -// limit. +// limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. +// +// * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master +// account from the organization. You can't remove the master account. Instead, +// after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the -// AWS Customer Agreement. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) -// in the AWS Organizations User Guide. +// AWS Customer Agreement. Follow the steps at Removing a member account +// from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in +// the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete -// phone verification. Follow the steps at To leave an organization when -// all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) +// phone verification. Follow the steps at Removing a member account from +// your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -13902,19 +14520,32 @@ func (s *ConcurrentModificationException) RequestID() string { // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still -// count toward your limit. If you get receive this exception when running -// a command immediately after creating the organization, wait one hour and -// try again. If after an hour it continues to fail with this error, contact +// count toward your limit. If you get this exception when running a command +// immediately after creating the organization, wait one hour and try again. +// After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // -// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate -// only a member account as a delegated administrator. +// * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to +// register the master account of the organization as a delegated administrator +// for an AWS service integrated with Organizations. You can designate only +// a member account as a delegated administrator. +// +// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove +// an account that is registered as a delegated administrator for a service +// integrated with your organization. To complete this operation, you must +// first deregister this account as a delegated administrator. // -// * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, -// you must first deregister this account as a delegated administrator. +// * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an +// organization in the specified region, you must enable all features mode. // -// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, -// you must first deregister all delegated administrators for this service. +// * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register +// an AWS account as a delegated administrator for an AWS service that already +// has a delegated administrator. To complete this operation, you must first +// deregister any existing delegated administrators for this service. +// +// * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only +// valid for a limited period of time. You must resubmit the request and +// generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -13926,8 +14557,12 @@ func (s *ConcurrentModificationException) RequestID() string { // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // +// * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions +// in China. To create an organization, the master must have an valid business +// license. For more information, contact customer support. +// // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you -// must first provide contact a valid address and phone number for the master +// must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -13964,19 +14599,26 @@ func (s *ConcurrentModificationException) RequestID() string { // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // -// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is -// too many levels deep. -// // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // +// * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is +// too many levels deep. +// // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // -// * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of +// * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that +// is larger than the maximum size. +// +// * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. +// +// * TAG_POLICY_VIOLATION: You attempted to create or update a resource with +// tags that are not compliant with the tag policy requirements for this +// account. type ConstraintViolationException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -14199,6 +14841,9 @@ type CreateAccountStatus struct { // * ACCOUNT_LIMIT_EXCEEDED: The account could not be created because you // have reached the limit on the number of accounts in your organization. // + // * CONCURRENT_ACCOUNT_MODIFICATION: You already submitted a request with + // the same information. + // // * EMAIL_ALREADY_EXISTS: The account could not be created because another // AWS account with that email address already exists. // @@ -14214,6 +14859,12 @@ type CreateAccountStatus struct { // // * INTERNAL_FAILURE: The account could not be created because of an internal // failure. Try again later. If the problem persists, contact Customer Support. + // + // * MISSING_BUSINESS_VALIDATION: The AWS account that owns your organization + // has not received Business Validation. + // + // * MISSING_PAYMENT_INSTRUMENT: You must configure the master account with + // a valid payment method, such as a credit card. FailureReason *string `type:"string" enum:"CreateAccountFailureReason"` // If the account was created successfully, the unique identifier (ID) of the @@ -14637,13 +15288,8 @@ func (s *CreateOrganizationalUnitOutput) SetOrganizationalUnit(v *Organizational type CreatePolicyInput struct { _ struct{} `type:"structure"` - // The policy content to add to the new policy. For example, if you create a - // service control policy (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scp.html) - // (SCP), this string must be JSON text that specifies the permissions that - // admins in attached accounts can delegate to their users, groups, and roles. - // For more information about the SCP syntax, see Service Control Policy Syntax - // (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_scp-syntax.html) - // in the AWS Organizations User Guide. + // The policy text content to add to the new policy. The text that you supply + // must adhere to the rules of the policy type you specify in the Type parameter. // // Content is a required field Content *string `min:"1" type:"string" required:"true"` @@ -14662,10 +15308,15 @@ type CreatePolicyInput struct { // Name is a required field Name *string `min:"1" type:"string" required:"true"` - // The type of policy to create. + // The type of policy to create. You can specify one of the following values: // - // In the current release, the only type of policy that you can create is a - // service control policy (SCP). + // * AISERVICES_OPT_OUT_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html) + // + // * BACKUP_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_backup.html) + // + // * SERVICE_CONTROL_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scp.html) + // + // * TAG_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) // // Type is a required field Type *string `type:"string" required:"true" enum:"PolicyType"` @@ -15300,14 +15951,21 @@ func (s *DescribeCreateAccountStatusOutput) SetCreateAccountStatus(v *CreateAcco type DescribeEffectivePolicyInput struct { _ struct{} `type:"structure"` - // The type of policy that you want information about. + // The type of policy that you want information about. You can specify one of + // the following values: + // + // * AISERVICES_OPT_OUT_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html) + // + // * BACKUP_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_backup.html) + // + // * TAG_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) // // PolicyType is a required field PolicyType *string `type:"string" required:"true" enum:"EffectivePolicyType"` // When you're signed in as the master account, specify the ID of the account - // that you want details about. Specifying an organization root or OU as the - // target is not supported. + // that you want details about. Specifying an organization root or organizational + // unit (OU) as the target is not supported. TargetId *string `type:"string"` } @@ -15453,6 +16111,11 @@ type DescribeOrganizationOutput struct { _ struct{} `type:"structure"` // A structure that contains information about the organization. + // + // The AvailablePolicyTypes part of the response is deprecated, and you shouldn't + // use it in your apps. It doesn't include any policy type supported by Organizations + // other than SCPs. To determine which policy types are enabled in your organization, + // use the ListRoots operation. Organization *Organization `type:"structure"` } @@ -15808,7 +16471,16 @@ func (s DisableAWSServiceAccessOutput) GoString() string { type DisablePolicyTypeInput struct { _ struct{} `type:"structure"` - // The policy type that you want to disable in this root. + // The policy type that you want to disable in this root. You can specify one + // of the following values: + // + // * AISERVICES_OPT_OUT_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html) + // + // * BACKUP_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_backup.html) + // + // * SERVICE_CONTROL_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scp.html) + // + // * TAG_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) // // PolicyType is a required field PolicyType *string `type:"string" required:"true" enum:"PolicyType"` @@ -16378,7 +17050,16 @@ func (s *EnableAllFeaturesOutput) SetHandshake(v *Handshake) *EnableAllFeaturesO type EnablePolicyTypeInput struct { _ struct{} `type:"structure"` - // The policy type that you want to enable. + // The policy type that you want to enable. You can specify one of the following + // values: + // + // * AISERVICES_OPT_OUT_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html) + // + // * BACKUP_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_backup.html) + // + // * SERVICE_CONTROL_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scp.html) + // + // * TAG_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) // // PolicyType is a required field PolicyType *string `type:"string" required:"true" enum:"PolicyType"` @@ -17122,7 +17803,7 @@ func (s *InvalidHandshakeTransitionException) RequestID() string { // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this -// specific API or operation: +// specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -18539,7 +19220,16 @@ func (s *ListParentsOutput) SetParents(v []*Parent) *ListParentsOutput { type ListPoliciesForTargetInput struct { _ struct{} `type:"structure"` - // The type of policy that you want to include in the returned list. + // The type of policy that you want to include in the returned list. You must + // specify one of the following values: + // + // * AISERVICES_OPT_OUT_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html) + // + // * BACKUP_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_backup.html) + // + // * SERVICE_CONTROL_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scp.html) + // + // * TAG_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) // // Filter is a required field Filter *string `type:"string" required:"true" enum:"PolicyType"` @@ -18672,7 +19362,16 @@ func (s *ListPoliciesForTargetOutput) SetPolicies(v []*PolicySummary) *ListPolic type ListPoliciesInput struct { _ struct{} `type:"structure"` - // Specifies the type of policy that you want to include in the response. + // Specifies the type of policy that you want to include in the response. You + // must specify one of the following values: + // + // * AISERVICES_OPT_OUT_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_ai-opt-out.html) + // + // * BACKUP_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_backup.html) + // + // * SERVICE_CONTROL_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scp.html) + // + // * TAG_POLICY (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) // // Filter is a required field Filter *string `type:"string" required:"true" enum:"PolicyType"` @@ -19300,14 +19999,12 @@ type Organization struct { // in the AWS Organizations User Guide. Arn *string `type:"string"` - // A list of policy types that are enabled for this organization. For example, - // if your organization has all features enabled, then service control policies - // (SCPs) are included in the list. // - // Even if a policy type is shown as available in the organization, you can - // separately enable and disable them at the root level by using EnablePolicyType - // and DisablePolicyType. Use ListRoots to see the status of a policy type in - // that root. + // Do not use. This field is deprecated and doesn't provide complete information + // about the policies in your organization. + // + // To determine the policies that are enabled and available for use in your + // organization, use the ListRoots operation instead. AvailablePolicyTypes []*PolicyTypeSummary `type:"list"` // Specifies the functionality that currently is available to the organization. @@ -20198,9 +20895,9 @@ func (s *PolicyTypeAlreadyEnabledException) RequestID() string { // You can't use the specified policy type with the feature set currently enabled // for this organization. For example, you can enable SCPs only after you enable -// all features in the organization. For more information, see Enabling and -// Disabling a Policy Type on a Root (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html#enable_policies_on_root) -// in the AWS Organizations User Guide. +// all features in the organization. For more information, see Managing AWS +// Organizations Policies (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html#enable_policies_on_root)in +// the AWS Organizations User Guide. type PolicyTypeNotAvailableForOrganizationException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -20787,9 +21484,9 @@ type TagResourceInput struct { // ResourceId is a required field ResourceId *string `type:"string" required:"true"` - // The tag to add to the specified resource. Specifying the tag key is required. - // You can set the value of a tag to an empty string, but you can't set the - // value of a tag to null. + // The tag to add to the specified resource. You must specify both a tag key + // and value. You can set the value of a tag to an empty string, but you can't + // set it to null. // // Tags is a required field Tags []*Tag `type:"list" required:"true"` @@ -20913,12 +21610,12 @@ func (s *TargetNotFoundException) RequestID() string { return s.RespMetadata.RequestID } -// You have sent too many requests in too short a period of time. The limit +// You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // -// For information on limits that affect AWS Organizations, see Limits of AWS -// Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) -// in the AWS Organizations User Guide. +// For information about quotas that affect AWS Organizations, see Quotas for +// AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in +// the AWS Organizations User Guide. type TooManyRequestsException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -20976,7 +21673,7 @@ func (s *TooManyRequestsException) RequestID() string { return s.RespMetadata.RequestID } -// This action isn't available in the current Region. +// This action isn't available in the current AWS Region. type UnsupportedAPIEndpointException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -21293,6 +21990,13 @@ const ( AccessDeniedForDependencyExceptionReasonAccessDeniedDuringCreateServiceLinkedRole = "ACCESS_DENIED_DURING_CREATE_SERVICE_LINKED_ROLE" ) +// AccessDeniedForDependencyExceptionReason_Values returns all elements of the AccessDeniedForDependencyExceptionReason enum +func AccessDeniedForDependencyExceptionReason_Values() []string { + return []string{ + AccessDeniedForDependencyExceptionReasonAccessDeniedDuringCreateServiceLinkedRole, + } +} + const ( // AccountJoinedMethodInvited is a AccountJoinedMethod enum value AccountJoinedMethodInvited = "INVITED" @@ -21301,6 +22005,14 @@ const ( AccountJoinedMethodCreated = "CREATED" ) +// AccountJoinedMethod_Values returns all elements of the AccountJoinedMethod enum +func AccountJoinedMethod_Values() []string { + return []string{ + AccountJoinedMethodInvited, + AccountJoinedMethodCreated, + } +} + const ( // AccountStatusActive is a AccountStatus enum value AccountStatusActive = "ACTIVE" @@ -21309,6 +22021,14 @@ const ( AccountStatusSuspended = "SUSPENDED" ) +// AccountStatus_Values returns all elements of the AccountStatus enum +func AccountStatus_Values() []string { + return []string{ + AccountStatusActive, + AccountStatusSuspended, + } +} + const ( // ActionTypeInvite is a ActionType enum value ActionTypeInvite = "INVITE" @@ -21323,6 +22043,16 @@ const ( ActionTypeAddOrganizationsServiceLinkedRole = "ADD_ORGANIZATIONS_SERVICE_LINKED_ROLE" ) +// ActionType_Values returns all elements of the ActionType enum +func ActionType_Values() []string { + return []string{ + ActionTypeInvite, + ActionTypeEnableAllFeatures, + ActionTypeApproveAllFeatures, + ActionTypeAddOrganizationsServiceLinkedRole, + } +} + const ( // ChildTypeAccount is a ChildType enum value ChildTypeAccount = "ACCOUNT" @@ -21331,6 +22061,14 @@ const ( ChildTypeOrganizationalUnit = "ORGANIZATIONAL_UNIT" ) +// ChildType_Values returns all elements of the ChildType enum +func ChildType_Values() []string { + return []string{ + ChildTypeAccount, + ChildTypeOrganizationalUnit, + } +} + const ( // ConstraintViolationExceptionReasonAccountNumberLimitExceeded is a ConstraintViolationExceptionReason enum value ConstraintViolationExceptionReasonAccountNumberLimitExceeded = "ACCOUNT_NUMBER_LIMIT_EXCEEDED" @@ -21412,8 +22150,45 @@ const ( // ConstraintViolationExceptionReasonDelegatedAdministratorExistsForThisService is a ConstraintViolationExceptionReason enum value ConstraintViolationExceptionReasonDelegatedAdministratorExistsForThisService = "DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE" + + // ConstraintViolationExceptionReasonMasterAccountMissingBusinessLicense is a ConstraintViolationExceptionReason enum value + ConstraintViolationExceptionReasonMasterAccountMissingBusinessLicense = "MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE" ) +// ConstraintViolationExceptionReason_Values returns all elements of the ConstraintViolationExceptionReason enum +func ConstraintViolationExceptionReason_Values() []string { + return []string{ + ConstraintViolationExceptionReasonAccountNumberLimitExceeded, + ConstraintViolationExceptionReasonHandshakeRateLimitExceeded, + ConstraintViolationExceptionReasonOuNumberLimitExceeded, + ConstraintViolationExceptionReasonOuDepthLimitExceeded, + ConstraintViolationExceptionReasonPolicyNumberLimitExceeded, + ConstraintViolationExceptionReasonPolicyContentLimitExceeded, + ConstraintViolationExceptionReasonMaxPolicyTypeAttachmentLimitExceeded, + ConstraintViolationExceptionReasonMinPolicyTypeAttachmentLimitExceeded, + ConstraintViolationExceptionReasonAccountCannotLeaveOrganization, + ConstraintViolationExceptionReasonAccountCannotLeaveWithoutEula, + ConstraintViolationExceptionReasonAccountCannotLeaveWithoutPhoneVerification, + ConstraintViolationExceptionReasonMasterAccountPaymentInstrumentRequired, + ConstraintViolationExceptionReasonMemberAccountPaymentInstrumentRequired, + ConstraintViolationExceptionReasonAccountCreationRateLimitExceeded, + ConstraintViolationExceptionReasonMasterAccountAddressDoesNotMatchMarketplace, + ConstraintViolationExceptionReasonMasterAccountMissingContactInfo, + ConstraintViolationExceptionReasonMasterAccountNotGovcloudEnabled, + ConstraintViolationExceptionReasonOrganizationNotInAllFeaturesMode, + ConstraintViolationExceptionReasonCreateOrganizationInBillingModeUnsupportedRegion, + ConstraintViolationExceptionReasonEmailVerificationCodeExpired, + ConstraintViolationExceptionReasonWaitPeriodActive, + ConstraintViolationExceptionReasonMaxTagLimitExceeded, + ConstraintViolationExceptionReasonTagPolicyViolation, + ConstraintViolationExceptionReasonMaxDelegatedAdministratorsForServiceLimitExceeded, + ConstraintViolationExceptionReasonCannotRegisterMasterAsDelegatedAdministrator, + ConstraintViolationExceptionReasonCannotRemoveDelegatedAdministratorFromOrg, + ConstraintViolationExceptionReasonDelegatedAdministratorExistsForThisService, + ConstraintViolationExceptionReasonMasterAccountMissingBusinessLicense, + } +} + const ( // CreateAccountFailureReasonAccountLimitExceeded is a CreateAccountFailureReason enum value CreateAccountFailureReasonAccountLimitExceeded = "ACCOUNT_LIMIT_EXCEEDED" @@ -21435,8 +22210,29 @@ const ( // CreateAccountFailureReasonGovcloudAccountAlreadyExists is a CreateAccountFailureReason enum value CreateAccountFailureReasonGovcloudAccountAlreadyExists = "GOVCLOUD_ACCOUNT_ALREADY_EXISTS" + + // CreateAccountFailureReasonMissingBusinessValidation is a CreateAccountFailureReason enum value + CreateAccountFailureReasonMissingBusinessValidation = "MISSING_BUSINESS_VALIDATION" + + // CreateAccountFailureReasonMissingPaymentInstrument is a CreateAccountFailureReason enum value + CreateAccountFailureReasonMissingPaymentInstrument = "MISSING_PAYMENT_INSTRUMENT" ) +// CreateAccountFailureReason_Values returns all elements of the CreateAccountFailureReason enum +func CreateAccountFailureReason_Values() []string { + return []string{ + CreateAccountFailureReasonAccountLimitExceeded, + CreateAccountFailureReasonEmailAlreadyExists, + CreateAccountFailureReasonInvalidAddress, + CreateAccountFailureReasonInvalidEmail, + CreateAccountFailureReasonConcurrentAccountModification, + CreateAccountFailureReasonInternalFailure, + CreateAccountFailureReasonGovcloudAccountAlreadyExists, + CreateAccountFailureReasonMissingBusinessValidation, + CreateAccountFailureReasonMissingPaymentInstrument, + } +} + const ( // CreateAccountStateInProgress is a CreateAccountState enum value CreateAccountStateInProgress = "IN_PROGRESS" @@ -21448,11 +22244,35 @@ const ( CreateAccountStateFailed = "FAILED" ) +// CreateAccountState_Values returns all elements of the CreateAccountState enum +func CreateAccountState_Values() []string { + return []string{ + CreateAccountStateInProgress, + CreateAccountStateSucceeded, + CreateAccountStateFailed, + } +} + const ( // EffectivePolicyTypeTagPolicy is a EffectivePolicyType enum value EffectivePolicyTypeTagPolicy = "TAG_POLICY" + + // EffectivePolicyTypeBackupPolicy is a EffectivePolicyType enum value + EffectivePolicyTypeBackupPolicy = "BACKUP_POLICY" + + // EffectivePolicyTypeAiservicesOptOutPolicy is a EffectivePolicyType enum value + EffectivePolicyTypeAiservicesOptOutPolicy = "AISERVICES_OPT_OUT_POLICY" ) +// EffectivePolicyType_Values returns all elements of the EffectivePolicyType enum +func EffectivePolicyType_Values() []string { + return []string{ + EffectivePolicyTypeTagPolicy, + EffectivePolicyTypeBackupPolicy, + EffectivePolicyTypeAiservicesOptOutPolicy, + } +} + const ( // HandshakeConstraintViolationExceptionReasonAccountNumberLimitExceeded is a HandshakeConstraintViolationExceptionReason enum value HandshakeConstraintViolationExceptionReasonAccountNumberLimitExceeded = "ACCOUNT_NUMBER_LIMIT_EXCEEDED" @@ -21479,6 +22299,20 @@ const ( HandshakeConstraintViolationExceptionReasonOrganizationMembershipChangeRateLimitExceeded = "ORGANIZATION_MEMBERSHIP_CHANGE_RATE_LIMIT_EXCEEDED" ) +// HandshakeConstraintViolationExceptionReason_Values returns all elements of the HandshakeConstraintViolationExceptionReason enum +func HandshakeConstraintViolationExceptionReason_Values() []string { + return []string{ + HandshakeConstraintViolationExceptionReasonAccountNumberLimitExceeded, + HandshakeConstraintViolationExceptionReasonHandshakeRateLimitExceeded, + HandshakeConstraintViolationExceptionReasonAlreadyInAnOrganization, + HandshakeConstraintViolationExceptionReasonOrganizationAlreadyHasAllFeatures, + HandshakeConstraintViolationExceptionReasonInviteDisabledDuringEnableAllFeatures, + HandshakeConstraintViolationExceptionReasonPaymentInstrumentRequired, + HandshakeConstraintViolationExceptionReasonOrganizationFromDifferentSellerOfRecord, + HandshakeConstraintViolationExceptionReasonOrganizationMembershipChangeRateLimitExceeded, + } +} + const ( // HandshakePartyTypeAccount is a HandshakePartyType enum value HandshakePartyTypeAccount = "ACCOUNT" @@ -21490,6 +22324,15 @@ const ( HandshakePartyTypeEmail = "EMAIL" ) +// HandshakePartyType_Values returns all elements of the HandshakePartyType enum +func HandshakePartyType_Values() []string { + return []string{ + HandshakePartyTypeAccount, + HandshakePartyTypeOrganization, + HandshakePartyTypeEmail, + } +} + const ( // HandshakeResourceTypeAccount is a HandshakeResourceType enum value HandshakeResourceTypeAccount = "ACCOUNT" @@ -21516,6 +22359,20 @@ const ( HandshakeResourceTypeParentHandshake = "PARENT_HANDSHAKE" ) +// HandshakeResourceType_Values returns all elements of the HandshakeResourceType enum +func HandshakeResourceType_Values() []string { + return []string{ + HandshakeResourceTypeAccount, + HandshakeResourceTypeOrganization, + HandshakeResourceTypeOrganizationFeatureSet, + HandshakeResourceTypeEmail, + HandshakeResourceTypeMasterEmail, + HandshakeResourceTypeMasterName, + HandshakeResourceTypeNotes, + HandshakeResourceTypeParentHandshake, + } +} + const ( // HandshakeStateRequested is a HandshakeState enum value HandshakeStateRequested = "REQUESTED" @@ -21536,6 +22393,18 @@ const ( HandshakeStateExpired = "EXPIRED" ) +// HandshakeState_Values returns all elements of the HandshakeState enum +func HandshakeState_Values() []string { + return []string{ + HandshakeStateRequested, + HandshakeStateOpen, + HandshakeStateCanceled, + HandshakeStateAccepted, + HandshakeStateDeclined, + HandshakeStateExpired, + } +} + const ( // IAMUserAccessToBillingAllow is a IAMUserAccessToBilling enum value IAMUserAccessToBillingAllow = "ALLOW" @@ -21544,6 +22413,14 @@ const ( IAMUserAccessToBillingDeny = "DENY" ) +// IAMUserAccessToBilling_Values returns all elements of the IAMUserAccessToBilling enum +func IAMUserAccessToBilling_Values() []string { + return []string{ + IAMUserAccessToBillingAllow, + IAMUserAccessToBillingDeny, + } +} + const ( // InvalidInputExceptionReasonInvalidPartyTypeTarget is a InvalidInputExceptionReason enum value InvalidInputExceptionReasonInvalidPartyTypeTarget = "INVALID_PARTY_TYPE_TARGET" @@ -21612,6 +22489,34 @@ const ( InvalidInputExceptionReasonTargetNotSupported = "TARGET_NOT_SUPPORTED" ) +// InvalidInputExceptionReason_Values returns all elements of the InvalidInputExceptionReason enum +func InvalidInputExceptionReason_Values() []string { + return []string{ + InvalidInputExceptionReasonInvalidPartyTypeTarget, + InvalidInputExceptionReasonInvalidSyntaxOrganizationArn, + InvalidInputExceptionReasonInvalidSyntaxPolicyId, + InvalidInputExceptionReasonInvalidEnum, + InvalidInputExceptionReasonInvalidEnumPolicyType, + InvalidInputExceptionReasonInvalidListMember, + InvalidInputExceptionReasonMaxLengthExceeded, + InvalidInputExceptionReasonMaxValueExceeded, + InvalidInputExceptionReasonMinLengthExceeded, + InvalidInputExceptionReasonMinValueExceeded, + InvalidInputExceptionReasonImmutablePolicy, + InvalidInputExceptionReasonInvalidPattern, + InvalidInputExceptionReasonInvalidPatternTargetId, + InvalidInputExceptionReasonInputRequired, + InvalidInputExceptionReasonInvalidNextToken, + InvalidInputExceptionReasonMaxLimitExceededFilter, + InvalidInputExceptionReasonMovingAccountBetweenDifferentRoots, + InvalidInputExceptionReasonInvalidFullNameTarget, + InvalidInputExceptionReasonUnrecognizedServicePrincipal, + InvalidInputExceptionReasonInvalidRoleName, + InvalidInputExceptionReasonInvalidSystemTagsParameter, + InvalidInputExceptionReasonTargetNotSupported, + } +} + const ( // OrganizationFeatureSetAll is a OrganizationFeatureSet enum value OrganizationFeatureSetAll = "ALL" @@ -21620,6 +22525,14 @@ const ( OrganizationFeatureSetConsolidatedBilling = "CONSOLIDATED_BILLING" ) +// OrganizationFeatureSet_Values returns all elements of the OrganizationFeatureSet enum +func OrganizationFeatureSet_Values() []string { + return []string{ + OrganizationFeatureSetAll, + OrganizationFeatureSetConsolidatedBilling, + } +} + const ( // ParentTypeRoot is a ParentType enum value ParentTypeRoot = "ROOT" @@ -21628,14 +22541,38 @@ const ( ParentTypeOrganizationalUnit = "ORGANIZATIONAL_UNIT" ) +// ParentType_Values returns all elements of the ParentType enum +func ParentType_Values() []string { + return []string{ + ParentTypeRoot, + ParentTypeOrganizationalUnit, + } +} + const ( // PolicyTypeServiceControlPolicy is a PolicyType enum value PolicyTypeServiceControlPolicy = "SERVICE_CONTROL_POLICY" // PolicyTypeTagPolicy is a PolicyType enum value PolicyTypeTagPolicy = "TAG_POLICY" + + // PolicyTypeBackupPolicy is a PolicyType enum value + PolicyTypeBackupPolicy = "BACKUP_POLICY" + + // PolicyTypeAiservicesOptOutPolicy is a PolicyType enum value + PolicyTypeAiservicesOptOutPolicy = "AISERVICES_OPT_OUT_POLICY" ) +// PolicyType_Values returns all elements of the PolicyType enum +func PolicyType_Values() []string { + return []string{ + PolicyTypeServiceControlPolicy, + PolicyTypeTagPolicy, + PolicyTypeBackupPolicy, + PolicyTypeAiservicesOptOutPolicy, + } +} + const ( // PolicyTypeStatusEnabled is a PolicyTypeStatus enum value PolicyTypeStatusEnabled = "ENABLED" @@ -21647,6 +22584,15 @@ const ( PolicyTypeStatusPendingDisable = "PENDING_DISABLE" ) +// PolicyTypeStatus_Values returns all elements of the PolicyTypeStatus enum +func PolicyTypeStatus_Values() []string { + return []string{ + PolicyTypeStatusEnabled, + PolicyTypeStatusPendingEnable, + PolicyTypeStatusPendingDisable, + } +} + const ( // TargetTypeAccount is a TargetType enum value TargetTypeAccount = "ACCOUNT" @@ -21657,3 +22603,12 @@ const ( // TargetTypeRoot is a TargetType enum value TargetTypeRoot = "ROOT" ) + +// TargetType_Values returns all elements of the TargetType enum +func TargetType_Values() []string { + return []string{ + TargetTypeAccount, + TargetTypeOrganizationalUnit, + TargetTypeRoot, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/organizations/errors.go b/vendor/github.com/aws/aws-sdk-go/service/organizations/errors.go index 8ad7420f57b..52cea61e083 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/organizations/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/organizations/errors.go @@ -91,23 +91,27 @@ const ( // an OU or root, inviting or creating too many accounts to the organization, // or attaching too many policies to an account, OU, or root. This exception // includes a reason that contains additional information about the violated - // limit. + // limit: // // Some of the reasons in the following list might not be applicable to this - // specific API or operation: + // specific API or operation. + // + // * ACCOUNT_CANNOT_LEAVE_ORGANIZAION: You attempted to remove the master + // account from the organization. You can't remove the master account. Instead, + // after you remove all member accounts, delete the organization itself. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_EULA: You attempted to remove an account // from the organization that doesn't yet have enough information to exist // as a standalone account. This account requires you to first agree to the - // AWS Customer Agreement. Follow the steps at To leave an organization when - // all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) - // in the AWS Organizations User Guide. + // AWS Customer Agreement. Follow the steps at Removing a member account + // from your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master)in + // the AWS Organizations User Guide. // // * ACCOUNT_CANNOT_LEAVE_WITHOUT_PHONE_VERIFICATION: You attempted to remove // an account from the organization that doesn't yet have enough information // to exist as a standalone account. This account requires you to first complete - // phone verification. Follow the steps at To leave an organization when - // all required account information has not yet been provided (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#leave-without-all-info) + // phone verification. Follow the steps at Removing a member account from + // your organization (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_remove.html#orgs_manage_accounts_remove-from-master) // in the AWS Organizations User Guide. // // * ACCOUNT_CREATION_RATE_LIMIT_EXCEEDED: You attempted to exceed the number @@ -120,19 +124,32 @@ const ( // tried to send would cause you to exceed the limit of accounts in your // organization. Send fewer invitations or contact AWS Support to request // an increase in the number of accounts. Deleted and closed accounts still - // count toward your limit. If you get receive this exception when running - // a command immediately after creating the organization, wait one hour and - // try again. If after an hour it continues to fail with this error, contact + // count toward your limit. If you get this exception when running a command + // immediately after creating the organization, wait one hour and try again. + // After an hour, if the command continues to fail with this error, contact // AWS Support (https://console.aws.amazon.com/support/home#/). // - // * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You can designate - // only a member account as a delegated administrator. + // * CANNOT_REGISTER_MASTER_AS_DELEGATED_ADMINISTRATOR: You attempted to + // register the master account of the organization as a delegated administrator + // for an AWS service integrated with Organizations. You can designate only + // a member account as a delegated administrator. + // + // * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: You attempted to remove + // an account that is registered as a delegated administrator for a service + // integrated with your organization. To complete this operation, you must + // first deregister this account as a delegated administrator. + // + // * CREATE_ORGANIZATION_IN_BILLING_MODE_UNSUPPORTED_REGION: To create an + // organization in the specified region, you must enable all features mode. // - // * CANNOT_REMOVE_DELEGATED_ADMINISTRATOR_FROM_ORG: To complete this operation, - // you must first deregister this account as a delegated administrator. + // * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: You attempted to register + // an AWS account as a delegated administrator for an AWS service that already + // has a delegated administrator. To complete this operation, you must first + // deregister any existing delegated administrators for this service. // - // * DELEGATED_ADMINISTRATOR_EXISTS_FOR_THIS_SERVICE: To complete this operation, - // you must first deregister all delegated administrators for this service. + // * EMAIL_VERIFICATION_CODE_EXPIRED: The email verification code is only + // valid for a limited period of time. You must resubmit the request and + // generate a new verfication code. // // * HANDSHAKE_RATE_LIMIT_EXCEEDED: You attempted to exceed the number of // handshakes that you can send in one day. @@ -144,8 +161,12 @@ const ( // AISPL marketplace. All accounts in an organization must be associated // with the same marketplace. // + // * MASTER_ACCOUNT_MISSING_BUSINESS_LICENSE: Applies only to the AWS Regions + // in China. To create an organization, the master must have an valid business + // license. For more information, contact customer support. + // // * MASTER_ACCOUNT_MISSING_CONTACT_INFO: To complete this operation, you - // must first provide contact a valid address and phone number for the master + // must first provide a valid contact address and phone number for the master // account. Then try the operation again. // // * MASTER_ACCOUNT_NOT_GOVCLOUD_ENABLED: To complete this operation, the @@ -182,19 +203,26 @@ const ( // policy from an entity that would cause the entity to have fewer than the // minimum number of policies of a certain type required. // - // * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is - // too many levels deep. - // // * ORGANIZATION_NOT_IN_ALL_FEATURES_MODE: You attempted to perform an operation // that requires the organization to be configured to support all features. // An organization that supports only consolidated billing features can't // perform this operation. // + // * OU_DEPTH_LIMIT_EXCEEDED: You attempted to create an OU tree that is + // too many levels deep. + // // * OU_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of OUs // that you can have in an organization. // - // * POLICY_NUMBER_LIMIT_EXCEEDED. You attempted to exceed the number of + // * POLICY_CONTENT_LIMIT_EXCEEDED: You attempted to create a policy that + // is larger than the maximum size. + // + // * POLICY_NUMBER_LIMIT_EXCEEDED: You attempted to exceed the number of // policies that you can have in an organization. + // + // * TAG_POLICY_VIOLATION: You attempted to create or update a resource with + // tags that are not compliant with the tag policy requirements for this + // account. ErrCodeConstraintViolationException = "ConstraintViolationException" // ErrCodeCreateAccountStatusNotFoundException for service response error code @@ -335,7 +363,7 @@ const ( // contains additional information about the violated limit: // // Some of the reasons in the following list might not be applicable to this - // specific API or operation: + // specific API or operation. // // * IMMUTABLE_POLICY: You specified a policy that is managed by AWS and // can't be modified. @@ -474,9 +502,9 @@ const ( // // You can't use the specified policy type with the feature set currently enabled // for this organization. For example, you can enable SCPs only after you enable - // all features in the organization. For more information, see Enabling and - // Disabling a Policy Type on a Root (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html#enable_policies_on_root) - // in the AWS Organizations User Guide. + // all features in the organization. For more information, see Managing AWS + // Organizations Policies (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies.html#enable_policies_on_root)in + // the AWS Organizations User Guide. ErrCodePolicyTypeNotAvailableForOrganizationException = "PolicyTypeNotAvailableForOrganizationException" // ErrCodePolicyTypeNotEnabledException for service response error code @@ -517,18 +545,18 @@ const ( // ErrCodeTooManyRequestsException for service response error code // "TooManyRequestsException". // - // You have sent too many requests in too short a period of time. The limit + // You have sent too many requests in too short a period of time. The quota // helps protect against denial-of-service attacks. Try again later. // - // For information on limits that affect AWS Organizations, see Limits of AWS - // Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html) - // in the AWS Organizations User Guide. + // For information about quotas that affect AWS Organizations, see Quotas for + // AWS Organizations (https://docs.aws.amazon.com/organizations/latest/userguide/orgs_reference_limits.html)in + // the AWS Organizations User Guide. ErrCodeTooManyRequestsException = "TooManyRequestsException" // ErrCodeUnsupportedAPIEndpointException for service response error code // "UnsupportedAPIEndpointException". // - // This action isn't available in the current Region. + // This action isn't available in the current AWS Region. ErrCodeUnsupportedAPIEndpointException = "UnsupportedAPIEndpointException" ) diff --git a/vendor/github.com/aws/aws-sdk-go/service/outposts/api.go b/vendor/github.com/aws/aws-sdk-go/service/outposts/api.go new file mode 100644 index 00000000000..2a2b23a4c3c --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/outposts/api.go @@ -0,0 +1,1764 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package outposts + +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" + "github.com/aws/aws-sdk-go/private/protocol/restjson" +) + +const opCreateOutpost = "CreateOutpost" + +// CreateOutpostRequest generates a "aws/request.Request" representing the +// client's request for the CreateOutpost operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateOutpost for more information on using the CreateOutpost +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateOutpostRequest method. +// req, resp := client.CreateOutpostRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/CreateOutpost +func (c *Outposts) CreateOutpostRequest(input *CreateOutpostInput) (req *request.Request, output *CreateOutpostOutput) { + op := &request.Operation{ + Name: opCreateOutpost, + HTTPMethod: "POST", + HTTPPath: "/outposts", + } + + if input == nil { + input = &CreateOutpostInput{} + } + + output = &CreateOutpostOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateOutpost API operation for AWS Outposts. +// +// Creates an Outpost. +// +// Returns awserr.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 Outposts's +// API operation CreateOutpost for usage and error information. +// +// Returned Error Types: +// * ValidationException +// A parameter is not valid. +// +// * NotFoundException +// The specified request is not valid. +// +// * AccessDeniedException +// You do not have permission to perform this operation. +// +// * InternalServerException +// An internal error has occurred. +// +// * ServiceQuotaExceededException +// You have exceeded a service quota. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/CreateOutpost +func (c *Outposts) CreateOutpost(input *CreateOutpostInput) (*CreateOutpostOutput, error) { + req, out := c.CreateOutpostRequest(input) + return out, req.Send() +} + +// CreateOutpostWithContext is the same as CreateOutpost with the addition of +// the ability to pass a context and additional request options. +// +// See CreateOutpost for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Outposts) CreateOutpostWithContext(ctx aws.Context, input *CreateOutpostInput, opts ...request.Option) (*CreateOutpostOutput, error) { + req, out := c.CreateOutpostRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteOutpost = "DeleteOutpost" + +// DeleteOutpostRequest generates a "aws/request.Request" representing the +// client's request for the DeleteOutpost operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteOutpost for more information on using the DeleteOutpost +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteOutpostRequest method. +// req, resp := client.DeleteOutpostRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/DeleteOutpost +func (c *Outposts) DeleteOutpostRequest(input *DeleteOutpostInput) (req *request.Request, output *DeleteOutpostOutput) { + op := &request.Operation{ + Name: opDeleteOutpost, + HTTPMethod: "DELETE", + HTTPPath: "/outposts/{OutpostId}", + } + + if input == nil { + input = &DeleteOutpostInput{} + } + + output = &DeleteOutpostOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteOutpost API operation for AWS Outposts. +// +// Deletes the Outpost. +// +// Returns awserr.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 Outposts's +// API operation DeleteOutpost for usage and error information. +// +// Returned Error Types: +// * ValidationException +// A parameter is not valid. +// +// * NotFoundException +// The specified request is not valid. +// +// * AccessDeniedException +// You do not have permission to perform this operation. +// +// * InternalServerException +// An internal error has occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/DeleteOutpost +func (c *Outposts) DeleteOutpost(input *DeleteOutpostInput) (*DeleteOutpostOutput, error) { + req, out := c.DeleteOutpostRequest(input) + return out, req.Send() +} + +// DeleteOutpostWithContext is the same as DeleteOutpost with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteOutpost for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Outposts) DeleteOutpostWithContext(ctx aws.Context, input *DeleteOutpostInput, opts ...request.Option) (*DeleteOutpostOutput, error) { + req, out := c.DeleteOutpostRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteSite = "DeleteSite" + +// DeleteSiteRequest generates a "aws/request.Request" representing the +// client's request for the DeleteSite operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteSite for more information on using the DeleteSite +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteSiteRequest method. +// req, resp := client.DeleteSiteRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/DeleteSite +func (c *Outposts) DeleteSiteRequest(input *DeleteSiteInput) (req *request.Request, output *DeleteSiteOutput) { + op := &request.Operation{ + Name: opDeleteSite, + HTTPMethod: "DELETE", + HTTPPath: "/sites/{SiteId}", + } + + if input == nil { + input = &DeleteSiteInput{} + } + + output = &DeleteSiteOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteSite API operation for AWS Outposts. +// +// Deletes the site. +// +// Returns awserr.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 Outposts's +// API operation DeleteSite for usage and error information. +// +// Returned Error Types: +// * ValidationException +// A parameter is not valid. +// +// * NotFoundException +// The specified request is not valid. +// +// * AccessDeniedException +// You do not have permission to perform this operation. +// +// * InternalServerException +// An internal error has occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/DeleteSite +func (c *Outposts) DeleteSite(input *DeleteSiteInput) (*DeleteSiteOutput, error) { + req, out := c.DeleteSiteRequest(input) + return out, req.Send() +} + +// DeleteSiteWithContext is the same as DeleteSite with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteSite for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Outposts) DeleteSiteWithContext(ctx aws.Context, input *DeleteSiteInput, opts ...request.Option) (*DeleteSiteOutput, error) { + req, out := c.DeleteSiteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetOutpost = "GetOutpost" + +// GetOutpostRequest generates a "aws/request.Request" representing the +// client's request for the GetOutpost operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetOutpost for more information on using the GetOutpost +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetOutpostRequest method. +// req, resp := client.GetOutpostRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/GetOutpost +func (c *Outposts) GetOutpostRequest(input *GetOutpostInput) (req *request.Request, output *GetOutpostOutput) { + op := &request.Operation{ + Name: opGetOutpost, + HTTPMethod: "GET", + HTTPPath: "/outposts/{OutpostId}", + } + + if input == nil { + input = &GetOutpostInput{} + } + + output = &GetOutpostOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetOutpost API operation for AWS Outposts. +// +// Gets information about the specified Outpost. +// +// Returns awserr.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 Outposts's +// API operation GetOutpost for usage and error information. +// +// Returned Error Types: +// * ValidationException +// A parameter is not valid. +// +// * NotFoundException +// The specified request is not valid. +// +// * AccessDeniedException +// You do not have permission to perform this operation. +// +// * InternalServerException +// An internal error has occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/GetOutpost +func (c *Outposts) GetOutpost(input *GetOutpostInput) (*GetOutpostOutput, error) { + req, out := c.GetOutpostRequest(input) + return out, req.Send() +} + +// GetOutpostWithContext is the same as GetOutpost with the addition of +// the ability to pass a context and additional request options. +// +// See GetOutpost for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Outposts) GetOutpostWithContext(ctx aws.Context, input *GetOutpostInput, opts ...request.Option) (*GetOutpostOutput, error) { + req, out := c.GetOutpostRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetOutpostInstanceTypes = "GetOutpostInstanceTypes" + +// GetOutpostInstanceTypesRequest generates a "aws/request.Request" representing the +// client's request for the GetOutpostInstanceTypes operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetOutpostInstanceTypes for more information on using the GetOutpostInstanceTypes +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetOutpostInstanceTypesRequest method. +// req, resp := client.GetOutpostInstanceTypesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/GetOutpostInstanceTypes +func (c *Outposts) GetOutpostInstanceTypesRequest(input *GetOutpostInstanceTypesInput) (req *request.Request, output *GetOutpostInstanceTypesOutput) { + op := &request.Operation{ + Name: opGetOutpostInstanceTypes, + HTTPMethod: "GET", + HTTPPath: "/outposts/{OutpostId}/instanceTypes", + } + + if input == nil { + input = &GetOutpostInstanceTypesInput{} + } + + output = &GetOutpostInstanceTypesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetOutpostInstanceTypes API operation for AWS Outposts. +// +// Lists the instance types for the specified Outpost. +// +// Returns awserr.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 Outposts's +// API operation GetOutpostInstanceTypes for usage and error information. +// +// Returned Error Types: +// * ValidationException +// A parameter is not valid. +// +// * NotFoundException +// The specified request is not valid. +// +// * AccessDeniedException +// You do not have permission to perform this operation. +// +// * InternalServerException +// An internal error has occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/GetOutpostInstanceTypes +func (c *Outposts) GetOutpostInstanceTypes(input *GetOutpostInstanceTypesInput) (*GetOutpostInstanceTypesOutput, error) { + req, out := c.GetOutpostInstanceTypesRequest(input) + return out, req.Send() +} + +// GetOutpostInstanceTypesWithContext is the same as GetOutpostInstanceTypes with the addition of +// the ability to pass a context and additional request options. +// +// See GetOutpostInstanceTypes for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Outposts) GetOutpostInstanceTypesWithContext(ctx aws.Context, input *GetOutpostInstanceTypesInput, opts ...request.Option) (*GetOutpostInstanceTypesOutput, error) { + req, out := c.GetOutpostInstanceTypesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListOutposts = "ListOutposts" + +// ListOutpostsRequest generates a "aws/request.Request" representing the +// client's request for the ListOutposts operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListOutposts for more information on using the ListOutposts +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListOutpostsRequest method. +// req, resp := client.ListOutpostsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/ListOutposts +func (c *Outposts) ListOutpostsRequest(input *ListOutpostsInput) (req *request.Request, output *ListOutpostsOutput) { + op := &request.Operation{ + Name: opListOutposts, + HTTPMethod: "GET", + HTTPPath: "/outposts", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListOutpostsInput{} + } + + output = &ListOutpostsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListOutposts API operation for AWS Outposts. +// +// List the Outposts for your 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. +// +// See the AWS API reference guide for AWS Outposts's +// API operation ListOutposts for usage and error information. +// +// Returned Error Types: +// * ValidationException +// A parameter is not valid. +// +// * AccessDeniedException +// You do not have permission to perform this operation. +// +// * InternalServerException +// An internal error has occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/ListOutposts +func (c *Outposts) ListOutposts(input *ListOutpostsInput) (*ListOutpostsOutput, error) { + req, out := c.ListOutpostsRequest(input) + return out, req.Send() +} + +// ListOutpostsWithContext is the same as ListOutposts with the addition of +// the ability to pass a context and additional request options. +// +// See ListOutposts for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Outposts) ListOutpostsWithContext(ctx aws.Context, input *ListOutpostsInput, opts ...request.Option) (*ListOutpostsOutput, error) { + req, out := c.ListOutpostsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListOutpostsPages iterates over the pages of a ListOutposts operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListOutposts 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 ListOutposts operation. +// pageNum := 0 +// err := client.ListOutpostsPages(params, +// func(page *outposts.ListOutpostsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Outposts) ListOutpostsPages(input *ListOutpostsInput, fn func(*ListOutpostsOutput, bool) bool) error { + return c.ListOutpostsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListOutpostsPagesWithContext same as ListOutpostsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Outposts) ListOutpostsPagesWithContext(ctx aws.Context, input *ListOutpostsInput, fn func(*ListOutpostsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListOutpostsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListOutpostsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListOutpostsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListSites = "ListSites" + +// ListSitesRequest generates a "aws/request.Request" representing the +// client's request for the ListSites operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListSites for more information on using the ListSites +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListSitesRequest method. +// req, resp := client.ListSitesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/ListSites +func (c *Outposts) ListSitesRequest(input *ListSitesInput) (req *request.Request, output *ListSitesOutput) { + op := &request.Operation{ + Name: opListSites, + HTTPMethod: "GET", + HTTPPath: "/sites", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListSitesInput{} + } + + output = &ListSitesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListSites API operation for AWS Outposts. +// +// Lists the sites for the specified 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. +// +// See the AWS API reference guide for AWS Outposts's +// API operation ListSites for usage and error information. +// +// Returned Error Types: +// * ValidationException +// A parameter is not valid. +// +// * AccessDeniedException +// You do not have permission to perform this operation. +// +// * InternalServerException +// An internal error has occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/ListSites +func (c *Outposts) ListSites(input *ListSitesInput) (*ListSitesOutput, error) { + req, out := c.ListSitesRequest(input) + return out, req.Send() +} + +// ListSitesWithContext is the same as ListSites with the addition of +// the ability to pass a context and additional request options. +// +// See ListSites for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Outposts) ListSitesWithContext(ctx aws.Context, input *ListSitesInput, opts ...request.Option) (*ListSitesOutput, error) { + req, out := c.ListSitesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListSitesPages iterates over the pages of a ListSites operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListSites 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 ListSites operation. +// pageNum := 0 +// err := client.ListSitesPages(params, +// func(page *outposts.ListSitesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Outposts) ListSitesPages(input *ListSitesInput, fn func(*ListSitesOutput, bool) bool) error { + return c.ListSitesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSitesPagesWithContext same as ListSitesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Outposts) ListSitesPagesWithContext(ctx aws.Context, input *ListSitesInput, fn func(*ListSitesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSitesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSitesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListSitesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +// You do not have permission to perform this operation. +type AccessDeniedException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" min:"1" type:"string"` +} + +// String returns the string representation +func (s AccessDeniedException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccessDeniedException) GoString() string { + return s.String() +} + +func newErrorAccessDeniedException(v protocol.ResponseMetadata) error { + return &AccessDeniedException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *AccessDeniedException) Code() string { + return "AccessDeniedException" +} + +// Message returns the exception's message. +func (s *AccessDeniedException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *AccessDeniedException) OrigErr() error { + return nil +} + +func (s *AccessDeniedException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *AccessDeniedException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *AccessDeniedException) RequestID() string { + return s.RespMetadata.RequestID +} + +type CreateOutpostInput struct { + _ struct{} `type:"structure"` + + // The Availability Zone. + // + // You must specify AvailabilityZone or AvailabilityZoneId. + AvailabilityZone *string `min:"1" type:"string"` + + // The ID of the Availability Zone. + // + // You must specify AvailabilityZone or AvailabilityZoneId. + AvailabilityZoneId *string `min:"1" type:"string"` + + // The Outpost description. + Description *string `min:"1" type:"string"` + + // The name of the Outpost. + Name *string `min:"1" type:"string"` + + // The ID of the site. + // + // SiteId is a required field + SiteId *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateOutpostInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateOutpostInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateOutpostInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateOutpostInput"} + if s.AvailabilityZone != nil && len(*s.AvailabilityZone) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AvailabilityZone", 1)) + } + if s.AvailabilityZoneId != nil && len(*s.AvailabilityZoneId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AvailabilityZoneId", 1)) + } + if s.Description != nil && len(*s.Description) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Description", 1)) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.SiteId == nil { + invalidParams.Add(request.NewErrParamRequired("SiteId")) + } + if s.SiteId != nil && len(*s.SiteId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("SiteId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAvailabilityZone sets the AvailabilityZone field's value. +func (s *CreateOutpostInput) SetAvailabilityZone(v string) *CreateOutpostInput { + s.AvailabilityZone = &v + return s +} + +// SetAvailabilityZoneId sets the AvailabilityZoneId field's value. +func (s *CreateOutpostInput) SetAvailabilityZoneId(v string) *CreateOutpostInput { + s.AvailabilityZoneId = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *CreateOutpostInput) SetDescription(v string) *CreateOutpostInput { + s.Description = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateOutpostInput) SetName(v string) *CreateOutpostInput { + s.Name = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *CreateOutpostInput) SetSiteId(v string) *CreateOutpostInput { + s.SiteId = &v + return s +} + +type CreateOutpostOutput struct { + _ struct{} `type:"structure"` + + // Information about an Outpost. + Outpost *Outpost `type:"structure"` +} + +// String returns the string representation +func (s CreateOutpostOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateOutpostOutput) GoString() string { + return s.String() +} + +// SetOutpost sets the Outpost field's value. +func (s *CreateOutpostOutput) SetOutpost(v *Outpost) *CreateOutpostOutput { + s.Outpost = v + return s +} + +type DeleteOutpostInput struct { + _ struct{} `type:"structure"` + + // The ID of the Outpost. + // + // OutpostId is a required field + OutpostId *string `location:"uri" locationName:"OutpostId" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteOutpostInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteOutpostInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteOutpostInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteOutpostInput"} + if s.OutpostId == nil { + invalidParams.Add(request.NewErrParamRequired("OutpostId")) + } + if s.OutpostId != nil && len(*s.OutpostId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("OutpostId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetOutpostId sets the OutpostId field's value. +func (s *DeleteOutpostInput) SetOutpostId(v string) *DeleteOutpostInput { + s.OutpostId = &v + return s +} + +type DeleteOutpostOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteOutpostOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteOutpostOutput) GoString() string { + return s.String() +} + +type DeleteSiteInput struct { + _ struct{} `type:"structure"` + + // The ID of the site. + // + // SiteId is a required field + SiteId *string `location:"uri" locationName:"SiteId" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteSiteInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteSiteInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteSiteInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteSiteInput"} + if s.SiteId == nil { + invalidParams.Add(request.NewErrParamRequired("SiteId")) + } + if s.SiteId != nil && len(*s.SiteId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("SiteId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetSiteId sets the SiteId field's value. +func (s *DeleteSiteInput) SetSiteId(v string) *DeleteSiteInput { + s.SiteId = &v + return s +} + +type DeleteSiteOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteSiteOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteSiteOutput) GoString() string { + return s.String() +} + +type GetOutpostInput struct { + _ struct{} `type:"structure"` + + // The ID of the Outpost. + // + // OutpostId is a required field + OutpostId *string `location:"uri" locationName:"OutpostId" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetOutpostInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetOutpostInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetOutpostInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetOutpostInput"} + if s.OutpostId == nil { + invalidParams.Add(request.NewErrParamRequired("OutpostId")) + } + if s.OutpostId != nil && len(*s.OutpostId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("OutpostId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetOutpostId sets the OutpostId field's value. +func (s *GetOutpostInput) SetOutpostId(v string) *GetOutpostInput { + s.OutpostId = &v + return s +} + +type GetOutpostInstanceTypesInput struct { + _ struct{} `type:"structure"` + + // The maximum page size. + MaxResults *int64 `location:"querystring" locationName:"MaxResults" min:"1" type:"integer"` + + // The pagination token. + NextToken *string `location:"querystring" locationName:"NextToken" min:"1" type:"string"` + + // The ID of the Outpost. + // + // OutpostId is a required field + OutpostId *string `location:"uri" locationName:"OutpostId" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetOutpostInstanceTypesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetOutpostInstanceTypesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetOutpostInstanceTypesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetOutpostInstanceTypesInput"} + 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 s.OutpostId == nil { + invalidParams.Add(request.NewErrParamRequired("OutpostId")) + } + if s.OutpostId != nil && len(*s.OutpostId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("OutpostId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetOutpostInstanceTypesInput) SetMaxResults(v int64) *GetOutpostInstanceTypesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetOutpostInstanceTypesInput) SetNextToken(v string) *GetOutpostInstanceTypesInput { + s.NextToken = &v + return s +} + +// SetOutpostId sets the OutpostId field's value. +func (s *GetOutpostInstanceTypesInput) SetOutpostId(v string) *GetOutpostInstanceTypesInput { + s.OutpostId = &v + return s +} + +type GetOutpostInstanceTypesOutput struct { + _ struct{} `type:"structure"` + + // Information about the instance types. + InstanceTypes []*InstanceTypeItem `type:"list"` + + // The pagination token. + NextToken *string `min:"1" type:"string"` + + // The Amazon Resource Name (ARN) of the Outpost. + OutpostArn *string `min:"1" type:"string"` + + // The ID of the Outpost. + OutpostId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s GetOutpostInstanceTypesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetOutpostInstanceTypesOutput) GoString() string { + return s.String() +} + +// SetInstanceTypes sets the InstanceTypes field's value. +func (s *GetOutpostInstanceTypesOutput) SetInstanceTypes(v []*InstanceTypeItem) *GetOutpostInstanceTypesOutput { + s.InstanceTypes = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetOutpostInstanceTypesOutput) SetNextToken(v string) *GetOutpostInstanceTypesOutput { + s.NextToken = &v + return s +} + +// SetOutpostArn sets the OutpostArn field's value. +func (s *GetOutpostInstanceTypesOutput) SetOutpostArn(v string) *GetOutpostInstanceTypesOutput { + s.OutpostArn = &v + return s +} + +// SetOutpostId sets the OutpostId field's value. +func (s *GetOutpostInstanceTypesOutput) SetOutpostId(v string) *GetOutpostInstanceTypesOutput { + s.OutpostId = &v + return s +} + +type GetOutpostOutput struct { + _ struct{} `type:"structure"` + + // Information about an Outpost. + Outpost *Outpost `type:"structure"` +} + +// String returns the string representation +func (s GetOutpostOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetOutpostOutput) GoString() string { + return s.String() +} + +// SetOutpost sets the Outpost field's value. +func (s *GetOutpostOutput) SetOutpost(v *Outpost) *GetOutpostOutput { + s.Outpost = v + return s +} + +// Information about an instance type. +type InstanceTypeItem struct { + _ struct{} `type:"structure"` + + // The instance type. + InstanceType *string `type:"string"` +} + +// String returns the string representation +func (s InstanceTypeItem) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InstanceTypeItem) GoString() string { + return s.String() +} + +// SetInstanceType sets the InstanceType field's value. +func (s *InstanceTypeItem) SetInstanceType(v string) *InstanceTypeItem { + s.InstanceType = &v + return s +} + +// An internal error has occurred. +type InternalServerException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" min:"1" type:"string"` +} + +// String returns the string representation +func (s InternalServerException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InternalServerException) GoString() string { + return s.String() +} + +func newErrorInternalServerException(v protocol.ResponseMetadata) error { + return &InternalServerException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InternalServerException) Code() string { + return "InternalServerException" +} + +// Message returns the exception's message. +func (s *InternalServerException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InternalServerException) OrigErr() error { + return nil +} + +func (s *InternalServerException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InternalServerException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InternalServerException) RequestID() string { + return s.RespMetadata.RequestID +} + +type ListOutpostsInput struct { + _ struct{} `type:"structure"` + + // The maximum page size. + MaxResults *int64 `location:"querystring" locationName:"MaxResults" min:"1" type:"integer"` + + // The pagination token. + NextToken *string `location:"querystring" locationName:"NextToken" min:"1" type:"string"` +} + +// String returns the string representation +func (s ListOutpostsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListOutpostsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListOutpostsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListOutpostsInput"} + 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 *ListOutpostsInput) SetMaxResults(v int64) *ListOutpostsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListOutpostsInput) SetNextToken(v string) *ListOutpostsInput { + s.NextToken = &v + return s +} + +type ListOutpostsOutput struct { + _ struct{} `type:"structure"` + + // The pagination token. + NextToken *string `min:"1" type:"string"` + + // Information about the Outposts. + Outposts []*Outpost `type:"list"` +} + +// String returns the string representation +func (s ListOutpostsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListOutpostsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListOutpostsOutput) SetNextToken(v string) *ListOutpostsOutput { + s.NextToken = &v + return s +} + +// SetOutposts sets the Outposts field's value. +func (s *ListOutpostsOutput) SetOutposts(v []*Outpost) *ListOutpostsOutput { + s.Outposts = v + return s +} + +type ListSitesInput struct { + _ struct{} `type:"structure"` + + // The maximum page size. + MaxResults *int64 `location:"querystring" locationName:"MaxResults" min:"1" type:"integer"` + + // The pagination token. + NextToken *string `location:"querystring" locationName:"NextToken" min:"1" type:"string"` +} + +// String returns the string representation +func (s ListSitesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListSitesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListSitesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListSitesInput"} + 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 *ListSitesInput) SetMaxResults(v int64) *ListSitesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListSitesInput) SetNextToken(v string) *ListSitesInput { + s.NextToken = &v + return s +} + +type ListSitesOutput struct { + _ struct{} `type:"structure"` + + // The pagination token. + NextToken *string `min:"1" type:"string"` + + // Information about the sites. + Sites []*Site `type:"list"` +} + +// String returns the string representation +func (s ListSitesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListSitesOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListSitesOutput) SetNextToken(v string) *ListSitesOutput { + s.NextToken = &v + return s +} + +// SetSites sets the Sites field's value. +func (s *ListSitesOutput) SetSites(v []*Site) *ListSitesOutput { + s.Sites = v + return s +} + +// The specified request is not valid. +type NotFoundException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" min:"1" type:"string"` +} + +// String returns the string representation +func (s NotFoundException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s NotFoundException) GoString() string { + return s.String() +} + +func newErrorNotFoundException(v protocol.ResponseMetadata) error { + return &NotFoundException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *NotFoundException) Code() string { + return "NotFoundException" +} + +// Message returns the exception's message. +func (s *NotFoundException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *NotFoundException) OrigErr() error { + return nil +} + +func (s *NotFoundException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *NotFoundException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *NotFoundException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Information about an Outpost. +type Outpost struct { + _ struct{} `type:"structure"` + + // The Availability Zone. + // + // You must specify AvailabilityZone or AvailabilityZoneId. + AvailabilityZone *string `min:"1" type:"string"` + + // The ID of the Availability Zone. + // + // You must specify AvailabilityZone or AvailabilityZoneId. + AvailabilityZoneId *string `min:"1" type:"string"` + + // The Outpost description. + Description *string `min:"1" type:"string"` + + // The life cycle status. + LifeCycleStatus *string `type:"string"` + + // The name of the Outpost. + Name *string `min:"1" type:"string"` + + // The Amazon Resource Name (ARN) of the Outpost. + OutpostArn *string `min:"1" type:"string"` + + // The ID of the Outpost. + OutpostId *string `min:"1" type:"string"` + + // The AWS account ID of the Outpost owner. + OwnerId *string `min:"12" type:"string"` + + // The ID of the site. + SiteId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s Outpost) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Outpost) GoString() string { + return s.String() +} + +// SetAvailabilityZone sets the AvailabilityZone field's value. +func (s *Outpost) SetAvailabilityZone(v string) *Outpost { + s.AvailabilityZone = &v + return s +} + +// SetAvailabilityZoneId sets the AvailabilityZoneId field's value. +func (s *Outpost) SetAvailabilityZoneId(v string) *Outpost { + s.AvailabilityZoneId = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *Outpost) SetDescription(v string) *Outpost { + s.Description = &v + return s +} + +// SetLifeCycleStatus sets the LifeCycleStatus field's value. +func (s *Outpost) SetLifeCycleStatus(v string) *Outpost { + s.LifeCycleStatus = &v + return s +} + +// SetName sets the Name field's value. +func (s *Outpost) SetName(v string) *Outpost { + s.Name = &v + return s +} + +// SetOutpostArn sets the OutpostArn field's value. +func (s *Outpost) SetOutpostArn(v string) *Outpost { + s.OutpostArn = &v + return s +} + +// SetOutpostId sets the OutpostId field's value. +func (s *Outpost) SetOutpostId(v string) *Outpost { + s.OutpostId = &v + return s +} + +// SetOwnerId sets the OwnerId field's value. +func (s *Outpost) SetOwnerId(v string) *Outpost { + s.OwnerId = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *Outpost) SetSiteId(v string) *Outpost { + s.SiteId = &v + return s +} + +// You have exceeded a service quota. +type ServiceQuotaExceededException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" min:"1" type:"string"` +} + +// String returns the string representation +func (s ServiceQuotaExceededException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ServiceQuotaExceededException) GoString() string { + return s.String() +} + +func newErrorServiceQuotaExceededException(v protocol.ResponseMetadata) error { + return &ServiceQuotaExceededException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ServiceQuotaExceededException) Code() string { + return "ServiceQuotaExceededException" +} + +// Message returns the exception's message. +func (s *ServiceQuotaExceededException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ServiceQuotaExceededException) OrigErr() error { + return nil +} + +func (s *ServiceQuotaExceededException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ServiceQuotaExceededException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ServiceQuotaExceededException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Information about a site. +type Site struct { + _ struct{} `type:"structure"` + + // The ID of the AWS account. + AccountId *string `min:"12" type:"string"` + + // The description of the site. + Description *string `min:"1" type:"string"` + + // The name of the site. + Name *string `min:"1" type:"string"` + + // The ID of the site. + SiteId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s Site) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Site) GoString() string { + return s.String() +} + +// SetAccountId sets the AccountId field's value. +func (s *Site) SetAccountId(v string) *Site { + s.AccountId = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *Site) SetDescription(v string) *Site { + s.Description = &v + return s +} + +// SetName sets the Name field's value. +func (s *Site) SetName(v string) *Site { + s.Name = &v + return s +} + +// SetSiteId sets the SiteId field's value. +func (s *Site) SetSiteId(v string) *Site { + s.SiteId = &v + return s +} + +// A parameter is not valid. +type ValidationException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" min:"1" type:"string"` +} + +// String returns the string representation +func (s ValidationException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationException) GoString() string { + return s.String() +} + +func newErrorValidationException(v protocol.ResponseMetadata) error { + return &ValidationException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ValidationException) Code() string { + return "ValidationException" +} + +// Message returns the exception's message. +func (s *ValidationException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ValidationException) OrigErr() error { + return nil +} + +func (s *ValidationException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ValidationException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ValidationException) RequestID() string { + return s.RespMetadata.RequestID +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/outposts/doc.go b/vendor/github.com/aws/aws-sdk-go/service/outposts/doc.go new file mode 100644 index 00000000000..135c1ea07dd --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/outposts/doc.go @@ -0,0 +1,33 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package outposts provides the client and types for making API +// requests to AWS Outposts. +// +// AWS Outposts is a fully-managed service that extends AWS infrastructure, +// APIs, and tools to customer premises. By providing local access to AWS-managed +// infrastructure, AWS Outposts enables customers to build and run applications +// on premises using the same programming interfaces as in AWS Regions, while +// using local compute and storage resources for lower latency and local data +// processing needs. +// +// See https://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03 for more information on this service. +// +// See outposts package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/outposts/ +// +// Using the Client +// +// To contact AWS Outposts with the SDK use the New function to create +// a new service client. With that client you can make API requests to the service. +// These clients are safe to use concurrently. +// +// See the SDK's documentation for more information on how to use the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws.Config documentation for more information on configuring SDK clients. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Outposts client Outposts for more +// information on creating client for this service. +// https://docs.aws.amazon.com/sdk-for-go/api/service/outposts/#New +package outposts diff --git a/vendor/github.com/aws/aws-sdk-go/service/outposts/errors.go b/vendor/github.com/aws/aws-sdk-go/service/outposts/errors.go new file mode 100644 index 00000000000..7960080b390 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/outposts/errors.go @@ -0,0 +1,48 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package outposts + +import ( + "github.com/aws/aws-sdk-go/private/protocol" +) + +const ( + + // ErrCodeAccessDeniedException for service response error code + // "AccessDeniedException". + // + // You do not have permission to perform this operation. + ErrCodeAccessDeniedException = "AccessDeniedException" + + // ErrCodeInternalServerException for service response error code + // "InternalServerException". + // + // An internal error has occurred. + ErrCodeInternalServerException = "InternalServerException" + + // ErrCodeNotFoundException for service response error code + // "NotFoundException". + // + // The specified request is not valid. + ErrCodeNotFoundException = "NotFoundException" + + // ErrCodeServiceQuotaExceededException for service response error code + // "ServiceQuotaExceededException". + // + // You have exceeded a service quota. + ErrCodeServiceQuotaExceededException = "ServiceQuotaExceededException" + + // ErrCodeValidationException for service response error code + // "ValidationException". + // + // A parameter is not valid. + ErrCodeValidationException = "ValidationException" +) + +var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ + "AccessDeniedException": newErrorAccessDeniedException, + "InternalServerException": newErrorInternalServerException, + "NotFoundException": newErrorNotFoundException, + "ServiceQuotaExceededException": newErrorServiceQuotaExceededException, + "ValidationException": newErrorValidationException, +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/outposts/service.go b/vendor/github.com/aws/aws-sdk-go/service/outposts/service.go new file mode 100644 index 00000000000..e9f396cf394 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/outposts/service.go @@ -0,0 +1,104 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package outposts + +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" + "github.com/aws/aws-sdk-go/private/protocol/restjson" +) + +// Outposts provides the API operation methods for making requests to +// AWS Outposts. See this package's package overview docs +// for details on the service. +// +// Outposts methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. +type Outposts 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 = "Outposts" // Name of service. + EndpointsID = "outposts" // ID to lookup a service endpoint with. + ServiceID = "Outposts" // ServiceID is a unique identifier of a specific service. +) + +// New creates a new instance of the Outposts 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: +// mySession := session.Must(session.NewSession()) +// +// // Create a Outposts client from just a session. +// svc := outposts.New(mySession) +// +// // Create a Outposts client with additional configuration +// svc := outposts.New(mySession, aws.NewConfig().WithRegion("us-west-2")) +func New(p client.ConfigProvider, cfgs ...*aws.Config) *Outposts { + c := p.ClientConfig(EndpointsID, cfgs...) + if c.SigningNameDerived || len(c.SigningName) == 0 { + c.SigningName = "outposts" + } + return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) +} + +// newClient creates, initializes and returns a new service client instance. +func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *Outposts { + svc := &Outposts{ + Client: client.New( + cfg, + metadata.ClientInfo{ + ServiceName: ServiceName, + ServiceID: ServiceID, + SigningName: signingName, + SigningRegion: signingRegion, + PartitionID: partitionID, + Endpoint: endpoint, + APIVersion: "2019-12-03", + }, + handlers, + ), + } + + // Handlers + svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) + svc.Handlers.Build.PushBackNamed(restjson.BuildHandler) + svc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler) + svc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler) + svc.Handlers.UnmarshalError.PushBackNamed( + protocol.NewUnmarshalErrorHandler(restjson.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(), + ) + + // Run custom client initialization if present + if initClient != nil { + initClient(svc.Client) + } + + return svc +} + +// newRequest creates a new request for a Outposts operation and runs any +// custom request initialization. +func (c *Outposts) 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/personalize/api.go b/vendor/github.com/aws/aws-sdk-go/service/personalize/api.go index 77af5917c09..1ad36ef7032 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/personalize/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/personalize/api.go @@ -534,7 +534,9 @@ func (c *Personalize) CreateDatasetImportJobRequest(input *CreateDatasetImportJo // Creates a job that imports training data from your data source (an Amazon // S3 bucket) to an Amazon Personalize dataset. To allow Amazon Personalize // to import the training data, you must specify an AWS Identity and Access -// Management (IAM) role that has permission to read from the data source. +// Management (IAM) role that has permission to read from the data source, as +// Amazon Personalize makes a copy of your data and processes it in an internal +// AWS system. // // The dataset import job replaces any previous data in the dataset. // @@ -727,6 +729,95 @@ func (c *Personalize) CreateEventTrackerWithContext(ctx aws.Context, input *Crea return out, req.Send() } +const opCreateFilter = "CreateFilter" + +// CreateFilterRequest generates a "aws/request.Request" representing the +// client's request for the CreateFilter operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateFilter for more information on using the CreateFilter +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateFilterRequest method. +// req, resp := client.CreateFilterRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/CreateFilter +func (c *Personalize) CreateFilterRequest(input *CreateFilterInput) (req *request.Request, output *CreateFilterOutput) { + op := &request.Operation{ + Name: opCreateFilter, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateFilterInput{} + } + + output = &CreateFilterOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateFilter API operation for Amazon Personalize. +// +// Creates a recommendation filter. For more information, see Using Filters +// with Amazon Personalize (https://docs.aws.amazon.com/personalize/latest/dg/filters.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon Personalize's +// API operation CreateFilter for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// Provide a valid value for the field or parameter. +// +// * ResourceAlreadyExistsException +// The specified resource already exists. +// +// * ResourceNotFoundException +// Could not find the specified resource. +// +// * LimitExceededException +// The limit on the number of requests per second has been exceeded. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/CreateFilter +func (c *Personalize) CreateFilter(input *CreateFilterInput) (*CreateFilterOutput, error) { + req, out := c.CreateFilterRequest(input) + return out, req.Send() +} + +// CreateFilterWithContext is the same as CreateFilter with the addition of +// the ability to pass a context and additional request options. +// +// See CreateFilter for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Personalize) CreateFilterWithContext(ctx aws.Context, input *CreateFilterInput, opts ...request.Option) (*CreateFilterOutput, error) { + req, out := c.CreateFilterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateSchema = "CreateSchema" // CreateSchemaRequest generates a "aws/request.Request" representing the @@ -1046,6 +1137,9 @@ func (c *Personalize) CreateSolutionVersionRequest(input *CreateSolutionVersionI // * ResourceNotFoundException // Could not find the specified resource. // +// * LimitExceededException +// The limit on the number of requests per second has been exceeded. +// // * ResourceInUseException // The specified resource is in use. // @@ -1429,6 +1523,92 @@ func (c *Personalize) DeleteEventTrackerWithContext(ctx aws.Context, input *Dele return out, req.Send() } +const opDeleteFilter = "DeleteFilter" + +// DeleteFilterRequest generates a "aws/request.Request" representing the +// client's request for the DeleteFilter operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteFilter for more information on using the DeleteFilter +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteFilterRequest method. +// req, resp := client.DeleteFilterRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/DeleteFilter +func (c *Personalize) DeleteFilterRequest(input *DeleteFilterInput) (req *request.Request, output *DeleteFilterOutput) { + op := &request.Operation{ + Name: opDeleteFilter, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteFilterInput{} + } + + output = &DeleteFilterOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteFilter API operation for Amazon Personalize. +// +// Deletes a filter. +// +// Returns awserr.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 Personalize's +// API operation DeleteFilter for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// Provide a valid value for the field or parameter. +// +// * ResourceNotFoundException +// Could not find the specified resource. +// +// * ResourceInUseException +// The specified resource is in use. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/DeleteFilter +func (c *Personalize) DeleteFilter(input *DeleteFilterInput) (*DeleteFilterOutput, error) { + req, out := c.DeleteFilterRequest(input) + return out, req.Send() +} + +// DeleteFilterWithContext is the same as DeleteFilter with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteFilter for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Personalize) DeleteFilterWithContext(ctx aws.Context, input *DeleteFilterInput, opts ...request.Option) (*DeleteFilterOutput, error) { + req, out := c.DeleteFilterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteSchema = "DeleteSchema" // DeleteSchemaRequest generates a "aws/request.Request" representing the @@ -2279,6 +2459,88 @@ func (c *Personalize) DescribeFeatureTransformationWithContext(ctx aws.Context, return out, req.Send() } +const opDescribeFilter = "DescribeFilter" + +// DescribeFilterRequest generates a "aws/request.Request" representing the +// client's request for the DescribeFilter operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeFilter for more information on using the DescribeFilter +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeFilterRequest method. +// req, resp := client.DescribeFilterRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/DescribeFilter +func (c *Personalize) DescribeFilterRequest(input *DescribeFilterInput) (req *request.Request, output *DescribeFilterOutput) { + op := &request.Operation{ + Name: opDescribeFilter, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeFilterInput{} + } + + output = &DescribeFilterOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeFilter API operation for Amazon Personalize. +// +// Describes a filter's properties. +// +// Returns awserr.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 Personalize's +// API operation DescribeFilter for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// Provide a valid value for the field or parameter. +// +// * ResourceNotFoundException +// Could not find the specified resource. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/DescribeFilter +func (c *Personalize) DescribeFilter(input *DescribeFilterInput) (*DescribeFilterOutput, error) { + req, out := c.DescribeFilterRequest(input) + return out, req.Send() +} + +// DescribeFilterWithContext is the same as DescribeFilter with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeFilter for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Personalize) DescribeFilterWithContext(ctx aws.Context, input *DescribeFilterInput, opts ...request.Option) (*DescribeFilterOutput, error) { + req, out := c.DescribeFilterRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeRecipe = "DescribeRecipe" // DescribeRecipeRequest generates a "aws/request.Request" representing the @@ -3561,6 +3823,88 @@ func (c *Personalize) ListEventTrackersPagesWithContext(ctx aws.Context, input * return p.Err() } +const opListFilters = "ListFilters" + +// ListFiltersRequest generates a "aws/request.Request" representing the +// client's request for the ListFilters operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListFilters for more information on using the ListFilters +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListFiltersRequest method. +// req, resp := client.ListFiltersRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/ListFilters +func (c *Personalize) ListFiltersRequest(input *ListFiltersInput) (req *request.Request, output *ListFiltersOutput) { + op := &request.Operation{ + Name: opListFilters, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListFiltersInput{} + } + + output = &ListFiltersOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListFilters API operation for Amazon Personalize. +// +// Lists all filters that belong to a given dataset group. +// +// Returns awserr.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 Personalize's +// API operation ListFilters for usage and error information. +// +// Returned Error Types: +// * InvalidInputException +// Provide a valid value for the field or parameter. +// +// * InvalidNextTokenException +// The token is not valid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/ListFilters +func (c *Personalize) ListFilters(input *ListFiltersInput) (*ListFiltersOutput, error) { + req, out := c.ListFiltersRequest(input) + return out, req.Send() +} + +// ListFiltersWithContext is the same as ListFilters with the addition of +// the ability to pass a context and additional request options. +// +// See ListFilters for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Personalize) ListFiltersWithContext(ctx aws.Context, input *ListFiltersInput, opts ...request.Option) (*ListFiltersOutput, error) { + req, out := c.ListFiltersRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opListRecipes = "ListRecipes" // ListRecipesRequest generates a "aws/request.Request" representing the @@ -4431,12 +4775,19 @@ type BatchInferenceJob struct { // The Amazon Resource Name (ARN) of the batch inference job. BatchInferenceJobArn *string `locationName:"batchInferenceJobArn" type:"string"` + // A string to string map of the configuration details of a batch inference + // job. + BatchInferenceJobConfig *BatchInferenceJobConfig `locationName:"batchInferenceJobConfig" type:"structure"` + // The time at which the batch inference job was created. CreationDateTime *time.Time `locationName:"creationDateTime" type:"timestamp"` // If the batch inference job failed, the reason for the failure. FailureReason *string `locationName:"failureReason" type:"string"` + // The ARN of the filter used on the batch inference job. + FilterArn *string `locationName:"filterArn" type:"string"` + // The Amazon S3 path that leads to the input data used to generate the batch // inference job. JobInput *BatchInferenceJobInput `locationName:"jobInput" type:"structure"` @@ -4492,6 +4843,12 @@ func (s *BatchInferenceJob) SetBatchInferenceJobArn(v string) *BatchInferenceJob return s } +// SetBatchInferenceJobConfig sets the BatchInferenceJobConfig field's value. +func (s *BatchInferenceJob) SetBatchInferenceJobConfig(v *BatchInferenceJobConfig) *BatchInferenceJob { + s.BatchInferenceJobConfig = v + return s +} + // SetCreationDateTime sets the CreationDateTime field's value. func (s *BatchInferenceJob) SetCreationDateTime(v time.Time) *BatchInferenceJob { s.CreationDateTime = &v @@ -4504,6 +4861,12 @@ func (s *BatchInferenceJob) SetFailureReason(v string) *BatchInferenceJob { return s } +// SetFilterArn sets the FilterArn field's value. +func (s *BatchInferenceJob) SetFilterArn(v string) *BatchInferenceJob { + s.FilterArn = &v + return s +} + // SetJobInput sets the JobInput field's value. func (s *BatchInferenceJob) SetJobInput(v *BatchInferenceJobInput) *BatchInferenceJob { s.JobInput = v @@ -4552,6 +4915,31 @@ func (s *BatchInferenceJob) SetStatus(v string) *BatchInferenceJob { return s } +// The configuration details of a batch inference job. +type BatchInferenceJobConfig struct { + _ struct{} `type:"structure"` + + // A string to string map specifying the inference hyperparameters you wish + // to use for hyperparameter optimization. See customizing-solution-config-hpo. + ItemExplorationConfig map[string]*string `locationName:"itemExplorationConfig" type:"map"` +} + +// String returns the string representation +func (s BatchInferenceJobConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BatchInferenceJobConfig) GoString() string { + return s.String() +} + +// SetItemExplorationConfig sets the ItemExplorationConfig field's value. +func (s *BatchInferenceJobConfig) SetItemExplorationConfig(v map[string]*string) *BatchInferenceJobConfig { + s.ItemExplorationConfig = v + return s +} + // The input configuration of a batch inference job. type BatchInferenceJobInput struct { _ struct{} `type:"structure"` @@ -4738,6 +5126,9 @@ type Campaign struct { // The Amazon Resource Name (ARN) of the campaign. CampaignArn *string `locationName:"campaignArn" type:"string"` + // The configuration details of a campaign. + CampaignConfig *CampaignConfig `locationName:"campaignConfig" type:"structure"` + // The date and time (in Unix format) that the campaign was created. CreationDateTime *time.Time `locationName:"creationDateTime" type:"timestamp"` @@ -4787,6 +5178,12 @@ func (s *Campaign) SetCampaignArn(v string) *Campaign { return s } +// SetCampaignConfig sets the CampaignConfig field's value. +func (s *Campaign) SetCampaignConfig(v *CampaignConfig) *Campaign { + s.CampaignConfig = v + return s +} + // SetCreationDateTime sets the CreationDateTime field's value. func (s *Campaign) SetCreationDateTime(v time.Time) *Campaign { s.CreationDateTime = &v @@ -4835,6 +5232,31 @@ func (s *Campaign) SetStatus(v string) *Campaign { return s } +// The configuration details of a campaign. +type CampaignConfig struct { + _ struct{} `type:"structure"` + + // A string to string map specifying the inference hyperparameters you wish + // to use for hyperparameter optimization. See customizing-solution-config-hpo. + ItemExplorationConfig map[string]*string `locationName:"itemExplorationConfig" type:"map"` +} + +// String returns the string representation +func (s CampaignConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CampaignConfig) GoString() string { + return s.String() +} + +// SetItemExplorationConfig sets the ItemExplorationConfig field's value. +func (s *CampaignConfig) SetItemExplorationConfig(v map[string]*string) *CampaignConfig { + s.ItemExplorationConfig = v + return s +} + // Provides a summary of the properties of a campaign. For a complete listing, // call the DescribeCampaign API. type CampaignSummary struct { @@ -4916,6 +5338,9 @@ func (s *CampaignSummary) SetStatus(v string) *CampaignSummary { type CampaignUpdateSummary struct { _ struct{} `type:"structure"` + // The configuration details of a campaign. + CampaignConfig *CampaignConfig `locationName:"campaignConfig" type:"structure"` + // The date and time (in Unix time) that the campaign update was created. CreationDateTime *time.Time `locationName:"creationDateTime" type:"timestamp"` @@ -4952,6 +5377,12 @@ func (s CampaignUpdateSummary) GoString() string { return s.String() } +// SetCampaignConfig sets the CampaignConfig field's value. +func (s *CampaignUpdateSummary) SetCampaignConfig(v *CampaignConfig) *CampaignUpdateSummary { + s.CampaignConfig = v + return s +} + // SetCreationDateTime sets the CreationDateTime field's value. func (s *CampaignUpdateSummary) SetCreationDateTime(v time.Time) *CampaignUpdateSummary { s.CreationDateTime = &v @@ -5082,6 +5513,13 @@ func (s *ContinuousHyperParameterRange) SetName(v string) *ContinuousHyperParame type CreateBatchInferenceJobInput struct { _ struct{} `type:"structure"` + // The configuration details of a batch inference job. + BatchInferenceJobConfig *BatchInferenceJobConfig `locationName:"batchInferenceJobConfig" type:"structure"` + + // The ARN of the filter to apply to the batch inference job. For more information + // on using filters, see Using Filters with Amazon Personalize. + FilterArn *string `locationName:"filterArn" type:"string"` + // The Amazon S3 path that leads to the input file to base your recommendations // on. The input material must be in JSON format. // @@ -5162,6 +5600,18 @@ func (s *CreateBatchInferenceJobInput) Validate() error { return nil } +// SetBatchInferenceJobConfig sets the BatchInferenceJobConfig field's value. +func (s *CreateBatchInferenceJobInput) SetBatchInferenceJobConfig(v *BatchInferenceJobConfig) *CreateBatchInferenceJobInput { + s.BatchInferenceJobConfig = v + return s +} + +// SetFilterArn sets the FilterArn field's value. +func (s *CreateBatchInferenceJobInput) SetFilterArn(v string) *CreateBatchInferenceJobInput { + s.FilterArn = &v + return s +} + // SetJobInput sets the JobInput field's value. func (s *CreateBatchInferenceJobInput) SetJobInput(v *BatchInferenceJobInput) *CreateBatchInferenceJobInput { s.JobInput = v @@ -5224,6 +5674,9 @@ func (s *CreateBatchInferenceJobOutput) SetBatchInferenceJobArn(v string) *Creat type CreateCampaignInput struct { _ struct{} `type:"structure"` + // The configuration details of a campaign. + CampaignConfig *CampaignConfig `locationName:"campaignConfig" type:"structure"` + // Specifies the requested minimum provisioned transactions (recommendations) // per second that Amazon Personalize will support. // @@ -5277,6 +5730,12 @@ func (s *CreateCampaignInput) Validate() error { return nil } +// SetCampaignConfig sets the CampaignConfig field's value. +func (s *CreateCampaignInput) SetCampaignConfig(v *CampaignConfig) *CreateCampaignInput { + s.CampaignConfig = v + return s +} + // SetMinProvisionedTPS sets the MinProvisionedTPS field's value. func (s *CreateCampaignInput) SetMinProvisionedTPS(v int64) *CreateCampaignInput { s.MinProvisionedTPS = &v @@ -5713,6 +6172,108 @@ func (s *CreateEventTrackerOutput) SetTrackingId(v string) *CreateEventTrackerOu return s } +type CreateFilterInput struct { + _ struct{} `type:"structure"` + + // The ARN of the dataset group that the filter will belong to. + // + // DatasetGroupArn is a required field + DatasetGroupArn *string `locationName:"datasetGroupArn" type:"string" required:"true"` + + // The filter expression that designates the interaction types that the filter + // will filter out. A filter expression must follow the following format: + // + // EXCLUDE itemId WHERE INTERACTIONS.event_type in ("EVENT_TYPE") + // + // Where "EVENT_TYPE" is the type of event to filter out. To filter out all + // items with any interactions history, set "*" as the EVENT_TYPE. For more + // information, see Using Filters with Amazon Personalize (https://docs.aws.amazon.com/personalize/latest/dg/filters.html). + // + // FilterExpression is a required field + FilterExpression *string `locationName:"filterExpression" min:"1" type:"string" required:"true" sensitive:"true"` + + // The name of the filter to create. + // + // Name is a required field + Name *string `locationName:"name" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateFilterInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateFilterInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateFilterInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateFilterInput"} + if s.DatasetGroupArn == nil { + invalidParams.Add(request.NewErrParamRequired("DatasetGroupArn")) + } + if s.FilterExpression == nil { + invalidParams.Add(request.NewErrParamRequired("FilterExpression")) + } + if s.FilterExpression != nil && len(*s.FilterExpression) < 1 { + invalidParams.Add(request.NewErrParamMinLen("FilterExpression", 1)) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDatasetGroupArn sets the DatasetGroupArn field's value. +func (s *CreateFilterInput) SetDatasetGroupArn(v string) *CreateFilterInput { + s.DatasetGroupArn = &v + return s +} + +// SetFilterExpression sets the FilterExpression field's value. +func (s *CreateFilterInput) SetFilterExpression(v string) *CreateFilterInput { + s.FilterExpression = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateFilterInput) SetName(v string) *CreateFilterInput { + s.Name = &v + return s +} + +type CreateFilterOutput struct { + _ struct{} `type:"structure"` + + // The ARN of the new filter. + FilterArn *string `locationName:"filterArn" type:"string"` +} + +// String returns the string representation +func (s CreateFilterOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateFilterOutput) GoString() string { + return s.String() +} + +// SetFilterArn sets the FilterArn field's value. +func (s *CreateFilterOutput) SetFilterArn(v string) *CreateFilterOutput { + s.FilterArn = &v + return s +} + type CreateSchemaInput struct { _ struct{} `type:"structure"` @@ -7036,39 +7597,91 @@ type DeleteDatasetOutput struct { } // String returns the string representation -func (s DeleteDatasetOutput) String() string { +func (s DeleteDatasetOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteDatasetOutput) GoString() string { + return s.String() +} + +type DeleteEventTrackerInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the event tracker to delete. + // + // EventTrackerArn is a required field + EventTrackerArn *string `locationName:"eventTrackerArn" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteEventTrackerInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteEventTrackerInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteEventTrackerInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteEventTrackerInput"} + if s.EventTrackerArn == nil { + invalidParams.Add(request.NewErrParamRequired("EventTrackerArn")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetEventTrackerArn sets the EventTrackerArn field's value. +func (s *DeleteEventTrackerInput) SetEventTrackerArn(v string) *DeleteEventTrackerInput { + s.EventTrackerArn = &v + return s +} + +type DeleteEventTrackerOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteEventTrackerOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDatasetOutput) GoString() string { +func (s DeleteEventTrackerOutput) GoString() string { return s.String() } -type DeleteEventTrackerInput struct { +type DeleteFilterInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the event tracker to delete. + // The ARN of the filter to delete. // - // EventTrackerArn is a required field - EventTrackerArn *string `locationName:"eventTrackerArn" type:"string" required:"true"` + // FilterArn is a required field + FilterArn *string `locationName:"filterArn" type:"string" required:"true"` } // String returns the string representation -func (s DeleteEventTrackerInput) String() string { +func (s DeleteFilterInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteEventTrackerInput) GoString() string { +func (s DeleteFilterInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteEventTrackerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteEventTrackerInput"} - if s.EventTrackerArn == nil { - invalidParams.Add(request.NewErrParamRequired("EventTrackerArn")) +func (s *DeleteFilterInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteFilterInput"} + if s.FilterArn == nil { + invalidParams.Add(request.NewErrParamRequired("FilterArn")) } if invalidParams.Len() > 0 { @@ -7077,23 +7690,23 @@ func (s *DeleteEventTrackerInput) Validate() error { return nil } -// SetEventTrackerArn sets the EventTrackerArn field's value. -func (s *DeleteEventTrackerInput) SetEventTrackerArn(v string) *DeleteEventTrackerInput { - s.EventTrackerArn = &v +// SetFilterArn sets the FilterArn field's value. +func (s *DeleteFilterInput) SetFilterArn(v string) *DeleteFilterInput { + s.FilterArn = &v return s } -type DeleteEventTrackerOutput struct { +type DeleteFilterOutput struct { _ struct{} `type:"structure"` } // String returns the string representation -func (s DeleteEventTrackerOutput) String() string { +func (s DeleteFilterOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteEventTrackerOutput) GoString() string { +func (s DeleteFilterOutput) GoString() string { return s.String() } @@ -7699,6 +8312,67 @@ func (s *DescribeFeatureTransformationOutput) SetFeatureTransformation(v *Featur return s } +type DescribeFilterInput struct { + _ struct{} `type:"structure"` + + // The ARN of the filter to describe. + // + // FilterArn is a required field + FilterArn *string `locationName:"filterArn" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeFilterInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeFilterInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeFilterInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeFilterInput"} + if s.FilterArn == nil { + invalidParams.Add(request.NewErrParamRequired("FilterArn")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetFilterArn sets the FilterArn field's value. +func (s *DescribeFilterInput) SetFilterArn(v string) *DescribeFilterInput { + s.FilterArn = &v + return s +} + +type DescribeFilterOutput struct { + _ struct{} `type:"structure"` + + // The filter's details. + Filter *Filter `locationName:"filter" type:"structure"` +} + +// String returns the string representation +func (s DescribeFilterOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeFilterOutput) GoString() string { + return s.String() +} + +// SetFilter sets the Filter field's value. +func (s *DescribeFilterOutput) SetFilter(v *Filter) *DescribeFilterOutput { + s.Filter = v + return s +} + type DescribeRecipeInput struct { _ struct{} `type:"structure"` @@ -8180,6 +8854,178 @@ func (s *FeatureTransformation) SetStatus(v string) *FeatureTransformation { return s } +// Contains information on a recommendation filter, including its ARN, status, +// and filter expression. +type Filter struct { + _ struct{} `type:"structure"` + + // The time at which the filter was created. + CreationDateTime *time.Time `locationName:"creationDateTime" type:"timestamp"` + + // The ARN of the dataset group to which the filter belongs. + DatasetGroupArn *string `locationName:"datasetGroupArn" type:"string"` + + // If the filter failed, the reason for its failure. + FailureReason *string `locationName:"failureReason" type:"string"` + + // The ARN of the filter. + FilterArn *string `locationName:"filterArn" type:"string"` + + // Specifies the type of item interactions to filter out of recommendation results. + // The filter expression must follow the following format: + // + // EXCLUDE itemId WHERE INTERACTIONS.event_type in ("EVENT_TYPE") + // + // Where "EVENT_TYPE" is the type of event to filter out. For more information, + // see Using Filters with Amazon Personalize (https://docs.aws.amazon.com/personalize/latest/dg/filters.html). + FilterExpression *string `locationName:"filterExpression" min:"1" type:"string" sensitive:"true"` + + // The time at which the filter was last updated. + LastUpdatedDateTime *time.Time `locationName:"lastUpdatedDateTime" type:"timestamp"` + + // The name of the filter. + Name *string `locationName:"name" min:"1" type:"string"` + + // The status of the filter. + Status *string `locationName:"status" type:"string"` +} + +// String returns the string representation +func (s Filter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Filter) GoString() string { + return s.String() +} + +// SetCreationDateTime sets the CreationDateTime field's value. +func (s *Filter) SetCreationDateTime(v time.Time) *Filter { + s.CreationDateTime = &v + return s +} + +// SetDatasetGroupArn sets the DatasetGroupArn field's value. +func (s *Filter) SetDatasetGroupArn(v string) *Filter { + s.DatasetGroupArn = &v + return s +} + +// SetFailureReason sets the FailureReason field's value. +func (s *Filter) SetFailureReason(v string) *Filter { + s.FailureReason = &v + return s +} + +// SetFilterArn sets the FilterArn field's value. +func (s *Filter) SetFilterArn(v string) *Filter { + s.FilterArn = &v + return s +} + +// SetFilterExpression sets the FilterExpression field's value. +func (s *Filter) SetFilterExpression(v string) *Filter { + s.FilterExpression = &v + return s +} + +// SetLastUpdatedDateTime sets the LastUpdatedDateTime field's value. +func (s *Filter) SetLastUpdatedDateTime(v time.Time) *Filter { + s.LastUpdatedDateTime = &v + return s +} + +// SetName sets the Name field's value. +func (s *Filter) SetName(v string) *Filter { + s.Name = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *Filter) SetStatus(v string) *Filter { + s.Status = &v + return s +} + +// A short summary of a filter's attributes. +type FilterSummary struct { + _ struct{} `type:"structure"` + + // The time at which the filter was created. + CreationDateTime *time.Time `locationName:"creationDateTime" type:"timestamp"` + + // The ARN of the dataset group to which the filter belongs. + DatasetGroupArn *string `locationName:"datasetGroupArn" type:"string"` + + // If the filter failed, the reason for the failure. + FailureReason *string `locationName:"failureReason" type:"string"` + + // The ARN of the filter. + FilterArn *string `locationName:"filterArn" type:"string"` + + // The time at which the filter was last updated. + LastUpdatedDateTime *time.Time `locationName:"lastUpdatedDateTime" type:"timestamp"` + + // The name of the filter. + Name *string `locationName:"name" min:"1" type:"string"` + + // The status of the filter. + Status *string `locationName:"status" type:"string"` +} + +// String returns the string representation +func (s FilterSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FilterSummary) GoString() string { + return s.String() +} + +// SetCreationDateTime sets the CreationDateTime field's value. +func (s *FilterSummary) SetCreationDateTime(v time.Time) *FilterSummary { + s.CreationDateTime = &v + return s +} + +// SetDatasetGroupArn sets the DatasetGroupArn field's value. +func (s *FilterSummary) SetDatasetGroupArn(v string) *FilterSummary { + s.DatasetGroupArn = &v + return s +} + +// SetFailureReason sets the FailureReason field's value. +func (s *FilterSummary) SetFailureReason(v string) *FilterSummary { + s.FailureReason = &v + return s +} + +// SetFilterArn sets the FilterArn field's value. +func (s *FilterSummary) SetFilterArn(v string) *FilterSummary { + s.FilterArn = &v + return s +} + +// SetLastUpdatedDateTime sets the LastUpdatedDateTime field's value. +func (s *FilterSummary) SetLastUpdatedDateTime(v time.Time) *FilterSummary { + s.LastUpdatedDateTime = &v + return s +} + +// SetName sets the Name field's value. +func (s *FilterSummary) SetName(v string) *FilterSummary { + s.Name = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *FilterSummary) SetStatus(v string) *FilterSummary { + s.Status = &v + return s +} + type GetSolutionMetricsInput struct { _ struct{} `type:"structure"` @@ -9201,6 +10047,93 @@ func (s *ListEventTrackersOutput) SetNextToken(v string) *ListEventTrackersOutpu return s } +type ListFiltersInput struct { + _ struct{} `type:"structure"` + + // The ARN of the dataset group that contains the filters. + DatasetGroupArn *string `locationName:"datasetGroupArn" type:"string"` + + // The maximum number of filters to return. + MaxResults *int64 `locationName:"maxResults" min:"1" type:"integer"` + + // A token returned from the previous call to ListFilters for getting the next + // set of filters (if they exist). + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s ListFiltersInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListFiltersInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListFiltersInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListFiltersInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDatasetGroupArn sets the DatasetGroupArn field's value. +func (s *ListFiltersInput) SetDatasetGroupArn(v string) *ListFiltersInput { + s.DatasetGroupArn = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListFiltersInput) SetMaxResults(v int64) *ListFiltersInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListFiltersInput) SetNextToken(v string) *ListFiltersInput { + s.NextToken = &v + return s +} + +type ListFiltersOutput struct { + _ struct{} `type:"structure"` + + // A list of returned filters. + Filters []*FilterSummary `type:"list"` + + // A token for getting the next set of filters (if they exist). + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s ListFiltersOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListFiltersOutput) GoString() string { + return s.String() +} + +// SetFilters sets the Filters field's value. +func (s *ListFiltersOutput) SetFilters(v []*FilterSummary) *ListFiltersOutput { + s.Filters = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListFiltersOutput) SetNextToken(v string) *ListFiltersOutput { + s.NextToken = &v + return s +} + type ListRecipesInput struct { _ struct{} `type:"structure"` @@ -10488,6 +11421,9 @@ type UpdateCampaignInput struct { // CampaignArn is a required field CampaignArn *string `locationName:"campaignArn" type:"string" required:"true"` + // The configuration details of a campaign. + CampaignConfig *CampaignConfig `locationName:"campaignConfig" type:"structure"` + // Specifies the requested minimum provisioned transactions (recommendations) // per second that Amazon Personalize will support. MinProvisionedTPS *int64 `locationName:"minProvisionedTPS" min:"1" type:"integer"` @@ -10528,6 +11464,12 @@ func (s *UpdateCampaignInput) SetCampaignArn(v string) *UpdateCampaignInput { return s } +// SetCampaignConfig sets the CampaignConfig field's value. +func (s *UpdateCampaignInput) SetCampaignConfig(v *CampaignConfig) *UpdateCampaignInput { + s.CampaignConfig = v + return s +} + // SetMinProvisionedTPS sets the MinProvisionedTPS field's value. func (s *UpdateCampaignInput) SetMinProvisionedTPS(v int64) *UpdateCampaignInput { s.MinProvisionedTPS = &v @@ -10568,6 +11510,13 @@ const ( RecipeProviderService = "SERVICE" ) +// RecipeProvider_Values returns all elements of the RecipeProvider enum +func RecipeProvider_Values() []string { + return []string{ + RecipeProviderService, + } +} + const ( // TrainingModeFull is a TrainingMode enum value TrainingModeFull = "FULL" @@ -10575,3 +11524,11 @@ const ( // TrainingModeUpdate is a TrainingMode enum value TrainingModeUpdate = "UPDATE" ) + +// TrainingMode_Values returns all elements of the TrainingMode enum +func TrainingMode_Values() []string { + return []string{ + TrainingModeFull, + TrainingModeUpdate, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/pinpoint/api.go b/vendor/github.com/aws/aws-sdk-go/service/pinpoint/api.go index d0798a85c60..e55bf8b0a74 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/pinpoint/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/pinpoint/api.go @@ -12569,6 +12569,10 @@ func (s *ActivitiesResponse) SetNextToken(v string) *ActivitiesResponse { type Activity struct { _ struct{} `type:"structure"` + // The settings for a custom message activity. This type of activity calls an + // AWS Lambda function or web hook that sends messages to participants. + CUSTOM *CustomMessageActivity `type:"structure"` + // The settings for a yes/no split activity. This type of activity sends participants // down one of two paths in a journey, based on conditions that you specify. ConditionalSplit *ConditionalSplitActivity `type:"structure"` @@ -12589,11 +12593,19 @@ type Activity struct { // path) in a journey, based on conditions that you specify. MultiCondition *MultiConditionalSplitActivity `type:"structure"` + // The settings for a push notification activity. This type of activity sends + // a push notification to participants. + PUSH *PushMessageActivity `type:"structure"` + // The settings for a random split activity. This type of activity randomly // sends specified percentages of participants down one of as many as five paths // in a journey, based on conditions that you specify. RandomSplit *RandomSplitActivity `type:"structure"` + // The settings for an SMS activity. This type of activity sends a text message + // to participants. + SMS *SMSMessageActivity `type:"structure"` + // The settings for a wait activity. This type of activity waits for a certain // amount of time or until a specific date and time before moving participants // to the next activity in a journey. @@ -12635,6 +12647,12 @@ func (s *Activity) Validate() error { return nil } +// SetCUSTOM sets the CUSTOM field's value. +func (s *Activity) SetCUSTOM(v *CustomMessageActivity) *Activity { + s.CUSTOM = v + return s +} + // SetConditionalSplit sets the ConditionalSplit field's value. func (s *Activity) SetConditionalSplit(v *ConditionalSplitActivity) *Activity { s.ConditionalSplit = v @@ -12665,12 +12683,24 @@ func (s *Activity) SetMultiCondition(v *MultiConditionalSplitActivity) *Activity return s } +// SetPUSH sets the PUSH field's value. +func (s *Activity) SetPUSH(v *PushMessageActivity) *Activity { + s.PUSH = v + return s +} + // SetRandomSplit sets the RandomSplit field's value. func (s *Activity) SetRandomSplit(v *RandomSplitActivity) *Activity { s.RandomSplit = v return s } +// SetSMS sets the SMS field's value. +func (s *Activity) SetSMS(v *SMSMessageActivity) *Activity { + s.SMS = v + return s +} + // SetWait sets the Wait field's value. func (s *Activity) SetWait(v *WaitActivity) *Activity { s.Wait = v @@ -14452,10 +14482,10 @@ type CampaignSmsMessage struct { // The body of the SMS message. Body *string `type:"string"` - // The type of SMS message. Valid values are: TRANSACTIONAL, the message is - // critical or time-sensitive, such as a one-time password that supports a customer - // transaction; and, PROMOTIONAL, the message isn't critical or time-sensitive, - // such as a marketing message. + // The SMS message type. Valid values are TRANSACTIONAL (for messages that are + // critical or time-sensitive, such as a one-time passwords) and PROMOTIONAL + // (for messsages that aren't critical or time-sensitive, such as marketing + // messages). MessageType *string `type:"string" enum:"MessageType"` // The sender ID to display on recipients' devices when they receive the SMS @@ -16029,6 +16059,97 @@ func (s *CustomDeliveryConfiguration) SetEndpointTypes(v []*string) *CustomDeliv return s } +// The settings for a custom message activity. This type of activity calls an +// AWS Lambda function or web hook that sends messages to participants. +type CustomMessageActivity struct { + _ struct{} `type:"structure"` + + // The destination to send the custom message to. This value can be one of the + // following: + // + // * The name or Amazon Resource Name (ARN) of an AWS Lambda function to + // invoke to handle delivery of the custom message. + // + // * The URL for a web application or service that supports HTTPS and can + // receive the message. The URL has to be a full URL, including the HTTPS + // protocol. + DeliveryUri *string `type:"string"` + + // The types of endpoints to send the custom message to. Each valid value maps + // to a type of channel that you can associate with an endpoint by using the + // ChannelType property of an endpoint. + EndpointTypes []*string `type:"list"` + + // Specifies the message data included in a custom channel message that's sent + // to participants in a journey. + MessageConfig *JourneyCustomMessage `type:"structure"` + + // The unique identifier for the next activity to perform, after Amazon Pinpoint + // calls the AWS Lambda function or web hook. + NextActivity *string `type:"string"` + + // The name of the custom message template to use for the message. If specified, + // this value must match the name of an existing message template. + TemplateName *string `type:"string"` + + // The unique identifier for the version of the message template to use for + // the message. If specified, this value must match the identifier for an existing + // template version. To retrieve a list of versions and version identifiers + // for a template, use the Template Versions resource. + // + // If you don't specify a value for this property, Amazon Pinpoint uses the + // active version of the template. The active version is typically the version + // of a template that's been most recently reviewed and approved for use, depending + // on your workflow. It isn't necessarily the latest version of a template. + TemplateVersion *string `type:"string"` +} + +// String returns the string representation +func (s CustomMessageActivity) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CustomMessageActivity) GoString() string { + return s.String() +} + +// SetDeliveryUri sets the DeliveryUri field's value. +func (s *CustomMessageActivity) SetDeliveryUri(v string) *CustomMessageActivity { + s.DeliveryUri = &v + return s +} + +// SetEndpointTypes sets the EndpointTypes field's value. +func (s *CustomMessageActivity) SetEndpointTypes(v []*string) *CustomMessageActivity { + s.EndpointTypes = v + return s +} + +// SetMessageConfig sets the MessageConfig field's value. +func (s *CustomMessageActivity) SetMessageConfig(v *JourneyCustomMessage) *CustomMessageActivity { + s.MessageConfig = v + return s +} + +// SetNextActivity sets the NextActivity field's value. +func (s *CustomMessageActivity) SetNextActivity(v string) *CustomMessageActivity { + s.NextActivity = &v + return s +} + +// SetTemplateName sets the TemplateName field's value. +func (s *CustomMessageActivity) SetTemplateName(v string) *CustomMessageActivity { + s.TemplateName = &v + return s +} + +// SetTemplateVersion sets the TemplateVersion field's value. +func (s *CustomMessageActivity) SetTemplateVersion(v string) *CustomMessageActivity { + s.TemplateVersion = &v + return s +} + // Specifies the default message for all channels. type DefaultMessage struct { _ struct{} `type:"structure"` @@ -18218,14 +18339,16 @@ func (s *EmailMessage) SetSubstitutions(v map[string][]*string) *EmailMessage { type EmailMessageActivity struct { _ struct{} `type:"structure"` - // The "From" address to use for the message. + // Specifies the sender address for an email message that's sent to participants + // in the journey. MessageConfig *JourneyEmailMessage `type:"structure"` // The unique identifier for the next activity to perform, after the message // is sent. NextActivity *string `type:"string"` - // The name of the email template to use for the message. + // The name of the email message template to use for the message. If specified, + // this value must match the name of an existing message template. TemplateName *string `type:"string"` // The unique identifier for the version of the email template to use for the @@ -25025,6 +25148,31 @@ func (s *ItemResponse) SetEventsItemResponse(v map[string]*EventItemResponse) *I return s } +// Specifies the message content for a custom channel message that's sent to +// participants in a journey. +type JourneyCustomMessage struct { + _ struct{} `type:"structure"` + + // The message content that's passed to an AWS Lambda function or to a web hook. + Data *string `type:"string"` +} + +// String returns the string representation +func (s JourneyCustomMessage) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s JourneyCustomMessage) GoString() string { + return s.String() +} + +// SetData sets the Data field's value. +func (s *JourneyCustomMessage) SetData(v string) *JourneyCustomMessage { + s.Data = &v + return s +} + // Provides the results of a query that retrieved the data for a standard engagement // metric that applies to a journey, and provides information about that query. type JourneyDateRangeKpiResponse struct { @@ -25200,7 +25348,7 @@ type JourneyExecutionActivityMetricsResponse struct { // A JSON object that contains the results of the query. The results vary depending // on the type of activity (ActivityType). For information about the structure - // and contents of the results, see the Amazon Pinpoint Developer Guide (https://docs.aws.amazon.com/pinpoint/latest/developerguide/welcome.html). + // and contents of the results, see the Amazon Pinpoint Developer Guide (https://docs.aws.amazon.com/pinpoint/latest/developerguide/analytics-standard-metrics.html). // // Metrics is a required field Metrics map[string]*string `type:"map" required:"true"` @@ -25275,7 +25423,7 @@ type JourneyExecutionMetricsResponse struct { // A JSON object that contains the results of the query. For information about // the structure and contents of the results, see the Amazon Pinpoint Developer - // Guide (https://docs.aws.amazon.com/pinpoint/latest/developerguide/welcome.html). + // Guide (https://docs.aws.amazon.com/pinpoint/latest/developerguide/analytics-standard-metrics.html). // // Metrics is a required field Metrics map[string]*string `type:"map" required:"true"` @@ -25361,6 +25509,39 @@ func (s *JourneyLimits) SetMessagesPerSecond(v int64) *JourneyLimits { return s } +// Specifies the message configuration for a push notification that's sent to +// participants in a journey. +type JourneyPushMessage struct { + _ struct{} `type:"structure"` + + // The number of seconds that the push notification service should keep the + // message, if the service is unable to deliver the notification the first time. + // This value is converted to an expiration value when it's sent to a push-notification + // service. If this value is 0, the service treats the notification as if it + // expires immediately and the service doesn't store or try to deliver the notification + // again. + // + // This value doesn't apply to messages that are sent through the Amazon Device + // Messaging (ADM) service. + TimeToLive *string `type:"string"` +} + +// String returns the string representation +func (s JourneyPushMessage) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s JourneyPushMessage) GoString() string { + return s.String() +} + +// SetTimeToLive sets the TimeToLive field's value. +func (s *JourneyPushMessage) SetTimeToLive(v string) *JourneyPushMessage { + s.TimeToLive = &v + return s +} + // Provides information about the status, configuration, and other settings // for a journey. type JourneyResponse struct { @@ -25559,6 +25740,46 @@ func (s *JourneyResponse) SetTags(v map[string]*string) *JourneyResponse { return s } +// Specifies the sender ID and message type for an SMS message that's sent to +// participants in a journey. +type JourneySMSMessage struct { + _ struct{} `type:"structure"` + + // The SMS message type. Valid values are TRANSACTIONAL (for messages that are + // critical or time-sensitive, such as a one-time passwords) and PROMOTIONAL + // (for messsages that aren't critical or time-sensitive, such as marketing + // messages). + MessageType *string `type:"string" enum:"MessageType"` + + // The sender ID to display as the sender of the message on a recipient's device. + // Support for sender IDs varies by country or region. For more information, + // see Supported Countries and Regions (https://docs.aws.amazon.com.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html) + // in the Amazon Pinpoint User Guide. + SenderId *string `type:"string"` +} + +// String returns the string representation +func (s JourneySMSMessage) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s JourneySMSMessage) GoString() string { + return s.String() +} + +// SetMessageType sets the MessageType field's value. +func (s *JourneySMSMessage) SetMessageType(v string) *JourneySMSMessage { + s.MessageType = &v + return s +} + +// SetSenderId sets the SenderId field's value. +func (s *JourneySMSMessage) SetSenderId(v string) *JourneySMSMessage { + s.SenderId = &v + return s +} + // Specifies the schedule settings for a journey. type JourneySchedule struct { _ struct{} `type:"structure"` @@ -27280,6 +27501,69 @@ func (s *PublicEndpoint) SetUser(v *EndpointUser) *PublicEndpoint { return s } +// Specifies the settings for a push notification activity in a journey. This +// type of activity sends a push notification to participants. +type PushMessageActivity struct { + _ struct{} `type:"structure"` + + // Specifies the time to live (TTL) value for push notifications that are sent + // to participants in a journey. + MessageConfig *JourneyPushMessage `type:"structure"` + + // The unique identifier for the next activity to perform, after the message + // is sent. + NextActivity *string `type:"string"` + + // The name of the push notification template to use for the message. If specified, + // this value must match the name of an existing message template. + TemplateName *string `type:"string"` + + // The unique identifier for the version of the push notification template to + // use for the message. If specified, this value must match the identifier for + // an existing template version. To retrieve a list of versions and version + // identifiers for a template, use the Template Versions resource. + // + // If you don't specify a value for this property, Amazon Pinpoint uses the + // active version of the template. The active version is typically the version + // of a template that's been most recently reviewed and approved for use, depending + // on your workflow. It isn't necessarily the latest version of a template. + TemplateVersion *string `type:"string"` +} + +// String returns the string representation +func (s PushMessageActivity) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PushMessageActivity) GoString() string { + return s.String() +} + +// SetMessageConfig sets the MessageConfig field's value. +func (s *PushMessageActivity) SetMessageConfig(v *JourneyPushMessage) *PushMessageActivity { + s.MessageConfig = v + return s +} + +// SetNextActivity sets the NextActivity field's value. +func (s *PushMessageActivity) SetNextActivity(v string) *PushMessageActivity { + s.NextActivity = &v + return s +} + +// SetTemplateName sets the TemplateName field's value. +func (s *PushMessageActivity) SetTemplateName(v string) *PushMessageActivity { + s.TemplateName = &v + return s +} + +// SetTemplateVersion sets the TemplateVersion field's value. +func (s *PushMessageActivity) SetTemplateVersion(v string) *PushMessageActivity { + s.TemplateVersion = &v + return s +} + // Specifies the content and settings for a message template that can be used // in messages that are sent through a push notification channel. type PushNotificationTemplateRequest struct { @@ -28499,10 +28783,10 @@ type SMSMessage struct { // The URL of an image or video to display in the SMS message. MediaUrl *string `type:"string"` - // The SMS message type. Valid values are: TRANSACTIONAL, the message is critical - // or time-sensitive, such as a one-time password that supports a customer transaction; - // and, PROMOTIONAL, the message is not critical or time-sensitive, such as - // a marketing message. + // The SMS message type. Valid values are TRANSACTIONAL (for messages that are + // critical or time-sensitive, such as a one-time passwords) and PROMOTIONAL + // (for messsages that aren't critical or time-sensitive, such as marketing + // messages). MessageType *string `type:"string" enum:"MessageType"` // The number to send the SMS message from. This value should be one of the @@ -28572,6 +28856,69 @@ func (s *SMSMessage) SetSubstitutions(v map[string][]*string) *SMSMessage { return s } +// Specifies the settings for an SMS activity in a journey. This type of activity +// sends a text message to participants. +type SMSMessageActivity struct { + _ struct{} `type:"structure"` + + // Specifies the sender ID and message type for an SMS message that's sent to + // participants in a journey. + MessageConfig *JourneySMSMessage `type:"structure"` + + // The unique identifier for the next activity to perform, after the message + // is sent. + NextActivity *string `type:"string"` + + // The name of the SMS message template to use for the message. If specified, + // this value must match the name of an existing message template. + TemplateName *string `type:"string"` + + // The unique identifier for the version of the SMS template to use for the + // message. If specified, this value must match the identifier for an existing + // template version. To retrieve a list of versions and version identifiers + // for a template, use the Template Versions resource. + // + // If you don't specify a value for this property, Amazon Pinpoint uses the + // active version of the template. The active version is typically the version + // of a template that's been most recently reviewed and approved for use, depending + // on your workflow. It isn't necessarily the latest version of a template. + TemplateVersion *string `type:"string"` +} + +// String returns the string representation +func (s SMSMessageActivity) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SMSMessageActivity) GoString() string { + return s.String() +} + +// SetMessageConfig sets the MessageConfig field's value. +func (s *SMSMessageActivity) SetMessageConfig(v *JourneySMSMessage) *SMSMessageActivity { + s.MessageConfig = v + return s +} + +// SetNextActivity sets the NextActivity field's value. +func (s *SMSMessageActivity) SetNextActivity(v string) *SMSMessageActivity { + s.NextActivity = &v + return s +} + +// SetTemplateName sets the TemplateName field's value. +func (s *SMSMessageActivity) SetTemplateName(v string) *SMSMessageActivity { + s.TemplateName = &v + return s +} + +// SetTemplateVersion sets the TemplateVersion field's value. +func (s *SMSMessageActivity) SetTemplateVersion(v string) *SMSMessageActivity { + s.TemplateVersion = &v + return s +} + // Specifies the content and settings for a message template that can be used // in text messages that are sent through the SMS channel. type SMSTemplateRequest struct { @@ -34613,6 +34960,15 @@ const ( ActionUrl = "URL" ) +// Action_Values returns all elements of the Action enum +func Action_Values() []string { + return []string{ + ActionOpenApp, + ActionDeepLink, + ActionUrl, + } +} + const ( // AttributeTypeInclusive is a AttributeType enum value AttributeTypeInclusive = "INCLUSIVE" @@ -34621,6 +34977,14 @@ const ( AttributeTypeExclusive = "EXCLUSIVE" ) +// AttributeType_Values returns all elements of the AttributeType enum +func AttributeType_Values() []string { + return []string{ + AttributeTypeInclusive, + AttributeTypeExclusive, + } +} + const ( // CampaignStatusScheduled is a CampaignStatus enum value CampaignStatusScheduled = "SCHEDULED" @@ -34641,7 +35005,22 @@ const ( CampaignStatusDeleted = "DELETED" ) +// CampaignStatus_Values returns all elements of the CampaignStatus enum +func CampaignStatus_Values() []string { + return []string{ + CampaignStatusScheduled, + CampaignStatusExecuting, + CampaignStatusPendingNextRun, + CampaignStatusCompleted, + CampaignStatusPaused, + CampaignStatusDeleted, + } +} + const ( + // ChannelTypePush is a ChannelType enum value + ChannelTypePush = "PUSH" + // ChannelTypeGcm is a ChannelType enum value ChannelTypeGcm = "GCM" @@ -34676,6 +35055,24 @@ const ( ChannelTypeCustom = "CUSTOM" ) +// ChannelType_Values returns all elements of the ChannelType enum +func ChannelType_Values() []string { + return []string{ + ChannelTypePush, + ChannelTypeGcm, + ChannelTypeApns, + ChannelTypeApnsSandbox, + ChannelTypeApnsVoip, + ChannelTypeApnsVoipSandbox, + ChannelTypeAdm, + ChannelTypeSms, + ChannelTypeVoice, + ChannelTypeEmail, + ChannelTypeBaidu, + ChannelTypeCustom, + } +} + const ( // DeliveryStatusSuccessful is a DeliveryStatus enum value DeliveryStatusSuccessful = "SUCCESSFUL" @@ -34699,6 +35096,19 @@ const ( DeliveryStatusDuplicate = "DUPLICATE" ) +// DeliveryStatus_Values returns all elements of the DeliveryStatus enum +func DeliveryStatus_Values() []string { + return []string{ + DeliveryStatusSuccessful, + DeliveryStatusThrottled, + DeliveryStatusTemporaryFailure, + DeliveryStatusPermanentFailure, + DeliveryStatusUnknownFailure, + DeliveryStatusOptOut, + DeliveryStatusDuplicate, + } +} + const ( // DimensionTypeInclusive is a DimensionType enum value DimensionTypeInclusive = "INCLUSIVE" @@ -34707,6 +35117,14 @@ const ( DimensionTypeExclusive = "EXCLUSIVE" ) +// DimensionType_Values returns all elements of the DimensionType enum +func DimensionType_Values() []string { + return []string{ + DimensionTypeInclusive, + DimensionTypeExclusive, + } +} + const ( // DurationHr24 is a Duration enum value DurationHr24 = "HR_24" @@ -34721,7 +35139,20 @@ const ( DurationDay30 = "DAY_30" ) +// Duration_Values returns all elements of the Duration enum +func Duration_Values() []string { + return []string{ + DurationHr24, + DurationDay7, + DurationDay14, + DurationDay30, + } +} + const ( + // EndpointTypesElementPush is a EndpointTypesElement enum value + EndpointTypesElementPush = "PUSH" + // EndpointTypesElementGcm is a EndpointTypesElement enum value EndpointTypesElementGcm = "GCM" @@ -34756,6 +35187,24 @@ const ( EndpointTypesElementCustom = "CUSTOM" ) +// EndpointTypesElement_Values returns all elements of the EndpointTypesElement enum +func EndpointTypesElement_Values() []string { + return []string{ + EndpointTypesElementPush, + EndpointTypesElementGcm, + EndpointTypesElementApns, + EndpointTypesElementApnsSandbox, + EndpointTypesElementApnsVoip, + EndpointTypesElementApnsVoipSandbox, + EndpointTypesElementAdm, + EndpointTypesElementSms, + EndpointTypesElementVoice, + EndpointTypesElementEmail, + EndpointTypesElementBaidu, + EndpointTypesElementCustom, + } +} + const ( // FilterTypeSystem is a FilterType enum value FilterTypeSystem = "SYSTEM" @@ -34764,6 +35213,14 @@ const ( FilterTypeEndpoint = "ENDPOINT" ) +// FilterType_Values returns all elements of the FilterType enum +func FilterType_Values() []string { + return []string{ + FilterTypeSystem, + FilterTypeEndpoint, + } +} + const ( // FormatCsv is a Format enum value FormatCsv = "CSV" @@ -34772,6 +35229,14 @@ const ( FormatJson = "JSON" ) +// Format_Values returns all elements of the Format enum +func Format_Values() []string { + return []string{ + FormatCsv, + FormatJson, + } +} + const ( // FrequencyOnce is a Frequency enum value FrequencyOnce = "ONCE" @@ -34792,6 +35257,18 @@ const ( FrequencyEvent = "EVENT" ) +// Frequency_Values returns all elements of the Frequency enum +func Frequency_Values() []string { + return []string{ + FrequencyOnce, + FrequencyHourly, + FrequencyDaily, + FrequencyWeekly, + FrequencyMonthly, + FrequencyEvent, + } +} + const ( // IncludeAll is a Include enum value IncludeAll = "ALL" @@ -34803,6 +35280,15 @@ const ( IncludeNone = "NONE" ) +// Include_Values returns all elements of the Include enum +func Include_Values() []string { + return []string{ + IncludeAll, + IncludeAny, + IncludeNone, + } +} + const ( // JobStatusCreated is a JobStatus enum value JobStatusCreated = "CREATED" @@ -34832,6 +35318,21 @@ const ( JobStatusFailed = "FAILED" ) +// JobStatus_Values returns all elements of the JobStatus enum +func JobStatus_Values() []string { + return []string{ + JobStatusCreated, + JobStatusPreparingForInitialization, + JobStatusInitializing, + JobStatusProcessing, + JobStatusPendingJob, + JobStatusCompleting, + JobStatusCompleted, + JobStatusFailing, + JobStatusFailed, + } +} + const ( // MessageTypeTransactional is a MessageType enum value MessageTypeTransactional = "TRANSACTIONAL" @@ -34840,6 +35341,14 @@ const ( MessageTypePromotional = "PROMOTIONAL" ) +// MessageType_Values returns all elements of the MessageType enum +func MessageType_Values() []string { + return []string{ + MessageTypeTransactional, + MessageTypePromotional, + } +} + const ( // ModeDelivery is a Mode enum value ModeDelivery = "DELIVERY" @@ -34848,6 +35357,14 @@ const ( ModeFilter = "FILTER" ) +// Mode_Values returns all elements of the Mode enum +func Mode_Values() []string { + return []string{ + ModeDelivery, + ModeFilter, + } +} + const ( // OperatorAll is a Operator enum value OperatorAll = "ALL" @@ -34856,6 +35373,14 @@ const ( OperatorAny = "ANY" ) +// Operator_Values returns all elements of the Operator enum +func Operator_Values() []string { + return []string{ + OperatorAll, + OperatorAny, + } +} + const ( // RecencyTypeActive is a RecencyType enum value RecencyTypeActive = "ACTIVE" @@ -34864,6 +35389,14 @@ const ( RecencyTypeInactive = "INACTIVE" ) +// RecencyType_Values returns all elements of the RecencyType enum +func RecencyType_Values() []string { + return []string{ + RecencyTypeActive, + RecencyTypeInactive, + } +} + const ( // SegmentTypeDimensional is a SegmentType enum value SegmentTypeDimensional = "DIMENSIONAL" @@ -34872,6 +35405,14 @@ const ( SegmentTypeImport = "IMPORT" ) +// SegmentType_Values returns all elements of the SegmentType enum +func SegmentType_Values() []string { + return []string{ + SegmentTypeDimensional, + SegmentTypeImport, + } +} + const ( // SourceTypeAll is a SourceType enum value SourceTypeAll = "ALL" @@ -34883,6 +35424,15 @@ const ( SourceTypeNone = "NONE" ) +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeAll, + SourceTypeAny, + SourceTypeNone, + } +} + const ( // StateDraft is a State enum value StateDraft = "DRAFT" @@ -34900,6 +35450,17 @@ const ( StateClosed = "CLOSED" ) +// State_Values returns all elements of the State enum +func State_Values() []string { + return []string{ + StateDraft, + StateActive, + StateCompleted, + StateCancelled, + StateClosed, + } +} + const ( // TemplateTypeEmail is a TemplateType enum value TemplateTypeEmail = "EMAIL" @@ -34914,6 +35475,16 @@ const ( TemplateTypePush = "PUSH" ) +// TemplateType_Values returns all elements of the TemplateType enum +func TemplateType_Values() []string { + return []string{ + TemplateTypeEmail, + TemplateTypeSms, + TemplateTypeVoice, + TemplateTypePush, + } +} + const ( // TypeAll is a Type enum value TypeAll = "ALL" @@ -34924,3 +35495,12 @@ const ( // TypeNone is a Type enum value TypeNone = "NONE" ) + +// Type_Values returns all elements of the Type enum +func Type_Values() []string { + return []string{ + TypeAll, + TypeAny, + TypeNone, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/pricing/api.go b/vendor/github.com/aws/aws-sdk-go/service/pricing/api.go index a1e8aa0a79a..af3787c5d7a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/pricing/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/pricing/api.go @@ -1241,3 +1241,10 @@ const ( // FilterTypeTermMatch is a FilterType enum value FilterTypeTermMatch = "TERM_MATCH" ) + +// FilterType_Values returns all elements of the FilterType enum +func FilterType_Values() []string { + return []string{ + FilterTypeTermMatch, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/qldb/api.go b/vendor/github.com/aws/aws-sdk-go/service/qldb/api.go index 8a4e4d98b1d..4a56b87d765 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/qldb/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/qldb/api.go @@ -13,6 +13,96 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/restjson" ) +const opCancelJournalKinesisStream = "CancelJournalKinesisStream" + +// CancelJournalKinesisStreamRequest generates a "aws/request.Request" representing the +// client's request for the CancelJournalKinesisStream operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CancelJournalKinesisStream for more information on using the CancelJournalKinesisStream +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CancelJournalKinesisStreamRequest method. +// req, resp := client.CancelJournalKinesisStreamRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/qldb-2019-01-02/CancelJournalKinesisStream +func (c *QLDB) CancelJournalKinesisStreamRequest(input *CancelJournalKinesisStreamInput) (req *request.Request, output *CancelJournalKinesisStreamOutput) { + op := &request.Operation{ + Name: opCancelJournalKinesisStream, + HTTPMethod: "DELETE", + HTTPPath: "/ledgers/{name}/journal-kinesis-streams/{streamId}", + } + + if input == nil { + input = &CancelJournalKinesisStreamInput{} + } + + output = &CancelJournalKinesisStreamOutput{} + req = c.newRequest(op, input, output) + return +} + +// CancelJournalKinesisStream API operation for Amazon QLDB. +// +// Ends a given Amazon QLDB journal stream. Before a stream can be canceled, +// its current status must be ACTIVE. +// +// You can't restart a stream after you cancel it. Canceled QLDB stream resources +// are subject to a 7-day retention period, so they are automatically deleted +// after this limit expires. +// +// Returns awserr.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 QLDB's +// API operation CancelJournalKinesisStream for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// One or more parameters in the request aren't valid. +// +// * ResourceNotFoundException +// The specified resource doesn't exist. +// +// * ResourcePreconditionNotMetException +// The operation failed because a condition wasn't satisfied in advance. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/qldb-2019-01-02/CancelJournalKinesisStream +func (c *QLDB) CancelJournalKinesisStream(input *CancelJournalKinesisStreamInput) (*CancelJournalKinesisStreamOutput, error) { + req, out := c.CancelJournalKinesisStreamRequest(input) + return out, req.Send() +} + +// CancelJournalKinesisStreamWithContext is the same as CancelJournalKinesisStream with the addition of +// the ability to pass a context and additional request options. +// +// See CancelJournalKinesisStream for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QLDB) CancelJournalKinesisStreamWithContext(ctx aws.Context, input *CancelJournalKinesisStreamInput, opts ...request.Option) (*CancelJournalKinesisStreamOutput, error) { + req, out := c.CancelJournalKinesisStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateLedger = "CreateLedger" // CreateLedgerRequest generates a "aws/request.Request" representing the @@ -196,6 +286,93 @@ func (c *QLDB) DeleteLedgerWithContext(ctx aws.Context, input *DeleteLedgerInput return out, req.Send() } +const opDescribeJournalKinesisStream = "DescribeJournalKinesisStream" + +// DescribeJournalKinesisStreamRequest generates a "aws/request.Request" representing the +// client's request for the DescribeJournalKinesisStream operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeJournalKinesisStream for more information on using the DescribeJournalKinesisStream +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeJournalKinesisStreamRequest method. +// req, resp := client.DescribeJournalKinesisStreamRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/qldb-2019-01-02/DescribeJournalKinesisStream +func (c *QLDB) DescribeJournalKinesisStreamRequest(input *DescribeJournalKinesisStreamInput) (req *request.Request, output *DescribeJournalKinesisStreamOutput) { + op := &request.Operation{ + Name: opDescribeJournalKinesisStream, + HTTPMethod: "GET", + HTTPPath: "/ledgers/{name}/journal-kinesis-streams/{streamId}", + } + + if input == nil { + input = &DescribeJournalKinesisStreamInput{} + } + + output = &DescribeJournalKinesisStreamOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeJournalKinesisStream API operation for Amazon QLDB. +// +// Returns detailed information about a given Amazon QLDB journal stream. The +// output includes the Amazon Resource Name (ARN), stream name, current status, +// creation time, and the parameters of your original stream creation 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 Amazon QLDB's +// API operation DescribeJournalKinesisStream for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// One or more parameters in the request aren't valid. +// +// * ResourceNotFoundException +// The specified resource doesn't exist. +// +// * ResourcePreconditionNotMetException +// The operation failed because a condition wasn't satisfied in advance. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/qldb-2019-01-02/DescribeJournalKinesisStream +func (c *QLDB) DescribeJournalKinesisStream(input *DescribeJournalKinesisStreamInput) (*DescribeJournalKinesisStreamOutput, error) { + req, out := c.DescribeJournalKinesisStreamRequest(input) + return out, req.Send() +} + +// DescribeJournalKinesisStreamWithContext is the same as DescribeJournalKinesisStream with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeJournalKinesisStream for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QLDB) DescribeJournalKinesisStreamWithContext(ctx aws.Context, input *DescribeJournalKinesisStreamInput, opts ...request.Option) (*DescribeJournalKinesisStreamOutput, error) { + req, out := c.DescribeJournalKinesisStreamRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeJournalS3Export = "DescribeJournalS3Export" // DescribeJournalS3ExportRequest generates a "aws/request.Request" representing the @@ -244,6 +421,10 @@ func (c *QLDB) DescribeJournalS3ExportRequest(input *DescribeJournalS3ExportInpu // export ID, when it was created, current status, and its start and end time // export parameters. // +// This action does not return any expired export jobs. For more information, +// see Export Job Expiration (https://docs.aws.amazon.com/qldb/latest/developerguide/export-journal.request.html#export-journal.request.expiration) +// in the Amazon QLDB Developer Guide. +// // If the export job with the given ExportId doesn't exist, then throws ResourceNotFoundException. // // If the ledger with the given Name doesn't exist, then throws ResourceNotFoundException. @@ -498,9 +679,13 @@ func (c *QLDB) GetBlockRequest(input *GetBlockInput) (req *request.Request, outp // GetBlock API operation for Amazon QLDB. // -// Returns a journal block object at a specified address in a ledger. Also returns +// Returns a block object at a specified address in a journal. Also returns // a proof of the specified block for verification if DigestTipAddress is provided. // +// For information about the data contents in a block, see Journal contents +// (https://docs.aws.amazon.com/qldb/latest/developerguide/journal-contents.html) +// in the Amazon QLDB Developer Guide. +// // If the specified ledger doesn't exist or is in DELETING status, then throws // ResourceNotFoundException. // @@ -720,6 +905,155 @@ func (c *QLDB) GetRevisionWithContext(ctx aws.Context, input *GetRevisionInput, return out, req.Send() } +const opListJournalKinesisStreamsForLedger = "ListJournalKinesisStreamsForLedger" + +// ListJournalKinesisStreamsForLedgerRequest generates a "aws/request.Request" representing the +// client's request for the ListJournalKinesisStreamsForLedger operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListJournalKinesisStreamsForLedger for more information on using the ListJournalKinesisStreamsForLedger +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListJournalKinesisStreamsForLedgerRequest method. +// req, resp := client.ListJournalKinesisStreamsForLedgerRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/qldb-2019-01-02/ListJournalKinesisStreamsForLedger +func (c *QLDB) ListJournalKinesisStreamsForLedgerRequest(input *ListJournalKinesisStreamsForLedgerInput) (req *request.Request, output *ListJournalKinesisStreamsForLedgerOutput) { + op := &request.Operation{ + Name: opListJournalKinesisStreamsForLedger, + HTTPMethod: "GET", + HTTPPath: "/ledgers/{name}/journal-kinesis-streams", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListJournalKinesisStreamsForLedgerInput{} + } + + output = &ListJournalKinesisStreamsForLedgerOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListJournalKinesisStreamsForLedger API operation for Amazon QLDB. +// +// Returns an array of all Amazon QLDB journal stream descriptors for a given +// ledger. The output of each stream descriptor includes the same details that +// are returned by DescribeJournalKinesisStream. +// +// This action returns a maximum of MaxResults items. It is paginated so that +// you can retrieve all the items by calling ListJournalKinesisStreamsForLedger +// multiple times. +// +// Returns awserr.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 QLDB's +// API operation ListJournalKinesisStreamsForLedger for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// One or more parameters in the request aren't valid. +// +// * ResourceNotFoundException +// The specified resource doesn't exist. +// +// * ResourcePreconditionNotMetException +// The operation failed because a condition wasn't satisfied in advance. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/qldb-2019-01-02/ListJournalKinesisStreamsForLedger +func (c *QLDB) ListJournalKinesisStreamsForLedger(input *ListJournalKinesisStreamsForLedgerInput) (*ListJournalKinesisStreamsForLedgerOutput, error) { + req, out := c.ListJournalKinesisStreamsForLedgerRequest(input) + return out, req.Send() +} + +// ListJournalKinesisStreamsForLedgerWithContext is the same as ListJournalKinesisStreamsForLedger with the addition of +// the ability to pass a context and additional request options. +// +// See ListJournalKinesisStreamsForLedger for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QLDB) ListJournalKinesisStreamsForLedgerWithContext(ctx aws.Context, input *ListJournalKinesisStreamsForLedgerInput, opts ...request.Option) (*ListJournalKinesisStreamsForLedgerOutput, error) { + req, out := c.ListJournalKinesisStreamsForLedgerRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListJournalKinesisStreamsForLedgerPages iterates over the pages of a ListJournalKinesisStreamsForLedger operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListJournalKinesisStreamsForLedger 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 ListJournalKinesisStreamsForLedger operation. +// pageNum := 0 +// err := client.ListJournalKinesisStreamsForLedgerPages(params, +// func(page *qldb.ListJournalKinesisStreamsForLedgerOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *QLDB) ListJournalKinesisStreamsForLedgerPages(input *ListJournalKinesisStreamsForLedgerInput, fn func(*ListJournalKinesisStreamsForLedgerOutput, bool) bool) error { + return c.ListJournalKinesisStreamsForLedgerPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListJournalKinesisStreamsForLedgerPagesWithContext same as ListJournalKinesisStreamsForLedgerPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QLDB) ListJournalKinesisStreamsForLedgerPagesWithContext(ctx aws.Context, input *ListJournalKinesisStreamsForLedgerInput, fn func(*ListJournalKinesisStreamsForLedgerOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListJournalKinesisStreamsForLedgerInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListJournalKinesisStreamsForLedgerRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListJournalKinesisStreamsForLedgerOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListJournalS3Exports = "ListJournalS3Exports" // ListJournalS3ExportsRequest generates a "aws/request.Request" representing the @@ -776,6 +1110,10 @@ func (c *QLDB) ListJournalS3ExportsRequest(input *ListJournalS3ExportsInput) (re // This action returns a maximum of MaxResults items, and is paginated so that // you can retrieve all the items by calling ListJournalS3Exports multiple times. // +// This action does not return any expired export jobs. For more information, +// see Export Job Expiration (https://docs.aws.amazon.com/qldb/latest/developerguide/export-journal.request.html#export-journal.request.expiration) +// in the Amazon QLDB Developer Guide. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -912,6 +1250,10 @@ func (c *QLDB) ListJournalS3ExportsForLedgerRequest(input *ListJournalS3ExportsF // you can retrieve all the items by calling ListJournalS3ExportsForLedger multiple // times. // +// This action does not return any expired export jobs. For more information, +// see Export Job Expiration (https://docs.aws.amazon.com/qldb/latest/developerguide/export-journal.request.html#export-journal.request.expiration) +// in the Amazon QLDB Developer Guide. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -1210,6 +1552,93 @@ func (c *QLDB) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsFo return out, req.Send() } +const opStreamJournalToKinesis = "StreamJournalToKinesis" + +// StreamJournalToKinesisRequest generates a "aws/request.Request" representing the +// client's request for the StreamJournalToKinesis operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See StreamJournalToKinesis for more information on using the StreamJournalToKinesis +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the StreamJournalToKinesisRequest method. +// req, resp := client.StreamJournalToKinesisRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/qldb-2019-01-02/StreamJournalToKinesis +func (c *QLDB) StreamJournalToKinesisRequest(input *StreamJournalToKinesisInput) (req *request.Request, output *StreamJournalToKinesisOutput) { + op := &request.Operation{ + Name: opStreamJournalToKinesis, + HTTPMethod: "POST", + HTTPPath: "/ledgers/{name}/journal-kinesis-streams", + } + + if input == nil { + input = &StreamJournalToKinesisInput{} + } + + output = &StreamJournalToKinesisOutput{} + req = c.newRequest(op, input, output) + return +} + +// StreamJournalToKinesis API operation for Amazon QLDB. +// +// Creates a journal stream for a given Amazon QLDB ledger. The stream captures +// every document revision that is committed to the ledger's journal and delivers +// the data to a specified Amazon Kinesis Data Streams 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 Amazon QLDB's +// API operation StreamJournalToKinesis for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// One or more parameters in the request aren't valid. +// +// * ResourceNotFoundException +// The specified resource doesn't exist. +// +// * ResourcePreconditionNotMetException +// The operation failed because a condition wasn't satisfied in advance. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/qldb-2019-01-02/StreamJournalToKinesis +func (c *QLDB) StreamJournalToKinesis(input *StreamJournalToKinesisInput) (*StreamJournalToKinesisOutput, error) { + req, out := c.StreamJournalToKinesisRequest(input) + return out, req.Send() +} + +// StreamJournalToKinesisWithContext is the same as StreamJournalToKinesis with the addition of +// the ability to pass a context and additional request options. +// +// See StreamJournalToKinesis for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QLDB) StreamJournalToKinesisWithContext(ctx aws.Context, input *StreamJournalToKinesisInput, opts ...request.Option) (*StreamJournalToKinesisOutput, error) { + req, out := c.StreamJournalToKinesisRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opTagResource = "TagResource" // TagResourceRequest generates a "aws/request.Request" representing the @@ -1462,6 +1891,87 @@ func (c *QLDB) UpdateLedgerWithContext(ctx aws.Context, input *UpdateLedgerInput return out, req.Send() } +type CancelJournalKinesisStreamInput struct { + _ struct{} `type:"structure"` + + // The name of the ledger. + // + // LedgerName is a required field + LedgerName *string `location:"uri" locationName:"name" min:"1" type:"string" required:"true"` + + // The unique ID that QLDB assigns to each QLDB journal stream. + // + // StreamId is a required field + StreamId *string `location:"uri" locationName:"streamId" min:"22" type:"string" required:"true"` +} + +// String returns the string representation +func (s CancelJournalKinesisStreamInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CancelJournalKinesisStreamInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CancelJournalKinesisStreamInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CancelJournalKinesisStreamInput"} + if s.LedgerName == nil { + invalidParams.Add(request.NewErrParamRequired("LedgerName")) + } + if s.LedgerName != nil && len(*s.LedgerName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("LedgerName", 1)) + } + if s.StreamId == nil { + invalidParams.Add(request.NewErrParamRequired("StreamId")) + } + if s.StreamId != nil && len(*s.StreamId) < 22 { + invalidParams.Add(request.NewErrParamMinLen("StreamId", 22)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLedgerName sets the LedgerName field's value. +func (s *CancelJournalKinesisStreamInput) SetLedgerName(v string) *CancelJournalKinesisStreamInput { + s.LedgerName = &v + return s +} + +// SetStreamId sets the StreamId field's value. +func (s *CancelJournalKinesisStreamInput) SetStreamId(v string) *CancelJournalKinesisStreamInput { + s.StreamId = &v + return s +} + +type CancelJournalKinesisStreamOutput struct { + _ struct{} `type:"structure"` + + // The unique ID that QLDB assigns to each QLDB journal stream. + StreamId *string `min:"22" type:"string"` +} + +// String returns the string representation +func (s CancelJournalKinesisStreamOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CancelJournalKinesisStreamOutput) GoString() string { + return s.String() +} + +// SetStreamId sets the StreamId field's value. +func (s *CancelJournalKinesisStreamOutput) SetStreamId(v string) *CancelJournalKinesisStreamOutput { + s.StreamId = &v + return s +} + type CreateLedgerInput struct { _ struct{} `type:"structure"` @@ -1478,6 +1988,10 @@ type CreateLedgerInput struct { // The name of the ledger that you want to create. The name must be unique among // all of your ledgers in the current AWS Region. // + // Naming constraints for ledger names are defined in Quotas in Amazon QLDB + // (https://docs.aws.amazon.com/qldb/latest/developerguide/limits.html#limits.naming) + // in the Amazon QLDB Developer Guide. + // // Name is a required field Name *string `min:"1" type:"string" required:"true"` @@ -1667,6 +2181,88 @@ func (s DeleteLedgerOutput) GoString() string { return s.String() } +type DescribeJournalKinesisStreamInput struct { + _ struct{} `type:"structure"` + + // The name of the ledger. + // + // LedgerName is a required field + LedgerName *string `location:"uri" locationName:"name" min:"1" type:"string" required:"true"` + + // The unique ID that QLDB assigns to each QLDB journal stream. + // + // StreamId is a required field + StreamId *string `location:"uri" locationName:"streamId" min:"22" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeJournalKinesisStreamInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeJournalKinesisStreamInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeJournalKinesisStreamInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeJournalKinesisStreamInput"} + if s.LedgerName == nil { + invalidParams.Add(request.NewErrParamRequired("LedgerName")) + } + if s.LedgerName != nil && len(*s.LedgerName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("LedgerName", 1)) + } + if s.StreamId == nil { + invalidParams.Add(request.NewErrParamRequired("StreamId")) + } + if s.StreamId != nil && len(*s.StreamId) < 22 { + invalidParams.Add(request.NewErrParamMinLen("StreamId", 22)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLedgerName sets the LedgerName field's value. +func (s *DescribeJournalKinesisStreamInput) SetLedgerName(v string) *DescribeJournalKinesisStreamInput { + s.LedgerName = &v + return s +} + +// SetStreamId sets the StreamId field's value. +func (s *DescribeJournalKinesisStreamInput) SetStreamId(v string) *DescribeJournalKinesisStreamInput { + s.StreamId = &v + return s +} + +type DescribeJournalKinesisStreamOutput struct { + _ struct{} `type:"structure"` + + // Information about the QLDB journal stream returned by a DescribeJournalS3Export + // request. + Stream *JournalKinesisStreamDescription `type:"structure"` +} + +// String returns the string representation +func (s DescribeJournalKinesisStreamOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeJournalKinesisStreamOutput) GoString() string { + return s.String() +} + +// SetStream sets the Stream field's value. +func (s *DescribeJournalKinesisStreamOutput) SetStream(v *JournalKinesisStreamDescription) *DescribeJournalKinesisStreamOutput { + s.Stream = v + return s +} + type DescribeJournalS3ExportInput struct { _ struct{} `type:"structure"` @@ -2395,14 +2991,149 @@ func (s *InvalidParameterException) Error() string { return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) } -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidParameterException) StatusCode() int { - return s.RespMetadata.StatusCode +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidParameterException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidParameterException) RequestID() string { + return s.RespMetadata.RequestID +} + +// The information about an Amazon QLDB journal stream, including the Amazon +// Resource Name (ARN), stream name, creation time, current status, and the +// parameters of your original stream creation request. +type JournalKinesisStreamDescription struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the QLDB journal stream. + Arn *string `min:"20" type:"string"` + + // The date and time, in epoch time format, when the QLDB journal stream was + // created. (Epoch time format is the number of seconds elapsed since 12:00:00 + // AM January 1, 1970 UTC.) + CreationTime *time.Time `type:"timestamp"` + + // The error message that describes the reason that a stream has a status of + // IMPAIRED or FAILED. This is not applicable to streams that have other status + // values. + ErrorCause *string `type:"string" enum:"ErrorCause"` + + // The exclusive date and time that specifies when the stream ends. If this + // parameter is blank, the stream runs indefinitely until you cancel it. + ExclusiveEndTime *time.Time `type:"timestamp"` + + // The inclusive start date and time from which to start streaming journal data. + InclusiveStartTime *time.Time `type:"timestamp"` + + // The configuration settings of the Amazon Kinesis Data Streams destination + // for your QLDB journal stream. + // + // KinesisConfiguration is a required field + KinesisConfiguration *KinesisConfiguration `type:"structure" required:"true"` + + // The name of the ledger. + // + // LedgerName is a required field + LedgerName *string `min:"1" type:"string" required:"true"` + + // The Amazon Resource Name (ARN) of the IAM role that grants QLDB permissions + // for a journal stream to write data records to a Kinesis Data Streams resource. + // + // RoleArn is a required field + RoleArn *string `min:"20" type:"string" required:"true"` + + // The current state of the QLDB journal stream. + // + // Status is a required field + Status *string `type:"string" required:"true" enum:"StreamStatus"` + + // The unique ID that QLDB assigns to each QLDB journal stream. + // + // StreamId is a required field + StreamId *string `min:"22" type:"string" required:"true"` + + // The user-defined name of the QLDB journal stream. + // + // StreamName is a required field + StreamName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s JournalKinesisStreamDescription) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s JournalKinesisStreamDescription) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *JournalKinesisStreamDescription) SetArn(v string) *JournalKinesisStreamDescription { + s.Arn = &v + return s +} + +// SetCreationTime sets the CreationTime field's value. +func (s *JournalKinesisStreamDescription) SetCreationTime(v time.Time) *JournalKinesisStreamDescription { + s.CreationTime = &v + return s +} + +// SetErrorCause sets the ErrorCause field's value. +func (s *JournalKinesisStreamDescription) SetErrorCause(v string) *JournalKinesisStreamDescription { + s.ErrorCause = &v + return s +} + +// SetExclusiveEndTime sets the ExclusiveEndTime field's value. +func (s *JournalKinesisStreamDescription) SetExclusiveEndTime(v time.Time) *JournalKinesisStreamDescription { + s.ExclusiveEndTime = &v + return s +} + +// SetInclusiveStartTime sets the InclusiveStartTime field's value. +func (s *JournalKinesisStreamDescription) SetInclusiveStartTime(v time.Time) *JournalKinesisStreamDescription { + s.InclusiveStartTime = &v + return s +} + +// SetKinesisConfiguration sets the KinesisConfiguration field's value. +func (s *JournalKinesisStreamDescription) SetKinesisConfiguration(v *KinesisConfiguration) *JournalKinesisStreamDescription { + s.KinesisConfiguration = v + return s +} + +// SetLedgerName sets the LedgerName field's value. +func (s *JournalKinesisStreamDescription) SetLedgerName(v string) *JournalKinesisStreamDescription { + s.LedgerName = &v + return s +} + +// SetRoleArn sets the RoleArn field's value. +func (s *JournalKinesisStreamDescription) SetRoleArn(v string) *JournalKinesisStreamDescription { + s.RoleArn = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *JournalKinesisStreamDescription) SetStatus(v string) *JournalKinesisStreamDescription { + s.Status = &v + return s +} + +// SetStreamId sets the StreamId field's value. +func (s *JournalKinesisStreamDescription) SetStreamId(v string) *JournalKinesisStreamDescription { + s.StreamId = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *InvalidParameterException) RequestID() string { - return s.RespMetadata.RequestID +// SetStreamName sets the StreamName field's value. +func (s *JournalKinesisStreamDescription) SetStreamName(v string) *JournalKinesisStreamDescription { + s.StreamName = &v + return s } // The information about a journal export job, including the ledger name, export @@ -2521,6 +3252,60 @@ func (s *JournalS3ExportDescription) SetStatus(v string) *JournalS3ExportDescrip return s } +// The configuration settings of the Amazon Kinesis Data Streams destination +// for your Amazon QLDB journal stream. +type KinesisConfiguration struct { + _ struct{} `type:"structure"` + + // Enables QLDB to publish multiple data records in a single Kinesis Data Streams + // record. To learn more, see KPL Key Concepts (https://docs.aws.amazon.com/streams/latest/dev/kinesis-kpl-concepts.html) + // in the Amazon Kinesis Data Streams Developer Guide. + AggregationEnabled *bool `type:"boolean"` + + // The Amazon Resource Name (ARN) of the Kinesis data stream resource. + // + // StreamArn is a required field + StreamArn *string `min:"20" type:"string" required:"true"` +} + +// String returns the string representation +func (s KinesisConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s KinesisConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *KinesisConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "KinesisConfiguration"} + if s.StreamArn == nil { + invalidParams.Add(request.NewErrParamRequired("StreamArn")) + } + if s.StreamArn != nil && len(*s.StreamArn) < 20 { + invalidParams.Add(request.NewErrParamMinLen("StreamArn", 20)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAggregationEnabled sets the AggregationEnabled field's value. +func (s *KinesisConfiguration) SetAggregationEnabled(v bool) *KinesisConfiguration { + s.AggregationEnabled = &v + return s +} + +// SetStreamArn sets the StreamArn field's value. +func (s *KinesisConfiguration) SetStreamArn(v string) *KinesisConfiguration { + s.StreamArn = &v + return s +} + // Information about a ledger, including its name, state, and when it was created. type LedgerSummary struct { _ struct{} `type:"structure"` @@ -2624,6 +3409,113 @@ func (s *LimitExceededException) RequestID() string { return s.RespMetadata.RequestID } +type ListJournalKinesisStreamsForLedgerInput struct { + _ struct{} `type:"structure"` + + // The name of the ledger. + // + // LedgerName is a required field + LedgerName *string `location:"uri" locationName:"name" min:"1" type:"string" required:"true"` + + // The maximum number of results to return in a single ListJournalKinesisStreamsForLedger + // request. (The actual number of results returned might be fewer.) + MaxResults *int64 `location:"querystring" locationName:"max_results" min:"1" type:"integer"` + + // A pagination token, indicating that you want to retrieve the next page of + // results. If you received a value for NextToken in the response from a previous + // ListJournalKinesisStreamsForLedger call, you should use that value as input + // here. + NextToken *string `location:"querystring" locationName:"next_token" min:"4" type:"string"` +} + +// String returns the string representation +func (s ListJournalKinesisStreamsForLedgerInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListJournalKinesisStreamsForLedgerInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListJournalKinesisStreamsForLedgerInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListJournalKinesisStreamsForLedgerInput"} + if s.LedgerName == nil { + invalidParams.Add(request.NewErrParamRequired("LedgerName")) + } + if s.LedgerName != nil && len(*s.LedgerName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("LedgerName", 1)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.NextToken != nil && len(*s.NextToken) < 4 { + invalidParams.Add(request.NewErrParamMinLen("NextToken", 4)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetLedgerName sets the LedgerName field's value. +func (s *ListJournalKinesisStreamsForLedgerInput) SetLedgerName(v string) *ListJournalKinesisStreamsForLedgerInput { + s.LedgerName = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListJournalKinesisStreamsForLedgerInput) SetMaxResults(v int64) *ListJournalKinesisStreamsForLedgerInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListJournalKinesisStreamsForLedgerInput) SetNextToken(v string) *ListJournalKinesisStreamsForLedgerInput { + s.NextToken = &v + return s +} + +type ListJournalKinesisStreamsForLedgerOutput struct { + _ struct{} `type:"structure"` + + // * If NextToken is empty, the last page of results has been processed and + // there are no more results to be retrieved. + // + // * If NextToken is not empty, more results are available. To retrieve the + // next page of results, use the value of NextToken in a subsequent ListJournalKinesisStreamsForLedger + // call. + NextToken *string `min:"4" type:"string"` + + // The array of QLDB journal stream descriptors that are associated with the + // given ledger. + Streams []*JournalKinesisStreamDescription `type:"list"` +} + +// String returns the string representation +func (s ListJournalKinesisStreamsForLedgerOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListJournalKinesisStreamsForLedgerOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListJournalKinesisStreamsForLedgerOutput) SetNextToken(v string) *ListJournalKinesisStreamsForLedgerOutput { + s.NextToken = &v + return s +} + +// SetStreams sets the Streams field's value. +func (s *ListJournalKinesisStreamsForLedgerOutput) SetStreams(v []*JournalKinesisStreamDescription) *ListJournalKinesisStreamsForLedgerOutput { + s.Streams = v + return s +} + type ListJournalS3ExportsForLedgerInput struct { _ struct{} `type:"structure"` @@ -3230,8 +4122,9 @@ func (s *ResourcePreconditionNotMetException) RequestID() string { type S3EncryptionConfiguration struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) for a customer master key (CMK) in AWS Key - // Management Service (AWS KMS). + // The Amazon Resource Name (ARN) for a symmetric customer master key (CMK) + // in AWS Key Management Service (AWS KMS). Amazon QLDB does not support asymmetric + // CMKs. // // You must provide a KmsKeyArn if you specify SSE_KMS as the ObjectEncryptionType. // @@ -3381,6 +4274,175 @@ func (s *S3ExportConfiguration) SetPrefix(v string) *S3ExportConfiguration { return s } +type StreamJournalToKinesisInput struct { + _ struct{} `type:"structure"` + + // The exclusive date and time that specifies when the stream ends. If you don't + // define this parameter, the stream runs indefinitely until you cancel it. + // + // The ExclusiveEndTime must be in ISO 8601 date and time format and in Universal + // Coordinated Time (UTC). For example: 2019-06-13T21:36:34Z + ExclusiveEndTime *time.Time `type:"timestamp"` + + // The inclusive start date and time from which to start streaming journal data. + // This parameter must be in ISO 8601 date and time format and in Universal + // Coordinated Time (UTC). For example: 2019-06-13T21:36:34Z + // + // The InclusiveStartTime cannot be in the future and must be before ExclusiveEndTime. + // + // If you provide an InclusiveStartTime that is before the ledger's CreationDateTime, + // QLDB effectively defaults it to the ledger's CreationDateTime. + // + // InclusiveStartTime is a required field + InclusiveStartTime *time.Time `type:"timestamp" required:"true"` + + // The configuration settings of the Kinesis Data Streams destination for your + // stream request. + // + // KinesisConfiguration is a required field + KinesisConfiguration *KinesisConfiguration `type:"structure" required:"true"` + + // The name of the ledger. + // + // LedgerName is a required field + LedgerName *string `location:"uri" locationName:"name" min:"1" type:"string" required:"true"` + + // The Amazon Resource Name (ARN) of the IAM role that grants QLDB permissions + // for a journal stream to write data records to a Kinesis Data Streams resource. + // + // RoleArn is a required field + RoleArn *string `min:"20" type:"string" required:"true"` + + // The name that you want to assign to the QLDB journal stream. User-defined + // names can help identify and indicate the purpose of a stream. + // + // Your stream name must be unique among other active streams for a given ledger. + // Stream names have the same naming constraints as ledger names, as defined + // in Quotas in Amazon QLDB (https://docs.aws.amazon.com/qldb/latest/developerguide/limits.html#limits.naming) + // in the Amazon QLDB Developer Guide. + // + // StreamName is a required field + StreamName *string `min:"1" type:"string" required:"true"` + + // The key-value pairs to add as tags to the stream that you want to create. + // Tag keys are case sensitive. Tag values are case sensitive and can be null. + Tags map[string]*string `type:"map"` +} + +// String returns the string representation +func (s StreamJournalToKinesisInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StreamJournalToKinesisInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StreamJournalToKinesisInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StreamJournalToKinesisInput"} + if s.InclusiveStartTime == nil { + invalidParams.Add(request.NewErrParamRequired("InclusiveStartTime")) + } + if s.KinesisConfiguration == nil { + invalidParams.Add(request.NewErrParamRequired("KinesisConfiguration")) + } + if s.LedgerName == nil { + invalidParams.Add(request.NewErrParamRequired("LedgerName")) + } + if s.LedgerName != nil && len(*s.LedgerName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("LedgerName", 1)) + } + 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.StreamName == nil { + invalidParams.Add(request.NewErrParamRequired("StreamName")) + } + if s.StreamName != nil && len(*s.StreamName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("StreamName", 1)) + } + if s.KinesisConfiguration != nil { + if err := s.KinesisConfiguration.Validate(); err != nil { + invalidParams.AddNested("KinesisConfiguration", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetExclusiveEndTime sets the ExclusiveEndTime field's value. +func (s *StreamJournalToKinesisInput) SetExclusiveEndTime(v time.Time) *StreamJournalToKinesisInput { + s.ExclusiveEndTime = &v + return s +} + +// SetInclusiveStartTime sets the InclusiveStartTime field's value. +func (s *StreamJournalToKinesisInput) SetInclusiveStartTime(v time.Time) *StreamJournalToKinesisInput { + s.InclusiveStartTime = &v + return s +} + +// SetKinesisConfiguration sets the KinesisConfiguration field's value. +func (s *StreamJournalToKinesisInput) SetKinesisConfiguration(v *KinesisConfiguration) *StreamJournalToKinesisInput { + s.KinesisConfiguration = v + return s +} + +// SetLedgerName sets the LedgerName field's value. +func (s *StreamJournalToKinesisInput) SetLedgerName(v string) *StreamJournalToKinesisInput { + s.LedgerName = &v + return s +} + +// SetRoleArn sets the RoleArn field's value. +func (s *StreamJournalToKinesisInput) SetRoleArn(v string) *StreamJournalToKinesisInput { + s.RoleArn = &v + return s +} + +// SetStreamName sets the StreamName field's value. +func (s *StreamJournalToKinesisInput) SetStreamName(v string) *StreamJournalToKinesisInput { + s.StreamName = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *StreamJournalToKinesisInput) SetTags(v map[string]*string) *StreamJournalToKinesisInput { + s.Tags = v + return s +} + +type StreamJournalToKinesisOutput struct { + _ struct{} `type:"structure"` + + // The unique ID that QLDB assigns to each QLDB journal stream. + StreamId *string `min:"22" type:"string"` +} + +// String returns the string representation +func (s StreamJournalToKinesisOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StreamJournalToKinesisOutput) GoString() string { + return s.String() +} + +// SetStreamId sets the StreamId field's value. +func (s *StreamJournalToKinesisOutput) SetStreamId(v string) *StreamJournalToKinesisOutput { + s.StreamId = &v + return s +} + type TagResourceInput struct { _ struct{} `type:"structure"` @@ -3652,7 +4714,7 @@ func (s *UpdateLedgerOutput) SetState(v string) *UpdateLedgerOutput { return s } -// A structure that can contain an Amazon Ion value in multiple encoding formats. +// A structure that can contain a value in multiple encoding formats. type ValueHolder struct { _ struct{} `type:"structure" sensitive:"true"` @@ -3689,6 +4751,22 @@ func (s *ValueHolder) SetIonText(v string) *ValueHolder { return s } +const ( + // ErrorCauseKinesisStreamNotFound is a ErrorCause enum value + ErrorCauseKinesisStreamNotFound = "KINESIS_STREAM_NOT_FOUND" + + // ErrorCauseIamPermissionRevoked is a ErrorCause enum value + ErrorCauseIamPermissionRevoked = "IAM_PERMISSION_REVOKED" +) + +// ErrorCause_Values returns all elements of the ErrorCause enum +func ErrorCause_Values() []string { + return []string{ + ErrorCauseKinesisStreamNotFound, + ErrorCauseIamPermissionRevoked, + } +} + const ( // ExportStatusInProgress is a ExportStatus enum value ExportStatusInProgress = "IN_PROGRESS" @@ -3700,6 +4778,15 @@ const ( ExportStatusCancelled = "CANCELLED" ) +// ExportStatus_Values returns all elements of the ExportStatus enum +func ExportStatus_Values() []string { + return []string{ + ExportStatusInProgress, + ExportStatusCompleted, + ExportStatusCancelled, + } +} + const ( // LedgerStateCreating is a LedgerState enum value LedgerStateCreating = "CREATING" @@ -3714,11 +4801,28 @@ const ( LedgerStateDeleted = "DELETED" ) +// LedgerState_Values returns all elements of the LedgerState enum +func LedgerState_Values() []string { + return []string{ + LedgerStateCreating, + LedgerStateActive, + LedgerStateDeleting, + LedgerStateDeleted, + } +} + const ( // PermissionsModeAllowAll is a PermissionsMode enum value PermissionsModeAllowAll = "ALLOW_ALL" ) +// PermissionsMode_Values returns all elements of the PermissionsMode enum +func PermissionsMode_Values() []string { + return []string{ + PermissionsModeAllowAll, + } +} + const ( // S3ObjectEncryptionTypeSseKms is a S3ObjectEncryptionType enum value S3ObjectEncryptionTypeSseKms = "SSE_KMS" @@ -3729,3 +4833,40 @@ const ( // S3ObjectEncryptionTypeNoEncryption is a S3ObjectEncryptionType enum value S3ObjectEncryptionTypeNoEncryption = "NO_ENCRYPTION" ) + +// S3ObjectEncryptionType_Values returns all elements of the S3ObjectEncryptionType enum +func S3ObjectEncryptionType_Values() []string { + return []string{ + S3ObjectEncryptionTypeSseKms, + S3ObjectEncryptionTypeSseS3, + S3ObjectEncryptionTypeNoEncryption, + } +} + +const ( + // StreamStatusActive is a StreamStatus enum value + StreamStatusActive = "ACTIVE" + + // StreamStatusCompleted is a StreamStatus enum value + StreamStatusCompleted = "COMPLETED" + + // StreamStatusCanceled is a StreamStatus enum value + StreamStatusCanceled = "CANCELED" + + // StreamStatusFailed is a StreamStatus enum value + StreamStatusFailed = "FAILED" + + // StreamStatusImpaired is a StreamStatus enum value + StreamStatusImpaired = "IMPAIRED" +) + +// StreamStatus_Values returns all elements of the StreamStatus enum +func StreamStatus_Values() []string { + return []string{ + StreamStatusActive, + StreamStatusCompleted, + StreamStatusCanceled, + StreamStatusFailed, + StreamStatusImpaired, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/quicksight/api.go b/vendor/github.com/aws/aws-sdk-go/service/quicksight/api.go index 9fe23e9cd6f..ff3d6ef6af2 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/quicksight/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/quicksight/api.go @@ -110,6 +110,108 @@ func (c *QuickSight) CancelIngestionWithContext(ctx aws.Context, input *CancelIn return out, req.Send() } +const opCreateAccountCustomization = "CreateAccountCustomization" + +// CreateAccountCustomizationRequest generates a "aws/request.Request" representing the +// client's request for the CreateAccountCustomization operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateAccountCustomization for more information on using the CreateAccountCustomization +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateAccountCustomizationRequest method. +// req, resp := client.CreateAccountCustomizationRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/CreateAccountCustomization +func (c *QuickSight) CreateAccountCustomizationRequest(input *CreateAccountCustomizationInput) (req *request.Request, output *CreateAccountCustomizationOutput) { + op := &request.Operation{ + Name: opCreateAccountCustomization, + HTTPMethod: "POST", + HTTPPath: "/accounts/{AwsAccountId}/customizations", + } + + if input == nil { + input = &CreateAccountCustomizationInput{} + } + + output = &CreateAccountCustomizationOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateAccountCustomization API operation for Amazon QuickSight. +// +// Creates a customization for the Amazon QuickSight subscription associated +// with your 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. +// +// See the AWS API reference guide for Amazon QuickSight's +// API operation CreateAccountCustomization for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceExistsException +// The resource specified already exists. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * InternalFailureException +// An internal failure occurred. +// +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/CreateAccountCustomization +func (c *QuickSight) CreateAccountCustomization(input *CreateAccountCustomizationInput) (*CreateAccountCustomizationOutput, error) { + req, out := c.CreateAccountCustomizationRequest(input) + return out, req.Send() +} + +// CreateAccountCustomizationWithContext is the same as CreateAccountCustomization with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAccountCustomization for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) CreateAccountCustomizationWithContext(ctx aws.Context, input *CreateAccountCustomizationInput, opts ...request.Option) (*CreateAccountCustomizationOutput, error) { + req, out := c.CreateAccountCustomizationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateDashboard = "CreateDashboard" // CreateDashboardRequest generates a "aws/request.Request" representing the @@ -796,7 +898,7 @@ func (c *QuickSight) CreateIngestionRequest(input *CreateIngestionInput) (req *r // // Any ingestions operating on tagged datasets inherit the same tags automatically // for use in access control. For an example, see How do I create an IAM policy -// to control access to Amazon EC2 resources using tags? (https://aws.example.com/premiumsupport/knowledge-center/iam-ec2-resource-tags/) +// to control access to Amazon EC2 resources using tags? (https://aws.amazon.com/premiumsupport/knowledge-center/iam-ec2-resource-tags/) // in the AWS Knowledge Center. Tags are visible on the tagged dataset, but // not on the ingestion resource. // @@ -855,6 +957,125 @@ func (c *QuickSight) CreateIngestionWithContext(ctx aws.Context, input *CreateIn return out, req.Send() } +const opCreateNamespace = "CreateNamespace" + +// CreateNamespaceRequest generates a "aws/request.Request" representing the +// client's request for the CreateNamespace operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateNamespace for more information on using the CreateNamespace +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateNamespaceRequest method. +// req, resp := client.CreateNamespaceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/CreateNamespace +func (c *QuickSight) CreateNamespaceRequest(input *CreateNamespaceInput) (req *request.Request, output *CreateNamespaceOutput) { + op := &request.Operation{ + Name: opCreateNamespace, + HTTPMethod: "POST", + HTTPPath: "/accounts/{AwsAccountId}", + } + + if input == nil { + input = &CreateNamespaceInput{} + } + + output = &CreateNamespaceOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateNamespace API operation for Amazon QuickSight. +// +// (Enterprise edition only) Creates a new namespace for you to use with Amazon +// QuickSight. +// +// A namespace allows you to isolate the QuickSight users and groups that are +// registered for that namespace. Users that access the namespace can share +// assets only with other users or groups in the same namespace. They can't +// see users and groups in other namespaces. You can create a namespace after +// your AWS account is subscribed to QuickSight. The namespace must be unique +// within the AWS account. By default, there is a limit of 100 namespaces per +// AWS account. To increase your limit, create a ticket with AWS Support. +// +// Returns awserr.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 QuickSight's +// API operation CreateNamespace for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * LimitExceededException +// A limit is exceeded. +// +// * ResourceExistsException +// The resource specified already exists. +// +// * PreconditionNotMetException +// One or more preconditions aren't met. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * InternalFailureException +// An internal failure occurred. +// +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/CreateNamespace +func (c *QuickSight) CreateNamespace(input *CreateNamespaceInput) (*CreateNamespaceOutput, error) { + req, out := c.CreateNamespaceRequest(input) + return out, req.Send() +} + +// CreateNamespaceWithContext is the same as CreateNamespace with the addition of +// the ability to pass a context and additional request options. +// +// See CreateNamespace for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) CreateNamespaceWithContext(ctx aws.Context, input *CreateNamespaceInput, opts ...request.Option) (*CreateNamespaceOutput, error) { + req, out := c.CreateNamespaceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateTemplate = "CreateTemplate" // CreateTemplateRequest generates a "aws/request.Request" representing the @@ -945,6 +1166,9 @@ func (c *QuickSight) CreateTemplateRequest(input *CreateTemplateInput) (req *req // Amazon QuickSight currently has Standard Edition and Enterprise Edition. // Not every operation and capability is available in every edition. // +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// // * InternalFailureException // An internal failure occurred. // @@ -1045,6 +1269,9 @@ func (c *QuickSight) CreateTemplateAliasRequest(input *CreateTemplateAliasInput) // Amazon QuickSight currently has Standard Edition and Enterprise Edition. // Not every operation and capability is available in every edition. // +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// // * InternalFailureException // An internal failure occurred. // @@ -1070,251 +1297,273 @@ func (c *QuickSight) CreateTemplateAliasWithContext(ctx aws.Context, input *Crea return out, req.Send() } -const opDeleteDashboard = "DeleteDashboard" +const opCreateTheme = "CreateTheme" -// DeleteDashboardRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDashboard operation. The "output" return +// CreateThemeRequest generates a "aws/request.Request" representing the +// client's request for the CreateTheme operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteDashboard for more information on using the DeleteDashboard +// See CreateTheme for more information on using the CreateTheme // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteDashboardRequest method. -// req, resp := client.DeleteDashboardRequest(params) +// // Example sending a request using the CreateThemeRequest method. +// req, resp := client.CreateThemeRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDashboard -func (c *QuickSight) DeleteDashboardRequest(input *DeleteDashboardInput) (req *request.Request, output *DeleteDashboardOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/CreateTheme +func (c *QuickSight) CreateThemeRequest(input *CreateThemeInput) (req *request.Request, output *CreateThemeOutput) { op := &request.Operation{ - Name: opDeleteDashboard, - HTTPMethod: "DELETE", - HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}", + Name: opCreateTheme, + HTTPMethod: "POST", + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}", } if input == nil { - input = &DeleteDashboardInput{} + input = &CreateThemeInput{} } - output = &DeleteDashboardOutput{} + output = &CreateThemeOutput{} req = c.newRequest(op, input, output) return } -// DeleteDashboard API operation for Amazon QuickSight. +// CreateTheme API operation for Amazon QuickSight. // -// Deletes a dashboard. +// Creates a theme. +// +// A theme is set of configuration options for color and layout. Themes apply +// to analyses and dashboards. For more information, see Using Themes in Amazon +// QuickSight (https://docs.aws.amazon.com/quicksight/latest/user/themes-in-quicksight.html) +// in the Amazon QuickSight 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 QuickSight's -// API operation DeleteDashboard for usage and error information. +// API operation CreateTheme for usage and error information. // // Returned Error Types: -// * ThrottlingException -// Access is throttled. +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. +// * ResourceExistsException +// The resource specified already exists. // // * ResourceNotFoundException // One or more resources can't be found. // +// * ThrottlingException +// Access is throttled. +// // * UnsupportedUserEditionException // This error indicates that you are calling an operation on an Amazon QuickSight // subscription where the edition doesn't include support for that operation. // Amazon QuickSight currently has Standard Edition and Enterprise Edition. // Not every operation and capability is available in every edition. // +// * LimitExceededException +// A limit is exceeded. +// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDashboard -func (c *QuickSight) DeleteDashboard(input *DeleteDashboardInput) (*DeleteDashboardOutput, error) { - req, out := c.DeleteDashboardRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/CreateTheme +func (c *QuickSight) CreateTheme(input *CreateThemeInput) (*CreateThemeOutput, error) { + req, out := c.CreateThemeRequest(input) return out, req.Send() } -// DeleteDashboardWithContext is the same as DeleteDashboard with the addition of +// CreateThemeWithContext is the same as CreateTheme with the addition of // the ability to pass a context and additional request options. // -// See DeleteDashboard for details on how to use this API operation. +// See CreateTheme for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DeleteDashboardWithContext(ctx aws.Context, input *DeleteDashboardInput, opts ...request.Option) (*DeleteDashboardOutput, error) { - req, out := c.DeleteDashboardRequest(input) +func (c *QuickSight) CreateThemeWithContext(ctx aws.Context, input *CreateThemeInput, opts ...request.Option) (*CreateThemeOutput, error) { + req, out := c.CreateThemeRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDeleteDataSet = "DeleteDataSet" +const opCreateThemeAlias = "CreateThemeAlias" -// DeleteDataSetRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDataSet operation. The "output" return +// CreateThemeAliasRequest generates a "aws/request.Request" representing the +// client's request for the CreateThemeAlias operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteDataSet for more information on using the DeleteDataSet +// See CreateThemeAlias for more information on using the CreateThemeAlias // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteDataSetRequest method. -// req, resp := client.DeleteDataSetRequest(params) +// // Example sending a request using the CreateThemeAliasRequest method. +// req, resp := client.CreateThemeAliasRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDataSet -func (c *QuickSight) DeleteDataSetRequest(input *DeleteDataSetInput) (req *request.Request, output *DeleteDataSetOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/CreateThemeAlias +func (c *QuickSight) CreateThemeAliasRequest(input *CreateThemeAliasInput) (req *request.Request, output *CreateThemeAliasOutput) { op := &request.Operation{ - Name: opDeleteDataSet, - HTTPMethod: "DELETE", - HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}", + Name: opCreateThemeAlias, + HTTPMethod: "POST", + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}/aliases/{AliasName}", } if input == nil { - input = &DeleteDataSetInput{} + input = &CreateThemeAliasInput{} } - output = &DeleteDataSetOutput{} + output = &CreateThemeAliasOutput{} req = c.newRequest(op, input, output) return } -// DeleteDataSet API operation for Amazon QuickSight. +// CreateThemeAlias API operation for Amazon QuickSight. // -// Deletes a dataset. +// Creates a theme alias for a theme. // // Returns awserr.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 QuickSight's -// API operation DeleteDataSet for usage and error information. +// API operation CreateThemeAlias for usage and error information. // // Returned Error Types: -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ThrottlingException -// Access is throttled. +// * LimitExceededException +// A limit is exceeded. +// +// * ResourceExistsException +// The resource specified already exists. // // * ResourceNotFoundException // One or more resources can't be found. // -// * InternalFailureException -// An internal failure occurred. +// * ThrottlingException +// Access is throttled. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDataSet -func (c *QuickSight) DeleteDataSet(input *DeleteDataSetInput) (*DeleteDataSetOutput, error) { - req, out := c.DeleteDataSetRequest(input) +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/CreateThemeAlias +func (c *QuickSight) CreateThemeAlias(input *CreateThemeAliasInput) (*CreateThemeAliasOutput, error) { + req, out := c.CreateThemeAliasRequest(input) return out, req.Send() } -// DeleteDataSetWithContext is the same as DeleteDataSet with the addition of +// CreateThemeAliasWithContext is the same as CreateThemeAlias with the addition of // the ability to pass a context and additional request options. // -// See DeleteDataSet for details on how to use this API operation. +// See CreateThemeAlias for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DeleteDataSetWithContext(ctx aws.Context, input *DeleteDataSetInput, opts ...request.Option) (*DeleteDataSetOutput, error) { - req, out := c.DeleteDataSetRequest(input) +func (c *QuickSight) CreateThemeAliasWithContext(ctx aws.Context, input *CreateThemeAliasInput, opts ...request.Option) (*CreateThemeAliasOutput, error) { + req, out := c.CreateThemeAliasRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDeleteDataSource = "DeleteDataSource" +const opDeleteAccountCustomization = "DeleteAccountCustomization" -// DeleteDataSourceRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDataSource operation. The "output" return +// DeleteAccountCustomizationRequest generates a "aws/request.Request" representing the +// client's request for the DeleteAccountCustomization operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteDataSource for more information on using the DeleteDataSource +// See DeleteAccountCustomization for more information on using the DeleteAccountCustomization // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteDataSourceRequest method. -// req, resp := client.DeleteDataSourceRequest(params) +// // Example sending a request using the DeleteAccountCustomizationRequest method. +// req, resp := client.DeleteAccountCustomizationRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDataSource -func (c *QuickSight) DeleteDataSourceRequest(input *DeleteDataSourceInput) (req *request.Request, output *DeleteDataSourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteAccountCustomization +func (c *QuickSight) DeleteAccountCustomizationRequest(input *DeleteAccountCustomizationInput) (req *request.Request, output *DeleteAccountCustomizationOutput) { op := &request.Operation{ - Name: opDeleteDataSource, + Name: opDeleteAccountCustomization, HTTPMethod: "DELETE", - HTTPPath: "/accounts/{AwsAccountId}/data-sources/{DataSourceId}", + HTTPPath: "/accounts/{AwsAccountId}/customizations", } if input == nil { - input = &DeleteDataSourceInput{} + input = &DeleteAccountCustomizationInput{} } - output = &DeleteDataSourceOutput{} + output = &DeleteAccountCustomizationOutput{} req = c.newRequest(op, input, output) return } -// DeleteDataSource API operation for Amazon QuickSight. +// DeleteAccountCustomization API operation for Amazon QuickSight. // -// Deletes the data source permanently. This action breaks all the datasets -// that reference the deleted data source. +// Deletes customizations for the QuickSight subscription on your 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. // // See the AWS API reference guide for Amazon QuickSight's -// API operation DeleteDataSource for usage and error information. +// API operation DeleteAccountCustomization for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -1327,191 +1576,189 @@ func (c *QuickSight) DeleteDataSourceRequest(input *DeleteDataSourceInput) (req // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ThrottlingException -// Access is throttled. -// // * ResourceNotFoundException // One or more resources can't be found. // +// * ThrottlingException +// Access is throttled. +// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDataSource -func (c *QuickSight) DeleteDataSource(input *DeleteDataSourceInput) (*DeleteDataSourceOutput, error) { - req, out := c.DeleteDataSourceRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteAccountCustomization +func (c *QuickSight) DeleteAccountCustomization(input *DeleteAccountCustomizationInput) (*DeleteAccountCustomizationOutput, error) { + req, out := c.DeleteAccountCustomizationRequest(input) return out, req.Send() } -// DeleteDataSourceWithContext is the same as DeleteDataSource with the addition of +// DeleteAccountCustomizationWithContext is the same as DeleteAccountCustomization with the addition of // the ability to pass a context and additional request options. // -// See DeleteDataSource for details on how to use this API operation. +// See DeleteAccountCustomization for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DeleteDataSourceWithContext(ctx aws.Context, input *DeleteDataSourceInput, opts ...request.Option) (*DeleteDataSourceOutput, error) { - req, out := c.DeleteDataSourceRequest(input) +func (c *QuickSight) DeleteAccountCustomizationWithContext(ctx aws.Context, input *DeleteAccountCustomizationInput, opts ...request.Option) (*DeleteAccountCustomizationOutput, error) { + req, out := c.DeleteAccountCustomizationRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDeleteGroup = "DeleteGroup" +const opDeleteDashboard = "DeleteDashboard" -// DeleteGroupRequest generates a "aws/request.Request" representing the -// client's request for the DeleteGroup operation. The "output" return +// DeleteDashboardRequest generates a "aws/request.Request" representing the +// client's request for the DeleteDashboard operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteGroup for more information on using the DeleteGroup +// See DeleteDashboard for more information on using the DeleteDashboard // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteGroupRequest method. -// req, resp := client.DeleteGroupRequest(params) +// // Example sending a request using the DeleteDashboardRequest method. +// req, resp := client.DeleteDashboardRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteGroup -func (c *QuickSight) DeleteGroupRequest(input *DeleteGroupInput) (req *request.Request, output *DeleteGroupOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDashboard +func (c *QuickSight) DeleteDashboardRequest(input *DeleteDashboardInput) (req *request.Request, output *DeleteDashboardOutput) { op := &request.Operation{ - Name: opDeleteGroup, + Name: opDeleteDashboard, HTTPMethod: "DELETE", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups/{GroupName}", + HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}", } if input == nil { - input = &DeleteGroupInput{} + input = &DeleteDashboardInput{} } - output = &DeleteGroupOutput{} + output = &DeleteDashboardOutput{} req = c.newRequest(op, input, output) return } -// DeleteGroup API operation for Amazon QuickSight. +// DeleteDashboard API operation for Amazon QuickSight. // -// Removes a user group from Amazon QuickSight. +// Deletes a dashboard. // // Returns awserr.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 QuickSight's -// API operation DeleteGroup for usage and error information. +// API operation DeleteDashboard for usage and error information. // // Returned Error Types: -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. +// * ThrottlingException +// Access is throttled. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// // * ResourceNotFoundException // One or more resources can't be found. // -// * ThrottlingException -// Access is throttled. -// -// * PreconditionNotMetException -// One or more preconditions aren't met. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// * ResourceUnavailableException -// This resource is currently unavailable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteGroup -func (c *QuickSight) DeleteGroup(input *DeleteGroupInput) (*DeleteGroupOutput, error) { - req, out := c.DeleteGroupRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDashboard +func (c *QuickSight) DeleteDashboard(input *DeleteDashboardInput) (*DeleteDashboardOutput, error) { + req, out := c.DeleteDashboardRequest(input) return out, req.Send() } -// DeleteGroupWithContext is the same as DeleteGroup with the addition of +// DeleteDashboardWithContext is the same as DeleteDashboard 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. +// See DeleteDashboard for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DeleteGroupWithContext(ctx aws.Context, input *DeleteGroupInput, opts ...request.Option) (*DeleteGroupOutput, error) { - req, out := c.DeleteGroupRequest(input) +func (c *QuickSight) DeleteDashboardWithContext(ctx aws.Context, input *DeleteDashboardInput, opts ...request.Option) (*DeleteDashboardOutput, error) { + req, out := c.DeleteDashboardRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDeleteGroupMembership = "DeleteGroupMembership" +const opDeleteDataSet = "DeleteDataSet" -// DeleteGroupMembershipRequest generates a "aws/request.Request" representing the -// client's request for the DeleteGroupMembership operation. The "output" return +// DeleteDataSetRequest generates a "aws/request.Request" representing the +// client's request for the DeleteDataSet operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteGroupMembership for more information on using the DeleteGroupMembership +// See DeleteDataSet for more information on using the DeleteDataSet // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteGroupMembershipRequest method. -// req, resp := client.DeleteGroupMembershipRequest(params) +// // Example sending a request using the DeleteDataSetRequest method. +// req, resp := client.DeleteDataSetRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteGroupMembership -func (c *QuickSight) DeleteGroupMembershipRequest(input *DeleteGroupMembershipInput) (req *request.Request, output *DeleteGroupMembershipOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDataSet +func (c *QuickSight) DeleteDataSetRequest(input *DeleteDataSetInput) (req *request.Request, output *DeleteDataSetOutput) { op := &request.Operation{ - Name: opDeleteGroupMembership, + Name: opDeleteDataSet, HTTPMethod: "DELETE", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups/{GroupName}/members/{MemberName}", + HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}", } if input == nil { - input = &DeleteGroupMembershipInput{} + input = &DeleteDataSetInput{} } - output = &DeleteGroupMembershipOutput{} + output = &DeleteDataSetOutput{} req = c.newRequest(op, input, output) return } -// DeleteGroupMembership API operation for Amazon QuickSight. +// DeleteDataSet API operation for Amazon QuickSight. // -// Removes a user from a group so that the user is no longer a member of the -// group. +// Deletes a dataset. // // Returns awserr.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 QuickSight's -// API operation DeleteGroupMembership for usage and error information. +// API operation DeleteDataSet for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -1524,95 +1771,90 @@ func (c *QuickSight) DeleteGroupMembershipRequest(input *DeleteGroupMembershipIn // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ResourceNotFoundException -// One or more resources can't be found. -// // * ThrottlingException // Access is throttled. // -// * PreconditionNotMetException -// One or more preconditions aren't met. +// * ResourceNotFoundException +// One or more resources can't be found. // // * InternalFailureException // An internal failure occurred. // -// * ResourceUnavailableException -// This resource is currently unavailable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteGroupMembership -func (c *QuickSight) DeleteGroupMembership(input *DeleteGroupMembershipInput) (*DeleteGroupMembershipOutput, error) { - req, out := c.DeleteGroupMembershipRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDataSet +func (c *QuickSight) DeleteDataSet(input *DeleteDataSetInput) (*DeleteDataSetOutput, error) { + req, out := c.DeleteDataSetRequest(input) return out, req.Send() } -// DeleteGroupMembershipWithContext is the same as DeleteGroupMembership with the addition of +// DeleteDataSetWithContext is the same as DeleteDataSet with the addition of // the ability to pass a context and additional request options. // -// See DeleteGroupMembership for details on how to use this API operation. +// See DeleteDataSet for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DeleteGroupMembershipWithContext(ctx aws.Context, input *DeleteGroupMembershipInput, opts ...request.Option) (*DeleteGroupMembershipOutput, error) { - req, out := c.DeleteGroupMembershipRequest(input) +func (c *QuickSight) DeleteDataSetWithContext(ctx aws.Context, input *DeleteDataSetInput, opts ...request.Option) (*DeleteDataSetOutput, error) { + req, out := c.DeleteDataSetRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDeleteIAMPolicyAssignment = "DeleteIAMPolicyAssignment" +const opDeleteDataSource = "DeleteDataSource" -// DeleteIAMPolicyAssignmentRequest generates a "aws/request.Request" representing the -// client's request for the DeleteIAMPolicyAssignment operation. The "output" return +// DeleteDataSourceRequest generates a "aws/request.Request" representing the +// client's request for the DeleteDataSource operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteIAMPolicyAssignment for more information on using the DeleteIAMPolicyAssignment +// See DeleteDataSource for more information on using the DeleteDataSource // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteIAMPolicyAssignmentRequest method. -// req, resp := client.DeleteIAMPolicyAssignmentRequest(params) +// // Example sending a request using the DeleteDataSourceRequest method. +// req, resp := client.DeleteDataSourceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteIAMPolicyAssignment -func (c *QuickSight) DeleteIAMPolicyAssignmentRequest(input *DeleteIAMPolicyAssignmentInput) (req *request.Request, output *DeleteIAMPolicyAssignmentOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDataSource +func (c *QuickSight) DeleteDataSourceRequest(input *DeleteDataSourceInput) (req *request.Request, output *DeleteDataSourceOutput) { op := &request.Operation{ - Name: opDeleteIAMPolicyAssignment, + Name: opDeleteDataSource, HTTPMethod: "DELETE", - HTTPPath: "/accounts/{AwsAccountId}/namespace/{Namespace}/iam-policy-assignments/{AssignmentName}", + HTTPPath: "/accounts/{AwsAccountId}/data-sources/{DataSourceId}", } if input == nil { - input = &DeleteIAMPolicyAssignmentInput{} + input = &DeleteDataSourceInput{} } - output = &DeleteIAMPolicyAssignmentOutput{} + output = &DeleteDataSourceOutput{} req = c.newRequest(op, input, output) return } -// DeleteIAMPolicyAssignment API operation for Amazon QuickSight. +// DeleteDataSource API operation for Amazon QuickSight. // -// Deletes an existing IAM policy assignment. +// Deletes the data source permanently. This action breaks all the datasets +// that reference the deleted data source. // // Returns awserr.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 QuickSight's -// API operation DeleteIAMPolicyAssignment for usage and error information. +// API operation DeleteDataSource for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -1625,100 +1867,100 @@ func (c *QuickSight) DeleteIAMPolicyAssignmentRequest(input *DeleteIAMPolicyAssi // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ResourceExistsException -// The resource specified already exists. -// -// * ResourceNotFoundException -// One or more resources can't be found. -// // * ThrottlingException // Access is throttled. // -// * ConcurrentUpdatingException -// A resource is already in a state that indicates an action is happening that -// must complete before a new update can be applied. +// * ResourceNotFoundException +// One or more resources can't be found. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteIAMPolicyAssignment -func (c *QuickSight) DeleteIAMPolicyAssignment(input *DeleteIAMPolicyAssignmentInput) (*DeleteIAMPolicyAssignmentOutput, error) { - req, out := c.DeleteIAMPolicyAssignmentRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteDataSource +func (c *QuickSight) DeleteDataSource(input *DeleteDataSourceInput) (*DeleteDataSourceOutput, error) { + req, out := c.DeleteDataSourceRequest(input) return out, req.Send() } -// DeleteIAMPolicyAssignmentWithContext is the same as DeleteIAMPolicyAssignment with the addition of +// DeleteDataSourceWithContext is the same as DeleteDataSource with the addition of // the ability to pass a context and additional request options. // -// See DeleteIAMPolicyAssignment for details on how to use this API operation. +// See DeleteDataSource for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DeleteIAMPolicyAssignmentWithContext(ctx aws.Context, input *DeleteIAMPolicyAssignmentInput, opts ...request.Option) (*DeleteIAMPolicyAssignmentOutput, error) { - req, out := c.DeleteIAMPolicyAssignmentRequest(input) +func (c *QuickSight) DeleteDataSourceWithContext(ctx aws.Context, input *DeleteDataSourceInput, opts ...request.Option) (*DeleteDataSourceOutput, error) { + req, out := c.DeleteDataSourceRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDeleteTemplate = "DeleteTemplate" +const opDeleteGroup = "DeleteGroup" -// DeleteTemplateRequest generates a "aws/request.Request" representing the -// client's request for the DeleteTemplate operation. The "output" return +// DeleteGroupRequest generates a "aws/request.Request" representing the +// client's request for the DeleteGroup operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteTemplate for more information on using the DeleteTemplate +// See DeleteGroup for more information on using the DeleteGroup // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteTemplateRequest method. -// req, resp := client.DeleteTemplateRequest(params) +// // Example sending a request using the DeleteGroupRequest method. +// req, resp := client.DeleteGroupRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteTemplate -func (c *QuickSight) DeleteTemplateRequest(input *DeleteTemplateInput) (req *request.Request, output *DeleteTemplateOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteGroup +func (c *QuickSight) DeleteGroupRequest(input *DeleteGroupInput) (req *request.Request, output *DeleteGroupOutput) { op := &request.Operation{ - Name: opDeleteTemplate, + Name: opDeleteGroup, HTTPMethod: "DELETE", - HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups/{GroupName}", } if input == nil { - input = &DeleteTemplateInput{} + input = &DeleteGroupInput{} } - output = &DeleteTemplateOutput{} + output = &DeleteGroupOutput{} req = c.newRequest(op, input, output) return } -// DeleteTemplate API operation for Amazon QuickSight. +// DeleteGroup API operation for Amazon QuickSight. // -// Deletes a template. +// Removes a user group from Amazon QuickSight. // // Returns awserr.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 QuickSight's -// API operation DeleteTemplate for usage and error information. +// API operation DeleteGroup for usage and error information. // // Returned Error Types: -// * InvalidParameterValueException -// One or more parameters has a value that isn't valid. +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. // // * ResourceNotFoundException // One or more resources can't be found. @@ -1726,190 +1968,191 @@ func (c *QuickSight) DeleteTemplateRequest(input *DeleteTemplateInput) (req *req // * ThrottlingException // Access is throttled. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. -// -// * LimitExceededException -// A limit is exceeded. -// -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. +// * PreconditionNotMetException +// One or more preconditions aren't met. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteTemplate -func (c *QuickSight) DeleteTemplate(input *DeleteTemplateInput) (*DeleteTemplateOutput, error) { - req, out := c.DeleteTemplateRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteGroup +func (c *QuickSight) DeleteGroup(input *DeleteGroupInput) (*DeleteGroupOutput, error) { + req, out := c.DeleteGroupRequest(input) return out, req.Send() } -// DeleteTemplateWithContext is the same as DeleteTemplate with the addition of +// DeleteGroupWithContext is the same as DeleteGroup with the addition of // the ability to pass a context and additional request options. // -// See DeleteTemplate for details on how to use this API operation. +// 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 *QuickSight) DeleteTemplateWithContext(ctx aws.Context, input *DeleteTemplateInput, opts ...request.Option) (*DeleteTemplateOutput, error) { - req, out := c.DeleteTemplateRequest(input) +func (c *QuickSight) 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 opDeleteTemplateAlias = "DeleteTemplateAlias" +const opDeleteGroupMembership = "DeleteGroupMembership" -// DeleteTemplateAliasRequest generates a "aws/request.Request" representing the -// client's request for the DeleteTemplateAlias operation. The "output" return +// DeleteGroupMembershipRequest generates a "aws/request.Request" representing the +// client's request for the DeleteGroupMembership operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteTemplateAlias for more information on using the DeleteTemplateAlias +// See DeleteGroupMembership for more information on using the DeleteGroupMembership // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteTemplateAliasRequest method. -// req, resp := client.DeleteTemplateAliasRequest(params) +// // Example sending a request using the DeleteGroupMembershipRequest method. +// req, resp := client.DeleteGroupMembershipRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteTemplateAlias -func (c *QuickSight) DeleteTemplateAliasRequest(input *DeleteTemplateAliasInput) (req *request.Request, output *DeleteTemplateAliasOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteGroupMembership +func (c *QuickSight) DeleteGroupMembershipRequest(input *DeleteGroupMembershipInput) (req *request.Request, output *DeleteGroupMembershipOutput) { op := &request.Operation{ - Name: opDeleteTemplateAlias, + Name: opDeleteGroupMembership, HTTPMethod: "DELETE", - HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/aliases/{AliasName}", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups/{GroupName}/members/{MemberName}", } if input == nil { - input = &DeleteTemplateAliasInput{} + input = &DeleteGroupMembershipInput{} } - output = &DeleteTemplateAliasOutput{} + output = &DeleteGroupMembershipOutput{} req = c.newRequest(op, input, output) return } -// DeleteTemplateAlias API operation for Amazon QuickSight. +// DeleteGroupMembership API operation for Amazon QuickSight. // -// Deletes the item that the specified template alias points to. If you provide -// a specific alias, you delete the version of the template that the alias points -// to. +// Removes a user from a group so that the user is no longer a member of the +// group. // // Returns awserr.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 QuickSight's -// API operation DeleteTemplateAlias for usage and error information. +// API operation DeleteGroupMembership for usage and error information. // // Returned Error Types: -// * ThrottlingException -// Access is throttled. +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. // // * ResourceNotFoundException // One or more resources can't be found. // -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. +// * ThrottlingException +// Access is throttled. +// +// * PreconditionNotMetException +// One or more preconditions aren't met. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteTemplateAlias -func (c *QuickSight) DeleteTemplateAlias(input *DeleteTemplateAliasInput) (*DeleteTemplateAliasOutput, error) { - req, out := c.DeleteTemplateAliasRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteGroupMembership +func (c *QuickSight) DeleteGroupMembership(input *DeleteGroupMembershipInput) (*DeleteGroupMembershipOutput, error) { + req, out := c.DeleteGroupMembershipRequest(input) return out, req.Send() } -// DeleteTemplateAliasWithContext is the same as DeleteTemplateAlias with the addition of +// DeleteGroupMembershipWithContext is the same as DeleteGroupMembership with the addition of // the ability to pass a context and additional request options. // -// See DeleteTemplateAlias for details on how to use this API operation. +// See DeleteGroupMembership for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DeleteTemplateAliasWithContext(ctx aws.Context, input *DeleteTemplateAliasInput, opts ...request.Option) (*DeleteTemplateAliasOutput, error) { - req, out := c.DeleteTemplateAliasRequest(input) +func (c *QuickSight) DeleteGroupMembershipWithContext(ctx aws.Context, input *DeleteGroupMembershipInput, opts ...request.Option) (*DeleteGroupMembershipOutput, error) { + req, out := c.DeleteGroupMembershipRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDeleteUser = "DeleteUser" +const opDeleteIAMPolicyAssignment = "DeleteIAMPolicyAssignment" -// DeleteUserRequest generates a "aws/request.Request" representing the -// client's request for the DeleteUser operation. The "output" return +// DeleteIAMPolicyAssignmentRequest generates a "aws/request.Request" representing the +// client's request for the DeleteIAMPolicyAssignment operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteUser for more information on using the DeleteUser +// See DeleteIAMPolicyAssignment for more information on using the DeleteIAMPolicyAssignment // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteUserRequest method. -// req, resp := client.DeleteUserRequest(params) +// // Example sending a request using the DeleteIAMPolicyAssignmentRequest method. +// req, resp := client.DeleteIAMPolicyAssignmentRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteUser -func (c *QuickSight) DeleteUserRequest(input *DeleteUserInput) (req *request.Request, output *DeleteUserOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteIAMPolicyAssignment +func (c *QuickSight) DeleteIAMPolicyAssignmentRequest(input *DeleteIAMPolicyAssignmentInput) (req *request.Request, output *DeleteIAMPolicyAssignmentOutput) { op := &request.Operation{ - Name: opDeleteUser, + Name: opDeleteIAMPolicyAssignment, HTTPMethod: "DELETE", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users/{UserName}", + HTTPPath: "/accounts/{AwsAccountId}/namespace/{Namespace}/iam-policy-assignments/{AssignmentName}", } if input == nil { - input = &DeleteUserInput{} + input = &DeleteIAMPolicyAssignmentInput{} } - output = &DeleteUserOutput{} + output = &DeleteIAMPolicyAssignmentOutput{} req = c.newRequest(op, input, output) return } -// DeleteUser API operation for Amazon QuickSight. +// DeleteIAMPolicyAssignment API operation for Amazon QuickSight. // -// Deletes the Amazon QuickSight user that is associated with the identity of -// the AWS Identity and Access Management (IAM) user or role that's making the -// call. The IAM user isn't deleted as a result of this call. +// Deletes an existing IAM policy assignment. // // Returns awserr.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 QuickSight's -// API operation DeleteUser for usage and error information. +// API operation DeleteIAMPolicyAssignment for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -1922,92 +2165,99 @@ func (c *QuickSight) DeleteUserRequest(input *DeleteUserInput) (req *request.Req // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ResourceExistsException +// The resource specified already exists. +// // * ResourceNotFoundException // One or more resources can't be found. // // * ThrottlingException // Access is throttled. // +// * ConcurrentUpdatingException +// A resource is already in a state that indicates an action is happening that +// must complete before a new update can be applied. +// // * InternalFailureException // An internal failure occurred. // -// * ResourceUnavailableException -// This resource is currently unavailable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteUser -func (c *QuickSight) DeleteUser(input *DeleteUserInput) (*DeleteUserOutput, error) { - req, out := c.DeleteUserRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteIAMPolicyAssignment +func (c *QuickSight) DeleteIAMPolicyAssignment(input *DeleteIAMPolicyAssignmentInput) (*DeleteIAMPolicyAssignmentOutput, error) { + req, out := c.DeleteIAMPolicyAssignmentRequest(input) return out, req.Send() } -// DeleteUserWithContext is the same as DeleteUser with the addition of +// DeleteIAMPolicyAssignmentWithContext is the same as DeleteIAMPolicyAssignment 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. +// See DeleteIAMPolicyAssignment for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DeleteUserWithContext(ctx aws.Context, input *DeleteUserInput, opts ...request.Option) (*DeleteUserOutput, error) { - req, out := c.DeleteUserRequest(input) +func (c *QuickSight) DeleteIAMPolicyAssignmentWithContext(ctx aws.Context, input *DeleteIAMPolicyAssignmentInput, opts ...request.Option) (*DeleteIAMPolicyAssignmentOutput, error) { + req, out := c.DeleteIAMPolicyAssignmentRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDeleteUserByPrincipalId = "DeleteUserByPrincipalId" +const opDeleteNamespace = "DeleteNamespace" -// DeleteUserByPrincipalIdRequest generates a "aws/request.Request" representing the -// client's request for the DeleteUserByPrincipalId operation. The "output" return +// DeleteNamespaceRequest generates a "aws/request.Request" representing the +// client's request for the DeleteNamespace operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DeleteUserByPrincipalId for more information on using the DeleteUserByPrincipalId +// See DeleteNamespace for more information on using the DeleteNamespace // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DeleteUserByPrincipalIdRequest method. -// req, resp := client.DeleteUserByPrincipalIdRequest(params) +// // Example sending a request using the DeleteNamespaceRequest method. +// req, resp := client.DeleteNamespaceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteUserByPrincipalId -func (c *QuickSight) DeleteUserByPrincipalIdRequest(input *DeleteUserByPrincipalIdInput) (req *request.Request, output *DeleteUserByPrincipalIdOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteNamespace +func (c *QuickSight) DeleteNamespaceRequest(input *DeleteNamespaceInput) (req *request.Request, output *DeleteNamespaceOutput) { op := &request.Operation{ - Name: opDeleteUserByPrincipalId, + Name: opDeleteNamespace, HTTPMethod: "DELETE", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/user-principals/{PrincipalId}", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}", } if input == nil { - input = &DeleteUserByPrincipalIdInput{} + input = &DeleteNamespaceInput{} } - output = &DeleteUserByPrincipalIdOutput{} + output = &DeleteNamespaceOutput{} req = c.newRequest(op, input, output) return } -// DeleteUserByPrincipalId API operation for Amazon QuickSight. +// DeleteNamespace API operation for Amazon QuickSight. // -// Deletes a user identified by its principal ID. +// Deletes a namespace and the users and groups that are associated with the +// namespace. This is an asynchronous process. Assets including dashboards, +// analyses, datasets and data sources are not deleted. To delete these assets, +// you use the APIs for the relevant asset. // // Returns awserr.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 QuickSight's -// API operation DeleteUserByPrincipalId for usage and error information. +// API operation DeleteNamespace for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -2026,86 +2276,89 @@ func (c *QuickSight) DeleteUserByPrincipalIdRequest(input *DeleteUserByPrincipal // * ThrottlingException // Access is throttled. // +// * PreconditionNotMetException +// One or more preconditions aren't met. +// // * InternalFailureException // An internal failure occurred. // // * ResourceUnavailableException // This resource is currently unavailable. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteUserByPrincipalId -func (c *QuickSight) DeleteUserByPrincipalId(input *DeleteUserByPrincipalIdInput) (*DeleteUserByPrincipalIdOutput, error) { - req, out := c.DeleteUserByPrincipalIdRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteNamespace +func (c *QuickSight) DeleteNamespace(input *DeleteNamespaceInput) (*DeleteNamespaceOutput, error) { + req, out := c.DeleteNamespaceRequest(input) return out, req.Send() } -// DeleteUserByPrincipalIdWithContext is the same as DeleteUserByPrincipalId with the addition of +// DeleteNamespaceWithContext is the same as DeleteNamespace with the addition of // the ability to pass a context and additional request options. // -// See DeleteUserByPrincipalId for details on how to use this API operation. +// See DeleteNamespace for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DeleteUserByPrincipalIdWithContext(ctx aws.Context, input *DeleteUserByPrincipalIdInput, opts ...request.Option) (*DeleteUserByPrincipalIdOutput, error) { - req, out := c.DeleteUserByPrincipalIdRequest(input) +func (c *QuickSight) DeleteNamespaceWithContext(ctx aws.Context, input *DeleteNamespaceInput, opts ...request.Option) (*DeleteNamespaceOutput, error) { + req, out := c.DeleteNamespaceRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeDashboard = "DescribeDashboard" +const opDeleteTemplate = "DeleteTemplate" -// DescribeDashboardRequest generates a "aws/request.Request" representing the -// client's request for the DescribeDashboard operation. The "output" return +// DeleteTemplateRequest generates a "aws/request.Request" representing the +// client's request for the DeleteTemplate operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeDashboard for more information on using the DescribeDashboard +// See DeleteTemplate for more information on using the DeleteTemplate // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeDashboardRequest method. -// req, resp := client.DescribeDashboardRequest(params) +// // Example sending a request using the DeleteTemplateRequest method. +// req, resp := client.DeleteTemplateRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDashboard -func (c *QuickSight) DescribeDashboardRequest(input *DescribeDashboardInput) (req *request.Request, output *DescribeDashboardOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteTemplate +func (c *QuickSight) DeleteTemplateRequest(input *DeleteTemplateInput) (req *request.Request, output *DeleteTemplateOutput) { op := &request.Operation{ - Name: opDescribeDashboard, - HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}", + Name: opDeleteTemplate, + HTTPMethod: "DELETE", + HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}", } if input == nil { - input = &DescribeDashboardInput{} + input = &DeleteTemplateInput{} } - output = &DescribeDashboardOutput{} + output = &DeleteTemplateOutput{} req = c.newRequest(op, input, output) return } -// DescribeDashboard API operation for Amazon QuickSight. +// DeleteTemplate API operation for Amazon QuickSight. // -// Provides a summary for a dashboard. +// Deletes a template. // // Returns awserr.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 QuickSight's -// API operation DescribeDashboard for usage and error information. +// API operation DeleteTemplate for usage and error information. // // Returned Error Types: // * InvalidParameterValueException @@ -2114,16 +2367,15 @@ func (c *QuickSight) DescribeDashboardRequest(input *DescribeDashboardInput) (re // * ResourceNotFoundException // One or more resources can't be found. // -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. -// // * ThrottlingException // Access is throttled. // +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * LimitExceededException +// A limit is exceeded. +// // * UnsupportedUserEditionException // This error indicates that you are calling an operation on an Amazon QuickSight // subscription where the edition doesn't include support for that operation. @@ -2133,174 +2385,176 @@ func (c *QuickSight) DescribeDashboardRequest(input *DescribeDashboardInput) (re // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDashboard -func (c *QuickSight) DescribeDashboard(input *DescribeDashboardInput) (*DescribeDashboardOutput, error) { - req, out := c.DescribeDashboardRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteTemplate +func (c *QuickSight) DeleteTemplate(input *DeleteTemplateInput) (*DeleteTemplateOutput, error) { + req, out := c.DeleteTemplateRequest(input) return out, req.Send() } -// DescribeDashboardWithContext is the same as DescribeDashboard with the addition of +// DeleteTemplateWithContext is the same as DeleteTemplate with the addition of // the ability to pass a context and additional request options. // -// See DescribeDashboard for details on how to use this API operation. +// See DeleteTemplate for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeDashboardWithContext(ctx aws.Context, input *DescribeDashboardInput, opts ...request.Option) (*DescribeDashboardOutput, error) { - req, out := c.DescribeDashboardRequest(input) +func (c *QuickSight) DeleteTemplateWithContext(ctx aws.Context, input *DeleteTemplateInput, opts ...request.Option) (*DeleteTemplateOutput, error) { + req, out := c.DeleteTemplateRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeDashboardPermissions = "DescribeDashboardPermissions" +const opDeleteTemplateAlias = "DeleteTemplateAlias" -// DescribeDashboardPermissionsRequest generates a "aws/request.Request" representing the -// client's request for the DescribeDashboardPermissions operation. The "output" return +// DeleteTemplateAliasRequest generates a "aws/request.Request" representing the +// client's request for the DeleteTemplateAlias operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeDashboardPermissions for more information on using the DescribeDashboardPermissions +// See DeleteTemplateAlias for more information on using the DeleteTemplateAlias // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeDashboardPermissionsRequest method. -// req, resp := client.DescribeDashboardPermissionsRequest(params) +// // Example sending a request using the DeleteTemplateAliasRequest method. +// req, resp := client.DeleteTemplateAliasRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDashboardPermissions -func (c *QuickSight) DescribeDashboardPermissionsRequest(input *DescribeDashboardPermissionsInput) (req *request.Request, output *DescribeDashboardPermissionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteTemplateAlias +func (c *QuickSight) DeleteTemplateAliasRequest(input *DeleteTemplateAliasInput) (req *request.Request, output *DeleteTemplateAliasOutput) { op := &request.Operation{ - Name: opDescribeDashboardPermissions, - HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}/permissions", + Name: opDeleteTemplateAlias, + HTTPMethod: "DELETE", + HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/aliases/{AliasName}", } if input == nil { - input = &DescribeDashboardPermissionsInput{} + input = &DeleteTemplateAliasInput{} } - output = &DescribeDashboardPermissionsOutput{} + output = &DeleteTemplateAliasOutput{} req = c.newRequest(op, input, output) return } -// DescribeDashboardPermissions API operation for Amazon QuickSight. +// DeleteTemplateAlias API operation for Amazon QuickSight. // -// Describes read and write permissions for a dashboard. +// Deletes the item that the specified template alias points to. If you provide +// a specific alias, you delete the version of the template that the alias points +// to. // // Returns awserr.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 QuickSight's -// API operation DescribeDashboardPermissions for usage and error information. +// API operation DeleteTemplateAlias for usage and error information. // // Returned Error Types: -// * InvalidParameterValueException -// One or more parameters has a value that isn't valid. +// * ThrottlingException +// Access is throttled. // // * ResourceNotFoundException // One or more resources can't be found. // -// * ThrottlingException -// Access is throttled. -// // * UnsupportedUserEditionException // This error indicates that you are calling an operation on an Amazon QuickSight // subscription where the edition doesn't include support for that operation. // Amazon QuickSight currently has Standard Edition and Enterprise Edition. // Not every operation and capability is available in every edition. // +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDashboardPermissions -func (c *QuickSight) DescribeDashboardPermissions(input *DescribeDashboardPermissionsInput) (*DescribeDashboardPermissionsOutput, error) { - req, out := c.DescribeDashboardPermissionsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteTemplateAlias +func (c *QuickSight) DeleteTemplateAlias(input *DeleteTemplateAliasInput) (*DeleteTemplateAliasOutput, error) { + req, out := c.DeleteTemplateAliasRequest(input) return out, req.Send() } -// DescribeDashboardPermissionsWithContext is the same as DescribeDashboardPermissions with the addition of +// DeleteTemplateAliasWithContext is the same as DeleteTemplateAlias with the addition of // the ability to pass a context and additional request options. // -// See DescribeDashboardPermissions for details on how to use this API operation. +// See DeleteTemplateAlias for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeDashboardPermissionsWithContext(ctx aws.Context, input *DescribeDashboardPermissionsInput, opts ...request.Option) (*DescribeDashboardPermissionsOutput, error) { - req, out := c.DescribeDashboardPermissionsRequest(input) +func (c *QuickSight) DeleteTemplateAliasWithContext(ctx aws.Context, input *DeleteTemplateAliasInput, opts ...request.Option) (*DeleteTemplateAliasOutput, error) { + req, out := c.DeleteTemplateAliasRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeDataSet = "DescribeDataSet" +const opDeleteTheme = "DeleteTheme" -// DescribeDataSetRequest generates a "aws/request.Request" representing the -// client's request for the DescribeDataSet operation. The "output" return +// DeleteThemeRequest generates a "aws/request.Request" representing the +// client's request for the DeleteTheme operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeDataSet for more information on using the DescribeDataSet +// See DeleteTheme for more information on using the DeleteTheme // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeDataSetRequest method. -// req, resp := client.DescribeDataSetRequest(params) +// // Example sending a request using the DeleteThemeRequest method. +// req, resp := client.DeleteThemeRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSet -func (c *QuickSight) DescribeDataSetRequest(input *DescribeDataSetInput) (req *request.Request, output *DescribeDataSetOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteTheme +func (c *QuickSight) DeleteThemeRequest(input *DeleteThemeInput) (req *request.Request, output *DeleteThemeOutput) { op := &request.Operation{ - Name: opDescribeDataSet, - HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}", + Name: opDeleteTheme, + HTTPMethod: "DELETE", + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}", } if input == nil { - input = &DescribeDataSetInput{} + input = &DeleteThemeInput{} } - output = &DescribeDataSetOutput{} + output = &DeleteThemeOutput{} req = c.newRequest(op, input, output) return } -// DescribeDataSet API operation for Amazon QuickSight. +// DeleteTheme API operation for Amazon QuickSight. // -// Describes a dataset. +// Deletes a theme. // // Returns awserr.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 QuickSight's -// API operation DescribeDataSet for usage and error information. +// API operation DeleteTheme for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -2310,189 +2564,202 @@ func (c *QuickSight) DescribeDataSetRequest(input *DescribeDataSetInput) (req *r // your policies have the correct permissions, and that you are using the correct // access keys. // +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ResourceNotFoundException +// One or more resources can't be found. +// // * ThrottlingException // Access is throttled. // -// * ResourceNotFoundException -// One or more resources can't be found. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSet -func (c *QuickSight) DescribeDataSet(input *DescribeDataSetInput) (*DescribeDataSetOutput, error) { - req, out := c.DescribeDataSetRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteTheme +func (c *QuickSight) DeleteTheme(input *DeleteThemeInput) (*DeleteThemeOutput, error) { + req, out := c.DeleteThemeRequest(input) return out, req.Send() } -// DescribeDataSetWithContext is the same as DescribeDataSet with the addition of +// DeleteThemeWithContext is the same as DeleteTheme with the addition of // the ability to pass a context and additional request options. // -// See DescribeDataSet for details on how to use this API operation. +// See DeleteTheme for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeDataSetWithContext(ctx aws.Context, input *DescribeDataSetInput, opts ...request.Option) (*DescribeDataSetOutput, error) { - req, out := c.DescribeDataSetRequest(input) +func (c *QuickSight) DeleteThemeWithContext(ctx aws.Context, input *DeleteThemeInput, opts ...request.Option) (*DeleteThemeOutput, error) { + req, out := c.DeleteThemeRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeDataSetPermissions = "DescribeDataSetPermissions" +const opDeleteThemeAlias = "DeleteThemeAlias" -// DescribeDataSetPermissionsRequest generates a "aws/request.Request" representing the -// client's request for the DescribeDataSetPermissions operation. The "output" return +// DeleteThemeAliasRequest generates a "aws/request.Request" representing the +// client's request for the DeleteThemeAlias operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeDataSetPermissions for more information on using the DescribeDataSetPermissions +// See DeleteThemeAlias for more information on using the DeleteThemeAlias // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeDataSetPermissionsRequest method. -// req, resp := client.DescribeDataSetPermissionsRequest(params) +// // Example sending a request using the DeleteThemeAliasRequest method. +// req, resp := client.DeleteThemeAliasRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSetPermissions -func (c *QuickSight) DescribeDataSetPermissionsRequest(input *DescribeDataSetPermissionsInput) (req *request.Request, output *DescribeDataSetPermissionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteThemeAlias +func (c *QuickSight) DeleteThemeAliasRequest(input *DeleteThemeAliasInput) (req *request.Request, output *DeleteThemeAliasOutput) { op := &request.Operation{ - Name: opDescribeDataSetPermissions, - HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}/permissions", + Name: opDeleteThemeAlias, + HTTPMethod: "DELETE", + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}/aliases/{AliasName}", } if input == nil { - input = &DescribeDataSetPermissionsInput{} + input = &DeleteThemeAliasInput{} } - output = &DescribeDataSetPermissionsOutput{} + output = &DeleteThemeAliasOutput{} req = c.newRequest(op, input, output) return } -// DescribeDataSetPermissions API operation for Amazon QuickSight. +// DeleteThemeAlias API operation for Amazon QuickSight. // -// Describes the permissions on a dataset. -// -// The permissions resource is arn:aws:quicksight:region:aws-account-id:dataset/data-set-id. +// Deletes the version of the theme that the specified theme alias points to. +// If you provide a specific alias, you delete the version of the theme that +// the alias points to. // // Returns awserr.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 QuickSight's -// API operation DescribeDataSetPermissions for usage and error information. +// API operation DeleteThemeAlias for usage and error information. // // Returned Error Types: -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ResourceNotFoundException +// One or more resources can't be found. +// // * ThrottlingException // Access is throttled. // -// * ResourceNotFoundException -// One or more resources can't be found. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSetPermissions -func (c *QuickSight) DescribeDataSetPermissions(input *DescribeDataSetPermissionsInput) (*DescribeDataSetPermissionsOutput, error) { - req, out := c.DescribeDataSetPermissionsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteThemeAlias +func (c *QuickSight) DeleteThemeAlias(input *DeleteThemeAliasInput) (*DeleteThemeAliasOutput, error) { + req, out := c.DeleteThemeAliasRequest(input) return out, req.Send() } -// DescribeDataSetPermissionsWithContext is the same as DescribeDataSetPermissions with the addition of +// DeleteThemeAliasWithContext is the same as DeleteThemeAlias with the addition of // the ability to pass a context and additional request options. // -// See DescribeDataSetPermissions for details on how to use this API operation. +// See DeleteThemeAlias for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeDataSetPermissionsWithContext(ctx aws.Context, input *DescribeDataSetPermissionsInput, opts ...request.Option) (*DescribeDataSetPermissionsOutput, error) { - req, out := c.DescribeDataSetPermissionsRequest(input) +func (c *QuickSight) DeleteThemeAliasWithContext(ctx aws.Context, input *DeleteThemeAliasInput, opts ...request.Option) (*DeleteThemeAliasOutput, error) { + req, out := c.DeleteThemeAliasRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeDataSource = "DescribeDataSource" +const opDeleteUser = "DeleteUser" -// DescribeDataSourceRequest generates a "aws/request.Request" representing the -// client's request for the DescribeDataSource operation. The "output" return +// DeleteUserRequest generates a "aws/request.Request" representing the +// client's request for the DeleteUser operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeDataSource for more information on using the DescribeDataSource +// See DeleteUser for more information on using the DeleteUser // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeDataSourceRequest method. -// req, resp := client.DescribeDataSourceRequest(params) +// // Example sending a request using the DeleteUserRequest method. +// req, resp := client.DeleteUserRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSource -func (c *QuickSight) DescribeDataSourceRequest(input *DescribeDataSourceInput) (req *request.Request, output *DescribeDataSourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteUser +func (c *QuickSight) DeleteUserRequest(input *DeleteUserInput) (req *request.Request, output *DeleteUserOutput) { op := &request.Operation{ - Name: opDescribeDataSource, - HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/data-sources/{DataSourceId}", + Name: opDeleteUser, + HTTPMethod: "DELETE", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users/{UserName}", } if input == nil { - input = &DescribeDataSourceInput{} + input = &DeleteUserInput{} } - output = &DescribeDataSourceOutput{} + output = &DeleteUserOutput{} req = c.newRequest(op, input, output) return } -// DescribeDataSource API operation for Amazon QuickSight. +// DeleteUser API operation for Amazon QuickSight. // -// Describes a data source. +// Deletes the Amazon QuickSight user that is associated with the identity of +// the AWS Identity and Access Management (IAM) user or role that's making the +// call. The IAM user isn't deleted as a result of this call. // // Returns awserr.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 QuickSight's -// API operation DescribeDataSource for usage and error information. +// API operation DeleteUser for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -2505,89 +2772,95 @@ func (c *QuickSight) DescribeDataSourceRequest(input *DescribeDataSourceInput) ( // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ResourceNotFoundException +// One or more resources can't be found. +// // * ThrottlingException // Access is throttled. // -// * ResourceNotFoundException -// One or more resources can't be found. +// * PreconditionNotMetException +// One or more preconditions aren't met. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSource -func (c *QuickSight) DescribeDataSource(input *DescribeDataSourceInput) (*DescribeDataSourceOutput, error) { - req, out := c.DescribeDataSourceRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteUser +func (c *QuickSight) DeleteUser(input *DeleteUserInput) (*DeleteUserOutput, error) { + req, out := c.DeleteUserRequest(input) return out, req.Send() } -// DescribeDataSourceWithContext is the same as DescribeDataSource with the addition of +// DeleteUserWithContext is the same as DeleteUser with the addition of // the ability to pass a context and additional request options. // -// See DescribeDataSource for details on how to use this API operation. +// 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 *QuickSight) DescribeDataSourceWithContext(ctx aws.Context, input *DescribeDataSourceInput, opts ...request.Option) (*DescribeDataSourceOutput, error) { - req, out := c.DescribeDataSourceRequest(input) +func (c *QuickSight) 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 opDescribeDataSourcePermissions = "DescribeDataSourcePermissions" +const opDeleteUserByPrincipalId = "DeleteUserByPrincipalId" -// DescribeDataSourcePermissionsRequest generates a "aws/request.Request" representing the -// client's request for the DescribeDataSourcePermissions operation. The "output" return +// DeleteUserByPrincipalIdRequest generates a "aws/request.Request" representing the +// client's request for the DeleteUserByPrincipalId operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeDataSourcePermissions for more information on using the DescribeDataSourcePermissions +// See DeleteUserByPrincipalId for more information on using the DeleteUserByPrincipalId // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeDataSourcePermissionsRequest method. -// req, resp := client.DescribeDataSourcePermissionsRequest(params) +// // Example sending a request using the DeleteUserByPrincipalIdRequest method. +// req, resp := client.DeleteUserByPrincipalIdRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSourcePermissions -func (c *QuickSight) DescribeDataSourcePermissionsRequest(input *DescribeDataSourcePermissionsInput) (req *request.Request, output *DescribeDataSourcePermissionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteUserByPrincipalId +func (c *QuickSight) DeleteUserByPrincipalIdRequest(input *DeleteUserByPrincipalIdInput) (req *request.Request, output *DeleteUserByPrincipalIdOutput) { op := &request.Operation{ - Name: opDescribeDataSourcePermissions, - HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/data-sources/{DataSourceId}/permissions", + Name: opDeleteUserByPrincipalId, + HTTPMethod: "DELETE", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/user-principals/{PrincipalId}", } if input == nil { - input = &DescribeDataSourcePermissionsInput{} + input = &DeleteUserByPrincipalIdInput{} } - output = &DescribeDataSourcePermissionsOutput{} + output = &DeleteUserByPrincipalIdOutput{} req = c.newRequest(op, input, output) return } -// DescribeDataSourcePermissions API operation for Amazon QuickSight. +// DeleteUserByPrincipalId API operation for Amazon QuickSight. // -// Describes the resource permissions for a data source. +// Deletes a user identified by its principal 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 // the error. // // See the AWS API reference guide for Amazon QuickSight's -// API operation DescribeDataSourcePermissions for usage and error information. +// API operation DeleteUserByPrincipalId for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -2600,90 +2873,95 @@ func (c *QuickSight) DescribeDataSourcePermissionsRequest(input *DescribeDataSou // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ResourceNotFoundException +// One or more resources can't be found. +// // * ThrottlingException // Access is throttled. // -// * ResourceNotFoundException -// One or more resources can't be found. +// * PreconditionNotMetException +// One or more preconditions aren't met. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSourcePermissions -func (c *QuickSight) DescribeDataSourcePermissions(input *DescribeDataSourcePermissionsInput) (*DescribeDataSourcePermissionsOutput, error) { - req, out := c.DescribeDataSourcePermissionsRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DeleteUserByPrincipalId +func (c *QuickSight) DeleteUserByPrincipalId(input *DeleteUserByPrincipalIdInput) (*DeleteUserByPrincipalIdOutput, error) { + req, out := c.DeleteUserByPrincipalIdRequest(input) return out, req.Send() } -// DescribeDataSourcePermissionsWithContext is the same as DescribeDataSourcePermissions with the addition of +// DeleteUserByPrincipalIdWithContext is the same as DeleteUserByPrincipalId with the addition of // the ability to pass a context and additional request options. // -// See DescribeDataSourcePermissions for details on how to use this API operation. +// See DeleteUserByPrincipalId for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeDataSourcePermissionsWithContext(ctx aws.Context, input *DescribeDataSourcePermissionsInput, opts ...request.Option) (*DescribeDataSourcePermissionsOutput, error) { - req, out := c.DescribeDataSourcePermissionsRequest(input) +func (c *QuickSight) DeleteUserByPrincipalIdWithContext(ctx aws.Context, input *DeleteUserByPrincipalIdInput, opts ...request.Option) (*DeleteUserByPrincipalIdOutput, error) { + req, out := c.DeleteUserByPrincipalIdRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeGroup = "DescribeGroup" +const opDescribeAccountCustomization = "DescribeAccountCustomization" -// DescribeGroupRequest generates a "aws/request.Request" representing the -// client's request for the DescribeGroup operation. The "output" return +// DescribeAccountCustomizationRequest generates a "aws/request.Request" representing the +// client's request for the DescribeAccountCustomization operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeGroup for more information on using the DescribeGroup +// See DescribeAccountCustomization for more information on using the DescribeAccountCustomization // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeGroupRequest method. -// req, resp := client.DescribeGroupRequest(params) +// // Example sending a request using the DescribeAccountCustomizationRequest method. +// req, resp := client.DescribeAccountCustomizationRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeGroup -func (c *QuickSight) DescribeGroupRequest(input *DescribeGroupInput) (req *request.Request, output *DescribeGroupOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeAccountCustomization +func (c *QuickSight) DescribeAccountCustomizationRequest(input *DescribeAccountCustomizationInput) (req *request.Request, output *DescribeAccountCustomizationOutput) { op := &request.Operation{ - Name: opDescribeGroup, + Name: opDescribeAccountCustomization, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups/{GroupName}", + HTTPPath: "/accounts/{AwsAccountId}/customizations", } if input == nil { - input = &DescribeGroupInput{} + input = &DescribeAccountCustomizationInput{} } - output = &DescribeGroupOutput{} + output = &DescribeAccountCustomizationOutput{} req = c.newRequest(op, input, output) return } -// DescribeGroup API operation for Amazon QuickSight. +// DescribeAccountCustomization API operation for Amazon QuickSight. // -// Returns an Amazon QuickSight group's description and Amazon Resource Name -// (ARN). +// Describes the customizations associated with your 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. // // See the AWS API reference guide for Amazon QuickSight's -// API operation DescribeGroup for usage and error information. +// API operation DescribeAccountCustomization for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -2702,90 +2980,87 @@ func (c *QuickSight) DescribeGroupRequest(input *DescribeGroupInput) (req *reque // * ThrottlingException // Access is throttled. // -// * PreconditionNotMetException -// One or more preconditions aren't met. -// // * InternalFailureException // An internal failure occurred. // // * ResourceUnavailableException // This resource is currently unavailable. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeGroup -func (c *QuickSight) DescribeGroup(input *DescribeGroupInput) (*DescribeGroupOutput, error) { - req, out := c.DescribeGroupRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeAccountCustomization +func (c *QuickSight) DescribeAccountCustomization(input *DescribeAccountCustomizationInput) (*DescribeAccountCustomizationOutput, error) { + req, out := c.DescribeAccountCustomizationRequest(input) return out, req.Send() } -// DescribeGroupWithContext is the same as DescribeGroup with the addition of +// DescribeAccountCustomizationWithContext is the same as DescribeAccountCustomization with the addition of // the ability to pass a context and additional request options. // -// See DescribeGroup for details on how to use this API operation. +// See DescribeAccountCustomization for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeGroupWithContext(ctx aws.Context, input *DescribeGroupInput, opts ...request.Option) (*DescribeGroupOutput, error) { - req, out := c.DescribeGroupRequest(input) +func (c *QuickSight) DescribeAccountCustomizationWithContext(ctx aws.Context, input *DescribeAccountCustomizationInput, opts ...request.Option) (*DescribeAccountCustomizationOutput, error) { + req, out := c.DescribeAccountCustomizationRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeIAMPolicyAssignment = "DescribeIAMPolicyAssignment" +const opDescribeAccountSettings = "DescribeAccountSettings" -// DescribeIAMPolicyAssignmentRequest generates a "aws/request.Request" representing the -// client's request for the DescribeIAMPolicyAssignment operation. The "output" return +// DescribeAccountSettingsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeAccountSettings operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeIAMPolicyAssignment for more information on using the DescribeIAMPolicyAssignment +// See DescribeAccountSettings for more information on using the DescribeAccountSettings // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeIAMPolicyAssignmentRequest method. -// req, resp := client.DescribeIAMPolicyAssignmentRequest(params) +// // Example sending a request using the DescribeAccountSettingsRequest method. +// req, resp := client.DescribeAccountSettingsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeIAMPolicyAssignment -func (c *QuickSight) DescribeIAMPolicyAssignmentRequest(input *DescribeIAMPolicyAssignmentInput) (req *request.Request, output *DescribeIAMPolicyAssignmentOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeAccountSettings +func (c *QuickSight) DescribeAccountSettingsRequest(input *DescribeAccountSettingsInput) (req *request.Request, output *DescribeAccountSettingsOutput) { op := &request.Operation{ - Name: opDescribeIAMPolicyAssignment, + Name: opDescribeAccountSettings, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/iam-policy-assignments/{AssignmentName}", + HTTPPath: "/accounts/{AwsAccountId}/settings", } if input == nil { - input = &DescribeIAMPolicyAssignmentInput{} + input = &DescribeAccountSettingsInput{} } - output = &DescribeIAMPolicyAssignmentOutput{} + output = &DescribeAccountSettingsOutput{} req = c.newRequest(op, input, output) return } -// DescribeIAMPolicyAssignment API operation for Amazon QuickSight. +// DescribeAccountSettings API operation for Amazon QuickSight. // -// Describes an existing IAM policy assignment, as specified by the assignment -// name. +// Describes the settings that were used when your QuickSight subscription was +// first created in this 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. // // See the AWS API reference guide for Amazon QuickSight's -// API operation DescribeIAMPolicyAssignment for usage and error information. +// API operation DescribeAccountSettings for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -2804,88 +3079,94 @@ func (c *QuickSight) DescribeIAMPolicyAssignmentRequest(input *DescribeIAMPolicy // * ThrottlingException // Access is throttled. // -// * InvalidNextTokenException -// The NextToken value isn't valid. -// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeIAMPolicyAssignment -func (c *QuickSight) DescribeIAMPolicyAssignment(input *DescribeIAMPolicyAssignmentInput) (*DescribeIAMPolicyAssignmentOutput, error) { - req, out := c.DescribeIAMPolicyAssignmentRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeAccountSettings +func (c *QuickSight) DescribeAccountSettings(input *DescribeAccountSettingsInput) (*DescribeAccountSettingsOutput, error) { + req, out := c.DescribeAccountSettingsRequest(input) return out, req.Send() } -// DescribeIAMPolicyAssignmentWithContext is the same as DescribeIAMPolicyAssignment with the addition of +// DescribeAccountSettingsWithContext is the same as DescribeAccountSettings with the addition of // the ability to pass a context and additional request options. // -// See DescribeIAMPolicyAssignment for details on how to use this API operation. +// See DescribeAccountSettings for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeIAMPolicyAssignmentWithContext(ctx aws.Context, input *DescribeIAMPolicyAssignmentInput, opts ...request.Option) (*DescribeIAMPolicyAssignmentOutput, error) { - req, out := c.DescribeIAMPolicyAssignmentRequest(input) +func (c *QuickSight) DescribeAccountSettingsWithContext(ctx aws.Context, input *DescribeAccountSettingsInput, opts ...request.Option) (*DescribeAccountSettingsOutput, error) { + req, out := c.DescribeAccountSettingsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeIngestion = "DescribeIngestion" +const opDescribeDashboard = "DescribeDashboard" -// DescribeIngestionRequest generates a "aws/request.Request" representing the -// client's request for the DescribeIngestion operation. The "output" return +// DescribeDashboardRequest generates a "aws/request.Request" representing the +// client's request for the DescribeDashboard operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeIngestion for more information on using the DescribeIngestion +// See DescribeDashboard for more information on using the DescribeDashboard // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeIngestionRequest method. -// req, resp := client.DescribeIngestionRequest(params) +// // Example sending a request using the DescribeDashboardRequest method. +// req, resp := client.DescribeDashboardRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeIngestion -func (c *QuickSight) DescribeIngestionRequest(input *DescribeIngestionInput) (req *request.Request, output *DescribeIngestionOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDashboard +func (c *QuickSight) DescribeDashboardRequest(input *DescribeDashboardInput) (req *request.Request, output *DescribeDashboardOutput) { op := &request.Operation{ - Name: opDescribeIngestion, + Name: opDescribeDashboard, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}/ingestions/{IngestionId}", + HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}", } if input == nil { - input = &DescribeIngestionInput{} + input = &DescribeDashboardInput{} } - output = &DescribeIngestionOutput{} + output = &DescribeDashboardOutput{} req = c.newRequest(op, input, output) return } -// DescribeIngestion API operation for Amazon QuickSight. +// DescribeDashboard API operation for Amazon QuickSight. // -// Describes a SPICE ingestion. +// Provides a summary for a dashboard. // // Returns awserr.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 QuickSight's -// API operation DescribeIngestion for usage and error information. +// API operation DescribeDashboard for usage and error information. // // Returned Error Types: +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// // * AccessDeniedException // You don't have access to this item. The provided credentials couldn't be // validated. You might not be authorized to carry out the request. Make sure @@ -2893,119 +3174,103 @@ func (c *QuickSight) DescribeIngestionRequest(input *DescribeIngestionInput) (re // your policies have the correct permissions, and that you are using the correct // access keys. // -// * InvalidParameterValueException -// One or more parameters has a value that isn't valid. -// -// * ResourceNotFoundException -// One or more resources can't be found. -// // * ThrottlingException // Access is throttled. // -// * ResourceExistsException -// The resource specified already exists. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeIngestion -func (c *QuickSight) DescribeIngestion(input *DescribeIngestionInput) (*DescribeIngestionOutput, error) { - req, out := c.DescribeIngestionRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDashboard +func (c *QuickSight) DescribeDashboard(input *DescribeDashboardInput) (*DescribeDashboardOutput, error) { + req, out := c.DescribeDashboardRequest(input) return out, req.Send() } -// DescribeIngestionWithContext is the same as DescribeIngestion with the addition of +// DescribeDashboardWithContext is the same as DescribeDashboard with the addition of // the ability to pass a context and additional request options. // -// See DescribeIngestion for details on how to use this API operation. +// See DescribeDashboard for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeIngestionWithContext(ctx aws.Context, input *DescribeIngestionInput, opts ...request.Option) (*DescribeIngestionOutput, error) { - req, out := c.DescribeIngestionRequest(input) +func (c *QuickSight) DescribeDashboardWithContext(ctx aws.Context, input *DescribeDashboardInput, opts ...request.Option) (*DescribeDashboardOutput, error) { + req, out := c.DescribeDashboardRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeTemplate = "DescribeTemplate" +const opDescribeDashboardPermissions = "DescribeDashboardPermissions" -// DescribeTemplateRequest generates a "aws/request.Request" representing the -// client's request for the DescribeTemplate operation. The "output" return +// DescribeDashboardPermissionsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeDashboardPermissions operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeTemplate for more information on using the DescribeTemplate +// See DescribeDashboardPermissions for more information on using the DescribeDashboardPermissions // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeTemplateRequest method. -// req, resp := client.DescribeTemplateRequest(params) +// // Example sending a request using the DescribeDashboardPermissionsRequest method. +// req, resp := client.DescribeDashboardPermissionsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplate -func (c *QuickSight) DescribeTemplateRequest(input *DescribeTemplateInput) (req *request.Request, output *DescribeTemplateOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDashboardPermissions +func (c *QuickSight) DescribeDashboardPermissionsRequest(input *DescribeDashboardPermissionsInput) (req *request.Request, output *DescribeDashboardPermissionsOutput) { op := &request.Operation{ - Name: opDescribeTemplate, + Name: opDescribeDashboardPermissions, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}", + HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}/permissions", } if input == nil { - input = &DescribeTemplateInput{} + input = &DescribeDashboardPermissionsInput{} } - output = &DescribeTemplateOutput{} + output = &DescribeDashboardPermissionsOutput{} req = c.newRequest(op, input, output) return } -// DescribeTemplate API operation for Amazon QuickSight. +// DescribeDashboardPermissions API operation for Amazon QuickSight. // -// Describes a template's metadata. +// Describes read and write permissions for a dashboard. // // Returns awserr.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 QuickSight's -// API operation DescribeTemplate for usage and error information. +// API operation DescribeDashboardPermissions for usage and error information. // // Returned Error Types: // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. -// -// * ResourceExistsException -// The resource specified already exists. -// // * ResourceNotFoundException // One or more resources can't be found. // // * ThrottlingException // Access is throttled. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. -// // * UnsupportedUserEditionException // This error indicates that you are calling an operation on an Amazon QuickSight // subscription where the edition doesn't include support for that operation. @@ -3015,268 +3280,272 @@ func (c *QuickSight) DescribeTemplateRequest(input *DescribeTemplateInput) (req // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplate -func (c *QuickSight) DescribeTemplate(input *DescribeTemplateInput) (*DescribeTemplateOutput, error) { - req, out := c.DescribeTemplateRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDashboardPermissions +func (c *QuickSight) DescribeDashboardPermissions(input *DescribeDashboardPermissionsInput) (*DescribeDashboardPermissionsOutput, error) { + req, out := c.DescribeDashboardPermissionsRequest(input) return out, req.Send() } -// DescribeTemplateWithContext is the same as DescribeTemplate with the addition of +// DescribeDashboardPermissionsWithContext is the same as DescribeDashboardPermissions with the addition of // the ability to pass a context and additional request options. // -// See DescribeTemplate for details on how to use this API operation. +// See DescribeDashboardPermissions for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeTemplateWithContext(ctx aws.Context, input *DescribeTemplateInput, opts ...request.Option) (*DescribeTemplateOutput, error) { - req, out := c.DescribeTemplateRequest(input) +func (c *QuickSight) DescribeDashboardPermissionsWithContext(ctx aws.Context, input *DescribeDashboardPermissionsInput, opts ...request.Option) (*DescribeDashboardPermissionsOutput, error) { + req, out := c.DescribeDashboardPermissionsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeTemplateAlias = "DescribeTemplateAlias" +const opDescribeDataSet = "DescribeDataSet" -// DescribeTemplateAliasRequest generates a "aws/request.Request" representing the -// client's request for the DescribeTemplateAlias operation. The "output" return +// DescribeDataSetRequest generates a "aws/request.Request" representing the +// client's request for the DescribeDataSet operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeTemplateAlias for more information on using the DescribeTemplateAlias +// See DescribeDataSet for more information on using the DescribeDataSet // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeTemplateAliasRequest method. -// req, resp := client.DescribeTemplateAliasRequest(params) +// // Example sending a request using the DescribeDataSetRequest method. +// req, resp := client.DescribeDataSetRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplateAlias -func (c *QuickSight) DescribeTemplateAliasRequest(input *DescribeTemplateAliasInput) (req *request.Request, output *DescribeTemplateAliasOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSet +func (c *QuickSight) DescribeDataSetRequest(input *DescribeDataSetInput) (req *request.Request, output *DescribeDataSetOutput) { op := &request.Operation{ - Name: opDescribeTemplateAlias, + Name: opDescribeDataSet, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/aliases/{AliasName}", + HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}", } if input == nil { - input = &DescribeTemplateAliasInput{} + input = &DescribeDataSetInput{} } - output = &DescribeTemplateAliasOutput{} + output = &DescribeDataSetOutput{} req = c.newRequest(op, input, output) return } -// DescribeTemplateAlias API operation for Amazon QuickSight. +// DescribeDataSet API operation for Amazon QuickSight. // -// Describes the template alias for a template. +// Describes a dataset. // // Returns awserr.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 QuickSight's -// API operation DescribeTemplateAlias for usage and error information. +// API operation DescribeDataSet for usage and error information. // // Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// // * ThrottlingException // Access is throttled. // // * ResourceNotFoundException // One or more resources can't be found. // -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. -// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplateAlias -func (c *QuickSight) DescribeTemplateAlias(input *DescribeTemplateAliasInput) (*DescribeTemplateAliasOutput, error) { - req, out := c.DescribeTemplateAliasRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSet +func (c *QuickSight) DescribeDataSet(input *DescribeDataSetInput) (*DescribeDataSetOutput, error) { + req, out := c.DescribeDataSetRequest(input) return out, req.Send() } -// DescribeTemplateAliasWithContext is the same as DescribeTemplateAlias with the addition of +// DescribeDataSetWithContext is the same as DescribeDataSet with the addition of // the ability to pass a context and additional request options. // -// See DescribeTemplateAlias for details on how to use this API operation. +// See DescribeDataSet for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeTemplateAliasWithContext(ctx aws.Context, input *DescribeTemplateAliasInput, opts ...request.Option) (*DescribeTemplateAliasOutput, error) { - req, out := c.DescribeTemplateAliasRequest(input) +func (c *QuickSight) DescribeDataSetWithContext(ctx aws.Context, input *DescribeDataSetInput, opts ...request.Option) (*DescribeDataSetOutput, error) { + req, out := c.DescribeDataSetRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeTemplatePermissions = "DescribeTemplatePermissions" +const opDescribeDataSetPermissions = "DescribeDataSetPermissions" -// DescribeTemplatePermissionsRequest generates a "aws/request.Request" representing the -// client's request for the DescribeTemplatePermissions operation. The "output" return +// DescribeDataSetPermissionsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeDataSetPermissions operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeTemplatePermissions for more information on using the DescribeTemplatePermissions +// See DescribeDataSetPermissions for more information on using the DescribeDataSetPermissions // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeTemplatePermissionsRequest method. -// req, resp := client.DescribeTemplatePermissionsRequest(params) +// // Example sending a request using the DescribeDataSetPermissionsRequest method. +// req, resp := client.DescribeDataSetPermissionsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplatePermissions -func (c *QuickSight) DescribeTemplatePermissionsRequest(input *DescribeTemplatePermissionsInput) (req *request.Request, output *DescribeTemplatePermissionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSetPermissions +func (c *QuickSight) DescribeDataSetPermissionsRequest(input *DescribeDataSetPermissionsInput) (req *request.Request, output *DescribeDataSetPermissionsOutput) { op := &request.Operation{ - Name: opDescribeTemplatePermissions, + Name: opDescribeDataSetPermissions, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/permissions", + HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}/permissions", } if input == nil { - input = &DescribeTemplatePermissionsInput{} + input = &DescribeDataSetPermissionsInput{} } - output = &DescribeTemplatePermissionsOutput{} + output = &DescribeDataSetPermissionsOutput{} req = c.newRequest(op, input, output) return } -// DescribeTemplatePermissions API operation for Amazon QuickSight. +// DescribeDataSetPermissions API operation for Amazon QuickSight. // -// Describes read and write permissions on a template. +// Describes the permissions on a dataset. +// +// The permissions resource is arn:aws:quicksight:region:aws-account-id:dataset/data-set-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 // the error. // // See the AWS API reference guide for Amazon QuickSight's -// API operation DescribeTemplatePermissions for usage and error information. +// API operation DescribeDataSetPermissions for usage and error information. // // Returned Error Types: -// * ThrottlingException -// Access is throttled. +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. +// * ThrottlingException +// Access is throttled. // // * ResourceNotFoundException // One or more resources can't be found. // -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. -// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplatePermissions -func (c *QuickSight) DescribeTemplatePermissions(input *DescribeTemplatePermissionsInput) (*DescribeTemplatePermissionsOutput, error) { - req, out := c.DescribeTemplatePermissionsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSetPermissions +func (c *QuickSight) DescribeDataSetPermissions(input *DescribeDataSetPermissionsInput) (*DescribeDataSetPermissionsOutput, error) { + req, out := c.DescribeDataSetPermissionsRequest(input) return out, req.Send() } -// DescribeTemplatePermissionsWithContext is the same as DescribeTemplatePermissions with the addition of +// DescribeDataSetPermissionsWithContext is the same as DescribeDataSetPermissions with the addition of // the ability to pass a context and additional request options. // -// See DescribeTemplatePermissions for details on how to use this API operation. +// See DescribeDataSetPermissions for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeTemplatePermissionsWithContext(ctx aws.Context, input *DescribeTemplatePermissionsInput, opts ...request.Option) (*DescribeTemplatePermissionsOutput, error) { - req, out := c.DescribeTemplatePermissionsRequest(input) +func (c *QuickSight) DescribeDataSetPermissionsWithContext(ctx aws.Context, input *DescribeDataSetPermissionsInput, opts ...request.Option) (*DescribeDataSetPermissionsOutput, error) { + req, out := c.DescribeDataSetPermissionsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opDescribeUser = "DescribeUser" +const opDescribeDataSource = "DescribeDataSource" -// DescribeUserRequest generates a "aws/request.Request" representing the -// client's request for the DescribeUser operation. The "output" return +// DescribeDataSourceRequest generates a "aws/request.Request" representing the +// client's request for the DescribeDataSource operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See DescribeUser for more information on using the DescribeUser +// See DescribeDataSource for more information on using the DescribeDataSource // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the DescribeUserRequest method. -// req, resp := client.DescribeUserRequest(params) +// // Example sending a request using the DescribeDataSourceRequest method. +// req, resp := client.DescribeDataSourceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeUser -func (c *QuickSight) DescribeUserRequest(input *DescribeUserInput) (req *request.Request, output *DescribeUserOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSource +func (c *QuickSight) DescribeDataSourceRequest(input *DescribeDataSourceInput) (req *request.Request, output *DescribeDataSourceOutput) { op := &request.Operation{ - Name: opDescribeUser, + Name: opDescribeDataSource, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users/{UserName}", + HTTPPath: "/accounts/{AwsAccountId}/data-sources/{DataSourceId}", } if input == nil { - input = &DescribeUserInput{} + input = &DescribeDataSourceInput{} } - output = &DescribeUserOutput{} + output = &DescribeDataSourceOutput{} req = c.newRequest(op, input, output) return } -// DescribeUser API operation for Amazon QuickSight. +// DescribeDataSource API operation for Amazon QuickSight. // -// Returns information about a user, given the user name. +// Describes a data source. // // Returns awserr.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 QuickSight's -// API operation DescribeUser for usage and error information. +// API operation DescribeDataSource for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -3289,100 +3558,89 @@ func (c *QuickSight) DescribeUserRequest(input *DescribeUserInput) (req *request // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ResourceNotFoundException -// One or more resources can't be found. -// // * ThrottlingException // Access is throttled. // +// * ResourceNotFoundException +// One or more resources can't be found. +// // * InternalFailureException // An internal failure occurred. // -// * ResourceUnavailableException -// This resource is currently unavailable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeUser -func (c *QuickSight) DescribeUser(input *DescribeUserInput) (*DescribeUserOutput, error) { - req, out := c.DescribeUserRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSource +func (c *QuickSight) DescribeDataSource(input *DescribeDataSourceInput) (*DescribeDataSourceOutput, error) { + req, out := c.DescribeDataSourceRequest(input) return out, req.Send() } -// DescribeUserWithContext is the same as DescribeUser with the addition of +// DescribeDataSourceWithContext is the same as DescribeDataSource with the addition of // the ability to pass a context and additional request options. // -// See DescribeUser for details on how to use this API operation. +// See DescribeDataSource for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) DescribeUserWithContext(ctx aws.Context, input *DescribeUserInput, opts ...request.Option) (*DescribeUserOutput, error) { - req, out := c.DescribeUserRequest(input) +func (c *QuickSight) DescribeDataSourceWithContext(ctx aws.Context, input *DescribeDataSourceInput, opts ...request.Option) (*DescribeDataSourceOutput, error) { + req, out := c.DescribeDataSourceRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opGetDashboardEmbedUrl = "GetDashboardEmbedUrl" +const opDescribeDataSourcePermissions = "DescribeDataSourcePermissions" -// GetDashboardEmbedUrlRequest generates a "aws/request.Request" representing the -// client's request for the GetDashboardEmbedUrl operation. The "output" return +// DescribeDataSourcePermissionsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeDataSourcePermissions operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See GetDashboardEmbedUrl for more information on using the GetDashboardEmbedUrl +// See DescribeDataSourcePermissions for more information on using the DescribeDataSourcePermissions // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the GetDashboardEmbedUrlRequest method. -// req, resp := client.GetDashboardEmbedUrlRequest(params) +// // Example sending a request using the DescribeDataSourcePermissionsRequest method. +// req, resp := client.DescribeDataSourcePermissionsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/GetDashboardEmbedUrl -func (c *QuickSight) GetDashboardEmbedUrlRequest(input *GetDashboardEmbedUrlInput) (req *request.Request, output *GetDashboardEmbedUrlOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSourcePermissions +func (c *QuickSight) DescribeDataSourcePermissionsRequest(input *DescribeDataSourcePermissionsInput) (req *request.Request, output *DescribeDataSourcePermissionsOutput) { op := &request.Operation{ - Name: opGetDashboardEmbedUrl, + Name: opDescribeDataSourcePermissions, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}/embed-url", + HTTPPath: "/accounts/{AwsAccountId}/data-sources/{DataSourceId}/permissions", } if input == nil { - input = &GetDashboardEmbedUrlInput{} + input = &DescribeDataSourcePermissionsInput{} } - output = &GetDashboardEmbedUrlOutput{} + output = &DescribeDataSourcePermissionsOutput{} req = c.newRequest(op, input, output) return } -// GetDashboardEmbedUrl API operation for Amazon QuickSight. -// -// Generates a server-side embeddable URL and authorization code. For this process -// to work properly, first configure the dashboards and user permissions. For -// more information, see Embedding Amazon QuickSight Dashboards (https://docs.aws.amazon.com/quicksight/latest/user/embedding-dashboards.html) -// in the Amazon QuickSight User Guide or Embedding Amazon QuickSight Dashboards -// (https://docs.aws.amazon.com/quicksight/latest/APIReference/qs-dev-embedded-dashboards.html) -// in the Amazon QuickSight API Reference. +// DescribeDataSourcePermissions API operation for Amazon QuickSight. // -// Currently, you can use GetDashboardEmbedURL only from the server, not from -// the user’s browser. +// Describes the resource permissions for a data source. // // Returns awserr.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 QuickSight's -// API operation GetDashboardEmbedUrl for usage and error information. +// API operation DescribeDataSourcePermissions for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -3395,123 +3653,99 @@ func (c *QuickSight) GetDashboardEmbedUrlRequest(input *GetDashboardEmbedUrlInpu // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ResourceExistsException -// The resource specified already exists. -// -// * ResourceNotFoundException -// One or more resources can't be found. -// // * ThrottlingException // Access is throttled. // -// * DomainNotWhitelistedException -// The domain specified isn't on the allow list. All domains for embedded dashboards -// must be added to the approved list by an Amazon QuickSight admin. -// -// * UserNotFoundException -// The user with the provided name isn't found. This error can happen in any -// operation that requires finding a user based on a provided user name, such -// as DeleteUser, DescribeUser, and so on. -// -// * IdentityTypeNotSupportedException -// The identity type specified isn't supported. Supported identity types include -// IAM and QUICKSIGHT. -// -// * SessionLifetimeInMinutesInvalidException -// The number of minutes specified for the lifetime of a session isn't valid. -// The session lifetime must be 15-600 minutes. -// -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. +// * ResourceNotFoundException +// One or more resources can't be found. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/GetDashboardEmbedUrl -func (c *QuickSight) GetDashboardEmbedUrl(input *GetDashboardEmbedUrlInput) (*GetDashboardEmbedUrlOutput, error) { - req, out := c.GetDashboardEmbedUrlRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeDataSourcePermissions +func (c *QuickSight) DescribeDataSourcePermissions(input *DescribeDataSourcePermissionsInput) (*DescribeDataSourcePermissionsOutput, error) { + req, out := c.DescribeDataSourcePermissionsRequest(input) return out, req.Send() } -// GetDashboardEmbedUrlWithContext is the same as GetDashboardEmbedUrl with the addition of +// DescribeDataSourcePermissionsWithContext is the same as DescribeDataSourcePermissions with the addition of // the ability to pass a context and additional request options. // -// See GetDashboardEmbedUrl for details on how to use this API operation. +// See DescribeDataSourcePermissions for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) GetDashboardEmbedUrlWithContext(ctx aws.Context, input *GetDashboardEmbedUrlInput, opts ...request.Option) (*GetDashboardEmbedUrlOutput, error) { - req, out := c.GetDashboardEmbedUrlRequest(input) +func (c *QuickSight) DescribeDataSourcePermissionsWithContext(ctx aws.Context, input *DescribeDataSourcePermissionsInput, opts ...request.Option) (*DescribeDataSourcePermissionsOutput, error) { + req, out := c.DescribeDataSourcePermissionsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opListDashboardVersions = "ListDashboardVersions" +const opDescribeGroup = "DescribeGroup" -// ListDashboardVersionsRequest generates a "aws/request.Request" representing the -// client's request for the ListDashboardVersions operation. The "output" return +// DescribeGroupRequest generates a "aws/request.Request" representing the +// client's request for the DescribeGroup operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListDashboardVersions for more information on using the ListDashboardVersions +// See DescribeGroup for more information on using the DescribeGroup // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListDashboardVersionsRequest method. -// req, resp := client.ListDashboardVersionsRequest(params) +// // Example sending a request using the DescribeGroupRequest method. +// req, resp := client.DescribeGroupRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDashboardVersions -func (c *QuickSight) ListDashboardVersionsRequest(input *ListDashboardVersionsInput) (req *request.Request, output *ListDashboardVersionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeGroup +func (c *QuickSight) DescribeGroupRequest(input *DescribeGroupInput) (req *request.Request, output *DescribeGroupOutput) { op := &request.Operation{ - Name: opListDashboardVersions, + Name: opDescribeGroup, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}/versions", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, - OutputTokens: []string{"NextToken"}, - LimitToken: "MaxResults", - TruncationToken: "", - }, + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups/{GroupName}", } if input == nil { - input = &ListDashboardVersionsInput{} + input = &DescribeGroupInput{} } - output = &ListDashboardVersionsOutput{} + output = &DescribeGroupOutput{} req = c.newRequest(op, input, output) return } -// ListDashboardVersions API operation for Amazon QuickSight. +// DescribeGroup API operation for Amazon QuickSight. // -// Lists all the versions of the dashboards in the QuickSight subscription. +// Returns an Amazon QuickSight group's description and Amazon Resource Name +// (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 Amazon QuickSight's -// API operation ListDashboardVersions for usage and error information. +// API operation DescribeGroup for usage and error information. // // Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // @@ -3521,302 +3755,188 @@ func (c *QuickSight) ListDashboardVersionsRequest(input *ListDashboardVersionsIn // * ThrottlingException // Access is throttled. // -// * InvalidNextTokenException -// The NextToken value isn't valid. -// -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. +// * PreconditionNotMetException +// One or more preconditions aren't met. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDashboardVersions -func (c *QuickSight) ListDashboardVersions(input *ListDashboardVersionsInput) (*ListDashboardVersionsOutput, error) { - req, out := c.ListDashboardVersionsRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeGroup +func (c *QuickSight) DescribeGroup(input *DescribeGroupInput) (*DescribeGroupOutput, error) { + req, out := c.DescribeGroupRequest(input) return out, req.Send() } -// ListDashboardVersionsWithContext is the same as ListDashboardVersions with the addition of +// DescribeGroupWithContext is the same as DescribeGroup with the addition of // the ability to pass a context and additional request options. // -// See ListDashboardVersions for details on how to use this API operation. +// See DescribeGroup for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListDashboardVersionsWithContext(ctx aws.Context, input *ListDashboardVersionsInput, opts ...request.Option) (*ListDashboardVersionsOutput, error) { - req, out := c.ListDashboardVersionsRequest(input) +func (c *QuickSight) DescribeGroupWithContext(ctx aws.Context, input *DescribeGroupInput, opts ...request.Option) (*DescribeGroupOutput, error) { + req, out := c.DescribeGroupRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListDashboardVersionsPages iterates over the pages of a ListDashboardVersions operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. +const opDescribeIAMPolicyAssignment = "DescribeIAMPolicyAssignment" + +// DescribeIAMPolicyAssignmentRequest generates a "aws/request.Request" representing the +// client's request for the DescribeIAMPolicyAssignment operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// See ListDashboardVersions method for more information on how to use this operation. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListDashboardVersions operation. -// pageNum := 0 -// err := client.ListDashboardVersionsPages(params, -// func(page *quicksight.ListDashboardVersionsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *QuickSight) ListDashboardVersionsPages(input *ListDashboardVersionsInput, fn func(*ListDashboardVersionsOutput, bool) bool) error { - return c.ListDashboardVersionsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListDashboardVersionsPagesWithContext same as ListDashboardVersionsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *QuickSight) ListDashboardVersionsPagesWithContext(ctx aws.Context, input *ListDashboardVersionsInput, fn func(*ListDashboardVersionsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListDashboardVersionsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListDashboardVersionsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*ListDashboardVersionsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opListDashboards = "ListDashboards" - -// ListDashboardsRequest generates a "aws/request.Request" representing the -// client's request for the ListDashboards operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListDashboards for more information on using the ListDashboards -// API call, and error handling. +// See DescribeIAMPolicyAssignment for more information on using the DescribeIAMPolicyAssignment +// API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListDashboardsRequest method. -// req, resp := client.ListDashboardsRequest(params) +// // Example sending a request using the DescribeIAMPolicyAssignmentRequest method. +// req, resp := client.DescribeIAMPolicyAssignmentRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDashboards -func (c *QuickSight) ListDashboardsRequest(input *ListDashboardsInput) (req *request.Request, output *ListDashboardsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeIAMPolicyAssignment +func (c *QuickSight) DescribeIAMPolicyAssignmentRequest(input *DescribeIAMPolicyAssignmentInput) (req *request.Request, output *DescribeIAMPolicyAssignmentOutput) { op := &request.Operation{ - Name: opListDashboards, + Name: opDescribeIAMPolicyAssignment, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/dashboards", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, - OutputTokens: []string{"NextToken"}, - LimitToken: "MaxResults", - TruncationToken: "", - }, + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/iam-policy-assignments/{AssignmentName}", } if input == nil { - input = &ListDashboardsInput{} + input = &DescribeIAMPolicyAssignmentInput{} } - output = &ListDashboardsOutput{} + output = &DescribeIAMPolicyAssignmentOutput{} req = c.newRequest(op, input, output) return } -// ListDashboards API operation for Amazon QuickSight. +// DescribeIAMPolicyAssignment API operation for Amazon QuickSight. // -// Lists dashboards in an AWS account. +// Describes an existing IAM policy assignment, as specified by the assignment +// 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 QuickSight's -// API operation ListDashboards for usage and error information. +// API operation DescribeIAMPolicyAssignment for usage and error information. // // Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// // * ThrottlingException // Access is throttled. // // * InvalidNextTokenException // The NextToken value isn't valid. // -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. -// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDashboards -func (c *QuickSight) ListDashboards(input *ListDashboardsInput) (*ListDashboardsOutput, error) { - req, out := c.ListDashboardsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeIAMPolicyAssignment +func (c *QuickSight) DescribeIAMPolicyAssignment(input *DescribeIAMPolicyAssignmentInput) (*DescribeIAMPolicyAssignmentOutput, error) { + req, out := c.DescribeIAMPolicyAssignmentRequest(input) return out, req.Send() } -// ListDashboardsWithContext is the same as ListDashboards with the addition of +// DescribeIAMPolicyAssignmentWithContext is the same as DescribeIAMPolicyAssignment with the addition of // the ability to pass a context and additional request options. // -// See ListDashboards for details on how to use this API operation. +// See DescribeIAMPolicyAssignment for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListDashboardsWithContext(ctx aws.Context, input *ListDashboardsInput, opts ...request.Option) (*ListDashboardsOutput, error) { - req, out := c.ListDashboardsRequest(input) +func (c *QuickSight) DescribeIAMPolicyAssignmentWithContext(ctx aws.Context, input *DescribeIAMPolicyAssignmentInput, opts ...request.Option) (*DescribeIAMPolicyAssignmentOutput, error) { + req, out := c.DescribeIAMPolicyAssignmentRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListDashboardsPages iterates over the pages of a ListDashboards operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListDashboards 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 ListDashboards operation. -// pageNum := 0 -// err := client.ListDashboardsPages(params, -// func(page *quicksight.ListDashboardsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *QuickSight) ListDashboardsPages(input *ListDashboardsInput, fn func(*ListDashboardsOutput, bool) bool) error { - return c.ListDashboardsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListDashboardsPagesWithContext same as ListDashboardsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *QuickSight) ListDashboardsPagesWithContext(ctx aws.Context, input *ListDashboardsInput, fn func(*ListDashboardsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListDashboardsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListDashboardsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*ListDashboardsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opListDataSets = "ListDataSets" +const opDescribeIngestion = "DescribeIngestion" -// ListDataSetsRequest generates a "aws/request.Request" representing the -// client's request for the ListDataSets operation. The "output" return +// DescribeIngestionRequest generates a "aws/request.Request" representing the +// client's request for the DescribeIngestion operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListDataSets for more information on using the ListDataSets +// See DescribeIngestion for more information on using the DescribeIngestion // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListDataSetsRequest method. -// req, resp := client.ListDataSetsRequest(params) +// // Example sending a request using the DescribeIngestionRequest method. +// req, resp := client.DescribeIngestionRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDataSets -func (c *QuickSight) ListDataSetsRequest(input *ListDataSetsInput) (req *request.Request, output *ListDataSetsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeIngestion +func (c *QuickSight) DescribeIngestionRequest(input *DescribeIngestionInput) (req *request.Request, output *DescribeIngestionOutput) { op := &request.Operation{ - Name: opListDataSets, + Name: opDescribeIngestion, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/data-sets", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, - OutputTokens: []string{"NextToken"}, - LimitToken: "MaxResults", - TruncationToken: "", - }, + HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}/ingestions/{IngestionId}", } if input == nil { - input = &ListDataSetsInput{} + input = &DescribeIngestionInput{} } - output = &ListDataSetsOutput{} + output = &DescribeIngestionOutput{} req = c.newRequest(op, input, output) return } -// ListDataSets API operation for Amazon QuickSight. -// -// Lists all of the datasets belonging to the current AWS account in an AWS -// Region. +// DescribeIngestion API operation for Amazon QuickSight. // -// The permissions resource is arn:aws:quicksight:region:aws-account-id:dataset/*. +// Describes a SPICE ingestion. // // Returns awserr.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 QuickSight's -// API operation ListDataSets for usage and error information. +// API operation DescribeIngestion for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -3829,147 +3949,92 @@ func (c *QuickSight) ListDataSetsRequest(input *ListDataSetsInput) (req *request // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ResourceNotFoundException +// One or more resources can't be found. +// // * ThrottlingException // Access is throttled. // -// * InvalidNextTokenException -// The NextToken value isn't valid. +// * ResourceExistsException +// The resource specified already exists. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDataSets -func (c *QuickSight) ListDataSets(input *ListDataSetsInput) (*ListDataSetsOutput, error) { - req, out := c.ListDataSetsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeIngestion +func (c *QuickSight) DescribeIngestion(input *DescribeIngestionInput) (*DescribeIngestionOutput, error) { + req, out := c.DescribeIngestionRequest(input) return out, req.Send() } -// ListDataSetsWithContext is the same as ListDataSets with the addition of +// DescribeIngestionWithContext is the same as DescribeIngestion with the addition of // the ability to pass a context and additional request options. // -// See ListDataSets for details on how to use this API operation. +// See DescribeIngestion for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListDataSetsWithContext(ctx aws.Context, input *ListDataSetsInput, opts ...request.Option) (*ListDataSetsOutput, error) { - req, out := c.ListDataSetsRequest(input) +func (c *QuickSight) DescribeIngestionWithContext(ctx aws.Context, input *DescribeIngestionInput, opts ...request.Option) (*DescribeIngestionOutput, error) { + req, out := c.DescribeIngestionRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListDataSetsPages iterates over the pages of a ListDataSets operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. +const opDescribeNamespace = "DescribeNamespace" + +// DescribeNamespaceRequest generates a "aws/request.Request" representing the +// client's request for the DescribeNamespace operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. // -// See ListDataSets method for more information on how to use this operation. +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. // -// Note: This operation can generate multiple requests to a service. +// See DescribeNamespace for more information on using the DescribeNamespace +// API call, and error handling. // -// // Example iterating over at most 3 pages of a ListDataSets operation. -// pageNum := 0 -// err := client.ListDataSetsPages(params, -// func(page *quicksight.ListDataSetsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. // -func (c *QuickSight) ListDataSetsPages(input *ListDataSetsInput, fn func(*ListDataSetsOutput, bool) bool) error { - return c.ListDataSetsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListDataSetsPagesWithContext same as ListDataSetsPages except -// it takes a Context and allows setting request options on the pages. // -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *QuickSight) ListDataSetsPagesWithContext(ctx aws.Context, input *ListDataSetsInput, fn func(*ListDataSetsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListDataSetsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListDataSetsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*ListDataSetsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opListDataSources = "ListDataSources" - -// ListDataSourcesRequest generates a "aws/request.Request" representing the -// client's request for the ListDataSources operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListDataSources for more information on using the ListDataSources -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListDataSourcesRequest method. -// req, resp := client.ListDataSourcesRequest(params) +// // Example sending a request using the DescribeNamespaceRequest method. +// req, resp := client.DescribeNamespaceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDataSources -func (c *QuickSight) ListDataSourcesRequest(input *ListDataSourcesInput) (req *request.Request, output *ListDataSourcesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeNamespace +func (c *QuickSight) DescribeNamespaceRequest(input *DescribeNamespaceInput) (req *request.Request, output *DescribeNamespaceOutput) { op := &request.Operation{ - Name: opListDataSources, + Name: opDescribeNamespace, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/data-sources", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, - OutputTokens: []string{"NextToken"}, - LimitToken: "MaxResults", - TruncationToken: "", - }, + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}", } if input == nil { - input = &ListDataSourcesInput{} + input = &DescribeNamespaceInput{} } - output = &ListDataSourcesOutput{} + output = &DescribeNamespaceOutput{} req = c.newRequest(op, input, output) return } -// ListDataSources API operation for Amazon QuickSight. +// DescribeNamespace API operation for Amazon QuickSight. // -// Lists data sources in current AWS Region that belong to this AWS account. +// Describes the current namespace. // // Returns awserr.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 QuickSight's -// API operation ListDataSources for usage and error information. +// API operation DescribeNamespace for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -3982,143 +4047,97 @@ func (c *QuickSight) ListDataSourcesRequest(input *ListDataSourcesInput) (req *r // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ResourceNotFoundException +// One or more resources can't be found. +// // * ThrottlingException // Access is throttled. // -// * InvalidNextTokenException -// The NextToken value isn't valid. -// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDataSources -func (c *QuickSight) ListDataSources(input *ListDataSourcesInput) (*ListDataSourcesOutput, error) { - req, out := c.ListDataSourcesRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeNamespace +func (c *QuickSight) DescribeNamespace(input *DescribeNamespaceInput) (*DescribeNamespaceOutput, error) { + req, out := c.DescribeNamespaceRequest(input) return out, req.Send() } -// ListDataSourcesWithContext is the same as ListDataSources with the addition of +// DescribeNamespaceWithContext is the same as DescribeNamespace with the addition of // the ability to pass a context and additional request options. // -// See ListDataSources for details on how to use this API operation. +// See DescribeNamespace for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListDataSourcesWithContext(ctx aws.Context, input *ListDataSourcesInput, opts ...request.Option) (*ListDataSourcesOutput, error) { - req, out := c.ListDataSourcesRequest(input) +func (c *QuickSight) DescribeNamespaceWithContext(ctx aws.Context, input *DescribeNamespaceInput, opts ...request.Option) (*DescribeNamespaceOutput, error) { + req, out := c.DescribeNamespaceRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListDataSourcesPages iterates over the pages of a ListDataSources operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListDataSources 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 ListDataSources operation. -// pageNum := 0 -// err := client.ListDataSourcesPages(params, -// func(page *quicksight.ListDataSourcesOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *QuickSight) ListDataSourcesPages(input *ListDataSourcesInput, fn func(*ListDataSourcesOutput, bool) bool) error { - return c.ListDataSourcesPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListDataSourcesPagesWithContext same as ListDataSourcesPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *QuickSight) ListDataSourcesPagesWithContext(ctx aws.Context, input *ListDataSourcesInput, fn func(*ListDataSourcesOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListDataSourcesInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListDataSourcesRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*ListDataSourcesOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opListGroupMemberships = "ListGroupMemberships" +const opDescribeTemplate = "DescribeTemplate" -// ListGroupMembershipsRequest generates a "aws/request.Request" representing the -// client's request for the ListGroupMemberships operation. The "output" return +// DescribeTemplateRequest generates a "aws/request.Request" representing the +// client's request for the DescribeTemplate operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListGroupMemberships for more information on using the ListGroupMemberships +// See DescribeTemplate for more information on using the DescribeTemplate // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListGroupMembershipsRequest method. -// req, resp := client.ListGroupMembershipsRequest(params) +// // Example sending a request using the DescribeTemplateRequest method. +// req, resp := client.DescribeTemplateRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListGroupMemberships -func (c *QuickSight) ListGroupMembershipsRequest(input *ListGroupMembershipsInput) (req *request.Request, output *ListGroupMembershipsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplate +func (c *QuickSight) DescribeTemplateRequest(input *DescribeTemplateInput) (req *request.Request, output *DescribeTemplateOutput) { op := &request.Operation{ - Name: opListGroupMemberships, + Name: opDescribeTemplate, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups/{GroupName}/members", + HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}", } if input == nil { - input = &ListGroupMembershipsInput{} + input = &DescribeTemplateInput{} } - output = &ListGroupMembershipsOutput{} + output = &DescribeTemplateOutput{} req = c.newRequest(op, input, output) return } -// ListGroupMemberships API operation for Amazon QuickSight. +// DescribeTemplate API operation for Amazon QuickSight. // -// Lists member users in a group. +// Describes a template's metadata. // // Returns awserr.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 QuickSight's -// API operation ListGroupMemberships for usage and error information. +// API operation DescribeTemplate for usage and error information. // // Returned Error Types: +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// // * AccessDeniedException // You don't have access to this item. The provided credentials couldn't be // validated. You might not be authorized to carry out the request. Make sure @@ -4126,8 +4145,8 @@ func (c *QuickSight) ListGroupMembershipsRequest(input *ListGroupMembershipsInpu // your policies have the correct permissions, and that you are using the correct // access keys. // -// * InvalidParameterValueException -// One or more parameters has a value that isn't valid. +// * ResourceExistsException +// The resource specified already exists. // // * ResourceNotFoundException // One or more resources can't be found. @@ -4135,296 +4154,280 @@ func (c *QuickSight) ListGroupMembershipsRequest(input *ListGroupMembershipsInpu // * ThrottlingException // Access is throttled. // -// * InvalidNextTokenException -// The NextToken value isn't valid. +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. // -// * PreconditionNotMetException -// One or more preconditions aren't met. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// * ResourceUnavailableException -// This resource is currently unavailable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListGroupMemberships -func (c *QuickSight) ListGroupMemberships(input *ListGroupMembershipsInput) (*ListGroupMembershipsOutput, error) { - req, out := c.ListGroupMembershipsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplate +func (c *QuickSight) DescribeTemplate(input *DescribeTemplateInput) (*DescribeTemplateOutput, error) { + req, out := c.DescribeTemplateRequest(input) return out, req.Send() } -// ListGroupMembershipsWithContext is the same as ListGroupMemberships with the addition of +// DescribeTemplateWithContext is the same as DescribeTemplate with the addition of // the ability to pass a context and additional request options. // -// See ListGroupMemberships for details on how to use this API operation. +// See DescribeTemplate for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListGroupMembershipsWithContext(ctx aws.Context, input *ListGroupMembershipsInput, opts ...request.Option) (*ListGroupMembershipsOutput, error) { - req, out := c.ListGroupMembershipsRequest(input) +func (c *QuickSight) DescribeTemplateWithContext(ctx aws.Context, input *DescribeTemplateInput, opts ...request.Option) (*DescribeTemplateOutput, error) { + req, out := c.DescribeTemplateRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opListGroups = "ListGroups" +const opDescribeTemplateAlias = "DescribeTemplateAlias" -// ListGroupsRequest generates a "aws/request.Request" representing the -// client's request for the ListGroups operation. The "output" return +// DescribeTemplateAliasRequest generates a "aws/request.Request" representing the +// client's request for the DescribeTemplateAlias operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListGroups for more information on using the ListGroups +// See DescribeTemplateAlias for more information on using the DescribeTemplateAlias // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListGroupsRequest method. -// req, resp := client.ListGroupsRequest(params) +// // Example sending a request using the DescribeTemplateAliasRequest method. +// req, resp := client.DescribeTemplateAliasRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListGroups -func (c *QuickSight) ListGroupsRequest(input *ListGroupsInput) (req *request.Request, output *ListGroupsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplateAlias +func (c *QuickSight) DescribeTemplateAliasRequest(input *DescribeTemplateAliasInput) (req *request.Request, output *DescribeTemplateAliasOutput) { op := &request.Operation{ - Name: opListGroups, + Name: opDescribeTemplateAlias, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups", + HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/aliases/{AliasName}", } if input == nil { - input = &ListGroupsInput{} + input = &DescribeTemplateAliasInput{} } - output = &ListGroupsOutput{} + output = &DescribeTemplateAliasOutput{} req = c.newRequest(op, input, output) return } -// ListGroups API operation for Amazon QuickSight. +// DescribeTemplateAlias API operation for Amazon QuickSight. // -// Lists all user groups in Amazon QuickSight. +// Describes the template alias for a template. // // Returns awserr.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 QuickSight's -// API operation ListGroups for usage and error information. +// API operation DescribeTemplateAlias for usage and error information. // // Returned Error Types: -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. -// -// * InvalidParameterValueException -// One or more parameters has a value that isn't valid. -// -// * ResourceNotFoundException -// One or more resources can't be found. -// // * ThrottlingException // Access is throttled. // -// * InvalidNextTokenException -// The NextToken value isn't valid. +// * ResourceNotFoundException +// One or more resources can't be found. // -// * PreconditionNotMetException -// One or more preconditions aren't met. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// * ResourceUnavailableException -// This resource is currently unavailable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListGroups -func (c *QuickSight) ListGroups(input *ListGroupsInput) (*ListGroupsOutput, error) { - req, out := c.ListGroupsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplateAlias +func (c *QuickSight) DescribeTemplateAlias(input *DescribeTemplateAliasInput) (*DescribeTemplateAliasOutput, error) { + req, out := c.DescribeTemplateAliasRequest(input) return out, req.Send() } -// ListGroupsWithContext is the same as ListGroups with the addition of +// DescribeTemplateAliasWithContext is the same as DescribeTemplateAlias 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. +// See DescribeTemplateAlias for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListGroupsWithContext(ctx aws.Context, input *ListGroupsInput, opts ...request.Option) (*ListGroupsOutput, error) { - req, out := c.ListGroupsRequest(input) +func (c *QuickSight) DescribeTemplateAliasWithContext(ctx aws.Context, input *DescribeTemplateAliasInput, opts ...request.Option) (*DescribeTemplateAliasOutput, error) { + req, out := c.DescribeTemplateAliasRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opListIAMPolicyAssignments = "ListIAMPolicyAssignments" +const opDescribeTemplatePermissions = "DescribeTemplatePermissions" -// ListIAMPolicyAssignmentsRequest generates a "aws/request.Request" representing the -// client's request for the ListIAMPolicyAssignments operation. The "output" return +// DescribeTemplatePermissionsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeTemplatePermissions operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListIAMPolicyAssignments for more information on using the ListIAMPolicyAssignments +// See DescribeTemplatePermissions for more information on using the DescribeTemplatePermissions // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListIAMPolicyAssignmentsRequest method. -// req, resp := client.ListIAMPolicyAssignmentsRequest(params) +// // Example sending a request using the DescribeTemplatePermissionsRequest method. +// req, resp := client.DescribeTemplatePermissionsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIAMPolicyAssignments -func (c *QuickSight) ListIAMPolicyAssignmentsRequest(input *ListIAMPolicyAssignmentsInput) (req *request.Request, output *ListIAMPolicyAssignmentsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplatePermissions +func (c *QuickSight) DescribeTemplatePermissionsRequest(input *DescribeTemplatePermissionsInput) (req *request.Request, output *DescribeTemplatePermissionsOutput) { op := &request.Operation{ - Name: opListIAMPolicyAssignments, + Name: opDescribeTemplatePermissions, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/iam-policy-assignments", + HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/permissions", } if input == nil { - input = &ListIAMPolicyAssignmentsInput{} + input = &DescribeTemplatePermissionsInput{} } - output = &ListIAMPolicyAssignmentsOutput{} + output = &DescribeTemplatePermissionsOutput{} req = c.newRequest(op, input, output) return } -// ListIAMPolicyAssignments API operation for Amazon QuickSight. +// DescribeTemplatePermissions API operation for Amazon QuickSight. // -// Lists IAM policy assignments in the current Amazon QuickSight account. +// Describes read and write permissions on a template. // // Returns awserr.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 QuickSight's -// API operation ListIAMPolicyAssignments for usage and error information. +// API operation DescribeTemplatePermissions for usage and error information. // // Returned Error Types: -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. +// * ThrottlingException +// Access is throttled. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// // * ResourceNotFoundException // One or more resources can't be found. // -// * ThrottlingException -// Access is throttled. -// -// * InvalidNextTokenException -// The NextToken value isn't valid. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIAMPolicyAssignments -func (c *QuickSight) ListIAMPolicyAssignments(input *ListIAMPolicyAssignmentsInput) (*ListIAMPolicyAssignmentsOutput, error) { - req, out := c.ListIAMPolicyAssignmentsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTemplatePermissions +func (c *QuickSight) DescribeTemplatePermissions(input *DescribeTemplatePermissionsInput) (*DescribeTemplatePermissionsOutput, error) { + req, out := c.DescribeTemplatePermissionsRequest(input) return out, req.Send() } -// ListIAMPolicyAssignmentsWithContext is the same as ListIAMPolicyAssignments with the addition of +// DescribeTemplatePermissionsWithContext is the same as DescribeTemplatePermissions with the addition of // the ability to pass a context and additional request options. // -// See ListIAMPolicyAssignments for details on how to use this API operation. +// See DescribeTemplatePermissions for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListIAMPolicyAssignmentsWithContext(ctx aws.Context, input *ListIAMPolicyAssignmentsInput, opts ...request.Option) (*ListIAMPolicyAssignmentsOutput, error) { - req, out := c.ListIAMPolicyAssignmentsRequest(input) +func (c *QuickSight) DescribeTemplatePermissionsWithContext(ctx aws.Context, input *DescribeTemplatePermissionsInput, opts ...request.Option) (*DescribeTemplatePermissionsOutput, error) { + req, out := c.DescribeTemplatePermissionsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opListIAMPolicyAssignmentsForUser = "ListIAMPolicyAssignmentsForUser" +const opDescribeTheme = "DescribeTheme" -// ListIAMPolicyAssignmentsForUserRequest generates a "aws/request.Request" representing the -// client's request for the ListIAMPolicyAssignmentsForUser operation. The "output" return +// DescribeThemeRequest generates a "aws/request.Request" representing the +// client's request for the DescribeTheme operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListIAMPolicyAssignmentsForUser for more information on using the ListIAMPolicyAssignmentsForUser +// See DescribeTheme for more information on using the DescribeTheme // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListIAMPolicyAssignmentsForUserRequest method. -// req, resp := client.ListIAMPolicyAssignmentsForUserRequest(params) +// // Example sending a request using the DescribeThemeRequest method. +// req, resp := client.DescribeThemeRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIAMPolicyAssignmentsForUser -func (c *QuickSight) ListIAMPolicyAssignmentsForUserRequest(input *ListIAMPolicyAssignmentsForUserInput) (req *request.Request, output *ListIAMPolicyAssignmentsForUserOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTheme +func (c *QuickSight) DescribeThemeRequest(input *DescribeThemeInput) (req *request.Request, output *DescribeThemeOutput) { op := &request.Operation{ - Name: opListIAMPolicyAssignmentsForUser, + Name: opDescribeTheme, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users/{UserName}/iam-policy-assignments", + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}", } if input == nil { - input = &ListIAMPolicyAssignmentsForUserInput{} + input = &DescribeThemeInput{} } - output = &ListIAMPolicyAssignmentsForUserOutput{} + output = &DescribeThemeOutput{} req = c.newRequest(op, input, output) return } -// ListIAMPolicyAssignmentsForUser API operation for Amazon QuickSight. +// DescribeTheme API operation for Amazon QuickSight. // -// Lists all the IAM policy assignments, including the Amazon Resource Names -// (ARNs) for the IAM policies assigned to the specified user and group or groups -// that the user belongs to. +// Describes a theme. // // Returns awserr.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 QuickSight's -// API operation ListIAMPolicyAssignmentsForUser for usage and error information. +// API operation DescribeTheme for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -4446,101 +4449,93 @@ func (c *QuickSight) ListIAMPolicyAssignmentsForUserRequest(input *ListIAMPolicy // * ThrottlingException // Access is throttled. // -// * ConcurrentUpdatingException -// A resource is already in a state that indicates an action is happening that -// must complete before a new update can be applied. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIAMPolicyAssignmentsForUser -func (c *QuickSight) ListIAMPolicyAssignmentsForUser(input *ListIAMPolicyAssignmentsForUserInput) (*ListIAMPolicyAssignmentsForUserOutput, error) { - req, out := c.ListIAMPolicyAssignmentsForUserRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeTheme +func (c *QuickSight) DescribeTheme(input *DescribeThemeInput) (*DescribeThemeOutput, error) { + req, out := c.DescribeThemeRequest(input) return out, req.Send() } -// ListIAMPolicyAssignmentsForUserWithContext is the same as ListIAMPolicyAssignmentsForUser with the addition of +// DescribeThemeWithContext is the same as DescribeTheme with the addition of // the ability to pass a context and additional request options. // -// See ListIAMPolicyAssignmentsForUser for details on how to use this API operation. +// See DescribeTheme for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListIAMPolicyAssignmentsForUserWithContext(ctx aws.Context, input *ListIAMPolicyAssignmentsForUserInput, opts ...request.Option) (*ListIAMPolicyAssignmentsForUserOutput, error) { - req, out := c.ListIAMPolicyAssignmentsForUserRequest(input) +func (c *QuickSight) DescribeThemeWithContext(ctx aws.Context, input *DescribeThemeInput, opts ...request.Option) (*DescribeThemeOutput, error) { + req, out := c.DescribeThemeRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opListIngestions = "ListIngestions" +const opDescribeThemeAlias = "DescribeThemeAlias" -// ListIngestionsRequest generates a "aws/request.Request" representing the -// client's request for the ListIngestions operation. The "output" return +// DescribeThemeAliasRequest generates a "aws/request.Request" representing the +// client's request for the DescribeThemeAlias operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListIngestions for more information on using the ListIngestions +// See DescribeThemeAlias for more information on using the DescribeThemeAlias // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListIngestionsRequest method. -// req, resp := client.ListIngestionsRequest(params) +// // Example sending a request using the DescribeThemeAliasRequest method. +// req, resp := client.DescribeThemeAliasRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIngestions -func (c *QuickSight) ListIngestionsRequest(input *ListIngestionsInput) (req *request.Request, output *ListIngestionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeThemeAlias +func (c *QuickSight) DescribeThemeAliasRequest(input *DescribeThemeAliasInput) (req *request.Request, output *DescribeThemeAliasOutput) { op := &request.Operation{ - Name: opListIngestions, + Name: opDescribeThemeAlias, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}/ingestions", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, - OutputTokens: []string{"NextToken"}, - LimitToken: "MaxResults", - TruncationToken: "", - }, + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}/aliases/{AliasName}", } if input == nil { - input = &ListIngestionsInput{} + input = &DescribeThemeAliasInput{} } - output = &ListIngestionsOutput{} + output = &DescribeThemeAliasOutput{} req = c.newRequest(op, input, output) return } -// ListIngestions API operation for Amazon QuickSight. +// DescribeThemeAlias API operation for Amazon QuickSight. // -// Lists the history of SPICE ingestions for a dataset. +// Describes the alias for a theme. // // Returns awserr.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 QuickSight's -// API operation ListIngestions for usage and error information. +// API operation DescribeThemeAlias for usage and error information. // // Returned Error Types: -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. @@ -4551,141 +4546,89 @@ func (c *QuickSight) ListIngestionsRequest(input *ListIngestionsInput) (req *req // * ThrottlingException // Access is throttled. // -// * ResourceExistsException -// The resource specified already exists. -// -// * InvalidNextTokenException -// The NextToken value isn't valid. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIngestions -func (c *QuickSight) ListIngestions(input *ListIngestionsInput) (*ListIngestionsOutput, error) { - req, out := c.ListIngestionsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeThemeAlias +func (c *QuickSight) DescribeThemeAlias(input *DescribeThemeAliasInput) (*DescribeThemeAliasOutput, error) { + req, out := c.DescribeThemeAliasRequest(input) return out, req.Send() } -// ListIngestionsWithContext is the same as ListIngestions with the addition of +// DescribeThemeAliasWithContext is the same as DescribeThemeAlias with the addition of // the ability to pass a context and additional request options. // -// See ListIngestions for details on how to use this API operation. +// See DescribeThemeAlias for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListIngestionsWithContext(ctx aws.Context, input *ListIngestionsInput, opts ...request.Option) (*ListIngestionsOutput, error) { - req, out := c.ListIngestionsRequest(input) +func (c *QuickSight) DescribeThemeAliasWithContext(ctx aws.Context, input *DescribeThemeAliasInput, opts ...request.Option) (*DescribeThemeAliasOutput, error) { + req, out := c.DescribeThemeAliasRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListIngestionsPages iterates over the pages of a ListIngestions operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListIngestions 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 ListIngestions operation. -// pageNum := 0 -// err := client.ListIngestionsPages(params, -// func(page *quicksight.ListIngestionsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *QuickSight) ListIngestionsPages(input *ListIngestionsInput, fn func(*ListIngestionsOutput, bool) bool) error { - return c.ListIngestionsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListIngestionsPagesWithContext same as ListIngestionsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *QuickSight) ListIngestionsPagesWithContext(ctx aws.Context, input *ListIngestionsInput, fn func(*ListIngestionsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListIngestionsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListIngestionsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*ListIngestionsOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opListTagsForResource = "ListTagsForResource" +const opDescribeThemePermissions = "DescribeThemePermissions" -// ListTagsForResourceRequest generates a "aws/request.Request" representing the -// client's request for the ListTagsForResource operation. The "output" return +// DescribeThemePermissionsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeThemePermissions operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListTagsForResource for more information on using the ListTagsForResource +// See DescribeThemePermissions for more information on using the DescribeThemePermissions // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListTagsForResourceRequest method. -// req, resp := client.ListTagsForResourceRequest(params) +// // Example sending a request using the DescribeThemePermissionsRequest method. +// req, resp := client.DescribeThemePermissionsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTagsForResource -func (c *QuickSight) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeThemePermissions +func (c *QuickSight) DescribeThemePermissionsRequest(input *DescribeThemePermissionsInput) (req *request.Request, output *DescribeThemePermissionsOutput) { op := &request.Operation{ - Name: opListTagsForResource, + Name: opDescribeThemePermissions, HTTPMethod: "GET", - HTTPPath: "/resources/{ResourceArn}/tags", + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}/permissions", } if input == nil { - input = &ListTagsForResourceInput{} + input = &DescribeThemePermissionsInput{} } - output = &ListTagsForResourceOutput{} + output = &DescribeThemePermissionsOutput{} req = c.newRequest(op, input, output) return } -// ListTagsForResource API operation for Amazon QuickSight. +// DescribeThemePermissions API operation for Amazon QuickSight. // -// Lists the tags assigned to a resource. +// Describes the read and write permissions for a theme. // // Returns awserr.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 QuickSight's -// API operation ListTagsForResource for usage and error information. +// API operation DescribeThemePermissions for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -4704,252 +4647,246 @@ func (c *QuickSight) ListTagsForResourceRequest(input *ListTagsForResourceInput) // * ThrottlingException // Access is throttled. // +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTagsForResource -func (c *QuickSight) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { - req, out := c.ListTagsForResourceRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeThemePermissions +func (c *QuickSight) DescribeThemePermissions(input *DescribeThemePermissionsInput) (*DescribeThemePermissionsOutput, error) { + req, out := c.DescribeThemePermissionsRequest(input) return out, req.Send() } -// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of +// DescribeThemePermissionsWithContext is the same as DescribeThemePermissions 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. +// See DescribeThemePermissions for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { - req, out := c.ListTagsForResourceRequest(input) +func (c *QuickSight) DescribeThemePermissionsWithContext(ctx aws.Context, input *DescribeThemePermissionsInput, opts ...request.Option) (*DescribeThemePermissionsOutput, error) { + req, out := c.DescribeThemePermissionsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opListTemplateAliases = "ListTemplateAliases" +const opDescribeUser = "DescribeUser" -// ListTemplateAliasesRequest generates a "aws/request.Request" representing the -// client's request for the ListTemplateAliases operation. The "output" return +// DescribeUserRequest generates a "aws/request.Request" representing the +// client's request for the DescribeUser operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListTemplateAliases for more information on using the ListTemplateAliases +// See DescribeUser for more information on using the DescribeUser // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListTemplateAliasesRequest method. -// req, resp := client.ListTemplateAliasesRequest(params) +// // Example sending a request using the DescribeUserRequest method. +// req, resp := client.DescribeUserRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplateAliases -func (c *QuickSight) ListTemplateAliasesRequest(input *ListTemplateAliasesInput) (req *request.Request, output *ListTemplateAliasesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeUser +func (c *QuickSight) DescribeUserRequest(input *DescribeUserInput) (req *request.Request, output *DescribeUserOutput) { op := &request.Operation{ - Name: opListTemplateAliases, + Name: opDescribeUser, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/aliases", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, - OutputTokens: []string{"NextToken"}, - LimitToken: "MaxResults", - TruncationToken: "", - }, + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users/{UserName}", } if input == nil { - input = &ListTemplateAliasesInput{} + input = &DescribeUserInput{} } - output = &ListTemplateAliasesOutput{} + output = &DescribeUserOutput{} req = c.newRequest(op, input, output) return } -// ListTemplateAliases API operation for Amazon QuickSight. +// DescribeUser API operation for Amazon QuickSight. // -// Lists all the aliases of a template. +// Returns information about a user, given the user 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 QuickSight's -// API operation ListTemplateAliases for usage and error information. +// API operation DescribeUser for usage and error information. // // Returned Error Types: -// * ThrottlingException -// Access is throttled. +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. // // * ResourceNotFoundException // One or more resources can't be found. // -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. +// * ThrottlingException +// Access is throttled. +// +// * PreconditionNotMetException +// One or more preconditions aren't met. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplateAliases -func (c *QuickSight) ListTemplateAliases(input *ListTemplateAliasesInput) (*ListTemplateAliasesOutput, error) { - req, out := c.ListTemplateAliasesRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/DescribeUser +func (c *QuickSight) DescribeUser(input *DescribeUserInput) (*DescribeUserOutput, error) { + req, out := c.DescribeUserRequest(input) return out, req.Send() } -// ListTemplateAliasesWithContext is the same as ListTemplateAliases with the addition of +// DescribeUserWithContext is the same as DescribeUser with the addition of // the ability to pass a context and additional request options. // -// See ListTemplateAliases for details on how to use this API operation. +// See DescribeUser for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListTemplateAliasesWithContext(ctx aws.Context, input *ListTemplateAliasesInput, opts ...request.Option) (*ListTemplateAliasesOutput, error) { - req, out := c.ListTemplateAliasesRequest(input) +func (c *QuickSight) DescribeUserWithContext(ctx aws.Context, input *DescribeUserInput, opts ...request.Option) (*DescribeUserOutput, error) { + req, out := c.DescribeUserRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListTemplateAliasesPages iterates over the pages of a ListTemplateAliases operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListTemplateAliases 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 ListTemplateAliases operation. -// pageNum := 0 -// err := client.ListTemplateAliasesPages(params, -// func(page *quicksight.ListTemplateAliasesOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *QuickSight) ListTemplateAliasesPages(input *ListTemplateAliasesInput, fn func(*ListTemplateAliasesOutput, bool) bool) error { - return c.ListTemplateAliasesPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListTemplateAliasesPagesWithContext same as ListTemplateAliasesPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *QuickSight) ListTemplateAliasesPagesWithContext(ctx aws.Context, input *ListTemplateAliasesInput, fn func(*ListTemplateAliasesOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListTemplateAliasesInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListTemplateAliasesRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*ListTemplateAliasesOutput), !p.HasNextPage()) { - break - } - } - - return p.Err() -} - -const opListTemplateVersions = "ListTemplateVersions" +const opGetDashboardEmbedUrl = "GetDashboardEmbedUrl" -// ListTemplateVersionsRequest generates a "aws/request.Request" representing the -// client's request for the ListTemplateVersions operation. The "output" return +// GetDashboardEmbedUrlRequest generates a "aws/request.Request" representing the +// client's request for the GetDashboardEmbedUrl operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListTemplateVersions for more information on using the ListTemplateVersions +// See GetDashboardEmbedUrl for more information on using the GetDashboardEmbedUrl // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListTemplateVersionsRequest method. -// req, resp := client.ListTemplateVersionsRequest(params) +// // Example sending a request using the GetDashboardEmbedUrlRequest method. +// req, resp := client.GetDashboardEmbedUrlRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplateVersions -func (c *QuickSight) ListTemplateVersionsRequest(input *ListTemplateVersionsInput) (req *request.Request, output *ListTemplateVersionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/GetDashboardEmbedUrl +func (c *QuickSight) GetDashboardEmbedUrlRequest(input *GetDashboardEmbedUrlInput) (req *request.Request, output *GetDashboardEmbedUrlOutput) { op := &request.Operation{ - Name: opListTemplateVersions, + Name: opGetDashboardEmbedUrl, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/versions", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, - OutputTokens: []string{"NextToken"}, - LimitToken: "MaxResults", - TruncationToken: "", - }, + HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}/embed-url", } if input == nil { - input = &ListTemplateVersionsInput{} + input = &GetDashboardEmbedUrlInput{} } - output = &ListTemplateVersionsOutput{} + output = &GetDashboardEmbedUrlOutput{} req = c.newRequest(op, input, output) return } -// ListTemplateVersions API operation for Amazon QuickSight. +// GetDashboardEmbedUrl API operation for Amazon QuickSight. // -// Lists all the versions of the templates in the current Amazon QuickSight -// account. +// Generates a URL and authorization code that you can embed in your web server +// code. Before you use this command, make sure that you have configured the +// dashboards and permissions. +// +// Currently, you can use GetDashboardEmbedURL only from the server, not from +// the user's browser. The following rules apply to the combination of URL and +// authorization code: +// +// * They must be used together. +// +// * They can be used one time only. +// +// * They are valid for 5 minutes after you run this command. +// +// * The resulting user session is valid for 10 hours. +// +// For more information, see Embedding Amazon QuickSight Dashboards (https://docs.aws.amazon.com/quicksight/latest/user/embedding-dashboards.html) +// in the Amazon QuickSight User Guide or Embedding Amazon QuickSight Dashboards +// (https://docs.aws.amazon.com/quicksight/latest/APIReference/qs-dev-embedded-dashboards.html) +// in the Amazon QuickSight API Reference. // // Returns awserr.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 QuickSight's -// API operation ListTemplateVersions for usage and error information. +// API operation GetDashboardEmbedUrl for usage and error information. // // Returned Error Types: -// * ThrottlingException -// Access is throttled. +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ResourceExistsException +// The resource specified already exists. +// // * ResourceNotFoundException // One or more resources can't be found. // -// * InvalidNextTokenException -// The NextToken value isn't valid. +// * ThrottlingException +// Access is throttled. +// +// * DomainNotWhitelistedException +// The domain specified isn't on the allow list. All domains for embedded dashboards +// must be added to the approved list by an Amazon QuickSight admin. +// +// * UserNotFoundException +// The user with the provided name isn't found. This error can happen in any +// operation that requires finding a user based on a provided user name, such +// as DeleteUser, DescribeUser, and so on. +// +// * IdentityTypeNotSupportedException +// The identity type specified isn't supported. Supported identity types include +// IAM and QUICKSIGHT. +// +// * SessionLifetimeInMinutesInvalidException +// The number of minutes specified for the lifetime of a session isn't valid. +// The session lifetime must be 15-600 minutes. // // * UnsupportedUserEditionException // This error indicates that you are calling an operation on an Amazon QuickSight @@ -4960,113 +4897,175 @@ func (c *QuickSight) ListTemplateVersionsRequest(input *ListTemplateVersionsInpu // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplateVersions -func (c *QuickSight) ListTemplateVersions(input *ListTemplateVersionsInput) (*ListTemplateVersionsOutput, error) { - req, out := c.ListTemplateVersionsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/GetDashboardEmbedUrl +func (c *QuickSight) GetDashboardEmbedUrl(input *GetDashboardEmbedUrlInput) (*GetDashboardEmbedUrlOutput, error) { + req, out := c.GetDashboardEmbedUrlRequest(input) return out, req.Send() } -// ListTemplateVersionsWithContext is the same as ListTemplateVersions with the addition of +// GetDashboardEmbedUrlWithContext is the same as GetDashboardEmbedUrl with the addition of // the ability to pass a context and additional request options. // -// See ListTemplateVersions for details on how to use this API operation. +// See GetDashboardEmbedUrl for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListTemplateVersionsWithContext(ctx aws.Context, input *ListTemplateVersionsInput, opts ...request.Option) (*ListTemplateVersionsOutput, error) { - req, out := c.ListTemplateVersionsRequest(input) +func (c *QuickSight) GetDashboardEmbedUrlWithContext(ctx aws.Context, input *GetDashboardEmbedUrlInput, opts ...request.Option) (*GetDashboardEmbedUrlOutput, error) { + req, out := c.GetDashboardEmbedUrlRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListTemplateVersionsPages iterates over the pages of a ListTemplateVersions operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListTemplateVersions 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 ListTemplateVersions operation. -// pageNum := 0 -// err := client.ListTemplateVersionsPages(params, -// func(page *quicksight.ListTemplateVersionsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *QuickSight) ListTemplateVersionsPages(input *ListTemplateVersionsInput, fn func(*ListTemplateVersionsOutput, bool) bool) error { - return c.ListTemplateVersionsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListTemplateVersionsPagesWithContext same as ListTemplateVersionsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *QuickSight) ListTemplateVersionsPagesWithContext(ctx aws.Context, input *ListTemplateVersionsInput, fn func(*ListTemplateVersionsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListTemplateVersionsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListTemplateVersionsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - for p.Next() { - if !fn(p.Page().(*ListTemplateVersionsOutput), !p.HasNextPage()) { - break - } - } +const opGetSessionEmbedUrl = "GetSessionEmbedUrl" - return p.Err() -} - -const opListTemplates = "ListTemplates" - -// ListTemplatesRequest generates a "aws/request.Request" representing the -// client's request for the ListTemplates operation. The "output" return +// GetSessionEmbedUrlRequest generates a "aws/request.Request" representing the +// client's request for the GetSessionEmbedUrl operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListTemplates for more information on using the ListTemplates +// See GetSessionEmbedUrl for more information on using the GetSessionEmbedUrl // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListTemplatesRequest method. -// req, resp := client.ListTemplatesRequest(params) +// // Example sending a request using the GetSessionEmbedUrlRequest method. +// req, resp := client.GetSessionEmbedUrlRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplates -func (c *QuickSight) ListTemplatesRequest(input *ListTemplatesInput) (req *request.Request, output *ListTemplatesOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/GetSessionEmbedUrl +func (c *QuickSight) GetSessionEmbedUrlRequest(input *GetSessionEmbedUrlInput) (req *request.Request, output *GetSessionEmbedUrlOutput) { op := &request.Operation{ - Name: opListTemplates, + Name: opGetSessionEmbedUrl, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/templates", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, + HTTPPath: "/accounts/{AwsAccountId}/session-embed-url", + } + + if input == nil { + input = &GetSessionEmbedUrlInput{} + } + + output = &GetSessionEmbedUrlOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetSessionEmbedUrl API operation for Amazon QuickSight. +// +// Generates a session URL and authorization code that you can embed in your +// web server 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 +// the error. +// +// See the AWS API reference guide for Amazon QuickSight's +// API operation GetSessionEmbedUrl for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceExistsException +// The resource specified already exists. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * UserNotFoundException +// The user with the provided name isn't found. This error can happen in any +// operation that requires finding a user based on a provided user name, such +// as DeleteUser, DescribeUser, and so on. +// +// * SessionLifetimeInMinutesInvalidException +// The number of minutes specified for the lifetime of a session isn't valid. +// The session lifetime must be 15-600 minutes. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/GetSessionEmbedUrl +func (c *QuickSight) GetSessionEmbedUrl(input *GetSessionEmbedUrlInput) (*GetSessionEmbedUrlOutput, error) { + req, out := c.GetSessionEmbedUrlRequest(input) + return out, req.Send() +} + +// GetSessionEmbedUrlWithContext is the same as GetSessionEmbedUrl with the addition of +// the ability to pass a context and additional request options. +// +// See GetSessionEmbedUrl for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) GetSessionEmbedUrlWithContext(ctx aws.Context, input *GetSessionEmbedUrlInput, opts ...request.Option) (*GetSessionEmbedUrlOutput, error) { + req, out := c.GetSessionEmbedUrlRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListDashboardVersions = "ListDashboardVersions" + +// ListDashboardVersionsRequest generates a "aws/request.Request" representing the +// client's request for the ListDashboardVersions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListDashboardVersions for more information on using the ListDashboardVersions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListDashboardVersionsRequest method. +// req, resp := client.ListDashboardVersionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDashboardVersions +func (c *QuickSight) ListDashboardVersionsRequest(input *ListDashboardVersionsInput) (req *request.Request, output *ListDashboardVersionsOutput) { + op := &request.Operation{ + Name: opListDashboardVersions, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}/versions", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, OutputTokens: []string{"NextToken"}, LimitToken: "MaxResults", TruncationToken: "", @@ -5074,35 +5073,35 @@ func (c *QuickSight) ListTemplatesRequest(input *ListTemplatesInput) (req *reque } if input == nil { - input = &ListTemplatesInput{} + input = &ListDashboardVersionsInput{} } - output = &ListTemplatesOutput{} + output = &ListDashboardVersionsOutput{} req = c.newRequest(op, input, output) return } -// ListTemplates API operation for Amazon QuickSight. +// ListDashboardVersions API operation for Amazon QuickSight. // -// Lists all the templates in the current Amazon QuickSight account. +// Lists all the versions of the dashboards in the QuickSight subscription. // // Returns awserr.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 QuickSight's -// API operation ListTemplates for usage and error information. +// API operation ListDashboardVersions for usage and error information. // // Returned Error Types: -// * ThrottlingException -// Access is throttled. -// // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // // * ResourceNotFoundException // One or more resources can't be found. // +// * ThrottlingException +// Access is throttled. +// // * InvalidNextTokenException // The NextToken value isn't valid. // @@ -5115,65 +5114,65 @@ func (c *QuickSight) ListTemplatesRequest(input *ListTemplatesInput) (req *reque // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplates -func (c *QuickSight) ListTemplates(input *ListTemplatesInput) (*ListTemplatesOutput, error) { - req, out := c.ListTemplatesRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDashboardVersions +func (c *QuickSight) ListDashboardVersions(input *ListDashboardVersionsInput) (*ListDashboardVersionsOutput, error) { + req, out := c.ListDashboardVersionsRequest(input) return out, req.Send() } -// ListTemplatesWithContext is the same as ListTemplates with the addition of +// ListDashboardVersionsWithContext is the same as ListDashboardVersions with the addition of // the ability to pass a context and additional request options. // -// See ListTemplates for details on how to use this API operation. +// See ListDashboardVersions for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListTemplatesWithContext(ctx aws.Context, input *ListTemplatesInput, opts ...request.Option) (*ListTemplatesOutput, error) { - req, out := c.ListTemplatesRequest(input) +func (c *QuickSight) ListDashboardVersionsWithContext(ctx aws.Context, input *ListDashboardVersionsInput, opts ...request.Option) (*ListDashboardVersionsOutput, error) { + req, out := c.ListDashboardVersionsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// ListTemplatesPages iterates over the pages of a ListTemplates operation, +// ListDashboardVersionsPages iterates over the pages of a ListDashboardVersions operation, // calling the "fn" function with the response data for each page. To stop // iterating, return false from the fn function. // -// See ListTemplates method for more information on how to use this operation. +// See ListDashboardVersions 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 ListTemplates operation. +// // Example iterating over at most 3 pages of a ListDashboardVersions operation. // pageNum := 0 -// err := client.ListTemplatesPages(params, -// func(page *quicksight.ListTemplatesOutput, lastPage bool) bool { +// err := client.ListDashboardVersionsPages(params, +// func(page *quicksight.ListDashboardVersionsOutput, lastPage bool) bool { // pageNum++ // fmt.Println(page) // return pageNum <= 3 // }) // -func (c *QuickSight) ListTemplatesPages(input *ListTemplatesInput, fn func(*ListTemplatesOutput, bool) bool) error { - return c.ListTemplatesPagesWithContext(aws.BackgroundContext(), input, fn) +func (c *QuickSight) ListDashboardVersionsPages(input *ListDashboardVersionsInput, fn func(*ListDashboardVersionsOutput, bool) bool) error { + return c.ListDashboardVersionsPagesWithContext(aws.BackgroundContext(), input, fn) } -// ListTemplatesPagesWithContext same as ListTemplatesPages except +// ListDashboardVersionsPagesWithContext same as ListDashboardVersionsPages except // it takes a Context and allows setting request options on the pages. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListTemplatesPagesWithContext(ctx aws.Context, input *ListTemplatesInput, fn func(*ListTemplatesOutput, bool) bool, opts ...request.Option) error { +func (c *QuickSight) ListDashboardVersionsPagesWithContext(ctx aws.Context, input *ListDashboardVersionsInput, fn func(*ListDashboardVersionsOutput, bool) bool, opts ...request.Option) error { p := request.Pagination{ NewRequest: func() (*request.Request, error) { - var inCpy *ListTemplatesInput + var inCpy *ListDashboardVersionsInput if input != nil { tmp := *input inCpy = &tmp } - req, _ := c.ListTemplatesRequest(inCpy) + req, _ := c.ListDashboardVersionsRequest(inCpy) req.SetContext(ctx) req.ApplyOptions(opts...) return req, nil @@ -5181,7 +5180,7 @@ func (c *QuickSight) ListTemplatesPagesWithContext(ctx aws.Context, input *ListT } for p.Next() { - if !fn(p.Page().(*ListTemplatesOutput), !p.HasNextPage()) { + if !fn(p.Page().(*ListDashboardVersionsOutput), !p.HasNextPage()) { break } } @@ -5189,157 +5188,216 @@ func (c *QuickSight) ListTemplatesPagesWithContext(ctx aws.Context, input *ListT return p.Err() } -const opListUserGroups = "ListUserGroups" +const opListDashboards = "ListDashboards" -// ListUserGroupsRequest generates a "aws/request.Request" representing the -// client's request for the ListUserGroups operation. The "output" return +// ListDashboardsRequest generates a "aws/request.Request" representing the +// client's request for the ListDashboards operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See ListUserGroups for more information on using the ListUserGroups +// See ListDashboards for more information on using the ListDashboards // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the ListUserGroupsRequest method. -// req, resp := client.ListUserGroupsRequest(params) +// // Example sending a request using the ListDashboardsRequest method. +// req, resp := client.ListDashboardsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListUserGroups -func (c *QuickSight) ListUserGroupsRequest(input *ListUserGroupsInput) (req *request.Request, output *ListUserGroupsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDashboards +func (c *QuickSight) ListDashboardsRequest(input *ListDashboardsInput) (req *request.Request, output *ListDashboardsOutput) { op := &request.Operation{ - Name: opListUserGroups, + Name: opListDashboards, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users/{UserName}/groups", + HTTPPath: "/accounts/{AwsAccountId}/dashboards", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { - input = &ListUserGroupsInput{} + input = &ListDashboardsInput{} } - output = &ListUserGroupsOutput{} + output = &ListDashboardsOutput{} req = c.newRequest(op, input, output) return } -// ListUserGroups API operation for Amazon QuickSight. +// ListDashboards API operation for Amazon QuickSight. // -// Lists the Amazon QuickSight groups that an Amazon QuickSight user is a member -// of. +// Lists dashboards in an 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. // // See the AWS API reference guide for Amazon QuickSight's -// API operation ListUserGroups for usage and error information. +// API operation ListDashboards for usage and error information. // // Returned Error Types: -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. -// -// * InvalidParameterValueException -// One or more parameters has a value that isn't valid. -// -// * ResourceNotFoundException -// One or more resources can't be found. -// // * ThrottlingException // Access is throttled. // +// * InvalidNextTokenException +// The NextToken value isn't valid. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// // * InternalFailureException // An internal failure occurred. // -// * ResourceUnavailableException -// This resource is currently unavailable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListUserGroups -func (c *QuickSight) ListUserGroups(input *ListUserGroupsInput) (*ListUserGroupsOutput, error) { - req, out := c.ListUserGroupsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDashboards +func (c *QuickSight) ListDashboards(input *ListDashboardsInput) (*ListDashboardsOutput, error) { + req, out := c.ListDashboardsRequest(input) return out, req.Send() } -// ListUserGroupsWithContext is the same as ListUserGroups with the addition of +// ListDashboardsWithContext is the same as ListDashboards with the addition of // the ability to pass a context and additional request options. // -// See ListUserGroups for details on how to use this API operation. +// See ListDashboards for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListUserGroupsWithContext(ctx aws.Context, input *ListUserGroupsInput, opts ...request.Option) (*ListUserGroupsOutput, error) { - req, out := c.ListUserGroupsRequest(input) +func (c *QuickSight) ListDashboardsWithContext(ctx aws.Context, input *ListDashboardsInput, opts ...request.Option) (*ListDashboardsOutput, error) { + req, out := c.ListDashboardsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opListUsers = "ListUsers" - -// ListUsersRequest generates a "aws/request.Request" representing the -// client's request for the ListUsers operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListUsers for more information on using the ListUsers -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// ListDashboardsPages iterates over the pages of a ListDashboards operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. // +// See ListDashboards method for more information on how to use this operation. // -// // Example sending a request using the ListUsersRequest method. -// req, resp := client.ListUsersRequest(params) +// Note: This operation can generate multiple requests to a service. // -// err := req.Send() +// // Example iterating over at most 3 pages of a ListDashboards operation. +// pageNum := 0 +// err := client.ListDashboardsPages(params, +// func(page *quicksight.ListDashboardsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *QuickSight) ListDashboardsPages(input *ListDashboardsInput, fn func(*ListDashboardsOutput, bool) bool) error { + return c.ListDashboardsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDashboardsPagesWithContext same as ListDashboardsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) ListDashboardsPagesWithContext(ctx aws.Context, input *ListDashboardsInput, fn func(*ListDashboardsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDashboardsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDashboardsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListDashboardsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListDataSets = "ListDataSets" + +// ListDataSetsRequest generates a "aws/request.Request" representing the +// client's request for the ListDataSets operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListDataSets for more information on using the ListDataSets +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListDataSetsRequest method. +// req, resp := client.ListDataSetsRequest(params) +// +// err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListUsers -func (c *QuickSight) ListUsersRequest(input *ListUsersInput) (req *request.Request, output *ListUsersOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDataSets +func (c *QuickSight) ListDataSetsRequest(input *ListDataSetsInput) (req *request.Request, output *ListDataSetsOutput) { op := &request.Operation{ - Name: opListUsers, + Name: opListDataSets, HTTPMethod: "GET", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users", + HTTPPath: "/accounts/{AwsAccountId}/data-sets", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { - input = &ListUsersInput{} + input = &ListDataSetsInput{} } - output = &ListUsersOutput{} + output = &ListDataSetsOutput{} req = c.newRequest(op, input, output) return } -// ListUsers API operation for Amazon QuickSight. +// ListDataSets API operation for Amazon QuickSight. // -// Returns a list of all of the Amazon QuickSight users belonging to this account. +// Lists all of the datasets belonging to the current AWS account in an AWS +// Region. +// +// The permissions resource is arn:aws:quicksight:region:aws-account-id:dataset/*. // // Returns awserr.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 QuickSight's -// API operation ListUsers for usage and error information. +// API operation ListDataSets for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -5352,9 +5410,6 @@ func (c *QuickSight) ListUsersRequest(input *ListUsersInput) (req *request.Reque // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ResourceNotFoundException -// One or more resources can't be found. -// // * ThrottlingException // Access is throttled. // @@ -5364,85 +5419,138 @@ func (c *QuickSight) ListUsersRequest(input *ListUsersInput) (req *request.Reque // * InternalFailureException // An internal failure occurred. // -// * ResourceUnavailableException -// This resource is currently unavailable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListUsers -func (c *QuickSight) ListUsers(input *ListUsersInput) (*ListUsersOutput, error) { - req, out := c.ListUsersRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDataSets +func (c *QuickSight) ListDataSets(input *ListDataSetsInput) (*ListDataSetsOutput, error) { + req, out := c.ListDataSetsRequest(input) return out, req.Send() } -// ListUsersWithContext is the same as ListUsers with the addition of +// ListDataSetsWithContext is the same as ListDataSets 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. +// See ListDataSets for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) ListUsersWithContext(ctx aws.Context, input *ListUsersInput, opts ...request.Option) (*ListUsersOutput, error) { - req, out := c.ListUsersRequest(input) +func (c *QuickSight) ListDataSetsWithContext(ctx aws.Context, input *ListDataSetsInput, opts ...request.Option) (*ListDataSetsOutput, error) { + req, out := c.ListDataSetsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opRegisterUser = "RegisterUser" +// ListDataSetsPages iterates over the pages of a ListDataSets operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListDataSets 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 ListDataSets operation. +// pageNum := 0 +// err := client.ListDataSetsPages(params, +// func(page *quicksight.ListDataSetsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *QuickSight) ListDataSetsPages(input *ListDataSetsInput, fn func(*ListDataSetsOutput, bool) bool) error { + return c.ListDataSetsPagesWithContext(aws.BackgroundContext(), input, fn) +} -// RegisterUserRequest generates a "aws/request.Request" representing the -// client's request for the RegisterUser operation. The "output" return +// ListDataSetsPagesWithContext same as ListDataSetsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) ListDataSetsPagesWithContext(ctx aws.Context, input *ListDataSetsInput, fn func(*ListDataSetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDataSetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDataSetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListDataSetsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListDataSources = "ListDataSources" + +// ListDataSourcesRequest generates a "aws/request.Request" representing the +// client's request for the ListDataSources operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See RegisterUser for more information on using the RegisterUser +// See ListDataSources for more information on using the ListDataSources // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the RegisterUserRequest method. -// req, resp := client.RegisterUserRequest(params) +// // Example sending a request using the ListDataSourcesRequest method. +// req, resp := client.ListDataSourcesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/RegisterUser -func (c *QuickSight) RegisterUserRequest(input *RegisterUserInput) (req *request.Request, output *RegisterUserOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDataSources +func (c *QuickSight) ListDataSourcesRequest(input *ListDataSourcesInput) (req *request.Request, output *ListDataSourcesOutput) { op := &request.Operation{ - Name: opRegisterUser, - HTTPMethod: "POST", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users", + Name: opListDataSources, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/data-sources", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { - input = &RegisterUserInput{} + input = &ListDataSourcesInput{} } - output = &RegisterUserOutput{} + output = &ListDataSourcesOutput{} req = c.newRequest(op, input, output) return } -// RegisterUser API operation for Amazon QuickSight. +// ListDataSources API operation for Amazon QuickSight. // -// Creates an Amazon QuickSight user, whose identity is associated with the -// AWS Identity and Access Management (IAM) identity or role specified in the -// request. +// Lists data sources in current AWS Region that belong to this 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. // // See the AWS API reference guide for Amazon QuickSight's -// API operation RegisterUser for usage and error information. +// API operation ListDataSources for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -5455,189 +5563,74 @@ func (c *QuickSight) RegisterUserRequest(input *RegisterUserInput) (req *request // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ResourceNotFoundException -// One or more resources can't be found. -// // * ThrottlingException // Access is throttled. // -// * LimitExceededException -// A limit is exceeded. -// -// * ResourceExistsException -// The resource specified already exists. -// -// * PreconditionNotMetException -// One or more preconditions aren't met. +// * InvalidNextTokenException +// The NextToken value isn't valid. // // * InternalFailureException // An internal failure occurred. // -// * ResourceUnavailableException -// This resource is currently unavailable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/RegisterUser -func (c *QuickSight) RegisterUser(input *RegisterUserInput) (*RegisterUserOutput, error) { - req, out := c.RegisterUserRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListDataSources +func (c *QuickSight) ListDataSources(input *ListDataSourcesInput) (*ListDataSourcesOutput, error) { + req, out := c.ListDataSourcesRequest(input) return out, req.Send() } -// RegisterUserWithContext is the same as RegisterUser with the addition of +// ListDataSourcesWithContext is the same as ListDataSources with the addition of // the ability to pass a context and additional request options. // -// See RegisterUser for details on how to use this API operation. +// See ListDataSources for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) RegisterUserWithContext(ctx aws.Context, input *RegisterUserInput, opts ...request.Option) (*RegisterUserOutput, error) { - req, out := c.RegisterUserRequest(input) +func (c *QuickSight) ListDataSourcesWithContext(ctx aws.Context, input *ListDataSourcesInput, opts ...request.Option) (*ListDataSourcesOutput, error) { + req, out := c.ListDataSourcesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opSearchDashboards = "SearchDashboards" - -// SearchDashboardsRequest generates a "aws/request.Request" representing the -// client's request for the SearchDashboards operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See SearchDashboards for more information on using the SearchDashboards -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// ListDataSourcesPages iterates over the pages of a ListDataSources operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. // +// See ListDataSources method for more information on how to use this operation. // -// // Example sending a request using the SearchDashboardsRequest method. -// req, resp := client.SearchDashboardsRequest(params) +// Note: This operation can generate multiple requests to a service. // -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/SearchDashboards -func (c *QuickSight) SearchDashboardsRequest(input *SearchDashboardsInput) (req *request.Request, output *SearchDashboardsOutput) { - op := &request.Operation{ - Name: opSearchDashboards, - HTTPMethod: "POST", - HTTPPath: "/accounts/{AwsAccountId}/search/dashboards", - Paginator: &request.Paginator{ - InputTokens: []string{"NextToken"}, - OutputTokens: []string{"NextToken"}, - LimitToken: "MaxResults", - TruncationToken: "", - }, - } - - if input == nil { - input = &SearchDashboardsInput{} - } - - output = &SearchDashboardsOutput{} - req = c.newRequest(op, input, output) - return -} - -// SearchDashboards API operation for Amazon QuickSight. -// -// Searchs for dashboards that belong to a user. -// -// Returns awserr.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 QuickSight's -// API operation SearchDashboards for usage and error information. -// -// Returned Error Types: -// * ThrottlingException -// Access is throttled. -// -// * ResourceNotFoundException -// One or more resources can't be found. -// -// * InvalidParameterValueException -// One or more parameters has a value that isn't valid. -// -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. -// -// * InvalidNextTokenException -// The NextToken value isn't valid. -// -// * InternalFailureException -// An internal failure occurred. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/SearchDashboards -func (c *QuickSight) SearchDashboards(input *SearchDashboardsInput) (*SearchDashboardsOutput, error) { - req, out := c.SearchDashboardsRequest(input) - return out, req.Send() -} - -// SearchDashboardsWithContext is the same as SearchDashboards with the addition of -// the ability to pass a context and additional request options. -// -// See SearchDashboards for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *QuickSight) SearchDashboardsWithContext(ctx aws.Context, input *SearchDashboardsInput, opts ...request.Option) (*SearchDashboardsOutput, error) { - req, out := c.SearchDashboardsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// SearchDashboardsPages iterates over the pages of a SearchDashboards operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See SearchDashboards 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 SearchDashboards operation. +// // Example iterating over at most 3 pages of a ListDataSources operation. // pageNum := 0 -// err := client.SearchDashboardsPages(params, -// func(page *quicksight.SearchDashboardsOutput, lastPage bool) bool { +// err := client.ListDataSourcesPages(params, +// func(page *quicksight.ListDataSourcesOutput, lastPage bool) bool { // pageNum++ // fmt.Println(page) // return pageNum <= 3 // }) // -func (c *QuickSight) SearchDashboardsPages(input *SearchDashboardsInput, fn func(*SearchDashboardsOutput, bool) bool) error { - return c.SearchDashboardsPagesWithContext(aws.BackgroundContext(), input, fn) +func (c *QuickSight) ListDataSourcesPages(input *ListDataSourcesInput, fn func(*ListDataSourcesOutput, bool) bool) error { + return c.ListDataSourcesPagesWithContext(aws.BackgroundContext(), input, fn) } -// SearchDashboardsPagesWithContext same as SearchDashboardsPages except +// ListDataSourcesPagesWithContext same as ListDataSourcesPages except // it takes a Context and allows setting request options on the pages. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) SearchDashboardsPagesWithContext(ctx aws.Context, input *SearchDashboardsInput, fn func(*SearchDashboardsOutput, bool) bool, opts ...request.Option) error { +func (c *QuickSight) ListDataSourcesPagesWithContext(ctx aws.Context, input *ListDataSourcesInput, fn func(*ListDataSourcesOutput, bool) bool, opts ...request.Option) error { p := request.Pagination{ NewRequest: func() (*request.Request, error) { - var inCpy *SearchDashboardsInput + var inCpy *ListDataSourcesInput if input != nil { tmp := *input inCpy = &tmp } - req, _ := c.SearchDashboardsRequest(inCpy) + req, _ := c.ListDataSourcesRequest(inCpy) req.SetContext(ctx) req.ApplyOptions(opts...) return req, nil @@ -5645,7 +5638,7 @@ func (c *QuickSight) SearchDashboardsPagesWithContext(ctx aws.Context, input *Se } for p.Next() { - if !fn(p.Page().(*SearchDashboardsOutput), !p.HasNextPage()) { + if !fn(p.Page().(*ListDataSourcesOutput), !p.HasNextPage()) { break } } @@ -5653,85 +5646,60 @@ func (c *QuickSight) SearchDashboardsPagesWithContext(ctx aws.Context, input *Se return p.Err() } -const opTagResource = "TagResource" +const opListGroupMemberships = "ListGroupMemberships" -// TagResourceRequest generates a "aws/request.Request" representing the -// client's request for the TagResource operation. The "output" return +// ListGroupMembershipsRequest generates a "aws/request.Request" representing the +// client's request for the ListGroupMemberships operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See TagResource for more information on using the TagResource +// See ListGroupMemberships for more information on using the ListGroupMemberships // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the TagResourceRequest method. -// req, resp := client.TagResourceRequest(params) +// // Example sending a request using the ListGroupMembershipsRequest method. +// req, resp := client.ListGroupMembershipsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/TagResource -func (c *QuickSight) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListGroupMemberships +func (c *QuickSight) ListGroupMembershipsRequest(input *ListGroupMembershipsInput) (req *request.Request, output *ListGroupMembershipsOutput) { op := &request.Operation{ - Name: opTagResource, - HTTPMethod: "POST", - HTTPPath: "/resources/{ResourceArn}/tags", + Name: opListGroupMemberships, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups/{GroupName}/members", } if input == nil { - input = &TagResourceInput{} + input = &ListGroupMembershipsInput{} } - output = &TagResourceOutput{} + output = &ListGroupMembershipsOutput{} req = c.newRequest(op, input, output) return } -// TagResource API operation for Amazon QuickSight. -// -// Assigns one or more tags (key-value pairs) to the specified QuickSight resource. -// -// Tags can help you organize and categorize your resources. You can also use -// them to scope user permissions, by granting a user permission to access or -// change only resources with certain tag values. You can use the TagResource -// operation with a resource that already has tags. If you specify a new tag -// key for the resource, this tag is appended to the list of tags associated -// with the resource. If you specify a tag key that is already associated with -// the resource, the new tag value that you specify replaces the previous value -// for that tag. -// -// You can associate as many as 50 tags with a resource. QuickSight supports -// tagging on data set, data source, dashboard, and template. -// -// Tagging for QuickSight works in a similar way to tagging for other AWS services, -// except for the following: -// -// * You can't use tags to track AWS costs for QuickSight. This restriction -// is because QuickSight costs are based on users and SPICE capacity, which -// aren't taggable resources. +// ListGroupMemberships API operation for Amazon QuickSight. // -// * QuickSight doesn't currently support the Tag Editor for AWS Resource -// Groups. +// Lists member users in a group. // // Returns awserr.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 QuickSight's -// API operation TagResource for usage and error information. +// API operation ListGroupMemberships for usage and error information. // // Returned Error Types: -// * LimitExceededException -// A limit is exceeded. -// // * AccessDeniedException // You don't have access to this item. The provided credentials couldn't be // validated. You might not be authorized to carry out the request. Make sure @@ -5748,83 +5716,92 @@ func (c *QuickSight) TagResourceRequest(input *TagResourceInput) (req *request.R // * ThrottlingException // Access is throttled. // +// * InvalidNextTokenException +// The NextToken value isn't valid. +// +// * PreconditionNotMetException +// One or more preconditions aren't met. +// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/TagResource -func (c *QuickSight) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { - req, out := c.TagResourceRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListGroupMemberships +func (c *QuickSight) ListGroupMemberships(input *ListGroupMembershipsInput) (*ListGroupMembershipsOutput, error) { + req, out := c.ListGroupMembershipsRequest(input) return out, req.Send() } -// TagResourceWithContext is the same as TagResource with the addition of +// ListGroupMembershipsWithContext is the same as ListGroupMemberships 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. +// See ListGroupMemberships for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) TagResourceWithContext(ctx aws.Context, input *TagResourceInput, opts ...request.Option) (*TagResourceOutput, error) { - req, out := c.TagResourceRequest(input) +func (c *QuickSight) ListGroupMembershipsWithContext(ctx aws.Context, input *ListGroupMembershipsInput, opts ...request.Option) (*ListGroupMembershipsOutput, error) { + req, out := c.ListGroupMembershipsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUntagResource = "UntagResource" +const opListGroups = "ListGroups" -// UntagResourceRequest generates a "aws/request.Request" representing the -// client's request for the UntagResource operation. The "output" return +// ListGroupsRequest generates a "aws/request.Request" representing the +// client's request for the ListGroups operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UntagResource for more information on using the UntagResource +// See ListGroups for more information on using the ListGroups // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UntagResourceRequest method. -// req, resp := client.UntagResourceRequest(params) +// // Example sending a request using the ListGroupsRequest method. +// req, resp := client.ListGroupsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UntagResource -func (c *QuickSight) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListGroups +func (c *QuickSight) ListGroupsRequest(input *ListGroupsInput) (req *request.Request, output *ListGroupsOutput) { op := &request.Operation{ - Name: opUntagResource, - HTTPMethod: "DELETE", - HTTPPath: "/resources/{ResourceArn}/tags", + Name: opListGroups, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups", } if input == nil { - input = &UntagResourceInput{} + input = &ListGroupsInput{} } - output = &UntagResourceOutput{} + output = &ListGroupsOutput{} req = c.newRequest(op, input, output) return } -// UntagResource API operation for Amazon QuickSight. +// ListGroups API operation for Amazon QuickSight. // -// Removes a tag or tags from a resource. +// Lists all user groups in Amazon QuickSight. // // Returns awserr.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 QuickSight's -// API operation UntagResource for usage and error information. +// API operation ListGroups for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -5843,87 +5820,100 @@ func (c *QuickSight) UntagResourceRequest(input *UntagResourceInput) (req *reque // * ThrottlingException // Access is throttled. // +// * InvalidNextTokenException +// The NextToken value isn't valid. +// +// * PreconditionNotMetException +// One or more preconditions aren't met. +// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UntagResource -func (c *QuickSight) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { - req, out := c.UntagResourceRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListGroups +func (c *QuickSight) ListGroups(input *ListGroupsInput) (*ListGroupsOutput, error) { + req, out := c.ListGroupsRequest(input) return out, req.Send() } -// UntagResourceWithContext is the same as UntagResource with the addition of +// ListGroupsWithContext is the same as ListGroups 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. +// 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 *QuickSight) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) { - req, out := c.UntagResourceRequest(input) +func (c *QuickSight) 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() } -const opUpdateDashboard = "UpdateDashboard" +const opListIAMPolicyAssignments = "ListIAMPolicyAssignments" -// UpdateDashboardRequest generates a "aws/request.Request" representing the -// client's request for the UpdateDashboard operation. The "output" return +// ListIAMPolicyAssignmentsRequest generates a "aws/request.Request" representing the +// client's request for the ListIAMPolicyAssignments operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateDashboard for more information on using the UpdateDashboard +// See ListIAMPolicyAssignments for more information on using the ListIAMPolicyAssignments // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateDashboardRequest method. -// req, resp := client.UpdateDashboardRequest(params) +// // Example sending a request using the ListIAMPolicyAssignmentsRequest method. +// req, resp := client.ListIAMPolicyAssignmentsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboard -func (c *QuickSight) UpdateDashboardRequest(input *UpdateDashboardInput) (req *request.Request, output *UpdateDashboardOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIAMPolicyAssignments +func (c *QuickSight) ListIAMPolicyAssignmentsRequest(input *ListIAMPolicyAssignmentsInput) (req *request.Request, output *ListIAMPolicyAssignmentsOutput) { op := &request.Operation{ - Name: opUpdateDashboard, - HTTPMethod: "PUT", - HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}", + Name: opListIAMPolicyAssignments, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/iam-policy-assignments", } if input == nil { - input = &UpdateDashboardInput{} + input = &ListIAMPolicyAssignmentsInput{} } - output = &UpdateDashboardOutput{} + output = &ListIAMPolicyAssignmentsOutput{} req = c.newRequest(op, input, output) return } -// UpdateDashboard API operation for Amazon QuickSight. +// ListIAMPolicyAssignments API operation for Amazon QuickSight. // -// Updates a dashboard in an AWS account. +// Lists IAM policy assignments in the current Amazon QuickSight 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 Amazon QuickSight's -// API operation UpdateDashboard for usage and error information. +// API operation ListIAMPolicyAssignments for usage and error information. // // Returned Error Types: -// * ThrottlingException -// Access is throttled. +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. @@ -5931,398 +5921,358 @@ func (c *QuickSight) UpdateDashboardRequest(input *UpdateDashboardInput) (req *r // * ResourceNotFoundException // One or more resources can't be found. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. -// -// * LimitExceededException -// A limit is exceeded. +// * ThrottlingException +// Access is throttled. // -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. +// * InvalidNextTokenException +// The NextToken value isn't valid. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboard -func (c *QuickSight) UpdateDashboard(input *UpdateDashboardInput) (*UpdateDashboardOutput, error) { - req, out := c.UpdateDashboardRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIAMPolicyAssignments +func (c *QuickSight) ListIAMPolicyAssignments(input *ListIAMPolicyAssignmentsInput) (*ListIAMPolicyAssignmentsOutput, error) { + req, out := c.ListIAMPolicyAssignmentsRequest(input) return out, req.Send() } -// UpdateDashboardWithContext is the same as UpdateDashboard with the addition of +// ListIAMPolicyAssignmentsWithContext is the same as ListIAMPolicyAssignments with the addition of // the ability to pass a context and additional request options. // -// See UpdateDashboard for details on how to use this API operation. +// See ListIAMPolicyAssignments for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateDashboardWithContext(ctx aws.Context, input *UpdateDashboardInput, opts ...request.Option) (*UpdateDashboardOutput, error) { - req, out := c.UpdateDashboardRequest(input) +func (c *QuickSight) ListIAMPolicyAssignmentsWithContext(ctx aws.Context, input *ListIAMPolicyAssignmentsInput, opts ...request.Option) (*ListIAMPolicyAssignmentsOutput, error) { + req, out := c.ListIAMPolicyAssignmentsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateDashboardPermissions = "UpdateDashboardPermissions" +const opListIAMPolicyAssignmentsForUser = "ListIAMPolicyAssignmentsForUser" -// UpdateDashboardPermissionsRequest generates a "aws/request.Request" representing the -// client's request for the UpdateDashboardPermissions operation. The "output" return +// ListIAMPolicyAssignmentsForUserRequest generates a "aws/request.Request" representing the +// client's request for the ListIAMPolicyAssignmentsForUser operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateDashboardPermissions for more information on using the UpdateDashboardPermissions +// See ListIAMPolicyAssignmentsForUser for more information on using the ListIAMPolicyAssignmentsForUser // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateDashboardPermissionsRequest method. -// req, resp := client.UpdateDashboardPermissionsRequest(params) +// // Example sending a request using the ListIAMPolicyAssignmentsForUserRequest method. +// req, resp := client.ListIAMPolicyAssignmentsForUserRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboardPermissions -func (c *QuickSight) UpdateDashboardPermissionsRequest(input *UpdateDashboardPermissionsInput) (req *request.Request, output *UpdateDashboardPermissionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIAMPolicyAssignmentsForUser +func (c *QuickSight) ListIAMPolicyAssignmentsForUserRequest(input *ListIAMPolicyAssignmentsForUserInput) (req *request.Request, output *ListIAMPolicyAssignmentsForUserOutput) { op := &request.Operation{ - Name: opUpdateDashboardPermissions, - HTTPMethod: "PUT", - HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}/permissions", + Name: opListIAMPolicyAssignmentsForUser, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users/{UserName}/iam-policy-assignments", } if input == nil { - input = &UpdateDashboardPermissionsInput{} + input = &ListIAMPolicyAssignmentsForUserInput{} } - output = &UpdateDashboardPermissionsOutput{} + output = &ListIAMPolicyAssignmentsForUserOutput{} req = c.newRequest(op, input, output) return } -// UpdateDashboardPermissions API operation for Amazon QuickSight. +// ListIAMPolicyAssignmentsForUser API operation for Amazon QuickSight. // -// Updates read and write permissions on a dashboard. +// Lists all the IAM policy assignments, including the Amazon Resource Names +// (ARNs) for the IAM policies assigned to the specified user and group or groups +// that the user belongs to. // // Returns awserr.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 QuickSight's -// API operation UpdateDashboardPermissions for usage and error information. +// API operation ListIAMPolicyAssignmentsForUser for usage and error information. // // Returned Error Types: -// * ThrottlingException -// Access is throttled. +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ResourceExistsException +// The resource specified already exists. +// // * ResourceNotFoundException // One or more resources can't be found. // -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. +// * ThrottlingException +// Access is throttled. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. +// * ConcurrentUpdatingException +// A resource is already in a state that indicates an action is happening that +// must complete before a new update can be applied. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboardPermissions -func (c *QuickSight) UpdateDashboardPermissions(input *UpdateDashboardPermissionsInput) (*UpdateDashboardPermissionsOutput, error) { - req, out := c.UpdateDashboardPermissionsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIAMPolicyAssignmentsForUser +func (c *QuickSight) ListIAMPolicyAssignmentsForUser(input *ListIAMPolicyAssignmentsForUserInput) (*ListIAMPolicyAssignmentsForUserOutput, error) { + req, out := c.ListIAMPolicyAssignmentsForUserRequest(input) return out, req.Send() } -// UpdateDashboardPermissionsWithContext is the same as UpdateDashboardPermissions with the addition of +// ListIAMPolicyAssignmentsForUserWithContext is the same as ListIAMPolicyAssignmentsForUser with the addition of // the ability to pass a context and additional request options. // -// See UpdateDashboardPermissions for details on how to use this API operation. +// See ListIAMPolicyAssignmentsForUser for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateDashboardPermissionsWithContext(ctx aws.Context, input *UpdateDashboardPermissionsInput, opts ...request.Option) (*UpdateDashboardPermissionsOutput, error) { - req, out := c.UpdateDashboardPermissionsRequest(input) +func (c *QuickSight) ListIAMPolicyAssignmentsForUserWithContext(ctx aws.Context, input *ListIAMPolicyAssignmentsForUserInput, opts ...request.Option) (*ListIAMPolicyAssignmentsForUserOutput, error) { + req, out := c.ListIAMPolicyAssignmentsForUserRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateDashboardPublishedVersion = "UpdateDashboardPublishedVersion" +const opListIngestions = "ListIngestions" -// UpdateDashboardPublishedVersionRequest generates a "aws/request.Request" representing the -// client's request for the UpdateDashboardPublishedVersion operation. The "output" return +// ListIngestionsRequest generates a "aws/request.Request" representing the +// client's request for the ListIngestions operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateDashboardPublishedVersion for more information on using the UpdateDashboardPublishedVersion +// See ListIngestions for more information on using the ListIngestions // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateDashboardPublishedVersionRequest method. -// req, resp := client.UpdateDashboardPublishedVersionRequest(params) +// // Example sending a request using the ListIngestionsRequest method. +// req, resp := client.ListIngestionsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboardPublishedVersion -func (c *QuickSight) UpdateDashboardPublishedVersionRequest(input *UpdateDashboardPublishedVersionInput) (req *request.Request, output *UpdateDashboardPublishedVersionOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIngestions +func (c *QuickSight) ListIngestionsRequest(input *ListIngestionsInput) (req *request.Request, output *ListIngestionsOutput) { op := &request.Operation{ - Name: opUpdateDashboardPublishedVersion, - HTTPMethod: "PUT", - HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}/versions/{VersionNumber}", + Name: opListIngestions, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}/ingestions", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { - input = &UpdateDashboardPublishedVersionInput{} + input = &ListIngestionsInput{} } - output = &UpdateDashboardPublishedVersionOutput{} + output = &ListIngestionsOutput{} req = c.newRequest(op, input, output) return } -// UpdateDashboardPublishedVersion API operation for Amazon QuickSight. +// ListIngestions API operation for Amazon QuickSight. // -// Updates the published version of a dashboard. +// Lists the history of SPICE ingestions for a dataset. // // Returns awserr.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 QuickSight's -// API operation UpdateDashboardPublishedVersion for usage and error information. +// API operation ListIngestions for usage and error information. // // Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // +// * ResourceNotFoundException +// One or more resources can't be found. +// // * ThrottlingException // Access is throttled. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. -// -// * ResourceNotFoundException -// One or more resources can't be found. +// * ResourceExistsException +// The resource specified already exists. // -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. +// * InvalidNextTokenException +// The NextToken value isn't valid. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboardPublishedVersion -func (c *QuickSight) UpdateDashboardPublishedVersion(input *UpdateDashboardPublishedVersionInput) (*UpdateDashboardPublishedVersionOutput, error) { - req, out := c.UpdateDashboardPublishedVersionRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListIngestions +func (c *QuickSight) ListIngestions(input *ListIngestionsInput) (*ListIngestionsOutput, error) { + req, out := c.ListIngestionsRequest(input) return out, req.Send() } -// UpdateDashboardPublishedVersionWithContext is the same as UpdateDashboardPublishedVersion with the addition of +// ListIngestionsWithContext is the same as ListIngestions with the addition of // the ability to pass a context and additional request options. // -// See UpdateDashboardPublishedVersion for details on how to use this API operation. +// See ListIngestions for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateDashboardPublishedVersionWithContext(ctx aws.Context, input *UpdateDashboardPublishedVersionInput, opts ...request.Option) (*UpdateDashboardPublishedVersionOutput, error) { - req, out := c.UpdateDashboardPublishedVersionRequest(input) +func (c *QuickSight) ListIngestionsWithContext(ctx aws.Context, input *ListIngestionsInput, opts ...request.Option) (*ListIngestionsOutput, error) { + req, out := c.ListIngestionsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateDataSet = "UpdateDataSet" - -// UpdateDataSetRequest generates a "aws/request.Request" representing the -// client's request for the UpdateDataSet operation. The "output" return -// value will be populated with the request's response once the request completes -// successfully. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateDataSet for more information on using the UpdateDataSet -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// ListIngestionsPages iterates over the pages of a ListIngestions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. // +// See ListIngestions method for more information on how to use this operation. // -// // Example sending a request using the UpdateDataSetRequest method. -// req, resp := client.UpdateDataSetRequest(params) +// Note: This operation can generate multiple requests to a service. // -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } +// // Example iterating over at most 3 pages of a ListIngestions operation. +// pageNum := 0 +// err := client.ListIngestionsPages(params, +// func(page *quicksight.ListIngestionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSet -func (c *QuickSight) UpdateDataSetRequest(input *UpdateDataSetInput) (req *request.Request, output *UpdateDataSetOutput) { - op := &request.Operation{ - Name: opUpdateDataSet, - HTTPMethod: "PUT", - HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}", - } - - if input == nil { - input = &UpdateDataSetInput{} - } - - output = &UpdateDataSetOutput{} - req = c.newRequest(op, input, output) - return +func (c *QuickSight) ListIngestionsPages(input *ListIngestionsInput, fn func(*ListIngestionsOutput, bool) bool) error { + return c.ListIngestionsPagesWithContext(aws.BackgroundContext(), input, fn) } -// UpdateDataSet API operation for Amazon QuickSight. -// -// Updates a dataset. -// -// Returns awserr.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 QuickSight's -// API operation UpdateDataSet for usage and error information. -// -// Returned Error Types: -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. -// -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. -// -// * InvalidParameterValueException -// One or more parameters has a value that isn't valid. -// -// * LimitExceededException -// A limit is exceeded. -// -// * ThrottlingException -// Access is throttled. -// -// * ResourceNotFoundException -// One or more resources can't be found. -// -// * UnsupportedUserEditionException -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. -// -// * InternalFailureException -// An internal failure occurred. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSet -func (c *QuickSight) UpdateDataSet(input *UpdateDataSetInput) (*UpdateDataSetOutput, error) { - req, out := c.UpdateDataSetRequest(input) - return out, req.Send() -} - -// UpdateDataSetWithContext is the same as UpdateDataSet with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateDataSet for details on how to use this API operation. +// ListIngestionsPagesWithContext same as ListIngestionsPages except +// it takes a Context and allows setting request options on the pages. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateDataSetWithContext(ctx aws.Context, input *UpdateDataSetInput, opts ...request.Option) (*UpdateDataSetOutput, error) { - req, out := c.UpdateDataSetRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() +func (c *QuickSight) ListIngestionsPagesWithContext(ctx aws.Context, input *ListIngestionsInput, fn func(*ListIngestionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListIngestionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListIngestionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListIngestionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() } -const opUpdateDataSetPermissions = "UpdateDataSetPermissions" +const opListNamespaces = "ListNamespaces" -// UpdateDataSetPermissionsRequest generates a "aws/request.Request" representing the -// client's request for the UpdateDataSetPermissions operation. The "output" return +// ListNamespacesRequest generates a "aws/request.Request" representing the +// client's request for the ListNamespaces operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateDataSetPermissions for more information on using the UpdateDataSetPermissions +// See ListNamespaces for more information on using the ListNamespaces // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateDataSetPermissionsRequest method. -// req, resp := client.UpdateDataSetPermissionsRequest(params) +// // Example sending a request using the ListNamespacesRequest method. +// req, resp := client.ListNamespacesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSetPermissions -func (c *QuickSight) UpdateDataSetPermissionsRequest(input *UpdateDataSetPermissionsInput) (req *request.Request, output *UpdateDataSetPermissionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListNamespaces +func (c *QuickSight) ListNamespacesRequest(input *ListNamespacesInput) (req *request.Request, output *ListNamespacesOutput) { op := &request.Operation{ - Name: opUpdateDataSetPermissions, - HTTPMethod: "POST", - HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}/permissions", + Name: opListNamespaces, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/namespaces", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { - input = &UpdateDataSetPermissionsInput{} + input = &ListNamespacesInput{} } - output = &UpdateDataSetPermissionsOutput{} + output = &ListNamespacesOutput{} req = c.newRequest(op, input, output) return } -// UpdateDataSetPermissions API operation for Amazon QuickSight. -// -// Updates the permissions on a dataset. +// ListNamespaces API operation for Amazon QuickSight. // -// The permissions resource is arn:aws:quicksight:region:aws-account-id:dataset/data-set-id. +// Lists the namespaces for the specified 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. // // See the AWS API reference guide for Amazon QuickSight's -// API operation UpdateDataSetPermissions for usage and error information. +// API operation ListNamespaces for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -6332,9 +6282,6 @@ func (c *QuickSight) UpdateDataSetPermissionsRequest(input *UpdateDataSetPermiss // your policies have the correct permissions, and that you are using the correct // access keys. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. -// // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // @@ -6344,83 +6291,144 @@ func (c *QuickSight) UpdateDataSetPermissionsRequest(input *UpdateDataSetPermiss // * ThrottlingException // Access is throttled. // +// * InvalidNextTokenException +// The NextToken value isn't valid. +// +// * PreconditionNotMetException +// One or more preconditions aren't met. +// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSetPermissions -func (c *QuickSight) UpdateDataSetPermissions(input *UpdateDataSetPermissionsInput) (*UpdateDataSetPermissionsOutput, error) { - req, out := c.UpdateDataSetPermissionsRequest(input) +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListNamespaces +func (c *QuickSight) ListNamespaces(input *ListNamespacesInput) (*ListNamespacesOutput, error) { + req, out := c.ListNamespacesRequest(input) return out, req.Send() } -// UpdateDataSetPermissionsWithContext is the same as UpdateDataSetPermissions with the addition of +// ListNamespacesWithContext is the same as ListNamespaces with the addition of // the ability to pass a context and additional request options. // -// See UpdateDataSetPermissions for details on how to use this API operation. +// See ListNamespaces for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateDataSetPermissionsWithContext(ctx aws.Context, input *UpdateDataSetPermissionsInput, opts ...request.Option) (*UpdateDataSetPermissionsOutput, error) { - req, out := c.UpdateDataSetPermissionsRequest(input) +func (c *QuickSight) ListNamespacesWithContext(ctx aws.Context, input *ListNamespacesInput, opts ...request.Option) (*ListNamespacesOutput, error) { + req, out := c.ListNamespacesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateDataSource = "UpdateDataSource" +// ListNamespacesPages iterates over the pages of a ListNamespaces operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListNamespaces 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 ListNamespaces operation. +// pageNum := 0 +// err := client.ListNamespacesPages(params, +// func(page *quicksight.ListNamespacesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *QuickSight) ListNamespacesPages(input *ListNamespacesInput, fn func(*ListNamespacesOutput, bool) bool) error { + return c.ListNamespacesPagesWithContext(aws.BackgroundContext(), input, fn) +} -// UpdateDataSourceRequest generates a "aws/request.Request" representing the -// client's request for the UpdateDataSource operation. The "output" return +// ListNamespacesPagesWithContext same as ListNamespacesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) ListNamespacesPagesWithContext(ctx aws.Context, input *ListNamespacesInput, fn func(*ListNamespacesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListNamespacesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListNamespacesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListNamespacesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListTagsForResource = "ListTagsForResource" + +// ListTagsForResourceRequest generates a "aws/request.Request" representing the +// client's request for the ListTagsForResource operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateDataSource for more information on using the UpdateDataSource +// See ListTagsForResource for more information on using the ListTagsForResource // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateDataSourceRequest method. -// req, resp := client.UpdateDataSourceRequest(params) +// // Example sending a request using the ListTagsForResourceRequest method. +// req, resp := client.ListTagsForResourceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSource -func (c *QuickSight) UpdateDataSourceRequest(input *UpdateDataSourceInput) (req *request.Request, output *UpdateDataSourceOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTagsForResource +func (c *QuickSight) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { op := &request.Operation{ - Name: opUpdateDataSource, - HTTPMethod: "PUT", - HTTPPath: "/accounts/{AwsAccountId}/data-sources/{DataSourceId}", + Name: opListTagsForResource, + HTTPMethod: "GET", + HTTPPath: "/resources/{ResourceArn}/tags", } if input == nil { - input = &UpdateDataSourceInput{} + input = &ListTagsForResourceInput{} } - output = &UpdateDataSourceOutput{} + output = &ListTagsForResourceOutput{} req = c.newRequest(op, input, output) return } -// UpdateDataSource API operation for Amazon QuickSight. +// ListTagsForResource API operation for Amazon QuickSight. // -// Updates a data source. +// Lists the tags assigned to 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 Amazon QuickSight's -// API operation UpdateDataSource for usage and error information. +// API operation ListTagsForResource for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -6430,201 +6438,255 @@ func (c *QuickSight) UpdateDataSourceRequest(input *UpdateDataSourceInput) (req // your policies have the correct permissions, and that you are using the correct // access keys. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. -// // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ThrottlingException -// Access is throttled. -// // * ResourceNotFoundException // One or more resources can't be found. // +// * ThrottlingException +// Access is throttled. +// // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSource -func (c *QuickSight) UpdateDataSource(input *UpdateDataSourceInput) (*UpdateDataSourceOutput, error) { - req, out := c.UpdateDataSourceRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTagsForResource +func (c *QuickSight) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) return out, req.Send() } -// UpdateDataSourceWithContext is the same as UpdateDataSource with the addition of +// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of // the ability to pass a context and additional request options. // -// See UpdateDataSource for details on how to use this API operation. +// 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 *QuickSight) UpdateDataSourceWithContext(ctx aws.Context, input *UpdateDataSourceInput, opts ...request.Option) (*UpdateDataSourceOutput, error) { - req, out := c.UpdateDataSourceRequest(input) +func (c *QuickSight) 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 opUpdateDataSourcePermissions = "UpdateDataSourcePermissions" +const opListTemplateAliases = "ListTemplateAliases" -// UpdateDataSourcePermissionsRequest generates a "aws/request.Request" representing the -// client's request for the UpdateDataSourcePermissions operation. The "output" return +// ListTemplateAliasesRequest generates a "aws/request.Request" representing the +// client's request for the ListTemplateAliases operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateDataSourcePermissions for more information on using the UpdateDataSourcePermissions +// See ListTemplateAliases for more information on using the ListTemplateAliases // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateDataSourcePermissionsRequest method. -// req, resp := client.UpdateDataSourcePermissionsRequest(params) +// // Example sending a request using the ListTemplateAliasesRequest method. +// req, resp := client.ListTemplateAliasesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSourcePermissions -func (c *QuickSight) UpdateDataSourcePermissionsRequest(input *UpdateDataSourcePermissionsInput) (req *request.Request, output *UpdateDataSourcePermissionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplateAliases +func (c *QuickSight) ListTemplateAliasesRequest(input *ListTemplateAliasesInput) (req *request.Request, output *ListTemplateAliasesOutput) { op := &request.Operation{ - Name: opUpdateDataSourcePermissions, - HTTPMethod: "POST", - HTTPPath: "/accounts/{AwsAccountId}/data-sources/{DataSourceId}/permissions", + Name: opListTemplateAliases, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/aliases", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { - input = &UpdateDataSourcePermissionsInput{} + input = &ListTemplateAliasesInput{} } - output = &UpdateDataSourcePermissionsOutput{} + output = &ListTemplateAliasesOutput{} req = c.newRequest(op, input, output) return } -// UpdateDataSourcePermissions API operation for Amazon QuickSight. +// ListTemplateAliases API operation for Amazon QuickSight. // -// Updates the permissions to a data source. +// Lists all the aliases of a template. // // Returns awserr.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 QuickSight's -// API operation UpdateDataSourcePermissions for usage and error information. +// API operation ListTemplateAliases for usage and error information. // // Returned Error Types: -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. -// -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. +// * InvalidNextTokenException +// The NextToken value isn't valid. // -// * InvalidParameterValueException -// One or more parameters has a value that isn't valid. +// * ThrottlingException +// Access is throttled. // // * ResourceNotFoundException // One or more resources can't be found. // -// * ThrottlingException -// Access is throttled. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSourcePermissions -func (c *QuickSight) UpdateDataSourcePermissions(input *UpdateDataSourcePermissionsInput) (*UpdateDataSourcePermissionsOutput, error) { - req, out := c.UpdateDataSourcePermissionsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplateAliases +func (c *QuickSight) ListTemplateAliases(input *ListTemplateAliasesInput) (*ListTemplateAliasesOutput, error) { + req, out := c.ListTemplateAliasesRequest(input) return out, req.Send() } -// UpdateDataSourcePermissionsWithContext is the same as UpdateDataSourcePermissions with the addition of +// ListTemplateAliasesWithContext is the same as ListTemplateAliases with the addition of // the ability to pass a context and additional request options. // -// See UpdateDataSourcePermissions for details on how to use this API operation. +// See ListTemplateAliases for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateDataSourcePermissionsWithContext(ctx aws.Context, input *UpdateDataSourcePermissionsInput, opts ...request.Option) (*UpdateDataSourcePermissionsOutput, error) { - req, out := c.UpdateDataSourcePermissionsRequest(input) +func (c *QuickSight) ListTemplateAliasesWithContext(ctx aws.Context, input *ListTemplateAliasesInput, opts ...request.Option) (*ListTemplateAliasesOutput, error) { + req, out := c.ListTemplateAliasesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateGroup = "UpdateGroup" +// ListTemplateAliasesPages iterates over the pages of a ListTemplateAliases operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListTemplateAliases 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 ListTemplateAliases operation. +// pageNum := 0 +// err := client.ListTemplateAliasesPages(params, +// func(page *quicksight.ListTemplateAliasesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *QuickSight) ListTemplateAliasesPages(input *ListTemplateAliasesInput, fn func(*ListTemplateAliasesOutput, bool) bool) error { + return c.ListTemplateAliasesPagesWithContext(aws.BackgroundContext(), input, fn) +} -// UpdateGroupRequest generates a "aws/request.Request" representing the -// client's request for the UpdateGroup operation. The "output" return +// ListTemplateAliasesPagesWithContext same as ListTemplateAliasesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) ListTemplateAliasesPagesWithContext(ctx aws.Context, input *ListTemplateAliasesInput, fn func(*ListTemplateAliasesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTemplateAliasesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTemplateAliasesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListTemplateAliasesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListTemplateVersions = "ListTemplateVersions" + +// ListTemplateVersionsRequest generates a "aws/request.Request" representing the +// client's request for the ListTemplateVersions operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateGroup for more information on using the UpdateGroup +// See ListTemplateVersions for more information on using the ListTemplateVersions // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateGroupRequest method. -// req, resp := client.UpdateGroupRequest(params) +// // Example sending a request using the ListTemplateVersionsRequest method. +// req, resp := client.ListTemplateVersionsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateGroup -func (c *QuickSight) UpdateGroupRequest(input *UpdateGroupInput) (req *request.Request, output *UpdateGroupOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplateVersions +func (c *QuickSight) ListTemplateVersionsRequest(input *ListTemplateVersionsInput) (req *request.Request, output *ListTemplateVersionsOutput) { op := &request.Operation{ - Name: opUpdateGroup, - HTTPMethod: "PUT", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups/{GroupName}", + Name: opListTemplateVersions, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/versions", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { - input = &UpdateGroupInput{} + input = &ListTemplateVersionsInput{} } - output = &UpdateGroupOutput{} + output = &ListTemplateVersionsOutput{} req = c.newRequest(op, input, output) return } -// UpdateGroup API operation for Amazon QuickSight. +// ListTemplateVersions API operation for Amazon QuickSight. // -// Changes a group description. +// Lists all the versions of the templates in the current Amazon QuickSight +// 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 Amazon QuickSight's -// API operation UpdateGroup for usage and error information. +// API operation ListTemplateVersions for usage and error information. // // Returned Error Types: -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. +// * ThrottlingException +// Access is throttled. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. @@ -6632,216 +6694,316 @@ func (c *QuickSight) UpdateGroupRequest(input *UpdateGroupInput) (req *request.R // * ResourceNotFoundException // One or more resources can't be found. // -// * ThrottlingException -// Access is throttled. +// * InvalidNextTokenException +// The NextToken value isn't valid. // -// * PreconditionNotMetException -// One or more preconditions aren't met. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// * ResourceUnavailableException -// This resource is currently unavailable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateGroup -func (c *QuickSight) UpdateGroup(input *UpdateGroupInput) (*UpdateGroupOutput, error) { - req, out := c.UpdateGroupRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplateVersions +func (c *QuickSight) ListTemplateVersions(input *ListTemplateVersionsInput) (*ListTemplateVersionsOutput, error) { + req, out := c.ListTemplateVersionsRequest(input) return out, req.Send() } -// UpdateGroupWithContext is the same as UpdateGroup with the addition of +// ListTemplateVersionsWithContext is the same as ListTemplateVersions 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. +// See ListTemplateVersions for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateGroupWithContext(ctx aws.Context, input *UpdateGroupInput, opts ...request.Option) (*UpdateGroupOutput, error) { - req, out := c.UpdateGroupRequest(input) +func (c *QuickSight) ListTemplateVersionsWithContext(ctx aws.Context, input *ListTemplateVersionsInput, opts ...request.Option) (*ListTemplateVersionsOutput, error) { + req, out := c.ListTemplateVersionsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateIAMPolicyAssignment = "UpdateIAMPolicyAssignment" +// ListTemplateVersionsPages iterates over the pages of a ListTemplateVersions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListTemplateVersions 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 ListTemplateVersions operation. +// pageNum := 0 +// err := client.ListTemplateVersionsPages(params, +// func(page *quicksight.ListTemplateVersionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *QuickSight) ListTemplateVersionsPages(input *ListTemplateVersionsInput, fn func(*ListTemplateVersionsOutput, bool) bool) error { + return c.ListTemplateVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} -// UpdateIAMPolicyAssignmentRequest generates a "aws/request.Request" representing the -// client's request for the UpdateIAMPolicyAssignment operation. The "output" return +// ListTemplateVersionsPagesWithContext same as ListTemplateVersionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) ListTemplateVersionsPagesWithContext(ctx aws.Context, input *ListTemplateVersionsInput, fn func(*ListTemplateVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTemplateVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTemplateVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListTemplateVersionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListTemplates = "ListTemplates" + +// ListTemplatesRequest generates a "aws/request.Request" representing the +// client's request for the ListTemplates operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateIAMPolicyAssignment for more information on using the UpdateIAMPolicyAssignment +// See ListTemplates for more information on using the ListTemplates // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateIAMPolicyAssignmentRequest method. -// req, resp := client.UpdateIAMPolicyAssignmentRequest(params) +// // Example sending a request using the ListTemplatesRequest method. +// req, resp := client.ListTemplatesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateIAMPolicyAssignment -func (c *QuickSight) UpdateIAMPolicyAssignmentRequest(input *UpdateIAMPolicyAssignmentInput) (req *request.Request, output *UpdateIAMPolicyAssignmentOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplates +func (c *QuickSight) ListTemplatesRequest(input *ListTemplatesInput) (req *request.Request, output *ListTemplatesOutput) { op := &request.Operation{ - Name: opUpdateIAMPolicyAssignment, - HTTPMethod: "PUT", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/iam-policy-assignments/{AssignmentName}", + Name: opListTemplates, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/templates", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { - input = &UpdateIAMPolicyAssignmentInput{} + input = &ListTemplatesInput{} } - output = &UpdateIAMPolicyAssignmentOutput{} + output = &ListTemplatesOutput{} req = c.newRequest(op, input, output) return } -// UpdateIAMPolicyAssignment API operation for Amazon QuickSight. +// ListTemplates API operation for Amazon QuickSight. // -// Updates an existing IAM policy assignment. This operation updates only the -// optional parameter or parameters that are specified in the request. +// Lists all the templates in the current Amazon QuickSight 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 Amazon QuickSight's -// API operation UpdateIAMPolicyAssignment for usage and error information. +// API operation ListTemplates for usage and error information. // // Returned Error Types: -// * AccessDeniedException -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. +// * ThrottlingException +// Access is throttled. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ResourceExistsException -// The resource specified already exists. -// // * ResourceNotFoundException // One or more resources can't be found. // -// * ThrottlingException -// Access is throttled. +// * InvalidNextTokenException +// The NextToken value isn't valid. // -// * ConcurrentUpdatingException -// A resource is already in a state that indicates an action is happening that -// must complete before a new update can be applied. +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. // // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateIAMPolicyAssignment -func (c *QuickSight) UpdateIAMPolicyAssignment(input *UpdateIAMPolicyAssignmentInput) (*UpdateIAMPolicyAssignmentOutput, error) { - req, out := c.UpdateIAMPolicyAssignmentRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListTemplates +func (c *QuickSight) ListTemplates(input *ListTemplatesInput) (*ListTemplatesOutput, error) { + req, out := c.ListTemplatesRequest(input) return out, req.Send() } -// UpdateIAMPolicyAssignmentWithContext is the same as UpdateIAMPolicyAssignment with the addition of +// ListTemplatesWithContext is the same as ListTemplates with the addition of // the ability to pass a context and additional request options. // -// See UpdateIAMPolicyAssignment for details on how to use this API operation. +// See ListTemplates for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateIAMPolicyAssignmentWithContext(ctx aws.Context, input *UpdateIAMPolicyAssignmentInput, opts ...request.Option) (*UpdateIAMPolicyAssignmentOutput, error) { - req, out := c.UpdateIAMPolicyAssignmentRequest(input) +func (c *QuickSight) ListTemplatesWithContext(ctx aws.Context, input *ListTemplatesInput, opts ...request.Option) (*ListTemplatesOutput, error) { + req, out := c.ListTemplatesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateTemplate = "UpdateTemplate" +// ListTemplatesPages iterates over the pages of a ListTemplates operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListTemplates 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 ListTemplates operation. +// pageNum := 0 +// err := client.ListTemplatesPages(params, +// func(page *quicksight.ListTemplatesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *QuickSight) ListTemplatesPages(input *ListTemplatesInput, fn func(*ListTemplatesOutput, bool) bool) error { + return c.ListTemplatesPagesWithContext(aws.BackgroundContext(), input, fn) +} -// UpdateTemplateRequest generates a "aws/request.Request" representing the -// client's request for the UpdateTemplate operation. The "output" return +// ListTemplatesPagesWithContext same as ListTemplatesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) ListTemplatesPagesWithContext(ctx aws.Context, input *ListTemplatesInput, fn func(*ListTemplatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTemplatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTemplatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListTemplatesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListThemeAliases = "ListThemeAliases" + +// ListThemeAliasesRequest generates a "aws/request.Request" representing the +// client's request for the ListThemeAliases operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateTemplate for more information on using the UpdateTemplate +// See ListThemeAliases for more information on using the ListThemeAliases // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateTemplateRequest method. -// req, resp := client.UpdateTemplateRequest(params) +// // Example sending a request using the ListThemeAliasesRequest method. +// req, resp := client.ListThemeAliasesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplate -func (c *QuickSight) UpdateTemplateRequest(input *UpdateTemplateInput) (req *request.Request, output *UpdateTemplateOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListThemeAliases +func (c *QuickSight) ListThemeAliasesRequest(input *ListThemeAliasesInput) (req *request.Request, output *ListThemeAliasesOutput) { op := &request.Operation{ - Name: opUpdateTemplate, - HTTPMethod: "PUT", - HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}", + Name: opListThemeAliases, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}/aliases", } if input == nil { - input = &UpdateTemplateInput{} + input = &ListThemeAliasesInput{} } - output = &UpdateTemplateOutput{} + output = &ListThemeAliasesOutput{} req = c.newRequest(op, input, output) return } -// UpdateTemplate API operation for Amazon QuickSight. +// ListThemeAliases API operation for Amazon QuickSight. // -// Updates a template from an existing Amazon QuickSight analysis or another -// template. +// Lists all the aliases of a theme. // // Returns awserr.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 QuickSight's -// API operation UpdateTemplate for usage and error information. +// API operation ListThemeAliases for usage and error information. // // Returned Error Types: +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * InvalidNextTokenException +// The NextToken value isn't valid. +// // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ResourceExistsException -// The resource specified already exists. -// // * ResourceNotFoundException // One or more resources can't be found. // // * ThrottlingException // Access is throttled. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. -// -// * LimitExceededException -// A limit is exceeded. -// // * UnsupportedUserEditionException // This error indicates that you are calling an operation on an Amazon QuickSight // subscription where the edition doesn't include support for that operation. @@ -6851,90 +7013,100 @@ func (c *QuickSight) UpdateTemplateRequest(input *UpdateTemplateInput) (req *req // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplate -func (c *QuickSight) UpdateTemplate(input *UpdateTemplateInput) (*UpdateTemplateOutput, error) { - req, out := c.UpdateTemplateRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListThemeAliases +func (c *QuickSight) ListThemeAliases(input *ListThemeAliasesInput) (*ListThemeAliasesOutput, error) { + req, out := c.ListThemeAliasesRequest(input) return out, req.Send() } -// UpdateTemplateWithContext is the same as UpdateTemplate with the addition of +// ListThemeAliasesWithContext is the same as ListThemeAliases with the addition of // the ability to pass a context and additional request options. // -// See UpdateTemplate for details on how to use this API operation. +// See ListThemeAliases for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateTemplateWithContext(ctx aws.Context, input *UpdateTemplateInput, opts ...request.Option) (*UpdateTemplateOutput, error) { - req, out := c.UpdateTemplateRequest(input) +func (c *QuickSight) ListThemeAliasesWithContext(ctx aws.Context, input *ListThemeAliasesInput, opts ...request.Option) (*ListThemeAliasesOutput, error) { + req, out := c.ListThemeAliasesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateTemplateAlias = "UpdateTemplateAlias" +const opListThemeVersions = "ListThemeVersions" -// UpdateTemplateAliasRequest generates a "aws/request.Request" representing the -// client's request for the UpdateTemplateAlias operation. The "output" return +// ListThemeVersionsRequest generates a "aws/request.Request" representing the +// client's request for the ListThemeVersions operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateTemplateAlias for more information on using the UpdateTemplateAlias +// See ListThemeVersions for more information on using the ListThemeVersions // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateTemplateAliasRequest method. -// req, resp := client.UpdateTemplateAliasRequest(params) +// // Example sending a request using the ListThemeVersionsRequest method. +// req, resp := client.ListThemeVersionsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplateAlias -func (c *QuickSight) UpdateTemplateAliasRequest(input *UpdateTemplateAliasInput) (req *request.Request, output *UpdateTemplateAliasOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListThemeVersions +func (c *QuickSight) ListThemeVersionsRequest(input *ListThemeVersionsInput) (req *request.Request, output *ListThemeVersionsOutput) { op := &request.Operation{ - Name: opUpdateTemplateAlias, - HTTPMethod: "PUT", - HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/aliases/{AliasName}", + Name: opListThemeVersions, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}/versions", } if input == nil { - input = &UpdateTemplateAliasInput{} + input = &ListThemeVersionsInput{} } - output = &UpdateTemplateAliasOutput{} + output = &ListThemeVersionsOutput{} req = c.newRequest(op, input, output) return } -// UpdateTemplateAlias API operation for Amazon QuickSight. +// ListThemeVersions API operation for Amazon QuickSight. // -// Updates the template alias of a template. +// Lists all the versions of the themes in 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. // // See the AWS API reference guide for Amazon QuickSight's -// API operation UpdateTemplateAlias for usage and error information. +// API operation ListThemeVersions for usage and error information. // // Returned Error Types: -// * ThrottlingException -// Access is throttled. +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidNextTokenException +// The NextToken value isn't valid. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. // // * ResourceNotFoundException // One or more resources can't be found. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. +// * ThrottlingException +// Access is throttled. // // * UnsupportedUserEditionException // This error indicates that you are calling an operation on an Amazon QuickSight @@ -6945,94 +7117,101 @@ func (c *QuickSight) UpdateTemplateAliasRequest(input *UpdateTemplateAliasInput) // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplateAlias -func (c *QuickSight) UpdateTemplateAlias(input *UpdateTemplateAliasInput) (*UpdateTemplateAliasOutput, error) { - req, out := c.UpdateTemplateAliasRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListThemeVersions +func (c *QuickSight) ListThemeVersions(input *ListThemeVersionsInput) (*ListThemeVersionsOutput, error) { + req, out := c.ListThemeVersionsRequest(input) return out, req.Send() } -// UpdateTemplateAliasWithContext is the same as UpdateTemplateAlias with the addition of +// ListThemeVersionsWithContext is the same as ListThemeVersions with the addition of // the ability to pass a context and additional request options. // -// See UpdateTemplateAlias for details on how to use this API operation. +// See ListThemeVersions for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateTemplateAliasWithContext(ctx aws.Context, input *UpdateTemplateAliasInput, opts ...request.Option) (*UpdateTemplateAliasOutput, error) { - req, out := c.UpdateTemplateAliasRequest(input) +func (c *QuickSight) ListThemeVersionsWithContext(ctx aws.Context, input *ListThemeVersionsInput, opts ...request.Option) (*ListThemeVersionsOutput, error) { + req, out := c.ListThemeVersionsRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateTemplatePermissions = "UpdateTemplatePermissions" +const opListThemes = "ListThemes" -// UpdateTemplatePermissionsRequest generates a "aws/request.Request" representing the -// client's request for the UpdateTemplatePermissions operation. The "output" return +// ListThemesRequest generates a "aws/request.Request" representing the +// client's request for the ListThemes operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateTemplatePermissions for more information on using the UpdateTemplatePermissions +// See ListThemes for more information on using the ListThemes // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateTemplatePermissionsRequest method. -// req, resp := client.UpdateTemplatePermissionsRequest(params) +// // Example sending a request using the ListThemesRequest method. +// req, resp := client.ListThemesRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplatePermissions -func (c *QuickSight) UpdateTemplatePermissionsRequest(input *UpdateTemplatePermissionsInput) (req *request.Request, output *UpdateTemplatePermissionsOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListThemes +func (c *QuickSight) ListThemesRequest(input *ListThemesInput) (req *request.Request, output *ListThemesOutput) { op := &request.Operation{ - Name: opUpdateTemplatePermissions, - HTTPMethod: "PUT", - HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/permissions", + Name: opListThemes, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/themes", } if input == nil { - input = &UpdateTemplatePermissionsInput{} + input = &ListThemesInput{} } - output = &UpdateTemplatePermissionsOutput{} + output = &ListThemesOutput{} req = c.newRequest(op, input, output) return } -// UpdateTemplatePermissions API operation for Amazon QuickSight. +// ListThemes API operation for Amazon QuickSight. // -// Updates the resource permissions for a template. +// Lists all the themes in 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. // // See the AWS API reference guide for Amazon QuickSight's -// API operation UpdateTemplatePermissions for usage and error information. +// API operation ListThemes for usage and error information. // // Returned Error Types: -// * ThrottlingException -// Access is throttled. +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. // // * InvalidParameterValueException // One or more parameters has a value that isn't valid. // -// * ConflictException -// Updating or deleting a resource can cause an inconsistent state. +// * InvalidNextTokenException +// The NextToken value isn't valid. // // * ResourceNotFoundException // One or more resources can't be found. // +// * ThrottlingException +// Access is throttled. +// // * UnsupportedUserEditionException // This error indicates that you are calling an operation on an Amazon QuickSight // subscription where the edition doesn't include support for that operation. @@ -7042,80 +7221,81 @@ func (c *QuickSight) UpdateTemplatePermissionsRequest(input *UpdateTemplatePermi // * InternalFailureException // An internal failure occurred. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplatePermissions -func (c *QuickSight) UpdateTemplatePermissions(input *UpdateTemplatePermissionsInput) (*UpdateTemplatePermissionsOutput, error) { - req, out := c.UpdateTemplatePermissionsRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListThemes +func (c *QuickSight) ListThemes(input *ListThemesInput) (*ListThemesOutput, error) { + req, out := c.ListThemesRequest(input) return out, req.Send() } -// UpdateTemplatePermissionsWithContext is the same as UpdateTemplatePermissions with the addition of +// ListThemesWithContext is the same as ListThemes with the addition of // the ability to pass a context and additional request options. // -// See UpdateTemplatePermissions for details on how to use this API operation. +// See ListThemes for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateTemplatePermissionsWithContext(ctx aws.Context, input *UpdateTemplatePermissionsInput, opts ...request.Option) (*UpdateTemplatePermissionsOutput, error) { - req, out := c.UpdateTemplatePermissionsRequest(input) +func (c *QuickSight) ListThemesWithContext(ctx aws.Context, input *ListThemesInput, opts ...request.Option) (*ListThemesOutput, error) { + req, out := c.ListThemesRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -const opUpdateUser = "UpdateUser" +const opListUserGroups = "ListUserGroups" -// UpdateUserRequest generates a "aws/request.Request" representing the -// client's request for the UpdateUser operation. The "output" return +// ListUserGroupsRequest generates a "aws/request.Request" representing the +// client's request for the ListUserGroups operation. The "output" return // value will be populated with the request's response once the request completes // successfully. // // Use "Send" method on the returned Request to send the API call to the service. // the "output" return value is not valid until after Send returns without error. // -// See UpdateUser for more information on using the UpdateUser +// See ListUserGroups for more information on using the ListUserGroups // API call, and error handling. // // This method is useful when you want to inject custom logic or configuration // into the SDK's request lifecycle. Such as custom headers, or retry logic. // // -// // Example sending a request using the UpdateUserRequest method. -// req, resp := client.UpdateUserRequest(params) +// // Example sending a request using the ListUserGroupsRequest method. +// req, resp := client.ListUserGroupsRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateUser -func (c *QuickSight) UpdateUserRequest(input *UpdateUserInput) (req *request.Request, output *UpdateUserOutput) { +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListUserGroups +func (c *QuickSight) ListUserGroupsRequest(input *ListUserGroupsInput) (req *request.Request, output *ListUserGroupsOutput) { op := &request.Operation{ - Name: opUpdateUser, - HTTPMethod: "PUT", - HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users/{UserName}", + Name: opListUserGroups, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users/{UserName}/groups", } if input == nil { - input = &UpdateUserInput{} + input = &ListUserGroupsInput{} } - output = &UpdateUserOutput{} + output = &ListUserGroupsOutput{} req = c.newRequest(op, input, output) return } -// UpdateUser API operation for Amazon QuickSight. +// ListUserGroups API operation for Amazon QuickSight. // -// Updates an Amazon QuickSight user. +// Lists the Amazon QuickSight groups that an Amazon QuickSight user is a member +// of. // // Returns awserr.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 QuickSight's -// API operation UpdateUser for usage and error information. +// API operation ListUserGroups for usage and error information. // // Returned Error Types: // * AccessDeniedException @@ -7134,359 +7314,7276 @@ func (c *QuickSight) UpdateUserRequest(input *UpdateUserInput) (req *request.Req // * ThrottlingException // Access is throttled. // +// * PreconditionNotMetException +// One or more preconditions aren't met. +// // * InternalFailureException // An internal failure occurred. // // * ResourceUnavailableException // This resource is currently unavailable. // -// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateUser -func (c *QuickSight) UpdateUser(input *UpdateUserInput) (*UpdateUserOutput, error) { - req, out := c.UpdateUserRequest(input) +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListUserGroups +func (c *QuickSight) ListUserGroups(input *ListUserGroupsInput) (*ListUserGroupsOutput, error) { + req, out := c.ListUserGroupsRequest(input) return out, req.Send() } -// UpdateUserWithContext is the same as UpdateUser with the addition of +// ListUserGroupsWithContext is the same as ListUserGroups 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. +// See ListUserGroups for details on how to use this API operation. // // The context must be non-nil and will be used for request cancellation. If // the context is nil a panic will occur. In the future the SDK may create // sub-contexts for http.Requests. See https://golang.org/pkg/context/ // for more information on using Contexts. -func (c *QuickSight) UpdateUserWithContext(ctx aws.Context, input *UpdateUserInput, opts ...request.Option) (*UpdateUserOutput, error) { - req, out := c.UpdateUserRequest(input) +func (c *QuickSight) ListUserGroupsWithContext(ctx aws.Context, input *ListUserGroupsInput, opts ...request.Option) (*ListUserGroupsOutput, error) { + req, out := c.ListUserGroupsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opListUsers = "ListUsers" + +// ListUsersRequest generates a "aws/request.Request" representing the +// client's request for the ListUsers operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListUsers for more information on using the ListUsers +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListUsersRequest method. +// req, resp := client.ListUsersRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListUsers +func (c *QuickSight) ListUsersRequest(input *ListUsersInput) (req *request.Request, output *ListUsersOutput) { + op := &request.Operation{ + Name: opListUsers, + HTTPMethod: "GET", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users", + } + + if input == nil { + input = &ListUsersInput{} + } + + output = &ListUsersOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListUsers API operation for Amazon QuickSight. +// +// Returns a list of all of the Amazon QuickSight users belonging to this 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 Amazon QuickSight's +// API operation ListUsers for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * InvalidNextTokenException +// The NextToken value isn't valid. +// +// * PreconditionNotMetException +// One or more preconditions aren't met. +// +// * InternalFailureException +// An internal failure occurred. +// +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ListUsers +func (c *QuickSight) ListUsers(input *ListUsersInput) (*ListUsersOutput, error) { + req, out := c.ListUsersRequest(input) + 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 *QuickSight) 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() +} + +const opRegisterUser = "RegisterUser" + +// RegisterUserRequest generates a "aws/request.Request" representing the +// client's request for the RegisterUser operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See RegisterUser for more information on using the RegisterUser +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the RegisterUserRequest method. +// req, resp := client.RegisterUserRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/RegisterUser +func (c *QuickSight) RegisterUserRequest(input *RegisterUserInput) (req *request.Request, output *RegisterUserOutput) { + op := &request.Operation{ + Name: opRegisterUser, + HTTPMethod: "POST", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users", + } + + if input == nil { + input = &RegisterUserInput{} + } + + output = &RegisterUserOutput{} + req = c.newRequest(op, input, output) + return +} + +// RegisterUser API operation for Amazon QuickSight. +// +// Creates an Amazon QuickSight user, whose identity is associated with the +// AWS Identity and Access Management (IAM) identity or role specified in the +// request. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon QuickSight's +// API operation RegisterUser for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * LimitExceededException +// A limit is exceeded. +// +// * ResourceExistsException +// The resource specified already exists. +// +// * PreconditionNotMetException +// One or more preconditions aren't met. +// +// * InternalFailureException +// An internal failure occurred. +// +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/RegisterUser +func (c *QuickSight) RegisterUser(input *RegisterUserInput) (*RegisterUserOutput, error) { + req, out := c.RegisterUserRequest(input) + return out, req.Send() +} + +// RegisterUserWithContext is the same as RegisterUser with the addition of +// the ability to pass a context and additional request options. +// +// See RegisterUser for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) RegisterUserWithContext(ctx aws.Context, input *RegisterUserInput, opts ...request.Option) (*RegisterUserOutput, error) { + req, out := c.RegisterUserRequest(input) req.SetContext(ctx) req.ApplyOptions(opts...) return out, req.Send() } -// You don't have access to this item. The provided credentials couldn't be -// validated. You might not be authorized to carry out the request. Make sure -// that your account is authorized to use the Amazon QuickSight service, that -// your policies have the correct permissions, and that you are using the correct -// access keys. -type AccessDeniedException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +const opSearchDashboards = "SearchDashboards" + +// SearchDashboardsRequest generates a "aws/request.Request" representing the +// client's request for the SearchDashboards operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See SearchDashboards for more information on using the SearchDashboards +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the SearchDashboardsRequest method. +// req, resp := client.SearchDashboardsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/SearchDashboards +func (c *QuickSight) SearchDashboardsRequest(input *SearchDashboardsInput) (req *request.Request, output *SearchDashboardsOutput) { + op := &request.Operation{ + Name: opSearchDashboards, + HTTPMethod: "POST", + HTTPPath: "/accounts/{AwsAccountId}/search/dashboards", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &SearchDashboardsInput{} + } + + output = &SearchDashboardsOutput{} + req = c.newRequest(op, input, output) + return +} + +// SearchDashboards API operation for Amazon QuickSight. +// +// Searchs for dashboards that belong to a user. +// +// Returns awserr.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 QuickSight's +// API operation SearchDashboards for usage and error information. +// +// Returned Error Types: +// * ThrottlingException +// Access is throttled. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * InvalidNextTokenException +// The NextToken value isn't valid. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/SearchDashboards +func (c *QuickSight) SearchDashboards(input *SearchDashboardsInput) (*SearchDashboardsOutput, error) { + req, out := c.SearchDashboardsRequest(input) + return out, req.Send() +} + +// SearchDashboardsWithContext is the same as SearchDashboards with the addition of +// the ability to pass a context and additional request options. +// +// See SearchDashboards for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) SearchDashboardsWithContext(ctx aws.Context, input *SearchDashboardsInput, opts ...request.Option) (*SearchDashboardsOutput, error) { + req, out := c.SearchDashboardsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// SearchDashboardsPages iterates over the pages of a SearchDashboards operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See SearchDashboards 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 SearchDashboards operation. +// pageNum := 0 +// err := client.SearchDashboardsPages(params, +// func(page *quicksight.SearchDashboardsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *QuickSight) SearchDashboardsPages(input *SearchDashboardsInput, fn func(*SearchDashboardsOutput, bool) bool) error { + return c.SearchDashboardsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// SearchDashboardsPagesWithContext same as SearchDashboardsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) SearchDashboardsPagesWithContext(ctx aws.Context, input *SearchDashboardsInput, fn func(*SearchDashboardsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *SearchDashboardsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.SearchDashboardsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*SearchDashboardsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opTagResource = "TagResource" + +// TagResourceRequest generates a "aws/request.Request" representing the +// client's request for the TagResource operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See TagResource for more information on using the TagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the TagResourceRequest method. +// req, resp := client.TagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/TagResource +func (c *QuickSight) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { + op := &request.Operation{ + Name: opTagResource, + HTTPMethod: "POST", + HTTPPath: "/resources/{ResourceArn}/tags", + } + + if input == nil { + input = &TagResourceInput{} + } + + output = &TagResourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// TagResource API operation for Amazon QuickSight. +// +// Assigns one or more tags (key-value pairs) to the specified QuickSight resource. +// +// Tags can help you organize and categorize your resources. You can also use +// them to scope user permissions, by granting a user permission to access or +// change only resources with certain tag values. You can use the TagResource +// operation with a resource that already has tags. If you specify a new tag +// key for the resource, this tag is appended to the list of tags associated +// with the resource. If you specify a tag key that is already associated with +// the resource, the new tag value that you specify replaces the previous value +// for that tag. +// +// You can associate as many as 50 tags with a resource. QuickSight supports +// tagging on data set, data source, dashboard, and template. +// +// Tagging for QuickSight works in a similar way to tagging for other AWS services, +// except for the following: +// +// * You can't use tags to track AWS costs for QuickSight. This restriction +// is because QuickSight costs are based on users and SPICE capacity, which +// aren't taggable resources. +// +// * QuickSight doesn't currently support the Tag Editor for AWS Resource +// 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 +// the error. +// +// See the AWS API reference guide for Amazon QuickSight's +// API operation TagResource for usage and error information. +// +// Returned Error Types: +// * LimitExceededException +// A limit is exceeded. +// +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/TagResource +func (c *QuickSight) 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 *QuickSight) 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 will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UntagResource for more information on using the UntagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UntagResourceRequest method. +// req, resp := client.UntagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UntagResource +func (c *QuickSight) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { + op := &request.Operation{ + Name: opUntagResource, + HTTPMethod: "DELETE", + HTTPPath: "/resources/{ResourceArn}/tags", + } + + if input == nil { + input = &UntagResourceInput{} + } + + output = &UntagResourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// UntagResource API operation for Amazon QuickSight. +// +// Removes a tag or tags from 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 Amazon QuickSight's +// API operation UntagResource for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UntagResource +func (c *QuickSight) 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 *QuickSight) 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 opUpdateAccountCustomization = "UpdateAccountCustomization" + +// UpdateAccountCustomizationRequest generates a "aws/request.Request" representing the +// client's request for the UpdateAccountCustomization operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateAccountCustomization for more information on using the UpdateAccountCustomization +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateAccountCustomizationRequest method. +// req, resp := client.UpdateAccountCustomizationRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateAccountCustomization +func (c *QuickSight) UpdateAccountCustomizationRequest(input *UpdateAccountCustomizationInput) (req *request.Request, output *UpdateAccountCustomizationOutput) { + op := &request.Operation{ + Name: opUpdateAccountCustomization, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/customizations", + } + + if input == nil { + input = &UpdateAccountCustomizationInput{} + } + + output = &UpdateAccountCustomizationOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateAccountCustomization API operation for Amazon QuickSight. +// +// Updates customizations associated with the QuickSight subscription on your +// 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. +// +// See the AWS API reference guide for Amazon QuickSight's +// API operation UpdateAccountCustomization for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * InternalFailureException +// An internal failure occurred. +// +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateAccountCustomization +func (c *QuickSight) UpdateAccountCustomization(input *UpdateAccountCustomizationInput) (*UpdateAccountCustomizationOutput, error) { + req, out := c.UpdateAccountCustomizationRequest(input) + return out, req.Send() +} + +// UpdateAccountCustomizationWithContext is the same as UpdateAccountCustomization with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAccountCustomization for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateAccountCustomizationWithContext(ctx aws.Context, input *UpdateAccountCustomizationInput, opts ...request.Option) (*UpdateAccountCustomizationOutput, error) { + req, out := c.UpdateAccountCustomizationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateAccountSettings = "UpdateAccountSettings" + +// UpdateAccountSettingsRequest generates a "aws/request.Request" representing the +// client's request for the UpdateAccountSettings operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateAccountSettings for more information on using the UpdateAccountSettings +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateAccountSettingsRequest method. +// req, resp := client.UpdateAccountSettingsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateAccountSettings +func (c *QuickSight) UpdateAccountSettingsRequest(input *UpdateAccountSettingsInput) (req *request.Request, output *UpdateAccountSettingsOutput) { + op := &request.Operation{ + Name: opUpdateAccountSettings, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/settings", + } + + if input == nil { + input = &UpdateAccountSettingsInput{} + } + + output = &UpdateAccountSettingsOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateAccountSettings API operation for Amazon QuickSight. +// +// Updates the settings for the Amazon QuickSight subscription in your 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. +// +// See the AWS API reference guide for Amazon QuickSight's +// API operation UpdateAccountSettings for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * InternalFailureException +// An internal failure occurred. +// +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateAccountSettings +func (c *QuickSight) UpdateAccountSettings(input *UpdateAccountSettingsInput) (*UpdateAccountSettingsOutput, error) { + req, out := c.UpdateAccountSettingsRequest(input) + return out, req.Send() +} + +// UpdateAccountSettingsWithContext is the same as UpdateAccountSettings with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAccountSettings for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateAccountSettingsWithContext(ctx aws.Context, input *UpdateAccountSettingsInput, opts ...request.Option) (*UpdateAccountSettingsOutput, error) { + req, out := c.UpdateAccountSettingsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateDashboard = "UpdateDashboard" + +// UpdateDashboardRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDashboard operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDashboard for more information on using the UpdateDashboard +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateDashboardRequest method. +// req, resp := client.UpdateDashboardRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboard +func (c *QuickSight) UpdateDashboardRequest(input *UpdateDashboardInput) (req *request.Request, output *UpdateDashboardOutput) { + op := &request.Operation{ + Name: opUpdateDashboard, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}", + } + + if input == nil { + input = &UpdateDashboardInput{} + } + + output = &UpdateDashboardOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDashboard API operation for Amazon QuickSight. +// +// Updates a dashboard in an 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. +// +// See the AWS API reference guide for Amazon QuickSight's +// API operation UpdateDashboard for usage and error information. +// +// Returned Error Types: +// * ThrottlingException +// Access is throttled. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * LimitExceededException +// A limit is exceeded. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboard +func (c *QuickSight) UpdateDashboard(input *UpdateDashboardInput) (*UpdateDashboardOutput, error) { + req, out := c.UpdateDashboardRequest(input) + return out, req.Send() +} + +// UpdateDashboardWithContext is the same as UpdateDashboard with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDashboard for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateDashboardWithContext(ctx aws.Context, input *UpdateDashboardInput, opts ...request.Option) (*UpdateDashboardOutput, error) { + req, out := c.UpdateDashboardRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateDashboardPermissions = "UpdateDashboardPermissions" + +// UpdateDashboardPermissionsRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDashboardPermissions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDashboardPermissions for more information on using the UpdateDashboardPermissions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateDashboardPermissionsRequest method. +// req, resp := client.UpdateDashboardPermissionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboardPermissions +func (c *QuickSight) UpdateDashboardPermissionsRequest(input *UpdateDashboardPermissionsInput) (req *request.Request, output *UpdateDashboardPermissionsOutput) { + op := &request.Operation{ + Name: opUpdateDashboardPermissions, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}/permissions", + } + + if input == nil { + input = &UpdateDashboardPermissionsInput{} + } + + output = &UpdateDashboardPermissionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDashboardPermissions API operation for Amazon QuickSight. +// +// Updates read and write permissions on a dashboard. +// +// Returns awserr.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 QuickSight's +// API operation UpdateDashboardPermissions for usage and error information. +// +// Returned Error Types: +// * ThrottlingException +// Access is throttled. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboardPermissions +func (c *QuickSight) UpdateDashboardPermissions(input *UpdateDashboardPermissionsInput) (*UpdateDashboardPermissionsOutput, error) { + req, out := c.UpdateDashboardPermissionsRequest(input) + return out, req.Send() +} + +// UpdateDashboardPermissionsWithContext is the same as UpdateDashboardPermissions with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDashboardPermissions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateDashboardPermissionsWithContext(ctx aws.Context, input *UpdateDashboardPermissionsInput, opts ...request.Option) (*UpdateDashboardPermissionsOutput, error) { + req, out := c.UpdateDashboardPermissionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateDashboardPublishedVersion = "UpdateDashboardPublishedVersion" + +// UpdateDashboardPublishedVersionRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDashboardPublishedVersion operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDashboardPublishedVersion for more information on using the UpdateDashboardPublishedVersion +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateDashboardPublishedVersionRequest method. +// req, resp := client.UpdateDashboardPublishedVersionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboardPublishedVersion +func (c *QuickSight) UpdateDashboardPublishedVersionRequest(input *UpdateDashboardPublishedVersionInput) (req *request.Request, output *UpdateDashboardPublishedVersionOutput) { + op := &request.Operation{ + Name: opUpdateDashboardPublishedVersion, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/dashboards/{DashboardId}/versions/{VersionNumber}", + } + + if input == nil { + input = &UpdateDashboardPublishedVersionInput{} + } + + output = &UpdateDashboardPublishedVersionOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDashboardPublishedVersion API operation for Amazon QuickSight. +// +// Updates the published version of a dashboard. +// +// Returns awserr.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 QuickSight's +// API operation UpdateDashboardPublishedVersion for usage and error information. +// +// Returned Error Types: +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ThrottlingException +// Access is throttled. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDashboardPublishedVersion +func (c *QuickSight) UpdateDashboardPublishedVersion(input *UpdateDashboardPublishedVersionInput) (*UpdateDashboardPublishedVersionOutput, error) { + req, out := c.UpdateDashboardPublishedVersionRequest(input) + return out, req.Send() +} + +// UpdateDashboardPublishedVersionWithContext is the same as UpdateDashboardPublishedVersion with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDashboardPublishedVersion for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateDashboardPublishedVersionWithContext(ctx aws.Context, input *UpdateDashboardPublishedVersionInput, opts ...request.Option) (*UpdateDashboardPublishedVersionOutput, error) { + req, out := c.UpdateDashboardPublishedVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateDataSet = "UpdateDataSet" + +// UpdateDataSetRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDataSet operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDataSet for more information on using the UpdateDataSet +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateDataSetRequest method. +// req, resp := client.UpdateDataSetRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSet +func (c *QuickSight) UpdateDataSetRequest(input *UpdateDataSetInput) (req *request.Request, output *UpdateDataSetOutput) { + op := &request.Operation{ + Name: opUpdateDataSet, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}", + } + + if input == nil { + input = &UpdateDataSetInput{} + } + + output = &UpdateDataSetOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDataSet API operation for Amazon QuickSight. +// +// Updates a dataset. +// +// Returns awserr.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 QuickSight's +// API operation UpdateDataSet for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * LimitExceededException +// A limit is exceeded. +// +// * ThrottlingException +// Access is throttled. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSet +func (c *QuickSight) UpdateDataSet(input *UpdateDataSetInput) (*UpdateDataSetOutput, error) { + req, out := c.UpdateDataSetRequest(input) + return out, req.Send() +} + +// UpdateDataSetWithContext is the same as UpdateDataSet with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDataSet for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateDataSetWithContext(ctx aws.Context, input *UpdateDataSetInput, opts ...request.Option) (*UpdateDataSetOutput, error) { + req, out := c.UpdateDataSetRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateDataSetPermissions = "UpdateDataSetPermissions" + +// UpdateDataSetPermissionsRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDataSetPermissions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDataSetPermissions for more information on using the UpdateDataSetPermissions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateDataSetPermissionsRequest method. +// req, resp := client.UpdateDataSetPermissionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSetPermissions +func (c *QuickSight) UpdateDataSetPermissionsRequest(input *UpdateDataSetPermissionsInput) (req *request.Request, output *UpdateDataSetPermissionsOutput) { + op := &request.Operation{ + Name: opUpdateDataSetPermissions, + HTTPMethod: "POST", + HTTPPath: "/accounts/{AwsAccountId}/data-sets/{DataSetId}/permissions", + } + + if input == nil { + input = &UpdateDataSetPermissionsInput{} + } + + output = &UpdateDataSetPermissionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDataSetPermissions API operation for Amazon QuickSight. +// +// Updates the permissions on a dataset. +// +// The permissions resource is arn:aws:quicksight:region:aws-account-id:dataset/data-set-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 +// the error. +// +// See the AWS API reference guide for Amazon QuickSight's +// API operation UpdateDataSetPermissions for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSetPermissions +func (c *QuickSight) UpdateDataSetPermissions(input *UpdateDataSetPermissionsInput) (*UpdateDataSetPermissionsOutput, error) { + req, out := c.UpdateDataSetPermissionsRequest(input) + return out, req.Send() +} + +// UpdateDataSetPermissionsWithContext is the same as UpdateDataSetPermissions with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDataSetPermissions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateDataSetPermissionsWithContext(ctx aws.Context, input *UpdateDataSetPermissionsInput, opts ...request.Option) (*UpdateDataSetPermissionsOutput, error) { + req, out := c.UpdateDataSetPermissionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateDataSource = "UpdateDataSource" + +// UpdateDataSourceRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDataSource operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDataSource for more information on using the UpdateDataSource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateDataSourceRequest method. +// req, resp := client.UpdateDataSourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSource +func (c *QuickSight) UpdateDataSourceRequest(input *UpdateDataSourceInput) (req *request.Request, output *UpdateDataSourceOutput) { + op := &request.Operation{ + Name: opUpdateDataSource, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/data-sources/{DataSourceId}", + } + + if input == nil { + input = &UpdateDataSourceInput{} + } + + output = &UpdateDataSourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDataSource API operation for Amazon QuickSight. +// +// Updates a data source. +// +// Returns awserr.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 QuickSight's +// API operation UpdateDataSource for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ThrottlingException +// Access is throttled. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSource +func (c *QuickSight) UpdateDataSource(input *UpdateDataSourceInput) (*UpdateDataSourceOutput, error) { + req, out := c.UpdateDataSourceRequest(input) + return out, req.Send() +} + +// UpdateDataSourceWithContext is the same as UpdateDataSource with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDataSource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateDataSourceWithContext(ctx aws.Context, input *UpdateDataSourceInput, opts ...request.Option) (*UpdateDataSourceOutput, error) { + req, out := c.UpdateDataSourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateDataSourcePermissions = "UpdateDataSourcePermissions" + +// UpdateDataSourcePermissionsRequest generates a "aws/request.Request" representing the +// client's request for the UpdateDataSourcePermissions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateDataSourcePermissions for more information on using the UpdateDataSourcePermissions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateDataSourcePermissionsRequest method. +// req, resp := client.UpdateDataSourcePermissionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSourcePermissions +func (c *QuickSight) UpdateDataSourcePermissionsRequest(input *UpdateDataSourcePermissionsInput) (req *request.Request, output *UpdateDataSourcePermissionsOutput) { + op := &request.Operation{ + Name: opUpdateDataSourcePermissions, + HTTPMethod: "POST", + HTTPPath: "/accounts/{AwsAccountId}/data-sources/{DataSourceId}/permissions", + } + + if input == nil { + input = &UpdateDataSourcePermissionsInput{} + } + + output = &UpdateDataSourcePermissionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateDataSourcePermissions API operation for Amazon QuickSight. +// +// Updates the permissions to a data source. +// +// Returns awserr.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 QuickSight's +// API operation UpdateDataSourcePermissions for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateDataSourcePermissions +func (c *QuickSight) UpdateDataSourcePermissions(input *UpdateDataSourcePermissionsInput) (*UpdateDataSourcePermissionsOutput, error) { + req, out := c.UpdateDataSourcePermissionsRequest(input) + return out, req.Send() +} + +// UpdateDataSourcePermissionsWithContext is the same as UpdateDataSourcePermissions with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateDataSourcePermissions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateDataSourcePermissionsWithContext(ctx aws.Context, input *UpdateDataSourcePermissionsInput, opts ...request.Option) (*UpdateDataSourcePermissionsOutput, error) { + req, out := c.UpdateDataSourcePermissionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateGroup = "UpdateGroup" + +// UpdateGroupRequest generates a "aws/request.Request" representing the +// client's request for the UpdateGroup operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateGroup for more information on using the UpdateGroup +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateGroupRequest method. +// req, resp := client.UpdateGroupRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateGroup +func (c *QuickSight) UpdateGroupRequest(input *UpdateGroupInput) (req *request.Request, output *UpdateGroupOutput) { + op := &request.Operation{ + Name: opUpdateGroup, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/groups/{GroupName}", + } + + if input == nil { + input = &UpdateGroupInput{} + } + + output = &UpdateGroupOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateGroup API operation for Amazon QuickSight. +// +// Changes a group description. +// +// Returns awserr.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 QuickSight's +// API operation UpdateGroup for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * PreconditionNotMetException +// One or more preconditions aren't met. +// +// * InternalFailureException +// An internal failure occurred. +// +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateGroup +func (c *QuickSight) UpdateGroup(input *UpdateGroupInput) (*UpdateGroupOutput, error) { + req, out := c.UpdateGroupRequest(input) + 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 *QuickSight) 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 opUpdateIAMPolicyAssignment = "UpdateIAMPolicyAssignment" + +// UpdateIAMPolicyAssignmentRequest generates a "aws/request.Request" representing the +// client's request for the UpdateIAMPolicyAssignment operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateIAMPolicyAssignment for more information on using the UpdateIAMPolicyAssignment +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateIAMPolicyAssignmentRequest method. +// req, resp := client.UpdateIAMPolicyAssignmentRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateIAMPolicyAssignment +func (c *QuickSight) UpdateIAMPolicyAssignmentRequest(input *UpdateIAMPolicyAssignmentInput) (req *request.Request, output *UpdateIAMPolicyAssignmentOutput) { + op := &request.Operation{ + Name: opUpdateIAMPolicyAssignment, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/iam-policy-assignments/{AssignmentName}", + } + + if input == nil { + input = &UpdateIAMPolicyAssignmentInput{} + } + + output = &UpdateIAMPolicyAssignmentOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateIAMPolicyAssignment API operation for Amazon QuickSight. +// +// Updates an existing IAM policy assignment. This operation updates only the +// optional parameter or parameters that are specified in the request. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon QuickSight's +// API operation UpdateIAMPolicyAssignment for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceExistsException +// The resource specified already exists. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * ConcurrentUpdatingException +// A resource is already in a state that indicates an action is happening that +// must complete before a new update can be applied. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateIAMPolicyAssignment +func (c *QuickSight) UpdateIAMPolicyAssignment(input *UpdateIAMPolicyAssignmentInput) (*UpdateIAMPolicyAssignmentOutput, error) { + req, out := c.UpdateIAMPolicyAssignmentRequest(input) + return out, req.Send() +} + +// UpdateIAMPolicyAssignmentWithContext is the same as UpdateIAMPolicyAssignment with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateIAMPolicyAssignment for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateIAMPolicyAssignmentWithContext(ctx aws.Context, input *UpdateIAMPolicyAssignmentInput, opts ...request.Option) (*UpdateIAMPolicyAssignmentOutput, error) { + req, out := c.UpdateIAMPolicyAssignmentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateTemplate = "UpdateTemplate" + +// UpdateTemplateRequest generates a "aws/request.Request" representing the +// client's request for the UpdateTemplate operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateTemplate for more information on using the UpdateTemplate +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateTemplateRequest method. +// req, resp := client.UpdateTemplateRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplate +func (c *QuickSight) UpdateTemplateRequest(input *UpdateTemplateInput) (req *request.Request, output *UpdateTemplateOutput) { + op := &request.Operation{ + Name: opUpdateTemplate, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}", + } + + if input == nil { + input = &UpdateTemplateInput{} + } + + output = &UpdateTemplateOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateTemplate API operation for Amazon QuickSight. +// +// Updates a template from an existing Amazon QuickSight analysis or another +// template. +// +// Returns awserr.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 QuickSight's +// API operation UpdateTemplate for usage and error information. +// +// Returned Error Types: +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceExistsException +// The resource specified already exists. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * LimitExceededException +// A limit is exceeded. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplate +func (c *QuickSight) UpdateTemplate(input *UpdateTemplateInput) (*UpdateTemplateOutput, error) { + req, out := c.UpdateTemplateRequest(input) + return out, req.Send() +} + +// UpdateTemplateWithContext is the same as UpdateTemplate with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateTemplate for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateTemplateWithContext(ctx aws.Context, input *UpdateTemplateInput, opts ...request.Option) (*UpdateTemplateOutput, error) { + req, out := c.UpdateTemplateRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateTemplateAlias = "UpdateTemplateAlias" + +// UpdateTemplateAliasRequest generates a "aws/request.Request" representing the +// client's request for the UpdateTemplateAlias operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateTemplateAlias for more information on using the UpdateTemplateAlias +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateTemplateAliasRequest method. +// req, resp := client.UpdateTemplateAliasRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplateAlias +func (c *QuickSight) UpdateTemplateAliasRequest(input *UpdateTemplateAliasInput) (req *request.Request, output *UpdateTemplateAliasOutput) { + op := &request.Operation{ + Name: opUpdateTemplateAlias, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/aliases/{AliasName}", + } + + if input == nil { + input = &UpdateTemplateAliasInput{} + } + + output = &UpdateTemplateAliasOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateTemplateAlias API operation for Amazon QuickSight. +// +// Updates the template alias of a template. +// +// Returns awserr.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 QuickSight's +// API operation UpdateTemplateAlias for usage and error information. +// +// Returned Error Types: +// * ThrottlingException +// Access is throttled. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplateAlias +func (c *QuickSight) UpdateTemplateAlias(input *UpdateTemplateAliasInput) (*UpdateTemplateAliasOutput, error) { + req, out := c.UpdateTemplateAliasRequest(input) + return out, req.Send() +} + +// UpdateTemplateAliasWithContext is the same as UpdateTemplateAlias with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateTemplateAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateTemplateAliasWithContext(ctx aws.Context, input *UpdateTemplateAliasInput, opts ...request.Option) (*UpdateTemplateAliasOutput, error) { + req, out := c.UpdateTemplateAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateTemplatePermissions = "UpdateTemplatePermissions" + +// UpdateTemplatePermissionsRequest generates a "aws/request.Request" representing the +// client's request for the UpdateTemplatePermissions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateTemplatePermissions for more information on using the UpdateTemplatePermissions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateTemplatePermissionsRequest method. +// req, resp := client.UpdateTemplatePermissionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplatePermissions +func (c *QuickSight) UpdateTemplatePermissionsRequest(input *UpdateTemplatePermissionsInput) (req *request.Request, output *UpdateTemplatePermissionsOutput) { + op := &request.Operation{ + Name: opUpdateTemplatePermissions, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/templates/{TemplateId}/permissions", + } + + if input == nil { + input = &UpdateTemplatePermissionsInput{} + } + + output = &UpdateTemplatePermissionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateTemplatePermissions API operation for Amazon QuickSight. +// +// Updates the resource permissions for a template. +// +// Returns awserr.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 QuickSight's +// API operation UpdateTemplatePermissions for usage and error information. +// +// Returned Error Types: +// * ThrottlingException +// Access is throttled. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTemplatePermissions +func (c *QuickSight) UpdateTemplatePermissions(input *UpdateTemplatePermissionsInput) (*UpdateTemplatePermissionsOutput, error) { + req, out := c.UpdateTemplatePermissionsRequest(input) + return out, req.Send() +} + +// UpdateTemplatePermissionsWithContext is the same as UpdateTemplatePermissions with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateTemplatePermissions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateTemplatePermissionsWithContext(ctx aws.Context, input *UpdateTemplatePermissionsInput, opts ...request.Option) (*UpdateTemplatePermissionsOutput, error) { + req, out := c.UpdateTemplatePermissionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateTheme = "UpdateTheme" + +// UpdateThemeRequest generates a "aws/request.Request" representing the +// client's request for the UpdateTheme operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateTheme for more information on using the UpdateTheme +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateThemeRequest method. +// req, resp := client.UpdateThemeRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTheme +func (c *QuickSight) UpdateThemeRequest(input *UpdateThemeInput) (req *request.Request, output *UpdateThemeOutput) { + op := &request.Operation{ + Name: opUpdateTheme, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}", + } + + if input == nil { + input = &UpdateThemeInput{} + } + + output = &UpdateThemeOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateTheme API operation for Amazon QuickSight. +// +// Updates a theme. +// +// Returns awserr.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 QuickSight's +// API operation UpdateTheme for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * LimitExceededException +// A limit is exceeded. +// +// * ResourceExistsException +// The resource specified already exists. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateTheme +func (c *QuickSight) UpdateTheme(input *UpdateThemeInput) (*UpdateThemeOutput, error) { + req, out := c.UpdateThemeRequest(input) + return out, req.Send() +} + +// UpdateThemeWithContext is the same as UpdateTheme with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateTheme for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateThemeWithContext(ctx aws.Context, input *UpdateThemeInput, opts ...request.Option) (*UpdateThemeOutput, error) { + req, out := c.UpdateThemeRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateThemeAlias = "UpdateThemeAlias" + +// UpdateThemeAliasRequest generates a "aws/request.Request" representing the +// client's request for the UpdateThemeAlias operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateThemeAlias for more information on using the UpdateThemeAlias +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateThemeAliasRequest method. +// req, resp := client.UpdateThemeAliasRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateThemeAlias +func (c *QuickSight) UpdateThemeAliasRequest(input *UpdateThemeAliasInput) (req *request.Request, output *UpdateThemeAliasOutput) { + op := &request.Operation{ + Name: opUpdateThemeAlias, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}/aliases/{AliasName}", + } + + if input == nil { + input = &UpdateThemeAliasInput{} + } + + output = &UpdateThemeAliasOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateThemeAlias API operation for Amazon QuickSight. +// +// Updates an alias of a theme. +// +// Returns awserr.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 QuickSight's +// API operation UpdateThemeAlias for usage and error information. +// +// Returned Error Types: +// * ConflictException +// Updating or deleting a resource can cause an inconsistent state. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceExistsException +// The resource specified already exists. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateThemeAlias +func (c *QuickSight) UpdateThemeAlias(input *UpdateThemeAliasInput) (*UpdateThemeAliasOutput, error) { + req, out := c.UpdateThemeAliasRequest(input) + return out, req.Send() +} + +// UpdateThemeAliasWithContext is the same as UpdateThemeAlias with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateThemeAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateThemeAliasWithContext(ctx aws.Context, input *UpdateThemeAliasInput, opts ...request.Option) (*UpdateThemeAliasOutput, error) { + req, out := c.UpdateThemeAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateThemePermissions = "UpdateThemePermissions" + +// UpdateThemePermissionsRequest generates a "aws/request.Request" representing the +// client's request for the UpdateThemePermissions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateThemePermissions for more information on using the UpdateThemePermissions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateThemePermissionsRequest method. +// req, resp := client.UpdateThemePermissionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateThemePermissions +func (c *QuickSight) UpdateThemePermissionsRequest(input *UpdateThemePermissionsInput) (req *request.Request, output *UpdateThemePermissionsOutput) { + op := &request.Operation{ + Name: opUpdateThemePermissions, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/themes/{ThemeId}/permissions", + } + + if input == nil { + input = &UpdateThemePermissionsInput{} + } + + output = &UpdateThemePermissionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateThemePermissions API operation for Amazon QuickSight. +// +// Updates the resource permissions for a theme. Permissions apply to the action +// to grant or revoke permissions on, for example "quicksight:DescribeTheme". +// +// Theme permissions apply in groupings. Valid groupings include the following +// for the three levels of permissions, which are user, owner, or no permissions: +// +// * User "quicksight:DescribeTheme" "quicksight:DescribeThemeAlias" "quicksight:ListThemeAliases" +// "quicksight:ListThemeVersions" +// +// * Owner "quicksight:DescribeTheme" "quicksight:DescribeThemeAlias" "quicksight:ListThemeAliases" +// "quicksight:ListThemeVersions" "quicksight:DeleteTheme" "quicksight:UpdateTheme" +// "quicksight:CreateThemeAlias" "quicksight:DeleteThemeAlias" "quicksight:UpdateThemeAlias" +// "quicksight:UpdateThemePermissions" "quicksight:DescribeThemePermissions" +// +// * To specify no permissions, omit the permissions list. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon QuickSight's +// API operation UpdateThemePermissions for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * UnsupportedUserEditionException +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +// +// * InternalFailureException +// An internal failure occurred. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateThemePermissions +func (c *QuickSight) UpdateThemePermissions(input *UpdateThemePermissionsInput) (*UpdateThemePermissionsOutput, error) { + req, out := c.UpdateThemePermissionsRequest(input) + return out, req.Send() +} + +// UpdateThemePermissionsWithContext is the same as UpdateThemePermissions with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateThemePermissions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *QuickSight) UpdateThemePermissionsWithContext(ctx aws.Context, input *UpdateThemePermissionsInput, opts ...request.Option) (*UpdateThemePermissionsOutput, error) { + req, out := c.UpdateThemePermissionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateUser = "UpdateUser" + +// UpdateUserRequest generates a "aws/request.Request" representing the +// client's request for the UpdateUser operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateUser for more information on using the UpdateUser +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateUserRequest method. +// req, resp := client.UpdateUserRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateUser +func (c *QuickSight) UpdateUserRequest(input *UpdateUserInput) (req *request.Request, output *UpdateUserOutput) { + op := &request.Operation{ + Name: opUpdateUser, + HTTPMethod: "PUT", + HTTPPath: "/accounts/{AwsAccountId}/namespaces/{Namespace}/users/{UserName}", + } + + if input == nil { + input = &UpdateUserInput{} + } + + output = &UpdateUserOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateUser API operation for Amazon QuickSight. +// +// Updates an Amazon QuickSight user. +// +// Returns awserr.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 QuickSight's +// API operation UpdateUser for usage and error information. +// +// Returned Error Types: +// * AccessDeniedException +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +// +// * InvalidParameterValueException +// One or more parameters has a value that isn't valid. +// +// * ResourceNotFoundException +// One or more resources can't be found. +// +// * ThrottlingException +// Access is throttled. +// +// * PreconditionNotMetException +// One or more preconditions aren't met. +// +// * InternalFailureException +// An internal failure occurred. +// +// * ResourceUnavailableException +// This resource is currently unavailable. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/UpdateUser +func (c *QuickSight) UpdateUser(input *UpdateUserInput) (*UpdateUserOutput, error) { + req, out := c.UpdateUserRequest(input) + 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 *QuickSight) 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() +} + +// You don't have access to this item. The provided credentials couldn't be +// validated. You might not be authorized to carry out the request. Make sure +// that your account is authorized to use the Amazon QuickSight service, that +// your policies have the correct permissions, and that you are using the correct +// access keys. +type AccessDeniedException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + // The AWS request ID for this request. + RequestId *string `type:"string"` +} + +// String returns the string representation +func (s AccessDeniedException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccessDeniedException) GoString() string { + return s.String() +} + +func newErrorAccessDeniedException(v protocol.ResponseMetadata) error { + return &AccessDeniedException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *AccessDeniedException) Code() string { + return "AccessDeniedException" +} + +// Message returns the exception's message. +func (s *AccessDeniedException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *AccessDeniedException) OrigErr() error { + return nil +} + +func (s *AccessDeniedException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *AccessDeniedException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *AccessDeniedException) RequestID() string { + return s.RespMetadata.RequestID +} + +// The customizations associated with your AWS account for QuickSight. +type AccountCustomization struct { + _ struct{} `type:"structure"` + + // The default theme for this QuickSight subscription. + DefaultTheme *string `type:"string"` +} + +// String returns the string representation +func (s AccountCustomization) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AccountCustomization) GoString() string { + return s.String() +} + +// SetDefaultTheme sets the DefaultTheme field's value. +func (s *AccountCustomization) SetDefaultTheme(v string) *AccountCustomization { + s.DefaultTheme = &v + return s +} + +// The QuickSight settings associated with your AWS account. +type AccountSettings struct { + _ struct{} `type:"structure"` + + // The name associated with the QuickSight subscription in your AWS account. + AccountName *string `type:"string"` + + // The default QuickSight namespace for your AWS account. + DefaultNamespace *string `type:"string"` + + // The edition of QuickSight that you're currently subscribed to. + Edition *string `type:"string" enum:"Edition"` + + // The main notification email for your QuickSight subscription. + NotificationEmail *string `type:"string"` +} + +// 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() +} + +// SetAccountName sets the AccountName field's value. +func (s *AccountSettings) SetAccountName(v string) *AccountSettings { + s.AccountName = &v + return s +} + +// SetDefaultNamespace sets the DefaultNamespace field's value. +func (s *AccountSettings) SetDefaultNamespace(v string) *AccountSettings { + s.DefaultNamespace = &v + return s +} + +// SetEdition sets the Edition field's value. +func (s *AccountSettings) SetEdition(v string) *AccountSettings { + s.Edition = &v + return s +} + +// SetNotificationEmail sets the NotificationEmail field's value. +func (s *AccountSettings) SetNotificationEmail(v string) *AccountSettings { + s.NotificationEmail = &v + return s +} + +// The active AWS Identity and Access Management (IAM) policy assignment. +type ActiveIAMPolicyAssignment struct { + _ struct{} `type:"structure"` + + // A name for the IAM policy assignment. + AssignmentName *string `min:"1" type:"string"` + + // The Amazon Resource Name (ARN) of the resource. + PolicyArn *string `type:"string"` +} + +// String returns the string representation +func (s ActiveIAMPolicyAssignment) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ActiveIAMPolicyAssignment) GoString() string { + return s.String() +} + +// SetAssignmentName sets the AssignmentName field's value. +func (s *ActiveIAMPolicyAssignment) SetAssignmentName(v string) *ActiveIAMPolicyAssignment { + s.AssignmentName = &v + return s +} + +// SetPolicyArn sets the PolicyArn field's value. +func (s *ActiveIAMPolicyAssignment) SetPolicyArn(v string) *ActiveIAMPolicyAssignment { + s.PolicyArn = &v + return s +} + +// Ad hoc (one-time) filtering option. +type AdHocFilteringOption struct { + _ struct{} `type:"structure"` + + // Availability status. + AvailabilityStatus *string `type:"string" enum:"DashboardBehavior"` +} + +// String returns the string representation +func (s AdHocFilteringOption) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AdHocFilteringOption) GoString() string { + return s.String() +} + +// SetAvailabilityStatus sets the AvailabilityStatus field's value. +func (s *AdHocFilteringOption) SetAvailabilityStatus(v string) *AdHocFilteringOption { + s.AvailabilityStatus = &v + return s +} + +// Amazon Elasticsearch Service parameters. +type AmazonElasticsearchParameters struct { + _ struct{} `type:"structure"` + + // The Amazon Elasticsearch Service domain. + // + // Domain is a required field + Domain *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s AmazonElasticsearchParameters) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AmazonElasticsearchParameters) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AmazonElasticsearchParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AmazonElasticsearchParameters"} + if s.Domain == nil { + invalidParams.Add(request.NewErrParamRequired("Domain")) + } + if s.Domain != nil && len(*s.Domain) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Domain", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDomain sets the Domain field's value. +func (s *AmazonElasticsearchParameters) SetDomain(v string) *AmazonElasticsearchParameters { + s.Domain = &v + return s +} + +// Amazon Athena parameters. +type AthenaParameters struct { + _ struct{} `type:"structure"` + + // The workgroup that Amazon Athena uses. + WorkGroup *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s AthenaParameters) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AthenaParameters) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AthenaParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AthenaParameters"} + if s.WorkGroup != nil && len(*s.WorkGroup) < 1 { + invalidParams.Add(request.NewErrParamMinLen("WorkGroup", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetWorkGroup sets the WorkGroup field's value. +func (s *AthenaParameters) SetWorkGroup(v string) *AthenaParameters { + s.WorkGroup = &v + return s +} + +// Amazon Aurora parameters. +type AuroraParameters struct { + _ struct{} `type:"structure"` + + // Database. + // + // Database is a required field + Database *string `min:"1" type:"string" required:"true"` + + // Host. + // + // Host is a required field + Host *string `min:"1" type:"string" required:"true"` + + // Port. + // + // Port is a required field + Port *int64 `min:"1" type:"integer" required:"true"` +} + +// String returns the string representation +func (s AuroraParameters) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AuroraParameters) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AuroraParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AuroraParameters"} + if s.Database == nil { + invalidParams.Add(request.NewErrParamRequired("Database")) + } + if s.Database != nil && len(*s.Database) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Database", 1)) + } + if s.Host == nil { + invalidParams.Add(request.NewErrParamRequired("Host")) + } + if s.Host != nil && len(*s.Host) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Host", 1)) + } + if s.Port == nil { + invalidParams.Add(request.NewErrParamRequired("Port")) + } + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDatabase sets the Database field's value. +func (s *AuroraParameters) SetDatabase(v string) *AuroraParameters { + s.Database = &v + return s +} + +// SetHost sets the Host field's value. +func (s *AuroraParameters) SetHost(v string) *AuroraParameters { + s.Host = &v + return s +} + +// SetPort sets the Port field's value. +func (s *AuroraParameters) SetPort(v int64) *AuroraParameters { + s.Port = &v + return s +} + +// Amazon Aurora with PostgreSQL compatibility parameters. +type AuroraPostgreSqlParameters struct { + _ struct{} `type:"structure"` + + // Database. + // + // Database is a required field + Database *string `min:"1" type:"string" required:"true"` + + // Host. + // + // Host is a required field + Host *string `min:"1" type:"string" required:"true"` + + // Port. + // + // Port is a required field + Port *int64 `min:"1" type:"integer" required:"true"` +} + +// String returns the string representation +func (s AuroraPostgreSqlParameters) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AuroraPostgreSqlParameters) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AuroraPostgreSqlParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AuroraPostgreSqlParameters"} + if s.Database == nil { + invalidParams.Add(request.NewErrParamRequired("Database")) + } + if s.Database != nil && len(*s.Database) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Database", 1)) + } + if s.Host == nil { + invalidParams.Add(request.NewErrParamRequired("Host")) + } + if s.Host != nil && len(*s.Host) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Host", 1)) + } + if s.Port == nil { + invalidParams.Add(request.NewErrParamRequired("Port")) + } + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDatabase sets the Database field's value. +func (s *AuroraPostgreSqlParameters) SetDatabase(v string) *AuroraPostgreSqlParameters { + s.Database = &v + return s +} + +// SetHost sets the Host field's value. +func (s *AuroraPostgreSqlParameters) SetHost(v string) *AuroraPostgreSqlParameters { + s.Host = &v + return s +} + +// SetPort sets the Port field's value. +func (s *AuroraPostgreSqlParameters) SetPort(v int64) *AuroraPostgreSqlParameters { + s.Port = &v + return s +} + +// AWS IoT Analytics parameters. +type AwsIotAnalyticsParameters struct { + _ struct{} `type:"structure"` + + // Dataset name. + // + // DataSetName is a required field + DataSetName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s AwsIotAnalyticsParameters) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsIotAnalyticsParameters) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AwsIotAnalyticsParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AwsIotAnalyticsParameters"} + if s.DataSetName == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetName")) + } + if s.DataSetName != nil && len(*s.DataSetName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDataSetName sets the DataSetName field's value. +func (s *AwsIotAnalyticsParameters) SetDataSetName(v string) *AwsIotAnalyticsParameters { + s.DataSetName = &v + return s +} + +// The display options for tile borders for visuals. +type BorderStyle struct { + _ struct{} `type:"structure"` + + // The option to enable display of borders for visuals. + Show *bool `type:"boolean"` +} + +// String returns the string representation +func (s BorderStyle) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s BorderStyle) GoString() string { + return s.String() +} + +// SetShow sets the Show field's value. +func (s *BorderStyle) SetShow(v bool) *BorderStyle { + s.Show = &v + return s +} + +// A calculated column for a dataset. +type CalculatedColumn struct { + _ struct{} `type:"structure"` + + // A unique ID to identify a calculated column. During a dataset update, if + // the column ID of a calculated column matches that of an existing calculated + // column, Amazon QuickSight preserves the existing calculated column. + // + // ColumnId is a required field + ColumnId *string `min:"1" type:"string" required:"true"` + + // Column name. + // + // ColumnName is a required field + ColumnName *string `min:"1" type:"string" required:"true"` + + // An expression that defines the calculated column. + // + // Expression is a required field + Expression *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CalculatedColumn) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CalculatedColumn) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CalculatedColumn) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CalculatedColumn"} + if s.ColumnId == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnId")) + } + if s.ColumnId != nil && len(*s.ColumnId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ColumnId", 1)) + } + if s.ColumnName == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnName")) + } + if s.ColumnName != nil && len(*s.ColumnName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ColumnName", 1)) + } + if s.Expression == nil { + invalidParams.Add(request.NewErrParamRequired("Expression")) + } + if s.Expression != nil && len(*s.Expression) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Expression", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetColumnId sets the ColumnId field's value. +func (s *CalculatedColumn) SetColumnId(v string) *CalculatedColumn { + s.ColumnId = &v + return s +} + +// SetColumnName sets the ColumnName field's value. +func (s *CalculatedColumn) SetColumnName(v string) *CalculatedColumn { + s.ColumnName = &v + return s +} + +// SetExpression sets the Expression field's value. +func (s *CalculatedColumn) SetExpression(v string) *CalculatedColumn { + s.Expression = &v + return s +} + +type CancelIngestionInput struct { + _ struct{} `type:"structure"` + + // The AWS account ID. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The ID of the dataset used in the ingestion. + // + // DataSetId is a required field + DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` + + // An ID for the ingestion. + // + // IngestionId is a required field + IngestionId *string `location:"uri" locationName:"IngestionId" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CancelIngestionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CancelIngestionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CancelIngestionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CancelIngestionInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DataSetId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetId")) + } + if s.DataSetId != nil && len(*s.DataSetId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) + } + if s.IngestionId == nil { + invalidParams.Add(request.NewErrParamRequired("IngestionId")) + } + if s.IngestionId != nil && len(*s.IngestionId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IngestionId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CancelIngestionInput) SetAwsAccountId(v string) *CancelIngestionInput { + s.AwsAccountId = &v + return s +} + +// SetDataSetId sets the DataSetId field's value. +func (s *CancelIngestionInput) SetDataSetId(v string) *CancelIngestionInput { + s.DataSetId = &v + return s +} + +// SetIngestionId sets the IngestionId field's value. +func (s *CancelIngestionInput) SetIngestionId(v string) *CancelIngestionInput { + s.IngestionId = &v + return s +} + +type CancelIngestionOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) for the data ingestion. + Arn *string `type:"string"` + + // An ID for the ingestion. + IngestionId *string `min:"1" type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} + +// String returns the string representation +func (s CancelIngestionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CancelIngestionOutput) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *CancelIngestionOutput) SetArn(v string) *CancelIngestionOutput { + s.Arn = &v + return s +} + +// SetIngestionId sets the IngestionId field's value. +func (s *CancelIngestionOutput) SetIngestionId(v string) *CancelIngestionOutput { + s.IngestionId = &v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CancelIngestionOutput) SetRequestId(v string) *CancelIngestionOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CancelIngestionOutput) SetStatus(v int64) *CancelIngestionOutput { + s.Status = &v + return s +} + +// A transform operation that casts a column to a different type. +type CastColumnTypeOperation struct { + _ struct{} `type:"structure"` + + // Column name. + // + // ColumnName is a required field + ColumnName *string `min:"1" type:"string" required:"true"` + + // When casting a column from string to datetime type, you can supply a string + // in a format supported by Amazon QuickSight to denote the source data format. + Format *string `type:"string"` + + // New column data type. + // + // NewColumnType is a required field + NewColumnType *string `type:"string" required:"true" enum:"ColumnDataType"` +} + +// String returns the string representation +func (s CastColumnTypeOperation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CastColumnTypeOperation) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CastColumnTypeOperation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CastColumnTypeOperation"} + if s.ColumnName == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnName")) + } + if s.ColumnName != nil && len(*s.ColumnName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ColumnName", 1)) + } + if s.NewColumnType == nil { + invalidParams.Add(request.NewErrParamRequired("NewColumnType")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetColumnName sets the ColumnName field's value. +func (s *CastColumnTypeOperation) SetColumnName(v string) *CastColumnTypeOperation { + s.ColumnName = &v + return s +} + +// SetFormat sets the Format field's value. +func (s *CastColumnTypeOperation) SetFormat(v string) *CastColumnTypeOperation { + s.Format = &v + return s +} + +// SetNewColumnType sets the NewColumnType field's value. +func (s *CastColumnTypeOperation) SetNewColumnType(v string) *CastColumnTypeOperation { + s.NewColumnType = &v + return s +} + +// Groupings of columns that work together in certain Amazon QuickSight features. +// This is a variant type structure. For this structure to be valid, only one +// of the attributes can be non-null. +type ColumnGroup struct { + _ struct{} `type:"structure"` + + // Geospatial column group that denotes a hierarchy. + GeoSpatialColumnGroup *GeoSpatialColumnGroup `type:"structure"` +} + +// String returns the string representation +func (s ColumnGroup) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ColumnGroup) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ColumnGroup) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ColumnGroup"} + if s.GeoSpatialColumnGroup != nil { + if err := s.GeoSpatialColumnGroup.Validate(); err != nil { + invalidParams.AddNested("GeoSpatialColumnGroup", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGeoSpatialColumnGroup sets the GeoSpatialColumnGroup field's value. +func (s *ColumnGroup) SetGeoSpatialColumnGroup(v *GeoSpatialColumnGroup) *ColumnGroup { + s.GeoSpatialColumnGroup = v + return s +} + +// A structure describing the name, data type, and geographic role of the columns. +type ColumnGroupColumnSchema struct { + _ struct{} `type:"structure"` + + // The name of the column group's column schema. + Name *string `type:"string"` +} + +// String returns the string representation +func (s ColumnGroupColumnSchema) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ColumnGroupColumnSchema) GoString() string { + return s.String() +} + +// SetName sets the Name field's value. +func (s *ColumnGroupColumnSchema) SetName(v string) *ColumnGroupColumnSchema { + s.Name = &v + return s +} + +// The column group schema. +type ColumnGroupSchema struct { + _ struct{} `type:"structure"` + + // A structure containing the list of schemas for column group columns. + ColumnGroupColumnSchemaList []*ColumnGroupColumnSchema `type:"list"` + + // The name of the column group schema. + Name *string `type:"string"` +} + +// String returns the string representation +func (s ColumnGroupSchema) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ColumnGroupSchema) GoString() string { + return s.String() +} + +// SetColumnGroupColumnSchemaList sets the ColumnGroupColumnSchemaList field's value. +func (s *ColumnGroupSchema) SetColumnGroupColumnSchemaList(v []*ColumnGroupColumnSchema) *ColumnGroupSchema { + s.ColumnGroupColumnSchemaList = v + return s +} + +// SetName sets the Name field's value. +func (s *ColumnGroupSchema) SetName(v string) *ColumnGroupSchema { + s.Name = &v + return s +} + +// The column schema. +type ColumnSchema struct { + _ struct{} `type:"structure"` + + // The data type of the column schema. + DataType *string `type:"string"` + + // The geographic role of the column schema. + GeographicRole *string `type:"string"` + + // The name of the column schema. + Name *string `type:"string"` +} + +// String returns the string representation +func (s ColumnSchema) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ColumnSchema) GoString() string { + return s.String() +} + +// SetDataType sets the DataType field's value. +func (s *ColumnSchema) SetDataType(v string) *ColumnSchema { + s.DataType = &v + return s +} + +// SetGeographicRole sets the GeographicRole field's value. +func (s *ColumnSchema) SetGeographicRole(v string) *ColumnSchema { + s.GeographicRole = &v + return s +} + +// SetName sets the Name field's value. +func (s *ColumnSchema) SetName(v string) *ColumnSchema { + s.Name = &v + return s +} + +// A tag for a column in a TagColumnOperation structure. This is a variant type +// structure. For this structure to be valid, only one of the attributes can +// be non-null. +type ColumnTag struct { + _ struct{} `type:"structure"` + + // A geospatial role for a column. + ColumnGeographicRole *string `type:"string" enum:"GeoSpatialDataRole"` +} + +// String returns the string representation +func (s ColumnTag) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ColumnTag) GoString() string { + return s.String() +} + +// SetColumnGeographicRole sets the ColumnGeographicRole field's value. +func (s *ColumnTag) SetColumnGeographicRole(v string) *ColumnTag { + s.ColumnGeographicRole = &v + return s +} + +// A resource is already in a state that indicates an action is happening that +// must complete before a new update can be applied. +type ConcurrentUpdatingException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + RequestId *string `type:"string"` +} + +// String returns the string representation +func (s ConcurrentUpdatingException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ConcurrentUpdatingException) GoString() string { + return s.String() +} + +func newErrorConcurrentUpdatingException(v protocol.ResponseMetadata) error { + return &ConcurrentUpdatingException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ConcurrentUpdatingException) Code() string { + return "ConcurrentUpdatingException" +} + +// Message returns the exception's message. +func (s *ConcurrentUpdatingException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ConcurrentUpdatingException) OrigErr() error { + return nil +} + +func (s *ConcurrentUpdatingException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ConcurrentUpdatingException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ConcurrentUpdatingException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Updating or deleting a resource can cause an inconsistent state. +type ConflictException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + // The AWS request ID for this request. + RequestId *string `type:"string"` +} + +// String returns the string representation +func (s ConflictException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ConflictException) GoString() string { + return s.String() +} + +func newErrorConflictException(v protocol.ResponseMetadata) error { + return &ConflictException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ConflictException) Code() string { + return "ConflictException" +} + +// Message returns the exception's message. +func (s *ConflictException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ConflictException) OrigErr() error { + return nil +} + +func (s *ConflictException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ConflictException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ConflictException) RequestID() string { + return s.RespMetadata.RequestID +} + +type CreateAccountCustomizationInput struct { + _ struct{} `type:"structure"` + + // The customizations you're adding to the QuickSight subscription for the AWS + // account. For example, you could add a default theme by setting AccountCustomization + // to the midnight theme (DefaultTheme="arn:aws:quicksight::aws:theme/MIDNIGHT") + // or to a custom theme (DefaultTheme="arn:aws:quicksight:us-west-2:111122223333:theme/bdb844d0-0fe9-4d9d-b520-0fe602d93639"). + // + // AccountCustomization is a required field + AccountCustomization *AccountCustomization `type:"structure" required:"true"` + + // The ID for the AWS account that you want to customize QuickSight for. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The namespace associated with the customization that you're creating. + Namespace *string `location:"querystring" locationName:"namespace" type:"string"` +} + +// String returns the string representation +func (s CreateAccountCustomizationInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateAccountCustomizationInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateAccountCustomizationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateAccountCustomizationInput"} + if s.AccountCustomization == nil { + invalidParams.Add(request.NewErrParamRequired("AccountCustomization")) + } + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAccountCustomization sets the AccountCustomization field's value. +func (s *CreateAccountCustomizationInput) SetAccountCustomization(v *AccountCustomization) *CreateAccountCustomizationInput { + s.AccountCustomization = v + return s +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateAccountCustomizationInput) SetAwsAccountId(v string) *CreateAccountCustomizationInput { + s.AwsAccountId = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *CreateAccountCustomizationInput) SetNamespace(v string) *CreateAccountCustomizationInput { + s.Namespace = &v + return s +} + +type CreateAccountCustomizationOutput struct { + _ struct{} `type:"structure"` + + // The customizations you're adding to the QuickSight subscription for the AWS + // account. + AccountCustomization *AccountCustomization `type:"structure"` + + // The ID for the AWS account that you want to customize QuickSight for. + AwsAccountId *string `min:"12" type:"string"` + + // The namespace associated with the customization you're creating. + Namespace *string `type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} + +// String returns the string representation +func (s CreateAccountCustomizationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateAccountCustomizationOutput) GoString() string { + return s.String() +} + +// SetAccountCustomization sets the AccountCustomization field's value. +func (s *CreateAccountCustomizationOutput) SetAccountCustomization(v *AccountCustomization) *CreateAccountCustomizationOutput { + s.AccountCustomization = v + return s +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateAccountCustomizationOutput) SetAwsAccountId(v string) *CreateAccountCustomizationOutput { + s.AwsAccountId = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *CreateAccountCustomizationOutput) SetNamespace(v string) *CreateAccountCustomizationOutput { + s.Namespace = &v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateAccountCustomizationOutput) SetRequestId(v string) *CreateAccountCustomizationOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateAccountCustomizationOutput) SetStatus(v int64) *CreateAccountCustomizationOutput { + s.Status = &v + return s +} + +// A transform operation that creates calculated columns. Columns created in +// one such operation form a lexical closure. +type CreateColumnsOperation struct { + _ struct{} `type:"structure"` + + // Calculated columns to create. + // + // Columns is a required field + Columns []*CalculatedColumn `min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s CreateColumnsOperation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateColumnsOperation) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateColumnsOperation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateColumnsOperation"} + if s.Columns == nil { + invalidParams.Add(request.NewErrParamRequired("Columns")) + } + if s.Columns != nil && len(s.Columns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Columns", 1)) + } + if s.Columns != nil { + for i, v := range s.Columns { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Columns", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetColumns sets the Columns field's value. +func (s *CreateColumnsOperation) SetColumns(v []*CalculatedColumn) *CreateColumnsOperation { + s.Columns = v + return s +} + +type CreateDashboardInput struct { + _ struct{} `type:"structure"` + + // The ID of the AWS account where you want to create the dashboard. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The ID for the dashboard, also added to the IAM policy. + // + // DashboardId is a required field + DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` + + // Options for publishing the dashboard when you create it: + // + // * AvailabilityStatus for AdHocFilteringOption - This status can be either + // ENABLED or DISABLED. When this is set to DISABLED, QuickSight disables + // the left filter pane on the published dashboard, which can be used for + // ad hoc (one-time) filtering. This option is ENABLED by default. + // + // * AvailabilityStatus for ExportToCSVOption - This status can be either + // ENABLED or DISABLED. The visual option to export data to .csv format isn't + // enabled when this is set to DISABLED. This option is ENABLED by default. + // + // * VisibilityState for SheetControlsOption - This visibility state can + // be either COLLAPSED or EXPANDED. This option is COLLAPSED by default. + DashboardPublishOptions *DashboardPublishOptions `type:"structure"` + + // The display name of the dashboard. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // The parameters for the creation of the dashboard, which you want to use to + // override the default settings. A dashboard can have any type of parameters, + // and some parameters might accept multiple values. + Parameters *Parameters `type:"structure"` + + // A structure that contains the permissions of the dashboard. You can use this + // structure for granting permissions with principal and action information. + Permissions []*ResourcePermission `min:"1" type:"list"` + + // The entity that you are using as a source when you create the dashboard. + // In SourceEntity, you specify the type of object you're using as source. You + // can only create a dashboard from a template, so you use a SourceTemplate + // entity. If you need to create a dashboard from an analysis, first convert + // the analysis to a template by using the CreateTemplate API operation. For + // SourceTemplate, specify the Amazon Resource Name (ARN) of the source template. + // The SourceTemplateARN can contain any AWS Account and any QuickSight-supported + // AWS Region. + // + // Use the DataSetReferences entity within SourceTemplate to list the replacement + // datasets for the placeholders listed in the original. The schema in each + // dataset must match its placeholder. + // + // SourceEntity is a required field + SourceEntity *DashboardSourceEntity `type:"structure" required:"true"` + + // Contains a map of the key-value pairs for the resource tag or tags assigned + // to the dashboard. + Tags []*Tag `min:"1" type:"list"` + + // The Amazon Resource Name (ARN) of the theme that is being used for this dashboard. + // If you add a value for this field, it overrides the value that is used in + // the source entity. The theme ARN must exist in the same AWS account where + // you create the dashboard. + ThemeArn *string `type:"string"` + + // A description for the first version of the dashboard being created. + VersionDescription *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s CreateDashboardInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDashboardInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateDashboardInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDashboardInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DashboardId == nil { + invalidParams.Add(request.NewErrParamRequired("DashboardId")) + } + if s.DashboardId != nil && len(*s.DashboardId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.Permissions != nil && len(s.Permissions) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Permissions", 1)) + } + if s.SourceEntity == nil { + invalidParams.Add(request.NewErrParamRequired("SourceEntity")) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + } + if s.VersionDescription != nil && len(*s.VersionDescription) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VersionDescription", 1)) + } + if s.Parameters != nil { + if err := s.Parameters.Validate(); err != nil { + invalidParams.AddNested("Parameters", err.(request.ErrInvalidParams)) + } + } + if s.Permissions != nil { + for i, v := range s.Permissions { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Permissions", i), err.(request.ErrInvalidParams)) + } + } + } + if s.SourceEntity != nil { + if err := s.SourceEntity.Validate(); err != nil { + invalidParams.AddNested("SourceEntity", err.(request.ErrInvalidParams)) + } + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateDashboardInput) SetAwsAccountId(v string) *CreateDashboardInput { + s.AwsAccountId = &v + return s +} + +// SetDashboardId sets the DashboardId field's value. +func (s *CreateDashboardInput) SetDashboardId(v string) *CreateDashboardInput { + s.DashboardId = &v + return s +} + +// SetDashboardPublishOptions sets the DashboardPublishOptions field's value. +func (s *CreateDashboardInput) SetDashboardPublishOptions(v *DashboardPublishOptions) *CreateDashboardInput { + s.DashboardPublishOptions = v + return s +} + +// SetName sets the Name field's value. +func (s *CreateDashboardInput) SetName(v string) *CreateDashboardInput { + s.Name = &v + return s +} + +// SetParameters sets the Parameters field's value. +func (s *CreateDashboardInput) SetParameters(v *Parameters) *CreateDashboardInput { + s.Parameters = v + return s +} + +// SetPermissions sets the Permissions field's value. +func (s *CreateDashboardInput) SetPermissions(v []*ResourcePermission) *CreateDashboardInput { + s.Permissions = v + return s +} + +// SetSourceEntity sets the SourceEntity field's value. +func (s *CreateDashboardInput) SetSourceEntity(v *DashboardSourceEntity) *CreateDashboardInput { + s.SourceEntity = v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateDashboardInput) SetTags(v []*Tag) *CreateDashboardInput { + s.Tags = v + return s +} + +// SetThemeArn sets the ThemeArn field's value. +func (s *CreateDashboardInput) SetThemeArn(v string) *CreateDashboardInput { + s.ThemeArn = &v + return s +} + +// SetVersionDescription sets the VersionDescription field's value. +func (s *CreateDashboardInput) SetVersionDescription(v string) *CreateDashboardInput { + s.VersionDescription = &v + return s +} + +type CreateDashboardOutput struct { + _ struct{} `type:"structure"` + + // The ARN of the dashboard. + Arn *string `type:"string"` + + // The status of the dashboard creation request. + CreationStatus *string `type:"string" enum:"ResourceStatus"` + + // The ID for the dashboard. + DashboardId *string `min:"1" type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` + + // The ARN of the dashboard, including the version number of the first version + // that is created. + VersionArn *string `type:"string"` +} + +// String returns the string representation +func (s CreateDashboardOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDashboardOutput) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *CreateDashboardOutput) SetArn(v string) *CreateDashboardOutput { + s.Arn = &v + return s +} + +// SetCreationStatus sets the CreationStatus field's value. +func (s *CreateDashboardOutput) SetCreationStatus(v string) *CreateDashboardOutput { + s.CreationStatus = &v + return s +} + +// SetDashboardId sets the DashboardId field's value. +func (s *CreateDashboardOutput) SetDashboardId(v string) *CreateDashboardOutput { + s.DashboardId = &v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateDashboardOutput) SetRequestId(v string) *CreateDashboardOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateDashboardOutput) SetStatus(v int64) *CreateDashboardOutput { + s.Status = &v + return s +} + +// SetVersionArn sets the VersionArn field's value. +func (s *CreateDashboardOutput) SetVersionArn(v string) *CreateDashboardOutput { + s.VersionArn = &v + return s +} + +type CreateDataSetInput struct { + _ struct{} `type:"structure"` + + // The AWS account ID. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // Groupings of columns that work together in certain QuickSight features. Currently, + // only geospatial hierarchy is supported. + ColumnGroups []*ColumnGroup `min:"1" type:"list"` + + // An ID for the dataset that you want to create. This ID is unique per AWS + // Region for each AWS account. + // + // DataSetId is a required field + DataSetId *string `type:"string" required:"true"` + + // Indicates whether you want to import the data into SPICE. + // + // ImportMode is a required field + ImportMode *string `type:"string" required:"true" enum:"DataSetImportMode"` + + // Configures the combination and transformation of the data from the physical + // tables. + LogicalTableMap map[string]*LogicalTable `min:"1" type:"map"` + + // The display name for the dataset. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // A list of resource permissions on the dataset. + Permissions []*ResourcePermission `min:"1" type:"list"` + + // Declares the physical tables that are available in the underlying data sources. + // + // PhysicalTableMap is a required field + PhysicalTableMap map[string]*PhysicalTable `min:"1" type:"map" required:"true"` + + // The row-level security configuration for the data that you want to create. + RowLevelPermissionDataSet *RowLevelPermissionDataSet `type:"structure"` + + // Contains a map of the key-value pairs for the resource tag or tags assigned + // to the dataset. + Tags []*Tag `min:"1" type:"list"` +} + +// String returns the string representation +func (s CreateDataSetInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDataSetInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateDataSetInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDataSetInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.ColumnGroups != nil && len(s.ColumnGroups) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ColumnGroups", 1)) + } + if s.DataSetId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetId")) + } + if s.ImportMode == nil { + invalidParams.Add(request.NewErrParamRequired("ImportMode")) + } + if s.LogicalTableMap != nil && len(s.LogicalTableMap) < 1 { + invalidParams.Add(request.NewErrParamMinLen("LogicalTableMap", 1)) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.Permissions != nil && len(s.Permissions) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Permissions", 1)) + } + if s.PhysicalTableMap == nil { + invalidParams.Add(request.NewErrParamRequired("PhysicalTableMap")) + } + if s.PhysicalTableMap != nil && len(s.PhysicalTableMap) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PhysicalTableMap", 1)) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + } + if s.ColumnGroups != nil { + for i, v := range s.ColumnGroups { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ColumnGroups", i), err.(request.ErrInvalidParams)) + } + } + } + if s.LogicalTableMap != nil { + for i, v := range s.LogicalTableMap { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LogicalTableMap", i), err.(request.ErrInvalidParams)) + } + } + } + if s.Permissions != nil { + for i, v := range s.Permissions { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Permissions", i), err.(request.ErrInvalidParams)) + } + } + } + if s.PhysicalTableMap != nil { + for i, v := range s.PhysicalTableMap { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "PhysicalTableMap", i), err.(request.ErrInvalidParams)) + } + } + } + if s.RowLevelPermissionDataSet != nil { + if err := s.RowLevelPermissionDataSet.Validate(); err != nil { + invalidParams.AddNested("RowLevelPermissionDataSet", err.(request.ErrInvalidParams)) + } + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateDataSetInput) SetAwsAccountId(v string) *CreateDataSetInput { + s.AwsAccountId = &v + return s +} + +// SetColumnGroups sets the ColumnGroups field's value. +func (s *CreateDataSetInput) SetColumnGroups(v []*ColumnGroup) *CreateDataSetInput { + s.ColumnGroups = v + return s +} + +// SetDataSetId sets the DataSetId field's value. +func (s *CreateDataSetInput) SetDataSetId(v string) *CreateDataSetInput { + s.DataSetId = &v + return s +} + +// SetImportMode sets the ImportMode field's value. +func (s *CreateDataSetInput) SetImportMode(v string) *CreateDataSetInput { + s.ImportMode = &v + return s +} + +// SetLogicalTableMap sets the LogicalTableMap field's value. +func (s *CreateDataSetInput) SetLogicalTableMap(v map[string]*LogicalTable) *CreateDataSetInput { + s.LogicalTableMap = v + return s +} + +// SetName sets the Name field's value. +func (s *CreateDataSetInput) SetName(v string) *CreateDataSetInput { + s.Name = &v + return s +} + +// SetPermissions sets the Permissions field's value. +func (s *CreateDataSetInput) SetPermissions(v []*ResourcePermission) *CreateDataSetInput { + s.Permissions = v + return s +} + +// SetPhysicalTableMap sets the PhysicalTableMap field's value. +func (s *CreateDataSetInput) SetPhysicalTableMap(v map[string]*PhysicalTable) *CreateDataSetInput { + s.PhysicalTableMap = v + return s +} + +// SetRowLevelPermissionDataSet sets the RowLevelPermissionDataSet field's value. +func (s *CreateDataSetInput) SetRowLevelPermissionDataSet(v *RowLevelPermissionDataSet) *CreateDataSetInput { + s.RowLevelPermissionDataSet = v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateDataSetInput) SetTags(v []*Tag) *CreateDataSetInput { + s.Tags = v + return s +} + +type CreateDataSetOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the dataset. + Arn *string `type:"string"` + + // The ID for the dataset that you want to create. This ID is unique per AWS + // Region for each AWS account. + DataSetId *string `type:"string"` + + // The ARN for the ingestion, which is triggered as a result of dataset creation + // if the import mode is SPICE. + IngestionArn *string `type:"string"` + + // The ID of the ingestion, which is triggered as a result of dataset creation + // if the import mode is SPICE. + IngestionId *string `type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} + +// String returns the string representation +func (s CreateDataSetOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDataSetOutput) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *CreateDataSetOutput) SetArn(v string) *CreateDataSetOutput { + s.Arn = &v + return s +} + +// SetDataSetId sets the DataSetId field's value. +func (s *CreateDataSetOutput) SetDataSetId(v string) *CreateDataSetOutput { + s.DataSetId = &v + return s +} + +// SetIngestionArn sets the IngestionArn field's value. +func (s *CreateDataSetOutput) SetIngestionArn(v string) *CreateDataSetOutput { + s.IngestionArn = &v + return s +} + +// SetIngestionId sets the IngestionId field's value. +func (s *CreateDataSetOutput) SetIngestionId(v string) *CreateDataSetOutput { + s.IngestionId = &v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateDataSetOutput) SetRequestId(v string) *CreateDataSetOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateDataSetOutput) SetStatus(v int64) *CreateDataSetOutput { + s.Status = &v + return s +} + +type CreateDataSourceInput struct { + _ struct{} `type:"structure"` + + // The AWS account ID. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The credentials QuickSight that uses to connect to your underlying source. + // Currently, only credentials based on user name and password are supported. + Credentials *DataSourceCredentials `type:"structure" sensitive:"true"` + + // An ID for the data source. This ID is unique per AWS Region for each AWS + // account. + // + // DataSourceId is a required field + DataSourceId *string `type:"string" required:"true"` + + // The parameters that QuickSight uses to connect to your underlying source. + DataSourceParameters *DataSourceParameters `type:"structure"` + + // A display name for the data source. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // A list of resource permissions on the data source. + Permissions []*ResourcePermission `min:"1" type:"list"` + + // Secure Socket Layer (SSL) properties that apply when QuickSight connects + // to your underlying source. + SslProperties *SslProperties `type:"structure"` + + // Contains a map of the key-value pairs for the resource tag or tags assigned + // to the data source. + Tags []*Tag `min:"1" type:"list"` + + // The type of the data source. Currently, the supported types for this operation + // are: ATHENA, AURORA, AURORA_POSTGRESQL, MARIADB, MYSQL, POSTGRESQL, PRESTO, + // REDSHIFT, S3, SNOWFLAKE, SPARK, SQLSERVER, TERADATA. Use ListDataSources + // to return a list of all data sources. + // + // Type is a required field + Type *string `type:"string" required:"true" enum:"DataSourceType"` + + // Use this parameter only when you want QuickSight to use a VPC connection + // when connecting to your underlying source. + VpcConnectionProperties *VpcConnectionProperties `type:"structure"` +} + +// String returns the string representation +func (s CreateDataSourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDataSourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateDataSourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateDataSourceInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DataSourceId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSourceId")) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.Permissions != nil && len(s.Permissions) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Permissions", 1)) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + } + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + if s.Credentials != nil { + if err := s.Credentials.Validate(); err != nil { + invalidParams.AddNested("Credentials", err.(request.ErrInvalidParams)) + } + } + if s.DataSourceParameters != nil { + if err := s.DataSourceParameters.Validate(); err != nil { + invalidParams.AddNested("DataSourceParameters", err.(request.ErrInvalidParams)) + } + } + if s.Permissions != nil { + for i, v := range s.Permissions { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Permissions", i), err.(request.ErrInvalidParams)) + } + } + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + if s.VpcConnectionProperties != nil { + if err := s.VpcConnectionProperties.Validate(); err != nil { + invalidParams.AddNested("VpcConnectionProperties", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateDataSourceInput) SetAwsAccountId(v string) *CreateDataSourceInput { + s.AwsAccountId = &v + return s +} + +// SetCredentials sets the Credentials field's value. +func (s *CreateDataSourceInput) SetCredentials(v *DataSourceCredentials) *CreateDataSourceInput { + s.Credentials = v + return s +} + +// SetDataSourceId sets the DataSourceId field's value. +func (s *CreateDataSourceInput) SetDataSourceId(v string) *CreateDataSourceInput { + s.DataSourceId = &v + return s +} + +// SetDataSourceParameters sets the DataSourceParameters field's value. +func (s *CreateDataSourceInput) SetDataSourceParameters(v *DataSourceParameters) *CreateDataSourceInput { + s.DataSourceParameters = v + return s +} + +// SetName sets the Name field's value. +func (s *CreateDataSourceInput) SetName(v string) *CreateDataSourceInput { + s.Name = &v + return s +} + +// SetPermissions sets the Permissions field's value. +func (s *CreateDataSourceInput) SetPermissions(v []*ResourcePermission) *CreateDataSourceInput { + s.Permissions = v + return s +} + +// SetSslProperties sets the SslProperties field's value. +func (s *CreateDataSourceInput) SetSslProperties(v *SslProperties) *CreateDataSourceInput { + s.SslProperties = v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateDataSourceInput) SetTags(v []*Tag) *CreateDataSourceInput { + s.Tags = v + return s +} + +// SetType sets the Type field's value. +func (s *CreateDataSourceInput) SetType(v string) *CreateDataSourceInput { + s.Type = &v + return s +} + +// SetVpcConnectionProperties sets the VpcConnectionProperties field's value. +func (s *CreateDataSourceInput) SetVpcConnectionProperties(v *VpcConnectionProperties) *CreateDataSourceInput { + s.VpcConnectionProperties = v + return s +} + +type CreateDataSourceOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the data source. + Arn *string `type:"string"` + + // The status of creating the data source. + CreationStatus *string `type:"string" enum:"ResourceStatus"` + + // The ID of the data source. This ID is unique per AWS Region for each AWS + // account. + DataSourceId *string `type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} + +// String returns the string representation +func (s CreateDataSourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateDataSourceOutput) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *CreateDataSourceOutput) SetArn(v string) *CreateDataSourceOutput { + s.Arn = &v + return s +} + +// SetCreationStatus sets the CreationStatus field's value. +func (s *CreateDataSourceOutput) SetCreationStatus(v string) *CreateDataSourceOutput { + s.CreationStatus = &v + return s +} + +// SetDataSourceId sets the DataSourceId field's value. +func (s *CreateDataSourceOutput) SetDataSourceId(v string) *CreateDataSourceOutput { + s.DataSourceId = &v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateDataSourceOutput) SetRequestId(v string) *CreateDataSourceOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateDataSourceOutput) SetStatus(v int64) *CreateDataSourceOutput { + s.Status = &v + return s +} + +// The request object for this operation. +type CreateGroupInput struct { + _ struct{} `type:"structure"` + + // The ID for the AWS account that the group is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // A description for the group that you want to create. + Description *string `min:"1" type:"string"` + + // A name for the group that you want to create. + // + // GroupName is a required field + GroupName *string `min:"1" type:"string" required:"true"` + + // The namespace. Currently, you should set this to default. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateGroupInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateGroupInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateGroupInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateGroupInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.Description != nil && len(*s.Description) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Description", 1)) + } + if s.GroupName == nil { + invalidParams.Add(request.NewErrParamRequired("GroupName")) + } + if s.GroupName != nil && len(*s.GroupName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateGroupInput) SetAwsAccountId(v string) *CreateGroupInput { + s.AwsAccountId = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *CreateGroupInput) SetDescription(v string) *CreateGroupInput { + s.Description = &v + return s +} + +// SetGroupName sets the GroupName field's value. +func (s *CreateGroupInput) SetGroupName(v string) *CreateGroupInput { + s.GroupName = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *CreateGroupInput) SetNamespace(v string) *CreateGroupInput { + s.Namespace = &v + return s +} + +type CreateGroupMembershipInput struct { + _ struct{} `type:"structure"` + + // The ID for the AWS account that the group is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The name of the group that you want to add the user to. + // + // GroupName is a required field + GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + + // The name of the user that you want to add to the group membership. + // + // MemberName is a required field + MemberName *string `location:"uri" locationName:"MemberName" min:"1" type:"string" required:"true"` + + // The namespace. Currently, you should set this to default. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateGroupMembershipInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateGroupMembershipInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateGroupMembershipInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateGroupMembershipInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.GroupName == nil { + invalidParams.Add(request.NewErrParamRequired("GroupName")) + } + if s.GroupName != nil && len(*s.GroupName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) + } + if s.MemberName == nil { + invalidParams.Add(request.NewErrParamRequired("MemberName")) + } + if s.MemberName != nil && len(*s.MemberName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MemberName", 1)) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateGroupMembershipInput) SetAwsAccountId(v string) *CreateGroupMembershipInput { + s.AwsAccountId = &v + return s +} + +// SetGroupName sets the GroupName field's value. +func (s *CreateGroupMembershipInput) SetGroupName(v string) *CreateGroupMembershipInput { + s.GroupName = &v + return s +} + +// SetMemberName sets the MemberName field's value. +func (s *CreateGroupMembershipInput) SetMemberName(v string) *CreateGroupMembershipInput { + s.MemberName = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *CreateGroupMembershipInput) SetNamespace(v string) *CreateGroupMembershipInput { + s.Namespace = &v + return s +} + +type CreateGroupMembershipOutput struct { + _ struct{} `type:"structure"` + + // The group member. + GroupMember *GroupMember `type:"structure"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} + +// String returns the string representation +func (s CreateGroupMembershipOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateGroupMembershipOutput) GoString() string { + return s.String() +} + +// SetGroupMember sets the GroupMember field's value. +func (s *CreateGroupMembershipOutput) SetGroupMember(v *GroupMember) *CreateGroupMembershipOutput { + s.GroupMember = v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateGroupMembershipOutput) SetRequestId(v string) *CreateGroupMembershipOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateGroupMembershipOutput) SetStatus(v int64) *CreateGroupMembershipOutput { + s.Status = &v + return s +} + +// The response object for this operation. +type CreateGroupOutput struct { + _ struct{} `type:"structure"` + + // The name of the group. + Group *Group `type:"structure"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} + +// String returns the string representation +func (s CreateGroupOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateGroupOutput) GoString() string { + return s.String() +} + +// SetGroup sets the Group field's value. +func (s *CreateGroupOutput) SetGroup(v *Group) *CreateGroupOutput { + s.Group = v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateGroupOutput) SetRequestId(v string) *CreateGroupOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateGroupOutput) SetStatus(v int64) *CreateGroupOutput { + s.Status = &v + return s +} + +type CreateIAMPolicyAssignmentInput struct { + _ struct{} `type:"structure"` + + // The name of the assignment. It must be unique within an AWS account. + // + // AssignmentName is a required field + AssignmentName *string `min:"1" type:"string" required:"true"` + + // The status of the assignment. Possible values are as follows: + // + // * ENABLED - Anything specified in this assignment is used when creating + // the data source. + // + // * DISABLED - This assignment isn't used when creating the data source. + // + // * DRAFT - This assignment is an unfinished draft and isn't used when creating + // the data source. + // + // AssignmentStatus is a required field + AssignmentStatus *string `type:"string" required:"true" enum:"AssignmentStatus"` + + // The ID of the AWS account where you want to assign an IAM policy to QuickSight + // users or groups. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The QuickSight users, groups, or both that you want to assign the policy + // to. + Identities map[string][]*string `type:"map"` + + // The namespace that contains the assignment. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + + // The ARN for the IAM policy to apply to the QuickSight users and groups specified + // in this assignment. + PolicyArn *string `type:"string"` +} + +// String returns the string representation +func (s CreateIAMPolicyAssignmentInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateIAMPolicyAssignmentInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateIAMPolicyAssignmentInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateIAMPolicyAssignmentInput"} + if s.AssignmentName == nil { + invalidParams.Add(request.NewErrParamRequired("AssignmentName")) + } + if s.AssignmentName != nil && len(*s.AssignmentName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AssignmentName", 1)) + } + if s.AssignmentStatus == nil { + invalidParams.Add(request.NewErrParamRequired("AssignmentStatus")) + } + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAssignmentName sets the AssignmentName field's value. +func (s *CreateIAMPolicyAssignmentInput) SetAssignmentName(v string) *CreateIAMPolicyAssignmentInput { + s.AssignmentName = &v + return s +} + +// SetAssignmentStatus sets the AssignmentStatus field's value. +func (s *CreateIAMPolicyAssignmentInput) SetAssignmentStatus(v string) *CreateIAMPolicyAssignmentInput { + s.AssignmentStatus = &v + return s +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateIAMPolicyAssignmentInput) SetAwsAccountId(v string) *CreateIAMPolicyAssignmentInput { + s.AwsAccountId = &v + return s +} + +// SetIdentities sets the Identities field's value. +func (s *CreateIAMPolicyAssignmentInput) SetIdentities(v map[string][]*string) *CreateIAMPolicyAssignmentInput { + s.Identities = v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *CreateIAMPolicyAssignmentInput) SetNamespace(v string) *CreateIAMPolicyAssignmentInput { + s.Namespace = &v + return s +} + +// SetPolicyArn sets the PolicyArn field's value. +func (s *CreateIAMPolicyAssignmentInput) SetPolicyArn(v string) *CreateIAMPolicyAssignmentInput { + s.PolicyArn = &v + return s +} + +type CreateIAMPolicyAssignmentOutput struct { + _ struct{} `type:"structure"` + + // The ID for the assignment. + AssignmentId *string `type:"string"` + + // The name of the assignment. This name must be unique within the AWS account. + AssignmentName *string `min:"1" type:"string"` + + // The status of the assignment. Possible values are as follows: + // + // * ENABLED - Anything specified in this assignment is used when creating + // the data source. + // + // * DISABLED - This assignment isn't used when creating the data source. + // + // * DRAFT - This assignment is an unfinished draft and isn't used when creating + // the data source. + AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` + + // The QuickSight users, groups, or both that the IAM policy is assigned to. + Identities map[string][]*string `type:"map"` + + // The ARN for the IAM policy that is applied to the QuickSight users and groups + // specified in this assignment. + PolicyArn *string `type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} + +// String returns the string representation +func (s CreateIAMPolicyAssignmentOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateIAMPolicyAssignmentOutput) GoString() string { + return s.String() +} + +// SetAssignmentId sets the AssignmentId field's value. +func (s *CreateIAMPolicyAssignmentOutput) SetAssignmentId(v string) *CreateIAMPolicyAssignmentOutput { + s.AssignmentId = &v + return s +} + +// SetAssignmentName sets the AssignmentName field's value. +func (s *CreateIAMPolicyAssignmentOutput) SetAssignmentName(v string) *CreateIAMPolicyAssignmentOutput { + s.AssignmentName = &v + return s +} + +// SetAssignmentStatus sets the AssignmentStatus field's value. +func (s *CreateIAMPolicyAssignmentOutput) SetAssignmentStatus(v string) *CreateIAMPolicyAssignmentOutput { + s.AssignmentStatus = &v + return s +} + +// SetIdentities sets the Identities field's value. +func (s *CreateIAMPolicyAssignmentOutput) SetIdentities(v map[string][]*string) *CreateIAMPolicyAssignmentOutput { + s.Identities = v + return s +} + +// SetPolicyArn sets the PolicyArn field's value. +func (s *CreateIAMPolicyAssignmentOutput) SetPolicyArn(v string) *CreateIAMPolicyAssignmentOutput { + s.PolicyArn = &v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateIAMPolicyAssignmentOutput) SetRequestId(v string) *CreateIAMPolicyAssignmentOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateIAMPolicyAssignmentOutput) SetStatus(v int64) *CreateIAMPolicyAssignmentOutput { + s.Status = &v + return s +} + +type CreateIngestionInput struct { + _ struct{} `type:"structure"` + + // The AWS account ID. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The ID of the dataset used in the ingestion. + // + // DataSetId is a required field + DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` + + // An ID for the ingestion. + // + // IngestionId is a required field + IngestionId *string `location:"uri" locationName:"IngestionId" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateIngestionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateIngestionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateIngestionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateIngestionInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DataSetId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetId")) + } + if s.DataSetId != nil && len(*s.DataSetId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) + } + if s.IngestionId == nil { + invalidParams.Add(request.NewErrParamRequired("IngestionId")) + } + if s.IngestionId != nil && len(*s.IngestionId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IngestionId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateIngestionInput) SetAwsAccountId(v string) *CreateIngestionInput { + s.AwsAccountId = &v + return s +} + +// SetDataSetId sets the DataSetId field's value. +func (s *CreateIngestionInput) SetDataSetId(v string) *CreateIngestionInput { + s.DataSetId = &v + return s +} + +// SetIngestionId sets the IngestionId field's value. +func (s *CreateIngestionInput) SetIngestionId(v string) *CreateIngestionInput { + s.IngestionId = &v + return s +} + +type CreateIngestionOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) for the data ingestion. + Arn *string `type:"string"` + + // An ID for the ingestion. + IngestionId *string `min:"1" type:"string"` + + // The ingestion status. + IngestionStatus *string `type:"string" enum:"IngestionStatus"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} + +// String returns the string representation +func (s CreateIngestionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateIngestionOutput) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *CreateIngestionOutput) SetArn(v string) *CreateIngestionOutput { + s.Arn = &v + return s +} + +// SetIngestionId sets the IngestionId field's value. +func (s *CreateIngestionOutput) SetIngestionId(v string) *CreateIngestionOutput { + s.IngestionId = &v + return s +} + +// SetIngestionStatus sets the IngestionStatus field's value. +func (s *CreateIngestionOutput) SetIngestionStatus(v string) *CreateIngestionOutput { + s.IngestionStatus = &v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateIngestionOutput) SetRequestId(v string) *CreateIngestionOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateIngestionOutput) SetStatus(v int64) *CreateIngestionOutput { + s.Status = &v + return s +} + +type CreateNamespaceInput struct { + _ struct{} `type:"structure"` + + // The ID for the AWS account that you want to create the QuickSight namespace + // in. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // Specifies the type of your user identity directory. Currently, this supports + // users with an identity type of QUICKSIGHT. + // + // IdentityStore is a required field + IdentityStore *string `type:"string" required:"true" enum:"IdentityStore"` + + // The name that you want to use to describe the new namespace. + // + // Namespace is a required field + Namespace *string `type:"string" required:"true"` + + // The tags that you want to associate with the namespace that you're creating. + Tags []*Tag `min:"1" type:"list"` +} + +// String returns the string representation +func (s CreateNamespaceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateNamespaceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateNamespaceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateNamespaceInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.IdentityStore == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityStore")) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateNamespaceInput) SetAwsAccountId(v string) *CreateNamespaceInput { + s.AwsAccountId = &v + return s +} + +// SetIdentityStore sets the IdentityStore field's value. +func (s *CreateNamespaceInput) SetIdentityStore(v string) *CreateNamespaceInput { + s.IdentityStore = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *CreateNamespaceInput) SetNamespace(v string) *CreateNamespaceInput { + s.Namespace = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateNamespaceInput) SetTags(v []*Tag) *CreateNamespaceInput { + s.Tags = v + return s +} + +type CreateNamespaceOutput struct { + _ struct{} `type:"structure"` + + // The ARN of the QuickSight namespace you created. + Arn *string `type:"string"` + + // The AWS Region that you want to use for the free SPICE capacity for the new + // namespace. This is set to the region that you run CreateNamespace in. + CapacityRegion *string `type:"string"` + + // The status of the creation of the namespace. This is an asynchronous process. + // A status of CREATED means that your namespace is ready to use. If an error + // occurs, it indicates if the process is retryable or non-retryable. In the + // case of a non-retryable error, refer to the error message for follow-up actions. + CreationStatus *string `type:"string" enum:"NamespaceStatus"` + + // Specifies the type of your user identity directory. Currently, this supports + // users with an identity type of QUICKSIGHT. + IdentityStore *string `type:"string" enum:"IdentityStore"` + + // The name of the new namespace that you created. + Name *string `type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} + +// String returns the string representation +func (s CreateNamespaceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateNamespaceOutput) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *CreateNamespaceOutput) SetArn(v string) *CreateNamespaceOutput { + s.Arn = &v + return s +} + +// SetCapacityRegion sets the CapacityRegion field's value. +func (s *CreateNamespaceOutput) SetCapacityRegion(v string) *CreateNamespaceOutput { + s.CapacityRegion = &v + return s +} + +// SetCreationStatus sets the CreationStatus field's value. +func (s *CreateNamespaceOutput) SetCreationStatus(v string) *CreateNamespaceOutput { + s.CreationStatus = &v + return s +} + +// SetIdentityStore sets the IdentityStore field's value. +func (s *CreateNamespaceOutput) SetIdentityStore(v string) *CreateNamespaceOutput { + s.IdentityStore = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateNamespaceOutput) SetName(v string) *CreateNamespaceOutput { + s.Name = &v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateNamespaceOutput) SetRequestId(v string) *CreateNamespaceOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateNamespaceOutput) SetStatus(v int64) *CreateNamespaceOutput { + s.Status = &v + return s +} + +type CreateTemplateAliasInput struct { + _ struct{} `type:"structure"` + + // The name that you want to give to the template alias that you're creating. + // Don't start the alias name with the $ character. Alias names that start with + // $ are reserved by QuickSight. + // + // AliasName is a required field + AliasName *string `location:"uri" locationName:"AliasName" min:"1" type:"string" required:"true"` + + // The ID of the AWS account that contains the template that you creating an + // alias for. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // An ID for the template. + // + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + + // The version number of the template. + // + // TemplateVersionNumber is a required field + TemplateVersionNumber *int64 `min:"1" type:"long" required:"true"` +} + +// String returns the string representation +func (s CreateTemplateAliasInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateTemplateAliasInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateTemplateAliasInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateTemplateAliasInput"} + if s.AliasName == nil { + invalidParams.Add(request.NewErrParamRequired("AliasName")) + } + if s.AliasName != nil && len(*s.AliasName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) + } + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) + } + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + } + if s.TemplateVersionNumber == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateVersionNumber")) + } + if s.TemplateVersionNumber != nil && *s.TemplateVersionNumber < 1 { + invalidParams.Add(request.NewErrParamMinValue("TemplateVersionNumber", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAliasName sets the AliasName field's value. +func (s *CreateTemplateAliasInput) SetAliasName(v string) *CreateTemplateAliasInput { + s.AliasName = &v + return s +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateTemplateAliasInput) SetAwsAccountId(v string) *CreateTemplateAliasInput { + s.AwsAccountId = &v + return s +} + +// SetTemplateId sets the TemplateId field's value. +func (s *CreateTemplateAliasInput) SetTemplateId(v string) *CreateTemplateAliasInput { + s.TemplateId = &v + return s +} + +// SetTemplateVersionNumber sets the TemplateVersionNumber field's value. +func (s *CreateTemplateAliasInput) SetTemplateVersionNumber(v int64) *CreateTemplateAliasInput { + s.TemplateVersionNumber = &v + return s +} + +type CreateTemplateAliasOutput struct { + _ struct{} `type:"structure"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` + + // Information about the template alias. + TemplateAlias *TemplateAlias `type:"structure"` +} + +// String returns the string representation +func (s CreateTemplateAliasOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateTemplateAliasOutput) GoString() string { + return s.String() +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateTemplateAliasOutput) SetRequestId(v string) *CreateTemplateAliasOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateTemplateAliasOutput) SetStatus(v int64) *CreateTemplateAliasOutput { + s.Status = &v + return s +} + +// SetTemplateAlias sets the TemplateAlias field's value. +func (s *CreateTemplateAliasOutput) SetTemplateAlias(v *TemplateAlias) *CreateTemplateAliasOutput { + s.TemplateAlias = v + return s +} + +type CreateTemplateInput struct { + _ struct{} `type:"structure"` + + // The ID for the AWS account that the group is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // A display name for the template. + Name *string `min:"1" type:"string"` + + // A list of resource permissions to be set on the template. + Permissions []*ResourcePermission `min:"1" type:"list"` + + // The entity that you are using as a source when you create the template. In + // SourceEntity, you specify the type of object you're using as source: SourceTemplate + // for a template or SourceAnalysis for an analysis. Both of these require an + // Amazon Resource Name (ARN). For SourceTemplate, specify the ARN of the source + // template. For SourceAnalysis, specify the ARN of the source analysis. The + // SourceTemplate ARN can contain any AWS Account and any QuickSight-supported + // AWS Region. + // + // Use the DataSetReferences entity within SourceTemplate or SourceAnalysis + // to list the replacement datasets for the placeholders listed in the original. + // The schema in each dataset must match its placeholder. + // + // SourceEntity is a required field + SourceEntity *TemplateSourceEntity `type:"structure" required:"true"` + + // Contains a map of the key-value pairs for the resource tag or tags assigned + // to the resource. + Tags []*Tag `min:"1" type:"list"` + + // An ID for the template that you want to create. This template is unique per + // AWS Region in each AWS account. + // + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + + // A description of the current template version being created. This API operation + // creates the first version of the template. Every time UpdateTemplate is called, + // a new version is created. Each version of the template maintains a description + // of the version in the VersionDescription field. + VersionDescription *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s CreateTemplateInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateTemplateInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateTemplateInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateTemplateInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.Permissions != nil && len(s.Permissions) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Permissions", 1)) + } + if s.SourceEntity == nil { + invalidParams.Add(request.NewErrParamRequired("SourceEntity")) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + } + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) + } + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + } + if s.VersionDescription != nil && len(*s.VersionDescription) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VersionDescription", 1)) + } + if s.Permissions != nil { + for i, v := range s.Permissions { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Permissions", i), err.(request.ErrInvalidParams)) + } + } + } + if s.SourceEntity != nil { + if err := s.SourceEntity.Validate(); err != nil { + invalidParams.AddNested("SourceEntity", err.(request.ErrInvalidParams)) + } + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateTemplateInput) SetAwsAccountId(v string) *CreateTemplateInput { + s.AwsAccountId = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateTemplateInput) SetName(v string) *CreateTemplateInput { + s.Name = &v + return s +} + +// SetPermissions sets the Permissions field's value. +func (s *CreateTemplateInput) SetPermissions(v []*ResourcePermission) *CreateTemplateInput { + s.Permissions = v + return s +} + +// SetSourceEntity sets the SourceEntity field's value. +func (s *CreateTemplateInput) SetSourceEntity(v *TemplateSourceEntity) *CreateTemplateInput { + s.SourceEntity = v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateTemplateInput) SetTags(v []*Tag) *CreateTemplateInput { + s.Tags = v + return s +} + +// SetTemplateId sets the TemplateId field's value. +func (s *CreateTemplateInput) SetTemplateId(v string) *CreateTemplateInput { + s.TemplateId = &v + return s +} + +// SetVersionDescription sets the VersionDescription field's value. +func (s *CreateTemplateInput) SetVersionDescription(v string) *CreateTemplateInput { + s.VersionDescription = &v + return s +} + +type CreateTemplateOutput struct { + _ struct{} `type:"structure"` + + // The ARN for the template. + Arn *string `type:"string"` + + // The template creation status. + CreationStatus *string `type:"string" enum:"ResourceStatus"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` + + // The ID of the template. + TemplateId *string `min:"1" type:"string"` + + // The ARN for the template, including the version information of the first + // version. + VersionArn *string `type:"string"` +} + +// String returns the string representation +func (s CreateTemplateOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateTemplateOutput) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *CreateTemplateOutput) SetArn(v string) *CreateTemplateOutput { + s.Arn = &v + return s +} + +// SetCreationStatus sets the CreationStatus field's value. +func (s *CreateTemplateOutput) SetCreationStatus(v string) *CreateTemplateOutput { + s.CreationStatus = &v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateTemplateOutput) SetRequestId(v string) *CreateTemplateOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateTemplateOutput) SetStatus(v int64) *CreateTemplateOutput { + s.Status = &v + return s +} + +// SetTemplateId sets the TemplateId field's value. +func (s *CreateTemplateOutput) SetTemplateId(v string) *CreateTemplateOutput { + s.TemplateId = &v + return s +} + +// SetVersionArn sets the VersionArn field's value. +func (s *CreateTemplateOutput) SetVersionArn(v string) *CreateTemplateOutput { + s.VersionArn = &v + return s +} + +type CreateThemeAliasInput struct { + _ struct{} `type:"structure"` + + // The name that you want to give to the theme alias that you are creating. + // The alias name can't begin with a $. Alias names that start with $ are reserved + // by Amazon QuickSight. + // + // AliasName is a required field + AliasName *string `location:"uri" locationName:"AliasName" min:"1" type:"string" required:"true"` + + // The ID of the AWS account that contains the theme for the new theme alias. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // An ID for the theme alias. + // + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` + + // The version number of the theme. + // + // ThemeVersionNumber is a required field + ThemeVersionNumber *int64 `min:"1" type:"long" required:"true"` +} + +// String returns the string representation +func (s CreateThemeAliasInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateThemeAliasInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateThemeAliasInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateThemeAliasInput"} + if s.AliasName == nil { + invalidParams.Add(request.NewErrParamRequired("AliasName")) + } + if s.AliasName != nil && len(*s.AliasName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) + } + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) + } + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) + } + if s.ThemeVersionNumber == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeVersionNumber")) + } + if s.ThemeVersionNumber != nil && *s.ThemeVersionNumber < 1 { + invalidParams.Add(request.NewErrParamMinValue("ThemeVersionNumber", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAliasName sets the AliasName field's value. +func (s *CreateThemeAliasInput) SetAliasName(v string) *CreateThemeAliasInput { + s.AliasName = &v + return s +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateThemeAliasInput) SetAwsAccountId(v string) *CreateThemeAliasInput { + s.AwsAccountId = &v + return s +} + +// SetThemeId sets the ThemeId field's value. +func (s *CreateThemeAliasInput) SetThemeId(v string) *CreateThemeAliasInput { + s.ThemeId = &v + return s +} + +// SetThemeVersionNumber sets the ThemeVersionNumber field's value. +func (s *CreateThemeAliasInput) SetThemeVersionNumber(v int64) *CreateThemeAliasInput { + s.ThemeVersionNumber = &v + return s +} + +type CreateThemeAliasOutput struct { + _ struct{} `type:"structure"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` + + // Information about the theme alias. + ThemeAlias *ThemeAlias `type:"structure"` +} + +// String returns the string representation +func (s CreateThemeAliasOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateThemeAliasOutput) GoString() string { + return s.String() +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateThemeAliasOutput) SetRequestId(v string) *CreateThemeAliasOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateThemeAliasOutput) SetStatus(v int64) *CreateThemeAliasOutput { + s.Status = &v + return s +} + +// SetThemeAlias sets the ThemeAlias field's value. +func (s *CreateThemeAliasOutput) SetThemeAlias(v *ThemeAlias) *CreateThemeAliasOutput { + s.ThemeAlias = v + return s +} + +type CreateThemeInput struct { + _ struct{} `type:"structure"` + + // The ID of the AWS account where you want to store the new theme. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The ID of the theme that a custom theme will inherit from. All themes inherit + // from one of the starting themes defined by Amazon QuickSight. For a list + // of the starting themes, use ListThemes or choose Themes from within a QuickSight + // analysis. + // + // BaseThemeId is a required field + BaseThemeId *string `min:"1" type:"string" required:"true"` + + // The theme configuration, which contains the theme display properties. + // + // Configuration is a required field + Configuration *ThemeConfiguration `type:"structure" required:"true"` + + // A display name for the theme. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // A valid grouping of resource permissions to apply to the new theme. + Permissions []*ResourcePermission `min:"1" type:"list"` + + // A map of the key-value pairs for the resource tag or tags that you want to + // add to the resource. + Tags []*Tag `min:"1" type:"list"` + + // An ID for the theme that you want to create. The theme ID is unique per AWS + // Region in each AWS account. + // + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` + + // A description of the first version of the theme that you're creating. Every + // time UpdateTheme is called, a new version is created. Each version of the + // theme has a description of the version in the VersionDescription field. + VersionDescription *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s CreateThemeInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateThemeInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateThemeInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateThemeInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.BaseThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("BaseThemeId")) + } + if s.BaseThemeId != nil && len(*s.BaseThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("BaseThemeId", 1)) + } + if s.Configuration == nil { + invalidParams.Add(request.NewErrParamRequired("Configuration")) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.Permissions != nil && len(s.Permissions) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Permissions", 1)) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + } + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) + } + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) + } + if s.VersionDescription != nil && len(*s.VersionDescription) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VersionDescription", 1)) + } + if s.Permissions != nil { + for i, v := range s.Permissions { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Permissions", i), err.(request.ErrInvalidParams)) + } + } + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *CreateThemeInput) SetAwsAccountId(v string) *CreateThemeInput { + s.AwsAccountId = &v + return s +} + +// SetBaseThemeId sets the BaseThemeId field's value. +func (s *CreateThemeInput) SetBaseThemeId(v string) *CreateThemeInput { + s.BaseThemeId = &v + return s +} + +// SetConfiguration sets the Configuration field's value. +func (s *CreateThemeInput) SetConfiguration(v *ThemeConfiguration) *CreateThemeInput { + s.Configuration = v + return s +} + +// SetName sets the Name field's value. +func (s *CreateThemeInput) SetName(v string) *CreateThemeInput { + s.Name = &v + return s +} + +// SetPermissions sets the Permissions field's value. +func (s *CreateThemeInput) SetPermissions(v []*ResourcePermission) *CreateThemeInput { + s.Permissions = v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateThemeInput) SetTags(v []*Tag) *CreateThemeInput { + s.Tags = v + return s +} + +// SetThemeId sets the ThemeId field's value. +func (s *CreateThemeInput) SetThemeId(v string) *CreateThemeInput { + s.ThemeId = &v + return s +} + +// SetVersionDescription sets the VersionDescription field's value. +func (s *CreateThemeInput) SetVersionDescription(v string) *CreateThemeInput { + s.VersionDescription = &v + return s +} + +type CreateThemeOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) for the theme. + Arn *string `type:"string"` + + // The theme creation status. + CreationStatus *string `type:"string" enum:"ResourceStatus"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` + + // The ID of the theme. + ThemeId *string `min:"1" type:"string"` + + // The Amazon Resource Name (ARN) for the new theme. + VersionArn *string `type:"string"` +} + +// String returns the string representation +func (s CreateThemeOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateThemeOutput) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *CreateThemeOutput) SetArn(v string) *CreateThemeOutput { + s.Arn = &v + return s +} + +// SetCreationStatus sets the CreationStatus field's value. +func (s *CreateThemeOutput) SetCreationStatus(v string) *CreateThemeOutput { + s.CreationStatus = &v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *CreateThemeOutput) SetRequestId(v string) *CreateThemeOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CreateThemeOutput) SetStatus(v int64) *CreateThemeOutput { + s.Status = &v + return s +} + +// SetThemeId sets the ThemeId field's value. +func (s *CreateThemeOutput) SetThemeId(v string) *CreateThemeOutput { + s.ThemeId = &v + return s +} + +// SetVersionArn sets the VersionArn field's value. +func (s *CreateThemeOutput) SetVersionArn(v string) *CreateThemeOutput { + s.VersionArn = &v + return s +} + +// The combination of user name and password that are used as credentials. +type CredentialPair struct { + _ struct{} `type:"structure"` + + // A set of alternate data source parameters that you want to share for these + // credentials. The credentials are applied in tandem with the data source parameters + // when you copy a data source by using a create or update request. The API + // compares the DataSourceParameters structure that's in the request with the + // structures in the AlternateDataSourceParameters allowlist. If the structures + // are an exact match, the request is allowed to use the new data source with + // the existing credentials. If the AlternateDataSourceParameters list is null, + // the DataSourceParameters originally used with these Credentials is automatically + // allowed. + AlternateDataSourceParameters []*DataSourceParameters `min:"1" type:"list"` + + // Password. + // + // Password is a required field + Password *string `min:"1" type:"string" required:"true"` + + // User name. + // + // Username is a required field + Username *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CredentialPair) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CredentialPair) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CredentialPair) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CredentialPair"} + if s.AlternateDataSourceParameters != nil && len(s.AlternateDataSourceParameters) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AlternateDataSourceParameters", 1)) + } + if s.Password == nil { + invalidParams.Add(request.NewErrParamRequired("Password")) + } + if s.Password != nil && len(*s.Password) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Password", 1)) + } + if s.Username == nil { + invalidParams.Add(request.NewErrParamRequired("Username")) + } + if s.Username != nil && len(*s.Username) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Username", 1)) + } + if s.AlternateDataSourceParameters != nil { + for i, v := range s.AlternateDataSourceParameters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "AlternateDataSourceParameters", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAlternateDataSourceParameters sets the AlternateDataSourceParameters field's value. +func (s *CredentialPair) SetAlternateDataSourceParameters(v []*DataSourceParameters) *CredentialPair { + s.AlternateDataSourceParameters = v + return s +} + +// SetPassword sets the Password field's value. +func (s *CredentialPair) SetPassword(v string) *CredentialPair { + s.Password = &v + return s +} + +// SetUsername sets the Username field's value. +func (s *CredentialPair) SetUsername(v string) *CredentialPair { + s.Username = &v + return s +} + +// A physical table type built from the results of the custom SQL query. +type CustomSql struct { + _ struct{} `type:"structure"` + + // The column schema from the SQL query result set. + Columns []*InputColumn `min:"1" type:"list"` + + // The Amazon Resource Name (ARN) of the data source. + // + // DataSourceArn is a required field + DataSourceArn *string `type:"string" required:"true"` + + // A display name for the SQL query result. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // The SQL query. + // + // SqlQuery is a required field + SqlQuery *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CustomSql) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CustomSql) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CustomSql) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CustomSql"} + if s.Columns != nil && len(s.Columns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Columns", 1)) + } + if s.DataSourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("DataSourceArn")) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.SqlQuery == nil { + invalidParams.Add(request.NewErrParamRequired("SqlQuery")) + } + if s.SqlQuery != nil && len(*s.SqlQuery) < 1 { + invalidParams.Add(request.NewErrParamMinLen("SqlQuery", 1)) + } + if s.Columns != nil { + for i, v := range s.Columns { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Columns", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetColumns sets the Columns field's value. +func (s *CustomSql) SetColumns(v []*InputColumn) *CustomSql { + s.Columns = v + return s +} + +// SetDataSourceArn sets the DataSourceArn field's value. +func (s *CustomSql) SetDataSourceArn(v string) *CustomSql { + s.DataSourceArn = &v + return s +} + +// SetName sets the Name field's value. +func (s *CustomSql) SetName(v string) *CustomSql { + s.Name = &v + return s +} + +// SetSqlQuery sets the SqlQuery field's value. +func (s *CustomSql) SetSqlQuery(v string) *CustomSql { + s.SqlQuery = &v + return s +} + +// Dashboard. +type Dashboard struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource. + Arn *string `type:"string"` + + // The time that this dataset was created. + CreatedTime *time.Time `type:"timestamp"` + + // Dashboard ID. + DashboardId *string `min:"1" type:"string"` + + // The last time that this dataset was published. + LastPublishedTime *time.Time `type:"timestamp"` + + // The last time that this dataset was updated. + LastUpdatedTime *time.Time `type:"timestamp"` + + // A display name for the dashboard. + Name *string `min:"1" type:"string"` + + // Version. + Version *DashboardVersion `type:"structure"` +} + +// String returns the string representation +func (s Dashboard) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Dashboard) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Dashboard) SetArn(v string) *Dashboard { + s.Arn = &v + return s +} + +// SetCreatedTime sets the CreatedTime field's value. +func (s *Dashboard) SetCreatedTime(v time.Time) *Dashboard { + s.CreatedTime = &v + return s +} + +// SetDashboardId sets the DashboardId field's value. +func (s *Dashboard) SetDashboardId(v string) *Dashboard { + s.DashboardId = &v + return s +} + +// SetLastPublishedTime sets the LastPublishedTime field's value. +func (s *Dashboard) SetLastPublishedTime(v time.Time) *Dashboard { + s.LastPublishedTime = &v + return s +} + +// SetLastUpdatedTime sets the LastUpdatedTime field's value. +func (s *Dashboard) SetLastUpdatedTime(v time.Time) *Dashboard { + s.LastUpdatedTime = &v + return s +} + +// SetName sets the Name field's value. +func (s *Dashboard) SetName(v string) *Dashboard { + s.Name = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *Dashboard) SetVersion(v *DashboardVersion) *Dashboard { + s.Version = v + return s +} + +// Dashboard error. +type DashboardError struct { + _ struct{} `type:"structure"` + + // Message. + Message *string `type:"string"` + + // Type. + Type *string `type:"string" enum:"DashboardErrorType"` +} + +// String returns the string representation +func (s DashboardError) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DashboardError) GoString() string { + return s.String() +} + +// SetMessage sets the Message field's value. +func (s *DashboardError) SetMessage(v string) *DashboardError { + s.Message = &v + return s +} + +// SetType sets the Type field's value. +func (s *DashboardError) SetType(v string) *DashboardError { + s.Type = &v + return s +} + +// Dashboard publish options. +type DashboardPublishOptions struct { + _ struct{} `type:"structure"` + + // Ad hoc (one-time) filtering option. + AdHocFilteringOption *AdHocFilteringOption `type:"structure"` + + // Export to .csv option. + ExportToCSVOption *ExportToCSVOption `type:"structure"` + + // Sheet controls option. + SheetControlsOption *SheetControlsOption `type:"structure"` +} + +// String returns the string representation +func (s DashboardPublishOptions) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DashboardPublishOptions) GoString() string { + return s.String() +} + +// SetAdHocFilteringOption sets the AdHocFilteringOption field's value. +func (s *DashboardPublishOptions) SetAdHocFilteringOption(v *AdHocFilteringOption) *DashboardPublishOptions { + s.AdHocFilteringOption = v + return s +} + +// SetExportToCSVOption sets the ExportToCSVOption field's value. +func (s *DashboardPublishOptions) SetExportToCSVOption(v *ExportToCSVOption) *DashboardPublishOptions { + s.ExportToCSVOption = v + return s +} + +// SetSheetControlsOption sets the SheetControlsOption field's value. +func (s *DashboardPublishOptions) SetSheetControlsOption(v *SheetControlsOption) *DashboardPublishOptions { + s.SheetControlsOption = v + return s +} + +// A filter that you apply when searching for dashboards. +type DashboardSearchFilter struct { + _ struct{} `type:"structure"` + + // The name of the value that you want to use as a filter, for example, "Name": + // "QUICKSIGHT_USER". + Name *string `type:"string" enum:"DashboardFilterAttribute"` + + // The comparison operator that you want to use as a filter, for example, "Operator": + // "StringEquals". + // + // Operator is a required field + Operator *string `type:"string" required:"true" enum:"FilterOperator"` + + // The value of the named item, in this case QUICKSIGHT_USER, that you want + // to use as a filter, for example, "Value": "arn:aws:quicksight:us-east-1:1:user/default/UserName1". + Value *string `type:"string"` +} + +// String returns the string representation +func (s DashboardSearchFilter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DashboardSearchFilter) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DashboardSearchFilter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DashboardSearchFilter"} + if s.Operator == nil { + invalidParams.Add(request.NewErrParamRequired("Operator")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *DashboardSearchFilter) SetName(v string) *DashboardSearchFilter { + s.Name = &v + return s +} + +// SetOperator sets the Operator field's value. +func (s *DashboardSearchFilter) SetOperator(v string) *DashboardSearchFilter { + s.Operator = &v + return s +} + +// SetValue sets the Value field's value. +func (s *DashboardSearchFilter) SetValue(v string) *DashboardSearchFilter { + s.Value = &v + return s +} + +// Dashboard source entity. +type DashboardSourceEntity struct { + _ struct{} `type:"structure"` + + // Source template. + SourceTemplate *DashboardSourceTemplate `type:"structure"` +} + +// String returns the string representation +func (s DashboardSourceEntity) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DashboardSourceEntity) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DashboardSourceEntity) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DashboardSourceEntity"} + if s.SourceTemplate != nil { + if err := s.SourceTemplate.Validate(); err != nil { + invalidParams.AddNested("SourceTemplate", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetSourceTemplate sets the SourceTemplate field's value. +func (s *DashboardSourceEntity) SetSourceTemplate(v *DashboardSourceTemplate) *DashboardSourceEntity { + s.SourceTemplate = v + return s +} + +// Dashboard source template. +type DashboardSourceTemplate struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource. + // + // Arn is a required field + Arn *string `type:"string" required:"true"` + + // Dataset references. + // + // DataSetReferences is a required field + DataSetReferences []*DataSetReference `min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s DashboardSourceTemplate) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DashboardSourceTemplate) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DashboardSourceTemplate) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DashboardSourceTemplate"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) + } + if s.DataSetReferences == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetReferences")) + } + if s.DataSetReferences != nil && len(s.DataSetReferences) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetReferences", 1)) + } + if s.DataSetReferences != nil { + for i, v := range s.DataSetReferences { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DataSetReferences", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArn sets the Arn field's value. +func (s *DashboardSourceTemplate) SetArn(v string) *DashboardSourceTemplate { + s.Arn = &v + return s +} + +// SetDataSetReferences sets the DataSetReferences field's value. +func (s *DashboardSourceTemplate) SetDataSetReferences(v []*DataSetReference) *DashboardSourceTemplate { + s.DataSetReferences = v + return s +} + +// Dashboard summary. +type DashboardSummary struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource. + Arn *string `type:"string"` + + // The time that this dashboard was created. + CreatedTime *time.Time `type:"timestamp"` + + // Dashboard ID. + DashboardId *string `min:"1" type:"string"` + + // The last time that this dashboard was published. + LastPublishedTime *time.Time `type:"timestamp"` + + // The last time that this dashboard was updated. + LastUpdatedTime *time.Time `type:"timestamp"` + + // A display name for the dashboard. + Name *string `min:"1" type:"string"` + + // Published version number. + PublishedVersionNumber *int64 `min:"1" type:"long"` +} + +// String returns the string representation +func (s DashboardSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DashboardSummary) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *DashboardSummary) SetArn(v string) *DashboardSummary { + s.Arn = &v + return s +} + +// SetCreatedTime sets the CreatedTime field's value. +func (s *DashboardSummary) SetCreatedTime(v time.Time) *DashboardSummary { + s.CreatedTime = &v + return s +} + +// SetDashboardId sets the DashboardId field's value. +func (s *DashboardSummary) SetDashboardId(v string) *DashboardSummary { + s.DashboardId = &v + return s +} + +// SetLastPublishedTime sets the LastPublishedTime field's value. +func (s *DashboardSummary) SetLastPublishedTime(v time.Time) *DashboardSummary { + s.LastPublishedTime = &v + return s +} + +// SetLastUpdatedTime sets the LastUpdatedTime field's value. +func (s *DashboardSummary) SetLastUpdatedTime(v time.Time) *DashboardSummary { + s.LastUpdatedTime = &v + return s +} + +// SetName sets the Name field's value. +func (s *DashboardSummary) SetName(v string) *DashboardSummary { + s.Name = &v + return s +} + +// SetPublishedVersionNumber sets the PublishedVersionNumber field's value. +func (s *DashboardSummary) SetPublishedVersionNumber(v int64) *DashboardSummary { + s.PublishedVersionNumber = &v + return s +} + +// Dashboard version. +type DashboardVersion struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource. + Arn *string `type:"string"` + + // The time that this dashboard version was created. + CreatedTime *time.Time `type:"timestamp"` + + // The Amazon Resource Numbers (ARNs) for the datasets that are associated with + // a version of the dashboard. + DataSetArns []*string `type:"list"` + + // Description. + Description *string `min:"1" type:"string"` + + // Errors. + Errors []*DashboardError `min:"1" type:"list"` + + // Source entity ARN. + SourceEntityArn *string `type:"string"` + + // The HTTP status of the request. + Status *string `type:"string" enum:"ResourceStatus"` + + // Version number. + VersionNumber *int64 `min:"1" type:"long"` +} + +// String returns the string representation +func (s DashboardVersion) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DashboardVersion) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *DashboardVersion) SetArn(v string) *DashboardVersion { + s.Arn = &v + return s +} + +// SetCreatedTime sets the CreatedTime field's value. +func (s *DashboardVersion) SetCreatedTime(v time.Time) *DashboardVersion { + s.CreatedTime = &v + return s +} + +// SetDataSetArns sets the DataSetArns field's value. +func (s *DashboardVersion) SetDataSetArns(v []*string) *DashboardVersion { + s.DataSetArns = v + return s +} + +// SetDescription sets the Description field's value. +func (s *DashboardVersion) SetDescription(v string) *DashboardVersion { + s.Description = &v + return s +} + +// SetErrors sets the Errors field's value. +func (s *DashboardVersion) SetErrors(v []*DashboardError) *DashboardVersion { + s.Errors = v + return s +} + +// SetSourceEntityArn sets the SourceEntityArn field's value. +func (s *DashboardVersion) SetSourceEntityArn(v string) *DashboardVersion { + s.SourceEntityArn = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *DashboardVersion) SetStatus(v string) *DashboardVersion { + s.Status = &v + return s +} + +// SetVersionNumber sets the VersionNumber field's value. +func (s *DashboardVersion) SetVersionNumber(v int64) *DashboardVersion { + s.VersionNumber = &v + return s +} + +// Dashboard version summary. +type DashboardVersionSummary struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource. + Arn *string `type:"string"` + + // The time that this dashboard version was created. + CreatedTime *time.Time `type:"timestamp"` + + // Description. + Description *string `min:"1" type:"string"` + + // Source entity ARN. + SourceEntityArn *string `type:"string"` + + // The HTTP status of the request. + Status *string `type:"string" enum:"ResourceStatus"` + + // Version number. + VersionNumber *int64 `min:"1" type:"long"` +} + +// String returns the string representation +func (s DashboardVersionSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DashboardVersionSummary) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *DashboardVersionSummary) SetArn(v string) *DashboardVersionSummary { + s.Arn = &v + return s +} + +// SetCreatedTime sets the CreatedTime field's value. +func (s *DashboardVersionSummary) SetCreatedTime(v time.Time) *DashboardVersionSummary { + s.CreatedTime = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *DashboardVersionSummary) SetDescription(v string) *DashboardVersionSummary { + s.Description = &v + return s +} + +// SetSourceEntityArn sets the SourceEntityArn field's value. +func (s *DashboardVersionSummary) SetSourceEntityArn(v string) *DashboardVersionSummary { + s.SourceEntityArn = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *DashboardVersionSummary) SetStatus(v string) *DashboardVersionSummary { + s.Status = &v + return s +} + +// SetVersionNumber sets the VersionNumber field's value. +func (s *DashboardVersionSummary) SetVersionNumber(v int64) *DashboardVersionSummary { + s.VersionNumber = &v + return s +} + +// The theme colors that are used for data colors in charts. The colors description +// is a hexidecimal color code that consists of six alphanumerical characters, +// prefixed with #, for example #37BFF5. +type DataColorPalette struct { + _ struct{} `type:"structure"` + + // The hexadecimal codes for the colors. + Colors []*string `type:"list"` + + // The hexadecimal code of a color that applies to charts where a lack of data + // is highlighted. + EmptyFillColor *string `type:"string"` + + // The minimum and maximum hexadecimal codes that describe a color gradient. + MinMaxGradient []*string `type:"list"` +} + +// String returns the string representation +func (s DataColorPalette) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DataColorPalette) GoString() string { + return s.String() +} + +// SetColors sets the Colors field's value. +func (s *DataColorPalette) SetColors(v []*string) *DataColorPalette { + s.Colors = v + return s +} + +// SetEmptyFillColor sets the EmptyFillColor field's value. +func (s *DataColorPalette) SetEmptyFillColor(v string) *DataColorPalette { + s.EmptyFillColor = &v + return s +} + +// SetMinMaxGradient sets the MinMaxGradient field's value. +func (s *DataColorPalette) SetMinMaxGradient(v []*string) *DataColorPalette { + s.MinMaxGradient = v + return s +} + +// Dataset. +type DataSet struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource. + Arn *string `type:"string"` + + // Groupings of columns that work together in certain Amazon QuickSight features. + // Currently, only geospatial hierarchy is supported. + ColumnGroups []*ColumnGroup `min:"1" type:"list"` + + // The amount of SPICE capacity used by this dataset. This is 0 if the dataset + // isn't imported into SPICE. + ConsumedSpiceCapacityInBytes *int64 `type:"long"` + + // The time that this dataset was created. + CreatedTime *time.Time `type:"timestamp"` + + // The ID of the dataset. + DataSetId *string `type:"string"` + + // Indicates whether you want to import the data into SPICE. + ImportMode *string `type:"string" enum:"DataSetImportMode"` + + // The last time that this dataset was updated. + LastUpdatedTime *time.Time `type:"timestamp"` + + // Configures the combination and transformation of the data from the physical + // tables. + LogicalTableMap map[string]*LogicalTable `min:"1" type:"map"` + + // A display name for the dataset. + Name *string `min:"1" type:"string"` + + // The list of columns after all transforms. These columns are available in + // templates, analyses, and dashboards. + OutputColumns []*OutputColumn `type:"list"` + + // Declares the physical tables that are available in the underlying data sources. + PhysicalTableMap map[string]*PhysicalTable `min:"1" type:"map"` + + // The row-level security configuration for the dataset. + RowLevelPermissionDataSet *RowLevelPermissionDataSet `type:"structure"` +} + +// String returns the string representation +func (s DataSet) String() string { + return awsutil.Prettify(s) +} - Message_ *string `locationName:"Message" type:"string"` +// GoString returns the string representation +func (s DataSet) GoString() string { + return s.String() +} - // The AWS request ID for this request. - RequestId *string `type:"string"` +// SetArn sets the Arn field's value. +func (s *DataSet) SetArn(v string) *DataSet { + s.Arn = &v + return s +} + +// SetColumnGroups sets the ColumnGroups field's value. +func (s *DataSet) SetColumnGroups(v []*ColumnGroup) *DataSet { + s.ColumnGroups = v + return s +} + +// SetConsumedSpiceCapacityInBytes sets the ConsumedSpiceCapacityInBytes field's value. +func (s *DataSet) SetConsumedSpiceCapacityInBytes(v int64) *DataSet { + s.ConsumedSpiceCapacityInBytes = &v + return s +} + +// SetCreatedTime sets the CreatedTime field's value. +func (s *DataSet) SetCreatedTime(v time.Time) *DataSet { + s.CreatedTime = &v + return s +} + +// SetDataSetId sets the DataSetId field's value. +func (s *DataSet) SetDataSetId(v string) *DataSet { + s.DataSetId = &v + return s +} + +// SetImportMode sets the ImportMode field's value. +func (s *DataSet) SetImportMode(v string) *DataSet { + s.ImportMode = &v + return s +} + +// SetLastUpdatedTime sets the LastUpdatedTime field's value. +func (s *DataSet) SetLastUpdatedTime(v time.Time) *DataSet { + s.LastUpdatedTime = &v + return s +} + +// SetLogicalTableMap sets the LogicalTableMap field's value. +func (s *DataSet) SetLogicalTableMap(v map[string]*LogicalTable) *DataSet { + s.LogicalTableMap = v + return s +} + +// SetName sets the Name field's value. +func (s *DataSet) SetName(v string) *DataSet { + s.Name = &v + return s +} + +// SetOutputColumns sets the OutputColumns field's value. +func (s *DataSet) SetOutputColumns(v []*OutputColumn) *DataSet { + s.OutputColumns = v + return s +} + +// SetPhysicalTableMap sets the PhysicalTableMap field's value. +func (s *DataSet) SetPhysicalTableMap(v map[string]*PhysicalTable) *DataSet { + s.PhysicalTableMap = v + return s +} + +// SetRowLevelPermissionDataSet sets the RowLevelPermissionDataSet field's value. +func (s *DataSet) SetRowLevelPermissionDataSet(v *RowLevelPermissionDataSet) *DataSet { + s.RowLevelPermissionDataSet = v + return s +} + +// Dataset configuration. +type DataSetConfiguration struct { + _ struct{} `type:"structure"` + + // A structure containing the list of column group schemas. + ColumnGroupSchemaList []*ColumnGroupSchema `type:"list"` + + // Dataset schema. + DataSetSchema *DataSetSchema `type:"structure"` + + // Placeholder. + Placeholder *string `type:"string"` } // String returns the string representation -func (s AccessDeniedException) String() string { +func (s DataSetConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AccessDeniedException) GoString() string { +func (s DataSetConfiguration) GoString() string { return s.String() } -func newErrorAccessDeniedException(v protocol.ResponseMetadata) error { - return &AccessDeniedException{ - RespMetadata: v, - } +// SetColumnGroupSchemaList sets the ColumnGroupSchemaList field's value. +func (s *DataSetConfiguration) SetColumnGroupSchemaList(v []*ColumnGroupSchema) *DataSetConfiguration { + s.ColumnGroupSchemaList = v + return s } -// Code returns the exception type name. -func (s *AccessDeniedException) Code() string { - return "AccessDeniedException" +// SetDataSetSchema sets the DataSetSchema field's value. +func (s *DataSetConfiguration) SetDataSetSchema(v *DataSetSchema) *DataSetConfiguration { + s.DataSetSchema = v + return s } -// Message returns the exception's message. -func (s *AccessDeniedException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" +// SetPlaceholder sets the Placeholder field's value. +func (s *DataSetConfiguration) SetPlaceholder(v string) *DataSetConfiguration { + s.Placeholder = &v + return s } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *AccessDeniedException) OrigErr() error { +// Dataset reference. +type DataSetReference struct { + _ struct{} `type:"structure"` + + // Dataset Amazon Resource Name (ARN). + // + // DataSetArn is a required field + DataSetArn *string `type:"string" required:"true"` + + // Dataset placeholder. + // + // DataSetPlaceholder is a required field + DataSetPlaceholder *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s DataSetReference) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DataSetReference) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DataSetReference) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DataSetReference"} + if s.DataSetArn == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetArn")) + } + if s.DataSetPlaceholder == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetPlaceholder")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } return nil } -func (s *AccessDeniedException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetDataSetArn sets the DataSetArn field's value. +func (s *DataSetReference) SetDataSetArn(v string) *DataSetReference { + s.DataSetArn = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *AccessDeniedException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetDataSetPlaceholder sets the DataSetPlaceholder field's value. +func (s *DataSetReference) SetDataSetPlaceholder(v string) *DataSetReference { + s.DataSetPlaceholder = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *AccessDeniedException) RequestID() string { - return s.RespMetadata.RequestID +// Dataset schema. +type DataSetSchema struct { + _ struct{} `type:"structure"` + + // A structure containing the list of column schemas. + ColumnSchemaList []*ColumnSchema `type:"list"` } -// The active AWS Identity and Access Management (IAM) policy assignment. -type ActiveIAMPolicyAssignment struct { +// String returns the string representation +func (s DataSetSchema) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DataSetSchema) GoString() string { + return s.String() +} + +// SetColumnSchemaList sets the ColumnSchemaList field's value. +func (s *DataSetSchema) SetColumnSchemaList(v []*ColumnSchema) *DataSetSchema { + s.ColumnSchemaList = v + return s +} + +// Dataset summary. +type DataSetSummary struct { _ struct{} `type:"structure"` - // A name for the IAM policy assignment. - AssignmentName *string `min:"1" type:"string"` + // The Amazon Resource Name (ARN) of the dataset. + Arn *string `type:"string"` + + // The time that this dataset was created. + CreatedTime *time.Time `type:"timestamp"` + + // The ID of the dataset. + DataSetId *string `type:"string"` + + // Indicates whether you want to import the data into SPICE. + ImportMode *string `type:"string" enum:"DataSetImportMode"` + + // The last time that this dataset was updated. + LastUpdatedTime *time.Time `type:"timestamp"` + + // A display name for the dataset. + Name *string `min:"1" type:"string"` - // The Amazon Resource Name (ARN) of the resource. - PolicyArn *string `type:"string"` + // The row-level security configuration for the dataset. + RowLevelPermissionDataSet *RowLevelPermissionDataSet `type:"structure"` } // String returns the string representation -func (s ActiveIAMPolicyAssignment) String() string { +func (s DataSetSummary) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ActiveIAMPolicyAssignment) GoString() string { +func (s DataSetSummary) GoString() string { return s.String() } -// SetAssignmentName sets the AssignmentName field's value. -func (s *ActiveIAMPolicyAssignment) SetAssignmentName(v string) *ActiveIAMPolicyAssignment { - s.AssignmentName = &v +// SetArn sets the Arn field's value. +func (s *DataSetSummary) SetArn(v string) *DataSetSummary { + s.Arn = &v return s } -// SetPolicyArn sets the PolicyArn field's value. -func (s *ActiveIAMPolicyAssignment) SetPolicyArn(v string) *ActiveIAMPolicyAssignment { - s.PolicyArn = &v +// SetCreatedTime sets the CreatedTime field's value. +func (s *DataSetSummary) SetCreatedTime(v time.Time) *DataSetSummary { + s.CreatedTime = &v return s } -// Ad hoc (one-time) filtering option. -type AdHocFilteringOption struct { - _ struct{} `type:"structure"` +// SetDataSetId sets the DataSetId field's value. +func (s *DataSetSummary) SetDataSetId(v string) *DataSetSummary { + s.DataSetId = &v + return s +} - // Availability status. - AvailabilityStatus *string `type:"string" enum:"DashboardBehavior"` +// SetImportMode sets the ImportMode field's value. +func (s *DataSetSummary) SetImportMode(v string) *DataSetSummary { + s.ImportMode = &v + return s } -// String returns the string representation -func (s AdHocFilteringOption) String() string { - return awsutil.Prettify(s) +// SetLastUpdatedTime sets the LastUpdatedTime field's value. +func (s *DataSetSummary) SetLastUpdatedTime(v time.Time) *DataSetSummary { + s.LastUpdatedTime = &v + return s } -// GoString returns the string representation -func (s AdHocFilteringOption) GoString() string { - return s.String() +// SetName sets the Name field's value. +func (s *DataSetSummary) SetName(v string) *DataSetSummary { + s.Name = &v + return s } -// SetAvailabilityStatus sets the AvailabilityStatus field's value. -func (s *AdHocFilteringOption) SetAvailabilityStatus(v string) *AdHocFilteringOption { - s.AvailabilityStatus = &v +// SetRowLevelPermissionDataSet sets the RowLevelPermissionDataSet field's value. +func (s *DataSetSummary) SetRowLevelPermissionDataSet(v *RowLevelPermissionDataSet) *DataSetSummary { + s.RowLevelPermissionDataSet = v return s } -// Amazon Elasticsearch Service parameters. -type AmazonElasticsearchParameters struct { +// The structure of a data source. +type DataSource struct { _ struct{} `type:"structure"` - // The Amazon Elasticsearch Service domain. - // - // Domain is a required field - Domain *string `min:"1" type:"string" required:"true"` -} + // A set of alternate data source parameters that you want to share for the + // credentials stored with this data source. The credentials are applied in + // tandem with the data source parameters when you copy a data source by using + // a create or update request. The API compares the DataSourceParameters structure + // that's in the request with the structures in the AlternateDataSourceParameters + // allowlist. If the structures are an exact match, the request is allowed to + // use the credentials from this existing data source. If the AlternateDataSourceParameters + // list is null, the Credentials originally used with this DataSourceParameters + // are automatically allowed. + AlternateDataSourceParameters []*DataSourceParameters `min:"1" type:"list"` -// String returns the string representation -func (s AmazonElasticsearchParameters) String() string { - return awsutil.Prettify(s) -} + // The Amazon Resource Name (ARN) of the data source. + Arn *string `type:"string"` -// GoString returns the string representation -func (s AmazonElasticsearchParameters) GoString() string { - return s.String() -} + // The time that this data source was created. + CreatedTime *time.Time `type:"timestamp"` -// Validate inspects the fields of the type to determine if they are valid. -func (s *AmazonElasticsearchParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AmazonElasticsearchParameters"} - if s.Domain == nil { - invalidParams.Add(request.NewErrParamRequired("Domain")) - } - if s.Domain != nil && len(*s.Domain) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Domain", 1)) - } + // The ID of the data source. This ID is unique per AWS Region for each AWS + // account. + DataSourceId *string `type:"string"` - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} + // The parameters that Amazon QuickSight uses to connect to your underlying + // source. This is a variant type structure. For this structure to be valid, + // only one of the attributes can be non-null. + DataSourceParameters *DataSourceParameters `type:"structure"` -// SetDomain sets the Domain field's value. -func (s *AmazonElasticsearchParameters) SetDomain(v string) *AmazonElasticsearchParameters { - s.Domain = &v - return s -} + // Error information from the last update or the creation of the data source. + ErrorInfo *DataSourceErrorInfo `type:"structure"` -// Amazon Athena parameters. -type AthenaParameters struct { - _ struct{} `type:"structure"` + // The last time that this data source was updated. + LastUpdatedTime *time.Time `type:"timestamp"` - // The workgroup that Amazon Athena uses. - WorkGroup *string `min:"1" type:"string"` + // A display name for the data source. + Name *string `min:"1" type:"string"` + + // Secure Socket Layer (SSL) properties that apply when QuickSight connects + // to your underlying source. + SslProperties *SslProperties `type:"structure"` + + // The HTTP status of the request. + Status *string `type:"string" enum:"ResourceStatus"` + + // The type of the data source. This type indicates which database engine the + // data source connects to. + Type *string `type:"string" enum:"DataSourceType"` + + // The VPC connection information. You need to use this parameter only when + // you want QuickSight to use a VPC connection when connecting to your underlying + // source. + VpcConnectionProperties *VpcConnectionProperties `type:"structure"` } // String returns the string representation -func (s AthenaParameters) String() string { +func (s DataSource) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AthenaParameters) GoString() string { +func (s DataSource) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AthenaParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AthenaParameters"} - if s.WorkGroup != nil && len(*s.WorkGroup) < 1 { - invalidParams.Add(request.NewErrParamMinLen("WorkGroup", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetAlternateDataSourceParameters sets the AlternateDataSourceParameters field's value. +func (s *DataSource) SetAlternateDataSourceParameters(v []*DataSourceParameters) *DataSource { + s.AlternateDataSourceParameters = v + return s } -// SetWorkGroup sets the WorkGroup field's value. -func (s *AthenaParameters) SetWorkGroup(v string) *AthenaParameters { - s.WorkGroup = &v +// SetArn sets the Arn field's value. +func (s *DataSource) SetArn(v string) *DataSource { + s.Arn = &v return s } -// Amazon Aurora parameters. -type AuroraParameters struct { - _ struct{} `type:"structure"` - - // Database. - // - // Database is a required field - Database *string `min:"1" type:"string" required:"true"` - - // Host. - // - // Host is a required field - Host *string `min:"1" type:"string" required:"true"` +// SetCreatedTime sets the CreatedTime field's value. +func (s *DataSource) SetCreatedTime(v time.Time) *DataSource { + s.CreatedTime = &v + return s +} - // Port. - // - // Port is a required field - Port *int64 `min:"1" type:"integer" required:"true"` +// SetDataSourceId sets the DataSourceId field's value. +func (s *DataSource) SetDataSourceId(v string) *DataSource { + s.DataSourceId = &v + return s } -// String returns the string representation -func (s AuroraParameters) String() string { - return awsutil.Prettify(s) +// SetDataSourceParameters sets the DataSourceParameters field's value. +func (s *DataSource) SetDataSourceParameters(v *DataSourceParameters) *DataSource { + s.DataSourceParameters = v + return s } -// GoString returns the string representation -func (s AuroraParameters) GoString() string { - return s.String() +// SetErrorInfo sets the ErrorInfo field's value. +func (s *DataSource) SetErrorInfo(v *DataSourceErrorInfo) *DataSource { + s.ErrorInfo = v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AuroraParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AuroraParameters"} - if s.Database == nil { - invalidParams.Add(request.NewErrParamRequired("Database")) - } - if s.Database != nil && len(*s.Database) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Database", 1)) - } - if s.Host == nil { - invalidParams.Add(request.NewErrParamRequired("Host")) - } - if s.Host != nil && len(*s.Host) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Host", 1)) - } - if s.Port == nil { - invalidParams.Add(request.NewErrParamRequired("Port")) - } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) - } +// SetLastUpdatedTime sets the LastUpdatedTime field's value. +func (s *DataSource) SetLastUpdatedTime(v time.Time) *DataSource { + s.LastUpdatedTime = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetName sets the Name field's value. +func (s *DataSource) SetName(v string) *DataSource { + s.Name = &v + return s } -// SetDatabase sets the Database field's value. -func (s *AuroraParameters) SetDatabase(v string) *AuroraParameters { - s.Database = &v +// SetSslProperties sets the SslProperties field's value. +func (s *DataSource) SetSslProperties(v *SslProperties) *DataSource { + s.SslProperties = v return s } -// SetHost sets the Host field's value. -func (s *AuroraParameters) SetHost(v string) *AuroraParameters { - s.Host = &v +// SetStatus sets the Status field's value. +func (s *DataSource) SetStatus(v string) *DataSource { + s.Status = &v return s } -// SetPort sets the Port field's value. -func (s *AuroraParameters) SetPort(v int64) *AuroraParameters { - s.Port = &v +// SetType sets the Type field's value. +func (s *DataSource) SetType(v string) *DataSource { + s.Type = &v return s } -// Amazon Aurora with PostgreSQL compatibility parameters. -type AuroraPostgreSqlParameters struct { - _ struct{} `type:"structure"` +// SetVpcConnectionProperties sets the VpcConnectionProperties field's value. +func (s *DataSource) SetVpcConnectionProperties(v *VpcConnectionProperties) *DataSource { + s.VpcConnectionProperties = v + return s +} - // Database. - // - // Database is a required field - Database *string `min:"1" type:"string" required:"true"` +// Data source credentials. This is a variant type structure. For this structure +// to be valid, only one of the attributes can be non-null. +type DataSourceCredentials struct { + _ struct{} `type:"structure" sensitive:"true"` - // Host. - // - // Host is a required field - Host *string `min:"1" type:"string" required:"true"` + // The Amazon Resource Name (ARN) of a data source that has the credential pair + // that you want to use. When CopySourceArn is not null, the credential pair + // from the data source in the ARN is used as the credentials for the DataSourceCredentials + // structure. + CopySourceArn *string `type:"string"` - // Port. - // - // Port is a required field - Port *int64 `min:"1" type:"integer" required:"true"` + // Credential pair. For more information, see CredentialPair. + CredentialPair *CredentialPair `type:"structure"` } // String returns the string representation -func (s AuroraPostgreSqlParameters) String() string { +func (s DataSourceCredentials) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AuroraPostgreSqlParameters) GoString() string { +func (s DataSourceCredentials) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *AuroraPostgreSqlParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AuroraPostgreSqlParameters"} - if s.Database == nil { - invalidParams.Add(request.NewErrParamRequired("Database")) - } - if s.Database != nil && len(*s.Database) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Database", 1)) - } - if s.Host == nil { - invalidParams.Add(request.NewErrParamRequired("Host")) - } - if s.Host != nil && len(*s.Host) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Host", 1)) - } - if s.Port == nil { - invalidParams.Add(request.NewErrParamRequired("Port")) - } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) +func (s *DataSourceCredentials) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DataSourceCredentials"} + if s.CredentialPair != nil { + if err := s.CredentialPair.Validate(); err != nil { + invalidParams.AddNested("CredentialPair", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -7495,193 +14592,222 @@ func (s *AuroraPostgreSqlParameters) Validate() error { return nil } -// SetDatabase sets the Database field's value. -func (s *AuroraPostgreSqlParameters) SetDatabase(v string) *AuroraPostgreSqlParameters { - s.Database = &v - return s -} - -// SetHost sets the Host field's value. -func (s *AuroraPostgreSqlParameters) SetHost(v string) *AuroraPostgreSqlParameters { - s.Host = &v +// SetCopySourceArn sets the CopySourceArn field's value. +func (s *DataSourceCredentials) SetCopySourceArn(v string) *DataSourceCredentials { + s.CopySourceArn = &v return s } -// SetPort sets the Port field's value. -func (s *AuroraPostgreSqlParameters) SetPort(v int64) *AuroraPostgreSqlParameters { - s.Port = &v +// SetCredentialPair sets the CredentialPair field's value. +func (s *DataSourceCredentials) SetCredentialPair(v *CredentialPair) *DataSourceCredentials { + s.CredentialPair = v return s } -// AWS IoT Analytics parameters. -type AwsIotAnalyticsParameters struct { +// Error information for the data source creation or update. +type DataSourceErrorInfo struct { _ struct{} `type:"structure"` - // Dataset name. - // - // DataSetName is a required field - DataSetName *string `min:"1" type:"string" required:"true"` + // Error message. + Message *string `type:"string"` + + // Error type. + Type *string `type:"string" enum:"DataSourceErrorInfoType"` } // String returns the string representation -func (s AwsIotAnalyticsParameters) String() string { +func (s DataSourceErrorInfo) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s AwsIotAnalyticsParameters) GoString() string { +func (s DataSourceErrorInfo) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *AwsIotAnalyticsParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AwsIotAnalyticsParameters"} - if s.DataSetName == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetName")) - } - if s.DataSetName != nil && len(*s.DataSetName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetMessage sets the Message field's value. +func (s *DataSourceErrorInfo) SetMessage(v string) *DataSourceErrorInfo { + s.Message = &v + return s } -// SetDataSetName sets the DataSetName field's value. -func (s *AwsIotAnalyticsParameters) SetDataSetName(v string) *AwsIotAnalyticsParameters { - s.DataSetName = &v +// SetType sets the Type field's value. +func (s *DataSourceErrorInfo) SetType(v string) *DataSourceErrorInfo { + s.Type = &v return s } -// A calculated column for a dataset. -type CalculatedColumn struct { +// The parameters that Amazon QuickSight uses to connect to your underlying +// data source. This is a variant type structure. For this structure to be valid, +// only one of the attributes can be non-null. +type DataSourceParameters struct { _ struct{} `type:"structure"` - // A unique ID to identify a calculated column. During a dataset update, if - // the column ID of a calculated column matches that of an existing calculated - // column, Amazon QuickSight preserves the existing calculated column. - // - // ColumnId is a required field - ColumnId *string `min:"1" type:"string" required:"true"` + // Amazon Elasticsearch Service parameters. + AmazonElasticsearchParameters *AmazonElasticsearchParameters `type:"structure"` - // Column name. - // - // ColumnName is a required field - ColumnName *string `min:"1" type:"string" required:"true"` + // Amazon Athena parameters. + AthenaParameters *AthenaParameters `type:"structure"` - // An expression that defines the calculated column. - // - // Expression is a required field - Expression *string `min:"1" type:"string" required:"true"` -} + // Amazon Aurora MySQL parameters. + AuroraParameters *AuroraParameters `type:"structure"` -// String returns the string representation -func (s CalculatedColumn) String() string { - return awsutil.Prettify(s) -} + // Aurora PostgreSQL parameters. + AuroraPostgreSqlParameters *AuroraPostgreSqlParameters `type:"structure"` -// GoString returns the string representation -func (s CalculatedColumn) GoString() string { - return s.String() -} + // AWS IoT Analytics parameters. + AwsIotAnalyticsParameters *AwsIotAnalyticsParameters `type:"structure"` -// Validate inspects the fields of the type to determine if they are valid. -func (s *CalculatedColumn) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CalculatedColumn"} - if s.ColumnId == nil { - invalidParams.Add(request.NewErrParamRequired("ColumnId")) - } - if s.ColumnId != nil && len(*s.ColumnId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ColumnId", 1)) - } - if s.ColumnName == nil { - invalidParams.Add(request.NewErrParamRequired("ColumnName")) - } - if s.ColumnName != nil && len(*s.ColumnName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ColumnName", 1)) - } - if s.Expression == nil { - invalidParams.Add(request.NewErrParamRequired("Expression")) - } - if s.Expression != nil && len(*s.Expression) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Expression", 1)) - } + // Jira parameters. + JiraParameters *JiraParameters `type:"structure"` - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} + // MariaDB parameters. + MariaDbParameters *MariaDbParameters `type:"structure"` -// SetColumnId sets the ColumnId field's value. -func (s *CalculatedColumn) SetColumnId(v string) *CalculatedColumn { - s.ColumnId = &v - return s -} + // MySQL parameters. + MySqlParameters *MySqlParameters `type:"structure"` -// SetColumnName sets the ColumnName field's value. -func (s *CalculatedColumn) SetColumnName(v string) *CalculatedColumn { - s.ColumnName = &v - return s -} + // PostgreSQL parameters. + PostgreSqlParameters *PostgreSqlParameters `type:"structure"` -// SetExpression sets the Expression field's value. -func (s *CalculatedColumn) SetExpression(v string) *CalculatedColumn { - s.Expression = &v - return s -} + // Presto parameters. + PrestoParameters *PrestoParameters `type:"structure"` -type CancelIngestionInput struct { - _ struct{} `type:"structure"` + // Amazon RDS parameters. + RdsParameters *RdsParameters `type:"structure"` - // The AWS account ID. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // Amazon Redshift parameters. + RedshiftParameters *RedshiftParameters `type:"structure"` - // The ID of the dataset used in the ingestion. - // - // DataSetId is a required field - DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` + // S3 parameters. + S3Parameters *S3Parameters `type:"structure"` - // An ID for the ingestion. - // - // IngestionId is a required field - IngestionId *string `location:"uri" locationName:"IngestionId" min:"1" type:"string" required:"true"` + // ServiceNow parameters. + ServiceNowParameters *ServiceNowParameters `type:"structure"` + + // Snowflake parameters. + SnowflakeParameters *SnowflakeParameters `type:"structure"` + + // Spark parameters. + SparkParameters *SparkParameters `type:"structure"` + + // SQL Server parameters. + SqlServerParameters *SqlServerParameters `type:"structure"` + + // Teradata parameters. + TeradataParameters *TeradataParameters `type:"structure"` + + // Twitter parameters. + TwitterParameters *TwitterParameters `type:"structure"` } // String returns the string representation -func (s CancelIngestionInput) String() string { +func (s DataSourceParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CancelIngestionInput) GoString() string { +func (s DataSourceParameters) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CancelIngestionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CancelIngestionInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) +func (s *DataSourceParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DataSourceParameters"} + if s.AmazonElasticsearchParameters != nil { + if err := s.AmazonElasticsearchParameters.Validate(); err != nil { + invalidParams.AddNested("AmazonElasticsearchParameters", err.(request.ErrInvalidParams)) + } + } + if s.AthenaParameters != nil { + if err := s.AthenaParameters.Validate(); err != nil { + invalidParams.AddNested("AthenaParameters", err.(request.ErrInvalidParams)) + } + } + if s.AuroraParameters != nil { + if err := s.AuroraParameters.Validate(); err != nil { + invalidParams.AddNested("AuroraParameters", err.(request.ErrInvalidParams)) + } + } + if s.AuroraPostgreSqlParameters != nil { + if err := s.AuroraPostgreSqlParameters.Validate(); err != nil { + invalidParams.AddNested("AuroraPostgreSqlParameters", err.(request.ErrInvalidParams)) + } + } + if s.AwsIotAnalyticsParameters != nil { + if err := s.AwsIotAnalyticsParameters.Validate(); err != nil { + invalidParams.AddNested("AwsIotAnalyticsParameters", err.(request.ErrInvalidParams)) + } + } + if s.JiraParameters != nil { + if err := s.JiraParameters.Validate(); err != nil { + invalidParams.AddNested("JiraParameters", err.(request.ErrInvalidParams)) + } } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + if s.MariaDbParameters != nil { + if err := s.MariaDbParameters.Validate(); err != nil { + invalidParams.AddNested("MariaDbParameters", err.(request.ErrInvalidParams)) + } } - if s.DataSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetId")) + if s.MySqlParameters != nil { + if err := s.MySqlParameters.Validate(); err != nil { + invalidParams.AddNested("MySqlParameters", err.(request.ErrInvalidParams)) + } } - if s.DataSetId != nil && len(*s.DataSetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) + if s.PostgreSqlParameters != nil { + if err := s.PostgreSqlParameters.Validate(); err != nil { + invalidParams.AddNested("PostgreSqlParameters", err.(request.ErrInvalidParams)) + } } - if s.IngestionId == nil { - invalidParams.Add(request.NewErrParamRequired("IngestionId")) + if s.PrestoParameters != nil { + if err := s.PrestoParameters.Validate(); err != nil { + invalidParams.AddNested("PrestoParameters", err.(request.ErrInvalidParams)) + } } - if s.IngestionId != nil && len(*s.IngestionId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("IngestionId", 1)) + if s.RdsParameters != nil { + if err := s.RdsParameters.Validate(); err != nil { + invalidParams.AddNested("RdsParameters", err.(request.ErrInvalidParams)) + } + } + if s.RedshiftParameters != nil { + if err := s.RedshiftParameters.Validate(); err != nil { + invalidParams.AddNested("RedshiftParameters", err.(request.ErrInvalidParams)) + } + } + if s.S3Parameters != nil { + if err := s.S3Parameters.Validate(); err != nil { + invalidParams.AddNested("S3Parameters", err.(request.ErrInvalidParams)) + } + } + if s.ServiceNowParameters != nil { + if err := s.ServiceNowParameters.Validate(); err != nil { + invalidParams.AddNested("ServiceNowParameters", err.(request.ErrInvalidParams)) + } + } + if s.SnowflakeParameters != nil { + if err := s.SnowflakeParameters.Validate(); err != nil { + invalidParams.AddNested("SnowflakeParameters", err.(request.ErrInvalidParams)) + } + } + if s.SparkParameters != nil { + if err := s.SparkParameters.Validate(); err != nil { + invalidParams.AddNested("SparkParameters", err.(request.ErrInvalidParams)) + } + } + if s.SqlServerParameters != nil { + if err := s.SqlServerParameters.Validate(); err != nil { + invalidParams.AddNested("SqlServerParameters", err.(request.ErrInvalidParams)) + } + } + if s.TeradataParameters != nil { + if err := s.TeradataParameters.Validate(); err != nil { + invalidParams.AddNested("TeradataParameters", err.(request.ErrInvalidParams)) + } + } + if s.TwitterParameters != nil { + if err := s.TwitterParameters.Validate(); err != nil { + invalidParams.AddNested("TwitterParameters", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -7690,896 +14816,787 @@ func (s *CancelIngestionInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *CancelIngestionInput) SetAwsAccountId(v string) *CancelIngestionInput { - s.AwsAccountId = &v +// SetAmazonElasticsearchParameters sets the AmazonElasticsearchParameters field's value. +func (s *DataSourceParameters) SetAmazonElasticsearchParameters(v *AmazonElasticsearchParameters) *DataSourceParameters { + s.AmazonElasticsearchParameters = v return s } -// SetDataSetId sets the DataSetId field's value. -func (s *CancelIngestionInput) SetDataSetId(v string) *CancelIngestionInput { - s.DataSetId = &v +// SetAthenaParameters sets the AthenaParameters field's value. +func (s *DataSourceParameters) SetAthenaParameters(v *AthenaParameters) *DataSourceParameters { + s.AthenaParameters = v return s } -// SetIngestionId sets the IngestionId field's value. -func (s *CancelIngestionInput) SetIngestionId(v string) *CancelIngestionInput { - s.IngestionId = &v +// SetAuroraParameters sets the AuroraParameters field's value. +func (s *DataSourceParameters) SetAuroraParameters(v *AuroraParameters) *DataSourceParameters { + s.AuroraParameters = v return s } -type CancelIngestionOutput struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) for the data ingestion. - Arn *string `type:"string"` - - // An ID for the ingestion. - IngestionId *string `min:"1" type:"string"` - - // The AWS request ID for this operation. - RequestId *string `type:"string"` - - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` -} - -// String returns the string representation -func (s CancelIngestionOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CancelIngestionOutput) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *CancelIngestionOutput) SetArn(v string) *CancelIngestionOutput { - s.Arn = &v +// SetAuroraPostgreSqlParameters sets the AuroraPostgreSqlParameters field's value. +func (s *DataSourceParameters) SetAuroraPostgreSqlParameters(v *AuroraPostgreSqlParameters) *DataSourceParameters { + s.AuroraPostgreSqlParameters = v return s } -// SetIngestionId sets the IngestionId field's value. -func (s *CancelIngestionOutput) SetIngestionId(v string) *CancelIngestionOutput { - s.IngestionId = &v +// SetAwsIotAnalyticsParameters sets the AwsIotAnalyticsParameters field's value. +func (s *DataSourceParameters) SetAwsIotAnalyticsParameters(v *AwsIotAnalyticsParameters) *DataSourceParameters { + s.AwsIotAnalyticsParameters = v return s } -// SetRequestId sets the RequestId field's value. -func (s *CancelIngestionOutput) SetRequestId(v string) *CancelIngestionOutput { - s.RequestId = &v +// SetJiraParameters sets the JiraParameters field's value. +func (s *DataSourceParameters) SetJiraParameters(v *JiraParameters) *DataSourceParameters { + s.JiraParameters = v return s } -// SetStatus sets the Status field's value. -func (s *CancelIngestionOutput) SetStatus(v int64) *CancelIngestionOutput { - s.Status = &v +// SetMariaDbParameters sets the MariaDbParameters field's value. +func (s *DataSourceParameters) SetMariaDbParameters(v *MariaDbParameters) *DataSourceParameters { + s.MariaDbParameters = v return s } -// A transform operation that casts a column to a different type. -type CastColumnTypeOperation struct { - _ struct{} `type:"structure"` - - // Column name. - // - // ColumnName is a required field - ColumnName *string `min:"1" type:"string" required:"true"` - - // When casting a column from string to datetime type, you can supply a string - // in a format supported by Amazon QuickSight to denote the source data format. - Format *string `type:"string"` - - // New column data type. - // - // NewColumnType is a required field - NewColumnType *string `type:"string" required:"true" enum:"ColumnDataType"` -} - -// String returns the string representation -func (s CastColumnTypeOperation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CastColumnTypeOperation) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CastColumnTypeOperation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CastColumnTypeOperation"} - if s.ColumnName == nil { - invalidParams.Add(request.NewErrParamRequired("ColumnName")) - } - if s.ColumnName != nil && len(*s.ColumnName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ColumnName", 1)) - } - if s.NewColumnType == nil { - invalidParams.Add(request.NewErrParamRequired("NewColumnType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetColumnName sets the ColumnName field's value. -func (s *CastColumnTypeOperation) SetColumnName(v string) *CastColumnTypeOperation { - s.ColumnName = &v +// SetMySqlParameters sets the MySqlParameters field's value. +func (s *DataSourceParameters) SetMySqlParameters(v *MySqlParameters) *DataSourceParameters { + s.MySqlParameters = v return s } -// SetFormat sets the Format field's value. -func (s *CastColumnTypeOperation) SetFormat(v string) *CastColumnTypeOperation { - s.Format = &v +// SetPostgreSqlParameters sets the PostgreSqlParameters field's value. +func (s *DataSourceParameters) SetPostgreSqlParameters(v *PostgreSqlParameters) *DataSourceParameters { + s.PostgreSqlParameters = v return s } -// SetNewColumnType sets the NewColumnType field's value. -func (s *CastColumnTypeOperation) SetNewColumnType(v string) *CastColumnTypeOperation { - s.NewColumnType = &v +// SetPrestoParameters sets the PrestoParameters field's value. +func (s *DataSourceParameters) SetPrestoParameters(v *PrestoParameters) *DataSourceParameters { + s.PrestoParameters = v return s } -// Groupings of columns that work together in certain Amazon QuickSight features. -// This is a variant type structure. For this structure to be valid, only one -// of the attributes can be non-null. -type ColumnGroup struct { - _ struct{} `type:"structure"` - - // Geospatial column group that denotes a hierarchy. - GeoSpatialColumnGroup *GeoSpatialColumnGroup `type:"structure"` +// SetRdsParameters sets the RdsParameters field's value. +func (s *DataSourceParameters) SetRdsParameters(v *RdsParameters) *DataSourceParameters { + s.RdsParameters = v + return s } -// String returns the string representation -func (s ColumnGroup) String() string { - return awsutil.Prettify(s) +// SetRedshiftParameters sets the RedshiftParameters field's value. +func (s *DataSourceParameters) SetRedshiftParameters(v *RedshiftParameters) *DataSourceParameters { + s.RedshiftParameters = v + return s } -// GoString returns the string representation -func (s ColumnGroup) GoString() string { - return s.String() +// SetS3Parameters sets the S3Parameters field's value. +func (s *DataSourceParameters) SetS3Parameters(v *S3Parameters) *DataSourceParameters { + s.S3Parameters = v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ColumnGroup) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ColumnGroup"} - if s.GeoSpatialColumnGroup != nil { - if err := s.GeoSpatialColumnGroup.Validate(); err != nil { - invalidParams.AddNested("GeoSpatialColumnGroup", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetServiceNowParameters sets the ServiceNowParameters field's value. +func (s *DataSourceParameters) SetServiceNowParameters(v *ServiceNowParameters) *DataSourceParameters { + s.ServiceNowParameters = v + return s } -// SetGeoSpatialColumnGroup sets the GeoSpatialColumnGroup field's value. -func (s *ColumnGroup) SetGeoSpatialColumnGroup(v *GeoSpatialColumnGroup) *ColumnGroup { - s.GeoSpatialColumnGroup = v +// SetSnowflakeParameters sets the SnowflakeParameters field's value. +func (s *DataSourceParameters) SetSnowflakeParameters(v *SnowflakeParameters) *DataSourceParameters { + s.SnowflakeParameters = v return s } -// A structure describing the name, data type, and geographic role of the columns. -type ColumnGroupColumnSchema struct { - _ struct{} `type:"structure"` - - // The name of the column group's column schema. - Name *string `type:"string"` +// SetSparkParameters sets the SparkParameters field's value. +func (s *DataSourceParameters) SetSparkParameters(v *SparkParameters) *DataSourceParameters { + s.SparkParameters = v + return s } -// String returns the string representation -func (s ColumnGroupColumnSchema) String() string { - return awsutil.Prettify(s) +// SetSqlServerParameters sets the SqlServerParameters field's value. +func (s *DataSourceParameters) SetSqlServerParameters(v *SqlServerParameters) *DataSourceParameters { + s.SqlServerParameters = v + return s } -// GoString returns the string representation -func (s ColumnGroupColumnSchema) GoString() string { - return s.String() +// SetTeradataParameters sets the TeradataParameters field's value. +func (s *DataSourceParameters) SetTeradataParameters(v *TeradataParameters) *DataSourceParameters { + s.TeradataParameters = v + return s } -// SetName sets the Name field's value. -func (s *ColumnGroupColumnSchema) SetName(v string) *ColumnGroupColumnSchema { - s.Name = &v +// SetTwitterParameters sets the TwitterParameters field's value. +func (s *DataSourceParameters) SetTwitterParameters(v *TwitterParameters) *DataSourceParameters { + s.TwitterParameters = v return s } -// The column group schema. -type ColumnGroupSchema struct { +// Date time parameter. +type DateTimeParameter struct { _ struct{} `type:"structure"` - // A structure containing the list of schemas for column group columns. - ColumnGroupColumnSchemaList []*ColumnGroupColumnSchema `type:"list"` + // A display name for the dataset. + // + // Name is a required field + Name *string `type:"string" required:"true"` - // The name of the column group schema. - Name *string `type:"string"` + // Values. + // + // Values is a required field + Values []*time.Time `type:"list" required:"true"` } // String returns the string representation -func (s ColumnGroupSchema) String() string { +func (s DateTimeParameter) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ColumnGroupSchema) GoString() string { +func (s DateTimeParameter) GoString() string { return s.String() } -// SetColumnGroupColumnSchemaList sets the ColumnGroupColumnSchemaList field's value. -func (s *ColumnGroupSchema) SetColumnGroupColumnSchemaList(v []*ColumnGroupColumnSchema) *ColumnGroupSchema { - s.ColumnGroupColumnSchemaList = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *DateTimeParameter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DateTimeParameter"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Values == nil { + invalidParams.Add(request.NewErrParamRequired("Values")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } // SetName sets the Name field's value. -func (s *ColumnGroupSchema) SetName(v string) *ColumnGroupSchema { +func (s *DateTimeParameter) SetName(v string) *DateTimeParameter { s.Name = &v return s } -// The column schema. -type ColumnSchema struct { - _ struct{} `type:"structure"` +// SetValues sets the Values field's value. +func (s *DateTimeParameter) SetValues(v []*time.Time) *DateTimeParameter { + s.Values = v + return s +} - // The data type of the column schema. - DataType *string `type:"string"` +// Decimal parameter. +type DecimalParameter struct { + _ struct{} `type:"structure"` - // The geographic role of the column schema. - GeographicRole *string `type:"string"` + // A display name for the dataset. + // + // Name is a required field + Name *string `type:"string" required:"true"` - // The name of the column schema. - Name *string `type:"string"` + // Values. + // + // Values is a required field + Values []*float64 `type:"list" required:"true"` } // String returns the string representation -func (s ColumnSchema) String() string { +func (s DecimalParameter) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ColumnSchema) GoString() string { +func (s DecimalParameter) GoString() string { return s.String() } -// SetDataType sets the DataType field's value. -func (s *ColumnSchema) SetDataType(v string) *ColumnSchema { - s.DataType = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *DecimalParameter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DecimalParameter"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Values == nil { + invalidParams.Add(request.NewErrParamRequired("Values")) + } -// SetGeographicRole sets the GeographicRole field's value. -func (s *ColumnSchema) SetGeographicRole(v string) *ColumnSchema { - s.GeographicRole = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } // SetName sets the Name field's value. -func (s *ColumnSchema) SetName(v string) *ColumnSchema { +func (s *DecimalParameter) SetName(v string) *DecimalParameter { s.Name = &v return s } -// A tag for a column in a TagColumnOperation structure. This is a variant type -// structure. For this structure to be valid, only one of the attributes can -// be non-null. -type ColumnTag struct { +// SetValues sets the Values field's value. +func (s *DecimalParameter) SetValues(v []*float64) *DecimalParameter { + s.Values = v + return s +} + +type DeleteAccountCustomizationInput struct { _ struct{} `type:"structure"` - // A geospatial role for a column. - ColumnGeographicRole *string `type:"string" enum:"GeoSpatialDataRole"` + // The ID for the AWS account that you want to delete QuickSight customizations + // from. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The namespace associated with the customization that you're deleting. + Namespace *string `location:"querystring" locationName:"namespace" type:"string"` } // String returns the string representation -func (s ColumnTag) String() string { +func (s DeleteAccountCustomizationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ColumnTag) GoString() string { +func (s DeleteAccountCustomizationInput) GoString() string { return s.String() } -// SetColumnGeographicRole sets the ColumnGeographicRole field's value. -func (s *ColumnTag) SetColumnGeographicRole(v string) *ColumnTag { - s.ColumnGeographicRole = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteAccountCustomizationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteAccountCustomizationInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DeleteAccountCustomizationInput) SetAwsAccountId(v string) *DeleteAccountCustomizationInput { + s.AwsAccountId = &v return s } -// A resource is already in a state that indicates an action is happening that -// must complete before a new update can be applied. -type ConcurrentUpdatingException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +// SetNamespace sets the Namespace field's value. +func (s *DeleteAccountCustomizationInput) SetNamespace(v string) *DeleteAccountCustomizationInput { + s.Namespace = &v + return s +} - Message_ *string `locationName:"Message" type:"string"` +type DeleteAccountCustomizationOutput struct { + _ struct{} `type:"structure"` + // The AWS request ID for this operation. RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s ConcurrentUpdatingException) String() string { +func (s DeleteAccountCustomizationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ConcurrentUpdatingException) GoString() string { +func (s DeleteAccountCustomizationOutput) GoString() string { return s.String() } -func newErrorConcurrentUpdatingException(v protocol.ResponseMetadata) error { - return &ConcurrentUpdatingException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ConcurrentUpdatingException) Code() string { - return "ConcurrentUpdatingException" -} - -// Message returns the exception's message. -func (s *ConcurrentUpdatingException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ConcurrentUpdatingException) OrigErr() error { - return nil -} - -func (s *ConcurrentUpdatingException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetRequestId sets the RequestId field's value. +func (s *DeleteAccountCustomizationOutput) SetRequestId(v string) *DeleteAccountCustomizationOutput { + s.RequestId = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *ConcurrentUpdatingException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetStatus sets the Status field's value. +func (s *DeleteAccountCustomizationOutput) SetStatus(v int64) *DeleteAccountCustomizationOutput { + s.Status = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *ConcurrentUpdatingException) RequestID() string { - return s.RespMetadata.RequestID -} +type DeleteDashboardInput struct { + _ struct{} `type:"structure"` -// Updating or deleting a resource can cause an inconsistent state. -type ConflictException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + // The ID of the AWS account that contains the dashboard that you're deleting. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - Message_ *string `locationName:"Message" type:"string"` + // The ID for the dashboard. + // + // DashboardId is a required field + DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` - // The AWS request ID for this request. - RequestId *string `type:"string"` + // The version number of the dashboard. If the version number property is provided, + // only the specified version of the dashboard is deleted. + VersionNumber *int64 `location:"querystring" locationName:"version-number" min:"1" type:"long"` } // String returns the string representation -func (s ConflictException) String() string { +func (s DeleteDashboardInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ConflictException) GoString() string { +func (s DeleteDashboardInput) GoString() string { return s.String() } -func newErrorConflictException(v protocol.ResponseMetadata) error { - return &ConflictException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteDashboardInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDashboardInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DashboardId == nil { + invalidParams.Add(request.NewErrParamRequired("DashboardId")) + } + if s.DashboardId != nil && len(*s.DashboardId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) } -} - -// Code returns the exception type name. -func (s *ConflictException) Code() string { - return "ConflictException" -} - -// Message returns the exception's message. -func (s *ConflictException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if s.VersionNumber != nil && *s.VersionNumber < 1 { + invalidParams.Add(request.NewErrParamMinValue("VersionNumber", 1)) } - return "" -} -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ConflictException) OrigErr() error { + if invalidParams.Len() > 0 { + return invalidParams + } return nil } -func (s *ConflictException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DeleteDashboardInput) SetAwsAccountId(v string) *DeleteDashboardInput { + s.AwsAccountId = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *ConflictException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetDashboardId sets the DashboardId field's value. +func (s *DeleteDashboardInput) SetDashboardId(v string) *DeleteDashboardInput { + s.DashboardId = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *ConflictException) RequestID() string { - return s.RespMetadata.RequestID +// SetVersionNumber sets the VersionNumber field's value. +func (s *DeleteDashboardInput) SetVersionNumber(v int64) *DeleteDashboardInput { + s.VersionNumber = &v + return s } -// A transform operation that creates calculated columns. Columns created in -// one such operation form a lexical closure. -type CreateColumnsOperation struct { +type DeleteDashboardOutput struct { _ struct{} `type:"structure"` - // Calculated columns to create. - // - // Columns is a required field - Columns []*CalculatedColumn `min:"1" type:"list" required:"true"` + // The Secure Socket Layer (SSL) properties that apply for the resource. + Arn *string `type:"string"` + + // The ID of the dashboard. + DashboardId *string `min:"1" type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s CreateColumnsOperation) String() string { +func (s DeleteDashboardOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateColumnsOperation) GoString() string { +func (s DeleteDashboardOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateColumnsOperation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateColumnsOperation"} - if s.Columns == nil { - invalidParams.Add(request.NewErrParamRequired("Columns")) - } - if s.Columns != nil && len(s.Columns) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Columns", 1)) - } - if s.Columns != nil { - for i, v := range s.Columns { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Columns", i), err.(request.ErrInvalidParams)) - } - } - } +// SetArn sets the Arn field's value. +func (s *DeleteDashboardOutput) SetArn(v string) *DeleteDashboardOutput { + s.Arn = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetDashboardId sets the DashboardId field's value. +func (s *DeleteDashboardOutput) SetDashboardId(v string) *DeleteDashboardOutput { + s.DashboardId = &v + return s } -// SetColumns sets the Columns field's value. -func (s *CreateColumnsOperation) SetColumns(v []*CalculatedColumn) *CreateColumnsOperation { - s.Columns = v +// SetRequestId sets the RequestId field's value. +func (s *DeleteDashboardOutput) SetRequestId(v string) *DeleteDashboardOutput { + s.RequestId = &v return s } -type CreateDashboardInput struct { +// SetStatus sets the Status field's value. +func (s *DeleteDashboardOutput) SetStatus(v int64) *DeleteDashboardOutput { + s.Status = &v + return s +} + +type DeleteDataSetInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account where you want to create the dashboard. + // The AWS account ID. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the dashboard, also added to the IAM policy. - // - // DashboardId is a required field - DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` - - // Options for publishing the dashboard when you create it: - // - // * AvailabilityStatus for AdHocFilteringOption - This status can be either - // ENABLED or DISABLED. When this is set to DISABLED, QuickSight disables - // the left filter pane on the published dashboard, which can be used for - // ad hoc (one-time) filtering. This option is ENABLED by default. - // - // * AvailabilityStatus for ExportToCSVOption - This status can be either - // ENABLED or DISABLED. The visual option to export data to .csv format isn't - // enabled when this is set to DISABLED. This option is ENABLED by default. - // - // * VisibilityState for SheetControlsOption - This visibility state can - // be either COLLAPSED or EXPANDED. The sheet controls pane is collapsed - // by default when set to true. This option is COLLAPSED by default. - DashboardPublishOptions *DashboardPublishOptions `type:"structure"` - - // The display name of the dashboard. - // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` - - // A structure that contains the parameters of the dashboard. These are parameter - // overrides for a dashboard. A dashboard can have any type of parameters, and - // some parameters might accept multiple values. You can use the dashboard permissions - // structure described following to override two string parameters that accept - // multiple values. - Parameters *Parameters `type:"structure"` - - // A structure that contains the permissions of the dashboard. You can use this - // structure for granting permissions with principal and action information. - Permissions []*ResourcePermission `min:"1" type:"list"` - - // The source entity from which the dashboard is created. The source entity - // accepts the Amazon Resource Name (ARN) of the source template or analysis - // and also references the replacement datasets for the placeholders set when - // creating the template. The replacement datasets need to follow the same schema - // as the datasets for which placeholders were created when creating the template. - // - // If you are creating a dashboard from a source entity in a different AWS account, - // use the ARN of the source template. + // The ID for the dataset that you want to create. This ID is unique per AWS + // Region for each AWS account. // - // SourceEntity is a required field - SourceEntity *DashboardSourceEntity `type:"structure" required:"true"` - - // Contains a map of the key-value pairs for the resource tag or tags assigned - // to the dashboard. - Tags []*Tag `min:"1" type:"list"` - - // A description for the first version of the dashboard being created. - VersionDescription *string `min:"1" type:"string"` + // DataSetId is a required field + DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` } // String returns the string representation -func (s CreateDashboardInput) String() string { +func (s DeleteDataSetInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDashboardInput) GoString() string { +func (s DeleteDataSetInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDashboardInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDashboardInput"} +func (s *DeleteDataSetInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDataSetInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DashboardId == nil { - invalidParams.Add(request.NewErrParamRequired("DashboardId")) - } - if s.DashboardId != nil && len(*s.DashboardId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.Permissions != nil && len(s.Permissions) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Permissions", 1)) - } - if s.SourceEntity == nil { - invalidParams.Add(request.NewErrParamRequired("SourceEntity")) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - if s.VersionDescription != nil && len(*s.VersionDescription) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VersionDescription", 1)) - } - if s.Parameters != nil { - if err := s.Parameters.Validate(); err != nil { - invalidParams.AddNested("Parameters", err.(request.ErrInvalidParams)) - } - } - if s.Permissions != nil { - for i, v := range s.Permissions { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Permissions", i), err.(request.ErrInvalidParams)) - } - } + if s.DataSetId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetId")) } - if s.SourceEntity != nil { - if err := s.SourceEntity.Validate(); err != nil { - invalidParams.AddNested("SourceEntity", err.(request.ErrInvalidParams)) - } + if s.DataSetId != nil && len(*s.DataSetId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) } - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } + + if invalidParams.Len() > 0 { + return invalidParams } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DeleteDataSetInput) SetAwsAccountId(v string) *DeleteDataSetInput { + s.AwsAccountId = &v + return s +} + +// SetDataSetId sets the DataSetId field's value. +func (s *DeleteDataSetInput) SetDataSetId(v string) *DeleteDataSetInput { + s.DataSetId = &v + return s +} + +type DeleteDataSetOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the dataset. + Arn *string `type:"string"` + + // The ID for the dataset that you want to create. This ID is unique per AWS + // Region for each AWS account. + DataSetId *string `type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// String returns the string representation +func (s DeleteDataSetOutput) String() string { + return awsutil.Prettify(s) } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *CreateDashboardInput) SetAwsAccountId(v string) *CreateDashboardInput { - s.AwsAccountId = &v - return s +// GoString returns the string representation +func (s DeleteDataSetOutput) GoString() string { + return s.String() } -// SetDashboardId sets the DashboardId field's value. -func (s *CreateDashboardInput) SetDashboardId(v string) *CreateDashboardInput { - s.DashboardId = &v +// SetArn sets the Arn field's value. +func (s *DeleteDataSetOutput) SetArn(v string) *DeleteDataSetOutput { + s.Arn = &v return s } -// SetDashboardPublishOptions sets the DashboardPublishOptions field's value. -func (s *CreateDashboardInput) SetDashboardPublishOptions(v *DashboardPublishOptions) *CreateDashboardInput { - s.DashboardPublishOptions = v +// SetDataSetId sets the DataSetId field's value. +func (s *DeleteDataSetOutput) SetDataSetId(v string) *DeleteDataSetOutput { + s.DataSetId = &v return s } -// SetName sets the Name field's value. -func (s *CreateDashboardInput) SetName(v string) *CreateDashboardInput { - s.Name = &v +// SetRequestId sets the RequestId field's value. +func (s *DeleteDataSetOutput) SetRequestId(v string) *DeleteDataSetOutput { + s.RequestId = &v return s } -// SetParameters sets the Parameters field's value. -func (s *CreateDashboardInput) SetParameters(v *Parameters) *CreateDashboardInput { - s.Parameters = v +// SetStatus sets the Status field's value. +func (s *DeleteDataSetOutput) SetStatus(v int64) *DeleteDataSetOutput { + s.Status = &v return s } -// SetPermissions sets the Permissions field's value. -func (s *CreateDashboardInput) SetPermissions(v []*ResourcePermission) *CreateDashboardInput { - s.Permissions = v - return s +type DeleteDataSourceInput struct { + _ struct{} `type:"structure"` + + // The AWS account ID. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The ID of the data source. This ID is unique per AWS Region for each AWS + // account. + // + // DataSourceId is a required field + DataSourceId *string `location:"uri" locationName:"DataSourceId" type:"string" required:"true"` } -// SetSourceEntity sets the SourceEntity field's value. -func (s *CreateDashboardInput) SetSourceEntity(v *DashboardSourceEntity) *CreateDashboardInput { - s.SourceEntity = v - return s +// String returns the string representation +func (s DeleteDataSourceInput) String() string { + return awsutil.Prettify(s) } -// SetTags sets the Tags field's value. -func (s *CreateDashboardInput) SetTags(v []*Tag) *CreateDashboardInput { - s.Tags = v +// GoString returns the string representation +func (s DeleteDataSourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteDataSourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteDataSourceInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DataSourceId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSourceId")) + } + if s.DataSourceId != nil && len(*s.DataSourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSourceId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DeleteDataSourceInput) SetAwsAccountId(v string) *DeleteDataSourceInput { + s.AwsAccountId = &v return s } -// SetVersionDescription sets the VersionDescription field's value. -func (s *CreateDashboardInput) SetVersionDescription(v string) *CreateDashboardInput { - s.VersionDescription = &v +// SetDataSourceId sets the DataSourceId field's value. +func (s *DeleteDataSourceInput) SetDataSourceId(v string) *DeleteDataSourceInput { + s.DataSourceId = &v return s } -type CreateDashboardOutput struct { +type DeleteDataSourceOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the dashboard. + // The Amazon Resource Name (ARN) of the data source that you deleted. Arn *string `type:"string"` - // The status of the dashboard creation request. - CreationStatus *string `type:"string" enum:"ResourceStatus"` - - // The ID for the dashboard. - DashboardId *string `min:"1" type:"string"` + // The ID of the data source. This ID is unique per AWS Region for each AWS + // account. + DataSourceId *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - - // The ARN of the dashboard, including the version number of the first version - // that is created. - VersionArn *string `type:"string"` } // String returns the string representation -func (s CreateDashboardOutput) String() string { +func (s DeleteDataSourceOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDashboardOutput) GoString() string { +func (s DeleteDataSourceOutput) GoString() string { return s.String() } // SetArn sets the Arn field's value. -func (s *CreateDashboardOutput) SetArn(v string) *CreateDashboardOutput { +func (s *DeleteDataSourceOutput) SetArn(v string) *DeleteDataSourceOutput { s.Arn = &v return s } -// SetCreationStatus sets the CreationStatus field's value. -func (s *CreateDashboardOutput) SetCreationStatus(v string) *CreateDashboardOutput { - s.CreationStatus = &v - return s -} - -// SetDashboardId sets the DashboardId field's value. -func (s *CreateDashboardOutput) SetDashboardId(v string) *CreateDashboardOutput { - s.DashboardId = &v +// SetDataSourceId sets the DataSourceId field's value. +func (s *DeleteDataSourceOutput) SetDataSourceId(v string) *DeleteDataSourceOutput { + s.DataSourceId = &v return s } // SetRequestId sets the RequestId field's value. -func (s *CreateDashboardOutput) SetRequestId(v string) *CreateDashboardOutput { +func (s *DeleteDataSourceOutput) SetRequestId(v string) *DeleteDataSourceOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *CreateDashboardOutput) SetStatus(v int64) *CreateDashboardOutput { +func (s *DeleteDataSourceOutput) SetStatus(v int64) *DeleteDataSourceOutput { s.Status = &v return s } -// SetVersionArn sets the VersionArn field's value. -func (s *CreateDashboardOutput) SetVersionArn(v string) *CreateDashboardOutput { - s.VersionArn = &v - return s -} - -type CreateDataSetInput struct { +type DeleteGroupInput struct { _ struct{} `type:"structure"` - // The AWS account ID. + // The ID for the AWS account that the group is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Groupings of columns that work together in certain QuickSight features. Currently, - // only geospatial hierarchy is supported. - ColumnGroups []*ColumnGroup `min:"1" type:"list"` - - // An ID for the dataset that you want to create. This ID is unique per AWS - // Region for each AWS account. + // The name of the group that you want to delete. // - // DataSetId is a required field - DataSetId *string `type:"string" required:"true"` + // GroupName is a required field + GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` - // Indicates whether you want to import the data into SPICE. + // The namespace. Currently, you should set this to default. // - // ImportMode is a required field - ImportMode *string `type:"string" required:"true" enum:"DataSetImportMode"` + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` +} - // Configures the combination and transformation of the data from the physical - // tables. - LogicalTableMap map[string]*LogicalTable `min:"1" type:"map"` +// String returns the string representation +func (s DeleteGroupInput) String() string { + return awsutil.Prettify(s) +} - // The display name for the dataset. - // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` +// GoString returns the string representation +func (s DeleteGroupInput) GoString() string { + return s.String() +} - // A list of resource permissions on the dataset. - Permissions []*ResourcePermission `min:"1" type:"list"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteGroupInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteGroupInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.GroupName == nil { + invalidParams.Add(request.NewErrParamRequired("GroupName")) + } + if s.GroupName != nil && len(*s.GroupName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } - // Declares the physical tables that are available in the underlying data sources. + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DeleteGroupInput) SetAwsAccountId(v string) *DeleteGroupInput { + s.AwsAccountId = &v + return s +} + +// SetGroupName sets the GroupName field's value. +func (s *DeleteGroupInput) SetGroupName(v string) *DeleteGroupInput { + s.GroupName = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *DeleteGroupInput) SetNamespace(v string) *DeleteGroupInput { + s.Namespace = &v + return s +} + +type DeleteGroupMembershipInput struct { + _ struct{} `type:"structure"` + + // The ID for the AWS account that the group is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. // - // PhysicalTableMap is a required field - PhysicalTableMap map[string]*PhysicalTable `min:"1" type:"map" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The row-level security configuration for the data that you want to create. - RowLevelPermissionDataSet *RowLevelPermissionDataSet `type:"structure"` + // The name of the group that you want to delete the user from. + // + // GroupName is a required field + GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` - // Contains a map of the key-value pairs for the resource tag or tags assigned - // to the dataset. - Tags []*Tag `min:"1" type:"list"` + // The name of the user that you want to delete from the group membership. + // + // MemberName is a required field + MemberName *string `location:"uri" locationName:"MemberName" min:"1" type:"string" required:"true"` + + // The namespace. Currently, you should set this to default. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` } // String returns the string representation -func (s CreateDataSetInput) String() string { +func (s DeleteGroupMembershipInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDataSetInput) GoString() string { +func (s DeleteGroupMembershipInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDataSetInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDataSetInput"} +func (s *DeleteGroupMembershipInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteGroupMembershipInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.ColumnGroups != nil && len(s.ColumnGroups) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ColumnGroups", 1)) - } - if s.DataSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetId")) - } - if s.ImportMode == nil { - invalidParams.Add(request.NewErrParamRequired("ImportMode")) - } - if s.LogicalTableMap != nil && len(s.LogicalTableMap) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogicalTableMap", 1)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.Permissions != nil && len(s.Permissions) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Permissions", 1)) - } - if s.PhysicalTableMap == nil { - invalidParams.Add(request.NewErrParamRequired("PhysicalTableMap")) - } - if s.PhysicalTableMap != nil && len(s.PhysicalTableMap) < 1 { - invalidParams.Add(request.NewErrParamMinLen("PhysicalTableMap", 1)) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - if s.ColumnGroups != nil { - for i, v := range s.ColumnGroups { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ColumnGroups", i), err.(request.ErrInvalidParams)) - } - } + if s.GroupName == nil { + invalidParams.Add(request.NewErrParamRequired("GroupName")) } - if s.LogicalTableMap != nil { - for i, v := range s.LogicalTableMap { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LogicalTableMap", i), err.(request.ErrInvalidParams)) - } - } + if s.GroupName != nil && len(*s.GroupName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) } - if s.Permissions != nil { - for i, v := range s.Permissions { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Permissions", i), err.(request.ErrInvalidParams)) - } - } + if s.MemberName == nil { + invalidParams.Add(request.NewErrParamRequired("MemberName")) } - if s.PhysicalTableMap != nil { - for i, v := range s.PhysicalTableMap { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "PhysicalTableMap", i), err.(request.ErrInvalidParams)) - } - } + if s.MemberName != nil && len(*s.MemberName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("MemberName", 1)) } - if s.RowLevelPermissionDataSet != nil { - if err := s.RowLevelPermissionDataSet.Validate(); err != nil { - invalidParams.AddNested("RowLevelPermissionDataSet", err.(request.ErrInvalidParams)) - } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) } - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) } if invalidParams.Len() > 0 { @@ -8589,83 +15606,64 @@ func (s *CreateDataSetInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *CreateDataSetInput) SetAwsAccountId(v string) *CreateDataSetInput { +func (s *DeleteGroupMembershipInput) SetAwsAccountId(v string) *DeleteGroupMembershipInput { s.AwsAccountId = &v return s } -// SetColumnGroups sets the ColumnGroups field's value. -func (s *CreateDataSetInput) SetColumnGroups(v []*ColumnGroup) *CreateDataSetInput { - s.ColumnGroups = v +// SetGroupName sets the GroupName field's value. +func (s *DeleteGroupMembershipInput) SetGroupName(v string) *DeleteGroupMembershipInput { + s.GroupName = &v return s } -// SetDataSetId sets the DataSetId field's value. -func (s *CreateDataSetInput) SetDataSetId(v string) *CreateDataSetInput { - s.DataSetId = &v +// SetMemberName sets the MemberName field's value. +func (s *DeleteGroupMembershipInput) SetMemberName(v string) *DeleteGroupMembershipInput { + s.MemberName = &v return s } -// SetImportMode sets the ImportMode field's value. -func (s *CreateDataSetInput) SetImportMode(v string) *CreateDataSetInput { - s.ImportMode = &v +// SetNamespace sets the Namespace field's value. +func (s *DeleteGroupMembershipInput) SetNamespace(v string) *DeleteGroupMembershipInput { + s.Namespace = &v return s } -// SetLogicalTableMap sets the LogicalTableMap field's value. -func (s *CreateDataSetInput) SetLogicalTableMap(v map[string]*LogicalTable) *CreateDataSetInput { - s.LogicalTableMap = v - return s -} +type DeleteGroupMembershipOutput struct { + _ struct{} `type:"structure"` -// SetName sets the Name field's value. -func (s *CreateDataSetInput) SetName(v string) *CreateDataSetInput { - s.Name = &v - return s + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } -// SetPermissions sets the Permissions field's value. -func (s *CreateDataSetInput) SetPermissions(v []*ResourcePermission) *CreateDataSetInput { - s.Permissions = v - return s +// String returns the string representation +func (s DeleteGroupMembershipOutput) String() string { + return awsutil.Prettify(s) } -// SetPhysicalTableMap sets the PhysicalTableMap field's value. -func (s *CreateDataSetInput) SetPhysicalTableMap(v map[string]*PhysicalTable) *CreateDataSetInput { - s.PhysicalTableMap = v - return s +// GoString returns the string representation +func (s DeleteGroupMembershipOutput) GoString() string { + return s.String() } -// SetRowLevelPermissionDataSet sets the RowLevelPermissionDataSet field's value. -func (s *CreateDataSetInput) SetRowLevelPermissionDataSet(v *RowLevelPermissionDataSet) *CreateDataSetInput { - s.RowLevelPermissionDataSet = v +// SetRequestId sets the RequestId field's value. +func (s *DeleteGroupMembershipOutput) SetRequestId(v string) *DeleteGroupMembershipOutput { + s.RequestId = &v return s } -// SetTags sets the Tags field's value. -func (s *CreateDataSetInput) SetTags(v []*Tag) *CreateDataSetInput { - s.Tags = v +// SetStatus sets the Status field's value. +func (s *DeleteGroupMembershipOutput) SetStatus(v int64) *DeleteGroupMembershipOutput { + s.Status = &v return s } -type CreateDataSetOutput struct { +type DeleteGroupOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the dataset. - Arn *string `type:"string"` - - // The ID for the dataset that you want to create. This ID is unique per AWS - // Region for each AWS account. - DataSetId *string `type:"string"` - - // The ARN for the ingestion, which is triggered as a result of dataset creation - // if the import mode is SPICE. - IngestionArn *string `type:"string"` - - // The ID of the ingestion, which is triggered as a result of dataset creation - // if the import mode is SPICE. - IngestionId *string `type:"string"` - // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -8674,172 +15672,76 @@ type CreateDataSetOutput struct { } // String returns the string representation -func (s CreateDataSetOutput) String() string { +func (s DeleteGroupOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDataSetOutput) GoString() string { +func (s DeleteGroupOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *CreateDataSetOutput) SetArn(v string) *CreateDataSetOutput { - s.Arn = &v - return s -} - -// SetDataSetId sets the DataSetId field's value. -func (s *CreateDataSetOutput) SetDataSetId(v string) *CreateDataSetOutput { - s.DataSetId = &v - return s -} - -// SetIngestionArn sets the IngestionArn field's value. -func (s *CreateDataSetOutput) SetIngestionArn(v string) *CreateDataSetOutput { - s.IngestionArn = &v - return s -} - -// SetIngestionId sets the IngestionId field's value. -func (s *CreateDataSetOutput) SetIngestionId(v string) *CreateDataSetOutput { - s.IngestionId = &v - return s -} - // SetRequestId sets the RequestId field's value. -func (s *CreateDataSetOutput) SetRequestId(v string) *CreateDataSetOutput { +func (s *DeleteGroupOutput) SetRequestId(v string) *DeleteGroupOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *CreateDataSetOutput) SetStatus(v int64) *CreateDataSetOutput { +func (s *DeleteGroupOutput) SetStatus(v int64) *DeleteGroupOutput { s.Status = &v return s } -type CreateDataSourceInput struct { +type DeleteIAMPolicyAssignmentInput struct { _ struct{} `type:"structure"` - // The AWS account ID. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // The credentials QuickSight that uses to connect to your underlying source. - // Currently, only credentials based on user name and password are supported. - Credentials *DataSourceCredentials `type:"structure" sensitive:"true"` - - // An ID for the data source. This ID is unique per AWS Region for each AWS - // account. - // - // DataSourceId is a required field - DataSourceId *string `type:"string" required:"true"` - - // The parameters that QuickSight uses to connect to your underlying source. - DataSourceParameters *DataSourceParameters `type:"structure"` - - // A display name for the data source. + // The name of the assignment. // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` - - // A list of resource permissions on the data source. - Permissions []*ResourcePermission `min:"1" type:"list"` - - // Secure Socket Layer (SSL) properties that apply when QuickSight connects - // to your underlying source. - SslProperties *SslProperties `type:"structure"` - - // Contains a map of the key-value pairs for the resource tag or tags assigned - // to the data source. - Tags []*Tag `min:"1" type:"list"` + // AssignmentName is a required field + AssignmentName *string `location:"uri" locationName:"AssignmentName" min:"1" type:"string" required:"true"` - // The type of the data source. Currently, the supported types for this operation - // are: ATHENA, AURORA, AURORA_POSTGRESQL, MARIADB, MYSQL, POSTGRESQL, PRESTO, - // REDSHIFT, S3, SNOWFLAKE, SPARK, SQLSERVER, TERADATA. Use ListDataSources - // to return a list of all data sources. + // The AWS account ID where you want to delete the IAM policy assignment. // - // Type is a required field - Type *string `type:"string" required:"true" enum:"DataSourceType"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Use this parameter only when you want QuickSight to use a VPC connection - // when connecting to your underlying source. - VpcConnectionProperties *VpcConnectionProperties `type:"structure"` + // The namespace that contains the assignment. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` } // String returns the string representation -func (s CreateDataSourceInput) String() string { +func (s DeleteIAMPolicyAssignmentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDataSourceInput) GoString() string { +func (s DeleteIAMPolicyAssignmentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDataSourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDataSourceInput"} +func (s *DeleteIAMPolicyAssignmentInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteIAMPolicyAssignmentInput"} + if s.AssignmentName == nil { + invalidParams.Add(request.NewErrParamRequired("AssignmentName")) + } + if s.AssignmentName != nil && len(*s.AssignmentName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AssignmentName", 1)) + } if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DataSourceId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSourceId")) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.Permissions != nil && len(s.Permissions) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Permissions", 1)) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - if s.Credentials != nil { - if err := s.Credentials.Validate(); err != nil { - invalidParams.AddNested("Credentials", err.(request.ErrInvalidParams)) - } - } - if s.DataSourceParameters != nil { - if err := s.DataSourceParameters.Validate(); err != nil { - invalidParams.AddNested("DataSourceParameters", err.(request.ErrInvalidParams)) - } - } - if s.Permissions != nil { - for i, v := range s.Permissions { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Permissions", i), err.(request.ErrInvalidParams)) - } - } - } - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) } - if s.VpcConnectionProperties != nil { - if err := s.VpcConnectionProperties.Validate(); err != nil { - invalidParams.AddNested("VpcConnectionProperties", err.(request.ErrInvalidParams)) - } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) } if invalidParams.Len() > 0 { @@ -8848,78 +15750,29 @@ func (s *CreateDataSourceInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *CreateDataSourceInput) SetAwsAccountId(v string) *CreateDataSourceInput { - s.AwsAccountId = &v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *CreateDataSourceInput) SetCredentials(v *DataSourceCredentials) *CreateDataSourceInput { - s.Credentials = v - return s -} - -// SetDataSourceId sets the DataSourceId field's value. -func (s *CreateDataSourceInput) SetDataSourceId(v string) *CreateDataSourceInput { - s.DataSourceId = &v - return s -} - -// SetDataSourceParameters sets the DataSourceParameters field's value. -func (s *CreateDataSourceInput) SetDataSourceParameters(v *DataSourceParameters) *CreateDataSourceInput { - s.DataSourceParameters = v - return s -} - -// SetName sets the Name field's value. -func (s *CreateDataSourceInput) SetName(v string) *CreateDataSourceInput { - s.Name = &v - return s -} - -// SetPermissions sets the Permissions field's value. -func (s *CreateDataSourceInput) SetPermissions(v []*ResourcePermission) *CreateDataSourceInput { - s.Permissions = v - return s -} - -// SetSslProperties sets the SslProperties field's value. -func (s *CreateDataSourceInput) SetSslProperties(v *SslProperties) *CreateDataSourceInput { - s.SslProperties = v - return s -} - -// SetTags sets the Tags field's value. -func (s *CreateDataSourceInput) SetTags(v []*Tag) *CreateDataSourceInput { - s.Tags = v +// SetAssignmentName sets the AssignmentName field's value. +func (s *DeleteIAMPolicyAssignmentInput) SetAssignmentName(v string) *DeleteIAMPolicyAssignmentInput { + s.AssignmentName = &v return s } -// SetType sets the Type field's value. -func (s *CreateDataSourceInput) SetType(v string) *CreateDataSourceInput { - s.Type = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DeleteIAMPolicyAssignmentInput) SetAwsAccountId(v string) *DeleteIAMPolicyAssignmentInput { + s.AwsAccountId = &v return s } -// SetVpcConnectionProperties sets the VpcConnectionProperties field's value. -func (s *CreateDataSourceInput) SetVpcConnectionProperties(v *VpcConnectionProperties) *CreateDataSourceInput { - s.VpcConnectionProperties = v +// SetNamespace sets the Namespace field's value. +func (s *DeleteIAMPolicyAssignmentInput) SetNamespace(v string) *DeleteIAMPolicyAssignmentInput { + s.Namespace = &v return s } -type CreateDataSourceOutput struct { +type DeleteIAMPolicyAssignmentOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the data source. - Arn *string `type:"string"` - - // The status of creating the data source. - CreationStatus *string `type:"string" enum:"ResourceStatus"` - - // The ID of the data source. This ID is unique per AWS Region for each AWS - // account. - DataSourceId *string `type:"string"` + // The name of the assignment. + AssignmentName *string `min:"1" type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -8929,97 +15782,67 @@ type CreateDataSourceOutput struct { } // String returns the string representation -func (s CreateDataSourceOutput) String() string { +func (s DeleteIAMPolicyAssignmentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateDataSourceOutput) GoString() string { +func (s DeleteIAMPolicyAssignmentOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *CreateDataSourceOutput) SetArn(v string) *CreateDataSourceOutput { - s.Arn = &v - return s -} - -// SetCreationStatus sets the CreationStatus field's value. -func (s *CreateDataSourceOutput) SetCreationStatus(v string) *CreateDataSourceOutput { - s.CreationStatus = &v - return s -} - -// SetDataSourceId sets the DataSourceId field's value. -func (s *CreateDataSourceOutput) SetDataSourceId(v string) *CreateDataSourceOutput { - s.DataSourceId = &v +// SetAssignmentName sets the AssignmentName field's value. +func (s *DeleteIAMPolicyAssignmentOutput) SetAssignmentName(v string) *DeleteIAMPolicyAssignmentOutput { + s.AssignmentName = &v return s } // SetRequestId sets the RequestId field's value. -func (s *CreateDataSourceOutput) SetRequestId(v string) *CreateDataSourceOutput { +func (s *DeleteIAMPolicyAssignmentOutput) SetRequestId(v string) *DeleteIAMPolicyAssignmentOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *CreateDataSourceOutput) SetStatus(v int64) *CreateDataSourceOutput { +func (s *DeleteIAMPolicyAssignmentOutput) SetStatus(v int64) *DeleteIAMPolicyAssignmentOutput { s.Status = &v return s } -// The request object for this operation. -type CreateGroupInput struct { +type DeleteNamespaceInput struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the group is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. + // The ID for the AWS account that you want to delete the QuickSight namespace + // from. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // A description for the group that you want to create. - Description *string `min:"1" type:"string"` - - // A name for the group that you want to create. - // - // GroupName is a required field - GroupName *string `min:"1" type:"string" required:"true"` - - // The namespace. Currently, you should set this to default. + // The namespace that you want to delete. // // Namespace is a required field Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` } // String returns the string representation -func (s CreateGroupInput) String() string { +func (s DeleteNamespaceInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateGroupInput) GoString() string { +func (s DeleteNamespaceInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateGroupInput"} +func (s *DeleteNamespaceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteNamespaceInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Description != nil && len(*s.Description) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Description", 1)) - } - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) - } - if s.GroupName != nil && len(*s.GroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) - } if s.Namespace == nil { invalidParams.Add(request.NewErrParamRequired("Namespace")) } @@ -9034,90 +15857,101 @@ func (s *CreateGroupInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *CreateGroupInput) SetAwsAccountId(v string) *CreateGroupInput { +func (s *DeleteNamespaceInput) SetAwsAccountId(v string) *DeleteNamespaceInput { s.AwsAccountId = &v return s } -// SetDescription sets the Description field's value. -func (s *CreateGroupInput) SetDescription(v string) *CreateGroupInput { - s.Description = &v +// SetNamespace sets the Namespace field's value. +func (s *DeleteNamespaceInput) SetNamespace(v string) *DeleteNamespaceInput { + s.Namespace = &v return s } -// SetGroupName sets the GroupName field's value. -func (s *CreateGroupInput) SetGroupName(v string) *CreateGroupInput { - s.GroupName = &v +type DeleteNamespaceOutput struct { + _ struct{} `type:"structure"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} + +// String returns the string representation +func (s DeleteNamespaceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteNamespaceOutput) GoString() string { + return s.String() +} + +// SetRequestId sets the RequestId field's value. +func (s *DeleteNamespaceOutput) SetRequestId(v string) *DeleteNamespaceOutput { + s.RequestId = &v return s } -// SetNamespace sets the Namespace field's value. -func (s *CreateGroupInput) SetNamespace(v string) *CreateGroupInput { - s.Namespace = &v +// SetStatus sets the Status field's value. +func (s *DeleteNamespaceOutput) SetStatus(v int64) *DeleteNamespaceOutput { + s.Status = &v return s } -type CreateGroupMembershipInput struct { +type DeleteTemplateAliasInput struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the group is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // The name of the group that you want to add the user to. + // The name for the template alias. To delete a specific alias, you delete the + // version that the alias points to. You can specify the alias name, or specify + // the latest version of the template by providing the keyword $LATEST in the + // AliasName parameter. // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + // AliasName is a required field + AliasName *string `location:"uri" locationName:"AliasName" min:"1" type:"string" required:"true"` - // The name of the user that you want to add to the group membership. + // The ID of the AWS account that contains the item to delete. // - // MemberName is a required field - MemberName *string `location:"uri" locationName:"MemberName" min:"1" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The namespace. Currently, you should set this to default. + // The ID for the template that the specified alias is for. // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s CreateGroupMembershipInput) String() string { +func (s DeleteTemplateAliasInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateGroupMembershipInput) GoString() string { +func (s DeleteTemplateAliasInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateGroupMembershipInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateGroupMembershipInput"} +func (s *DeleteTemplateAliasInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteTemplateAliasInput"} + if s.AliasName == nil { + invalidParams.Add(request.NewErrParamRequired("AliasName")) + } + if s.AliasName != nil && len(*s.AliasName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) + } if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) - } - if s.GroupName != nil && len(*s.GroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) - } - if s.MemberName == nil { - invalidParams.Add(request.NewErrParamRequired("MemberName")) - } - if s.MemberName != nil && len(*s.MemberName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MemberName", 1)) - } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) } if invalidParams.Len() > 0 { @@ -9126,187 +15960,128 @@ func (s *CreateGroupMembershipInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *CreateGroupMembershipInput) SetAwsAccountId(v string) *CreateGroupMembershipInput { - s.AwsAccountId = &v - return s -} - -// SetGroupName sets the GroupName field's value. -func (s *CreateGroupMembershipInput) SetGroupName(v string) *CreateGroupMembershipInput { - s.GroupName = &v +// SetAliasName sets the AliasName field's value. +func (s *DeleteTemplateAliasInput) SetAliasName(v string) *DeleteTemplateAliasInput { + s.AliasName = &v return s } -// SetMemberName sets the MemberName field's value. -func (s *CreateGroupMembershipInput) SetMemberName(v string) *CreateGroupMembershipInput { - s.MemberName = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DeleteTemplateAliasInput) SetAwsAccountId(v string) *DeleteTemplateAliasInput { + s.AwsAccountId = &v return s } -// SetNamespace sets the Namespace field's value. -func (s *CreateGroupMembershipInput) SetNamespace(v string) *CreateGroupMembershipInput { - s.Namespace = &v +// SetTemplateId sets the TemplateId field's value. +func (s *DeleteTemplateAliasInput) SetTemplateId(v string) *DeleteTemplateAliasInput { + s.TemplateId = &v return s } -type CreateGroupMembershipOutput struct { +type DeleteTemplateAliasOutput struct { _ struct{} `type:"structure"` - // The group member. - GroupMember *GroupMember `type:"structure"` + // The name for the template alias. + AliasName *string `min:"1" type:"string"` + + // The Amazon Resource Name (ARN) of the template you want to delete. + Arn *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // An ID for the template associated with the deletion. + TemplateId *string `min:"1" type:"string"` } // String returns the string representation -func (s CreateGroupMembershipOutput) String() string { +func (s DeleteTemplateAliasOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateGroupMembershipOutput) GoString() string { +func (s DeleteTemplateAliasOutput) GoString() string { return s.String() } -// SetGroupMember sets the GroupMember field's value. -func (s *CreateGroupMembershipOutput) SetGroupMember(v *GroupMember) *CreateGroupMembershipOutput { - s.GroupMember = v - return s -} - -// SetRequestId sets the RequestId field's value. -func (s *CreateGroupMembershipOutput) SetRequestId(v string) *CreateGroupMembershipOutput { - s.RequestId = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *CreateGroupMembershipOutput) SetStatus(v int64) *CreateGroupMembershipOutput { - s.Status = &v +// SetAliasName sets the AliasName field's value. +func (s *DeleteTemplateAliasOutput) SetAliasName(v string) *DeleteTemplateAliasOutput { + s.AliasName = &v return s } -// The response object for this operation. -type CreateGroupOutput struct { - _ struct{} `type:"structure"` - - // The name of the group. - Group *Group `type:"structure"` - - // The AWS request ID for this operation. - RequestId *string `type:"string"` - - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` -} - -// String returns the string representation -func (s CreateGroupOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateGroupOutput) GoString() string { - return s.String() -} - -// SetGroup sets the Group field's value. -func (s *CreateGroupOutput) SetGroup(v *Group) *CreateGroupOutput { - s.Group = v +// SetArn sets the Arn field's value. +func (s *DeleteTemplateAliasOutput) SetArn(v string) *DeleteTemplateAliasOutput { + s.Arn = &v return s } // SetRequestId sets the RequestId field's value. -func (s *CreateGroupOutput) SetRequestId(v string) *CreateGroupOutput { +func (s *DeleteTemplateAliasOutput) SetRequestId(v string) *DeleteTemplateAliasOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *CreateGroupOutput) SetStatus(v int64) *CreateGroupOutput { +func (s *DeleteTemplateAliasOutput) SetStatus(v int64) *DeleteTemplateAliasOutput { s.Status = &v return s } -type CreateIAMPolicyAssignmentInput struct { - _ struct{} `type:"structure"` - - // The name of the assignment. It must be unique within an AWS account. - // - // AssignmentName is a required field - AssignmentName *string `min:"1" type:"string" required:"true"` +// SetTemplateId sets the TemplateId field's value. +func (s *DeleteTemplateAliasOutput) SetTemplateId(v string) *DeleteTemplateAliasOutput { + s.TemplateId = &v + return s +} - // The status of the assignment. Possible values are as follows: - // - // * ENABLED - Anything specified in this assignment is used when creating - // the data source. - // - // * DISABLED - This assignment isn't used when creating the data source. - // - // * DRAFT - This assignment is an unfinished draft and isn't used when creating - // the data source. - // - // AssignmentStatus is a required field - AssignmentStatus *string `type:"string" required:"true" enum:"AssignmentStatus"` +type DeleteTemplateInput struct { + _ struct{} `type:"structure"` - // The ID of the AWS account where you want to assign an IAM policy to QuickSight - // users or groups. + // The ID of the AWS account that contains the template that you're deleting. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The QuickSight users, groups, or both that you want to assign the policy - // to. - Identities map[string][]*string `type:"map"` - - // The namespace that contains the assignment. + // An ID for the template you want to delete. // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` - // The ARN for the IAM policy to apply to the QuickSight users and groups specified - // in this assignment. - PolicyArn *string `type:"string"` + // Specifies the version of the template that you want to delete. If you don't + // provide a version number, DeleteTemplate deletes all versions of the template. + VersionNumber *int64 `location:"querystring" locationName:"version-number" min:"1" type:"long"` } // String returns the string representation -func (s CreateIAMPolicyAssignmentInput) String() string { +func (s DeleteTemplateInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateIAMPolicyAssignmentInput) GoString() string { +func (s DeleteTemplateInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateIAMPolicyAssignmentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateIAMPolicyAssignmentInput"} - if s.AssignmentName == nil { - invalidParams.Add(request.NewErrParamRequired("AssignmentName")) - } - if s.AssignmentName != nil && len(*s.AssignmentName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AssignmentName", 1)) - } - if s.AssignmentStatus == nil { - invalidParams.Add(request.NewErrParamRequired("AssignmentStatus")) - } +func (s *DeleteTemplateInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteTemplateInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + } + if s.VersionNumber != nil && *s.VersionNumber < 1 { + invalidParams.Add(request.NewErrParamMinValue("VersionNumber", 1)) } if invalidParams.Len() > 0 { @@ -9315,177 +16090,123 @@ func (s *CreateIAMPolicyAssignmentInput) Validate() error { return nil } -// SetAssignmentName sets the AssignmentName field's value. -func (s *CreateIAMPolicyAssignmentInput) SetAssignmentName(v string) *CreateIAMPolicyAssignmentInput { - s.AssignmentName = &v - return s -} - -// SetAssignmentStatus sets the AssignmentStatus field's value. -func (s *CreateIAMPolicyAssignmentInput) SetAssignmentStatus(v string) *CreateIAMPolicyAssignmentInput { - s.AssignmentStatus = &v - return s -} - // SetAwsAccountId sets the AwsAccountId field's value. -func (s *CreateIAMPolicyAssignmentInput) SetAwsAccountId(v string) *CreateIAMPolicyAssignmentInput { +func (s *DeleteTemplateInput) SetAwsAccountId(v string) *DeleteTemplateInput { s.AwsAccountId = &v return s } -// SetIdentities sets the Identities field's value. -func (s *CreateIAMPolicyAssignmentInput) SetIdentities(v map[string][]*string) *CreateIAMPolicyAssignmentInput { - s.Identities = v - return s -} - -// SetNamespace sets the Namespace field's value. -func (s *CreateIAMPolicyAssignmentInput) SetNamespace(v string) *CreateIAMPolicyAssignmentInput { - s.Namespace = &v - return s -} - -// SetPolicyArn sets the PolicyArn field's value. -func (s *CreateIAMPolicyAssignmentInput) SetPolicyArn(v string) *CreateIAMPolicyAssignmentInput { - s.PolicyArn = &v - return s -} - -type CreateIAMPolicyAssignmentOutput struct { - _ struct{} `type:"structure"` - - // The ID for the assignment. - AssignmentId *string `type:"string"` - - // The name of the assignment. This name must be unique within the AWS account. - AssignmentName *string `min:"1" type:"string"` - - // The status of the assignment. Possible values are as follows: - // - // * ENABLED - Anything specified in this assignment is used when creating - // the data source. - // - // * DISABLED - This assignment isn't used when creating the data source. - // - // * DRAFT - This assignment is an unfinished draft and isn't used when creating - // the data source. - AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` - - // The QuickSight users, groups, or both that the IAM policy is assigned to. - Identities map[string][]*string `type:"map"` +// SetTemplateId sets the TemplateId field's value. +func (s *DeleteTemplateInput) SetTemplateId(v string) *DeleteTemplateInput { + s.TemplateId = &v + return s +} - // The ARN for the IAM policy that is applied to the QuickSight users and groups - // specified in this assignment. - PolicyArn *string `type:"string"` +// SetVersionNumber sets the VersionNumber field's value. +func (s *DeleteTemplateInput) SetVersionNumber(v int64) *DeleteTemplateInput { + s.VersionNumber = &v + return s +} + +type DeleteTemplateOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource. + Arn *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // An ID for the template. + TemplateId *string `min:"1" type:"string"` } // String returns the string representation -func (s CreateIAMPolicyAssignmentOutput) String() string { +func (s DeleteTemplateOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateIAMPolicyAssignmentOutput) GoString() string { +func (s DeleteTemplateOutput) GoString() string { return s.String() } -// SetAssignmentId sets the AssignmentId field's value. -func (s *CreateIAMPolicyAssignmentOutput) SetAssignmentId(v string) *CreateIAMPolicyAssignmentOutput { - s.AssignmentId = &v - return s -} - -// SetAssignmentName sets the AssignmentName field's value. -func (s *CreateIAMPolicyAssignmentOutput) SetAssignmentName(v string) *CreateIAMPolicyAssignmentOutput { - s.AssignmentName = &v - return s -} - -// SetAssignmentStatus sets the AssignmentStatus field's value. -func (s *CreateIAMPolicyAssignmentOutput) SetAssignmentStatus(v string) *CreateIAMPolicyAssignmentOutput { - s.AssignmentStatus = &v - return s -} - -// SetIdentities sets the Identities field's value. -func (s *CreateIAMPolicyAssignmentOutput) SetIdentities(v map[string][]*string) *CreateIAMPolicyAssignmentOutput { - s.Identities = v - return s -} - -// SetPolicyArn sets the PolicyArn field's value. -func (s *CreateIAMPolicyAssignmentOutput) SetPolicyArn(v string) *CreateIAMPolicyAssignmentOutput { - s.PolicyArn = &v +// SetArn sets the Arn field's value. +func (s *DeleteTemplateOutput) SetArn(v string) *DeleteTemplateOutput { + s.Arn = &v return s } // SetRequestId sets the RequestId field's value. -func (s *CreateIAMPolicyAssignmentOutput) SetRequestId(v string) *CreateIAMPolicyAssignmentOutput { +func (s *DeleteTemplateOutput) SetRequestId(v string) *DeleteTemplateOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *CreateIAMPolicyAssignmentOutput) SetStatus(v int64) *CreateIAMPolicyAssignmentOutput { +func (s *DeleteTemplateOutput) SetStatus(v int64) *DeleteTemplateOutput { s.Status = &v return s } -type CreateIngestionInput struct { +// SetTemplateId sets the TemplateId field's value. +func (s *DeleteTemplateOutput) SetTemplateId(v string) *DeleteTemplateOutput { + s.TemplateId = &v + return s +} + +type DeleteThemeAliasInput struct { _ struct{} `type:"structure"` - // The AWS account ID. + // The unique name for the theme alias to delete. // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // AliasName is a required field + AliasName *string `location:"uri" locationName:"AliasName" min:"1" type:"string" required:"true"` - // The ID of the dataset used in the ingestion. + // The ID of the AWS account that contains the theme alias to delete. // - // DataSetId is a required field - DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // An ID for the ingestion. + // The ID for the theme that the specified alias is for. // - // IngestionId is a required field - IngestionId *string `location:"uri" locationName:"IngestionId" min:"1" type:"string" required:"true"` + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s CreateIngestionInput) String() string { +func (s DeleteThemeAliasInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateIngestionInput) GoString() string { +func (s DeleteThemeAliasInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateIngestionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateIngestionInput"} +func (s *DeleteThemeAliasInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteThemeAliasInput"} + if s.AliasName == nil { + invalidParams.Add(request.NewErrParamRequired("AliasName")) + } + if s.AliasName != nil && len(*s.AliasName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) + } if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DataSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetId")) - } - if s.DataSetId != nil && len(*s.DataSetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) - } - if s.IngestionId == nil { - invalidParams.Add(request.NewErrParamRequired("IngestionId")) + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) } - if s.IngestionId != nil && len(*s.IngestionId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("IngestionId", 1)) + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) } if invalidParams.Len() > 0 { @@ -9494,146 +16215,130 @@ func (s *CreateIngestionInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *CreateIngestionInput) SetAwsAccountId(v string) *CreateIngestionInput { - s.AwsAccountId = &v +// SetAliasName sets the AliasName field's value. +func (s *DeleteThemeAliasInput) SetAliasName(v string) *DeleteThemeAliasInput { + s.AliasName = &v return s } -// SetDataSetId sets the DataSetId field's value. -func (s *CreateIngestionInput) SetDataSetId(v string) *CreateIngestionInput { - s.DataSetId = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DeleteThemeAliasInput) SetAwsAccountId(v string) *DeleteThemeAliasInput { + s.AwsAccountId = &v return s } -// SetIngestionId sets the IngestionId field's value. -func (s *CreateIngestionInput) SetIngestionId(v string) *CreateIngestionInput { - s.IngestionId = &v +// SetThemeId sets the ThemeId field's value. +func (s *DeleteThemeAliasInput) SetThemeId(v string) *DeleteThemeAliasInput { + s.ThemeId = &v return s } -type CreateIngestionOutput struct { +type DeleteThemeAliasOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) for the data ingestion. - Arn *string `type:"string"` - - // An ID for the ingestion. - IngestionId *string `min:"1" type:"string"` + // The name for the theme alias. + AliasName *string `min:"1" type:"string"` - // The ingestion status. - IngestionStatus *string `type:"string" enum:"IngestionStatus"` + // The Amazon Resource Name (ARN) of the theme resource using the deleted alias. + Arn *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // An ID for the theme associated with the deletion. + ThemeId *string `min:"1" type:"string"` } // String returns the string representation -func (s CreateIngestionOutput) String() string { +func (s DeleteThemeAliasOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateIngestionOutput) GoString() string { +func (s DeleteThemeAliasOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *CreateIngestionOutput) SetArn(v string) *CreateIngestionOutput { - s.Arn = &v - return s -} - -// SetIngestionId sets the IngestionId field's value. -func (s *CreateIngestionOutput) SetIngestionId(v string) *CreateIngestionOutput { - s.IngestionId = &v +// SetAliasName sets the AliasName field's value. +func (s *DeleteThemeAliasOutput) SetAliasName(v string) *DeleteThemeAliasOutput { + s.AliasName = &v return s } -// SetIngestionStatus sets the IngestionStatus field's value. -func (s *CreateIngestionOutput) SetIngestionStatus(v string) *CreateIngestionOutput { - s.IngestionStatus = &v +// SetArn sets the Arn field's value. +func (s *DeleteThemeAliasOutput) SetArn(v string) *DeleteThemeAliasOutput { + s.Arn = &v return s } // SetRequestId sets the RequestId field's value. -func (s *CreateIngestionOutput) SetRequestId(v string) *CreateIngestionOutput { +func (s *DeleteThemeAliasOutput) SetRequestId(v string) *DeleteThemeAliasOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *CreateIngestionOutput) SetStatus(v int64) *CreateIngestionOutput { +func (s *DeleteThemeAliasOutput) SetStatus(v int64) *DeleteThemeAliasOutput { s.Status = &v return s } -type CreateTemplateAliasInput struct { - _ struct{} `type:"structure"` +// SetThemeId sets the ThemeId field's value. +func (s *DeleteThemeAliasOutput) SetThemeId(v string) *DeleteThemeAliasOutput { + s.ThemeId = &v + return s +} - // The name that you want to give to the template alias that you're creating. - // Don't start the alias name with the $ character. Alias names that start with - // $ are reserved by QuickSight. - // - // AliasName is a required field - AliasName *string `location:"uri" locationName:"AliasName" min:"1" type:"string" required:"true"` +type DeleteThemeInput struct { + _ struct{} `type:"structure"` - // The ID of the AWS account that contains the template that you creating an - // alias for. + // The ID of the AWS account that contains the theme that you're deleting. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // An ID for the template. + // An ID for the theme that you want to delete. // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` - // The version number of the template. + // The version of the theme that you want to delete. // - // TemplateVersionNumber is a required field - TemplateVersionNumber *int64 `min:"1" type:"long" required:"true"` + // Note: If you don't provide a version number, you're using this call to DeleteTheme + // to delete all versions of the theme. + VersionNumber *int64 `location:"querystring" locationName:"version-number" min:"1" type:"long"` } // String returns the string representation -func (s CreateTemplateAliasInput) String() string { +func (s DeleteThemeInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateTemplateAliasInput) GoString() string { +func (s DeleteThemeInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateTemplateAliasInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateTemplateAliasInput"} - if s.AliasName == nil { - invalidParams.Add(request.NewErrParamRequired("AliasName")) - } - if s.AliasName != nil && len(*s.AliasName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) - } +func (s *DeleteThemeInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteThemeInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) - } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) } - if s.TemplateVersionNumber == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateVersionNumber")) + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) } - if s.TemplateVersionNumber != nil && *s.TemplateVersionNumber < 1 { - invalidParams.Add(request.NewErrParamMinValue("TemplateVersionNumber", 1)) + if s.VersionNumber != nil && *s.VersionNumber < 1 { + invalidParams.Add(request.NewErrParamMinValue("VersionNumber", 1)) } if invalidParams.Len() > 0 { @@ -9642,174 +16347,124 @@ func (s *CreateTemplateAliasInput) Validate() error { return nil } -// SetAliasName sets the AliasName field's value. -func (s *CreateTemplateAliasInput) SetAliasName(v string) *CreateTemplateAliasInput { - s.AliasName = &v - return s -} - // SetAwsAccountId sets the AwsAccountId field's value. -func (s *CreateTemplateAliasInput) SetAwsAccountId(v string) *CreateTemplateAliasInput { +func (s *DeleteThemeInput) SetAwsAccountId(v string) *DeleteThemeInput { s.AwsAccountId = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *CreateTemplateAliasInput) SetTemplateId(v string) *CreateTemplateAliasInput { - s.TemplateId = &v +// SetThemeId sets the ThemeId field's value. +func (s *DeleteThemeInput) SetThemeId(v string) *DeleteThemeInput { + s.ThemeId = &v return s } -// SetTemplateVersionNumber sets the TemplateVersionNumber field's value. -func (s *CreateTemplateAliasInput) SetTemplateVersionNumber(v int64) *CreateTemplateAliasInput { - s.TemplateVersionNumber = &v +// SetVersionNumber sets the VersionNumber field's value. +func (s *DeleteThemeInput) SetVersionNumber(v int64) *DeleteThemeInput { + s.VersionNumber = &v return s } -type CreateTemplateAliasOutput struct { +type DeleteThemeOutput struct { _ struct{} `type:"structure"` + // The Amazon Resource Name (ARN) of the resource. + Arn *string `type:"string"` + // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - // Information about the template alias. - TemplateAlias *TemplateAlias `type:"structure"` + // An ID for the theme. + ThemeId *string `min:"1" type:"string"` } // String returns the string representation -func (s CreateTemplateAliasOutput) String() string { +func (s DeleteThemeOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateTemplateAliasOutput) GoString() string { +func (s DeleteThemeOutput) GoString() string { return s.String() } +// SetArn sets the Arn field's value. +func (s *DeleteThemeOutput) SetArn(v string) *DeleteThemeOutput { + s.Arn = &v + return s +} + // SetRequestId sets the RequestId field's value. -func (s *CreateTemplateAliasOutput) SetRequestId(v string) *CreateTemplateAliasOutput { +func (s *DeleteThemeOutput) SetRequestId(v string) *DeleteThemeOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *CreateTemplateAliasOutput) SetStatus(v int64) *CreateTemplateAliasOutput { +func (s *DeleteThemeOutput) SetStatus(v int64) *DeleteThemeOutput { s.Status = &v return s } -// SetTemplateAlias sets the TemplateAlias field's value. -func (s *CreateTemplateAliasOutput) SetTemplateAlias(v *TemplateAlias) *CreateTemplateAliasOutput { - s.TemplateAlias = v +// SetThemeId sets the ThemeId field's value. +func (s *DeleteThemeOutput) SetThemeId(v string) *DeleteThemeOutput { + s.ThemeId = &v return s } -type CreateTemplateInput struct { +type DeleteUserByPrincipalIdInput struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the group is in. Currently, you use the ID + // The ID for the AWS account that the user is in. Currently, you use the ID // for the AWS account that contains your Amazon QuickSight account. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // A display name for the template. - Name *string `min:"1" type:"string"` - - // A list of resource permissions to be set on the template. - Permissions []*ResourcePermission `min:"1" type:"list"` - - // The Amazon Resource Name (ARN) of the source entity from which this template - // is being created. Currently, you can create a template from an analysis or - // another template. If the ARN is for an analysis, include its dataset references. + // The namespace. Currently, you should set this to default. // - // SourceEntity is a required field - SourceEntity *TemplateSourceEntity `type:"structure" required:"true"` - - // Contains a map of the key-value pairs for the resource tag or tags assigned - // to the resource. - Tags []*Tag `min:"1" type:"list"` + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` - // An ID for the template that you want to create. This template is unique per - // AWS Region in each AWS account. + // The principal ID of the user. // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` - - // A description of the current template version being created. This API operation - // creates the first version of the template. Every time UpdateTemplate is called, - // a new version is created. Each version of the template maintains a description - // of the version in the VersionDescription field. - VersionDescription *string `min:"1" type:"string"` + // PrincipalId is a required field + PrincipalId *string `location:"uri" locationName:"PrincipalId" type:"string" required:"true"` } // String returns the string representation -func (s CreateTemplateInput) String() string { +func (s DeleteUserByPrincipalIdInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateTemplateInput) GoString() string { +func (s DeleteUserByPrincipalIdInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CreateTemplateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateTemplateInput"} +func (s *DeleteUserByPrincipalIdInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteUserByPrincipalIdInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.Permissions != nil && len(s.Permissions) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Permissions", 1)) - } - if s.SourceEntity == nil { - invalidParams.Add(request.NewErrParamRequired("SourceEntity")) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) - } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) - } - if s.VersionDescription != nil && len(*s.VersionDescription) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VersionDescription", 1)) + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) } - if s.Permissions != nil { - for i, v := range s.Permissions { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Permissions", i), err.(request.ErrInvalidParams)) - } - } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) } - if s.SourceEntity != nil { - if err := s.SourceEntity.Validate(); err != nil { - invalidParams.AddNested("SourceEntity", err.(request.ErrInvalidParams)) - } + if s.PrincipalId == nil { + invalidParams.Add(request.NewErrParamRequired("PrincipalId")) } - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } + if s.PrincipalId != nil && len(*s.PrincipalId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PrincipalId", 1)) } if invalidParams.Len() > 0 { @@ -9819,155 +16474,105 @@ func (s *CreateTemplateInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *CreateTemplateInput) SetAwsAccountId(v string) *CreateTemplateInput { +func (s *DeleteUserByPrincipalIdInput) SetAwsAccountId(v string) *DeleteUserByPrincipalIdInput { s.AwsAccountId = &v return s } -// SetName sets the Name field's value. -func (s *CreateTemplateInput) SetName(v string) *CreateTemplateInput { - s.Name = &v - return s -} - -// SetPermissions sets the Permissions field's value. -func (s *CreateTemplateInput) SetPermissions(v []*ResourcePermission) *CreateTemplateInput { - s.Permissions = v - return s -} - -// SetSourceEntity sets the SourceEntity field's value. -func (s *CreateTemplateInput) SetSourceEntity(v *TemplateSourceEntity) *CreateTemplateInput { - s.SourceEntity = v - return s -} - -// SetTags sets the Tags field's value. -func (s *CreateTemplateInput) SetTags(v []*Tag) *CreateTemplateInput { - s.Tags = v - return s -} - -// SetTemplateId sets the TemplateId field's value. -func (s *CreateTemplateInput) SetTemplateId(v string) *CreateTemplateInput { - s.TemplateId = &v +// SetNamespace sets the Namespace field's value. +func (s *DeleteUserByPrincipalIdInput) SetNamespace(v string) *DeleteUserByPrincipalIdInput { + s.Namespace = &v return s } -// SetVersionDescription sets the VersionDescription field's value. -func (s *CreateTemplateInput) SetVersionDescription(v string) *CreateTemplateInput { - s.VersionDescription = &v +// SetPrincipalId sets the PrincipalId field's value. +func (s *DeleteUserByPrincipalIdInput) SetPrincipalId(v string) *DeleteUserByPrincipalIdInput { + s.PrincipalId = &v return s } -type CreateTemplateOutput struct { +type DeleteUserByPrincipalIdOutput struct { _ struct{} `type:"structure"` - // The ARN for the template. - Arn *string `type:"string"` - - // The template creation status. - CreationStatus *string `type:"string" enum:"ResourceStatus"` - // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - - // The ID of the template. - TemplateId *string `min:"1" type:"string"` - - // The ARN for the template, including the version information of the first - // version. - VersionArn *string `type:"string"` } // String returns the string representation -func (s CreateTemplateOutput) String() string { +func (s DeleteUserByPrincipalIdOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CreateTemplateOutput) GoString() string { +func (s DeleteUserByPrincipalIdOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *CreateTemplateOutput) SetArn(v string) *CreateTemplateOutput { - s.Arn = &v - return s -} - -// SetCreationStatus sets the CreationStatus field's value. -func (s *CreateTemplateOutput) SetCreationStatus(v string) *CreateTemplateOutput { - s.CreationStatus = &v - return s -} - // SetRequestId sets the RequestId field's value. -func (s *CreateTemplateOutput) SetRequestId(v string) *CreateTemplateOutput { +func (s *DeleteUserByPrincipalIdOutput) SetRequestId(v string) *DeleteUserByPrincipalIdOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *CreateTemplateOutput) SetStatus(v int64) *CreateTemplateOutput { +func (s *DeleteUserByPrincipalIdOutput) SetStatus(v int64) *DeleteUserByPrincipalIdOutput { s.Status = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *CreateTemplateOutput) SetTemplateId(v string) *CreateTemplateOutput { - s.TemplateId = &v - return s -} - -// SetVersionArn sets the VersionArn field's value. -func (s *CreateTemplateOutput) SetVersionArn(v string) *CreateTemplateOutput { - s.VersionArn = &v - return s -} - -// The combination of user name and password that are used as credentials. -type CredentialPair struct { +type DeleteUserInput struct { _ struct{} `type:"structure"` - // Password. + // The ID for the AWS account that the user is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. // - // Password is a required field - Password *string `min:"1" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // User name. + // The namespace. Currently, you should set this to default. // - // Username is a required field - Username *string `min:"1" type:"string" required:"true"` + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + + // The name of the user that you want to delete. + // + // UserName is a required field + UserName *string `location:"uri" locationName:"UserName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s CredentialPair) String() string { +func (s DeleteUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CredentialPair) GoString() string { +func (s DeleteUserInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CredentialPair) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CredentialPair"} - if s.Password == nil { - invalidParams.Add(request.NewErrParamRequired("Password")) +func (s *DeleteUserInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteUserInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.Password != nil && len(*s.Password) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Password", 1)) + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Username == nil { - invalidParams.Add(request.NewErrParamRequired("Username")) + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) } - if s.Username != nil && len(*s.Username) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Username", 1)) + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.UserName == nil { + invalidParams.Add(request.NewErrParamRequired("UserName")) + } + if s.UserName != nil && len(*s.UserName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) } if invalidParams.Len() > 0 { @@ -9976,81 +16581,91 @@ func (s *CredentialPair) Validate() error { return nil } -// SetPassword sets the Password field's value. -func (s *CredentialPair) SetPassword(v string) *CredentialPair { - s.Password = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DeleteUserInput) SetAwsAccountId(v string) *DeleteUserInput { + s.AwsAccountId = &v return s } -// SetUsername sets the Username field's value. -func (s *CredentialPair) SetUsername(v string) *CredentialPair { - s.Username = &v +// SetNamespace sets the Namespace field's value. +func (s *DeleteUserInput) SetNamespace(v string) *DeleteUserInput { + s.Namespace = &v return s } -// A physical table type built from the results of the custom SQL query. -type CustomSql struct { +// SetUserName sets the UserName field's value. +func (s *DeleteUserInput) SetUserName(v string) *DeleteUserInput { + s.UserName = &v + return s +} + +type DeleteUserOutput struct { _ struct{} `type:"structure"` - // The column schema from the SQL query result set. - Columns []*InputColumn `min:"1" type:"list"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // The Amazon Resource Name (ARN) of the data source. - // - // DataSourceArn is a required field - DataSourceArn *string `type:"string" required:"true"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} - // A display name for the SQL query result. - // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` +// String returns the string representation +func (s DeleteUserOutput) String() string { + return awsutil.Prettify(s) +} - // The SQL query. +// GoString returns the string representation +func (s DeleteUserOutput) GoString() string { + return s.String() +} + +// SetRequestId sets the RequestId field's value. +func (s *DeleteUserOutput) SetRequestId(v string) *DeleteUserOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *DeleteUserOutput) SetStatus(v int64) *DeleteUserOutput { + s.Status = &v + return s +} + +type DescribeAccountCustomizationInput struct { + _ struct{} `type:"structure"` + + // The ID for the AWS account that you want to describe QuickSight customizations + // for. // - // SqlQuery is a required field - SqlQuery *string `min:"1" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The namespace associated with the customization that you're describing. + Namespace *string `location:"querystring" locationName:"namespace" type:"string"` + + // The status of the creation of the customization. This is an asynchronous + // process. A status of CREATED means that your customization is ready to use. + Resolved *bool `location:"querystring" locationName:"resolved" type:"boolean"` } // String returns the string representation -func (s CustomSql) String() string { +func (s DescribeAccountCustomizationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s CustomSql) GoString() string { +func (s DescribeAccountCustomizationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *CustomSql) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CustomSql"} - if s.Columns != nil && len(s.Columns) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Columns", 1)) - } - if s.DataSourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("DataSourceArn")) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.SqlQuery == nil { - invalidParams.Add(request.NewErrParamRequired("SqlQuery")) - } - if s.SqlQuery != nil && len(*s.SqlQuery) < 1 { - invalidParams.Add(request.NewErrParamMinLen("SqlQuery", 1)) +func (s *DescribeAccountCustomizationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeAccountCustomizationInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.Columns != nil { - for i, v := range s.Columns { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Columns", i), err.(request.ErrInvalidParams)) - } - } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } if invalidParams.Len() > 0 { @@ -10059,217 +16674,223 @@ func (s *CustomSql) Validate() error { return nil } -// SetColumns sets the Columns field's value. -func (s *CustomSql) SetColumns(v []*InputColumn) *CustomSql { - s.Columns = v - return s -} - -// SetDataSourceArn sets the DataSourceArn field's value. -func (s *CustomSql) SetDataSourceArn(v string) *CustomSql { - s.DataSourceArn = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeAccountCustomizationInput) SetAwsAccountId(v string) *DescribeAccountCustomizationInput { + s.AwsAccountId = &v return s } -// SetName sets the Name field's value. -func (s *CustomSql) SetName(v string) *CustomSql { - s.Name = &v +// SetNamespace sets the Namespace field's value. +func (s *DescribeAccountCustomizationInput) SetNamespace(v string) *DescribeAccountCustomizationInput { + s.Namespace = &v return s } -// SetSqlQuery sets the SqlQuery field's value. -func (s *CustomSql) SetSqlQuery(v string) *CustomSql { - s.SqlQuery = &v +// SetResolved sets the Resolved field's value. +func (s *DescribeAccountCustomizationInput) SetResolved(v bool) *DescribeAccountCustomizationInput { + s.Resolved = &v return s } -// Dashboard. -type Dashboard struct { +type DescribeAccountCustomizationOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. - Arn *string `type:"string"` - - // The time that this dataset was created. - CreatedTime *time.Time `type:"timestamp"` - - // Dashboard ID. - DashboardId *string `min:"1" type:"string"` + // The customizations associated with QuickSight. + AccountCustomization *AccountCustomization `type:"structure"` - // The last time that this dataset was published. - LastPublishedTime *time.Time `type:"timestamp"` + // The ID for the AWS account that you want to describe QuickSight customizations + // for. + AwsAccountId *string `min:"12" type:"string"` - // The last time that this dataset was updated. - LastUpdatedTime *time.Time `type:"timestamp"` + // The namespace associated with the customization that you're describing. + Namespace *string `type:"string"` - // A display name for the dataset. - Name *string `min:"1" type:"string"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // Version. - Version *DashboardVersion `type:"structure"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s Dashboard) String() string { +func (s DescribeAccountCustomizationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Dashboard) GoString() string { +func (s DescribeAccountCustomizationOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *Dashboard) SetArn(v string) *Dashboard { - s.Arn = &v - return s -} - -// SetCreatedTime sets the CreatedTime field's value. -func (s *Dashboard) SetCreatedTime(v time.Time) *Dashboard { - s.CreatedTime = &v - return s -} - -// SetDashboardId sets the DashboardId field's value. -func (s *Dashboard) SetDashboardId(v string) *Dashboard { - s.DashboardId = &v +// SetAccountCustomization sets the AccountCustomization field's value. +func (s *DescribeAccountCustomizationOutput) SetAccountCustomization(v *AccountCustomization) *DescribeAccountCustomizationOutput { + s.AccountCustomization = v return s } -// SetLastPublishedTime sets the LastPublishedTime field's value. -func (s *Dashboard) SetLastPublishedTime(v time.Time) *Dashboard { - s.LastPublishedTime = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeAccountCustomizationOutput) SetAwsAccountId(v string) *DescribeAccountCustomizationOutput { + s.AwsAccountId = &v return s } -// SetLastUpdatedTime sets the LastUpdatedTime field's value. -func (s *Dashboard) SetLastUpdatedTime(v time.Time) *Dashboard { - s.LastUpdatedTime = &v +// SetNamespace sets the Namespace field's value. +func (s *DescribeAccountCustomizationOutput) SetNamespace(v string) *DescribeAccountCustomizationOutput { + s.Namespace = &v return s } -// SetName sets the Name field's value. -func (s *Dashboard) SetName(v string) *Dashboard { - s.Name = &v +// SetRequestId sets the RequestId field's value. +func (s *DescribeAccountCustomizationOutput) SetRequestId(v string) *DescribeAccountCustomizationOutput { + s.RequestId = &v return s } -// SetVersion sets the Version field's value. -func (s *Dashboard) SetVersion(v *DashboardVersion) *Dashboard { - s.Version = v +// SetStatus sets the Status field's value. +func (s *DescribeAccountCustomizationOutput) SetStatus(v int64) *DescribeAccountCustomizationOutput { + s.Status = &v return s } -// Dashboard error. -type DashboardError struct { +type DescribeAccountSettingsInput struct { _ struct{} `type:"structure"` - // Message. - Message *string `type:"string"` - - // Type. - Type *string `type:"string" enum:"DashboardErrorType"` + // The ID for the AWS account that contains the QuickSight namespaces that you + // want to list. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` } // String returns the string representation -func (s DashboardError) String() string { +func (s DescribeAccountSettingsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DashboardError) GoString() string { +func (s DescribeAccountSettingsInput) GoString() string { return s.String() } -// SetMessage sets the Message field's value. -func (s *DashboardError) SetMessage(v string) *DashboardError { - s.Message = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeAccountSettingsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeAccountSettingsInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetType sets the Type field's value. -func (s *DashboardError) SetType(v string) *DashboardError { - s.Type = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeAccountSettingsInput) SetAwsAccountId(v string) *DescribeAccountSettingsInput { + s.AwsAccountId = &v return s } -// Dashboard publish options. -type DashboardPublishOptions struct { +type DescribeAccountSettingsOutput struct { _ struct{} `type:"structure"` - // Ad hoc (one-time) filtering option. - AdHocFilteringOption *AdHocFilteringOption `type:"structure"` + // The settings associated with the QuickSight subscription associated with + // this AWS account. This information includes the edition of Amazon QuickSight + // that you subscribed to (Standard or Enterprise) and the notification email + // for the QuickSight subscription. The QuickSight console, the QuickSight subscription + // is sometimes referred to as a QuickSight "account" even though it is technically + // not an account, but a subscription in your AWS account. + AccountSettings *AccountSettings `type:"structure"` - // Export to .csv option. - ExportToCSVOption *ExportToCSVOption `type:"structure"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // Sheet controls option. - SheetControlsOption *SheetControlsOption `type:"structure"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s DashboardPublishOptions) String() string { +func (s DescribeAccountSettingsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DashboardPublishOptions) GoString() string { +func (s DescribeAccountSettingsOutput) GoString() string { return s.String() } -// SetAdHocFilteringOption sets the AdHocFilteringOption field's value. -func (s *DashboardPublishOptions) SetAdHocFilteringOption(v *AdHocFilteringOption) *DashboardPublishOptions { - s.AdHocFilteringOption = v +// SetAccountSettings sets the AccountSettings field's value. +func (s *DescribeAccountSettingsOutput) SetAccountSettings(v *AccountSettings) *DescribeAccountSettingsOutput { + s.AccountSettings = v return s } -// SetExportToCSVOption sets the ExportToCSVOption field's value. -func (s *DashboardPublishOptions) SetExportToCSVOption(v *ExportToCSVOption) *DashboardPublishOptions { - s.ExportToCSVOption = v +// SetRequestId sets the RequestId field's value. +func (s *DescribeAccountSettingsOutput) SetRequestId(v string) *DescribeAccountSettingsOutput { + s.RequestId = &v return s } -// SetSheetControlsOption sets the SheetControlsOption field's value. -func (s *DashboardPublishOptions) SetSheetControlsOption(v *SheetControlsOption) *DashboardPublishOptions { - s.SheetControlsOption = v +// SetStatus sets the Status field's value. +func (s *DescribeAccountSettingsOutput) SetStatus(v int64) *DescribeAccountSettingsOutput { + s.Status = &v return s } -// A filter that you apply when searching for dashboards. -type DashboardSearchFilter struct { +type DescribeDashboardInput struct { _ struct{} `type:"structure"` - // The name of the value that you want to use as a filter. For example, "Name": - // "QUICKSIGHT_USER". - Name *string `type:"string" enum:"DashboardFilterAttribute"` + // The alias name. + AliasName *string `location:"querystring" locationName:"alias-name" min:"1" type:"string"` - // The comparison operator that you want to use as a filter. For example, "Operator": - // "StringEquals". + // The ID of the AWS account that contains the dashboard that you're describing. // - // Operator is a required field - Operator *string `type:"string" required:"true" enum:"FilterOperator"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The value of the named item, in this case QUICKSIGHT_USER, that you want - // to use as a filter. For example, "Value": "arn:aws:quicksight:us-east-1:1:user/default/UserName1". - Value *string `type:"string"` + // The ID for the dashboard. + // + // DashboardId is a required field + DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` + + // The version number for the dashboard. If a version number isn't passed, the + // latest published dashboard version is described. + VersionNumber *int64 `location:"querystring" locationName:"version-number" min:"1" type:"long"` } // String returns the string representation -func (s DashboardSearchFilter) String() string { +func (s DescribeDashboardInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DashboardSearchFilter) GoString() string { +func (s DescribeDashboardInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DashboardSearchFilter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DashboardSearchFilter"} - if s.Operator == nil { - invalidParams.Add(request.NewErrParamRequired("Operator")) +func (s *DescribeDashboardInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeDashboardInput"} + if s.AliasName != nil && len(*s.AliasName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) + } + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DashboardId == nil { + invalidParams.Add(request.NewErrParamRequired("DashboardId")) + } + if s.DashboardId != nil && len(*s.DashboardId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) + } + if s.VersionNumber != nil && *s.VersionNumber < 1 { + invalidParams.Add(request.NewErrParamMinValue("VersionNumber", 1)) } if invalidParams.Len() > 0 { @@ -10278,109 +16899,110 @@ func (s *DashboardSearchFilter) Validate() error { return nil } -// SetName sets the Name field's value. -func (s *DashboardSearchFilter) SetName(v string) *DashboardSearchFilter { - s.Name = &v +// SetAliasName sets the AliasName field's value. +func (s *DescribeDashboardInput) SetAliasName(v string) *DescribeDashboardInput { + s.AliasName = &v return s } -// SetOperator sets the Operator field's value. -func (s *DashboardSearchFilter) SetOperator(v string) *DashboardSearchFilter { - s.Operator = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeDashboardInput) SetAwsAccountId(v string) *DescribeDashboardInput { + s.AwsAccountId = &v return s } -// SetValue sets the Value field's value. -func (s *DashboardSearchFilter) SetValue(v string) *DashboardSearchFilter { - s.Value = &v +// SetDashboardId sets the DashboardId field's value. +func (s *DescribeDashboardInput) SetDashboardId(v string) *DescribeDashboardInput { + s.DashboardId = &v return s } -// Dashboard source entity. -type DashboardSourceEntity struct { +// SetVersionNumber sets the VersionNumber field's value. +func (s *DescribeDashboardInput) SetVersionNumber(v int64) *DescribeDashboardInput { + s.VersionNumber = &v + return s +} + +type DescribeDashboardOutput struct { _ struct{} `type:"structure"` - // Source template. - SourceTemplate *DashboardSourceTemplate `type:"structure"` + // Information about the dashboard. + Dashboard *Dashboard `type:"structure"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of this request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s DashboardSourceEntity) String() string { +func (s DescribeDashboardOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DashboardSourceEntity) GoString() string { +func (s DescribeDashboardOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DashboardSourceEntity) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DashboardSourceEntity"} - if s.SourceTemplate != nil { - if err := s.SourceTemplate.Validate(); err != nil { - invalidParams.AddNested("SourceTemplate", err.(request.ErrInvalidParams)) - } - } +// SetDashboard sets the Dashboard field's value. +func (s *DescribeDashboardOutput) SetDashboard(v *Dashboard) *DescribeDashboardOutput { + s.Dashboard = v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetRequestId sets the RequestId field's value. +func (s *DescribeDashboardOutput) SetRequestId(v string) *DescribeDashboardOutput { + s.RequestId = &v + return s } -// SetSourceTemplate sets the SourceTemplate field's value. -func (s *DashboardSourceEntity) SetSourceTemplate(v *DashboardSourceTemplate) *DashboardSourceEntity { - s.SourceTemplate = v +// SetStatus sets the Status field's value. +func (s *DescribeDashboardOutput) SetStatus(v int64) *DescribeDashboardOutput { + s.Status = &v return s } -// Dashboard source template. -type DashboardSourceTemplate struct { +type DescribeDashboardPermissionsInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. + // The ID of the AWS account that contains the dashboard that you're describing + // permissions for. // - // Arn is a required field - Arn *string `type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Dataset references. + // The ID for the dashboard, also added to the IAM policy. // - // DataSetReferences is a required field - DataSetReferences []*DataSetReference `min:"1" type:"list" required:"true"` + // DashboardId is a required field + DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DashboardSourceTemplate) String() string { +func (s DescribeDashboardPermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DashboardSourceTemplate) GoString() string { +func (s DescribeDashboardPermissionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DashboardSourceTemplate) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DashboardSourceTemplate"} - if s.Arn == nil { - invalidParams.Add(request.NewErrParamRequired("Arn")) +func (s *DescribeDashboardPermissionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeDashboardPermissionsInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.DataSetReferences == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetReferences")) + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DataSetReferences != nil && len(s.DataSetReferences) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetReferences", 1)) + if s.DashboardId == nil { + invalidParams.Add(request.NewErrParamRequired("DashboardId")) } - if s.DataSetReferences != nil { - for i, v := range s.DataSetReferences { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DataSetReferences", i), err.(request.ErrInvalidParams)) - } - } + if s.DashboardId != nil && len(*s.DashboardId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) } if invalidParams.Len() > 0 { @@ -10389,445 +17011,435 @@ func (s *DashboardSourceTemplate) Validate() error { return nil } -// SetArn sets the Arn field's value. -func (s *DashboardSourceTemplate) SetArn(v string) *DashboardSourceTemplate { - s.Arn = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeDashboardPermissionsInput) SetAwsAccountId(v string) *DescribeDashboardPermissionsInput { + s.AwsAccountId = &v return s } -// SetDataSetReferences sets the DataSetReferences field's value. -func (s *DashboardSourceTemplate) SetDataSetReferences(v []*DataSetReference) *DashboardSourceTemplate { - s.DataSetReferences = v +// SetDashboardId sets the DashboardId field's value. +func (s *DescribeDashboardPermissionsInput) SetDashboardId(v string) *DescribeDashboardPermissionsInput { + s.DashboardId = &v return s } -// Dashboard summary. -type DashboardSummary struct { +type DescribeDashboardPermissionsOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. - Arn *string `type:"string"` - - // The time that this dashboard was created. - CreatedTime *time.Time `type:"timestamp"` + // The Amazon Resource Name (ARN) of the dashboard. + DashboardArn *string `type:"string"` - // Dashboard ID. + // The ID for the dashboard. DashboardId *string `min:"1" type:"string"` - // The last time that this dashboard was published. - LastPublishedTime *time.Time `type:"timestamp"` - - // The last time that this dashboard was updated. - LastUpdatedTime *time.Time `type:"timestamp"` + // A structure that contains the permissions for the dashboard. + Permissions []*ResourcePermission `min:"1" type:"list"` - // A display name for the dashboard. - Name *string `min:"1" type:"string"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // Published version number. - PublishedVersionNumber *int64 `min:"1" type:"long"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s DashboardSummary) String() string { +func (s DescribeDashboardPermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DashboardSummary) GoString() string { +func (s DescribeDashboardPermissionsOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *DashboardSummary) SetArn(v string) *DashboardSummary { - s.Arn = &v - return s -} - -// SetCreatedTime sets the CreatedTime field's value. -func (s *DashboardSummary) SetCreatedTime(v time.Time) *DashboardSummary { - s.CreatedTime = &v +// SetDashboardArn sets the DashboardArn field's value. +func (s *DescribeDashboardPermissionsOutput) SetDashboardArn(v string) *DescribeDashboardPermissionsOutput { + s.DashboardArn = &v return s } // SetDashboardId sets the DashboardId field's value. -func (s *DashboardSummary) SetDashboardId(v string) *DashboardSummary { +func (s *DescribeDashboardPermissionsOutput) SetDashboardId(v string) *DescribeDashboardPermissionsOutput { s.DashboardId = &v return s } -// SetLastPublishedTime sets the LastPublishedTime field's value. -func (s *DashboardSummary) SetLastPublishedTime(v time.Time) *DashboardSummary { - s.LastPublishedTime = &v - return s -} - -// SetLastUpdatedTime sets the LastUpdatedTime field's value. -func (s *DashboardSummary) SetLastUpdatedTime(v time.Time) *DashboardSummary { - s.LastUpdatedTime = &v +// SetPermissions sets the Permissions field's value. +func (s *DescribeDashboardPermissionsOutput) SetPermissions(v []*ResourcePermission) *DescribeDashboardPermissionsOutput { + s.Permissions = v return s } -// SetName sets the Name field's value. -func (s *DashboardSummary) SetName(v string) *DashboardSummary { - s.Name = &v +// SetRequestId sets the RequestId field's value. +func (s *DescribeDashboardPermissionsOutput) SetRequestId(v string) *DescribeDashboardPermissionsOutput { + s.RequestId = &v return s } -// SetPublishedVersionNumber sets the PublishedVersionNumber field's value. -func (s *DashboardSummary) SetPublishedVersionNumber(v int64) *DashboardSummary { - s.PublishedVersionNumber = &v +// SetStatus sets the Status field's value. +func (s *DescribeDashboardPermissionsOutput) SetStatus(v int64) *DescribeDashboardPermissionsOutput { + s.Status = &v return s } -// Dashboard version. -type DashboardVersion struct { +type DescribeDataSetInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. - Arn *string `type:"string"` - - // The time that this dashboard version was created. - CreatedTime *time.Time `type:"timestamp"` - - // Description. - Description *string `min:"1" type:"string"` - - // Errors. - Errors []*DashboardError `min:"1" type:"list"` - - // Source entity ARN. - SourceEntityArn *string `type:"string"` - - // The HTTP status of the request. - Status *string `type:"string" enum:"ResourceStatus"` + // The AWS account ID. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Version number. - VersionNumber *int64 `min:"1" type:"long"` + // The ID for the dataset that you want to create. This ID is unique per AWS + // Region for each AWS account. + // + // DataSetId is a required field + DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` } // String returns the string representation -func (s DashboardVersion) String() string { +func (s DescribeDataSetInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DashboardVersion) GoString() string { +func (s DescribeDataSetInput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *DashboardVersion) SetArn(v string) *DashboardVersion { - s.Arn = &v - return s -} - -// SetCreatedTime sets the CreatedTime field's value. -func (s *DashboardVersion) SetCreatedTime(v time.Time) *DashboardVersion { - s.CreatedTime = &v - return s -} - -// SetDescription sets the Description field's value. -func (s *DashboardVersion) SetDescription(v string) *DashboardVersion { - s.Description = &v - return s -} - -// SetErrors sets the Errors field's value. -func (s *DashboardVersion) SetErrors(v []*DashboardError) *DashboardVersion { - s.Errors = v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeDataSetInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeDataSetInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DataSetId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetId")) + } + if s.DataSetId != nil && len(*s.DataSetId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) + } -// SetSourceEntityArn sets the SourceEntityArn field's value. -func (s *DashboardVersion) SetSourceEntityArn(v string) *DashboardVersion { - s.SourceEntityArn = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetStatus sets the Status field's value. -func (s *DashboardVersion) SetStatus(v string) *DashboardVersion { - s.Status = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeDataSetInput) SetAwsAccountId(v string) *DescribeDataSetInput { + s.AwsAccountId = &v return s } -// SetVersionNumber sets the VersionNumber field's value. -func (s *DashboardVersion) SetVersionNumber(v int64) *DashboardVersion { - s.VersionNumber = &v +// SetDataSetId sets the DataSetId field's value. +func (s *DescribeDataSetInput) SetDataSetId(v string) *DescribeDataSetInput { + s.DataSetId = &v return s } -// Dashboard version summary. -type DashboardVersionSummary struct { +type DescribeDataSetOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. - Arn *string `type:"string"` - - // The time that this dashboard version was created. - CreatedTime *time.Time `type:"timestamp"` - - // Description. - Description *string `min:"1" type:"string"` + // Information on the dataset. + DataSet *DataSet `type:"structure"` - // Source entity ARN. - SourceEntityArn *string `type:"string"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` // The HTTP status of the request. - Status *string `type:"string" enum:"ResourceStatus"` - - // Version number. - VersionNumber *int64 `min:"1" type:"long"` + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s DashboardVersionSummary) String() string { +func (s DescribeDataSetOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DashboardVersionSummary) GoString() string { +func (s DescribeDataSetOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *DashboardVersionSummary) SetArn(v string) *DashboardVersionSummary { - s.Arn = &v - return s -} - -// SetCreatedTime sets the CreatedTime field's value. -func (s *DashboardVersionSummary) SetCreatedTime(v time.Time) *DashboardVersionSummary { - s.CreatedTime = &v - return s -} - -// SetDescription sets the Description field's value. -func (s *DashboardVersionSummary) SetDescription(v string) *DashboardVersionSummary { - s.Description = &v +// SetDataSet sets the DataSet field's value. +func (s *DescribeDataSetOutput) SetDataSet(v *DataSet) *DescribeDataSetOutput { + s.DataSet = v return s } -// SetSourceEntityArn sets the SourceEntityArn field's value. -func (s *DashboardVersionSummary) SetSourceEntityArn(v string) *DashboardVersionSummary { - s.SourceEntityArn = &v +// SetRequestId sets the RequestId field's value. +func (s *DescribeDataSetOutput) SetRequestId(v string) *DescribeDataSetOutput { + s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DashboardVersionSummary) SetStatus(v string) *DashboardVersionSummary { +func (s *DescribeDataSetOutput) SetStatus(v int64) *DescribeDataSetOutput { s.Status = &v return s } -// SetVersionNumber sets the VersionNumber field's value. -func (s *DashboardVersionSummary) SetVersionNumber(v int64) *DashboardVersionSummary { - s.VersionNumber = &v - return s -} - -// Dataset. -type DataSet struct { +type DescribeDataSetPermissionsInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. - Arn *string `type:"string"` + // The AWS account ID. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Groupings of columns that work together in certain Amazon QuickSight features. - // Currently, only geospatial hierarchy is supported. - ColumnGroups []*ColumnGroup `min:"1" type:"list"` + // The ID for the dataset that you want to create. This ID is unique per AWS + // Region for each AWS account. + // + // DataSetId is a required field + DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` +} - // The amount of SPICE capacity used by this dataset. This is 0 if the dataset - // isn't imported into SPICE. - ConsumedSpiceCapacityInBytes *int64 `type:"long"` +// String returns the string representation +func (s DescribeDataSetPermissionsInput) String() string { + return awsutil.Prettify(s) +} - // The time that this dataset was created. - CreatedTime *time.Time `type:"timestamp"` +// GoString returns the string representation +func (s DescribeDataSetPermissionsInput) GoString() string { + return s.String() +} - // The ID of the dataset. - DataSetId *string `type:"string"` +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeDataSetPermissionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeDataSetPermissionsInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DataSetId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetId")) + } + if s.DataSetId != nil && len(*s.DataSetId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) + } - // Indicates whether you want to import the data into SPICE. - ImportMode *string `type:"string" enum:"DataSetImportMode"` + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} - // The last time that this dataset was updated. - LastUpdatedTime *time.Time `type:"timestamp"` +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeDataSetPermissionsInput) SetAwsAccountId(v string) *DescribeDataSetPermissionsInput { + s.AwsAccountId = &v + return s +} - // Configures the combination and transformation of the data from the physical - // tables. - LogicalTableMap map[string]*LogicalTable `min:"1" type:"map"` +// SetDataSetId sets the DataSetId field's value. +func (s *DescribeDataSetPermissionsInput) SetDataSetId(v string) *DescribeDataSetPermissionsInput { + s.DataSetId = &v + return s +} - // A display name for the dataset. - Name *string `min:"1" type:"string"` +type DescribeDataSetPermissionsOutput struct { + _ struct{} `type:"structure"` - // The list of columns after all transforms. These columns are available in - // templates, analyses, and dashboards. - OutputColumns []*OutputColumn `type:"list"` + // The Amazon Resource Name (ARN) of the dataset. + DataSetArn *string `type:"string"` - // Declares the physical tables that are available in the underlying data sources. - PhysicalTableMap map[string]*PhysicalTable `min:"1" type:"map"` + // The ID for the dataset that you want to create. This ID is unique per AWS + // Region for each AWS account. + DataSetId *string `type:"string"` - // The row-level security configuration for the dataset. - RowLevelPermissionDataSet *RowLevelPermissionDataSet `type:"structure"` + // A list of resource permissions on the dataset. + Permissions []*ResourcePermission `min:"1" type:"list"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s DataSet) String() string { +func (s DescribeDataSetPermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DataSet) GoString() string { +func (s DescribeDataSetPermissionsOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *DataSet) SetArn(v string) *DataSet { - s.Arn = &v +// SetDataSetArn sets the DataSetArn field's value. +func (s *DescribeDataSetPermissionsOutput) SetDataSetArn(v string) *DescribeDataSetPermissionsOutput { + s.DataSetArn = &v return s } -// SetColumnGroups sets the ColumnGroups field's value. -func (s *DataSet) SetColumnGroups(v []*ColumnGroup) *DataSet { - s.ColumnGroups = v +// SetDataSetId sets the DataSetId field's value. +func (s *DescribeDataSetPermissionsOutput) SetDataSetId(v string) *DescribeDataSetPermissionsOutput { + s.DataSetId = &v return s } -// SetConsumedSpiceCapacityInBytes sets the ConsumedSpiceCapacityInBytes field's value. -func (s *DataSet) SetConsumedSpiceCapacityInBytes(v int64) *DataSet { - s.ConsumedSpiceCapacityInBytes = &v +// SetPermissions sets the Permissions field's value. +func (s *DescribeDataSetPermissionsOutput) SetPermissions(v []*ResourcePermission) *DescribeDataSetPermissionsOutput { + s.Permissions = v return s } -// SetCreatedTime sets the CreatedTime field's value. -func (s *DataSet) SetCreatedTime(v time.Time) *DataSet { - s.CreatedTime = &v +// SetRequestId sets the RequestId field's value. +func (s *DescribeDataSetPermissionsOutput) SetRequestId(v string) *DescribeDataSetPermissionsOutput { + s.RequestId = &v return s } -// SetDataSetId sets the DataSetId field's value. -func (s *DataSet) SetDataSetId(v string) *DataSet { - s.DataSetId = &v +// SetStatus sets the Status field's value. +func (s *DescribeDataSetPermissionsOutput) SetStatus(v int64) *DescribeDataSetPermissionsOutput { + s.Status = &v return s } -// SetImportMode sets the ImportMode field's value. -func (s *DataSet) SetImportMode(v string) *DataSet { - s.ImportMode = &v - return s -} +type DescribeDataSourceInput struct { + _ struct{} `type:"structure"` -// SetLastUpdatedTime sets the LastUpdatedTime field's value. -func (s *DataSet) SetLastUpdatedTime(v time.Time) *DataSet { - s.LastUpdatedTime = &v - return s + // The AWS account ID. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The ID of the data source. This ID is unique per AWS Region for each AWS + // account. + // + // DataSourceId is a required field + DataSourceId *string `location:"uri" locationName:"DataSourceId" type:"string" required:"true"` } -// SetLogicalTableMap sets the LogicalTableMap field's value. -func (s *DataSet) SetLogicalTableMap(v map[string]*LogicalTable) *DataSet { - s.LogicalTableMap = v - return s +// String returns the string representation +func (s DescribeDataSourceInput) String() string { + return awsutil.Prettify(s) } -// SetName sets the Name field's value. -func (s *DataSet) SetName(v string) *DataSet { - s.Name = &v - return s +// GoString returns the string representation +func (s DescribeDataSourceInput) GoString() string { + return s.String() } -// SetOutputColumns sets the OutputColumns field's value. -func (s *DataSet) SetOutputColumns(v []*OutputColumn) *DataSet { - s.OutputColumns = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeDataSourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeDataSourceInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DataSourceId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSourceId")) + } + if s.DataSourceId != nil && len(*s.DataSourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSourceId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetPhysicalTableMap sets the PhysicalTableMap field's value. -func (s *DataSet) SetPhysicalTableMap(v map[string]*PhysicalTable) *DataSet { - s.PhysicalTableMap = v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeDataSourceInput) SetAwsAccountId(v string) *DescribeDataSourceInput { + s.AwsAccountId = &v return s } -// SetRowLevelPermissionDataSet sets the RowLevelPermissionDataSet field's value. -func (s *DataSet) SetRowLevelPermissionDataSet(v *RowLevelPermissionDataSet) *DataSet { - s.RowLevelPermissionDataSet = v +// SetDataSourceId sets the DataSourceId field's value. +func (s *DescribeDataSourceInput) SetDataSourceId(v string) *DescribeDataSourceInput { + s.DataSourceId = &v return s } -// Dataset configuration. -type DataSetConfiguration struct { +type DescribeDataSourceOutput struct { _ struct{} `type:"structure"` - // A structure containing the list of column group schemas. - ColumnGroupSchemaList []*ColumnGroupSchema `type:"list"` + // The information on the data source. + DataSource *DataSource `type:"structure"` - // Dataset schema. - DataSetSchema *DataSetSchema `type:"structure"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // Placeholder. - Placeholder *string `type:"string"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s DataSetConfiguration) String() string { +func (s DescribeDataSourceOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DataSetConfiguration) GoString() string { +func (s DescribeDataSourceOutput) GoString() string { return s.String() } -// SetColumnGroupSchemaList sets the ColumnGroupSchemaList field's value. -func (s *DataSetConfiguration) SetColumnGroupSchemaList(v []*ColumnGroupSchema) *DataSetConfiguration { - s.ColumnGroupSchemaList = v +// SetDataSource sets the DataSource field's value. +func (s *DescribeDataSourceOutput) SetDataSource(v *DataSource) *DescribeDataSourceOutput { + s.DataSource = v return s } -// SetDataSetSchema sets the DataSetSchema field's value. -func (s *DataSetConfiguration) SetDataSetSchema(v *DataSetSchema) *DataSetConfiguration { - s.DataSetSchema = v +// SetRequestId sets the RequestId field's value. +func (s *DescribeDataSourceOutput) SetRequestId(v string) *DescribeDataSourceOutput { + s.RequestId = &v return s } -// SetPlaceholder sets the Placeholder field's value. -func (s *DataSetConfiguration) SetPlaceholder(v string) *DataSetConfiguration { - s.Placeholder = &v +// SetStatus sets the Status field's value. +func (s *DescribeDataSourceOutput) SetStatus(v int64) *DescribeDataSourceOutput { + s.Status = &v return s } -// Dataset reference. -type DataSetReference struct { +type DescribeDataSourcePermissionsInput struct { _ struct{} `type:"structure"` - // Dataset Amazon Resource Name (ARN). + // The AWS account ID. // - // DataSetArn is a required field - DataSetArn *string `type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Dataset placeholder. + // The ID of the data source. This ID is unique per AWS Region for each AWS + // account. // - // DataSetPlaceholder is a required field - DataSetPlaceholder *string `type:"string" required:"true"` + // DataSourceId is a required field + DataSourceId *string `location:"uri" locationName:"DataSourceId" type:"string" required:"true"` } // String returns the string representation -func (s DataSetReference) String() string { +func (s DescribeDataSourcePermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DataSetReference) GoString() string { +func (s DescribeDataSourcePermissionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DataSetReference) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DataSetReference"} - if s.DataSetArn == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetArn")) +func (s *DescribeDataSourcePermissionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeDataSourcePermissionsInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.DataSetPlaceholder == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetPlaceholder")) + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DataSourceId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSourceId")) + } + if s.DataSourceId != nil && len(*s.DataSourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSourceId", 1)) } if invalidParams.Len() > 0 { @@ -10836,266 +17448,244 @@ func (s *DataSetReference) Validate() error { return nil } -// SetDataSetArn sets the DataSetArn field's value. -func (s *DataSetReference) SetDataSetArn(v string) *DataSetReference { - s.DataSetArn = &v - return s -} - -// SetDataSetPlaceholder sets the DataSetPlaceholder field's value. -func (s *DataSetReference) SetDataSetPlaceholder(v string) *DataSetReference { - s.DataSetPlaceholder = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeDataSourcePermissionsInput) SetAwsAccountId(v string) *DescribeDataSourcePermissionsInput { + s.AwsAccountId = &v return s } -// Dataset schema. -type DataSetSchema struct { - _ struct{} `type:"structure"` - - // A structure containing the list of column schemas. - ColumnSchemaList []*ColumnSchema `type:"list"` -} - -// String returns the string representation -func (s DataSetSchema) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DataSetSchema) GoString() string { - return s.String() -} - -// SetColumnSchemaList sets the ColumnSchemaList field's value. -func (s *DataSetSchema) SetColumnSchemaList(v []*ColumnSchema) *DataSetSchema { - s.ColumnSchemaList = v +// SetDataSourceId sets the DataSourceId field's value. +func (s *DescribeDataSourcePermissionsInput) SetDataSourceId(v string) *DescribeDataSourcePermissionsInput { + s.DataSourceId = &v return s } -// Dataset summary. -type DataSetSummary struct { +type DescribeDataSourcePermissionsOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the dataset. - Arn *string `type:"string"` - - // The time that this dataset was created. - CreatedTime *time.Time `type:"timestamp"` - - // The ID of the dataset. - DataSetId *string `type:"string"` + // The Amazon Resource Name (ARN) of the data source. + DataSourceArn *string `type:"string"` - // Indicates whether you want to import the data into SPICE. - ImportMode *string `type:"string" enum:"DataSetImportMode"` + // The ID of the data source. This ID is unique per AWS Region for each AWS + // account. + DataSourceId *string `type:"string"` - // The last time that this dataset was updated. - LastUpdatedTime *time.Time `type:"timestamp"` + // A list of resource permissions on the data source. + Permissions []*ResourcePermission `min:"1" type:"list"` - // A display name for the dataset. - Name *string `min:"1" type:"string"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // The row-level security configuration for the dataset. - RowLevelPermissionDataSet *RowLevelPermissionDataSet `type:"structure"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s DataSetSummary) String() string { +func (s DescribeDataSourcePermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DataSetSummary) GoString() string { +func (s DescribeDataSourcePermissionsOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *DataSetSummary) SetArn(v string) *DataSetSummary { - s.Arn = &v - return s -} - -// SetCreatedTime sets the CreatedTime field's value. -func (s *DataSetSummary) SetCreatedTime(v time.Time) *DataSetSummary { - s.CreatedTime = &v - return s -} - -// SetDataSetId sets the DataSetId field's value. -func (s *DataSetSummary) SetDataSetId(v string) *DataSetSummary { - s.DataSetId = &v +// SetDataSourceArn sets the DataSourceArn field's value. +func (s *DescribeDataSourcePermissionsOutput) SetDataSourceArn(v string) *DescribeDataSourcePermissionsOutput { + s.DataSourceArn = &v return s } -// SetImportMode sets the ImportMode field's value. -func (s *DataSetSummary) SetImportMode(v string) *DataSetSummary { - s.ImportMode = &v +// SetDataSourceId sets the DataSourceId field's value. +func (s *DescribeDataSourcePermissionsOutput) SetDataSourceId(v string) *DescribeDataSourcePermissionsOutput { + s.DataSourceId = &v return s } -// SetLastUpdatedTime sets the LastUpdatedTime field's value. -func (s *DataSetSummary) SetLastUpdatedTime(v time.Time) *DataSetSummary { - s.LastUpdatedTime = &v +// SetPermissions sets the Permissions field's value. +func (s *DescribeDataSourcePermissionsOutput) SetPermissions(v []*ResourcePermission) *DescribeDataSourcePermissionsOutput { + s.Permissions = v return s } -// SetName sets the Name field's value. -func (s *DataSetSummary) SetName(v string) *DataSetSummary { - s.Name = &v +// SetRequestId sets the RequestId field's value. +func (s *DescribeDataSourcePermissionsOutput) SetRequestId(v string) *DescribeDataSourcePermissionsOutput { + s.RequestId = &v return s } -// SetRowLevelPermissionDataSet sets the RowLevelPermissionDataSet field's value. -func (s *DataSetSummary) SetRowLevelPermissionDataSet(v *RowLevelPermissionDataSet) *DataSetSummary { - s.RowLevelPermissionDataSet = v +// SetStatus sets the Status field's value. +func (s *DescribeDataSourcePermissionsOutput) SetStatus(v int64) *DescribeDataSourcePermissionsOutput { + s.Status = &v return s } -// The structure of a data source. -type DataSource struct { +type DescribeGroupInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the data source. - Arn *string `type:"string"` - - // The time that this data source was created. - CreatedTime *time.Time `type:"timestamp"` - - // The ID of the data source. This ID is unique per AWS Region for each AWS - // account. - DataSourceId *string `type:"string"` - - // The parameters that Amazon QuickSight uses to connect to your underlying - // source. This is a variant type structure. For this structure to be valid, - // only one of the attributes can be non-null. - DataSourceParameters *DataSourceParameters `type:"structure"` - - // Error information from the last update or the creation of the data source. - ErrorInfo *DataSourceErrorInfo `type:"structure"` - - // The last time that this data source was updated. - LastUpdatedTime *time.Time `type:"timestamp"` - - // A display name for the data source. - Name *string `min:"1" type:"string"` - - // Secure Socket Layer (SSL) properties that apply when QuickSight connects - // to your underlying source. - SslProperties *SslProperties `type:"structure"` - - // The HTTP status of the request. - Status *string `type:"string" enum:"ResourceStatus"` + // The ID for the AWS account that the group is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The type of the data source. This type indicates which database engine the - // data source connects to. - Type *string `type:"string" enum:"DataSourceType"` + // The name of the group that you want to describe. + // + // GroupName is a required field + GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` - // The VPC connection information. You need to use this parameter only when - // you want QuickSight to use a VPC connection when connecting to your underlying - // source. - VpcConnectionProperties *VpcConnectionProperties `type:"structure"` + // The namespace. Currently, you should set this to default. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` } // String returns the string representation -func (s DataSource) String() string { +func (s DescribeGroupInput) String() string { return awsutil.Prettify(s) } -// GoString returns the string representation -func (s DataSource) GoString() string { - return s.String() +// GoString returns the string representation +func (s DescribeGroupInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeGroupInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeGroupInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.GroupName == nil { + invalidParams.Add(request.NewErrParamRequired("GroupName")) + } + if s.GroupName != nil && len(*s.GroupName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetArn sets the Arn field's value. -func (s *DataSource) SetArn(v string) *DataSource { - s.Arn = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeGroupInput) SetAwsAccountId(v string) *DescribeGroupInput { + s.AwsAccountId = &v return s } -// SetCreatedTime sets the CreatedTime field's value. -func (s *DataSource) SetCreatedTime(v time.Time) *DataSource { - s.CreatedTime = &v +// SetGroupName sets the GroupName field's value. +func (s *DescribeGroupInput) SetGroupName(v string) *DescribeGroupInput { + s.GroupName = &v return s } -// SetDataSourceId sets the DataSourceId field's value. -func (s *DataSource) SetDataSourceId(v string) *DataSource { - s.DataSourceId = &v +// SetNamespace sets the Namespace field's value. +func (s *DescribeGroupInput) SetNamespace(v string) *DescribeGroupInput { + s.Namespace = &v return s } -// SetDataSourceParameters sets the DataSourceParameters field's value. -func (s *DataSource) SetDataSourceParameters(v *DataSourceParameters) *DataSource { - s.DataSourceParameters = v - return s +type DescribeGroupOutput struct { + _ struct{} `type:"structure"` + + // The name of the group. + Group *Group `type:"structure"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } -// SetErrorInfo sets the ErrorInfo field's value. -func (s *DataSource) SetErrorInfo(v *DataSourceErrorInfo) *DataSource { - s.ErrorInfo = v - return s +// String returns the string representation +func (s DescribeGroupOutput) String() string { + return awsutil.Prettify(s) } -// SetLastUpdatedTime sets the LastUpdatedTime field's value. -func (s *DataSource) SetLastUpdatedTime(v time.Time) *DataSource { - s.LastUpdatedTime = &v - return s +// GoString returns the string representation +func (s DescribeGroupOutput) GoString() string { + return s.String() } -// SetName sets the Name field's value. -func (s *DataSource) SetName(v string) *DataSource { - s.Name = &v +// SetGroup sets the Group field's value. +func (s *DescribeGroupOutput) SetGroup(v *Group) *DescribeGroupOutput { + s.Group = v return s } -// SetSslProperties sets the SslProperties field's value. -func (s *DataSource) SetSslProperties(v *SslProperties) *DataSource { - s.SslProperties = v +// SetRequestId sets the RequestId field's value. +func (s *DescribeGroupOutput) SetRequestId(v string) *DescribeGroupOutput { + s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DataSource) SetStatus(v string) *DataSource { +func (s *DescribeGroupOutput) SetStatus(v int64) *DescribeGroupOutput { s.Status = &v return s } -// SetType sets the Type field's value. -func (s *DataSource) SetType(v string) *DataSource { - s.Type = &v - return s -} +type DescribeIAMPolicyAssignmentInput struct { + _ struct{} `type:"structure"` -// SetVpcConnectionProperties sets the VpcConnectionProperties field's value. -func (s *DataSource) SetVpcConnectionProperties(v *VpcConnectionProperties) *DataSource { - s.VpcConnectionProperties = v - return s -} + // The name of the assignment. + // + // AssignmentName is a required field + AssignmentName *string `location:"uri" locationName:"AssignmentName" min:"1" type:"string" required:"true"` -// Data source credentials. -type DataSourceCredentials struct { - _ struct{} `type:"structure" sensitive:"true"` + // The ID of the AWS account that contains the assignment that you want to describe. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Credential pair. - CredentialPair *CredentialPair `type:"structure"` + // The namespace that contains the assignment. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` } // String returns the string representation -func (s DataSourceCredentials) String() string { +func (s DescribeIAMPolicyAssignmentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DataSourceCredentials) GoString() string { +func (s DescribeIAMPolicyAssignmentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DataSourceCredentials) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DataSourceCredentials"} - if s.CredentialPair != nil { - if err := s.CredentialPair.Validate(); err != nil { - invalidParams.AddNested("CredentialPair", err.(request.ErrInvalidParams)) - } +func (s *DescribeIAMPolicyAssignmentInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeIAMPolicyAssignmentInput"} + if s.AssignmentName == nil { + invalidParams.Add(request.NewErrParamRequired("AssignmentName")) + } + if s.AssignmentName != nil && len(*s.AssignmentName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AssignmentName", 1)) + } + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) } if invalidParams.Len() > 0 { @@ -11104,216 +17694,114 @@ func (s *DataSourceCredentials) Validate() error { return nil } -// SetCredentialPair sets the CredentialPair field's value. -func (s *DataSourceCredentials) SetCredentialPair(v *CredentialPair) *DataSourceCredentials { - s.CredentialPair = v +// SetAssignmentName sets the AssignmentName field's value. +func (s *DescribeIAMPolicyAssignmentInput) SetAssignmentName(v string) *DescribeIAMPolicyAssignmentInput { + s.AssignmentName = &v return s } -// Error information for the data source creation or update. -type DataSourceErrorInfo struct { +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeIAMPolicyAssignmentInput) SetAwsAccountId(v string) *DescribeIAMPolicyAssignmentInput { + s.AwsAccountId = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *DescribeIAMPolicyAssignmentInput) SetNamespace(v string) *DescribeIAMPolicyAssignmentInput { + s.Namespace = &v + return s +} + +type DescribeIAMPolicyAssignmentOutput struct { _ struct{} `type:"structure"` - // Error message. - Message *string `type:"string"` + // Information describing the IAM policy assignment. + IAMPolicyAssignment *IAMPolicyAssignment `type:"structure"` - // Error type. - Type *string `type:"string" enum:"DataSourceErrorInfoType"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s DataSourceErrorInfo) String() string { +func (s DescribeIAMPolicyAssignmentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DataSourceErrorInfo) GoString() string { +func (s DescribeIAMPolicyAssignmentOutput) GoString() string { return s.String() } -// SetMessage sets the Message field's value. -func (s *DataSourceErrorInfo) SetMessage(v string) *DataSourceErrorInfo { - s.Message = &v +// SetIAMPolicyAssignment sets the IAMPolicyAssignment field's value. +func (s *DescribeIAMPolicyAssignmentOutput) SetIAMPolicyAssignment(v *IAMPolicyAssignment) *DescribeIAMPolicyAssignmentOutput { + s.IAMPolicyAssignment = v return s } -// SetType sets the Type field's value. -func (s *DataSourceErrorInfo) SetType(v string) *DataSourceErrorInfo { - s.Type = &v +// SetRequestId sets the RequestId field's value. +func (s *DescribeIAMPolicyAssignmentOutput) SetRequestId(v string) *DescribeIAMPolicyAssignmentOutput { + s.RequestId = &v return s } -// The parameters that Amazon QuickSight uses to connect to your underlying -// data source. This is a variant type structure. For this structure to be valid, -// only one of the attributes can be non-null. -type DataSourceParameters struct { - _ struct{} `type:"structure"` - - // Amazon Elasticsearch Service parameters. - AmazonElasticsearchParameters *AmazonElasticsearchParameters `type:"structure"` - - // Amazon Athena parameters. - AthenaParameters *AthenaParameters `type:"structure"` - - // Amazon Aurora MySQL parameters. - AuroraParameters *AuroraParameters `type:"structure"` - - // Aurora PostgreSQL parameters. - AuroraPostgreSqlParameters *AuroraPostgreSqlParameters `type:"structure"` - - // AWS IoT Analytics parameters. - AwsIotAnalyticsParameters *AwsIotAnalyticsParameters `type:"structure"` - - // Jira parameters. - JiraParameters *JiraParameters `type:"structure"` - - // MariaDB parameters. - MariaDbParameters *MariaDbParameters `type:"structure"` - - // MySQL parameters. - MySqlParameters *MySqlParameters `type:"structure"` - - // PostgreSQL parameters. - PostgreSqlParameters *PostgreSqlParameters `type:"structure"` - - // Presto parameters. - PrestoParameters *PrestoParameters `type:"structure"` - - // Amazon RDS parameters. - RdsParameters *RdsParameters `type:"structure"` - - // Amazon Redshift parameters. - RedshiftParameters *RedshiftParameters `type:"structure"` - - // S3 parameters. - S3Parameters *S3Parameters `type:"structure"` - - // ServiceNow parameters. - ServiceNowParameters *ServiceNowParameters `type:"structure"` - - // Snowflake parameters. - SnowflakeParameters *SnowflakeParameters `type:"structure"` +// SetStatus sets the Status field's value. +func (s *DescribeIAMPolicyAssignmentOutput) SetStatus(v int64) *DescribeIAMPolicyAssignmentOutput { + s.Status = &v + return s +} - // Spark parameters. - SparkParameters *SparkParameters `type:"structure"` +type DescribeIngestionInput struct { + _ struct{} `type:"structure"` - // SQL Server parameters. - SqlServerParameters *SqlServerParameters `type:"structure"` + // The AWS account ID. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Teradata parameters. - TeradataParameters *TeradataParameters `type:"structure"` + // The ID of the dataset used in the ingestion. + // + // DataSetId is a required field + DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` - // Twitter parameters. - TwitterParameters *TwitterParameters `type:"structure"` + // An ID for the ingestion. + // + // IngestionId is a required field + IngestionId *string `location:"uri" locationName:"IngestionId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DataSourceParameters) String() string { +func (s DescribeIngestionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DataSourceParameters) GoString() string { +func (s DescribeIngestionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DataSourceParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DataSourceParameters"} - if s.AmazonElasticsearchParameters != nil { - if err := s.AmazonElasticsearchParameters.Validate(); err != nil { - invalidParams.AddNested("AmazonElasticsearchParameters", err.(request.ErrInvalidParams)) - } - } - if s.AthenaParameters != nil { - if err := s.AthenaParameters.Validate(); err != nil { - invalidParams.AddNested("AthenaParameters", err.(request.ErrInvalidParams)) - } - } - if s.AuroraParameters != nil { - if err := s.AuroraParameters.Validate(); err != nil { - invalidParams.AddNested("AuroraParameters", err.(request.ErrInvalidParams)) - } - } - if s.AuroraPostgreSqlParameters != nil { - if err := s.AuroraPostgreSqlParameters.Validate(); err != nil { - invalidParams.AddNested("AuroraPostgreSqlParameters", err.(request.ErrInvalidParams)) - } - } - if s.AwsIotAnalyticsParameters != nil { - if err := s.AwsIotAnalyticsParameters.Validate(); err != nil { - invalidParams.AddNested("AwsIotAnalyticsParameters", err.(request.ErrInvalidParams)) - } - } - if s.JiraParameters != nil { - if err := s.JiraParameters.Validate(); err != nil { - invalidParams.AddNested("JiraParameters", err.(request.ErrInvalidParams)) - } - } - if s.MariaDbParameters != nil { - if err := s.MariaDbParameters.Validate(); err != nil { - invalidParams.AddNested("MariaDbParameters", err.(request.ErrInvalidParams)) - } - } - if s.MySqlParameters != nil { - if err := s.MySqlParameters.Validate(); err != nil { - invalidParams.AddNested("MySqlParameters", err.(request.ErrInvalidParams)) - } - } - if s.PostgreSqlParameters != nil { - if err := s.PostgreSqlParameters.Validate(); err != nil { - invalidParams.AddNested("PostgreSqlParameters", err.(request.ErrInvalidParams)) - } - } - if s.PrestoParameters != nil { - if err := s.PrestoParameters.Validate(); err != nil { - invalidParams.AddNested("PrestoParameters", err.(request.ErrInvalidParams)) - } - } - if s.RdsParameters != nil { - if err := s.RdsParameters.Validate(); err != nil { - invalidParams.AddNested("RdsParameters", err.(request.ErrInvalidParams)) - } - } - if s.RedshiftParameters != nil { - if err := s.RedshiftParameters.Validate(); err != nil { - invalidParams.AddNested("RedshiftParameters", err.(request.ErrInvalidParams)) - } - } - if s.S3Parameters != nil { - if err := s.S3Parameters.Validate(); err != nil { - invalidParams.AddNested("S3Parameters", err.(request.ErrInvalidParams)) - } - } - if s.ServiceNowParameters != nil { - if err := s.ServiceNowParameters.Validate(); err != nil { - invalidParams.AddNested("ServiceNowParameters", err.(request.ErrInvalidParams)) - } +func (s *DescribeIngestionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeIngestionInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.SnowflakeParameters != nil { - if err := s.SnowflakeParameters.Validate(); err != nil { - invalidParams.AddNested("SnowflakeParameters", err.(request.ErrInvalidParams)) - } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.SparkParameters != nil { - if err := s.SparkParameters.Validate(); err != nil { - invalidParams.AddNested("SparkParameters", err.(request.ErrInvalidParams)) - } + if s.DataSetId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetId")) } - if s.SqlServerParameters != nil { - if err := s.SqlServerParameters.Validate(); err != nil { - invalidParams.AddNested("SqlServerParameters", err.(request.ErrInvalidParams)) - } + if s.DataSetId != nil && len(*s.DataSetId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) } - if s.TeradataParameters != nil { - if err := s.TeradataParameters.Validate(); err != nil { - invalidParams.AddNested("TeradataParameters", err.(request.ErrInvalidParams)) - } + if s.IngestionId == nil { + invalidParams.Add(request.NewErrParamRequired("IngestionId")) } - if s.TwitterParameters != nil { - if err := s.TwitterParameters.Validate(); err != nil { - invalidParams.AddNested("TwitterParameters", err.(request.ErrInvalidParams)) - } + if s.IngestionId != nil && len(*s.IngestionId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("IngestionId", 1)) } if invalidParams.Len() > 0 { @@ -11322,153 +17810,221 @@ func (s *DataSourceParameters) Validate() error { return nil } -// SetAmazonElasticsearchParameters sets the AmazonElasticsearchParameters field's value. -func (s *DataSourceParameters) SetAmazonElasticsearchParameters(v *AmazonElasticsearchParameters) *DataSourceParameters { - s.AmazonElasticsearchParameters = v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeIngestionInput) SetAwsAccountId(v string) *DescribeIngestionInput { + s.AwsAccountId = &v return s } -// SetAthenaParameters sets the AthenaParameters field's value. -func (s *DataSourceParameters) SetAthenaParameters(v *AthenaParameters) *DataSourceParameters { - s.AthenaParameters = v +// SetDataSetId sets the DataSetId field's value. +func (s *DescribeIngestionInput) SetDataSetId(v string) *DescribeIngestionInput { + s.DataSetId = &v return s } -// SetAuroraParameters sets the AuroraParameters field's value. -func (s *DataSourceParameters) SetAuroraParameters(v *AuroraParameters) *DataSourceParameters { - s.AuroraParameters = v +// SetIngestionId sets the IngestionId field's value. +func (s *DescribeIngestionInput) SetIngestionId(v string) *DescribeIngestionInput { + s.IngestionId = &v return s } -// SetAuroraPostgreSqlParameters sets the AuroraPostgreSqlParameters field's value. -func (s *DataSourceParameters) SetAuroraPostgreSqlParameters(v *AuroraPostgreSqlParameters) *DataSourceParameters { - s.AuroraPostgreSqlParameters = v - return s +type DescribeIngestionOutput struct { + _ struct{} `type:"structure"` + + // Information about the ingestion. + Ingestion *Ingestion `type:"structure"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } -// SetAwsIotAnalyticsParameters sets the AwsIotAnalyticsParameters field's value. -func (s *DataSourceParameters) SetAwsIotAnalyticsParameters(v *AwsIotAnalyticsParameters) *DataSourceParameters { - s.AwsIotAnalyticsParameters = v - return s +// String returns the string representation +func (s DescribeIngestionOutput) String() string { + return awsutil.Prettify(s) } -// SetJiraParameters sets the JiraParameters field's value. -func (s *DataSourceParameters) SetJiraParameters(v *JiraParameters) *DataSourceParameters { - s.JiraParameters = v - return s +// GoString returns the string representation +func (s DescribeIngestionOutput) GoString() string { + return s.String() } -// SetMariaDbParameters sets the MariaDbParameters field's value. -func (s *DataSourceParameters) SetMariaDbParameters(v *MariaDbParameters) *DataSourceParameters { - s.MariaDbParameters = v +// SetIngestion sets the Ingestion field's value. +func (s *DescribeIngestionOutput) SetIngestion(v *Ingestion) *DescribeIngestionOutput { + s.Ingestion = v return s } -// SetMySqlParameters sets the MySqlParameters field's value. -func (s *DataSourceParameters) SetMySqlParameters(v *MySqlParameters) *DataSourceParameters { - s.MySqlParameters = v +// SetRequestId sets the RequestId field's value. +func (s *DescribeIngestionOutput) SetRequestId(v string) *DescribeIngestionOutput { + s.RequestId = &v return s } -// SetPostgreSqlParameters sets the PostgreSqlParameters field's value. -func (s *DataSourceParameters) SetPostgreSqlParameters(v *PostgreSqlParameters) *DataSourceParameters { - s.PostgreSqlParameters = v +// SetStatus sets the Status field's value. +func (s *DescribeIngestionOutput) SetStatus(v int64) *DescribeIngestionOutput { + s.Status = &v return s } -// SetPrestoParameters sets the PrestoParameters field's value. -func (s *DataSourceParameters) SetPrestoParameters(v *PrestoParameters) *DataSourceParameters { - s.PrestoParameters = v - return s +type DescribeNamespaceInput struct { + _ struct{} `type:"structure"` + + // The ID for the AWS account that contains the QuickSight namespace that you + // want to describe. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The namespace that you want to describe. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` } -// SetRdsParameters sets the RdsParameters field's value. -func (s *DataSourceParameters) SetRdsParameters(v *RdsParameters) *DataSourceParameters { - s.RdsParameters = v - return s +// String returns the string representation +func (s DescribeNamespaceInput) String() string { + return awsutil.Prettify(s) } -// SetRedshiftParameters sets the RedshiftParameters field's value. -func (s *DataSourceParameters) SetRedshiftParameters(v *RedshiftParameters) *DataSourceParameters { - s.RedshiftParameters = v - return s +// GoString returns the string representation +func (s DescribeNamespaceInput) GoString() string { + return s.String() } -// SetS3Parameters sets the S3Parameters field's value. -func (s *DataSourceParameters) SetS3Parameters(v *S3Parameters) *DataSourceParameters { - s.S3Parameters = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeNamespaceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeNamespaceInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetServiceNowParameters sets the ServiceNowParameters field's value. -func (s *DataSourceParameters) SetServiceNowParameters(v *ServiceNowParameters) *DataSourceParameters { - s.ServiceNowParameters = v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeNamespaceInput) SetAwsAccountId(v string) *DescribeNamespaceInput { + s.AwsAccountId = &v return s } -// SetSnowflakeParameters sets the SnowflakeParameters field's value. -func (s *DataSourceParameters) SetSnowflakeParameters(v *SnowflakeParameters) *DataSourceParameters { - s.SnowflakeParameters = v +// SetNamespace sets the Namespace field's value. +func (s *DescribeNamespaceInput) SetNamespace(v string) *DescribeNamespaceInput { + s.Namespace = &v return s } -// SetSparkParameters sets the SparkParameters field's value. -func (s *DataSourceParameters) SetSparkParameters(v *SparkParameters) *DataSourceParameters { - s.SparkParameters = v - return s +type DescribeNamespaceOutput struct { + _ struct{} `type:"structure"` + + // The information about the namespace that you're describing. The response + // includes the namespace ARN, name, AWS Region, creation status, and identity + // store. DescribeNamespace also works for namespaces that are in the process + // of being created. For incomplete namespaces, this API lists the namespace + // error types and messages associated with the creation process. + Namespace *NamespaceInfoV2 `type:"structure"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` +} + +// String returns the string representation +func (s DescribeNamespaceOutput) String() string { + return awsutil.Prettify(s) } -// SetSqlServerParameters sets the SqlServerParameters field's value. -func (s *DataSourceParameters) SetSqlServerParameters(v *SqlServerParameters) *DataSourceParameters { - s.SqlServerParameters = v +// GoString returns the string representation +func (s DescribeNamespaceOutput) GoString() string { + return s.String() +} + +// SetNamespace sets the Namespace field's value. +func (s *DescribeNamespaceOutput) SetNamespace(v *NamespaceInfoV2) *DescribeNamespaceOutput { + s.Namespace = v return s } -// SetTeradataParameters sets the TeradataParameters field's value. -func (s *DataSourceParameters) SetTeradataParameters(v *TeradataParameters) *DataSourceParameters { - s.TeradataParameters = v +// SetRequestId sets the RequestId field's value. +func (s *DescribeNamespaceOutput) SetRequestId(v string) *DescribeNamespaceOutput { + s.RequestId = &v return s } -// SetTwitterParameters sets the TwitterParameters field's value. -func (s *DataSourceParameters) SetTwitterParameters(v *TwitterParameters) *DataSourceParameters { - s.TwitterParameters = v +// SetStatus sets the Status field's value. +func (s *DescribeNamespaceOutput) SetStatus(v int64) *DescribeNamespaceOutput { + s.Status = &v return s } -// Date time parameter. -type DateTimeParameter struct { +type DescribeTemplateAliasInput struct { _ struct{} `type:"structure"` - // A display name for the dataset. + // The name of the template alias that you want to describe. If you name a specific + // alias, you describe the version that the alias points to. You can specify + // the latest version of the template by providing the keyword $LATEST in the + // AliasName parameter. The keyword $PUBLISHED doesn't apply to templates. // - // Name is a required field - Name *string `type:"string" required:"true"` + // AliasName is a required field + AliasName *string `location:"uri" locationName:"AliasName" min:"1" type:"string" required:"true"` - // Values. + // The ID of the AWS account that contains the template alias that you're describing. // - // Values is a required field - Values []*time.Time `type:"list" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The ID for the template. + // + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DateTimeParameter) String() string { +func (s DescribeTemplateAliasInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DateTimeParameter) GoString() string { +func (s DescribeTemplateAliasInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DateTimeParameter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DateTimeParameter"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) +func (s *DescribeTemplateAliasInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeTemplateAliasInput"} + if s.AliasName == nil { + invalidParams.Add(request.NewErrParamRequired("AliasName")) } - if s.Values == nil { - invalidParams.Add(request.NewErrParamRequired("Values")) + if s.AliasName != nil && len(*s.AliasName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) + } + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) + } + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) } if invalidParams.Len() > 0 { @@ -11477,113 +18033,116 @@ func (s *DateTimeParameter) Validate() error { return nil } -// SetName sets the Name field's value. -func (s *DateTimeParameter) SetName(v string) *DateTimeParameter { - s.Name = &v +// SetAliasName sets the AliasName field's value. +func (s *DescribeTemplateAliasInput) SetAliasName(v string) *DescribeTemplateAliasInput { + s.AliasName = &v return s } -// SetValues sets the Values field's value. -func (s *DateTimeParameter) SetValues(v []*time.Time) *DateTimeParameter { - s.Values = v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeTemplateAliasInput) SetAwsAccountId(v string) *DescribeTemplateAliasInput { + s.AwsAccountId = &v return s } -// Decimal parameter. -type DecimalParameter struct { +// SetTemplateId sets the TemplateId field's value. +func (s *DescribeTemplateAliasInput) SetTemplateId(v string) *DescribeTemplateAliasInput { + s.TemplateId = &v + return s +} + +type DescribeTemplateAliasOutput struct { _ struct{} `type:"structure"` - // A display name for the dataset. - // - // Name is a required field - Name *string `type:"string" required:"true"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // Values. - // - // Values is a required field - Values []*float64 `type:"list" required:"true"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` + + // Information about the template alias. + TemplateAlias *TemplateAlias `type:"structure"` } // String returns the string representation -func (s DecimalParameter) String() string { +func (s DescribeTemplateAliasOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DecimalParameter) GoString() string { +func (s DescribeTemplateAliasOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DecimalParameter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DecimalParameter"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Values == nil { - invalidParams.Add(request.NewErrParamRequired("Values")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetRequestId sets the RequestId field's value. +func (s *DescribeTemplateAliasOutput) SetRequestId(v string) *DescribeTemplateAliasOutput { + s.RequestId = &v + return s } -// SetName sets the Name field's value. -func (s *DecimalParameter) SetName(v string) *DecimalParameter { - s.Name = &v +// SetStatus sets the Status field's value. +func (s *DescribeTemplateAliasOutput) SetStatus(v int64) *DescribeTemplateAliasOutput { + s.Status = &v return s } -// SetValues sets the Values field's value. -func (s *DecimalParameter) SetValues(v []*float64) *DecimalParameter { - s.Values = v +// SetTemplateAlias sets the TemplateAlias field's value. +func (s *DescribeTemplateAliasOutput) SetTemplateAlias(v *TemplateAlias) *DescribeTemplateAliasOutput { + s.TemplateAlias = v return s } -type DeleteDashboardInput struct { +type DescribeTemplateInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the dashboard that you're deleting. + // The alias of the template that you want to describe. If you name a specific + // alias, you describe the version that the alias points to. You can specify + // the latest version of the template by providing the keyword $LATEST in the + // AliasName parameter. The keyword $PUBLISHED doesn't apply to templates. + AliasName *string `location:"querystring" locationName:"alias-name" min:"1" type:"string"` + + // The ID of the AWS account that contains the template that you're describing. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the dashboard. + // The ID for the template. // - // DashboardId is a required field - DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` - // The version number of the dashboard. If the version number property is provided, - // only the specified version of the dashboard is deleted. + // (Optional) The number for the version to describe. If a VersionNumber parameter + // value isn't provided, the latest version of the template is described. VersionNumber *int64 `location:"querystring" locationName:"version-number" min:"1" type:"long"` } // String returns the string representation -func (s DeleteDashboardInput) String() string { +func (s DescribeTemplateInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDashboardInput) GoString() string { +func (s DescribeTemplateInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDashboardInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDashboardInput"} +func (s *DescribeTemplateInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeTemplateInput"} + if s.AliasName != nil && len(*s.AliasName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) + } if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DashboardId == nil { - invalidParams.Add(request.NewErrParamRequired("DashboardId")) + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) } - if s.DashboardId != nil && len(*s.DashboardId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) } if s.VersionNumber != nil && *s.VersionNumber < 1 { invalidParams.Add(request.NewErrParamMinValue("VersionNumber", 1)) @@ -11595,113 +18154,109 @@ func (s *DeleteDashboardInput) Validate() error { return nil } +// SetAliasName sets the AliasName field's value. +func (s *DescribeTemplateInput) SetAliasName(v string) *DescribeTemplateInput { + s.AliasName = &v + return s +} + // SetAwsAccountId sets the AwsAccountId field's value. -func (s *DeleteDashboardInput) SetAwsAccountId(v string) *DeleteDashboardInput { +func (s *DescribeTemplateInput) SetAwsAccountId(v string) *DescribeTemplateInput { s.AwsAccountId = &v return s } -// SetDashboardId sets the DashboardId field's value. -func (s *DeleteDashboardInput) SetDashboardId(v string) *DeleteDashboardInput { - s.DashboardId = &v +// SetTemplateId sets the TemplateId field's value. +func (s *DescribeTemplateInput) SetTemplateId(v string) *DescribeTemplateInput { + s.TemplateId = &v return s } // SetVersionNumber sets the VersionNumber field's value. -func (s *DeleteDashboardInput) SetVersionNumber(v int64) *DeleteDashboardInput { +func (s *DescribeTemplateInput) SetVersionNumber(v int64) *DescribeTemplateInput { s.VersionNumber = &v return s } -type DeleteDashboardOutput struct { +type DescribeTemplateOutput struct { _ struct{} `type:"structure"` - // The Secure Socket Layer (SSL) properties that apply for the resource. - Arn *string `type:"string"` - - // The ID of the dashboard. - DashboardId *string `min:"1" type:"string"` - // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // The template structure for the object you want to describe. + Template *Template `type:"structure"` } // String returns the string representation -func (s DeleteDashboardOutput) String() string { +func (s DescribeTemplateOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDashboardOutput) GoString() string { +func (s DescribeTemplateOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *DeleteDashboardOutput) SetArn(v string) *DeleteDashboardOutput { - s.Arn = &v - return s -} - -// SetDashboardId sets the DashboardId field's value. -func (s *DeleteDashboardOutput) SetDashboardId(v string) *DeleteDashboardOutput { - s.DashboardId = &v - return s -} - // SetRequestId sets the RequestId field's value. -func (s *DeleteDashboardOutput) SetRequestId(v string) *DeleteDashboardOutput { +func (s *DescribeTemplateOutput) SetRequestId(v string) *DescribeTemplateOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DeleteDashboardOutput) SetStatus(v int64) *DeleteDashboardOutput { +func (s *DescribeTemplateOutput) SetStatus(v int64) *DescribeTemplateOutput { s.Status = &v return s } -type DeleteDataSetInput struct { +// SetTemplate sets the Template field's value. +func (s *DescribeTemplateOutput) SetTemplate(v *Template) *DescribeTemplateOutput { + s.Template = v + return s +} + +type DescribeTemplatePermissionsInput struct { _ struct{} `type:"structure"` - // The AWS account ID. + // The ID of the AWS account that contains the template that you're describing. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the dataset that you want to create. This ID is unique per AWS - // Region for each AWS account. + // The ID for the template. // - // DataSetId is a required field - DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DeleteDataSetInput) String() string { +func (s DescribeTemplatePermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDataSetInput) GoString() string { +func (s DescribeTemplatePermissionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDataSetInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDataSetInput"} +func (s *DescribeTemplatePermissionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeTemplatePermissionsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DataSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetId")) - } - if s.DataSetId != nil && len(*s.DataSetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) + } + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) } if invalidParams.Len() > 0 { @@ -11711,107 +18266,125 @@ func (s *DeleteDataSetInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *DeleteDataSetInput) SetAwsAccountId(v string) *DeleteDataSetInput { +func (s *DescribeTemplatePermissionsInput) SetAwsAccountId(v string) *DescribeTemplatePermissionsInput { s.AwsAccountId = &v return s } -// SetDataSetId sets the DataSetId field's value. -func (s *DeleteDataSetInput) SetDataSetId(v string) *DeleteDataSetInput { - s.DataSetId = &v +// SetTemplateId sets the TemplateId field's value. +func (s *DescribeTemplatePermissionsInput) SetTemplateId(v string) *DescribeTemplatePermissionsInput { + s.TemplateId = &v return s } -type DeleteDataSetOutput struct { +type DescribeTemplatePermissionsOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the dataset. - Arn *string `type:"string"` - - // The ID for the dataset that you want to create. This ID is unique per AWS - // Region for each AWS account. - DataSetId *string `type:"string"` + // A list of resource permissions to be set on the template. + Permissions []*ResourcePermission `min:"1" type:"list"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // The Amazon Resource Name (ARN) of the template. + TemplateArn *string `type:"string"` + + // The ID for the template. + TemplateId *string `min:"1" type:"string"` } // String returns the string representation -func (s DeleteDataSetOutput) String() string { +func (s DescribeTemplatePermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDataSetOutput) GoString() string { +func (s DescribeTemplatePermissionsOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *DeleteDataSetOutput) SetArn(v string) *DeleteDataSetOutput { - s.Arn = &v - return s -} - -// SetDataSetId sets the DataSetId field's value. -func (s *DeleteDataSetOutput) SetDataSetId(v string) *DeleteDataSetOutput { - s.DataSetId = &v +// SetPermissions sets the Permissions field's value. +func (s *DescribeTemplatePermissionsOutput) SetPermissions(v []*ResourcePermission) *DescribeTemplatePermissionsOutput { + s.Permissions = v return s } // SetRequestId sets the RequestId field's value. -func (s *DeleteDataSetOutput) SetRequestId(v string) *DeleteDataSetOutput { +func (s *DescribeTemplatePermissionsOutput) SetRequestId(v string) *DescribeTemplatePermissionsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DeleteDataSetOutput) SetStatus(v int64) *DeleteDataSetOutput { +func (s *DescribeTemplatePermissionsOutput) SetStatus(v int64) *DescribeTemplatePermissionsOutput { s.Status = &v return s } -type DeleteDataSourceInput struct { +// SetTemplateArn sets the TemplateArn field's value. +func (s *DescribeTemplatePermissionsOutput) SetTemplateArn(v string) *DescribeTemplatePermissionsOutput { + s.TemplateArn = &v + return s +} + +// SetTemplateId sets the TemplateId field's value. +func (s *DescribeTemplatePermissionsOutput) SetTemplateId(v string) *DescribeTemplatePermissionsOutput { + s.TemplateId = &v + return s +} + +type DescribeThemeAliasInput struct { _ struct{} `type:"structure"` - // The AWS account ID. + // The name of the theme alias that you want to describe. + // + // AliasName is a required field + AliasName *string `location:"uri" locationName:"AliasName" min:"1" type:"string" required:"true"` + + // The ID of the AWS account that contains the theme alias that you're describing. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID of the data source. This ID is unique per AWS Region for each AWS - // account. + // The ID for the theme. // - // DataSourceId is a required field - DataSourceId *string `location:"uri" locationName:"DataSourceId" type:"string" required:"true"` + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DeleteDataSourceInput) String() string { +func (s DescribeThemeAliasInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDataSourceInput) GoString() string { +func (s DescribeThemeAliasInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDataSourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDataSourceInput"} +func (s *DescribeThemeAliasInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeThemeAliasInput"} + if s.AliasName == nil { + invalidParams.Add(request.NewErrParamRequired("AliasName")) + } + if s.AliasName != nil && len(*s.AliasName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) + } if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DataSourceId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSourceId")) + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) } - if s.DataSourceId != nil && len(*s.DataSourceId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSourceId", 1)) + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) } if invalidParams.Len() > 0 { @@ -11820,119 +18393,119 @@ func (s *DeleteDataSourceInput) Validate() error { return nil } +// SetAliasName sets the AliasName field's value. +func (s *DescribeThemeAliasInput) SetAliasName(v string) *DescribeThemeAliasInput { + s.AliasName = &v + return s +} + // SetAwsAccountId sets the AwsAccountId field's value. -func (s *DeleteDataSourceInput) SetAwsAccountId(v string) *DeleteDataSourceInput { +func (s *DescribeThemeAliasInput) SetAwsAccountId(v string) *DescribeThemeAliasInput { s.AwsAccountId = &v return s } -// SetDataSourceId sets the DataSourceId field's value. -func (s *DeleteDataSourceInput) SetDataSourceId(v string) *DeleteDataSourceInput { - s.DataSourceId = &v +// SetThemeId sets the ThemeId field's value. +func (s *DescribeThemeAliasInput) SetThemeId(v string) *DescribeThemeAliasInput { + s.ThemeId = &v return s } -type DeleteDataSourceOutput struct { +type DescribeThemeAliasOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the data source that you deleted. - Arn *string `type:"string"` - - // The ID of the data source. This ID is unique per AWS Region for each AWS - // account. - DataSourceId *string `type:"string"` - // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // Information about the theme alias. + ThemeAlias *ThemeAlias `type:"structure"` } // String returns the string representation -func (s DeleteDataSourceOutput) String() string { +func (s DescribeThemeAliasOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteDataSourceOutput) GoString() string { +func (s DescribeThemeAliasOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *DeleteDataSourceOutput) SetArn(v string) *DeleteDataSourceOutput { - s.Arn = &v - return s -} - -// SetDataSourceId sets the DataSourceId field's value. -func (s *DeleteDataSourceOutput) SetDataSourceId(v string) *DeleteDataSourceOutput { - s.DataSourceId = &v - return s -} - // SetRequestId sets the RequestId field's value. -func (s *DeleteDataSourceOutput) SetRequestId(v string) *DeleteDataSourceOutput { +func (s *DescribeThemeAliasOutput) SetRequestId(v string) *DescribeThemeAliasOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DeleteDataSourceOutput) SetStatus(v int64) *DeleteDataSourceOutput { +func (s *DescribeThemeAliasOutput) SetStatus(v int64) *DescribeThemeAliasOutput { s.Status = &v return s } -type DeleteGroupInput struct { +// SetThemeAlias sets the ThemeAlias field's value. +func (s *DescribeThemeAliasOutput) SetThemeAlias(v *ThemeAlias) *DescribeThemeAliasOutput { + s.ThemeAlias = v + return s +} + +type DescribeThemeInput struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the group is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. + // The alias of the theme that you want to describe. If you name a specific + // alias, you describe the version that the alias points to. You can specify + // the latest version of the theme by providing the keyword $LATEST in the AliasName + // parameter. The keyword $PUBLISHED doesn't apply to themes. + AliasName *string `location:"querystring" locationName:"alias-name" min:"1" type:"string"` + + // The ID of the AWS account that contains the theme that you're describing. // // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" type:"string" required:"true"` - // The name of the group that you want to delete. + // The ID for the theme. // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` - // The namespace. Currently, you should set this to default. - // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // The version number for the version to describe. If a VersionNumber parameter + // value isn't provided, the latest version of the theme is described. + VersionNumber *int64 `location:"querystring" locationName:"version-number" min:"1" type:"long"` } // String returns the string representation -func (s DeleteGroupInput) String() string { +func (s DescribeThemeInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteGroupInput) GoString() string { +func (s DescribeThemeInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteGroupInput"} +func (s *DescribeThemeInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeThemeInput"} + if s.AliasName != nil && len(*s.AliasName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) + } if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 1)) } - if s.GroupName != nil && len(*s.GroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.VersionNumber != nil && *s.VersionNumber < 1 { + invalidParams.Add(request.NewErrParamMinValue("VersionNumber", 1)) } if invalidParams.Len() > 0 { @@ -11941,219 +18514,221 @@ func (s *DeleteGroupInput) Validate() error { return nil } +// SetAliasName sets the AliasName field's value. +func (s *DescribeThemeInput) SetAliasName(v string) *DescribeThemeInput { + s.AliasName = &v + return s +} + // SetAwsAccountId sets the AwsAccountId field's value. -func (s *DeleteGroupInput) SetAwsAccountId(v string) *DeleteGroupInput { +func (s *DescribeThemeInput) SetAwsAccountId(v string) *DescribeThemeInput { s.AwsAccountId = &v return s } -// SetGroupName sets the GroupName field's value. -func (s *DeleteGroupInput) SetGroupName(v string) *DeleteGroupInput { - s.GroupName = &v +// SetThemeId sets the ThemeId field's value. +func (s *DescribeThemeInput) SetThemeId(v string) *DescribeThemeInput { + s.ThemeId = &v return s } -// SetNamespace sets the Namespace field's value. -func (s *DeleteGroupInput) SetNamespace(v string) *DeleteGroupInput { - s.Namespace = &v +// SetVersionNumber sets the VersionNumber field's value. +func (s *DescribeThemeInput) SetVersionNumber(v int64) *DescribeThemeInput { + s.VersionNumber = &v return s } -type DeleteGroupMembershipInput struct { +type DescribeThemeOutput struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the group is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // The name of the group that you want to delete the user from. - // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // The name of the user that you want to delete from the group membership. - // - // MemberName is a required field - MemberName *string `location:"uri" locationName:"MemberName" min:"1" type:"string" required:"true"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` - // The namespace. Currently, you should set this to default. - // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // The information about the theme that you are describing. + Theme *Theme `type:"structure"` } // String returns the string representation -func (s DeleteGroupMembershipInput) String() string { +func (s DescribeThemeOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteGroupMembershipInput) GoString() string { +func (s DescribeThemeOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteGroupMembershipInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteGroupMembershipInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) - } - if s.GroupName != nil && len(*s.GroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) - } - if s.MemberName == nil { - invalidParams.Add(request.NewErrParamRequired("MemberName")) - } - if s.MemberName != nil && len(*s.MemberName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("MemberName", 1)) - } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) - } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DeleteGroupMembershipInput) SetAwsAccountId(v string) *DeleteGroupMembershipInput { - s.AwsAccountId = &v - return s -} - -// SetGroupName sets the GroupName field's value. -func (s *DeleteGroupMembershipInput) SetGroupName(v string) *DeleteGroupMembershipInput { - s.GroupName = &v +// SetRequestId sets the RequestId field's value. +func (s *DescribeThemeOutput) SetRequestId(v string) *DescribeThemeOutput { + s.RequestId = &v return s } -// SetMemberName sets the MemberName field's value. -func (s *DeleteGroupMembershipInput) SetMemberName(v string) *DeleteGroupMembershipInput { - s.MemberName = &v +// SetStatus sets the Status field's value. +func (s *DescribeThemeOutput) SetStatus(v int64) *DescribeThemeOutput { + s.Status = &v return s } -// SetNamespace sets the Namespace field's value. -func (s *DeleteGroupMembershipInput) SetNamespace(v string) *DeleteGroupMembershipInput { - s.Namespace = &v +// SetTheme sets the Theme field's value. +func (s *DescribeThemeOutput) SetTheme(v *Theme) *DescribeThemeOutput { + s.Theme = v return s } -type DeleteGroupMembershipOutput struct { +type DescribeThemePermissionsInput struct { _ struct{} `type:"structure"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // The ID of the AWS account that contains the theme that you're describing. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // The ID for the theme that you want to describe permissions for. + // + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DeleteGroupMembershipOutput) String() string { +func (s DescribeThemePermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteGroupMembershipOutput) GoString() string { +func (s DescribeThemePermissionsInput) GoString() string { return s.String() } -// SetRequestId sets the RequestId field's value. -func (s *DeleteGroupMembershipOutput) SetRequestId(v string) *DeleteGroupMembershipOutput { - s.RequestId = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeThemePermissionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeThemePermissionsInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) + } + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *DescribeThemePermissionsInput) SetAwsAccountId(v string) *DescribeThemePermissionsInput { + s.AwsAccountId = &v return s } -// SetStatus sets the Status field's value. -func (s *DeleteGroupMembershipOutput) SetStatus(v int64) *DeleteGroupMembershipOutput { - s.Status = &v +// SetThemeId sets the ThemeId field's value. +func (s *DescribeThemePermissionsInput) SetThemeId(v string) *DescribeThemePermissionsInput { + s.ThemeId = &v return s } -type DeleteGroupOutput struct { +type DescribeThemePermissionsOutput struct { _ struct{} `type:"structure"` + // A list of resource permissions set on the theme. + Permissions []*ResourcePermission `min:"1" type:"list"` + // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // The Amazon Resource Name (ARN) of the theme. + ThemeArn *string `type:"string"` + + // The ID for the theme. + ThemeId *string `min:"1" type:"string"` } // String returns the string representation -func (s DeleteGroupOutput) String() string { +func (s DescribeThemePermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteGroupOutput) GoString() string { +func (s DescribeThemePermissionsOutput) GoString() string { return s.String() } +// SetPermissions sets the Permissions field's value. +func (s *DescribeThemePermissionsOutput) SetPermissions(v []*ResourcePermission) *DescribeThemePermissionsOutput { + s.Permissions = v + return s +} + // SetRequestId sets the RequestId field's value. -func (s *DeleteGroupOutput) SetRequestId(v string) *DeleteGroupOutput { +func (s *DescribeThemePermissionsOutput) SetRequestId(v string) *DescribeThemePermissionsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DeleteGroupOutput) SetStatus(v int64) *DeleteGroupOutput { +func (s *DescribeThemePermissionsOutput) SetStatus(v int64) *DescribeThemePermissionsOutput { s.Status = &v return s } -type DeleteIAMPolicyAssignmentInput struct { - _ struct{} `type:"structure"` +// SetThemeArn sets the ThemeArn field's value. +func (s *DescribeThemePermissionsOutput) SetThemeArn(v string) *DescribeThemePermissionsOutput { + s.ThemeArn = &v + return s +} - // The name of the assignment. - // - // AssignmentName is a required field - AssignmentName *string `location:"uri" locationName:"AssignmentName" min:"1" type:"string" required:"true"` +// SetThemeId sets the ThemeId field's value. +func (s *DescribeThemePermissionsOutput) SetThemeId(v string) *DescribeThemePermissionsOutput { + s.ThemeId = &v + return s +} - // The AWS account ID where you want to delete the IAM policy assignment. +type DescribeUserInput struct { + _ struct{} `type:"structure"` + + // The ID for the AWS account that the user is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The namespace that contains the assignment. + // The namespace. Currently, you should set this to default. // // Namespace is a required field Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + + // The name of the user that you want to describe. + // + // UserName is a required field + UserName *string `location:"uri" locationName:"UserName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DeleteIAMPolicyAssignmentInput) String() string { +func (s DescribeUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteIAMPolicyAssignmentInput) GoString() string { +func (s DescribeUserInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteIAMPolicyAssignmentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteIAMPolicyAssignmentInput"} - if s.AssignmentName == nil { - invalidParams.Add(request.NewErrParamRequired("AssignmentName")) - } - if s.AssignmentName != nil && len(*s.AssignmentName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AssignmentName", 1)) - } +func (s *DescribeUserInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeUserInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } @@ -12166,6 +18741,12 @@ func (s *DeleteIAMPolicyAssignmentInput) Validate() error { if s.Namespace != nil && len(*s.Namespace) < 1 { invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) } + if s.UserName == nil { + invalidParams.Add(request.NewErrParamRequired("UserName")) + } + if s.UserName != nil && len(*s.UserName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -12173,246 +18754,211 @@ func (s *DeleteIAMPolicyAssignmentInput) Validate() error { return nil } -// SetAssignmentName sets the AssignmentName field's value. -func (s *DeleteIAMPolicyAssignmentInput) SetAssignmentName(v string) *DeleteIAMPolicyAssignmentInput { - s.AssignmentName = &v - return s -} - // SetAwsAccountId sets the AwsAccountId field's value. -func (s *DeleteIAMPolicyAssignmentInput) SetAwsAccountId(v string) *DeleteIAMPolicyAssignmentInput { +func (s *DescribeUserInput) SetAwsAccountId(v string) *DescribeUserInput { s.AwsAccountId = &v return s } // SetNamespace sets the Namespace field's value. -func (s *DeleteIAMPolicyAssignmentInput) SetNamespace(v string) *DeleteIAMPolicyAssignmentInput { +func (s *DescribeUserInput) SetNamespace(v string) *DescribeUserInput { s.Namespace = &v return s } -type DeleteIAMPolicyAssignmentOutput struct { - _ struct{} `type:"structure"` +// SetUserName sets the UserName field's value. +func (s *DescribeUserInput) SetUserName(v string) *DescribeUserInput { + s.UserName = &v + return s +} - // The name of the assignment. - AssignmentName *string `min:"1" type:"string"` +type DescribeUserOutput struct { + _ struct{} `type:"structure"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // The user name. + User *User `type:"structure"` } // String returns the string representation -func (s DeleteIAMPolicyAssignmentOutput) String() string { +func (s DescribeUserOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteIAMPolicyAssignmentOutput) GoString() string { +func (s DescribeUserOutput) GoString() string { return s.String() } -// SetAssignmentName sets the AssignmentName field's value. -func (s *DeleteIAMPolicyAssignmentOutput) SetAssignmentName(v string) *DeleteIAMPolicyAssignmentOutput { - s.AssignmentName = &v - return s -} - // SetRequestId sets the RequestId field's value. -func (s *DeleteIAMPolicyAssignmentOutput) SetRequestId(v string) *DeleteIAMPolicyAssignmentOutput { +func (s *DescribeUserOutput) SetRequestId(v string) *DescribeUserOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DeleteIAMPolicyAssignmentOutput) SetStatus(v int64) *DeleteIAMPolicyAssignmentOutput { +func (s *DescribeUserOutput) SetStatus(v int64) *DescribeUserOutput { s.Status = &v return s } -type DeleteTemplateAliasInput struct { - _ struct{} `type:"structure"` +// SetUser sets the User field's value. +func (s *DescribeUserOutput) SetUser(v *User) *DescribeUserOutput { + s.User = v + return s +} - // The name for the template alias. If you name a specific alias, you delete - // the version that the alias points to. You can specify the latest version - // of the template by providing the keyword $LATEST in the AliasName parameter. - // - // AliasName is a required field - AliasName *string `location:"uri" locationName:"AliasName" min:"1" type:"string" required:"true"` +// The domain specified isn't on the allow list. All domains for embedded dashboards +// must be added to the approved list by an Amazon QuickSight admin. +type DomainNotWhitelistedException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // The ID of the AWS account that contains the item to delete. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + Message_ *string `locationName:"Message" type:"string"` - // The ID for the template that the specified alias is for. - // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + // The AWS request ID for this request. + RequestId *string `type:"string"` } // String returns the string representation -func (s DeleteTemplateAliasInput) String() string { +func (s DomainNotWhitelistedException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteTemplateAliasInput) GoString() string { +func (s DomainNotWhitelistedException) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteTemplateAliasInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteTemplateAliasInput"} - if s.AliasName == nil { - invalidParams.Add(request.NewErrParamRequired("AliasName")) - } - if s.AliasName != nil && len(*s.AliasName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) - } - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) - } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) +func newErrorDomainNotWhitelistedException(v protocol.ResponseMetadata) error { + return &DomainNotWhitelistedException{ + RespMetadata: v, } +} - if invalidParams.Len() > 0 { - return invalidParams +// Code returns the exception type name. +func (s *DomainNotWhitelistedException) Code() string { + return "DomainNotWhitelistedException" +} + +// Message returns the exception's message. +func (s *DomainNotWhitelistedException) Message() string { + if s.Message_ != nil { + return *s.Message_ } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *DomainNotWhitelistedException) OrigErr() error { return nil } -// SetAliasName sets the AliasName field's value. -func (s *DeleteTemplateAliasInput) SetAliasName(v string) *DeleteTemplateAliasInput { - s.AliasName = &v - return s +func (s *DomainNotWhitelistedException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DeleteTemplateAliasInput) SetAwsAccountId(v string) *DeleteTemplateAliasInput { - s.AwsAccountId = &v - return s +// Status code returns the HTTP status code for the request's response error. +func (s *DomainNotWhitelistedException) StatusCode() int { + return s.RespMetadata.StatusCode } -// SetTemplateId sets the TemplateId field's value. -func (s *DeleteTemplateAliasInput) SetTemplateId(v string) *DeleteTemplateAliasInput { - s.TemplateId = &v - return s +// RequestID returns the service's response RequestID for request. +func (s *DomainNotWhitelistedException) RequestID() string { + return s.RespMetadata.RequestID } -type DeleteTemplateAliasOutput struct { +// Error information for the SPICE ingestion of a dataset. +type ErrorInfo struct { _ struct{} `type:"structure"` - // The name for the template alias. - AliasName *string `min:"1" type:"string"` - - // The Amazon Resource Name (ARN) of the resource. - Arn *string `type:"string"` - - // The AWS request ID for this operation. - RequestId *string `type:"string"` - - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // Error message. + Message *string `type:"string"` - // An ID for the template associated with the deletion. - TemplateId *string `min:"1" type:"string"` + // Error type. + Type *string `type:"string" enum:"IngestionErrorType"` } // String returns the string representation -func (s DeleteTemplateAliasOutput) String() string { +func (s ErrorInfo) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteTemplateAliasOutput) GoString() string { +func (s ErrorInfo) GoString() string { return s.String() } -// SetAliasName sets the AliasName field's value. -func (s *DeleteTemplateAliasOutput) SetAliasName(v string) *DeleteTemplateAliasOutput { - s.AliasName = &v +// SetMessage sets the Message field's value. +func (s *ErrorInfo) SetMessage(v string) *ErrorInfo { + s.Message = &v return s } -// SetArn sets the Arn field's value. -func (s *DeleteTemplateAliasOutput) SetArn(v string) *DeleteTemplateAliasOutput { - s.Arn = &v +// SetType sets the Type field's value. +func (s *ErrorInfo) SetType(v string) *ErrorInfo { + s.Type = &v return s } -// SetRequestId sets the RequestId field's value. -func (s *DeleteTemplateAliasOutput) SetRequestId(v string) *DeleteTemplateAliasOutput { - s.RequestId = &v - return s +// Export to .csv option. +type ExportToCSVOption struct { + _ struct{} `type:"structure"` + + // Availability status. + AvailabilityStatus *string `type:"string" enum:"DashboardBehavior"` } -// SetStatus sets the Status field's value. -func (s *DeleteTemplateAliasOutput) SetStatus(v int64) *DeleteTemplateAliasOutput { - s.Status = &v - return s +// String returns the string representation +func (s ExportToCSVOption) String() string { + return awsutil.Prettify(s) } -// SetTemplateId sets the TemplateId field's value. -func (s *DeleteTemplateAliasOutput) SetTemplateId(v string) *DeleteTemplateAliasOutput { - s.TemplateId = &v +// GoString returns the string representation +func (s ExportToCSVOption) GoString() string { + return s.String() +} + +// SetAvailabilityStatus sets the AvailabilityStatus field's value. +func (s *ExportToCSVOption) SetAvailabilityStatus(v string) *ExportToCSVOption { + s.AvailabilityStatus = &v return s } -type DeleteTemplateInput struct { +// A transform operation that filters rows based on a condition. +type FilterOperation struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the template that you're deleting. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // An ID for the template you want to delete. + // An expression that must evaluate to a Boolean value. Rows for which the expression + // evaluates to true are kept in the dataset. // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` - - // Specifies the version of the template that you want to delete. If you don't - // provide a version number, DeleteTemplate deletes all versions of the template. - VersionNumber *int64 `location:"querystring" locationName:"version-number" min:"1" type:"long"` + // ConditionExpression is a required field + ConditionExpression *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DeleteTemplateInput) String() string { +func (s FilterOperation) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteTemplateInput) GoString() string { +func (s FilterOperation) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteTemplateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteTemplateInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) - } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) +func (s *FilterOperation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "FilterOperation"} + if s.ConditionExpression == nil { + invalidParams.Add(request.NewErrParamRequired("ConditionExpression")) } - if s.VersionNumber != nil && *s.VersionNumber < 1 { - invalidParams.Add(request.NewErrParamMinValue("VersionNumber", 1)) + if s.ConditionExpression != nil && len(*s.ConditionExpression) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ConditionExpression", 1)) } if invalidParams.Len() > 0 { @@ -12421,124 +18967,158 @@ func (s *DeleteTemplateInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DeleteTemplateInput) SetAwsAccountId(v string) *DeleteTemplateInput { - s.AwsAccountId = &v - return s -} - -// SetTemplateId sets the TemplateId field's value. -func (s *DeleteTemplateInput) SetTemplateId(v string) *DeleteTemplateInput { - s.TemplateId = &v - return s -} - -// SetVersionNumber sets the VersionNumber field's value. -func (s *DeleteTemplateInput) SetVersionNumber(v int64) *DeleteTemplateInput { - s.VersionNumber = &v +// SetConditionExpression sets the ConditionExpression field's value. +func (s *FilterOperation) SetConditionExpression(v string) *FilterOperation { + s.ConditionExpression = &v return s } -type DeleteTemplateOutput struct { +// Geospatial column group that denotes a hierarchy. +type GeoSpatialColumnGroup struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. - Arn *string `type:"string"` - - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // Columns in this hierarchy. + // + // Columns is a required field + Columns []*string `min:"1" type:"list" required:"true"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // Country code. + // + // CountryCode is a required field + CountryCode *string `type:"string" required:"true" enum:"GeoSpatialCountryCode"` - // An ID for the template. - TemplateId *string `min:"1" type:"string"` + // A display name for the hierarchy. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DeleteTemplateOutput) String() string { +func (s GeoSpatialColumnGroup) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteTemplateOutput) GoString() string { +func (s GeoSpatialColumnGroup) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *DeleteTemplateOutput) SetArn(v string) *DeleteTemplateOutput { - s.Arn = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *GeoSpatialColumnGroup) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GeoSpatialColumnGroup"} + if s.Columns == nil { + invalidParams.Add(request.NewErrParamRequired("Columns")) + } + if s.Columns != nil && len(s.Columns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Columns", 1)) + } + if s.CountryCode == nil { + invalidParams.Add(request.NewErrParamRequired("CountryCode")) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetRequestId sets the RequestId field's value. -func (s *DeleteTemplateOutput) SetRequestId(v string) *DeleteTemplateOutput { - s.RequestId = &v +// SetColumns sets the Columns field's value. +func (s *GeoSpatialColumnGroup) SetColumns(v []*string) *GeoSpatialColumnGroup { + s.Columns = v return s } -// SetStatus sets the Status field's value. -func (s *DeleteTemplateOutput) SetStatus(v int64) *DeleteTemplateOutput { - s.Status = &v +// SetCountryCode sets the CountryCode field's value. +func (s *GeoSpatialColumnGroup) SetCountryCode(v string) *GeoSpatialColumnGroup { + s.CountryCode = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *DeleteTemplateOutput) SetTemplateId(v string) *DeleteTemplateOutput { - s.TemplateId = &v +// SetName sets the Name field's value. +func (s *GeoSpatialColumnGroup) SetName(v string) *GeoSpatialColumnGroup { + s.Name = &v return s } -type DeleteUserByPrincipalIdInput struct { +type GetDashboardEmbedUrlInput struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the user is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. + // The ID for the AWS account that contains the dashboard that you're embedding. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The namespace. Currently, you should set this to default. + // The ID for the dashboard, also added to the IAM policy. // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // DashboardId is a required field + DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` - // The principal ID of the user. + // The authentication method that the user uses to sign in. // - // PrincipalId is a required field - PrincipalId *string `location:"uri" locationName:"PrincipalId" type:"string" required:"true"` + // IdentityType is a required field + IdentityType *string `location:"querystring" locationName:"creds-type" type:"string" required:"true" enum:"IdentityType"` + + // Remove the reset button on the embedded dashboard. The default is FALSE, + // which enables the reset button. + ResetDisabled *bool `location:"querystring" locationName:"reset-disabled" type:"boolean"` + + // How many minutes the session is valid. The session lifetime must be 15-600 + // minutes. + SessionLifetimeInMinutes *int64 `location:"querystring" locationName:"session-lifetime" min:"15" type:"long"` + + // Remove the undo/redo button on the embedded dashboard. The default is FALSE, + // which enables the undo/redo button. + UndoRedoDisabled *bool `location:"querystring" locationName:"undo-redo-disabled" type:"boolean"` + + // The Amazon QuickSight user's Amazon Resource Name (ARN), for use with QUICKSIGHT + // identity type. You can use this for any Amazon QuickSight users in your account + // (readers, authors, or admins) authenticated as one of the following: + // + // * Active Directory (AD) users or group members + // + // * Invited nonfederated users + // + // * IAM users and IAM role-based sessions authenticated through Federated + // Single Sign-On using SAML, OpenID Connect, or IAM federation. + UserArn *string `location:"querystring" locationName:"user-arn" type:"string"` } // String returns the string representation -func (s DeleteUserByPrincipalIdInput) String() string { +func (s GetDashboardEmbedUrlInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteUserByPrincipalIdInput) GoString() string { +func (s GetDashboardEmbedUrlInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteUserByPrincipalIdInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteUserByPrincipalIdInput"} +func (s *GetDashboardEmbedUrlInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDashboardEmbedUrlInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.DashboardId == nil { + invalidParams.Add(request.NewErrParamRequired("DashboardId")) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.DashboardId != nil && len(*s.DashboardId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) } - if s.PrincipalId == nil { - invalidParams.Add(request.NewErrParamRequired("PrincipalId")) + if s.IdentityType == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityType")) } - if s.PrincipalId != nil && len(*s.PrincipalId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("PrincipalId", 1)) + if s.SessionLifetimeInMinutes != nil && *s.SessionLifetimeInMinutes < 15 { + invalidParams.Add(request.NewErrParamMinValue("SessionLifetimeInMinutes", 15)) } if invalidParams.Len() > 0 { @@ -12548,26 +19128,56 @@ func (s *DeleteUserByPrincipalIdInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *DeleteUserByPrincipalIdInput) SetAwsAccountId(v string) *DeleteUserByPrincipalIdInput { +func (s *GetDashboardEmbedUrlInput) SetAwsAccountId(v string) *GetDashboardEmbedUrlInput { s.AwsAccountId = &v return s } -// SetNamespace sets the Namespace field's value. -func (s *DeleteUserByPrincipalIdInput) SetNamespace(v string) *DeleteUserByPrincipalIdInput { - s.Namespace = &v +// SetDashboardId sets the DashboardId field's value. +func (s *GetDashboardEmbedUrlInput) SetDashboardId(v string) *GetDashboardEmbedUrlInput { + s.DashboardId = &v return s } -// SetPrincipalId sets the PrincipalId field's value. -func (s *DeleteUserByPrincipalIdInput) SetPrincipalId(v string) *DeleteUserByPrincipalIdInput { - s.PrincipalId = &v +// SetIdentityType sets the IdentityType field's value. +func (s *GetDashboardEmbedUrlInput) SetIdentityType(v string) *GetDashboardEmbedUrlInput { + s.IdentityType = &v + return s +} + +// SetResetDisabled sets the ResetDisabled field's value. +func (s *GetDashboardEmbedUrlInput) SetResetDisabled(v bool) *GetDashboardEmbedUrlInput { + s.ResetDisabled = &v + return s +} + +// SetSessionLifetimeInMinutes sets the SessionLifetimeInMinutes field's value. +func (s *GetDashboardEmbedUrlInput) SetSessionLifetimeInMinutes(v int64) *GetDashboardEmbedUrlInput { + s.SessionLifetimeInMinutes = &v + return s +} + +// SetUndoRedoDisabled sets the UndoRedoDisabled field's value. +func (s *GetDashboardEmbedUrlInput) SetUndoRedoDisabled(v bool) *GetDashboardEmbedUrlInput { + s.UndoRedoDisabled = &v + return s +} + +// SetUserArn sets the UserArn field's value. +func (s *GetDashboardEmbedUrlInput) SetUserArn(v string) *GetDashboardEmbedUrlInput { + s.UserArn = &v return s } -type DeleteUserByPrincipalIdOutput struct { +type GetDashboardEmbedUrlOutput struct { _ struct{} `type:"structure"` + // A single-use URL that you can put into your server-side webpage to embed + // your dashboard. This URL is valid for 5 minutes. The API provides the URL + // with an auth_code value that enables one (and only one) sign-on to a user + // session that is valid for 10 hours. + EmbedUrl *string `type:"string" sensitive:"true"` + // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -12576,77 +19186,86 @@ type DeleteUserByPrincipalIdOutput struct { } // String returns the string representation -func (s DeleteUserByPrincipalIdOutput) String() string { +func (s GetDashboardEmbedUrlOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteUserByPrincipalIdOutput) GoString() string { +func (s GetDashboardEmbedUrlOutput) GoString() string { return s.String() } +// SetEmbedUrl sets the EmbedUrl field's value. +func (s *GetDashboardEmbedUrlOutput) SetEmbedUrl(v string) *GetDashboardEmbedUrlOutput { + s.EmbedUrl = &v + return s +} + // SetRequestId sets the RequestId field's value. -func (s *DeleteUserByPrincipalIdOutput) SetRequestId(v string) *DeleteUserByPrincipalIdOutput { +func (s *GetDashboardEmbedUrlOutput) SetRequestId(v string) *GetDashboardEmbedUrlOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DeleteUserByPrincipalIdOutput) SetStatus(v int64) *DeleteUserByPrincipalIdOutput { +func (s *GetDashboardEmbedUrlOutput) SetStatus(v int64) *GetDashboardEmbedUrlOutput { s.Status = &v return s } -type DeleteUserInput struct { +type GetSessionEmbedUrlInput struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the user is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. + // The ID for the AWS account that contains the QuickSight session that you're + // embedding. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The namespace. Currently, you should set this to default. - // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // The entry point for the embedded session. + EntryPoint *string `location:"querystring" locationName:"entry-point" min:"1" type:"string"` - // The name of the user that you want to delete. + // How many minutes the session is valid. The session lifetime must be 15-600 + // minutes. + SessionLifetimeInMinutes *int64 `location:"querystring" locationName:"session-lifetime" min:"15" type:"long"` + + // The Amazon QuickSight user's Amazon Resource Name (ARN), for use with QUICKSIGHT + // identity type. You can use this for any Amazon QuickSight users in your account + // (readers, authors, or admins) authenticated as one of the following: // - // UserName is a required field - UserName *string `location:"uri" locationName:"UserName" min:"1" type:"string" required:"true"` + // * Active Directory (AD) users or group members + // + // * Invited nonfederated users + // + // * IAM users and IAM role-based sessions authenticated through Federated + // Single Sign-On using SAML, OpenID Connect, or IAM federation. + UserArn *string `location:"querystring" locationName:"user-arn" type:"string"` } // String returns the string representation -func (s DeleteUserInput) String() string { +func (s GetSessionEmbedUrlInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteUserInput) GoString() string { +func (s GetSessionEmbedUrlInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteUserInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteUserInput"} +func (s *GetSessionEmbedUrlInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetSessionEmbedUrlInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) - } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) - } - if s.UserName == nil { - invalidParams.Add(request.NewErrParamRequired("UserName")) + if s.EntryPoint != nil && len(*s.EntryPoint) < 1 { + invalidParams.Add(request.NewErrParamMinLen("EntryPoint", 1)) } - if s.UserName != nil && len(*s.UserName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) + if s.SessionLifetimeInMinutes != nil && *s.SessionLifetimeInMinutes < 15 { + invalidParams.Add(request.NewErrParamMinValue("SessionLifetimeInMinutes", 15)) } if invalidParams.Len() > 0 { @@ -12656,26 +19275,38 @@ func (s *DeleteUserInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *DeleteUserInput) SetAwsAccountId(v string) *DeleteUserInput { +func (s *GetSessionEmbedUrlInput) SetAwsAccountId(v string) *GetSessionEmbedUrlInput { s.AwsAccountId = &v return s } -// SetNamespace sets the Namespace field's value. -func (s *DeleteUserInput) SetNamespace(v string) *DeleteUserInput { - s.Namespace = &v +// SetEntryPoint sets the EntryPoint field's value. +func (s *GetSessionEmbedUrlInput) SetEntryPoint(v string) *GetSessionEmbedUrlInput { + s.EntryPoint = &v return s } -// SetUserName sets the UserName field's value. -func (s *DeleteUserInput) SetUserName(v string) *DeleteUserInput { - s.UserName = &v +// SetSessionLifetimeInMinutes sets the SessionLifetimeInMinutes field's value. +func (s *GetSessionEmbedUrlInput) SetSessionLifetimeInMinutes(v int64) *GetSessionEmbedUrlInput { + s.SessionLifetimeInMinutes = &v return s } -type DeleteUserOutput struct { +// SetUserArn sets the UserArn field's value. +func (s *GetSessionEmbedUrlInput) SetUserArn(v string) *GetSessionEmbedUrlInput { + s.UserArn = &v + return s +} + +type GetSessionEmbedUrlOutput struct { _ struct{} `type:"structure"` + // A single-use URL that you can put into your server-side web page to embed + // your QuickSight session. This URL is valid for 5 minutes. The API provides + // the URL with an auth_code value that enables one (and only one) sign-on to + // a user session that is valid for 10 hours. + EmbedUrl *string `type:"string" sensitive:"true"` + // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -12684,408 +19315,463 @@ type DeleteUserOutput struct { } // String returns the string representation -func (s DeleteUserOutput) String() string { +func (s GetSessionEmbedUrlOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DeleteUserOutput) GoString() string { +func (s GetSessionEmbedUrlOutput) GoString() string { return s.String() } +// SetEmbedUrl sets the EmbedUrl field's value. +func (s *GetSessionEmbedUrlOutput) SetEmbedUrl(v string) *GetSessionEmbedUrlOutput { + s.EmbedUrl = &v + return s +} + // SetRequestId sets the RequestId field's value. -func (s *DeleteUserOutput) SetRequestId(v string) *DeleteUserOutput { +func (s *GetSessionEmbedUrlOutput) SetRequestId(v string) *GetSessionEmbedUrlOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DeleteUserOutput) SetStatus(v int64) *DeleteUserOutput { +func (s *GetSessionEmbedUrlOutput) SetStatus(v int64) *GetSessionEmbedUrlOutput { s.Status = &v return s } -type DescribeDashboardInput struct { +// A group in Amazon QuickSight consists of a set of users. You can use groups +// to make it easier to manage access and security. Currently, an Amazon QuickSight +// subscription can't contain more than 500 Amazon QuickSight groups. +type Group struct { _ struct{} `type:"structure"` - // The alias name. - AliasName *string `location:"querystring" locationName:"alias-name" min:"1" type:"string"` + // The Amazon Resource Name (ARN) for the group. + Arn *string `type:"string"` - // The ID of the AWS account that contains the dashboard that you're describing. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // The group description. + Description *string `min:"1" type:"string"` - // The ID for the dashboard. - // - // DashboardId is a required field - DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` + // The name of the group. + GroupName *string `min:"1" type:"string"` - // The version number for the dashboard. If a version number isn't passed, the - // latest published dashboard version is described. - VersionNumber *int64 `location:"querystring" locationName:"version-number" min:"1" type:"long"` + // The principal ID of the group. + PrincipalId *string `type:"string"` } // String returns the string representation -func (s DescribeDashboardInput) String() string { +func (s Group) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeDashboardInput) GoString() string { +func (s Group) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeDashboardInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeDashboardInput"} - if s.AliasName != nil && len(*s.AliasName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) - } - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.DashboardId == nil { - invalidParams.Add(request.NewErrParamRequired("DashboardId")) - } - if s.DashboardId != nil && len(*s.DashboardId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) - } - if s.VersionNumber != nil && *s.VersionNumber < 1 { - invalidParams.Add(request.NewErrParamMinValue("VersionNumber", 1)) - } +// SetArn sets the Arn field's value. +func (s *Group) SetArn(v string) *Group { + s.Arn = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetDescription sets the Description field's value. +func (s *Group) SetDescription(v string) *Group { + s.Description = &v + return s } -// SetAliasName sets the AliasName field's value. -func (s *DescribeDashboardInput) SetAliasName(v string) *DescribeDashboardInput { - s.AliasName = &v +// SetGroupName sets the GroupName field's value. +func (s *Group) SetGroupName(v string) *Group { + s.GroupName = &v return s } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeDashboardInput) SetAwsAccountId(v string) *DescribeDashboardInput { - s.AwsAccountId = &v +// SetPrincipalId sets the PrincipalId field's value. +func (s *Group) SetPrincipalId(v string) *Group { + s.PrincipalId = &v return s } -// SetDashboardId sets the DashboardId field's value. -func (s *DescribeDashboardInput) SetDashboardId(v string) *DescribeDashboardInput { - s.DashboardId = &v +// A member of an Amazon QuickSight group. Currently, group members must be +// users. Groups can't be members of another group. . +type GroupMember struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) for the group member (user). + Arn *string `type:"string"` + + // The name of the group member (user). + MemberName *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s GroupMember) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GroupMember) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *GroupMember) SetArn(v string) *GroupMember { + s.Arn = &v return s } -// SetVersionNumber sets the VersionNumber field's value. -func (s *DescribeDashboardInput) SetVersionNumber(v int64) *DescribeDashboardInput { - s.VersionNumber = &v +// SetMemberName sets the MemberName field's value. +func (s *GroupMember) SetMemberName(v string) *GroupMember { + s.MemberName = &v return s } -type DescribeDashboardOutput struct { +// The display options for gutter spacing between tiles on a sheet. +type GutterStyle struct { _ struct{} `type:"structure"` - // Information about the dashboard. - Dashboard *Dashboard `type:"structure"` + // This Boolean value controls whether to display a gutter space between sheet + // tiles. + Show *bool `type:"boolean"` +} - // The AWS request ID for this operation. - RequestId *string `type:"string"` +// String returns the string representation +func (s GutterStyle) String() string { + return awsutil.Prettify(s) +} - // The HTTP status of this request. - Status *int64 `location:"statusCode" type:"integer"` +// GoString returns the string representation +func (s GutterStyle) GoString() string { + return s.String() +} + +// SetShow sets the Show field's value. +func (s *GutterStyle) SetShow(v bool) *GutterStyle { + s.Show = &v + return s +} + +// An AWS Identity and Access Management (IAM) policy assignment. +type IAMPolicyAssignment struct { + _ struct{} `type:"structure"` + + // Assignment ID. + AssignmentId *string `type:"string"` + + // Assignment name. + AssignmentName *string `min:"1" type:"string"` + + // Assignment status. + AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` + + // The AWS account ID. + AwsAccountId *string `min:"12" type:"string"` + + // Identities. + Identities map[string][]*string `type:"map"` + + // The Amazon Resource Name (ARN) for the IAM policy. + PolicyArn *string `type:"string"` } // String returns the string representation -func (s DescribeDashboardOutput) String() string { +func (s IAMPolicyAssignment) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeDashboardOutput) GoString() string { +func (s IAMPolicyAssignment) GoString() string { return s.String() } -// SetDashboard sets the Dashboard field's value. -func (s *DescribeDashboardOutput) SetDashboard(v *Dashboard) *DescribeDashboardOutput { - s.Dashboard = v +// SetAssignmentId sets the AssignmentId field's value. +func (s *IAMPolicyAssignment) SetAssignmentId(v string) *IAMPolicyAssignment { + s.AssignmentId = &v + return s +} + +// SetAssignmentName sets the AssignmentName field's value. +func (s *IAMPolicyAssignment) SetAssignmentName(v string) *IAMPolicyAssignment { + s.AssignmentName = &v + return s +} + +// SetAssignmentStatus sets the AssignmentStatus field's value. +func (s *IAMPolicyAssignment) SetAssignmentStatus(v string) *IAMPolicyAssignment { + s.AssignmentStatus = &v + return s +} + +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *IAMPolicyAssignment) SetAwsAccountId(v string) *IAMPolicyAssignment { + s.AwsAccountId = &v return s } -// SetRequestId sets the RequestId field's value. -func (s *DescribeDashboardOutput) SetRequestId(v string) *DescribeDashboardOutput { - s.RequestId = &v +// SetIdentities sets the Identities field's value. +func (s *IAMPolicyAssignment) SetIdentities(v map[string][]*string) *IAMPolicyAssignment { + s.Identities = v return s } -// SetStatus sets the Status field's value. -func (s *DescribeDashboardOutput) SetStatus(v int64) *DescribeDashboardOutput { - s.Status = &v +// SetPolicyArn sets the PolicyArn field's value. +func (s *IAMPolicyAssignment) SetPolicyArn(v string) *IAMPolicyAssignment { + s.PolicyArn = &v return s } -type DescribeDashboardPermissionsInput struct { +// IAM policy assignment summary. +type IAMPolicyAssignmentSummary struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the dashboard that you're describing - // permissions for. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // Assignment name. + AssignmentName *string `min:"1" type:"string"` - // The ID for the dashboard, also added to the IAM policy. - // - // DashboardId is a required field - DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` + // Assignment status. + AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` } // String returns the string representation -func (s DescribeDashboardPermissionsInput) String() string { +func (s IAMPolicyAssignmentSummary) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeDashboardPermissionsInput) GoString() string { +func (s IAMPolicyAssignmentSummary) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeDashboardPermissionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeDashboardPermissionsInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.DashboardId == nil { - invalidParams.Add(request.NewErrParamRequired("DashboardId")) - } - if s.DashboardId != nil && len(*s.DashboardId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeDashboardPermissionsInput) SetAwsAccountId(v string) *DescribeDashboardPermissionsInput { - s.AwsAccountId = &v +// SetAssignmentName sets the AssignmentName field's value. +func (s *IAMPolicyAssignmentSummary) SetAssignmentName(v string) *IAMPolicyAssignmentSummary { + s.AssignmentName = &v return s } -// SetDashboardId sets the DashboardId field's value. -func (s *DescribeDashboardPermissionsInput) SetDashboardId(v string) *DescribeDashboardPermissionsInput { - s.DashboardId = &v +// SetAssignmentStatus sets the AssignmentStatus field's value. +func (s *IAMPolicyAssignmentSummary) SetAssignmentStatus(v string) *IAMPolicyAssignmentSummary { + s.AssignmentStatus = &v return s } -type DescribeDashboardPermissionsOutput struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the dashboard. - DashboardArn *string `type:"string"` - - // The ID for the dashboard. - DashboardId *string `min:"1" type:"string"` +// The identity type specified isn't supported. Supported identity types include +// IAM and QUICKSIGHT. +type IdentityTypeNotSupportedException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // A structure that contains the permissions for the dashboard. - Permissions []*ResourcePermission `min:"1" type:"list"` + Message_ *string `locationName:"Message" type:"string"` - // The AWS request ID for this operation. + // The AWS request ID for this request. RequestId *string `type:"string"` - - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s DescribeDashboardPermissionsOutput) String() string { +func (s IdentityTypeNotSupportedException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeDashboardPermissionsOutput) GoString() string { +func (s IdentityTypeNotSupportedException) GoString() string { return s.String() } -// SetDashboardArn sets the DashboardArn field's value. -func (s *DescribeDashboardPermissionsOutput) SetDashboardArn(v string) *DescribeDashboardPermissionsOutput { - s.DashboardArn = &v - return s +func newErrorIdentityTypeNotSupportedException(v protocol.ResponseMetadata) error { + return &IdentityTypeNotSupportedException{ + RespMetadata: v, + } } -// SetDashboardId sets the DashboardId field's value. -func (s *DescribeDashboardPermissionsOutput) SetDashboardId(v string) *DescribeDashboardPermissionsOutput { - s.DashboardId = &v - return s +// Code returns the exception type name. +func (s *IdentityTypeNotSupportedException) Code() string { + return "IdentityTypeNotSupportedException" } -// SetPermissions sets the Permissions field's value. -func (s *DescribeDashboardPermissionsOutput) SetPermissions(v []*ResourcePermission) *DescribeDashboardPermissionsOutput { - s.Permissions = v - return s +// Message returns the exception's message. +func (s *IdentityTypeNotSupportedException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" } -// SetRequestId sets the RequestId field's value. -func (s *DescribeDashboardPermissionsOutput) SetRequestId(v string) *DescribeDashboardPermissionsOutput { - s.RequestId = &v - return s +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *IdentityTypeNotSupportedException) OrigErr() error { + return nil } -// SetStatus sets the Status field's value. -func (s *DescribeDashboardPermissionsOutput) SetStatus(v int64) *DescribeDashboardPermissionsOutput { - s.Status = &v - return s +func (s *IdentityTypeNotSupportedException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) } -type DescribeDataSetInput struct { +// Status code returns the HTTP status code for the request's response error. +func (s *IdentityTypeNotSupportedException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *IdentityTypeNotSupportedException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Information about the SPICE ingestion for a dataset. +type Ingestion struct { _ struct{} `type:"structure"` - // The AWS account ID. + // The Amazon Resource Name (ARN) of the resource. // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // Arn is a required field + Arn *string `type:"string" required:"true"` - // The ID for the dataset that you want to create. This ID is unique per AWS - // Region for each AWS account. + // The time that this ingestion started. // - // DataSetId is a required field - DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` + // CreatedTime is a required field + CreatedTime *time.Time `type:"timestamp" required:"true"` + + // Error information for this ingestion. + ErrorInfo *ErrorInfo `type:"structure"` + + // Ingestion ID. + IngestionId *string `min:"1" type:"string"` + + // The size of the data ingested, in bytes. + IngestionSizeInBytes *int64 `type:"long"` + + // Ingestion status. + // + // IngestionStatus is a required field + IngestionStatus *string `type:"string" required:"true" enum:"IngestionStatus"` + + // The time that this ingestion took, measured in seconds. + IngestionTimeInSeconds *int64 `type:"long"` + + // Information about a queued dataset SPICE ingestion. + QueueInfo *QueueInfo `type:"structure"` + + // Event source for this ingestion. + RequestSource *string `type:"string" enum:"IngestionRequestSource"` + + // Type of this ingestion. + RequestType *string `type:"string" enum:"IngestionRequestType"` + + // Information about rows for a data set SPICE ingestion. + RowInfo *RowInfo `type:"structure"` } // String returns the string representation -func (s DescribeDataSetInput) String() string { +func (s Ingestion) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeDataSetInput) GoString() string { +func (s Ingestion) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeDataSetInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeDataSetInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.DataSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetId")) - } - if s.DataSetId != nil && len(*s.DataSetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetArn sets the Arn field's value. +func (s *Ingestion) SetArn(v string) *Ingestion { + s.Arn = &v + return s } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeDataSetInput) SetAwsAccountId(v string) *DescribeDataSetInput { - s.AwsAccountId = &v +// SetCreatedTime sets the CreatedTime field's value. +func (s *Ingestion) SetCreatedTime(v time.Time) *Ingestion { + s.CreatedTime = &v return s } -// SetDataSetId sets the DataSetId field's value. -func (s *DescribeDataSetInput) SetDataSetId(v string) *DescribeDataSetInput { - s.DataSetId = &v +// SetErrorInfo sets the ErrorInfo field's value. +func (s *Ingestion) SetErrorInfo(v *ErrorInfo) *Ingestion { + s.ErrorInfo = v return s } -type DescribeDataSetOutput struct { - _ struct{} `type:"structure"` - - // Information on the dataset. - DataSet *DataSet `type:"structure"` +// SetIngestionId sets the IngestionId field's value. +func (s *Ingestion) SetIngestionId(v string) *Ingestion { + s.IngestionId = &v + return s +} - // The AWS request ID for this operation. - RequestId *string `type:"string"` +// SetIngestionSizeInBytes sets the IngestionSizeInBytes field's value. +func (s *Ingestion) SetIngestionSizeInBytes(v int64) *Ingestion { + s.IngestionSizeInBytes = &v + return s +} - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` +// SetIngestionStatus sets the IngestionStatus field's value. +func (s *Ingestion) SetIngestionStatus(v string) *Ingestion { + s.IngestionStatus = &v + return s } -// String returns the string representation -func (s DescribeDataSetOutput) String() string { - return awsutil.Prettify(s) +// SetIngestionTimeInSeconds sets the IngestionTimeInSeconds field's value. +func (s *Ingestion) SetIngestionTimeInSeconds(v int64) *Ingestion { + s.IngestionTimeInSeconds = &v + return s } -// GoString returns the string representation -func (s DescribeDataSetOutput) GoString() string { - return s.String() +// SetQueueInfo sets the QueueInfo field's value. +func (s *Ingestion) SetQueueInfo(v *QueueInfo) *Ingestion { + s.QueueInfo = v + return s } -// SetDataSet sets the DataSet field's value. -func (s *DescribeDataSetOutput) SetDataSet(v *DataSet) *DescribeDataSetOutput { - s.DataSet = v +// SetRequestSource sets the RequestSource field's value. +func (s *Ingestion) SetRequestSource(v string) *Ingestion { + s.RequestSource = &v return s } -// SetRequestId sets the RequestId field's value. -func (s *DescribeDataSetOutput) SetRequestId(v string) *DescribeDataSetOutput { - s.RequestId = &v +// SetRequestType sets the RequestType field's value. +func (s *Ingestion) SetRequestType(v string) *Ingestion { + s.RequestType = &v return s } -// SetStatus sets the Status field's value. -func (s *DescribeDataSetOutput) SetStatus(v int64) *DescribeDataSetOutput { - s.Status = &v +// SetRowInfo sets the RowInfo field's value. +func (s *Ingestion) SetRowInfo(v *RowInfo) *Ingestion { + s.RowInfo = v return s } -type DescribeDataSetPermissionsInput struct { +// Metadata for a column that is used as the input of a transform operation. +type InputColumn struct { _ struct{} `type:"structure"` - // The AWS account ID. + // The name of this column in the underlying data source. // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` - // The ID for the dataset that you want to create. This ID is unique per AWS - // Region for each AWS account. + // The data type of the column. // - // DataSetId is a required field - DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` + // Type is a required field + Type *string `type:"string" required:"true" enum:"InputColumnDataType"` } // String returns the string representation -func (s DescribeDataSetPermissionsInput) String() string { +func (s InputColumn) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeDataSetPermissionsInput) GoString() string { +func (s InputColumn) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeDataSetPermissionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeDataSetPermissionsInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) +func (s *InputColumn) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "InputColumn"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) } - if s.DataSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetId")) + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } - if s.DataSetId != nil && len(*s.DataSetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) } if invalidParams.Len() > 0 { @@ -13094,347 +19780,348 @@ func (s *DescribeDataSetPermissionsInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeDataSetPermissionsInput) SetAwsAccountId(v string) *DescribeDataSetPermissionsInput { - s.AwsAccountId = &v +// SetName sets the Name field's value. +func (s *InputColumn) SetName(v string) *InputColumn { + s.Name = &v return s } -// SetDataSetId sets the DataSetId field's value. -func (s *DescribeDataSetPermissionsInput) SetDataSetId(v string) *DescribeDataSetPermissionsInput { - s.DataSetId = &v +// SetType sets the Type field's value. +func (s *InputColumn) SetType(v string) *InputColumn { + s.Type = &v return s } -type DescribeDataSetPermissionsOutput struct { +// Integer parameter. +type IntegerParameter struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the dataset. - DataSetArn *string `type:"string"` - - // The ID for the dataset that you want to create. This ID is unique per AWS - // Region for each AWS account. - DataSetId *string `type:"string"` - - // A list of resource permissions on the dataset. - Permissions []*ResourcePermission `min:"1" type:"list"` - - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // A display name for the dataset. + // + // Name is a required field + Name *string `type:"string" required:"true"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // Values. + // + // Values is a required field + Values []*int64 `type:"list" required:"true"` } // String returns the string representation -func (s DescribeDataSetPermissionsOutput) String() string { +func (s IntegerParameter) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeDataSetPermissionsOutput) GoString() string { +func (s IntegerParameter) GoString() string { return s.String() } -// SetDataSetArn sets the DataSetArn field's value. -func (s *DescribeDataSetPermissionsOutput) SetDataSetArn(v string) *DescribeDataSetPermissionsOutput { - s.DataSetArn = &v - return s -} - -// SetDataSetId sets the DataSetId field's value. -func (s *DescribeDataSetPermissionsOutput) SetDataSetId(v string) *DescribeDataSetPermissionsOutput { - s.DataSetId = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *IntegerParameter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "IntegerParameter"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Values == nil { + invalidParams.Add(request.NewErrParamRequired("Values")) + } -// SetPermissions sets the Permissions field's value. -func (s *DescribeDataSetPermissionsOutput) SetPermissions(v []*ResourcePermission) *DescribeDataSetPermissionsOutput { - s.Permissions = v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetRequestId sets the RequestId field's value. -func (s *DescribeDataSetPermissionsOutput) SetRequestId(v string) *DescribeDataSetPermissionsOutput { - s.RequestId = &v +// SetName sets the Name field's value. +func (s *IntegerParameter) SetName(v string) *IntegerParameter { + s.Name = &v return s } -// SetStatus sets the Status field's value. -func (s *DescribeDataSetPermissionsOutput) SetStatus(v int64) *DescribeDataSetPermissionsOutput { - s.Status = &v +// SetValues sets the Values field's value. +func (s *IntegerParameter) SetValues(v []*int64) *IntegerParameter { + s.Values = v return s } -type DescribeDataSourceInput struct { - _ struct{} `type:"structure"` +// An internal failure occurred. +type InternalFailureException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // The AWS account ID. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + Message_ *string `locationName:"Message" type:"string"` - // The ID of the data source. This ID is unique per AWS Region for each AWS - // account. - // - // DataSourceId is a required field - DataSourceId *string `location:"uri" locationName:"DataSourceId" type:"string" required:"true"` + // The AWS request ID for this request. + RequestId *string `type:"string"` } // String returns the string representation -func (s DescribeDataSourceInput) String() string { +func (s InternalFailureException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeDataSourceInput) GoString() string { +func (s InternalFailureException) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeDataSourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeDataSourceInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.DataSourceId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSourceId")) - } - if s.DataSourceId != nil && len(*s.DataSourceId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSourceId", 1)) +func newErrorInternalFailureException(v protocol.ResponseMetadata) error { + return &InternalFailureException{ + RespMetadata: v, } +} - if invalidParams.Len() > 0 { - return invalidParams +// Code returns the exception type name. +func (s *InternalFailureException) Code() string { + return "InternalFailureException" +} + +// Message returns the exception's message. +func (s *InternalFailureException) Message() string { + if s.Message_ != nil { + return *s.Message_ } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InternalFailureException) OrigErr() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeDataSourceInput) SetAwsAccountId(v string) *DescribeDataSourceInput { - s.AwsAccountId = &v - return s +func (s *InternalFailureException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) } -// SetDataSourceId sets the DataSourceId field's value. -func (s *DescribeDataSourceInput) SetDataSourceId(v string) *DescribeDataSourceInput { - s.DataSourceId = &v - return s +// Status code returns the HTTP status code for the request's response error. +func (s *InternalFailureException) StatusCode() int { + return s.RespMetadata.StatusCode } -type DescribeDataSourceOutput struct { - _ struct{} `type:"structure"` +// RequestID returns the service's response RequestID for request. +func (s *InternalFailureException) RequestID() string { + return s.RespMetadata.RequestID +} - // The information on the data source. - DataSource *DataSource `type:"structure"` +// The NextToken value isn't valid. +type InvalidNextTokenException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` + Message_ *string `locationName:"Message" type:"string"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // The AWS request ID for this request. + RequestId *string `type:"string"` } // String returns the string representation -func (s DescribeDataSourceOutput) String() string { +func (s InvalidNextTokenException) String() string { return awsutil.Prettify(s) } -// GoString returns the string representation -func (s DescribeDataSourceOutput) GoString() string { - return s.String() +// GoString returns the string representation +func (s InvalidNextTokenException) GoString() string { + return s.String() +} + +func newErrorInvalidNextTokenException(v protocol.ResponseMetadata) error { + return &InvalidNextTokenException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidNextTokenException) Code() string { + return "InvalidNextTokenException" +} + +// Message returns the exception's message. +func (s *InvalidNextTokenException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidNextTokenException) OrigErr() error { + return nil } -// SetDataSource sets the DataSource field's value. -func (s *DescribeDataSourceOutput) SetDataSource(v *DataSource) *DescribeDataSourceOutput { - s.DataSource = v - return s +func (s *InvalidNextTokenException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) } -// SetRequestId sets the RequestId field's value. -func (s *DescribeDataSourceOutput) SetRequestId(v string) *DescribeDataSourceOutput { - s.RequestId = &v - return s +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidNextTokenException) StatusCode() int { + return s.RespMetadata.StatusCode } -// SetStatus sets the Status field's value. -func (s *DescribeDataSourceOutput) SetStatus(v int64) *DescribeDataSourceOutput { - s.Status = &v - return s +// RequestID returns the service's response RequestID for request. +func (s *InvalidNextTokenException) RequestID() string { + return s.RespMetadata.RequestID } -type DescribeDataSourcePermissionsInput struct { - _ struct{} `type:"structure"` +// One or more parameters has a value that isn't valid. +type InvalidParameterValueException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // The AWS account ID. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + Message_ *string `locationName:"Message" type:"string"` - // The ID of the data source. This ID is unique per AWS Region for each AWS - // account. - // - // DataSourceId is a required field - DataSourceId *string `location:"uri" locationName:"DataSourceId" type:"string" required:"true"` + // The AWS request ID for this request. + RequestId *string `type:"string"` } // String returns the string representation -func (s DescribeDataSourcePermissionsInput) String() string { +func (s InvalidParameterValueException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeDataSourcePermissionsInput) GoString() string { +func (s InvalidParameterValueException) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeDataSourcePermissionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeDataSourcePermissionsInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.DataSourceId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSourceId")) - } - if s.DataSourceId != nil && len(*s.DataSourceId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSourceId", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams +func newErrorInvalidParameterValueException(v protocol.ResponseMetadata) error { + return &InvalidParameterValueException{ + RespMetadata: v, } - return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeDataSourcePermissionsInput) SetAwsAccountId(v string) *DescribeDataSourcePermissionsInput { - s.AwsAccountId = &v - return s +// Code returns the exception type name. +func (s *InvalidParameterValueException) Code() string { + return "InvalidParameterValueException" } -// SetDataSourceId sets the DataSourceId field's value. -func (s *DescribeDataSourcePermissionsInput) SetDataSourceId(v string) *DescribeDataSourcePermissionsInput { - s.DataSourceId = &v - return s +// Message returns the exception's message. +func (s *InvalidParameterValueException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" } -type DescribeDataSourcePermissionsOutput struct { - _ struct{} `type:"structure"` +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidParameterValueException) OrigErr() error { + return nil +} - // The Amazon Resource Name (ARN) of the data source. - DataSourceArn *string `type:"string"` +func (s *InvalidParameterValueException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} - // The ID of the data source. This ID is unique per AWS Region for each AWS - // account. - DataSourceId *string `type:"string"` +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidParameterValueException) StatusCode() int { + return s.RespMetadata.StatusCode +} - // A list of resource permissions on the data source. - Permissions []*ResourcePermission `min:"1" type:"list"` +// RequestID returns the service's response RequestID for request. +func (s *InvalidParameterValueException) RequestID() string { + return s.RespMetadata.RequestID +} - // The AWS request ID for this operation. - RequestId *string `type:"string"` +// Jira parameters. +type JiraParameters struct { + _ struct{} `type:"structure"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // The base URL of the Jira site. + // + // SiteBaseUrl is a required field + SiteBaseUrl *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DescribeDataSourcePermissionsOutput) String() string { +func (s JiraParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeDataSourcePermissionsOutput) GoString() string { +func (s JiraParameters) GoString() string { return s.String() } -// SetDataSourceArn sets the DataSourceArn field's value. -func (s *DescribeDataSourcePermissionsOutput) SetDataSourceArn(v string) *DescribeDataSourcePermissionsOutput { - s.DataSourceArn = &v - return s -} - -// SetDataSourceId sets the DataSourceId field's value. -func (s *DescribeDataSourcePermissionsOutput) SetDataSourceId(v string) *DescribeDataSourcePermissionsOutput { - s.DataSourceId = &v - return s -} - -// SetPermissions sets the Permissions field's value. -func (s *DescribeDataSourcePermissionsOutput) SetPermissions(v []*ResourcePermission) *DescribeDataSourcePermissionsOutput { - s.Permissions = v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *JiraParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "JiraParameters"} + if s.SiteBaseUrl == nil { + invalidParams.Add(request.NewErrParamRequired("SiteBaseUrl")) + } + if s.SiteBaseUrl != nil && len(*s.SiteBaseUrl) < 1 { + invalidParams.Add(request.NewErrParamMinLen("SiteBaseUrl", 1)) + } -// SetRequestId sets the RequestId field's value. -func (s *DescribeDataSourcePermissionsOutput) SetRequestId(v string) *DescribeDataSourcePermissionsOutput { - s.RequestId = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetStatus sets the Status field's value. -func (s *DescribeDataSourcePermissionsOutput) SetStatus(v int64) *DescribeDataSourcePermissionsOutput { - s.Status = &v +// SetSiteBaseUrl sets the SiteBaseUrl field's value. +func (s *JiraParameters) SetSiteBaseUrl(v string) *JiraParameters { + s.SiteBaseUrl = &v return s } -type DescribeGroupInput struct { +// Join instruction. +type JoinInstruction struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the group is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. + // Left operand. // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // LeftOperand is a required field + LeftOperand *string `min:"1" type:"string" required:"true"` - // The name of the group that you want to describe. + // On Clause. // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + // OnClause is a required field + OnClause *string `min:"1" type:"string" required:"true"` - // The namespace. Currently, you should set this to default. + // Right operand. // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // RightOperand is a required field + RightOperand *string `min:"1" type:"string" required:"true"` + + // Type. + // + // Type is a required field + Type *string `type:"string" required:"true" enum:"JoinType"` } // String returns the string representation -func (s DescribeGroupInput) String() string { +func (s JoinInstruction) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeGroupInput) GoString() string { +func (s JoinInstruction) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeGroupInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) +func (s *JoinInstruction) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "JoinInstruction"} + if s.LeftOperand == nil { + invalidParams.Add(request.NewErrParamRequired("LeftOperand")) } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + if s.LeftOperand != nil && len(*s.LeftOperand) < 1 { + invalidParams.Add(request.NewErrParamMinLen("LeftOperand", 1)) } - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) + if s.OnClause == nil { + invalidParams.Add(request.NewErrParamRequired("OnClause")) } - if s.GroupName != nil && len(*s.GroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) + if s.OnClause != nil && len(*s.OnClause) < 1 { + invalidParams.Add(request.NewErrParamMinLen("OnClause", 1)) } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.RightOperand == nil { + invalidParams.Add(request.NewErrParamRequired("RightOperand")) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.RightOperand != nil && len(*s.RightOperand) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RightOperand", 1)) + } + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) } if invalidParams.Len() > 0 { @@ -13443,114 +20130,140 @@ func (s *DescribeGroupInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeGroupInput) SetAwsAccountId(v string) *DescribeGroupInput { - s.AwsAccountId = &v +// SetLeftOperand sets the LeftOperand field's value. +func (s *JoinInstruction) SetLeftOperand(v string) *JoinInstruction { + s.LeftOperand = &v return s } -// SetGroupName sets the GroupName field's value. -func (s *DescribeGroupInput) SetGroupName(v string) *DescribeGroupInput { - s.GroupName = &v +// SetOnClause sets the OnClause field's value. +func (s *JoinInstruction) SetOnClause(v string) *JoinInstruction { + s.OnClause = &v return s } -// SetNamespace sets the Namespace field's value. -func (s *DescribeGroupInput) SetNamespace(v string) *DescribeGroupInput { - s.Namespace = &v +// SetRightOperand sets the RightOperand field's value. +func (s *JoinInstruction) SetRightOperand(v string) *JoinInstruction { + s.RightOperand = &v + return s +} + +// SetType sets the Type field's value. +func (s *JoinInstruction) SetType(v string) *JoinInstruction { + s.Type = &v return s } -type DescribeGroupOutput struct { - _ struct{} `type:"structure"` +// A limit is exceeded. +type LimitExceededException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // The name of the group. - Group *Group `type:"structure"` + Message_ *string `locationName:"Message" type:"string"` - // The AWS request ID for this operation. + // The AWS request ID for this request. RequestId *string `type:"string"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // Limit exceeded. + ResourceType *string `type:"string" enum:"ExceptionResourceType"` } // String returns the string representation -func (s DescribeGroupOutput) String() string { +func (s LimitExceededException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeGroupOutput) GoString() string { +func (s LimitExceededException) GoString() string { return s.String() } -// SetGroup sets the Group field's value. -func (s *DescribeGroupOutput) SetGroup(v *Group) *DescribeGroupOutput { - s.Group = v - return s +func newErrorLimitExceededException(v protocol.ResponseMetadata) error { + return &LimitExceededException{ + RespMetadata: v, + } } -// SetRequestId sets the RequestId field's value. -func (s *DescribeGroupOutput) SetRequestId(v string) *DescribeGroupOutput { - s.RequestId = &v - return s +// Code returns the exception type name. +func (s *LimitExceededException) Code() string { + return "LimitExceededException" } -// SetStatus sets the Status field's value. -func (s *DescribeGroupOutput) SetStatus(v int64) *DescribeGroupOutput { - s.Status = &v - return s +// Message returns the exception's message. +func (s *LimitExceededException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" } -type DescribeIAMPolicyAssignmentInput struct { - _ struct{} `type:"structure"` +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *LimitExceededException) OrigErr() error { + return nil +} - // The name of the assignment. - // - // AssignmentName is a required field - AssignmentName *string `location:"uri" locationName:"AssignmentName" min:"1" type:"string" required:"true"` +func (s *LimitExceededException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} - // The ID of the AWS account that contains the assignment that you want to describe. +// Status code returns the HTTP status code for the request's response error. +func (s *LimitExceededException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *LimitExceededException) RequestID() string { + return s.RespMetadata.RequestID +} + +type ListDashboardVersionsInput struct { + _ struct{} `type:"structure"` + + // The ID of the AWS account that contains the dashboard that you're listing + // versions for. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The namespace that contains the assignment. + // The ID for the dashboard. // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // DashboardId is a required field + DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` + + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` } // String returns the string representation -func (s DescribeIAMPolicyAssignmentInput) String() string { +func (s ListDashboardVersionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeIAMPolicyAssignmentInput) GoString() string { +func (s ListDashboardVersionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeIAMPolicyAssignmentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeIAMPolicyAssignmentInput"} - if s.AssignmentName == nil { - invalidParams.Add(request.NewErrParamRequired("AssignmentName")) - } - if s.AssignmentName != nil && len(*s.AssignmentName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AssignmentName", 1)) - } +func (s *ListDashboardVersionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDashboardVersionsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.DashboardId == nil { + invalidParams.Add(request.NewErrParamRequired("DashboardId")) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.DashboardId != nil && len(*s.DashboardId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } if invalidParams.Len() > 0 { @@ -13559,29 +20272,38 @@ func (s *DescribeIAMPolicyAssignmentInput) Validate() error { return nil } -// SetAssignmentName sets the AssignmentName field's value. -func (s *DescribeIAMPolicyAssignmentInput) SetAssignmentName(v string) *DescribeIAMPolicyAssignmentInput { - s.AssignmentName = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *ListDashboardVersionsInput) SetAwsAccountId(v string) *ListDashboardVersionsInput { + s.AwsAccountId = &v return s } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeIAMPolicyAssignmentInput) SetAwsAccountId(v string) *DescribeIAMPolicyAssignmentInput { - s.AwsAccountId = &v +// SetDashboardId sets the DashboardId field's value. +func (s *ListDashboardVersionsInput) SetDashboardId(v string) *ListDashboardVersionsInput { + s.DashboardId = &v return s } -// SetNamespace sets the Namespace field's value. -func (s *DescribeIAMPolicyAssignmentInput) SetNamespace(v string) *DescribeIAMPolicyAssignmentInput { - s.Namespace = &v +// SetMaxResults sets the MaxResults field's value. +func (s *ListDashboardVersionsInput) SetMaxResults(v int64) *ListDashboardVersionsInput { + s.MaxResults = &v return s } -type DescribeIAMPolicyAssignmentOutput struct { +// SetNextToken sets the NextToken field's value. +func (s *ListDashboardVersionsInput) SetNextToken(v string) *ListDashboardVersionsInput { + s.NextToken = &v + return s +} + +type ListDashboardVersionsOutput struct { _ struct{} `type:"structure"` - // Information describing the IAM policy assignment. - IAMPolicyAssignment *IAMPolicyAssignment `type:"structure"` + // A structure that contains information about each version of the dashboard. + DashboardVersionSummaryList []*DashboardVersionSummary `type:"list"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -13591,82 +20313,75 @@ type DescribeIAMPolicyAssignmentOutput struct { } // String returns the string representation -func (s DescribeIAMPolicyAssignmentOutput) String() string { +func (s ListDashboardVersionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeIAMPolicyAssignmentOutput) GoString() string { +func (s ListDashboardVersionsOutput) GoString() string { return s.String() } -// SetIAMPolicyAssignment sets the IAMPolicyAssignment field's value. -func (s *DescribeIAMPolicyAssignmentOutput) SetIAMPolicyAssignment(v *IAMPolicyAssignment) *DescribeIAMPolicyAssignmentOutput { - s.IAMPolicyAssignment = v +// SetDashboardVersionSummaryList sets the DashboardVersionSummaryList field's value. +func (s *ListDashboardVersionsOutput) SetDashboardVersionSummaryList(v []*DashboardVersionSummary) *ListDashboardVersionsOutput { + s.DashboardVersionSummaryList = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDashboardVersionsOutput) SetNextToken(v string) *ListDashboardVersionsOutput { + s.NextToken = &v return s } // SetRequestId sets the RequestId field's value. -func (s *DescribeIAMPolicyAssignmentOutput) SetRequestId(v string) *DescribeIAMPolicyAssignmentOutput { +func (s *ListDashboardVersionsOutput) SetRequestId(v string) *ListDashboardVersionsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DescribeIAMPolicyAssignmentOutput) SetStatus(v int64) *DescribeIAMPolicyAssignmentOutput { +func (s *ListDashboardVersionsOutput) SetStatus(v int64) *ListDashboardVersionsOutput { s.Status = &v return s } -type DescribeIngestionInput struct { +type ListDashboardsInput struct { _ struct{} `type:"structure"` - // The AWS account ID. + // The ID of the AWS account that contains the dashboards that you're listing. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID of the dataset used in the ingestion. - // - // DataSetId is a required field - DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` - // An ID for the ingestion. - // - // IngestionId is a required field - IngestionId *string `location:"uri" locationName:"IngestionId" min:"1" type:"string" required:"true"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` } // String returns the string representation -func (s DescribeIngestionInput) String() string { +func (s ListDashboardsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeIngestionInput) GoString() string { +func (s ListDashboardsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeIngestionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeIngestionInput"} +func (s *ListDashboardsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDashboardsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DataSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetId")) - } - if s.DataSetId != nil && len(*s.DataSetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) - } - if s.IngestionId == nil { - invalidParams.Add(request.NewErrParamRequired("IngestionId")) - } - if s.IngestionId != nil && len(*s.IngestionId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("IngestionId", 1)) + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } if invalidParams.Len() > 0 { @@ -13676,28 +20391,32 @@ func (s *DescribeIngestionInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeIngestionInput) SetAwsAccountId(v string) *DescribeIngestionInput { +func (s *ListDashboardsInput) SetAwsAccountId(v string) *ListDashboardsInput { s.AwsAccountId = &v return s } -// SetDataSetId sets the DataSetId field's value. -func (s *DescribeIngestionInput) SetDataSetId(v string) *DescribeIngestionInput { - s.DataSetId = &v +// SetMaxResults sets the MaxResults field's value. +func (s *ListDashboardsInput) SetMaxResults(v int64) *ListDashboardsInput { + s.MaxResults = &v return s } -// SetIngestionId sets the IngestionId field's value. -func (s *DescribeIngestionInput) SetIngestionId(v string) *DescribeIngestionInput { - s.IngestionId = &v +// SetNextToken sets the NextToken field's value. +func (s *ListDashboardsInput) SetNextToken(v string) *ListDashboardsInput { + s.NextToken = &v return s } -type DescribeIngestionOutput struct { +type ListDashboardsOutput struct { _ struct{} `type:"structure"` - // Information about the ingestion. - Ingestion *Ingestion `type:"structure"` + // A structure that contains all of the dashboards in your AWS account. This + // structure provides basic information about the dashboards. + DashboardSummaryList []*DashboardSummary `type:"list"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -13707,85 +20426,75 @@ type DescribeIngestionOutput struct { } // String returns the string representation -func (s DescribeIngestionOutput) String() string { +func (s ListDashboardsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeIngestionOutput) GoString() string { +func (s ListDashboardsOutput) GoString() string { return s.String() } -// SetIngestion sets the Ingestion field's value. -func (s *DescribeIngestionOutput) SetIngestion(v *Ingestion) *DescribeIngestionOutput { - s.Ingestion = v +// SetDashboardSummaryList sets the DashboardSummaryList field's value. +func (s *ListDashboardsOutput) SetDashboardSummaryList(v []*DashboardSummary) *ListDashboardsOutput { + s.DashboardSummaryList = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDashboardsOutput) SetNextToken(v string) *ListDashboardsOutput { + s.NextToken = &v return s } // SetRequestId sets the RequestId field's value. -func (s *DescribeIngestionOutput) SetRequestId(v string) *DescribeIngestionOutput { +func (s *ListDashboardsOutput) SetRequestId(v string) *ListDashboardsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DescribeIngestionOutput) SetStatus(v int64) *DescribeIngestionOutput { +func (s *ListDashboardsOutput) SetStatus(v int64) *ListDashboardsOutput { s.Status = &v return s } -type DescribeTemplateAliasInput struct { - _ struct{} `type:"structure"` - - // The name of the template alias that you want to describe. If you name a specific - // alias, you describe the version that the alias points to. You can specify - // the latest version of the template by providing the keyword $LATEST in the - // AliasName parameter. The keyword $PUBLISHED doesn't apply to templates. - // - // AliasName is a required field - AliasName *string `location:"uri" locationName:"AliasName" min:"1" type:"string" required:"true"` - - // The ID of the AWS account that contains the template alias that you're describing. +type ListDataSetsInput struct { + _ struct{} `type:"structure"` + + // The AWS account ID. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the template. - // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` } // String returns the string representation -func (s DescribeTemplateAliasInput) String() string { +func (s ListDataSetsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeTemplateAliasInput) GoString() string { +func (s ListDataSetsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeTemplateAliasInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeTemplateAliasInput"} - if s.AliasName == nil { - invalidParams.Add(request.NewErrParamRequired("AliasName")) - } - if s.AliasName != nil && len(*s.AliasName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) - } +func (s *ListDataSetsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDataSetsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) - } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } if invalidParams.Len() > 0 { @@ -13794,119 +20503,110 @@ func (s *DescribeTemplateAliasInput) Validate() error { return nil } -// SetAliasName sets the AliasName field's value. -func (s *DescribeTemplateAliasInput) SetAliasName(v string) *DescribeTemplateAliasInput { - s.AliasName = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *ListDataSetsInput) SetAwsAccountId(v string) *ListDataSetsInput { + s.AwsAccountId = &v return s } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeTemplateAliasInput) SetAwsAccountId(v string) *DescribeTemplateAliasInput { - s.AwsAccountId = &v +// SetMaxResults sets the MaxResults field's value. +func (s *ListDataSetsInput) SetMaxResults(v int64) *ListDataSetsInput { + s.MaxResults = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *DescribeTemplateAliasInput) SetTemplateId(v string) *DescribeTemplateAliasInput { - s.TemplateId = &v +// SetNextToken sets the NextToken field's value. +func (s *ListDataSetsInput) SetNextToken(v string) *ListDataSetsInput { + s.NextToken = &v return s } -type DescribeTemplateAliasOutput struct { +type ListDataSetsOutput struct { _ struct{} `type:"structure"` + // The list of dataset summaries. + DataSetSummaries []*DataSetSummary `type:"list"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` + // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - - // Information about the template alias. - TemplateAlias *TemplateAlias `type:"structure"` } // String returns the string representation -func (s DescribeTemplateAliasOutput) String() string { +func (s ListDataSetsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeTemplateAliasOutput) GoString() string { +func (s ListDataSetsOutput) GoString() string { return s.String() } +// SetDataSetSummaries sets the DataSetSummaries field's value. +func (s *ListDataSetsOutput) SetDataSetSummaries(v []*DataSetSummary) *ListDataSetsOutput { + s.DataSetSummaries = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDataSetsOutput) SetNextToken(v string) *ListDataSetsOutput { + s.NextToken = &v + return s +} + // SetRequestId sets the RequestId field's value. -func (s *DescribeTemplateAliasOutput) SetRequestId(v string) *DescribeTemplateAliasOutput { +func (s *ListDataSetsOutput) SetRequestId(v string) *ListDataSetsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DescribeTemplateAliasOutput) SetStatus(v int64) *DescribeTemplateAliasOutput { +func (s *ListDataSetsOutput) SetStatus(v int64) *ListDataSetsOutput { s.Status = &v return s } -// SetTemplateAlias sets the TemplateAlias field's value. -func (s *DescribeTemplateAliasOutput) SetTemplateAlias(v *TemplateAlias) *DescribeTemplateAliasOutput { - s.TemplateAlias = v - return s -} - -type DescribeTemplateInput struct { +type ListDataSourcesInput struct { _ struct{} `type:"structure"` - // The alias of the template that you want to describe. If you name a specific - // alias, you describe the version that the alias points to. You can specify - // the latest version of the template by providing the keyword $LATEST in the - // AliasName parameter. The keyword $PUBLISHED doesn't apply to templates. - AliasName *string `location:"querystring" locationName:"alias-name" min:"1" type:"string"` - - // The ID of the AWS account that contains the template that you're describing. + // The AWS account ID. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the template. - // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` - // (Optional) The number for the version to describe. If a VersionNumber parameter - // value isn't provided, the latest version of the template is described. - VersionNumber *int64 `location:"querystring" locationName:"version-number" min:"1" type:"long"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` } // String returns the string representation -func (s DescribeTemplateInput) String() string { +func (s ListDataSourcesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeTemplateInput) GoString() string { +func (s ListDataSourcesInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeTemplateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeTemplateInput"} - if s.AliasName != nil && len(*s.AliasName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) - } +func (s *ListDataSourcesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListDataSourcesInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) - } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) - } - if s.VersionNumber != nil && *s.VersionNumber < 1 { - invalidParams.Add(request.NewErrParamMinValue("VersionNumber", 1)) + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } if invalidParams.Len() > 0 { @@ -13915,100 +20615,133 @@ func (s *DescribeTemplateInput) Validate() error { return nil } -// SetAliasName sets the AliasName field's value. -func (s *DescribeTemplateInput) SetAliasName(v string) *DescribeTemplateInput { - s.AliasName = &v - return s -} - // SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeTemplateInput) SetAwsAccountId(v string) *DescribeTemplateInput { +func (s *ListDataSourcesInput) SetAwsAccountId(v string) *ListDataSourcesInput { s.AwsAccountId = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *DescribeTemplateInput) SetTemplateId(v string) *DescribeTemplateInput { - s.TemplateId = &v +// SetMaxResults sets the MaxResults field's value. +func (s *ListDataSourcesInput) SetMaxResults(v int64) *ListDataSourcesInput { + s.MaxResults = &v return s } -// SetVersionNumber sets the VersionNumber field's value. -func (s *DescribeTemplateInput) SetVersionNumber(v int64) *DescribeTemplateInput { - s.VersionNumber = &v +// SetNextToken sets the NextToken field's value. +func (s *ListDataSourcesInput) SetNextToken(v string) *ListDataSourcesInput { + s.NextToken = &v return s } -type DescribeTemplateOutput struct { +type ListDataSourcesOutput struct { _ struct{} `type:"structure"` + // A list of data sources. + DataSources []*DataSource `type:"list"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - - // The template structure for the object you want to describe. - Template *Template `type:"structure"` } // String returns the string representation -func (s DescribeTemplateOutput) String() string { +func (s ListDataSourcesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeTemplateOutput) GoString() string { +func (s ListDataSourcesOutput) GoString() string { return s.String() } -// SetStatus sets the Status field's value. -func (s *DescribeTemplateOutput) SetStatus(v int64) *DescribeTemplateOutput { - s.Status = &v +// SetDataSources sets the DataSources field's value. +func (s *ListDataSourcesOutput) SetDataSources(v []*DataSource) *ListDataSourcesOutput { + s.DataSources = v return s } -// SetTemplate sets the Template field's value. -func (s *DescribeTemplateOutput) SetTemplate(v *Template) *DescribeTemplateOutput { - s.Template = v +// SetNextToken sets the NextToken field's value. +func (s *ListDataSourcesOutput) SetNextToken(v string) *ListDataSourcesOutput { + s.NextToken = &v return s } -type DescribeTemplatePermissionsInput struct { +// SetRequestId sets the RequestId field's value. +func (s *ListDataSourcesOutput) SetRequestId(v string) *ListDataSourcesOutput { + s.RequestId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *ListDataSourcesOutput) SetStatus(v int64) *ListDataSourcesOutput { + s.Status = &v + return s +} + +type ListGroupMembershipsInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the template that you're describing. + // The ID for the AWS account that the group is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the template. + // The name of the group that you want to see a membership list of. // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + // GroupName is a required field + GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + + // The maximum number of results to return from this request. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + + // The namespace. Currently, you should set this to default. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + + // A pagination token that can be used in a subsequent request. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` } // String returns the string representation -func (s DescribeTemplatePermissionsInput) String() string { +func (s ListGroupMembershipsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeTemplatePermissionsInput) GoString() string { +func (s ListGroupMembershipsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeTemplatePermissionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeTemplatePermissionsInput"} +func (s *ListGroupMembershipsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListGroupMembershipsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) + if s.GroupName == nil { + invalidParams.Add(request.NewErrParamRequired("GroupName")) } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + if s.GroupName != nil && len(*s.GroupName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) } if invalidParams.Len() > 0 { @@ -14017,128 +20750,135 @@ func (s *DescribeTemplatePermissionsInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeTemplatePermissionsInput) SetAwsAccountId(v string) *DescribeTemplatePermissionsInput { - s.AwsAccountId = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *ListGroupMembershipsInput) SetAwsAccountId(v string) *ListGroupMembershipsInput { + s.AwsAccountId = &v + return s +} + +// SetGroupName sets the GroupName field's value. +func (s *ListGroupMembershipsInput) SetGroupName(v string) *ListGroupMembershipsInput { + s.GroupName = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListGroupMembershipsInput) SetMaxResults(v int64) *ListGroupMembershipsInput { + s.MaxResults = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *ListGroupMembershipsInput) SetNamespace(v string) *ListGroupMembershipsInput { + s.Namespace = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *DescribeTemplatePermissionsInput) SetTemplateId(v string) *DescribeTemplatePermissionsInput { - s.TemplateId = &v +// SetNextToken sets the NextToken field's value. +func (s *ListGroupMembershipsInput) SetNextToken(v string) *ListGroupMembershipsInput { + s.NextToken = &v return s } -type DescribeTemplatePermissionsOutput struct { +type ListGroupMembershipsOutput struct { _ struct{} `type:"structure"` - // A list of resource permissions to be set on the template. - Permissions []*ResourcePermission `min:"1" type:"list"` + // The list of the members of the group. + GroupMemberList []*GroupMember `type:"list"` + + // A pagination token that can be used in a subsequent request. + NextToken *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - - // The Amazon Resource Name (ARN) of the template. - TemplateArn *string `type:"string"` - - // The ID for the template. - TemplateId *string `min:"1" type:"string"` } // String returns the string representation -func (s DescribeTemplatePermissionsOutput) String() string { +func (s ListGroupMembershipsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeTemplatePermissionsOutput) GoString() string { +func (s ListGroupMembershipsOutput) GoString() string { return s.String() } -// SetPermissions sets the Permissions field's value. -func (s *DescribeTemplatePermissionsOutput) SetPermissions(v []*ResourcePermission) *DescribeTemplatePermissionsOutput { - s.Permissions = v +// SetGroupMemberList sets the GroupMemberList field's value. +func (s *ListGroupMembershipsOutput) SetGroupMemberList(v []*GroupMember) *ListGroupMembershipsOutput { + s.GroupMemberList = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListGroupMembershipsOutput) SetNextToken(v string) *ListGroupMembershipsOutput { + s.NextToken = &v return s } // SetRequestId sets the RequestId field's value. -func (s *DescribeTemplatePermissionsOutput) SetRequestId(v string) *DescribeTemplatePermissionsOutput { +func (s *ListGroupMembershipsOutput) SetRequestId(v string) *ListGroupMembershipsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DescribeTemplatePermissionsOutput) SetStatus(v int64) *DescribeTemplatePermissionsOutput { +func (s *ListGroupMembershipsOutput) SetStatus(v int64) *ListGroupMembershipsOutput { s.Status = &v return s } -// SetTemplateArn sets the TemplateArn field's value. -func (s *DescribeTemplatePermissionsOutput) SetTemplateArn(v string) *DescribeTemplatePermissionsOutput { - s.TemplateArn = &v - return s -} - -// SetTemplateId sets the TemplateId field's value. -func (s *DescribeTemplatePermissionsOutput) SetTemplateId(v string) *DescribeTemplatePermissionsOutput { - s.TemplateId = &v - return s -} - -type DescribeUserInput struct { +type ListGroupsInput struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the user is in. Currently, you use the ID + // The ID for the AWS account that the group is in. Currently, you use the ID // for the AWS account that contains your Amazon QuickSight account. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // The maximum number of results to return. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + // The namespace. Currently, you should set this to default. // // Namespace is a required field Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` - // The name of the user that you want to describe. - // - // UserName is a required field - UserName *string `location:"uri" locationName:"UserName" min:"1" type:"string" required:"true"` + // A pagination token that can be used in a subsequent request. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` } // String returns the string representation -func (s DescribeUserInput) String() string { +func (s ListGroupsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeUserInput) GoString() string { +func (s ListGroupsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *DescribeUserInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DescribeUserInput"} +func (s *ListGroupsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListGroupsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } if s.Namespace == nil { invalidParams.Add(request.NewErrParamRequired("Namespace")) } if s.Namespace != nil && len(*s.Namespace) < 1 { invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) } - if s.UserName == nil { - invalidParams.Add(request.NewErrParamRequired("UserName")) - } - if s.UserName != nil && len(*s.UserName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) - } if invalidParams.Len() > 0 { return invalidParams @@ -14147,210 +20887,275 @@ func (s *DescribeUserInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *DescribeUserInput) SetAwsAccountId(v string) *DescribeUserInput { +func (s *ListGroupsInput) SetAwsAccountId(v string) *ListGroupsInput { s.AwsAccountId = &v return s } +// SetMaxResults sets the MaxResults field's value. +func (s *ListGroupsInput) SetMaxResults(v int64) *ListGroupsInput { + s.MaxResults = &v + return s +} + // SetNamespace sets the Namespace field's value. -func (s *DescribeUserInput) SetNamespace(v string) *DescribeUserInput { +func (s *ListGroupsInput) SetNamespace(v string) *ListGroupsInput { s.Namespace = &v return s } -// SetUserName sets the UserName field's value. -func (s *DescribeUserInput) SetUserName(v string) *DescribeUserInput { - s.UserName = &v +// SetNextToken sets the NextToken field's value. +func (s *ListGroupsInput) SetNextToken(v string) *ListGroupsInput { + s.NextToken = &v return s } -type DescribeUserOutput struct { +type ListGroupsOutput struct { _ struct{} `type:"structure"` + // The list of the groups. + GroupList []*Group `type:"list"` + + // A pagination token that can be used in a subsequent request. + NextToken *string `type:"string"` + // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - - // The user name. - User *User `type:"structure"` } // String returns the string representation -func (s DescribeUserOutput) String() string { +func (s ListGroupsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DescribeUserOutput) GoString() string { +func (s ListGroupsOutput) GoString() string { return s.String() } +// SetGroupList sets the GroupList field's value. +func (s *ListGroupsOutput) SetGroupList(v []*Group) *ListGroupsOutput { + s.GroupList = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListGroupsOutput) SetNextToken(v string) *ListGroupsOutput { + s.NextToken = &v + return s +} + // SetRequestId sets the RequestId field's value. -func (s *DescribeUserOutput) SetRequestId(v string) *DescribeUserOutput { +func (s *ListGroupsOutput) SetRequestId(v string) *ListGroupsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *DescribeUserOutput) SetStatus(v int64) *DescribeUserOutput { +func (s *ListGroupsOutput) SetStatus(v int64) *ListGroupsOutput { s.Status = &v return s } -// SetUser sets the User field's value. -func (s *DescribeUserOutput) SetUser(v *User) *DescribeUserOutput { - s.User = v - return s -} +type ListIAMPolicyAssignmentsForUserInput struct { + _ struct{} `type:"structure"` -// The domain specified isn't on the allow list. All domains for embedded dashboards -// must be added to the approved list by an Amazon QuickSight admin. -type DomainNotWhitelistedException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + // The ID of the AWS account that contains the assignments. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - Message_ *string `locationName:"Message" type:"string"` + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` - // The AWS request ID for this request. - RequestId *string `type:"string"` + // The namespace of the assignment. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + + // The name of the user. + // + // UserName is a required field + UserName *string `location:"uri" locationName:"UserName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s DomainNotWhitelistedException) String() string { +func (s ListIAMPolicyAssignmentsForUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s DomainNotWhitelistedException) GoString() string { +func (s ListIAMPolicyAssignmentsForUserInput) GoString() string { return s.String() } -func newErrorDomainNotWhitelistedException(v protocol.ResponseMetadata) error { - return &DomainNotWhitelistedException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListIAMPolicyAssignmentsForUserInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListIAMPolicyAssignmentsForUserInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.UserName == nil { + invalidParams.Add(request.NewErrParamRequired("UserName")) + } + if s.UserName != nil && len(*s.UserName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) } -} -// Code returns the exception type name. -func (s *DomainNotWhitelistedException) Code() string { - return "DomainNotWhitelistedException" + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// Message returns the exception's message. -func (s *DomainNotWhitelistedException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *ListIAMPolicyAssignmentsForUserInput) SetAwsAccountId(v string) *ListIAMPolicyAssignmentsForUserInput { + s.AwsAccountId = &v + return s } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *DomainNotWhitelistedException) OrigErr() error { - return nil +// SetMaxResults sets the MaxResults field's value. +func (s *ListIAMPolicyAssignmentsForUserInput) SetMaxResults(v int64) *ListIAMPolicyAssignmentsForUserInput { + s.MaxResults = &v + return s } -func (s *DomainNotWhitelistedException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetNamespace sets the Namespace field's value. +func (s *ListIAMPolicyAssignmentsForUserInput) SetNamespace(v string) *ListIAMPolicyAssignmentsForUserInput { + s.Namespace = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *DomainNotWhitelistedException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetNextToken sets the NextToken field's value. +func (s *ListIAMPolicyAssignmentsForUserInput) SetNextToken(v string) *ListIAMPolicyAssignmentsForUserInput { + s.NextToken = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *DomainNotWhitelistedException) RequestID() string { - return s.RespMetadata.RequestID +// SetUserName sets the UserName field's value. +func (s *ListIAMPolicyAssignmentsForUserInput) SetUserName(v string) *ListIAMPolicyAssignmentsForUserInput { + s.UserName = &v + return s } -// Error information for the SPICE ingestion of a dataset. -type ErrorInfo struct { +type ListIAMPolicyAssignmentsForUserOutput struct { _ struct{} `type:"structure"` - // Error message. - Message *string `type:"string"` + // The active assignments for this user. + ActiveAssignments []*ActiveIAMPolicyAssignment `type:"list"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // Error type. - Type *string `type:"string" enum:"IngestionErrorType"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s ErrorInfo) String() string { +func (s ListIAMPolicyAssignmentsForUserOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ErrorInfo) GoString() string { +func (s ListIAMPolicyAssignmentsForUserOutput) GoString() string { return s.String() } -// SetMessage sets the Message field's value. -func (s *ErrorInfo) SetMessage(v string) *ErrorInfo { - s.Message = &v +// SetActiveAssignments sets the ActiveAssignments field's value. +func (s *ListIAMPolicyAssignmentsForUserOutput) SetActiveAssignments(v []*ActiveIAMPolicyAssignment) *ListIAMPolicyAssignmentsForUserOutput { + s.ActiveAssignments = v return s } -// SetType sets the Type field's value. -func (s *ErrorInfo) SetType(v string) *ErrorInfo { - s.Type = &v +// SetNextToken sets the NextToken field's value. +func (s *ListIAMPolicyAssignmentsForUserOutput) SetNextToken(v string) *ListIAMPolicyAssignmentsForUserOutput { + s.NextToken = &v return s } -// Export to .csv option. -type ExportToCSVOption struct { - _ struct{} `type:"structure"` - - // Availability status. - AvailabilityStatus *string `type:"string" enum:"DashboardBehavior"` -} - -// String returns the string representation -func (s ExportToCSVOption) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ExportToCSVOption) GoString() string { - return s.String() +// SetRequestId sets the RequestId field's value. +func (s *ListIAMPolicyAssignmentsForUserOutput) SetRequestId(v string) *ListIAMPolicyAssignmentsForUserOutput { + s.RequestId = &v + return s } -// SetAvailabilityStatus sets the AvailabilityStatus field's value. -func (s *ExportToCSVOption) SetAvailabilityStatus(v string) *ExportToCSVOption { - s.AvailabilityStatus = &v +// SetStatus sets the Status field's value. +func (s *ListIAMPolicyAssignmentsForUserOutput) SetStatus(v int64) *ListIAMPolicyAssignmentsForUserOutput { + s.Status = &v return s } -// A transform operation that filters rows based on a condition. -type FilterOperation struct { +type ListIAMPolicyAssignmentsInput struct { _ struct{} `type:"structure"` - // An expression that must evaluate to a Boolean value. Rows for which the expression - // evaluates to true are kept in the dataset. + // The status of the assignments. + AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` + + // The ID of the AWS account that contains these IAM policy assignments. // - // ConditionExpression is a required field - ConditionExpression *string `min:"1" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + + // The namespace for the assignments. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` } // String returns the string representation -func (s FilterOperation) String() string { +func (s ListIAMPolicyAssignmentsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s FilterOperation) GoString() string { +func (s ListIAMPolicyAssignmentsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *FilterOperation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "FilterOperation"} - if s.ConditionExpression == nil { - invalidParams.Add(request.NewErrParamRequired("ConditionExpression")) +func (s *ListIAMPolicyAssignmentsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListIAMPolicyAssignmentsInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.ConditionExpression != nil && len(*s.ConditionExpression) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ConditionExpression", 1)) + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) } if invalidParams.Len() > 0 { @@ -14359,158 +21164,133 @@ func (s *FilterOperation) Validate() error { return nil } -// SetConditionExpression sets the ConditionExpression field's value. -func (s *FilterOperation) SetConditionExpression(v string) *FilterOperation { - s.ConditionExpression = &v +// SetAssignmentStatus sets the AssignmentStatus field's value. +func (s *ListIAMPolicyAssignmentsInput) SetAssignmentStatus(v string) *ListIAMPolicyAssignmentsInput { + s.AssignmentStatus = &v return s } -// Geospatial column group that denotes a hierarchy. -type GeoSpatialColumnGroup struct { +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *ListIAMPolicyAssignmentsInput) SetAwsAccountId(v string) *ListIAMPolicyAssignmentsInput { + s.AwsAccountId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListIAMPolicyAssignmentsInput) SetMaxResults(v int64) *ListIAMPolicyAssignmentsInput { + s.MaxResults = &v + return s +} + +// SetNamespace sets the Namespace field's value. +func (s *ListIAMPolicyAssignmentsInput) SetNamespace(v string) *ListIAMPolicyAssignmentsInput { + s.Namespace = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListIAMPolicyAssignmentsInput) SetNextToken(v string) *ListIAMPolicyAssignmentsInput { + s.NextToken = &v + return s +} + +type ListIAMPolicyAssignmentsOutput struct { _ struct{} `type:"structure"` - // Columns in this hierarchy. - // - // Columns is a required field - Columns []*string `min:"1" type:"list" required:"true"` + // Information describing the IAM policy assignments. + IAMPolicyAssignments []*IAMPolicyAssignmentSummary `type:"list"` - // Country code. - // - // CountryCode is a required field - CountryCode *string `type:"string" required:"true" enum:"GeoSpatialCountryCode"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` - // A display name for the hierarchy. - // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s GeoSpatialColumnGroup) String() string { +func (s ListIAMPolicyAssignmentsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GeoSpatialColumnGroup) GoString() string { +func (s ListIAMPolicyAssignmentsOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *GeoSpatialColumnGroup) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GeoSpatialColumnGroup"} - if s.Columns == nil { - invalidParams.Add(request.NewErrParamRequired("Columns")) - } - if s.Columns != nil && len(s.Columns) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Columns", 1)) - } - if s.CountryCode == nil { - invalidParams.Add(request.NewErrParamRequired("CountryCode")) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetIAMPolicyAssignments sets the IAMPolicyAssignments field's value. +func (s *ListIAMPolicyAssignmentsOutput) SetIAMPolicyAssignments(v []*IAMPolicyAssignmentSummary) *ListIAMPolicyAssignmentsOutput { + s.IAMPolicyAssignments = v + return s } -// SetColumns sets the Columns field's value. -func (s *GeoSpatialColumnGroup) SetColumns(v []*string) *GeoSpatialColumnGroup { - s.Columns = v +// SetNextToken sets the NextToken field's value. +func (s *ListIAMPolicyAssignmentsOutput) SetNextToken(v string) *ListIAMPolicyAssignmentsOutput { + s.NextToken = &v return s } -// SetCountryCode sets the CountryCode field's value. -func (s *GeoSpatialColumnGroup) SetCountryCode(v string) *GeoSpatialColumnGroup { - s.CountryCode = &v +// SetRequestId sets the RequestId field's value. +func (s *ListIAMPolicyAssignmentsOutput) SetRequestId(v string) *ListIAMPolicyAssignmentsOutput { + s.RequestId = &v return s } -// SetName sets the Name field's value. -func (s *GeoSpatialColumnGroup) SetName(v string) *GeoSpatialColumnGroup { - s.Name = &v +// SetStatus sets the Status field's value. +func (s *ListIAMPolicyAssignmentsOutput) SetStatus(v int64) *ListIAMPolicyAssignmentsOutput { + s.Status = &v return s } -type GetDashboardEmbedUrlInput struct { +type ListIngestionsInput struct { _ struct{} `type:"structure"` - // The ID for the AWS account that contains the dashboard that you're embedding. + // The AWS account ID. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the dashboard, also added to the IAM policy. - // - // DashboardId is a required field - DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` - - // The authentication method that the user uses to sign in. + // The ID of the dataset used in the ingestion. // - // IdentityType is a required field - IdentityType *string `location:"querystring" locationName:"creds-type" type:"string" required:"true" enum:"IdentityType"` - - // Remove the reset button on the embedded dashboard. The default is FALSE, - // which enables the reset button. - ResetDisabled *bool `location:"querystring" locationName:"reset-disabled" type:"boolean"` - - // How many minutes the session is valid. The session lifetime must be 15-600 - // minutes. - SessionLifetimeInMinutes *int64 `location:"querystring" locationName:"session-lifetime" min:"15" type:"long"` + // DataSetId is a required field + DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` - // Remove the undo/redo button on the embedded dashboard. The default is FALSE, - // which enables the undo/redo button. - UndoRedoDisabled *bool `location:"querystring" locationName:"undo-redo-disabled" type:"boolean"` + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` - // The Amazon QuickSight user's Amazon Resource Name (ARN), for use with QUICKSIGHT - // identity type. You can use this for any Amazon QuickSight users in your account - // (readers, authors, or admins) authenticated as one of the following: - // - // * Active Directory (AD) users or group members - // - // * Invited nonfederated users - // - // * IAM users and IAM role-based sessions authenticated through Federated - // Single Sign-On using SAML, OpenID Connect, or IAM federation. - UserArn *string `location:"querystring" locationName:"user-arn" type:"string"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` } // String returns the string representation -func (s GetDashboardEmbedUrlInput) String() string { +func (s ListIngestionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDashboardEmbedUrlInput) GoString() string { +func (s ListIngestionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *GetDashboardEmbedUrlInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDashboardEmbedUrlInput"} +func (s *ListIngestionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListIngestionsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DashboardId == nil { - invalidParams.Add(request.NewErrParamRequired("DashboardId")) - } - if s.DashboardId != nil && len(*s.DashboardId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) + if s.DataSetId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetId")) } - if s.IdentityType == nil { - invalidParams.Add(request.NewErrParamRequired("IdentityType")) + if s.DataSetId != nil && len(*s.DataSetId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) } - if s.SessionLifetimeInMinutes != nil && *s.SessionLifetimeInMinutes < 15 { - invalidParams.Add(request.NewErrParamMinValue("SessionLifetimeInMinutes", 15)) + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } if invalidParams.Len() > 0 { @@ -14520,55 +21300,37 @@ func (s *GetDashboardEmbedUrlInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *GetDashboardEmbedUrlInput) SetAwsAccountId(v string) *GetDashboardEmbedUrlInput { +func (s *ListIngestionsInput) SetAwsAccountId(v string) *ListIngestionsInput { s.AwsAccountId = &v return s } -// SetDashboardId sets the DashboardId field's value. -func (s *GetDashboardEmbedUrlInput) SetDashboardId(v string) *GetDashboardEmbedUrlInput { - s.DashboardId = &v - return s -} - -// SetIdentityType sets the IdentityType field's value. -func (s *GetDashboardEmbedUrlInput) SetIdentityType(v string) *GetDashboardEmbedUrlInput { - s.IdentityType = &v - return s -} - -// SetResetDisabled sets the ResetDisabled field's value. -func (s *GetDashboardEmbedUrlInput) SetResetDisabled(v bool) *GetDashboardEmbedUrlInput { - s.ResetDisabled = &v - return s -} - -// SetSessionLifetimeInMinutes sets the SessionLifetimeInMinutes field's value. -func (s *GetDashboardEmbedUrlInput) SetSessionLifetimeInMinutes(v int64) *GetDashboardEmbedUrlInput { - s.SessionLifetimeInMinutes = &v +// SetDataSetId sets the DataSetId field's value. +func (s *ListIngestionsInput) SetDataSetId(v string) *ListIngestionsInput { + s.DataSetId = &v return s } -// SetUndoRedoDisabled sets the UndoRedoDisabled field's value. -func (s *GetDashboardEmbedUrlInput) SetUndoRedoDisabled(v bool) *GetDashboardEmbedUrlInput { - s.UndoRedoDisabled = &v +// SetMaxResults sets the MaxResults field's value. +func (s *ListIngestionsInput) SetMaxResults(v int64) *ListIngestionsInput { + s.MaxResults = &v return s } -// SetUserArn sets the UserArn field's value. -func (s *GetDashboardEmbedUrlInput) SetUserArn(v string) *GetDashboardEmbedUrlInput { - s.UserArn = &v +// SetNextToken sets the NextToken field's value. +func (s *ListIngestionsInput) SetNextToken(v string) *ListIngestionsInput { + s.NextToken = &v return s } -type GetDashboardEmbedUrlOutput struct { +type ListIngestionsOutput struct { _ struct{} `type:"structure"` - // An URL that you can put into your server-side webpage to embed your dashboard. - // This URL is valid for 5 minutes, and the resulting session is valid for 10 - // hours. The API provides the URL with an auth_code value that enables a single - // sign-on session. - EmbedUrl *string `type:"string" sensitive:"true"` + // A list of the ingestions. + Ingestions []*Ingestion `type:"list"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -14578,438 +21340,415 @@ type GetDashboardEmbedUrlOutput struct { } // String returns the string representation -func (s GetDashboardEmbedUrlOutput) String() string { +func (s ListIngestionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s GetDashboardEmbedUrlOutput) GoString() string { +func (s ListIngestionsOutput) GoString() string { return s.String() } -// SetEmbedUrl sets the EmbedUrl field's value. -func (s *GetDashboardEmbedUrlOutput) SetEmbedUrl(v string) *GetDashboardEmbedUrlOutput { - s.EmbedUrl = &v +// SetIngestions sets the Ingestions field's value. +func (s *ListIngestionsOutput) SetIngestions(v []*Ingestion) *ListIngestionsOutput { + s.Ingestions = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListIngestionsOutput) SetNextToken(v string) *ListIngestionsOutput { + s.NextToken = &v return s } // SetRequestId sets the RequestId field's value. -func (s *GetDashboardEmbedUrlOutput) SetRequestId(v string) *GetDashboardEmbedUrlOutput { +func (s *ListIngestionsOutput) SetRequestId(v string) *ListIngestionsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *GetDashboardEmbedUrlOutput) SetStatus(v int64) *GetDashboardEmbedUrlOutput { +func (s *ListIngestionsOutput) SetStatus(v int64) *ListIngestionsOutput { s.Status = &v return s } -// A group in Amazon QuickSight consists of a set of users. You can use groups -// to make it easier to manage access and security. Currently, an Amazon QuickSight -// subscription can't contain more than 500 Amazon QuickSight groups. -type Group struct { +type ListNamespacesInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) for the group. - Arn *string `type:"string"` - - // The group description. - Description *string `min:"1" type:"string"` + // The ID for the AWS account that contains the QuickSight namespaces that you + // want to list. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The name of the group. - GroupName *string `min:"1" type:"string"` + // The maximum number of results to return. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` - // The principal ID of the group. - PrincipalId *string `type:"string"` + // A pagination token that can be used in a subsequent request. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` } // String returns the string representation -func (s Group) String() string { +func (s ListNamespacesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Group) GoString() string { +func (s ListNamespacesInput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *Group) SetArn(v string) *Group { - s.Arn = &v - return s -} - -// SetDescription sets the Description field's value. -func (s *Group) SetDescription(v string) *Group { - s.Description = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListNamespacesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListNamespacesInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } -// SetGroupName sets the GroupName field's value. -func (s *Group) SetGroupName(v string) *Group { - s.GroupName = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetPrincipalId sets the PrincipalId field's value. -func (s *Group) SetPrincipalId(v string) *Group { - s.PrincipalId = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *ListNamespacesInput) SetAwsAccountId(v string) *ListNamespacesInput { + s.AwsAccountId = &v return s } -// A member of an Amazon QuickSight group. Currently, group members must be -// users. Groups can't be members of another group. . -type GroupMember struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) for the group member (user). - Arn *string `type:"string"` - - // The name of the group member (user). - MemberName *string `min:"1" type:"string"` -} - -// String returns the string representation -func (s GroupMember) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GroupMember) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *GroupMember) SetArn(v string) *GroupMember { - s.Arn = &v +// SetMaxResults sets the MaxResults field's value. +func (s *ListNamespacesInput) SetMaxResults(v int64) *ListNamespacesInput { + s.MaxResults = &v return s } -// SetMemberName sets the MemberName field's value. -func (s *GroupMember) SetMemberName(v string) *GroupMember { - s.MemberName = &v +// SetNextToken sets the NextToken field's value. +func (s *ListNamespacesInput) SetNextToken(v string) *ListNamespacesInput { + s.NextToken = &v return s } -// An IAM policy assignment. -type IAMPolicyAssignment struct { +type ListNamespacesOutput struct { _ struct{} `type:"structure"` - // Assignment ID. - AssignmentId *string `type:"string"` - - // Assignment name. - AssignmentName *string `min:"1" type:"string"` - - // Assignment status. - AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` + // The information about the namespaces in this AWS account. The response includes + // the namespace ARN, name, AWS Region, notification email address, creation + // status, and identity store. + Namespaces []*NamespaceInfoV2 `type:"list"` - // The AWS account ID. - AwsAccountId *string `min:"12" type:"string"` + // A pagination token that can be used in a subsequent request. + NextToken *string `type:"string"` - // Identities. - Identities map[string][]*string `type:"map"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // The Amazon Resource Name (ARN) for the IAM policy. - PolicyArn *string `type:"string"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s IAMPolicyAssignment) String() string { +func (s ListNamespacesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s IAMPolicyAssignment) GoString() string { +func (s ListNamespacesOutput) GoString() string { return s.String() } -// SetAssignmentId sets the AssignmentId field's value. -func (s *IAMPolicyAssignment) SetAssignmentId(v string) *IAMPolicyAssignment { - s.AssignmentId = &v - return s -} - -// SetAssignmentName sets the AssignmentName field's value. -func (s *IAMPolicyAssignment) SetAssignmentName(v string) *IAMPolicyAssignment { - s.AssignmentName = &v - return s -} - -// SetAssignmentStatus sets the AssignmentStatus field's value. -func (s *IAMPolicyAssignment) SetAssignmentStatus(v string) *IAMPolicyAssignment { - s.AssignmentStatus = &v +// SetNamespaces sets the Namespaces field's value. +func (s *ListNamespacesOutput) SetNamespaces(v []*NamespaceInfoV2) *ListNamespacesOutput { + s.Namespaces = v return s } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *IAMPolicyAssignment) SetAwsAccountId(v string) *IAMPolicyAssignment { - s.AwsAccountId = &v +// SetNextToken sets the NextToken field's value. +func (s *ListNamespacesOutput) SetNextToken(v string) *ListNamespacesOutput { + s.NextToken = &v return s } -// SetIdentities sets the Identities field's value. -func (s *IAMPolicyAssignment) SetIdentities(v map[string][]*string) *IAMPolicyAssignment { - s.Identities = v +// SetRequestId sets the RequestId field's value. +func (s *ListNamespacesOutput) SetRequestId(v string) *ListNamespacesOutput { + s.RequestId = &v return s } -// SetPolicyArn sets the PolicyArn field's value. -func (s *IAMPolicyAssignment) SetPolicyArn(v string) *IAMPolicyAssignment { - s.PolicyArn = &v +// SetStatus sets the Status field's value. +func (s *ListNamespacesOutput) SetStatus(v int64) *ListNamespacesOutput { + s.Status = &v return s } -// IAM policy assignment summary. -type IAMPolicyAssignmentSummary struct { +type ListTagsForResourceInput struct { _ struct{} `type:"structure"` - // Assignment name. - AssignmentName *string `min:"1" type:"string"` - - // Assignment status. - AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` + // The Amazon Resource Name (ARN) of the resource that you want a list of tags + // for. + // + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"ResourceArn" type:"string" required:"true"` } // String returns the string representation -func (s IAMPolicyAssignmentSummary) String() string { +func (s ListTagsForResourceInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s IAMPolicyAssignmentSummary) GoString() string { +func (s ListTagsForResourceInput) GoString() string { return s.String() } -// SetAssignmentName sets the AssignmentName field's value. -func (s *IAMPolicyAssignmentSummary) SetAssignmentName(v string) *IAMPolicyAssignmentSummary { - s.AssignmentName = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTagsForResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} + 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 *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResourceInput { + s.ResourceArn = &v return s } -// SetAssignmentStatus sets the AssignmentStatus field's value. -func (s *IAMPolicyAssignmentSummary) SetAssignmentStatus(v string) *IAMPolicyAssignmentSummary { - s.AssignmentStatus = &v - return s -} +type ListTagsForResourceOutput struct { + _ struct{} `type:"structure"` -// The identity type specified isn't supported. Supported identity types include -// IAM and QUICKSIGHT. -type IdentityTypeNotSupportedException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - Message_ *string `locationName:"Message" type:"string"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` - // The AWS request ID for this request. - RequestId *string `type:"string"` + // Contains a map of the key-value pairs for the resource tag or tags assigned + // to the resource. + Tags []*Tag `min:"1" type:"list"` } // String returns the string representation -func (s IdentityTypeNotSupportedException) String() string { +func (s ListTagsForResourceOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s IdentityTypeNotSupportedException) GoString() string { +func (s ListTagsForResourceOutput) GoString() string { return s.String() } -func newErrorIdentityTypeNotSupportedException(v protocol.ResponseMetadata) error { - return &IdentityTypeNotSupportedException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *IdentityTypeNotSupportedException) Code() string { - return "IdentityTypeNotSupportedException" -} - -// Message returns the exception's message. -func (s *IdentityTypeNotSupportedException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *IdentityTypeNotSupportedException) OrigErr() error { - return nil -} - -func (s *IdentityTypeNotSupportedException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetRequestId sets the RequestId field's value. +func (s *ListTagsForResourceOutput) SetRequestId(v string) *ListTagsForResourceOutput { + s.RequestId = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *IdentityTypeNotSupportedException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetStatus sets the Status field's value. +func (s *ListTagsForResourceOutput) SetStatus(v int64) *ListTagsForResourceOutput { + s.Status = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *IdentityTypeNotSupportedException) RequestID() string { - return s.RespMetadata.RequestID +// SetTags sets the Tags field's value. +func (s *ListTagsForResourceOutput) SetTags(v []*Tag) *ListTagsForResourceOutput { + s.Tags = v + return s } -// Information about the SPICE ingestion for a dataset. -type Ingestion struct { +type ListTemplateAliasesInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. - // - // Arn is a required field - Arn *string `type:"string" required:"true"` - - // The time that this ingestion started. + // The ID of the AWS account that contains the template aliases that you're + // listing. // - // CreatedTime is a required field - CreatedTime *time.Time `type:"timestamp" required:"true"` - - // Error information for this ingestion. - ErrorInfo *ErrorInfo `type:"structure"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Ingestion ID. - IngestionId *string `min:"1" type:"string"` + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-result" min:"1" type:"integer"` - // The size of the data ingested, in bytes. - IngestionSizeInBytes *int64 `type:"long"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` - // Ingestion status. + // The ID for the template. // - // IngestionStatus is a required field - IngestionStatus *string `type:"string" required:"true" enum:"IngestionStatus"` - - // The time that this ingestion took, measured in seconds. - IngestionTimeInSeconds *int64 `type:"long"` - - // Information about a queued dataset SPICE ingestion. - QueueInfo *QueueInfo `type:"structure"` - - // Event source for this ingestion. - RequestSource *string `type:"string" enum:"IngestionRequestSource"` - - // Type of this ingestion. - RequestType *string `type:"string" enum:"IngestionRequestType"` - - // Information about rows for a data set SPICE ingestion. - RowInfo *RowInfo `type:"structure"` + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s Ingestion) String() string { +func (s ListTemplateAliasesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Ingestion) GoString() string { +func (s ListTemplateAliasesInput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *Ingestion) SetArn(v string) *Ingestion { - s.Arn = &v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTemplateAliasesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTemplateAliasesInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) + } + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetCreatedTime sets the CreatedTime field's value. -func (s *Ingestion) SetCreatedTime(v time.Time) *Ingestion { - s.CreatedTime = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *ListTemplateAliasesInput) SetAwsAccountId(v string) *ListTemplateAliasesInput { + s.AwsAccountId = &v return s } -// SetErrorInfo sets the ErrorInfo field's value. -func (s *Ingestion) SetErrorInfo(v *ErrorInfo) *Ingestion { - s.ErrorInfo = v +// SetMaxResults sets the MaxResults field's value. +func (s *ListTemplateAliasesInput) SetMaxResults(v int64) *ListTemplateAliasesInput { + s.MaxResults = &v return s } -// SetIngestionId sets the IngestionId field's value. -func (s *Ingestion) SetIngestionId(v string) *Ingestion { - s.IngestionId = &v +// SetNextToken sets the NextToken field's value. +func (s *ListTemplateAliasesInput) SetNextToken(v string) *ListTemplateAliasesInput { + s.NextToken = &v return s } -// SetIngestionSizeInBytes sets the IngestionSizeInBytes field's value. -func (s *Ingestion) SetIngestionSizeInBytes(v int64) *Ingestion { - s.IngestionSizeInBytes = &v +// SetTemplateId sets the TemplateId field's value. +func (s *ListTemplateAliasesInput) SetTemplateId(v string) *ListTemplateAliasesInput { + s.TemplateId = &v return s } -// SetIngestionStatus sets the IngestionStatus field's value. -func (s *Ingestion) SetIngestionStatus(v string) *Ingestion { - s.IngestionStatus = &v - return s +type ListTemplateAliasesOutput struct { + _ struct{} `type:"structure"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` + + // A structure containing the list of the template's aliases. + TemplateAliasList []*TemplateAlias `type:"list"` } -// SetIngestionTimeInSeconds sets the IngestionTimeInSeconds field's value. -func (s *Ingestion) SetIngestionTimeInSeconds(v int64) *Ingestion { - s.IngestionTimeInSeconds = &v - return s +// String returns the string representation +func (s ListTemplateAliasesOutput) String() string { + return awsutil.Prettify(s) } -// SetQueueInfo sets the QueueInfo field's value. -func (s *Ingestion) SetQueueInfo(v *QueueInfo) *Ingestion { - s.QueueInfo = v +// GoString returns the string representation +func (s ListTemplateAliasesOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListTemplateAliasesOutput) SetNextToken(v string) *ListTemplateAliasesOutput { + s.NextToken = &v return s } -// SetRequestSource sets the RequestSource field's value. -func (s *Ingestion) SetRequestSource(v string) *Ingestion { - s.RequestSource = &v +// SetRequestId sets the RequestId field's value. +func (s *ListTemplateAliasesOutput) SetRequestId(v string) *ListTemplateAliasesOutput { + s.RequestId = &v return s } -// SetRequestType sets the RequestType field's value. -func (s *Ingestion) SetRequestType(v string) *Ingestion { - s.RequestType = &v +// SetStatus sets the Status field's value. +func (s *ListTemplateAliasesOutput) SetStatus(v int64) *ListTemplateAliasesOutput { + s.Status = &v return s } -// SetRowInfo sets the RowInfo field's value. -func (s *Ingestion) SetRowInfo(v *RowInfo) *Ingestion { - s.RowInfo = v +// SetTemplateAliasList sets the TemplateAliasList field's value. +func (s *ListTemplateAliasesOutput) SetTemplateAliasList(v []*TemplateAlias) *ListTemplateAliasesOutput { + s.TemplateAliasList = v return s } -// Metadata for a column that is used as the input of a transform operation. -type InputColumn struct { +type ListTemplateVersionsInput struct { _ struct{} `type:"structure"` - // The name of this column in the underlying data source. + // The ID of the AWS account that contains the templates that you're listing. // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The data type of the column. + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + + // The ID for the template. // - // Type is a required field - Type *string `type:"string" required:"true" enum:"InputColumnDataType"` + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s InputColumn) String() string { +func (s ListTemplateVersionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InputColumn) GoString() string { +func (s ListTemplateVersionsInput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *InputColumn) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InputColumn"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTemplateVersionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTemplateVersionsInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) + } + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) } if invalidParams.Len() > 0 { @@ -15018,348 +21757,368 @@ func (s *InputColumn) Validate() error { return nil } -// SetName sets the Name field's value. -func (s *InputColumn) SetName(v string) *InputColumn { - s.Name = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *ListTemplateVersionsInput) SetAwsAccountId(v string) *ListTemplateVersionsInput { + s.AwsAccountId = &v return s } -// SetType sets the Type field's value. -func (s *InputColumn) SetType(v string) *InputColumn { - s.Type = &v +// SetMaxResults sets the MaxResults field's value. +func (s *ListTemplateVersionsInput) SetMaxResults(v int64) *ListTemplateVersionsInput { + s.MaxResults = &v return s } -// Integer parameter. -type IntegerParameter struct { +// SetNextToken sets the NextToken field's value. +func (s *ListTemplateVersionsInput) SetNextToken(v string) *ListTemplateVersionsInput { + s.NextToken = &v + return s +} + +// SetTemplateId sets the TemplateId field's value. +func (s *ListTemplateVersionsInput) SetTemplateId(v string) *ListTemplateVersionsInput { + s.TemplateId = &v + return s +} + +type ListTemplateVersionsOutput struct { _ struct{} `type:"structure"` - // A display name for the dataset. - // - // Name is a required field - Name *string `type:"string" required:"true"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` - // Values. - // - // Values is a required field - Values []*int64 `type:"list" required:"true"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` + + // A structure containing a list of all the versions of the specified template. + TemplateVersionSummaryList []*TemplateVersionSummary `type:"list"` } // String returns the string representation -func (s IntegerParameter) String() string { +func (s ListTemplateVersionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s IntegerParameter) GoString() string { +func (s ListTemplateVersionsOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *IntegerParameter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "IntegerParameter"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Values == nil { - invalidParams.Add(request.NewErrParamRequired("Values")) - } +// SetNextToken sets the NextToken field's value. +func (s *ListTemplateVersionsOutput) SetNextToken(v string) *ListTemplateVersionsOutput { + s.NextToken = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetRequestId sets the RequestId field's value. +func (s *ListTemplateVersionsOutput) SetRequestId(v string) *ListTemplateVersionsOutput { + s.RequestId = &v + return s } -// SetName sets the Name field's value. -func (s *IntegerParameter) SetName(v string) *IntegerParameter { - s.Name = &v +// SetStatus sets the Status field's value. +func (s *ListTemplateVersionsOutput) SetStatus(v int64) *ListTemplateVersionsOutput { + s.Status = &v return s } -// SetValues sets the Values field's value. -func (s *IntegerParameter) SetValues(v []*int64) *IntegerParameter { - s.Values = v +// SetTemplateVersionSummaryList sets the TemplateVersionSummaryList field's value. +func (s *ListTemplateVersionsOutput) SetTemplateVersionSummaryList(v []*TemplateVersionSummary) *ListTemplateVersionsOutput { + s.TemplateVersionSummaryList = v return s } -// An internal failure occurred. -type InternalFailureException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +type ListTemplatesInput struct { + _ struct{} `type:"structure"` - Message_ *string `locationName:"Message" type:"string"` + // The ID of the AWS account that contains the templates that you're listing. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The AWS request ID for this request. - RequestId *string `type:"string"` + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-result" min:"1" type:"integer"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` } // String returns the string representation -func (s InternalFailureException) String() string { +func (s ListTemplatesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InternalFailureException) GoString() string { +func (s ListTemplatesInput) GoString() string { return s.String() } -func newErrorInternalFailureException(v protocol.ResponseMetadata) error { - return &InternalFailureException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTemplatesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTemplatesInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } -} - -// Code returns the exception type name. -func (s *InternalFailureException) Code() string { - return "InternalFailureException" -} - -// Message returns the exception's message. -func (s *InternalFailureException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } - return "" -} -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InternalFailureException) OrigErr() error { + if invalidParams.Len() > 0 { + return invalidParams + } return nil } -func (s *InternalFailureException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *ListTemplatesInput) SetAwsAccountId(v string) *ListTemplatesInput { + s.AwsAccountId = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *InternalFailureException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetMaxResults sets the MaxResults field's value. +func (s *ListTemplatesInput) SetMaxResults(v int64) *ListTemplatesInput { + s.MaxResults = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *InternalFailureException) RequestID() string { - return s.RespMetadata.RequestID +// SetNextToken sets the NextToken field's value. +func (s *ListTemplatesInput) SetNextToken(v string) *ListTemplatesInput { + s.NextToken = &v + return s } -// The NextToken value isn't valid. -type InvalidNextTokenException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +type ListTemplatesOutput struct { + _ struct{} `type:"structure"` - Message_ *string `locationName:"Message" type:"string"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` - // The AWS request ID for this request. + // The AWS request ID for this operation. RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` + + // A structure containing information about the templates in the list. + TemplateSummaryList []*TemplateSummary `type:"list"` } // String returns the string representation -func (s InvalidNextTokenException) String() string { +func (s ListTemplatesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InvalidNextTokenException) GoString() string { +func (s ListTemplatesOutput) GoString() string { return s.String() } -func newErrorInvalidNextTokenException(v protocol.ResponseMetadata) error { - return &InvalidNextTokenException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *InvalidNextTokenException) Code() string { - return "InvalidNextTokenException" +// SetNextToken sets the NextToken field's value. +func (s *ListTemplatesOutput) SetNextToken(v string) *ListTemplatesOutput { + s.NextToken = &v + return s } -// Message returns the exception's message. -func (s *InvalidNextTokenException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" +// SetRequestId sets the RequestId field's value. +func (s *ListTemplatesOutput) SetRequestId(v string) *ListTemplatesOutput { + s.RequestId = &v + return s } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidNextTokenException) OrigErr() error { - return nil +// SetStatus sets the Status field's value. +func (s *ListTemplatesOutput) SetStatus(v int64) *ListTemplatesOutput { + s.Status = &v + return s } -func (s *InvalidNextTokenException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetTemplateSummaryList sets the TemplateSummaryList field's value. +func (s *ListTemplatesOutput) SetTemplateSummaryList(v []*TemplateSummary) *ListTemplatesOutput { + s.TemplateSummaryList = v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidNextTokenException) StatusCode() int { - return s.RespMetadata.StatusCode -} +type ListThemeAliasesInput struct { + _ struct{} `type:"structure"` -// RequestID returns the service's response RequestID for request. -func (s *InvalidNextTokenException) RequestID() string { - return s.RespMetadata.RequestID -} + // The ID of the AWS account that contains the theme aliases that you're listing. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` -// One or more parameters has a value that isn't valid. -type InvalidParameterValueException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-result" min:"1" type:"integer"` - Message_ *string `locationName:"Message" type:"string"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` - // The AWS request ID for this request. - RequestId *string `type:"string"` + // The ID for the theme. + // + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s InvalidParameterValueException) String() string { +func (s ListThemeAliasesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s InvalidParameterValueException) GoString() string { +func (s ListThemeAliasesInput) GoString() string { return s.String() } -func newErrorInvalidParameterValueException(v protocol.ResponseMetadata) error { - return &InvalidParameterValueException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListThemeAliasesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListThemeAliasesInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) + } + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) } -} - -// Code returns the exception type name. -func (s *InvalidParameterValueException) Code() string { - return "InvalidParameterValueException" -} -// Message returns the exception's message. -func (s *InvalidParameterValueException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if invalidParams.Len() > 0 { + return invalidParams } - return "" + return nil } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *InvalidParameterValueException) OrigErr() error { - return nil +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *ListThemeAliasesInput) SetAwsAccountId(v string) *ListThemeAliasesInput { + s.AwsAccountId = &v + return s } -func (s *InvalidParameterValueException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetMaxResults sets the MaxResults field's value. +func (s *ListThemeAliasesInput) SetMaxResults(v int64) *ListThemeAliasesInput { + s.MaxResults = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *InvalidParameterValueException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetNextToken sets the NextToken field's value. +func (s *ListThemeAliasesInput) SetNextToken(v string) *ListThemeAliasesInput { + s.NextToken = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *InvalidParameterValueException) RequestID() string { - return s.RespMetadata.RequestID +// SetThemeId sets the ThemeId field's value. +func (s *ListThemeAliasesInput) SetThemeId(v string) *ListThemeAliasesInput { + s.ThemeId = &v + return s } -// Jira parameters. -type JiraParameters struct { +type ListThemeAliasesOutput struct { _ struct{} `type:"structure"` - // The base URL of the Jira site. - // - // SiteBaseUrl is a required field - SiteBaseUrl *string `min:"1" type:"string" required:"true"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` + + // A structure containing the list of the theme's aliases. + ThemeAliasList []*ThemeAlias `type:"list"` } // String returns the string representation -func (s JiraParameters) String() string { +func (s ListThemeAliasesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s JiraParameters) GoString() string { +func (s ListThemeAliasesOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *JiraParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "JiraParameters"} - if s.SiteBaseUrl == nil { - invalidParams.Add(request.NewErrParamRequired("SiteBaseUrl")) - } - if s.SiteBaseUrl != nil && len(*s.SiteBaseUrl) < 1 { - invalidParams.Add(request.NewErrParamMinLen("SiteBaseUrl", 1)) - } +// SetNextToken sets the NextToken field's value. +func (s *ListThemeAliasesOutput) SetNextToken(v string) *ListThemeAliasesOutput { + s.NextToken = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetRequestId sets the RequestId field's value. +func (s *ListThemeAliasesOutput) SetRequestId(v string) *ListThemeAliasesOutput { + s.RequestId = &v + return s } -// SetSiteBaseUrl sets the SiteBaseUrl field's value. -func (s *JiraParameters) SetSiteBaseUrl(v string) *JiraParameters { - s.SiteBaseUrl = &v +// SetStatus sets the Status field's value. +func (s *ListThemeAliasesOutput) SetStatus(v int64) *ListThemeAliasesOutput { + s.Status = &v return s } -// Join instruction. -type JoinInstruction struct { +// SetThemeAliasList sets the ThemeAliasList field's value. +func (s *ListThemeAliasesOutput) SetThemeAliasList(v []*ThemeAlias) *ListThemeAliasesOutput { + s.ThemeAliasList = v + return s +} + +type ListThemeVersionsInput struct { _ struct{} `type:"structure"` - // Left operand. + // The ID of the AWS account that contains the themes that you're listing. // - // LeftOperand is a required field - LeftOperand *string `min:"1" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // On Clause. - // - // OnClause is a required field - OnClause *string `min:"1" type:"string" required:"true"` + // The maximum number of results to be returned per request. + MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` - // Right operand. - // - // RightOperand is a required field - RightOperand *string `min:"1" type:"string" required:"true"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `location:"querystring" locationName:"next-token" type:"string"` - // Type. + // The ID for the theme. // - // Type is a required field - Type *string `type:"string" required:"true" enum:"JoinType"` + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s JoinInstruction) String() string { +func (s ListThemeVersionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s JoinInstruction) GoString() string { +func (s ListThemeVersionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *JoinInstruction) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "JoinInstruction"} - if s.LeftOperand == nil { - invalidParams.Add(request.NewErrParamRequired("LeftOperand")) - } - if s.LeftOperand != nil && len(*s.LeftOperand) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LeftOperand", 1)) - } - if s.OnClause == nil { - invalidParams.Add(request.NewErrParamRequired("OnClause")) +func (s *ListThemeVersionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListThemeVersionsInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.OnClause != nil && len(*s.OnClause) < 1 { - invalidParams.Add(request.NewErrParamMinLen("OnClause", 1)) + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.RightOperand == nil { - invalidParams.Add(request.NewErrParamRequired("RightOperand")) + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } - if s.RightOperand != nil && len(*s.RightOperand) < 1 { - invalidParams.Add(request.NewErrParamMinLen("RightOperand", 1)) + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) } if invalidParams.Len() > 0 { @@ -15368,138 +22127,123 @@ func (s *JoinInstruction) Validate() error { return nil } -// SetLeftOperand sets the LeftOperand field's value. -func (s *JoinInstruction) SetLeftOperand(v string) *JoinInstruction { - s.LeftOperand = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *ListThemeVersionsInput) SetAwsAccountId(v string) *ListThemeVersionsInput { + s.AwsAccountId = &v return s } -// SetOnClause sets the OnClause field's value. -func (s *JoinInstruction) SetOnClause(v string) *JoinInstruction { - s.OnClause = &v +// SetMaxResults sets the MaxResults field's value. +func (s *ListThemeVersionsInput) SetMaxResults(v int64) *ListThemeVersionsInput { + s.MaxResults = &v return s } -// SetRightOperand sets the RightOperand field's value. -func (s *JoinInstruction) SetRightOperand(v string) *JoinInstruction { - s.RightOperand = &v +// SetNextToken sets the NextToken field's value. +func (s *ListThemeVersionsInput) SetNextToken(v string) *ListThemeVersionsInput { + s.NextToken = &v return s } -// SetType sets the Type field's value. -func (s *JoinInstruction) SetType(v string) *JoinInstruction { - s.Type = &v +// SetThemeId sets the ThemeId field's value. +func (s *ListThemeVersionsInput) SetThemeId(v string) *ListThemeVersionsInput { + s.ThemeId = &v return s } -// A limit is exceeded. -type LimitExceededException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +type ListThemeVersionsOutput struct { + _ struct{} `type:"structure"` - Message_ *string `locationName:"Message" type:"string"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` - // The AWS request ID for this request. + // The AWS request ID for this operation. RequestId *string `type:"string"` - // Limit exceeded. - ResourceType *string `type:"string" enum:"ExceptionResourceType"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` + + // A structure containing a list of all the versions of the specified theme. + ThemeVersionSummaryList []*ThemeVersionSummary `type:"list"` } // String returns the string representation -func (s LimitExceededException) String() string { +func (s ListThemeVersionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s LimitExceededException) GoString() string { +func (s ListThemeVersionsOutput) GoString() string { return s.String() } -func newErrorLimitExceededException(v protocol.ResponseMetadata) error { - return &LimitExceededException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *LimitExceededException) Code() string { - return "LimitExceededException" -} - -// Message returns the exception's message. -func (s *LimitExceededException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" -} - -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *LimitExceededException) OrigErr() error { - return nil +// SetNextToken sets the NextToken field's value. +func (s *ListThemeVersionsOutput) SetNextToken(v string) *ListThemeVersionsOutput { + s.NextToken = &v + return s } -func (s *LimitExceededException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetRequestId sets the RequestId field's value. +func (s *ListThemeVersionsOutput) SetRequestId(v string) *ListThemeVersionsOutput { + s.RequestId = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *LimitExceededException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetStatus sets the Status field's value. +func (s *ListThemeVersionsOutput) SetStatus(v int64) *ListThemeVersionsOutput { + s.Status = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *LimitExceededException) RequestID() string { - return s.RespMetadata.RequestID +// SetThemeVersionSummaryList sets the ThemeVersionSummaryList field's value. +func (s *ListThemeVersionsOutput) SetThemeVersionSummaryList(v []*ThemeVersionSummary) *ListThemeVersionsOutput { + s.ThemeVersionSummaryList = v + return s } -type ListDashboardVersionsInput struct { +type ListThemesInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the dashboard that you're listing - // versions for. + // The ID of the AWS account that contains the themes that you're listing. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the dashboard. - // - // DashboardId is a required field - DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` - // The maximum number of results to be returned per request. MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` // The token for the next set of results, or null if there are no more results. NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + + // The type of themes that you want to list. Valid options include the following: + // + // * ALL (default)- Display all existing themes. + // + // * CUSTOM - Display only the themes created by people using Amazon QuickSight. + // + // * QUICKSIGHT - Display only the starting themes defined by QuickSight. + Type *string `location:"querystring" locationName:"type" type:"string" enum:"ThemeType"` } // String returns the string representation -func (s ListDashboardVersionsInput) String() string { +func (s ListThemesInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDashboardVersionsInput) GoString() string { +func (s ListThemesInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListDashboardVersionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListDashboardVersionsInput"} +func (s *ListThemesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListThemesInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DashboardId == nil { - invalidParams.Add(request.NewErrParamRequired("DashboardId")) - } - if s.DashboardId != nil && len(*s.DashboardId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) - } if s.MaxResults != nil && *s.MaxResults < 1 { invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } @@ -15511,34 +22255,31 @@ func (s *ListDashboardVersionsInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListDashboardVersionsInput) SetAwsAccountId(v string) *ListDashboardVersionsInput { +func (s *ListThemesInput) SetAwsAccountId(v string) *ListThemesInput { s.AwsAccountId = &v return s } -// SetDashboardId sets the DashboardId field's value. -func (s *ListDashboardVersionsInput) SetDashboardId(v string) *ListDashboardVersionsInput { - s.DashboardId = &v - return s -} - // SetMaxResults sets the MaxResults field's value. -func (s *ListDashboardVersionsInput) SetMaxResults(v int64) *ListDashboardVersionsInput { +func (s *ListThemesInput) SetMaxResults(v int64) *ListThemesInput { s.MaxResults = &v return s } // SetNextToken sets the NextToken field's value. -func (s *ListDashboardVersionsInput) SetNextToken(v string) *ListDashboardVersionsInput { +func (s *ListThemesInput) SetNextToken(v string) *ListThemesInput { s.NextToken = &v return s } -type ListDashboardVersionsOutput struct { - _ struct{} `type:"structure"` +// SetType sets the Type field's value. +func (s *ListThemesInput) SetType(v string) *ListThemesInput { + s.Type = &v + return s +} - // A structure that contains information about each version of the dashboard. - DashboardVersionSummaryList []*DashboardVersionSummary `type:"list"` +type ListThemesOutput struct { + _ struct{} `type:"structure"` // The token for the next set of results, or null if there are no more results. NextToken *string `type:"string"` @@ -15548,70 +22289,84 @@ type ListDashboardVersionsOutput struct { // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // Information about the themes in the list. + ThemeSummaryList []*ThemeSummary `type:"list"` } // String returns the string representation -func (s ListDashboardVersionsOutput) String() string { +func (s ListThemesOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDashboardVersionsOutput) GoString() string { +func (s ListThemesOutput) GoString() string { return s.String() } -// SetDashboardVersionSummaryList sets the DashboardVersionSummaryList field's value. -func (s *ListDashboardVersionsOutput) SetDashboardVersionSummaryList(v []*DashboardVersionSummary) *ListDashboardVersionsOutput { - s.DashboardVersionSummaryList = v - return s -} - // SetNextToken sets the NextToken field's value. -func (s *ListDashboardVersionsOutput) SetNextToken(v string) *ListDashboardVersionsOutput { +func (s *ListThemesOutput) SetNextToken(v string) *ListThemesOutput { s.NextToken = &v return s } // SetRequestId sets the RequestId field's value. -func (s *ListDashboardVersionsOutput) SetRequestId(v string) *ListDashboardVersionsOutput { +func (s *ListThemesOutput) SetRequestId(v string) *ListThemesOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *ListDashboardVersionsOutput) SetStatus(v int64) *ListDashboardVersionsOutput { +func (s *ListThemesOutput) SetStatus(v int64) *ListThemesOutput { s.Status = &v return s } -type ListDashboardsInput struct { +// SetThemeSummaryList sets the ThemeSummaryList field's value. +func (s *ListThemesOutput) SetThemeSummaryList(v []*ThemeSummary) *ListThemesOutput { + s.ThemeSummaryList = v + return s +} + +type ListUserGroupsInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the dashboards that you're listing. + // The AWS account ID that the user is in. Currently, you use the ID for the + // AWS account that contains your Amazon QuickSight account. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The maximum number of results to be returned per request. + // The maximum number of results to return from this request. MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` - // The token for the next set of results, or null if there are no more results. + // The namespace. Currently, you should set this to default. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + + // A pagination token that can be used in a subsequent request. NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + + // The Amazon QuickSight user name that you want to list group memberships for. + // + // UserName is a required field + UserName *string `location:"uri" locationName:"UserName" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s ListDashboardsInput) String() string { +func (s ListUserGroupsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDashboardsInput) GoString() string { +func (s ListUserGroupsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListDashboardsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListDashboardsInput"} +func (s *ListUserGroupsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListUserGroupsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } @@ -15621,6 +22376,18 @@ func (s *ListDashboardsInput) Validate() error { if s.MaxResults != nil && *s.MaxResults < 1 { invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.UserName == nil { + invalidParams.Add(request.NewErrParamRequired("UserName")) + } + if s.UserName != nil && len(*s.UserName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -15629,31 +22396,42 @@ func (s *ListDashboardsInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListDashboardsInput) SetAwsAccountId(v string) *ListDashboardsInput { +func (s *ListUserGroupsInput) SetAwsAccountId(v string) *ListUserGroupsInput { s.AwsAccountId = &v return s } // SetMaxResults sets the MaxResults field's value. -func (s *ListDashboardsInput) SetMaxResults(v int64) *ListDashboardsInput { +func (s *ListUserGroupsInput) SetMaxResults(v int64) *ListUserGroupsInput { s.MaxResults = &v return s } +// SetNamespace sets the Namespace field's value. +func (s *ListUserGroupsInput) SetNamespace(v string) *ListUserGroupsInput { + s.Namespace = &v + return s +} + // SetNextToken sets the NextToken field's value. -func (s *ListDashboardsInput) SetNextToken(v string) *ListDashboardsInput { +func (s *ListUserGroupsInput) SetNextToken(v string) *ListUserGroupsInput { s.NextToken = &v return s } -type ListDashboardsOutput struct { +// SetUserName sets the UserName field's value. +func (s *ListUserGroupsInput) SetUserName(v string) *ListUserGroupsInput { + s.UserName = &v + return s +} + +type ListUserGroupsOutput struct { _ struct{} `type:"structure"` - // A structure that contains all of the dashboards shared with the user. This - // structure provides basic information about the dashboards. - DashboardSummaryList []*DashboardSummary `type:"list"` + // The list of groups the user is a member of. + GroupList []*Group `type:"list"` - // The token for the next set of results, or null if there are no more results. + // A pagination token that can be used in a subsequent request. NextToken *string `type:"string"` // The AWS request ID for this operation. @@ -15664,67 +22442,73 @@ type ListDashboardsOutput struct { } // String returns the string representation -func (s ListDashboardsOutput) String() string { +func (s ListUserGroupsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDashboardsOutput) GoString() string { +func (s ListUserGroupsOutput) GoString() string { return s.String() } -// SetDashboardSummaryList sets the DashboardSummaryList field's value. -func (s *ListDashboardsOutput) SetDashboardSummaryList(v []*DashboardSummary) *ListDashboardsOutput { - s.DashboardSummaryList = v +// SetGroupList sets the GroupList field's value. +func (s *ListUserGroupsOutput) SetGroupList(v []*Group) *ListUserGroupsOutput { + s.GroupList = v return s } // SetNextToken sets the NextToken field's value. -func (s *ListDashboardsOutput) SetNextToken(v string) *ListDashboardsOutput { +func (s *ListUserGroupsOutput) SetNextToken(v string) *ListUserGroupsOutput { s.NextToken = &v return s } // SetRequestId sets the RequestId field's value. -func (s *ListDashboardsOutput) SetRequestId(v string) *ListDashboardsOutput { +func (s *ListUserGroupsOutput) SetRequestId(v string) *ListUserGroupsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *ListDashboardsOutput) SetStatus(v int64) *ListDashboardsOutput { +func (s *ListUserGroupsOutput) SetStatus(v int64) *ListUserGroupsOutput { s.Status = &v return s } -type ListDataSetsInput struct { +type ListUsersInput struct { _ struct{} `type:"structure"` - // The AWS account ID. + // The ID for the AWS account that the user is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The maximum number of results to be returned per request. + // The maximum number of results to return from this request. MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` - // The token for the next set of results, or null if there are no more results. + // The namespace. Currently, you should set this to default. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + + // A pagination token that can be used in a subsequent request. NextToken *string `location:"querystring" locationName:"next-token" type:"string"` } // String returns the string representation -func (s ListDataSetsInput) String() string { +func (s ListUsersInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDataSetsInput) GoString() string { +func (s ListUsersInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListDataSetsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListDataSetsInput"} +func (s *ListUsersInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListUsersInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } @@ -15734,6 +22518,12 @@ func (s *ListDataSetsInput) Validate() error { if s.MaxResults != nil && *s.MaxResults < 1 { invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -15742,30 +22532,33 @@ func (s *ListDataSetsInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListDataSetsInput) SetAwsAccountId(v string) *ListDataSetsInput { +func (s *ListUsersInput) SetAwsAccountId(v string) *ListUsersInput { s.AwsAccountId = &v return s } // SetMaxResults sets the MaxResults field's value. -func (s *ListDataSetsInput) SetMaxResults(v int64) *ListDataSetsInput { +func (s *ListUsersInput) SetMaxResults(v int64) *ListUsersInput { s.MaxResults = &v return s } +// SetNamespace sets the Namespace field's value. +func (s *ListUsersInput) SetNamespace(v string) *ListUsersInput { + s.Namespace = &v + return s +} + // SetNextToken sets the NextToken field's value. -func (s *ListDataSetsInput) SetNextToken(v string) *ListDataSetsInput { +func (s *ListUsersInput) SetNextToken(v string) *ListUsersInput { s.NextToken = &v return s } -type ListDataSetsOutput struct { +type ListUsersOutput struct { _ struct{} `type:"structure"` - // The list of dataset summaries. - DataSetSummaries []*DataSetSummary `type:"list"` - - // The token for the next set of results, or null if there are no more results. + // A pagination token that can be used in a subsequent request. NextToken *string `type:"string"` // The AWS request ID for this operation. @@ -15773,78 +22566,105 @@ type ListDataSetsOutput struct { // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // The list of users. + UserList []*User `type:"list"` } // String returns the string representation -func (s ListDataSetsOutput) String() string { +func (s ListUsersOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDataSetsOutput) GoString() string { +func (s ListUsersOutput) GoString() string { return s.String() } -// SetDataSetSummaries sets the DataSetSummaries field's value. -func (s *ListDataSetsOutput) SetDataSetSummaries(v []*DataSetSummary) *ListDataSetsOutput { - s.DataSetSummaries = v - return s -} - // SetNextToken sets the NextToken field's value. -func (s *ListDataSetsOutput) SetNextToken(v string) *ListDataSetsOutput { +func (s *ListUsersOutput) SetNextToken(v string) *ListUsersOutput { s.NextToken = &v return s } // SetRequestId sets the RequestId field's value. -func (s *ListDataSetsOutput) SetRequestId(v string) *ListDataSetsOutput { +func (s *ListUsersOutput) SetRequestId(v string) *ListUsersOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *ListDataSetsOutput) SetStatus(v int64) *ListDataSetsOutput { +func (s *ListUsersOutput) SetStatus(v int64) *ListUsersOutput { s.Status = &v return s } -type ListDataSourcesInput struct { +// SetUserList sets the UserList field's value. +func (s *ListUsersOutput) SetUserList(v []*User) *ListUsersOutput { + s.UserList = v + return s +} + +// A logical table is a unit that joins and that data transformations operate +// on. A logical table has a source, which can be either a physical table or +// result of a join. When a logical table points to a physical table, the logical +// table acts as a mutable copy of that physical table through transform operations. +type LogicalTable struct { _ struct{} `type:"structure"` - // The AWS account ID. + // A display name for the logical table. // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // Alias is a required field + Alias *string `min:"1" type:"string" required:"true"` - // The maximum number of results to be returned per request. - MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + // Transform operations that act on this logical table. + DataTransforms []*TransformOperation `min:"1" type:"list"` - // The token for the next set of results, or null if there are no more results. - NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + // Source of this logical table. + // + // Source is a required field + Source *LogicalTableSource `type:"structure" required:"true"` } // String returns the string representation -func (s ListDataSourcesInput) String() string { +func (s LogicalTable) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDataSourcesInput) GoString() string { +func (s LogicalTable) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListDataSourcesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListDataSourcesInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) +func (s *LogicalTable) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LogicalTable"} + if s.Alias == nil { + invalidParams.Add(request.NewErrParamRequired("Alias")) } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + if s.Alias != nil && len(*s.Alias) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Alias", 1)) } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + if s.DataTransforms != nil && len(s.DataTransforms) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataTransforms", 1)) + } + if s.Source == nil { + invalidParams.Add(request.NewErrParamRequired("Source")) + } + if s.DataTransforms != nil { + for i, v := range s.DataTransforms { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DataTransforms", i), err.(request.ErrInvalidParams)) + } + } + } + if s.Source != nil { + if err := s.Source.Validate(); err != nil { + invalidParams.AddNested("Source", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -15853,133 +22673,115 @@ func (s *ListDataSourcesInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListDataSourcesInput) SetAwsAccountId(v string) *ListDataSourcesInput { - s.AwsAccountId = &v +// SetAlias sets the Alias field's value. +func (s *LogicalTable) SetAlias(v string) *LogicalTable { + s.Alias = &v return s } -// SetMaxResults sets the MaxResults field's value. -func (s *ListDataSourcesInput) SetMaxResults(v int64) *ListDataSourcesInput { - s.MaxResults = &v +// SetDataTransforms sets the DataTransforms field's value. +func (s *LogicalTable) SetDataTransforms(v []*TransformOperation) *LogicalTable { + s.DataTransforms = v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListDataSourcesInput) SetNextToken(v string) *ListDataSourcesInput { - s.NextToken = &v +// SetSource sets the Source field's value. +func (s *LogicalTable) SetSource(v *LogicalTableSource) *LogicalTable { + s.Source = v return s -} - -type ListDataSourcesOutput struct { - _ struct{} `type:"structure"` - - // A list of data sources. - DataSources []*DataSource `type:"list"` +} - // The token for the next set of results, or null if there are no more results. - NextToken *string `type:"string"` +// Information about the source of a logical table. This is a variant type structure. +// For this structure to be valid, only one of the attributes can be non-null. +type LogicalTableSource struct { + _ struct{} `type:"structure"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // Specifies the result of a join of two logical tables. + JoinInstruction *JoinInstruction `type:"structure"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // Physical table ID. + PhysicalTableId *string `min:"1" type:"string"` } // String returns the string representation -func (s ListDataSourcesOutput) String() string { +func (s LogicalTableSource) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListDataSourcesOutput) GoString() string { +func (s LogicalTableSource) GoString() string { return s.String() } -// SetDataSources sets the DataSources field's value. -func (s *ListDataSourcesOutput) SetDataSources(v []*DataSource) *ListDataSourcesOutput { - s.DataSources = v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *LogicalTableSource) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "LogicalTableSource"} + if s.PhysicalTableId != nil && len(*s.PhysicalTableId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PhysicalTableId", 1)) + } + if s.JoinInstruction != nil { + if err := s.JoinInstruction.Validate(); err != nil { + invalidParams.AddNested("JoinInstruction", err.(request.ErrInvalidParams)) + } + } -// SetNextToken sets the NextToken field's value. -func (s *ListDataSourcesOutput) SetNextToken(v string) *ListDataSourcesOutput { - s.NextToken = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetRequestId sets the RequestId field's value. -func (s *ListDataSourcesOutput) SetRequestId(v string) *ListDataSourcesOutput { - s.RequestId = &v +// SetJoinInstruction sets the JoinInstruction field's value. +func (s *LogicalTableSource) SetJoinInstruction(v *JoinInstruction) *LogicalTableSource { + s.JoinInstruction = v return s } -// SetStatus sets the Status field's value. -func (s *ListDataSourcesOutput) SetStatus(v int64) *ListDataSourcesOutput { - s.Status = &v +// SetPhysicalTableId sets the PhysicalTableId field's value. +func (s *LogicalTableSource) SetPhysicalTableId(v string) *LogicalTableSource { + s.PhysicalTableId = &v return s } -type ListGroupMembershipsInput struct { +// Amazon S3 manifest file location. +type ManifestFileLocation struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the group is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // The name of the group that you want to see a membership list of. + // Amazon S3 bucket. // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` - - // The maximum number of results to return from this request. - MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + // Bucket is a required field + Bucket *string `min:"1" type:"string" required:"true"` - // The namespace. Currently, you should set this to default. + // Amazon S3 key that identifies an object. // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` - - // A pagination token that can be used in a subsequent request. - NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s ListGroupMembershipsInput) String() string { +func (s ManifestFileLocation) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListGroupMembershipsInput) GoString() string { +func (s ManifestFileLocation) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListGroupMembershipsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListGroupMembershipsInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) - } - if s.GroupName != nil && len(*s.GroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) +func (s *ManifestFileLocation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ManifestFileLocation"} + if s.Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("Bucket")) } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + if s.Bucket != nil && len(*s.Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } if invalidParams.Len() > 0 { @@ -15988,134 +22790,168 @@ func (s *ListGroupMembershipsInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListGroupMembershipsInput) SetAwsAccountId(v string) *ListGroupMembershipsInput { - s.AwsAccountId = &v +// SetBucket sets the Bucket field's value. +func (s *ManifestFileLocation) SetBucket(v string) *ManifestFileLocation { + s.Bucket = &v return s } -// SetGroupName sets the GroupName field's value. -func (s *ListGroupMembershipsInput) SetGroupName(v string) *ListGroupMembershipsInput { - s.GroupName = &v +// SetKey sets the Key field's value. +func (s *ManifestFileLocation) SetKey(v string) *ManifestFileLocation { + s.Key = &v return s } -// SetMaxResults sets the MaxResults field's value. -func (s *ListGroupMembershipsInput) SetMaxResults(v int64) *ListGroupMembershipsInput { - s.MaxResults = &v - return s +// The display options for margins around the outside edge of sheets. +type MarginStyle struct { + _ struct{} `type:"structure"` + + // This Boolean value controls whether to display sheet margins. + Show *bool `type:"boolean"` } -// SetNamespace sets the Namespace field's value. -func (s *ListGroupMembershipsInput) SetNamespace(v string) *ListGroupMembershipsInput { - s.Namespace = &v - return s +// String returns the string representation +func (s MarginStyle) String() string { + return awsutil.Prettify(s) } -// SetNextToken sets the NextToken field's value. -func (s *ListGroupMembershipsInput) SetNextToken(v string) *ListGroupMembershipsInput { - s.NextToken = &v +// GoString returns the string representation +func (s MarginStyle) GoString() string { + return s.String() +} + +// SetShow sets the Show field's value. +func (s *MarginStyle) SetShow(v bool) *MarginStyle { + s.Show = &v return s } -type ListGroupMembershipsOutput struct { +// MariaDB parameters. +type MariaDbParameters struct { _ struct{} `type:"structure"` - // The list of the members of the group. - GroupMemberList []*GroupMember `type:"list"` - - // A pagination token that can be used in a subsequent request. - NextToken *string `type:"string"` + // Database. + // + // Database is a required field + Database *string `min:"1" type:"string" required:"true"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // Host. + // + // Host is a required field + Host *string `min:"1" type:"string" required:"true"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // Port. + // + // Port is a required field + Port *int64 `min:"1" type:"integer" required:"true"` } // String returns the string representation -func (s ListGroupMembershipsOutput) String() string { +func (s MariaDbParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListGroupMembershipsOutput) GoString() string { +func (s MariaDbParameters) GoString() string { return s.String() } -// SetGroupMemberList sets the GroupMemberList field's value. -func (s *ListGroupMembershipsOutput) SetGroupMemberList(v []*GroupMember) *ListGroupMembershipsOutput { - s.GroupMemberList = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *MariaDbParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "MariaDbParameters"} + if s.Database == nil { + invalidParams.Add(request.NewErrParamRequired("Database")) + } + if s.Database != nil && len(*s.Database) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Database", 1)) + } + if s.Host == nil { + invalidParams.Add(request.NewErrParamRequired("Host")) + } + if s.Host != nil && len(*s.Host) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Host", 1)) + } + if s.Port == nil { + invalidParams.Add(request.NewErrParamRequired("Port")) + } + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetNextToken sets the NextToken field's value. -func (s *ListGroupMembershipsOutput) SetNextToken(v string) *ListGroupMembershipsOutput { - s.NextToken = &v +// SetDatabase sets the Database field's value. +func (s *MariaDbParameters) SetDatabase(v string) *MariaDbParameters { + s.Database = &v return s } -// SetRequestId sets the RequestId field's value. -func (s *ListGroupMembershipsOutput) SetRequestId(v string) *ListGroupMembershipsOutput { - s.RequestId = &v +// SetHost sets the Host field's value. +func (s *MariaDbParameters) SetHost(v string) *MariaDbParameters { + s.Host = &v return s } -// SetStatus sets the Status field's value. -func (s *ListGroupMembershipsOutput) SetStatus(v int64) *ListGroupMembershipsOutput { - s.Status = &v +// SetPort sets the Port field's value. +func (s *MariaDbParameters) SetPort(v int64) *MariaDbParameters { + s.Port = &v return s } -type ListGroupsInput struct { +// MySQL parameters. +type MySqlParameters struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the group is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. + // Database. // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // The maximum number of results to return. - MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + // Database is a required field + Database *string `min:"1" type:"string" required:"true"` - // The namespace. Currently, you should set this to default. + // Host. // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // Host is a required field + Host *string `min:"1" type:"string" required:"true"` - // A pagination token that can be used in a subsequent request. - NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + // Port. + // + // Port is a required field + Port *int64 `min:"1" type:"integer" required:"true"` } // String returns the string representation -func (s ListGroupsInput) String() string { +func (s MySqlParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListGroupsInput) GoString() string { +func (s MySqlParameters) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListGroupsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListGroupsInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) +// Validate inspects the fields of the type to determine if they are valid. +func (s *MySqlParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "MySqlParameters"} + if s.Database == nil { + invalidParams.Add(request.NewErrParamRequired("Database")) } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + if s.Database != nil && len(*s.Database) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Database", 1)) } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + if s.Host == nil { + invalidParams.Add(request.NewErrParamRequired("Host")) } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.Host != nil && len(*s.Host) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Host", 1)) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.Port == nil { + invalidParams.Add(request.NewErrParamRequired("Port")) + } + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) } if invalidParams.Len() > 0 { @@ -16124,276 +22960,303 @@ func (s *ListGroupsInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListGroupsInput) SetAwsAccountId(v string) *ListGroupsInput { - s.AwsAccountId = &v - return s -} - -// SetMaxResults sets the MaxResults field's value. -func (s *ListGroupsInput) SetMaxResults(v int64) *ListGroupsInput { - s.MaxResults = &v +// SetDatabase sets the Database field's value. +func (s *MySqlParameters) SetDatabase(v string) *MySqlParameters { + s.Database = &v return s } -// SetNamespace sets the Namespace field's value. -func (s *ListGroupsInput) SetNamespace(v string) *ListGroupsInput { - s.Namespace = &v +// SetHost sets the Host field's value. +func (s *MySqlParameters) SetHost(v string) *MySqlParameters { + s.Host = &v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListGroupsInput) SetNextToken(v string) *ListGroupsInput { - s.NextToken = &v +// SetPort sets the Port field's value. +func (s *MySqlParameters) SetPort(v int64) *MySqlParameters { + s.Port = &v return s } -type ListGroupsOutput struct { +// Errors that occur during namespace creation. +type NamespaceError struct { _ struct{} `type:"structure"` - // The list of the groups. - GroupList []*Group `type:"list"` - - // A pagination token that can be used in a subsequent request. - NextToken *string `type:"string"` - - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // The message for the error. + Message *string `type:"string"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // The error type. + Type *string `type:"string" enum:"NamespaceErrorType"` } // String returns the string representation -func (s ListGroupsOutput) String() string { +func (s NamespaceError) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListGroupsOutput) GoString() string { +func (s NamespaceError) GoString() string { return s.String() } -// SetGroupList sets the GroupList field's value. -func (s *ListGroupsOutput) SetGroupList(v []*Group) *ListGroupsOutput { - s.GroupList = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListGroupsOutput) SetNextToken(v string) *ListGroupsOutput { - s.NextToken = &v - return s -} - -// SetRequestId sets the RequestId field's value. -func (s *ListGroupsOutput) SetRequestId(v string) *ListGroupsOutput { - s.RequestId = &v +// SetMessage sets the Message field's value. +func (s *NamespaceError) SetMessage(v string) *NamespaceError { + s.Message = &v return s } -// SetStatus sets the Status field's value. -func (s *ListGroupsOutput) SetStatus(v int64) *ListGroupsOutput { - s.Status = &v +// SetType sets the Type field's value. +func (s *NamespaceError) SetType(v string) *NamespaceError { + s.Type = &v return s } -type ListIAMPolicyAssignmentsForUserInput struct { +// The error type. +type NamespaceInfoV2 struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the assignments. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // The namespace ARN. + Arn *string `type:"string"` - // The maximum number of results to be returned per request. - MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + // The namespace AWS Region. + CapacityRegion *string `type:"string"` - // The namespace of the assignment. - // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // The creation status of a namespace that is not yet completely created. + CreationStatus *string `type:"string" enum:"NamespaceStatus"` - // The token for the next set of results, or null if there are no more results. - NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + // The identity store used for the namespace. + IdentityStore *string `type:"string" enum:"IdentityStore"` - // The name of the user. - // - // UserName is a required field - UserName *string `location:"uri" locationName:"UserName" min:"1" type:"string" required:"true"` + // The name of the error. + Name *string `type:"string"` + + // An error that occured when the namespace was created. + NamespaceError *NamespaceError `type:"structure"` } // String returns the string representation -func (s ListIAMPolicyAssignmentsForUserInput) String() string { +func (s NamespaceInfoV2) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListIAMPolicyAssignmentsForUserInput) GoString() string { +func (s NamespaceInfoV2) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListIAMPolicyAssignmentsForUserInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListIAMPolicyAssignmentsForUserInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) - } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) - } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) - } - if s.UserName == nil { - invalidParams.Add(request.NewErrParamRequired("UserName")) - } - if s.UserName != nil && len(*s.UserName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) - } +// SetArn sets the Arn field's value. +func (s *NamespaceInfoV2) SetArn(v string) *NamespaceInfoV2 { + s.Arn = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCapacityRegion sets the CapacityRegion field's value. +func (s *NamespaceInfoV2) SetCapacityRegion(v string) *NamespaceInfoV2 { + s.CapacityRegion = &v + return s } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListIAMPolicyAssignmentsForUserInput) SetAwsAccountId(v string) *ListIAMPolicyAssignmentsForUserInput { - s.AwsAccountId = &v +// SetCreationStatus sets the CreationStatus field's value. +func (s *NamespaceInfoV2) SetCreationStatus(v string) *NamespaceInfoV2 { + s.CreationStatus = &v return s } -// SetMaxResults sets the MaxResults field's value. -func (s *ListIAMPolicyAssignmentsForUserInput) SetMaxResults(v int64) *ListIAMPolicyAssignmentsForUserInput { - s.MaxResults = &v +// SetIdentityStore sets the IdentityStore field's value. +func (s *NamespaceInfoV2) SetIdentityStore(v string) *NamespaceInfoV2 { + s.IdentityStore = &v return s } -// SetNamespace sets the Namespace field's value. -func (s *ListIAMPolicyAssignmentsForUserInput) SetNamespace(v string) *ListIAMPolicyAssignmentsForUserInput { - s.Namespace = &v +// SetName sets the Name field's value. +func (s *NamespaceInfoV2) SetName(v string) *NamespaceInfoV2 { + s.Name = &v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListIAMPolicyAssignmentsForUserInput) SetNextToken(v string) *ListIAMPolicyAssignmentsForUserInput { - s.NextToken = &v +// SetNamespaceError sets the NamespaceError field's value. +func (s *NamespaceInfoV2) SetNamespaceError(v *NamespaceError) *NamespaceInfoV2 { + s.NamespaceError = v return s } -// SetUserName sets the UserName field's value. -func (s *ListIAMPolicyAssignmentsForUserInput) SetUserName(v string) *ListIAMPolicyAssignmentsForUserInput { - s.UserName = &v +// Output column. +type OutputColumn struct { + _ struct{} `type:"structure"` + + // A display name for the dataset. + Name *string `min:"1" type:"string"` + + // Type. + Type *string `type:"string" enum:"ColumnDataType"` +} + +// String returns the string representation +func (s OutputColumn) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OutputColumn) GoString() string { + return s.String() +} + +// SetName sets the Name field's value. +func (s *OutputColumn) SetName(v string) *OutputColumn { + s.Name = &v return s } -type ListIAMPolicyAssignmentsForUserOutput struct { +// SetType sets the Type field's value. +func (s *OutputColumn) SetType(v string) *OutputColumn { + s.Type = &v + return s +} + +// Parameters. +type Parameters struct { _ struct{} `type:"structure"` - // The active assignments for this user. - ActiveAssignments []*ActiveIAMPolicyAssignment `type:"list"` + // DateTime parameters. + DateTimeParameters []*DateTimeParameter `type:"list"` - // The token for the next set of results, or null if there are no more results. - NextToken *string `type:"string"` + // Decimal parameters. + DecimalParameters []*DecimalParameter `type:"list"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // Integer parameters. + IntegerParameters []*IntegerParameter `type:"list"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // String parameters. + StringParameters []*StringParameter `type:"list"` } // String returns the string representation -func (s ListIAMPolicyAssignmentsForUserOutput) String() string { +func (s Parameters) String() string { return awsutil.Prettify(s) } -// GoString returns the string representation -func (s ListIAMPolicyAssignmentsForUserOutput) GoString() string { - return s.String() +// GoString returns the string representation +func (s Parameters) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Parameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Parameters"} + if s.DateTimeParameters != nil { + for i, v := range s.DateTimeParameters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DateTimeParameters", i), err.(request.ErrInvalidParams)) + } + } + } + if s.DecimalParameters != nil { + for i, v := range s.DecimalParameters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DecimalParameters", i), err.(request.ErrInvalidParams)) + } + } + } + if s.IntegerParameters != nil { + for i, v := range s.IntegerParameters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "IntegerParameters", i), err.(request.ErrInvalidParams)) + } + } + } + if s.StringParameters != nil { + for i, v := range s.StringParameters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "StringParameters", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetActiveAssignments sets the ActiveAssignments field's value. -func (s *ListIAMPolicyAssignmentsForUserOutput) SetActiveAssignments(v []*ActiveIAMPolicyAssignment) *ListIAMPolicyAssignmentsForUserOutput { - s.ActiveAssignments = v +// SetDateTimeParameters sets the DateTimeParameters field's value. +func (s *Parameters) SetDateTimeParameters(v []*DateTimeParameter) *Parameters { + s.DateTimeParameters = v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListIAMPolicyAssignmentsForUserOutput) SetNextToken(v string) *ListIAMPolicyAssignmentsForUserOutput { - s.NextToken = &v +// SetDecimalParameters sets the DecimalParameters field's value. +func (s *Parameters) SetDecimalParameters(v []*DecimalParameter) *Parameters { + s.DecimalParameters = v return s } -// SetRequestId sets the RequestId field's value. -func (s *ListIAMPolicyAssignmentsForUserOutput) SetRequestId(v string) *ListIAMPolicyAssignmentsForUserOutput { - s.RequestId = &v +// SetIntegerParameters sets the IntegerParameters field's value. +func (s *Parameters) SetIntegerParameters(v []*IntegerParameter) *Parameters { + s.IntegerParameters = v return s } -// SetStatus sets the Status field's value. -func (s *ListIAMPolicyAssignmentsForUserOutput) SetStatus(v int64) *ListIAMPolicyAssignmentsForUserOutput { - s.Status = &v +// SetStringParameters sets the StringParameters field's value. +func (s *Parameters) SetStringParameters(v []*StringParameter) *Parameters { + s.StringParameters = v return s } -type ListIAMPolicyAssignmentsInput struct { +// A view of a data source that contains information about the shape of the +// data in the underlying source. This is a variant type structure. For this +// structure to be valid, only one of the attributes can be non-null. +type PhysicalTable struct { _ struct{} `type:"structure"` - // The status of the assignments. - AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` - - // The ID of the AWS account that contains these IAM policy assignments. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // The maximum number of results to be returned per request. - MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + // A physical table type built from the results of the custom SQL query. + CustomSql *CustomSql `type:"structure"` - // The namespace for the assignments. - // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // A physical table type for relational data sources. + RelationalTable *RelationalTable `type:"structure"` - // The token for the next set of results, or null if there are no more results. - NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + // A physical table type for as S3 data source. + S3Source *S3Source `type:"structure"` } // String returns the string representation -func (s ListIAMPolicyAssignmentsInput) String() string { +func (s PhysicalTable) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListIAMPolicyAssignmentsInput) GoString() string { +func (s PhysicalTable) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListIAMPolicyAssignmentsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListIAMPolicyAssignmentsInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) +func (s *PhysicalTable) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PhysicalTable"} + if s.CustomSql != nil { + if err := s.CustomSql.Validate(); err != nil { + invalidParams.AddNested("CustomSql", err.(request.ErrInvalidParams)) + } } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.RelationalTable != nil { + if err := s.RelationalTable.Validate(); err != nil { + invalidParams.AddNested("RelationalTable", err.(request.ErrInvalidParams)) + } } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.S3Source != nil { + if err := s.S3Source.Validate(); err != nil { + invalidParams.AddNested("S3Source", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -16402,243 +23265,261 @@ func (s *ListIAMPolicyAssignmentsInput) Validate() error { return nil } -// SetAssignmentStatus sets the AssignmentStatus field's value. -func (s *ListIAMPolicyAssignmentsInput) SetAssignmentStatus(v string) *ListIAMPolicyAssignmentsInput { - s.AssignmentStatus = &v - return s -} - -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListIAMPolicyAssignmentsInput) SetAwsAccountId(v string) *ListIAMPolicyAssignmentsInput { - s.AwsAccountId = &v - return s -} - -// SetMaxResults sets the MaxResults field's value. -func (s *ListIAMPolicyAssignmentsInput) SetMaxResults(v int64) *ListIAMPolicyAssignmentsInput { - s.MaxResults = &v +// SetCustomSql sets the CustomSql field's value. +func (s *PhysicalTable) SetCustomSql(v *CustomSql) *PhysicalTable { + s.CustomSql = v return s } -// SetNamespace sets the Namespace field's value. -func (s *ListIAMPolicyAssignmentsInput) SetNamespace(v string) *ListIAMPolicyAssignmentsInput { - s.Namespace = &v +// SetRelationalTable sets the RelationalTable field's value. +func (s *PhysicalTable) SetRelationalTable(v *RelationalTable) *PhysicalTable { + s.RelationalTable = v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListIAMPolicyAssignmentsInput) SetNextToken(v string) *ListIAMPolicyAssignmentsInput { - s.NextToken = &v +// SetS3Source sets the S3Source field's value. +func (s *PhysicalTable) SetS3Source(v *S3Source) *PhysicalTable { + s.S3Source = v return s } -type ListIAMPolicyAssignmentsOutput struct { +// PostgreSQL parameters. +type PostgreSqlParameters struct { _ struct{} `type:"structure"` - // Information describing the IAM policy assignments. - IAMPolicyAssignments []*IAMPolicyAssignmentSummary `type:"list"` - - // The token for the next set of results, or null if there are no more results. - NextToken *string `type:"string"` + // Database. + // + // Database is a required field + Database *string `min:"1" type:"string" required:"true"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // Host. + // + // Host is a required field + Host *string `min:"1" type:"string" required:"true"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // Port. + // + // Port is a required field + Port *int64 `min:"1" type:"integer" required:"true"` } // String returns the string representation -func (s ListIAMPolicyAssignmentsOutput) String() string { +func (s PostgreSqlParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListIAMPolicyAssignmentsOutput) GoString() string { +func (s PostgreSqlParameters) GoString() string { return s.String() } -// SetIAMPolicyAssignments sets the IAMPolicyAssignments field's value. -func (s *ListIAMPolicyAssignmentsOutput) SetIAMPolicyAssignments(v []*IAMPolicyAssignmentSummary) *ListIAMPolicyAssignmentsOutput { - s.IAMPolicyAssignments = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *PostgreSqlParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PostgreSqlParameters"} + if s.Database == nil { + invalidParams.Add(request.NewErrParamRequired("Database")) + } + if s.Database != nil && len(*s.Database) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Database", 1)) + } + if s.Host == nil { + invalidParams.Add(request.NewErrParamRequired("Host")) + } + if s.Host != nil && len(*s.Host) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Host", 1)) + } + if s.Port == nil { + invalidParams.Add(request.NewErrParamRequired("Port")) + } + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetNextToken sets the NextToken field's value. -func (s *ListIAMPolicyAssignmentsOutput) SetNextToken(v string) *ListIAMPolicyAssignmentsOutput { - s.NextToken = &v +// SetDatabase sets the Database field's value. +func (s *PostgreSqlParameters) SetDatabase(v string) *PostgreSqlParameters { + s.Database = &v return s } -// SetRequestId sets the RequestId field's value. -func (s *ListIAMPolicyAssignmentsOutput) SetRequestId(v string) *ListIAMPolicyAssignmentsOutput { - s.RequestId = &v +// SetHost sets the Host field's value. +func (s *PostgreSqlParameters) SetHost(v string) *PostgreSqlParameters { + s.Host = &v return s } -// SetStatus sets the Status field's value. -func (s *ListIAMPolicyAssignmentsOutput) SetStatus(v int64) *ListIAMPolicyAssignmentsOutput { - s.Status = &v +// SetPort sets the Port field's value. +func (s *PostgreSqlParameters) SetPort(v int64) *PostgreSqlParameters { + s.Port = &v return s } -type ListIngestionsInput struct { - _ struct{} `type:"structure"` - - // The AWS account ID. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // The ID of the dataset used in the ingestion. - // - // DataSetId is a required field - DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` +// One or more preconditions aren't met. +type PreconditionNotMetException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // The maximum number of results to be returned per request. - MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + Message_ *string `locationName:"Message" type:"string"` - // The token for the next set of results, or null if there are no more results. - NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + // The AWS request ID for this request. + RequestId *string `type:"string"` } // String returns the string representation -func (s ListIngestionsInput) String() string { +func (s PreconditionNotMetException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListIngestionsInput) GoString() string { +func (s PreconditionNotMetException) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListIngestionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListIngestionsInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.DataSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetId")) - } - if s.DataSetId != nil && len(*s.DataSetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) - } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) +func newErrorPreconditionNotMetException(v protocol.ResponseMetadata) error { + return &PreconditionNotMetException{ + RespMetadata: v, } +} - if invalidParams.Len() > 0 { - return invalidParams +// Code returns the exception type name. +func (s *PreconditionNotMetException) Code() string { + return "PreconditionNotMetException" +} + +// Message returns the exception's message. +func (s *PreconditionNotMetException) Message() string { + if s.Message_ != nil { + return *s.Message_ } - return nil + return "" } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListIngestionsInput) SetAwsAccountId(v string) *ListIngestionsInput { - s.AwsAccountId = &v - return s +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *PreconditionNotMetException) OrigErr() error { + return nil } -// SetDataSetId sets the DataSetId field's value. -func (s *ListIngestionsInput) SetDataSetId(v string) *ListIngestionsInput { - s.DataSetId = &v - return s +func (s *PreconditionNotMetException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) } -// SetMaxResults sets the MaxResults field's value. -func (s *ListIngestionsInput) SetMaxResults(v int64) *ListIngestionsInput { - s.MaxResults = &v - return s +// Status code returns the HTTP status code for the request's response error. +func (s *PreconditionNotMetException) StatusCode() int { + return s.RespMetadata.StatusCode } -// SetNextToken sets the NextToken field's value. -func (s *ListIngestionsInput) SetNextToken(v string) *ListIngestionsInput { - s.NextToken = &v - return s +// RequestID returns the service's response RequestID for request. +func (s *PreconditionNotMetException) RequestID() string { + return s.RespMetadata.RequestID } -type ListIngestionsOutput struct { +// Presto parameters. +type PrestoParameters struct { _ struct{} `type:"structure"` - // A list of the ingestions. - Ingestions []*Ingestion `type:"list"` - - // The token for the next set of results, or null if there are no more results. - NextToken *string `type:"string"` + // Catalog. + // + // Catalog is a required field + Catalog *string `type:"string" required:"true"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // Host. + // + // Host is a required field + Host *string `min:"1" type:"string" required:"true"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // Port. + // + // Port is a required field + Port *int64 `min:"1" type:"integer" required:"true"` } // String returns the string representation -func (s ListIngestionsOutput) String() string { +func (s PrestoParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListIngestionsOutput) GoString() string { +func (s PrestoParameters) GoString() string { return s.String() } -// SetIngestions sets the Ingestions field's value. -func (s *ListIngestionsOutput) SetIngestions(v []*Ingestion) *ListIngestionsOutput { - s.Ingestions = v - return s +// Validate inspects the fields of the type to determine if they are valid. +func (s *PrestoParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PrestoParameters"} + if s.Catalog == nil { + invalidParams.Add(request.NewErrParamRequired("Catalog")) + } + if s.Host == nil { + invalidParams.Add(request.NewErrParamRequired("Host")) + } + if s.Host != nil && len(*s.Host) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Host", 1)) + } + if s.Port == nil { + invalidParams.Add(request.NewErrParamRequired("Port")) + } + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetNextToken sets the NextToken field's value. -func (s *ListIngestionsOutput) SetNextToken(v string) *ListIngestionsOutput { - s.NextToken = &v +// SetCatalog sets the Catalog field's value. +func (s *PrestoParameters) SetCatalog(v string) *PrestoParameters { + s.Catalog = &v return s } -// SetRequestId sets the RequestId field's value. -func (s *ListIngestionsOutput) SetRequestId(v string) *ListIngestionsOutput { - s.RequestId = &v +// SetHost sets the Host field's value. +func (s *PrestoParameters) SetHost(v string) *PrestoParameters { + s.Host = &v return s } -// SetStatus sets the Status field's value. -func (s *ListIngestionsOutput) SetStatus(v int64) *ListIngestionsOutput { - s.Status = &v +// SetPort sets the Port field's value. +func (s *PrestoParameters) SetPort(v int64) *PrestoParameters { + s.Port = &v return s } -type ListTagsForResourceInput struct { +// A transform operation that projects columns. Operations that come after a +// projection can only refer to projected columns. +type ProjectOperation struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource that you want a list of tags - // for. + // Projected columns. // - // ResourceArn is a required field - ResourceArn *string `location:"uri" locationName:"ResourceArn" type:"string" required:"true"` + // ProjectedColumns is a required field + ProjectedColumns []*string `min:"1" type:"list" required:"true"` } // String returns the string representation -func (s ListTagsForResourceInput) String() string { +func (s ProjectOperation) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListTagsForResourceInput) GoString() string { +func (s ProjectOperation) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListTagsForResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) +func (s *ProjectOperation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ProjectOperation"} + if s.ProjectedColumns == nil { + invalidParams.Add(request.NewErrParamRequired("ProjectedColumns")) } - if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + if s.ProjectedColumns != nil && len(s.ProjectedColumns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ProjectedColumns", 1)) } if invalidParams.Len() > 0 { @@ -16647,102 +23528,89 @@ func (s *ListTagsForResourceInput) Validate() error { return nil } -// SetResourceArn sets the ResourceArn field's value. -func (s *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResourceInput { - s.ResourceArn = &v +// SetProjectedColumns sets the ProjectedColumns field's value. +func (s *ProjectOperation) SetProjectedColumns(v []*string) *ProjectOperation { + s.ProjectedColumns = v return s } -type ListTagsForResourceOutput struct { +// Information about a queued dataset SPICE ingestion. +type QueueInfo struct { _ struct{} `type:"structure"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` - - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // The ID of the ongoing ingestion. The queued ingestion is waiting for the + // ongoing ingestion to complete. + // + // QueuedIngestion is a required field + QueuedIngestion *string `type:"string" required:"true"` - // Contains a map of the key-value pairs for the resource tag or tags assigned - // to the resource. - Tags []*Tag `min:"1" type:"list"` + // The ID of the queued ingestion. + // + // WaitingOnIngestion is a required field + WaitingOnIngestion *string `type:"string" required:"true"` } // String returns the string representation -func (s ListTagsForResourceOutput) String() string { +func (s QueueInfo) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListTagsForResourceOutput) GoString() string { +func (s QueueInfo) GoString() string { return s.String() } -// SetRequestId sets the RequestId field's value. -func (s *ListTagsForResourceOutput) SetRequestId(v string) *ListTagsForResourceOutput { - s.RequestId = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *ListTagsForResourceOutput) SetStatus(v int64) *ListTagsForResourceOutput { - s.Status = &v +// SetQueuedIngestion sets the QueuedIngestion field's value. +func (s *QueueInfo) SetQueuedIngestion(v string) *QueueInfo { + s.QueuedIngestion = &v return s } -// SetTags sets the Tags field's value. -func (s *ListTagsForResourceOutput) SetTags(v []*Tag) *ListTagsForResourceOutput { - s.Tags = v +// SetWaitingOnIngestion sets the WaitingOnIngestion field's value. +func (s *QueueInfo) SetWaitingOnIngestion(v string) *QueueInfo { + s.WaitingOnIngestion = &v return s } -type ListTemplateAliasesInput struct { +// Amazon RDS parameters. +type RdsParameters struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the template aliases that you're - // listing. + // Database. // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // The maximum number of results to be returned per request. - MaxResults *int64 `location:"querystring" locationName:"max-result" min:"1" type:"integer"` - - // The token for the next set of results, or null if there are no more results. - NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + // Database is a required field + Database *string `min:"1" type:"string" required:"true"` - // The ID for the template. + // Instance ID. // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + // InstanceId is a required field + InstanceId *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s ListTemplateAliasesInput) String() string { +func (s RdsParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListTemplateAliasesInput) GoString() string { +func (s RdsParameters) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListTemplateAliasesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTemplateAliasesInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) +func (s *RdsParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RdsParameters"} + if s.Database == nil { + invalidParams.Add(request.NewErrParamRequired("Database")) } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + if s.Database != nil && len(*s.Database) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Database", 1)) } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) + if s.InstanceId == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceId")) } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + if s.InstanceId != nil && len(*s.InstanceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("InstanceId", 1)) } if invalidParams.Len() > 0 { @@ -16751,127 +23619,226 @@ func (s *ListTemplateAliasesInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListTemplateAliasesInput) SetAwsAccountId(v string) *ListTemplateAliasesInput { - s.AwsAccountId = &v - return s -} - -// SetMaxResults sets the MaxResults field's value. -func (s *ListTemplateAliasesInput) SetMaxResults(v int64) *ListTemplateAliasesInput { - s.MaxResults = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListTemplateAliasesInput) SetNextToken(v string) *ListTemplateAliasesInput { - s.NextToken = &v +// SetDatabase sets the Database field's value. +func (s *RdsParameters) SetDatabase(v string) *RdsParameters { + s.Database = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *ListTemplateAliasesInput) SetTemplateId(v string) *ListTemplateAliasesInput { - s.TemplateId = &v +// SetInstanceId sets the InstanceId field's value. +func (s *RdsParameters) SetInstanceId(v string) *RdsParameters { + s.InstanceId = &v return s } -type ListTemplateAliasesOutput struct { +// Amazon Redshift parameters. The ClusterId field can be blank if Host and +// Port are both set. The Host and Port fields can be blank if the ClusterId +// field is set. +type RedshiftParameters struct { _ struct{} `type:"structure"` - // The token for the next set of results, or null if there are no more results. - NextToken *string `type:"string"` + // Cluster ID. This field can be blank if the Host and Port are provided. + ClusterId *string `min:"1" type:"string"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // Database. + // + // Database is a required field + Database *string `min:"1" type:"string" required:"true"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // Host. This field can be blank if ClusterId is provided. + Host *string `min:"1" type:"string"` - // A structure containing the list of the template's aliases. - TemplateAliasList []*TemplateAlias `type:"list"` + // Port. This field can be blank if the ClusterId is provided. + Port *int64 `type:"integer"` } // String returns the string representation -func (s ListTemplateAliasesOutput) String() string { +func (s RedshiftParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListTemplateAliasesOutput) GoString() string { +func (s RedshiftParameters) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListTemplateAliasesOutput) SetNextToken(v string) *ListTemplateAliasesOutput { - s.NextToken = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *RedshiftParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RedshiftParameters"} + if s.ClusterId != nil && len(*s.ClusterId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClusterId", 1)) + } + if s.Database == nil { + invalidParams.Add(request.NewErrParamRequired("Database")) + } + if s.Database != nil && len(*s.Database) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Database", 1)) + } + if s.Host != nil && len(*s.Host) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Host", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClusterId sets the ClusterId field's value. +func (s *RedshiftParameters) SetClusterId(v string) *RedshiftParameters { + s.ClusterId = &v return s } -// SetRequestId sets the RequestId field's value. -func (s *ListTemplateAliasesOutput) SetRequestId(v string) *ListTemplateAliasesOutput { - s.RequestId = &v +// SetDatabase sets the Database field's value. +func (s *RedshiftParameters) SetDatabase(v string) *RedshiftParameters { + s.Database = &v return s } -// SetStatus sets the Status field's value. -func (s *ListTemplateAliasesOutput) SetStatus(v int64) *ListTemplateAliasesOutput { - s.Status = &v +// SetHost sets the Host field's value. +func (s *RedshiftParameters) SetHost(v string) *RedshiftParameters { + s.Host = &v return s } -// SetTemplateAliasList sets the TemplateAliasList field's value. -func (s *ListTemplateAliasesOutput) SetTemplateAliasList(v []*TemplateAlias) *ListTemplateAliasesOutput { - s.TemplateAliasList = v +// SetPort sets the Port field's value. +func (s *RedshiftParameters) SetPort(v int64) *RedshiftParameters { + s.Port = &v return s } -type ListTemplateVersionsInput struct { +type RegisterUserInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the templates that you're listing. + // The ID for the AWS account that the user is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The maximum number of results to be returned per request. - MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` + // (Enterprise edition only) The name of the custom permissions profile that + // you want to assign to this user. Currently, custom permissions profile names + // are assigned to permissions profiles in the QuickSight console. You use this + // API to assign the named set of permissions to a QuickSight user. + // + // Customizing permissions in the QuickSight UI allows you to control a user's + // access to the following operations: + // + // * + // + // * + // + // * + // + // * + // + // QuickSight custom permissions are applied through IAM policies. Therefore, + // they override the permissions typically granted by assigning QuickSight users + // to one of the default security cohorts (admin, author, reader) in QuickSight. + // + // This feature is available only to QuickSight Enterprise edition subscriptions + // that use SAML 2.0-Based Federation for Single Sign-On (SSO). + CustomPermissionsName *string `min:"1" type:"string"` - // The token for the next set of results, or null if there are no more results. - NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + // The email address of the user that you want to register. + // + // Email is a required field + Email *string `type:"string" required:"true"` - // The ID for the template. + // The ARN of the IAM user or role that you are registering with Amazon QuickSight. + IamArn *string `type:"string"` + + // Amazon QuickSight supports several ways of managing the identity of users. + // This parameter accepts two values: // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + // * IAM: A user whose identity maps to an existing IAM user or role. + // + // * QUICKSIGHT: A user whose identity is owned and managed internally by + // Amazon QuickSight. + // + // IdentityType is a required field + IdentityType *string `type:"string" required:"true" enum:"IdentityType"` + + // The namespace. Currently, you should set this to default. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + + // You need to use this parameter only when you register one or more users using + // an assumed IAM role. You don't need to provide the session name for other + // scenarios, for example when you are registering an IAM user or an Amazon + // QuickSight user. You can register multiple users using the same IAM role + // if each user has a different session name. For more information on assuming + // IAM roles, see assume-role (https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role.html) + // in the AWS CLI Reference. + SessionName *string `min:"2" type:"string"` + + // The Amazon QuickSight user name that you want to create for the user you + // are registering. + UserName *string `min:"1" type:"string"` + + // The Amazon QuickSight role for the user. The user role can be one of the + // following: + // + // * READER: A user who has read-only access to dashboards. + // + // * AUTHOR: A user who can create data sources, datasets, analyses, and + // dashboards. + // + // * ADMIN: A user who is an author, who can also manage Amazon QuickSight + // settings. + // + // * RESTRICTED_READER: This role isn't currently available for use. + // + // * RESTRICTED_AUTHOR: This role isn't currently available for use. + // + // UserRole is a required field + UserRole *string `type:"string" required:"true" enum:"UserRole"` } // String returns the string representation -func (s ListTemplateVersionsInput) String() string { +func (s RegisterUserInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListTemplateVersionsInput) GoString() string { +func (s RegisterUserInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListTemplateVersionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTemplateVersionsInput"} +func (s *RegisterUserInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RegisterUserInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + if s.CustomPermissionsName != nil && len(*s.CustomPermissionsName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CustomPermissionsName", 1)) } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) + if s.Email == nil { + invalidParams.Add(request.NewErrParamRequired("Email")) } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + if s.IdentityType == nil { + invalidParams.Add(request.NewErrParamRequired("IdentityType")) + } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) + } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + } + if s.SessionName != nil && len(*s.SessionName) < 2 { + invalidParams.Add(request.NewErrParamMinLen("SessionName", 2)) + } + if s.UserName != nil && len(*s.UserName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) + } + if s.UserRole == nil { + invalidParams.Add(request.NewErrParamRequired("UserRole")) } if invalidParams.Len() > 0 { @@ -16881,34 +23848,61 @@ func (s *ListTemplateVersionsInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListTemplateVersionsInput) SetAwsAccountId(v string) *ListTemplateVersionsInput { +func (s *RegisterUserInput) SetAwsAccountId(v string) *RegisterUserInput { s.AwsAccountId = &v return s } -// SetMaxResults sets the MaxResults field's value. -func (s *ListTemplateVersionsInput) SetMaxResults(v int64) *ListTemplateVersionsInput { - s.MaxResults = &v +// SetCustomPermissionsName sets the CustomPermissionsName field's value. +func (s *RegisterUserInput) SetCustomPermissionsName(v string) *RegisterUserInput { + s.CustomPermissionsName = &v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListTemplateVersionsInput) SetNextToken(v string) *ListTemplateVersionsInput { - s.NextToken = &v +// SetEmail sets the Email field's value. +func (s *RegisterUserInput) SetEmail(v string) *RegisterUserInput { + s.Email = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *ListTemplateVersionsInput) SetTemplateId(v string) *ListTemplateVersionsInput { - s.TemplateId = &v +// SetIamArn sets the IamArn field's value. +func (s *RegisterUserInput) SetIamArn(v string) *RegisterUserInput { + s.IamArn = &v return s } -type ListTemplateVersionsOutput struct { - _ struct{} `type:"structure"` +// SetIdentityType sets the IdentityType field's value. +func (s *RegisterUserInput) SetIdentityType(v string) *RegisterUserInput { + s.IdentityType = &v + return s +} - // The token for the next set of results, or null if there are no more results. - NextToken *string `type:"string"` +// SetNamespace sets the Namespace field's value. +func (s *RegisterUserInput) SetNamespace(v string) *RegisterUserInput { + s.Namespace = &v + return s +} + +// SetSessionName sets the SessionName field's value. +func (s *RegisterUserInput) SetSessionName(v string) *RegisterUserInput { + s.SessionName = &v + return s +} + +// SetUserName sets the UserName field's value. +func (s *RegisterUserInput) SetUserName(v string) *RegisterUserInput { + s.UserName = &v + return s +} + +// SetUserRole sets the UserRole field's value. +func (s *RegisterUserInput) SetUserRole(v string) *RegisterUserInput { + s.UserRole = &v + return s +} + +type RegisterUserOutput struct { + _ struct{} `type:"structure"` // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -16916,80 +23910,108 @@ type ListTemplateVersionsOutput struct { // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - // A structure containing a list of all the versions of the specified template. - TemplateVersionSummaryList []*TemplateVersionSummary `type:"list"` + // The user name. + User *User `type:"structure"` + + // The URL the user visits to complete registration and provide a password. + // This is returned only for users with an identity type of QUICKSIGHT. + UserInvitationUrl *string `type:"string"` } // String returns the string representation -func (s ListTemplateVersionsOutput) String() string { +func (s RegisterUserOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListTemplateVersionsOutput) GoString() string { +func (s RegisterUserOutput) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListTemplateVersionsOutput) SetNextToken(v string) *ListTemplateVersionsOutput { - s.NextToken = &v - return s -} - // SetRequestId sets the RequestId field's value. -func (s *ListTemplateVersionsOutput) SetRequestId(v string) *ListTemplateVersionsOutput { +func (s *RegisterUserOutput) SetRequestId(v string) *RegisterUserOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *ListTemplateVersionsOutput) SetStatus(v int64) *ListTemplateVersionsOutput { +func (s *RegisterUserOutput) SetStatus(v int64) *RegisterUserOutput { s.Status = &v return s } -// SetTemplateVersionSummaryList sets the TemplateVersionSummaryList field's value. -func (s *ListTemplateVersionsOutput) SetTemplateVersionSummaryList(v []*TemplateVersionSummary) *ListTemplateVersionsOutput { - s.TemplateVersionSummaryList = v +// SetUser sets the User field's value. +func (s *RegisterUserOutput) SetUser(v *User) *RegisterUserOutput { + s.User = v + return s +} + +// SetUserInvitationUrl sets the UserInvitationUrl field's value. +func (s *RegisterUserOutput) SetUserInvitationUrl(v string) *RegisterUserOutput { + s.UserInvitationUrl = &v return s } -type ListTemplatesInput struct { +// A physical table type for relational data sources. +type RelationalTable struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the templates that you're listing. + // The Amazon Resource Name (ARN) for the data source. // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // DataSourceArn is a required field + DataSourceArn *string `type:"string" required:"true"` - // The maximum number of results to be returned per request. - MaxResults *int64 `location:"querystring" locationName:"max-result" min:"1" type:"integer"` + // The column schema of the table. + // + // InputColumns is a required field + InputColumns []*InputColumn `min:"1" type:"list" required:"true"` - // The token for the next set of results, or null if there are no more results. - NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + // The name of the relational table. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // The schema name. This name applies to certain relational database engines. + Schema *string `type:"string"` } // String returns the string representation -func (s ListTemplatesInput) String() string { +func (s RelationalTable) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListTemplatesInput) GoString() string { +func (s RelationalTable) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListTemplatesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTemplatesInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) +func (s *RelationalTable) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RelationalTable"} + if s.DataSourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("DataSourceArn")) } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + if s.InputColumns == nil { + invalidParams.Add(request.NewErrParamRequired("InputColumns")) } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + if s.InputColumns != nil && len(s.InputColumns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("InputColumns", 1)) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.InputColumns != nil { + for i, v := range s.InputColumns { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "InputColumns", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -16998,269 +24020,259 @@ func (s *ListTemplatesInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListTemplatesInput) SetAwsAccountId(v string) *ListTemplatesInput { - s.AwsAccountId = &v +// SetDataSourceArn sets the DataSourceArn field's value. +func (s *RelationalTable) SetDataSourceArn(v string) *RelationalTable { + s.DataSourceArn = &v return s } -// SetMaxResults sets the MaxResults field's value. -func (s *ListTemplatesInput) SetMaxResults(v int64) *ListTemplatesInput { - s.MaxResults = &v +// SetInputColumns sets the InputColumns field's value. +func (s *RelationalTable) SetInputColumns(v []*InputColumn) *RelationalTable { + s.InputColumns = v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListTemplatesInput) SetNextToken(v string) *ListTemplatesInput { - s.NextToken = &v +// SetName sets the Name field's value. +func (s *RelationalTable) SetName(v string) *RelationalTable { + s.Name = &v return s } -type ListTemplatesOutput struct { - _ struct{} `type:"structure"` - - // The token for the next set of results, or null if there are no more results. - NextToken *string `type:"string"` +// SetSchema sets the Schema field's value. +func (s *RelationalTable) SetSchema(v string) *RelationalTable { + s.Schema = &v + return s +} - // The AWS request ID for this operation. - RequestId *string `type:"string"` +// A transform operation that renames a column. +type RenameColumnOperation struct { + _ struct{} `type:"structure"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // The name of the column to be renamed. + // + // ColumnName is a required field + ColumnName *string `min:"1" type:"string" required:"true"` - // A structure containing information about the templates in the list. - TemplateSummaryList []*TemplateSummary `type:"list"` + // The new name for the column. + // + // NewColumnName is a required field + NewColumnName *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s ListTemplatesOutput) String() string { +func (s RenameColumnOperation) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListTemplatesOutput) GoString() string { +func (s RenameColumnOperation) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListTemplatesOutput) SetNextToken(v string) *ListTemplatesOutput { - s.NextToken = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *RenameColumnOperation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RenameColumnOperation"} + if s.ColumnName == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnName")) + } + if s.ColumnName != nil && len(*s.ColumnName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ColumnName", 1)) + } + if s.NewColumnName == nil { + invalidParams.Add(request.NewErrParamRequired("NewColumnName")) + } + if s.NewColumnName != nil && len(*s.NewColumnName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("NewColumnName", 1)) + } -// SetRequestId sets the RequestId field's value. -func (s *ListTemplatesOutput) SetRequestId(v string) *ListTemplatesOutput { - s.RequestId = &v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetStatus sets the Status field's value. -func (s *ListTemplatesOutput) SetStatus(v int64) *ListTemplatesOutput { - s.Status = &v +// SetColumnName sets the ColumnName field's value. +func (s *RenameColumnOperation) SetColumnName(v string) *RenameColumnOperation { + s.ColumnName = &v return s } -// SetTemplateSummaryList sets the TemplateSummaryList field's value. -func (s *ListTemplatesOutput) SetTemplateSummaryList(v []*TemplateSummary) *ListTemplatesOutput { - s.TemplateSummaryList = v +// SetNewColumnName sets the NewColumnName field's value. +func (s *RenameColumnOperation) SetNewColumnName(v string) *RenameColumnOperation { + s.NewColumnName = &v return s } -type ListUserGroupsInput struct { - _ struct{} `type:"structure"` - - // The AWS account ID that the user is in. Currently, you use the ID for the - // AWS account that contains your Amazon QuickSight account. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // The maximum number of results to return from this request. - MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` +// The resource specified already exists. +type ResourceExistsException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // The namespace. Currently, you should set this to default. - // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + Message_ *string `locationName:"Message" type:"string"` - // A pagination token that can be used in a subsequent request. - NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + // The AWS request ID for this request. + RequestId *string `type:"string"` - // The Amazon QuickSight user name that you want to list group memberships for. - // - // UserName is a required field - UserName *string `location:"uri" locationName:"UserName" min:"1" type:"string" required:"true"` + // The resource type for this request. + ResourceType *string `type:"string" enum:"ExceptionResourceType"` } // String returns the string representation -func (s ListUserGroupsInput) String() string { +func (s ResourceExistsException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListUserGroupsInput) GoString() string { +func (s ResourceExistsException) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListUserGroupsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListUserGroupsInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) - } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) - } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) - } - if s.UserName == nil { - invalidParams.Add(request.NewErrParamRequired("UserName")) - } - if s.UserName != nil && len(*s.UserName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams +func newErrorResourceExistsException(v protocol.ResponseMetadata) error { + return &ResourceExistsException{ + RespMetadata: v, } - return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListUserGroupsInput) SetAwsAccountId(v string) *ListUserGroupsInput { - s.AwsAccountId = &v - return s +// Code returns the exception type name. +func (s *ResourceExistsException) Code() string { + return "ResourceExistsException" } -// SetMaxResults sets the MaxResults field's value. -func (s *ListUserGroupsInput) SetMaxResults(v int64) *ListUserGroupsInput { - s.MaxResults = &v - return s +// Message returns the exception's message. +func (s *ResourceExistsException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" } -// SetNamespace sets the Namespace field's value. -func (s *ListUserGroupsInput) SetNamespace(v string) *ListUserGroupsInput { - s.Namespace = &v - return s +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ResourceExistsException) OrigErr() error { + return nil } -// SetNextToken sets the NextToken field's value. -func (s *ListUserGroupsInput) SetNextToken(v string) *ListUserGroupsInput { - s.NextToken = &v - return s +func (s *ResourceExistsException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) } -// SetUserName sets the UserName field's value. -func (s *ListUserGroupsInput) SetUserName(v string) *ListUserGroupsInput { - s.UserName = &v - return s +// Status code returns the HTTP status code for the request's response error. +func (s *ResourceExistsException) StatusCode() int { + return s.RespMetadata.StatusCode } -type ListUserGroupsOutput struct { - _ struct{} `type:"structure"` +// RequestID returns the service's response RequestID for request. +func (s *ResourceExistsException) RequestID() string { + return s.RespMetadata.RequestID +} - // The list of groups the user is a member of. - GroupList []*Group `type:"list"` +// One or more resources can't be found. +type ResourceNotFoundException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // A pagination token that can be used in a subsequent request. - NextToken *string `type:"string"` + Message_ *string `locationName:"Message" type:"string"` - // The AWS request ID for this operation. + // The AWS request ID for this request. RequestId *string `type:"string"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // The resource type for this request. + ResourceType *string `type:"string" enum:"ExceptionResourceType"` } // String returns the string representation -func (s ListUserGroupsOutput) String() string { +func (s ResourceNotFoundException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListUserGroupsOutput) GoString() string { +func (s ResourceNotFoundException) GoString() string { return s.String() } -// SetGroupList sets the GroupList field's value. -func (s *ListUserGroupsOutput) SetGroupList(v []*Group) *ListUserGroupsOutput { - s.GroupList = v - return s +func newErrorResourceNotFoundException(v protocol.ResponseMetadata) error { + return &ResourceNotFoundException{ + RespMetadata: v, + } } -// SetNextToken sets the NextToken field's value. -func (s *ListUserGroupsOutput) SetNextToken(v string) *ListUserGroupsOutput { - s.NextToken = &v - return s +// Code returns the exception type name. +func (s *ResourceNotFoundException) Code() string { + return "ResourceNotFoundException" } -// SetRequestId sets the RequestId field's value. -func (s *ListUserGroupsOutput) SetRequestId(v string) *ListUserGroupsOutput { - s.RequestId = &v - return s +// Message returns the exception's message. +func (s *ResourceNotFoundException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" } -// SetStatus sets the Status field's value. -func (s *ListUserGroupsOutput) SetStatus(v int64) *ListUserGroupsOutput { - s.Status = &v - return s +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ResourceNotFoundException) OrigErr() error { + return nil } -type ListUsersInput struct { - _ struct{} `type:"structure"` +func (s *ResourceNotFoundException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} - // The ID for the AWS account that the user is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` +// Status code returns the HTTP status code for the request's response error. +func (s *ResourceNotFoundException) StatusCode() int { + return s.RespMetadata.StatusCode +} - // The maximum number of results to return from this request. - MaxResults *int64 `location:"querystring" locationName:"max-results" min:"1" type:"integer"` +// RequestID returns the service's response RequestID for request. +func (s *ResourceNotFoundException) RequestID() string { + return s.RespMetadata.RequestID +} - // The namespace. Currently, you should set this to default. +// Permission for the resource. +type ResourcePermission struct { + _ struct{} `type:"structure"` + + // The action to grant or revoke permissions on, for example "quicksight:DescribeDashboard". // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // Actions is a required field + Actions []*string `min:"1" type:"list" required:"true"` - // A pagination token that can be used in a subsequent request. - NextToken *string `location:"querystring" locationName:"next-token" type:"string"` + // The Amazon Resource Name (ARN) of the principal. This can be one of the following: + // + // * The ARN of an Amazon QuickSight user, group, or namespace. (This is + // most common.) + // + // * The ARN of an AWS account root: This is an IAM ARN rather than a QuickSight + // ARN. Use this option only to share resources (templates) across AWS accounts. + // (This is less common.) + // + // Principal is a required field + Principal *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s ListUsersInput) String() string { +func (s ResourcePermission) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListUsersInput) GoString() string { +func (s ResourcePermission) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ListUsersInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListUsersInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) +func (s *ResourcePermission) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ResourcePermission"} + if s.Actions == nil { + invalidParams.Add(request.NewErrParamRequired("Actions")) } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + if s.Actions != nil && len(s.Actions) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Actions", 1)) } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.Principal == nil { + invalidParams.Add(request.NewErrParamRequired("Principal")) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.Principal != nil && len(*s.Principal) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Principal", 1)) } if invalidParams.Len() > 0 { @@ -17269,198 +24281,149 @@ func (s *ListUsersInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *ListUsersInput) SetAwsAccountId(v string) *ListUsersInput { - s.AwsAccountId = &v - return s -} - -// SetMaxResults sets the MaxResults field's value. -func (s *ListUsersInput) SetMaxResults(v int64) *ListUsersInput { - s.MaxResults = &v - return s -} - -// SetNamespace sets the Namespace field's value. -func (s *ListUsersInput) SetNamespace(v string) *ListUsersInput { - s.Namespace = &v +// SetActions sets the Actions field's value. +func (s *ResourcePermission) SetActions(v []*string) *ResourcePermission { + s.Actions = v return s } -// SetNextToken sets the NextToken field's value. -func (s *ListUsersInput) SetNextToken(v string) *ListUsersInput { - s.NextToken = &v +// SetPrincipal sets the Principal field's value. +func (s *ResourcePermission) SetPrincipal(v string) *ResourcePermission { + s.Principal = &v return s } -type ListUsersOutput struct { - _ struct{} `type:"structure"` +// This resource is currently unavailable. +type ResourceUnavailableException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // A pagination token that can be used in a subsequent request. - NextToken *string `type:"string"` + Message_ *string `locationName:"Message" type:"string"` - // The AWS request ID for this operation. + // The AWS request ID for this request. RequestId *string `type:"string"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` - - // The list of users. - UserList []*User `type:"list"` + // The resource type for this request. + ResourceType *string `type:"string" enum:"ExceptionResourceType"` } // String returns the string representation -func (s ListUsersOutput) String() string { +func (s ResourceUnavailableException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ListUsersOutput) GoString() string { +func (s ResourceUnavailableException) GoString() string { return s.String() } -// SetNextToken sets the NextToken field's value. -func (s *ListUsersOutput) SetNextToken(v string) *ListUsersOutput { - s.NextToken = &v - return s -} - -// SetRequestId sets the RequestId field's value. -func (s *ListUsersOutput) SetRequestId(v string) *ListUsersOutput { - s.RequestId = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *ListUsersOutput) SetStatus(v int64) *ListUsersOutput { - s.Status = &v - return s +func newErrorResourceUnavailableException(v protocol.ResponseMetadata) error { + return &ResourceUnavailableException{ + RespMetadata: v, + } } -// SetUserList sets the UserList field's value. -func (s *ListUsersOutput) SetUserList(v []*User) *ListUsersOutput { - s.UserList = v - return s +// Code returns the exception type name. +func (s *ResourceUnavailableException) Code() string { + return "ResourceUnavailableException" } -// A logical table is a unit that joins and that data transformations operate -// on. A logical table has a source, which can be either a physical table or -// result of a join. When a logical table points to a physical table, the logical -// table acts as a mutable copy of that physical table through transform operations. -type LogicalTable struct { - _ struct{} `type:"structure"` - - // A display name for the logical table. - // - // Alias is a required field - Alias *string `min:"1" type:"string" required:"true"` - - // Transform operations that act on this logical table. - DataTransforms []*TransformOperation `min:"1" type:"list"` - - // Source of this logical table. - // - // Source is a required field - Source *LogicalTableSource `type:"structure" required:"true"` +// Message returns the exception's message. +func (s *ResourceUnavailableException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" } -// String returns the string representation -func (s LogicalTable) String() string { - return awsutil.Prettify(s) +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ResourceUnavailableException) OrigErr() error { + return nil } -// GoString returns the string representation -func (s LogicalTable) GoString() string { - return s.String() +func (s *ResourceUnavailableException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) } -// Validate inspects the fields of the type to determine if they are valid. -func (s *LogicalTable) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LogicalTable"} - if s.Alias == nil { - invalidParams.Add(request.NewErrParamRequired("Alias")) - } - if s.Alias != nil && len(*s.Alias) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Alias", 1)) - } - if s.DataTransforms != nil && len(s.DataTransforms) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataTransforms", 1)) - } - if s.Source == nil { - invalidParams.Add(request.NewErrParamRequired("Source")) - } - if s.DataTransforms != nil { - for i, v := range s.DataTransforms { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DataTransforms", i), err.(request.ErrInvalidParams)) - } - } - } - if s.Source != nil { - if err := s.Source.Validate(); err != nil { - invalidParams.AddNested("Source", err.(request.ErrInvalidParams)) - } - } +// Status code returns the HTTP status code for the request's response error. +func (s *ResourceUnavailableException) StatusCode() int { + return s.RespMetadata.StatusCode +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// RequestID returns the service's response RequestID for request. +func (s *ResourceUnavailableException) RequestID() string { + return s.RespMetadata.RequestID } -// SetAlias sets the Alias field's value. -func (s *LogicalTable) SetAlias(v string) *LogicalTable { - s.Alias = &v - return s +// Information about rows for a data set SPICE ingestion. +type RowInfo struct { + _ struct{} `type:"structure"` + + // The number of rows that were not ingested. + RowsDropped *int64 `type:"long"` + + // The number of rows that were ingested. + RowsIngested *int64 `type:"long"` } -// SetDataTransforms sets the DataTransforms field's value. -func (s *LogicalTable) SetDataTransforms(v []*TransformOperation) *LogicalTable { - s.DataTransforms = v +// String returns the string representation +func (s RowInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RowInfo) GoString() string { + return s.String() +} + +// SetRowsDropped sets the RowsDropped field's value. +func (s *RowInfo) SetRowsDropped(v int64) *RowInfo { + s.RowsDropped = &v return s } -// SetSource sets the Source field's value. -func (s *LogicalTable) SetSource(v *LogicalTableSource) *LogicalTable { - s.Source = v +// SetRowsIngested sets the RowsIngested field's value. +func (s *RowInfo) SetRowsIngested(v int64) *RowInfo { + s.RowsIngested = &v return s } -// Information about the source of a logical table. This is a variant type structure. -// For this structure to be valid, only one of the attributes can be non-null. -type LogicalTableSource struct { +// The row-level security configuration for the dataset. +type RowLevelPermissionDataSet struct { _ struct{} `type:"structure"` - // Specifies the result of a join of two logical tables. - JoinInstruction *JoinInstruction `type:"structure"` + // The Amazon Resource Name (ARN) of the permission dataset. + // + // Arn is a required field + Arn *string `type:"string" required:"true"` - // Physical table ID. - PhysicalTableId *string `min:"1" type:"string"` + // The namespace associated with the row-level permissions dataset. + Namespace *string `type:"string"` + + // Permission policy. + // + // PermissionPolicy is a required field + PermissionPolicy *string `type:"string" required:"true" enum:"RowLevelPermissionPolicy"` } // String returns the string representation -func (s LogicalTableSource) String() string { +func (s RowLevelPermissionDataSet) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s LogicalTableSource) GoString() string { +func (s RowLevelPermissionDataSet) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *LogicalTableSource) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LogicalTableSource"} - if s.PhysicalTableId != nil && len(*s.PhysicalTableId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("PhysicalTableId", 1)) +func (s *RowLevelPermissionDataSet) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RowLevelPermissionDataSet"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) } - if s.JoinInstruction != nil { - if err := s.JoinInstruction.Validate(); err != nil { - invalidParams.AddNested("JoinInstruction", err.(request.ErrInvalidParams)) - } + if s.PermissionPolicy == nil { + invalidParams.Add(request.NewErrParamRequired("PermissionPolicy")) } if invalidParams.Len() > 0 { @@ -17469,57 +24432,55 @@ func (s *LogicalTableSource) Validate() error { return nil } -// SetJoinInstruction sets the JoinInstruction field's value. -func (s *LogicalTableSource) SetJoinInstruction(v *JoinInstruction) *LogicalTableSource { - s.JoinInstruction = v +// SetArn sets the Arn field's value. +func (s *RowLevelPermissionDataSet) SetArn(v string) *RowLevelPermissionDataSet { + s.Arn = &v return s } -// SetPhysicalTableId sets the PhysicalTableId field's value. -func (s *LogicalTableSource) SetPhysicalTableId(v string) *LogicalTableSource { - s.PhysicalTableId = &v +// SetNamespace sets the Namespace field's value. +func (s *RowLevelPermissionDataSet) SetNamespace(v string) *RowLevelPermissionDataSet { + s.Namespace = &v return s } -// Amazon S3 manifest file location. -type ManifestFileLocation struct { - _ struct{} `type:"structure"` +// SetPermissionPolicy sets the PermissionPolicy field's value. +func (s *RowLevelPermissionDataSet) SetPermissionPolicy(v string) *RowLevelPermissionDataSet { + s.PermissionPolicy = &v + return s +} - // Amazon S3 bucket. - // - // Bucket is a required field - Bucket *string `min:"1" type:"string" required:"true"` +// S3 parameters. +type S3Parameters struct { + _ struct{} `type:"structure"` - // Amazon S3 key that identifies an object. + // Location of the Amazon S3 manifest file. This is NULL if the manifest file + // was uploaded in the console. // - // Key is a required field - Key *string `min:"1" type:"string" required:"true"` + // ManifestFileLocation is a required field + ManifestFileLocation *ManifestFileLocation `type:"structure" required:"true"` } // String returns the string representation -func (s ManifestFileLocation) String() string { +func (s S3Parameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ManifestFileLocation) GoString() string { +func (s S3Parameters) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ManifestFileLocation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ManifestFileLocation"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Bucket != nil && len(*s.Bucket) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Bucket", 1)) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) +func (s *S3Parameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "S3Parameters"} + if s.ManifestFileLocation == nil { + invalidParams.Add(request.NewErrParamRequired("ManifestFileLocation")) } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + if s.ManifestFileLocation != nil { + if err := s.ManifestFileLocation.Validate(); err != nil { + invalidParams.AddNested("ManifestFileLocation", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -17528,68 +24489,66 @@ func (s *ManifestFileLocation) Validate() error { return nil } -// SetBucket sets the Bucket field's value. -func (s *ManifestFileLocation) SetBucket(v string) *ManifestFileLocation { - s.Bucket = &v - return s -} - -// SetKey sets the Key field's value. -func (s *ManifestFileLocation) SetKey(v string) *ManifestFileLocation { - s.Key = &v +// SetManifestFileLocation sets the ManifestFileLocation field's value. +func (s *S3Parameters) SetManifestFileLocation(v *ManifestFileLocation) *S3Parameters { + s.ManifestFileLocation = v return s } -// MariaDB parameters. -type MariaDbParameters struct { +// A physical table type for as S3 data source. +type S3Source struct { _ struct{} `type:"structure"` - // Database. + // The amazon Resource Name (ARN) for the data source. // - // Database is a required field - Database *string `min:"1" type:"string" required:"true"` + // DataSourceArn is a required field + DataSourceArn *string `type:"string" required:"true"` - // Host. + // A physical table type for as S3 data source. // - // Host is a required field - Host *string `min:"1" type:"string" required:"true"` + // InputColumns is a required field + InputColumns []*InputColumn `min:"1" type:"list" required:"true"` - // Port. - // - // Port is a required field - Port *int64 `min:"1" type:"integer" required:"true"` + // Information about the format for the S3 source file or files. + UploadSettings *UploadSettings `type:"structure"` } // String returns the string representation -func (s MariaDbParameters) String() string { +func (s S3Source) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s MariaDbParameters) GoString() string { +func (s S3Source) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *MariaDbParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "MariaDbParameters"} - if s.Database == nil { - invalidParams.Add(request.NewErrParamRequired("Database")) - } - if s.Database != nil && len(*s.Database) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Database", 1)) +func (s *S3Source) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "S3Source"} + if s.DataSourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("DataSourceArn")) } - if s.Host == nil { - invalidParams.Add(request.NewErrParamRequired("Host")) + if s.InputColumns == nil { + invalidParams.Add(request.NewErrParamRequired("InputColumns")) } - if s.Host != nil && len(*s.Host) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Host", 1)) + if s.InputColumns != nil && len(s.InputColumns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("InputColumns", 1)) } - if s.Port == nil { - invalidParams.Add(request.NewErrParamRequired("Port")) + if s.InputColumns != nil { + for i, v := range s.InputColumns { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "InputColumns", i), err.(request.ErrInvalidParams)) + } + } } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + if s.UploadSettings != nil { + if err := s.UploadSettings.Validate(); err != nil { + invalidParams.AddNested("UploadSettings", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -17598,74 +24557,82 @@ func (s *MariaDbParameters) Validate() error { return nil } -// SetDatabase sets the Database field's value. -func (s *MariaDbParameters) SetDatabase(v string) *MariaDbParameters { - s.Database = &v +// SetDataSourceArn sets the DataSourceArn field's value. +func (s *S3Source) SetDataSourceArn(v string) *S3Source { + s.DataSourceArn = &v return s } -// SetHost sets the Host field's value. -func (s *MariaDbParameters) SetHost(v string) *MariaDbParameters { - s.Host = &v +// SetInputColumns sets the InputColumns field's value. +func (s *S3Source) SetInputColumns(v []*InputColumn) *S3Source { + s.InputColumns = v return s } -// SetPort sets the Port field's value. -func (s *MariaDbParameters) SetPort(v int64) *MariaDbParameters { - s.Port = &v +// SetUploadSettings sets the UploadSettings field's value. +func (s *S3Source) SetUploadSettings(v *UploadSettings) *S3Source { + s.UploadSettings = v return s } -// MySQL parameters. -type MySqlParameters struct { +type SearchDashboardsInput struct { _ struct{} `type:"structure"` - // Database. + // The ID of the AWS account that contains the user whose dashboards you're + // searching for. // - // Database is a required field - Database *string `min:"1" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Host. + // The filters to apply to the search. Currently, you can search only by user + // name, for example, "Filters": [ { "Name": "QUICKSIGHT_USER", "Operator": + // "StringEquals", "Value": "arn:aws:quicksight:us-east-1:1:user/default/UserName1" + // } ] // - // Host is a required field - Host *string `min:"1" type:"string" required:"true"` + // Filters is a required field + Filters []*DashboardSearchFilter `type:"list" required:"true"` - // Port. - // - // Port is a required field - Port *int64 `min:"1" type:"integer" required:"true"` + // The maximum number of results to be returned per request. + MaxResults *int64 `min:"1" type:"integer"` + + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` } // String returns the string representation -func (s MySqlParameters) String() string { +func (s SearchDashboardsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s MySqlParameters) GoString() string { +func (s SearchDashboardsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *MySqlParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "MySqlParameters"} - if s.Database == nil { - invalidParams.Add(request.NewErrParamRequired("Database")) - } - if s.Database != nil && len(*s.Database) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Database", 1)) +func (s *SearchDashboardsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SearchDashboardsInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.Host == nil { - invalidParams.Add(request.NewErrParamRequired("Host")) + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Host != nil && len(*s.Host) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Host", 1)) + if s.Filters == nil { + invalidParams.Add(request.NewErrParamRequired("Filters")) } - if s.Port == nil { - invalidParams.Add(request.NewErrParamRequired("Port")) + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + if s.Filters != nil { + for i, v := range s.Filters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -17674,126 +24641,108 @@ func (s *MySqlParameters) Validate() error { return nil } -// SetDatabase sets the Database field's value. -func (s *MySqlParameters) SetDatabase(v string) *MySqlParameters { - s.Database = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *SearchDashboardsInput) SetAwsAccountId(v string) *SearchDashboardsInput { + s.AwsAccountId = &v return s } -// SetHost sets the Host field's value. -func (s *MySqlParameters) SetHost(v string) *MySqlParameters { - s.Host = &v +// SetFilters sets the Filters field's value. +func (s *SearchDashboardsInput) SetFilters(v []*DashboardSearchFilter) *SearchDashboardsInput { + s.Filters = v return s } -// SetPort sets the Port field's value. -func (s *MySqlParameters) SetPort(v int64) *MySqlParameters { - s.Port = &v +// SetMaxResults sets the MaxResults field's value. +func (s *SearchDashboardsInput) SetMaxResults(v int64) *SearchDashboardsInput { + s.MaxResults = &v return s } -// Output column. -type OutputColumn struct { +// SetNextToken sets the NextToken field's value. +func (s *SearchDashboardsInput) SetNextToken(v string) *SearchDashboardsInput { + s.NextToken = &v + return s +} + +type SearchDashboardsOutput struct { _ struct{} `type:"structure"` - // A display name for the dataset. - Name *string `min:"1" type:"string"` + // The list of dashboards owned by the user specified in Filters in your request. + DashboardSummaryList []*DashboardSummary `type:"list"` - // Type. - Type *string `type:"string" enum:"ColumnDataType"` + // The token for the next set of results, or null if there are no more results. + NextToken *string `type:"string"` + + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s OutputColumn) String() string { +func (s SearchDashboardsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s OutputColumn) GoString() string { +func (s SearchDashboardsOutput) GoString() string { return s.String() } -// SetName sets the Name field's value. -func (s *OutputColumn) SetName(v string) *OutputColumn { - s.Name = &v +// SetDashboardSummaryList sets the DashboardSummaryList field's value. +func (s *SearchDashboardsOutput) SetDashboardSummaryList(v []*DashboardSummary) *SearchDashboardsOutput { + s.DashboardSummaryList = v return s } -// SetType sets the Type field's value. -func (s *OutputColumn) SetType(v string) *OutputColumn { - s.Type = &v +// SetNextToken sets the NextToken field's value. +func (s *SearchDashboardsOutput) SetNextToken(v string) *SearchDashboardsOutput { + s.NextToken = &v return s } -// Parameters. -type Parameters struct { - _ struct{} `type:"structure"` - - // DateTime parameters. - DateTimeParameters []*DateTimeParameter `type:"list"` +// SetRequestId sets the RequestId field's value. +func (s *SearchDashboardsOutput) SetRequestId(v string) *SearchDashboardsOutput { + s.RequestId = &v + return s +} - // Decimal parameters. - DecimalParameters []*DecimalParameter `type:"list"` +// SetStatus sets the Status field's value. +func (s *SearchDashboardsOutput) SetStatus(v int64) *SearchDashboardsOutput { + s.Status = &v + return s +} - // Integer parameters. - IntegerParameters []*IntegerParameter `type:"list"` +// ServiceNow parameters. +type ServiceNowParameters struct { + _ struct{} `type:"structure"` - // String parameters. - StringParameters []*StringParameter `type:"list"` + // URL of the base site. + // + // SiteBaseUrl is a required field + SiteBaseUrl *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s Parameters) String() string { +func (s ServiceNowParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Parameters) GoString() string { +func (s ServiceNowParameters) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *Parameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Parameters"} - if s.DateTimeParameters != nil { - for i, v := range s.DateTimeParameters { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DateTimeParameters", i), err.(request.ErrInvalidParams)) - } - } - } - if s.DecimalParameters != nil { - for i, v := range s.DecimalParameters { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DecimalParameters", i), err.(request.ErrInvalidParams)) - } - } - } - if s.IntegerParameters != nil { - for i, v := range s.IntegerParameters { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "IntegerParameters", i), err.(request.ErrInvalidParams)) - } - } +func (s *ServiceNowParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ServiceNowParameters"} + if s.SiteBaseUrl == nil { + invalidParams.Add(request.NewErrParamRequired("SiteBaseUrl")) } - if s.StringParameters != nil { - for i, v := range s.StringParameters { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "StringParameters", i), err.(request.ErrInvalidParams)) - } - } + if s.SiteBaseUrl != nil && len(*s.SiteBaseUrl) < 1 { + invalidParams.Add(request.NewErrParamMinLen("SiteBaseUrl", 1)) } if invalidParams.Len() > 0 { @@ -17802,101 +24751,131 @@ func (s *Parameters) Validate() error { return nil } -// SetDateTimeParameters sets the DateTimeParameters field's value. -func (s *Parameters) SetDateTimeParameters(v []*DateTimeParameter) *Parameters { - s.DateTimeParameters = v +// SetSiteBaseUrl sets the SiteBaseUrl field's value. +func (s *ServiceNowParameters) SetSiteBaseUrl(v string) *ServiceNowParameters { + s.SiteBaseUrl = &v return s } -// SetDecimalParameters sets the DecimalParameters field's value. -func (s *Parameters) SetDecimalParameters(v []*DecimalParameter) *Parameters { - s.DecimalParameters = v - return s +// The number of minutes specified for the lifetime of a session isn't valid. +// The session lifetime must be 15-600 minutes. +type SessionLifetimeInMinutesInvalidException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + // The AWS request ID for this request. + RequestId *string `type:"string"` +} + +// String returns the string representation +func (s SessionLifetimeInMinutesInvalidException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SessionLifetimeInMinutesInvalidException) GoString() string { + return s.String() +} + +func newErrorSessionLifetimeInMinutesInvalidException(v protocol.ResponseMetadata) error { + return &SessionLifetimeInMinutesInvalidException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *SessionLifetimeInMinutesInvalidException) Code() string { + return "SessionLifetimeInMinutesInvalidException" +} + +// Message returns the exception's message. +func (s *SessionLifetimeInMinutesInvalidException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *SessionLifetimeInMinutesInvalidException) OrigErr() error { + return nil +} + +func (s *SessionLifetimeInMinutesInvalidException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *SessionLifetimeInMinutesInvalidException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *SessionLifetimeInMinutesInvalidException) RequestID() string { + return s.RespMetadata.RequestID +} + +// Sheet controls option. +type SheetControlsOption struct { + _ struct{} `type:"structure"` + + // Visibility state. + VisibilityState *string `type:"string" enum:"DashboardUIState"` +} + +// String returns the string representation +func (s SheetControlsOption) String() string { + return awsutil.Prettify(s) } -// SetIntegerParameters sets the IntegerParameters field's value. -func (s *Parameters) SetIntegerParameters(v []*IntegerParameter) *Parameters { - s.IntegerParameters = v - return s +// GoString returns the string representation +func (s SheetControlsOption) GoString() string { + return s.String() } -// SetStringParameters sets the StringParameters field's value. -func (s *Parameters) SetStringParameters(v []*StringParameter) *Parameters { - s.StringParameters = v +// SetVisibilityState sets the VisibilityState field's value. +func (s *SheetControlsOption) SetVisibilityState(v string) *SheetControlsOption { + s.VisibilityState = &v return s } -// A view of a data source that contains information about the shape of the -// data in the underlying source. This is a variant type structure. For this -// structure to be valid, only one of the attributes can be non-null. -type PhysicalTable struct { +// The theme display options for sheets. +type SheetStyle struct { _ struct{} `type:"structure"` - // A physical table type built from the results of the custom SQL query. - CustomSql *CustomSql `type:"structure"` - - // A physical table type for relational data sources. - RelationalTable *RelationalTable `type:"structure"` + // The display options for tiles. + Tile *TileStyle `type:"structure"` - // A physical table type for as S3 data source. - S3Source *S3Source `type:"structure"` + // The layout options for tiles. + TileLayout *TileLayoutStyle `type:"structure"` } // String returns the string representation -func (s PhysicalTable) String() string { +func (s SheetStyle) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PhysicalTable) GoString() string { +func (s SheetStyle) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *PhysicalTable) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PhysicalTable"} - if s.CustomSql != nil { - if err := s.CustomSql.Validate(); err != nil { - invalidParams.AddNested("CustomSql", err.(request.ErrInvalidParams)) - } - } - if s.RelationalTable != nil { - if err := s.RelationalTable.Validate(); err != nil { - invalidParams.AddNested("RelationalTable", err.(request.ErrInvalidParams)) - } - } - if s.S3Source != nil { - if err := s.S3Source.Validate(); err != nil { - invalidParams.AddNested("S3Source", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCustomSql sets the CustomSql field's value. -func (s *PhysicalTable) SetCustomSql(v *CustomSql) *PhysicalTable { - s.CustomSql = v - return s -} - -// SetRelationalTable sets the RelationalTable field's value. -func (s *PhysicalTable) SetRelationalTable(v *RelationalTable) *PhysicalTable { - s.RelationalTable = v +// SetTile sets the Tile field's value. +func (s *SheetStyle) SetTile(v *TileStyle) *SheetStyle { + s.Tile = v return s } -// SetS3Source sets the S3Source field's value. -func (s *PhysicalTable) SetS3Source(v *S3Source) *PhysicalTable { - s.S3Source = v +// SetTileLayout sets the TileLayout field's value. +func (s *SheetStyle) SetTileLayout(v *TileLayoutStyle) *SheetStyle { + s.TileLayout = v return s } -// PostgreSQL parameters. -type PostgreSqlParameters struct { +// Snowflake parameters. +type SnowflakeParameters struct { _ struct{} `type:"structure"` // Database. @@ -17909,25 +24888,25 @@ type PostgreSqlParameters struct { // Host is a required field Host *string `min:"1" type:"string" required:"true"` - // Port. + // Warehouse. // - // Port is a required field - Port *int64 `min:"1" type:"integer" required:"true"` + // Warehouse is a required field + Warehouse *string `type:"string" required:"true"` } // String returns the string representation -func (s PostgreSqlParameters) String() string { +func (s SnowflakeParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PostgreSqlParameters) GoString() string { +func (s SnowflakeParameters) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PostgreSqlParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PostgreSqlParameters"} +func (s *SnowflakeParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SnowflakeParameters"} if s.Database == nil { invalidParams.Add(request.NewErrParamRequired("Database")) } @@ -17940,11 +24919,8 @@ func (s *PostgreSqlParameters) Validate() error { if s.Host != nil && len(*s.Host) < 1 { invalidParams.Add(request.NewErrParamMinLen("Host", 1)) } - if s.Port == nil { - invalidParams.Add(request.NewErrParamRequired("Port")) - } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + if s.Warehouse == nil { + invalidParams.Add(request.NewErrParamRequired("Warehouse")) } if invalidParams.Len() > 0 { @@ -17954,90 +24930,90 @@ func (s *PostgreSqlParameters) Validate() error { } // SetDatabase sets the Database field's value. -func (s *PostgreSqlParameters) SetDatabase(v string) *PostgreSqlParameters { +func (s *SnowflakeParameters) SetDatabase(v string) *SnowflakeParameters { s.Database = &v return s } // SetHost sets the Host field's value. -func (s *PostgreSqlParameters) SetHost(v string) *PostgreSqlParameters { +func (s *SnowflakeParameters) SetHost(v string) *SnowflakeParameters { s.Host = &v return s } -// SetPort sets the Port field's value. -func (s *PostgreSqlParameters) SetPort(v int64) *PostgreSqlParameters { - s.Port = &v +// SetWarehouse sets the Warehouse field's value. +func (s *SnowflakeParameters) SetWarehouse(v string) *SnowflakeParameters { + s.Warehouse = &v return s } -// One or more preconditions aren't met. -type PreconditionNotMetException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +// Spark parameters. +type SparkParameters struct { + _ struct{} `type:"structure"` - Message_ *string `locationName:"Message" type:"string"` + // Host. + // + // Host is a required field + Host *string `min:"1" type:"string" required:"true"` - // The AWS request ID for this request. - RequestId *string `type:"string"` + // Port. + // + // Port is a required field + Port *int64 `min:"1" type:"integer" required:"true"` } // String returns the string representation -func (s PreconditionNotMetException) String() string { +func (s SparkParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PreconditionNotMetException) GoString() string { +func (s SparkParameters) GoString() string { return s.String() } -func newErrorPreconditionNotMetException(v protocol.ResponseMetadata) error { - return &PreconditionNotMetException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *SparkParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SparkParameters"} + if s.Host == nil { + invalidParams.Add(request.NewErrParamRequired("Host")) } -} - -// Code returns the exception type name. -func (s *PreconditionNotMetException) Code() string { - return "PreconditionNotMetException" -} - -// Message returns the exception's message. -func (s *PreconditionNotMetException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if s.Host != nil && len(*s.Host) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Host", 1)) + } + if s.Port == nil { + invalidParams.Add(request.NewErrParamRequired("Port")) + } + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) } - return "" -} -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *PreconditionNotMetException) OrigErr() error { + if invalidParams.Len() > 0 { + return invalidParams + } return nil } -func (s *PreconditionNotMetException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *PreconditionNotMetException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetHost sets the Host field's value. +func (s *SparkParameters) SetHost(v string) *SparkParameters { + s.Host = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *PreconditionNotMetException) RequestID() string { - return s.RespMetadata.RequestID +// SetPort sets the Port field's value. +func (s *SparkParameters) SetPort(v int64) *SparkParameters { + s.Port = &v + return s } -// Presto parameters. -type PrestoParameters struct { +// SQL Server parameters. +type SqlServerParameters struct { _ struct{} `type:"structure"` - // Catalog. + // Database. // - // Catalog is a required field - Catalog *string `type:"string" required:"true"` + // Database is a required field + Database *string `min:"1" type:"string" required:"true"` // Host. // @@ -18051,20 +25027,23 @@ type PrestoParameters struct { } // String returns the string representation -func (s PrestoParameters) String() string { +func (s SqlServerParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s PrestoParameters) GoString() string { +func (s SqlServerParameters) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *PrestoParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PrestoParameters"} - if s.Catalog == nil { - invalidParams.Add(request.NewErrParamRequired("Catalog")) +func (s *SqlServerParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "SqlServerParameters"} + if s.Database == nil { + invalidParams.Add(request.NewErrParamRequired("Database")) + } + if s.Database != nil && len(*s.Database) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Database", 1)) } if s.Host == nil { invalidParams.Add(request.NewErrParamRequired("Host")) @@ -18085,144 +25064,142 @@ func (s *PrestoParameters) Validate() error { return nil } -// SetCatalog sets the Catalog field's value. -func (s *PrestoParameters) SetCatalog(v string) *PrestoParameters { - s.Catalog = &v +// SetDatabase sets the Database field's value. +func (s *SqlServerParameters) SetDatabase(v string) *SqlServerParameters { + s.Database = &v return s } // SetHost sets the Host field's value. -func (s *PrestoParameters) SetHost(v string) *PrestoParameters { +func (s *SqlServerParameters) SetHost(v string) *SqlServerParameters { s.Host = &v return s } // SetPort sets the Port field's value. -func (s *PrestoParameters) SetPort(v int64) *PrestoParameters { +func (s *SqlServerParameters) SetPort(v int64) *SqlServerParameters { s.Port = &v return s } -// A transform operation that projects columns. Operations that come after a -// projection can only refer to projected columns. -type ProjectOperation struct { +// Secure Socket Layer (SSL) properties that apply when QuickSight connects +// to your underlying data source. +type SslProperties struct { _ struct{} `type:"structure"` - // Projected columns. - // - // ProjectedColumns is a required field - ProjectedColumns []*string `min:"1" type:"list" required:"true"` + // A Boolean option to control whether SSL should be disabled. + DisableSsl *bool `type:"boolean"` } // String returns the string representation -func (s ProjectOperation) String() string { +func (s SslProperties) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ProjectOperation) GoString() string { +func (s SslProperties) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ProjectOperation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ProjectOperation"} - if s.ProjectedColumns == nil { - invalidParams.Add(request.NewErrParamRequired("ProjectedColumns")) - } - if s.ProjectedColumns != nil && len(s.ProjectedColumns) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ProjectedColumns", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetProjectedColumns sets the ProjectedColumns field's value. -func (s *ProjectOperation) SetProjectedColumns(v []*string) *ProjectOperation { - s.ProjectedColumns = v +// SetDisableSsl sets the DisableSsl field's value. +func (s *SslProperties) SetDisableSsl(v bool) *SslProperties { + s.DisableSsl = &v return s } -// Information about a queued dataset SPICE ingestion. -type QueueInfo struct { +// String parameter. +type StringParameter struct { _ struct{} `type:"structure"` - // The ID of the ongoing ingestion. The queued ingestion is waiting for the - // ongoing ingestion to complete. - // - // QueuedIngestion is a required field - QueuedIngestion *string `type:"string" required:"true"` + // A display name for the dataset. + // + // Name is a required field + Name *string `type:"string" required:"true"` - // The ID of the queued ingestion. + // Values. // - // WaitingOnIngestion is a required field - WaitingOnIngestion *string `type:"string" required:"true"` + // Values is a required field + Values []*string `type:"list" required:"true"` } // String returns the string representation -func (s QueueInfo) String() string { +func (s StringParameter) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s QueueInfo) GoString() string { +func (s StringParameter) GoString() string { return s.String() } -// SetQueuedIngestion sets the QueuedIngestion field's value. -func (s *QueueInfo) SetQueuedIngestion(v string) *QueueInfo { - s.QueuedIngestion = &v +// Validate inspects the fields of the type to determine if they are valid. +func (s *StringParameter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StringParameter"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Values == nil { + invalidParams.Add(request.NewErrParamRequired("Values")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *StringParameter) SetName(v string) *StringParameter { + s.Name = &v return s } -// SetWaitingOnIngestion sets the WaitingOnIngestion field's value. -func (s *QueueInfo) SetWaitingOnIngestion(v string) *QueueInfo { - s.WaitingOnIngestion = &v +// SetValues sets the Values field's value. +func (s *StringParameter) SetValues(v []*string) *StringParameter { + s.Values = v return s } -// Amazon RDS parameters. -type RdsParameters struct { +// The key or keys of the key-value pairs for the resource tag or tags assigned +// to the resource. +type Tag struct { _ struct{} `type:"structure"` - // Database. + // Tag key. // - // Database is a required field - Database *string `min:"1" type:"string" required:"true"` + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` - // Instance ID. + // Tag value. // - // InstanceId is a required field - InstanceId *string `min:"1" type:"string" required:"true"` + // Value is a required field + Value *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s RdsParameters) String() string { +func (s Tag) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RdsParameters) GoString() string { +func (s Tag) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *RdsParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RdsParameters"} - if s.Database == nil { - invalidParams.Add(request.NewErrParamRequired("Database")) +func (s *Tag) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Tag"} + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) } - if s.Database != nil && len(*s.Database) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Database", 1)) + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } - if s.InstanceId == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceId")) + if s.Value == nil { + invalidParams.Add(request.NewErrParamRequired("Value")) } - if s.InstanceId != nil && len(*s.InstanceId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("InstanceId", 1)) + if s.Value != nil && len(*s.Value) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Value", 1)) } if invalidParams.Len() > 0 { @@ -18231,63 +25208,59 @@ func (s *RdsParameters) Validate() error { return nil } -// SetDatabase sets the Database field's value. -func (s *RdsParameters) SetDatabase(v string) *RdsParameters { - s.Database = &v +// SetKey sets the Key field's value. +func (s *Tag) SetKey(v string) *Tag { + s.Key = &v return s } -// SetInstanceId sets the InstanceId field's value. -func (s *RdsParameters) SetInstanceId(v string) *RdsParameters { - s.InstanceId = &v +// SetValue sets the Value field's value. +func (s *Tag) SetValue(v string) *Tag { + s.Value = &v return s } -// Amazon Redshift parameters. The ClusterId field can be blank if Host and -// Port are both set. The Host and Port fields can be blank if the ClusterId -// field is set. -type RedshiftParameters struct { +// A transform operation that tags a column with additional information. +type TagColumnOperation struct { _ struct{} `type:"structure"` - // Cluster ID. This field can be blank if the Host and Port are provided. - ClusterId *string `min:"1" type:"string"` - - // Database. + // The column that this operation acts on. // - // Database is a required field - Database *string `min:"1" type:"string" required:"true"` - - // Host. This field can be blank if ClusterId is provided. - Host *string `min:"1" type:"string"` + // ColumnName is a required field + ColumnName *string `min:"1" type:"string" required:"true"` - // Port. This field can be blank if the ClusterId is provided. - Port *int64 `type:"integer"` + // The dataset column tag, currently only used for geospatial type tagging. . + // + // This is not tags for the AWS tagging feature. . + // + // Tags is a required field + Tags []*ColumnTag `min:"1" type:"list" required:"true"` } // String returns the string representation -func (s RedshiftParameters) String() string { +func (s TagColumnOperation) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RedshiftParameters) GoString() string { +func (s TagColumnOperation) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *RedshiftParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RedshiftParameters"} - if s.ClusterId != nil && len(*s.ClusterId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ClusterId", 1)) +func (s *TagColumnOperation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagColumnOperation"} + if s.ColumnName == nil { + invalidParams.Add(request.NewErrParamRequired("ColumnName")) } - if s.Database == nil { - invalidParams.Add(request.NewErrParamRequired("Database")) + if s.ColumnName != nil && len(*s.ColumnName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ColumnName", 1)) } - if s.Database != nil && len(*s.Database) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Database", 1)) + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) } - if s.Host != nil && len(*s.Host) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Host", 1)) + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) } if invalidParams.Len() > 0 { @@ -18296,134 +25269,67 @@ func (s *RedshiftParameters) Validate() error { return nil } -// SetClusterId sets the ClusterId field's value. -func (s *RedshiftParameters) SetClusterId(v string) *RedshiftParameters { - s.ClusterId = &v - return s -} - -// SetDatabase sets the Database field's value. -func (s *RedshiftParameters) SetDatabase(v string) *RedshiftParameters { - s.Database = &v - return s -} - -// SetHost sets the Host field's value. -func (s *RedshiftParameters) SetHost(v string) *RedshiftParameters { - s.Host = &v +// SetColumnName sets the ColumnName field's value. +func (s *TagColumnOperation) SetColumnName(v string) *TagColumnOperation { + s.ColumnName = &v return s } -// SetPort sets the Port field's value. -func (s *RedshiftParameters) SetPort(v int64) *RedshiftParameters { - s.Port = &v +// SetTags sets the Tags field's value. +func (s *TagColumnOperation) SetTags(v []*ColumnTag) *TagColumnOperation { + s.Tags = v return s } -type RegisterUserInput struct { +type TagResourceInput struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the user is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // The email address of the user that you want to register. - // - // Email is a required field - Email *string `type:"string" required:"true"` - - // The ARN of the IAM user or role that you are registering with Amazon QuickSight. - IamArn *string `type:"string"` - - // Amazon QuickSight supports several ways of managing the identity of users. - // This parameter accepts two values: - // - // * IAM: A user whose identity maps to an existing IAM user or role. - // - // * QUICKSIGHT: A user whose identity is owned and managed internally by - // Amazon QuickSight. - // - // IdentityType is a required field - IdentityType *string `type:"string" required:"true" enum:"IdentityType"` - - // The namespace. Currently, you should set this to default. + // The Amazon Resource Name (ARN) of the resource that you want to tag. // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` - - // You need to use this parameter only when you register one or more users using - // an assumed IAM role. You don't need to provide the session name for other - // scenarios, for example when you are registering an IAM user or an Amazon - // QuickSight user. You can register multiple users using the same IAM role - // if each user has a different session name. For more information on assuming - // IAM roles, see assume-role (https://docs.aws.example.com/cli/latest/reference/sts/assume-role.html) - // in the AWS CLI Reference. - SessionName *string `min:"2" type:"string"` - - // The Amazon QuickSight user name that you want to create for the user you - // are registering. - UserName *string `min:"1" type:"string"` + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"ResourceArn" type:"string" required:"true"` - // The Amazon QuickSight role for the user. The user role can be one of the - // following: - // - // * READER: A user who has read-only access to dashboards. - // - // * AUTHOR: A user who can create data sources, datasets, analyses, and - // dashboards. - // - // * ADMIN: A user who is an author, who can also manage Amazon QuickSight - // settings. - // - // * RESTRICTED_READER: This role isn't currently available for use. - // - // * RESTRICTED_AUTHOR: This role isn't currently available for use. + // Contains a map of the key-value pairs for the resource tag or tags assigned + // to the resource. // - // UserRole is a required field - UserRole *string `type:"string" required:"true" enum:"UserRole"` + // Tags is a required field + Tags []*Tag `min:"1" type:"list" required:"true"` } // String returns the string representation -func (s RegisterUserInput) String() string { +func (s TagResourceInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RegisterUserInput) GoString() string { +func (s TagResourceInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *RegisterUserInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RegisterUserInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.Email == nil { - invalidParams.Add(request.NewErrParamRequired("Email")) - } - if s.IdentityType == nil { - invalidParams.Add(request.NewErrParamRequired("IdentityType")) - } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) +func (s *TagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) } - if s.SessionName != nil && len(*s.SessionName) < 2 { - invalidParams.Add(request.NewErrParamMinLen("SessionName", 2)) + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) } - if s.UserName != nil && len(*s.UserName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("UserName", 1)) + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) } - if s.UserRole == nil { - invalidParams.Add(request.NewErrParamRequired("UserRole")) + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -18432,422 +25338,347 @@ func (s *RegisterUserInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *RegisterUserInput) SetAwsAccountId(v string) *RegisterUserInput { - s.AwsAccountId = &v +// SetResourceArn sets the ResourceArn field's value. +func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput { + s.ResourceArn = &v return s } -// SetEmail sets the Email field's value. -func (s *RegisterUserInput) SetEmail(v string) *RegisterUserInput { - s.Email = &v +// SetTags sets the Tags field's value. +func (s *TagResourceInput) SetTags(v []*Tag) *TagResourceInput { + s.Tags = v return s } -// SetIamArn sets the IamArn field's value. -func (s *RegisterUserInput) SetIamArn(v string) *RegisterUserInput { - s.IamArn = &v - return s -} +type TagResourceOutput struct { + _ struct{} `type:"structure"` -// SetIdentityType sets the IdentityType field's value. -func (s *RegisterUserInput) SetIdentityType(v string) *RegisterUserInput { - s.IdentityType = &v - return s + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } -// SetNamespace sets the Namespace field's value. -func (s *RegisterUserInput) SetNamespace(v string) *RegisterUserInput { - s.Namespace = &v - return s +// String returns the string representation +func (s TagResourceOutput) String() string { + return awsutil.Prettify(s) } -// SetSessionName sets the SessionName field's value. -func (s *RegisterUserInput) SetSessionName(v string) *RegisterUserInput { - s.SessionName = &v - return s +// GoString returns the string representation +func (s TagResourceOutput) GoString() string { + return s.String() } -// SetUserName sets the UserName field's value. -func (s *RegisterUserInput) SetUserName(v string) *RegisterUserInput { - s.UserName = &v +// SetRequestId sets the RequestId field's value. +func (s *TagResourceOutput) SetRequestId(v string) *TagResourceOutput { + s.RequestId = &v return s } -// SetUserRole sets the UserRole field's value. -func (s *RegisterUserInput) SetUserRole(v string) *RegisterUserInput { - s.UserRole = &v +// SetStatus sets the Status field's value. +func (s *TagResourceOutput) SetStatus(v int64) *TagResourceOutput { + s.Status = &v return s } -type RegisterUserOutput struct { +// A template object. A template is an entity in QuickSight that encapsulates +// the metadata required to create an analysis and that you can use to create +// a dashboard. A template adds a layer of abstraction by using placeholders +// to replace the dataset associated with the analysis. You can use templates +// to create dashboards by replacing dataset placeholders with datasets that +// follow the same schema that was used to create the source analysis and template. +// +// You can share templates across AWS accounts by allowing users in other AWS +// accounts to create a template or a dashboard from an existing template. +type Template struct { _ struct{} `type:"structure"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // The Amazon Resource Name (ARN) of the template. + Arn *string `type:"string"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // Time when this was created. + CreatedTime *time.Time `type:"timestamp"` - // The user name. - User *User `type:"structure"` + // Time when this was last updated. + LastUpdatedTime *time.Time `type:"timestamp"` - // The URL the user visits to complete registration and provide a password. - // This is returned only for users with an identity type of QUICKSIGHT. - UserInvitationUrl *string `type:"string"` + // The display name of the template. + Name *string `min:"1" type:"string"` + + // The ID for the template. This is unique per AWS Region for each AWS account. + TemplateId *string `min:"1" type:"string"` + + // A structure describing the versions of the template. + Version *TemplateVersion `type:"structure"` } // String returns the string representation -func (s RegisterUserOutput) String() string { +func (s Template) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RegisterUserOutput) GoString() string { +func (s Template) GoString() string { return s.String() } -// SetRequestId sets the RequestId field's value. -func (s *RegisterUserOutput) SetRequestId(v string) *RegisterUserOutput { - s.RequestId = &v +// SetArn sets the Arn field's value. +func (s *Template) SetArn(v string) *Template { + s.Arn = &v return s } -// SetStatus sets the Status field's value. -func (s *RegisterUserOutput) SetStatus(v int64) *RegisterUserOutput { - s.Status = &v +// SetCreatedTime sets the CreatedTime field's value. +func (s *Template) SetCreatedTime(v time.Time) *Template { + s.CreatedTime = &v return s } -// SetUser sets the User field's value. -func (s *RegisterUserOutput) SetUser(v *User) *RegisterUserOutput { - s.User = v +// SetLastUpdatedTime sets the LastUpdatedTime field's value. +func (s *Template) SetLastUpdatedTime(v time.Time) *Template { + s.LastUpdatedTime = &v return s } -// SetUserInvitationUrl sets the UserInvitationUrl field's value. -func (s *RegisterUserOutput) SetUserInvitationUrl(v string) *RegisterUserOutput { - s.UserInvitationUrl = &v +// SetName sets the Name field's value. +func (s *Template) SetName(v string) *Template { + s.Name = &v return s } -// A physical table type for relational data sources. -type RelationalTable struct { - _ struct{} `type:"structure"` +// SetTemplateId sets the TemplateId field's value. +func (s *Template) SetTemplateId(v string) *Template { + s.TemplateId = &v + return s +} - // The Amazon Resource Name (ARN) for the data source. - // - // DataSourceArn is a required field - DataSourceArn *string `type:"string" required:"true"` +// SetVersion sets the Version field's value. +func (s *Template) SetVersion(v *TemplateVersion) *Template { + s.Version = v + return s +} - // The column schema of the table. - // - // InputColumns is a required field - InputColumns []*InputColumn `min:"1" type:"list" required:"true"` +// The template alias. +type TemplateAlias struct { + _ struct{} `type:"structure"` - // The name of the relational table. - // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` + // The display name of the template alias. + AliasName *string `min:"1" type:"string"` - // The schema name. This name applies to certain relational database engines. - Schema *string `type:"string"` + // The Amazon Resource Name (ARN) of the template alias. + Arn *string `type:"string"` + + // The version number of the template alias. + TemplateVersionNumber *int64 `min:"1" type:"long"` } // String returns the string representation -func (s RelationalTable) String() string { +func (s TemplateAlias) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RelationalTable) GoString() string { +func (s TemplateAlias) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *RelationalTable) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RelationalTable"} - if s.DataSourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("DataSourceArn")) - } - if s.InputColumns == nil { - invalidParams.Add(request.NewErrParamRequired("InputColumns")) - } - if s.InputColumns != nil && len(s.InputColumns) < 1 { - invalidParams.Add(request.NewErrParamMinLen("InputColumns", 1)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.InputColumns != nil { - for i, v := range s.InputColumns { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "InputColumns", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDataSourceArn sets the DataSourceArn field's value. -func (s *RelationalTable) SetDataSourceArn(v string) *RelationalTable { - s.DataSourceArn = &v - return s -} - -// SetInputColumns sets the InputColumns field's value. -func (s *RelationalTable) SetInputColumns(v []*InputColumn) *RelationalTable { - s.InputColumns = v +// SetAliasName sets the AliasName field's value. +func (s *TemplateAlias) SetAliasName(v string) *TemplateAlias { + s.AliasName = &v return s } -// SetName sets the Name field's value. -func (s *RelationalTable) SetName(v string) *RelationalTable { - s.Name = &v +// SetArn sets the Arn field's value. +func (s *TemplateAlias) SetArn(v string) *TemplateAlias { + s.Arn = &v return s } -// SetSchema sets the Schema field's value. -func (s *RelationalTable) SetSchema(v string) *RelationalTable { - s.Schema = &v +// SetTemplateVersionNumber sets the TemplateVersionNumber field's value. +func (s *TemplateAlias) SetTemplateVersionNumber(v int64) *TemplateAlias { + s.TemplateVersionNumber = &v return s } -// A transform operation that renames a column. -type RenameColumnOperation struct { +// List of errors that occurred when the template version creation failed. +type TemplateError struct { _ struct{} `type:"structure"` - // The name of the column to be renamed. - // - // ColumnName is a required field - ColumnName *string `min:"1" type:"string" required:"true"` + // Description of the error type. + Message *string `type:"string"` - // The new name for the column. - // - // NewColumnName is a required field - NewColumnName *string `min:"1" type:"string" required:"true"` + // Type of error. + Type *string `type:"string" enum:"TemplateErrorType"` } // String returns the string representation -func (s RenameColumnOperation) String() string { +func (s TemplateError) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RenameColumnOperation) GoString() string { +func (s TemplateError) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *RenameColumnOperation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RenameColumnOperation"} - if s.ColumnName == nil { - invalidParams.Add(request.NewErrParamRequired("ColumnName")) - } - if s.ColumnName != nil && len(*s.ColumnName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ColumnName", 1)) - } - if s.NewColumnName == nil { - invalidParams.Add(request.NewErrParamRequired("NewColumnName")) - } - if s.NewColumnName != nil && len(*s.NewColumnName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("NewColumnName", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetColumnName sets the ColumnName field's value. -func (s *RenameColumnOperation) SetColumnName(v string) *RenameColumnOperation { - s.ColumnName = &v +// SetMessage sets the Message field's value. +func (s *TemplateError) SetMessage(v string) *TemplateError { + s.Message = &v return s } -// SetNewColumnName sets the NewColumnName field's value. -func (s *RenameColumnOperation) SetNewColumnName(v string) *RenameColumnOperation { - s.NewColumnName = &v +// SetType sets the Type field's value. +func (s *TemplateError) SetType(v string) *TemplateError { + s.Type = &v return s } -// The resource specified already exists. -type ResourceExistsException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"Message" type:"string"` +// The source analysis of the template. +type TemplateSourceAnalysis struct { + _ struct{} `type:"structure"` - // The AWS request ID for this request. - RequestId *string `type:"string"` + // The Amazon Resource Name (ARN) of the resource. + // + // Arn is a required field + Arn *string `type:"string" required:"true"` - // The AWS request ID for this request. - ResourceType *string `type:"string" enum:"ExceptionResourceType"` + // A structure containing information about the dataset references used as placeholders + // in the template. + // + // DataSetReferences is a required field + DataSetReferences []*DataSetReference `min:"1" type:"list" required:"true"` } // String returns the string representation -func (s ResourceExistsException) String() string { +func (s TemplateSourceAnalysis) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ResourceExistsException) GoString() string { +func (s TemplateSourceAnalysis) GoString() string { return s.String() } -func newErrorResourceExistsException(v protocol.ResponseMetadata) error { - return &ResourceExistsException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *TemplateSourceAnalysis) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TemplateSourceAnalysis"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) } -} - -// Code returns the exception type name. -func (s *ResourceExistsException) Code() string { - return "ResourceExistsException" -} - -// Message returns the exception's message. -func (s *ResourceExistsException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if s.DataSetReferences == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetReferences")) + } + if s.DataSetReferences != nil && len(s.DataSetReferences) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetReferences", 1)) + } + if s.DataSetReferences != nil { + for i, v := range s.DataSetReferences { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DataSetReferences", i), err.(request.ErrInvalidParams)) + } + } } - return "" -} -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ResourceExistsException) OrigErr() error { + if invalidParams.Len() > 0 { + return invalidParams + } return nil } -func (s *ResourceExistsException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ResourceExistsException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetArn sets the Arn field's value. +func (s *TemplateSourceAnalysis) SetArn(v string) *TemplateSourceAnalysis { + s.Arn = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *ResourceExistsException) RequestID() string { - return s.RespMetadata.RequestID +// SetDataSetReferences sets the DataSetReferences field's value. +func (s *TemplateSourceAnalysis) SetDataSetReferences(v []*DataSetReference) *TemplateSourceAnalysis { + s.DataSetReferences = v + return s } -// One or more resources can't be found. -type ResourceNotFoundException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"Message" type:"string"` +// The source entity of the template. +type TemplateSourceEntity struct { + _ struct{} `type:"structure"` - // The AWS request ID for this request. - RequestId *string `type:"string"` + // The source analysis, if it is based on an analysis. + SourceAnalysis *TemplateSourceAnalysis `type:"structure"` - // The AWS request ID for this request. - ResourceType *string `type:"string" enum:"ExceptionResourceType"` + // The source template, if it is based on an template. + SourceTemplate *TemplateSourceTemplate `type:"structure"` } // String returns the string representation -func (s ResourceNotFoundException) String() string { +func (s TemplateSourceEntity) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ResourceNotFoundException) GoString() string { +func (s TemplateSourceEntity) GoString() string { return s.String() } -func newErrorResourceNotFoundException(v protocol.ResponseMetadata) error { - return &ResourceNotFoundException{ - RespMetadata: v, +// Validate inspects the fields of the type to determine if they are valid. +func (s *TemplateSourceEntity) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TemplateSourceEntity"} + if s.SourceAnalysis != nil { + if err := s.SourceAnalysis.Validate(); err != nil { + invalidParams.AddNested("SourceAnalysis", err.(request.ErrInvalidParams)) + } } -} - -// Code returns the exception type name. -func (s *ResourceNotFoundException) Code() string { - return "ResourceNotFoundException" -} - -// Message returns the exception's message. -func (s *ResourceNotFoundException) Message() string { - if s.Message_ != nil { - return *s.Message_ + if s.SourceTemplate != nil { + if err := s.SourceTemplate.Validate(); err != nil { + invalidParams.AddNested("SourceTemplate", err.(request.ErrInvalidParams)) + } } - return "" -} -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ResourceNotFoundException) OrigErr() error { + if invalidParams.Len() > 0 { + return invalidParams + } return nil } -func (s *ResourceNotFoundException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) -} - -// Status code returns the HTTP status code for the request's response error. -func (s *ResourceNotFoundException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetSourceAnalysis sets the SourceAnalysis field's value. +func (s *TemplateSourceEntity) SetSourceAnalysis(v *TemplateSourceAnalysis) *TemplateSourceEntity { + s.SourceAnalysis = v + return s } -// RequestID returns the service's response RequestID for request. -func (s *ResourceNotFoundException) RequestID() string { - return s.RespMetadata.RequestID +// SetSourceTemplate sets the SourceTemplate field's value. +func (s *TemplateSourceEntity) SetSourceTemplate(v *TemplateSourceTemplate) *TemplateSourceEntity { + s.SourceTemplate = v + return s } -// Permission for the resource. -type ResourcePermission struct { +// The source template of the template. +type TemplateSourceTemplate struct { _ struct{} `type:"structure"` - // The action to grant or revoke permissions on, for example "quicksight:DescribeDashboard". - // - // Actions is a required field - Actions []*string `min:"1" type:"list" required:"true"` - - // The Amazon Resource Name (ARN) of an Amazon QuickSight user or group, or - // an IAM ARN. If you are using cross-account resource sharing, this is the - // IAM ARN of an account root. Otherwise, it is the ARN of a QuickSight user - // or group. . + // The Amazon Resource Name (ARN) of the resource. // - // Principal is a required field - Principal *string `min:"1" type:"string" required:"true"` + // Arn is a required field + Arn *string `type:"string" required:"true"` } // String returns the string representation -func (s ResourcePermission) String() string { +func (s TemplateSourceTemplate) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ResourcePermission) GoString() string { +func (s TemplateSourceTemplate) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *ResourcePermission) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ResourcePermission"} - if s.Actions == nil { - invalidParams.Add(request.NewErrParamRequired("Actions")) - } - if s.Actions != nil && len(s.Actions) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Actions", 1)) - } - if s.Principal == nil { - invalidParams.Add(request.NewErrParamRequired("Principal")) - } - if s.Principal != nil && len(*s.Principal) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Principal", 1)) +func (s *TemplateSourceTemplate) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TemplateSourceTemplate"} + if s.Arn == nil { + invalidParams.Add(request.NewErrParamRequired("Arn")) } if invalidParams.Len() > 0 { @@ -18856,265 +25687,272 @@ func (s *ResourcePermission) Validate() error { return nil } -// SetActions sets the Actions field's value. -func (s *ResourcePermission) SetActions(v []*string) *ResourcePermission { - s.Actions = v +// SetArn sets the Arn field's value. +func (s *TemplateSourceTemplate) SetArn(v string) *TemplateSourceTemplate { + s.Arn = &v return s } -// SetPrincipal sets the Principal field's value. -func (s *ResourcePermission) SetPrincipal(v string) *ResourcePermission { - s.Principal = &v - return s -} +// The template summary. +type TemplateSummary struct { + _ struct{} `type:"structure"` -// This resource is currently unavailable. -type ResourceUnavailableException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + // A summary of a template. + Arn *string `type:"string"` - Message_ *string `locationName:"Message" type:"string"` + // The last time that this template was created. + CreatedTime *time.Time `type:"timestamp"` + + // The last time that this template was updated. + LastUpdatedTime *time.Time `type:"timestamp"` + + // A structure containing a list of version numbers for the template summary. + LatestVersionNumber *int64 `min:"1" type:"long"` - // The AWS request ID for this request. - RequestId *string `type:"string"` + // A display name for the template. + Name *string `min:"1" type:"string"` - // The resource type for this request. - ResourceType *string `type:"string" enum:"ExceptionResourceType"` + // The ID of the template. This ID is unique per AWS Region for each AWS account. + TemplateId *string `min:"1" type:"string"` } // String returns the string representation -func (s ResourceUnavailableException) String() string { +func (s TemplateSummary) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ResourceUnavailableException) GoString() string { +func (s TemplateSummary) GoString() string { return s.String() } -func newErrorResourceUnavailableException(v protocol.ResponseMetadata) error { - return &ResourceUnavailableException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ResourceUnavailableException) Code() string { - return "ResourceUnavailableException" +// SetArn sets the Arn field's value. +func (s *TemplateSummary) SetArn(v string) *TemplateSummary { + s.Arn = &v + return s } -// Message returns the exception's message. -func (s *ResourceUnavailableException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" +// SetCreatedTime sets the CreatedTime field's value. +func (s *TemplateSummary) SetCreatedTime(v time.Time) *TemplateSummary { + s.CreatedTime = &v + return s } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ResourceUnavailableException) OrigErr() error { - return nil +// SetLastUpdatedTime sets the LastUpdatedTime field's value. +func (s *TemplateSummary) SetLastUpdatedTime(v time.Time) *TemplateSummary { + s.LastUpdatedTime = &v + return s } -func (s *ResourceUnavailableException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetLatestVersionNumber sets the LatestVersionNumber field's value. +func (s *TemplateSummary) SetLatestVersionNumber(v int64) *TemplateSummary { + s.LatestVersionNumber = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *ResourceUnavailableException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetName sets the Name field's value. +func (s *TemplateSummary) SetName(v string) *TemplateSummary { + s.Name = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *ResourceUnavailableException) RequestID() string { - return s.RespMetadata.RequestID +// SetTemplateId sets the TemplateId field's value. +func (s *TemplateSummary) SetTemplateId(v string) *TemplateSummary { + s.TemplateId = &v + return s } -// Information about rows for a data set SPICE ingestion. -type RowInfo struct { +// A version of a template. +type TemplateVersion struct { _ struct{} `type:"structure"` - // The number of rows that were not ingested. - RowsDropped *int64 `type:"long"` + // The time that this template version was created. + CreatedTime *time.Time `type:"timestamp"` - // The number of rows that were ingested. - RowsIngested *int64 `type:"long"` + // Schema of the dataset identified by the placeholder. The idea is that any + // dashboard created from the template should be bound to new datasets matching + // the same schema described through this API. . + DataSetConfigurations []*DataSetConfiguration `type:"list"` + + // The description of the template. + Description *string `min:"1" type:"string"` + + // Errors associated with the template. + Errors []*TemplateError `min:"1" type:"list"` + + // The Amazon Resource Name (ARN) of the analysis or template which was used + // to create this template. + SourceEntityArn *string `type:"string"` + + // The HTTP status of the request. + Status *string `type:"string" enum:"ResourceStatus"` + + // The version number of the template. + VersionNumber *int64 `min:"1" type:"long"` } // String returns the string representation -func (s RowInfo) String() string { +func (s TemplateVersion) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s RowInfo) GoString() string { +func (s TemplateVersion) GoString() string { return s.String() } -// SetRowsDropped sets the RowsDropped field's value. -func (s *RowInfo) SetRowsDropped(v int64) *RowInfo { - s.RowsDropped = &v +// SetCreatedTime sets the CreatedTime field's value. +func (s *TemplateVersion) SetCreatedTime(v time.Time) *TemplateVersion { + s.CreatedTime = &v return s } -// SetRowsIngested sets the RowsIngested field's value. -func (s *RowInfo) SetRowsIngested(v int64) *RowInfo { - s.RowsIngested = &v +// SetDataSetConfigurations sets the DataSetConfigurations field's value. +func (s *TemplateVersion) SetDataSetConfigurations(v []*DataSetConfiguration) *TemplateVersion { + s.DataSetConfigurations = v return s } -// The row-level security configuration for the dataset. -type RowLevelPermissionDataSet struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the permission dataset. - // - // Arn is a required field - Arn *string `type:"string" required:"true"` - - // Permission policy. - // - // PermissionPolicy is a required field - PermissionPolicy *string `type:"string" required:"true" enum:"RowLevelPermissionPolicy"` -} - -// String returns the string representation -func (s RowLevelPermissionDataSet) String() string { - return awsutil.Prettify(s) +// SetDescription sets the Description field's value. +func (s *TemplateVersion) SetDescription(v string) *TemplateVersion { + s.Description = &v + return s } -// GoString returns the string representation -func (s RowLevelPermissionDataSet) GoString() string { - return s.String() +// SetErrors sets the Errors field's value. +func (s *TemplateVersion) SetErrors(v []*TemplateError) *TemplateVersion { + s.Errors = v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *RowLevelPermissionDataSet) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RowLevelPermissionDataSet"} - if s.Arn == nil { - invalidParams.Add(request.NewErrParamRequired("Arn")) - } - if s.PermissionPolicy == nil { - invalidParams.Add(request.NewErrParamRequired("PermissionPolicy")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetSourceEntityArn sets the SourceEntityArn field's value. +func (s *TemplateVersion) SetSourceEntityArn(v string) *TemplateVersion { + s.SourceEntityArn = &v + return s } -// SetArn sets the Arn field's value. -func (s *RowLevelPermissionDataSet) SetArn(v string) *RowLevelPermissionDataSet { - s.Arn = &v +// SetStatus sets the Status field's value. +func (s *TemplateVersion) SetStatus(v string) *TemplateVersion { + s.Status = &v return s } -// SetPermissionPolicy sets the PermissionPolicy field's value. -func (s *RowLevelPermissionDataSet) SetPermissionPolicy(v string) *RowLevelPermissionDataSet { - s.PermissionPolicy = &v +// SetVersionNumber sets the VersionNumber field's value. +func (s *TemplateVersion) SetVersionNumber(v int64) *TemplateVersion { + s.VersionNumber = &v return s } -// S3 parameters. -type S3Parameters struct { +// The template version. +type TemplateVersionSummary struct { _ struct{} `type:"structure"` - // Location of the Amazon S3 manifest file. This is NULL if the manifest file - // was uploaded in the console. - // - // ManifestFileLocation is a required field - ManifestFileLocation *ManifestFileLocation `type:"structure" required:"true"` + // The Amazon Resource Name (ARN) of the template version. + Arn *string `type:"string"` + + // The time that this template version was created. + CreatedTime *time.Time `type:"timestamp"` + + // The description of the template version. + Description *string `min:"1" type:"string"` + + // The status of the template version. + Status *string `type:"string" enum:"ResourceStatus"` + + // The version number of the template version. + VersionNumber *int64 `min:"1" type:"long"` } // String returns the string representation -func (s S3Parameters) String() string { +func (s TemplateVersionSummary) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s S3Parameters) GoString() string { +func (s TemplateVersionSummary) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *S3Parameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "S3Parameters"} - if s.ManifestFileLocation == nil { - invalidParams.Add(request.NewErrParamRequired("ManifestFileLocation")) - } - if s.ManifestFileLocation != nil { - if err := s.ManifestFileLocation.Validate(); err != nil { - invalidParams.AddNested("ManifestFileLocation", err.(request.ErrInvalidParams)) - } - } +// SetArn sets the Arn field's value. +func (s *TemplateVersionSummary) SetArn(v string) *TemplateVersionSummary { + s.Arn = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCreatedTime sets the CreatedTime field's value. +func (s *TemplateVersionSummary) SetCreatedTime(v time.Time) *TemplateVersionSummary { + s.CreatedTime = &v + return s } -// SetManifestFileLocation sets the ManifestFileLocation field's value. -func (s *S3Parameters) SetManifestFileLocation(v *ManifestFileLocation) *S3Parameters { - s.ManifestFileLocation = v +// SetDescription sets the Description field's value. +func (s *TemplateVersionSummary) SetDescription(v string) *TemplateVersionSummary { + s.Description = &v return s } -// A physical table type for as S3 data source. -type S3Source struct { +// SetStatus sets the Status field's value. +func (s *TemplateVersionSummary) SetStatus(v string) *TemplateVersionSummary { + s.Status = &v + return s +} + +// SetVersionNumber sets the VersionNumber field's value. +func (s *TemplateVersionSummary) SetVersionNumber(v int64) *TemplateVersionSummary { + s.VersionNumber = &v + return s +} + +// Teradata parameters. +type TeradataParameters struct { _ struct{} `type:"structure"` - // The amazon Resource Name (ARN) for the data source. + // Database. // - // DataSourceArn is a required field - DataSourceArn *string `type:"string" required:"true"` + // Database is a required field + Database *string `min:"1" type:"string" required:"true"` - // A physical table type for as S3 data source. + // Host. // - // InputColumns is a required field - InputColumns []*InputColumn `min:"1" type:"list" required:"true"` - - // Information about the format for the S3 source file or files. - UploadSettings *UploadSettings `type:"structure"` + // Host is a required field + Host *string `min:"1" type:"string" required:"true"` + + // Port. + // + // Port is a required field + Port *int64 `min:"1" type:"integer" required:"true"` } // String returns the string representation -func (s S3Source) String() string { +func (s TeradataParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s S3Source) GoString() string { +func (s TeradataParameters) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *S3Source) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "S3Source"} - if s.DataSourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("DataSourceArn")) +func (s *TeradataParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TeradataParameters"} + if s.Database == nil { + invalidParams.Add(request.NewErrParamRequired("Database")) } - if s.InputColumns == nil { - invalidParams.Add(request.NewErrParamRequired("InputColumns")) + if s.Database != nil && len(*s.Database) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Database", 1)) } - if s.InputColumns != nil && len(s.InputColumns) < 1 { - invalidParams.Add(request.NewErrParamMinLen("InputColumns", 1)) + if s.Host == nil { + invalidParams.Add(request.NewErrParamRequired("Host")) } - if s.InputColumns != nil { - for i, v := range s.InputColumns { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "InputColumns", i), err.(request.ErrInvalidParams)) - } - } + if s.Host != nil && len(*s.Host) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Host", 1)) } - if s.UploadSettings != nil { - if err := s.UploadSettings.Validate(); err != nil { - invalidParams.AddNested("UploadSettings", err.(request.ErrInvalidParams)) - } + if s.Port == nil { + invalidParams.Add(request.NewErrParamRequired("Port")) + } + if s.Port != nil && *s.Port < 1 { + invalidParams.Add(request.NewErrParamMinValue("Port", 1)) } if invalidParams.Len() > 0 { @@ -19123,616 +25961,622 @@ func (s *S3Source) Validate() error { return nil } -// SetDataSourceArn sets the DataSourceArn field's value. -func (s *S3Source) SetDataSourceArn(v string) *S3Source { - s.DataSourceArn = &v +// SetDatabase sets the Database field's value. +func (s *TeradataParameters) SetDatabase(v string) *TeradataParameters { + s.Database = &v return s } -// SetInputColumns sets the InputColumns field's value. -func (s *S3Source) SetInputColumns(v []*InputColumn) *S3Source { - s.InputColumns = v +// SetHost sets the Host field's value. +func (s *TeradataParameters) SetHost(v string) *TeradataParameters { + s.Host = &v return s } -// SetUploadSettings sets the UploadSettings field's value. -func (s *S3Source) SetUploadSettings(v *UploadSettings) *S3Source { - s.UploadSettings = v +// SetPort sets the Port field's value. +func (s *TeradataParameters) SetPort(v int64) *TeradataParameters { + s.Port = &v return s } -type SearchDashboardsInput struct { +type Theme struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the user whose dashboards you're - // searching for. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // The Amazon Resource Name (ARN) of the theme. + Arn *string `type:"string"` - // The filters to apply to the search. Currently, you can search only by user - // name. For example, "Filters": [ { "Name": "QUICKSIGHT_USER", "Operator": - // "StringEquals", "Value": "arn:aws:quicksight:us-east-1:1:user/default/UserName1" - // } ] - // - // Filters is a required field - Filters []*DashboardSearchFilter `type:"list" required:"true"` + // The date and time that the theme was created. + CreatedTime *time.Time `type:"timestamp"` - // The maximum number of results to be returned per request. - MaxResults *int64 `min:"1" type:"integer"` + // The date and time that the theme was last updated. + LastUpdatedTime *time.Time `type:"timestamp"` - // The token for the next set of results, or null if there are no more results. - NextToken *string `type:"string"` + // The name that the user gives to the theme. + Name *string `min:"1" type:"string"` + + // The identifier that the user gives to the theme. + ThemeId *string `min:"1" type:"string"` + + // The type of theme, based on how it was created. Valid values include: QUICKSIGHT + // and CUSTOM. + Type *string `type:"string" enum:"ThemeType"` + + // A version of a theme. + Version *ThemeVersion `type:"structure"` } // String returns the string representation -func (s SearchDashboardsInput) String() string { +func (s Theme) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SearchDashboardsInput) GoString() string { +func (s Theme) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *SearchDashboardsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SearchDashboardsInput"} - if s.AwsAccountId == nil { - invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) - } - if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { - invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) - } - if s.Filters == nil { - invalidParams.Add(request.NewErrParamRequired("Filters")) - } - if s.MaxResults != nil && *s.MaxResults < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) - } - if s.Filters != nil { - for i, v := range s.Filters { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams)) - } - } - } +// SetArn sets the Arn field's value. +func (s *Theme) SetArn(v string) *Theme { + s.Arn = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCreatedTime sets the CreatedTime field's value. +func (s *Theme) SetCreatedTime(v time.Time) *Theme { + s.CreatedTime = &v + return s } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *SearchDashboardsInput) SetAwsAccountId(v string) *SearchDashboardsInput { - s.AwsAccountId = &v +// SetLastUpdatedTime sets the LastUpdatedTime field's value. +func (s *Theme) SetLastUpdatedTime(v time.Time) *Theme { + s.LastUpdatedTime = &v return s } -// SetFilters sets the Filters field's value. -func (s *SearchDashboardsInput) SetFilters(v []*DashboardSearchFilter) *SearchDashboardsInput { - s.Filters = v +// SetName sets the Name field's value. +func (s *Theme) SetName(v string) *Theme { + s.Name = &v return s } -// SetMaxResults sets the MaxResults field's value. -func (s *SearchDashboardsInput) SetMaxResults(v int64) *SearchDashboardsInput { - s.MaxResults = &v +// SetThemeId sets the ThemeId field's value. +func (s *Theme) SetThemeId(v string) *Theme { + s.ThemeId = &v return s } -// SetNextToken sets the NextToken field's value. -func (s *SearchDashboardsInput) SetNextToken(v string) *SearchDashboardsInput { - s.NextToken = &v +// SetType sets the Type field's value. +func (s *Theme) SetType(v string) *Theme { + s.Type = &v return s } -type SearchDashboardsOutput struct { - _ struct{} `type:"structure"` +// SetVersion sets the Version field's value. +func (s *Theme) SetVersion(v *ThemeVersion) *Theme { + s.Version = v + return s +} - // The list of dashboards owned by the user specified in Filters in your request. - DashboardSummaryList []*DashboardSummary `type:"list"` +// An alias for a theme. +type ThemeAlias struct { + _ struct{} `type:"structure"` - // The token for the next set of results, or null if there are no more results. - NextToken *string `type:"string"` + // The display name of the theme alias. + AliasName *string `min:"1" type:"string"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // The Amazon Resource Name (ARN) of the theme alias. + Arn *string `type:"string"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` + // The version number of the theme alias. + ThemeVersionNumber *int64 `min:"1" type:"long"` } // String returns the string representation -func (s SearchDashboardsOutput) String() string { +func (s ThemeAlias) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SearchDashboardsOutput) GoString() string { +func (s ThemeAlias) GoString() string { return s.String() } -// SetDashboardSummaryList sets the DashboardSummaryList field's value. -func (s *SearchDashboardsOutput) SetDashboardSummaryList(v []*DashboardSummary) *SearchDashboardsOutput { - s.DashboardSummaryList = v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *SearchDashboardsOutput) SetNextToken(v string) *SearchDashboardsOutput { - s.NextToken = &v +// SetAliasName sets the AliasName field's value. +func (s *ThemeAlias) SetAliasName(v string) *ThemeAlias { + s.AliasName = &v return s } -// SetRequestId sets the RequestId field's value. -func (s *SearchDashboardsOutput) SetRequestId(v string) *SearchDashboardsOutput { - s.RequestId = &v +// SetArn sets the Arn field's value. +func (s *ThemeAlias) SetArn(v string) *ThemeAlias { + s.Arn = &v return s } -// SetStatus sets the Status field's value. -func (s *SearchDashboardsOutput) SetStatus(v int64) *SearchDashboardsOutput { - s.Status = &v +// SetThemeVersionNumber sets the ThemeVersionNumber field's value. +func (s *ThemeAlias) SetThemeVersionNumber(v int64) *ThemeAlias { + s.ThemeVersionNumber = &v return s } -// ServiceNow parameters. -type ServiceNowParameters struct { +// The theme configuration. This configuration contains all of the display properties +// for a theme. +type ThemeConfiguration struct { _ struct{} `type:"structure"` - // URL of the base site. - // - // SiteBaseUrl is a required field - SiteBaseUrl *string `min:"1" type:"string" required:"true"` + // Color properties that apply to chart data colors. + DataColorPalette *DataColorPalette `type:"structure"` + + // Display options related to sheets. + Sheet *SheetStyle `type:"structure"` + + // Color properties that apply to the UI and to charts, excluding the colors + // that apply to data. + UIColorPalette *UIColorPalette `type:"structure"` } // String returns the string representation -func (s ServiceNowParameters) String() string { +func (s ThemeConfiguration) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ServiceNowParameters) GoString() string { +func (s ThemeConfiguration) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *ServiceNowParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ServiceNowParameters"} - if s.SiteBaseUrl == nil { - invalidParams.Add(request.NewErrParamRequired("SiteBaseUrl")) - } - if s.SiteBaseUrl != nil && len(*s.SiteBaseUrl) < 1 { - invalidParams.Add(request.NewErrParamMinLen("SiteBaseUrl", 1)) - } +// SetDataColorPalette sets the DataColorPalette field's value. +func (s *ThemeConfiguration) SetDataColorPalette(v *DataColorPalette) *ThemeConfiguration { + s.DataColorPalette = v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetSheet sets the Sheet field's value. +func (s *ThemeConfiguration) SetSheet(v *SheetStyle) *ThemeConfiguration { + s.Sheet = v + return s } -// SetSiteBaseUrl sets the SiteBaseUrl field's value. -func (s *ServiceNowParameters) SetSiteBaseUrl(v string) *ServiceNowParameters { - s.SiteBaseUrl = &v +// SetUIColorPalette sets the UIColorPalette field's value. +func (s *ThemeConfiguration) SetUIColorPalette(v *UIColorPalette) *ThemeConfiguration { + s.UIColorPalette = v return s } -// The number of minutes specified for the lifetime of a session isn't valid. -// The session lifetime must be 15-600 minutes. -type SessionLifetimeInMinutesInvalidException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +// Theme error. +type ThemeError struct { + _ struct{} `type:"structure"` - Message_ *string `locationName:"Message" type:"string"` + // The error message. + Message *string `type:"string"` - // The AWS request ID for this request. - RequestId *string `type:"string"` + // The type of error. + Type *string `type:"string" enum:"ThemeErrorType"` } // String returns the string representation -func (s SessionLifetimeInMinutesInvalidException) String() string { +func (s ThemeError) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SessionLifetimeInMinutesInvalidException) GoString() string { +func (s ThemeError) GoString() string { return s.String() } -func newErrorSessionLifetimeInMinutesInvalidException(v protocol.ResponseMetadata) error { - return &SessionLifetimeInMinutesInvalidException{ - RespMetadata: v, - } +// SetMessage sets the Message field's value. +func (s *ThemeError) SetMessage(v string) *ThemeError { + s.Message = &v + return s +} + +// SetType sets the Type field's value. +func (s *ThemeError) SetType(v string) *ThemeError { + s.Type = &v + return s +} + +// The theme summary. +type ThemeSummary struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource. + Arn *string `type:"string"` + + // The date and time that this theme was created. + CreatedTime *time.Time `type:"timestamp"` + + // The last date and time that this theme was updated. + LastUpdatedTime *time.Time `type:"timestamp"` + + // The latest version number for the theme. + LatestVersionNumber *int64 `min:"1" type:"long"` + + // the display name for the theme. + Name *string `min:"1" type:"string"` + + // The ID of the theme. This ID is unique per AWS Region for each AWS account. + ThemeId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ThemeSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ThemeSummary) GoString() string { + return s.String() } -// Code returns the exception type name. -func (s *SessionLifetimeInMinutesInvalidException) Code() string { - return "SessionLifetimeInMinutesInvalidException" +// SetArn sets the Arn field's value. +func (s *ThemeSummary) SetArn(v string) *ThemeSummary { + s.Arn = &v + return s } -// Message returns the exception's message. -func (s *SessionLifetimeInMinutesInvalidException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" +// SetCreatedTime sets the CreatedTime field's value. +func (s *ThemeSummary) SetCreatedTime(v time.Time) *ThemeSummary { + s.CreatedTime = &v + return s } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *SessionLifetimeInMinutesInvalidException) OrigErr() error { - return nil +// SetLastUpdatedTime sets the LastUpdatedTime field's value. +func (s *ThemeSummary) SetLastUpdatedTime(v time.Time) *ThemeSummary { + s.LastUpdatedTime = &v + return s } -func (s *SessionLifetimeInMinutesInvalidException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetLatestVersionNumber sets the LatestVersionNumber field's value. +func (s *ThemeSummary) SetLatestVersionNumber(v int64) *ThemeSummary { + s.LatestVersionNumber = &v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *SessionLifetimeInMinutesInvalidException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetName sets the Name field's value. +func (s *ThemeSummary) SetName(v string) *ThemeSummary { + s.Name = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *SessionLifetimeInMinutesInvalidException) RequestID() string { - return s.RespMetadata.RequestID +// SetThemeId sets the ThemeId field's value. +func (s *ThemeSummary) SetThemeId(v string) *ThemeSummary { + s.ThemeId = &v + return s } -// Sheet controls option. -type SheetControlsOption struct { +// A version of a theme. +type ThemeVersion struct { _ struct{} `type:"structure"` - // Visibility state. - VisibilityState *string `type:"string" enum:"DashboardUIState"` + // The Amazon Resource Name (ARN) of the resource. + Arn *string `type:"string"` + + // The Amazon QuickSight-defined ID of the theme that a custom theme inherits + // from. All themes initially inherit from a default QuickSight theme. + BaseThemeId *string `min:"1" type:"string"` + + // The theme configuration, which contains all the theme display properties. + Configuration *ThemeConfiguration `type:"structure"` + + // The date and time that this theme version was created. + CreatedTime *time.Time `type:"timestamp"` + + // The description of the theme. + Description *string `min:"1" type:"string"` + + // Errors associated with the theme. + Errors []*ThemeError `min:"1" type:"list"` + + // The status of the theme version. + Status *string `type:"string" enum:"ResourceStatus"` + + // The version number of the theme. + VersionNumber *int64 `min:"1" type:"long"` } // String returns the string representation -func (s SheetControlsOption) String() string { +func (s ThemeVersion) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SheetControlsOption) GoString() string { +func (s ThemeVersion) GoString() string { return s.String() } -// SetVisibilityState sets the VisibilityState field's value. -func (s *SheetControlsOption) SetVisibilityState(v string) *SheetControlsOption { - s.VisibilityState = &v +// SetArn sets the Arn field's value. +func (s *ThemeVersion) SetArn(v string) *ThemeVersion { + s.Arn = &v return s } -// Snowflake parameters. -type SnowflakeParameters struct { - _ struct{} `type:"structure"` - - // Database. - // - // Database is a required field - Database *string `min:"1" type:"string" required:"true"` - - // Host. - // - // Host is a required field - Host *string `min:"1" type:"string" required:"true"` - - // Warehouse. - // - // Warehouse is a required field - Warehouse *string `type:"string" required:"true"` +// SetBaseThemeId sets the BaseThemeId field's value. +func (s *ThemeVersion) SetBaseThemeId(v string) *ThemeVersion { + s.BaseThemeId = &v + return s } -// String returns the string representation -func (s SnowflakeParameters) String() string { - return awsutil.Prettify(s) +// SetConfiguration sets the Configuration field's value. +func (s *ThemeVersion) SetConfiguration(v *ThemeConfiguration) *ThemeVersion { + s.Configuration = v + return s } -// GoString returns the string representation -func (s SnowflakeParameters) GoString() string { - return s.String() +// SetCreatedTime sets the CreatedTime field's value. +func (s *ThemeVersion) SetCreatedTime(v time.Time) *ThemeVersion { + s.CreatedTime = &v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *SnowflakeParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SnowflakeParameters"} - if s.Database == nil { - invalidParams.Add(request.NewErrParamRequired("Database")) - } - if s.Database != nil && len(*s.Database) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Database", 1)) - } - if s.Host == nil { - invalidParams.Add(request.NewErrParamRequired("Host")) - } - if s.Host != nil && len(*s.Host) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Host", 1)) - } - if s.Warehouse == nil { - invalidParams.Add(request.NewErrParamRequired("Warehouse")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetDescription sets the Description field's value. +func (s *ThemeVersion) SetDescription(v string) *ThemeVersion { + s.Description = &v + return s } -// SetDatabase sets the Database field's value. -func (s *SnowflakeParameters) SetDatabase(v string) *SnowflakeParameters { - s.Database = &v +// SetErrors sets the Errors field's value. +func (s *ThemeVersion) SetErrors(v []*ThemeError) *ThemeVersion { + s.Errors = v return s } -// SetHost sets the Host field's value. -func (s *SnowflakeParameters) SetHost(v string) *SnowflakeParameters { - s.Host = &v +// SetStatus sets the Status field's value. +func (s *ThemeVersion) SetStatus(v string) *ThemeVersion { + s.Status = &v return s } -// SetWarehouse sets the Warehouse field's value. -func (s *SnowflakeParameters) SetWarehouse(v string) *SnowflakeParameters { - s.Warehouse = &v +// SetVersionNumber sets the VersionNumber field's value. +func (s *ThemeVersion) SetVersionNumber(v int64) *ThemeVersion { + s.VersionNumber = &v return s } -// Spark parameters. -type SparkParameters struct { +// The theme version. +type ThemeVersionSummary struct { _ struct{} `type:"structure"` - // Host. - // - // Host is a required field - Host *string `min:"1" type:"string" required:"true"` + // The Amazon Resource Name (ARN) of the theme version. + Arn *string `type:"string"` - // Port. - // - // Port is a required field - Port *int64 `min:"1" type:"integer" required:"true"` + // The date and time that this theme version was created. + CreatedTime *time.Time `type:"timestamp"` + + // The description of the theme version. + Description *string `min:"1" type:"string"` + + // The status of the theme version. + Status *string `type:"string" enum:"ResourceStatus"` + + // The version number of the theme version. + VersionNumber *int64 `min:"1" type:"long"` } // String returns the string representation -func (s SparkParameters) String() string { +func (s ThemeVersionSummary) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SparkParameters) GoString() string { +func (s ThemeVersionSummary) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *SparkParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SparkParameters"} - if s.Host == nil { - invalidParams.Add(request.NewErrParamRequired("Host")) - } - if s.Host != nil && len(*s.Host) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Host", 1)) - } - if s.Port == nil { - invalidParams.Add(request.NewErrParamRequired("Port")) - } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) - } +// SetArn sets the Arn field's value. +func (s *ThemeVersionSummary) SetArn(v string) *ThemeVersionSummary { + s.Arn = &v + return s +} - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetCreatedTime sets the CreatedTime field's value. +func (s *ThemeVersionSummary) SetCreatedTime(v time.Time) *ThemeVersionSummary { + s.CreatedTime = &v + return s } -// SetHost sets the Host field's value. -func (s *SparkParameters) SetHost(v string) *SparkParameters { - s.Host = &v +// SetDescription sets the Description field's value. +func (s *ThemeVersionSummary) SetDescription(v string) *ThemeVersionSummary { + s.Description = &v return s } -// SetPort sets the Port field's value. -func (s *SparkParameters) SetPort(v int64) *SparkParameters { - s.Port = &v +// SetStatus sets the Status field's value. +func (s *ThemeVersionSummary) SetStatus(v string) *ThemeVersionSummary { + s.Status = &v return s } -// SQL Server parameters. -type SqlServerParameters struct { - _ struct{} `type:"structure"` +// SetVersionNumber sets the VersionNumber field's value. +func (s *ThemeVersionSummary) SetVersionNumber(v int64) *ThemeVersionSummary { + s.VersionNumber = &v + return s +} - // Database. - // - // Database is a required field - Database *string `min:"1" type:"string" required:"true"` +// Access is throttled. +type ThrottlingException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // Host. - // - // Host is a required field - Host *string `min:"1" type:"string" required:"true"` + Message_ *string `locationName:"Message" type:"string"` - // Port. - // - // Port is a required field - Port *int64 `min:"1" type:"integer" required:"true"` + // The AWS request ID for this request. + RequestId *string `type:"string"` } // String returns the string representation -func (s SqlServerParameters) String() string { +func (s ThrottlingException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SqlServerParameters) GoString() string { +func (s ThrottlingException) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *SqlServerParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SqlServerParameters"} - if s.Database == nil { - invalidParams.Add(request.NewErrParamRequired("Database")) - } - if s.Database != nil && len(*s.Database) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Database", 1)) - } - if s.Host == nil { - invalidParams.Add(request.NewErrParamRequired("Host")) - } - if s.Host != nil && len(*s.Host) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Host", 1)) - } - if s.Port == nil { - invalidParams.Add(request.NewErrParamRequired("Port")) - } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) +func newErrorThrottlingException(v protocol.ResponseMetadata) error { + return &ThrottlingException{ + RespMetadata: v, } +} - if invalidParams.Len() > 0 { - return invalidParams +// Code returns the exception type name. +func (s *ThrottlingException) Code() string { + return "ThrottlingException" +} + +// Message returns the exception's message. +func (s *ThrottlingException) Message() string { + if s.Message_ != nil { + return *s.Message_ } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ThrottlingException) OrigErr() error { return nil } -// SetDatabase sets the Database field's value. -func (s *SqlServerParameters) SetDatabase(v string) *SqlServerParameters { - s.Database = &v - return s +func (s *ThrottlingException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) } -// SetHost sets the Host field's value. -func (s *SqlServerParameters) SetHost(v string) *SqlServerParameters { - s.Host = &v - return s +// Status code returns the HTTP status code for the request's response error. +func (s *ThrottlingException) StatusCode() int { + return s.RespMetadata.StatusCode } -// SetPort sets the Port field's value. -func (s *SqlServerParameters) SetPort(v int64) *SqlServerParameters { - s.Port = &v - return s +// RequestID returns the service's response RequestID for request. +func (s *ThrottlingException) RequestID() string { + return s.RespMetadata.RequestID } -// Secure Socket Layer (SSL) properties that apply when QuickSight connects -// to your underlying data source. -type SslProperties struct { +// The display options for the layout of tiles on a sheet. +type TileLayoutStyle struct { _ struct{} `type:"structure"` - // A Boolean option to control whether SSL should be disabled. - DisableSsl *bool `type:"boolean"` + // The gutter settings that apply between tiles. + Gutter *GutterStyle `type:"structure"` + + // The margin settings that apply around the outside edge of sheets. + Margin *MarginStyle `type:"structure"` } // String returns the string representation -func (s SslProperties) String() string { +func (s TileLayoutStyle) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s SslProperties) GoString() string { +func (s TileLayoutStyle) GoString() string { return s.String() } -// SetDisableSsl sets the DisableSsl field's value. -func (s *SslProperties) SetDisableSsl(v bool) *SslProperties { - s.DisableSsl = &v +// SetGutter sets the Gutter field's value. +func (s *TileLayoutStyle) SetGutter(v *GutterStyle) *TileLayoutStyle { + s.Gutter = v return s } -// String parameter. -type StringParameter struct { - _ struct{} `type:"structure"` +// SetMargin sets the Margin field's value. +func (s *TileLayoutStyle) SetMargin(v *MarginStyle) *TileLayoutStyle { + s.Margin = v + return s +} - // A display name for the dataset. - // - // Name is a required field - Name *string `type:"string" required:"true"` +// Display options related to tiles on a sheet. +type TileStyle struct { + _ struct{} `type:"structure"` - // Values. - // - // Values is a required field - Values []*string `type:"list" required:"true"` + // The border around a tile. + Border *BorderStyle `type:"structure"` } // String returns the string representation -func (s StringParameter) String() string { +func (s TileStyle) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s StringParameter) GoString() string { +func (s TileStyle) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *StringParameter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StringParameter"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Values == nil { - invalidParams.Add(request.NewErrParamRequired("Values")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetName sets the Name field's value. -func (s *StringParameter) SetName(v string) *StringParameter { - s.Name = &v - return s -} - -// SetValues sets the Values field's value. -func (s *StringParameter) SetValues(v []*string) *StringParameter { - s.Values = v +// SetBorder sets the Border field's value. +func (s *TileStyle) SetBorder(v *BorderStyle) *TileStyle { + s.Border = v return s } -// The key or keys of the key-value pairs for the resource tag or tags assigned -// to the resource. -type Tag struct { +// A data transformation on a logical table. This is a variant type structure. +// For this structure to be valid, only one of the attributes can be non-null. +type TransformOperation struct { _ struct{} `type:"structure"` - // Tag key. - // - // Key is a required field - Key *string `min:"1" type:"string" required:"true"` + // A transform operation that casts a column to a different type. + CastColumnTypeOperation *CastColumnTypeOperation `type:"structure"` - // Tag value. - // - // Value is a required field - Value *string `min:"1" type:"string" required:"true"` + // An operation that creates calculated columns. Columns created in one such + // operation form a lexical closure. + CreateColumnsOperation *CreateColumnsOperation `type:"structure"` + + // An operation that filters rows based on some condition. + FilterOperation *FilterOperation `type:"structure"` + + // An operation that projects columns. Operations that come after a projection + // can only refer to projected columns. + ProjectOperation *ProjectOperation `type:"structure"` + + // An operation that renames a column. + RenameColumnOperation *RenameColumnOperation `type:"structure"` + + // An operation that tags a column with additional information. + TagColumnOperation *TagColumnOperation `type:"structure"` } // String returns the string representation -func (s Tag) String() string { +func (s TransformOperation) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Tag) GoString() string { +func (s TransformOperation) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *Tag) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Tag"} - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) +func (s *TransformOperation) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TransformOperation"} + if s.CastColumnTypeOperation != nil { + if err := s.CastColumnTypeOperation.Validate(); err != nil { + invalidParams.AddNested("CastColumnTypeOperation", err.(request.ErrInvalidParams)) + } } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + if s.CreateColumnsOperation != nil { + if err := s.CreateColumnsOperation.Validate(); err != nil { + invalidParams.AddNested("CreateColumnsOperation", err.(request.ErrInvalidParams)) + } } - if s.Value == nil { - invalidParams.Add(request.NewErrParamRequired("Value")) + if s.FilterOperation != nil { + if err := s.FilterOperation.Validate(); err != nil { + invalidParams.AddNested("FilterOperation", err.(request.ErrInvalidParams)) + } } - if s.Value != nil && len(*s.Value) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Value", 1)) + if s.ProjectOperation != nil { + if err := s.ProjectOperation.Validate(); err != nil { + invalidParams.AddNested("ProjectOperation", err.(request.ErrInvalidParams)) + } + } + if s.RenameColumnOperation != nil { + if err := s.RenameColumnOperation.Validate(); err != nil { + invalidParams.AddNested("RenameColumnOperation", err.(request.ErrInvalidParams)) + } + } + if s.TagColumnOperation != nil { + if err := s.TagColumnOperation.Validate(); err != nil { + invalidParams.AddNested("TagColumnOperation", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -19741,128 +26585,81 @@ func (s *Tag) Validate() error { return nil } -// SetKey sets the Key field's value. -func (s *Tag) SetKey(v string) *Tag { - s.Key = &v +// SetCastColumnTypeOperation sets the CastColumnTypeOperation field's value. +func (s *TransformOperation) SetCastColumnTypeOperation(v *CastColumnTypeOperation) *TransformOperation { + s.CastColumnTypeOperation = v return s } -// SetValue sets the Value field's value. -func (s *Tag) SetValue(v string) *Tag { - s.Value = &v +// SetCreateColumnsOperation sets the CreateColumnsOperation field's value. +func (s *TransformOperation) SetCreateColumnsOperation(v *CreateColumnsOperation) *TransformOperation { + s.CreateColumnsOperation = v return s } -// A transform operation that tags a column with additional information. -type TagColumnOperation struct { - _ struct{} `type:"structure"` - - // The column that this operation acts on. - // - // ColumnName is a required field - ColumnName *string `min:"1" type:"string" required:"true"` - - // The dataset column tag, currently only used for geospatial type tagging. . - // - // This is not tags for the AWS tagging feature. . - // - // Tags is a required field - Tags []*ColumnTag `min:"1" type:"list" required:"true"` -} - -// String returns the string representation -func (s TagColumnOperation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TagColumnOperation) GoString() string { - return s.String() +// SetFilterOperation sets the FilterOperation field's value. +func (s *TransformOperation) SetFilterOperation(v *FilterOperation) *TransformOperation { + s.FilterOperation = v + return s } -// Validate inspects the fields of the type to determine if they are valid. -func (s *TagColumnOperation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TagColumnOperation"} - if s.ColumnName == nil { - invalidParams.Add(request.NewErrParamRequired("ColumnName")) - } - if s.ColumnName != nil && len(*s.ColumnName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ColumnName", 1)) - } - if s.Tags == nil { - invalidParams.Add(request.NewErrParamRequired("Tags")) - } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetProjectOperation sets the ProjectOperation field's value. +func (s *TransformOperation) SetProjectOperation(v *ProjectOperation) *TransformOperation { + s.ProjectOperation = v + return s } -// SetColumnName sets the ColumnName field's value. -func (s *TagColumnOperation) SetColumnName(v string) *TagColumnOperation { - s.ColumnName = &v +// SetRenameColumnOperation sets the RenameColumnOperation field's value. +func (s *TransformOperation) SetRenameColumnOperation(v *RenameColumnOperation) *TransformOperation { + s.RenameColumnOperation = v return s } -// SetTags sets the Tags field's value. -func (s *TagColumnOperation) SetTags(v []*ColumnTag) *TagColumnOperation { - s.Tags = v +// SetTagColumnOperation sets the TagColumnOperation field's value. +func (s *TransformOperation) SetTagColumnOperation(v *TagColumnOperation) *TransformOperation { + s.TagColumnOperation = v return s } -type TagResourceInput struct { +// Twitter parameters. +type TwitterParameters struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource that you want to tag. + // Maximum number of rows to query Twitter. // - // ResourceArn is a required field - ResourceArn *string `location:"uri" locationName:"ResourceArn" type:"string" required:"true"` + // MaxRows is a required field + MaxRows *int64 `min:"1" type:"integer" required:"true"` - // Contains a map of the key-value pairs for the resource tag or tags assigned - // to the resource. + // Twitter query string. // - // Tags is a required field - Tags []*Tag `min:"1" type:"list" required:"true"` + // Query is a required field + Query *string `min:"1" type:"string" required:"true"` } // String returns the string representation -func (s TagResourceInput) String() string { +func (s TwitterParameters) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TagResourceInput) GoString() string { +func (s TwitterParameters) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *TagResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"} - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) - } - if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) +func (s *TwitterParameters) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TwitterParameters"} + if s.MaxRows == nil { + invalidParams.Add(request.NewErrParamRequired("MaxRows")) } - if s.Tags == nil { - invalidParams.Add(request.NewErrParamRequired("Tags")) + if s.MaxRows != nil && *s.MaxRows < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxRows", 1)) } - if s.Tags != nil && len(s.Tags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + if s.Query == nil { + invalidParams.Add(request.NewErrParamRequired("Query")) } - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } + if s.Query != nil && len(*s.Query) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Query", 1)) } if invalidParams.Len() > 0 { @@ -19871,249 +26668,292 @@ func (s *TagResourceInput) Validate() error { return nil } -// SetResourceArn sets the ResourceArn field's value. -func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput { - s.ResourceArn = &v +// SetMaxRows sets the MaxRows field's value. +func (s *TwitterParameters) SetMaxRows(v int64) *TwitterParameters { + s.MaxRows = &v return s } -// SetTags sets the Tags field's value. -func (s *TagResourceInput) SetTags(v []*Tag) *TagResourceInput { - s.Tags = v +// SetQuery sets the Query field's value. +func (s *TwitterParameters) SetQuery(v string) *TwitterParameters { + s.Query = &v return s } -type TagResourceOutput struct { +// The theme colors that apply to UI and to charts, excluding data colors. The +// colors description is a hexidecimal color code that consists of six alphanumerical +// characters, prefixed with #, for example #37BFF5. For more information, see +// Using Themes in Amazon QuickSight (https://docs.aws.amazon.com/quicksight/latest/user/themes-in-quicksight.html) +// in the Amazon QuickSight User Guide. +type UIColorPalette struct { _ struct{} `type:"structure"` - // The AWS request ID for this operation. - RequestId *string `type:"string"` + // This color is that applies to selected states and buttons. + Accent *string `type:"string"` - // The HTTP status of the request. - Status *int64 `location:"statusCode" type:"integer"` -} + // The foreground color that applies to any text or other elements that appear + // over the accent color. + AccentForeground *string `type:"string"` -// String returns the string representation -func (s TagResourceOutput) String() string { - return awsutil.Prettify(s) -} + // The color that applies to error messages. + Danger *string `type:"string"` -// GoString returns the string representation -func (s TagResourceOutput) GoString() string { - return s.String() -} + // The foreground color that applies to any text or other elements that appear + // over the error color. + DangerForeground *string `type:"string"` -// SetRequestId sets the RequestId field's value. -func (s *TagResourceOutput) SetRequestId(v string) *TagResourceOutput { - s.RequestId = &v - return s -} + // The color that applies to the names of fields that are identified as dimensions. + Dimension *string `type:"string"` -// SetStatus sets the Status field's value. -func (s *TagResourceOutput) SetStatus(v int64) *TagResourceOutput { - s.Status = &v - return s -} + // The foreground color that applies to any text or other elements that appear + // over the dimension color. + DimensionForeground *string `type:"string"` -// A template object. A template is an entity in QuickSight that encapsulates -// the metadata required to create an analysis and that you can use to create -// a dashboard. A template adds a layer of abstraction by using placeholders -// to replace the dataset associated with the analysis. You can use templates -// to create dashboards by replacing dataset placeholders with datasets that -// follow the same schema that was used to create the source analysis and template. -// -// You can share templates across AWS accounts by allowing users in other AWS -// accounts to create a template or a dashboard from an existing template. -type Template struct { - _ struct{} `type:"structure"` + // The color that applies to the names of fields that are identified as measures. + Measure *string `type:"string"` - // The Amazon Resource Name (ARN) of the template. - Arn *string `type:"string"` + // The foreground color that applies to any text or other elements that appear + // over the measure color. + MeasureForeground *string `type:"string"` - // Time when this was created. - CreatedTime *time.Time `type:"timestamp"` + // The background color that applies to visuals and other high emphasis UI. + PrimaryBackground *string `type:"string"` - // Time when this was last updated. - LastUpdatedTime *time.Time `type:"timestamp"` + // The color of text and other foreground elements that appear over the primary + // background regions, such as grid lines, borders, table banding, icons, and + // so on. + PrimaryForeground *string `type:"string"` - // The display name of the template. - Name *string `min:"1" type:"string"` + // The background color that applies to the sheet background and sheet controls. + SecondaryBackground *string `type:"string"` - // The ID for the template. This is unique per AWS Region for each AWS account. - TemplateId *string `min:"1" type:"string"` + // The foreground color that applies to any sheet title, sheet control text, + // or UI that appears over the secondary background. + SecondaryForeground *string `type:"string"` - // A structure describing the versions of the template. - Version *TemplateVersion `type:"structure"` + // The color that applies to success messages, for example the check mark for + // a successful download. + Success *string `type:"string"` + + // The foreground color that applies to any text or other elements that appear + // over the success color. + SuccessForeground *string `type:"string"` + + // This color that applies to warning and informational messages. + Warning *string `type:"string"` + + // The foreground color that applies to any text or other elements that appear + // over the warning color. + WarningForeground *string `type:"string"` } // String returns the string representation -func (s Template) String() string { +func (s UIColorPalette) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Template) GoString() string { +func (s UIColorPalette) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *Template) SetArn(v string) *Template { - s.Arn = &v +// SetAccent sets the Accent field's value. +func (s *UIColorPalette) SetAccent(v string) *UIColorPalette { + s.Accent = &v return s } -// SetCreatedTime sets the CreatedTime field's value. -func (s *Template) SetCreatedTime(v time.Time) *Template { - s.CreatedTime = &v +// SetAccentForeground sets the AccentForeground field's value. +func (s *UIColorPalette) SetAccentForeground(v string) *UIColorPalette { + s.AccentForeground = &v return s } -// SetLastUpdatedTime sets the LastUpdatedTime field's value. -func (s *Template) SetLastUpdatedTime(v time.Time) *Template { - s.LastUpdatedTime = &v +// SetDanger sets the Danger field's value. +func (s *UIColorPalette) SetDanger(v string) *UIColorPalette { + s.Danger = &v return s } -// SetName sets the Name field's value. -func (s *Template) SetName(v string) *Template { - s.Name = &v +// SetDangerForeground sets the DangerForeground field's value. +func (s *UIColorPalette) SetDangerForeground(v string) *UIColorPalette { + s.DangerForeground = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *Template) SetTemplateId(v string) *Template { - s.TemplateId = &v +// SetDimension sets the Dimension field's value. +func (s *UIColorPalette) SetDimension(v string) *UIColorPalette { + s.Dimension = &v return s } -// SetVersion sets the Version field's value. -func (s *Template) SetVersion(v *TemplateVersion) *Template { - s.Version = v +// SetDimensionForeground sets the DimensionForeground field's value. +func (s *UIColorPalette) SetDimensionForeground(v string) *UIColorPalette { + s.DimensionForeground = &v return s } -// The template alias. -type TemplateAlias struct { - _ struct{} `type:"structure"` +// SetMeasure sets the Measure field's value. +func (s *UIColorPalette) SetMeasure(v string) *UIColorPalette { + s.Measure = &v + return s +} - // The display name of the template alias. - AliasName *string `min:"1" type:"string"` +// SetMeasureForeground sets the MeasureForeground field's value. +func (s *UIColorPalette) SetMeasureForeground(v string) *UIColorPalette { + s.MeasureForeground = &v + return s +} - // The Amazon Resource Name (ARN) of the template alias. - Arn *string `type:"string"` +// SetPrimaryBackground sets the PrimaryBackground field's value. +func (s *UIColorPalette) SetPrimaryBackground(v string) *UIColorPalette { + s.PrimaryBackground = &v + return s +} - // The version number of the template alias. - TemplateVersionNumber *int64 `min:"1" type:"long"` +// SetPrimaryForeground sets the PrimaryForeground field's value. +func (s *UIColorPalette) SetPrimaryForeground(v string) *UIColorPalette { + s.PrimaryForeground = &v + return s } -// String returns the string representation -func (s TemplateAlias) String() string { - return awsutil.Prettify(s) +// SetSecondaryBackground sets the SecondaryBackground field's value. +func (s *UIColorPalette) SetSecondaryBackground(v string) *UIColorPalette { + s.SecondaryBackground = &v + return s } -// GoString returns the string representation -func (s TemplateAlias) GoString() string { - return s.String() +// SetSecondaryForeground sets the SecondaryForeground field's value. +func (s *UIColorPalette) SetSecondaryForeground(v string) *UIColorPalette { + s.SecondaryForeground = &v + return s } -// SetAliasName sets the AliasName field's value. -func (s *TemplateAlias) SetAliasName(v string) *TemplateAlias { - s.AliasName = &v +// SetSuccess sets the Success field's value. +func (s *UIColorPalette) SetSuccess(v string) *UIColorPalette { + s.Success = &v return s } -// SetArn sets the Arn field's value. -func (s *TemplateAlias) SetArn(v string) *TemplateAlias { - s.Arn = &v +// SetSuccessForeground sets the SuccessForeground field's value. +func (s *UIColorPalette) SetSuccessForeground(v string) *UIColorPalette { + s.SuccessForeground = &v return s } -// SetTemplateVersionNumber sets the TemplateVersionNumber field's value. -func (s *TemplateAlias) SetTemplateVersionNumber(v int64) *TemplateAlias { - s.TemplateVersionNumber = &v +// SetWarning sets the Warning field's value. +func (s *UIColorPalette) SetWarning(v string) *UIColorPalette { + s.Warning = &v return s } -// List of errors that occurred when the template version creation failed. -type TemplateError struct { - _ struct{} `type:"structure"` +// SetWarningForeground sets the WarningForeground field's value. +func (s *UIColorPalette) SetWarningForeground(v string) *UIColorPalette { + s.WarningForeground = &v + return s +} - // Description of the error type. - Message *string `type:"string"` +// This error indicates that you are calling an operation on an Amazon QuickSight +// subscription where the edition doesn't include support for that operation. +// Amazon QuickSight currently has Standard Edition and Enterprise Edition. +// Not every operation and capability is available in every edition. +type UnsupportedUserEditionException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - // Type of error. - Type *string `type:"string" enum:"TemplateErrorType"` + Message_ *string `locationName:"Message" type:"string"` + + // The AWS request ID for this request. + RequestId *string `type:"string"` } // String returns the string representation -func (s TemplateError) String() string { +func (s UnsupportedUserEditionException) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TemplateError) GoString() string { +func (s UnsupportedUserEditionException) GoString() string { return s.String() } -// SetMessage sets the Message field's value. -func (s *TemplateError) SetMessage(v string) *TemplateError { - s.Message = &v - return s +func newErrorUnsupportedUserEditionException(v protocol.ResponseMetadata) error { + return &UnsupportedUserEditionException{ + RespMetadata: v, + } } -// SetType sets the Type field's value. -func (s *TemplateError) SetType(v string) *TemplateError { - s.Type = &v - return s +// Code returns the exception type name. +func (s *UnsupportedUserEditionException) Code() string { + return "UnsupportedUserEditionException" } -// The source analysis of the template. -type TemplateSourceAnalysis struct { +// Message returns the exception's message. +func (s *UnsupportedUserEditionException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *UnsupportedUserEditionException) OrigErr() error { + return nil +} + +func (s *UnsupportedUserEditionException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *UnsupportedUserEditionException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *UnsupportedUserEditionException) RequestID() string { + return s.RespMetadata.RequestID +} + +type UntagResourceInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. + // The Amazon Resource Name (ARN) of the resource that you want to untag. // - // Arn is a required field - Arn *string `type:"string" required:"true"` + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"ResourceArn" type:"string" required:"true"` - // A structure containing information about the dataset references used as placeholders - // in the template. + // The keys of the key-value pairs for the resource tag or tags assigned to + // the resource. // - // DataSetReferences is a required field - DataSetReferences []*DataSetReference `min:"1" type:"list" required:"true"` + // TagKeys is a required field + TagKeys []*string `location:"querystring" locationName:"keys" min:"1" type:"list" required:"true"` } // String returns the string representation -func (s TemplateSourceAnalysis) String() string { +func (s UntagResourceInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TemplateSourceAnalysis) GoString() string { +func (s UntagResourceInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *TemplateSourceAnalysis) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TemplateSourceAnalysis"} - if s.Arn == nil { - invalidParams.Add(request.NewErrParamRequired("Arn")) +func (s *UntagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) } - if s.DataSetReferences == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetReferences")) + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) } - if s.DataSetReferences != nil && len(s.DataSetReferences) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetReferences", 1)) + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) } - if s.DataSetReferences != nil { - for i, v := range s.DataSetReferences { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "DataSetReferences", i), err.(request.ErrInvalidParams)) - } - } + if s.TagKeys != nil && len(s.TagKeys) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TagKeys", 1)) } if invalidParams.Len() > 0 { @@ -20122,96 +26962,89 @@ func (s *TemplateSourceAnalysis) Validate() error { return nil } -// SetArn sets the Arn field's value. -func (s *TemplateSourceAnalysis) SetArn(v string) *TemplateSourceAnalysis { - s.Arn = &v +// SetResourceArn sets the ResourceArn field's value. +func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { + s.ResourceArn = &v return s } -// SetDataSetReferences sets the DataSetReferences field's value. -func (s *TemplateSourceAnalysis) SetDataSetReferences(v []*DataSetReference) *TemplateSourceAnalysis { - s.DataSetReferences = v +// SetTagKeys sets the TagKeys field's value. +func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { + s.TagKeys = v return s } -// The source entity of the template. -type TemplateSourceEntity struct { +type UntagResourceOutput struct { _ struct{} `type:"structure"` - // The source analysis, if it is based on an analysis. - SourceAnalysis *TemplateSourceAnalysis `type:"structure"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // The source template, if it is based on an template. - SourceTemplate *TemplateSourceTemplate `type:"structure"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s TemplateSourceEntity) String() string { +func (s UntagResourceOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TemplateSourceEntity) GoString() string { +func (s UntagResourceOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *TemplateSourceEntity) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TemplateSourceEntity"} - if s.SourceAnalysis != nil { - if err := s.SourceAnalysis.Validate(); err != nil { - invalidParams.AddNested("SourceAnalysis", err.(request.ErrInvalidParams)) - } - } - if s.SourceTemplate != nil { - if err := s.SourceTemplate.Validate(); err != nil { - invalidParams.AddNested("SourceTemplate", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetSourceAnalysis sets the SourceAnalysis field's value. -func (s *TemplateSourceEntity) SetSourceAnalysis(v *TemplateSourceAnalysis) *TemplateSourceEntity { - s.SourceAnalysis = v +// SetRequestId sets the RequestId field's value. +func (s *UntagResourceOutput) SetRequestId(v string) *UntagResourceOutput { + s.RequestId = &v return s } -// SetSourceTemplate sets the SourceTemplate field's value. -func (s *TemplateSourceEntity) SetSourceTemplate(v *TemplateSourceTemplate) *TemplateSourceEntity { - s.SourceTemplate = v +// SetStatus sets the Status field's value. +func (s *UntagResourceOutput) SetStatus(v int64) *UntagResourceOutput { + s.Status = &v return s } -// The source template of the template. -type TemplateSourceTemplate struct { +type UpdateAccountCustomizationInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. + // The customizations you want to update in QuickSight. // - // Arn is a required field - Arn *string `type:"string" required:"true"` + // AccountCustomization is a required field + AccountCustomization *AccountCustomization `type:"structure" required:"true"` + + // The ID for the AWS account that you want to update QuickSight customizations + // for. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + + // The namespace associated with the customization that you're updating. + Namespace *string `location:"querystring" locationName:"namespace" type:"string"` } // String returns the string representation -func (s TemplateSourceTemplate) String() string { +func (s UpdateAccountCustomizationInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TemplateSourceTemplate) GoString() string { +func (s UpdateAccountCustomizationInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *TemplateSourceTemplate) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TemplateSourceTemplate"} - if s.Arn == nil { - invalidParams.Add(request.NewErrParamRequired("Arn")) +func (s *UpdateAccountCustomizationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateAccountCustomizationInput"} + if s.AccountCustomization == nil { + invalidParams.Add(request.NewErrParamRequired("AccountCustomization")) + } + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } if invalidParams.Len() > 0 { @@ -20220,272 +27053,293 @@ func (s *TemplateSourceTemplate) Validate() error { return nil } -// SetArn sets the Arn field's value. -func (s *TemplateSourceTemplate) SetArn(v string) *TemplateSourceTemplate { - s.Arn = &v +// SetAccountCustomization sets the AccountCustomization field's value. +func (s *UpdateAccountCustomizationInput) SetAccountCustomization(v *AccountCustomization) *UpdateAccountCustomizationInput { + s.AccountCustomization = v return s } -// The template summary. -type TemplateSummary struct { - _ struct{} `type:"structure"` +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *UpdateAccountCustomizationInput) SetAwsAccountId(v string) *UpdateAccountCustomizationInput { + s.AwsAccountId = &v + return s +} - // A summary of a template. - Arn *string `type:"string"` +// SetNamespace sets the Namespace field's value. +func (s *UpdateAccountCustomizationInput) SetNamespace(v string) *UpdateAccountCustomizationInput { + s.Namespace = &v + return s +} - // The last time that this template was created. - CreatedTime *time.Time `type:"timestamp"` +type UpdateAccountCustomizationOutput struct { + _ struct{} `type:"structure"` - // The last time that this template was updated. - LastUpdatedTime *time.Time `type:"timestamp"` + // The customizations associated with your QuickSight subscription. + AccountCustomization *AccountCustomization `type:"structure"` - // A structure containing a list of version numbers for the template summary. - LatestVersionNumber *int64 `min:"1" type:"long"` + // The ID for the AWS account that you want to update QuickSight customizations + // for. + AwsAccountId *string `min:"12" type:"string"` - // A display name for the template. - Name *string `min:"1" type:"string"` + // The namespace associated with the customization that you're updating. + Namespace *string `type:"string"` - // The ID of the template. This ID is unique per AWS Region for each AWS account. - TemplateId *string `min:"1" type:"string"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s TemplateSummary) String() string { +func (s UpdateAccountCustomizationOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TemplateSummary) GoString() string { +func (s UpdateAccountCustomizationOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *TemplateSummary) SetArn(v string) *TemplateSummary { - s.Arn = &v - return s -} - -// SetCreatedTime sets the CreatedTime field's value. -func (s *TemplateSummary) SetCreatedTime(v time.Time) *TemplateSummary { - s.CreatedTime = &v +// SetAccountCustomization sets the AccountCustomization field's value. +func (s *UpdateAccountCustomizationOutput) SetAccountCustomization(v *AccountCustomization) *UpdateAccountCustomizationOutput { + s.AccountCustomization = v return s } -// SetLastUpdatedTime sets the LastUpdatedTime field's value. -func (s *TemplateSummary) SetLastUpdatedTime(v time.Time) *TemplateSummary { - s.LastUpdatedTime = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *UpdateAccountCustomizationOutput) SetAwsAccountId(v string) *UpdateAccountCustomizationOutput { + s.AwsAccountId = &v return s } -// SetLatestVersionNumber sets the LatestVersionNumber field's value. -func (s *TemplateSummary) SetLatestVersionNumber(v int64) *TemplateSummary { - s.LatestVersionNumber = &v +// SetNamespace sets the Namespace field's value. +func (s *UpdateAccountCustomizationOutput) SetNamespace(v string) *UpdateAccountCustomizationOutput { + s.Namespace = &v return s } -// SetName sets the Name field's value. -func (s *TemplateSummary) SetName(v string) *TemplateSummary { - s.Name = &v +// SetRequestId sets the RequestId field's value. +func (s *UpdateAccountCustomizationOutput) SetRequestId(v string) *UpdateAccountCustomizationOutput { + s.RequestId = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *TemplateSummary) SetTemplateId(v string) *TemplateSummary { - s.TemplateId = &v +// SetStatus sets the Status field's value. +func (s *UpdateAccountCustomizationOutput) SetStatus(v int64) *UpdateAccountCustomizationOutput { + s.Status = &v return s } -// A version of a template. -type TemplateVersion struct { +type UpdateAccountSettingsInput struct { _ struct{} `type:"structure"` - // The time that this template version was created. - CreatedTime *time.Time `type:"timestamp"` - - // Schema of the dataset identified by the placeholder. The idea is that any - // dashboard created from the template should be bound to new datasets matching - // the same schema described through this API. . - DataSetConfigurations []*DataSetConfiguration `type:"list"` - - // The description of the template. - Description *string `min:"1" type:"string"` - - // Errors associated with the template. - Errors []*TemplateError `min:"1" type:"list"` - - // The Amazon Resource Name (ARN) of the analysis or template which was used - // to create this template. - SourceEntityArn *string `type:"string"` + // The ID for the AWS account that contains the QuickSight namespaces that you + // want to list. + // + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The HTTP status of the request. - Status *string `type:"string" enum:"ResourceStatus"` + // The default namespace for this AWS Account. Currently, the default is default. + // IAM users who register for the first time with QuickSight provide an email + // that becomes associated with the default namespace. + // + // DefaultNamespace is a required field + DefaultNamespace *string `type:"string" required:"true"` - // The version number of the template. - VersionNumber *int64 `min:"1" type:"long"` + // Email address used to send notifications regarding administration of QuickSight. + NotificationEmail *string `type:"string"` } // String returns the string representation -func (s TemplateVersion) String() string { +func (s UpdateAccountSettingsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TemplateVersion) GoString() string { +func (s UpdateAccountSettingsInput) GoString() string { return s.String() } -// SetCreatedTime sets the CreatedTime field's value. -func (s *TemplateVersion) SetCreatedTime(v time.Time) *TemplateVersion { - s.CreatedTime = &v - return s -} - -// SetDataSetConfigurations sets the DataSetConfigurations field's value. -func (s *TemplateVersion) SetDataSetConfigurations(v []*DataSetConfiguration) *TemplateVersion { - s.DataSetConfigurations = v - return s -} - -// SetDescription sets the Description field's value. -func (s *TemplateVersion) SetDescription(v string) *TemplateVersion { - s.Description = &v - return s -} +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateAccountSettingsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateAccountSettingsInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) + } + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) + } + if s.DefaultNamespace == nil { + invalidParams.Add(request.NewErrParamRequired("DefaultNamespace")) + } -// SetErrors sets the Errors field's value. -func (s *TemplateVersion) SetErrors(v []*TemplateError) *TemplateVersion { - s.Errors = v - return s + if invalidParams.Len() > 0 { + return invalidParams + } + return nil } -// SetSourceEntityArn sets the SourceEntityArn field's value. -func (s *TemplateVersion) SetSourceEntityArn(v string) *TemplateVersion { - s.SourceEntityArn = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *UpdateAccountSettingsInput) SetAwsAccountId(v string) *UpdateAccountSettingsInput { + s.AwsAccountId = &v return s } -// SetStatus sets the Status field's value. -func (s *TemplateVersion) SetStatus(v string) *TemplateVersion { - s.Status = &v +// SetDefaultNamespace sets the DefaultNamespace field's value. +func (s *UpdateAccountSettingsInput) SetDefaultNamespace(v string) *UpdateAccountSettingsInput { + s.DefaultNamespace = &v return s } -// SetVersionNumber sets the VersionNumber field's value. -func (s *TemplateVersion) SetVersionNumber(v int64) *TemplateVersion { - s.VersionNumber = &v +// SetNotificationEmail sets the NotificationEmail field's value. +func (s *UpdateAccountSettingsInput) SetNotificationEmail(v string) *UpdateAccountSettingsInput { + s.NotificationEmail = &v return s } -// The template version. -type TemplateVersionSummary struct { +type UpdateAccountSettingsOutput struct { _ struct{} `type:"structure"` - // The ARN of the template version. - Arn *string `type:"string"` - - // The time that this template version was created. - CreatedTime *time.Time `type:"timestamp"` - - // The description of the template version. - Description *string `min:"1" type:"string"` - - // The status of the template version. - Status *string `type:"string" enum:"ResourceStatus"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // The version number of the template version. - VersionNumber *int64 `min:"1" type:"long"` + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s TemplateVersionSummary) String() string { +func (s UpdateAccountSettingsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TemplateVersionSummary) GoString() string { +func (s UpdateAccountSettingsOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *TemplateVersionSummary) SetArn(v string) *TemplateVersionSummary { - s.Arn = &v - return s -} - -// SetCreatedTime sets the CreatedTime field's value. -func (s *TemplateVersionSummary) SetCreatedTime(v time.Time) *TemplateVersionSummary { - s.CreatedTime = &v - return s -} - -// SetDescription sets the Description field's value. -func (s *TemplateVersionSummary) SetDescription(v string) *TemplateVersionSummary { - s.Description = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *TemplateVersionSummary) SetStatus(v string) *TemplateVersionSummary { - s.Status = &v +// SetRequestId sets the RequestId field's value. +func (s *UpdateAccountSettingsOutput) SetRequestId(v string) *UpdateAccountSettingsOutput { + s.RequestId = &v return s } -// SetVersionNumber sets the VersionNumber field's value. -func (s *TemplateVersionSummary) SetVersionNumber(v int64) *TemplateVersionSummary { - s.VersionNumber = &v +// SetStatus sets the Status field's value. +func (s *UpdateAccountSettingsOutput) SetStatus(v int64) *UpdateAccountSettingsOutput { + s.Status = &v return s } -// Teradata parameters. -type TeradataParameters struct { +type UpdateDashboardInput struct { _ struct{} `type:"structure"` - // Database. + // The ID of the AWS account that contains the dashboard that you're updating. // - // Database is a required field - Database *string `min:"1" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Host. + // The ID for the dashboard. // - // Host is a required field - Host *string `min:"1" type:"string" required:"true"` + // DashboardId is a required field + DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` - // Port. + // Options for publishing the dashboard when you create it: // - // Port is a required field - Port *int64 `min:"1" type:"integer" required:"true"` + // * AvailabilityStatus for AdHocFilteringOption - This status can be either + // ENABLED or DISABLED. When this is set to DISABLED, QuickSight disables + // the left filter pane on the published dashboard, which can be used for + // ad hoc (one-time) filtering. This option is ENABLED by default. + // + // * AvailabilityStatus for ExportToCSVOption - This status can be either + // ENABLED or DISABLED. The visual option to export data to .csv format isn't + // enabled when this is set to DISABLED. This option is ENABLED by default. + // + // * VisibilityState for SheetControlsOption - This visibility state can + // be either COLLAPSED or EXPANDED. This option is COLLAPSED by default. + DashboardPublishOptions *DashboardPublishOptions `type:"structure"` + + // The display name of the dashboard. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // A structure that contains the parameters of the dashboard. These are parameter + // overrides for a dashboard. A dashboard can have any type of parameters, and + // some parameters might accept multiple values. + Parameters *Parameters `type:"structure"` + + // The entity that you are using as a source when you update the dashboard. + // In SourceEntity, you specify the type of object you're using as source. You + // can only update a dashboard from a template, so you use a SourceTemplate + // entity. If you need to update a dashboard from an analysis, first convert + // the analysis to a template by using the CreateTemplate API operation. For + // SourceTemplate, specify the Amazon Resource Name (ARN) of the source template. + // The SourceTemplate ARN can contain any AWS Account and any QuickSight-supported + // AWS Region. + // + // Use the DataSetReferences entity within SourceTemplate to list the replacement + // datasets for the placeholders listed in the original. The schema in each + // dataset must match its placeholder. + // + // SourceEntity is a required field + SourceEntity *DashboardSourceEntity `type:"structure" required:"true"` + + // The Amazon Resource Name (ARN) of the theme that is being used for this dashboard. + // If you add a value for this field, it overrides the value that was originally + // associated with the entity. The theme ARN must exist in the same AWS account + // where you create the dashboard. + ThemeArn *string `type:"string"` + + // A description for the first version of the dashboard being created. + VersionDescription *string `min:"1" type:"string"` } // String returns the string representation -func (s TeradataParameters) String() string { +func (s UpdateDashboardInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TeradataParameters) GoString() string { +func (s UpdateDashboardInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *TeradataParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TeradataParameters"} - if s.Database == nil { - invalidParams.Add(request.NewErrParamRequired("Database")) +func (s *UpdateDashboardInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateDashboardInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.Database != nil && len(*s.Database) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Database", 1)) + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Host == nil { - invalidParams.Add(request.NewErrParamRequired("Host")) + if s.DashboardId == nil { + invalidParams.Add(request.NewErrParamRequired("DashboardId")) } - if s.Host != nil && len(*s.Host) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Host", 1)) + if s.DashboardId != nil && len(*s.DashboardId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) } - if s.Port == nil { - invalidParams.Add(request.NewErrParamRequired("Port")) + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.SourceEntity == nil { + invalidParams.Add(request.NewErrParamRequired("SourceEntity")) + } + if s.VersionDescription != nil && len(*s.VersionDescription) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VersionDescription", 1)) + } + if s.Parameters != nil { + if err := s.Parameters.Validate(); err != nil { + invalidParams.AddNested("Parameters", err.(request.ErrInvalidParams)) + } + } + if s.SourceEntity != nil { + if err := s.SourceEntity.Validate(); err != nil { + invalidParams.AddNested("SourceEntity", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -20494,234 +27348,187 @@ func (s *TeradataParameters) Validate() error { return nil } -// SetDatabase sets the Database field's value. -func (s *TeradataParameters) SetDatabase(v string) *TeradataParameters { - s.Database = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *UpdateDashboardInput) SetAwsAccountId(v string) *UpdateDashboardInput { + s.AwsAccountId = &v return s } -// SetHost sets the Host field's value. -func (s *TeradataParameters) SetHost(v string) *TeradataParameters { - s.Host = &v +// SetDashboardId sets the DashboardId field's value. +func (s *UpdateDashboardInput) SetDashboardId(v string) *UpdateDashboardInput { + s.DashboardId = &v return s } -// SetPort sets the Port field's value. -func (s *TeradataParameters) SetPort(v int64) *TeradataParameters { - s.Port = &v +// SetDashboardPublishOptions sets the DashboardPublishOptions field's value. +func (s *UpdateDashboardInput) SetDashboardPublishOptions(v *DashboardPublishOptions) *UpdateDashboardInput { + s.DashboardPublishOptions = v return s } -// Access is throttled. -type ThrottlingException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` - - Message_ *string `locationName:"Message" type:"string"` - - // The AWS request ID for this request. - RequestId *string `type:"string"` -} - -// String returns the string representation -func (s ThrottlingException) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ThrottlingException) GoString() string { - return s.String() -} - -func newErrorThrottlingException(v protocol.ResponseMetadata) error { - return &ThrottlingException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *ThrottlingException) Code() string { - return "ThrottlingException" -} - -// Message returns the exception's message. -func (s *ThrottlingException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" +// SetName sets the Name field's value. +func (s *UpdateDashboardInput) SetName(v string) *UpdateDashboardInput { + s.Name = &v + return s } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *ThrottlingException) OrigErr() error { - return nil +// SetParameters sets the Parameters field's value. +func (s *UpdateDashboardInput) SetParameters(v *Parameters) *UpdateDashboardInput { + s.Parameters = v + return s } -func (s *ThrottlingException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetSourceEntity sets the SourceEntity field's value. +func (s *UpdateDashboardInput) SetSourceEntity(v *DashboardSourceEntity) *UpdateDashboardInput { + s.SourceEntity = v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *ThrottlingException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetThemeArn sets the ThemeArn field's value. +func (s *UpdateDashboardInput) SetThemeArn(v string) *UpdateDashboardInput { + s.ThemeArn = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *ThrottlingException) RequestID() string { - return s.RespMetadata.RequestID +// SetVersionDescription sets the VersionDescription field's value. +func (s *UpdateDashboardInput) SetVersionDescription(v string) *UpdateDashboardInput { + s.VersionDescription = &v + return s } -// A data transformation on a logical table. This is a variant type structure. -// For this structure to be valid, only one of the attributes can be non-null. -type TransformOperation struct { +type UpdateDashboardOutput struct { _ struct{} `type:"structure"` - // A transform operation that casts a column to a different type. - CastColumnTypeOperation *CastColumnTypeOperation `type:"structure"` + // The Amazon Resource Name (ARN) of the resource. + Arn *string `type:"string"` - // An operation that creates calculated columns. Columns created in one such - // operation form a lexical closure. - CreateColumnsOperation *CreateColumnsOperation `type:"structure"` + // The creation status of the request. + CreationStatus *string `type:"string" enum:"ResourceStatus"` - // An operation that filters rows based on some condition. - FilterOperation *FilterOperation `type:"structure"` + // The ID for the dashboard. + DashboardId *string `min:"1" type:"string"` - // An operation that projects columns. Operations that come after a projection - // can only refer to projected columns. - ProjectOperation *ProjectOperation `type:"structure"` + // The AWS request ID for this operation. + RequestId *string `type:"string"` - // An operation that renames a column. - RenameColumnOperation *RenameColumnOperation `type:"structure"` + // The HTTP status of the request. + Status *int64 `type:"integer"` - // An operation that tags a column with additional information. - TagColumnOperation *TagColumnOperation `type:"structure"` + // The ARN of the dashboard, including the version number. + VersionArn *string `type:"string"` } // String returns the string representation -func (s TransformOperation) String() string { +func (s UpdateDashboardOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TransformOperation) GoString() string { +func (s UpdateDashboardOutput) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *TransformOperation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TransformOperation"} - if s.CastColumnTypeOperation != nil { - if err := s.CastColumnTypeOperation.Validate(); err != nil { - invalidParams.AddNested("CastColumnTypeOperation", err.(request.ErrInvalidParams)) - } - } - if s.CreateColumnsOperation != nil { - if err := s.CreateColumnsOperation.Validate(); err != nil { - invalidParams.AddNested("CreateColumnsOperation", err.(request.ErrInvalidParams)) - } - } - if s.FilterOperation != nil { - if err := s.FilterOperation.Validate(); err != nil { - invalidParams.AddNested("FilterOperation", err.(request.ErrInvalidParams)) - } - } - if s.ProjectOperation != nil { - if err := s.ProjectOperation.Validate(); err != nil { - invalidParams.AddNested("ProjectOperation", err.(request.ErrInvalidParams)) - } - } - if s.RenameColumnOperation != nil { - if err := s.RenameColumnOperation.Validate(); err != nil { - invalidParams.AddNested("RenameColumnOperation", err.(request.ErrInvalidParams)) - } - } - if s.TagColumnOperation != nil { - if err := s.TagColumnOperation.Validate(); err != nil { - invalidParams.AddNested("TagColumnOperation", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCastColumnTypeOperation sets the CastColumnTypeOperation field's value. -func (s *TransformOperation) SetCastColumnTypeOperation(v *CastColumnTypeOperation) *TransformOperation { - s.CastColumnTypeOperation = v +// SetArn sets the Arn field's value. +func (s *UpdateDashboardOutput) SetArn(v string) *UpdateDashboardOutput { + s.Arn = &v return s } -// SetCreateColumnsOperation sets the CreateColumnsOperation field's value. -func (s *TransformOperation) SetCreateColumnsOperation(v *CreateColumnsOperation) *TransformOperation { - s.CreateColumnsOperation = v +// SetCreationStatus sets the CreationStatus field's value. +func (s *UpdateDashboardOutput) SetCreationStatus(v string) *UpdateDashboardOutput { + s.CreationStatus = &v return s } -// SetFilterOperation sets the FilterOperation field's value. -func (s *TransformOperation) SetFilterOperation(v *FilterOperation) *TransformOperation { - s.FilterOperation = v +// SetDashboardId sets the DashboardId field's value. +func (s *UpdateDashboardOutput) SetDashboardId(v string) *UpdateDashboardOutput { + s.DashboardId = &v return s } -// SetProjectOperation sets the ProjectOperation field's value. -func (s *TransformOperation) SetProjectOperation(v *ProjectOperation) *TransformOperation { - s.ProjectOperation = v +// SetRequestId sets the RequestId field's value. +func (s *UpdateDashboardOutput) SetRequestId(v string) *UpdateDashboardOutput { + s.RequestId = &v return s } -// SetRenameColumnOperation sets the RenameColumnOperation field's value. -func (s *TransformOperation) SetRenameColumnOperation(v *RenameColumnOperation) *TransformOperation { - s.RenameColumnOperation = v +// SetStatus sets the Status field's value. +func (s *UpdateDashboardOutput) SetStatus(v int64) *UpdateDashboardOutput { + s.Status = &v return s } -// SetTagColumnOperation sets the TagColumnOperation field's value. -func (s *TransformOperation) SetTagColumnOperation(v *TagColumnOperation) *TransformOperation { - s.TagColumnOperation = v +// SetVersionArn sets the VersionArn field's value. +func (s *UpdateDashboardOutput) SetVersionArn(v string) *UpdateDashboardOutput { + s.VersionArn = &v return s } -// Twitter parameters. -type TwitterParameters struct { +type UpdateDashboardPermissionsInput struct { _ struct{} `type:"structure"` - // Maximum number of rows to query Twitter. + // The ID of the AWS account that contains the dashboard whose permissions you're + // updating. // - // MaxRows is a required field - MaxRows *int64 `min:"1" type:"integer" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Twitter query string. + // The ID for the dashboard. // - // Query is a required field - Query *string `min:"1" type:"string" required:"true"` + // DashboardId is a required field + DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` + + // The permissions that you want to grant on this resource. + GrantPermissions []*ResourcePermission `type:"list"` + + // The permissions that you want to revoke from this resource. + RevokePermissions []*ResourcePermission `type:"list"` } // String returns the string representation -func (s TwitterParameters) String() string { +func (s UpdateDashboardPermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s TwitterParameters) GoString() string { +func (s UpdateDashboardPermissionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *TwitterParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TwitterParameters"} - if s.MaxRows == nil { - invalidParams.Add(request.NewErrParamRequired("MaxRows")) +func (s *UpdateDashboardPermissionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateDashboardPermissionsInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.MaxRows != nil && *s.MaxRows < 1 { - invalidParams.Add(request.NewErrParamMinValue("MaxRows", 1)) + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Query == nil { - invalidParams.Add(request.NewErrParamRequired("Query")) + if s.DashboardId == nil { + invalidParams.Add(request.NewErrParamRequired("DashboardId")) } - if s.Query != nil && len(*s.Query) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Query", 1)) + if s.DashboardId != nil && len(*s.DashboardId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) + } + if s.GrantPermissions != nil { + for i, v := range s.GrantPermissions { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "GrantPermissions", i), err.(request.ErrInvalidParams)) + } + } + } + if s.RevokePermissions != nil { + for i, v := range s.RevokePermissions { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RevokePermissions", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -20730,119 +27537,138 @@ func (s *TwitterParameters) Validate() error { return nil } -// SetMaxRows sets the MaxRows field's value. -func (s *TwitterParameters) SetMaxRows(v int64) *TwitterParameters { - s.MaxRows = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *UpdateDashboardPermissionsInput) SetAwsAccountId(v string) *UpdateDashboardPermissionsInput { + s.AwsAccountId = &v return s } -// SetQuery sets the Query field's value. -func (s *TwitterParameters) SetQuery(v string) *TwitterParameters { - s.Query = &v +// SetDashboardId sets the DashboardId field's value. +func (s *UpdateDashboardPermissionsInput) SetDashboardId(v string) *UpdateDashboardPermissionsInput { + s.DashboardId = &v return s } -// This error indicates that you are calling an operation on an Amazon QuickSight -// subscription where the edition doesn't include support for that operation. -// Amazon QuickSight currently has Standard Edition and Enterprise Edition. -// Not every operation and capability is available in every edition. -type UnsupportedUserEditionException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +// SetGrantPermissions sets the GrantPermissions field's value. +func (s *UpdateDashboardPermissionsInput) SetGrantPermissions(v []*ResourcePermission) *UpdateDashboardPermissionsInput { + s.GrantPermissions = v + return s +} - Message_ *string `locationName:"Message" type:"string"` +// SetRevokePermissions sets the RevokePermissions field's value. +func (s *UpdateDashboardPermissionsInput) SetRevokePermissions(v []*ResourcePermission) *UpdateDashboardPermissionsInput { + s.RevokePermissions = v + return s +} - // The AWS request ID for this request. +type UpdateDashboardPermissionsOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the dashboard. + DashboardArn *string `type:"string"` + + // The ID for the dashboard. + DashboardId *string `min:"1" type:"string"` + + // Information about the permissions on the dashboard. + Permissions []*ResourcePermission `min:"1" type:"list"` + + // The AWS request ID for this operation. RequestId *string `type:"string"` + + // The HTTP status of the request. + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s UnsupportedUserEditionException) String() string { +func (s UpdateDashboardPermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UnsupportedUserEditionException) GoString() string { +func (s UpdateDashboardPermissionsOutput) GoString() string { return s.String() } -func newErrorUnsupportedUserEditionException(v protocol.ResponseMetadata) error { - return &UnsupportedUserEditionException{ - RespMetadata: v, - } -} - -// Code returns the exception type name. -func (s *UnsupportedUserEditionException) Code() string { - return "UnsupportedUserEditionException" -} - -// Message returns the exception's message. -func (s *UnsupportedUserEditionException) Message() string { - if s.Message_ != nil { - return *s.Message_ - } - return "" +// SetDashboardArn sets the DashboardArn field's value. +func (s *UpdateDashboardPermissionsOutput) SetDashboardArn(v string) *UpdateDashboardPermissionsOutput { + s.DashboardArn = &v + return s } -// OrigErr always returns nil, satisfies awserr.Error interface. -func (s *UnsupportedUserEditionException) OrigErr() error { - return nil +// SetDashboardId sets the DashboardId field's value. +func (s *UpdateDashboardPermissionsOutput) SetDashboardId(v string) *UpdateDashboardPermissionsOutput { + s.DashboardId = &v + return s } -func (s *UnsupportedUserEditionException) Error() string { - return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +// SetPermissions sets the Permissions field's value. +func (s *UpdateDashboardPermissionsOutput) SetPermissions(v []*ResourcePermission) *UpdateDashboardPermissionsOutput { + s.Permissions = v + return s } -// Status code returns the HTTP status code for the request's response error. -func (s *UnsupportedUserEditionException) StatusCode() int { - return s.RespMetadata.StatusCode +// SetRequestId sets the RequestId field's value. +func (s *UpdateDashboardPermissionsOutput) SetRequestId(v string) *UpdateDashboardPermissionsOutput { + s.RequestId = &v + return s } -// RequestID returns the service's response RequestID for request. -func (s *UnsupportedUserEditionException) RequestID() string { - return s.RespMetadata.RequestID +// SetStatus sets the Status field's value. +func (s *UpdateDashboardPermissionsOutput) SetStatus(v int64) *UpdateDashboardPermissionsOutput { + s.Status = &v + return s } -type UntagResourceInput struct { +type UpdateDashboardPublishedVersionInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource that you want to untag. + // The ID of the AWS account that contains the dashboard that you're updating. // - // ResourceArn is a required field - ResourceArn *string `location:"uri" locationName:"ResourceArn" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The keys of the key-value pairs for the resource tag or tags assigned to - // the resource. + // The ID for the dashboard. // - // TagKeys is a required field - TagKeys []*string `location:"querystring" locationName:"keys" min:"1" type:"list" required:"true"` + // DashboardId is a required field + DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` + + // The version number of the dashboard. + // + // VersionNumber is a required field + VersionNumber *int64 `location:"uri" locationName:"VersionNumber" min:"1" type:"long" required:"true"` } // String returns the string representation -func (s UntagResourceInput) String() string { +func (s UpdateDashboardPublishedVersionInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UntagResourceInput) GoString() string { +func (s UpdateDashboardPublishedVersionInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UntagResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"} - if s.ResourceArn == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceArn")) +func (s *UpdateDashboardPublishedVersionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateDashboardPublishedVersionInput"} + if s.AwsAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } - if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { + invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.TagKeys == nil { - invalidParams.Add(request.NewErrParamRequired("TagKeys")) + if s.DashboardId == nil { + invalidParams.Add(request.NewErrParamRequired("DashboardId")) } - if s.TagKeys != nil && len(s.TagKeys) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TagKeys", 1)) + if s.DashboardId != nil && len(*s.DashboardId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) + } + if s.VersionNumber == nil { + invalidParams.Add(request.NewErrParamRequired("VersionNumber")) + } + if s.VersionNumber != nil && *s.VersionNumber < 1 { + invalidParams.Add(request.NewErrParamMinValue("VersionNumber", 1)) } if invalidParams.Len() > 0 { @@ -20851,21 +27677,33 @@ func (s *UntagResourceInput) Validate() error { return nil } -// SetResourceArn sets the ResourceArn field's value. -func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { - s.ResourceArn = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *UpdateDashboardPublishedVersionInput) SetAwsAccountId(v string) *UpdateDashboardPublishedVersionInput { + s.AwsAccountId = &v + return s +} + +// SetDashboardId sets the DashboardId field's value. +func (s *UpdateDashboardPublishedVersionInput) SetDashboardId(v string) *UpdateDashboardPublishedVersionInput { + s.DashboardId = &v return s } -// SetTagKeys sets the TagKeys field's value. -func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { - s.TagKeys = v +// SetVersionNumber sets the VersionNumber field's value. +func (s *UpdateDashboardPublishedVersionInput) SetVersionNumber(v int64) *UpdateDashboardPublishedVersionInput { + s.VersionNumber = &v return s } -type UntagResourceOutput struct { +type UpdateDashboardPublishedVersionOutput struct { _ struct{} `type:"structure"` + // The Amazon Resource Name (ARN) of the dashboard. + DashboardArn *string `type:"string"` + + // The ID for the dashboard. + DashboardId *string `min:"1" type:"string"` + // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -20874,101 +27712,113 @@ type UntagResourceOutput struct { } // String returns the string representation -func (s UntagResourceOutput) String() string { +func (s UpdateDashboardPublishedVersionOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UntagResourceOutput) GoString() string { +func (s UpdateDashboardPublishedVersionOutput) GoString() string { return s.String() } +// SetDashboardArn sets the DashboardArn field's value. +func (s *UpdateDashboardPublishedVersionOutput) SetDashboardArn(v string) *UpdateDashboardPublishedVersionOutput { + s.DashboardArn = &v + return s +} + +// SetDashboardId sets the DashboardId field's value. +func (s *UpdateDashboardPublishedVersionOutput) SetDashboardId(v string) *UpdateDashboardPublishedVersionOutput { + s.DashboardId = &v + return s +} + // SetRequestId sets the RequestId field's value. -func (s *UntagResourceOutput) SetRequestId(v string) *UntagResourceOutput { +func (s *UpdateDashboardPublishedVersionOutput) SetRequestId(v string) *UpdateDashboardPublishedVersionOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *UntagResourceOutput) SetStatus(v int64) *UntagResourceOutput { +func (s *UpdateDashboardPublishedVersionOutput) SetStatus(v int64) *UpdateDashboardPublishedVersionOutput { s.Status = &v return s } -type UpdateDashboardInput struct { +type UpdateDataSetInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the dashboard that you're updating. + // The AWS account ID. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the dashboard. - // - // DashboardId is a required field - DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` + // Groupings of columns that work together in certain QuickSight features. Currently, + // only geospatial hierarchy is supported. + ColumnGroups []*ColumnGroup `min:"1" type:"list"` - // Options for publishing the dashboard when you create it: - // - // * AvailabilityStatus for AdHocFilteringOption - This status can be either - // ENABLED or DISABLED. When this is set to DISABLED, QuickSight disables - // the left filter pane on the published dashboard, which can be used for - // ad hoc (one-time) filtering. This option is ENABLED by default. + // The ID for the dataset that you want to update. This ID is unique per AWS + // Region for each AWS account. // - // * AvailabilityStatus for ExportToCSVOption - This status can be either - // ENABLED or DISABLED. The visual option to export data to .csv format isn't - // enabled when this is set to DISABLED. This option is ENABLED by default. + // DataSetId is a required field + DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` + + // Indicates whether you want to import the data into SPICE. // - // * VisibilityState for SheetControlsOption - This visibility state can - // be either COLLAPSED or EXPANDED. The sheet controls pane is collapsed - // by default when set to true. This option is COLLAPSED by default. - DashboardPublishOptions *DashboardPublishOptions `type:"structure"` + // ImportMode is a required field + ImportMode *string `type:"string" required:"true" enum:"DataSetImportMode"` - // The display name of the dashboard. + // Configures the combination and transformation of the data from the physical + // tables. + LogicalTableMap map[string]*LogicalTable `min:"1" type:"map"` + + // The display name for the dataset. // // Name is a required field Name *string `min:"1" type:"string" required:"true"` - // A structure that contains the parameters of the dashboard. - Parameters *Parameters `type:"structure"` - - // The template or analysis from which the dashboard is created. The SouceTemplate - // entity accepts the Amazon Resource Name (ARN) of the template and also references - // to replacement datasets for the placeholders set when creating the template. - // The replacement datasets need to follow the same schema as the datasets for - // which placeholders were created when creating the template. + // Declares the physical tables that are available in the underlying data sources. // - // SourceEntity is a required field - SourceEntity *DashboardSourceEntity `type:"structure" required:"true"` + // PhysicalTableMap is a required field + PhysicalTableMap map[string]*PhysicalTable `min:"1" type:"map" required:"true"` - // A description for the first version of the dashboard being created. - VersionDescription *string `min:"1" type:"string"` + // The row-level security configuration for the data you want to create. + RowLevelPermissionDataSet *RowLevelPermissionDataSet `type:"structure"` } // String returns the string representation -func (s UpdateDashboardInput) String() string { +func (s UpdateDataSetInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDashboardInput) GoString() string { +func (s UpdateDataSetInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateDashboardInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateDashboardInput"} +func (s *UpdateDataSetInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateDataSetInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DashboardId == nil { - invalidParams.Add(request.NewErrParamRequired("DashboardId")) + if s.ColumnGroups != nil && len(s.ColumnGroups) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ColumnGroups", 1)) } - if s.DashboardId != nil && len(*s.DashboardId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) + if s.DataSetId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetId")) + } + if s.DataSetId != nil && len(*s.DataSetId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) + } + if s.ImportMode == nil { + invalidParams.Add(request.NewErrParamRequired("ImportMode")) + } + if s.LogicalTableMap != nil && len(s.LogicalTableMap) < 1 { + invalidParams.Add(request.NewErrParamMinLen("LogicalTableMap", 1)) } if s.Name == nil { invalidParams.Add(request.NewErrParamRequired("Name")) @@ -20976,20 +27826,45 @@ func (s *UpdateDashboardInput) Validate() error { if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } - if s.SourceEntity == nil { - invalidParams.Add(request.NewErrParamRequired("SourceEntity")) + if s.PhysicalTableMap == nil { + invalidParams.Add(request.NewErrParamRequired("PhysicalTableMap")) } - if s.VersionDescription != nil && len(*s.VersionDescription) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VersionDescription", 1)) + if s.PhysicalTableMap != nil && len(s.PhysicalTableMap) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PhysicalTableMap", 1)) } - if s.Parameters != nil { - if err := s.Parameters.Validate(); err != nil { - invalidParams.AddNested("Parameters", err.(request.ErrInvalidParams)) + if s.ColumnGroups != nil { + for i, v := range s.ColumnGroups { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ColumnGroups", i), err.(request.ErrInvalidParams)) + } } } - if s.SourceEntity != nil { - if err := s.SourceEntity.Validate(); err != nil { - invalidParams.AddNested("SourceEntity", err.(request.ErrInvalidParams)) + if s.LogicalTableMap != nil { + for i, v := range s.LogicalTableMap { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LogicalTableMap", i), err.(request.ErrInvalidParams)) + } + } + } + if s.PhysicalTableMap != nil { + for i, v := range s.PhysicalTableMap { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "PhysicalTableMap", i), err.(request.ErrInvalidParams)) + } + } + } + if s.RowLevelPermissionDataSet != nil { + if err := s.RowLevelPermissionDataSet.Validate(); err != nil { + invalidParams.AddNested("RowLevelPermissionDataSet", err.(request.ErrInvalidParams)) } } @@ -21000,160 +27875,169 @@ func (s *UpdateDashboardInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateDashboardInput) SetAwsAccountId(v string) *UpdateDashboardInput { +func (s *UpdateDataSetInput) SetAwsAccountId(v string) *UpdateDataSetInput { s.AwsAccountId = &v return s } -// SetDashboardId sets the DashboardId field's value. -func (s *UpdateDashboardInput) SetDashboardId(v string) *UpdateDashboardInput { - s.DashboardId = &v +// SetColumnGroups sets the ColumnGroups field's value. +func (s *UpdateDataSetInput) SetColumnGroups(v []*ColumnGroup) *UpdateDataSetInput { + s.ColumnGroups = v return s } -// SetDashboardPublishOptions sets the DashboardPublishOptions field's value. -func (s *UpdateDashboardInput) SetDashboardPublishOptions(v *DashboardPublishOptions) *UpdateDashboardInput { - s.DashboardPublishOptions = v +// SetDataSetId sets the DataSetId field's value. +func (s *UpdateDataSetInput) SetDataSetId(v string) *UpdateDataSetInput { + s.DataSetId = &v return s } -// SetName sets the Name field's value. -func (s *UpdateDashboardInput) SetName(v string) *UpdateDashboardInput { - s.Name = &v +// SetImportMode sets the ImportMode field's value. +func (s *UpdateDataSetInput) SetImportMode(v string) *UpdateDataSetInput { + s.ImportMode = &v return s } -// SetParameters sets the Parameters field's value. -func (s *UpdateDashboardInput) SetParameters(v *Parameters) *UpdateDashboardInput { - s.Parameters = v +// SetLogicalTableMap sets the LogicalTableMap field's value. +func (s *UpdateDataSetInput) SetLogicalTableMap(v map[string]*LogicalTable) *UpdateDataSetInput { + s.LogicalTableMap = v return s } -// SetSourceEntity sets the SourceEntity field's value. -func (s *UpdateDashboardInput) SetSourceEntity(v *DashboardSourceEntity) *UpdateDashboardInput { - s.SourceEntity = v +// SetName sets the Name field's value. +func (s *UpdateDataSetInput) SetName(v string) *UpdateDataSetInput { + s.Name = &v return s } -// SetVersionDescription sets the VersionDescription field's value. -func (s *UpdateDashboardInput) SetVersionDescription(v string) *UpdateDashboardInput { - s.VersionDescription = &v +// SetPhysicalTableMap sets the PhysicalTableMap field's value. +func (s *UpdateDataSetInput) SetPhysicalTableMap(v map[string]*PhysicalTable) *UpdateDataSetInput { + s.PhysicalTableMap = v return s } -type UpdateDashboardOutput struct { +// SetRowLevelPermissionDataSet sets the RowLevelPermissionDataSet field's value. +func (s *UpdateDataSetInput) SetRowLevelPermissionDataSet(v *RowLevelPermissionDataSet) *UpdateDataSetInput { + s.RowLevelPermissionDataSet = v + return s +} + +type UpdateDataSetOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the resource. + // The Amazon Resource Name (ARN) of the dataset. Arn *string `type:"string"` - // The creation status of the request. - CreationStatus *string `type:"string" enum:"ResourceStatus"` + // The ID for the dataset that you want to create. This ID is unique per AWS + // Region for each AWS account. + DataSetId *string `type:"string"` - // The ID for the dashboard. - DashboardId *string `min:"1" type:"string"` + // The ARN for the ingestion, which is triggered as a result of dataset creation + // if the import mode is SPICE. + IngestionArn *string `type:"string"` + + // The ID of the ingestion, which is triggered as a result of dataset creation + // if the import mode is SPICE. + IngestionId *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. - Status *int64 `type:"integer"` - - // The ARN of the dashboard, including the version number. - VersionArn *string `type:"string"` + Status *int64 `location:"statusCode" type:"integer"` } // String returns the string representation -func (s UpdateDashboardOutput) String() string { +func (s UpdateDataSetOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDashboardOutput) GoString() string { +func (s UpdateDataSetOutput) GoString() string { return s.String() } // SetArn sets the Arn field's value. -func (s *UpdateDashboardOutput) SetArn(v string) *UpdateDashboardOutput { +func (s *UpdateDataSetOutput) SetArn(v string) *UpdateDataSetOutput { s.Arn = &v return s } -// SetCreationStatus sets the CreationStatus field's value. -func (s *UpdateDashboardOutput) SetCreationStatus(v string) *UpdateDashboardOutput { - s.CreationStatus = &v +// SetDataSetId sets the DataSetId field's value. +func (s *UpdateDataSetOutput) SetDataSetId(v string) *UpdateDataSetOutput { + s.DataSetId = &v return s } -// SetDashboardId sets the DashboardId field's value. -func (s *UpdateDashboardOutput) SetDashboardId(v string) *UpdateDashboardOutput { - s.DashboardId = &v +// SetIngestionArn sets the IngestionArn field's value. +func (s *UpdateDataSetOutput) SetIngestionArn(v string) *UpdateDataSetOutput { + s.IngestionArn = &v return s } -// SetRequestId sets the RequestId field's value. -func (s *UpdateDashboardOutput) SetRequestId(v string) *UpdateDashboardOutput { - s.RequestId = &v +// SetIngestionId sets the IngestionId field's value. +func (s *UpdateDataSetOutput) SetIngestionId(v string) *UpdateDataSetOutput { + s.IngestionId = &v return s } -// SetStatus sets the Status field's value. -func (s *UpdateDashboardOutput) SetStatus(v int64) *UpdateDashboardOutput { - s.Status = &v +// SetRequestId sets the RequestId field's value. +func (s *UpdateDataSetOutput) SetRequestId(v string) *UpdateDataSetOutput { + s.RequestId = &v return s } -// SetVersionArn sets the VersionArn field's value. -func (s *UpdateDashboardOutput) SetVersionArn(v string) *UpdateDashboardOutput { - s.VersionArn = &v +// SetStatus sets the Status field's value. +func (s *UpdateDataSetOutput) SetStatus(v int64) *UpdateDataSetOutput { + s.Status = &v return s } -type UpdateDashboardPermissionsInput struct { +type UpdateDataSetPermissionsInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the dashboard whose permissions you're - // updating. + // The AWS account ID. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the dashboard. + // The ID for the dataset whose permissions you want to update. This ID is unique + // per AWS Region for each AWS account. // - // DashboardId is a required field - DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` + // DataSetId is a required field + DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` - // The permissions that you want to grant on this resource. + // The resource permissions that you want to grant to the dataset. GrantPermissions []*ResourcePermission `min:"1" type:"list"` - // The permissions that you want to revoke from this resource. + // The resource permissions that you want to revoke from the dataset. RevokePermissions []*ResourcePermission `min:"1" type:"list"` } // String returns the string representation -func (s UpdateDashboardPermissionsInput) String() string { +func (s UpdateDataSetPermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDashboardPermissionsInput) GoString() string { +func (s UpdateDataSetPermissionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateDashboardPermissionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateDashboardPermissionsInput"} +func (s *UpdateDataSetPermissionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateDataSetPermissionsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DashboardId == nil { - invalidParams.Add(request.NewErrParamRequired("DashboardId")) + if s.DataSetId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSetId")) } - if s.DashboardId != nil && len(*s.DashboardId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) + if s.DataSetId != nil && len(*s.DataSetId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) } if s.GrantPermissions != nil && len(s.GrantPermissions) < 1 { invalidParams.Add(request.NewErrParamMinLen("GrantPermissions", 1)) @@ -21189,40 +28073,38 @@ func (s *UpdateDashboardPermissionsInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateDashboardPermissionsInput) SetAwsAccountId(v string) *UpdateDashboardPermissionsInput { +func (s *UpdateDataSetPermissionsInput) SetAwsAccountId(v string) *UpdateDataSetPermissionsInput { s.AwsAccountId = &v return s } -// SetDashboardId sets the DashboardId field's value. -func (s *UpdateDashboardPermissionsInput) SetDashboardId(v string) *UpdateDashboardPermissionsInput { - s.DashboardId = &v +// SetDataSetId sets the DataSetId field's value. +func (s *UpdateDataSetPermissionsInput) SetDataSetId(v string) *UpdateDataSetPermissionsInput { + s.DataSetId = &v return s } // SetGrantPermissions sets the GrantPermissions field's value. -func (s *UpdateDashboardPermissionsInput) SetGrantPermissions(v []*ResourcePermission) *UpdateDashboardPermissionsInput { +func (s *UpdateDataSetPermissionsInput) SetGrantPermissions(v []*ResourcePermission) *UpdateDataSetPermissionsInput { s.GrantPermissions = v return s } // SetRevokePermissions sets the RevokePermissions field's value. -func (s *UpdateDashboardPermissionsInput) SetRevokePermissions(v []*ResourcePermission) *UpdateDashboardPermissionsInput { +func (s *UpdateDataSetPermissionsInput) SetRevokePermissions(v []*ResourcePermission) *UpdateDataSetPermissionsInput { s.RevokePermissions = v return s } -type UpdateDashboardPermissionsOutput struct { +type UpdateDataSetPermissionsOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the dashboard. - DashboardArn *string `type:"string"` - - // The ID for the dashboard. - DashboardId *string `min:"1" type:"string"` + // The Amazon Resource Name (ARN) of the dataset. + DataSetArn *string `type:"string"` - // Information about the permissions on the dashboard. - Permissions []*ResourcePermission `min:"1" type:"list"` + // The ID for the dataset whose permissions you want to update. This ID is unique + // per AWS Region for each AWS account. + DataSetId *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -21232,94 +28114,119 @@ type UpdateDashboardPermissionsOutput struct { } // String returns the string representation -func (s UpdateDashboardPermissionsOutput) String() string { +func (s UpdateDataSetPermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDashboardPermissionsOutput) GoString() string { +func (s UpdateDataSetPermissionsOutput) GoString() string { return s.String() } -// SetDashboardArn sets the DashboardArn field's value. -func (s *UpdateDashboardPermissionsOutput) SetDashboardArn(v string) *UpdateDashboardPermissionsOutput { - s.DashboardArn = &v - return s -} - -// SetDashboardId sets the DashboardId field's value. -func (s *UpdateDashboardPermissionsOutput) SetDashboardId(v string) *UpdateDashboardPermissionsOutput { - s.DashboardId = &v +// SetDataSetArn sets the DataSetArn field's value. +func (s *UpdateDataSetPermissionsOutput) SetDataSetArn(v string) *UpdateDataSetPermissionsOutput { + s.DataSetArn = &v return s } -// SetPermissions sets the Permissions field's value. -func (s *UpdateDashboardPermissionsOutput) SetPermissions(v []*ResourcePermission) *UpdateDashboardPermissionsOutput { - s.Permissions = v +// SetDataSetId sets the DataSetId field's value. +func (s *UpdateDataSetPermissionsOutput) SetDataSetId(v string) *UpdateDataSetPermissionsOutput { + s.DataSetId = &v return s } // SetRequestId sets the RequestId field's value. -func (s *UpdateDashboardPermissionsOutput) SetRequestId(v string) *UpdateDashboardPermissionsOutput { +func (s *UpdateDataSetPermissionsOutput) SetRequestId(v string) *UpdateDataSetPermissionsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *UpdateDashboardPermissionsOutput) SetStatus(v int64) *UpdateDashboardPermissionsOutput { +func (s *UpdateDataSetPermissionsOutput) SetStatus(v int64) *UpdateDataSetPermissionsOutput { s.Status = &v return s } -type UpdateDashboardPublishedVersionInput struct { +type UpdateDataSourceInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the dashboard that you're updating. + // The AWS account ID. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the dashboard. + // The credentials that QuickSight that uses to connect to your underlying source. + // Currently, only credentials based on user name and password are supported. + Credentials *DataSourceCredentials `type:"structure" sensitive:"true"` + + // The ID of the data source. This ID is unique per AWS Region for each AWS + // account. // - // DashboardId is a required field - DashboardId *string `location:"uri" locationName:"DashboardId" min:"1" type:"string" required:"true"` + // DataSourceId is a required field + DataSourceId *string `location:"uri" locationName:"DataSourceId" type:"string" required:"true"` - // The version number of the dashboard. + // The parameters that QuickSight uses to connect to your underlying source. + DataSourceParameters *DataSourceParameters `type:"structure"` + + // A display name for the data source. // - // VersionNumber is a required field - VersionNumber *int64 `location:"uri" locationName:"VersionNumber" min:"1" type:"long" required:"true"` + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // Secure Socket Layer (SSL) properties that apply when QuickSight connects + // to your underlying source. + SslProperties *SslProperties `type:"structure"` + + // Use this parameter only when you want QuickSight to use a VPC connection + // when connecting to your underlying source. + VpcConnectionProperties *VpcConnectionProperties `type:"structure"` } // String returns the string representation -func (s UpdateDashboardPublishedVersionInput) String() string { +func (s UpdateDataSourceInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDashboardPublishedVersionInput) GoString() string { +func (s UpdateDataSourceInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateDashboardPublishedVersionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateDashboardPublishedVersionInput"} +func (s *UpdateDataSourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateDataSourceInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DashboardId == nil { - invalidParams.Add(request.NewErrParamRequired("DashboardId")) + if s.DataSourceId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSourceId")) } - if s.DashboardId != nil && len(*s.DashboardId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DashboardId", 1)) + if s.DataSourceId != nil && len(*s.DataSourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSourceId", 1)) } - if s.VersionNumber == nil { - invalidParams.Add(request.NewErrParamRequired("VersionNumber")) + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) } - if s.VersionNumber != nil && *s.VersionNumber < 1 { - invalidParams.Add(request.NewErrParamMinValue("VersionNumber", 1)) + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.Credentials != nil { + if err := s.Credentials.Validate(); err != nil { + invalidParams.AddNested("Credentials", err.(request.ErrInvalidParams)) + } + } + if s.DataSourceParameters != nil { + if err := s.DataSourceParameters.Validate(); err != nil { + invalidParams.AddNested("DataSourceParameters", err.(request.ErrInvalidParams)) + } + } + if s.VpcConnectionProperties != nil { + if err := s.VpcConnectionProperties.Validate(); err != nil { + invalidParams.AddNested("VpcConnectionProperties", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -21329,195 +28236,179 @@ func (s *UpdateDashboardPublishedVersionInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateDashboardPublishedVersionInput) SetAwsAccountId(v string) *UpdateDashboardPublishedVersionInput { +func (s *UpdateDataSourceInput) SetAwsAccountId(v string) *UpdateDataSourceInput { s.AwsAccountId = &v return s } -// SetDashboardId sets the DashboardId field's value. -func (s *UpdateDashboardPublishedVersionInput) SetDashboardId(v string) *UpdateDashboardPublishedVersionInput { - s.DashboardId = &v +// SetCredentials sets the Credentials field's value. +func (s *UpdateDataSourceInput) SetCredentials(v *DataSourceCredentials) *UpdateDataSourceInput { + s.Credentials = v return s } -// SetVersionNumber sets the VersionNumber field's value. -func (s *UpdateDashboardPublishedVersionInput) SetVersionNumber(v int64) *UpdateDashboardPublishedVersionInput { - s.VersionNumber = &v +// SetDataSourceId sets the DataSourceId field's value. +func (s *UpdateDataSourceInput) SetDataSourceId(v string) *UpdateDataSourceInput { + s.DataSourceId = &v return s } -type UpdateDashboardPublishedVersionOutput struct { +// SetDataSourceParameters sets the DataSourceParameters field's value. +func (s *UpdateDataSourceInput) SetDataSourceParameters(v *DataSourceParameters) *UpdateDataSourceInput { + s.DataSourceParameters = v + return s +} + +// SetName sets the Name field's value. +func (s *UpdateDataSourceInput) SetName(v string) *UpdateDataSourceInput { + s.Name = &v + return s +} + +// SetSslProperties sets the SslProperties field's value. +func (s *UpdateDataSourceInput) SetSslProperties(v *SslProperties) *UpdateDataSourceInput { + s.SslProperties = v + return s +} + +// SetVpcConnectionProperties sets the VpcConnectionProperties field's value. +func (s *UpdateDataSourceInput) SetVpcConnectionProperties(v *VpcConnectionProperties) *UpdateDataSourceInput { + s.VpcConnectionProperties = v + return s +} + +type UpdateDataSourceOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the dashboard. - DashboardArn *string `type:"string"` + // The Amazon Resource Name (ARN) of the data source. + Arn *string `type:"string"` - // The ID for the dashboard. - DashboardId *string `min:"1" type:"string"` + // The ID of the data source. This ID is unique per AWS Region for each AWS + // account. + DataSourceId *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // The update status of the data source's last update. + UpdateStatus *string `type:"string" enum:"ResourceStatus"` } // String returns the string representation -func (s UpdateDashboardPublishedVersionOutput) String() string { +func (s UpdateDataSourceOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDashboardPublishedVersionOutput) GoString() string { +func (s UpdateDataSourceOutput) GoString() string { return s.String() } -// SetDashboardArn sets the DashboardArn field's value. -func (s *UpdateDashboardPublishedVersionOutput) SetDashboardArn(v string) *UpdateDashboardPublishedVersionOutput { - s.DashboardArn = &v +// SetArn sets the Arn field's value. +func (s *UpdateDataSourceOutput) SetArn(v string) *UpdateDataSourceOutput { + s.Arn = &v return s } -// SetDashboardId sets the DashboardId field's value. -func (s *UpdateDashboardPublishedVersionOutput) SetDashboardId(v string) *UpdateDashboardPublishedVersionOutput { - s.DashboardId = &v +// SetDataSourceId sets the DataSourceId field's value. +func (s *UpdateDataSourceOutput) SetDataSourceId(v string) *UpdateDataSourceOutput { + s.DataSourceId = &v return s } // SetRequestId sets the RequestId field's value. -func (s *UpdateDashboardPublishedVersionOutput) SetRequestId(v string) *UpdateDashboardPublishedVersionOutput { +func (s *UpdateDataSourceOutput) SetRequestId(v string) *UpdateDataSourceOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *UpdateDashboardPublishedVersionOutput) SetStatus(v int64) *UpdateDashboardPublishedVersionOutput { +func (s *UpdateDataSourceOutput) SetStatus(v int64) *UpdateDataSourceOutput { s.Status = &v return s } -type UpdateDataSetInput struct { - _ struct{} `type:"structure"` - - // The AWS account ID. - // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - - // Groupings of columns that work together in certain QuickSight features. Currently, - // only geospatial hierarchy is supported. - ColumnGroups []*ColumnGroup `min:"1" type:"list"` - - // The ID for the dataset that you want to update. This ID is unique per AWS - // Region for each AWS account. - // - // DataSetId is a required field - DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` - - // Indicates whether you want to import the data into SPICE. - // - // ImportMode is a required field - ImportMode *string `type:"string" required:"true" enum:"DataSetImportMode"` +// SetUpdateStatus sets the UpdateStatus field's value. +func (s *UpdateDataSourceOutput) SetUpdateStatus(v string) *UpdateDataSourceOutput { + s.UpdateStatus = &v + return s +} - // Configures the combination and transformation of the data from the physical - // tables. - LogicalTableMap map[string]*LogicalTable `min:"1" type:"map"` +type UpdateDataSourcePermissionsInput struct { + _ struct{} `type:"structure"` - // The display name for the dataset. + // The AWS account ID. // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // Declares the physical tables that are available in the underlying data sources. + // The ID of the data source. This ID is unique per AWS Region for each AWS + // account. // - // PhysicalTableMap is a required field - PhysicalTableMap map[string]*PhysicalTable `min:"1" type:"map" required:"true"` + // DataSourceId is a required field + DataSourceId *string `location:"uri" locationName:"DataSourceId" type:"string" required:"true"` - // The row-level security configuration for the data you want to create. - RowLevelPermissionDataSet *RowLevelPermissionDataSet `type:"structure"` + // A list of resource permissions that you want to grant on the data source. + GrantPermissions []*ResourcePermission `min:"1" type:"list"` + + // A list of resource permissions that you want to revoke on the data source. + RevokePermissions []*ResourcePermission `min:"1" type:"list"` } // String returns the string representation -func (s UpdateDataSetInput) String() string { +func (s UpdateDataSourcePermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDataSetInput) GoString() string { +func (s UpdateDataSourcePermissionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateDataSetInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateDataSetInput"} +func (s *UpdateDataSourcePermissionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateDataSourcePermissionsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.ColumnGroups != nil && len(s.ColumnGroups) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ColumnGroups", 1)) - } - if s.DataSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetId")) - } - if s.DataSetId != nil && len(*s.DataSetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) - } - if s.ImportMode == nil { - invalidParams.Add(request.NewErrParamRequired("ImportMode")) - } - if s.LogicalTableMap != nil && len(s.LogicalTableMap) < 1 { - invalidParams.Add(request.NewErrParamMinLen("LogicalTableMap", 1)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + if s.DataSourceId == nil { + invalidParams.Add(request.NewErrParamRequired("DataSourceId")) } - if s.PhysicalTableMap == nil { - invalidParams.Add(request.NewErrParamRequired("PhysicalTableMap")) + if s.DataSourceId != nil && len(*s.DataSourceId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("DataSourceId", 1)) } - if s.PhysicalTableMap != nil && len(s.PhysicalTableMap) < 1 { - invalidParams.Add(request.NewErrParamMinLen("PhysicalTableMap", 1)) + if s.GrantPermissions != nil && len(s.GrantPermissions) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GrantPermissions", 1)) } - if s.ColumnGroups != nil { - for i, v := range s.ColumnGroups { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ColumnGroups", i), err.(request.ErrInvalidParams)) - } - } + if s.RevokePermissions != nil && len(s.RevokePermissions) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RevokePermissions", 1)) } - if s.LogicalTableMap != nil { - for i, v := range s.LogicalTableMap { + if s.GrantPermissions != nil { + for i, v := range s.GrantPermissions { if v == nil { continue } if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LogicalTableMap", i), err.(request.ErrInvalidParams)) + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "GrantPermissions", i), err.(request.ErrInvalidParams)) } } } - if s.PhysicalTableMap != nil { - for i, v := range s.PhysicalTableMap { + if s.RevokePermissions != nil { + for i, v := range s.RevokePermissions { if v == nil { continue } if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "PhysicalTableMap", i), err.(request.ErrInvalidParams)) + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RevokePermissions", i), err.(request.ErrInvalidParams)) } } } - if s.RowLevelPermissionDataSet != nil { - if err := s.RowLevelPermissionDataSet.Validate(); err != nil { - invalidParams.AddNested("RowLevelPermissionDataSet", err.(request.ErrInvalidParams)) - } - } if invalidParams.Len() > 0 { return invalidParams @@ -21526,70 +28417,38 @@ func (s *UpdateDataSetInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateDataSetInput) SetAwsAccountId(v string) *UpdateDataSetInput { +func (s *UpdateDataSourcePermissionsInput) SetAwsAccountId(v string) *UpdateDataSourcePermissionsInput { s.AwsAccountId = &v return s } -// SetColumnGroups sets the ColumnGroups field's value. -func (s *UpdateDataSetInput) SetColumnGroups(v []*ColumnGroup) *UpdateDataSetInput { - s.ColumnGroups = v - return s -} - -// SetDataSetId sets the DataSetId field's value. -func (s *UpdateDataSetInput) SetDataSetId(v string) *UpdateDataSetInput { - s.DataSetId = &v - return s -} - -// SetImportMode sets the ImportMode field's value. -func (s *UpdateDataSetInput) SetImportMode(v string) *UpdateDataSetInput { - s.ImportMode = &v - return s -} - -// SetLogicalTableMap sets the LogicalTableMap field's value. -func (s *UpdateDataSetInput) SetLogicalTableMap(v map[string]*LogicalTable) *UpdateDataSetInput { - s.LogicalTableMap = v - return s -} - -// SetName sets the Name field's value. -func (s *UpdateDataSetInput) SetName(v string) *UpdateDataSetInput { - s.Name = &v +// SetDataSourceId sets the DataSourceId field's value. +func (s *UpdateDataSourcePermissionsInput) SetDataSourceId(v string) *UpdateDataSourcePermissionsInput { + s.DataSourceId = &v return s } -// SetPhysicalTableMap sets the PhysicalTableMap field's value. -func (s *UpdateDataSetInput) SetPhysicalTableMap(v map[string]*PhysicalTable) *UpdateDataSetInput { - s.PhysicalTableMap = v +// SetGrantPermissions sets the GrantPermissions field's value. +func (s *UpdateDataSourcePermissionsInput) SetGrantPermissions(v []*ResourcePermission) *UpdateDataSourcePermissionsInput { + s.GrantPermissions = v return s } -// SetRowLevelPermissionDataSet sets the RowLevelPermissionDataSet field's value. -func (s *UpdateDataSetInput) SetRowLevelPermissionDataSet(v *RowLevelPermissionDataSet) *UpdateDataSetInput { - s.RowLevelPermissionDataSet = v +// SetRevokePermissions sets the RevokePermissions field's value. +func (s *UpdateDataSourcePermissionsInput) SetRevokePermissions(v []*ResourcePermission) *UpdateDataSourcePermissionsInput { + s.RevokePermissions = v return s } -type UpdateDataSetOutput struct { +type UpdateDataSourcePermissionsOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the dataset. - Arn *string `type:"string"` - - // The ID for the dataset that you want to create. This ID is unique per AWS - // Region for each AWS account. - DataSetId *string `type:"string"` - - // The ARN for the ingestion, which is triggered as a result of dataset creation - // if the import mode is SPICE. - IngestionArn *string `type:"string"` + // The Amazon Resource Name (ARN) of the data source. + DataSourceArn *string `type:"string"` - // The ID of the ingestion, which is triggered as a result of dataset creation - // if the import mode is SPICE. - IngestionId *string `type:"string"` + // The ID of the data source. This ID is unique per AWS Region for each AWS + // account. + DataSourceId *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -21599,122 +28458,95 @@ type UpdateDataSetOutput struct { } // String returns the string representation -func (s UpdateDataSetOutput) String() string { +func (s UpdateDataSourcePermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDataSetOutput) GoString() string { +func (s UpdateDataSourcePermissionsOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *UpdateDataSetOutput) SetArn(v string) *UpdateDataSetOutput { - s.Arn = &v - return s -} - -// SetDataSetId sets the DataSetId field's value. -func (s *UpdateDataSetOutput) SetDataSetId(v string) *UpdateDataSetOutput { - s.DataSetId = &v - return s -} - -// SetIngestionArn sets the IngestionArn field's value. -func (s *UpdateDataSetOutput) SetIngestionArn(v string) *UpdateDataSetOutput { - s.IngestionArn = &v +// SetDataSourceArn sets the DataSourceArn field's value. +func (s *UpdateDataSourcePermissionsOutput) SetDataSourceArn(v string) *UpdateDataSourcePermissionsOutput { + s.DataSourceArn = &v return s } -// SetIngestionId sets the IngestionId field's value. -func (s *UpdateDataSetOutput) SetIngestionId(v string) *UpdateDataSetOutput { - s.IngestionId = &v +// SetDataSourceId sets the DataSourceId field's value. +func (s *UpdateDataSourcePermissionsOutput) SetDataSourceId(v string) *UpdateDataSourcePermissionsOutput { + s.DataSourceId = &v return s } // SetRequestId sets the RequestId field's value. -func (s *UpdateDataSetOutput) SetRequestId(v string) *UpdateDataSetOutput { +func (s *UpdateDataSourcePermissionsOutput) SetRequestId(v string) *UpdateDataSourcePermissionsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *UpdateDataSetOutput) SetStatus(v int64) *UpdateDataSetOutput { +func (s *UpdateDataSourcePermissionsOutput) SetStatus(v int64) *UpdateDataSourcePermissionsOutput { s.Status = &v return s } -type UpdateDataSetPermissionsInput struct { +type UpdateGroupInput struct { _ struct{} `type:"structure"` - // The AWS account ID. + // The ID for the AWS account that the group is in. Currently, you use the ID + // for the AWS account that contains your Amazon QuickSight account. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the dataset whose permissions you want to update. This ID is unique - // per AWS Region for each AWS account. - // - // DataSetId is a required field - DataSetId *string `location:"uri" locationName:"DataSetId" type:"string" required:"true"` + // The description for the group that you want to update. + Description *string `min:"1" type:"string"` - // The resource permissions that you want to grant to the dataset. - GrantPermissions []*ResourcePermission `min:"1" type:"list"` + // The name of the group that you want to update. + // + // GroupName is a required field + GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` - // The resource permissions that you want to revoke from the dataset. - RevokePermissions []*ResourcePermission `min:"1" type:"list"` + // The namespace. Currently, you should set this to default. + // + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` } // String returns the string representation -func (s UpdateDataSetPermissionsInput) String() string { +func (s UpdateGroupInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDataSetPermissionsInput) GoString() string { +func (s UpdateGroupInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateDataSetPermissionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateDataSetPermissionsInput"} +func (s *UpdateGroupInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateGroupInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DataSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSetId")) - } - if s.DataSetId != nil && len(*s.DataSetId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSetId", 1)) + if s.Description != nil && len(*s.Description) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Description", 1)) } - if s.GrantPermissions != nil && len(s.GrantPermissions) < 1 { - invalidParams.Add(request.NewErrParamMinLen("GrantPermissions", 1)) + if s.GroupName == nil { + invalidParams.Add(request.NewErrParamRequired("GroupName")) } - if s.RevokePermissions != nil && len(s.RevokePermissions) < 1 { - invalidParams.Add(request.NewErrParamMinLen("RevokePermissions", 1)) + if s.GroupName != nil && len(*s.GroupName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) } - if s.GrantPermissions != nil { - for i, v := range s.GrantPermissions { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "GrantPermissions", i), err.(request.ErrInvalidParams)) - } - } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) } - if s.RevokePermissions != nil { - for i, v := range s.RevokePermissions { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RevokePermissions", i), err.(request.ErrInvalidParams)) - } - } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) } if invalidParams.Len() > 0 { @@ -21724,38 +28556,34 @@ func (s *UpdateDataSetPermissionsInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateDataSetPermissionsInput) SetAwsAccountId(v string) *UpdateDataSetPermissionsInput { +func (s *UpdateGroupInput) SetAwsAccountId(v string) *UpdateGroupInput { s.AwsAccountId = &v return s } -// SetDataSetId sets the DataSetId field's value. -func (s *UpdateDataSetPermissionsInput) SetDataSetId(v string) *UpdateDataSetPermissionsInput { - s.DataSetId = &v +// SetDescription sets the Description field's value. +func (s *UpdateGroupInput) SetDescription(v string) *UpdateGroupInput { + s.Description = &v return s } -// SetGrantPermissions sets the GrantPermissions field's value. -func (s *UpdateDataSetPermissionsInput) SetGrantPermissions(v []*ResourcePermission) *UpdateDataSetPermissionsInput { - s.GrantPermissions = v +// SetGroupName sets the GroupName field's value. +func (s *UpdateGroupInput) SetGroupName(v string) *UpdateGroupInput { + s.GroupName = &v return s } -// SetRevokePermissions sets the RevokePermissions field's value. -func (s *UpdateDataSetPermissionsInput) SetRevokePermissions(v []*ResourcePermission) *UpdateDataSetPermissionsInput { - s.RevokePermissions = v +// SetNamespace sets the Namespace field's value. +func (s *UpdateGroupInput) SetNamespace(v string) *UpdateGroupInput { + s.Namespace = &v return s } -type UpdateDataSetPermissionsOutput struct { +type UpdateGroupOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the dataset. - DataSetArn *string `type:"string"` - - // The ID for the dataset whose permissions you want to update. This ID is unique - // per AWS Region for each AWS account. - DataSetId *string `type:"string"` + // The name of the group. + Group *Group `type:"structure"` // The AWS request ID for this operation. RequestId *string `type:"string"` @@ -21765,119 +28593,101 @@ type UpdateDataSetPermissionsOutput struct { } // String returns the string representation -func (s UpdateDataSetPermissionsOutput) String() string { +func (s UpdateGroupOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDataSetPermissionsOutput) GoString() string { +func (s UpdateGroupOutput) GoString() string { return s.String() } -// SetDataSetArn sets the DataSetArn field's value. -func (s *UpdateDataSetPermissionsOutput) SetDataSetArn(v string) *UpdateDataSetPermissionsOutput { - s.DataSetArn = &v - return s -} - -// SetDataSetId sets the DataSetId field's value. -func (s *UpdateDataSetPermissionsOutput) SetDataSetId(v string) *UpdateDataSetPermissionsOutput { - s.DataSetId = &v +// SetGroup sets the Group field's value. +func (s *UpdateGroupOutput) SetGroup(v *Group) *UpdateGroupOutput { + s.Group = v return s } // SetRequestId sets the RequestId field's value. -func (s *UpdateDataSetPermissionsOutput) SetRequestId(v string) *UpdateDataSetPermissionsOutput { +func (s *UpdateGroupOutput) SetRequestId(v string) *UpdateGroupOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *UpdateDataSetPermissionsOutput) SetStatus(v int64) *UpdateDataSetPermissionsOutput { +func (s *UpdateGroupOutput) SetStatus(v int64) *UpdateGroupOutput { s.Status = &v return s } -type UpdateDataSourceInput struct { +type UpdateIAMPolicyAssignmentInput struct { _ struct{} `type:"structure"` - // The AWS account ID. + // The name of the assignment. This name must be unique within an AWS account. // - // AwsAccountId is a required field - AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // AssignmentName is a required field + AssignmentName *string `location:"uri" locationName:"AssignmentName" min:"1" type:"string" required:"true"` - // The credentials that QuickSight that uses to connect to your underlying source. - // Currently, only credentials based on user name and password are supported. - Credentials *DataSourceCredentials `type:"structure" sensitive:"true"` + // The status of the assignment. Possible values are as follows: + // + // * ENABLED - Anything specified in this assignment is used when creating + // the data source. + // + // * DISABLED - This assignment isn't used when creating the data source. + // + // * DRAFT - This assignment is an unfinished draft and isn't used when creating + // the data source. + AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` - // The ID of the data source. This ID is unique per AWS Region for each AWS - // account. + // The ID of the AWS account that contains the IAM policy assignment. // - // DataSourceId is a required field - DataSourceId *string `location:"uri" locationName:"DataSourceId" type:"string" required:"true"` + // AwsAccountId is a required field + AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The parameters that QuickSight uses to connect to your underlying source. - DataSourceParameters *DataSourceParameters `type:"structure"` + // The QuickSight users, groups, or both that you want to assign the policy + // to. + Identities map[string][]*string `type:"map"` - // A display name for the data source. + // The namespace of the assignment. // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` - - // Secure Socket Layer (SSL) properties that apply when QuickSight connects - // to your underlying source. - SslProperties *SslProperties `type:"structure"` + // Namespace is a required field + Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` - // Use this parameter only when you want QuickSight to use a VPC connection - // when connecting to your underlying source. - VpcConnectionProperties *VpcConnectionProperties `type:"structure"` + // The ARN for the IAM policy to apply to the QuickSight users and groups specified + // in this assignment. + PolicyArn *string `type:"string"` } // String returns the string representation -func (s UpdateDataSourceInput) String() string { +func (s UpdateIAMPolicyAssignmentInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDataSourceInput) GoString() string { +func (s UpdateIAMPolicyAssignmentInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateDataSourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateDataSourceInput"} +func (s *UpdateIAMPolicyAssignmentInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateIAMPolicyAssignmentInput"} + if s.AssignmentName == nil { + invalidParams.Add(request.NewErrParamRequired("AssignmentName")) + } + if s.AssignmentName != nil && len(*s.AssignmentName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AssignmentName", 1)) + } if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DataSourceId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSourceId")) - } - if s.DataSourceId != nil && len(*s.DataSourceId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSourceId", 1)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.Credentials != nil { - if err := s.Credentials.Validate(); err != nil { - invalidParams.AddNested("Credentials", err.(request.ErrInvalidParams)) - } - } - if s.DataSourceParameters != nil { - if err := s.DataSourceParameters.Validate(); err != nil { - invalidParams.AddNested("DataSourceParameters", err.(request.ErrInvalidParams)) - } + if s.Namespace == nil { + invalidParams.Add(request.NewErrParamRequired("Namespace")) } - if s.VpcConnectionProperties != nil { - if err := s.VpcConnectionProperties.Validate(); err != nil { - invalidParams.AddNested("VpcConnectionProperties", err.(request.ErrInvalidParams)) - } + if s.Namespace != nil && len(*s.Namespace) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) } if invalidParams.Len() > 0 { @@ -21886,179 +28696,191 @@ func (s *UpdateDataSourceInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateDataSourceInput) SetAwsAccountId(v string) *UpdateDataSourceInput { - s.AwsAccountId = &v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *UpdateDataSourceInput) SetCredentials(v *DataSourceCredentials) *UpdateDataSourceInput { - s.Credentials = v +// SetAssignmentName sets the AssignmentName field's value. +func (s *UpdateIAMPolicyAssignmentInput) SetAssignmentName(v string) *UpdateIAMPolicyAssignmentInput { + s.AssignmentName = &v return s } -// SetDataSourceId sets the DataSourceId field's value. -func (s *UpdateDataSourceInput) SetDataSourceId(v string) *UpdateDataSourceInput { - s.DataSourceId = &v +// SetAssignmentStatus sets the AssignmentStatus field's value. +func (s *UpdateIAMPolicyAssignmentInput) SetAssignmentStatus(v string) *UpdateIAMPolicyAssignmentInput { + s.AssignmentStatus = &v return s } -// SetDataSourceParameters sets the DataSourceParameters field's value. -func (s *UpdateDataSourceInput) SetDataSourceParameters(v *DataSourceParameters) *UpdateDataSourceInput { - s.DataSourceParameters = v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *UpdateIAMPolicyAssignmentInput) SetAwsAccountId(v string) *UpdateIAMPolicyAssignmentInput { + s.AwsAccountId = &v return s } -// SetName sets the Name field's value. -func (s *UpdateDataSourceInput) SetName(v string) *UpdateDataSourceInput { - s.Name = &v +// SetIdentities sets the Identities field's value. +func (s *UpdateIAMPolicyAssignmentInput) SetIdentities(v map[string][]*string) *UpdateIAMPolicyAssignmentInput { + s.Identities = v return s } -// SetSslProperties sets the SslProperties field's value. -func (s *UpdateDataSourceInput) SetSslProperties(v *SslProperties) *UpdateDataSourceInput { - s.SslProperties = v +// SetNamespace sets the Namespace field's value. +func (s *UpdateIAMPolicyAssignmentInput) SetNamespace(v string) *UpdateIAMPolicyAssignmentInput { + s.Namespace = &v return s } -// SetVpcConnectionProperties sets the VpcConnectionProperties field's value. -func (s *UpdateDataSourceInput) SetVpcConnectionProperties(v *VpcConnectionProperties) *UpdateDataSourceInput { - s.VpcConnectionProperties = v +// SetPolicyArn sets the PolicyArn field's value. +func (s *UpdateIAMPolicyAssignmentInput) SetPolicyArn(v string) *UpdateIAMPolicyAssignmentInput { + s.PolicyArn = &v return s } -type UpdateDataSourceOutput struct { +type UpdateIAMPolicyAssignmentOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the data source. - Arn *string `type:"string"` + // The ID of the assignment. + AssignmentId *string `type:"string"` - // The ID of the data source. This ID is unique per AWS Region for each AWS - // account. - DataSourceId *string `type:"string"` + // The name of the assignment. + AssignmentName *string `min:"1" type:"string"` + + // The status of the assignment. Possible values are as follows: + // + // * ENABLED - Anything specified in this assignment is used when creating + // the data source. + // + // * DISABLED - This assignment isn't used when creating the data source. + // + // * DRAFT - This assignment is an unfinished draft and isn't used when creating + // the data source. + AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` + + // The QuickSight users, groups, or both that the IAM policy is assigned to. + Identities map[string][]*string `type:"map"` + + // The ARN for the IAM policy applied to the QuickSight users and groups specified + // in this assignment. + PolicyArn *string `type:"string"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - - // The update status of the data source's last update. - UpdateStatus *string `type:"string" enum:"ResourceStatus"` } // String returns the string representation -func (s UpdateDataSourceOutput) String() string { +func (s UpdateIAMPolicyAssignmentOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDataSourceOutput) GoString() string { +func (s UpdateIAMPolicyAssignmentOutput) GoString() string { return s.String() } -// SetArn sets the Arn field's value. -func (s *UpdateDataSourceOutput) SetArn(v string) *UpdateDataSourceOutput { - s.Arn = &v +// SetAssignmentId sets the AssignmentId field's value. +func (s *UpdateIAMPolicyAssignmentOutput) SetAssignmentId(v string) *UpdateIAMPolicyAssignmentOutput { + s.AssignmentId = &v return s } -// SetDataSourceId sets the DataSourceId field's value. -func (s *UpdateDataSourceOutput) SetDataSourceId(v string) *UpdateDataSourceOutput { - s.DataSourceId = &v +// SetAssignmentName sets the AssignmentName field's value. +func (s *UpdateIAMPolicyAssignmentOutput) SetAssignmentName(v string) *UpdateIAMPolicyAssignmentOutput { + s.AssignmentName = &v return s } -// SetRequestId sets the RequestId field's value. -func (s *UpdateDataSourceOutput) SetRequestId(v string) *UpdateDataSourceOutput { - s.RequestId = &v +// SetAssignmentStatus sets the AssignmentStatus field's value. +func (s *UpdateIAMPolicyAssignmentOutput) SetAssignmentStatus(v string) *UpdateIAMPolicyAssignmentOutput { + s.AssignmentStatus = &v return s } -// SetStatus sets the Status field's value. -func (s *UpdateDataSourceOutput) SetStatus(v int64) *UpdateDataSourceOutput { - s.Status = &v +// SetIdentities sets the Identities field's value. +func (s *UpdateIAMPolicyAssignmentOutput) SetIdentities(v map[string][]*string) *UpdateIAMPolicyAssignmentOutput { + s.Identities = v + return s +} + +// SetPolicyArn sets the PolicyArn field's value. +func (s *UpdateIAMPolicyAssignmentOutput) SetPolicyArn(v string) *UpdateIAMPolicyAssignmentOutput { + s.PolicyArn = &v + return s +} + +// SetRequestId sets the RequestId field's value. +func (s *UpdateIAMPolicyAssignmentOutput) SetRequestId(v string) *UpdateIAMPolicyAssignmentOutput { + s.RequestId = &v return s } -// SetUpdateStatus sets the UpdateStatus field's value. -func (s *UpdateDataSourceOutput) SetUpdateStatus(v string) *UpdateDataSourceOutput { - s.UpdateStatus = &v +// SetStatus sets the Status field's value. +func (s *UpdateIAMPolicyAssignmentOutput) SetStatus(v int64) *UpdateIAMPolicyAssignmentOutput { + s.Status = &v return s } -type UpdateDataSourcePermissionsInput struct { +type UpdateTemplateAliasInput struct { _ struct{} `type:"structure"` - // The AWS account ID. + // The alias of the template that you want to update. If you name a specific + // alias, you update the version that the alias points to. You can specify the + // latest version of the template by providing the keyword $LATEST in the AliasName + // parameter. The keyword $PUBLISHED doesn't apply to templates. + // + // AliasName is a required field + AliasName *string `location:"uri" locationName:"AliasName" min:"1" type:"string" required:"true"` + + // The ID of the AWS account that contains the template alias that you're updating. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID of the data source. This ID is unique per AWS Region for each AWS - // account. + // The ID for the template. // - // DataSourceId is a required field - DataSourceId *string `location:"uri" locationName:"DataSourceId" type:"string" required:"true"` - - // A list of resource permissions that you want to grant on the data source. - GrantPermissions []*ResourcePermission `min:"1" type:"list"` + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` - // A list of resource permissions that you want to revoke on the data source. - RevokePermissions []*ResourcePermission `min:"1" type:"list"` + // The version number of the template. + // + // TemplateVersionNumber is a required field + TemplateVersionNumber *int64 `min:"1" type:"long" required:"true"` } // String returns the string representation -func (s UpdateDataSourcePermissionsInput) String() string { +func (s UpdateTemplateAliasInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDataSourcePermissionsInput) GoString() string { +func (s UpdateTemplateAliasInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateDataSourcePermissionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateDataSourcePermissionsInput"} +func (s *UpdateTemplateAliasInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateTemplateAliasInput"} + if s.AliasName == nil { + invalidParams.Add(request.NewErrParamRequired("AliasName")) + } + if s.AliasName != nil && len(*s.AliasName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AliasName", 1)) + } if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.DataSourceId == nil { - invalidParams.Add(request.NewErrParamRequired("DataSourceId")) - } - if s.DataSourceId != nil && len(*s.DataSourceId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("DataSourceId", 1)) - } - if s.GrantPermissions != nil && len(s.GrantPermissions) < 1 { - invalidParams.Add(request.NewErrParamMinLen("GrantPermissions", 1)) + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) } - if s.RevokePermissions != nil && len(s.RevokePermissions) < 1 { - invalidParams.Add(request.NewErrParamMinLen("RevokePermissions", 1)) + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) } - if s.GrantPermissions != nil { - for i, v := range s.GrantPermissions { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "GrantPermissions", i), err.(request.ErrInvalidParams)) - } - } + if s.TemplateVersionNumber == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateVersionNumber")) } - if s.RevokePermissions != nil { - for i, v := range s.RevokePermissions { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RevokePermissions", i), err.(request.ErrInvalidParams)) - } - } + if s.TemplateVersionNumber != nil && *s.TemplateVersionNumber < 1 { + invalidParams.Add(request.NewErrParamMinValue("TemplateVersionNumber", 1)) } if invalidParams.Len() > 0 { @@ -22067,137 +28889,147 @@ func (s *UpdateDataSourcePermissionsInput) Validate() error { return nil } -// SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateDataSourcePermissionsInput) SetAwsAccountId(v string) *UpdateDataSourcePermissionsInput { - s.AwsAccountId = &v +// SetAliasName sets the AliasName field's value. +func (s *UpdateTemplateAliasInput) SetAliasName(v string) *UpdateTemplateAliasInput { + s.AliasName = &v return s } -// SetDataSourceId sets the DataSourceId field's value. -func (s *UpdateDataSourcePermissionsInput) SetDataSourceId(v string) *UpdateDataSourcePermissionsInput { - s.DataSourceId = &v +// SetAwsAccountId sets the AwsAccountId field's value. +func (s *UpdateTemplateAliasInput) SetAwsAccountId(v string) *UpdateTemplateAliasInput { + s.AwsAccountId = &v return s } -// SetGrantPermissions sets the GrantPermissions field's value. -func (s *UpdateDataSourcePermissionsInput) SetGrantPermissions(v []*ResourcePermission) *UpdateDataSourcePermissionsInput { - s.GrantPermissions = v +// SetTemplateId sets the TemplateId field's value. +func (s *UpdateTemplateAliasInput) SetTemplateId(v string) *UpdateTemplateAliasInput { + s.TemplateId = &v return s } -// SetRevokePermissions sets the RevokePermissions field's value. -func (s *UpdateDataSourcePermissionsInput) SetRevokePermissions(v []*ResourcePermission) *UpdateDataSourcePermissionsInput { - s.RevokePermissions = v +// SetTemplateVersionNumber sets the TemplateVersionNumber field's value. +func (s *UpdateTemplateAliasInput) SetTemplateVersionNumber(v int64) *UpdateTemplateAliasInput { + s.TemplateVersionNumber = &v return s } -type UpdateDataSourcePermissionsOutput struct { +type UpdateTemplateAliasOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the data source. - DataSourceArn *string `type:"string"` - - // The ID of the data source. This ID is unique per AWS Region for each AWS - // account. - DataSourceId *string `type:"string"` - // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // The template alias. + TemplateAlias *TemplateAlias `type:"structure"` } // String returns the string representation -func (s UpdateDataSourcePermissionsOutput) String() string { +func (s UpdateTemplateAliasOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateDataSourcePermissionsOutput) GoString() string { +func (s UpdateTemplateAliasOutput) GoString() string { return s.String() } -// SetDataSourceArn sets the DataSourceArn field's value. -func (s *UpdateDataSourcePermissionsOutput) SetDataSourceArn(v string) *UpdateDataSourcePermissionsOutput { - s.DataSourceArn = &v - return s -} - -// SetDataSourceId sets the DataSourceId field's value. -func (s *UpdateDataSourcePermissionsOutput) SetDataSourceId(v string) *UpdateDataSourcePermissionsOutput { - s.DataSourceId = &v - return s -} - // SetRequestId sets the RequestId field's value. -func (s *UpdateDataSourcePermissionsOutput) SetRequestId(v string) *UpdateDataSourcePermissionsOutput { +func (s *UpdateTemplateAliasOutput) SetRequestId(v string) *UpdateTemplateAliasOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *UpdateDataSourcePermissionsOutput) SetStatus(v int64) *UpdateDataSourcePermissionsOutput { +func (s *UpdateTemplateAliasOutput) SetStatus(v int64) *UpdateTemplateAliasOutput { s.Status = &v return s } -type UpdateGroupInput struct { +// SetTemplateAlias sets the TemplateAlias field's value. +func (s *UpdateTemplateAliasOutput) SetTemplateAlias(v *TemplateAlias) *UpdateTemplateAliasOutput { + s.TemplateAlias = v + return s +} + +type UpdateTemplateInput struct { _ struct{} `type:"structure"` - // The ID for the AWS account that the group is in. Currently, you use the ID - // for the AWS account that contains your Amazon QuickSight account. + // The ID of the AWS account that contains the template that you're updating. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The description for the group that you want to update. - Description *string `min:"1" type:"string"` + // The name for the template. + Name *string `min:"1" type:"string"` - // The name of the group that you want to update. + // The entity that you are using as a source when you update the template. In + // SourceEntity, you specify the type of object you're using as source: SourceTemplate + // for a template or SourceAnalysis for an analysis. Both of these require an + // Amazon Resource Name (ARN). For SourceTemplate, specify the ARN of the source + // template. For SourceAnalysis, specify the ARN of the source analysis. The + // SourceTemplate ARN can contain any AWS Account and any QuickSight-supported + // AWS Region. // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + // Use the DataSetReferences entity within SourceTemplate or SourceAnalysis + // to list the replacement datasets for the placeholders listed in the original. + // The schema in each dataset must match its placeholder. + // + // SourceEntity is a required field + SourceEntity *TemplateSourceEntity `type:"structure" required:"true"` - // The namespace. Currently, you should set this to default. + // The ID for the template. // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + + // A description of the current template version that is being updated. Every + // time you call UpdateTemplate, you create a new version of the template. Each + // version of the template maintains a description of the version in the VersionDescription + // field. + VersionDescription *string `min:"1" type:"string"` } // String returns the string representation -func (s UpdateGroupInput) String() string { +func (s UpdateTemplateInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateGroupInput) GoString() string { +func (s UpdateTemplateInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateGroupInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateGroupInput"} +func (s *UpdateTemplateInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateTemplateInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Description != nil && len(*s.Description) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Description", 1)) + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) + if s.SourceEntity == nil { + invalidParams.Add(request.NewErrParamRequired("SourceEntity")) } - if s.GroupName != nil && len(*s.GroupName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.VersionDescription != nil && len(*s.VersionDescription) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VersionDescription", 1)) + } + if s.SourceEntity != nil { + if err := s.SourceEntity.Validate(); err != nil { + invalidParams.AddNested("SourceEntity", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -22207,138 +29039,168 @@ func (s *UpdateGroupInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateGroupInput) SetAwsAccountId(v string) *UpdateGroupInput { +func (s *UpdateTemplateInput) SetAwsAccountId(v string) *UpdateTemplateInput { s.AwsAccountId = &v return s } -// SetDescription sets the Description field's value. -func (s *UpdateGroupInput) SetDescription(v string) *UpdateGroupInput { - s.Description = &v +// SetName sets the Name field's value. +func (s *UpdateTemplateInput) SetName(v string) *UpdateTemplateInput { + s.Name = &v return s } -// SetGroupName sets the GroupName field's value. -func (s *UpdateGroupInput) SetGroupName(v string) *UpdateGroupInput { - s.GroupName = &v +// SetSourceEntity sets the SourceEntity field's value. +func (s *UpdateTemplateInput) SetSourceEntity(v *TemplateSourceEntity) *UpdateTemplateInput { + s.SourceEntity = v return s } -// SetNamespace sets the Namespace field's value. -func (s *UpdateGroupInput) SetNamespace(v string) *UpdateGroupInput { - s.Namespace = &v +// SetTemplateId sets the TemplateId field's value. +func (s *UpdateTemplateInput) SetTemplateId(v string) *UpdateTemplateInput { + s.TemplateId = &v return s } -type UpdateGroupOutput struct { +// SetVersionDescription sets the VersionDescription field's value. +func (s *UpdateTemplateInput) SetVersionDescription(v string) *UpdateTemplateInput { + s.VersionDescription = &v + return s +} + +type UpdateTemplateOutput struct { _ struct{} `type:"structure"` - // The name of the group. - Group *Group `type:"structure"` + // The Amazon Resource Name (ARN) for the template. + Arn *string `type:"string"` + + // The creation status of the template. + CreationStatus *string `type:"string" enum:"ResourceStatus"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // The ID for the template. + TemplateId *string `min:"1" type:"string"` + + // The ARN for the template, including the version information of the first + // version. + VersionArn *string `type:"string"` } // String returns the string representation -func (s UpdateGroupOutput) String() string { +func (s UpdateTemplateOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateGroupOutput) GoString() string { +func (s UpdateTemplateOutput) GoString() string { return s.String() } -// SetGroup sets the Group field's value. -func (s *UpdateGroupOutput) SetGroup(v *Group) *UpdateGroupOutput { - s.Group = v +// SetArn sets the Arn field's value. +func (s *UpdateTemplateOutput) SetArn(v string) *UpdateTemplateOutput { + s.Arn = &v + return s +} + +// SetCreationStatus sets the CreationStatus field's value. +func (s *UpdateTemplateOutput) SetCreationStatus(v string) *UpdateTemplateOutput { + s.CreationStatus = &v return s } // SetRequestId sets the RequestId field's value. -func (s *UpdateGroupOutput) SetRequestId(v string) *UpdateGroupOutput { +func (s *UpdateTemplateOutput) SetRequestId(v string) *UpdateTemplateOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *UpdateGroupOutput) SetStatus(v int64) *UpdateGroupOutput { +func (s *UpdateTemplateOutput) SetStatus(v int64) *UpdateTemplateOutput { s.Status = &v return s } -type UpdateIAMPolicyAssignmentInput struct { - _ struct{} `type:"structure"` +// SetTemplateId sets the TemplateId field's value. +func (s *UpdateTemplateOutput) SetTemplateId(v string) *UpdateTemplateOutput { + s.TemplateId = &v + return s +} - // The name of the assignment. This name must be unique within an AWS account. - // - // AssignmentName is a required field - AssignmentName *string `location:"uri" locationName:"AssignmentName" min:"1" type:"string" required:"true"` +// SetVersionArn sets the VersionArn field's value. +func (s *UpdateTemplateOutput) SetVersionArn(v string) *UpdateTemplateOutput { + s.VersionArn = &v + return s +} - // The status of the assignment. Possible values are as follows: - // - // * ENABLED - Anything specified in this assignment is used when creating - // the data source. - // - // * DISABLED - This assignment isn't used when creating the data source. - // - // * DRAFT - This assignment is an unfinished draft and isn't used when creating - // the data source. - AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` +type UpdateTemplatePermissionsInput struct { + _ struct{} `type:"structure"` - // The ID of the AWS account that contains the IAM policy assignment. + // The ID of the AWS account that contains the template. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The QuickSight users, groups, or both that you want to assign the policy - // to. - Identities map[string][]*string `type:"map"` + // A list of resource permissions to be granted on the template. + GrantPermissions []*ResourcePermission `type:"list"` - // The namespace of the assignment. - // - // Namespace is a required field - Namespace *string `location:"uri" locationName:"Namespace" type:"string" required:"true"` + // A list of resource permissions to be revoked from the template. + RevokePermissions []*ResourcePermission `type:"list"` - // The ARN for the IAM policy to apply to the QuickSight users and groups specified - // in this assignment. - PolicyArn *string `type:"string"` + // The ID for the template. + // + // TemplateId is a required field + TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s UpdateIAMPolicyAssignmentInput) String() string { +func (s UpdateTemplatePermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateIAMPolicyAssignmentInput) GoString() string { +func (s UpdateTemplatePermissionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateIAMPolicyAssignmentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateIAMPolicyAssignmentInput"} - if s.AssignmentName == nil { - invalidParams.Add(request.NewErrParamRequired("AssignmentName")) - } - if s.AssignmentName != nil && len(*s.AssignmentName) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AssignmentName", 1)) - } +func (s *UpdateTemplatePermissionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateTemplatePermissionsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.Namespace == nil { - invalidParams.Add(request.NewErrParamRequired("Namespace")) + if s.TemplateId == nil { + invalidParams.Add(request.NewErrParamRequired("TemplateId")) } - if s.Namespace != nil && len(*s.Namespace) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Namespace", 1)) + if s.TemplateId != nil && len(*s.TemplateId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + } + if s.GrantPermissions != nil { + for i, v := range s.GrantPermissions { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "GrantPermissions", i), err.(request.ErrInvalidParams)) + } + } + } + if s.RevokePermissions != nil { + for i, v := range s.RevokePermissions { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RevokePermissions", i), err.(request.ErrInvalidParams)) + } + } } if invalidParams.Len() > 0 { @@ -22347,168 +29209,126 @@ func (s *UpdateIAMPolicyAssignmentInput) Validate() error { return nil } -// SetAssignmentName sets the AssignmentName field's value. -func (s *UpdateIAMPolicyAssignmentInput) SetAssignmentName(v string) *UpdateIAMPolicyAssignmentInput { - s.AssignmentName = &v - return s -} - -// SetAssignmentStatus sets the AssignmentStatus field's value. -func (s *UpdateIAMPolicyAssignmentInput) SetAssignmentStatus(v string) *UpdateIAMPolicyAssignmentInput { - s.AssignmentStatus = &v - return s -} - // SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateIAMPolicyAssignmentInput) SetAwsAccountId(v string) *UpdateIAMPolicyAssignmentInput { +func (s *UpdateTemplatePermissionsInput) SetAwsAccountId(v string) *UpdateTemplatePermissionsInput { s.AwsAccountId = &v return s } -// SetIdentities sets the Identities field's value. -func (s *UpdateIAMPolicyAssignmentInput) SetIdentities(v map[string][]*string) *UpdateIAMPolicyAssignmentInput { - s.Identities = v +// SetGrantPermissions sets the GrantPermissions field's value. +func (s *UpdateTemplatePermissionsInput) SetGrantPermissions(v []*ResourcePermission) *UpdateTemplatePermissionsInput { + s.GrantPermissions = v return s } -// SetNamespace sets the Namespace field's value. -func (s *UpdateIAMPolicyAssignmentInput) SetNamespace(v string) *UpdateIAMPolicyAssignmentInput { - s.Namespace = &v +// SetRevokePermissions sets the RevokePermissions field's value. +func (s *UpdateTemplatePermissionsInput) SetRevokePermissions(v []*ResourcePermission) *UpdateTemplatePermissionsInput { + s.RevokePermissions = v return s } -// SetPolicyArn sets the PolicyArn field's value. -func (s *UpdateIAMPolicyAssignmentInput) SetPolicyArn(v string) *UpdateIAMPolicyAssignmentInput { - s.PolicyArn = &v +// SetTemplateId sets the TemplateId field's value. +func (s *UpdateTemplatePermissionsInput) SetTemplateId(v string) *UpdateTemplatePermissionsInput { + s.TemplateId = &v return s } -type UpdateIAMPolicyAssignmentOutput struct { +type UpdateTemplatePermissionsOutput struct { _ struct{} `type:"structure"` - // The ID of the assignment. - AssignmentId *string `type:"string"` - - // The name of the assignment. - AssignmentName *string `min:"1" type:"string"` - - // The status of the assignment. Possible values are as follows: - // - // * ENABLED - Anything specified in this assignment is used when creating - // the data source. - // - // * DISABLED - This assignment isn't used when creating the data source. - // - // * DRAFT - This assignment is an unfinished draft and isn't used when creating - // the data source. - AssignmentStatus *string `type:"string" enum:"AssignmentStatus"` - - // The QuickSight users, groups, or both that the IAM policy is assigned to. - Identities map[string][]*string `type:"map"` - - // The ARN for the IAM policy applied to the QuickSight users and groups specified - // in this assignment. - PolicyArn *string `type:"string"` + // A list of resource permissions to be set on the template. + Permissions []*ResourcePermission `min:"1" type:"list"` // The AWS request ID for this operation. RequestId *string `type:"string"` // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` + + // The Amazon Resource Name (ARN) of the template. + TemplateArn *string `type:"string"` + + // The ID for the template. + TemplateId *string `min:"1" type:"string"` } // String returns the string representation -func (s UpdateIAMPolicyAssignmentOutput) String() string { +func (s UpdateTemplatePermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateIAMPolicyAssignmentOutput) GoString() string { +func (s UpdateTemplatePermissionsOutput) GoString() string { return s.String() } -// SetAssignmentId sets the AssignmentId field's value. -func (s *UpdateIAMPolicyAssignmentOutput) SetAssignmentId(v string) *UpdateIAMPolicyAssignmentOutput { - s.AssignmentId = &v - return s -} - -// SetAssignmentName sets the AssignmentName field's value. -func (s *UpdateIAMPolicyAssignmentOutput) SetAssignmentName(v string) *UpdateIAMPolicyAssignmentOutput { - s.AssignmentName = &v - return s -} - -// SetAssignmentStatus sets the AssignmentStatus field's value. -func (s *UpdateIAMPolicyAssignmentOutput) SetAssignmentStatus(v string) *UpdateIAMPolicyAssignmentOutput { - s.AssignmentStatus = &v +// SetPermissions sets the Permissions field's value. +func (s *UpdateTemplatePermissionsOutput) SetPermissions(v []*ResourcePermission) *UpdateTemplatePermissionsOutput { + s.Permissions = v return s } -// SetIdentities sets the Identities field's value. -func (s *UpdateIAMPolicyAssignmentOutput) SetIdentities(v map[string][]*string) *UpdateIAMPolicyAssignmentOutput { - s.Identities = v +// SetRequestId sets the RequestId field's value. +func (s *UpdateTemplatePermissionsOutput) SetRequestId(v string) *UpdateTemplatePermissionsOutput { + s.RequestId = &v return s } -// SetPolicyArn sets the PolicyArn field's value. -func (s *UpdateIAMPolicyAssignmentOutput) SetPolicyArn(v string) *UpdateIAMPolicyAssignmentOutput { - s.PolicyArn = &v +// SetStatus sets the Status field's value. +func (s *UpdateTemplatePermissionsOutput) SetStatus(v int64) *UpdateTemplatePermissionsOutput { + s.Status = &v return s } -// SetRequestId sets the RequestId field's value. -func (s *UpdateIAMPolicyAssignmentOutput) SetRequestId(v string) *UpdateIAMPolicyAssignmentOutput { - s.RequestId = &v +// SetTemplateArn sets the TemplateArn field's value. +func (s *UpdateTemplatePermissionsOutput) SetTemplateArn(v string) *UpdateTemplatePermissionsOutput { + s.TemplateArn = &v return s } -// SetStatus sets the Status field's value. -func (s *UpdateIAMPolicyAssignmentOutput) SetStatus(v int64) *UpdateIAMPolicyAssignmentOutput { - s.Status = &v +// SetTemplateId sets the TemplateId field's value. +func (s *UpdateTemplatePermissionsOutput) SetTemplateId(v string) *UpdateTemplatePermissionsOutput { + s.TemplateId = &v return s } -type UpdateTemplateAliasInput struct { +type UpdateThemeAliasInput struct { _ struct{} `type:"structure"` - // The alias of the template that you want to update. If you name a specific - // alias, you update the version that the alias points to. You can specify the - // latest version of the template by providing the keyword $LATEST in the AliasName - // parameter. The keyword $PUBLISHED doesn't apply to templates. + // The name of the theme alias that you want to update. // // AliasName is a required field AliasName *string `location:"uri" locationName:"AliasName" min:"1" type:"string" required:"true"` - // The ID of the AWS account that contains the template alias that you're updating. + // The ID of the AWS account that contains the theme alias that you're updating. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The ID for the template. + // The ID for the theme. // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` - // The version number of the template. + // The version number of the theme that the alias should reference. // - // TemplateVersionNumber is a required field - TemplateVersionNumber *int64 `min:"1" type:"long" required:"true"` + // ThemeVersionNumber is a required field + ThemeVersionNumber *int64 `min:"1" type:"long" required:"true"` } // String returns the string representation -func (s UpdateTemplateAliasInput) String() string { +func (s UpdateThemeAliasInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateTemplateAliasInput) GoString() string { +func (s UpdateThemeAliasInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateTemplateAliasInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateTemplateAliasInput"} +func (s *UpdateThemeAliasInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateThemeAliasInput"} if s.AliasName == nil { invalidParams.Add(request.NewErrParamRequired("AliasName")) } @@ -22521,17 +29341,17 @@ func (s *UpdateTemplateAliasInput) Validate() error { if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) } - if s.TemplateVersionNumber == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateVersionNumber")) + if s.ThemeVersionNumber == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeVersionNumber")) } - if s.TemplateVersionNumber != nil && *s.TemplateVersionNumber < 1 { - invalidParams.Add(request.NewErrParamMinValue("TemplateVersionNumber", 1)) + if s.ThemeVersionNumber != nil && *s.ThemeVersionNumber < 1 { + invalidParams.Add(request.NewErrParamMinValue("ThemeVersionNumber", 1)) } if invalidParams.Len() > 0 { @@ -22541,30 +29361,30 @@ func (s *UpdateTemplateAliasInput) Validate() error { } // SetAliasName sets the AliasName field's value. -func (s *UpdateTemplateAliasInput) SetAliasName(v string) *UpdateTemplateAliasInput { +func (s *UpdateThemeAliasInput) SetAliasName(v string) *UpdateThemeAliasInput { s.AliasName = &v return s } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateTemplateAliasInput) SetAwsAccountId(v string) *UpdateTemplateAliasInput { +func (s *UpdateThemeAliasInput) SetAwsAccountId(v string) *UpdateThemeAliasInput { s.AwsAccountId = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *UpdateTemplateAliasInput) SetTemplateId(v string) *UpdateTemplateAliasInput { - s.TemplateId = &v +// SetThemeId sets the ThemeId field's value. +func (s *UpdateThemeAliasInput) SetThemeId(v string) *UpdateThemeAliasInput { + s.ThemeId = &v return s } -// SetTemplateVersionNumber sets the TemplateVersionNumber field's value. -func (s *UpdateTemplateAliasInput) SetTemplateVersionNumber(v int64) *UpdateTemplateAliasInput { - s.TemplateVersionNumber = &v +// SetThemeVersionNumber sets the ThemeVersionNumber field's value. +func (s *UpdateThemeAliasInput) SetThemeVersionNumber(v int64) *UpdateThemeAliasInput { + s.ThemeVersionNumber = &v return s } -type UpdateTemplateAliasOutput struct { +type UpdateThemeAliasOutput struct { _ struct{} `type:"structure"` // The AWS request ID for this operation. @@ -22573,106 +29393,106 @@ type UpdateTemplateAliasOutput struct { // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - // The template alias. - TemplateAlias *TemplateAlias `type:"structure"` + // Information about the theme alias. + ThemeAlias *ThemeAlias `type:"structure"` } // String returns the string representation -func (s UpdateTemplateAliasOutput) String() string { +func (s UpdateThemeAliasOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateTemplateAliasOutput) GoString() string { +func (s UpdateThemeAliasOutput) GoString() string { return s.String() } // SetRequestId sets the RequestId field's value. -func (s *UpdateTemplateAliasOutput) SetRequestId(v string) *UpdateTemplateAliasOutput { +func (s *UpdateThemeAliasOutput) SetRequestId(v string) *UpdateThemeAliasOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *UpdateTemplateAliasOutput) SetStatus(v int64) *UpdateTemplateAliasOutput { +func (s *UpdateThemeAliasOutput) SetStatus(v int64) *UpdateThemeAliasOutput { s.Status = &v return s -} - -// SetTemplateAlias sets the TemplateAlias field's value. -func (s *UpdateTemplateAliasOutput) SetTemplateAlias(v *TemplateAlias) *UpdateTemplateAliasOutput { - s.TemplateAlias = v +} + +// SetThemeAlias sets the ThemeAlias field's value. +func (s *UpdateThemeAliasOutput) SetThemeAlias(v *ThemeAlias) *UpdateThemeAliasOutput { + s.ThemeAlias = v return s } -type UpdateTemplateInput struct { +type UpdateThemeInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the template that you're updating. + // The ID of the AWS account that contains the theme that you're updating. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // The name for the template. - Name *string `min:"1" type:"string"` - - // The source QuickSight entity from which this template is being updated. You - // can currently update templates from an Analysis or another template. + // The theme ID, defined by Amazon QuickSight, that a custom theme inherits + // from. All themes initially inherit from a default QuickSight theme. // - // SourceEntity is a required field - SourceEntity *TemplateSourceEntity `type:"structure" required:"true"` + // BaseThemeId is a required field + BaseThemeId *string `min:"1" type:"string" required:"true"` - // The ID for the template. + // The theme configuration, which contains the theme display properties. + Configuration *ThemeConfiguration `type:"structure"` + + // The name for the theme. + Name *string `min:"1" type:"string"` + + // The ID for the theme. // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` - // A description of the current template version that is being updated. Every - // time you call UpdateTemplate, you create a new version of the template. Each - // version of the template maintains a description of the version in the VersionDescription - // field. + // A description of the theme version that you're updating Every time that you + // call UpdateTheme, you create a new version of the theme. Each version of + // the theme maintains a description of the version in VersionDescription. VersionDescription *string `min:"1" type:"string"` } // String returns the string representation -func (s UpdateTemplateInput) String() string { +func (s UpdateThemeInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateTemplateInput) GoString() string { +func (s UpdateThemeInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateTemplateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateTemplateInput"} +func (s *UpdateThemeInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateThemeInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } + if s.BaseThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("BaseThemeId")) + } + if s.BaseThemeId != nil && len(*s.BaseThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("BaseThemeId", 1)) + } if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } - if s.SourceEntity == nil { - invalidParams.Add(request.NewErrParamRequired("SourceEntity")) - } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) } if s.VersionDescription != nil && len(*s.VersionDescription) < 1 { invalidParams.Add(request.NewErrParamMinLen("VersionDescription", 1)) } - if s.SourceEntity != nil { - if err := s.SourceEntity.Validate(); err != nil { - invalidParams.AddNested("SourceEntity", err.(request.ErrInvalidParams)) - } - } if invalidParams.Len() > 0 { return invalidParams @@ -22681,42 +29501,48 @@ func (s *UpdateTemplateInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateTemplateInput) SetAwsAccountId(v string) *UpdateTemplateInput { +func (s *UpdateThemeInput) SetAwsAccountId(v string) *UpdateThemeInput { s.AwsAccountId = &v return s } -// SetName sets the Name field's value. -func (s *UpdateTemplateInput) SetName(v string) *UpdateTemplateInput { - s.Name = &v +// SetBaseThemeId sets the BaseThemeId field's value. +func (s *UpdateThemeInput) SetBaseThemeId(v string) *UpdateThemeInput { + s.BaseThemeId = &v return s } -// SetSourceEntity sets the SourceEntity field's value. -func (s *UpdateTemplateInput) SetSourceEntity(v *TemplateSourceEntity) *UpdateTemplateInput { - s.SourceEntity = v +// SetConfiguration sets the Configuration field's value. +func (s *UpdateThemeInput) SetConfiguration(v *ThemeConfiguration) *UpdateThemeInput { + s.Configuration = v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *UpdateTemplateInput) SetTemplateId(v string) *UpdateTemplateInput { - s.TemplateId = &v +// SetName sets the Name field's value. +func (s *UpdateThemeInput) SetName(v string) *UpdateThemeInput { + s.Name = &v + return s +} + +// SetThemeId sets the ThemeId field's value. +func (s *UpdateThemeInput) SetThemeId(v string) *UpdateThemeInput { + s.ThemeId = &v return s } // SetVersionDescription sets the VersionDescription field's value. -func (s *UpdateTemplateInput) SetVersionDescription(v string) *UpdateTemplateInput { +func (s *UpdateThemeInput) SetVersionDescription(v string) *UpdateThemeInput { s.VersionDescription = &v return s } -type UpdateTemplateOutput struct { +type UpdateThemeOutput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) for the template. + // The Amazon Resource Name (ARN) for the theme. Arn *string `type:"string"` - // The creation status of the template. + // The creation status of the theme. CreationStatus *string `type:"string" enum:"ResourceStatus"` // The AWS request ID for this operation. @@ -22725,110 +29551,103 @@ type UpdateTemplateOutput struct { // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - // The ID for the template. - TemplateId *string `min:"1" type:"string"` + // The ID for the theme. + ThemeId *string `min:"1" type:"string"` - // The ARN for the template, including the version information of the first - // version. + // The Amazon Resource Name (ARN) for the new version of the theme. VersionArn *string `type:"string"` } // String returns the string representation -func (s UpdateTemplateOutput) String() string { +func (s UpdateThemeOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateTemplateOutput) GoString() string { +func (s UpdateThemeOutput) GoString() string { return s.String() } // SetArn sets the Arn field's value. -func (s *UpdateTemplateOutput) SetArn(v string) *UpdateTemplateOutput { +func (s *UpdateThemeOutput) SetArn(v string) *UpdateThemeOutput { s.Arn = &v return s } // SetCreationStatus sets the CreationStatus field's value. -func (s *UpdateTemplateOutput) SetCreationStatus(v string) *UpdateTemplateOutput { +func (s *UpdateThemeOutput) SetCreationStatus(v string) *UpdateThemeOutput { s.CreationStatus = &v return s } // SetRequestId sets the RequestId field's value. -func (s *UpdateTemplateOutput) SetRequestId(v string) *UpdateTemplateOutput { +func (s *UpdateThemeOutput) SetRequestId(v string) *UpdateThemeOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *UpdateTemplateOutput) SetStatus(v int64) *UpdateTemplateOutput { +func (s *UpdateThemeOutput) SetStatus(v int64) *UpdateThemeOutput { s.Status = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *UpdateTemplateOutput) SetTemplateId(v string) *UpdateTemplateOutput { - s.TemplateId = &v +// SetThemeId sets the ThemeId field's value. +func (s *UpdateThemeOutput) SetThemeId(v string) *UpdateThemeOutput { + s.ThemeId = &v return s } // SetVersionArn sets the VersionArn field's value. -func (s *UpdateTemplateOutput) SetVersionArn(v string) *UpdateTemplateOutput { +func (s *UpdateThemeOutput) SetVersionArn(v string) *UpdateThemeOutput { s.VersionArn = &v return s } -type UpdateTemplatePermissionsInput struct { +type UpdateThemePermissionsInput struct { _ struct{} `type:"structure"` - // The ID of the AWS account that contains the template. + // The ID of the AWS account that contains the theme. // // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` - // A list of resource permissions to be granted on the template. - GrantPermissions []*ResourcePermission `min:"1" type:"list"` + // A list of resource permissions to be granted for the theme. + GrantPermissions []*ResourcePermission `type:"list"` - // A list of resource permissions to be revoked from the template. - RevokePermissions []*ResourcePermission `min:"1" type:"list"` + // A list of resource permissions to be revoked from the theme. + RevokePermissions []*ResourcePermission `type:"list"` - // The ID for the template. + // The ID for the theme. // - // TemplateId is a required field - TemplateId *string `location:"uri" locationName:"TemplateId" min:"1" type:"string" required:"true"` + // ThemeId is a required field + ThemeId *string `location:"uri" locationName:"ThemeId" min:"1" type:"string" required:"true"` } // String returns the string representation -func (s UpdateTemplatePermissionsInput) String() string { +func (s UpdateThemePermissionsInput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateTemplatePermissionsInput) GoString() string { +func (s UpdateThemePermissionsInput) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateTemplatePermissionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateTemplatePermissionsInput"} +func (s *UpdateThemePermissionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateThemePermissionsInput"} if s.AwsAccountId == nil { invalidParams.Add(request.NewErrParamRequired("AwsAccountId")) } if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } - if s.GrantPermissions != nil && len(s.GrantPermissions) < 1 { - invalidParams.Add(request.NewErrParamMinLen("GrantPermissions", 1)) - } - if s.RevokePermissions != nil && len(s.RevokePermissions) < 1 { - invalidParams.Add(request.NewErrParamMinLen("RevokePermissions", 1)) - } - if s.TemplateId == nil { - invalidParams.Add(request.NewErrParamRequired("TemplateId")) + if s.ThemeId == nil { + invalidParams.Add(request.NewErrParamRequired("ThemeId")) } - if s.TemplateId != nil && len(*s.TemplateId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TemplateId", 1)) + if s.ThemeId != nil && len(*s.ThemeId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ThemeId", 1)) } if s.GrantPermissions != nil { for i, v := range s.GrantPermissions { @@ -22858,33 +29677,33 @@ func (s *UpdateTemplatePermissionsInput) Validate() error { } // SetAwsAccountId sets the AwsAccountId field's value. -func (s *UpdateTemplatePermissionsInput) SetAwsAccountId(v string) *UpdateTemplatePermissionsInput { +func (s *UpdateThemePermissionsInput) SetAwsAccountId(v string) *UpdateThemePermissionsInput { s.AwsAccountId = &v return s } // SetGrantPermissions sets the GrantPermissions field's value. -func (s *UpdateTemplatePermissionsInput) SetGrantPermissions(v []*ResourcePermission) *UpdateTemplatePermissionsInput { +func (s *UpdateThemePermissionsInput) SetGrantPermissions(v []*ResourcePermission) *UpdateThemePermissionsInput { s.GrantPermissions = v return s } // SetRevokePermissions sets the RevokePermissions field's value. -func (s *UpdateTemplatePermissionsInput) SetRevokePermissions(v []*ResourcePermission) *UpdateTemplatePermissionsInput { +func (s *UpdateThemePermissionsInput) SetRevokePermissions(v []*ResourcePermission) *UpdateThemePermissionsInput { s.RevokePermissions = v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *UpdateTemplatePermissionsInput) SetTemplateId(v string) *UpdateTemplatePermissionsInput { - s.TemplateId = &v +// SetThemeId sets the ThemeId field's value. +func (s *UpdateThemePermissionsInput) SetThemeId(v string) *UpdateThemePermissionsInput { + s.ThemeId = &v return s } -type UpdateTemplatePermissionsOutput struct { +type UpdateThemePermissionsOutput struct { _ struct{} `type:"structure"` - // A list of resource permissions to be set on the template. + // The resulting list of resource permissions for the theme. Permissions []*ResourcePermission `min:"1" type:"list"` // The AWS request ID for this operation. @@ -22893,50 +29712,50 @@ type UpdateTemplatePermissionsOutput struct { // The HTTP status of the request. Status *int64 `location:"statusCode" type:"integer"` - // The Amazon Resource Name (ARN) of the template. - TemplateArn *string `type:"string"` + // The Amazon Resource Name (ARN) of the theme. + ThemeArn *string `type:"string"` - // The ID for the template. - TemplateId *string `min:"1" type:"string"` + // The ID for the theme. + ThemeId *string `min:"1" type:"string"` } // String returns the string representation -func (s UpdateTemplatePermissionsOutput) String() string { +func (s UpdateThemePermissionsOutput) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateTemplatePermissionsOutput) GoString() string { +func (s UpdateThemePermissionsOutput) GoString() string { return s.String() } // SetPermissions sets the Permissions field's value. -func (s *UpdateTemplatePermissionsOutput) SetPermissions(v []*ResourcePermission) *UpdateTemplatePermissionsOutput { +func (s *UpdateThemePermissionsOutput) SetPermissions(v []*ResourcePermission) *UpdateThemePermissionsOutput { s.Permissions = v return s } // SetRequestId sets the RequestId field's value. -func (s *UpdateTemplatePermissionsOutput) SetRequestId(v string) *UpdateTemplatePermissionsOutput { +func (s *UpdateThemePermissionsOutput) SetRequestId(v string) *UpdateThemePermissionsOutput { s.RequestId = &v return s } // SetStatus sets the Status field's value. -func (s *UpdateTemplatePermissionsOutput) SetStatus(v int64) *UpdateTemplatePermissionsOutput { +func (s *UpdateThemePermissionsOutput) SetStatus(v int64) *UpdateThemePermissionsOutput { s.Status = &v return s } -// SetTemplateArn sets the TemplateArn field's value. -func (s *UpdateTemplatePermissionsOutput) SetTemplateArn(v string) *UpdateTemplatePermissionsOutput { - s.TemplateArn = &v +// SetThemeArn sets the ThemeArn field's value. +func (s *UpdateThemePermissionsOutput) SetThemeArn(v string) *UpdateThemePermissionsOutput { + s.ThemeArn = &v return s } -// SetTemplateId sets the TemplateId field's value. -func (s *UpdateTemplatePermissionsOutput) SetTemplateId(v string) *UpdateTemplatePermissionsOutput { - s.TemplateId = &v +// SetThemeId sets the ThemeId field's value. +func (s *UpdateThemePermissionsOutput) SetThemeId(v string) *UpdateThemePermissionsOutput { + s.ThemeId = &v return s } @@ -22949,6 +29768,12 @@ type UpdateUserInput struct { // AwsAccountId is a required field AwsAccountId *string `location:"uri" locationName:"AwsAccountId" min:"12" type:"string" required:"true"` + // The name of the custom permissions profile that you want to assign to this + // user. Currently, custom permissions profile names are assigned to permissions + // profiles in the QuickSight console. You use this API to assign the named + // set of permissions to a QuickSight user. + CustomPermissionsName *string `min:"1" type:"string"` + // The email address of the user that you want to update. // // Email is a required field @@ -22972,6 +29797,12 @@ type UpdateUserInput struct { // Role is a required field Role *string `type:"string" required:"true" enum:"UserRole"` + // A flag that you use to indicate that you want to remove all custom permissions + // from this user. Using this parameter resets the user to the state it was + // in before a custom permissions profile was applied. This parameter defaults + // to NULL and it doesn't accept any other value. + UnapplyCustomPermissions *bool `type:"boolean"` + // The Amazon QuickSight user name that you want to update. // // UserName is a required field @@ -22997,6 +29828,9 @@ func (s *UpdateUserInput) Validate() error { if s.AwsAccountId != nil && len(*s.AwsAccountId) < 12 { invalidParams.Add(request.NewErrParamMinLen("AwsAccountId", 12)) } + if s.CustomPermissionsName != nil && len(*s.CustomPermissionsName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("CustomPermissionsName", 1)) + } if s.Email == nil { invalidParams.Add(request.NewErrParamRequired("Email")) } @@ -23028,6 +29862,12 @@ func (s *UpdateUserInput) SetAwsAccountId(v string) *UpdateUserInput { return s } +// SetCustomPermissionsName sets the CustomPermissionsName field's value. +func (s *UpdateUserInput) SetCustomPermissionsName(v string) *UpdateUserInput { + s.CustomPermissionsName = &v + return s +} + // SetEmail sets the Email field's value. func (s *UpdateUserInput) SetEmail(v string) *UpdateUserInput { s.Email = &v @@ -23046,6 +29886,12 @@ func (s *UpdateUserInput) SetRole(v string) *UpdateUserInput { return s } +// SetUnapplyCustomPermissions sets the UnapplyCustomPermissions field's value. +func (s *UpdateUserInput) SetUnapplyCustomPermissions(v bool) *UpdateUserInput { + s.UnapplyCustomPermissions = &v + return s +} + // SetUserName sets the UserName field's value. func (s *UpdateUserInput) SetUserName(v string) *UpdateUserInput { s.UserName = &v @@ -23182,6 +30028,9 @@ type User struct { // The Amazon Resource Name (ARN) for the user. Arn *string `type:"string"` + // The custom permissions profile associated with this user. + CustomPermissionsName *string `min:"1" type:"string"` + // The user's email address. Email *string `type:"string"` @@ -23233,6 +30082,12 @@ func (s *User) SetArn(v string) *User { return s } +// SetCustomPermissionsName sets the CustomPermissionsName field's value. +func (s *User) SetCustomPermissionsName(v string) *User { + s.CustomPermissionsName = &v + return s +} + // SetEmail sets the Email field's value. func (s *User) SetEmail(v string) *User { s.Email = &v @@ -23374,6 +30229,15 @@ const ( AssignmentStatusDisabled = "DISABLED" ) +// AssignmentStatus_Values returns all elements of the AssignmentStatus enum +func AssignmentStatus_Values() []string { + return []string{ + AssignmentStatusEnabled, + AssignmentStatusDraft, + AssignmentStatusDisabled, + } +} + const ( // ColumnDataTypeString is a ColumnDataType enum value ColumnDataTypeString = "STRING" @@ -23388,6 +30252,16 @@ const ( ColumnDataTypeDatetime = "DATETIME" ) +// ColumnDataType_Values returns all elements of the ColumnDataType enum +func ColumnDataType_Values() []string { + return []string{ + ColumnDataTypeString, + ColumnDataTypeInteger, + ColumnDataTypeDecimal, + ColumnDataTypeDatetime, + } +} + const ( // DashboardBehaviorEnabled is a DashboardBehavior enum value DashboardBehaviorEnabled = "ENABLED" @@ -23396,7 +30270,21 @@ const ( DashboardBehaviorDisabled = "DISABLED" ) +// DashboardBehavior_Values returns all elements of the DashboardBehavior enum +func DashboardBehavior_Values() []string { + return []string{ + DashboardBehaviorEnabled, + DashboardBehaviorDisabled, + } +} + const ( + // DashboardErrorTypeAccessDenied is a DashboardErrorType enum value + DashboardErrorTypeAccessDenied = "ACCESS_DENIED" + + // DashboardErrorTypeSourceNotFound is a DashboardErrorType enum value + DashboardErrorTypeSourceNotFound = "SOURCE_NOT_FOUND" + // DashboardErrorTypeDataSetNotFound is a DashboardErrorType enum value DashboardErrorTypeDataSetNotFound = "DATA_SET_NOT_FOUND" @@ -23422,11 +30310,34 @@ const ( DashboardErrorTypeColumnReplacementMissing = "COLUMN_REPLACEMENT_MISSING" ) +// DashboardErrorType_Values returns all elements of the DashboardErrorType enum +func DashboardErrorType_Values() []string { + return []string{ + DashboardErrorTypeAccessDenied, + DashboardErrorTypeSourceNotFound, + DashboardErrorTypeDataSetNotFound, + DashboardErrorTypeInternalFailure, + DashboardErrorTypeParameterValueIncompatible, + DashboardErrorTypeParameterTypeInvalid, + DashboardErrorTypeParameterNotFound, + DashboardErrorTypeColumnTypeMismatch, + DashboardErrorTypeColumnGeographicRoleMismatch, + DashboardErrorTypeColumnReplacementMissing, + } +} + const ( // DashboardFilterAttributeQuicksightUser is a DashboardFilterAttribute enum value DashboardFilterAttributeQuicksightUser = "QUICKSIGHT_USER" ) +// DashboardFilterAttribute_Values returns all elements of the DashboardFilterAttribute enum +func DashboardFilterAttribute_Values() []string { + return []string{ + DashboardFilterAttributeQuicksightUser, + } +} + const ( // DashboardUIStateExpanded is a DashboardUIState enum value DashboardUIStateExpanded = "EXPANDED" @@ -23435,6 +30346,14 @@ const ( DashboardUIStateCollapsed = "COLLAPSED" ) +// DashboardUIState_Values returns all elements of the DashboardUIState enum +func DashboardUIState_Values() []string { + return []string{ + DashboardUIStateExpanded, + DashboardUIStateCollapsed, + } +} + const ( // DataSetImportModeSpice is a DataSetImportMode enum value DataSetImportModeSpice = "SPICE" @@ -23443,7 +30362,21 @@ const ( DataSetImportModeDirectQuery = "DIRECT_QUERY" ) +// DataSetImportMode_Values returns all elements of the DataSetImportMode enum +func DataSetImportMode_Values() []string { + return []string{ + DataSetImportModeSpice, + DataSetImportModeDirectQuery, + } +} + const ( + // DataSourceErrorInfoTypeAccessDenied is a DataSourceErrorInfoType enum value + DataSourceErrorInfoTypeAccessDenied = "ACCESS_DENIED" + + // DataSourceErrorInfoTypeCopySourceNotFound is a DataSourceErrorInfoType enum value + DataSourceErrorInfoTypeCopySourceNotFound = "COPY_SOURCE_NOT_FOUND" + // DataSourceErrorInfoTypeTimeout is a DataSourceErrorInfoType enum value DataSourceErrorInfoTypeTimeout = "TIMEOUT" @@ -23463,6 +30396,20 @@ const ( DataSourceErrorInfoTypeUnknown = "UNKNOWN" ) +// DataSourceErrorInfoType_Values returns all elements of the DataSourceErrorInfoType enum +func DataSourceErrorInfoType_Values() []string { + return []string{ + DataSourceErrorInfoTypeAccessDenied, + DataSourceErrorInfoTypeCopySourceNotFound, + DataSourceErrorInfoTypeTimeout, + DataSourceErrorInfoTypeEngineVersionNotSupported, + DataSourceErrorInfoTypeUnknownHost, + DataSourceErrorInfoTypeGenericSqlFailure, + DataSourceErrorInfoTypeConflict, + DataSourceErrorInfoTypeUnknown, + } +} + const ( // DataSourceTypeAdobeAnalytics is a DataSourceType enum value DataSourceTypeAdobeAnalytics = "ADOBE_ANALYTICS" @@ -23528,6 +30475,49 @@ const ( DataSourceTypeTwitter = "TWITTER" ) +// DataSourceType_Values returns all elements of the DataSourceType enum +func DataSourceType_Values() []string { + return []string{ + DataSourceTypeAdobeAnalytics, + DataSourceTypeAmazonElasticsearch, + DataSourceTypeAthena, + DataSourceTypeAurora, + DataSourceTypeAuroraPostgresql, + DataSourceTypeAwsIotAnalytics, + DataSourceTypeGithub, + DataSourceTypeJira, + DataSourceTypeMariadb, + DataSourceTypeMysql, + DataSourceTypePostgresql, + DataSourceTypePresto, + DataSourceTypeRedshift, + DataSourceTypeS3, + DataSourceTypeSalesforce, + DataSourceTypeServicenow, + DataSourceTypeSnowflake, + DataSourceTypeSpark, + DataSourceTypeSqlserver, + DataSourceTypeTeradata, + DataSourceTypeTwitter, + } +} + +const ( + // EditionStandard is a Edition enum value + EditionStandard = "STANDARD" + + // EditionEnterprise is a Edition enum value + EditionEnterprise = "ENTERPRISE" +) + +// Edition_Values returns all elements of the Edition enum +func Edition_Values() []string { + return []string{ + EditionStandard, + EditionEnterprise, + } +} + const ( // ExceptionResourceTypeUser is a ExceptionResourceType enum value ExceptionResourceTypeUser = "USER" @@ -23557,6 +30547,21 @@ const ( ExceptionResourceTypeIngestion = "INGESTION" ) +// ExceptionResourceType_Values returns all elements of the ExceptionResourceType enum +func ExceptionResourceType_Values() []string { + return []string{ + ExceptionResourceTypeUser, + ExceptionResourceTypeGroup, + ExceptionResourceTypeNamespace, + ExceptionResourceTypeAccountSettings, + ExceptionResourceTypeIampolicyAssignment, + ExceptionResourceTypeDataSource, + ExceptionResourceTypeDataSet, + ExceptionResourceTypeVpcConnection, + ExceptionResourceTypeIngestion, + } +} + const ( // FileFormatCsv is a FileFormat enum value FileFormatCsv = "CSV" @@ -23577,16 +30582,42 @@ const ( FileFormatJson = "JSON" ) +// FileFormat_Values returns all elements of the FileFormat enum +func FileFormat_Values() []string { + return []string{ + FileFormatCsv, + FileFormatTsv, + FileFormatClf, + FileFormatElf, + FileFormatXlsx, + FileFormatJson, + } +} + const ( // FilterOperatorStringEquals is a FilterOperator enum value FilterOperatorStringEquals = "StringEquals" ) +// FilterOperator_Values returns all elements of the FilterOperator enum +func FilterOperator_Values() []string { + return []string{ + FilterOperatorStringEquals, + } +} + const ( // GeoSpatialCountryCodeUs is a GeoSpatialCountryCode enum value GeoSpatialCountryCodeUs = "US" ) +// GeoSpatialCountryCode_Values returns all elements of the GeoSpatialCountryCode enum +func GeoSpatialCountryCode_Values() []string { + return []string{ + GeoSpatialCountryCodeUs, + } +} + const ( // GeoSpatialDataRoleCountry is a GeoSpatialDataRole enum value GeoSpatialDataRoleCountry = "COUNTRY" @@ -23610,6 +30641,31 @@ const ( GeoSpatialDataRoleLatitude = "LATITUDE" ) +// GeoSpatialDataRole_Values returns all elements of the GeoSpatialDataRole enum +func GeoSpatialDataRole_Values() []string { + return []string{ + GeoSpatialDataRoleCountry, + GeoSpatialDataRoleState, + GeoSpatialDataRoleCounty, + GeoSpatialDataRoleCity, + GeoSpatialDataRolePostcode, + GeoSpatialDataRoleLongitude, + GeoSpatialDataRoleLatitude, + } +} + +const ( + // IdentityStoreQuicksight is a IdentityStore enum value + IdentityStoreQuicksight = "QUICKSIGHT" +) + +// IdentityStore_Values returns all elements of the IdentityStore enum +func IdentityStore_Values() []string { + return []string{ + IdentityStoreQuicksight, + } +} + const ( // IdentityTypeIam is a IdentityType enum value IdentityTypeIam = "IAM" @@ -23618,6 +30674,14 @@ const ( IdentityTypeQuicksight = "QUICKSIGHT" ) +// IdentityType_Values returns all elements of the IdentityType enum +func IdentityType_Values() []string { + return []string{ + IdentityTypeIam, + IdentityTypeQuicksight, + } +} + const ( // IngestionErrorTypeFailureToAssumeRole is a IngestionErrorType enum value IngestionErrorTypeFailureToAssumeRole = "FAILURE_TO_ASSUME_ROLE" @@ -23740,6 +30804,52 @@ const ( IngestionErrorTypeInternalServiceError = "INTERNAL_SERVICE_ERROR" ) +// IngestionErrorType_Values returns all elements of the IngestionErrorType enum +func IngestionErrorType_Values() []string { + return []string{ + IngestionErrorTypeFailureToAssumeRole, + IngestionErrorTypeIngestionSuperseded, + IngestionErrorTypeIngestionCanceled, + IngestionErrorTypeDataSetDeleted, + IngestionErrorTypeDataSetNotSpice, + IngestionErrorTypeS3UploadedFileDeleted, + IngestionErrorTypeS3ManifestError, + IngestionErrorTypeDataToleranceException, + IngestionErrorTypeSpiceTableNotFound, + IngestionErrorTypeDataSetSizeLimitExceeded, + IngestionErrorTypeRowSizeLimitExceeded, + IngestionErrorTypeAccountCapacityLimitExceeded, + IngestionErrorTypeCustomerError, + IngestionErrorTypeDataSourceNotFound, + IngestionErrorTypeIamRoleNotAvailable, + IngestionErrorTypeConnectionFailure, + IngestionErrorTypeSqlTableNotFound, + IngestionErrorTypePermissionDenied, + IngestionErrorTypeSslCertificateValidationFailure, + IngestionErrorTypeOauthTokenFailure, + IngestionErrorTypeSourceApiLimitExceededFailure, + IngestionErrorTypePasswordAuthenticationFailure, + IngestionErrorTypeSqlSchemaMismatchError, + IngestionErrorTypeInvalidDateFormat, + IngestionErrorTypeInvalidDataprepSyntax, + IngestionErrorTypeSourceResourceLimitExceeded, + IngestionErrorTypeSqlInvalidParameterValue, + IngestionErrorTypeQueryTimeout, + IngestionErrorTypeSqlNumericOverflow, + IngestionErrorTypeUnresolvableHost, + IngestionErrorTypeUnroutableHost, + IngestionErrorTypeSqlException, + IngestionErrorTypeS3FileInaccessible, + IngestionErrorTypeIotFileNotFound, + IngestionErrorTypeIotDataSetFileEmpty, + IngestionErrorTypeInvalidDataSourceConfig, + IngestionErrorTypeDataSourceAuthFailed, + IngestionErrorTypeDataSourceConnectionFailed, + IngestionErrorTypeFailureToProcessJsonFile, + IngestionErrorTypeInternalServiceError, + } +} + const ( // IngestionRequestSourceManual is a IngestionRequestSource enum value IngestionRequestSourceManual = "MANUAL" @@ -23748,6 +30858,14 @@ const ( IngestionRequestSourceScheduled = "SCHEDULED" ) +// IngestionRequestSource_Values returns all elements of the IngestionRequestSource enum +func IngestionRequestSource_Values() []string { + return []string{ + IngestionRequestSourceManual, + IngestionRequestSourceScheduled, + } +} + const ( // IngestionRequestTypeInitialIngestion is a IngestionRequestType enum value IngestionRequestTypeInitialIngestion = "INITIAL_INGESTION" @@ -23762,6 +30880,16 @@ const ( IngestionRequestTypeFullRefresh = "FULL_REFRESH" ) +// IngestionRequestType_Values returns all elements of the IngestionRequestType enum +func IngestionRequestType_Values() []string { + return []string{ + IngestionRequestTypeInitialIngestion, + IngestionRequestTypeEdit, + IngestionRequestTypeIncrementalRefresh, + IngestionRequestTypeFullRefresh, + } +} + const ( // IngestionStatusInitialized is a IngestionStatus enum value IngestionStatusInitialized = "INITIALIZED" @@ -23782,6 +30910,18 @@ const ( IngestionStatusCancelled = "CANCELLED" ) +// IngestionStatus_Values returns all elements of the IngestionStatus enum +func IngestionStatus_Values() []string { + return []string{ + IngestionStatusInitialized, + IngestionStatusQueued, + IngestionStatusRunning, + IngestionStatusFailed, + IngestionStatusCompleted, + IngestionStatusCancelled, + } +} + const ( // InputColumnDataTypeString is a InputColumnDataType enum value InputColumnDataTypeString = "STRING" @@ -23805,6 +30945,19 @@ const ( InputColumnDataTypeJson = "JSON" ) +// InputColumnDataType_Values returns all elements of the InputColumnDataType enum +func InputColumnDataType_Values() []string { + return []string{ + InputColumnDataTypeString, + InputColumnDataTypeInteger, + InputColumnDataTypeDecimal, + InputColumnDataTypeDatetime, + InputColumnDataTypeBit, + InputColumnDataTypeBoolean, + InputColumnDataTypeJson, + } +} + const ( // JoinTypeInner is a JoinType enum value JoinTypeInner = "INNER" @@ -23819,6 +30972,60 @@ const ( JoinTypeRight = "RIGHT" ) +// JoinType_Values returns all elements of the JoinType enum +func JoinType_Values() []string { + return []string{ + JoinTypeInner, + JoinTypeOuter, + JoinTypeLeft, + JoinTypeRight, + } +} + +const ( + // NamespaceErrorTypePermissionDenied is a NamespaceErrorType enum value + NamespaceErrorTypePermissionDenied = "PERMISSION_DENIED" + + // NamespaceErrorTypeInternalServiceError is a NamespaceErrorType enum value + NamespaceErrorTypeInternalServiceError = "INTERNAL_SERVICE_ERROR" +) + +// NamespaceErrorType_Values returns all elements of the NamespaceErrorType enum +func NamespaceErrorType_Values() []string { + return []string{ + NamespaceErrorTypePermissionDenied, + NamespaceErrorTypeInternalServiceError, + } +} + +const ( + // NamespaceStatusCreated is a NamespaceStatus enum value + NamespaceStatusCreated = "CREATED" + + // NamespaceStatusCreating is a NamespaceStatus enum value + NamespaceStatusCreating = "CREATING" + + // NamespaceStatusDeleting is a NamespaceStatus enum value + NamespaceStatusDeleting = "DELETING" + + // NamespaceStatusRetryableFailure is a NamespaceStatus enum value + NamespaceStatusRetryableFailure = "RETRYABLE_FAILURE" + + // NamespaceStatusNonRetryableFailure is a NamespaceStatus enum value + NamespaceStatusNonRetryableFailure = "NON_RETRYABLE_FAILURE" +) + +// NamespaceStatus_Values returns all elements of the NamespaceStatus enum +func NamespaceStatus_Values() []string { + return []string{ + NamespaceStatusCreated, + NamespaceStatusCreating, + NamespaceStatusDeleting, + NamespaceStatusRetryableFailure, + NamespaceStatusNonRetryableFailure, + } +} + const ( // ResourceStatusCreationInProgress is a ResourceStatus enum value ResourceStatusCreationInProgress = "CREATION_IN_PROGRESS" @@ -23839,6 +31046,18 @@ const ( ResourceStatusUpdateFailed = "UPDATE_FAILED" ) +// ResourceStatus_Values returns all elements of the ResourceStatus enum +func ResourceStatus_Values() []string { + return []string{ + ResourceStatusCreationInProgress, + ResourceStatusCreationSuccessful, + ResourceStatusCreationFailed, + ResourceStatusUpdateInProgress, + ResourceStatusUpdateSuccessful, + ResourceStatusUpdateFailed, + } +} + const ( // RowLevelPermissionPolicyGrantAccess is a RowLevelPermissionPolicy enum value RowLevelPermissionPolicyGrantAccess = "GRANT_ACCESS" @@ -23847,7 +31066,18 @@ const ( RowLevelPermissionPolicyDenyAccess = "DENY_ACCESS" ) +// RowLevelPermissionPolicy_Values returns all elements of the RowLevelPermissionPolicy enum +func RowLevelPermissionPolicy_Values() []string { + return []string{ + RowLevelPermissionPolicyGrantAccess, + RowLevelPermissionPolicyDenyAccess, + } +} + const ( + // TemplateErrorTypeSourceNotFound is a TemplateErrorType enum value + TemplateErrorTypeSourceNotFound = "SOURCE_NOT_FOUND" + // TemplateErrorTypeDataSetNotFound is a TemplateErrorType enum value TemplateErrorTypeDataSetNotFound = "DATA_SET_NOT_FOUND" @@ -23855,6 +31085,15 @@ const ( TemplateErrorTypeInternalFailure = "INTERNAL_FAILURE" ) +// TemplateErrorType_Values returns all elements of the TemplateErrorType enum +func TemplateErrorType_Values() []string { + return []string{ + TemplateErrorTypeSourceNotFound, + TemplateErrorTypeDataSetNotFound, + TemplateErrorTypeInternalFailure, + } +} + const ( // TextQualifierDoubleQuote is a TextQualifier enum value TextQualifierDoubleQuote = "DOUBLE_QUOTE" @@ -23863,6 +31102,46 @@ const ( TextQualifierSingleQuote = "SINGLE_QUOTE" ) +// TextQualifier_Values returns all elements of the TextQualifier enum +func TextQualifier_Values() []string { + return []string{ + TextQualifierDoubleQuote, + TextQualifierSingleQuote, + } +} + +const ( + // ThemeErrorTypeInternalFailure is a ThemeErrorType enum value + ThemeErrorTypeInternalFailure = "INTERNAL_FAILURE" +) + +// ThemeErrorType_Values returns all elements of the ThemeErrorType enum +func ThemeErrorType_Values() []string { + return []string{ + ThemeErrorTypeInternalFailure, + } +} + +const ( + // ThemeTypeQuicksight is a ThemeType enum value + ThemeTypeQuicksight = "QUICKSIGHT" + + // ThemeTypeCustom is a ThemeType enum value + ThemeTypeCustom = "CUSTOM" + + // ThemeTypeAll is a ThemeType enum value + ThemeTypeAll = "ALL" +) + +// ThemeType_Values returns all elements of the ThemeType enum +func ThemeType_Values() []string { + return []string{ + ThemeTypeQuicksight, + ThemeTypeCustom, + ThemeTypeAll, + } +} + const ( // UserRoleAdmin is a UserRole enum value UserRoleAdmin = "ADMIN" @@ -23879,3 +31158,14 @@ const ( // UserRoleRestrictedReader is a UserRole enum value UserRoleRestrictedReader = "RESTRICTED_READER" ) + +// UserRole_Values returns all elements of the UserRole enum +func UserRole_Values() []string { + return []string{ + UserRoleAdmin, + UserRoleAuthor, + UserRoleReader, + UserRoleRestrictedAuthor, + UserRoleRestrictedReader, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ram/api.go b/vendor/github.com/aws/aws-sdk-go/service/ram/api.go index 88d61c3784a..9edc288d208 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ram/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ram/api.go @@ -6982,6 +6982,14 @@ const ( ResourceOwnerOtherAccounts = "OTHER-ACCOUNTS" ) +// ResourceOwner_Values returns all elements of the ResourceOwner enum +func ResourceOwner_Values() []string { + return []string{ + ResourceOwnerSelf, + ResourceOwnerOtherAccounts, + } +} + const ( // ResourceShareAssociationStatusAssociating is a ResourceShareAssociationStatus enum value ResourceShareAssociationStatusAssociating = "ASSOCIATING" @@ -6999,6 +7007,17 @@ const ( ResourceShareAssociationStatusDisassociated = "DISASSOCIATED" ) +// ResourceShareAssociationStatus_Values returns all elements of the ResourceShareAssociationStatus enum +func ResourceShareAssociationStatus_Values() []string { + return []string{ + ResourceShareAssociationStatusAssociating, + ResourceShareAssociationStatusAssociated, + ResourceShareAssociationStatusFailed, + ResourceShareAssociationStatusDisassociating, + ResourceShareAssociationStatusDisassociated, + } +} + const ( // ResourceShareAssociationTypePrincipal is a ResourceShareAssociationType enum value ResourceShareAssociationTypePrincipal = "PRINCIPAL" @@ -7007,6 +7026,14 @@ const ( ResourceShareAssociationTypeResource = "RESOURCE" ) +// ResourceShareAssociationType_Values returns all elements of the ResourceShareAssociationType enum +func ResourceShareAssociationType_Values() []string { + return []string{ + ResourceShareAssociationTypePrincipal, + ResourceShareAssociationTypeResource, + } +} + const ( // ResourceShareFeatureSetCreatedFromPolicy is a ResourceShareFeatureSet enum value ResourceShareFeatureSetCreatedFromPolicy = "CREATED_FROM_POLICY" @@ -7018,6 +7045,15 @@ const ( ResourceShareFeatureSetStandard = "STANDARD" ) +// ResourceShareFeatureSet_Values returns all elements of the ResourceShareFeatureSet enum +func ResourceShareFeatureSet_Values() []string { + return []string{ + ResourceShareFeatureSetCreatedFromPolicy, + ResourceShareFeatureSetPromotingToStandard, + ResourceShareFeatureSetStandard, + } +} + const ( // ResourceShareInvitationStatusPending is a ResourceShareInvitationStatus enum value ResourceShareInvitationStatusPending = "PENDING" @@ -7032,6 +7068,16 @@ const ( ResourceShareInvitationStatusExpired = "EXPIRED" ) +// ResourceShareInvitationStatus_Values returns all elements of the ResourceShareInvitationStatus enum +func ResourceShareInvitationStatus_Values() []string { + return []string{ + ResourceShareInvitationStatusPending, + ResourceShareInvitationStatusAccepted, + ResourceShareInvitationStatusRejected, + ResourceShareInvitationStatusExpired, + } +} + const ( // ResourceShareStatusPending is a ResourceShareStatus enum value ResourceShareStatusPending = "PENDING" @@ -7049,6 +7095,17 @@ const ( ResourceShareStatusDeleted = "DELETED" ) +// ResourceShareStatus_Values returns all elements of the ResourceShareStatus enum +func ResourceShareStatus_Values() []string { + return []string{ + ResourceShareStatusPending, + ResourceShareStatusActive, + ResourceShareStatusFailed, + ResourceShareStatusDeleting, + ResourceShareStatusDeleted, + } +} + const ( // ResourceStatusAvailable is a ResourceStatus enum value ResourceStatusAvailable = "AVAILABLE" @@ -7065,3 +7122,14 @@ const ( // ResourceStatusPending is a ResourceStatus enum value ResourceStatusPending = "PENDING" ) + +// ResourceStatus_Values returns all elements of the ResourceStatus enum +func ResourceStatus_Values() []string { + return []string{ + ResourceStatusAvailable, + ResourceStatusZonalResourceInaccessible, + ResourceStatusLimitExceeded, + ResourceStatusUnavailable, + ResourceStatusPending, + } +} 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 2866909945c..538f9eebeed 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 @@ -620,7 +620,7 @@ func (c *RDS) BacktrackDBClusterRequest(input *BacktrackDBClusterInput) (req *re // (https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Managing.Backtrack.html) // in the Amazon Aurora User Guide. // -// This action only applies to Aurora DB clusters. +// This action only applies to Aurora MySQL DB clusters. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2236,10 +2236,6 @@ func (c *RDS) CreateDBProxyRequest(input *CreateDBProxyInput) (req *request.Requ // CreateDBProxy API operation for Amazon Relational Database Service. // -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Creates a new DB proxy. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -2608,11 +2604,12 @@ func (c *RDS) CreateEventSubscriptionRequest(input *CreateEventSubscriptionInput // or the SNS API. To obtain an ARN with SNS, you must create a topic in Amazon // SNS and subscribe to the topic. The ARN is displayed in the SNS console. // -// You can specify the type of source (SourceType) you want to be notified of, -// provide a list of RDS sources (SourceIds) that triggers the events, and provide -// a list of event categories (EventCategories) for events you want to be notified -// of. For example, you can specify SourceType = db-instance, SourceIds = mydbinstance1, -// mydbinstance2 and EventCategories = Availability, Backup. +// You can specify the type of source (SourceType) that you want to be notified +// of and provide a list of RDS sources (SourceIds) that triggers the events. +// You can also provide a list of event categories (EventCategories) for events +// that you want to be notified of. For example, you can specify SourceType +// = db-instance, SourceIds = mydbinstance1, mydbinstance2 and EventCategories +// = Availability, Backup. // // If you specify both the SourceType and SourceIds, such as SourceType = db-instance // and SourceIdentifier = myDBInstance1, you are notified of all the db-instance @@ -2720,7 +2717,6 @@ func (c *RDS) CreateGlobalClusterRequest(input *CreateGlobalClusterInput) (req * // CreateGlobalCluster API operation for Amazon Relational Database Service. // -// // Creates an Aurora global database spread across multiple regions. The global // database contains a single primary cluster with read-write capability, and // a read-only secondary cluster that receives data from the primary cluster @@ -3646,10 +3642,6 @@ func (c *RDS) DeleteDBProxyRequest(input *DeleteDBProxyInput) (req *request.Requ // DeleteDBProxy API operation for Amazon Relational Database Service. // -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Deletes an existing proxy. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -4321,10 +4313,6 @@ func (c *RDS) DeregisterDBProxyTargetsRequest(input *DeregisterDBProxyTargetsInp // DeregisterDBProxyTargets API operation for Amazon Relational Database Service. // -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Remove the association between one or more DBProxyTarget data structures // and a DBProxyTargetGroup. // @@ -4483,6 +4471,12 @@ func (c *RDS) DescribeCertificatesRequest(input *DescribeCertificatesInput) (req Name: opDescribeCertificates, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, } if input == nil { @@ -4531,6 +4525,58 @@ func (c *RDS) DescribeCertificatesWithContext(ctx aws.Context, input *DescribeCe return out, req.Send() } +// DescribeCertificatesPages iterates over the pages of a DescribeCertificates operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeCertificates 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 DescribeCertificates operation. +// pageNum := 0 +// err := client.DescribeCertificatesPages(params, +// func(page *rds.DescribeCertificatesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *RDS) DescribeCertificatesPages(input *DescribeCertificatesInput, fn func(*DescribeCertificatesOutput, bool) bool) error { + return c.DescribeCertificatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCertificatesPagesWithContext same as DescribeCertificatesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeCertificatesPagesWithContext(ctx aws.Context, input *DescribeCertificatesInput, fn func(*DescribeCertificatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCertificatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCertificatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeCertificatesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeCustomAvailabilityZones = "DescribeCustomAvailabilityZones" // DescribeCustomAvailabilityZonesRequest generates a "aws/request.Request" representing the @@ -4706,6 +4752,12 @@ func (c *RDS) DescribeDBClusterBacktracksRequest(input *DescribeDBClusterBacktra Name: opDescribeDBClusterBacktracks, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, } if input == nil { @@ -4724,7 +4776,7 @@ func (c *RDS) DescribeDBClusterBacktracksRequest(input *DescribeDBClusterBacktra // For more information on Amazon Aurora, see What Is Amazon Aurora? (https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_AuroraOverview.html) // in the Amazon Aurora User Guide. // -// This action only applies to Aurora DB clusters. +// This action only applies to Aurora MySQL DB clusters. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4762,6 +4814,58 @@ func (c *RDS) DescribeDBClusterBacktracksWithContext(ctx aws.Context, input *Des return out, req.Send() } +// DescribeDBClusterBacktracksPages iterates over the pages of a DescribeDBClusterBacktracks operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeDBClusterBacktracks 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 DescribeDBClusterBacktracks operation. +// pageNum := 0 +// err := client.DescribeDBClusterBacktracksPages(params, +// func(page *rds.DescribeDBClusterBacktracksOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *RDS) DescribeDBClusterBacktracksPages(input *DescribeDBClusterBacktracksInput, fn func(*DescribeDBClusterBacktracksOutput, bool) bool) error { + return c.DescribeDBClusterBacktracksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBClusterBacktracksPagesWithContext same as DescribeDBClusterBacktracksPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeDBClusterBacktracksPagesWithContext(ctx aws.Context, input *DescribeDBClusterBacktracksInput, fn func(*DescribeDBClusterBacktracksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBClusterBacktracksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBClusterBacktracksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeDBClusterBacktracksOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeDBClusterEndpoints = "DescribeDBClusterEndpoints" // DescribeDBClusterEndpointsRequest generates a "aws/request.Request" representing the @@ -4793,6 +4897,12 @@ func (c *RDS) DescribeDBClusterEndpointsRequest(input *DescribeDBClusterEndpoint Name: opDescribeDBClusterEndpoints, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, } if input == nil { @@ -4843,6 +4953,58 @@ func (c *RDS) DescribeDBClusterEndpointsWithContext(ctx aws.Context, input *Desc return out, req.Send() } +// DescribeDBClusterEndpointsPages iterates over the pages of a DescribeDBClusterEndpoints operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeDBClusterEndpoints 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 DescribeDBClusterEndpoints operation. +// pageNum := 0 +// err := client.DescribeDBClusterEndpointsPages(params, +// func(page *rds.DescribeDBClusterEndpointsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *RDS) DescribeDBClusterEndpointsPages(input *DescribeDBClusterEndpointsInput, fn func(*DescribeDBClusterEndpointsOutput, bool) bool) error { + return c.DescribeDBClusterEndpointsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBClusterEndpointsPagesWithContext same as DescribeDBClusterEndpointsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeDBClusterEndpointsPagesWithContext(ctx aws.Context, input *DescribeDBClusterEndpointsInput, fn func(*DescribeDBClusterEndpointsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBClusterEndpointsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBClusterEndpointsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeDBClusterEndpointsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeDBClusterParameterGroups = "DescribeDBClusterParameterGroups" // DescribeDBClusterParameterGroupsRequest generates a "aws/request.Request" representing the @@ -4874,6 +5036,12 @@ func (c *RDS) DescribeDBClusterParameterGroupsRequest(input *DescribeDBClusterPa Name: opDescribeDBClusterParameterGroups, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, } if input == nil { @@ -4929,6 +5097,58 @@ func (c *RDS) DescribeDBClusterParameterGroupsWithContext(ctx aws.Context, input return out, req.Send() } +// DescribeDBClusterParameterGroupsPages iterates over the pages of a DescribeDBClusterParameterGroups operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeDBClusterParameterGroups 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 DescribeDBClusterParameterGroups operation. +// pageNum := 0 +// err := client.DescribeDBClusterParameterGroupsPages(params, +// func(page *rds.DescribeDBClusterParameterGroupsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *RDS) DescribeDBClusterParameterGroupsPages(input *DescribeDBClusterParameterGroupsInput, fn func(*DescribeDBClusterParameterGroupsOutput, bool) bool) error { + return c.DescribeDBClusterParameterGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBClusterParameterGroupsPagesWithContext same as DescribeDBClusterParameterGroupsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeDBClusterParameterGroupsPagesWithContext(ctx aws.Context, input *DescribeDBClusterParameterGroupsInput, fn func(*DescribeDBClusterParameterGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBClusterParameterGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBClusterParameterGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeDBClusterParameterGroupsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeDBClusterParameters = "DescribeDBClusterParameters" // DescribeDBClusterParametersRequest generates a "aws/request.Request" representing the @@ -4960,6 +5180,12 @@ func (c *RDS) DescribeDBClusterParametersRequest(input *DescribeDBClusterParamet Name: opDescribeDBClusterParameters, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, } if input == nil { @@ -5014,6 +5240,58 @@ func (c *RDS) DescribeDBClusterParametersWithContext(ctx aws.Context, input *Des return out, req.Send() } +// DescribeDBClusterParametersPages iterates over the pages of a DescribeDBClusterParameters operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeDBClusterParameters 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 DescribeDBClusterParameters operation. +// pageNum := 0 +// err := client.DescribeDBClusterParametersPages(params, +// func(page *rds.DescribeDBClusterParametersOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *RDS) DescribeDBClusterParametersPages(input *DescribeDBClusterParametersInput, fn func(*DescribeDBClusterParametersOutput, bool) bool) error { + return c.DescribeDBClusterParametersPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBClusterParametersPagesWithContext same as DescribeDBClusterParametersPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeDBClusterParametersPagesWithContext(ctx aws.Context, input *DescribeDBClusterParametersInput, fn func(*DescribeDBClusterParametersOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBClusterParametersInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBClusterParametersRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeDBClusterParametersOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeDBClusterSnapshotAttributes = "DescribeDBClusterSnapshotAttributes" // DescribeDBClusterSnapshotAttributesRequest generates a "aws/request.Request" representing the @@ -5137,6 +5415,12 @@ func (c *RDS) DescribeDBClusterSnapshotsRequest(input *DescribeDBClusterSnapshot Name: opDescribeDBClusterSnapshots, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, } if input == nil { @@ -5191,6 +5475,58 @@ func (c *RDS) DescribeDBClusterSnapshotsWithContext(ctx aws.Context, input *Desc return out, req.Send() } +// DescribeDBClusterSnapshotsPages iterates over the pages of a DescribeDBClusterSnapshots operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeDBClusterSnapshots 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 DescribeDBClusterSnapshots operation. +// pageNum := 0 +// err := client.DescribeDBClusterSnapshotsPages(params, +// func(page *rds.DescribeDBClusterSnapshotsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *RDS) DescribeDBClusterSnapshotsPages(input *DescribeDBClusterSnapshotsInput, fn func(*DescribeDBClusterSnapshotsOutput, bool) bool) error { + return c.DescribeDBClusterSnapshotsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeDBClusterSnapshotsPagesWithContext same as DescribeDBClusterSnapshotsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeDBClusterSnapshotsPagesWithContext(ctx aws.Context, input *DescribeDBClusterSnapshotsInput, fn func(*DescribeDBClusterSnapshotsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeDBClusterSnapshotsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeDBClusterSnapshotsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeDBClusterSnapshotsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeDBClusters = "DescribeDBClusters" // DescribeDBClustersRequest generates a "aws/request.Request" representing the @@ -6213,10 +6549,6 @@ func (c *RDS) DescribeDBProxiesRequest(input *DescribeDBProxiesInput) (req *requ // DescribeDBProxies API operation for Amazon Relational Database Service. // -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Returns information about DB proxies. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -6355,10 +6687,6 @@ func (c *RDS) DescribeDBProxyTargetGroupsRequest(input *DescribeDBProxyTargetGro // DescribeDBProxyTargetGroups API operation for Amazon Relational Database Service. // -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Returns information about DB proxy target groups, represented by DBProxyTargetGroup // data structures. // @@ -6505,10 +6833,6 @@ func (c *RDS) DescribeDBProxyTargetsRequest(input *DescribeDBProxyTargetsInput) // DescribeDBProxyTargets API operation for Amazon Relational Database Service. // -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Returns information about DBProxyTarget objects. This API supports pagination. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -7371,8 +7695,8 @@ func (c *RDS) DescribeEventCategoriesRequest(input *DescribeEventCategoriesInput // // Displays a list of categories for all event source types, or, if specified, // for a specified source type. You can see a list of the event categories and -// source types in the Events (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.html) -// topic in the Amazon RDS User Guide. +// source types in Events (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.html) +// in the Amazon RDS 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 @@ -7593,9 +7917,10 @@ func (c *RDS) DescribeEventsRequest(input *DescribeEventsInput) (req *request.Re // DescribeEvents API operation for Amazon Relational Database Service. // -// Returns events related to DB instances, DB security groups, DB snapshots, -// and DB parameter groups for the past 14 days. Events specific to a particular -// DB instance, DB security group, database snapshot, or DB parameter group +// Returns events related to DB instances, DB clusters, DB parameter groups, +// DB security groups, DB snapshots, and DB cluster snapshots for the past 14 +// days. Events specific to a particular DB instances, DB clusters, DB parameter +// groups, DB security groups, DB snapshots, and DB cluster snapshots group // can be obtained by providing the name as a parameter. By default, the past // hour of events are returned. // @@ -8529,6 +8854,12 @@ func (c *RDS) DescribePendingMaintenanceActionsRequest(input *DescribePendingMai Name: opDescribePendingMaintenanceActions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, } if input == nil { @@ -8578,6 +8909,58 @@ func (c *RDS) DescribePendingMaintenanceActionsWithContext(ctx aws.Context, inpu return out, req.Send() } +// DescribePendingMaintenanceActionsPages iterates over the pages of a DescribePendingMaintenanceActions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribePendingMaintenanceActions 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 DescribePendingMaintenanceActions operation. +// pageNum := 0 +// err := client.DescribePendingMaintenanceActionsPages(params, +// func(page *rds.DescribePendingMaintenanceActionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *RDS) DescribePendingMaintenanceActionsPages(input *DescribePendingMaintenanceActionsInput, fn func(*DescribePendingMaintenanceActionsOutput, bool) bool) error { + return c.DescribePendingMaintenanceActionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribePendingMaintenanceActionsPagesWithContext same as DescribePendingMaintenanceActionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribePendingMaintenanceActionsPagesWithContext(ctx aws.Context, input *DescribePendingMaintenanceActionsInput, fn func(*DescribePendingMaintenanceActionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribePendingMaintenanceActionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribePendingMaintenanceActionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribePendingMaintenanceActionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeReservedDBInstances = "DescribeReservedDBInstances" // DescribeReservedDBInstancesRequest generates a "aws/request.Request" representing the @@ -8884,6 +9267,12 @@ func (c *RDS) DescribeSourceRegionsRequest(input *DescribeSourceRegionsInput) (r Name: opDescribeSourceRegions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"Marker"}, + LimitToken: "MaxRecords", + TruncationToken: "", + }, } if input == nil { @@ -8929,6 +9318,58 @@ func (c *RDS) DescribeSourceRegionsWithContext(ctx aws.Context, input *DescribeS return out, req.Send() } +// DescribeSourceRegionsPages iterates over the pages of a DescribeSourceRegions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeSourceRegions 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 DescribeSourceRegions operation. +// pageNum := 0 +// err := client.DescribeSourceRegionsPages(params, +// func(page *rds.DescribeSourceRegionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *RDS) DescribeSourceRegionsPages(input *DescribeSourceRegionsInput, fn func(*DescribeSourceRegionsOutput, bool) bool) error { + return c.DescribeSourceRegionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeSourceRegionsPagesWithContext same as DescribeSourceRegionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) DescribeSourceRegionsPagesWithContext(ctx aws.Context, input *DescribeSourceRegionsInput, fn func(*DescribeSourceRegionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeSourceRegionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeSourceRegionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeSourceRegionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeValidDBInstanceModifications = "DescribeValidDBInstanceModifications" // DescribeValidDBInstanceModificationsRequest generates a "aws/request.Request" representing the @@ -10025,16 +10466,19 @@ func (c *RDS) ModifyDBClusterSnapshotAttributeRequest(input *ModifyDBClusterSnap // as the AttributeName and use the ValuesToAdd parameter to add a list of IDs // of the AWS accounts that are authorized to restore the manual DB cluster // 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. 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. +// which means that it can be copied or restored by all AWS accounts. +// +// Don't add the all value for any manual DB cluster snapshots that contain +// private 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. +// snapshot, or whether a manual DB cluster snapshot is public or private, use +// the DescribeDBClusterSnapshotAttributes API action. The accounts are returned +// as values for the restore attribute. // // This action only applies to Aurora DB clusters. // @@ -10192,6 +10636,12 @@ func (c *RDS) ModifyDBInstanceRequest(input *ModifyDBInstanceInput) (req *reques // // * ErrCodeBackupPolicyNotFoundFault "BackupPolicyNotFoundFault" // +// * ErrCodeKMSKeyNotAccessibleFault "KMSKeyNotAccessibleFault" +// An error occurred accessing an AWS KMS key. +// +// * ErrCodeInvalidDBClusterStateFault "InvalidDBClusterStateFault" +// The requested operation can't be performed while the cluster is in this state. +// // See also, 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) @@ -10359,10 +10809,6 @@ func (c *RDS) ModifyDBProxyRequest(input *ModifyDBProxyInput) (req *request.Requ // ModifyDBProxy API operation for Amazon Relational Database Service. // -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Changes the settings for an existing DB proxy. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -10450,10 +10896,6 @@ func (c *RDS) ModifyDBProxyTargetGroupRequest(input *ModifyDBProxyTargetGroupInp // ModifyDBProxyTargetGroup API operation for Amazon Relational Database Service. // -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Modifies the properties of a DBProxyTargetGroup. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -10630,16 +11072,18 @@ func (c *RDS) ModifyDBSnapshotAttributeRequest(input *ModifyDBSnapshotAttributeI // the AttributeName and use the ValuesToAdd parameter to add a list of IDs // of the AWS accounts that are authorized to restore the manual DB snapshot. // 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. 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. +// can be copied or restored by all AWS accounts. +// +// Don't add the all value for any manual DB snapshots that contain private +// information that you don't want 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. +// API action. The accounts are returned as values for the restore attribute. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -10825,10 +11269,9 @@ func (c *RDS) ModifyEventSubscriptionRequest(input *ModifyEventSubscriptionInput // a subscription, use the AddSourceIdentifierToSubscription and RemoveSourceIdentifierFromSubscription // calls. // -// You can see a list of the event categories for a given SourceType in the -// Events (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.html) -// topic in the Amazon RDS User Guide or by using the DescribeEventCategories -// action. +// You can see a list of the event categories for a given source type (SourceType) +// in Events (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.html) +// in the Amazon RDS User Guide or by using the DescribeEventCategories 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 @@ -11444,10 +11887,6 @@ func (c *RDS) RegisterDBProxyTargetsRequest(input *RegisterDBProxyTargetsInput) // RegisterDBProxyTargets API operation for Amazon Relational Database Service. // -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Associate one or more DBProxyTarget data structures with a DBProxyTargetGroup. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -12187,10 +12626,10 @@ func (c *RDS) RestoreDBClusterFromS3Request(input *RestoreDBClusterFromS3Input) // RestoreDBClusterFromS3 API operation for Amazon Relational Database Service. // -// 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 to an Amazon Aurora MySQL DB Cluster (https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Migrating.html) +// Creates an Amazon Aurora DB cluster from MySQL 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 (https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Migrating.ExtMySQL.html#AuroraMySQL.Migrating.ExtMySQL.S3) // in the Amazon Aurora User Guide. // // This action only restores the DB cluster, not the DB instances for that DB @@ -12202,7 +12641,8 @@ func (c *RDS) RestoreDBClusterFromS3Request(input *RestoreDBClusterFromS3Input) // For more information on Amazon Aurora, see What Is Amazon Aurora? (https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_AuroraOverview.html) // in the Amazon Aurora User Guide. // -// This action only applies to Aurora DB clusters. +// This action only applies to Aurora DB clusters. The source DB engine must +// be MySQL. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -13921,8 +14361,13 @@ func (c *RDS) StopDBInstanceWithContext(ctx aws.Context, input *StopDBInstanceIn // * EventSubscriptions - The number of event subscriptions per account. // The used value is the count of the event subscriptions in the account. // -// * ManualSnapshots - The number of manual DB snapshots per account. The -// used value is the count of the manual DB snapshots in the account. +// * ManualClusterSnapshots - The number of manual DB cluster snapshots per +// account. The used value is the count of the manual DB cluster snapshots +// in the account. +// +// * ManualSnapshots - The number of manual DB instance snapshots per account. +// The used value is the count of the manual DB instance snapshots in the +// account. // // * OptionGroups - The number of DB option groups per account, excluding // default option groups. The used value is the count of nondefault DB option @@ -14152,17 +14597,23 @@ type AddSourceIdentifierToSubscriptionInput struct { // // Constraints: // - // * If the source type is a DB instance, then a DBInstanceIdentifier must + // * If the source type is a DB instance, a DBInstanceIdentifier value must // be supplied. // - // * If the source type is a DB security group, a DBSecurityGroupName must + // * If the source type is a DB cluster, a DBClusterIdentifier value must // be supplied. // - // * If the source type is a DB parameter group, a DBParameterGroupName must + // * If the source type is a DB parameter group, a DBParameterGroupName value + // must be supplied. + // + // * If the source type is a DB security group, a DBSecurityGroupName value + // must be supplied. + // + // * If the source type is a DB snapshot, a DBSnapshotIdentifier value must // be supplied. // - // * If the source type is a DB snapshot, a DBSnapshotIdentifier must be - // supplied. + // * If the source type is a DB cluster snapshot, a DBClusterSnapshotIdentifier + // value must be supplied. // // SourceIdentifier is a required field SourceIdentifier *string `type:"string" required:"true"` @@ -15141,10 +15592,6 @@ func (s *CloudwatchLogsExportConfiguration) SetEnableLogTypes(v []*string) *Clou return s } -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Specifies the settings that control the size and behavior of the connection // pool associated with a DBProxyTargetGroup. type ConnectionPoolConfiguration struct { @@ -15165,8 +15612,6 @@ type ConnectionPoolConfiguration struct { // statements, use semicolons as the separator. You can also include multiple // variables in a single SET statement, such as SET x=1, y=2. // - // InitQuery is not currently supported for PostgreSQL. - // // Default: no initialization query InitQuery *string `type:"string"` @@ -15240,10 +15685,6 @@ func (s *ConnectionPoolConfiguration) SetSessionPinningFilters(v []*string) *Con return s } -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Displays the settings that control the size and behavior of the connection // pool associated with a DBProxyTarget. type ConnectionPoolConfigurationInfo struct { @@ -15260,8 +15701,6 @@ type ConnectionPoolConfigurationInfo struct { // is empty by default. For multiple statements, use semicolons as the separator. // You can also include multiple variables in a single SET statement, such as // SET x=1, y=2. - // - // InitQuery is not currently supported for PostgreSQL. InitQuery *string `type:"string"` // The maximum size of the connection pool for each target in a target group. @@ -16404,7 +16843,9 @@ type CreateDBClusterEndpointOutput struct { StaticMembers []*string `type:"list"` // The current status of the endpoint. One of: creating, available, deleting, - // modifying. + // inactive, modifying. The inactive state applies to an endpoint that can't + // be used for a certain kind of cluster, such as a writer endpoint for a read-only + // secondary cluster in a global database. Status *string `type:"string"` } @@ -16490,6 +16931,8 @@ type CreateDBClusterInput struct { // The target backtrack window, in seconds. To disable backtracking, set this // value to 0. // + // Currently, Backtrack is only supported for Aurora MySQL DB clusters. + // // Default: 0 // // Constraints: @@ -16579,6 +17022,13 @@ type CreateDBClusterInput struct { // in the Amazon Aurora User Guide. EnableCloudwatchLogsExports []*string `type:"list"` + // A value that indicates whether to enable write operations to be forwarded + // from this cluster to the primary cluster in an Aurora global database. The + // resulting changes are replicated back to this cluster. This parameter only + // applies to DB clusters that are secondary clusters in an Aurora global database. + // By default, Aurora disallows write operations for secondary clusters. + EnableGlobalWriteForwarding *bool `type:"boolean"` + // A value that indicates whether to enable the HTTP endpoint for an Aurora // Serverless DB cluster. By default, the HTTP endpoint is disabled. // @@ -16911,6 +17361,12 @@ func (s *CreateDBClusterInput) SetEnableCloudwatchLogsExports(v []*string) *Crea return s } +// SetEnableGlobalWriteForwarding sets the EnableGlobalWriteForwarding field's value. +func (s *CreateDBClusterInput) SetEnableGlobalWriteForwarding(v bool) *CreateDBClusterInput { + s.EnableGlobalWriteForwarding = &v + return s +} + // SetEnableHttpEndpoint sets the EnableHttpEndpoint field's value. func (s *CreateDBClusterInput) SetEnableHttpEndpoint(v bool) *CreateDBClusterInput { s.EnableHttpEndpoint = &v @@ -17451,6 +17907,9 @@ type CreateDBInstanceInput struct { // // * Must contain 1 to 64 letters or numbers. // + // * Must begin with a letter. Subsequent characters can be letters, underscores, + // or digits (0-9). + // // * Can't be a word reserved by the specified database engine // // MariaDB @@ -17462,6 +17921,9 @@ type CreateDBInstanceInput struct { // // * Must contain 1 to 64 letters or numbers. // + // * Must begin with a letter. Subsequent characters can be letters, underscores, + // or digits (0-9). + // // * Can't be a word reserved by the specified database engine // // PostgreSQL @@ -17474,8 +17936,8 @@ type CreateDBInstanceInput struct { // // * Must contain 1 to 63 letters, numbers, or underscores. // - // * Must begin with a letter or an underscore. Subsequent characters can - // be letters, underscores, or digits (0-9). + // * Must begin with a letter. Subsequent characters can be letters, underscores, + // or digits (0-9). // // * Can't be a word reserved by the specified database engine // @@ -17545,18 +18007,10 @@ type CreateDBInstanceInput struct { DeletionProtection *bool `type:"boolean"` // The Active Directory directory ID to create the DB instance in. Currently, - // only Microsoft SQL Server and Oracle DB instances can be created in an Active - // Directory Domain. + // only MySQL, Microsoft SQL Server, Oracle, and PostgreSQL DB instances can + // be created in an Active Directory Domain. // - // For Microsoft SQL Server DB instances, Amazon RDS can use Windows Authentication - // to authenticate users that connect to the DB instance. For more information, - // see Using Windows Authentication with an Amazon RDS DB Instance Running Microsoft - // SQL Server (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_SQLServerWinAuth.html) - // in the Amazon RDS User Guide. - // - // For Oracle DB instances, Amazon RDS can use Kerberos Authentication to authenticate - // users that connect to the DB instance. For more information, see Using Kerberos - // Authentication with Amazon RDS for Oracle (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-kerberos.html) + // For more information, see Kerberos Authentication (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html) // in the Amazon RDS User Guide. Domain *string `type:"string"` @@ -17964,10 +18418,16 @@ type CreateDBInstanceInput struct { // Valid Values: 0 - 15 PromotionTier *int64 `type:"integer"` - // A value that indicates whether the DB instance is publicly accessible. When - // the DB instance is publicly accessible, it is an Internet-facing instance - // with a publicly resolvable DNS name, which resolves to a public IP address. - // When the DB instance isn't publicly accessible, it is an internal instance + // A value that indicates whether the DB instance is publicly accessible. + // + // When the DB instance is publicly accessible, its DNS endpoint resolves to + // the private IP address from within the DB instance's VPC, and to the public + // IP address from outside of the DB instance's VPC. Access to the DB instance + // is ultimately controlled by the security group it uses, and that public access + // is not permitted if the security group assigned to the DB instance doesn't + // permit it. + // + // When the DB instance isn't publicly accessible, it is an internal DB instance // with a DNS name that resolves to a private IP address. // // Default: The default behavior varies depending on whether DBSubnetGroupName @@ -18451,17 +18911,11 @@ type CreateDBInstanceReadReplicaInput struct { // DestinationRegion is used for presigning the request to a given region. DestinationRegion *string `type:"string"` - // The Active Directory directory ID to create the DB instance in. - // - // For Oracle DB instances, Amazon RDS can use Kerberos Authentication to authenticate - // users that connect to the DB instance. For more information, see Using Kerberos - // Authentication with Amazon RDS for Oracle (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-kerberos.html) - // in the Amazon RDS User Guide. + // The Active Directory directory ID to create the DB instance in. Currently, + // only MySQL, Microsoft SQL Server, Oracle, and PostgreSQL DB instances can + // be created in an Active Directory Domain. // - // For Microsoft SQL Server DB instances, Amazon RDS can use Windows Authentication - // to authenticate users that connect to the DB instance. For more information, - // see Using Windows Authentication with an Amazon RDS DB Instance Running Microsoft - // SQL Server (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_SQLServerWinAuth.html) + // For more information, see Kerberos Authentication (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html) // in the Amazon RDS User Guide. Domain *string `type:"string"` @@ -18618,14 +19072,37 @@ type CreateDBInstanceReadReplicaInput struct { // class of the DB instance. ProcessorFeatures []*ProcessorFeature `locationNameList:"ProcessorFeature" type:"list"` - // A value that indicates whether the DB instance is publicly accessible. When - // the DB instance is publicly accessible, it is an Internet-facing instance - // with a publicly resolvable DNS name, which resolves to a public IP address. - // When the DB instance isn't publicly accessible, it is an internal instance - // with a DNS name that resolves to a private IP address. For more information, - // see CreateDBInstance. + // A value that indicates whether the DB instance is publicly accessible. + // + // When the DB instance is publicly accessible, its DNS endpoint resolves to + // the private IP address from within the DB instance's VPC, and to the public + // IP address from outside of the DB instance's VPC. Access to the DB instance + // is ultimately controlled by the security group it uses, and that public access + // is not permitted if the security group assigned to the DB instance doesn't + // permit it. + // + // When the DB instance isn't publicly accessible, it is an internal DB instance + // with a DNS name that resolves to a private IP address. + // + // For more information, see CreateDBInstance. PubliclyAccessible *bool `type:"boolean"` + // The open mode of the replica database: mounted or read-only. + // + // This parameter is only supported for Oracle DB instances. + // + // Mounted DB replicas are included in Oracle Enterprise Edition. The main use + // case for mounted replicas is cross-Region disaster recovery. The primary + // database doesn't use Active Data Guard to transmit information to the mounted + // replica. Because it doesn't accept user connections, a mounted replica can't + // serve a read-only workload. + // + // You can create a combination of mounted and read-only DB replicas for the + // same primary DB instance. For more information, see Working with Oracle Read + // Replicas for Amazon RDS (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-read-replicas.html) + // in the Amazon RDS User Guide. + ReplicaMode *string `type:"string" enum:"ReplicaMode"` + // The identifier of the DB instance that will act as the source for the read // replica. Each DB instance can have up to five read replicas. // @@ -18873,6 +19350,12 @@ func (s *CreateDBInstanceReadReplicaInput) SetPubliclyAccessible(v bool) *Create return s } +// SetReplicaMode sets the ReplicaMode field's value. +func (s *CreateDBInstanceReadReplicaInput) SetReplicaMode(v string) *CreateDBInstanceReadReplicaInput { + s.ReplicaMode = &v + return s +} + // SetSourceDBInstanceIdentifier sets the SourceDBInstanceIdentifier field's value. func (s *CreateDBInstanceReadReplicaInput) SetSourceDBInstanceIdentifier(v string) *CreateDBInstanceReadReplicaInput { s.SourceDBInstanceIdentifier = &v @@ -19551,11 +20034,10 @@ type CreateEventSubscriptionInput struct { // not active. Enabled *bool `type:"boolean"` - // A list of event categories for a SourceType that you want to subscribe to. - // You can see a list of the categories for a given SourceType in the Events - // (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.html) - // topic in the Amazon RDS User Guide or by using the DescribeEventCategories - // action. + // A list of event categories for a particular source type (SourceType) that + // you want to subscribe to. You can see a list of the categories for a given + // source type in Events (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.html) + // in the Amazon RDS User Guide or by using the DescribeEventCategories operation. EventCategories []*string `locationNameList:"EventCategory" type:"list"` // The Amazon Resource Name (ARN) of the SNS topic created for event notification. @@ -19572,24 +20054,30 @@ type CreateEventSubscriptionInput struct { // // Constraints: // - // * If SourceIds are supplied, SourceType must also be provided. + // * If a SourceIds value is supplied, SourceType must also be provided. // - // * If the source type is a DB instance, then a DBInstanceIdentifier must + // * If the source type is a DB instance, a DBInstanceIdentifier value must // be supplied. // - // * If the source type is a DB security group, a DBSecurityGroupName must + // * If the source type is a DB cluster, a DBClusterIdentifier value must // be supplied. // - // * If the source type is a DB parameter group, a DBParameterGroupName must + // * If the source type is a DB parameter group, a DBParameterGroupName value + // must be supplied. + // + // * If the source type is a DB security group, a DBSecurityGroupName value + // must be supplied. + // + // * If the source type is a DB snapshot, a DBSnapshotIdentifier value must // be supplied. // - // * If the source type is a DB snapshot, a DBSnapshotIdentifier must be - // supplied. + // * If the source type is a DB cluster snapshot, a DBClusterSnapshotIdentifier + // value must be supplied. SourceIds []*string `locationNameList:"SourceId" type:"list"` // The type of source that is generating the events. For example, if you want - // to be notified of events generated by a DB instance, you would set this parameter - // to db-instance. if this value isn't specified, all events are returned. + // to be notified of events generated by a DB instance, you set this parameter + // to db-instance. If this value isn't specified, all events are returned. // // Valid values: db-instance | db-cluster | db-parameter-group | db-security-group // | db-snapshot | db-cluster-snapshot @@ -20134,6 +20622,17 @@ type DBCluster struct { // Indicates the database engine version. EngineVersion *string `type:"string"` + // Specifies whether you have requested to enable write forwarding for a secondary + // cluster in an Aurora global database. Because write forwarding takes time + // to enable, check the value of GlobalWriteForwardingStatus to confirm that + // the request has completed before using the write forwarding feature for this + // cluster. + GlobalWriteForwardingRequested *bool `type:"boolean"` + + // Specifies whether a secondary cluster in an Aurora global database has write + // forwarding enabled, not enabled, or is in the process of enabling it. + GlobalWriteForwardingStatus *string `type:"string" enum:"WriteForwardingStatus"` + // Specifies the ID that Amazon Route 53 assigns when you create a hosted zone. HostedZoneId *string `type:"string"` @@ -20432,6 +20931,18 @@ func (s *DBCluster) SetEngineVersion(v string) *DBCluster { return s } +// SetGlobalWriteForwardingRequested sets the GlobalWriteForwardingRequested field's value. +func (s *DBCluster) SetGlobalWriteForwardingRequested(v bool) *DBCluster { + s.GlobalWriteForwardingRequested = &v + return s +} + +// SetGlobalWriteForwardingStatus sets the GlobalWriteForwardingStatus field's value. +func (s *DBCluster) SetGlobalWriteForwardingStatus(v string) *DBCluster { + s.GlobalWriteForwardingStatus = &v + return s +} + // SetHostedZoneId sets the HostedZoneId field's value. func (s *DBCluster) SetHostedZoneId(v string) *DBCluster { s.HostedZoneId = &v @@ -20590,7 +21101,9 @@ type DBClusterEndpoint struct { StaticMembers []*string `type:"list"` // The current status of the endpoint. One of: creating, available, deleting, - // modifying. + // inactive, modifying. The inactive state applies to an endpoint that can't + // be used for a certain kind of cluster, such as a writer endpoint for a read-only + // secondary cluster in a global database. Status *string `type:"string"` } @@ -21241,10 +21754,18 @@ type DBEngineVersion struct { // of the CreateDBInstance action. SupportedTimezones []*Timezone `locationNameList:"Timezone" type:"list"` + // A value that indicates whether you can use Aurora global databases with a + // specific DB engine version. + SupportsGlobalDatabases *bool `type:"boolean"` + // A value that indicates whether the engine version supports exporting the // log types specified by ExportableLogTypes to CloudWatch Logs. SupportsLogExportsToCloudwatchLogs *bool `type:"boolean"` + // A value that indicates whether you can use Aurora parallel query with a specific + // DB engine version. + SupportsParallelQuery *bool `type:"boolean"` + // Indicates whether the database engine version supports read replicas. SupportsReadReplica *bool `type:"boolean"` @@ -21335,12 +21856,24 @@ func (s *DBEngineVersion) SetSupportedTimezones(v []*Timezone) *DBEngineVersion return s } +// SetSupportsGlobalDatabases sets the SupportsGlobalDatabases field's value. +func (s *DBEngineVersion) SetSupportsGlobalDatabases(v bool) *DBEngineVersion { + s.SupportsGlobalDatabases = &v + return s +} + // SetSupportsLogExportsToCloudwatchLogs sets the SupportsLogExportsToCloudwatchLogs field's value. func (s *DBEngineVersion) SetSupportsLogExportsToCloudwatchLogs(v bool) *DBEngineVersion { s.SupportsLogExportsToCloudwatchLogs = &v return s } +// SetSupportsParallelQuery sets the SupportsParallelQuery field's value. +func (s *DBEngineVersion) SetSupportsParallelQuery(v bool) *DBEngineVersion { + s.SupportsParallelQuery = &v + return s +} + // SetSupportsReadReplica sets the SupportsReadReplica field's value. func (s *DBEngineVersion) SetSupportsReadReplica(v bool) *DBEngineVersion { s.SupportsReadReplica = &v @@ -21567,10 +22100,19 @@ type DBInstance struct { // in the Amazon Aurora User Guide. PromotionTier *int64 `type:"integer"` - // Specifies the accessibility options for the DB instance. A value of true - // specifies an Internet-facing instance with a publicly resolvable DNS name, - // which resolves to a public IP address. A value of false specifies an internal - // instance with a DNS name that resolves to a private IP address. + // Specifies the accessibility options for the DB instance. + // + // When the DB instance is publicly accessible, its DNS endpoint resolves to + // the private IP address from within the DB instance's VPC, and to the public + // IP address from outside of the DB instance's VPC. Access to the DB instance + // is ultimately controlled by the security group it uses, and that public access + // is not permitted if the security group assigned to the DB instance doesn't + // permit it. + // + // When the DB instance isn't publicly accessible, it is an internal DB instance + // with a DNS name that resolves to a private IP address. + // + // For more information, see CreateDBInstance. PubliclyAccessible *bool `type:"boolean"` // Contains one or more identifiers of Aurora DB clusters to which the RDS DB @@ -21590,6 +22132,13 @@ type DBInstance struct { // a read replica. ReadReplicaSourceDBInstanceIdentifier *string `type:"string"` + // The open mode of an Oracle read replica. The default is open-read-only. For + // more information, see Working with Oracle Read Replicas for Amazon RDS (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-read-replicas.html) + // in the Amazon RDS User Guide. + // + // This attribute is only supported in RDS for Oracle. + ReplicaMode *string `type:"string" enum:"ReplicaMode"` + // If present, specifies the name of the secondary Availability Zone for a DB // instance with multi-AZ support. SecondaryAvailabilityZone *string `type:"string"` @@ -21934,6 +22483,12 @@ func (s *DBInstance) SetReadReplicaSourceDBInstanceIdentifier(v string) *DBInsta return s } +// SetReplicaMode sets the ReplicaMode field's value. +func (s *DBInstance) SetReplicaMode(v string) *DBInstance { + s.ReplicaMode = &v + return s +} + // SetSecondaryAvailabilityZone sets the SecondaryAvailabilityZone field's value. func (s *DBInstance) SetSecondaryAvailabilityZone(v string) *DBInstance { s.SecondaryAvailabilityZone = &v @@ -22459,10 +23014,6 @@ func (s *DBParameterGroupStatus) SetParameterApplyStatus(v string) *DBParameterG return s } -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // The data structure representing a proxy managed by the RDS Proxy. // // This data type is used as a response element in the DescribeDBProxies action. @@ -22626,10 +23177,6 @@ func (s *DBProxy) SetVpcSubnetIds(v []*string) *DBProxy { return s } -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Contains the details for an RDS Proxy target. It represents an RDS DB instance // or Aurora DB cluster that the proxy can connect to. One or more targets are // associated with an RDS Proxy target group. @@ -22717,10 +23264,6 @@ func (s *DBProxyTarget) SetType(v string) *DBProxyTarget { return s } -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Represents a set of RDS DB instances, Aurora DB clusters, or both that a // proxy can connect to. Currently, each target group is associated with exactly // one RDS DB instance or Aurora DB cluster. @@ -22982,8 +23525,8 @@ type DBSnapshot struct { // accounts is enabled, and otherwise false. IAMDatabaseAuthenticationEnabled *bool `type:"boolean"` - // Specifies the time when the snapshot was taken, in Universal Coordinated - // Time (UTC). + // Specifies the time in Coordinated Universal Time (UTC) when the DB instance, + // from which the snapshot was taken, was created. InstanceCreateTime *time.Time `type:"timestamp"` // Specifies the Provisioned IOPS (I/O operations per second) value of the DB @@ -23013,8 +23556,7 @@ type DBSnapshot struct { // class of the DB instance when the DB snapshot was created. ProcessorFeatures []*ProcessorFeature `locationNameList:"ProcessorFeature" type:"list"` - // Provides the time when the snapshot was taken, in Universal Coordinated Time - // (UTC). + // Specifies when the snapshot was taken in Coodinated Universal Time (UTC). SnapshotCreateTime *time.Time `type:"timestamp"` // Provides the type of the DB snapshot. @@ -23533,7 +24075,9 @@ type DeleteDBClusterEndpointOutput struct { StaticMembers []*string `type:"list"` // The current status of the endpoint. One of: creating, available, deleting, - // modifying. + // inactive, modifying. The inactive state applies to an endpoint that can't + // be used for a certain kind of cluster, such as a writer endpoint for a read-only + // secondary cluster in a global database. Status *string `type:"string"` } @@ -25166,7 +25710,7 @@ type DescribeDBClusterEndpointsInput struct { // db-cluster-endpoint-id, db-cluster-endpoint-status. Values for the db-cluster-endpoint-type // filter can be one or more of: reader, writer, custom. Values for the db-cluster-endpoint-custom-type // filter can be one or more of: reader, any. Values for the db-cluster-endpoint-status - // filter can be one or more of: available, creating, deleting, modifying. + // filter can be one or more of: available, creating, deleting, inactive, modifying. Filters []*Filter `locationNameList:"Filter" type:"list"` // An optional pagination token provided by a previous DescribeDBClusterEndpoints @@ -27963,7 +28507,8 @@ type DescribeEventCategoriesInput struct { // The type of source that is generating the events. // - // Valid values: db-instance | db-parameter-group | db-security-group | db-snapshot + // Valid values: db-instance | db-cluster | db-parameter-group | db-security-group + // | db-snapshot | db-cluster-snapshot SourceType *string `type:"string"` } @@ -28009,7 +28554,7 @@ func (s *DescribeEventCategoriesInput) SetSourceType(v string) *DescribeEventCat return s } -// Data returned from the DescribeEventCategories action. +// Data returned from the DescribeEventCategories operation. type DescribeEventCategoriesOutput struct { _ struct{} `type:"structure"` @@ -28189,16 +28734,23 @@ type DescribeEventsInput struct { // // * If SourceIdentifier is supplied, SourceType must also be provided. // - // * If the source type is DBInstance, then a DBInstanceIdentifier must be - // supplied. + // * If the source type is a DB instance, a DBInstanceIdentifier value must + // be supplied. + // + // * If the source type is a DB cluster, a DBClusterIdentifier value must + // be supplied. + // + // * If the source type is a DB parameter group, a DBParameterGroupName value + // must be supplied. // - // * If the source type is DBSecurityGroup, a DBSecurityGroupName must be - // supplied. + // * If the source type is a DB security group, a DBSecurityGroupName value + // must be supplied. // - // * If the source type is DBParameterGroup, a DBParameterGroupName must + // * If the source type is a DB snapshot, a DBSnapshotIdentifier value must // be supplied. // - // * If the source type is DBSnapshot, a DBSnapshotIdentifier must be supplied. + // * If the source type is a DB cluster snapshot, a DBClusterSnapshotIdentifier + // value must be supplied. // // * Can't end with a hyphen or contain two consecutive hyphens. SourceIdentifier *string `type:"string"` @@ -30272,7 +30824,7 @@ func (s *Event) SetSourceType(v string) *Event { } // Contains the results of a successful invocation of the DescribeEventCategories -// action. +// operation. type EventCategoriesMap struct { _ struct{} `type:"structure"` @@ -30858,6 +31410,10 @@ type GlobalClusterMember struct { // The Amazon Resource Name (ARN) for each Aurora cluster. DBClusterArn *string `type:"string"` + // Specifies whether a secondary cluster in an Aurora global database has write + // forwarding enabled, not enabled, or is in the process of enabling it. + GlobalWriteForwardingStatus *string `type:"string" enum:"WriteForwardingStatus"` + // Specifies whether the Aurora cluster is the primary cluster (that is, has // read-write capability) for the Aurora global database with which it is associated. IsWriter *bool `type:"boolean"` @@ -30883,6 +31439,12 @@ func (s *GlobalClusterMember) SetDBClusterArn(v string) *GlobalClusterMember { return s } +// SetGlobalWriteForwardingStatus sets the GlobalWriteForwardingStatus field's value. +func (s *GlobalClusterMember) SetGlobalWriteForwardingStatus(v string) *GlobalClusterMember { + s.GlobalWriteForwardingStatus = &v + return s +} + // SetIsWriter sets the IsWriter field's value. func (s *GlobalClusterMember) SetIsWriter(v bool) *GlobalClusterMember { s.IsWriter = &v @@ -31706,7 +32268,9 @@ type ModifyDBClusterEndpointOutput struct { StaticMembers []*string `type:"list"` // The current status of the endpoint. One of: creating, available, deleting, - // modifying. + // inactive, modifying. The inactive state applies to an endpoint that can't + // be used for a certain kind of cluster, such as a writer endpoint for a read-only + // secondary cluster in a global database. Status *string `type:"string"` } @@ -31809,6 +32373,8 @@ type ModifyDBClusterInput struct { // The target backtrack window, in seconds. To disable backtracking, set this // value to 0. // + // Currently, Backtrack is only supported for Aurora MySQL DB clusters. + // // Default: 0 // // Constraints: @@ -31872,12 +32438,22 @@ type ModifyDBClusterInput struct { // The Active Directory directory ID to move the DB cluster to. Specify none // to remove the cluster from its current domain. The domain must be created // prior to this operation. + // + // For more information, see Kerberos Authentication (https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/kerberos-authentication.html) + // in the Amazon Aurora User Guide. Domain *string `type:"string"` // Specify the name of the IAM role to be used when making API calls to the // Directory Service. DomainIAMRoleName *string `type:"string"` + // A value that indicates whether to enable write operations to be forwarded + // from this cluster to the primary cluster in an Aurora global database. The + // resulting changes are replicated back to this cluster. This parameter only + // applies to DB clusters that are secondary clusters in an Aurora global database. + // By default, Aurora disallows write operations for secondary clusters. + EnableGlobalWriteForwarding *bool `type:"boolean"` + // A value that indicates whether to enable the HTTP endpoint for an Aurora // Serverless DB cluster. By default, the HTTP endpoint is disabled. // @@ -32093,6 +32669,12 @@ func (s *ModifyDBClusterInput) SetDomainIAMRoleName(v string) *ModifyDBClusterIn return s } +// SetEnableGlobalWriteForwarding sets the EnableGlobalWriteForwarding field's value. +func (s *ModifyDBClusterInput) SetEnableGlobalWriteForwarding(v bool) *ModifyDBClusterInput { + s.EnableGlobalWriteForwarding = &v + return s +} + // SetEnableHttpEndpoint sets the EnableHttpEndpoint field's value. func (s *ModifyDBClusterInput) SetEnableHttpEndpoint(v bool) *ModifyDBClusterInput { s.EnableHttpEndpoint = &v @@ -32245,6 +32827,9 @@ type ModifyDBClusterSnapshotAttributeInput struct { // To manage authorization for other AWS accounts to copy or restore a manual // DB cluster snapshot, set this value to restore. // + // To view the list of attributes available to modify, use the DescribeDBClusterSnapshotAttributes + // API action. + // // AttributeName is a required field AttributeName *string `type:"string" required:"true"` @@ -32583,18 +33168,10 @@ type ModifyDBInstanceInput struct { // The Active Directory directory ID to move the DB instance to. Specify none // to remove the instance from its current domain. The domain must be created - // prior to this operation. Currently, only Microsoft SQL Server and Oracle - // DB instances can be created in an Active Directory Domain. - // - // For Microsoft SQL Server DB instances, Amazon RDS can use Windows Authentication - // to authenticate users that connect to the DB instance. For more information, - // see Using Windows Authentication with an Amazon RDS DB Instance Running Microsoft - // SQL Server (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_SQLServerWinAuth.html) - // in the Amazon RDS User Guide. + // prior to this operation. Currently, only MySQL, Microsoft SQL Server, Oracle, + // and PostgreSQL DB instances can be created in an Active Directory Domain. // - // For Oracle DB instances, Amazon RDS can use Kerberos Authentication to authenticate - // users that connect to the DB instance. For more information, see Using Kerberos - // Authentication with Amazon RDS for Oracle (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-kerberos.html) + // For more information, see Kerberos Authentication (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html) // in the Amazon RDS User Guide. Domain *string `type:"string"` @@ -32831,10 +33408,16 @@ type ModifyDBInstanceInput struct { // Valid Values: 0 - 15 PromotionTier *int64 `type:"integer"` - // A value that indicates whether the DB instance is publicly accessible. When - // the DB instance is publicly accessible, it is an Internet-facing instance - // with a publicly resolvable DNS name, which resolves to a public IP address. - // When the DB instance isn't publicly accessible, it is an internal instance + // A value that indicates whether the DB instance is publicly accessible. + // + // When the DB instance is publicly accessible, its DNS endpoint resolves to + // the private IP address from within the DB instance's VPC, and to the public + // IP address from outside of the DB instance's VPC. Access to the DB instance + // is ultimately controlled by the security group it uses, and that public access + // is not permitted if the security group assigned to the DB instance doesn't + // permit it. + // + // When the DB instance isn't publicly accessible, it is an internal DB instance // with a DNS name that resolves to a private IP address. // // PubliclyAccessible only applies to DB instances in a VPC. The DB instance @@ -32845,6 +33428,20 @@ type ModifyDBInstanceInput struct { // of the value of the ApplyImmediately parameter. PubliclyAccessible *bool `type:"boolean"` + // A value that sets the open mode of a replica database to either mounted or + // read-only. + // + // Currently, this parameter is only supported for Oracle DB instances. + // + // Mounted DB replicas are included in Oracle Enterprise Edition. The main use + // case for mounted replicas is cross-Region disaster recovery. The primary + // database doesn't use Active Data Guard to transmit information to the mounted + // replica. Because it doesn't accept user connections, a mounted replica can't + // serve a read-only workload. For more information, see Working with Oracle + // Read Replicas for Amazon RDS (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-read-replicas.html) + // in the Amazon RDS User Guide. + ReplicaMode *string `type:"string" enum:"ReplicaMode"` + // Specifies the storage type to be associated with the DB instance. // // If you specify Provisioned IOPS (io1), you must also include a value for @@ -33138,6 +33735,12 @@ func (s *ModifyDBInstanceInput) SetPubliclyAccessible(v bool) *ModifyDBInstanceI return s } +// SetReplicaMode sets the ReplicaMode field's value. +func (s *ModifyDBInstanceInput) SetReplicaMode(v string) *ModifyDBInstanceInput { + s.ReplicaMode = &v + return s +} + // SetStorageType sets the StorageType field's value. func (s *ModifyDBInstanceInput) SetStorageType(v string) *ModifyDBInstanceInput { s.StorageType = &v @@ -33499,6 +34102,9 @@ type ModifyDBSnapshotAttributeInput struct { // To manage authorization for other AWS accounts to copy or restore a manual // DB snapshot, set this value to restore. // + // To view the list of attributes available to modify, use the DescribeDBSnapshotAttributes + // API action. + // // AttributeName is a required field AttributeName *string `type:"string" required:"true"` @@ -33811,11 +34417,10 @@ type ModifyEventSubscriptionInput struct { // A value that indicates whether to activate the subscription. Enabled *bool `type:"boolean"` - // A list of event categories for a SourceType that you want to subscribe to. - // You can see a list of the categories for a given SourceType in the Events - // (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.html) - // topic in the Amazon RDS User Guide or by using the DescribeEventCategories - // action. + // A list of event categories for a source type (SourceType) that you want to + // subscribe to. You can see a list of the categories for a given source type + // in Events (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Events.html) + // in the Amazon RDS User Guide or by using the DescribeEventCategories operation. EventCategories []*string `locationNameList:"EventCategory" type:"list"` // The Amazon Resource Name (ARN) of the SNS topic created for event notification. @@ -33827,7 +34432,8 @@ type ModifyEventSubscriptionInput struct { // to be notified of events generated by a DB instance, you would set this parameter // to db-instance. If this value isn't specified, all events are returned. // - // Valid values: db-instance | db-parameter-group | db-security-group | db-snapshot + // Valid values: db-instance | db-cluster | db-parameter-group | db-security-group + // | db-snapshot | db-cluster-snapshot SourceType *string `type:"string"` // The name of the RDS event notification subscription. @@ -34852,6 +35458,13 @@ type OrderableDBInstanceOption struct { // Indicates whether a DB instance is Multi-AZ capable. MultiAZCapable *bool `type:"boolean"` + // Whether a DB instance supports RDS on Outposts. + // + // For more information about RDS on Outposts, see Amazon RDS on AWS Outposts + // (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-on-outposts.html) + // in the Amazon RDS User Guide. + OutpostCapable *bool `type:"boolean"` + // Indicates whether a DB instance can have a read replica. ReadReplicaCapable *bool `type:"boolean"` @@ -34869,6 +35482,10 @@ type OrderableDBInstanceOption struct { // from 1 to 60 seconds. SupportsEnhancedMonitoring *bool `type:"boolean"` + // A value that indicates whether you can use Aurora global databases with a + // specific combination of other DB engine attributes. + SupportsGlobalDatabases *bool `type:"boolean"` + // Indicates whether a DB instance supports IAM database authentication. SupportsIAMDatabaseAuthentication *bool `type:"boolean"` @@ -34986,6 +35603,12 @@ func (s *OrderableDBInstanceOption) SetMultiAZCapable(v bool) *OrderableDBInstan return s } +// SetOutpostCapable sets the OutpostCapable field's value. +func (s *OrderableDBInstanceOption) SetOutpostCapable(v bool) *OrderableDBInstanceOption { + s.OutpostCapable = &v + return s +} + // SetReadReplicaCapable sets the ReadReplicaCapable field's value. func (s *OrderableDBInstanceOption) SetReadReplicaCapable(v bool) *OrderableDBInstanceOption { s.ReadReplicaCapable = &v @@ -35010,6 +35633,12 @@ func (s *OrderableDBInstanceOption) SetSupportsEnhancedMonitoring(v bool) *Order return s } +// SetSupportsGlobalDatabases sets the SupportsGlobalDatabases field's value. +func (s *OrderableDBInstanceOption) SetSupportsGlobalDatabases(v bool) *OrderableDBInstanceOption { + s.SupportsGlobalDatabases = &v + return s +} + // SetSupportsIAMDatabaseAuthentication sets the SupportsIAMDatabaseAuthentication field's value. func (s *OrderableDBInstanceOption) SetSupportsIAMDatabaseAuthentication(v bool) *OrderableDBInstanceOption { s.SupportsIAMDatabaseAuthentication = &v @@ -35052,6 +35681,34 @@ func (s *OrderableDBInstanceOption) SetVpc(v bool) *OrderableDBInstanceOption { return s } +// A data type that represents an Outpost. +// +// For more information about RDS on Outposts, see Amazon RDS on AWS Outposts +// (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-on-outposts.html) +// in the Amazon RDS User Guide. +type Outpost struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the Outpost. + Arn *string `type:"string"` +} + +// String returns the string representation +func (s Outpost) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Outpost) GoString() string { + return s.String() +} + +// SetArn sets the Arn field's value. +func (s *Outpost) SetArn(v string) *Outpost { + s.Arn = &v + return s +} + // This data type is used as a request parameter in the ModifyDBParameterGroup // and ResetDBParameterGroup actions. // @@ -36860,6 +37517,8 @@ type RestoreDBClusterFromS3Input struct { // The target backtrack window, in seconds. To disable backtracking, set this // value to 0. // + // Currently, Backtrack is only supported for Aurora MySQL DB clusters. + // // Default: 0 // // Constraints: @@ -36887,7 +37546,7 @@ type RestoreDBClusterFromS3Input struct { CopyTagsToSnapshot *bool `type:"boolean"` // The name of the DB cluster to create from the source data in the Amazon S3 - // bucket. This parameter is isn't case-sensitive. + // bucket. This parameter isn't case-sensitive. // // Constraints: // @@ -36951,9 +37610,10 @@ type RestoreDBClusterFromS3Input struct { // in the Amazon Aurora User Guide. EnableIAMDatabaseAuthentication *bool `type:"boolean"` - // The name of the database engine to be used for the restored DB cluster. + // The name of the database engine to be used for this DB cluster. // - // Valid Values: aurora, aurora-postgresql + // Valid Values: aurora (for MySQL 5.6-compatible Aurora), aurora-mysql (for + // MySQL 5.7-compatible Aurora), and aurora-postgresql // // Engine is a required field Engine *string `type:"string" required:"true"` @@ -37095,9 +37755,9 @@ type RestoreDBClusterFromS3Input struct { // The version of the database that the backup files were created from. // - // MySQL version 5.5 and 5.6 are supported. + // MySQL versions 5.5, 5.6, and 5.7 are supported. // - // Example: 5.6.22 + // Example: 5.6.40, 5.7.28 // // SourceEngineVersion is a required field SourceEngineVersion *string `type:"string" required:"true"` @@ -37379,6 +38039,8 @@ type RestoreDBClusterFromSnapshotInput struct { // The target backtrack window, in seconds. To disable backtracking, set this // value to 0. // + // Currently, Backtrack is only supported for Aurora MySQL DB clusters. + // // Default: 0 // // Constraints: @@ -37439,7 +38101,12 @@ type RestoreDBClusterFromSnapshotInput struct { DeletionProtection *bool `type:"boolean"` // Specify the Active Directory directory ID to restore the DB cluster in. The - // domain must be created prior to this operation. + // domain must be created prior to this operation. Currently, only MySQL, Microsoft + // SQL Server, Oracle, and PostgreSQL DB instances can be created in an Active + // Directory Domain. + // + // For more information, see Kerberos Authentication (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html) + // in the Amazon RDS User Guide. Domain *string `type:"string"` // Specify the name of the IAM role to be used when making API calls to the @@ -37747,6 +38414,8 @@ type RestoreDBClusterToPointInTimeInput struct { // The target backtrack window, in seconds. To disable backtracking, set this // value to 0. // + // Currently, Backtrack is only supported for Aurora MySQL DB clusters. + // // Default: 0 // // Constraints: @@ -38178,19 +38847,11 @@ type RestoreDBInstanceFromDBSnapshotInput struct { DeletionProtection *bool `type:"boolean"` // Specify the Active Directory directory ID to restore the DB instance in. - // The domain must be created prior to this operation. Currently, only Microsoft - // SQL Server and Oracle DB instances can be created in an Active Directory - // Domain. - // - // For Microsoft SQL Server DB instances, Amazon RDS can use Windows Authentication - // to authenticate users that connect to the DB instance. For more information, - // see Using Windows Authentication with an Amazon RDS DB Instance Running Microsoft - // SQL Server (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_SQLServerWinAuth.html) - // in the Amazon RDS User Guide. + // The domain must be created prior to this operation. Currently, only MySQL, + // Microsoft SQL Server, Oracle, and PostgreSQL DB instances can be created + // in an Active Directory Domain. // - // For Oracle DB instances, Amazon RDS can use Kerberos Authentication to authenticate - // users that connect to the DB instance. For more information, see Using Kerberos - // Authentication with Amazon RDS for Oracle (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-kerberos.html) + // For more information, see Kerberos Authentication (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html) // in the Amazon RDS User Guide. Domain *string `type:"string"` @@ -38291,12 +38952,19 @@ type RestoreDBInstanceFromDBSnapshotInput struct { // class of the DB instance. ProcessorFeatures []*ProcessorFeature `locationNameList:"ProcessorFeature" type:"list"` - // A value that indicates whether the DB instance is publicly accessible. When - // the DB instance is publicly accessible, it is an Internet-facing instance - // with a publicly resolvable DNS name, which resolves to a public IP address. - // When the DB instance isn't publicly accessible, it is an internal instance - // with a DNS name that resolves to a private IP address. For more information, - // see CreateDBInstance. + // A value that indicates whether the DB instance is publicly accessible. + // + // When the DB instance is publicly accessible, its DNS endpoint resolves to + // the private IP address from within the DB instance's VPC, and to the public + // IP address from outside of the DB instance's VPC. Access to the DB instance + // is ultimately controlled by the security group it uses, and that public access + // is not permitted if the security group assigned to the DB instance doesn't + // permit it. + // + // When the DB instance isn't publicly accessible, it is an internal DB instance + // with a DNS name that resolves to a private IP address. + // + // For more information, see CreateDBInstance. PubliclyAccessible *bool `type:"boolean"` // Specifies the storage type to be associated with the DB instance. @@ -38803,12 +39471,19 @@ type RestoreDBInstanceFromS3Input struct { // class of the DB instance. ProcessorFeatures []*ProcessorFeature `locationNameList:"ProcessorFeature" type:"list"` - // A value that indicates whether the DB instance is publicly accessible. When - // the DB instance is publicly accessible, it is an Internet-facing instance - // with a publicly resolvable DNS name, which resolves to a public IP address. - // When the DB instance isn't publicly accessible, it is an internal instance - // with a DNS name that resolves to a private IP address. For more information, - // see CreateDBInstance. + // A value that indicates whether the DB instance is publicly accessible. + // + // When the DB instance is publicly accessible, its DNS endpoint resolves to + // the private IP address from within the DB instance's VPC, and to the public + // IP address from outside of the DB instance's VPC. Access to the DB instance + // is ultimately controlled by the security group it uses, and that public access + // is not permitted if the security group assigned to the DB instance doesn't + // permit it. + // + // When the DB instance isn't publicly accessible, it is an internal DB instance + // with a DNS name that resolves to a private IP address. + // + // For more information, see CreateDBInstance. PubliclyAccessible *bool `type:"boolean"` // The name of your Amazon S3 bucket that contains your database backup file. @@ -38832,9 +39507,11 @@ type RestoreDBInstanceFromS3Input struct { // SourceEngine is a required field SourceEngine *string `type:"string" required:"true"` - // The engine version of your source database. + // The version of the database that the backup files were created from. + // + // MySQL versions 5.6 and 5.7 are supported. // - // Valid Values: 5.6 + // Example: 5.6.40 // // SourceEngineVersion is a required field SourceEngineVersion *string `type:"string" required:"true"` @@ -39253,19 +39930,11 @@ type RestoreDBInstanceToPointInTimeInput struct { DeletionProtection *bool `type:"boolean"` // Specify the Active Directory directory ID to restore the DB instance in. - // The domain must be created prior to this operation. Currently, only Microsoft - // SQL Server and Oracle DB instances can be created in an Active Directory - // Domain. - // - // For Microsoft SQL Server DB instances, Amazon RDS can use Windows Authentication - // to authenticate users that connect to the DB instance. For more information, - // see Using Windows Authentication with an Amazon RDS DB Instance Running Microsoft - // SQL Server (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_SQLServerWinAuth.html) - // in the Amazon RDS User Guide. + // The domain must be created prior to this operation. Currently, only MySQL, + // Microsoft SQL Server, Oracle, and PostgreSQL DB instances can be created + // in an Active Directory Domain. // - // For Oracle DB instances, Amazon RDS can use Kerberos Authentication to authenticate - // users that connect to the DB instance. For more information, see Using Kerberos - // Authentication with Amazon RDS for Oracle (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-kerberos.html) + // For more information, see Kerberos Authentication (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html) // in the Amazon RDS User Guide. Domain *string `type:"string"` @@ -39360,12 +40029,19 @@ type RestoreDBInstanceToPointInTimeInput struct { // class of the DB instance. ProcessorFeatures []*ProcessorFeature `locationNameList:"ProcessorFeature" type:"list"` - // A value that indicates whether the DB instance is publicly accessible. When - // the DB instance is publicly accessible, it is an Internet-facing instance - // with a publicly resolvable DNS name, which resolves to a public IP address. - // When the DB instance isn't publicly accessible, it is an internal instance - // with a DNS name that resolves to a private IP address. For more information, - // see CreateDBInstance. + // A value that indicates whether the DB instance is publicly accessible. + // + // When the DB instance is publicly accessible, its DNS endpoint resolves to + // the private IP address from within the DB instance's VPC, and to the public + // IP address from outside of the DB instance's VPC. Access to the DB instance + // is ultimately controlled by the security group it uses, and that public access + // is not permitted if the security group assigned to the DB instance doesn't + // permit it. + // + // When the DB instance isn't publicly accessible, it is an internal DB instance + // with a DNS name that resolves to a private IP address. + // + // For more information, see CreateDBInstance. PubliclyAccessible *bool `type:"boolean"` // The date and time to restore from. @@ -40331,9 +41007,27 @@ type StartExportTaskInput struct { // The ID of the AWS KMS key to use to encrypt the snapshot exported to Amazon // S3. The KMS key ID is the Amazon Resource Name (ARN), the KMS key identifier, - // or the KMS key alias for the KMS encryption key. The IAM role used for the - // snapshot export must have encryption and decryption permissions to use this - // KMS key. + // or the KMS key alias for the KMS encryption key. The caller of this operation + // must be authorized to execute the following operations. These can be set + // in the KMS key policy: + // + // * GrantOperation.Encrypt + // + // * GrantOperation.Decrypt + // + // * GrantOperation.GenerateDataKey + // + // * GrantOperation.GenerateDataKeyWithoutPlaintext + // + // * GrantOperation.ReEncryptFrom + // + // * GrantOperation.ReEncryptTo + // + // * GrantOperation.CreateGrant + // + // * GrantOperation.DescribeKey + // + // * GrantOperation.RetireGrant // // KmsKeyId is a required field KmsKeyId *string `type:"string" required:"true"` @@ -40830,8 +41524,8 @@ func (s *StopDBInstanceOutput) SetDBInstance(v *DBInstance) *StopDBInstanceOutpu return s } -// This data type is used as a response element in the DescribeDBSubnetGroups -// action. +// This data type is used as a response element for the DescribeDBSubnetGroups +// operation. type Subnet struct { _ struct{} `type:"structure"` @@ -40841,10 +41535,17 @@ type Subnet struct { // type. SubnetAvailabilityZone *AvailabilityZone `type:"structure"` - // Specifies the identifier of the subnet. + // The identifier of the subnet. SubnetIdentifier *string `type:"string"` - // Specifies the status of the subnet. + // If the subnet is associated with an Outpost, this value specifies the Outpost. + // + // For more information about RDS on Outposts, see Amazon RDS on AWS Outposts + // (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-on-outposts.html) + // in the Amazon RDS User Guide. + SubnetOutpost *Outpost `type:"structure"` + + // The status of the subnet. SubnetStatus *string `type:"string"` } @@ -40870,6 +41571,12 @@ func (s *Subnet) SetSubnetIdentifier(v string) *Subnet { return s } +// SetSubnetOutpost sets the SubnetOutpost field's value. +func (s *Subnet) SetSubnetOutpost(v *Outpost) *Subnet { + s.SubnetOutpost = v + return s +} + // SetSubnetStatus sets the SubnetStatus field's value. func (s *Subnet) SetSubnetStatus(v string) *Subnet { s.SubnetStatus = &v @@ -40915,10 +41622,6 @@ func (s *Tag) SetValue(v string) *Tag { return s } -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Information about the connection health of an RDS Proxy target. type TargetHealth struct { _ struct{} `type:"structure"` @@ -41053,10 +41756,6 @@ func (s *UpgradeTarget) SetIsMajorVersionUpgrade(v bool) *UpgradeTarget { return s } -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Specifies the details of authentication used by a proxy to log in as a specific // database user. type UserAuthConfig struct { @@ -41123,10 +41822,6 @@ func (s *UserAuthConfig) SetUserName(v string) *UserAuthConfig { return s } -// -// This is prerelease documentation for the RDS Database Proxy feature in preview -// release. It is subject to change. -// // Returns the details of authentication used by a proxy to log in as a specific // database user. type UserAuthConfigInfo struct { @@ -41409,6 +42104,14 @@ const ( ActivityStreamModeAsync = "async" ) +// ActivityStreamMode_Values returns all elements of the ActivityStreamMode enum +func ActivityStreamMode_Values() []string { + return []string{ + ActivityStreamModeSync, + ActivityStreamModeAsync, + } +} + const ( // ActivityStreamStatusStopped is a ActivityStreamStatus enum value ActivityStreamStatusStopped = "stopped" @@ -41423,6 +42126,16 @@ const ( ActivityStreamStatusStopping = "stopping" ) +// ActivityStreamStatus_Values returns all elements of the ActivityStreamStatus enum +func ActivityStreamStatus_Values() []string { + return []string{ + ActivityStreamStatusStopped, + ActivityStreamStatusStarting, + ActivityStreamStatusStarted, + ActivityStreamStatusStopping, + } +} + const ( // ApplyMethodImmediate is a ApplyMethod enum value ApplyMethodImmediate = "immediate" @@ -41431,11 +42144,26 @@ const ( ApplyMethodPendingReboot = "pending-reboot" ) +// ApplyMethod_Values returns all elements of the ApplyMethod enum +func ApplyMethod_Values() []string { + return []string{ + ApplyMethodImmediate, + ApplyMethodPendingReboot, + } +} + const ( // AuthSchemeSecrets is a AuthScheme enum value AuthSchemeSecrets = "SECRETS" ) +// AuthScheme_Values returns all elements of the AuthScheme enum +func AuthScheme_Values() []string { + return []string{ + AuthSchemeSecrets, + } +} + const ( // DBProxyStatusAvailable is a DBProxyStatus enum value DBProxyStatusAvailable = "available" @@ -41465,6 +42193,21 @@ const ( DBProxyStatusReactivating = "reactivating" ) +// DBProxyStatus_Values returns all elements of the DBProxyStatus enum +func DBProxyStatus_Values() []string { + return []string{ + DBProxyStatusAvailable, + DBProxyStatusModifying, + DBProxyStatusIncompatibleNetwork, + DBProxyStatusInsufficientResourceLimits, + DBProxyStatusCreating, + DBProxyStatusDeleting, + DBProxyStatusSuspended, + DBProxyStatusSuspending, + DBProxyStatusReactivating, + } +} + const ( // EngineFamilyMysql is a EngineFamily enum value EngineFamilyMysql = "MYSQL" @@ -41473,6 +42216,14 @@ const ( EngineFamilyPostgresql = "POSTGRESQL" ) +// EngineFamily_Values returns all elements of the EngineFamily enum +func EngineFamily_Values() []string { + return []string{ + EngineFamilyMysql, + EngineFamilyPostgresql, + } +} + const ( // IAMAuthModeDisabled is a IAMAuthMode enum value IAMAuthModeDisabled = "DISABLED" @@ -41481,6 +42232,30 @@ const ( IAMAuthModeRequired = "REQUIRED" ) +// IAMAuthMode_Values returns all elements of the IAMAuthMode enum +func IAMAuthMode_Values() []string { + return []string{ + IAMAuthModeDisabled, + IAMAuthModeRequired, + } +} + +const ( + // ReplicaModeOpenReadOnly is a ReplicaMode enum value + ReplicaModeOpenReadOnly = "open-read-only" + + // ReplicaModeMounted is a ReplicaMode enum value + ReplicaModeMounted = "mounted" +) + +// ReplicaMode_Values returns all elements of the ReplicaMode enum +func ReplicaMode_Values() []string { + return []string{ + ReplicaModeOpenReadOnly, + ReplicaModeMounted, + } +} + const ( // SourceTypeDbInstance is a SourceType enum value SourceTypeDbInstance = "db-instance" @@ -41501,6 +42276,18 @@ const ( SourceTypeDbClusterSnapshot = "db-cluster-snapshot" ) +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeDbInstance, + SourceTypeDbParameterGroup, + SourceTypeDbSecurityGroup, + SourceTypeDbSnapshot, + SourceTypeDbCluster, + SourceTypeDbClusterSnapshot, + } +} + const ( // TargetHealthReasonUnreachable is a TargetHealthReason enum value TargetHealthReasonUnreachable = "UNREACHABLE" @@ -41515,6 +42302,16 @@ const ( TargetHealthReasonPendingProxyCapacity = "PENDING_PROXY_CAPACITY" ) +// TargetHealthReason_Values returns all elements of the TargetHealthReason enum +func TargetHealthReason_Values() []string { + return []string{ + TargetHealthReasonUnreachable, + TargetHealthReasonConnectionFailed, + TargetHealthReasonAuthFailure, + TargetHealthReasonPendingProxyCapacity, + } +} + const ( // TargetStateRegistering is a TargetState enum value TargetStateRegistering = "REGISTERING" @@ -41526,6 +42323,15 @@ const ( TargetStateUnavailable = "UNAVAILABLE" ) +// TargetState_Values returns all elements of the TargetState enum +func TargetState_Values() []string { + return []string{ + TargetStateRegistering, + TargetStateAvailable, + TargetStateUnavailable, + } +} + const ( // TargetTypeRdsInstance is a TargetType enum value TargetTypeRdsInstance = "RDS_INSTANCE" @@ -41536,3 +42342,40 @@ const ( // TargetTypeTrackedCluster is a TargetType enum value TargetTypeTrackedCluster = "TRACKED_CLUSTER" ) + +// TargetType_Values returns all elements of the TargetType enum +func TargetType_Values() []string { + return []string{ + TargetTypeRdsInstance, + TargetTypeRdsServerlessEndpoint, + TargetTypeTrackedCluster, + } +} + +const ( + // WriteForwardingStatusEnabled is a WriteForwardingStatus enum value + WriteForwardingStatusEnabled = "enabled" + + // WriteForwardingStatusDisabled is a WriteForwardingStatus enum value + WriteForwardingStatusDisabled = "disabled" + + // WriteForwardingStatusEnabling is a WriteForwardingStatus enum value + WriteForwardingStatusEnabling = "enabling" + + // WriteForwardingStatusDisabling is a WriteForwardingStatus enum value + WriteForwardingStatusDisabling = "disabling" + + // WriteForwardingStatusUnknown is a WriteForwardingStatus enum value + WriteForwardingStatusUnknown = "unknown" +) + +// WriteForwardingStatus_Values returns all elements of the WriteForwardingStatus enum +func WriteForwardingStatus_Values() []string { + return []string{ + WriteForwardingStatusEnabled, + WriteForwardingStatusDisabled, + WriteForwardingStatusEnabling, + WriteForwardingStatusDisabling, + WriteForwardingStatusUnknown, + } +} 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 a2985aeb536..d8b2573da17 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 @@ -24830,6 +24830,15 @@ const ( ActionTypeResizeCluster = "resize-cluster" ) +// ActionType_Values returns all elements of the ActionType enum +func ActionType_Values() []string { + return []string{ + ActionTypeRestoreCluster, + ActionTypeRecommendNodeConfig, + ActionTypeResizeCluster, + } +} + const ( // ModeStandard is a Mode enum value ModeStandard = "standard" @@ -24838,6 +24847,14 @@ const ( ModeHighPerformance = "high-performance" ) +// Mode_Values returns all elements of the Mode enum +func Mode_Values() []string { + return []string{ + ModeStandard, + ModeHighPerformance, + } +} + const ( // NodeConfigurationOptionsFilterNameNodeType is a NodeConfigurationOptionsFilterName enum value NodeConfigurationOptionsFilterNameNodeType = "NodeType" @@ -24852,6 +24869,16 @@ const ( NodeConfigurationOptionsFilterNameMode = "Mode" ) +// NodeConfigurationOptionsFilterName_Values returns all elements of the NodeConfigurationOptionsFilterName enum +func NodeConfigurationOptionsFilterName_Values() []string { + return []string{ + NodeConfigurationOptionsFilterNameNodeType, + NodeConfigurationOptionsFilterNameNumberOfNodes, + NodeConfigurationOptionsFilterNameEstimatedDiskUtilizationPercent, + NodeConfigurationOptionsFilterNameMode, + } +} + const ( // OperatorTypeEq is a OperatorType enum value OperatorTypeEq = "eq" @@ -24875,6 +24902,19 @@ const ( OperatorTypeBetween = "between" ) +// OperatorType_Values returns all elements of the OperatorType enum +func OperatorType_Values() []string { + return []string{ + OperatorTypeEq, + OperatorTypeLt, + OperatorTypeGt, + OperatorTypeLe, + OperatorTypeGe, + OperatorTypeIn, + OperatorTypeBetween, + } +} + const ( // ParameterApplyTypeStatic is a ParameterApplyType enum value ParameterApplyTypeStatic = "static" @@ -24883,6 +24923,14 @@ const ( ParameterApplyTypeDynamic = "dynamic" ) +// ParameterApplyType_Values returns all elements of the ParameterApplyType enum +func ParameterApplyType_Values() []string { + return []string{ + ParameterApplyTypeStatic, + ParameterApplyTypeDynamic, + } +} + const ( // ReservedNodeOfferingTypeRegular is a ReservedNodeOfferingType enum value ReservedNodeOfferingTypeRegular = "Regular" @@ -24891,6 +24939,14 @@ const ( ReservedNodeOfferingTypeUpgradable = "Upgradable" ) +// ReservedNodeOfferingType_Values returns all elements of the ReservedNodeOfferingType enum +func ReservedNodeOfferingType_Values() []string { + return []string{ + ReservedNodeOfferingTypeRegular, + ReservedNodeOfferingTypeUpgradable, + } +} + const ( // ScheduleStateModifying is a ScheduleState enum value ScheduleStateModifying = "MODIFYING" @@ -24902,6 +24958,15 @@ const ( ScheduleStateFailed = "FAILED" ) +// ScheduleState_Values returns all elements of the ScheduleState enum +func ScheduleState_Values() []string { + return []string{ + ScheduleStateModifying, + ScheduleStateActive, + ScheduleStateFailed, + } +} + const ( // ScheduledActionFilterNameClusterIdentifier is a ScheduledActionFilterName enum value ScheduledActionFilterNameClusterIdentifier = "cluster-identifier" @@ -24910,6 +24975,14 @@ const ( ScheduledActionFilterNameIamRole = "iam-role" ) +// ScheduledActionFilterName_Values returns all elements of the ScheduledActionFilterName enum +func ScheduledActionFilterName_Values() []string { + return []string{ + ScheduledActionFilterNameClusterIdentifier, + ScheduledActionFilterNameIamRole, + } +} + const ( // ScheduledActionStateActive is a ScheduledActionState enum value ScheduledActionStateActive = "ACTIVE" @@ -24918,6 +24991,14 @@ const ( ScheduledActionStateDisabled = "DISABLED" ) +// ScheduledActionState_Values returns all elements of the ScheduledActionState enum +func ScheduledActionState_Values() []string { + return []string{ + ScheduledActionStateActive, + ScheduledActionStateDisabled, + } +} + const ( // ScheduledActionTypeValuesResizeCluster is a ScheduledActionTypeValues enum value ScheduledActionTypeValuesResizeCluster = "ResizeCluster" @@ -24929,6 +25010,15 @@ const ( ScheduledActionTypeValuesResumeCluster = "ResumeCluster" ) +// ScheduledActionTypeValues_Values returns all elements of the ScheduledActionTypeValues enum +func ScheduledActionTypeValues_Values() []string { + return []string{ + ScheduledActionTypeValuesResizeCluster, + ScheduledActionTypeValuesPauseCluster, + ScheduledActionTypeValuesResumeCluster, + } +} + const ( // SnapshotAttributeToSortBySourceType is a SnapshotAttributeToSortBy enum value SnapshotAttributeToSortBySourceType = "SOURCE_TYPE" @@ -24940,6 +25030,15 @@ const ( SnapshotAttributeToSortByCreateTime = "CREATE_TIME" ) +// SnapshotAttributeToSortBy_Values returns all elements of the SnapshotAttributeToSortBy enum +func SnapshotAttributeToSortBy_Values() []string { + return []string{ + SnapshotAttributeToSortBySourceType, + SnapshotAttributeToSortByTotalSize, + SnapshotAttributeToSortByCreateTime, + } +} + const ( // SortByOrderAsc is a SortByOrder enum value SortByOrderAsc = "ASC" @@ -24948,6 +25047,14 @@ const ( SortByOrderDesc = "DESC" ) +// SortByOrder_Values returns all elements of the SortByOrder enum +func SortByOrder_Values() []string { + return []string{ + SortByOrderAsc, + SortByOrderDesc, + } +} + const ( // SourceTypeCluster is a SourceType enum value SourceTypeCluster = "cluster" @@ -24965,6 +25072,17 @@ const ( SourceTypeScheduledAction = "scheduled-action" ) +// SourceType_Values returns all elements of the SourceType enum +func SourceType_Values() []string { + return []string{ + SourceTypeCluster, + SourceTypeClusterParameterGroup, + SourceTypeClusterSecurityGroup, + SourceTypeClusterSnapshot, + SourceTypeScheduledAction, + } +} + const ( // TableRestoreStatusTypePending is a TableRestoreStatusType enum value TableRestoreStatusTypePending = "PENDING" @@ -24982,6 +25100,17 @@ const ( TableRestoreStatusTypeCanceled = "CANCELED" ) +// TableRestoreStatusType_Values returns all elements of the TableRestoreStatusType enum +func TableRestoreStatusType_Values() []string { + return []string{ + TableRestoreStatusTypePending, + TableRestoreStatusTypeInProgress, + TableRestoreStatusTypeSucceeded, + TableRestoreStatusTypeFailed, + TableRestoreStatusTypeCanceled, + } +} + const ( // UsageLimitBreachActionLog is a UsageLimitBreachAction enum value UsageLimitBreachActionLog = "log" @@ -24993,6 +25122,15 @@ const ( UsageLimitBreachActionDisable = "disable" ) +// UsageLimitBreachAction_Values returns all elements of the UsageLimitBreachAction enum +func UsageLimitBreachAction_Values() []string { + return []string{ + UsageLimitBreachActionLog, + UsageLimitBreachActionEmitMetric, + UsageLimitBreachActionDisable, + } +} + const ( // UsageLimitFeatureTypeSpectrum is a UsageLimitFeatureType enum value UsageLimitFeatureTypeSpectrum = "spectrum" @@ -25001,6 +25139,14 @@ const ( UsageLimitFeatureTypeConcurrencyScaling = "concurrency-scaling" ) +// UsageLimitFeatureType_Values returns all elements of the UsageLimitFeatureType enum +func UsageLimitFeatureType_Values() []string { + return []string{ + UsageLimitFeatureTypeSpectrum, + UsageLimitFeatureTypeConcurrencyScaling, + } +} + const ( // UsageLimitLimitTypeTime is a UsageLimitLimitType enum value UsageLimitLimitTypeTime = "time" @@ -25009,6 +25155,14 @@ const ( UsageLimitLimitTypeDataScanned = "data-scanned" ) +// UsageLimitLimitType_Values returns all elements of the UsageLimitLimitType enum +func UsageLimitLimitType_Values() []string { + return []string{ + UsageLimitLimitTypeTime, + UsageLimitLimitTypeDataScanned, + } +} + const ( // UsageLimitPeriodDaily is a UsageLimitPeriod enum value UsageLimitPeriodDaily = "daily" @@ -25019,3 +25173,12 @@ const ( // UsageLimitPeriodMonthly is a UsageLimitPeriod enum value UsageLimitPeriodMonthly = "monthly" ) + +// UsageLimitPeriod_Values returns all elements of the UsageLimitPeriod enum +func UsageLimitPeriod_Values() []string { + return []string{ + UsageLimitPeriodDaily, + UsageLimitPeriodWeekly, + UsageLimitPeriodMonthly, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/resourcegroups/api.go b/vendor/github.com/aws/aws-sdk-go/service/resourcegroups/api.go index c339a2c8eec..04b31538c24 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/resourcegroups/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/resourcegroups/api.go @@ -55,7 +55,8 @@ func (c *ResourceGroups) CreateGroupRequest(input *CreateGroupInput) (req *reque // CreateGroup API operation for AWS Resource Groups. // -// Creates a group with a specified name, description, and resource query. +// Creates a resource group with the specified name and description. You can +// optionally include a resource query, or a service configuration. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -66,20 +67,20 @@ func (c *ResourceGroups) CreateGroupRequest(input *CreateGroupInput) (req *reque // // Returned Error Types: // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/CreateGroup func (c *ResourceGroups) CreateGroup(input *CreateGroupInput) (*CreateGroupOutput, error) { @@ -132,8 +133,8 @@ const opDeleteGroup = "DeleteGroup" func (c *ResourceGroups) DeleteGroupRequest(input *DeleteGroupInput) (req *request.Request, output *DeleteGroupOutput) { op := &request.Operation{ Name: opDeleteGroup, - HTTPMethod: "DELETE", - HTTPPath: "/groups/{GroupName}", + HTTPMethod: "POST", + HTTPPath: "/delete-group", } if input == nil { @@ -147,8 +148,9 @@ func (c *ResourceGroups) DeleteGroupRequest(input *DeleteGroupInput) (req *reque // DeleteGroup API operation for AWS Resource Groups. // -// Deletes a specified resource group. Deleting a resource group does not delete -// resources that are members of the group; it only deletes the group structure. +// Deletes the specified resource group. Deleting a resource group does not +// delete any resources that are members of the group; it only deletes the group +// structure. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -159,23 +161,23 @@ func (c *ResourceGroups) DeleteGroupRequest(input *DeleteGroupInput) (req *reque // // Returned Error Types: // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * NotFoundException -// One or more resources specified in the request do not exist. +// One or more of the specified resources don't exist. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/DeleteGroup func (c *ResourceGroups) DeleteGroup(input *DeleteGroupInput) (*DeleteGroupOutput, error) { @@ -228,8 +230,8 @@ const opGetGroup = "GetGroup" func (c *ResourceGroups) GetGroupRequest(input *GetGroupInput) (req *request.Request, output *GetGroupOutput) { op := &request.Operation{ Name: opGetGroup, - HTTPMethod: "GET", - HTTPPath: "/groups/{GroupName}", + HTTPMethod: "POST", + HTTPPath: "/get-group", } if input == nil { @@ -254,23 +256,23 @@ func (c *ResourceGroups) GetGroupRequest(input *GetGroupInput) (req *request.Req // // Returned Error Types: // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * NotFoundException -// One or more resources specified in the request do not exist. +// One or more of the specified resources don't exist. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/GetGroup func (c *ResourceGroups) GetGroup(input *GetGroupInput) (*GetGroupOutput, error) { @@ -294,6 +296,108 @@ func (c *ResourceGroups) GetGroupWithContext(ctx aws.Context, input *GetGroupInp return out, req.Send() } +const opGetGroupConfiguration = "GetGroupConfiguration" + +// GetGroupConfigurationRequest generates a "aws/request.Request" representing the +// client's request for the GetGroupConfiguration operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetGroupConfiguration for more information on using the GetGroupConfiguration +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetGroupConfigurationRequest method. +// req, resp := client.GetGroupConfigurationRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/GetGroupConfiguration +func (c *ResourceGroups) GetGroupConfigurationRequest(input *GetGroupConfigurationInput) (req *request.Request, output *GetGroupConfigurationOutput) { + op := &request.Operation{ + Name: opGetGroupConfiguration, + HTTPMethod: "POST", + HTTPPath: "/get-group-configuration", + } + + if input == nil { + input = &GetGroupConfigurationInput{} + } + + output = &GetGroupConfigurationOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetGroupConfiguration API operation for AWS Resource Groups. +// +// Returns the service configuration associated with the specified resource +// group. AWS Resource Groups supports configurations for the following resource +// group types: +// +// * AWS::EC2::CapacityReservationPool - Amazon EC2 capacity reservation +// pools. For more information, see Working with capacity reservation groups +// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-using.html#create-cr-group) +// in the EC2 Users 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 AWS Resource Groups's +// API operation GetGroupConfiguration for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request includes one or more parameters that violate validation rules. +// +// * ForbiddenException +// The caller isn't authorized to make the request. Check permissions. +// +// * NotFoundException +// One or more of the specified resources don't exist. +// +// * MethodNotAllowedException +// The request uses an HTTP method that isn't allowed for the specified resource. +// +// * TooManyRequestsException +// You've exceeded throttling limits by making too many requests in a period +// of time. +// +// * InternalServerErrorException +// An internal error occurred while processing the request. Try again later. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/GetGroupConfiguration +func (c *ResourceGroups) GetGroupConfiguration(input *GetGroupConfigurationInput) (*GetGroupConfigurationOutput, error) { + req, out := c.GetGroupConfigurationRequest(input) + return out, req.Send() +} + +// GetGroupConfigurationWithContext is the same as GetGroupConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetGroupConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroups) GetGroupConfigurationWithContext(ctx aws.Context, input *GetGroupConfigurationInput, opts ...request.Option) (*GetGroupConfigurationOutput, error) { + req, out := c.GetGroupConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetGroupQuery = "GetGroupQuery" // GetGroupQueryRequest generates a "aws/request.Request" representing the @@ -323,8 +427,8 @@ const opGetGroupQuery = "GetGroupQuery" func (c *ResourceGroups) GetGroupQueryRequest(input *GetGroupQueryInput) (req *request.Request, output *GetGroupQueryOutput) { op := &request.Operation{ Name: opGetGroupQuery, - HTTPMethod: "GET", - HTTPPath: "/groups/{GroupName}/query", + HTTPMethod: "POST", + HTTPPath: "/get-group-query", } if input == nil { @@ -338,7 +442,7 @@ func (c *ResourceGroups) GetGroupQueryRequest(input *GetGroupQueryInput) (req *r // GetGroupQuery API operation for AWS Resource Groups. // -// Returns the resource query associated with the specified resource group. +// Retrieves the resource query associated with the specified resource group. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -349,23 +453,23 @@ func (c *ResourceGroups) GetGroupQueryRequest(input *GetGroupQueryInput) (req *r // // Returned Error Types: // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * NotFoundException -// One or more resources specified in the request do not exist. +// One or more of the specified resources don't exist. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/GetGroupQuery func (c *ResourceGroups) GetGroupQuery(input *GetGroupQueryInput) (*GetGroupQueryOutput, error) { @@ -445,23 +549,23 @@ func (c *ResourceGroups) GetTagsRequest(input *GetTagsInput) (req *request.Reque // // Returned Error Types: // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * NotFoundException -// One or more resources specified in the request do not exist. +// One or more of the specified resources don't exist. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/GetTags func (c *ResourceGroups) GetTags(input *GetTagsInput) (*GetTagsOutput, error) { @@ -485,6 +589,101 @@ func (c *ResourceGroups) GetTagsWithContext(ctx aws.Context, input *GetTagsInput return out, req.Send() } +const opGroupResources = "GroupResources" + +// GroupResourcesRequest generates a "aws/request.Request" representing the +// client's request for the GroupResources operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GroupResources for more information on using the GroupResources +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GroupResourcesRequest method. +// req, resp := client.GroupResourcesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/GroupResources +func (c *ResourceGroups) GroupResourcesRequest(input *GroupResourcesInput) (req *request.Request, output *GroupResourcesOutput) { + op := &request.Operation{ + Name: opGroupResources, + HTTPMethod: "POST", + HTTPPath: "/group-resources", + } + + if input == nil { + input = &GroupResourcesInput{} + } + + output = &GroupResourcesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GroupResources API operation for AWS Resource Groups. +// +// Adds the specified resources to the specified group. +// +// Returns awserr.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 Resource Groups's +// API operation GroupResources for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request includes one or more parameters that violate validation rules. +// +// * ForbiddenException +// The caller isn't authorized to make the request. Check permissions. +// +// * NotFoundException +// One or more of the specified resources don't exist. +// +// * MethodNotAllowedException +// The request uses an HTTP method that isn't allowed for the specified resource. +// +// * TooManyRequestsException +// You've exceeded throttling limits by making too many requests in a period +// of time. +// +// * InternalServerErrorException +// An internal error occurred while processing the request. Try again later. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/GroupResources +func (c *ResourceGroups) GroupResources(input *GroupResourcesInput) (*GroupResourcesOutput, error) { + req, out := c.GroupResourcesRequest(input) + return out, req.Send() +} + +// GroupResourcesWithContext is the same as GroupResources with the addition of +// the ability to pass a context and additional request options. +// +// See GroupResources for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroups) GroupResourcesWithContext(ctx aws.Context, input *GroupResourcesInput, opts ...request.Option) (*GroupResourcesOutput, error) { + req, out := c.GroupResourcesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opListGroupResources = "ListGroupResources" // ListGroupResourcesRequest generates a "aws/request.Request" representing the @@ -515,7 +714,7 @@ func (c *ResourceGroups) ListGroupResourcesRequest(input *ListGroupResourcesInpu op := &request.Operation{ Name: opListGroupResources, HTTPMethod: "POST", - HTTPPath: "/groups/{GroupName}/resource-identifiers-list", + HTTPPath: "/list-group-resources", Paginator: &request.Paginator{ InputTokens: []string{"NextToken"}, OutputTokens: []string{"NextToken"}, @@ -535,7 +734,7 @@ func (c *ResourceGroups) ListGroupResourcesRequest(input *ListGroupResourcesInpu // ListGroupResources API operation for AWS Resource Groups. // -// Returns a list of ARNs of resources that are members of a specified resource +// Returns a list of ARNs of the resources that are members of a specified resource // group. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -547,27 +746,27 @@ func (c *ResourceGroups) ListGroupResourcesRequest(input *ListGroupResourcesInpu // // Returned Error Types: // * UnauthorizedException -// The request has not been applied because it lacks valid authentication credentials -// for the target resource. +// The request was rejected because it doesn't have valid credentials for the +// target resource. // // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * NotFoundException -// One or more resources specified in the request do not exist. +// One or more of the specified resources don't exist. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/ListGroupResources func (c *ResourceGroups) ListGroupResources(input *ListGroupResourcesInput) (*ListGroupResourcesOutput, error) { @@ -704,20 +903,20 @@ func (c *ResourceGroups) ListGroupsRequest(input *ListGroupsInput) (req *request // // Returned Error Types: // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/ListGroups func (c *ResourceGroups) ListGroups(input *ListGroupsInput) (*ListGroupsOutput, error) { @@ -843,7 +1042,7 @@ func (c *ResourceGroups) SearchResourcesRequest(input *SearchResourcesInput) (re // SearchResources API operation for AWS Resource Groups. // -// Returns a list of AWS resource identifiers that matches a specified query. +// Returns a list of AWS resource identifiers that matches tne specified query. // The query uses the same format as a resource query in a CreateGroup or UpdateGroupQuery // operation. // @@ -856,24 +1055,24 @@ func (c *ResourceGroups) SearchResourcesRequest(input *SearchResourcesInput) (re // // Returned Error Types: // * UnauthorizedException -// The request has not been applied because it lacks valid authentication credentials -// for the target resource. +// The request was rejected because it doesn't have valid credentials for the +// target resource. // // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/SearchResources func (c *ResourceGroups) SearchResources(input *SearchResourcesInput) (*SearchResourcesOutput, error) { @@ -996,6 +1195,11 @@ func (c *ResourceGroups) TagRequest(input *TagInput) (req *request.Request, outp // Adds tags to a resource group with the specified ARN. Existing tags on a // resource group are not changed if they are not specified in the request parameters. // +// Do not store personally identifiable information (PII) or other confidential +// or sensitive information in tags. We use tags to provide you with billing +// and administration services. Tags are not intended to be used for private +// or sensitive data. +// // Returns awserr.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. @@ -1005,23 +1209,23 @@ func (c *ResourceGroups) TagRequest(input *TagInput) (req *request.Request, outp // // Returned Error Types: // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * NotFoundException -// One or more resources specified in the request do not exist. +// One or more of the specified resources don't exist. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/Tag func (c *ResourceGroups) Tag(input *TagInput) (*TagOutput, error) { @@ -1045,6 +1249,101 @@ func (c *ResourceGroups) TagWithContext(ctx aws.Context, input *TagInput, opts . return out, req.Send() } +const opUngroupResources = "UngroupResources" + +// UngroupResourcesRequest generates a "aws/request.Request" representing the +// client's request for the UngroupResources operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UngroupResources for more information on using the UngroupResources +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UngroupResourcesRequest method. +// req, resp := client.UngroupResourcesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/UngroupResources +func (c *ResourceGroups) UngroupResourcesRequest(input *UngroupResourcesInput) (req *request.Request, output *UngroupResourcesOutput) { + op := &request.Operation{ + Name: opUngroupResources, + HTTPMethod: "POST", + HTTPPath: "/ungroup-resources", + } + + if input == nil { + input = &UngroupResourcesInput{} + } + + output = &UngroupResourcesOutput{} + req = c.newRequest(op, input, output) + return +} + +// UngroupResources API operation for AWS Resource Groups. +// +// Removes the specified resources from the specified group. +// +// Returns awserr.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 Resource Groups's +// API operation UngroupResources for usage and error information. +// +// Returned Error Types: +// * BadRequestException +// The request includes one or more parameters that violate validation rules. +// +// * ForbiddenException +// The caller isn't authorized to make the request. Check permissions. +// +// * NotFoundException +// One or more of the specified resources don't exist. +// +// * MethodNotAllowedException +// The request uses an HTTP method that isn't allowed for the specified resource. +// +// * TooManyRequestsException +// You've exceeded throttling limits by making too many requests in a period +// of time. +// +// * InternalServerErrorException +// An internal error occurred while processing the request. Try again later. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/UngroupResources +func (c *ResourceGroups) UngroupResources(input *UngroupResourcesInput) (*UngroupResourcesOutput, error) { + req, out := c.UngroupResourcesRequest(input) + return out, req.Send() +} + +// UngroupResourcesWithContext is the same as UngroupResources with the addition of +// the ability to pass a context and additional request options. +// +// See UngroupResources for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroups) UngroupResourcesWithContext(ctx aws.Context, input *UngroupResourcesInput, opts ...request.Option) (*UngroupResourcesOutput, error) { + req, out := c.UngroupResourcesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opUntag = "Untag" // UntagRequest generates a "aws/request.Request" representing the @@ -1089,7 +1388,7 @@ func (c *ResourceGroups) UntagRequest(input *UntagInput) (req *request.Request, // Untag API operation for AWS Resource Groups. // -// Deletes specified tags from a specified resource. +// Deletes tags from a specified resource group. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1100,23 +1399,23 @@ func (c *ResourceGroups) UntagRequest(input *UntagInput) (req *request.Request, // // Returned Error Types: // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * NotFoundException -// One or more resources specified in the request do not exist. +// One or more of the specified resources don't exist. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/Untag func (c *ResourceGroups) Untag(input *UntagInput) (*UntagOutput, error) { @@ -1169,8 +1468,8 @@ const opUpdateGroup = "UpdateGroup" func (c *ResourceGroups) UpdateGroupRequest(input *UpdateGroupInput) (req *request.Request, output *UpdateGroupOutput) { op := &request.Operation{ Name: opUpdateGroup, - HTTPMethod: "PUT", - HTTPPath: "/groups/{GroupName}", + HTTPMethod: "POST", + HTTPPath: "/update-group", } if input == nil { @@ -1184,8 +1483,8 @@ func (c *ResourceGroups) UpdateGroupRequest(input *UpdateGroupInput) (req *reque // UpdateGroup API operation for AWS Resource Groups. // -// Updates an existing group with a new or changed description. You cannot update -// the name of a resource group. +// Updates the description for an existing group. You cannot update the name +// of a resource group. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1196,23 +1495,23 @@ func (c *ResourceGroups) UpdateGroupRequest(input *UpdateGroupInput) (req *reque // // Returned Error Types: // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * NotFoundException -// One or more resources specified in the request do not exist. +// One or more of the specified resources don't exist. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/UpdateGroup func (c *ResourceGroups) UpdateGroup(input *UpdateGroupInput) (*UpdateGroupOutput, error) { @@ -1265,8 +1564,8 @@ const opUpdateGroupQuery = "UpdateGroupQuery" func (c *ResourceGroups) UpdateGroupQueryRequest(input *UpdateGroupQueryInput) (req *request.Request, output *UpdateGroupQueryOutput) { op := &request.Operation{ Name: opUpdateGroupQuery, - HTTPMethod: "PUT", - HTTPPath: "/groups/{GroupName}/query", + HTTPMethod: "POST", + HTTPPath: "/update-group-query", } if input == nil { @@ -1291,23 +1590,23 @@ func (c *ResourceGroups) UpdateGroupQueryRequest(input *UpdateGroupQueryInput) ( // // Returned Error Types: // * BadRequestException -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. // // * ForbiddenException -// The caller is not authorized to make the request. +// The caller isn't authorized to make the request. Check permissions. // // * NotFoundException -// One or more resources specified in the request do not exist. +// One or more of the specified resources don't exist. // // * MethodNotAllowedException -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. // // * TooManyRequestsException -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. // // * InternalServerErrorException -// An internal error occurred while processing the request. +// An internal error occurred while processing the request. Try again later. // // See also, https://docs.aws.amazon.com/goto/WebAPI/resource-groups-2017-11-27/UpdateGroupQuery func (c *ResourceGroups) UpdateGroupQuery(input *UpdateGroupQueryInput) (*UpdateGroupQueryOutput, error) { @@ -1331,8 +1630,7 @@ func (c *ResourceGroups) UpdateGroupQueryWithContext(ctx aws.Context, input *Upd return out, req.Send() } -// The request does not comply with validation rules that are defined for the -// request parameters. +// The request includes one or more parameters that violate validation rules. type BadRequestException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -1391,16 +1689,23 @@ func (s *BadRequestException) RequestID() string { type CreateGroupInput struct { _ struct{} `type:"structure"` - // The description of the resource group. Descriptions can have a maximum of - // 511 characters, including letters, numbers, hyphens, underscores, punctuation, - // and spaces. + // A configuration associates the resource group with an AWS service and specifies + // how the service can interact with the resources in the group. A configuration + // is an array of GroupConfigurationItem elements. + // + // You can specify either a Configuration or a ResourceQuery in a group, but + // not both. + Configuration []*GroupConfigurationItem `type:"list"` + + // The description of the resource group. Descriptions can consist of letters, + // numbers, hyphens, underscores, periods, and spaces. Description *string `type:"string"` // The name of the group, which is the identifier of the group in other operations. - // A resource group name cannot be updated after it is created. A resource group - // name can have a maximum of 128 characters, including letters, numbers, hyphens, - // dots, and underscores. The name cannot start with AWS or aws; these are reserved. - // A resource group name must be unique within your account. + // You can't change the name of a resource group after you create it. A resource + // group name can consist of letters, numbers, hyphens, periods, and underscores. + // The name cannot start with AWS or aws; these are reserved. A resource group + // name must be unique within each AWS Region in your AWS account. // // Name is a required field Name *string `min:"1" type:"string" required:"true"` @@ -1408,12 +1713,10 @@ type CreateGroupInput struct { // The resource query that determines which AWS resources are members of this // group. // - // ResourceQuery is a required field - ResourceQuery *ResourceQuery `type:"structure" required:"true"` + // You can specify either a ResourceQuery or a Configuration, but not both. + ResourceQuery *ResourceQuery `type:"structure"` - // The tags to add to the group. A tag is a string-to-string map of key-value - // pairs. Tag keys can have a maximum character length of 128 characters, and - // tag values can have a maximum length of 256 characters. + // The tags to add to the group. A tag is key-value pair string. Tags map[string]*string `type:"map"` } @@ -1436,8 +1739,15 @@ func (s *CreateGroupInput) Validate() error { if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } - if s.ResourceQuery == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceQuery")) + if s.Configuration != nil { + for i, v := range s.Configuration { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Configuration", i), err.(request.ErrInvalidParams)) + } + } } if s.ResourceQuery != nil { if err := s.ResourceQuery.Validate(); err != nil { @@ -1451,6 +1761,12 @@ func (s *CreateGroupInput) Validate() error { return nil } +// SetConfiguration sets the Configuration field's value. +func (s *CreateGroupInput) SetConfiguration(v []*GroupConfigurationItem) *CreateGroupInput { + s.Configuration = v + return s +} + // SetDescription sets the Description field's value. func (s *CreateGroupInput) SetDescription(v string) *CreateGroupInput { s.Description = &v @@ -1478,9 +1794,19 @@ func (s *CreateGroupInput) SetTags(v map[string]*string) *CreateGroupInput { type CreateGroupOutput struct { _ struct{} `type:"structure"` - // A full description of the resource group after it is created. + // The description of the resource group. Group *Group `type:"structure"` + // The service configuration associated with the resource group. AWS Resource + // Groups supports adding service configurations for the following resource + // group types: + // + // * AWS::EC2::CapacityReservationPool - Amazon EC2 capacity reservation + // pools. For more information, see Working with capacity reservation groups + // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-using.html#create-cr-group) + // in the EC2 Users Guide. + GroupConfiguration *GroupConfiguration `type:"structure"` + // The resource query associated with the group. ResourceQuery *ResourceQuery `type:"structure"` @@ -1504,6 +1830,12 @@ func (s *CreateGroupOutput) SetGroup(v *Group) *CreateGroupOutput { return s } +// SetGroupConfiguration sets the GroupConfiguration field's value. +func (s *CreateGroupOutput) SetGroupConfiguration(v *GroupConfiguration) *CreateGroupOutput { + s.GroupConfiguration = v + return s +} + // SetResourceQuery sets the ResourceQuery field's value. func (s *CreateGroupOutput) SetResourceQuery(v *ResourceQuery) *CreateGroupOutput { s.ResourceQuery = v @@ -1519,10 +1851,13 @@ func (s *CreateGroupOutput) SetTags(v map[string]*string) *CreateGroupOutput { type DeleteGroupInput struct { _ struct{} `type:"structure"` - // The name of the resource group to delete. + // The name or the ARN of the resource group to delete. + Group *string `min:"1" type:"string"` + + // Don't use this parameter. Use Group instead. // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + // Deprecated: This field is deprecated, use Group instead. + GroupName *string `min:"1" deprecated:"true" type:"string"` } // String returns the string representation @@ -1538,8 +1873,8 @@ func (s DeleteGroupInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteGroupInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "DeleteGroupInput"} - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) + if s.Group != nil && len(*s.Group) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Group", 1)) } if s.GroupName != nil && len(*s.GroupName) < 1 { invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) @@ -1551,6 +1886,12 @@ func (s *DeleteGroupInput) Validate() error { return nil } +// SetGroup sets the Group field's value. +func (s *DeleteGroupInput) SetGroup(v string) *DeleteGroupInput { + s.Group = &v + return s +} + // SetGroupName sets the GroupName field's value. func (s *DeleteGroupInput) SetGroupName(v string) *DeleteGroupInput { s.GroupName = &v @@ -1580,32 +1921,74 @@ func (s *DeleteGroupOutput) SetGroup(v *Group) *DeleteGroupOutput { return s } -// The caller is not authorized to make the request. -type ForbiddenException struct { - _ struct{} `type:"structure"` - RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` +// A resource that failed to be added to or removed from a group. +type FailedResource struct { + _ struct{} `type:"structure"` - Message_ *string `locationName:"Message" min:"1" type:"string"` + // The error code associated with the failure. + ErrorCode *string `min:"1" type:"string"` + + // The error message text associated with the failure. + ErrorMessage *string `min:"1" type:"string"` + + // The ARN of the resource that failed to be added or removed. + ResourceArn *string `type:"string"` } // String returns the string representation -func (s ForbiddenException) String() string { +func (s FailedResource) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s ForbiddenException) GoString() string { +func (s FailedResource) GoString() string { return s.String() } -func newErrorForbiddenException(v protocol.ResponseMetadata) error { - return &ForbiddenException{ - RespMetadata: v, - } +// SetErrorCode sets the ErrorCode field's value. +func (s *FailedResource) SetErrorCode(v string) *FailedResource { + s.ErrorCode = &v + return s } -// Code returns the exception type name. -func (s *ForbiddenException) Code() string { +// SetErrorMessage sets the ErrorMessage field's value. +func (s *FailedResource) SetErrorMessage(v string) *FailedResource { + s.ErrorMessage = &v + return s +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *FailedResource) SetResourceArn(v string) *FailedResource { + s.ResourceArn = &v + return s +} + +// The caller isn't authorized to make the request. Check permissions. +type ForbiddenException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" min:"1" type:"string"` +} + +// String returns the string representation +func (s ForbiddenException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ForbiddenException) GoString() string { + return s.String() +} + +func newErrorForbiddenException(v protocol.ResponseMetadata) error { + return &ForbiddenException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ForbiddenException) Code() string { return "ForbiddenException" } @@ -1636,13 +2019,75 @@ func (s *ForbiddenException) RequestID() string { return s.RespMetadata.RequestID } +type GetGroupConfigurationInput struct { + _ struct{} `type:"structure"` + + // The name or the ARN of the resource group. + Group *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s GetGroupConfigurationInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetGroupConfigurationInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetGroupConfigurationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetGroupConfigurationInput"} + if s.Group != nil && len(*s.Group) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Group", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGroup sets the Group field's value. +func (s *GetGroupConfigurationInput) SetGroup(v string) *GetGroupConfigurationInput { + s.Group = &v + return s +} + +type GetGroupConfigurationOutput struct { + _ struct{} `type:"structure"` + + // The configuration associated with the specified group. + GroupConfiguration *GroupConfiguration `type:"structure"` +} + +// String returns the string representation +func (s GetGroupConfigurationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetGroupConfigurationOutput) GoString() string { + return s.String() +} + +// SetGroupConfiguration sets the GroupConfiguration field's value. +func (s *GetGroupConfigurationOutput) SetGroupConfiguration(v *GroupConfiguration) *GetGroupConfigurationOutput { + s.GroupConfiguration = v + return s +} + type GetGroupInput struct { _ struct{} `type:"structure"` - // The name of the resource group. + // The name or the ARN of the resource group to retrieve. + Group *string `min:"1" type:"string"` + + // Don't use this parameter. Use Group instead. // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + // Deprecated: This field is deprecated, use Group instead. + GroupName *string `min:"1" deprecated:"true" type:"string"` } // String returns the string representation @@ -1658,8 +2103,8 @@ func (s GetGroupInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *GetGroupInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "GetGroupInput"} - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) + if s.Group != nil && len(*s.Group) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Group", 1)) } if s.GroupName != nil && len(*s.GroupName) < 1 { invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) @@ -1671,6 +2116,12 @@ func (s *GetGroupInput) Validate() error { return nil } +// SetGroup sets the Group field's value. +func (s *GetGroupInput) SetGroup(v string) *GetGroupInput { + s.Group = &v + return s +} + // SetGroupName sets the GroupName field's value. func (s *GetGroupInput) SetGroupName(v string) *GetGroupInput { s.GroupName = &v @@ -1703,10 +2154,13 @@ func (s *GetGroupOutput) SetGroup(v *Group) *GetGroupOutput { type GetGroupQueryInput struct { _ struct{} `type:"structure"` - // The name of the resource group. + // The name or the ARN of the resource group to query. + Group *string `min:"1" type:"string"` + + // Don't use this parameter. Use Group instead. // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + // Deprecated: This field is deprecated, use Group instead. + GroupName *string `min:"1" deprecated:"true" type:"string"` } // String returns the string representation @@ -1722,8 +2176,8 @@ func (s GetGroupQueryInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *GetGroupQueryInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "GetGroupQueryInput"} - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) + if s.Group != nil && len(*s.Group) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Group", 1)) } if s.GroupName != nil && len(*s.GroupName) < 1 { invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) @@ -1735,6 +2189,12 @@ func (s *GetGroupQueryInput) Validate() error { return nil } +// SetGroup sets the Group field's value. +func (s *GetGroupQueryInput) SetGroup(v string) *GetGroupQueryInput { + s.Group = &v + return s +} + // SetGroupName sets the GroupName field's value. func (s *GetGroupQueryInput) SetGroupName(v string) *GetGroupQueryInput { s.GroupName = &v @@ -1767,8 +2227,7 @@ func (s *GetGroupQueryOutput) SetGroupQuery(v *GroupQuery) *GetGroupQueryOutput type GetTagsInput struct { _ struct{} `type:"structure"` - // The ARN of the resource group for which you want a list of tags. The resource - // must exist within the account you are using. + // The ARN of the resource group whose tags you want to retrieve. // // Arn is a required field Arn *string `location:"uri" locationName:"Arn" min:"12" type:"string" required:"true"` @@ -1838,19 +2297,29 @@ func (s *GetTagsOutput) SetTags(v map[string]*string) *GetTagsOutput { return s } -// A resource group. +// A resource group that contains AWS resources. You can assign resources to +// the group by associating either of the following elements with the group: +// +// * ResourceQuery - Use a resource query to specify a set of tag keys and +// values. All resources in the same AWS Region and AWS account that have +// those keys with the same values are included in the group. You can add +// a resource query when you create the group. +// +// * GroupConfiguration - Use a service configuration to associate the group +// with an AWS service. The configuration specifies which resource types +// can be included in the group. type Group struct { _ struct{} `type:"structure"` // The description of the resource group. Description *string `type:"string"` - // The ARN of a resource group. + // The ARN of the resource group. // // GroupArn is a required field GroupArn *string `min:"12" type:"string" required:"true"` - // The name of a resource group. + // The name of the resource group. // // Name is a required field Name *string `min:"1" type:"string" required:"true"` @@ -1884,8 +2353,200 @@ func (s *Group) SetName(v string) *Group { return s } -// A filter name and value pair that is used to obtain more specific results -// from a list of groups. +// A service configuration associated with a resource group. The configuration +// options are determined by the AWS service that defines the Type, and specifies +// which resources can be included in the group. You can add a service configuration +// when you create the group. +type GroupConfiguration struct { + _ struct{} `type:"structure"` + + // The configuration currently associated with the group and in effect. + Configuration []*GroupConfigurationItem `type:"list"` + + // If present, the reason why a request to update the group configuration failed. + FailureReason *string `type:"string"` + + // If present, the new configuration that is in the process of being applied + // to the group. + ProposedConfiguration []*GroupConfigurationItem `type:"list"` + + // The current status of an attempt to update the group configuration. + Status *string `type:"string" enum:"GroupConfigurationStatus"` +} + +// String returns the string representation +func (s GroupConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GroupConfiguration) GoString() string { + return s.String() +} + +// SetConfiguration sets the Configuration field's value. +func (s *GroupConfiguration) SetConfiguration(v []*GroupConfigurationItem) *GroupConfiguration { + s.Configuration = v + return s +} + +// SetFailureReason sets the FailureReason field's value. +func (s *GroupConfiguration) SetFailureReason(v string) *GroupConfiguration { + s.FailureReason = &v + return s +} + +// SetProposedConfiguration sets the ProposedConfiguration field's value. +func (s *GroupConfiguration) SetProposedConfiguration(v []*GroupConfigurationItem) *GroupConfiguration { + s.ProposedConfiguration = v + return s +} + +// SetStatus sets the Status field's value. +func (s *GroupConfiguration) SetStatus(v string) *GroupConfiguration { + s.Status = &v + return s +} + +// An item in a group configuration. A group configuration can have one or more +// items. +type GroupConfigurationItem struct { + _ struct{} `type:"structure"` + + // A collection of parameters for this group configuration item. + Parameters []*GroupConfigurationParameter `type:"list"` + + // Specifies the type of group configuration item. Each item must have a unique + // value for type. + // + // You can specify the following string values: + // + // * AWS::EC2::CapacityReservationPool For more information about EC2 capacity + // reservation groups, see Working with capacity reservation groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-using.html#create-cr-group) + // in the EC2 Users Guide. + // + // * AWS::ResourceGroups::Generic - Supports parameters that configure the + // behavior of resource groups of any type. + // + // Type is a required field + Type *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s GroupConfigurationItem) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GroupConfigurationItem) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GroupConfigurationItem) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GroupConfigurationItem"} + if s.Type == nil { + invalidParams.Add(request.NewErrParamRequired("Type")) + } + if s.Parameters != nil { + for i, v := range s.Parameters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Parameters", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetParameters sets the Parameters field's value. +func (s *GroupConfigurationItem) SetParameters(v []*GroupConfigurationParameter) *GroupConfigurationItem { + s.Parameters = v + return s +} + +// SetType sets the Type field's value. +func (s *GroupConfigurationItem) SetType(v string) *GroupConfigurationItem { + s.Type = &v + return s +} + +// A parameter for a group configuration item. +type GroupConfigurationParameter struct { + _ struct{} `type:"structure"` + + // The name of the group configuration parameter. + // + // You can specify the following string values: + // + // * For configuration item type AWS::ResourceGroups::Generic: allowed-resource-types + // Specifies the types of resources that you can add to this group by using + // the GroupResources operation. + // + // * For configuration item type AWS::EC2::CapacityReservationPool: None + // - This configuration item type doesn't support any parameters. For more + // information about EC2 capacity reservation groups, see Working with capacity + // reservation groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-using.html#create-cr-group) + // in the EC2 Users Guide. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // The values of for this parameter. + // + // You can specify the following string value: + // + // * For item type allowed-resource-types: the only supported parameter value + // is AWS::EC2::CapacityReservation. + Values []*string `type:"list"` +} + +// String returns the string representation +func (s GroupConfigurationParameter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GroupConfigurationParameter) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GroupConfigurationParameter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GroupConfigurationParameter"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *GroupConfigurationParameter) SetName(v string) *GroupConfigurationParameter { + s.Name = &v + return s +} + +// SetValues sets the Values field's value. +func (s *GroupConfigurationParameter) SetValues(v []*string) *GroupConfigurationParameter { + s.Values = v + return s +} + +// A filter collection that you can use to restrict the results from a List +// operation to only those you want to include. type GroupFilter struct { _ struct{} `type:"structure"` @@ -1942,14 +2603,14 @@ func (s *GroupFilter) SetValues(v []*string) *GroupFilter { return s } -// The ARN and group name of a group. +// The unique identifiers for a resource group. type GroupIdentifier struct { _ struct{} `type:"structure"` - // The ARN of a resource group. + // The ARN of the resource group. GroupArn *string `min:"12" type:"string"` - // The name of a resource group. + // The name of the resource group. GroupName *string `min:"1" type:"string"` } @@ -1975,18 +2636,18 @@ func (s *GroupIdentifier) SetGroupName(v string) *GroupIdentifier { return s } -// The underlying resource query of a resource group. Resources that match query -// results are part of the group. +// A mapping of a query attached to a resource group that determines the AWS +// resources that are members of the group. type GroupQuery struct { _ struct{} `type:"structure"` - // The name of a resource group that is associated with a specific resource + // The name of the resource group that is associated with the specified resource // query. // // GroupName is a required field GroupName *string `min:"1" type:"string" required:"true"` - // The resource query which determines which AWS resources are members of the + // The resource query that determines which AWS resources are members of the // associated resource group. // // ResourceQuery is a required field @@ -2015,7 +2676,98 @@ func (s *GroupQuery) SetResourceQuery(v *ResourceQuery) *GroupQuery { return s } -// An internal error occurred while processing the request. +type GroupResourcesInput struct { + _ struct{} `type:"structure"` + + // The name or the ARN of the resource group to add resources to. + // + // Group is a required field + Group *string `min:"1" type:"string" required:"true"` + + // The list of ARNs for resources to be added to the group. + // + // ResourceArns is a required field + ResourceArns []*string `min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s GroupResourcesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GroupResourcesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GroupResourcesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GroupResourcesInput"} + if s.Group == nil { + invalidParams.Add(request.NewErrParamRequired("Group")) + } + if s.Group != nil && len(*s.Group) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Group", 1)) + } + if s.ResourceArns == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArns")) + } + if s.ResourceArns != nil && len(s.ResourceArns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArns", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGroup sets the Group field's value. +func (s *GroupResourcesInput) SetGroup(v string) *GroupResourcesInput { + s.Group = &v + return s +} + +// SetResourceArns sets the ResourceArns field's value. +func (s *GroupResourcesInput) SetResourceArns(v []*string) *GroupResourcesInput { + s.ResourceArns = v + return s +} + +type GroupResourcesOutput struct { + _ struct{} `type:"structure"` + + // The ARNs of the resources that failed to be added to the group by this operation. + Failed []*FailedResource `type:"list"` + + // The ARNs of the resources that were successfully added to the group by this + // operation. + Succeeded []*string `min:"1" type:"list"` +} + +// String returns the string representation +func (s GroupResourcesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GroupResourcesOutput) GoString() string { + return s.String() +} + +// SetFailed sets the Failed field's value. +func (s *GroupResourcesOutput) SetFailed(v []*FailedResource) *GroupResourcesOutput { + s.Failed = v + return s +} + +// SetSucceeded sets the Succeeded field's value. +func (s *GroupResourcesOutput) SetSucceeded(v []*string) *GroupResourcesOutput { + s.Succeeded = v + return s +} + +// An internal error occurred while processing the request. Try again later. type InternalServerErrorException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -2075,26 +2827,54 @@ type ListGroupResourcesInput struct { _ struct{} `type:"structure"` // Filters, formatted as ResourceFilter objects, that you want to apply to a - // ListGroupResources operation. + // ListGroupResources operation. Filters the results to include only those of + // the specified resource types. // // * resource-type - Filter resources by their type. Specify up to five resource // types in the format AWS::ServiceCode::ResourceType. For example, AWS::EC2::Instance, // or AWS::S3::Bucket. + // + // When you specify a resource-type filter for ListGroupResources, AWS Resource + // Groups validates your filter resource types against the types that are defined + // in the query associated with the group. For example, if a group contains + // only S3 buckets because its query specifies only that resource type, but + // your resource-type filter includes EC2 instances, AWS Resource Groups does + // not filter for EC2 instances. In this case, a ListGroupResources request + // returns a BadRequestException error with a message similar to the following: + // + // The resource types specified as filters in the request are not valid. + // + // The error includes a list of resource types that failed the validation because + // they are not part of the query associated with the group. This validation + // doesn't occur when the group query specifies AWS::AllSupported, because a + // group based on such a query can contain any of the allowed resource types + // for the query type (tag-based or AWS CloudFormation stack-based queries). Filters []*ResourceFilter `type:"list"` - // The name of the resource group. - // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + // The name or the ARN of the resource group + Group *string `min:"1" type:"string"` - // The maximum number of group member ARNs that are returned in a single call - // by ListGroupResources, in paginated output. By default, this number is 50. - MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` + // Don't use this parameter. Use Group instead. + // + // Deprecated: This field is deprecated, use Group instead. + GroupName *string `min:"1" deprecated:"true" type:"string"` + + // The total number of results that you want included on each page of the response. + // If you do not include this parameter, it defaults to a value that is specific + // to the operation. If additional items exist beyond the maximum you specify, + // the NextToken response element is present and has a value (is not null). + // Include that value as the NextToken request parameter in the next call to + // the operation to get the next part of the results. Note that the service + // might return fewer results than the maximum even when there are more results + // available. You should check NextToken after every operation to ensure that + // you receive all of the results. + MaxResults *int64 `min:"1" type:"integer"` - // The NextToken value that is returned in a paginated ListGroupResources request. - // To get the next page of results, run the call again, add the NextToken parameter, - // and specify the NextToken value. - NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` + // The parameter for receiving additional results if you receive a NextToken + // response in a previous request. A NextToken response indicates that more + // output is available. Set this parameter to the value provided by a previous + // call's NextToken response to indicate where the output should continue from. + NextToken *string `type:"string"` } // String returns the string representation @@ -2110,8 +2890,8 @@ func (s ListGroupResourcesInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *ListGroupResourcesInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "ListGroupResourcesInput"} - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) + if s.Group != nil && len(*s.Group) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Group", 1)) } if s.GroupName != nil && len(*s.GroupName) < 1 { invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) @@ -2142,6 +2922,12 @@ func (s *ListGroupResourcesInput) SetFilters(v []*ResourceFilter) *ListGroupReso return s } +// SetGroup sets the Group field's value. +func (s *ListGroupResourcesInput) SetGroup(v string) *ListGroupResourcesInput { + s.Group = &v + return s +} + // SetGroupName sets the GroupName field's value. func (s *ListGroupResourcesInput) SetGroupName(v string) *ListGroupResourcesInput { s.GroupName = &v @@ -2163,8 +2949,10 @@ func (s *ListGroupResourcesInput) SetNextToken(v string) *ListGroupResourcesInpu type ListGroupResourcesOutput struct { _ struct{} `type:"structure"` - // The NextToken value to include in a subsequent ListGroupResources request, - // to get more results. + // If present, indicates that more output is available than is included in the + // current response. Use this value in the NextToken request parameter in a + // subsequent call to the operation to get the next part of the output. You + // should repeat this until the NextToken response element comes back as null. NextToken *string `type:"string"` // A list of QueryError objects. Each error is an object that contains ErrorCode @@ -2211,18 +2999,30 @@ type ListGroupsInput struct { // Filters, formatted as GroupFilter objects, that you want to apply to a ListGroups // operation. // - // * resource-type - Filter groups by resource type. Specify up to five resource - // types in the format AWS::ServiceCode::ResourceType. For example, AWS::EC2::Instance, - // or AWS::S3::Bucket. + // * resource-type - Filter the results to include only those of the specified + // resource types. Specify up to five resource types in the format AWS::ServiceCode::ResourceType + // . For example, AWS::EC2::Instance, or AWS::S3::Bucket. + // + // * configuration-type - Filter the results to include only those groups + // that have the specified configuration types attached. The current supported + // values are: AWS:EC2::CapacityReservationPool Filters []*GroupFilter `type:"list"` - // The maximum number of resource group results that are returned by ListGroups - // in paginated output. By default, this number is 50. + // The total number of results that you want included on each page of the response. + // If you do not include this parameter, it defaults to a value that is specific + // to the operation. If additional items exist beyond the maximum you specify, + // the NextToken response element is present and has a value (is not null). + // Include that value as the NextToken request parameter in the next call to + // the operation to get the next part of the results. Note that the service + // might return fewer results than the maximum even when there are more results + // available. You should check NextToken after every operation to ensure that + // you receive all of the results. MaxResults *int64 `location:"querystring" locationName:"maxResults" min:"1" type:"integer"` - // The NextToken value that is returned in a paginated ListGroups request. To - // get the next page of results, run the call again, add the NextToken parameter, - // and specify the NextToken value. + // The parameter for receiving additional results if you receive a NextToken + // response in a previous request. A NextToken response indicates that more + // output is available. Set this parameter to the value provided by a previous + // call's NextToken response to indicate where the output should continue from. NextToken *string `location:"querystring" locationName:"nextToken" type:"string"` } @@ -2281,16 +3081,19 @@ type ListGroupsOutput struct { _ struct{} `type:"structure"` // A list of GroupIdentifier objects. Each identifier is an object that contains - // both the GroupName and the GroupArn. + // both the Name and the GroupArn. GroupIdentifiers []*GroupIdentifier `type:"list"` - // A list of resource groups. + // This output element is deprecated and shouldn't be used. Refer to GroupIdentifiers + // instead. // // Deprecated: This field is deprecated, use GroupIdentifiers instead. Groups []*Group `deprecated:"true" type:"list"` - // The NextToken value to include in a subsequent ListGroups request, to get - // more results. + // If present, indicates that more output is available than is included in the + // current response. Use this value in the NextToken request parameter in a + // subsequent call to the operation to get the next part of the output. You + // should repeat this until the NextToken response element comes back as null. NextToken *string `type:"string"` } @@ -2322,7 +3125,7 @@ func (s *ListGroupsOutput) SetNextToken(v string) *ListGroupsOutput { return s } -// The request uses an HTTP method which is not allowed for the specified resource. +// The request uses an HTTP method that isn't allowed for the specified resource. type MethodNotAllowedException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -2378,7 +3181,7 @@ func (s *MethodNotAllowedException) RequestID() string { return s.RespMetadata.RequestID } -// One or more resources specified in the request do not exist. +// One or more of the specified resources don't exist. type NotFoundException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -2575,40 +3378,32 @@ type ResourceQuery struct { // Query is a required field Query *string `type:"string" required:"true"` - // The type of the query. The valid values in this release are TAG_FILTERS_1_0 - // and CLOUDFORMATION_STACK_1_0. - // - // TAG_FILTERS_1_0: A JSON syntax that lets you specify a collection of simple - // tag filters for resource types and tags, as supported by the AWS Tagging - // API GetResources (https://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/API_GetResources.html) - // operation. If you specify more than one tag key, only resources that match - // all tag keys, and at least one value of each specified tag key, are returned - // in your query. If you specify more than one value for a tag key, a resource - // matches the filter if it has a tag key value that matches any of the specified - // values. + // The type of the query. You can use the following values: // - // For example, consider the following sample query for resources that have - // two tags, Stage and Version, with two values each. ([{"Key":"Stage","Values":["Test","Deploy"]},{"Key":"Version","Values":["1","2"]}]) - // The results of this query might include the following. + // * CLOUDFORMATION_STACK_1_0: A JSON syntax that lets you specify a CloudFormation + // stack ARN. // - // * An EC2 instance that has the following two tags: {"Key":"Stage","Value":"Deploy"}, - // and {"Key":"Version","Value":"2"} - // - // * An S3 bucket that has the following two tags: {"Key":"Stage","Value":"Test"}, - // and {"Key":"Version","Value":"1"} - // - // The query would not return the following results, however. The following - // EC2 instance does not have all tag keys specified in the filter, so it is - // rejected. The RDS database has all of the tag keys, but no values that match - // at least one of the specified tag key values in the filter. - // - // * An EC2 instance that has only the following tag: {"Key":"Stage","Value":"Deploy"}. - // - // * An RDS database that has the following two tags: {"Key":"Stage","Value":"Archived"}, - // and {"Key":"Version","Value":"4"} - // - // CLOUDFORMATION_STACK_1_0: A JSON syntax that lets you specify a CloudFormation - // stack ARN. + // * TAG_FILTERS_1_0: A JSON syntax that lets you specify a collection of + // simple tag filters for resource types and tags, as supported by the AWS + // Tagging API ResourceTypeFilters parameter of the tagging:GetResources + // (https://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/API_GetResources.html#resourcegrouptagging-GetResources-request-ResourceTypeFilters) + // operation. If you specify more than one tag key, only resources that match + // all tag keys, and at least one value of each specified tag key, are returned + // in your query. If you specify more than one value for a tag key, a resource + // matches the filter if it has a tag key value that matches any of the specified + // values. For example, consider the following sample query for resources + // that have two tags, Stage and Version, with two values each: [{"Key":"Stage","Values":["Test","Deploy"]},{"Key":"Version","Values":["1","2"]}] + // The results of this query could include the following. An EC2 instance + // that has the following two tags: {"Key":"Stage","Value":"Deploy"}, and + // {"Key":"Version","Value":"2"} An S3 bucket that has the following two + // tags: {"Key":"Stage","Value":"Test"}, and {"Key":"Version","Value":"1"} + // The query would not include the following items in the results, however. + // An EC2 instance that has only the following tag: {"Key":"Stage","Value":"Deploy"}. + // The instance does not have all of the tag keys specified in the filter, + // so it is excluded from the results. An RDS database that has the following + // two tags: {"Key":"Stage","Value":"Archived"}, and {"Key":"Version","Value":"4"} + // The database has all of the tag keys, but none of those keys has an associated + // value that matches at least one of the specified values in the filter. // // Type is a required field Type *string `min:"1" type:"string" required:"true" enum:"QueryType"` @@ -2658,17 +3453,25 @@ func (s *ResourceQuery) SetType(v string) *ResourceQuery { type SearchResourcesInput struct { _ struct{} `type:"structure"` - // The maximum number of group member ARNs returned by SearchResources in paginated - // output. By default, this number is 50. + // The total number of results that you want included on each page of the response. + // If you do not include this parameter, it defaults to a value that is specific + // to the operation. If additional items exist beyond the maximum you specify, + // the NextToken response element is present and has a value (is not null). + // Include that value as the NextToken request parameter in the next call to + // the operation to get the next part of the results. Note that the service + // might return fewer results than the maximum even when there are more results + // available. You should check NextToken after every operation to ensure that + // you receive all of the results. MaxResults *int64 `min:"1" type:"integer"` - // The NextToken value that is returned in a paginated SearchResources request. - // To get the next page of results, run the call again, add the NextToken parameter, - // and specify the NextToken value. + // The parameter for receiving additional results if you receive a NextToken + // response in a previous request. A NextToken response indicates that more + // output is available. Set this parameter to the value provided by a previous + // call's NextToken response to indicate where the output should continue from. NextToken *string `type:"string"` // The search query, using the same formats that are supported for resource - // group definition. + // group definition. For more information, see CreateGroup. // // ResourceQuery is a required field ResourceQuery *ResourceQuery `type:"structure" required:"true"` @@ -2726,8 +3529,10 @@ func (s *SearchResourcesInput) SetResourceQuery(v *ResourceQuery) *SearchResourc type SearchResourcesOutput struct { _ struct{} `type:"structure"` - // The NextToken value to include in a subsequent SearchResources request, to - // get more results. + // If present, indicates that more output is available than is included in the + // current response. Use this value in the NextToken request parameter in a + // subsequent call to the operation to get the next part of the output. You + // should repeat this until the NextToken response element comes back as null. NextToken *string `type:"string"` // A list of QueryError objects. Each error is an object that contains ErrorCode @@ -2771,14 +3576,13 @@ func (s *SearchResourcesOutput) SetResourceIdentifiers(v []*ResourceIdentifier) type TagInput struct { _ struct{} `type:"structure"` - // The ARN of the resource to which to add tags. + // The ARN of the resource group to which to add tags. // // Arn is a required field Arn *string `location:"uri" locationName:"Arn" min:"12" type:"string" required:"true"` - // The tags to add to the specified resource. A tag is a string-to-string map - // of key-value pairs. Tag keys can have a maximum character length of 128 characters, - // and tag values can have a maximum length of 256 characters. + // The tags to add to the specified resource group. A tag is a string-to-string + // map of key-value pairs. // // Tags is a required field Tags map[string]*string `type:"map" required:"true"` @@ -2831,7 +3635,7 @@ type TagOutput struct { // The ARN of the tagged resource. Arn *string `min:"12" type:"string"` - // The tags that have been added to the specified resource. + // The tags that have been added to the specified resource group. Tags map[string]*string `type:"map"` } @@ -2857,7 +3661,8 @@ func (s *TagOutput) SetTags(v map[string]*string) *TagOutput { return s } -// The caller has exceeded throttling limits. +// You've exceeded throttling limits by making too many requests in a period +// of time. type TooManyRequestsException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -2913,8 +3718,8 @@ func (s *TooManyRequestsException) RequestID() string { return s.RespMetadata.RequestID } -// The request has not been applied because it lacks valid authentication credentials -// for the target resource. +// The request was rejected because it doesn't have valid credentials for the +// target resource. type UnauthorizedException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -2970,10 +3775,101 @@ func (s *UnauthorizedException) RequestID() string { return s.RespMetadata.RequestID } +type UngroupResourcesInput struct { + _ struct{} `type:"structure"` + + // The name or the ARN of the resource group from which to remove the resources. + // + // Group is a required field + Group *string `min:"1" type:"string" required:"true"` + + // The ARNs of the resources to be removed from the group. + // + // ResourceArns is a required field + ResourceArns []*string `min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s UngroupResourcesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UngroupResourcesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UngroupResourcesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UngroupResourcesInput"} + if s.Group == nil { + invalidParams.Add(request.NewErrParamRequired("Group")) + } + if s.Group != nil && len(*s.Group) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Group", 1)) + } + if s.ResourceArns == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArns")) + } + if s.ResourceArns != nil && len(s.ResourceArns) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArns", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGroup sets the Group field's value. +func (s *UngroupResourcesInput) SetGroup(v string) *UngroupResourcesInput { + s.Group = &v + return s +} + +// SetResourceArns sets the ResourceArns field's value. +func (s *UngroupResourcesInput) SetResourceArns(v []*string) *UngroupResourcesInput { + s.ResourceArns = v + return s +} + +type UngroupResourcesOutput struct { + _ struct{} `type:"structure"` + + // The resources that failed to be removed from the group. + Failed []*FailedResource `type:"list"` + + // The ARNs of the resources that were successfully removed from the group. + Succeeded []*string `min:"1" type:"list"` +} + +// String returns the string representation +func (s UngroupResourcesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UngroupResourcesOutput) GoString() string { + return s.String() +} + +// SetFailed sets the Failed field's value. +func (s *UngroupResourcesOutput) SetFailed(v []*FailedResource) *UngroupResourcesOutput { + s.Failed = v + return s +} + +// SetSucceeded sets the Succeeded field's value. +func (s *UngroupResourcesOutput) SetSucceeded(v []*string) *UngroupResourcesOutput { + s.Succeeded = v + return s +} + type UntagInput struct { _ struct{} `type:"structure"` - // The ARN of the resource from which to remove tags. + // The ARN of the resource group from which to remove tags. The command removed + // both the specified keys and any values associated with those keys. // // Arn is a required field Arn *string `location:"uri" locationName:"Arn" min:"12" type:"string" required:"true"` @@ -3028,10 +3924,10 @@ func (s *UntagInput) SetKeys(v []*string) *UntagInput { type UntagOutput struct { _ struct{} `type:"structure"` - // The ARN of the resource from which tags have been removed. + // The ARN of the resource group from which tags have been removed. Arn *string `min:"12" type:"string"` - // The keys of tags that have been removed. + // The keys of the tags that were removed. Keys []*string `type:"list"` } @@ -3060,15 +3956,17 @@ func (s *UntagOutput) SetKeys(v []*string) *UntagOutput { type UpdateGroupInput struct { _ struct{} `type:"structure"` - // The description of the resource group. Descriptions can have a maximum of - // 511 characters, including letters, numbers, hyphens, underscores, punctuation, - // and spaces. + // The new description that you want to update the resource group with. Descriptions + // can contain letters, numbers, hyphens, underscores, periods, and spaces. Description *string `type:"string"` - // The name of the resource group for which you want to update its description. + // The name or the ARN of the resource group to modify. + Group *string `min:"1" type:"string"` + + // Don't use this parameter. Use Group instead. // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + // Deprecated: This field is deprecated, use Group instead. + GroupName *string `min:"1" deprecated:"true" type:"string"` } // String returns the string representation @@ -3084,8 +3982,8 @@ func (s UpdateGroupInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *UpdateGroupInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "UpdateGroupInput"} - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) + if s.Group != nil && len(*s.Group) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Group", 1)) } if s.GroupName != nil && len(*s.GroupName) < 1 { invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) @@ -3103,6 +4001,12 @@ func (s *UpdateGroupInput) SetDescription(v string) *UpdateGroupInput { return s } +// SetGroup sets the Group field's value. +func (s *UpdateGroupInput) SetGroup(v string) *UpdateGroupInput { + s.Group = &v + return s +} + // SetGroupName sets the GroupName field's value. func (s *UpdateGroupInput) SetGroupName(v string) *UpdateGroupInput { s.GroupName = &v @@ -3112,7 +4016,7 @@ func (s *UpdateGroupInput) SetGroupName(v string) *UpdateGroupInput { type UpdateGroupOutput struct { _ struct{} `type:"structure"` - // The full description of the resource group after it has been updated. + // The update description of the resource group. Group *Group `type:"structure"` } @@ -3135,13 +4039,16 @@ func (s *UpdateGroupOutput) SetGroup(v *Group) *UpdateGroupOutput { type UpdateGroupQueryInput struct { _ struct{} `type:"structure"` - // The name of the resource group for which you want to edit the query. + // The name or the ARN of the resource group to query. + Group *string `min:"1" type:"string"` + + // Don't use this parameter. Use Group instead. // - // GroupName is a required field - GroupName *string `location:"uri" locationName:"GroupName" min:"1" type:"string" required:"true"` + // Deprecated: This field is deprecated, use Group instead. + GroupName *string `min:"1" deprecated:"true" type:"string"` - // The resource query that determines which AWS resources are members of the - // resource group. + // The resource query to determine which AWS resources are members of this resource + // group. // // ResourceQuery is a required field ResourceQuery *ResourceQuery `type:"structure" required:"true"` @@ -3160,8 +4067,8 @@ func (s UpdateGroupQueryInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *UpdateGroupQueryInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "UpdateGroupQueryInput"} - if s.GroupName == nil { - invalidParams.Add(request.NewErrParamRequired("GroupName")) + if s.Group != nil && len(*s.Group) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Group", 1)) } if s.GroupName != nil && len(*s.GroupName) < 1 { invalidParams.Add(request.NewErrParamMinLen("GroupName", 1)) @@ -3181,6 +4088,12 @@ func (s *UpdateGroupQueryInput) Validate() error { return nil } +// SetGroup sets the Group field's value. +func (s *UpdateGroupQueryInput) SetGroup(v string) *UpdateGroupQueryInput { + s.Group = &v + return s +} + // SetGroupName sets the GroupName field's value. func (s *UpdateGroupQueryInput) SetGroupName(v string) *UpdateGroupQueryInput { s.GroupName = &v @@ -3196,7 +4109,7 @@ func (s *UpdateGroupQueryInput) SetResourceQuery(v *ResourceQuery) *UpdateGroupQ type UpdateGroupQueryOutput struct { _ struct{} `type:"structure"` - // The resource query associated with the resource group after the update. + // The updated resource query associated with the resource group after the update. GroupQuery *GroupQuery `type:"structure"` } @@ -3216,11 +4129,42 @@ func (s *UpdateGroupQueryOutput) SetGroupQuery(v *GroupQuery) *UpdateGroupQueryO return s } +const ( + // GroupConfigurationStatusUpdating is a GroupConfigurationStatus enum value + GroupConfigurationStatusUpdating = "UPDATING" + + // GroupConfigurationStatusUpdateComplete is a GroupConfigurationStatus enum value + GroupConfigurationStatusUpdateComplete = "UPDATE_COMPLETE" + + // GroupConfigurationStatusUpdateFailed is a GroupConfigurationStatus enum value + GroupConfigurationStatusUpdateFailed = "UPDATE_FAILED" +) + +// GroupConfigurationStatus_Values returns all elements of the GroupConfigurationStatus enum +func GroupConfigurationStatus_Values() []string { + return []string{ + GroupConfigurationStatusUpdating, + GroupConfigurationStatusUpdateComplete, + GroupConfigurationStatusUpdateFailed, + } +} + const ( // GroupFilterNameResourceType is a GroupFilterName enum value GroupFilterNameResourceType = "resource-type" + + // GroupFilterNameConfigurationType is a GroupFilterName enum value + GroupFilterNameConfigurationType = "configuration-type" ) +// GroupFilterName_Values returns all elements of the GroupFilterName enum +func GroupFilterName_Values() []string { + return []string{ + GroupFilterNameResourceType, + GroupFilterNameConfigurationType, + } +} + const ( // QueryErrorCodeCloudformationStackInactive is a QueryErrorCode enum value QueryErrorCodeCloudformationStackInactive = "CLOUDFORMATION_STACK_INACTIVE" @@ -3229,6 +4173,14 @@ const ( QueryErrorCodeCloudformationStackNotExisting = "CLOUDFORMATION_STACK_NOT_EXISTING" ) +// QueryErrorCode_Values returns all elements of the QueryErrorCode enum +func QueryErrorCode_Values() []string { + return []string{ + QueryErrorCodeCloudformationStackInactive, + QueryErrorCodeCloudformationStackNotExisting, + } +} + const ( // QueryTypeTagFilters10 is a QueryType enum value QueryTypeTagFilters10 = "TAG_FILTERS_1_0" @@ -3237,7 +4189,22 @@ const ( QueryTypeCloudformationStack10 = "CLOUDFORMATION_STACK_1_0" ) +// QueryType_Values returns all elements of the QueryType enum +func QueryType_Values() []string { + return []string{ + QueryTypeTagFilters10, + QueryTypeCloudformationStack10, + } +} + const ( // ResourceFilterNameResourceType is a ResourceFilterName enum value ResourceFilterNameResourceType = "resource-type" ) + +// ResourceFilterName_Values returns all elements of the ResourceFilterName enum +func ResourceFilterName_Values() []string { + return []string{ + ResourceFilterNameResourceType, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/resourcegroups/errors.go b/vendor/github.com/aws/aws-sdk-go/service/resourcegroups/errors.go index 0d0a2a074ca..27a78e163ac 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/resourcegroups/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/resourcegroups/errors.go @@ -11,45 +11,45 @@ const ( // ErrCodeBadRequestException for service response error code // "BadRequestException". // - // The request does not comply with validation rules that are defined for the - // request parameters. + // The request includes one or more parameters that violate validation rules. ErrCodeBadRequestException = "BadRequestException" // ErrCodeForbiddenException for service response error code // "ForbiddenException". // - // The caller is not authorized to make the request. + // The caller isn't authorized to make the request. Check permissions. ErrCodeForbiddenException = "ForbiddenException" // ErrCodeInternalServerErrorException for service response error code // "InternalServerErrorException". // - // An internal error occurred while processing the request. + // An internal error occurred while processing the request. Try again later. ErrCodeInternalServerErrorException = "InternalServerErrorException" // ErrCodeMethodNotAllowedException for service response error code // "MethodNotAllowedException". // - // The request uses an HTTP method which is not allowed for the specified resource. + // The request uses an HTTP method that isn't allowed for the specified resource. ErrCodeMethodNotAllowedException = "MethodNotAllowedException" // ErrCodeNotFoundException for service response error code // "NotFoundException". // - // One or more resources specified in the request do not exist. + // One or more of the specified resources don't exist. ErrCodeNotFoundException = "NotFoundException" // ErrCodeTooManyRequestsException for service response error code // "TooManyRequestsException". // - // The caller has exceeded throttling limits. + // You've exceeded throttling limits by making too many requests in a period + // of time. ErrCodeTooManyRequestsException = "TooManyRequestsException" // ErrCodeUnauthorizedException for service response error code // "UnauthorizedException". // - // The request has not been applied because it lacks valid authentication credentials - // for the target resource. + // The request was rejected because it doesn't have valid credentials for the + // target resource. ErrCodeUnauthorizedException = "UnauthorizedException" ) diff --git a/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/api.go b/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/api.go new file mode 100644 index 00000000000..4df9efecb85 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/api.go @@ -0,0 +1,2722 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package resourcegroupstaggingapi + +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" + "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" +) + +const opDescribeReportCreation = "DescribeReportCreation" + +// DescribeReportCreationRequest generates a "aws/request.Request" representing the +// client's request for the DescribeReportCreation operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeReportCreation for more information on using the DescribeReportCreation +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeReportCreationRequest method. +// req, resp := client.DescribeReportCreationRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/DescribeReportCreation +func (c *ResourceGroupsTaggingAPI) DescribeReportCreationRequest(input *DescribeReportCreationInput) (req *request.Request, output *DescribeReportCreationOutput) { + op := &request.Operation{ + Name: opDescribeReportCreation, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeReportCreationInput{} + } + + output = &DescribeReportCreationOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeReportCreation API operation for AWS Resource Groups Tagging API. +// +// Describes the status of the StartReportCreation operation. +// +// You can call this operation only from the organization's master account and +// from the us-east-1 Region. +// +// Returns awserr.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 Resource Groups Tagging API's +// API operation DescribeReportCreation for usage and error information. +// +// Returned Error Types: +// * ConstraintViolationException +// The request was denied because performing this operation violates a constraint. +// +// Some of the reasons in the following list might not apply to this specific +// operation. +// +// * You must meet the prerequisites for using tag policies. For information, +// see Prerequisites and Permissions for Using Tag Policies (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html) +// in the AWS Organizations User Guide. +// +// * You must enable the tag policies service principal (tagpolicies.tag.amazonaws.com) +// to integrate with AWS Organizations For information, see EnableAWSServiceAccess +// (http://docs.aws.amazon.com/organizations/latest/APIReference/API_EnableAWSServiceAccess.html). +// +// * You must have a tag policy attached to the organization root, an OU, +// or an account. +// +// * InternalServiceException +// The request processing failed because of an unknown error, exception, or +// failure. You can retry the request. +// +// * InvalidParameterException +// This error indicates one of the following: +// +// * A parameter is missing. +// +// * A malformed string was supplied for the request parameter. +// +// * An out-of-range value was supplied for the request parameter. +// +// * The target ID is invalid, unsupported, or doesn't exist. +// +// * You can't access the Amazon S3 bucket for report storage. For more information, +// see Additional Requirements for Organization-wide Tag Compliance Reports +// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html#bucket-policies-org-report) +// in the AWS Organizations User Guide. +// +// * ThrottledException +// The request was denied to limit the frequency of submitted requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/DescribeReportCreation +func (c *ResourceGroupsTaggingAPI) DescribeReportCreation(input *DescribeReportCreationInput) (*DescribeReportCreationOutput, error) { + req, out := c.DescribeReportCreationRequest(input) + return out, req.Send() +} + +// DescribeReportCreationWithContext is the same as DescribeReportCreation with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeReportCreation for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroupsTaggingAPI) DescribeReportCreationWithContext(ctx aws.Context, input *DescribeReportCreationInput, opts ...request.Option) (*DescribeReportCreationOutput, error) { + req, out := c.DescribeReportCreationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetComplianceSummary = "GetComplianceSummary" + +// GetComplianceSummaryRequest generates a "aws/request.Request" representing the +// client's request for the GetComplianceSummary operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetComplianceSummary for more information on using the GetComplianceSummary +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetComplianceSummaryRequest method. +// req, resp := client.GetComplianceSummaryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetComplianceSummary +func (c *ResourceGroupsTaggingAPI) GetComplianceSummaryRequest(input *GetComplianceSummaryInput) (req *request.Request, output *GetComplianceSummaryOutput) { + op := &request.Operation{ + Name: opGetComplianceSummary, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"PaginationToken"}, + OutputTokens: []string{"PaginationToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetComplianceSummaryInput{} + } + + output = &GetComplianceSummaryOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetComplianceSummary API operation for AWS Resource Groups Tagging API. +// +// Returns a table that shows counts of resources that are noncompliant with +// their tag policies. +// +// For more information on tag policies, see Tag Policies (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) +// in the AWS Organizations User Guide. +// +// You can call this operation only from the organization's master account and +// from the us-east-1 Region. +// +// Returns awserr.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 Resource Groups Tagging API's +// API operation GetComplianceSummary for usage and error information. +// +// Returned Error Types: +// * ConstraintViolationException +// The request was denied because performing this operation violates a constraint. +// +// Some of the reasons in the following list might not apply to this specific +// operation. +// +// * You must meet the prerequisites for using tag policies. For information, +// see Prerequisites and Permissions for Using Tag Policies (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html) +// in the AWS Organizations User Guide. +// +// * You must enable the tag policies service principal (tagpolicies.tag.amazonaws.com) +// to integrate with AWS Organizations For information, see EnableAWSServiceAccess +// (http://docs.aws.amazon.com/organizations/latest/APIReference/API_EnableAWSServiceAccess.html). +// +// * You must have a tag policy attached to the organization root, an OU, +// or an account. +// +// * InternalServiceException +// The request processing failed because of an unknown error, exception, or +// failure. You can retry the request. +// +// * InvalidParameterException +// This error indicates one of the following: +// +// * A parameter is missing. +// +// * A malformed string was supplied for the request parameter. +// +// * An out-of-range value was supplied for the request parameter. +// +// * The target ID is invalid, unsupported, or doesn't exist. +// +// * You can't access the Amazon S3 bucket for report storage. For more information, +// see Additional Requirements for Organization-wide Tag Compliance Reports +// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html#bucket-policies-org-report) +// in the AWS Organizations User Guide. +// +// * ThrottledException +// The request was denied to limit the frequency of submitted requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetComplianceSummary +func (c *ResourceGroupsTaggingAPI) GetComplianceSummary(input *GetComplianceSummaryInput) (*GetComplianceSummaryOutput, error) { + req, out := c.GetComplianceSummaryRequest(input) + return out, req.Send() +} + +// GetComplianceSummaryWithContext is the same as GetComplianceSummary with the addition of +// the ability to pass a context and additional request options. +// +// See GetComplianceSummary for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroupsTaggingAPI) GetComplianceSummaryWithContext(ctx aws.Context, input *GetComplianceSummaryInput, opts ...request.Option) (*GetComplianceSummaryOutput, error) { + req, out := c.GetComplianceSummaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetComplianceSummaryPages iterates over the pages of a GetComplianceSummary operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetComplianceSummary 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 GetComplianceSummary operation. +// pageNum := 0 +// err := client.GetComplianceSummaryPages(params, +// func(page *resourcegroupstaggingapi.GetComplianceSummaryOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *ResourceGroupsTaggingAPI) GetComplianceSummaryPages(input *GetComplianceSummaryInput, fn func(*GetComplianceSummaryOutput, bool) bool) error { + return c.GetComplianceSummaryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetComplianceSummaryPagesWithContext same as GetComplianceSummaryPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroupsTaggingAPI) GetComplianceSummaryPagesWithContext(ctx aws.Context, input *GetComplianceSummaryInput, fn func(*GetComplianceSummaryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetComplianceSummaryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetComplianceSummaryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetComplianceSummaryOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opGetResources = "GetResources" + +// GetResourcesRequest generates a "aws/request.Request" representing the +// client's request for the GetResources operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetResources for more information on using the GetResources +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetResourcesRequest method. +// req, resp := client.GetResourcesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetResources +func (c *ResourceGroupsTaggingAPI) GetResourcesRequest(input *GetResourcesInput) (req *request.Request, output *GetResourcesOutput) { + op := &request.Operation{ + Name: opGetResources, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"PaginationToken"}, + OutputTokens: []string{"PaginationToken"}, + LimitToken: "ResourcesPerPage", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetResourcesInput{} + } + + output = &GetResourcesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetResources API operation for AWS Resource Groups Tagging API. +// +// Returns all the tagged or previously tagged resources that are located in +// the specified Region for the AWS account. +// +// Depending on what information you want returned, you can also specify the +// following: +// +// * Filters that specify what tags and resource types you want returned. +// The response includes all tags that are associated with the requested +// resources. +// +// * Information about compliance with the account's effective tag policy. +// For more information on tag policies, see Tag Policies (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) +// in the AWS Organizations User Guide. +// +// You can check the PaginationToken response parameter to determine if a query +// is complete. Queries occasionally return fewer results on a page than allowed. +// The PaginationToken response parameter value is null only when there are +// no more results to display. +// +// Returns awserr.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 Resource Groups Tagging API's +// API operation GetResources for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// This error indicates one of the following: +// +// * A parameter is missing. +// +// * A malformed string was supplied for the request parameter. +// +// * An out-of-range value was supplied for the request parameter. +// +// * The target ID is invalid, unsupported, or doesn't exist. +// +// * You can't access the Amazon S3 bucket for report storage. For more information, +// see Additional Requirements for Organization-wide Tag Compliance Reports +// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html#bucket-policies-org-report) +// in the AWS Organizations User Guide. +// +// * ThrottledException +// The request was denied to limit the frequency of submitted requests. +// +// * InternalServiceException +// The request processing failed because of an unknown error, exception, or +// failure. You can retry the request. +// +// * PaginationTokenExpiredException +// A PaginationToken is valid for a maximum of 15 minutes. Your request was +// denied because the specified PaginationToken has expired. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetResources +func (c *ResourceGroupsTaggingAPI) GetResources(input *GetResourcesInput) (*GetResourcesOutput, error) { + req, out := c.GetResourcesRequest(input) + 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 *ResourceGroupsTaggingAPI) 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, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetResources 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 GetResources operation. +// pageNum := 0 +// err := client.GetResourcesPages(params, +// func(page *resourcegroupstaggingapi.GetResourcesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *ResourceGroupsTaggingAPI) 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 *ResourceGroupsTaggingAPI) 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 + }, + } + + for p.Next() { + if !fn(p.Page().(*GetResourcesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opGetTagKeys = "GetTagKeys" + +// GetTagKeysRequest generates a "aws/request.Request" representing the +// client's request for the GetTagKeys operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetTagKeys for more information on using the GetTagKeys +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetTagKeysRequest method. +// req, resp := client.GetTagKeysRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetTagKeys +func (c *ResourceGroupsTaggingAPI) GetTagKeysRequest(input *GetTagKeysInput) (req *request.Request, output *GetTagKeysOutput) { + op := &request.Operation{ + Name: opGetTagKeys, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"PaginationToken"}, + OutputTokens: []string{"PaginationToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetTagKeysInput{} + } + + output = &GetTagKeysOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetTagKeys API operation for AWS Resource Groups Tagging API. +// +// Returns all tag keys in the specified Region for the 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. +// +// See the AWS API reference guide for AWS Resource Groups Tagging API's +// API operation GetTagKeys for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// This error indicates one of the following: +// +// * A parameter is missing. +// +// * A malformed string was supplied for the request parameter. +// +// * An out-of-range value was supplied for the request parameter. +// +// * The target ID is invalid, unsupported, or doesn't exist. +// +// * You can't access the Amazon S3 bucket for report storage. For more information, +// see Additional Requirements for Organization-wide Tag Compliance Reports +// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html#bucket-policies-org-report) +// in the AWS Organizations User Guide. +// +// * ThrottledException +// The request was denied to limit the frequency of submitted requests. +// +// * InternalServiceException +// The request processing failed because of an unknown error, exception, or +// failure. You can retry the request. +// +// * PaginationTokenExpiredException +// A PaginationToken is valid for a maximum of 15 minutes. Your request was +// denied because the specified PaginationToken has expired. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetTagKeys +func (c *ResourceGroupsTaggingAPI) GetTagKeys(input *GetTagKeysInput) (*GetTagKeysOutput, error) { + req, out := c.GetTagKeysRequest(input) + return out, req.Send() +} + +// GetTagKeysWithContext is the same as GetTagKeys with the addition of +// the ability to pass a context and additional request options. +// +// See GetTagKeys for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroupsTaggingAPI) GetTagKeysWithContext(ctx aws.Context, input *GetTagKeysInput, opts ...request.Option) (*GetTagKeysOutput, error) { + req, out := c.GetTagKeysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetTagKeysPages iterates over the pages of a GetTagKeys operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetTagKeys 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 GetTagKeys operation. +// pageNum := 0 +// err := client.GetTagKeysPages(params, +// func(page *resourcegroupstaggingapi.GetTagKeysOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *ResourceGroupsTaggingAPI) GetTagKeysPages(input *GetTagKeysInput, fn func(*GetTagKeysOutput, bool) bool) error { + return c.GetTagKeysPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetTagKeysPagesWithContext same as GetTagKeysPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroupsTaggingAPI) GetTagKeysPagesWithContext(ctx aws.Context, input *GetTagKeysInput, fn func(*GetTagKeysOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetTagKeysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetTagKeysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetTagKeysOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opGetTagValues = "GetTagValues" + +// GetTagValuesRequest generates a "aws/request.Request" representing the +// client's request for the GetTagValues operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetTagValues for more information on using the GetTagValues +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetTagValuesRequest method. +// req, resp := client.GetTagValuesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetTagValues +func (c *ResourceGroupsTaggingAPI) GetTagValuesRequest(input *GetTagValuesInput) (req *request.Request, output *GetTagValuesOutput) { + op := &request.Operation{ + Name: opGetTagValues, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"PaginationToken"}, + OutputTokens: []string{"PaginationToken"}, + LimitToken: "", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetTagValuesInput{} + } + + output = &GetTagValuesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetTagValues API operation for AWS Resource Groups Tagging API. +// +// Returns all tag values for the specified key in the specified Region for +// the 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. +// +// See the AWS API reference guide for AWS Resource Groups Tagging API's +// API operation GetTagValues for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// This error indicates one of the following: +// +// * A parameter is missing. +// +// * A malformed string was supplied for the request parameter. +// +// * An out-of-range value was supplied for the request parameter. +// +// * The target ID is invalid, unsupported, or doesn't exist. +// +// * You can't access the Amazon S3 bucket for report storage. For more information, +// see Additional Requirements for Organization-wide Tag Compliance Reports +// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html#bucket-policies-org-report) +// in the AWS Organizations User Guide. +// +// * ThrottledException +// The request was denied to limit the frequency of submitted requests. +// +// * InternalServiceException +// The request processing failed because of an unknown error, exception, or +// failure. You can retry the request. +// +// * PaginationTokenExpiredException +// A PaginationToken is valid for a maximum of 15 minutes. Your request was +// denied because the specified PaginationToken has expired. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/GetTagValues +func (c *ResourceGroupsTaggingAPI) GetTagValues(input *GetTagValuesInput) (*GetTagValuesOutput, error) { + req, out := c.GetTagValuesRequest(input) + return out, req.Send() +} + +// GetTagValuesWithContext is the same as GetTagValues with the addition of +// the ability to pass a context and additional request options. +// +// See GetTagValues for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroupsTaggingAPI) GetTagValuesWithContext(ctx aws.Context, input *GetTagValuesInput, opts ...request.Option) (*GetTagValuesOutput, error) { + req, out := c.GetTagValuesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetTagValuesPages iterates over the pages of a GetTagValues operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetTagValues 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 GetTagValues operation. +// pageNum := 0 +// err := client.GetTagValuesPages(params, +// func(page *resourcegroupstaggingapi.GetTagValuesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *ResourceGroupsTaggingAPI) GetTagValuesPages(input *GetTagValuesInput, fn func(*GetTagValuesOutput, bool) bool) error { + return c.GetTagValuesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetTagValuesPagesWithContext same as GetTagValuesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroupsTaggingAPI) GetTagValuesPagesWithContext(ctx aws.Context, input *GetTagValuesInput, fn func(*GetTagValuesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetTagValuesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetTagValuesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetTagValuesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opStartReportCreation = "StartReportCreation" + +// StartReportCreationRequest generates a "aws/request.Request" representing the +// client's request for the StartReportCreation operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See StartReportCreation for more information on using the StartReportCreation +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the StartReportCreationRequest method. +// req, resp := client.StartReportCreationRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/StartReportCreation +func (c *ResourceGroupsTaggingAPI) StartReportCreationRequest(input *StartReportCreationInput) (req *request.Request, output *StartReportCreationOutput) { + op := &request.Operation{ + Name: opStartReportCreation, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &StartReportCreationInput{} + } + + output = &StartReportCreationOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// StartReportCreation API operation for AWS Resource Groups Tagging API. +// +// Generates a report that lists all tagged resources in accounts across your +// organization and tells whether each resource is compliant with the effective +// tag policy. Compliance data is refreshed daily. +// +// The generated report is saved to the following location: +// +// s3://example-bucket/AwsTagPolicies/o-exampleorgid/YYYY-MM-ddTHH:mm:ssZ/report.csv +// +// You can call this operation only from the organization's master account and +// from the us-east-1 Region. +// +// Returns awserr.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 Resource Groups Tagging API's +// API operation StartReportCreation for usage and error information. +// +// Returned Error Types: +// * ConcurrentModificationException +// The target of the operation is currently being modified by a different request. +// Try again later. +// +// * ConstraintViolationException +// The request was denied because performing this operation violates a constraint. +// +// Some of the reasons in the following list might not apply to this specific +// operation. +// +// * You must meet the prerequisites for using tag policies. For information, +// see Prerequisites and Permissions for Using Tag Policies (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html) +// in the AWS Organizations User Guide. +// +// * You must enable the tag policies service principal (tagpolicies.tag.amazonaws.com) +// to integrate with AWS Organizations For information, see EnableAWSServiceAccess +// (http://docs.aws.amazon.com/organizations/latest/APIReference/API_EnableAWSServiceAccess.html). +// +// * You must have a tag policy attached to the organization root, an OU, +// or an account. +// +// * InternalServiceException +// The request processing failed because of an unknown error, exception, or +// failure. You can retry the request. +// +// * InvalidParameterException +// This error indicates one of the following: +// +// * A parameter is missing. +// +// * A malformed string was supplied for the request parameter. +// +// * An out-of-range value was supplied for the request parameter. +// +// * The target ID is invalid, unsupported, or doesn't exist. +// +// * You can't access the Amazon S3 bucket for report storage. For more information, +// see Additional Requirements for Organization-wide Tag Compliance Reports +// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html#bucket-policies-org-report) +// in the AWS Organizations User Guide. +// +// * ThrottledException +// The request was denied to limit the frequency of submitted requests. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/StartReportCreation +func (c *ResourceGroupsTaggingAPI) StartReportCreation(input *StartReportCreationInput) (*StartReportCreationOutput, error) { + req, out := c.StartReportCreationRequest(input) + return out, req.Send() +} + +// StartReportCreationWithContext is the same as StartReportCreation with the addition of +// the ability to pass a context and additional request options. +// +// See StartReportCreation for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroupsTaggingAPI) StartReportCreationWithContext(ctx aws.Context, input *StartReportCreationInput, opts ...request.Option) (*StartReportCreationOutput, error) { + req, out := c.StartReportCreationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opTagResources = "TagResources" + +// TagResourcesRequest generates a "aws/request.Request" representing the +// client's request for the TagResources operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See TagResources for more information on using the TagResources +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the TagResourcesRequest method. +// req, resp := client.TagResourcesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/TagResources +func (c *ResourceGroupsTaggingAPI) TagResourcesRequest(input *TagResourcesInput) (req *request.Request, output *TagResourcesOutput) { + op := &request.Operation{ + Name: opTagResources, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &TagResourcesInput{} + } + + output = &TagResourcesOutput{} + req = c.newRequest(op, input, output) + return +} + +// TagResources API operation for AWS Resource Groups Tagging API. +// +// Applies one or more tags to the specified resources. Note the following: +// +// * Not all resources can have tags. For a list of services that support +// tagging, see this list (http://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/Welcome.html). +// +// * Each resource can have up to 50 tags. For other limits, see Tag Naming +// and Usage Conventions (http://docs.aws.amazon.com/general/latest/gr/aws_tagging.html#tag-conventions) +// in the AWS General Reference. +// +// * You can only tag resources that are located in the specified Region +// for the AWS account. +// +// * To add tags to a resource, you need the necessary permissions for the +// service that the resource belongs to as well as permissions for adding +// tags. For more information, see this list (http://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/Welcome.html). +// +// Do not store personally identifiable information (PII) or other confidential +// or sensitive information in tags. We use tags to provide you with billing +// and administration services. Tags are not intended to be used for private +// or sensitive data. +// +// Returns awserr.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 Resource Groups Tagging API's +// API operation TagResources for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// This error indicates one of the following: +// +// * A parameter is missing. +// +// * A malformed string was supplied for the request parameter. +// +// * An out-of-range value was supplied for the request parameter. +// +// * The target ID is invalid, unsupported, or doesn't exist. +// +// * You can't access the Amazon S3 bucket for report storage. For more information, +// see Additional Requirements for Organization-wide Tag Compliance Reports +// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html#bucket-policies-org-report) +// in the AWS Organizations User Guide. +// +// * ThrottledException +// The request was denied to limit the frequency of submitted requests. +// +// * InternalServiceException +// The request processing failed because of an unknown error, exception, or +// failure. You can retry the request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/TagResources +func (c *ResourceGroupsTaggingAPI) TagResources(input *TagResourcesInput) (*TagResourcesOutput, error) { + req, out := c.TagResourcesRequest(input) + return out, req.Send() +} + +// TagResourcesWithContext is the same as TagResources with the addition of +// the ability to pass a context and additional request options. +// +// See TagResources for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroupsTaggingAPI) TagResourcesWithContext(ctx aws.Context, input *TagResourcesInput, opts ...request.Option) (*TagResourcesOutput, error) { + req, out := c.TagResourcesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUntagResources = "UntagResources" + +// UntagResourcesRequest generates a "aws/request.Request" representing the +// client's request for the UntagResources operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UntagResources for more information on using the UntagResources +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UntagResourcesRequest method. +// req, resp := client.UntagResourcesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/UntagResources +func (c *ResourceGroupsTaggingAPI) UntagResourcesRequest(input *UntagResourcesInput) (req *request.Request, output *UntagResourcesOutput) { + op := &request.Operation{ + Name: opUntagResources, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UntagResourcesInput{} + } + + output = &UntagResourcesOutput{} + req = c.newRequest(op, input, output) + return +} + +// UntagResources API operation for AWS Resource Groups Tagging API. +// +// Removes the specified tags from the specified resources. When you specify +// a tag key, the action removes both that key and its associated value. The +// operation succeeds even if you attempt to remove tags from a resource that +// were already removed. Note the following: +// +// * To remove tags from a resource, you need the necessary permissions for +// the service that the resource belongs to as well as permissions for removing +// tags. For more information, see this list (http://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/Welcome.html). +// +// * You can only tag resources that are located in the specified Region +// for the 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. +// +// See the AWS API reference guide for AWS Resource Groups Tagging API's +// API operation UntagResources for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// This error indicates one of the following: +// +// * A parameter is missing. +// +// * A malformed string was supplied for the request parameter. +// +// * An out-of-range value was supplied for the request parameter. +// +// * The target ID is invalid, unsupported, or doesn't exist. +// +// * You can't access the Amazon S3 bucket for report storage. For more information, +// see Additional Requirements for Organization-wide Tag Compliance Reports +// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html#bucket-policies-org-report) +// in the AWS Organizations User Guide. +// +// * ThrottledException +// The request was denied to limit the frequency of submitted requests. +// +// * InternalServiceException +// The request processing failed because of an unknown error, exception, or +// failure. You can retry the request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26/UntagResources +func (c *ResourceGroupsTaggingAPI) UntagResources(input *UntagResourcesInput) (*UntagResourcesOutput, error) { + req, out := c.UntagResourcesRequest(input) + return out, req.Send() +} + +// UntagResourcesWithContext is the same as UntagResources with the addition of +// the ability to pass a context and additional request options. +// +// See UntagResources for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *ResourceGroupsTaggingAPI) UntagResourcesWithContext(ctx aws.Context, input *UntagResourcesInput, opts ...request.Option) (*UntagResourcesOutput, error) { + req, out := c.UntagResourcesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// Information that shows whether a resource is compliant with the effective +// tag policy, including details on any noncompliant tag keys. +type ComplianceDetails struct { + _ struct{} `type:"structure"` + + // Whether a resource is compliant with the effective tag policy. + ComplianceStatus *bool `type:"boolean"` + + // These are keys defined in the effective policy that are on the resource with + // either incorrect case treatment or noncompliant values. + KeysWithNoncompliantValues []*string `type:"list"` + + // These tag keys on the resource are noncompliant with the effective tag policy. + NoncompliantKeys []*string `type:"list"` +} + +// String returns the string representation +func (s ComplianceDetails) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ComplianceDetails) GoString() string { + return s.String() +} + +// SetComplianceStatus sets the ComplianceStatus field's value. +func (s *ComplianceDetails) SetComplianceStatus(v bool) *ComplianceDetails { + s.ComplianceStatus = &v + return s +} + +// SetKeysWithNoncompliantValues sets the KeysWithNoncompliantValues field's value. +func (s *ComplianceDetails) SetKeysWithNoncompliantValues(v []*string) *ComplianceDetails { + s.KeysWithNoncompliantValues = v + return s +} + +// SetNoncompliantKeys sets the NoncompliantKeys field's value. +func (s *ComplianceDetails) SetNoncompliantKeys(v []*string) *ComplianceDetails { + s.NoncompliantKeys = v + return s +} + +// The target of the operation is currently being modified by a different request. +// Try again later. +type ConcurrentModificationException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s ConcurrentModificationException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ConcurrentModificationException) GoString() string { + return s.String() +} + +func newErrorConcurrentModificationException(v protocol.ResponseMetadata) error { + return &ConcurrentModificationException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ConcurrentModificationException) Code() string { + return "ConcurrentModificationException" +} + +// Message returns the exception's message. +func (s *ConcurrentModificationException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ConcurrentModificationException) OrigErr() error { + return nil +} + +func (s *ConcurrentModificationException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ConcurrentModificationException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ConcurrentModificationException) RequestID() string { + return s.RespMetadata.RequestID +} + +// The request was denied because performing this operation violates a constraint. +// +// Some of the reasons in the following list might not apply to this specific +// operation. +// +// * You must meet the prerequisites for using tag policies. For information, +// see Prerequisites and Permissions for Using Tag Policies (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html) +// in the AWS Organizations User Guide. +// +// * You must enable the tag policies service principal (tagpolicies.tag.amazonaws.com) +// to integrate with AWS Organizations For information, see EnableAWSServiceAccess +// (http://docs.aws.amazon.com/organizations/latest/APIReference/API_EnableAWSServiceAccess.html). +// +// * You must have a tag policy attached to the organization root, an OU, +// or an account. +type ConstraintViolationException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s ConstraintViolationException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ConstraintViolationException) GoString() string { + return s.String() +} + +func newErrorConstraintViolationException(v protocol.ResponseMetadata) error { + return &ConstraintViolationException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ConstraintViolationException) Code() string { + return "ConstraintViolationException" +} + +// Message returns the exception's message. +func (s *ConstraintViolationException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ConstraintViolationException) OrigErr() error { + return nil +} + +func (s *ConstraintViolationException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ConstraintViolationException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ConstraintViolationException) RequestID() string { + return s.RespMetadata.RequestID +} + +type DescribeReportCreationInput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DescribeReportCreationInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeReportCreationInput) GoString() string { + return s.String() +} + +type DescribeReportCreationOutput struct { + _ struct{} `type:"structure"` + + // Details of the common errors that all operations return. + ErrorMessage *string `type:"string"` + + // The path to the Amazon S3 bucket where the report was stored on creation. + S3Location *string `type:"string"` + + // Reports the status of the operation. + // + // The operation status can be one of the following: + // + // * RUNNING - Report creation is in progress. + // + // * SUCCEEDED - Report creation is complete. You can open the report from + // the Amazon S3 bucket that you specified when you ran StartReportCreation. + // + // * FAILED - Report creation timed out or the Amazon S3 bucket is not accessible. + // + // * NO REPORT - No report was generated in the last 90 days. + Status *string `type:"string"` +} + +// String returns the string representation +func (s DescribeReportCreationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeReportCreationOutput) GoString() string { + return s.String() +} + +// SetErrorMessage sets the ErrorMessage field's value. +func (s *DescribeReportCreationOutput) SetErrorMessage(v string) *DescribeReportCreationOutput { + s.ErrorMessage = &v + return s +} + +// SetS3Location sets the S3Location field's value. +func (s *DescribeReportCreationOutput) SetS3Location(v string) *DescribeReportCreationOutput { + s.S3Location = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *DescribeReportCreationOutput) SetStatus(v string) *DescribeReportCreationOutput { + s.Status = &v + return s +} + +// Information about the errors that are returned for each failed resource. +// This information can include InternalServiceException and InvalidParameterException +// errors. It can also include any valid error code returned by the AWS service +// that hosts the resource that the ARN key represents. +// +// The following are common error codes that you might receive from other AWS +// services: +// +// * InternalServiceException – This can mean that the Resource Groups +// Tagging API didn't receive a response from another AWS service. It can +// also mean the the resource type in the request is not supported by the +// Resource Groups Tagging API. In these cases, it's safe to retry the request +// and then call GetResources (http://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/API_GetResources.html) +// to verify the changes. +// +// * AccessDeniedException – This can mean that you need permission to +// calling tagging operations in the AWS service that contains the resource. +// For example, to use the Resource Groups Tagging API to tag a CloudWatch +// alarm resource, you need permission to call TagResources (http://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/API_TagResources.html) +// and TagResource (http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_TagResource.html) +// in the CloudWatch API. +// +// For more information on errors that are generated from other AWS services, +// see the documentation for that service. +type FailureInfo struct { + _ struct{} `type:"structure"` + + // The code of the common error. Valid values include InternalServiceException, + // InvalidParameterException, and any valid error code returned by the AWS service + // that hosts the resource that you want to tag. + ErrorCode *string `type:"string" enum:"ErrorCode"` + + // The message of the common error. + ErrorMessage *string `type:"string"` + + // The HTTP status code of the common error. + StatusCode *int64 `type:"integer"` +} + +// String returns the string representation +func (s FailureInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FailureInfo) GoString() string { + return s.String() +} + +// SetErrorCode sets the ErrorCode field's value. +func (s *FailureInfo) SetErrorCode(v string) *FailureInfo { + s.ErrorCode = &v + return s +} + +// SetErrorMessage sets the ErrorMessage field's value. +func (s *FailureInfo) SetErrorMessage(v string) *FailureInfo { + s.ErrorMessage = &v + return s +} + +// SetStatusCode sets the StatusCode field's value. +func (s *FailureInfo) SetStatusCode(v int64) *FailureInfo { + s.StatusCode = &v + return s +} + +type GetComplianceSummaryInput struct { + _ struct{} `type:"structure"` + + // A list of attributes to group the counts of noncompliant resources by. If + // supplied, the counts are sorted by those attributes. + GroupBy []*string `type:"list"` + + // A limit that restricts the number of results that are returned per page. + MaxResults *int64 `min:"1" type:"integer"` + + // A string that indicates that additional data is available. Leave this value + // empty for your initial request. If the response includes a PaginationToken, + // use that string for this value to request an additional page of data. + PaginationToken *string `type:"string"` + + // A list of Regions to limit the output by. If you use this parameter, the + // count of returned noncompliant resources includes only resources in the specified + // Regions. + RegionFilters []*string `min:"1" type:"list"` + + // The constraints on the resources that you want returned. The format of each + // resource type is service[:resourceType]. For example, specifying a resource + // type of ec2 returns all Amazon EC2 resources (which includes EC2 instances). + // Specifying a resource type of ec2:instance returns only EC2 instances. + // + // The string for each service name and resource type is the same as that embedded + // in a resource's Amazon Resource Name (ARN). Consult the AWS General Reference + // for the following: + // + // * For a list of service name strings, see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces). + // + // * For resource type strings, see Example ARNs (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arns-syntax). + // + // * For more information about ARNs, see Amazon Resource Names (ARNs) and + // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). + // + // You can specify multiple resource types by using an array. The array can + // include up to 100 items. Note that the length constraint requirement applies + // to each resource type filter. + ResourceTypeFilters []*string `type:"list"` + + // A list of tag keys to limit the output by. If you use this parameter, the + // count of returned noncompliant resources includes only resources that have + // the specified tag keys. + TagKeyFilters []*string `min:"1" type:"list"` + + // The target identifiers (usually, specific account IDs) to limit the output + // by. If you use this parameter, the count of returned noncompliant resources + // includes only resources with the specified target IDs. + TargetIdFilters []*string `min:"1" type:"list"` +} + +// String returns the string representation +func (s GetComplianceSummaryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetComplianceSummaryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetComplianceSummaryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetComplianceSummaryInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.RegionFilters != nil && len(s.RegionFilters) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RegionFilters", 1)) + } + if s.TagKeyFilters != nil && len(s.TagKeyFilters) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TagKeyFilters", 1)) + } + if s.TargetIdFilters != nil && len(s.TargetIdFilters) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TargetIdFilters", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGroupBy sets the GroupBy field's value. +func (s *GetComplianceSummaryInput) SetGroupBy(v []*string) *GetComplianceSummaryInput { + s.GroupBy = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetComplianceSummaryInput) SetMaxResults(v int64) *GetComplianceSummaryInput { + s.MaxResults = &v + return s +} + +// SetPaginationToken sets the PaginationToken field's value. +func (s *GetComplianceSummaryInput) SetPaginationToken(v string) *GetComplianceSummaryInput { + s.PaginationToken = &v + return s +} + +// SetRegionFilters sets the RegionFilters field's value. +func (s *GetComplianceSummaryInput) SetRegionFilters(v []*string) *GetComplianceSummaryInput { + s.RegionFilters = v + return s +} + +// SetResourceTypeFilters sets the ResourceTypeFilters field's value. +func (s *GetComplianceSummaryInput) SetResourceTypeFilters(v []*string) *GetComplianceSummaryInput { + s.ResourceTypeFilters = v + return s +} + +// SetTagKeyFilters sets the TagKeyFilters field's value. +func (s *GetComplianceSummaryInput) SetTagKeyFilters(v []*string) *GetComplianceSummaryInput { + s.TagKeyFilters = v + return s +} + +// SetTargetIdFilters sets the TargetIdFilters field's value. +func (s *GetComplianceSummaryInput) SetTargetIdFilters(v []*string) *GetComplianceSummaryInput { + s.TargetIdFilters = v + return s +} + +type GetComplianceSummaryOutput struct { + _ struct{} `type:"structure"` + + // A string that indicates that the response contains more data than can be + // returned in a single response. To receive additional data, specify this string + // for the PaginationToken value in a subsequent request. + PaginationToken *string `type:"string"` + + // A table that shows counts of noncompliant resources. + SummaryList []*Summary `type:"list"` +} + +// String returns the string representation +func (s GetComplianceSummaryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetComplianceSummaryOutput) GoString() string { + return s.String() +} + +// SetPaginationToken sets the PaginationToken field's value. +func (s *GetComplianceSummaryOutput) SetPaginationToken(v string) *GetComplianceSummaryOutput { + s.PaginationToken = &v + return s +} + +// SetSummaryList sets the SummaryList field's value. +func (s *GetComplianceSummaryOutput) SetSummaryList(v []*Summary) *GetComplianceSummaryOutput { + s.SummaryList = v + return s +} + +type GetResourcesInput struct { + _ struct{} `type:"structure"` + + // Specifies whether to exclude resources that are compliant with the tag policy. + // Set this to true if you are interested in retrieving information on noncompliant + // resources only. + // + // You can use this parameter only if the IncludeComplianceDetails parameter + // is also set to true. + ExcludeCompliantResources *bool `type:"boolean"` + + // Specifies whether to include details regarding the compliance with the effective + // tag policy. Set this to true to determine whether resources are compliant + // with the tag policy and to get details. + IncludeComplianceDetails *bool `type:"boolean"` + + // A string that indicates that additional data is available. Leave this value + // empty for your initial request. If the response includes a PaginationToken, + // use that string for this value to request an additional page of data. + PaginationToken *string `type:"string"` + + // The constraints on the resources that you want returned. The format of each + // resource type is service[:resourceType]. For example, specifying a resource + // type of ec2 returns all Amazon EC2 resources (which includes EC2 instances). + // Specifying a resource type of ec2:instance returns only EC2 instances. + // + // The string for each service name and resource type is the same as that embedded + // in a resource's Amazon Resource Name (ARN). Consult the AWS General Reference + // for the following: + // + // * For a list of service name strings, see AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces). + // + // * For resource type strings, see Example ARNs (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arns-syntax). + // + // * For more information about ARNs, see Amazon Resource Names (ARNs) and + // AWS Service Namespaces (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). + // + // You can specify multiple resource types by using an array. The array can + // include up to 100 items. Note that the length constraint requirement applies + // to each resource type filter. + ResourceTypeFilters []*string `type:"list"` + + // A limit that restricts the number of resources returned by GetResources in + // paginated output. You can set ResourcesPerPage to a minimum of 1 item and + // the maximum of 100 items. + ResourcesPerPage *int64 `type:"integer"` + + // A list of TagFilters (keys and values). Each TagFilter specified must contain + // a key with values as optional. A request can include up to 50 keys, and each + // key can include up to 20 values. + // + // Note the following when deciding how to use TagFilters: + // + // * If you do specify a TagFilter, the response returns only those resources + // that are currently associated with the specified tag. + // + // * If you don't specify a TagFilter, the response includes all resources + // that were ever associated with tags. Resources that currently don't have + // associated tags are shown with an empty tag set, like this: "Tags": []. + // + // * If you specify more than one filter in a single request, the response + // returns only those resources that satisfy all specified filters. + // + // * If you specify a filter that contains more than one value for a key, + // the response returns resources that match any of the specified values + // for that key. + // + // * If you don't specify any values for a key, the response returns resources + // that are tagged with that key irrespective of the value. For example, + // for filters: filter1 = {key1, {value1}}, filter2 = {key2, {value2,value3,value4}} + // , filter3 = {key3}: GetResources( {filter1} ) returns resources tagged + // with key1=value1 GetResources( {filter2} ) returns resources tagged with + // key2=value2 or key2=value3 or key2=value4 GetResources( {filter3} ) returns + // resources tagged with any tag containing key3 as its tag key, irrespective + // of its value GetResources( {filter1,filter2,filter3} ) returns resources + // tagged with ( key1=value1) and ( key2=value2 or key2=value3 or key2=value4) + // and (key3, irrespective of the value) + TagFilters []*TagFilter `type:"list"` + + // AWS recommends using ResourcesPerPage instead of this parameter. + // + // A limit that restricts the number of tags (key and value pairs) returned + // by GetResources in paginated output. A resource with no tags is counted as + // having one tag (one key and value pair). + // + // GetResources does not split a resource and its associated tags across pages. + // If the specified TagsPerPage would cause such a break, a PaginationToken + // is returned in place of the affected resource and its tags. Use that token + // in another request to get the remaining data. For example, if you specify + // a TagsPerPage of 100 and the account has 22 resources with 10 tags each (meaning + // that each resource has 10 key and value pairs), the output will consist of + // three pages. The first page displays the first 10 resources, each with its + // 10 tags. The second page displays the next 10 resources, each with its 10 + // tags. The third page displays the remaining 2 resources, each with its 10 + // tags. + // + // You can set TagsPerPage to a minimum of 100 items and the maximum of 500 + // items. + TagsPerPage *int64 `type:"integer"` +} + +// String returns the string representation +func (s GetResourcesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetResourcesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetResourcesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetResourcesInput"} + if s.TagFilters != nil { + for i, v := range s.TagFilters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TagFilters", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetExcludeCompliantResources sets the ExcludeCompliantResources field's value. +func (s *GetResourcesInput) SetExcludeCompliantResources(v bool) *GetResourcesInput { + s.ExcludeCompliantResources = &v + return s +} + +// SetIncludeComplianceDetails sets the IncludeComplianceDetails field's value. +func (s *GetResourcesInput) SetIncludeComplianceDetails(v bool) *GetResourcesInput { + s.IncludeComplianceDetails = &v + return s +} + +// SetPaginationToken sets the PaginationToken field's value. +func (s *GetResourcesInput) SetPaginationToken(v string) *GetResourcesInput { + s.PaginationToken = &v + return s +} + +// SetResourceTypeFilters sets the ResourceTypeFilters field's value. +func (s *GetResourcesInput) SetResourceTypeFilters(v []*string) *GetResourcesInput { + s.ResourceTypeFilters = v + return s +} + +// SetResourcesPerPage sets the ResourcesPerPage field's value. +func (s *GetResourcesInput) SetResourcesPerPage(v int64) *GetResourcesInput { + s.ResourcesPerPage = &v + return s +} + +// SetTagFilters sets the TagFilters field's value. +func (s *GetResourcesInput) SetTagFilters(v []*TagFilter) *GetResourcesInput { + s.TagFilters = v + return s +} + +// SetTagsPerPage sets the TagsPerPage field's value. +func (s *GetResourcesInput) SetTagsPerPage(v int64) *GetResourcesInput { + s.TagsPerPage = &v + return s +} + +type GetResourcesOutput struct { + _ struct{} `type:"structure"` + + // A string that indicates that the response contains more data than can be + // returned in a single response. To receive additional data, specify this string + // for the PaginationToken value in a subsequent request. + PaginationToken *string `type:"string"` + + // A list of resource ARNs and the tags (keys and values) associated with each. + ResourceTagMappingList []*ResourceTagMapping `type:"list"` +} + +// String returns the string representation +func (s GetResourcesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetResourcesOutput) GoString() string { + return s.String() +} + +// SetPaginationToken sets the PaginationToken field's value. +func (s *GetResourcesOutput) SetPaginationToken(v string) *GetResourcesOutput { + s.PaginationToken = &v + return s +} + +// SetResourceTagMappingList sets the ResourceTagMappingList field's value. +func (s *GetResourcesOutput) SetResourceTagMappingList(v []*ResourceTagMapping) *GetResourcesOutput { + s.ResourceTagMappingList = v + return s +} + +type GetTagKeysInput struct { + _ struct{} `type:"structure"` + + // A string that indicates that additional data is available. Leave this value + // empty for your initial request. If the response includes a PaginationToken, + // use that string for this value to request an additional page of data. + PaginationToken *string `type:"string"` +} + +// String returns the string representation +func (s GetTagKeysInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetTagKeysInput) GoString() string { + return s.String() +} + +// SetPaginationToken sets the PaginationToken field's value. +func (s *GetTagKeysInput) SetPaginationToken(v string) *GetTagKeysInput { + s.PaginationToken = &v + return s +} + +type GetTagKeysOutput struct { + _ struct{} `type:"structure"` + + // A string that indicates that the response contains more data than can be + // returned in a single response. To receive additional data, specify this string + // for the PaginationToken value in a subsequent request. + PaginationToken *string `type:"string"` + + // A list of all tag keys in the AWS account. + TagKeys []*string `type:"list"` +} + +// String returns the string representation +func (s GetTagKeysOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetTagKeysOutput) GoString() string { + return s.String() +} + +// SetPaginationToken sets the PaginationToken field's value. +func (s *GetTagKeysOutput) SetPaginationToken(v string) *GetTagKeysOutput { + s.PaginationToken = &v + return s +} + +// SetTagKeys sets the TagKeys field's value. +func (s *GetTagKeysOutput) SetTagKeys(v []*string) *GetTagKeysOutput { + s.TagKeys = v + return s +} + +type GetTagValuesInput struct { + _ struct{} `type:"structure"` + + // The key for which you want to list all existing values in the specified Region + // for the AWS account. + // + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` + + // A string that indicates that additional data is available. Leave this value + // empty for your initial request. If the response includes a PaginationToken, + // use that string for this value to request an additional page of data. + PaginationToken *string `type:"string"` +} + +// String returns the string representation +func (s GetTagValuesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetTagValuesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetTagValuesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetTagValuesInput"} + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKey sets the Key field's value. +func (s *GetTagValuesInput) SetKey(v string) *GetTagValuesInput { + s.Key = &v + return s +} + +// SetPaginationToken sets the PaginationToken field's value. +func (s *GetTagValuesInput) SetPaginationToken(v string) *GetTagValuesInput { + s.PaginationToken = &v + return s +} + +type GetTagValuesOutput struct { + _ struct{} `type:"structure"` + + // A string that indicates that the response contains more data than can be + // returned in a single response. To receive additional data, specify this string + // for the PaginationToken value in a subsequent request. + PaginationToken *string `type:"string"` + + // A list of all tag values for the specified key in the AWS account. + TagValues []*string `type:"list"` +} + +// String returns the string representation +func (s GetTagValuesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetTagValuesOutput) GoString() string { + return s.String() +} + +// SetPaginationToken sets the PaginationToken field's value. +func (s *GetTagValuesOutput) SetPaginationToken(v string) *GetTagValuesOutput { + s.PaginationToken = &v + return s +} + +// SetTagValues sets the TagValues field's value. +func (s *GetTagValuesOutput) SetTagValues(v []*string) *GetTagValuesOutput { + s.TagValues = v + return s +} + +// The request processing failed because of an unknown error, exception, or +// failure. You can retry the request. +type InternalServiceException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s InternalServiceException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InternalServiceException) GoString() string { + return s.String() +} + +func newErrorInternalServiceException(v protocol.ResponseMetadata) error { + return &InternalServiceException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InternalServiceException) Code() string { + return "InternalServiceException" +} + +// Message returns the exception's message. +func (s *InternalServiceException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InternalServiceException) OrigErr() error { + return nil +} + +func (s *InternalServiceException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InternalServiceException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InternalServiceException) RequestID() string { + return s.RespMetadata.RequestID +} + +// This error indicates one of the following: +// +// * A parameter is missing. +// +// * A malformed string was supplied for the request parameter. +// +// * An out-of-range value was supplied for the request parameter. +// +// * The target ID is invalid, unsupported, or doesn't exist. +// +// * You can't access the Amazon S3 bucket for report storage. For more information, +// see Additional Requirements for Organization-wide Tag Compliance Reports +// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html#bucket-policies-org-report) +// in the AWS Organizations User Guide. +type InvalidParameterException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s InvalidParameterException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InvalidParameterException) GoString() string { + return s.String() +} + +func newErrorInvalidParameterException(v protocol.ResponseMetadata) error { + return &InvalidParameterException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InvalidParameterException) Code() string { + return "InvalidParameterException" +} + +// Message returns the exception's message. +func (s *InvalidParameterException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InvalidParameterException) OrigErr() error { + return nil +} + +func (s *InvalidParameterException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InvalidParameterException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InvalidParameterException) RequestID() string { + return s.RespMetadata.RequestID +} + +// A PaginationToken is valid for a maximum of 15 minutes. Your request was +// denied because the specified PaginationToken has expired. +type PaginationTokenExpiredException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s PaginationTokenExpiredException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PaginationTokenExpiredException) GoString() string { + return s.String() +} + +func newErrorPaginationTokenExpiredException(v protocol.ResponseMetadata) error { + return &PaginationTokenExpiredException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *PaginationTokenExpiredException) Code() string { + return "PaginationTokenExpiredException" +} + +// Message returns the exception's message. +func (s *PaginationTokenExpiredException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *PaginationTokenExpiredException) OrigErr() error { + return nil +} + +func (s *PaginationTokenExpiredException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *PaginationTokenExpiredException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *PaginationTokenExpiredException) RequestID() string { + return s.RespMetadata.RequestID +} + +// A list of resource ARNs and the tags (keys and values) that are associated +// with each. +type ResourceTagMapping struct { + _ struct{} `type:"structure"` + + // Information that shows whether a resource is compliant with the effective + // tag policy, including details on any noncompliant tag keys. + ComplianceDetails *ComplianceDetails `type:"structure"` + + // The ARN of the resource. + ResourceARN *string `min:"1" type:"string"` + + // The tags that have been applied to one or more AWS resources. + Tags []*Tag `type:"list"` +} + +// String returns the string representation +func (s ResourceTagMapping) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResourceTagMapping) GoString() string { + return s.String() +} + +// SetComplianceDetails sets the ComplianceDetails field's value. +func (s *ResourceTagMapping) SetComplianceDetails(v *ComplianceDetails) *ResourceTagMapping { + s.ComplianceDetails = v + return s +} + +// SetResourceARN sets the ResourceARN field's value. +func (s *ResourceTagMapping) SetResourceARN(v string) *ResourceTagMapping { + s.ResourceARN = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *ResourceTagMapping) SetTags(v []*Tag) *ResourceTagMapping { + s.Tags = v + return s +} + +type StartReportCreationInput struct { + _ struct{} `type:"structure"` + + // The name of the Amazon S3 bucket where the report will be stored; for example: + // + // awsexamplebucket + // + // For more information on S3 bucket requirements, including an example bucket + // policy, see the example S3 bucket policy on this page. + // + // S3Bucket is a required field + S3Bucket *string `min:"3" type:"string" required:"true"` +} + +// String returns the string representation +func (s StartReportCreationInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StartReportCreationInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StartReportCreationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StartReportCreationInput"} + if s.S3Bucket == nil { + invalidParams.Add(request.NewErrParamRequired("S3Bucket")) + } + if s.S3Bucket != nil && len(*s.S3Bucket) < 3 { + invalidParams.Add(request.NewErrParamMinLen("S3Bucket", 3)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetS3Bucket sets the S3Bucket field's value. +func (s *StartReportCreationInput) SetS3Bucket(v string) *StartReportCreationInput { + s.S3Bucket = &v + return s +} + +type StartReportCreationOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s StartReportCreationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StartReportCreationOutput) GoString() string { + return s.String() +} + +// A count of noncompliant resources. +type Summary struct { + _ struct{} `type:"structure"` + + // The timestamp that shows when this summary was generated in this Region. + LastUpdated *string `type:"string"` + + // The count of noncompliant resources. + NonCompliantResources *int64 `type:"long"` + + // The AWS Region that the summary applies to. + Region *string `min:"1" type:"string"` + + // The AWS resource type. + ResourceType *string `type:"string"` + + // The account identifier or the root identifier of the organization. If you + // don't know the root ID, you can call the AWS Organizations ListRoots (http://docs.aws.amazon.com/organizations/latest/APIReference/API_ListRoots.html) + // API. + TargetId *string `min:"6" type:"string"` + + // Whether the target is an account, an OU, or the organization root. + TargetIdType *string `type:"string" enum:"TargetIdType"` +} + +// String returns the string representation +func (s Summary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Summary) GoString() string { + return s.String() +} + +// SetLastUpdated sets the LastUpdated field's value. +func (s *Summary) SetLastUpdated(v string) *Summary { + s.LastUpdated = &v + return s +} + +// SetNonCompliantResources sets the NonCompliantResources field's value. +func (s *Summary) SetNonCompliantResources(v int64) *Summary { + s.NonCompliantResources = &v + return s +} + +// SetRegion sets the Region field's value. +func (s *Summary) SetRegion(v string) *Summary { + s.Region = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *Summary) SetResourceType(v string) *Summary { + s.ResourceType = &v + return s +} + +// SetTargetId sets the TargetId field's value. +func (s *Summary) SetTargetId(v string) *Summary { + s.TargetId = &v + return s +} + +// SetTargetIdType sets the TargetIdType field's value. +func (s *Summary) SetTargetIdType(v string) *Summary { + s.TargetIdType = &v + return s +} + +// The metadata that you apply to AWS resources to help you categorize and organize +// them. Each tag consists of a key and a value, both of which you define. For +// more information, see Tagging AWS Resources (http://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) +// in the AWS General Reference. +type Tag struct { + _ struct{} `type:"structure"` + + // One part of a key-value pair that makes up a tag. A key is a general label + // that acts like a category for more specific tag values. + // + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` + + // One part of a key-value pair that make up a tag. A value acts as a descriptor + // within a tag category (key). The value can be empty or null. + // + // Value is a required field + Value *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s Tag) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Tag) GoString() string { + return s.String() +} + +// SetKey sets the Key field's value. +func (s *Tag) SetKey(v string) *Tag { + s.Key = &v + return s +} + +// SetValue sets the Value field's value. +func (s *Tag) SetValue(v string) *Tag { + s.Value = &v + return s +} + +// A list of tags (keys and values) that are used to specify the associated +// resources. +type TagFilter struct { + _ struct{} `type:"structure"` + + // One part of a key-value pair that makes up a tag. A key is a general label + // that acts like a category for more specific tag values. + Key *string `min:"1" type:"string"` + + // One part of a key-value pair that make up a tag. A value acts as a descriptor + // within a tag category (key). The value can be empty or null. + Values []*string `type:"list"` +} + +// String returns the string representation +func (s TagFilter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagFilter) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagFilter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagFilter"} + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKey sets the Key field's value. +func (s *TagFilter) SetKey(v string) *TagFilter { + s.Key = &v + return s +} + +// SetValues sets the Values field's value. +func (s *TagFilter) SetValues(v []*string) *TagFilter { + s.Values = v + return s +} + +type TagResourcesInput struct { + _ struct{} `type:"structure"` + + // A list of ARNs. An ARN (Amazon Resource Name) uniquely identifies a resource. + // For more information, see Amazon Resource Names (ARNs) and AWS Service Namespaces + // (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) + // in the AWS General Reference. + // + // ResourceARNList is a required field + ResourceARNList []*string `min:"1" type:"list" required:"true"` + + // The tags that you want to add to the specified resources. A tag consists + // of a key and a value that you define. + // + // Tags is a required field + Tags map[string]*string `min:"1" type:"map" required:"true"` +} + +// String returns the string representation +func (s TagResourcesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagResourcesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagResourcesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagResourcesInput"} + if s.ResourceARNList == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceARNList")) + } + if s.ResourceARNList != nil && len(s.ResourceARNList) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceARNList", 1)) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceARNList sets the ResourceARNList field's value. +func (s *TagResourcesInput) SetResourceARNList(v []*string) *TagResourcesInput { + s.ResourceARNList = v + return s +} + +// SetTags sets the Tags field's value. +func (s *TagResourcesInput) SetTags(v map[string]*string) *TagResourcesInput { + s.Tags = v + return s +} + +type TagResourcesOutput struct { + _ struct{} `type:"structure"` + + // A map containing a key-value pair for each failed item that couldn't be tagged. + // The key is the ARN of the failed resource. The value is a FailureInfo object + // that contains an error code, a status code, and an error message. If there + // are no errors, the FailedResourcesMap is empty. + FailedResourcesMap map[string]*FailureInfo `type:"map"` +} + +// String returns the string representation +func (s TagResourcesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagResourcesOutput) GoString() string { + return s.String() +} + +// SetFailedResourcesMap sets the FailedResourcesMap field's value. +func (s *TagResourcesOutput) SetFailedResourcesMap(v map[string]*FailureInfo) *TagResourcesOutput { + s.FailedResourcesMap = v + return s +} + +// The request was denied to limit the frequency of submitted requests. +type ThrottledException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s ThrottledException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ThrottledException) GoString() string { + return s.String() +} + +func newErrorThrottledException(v protocol.ResponseMetadata) error { + return &ThrottledException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ThrottledException) Code() string { + return "ThrottledException" +} + +// Message returns the exception's message. +func (s *ThrottledException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ThrottledException) OrigErr() error { + return nil +} + +func (s *ThrottledException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ThrottledException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ThrottledException) RequestID() string { + return s.RespMetadata.RequestID +} + +type UntagResourcesInput struct { + _ struct{} `type:"structure"` + + // A list of ARNs. An ARN (Amazon Resource Name) uniquely identifies a resource. + // For more information, see Amazon Resource Names (ARNs) and AWS Service Namespaces + // (http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) + // in the AWS General Reference. + // + // ResourceARNList is a required field + ResourceARNList []*string `min:"1" type:"list" required:"true"` + + // A list of the tag keys that you want to remove from the specified resources. + // + // TagKeys is a required field + TagKeys []*string `min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s UntagResourcesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourcesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UntagResourcesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UntagResourcesInput"} + if s.ResourceARNList == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceARNList")) + } + if s.ResourceARNList != nil && len(s.ResourceARNList) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceARNList", 1)) + } + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + if s.TagKeys != nil && len(s.TagKeys) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TagKeys", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceARNList sets the ResourceARNList field's value. +func (s *UntagResourcesInput) SetResourceARNList(v []*string) *UntagResourcesInput { + s.ResourceARNList = v + return s +} + +// SetTagKeys sets the TagKeys field's value. +func (s *UntagResourcesInput) SetTagKeys(v []*string) *UntagResourcesInput { + s.TagKeys = v + return s +} + +type UntagResourcesOutput struct { + _ struct{} `type:"structure"` + + // Details of resources that could not be untagged. An error code, status code, + // and error message are returned for each failed item. + FailedResourcesMap map[string]*FailureInfo `type:"map"` +} + +// String returns the string representation +func (s UntagResourcesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourcesOutput) GoString() string { + return s.String() +} + +// SetFailedResourcesMap sets the FailedResourcesMap field's value. +func (s *UntagResourcesOutput) SetFailedResourcesMap(v map[string]*FailureInfo) *UntagResourcesOutput { + s.FailedResourcesMap = v + return s +} + +const ( + // ErrorCodeInternalServiceException is a ErrorCode enum value + ErrorCodeInternalServiceException = "InternalServiceException" + + // ErrorCodeInvalidParameterException is a ErrorCode enum value + ErrorCodeInvalidParameterException = "InvalidParameterException" +) + +// ErrorCode_Values returns all elements of the ErrorCode enum +func ErrorCode_Values() []string { + return []string{ + ErrorCodeInternalServiceException, + ErrorCodeInvalidParameterException, + } +} + +const ( + // GroupByAttributeTargetId is a GroupByAttribute enum value + GroupByAttributeTargetId = "TARGET_ID" + + // GroupByAttributeRegion is a GroupByAttribute enum value + GroupByAttributeRegion = "REGION" + + // GroupByAttributeResourceType is a GroupByAttribute enum value + GroupByAttributeResourceType = "RESOURCE_TYPE" +) + +// GroupByAttribute_Values returns all elements of the GroupByAttribute enum +func GroupByAttribute_Values() []string { + return []string{ + GroupByAttributeTargetId, + GroupByAttributeRegion, + GroupByAttributeResourceType, + } +} + +const ( + // TargetIdTypeAccount is a TargetIdType enum value + TargetIdTypeAccount = "ACCOUNT" + + // TargetIdTypeOu is a TargetIdType enum value + TargetIdTypeOu = "OU" + + // TargetIdTypeRoot is a TargetIdType enum value + TargetIdTypeRoot = "ROOT" +) + +// TargetIdType_Values returns all elements of the TargetIdType enum +func TargetIdType_Values() []string { + return []string{ + TargetIdTypeAccount, + TargetIdTypeOu, + TargetIdTypeRoot, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/doc.go b/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/doc.go new file mode 100644 index 00000000000..1c60a1c7c14 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/doc.go @@ -0,0 +1,311 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package resourcegroupstaggingapi provides the client and types for making API +// requests to AWS Resource Groups Tagging API. +// +// This guide describes the API operations for the resource groups tagging. +// +// A tag is a label that you assign to an AWS resource. A tag consists of a +// key and a value, both of which you define. For example, if you have two Amazon +// EC2 instances, you might assign both a tag key of "Stack." But the value +// of "Stack" might be "Testing" for one and "Production" for the other. +// +// Do not store personally identifiable information (PII) or other confidential +// or sensitive information in tags. We use tags to provide you with billing +// and administration services. Tags are not intended to be used for private +// or sensitive data. +// +// Tagging can help you organize your resources and enables you to simplify +// resource management, access management and cost allocation. +// +// You can use the resource groups tagging API operations to complete the following +// tasks: +// +// * Tag and untag supported resources located in the specified Region for +// the AWS account. +// +// * Use tag-based filters to search for resources located in the specified +// Region for the AWS account. +// +// * List all existing tag keys in the specified Region for the AWS account. +// +// * List all existing values for the specified key in the specified Region +// for the AWS account. +// +// To use resource groups tagging API operations, you must add the following +// permissions to your IAM policy: +// +// * tag:GetResources +// +// * tag:TagResources +// +// * tag:UntagResources +// +// * tag:GetTagKeys +// +// * tag:GetTagValues +// +// You'll also need permissions to access the resources of individual services +// so that you can tag and untag those resources. +// +// For more information on IAM policies, see Managing IAM Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html) +// in the IAM User Guide. +// +// Services that support the Resource Groups Tagging API +// +// You can use the Resource Groups Tagging API to tag resources for the following +// AWS services. +// +// * Alexa for Business (a4b) (https://docs.aws.amazon.com/a4b) +// +// * API Gateway (https://docs.aws.amazon.com/apigateway) +// +// * Amazon AppStream (https://docs.aws.amazon.com/appstream2) +// +// * AWS AppSync (https://docs.aws.amazon.com/appsync) +// +// * AWS App Mesh (https://docs.aws.amazon.com/app-mesh) +// +// * Amazon Athena (https://docs.aws.amazon.com/athena) +// +// * Amazon Aurora (https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide) +// +// * AWS Backup (https://docs.aws.amazon.com/aws-backup) +// +// * AWS Certificate Manager (https://docs.aws.amazon.com/acm) +// +// * AWS Certificate Manager Private CA (https://docs.aws.amazon.com/acm) +// +// * Amazon Cloud Directory (https://docs.aws.amazon.com/clouddirectory) +// +// * AWS Cloud Map (https://docs.aws.amazon.com/cloud-map) +// +// * AWS CloudFormation (https://docs.aws.amazon.com/cloudformation) +// +// * Amazon CloudFront (https://docs.aws.amazon.com/cloudfront) +// +// * AWS CloudHSM (https://docs.aws.amazon.com/cloudhsm) +// +// * AWS CloudTrail (https://docs.aws.amazon.com/cloudtrail) +// +// * Amazon CloudWatch (alarms only) (https://docs.aws.amazon.com/cloudwatch) +// +// * Amazon CloudWatch Events (https://docs.aws.amazon.com/cloudwatch/?id=docs_gateway#amazon-cloudwatch-events) +// +// * Amazon CloudWatch Logs (https://docs.aws.amazon.com/cloudwatch/?id=docs_gateway#amazon-cloudwatch-logs) +// +// * Amazon Cloudwatch Synthetics (https://docs.aws.amazon.com/cloudwatch) +// +// * AWS CodeBuild (https://docs.aws.amazon.com/codebuild) +// +// * AWS CodeCommit (https://docs.aws.amazon.com/codecommit) +// +// * AWS CodePipeline (https://docs.aws.amazon.com/codepipeline) +// +// * AWS CodeStar (https://docs.aws.amazon.com/codestar) +// +// * AWS CodeStar Connections (https://docs.aws.amazon.com/codestar-connections/latest/APIReference/) +// +// * Amazon Cognito Identity (https://docs.aws.amazon.com/cognito) +// +// * Amazon Cognito User Pools (https://docs.aws.amazon.com/cognito) +// +// * Amazon Comprehend (https://docs.aws.amazon.com/comprehend) +// +// * AWS Config (https://docs.aws.amazon.com/config) +// +// * Amazon Connect (http://aws.amazon.com/connect/resources/?whats-new-cards#Documentation) +// +// * AWS Data Exchange (https://docs.aws.amazon.com/data-exchange) +// +// * AWS Data Pipeline (https://docs.aws.amazon.com/data-pipeline) +// +// * AWS Database Migration Service (https://docs.aws.amazon.com/dms) +// +// * AWS DataSync (https://docs.aws.amazon.com/datasync) +// +// * AWS Device Farm (https://docs.aws.amazon.com/devicefarm) +// +// * AWS Direct Connect (https://docs.aws.amazon.com/directconnect) +// +// * AWS Directory Service (https://docs.aws.amazon.com/directory-service) +// +// * Amazon DynamoDB (https://docs.aws.amazon.com/dynamodb) +// +// * Amazon EBS (https://docs.aws.amazon.com/ebs) +// +// * Amazon EC2 (https://docs.aws.amazon.com/ec2) +// +// * EC2 Image Builder (https://docs.aws.amazon.com/imagebuilder) +// +// * Amazon ECR (https://docs.aws.amazon.com/ecr) +// +// * Amazon ECS (https://docs.aws.amazon.com/ecs) +// +// * Amazon EKS (https://docs.aws.amazon.com/eks) +// +// * AWS Elastic Beanstalk (https://docs.aws.amazon.com/elastic-beanstalk) +// +// * Amazon Elastic File System (https://docs.aws.amazon.com/efs) +// +// * Elastic Load Balancing (https://docs.aws.amazon.com/elasticloadbalancing) +// +// * Amazon ElastiCache (https://docs.aws.amazon.com/elasticache) +// +// * Amazon Elasticsearch Service (https://docs.aws.amazon.com/elasticsearch-service) +// +// * AWS Elemental MediaLive (https://docs.aws.amazon.com/medialive) +// +// * AWS Elemental MediaPackage (https://docs.aws.amazon.com/mediapackage) +// +// * AWS Elemental MediaPackage VoD (https://docs.aws.amazon.com/mediapackage) +// +// * AWS Elemental MediaTailor (https://docs.aws.amazon.com/mediatailor) +// +// * Amazon EMR (https://docs.aws.amazon.com/emr) +// +// * Amazon EventBridge Schema (https://docs.aws.amazon.com/eventbridge) +// +// * AWS Firewall Manager (https://docs.aws.amazon.com/firewall-manager) +// +// * Amazon FSx (https://docs.aws.amazon.com/fsx) +// +// * Amazon S3 Glacier (https://docs.aws.amazon.com/s3/?id=docs_gateway#amazon-s3-glacier) +// +// * AWS Global Accelerator (https://docs.aws.amazon.com/global-accelerator) +// +// * AWS Ground Station (https://docs.aws.amazon.com/ground-station) +// +// * AWS Glue (https://docs.aws.amazon.com/glue) +// +// * Amazon GuardDuty (https://docs.aws.amazon.com/guardduty) +// +// * Amazon Inspector (https://docs.aws.amazon.com/inspector) +// +// * AWS IoT Analytics (https://docs.aws.amazon.com/iotanalytics) +// +// * AWS IoT Core (https://docs.aws.amazon.com/iot) +// +// * AWS IoT Device Defender (https://docs.aws.amazon.com/iot-device-defender) +// +// * AWS IoT Device Management (https://docs.aws.amazon.com/iot-device-management) +// +// * AWS IoT Events (https://docs.aws.amazon.com/iotevents) +// +// * AWS IoT Greengrass (https://docs.aws.amazon.com/greengrass) +// +// * AWS IoT 1-Click (https://docs.aws.amazon.com/iot-1-click) +// +// * AWS IoT Sitewise (https://docs.aws.amazon.com/iot-sitewise) +// +// * AWS IoT Things Graph (https://docs.aws.amazon.com/thingsgraph) +// +// * Amazon Kendra (https://docs.aws.amazon.com/kendra) +// +// * AWS Key Management Service (https://docs.aws.amazon.com/kms) +// +// * Amazon Kinesis (https://docs.aws.amazon.com/kinesis) +// +// * Amazon Kinesis Data Analytics (https://docs.aws.amazon.com/kinesis/?id=docs_gateway#amazon-kinesis-data-analytics) +// +// * Amazon Kinesis Data Firehose (https://docs.aws.amazon.com/kinesis/?id=docs_gateway#amazon-kinesis-data-firehose) +// +// * AWS Lambda (https://docs.aws.amazon.com/lambda) +// +// * Amazon Lex (https://docs.aws.amazon.com/lex) +// +// * AWS License Manager (https://docs.aws.amazon.com/license-manager) +// +// * Amazon Macie (https://docs.aws.amazon.com/macie) +// +// * Amazon Machine Learning (https://docs.aws.amazon.com/machine-learning) +// +// * Amazon MQ (https://docs.aws.amazon.com/amazon-mq) +// +// * Amazon MSK (https://docs.aws.amazon.com/msk) +// +// * Amazon Neptune (https://docs.aws.amazon.com/neptune) +// +// * AWS OpsWorks (https://docs.aws.amazon.com/opsworks) +// +// * AWS OpsWorks CM (https://docs.aws.amazon.com/opsworks) +// +// * AWS Organizations (https://docs.aws.amazon.com/organizations) +// +// * Amazon Pinpoint (https://docs.aws.amazon.com/pinpoint) +// +// * Amazon Quantum Ledger Database (QLDB) (https://docs.aws.amazon.com/qldb) +// +// * Amazon RDS (https://docs.aws.amazon.com/rds) +// +// * Amazon Redshift (https://docs.aws.amazon.com/redshift) +// +// * AWS Resource Access Manager (https://docs.aws.amazon.com/ram) +// +// * AWS Resource Groups (https://docs.aws.amazon.com/ARG) +// +// * AWS RoboMaker (https://docs.aws.amazon.com/robomaker) +// +// * Amazon Route 53 (https://docs.aws.amazon.com/route53) +// +// * Amazon Route 53 Resolver (https://docs.aws.amazon.com/route53) +// +// * Amazon S3 (buckets only) (https://docs.aws.amazon.com/s3) +// +// * Amazon SageMaker (https://docs.aws.amazon.com/sagemaker) +// +// * Savings Plans (https://docs.aws.amazon.com/savingsplans) +// +// * AWS Secrets Manager (https://docs.aws.amazon.com/secretsmanager) +// +// * AWS Security Hub (https://docs.aws.amazon.com/securityhub) +// +// * AWS Service Catalog (https://docs.aws.amazon.com/servicecatalog) +// +// * Amazon Simple Email Service (SES) (https://docs.aws.amazon.com/ses) +// +// * Amazon Simple Notification Service (SNS) (https://docs.aws.amazon.com/sns) +// +// * Amazon Simple Queue Service (SQS) (https://docs.aws.amazon.com/sqs) +// +// * Amazon Simple Workflow Service (https://docs.aws.amazon.com/swf) +// +// * AWS Step Functions (https://docs.aws.amazon.com/step-functions) +// +// * AWS Storage Gateway (https://docs.aws.amazon.com/storagegateway) +// +// * AWS Systems Manager (https://docs.aws.amazon.com/systems-manager) +// +// * AWS Transfer for SFTP (https://docs.aws.amazon.com/transfer) +// +// * Amazon VPC (https://docs.aws.amazon.com/vpc) +// +// * AWS WAFv2 (https://docs.aws.amazon.com/waf) +// +// * AWS WAF Regional (https://docs.aws.amazon.com/waf) +// +// * Amazon WorkLink (https://docs.aws.amazon.com/worklink) +// +// * Amazon WorkSpaces (https://docs.aws.amazon.com/workspaces) +// +// See https://docs.aws.amazon.com/goto/WebAPI/resourcegroupstaggingapi-2017-01-26 for more information on this service. +// +// See resourcegroupstaggingapi package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/resourcegroupstaggingapi/ +// +// Using the Client +// +// To contact AWS Resource Groups Tagging API with the SDK use the New function to create +// a new service client. With that client you can make API requests to the service. +// These clients are safe to use concurrently. +// +// See the SDK's documentation for more information on how to use the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws.Config documentation for more information on configuring SDK clients. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the AWS Resource Groups Tagging API client ResourceGroupsTaggingAPI for more +// information on creating client for this service. +// https://docs.aws.amazon.com/sdk-for-go/api/service/resourcegroupstaggingapi/#New +package resourcegroupstaggingapi diff --git a/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/errors.go b/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/errors.go new file mode 100644 index 00000000000..0f4fa113639 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/errors.go @@ -0,0 +1,85 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package resourcegroupstaggingapi + +import ( + "github.com/aws/aws-sdk-go/private/protocol" +) + +const ( + + // ErrCodeConcurrentModificationException for service response error code + // "ConcurrentModificationException". + // + // The target of the operation is currently being modified by a different request. + // Try again later. + ErrCodeConcurrentModificationException = "ConcurrentModificationException" + + // ErrCodeConstraintViolationException for service response error code + // "ConstraintViolationException". + // + // The request was denied because performing this operation violates a constraint. + // + // Some of the reasons in the following list might not apply to this specific + // operation. + // + // * You must meet the prerequisites for using tag policies. For information, + // see Prerequisites and Permissions for Using Tag Policies (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html) + // in the AWS Organizations User Guide. + // + // * You must enable the tag policies service principal (tagpolicies.tag.amazonaws.com) + // to integrate with AWS Organizations For information, see EnableAWSServiceAccess + // (http://docs.aws.amazon.com/organizations/latest/APIReference/API_EnableAWSServiceAccess.html). + // + // * You must have a tag policy attached to the organization root, an OU, + // or an account. + ErrCodeConstraintViolationException = "ConstraintViolationException" + + // ErrCodeInternalServiceException for service response error code + // "InternalServiceException". + // + // The request processing failed because of an unknown error, exception, or + // failure. You can retry the request. + ErrCodeInternalServiceException = "InternalServiceException" + + // ErrCodeInvalidParameterException for service response error code + // "InvalidParameterException". + // + // This error indicates one of the following: + // + // * A parameter is missing. + // + // * A malformed string was supplied for the request parameter. + // + // * An out-of-range value was supplied for the request parameter. + // + // * The target ID is invalid, unsupported, or doesn't exist. + // + // * You can't access the Amazon S3 bucket for report storage. For more information, + // see Additional Requirements for Organization-wide Tag Compliance Reports + // (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html#bucket-policies-org-report) + // in the AWS Organizations User Guide. + ErrCodeInvalidParameterException = "InvalidParameterException" + + // ErrCodePaginationTokenExpiredException for service response error code + // "PaginationTokenExpiredException". + // + // A PaginationToken is valid for a maximum of 15 minutes. Your request was + // denied because the specified PaginationToken has expired. + ErrCodePaginationTokenExpiredException = "PaginationTokenExpiredException" + + // ErrCodeThrottledException for service response error code + // "ThrottledException". + // + // The request was denied to limit the frequency of submitted requests. + ErrCodeThrottledException = "ThrottledException" +) + +var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ + "ConcurrentModificationException": newErrorConcurrentModificationException, + "ConstraintViolationException": newErrorConstraintViolationException, + "InternalServiceException": newErrorInternalServiceException, + "InvalidParameterException": newErrorInvalidParameterException, + "PaginationTokenExpiredException": newErrorPaginationTokenExpiredException, + "ThrottledException": newErrorThrottledException, +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/service.go b/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/service.go new file mode 100644 index 00000000000..997fa35ab09 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/service.go @@ -0,0 +1,103 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package resourcegroupstaggingapi + +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" + "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" +) + +// ResourceGroupsTaggingAPI provides the API operation methods for making requests to +// AWS Resource Groups Tagging API. See this package's package overview docs +// for details on the service. +// +// ResourceGroupsTaggingAPI methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. +type ResourceGroupsTaggingAPI 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 = "tagging" // Name of service. + EndpointsID = ServiceName // ID to lookup a service endpoint with. + ServiceID = "Resource Groups Tagging API" // ServiceID is a unique identifier of a specific service. +) + +// New creates a new instance of the ResourceGroupsTaggingAPI 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: +// mySession := session.Must(session.NewSession()) +// +// // Create a ResourceGroupsTaggingAPI client from just a session. +// svc := resourcegroupstaggingapi.New(mySession) +// +// // Create a ResourceGroupsTaggingAPI client with additional configuration +// svc := resourcegroupstaggingapi.New(mySession, aws.NewConfig().WithRegion("us-west-2")) +func New(p client.ConfigProvider, cfgs ...*aws.Config) *ResourceGroupsTaggingAPI { + c := p.ClientConfig(EndpointsID, cfgs...) + return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) +} + +// newClient creates, initializes and returns a new service client instance. +func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *ResourceGroupsTaggingAPI { + svc := &ResourceGroupsTaggingAPI{ + Client: client.New( + cfg, + metadata.ClientInfo{ + ServiceName: ServiceName, + ServiceID: ServiceID, + SigningName: signingName, + SigningRegion: signingRegion, + PartitionID: partitionID, + Endpoint: endpoint, + APIVersion: "2017-01-26", + JSONVersion: "1.1", + TargetPrefix: "ResourceGroupsTaggingAPI_20170126", + }, + 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( + protocol.NewUnmarshalErrorHandler(jsonrpc.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(), + ) + + // Run custom client initialization if present + if initClient != nil { + initClient(svc.Client) + } + + return svc +} + +// newRequest creates a new request for a ResourceGroupsTaggingAPI operation and runs any +// custom request initialization. +func (c *ResourceGroupsTaggingAPI) 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/route53/api.go b/vendor/github.com/aws/aws-sdk-go/service/route53/api.go index 38b6207b0bd..da7c8dc6cf8 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 @@ -132,6 +132,13 @@ func (c *Route53) AssociateVPCWithHostedZoneRequest(input *AssociateVPCWithHoste // To request a higher limit, create a case (http://aws.amazon.com/route53-request) // with the AWS Support Center. // +// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" +// If Amazon Route 53 can't process a request before the next request arrives, +// it will reject subsequent requests for the same hosted zone and return an +// HTTP 400 error (Bad request). If Route 53 returns this error repeatedly for +// the same request, we recommend that you wait, in intervals of increasing +// duration, before you try the request again. +// // See also, 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) @@ -2290,16 +2297,25 @@ func (c *Route53) DisassociateVPCFromHostedZoneRequest(input *DisassociateVPCFro // DisassociateVPCFromHostedZone API operation for Amazon Route 53. // -// Disassociates a VPC from a Amazon Route 53 private hosted zone. Note the -// following: +// Disassociates an Amazon Virtual Private Cloud (Amazon VPC) from an Amazon +// Route 53 private hosted zone. Note the following: // -// * You can't disassociate the last VPC from a private hosted zone. +// * You can't disassociate the last Amazon VPC from a private hosted zone. // // * You can't convert a private hosted zone into a public hosted zone. // // * You can submit a DisassociateVPCFromHostedZone request using either // the account that created the hosted zone or the account that created the -// VPC. +// Amazon VPC. +// +// * Some services, such as AWS Cloud Map and Amazon Elastic File System +// (Amazon EFS) automatically create hosted zones and associate VPCs with +// the hosted zones. A service can create a hosted zone using your account +// or using its own account. You can disassociate a VPC from a hosted zone +// only if the service created the hosted zone using your account. When you +// run DisassociateVPCFromHostedZone (https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListHostedZonesByVPC.html), +// if the hosted zone has a value for OwningAccount, you can use DisassociateVPCFromHostedZone. +// If the hosted zone has a value for OwningService, you can't use DisassociateVPCFromHostedZone. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4297,6 +4313,99 @@ func (c *Route53) ListHostedZonesByNameWithContext(ctx aws.Context, input *ListH return out, req.Send() } +const opListHostedZonesByVPC = "ListHostedZonesByVPC" + +// ListHostedZonesByVPCRequest generates a "aws/request.Request" representing the +// client's request for the ListHostedZonesByVPC operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListHostedZonesByVPC for more information on using the ListHostedZonesByVPC +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListHostedZonesByVPCRequest method. +// req, resp := client.ListHostedZonesByVPCRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZonesByVPC +func (c *Route53) ListHostedZonesByVPCRequest(input *ListHostedZonesByVPCInput) (req *request.Request, output *ListHostedZonesByVPCOutput) { + op := &request.Operation{ + Name: opListHostedZonesByVPC, + HTTPMethod: "GET", + HTTPPath: "/2013-04-01/hostedzonesbyvpc", + } + + if input == nil { + input = &ListHostedZonesByVPCInput{} + } + + output = &ListHostedZonesByVPCOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListHostedZonesByVPC API operation for Amazon Route 53. +// +// Lists all the private hosted zones that a specified VPC is associated with, +// regardless of which AWS account or AWS service owns the hosted zones. The +// HostedZoneOwner structure in the response contains one of the following values: +// +// * An OwningAccount element, which contains the account number of either +// the current AWS account or another AWS account. Some services, such as +// AWS Cloud Map, create hosted zones using the current account. +// +// * An OwningService element, which identifies the AWS service that created +// and owns the hosted zone. For example, if a hosted zone was created by +// Amazon Elastic File System (Amazon EFS), the value of Owner is efs.amazonaws.com. +// +// Returns awserr.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 Route 53's +// API operation ListHostedZonesByVPC for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInvalidInput "InvalidInput" +// The input is not valid. +// +// * ErrCodeInvalidPaginationToken "InvalidPaginationToken" +// The value that you specified to get the second or subsequent page of results +// is invalid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZonesByVPC +func (c *Route53) ListHostedZonesByVPC(input *ListHostedZonesByVPCInput) (*ListHostedZonesByVPCOutput, error) { + req, out := c.ListHostedZonesByVPCRequest(input) + return out, req.Send() +} + +// ListHostedZonesByVPCWithContext is the same as ListHostedZonesByVPC with the addition of +// the ability to pass a context and additional request options. +// +// See ListHostedZonesByVPC for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListHostedZonesByVPCWithContext(ctx aws.Context, input *ListHostedZonesByVPCInput, opts ...request.Option) (*ListHostedZonesByVPCOutput, error) { + req, out := c.ListHostedZonesByVPCRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opListQueryLoggingConfigs = "ListQueryLoggingConfigs" // ListQueryLoggingConfigsRequest generates a "aws/request.Request" representing the @@ -10776,6 +10885,103 @@ func (s *HostedZoneLimit) SetValue(v int64) *HostedZoneLimit { return s } +// A complex type that identifies a hosted zone that a specified Amazon VPC +// is associated with and the owner of the hosted zone. If there is a value +// for OwningAccount, there is no value for OwningService, and vice versa. +type HostedZoneOwner struct { + _ struct{} `type:"structure"` + + // If the hosted zone was created by an AWS account, or was created by an AWS + // service that creates hosted zones using the current account, OwningAccount + // contains the account ID of that account. For example, when you use AWS Cloud + // Map to create a hosted zone, Cloud Map creates the hosted zone using the + // current AWS account. + OwningAccount *string `type:"string"` + + // If an AWS service uses its own account to create a hosted zone and associate + // the specified VPC with that hosted zone, OwningService contains an abbreviation + // that identifies the service. For example, if Amazon Elastic File System (Amazon + // EFS) created a hosted zone and associated a VPC with the hosted zone, the + // value of OwningService is efs.amazonaws.com. + OwningService *string `type:"string"` +} + +// String returns the string representation +func (s HostedZoneOwner) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s HostedZoneOwner) GoString() string { + return s.String() +} + +// SetOwningAccount sets the OwningAccount field's value. +func (s *HostedZoneOwner) SetOwningAccount(v string) *HostedZoneOwner { + s.OwningAccount = &v + return s +} + +// SetOwningService sets the OwningService field's value. +func (s *HostedZoneOwner) SetOwningService(v string) *HostedZoneOwner { + s.OwningService = &v + return s +} + +// In the response to a ListHostedZonesByVPC request, the HostedZoneSummaries +// element contains one HostedZoneSummary element for each hosted zone that +// the specified Amazon VPC is associated with. Each HostedZoneSummary element +// contains the hosted zone name and ID, and information about who owns the +// hosted zone. +type HostedZoneSummary struct { + _ struct{} `type:"structure"` + + // The Route 53 hosted zone ID of a private hosted zone that the specified VPC + // is associated with. + // + // HostedZoneId is a required field + HostedZoneId *string `type:"string" required:"true"` + + // The name of the private hosted zone, such as example.com. + // + // Name is a required field + Name *string `type:"string" required:"true"` + + // The owner of a private hosted zone that the specified VPC is associated with. + // The owner can be either an AWS account or an AWS service. + // + // Owner is a required field + Owner *HostedZoneOwner `type:"structure" required:"true"` +} + +// String returns the string representation +func (s HostedZoneSummary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s HostedZoneSummary) GoString() string { + return s.String() +} + +// SetHostedZoneId sets the HostedZoneId field's value. +func (s *HostedZoneSummary) SetHostedZoneId(v string) *HostedZoneSummary { + s.HostedZoneId = &v + return s +} + +// SetName sets the Name field's value. +func (s *HostedZoneSummary) SetName(v string) *HostedZoneSummary { + s.Name = &v + return s +} + +// SetOwner sets the Owner field's value. +func (s *HostedZoneSummary) SetOwner(v *HostedZoneOwner) *HostedZoneSummary { + s.Owner = v + return s +} + // If a health check or hosted zone was created by another service, LinkedService // is a complex type that describes the service that created the resource. When // a resource is created by another service, you can't edit or delete it using @@ -11278,6 +11484,144 @@ func (s *ListHostedZonesByNameOutput) SetNextHostedZoneId(v string) *ListHostedZ return s } +// Lists all the private hosted zones that a specified VPC is associated with, +// regardless of which AWS account created the hosted zones. +type ListHostedZonesByVPCInput struct { + _ struct{} `locationName:"ListHostedZonesByVPCRequest" type:"structure"` + + // (Optional) The maximum number of hosted zones that you want Amazon Route + // 53 to return. If the specified VPC is associated with more than MaxItems + // hosted zones, the response includes a NextToken element. NextToken contains + // the hosted zone ID of the first hosted zone that Route 53 will return if + // you submit another request. + MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` + + // If the previous response included a NextToken element, the specified VPC + // is associated with more hosted zones. To get more hosted zones, submit another + // ListHostedZonesByVPC request. + // + // For the value of NextToken, specify the value of NextToken from the previous + // response. + // + // If the previous response didn't include a NextToken element, there are no + // more hosted zones to get. + NextToken *string `location:"querystring" locationName:"nexttoken" type:"string"` + + // The ID of the Amazon VPC that you want to list hosted zones for. + // + // VPCId is a required field + VPCId *string `location:"querystring" locationName:"vpcid" type:"string" required:"true"` + + // For the Amazon VPC that you specified for VPCId, the AWS Region that you + // created the VPC in. + // + // VPCRegion is a required field + VPCRegion *string `location:"querystring" locationName:"vpcregion" min:"1" type:"string" required:"true" enum:"VPCRegion"` +} + +// String returns the string representation +func (s ListHostedZonesByVPCInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListHostedZonesByVPCInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListHostedZonesByVPCInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListHostedZonesByVPCInput"} + if s.VPCId == nil { + invalidParams.Add(request.NewErrParamRequired("VPCId")) + } + if s.VPCRegion == nil { + invalidParams.Add(request.NewErrParamRequired("VPCRegion")) + } + if s.VPCRegion != nil && len(*s.VPCRegion) < 1 { + invalidParams.Add(request.NewErrParamMinLen("VPCRegion", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxItems sets the MaxItems field's value. +func (s *ListHostedZonesByVPCInput) SetMaxItems(v string) *ListHostedZonesByVPCInput { + s.MaxItems = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListHostedZonesByVPCInput) SetNextToken(v string) *ListHostedZonesByVPCInput { + s.NextToken = &v + return s +} + +// SetVPCId sets the VPCId field's value. +func (s *ListHostedZonesByVPCInput) SetVPCId(v string) *ListHostedZonesByVPCInput { + s.VPCId = &v + return s +} + +// SetVPCRegion sets the VPCRegion field's value. +func (s *ListHostedZonesByVPCInput) SetVPCRegion(v string) *ListHostedZonesByVPCInput { + s.VPCRegion = &v + return s +} + +type ListHostedZonesByVPCOutput struct { + _ struct{} `type:"structure"` + + // A list that contains one HostedZoneSummary element for each hosted zone that + // the specified Amazon VPC is associated with. Each HostedZoneSummary element + // contains the hosted zone name and ID, and information about who owns the + // hosted zone. + // + // HostedZoneSummaries is a required field + HostedZoneSummaries []*HostedZoneSummary `locationNameList:"HostedZoneSummary" type:"list" required:"true"` + + // The value that you specified for MaxItems in the most recent ListHostedZonesByVPC + // request. + // + // MaxItems is a required field + MaxItems *string `type:"string" required:"true"` + + // The value that you specified for NextToken in the most recent ListHostedZonesByVPC + // request. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s ListHostedZonesByVPCOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListHostedZonesByVPCOutput) GoString() string { + return s.String() +} + +// SetHostedZoneSummaries sets the HostedZoneSummaries field's value. +func (s *ListHostedZonesByVPCOutput) SetHostedZoneSummaries(v []*HostedZoneSummary) *ListHostedZonesByVPCOutput { + s.HostedZoneSummaries = v + return s +} + +// SetMaxItems sets the MaxItems field's value. +func (s *ListHostedZonesByVPCOutput) SetMaxItems(v string) *ListHostedZonesByVPCOutput { + s.MaxItems = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListHostedZonesByVPCOutput) SetNextToken(v string) *ListHostedZonesByVPCOutput { + s.NextToken = &v + return s +} + // A request to retrieve a list of the public and private hosted zones that // are associated with the current AWS account. type ListHostedZonesInput struct { @@ -15108,6 +15452,17 @@ const ( AccountLimitTypeMaxTrafficPoliciesByOwner = "MAX_TRAFFIC_POLICIES_BY_OWNER" ) +// AccountLimitType_Values returns all elements of the AccountLimitType enum +func AccountLimitType_Values() []string { + return []string{ + AccountLimitTypeMaxHealthChecksByOwner, + AccountLimitTypeMaxHostedZonesByOwner, + AccountLimitTypeMaxTrafficPolicyInstancesByOwner, + AccountLimitTypeMaxReusableDelegationSetsByOwner, + AccountLimitTypeMaxTrafficPoliciesByOwner, + } +} + const ( // ChangeActionCreate is a ChangeAction enum value ChangeActionCreate = "CREATE" @@ -15119,6 +15474,15 @@ const ( ChangeActionUpsert = "UPSERT" ) +// ChangeAction_Values returns all elements of the ChangeAction enum +func ChangeAction_Values() []string { + return []string{ + ChangeActionCreate, + ChangeActionDelete, + ChangeActionUpsert, + } +} + const ( // ChangeStatusPending is a ChangeStatus enum value ChangeStatusPending = "PENDING" @@ -15127,6 +15491,14 @@ const ( ChangeStatusInsync = "INSYNC" ) +// ChangeStatus_Values returns all elements of the ChangeStatus enum +func ChangeStatus_Values() []string { + return []string{ + ChangeStatusPending, + ChangeStatusInsync, + } +} + const ( // CloudWatchRegionUsEast1 is a CloudWatchRegion enum value CloudWatchRegionUsEast1 = "us-east-1" @@ -15194,6 +15566,9 @@ const ( // CloudWatchRegionAfSouth1 is a CloudWatchRegion enum value CloudWatchRegionAfSouth1 = "af-south-1" + // CloudWatchRegionEuSouth1 is a CloudWatchRegion enum value + CloudWatchRegionEuSouth1 = "eu-south-1" + // CloudWatchRegionUsGovWest1 is a CloudWatchRegion enum value CloudWatchRegionUsGovWest1 = "us-gov-west-1" @@ -15207,6 +15582,39 @@ const ( CloudWatchRegionUsIsobEast1 = "us-isob-east-1" ) +// CloudWatchRegion_Values returns all elements of the CloudWatchRegion enum +func CloudWatchRegion_Values() []string { + return []string{ + CloudWatchRegionUsEast1, + CloudWatchRegionUsEast2, + CloudWatchRegionUsWest1, + CloudWatchRegionUsWest2, + CloudWatchRegionCaCentral1, + CloudWatchRegionEuCentral1, + CloudWatchRegionEuWest1, + CloudWatchRegionEuWest2, + CloudWatchRegionEuWest3, + CloudWatchRegionApEast1, + CloudWatchRegionMeSouth1, + CloudWatchRegionApSouth1, + CloudWatchRegionApSoutheast1, + CloudWatchRegionApSoutheast2, + CloudWatchRegionApNortheast1, + CloudWatchRegionApNortheast2, + CloudWatchRegionApNortheast3, + CloudWatchRegionEuNorth1, + CloudWatchRegionSaEast1, + CloudWatchRegionCnNorthwest1, + CloudWatchRegionCnNorth1, + CloudWatchRegionAfSouth1, + CloudWatchRegionEuSouth1, + CloudWatchRegionUsGovWest1, + CloudWatchRegionUsGovEast1, + CloudWatchRegionUsIsoEast1, + CloudWatchRegionUsIsobEast1, + } +} + const ( // ComparisonOperatorGreaterThanOrEqualToThreshold is a ComparisonOperator enum value ComparisonOperatorGreaterThanOrEqualToThreshold = "GreaterThanOrEqualToThreshold" @@ -15221,6 +15629,16 @@ const ( ComparisonOperatorLessThanOrEqualToThreshold = "LessThanOrEqualToThreshold" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorGreaterThanOrEqualToThreshold, + ComparisonOperatorGreaterThanThreshold, + ComparisonOperatorLessThanThreshold, + ComparisonOperatorLessThanOrEqualToThreshold, + } +} + const ( // HealthCheckRegionUsEast1 is a HealthCheckRegion enum value HealthCheckRegionUsEast1 = "us-east-1" @@ -15247,6 +15665,20 @@ const ( HealthCheckRegionSaEast1 = "sa-east-1" ) +// HealthCheckRegion_Values returns all elements of the HealthCheckRegion enum +func HealthCheckRegion_Values() []string { + return []string{ + HealthCheckRegionUsEast1, + HealthCheckRegionUsWest1, + HealthCheckRegionUsWest2, + HealthCheckRegionEuWest1, + HealthCheckRegionApSoutheast1, + HealthCheckRegionApSoutheast2, + HealthCheckRegionApNortheast1, + HealthCheckRegionSaEast1, + } +} + const ( // HealthCheckTypeHttp is a HealthCheckType enum value HealthCheckTypeHttp = "HTTP" @@ -15270,6 +15702,19 @@ const ( HealthCheckTypeCloudwatchMetric = "CLOUDWATCH_METRIC" ) +// HealthCheckType_Values returns all elements of the HealthCheckType enum +func HealthCheckType_Values() []string { + return []string{ + HealthCheckTypeHttp, + HealthCheckTypeHttps, + HealthCheckTypeHttpStrMatch, + HealthCheckTypeHttpsStrMatch, + HealthCheckTypeTcp, + HealthCheckTypeCalculated, + HealthCheckTypeCloudwatchMetric, + } +} + const ( // HostedZoneLimitTypeMaxRrsetsByZone is a HostedZoneLimitType enum value HostedZoneLimitTypeMaxRrsetsByZone = "MAX_RRSETS_BY_ZONE" @@ -15278,6 +15723,14 @@ const ( HostedZoneLimitTypeMaxVpcsAssociatedByZone = "MAX_VPCS_ASSOCIATED_BY_ZONE" ) +// HostedZoneLimitType_Values returns all elements of the HostedZoneLimitType enum +func HostedZoneLimitType_Values() []string { + return []string{ + HostedZoneLimitTypeMaxRrsetsByZone, + HostedZoneLimitTypeMaxVpcsAssociatedByZone, + } +} + const ( // InsufficientDataHealthStatusHealthy is a InsufficientDataHealthStatus enum value InsufficientDataHealthStatusHealthy = "Healthy" @@ -15289,6 +15742,15 @@ const ( InsufficientDataHealthStatusLastKnownStatus = "LastKnownStatus" ) +// InsufficientDataHealthStatus_Values returns all elements of the InsufficientDataHealthStatus enum +func InsufficientDataHealthStatus_Values() []string { + return []string{ + InsufficientDataHealthStatusHealthy, + InsufficientDataHealthStatusUnhealthy, + InsufficientDataHealthStatusLastKnownStatus, + } +} + const ( // RRTypeSoa is a RRType enum value RRTypeSoa = "SOA" @@ -15327,6 +15789,24 @@ const ( RRTypeCaa = "CAA" ) +// RRType_Values returns all elements of the RRType enum +func RRType_Values() []string { + return []string{ + RRTypeSoa, + RRTypeA, + RRTypeTxt, + RRTypeNs, + RRTypeCname, + RRTypeMx, + RRTypeNaptr, + RRTypePtr, + RRTypeSrv, + RRTypeSpf, + RRTypeAaaa, + RRTypeCaa, + } +} + const ( // ResettableElementNameFullyQualifiedDomainName is a ResettableElementName enum value ResettableElementNameFullyQualifiedDomainName = "FullyQualifiedDomainName" @@ -15341,6 +15821,16 @@ const ( ResettableElementNameChildHealthChecks = "ChildHealthChecks" ) +// ResettableElementName_Values returns all elements of the ResettableElementName enum +func ResettableElementName_Values() []string { + return []string{ + ResettableElementNameFullyQualifiedDomainName, + ResettableElementNameRegions, + ResettableElementNameResourcePath, + ResettableElementNameChildHealthChecks, + } +} + const ( // ResourceRecordSetFailoverPrimary is a ResourceRecordSetFailover enum value ResourceRecordSetFailoverPrimary = "PRIMARY" @@ -15349,6 +15839,14 @@ const ( ResourceRecordSetFailoverSecondary = "SECONDARY" ) +// ResourceRecordSetFailover_Values returns all elements of the ResourceRecordSetFailover enum +func ResourceRecordSetFailover_Values() []string { + return []string{ + ResourceRecordSetFailoverPrimary, + ResourceRecordSetFailoverSecondary, + } +} + const ( // ResourceRecordSetRegionUsEast1 is a ResourceRecordSetRegion enum value ResourceRecordSetRegionUsEast1 = "us-east-1" @@ -15415,13 +15913,52 @@ const ( // ResourceRecordSetRegionAfSouth1 is a ResourceRecordSetRegion enum value ResourceRecordSetRegionAfSouth1 = "af-south-1" + + // ResourceRecordSetRegionEuSouth1 is a ResourceRecordSetRegion enum value + ResourceRecordSetRegionEuSouth1 = "eu-south-1" ) +// ResourceRecordSetRegion_Values returns all elements of the ResourceRecordSetRegion enum +func ResourceRecordSetRegion_Values() []string { + return []string{ + ResourceRecordSetRegionUsEast1, + ResourceRecordSetRegionUsEast2, + ResourceRecordSetRegionUsWest1, + ResourceRecordSetRegionUsWest2, + ResourceRecordSetRegionCaCentral1, + ResourceRecordSetRegionEuWest1, + ResourceRecordSetRegionEuWest2, + ResourceRecordSetRegionEuWest3, + ResourceRecordSetRegionEuCentral1, + ResourceRecordSetRegionApSoutheast1, + ResourceRecordSetRegionApSoutheast2, + ResourceRecordSetRegionApNortheast1, + ResourceRecordSetRegionApNortheast2, + ResourceRecordSetRegionApNortheast3, + ResourceRecordSetRegionEuNorth1, + ResourceRecordSetRegionSaEast1, + ResourceRecordSetRegionCnNorth1, + ResourceRecordSetRegionCnNorthwest1, + ResourceRecordSetRegionApEast1, + ResourceRecordSetRegionMeSouth1, + ResourceRecordSetRegionApSouth1, + ResourceRecordSetRegionAfSouth1, + ResourceRecordSetRegionEuSouth1, + } +} + const ( // ReusableDelegationSetLimitTypeMaxZonesByReusableDelegationSet is a ReusableDelegationSetLimitType enum value ReusableDelegationSetLimitTypeMaxZonesByReusableDelegationSet = "MAX_ZONES_BY_REUSABLE_DELEGATION_SET" ) +// ReusableDelegationSetLimitType_Values returns all elements of the ReusableDelegationSetLimitType enum +func ReusableDelegationSetLimitType_Values() []string { + return []string{ + ReusableDelegationSetLimitTypeMaxZonesByReusableDelegationSet, + } +} + const ( // StatisticAverage is a Statistic enum value StatisticAverage = "Average" @@ -15439,6 +15976,17 @@ const ( StatisticMinimum = "Minimum" ) +// Statistic_Values returns all elements of the Statistic enum +func Statistic_Values() []string { + return []string{ + StatisticAverage, + StatisticSum, + StatisticSampleCount, + StatisticMaximum, + StatisticMinimum, + } +} + const ( // TagResourceTypeHealthcheck is a TagResourceType enum value TagResourceTypeHealthcheck = "healthcheck" @@ -15447,6 +15995,14 @@ const ( TagResourceTypeHostedzone = "hostedzone" ) +// TagResourceType_Values returns all elements of the TagResourceType enum +func TagResourceType_Values() []string { + return []string{ + TagResourceTypeHealthcheck, + TagResourceTypeHostedzone, + } +} + const ( // VPCRegionUsEast1 is a VPCRegion enum value VPCRegionUsEast1 = "us-east-1" @@ -15522,4 +16078,39 @@ const ( // VPCRegionAfSouth1 is a VPCRegion enum value VPCRegionAfSouth1 = "af-south-1" + + // VPCRegionEuSouth1 is a VPCRegion enum value + VPCRegionEuSouth1 = "eu-south-1" ) + +// VPCRegion_Values returns all elements of the VPCRegion enum +func VPCRegion_Values() []string { + return []string{ + VPCRegionUsEast1, + VPCRegionUsEast2, + VPCRegionUsWest1, + VPCRegionUsWest2, + VPCRegionEuWest1, + VPCRegionEuWest2, + VPCRegionEuWest3, + VPCRegionEuCentral1, + VPCRegionApEast1, + VPCRegionMeSouth1, + VPCRegionUsGovWest1, + VPCRegionUsGovEast1, + VPCRegionUsIsoEast1, + VPCRegionUsIsobEast1, + VPCRegionApSoutheast1, + VPCRegionApSoutheast2, + VPCRegionApSouth1, + VPCRegionApNortheast1, + VPCRegionApNortheast2, + VPCRegionApNortheast3, + VPCRegionEuNorth1, + VPCRegionSaEast1, + VPCRegionCaCentral1, + VPCRegionCnNorth1, + VPCRegionAfSouth1, + VPCRegionEuSouth1, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53domains/api.go b/vendor/github.com/aws/aws-sdk-go/service/route53domains/api.go index e3e02e0b0ce..050ae64c1e0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/route53domains/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/route53domains/api.go @@ -6814,6 +6814,17 @@ const ( ContactTypeReseller = "RESELLER" ) +// ContactType_Values returns all elements of the ContactType enum +func ContactType_Values() []string { + return []string{ + ContactTypePerson, + ContactTypeCompany, + ContactTypeAssociation, + ContactTypePublicBody, + ContactTypeReseller, + } +} + const ( // CountryCodeAd is a CountryCode enum value CountryCodeAd = "AD" @@ -7503,6 +7514,241 @@ const ( CountryCodeZw = "ZW" ) +// CountryCode_Values returns all elements of the CountryCode enum +func CountryCode_Values() []string { + return []string{ + CountryCodeAd, + CountryCodeAe, + CountryCodeAf, + CountryCodeAg, + CountryCodeAi, + CountryCodeAl, + CountryCodeAm, + CountryCodeAn, + CountryCodeAo, + CountryCodeAq, + CountryCodeAr, + CountryCodeAs, + CountryCodeAt, + CountryCodeAu, + CountryCodeAw, + CountryCodeAz, + CountryCodeBa, + CountryCodeBb, + CountryCodeBd, + CountryCodeBe, + CountryCodeBf, + CountryCodeBg, + CountryCodeBh, + CountryCodeBi, + CountryCodeBj, + CountryCodeBl, + CountryCodeBm, + CountryCodeBn, + CountryCodeBo, + CountryCodeBr, + CountryCodeBs, + CountryCodeBt, + CountryCodeBw, + CountryCodeBy, + CountryCodeBz, + CountryCodeCa, + CountryCodeCc, + CountryCodeCd, + CountryCodeCf, + CountryCodeCg, + CountryCodeCh, + CountryCodeCi, + CountryCodeCk, + CountryCodeCl, + CountryCodeCm, + CountryCodeCn, + CountryCodeCo, + CountryCodeCr, + CountryCodeCu, + CountryCodeCv, + CountryCodeCx, + CountryCodeCy, + CountryCodeCz, + CountryCodeDe, + CountryCodeDj, + CountryCodeDk, + CountryCodeDm, + CountryCodeDo, + CountryCodeDz, + CountryCodeEc, + CountryCodeEe, + CountryCodeEg, + CountryCodeEr, + CountryCodeEs, + CountryCodeEt, + CountryCodeFi, + CountryCodeFj, + CountryCodeFk, + CountryCodeFm, + CountryCodeFo, + CountryCodeFr, + CountryCodeGa, + CountryCodeGb, + CountryCodeGd, + CountryCodeGe, + CountryCodeGh, + CountryCodeGi, + CountryCodeGl, + CountryCodeGm, + CountryCodeGn, + CountryCodeGq, + CountryCodeGr, + CountryCodeGt, + CountryCodeGu, + CountryCodeGw, + CountryCodeGy, + CountryCodeHk, + CountryCodeHn, + CountryCodeHr, + CountryCodeHt, + CountryCodeHu, + CountryCodeId, + CountryCodeIe, + CountryCodeIl, + CountryCodeIm, + CountryCodeIn, + CountryCodeIq, + CountryCodeIr, + CountryCodeIs, + CountryCodeIt, + CountryCodeJm, + CountryCodeJo, + CountryCodeJp, + CountryCodeKe, + CountryCodeKg, + CountryCodeKh, + CountryCodeKi, + CountryCodeKm, + CountryCodeKn, + CountryCodeKp, + CountryCodeKr, + CountryCodeKw, + CountryCodeKy, + CountryCodeKz, + CountryCodeLa, + CountryCodeLb, + CountryCodeLc, + CountryCodeLi, + CountryCodeLk, + CountryCodeLr, + CountryCodeLs, + CountryCodeLt, + CountryCodeLu, + CountryCodeLv, + CountryCodeLy, + CountryCodeMa, + CountryCodeMc, + CountryCodeMd, + CountryCodeMe, + CountryCodeMf, + CountryCodeMg, + CountryCodeMh, + CountryCodeMk, + CountryCodeMl, + CountryCodeMm, + CountryCodeMn, + CountryCodeMo, + CountryCodeMp, + CountryCodeMr, + CountryCodeMs, + CountryCodeMt, + CountryCodeMu, + CountryCodeMv, + CountryCodeMw, + CountryCodeMx, + CountryCodeMy, + CountryCodeMz, + CountryCodeNa, + CountryCodeNc, + CountryCodeNe, + CountryCodeNg, + CountryCodeNi, + CountryCodeNl, + CountryCodeNo, + CountryCodeNp, + CountryCodeNr, + CountryCodeNu, + CountryCodeNz, + CountryCodeOm, + CountryCodePa, + CountryCodePe, + CountryCodePf, + CountryCodePg, + CountryCodePh, + CountryCodePk, + CountryCodePl, + CountryCodePm, + CountryCodePn, + CountryCodePr, + CountryCodePt, + CountryCodePw, + CountryCodePy, + CountryCodeQa, + CountryCodeRo, + CountryCodeRs, + CountryCodeRu, + CountryCodeRw, + CountryCodeSa, + CountryCodeSb, + CountryCodeSc, + CountryCodeSd, + CountryCodeSe, + CountryCodeSg, + CountryCodeSh, + CountryCodeSi, + CountryCodeSk, + CountryCodeSl, + CountryCodeSm, + CountryCodeSn, + CountryCodeSo, + CountryCodeSr, + CountryCodeSt, + CountryCodeSv, + CountryCodeSy, + CountryCodeSz, + CountryCodeTc, + CountryCodeTd, + CountryCodeTg, + CountryCodeTh, + CountryCodeTj, + CountryCodeTk, + CountryCodeTl, + CountryCodeTm, + CountryCodeTn, + CountryCodeTo, + CountryCodeTr, + CountryCodeTt, + CountryCodeTv, + CountryCodeTw, + CountryCodeTz, + CountryCodeUa, + CountryCodeUg, + CountryCodeUs, + CountryCodeUy, + CountryCodeUz, + CountryCodeVa, + CountryCodeVc, + CountryCodeVe, + CountryCodeVg, + CountryCodeVi, + CountryCodeVn, + CountryCodeVu, + CountryCodeWf, + CountryCodeWs, + CountryCodeYe, + CountryCodeYt, + CountryCodeZa, + CountryCodeZm, + CountryCodeZw, + } +} + const ( // DomainAvailabilityAvailable is a DomainAvailability enum value DomainAvailabilityAvailable = "AVAILABLE" @@ -7529,6 +7775,20 @@ const ( DomainAvailabilityDontKnow = "DONT_KNOW" ) +// DomainAvailability_Values returns all elements of the DomainAvailability enum +func DomainAvailability_Values() []string { + return []string{ + DomainAvailabilityAvailable, + DomainAvailabilityAvailableReserved, + DomainAvailabilityAvailablePreorder, + DomainAvailabilityUnavailable, + DomainAvailabilityUnavailablePremium, + DomainAvailabilityUnavailableRestricted, + DomainAvailabilityReserved, + DomainAvailabilityDontKnow, + } +} + const ( // ExtraParamNameDunsNumber is a ExtraParamName enum value ExtraParamNameDunsNumber = "DUNS_NUMBER" @@ -7618,6 +7878,41 @@ const ( ExtraParamNameUkCompanyNumber = "UK_COMPANY_NUMBER" ) +// ExtraParamName_Values returns all elements of the ExtraParamName enum +func ExtraParamName_Values() []string { + return []string{ + ExtraParamNameDunsNumber, + ExtraParamNameBrandNumber, + ExtraParamNameBirthDepartment, + ExtraParamNameBirthDateInYyyyMmDd, + ExtraParamNameBirthCountry, + ExtraParamNameBirthCity, + ExtraParamNameDocumentNumber, + ExtraParamNameAuIdNumber, + ExtraParamNameAuIdType, + ExtraParamNameCaLegalType, + ExtraParamNameCaBusinessEntityType, + ExtraParamNameCaLegalRepresentative, + ExtraParamNameCaLegalRepresentativeCapacity, + ExtraParamNameEsIdentification, + ExtraParamNameEsIdentificationType, + ExtraParamNameEsLegalForm, + ExtraParamNameFiBusinessNumber, + ExtraParamNameFiIdNumber, + ExtraParamNameFiNationality, + ExtraParamNameFiOrganizationType, + ExtraParamNameItNationality, + ExtraParamNameItPin, + ExtraParamNameItRegistrantEntityType, + ExtraParamNameRuPassportData, + ExtraParamNameSeIdNumber, + ExtraParamNameSgIdNumber, + ExtraParamNameVatNumber, + ExtraParamNameUkContactType, + ExtraParamNameUkCompanyNumber, + } +} + const ( // OperationStatusSubmitted is a OperationStatus enum value OperationStatusSubmitted = "SUBMITTED" @@ -7635,6 +7930,17 @@ const ( OperationStatusFailed = "FAILED" ) +// OperationStatus_Values returns all elements of the OperationStatus enum +func OperationStatus_Values() []string { + return []string{ + OperationStatusSubmitted, + OperationStatusInProgress, + OperationStatusError, + OperationStatusSuccessful, + OperationStatusFailed, + } +} + const ( // OperationTypeRegisterDomain is a OperationType enum value OperationTypeRegisterDomain = "REGISTER_DOMAIN" @@ -7691,6 +7997,30 @@ const ( OperationTypeInternalTransferInDomain = "INTERNAL_TRANSFER_IN_DOMAIN" ) +// OperationType_Values returns all elements of the OperationType enum +func OperationType_Values() []string { + return []string{ + OperationTypeRegisterDomain, + OperationTypeDeleteDomain, + OperationTypeTransferInDomain, + OperationTypeUpdateDomainContact, + OperationTypeUpdateNameserver, + OperationTypeChangePrivacyProtection, + OperationTypeDomainLock, + OperationTypeEnableAutorenew, + OperationTypeDisableAutorenew, + OperationTypeAddDnssec, + OperationTypeRemoveDnssec, + OperationTypeExpireDomain, + OperationTypeTransferOutDomain, + OperationTypeChangeDomainOwner, + OperationTypeRenewDomain, + OperationTypePushDomain, + OperationTypeInternalTransferOutDomain, + OperationTypeInternalTransferInDomain, + } +} + const ( // ReachabilityStatusPending is a ReachabilityStatus enum value ReachabilityStatusPending = "PENDING" @@ -7702,6 +8032,15 @@ const ( ReachabilityStatusExpired = "EXPIRED" ) +// ReachabilityStatus_Values returns all elements of the ReachabilityStatus enum +func ReachabilityStatus_Values() []string { + return []string{ + ReachabilityStatusPending, + ReachabilityStatusDone, + ReachabilityStatusExpired, + } +} + // Whether the domain name can be transferred to Route 53. // // You can transfer only domains that have a value of TRANSFERABLE for Transferable. @@ -7729,3 +8068,12 @@ const ( // TransferableDontKnow is a Transferable enum value TransferableDontKnow = "DONT_KNOW" ) + +// Transferable_Values returns all elements of the Transferable enum +func Transferable_Values() []string { + return []string{ + TransferableTransferable, + TransferableUntransferable, + TransferableDontKnow, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53resolver/api.go b/vendor/github.com/aws/aws-sdk-go/service/route53resolver/api.go index d2c81e00493..38c84034310 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/route53resolver/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/route53resolver/api.go @@ -5880,6 +5880,22 @@ const ( IpAddressStatusDeleteFailedFasExpired = "DELETE_FAILED_FAS_EXPIRED" ) +// IpAddressStatus_Values returns all elements of the IpAddressStatus enum +func IpAddressStatus_Values() []string { + return []string{ + IpAddressStatusCreating, + IpAddressStatusFailedCreation, + IpAddressStatusAttaching, + IpAddressStatusAttached, + IpAddressStatusRemapDetaching, + IpAddressStatusRemapAttaching, + IpAddressStatusDetaching, + IpAddressStatusFailedResourceGone, + IpAddressStatusDeleting, + IpAddressStatusDeleteFailedFasExpired, + } +} + const ( // ResolverEndpointDirectionInbound is a ResolverEndpointDirection enum value ResolverEndpointDirectionInbound = "INBOUND" @@ -5888,6 +5904,14 @@ const ( ResolverEndpointDirectionOutbound = "OUTBOUND" ) +// ResolverEndpointDirection_Values returns all elements of the ResolverEndpointDirection enum +func ResolverEndpointDirection_Values() []string { + return []string{ + ResolverEndpointDirectionInbound, + ResolverEndpointDirectionOutbound, + } +} + const ( // ResolverEndpointStatusCreating is a ResolverEndpointStatus enum value ResolverEndpointStatusCreating = "CREATING" @@ -5908,6 +5932,18 @@ const ( ResolverEndpointStatusDeleting = "DELETING" ) +// ResolverEndpointStatus_Values returns all elements of the ResolverEndpointStatus enum +func ResolverEndpointStatus_Values() []string { + return []string{ + ResolverEndpointStatusCreating, + ResolverEndpointStatusOperational, + ResolverEndpointStatusUpdating, + ResolverEndpointStatusAutoRecovering, + ResolverEndpointStatusActionNeeded, + ResolverEndpointStatusDeleting, + } +} + const ( // ResolverRuleAssociationStatusCreating is a ResolverRuleAssociationStatus enum value ResolverRuleAssociationStatusCreating = "CREATING" @@ -5925,6 +5961,17 @@ const ( ResolverRuleAssociationStatusOverridden = "OVERRIDDEN" ) +// ResolverRuleAssociationStatus_Values returns all elements of the ResolverRuleAssociationStatus enum +func ResolverRuleAssociationStatus_Values() []string { + return []string{ + ResolverRuleAssociationStatusCreating, + ResolverRuleAssociationStatusComplete, + ResolverRuleAssociationStatusDeleting, + ResolverRuleAssociationStatusFailed, + ResolverRuleAssociationStatusOverridden, + } +} + const ( // ResolverRuleStatusComplete is a ResolverRuleStatus enum value ResolverRuleStatusComplete = "COMPLETE" @@ -5939,6 +5986,16 @@ const ( ResolverRuleStatusFailed = "FAILED" ) +// ResolverRuleStatus_Values returns all elements of the ResolverRuleStatus enum +func ResolverRuleStatus_Values() []string { + return []string{ + ResolverRuleStatusComplete, + ResolverRuleStatusDeleting, + ResolverRuleStatusUpdating, + ResolverRuleStatusFailed, + } +} + const ( // RuleTypeOptionForward is a RuleTypeOption enum value RuleTypeOptionForward = "FORWARD" @@ -5950,6 +6007,15 @@ const ( RuleTypeOptionRecursive = "RECURSIVE" ) +// RuleTypeOption_Values returns all elements of the RuleTypeOption enum +func RuleTypeOption_Values() []string { + return []string{ + RuleTypeOptionForward, + RuleTypeOptionSystem, + RuleTypeOptionRecursive, + } +} + const ( // ShareStatusNotShared is a ShareStatus enum value ShareStatusNotShared = "NOT_SHARED" @@ -5960,3 +6026,12 @@ const ( // ShareStatusSharedByMe is a ShareStatus enum value ShareStatusSharedByMe = "SHARED_BY_ME" ) + +// ShareStatus_Values returns all elements of the ShareStatus enum +func ShareStatus_Values() []string { + return []string{ + ShareStatusNotShared, + ShareStatusSharedWithMe, + ShareStatusSharedByMe, + } +} 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 52e87308f69..8b14d6f7b63 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/api.go @@ -14,6 +14,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/private/checksum" "github.com/aws/aws-sdk-go/private/protocol" "github.com/aws/aws-sdk-go/private/protocol/eventstream" "github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi" @@ -199,7 +200,7 @@ func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) // For information about permissions required to use the multipart upload API, // see Multipart Upload API and Permissions (https://docs.aws.amazon.com/AmazonS3/latest/dev/mpuAndPermissions.html). // -// GetBucketLifecycle has the following special errors: +// CompleteMultipartUpload has the following special errors: // // * Error code: EntityTooSmall Description: Your proposed upload is smaller // than the minimum allowed object size. Each part must be at least 5 MB @@ -217,7 +218,7 @@ func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) // does not exist. The upload ID might be invalid, or the multipart upload // might have been aborted or completed. 404 Not Found // -// The following operations are related to DeleteBucketMetricsConfiguration: +// The following operations are related to CompleteMultipartUpload: // // * CreateMultipartUpload // @@ -305,20 +306,9 @@ func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, ou // // You can store individual objects of up to 5 TB in Amazon S3. You create a // copy of your object up to 5 GB in size in a single atomic operation using -// this API. However, for copying an object greater than 5 GB, you must use -// the multipart upload Upload Part - Copy API. For more information, see Copy -// Object Using the REST Multipart Upload API (https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingRESTMPUapi.html). -// -// When copying an object, you can preserve all metadata (default) or specify -// new metadata. However, the ACL is not preserved and is set to private for -// the user making the request. To override the default ACL setting, specify -// a new ACL when generating a copy request. For more information, see Using -// ACLs (https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html). -// -// Amazon S3 transfer acceleration does not support cross-region copies. If -// you request a cross-region copy using a transfer acceleration endpoint, you -// get a 400 Bad Request error. For more information about transfer acceleration, -// see Transfer Acceleration (https://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html). +// this API. However, to copy an object greater than 5 GB, you must use the +// multipart upload Upload Part - Copy API. For more information, see Copy Object +// Using the REST Multipart Upload API (https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingRESTMPUapi.html). // // All copy requests must be authenticated. Additionally, you must have read // access to the source object and write access to the destination bucket. For @@ -326,28 +316,6 @@ func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, ou // Both the Region that you want to copy the object from and the Region that // you want to copy the object to must be enabled for your account. // -// To only copy an object under certain conditions, such as whether the Etag -// matches or whether the object was modified before or after a specified date, -// use the request parameters x-amz-copy-source-if-match, x-amz-copy-source-if-none-match, -// x-amz-copy-source-if-unmodified-since, or x-amz-copy-source-if-modified-since. -// -// All headers with the x-amz- prefix, including x-amz-copy-source, must be -// signed. -// -// You can use this operation to change the storage class of an object that -// is already stored in Amazon S3 using the StorageClass parameter. For more -// information, see Storage Classes (https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html). -// -// The source object that you are copying can be encrypted or unencrypted. If -// the source object is encrypted, it can be encrypted by server-side encryption -// using AWS managed encryption keys or by using a customer-provided encryption -// key. When copying an object, you can request that Amazon S3 encrypt the target -// object by using either the AWS managed encryption keys or by using your own -// encryption key. You can do this regardless of the form of server-side encryption -// that was used to encrypt the source, or even if the source object was not -// encrypted. For more information about server-side encryption, see Using Server-Side -// Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/serv-side-encryption.html). -// // A copy request might return an error when Amazon S3 receives the copy request // or while Amazon S3 is copying the files. If the error occurs before the copy // operation starts, you receive a standard Amazon S3 error. If the error occurs @@ -363,125 +331,117 @@ func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, ou // it were not, it would not contain the content-length, and you would need // to read the entire body. // -// Consider the following when using request headers: +// The copy request charge is based on the storage class and Region that you +// specify for the destination object. For pricing information, see Amazon S3 +// pricing (https://aws.amazon.com/s3/pricing/). // -// * Consideration 1 – If both the x-amz-copy-source-if-match and x-amz-copy-source-if-unmodified-since -// headers are present in the request and evaluate as follows, Amazon S3 -// returns 200 OK and copies the data: x-amz-copy-source-if-match condition -// evaluates to true x-amz-copy-source-if-unmodified-since condition evaluates -// to false +// Amazon S3 transfer acceleration does not support cross-Region copies. If +// you request a cross-Region copy using a transfer acceleration endpoint, you +// get a 400 Bad Request error. For more information, see Transfer Acceleration +// (https://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html). // -// * Consideration 2 – If both of the x-amz-copy-source-if-none-match and -// x-amz-copy-source-if-modified-since headers are present in the request -// and evaluate as follows, Amazon S3 returns the 412 Precondition Failed -// response code: x-amz-copy-source-if-none-match condition evaluates to -// false x-amz-copy-source-if-modified-since condition evaluates to true +// Metadata // -// The copy request charge is based on the storage class and Region you specify -// for the destination object. For pricing information, see Amazon S3 Pricing -// (https://aws.amazon.com/s3/pricing/). +// When copying an object, you can preserve all metadata (default) or specify +// new metadata. However, the ACL is not preserved and is set to private for +// the user making the request. To override the default ACL setting, specify +// a new ACL when generating a copy request. For more information, see Using +// ACLs (https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html). // -// Following are other considerations when using CopyObject: +// To specify whether you want the object metadata copied from the source object +// or replaced with metadata provided in the request, you can optionally add +// the x-amz-metadata-directive header. When you grant permissions, you can +// use the s3:x-amz-metadata-directive condition key to enforce certain metadata +// behavior when objects are uploaded. For more information, see Specifying +// Conditions in a Policy (https://docs.aws.amazon.com/AmazonS3/latest/dev/amazon-s3-policy-keys.html) +// in the Amazon S3 Developer Guide. For a complete list of Amazon S3-specific +// condition keys, see Actions, Resources, and Condition Keys for Amazon S3 +// (https://docs.aws.amazon.com/AmazonS3/latest/dev/list_amazons3.html). // -// Versioning +// x-amz-copy-source-if Headers // -// By default, x-amz-copy-source identifies the current version of an object -// to copy. (If the current version is a delete marker, Amazon S3 behaves as -// if the object was deleted.) To copy a different version, use the versionId -// subresource. +// To only copy an object under certain conditions, such as whether the Etag +// matches or whether the object was modified before or after a specified date, +// use the following request parameters: // -// If you enable versioning on the target bucket, Amazon S3 generates a unique -// version ID for the object being copied. This version ID is different from -// the version ID of the source object. Amazon S3 returns the version ID of -// the copied object in the x-amz-version-id response header in the response. +// * x-amz-copy-source-if-match // -// If you do not enable versioning or suspend it on the target bucket, the version -// ID that Amazon S3 generates is always null. +// * x-amz-copy-source-if-none-match // -// If the source object's storage class is GLACIER, you must restore a copy -// of this object before you can use it as a source object for the copy operation. -// For more information, see . +// * x-amz-copy-source-if-unmodified-since // -// Access Permissions +// * x-amz-copy-source-if-modified-since // -// When copying an object, you can optionally specify the accounts or groups -// that should be granted specific permissions on the new object. There are -// two ways to grant the permissions using the request headers: +// If both the x-amz-copy-source-if-match and x-amz-copy-source-if-unmodified-since +// headers are present in the request and evaluate as follows, Amazon S3 returns +// 200 OK and copies the data: // -// * Specify a canned ACL with the x-amz-acl request header. For more information, -// see Canned ACL (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL). +// * x-amz-copy-source-if-match condition evaluates to true // -// * Specify access permissions explicitly with the x-amz-grant-read, x-amz-grant-read-acp, -// x-amz-grant-write-acp, and x-amz-grant-full-control headers. These parameters -// map to the set of permissions that Amazon S3 supports in an ACL. For more -// information, see Access Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). +// * x-amz-copy-source-if-unmodified-since condition evaluates to false // -// You can use either a canned ACL or specify access permissions explicitly. -// You cannot do both. +// If both the x-amz-copy-source-if-none-match and x-amz-copy-source-if-modified-since +// headers are present in the request and evaluate as follows, Amazon S3 returns +// the 412 Precondition Failed response code: // -// Server-Side- Encryption-Specific Request Headers +// * x-amz-copy-source-if-none-match condition evaluates to false // -// To encrypt the target object, you must provide the appropriate encryption-related -// request headers. The one you use depends on whether you want to use AWS managed -// encryption keys or provide your own encryption key. +// * x-amz-copy-source-if-modified-since condition evaluates to true // -// * To encrypt the target object using server-side encryption with an AWS -// managed encryption key, provide the following request headers, as appropriate. -// x-amz-server-side​-encryption x-amz-server-side-encryption-aws-kms-key-id -// x-amz-server-side-encryption-context If you specify x-amz-server-side-encryption:aws:kms, -// but don't provide x-amz-server-side-encryption-aws-kms-key-id, Amazon -// S3 uses the AWS managed CMK in AWS KMS to protect the data. If you want -// to use a customer managed AWS KMS CMK, you must provide the x-amz-server-side-encryption-aws-kms-key-id -// of the symmetric customer managed CMK. Amazon S3 only supports symmetric -// CMKs and not asymmetric CMKs. For more information, see Using Symmetric -// and Asymmetric Keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) -// in the AWS Key Management Service Developer Guide. All GET and PUT requests -// for an object protected by AWS KMS fail if you don't make them with SSL -// or by using SigV4. For more information about server-side encryption with -// CMKs stored in AWS KMS (SSE-KMS), see Protecting Data Using Server-Side -// Encryption with CMKs stored in KMS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). -// -// * To encrypt the target object using server-side encryption with an encryption -// key that you provide, use the following headers. x-amz-server-side​-encryption​-customer-algorithm -// x-amz-server-side​-encryption​-customer-key x-amz-server-side​-encryption​-customer-key-MD5 -// -// * If the source object is encrypted using server-side encryption with -// customer-provided encryption keys, you must use the following headers. -// x-amz-copy-source​-server-side​-encryption​-customer-algorithm x-amz-copy-source​-server-side​-encryption​-customer-key -// x-amz-copy-source-​server-side​-encryption​-customer-key-MD5 For -// more information about server-side encryption with CMKs stored in AWS -// KMS (SSE-KMS), see Protecting Data Using Server-Side Encryption with CMKs -// stored in Amazon KMS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). +// All headers with the x-amz- prefix, including x-amz-copy-source, must be +// signed. // -// Access-Control-List (ACL)-Specific Request Headers +// Encryption // -// You also can use the following access control–related headers with this -// operation. By default, all objects are private. Only the owner has full access -// control. When adding a new object, you can grant permissions to individual +// The source object that you are copying can be encrypted or unencrypted. The +// source object can be encrypted with server-side encryption using AWS managed +// encryption keys (SSE-S3 or SSE-KMS) or by using a customer-provided encryption +// key. With server-side encryption, Amazon S3 encrypts your data as it writes +// it to disks in its data centers and decrypts the data when you access it. +// +// You can optionally use the appropriate encryption-related headers to request +// server-side encryption for the target object. You have the option to provide +// your own encryption key or use SSE-S3 or SSE-KMS, regardless of the form +// of server-side encryption that was used to encrypt the source object. You +// can even request encryption if the source object was not encrypted. For more +// information about server-side encryption, see Using Server-Side Encryption +// (https://docs.aws.amazon.com/AmazonS3/latest/dev/serv-side-encryption.html). +// +// Access Control List (ACL)-Specific Request Headers +// +// When copying an object, you can optionally use headers to grant ACL-based +// permissions. By default, all objects are private. Only the owner has full +// access control. When adding a new object, you can grant permissions to individual // AWS accounts or to predefined groups defined by Amazon S3. These permissions -// are then added to the access control list (ACL) on the object. For more information, -// see Using ACLs (https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html). -// With this operation, you can grant access permissions using one of the following -// two methods: +// are then added to the ACL on the object. For more information, see Access +// Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html) +// and Managing ACLs Using the REST API (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-using-rest-api.html). // -// * Specify a canned ACL (x-amz-acl) — Amazon S3 supports a set of predefined -// ACLs, known as canned ACLs. Each canned ACL has a predefined set of grantees -// and permissions. For more information, see Canned ACL (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL). +// Storage Class Options // -// * Specify access permissions explicitly — To explicitly grant access -// permissions to specific AWS accounts or groups, use the following headers. -// Each header maps to specific permissions that Amazon S3 supports in an -// ACL. For more information, see Access Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). -// In the header, you specify a list of grantees who get the specific permission. -// To grant permissions explicitly, use: x-amz-grant-read x-amz-grant-write -// x-amz-grant-read-acp x-amz-grant-write-acp x-amz-grant-full-control You -// specify each grantee as a type=value pair, where the type is one of the -// following: emailAddress – if the value specified is the email address -// of an AWS account id – if the value specified is the canonical user -// ID of an AWS account uri – if you are granting permissions to a predefined -// group For example, the following x-amz-grant-read header grants the AWS -// accounts identified by email addresses permissions to read object data -// and its metadata: x-amz-grant-read: emailAddress="xyz@amazon.com", emailAddress="abc@amazon.com" +// You can use the CopyObject operation to change the storage class of an object +// that is already stored in Amazon S3 using the StorageClass parameter. For +// more information, see Storage Classes (https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html) +// in the Amazon S3 Service Developer Guide. +// +// Versioning +// +// By default, x-amz-copy-source identifies the current version of an object +// to copy. If the current version is a delete marker, Amazon S3 behaves as +// if the object was deleted. To copy a different version, use the versionId +// subresource. +// +// If you enable versioning on the target bucket, Amazon S3 generates a unique +// version ID for the object being copied. This version ID is different from +// the version ID of the source object. Amazon S3 returns the version ID of +// the copied object in the x-amz-version-id response header in the response. +// +// If you do not enable versioning or suspend it on the target bucket, the version +// ID that Amazon S3 generates is always null. +// +// If the source object's storage class is GLACIER, you must restore a copy +// of this object before you can use it as a source object for the copy operation. +// For more information, see . // // The following operations are related to CopyObject: // @@ -581,8 +541,8 @@ func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request // can optionally specify a Region in the request body. You might choose a Region // to optimize latency, minimize costs, or address regulatory requirements. // For example, if you reside in Europe, you will probably find it advantageous -// to create buckets in the EU (Ireland) Region. For more information, see How -// to Select a Region for Your Buckets (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro). +// to create buckets in the Europe (Ireland) Region. For more information, see +// How to Select a Region for Your Buckets (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro). // // If you send your create bucket request to the s3.amazonaws.com endpoint, // the request goes to the us-east-1 Region. Accordingly, the signature calculations @@ -608,12 +568,19 @@ func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request // in an ACL. For more information, see Access Control List (ACL) Overview // (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). You // specify each grantee as a type=value pair, where the type is one of the -// following: emailAddress – if the value specified is the email address -// of an AWS account id – if the value specified is the canonical user -// ID of an AWS account uri – if you are granting permissions to a predefined -// group For example, the following x-amz-grant-read header grants the AWS -// accounts identified by email addresses permissions to read object data -// and its metadata: x-amz-grant-read: emailAddress="xyz@amazon.com", emailAddress="abc@amazon.com" +// following: id – if the value specified is the canonical user ID of an +// AWS account uri – if you are granting permissions to a predefined group +// emailAddress – if the value specified is the email address of an AWS +// account Using email addresses to specify a grantee is only supported in +// the following AWS Regions: US East (N. Virginia) US West (N. California) +// US West (Oregon) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific +// (Tokyo) Europe (Ireland) South America (São Paulo) For a list of all +// the Amazon S3 supported Regions and endpoints, see Regions and Endpoints +// (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) in +// the AWS General Reference. For example, the following x-amz-grant-read +// header grants the AWS accounts identified by account IDs permissions to +// read object data and its metadata: x-amz-grant-read: id="11112222333", +// id="444455556666" // // You can use either a canned ACL or specify access permissions explicitly. // You cannot do both. @@ -832,12 +799,19 @@ func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (re // To grant permissions explicitly, use: x-amz-grant-read x-amz-grant-write // x-amz-grant-read-acp x-amz-grant-write-acp x-amz-grant-full-control You // specify each grantee as a type=value pair, where the type is one of the -// following: emailAddress – if the value specified is the email address -// of an AWS account id – if the value specified is the canonical user -// ID of an AWS account uri – if you are granting permissions to a predefined -// group For example, the following x-amz-grant-read header grants the AWS -// accounts identified by email addresses permissions to read object data -// and its metadata: x-amz-grant-read: emailAddress="xyz@amazon.com", emailAddress="abc@amazon.com" +// following: id – if the value specified is the canonical user ID of an +// AWS account uri – if you are granting permissions to a predefined group +// emailAddress – if the value specified is the email address of an AWS +// account Using email addresses to specify a grantee is only supported in +// the following AWS Regions: US East (N. Virginia) US West (N. California) +// US West (Oregon) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific +// (Tokyo) Europe (Ireland) South America (São Paulo) For a list of all +// the Amazon S3 supported Regions and endpoints, see Regions and Endpoints +// (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) in +// the AWS General Reference. For example, the following x-amz-grant-read +// header grants the AWS accounts identified by account IDs permissions to +// read object data and its metadata: x-amz-grant-read: id="11112222333", +// id="444455556666" // // The following operations are related to CreateMultipartUpload: // @@ -1012,7 +986,7 @@ func (c *S3) DeleteBucketAnalyticsConfigurationRequest(input *DeleteBucketAnalyt // To use this operation, you must have permissions to perform the s3:PutAnalyticsConfiguration // action. The bucket owner has this permission by default. The bucket owner // can grant this permission to others. For more information about permissions, -// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev//using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) +// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) // and Managing Access Permissions to Your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html). // // For information about the Amazon S3 analytics feature, see Amazon S3 Analytics @@ -1189,14 +1163,14 @@ func (c *S3) DeleteBucketEncryptionRequest(input *DeleteBucketEncryptionInput) ( // // This implementation of the DELETE operation removes default encryption from // the bucket. For information about the Amazon S3 default encryption feature, -// see Amazon S3 Default Bucket Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev//bucket-encryption.html) +// see Amazon S3 Default Bucket Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/bucket-encryption.html) // in the Amazon Simple Storage Service Developer Guide. // // To use this operation, you must have permissions to perform the s3:PutEncryptionConfiguration // action. The bucket owner has this permission by default. The bucket owner // can grant this permission to others. For more information about permissions, -// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev//using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) -// and Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev//s3-access-control.html) +// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) +// and Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // in the Amazon Simple Storage Service Developer Guide. // // Related Resources @@ -2112,6 +2086,10 @@ func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *request.Reque output = &DeleteObjectsOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -2239,7 +2217,7 @@ func (c *S3) DeletePublicAccessBlockRequest(input *DeletePublicAccessBlockInput) // Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) // and Managing Access Permissions to Your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html). // -// The following operations are related to DeleteBucketMetricsConfiguration: +// The following operations are related to DeletePublicAccessBlock: // // * Using Amazon S3 Block Public Access (https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html) // @@ -2329,8 +2307,8 @@ func (c *S3) GetBucketAccelerateConfigurationRequest(input *GetBucketAccelerateC // To use this operation, you must have permission to perform the s3:GetAccelerateConfiguration // action. The bucket owner has this permission by default. The bucket owner // can grant this permission to others. For more information about permissions, -// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev//using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) -// and Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev//s3-access-control.html) +// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) +// and Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // in the Amazon Simple Storage Service Developer Guide. // // You set the Transfer Acceleration state of an existing bucket to Enabled @@ -2341,7 +2319,7 @@ func (c *S3) GetBucketAccelerateConfigurationRequest(input *GetBucketAccelerateC // state if a state has never been set on the bucket. // // For more information about transfer acceleration, see Transfer Acceleration -// (https://docs.aws.amazon.com/AmazonS3/latest/dev//transfer-acceleration.html) +// (https://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html) // in the Amazon Simple Storage Service Developer Guide. // // Related Resources @@ -2997,7 +2975,7 @@ func (c *S3) GetBucketLifecycleConfigurationRequest(input *GetBucketLifecycleCon // configuration does not exist. HTTP Status Code: 404 Not Found SOAP Fault // Code Prefix: Client // -// The following operations are related to DeleteBucketMetricsConfiguration: +// The following operations are related to GetBucketLifecycleConfiguration: // // * GetBucketLifecycle // @@ -6430,6 +6408,10 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request output = &PutBucketAclOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -6473,14 +6455,20 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request // Amazon S3 supports in an ACL. For more information, see Access Control // List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). // You specify each grantee as a type=value pair, where the type is one of -// the following: emailAddress – if the value specified is the email address -// of an AWS account id – if the value specified is the canonical user -// ID of an AWS account uri – if you are granting permissions to a predefined -// group For example, the following x-amz-grant-write header grants create, -// overwrite, and delete objects permission to LogDelivery group predefined -// by Amazon S3 and two AWS accounts identified by their email addresses. -// x-amz-grant-write: uri="http://acs.amazonaws.com/groups/s3/LogDelivery", -// emailAddress="xyz@amazon.com", emailAddress="abc@amazon.com" +// the following: id – if the value specified is the canonical user ID +// of an AWS account uri – if you are granting permissions to a predefined +// group emailAddress – if the value specified is the email address of +// an AWS account Using email addresses to specify a grantee is only supported +// in the following AWS Regions: US East (N. Virginia) US West (N. California) +// US West (Oregon) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific +// (Tokyo) Europe (Ireland) South America (São Paulo) For a list of all +// the Amazon S3 supported Regions and endpoints, see Regions and Endpoints +// (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) in +// the AWS General Reference. For example, the following x-amz-grant-write +// header grants create, overwrite, and delete objects permission to LogDelivery +// group predefined by Amazon S3 and two AWS accounts identified by their +// email addresses. x-amz-grant-write: uri="http://acs.amazonaws.com/groups/s3/LogDelivery", +// id="111122223333", id="555566667777" // // You can use either a canned ACL or specify access permissions explicitly. // You cannot do both. @@ -6490,11 +6478,6 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request // You can specify the person (grantee) to whom you're assigning access rights // (using request elements) in the following ways: // -// * By Email address: <>Grantees@email.com<>lt;/Grantee> -// The grantee is resolved to the CanonicalUser and, in a response to a GET -// Object acl request, appears as the CanonicalUser. -// // * By the person's ID: <>ID<><>GranteesEmail<> // DisplayName is optional and ignored in the request @@ -6502,6 +6485,17 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request // * By URI: <>http://acs.amazonaws.com/groups/global/AuthenticatedUsers<> // +// * By Email address: <>Grantees@email.com<>lt;/Grantee> +// The grantee is resolved to the CanonicalUser and, in a response to a GET +// Object acl request, appears as the CanonicalUser. Using email addresses +// to specify a grantee is only supported in the following AWS Regions: US +// East (N. Virginia) US West (N. California) US West (Oregon) Asia Pacific +// (Singapore) Asia Pacific (Sydney) Asia Pacific (Tokyo) Europe (Ireland) +// South America (São Paulo) For a list of all the Amazon S3 supported Regions +// and endpoints, see Regions and Endpoints (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) +// in the AWS General Reference. +// // Related Resources // // * CreateBucket @@ -6697,6 +6691,10 @@ func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Reque output = &PutBucketCorsOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -6814,6 +6812,10 @@ func (c *S3) PutBucketEncryptionRequest(input *PutBucketEncryptionInput) (req *r output = &PutBucketEncryptionOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -6824,7 +6826,8 @@ func (c *S3) PutBucketEncryptionRequest(input *PutBucketEncryptionInput) (req *r // // This implementation of the PUT operation sets default encryption for a bucket // using server-side encryption with Amazon S3-managed keys SSE-S3 or AWS KMS -// customer master keys (CMKs) (SSE-KMS). +// customer master keys (CMKs) (SSE-KMS). For information about the Amazon S3 +// default encryption feature, see Amazon S3 Default Bucket Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/bucket-encryption.html). // // This operation requires AWS Signature Version 4. For more information, see // Authenticating Requests (AWS Signature Version 4) (sig-v4-authenticating-requests.html). @@ -6929,19 +6932,19 @@ func (c *S3) PutBucketInventoryConfigurationRequest(input *PutBucketInventoryCon // bucket where you want the inventory to be stored, and whether to generate // the inventory daily or weekly. You can also configure what object metadata // to include and whether to inventory all object versions or only current versions. -// For more information, see Amazon S3 Inventory (https://docs.aws.amazon.com/AmazonS3/latest/dev//storage-inventory.html) +// For more information, see Amazon S3 Inventory (https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-inventory.html) // in the Amazon Simple Storage Service Developer Guide. // // You must create a bucket policy on the destination bucket to grant permissions // to Amazon S3 to write objects to the bucket in the defined location. For // an example policy, see Granting Permissions for Amazon S3 Inventory and Storage -// Class Analysis. (https://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html#example-bucket-policies-use-case-9) +// Class Analysis (https://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html#example-bucket-policies-use-case-9). // // To use this operation, you must have permissions to perform the s3:PutInventoryConfiguration // action. The bucket owner has this permission by default and can grant this // permission to others. For more information about permissions, see Permissions -// Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev//using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) -// and Managing Access Permissions to Your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev//s3-access-control.html) +// Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) +// and Managing Access Permissions to Your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // in the Amazon Simple Storage Service Developer Guide. // // Special Errors @@ -6954,7 +6957,7 @@ func (c *S3) PutBucketInventoryConfigurationRequest(input *PutBucketInventoryCon // // * HTTP 403 Forbidden Error Code: AccessDenied Cause: You are not the owner // of the specified bucket, or you do not have the s3:PutInventoryConfiguration -// bucket permission to set the configuration on the bucket +// bucket permission to set the configuration on the bucket. // // Related Resources // @@ -7037,6 +7040,10 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *req output = &PutBucketLifecycleOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -7049,7 +7056,7 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *req // // Creates a new lifecycle configuration for the bucket or replaces an existing // lifecycle configuration. For information about lifecycle configuration, see -// Object Lifecycle Management (https://docs.aws.amazon.com/AmazonS3/latest/dev//object-lifecycle-mgmt.html) +// Object Lifecycle Management (https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html) // in the Amazon Simple Storage Service Developer Guide. // // By default, all Amazon S3 resources, including buckets, objects, and related @@ -7071,11 +7078,11 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *req // * s3:PutLifecycleConfiguration // // For more information about permissions, see Managing Access Permissions to -// your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev//s3-access-control.html) +// your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // in the Amazon Simple Storage Service Developer Guide. // // For more examples of transitioning objects to storage classes such as STANDARD_IA -// or ONEZONE_IA, see Examples of Lifecycle Configuration (https://docs.aws.amazon.com/AmazonS3/latest/dev//intro-lifecycle-rules.html#lifecycle-configuration-examples). +// or ONEZONE_IA, see Examples of Lifecycle Configuration (https://docs.aws.amazon.com/AmazonS3/latest/dev/intro-lifecycle-rules.html#lifecycle-configuration-examples). // // Related Resources // @@ -7089,8 +7096,8 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *req // the AWS account that created the bucket—can perform any of the operations. // A resource owner can also grant others permission to perform the operation. // For more information, see the following topics in the Amazon Simple Storage -// Service Developer Guide: Specifying Permissions in a Policy (https://docs.aws.amazon.com/AmazonS3/latest/dev//using-with-s3-actions.html) -// Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev//s3-access-control.html) +// Service Developer Guide: Specifying Permissions in a Policy (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html) +// Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -7164,6 +7171,10 @@ func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleCon output = &PutBucketLifecycleConfigurationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -7301,6 +7312,10 @@ func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request output = &PutBucketLoggingOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -7528,6 +7543,10 @@ func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (re output = &PutBucketNotificationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -7730,6 +7749,10 @@ func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.R output = &PutBucketPolicyOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -7826,6 +7849,10 @@ func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req output = &PutBucketReplicationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -7856,6 +7883,13 @@ func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req // When you add the Filter element in the configuration, you must also add the // following elements: DeleteMarkerReplication, Status, and Priority. // +// The latest version of the replication configuration XML is V2. XML V2 replication +// configurations are those that contain the Filter element for rules, and rules +// that specify S3 Replication Time Control (S3 RTC). In XML V2 replication +// configurations, Amazon S3 doesn't replicate delete markers. Therefore, you +// must set the DeleteMarkerReplication element to Disabled. For backward compatibility, +// Amazon S3 continues to support the XML V1 replication configuration. +// // For information about enabling versioning on a bucket, see Using Versioning // (https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html). // @@ -7950,6 +7984,10 @@ func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) output = &PutBucketRequestPaymentOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8035,6 +8073,10 @@ func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request output = &PutBucketTaggingOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8065,8 +8107,8 @@ func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request // * Error code: InvalidTagError Description: The tag provided was not a // valid tag. This error can occur if the tag did not pass input validation. // For information about tag restrictions, see User-Defined Tag Restrictions -// (https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2//allocation-tag-restrictions.html) -// and AWS-Generated Cost Allocation Tag Restrictions (https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2//aws-tag-restrictions.html). +// (https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/allocation-tag-restrictions.html) +// and AWS-Generated Cost Allocation Tag Restrictions (https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/aws-tag-restrictions.html). // // * Error code: MalformedXMLError Description: The XML provided does not // match the schema. @@ -8151,6 +8193,10 @@ func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *r output = &PutBucketVersioningOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8259,6 +8305,10 @@ func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request output = &PutBucketWebsiteOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8326,6 +8376,11 @@ func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request // // * HttpRedirectCode // +// Amazon S3 has a limitation of 50 routing rules per website configuration. +// If you require more than 50 routing rules, you can use object redirect. For +// more information, see Configuring an Object Redirect (https://docs.aws.amazon.com/AmazonS3/latest/dev/how-to-page-redirect.html) +// in the Amazon Simple Storage Service Developer Guide. +// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -8415,12 +8470,12 @@ func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, outp // you can calculate the MD5 while putting an object to Amazon S3 and compare // the returned ETag to the calculated MD5 value. // -// To configure your application to send the request headers before sending -// the request body, use the 100-continue HTTP status code. For PUT operations, -// this helps you avoid sending the message body if the message is rejected -// based on the headers (for example, because authentication fails or a redirect -// occurs). For more information on the 100-continue HTTP status code, see Section -// 8.2.3 of http://www.ietf.org/rfc/rfc2616.txt (http://www.ietf.org/rfc/rfc2616.txt). +// The Content-MD5 header is required for any request to upload an object with +// a retention period configured using Amazon S3 Object Lock. For more information +// about Amazon S3 Object Lock, see Amazon S3 Object Lock Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lock-overview.html) +// in the Amazon Simple Storage Service Developer Guide. +// +// Server-side Encryption // // You can optionally request server-side encryption. With server-side encryption, // Amazon S3 encrypts your data as it writes it to disks in its data centers @@ -8428,143 +8483,34 @@ func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, outp // your own encryption key or use AWS managed encryption keys. For more information, // see Using Server-Side Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html). // -// Access Permissions -// -// You can optionally specify the accounts or groups that should be granted -// specific permissions on the new object. There are two ways to grant the permissions -// using the request headers: -// -// * Specify a canned ACL with the x-amz-acl request header. For more information, -// see Canned ACL (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL). -// -// * Specify access permissions explicitly with the x-amz-grant-read, x-amz-grant-read-acp, -// x-amz-grant-write-acp, and x-amz-grant-full-control headers. These parameters -// map to the set of permissions that Amazon S3 supports in an ACL. For more -// information, see Access Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). -// -// You can use either a canned ACL or specify access permissions explicitly. -// You cannot do both. -// -// Server-Side- Encryption-Specific Request Headers -// -// You can optionally tell Amazon S3 to encrypt data at rest using server-side -// encryption. Server-side encryption is for data encryption at rest. Amazon -// S3 encrypts your data as it writes it to disks in its data centers and decrypts -// it when you access it. The option you use depends on whether you want to -// use AWS managed encryption keys or provide your own encryption key. -// -// * Use encryption keys managed by Amazon S3 or customer master keys (CMKs) -// stored in AWS Key Management Service (AWS KMS) – If you want AWS to -// manage the keys used to encrypt data, specify the following headers in -// the request. x-amz-server-side​-encryption x-amz-server-side-encryption-aws-kms-key-id -// x-amz-server-side-encryption-context If you specify x-amz-server-side-encryption:aws:kms, -// but don't provide x-amz-server-side-encryption-aws-kms-key-id, Amazon -// S3 uses the AWS managed CMK in AWS KMS to protect the data. If you want -// to use a customer managed AWS KMS CMK, you must provide the x-amz-server-side-encryption-aws-kms-key-id -// of the symmetric customer managed CMK. Amazon S3 only supports symmetric -// CMKs and not asymmetric CMKs. For more information, see Using Symmetric -// and Asymmetric Keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) -// in the AWS Key Management Service Developer Guide. All GET and PUT requests -// for an object protected by AWS KMS fail if you don't make them with SSL -// or by using SigV4. For more information about server-side encryption with -// CMKs stored in AWS KMS (SSE-KMS), see Protecting Data Using Server-Side -// Encryption with CMKs stored in AWS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). -// -// * Use customer-provided encryption keys – If you want to manage your -// own encryption keys, provide all the following headers in the request. -// x-amz-server-side​-encryption​-customer-algorithm x-amz-server-side​-encryption​-customer-key -// x-amz-server-side​-encryption​-customer-key-MD5 For more information -// about server-side encryption with CMKs stored in KMS (SSE-KMS), see Protecting -// Data Using Server-Side Encryption with CMKs stored in AWS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). -// -// Access-Control-List (ACL)-Specific Request Headers -// -// You also can use the following access control–related headers with this -// operation. By default, all objects are private. Only the owner has full access -// control. When adding a new object, you can grant permissions to individual -// AWS accounts or to predefined groups defined by Amazon S3. These permissions -// are then added to the Access Control List (ACL) on the object. For more information, -// see Using ACLs (https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html). -// With this operation, you can grant access permissions using one of the following -// two methods: -// -// * Specify a canned ACL (x-amz-acl) — Amazon S3 supports a set of predefined -// ACLs, known as canned ACLs. Each canned ACL has a predefined set of grantees -// and permissions. For more information, see Canned ACL (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL). -// -// * Specify access permissions explicitly — To explicitly grant access -// permissions to specific AWS accounts or groups, use the following headers. -// Each header maps to specific permissions that Amazon S3 supports in an -// ACL. For more information, see Access Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). -// In the header, you specify a list of grantees who get the specific permission. -// To grant permissions explicitly use: x-amz-grant-read x-amz-grant-write -// x-amz-grant-read-acp x-amz-grant-write-acp x-amz-grant-full-control You -// specify each grantee as a type=value pair, where the type is one of the -// following: emailAddress – if the value specified is the email address -// of an AWS account Using email addresses to specify a grantee is only supported -// in the following AWS Regions: US East (N. Virginia) US West (N. California) -// US West (Oregon) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific -// (Tokyo) EU (Ireland) South America (São Paulo) For a list of all the -// Amazon S3 supported Regions and endpoints, see Regions and Endpoints (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) -// in the AWS General Reference id – if the value specified is the canonical -// user ID of an AWS account uri – if you are granting permissions to a -// predefined group For example, the following x-amz-grant-read header grants -// the AWS accounts identified by email addresses permissions to read object -// data and its metadata: x-amz-grant-read: emailAddress="xyz@amazon.com", -// emailAddress="abc@amazon.com" -// -// Server-Side- Encryption-Specific Request Headers +// Access Control List (ACL)-Specific Request Headers // -// You can optionally tell Amazon S3 to encrypt data at rest using server-side -// encryption. Server-side encryption is for data encryption at rest. Amazon -// S3 encrypts your data as it writes it to disks in its data centers and decrypts -// it when you access it. The option you use depends on whether you want to -// use AWS-managed encryption keys or provide your own encryption key. -// -// * Use encryption keys managed by Amazon S3 or customer master keys (CMKs) -// stored in AWS Key Management Service (AWS KMS) – If you want AWS to -// manage the keys used to encrypt data, specify the following headers in -// the request. x-amz-server-side​-encryption x-amz-server-side-encryption-aws-kms-key-id -// x-amz-server-side-encryption-context If you specify x-amz-server-side-encryption:aws:kms, -// but don't provide x-amz-server-side-encryption-aws-kms-key-id, Amazon -// S3 uses the AWS managed CMK in AWS KMS to protect the data. If you want -// to use a customer managed AWS KMS CMK, you must provide the x-amz-server-side-encryption-aws-kms-key-id -// of the symmetric customer managed CMK. Amazon S3 only supports symmetric -// CMKs and not asymmetric CMKs. For more information, see Using Symmetric -// and Asymmetric Keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) -// in the AWS Key Management Service Developer Guide. All GET and PUT requests -// for an object protected by AWS KMS fail if you don't make them with SSL -// or by using SigV4. For more information about server-side encryption with -// CMKs stored in AWS KMS (SSE-KMS), see Protecting Data Using Server-Side -// Encryption with CMKs stored in AWS KMS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). -// -// * Use customer-provided encryption keys – If you want to manage your -// own encryption keys, provide all the following headers in the request. -// If you use this feature, the ETag value that Amazon S3 returns in the -// response is not the MD5 of the object. x-amz-server-side​-encryption​-customer-algorithm -// x-amz-server-side​-encryption​-customer-key x-amz-server-side​-encryption​-customer-key-MD5 -// For more information about server-side encryption with CMKs stored in -// AWS KMS (SSE-KMS), see Protecting Data Using Server-Side Encryption with -// CMKs stored in AWS KMS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). +// You can use headers to grant ACL- based permissions. By default, all objects +// are private. Only the owner has full access control. When adding a new object, +// you can grant permissions to individual AWS accounts or to predefined groups +// defined by Amazon S3. These permissions are then added to the ACL on the +// object. For more information, see Access Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html) +// and Managing ACLs Using the REST API (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-using-rest-api.html). // // Storage Class Options // -// By default, Amazon S3 uses the Standard storage class to store newly created -// objects. The Standard storage class provides high durability and high availability. -// You can specify other storage classes depending on the performance needs. +// By default, Amazon S3 uses the STANDARD storage class to store newly created +// objects. The STANDARD storage class provides high durability and high availability. +// Depending on performance needs, you can specify a different storage class. // For more information, see Storage Classes (https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html) -// in the Amazon Simple Storage Service Developer Guide. +// in the Amazon S3 Service Developer Guide. // // Versioning // // If you enable versioning for a bucket, Amazon S3 automatically generates // a unique version ID for the object being stored. Amazon S3 returns this ID -// in the response using the x-amz-version-id response header. If versioning -// is suspended, Amazon S3 always uses null as the version ID for the object -// stored. For more information about returning the versioning state of a bucket, -// see GetBucketVersioning. If you enable versioning for a bucket, when Amazon -// S3 receives multiple write requests for the same object simultaneously, it -// stores all of the objects. +// in the response. When you enable versioning for a bucket, if Amazon S3 receives +// multiple write requests for the same object simultaneously, it stores all +// of the objects. +// +// For more information about versioning, see Adding Objects to Versioning Enabled +// Buckets (https://docs.aws.amazon.com/AmazonS3/latest/dev/AddingObjectstoVersioningEnabledBuckets.html). +// For information about returning the versioning state of a bucket, see GetBucketVersioning. // // Related Resources // @@ -8639,6 +8585,10 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request output = &PutObjectAclOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8651,7 +8601,9 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request // Depending on your application needs, you can choose to set the ACL on an // object using either the request body or the headers. For example, if you // have an existing application that updates a bucket ACL using the request -// body, you can continue to use that approach. +// body, you can continue to use that approach. For more information, see Access +// Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html) +// in the Amazon S3 Developer Guide. // // Access Permissions // @@ -8673,12 +8625,19 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request // S3 supports in an ACL. For more information, see Access Control List (ACL) // Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). // You specify each grantee as a type=value pair, where the type is one of -// the following: emailAddress – if the value specified is the email address -// of an AWS account id – if the value specified is the canonical user -// ID of an AWS account uri – if you are granting permissions to a predefined -// group For example, the following x-amz-grant-read header grants list objects -// permission to the two AWS accounts identified by their email addresses. -// x-amz-grant-read: emailAddress="xyz@amazon.com", emailAddress="abc@amazon.com" +// the following: id – if the value specified is the canonical user ID +// of an AWS account uri – if you are granting permissions to a predefined +// group emailAddress – if the value specified is the email address of +// an AWS account Using email addresses to specify a grantee is only supported +// in the following AWS Regions: US East (N. Virginia) US West (N. California) +// US West (Oregon) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific +// (Tokyo) Europe (Ireland) South America (São Paulo) For a list of all +// the Amazon S3 supported Regions and endpoints, see Regions and Endpoints +// (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) in +// the AWS General Reference. For example, the following x-amz-grant-read +// header grants list objects permission to the two AWS accounts identified +// by their email addresses. x-amz-grant-read: emailAddress="xyz@amazon.com", +// emailAddress="abc@amazon.com" // // You can use either a canned ACL or specify access permissions explicitly. // You cannot do both. @@ -8688,11 +8647,6 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request // You can specify the person (grantee) to whom you're assigning access rights // (using request elements) in the following ways: // -// * By Email address: <>Grantees@email.com<>lt;/Grantee> -// The grantee is resolved to the CanonicalUser and, in a response to a GET -// Object acl request, appears as the CanonicalUser. -// // * By the person's ID: <>ID<><>GranteesEmail<> // DisplayName is optional and ignored in the request. @@ -8700,6 +8654,17 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request // * By URI: <>http://acs.amazonaws.com/groups/global/AuthenticatedUsers<> // +// * By Email address: <>Grantees@email.com<>lt;/Grantee> +// The grantee is resolved to the CanonicalUser and, in a response to a GET +// Object acl request, appears as the CanonicalUser. Using email addresses +// to specify a grantee is only supported in the following AWS Regions: US +// East (N. Virginia) US West (N. California) US West (Oregon) Asia Pacific +// (Singapore) Asia Pacific (Sydney) Asia Pacific (Tokyo) Europe (Ireland) +// South America (São Paulo) For a list of all the Amazon S3 supported Regions +// and endpoints, see Regions and Endpoints (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) +// in the AWS General Reference. +// // Versioning // // The ACL of an object is set at the object version level. By default, PUT @@ -8784,6 +8749,10 @@ func (c *S3) PutObjectLegalHoldRequest(input *PutObjectLegalHoldInput) (req *req output = &PutObjectLegalHoldOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8862,6 +8831,10 @@ func (c *S3) PutObjectLockConfigurationRequest(input *PutObjectLockConfiguration output = &PutObjectLockConfigurationOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8945,6 +8918,10 @@ func (c *S3) PutObjectRetentionRequest(input *PutObjectRetentionInput) (req *req output = &PutObjectRetentionOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -9023,12 +9000,16 @@ func (c *S3) PutObjectTaggingRequest(input *PutObjectTaggingInput) (req *request output = &PutObjectTaggingOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } // PutObjectTagging API operation for Amazon Simple Storage Service. // -// Sets the supplied tag-set to an object that already exists in a bucket +// Sets the supplied tag-set to an object that already exists in a bucket. // // A tag is a key-value pair. You can associate tags with an object by sending // a PUT request against the tagging subresource that is associated with the @@ -9135,6 +9116,10 @@ func (c *S3) PutPublicAccessBlockRequest(input *PutPublicAccessBlockInput) (req output = &PutPublicAccessBlockOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -9246,9 +9231,9 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // * restore an archive - Restore an archived object // // To use this operation, you must have permissions to perform the s3:RestoreObject -// and s3:GetObject actions. The bucket owner has this permission by default -// and can grant this permission to others. For more information about permissions, -// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) +// action. The bucket owner has this permission by default and can grant this +// permission to others. For more information about permissions, see Permissions +// Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) // and Managing Access Permissions to Your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // in the Amazon Simple Storage Service Developer Guide. // @@ -9290,8 +9275,8 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // the query.) You cannot mix ordinal positions with header column names. // SELECT s.Id, s.FirstName, s.SSN FROM S3Object s // -// For more information about using SQL with Glacier Select restore, see SQL -// Reference for Amazon S3 Select and Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) +// For more information about using SQL with S3 Glacier Select restore, see +// SQL Reference for Amazon S3 Select and S3 Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) // in the Amazon Simple Storage Service Developer Guide. // // When making a select request, you can also do the following: @@ -9344,12 +9329,12 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // retrievals and provisioned capacity are not available for the DEEP_ARCHIVE // storage class. // -// * Standard - Standard retrievals allow you to access any of your archived +// * Standard - S3 Standard retrievals allow you to access any of your archived // objects within several hours. This is the default option for the GLACIER // and DEEP_ARCHIVE retrieval requests that do not specify the retrieval -// option. Standard retrievals typically complete within 3-5 hours from the -// GLACIER storage class and typically complete within 12 hours from the -// DEEP_ARCHIVE storage class. +// option. S3 Standard retrievals typically complete within 3-5 hours from +// the GLACIER storage class and typically complete within 12 hours from +// the DEEP_ARCHIVE storage class. // // * Bulk - Bulk retrievals are Amazon S3 Glacier’s lowest-cost retrieval // option, enabling you to retrieve large amounts, even petabytes, of data @@ -9408,10 +9393,10 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // (This error does not apply to SELECT type requests.) HTTP Status Code: // 409 Conflict SOAP Fault Code Prefix: Client // -// * Code: GlacierExpeditedRetrievalNotAvailable Cause: Glacier expedited +// * Code: GlacierExpeditedRetrievalNotAvailable Cause: S3 Glacier expedited // retrievals are currently not available. Try again later. (Returned if // there is insufficient capacity to process the Expedited request. This -// error applies only to Expedited retrievals and not to Standard or Bulk +// error applies only to Expedited retrievals and not to S3 Standard or Bulk // retrievals.) HTTP Status Code: 503 SOAP Fault Code Prefix: N/A // // Related Resources @@ -9420,7 +9405,7 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // // * GetBucketNotificationConfiguration // -// * SQL Reference for Amazon S3 Select and Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) +// * SQL Reference for Amazon S3 Select and S3 Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) // in the Amazon Simple Storage Service Developer Guide // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -9496,7 +9481,7 @@ func (c *S3) SelectObjectContentRequest(input *SelectObjectContentInput) (req *r output = &SelectObjectContentOutput{} req = c.newRequest(op, input, output) - es := newSelectObjectContentEventStream() + es := NewSelectObjectContentEventStream() req.Handlers.Unmarshal.PushBack(es.setStreamCloser) output.EventStream = es @@ -9522,7 +9507,7 @@ func (c *S3) SelectObjectContentRequest(input *SelectObjectContentInput) (req *r // in the Amazon Simple Storage Service Developer Guide. // // For more information about using SQL with Amazon S3 Select, see SQL Reference -// for Amazon S3 Select and Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) +// for Amazon S3 Select and S3 Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) // in the Amazon Simple Storage Service Developer Guide. // // Permissions @@ -9572,8 +9557,8 @@ func (c *S3) SelectObjectContentRequest(input *SelectObjectContentInput) (req *r // The SelectObjectContent operation does not support the following GetObject // functionality. For more information, see GetObject. // -// * Range: While you can specify a scan range for a Amazon S3 Select request, -// see SelectObjectContentRequest$ScanRange in the request parameters below, +// * Range: Although you can specify a scan range for an Amazon S3 Select +// request (see SelectObjectContentRequest$ScanRange in the request parameters), // you cannot specify the range of bytes of an object to return. // // * GLACIER, DEEP_ARCHIVE and REDUCED_REDUNDANCY storage classes: You cannot @@ -9583,8 +9568,7 @@ func (c *S3) SelectObjectContentRequest(input *SelectObjectContentInput) (req *r // // Special Errors // -// For a list of special errors for this operation and for general information -// about Amazon S3 errors and a list of error codes, see ErrorResponses +// For a list of special errors for this operation, see SelectObjectContentErrorCodeList // // Related Resources // @@ -9622,7 +9606,13 @@ func (c *S3) SelectObjectContentWithContext(ctx aws.Context, input *SelectObject return out, req.Send() } +var _ awserr.Error + // SelectObjectContentEventStream provides the event stream handling for the SelectObjectContent. +// +// For testing and mocking the event stream this type should be initialized via +// the NewSelectObjectContentEventStream constructor function. Using the functional options +// to pass in nested mock behavior. type SelectObjectContentEventStream struct { // Reader is the EventStream reader for the SelectObjectContentEventStream @@ -9645,11 +9635,31 @@ type SelectObjectContentEventStream struct { err *eventstreamapi.OnceError } -func newSelectObjectContentEventStream() *SelectObjectContentEventStream { - return &SelectObjectContentEventStream{ +// NewSelectObjectContentEventStream initializes an SelectObjectContentEventStream. +// This function should only be used for testing and mocking the SelectObjectContentEventStream +// stream within your application. +// +// The Reader member must be set before reading events from the stream. +// +// The StreamCloser member should be set to the underlying io.Closer, +// (e.g. http.Response.Body), that will be closed when the stream Close method +// is called. +// +// es := NewSelectObjectContentEventStream(func(o *SelectObjectContentEventStream{ +// es.Reader = myMockStreamReader +// es.StreamCloser = myMockStreamCloser +// }) +func NewSelectObjectContentEventStream(opts ...func(*SelectObjectContentEventStream)) *SelectObjectContentEventStream { + es := &SelectObjectContentEventStream{ done: make(chan struct{}), err: eventstreamapi.NewOnceError(), } + + for _, fn := range opts { + fn(es) + } + + return es } func (es *SelectObjectContentEventStream) setStreamCloser(r *request.Request) { @@ -9696,6 +9706,7 @@ func (es *SelectObjectContentEventStream) waitStreamPartClose() { // * ProgressEvent // * RecordsEvent // * StatsEvent +// * SelectObjectContentEventStreamUnknownEvent func (es *SelectObjectContentEventStream) Events() <-chan SelectObjectContentEventStreamEvent { return es.Reader.Events() } @@ -10615,8 +10626,11 @@ type AnalyticsS3BucketDestination struct { // Bucket is a required field Bucket *string `type:"string" required:"true"` - // The account ID that owns the destination bucket. If no account ID is provided, - // the owner will not be validated prior to exporting data. + // The account ID that owns the destination S3 bucket. If no account ID is provided, + // the owner is not validated before exporting data. + // + // Although this value is optional, we strongly recommend that you set it to + // help prevent problems if the destination bucket ownership changes. BucketAccountId *string `type:"string"` // Specifies the file format used when exporting data to Amazon S3. @@ -11578,6 +11592,8 @@ func (s *ContinuationEvent) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *ContinuationEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) return msg, err @@ -14133,7 +14149,7 @@ type DeleteObjectTaggingInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // Name of the tag. + // Name of the object key. // // Key is a required field Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` @@ -14575,9 +14591,9 @@ type Destination struct { // must be replicated. Must be specified together with a Metrics block. ReplicationTime *ReplicationTime `type:"structure"` - // The storage class to use when replicating objects, such as standard or reduced - // redundancy. By default, Amazon S3 uses the storage class of the source object - // to create the object replica. + // The storage class to use when replicating objects, such as S3 Standard or + // reduced redundancy. By default, Amazon S3 uses the storage class of the source + // object to create the object replica. // // For valid values, see the StorageClass element of the PUT Bucket replication // (https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTreplication.html) @@ -14794,6 +14810,8 @@ func (s *EndEvent) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *EndEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) return msg, err @@ -16110,6 +16128,7 @@ type GetBucketLocationOutput struct { // Specifies the Region where the bucket resides. For a list of all the Amazon // S3 supported location constraints by Region, see Regions and Endpoints (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region). + // Buckets in Region us-east-1 have a LocationConstraint of null. LocationConstraint *string `type:"string" enum:"BucketLocationConstraint"` } @@ -16319,7 +16338,7 @@ func (s *GetBucketMetricsConfigurationOutput) SetMetricsConfiguration(v *Metrics type GetBucketNotificationConfigurationRequest struct { _ struct{} `locationName:"GetBucketNotificationConfigurationRequest" type:"structure"` - // Name of the bucket for which to get the notification configuration + // Name of the bucket for which to get the notification configuration. // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` @@ -16967,10 +16986,10 @@ func (s *GetBucketWebsiteInput) hasEndpointARN() bool { type GetBucketWebsiteOutput struct { _ struct{} `type:"structure"` - // The name of the error document for the website. + // The object key name of the website error document to use for 4XX class errors. ErrorDocument *ErrorDocument `type:"structure"` - // The name of the index document for the website. + // The name of the index document for the website (for example index.html). IndexDocument *IndexDocument `type:"structure"` // Specifies the redirect behavior of all requests to a website endpoint of @@ -17207,7 +17226,10 @@ type GetObjectInput struct { PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer"` // Downloads the specified range bytes of an object. For more information about - // the HTTP Range header, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. + // the HTTP Range header, see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 + // (https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35). + // + // Amazon S3 doesn't support retrieving multiple ranges of data per GET request. Range *string `location:"header" locationName:"Range" type:"string"` // Confirms that the requester knows that they will be charged for the request. @@ -17756,7 +17778,7 @@ type GetObjectOutput struct { ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` // Provides storage class information of the object. Amazon S3 returns this - // header for all objects except for Standard storage class objects. + // header for all objects except for S3 Standard storage class objects. StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` // The number of tags, if any, on the object. @@ -18441,11 +18463,11 @@ func (s *GetPublicAccessBlockOutput) SetPublicAccessBlockConfiguration(v *Public return s } -// Container for Glacier job parameters. +// Container for S3 Glacier job parameters. type GlacierJobParameters struct { _ struct{} `type:"structure"` - // Glacier retrieval tier at which the restore will be processed. + // S3 Glacier retrieval tier at which the restore will be processed. // // Tier is a required field Tier *string `type:"string" required:"true" enum:"Tier"` @@ -18536,6 +18558,29 @@ type Grantee struct { DisplayName *string `type:"string"` // Email address of the grantee. + // + // Using email addresses to specify a grantee is only supported in the following + // AWS Regions: + // + // * US East (N. Virginia) + // + // * US West (N. California) + // + // * US West (Oregon) + // + // * Asia Pacific (Singapore) + // + // * Asia Pacific (Sydney) + // + // * Asia Pacific (Tokyo) + // + // * Europe (Ireland) + // + // * South America (São Paulo) + // + // For a list of all the Amazon S3 supported Regions and endpoints, see Regions + // and Endpoints (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) + // in the AWS General Reference. EmailAddress *string `type:"string"` // The canonical user ID of the grantee. @@ -18716,6 +18761,8 @@ type HeadObjectInput struct { // Downloads the specified range bytes of an object. For more information about // the HTTP Range header, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. + // + // Amazon S3 doesn't support retrieving multiple ranges of data per GET request. Range *string `location:"header" locationName:"Range" type:"string"` // Confirms that the requester knows that they will be charged for the request. @@ -19029,7 +19076,7 @@ type HeadObjectOutput struct { ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` // Provides storage class information of the object. Amazon S3 returns this - // header for all objects except for Standard storage class objects. + // header for all objects except for S3 Standard storage class objects. // // For more information, see Storage Classes (https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html). StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` @@ -19624,7 +19671,11 @@ func (s *InventoryFilter) SetPrefix(v string) *InventoryFilter { type InventoryS3BucketDestination struct { _ struct{} `type:"structure"` - // The ID of the account that owns the destination bucket. + // The account ID that owns the destination S3 bucket. If no account ID is provided, + // the owner is not validated before exporting data. + // + // Although this value is optional, we strongly recommend that you set it to + // help prevent problems if the destination bucket ownership changes. AccountId *string `type:"string"` // The Amazon Resource Name (ARN) of the bucket where inventory results will @@ -19781,7 +19832,8 @@ func (s *JSONInput) SetType(v string) *JSONInput { type JSONOutput struct { _ struct{} `type:"structure"` - // The value used to separate individual records in the output. + // The value used to separate individual records in the output. If no value + // is specified, Amazon S3 uses a newline character ('\n'). RecordDelimiter *string `type:"string"` } @@ -21017,11 +21069,12 @@ type ListObjectVersionsInput struct { // Specifies the key to start with when listing objects in a bucket. KeyMarker *string `location:"querystring" locationName:"key-marker" type:"string"` - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. If additional keys satisfy - // the search criteria, but were not returned because max-keys was exceeded, - // the response contains true. To return the additional - // keys, see key-marker and version-id-marker. + // Sets the maximum number of keys returned in the response. By default the + // API returns up to 1,000 key names. The response might contain fewer keys + // but will never contain more. If additional keys satisfy the search criteria, + // but were not returned because max-keys was exceeded, the response contains + // true. To return the additional keys, see key-marker + // and version-id-marker. MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` // Use this parameter to select only those keys that begin with the specified @@ -21298,8 +21351,9 @@ type ListObjectsInput struct { // Specifies the key to start with when listing objects in a bucket. Marker *string `location:"querystring" locationName:"marker" type:"string"` - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. + // Sets the maximum number of keys returned in the response. By default the + // API returns up to 1,000 key names. The response might contain fewer keys + // but will never contain more. MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` // Limits the response to keys that begin with the specified prefix. @@ -21451,7 +21505,7 @@ type ListObjectsOutput struct { // is true), you can use the key name in this field as marker in the subsequent // request to get next set of objects. Amazon S3 lists objects in alphabetical // order Note: This element is returned only if you have delimiter request parameter - // specified. If response does not include the NextMaker and it is truncated, + // specified. If response does not include the NextMarker and it is truncated, // you can use the value of the last Key in the response as the marker in the // subsequent request to get the next set of object keys. NextMarker *string `type:"string"` @@ -21561,8 +21615,9 @@ type ListObjectsV2Input struct { // true. FetchOwner *bool `location:"querystring" locationName:"fetch-owner" type:"boolean"` - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. + // Sets the maximum number of keys returned in the response. By default the + // API returns up to 1,000 key names. The response might contain fewer keys + // but will never contain more. MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` // Limits the response to keys that begin with the specified prefix. @@ -21731,8 +21786,9 @@ type ListObjectsV2Output struct { // result will include less than equals 50 keys KeyCount *int64 `type:"integer"` - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. + // Sets the maximum number of keys returned in the response. By default the + // API returns up to 1,000 key names. The response might contain fewer keys + // but will never contain more. MaxKeys *int64 `type:"integer"` // Bucket name. @@ -22929,8 +22985,22 @@ func (s *NotificationConfigurationFilter) SetKey(v *KeyFilter) *NotificationConf type Object struct { _ struct{} `type:"structure"` - // The entity tag is an MD5 hash of the object. ETag reflects only changes to - // the contents of an object, not its metadata. + // The entity tag is a hash of the object. The ETag reflects changes only to + // the contents of an object, not its metadata. The ETag may or may not be an + // MD5 digest of the object data. Whether or not it is depends on how the object + // was created and how it is encrypted as described below: + // + // * Objects created by the PUT Object, POST Object, or Copy operation, or + // through the AWS Management Console, and are encrypted by SSE-S3 or plaintext, + // have ETags that are an MD5 digest of their object data. + // + // * Objects created by the PUT Object, POST Object, or Copy operation, or + // through the AWS Management Console, and are encrypted by SSE-C or SSE-KMS, + // have ETags that are not an MD5 digest of their object data. + // + // * If an object is created by either the Multipart Upload or Part Copy + // operation, the ETag is not an MD5 digest, regardless of the method of + // encryption. ETag *string `type:"string"` // The name that you assign to an object. You use the object key to retrieve @@ -23530,6 +23600,8 @@ func (s *ProgressEvent) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *ProgressEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) var buf bytes.Buffer @@ -23976,7 +24048,7 @@ type PutBucketCorsInput struct { // Describes the cross-origin access configuration for objects in an Amazon // S3 bucket. For more information, see Enabling Cross-Origin Resource Sharing - // (https://docs.aws.amazon.com/AmazonS3/latest/dev//cors.html) in the Amazon + // (https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html) in the Amazon // Simple Storage Service Developer Guide. // // CORSConfiguration is a required field @@ -25767,8 +25839,8 @@ type PutObjectInput struct { // S3 (for example, AES256, aws:kms). ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - // If you don't specify, Standard is the default storage class. Amazon S3 supports - // other storage classes. + // If you don't specify, S3 Standard is the default storage class. Amazon S3 + // supports other storage classes. StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` // The tag-set for the object. The tag-set must be encoded as URL Query parameters. @@ -26575,7 +26647,7 @@ type PutObjectTaggingInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // Name of the tag. + // Name of the object key. // // Key is a required field Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` @@ -26966,6 +27038,8 @@ func (s *RecordsEvent) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *RecordsEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) msg.Headers.Set(":content-type", eventstream.StringValue("application/octet-stream")) @@ -27784,7 +27858,7 @@ type RestoreRequest struct { // The optional description for the job. Description *string `type:"string"` - // Glacier related parameters pertaining to this job. Do not use with restores + // S3 Glacier related parameters pertaining to this job. Do not use with restores // that specify OutputLocation. GlacierJobParameters *GlacierJobParameters `type:"structure"` @@ -27794,7 +27868,7 @@ type RestoreRequest struct { // Describes the parameters for Select job types. SelectParameters *SelectParameters `type:"structure"` - // Glacier retrieval tier at which the restore will be processed. + // S3 Glacier retrieval tier at which the restore will be processed. Tier *string `type:"string" enum:"Tier"` // Type of restore request. @@ -27932,8 +28006,9 @@ func (s *RoutingRule) SetRedirect(v *Redirect) *RoutingRule { } // Specifies lifecycle rules for an Amazon S3 bucket. For more information, -// see PUT Bucket lifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html) -// in the Amazon Simple Storage Service API Reference. +// see Put Bucket Lifecycle Configuration (https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html) +// in the Amazon Simple Storage Service API Reference. For examples, see Put +// Bucket Lifecycle Configuration Examples (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycleConfiguration.html#API_PutBucketLifecycleConfiguration_Examples) type Rule struct { _ struct{} `type:"structure"` @@ -27978,7 +28053,10 @@ type Rule struct { // Status is a required field Status *string `type:"string" required:"true" enum:"ExpirationStatus"` - // Specifies when an object transitions to a specified storage class. + // Specifies when an object transitions to a specified storage class. For more + // information about Amazon S3 lifecycle configuration rules, see Transitioning + // Objects Using Amazon S3 Lifecycle (https://docs.aws.amazon.com/AmazonS3/latest/dev/lifecycle-transition-general-considerations.html) + // in the Amazon Simple Storage Service Developer Guide. Transition *Transition `type:"structure"` } @@ -28182,6 +28260,7 @@ type SelectObjectContentEventStreamEvent interface { // * ProgressEvent // * RecordsEvent // * StatsEvent +// * SelectObjectContentEventStreamUnknownEvent type SelectObjectContentEventStreamReader interface { // Returns a channel of events as they are read from the event stream. Events() <-chan SelectObjectContentEventStreamEvent @@ -28256,6 +28335,9 @@ func (r *readSelectObjectContentEventStream) readEventStream() { return default: } + if _, ok := err.(*eventstreamapi.UnknownMessageTypeError); ok { + continue + } r.err.SetError(err) return } @@ -28285,14 +28367,39 @@ func (u unmarshalerForSelectObjectContentEventStreamEvent) UnmarshalerForEventNa case "Stats": return &StatsEvent{}, nil default: - return nil, awserr.New( - request.ErrCodeSerialization, - fmt.Sprintf("unknown event type name, %s, for SelectObjectContentEventStream", eventType), - nil, - ) + return &SelectObjectContentEventStreamUnknownEvent{Type: eventType}, nil } } +// SelectObjectContentEventStreamUnknownEvent provides a failsafe event for the +// SelectObjectContentEventStream group of events when an unknown event is received. +type SelectObjectContentEventStreamUnknownEvent struct { + Type string + Message eventstream.Message +} + +// The SelectObjectContentEventStreamUnknownEvent is and event in the SelectObjectContentEventStream +// group of events. +func (s *SelectObjectContentEventStreamUnknownEvent) eventSelectObjectContentEventStream() {} + +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. +func (e *SelectObjectContentEventStreamUnknownEvent) MarshalEvent(pm protocol.PayloadMarshaler) ( + msg eventstream.Message, err error, +) { + return e.Message.Clone(), nil +} + +// UnmarshalEvent unmarshals the EventStream Message into the SelectObjectContentEventStreamData value. +// This method is only used internally within the SDK's EventStream handling. +func (e *SelectObjectContentEventStreamUnknownEvent) UnmarshalEvent( + payloadUnmarshaler protocol.PayloadUnmarshaler, + msg eventstream.Message, +) error { + e.Message = msg.Clone() + return nil +} + // Request to filter the contents of an Amazon S3 object based on a simple Structured // Query Language (SQL) statement. In the request, along with the SQL expression, // you must specify a data serialization format (JSON or CSV) of the object. @@ -28623,8 +28730,24 @@ func (s *SelectParameters) SetOutputSerialization(v *OutputSerialization) *Selec type ServerSideEncryptionByDefault struct { _ struct{} `type:"structure"` - // KMS master key ID to use for the default encryption. This parameter is allowed - // if and only if SSEAlgorithm is set to aws:kms. + // AWS Key Management Service (KMS) customer master key ID to use for the default + // encryption. This parameter is allowed if and only if SSEAlgorithm is set + // to aws:kms. + // + // You can specify the key ID or the Amazon Resource Name (ARN) of the CMK. + // However, if you are using encryption with cross-account operations, you must + // use a fully qualified CMK ARN. For more information, see Using encryption + // for cross-account operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/bucket-encryption.html#bucket-encryption-update-bucket-policy). + // + // For example: + // + // * Key ID: 1234abcd-12ab-34cd-56ef-1234567890ab + // + // * Key ARN: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab + // + // Amazon S3 only supports symmetric CMKs and not asymmetric CMKs. For more + // information, see Using Symmetric and Asymmetric Keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) + // in the AWS Key Management Service Developer Guide. KMSMasterKeyID *string `type:"string" sensitive:"true"` // Server-side encryption algorithm to use for the default encryption. @@ -28928,6 +29051,8 @@ func (s *StatsEvent) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *StatsEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) var buf bytes.Buffer @@ -29043,7 +29168,7 @@ func (s *StorageClassAnalysisDataExport) SetOutputSchemaVersion(v string) *Stora type Tag struct { _ struct{} `type:"structure"` - // Name of the tag. + // Name of the object key. // // Key is a required field Key *string `min:"1" type:"string" required:"true"` @@ -29329,7 +29454,10 @@ func (s *TopicConfigurationDeprecated) SetTopic(v string) *TopicConfigurationDep return s } -// Specifies when an object transitions to a specified storage class. +// Specifies when an object transitions to a specified storage class. For more +// information about Amazon S3 lifecycle configuration rules, see Transitioning +// Objects Using Amazon S3 Lifecycle (https://docs.aws.amazon.com/AmazonS3/latest/dev/lifecycle-transition-general-considerations.html) +// in the Amazon Simple Storage Service Developer Guide. type Transition struct { _ struct{} `type:"structure"` @@ -30124,6 +30252,13 @@ const ( AnalyticsS3ExportFileFormatCsv = "CSV" ) +// AnalyticsS3ExportFileFormat_Values returns all elements of the AnalyticsS3ExportFileFormat enum +func AnalyticsS3ExportFileFormat_Values() []string { + return []string{ + AnalyticsS3ExportFileFormatCsv, + } +} + const ( // BucketAccelerateStatusEnabled is a BucketAccelerateStatus enum value BucketAccelerateStatusEnabled = "Enabled" @@ -30132,6 +30267,14 @@ const ( BucketAccelerateStatusSuspended = "Suspended" ) +// BucketAccelerateStatus_Values returns all elements of the BucketAccelerateStatus enum +func BucketAccelerateStatus_Values() []string { + return []string{ + BucketAccelerateStatusEnabled, + BucketAccelerateStatusSuspended, + } +} + const ( // BucketCannedACLPrivate is a BucketCannedACL enum value BucketCannedACLPrivate = "private" @@ -30146,18 +30289,31 @@ const ( BucketCannedACLAuthenticatedRead = "authenticated-read" ) +// BucketCannedACL_Values returns all elements of the BucketCannedACL enum +func BucketCannedACL_Values() []string { + return []string{ + BucketCannedACLPrivate, + BucketCannedACLPublicRead, + BucketCannedACLPublicReadWrite, + BucketCannedACLAuthenticatedRead, + } +} + const ( - // BucketLocationConstraintEu is a BucketLocationConstraint enum value - BucketLocationConstraintEu = "EU" + // BucketLocationConstraintAfSouth1 is a BucketLocationConstraint enum value + BucketLocationConstraintAfSouth1 = "af-south-1" - // BucketLocationConstraintEuWest1 is a BucketLocationConstraint enum value - BucketLocationConstraintEuWest1 = "eu-west-1" + // BucketLocationConstraintApEast1 is a BucketLocationConstraint enum value + BucketLocationConstraintApEast1 = "ap-east-1" - // BucketLocationConstraintUsWest1 is a BucketLocationConstraint enum value - BucketLocationConstraintUsWest1 = "us-west-1" + // BucketLocationConstraintApNortheast1 is a BucketLocationConstraint enum value + BucketLocationConstraintApNortheast1 = "ap-northeast-1" - // BucketLocationConstraintUsWest2 is a BucketLocationConstraint enum value - BucketLocationConstraintUsWest2 = "us-west-2" + // BucketLocationConstraintApNortheast2 is a BucketLocationConstraint enum value + BucketLocationConstraintApNortheast2 = "ap-northeast-2" + + // BucketLocationConstraintApNortheast3 is a BucketLocationConstraint enum value + BucketLocationConstraintApNortheast3 = "ap-northeast-3" // BucketLocationConstraintApSouth1 is a BucketLocationConstraint enum value BucketLocationConstraintApSouth1 = "ap-south-1" @@ -30168,19 +30324,89 @@ const ( // BucketLocationConstraintApSoutheast2 is a BucketLocationConstraint enum value BucketLocationConstraintApSoutheast2 = "ap-southeast-2" - // BucketLocationConstraintApNortheast1 is a BucketLocationConstraint enum value - BucketLocationConstraintApNortheast1 = "ap-northeast-1" - - // BucketLocationConstraintSaEast1 is a BucketLocationConstraint enum value - BucketLocationConstraintSaEast1 = "sa-east-1" + // BucketLocationConstraintCaCentral1 is a BucketLocationConstraint enum value + BucketLocationConstraintCaCentral1 = "ca-central-1" // BucketLocationConstraintCnNorth1 is a BucketLocationConstraint enum value BucketLocationConstraintCnNorth1 = "cn-north-1" + // BucketLocationConstraintCnNorthwest1 is a BucketLocationConstraint enum value + BucketLocationConstraintCnNorthwest1 = "cn-northwest-1" + + // BucketLocationConstraintEu is a BucketLocationConstraint enum value + BucketLocationConstraintEu = "EU" + // BucketLocationConstraintEuCentral1 is a BucketLocationConstraint enum value BucketLocationConstraintEuCentral1 = "eu-central-1" + + // BucketLocationConstraintEuNorth1 is a BucketLocationConstraint enum value + BucketLocationConstraintEuNorth1 = "eu-north-1" + + // BucketLocationConstraintEuSouth1 is a BucketLocationConstraint enum value + BucketLocationConstraintEuSouth1 = "eu-south-1" + + // BucketLocationConstraintEuWest1 is a BucketLocationConstraint enum value + BucketLocationConstraintEuWest1 = "eu-west-1" + + // BucketLocationConstraintEuWest2 is a BucketLocationConstraint enum value + BucketLocationConstraintEuWest2 = "eu-west-2" + + // BucketLocationConstraintEuWest3 is a BucketLocationConstraint enum value + BucketLocationConstraintEuWest3 = "eu-west-3" + + // BucketLocationConstraintMeSouth1 is a BucketLocationConstraint enum value + BucketLocationConstraintMeSouth1 = "me-south-1" + + // BucketLocationConstraintSaEast1 is a BucketLocationConstraint enum value + BucketLocationConstraintSaEast1 = "sa-east-1" + + // BucketLocationConstraintUsEast2 is a BucketLocationConstraint enum value + BucketLocationConstraintUsEast2 = "us-east-2" + + // BucketLocationConstraintUsGovEast1 is a BucketLocationConstraint enum value + BucketLocationConstraintUsGovEast1 = "us-gov-east-1" + + // BucketLocationConstraintUsGovWest1 is a BucketLocationConstraint enum value + BucketLocationConstraintUsGovWest1 = "us-gov-west-1" + + // BucketLocationConstraintUsWest1 is a BucketLocationConstraint enum value + BucketLocationConstraintUsWest1 = "us-west-1" + + // BucketLocationConstraintUsWest2 is a BucketLocationConstraint enum value + BucketLocationConstraintUsWest2 = "us-west-2" ) +// BucketLocationConstraint_Values returns all elements of the BucketLocationConstraint enum +func BucketLocationConstraint_Values() []string { + return []string{ + BucketLocationConstraintAfSouth1, + BucketLocationConstraintApEast1, + BucketLocationConstraintApNortheast1, + BucketLocationConstraintApNortheast2, + BucketLocationConstraintApNortheast3, + BucketLocationConstraintApSouth1, + BucketLocationConstraintApSoutheast1, + BucketLocationConstraintApSoutheast2, + BucketLocationConstraintCaCentral1, + BucketLocationConstraintCnNorth1, + BucketLocationConstraintCnNorthwest1, + BucketLocationConstraintEu, + BucketLocationConstraintEuCentral1, + BucketLocationConstraintEuNorth1, + BucketLocationConstraintEuSouth1, + BucketLocationConstraintEuWest1, + BucketLocationConstraintEuWest2, + BucketLocationConstraintEuWest3, + BucketLocationConstraintMeSouth1, + BucketLocationConstraintSaEast1, + BucketLocationConstraintUsEast2, + BucketLocationConstraintUsGovEast1, + BucketLocationConstraintUsGovWest1, + BucketLocationConstraintUsWest1, + BucketLocationConstraintUsWest2, + } +} + const ( // BucketLogsPermissionFullControl is a BucketLogsPermission enum value BucketLogsPermissionFullControl = "FULL_CONTROL" @@ -30192,6 +30418,15 @@ const ( BucketLogsPermissionWrite = "WRITE" ) +// BucketLogsPermission_Values returns all elements of the BucketLogsPermission enum +func BucketLogsPermission_Values() []string { + return []string{ + BucketLogsPermissionFullControl, + BucketLogsPermissionRead, + BucketLogsPermissionWrite, + } +} + const ( // BucketVersioningStatusEnabled is a BucketVersioningStatus enum value BucketVersioningStatusEnabled = "Enabled" @@ -30200,6 +30435,14 @@ const ( BucketVersioningStatusSuspended = "Suspended" ) +// BucketVersioningStatus_Values returns all elements of the BucketVersioningStatus enum +func BucketVersioningStatus_Values() []string { + return []string{ + BucketVersioningStatusEnabled, + BucketVersioningStatusSuspended, + } +} + const ( // CompressionTypeNone is a CompressionType enum value CompressionTypeNone = "NONE" @@ -30211,6 +30454,15 @@ const ( CompressionTypeBzip2 = "BZIP2" ) +// CompressionType_Values returns all elements of the CompressionType enum +func CompressionType_Values() []string { + return []string{ + CompressionTypeNone, + CompressionTypeGzip, + CompressionTypeBzip2, + } +} + const ( // DeleteMarkerReplicationStatusEnabled is a DeleteMarkerReplicationStatus enum value DeleteMarkerReplicationStatusEnabled = "Enabled" @@ -30219,6 +30471,14 @@ const ( DeleteMarkerReplicationStatusDisabled = "Disabled" ) +// DeleteMarkerReplicationStatus_Values returns all elements of the DeleteMarkerReplicationStatus enum +func DeleteMarkerReplicationStatus_Values() []string { + return []string{ + DeleteMarkerReplicationStatusEnabled, + DeleteMarkerReplicationStatusDisabled, + } +} + // Requests Amazon S3 to encode the object keys in the response and specifies // the encoding method to use. An object key may contain any Unicode character; // however, XML 1.0 parser cannot parse some characters, such as characters @@ -30230,6 +30490,13 @@ const ( EncodingTypeUrl = "url" ) +// EncodingType_Values returns all elements of the EncodingType enum +func EncodingType_Values() []string { + return []string{ + EncodingTypeUrl, + } +} + // The bucket event for which to send notifications. const ( // EventS3ReducedRedundancyLostObject is a Event enum value @@ -30284,6 +30551,29 @@ const ( EventS3ReplicationOperationReplicatedAfterThreshold = "s3:Replication:OperationReplicatedAfterThreshold" ) +// Event_Values returns all elements of the Event enum +func Event_Values() []string { + return []string{ + EventS3ReducedRedundancyLostObject, + EventS3ObjectCreated, + EventS3ObjectCreatedPut, + EventS3ObjectCreatedPost, + EventS3ObjectCreatedCopy, + EventS3ObjectCreatedCompleteMultipartUpload, + EventS3ObjectRemoved, + EventS3ObjectRemovedDelete, + EventS3ObjectRemovedDeleteMarkerCreated, + EventS3ObjectRestore, + EventS3ObjectRestorePost, + EventS3ObjectRestoreCompleted, + EventS3Replication, + EventS3ReplicationOperationFailedReplication, + EventS3ReplicationOperationNotTracked, + EventS3ReplicationOperationMissedThreshold, + EventS3ReplicationOperationReplicatedAfterThreshold, + } +} + const ( // ExistingObjectReplicationStatusEnabled is a ExistingObjectReplicationStatus enum value ExistingObjectReplicationStatusEnabled = "Enabled" @@ -30292,6 +30582,14 @@ const ( ExistingObjectReplicationStatusDisabled = "Disabled" ) +// ExistingObjectReplicationStatus_Values returns all elements of the ExistingObjectReplicationStatus enum +func ExistingObjectReplicationStatus_Values() []string { + return []string{ + ExistingObjectReplicationStatusEnabled, + ExistingObjectReplicationStatusDisabled, + } +} + const ( // ExpirationStatusEnabled is a ExpirationStatus enum value ExpirationStatusEnabled = "Enabled" @@ -30300,11 +30598,26 @@ const ( ExpirationStatusDisabled = "Disabled" ) +// ExpirationStatus_Values returns all elements of the ExpirationStatus enum +func ExpirationStatus_Values() []string { + return []string{ + ExpirationStatusEnabled, + ExpirationStatusDisabled, + } +} + const ( // ExpressionTypeSql is a ExpressionType enum value ExpressionTypeSql = "SQL" ) +// ExpressionType_Values returns all elements of the ExpressionType enum +func ExpressionType_Values() []string { + return []string{ + ExpressionTypeSql, + } +} + const ( // FileHeaderInfoUse is a FileHeaderInfo enum value FileHeaderInfoUse = "USE" @@ -30316,6 +30629,15 @@ const ( FileHeaderInfoNone = "NONE" ) +// FileHeaderInfo_Values returns all elements of the FileHeaderInfo enum +func FileHeaderInfo_Values() []string { + return []string{ + FileHeaderInfoUse, + FileHeaderInfoIgnore, + FileHeaderInfoNone, + } +} + const ( // FilterRuleNamePrefix is a FilterRuleName enum value FilterRuleNamePrefix = "prefix" @@ -30324,6 +30646,14 @@ const ( FilterRuleNameSuffix = "suffix" ) +// FilterRuleName_Values returns all elements of the FilterRuleName enum +func FilterRuleName_Values() []string { + return []string{ + FilterRuleNamePrefix, + FilterRuleNameSuffix, + } +} + const ( // InventoryFormatCsv is a InventoryFormat enum value InventoryFormatCsv = "CSV" @@ -30335,6 +30665,15 @@ const ( InventoryFormatParquet = "Parquet" ) +// InventoryFormat_Values returns all elements of the InventoryFormat enum +func InventoryFormat_Values() []string { + return []string{ + InventoryFormatCsv, + InventoryFormatOrc, + InventoryFormatParquet, + } +} + const ( // InventoryFrequencyDaily is a InventoryFrequency enum value InventoryFrequencyDaily = "Daily" @@ -30343,6 +30682,14 @@ const ( InventoryFrequencyWeekly = "Weekly" ) +// InventoryFrequency_Values returns all elements of the InventoryFrequency enum +func InventoryFrequency_Values() []string { + return []string{ + InventoryFrequencyDaily, + InventoryFrequencyWeekly, + } +} + const ( // InventoryIncludedObjectVersionsAll is a InventoryIncludedObjectVersions enum value InventoryIncludedObjectVersionsAll = "All" @@ -30351,6 +30698,14 @@ const ( InventoryIncludedObjectVersionsCurrent = "Current" ) +// InventoryIncludedObjectVersions_Values returns all elements of the InventoryIncludedObjectVersions enum +func InventoryIncludedObjectVersions_Values() []string { + return []string{ + InventoryIncludedObjectVersionsAll, + InventoryIncludedObjectVersionsCurrent, + } +} + const ( // InventoryOptionalFieldSize is a InventoryOptionalField enum value InventoryOptionalFieldSize = "Size" @@ -30386,6 +30741,23 @@ const ( InventoryOptionalFieldIntelligentTieringAccessTier = "IntelligentTieringAccessTier" ) +// InventoryOptionalField_Values returns all elements of the InventoryOptionalField enum +func InventoryOptionalField_Values() []string { + return []string{ + InventoryOptionalFieldSize, + InventoryOptionalFieldLastModifiedDate, + InventoryOptionalFieldStorageClass, + InventoryOptionalFieldEtag, + InventoryOptionalFieldIsMultipartUploaded, + InventoryOptionalFieldReplicationStatus, + InventoryOptionalFieldEncryptionStatus, + InventoryOptionalFieldObjectLockRetainUntilDate, + InventoryOptionalFieldObjectLockMode, + InventoryOptionalFieldObjectLockLegalHoldStatus, + InventoryOptionalFieldIntelligentTieringAccessTier, + } +} + const ( // JSONTypeDocument is a JSONType enum value JSONTypeDocument = "DOCUMENT" @@ -30394,6 +30766,14 @@ const ( JSONTypeLines = "LINES" ) +// JSONType_Values returns all elements of the JSONType enum +func JSONType_Values() []string { + return []string{ + JSONTypeDocument, + JSONTypeLines, + } +} + const ( // MFADeleteEnabled is a MFADelete enum value MFADeleteEnabled = "Enabled" @@ -30402,6 +30782,14 @@ const ( MFADeleteDisabled = "Disabled" ) +// MFADelete_Values returns all elements of the MFADelete enum +func MFADelete_Values() []string { + return []string{ + MFADeleteEnabled, + MFADeleteDisabled, + } +} + const ( // MFADeleteStatusEnabled is a MFADeleteStatus enum value MFADeleteStatusEnabled = "Enabled" @@ -30410,6 +30798,14 @@ const ( MFADeleteStatusDisabled = "Disabled" ) +// MFADeleteStatus_Values returns all elements of the MFADeleteStatus enum +func MFADeleteStatus_Values() []string { + return []string{ + MFADeleteStatusEnabled, + MFADeleteStatusDisabled, + } +} + const ( // MetadataDirectiveCopy is a MetadataDirective enum value MetadataDirectiveCopy = "COPY" @@ -30418,6 +30814,14 @@ const ( MetadataDirectiveReplace = "REPLACE" ) +// MetadataDirective_Values returns all elements of the MetadataDirective enum +func MetadataDirective_Values() []string { + return []string{ + MetadataDirectiveCopy, + MetadataDirectiveReplace, + } +} + const ( // MetricsStatusEnabled is a MetricsStatus enum value MetricsStatusEnabled = "Enabled" @@ -30426,6 +30830,14 @@ const ( MetricsStatusDisabled = "Disabled" ) +// MetricsStatus_Values returns all elements of the MetricsStatus enum +func MetricsStatus_Values() []string { + return []string{ + MetricsStatusEnabled, + MetricsStatusDisabled, + } +} + const ( // ObjectCannedACLPrivate is a ObjectCannedACL enum value ObjectCannedACLPrivate = "private" @@ -30449,11 +30861,31 @@ const ( ObjectCannedACLBucketOwnerFullControl = "bucket-owner-full-control" ) +// ObjectCannedACL_Values returns all elements of the ObjectCannedACL enum +func ObjectCannedACL_Values() []string { + return []string{ + ObjectCannedACLPrivate, + ObjectCannedACLPublicRead, + ObjectCannedACLPublicReadWrite, + ObjectCannedACLAuthenticatedRead, + ObjectCannedACLAwsExecRead, + ObjectCannedACLBucketOwnerRead, + ObjectCannedACLBucketOwnerFullControl, + } +} + const ( // ObjectLockEnabledEnabled is a ObjectLockEnabled enum value ObjectLockEnabledEnabled = "Enabled" ) +// ObjectLockEnabled_Values returns all elements of the ObjectLockEnabled enum +func ObjectLockEnabled_Values() []string { + return []string{ + ObjectLockEnabledEnabled, + } +} + const ( // ObjectLockLegalHoldStatusOn is a ObjectLockLegalHoldStatus enum value ObjectLockLegalHoldStatusOn = "ON" @@ -30462,6 +30894,14 @@ const ( ObjectLockLegalHoldStatusOff = "OFF" ) +// ObjectLockLegalHoldStatus_Values returns all elements of the ObjectLockLegalHoldStatus enum +func ObjectLockLegalHoldStatus_Values() []string { + return []string{ + ObjectLockLegalHoldStatusOn, + ObjectLockLegalHoldStatusOff, + } +} + const ( // ObjectLockModeGovernance is a ObjectLockMode enum value ObjectLockModeGovernance = "GOVERNANCE" @@ -30470,6 +30910,14 @@ const ( ObjectLockModeCompliance = "COMPLIANCE" ) +// ObjectLockMode_Values returns all elements of the ObjectLockMode enum +func ObjectLockMode_Values() []string { + return []string{ + ObjectLockModeGovernance, + ObjectLockModeCompliance, + } +} + const ( // ObjectLockRetentionModeGovernance is a ObjectLockRetentionMode enum value ObjectLockRetentionModeGovernance = "GOVERNANCE" @@ -30478,6 +30926,14 @@ const ( ObjectLockRetentionModeCompliance = "COMPLIANCE" ) +// ObjectLockRetentionMode_Values returns all elements of the ObjectLockRetentionMode enum +func ObjectLockRetentionMode_Values() []string { + return []string{ + ObjectLockRetentionModeGovernance, + ObjectLockRetentionModeCompliance, + } +} + const ( // ObjectStorageClassStandard is a ObjectStorageClass enum value ObjectStorageClassStandard = "STANDARD" @@ -30501,16 +30957,43 @@ const ( ObjectStorageClassDeepArchive = "DEEP_ARCHIVE" ) +// ObjectStorageClass_Values returns all elements of the ObjectStorageClass enum +func ObjectStorageClass_Values() []string { + return []string{ + ObjectStorageClassStandard, + ObjectStorageClassReducedRedundancy, + ObjectStorageClassGlacier, + ObjectStorageClassStandardIa, + ObjectStorageClassOnezoneIa, + ObjectStorageClassIntelligentTiering, + ObjectStorageClassDeepArchive, + } +} + const ( // ObjectVersionStorageClassStandard is a ObjectVersionStorageClass enum value ObjectVersionStorageClassStandard = "STANDARD" ) +// ObjectVersionStorageClass_Values returns all elements of the ObjectVersionStorageClass enum +func ObjectVersionStorageClass_Values() []string { + return []string{ + ObjectVersionStorageClassStandard, + } +} + const ( // OwnerOverrideDestination is a OwnerOverride enum value OwnerOverrideDestination = "Destination" ) +// OwnerOverride_Values returns all elements of the OwnerOverride enum +func OwnerOverride_Values() []string { + return []string{ + OwnerOverrideDestination, + } +} + const ( // PayerRequester is a Payer enum value PayerRequester = "Requester" @@ -30519,6 +31002,14 @@ const ( PayerBucketOwner = "BucketOwner" ) +// Payer_Values returns all elements of the Payer enum +func Payer_Values() []string { + return []string{ + PayerRequester, + PayerBucketOwner, + } +} + const ( // PermissionFullControl is a Permission enum value PermissionFullControl = "FULL_CONTROL" @@ -30536,6 +31027,17 @@ const ( PermissionReadAcp = "READ_ACP" ) +// Permission_Values returns all elements of the Permission enum +func Permission_Values() []string { + return []string{ + PermissionFullControl, + PermissionWrite, + PermissionWriteAcp, + PermissionRead, + PermissionReadAcp, + } +} + const ( // ProtocolHttp is a Protocol enum value ProtocolHttp = "http" @@ -30544,6 +31046,14 @@ const ( ProtocolHttps = "https" ) +// Protocol_Values returns all elements of the Protocol enum +func Protocol_Values() []string { + return []string{ + ProtocolHttp, + ProtocolHttps, + } +} + const ( // QuoteFieldsAlways is a QuoteFields enum value QuoteFieldsAlways = "ALWAYS" @@ -30552,6 +31062,14 @@ const ( QuoteFieldsAsneeded = "ASNEEDED" ) +// QuoteFields_Values returns all elements of the QuoteFields enum +func QuoteFields_Values() []string { + return []string{ + QuoteFieldsAlways, + QuoteFieldsAsneeded, + } +} + const ( // ReplicationRuleStatusEnabled is a ReplicationRuleStatus enum value ReplicationRuleStatusEnabled = "Enabled" @@ -30560,6 +31078,14 @@ const ( ReplicationRuleStatusDisabled = "Disabled" ) +// ReplicationRuleStatus_Values returns all elements of the ReplicationRuleStatus enum +func ReplicationRuleStatus_Values() []string { + return []string{ + ReplicationRuleStatusEnabled, + ReplicationRuleStatusDisabled, + } +} + const ( // ReplicationStatusComplete is a ReplicationStatus enum value ReplicationStatusComplete = "COMPLETE" @@ -30574,6 +31100,16 @@ const ( ReplicationStatusReplica = "REPLICA" ) +// ReplicationStatus_Values returns all elements of the ReplicationStatus enum +func ReplicationStatus_Values() []string { + return []string{ + ReplicationStatusComplete, + ReplicationStatusPending, + ReplicationStatusFailed, + ReplicationStatusReplica, + } +} + const ( // ReplicationTimeStatusEnabled is a ReplicationTimeStatus enum value ReplicationTimeStatusEnabled = "Enabled" @@ -30582,6 +31118,14 @@ const ( ReplicationTimeStatusDisabled = "Disabled" ) +// ReplicationTimeStatus_Values returns all elements of the ReplicationTimeStatus enum +func ReplicationTimeStatus_Values() []string { + return []string{ + ReplicationTimeStatusEnabled, + ReplicationTimeStatusDisabled, + } +} + // If present, indicates that the requester was successfully charged for the // request. const ( @@ -30589,6 +31133,13 @@ const ( RequestChargedRequester = "requester" ) +// RequestCharged_Values returns all elements of the RequestCharged enum +func RequestCharged_Values() []string { + return []string{ + RequestChargedRequester, + } +} + // Confirms that the requester knows that they will be charged for the request. // Bucket owners need not specify this parameter in their requests. For information // about downloading objects from requester pays buckets, see Downloading Objects @@ -30599,11 +31150,25 @@ const ( RequestPayerRequester = "requester" ) +// RequestPayer_Values returns all elements of the RequestPayer enum +func RequestPayer_Values() []string { + return []string{ + RequestPayerRequester, + } +} + const ( // RestoreRequestTypeSelect is a RestoreRequestType enum value RestoreRequestTypeSelect = "SELECT" ) +// RestoreRequestType_Values returns all elements of the RestoreRequestType enum +func RestoreRequestType_Values() []string { + return []string{ + RestoreRequestTypeSelect, + } +} + const ( // ServerSideEncryptionAes256 is a ServerSideEncryption enum value ServerSideEncryptionAes256 = "AES256" @@ -30612,6 +31177,14 @@ const ( ServerSideEncryptionAwsKms = "aws:kms" ) +// ServerSideEncryption_Values returns all elements of the ServerSideEncryption enum +func ServerSideEncryption_Values() []string { + return []string{ + ServerSideEncryptionAes256, + ServerSideEncryptionAwsKms, + } +} + const ( // SseKmsEncryptedObjectsStatusEnabled is a SseKmsEncryptedObjectsStatus enum value SseKmsEncryptedObjectsStatusEnabled = "Enabled" @@ -30620,6 +31193,14 @@ const ( SseKmsEncryptedObjectsStatusDisabled = "Disabled" ) +// SseKmsEncryptedObjectsStatus_Values returns all elements of the SseKmsEncryptedObjectsStatus enum +func SseKmsEncryptedObjectsStatus_Values() []string { + return []string{ + SseKmsEncryptedObjectsStatusEnabled, + SseKmsEncryptedObjectsStatusDisabled, + } +} + const ( // StorageClassStandard is a StorageClass enum value StorageClassStandard = "STANDARD" @@ -30643,11 +31224,31 @@ const ( StorageClassDeepArchive = "DEEP_ARCHIVE" ) +// StorageClass_Values returns all elements of the StorageClass enum +func StorageClass_Values() []string { + return []string{ + StorageClassStandard, + StorageClassReducedRedundancy, + StorageClassStandardIa, + StorageClassOnezoneIa, + StorageClassIntelligentTiering, + StorageClassGlacier, + StorageClassDeepArchive, + } +} + const ( // StorageClassAnalysisSchemaVersionV1 is a StorageClassAnalysisSchemaVersion enum value StorageClassAnalysisSchemaVersionV1 = "V_1" ) +// StorageClassAnalysisSchemaVersion_Values returns all elements of the StorageClassAnalysisSchemaVersion enum +func StorageClassAnalysisSchemaVersion_Values() []string { + return []string{ + StorageClassAnalysisSchemaVersionV1, + } +} + const ( // TaggingDirectiveCopy is a TaggingDirective enum value TaggingDirectiveCopy = "COPY" @@ -30656,6 +31257,14 @@ const ( TaggingDirectiveReplace = "REPLACE" ) +// TaggingDirective_Values returns all elements of the TaggingDirective enum +func TaggingDirective_Values() []string { + return []string{ + TaggingDirectiveCopy, + TaggingDirectiveReplace, + } +} + const ( // TierStandard is a Tier enum value TierStandard = "Standard" @@ -30667,6 +31276,15 @@ const ( TierExpedited = "Expedited" ) +// Tier_Values returns all elements of the Tier enum +func Tier_Values() []string { + return []string{ + TierStandard, + TierBulk, + TierExpedited, + } +} + const ( // TransitionStorageClassGlacier is a TransitionStorageClass enum value TransitionStorageClassGlacier = "GLACIER" @@ -30684,6 +31302,17 @@ const ( TransitionStorageClassDeepArchive = "DEEP_ARCHIVE" ) +// TransitionStorageClass_Values returns all elements of the TransitionStorageClass enum +func TransitionStorageClass_Values() []string { + return []string{ + TransitionStorageClassGlacier, + TransitionStorageClassStandardIa, + TransitionStorageClassOnezoneIa, + TransitionStorageClassIntelligentTiering, + TransitionStorageClassDeepArchive, + } +} + const ( // TypeCanonicalUser is a Type enum value TypeCanonicalUser = "CanonicalUser" @@ -30694,3 +31323,12 @@ const ( // TypeGroup is a Type enum value TypeGroup = "Group" ) + +// Type_Values returns all elements of the Type enum +func Type_Values() []string { + return []string{ + TypeCanonicalUser, + TypeAmazonCustomerByEmail, + TypeGroup, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go b/vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go index 5c8ce5cc8a5..407f06b6ede 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go @@ -13,7 +13,6 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkio" ) const ( @@ -25,30 +24,6 @@ const ( appendMD5TxEncoding = "append-md5" ) -// contentMD5 computes and sets the HTTP Content-MD5 header for requests that -// require it. -func contentMD5(r *request.Request) { - h := md5.New() - - if !aws.IsReaderSeekable(r.Body) { - if r.Config.Logger != nil { - r.Config.Logger.Log(fmt.Sprintf( - "Unable to compute Content-MD5 for unseekable body, S3.%s", - r.Operation.Name)) - } - return - } - - if _, err := copySeekableBody(h, r.Body); err != nil { - r.Error = awserr.New("ContentMD5", "failed to compute body MD5", err) - return - } - - // encode the md5 checksum in base64 and set the request header. - v := base64.StdEncoding.EncodeToString(h.Sum(nil)) - r.HTTPRequest.Header.Set(contentMD5Header, v) -} - // computeBodyHashes will add Content MD5 and Content Sha256 hashes to the // request. If the body is not seekable or S3DisableContentMD5Validation set // this handler will be ignored. @@ -90,7 +65,7 @@ func computeBodyHashes(r *request.Request) { dst = io.MultiWriter(hashers...) } - if _, err := copySeekableBody(dst, r.Body); err != nil { + if _, err := aws.CopySeekableBody(dst, r.Body); err != nil { r.Error = awserr.New("BodyHashError", "failed to compute body hashes", err) return } @@ -119,28 +94,6 @@ const ( sha256HexEncLen = sha256.Size * 2 // hex.EncodedLen ) -func copySeekableBody(dst io.Writer, src io.ReadSeeker) (int64, error) { - curPos, err := src.Seek(0, sdkio.SeekCurrent) - if err != nil { - return 0, err - } - - // hash the body. seek back to the first position after reading to reset - // the body for transmission. copy errors may be assumed to be from the - // body. - n, err := io.Copy(dst, src) - if err != nil { - return n, err - } - - _, err = src.Seek(curPos, sdkio.SeekStart) - if err != nil { - return n, err - } - - return n, nil -} - // Adds the x-amz-te: append_md5 header to the request. This requests the service // responds with a trailing MD5 checksum. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go index 036d0b2e013..a7698d5eb94 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go @@ -33,12 +33,6 @@ func defaultInitRequestFn(r *request.Request) { platformRequestHandlers(r) switch r.Operation.Name { - case opPutBucketCors, opPutBucketLifecycle, opPutBucketPolicy, - opPutBucketTagging, opDeleteObjects, opPutBucketLifecycleConfiguration, - opPutObjectLegalHold, opPutObjectRetention, opPutObjectLockConfiguration, - opPutBucketReplication: - // These S3 operations require Content-MD5 to be set - r.Handlers.Build.PushBack(contentMD5) case opGetBucketLocation: // GetBucketLocation has custom parsing logic r.Handlers.Unmarshal.PushFront(buildGetBucketLocation) diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go b/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go index 4b65f71531a..7f7aca20859 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go @@ -104,19 +104,6 @@ // content from S3. The Encryption and Decryption clients can be used concurrently // once the client is created. // -// sess := session.Must(session.NewSession()) -// -// // Create the decryption client. -// svc := s3crypto.NewDecryptionClient(sess) -// -// // The object will be downloaded from S3 and decrypted locally. By metadata -// // about the object's encryption will instruct the decryption client how -// // decrypt the content of the object. By default KMS is used for keys. -// result, err := svc.GetObject(&s3.GetObjectInput { -// Bucket: aws.String(myBucket), -// Key: aws.String(myKey), -// }) -// // See the s3crypto package documentation for more information. // https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/ // diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3iface/interface.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3iface/interface.go new file mode 100644 index 00000000000..2646a42722b --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3iface/interface.go @@ -0,0 +1,443 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package s3iface provides an interface to enable mocking the Amazon Simple Storage Service service client +// for testing your code. +// +// It is important to note that this interface will have breaking changes +// when the service model is updated and adds new API operations, paginators, +// and waiters. +package s3iface + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/service/s3" +) + +// S3API provides an interface to enable mocking the +// s3.S3 service client's API operation, +// paginators, and waiters. This make unit testing your code that calls out +// to the SDK's service client's calls easier. +// +// The best way to use this interface is so the SDK's service client's calls +// can be stubbed out for unit testing your code with the SDK without needing +// to inject custom request handlers into the SDK's request pipeline. +// +// // myFunc uses an SDK service client to make a request to +// // Amazon Simple Storage Service. +// func myFunc(svc s3iface.S3API) bool { +// // Make svc.AbortMultipartUpload request +// } +// +// func main() { +// sess := session.New() +// svc := s3.New(sess) +// +// myFunc(svc) +// } +// +// In your _test.go file: +// +// // Define a mock struct to be used in your unit tests of myFunc. +// type mockS3Client struct { +// s3iface.S3API +// } +// func (m *mockS3Client) AbortMultipartUpload(input *s3.AbortMultipartUploadInput) (*s3.AbortMultipartUploadOutput, error) { +// // mock response/functionality +// } +// +// func TestMyFunc(t *testing.T) { +// // Setup Test +// mockSvc := &mockS3Client{} +// +// myfunc(mockSvc) +// +// // Verify myFunc's functionality +// } +// +// It is important to note that this interface will have breaking changes +// when the service model is updated and adds new API operations, paginators, +// and waiters. Its suggested to use the pattern above for testing, or using +// tooling to generate mocks to satisfy the interfaces. +type S3API interface { + AbortMultipartUpload(*s3.AbortMultipartUploadInput) (*s3.AbortMultipartUploadOutput, error) + AbortMultipartUploadWithContext(aws.Context, *s3.AbortMultipartUploadInput, ...request.Option) (*s3.AbortMultipartUploadOutput, error) + AbortMultipartUploadRequest(*s3.AbortMultipartUploadInput) (*request.Request, *s3.AbortMultipartUploadOutput) + + CompleteMultipartUpload(*s3.CompleteMultipartUploadInput) (*s3.CompleteMultipartUploadOutput, error) + CompleteMultipartUploadWithContext(aws.Context, *s3.CompleteMultipartUploadInput, ...request.Option) (*s3.CompleteMultipartUploadOutput, error) + CompleteMultipartUploadRequest(*s3.CompleteMultipartUploadInput) (*request.Request, *s3.CompleteMultipartUploadOutput) + + CopyObject(*s3.CopyObjectInput) (*s3.CopyObjectOutput, error) + CopyObjectWithContext(aws.Context, *s3.CopyObjectInput, ...request.Option) (*s3.CopyObjectOutput, error) + CopyObjectRequest(*s3.CopyObjectInput) (*request.Request, *s3.CopyObjectOutput) + + CreateBucket(*s3.CreateBucketInput) (*s3.CreateBucketOutput, error) + CreateBucketWithContext(aws.Context, *s3.CreateBucketInput, ...request.Option) (*s3.CreateBucketOutput, error) + CreateBucketRequest(*s3.CreateBucketInput) (*request.Request, *s3.CreateBucketOutput) + + CreateMultipartUpload(*s3.CreateMultipartUploadInput) (*s3.CreateMultipartUploadOutput, error) + CreateMultipartUploadWithContext(aws.Context, *s3.CreateMultipartUploadInput, ...request.Option) (*s3.CreateMultipartUploadOutput, error) + CreateMultipartUploadRequest(*s3.CreateMultipartUploadInput) (*request.Request, *s3.CreateMultipartUploadOutput) + + DeleteBucket(*s3.DeleteBucketInput) (*s3.DeleteBucketOutput, error) + DeleteBucketWithContext(aws.Context, *s3.DeleteBucketInput, ...request.Option) (*s3.DeleteBucketOutput, error) + DeleteBucketRequest(*s3.DeleteBucketInput) (*request.Request, *s3.DeleteBucketOutput) + + DeleteBucketAnalyticsConfiguration(*s3.DeleteBucketAnalyticsConfigurationInput) (*s3.DeleteBucketAnalyticsConfigurationOutput, error) + DeleteBucketAnalyticsConfigurationWithContext(aws.Context, *s3.DeleteBucketAnalyticsConfigurationInput, ...request.Option) (*s3.DeleteBucketAnalyticsConfigurationOutput, error) + DeleteBucketAnalyticsConfigurationRequest(*s3.DeleteBucketAnalyticsConfigurationInput) (*request.Request, *s3.DeleteBucketAnalyticsConfigurationOutput) + + DeleteBucketCors(*s3.DeleteBucketCorsInput) (*s3.DeleteBucketCorsOutput, error) + DeleteBucketCorsWithContext(aws.Context, *s3.DeleteBucketCorsInput, ...request.Option) (*s3.DeleteBucketCorsOutput, error) + DeleteBucketCorsRequest(*s3.DeleteBucketCorsInput) (*request.Request, *s3.DeleteBucketCorsOutput) + + DeleteBucketEncryption(*s3.DeleteBucketEncryptionInput) (*s3.DeleteBucketEncryptionOutput, error) + DeleteBucketEncryptionWithContext(aws.Context, *s3.DeleteBucketEncryptionInput, ...request.Option) (*s3.DeleteBucketEncryptionOutput, error) + DeleteBucketEncryptionRequest(*s3.DeleteBucketEncryptionInput) (*request.Request, *s3.DeleteBucketEncryptionOutput) + + DeleteBucketInventoryConfiguration(*s3.DeleteBucketInventoryConfigurationInput) (*s3.DeleteBucketInventoryConfigurationOutput, error) + DeleteBucketInventoryConfigurationWithContext(aws.Context, *s3.DeleteBucketInventoryConfigurationInput, ...request.Option) (*s3.DeleteBucketInventoryConfigurationOutput, error) + DeleteBucketInventoryConfigurationRequest(*s3.DeleteBucketInventoryConfigurationInput) (*request.Request, *s3.DeleteBucketInventoryConfigurationOutput) + + DeleteBucketLifecycle(*s3.DeleteBucketLifecycleInput) (*s3.DeleteBucketLifecycleOutput, error) + DeleteBucketLifecycleWithContext(aws.Context, *s3.DeleteBucketLifecycleInput, ...request.Option) (*s3.DeleteBucketLifecycleOutput, error) + DeleteBucketLifecycleRequest(*s3.DeleteBucketLifecycleInput) (*request.Request, *s3.DeleteBucketLifecycleOutput) + + DeleteBucketMetricsConfiguration(*s3.DeleteBucketMetricsConfigurationInput) (*s3.DeleteBucketMetricsConfigurationOutput, error) + DeleteBucketMetricsConfigurationWithContext(aws.Context, *s3.DeleteBucketMetricsConfigurationInput, ...request.Option) (*s3.DeleteBucketMetricsConfigurationOutput, error) + DeleteBucketMetricsConfigurationRequest(*s3.DeleteBucketMetricsConfigurationInput) (*request.Request, *s3.DeleteBucketMetricsConfigurationOutput) + + DeleteBucketPolicy(*s3.DeleteBucketPolicyInput) (*s3.DeleteBucketPolicyOutput, error) + DeleteBucketPolicyWithContext(aws.Context, *s3.DeleteBucketPolicyInput, ...request.Option) (*s3.DeleteBucketPolicyOutput, error) + DeleteBucketPolicyRequest(*s3.DeleteBucketPolicyInput) (*request.Request, *s3.DeleteBucketPolicyOutput) + + DeleteBucketReplication(*s3.DeleteBucketReplicationInput) (*s3.DeleteBucketReplicationOutput, error) + DeleteBucketReplicationWithContext(aws.Context, *s3.DeleteBucketReplicationInput, ...request.Option) (*s3.DeleteBucketReplicationOutput, error) + DeleteBucketReplicationRequest(*s3.DeleteBucketReplicationInput) (*request.Request, *s3.DeleteBucketReplicationOutput) + + DeleteBucketTagging(*s3.DeleteBucketTaggingInput) (*s3.DeleteBucketTaggingOutput, error) + DeleteBucketTaggingWithContext(aws.Context, *s3.DeleteBucketTaggingInput, ...request.Option) (*s3.DeleteBucketTaggingOutput, error) + DeleteBucketTaggingRequest(*s3.DeleteBucketTaggingInput) (*request.Request, *s3.DeleteBucketTaggingOutput) + + DeleteBucketWebsite(*s3.DeleteBucketWebsiteInput) (*s3.DeleteBucketWebsiteOutput, error) + DeleteBucketWebsiteWithContext(aws.Context, *s3.DeleteBucketWebsiteInput, ...request.Option) (*s3.DeleteBucketWebsiteOutput, error) + DeleteBucketWebsiteRequest(*s3.DeleteBucketWebsiteInput) (*request.Request, *s3.DeleteBucketWebsiteOutput) + + DeleteObject(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) + DeleteObjectWithContext(aws.Context, *s3.DeleteObjectInput, ...request.Option) (*s3.DeleteObjectOutput, error) + DeleteObjectRequest(*s3.DeleteObjectInput) (*request.Request, *s3.DeleteObjectOutput) + + DeleteObjectTagging(*s3.DeleteObjectTaggingInput) (*s3.DeleteObjectTaggingOutput, error) + DeleteObjectTaggingWithContext(aws.Context, *s3.DeleteObjectTaggingInput, ...request.Option) (*s3.DeleteObjectTaggingOutput, error) + DeleteObjectTaggingRequest(*s3.DeleteObjectTaggingInput) (*request.Request, *s3.DeleteObjectTaggingOutput) + + DeleteObjects(*s3.DeleteObjectsInput) (*s3.DeleteObjectsOutput, error) + DeleteObjectsWithContext(aws.Context, *s3.DeleteObjectsInput, ...request.Option) (*s3.DeleteObjectsOutput, error) + DeleteObjectsRequest(*s3.DeleteObjectsInput) (*request.Request, *s3.DeleteObjectsOutput) + + DeletePublicAccessBlock(*s3.DeletePublicAccessBlockInput) (*s3.DeletePublicAccessBlockOutput, error) + DeletePublicAccessBlockWithContext(aws.Context, *s3.DeletePublicAccessBlockInput, ...request.Option) (*s3.DeletePublicAccessBlockOutput, error) + DeletePublicAccessBlockRequest(*s3.DeletePublicAccessBlockInput) (*request.Request, *s3.DeletePublicAccessBlockOutput) + + GetBucketAccelerateConfiguration(*s3.GetBucketAccelerateConfigurationInput) (*s3.GetBucketAccelerateConfigurationOutput, error) + GetBucketAccelerateConfigurationWithContext(aws.Context, *s3.GetBucketAccelerateConfigurationInput, ...request.Option) (*s3.GetBucketAccelerateConfigurationOutput, error) + GetBucketAccelerateConfigurationRequest(*s3.GetBucketAccelerateConfigurationInput) (*request.Request, *s3.GetBucketAccelerateConfigurationOutput) + + GetBucketAcl(*s3.GetBucketAclInput) (*s3.GetBucketAclOutput, error) + GetBucketAclWithContext(aws.Context, *s3.GetBucketAclInput, ...request.Option) (*s3.GetBucketAclOutput, error) + GetBucketAclRequest(*s3.GetBucketAclInput) (*request.Request, *s3.GetBucketAclOutput) + + GetBucketAnalyticsConfiguration(*s3.GetBucketAnalyticsConfigurationInput) (*s3.GetBucketAnalyticsConfigurationOutput, error) + GetBucketAnalyticsConfigurationWithContext(aws.Context, *s3.GetBucketAnalyticsConfigurationInput, ...request.Option) (*s3.GetBucketAnalyticsConfigurationOutput, error) + GetBucketAnalyticsConfigurationRequest(*s3.GetBucketAnalyticsConfigurationInput) (*request.Request, *s3.GetBucketAnalyticsConfigurationOutput) + + GetBucketCors(*s3.GetBucketCorsInput) (*s3.GetBucketCorsOutput, error) + GetBucketCorsWithContext(aws.Context, *s3.GetBucketCorsInput, ...request.Option) (*s3.GetBucketCorsOutput, error) + GetBucketCorsRequest(*s3.GetBucketCorsInput) (*request.Request, *s3.GetBucketCorsOutput) + + GetBucketEncryption(*s3.GetBucketEncryptionInput) (*s3.GetBucketEncryptionOutput, error) + GetBucketEncryptionWithContext(aws.Context, *s3.GetBucketEncryptionInput, ...request.Option) (*s3.GetBucketEncryptionOutput, error) + GetBucketEncryptionRequest(*s3.GetBucketEncryptionInput) (*request.Request, *s3.GetBucketEncryptionOutput) + + GetBucketInventoryConfiguration(*s3.GetBucketInventoryConfigurationInput) (*s3.GetBucketInventoryConfigurationOutput, error) + GetBucketInventoryConfigurationWithContext(aws.Context, *s3.GetBucketInventoryConfigurationInput, ...request.Option) (*s3.GetBucketInventoryConfigurationOutput, error) + GetBucketInventoryConfigurationRequest(*s3.GetBucketInventoryConfigurationInput) (*request.Request, *s3.GetBucketInventoryConfigurationOutput) + + GetBucketLifecycle(*s3.GetBucketLifecycleInput) (*s3.GetBucketLifecycleOutput, error) + GetBucketLifecycleWithContext(aws.Context, *s3.GetBucketLifecycleInput, ...request.Option) (*s3.GetBucketLifecycleOutput, error) + GetBucketLifecycleRequest(*s3.GetBucketLifecycleInput) (*request.Request, *s3.GetBucketLifecycleOutput) + + GetBucketLifecycleConfiguration(*s3.GetBucketLifecycleConfigurationInput) (*s3.GetBucketLifecycleConfigurationOutput, error) + GetBucketLifecycleConfigurationWithContext(aws.Context, *s3.GetBucketLifecycleConfigurationInput, ...request.Option) (*s3.GetBucketLifecycleConfigurationOutput, error) + GetBucketLifecycleConfigurationRequest(*s3.GetBucketLifecycleConfigurationInput) (*request.Request, *s3.GetBucketLifecycleConfigurationOutput) + + GetBucketLocation(*s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error) + GetBucketLocationWithContext(aws.Context, *s3.GetBucketLocationInput, ...request.Option) (*s3.GetBucketLocationOutput, error) + GetBucketLocationRequest(*s3.GetBucketLocationInput) (*request.Request, *s3.GetBucketLocationOutput) + + GetBucketLogging(*s3.GetBucketLoggingInput) (*s3.GetBucketLoggingOutput, error) + GetBucketLoggingWithContext(aws.Context, *s3.GetBucketLoggingInput, ...request.Option) (*s3.GetBucketLoggingOutput, error) + GetBucketLoggingRequest(*s3.GetBucketLoggingInput) (*request.Request, *s3.GetBucketLoggingOutput) + + GetBucketMetricsConfiguration(*s3.GetBucketMetricsConfigurationInput) (*s3.GetBucketMetricsConfigurationOutput, error) + GetBucketMetricsConfigurationWithContext(aws.Context, *s3.GetBucketMetricsConfigurationInput, ...request.Option) (*s3.GetBucketMetricsConfigurationOutput, error) + GetBucketMetricsConfigurationRequest(*s3.GetBucketMetricsConfigurationInput) (*request.Request, *s3.GetBucketMetricsConfigurationOutput) + + GetBucketNotification(*s3.GetBucketNotificationConfigurationRequest) (*s3.NotificationConfigurationDeprecated, error) + GetBucketNotificationWithContext(aws.Context, *s3.GetBucketNotificationConfigurationRequest, ...request.Option) (*s3.NotificationConfigurationDeprecated, error) + GetBucketNotificationRequest(*s3.GetBucketNotificationConfigurationRequest) (*request.Request, *s3.NotificationConfigurationDeprecated) + + GetBucketNotificationConfiguration(*s3.GetBucketNotificationConfigurationRequest) (*s3.NotificationConfiguration, error) + GetBucketNotificationConfigurationWithContext(aws.Context, *s3.GetBucketNotificationConfigurationRequest, ...request.Option) (*s3.NotificationConfiguration, error) + GetBucketNotificationConfigurationRequest(*s3.GetBucketNotificationConfigurationRequest) (*request.Request, *s3.NotificationConfiguration) + + GetBucketPolicy(*s3.GetBucketPolicyInput) (*s3.GetBucketPolicyOutput, error) + GetBucketPolicyWithContext(aws.Context, *s3.GetBucketPolicyInput, ...request.Option) (*s3.GetBucketPolicyOutput, error) + GetBucketPolicyRequest(*s3.GetBucketPolicyInput) (*request.Request, *s3.GetBucketPolicyOutput) + + GetBucketPolicyStatus(*s3.GetBucketPolicyStatusInput) (*s3.GetBucketPolicyStatusOutput, error) + GetBucketPolicyStatusWithContext(aws.Context, *s3.GetBucketPolicyStatusInput, ...request.Option) (*s3.GetBucketPolicyStatusOutput, error) + GetBucketPolicyStatusRequest(*s3.GetBucketPolicyStatusInput) (*request.Request, *s3.GetBucketPolicyStatusOutput) + + GetBucketReplication(*s3.GetBucketReplicationInput) (*s3.GetBucketReplicationOutput, error) + GetBucketReplicationWithContext(aws.Context, *s3.GetBucketReplicationInput, ...request.Option) (*s3.GetBucketReplicationOutput, error) + GetBucketReplicationRequest(*s3.GetBucketReplicationInput) (*request.Request, *s3.GetBucketReplicationOutput) + + GetBucketRequestPayment(*s3.GetBucketRequestPaymentInput) (*s3.GetBucketRequestPaymentOutput, error) + GetBucketRequestPaymentWithContext(aws.Context, *s3.GetBucketRequestPaymentInput, ...request.Option) (*s3.GetBucketRequestPaymentOutput, error) + GetBucketRequestPaymentRequest(*s3.GetBucketRequestPaymentInput) (*request.Request, *s3.GetBucketRequestPaymentOutput) + + GetBucketTagging(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error) + GetBucketTaggingWithContext(aws.Context, *s3.GetBucketTaggingInput, ...request.Option) (*s3.GetBucketTaggingOutput, error) + GetBucketTaggingRequest(*s3.GetBucketTaggingInput) (*request.Request, *s3.GetBucketTaggingOutput) + + GetBucketVersioning(*s3.GetBucketVersioningInput) (*s3.GetBucketVersioningOutput, error) + GetBucketVersioningWithContext(aws.Context, *s3.GetBucketVersioningInput, ...request.Option) (*s3.GetBucketVersioningOutput, error) + GetBucketVersioningRequest(*s3.GetBucketVersioningInput) (*request.Request, *s3.GetBucketVersioningOutput) + + GetBucketWebsite(*s3.GetBucketWebsiteInput) (*s3.GetBucketWebsiteOutput, error) + GetBucketWebsiteWithContext(aws.Context, *s3.GetBucketWebsiteInput, ...request.Option) (*s3.GetBucketWebsiteOutput, error) + GetBucketWebsiteRequest(*s3.GetBucketWebsiteInput) (*request.Request, *s3.GetBucketWebsiteOutput) + + GetObject(*s3.GetObjectInput) (*s3.GetObjectOutput, error) + GetObjectWithContext(aws.Context, *s3.GetObjectInput, ...request.Option) (*s3.GetObjectOutput, error) + GetObjectRequest(*s3.GetObjectInput) (*request.Request, *s3.GetObjectOutput) + + GetObjectAcl(*s3.GetObjectAclInput) (*s3.GetObjectAclOutput, error) + GetObjectAclWithContext(aws.Context, *s3.GetObjectAclInput, ...request.Option) (*s3.GetObjectAclOutput, error) + GetObjectAclRequest(*s3.GetObjectAclInput) (*request.Request, *s3.GetObjectAclOutput) + + GetObjectLegalHold(*s3.GetObjectLegalHoldInput) (*s3.GetObjectLegalHoldOutput, error) + GetObjectLegalHoldWithContext(aws.Context, *s3.GetObjectLegalHoldInput, ...request.Option) (*s3.GetObjectLegalHoldOutput, error) + GetObjectLegalHoldRequest(*s3.GetObjectLegalHoldInput) (*request.Request, *s3.GetObjectLegalHoldOutput) + + GetObjectLockConfiguration(*s3.GetObjectLockConfigurationInput) (*s3.GetObjectLockConfigurationOutput, error) + GetObjectLockConfigurationWithContext(aws.Context, *s3.GetObjectLockConfigurationInput, ...request.Option) (*s3.GetObjectLockConfigurationOutput, error) + GetObjectLockConfigurationRequest(*s3.GetObjectLockConfigurationInput) (*request.Request, *s3.GetObjectLockConfigurationOutput) + + GetObjectRetention(*s3.GetObjectRetentionInput) (*s3.GetObjectRetentionOutput, error) + GetObjectRetentionWithContext(aws.Context, *s3.GetObjectRetentionInput, ...request.Option) (*s3.GetObjectRetentionOutput, error) + GetObjectRetentionRequest(*s3.GetObjectRetentionInput) (*request.Request, *s3.GetObjectRetentionOutput) + + GetObjectTagging(*s3.GetObjectTaggingInput) (*s3.GetObjectTaggingOutput, error) + GetObjectTaggingWithContext(aws.Context, *s3.GetObjectTaggingInput, ...request.Option) (*s3.GetObjectTaggingOutput, error) + GetObjectTaggingRequest(*s3.GetObjectTaggingInput) (*request.Request, *s3.GetObjectTaggingOutput) + + GetObjectTorrent(*s3.GetObjectTorrentInput) (*s3.GetObjectTorrentOutput, error) + GetObjectTorrentWithContext(aws.Context, *s3.GetObjectTorrentInput, ...request.Option) (*s3.GetObjectTorrentOutput, error) + GetObjectTorrentRequest(*s3.GetObjectTorrentInput) (*request.Request, *s3.GetObjectTorrentOutput) + + GetPublicAccessBlock(*s3.GetPublicAccessBlockInput) (*s3.GetPublicAccessBlockOutput, error) + GetPublicAccessBlockWithContext(aws.Context, *s3.GetPublicAccessBlockInput, ...request.Option) (*s3.GetPublicAccessBlockOutput, error) + GetPublicAccessBlockRequest(*s3.GetPublicAccessBlockInput) (*request.Request, *s3.GetPublicAccessBlockOutput) + + HeadBucket(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error) + HeadBucketWithContext(aws.Context, *s3.HeadBucketInput, ...request.Option) (*s3.HeadBucketOutput, error) + HeadBucketRequest(*s3.HeadBucketInput) (*request.Request, *s3.HeadBucketOutput) + + HeadObject(*s3.HeadObjectInput) (*s3.HeadObjectOutput, error) + HeadObjectWithContext(aws.Context, *s3.HeadObjectInput, ...request.Option) (*s3.HeadObjectOutput, error) + HeadObjectRequest(*s3.HeadObjectInput) (*request.Request, *s3.HeadObjectOutput) + + ListBucketAnalyticsConfigurations(*s3.ListBucketAnalyticsConfigurationsInput) (*s3.ListBucketAnalyticsConfigurationsOutput, error) + ListBucketAnalyticsConfigurationsWithContext(aws.Context, *s3.ListBucketAnalyticsConfigurationsInput, ...request.Option) (*s3.ListBucketAnalyticsConfigurationsOutput, error) + ListBucketAnalyticsConfigurationsRequest(*s3.ListBucketAnalyticsConfigurationsInput) (*request.Request, *s3.ListBucketAnalyticsConfigurationsOutput) + + ListBucketInventoryConfigurations(*s3.ListBucketInventoryConfigurationsInput) (*s3.ListBucketInventoryConfigurationsOutput, error) + ListBucketInventoryConfigurationsWithContext(aws.Context, *s3.ListBucketInventoryConfigurationsInput, ...request.Option) (*s3.ListBucketInventoryConfigurationsOutput, error) + ListBucketInventoryConfigurationsRequest(*s3.ListBucketInventoryConfigurationsInput) (*request.Request, *s3.ListBucketInventoryConfigurationsOutput) + + ListBucketMetricsConfigurations(*s3.ListBucketMetricsConfigurationsInput) (*s3.ListBucketMetricsConfigurationsOutput, error) + ListBucketMetricsConfigurationsWithContext(aws.Context, *s3.ListBucketMetricsConfigurationsInput, ...request.Option) (*s3.ListBucketMetricsConfigurationsOutput, error) + ListBucketMetricsConfigurationsRequest(*s3.ListBucketMetricsConfigurationsInput) (*request.Request, *s3.ListBucketMetricsConfigurationsOutput) + + ListBuckets(*s3.ListBucketsInput) (*s3.ListBucketsOutput, error) + ListBucketsWithContext(aws.Context, *s3.ListBucketsInput, ...request.Option) (*s3.ListBucketsOutput, error) + ListBucketsRequest(*s3.ListBucketsInput) (*request.Request, *s3.ListBucketsOutput) + + ListMultipartUploads(*s3.ListMultipartUploadsInput) (*s3.ListMultipartUploadsOutput, error) + ListMultipartUploadsWithContext(aws.Context, *s3.ListMultipartUploadsInput, ...request.Option) (*s3.ListMultipartUploadsOutput, error) + ListMultipartUploadsRequest(*s3.ListMultipartUploadsInput) (*request.Request, *s3.ListMultipartUploadsOutput) + + ListMultipartUploadsPages(*s3.ListMultipartUploadsInput, func(*s3.ListMultipartUploadsOutput, bool) bool) error + ListMultipartUploadsPagesWithContext(aws.Context, *s3.ListMultipartUploadsInput, func(*s3.ListMultipartUploadsOutput, bool) bool, ...request.Option) error + + ListObjectVersions(*s3.ListObjectVersionsInput) (*s3.ListObjectVersionsOutput, error) + ListObjectVersionsWithContext(aws.Context, *s3.ListObjectVersionsInput, ...request.Option) (*s3.ListObjectVersionsOutput, error) + ListObjectVersionsRequest(*s3.ListObjectVersionsInput) (*request.Request, *s3.ListObjectVersionsOutput) + + ListObjectVersionsPages(*s3.ListObjectVersionsInput, func(*s3.ListObjectVersionsOutput, bool) bool) error + ListObjectVersionsPagesWithContext(aws.Context, *s3.ListObjectVersionsInput, func(*s3.ListObjectVersionsOutput, bool) bool, ...request.Option) error + + ListObjects(*s3.ListObjectsInput) (*s3.ListObjectsOutput, error) + ListObjectsWithContext(aws.Context, *s3.ListObjectsInput, ...request.Option) (*s3.ListObjectsOutput, error) + ListObjectsRequest(*s3.ListObjectsInput) (*request.Request, *s3.ListObjectsOutput) + + ListObjectsPages(*s3.ListObjectsInput, func(*s3.ListObjectsOutput, bool) bool) error + ListObjectsPagesWithContext(aws.Context, *s3.ListObjectsInput, func(*s3.ListObjectsOutput, bool) bool, ...request.Option) error + + ListObjectsV2(*s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) + ListObjectsV2WithContext(aws.Context, *s3.ListObjectsV2Input, ...request.Option) (*s3.ListObjectsV2Output, error) + ListObjectsV2Request(*s3.ListObjectsV2Input) (*request.Request, *s3.ListObjectsV2Output) + + ListObjectsV2Pages(*s3.ListObjectsV2Input, func(*s3.ListObjectsV2Output, bool) bool) error + ListObjectsV2PagesWithContext(aws.Context, *s3.ListObjectsV2Input, func(*s3.ListObjectsV2Output, bool) bool, ...request.Option) error + + ListParts(*s3.ListPartsInput) (*s3.ListPartsOutput, error) + ListPartsWithContext(aws.Context, *s3.ListPartsInput, ...request.Option) (*s3.ListPartsOutput, error) + ListPartsRequest(*s3.ListPartsInput) (*request.Request, *s3.ListPartsOutput) + + ListPartsPages(*s3.ListPartsInput, func(*s3.ListPartsOutput, bool) bool) error + ListPartsPagesWithContext(aws.Context, *s3.ListPartsInput, func(*s3.ListPartsOutput, bool) bool, ...request.Option) error + + PutBucketAccelerateConfiguration(*s3.PutBucketAccelerateConfigurationInput) (*s3.PutBucketAccelerateConfigurationOutput, error) + PutBucketAccelerateConfigurationWithContext(aws.Context, *s3.PutBucketAccelerateConfigurationInput, ...request.Option) (*s3.PutBucketAccelerateConfigurationOutput, error) + PutBucketAccelerateConfigurationRequest(*s3.PutBucketAccelerateConfigurationInput) (*request.Request, *s3.PutBucketAccelerateConfigurationOutput) + + PutBucketAcl(*s3.PutBucketAclInput) (*s3.PutBucketAclOutput, error) + PutBucketAclWithContext(aws.Context, *s3.PutBucketAclInput, ...request.Option) (*s3.PutBucketAclOutput, error) + PutBucketAclRequest(*s3.PutBucketAclInput) (*request.Request, *s3.PutBucketAclOutput) + + PutBucketAnalyticsConfiguration(*s3.PutBucketAnalyticsConfigurationInput) (*s3.PutBucketAnalyticsConfigurationOutput, error) + PutBucketAnalyticsConfigurationWithContext(aws.Context, *s3.PutBucketAnalyticsConfigurationInput, ...request.Option) (*s3.PutBucketAnalyticsConfigurationOutput, error) + PutBucketAnalyticsConfigurationRequest(*s3.PutBucketAnalyticsConfigurationInput) (*request.Request, *s3.PutBucketAnalyticsConfigurationOutput) + + PutBucketCors(*s3.PutBucketCorsInput) (*s3.PutBucketCorsOutput, error) + PutBucketCorsWithContext(aws.Context, *s3.PutBucketCorsInput, ...request.Option) (*s3.PutBucketCorsOutput, error) + PutBucketCorsRequest(*s3.PutBucketCorsInput) (*request.Request, *s3.PutBucketCorsOutput) + + PutBucketEncryption(*s3.PutBucketEncryptionInput) (*s3.PutBucketEncryptionOutput, error) + PutBucketEncryptionWithContext(aws.Context, *s3.PutBucketEncryptionInput, ...request.Option) (*s3.PutBucketEncryptionOutput, error) + PutBucketEncryptionRequest(*s3.PutBucketEncryptionInput) (*request.Request, *s3.PutBucketEncryptionOutput) + + PutBucketInventoryConfiguration(*s3.PutBucketInventoryConfigurationInput) (*s3.PutBucketInventoryConfigurationOutput, error) + PutBucketInventoryConfigurationWithContext(aws.Context, *s3.PutBucketInventoryConfigurationInput, ...request.Option) (*s3.PutBucketInventoryConfigurationOutput, error) + PutBucketInventoryConfigurationRequest(*s3.PutBucketInventoryConfigurationInput) (*request.Request, *s3.PutBucketInventoryConfigurationOutput) + + PutBucketLifecycle(*s3.PutBucketLifecycleInput) (*s3.PutBucketLifecycleOutput, error) + PutBucketLifecycleWithContext(aws.Context, *s3.PutBucketLifecycleInput, ...request.Option) (*s3.PutBucketLifecycleOutput, error) + PutBucketLifecycleRequest(*s3.PutBucketLifecycleInput) (*request.Request, *s3.PutBucketLifecycleOutput) + + PutBucketLifecycleConfiguration(*s3.PutBucketLifecycleConfigurationInput) (*s3.PutBucketLifecycleConfigurationOutput, error) + PutBucketLifecycleConfigurationWithContext(aws.Context, *s3.PutBucketLifecycleConfigurationInput, ...request.Option) (*s3.PutBucketLifecycleConfigurationOutput, error) + PutBucketLifecycleConfigurationRequest(*s3.PutBucketLifecycleConfigurationInput) (*request.Request, *s3.PutBucketLifecycleConfigurationOutput) + + PutBucketLogging(*s3.PutBucketLoggingInput) (*s3.PutBucketLoggingOutput, error) + PutBucketLoggingWithContext(aws.Context, *s3.PutBucketLoggingInput, ...request.Option) (*s3.PutBucketLoggingOutput, error) + PutBucketLoggingRequest(*s3.PutBucketLoggingInput) (*request.Request, *s3.PutBucketLoggingOutput) + + PutBucketMetricsConfiguration(*s3.PutBucketMetricsConfigurationInput) (*s3.PutBucketMetricsConfigurationOutput, error) + PutBucketMetricsConfigurationWithContext(aws.Context, *s3.PutBucketMetricsConfigurationInput, ...request.Option) (*s3.PutBucketMetricsConfigurationOutput, error) + PutBucketMetricsConfigurationRequest(*s3.PutBucketMetricsConfigurationInput) (*request.Request, *s3.PutBucketMetricsConfigurationOutput) + + PutBucketNotification(*s3.PutBucketNotificationInput) (*s3.PutBucketNotificationOutput, error) + PutBucketNotificationWithContext(aws.Context, *s3.PutBucketNotificationInput, ...request.Option) (*s3.PutBucketNotificationOutput, error) + PutBucketNotificationRequest(*s3.PutBucketNotificationInput) (*request.Request, *s3.PutBucketNotificationOutput) + + PutBucketNotificationConfiguration(*s3.PutBucketNotificationConfigurationInput) (*s3.PutBucketNotificationConfigurationOutput, error) + PutBucketNotificationConfigurationWithContext(aws.Context, *s3.PutBucketNotificationConfigurationInput, ...request.Option) (*s3.PutBucketNotificationConfigurationOutput, error) + PutBucketNotificationConfigurationRequest(*s3.PutBucketNotificationConfigurationInput) (*request.Request, *s3.PutBucketNotificationConfigurationOutput) + + PutBucketPolicy(*s3.PutBucketPolicyInput) (*s3.PutBucketPolicyOutput, error) + PutBucketPolicyWithContext(aws.Context, *s3.PutBucketPolicyInput, ...request.Option) (*s3.PutBucketPolicyOutput, error) + PutBucketPolicyRequest(*s3.PutBucketPolicyInput) (*request.Request, *s3.PutBucketPolicyOutput) + + PutBucketReplication(*s3.PutBucketReplicationInput) (*s3.PutBucketReplicationOutput, error) + PutBucketReplicationWithContext(aws.Context, *s3.PutBucketReplicationInput, ...request.Option) (*s3.PutBucketReplicationOutput, error) + PutBucketReplicationRequest(*s3.PutBucketReplicationInput) (*request.Request, *s3.PutBucketReplicationOutput) + + PutBucketRequestPayment(*s3.PutBucketRequestPaymentInput) (*s3.PutBucketRequestPaymentOutput, error) + PutBucketRequestPaymentWithContext(aws.Context, *s3.PutBucketRequestPaymentInput, ...request.Option) (*s3.PutBucketRequestPaymentOutput, error) + PutBucketRequestPaymentRequest(*s3.PutBucketRequestPaymentInput) (*request.Request, *s3.PutBucketRequestPaymentOutput) + + PutBucketTagging(*s3.PutBucketTaggingInput) (*s3.PutBucketTaggingOutput, error) + PutBucketTaggingWithContext(aws.Context, *s3.PutBucketTaggingInput, ...request.Option) (*s3.PutBucketTaggingOutput, error) + PutBucketTaggingRequest(*s3.PutBucketTaggingInput) (*request.Request, *s3.PutBucketTaggingOutput) + + PutBucketVersioning(*s3.PutBucketVersioningInput) (*s3.PutBucketVersioningOutput, error) + PutBucketVersioningWithContext(aws.Context, *s3.PutBucketVersioningInput, ...request.Option) (*s3.PutBucketVersioningOutput, error) + PutBucketVersioningRequest(*s3.PutBucketVersioningInput) (*request.Request, *s3.PutBucketVersioningOutput) + + PutBucketWebsite(*s3.PutBucketWebsiteInput) (*s3.PutBucketWebsiteOutput, error) + PutBucketWebsiteWithContext(aws.Context, *s3.PutBucketWebsiteInput, ...request.Option) (*s3.PutBucketWebsiteOutput, error) + PutBucketWebsiteRequest(*s3.PutBucketWebsiteInput) (*request.Request, *s3.PutBucketWebsiteOutput) + + PutObject(*s3.PutObjectInput) (*s3.PutObjectOutput, error) + PutObjectWithContext(aws.Context, *s3.PutObjectInput, ...request.Option) (*s3.PutObjectOutput, error) + PutObjectRequest(*s3.PutObjectInput) (*request.Request, *s3.PutObjectOutput) + + PutObjectAcl(*s3.PutObjectAclInput) (*s3.PutObjectAclOutput, error) + PutObjectAclWithContext(aws.Context, *s3.PutObjectAclInput, ...request.Option) (*s3.PutObjectAclOutput, error) + PutObjectAclRequest(*s3.PutObjectAclInput) (*request.Request, *s3.PutObjectAclOutput) + + PutObjectLegalHold(*s3.PutObjectLegalHoldInput) (*s3.PutObjectLegalHoldOutput, error) + PutObjectLegalHoldWithContext(aws.Context, *s3.PutObjectLegalHoldInput, ...request.Option) (*s3.PutObjectLegalHoldOutput, error) + PutObjectLegalHoldRequest(*s3.PutObjectLegalHoldInput) (*request.Request, *s3.PutObjectLegalHoldOutput) + + PutObjectLockConfiguration(*s3.PutObjectLockConfigurationInput) (*s3.PutObjectLockConfigurationOutput, error) + PutObjectLockConfigurationWithContext(aws.Context, *s3.PutObjectLockConfigurationInput, ...request.Option) (*s3.PutObjectLockConfigurationOutput, error) + PutObjectLockConfigurationRequest(*s3.PutObjectLockConfigurationInput) (*request.Request, *s3.PutObjectLockConfigurationOutput) + + PutObjectRetention(*s3.PutObjectRetentionInput) (*s3.PutObjectRetentionOutput, error) + PutObjectRetentionWithContext(aws.Context, *s3.PutObjectRetentionInput, ...request.Option) (*s3.PutObjectRetentionOutput, error) + PutObjectRetentionRequest(*s3.PutObjectRetentionInput) (*request.Request, *s3.PutObjectRetentionOutput) + + PutObjectTagging(*s3.PutObjectTaggingInput) (*s3.PutObjectTaggingOutput, error) + PutObjectTaggingWithContext(aws.Context, *s3.PutObjectTaggingInput, ...request.Option) (*s3.PutObjectTaggingOutput, error) + PutObjectTaggingRequest(*s3.PutObjectTaggingInput) (*request.Request, *s3.PutObjectTaggingOutput) + + PutPublicAccessBlock(*s3.PutPublicAccessBlockInput) (*s3.PutPublicAccessBlockOutput, error) + PutPublicAccessBlockWithContext(aws.Context, *s3.PutPublicAccessBlockInput, ...request.Option) (*s3.PutPublicAccessBlockOutput, error) + PutPublicAccessBlockRequest(*s3.PutPublicAccessBlockInput) (*request.Request, *s3.PutPublicAccessBlockOutput) + + RestoreObject(*s3.RestoreObjectInput) (*s3.RestoreObjectOutput, error) + RestoreObjectWithContext(aws.Context, *s3.RestoreObjectInput, ...request.Option) (*s3.RestoreObjectOutput, error) + RestoreObjectRequest(*s3.RestoreObjectInput) (*request.Request, *s3.RestoreObjectOutput) + + SelectObjectContent(*s3.SelectObjectContentInput) (*s3.SelectObjectContentOutput, error) + SelectObjectContentWithContext(aws.Context, *s3.SelectObjectContentInput, ...request.Option) (*s3.SelectObjectContentOutput, error) + SelectObjectContentRequest(*s3.SelectObjectContentInput) (*request.Request, *s3.SelectObjectContentOutput) + + UploadPart(*s3.UploadPartInput) (*s3.UploadPartOutput, error) + UploadPartWithContext(aws.Context, *s3.UploadPartInput, ...request.Option) (*s3.UploadPartOutput, error) + UploadPartRequest(*s3.UploadPartInput) (*request.Request, *s3.UploadPartOutput) + + UploadPartCopy(*s3.UploadPartCopyInput) (*s3.UploadPartCopyOutput, error) + UploadPartCopyWithContext(aws.Context, *s3.UploadPartCopyInput, ...request.Option) (*s3.UploadPartCopyOutput, error) + UploadPartCopyRequest(*s3.UploadPartCopyInput) (*request.Request, *s3.UploadPartCopyOutput) + + WaitUntilBucketExists(*s3.HeadBucketInput) error + WaitUntilBucketExistsWithContext(aws.Context, *s3.HeadBucketInput, ...request.WaiterOption) error + + WaitUntilBucketNotExists(*s3.HeadBucketInput) error + WaitUntilBucketNotExistsWithContext(aws.Context, *s3.HeadBucketInput, ...request.WaiterOption) error + + WaitUntilObjectExists(*s3.HeadObjectInput) error + WaitUntilObjectExistsWithContext(aws.Context, *s3.HeadObjectInput, ...request.WaiterOption) error + + WaitUntilObjectNotExists(*s3.HeadObjectInput) error + WaitUntilObjectNotExistsWithContext(aws.Context, *s3.HeadObjectInput, ...request.WaiterOption) error +} + +var _ S3API = (*s3.S3)(nil) diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/batch.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/batch.go new file mode 100644 index 00000000000..22bd0b7ce59 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/batch.go @@ -0,0 +1,529 @@ +package s3manager + +import ( + "bytes" + "fmt" + "io" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/client" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" +) + +const ( + // DefaultBatchSize is the batch size we initialize when constructing a batch delete client. + // This value is used when calling DeleteObjects. This represents how many objects to delete + // per DeleteObjects call. + DefaultBatchSize = 100 +) + +// BatchError will contain the key and bucket of the object that failed to +// either upload or download. +type BatchError struct { + Errors Errors + code string + message string +} + +// Errors is a typed alias for a slice of errors to satisfy the error +// interface. +type Errors []Error + +func (errs Errors) Error() string { + buf := bytes.NewBuffer(nil) + for i, err := range errs { + buf.WriteString(err.Error()) + if i+1 < len(errs) { + buf.WriteString("\n") + } + } + return buf.String() +} + +// Error will contain the original error, bucket, and key of the operation that failed +// during batch operations. +type Error struct { + OrigErr error + Bucket *string + Key *string +} + +func newError(err error, bucket, key *string) Error { + return Error{ + err, + bucket, + key, + } +} + +func (err *Error) Error() string { + origErr := "" + if err.OrigErr != nil { + origErr = ":\n" + err.OrigErr.Error() + } + return fmt.Sprintf("failed to perform batch operation on %q to %q%s", + aws.StringValue(err.Key), + aws.StringValue(err.Bucket), + origErr, + ) +} + +// NewBatchError will return a BatchError that satisfies the awserr.Error interface. +func NewBatchError(code, message string, err []Error) awserr.Error { + return &BatchError{ + Errors: err, + code: code, + message: message, + } +} + +// Code will return the code associated with the batch error. +func (err *BatchError) Code() string { + return err.code +} + +// Message will return the message associated with the batch error. +func (err *BatchError) Message() string { + return err.message +} + +func (err *BatchError) Error() string { + return awserr.SprintError(err.Code(), err.Message(), "", err.Errors) +} + +// OrigErr will return the original error. Which, in this case, will always be nil +// for batched operations. +func (err *BatchError) OrigErr() error { + return err.Errors +} + +// BatchDeleteIterator is an interface that uses the scanner pattern to +// iterate through what needs to be deleted. +type BatchDeleteIterator interface { + Next() bool + Err() error + DeleteObject() BatchDeleteObject +} + +// DeleteListIterator is an alternative iterator for the BatchDelete client. This will +// iterate through a list of objects and delete the objects. +// +// Example: +// iter := &s3manager.DeleteListIterator{ +// Client: svc, +// Input: &s3.ListObjectsInput{ +// Bucket: aws.String("bucket"), +// MaxKeys: aws.Int64(5), +// }, +// Paginator: request.Pagination{ +// NewRequest: func() (*request.Request, error) { +// var inCpy *ListObjectsInput +// if input != nil { +// tmp := *input +// inCpy = &tmp +// } +// req, _ := c.ListObjectsRequest(inCpy) +// return req, nil +// }, +// }, +// } +// +// batcher := s3manager.NewBatchDeleteWithClient(svc) +// if err := batcher.Delete(aws.BackgroundContext(), iter); err != nil { +// return err +// } +type DeleteListIterator struct { + Bucket *string + Paginator request.Pagination + objects []*s3.Object +} + +// NewDeleteListIterator will return a new DeleteListIterator. +func NewDeleteListIterator(svc s3iface.S3API, input *s3.ListObjectsInput, opts ...func(*DeleteListIterator)) BatchDeleteIterator { + iter := &DeleteListIterator{ + Bucket: input.Bucket, + Paginator: request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *s3.ListObjectsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := svc.ListObjectsRequest(inCpy) + return req, nil + }, + }, + } + + for _, opt := range opts { + opt(iter) + } + return iter +} + +// Next will use the S3API client to iterate through a list of objects. +func (iter *DeleteListIterator) Next() bool { + if len(iter.objects) > 0 { + iter.objects = iter.objects[1:] + } + + if len(iter.objects) == 0 && iter.Paginator.Next() { + iter.objects = iter.Paginator.Page().(*s3.ListObjectsOutput).Contents + } + + return len(iter.objects) > 0 +} + +// Err will return the last known error from Next. +func (iter *DeleteListIterator) Err() error { + return iter.Paginator.Err() +} + +// DeleteObject will return the current object to be deleted. +func (iter *DeleteListIterator) DeleteObject() BatchDeleteObject { + return BatchDeleteObject{ + Object: &s3.DeleteObjectInput{ + Bucket: iter.Bucket, + Key: iter.objects[0].Key, + }, + } +} + +// BatchDelete will use the s3 package's service client to perform a batch +// delete. +type BatchDelete struct { + Client s3iface.S3API + BatchSize int +} + +// NewBatchDeleteWithClient will return a new delete client that can delete a batched amount of +// objects. +// +// Example: +// batcher := s3manager.NewBatchDeleteWithClient(client, size) +// +// objects := []BatchDeleteObject{ +// { +// Object: &s3.DeleteObjectInput { +// Key: aws.String("key"), +// Bucket: aws.String("bucket"), +// }, +// }, +// } +// +// if err := batcher.Delete(aws.BackgroundContext(), &s3manager.DeleteObjectsIterator{ +// Objects: objects, +// }); err != nil { +// return err +// } +func NewBatchDeleteWithClient(client s3iface.S3API, options ...func(*BatchDelete)) *BatchDelete { + svc := &BatchDelete{ + Client: client, + BatchSize: DefaultBatchSize, + } + + for _, opt := range options { + opt(svc) + } + + return svc +} + +// NewBatchDelete will return a new delete client that can delete a batched amount of +// objects. +// +// Example: +// batcher := s3manager.NewBatchDelete(sess, size) +// +// objects := []BatchDeleteObject{ +// { +// Object: &s3.DeleteObjectInput { +// Key: aws.String("key"), +// Bucket: aws.String("bucket"), +// }, +// }, +// } +// +// if err := batcher.Delete(aws.BackgroundContext(), &s3manager.DeleteObjectsIterator{ +// Objects: objects, +// }); err != nil { +// return err +// } +func NewBatchDelete(c client.ConfigProvider, options ...func(*BatchDelete)) *BatchDelete { + client := s3.New(c) + return NewBatchDeleteWithClient(client, options...) +} + +// BatchDeleteObject is a wrapper object for calling the batch delete operation. +type BatchDeleteObject struct { + Object *s3.DeleteObjectInput + // After will run after each iteration during the batch process. This function will + // be executed whether or not the request was successful. + After func() error +} + +// DeleteObjectsIterator is an interface that uses the scanner pattern to iterate +// through a series of objects to be deleted. +type DeleteObjectsIterator struct { + Objects []BatchDeleteObject + index int + inc bool +} + +// Next will increment the default iterator's index and ensure that there +// is another object to iterator to. +func (iter *DeleteObjectsIterator) Next() bool { + if iter.inc { + iter.index++ + } else { + iter.inc = true + } + return iter.index < len(iter.Objects) +} + +// Err will return an error. Since this is just used to satisfy the BatchDeleteIterator interface +// this will only return nil. +func (iter *DeleteObjectsIterator) Err() error { + return nil +} + +// DeleteObject will return the BatchDeleteObject at the current batched index. +func (iter *DeleteObjectsIterator) DeleteObject() BatchDeleteObject { + object := iter.Objects[iter.index] + return object +} + +// Delete will use the iterator to queue up objects that need to be deleted. +// Once the batch size is met, this will call the deleteBatch function. +func (d *BatchDelete) Delete(ctx aws.Context, iter BatchDeleteIterator) error { + var errs []Error + objects := []BatchDeleteObject{} + var input *s3.DeleteObjectsInput + + for iter.Next() { + o := iter.DeleteObject() + + if input == nil { + input = initDeleteObjectsInput(o.Object) + } + + parity := hasParity(input, o) + if parity { + input.Delete.Objects = append(input.Delete.Objects, &s3.ObjectIdentifier{ + Key: o.Object.Key, + VersionId: o.Object.VersionId, + }) + objects = append(objects, o) + } + + if len(input.Delete.Objects) == d.BatchSize || !parity { + if err := deleteBatch(ctx, d, input, objects); err != nil { + errs = append(errs, err...) + } + + objects = objects[:0] + input = nil + + if !parity { + objects = append(objects, o) + input = initDeleteObjectsInput(o.Object) + input.Delete.Objects = append(input.Delete.Objects, &s3.ObjectIdentifier{ + Key: o.Object.Key, + VersionId: o.Object.VersionId, + }) + } + } + } + + // iter.Next() could return false (above) plus populate iter.Err() + if iter.Err() != nil { + errs = append(errs, newError(iter.Err(), nil, nil)) + } + + if input != nil && len(input.Delete.Objects) > 0 { + if err := deleteBatch(ctx, d, input, objects); err != nil { + errs = append(errs, err...) + } + } + + if len(errs) > 0 { + return NewBatchError("BatchedDeleteIncomplete", "some objects have failed to be deleted.", errs) + } + return nil +} + +func initDeleteObjectsInput(o *s3.DeleteObjectInput) *s3.DeleteObjectsInput { + return &s3.DeleteObjectsInput{ + Bucket: o.Bucket, + MFA: o.MFA, + RequestPayer: o.RequestPayer, + Delete: &s3.Delete{}, + } +} + +const ( + // ErrDeleteBatchFailCode represents an error code which will be returned + // only when DeleteObjects.Errors has an error that does not contain a code. + ErrDeleteBatchFailCode = "DeleteBatchError" + errDefaultDeleteBatchMessage = "failed to delete" +) + +// deleteBatch will delete a batch of items in the objects parameters. +func deleteBatch(ctx aws.Context, d *BatchDelete, input *s3.DeleteObjectsInput, objects []BatchDeleteObject) []Error { + errs := []Error{} + + if result, err := d.Client.DeleteObjectsWithContext(ctx, input); err != nil { + for i := 0; i < len(input.Delete.Objects); i++ { + errs = append(errs, newError(err, input.Bucket, input.Delete.Objects[i].Key)) + } + } else if len(result.Errors) > 0 { + for i := 0; i < len(result.Errors); i++ { + code := ErrDeleteBatchFailCode + msg := errDefaultDeleteBatchMessage + if result.Errors[i].Message != nil { + msg = *result.Errors[i].Message + } + if result.Errors[i].Code != nil { + code = *result.Errors[i].Code + } + + errs = append(errs, newError(awserr.New(code, msg, err), input.Bucket, result.Errors[i].Key)) + } + } + for _, object := range objects { + if object.After == nil { + continue + } + if err := object.After(); err != nil { + errs = append(errs, newError(err, object.Object.Bucket, object.Object.Key)) + } + } + + return errs +} + +func hasParity(o1 *s3.DeleteObjectsInput, o2 BatchDeleteObject) bool { + if o1.Bucket != nil && o2.Object.Bucket != nil { + if *o1.Bucket != *o2.Object.Bucket { + return false + } + } else if o1.Bucket != o2.Object.Bucket { + return false + } + + if o1.MFA != nil && o2.Object.MFA != nil { + if *o1.MFA != *o2.Object.MFA { + return false + } + } else if o1.MFA != o2.Object.MFA { + return false + } + + if o1.RequestPayer != nil && o2.Object.RequestPayer != nil { + if *o1.RequestPayer != *o2.Object.RequestPayer { + return false + } + } else if o1.RequestPayer != o2.Object.RequestPayer { + return false + } + + return true +} + +// BatchDownloadIterator is an interface that uses the scanner pattern to iterate +// through a series of objects to be downloaded. +type BatchDownloadIterator interface { + Next() bool + Err() error + DownloadObject() BatchDownloadObject +} + +// BatchDownloadObject contains all necessary information to run a batch operation once. +type BatchDownloadObject struct { + Object *s3.GetObjectInput + Writer io.WriterAt + // After will run after each iteration during the batch process. This function will + // be executed whether or not the request was successful. + After func() error +} + +// DownloadObjectsIterator implements the BatchDownloadIterator interface and allows for batched +// download of objects. +type DownloadObjectsIterator struct { + Objects []BatchDownloadObject + index int + inc bool +} + +// Next will increment the default iterator's index and ensure that there +// is another object to iterator to. +func (batcher *DownloadObjectsIterator) Next() bool { + if batcher.inc { + batcher.index++ + } else { + batcher.inc = true + } + return batcher.index < len(batcher.Objects) +} + +// DownloadObject will return the BatchDownloadObject at the current batched index. +func (batcher *DownloadObjectsIterator) DownloadObject() BatchDownloadObject { + object := batcher.Objects[batcher.index] + return object +} + +// Err will return an error. Since this is just used to satisfy the BatchDeleteIterator interface +// this will only return nil. +func (batcher *DownloadObjectsIterator) Err() error { + return nil +} + +// BatchUploadIterator is an interface that uses the scanner pattern to +// iterate through what needs to be uploaded. +type BatchUploadIterator interface { + Next() bool + Err() error + UploadObject() BatchUploadObject +} + +// UploadObjectsIterator implements the BatchUploadIterator interface and allows for batched +// upload of objects. +type UploadObjectsIterator struct { + Objects []BatchUploadObject + index int + inc bool +} + +// Next will increment the default iterator's index and ensure that there +// is another object to iterator to. +func (batcher *UploadObjectsIterator) Next() bool { + if batcher.inc { + batcher.index++ + } else { + batcher.inc = true + } + return batcher.index < len(batcher.Objects) +} + +// Err will return an error. Since this is just used to satisfy the BatchUploadIterator interface +// this will only return nil. +func (batcher *UploadObjectsIterator) Err() error { + return nil +} + +// UploadObject will return the BatchUploadObject at the current batched index. +func (batcher *UploadObjectsIterator) UploadObject() BatchUploadObject { + object := batcher.Objects[batcher.index] + return object +} + +// BatchUploadObject contains all necessary information to run a batch operation once. +type BatchUploadObject struct { + Object *UploadInput + // After will run after each iteration during the batch process. This function will + // be executed whether or not the request was successful. + After func() error +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/bucket_region.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/bucket_region.go new file mode 100644 index 00000000000..9cc1e5970c1 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/bucket_region.go @@ -0,0 +1,159 @@ +package s3manager + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/client" + "github.com/aws/aws-sdk-go/aws/corehandlers" + "github.com/aws/aws-sdk-go/aws/credentials" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" +) + +// GetBucketRegion will attempt to get the region for a bucket using the +// regionHint to determine which AWS partition to perform the query on. +// +// The request will not be signed, and will not use your AWS credentials. +// +// A "NotFound" error code will be returned if the bucket does not exist in the +// AWS partition the regionHint belongs to. If the regionHint parameter is an +// empty string GetBucketRegion will fallback to the ConfigProvider's region +// config. If the regionHint is empty, and the ConfigProvider does not have a +// region value, an error will be returned.. +// +// For example to get the region of a bucket which exists in "eu-central-1" +// you could provide a region hint of "us-west-2". +// +// 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) +// +// By default the request will be made to the Amazon S3 endpoint using the Path +// style addressing. +// +// s3.us-west-2.amazonaws.com/bucketname +// +// This is not compatible with Amazon S3's FIPS endpoints. To override this +// behavior to use Virtual Host style addressing, provide a functional option +// that will set the Request's Config.S3ForcePathStyle to aws.Bool(false). +// +// region, err := s3manager.GetBucketRegion(ctx, sess, "bucketname", "us-west-2", func(r *request.Request) { +// r.S3ForcePathStyle = aws.Bool(false) +// }) +// +// To configure the GetBucketRegion to make a request via the Amazon +// S3 FIPS endpoints directly when a FIPS region name is not available, (e.g. +// fips-us-gov-west-1) set the Config.Endpoint on the Session, or client the +// utility is called with. The hint region will be ignored if an endpoint URL +// is configured on the session or client. +// +// sess, err := session.NewSession(&aws.Config{ +// Endpoint: aws.String("https://s3-fips.us-west-2.amazonaws.com"), +// }) +// +// region, err := s3manager.GetBucketRegion(context.Background(), sess, "bucketname", "") +func GetBucketRegion(ctx aws.Context, c client.ConfigProvider, bucket, regionHint string, opts ...request.Option) (string, error) { + var cfg aws.Config + if len(regionHint) != 0 { + cfg.Region = aws.String(regionHint) + } + svc := s3.New(c, &cfg) + return GetBucketRegionWithClient(ctx, svc, bucket, opts...) +} + +const bucketRegionHeader = "X-Amz-Bucket-Region" + +// GetBucketRegionWithClient is the same as GetBucketRegion with the exception +// that it takes a S3 service client instead of a Session. The regionHint is +// derived from the region the S3 service client was created in. +// +// By default the request will be made to the Amazon S3 endpoint using the Path +// style addressing. +// +// s3.us-west-2.amazonaws.com/bucketname +// +// This is not compatible with Amazon S3's FIPS endpoints. To override this +// behavior to use Virtual Host style addressing, provide a functional option +// that will set the Request's Config.S3ForcePathStyle to aws.Bool(false). +// +// region, err := s3manager.GetBucketRegionWithClient(ctx, client, "bucketname", func(r *request.Request) { +// r.S3ForcePathStyle = aws.Bool(false) +// }) +// +// To configure the GetBucketRegion to make a request via the Amazon +// S3 FIPS endpoints directly when a FIPS region name is not available, (e.g. +// fips-us-gov-west-1) set the Config.Endpoint on the Session, or client the +// utility is called with. The hint region will be ignored if an endpoint URL +// is configured on the session or client. +// +// region, err := s3manager.GetBucketRegionWithClient(context.Background(), +// s3.New(sess, &aws.Config{ +// Endpoint: aws.String("https://s3-fips.us-west-2.amazonaws.com"), +// }), +// "bucketname") +// +// See GetBucketRegion for more information. +func GetBucketRegionWithClient(ctx aws.Context, svc s3iface.S3API, bucket string, opts ...request.Option) (string, error) { + req, _ := svc.HeadBucketRequest(&s3.HeadBucketInput{ + Bucket: aws.String(bucket), + }) + req.Config.S3ForcePathStyle = aws.Bool(true) + + req.Config.Credentials = credentials.AnonymousCredentials + req.SetContext(ctx) + + // Disable HTTP redirects to prevent an invalid 301 from eating the response + // because Go's HTTP client will fail, and drop the response if an 301 is + // received without a location header. S3 will return a 301 without the + // location header for HeadObject API calls. + req.DisableFollowRedirects = true + + var bucketRegion string + req.Handlers.Send.PushBack(func(r *request.Request) { + bucketRegion = r.HTTPResponse.Header.Get(bucketRegionHeader) + if len(bucketRegion) == 0 { + return + } + r.HTTPResponse.StatusCode = 200 + r.HTTPResponse.Status = "OK" + r.Error = nil + }) + // Replace the endpoint validation handler to not require a region if an + // endpoint URL was specified. Since these requests are not authenticated, + // requiring a region is not needed when an endpoint URL is provided. + req.Handlers.Validate.Swap( + corehandlers.ValidateEndpointHandler.Name, + request.NamedHandler{ + Name: "validateEndpointWithoutRegion", + Fn: validateEndpointWithoutRegion, + }, + ) + + req.ApplyOptions(opts...) + + if err := req.Send(); err != nil { + return "", err + } + + bucketRegion = s3.NormalizeBucketLocation(bucketRegion) + + return bucketRegion, nil +} + +func validateEndpointWithoutRegion(r *request.Request) { + // Check if the caller provided an explicit URL instead of one derived by + // the SDK's endpoint resolver. For GetBucketRegion, with an explicit + // endpoint URL, a region is not needed. If no endpoint URL is provided, + // fallback the SDK's standard endpoint validation handler. + if len(aws.StringValue(r.Config.Endpoint)) == 0 { + corehandlers.ValidateEndpointHandler.Fn(r) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/buffered_read_seeker.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/buffered_read_seeker.go new file mode 100644 index 00000000000..f1d9e85c7b3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/buffered_read_seeker.go @@ -0,0 +1,81 @@ +package s3manager + +import ( + "io" + + "github.com/aws/aws-sdk-go/internal/sdkio" +) + +// BufferedReadSeeker is buffered io.ReadSeeker +type BufferedReadSeeker struct { + r io.ReadSeeker + buffer []byte + readIdx, writeIdx int +} + +// NewBufferedReadSeeker returns a new BufferedReadSeeker +// if len(b) == 0 then the buffer will be initialized to 64 KiB. +func NewBufferedReadSeeker(r io.ReadSeeker, b []byte) *BufferedReadSeeker { + if len(b) == 0 { + b = make([]byte, 64*1024) + } + return &BufferedReadSeeker{r: r, buffer: b} +} + +func (b *BufferedReadSeeker) reset(r io.ReadSeeker) { + b.r = r + b.readIdx, b.writeIdx = 0, 0 +} + +// Read will read up len(p) bytes into p and will return +// the number of bytes read and any error that occurred. +// If the len(p) > the buffer size then a single read request +// will be issued to the underlying io.ReadSeeker for len(p) bytes. +// A Read request will at most perform a single Read to the underlying +// io.ReadSeeker, and may return < len(p) if serviced from the buffer. +func (b *BufferedReadSeeker) Read(p []byte) (n int, err error) { + if len(p) == 0 { + return n, err + } + + if b.readIdx == b.writeIdx { + if len(p) >= len(b.buffer) { + n, err = b.r.Read(p) + return n, err + } + b.readIdx, b.writeIdx = 0, 0 + + n, err = b.r.Read(b.buffer) + if n == 0 { + return n, err + } + + b.writeIdx += n + } + + n = copy(p, b.buffer[b.readIdx:b.writeIdx]) + b.readIdx += n + + return n, err +} + +// Seek will position then underlying io.ReadSeeker to the given offset +// and will clear the buffer. +func (b *BufferedReadSeeker) Seek(offset int64, whence int) (int64, error) { + n, err := b.r.Seek(offset, whence) + + b.reset(b.r) + + return n, err +} + +// ReadAt will read up to len(p) bytes at the given file offset. +// This will result in the buffer being cleared. +func (b *BufferedReadSeeker) ReadAt(p []byte, off int64) (int, error) { + _, err := b.Seek(off, sdkio.SeekStart) + if err != nil { + return 0, err + } + + return b.Read(p) +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_read_seeker_write_to.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_read_seeker_write_to.go new file mode 100644 index 00000000000..42276530a8b --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_read_seeker_write_to.go @@ -0,0 +1,7 @@ +// +build !windows + +package s3manager + +func defaultUploadBufferProvider() ReadSeekerWriteToProvider { + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_read_seeker_write_to_windows.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_read_seeker_write_to_windows.go new file mode 100644 index 00000000000..687082c3066 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_read_seeker_write_to_windows.go @@ -0,0 +1,5 @@ +package s3manager + +func defaultUploadBufferProvider() ReadSeekerWriteToProvider { + return NewBufferedReadSeekerWriteToPool(1024 * 1024) +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_writer_read_from.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_writer_read_from.go new file mode 100644 index 00000000000..ada50c24355 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_writer_read_from.go @@ -0,0 +1,7 @@ +// +build !windows + +package s3manager + +func defaultDownloadBufferProvider() WriterReadFromProvider { + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_writer_read_from_windows.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_writer_read_from_windows.go new file mode 100644 index 00000000000..7e9d9579f64 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/default_writer_read_from_windows.go @@ -0,0 +1,5 @@ +package s3manager + +func defaultDownloadBufferProvider() WriterReadFromProvider { + return NewPooledBufferedWriterReadFromProvider(1024 * 1024) +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/doc.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/doc.go new file mode 100644 index 00000000000..229c0d63bda --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/doc.go @@ -0,0 +1,3 @@ +// Package s3manager provides utilities to upload and download objects from +// S3 concurrently. Helpful for when working with large objects. +package s3manager diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/download.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/download.go new file mode 100644 index 00000000000..4b54b7c033d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/download.go @@ -0,0 +1,597 @@ +package s3manager + +import ( + "fmt" + "io" + "net/http" + "strconv" + "strings" + "sync" + + "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/client" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" +) + +// DefaultDownloadPartSize is the default range of bytes to get at a time when +// using Download(). +const DefaultDownloadPartSize = 1024 * 1024 * 5 + +// DefaultDownloadConcurrency is the default number of goroutines to spin up +// when using Download(). +const DefaultDownloadConcurrency = 5 + +type errReadingBody struct { + err error +} + +func (e *errReadingBody) Error() string { + return fmt.Sprintf("failed to read part body: %v", e.err) +} + +func (e *errReadingBody) Unwrap() error { + return e.err +} + +// The Downloader structure that calls Download(). It is safe to call Download() +// on this structure for multiple objects and across concurrent goroutines. +// Mutating the Downloader's properties is not safe to be done concurrently. +type Downloader struct { + // The size (in bytes) to request from S3 for each part. + // The minimum allowed part size is 5MB, and if this value is set to zero, + // the DefaultDownloadPartSize value will be used. + // + // PartSize is ignored if the Range input parameter is provided. + PartSize int64 + + // The number of goroutines to spin up in parallel when sending parts. + // If this is set to zero, the DefaultDownloadConcurrency value will be used. + // + // Concurrency of 1 will download the parts sequentially. + // + // Concurrency is ignored if the Range input parameter is provided. + Concurrency int + + // An S3 client to use when performing downloads. + S3 s3iface.S3API + + // List of request options that will be passed down to individual API + // operation requests made by the downloader. + RequestOptions []request.Option + + // Defines the buffer strategy used when downloading a part. + // + // If a WriterReadFromProvider is given the Download manager + // will pass the io.WriterAt of the Download request to the provider + // and will use the returned WriterReadFrom from the provider as the + // destination writer when copying from http response body. + BufferProvider WriterReadFromProvider +} + +// WithDownloaderRequestOptions appends to the Downloader's API request options. +func WithDownloaderRequestOptions(opts ...request.Option) func(*Downloader) { + return func(d *Downloader) { + d.RequestOptions = append(d.RequestOptions, opts...) + } +} + +// NewDownloader creates a new Downloader instance to downloads objects from +// S3 in concurrent chunks. Pass in additional functional options to customize +// the downloader behavior. Requires a client.ConfigProvider in order to create +// a S3 service client. The session.Session satisfies the client.ConfigProvider +// interface. +// +// Example: +// // 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 downloader with the session and custom options +// downloader := s3manager.NewDownloader(sess, func(d *s3manager.Downloader) { +// d.PartSize = 64 * 1024 * 1024 // 64MB per part +// }) +func NewDownloader(c client.ConfigProvider, options ...func(*Downloader)) *Downloader { + return newDownloader(s3.New(c), options...) +} + +func newDownloader(client s3iface.S3API, options ...func(*Downloader)) *Downloader { + d := &Downloader{ + S3: client, + PartSize: DefaultDownloadPartSize, + Concurrency: DefaultDownloadConcurrency, + BufferProvider: defaultDownloadBufferProvider(), + } + for _, option := range options { + option(d) + } + + return d +} + +// NewDownloaderWithClient creates a new Downloader instance to downloads +// objects from S3 in concurrent chunks. Pass in additional functional +// options to customize the downloader behavior. Requires a S3 service client +// to make S3 API calls. +// +// Example: +// // The session the S3 Downloader will use +// sess := session.Must(session.NewSession()) +// +// // The S3 client the S3 Downloader will use +// s3Svc := s3.New(sess) +// +// // Create a downloader with the s3 client and default options +// downloader := s3manager.NewDownloaderWithClient(s3Svc) +// +// // Create a downloader with the s3 client and custom options +// downloader := s3manager.NewDownloaderWithClient(s3Svc, func(d *s3manager.Downloader) { +// d.PartSize = 64 * 1024 * 1024 // 64MB per part +// }) +func NewDownloaderWithClient(svc s3iface.S3API, options ...func(*Downloader)) *Downloader { + return newDownloader(svc, options...) +} + +type maxRetrier interface { + MaxRetries() int +} + +// Download downloads an object in S3 and writes the payload into w using +// concurrent GET requests. The n int64 returned is the size of the object downloaded +// in bytes. +// +// Additional functional options can be provided to configure the individual +// download. These options are copies of the Downloader instance Download is called from. +// Modifying the options will not impact the original Downloader instance. +// +// It is safe to call this method concurrently across goroutines. +// +// The w io.WriterAt can be satisfied by an os.File to do multipart concurrent +// downloads, or in memory []byte wrapper using aws.WriteAtBuffer. +// +// Specifying a Downloader.Concurrency of 1 will cause the Downloader to +// download the parts from S3 sequentially. +// +// If the GetObjectInput's Range value is provided that will cause the downloader +// to perform a single GetObjectInput request for that object's range. This will +// caused the part size, and concurrency configurations to be ignored. +func (d Downloader) Download(w io.WriterAt, input *s3.GetObjectInput, options ...func(*Downloader)) (n int64, err error) { + return d.DownloadWithContext(aws.BackgroundContext(), w, input, options...) +} + +// DownloadWithContext downloads an object in S3 and writes the payload into w +// using concurrent GET requests. The n int64 returned is the size of the object downloaded +// in bytes. +// +// DownloadWithContext is the same as Download with the additional support for +// Context input parameters. The Context must not be nil. A nil Context will +// cause a panic. Use the Context to add deadlining, timeouts, etc. The +// DownloadWithContext may create sub-contexts for individual underlying +// requests. +// +// Additional functional options can be provided to configure the individual +// download. These options are copies of the Downloader instance Download is +// called from. Modifying the options will not impact the original Downloader +// instance. Use the WithDownloaderRequestOptions helper function to pass in request +// options that will be applied to all API operations made with this downloader. +// +// The w io.WriterAt can be satisfied by an os.File to do multipart concurrent +// downloads, or in memory []byte wrapper using aws.WriteAtBuffer. +// +// Specifying a Downloader.Concurrency of 1 will cause the Downloader to +// download the parts from S3 sequentially. +// +// It is safe to call this method concurrently across goroutines. +// +// If the GetObjectInput's Range value is provided that will cause the downloader +// to perform a single GetObjectInput request for that object's range. This will +// caused the part size, and concurrency configurations to be ignored. +func (d Downloader) DownloadWithContext(ctx aws.Context, w io.WriterAt, input *s3.GetObjectInput, options ...func(*Downloader)) (n int64, err error) { + impl := downloader{w: w, in: input, cfg: d, ctx: ctx} + + for _, option := range options { + option(&impl.cfg) + } + impl.cfg.RequestOptions = append(impl.cfg.RequestOptions, request.WithAppendUserAgent("S3Manager")) + + if s, ok := d.S3.(maxRetrier); ok { + impl.partBodyMaxRetries = s.MaxRetries() + } + + impl.totalBytes = -1 + if impl.cfg.Concurrency == 0 { + impl.cfg.Concurrency = DefaultDownloadConcurrency + } + + if impl.cfg.PartSize == 0 { + impl.cfg.PartSize = DefaultDownloadPartSize + } + + return impl.download() +} + +// DownloadWithIterator will download a batched amount of objects in S3 and writes them +// to the io.WriterAt specificed in the iterator. +// +// Example: +// svc := s3manager.NewDownloader(session) +// +// fooFile, err := os.Open("/tmp/foo.file") +// if err != nil { +// return err +// } +// +// barFile, err := os.Open("/tmp/bar.file") +// if err != nil { +// return err +// } +// +// objects := []s3manager.BatchDownloadObject { +// { +// Object: &s3.GetObjectInput { +// Bucket: aws.String("bucket"), +// Key: aws.String("foo"), +// }, +// Writer: fooFile, +// }, +// { +// Object: &s3.GetObjectInput { +// Bucket: aws.String("bucket"), +// Key: aws.String("bar"), +// }, +// Writer: barFile, +// }, +// } +// +// iter := &s3manager.DownloadObjectsIterator{Objects: objects} +// if err := svc.DownloadWithIterator(aws.BackgroundContext(), iter); err != nil { +// return err +// } +func (d Downloader) DownloadWithIterator(ctx aws.Context, iter BatchDownloadIterator, opts ...func(*Downloader)) error { + var errs []Error + for iter.Next() { + object := iter.DownloadObject() + if _, err := d.DownloadWithContext(ctx, object.Writer, object.Object, opts...); err != nil { + errs = append(errs, newError(err, object.Object.Bucket, object.Object.Key)) + } + + if object.After == nil { + continue + } + + if err := object.After(); err != nil { + errs = append(errs, newError(err, object.Object.Bucket, object.Object.Key)) + } + } + + if len(errs) > 0 { + return NewBatchError("BatchedDownloadIncomplete", "some objects have failed to download.", errs) + } + return nil +} + +// downloader is the implementation structure used internally by Downloader. +type downloader struct { + ctx aws.Context + cfg Downloader + + in *s3.GetObjectInput + w io.WriterAt + + wg sync.WaitGroup + m sync.Mutex + + pos int64 + totalBytes int64 + written int64 + err error + + partBodyMaxRetries int +} + +// download performs the implementation of the object download across ranged +// GETs. +func (d *downloader) download() (n int64, err error) { + // If range is specified fall back to single download of that range + // this enables the functionality of ranged gets with the downloader but + // at the cost of no multipart downloads. + if rng := aws.StringValue(d.in.Range); len(rng) > 0 { + d.downloadRange(rng) + return d.written, d.err + } + + // Spin off first worker to check additional header information + d.getChunk() + + if total := d.getTotalBytes(); total >= 0 { + // Spin up workers + ch := make(chan dlchunk, d.cfg.Concurrency) + + for i := 0; i < d.cfg.Concurrency; i++ { + d.wg.Add(1) + go d.downloadPart(ch) + } + + // Assign work + for d.getErr() == nil { + if d.pos >= total { + break // We're finished queuing chunks + } + + // Queue the next range of bytes to read. + ch <- dlchunk{w: d.w, start: d.pos, size: d.cfg.PartSize} + d.pos += d.cfg.PartSize + } + + // Wait for completion + close(ch) + d.wg.Wait() + } else { + // Checking if we read anything new + for d.err == nil { + d.getChunk() + } + + // We expect a 416 error letting us know we are done downloading the + // total bytes. Since we do not know the content's length, this will + // keep grabbing chunks of data until the range of bytes specified in + // the request is out of range of the content. Once, this happens, a + // 416 should occur. + e, ok := d.err.(awserr.RequestFailure) + if ok && e.StatusCode() == http.StatusRequestedRangeNotSatisfiable { + d.err = nil + } + } + + // Return error + return d.written, d.err +} + +// downloadPart is an individual goroutine worker reading from the ch channel +// and performing a GetObject request on the data with a given byte range. +// +// If this is the first worker, this operation also resolves the total number +// of bytes to be read so that the worker manager knows when it is finished. +func (d *downloader) downloadPart(ch chan dlchunk) { + defer d.wg.Done() + for { + chunk, ok := <-ch + if !ok { + break + } + if d.getErr() != nil { + // Drain the channel if there is an error, to prevent deadlocking + // of download producer. + continue + } + + if err := d.downloadChunk(chunk); err != nil { + d.setErr(err) + } + } +} + +// getChunk grabs a chunk of data from the body. +// Not thread safe. Should only used when grabbing data on a single thread. +func (d *downloader) getChunk() { + if d.getErr() != nil { + return + } + + chunk := dlchunk{w: d.w, start: d.pos, size: d.cfg.PartSize} + d.pos += d.cfg.PartSize + + if err := d.downloadChunk(chunk); err != nil { + d.setErr(err) + } +} + +// downloadRange downloads an Object given the passed in Byte-Range value. +// The chunk used down download the range will be configured for that range. +func (d *downloader) downloadRange(rng string) { + if d.getErr() != nil { + return + } + + chunk := dlchunk{w: d.w, start: d.pos} + // Ranges specified will short circuit the multipart download + chunk.withRange = rng + + if err := d.downloadChunk(chunk); err != nil { + d.setErr(err) + } + + // Update the position based on the amount of data received. + d.pos = d.written +} + +// downloadChunk downloads the chunk from s3 +func (d *downloader) downloadChunk(chunk dlchunk) error { + in := &s3.GetObjectInput{} + awsutil.Copy(in, d.in) + + // Get the next byte range of data + in.Range = aws.String(chunk.ByteRange()) + + var n int64 + var err error + for retry := 0; retry <= d.partBodyMaxRetries; retry++ { + n, err = d.tryDownloadChunk(in, &chunk) + if err == nil { + break + } + // Check if the returned error is an errReadingBody. + // If err is errReadingBody this indicates that an error + // occurred while copying the http response body. + // If this occurs we unwrap the err to set the underlying error + // and attempt any remaining retries. + if bodyErr, ok := err.(*errReadingBody); ok { + err = bodyErr.Unwrap() + } else { + return err + } + + chunk.cur = 0 + logMessage(d.cfg.S3, aws.LogDebugWithRequestRetries, + fmt.Sprintf("DEBUG: object part body download interrupted %s, err, %v, retrying attempt %d", + aws.StringValue(in.Key), err, retry)) + } + + d.incrWritten(n) + + return err +} + +func (d *downloader) tryDownloadChunk(in *s3.GetObjectInput, w io.Writer) (int64, error) { + cleanup := func() {} + if d.cfg.BufferProvider != nil { + w, cleanup = d.cfg.BufferProvider.GetReadFrom(w) + } + defer cleanup() + + resp, err := d.cfg.S3.GetObjectWithContext(d.ctx, in, d.cfg.RequestOptions...) + if err != nil { + return 0, err + } + d.setTotalBytes(resp) // Set total if not yet set. + + n, err := io.Copy(w, resp.Body) + resp.Body.Close() + if err != nil { + return n, &errReadingBody{err: err} + } + + return n, nil +} + +func logMessage(svc s3iface.S3API, level aws.LogLevelType, msg string) { + s, ok := svc.(*s3.S3) + if !ok { + return + } + + if s.Config.Logger == nil { + return + } + + if s.Config.LogLevel.Matches(level) { + s.Config.Logger.Log(msg) + } +} + +// getTotalBytes is a thread-safe getter for retrieving the total byte status. +func (d *downloader) getTotalBytes() int64 { + d.m.Lock() + defer d.m.Unlock() + + return d.totalBytes +} + +// setTotalBytes is a thread-safe setter for setting the total byte status. +// Will extract the object's total bytes from the Content-Range if the file +// will be chunked, or Content-Length. Content-Length is used when the response +// does not include a Content-Range. Meaning the object was not chunked. This +// occurs when the full file fits within the PartSize directive. +func (d *downloader) setTotalBytes(resp *s3.GetObjectOutput) { + d.m.Lock() + defer d.m.Unlock() + + if d.totalBytes >= 0 { + return + } + + if resp.ContentRange == nil { + // ContentRange is nil when the full file contents is provided, and + // is not chunked. Use ContentLength instead. + if resp.ContentLength != nil { + d.totalBytes = *resp.ContentLength + return + } + } else { + parts := strings.Split(*resp.ContentRange, "/") + + total := int64(-1) + var err error + // Checking for whether or not a numbered total exists + // If one does not exist, we will assume the total to be -1, undefined, + // and sequentially download each chunk until hitting a 416 error + totalStr := parts[len(parts)-1] + if totalStr != "*" { + total, err = strconv.ParseInt(totalStr, 10, 64) + if err != nil { + d.err = err + return + } + } + + d.totalBytes = total + } +} + +func (d *downloader) incrWritten(n int64) { + d.m.Lock() + defer d.m.Unlock() + + d.written += n +} + +// getErr is a thread-safe getter for the error object +func (d *downloader) getErr() error { + d.m.Lock() + defer d.m.Unlock() + + return d.err +} + +// setErr is a thread-safe setter for the error object +func (d *downloader) setErr(e error) { + d.m.Lock() + defer d.m.Unlock() + + d.err = e +} + +// dlchunk represents a single chunk of data to write by the worker routine. +// This structure also implements an io.SectionReader style interface for +// io.WriterAt, effectively making it an io.SectionWriter (which does not +// exist). +type dlchunk struct { + w io.WriterAt + start int64 + size int64 + cur int64 + + // specifies the byte range the chunk should be downloaded with. + withRange string +} + +// Write wraps io.WriterAt for the dlchunk, writing from the dlchunk's start +// position to its end (or EOF). +// +// If a range is specified on the dlchunk the size will be ignored when writing. +// as the total size may not of be known ahead of time. +func (c *dlchunk) Write(p []byte) (n int, err error) { + if c.cur >= c.size && len(c.withRange) == 0 { + return 0, io.EOF + } + + n, err = c.w.WriteAt(p, c.start+c.cur) + c.cur += int64(n) + + return +} + +// ByteRange returns a HTTP Byte-Range header value that should be used by the +// client to request the chunk's range. +func (c *dlchunk) ByteRange() string { + if len(c.withRange) != 0 { + return c.withRange + } + + return fmt.Sprintf("bytes=%d-%d", c.start, c.start+c.size-1) +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/pool.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/pool.go new file mode 100644 index 00000000000..05113286d3e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/pool.go @@ -0,0 +1,244 @@ +package s3manager + +import ( + "fmt" + "sync" + + "github.com/aws/aws-sdk-go/aws" +) + +type byteSlicePool interface { + Get(aws.Context) (*[]byte, error) + Put(*[]byte) + ModifyCapacity(int) + SliceSize() int64 + Close() +} + +type maxSlicePool struct { + // allocator is defined as a function pointer to allow + // for test cases to instrument custom tracers when allocations + // occur. + allocator sliceAllocator + + slices chan *[]byte + allocations chan struct{} + capacityChange chan struct{} + + max int + sliceSize int64 + + mtx sync.RWMutex +} + +func newMaxSlicePool(sliceSize int64) *maxSlicePool { + p := &maxSlicePool{sliceSize: sliceSize} + p.allocator = p.newSlice + + return p +} + +var errZeroCapacity = fmt.Errorf("get called on zero capacity pool") + +func (p *maxSlicePool) Get(ctx aws.Context) (*[]byte, error) { + // check if context is canceled before attempting to get a slice + // this ensures priority is given to the cancel case first + select { + case <-ctx.Done(): + return nil, ctx.Err() + default: + } + + p.mtx.RLock() + + for { + select { + case bs, ok := <-p.slices: + p.mtx.RUnlock() + if !ok { + // attempt to get on a zero capacity pool + return nil, errZeroCapacity + } + return bs, nil + case _, ok := <-p.allocations: + p.mtx.RUnlock() + if !ok { + // attempt to get on a zero capacity pool + return nil, errZeroCapacity + } + return p.allocator(), nil + case <-ctx.Done(): + p.mtx.RUnlock() + return nil, ctx.Err() + default: + // In the event that there are no slices or allocations available + // This prevents some deadlock situations that can occur around sync.RWMutex + // When a lock request occurs on ModifyCapacity, no new readers are allowed to acquire a read lock. + // By releasing the read lock here and waiting for a notification, we prevent a deadlock situation where + // Get could hold the read lock indefinitely waiting for capacity, ModifyCapacity is waiting for a write lock, + // and a Put is blocked trying to get a read-lock which is blocked by ModifyCapacity. + + // Short-circuit if the pool capacity is zero. + if p.max == 0 { + p.mtx.RUnlock() + return nil, errZeroCapacity + } + + // Since we will be releasing the read-lock we need to take the reference to the channel. + // Since channels are references we will still get notified if slices are added, or if + // the channel is closed due to a capacity modification. This specifically avoids a data race condition + // where ModifyCapacity both closes a channel and initializes a new one while we don't have a read-lock. + c := p.capacityChange + + p.mtx.RUnlock() + + select { + case _ = <-c: + p.mtx.RLock() + case <-ctx.Done(): + return nil, ctx.Err() + } + } + } +} + +func (p *maxSlicePool) Put(bs *[]byte) { + p.mtx.RLock() + defer p.mtx.RUnlock() + + if p.max == 0 { + return + } + + select { + case p.slices <- bs: + p.notifyCapacity() + default: + // If the new channel when attempting to add the slice then we drop the slice. + // The logic here is to prevent a deadlock situation if channel is already at max capacity. + // Allows us to reap allocations that are returned and are no longer needed. + } +} + +func (p *maxSlicePool) ModifyCapacity(delta int) { + if delta == 0 { + return + } + + p.mtx.Lock() + defer p.mtx.Unlock() + + p.max += delta + + if p.max == 0 { + p.empty() + return + } + + if p.capacityChange != nil { + close(p.capacityChange) + } + p.capacityChange = make(chan struct{}, p.max) + + origAllocations := p.allocations + p.allocations = make(chan struct{}, p.max) + + newAllocs := len(origAllocations) + delta + for i := 0; i < newAllocs; i++ { + p.allocations <- struct{}{} + } + + if origAllocations != nil { + close(origAllocations) + } + + origSlices := p.slices + p.slices = make(chan *[]byte, p.max) + if origSlices == nil { + return + } + + close(origSlices) + for bs := range origSlices { + select { + case p.slices <- bs: + default: + // If the new channel blocks while adding slices from the old channel + // then we drop the slice. The logic here is to prevent a deadlock situation + // if the new channel has a smaller capacity then the old. + } + } +} + +func (p *maxSlicePool) notifyCapacity() { + select { + case p.capacityChange <- struct{}{}: + default: + // This *shouldn't* happen as the channel is both buffered to the max pool capacity size and is resized + // on capacity modifications. This is just a safety to ensure that a blocking situation can't occur. + } +} + +func (p *maxSlicePool) SliceSize() int64 { + return p.sliceSize +} + +func (p *maxSlicePool) Close() { + p.mtx.Lock() + defer p.mtx.Unlock() + p.empty() +} + +func (p *maxSlicePool) empty() { + p.max = 0 + + if p.capacityChange != nil { + close(p.capacityChange) + p.capacityChange = nil + } + + if p.allocations != nil { + close(p.allocations) + for range p.allocations { + // drain channel + } + p.allocations = nil + } + + if p.slices != nil { + close(p.slices) + for range p.slices { + // drain channel + } + p.slices = nil + } +} + +func (p *maxSlicePool) newSlice() *[]byte { + bs := make([]byte, p.sliceSize) + return &bs +} + +type returnCapacityPoolCloser struct { + byteSlicePool + returnCapacity int +} + +func (n *returnCapacityPoolCloser) ModifyCapacity(delta int) { + if delta > 0 { + n.returnCapacity = -1 * delta + } + n.byteSlicePool.ModifyCapacity(delta) +} + +func (n *returnCapacityPoolCloser) Close() { + if n.returnCapacity < 0 { + n.byteSlicePool.ModifyCapacity(n.returnCapacity) + } +} + +type sliceAllocator func() *[]byte + +var newByteSlicePool = func(sliceSize int64) byteSlicePool { + return newMaxSlicePool(sliceSize) +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/read_seeker_write_to.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/read_seeker_write_to.go new file mode 100644 index 00000000000..f62e1a45eef --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/read_seeker_write_to.go @@ -0,0 +1,65 @@ +package s3manager + +import ( + "io" + "sync" +) + +// ReadSeekerWriteTo defines an interface implementing io.WriteTo and io.ReadSeeker +type ReadSeekerWriteTo interface { + io.ReadSeeker + io.WriterTo +} + +// BufferedReadSeekerWriteTo wraps a BufferedReadSeeker with an io.WriteAt +// implementation. +type BufferedReadSeekerWriteTo struct { + *BufferedReadSeeker +} + +// WriteTo writes to the given io.Writer from BufferedReadSeeker until there's no more data to write or +// an error occurs. Returns the number of bytes written and any error encountered during the write. +func (b *BufferedReadSeekerWriteTo) WriteTo(writer io.Writer) (int64, error) { + return io.Copy(writer, b.BufferedReadSeeker) +} + +// ReadSeekerWriteToProvider provides an implementation of io.WriteTo for an io.ReadSeeker +type ReadSeekerWriteToProvider interface { + GetWriteTo(seeker io.ReadSeeker) (r ReadSeekerWriteTo, cleanup func()) +} + +// BufferedReadSeekerWriteToPool uses a sync.Pool to create and reuse +// []byte slices for buffering parts in memory +type BufferedReadSeekerWriteToPool struct { + pool sync.Pool +} + +// NewBufferedReadSeekerWriteToPool will return a new BufferedReadSeekerWriteToPool that will create +// a pool of reusable buffers . If size is less then < 64 KiB then the buffer +// will default to 64 KiB. Reason: io.Copy from writers or readers that don't support io.WriteTo or io.ReadFrom +// respectively will default to copying 32 KiB. +func NewBufferedReadSeekerWriteToPool(size int) *BufferedReadSeekerWriteToPool { + if size < 65536 { + size = 65536 + } + + return &BufferedReadSeekerWriteToPool{ + pool: sync.Pool{New: func() interface{} { + return make([]byte, size) + }}, + } +} + +// GetWriteTo will wrap the provided io.ReadSeeker with a BufferedReadSeekerWriteTo. +// The provided cleanup must be called after operations have been completed on the +// returned io.ReadSeekerWriteTo in order to signal the return of resources to the pool. +func (p *BufferedReadSeekerWriteToPool) GetWriteTo(seeker io.ReadSeeker) (r ReadSeekerWriteTo, cleanup func()) { + buffer := p.pool.Get().([]byte) + + r = &BufferedReadSeekerWriteTo{BufferedReadSeeker: NewBufferedReadSeeker(seeker, buffer)} + cleanup = func() { + p.pool.Put(buffer) + } + + return r, cleanup +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go new file mode 100644 index 00000000000..8770d404119 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go @@ -0,0 +1,777 @@ +package s3manager + +import ( + "bytes" + "fmt" + "io" + "sort" + "sync" + + "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/client" + "github.com/aws/aws-sdk-go/aws/credentials" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" +) + +// MaxUploadParts is the maximum allowed number of parts in a multi-part upload +// on Amazon S3. +const MaxUploadParts = 10000 + +// MinUploadPartSize is the minimum allowed part size when uploading a part to +// Amazon S3. +const MinUploadPartSize int64 = 1024 * 1024 * 5 + +// DefaultUploadPartSize is the default part size to buffer chunks of a +// payload into. +const DefaultUploadPartSize = MinUploadPartSize + +// DefaultUploadConcurrency is the default number of goroutines to spin up when +// using Upload(). +const DefaultUploadConcurrency = 5 + +// A MultiUploadFailure wraps a failed S3 multipart upload. An error returned +// will satisfy this interface when a multi part upload failed to upload all +// chucks to S3. In the case of a failure the UploadID is needed to operate on +// the chunks, if any, which were uploaded. +// +// Example: +// +// u := s3manager.NewUploader(opts) +// output, err := u.upload(input) +// if err != nil { +// if multierr, ok := err.(s3manager.MultiUploadFailure); ok { +// // Process error and its associated uploadID +// fmt.Println("Error:", multierr.Code(), multierr.Message(), multierr.UploadID()) +// } else { +// // Process error generically +// fmt.Println("Error:", err.Error()) +// } +// } +// +type MultiUploadFailure interface { + awserr.Error + + // Returns the upload id for the S3 multipart upload that failed. + UploadID() string +} + +// So that the Error interface type can be included as an anonymous field +// in the multiUploadError struct and not conflict with the error.Error() method. +type awsError awserr.Error + +// A multiUploadError wraps the upload ID of a failed s3 multipart upload. +// Composed of BaseError for code, message, and original error +// +// Should be used for an error that occurred failing a S3 multipart upload, +// and a upload ID is available. If an uploadID is not available a more relevant +type multiUploadError struct { + awsError + + // ID for multipart upload which failed. + uploadID string +} + +// Error returns the string representation of the error. +// +// See apierr.BaseError ErrorWithExtra for output format +// +// Satisfies the error interface. +func (m multiUploadError) Error() string { + extra := fmt.Sprintf("upload id: %s", m.uploadID) + return awserr.SprintError(m.Code(), m.Message(), extra, m.OrigErr()) +} + +// String returns the string representation of the error. +// Alias for Error to satisfy the stringer interface. +func (m multiUploadError) String() string { + return m.Error() +} + +// UploadID returns the id of the S3 upload which failed. +func (m multiUploadError) UploadID() string { + return m.uploadID +} + +// UploadOutput represents a response from the Upload() call. +type UploadOutput struct { + // The URL where the object was uploaded to. + Location string + + // The version of the object that was uploaded. Will only be populated if + // the S3 Bucket is versioned. If the bucket is not versioned this field + // will not be set. + VersionID *string + + // The ID for a multipart upload to S3. In the case of an error the error + // can be cast to the MultiUploadFailure interface to extract the upload ID. + UploadID string +} + +// WithUploaderRequestOptions appends to the Uploader's API request options. +func WithUploaderRequestOptions(opts ...request.Option) func(*Uploader) { + return func(u *Uploader) { + u.RequestOptions = append(u.RequestOptions, opts...) + } +} + +// The Uploader structure that calls Upload(). It is safe to call Upload() +// on this structure for multiple objects and across concurrent goroutines. +// Mutating the Uploader's properties is not safe to be done concurrently. +type Uploader struct { + // The buffer size (in bytes) to use when buffering data into chunks and + // sending them as parts to S3. The minimum allowed part size is 5MB, and + // if this value is set to zero, the DefaultUploadPartSize value will be used. + PartSize int64 + + // The number of goroutines to spin up in parallel per call to Upload when + // sending parts. If this is set to zero, the DefaultUploadConcurrency value + // will be used. + // + // The concurrency pool is not shared between calls to Upload. + Concurrency int + + // Setting this value to true will cause the SDK to avoid calling + // AbortMultipartUpload on a failure, leaving all successfully uploaded + // parts on S3 for manual recovery. + // + // Note that storing parts of an incomplete multipart upload counts towards + // space usage on S3 and will add additional costs if not cleaned up. + LeavePartsOnError bool + + // MaxUploadParts is the max number of parts which will be uploaded to S3. + // Will be used to calculate the partsize of the object to be uploaded. + // E.g: 5GB file, with MaxUploadParts set to 100, will upload the file + // as 100, 50MB parts. With a limited of s3.MaxUploadParts (10,000 parts). + // + // MaxUploadParts must not be used to limit the total number of bytes uploaded. + // Use a type like to io.LimitReader (https://golang.org/pkg/io/#LimitedReader) + // instead. An io.LimitReader is helpful when uploading an unbounded reader + // to S3, and you know its maximum size. Otherwise the reader's io.EOF returned + // error must be used to signal end of stream. + // + // Defaults to package const's MaxUploadParts value. + MaxUploadParts int + + // The client to use when uploading to S3. + S3 s3iface.S3API + + // List of request options that will be passed down to individual API + // operation requests made by the uploader. + RequestOptions []request.Option + + // Defines the buffer strategy used when uploading a part + BufferProvider ReadSeekerWriteToProvider + + // partPool allows for the re-usage of streaming payload part buffers between upload calls + partPool byteSlicePool +} + +// NewUploader creates a new Uploader instance to upload objects to S3. Pass In +// additional functional options to customize the uploader's behavior. Requires a +// client.ConfigProvider in order to create a S3 service client. The session.Session +// satisfies the client.ConfigProvider interface. +// +// Example: +// // 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) +// +// // Create an uploader with the session and custom options +// uploader := s3manager.NewUploader(session, func(u *s3manager.Uploader) { +// u.PartSize = 64 * 1024 * 1024 // 64MB per part +// }) +func NewUploader(c client.ConfigProvider, options ...func(*Uploader)) *Uploader { + return newUploader(s3.New(c), options...) +} + +func newUploader(client s3iface.S3API, options ...func(*Uploader)) *Uploader { + u := &Uploader{ + S3: client, + PartSize: DefaultUploadPartSize, + Concurrency: DefaultUploadConcurrency, + LeavePartsOnError: false, + MaxUploadParts: MaxUploadParts, + BufferProvider: defaultUploadBufferProvider(), + } + + for _, option := range options { + option(u) + } + + u.partPool = newByteSlicePool(u.PartSize) + + return u +} + +// NewUploaderWithClient creates a new Uploader instance to upload objects to S3. Pass in +// additional functional options to customize the uploader's behavior. Requires +// a S3 service client to make S3 API calls. +// +// Example: +// // The session the S3 Uploader will use +// sess := session.Must(session.NewSession()) +// +// // S3 service client the Upload manager will use. +// s3Svc := s3.New(sess) +// +// // Create an uploader with S3 client and default options +// uploader := s3manager.NewUploaderWithClient(s3Svc) +// +// // Create an uploader with S3 client and custom options +// uploader := s3manager.NewUploaderWithClient(s3Svc, func(u *s3manager.Uploader) { +// u.PartSize = 64 * 1024 * 1024 // 64MB per part +// }) +func NewUploaderWithClient(svc s3iface.S3API, options ...func(*Uploader)) *Uploader { + return newUploader(svc, options...) +} + +// Upload uploads an object to S3, intelligently buffering large files into +// smaller chunks and sending them in parallel across multiple goroutines. You +// can configure the buffer size and concurrency through the Uploader's parameters. +// +// Additional functional options can be provided to configure the individual +// upload. These options are copies of the Uploader instance Upload is called from. +// Modifying the options will not impact the original Uploader instance. +// +// Use the WithUploaderRequestOptions helper function to pass in request +// options that will be applied to all API operations made with this uploader. +// +// It is safe to call this method concurrently across goroutines. +// +// Example: +// // Upload input parameters +// upParams := &s3manager.UploadInput{ +// Bucket: &bucketName, +// Key: &keyName, +// Body: file, +// } +// +// // Perform an upload. +// result, err := uploader.Upload(upParams) +// +// // Perform upload with options different than the those in the Uploader. +// result, err := uploader.Upload(upParams, func(u *s3manager.Uploader) { +// u.PartSize = 10 * 1024 * 1024 // 10MB part size +// u.LeavePartsOnError = true // Don't delete the parts if the upload fails. +// }) +func (u Uploader) Upload(input *UploadInput, options ...func(*Uploader)) (*UploadOutput, error) { + return u.UploadWithContext(aws.BackgroundContext(), input, options...) +} + +// UploadWithContext uploads an object to S3, intelligently buffering large +// files into smaller chunks and sending them in parallel across multiple +// goroutines. You can configure the buffer size and concurrency through the +// Uploader's parameters. +// +// UploadWithContext is the same as Upload with the additional support for +// Context input parameters. The Context must not be nil. A nil Context will +// cause a panic. Use the context to add deadlining, timeouts, etc. The +// UploadWithContext may create sub-contexts for individual underlying requests. +// +// Additional functional options can be provided to configure the individual +// upload. These options are copies of the Uploader instance Upload is called from. +// Modifying the options will not impact the original Uploader instance. +// +// Use the WithUploaderRequestOptions helper function to pass in request +// options that will be applied to all API operations made with this uploader. +// +// It is safe to call this method concurrently across goroutines. +func (u Uploader) UploadWithContext(ctx aws.Context, input *UploadInput, opts ...func(*Uploader)) (*UploadOutput, error) { + i := uploader{in: input, cfg: u, ctx: ctx} + + for _, opt := range opts { + opt(&i.cfg) + } + + i.cfg.RequestOptions = append(i.cfg.RequestOptions, request.WithAppendUserAgent("S3Manager")) + + return i.upload() +} + +// UploadWithIterator will upload a batched amount of objects to S3. This operation uses +// the iterator pattern to know which object to upload next. Since this is an interface this +// allows for custom defined functionality. +// +// Example: +// svc:= s3manager.NewUploader(sess) +// +// objects := []BatchUploadObject{ +// { +// Object: &s3manager.UploadInput { +// Key: aws.String("key"), +// Bucket: aws.String("bucket"), +// }, +// }, +// } +// +// iter := &s3manager.UploadObjectsIterator{Objects: objects} +// if err := svc.UploadWithIterator(aws.BackgroundContext(), iter); err != nil { +// return err +// } +func (u Uploader) UploadWithIterator(ctx aws.Context, iter BatchUploadIterator, opts ...func(*Uploader)) error { + var errs []Error + for iter.Next() { + object := iter.UploadObject() + if _, err := u.UploadWithContext(ctx, object.Object, opts...); err != nil { + s3Err := Error{ + OrigErr: err, + Bucket: object.Object.Bucket, + Key: object.Object.Key, + } + + errs = append(errs, s3Err) + } + + if object.After == nil { + continue + } + + if err := object.After(); err != nil { + s3Err := Error{ + OrigErr: err, + Bucket: object.Object.Bucket, + Key: object.Object.Key, + } + + errs = append(errs, s3Err) + } + } + + if len(errs) > 0 { + return NewBatchError("BatchedUploadIncomplete", "some objects have failed to upload.", errs) + } + return nil +} + +// internal structure to manage an upload to S3. +type uploader struct { + ctx aws.Context + cfg Uploader + + in *UploadInput + + readerPos int64 // current reader position + totalSize int64 // set to -1 if the size is not known +} + +// internal logic for deciding whether to upload a single part or use a +// multipart upload. +func (u *uploader) upload() (*UploadOutput, error) { + if err := u.init(); err != nil { + return nil, awserr.New("ReadRequestBody", "unable to initialize upload", err) + } + defer u.cfg.partPool.Close() + + if u.cfg.PartSize < MinUploadPartSize { + msg := fmt.Sprintf("part size must be at least %d bytes", MinUploadPartSize) + return nil, awserr.New("ConfigError", msg, nil) + } + + // Do one read to determine if we have more than one part + reader, _, cleanup, err := u.nextReader() + if err == io.EOF { // single part + return u.singlePart(reader, cleanup) + } else if err != nil { + cleanup() + return nil, awserr.New("ReadRequestBody", "read upload data failed", err) + } + + mu := multiuploader{uploader: u} + return mu.upload(reader, cleanup) +} + +// init will initialize all default options. +func (u *uploader) init() error { + if u.cfg.Concurrency == 0 { + u.cfg.Concurrency = DefaultUploadConcurrency + } + if u.cfg.PartSize == 0 { + u.cfg.PartSize = DefaultUploadPartSize + } + if u.cfg.MaxUploadParts == 0 { + u.cfg.MaxUploadParts = MaxUploadParts + } + + // Try to get the total size for some optimizations + if err := u.initSize(); err != nil { + return err + } + + // If PartSize was changed or partPool was never setup then we need to allocated a new pool + // so that we return []byte slices of the correct size + poolCap := u.cfg.Concurrency + 1 + if u.cfg.partPool == nil || u.cfg.partPool.SliceSize() != u.cfg.PartSize { + u.cfg.partPool = newByteSlicePool(u.cfg.PartSize) + u.cfg.partPool.ModifyCapacity(poolCap) + } else { + u.cfg.partPool = &returnCapacityPoolCloser{byteSlicePool: u.cfg.partPool} + u.cfg.partPool.ModifyCapacity(poolCap) + } + + return nil +} + +// initSize tries to detect the total stream size, setting u.totalSize. If +// the size is not known, totalSize is set to -1. +func (u *uploader) initSize() error { + u.totalSize = -1 + + switch r := u.in.Body.(type) { + case io.Seeker: + n, err := aws.SeekerLen(r) + if err != nil { + return err + } + u.totalSize = n + + // Try to adjust partSize if it is too small and account for + // integer division truncation. + if u.totalSize/u.cfg.PartSize >= int64(u.cfg.MaxUploadParts) { + // Add one to the part size to account for remainders + // during the size calculation. e.g odd number of bytes. + u.cfg.PartSize = (u.totalSize / int64(u.cfg.MaxUploadParts)) + 1 + } + } + + return nil +} + +// nextReader returns a seekable reader representing the next packet of data. +// This operation increases the shared u.readerPos counter, but note that it +// does not need to be wrapped in a mutex because nextReader is only called +// from the main thread. +func (u *uploader) nextReader() (io.ReadSeeker, int, func(), error) { + switch r := u.in.Body.(type) { + case readerAtSeeker: + var err error + + n := u.cfg.PartSize + if u.totalSize >= 0 { + bytesLeft := u.totalSize - u.readerPos + + if bytesLeft <= u.cfg.PartSize { + err = io.EOF + n = bytesLeft + } + } + + var ( + reader io.ReadSeeker + cleanup func() + ) + + reader = io.NewSectionReader(r, u.readerPos, n) + if u.cfg.BufferProvider != nil { + reader, cleanup = u.cfg.BufferProvider.GetWriteTo(reader) + } else { + cleanup = func() {} + } + + u.readerPos += n + + return reader, int(n), cleanup, err + + default: + part, err := u.cfg.partPool.Get(u.ctx) + if err != nil { + return nil, 0, func() {}, err + } + + n, err := readFillBuf(r, *part) + u.readerPos += int64(n) + + cleanup := func() { + u.cfg.partPool.Put(part) + } + + return bytes.NewReader((*part)[0:n]), n, cleanup, err + } +} + +func readFillBuf(r io.Reader, b []byte) (offset int, err error) { + for offset < len(b) && err == nil { + var n int + n, err = r.Read(b[offset:]) + offset += n + } + + return offset, err +} + +// singlePart contains upload logic for uploading a single chunk via +// a regular PutObject request. Multipart requests require at least two +// parts, or at least 5MB of data. +func (u *uploader) singlePart(r io.ReadSeeker, cleanup func()) (*UploadOutput, error) { + defer cleanup() + + params := &s3.PutObjectInput{} + awsutil.Copy(params, u.in) + params.Body = r + + // Need to use request form because URL generated in request is + // used in return. + req, out := u.cfg.S3.PutObjectRequest(params) + req.SetContext(u.ctx) + req.ApplyOptions(u.cfg.RequestOptions...) + if err := req.Send(); err != nil { + return nil, err + } + + url := req.HTTPRequest.URL.String() + return &UploadOutput{ + Location: url, + VersionID: out.VersionId, + }, nil +} + +// internal structure to manage a specific multipart upload to S3. +type multiuploader struct { + *uploader + wg sync.WaitGroup + m sync.Mutex + err error + uploadID string + parts completedParts +} + +// keeps track of a single chunk of data being sent to S3. +type chunk struct { + buf io.ReadSeeker + num int64 + cleanup func() +} + +// completedParts is a wrapper to make parts sortable by their part number, +// since S3 required this list to be sent in sorted order. +type completedParts []*s3.CompletedPart + +func (a completedParts) Len() int { return len(a) } +func (a completedParts) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a completedParts) Less(i, j int) bool { return *a[i].PartNumber < *a[j].PartNumber } + +// upload will perform a multipart upload using the firstBuf buffer containing +// the first chunk of data. +func (u *multiuploader) upload(firstBuf io.ReadSeeker, cleanup func()) (*UploadOutput, error) { + params := &s3.CreateMultipartUploadInput{} + awsutil.Copy(params, u.in) + + // Create the multipart + resp, err := u.cfg.S3.CreateMultipartUploadWithContext(u.ctx, params, u.cfg.RequestOptions...) + if err != nil { + cleanup() + return nil, err + } + u.uploadID = *resp.UploadId + + // Create the workers + ch := make(chan chunk, u.cfg.Concurrency) + for i := 0; i < u.cfg.Concurrency; i++ { + u.wg.Add(1) + go u.readChunk(ch) + } + + // Send part 1 to the workers + var num int64 = 1 + ch <- chunk{buf: firstBuf, num: num, cleanup: cleanup} + + // Read and queue the rest of the parts + for u.geterr() == nil && err == nil { + var ( + reader io.ReadSeeker + nextChunkLen int + ok bool + ) + + reader, nextChunkLen, cleanup, err = u.nextReader() + ok, err = u.shouldContinue(num, nextChunkLen, err) + if !ok { + cleanup() + if err != nil { + u.seterr(err) + } + break + } + + num++ + + ch <- chunk{buf: reader, num: num, cleanup: cleanup} + } + + // Close the channel, wait for workers, and complete upload + close(ch) + u.wg.Wait() + complete := u.complete() + + if err := u.geterr(); err != nil { + return nil, &multiUploadError{ + awsError: awserr.New( + "MultipartUpload", + "upload multipart failed", + err), + uploadID: u.uploadID, + } + } + + // Create a presigned URL of the S3 Get Object in order to have parity with + // single part upload. + getReq, _ := u.cfg.S3.GetObjectRequest(&s3.GetObjectInput{ + Bucket: u.in.Bucket, + Key: u.in.Key, + }) + getReq.Config.Credentials = credentials.AnonymousCredentials + getReq.SetContext(u.ctx) + uploadLocation, _, _ := getReq.PresignRequest(1) + + return &UploadOutput{ + Location: uploadLocation, + VersionID: complete.VersionId, + UploadID: u.uploadID, + }, nil +} + +func (u *multiuploader) shouldContinue(part int64, nextChunkLen int, err error) (bool, error) { + if err != nil && err != io.EOF { + return false, awserr.New("ReadRequestBody", "read multipart upload data failed", err) + } + + if nextChunkLen == 0 { + // No need to upload empty part, if file was empty to start + // with empty single part would of been created and never + // started multipart upload. + return false, nil + } + + part++ + // This upload exceeded maximum number of supported parts, error now. + if part > int64(u.cfg.MaxUploadParts) || part > int64(MaxUploadParts) { + var msg string + if part > int64(u.cfg.MaxUploadParts) { + msg = fmt.Sprintf("exceeded total allowed configured MaxUploadParts (%d). Adjust PartSize to fit in this limit", + u.cfg.MaxUploadParts) + } else { + msg = fmt.Sprintf("exceeded total allowed S3 limit MaxUploadParts (%d). Adjust PartSize to fit in this limit", + MaxUploadParts) + } + return false, awserr.New("TotalPartsExceeded", msg, nil) + } + + return true, err +} + +// readChunk runs in worker goroutines to pull chunks off of the ch channel +// and send() them as UploadPart requests. +func (u *multiuploader) readChunk(ch chan chunk) { + defer u.wg.Done() + for { + data, ok := <-ch + + if !ok { + break + } + + if u.geterr() == nil { + if err := u.send(data); err != nil { + u.seterr(err) + } + } + + data.cleanup() + } +} + +// send performs an UploadPart request and keeps track of the completed +// part information. +func (u *multiuploader) send(c chunk) error { + params := &s3.UploadPartInput{ + Bucket: u.in.Bucket, + Key: u.in.Key, + Body: c.buf, + UploadId: &u.uploadID, + SSECustomerAlgorithm: u.in.SSECustomerAlgorithm, + SSECustomerKey: u.in.SSECustomerKey, + PartNumber: &c.num, + } + + resp, err := u.cfg.S3.UploadPartWithContext(u.ctx, params, u.cfg.RequestOptions...) + if err != nil { + return err + } + + n := c.num + completed := &s3.CompletedPart{ETag: resp.ETag, PartNumber: &n} + + u.m.Lock() + u.parts = append(u.parts, completed) + u.m.Unlock() + + return nil +} + +// geterr is a thread-safe getter for the error object +func (u *multiuploader) geterr() error { + u.m.Lock() + defer u.m.Unlock() + + return u.err +} + +// seterr is a thread-safe setter for the error object +func (u *multiuploader) seterr(e error) { + u.m.Lock() + defer u.m.Unlock() + + u.err = e +} + +// fail will abort the multipart unless LeavePartsOnError is set to true. +func (u *multiuploader) fail() { + if u.cfg.LeavePartsOnError { + return + } + + params := &s3.AbortMultipartUploadInput{ + Bucket: u.in.Bucket, + Key: u.in.Key, + UploadId: &u.uploadID, + } + _, err := u.cfg.S3.AbortMultipartUploadWithContext(u.ctx, params, u.cfg.RequestOptions...) + if err != nil { + logMessage(u.cfg.S3, aws.LogDebug, fmt.Sprintf("failed to abort multipart upload, %v", err)) + } +} + +// complete successfully completes a multipart upload and returns the response. +func (u *multiuploader) complete() *s3.CompleteMultipartUploadOutput { + if u.geterr() != nil { + u.fail() + return nil + } + + // Parts must be sorted in PartNumber order. + sort.Sort(u.parts) + + params := &s3.CompleteMultipartUploadInput{ + Bucket: u.in.Bucket, + Key: u.in.Key, + UploadId: &u.uploadID, + MultipartUpload: &s3.CompletedMultipartUpload{Parts: u.parts}, + } + resp, err := u.cfg.S3.CompleteMultipartUploadWithContext(u.ctx, params, u.cfg.RequestOptions...) + if err != nil { + u.seterr(err) + u.fail() + } + + return resp +} + +type readerAtSeeker interface { + io.ReaderAt + io.ReadSeeker +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_input.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_input.go new file mode 100644 index 00000000000..c8810c11bbf --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_input.go @@ -0,0 +1,171 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package s3manager + +import ( + "io" + "time" +) + +// UploadInput provides the input parameters for uploading a stream or buffer +// to an object in an Amazon S3 bucket. This type is similar to the s3 +// package's PutObjectInput with the exception that the Body member is an +// io.Reader instead of an io.ReadSeeker. +type UploadInput struct { + _ struct{} `locationName:"PutObjectRequest" type:"structure" payload:"Body"` + + // The canned ACL to apply to the object. For more information, see Canned ACL + // (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL). + ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` + + // The readable body payload to send to S3. + Body io.Reader + + // Bucket name to which the PUT operation was initiated. + // + // When using this API with an access point, you must direct requests to the + // access point hostname. The access point hostname takes the form AccessPointName-AccountId.s3-accesspoint.Region.amazonaws.com. + // When using this operation using an access point through the AWS SDKs, you + // provide the access point ARN in place of the bucket name. For more information + // about access point ARNs, see Using Access Points (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-access-points.html) + // in the Amazon Simple Storage Service Developer Guide. + // + // Bucket is a required field + Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // Can be used to specify caching behavior along the request/reply chain. For + // more information, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 + // (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9). + CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` + + // Specifies presentational information for the object. For more information, + // see http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1). + ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` + + // Specifies what content encodings have been applied to the object and thus + // what decoding mechanisms must be applied to obtain the media-type referenced + // by the Content-Type header field. For more information, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 + // (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11). + ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` + + // The language the content is in. + ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` + + // The base64-encoded 128-bit MD5 digest of the message (without the headers) + // according to RFC 1864. This header can be used as a message integrity check + // to verify that the data is the same data that was originally sent. Although + // it is optional, we recommend using the Content-MD5 mechanism as an end-to-end + // integrity check. For more information about REST request authentication, + // see REST Authentication (https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html). + ContentMD5 *string `location:"header" locationName:"Content-MD5" type:"string"` + + // A standard MIME type describing the format of the contents. For more information, + // see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17). + ContentType *string `location:"header" locationName:"Content-Type" type:"string"` + + // The date and time at which the object is no longer cacheable. For more information, + // see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21). + Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp"` + + // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. + GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` + + // Allows grantee to read the object data and its metadata. + GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` + + // Allows grantee to read the object ACL. + GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` + + // Allows grantee to write the ACL for the applicable object. + GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` + + // Object key for which the PUT operation was initiated. + // + // Key is a required field + Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` + + // A map of metadata to store with the object in S3. + Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` + + // Specifies whether a legal hold will be applied to this object. For more information + // about S3 Object Lock, see Object Lock (https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lock.html). + ObjectLockLegalHoldStatus *string `location:"header" locationName:"x-amz-object-lock-legal-hold" type:"string" enum:"ObjectLockLegalHoldStatus"` + + // The Object Lock mode that you want to apply to this object. + ObjectLockMode *string `location:"header" locationName:"x-amz-object-lock-mode" type:"string" enum:"ObjectLockMode"` + + // The date and time when you want this object's Object Lock to expire. + ObjectLockRetainUntilDate *time.Time `location:"header" locationName:"x-amz-object-lock-retain-until-date" type:"timestamp" timestampFormat:"iso8601"` + + // Confirms that the requester knows that they will be charged for the request. + // Bucket owners need not specify this parameter in their requests. For information + // about downloading objects from requester pays buckets, see Downloading Objects + // in Requestor Pays Buckets (https://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html) + // in the Amazon S3 Developer Guide. + RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` + + // Specifies the algorithm to use to when encrypting the object (for example, + // AES256). + SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` + + // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting + // data. This value is used to store the object and then it is discarded; Amazon + // S3 does not store the encryption key. The key must be appropriate for use + // with the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // header. + SSECustomerKey *string `marshal-as:"blob" location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` + + // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. + // Amazon S3 uses this header for a message integrity check to ensure that the + // encryption key was transmitted without error. + SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` + + // Specifies the AWS KMS Encryption Context to use for object encryption. The + // value of this header is a base64-encoded UTF-8 string holding JSON with the + // encryption context key-value pairs. + SSEKMSEncryptionContext *string `location:"header" locationName:"x-amz-server-side-encryption-context" type:"string" sensitive:"true"` + + // If x-amz-server-side-encryption is present and has the value of aws:kms, + // this header specifies the ID of the AWS Key Management Service (AWS KMS) + // symmetrical customer managed customer master key (CMK) that was used for + // the object. + // + // If the value of x-amz-server-side-encryption is aws:kms, this header specifies + // the ID of the symmetric customer managed AWS KMS CMK that will be used for + // the object. If you specify x-amz-server-side-encryption:aws:kms, but do not + // providex-amz-server-side-encryption-aws-kms-key-id, Amazon S3 uses the AWS + // managed CMK in AWS to protect the data. + SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string" sensitive:"true"` + + // The server-side encryption algorithm used when storing this object in Amazon + // S3 (for example, AES256, aws:kms). + ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` + + // If you don't specify, S3 Standard is the default storage class. Amazon S3 + // supports other storage classes. + StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` + + // The tag-set for the object. The tag-set must be encoded as URL Query parameters. + // (For example, "Key1=Value1") + Tagging *string `location:"header" locationName:"x-amz-tagging" type:"string"` + + // If the bucket is configured as a website, redirects requests for this object + // to another object in the same bucket or to an external URL. Amazon S3 stores + // the value of this header in the object metadata. For information about object + // metadata, see Object Key and Metadata (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html). + // + // In the following example, the request header sets the redirect to an object + // (anotherPage.html) in the same bucket: + // + // x-amz-website-redirect-location: /anotherPage.html + // + // In the following example, the request header sets the object redirect to + // another website: + // + // x-amz-website-redirect-location: http://www.example.com/ + // + // For more information about website hosting in Amazon S3, see Hosting Websites + // on Amazon S3 (https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html) + // and How to Configure Website Page Redirects (https://docs.aws.amazon.com/AmazonS3/latest/dev/how-to-page-redirect.html). + WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/writer_read_from.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/writer_read_from.go new file mode 100644 index 00000000000..765dc07ca32 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/writer_read_from.go @@ -0,0 +1,75 @@ +package s3manager + +import ( + "bufio" + "io" + "sync" + + "github.com/aws/aws-sdk-go/internal/sdkio" +) + +// WriterReadFrom defines an interface implementing io.Writer and io.ReaderFrom +type WriterReadFrom interface { + io.Writer + io.ReaderFrom +} + +// WriterReadFromProvider provides an implementation of io.ReadFrom for the given io.Writer +type WriterReadFromProvider interface { + GetReadFrom(writer io.Writer) (w WriterReadFrom, cleanup func()) +} + +type bufferedWriter interface { + WriterReadFrom + Flush() error + Reset(io.Writer) +} + +type bufferedReadFrom struct { + bufferedWriter +} + +func (b *bufferedReadFrom) ReadFrom(r io.Reader) (int64, error) { + n, err := b.bufferedWriter.ReadFrom(r) + if flushErr := b.Flush(); flushErr != nil && err == nil { + err = flushErr + } + return n, err +} + +// PooledBufferedReadFromProvider is a WriterReadFromProvider that uses a sync.Pool +// to manage allocation and reuse of *bufio.Writer structures. +type PooledBufferedReadFromProvider struct { + pool sync.Pool +} + +// NewPooledBufferedWriterReadFromProvider returns a new PooledBufferedReadFromProvider +// Size is used to control the size of the underlying *bufio.Writer created for +// calls to GetReadFrom. +func NewPooledBufferedWriterReadFromProvider(size int) *PooledBufferedReadFromProvider { + if size < int(32*sdkio.KibiByte) { + size = int(64 * sdkio.KibiByte) + } + + return &PooledBufferedReadFromProvider{ + pool: sync.Pool{ + New: func() interface{} { + return &bufferedReadFrom{bufferedWriter: bufio.NewWriterSize(nil, size)} + }, + }, + } +} + +// GetReadFrom takes an io.Writer and wraps it with a type which satisfies the WriterReadFrom +// interface/ Additionally a cleanup function is provided which must be called after usage of the WriterReadFrom +// has been completed in order to allow the reuse of the *bufio.Writer +func (p *PooledBufferedReadFromProvider) GetReadFrom(writer io.Writer) (r WriterReadFrom, cleanup func()) { + buffer := p.pool.Get().(*bufferedReadFrom) + buffer.Reset(writer) + r = buffer + cleanup = func() { + buffer.Reset(nil) // Reset to nil writer to release reference + p.pool.Put(buffer) + } + return r, cleanup +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go b/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go index b71c835deef..57a0bd92ca3 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go @@ -69,7 +69,7 @@ func computeKeyMD5(keyHeader, keyMD5Header, key string, r *http.Request) { return } - // In backwards compatiable, the header's value is not base64 encoded, + // In backwards compatible, the header's value is not base64 encoded, // and needs to be encoded and updated by the SDK's customizations. b64Key := base64.StdEncoding.EncodeToString([]byte(key)) r.Header.Set(keyHeader, b64Key) diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3control/api.go b/vendor/github.com/aws/aws-sdk-go/service/s3control/api.go index 88503e0fe50..6ad326a3b4a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3control/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3control/api.go @@ -5690,6 +5690,16 @@ const ( JobManifestFieldNameVersionId = "VersionId" ) +// JobManifestFieldName_Values returns all elements of the JobManifestFieldName enum +func JobManifestFieldName_Values() []string { + return []string{ + JobManifestFieldNameIgnore, + JobManifestFieldNameBucket, + JobManifestFieldNameKey, + JobManifestFieldNameVersionId, + } +} + const ( // JobManifestFormatS3batchOperationsCsv20180820 is a JobManifestFormat enum value JobManifestFormatS3batchOperationsCsv20180820 = "S3BatchOperations_CSV_20180820" @@ -5698,11 +5708,26 @@ const ( JobManifestFormatS3inventoryReportCsv20161130 = "S3InventoryReport_CSV_20161130" ) +// JobManifestFormat_Values returns all elements of the JobManifestFormat enum +func JobManifestFormat_Values() []string { + return []string{ + JobManifestFormatS3batchOperationsCsv20180820, + JobManifestFormatS3inventoryReportCsv20161130, + } +} + const ( // JobReportFormatReportCsv20180820 is a JobReportFormat enum value JobReportFormatReportCsv20180820 = "Report_CSV_20180820" ) +// JobReportFormat_Values returns all elements of the JobReportFormat enum +func JobReportFormat_Values() []string { + return []string{ + JobReportFormatReportCsv20180820, + } +} + const ( // JobReportScopeAllTasks is a JobReportScope enum value JobReportScopeAllTasks = "AllTasks" @@ -5711,6 +5736,14 @@ const ( JobReportScopeFailedTasksOnly = "FailedTasksOnly" ) +// JobReportScope_Values returns all elements of the JobReportScope enum +func JobReportScope_Values() []string { + return []string{ + JobReportScopeAllTasks, + JobReportScopeFailedTasksOnly, + } +} + const ( // JobStatusActive is a JobStatus enum value JobStatusActive = "Active" @@ -5752,6 +5785,25 @@ const ( JobStatusSuspended = "Suspended" ) +// JobStatus_Values returns all elements of the JobStatus enum +func JobStatus_Values() []string { + return []string{ + JobStatusActive, + JobStatusCancelled, + JobStatusCancelling, + JobStatusComplete, + JobStatusCompleting, + JobStatusFailed, + JobStatusFailing, + JobStatusNew, + JobStatusPaused, + JobStatusPausing, + JobStatusPreparing, + JobStatusReady, + JobStatusSuspended, + } +} + const ( // NetworkOriginInternet is a NetworkOrigin enum value NetworkOriginInternet = "Internet" @@ -5760,6 +5812,14 @@ const ( NetworkOriginVpc = "VPC" ) +// NetworkOrigin_Values returns all elements of the NetworkOrigin enum +func NetworkOrigin_Values() []string { + return []string{ + NetworkOriginInternet, + NetworkOriginVpc, + } +} + const ( // OperationNameLambdaInvoke is a OperationName enum value OperationNameLambdaInvoke = "LambdaInvoke" @@ -5783,6 +5843,19 @@ const ( OperationNameS3putObjectRetention = "S3PutObjectRetention" ) +// OperationName_Values returns all elements of the OperationName enum +func OperationName_Values() []string { + return []string{ + OperationNameLambdaInvoke, + OperationNameS3putObjectCopy, + OperationNameS3putObjectAcl, + OperationNameS3putObjectTagging, + OperationNameS3initiateRestoreObject, + OperationNameS3putObjectLegalHold, + OperationNameS3putObjectRetention, + } +} + const ( // RequestedJobStatusCancelled is a RequestedJobStatus enum value RequestedJobStatusCancelled = "Cancelled" @@ -5791,6 +5864,14 @@ const ( RequestedJobStatusReady = "Ready" ) +// RequestedJobStatus_Values returns all elements of the RequestedJobStatus enum +func RequestedJobStatus_Values() []string { + return []string{ + RequestedJobStatusCancelled, + RequestedJobStatusReady, + } +} + const ( // S3CannedAccessControlListPrivate is a S3CannedAccessControlList enum value S3CannedAccessControlListPrivate = "private" @@ -5814,6 +5895,19 @@ const ( S3CannedAccessControlListBucketOwnerFullControl = "bucket-owner-full-control" ) +// S3CannedAccessControlList_Values returns all elements of the S3CannedAccessControlList enum +func S3CannedAccessControlList_Values() []string { + return []string{ + S3CannedAccessControlListPrivate, + S3CannedAccessControlListPublicRead, + S3CannedAccessControlListPublicReadWrite, + S3CannedAccessControlListAwsExecRead, + S3CannedAccessControlListAuthenticatedRead, + S3CannedAccessControlListBucketOwnerRead, + S3CannedAccessControlListBucketOwnerFullControl, + } +} + const ( // S3GlacierJobTierBulk is a S3GlacierJobTier enum value S3GlacierJobTierBulk = "BULK" @@ -5822,6 +5916,14 @@ const ( S3GlacierJobTierStandard = "STANDARD" ) +// S3GlacierJobTier_Values returns all elements of the S3GlacierJobTier enum +func S3GlacierJobTier_Values() []string { + return []string{ + S3GlacierJobTierBulk, + S3GlacierJobTierStandard, + } +} + const ( // S3GranteeTypeIdentifierId is a S3GranteeTypeIdentifier enum value S3GranteeTypeIdentifierId = "id" @@ -5833,6 +5935,15 @@ const ( S3GranteeTypeIdentifierUri = "uri" ) +// S3GranteeTypeIdentifier_Values returns all elements of the S3GranteeTypeIdentifier enum +func S3GranteeTypeIdentifier_Values() []string { + return []string{ + S3GranteeTypeIdentifierId, + S3GranteeTypeIdentifierEmailAddress, + S3GranteeTypeIdentifierUri, + } +} + const ( // S3MetadataDirectiveCopy is a S3MetadataDirective enum value S3MetadataDirectiveCopy = "COPY" @@ -5841,6 +5952,14 @@ const ( S3MetadataDirectiveReplace = "REPLACE" ) +// S3MetadataDirective_Values returns all elements of the S3MetadataDirective enum +func S3MetadataDirective_Values() []string { + return []string{ + S3MetadataDirectiveCopy, + S3MetadataDirectiveReplace, + } +} + const ( // S3ObjectLockLegalHoldStatusOff is a S3ObjectLockLegalHoldStatus enum value S3ObjectLockLegalHoldStatusOff = "OFF" @@ -5849,6 +5968,14 @@ const ( S3ObjectLockLegalHoldStatusOn = "ON" ) +// S3ObjectLockLegalHoldStatus_Values returns all elements of the S3ObjectLockLegalHoldStatus enum +func S3ObjectLockLegalHoldStatus_Values() []string { + return []string{ + S3ObjectLockLegalHoldStatusOff, + S3ObjectLockLegalHoldStatusOn, + } +} + const ( // S3ObjectLockModeCompliance is a S3ObjectLockMode enum value S3ObjectLockModeCompliance = "COMPLIANCE" @@ -5857,6 +5984,14 @@ const ( S3ObjectLockModeGovernance = "GOVERNANCE" ) +// S3ObjectLockMode_Values returns all elements of the S3ObjectLockMode enum +func S3ObjectLockMode_Values() []string { + return []string{ + S3ObjectLockModeCompliance, + S3ObjectLockModeGovernance, + } +} + const ( // S3ObjectLockRetentionModeCompliance is a S3ObjectLockRetentionMode enum value S3ObjectLockRetentionModeCompliance = "COMPLIANCE" @@ -5865,6 +6000,14 @@ const ( S3ObjectLockRetentionModeGovernance = "GOVERNANCE" ) +// S3ObjectLockRetentionMode_Values returns all elements of the S3ObjectLockRetentionMode enum +func S3ObjectLockRetentionMode_Values() []string { + return []string{ + S3ObjectLockRetentionModeCompliance, + S3ObjectLockRetentionModeGovernance, + } +} + const ( // S3PermissionFullControl is a S3Permission enum value S3PermissionFullControl = "FULL_CONTROL" @@ -5882,6 +6025,17 @@ const ( S3PermissionWriteAcp = "WRITE_ACP" ) +// S3Permission_Values returns all elements of the S3Permission enum +func S3Permission_Values() []string { + return []string{ + S3PermissionFullControl, + S3PermissionRead, + S3PermissionWrite, + S3PermissionReadAcp, + S3PermissionWriteAcp, + } +} + const ( // S3SSEAlgorithmAes256 is a S3SSEAlgorithm enum value S3SSEAlgorithmAes256 = "AES256" @@ -5890,6 +6044,14 @@ const ( S3SSEAlgorithmKms = "KMS" ) +// S3SSEAlgorithm_Values returns all elements of the S3SSEAlgorithm enum +func S3SSEAlgorithm_Values() []string { + return []string{ + S3SSEAlgorithmAes256, + S3SSEAlgorithmKms, + } +} + const ( // S3StorageClassStandard is a S3StorageClass enum value S3StorageClassStandard = "STANDARD" @@ -5909,3 +6071,15 @@ const ( // S3StorageClassDeepArchive is a S3StorageClass enum value S3StorageClassDeepArchive = "DEEP_ARCHIVE" ) + +// S3StorageClass_Values returns all elements of the S3StorageClass enum +func S3StorageClass_Values() []string { + return []string{ + S3StorageClassStandard, + S3StorageClassStandardIa, + S3StorageClassOnezoneIa, + S3StorageClassGlacier, + S3StorageClassIntelligentTiering, + S3StorageClassDeepArchive, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sagemaker/api.go b/vendor/github.com/aws/aws-sdk-go/service/sagemaker/api.go index 0a749943fc0..671b79722a2 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sagemaker/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sagemaker/api.go @@ -308,12 +308,8 @@ func (c *SageMaker) CreateAppRequest(input *CreateAppInput) (req *request.Reques // // Creates a running App for the specified UserProfile. Supported Apps are JupyterServer // and KernelGateway. This operation is automatically invoked by Amazon SageMaker -// Amazon SageMaker Studio (Studio) upon access to the associated Studio Domain, -// and when new kernel configurations are selected by the user. A user may have -// multiple Apps active simultaneously. Apps will automatically terminate and -// be deleted when stopped from within Studio, or when the DeleteApp API is -// manually called. UserProfiles are limited to 5 concurrently running Apps -// at a time. +// Studio upon access to the associated Domain, and when new kernel configurations +// are selected by the user. A user may have multiple Apps active simultaneously. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -587,7 +583,7 @@ func (c *SageMaker) CreateCompilationJobRequest(input *CreateCompilationJobInput // the model runs on // // * The Amazon Resource Name (ARN) of the IAM role that Amazon SageMaker -// assumes to perform the model compilation job +// assumes to perform the model compilation job. // // You can also provide a Tag to track the model compilation job's resource // use and costs. The response body contains the CompilationJobArn for the compiled @@ -678,15 +674,24 @@ func (c *SageMaker) CreateDomainRequest(input *CreateDomainInput) (req *request. // CreateDomain API operation for Amazon SageMaker Service. // -// Creates a Domain for Amazon SageMaker Amazon SageMaker Studio (Studio), which -// can be accessed by end-users in a web browser. A Domain has an associated -// directory, list of authorized users, and a variety of security, application, -// policies, and Amazon Virtual Private Cloud configurations. An AWS account -// is limited to one Domain, per region. Users within a domain can share notebook -// files and other artifacts with each other. When a Domain is created, an Amazon -// Elastic File System (EFS) is also created for use by all of the users within -// the Domain. Each user receives a private home directory within the EFS for -// notebooks, Git repositories, and data files. +// Creates a Domain used by SageMaker Studio. A domain consists of an associated +// directory, a list of authorized users, and a variety of security, application, +// policy, and Amazon Virtual Private Cloud (VPC) configurations. An AWS account +// is limited to one domain per region. Users within a domain can share notebook +// files and other artifacts with each other. +// +// When a domain is created, an Amazon Elastic File System (EFS) volume is also +// created for use by all of the users within the domain. Each user receives +// a private home directory within the EFS for notebooks, Git repositories, +// and data files. +// +// All traffic between the domain and the EFS volume is communicated through +// the specified subnet IDs. All other traffic goes over the Internet through +// an Amazon SageMaker system VPC. The EFS traffic uses the NFS/TCP protocol +// over port 2049. +// +// NFS traffic over TCP on port 2049 needs to be allowed in both inbound and +// outbound rules in order to launch a SageMaker Studio app successfully. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -788,6 +793,17 @@ func (c *SageMaker) CreateEndpointRequest(input *CreateEndpointInput) (req *requ // When it receives the request, Amazon SageMaker creates the endpoint, launches // the resources (ML compute instances), and deploys the model(s) on them. // +// When you call CreateEndpoint, a load call is made to DynamoDB to verify that +// your endpoint configuration exists. When you read data from a DynamoDB table +// supporting Eventually Consistent Reads (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html), +// the response might not reflect the results of a recently completed write +// operation. The response might include some stale data. If the dependent entities +// are not yet in DynamoDB, this causes a validation error. If you repeat your +// read request after a short time, the response should return the latest data. +// So retry logic is recommended to handle these possible issues. We also recommend +// that customers call DescribeEndpointConfig before calling CreateEndpoint +// to minimize the potential impact of a DynamoDB eventually consistent read. +// // When Amazon SageMaker receives the request, it sets the endpoint status to // Creating. After it creates the endpoint, it sets the status to InService. // Amazon SageMaker can then process incoming requests for inferences. To check @@ -902,6 +918,17 @@ func (c *SageMaker) CreateEndpointConfigRequest(input *CreateEndpointConfigInput // hosting services, see Deploy the Model to Amazon SageMaker Hosting Services // (AWS SDK for Python (Boto 3)). (https://docs.aws.amazon.com/sagemaker/latest/dg/ex1-deploy-model.html#ex1-deploy-model-boto) // +// When you call CreateEndpoint, a load call is made to DynamoDB to verify that +// your endpoint configuration exists. When you read data from a DynamoDB table +// supporting Eventually Consistent Reads (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html), +// the response might not reflect the results of a recently completed write +// operation. The response might include some stale data. If the dependent entities +// are not yet in DynamoDB, this causes a validation error. If you repeat your +// read request after a short time, the response should return the latest data. +// So retry logic is recommended to handle these possible issues. We also recommend +// that customers call DescribeEndpointConfig before calling CreateEndpoint +// to minimize the potential impact of a DynamoDB eventually consistent read. +// // Returns awserr.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. @@ -980,9 +1007,9 @@ func (c *SageMaker) CreateExperimentRequest(input *CreateExperimentInput) (req * // CreateExperiment API operation for Amazon SageMaker Service. // -// Creates an Amazon SageMaker experiment. An experiment is a collection of -// trials that are observed, compared and evaluated as a group. A trial is a -// set of steps, called trial components, that produce a machine learning model. +// Creates an SageMaker experiment. An experiment is a collection of trials +// that are observed, compared and evaluated as a group. A trial is a set of +// steps, called trial components, that produce a machine learning model. // // The goal of an experiment is to determine the components that produce the // best model. Multiple trials are performed, each one isolating and measuring @@ -1941,9 +1968,9 @@ func (c *SageMaker) CreatePresignedDomainUrlRequest(input *CreatePresignedDomain // // Creates a URL for a specified UserProfile in a Domain. When accessed in a // web browser, the user will be automatically signed in to Amazon SageMaker -// Amazon SageMaker Studio (Studio), and granted access to all of the Apps and -// files associated with that Amazon Elastic File System (EFS). This operation -// can only be called when AuthMode equals IAM. +// Studio, and granted access to all of the Apps and files associated with the +// Domain's Amazon Elastic File System (EFS) volume. This operation can only +// be called when the authentication mode equals IAM. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2028,13 +2055,17 @@ func (c *SageMaker) CreatePresignedNotebookInstanceUrlRequest(input *CreatePresi // home page from the notebook instance. The console uses this API to get the // URL and show the page. // -// IAM authorization policies for this API are also enforced for every HTTP -// request and WebSocket frame that attempts to connect to the notebook instance.For -// example, you can restrict access to this API and to the URL that it returns -// to a list of IP addresses that you specify. Use the NotIpAddress condition -// operator and the aws:SourceIP condition context key to specify the list of -// IP addresses that you want to have access to the notebook instance. For more -// information, see Limit Access to a Notebook Instance by IP Address (https://docs.aws.amazon.com/sagemaker/latest/dg/security_iam_id-based-policy-examples.html#nbi-ip-filter). +// The IAM role or user used to call this API defines the permissions to access +// the notebook instance. Once the presigned URL is created, no additional permission +// is required to access this URL. IAM authorization policies for this API are +// also enforced for every HTTP request and WebSocket frame that attempts to +// connect to the notebook instance. +// +// You can restrict access to this API and to the URL that it returns to a list +// of IP addresses that you specify. Use the NotIpAddress condition operator +// and the aws:SourceIP condition context key to specify the list of IP addresses +// that you want to have access to the notebook instance. For more information, +// see Limit Access to a Notebook Instance by IP Address (https://docs.aws.amazon.com/sagemaker/latest/dg/security_iam_id-based-policy-examples.html#nbi-ip-filter). // // The URL that you get from a call to CreatePresignedNotebookInstanceUrl is // valid only for 5 minutes. If you try to use the URL after the 5-minute limit @@ -2631,13 +2662,14 @@ func (c *SageMaker) CreateUserProfileRequest(input *CreateUserProfileInput) (req // CreateUserProfile API operation for Amazon SageMaker Service. // -// Creates a new user profile. A user profile represents a single user within -// a Domain, and is the main way to reference a "person" for the purposes of -// sharing, reporting and other user-oriented features. This entity is created -// during on-boarding. If an administrator invites a person by email or imports -// them from SSO, a new UserProfile is automatically created. This entity is -// the primary holder of settings for an individual user and has a reference -// to the user's private Amazon Elastic File System (EFS) home directory. +// Creates a user profile. A user profile represents a single user within a +// domain, and is the main way to reference a "person" for the purposes of sharing, +// reporting, and other user-oriented features. This entity is created when +// a user onboards to Amazon SageMaker Studio. If an administrator invites a +// person by email or imports them from SSO, a user profile is automatically +// created. A user profile is the primary holder of settings for an individual +// user and has a reference to the user's private Amazon Elastic File System +// (EFS) home directory. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2676,6 +2708,96 @@ func (c *SageMaker) CreateUserProfileWithContext(ctx aws.Context, input *CreateU return out, req.Send() } +const opCreateWorkforce = "CreateWorkforce" + +// CreateWorkforceRequest generates a "aws/request.Request" representing the +// client's request for the CreateWorkforce operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateWorkforce for more information on using the CreateWorkforce +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateWorkforceRequest method. +// req, resp := client.CreateWorkforceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/CreateWorkforce +func (c *SageMaker) CreateWorkforceRequest(input *CreateWorkforceInput) (req *request.Request, output *CreateWorkforceOutput) { + op := &request.Operation{ + Name: opCreateWorkforce, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateWorkforceInput{} + } + + output = &CreateWorkforceOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateWorkforce API operation for Amazon SageMaker Service. +// +// Use this operation to create a workforce. This operation will return an error +// if a workforce already exists in the AWS Region that you specify. You can +// only create one workforce in each AWS Region. +// +// If you want to create a new workforce in an AWS Region where the a workforce +// already exists, use the API operation to delete the existing workforce and +// then use this operation to create a new workforce. +// +// To create a private workforce using Amazon Cognito, you must specify a Cognito +// user pool in CognitoConfig. You can also create an Amazon Cognito workforce +// using the Amazon SageMaker console. For more information, see Create a Private +// Workforce (Amazon Cognito) (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-workforce-create-private.html). +// +// To create a private workforce using your own OIDC Identity Provider (IdP), +// specify your IdP configuration in OidcConfig. You must create a OIDC IdP +// workforce using this API operation. For more information, see Create a Private +// Workforce (OIDC IdP) (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-workforce-create-private-oidc.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon SageMaker Service's +// API operation CreateWorkforce for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/CreateWorkforce +func (c *SageMaker) CreateWorkforce(input *CreateWorkforceInput) (*CreateWorkforceOutput, error) { + req, out := c.CreateWorkforceRequest(input) + return out, req.Send() +} + +// CreateWorkforceWithContext is the same as CreateWorkforce with the addition of +// the ability to pass a context and additional request options. +// +// See CreateWorkforce for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SageMaker) CreateWorkforceWithContext(ctx aws.Context, input *CreateWorkforceInput, opts ...request.Option) (*CreateWorkforceOutput, error) { + req, out := c.CreateWorkforceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateWorkteam = "CreateWorkteam" // CreateWorkteamRequest generates a "aws/request.Request" representing the @@ -3041,10 +3163,10 @@ func (c *SageMaker) DeleteDomainRequest(input *DeleteDomainInput) (req *request. // DeleteDomain API operation for Amazon SageMaker Service. // -// Used to delete a domain. If you on-boarded with IAM mode, you will need to -// delete your domain to on-board again using SSO. Use with caution. All of -// the members of the domain will lose access to their EFS volume, including -// data, notebooks, and other artifacts. +// Used to delete a domain. If you onboarded with IAM mode, you will need to +// delete your domain to onboard again using SSO. Use with caution. All of the +// members of the domain will lose access to their EFS volume, including data, +// notebooks, and other 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 @@ -3211,6 +3333,13 @@ func (c *SageMaker) DeleteEndpointConfigRequest(input *DeleteEndpointConfigInput // the specified configuration. It does not delete endpoints created using the // configuration. // +// You must not delete an EndpointConfig in use by an endpoint that is live +// or while the UpdateEndpoint or CreateEndpoint operations are being performed +// on the endpoint. If you delete the EndpointConfig of an endpoint that is +// active or being created or updated you may lose visibility into the instance +// type the endpoint is using. The endpoint must be deleted in order to stop +// incurring charges. +// // Returns awserr.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. @@ -3375,6 +3504,9 @@ func (c *SageMaker) DeleteFlowDefinitionRequest(input *DeleteFlowDefinitionInput // API operation DeleteFlowDefinition for usage and error information. // // Returned Error Types: +// * ResourceInUse +// Resource being accessed is in use. +// // * ResourceNotFound // Resource being access is not found. // @@ -3400,6 +3532,90 @@ func (c *SageMaker) DeleteFlowDefinitionWithContext(ctx aws.Context, input *Dele return out, req.Send() } +const opDeleteHumanTaskUi = "DeleteHumanTaskUi" + +// DeleteHumanTaskUiRequest generates a "aws/request.Request" representing the +// client's request for the DeleteHumanTaskUi operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteHumanTaskUi for more information on using the DeleteHumanTaskUi +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteHumanTaskUiRequest method. +// req, resp := client.DeleteHumanTaskUiRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/DeleteHumanTaskUi +func (c *SageMaker) DeleteHumanTaskUiRequest(input *DeleteHumanTaskUiInput) (req *request.Request, output *DeleteHumanTaskUiOutput) { + op := &request.Operation{ + Name: opDeleteHumanTaskUi, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteHumanTaskUiInput{} + } + + output = &DeleteHumanTaskUiOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteHumanTaskUi API operation for Amazon SageMaker Service. +// +// Use this operation to delete a human task user interface (worker task template). +// +// To see a list of human task user interfaces (work task templates) in your +// account, use . When you delete a worker task template, it no longer appears +// when you call ListHumanTaskUis. +// +// Returns awserr.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 SageMaker Service's +// API operation DeleteHumanTaskUi for usage and error information. +// +// Returned Error Types: +// * ResourceNotFound +// Resource being access is not found. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/DeleteHumanTaskUi +func (c *SageMaker) DeleteHumanTaskUi(input *DeleteHumanTaskUiInput) (*DeleteHumanTaskUiOutput, error) { + req, out := c.DeleteHumanTaskUiRequest(input) + return out, req.Send() +} + +// DeleteHumanTaskUiWithContext is the same as DeleteHumanTaskUi with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteHumanTaskUi for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SageMaker) DeleteHumanTaskUiWithContext(ctx aws.Context, input *DeleteHumanTaskUiInput, opts ...request.Option) (*DeleteHumanTaskUiOutput, error) { + req, out := c.DeleteHumanTaskUiRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteModel = "DeleteModel" // DeleteModelRequest generates a "aws/request.Request" representing the @@ -4082,7 +4298,8 @@ func (c *SageMaker) DeleteUserProfileRequest(input *DeleteUserProfileInput) (req // DeleteUserProfile API operation for Amazon SageMaker Service. // -// Deletes a user profile. +// Deletes a user profile. When a user profile is deleted, the user loses access +// to their EFS volume, including data, notebooks, and other 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 @@ -4120,6 +4337,85 @@ func (c *SageMaker) DeleteUserProfileWithContext(ctx aws.Context, input *DeleteU return out, req.Send() } +const opDeleteWorkforce = "DeleteWorkforce" + +// DeleteWorkforceRequest generates a "aws/request.Request" representing the +// client's request for the DeleteWorkforce operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteWorkforce for more information on using the DeleteWorkforce +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteWorkforceRequest method. +// req, resp := client.DeleteWorkforceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/DeleteWorkforce +func (c *SageMaker) DeleteWorkforceRequest(input *DeleteWorkforceInput) (req *request.Request, output *DeleteWorkforceOutput) { + op := &request.Operation{ + Name: opDeleteWorkforce, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteWorkforceInput{} + } + + output = &DeleteWorkforceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteWorkforce API operation for Amazon SageMaker Service. +// +// Use this operation to delete a workforce. +// +// If you want to create a new workforce in an AWS Region where the a workforce +// already exists, use this operation to delete the existing workforce and then +// use to create a new workforce. +// +// Returns awserr.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 SageMaker Service's +// API operation DeleteWorkforce for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/DeleteWorkforce +func (c *SageMaker) DeleteWorkforce(input *DeleteWorkforceInput) (*DeleteWorkforceOutput, error) { + req, out := c.DeleteWorkforceRequest(input) + return out, req.Send() +} + +// DeleteWorkforceWithContext is the same as DeleteWorkforce with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteWorkforce for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SageMaker) DeleteWorkforceWithContext(ctx aws.Context, input *DeleteWorkforceInput, opts ...request.Option) (*DeleteWorkforceOutput, error) { + req, out := c.DeleteWorkforceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteWorkteam = "DeleteWorkteam" // DeleteWorkteamRequest generates a "aws/request.Request" representing the @@ -4632,7 +4928,7 @@ func (c *SageMaker) DescribeDomainRequest(input *DescribeDomainInput) (req *requ // DescribeDomain API operation for Amazon SageMaker Service. // -// The desciption of the domain. +// The description of the domain. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -5018,7 +5314,8 @@ func (c *SageMaker) DescribeHumanTaskUiRequest(input *DescribeHumanTaskUiInput) // DescribeHumanTaskUi API operation for Amazon SageMaker Service. // -// Returns information about the requested human task user interface. +// Returns information about the requested human task user interface (worker +// task template). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -6107,7 +6404,7 @@ func (c *SageMaker) DescribeUserProfileRequest(input *DescribeUserProfileInput) // DescribeUserProfile API operation for Amazon SageMaker Service. // -// Describes the user profile. +// Describes a user profile. For more information, see CreateUserProfile. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -10470,6 +10767,139 @@ func (c *SageMaker) ListUserProfilesPagesWithContext(ctx aws.Context, input *Lis return p.Err() } +const opListWorkforces = "ListWorkforces" + +// ListWorkforcesRequest generates a "aws/request.Request" representing the +// client's request for the ListWorkforces operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListWorkforces for more information on using the ListWorkforces +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListWorkforcesRequest method. +// req, resp := client.ListWorkforcesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/ListWorkforces +func (c *SageMaker) ListWorkforcesRequest(input *ListWorkforcesInput) (req *request.Request, output *ListWorkforcesOutput) { + op := &request.Operation{ + Name: opListWorkforces, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListWorkforcesInput{} + } + + output = &ListWorkforcesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListWorkforces API operation for Amazon SageMaker Service. +// +// Use this operation to list all private and vendor workforces in an AWS Region. +// Note that you can only have one private workforce per AWS Region. +// +// Returns awserr.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 SageMaker Service's +// API operation ListWorkforces for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/ListWorkforces +func (c *SageMaker) ListWorkforces(input *ListWorkforcesInput) (*ListWorkforcesOutput, error) { + req, out := c.ListWorkforcesRequest(input) + return out, req.Send() +} + +// ListWorkforcesWithContext is the same as ListWorkforces with the addition of +// the ability to pass a context and additional request options. +// +// See ListWorkforces for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SageMaker) ListWorkforcesWithContext(ctx aws.Context, input *ListWorkforcesInput, opts ...request.Option) (*ListWorkforcesOutput, error) { + req, out := c.ListWorkforcesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListWorkforcesPages iterates over the pages of a ListWorkforces operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListWorkforces 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 ListWorkforces operation. +// pageNum := 0 +// err := client.ListWorkforcesPages(params, +// func(page *sagemaker.ListWorkforcesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SageMaker) ListWorkforcesPages(input *ListWorkforcesInput, fn func(*ListWorkforcesOutput, bool) bool) error { + return c.ListWorkforcesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListWorkforcesPagesWithContext same as ListWorkforcesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SageMaker) ListWorkforcesPagesWithContext(ctx aws.Context, input *ListWorkforcesInput, fn func(*ListWorkforcesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListWorkforcesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListWorkforcesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListWorkforcesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListWorkteams = "ListWorkteams" // ListWorkteamsRequest generates a "aws/request.Request" representing the @@ -10656,6 +11086,11 @@ func (c *SageMaker) RenderUiTemplateRequest(input *RenderUiTemplateInput) (req * // // See the AWS API reference guide for Amazon SageMaker Service's // API operation RenderUiTemplate for usage and error information. +// +// Returned Error Types: +// * ResourceNotFound +// Resource being access is not found. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/RenderUiTemplate func (c *SageMaker) RenderUiTemplate(input *RenderUiTemplateInput) (*RenderUiTemplateOutput, error) { req, out := c.RenderUiTemplateRequest(input) @@ -11853,7 +12288,7 @@ func (c *SageMaker) UpdateDomainRequest(input *UpdateDomainInput) (req *request. // UpdateDomain API operation for Amazon SageMaker Service. // -// Updates a domain. Changes will impact all of the people in the domain. +// Updates the default settings for new user profiles in the domain. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -11951,6 +12386,10 @@ func (c *SageMaker) UpdateEndpointRequest(input *UpdateEndpointInput) (req *requ // or while the UpdateEndpoint or CreateEndpoint operations are being performed // on the endpoint. To update an endpoint, you must create a new EndpointConfig. // +// If you delete the EndpointConfig of an endpoint that is active or being created +// or updated you may lose visibility into the instance type the endpoint is +// using. The endpoint must be deleted in order to stop incurring charges. +// // Returns awserr.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. @@ -12699,7 +13138,7 @@ func (c *SageMaker) UpdateWorkforceRequest(input *UpdateWorkforceInput) (req *re // // Restricts access to tasks assigned to workers in the specified workforce // to those within specific ranges of IP addresses. You specify allowed IP addresses -// by creating a list of up to four CIDRs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html). +// by creating a list of up to ten CIDRs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html). // // By default, a workforce isn't restricted to specific IP addresses. If you // specify a range of IP addresses, workers who attempt to access tasks using @@ -13338,40 +13777,49 @@ func (s *AlgorithmValidationSpecification) SetValidationRole(v string) *Algorith return s } -// Configures how labels are consolidated across human workers. +// Configures how labels are consolidated across human workers and processes +// output data. type AnnotationConsolidationConfig struct { _ struct{} `type:"structure"` // The Amazon Resource Name (ARN) of a Lambda function implements the logic - // for annotation consolidation. - // - // For the built-in bounding box, image classification, semantic segmentation, - // and text classification task types, Amazon SageMaker Ground Truth provides - // the following Lambda functions: - // - // * Bounding box - Finds the most similar boxes from different workers based - // on the Jaccard index of the boxes. arn:aws:lambda:us-east-1:432418664414:function:ACS-BoundingBox - // arn:aws:lambda:us-east-2:266458841044:function:ACS-BoundingBox arn:aws:lambda:us-west-2:081040173940:function:ACS-BoundingBox - // arn:aws:lambda:eu-west-1:568282634449:function:ACS-BoundingBox arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-BoundingBox - // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-BoundingBox arn:aws:lambda:ap-south-1:565803892007:function:ACS-BoundingBox - // arn:aws:lambda:eu-central-1:203001061592:function:ACS-BoundingBox arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-BoundingBox - // arn:aws:lambda:eu-west-2:487402164563:function:ACS-BoundingBox arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-BoundingBox - // arn:aws:lambda:ca-central-1:918755190332:function:ACS-BoundingBox - // - // * Image classification - Uses a variant of the Expectation Maximization - // approach to estimate the true class of an image based on annotations from - // individual workers. arn:aws:lambda:us-east-1:432418664414:function:ACS-ImageMultiClass - // arn:aws:lambda:us-east-2:266458841044:function:ACS-ImageMultiClass arn:aws:lambda:us-west-2:081040173940:function:ACS-ImageMultiClass - // arn:aws:lambda:eu-west-1:568282634449:function:ACS-ImageMultiClass arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-ImageMultiClass + // for annotation consolidation (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-annotation-consolidation.html) + // and to process output data. + // + // This parameter is required for all labeling jobs. For built-in task types + // (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-task-types.html), use + // one of the following Amazon SageMaker Ground Truth Lambda function ARNs for + // AnnotationConsolidationLambdaArn. For custom labeling workflows, see Post-annotation + // Lambda (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-custom-templates-step3.html#sms-custom-templates-step3-postlambda). + // + // Bounding box - Finds the most similar boxes from different workers based + // on the Jaccard index of the boxes. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-BoundingBox arn:aws:lambda:us-east-2:266458841044:function:ACS-BoundingBox + // arn:aws:lambda:us-west-2:081040173940:function:ACS-BoundingBox arn:aws:lambda:eu-west-1:568282634449:function:ACS-BoundingBox + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-BoundingBox arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-BoundingBox + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-BoundingBox arn:aws:lambda:eu-central-1:203001061592:function:ACS-BoundingBox + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-BoundingBox arn:aws:lambda:eu-west-2:487402164563:function:ACS-BoundingBox + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-BoundingBox arn:aws:lambda:ca-central-1:918755190332:function:ACS-BoundingBox + // + // Image classification - Uses a variant of the Expectation Maximization approach + // to estimate the true class of an image based on annotations from individual + // workers. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-ImageMultiClass arn:aws:lambda:us-east-2:266458841044:function:ACS-ImageMultiClass + // arn:aws:lambda:us-west-2:081040173940:function:ACS-ImageMultiClass arn:aws:lambda:eu-west-1:568282634449:function:ACS-ImageMultiClass + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-ImageMultiClass // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-ImageMultiClass // arn:aws:lambda:ap-south-1:565803892007:function:ACS-ImageMultiClass arn:aws:lambda:eu-central-1:203001061592:function:ACS-ImageMultiClass // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-ImageMultiClass // arn:aws:lambda:eu-west-2:487402164563:function:ACS-ImageMultiClass arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-ImageMultiClass // arn:aws:lambda:ca-central-1:918755190332:function:ACS-ImageMultiClass // - // * Multi-label image classification - Uses a variant of the Expectation - // Maximization approach to estimate the true classes of an image based on - // annotations from individual workers. arn:aws:lambda:us-east-1:432418664414:function:ACS-ImageMultiClassMultiLabel + // Multi-label image classification - Uses a variant of the Expectation Maximization + // approach to estimate the true classes of an image based on annotations from + // individual workers. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-ImageMultiClassMultiLabel // arn:aws:lambda:us-east-2:266458841044:function:ACS-ImageMultiClassMultiLabel // arn:aws:lambda:us-west-2:081040173940:function:ACS-ImageMultiClassMultiLabel // arn:aws:lambda:eu-west-1:568282634449:function:ACS-ImageMultiClassMultiLabel @@ -13384,9 +13832,10 @@ type AnnotationConsolidationConfig struct { // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-ImageMultiClassMultiLabel // arn:aws:lambda:ca-central-1:918755190332:function:ACS-ImageMultiClassMultiLabel // - // * Semantic segmentation - Treats each pixel in an image as a multi-class - // classification and treats pixel annotations from workers as "votes" for - // the correct label. arn:aws:lambda:us-east-1:432418664414:function:ACS-SemanticSegmentation + // Semantic segmentation - Treats each pixel in an image as a multi-class classification + // and treats pixel annotations from workers as "votes" for the correct label. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-SemanticSegmentation // arn:aws:lambda:us-east-2:266458841044:function:ACS-SemanticSegmentation // arn:aws:lambda:us-west-2:081040173940:function:ACS-SemanticSegmentation // arn:aws:lambda:eu-west-1:568282634449:function:ACS-SemanticSegmentation @@ -13399,20 +13848,23 @@ type AnnotationConsolidationConfig struct { // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-SemanticSegmentation // arn:aws:lambda:ca-central-1:918755190332:function:ACS-SemanticSegmentation // - // * Text classification - Uses a variant of the Expectation Maximization - // approach to estimate the true class of text based on annotations from - // individual workers. arn:aws:lambda:us-east-1:432418664414:function:ACS-TextMultiClass - // arn:aws:lambda:us-east-2:266458841044:function:ACS-TextMultiClass arn:aws:lambda:us-west-2:081040173940:function:ACS-TextMultiClass - // arn:aws:lambda:eu-west-1:568282634449:function:ACS-TextMultiClass arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-TextMultiClass + // Text classification - Uses a variant of the Expectation Maximization approach + // to estimate the true class of text based on annotations from individual workers. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-TextMultiClass arn:aws:lambda:us-east-2:266458841044:function:ACS-TextMultiClass + // arn:aws:lambda:us-west-2:081040173940:function:ACS-TextMultiClass arn:aws:lambda:eu-west-1:568282634449:function:ACS-TextMultiClass + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-TextMultiClass // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-TextMultiClass // arn:aws:lambda:ap-south-1:565803892007:function:ACS-TextMultiClass arn:aws:lambda:eu-central-1:203001061592:function:ACS-TextMultiClass // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-TextMultiClass // arn:aws:lambda:eu-west-2:487402164563:function:ACS-TextMultiClass arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-TextMultiClass // arn:aws:lambda:ca-central-1:918755190332:function:ACS-TextMultiClass // - // * Multi-label text classification - Uses a variant of the Expectation - // Maximization approach to estimate the true classes of text based on annotations - // from individual workers. arn:aws:lambda:us-east-1:432418664414:function:ACS-TextMultiClassMultiLabel + // Multi-label text classification - Uses a variant of the Expectation Maximization + // approach to estimate the true classes of text based on annotations from individual + // workers. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-TextMultiClassMultiLabel // arn:aws:lambda:us-east-2:266458841044:function:ACS-TextMultiClassMultiLabel // arn:aws:lambda:us-west-2:081040173940:function:ACS-TextMultiClassMultiLabel // arn:aws:lambda:eu-west-1:568282634449:function:ACS-TextMultiClassMultiLabel @@ -13425,8 +13877,10 @@ type AnnotationConsolidationConfig struct { // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-TextMultiClassMultiLabel // arn:aws:lambda:ca-central-1:918755190332:function:ACS-TextMultiClassMultiLabel // - // * Named entity recognition - Groups similar selections and calculates - // aggregate boundaries, resolving to most-assigned label. arn:aws:lambda:us-east-1:432418664414:function:ACS-NamedEntityRecognition + // Named entity recognition - Groups similar selections and calculates aggregate + // boundaries, resolving to most-assigned label. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-NamedEntityRecognition // arn:aws:lambda:us-east-2:266458841044:function:ACS-NamedEntityRecognition // arn:aws:lambda:us-west-2:081040173940:function:ACS-NamedEntityRecognition // arn:aws:lambda:eu-west-1:568282634449:function:ACS-NamedEntityRecognition @@ -13439,25 +13893,153 @@ type AnnotationConsolidationConfig struct { // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-NamedEntityRecognition // arn:aws:lambda:ca-central-1:918755190332:function:ACS-NamedEntityRecognition // - // * Bounding box verification - Uses a variant of the Expectation Maximization - // approach to estimate the true class of verification judgement for bounding - // box labels based on annotations from individual workers. arn:aws:lambda:us-east-1:432418664414:function:ACS-VerificationBoundingBox - // arn:aws:lambda:us-east-2:266458841044:function:ACS-VerificationBoundingBox - // arn:aws:lambda:us-west-2:081040173940:function:ACS-VerificationBoundingBox - // arn:aws:lambda:eu-west-1:568282634449:function:ACS-VerificationBoundingBox - // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-VerificationBoundingBox - // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-VerificationBoundingBox - // arn:aws:lambda:ap-south-1:565803892007:function:ACS-VerificationBoundingBox - // arn:aws:lambda:eu-central-1:203001061592:function:ACS-VerificationBoundingBox - // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-VerificationBoundingBox - // arn:aws:lambda:eu-west-2:487402164563:function:ACS-VerificationBoundingBox - // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-VerificationBoundingBox - // arn:aws:lambda:ca-central-1:918755190332:function:ACS-VerificationBoundingBox + // Named entity recognition - Groups similar selections and calculates aggregate + // boundaries, resolving to most-assigned label. // - // * Semantic segmentation verification - Uses a variant of the Expectation - // Maximization approach to estimate the true class of verification judgment - // for semantic segmentation labels based on annotations from individual - // workers. arn:aws:lambda:us-east-1:432418664414:function:ACS-VerificationSemanticSegmentation + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-NamedEntityRecognition + // arn:aws:lambda:us-east-2:266458841044:function:ACS-NamedEntityRecognition + // arn:aws:lambda:us-west-2:081040173940:function:ACS-NamedEntityRecognition + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-NamedEntityRecognition + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-NamedEntityRecognition + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-NamedEntityRecognition + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-NamedEntityRecognition + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-NamedEntityRecognition + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-NamedEntityRecognition + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-NamedEntityRecognition + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-NamedEntityRecognition + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-NamedEntityRecognition + // + // Video Classification - Use this task type when you need workers to classify + // videos using predefined labels that you specify. Workers are shown videos + // and are asked to choose one label for each video. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-VideoMultiClass arn:aws:lambda:us-east-2:266458841044:function:ACS-VideoMultiClass + // arn:aws:lambda:us-west-2:081040173940:function:ACS-VideoMultiClass arn:aws:lambda:eu-west-1:568282634449:function:ACS-VideoMultiClass + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-VideoMultiClass + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-VideoMultiClass + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-VideoMultiClass arn:aws:lambda:eu-central-1:203001061592:function:ACS-VideoMultiClass + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-VideoMultiClass + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-VideoMultiClass arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-VideoMultiClass + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-VideoMultiClass + // + // Video Frame Object Detection - Use this task type to have workers identify + // and locate objects in a sequence of video frames (images extracted from a + // video) using bounding boxes. For example, you can use this task to ask workers + // to identify and localize various objects in a series of video frames, such + // as cars, bikes, and pedestrians. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-VideoObjectDetection + // arn:aws:lambda:us-east-2:266458841044:function:ACS-VideoObjectDetection + // arn:aws:lambda:us-west-2:081040173940:function:ACS-VideoObjectDetection + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-VideoObjectDetection + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-VideoObjectDetection + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-VideoObjectDetection + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-VideoObjectDetection + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-VideoObjectDetection + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-VideoObjectDetection + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-VideoObjectDetection + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-VideoObjectDetection + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-VideoObjectDetection + // + // Video Frame Object Tracking - Use this task type to have workers track the + // movement of objects in a sequence of video frames (images extracted from + // a video) using bounding boxes. For example, you can use this task to ask + // workers to track the movement of objects, such as cars, bikes, and pedestrians. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-VideoObjectTracking + // arn:aws:lambda:us-east-2:266458841044:function:ACS-VideoObjectTracking + // arn:aws:lambda:us-west-2:081040173940:function:ACS-VideoObjectTracking + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-VideoObjectTracking + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-VideoObjectTracking + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-VideoObjectTracking + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-VideoObjectTracking + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-VideoObjectTracking + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-VideoObjectTracking + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-VideoObjectTracking + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-VideoObjectTracking + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-VideoObjectTracking + // + // 3D point cloud object detection - Use this task type when you want workers + // to classify objects in a 3D point cloud by drawing 3D cuboids around objects. + // For example, you can use this task type to ask workers to identify different + // types of objects in a point cloud, such as cars, bikes, and pedestrians. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-3DPointCloudObjectDetection + // arn:aws:lambda:us-east-2:266458841044:function:ACS-3DPointCloudObjectDetection + // arn:aws:lambda:us-west-2:081040173940:function:ACS-3DPointCloudObjectDetection + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-3DPointCloudObjectDetection + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-3DPointCloudObjectDetection + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-3DPointCloudObjectDetection + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-3DPointCloudObjectDetection + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-3DPointCloudObjectDetection + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-3DPointCloudObjectDetection + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-3DPointCloudObjectDetection + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-3DPointCloudObjectDetection + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-3DPointCloudObjectDetection + // + // 3D point cloud object tracking - Use this task type when you want workers + // to draw 3D cuboids around objects that appear in a sequence of 3D point cloud + // frames. For example, you can use this task type to ask workers to track the + // movement of vehicles across multiple point cloud frames. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-3DPointCloudObjectTracking + // arn:aws:lambda:us-east-2:266458841044:function:ACS-3DPointCloudObjectTracking + // arn:aws:lambda:us-west-2:081040173940:function:ACS-3DPointCloudObjectTracking + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-3DPointCloudObjectTracking + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-3DPointCloudObjectTracking + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-3DPointCloudObjectTracking + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-3DPointCloudObjectTracking + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-3DPointCloudObjectTracking + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-3DPointCloudObjectTracking + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-3DPointCloudObjectTracking + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-3DPointCloudObjectTracking + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-3DPointCloudObjectTracking + // + // 3D point cloud semantic segmentation - Use this task type when you want workers + // to create a point-level semantic segmentation masks by painting objects in + // a 3D point cloud using different colors where each color is assigned to one + // of the classes you specify. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-3DPointCloudSemanticSegmentation + // arn:aws:lambda:us-east-2:266458841044:function:ACS-3DPointCloudSemanticSegmentation + // arn:aws:lambda:us-west-2:081040173940:function:ACS-3DPointCloudSemanticSegmentation + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-3DPointCloudSemanticSegmentation + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-3DPointCloudSemanticSegmentation + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-3DPointCloudSemanticSegmentation + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-3DPointCloudSemanticSegmentation + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-3DPointCloudSemanticSegmentation + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-3DPointCloudSemanticSegmentation + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-3DPointCloudSemanticSegmentation + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-3DPointCloudSemanticSegmentation + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-3DPointCloudSemanticSegmentation + // + // Use the following ARNs for Label Verification and Adjustment Jobs + // + // Use label verification and adjustment jobs to review and adjust labels. To + // learn more, see Verify and Adjust Labels (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-verification-data.html). + // + // Semantic segmentation adjustment - Treats each pixel in an image as a multi-class + // classification and treats pixel adjusted annotations from workers as "votes" + // for the correct label. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-AdjustmentSemanticSegmentation + // arn:aws:lambda:us-east-2:266458841044:function:ACS-AdjustmentSemanticSegmentation + // arn:aws:lambda:us-west-2:081040173940:function:ACS-AdjustmentSemanticSegmentation + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-AdjustmentSemanticSegmentation + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-AdjustmentSemanticSegmentation + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-AdjustmentSemanticSegmentation + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-AdjustmentSemanticSegmentation + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-AdjustmentSemanticSegmentation + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-AdjustmentSemanticSegmentation + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-AdjustmentSemanticSegmentation + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-AdjustmentSemanticSegmentation + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-AdjustmentSemanticSegmentation + // + // Semantic segmentation verification - Uses a variant of the Expectation Maximization + // approach to estimate the true class of verification judgment for semantic + // segmentation labels based on annotations from individual workers. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-VerificationSemanticSegmentation // arn:aws:lambda:us-east-2:266458841044:function:ACS-VerificationSemanticSegmentation // arn:aws:lambda:us-west-2:081040173940:function:ACS-VerificationSemanticSegmentation // arn:aws:lambda:eu-west-1:568282634449:function:ACS-VerificationSemanticSegmentation @@ -13470,8 +14052,27 @@ type AnnotationConsolidationConfig struct { // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-VerificationSemanticSegmentation // arn:aws:lambda:ca-central-1:918755190332:function:ACS-VerificationSemanticSegmentation // - // * Bounding box adjustment - Finds the most similar boxes from different - // workers based on the Jaccard index of the adjusted annotations. arn:aws:lambda:us-east-1:432418664414:function:ACS-AdjustmentBoundingBox + // Bounding box verification - Uses a variant of the Expectation Maximization + // approach to estimate the true class of verification judgement for bounding + // box labels based on annotations from individual workers. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-VerificationBoundingBox + // arn:aws:lambda:us-east-2:266458841044:function:ACS-VerificationBoundingBox + // arn:aws:lambda:us-west-2:081040173940:function:ACS-VerificationBoundingBox + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-VerificationBoundingBox + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-VerificationBoundingBox + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-VerificationBoundingBox + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-VerificationBoundingBox + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-VerificationBoundingBox + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-VerificationBoundingBox + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-VerificationBoundingBox + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-VerificationBoundingBox + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-VerificationBoundingBox + // + // Bounding box adjustment - Finds the most similar boxes from different workers + // based on the Jaccard index of the adjusted annotations. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-AdjustmentBoundingBox // arn:aws:lambda:us-east-2:266458841044:function:ACS-AdjustmentBoundingBox // arn:aws:lambda:us-west-2:081040173940:function:ACS-AdjustmentBoundingBox // arn:aws:lambda:eu-west-1:568282634449:function:ACS-AdjustmentBoundingBox @@ -13484,22 +14085,89 @@ type AnnotationConsolidationConfig struct { // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-AdjustmentBoundingBox // arn:aws:lambda:ca-central-1:918755190332:function:ACS-AdjustmentBoundingBox // - // * Semantic segmentation adjustment - Treats each pixel in an image as - // a multi-class classification and treats pixel adjusted annotations from - // workers as "votes" for the correct label. arn:aws:lambda:us-east-1:432418664414:function:ACS-AdjustmentSemanticSegmentation - // arn:aws:lambda:us-east-2:266458841044:function:ACS-AdjustmentSemanticSegmentation - // arn:aws:lambda:us-west-2:081040173940:function:ACS-AdjustmentSemanticSegmentation - // arn:aws:lambda:eu-west-1:568282634449:function:ACS-AdjustmentSemanticSegmentation - // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-AdjustmentSemanticSegmentation - // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-AdjustmentSemanticSegmentation - // arn:aws:lambda:ap-south-1:565803892007:function:ACS-AdjustmentSemanticSegmentation - // arn:aws:lambda:eu-central-1:203001061592:function:ACS-AdjustmentSemanticSegmentation - // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-AdjustmentSemanticSegmentation - // arn:aws:lambda:eu-west-2:487402164563:function:ACS-AdjustmentSemanticSegmentation - // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-AdjustmentSemanticSegmentation - // arn:aws:lambda:ca-central-1:918755190332:function:ACS-AdjustmentSemanticSegmentation - // - // For more information, see Annotation Consolidation (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-annotation-consolidation.html). + // Video Frame Object Detection Adjustment - Use this task type when you want + // workers to adjust bounding boxes that workers have added to video frames + // to classify and localize objects in a sequence of video frames. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-AdjustmentVideoObjectDetection + // arn:aws:lambda:us-east-2:266458841044:function:ACS-AdjustmentVideoObjectDetection + // arn:aws:lambda:us-west-2:081040173940:function:ACS-AdjustmentVideoObjectDetection + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-AdjustmentVideoObjectDetection + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-AdjustmentVideoObjectDetection + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-AdjustmentVideoObjectDetection + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-AdjustmentVideoObjectDetection + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-AdjustmentVideoObjectDetection + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-AdjustmentVideoObjectDetection + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-AdjustmentVideoObjectDetection + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-AdjustmentVideoObjectDetection + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-AdjustmentVideoObjectDetection + // + // Video Frame Object Tracking Adjustment - Use this task type when you want + // workers to adjust bounding boxes that workers have added to video frames + // to track object movement across a sequence of video frames. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-AdjustmentVideoObjectTracking + // arn:aws:lambda:us-east-2:266458841044:function:ACS-AdjustmentVideoObjectTracking + // arn:aws:lambda:us-west-2:081040173940:function:ACS-AdjustmentVideoObjectTracking + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-AdjustmentVideoObjectTracking + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-AdjustmentVideoObjectTracking + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-AdjustmentVideoObjectTracking + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-AdjustmentVideoObjectTracking + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-AdjustmentVideoObjectTracking + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-AdjustmentVideoObjectTracking + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-AdjustmentVideoObjectTracking + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-AdjustmentVideoObjectTracking + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-AdjustmentVideoObjectTracking + // + // 3D point cloud object detection adjustment - Use this task type when you + // want workers to adjust 3D cuboids around objects in a 3D point cloud. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-Adjustment3DPointCloudObjectDetection + // arn:aws:lambda:us-east-2:266458841044:function:ACS-Adjustment3DPointCloudObjectDetection + // arn:aws:lambda:us-west-2:081040173940:function:ACS-Adjustment3DPointCloudObjectDetection + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-Adjustment3DPointCloudObjectDetection + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-Adjustment3DPointCloudObjectDetection + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-Adjustment3DPointCloudObjectDetection + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-Adjustment3DPointCloudObjectDetection + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-Adjustment3DPointCloudObjectDetection + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-Adjustment3DPointCloudObjectDetection + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-Adjustment3DPointCloudObjectDetection + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-Adjustment3DPointCloudObjectDetection + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-Adjustment3DPointCloudObjectDetection + // + // 3D point cloud object tracking adjustment - Use this task type when you want + // workers to adjust 3D cuboids around objects that appear in a sequence of + // 3D point cloud frames. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-Adjustment3DPointCloudObjectTracking + // arn:aws:lambda:us-east-2:266458841044:function:ACS-Adjustment3DPointCloudObjectTracking + // arn:aws:lambda:us-west-2:081040173940:function:ACS-Adjustment3DPointCloudObjectTracking + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-Adjustment3DPointCloudObjectTracking + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-Adjustment3DPointCloudObjectTracking + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-Adjustment3DPointCloudObjectTracking + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-Adjustment3DPointCloudObjectTracking + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-Adjustment3DPointCloudObjectTracking + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-Adjustment3DPointCloudObjectTracking + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-Adjustment3DPointCloudObjectTracking + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-Adjustment3DPointCloudObjectTracking + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-Adjustment3DPointCloudObjectTracking + // + // 3D point cloud semantic segmentation adjustment - Use this task type when + // you want workers to adjust a point-level semantic segmentation masks using + // a paint tool. + // + // * arn:aws:lambda:us-east-1:432418664414:function:ACS-Adjustment3DPointCloudSemanticSegmentation + // arn:aws:lambda:us-east-2:266458841044:function:ACS-Adjustment3DPointCloudSemanticSegmentation + // arn:aws:lambda:us-west-2:081040173940:function:ACS-Adjustment3DPointCloudSemanticSegmentation + // arn:aws:lambda:eu-west-1:568282634449:function:ACS-Adjustment3DPointCloudSemanticSegmentation + // arn:aws:lambda:ap-northeast-1:477331159723:function:ACS-Adjustment3DPointCloudSemanticSegmentation + // arn:aws:lambda:ap-southeast-2:454466003867:function:ACS-Adjustment3DPointCloudSemanticSegmentation + // arn:aws:lambda:ap-south-1:565803892007:function:ACS-Adjustment3DPointCloudSemanticSegmentation + // arn:aws:lambda:eu-central-1:203001061592:function:ACS-Adjustment3DPointCloudSemanticSegmentation + // arn:aws:lambda:ap-northeast-2:845288260483:function:ACS-Adjustment3DPointCloudSemanticSegmentation + // arn:aws:lambda:eu-west-2:487402164563:function:ACS-Adjustment3DPointCloudSemanticSegmentation + // arn:aws:lambda:ap-southeast-1:377565633583:function:ACS-Adjustment3DPointCloudSemanticSegmentation + // arn:aws:lambda:ca-central-1:918755190332:function:ACS-Adjustment3DPointCloudSemanticSegmentation // // AnnotationConsolidationLambdaArn is a required field AnnotationConsolidationLambdaArn *string `type:"string" required:"true"` @@ -15085,6 +15753,71 @@ func (s *CodeRepositorySummary) SetLastModifiedTime(v time.Time) *CodeRepository return s } +// Use this parameter to configure your Amazon Cognito workforce. A single Cognito +// workforce is created using and corresponds to a single Amazon Cognito user +// pool (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html). +type CognitoConfig struct { + _ struct{} `type:"structure"` + + // The client ID for your Amazon Cognito user pool. + // + // ClientId is a required field + ClientId *string `min:"1" type:"string" required:"true"` + + // A user pool (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html) + // is a user directory in Amazon Cognito. With a user pool, your users can sign + // in to your web or mobile app through Amazon Cognito. Your users can also + // sign in through social identity providers like Google, Facebook, Amazon, + // or Apple, and through SAML identity providers. + // + // UserPool is a required field + UserPool *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CognitoConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CognitoConfig) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CognitoConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CognitoConfig"} + if s.ClientId == nil { + invalidParams.Add(request.NewErrParamRequired("ClientId")) + } + if s.ClientId != nil && len(*s.ClientId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClientId", 1)) + } + if s.UserPool == nil { + invalidParams.Add(request.NewErrParamRequired("UserPool")) + } + if s.UserPool != nil && len(*s.UserPool) < 1 { + invalidParams.Add(request.NewErrParamMinLen("UserPool", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientId sets the ClientId field's value. +func (s *CognitoConfig) SetClientId(v string) *CognitoConfig { + s.ClientId = &v + return s +} + +// SetUserPool sets the UserPool field's value. +func (s *CognitoConfig) SetUserPool(v string) *CognitoConfig { + s.UserPool = &v + return s +} + // Identifies a Amazon Cognito user group. A user group can be used in on or // more work teams. type CognitoMemberDefinition struct { @@ -15237,10 +15970,20 @@ type CompilationJobSummary struct { // The time when the model compilation job started. CompilationStartTime *time.Time `type:"timestamp"` - // The type of device that the model will run on after compilation has completed. - // - // CompilationTargetDevice is a required field - CompilationTargetDevice *string `type:"string" required:"true" enum:"TargetDevice"` + // The type of device that the model will run on after the compilation job has + // completed. + CompilationTargetDevice *string `type:"string" enum:"TargetDevice"` + + // The type of accelerator that the model will run on after the compilation + // job has completed. + CompilationTargetPlatformAccelerator *string `type:"string" enum:"TargetPlatformAccelerator"` + + // The type of architecture that the model will run on after the compilation + // job has completed. + CompilationTargetPlatformArch *string `type:"string" enum:"TargetPlatformArch"` + + // The type of OS that the model will run on after the compilation job has completed. + CompilationTargetPlatformOs *string `type:"string" enum:"TargetPlatformOs"` // The time when the model compilation job was created. // @@ -15297,6 +16040,24 @@ func (s *CompilationJobSummary) SetCompilationTargetDevice(v string) *Compilatio return s } +// SetCompilationTargetPlatformAccelerator sets the CompilationTargetPlatformAccelerator field's value. +func (s *CompilationJobSummary) SetCompilationTargetPlatformAccelerator(v string) *CompilationJobSummary { + s.CompilationTargetPlatformAccelerator = &v + return s +} + +// SetCompilationTargetPlatformArch sets the CompilationTargetPlatformArch field's value. +func (s *CompilationJobSummary) SetCompilationTargetPlatformArch(v string) *CompilationJobSummary { + s.CompilationTargetPlatformArch = &v + return s +} + +// SetCompilationTargetPlatformOs sets the CompilationTargetPlatformOs field's value. +func (s *CompilationJobSummary) SetCompilationTargetPlatformOs(v string) *CompilationJobSummary { + s.CompilationTargetPlatformOs = &v + return s +} + // SetCreationTime sets the CreationTime field's value. func (s *CompilationJobSummary) SetCreationTime(v time.Time) *CompilationJobSummary { s.CreationTime = &v @@ -15820,7 +16581,8 @@ type CreateAppInput struct { // DomainId is a required field DomainId *string `type:"string" required:"true"` - // The instance type and quantity. + // The instance type and the Amazon Resource Name (ARN) of the SageMaker image + // created on the instance. ResourceSpec *ResourceSpec `type:"structure"` // Each tag consists of a key and an optional value. Tag keys must be unique @@ -15914,7 +16676,7 @@ func (s *CreateAppInput) SetUserProfileName(v string) *CreateAppInput { type CreateAppOutput struct { _ struct{} `type:"structure"` - // The app's Amazon Resource Name (ARN). + // The App's Amazon Resource Name (ARN). AppArn *string `type:"string"` } @@ -16389,7 +17151,7 @@ func (s *CreateCompilationJobOutput) SetCompilationJobArn(v string) *CreateCompi type CreateDomainInput struct { _ struct{} `type:"structure"` - // The mode of authentication that member use to access the domain. + // The mode of authentication that members use to access the domain. // // AuthMode is a required field AuthMode *string `type:"string" required:"true" enum:"AuthMode"` @@ -16404,20 +17166,22 @@ type CreateDomainInput struct { // DomainName is a required field DomainName *string `type:"string" required:"true"` - // The AWS Key Management Service encryption key ID. + // The AWS Key Management Service (KMS) encryption key ID. Encryption with a + // customer master key (CMK) is not supported. HomeEfsFileSystemKmsKeyId *string `type:"string"` - // Security setting to limit to a set of subnets. + // The VPC subnets to use for communication with the EFS volume. // // SubnetIds is a required field SubnetIds []*string `min:"1" type:"list" required:"true"` - // Each tag consists of a key and an optional value. Tag keys must be unique - // per resource. + // Tags to associated with the Domain. Each tag consists of a key and an optional + // value. Tag keys must be unique per resource. Tags are searchable using the + // Search API. Tags []*Tag `type:"list"` - // Security setting to limit the domain's communication to a Amazon Virtual - // Private Cloud. + // The ID of the Amazon Virtual Private Cloud (VPC) to use for communication + // with the EFS volume. // // VpcId is a required field VpcId *string `type:"string" required:"true"` @@ -17237,6 +18001,8 @@ type CreateHyperParameterTuningJobInput struct { // stopping condition. TrainingJobDefinition *HyperParameterTrainingJobDefinition `type:"structure"` + // A list of the HyperParameterTrainingJobDefinition objects launched for this + // tuning job. TrainingJobDefinitions []*HyperParameterTrainingJobDefinition `min:"1" type:"list"` // Specifies the configuration for starting the hyperparameter tuning job using @@ -17415,7 +18181,14 @@ type CreateLabelingJobInput struct { // The S3 URL of the file that defines the categories used to label the data // objects. // - // The file is a JSON structure in the following format: + // For 3D point cloud task types, see Create a Labeling Category Configuration + // File for 3D Point Cloud Labeling Jobs (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-point-cloud-label-category-config.html). + // + // For all other built-in task types (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-task-types.html) + // and custom tasks (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-custom-templates.html), + // your label category configuration file must be a JSON file in the following + // format. Identify the labels you want to use by replacing label_1, label_2,...,label_n + // with your label categories. // // { // @@ -17425,13 +18198,13 @@ type CreateLabelingJobInput struct { // // { // - // "label": "label 1" + // "label": "label_1" // // }, // // { // - // "label": "label 2" + // "label": "label_2" // // }, // @@ -17439,7 +18212,7 @@ type CreateLabelingJobInput struct { // // { // - // "label": "label n" + // "label": "label_n" // // } // @@ -18594,7 +19367,14 @@ type CreateProcessingJobInput struct { // Sets the environment variables in the Docker container. Environment map[string]*string `type:"map"` - // Configuration for the experiment. + // Associates a SageMaker job as a trial component with an experiment and trial. + // Specified when you call the following APIs: + // + // * CreateProcessingJob + // + // * CreateTrainingJob + // + // * CreateTransformJob ExperimentConfig *ExperimentConfig `type:"structure"` // Networking options for a processing job. @@ -18866,7 +19646,14 @@ type CreateTrainingJobInput struct { // have network access. EnableNetworkIsolation *bool `type:"boolean"` - // Configuration for the experiment. + // Associates a SageMaker job as a trial component with an experiment and trial. + // Specified when you call the following APIs: + // + // * CreateProcessingJob + // + // * CreateTrainingJob + // + // * CreateTransformJob ExperimentConfig *ExperimentConfig `type:"structure"` // Algorithm-specific parameters that influence the quality of the model. You @@ -19247,7 +20034,14 @@ type CreateTransformJobInput struct { // 16 key and values entries in the map. Environment map[string]*string `type:"map"` - // Configuration for the experiment. + // Associates a SageMaker job as a trial component with an experiment and trial. + // Specified when you call the following APIs: + // + // * CreateProcessingJob + // + // * CreateTrainingJob + // + // * CreateTransformJob ExperimentConfig *ExperimentConfig `type:"structure"` // The maximum number of parallel requests that can be sent to each instance @@ -19272,6 +20066,10 @@ type CreateTransformJobInput struct { // do not support HTTP chunked encoding. MaxPayloadInMB *int64 `type:"integer"` + // Configures the timeout and maximum number of retries for processing a transform + // job invocation. + ModelClientConfig *ModelClientConfig `type:"structure"` + // The name of the model that you want to use for the transform job. ModelName // must be the name of an existing Amazon SageMaker model within an AWS Region // in an AWS account. @@ -19343,6 +20141,11 @@ func (s *CreateTransformJobInput) Validate() error { invalidParams.AddNested("ExperimentConfig", err.(request.ErrInvalidParams)) } } + if s.ModelClientConfig != nil { + if err := s.ModelClientConfig.Validate(); err != nil { + invalidParams.AddNested("ModelClientConfig", err.(request.ErrInvalidParams)) + } + } if s.Tags != nil { for i, v := range s.Tags { if v == nil { @@ -19411,6 +20214,12 @@ func (s *CreateTransformJobInput) SetMaxPayloadInMB(v int64) *CreateTransformJob return s } +// SetModelClientConfig sets the ModelClientConfig field's value. +func (s *CreateTransformJobInput) SetModelClientConfig(v *ModelClientConfig) *CreateTransformJobInput { + s.ModelClientConfig = v + return s +} + // SetModelName sets the ModelName field's value. func (s *CreateTransformJobInput) SetModelName(v string) *CreateTransformJobInput { s.ModelName = &v @@ -19900,6 +20709,142 @@ func (s *CreateUserProfileOutput) SetUserProfileArn(v string) *CreateUserProfile return s } +type CreateWorkforceInput struct { + _ struct{} `type:"structure"` + + // Use this parameter to configure an Amazon Cognito private workforce. A single + // Cognito workforce is created using and corresponds to a single Amazon Cognito + // user pool (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html). + // + // Do not use OidcConfig if you specify values for CognitoConfig. + CognitoConfig *CognitoConfig `type:"structure"` + + // Use this parameter to configure a private workforce using your own OIDC Identity + // Provider. Do not use CognitoConfig if you specify values for OidcConfig. + OidcConfig *OidcConfig `type:"structure"` + + // A list of IP address ranges (CIDRs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html)). + // Used to create an allow list of IP addresses for a private workforce. For + // more information, see . + SourceIpConfig *SourceIpConfig `type:"structure"` + + // An array of key-value pairs that contain metadata to help you categorize + // and organize our workforce. Each tag consists of a key and a value, both + // of which you define. + Tags []*Tag `type:"list"` + + // The name of the private workforce. + // + // WorkforceName is a required field + WorkforceName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateWorkforceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateWorkforceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateWorkforceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateWorkforceInput"} + if s.WorkforceName == nil { + invalidParams.Add(request.NewErrParamRequired("WorkforceName")) + } + if s.WorkforceName != nil && len(*s.WorkforceName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("WorkforceName", 1)) + } + if s.CognitoConfig != nil { + if err := s.CognitoConfig.Validate(); err != nil { + invalidParams.AddNested("CognitoConfig", err.(request.ErrInvalidParams)) + } + } + if s.OidcConfig != nil { + if err := s.OidcConfig.Validate(); err != nil { + invalidParams.AddNested("OidcConfig", err.(request.ErrInvalidParams)) + } + } + if s.SourceIpConfig != nil { + if err := s.SourceIpConfig.Validate(); err != nil { + invalidParams.AddNested("SourceIpConfig", err.(request.ErrInvalidParams)) + } + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCognitoConfig sets the CognitoConfig field's value. +func (s *CreateWorkforceInput) SetCognitoConfig(v *CognitoConfig) *CreateWorkforceInput { + s.CognitoConfig = v + return s +} + +// SetOidcConfig sets the OidcConfig field's value. +func (s *CreateWorkforceInput) SetOidcConfig(v *OidcConfig) *CreateWorkforceInput { + s.OidcConfig = v + return s +} + +// SetSourceIpConfig sets the SourceIpConfig field's value. +func (s *CreateWorkforceInput) SetSourceIpConfig(v *SourceIpConfig) *CreateWorkforceInput { + s.SourceIpConfig = v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateWorkforceInput) SetTags(v []*Tag) *CreateWorkforceInput { + s.Tags = v + return s +} + +// SetWorkforceName sets the WorkforceName field's value. +func (s *CreateWorkforceInput) SetWorkforceName(v string) *CreateWorkforceInput { + s.WorkforceName = &v + return s +} + +type CreateWorkforceOutput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the workforce. + // + // WorkforceArn is a required field + WorkforceArn *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateWorkforceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateWorkforceOutput) GoString() string { + return s.String() +} + +// SetWorkforceArn sets the WorkforceArn field's value. +func (s *CreateWorkforceOutput) SetWorkforceArn(v string) *CreateWorkforceOutput { + s.WorkforceArn = &v + return s +} + type CreateWorkteamInput struct { _ struct{} `type:"structure"` @@ -19928,6 +20873,9 @@ type CreateWorkteamInput struct { // in the AWS Billing and Cost Management User Guide. Tags []*Tag `type:"list"` + // The name of the workforce. + WorkforceName *string `min:"1" type:"string"` + // The name of the work team. Use this name to identify the work team. // // WorkteamName is a required field @@ -19959,6 +20907,9 @@ func (s *CreateWorkteamInput) Validate() error { if s.MemberDefinitions != nil && len(s.MemberDefinitions) < 1 { invalidParams.Add(request.NewErrParamMinLen("MemberDefinitions", 1)) } + if s.WorkforceName != nil && len(*s.WorkforceName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("WorkforceName", 1)) + } if s.WorkteamName == nil { invalidParams.Add(request.NewErrParamRequired("WorkteamName")) } @@ -20016,6 +20967,12 @@ func (s *CreateWorkteamInput) SetTags(v []*Tag) *CreateWorkteamInput { return s } +// SetWorkforceName sets the WorkforceName field's value. +func (s *CreateWorkteamInput) SetWorkforceName(v string) *CreateWorkteamInput { + s.WorkforceName = &v + return s +} + // SetWorkteamName sets the WorkteamName field's value. func (s *CreateWorkteamInput) SetWorkteamName(v string) *CreateWorkteamInput { s.WorkteamName = &v @@ -20788,7 +21745,7 @@ type DeleteDomainInput struct { // DomainId is a required field DomainId *string `type:"string" required:"true"` - // The retention policy for this domain, which specifies which resources will + // The retention policy for this domain, which specifies whether resources will // be retained after the Domain is deleted. By default, all resources are retained // (not automatically deleted). RetentionPolicy *RetentionPolicy `type:"structure"` @@ -21066,6 +22023,62 @@ func (s DeleteFlowDefinitionOutput) GoString() string { return s.String() } +type DeleteHumanTaskUiInput struct { + _ struct{} `type:"structure"` + + // The name of the human task user interface (work task template) you want to + // delete. + // + // HumanTaskUiName is a required field + HumanTaskUiName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteHumanTaskUiInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteHumanTaskUiInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteHumanTaskUiInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteHumanTaskUiInput"} + if s.HumanTaskUiName == nil { + invalidParams.Add(request.NewErrParamRequired("HumanTaskUiName")) + } + if s.HumanTaskUiName != nil && len(*s.HumanTaskUiName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("HumanTaskUiName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetHumanTaskUiName sets the HumanTaskUiName field's value. +func (s *DeleteHumanTaskUiInput) SetHumanTaskUiName(v string) *DeleteHumanTaskUiInput { + s.HumanTaskUiName = &v + return s +} + +type DeleteHumanTaskUiOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteHumanTaskUiOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteHumanTaskUiOutput) GoString() string { + return s.String() +} + type DeleteModelInput struct { _ struct{} `type:"structure"` @@ -21596,6 +22609,61 @@ func (s DeleteUserProfileOutput) GoString() string { return s.String() } +type DeleteWorkforceInput struct { + _ struct{} `type:"structure"` + + // The name of the workforce. + // + // WorkforceName is a required field + WorkforceName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteWorkforceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteWorkforceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteWorkforceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteWorkforceInput"} + if s.WorkforceName == nil { + invalidParams.Add(request.NewErrParamRequired("WorkforceName")) + } + if s.WorkforceName != nil && len(*s.WorkforceName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("WorkforceName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetWorkforceName sets the WorkforceName field's value. +func (s *DeleteWorkforceInput) SetWorkforceName(v string) *DeleteWorkforceInput { + s.WorkforceName = &v + return s +} + +type DeleteWorkforceOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteWorkforceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteWorkforceOutput) GoString() string { + return s.String() +} + type DeleteWorkteamInput struct { _ struct{} `type:"structure"` @@ -21987,7 +23055,8 @@ type DescribeAppOutput struct { // The timestamp of the last user's activity. LastUserActivityTimestamp *time.Time `type:"timestamp"` - // The instance type and quantity. + // The instance type and the Amazon Resource Name (ARN) of the SageMaker image + // created on the instance. ResourceSpec *ResourceSpec `type:"structure"` // The status. @@ -23294,6 +24363,7 @@ type DescribeFlowDefinitionOutput struct { // CreationTime is a required field CreationTime *time.Time `type:"timestamp" required:"true"` + // The reason your flow definition failed. FailureReason *string `type:"string"` // The Amazon Resource Name (ARN) of the flow defintion. @@ -23409,7 +24479,8 @@ func (s *DescribeFlowDefinitionOutput) SetRoleArn(v string) *DescribeFlowDefinit type DescribeHumanTaskUiInput struct { _ struct{} `type:"structure"` - // The name of the human task user interface you want information about. + // The name of the human task user interface (worker task template) you want + // information about. // // HumanTaskUiName is a required field HumanTaskUiName *string `min:"1" type:"string" required:"true"` @@ -23455,16 +24526,21 @@ type DescribeHumanTaskUiOutput struct { // CreationTime is a required field CreationTime *time.Time `type:"timestamp" required:"true"` - // The Amazon Resource Name (ARN) of the human task user interface. + // The Amazon Resource Name (ARN) of the human task user interface (worker task + // template). // // HumanTaskUiArn is a required field HumanTaskUiArn *string `type:"string" required:"true"` - // The name of the human task user interface. + // The name of the human task user interface (worker task template). // // HumanTaskUiName is a required field HumanTaskUiName *string `min:"1" type:"string" required:"true"` + // The status of the human task user interface (worker task template). Valid + // values are listed below. + HumanTaskUiStatus *string `type:"string" enum:"HumanTaskUiStatus"` + // Container for user interface template information. // // UiTemplate is a required field @@ -23499,6 +24575,12 @@ func (s *DescribeHumanTaskUiOutput) SetHumanTaskUiName(v string) *DescribeHumanT return s } +// SetHumanTaskUiStatus sets the HumanTaskUiStatus field's value. +func (s *DescribeHumanTaskUiOutput) SetHumanTaskUiStatus(v string) *DescribeHumanTaskUiOutput { + s.HumanTaskUiStatus = &v + return s +} + // SetUiTemplate sets the UiTemplate field's value. func (s *DescribeHumanTaskUiOutput) SetUiTemplate(v *UiTemplateInfo) *DescribeHumanTaskUiOutput { s.UiTemplate = v @@ -23508,7 +24590,7 @@ func (s *DescribeHumanTaskUiOutput) SetUiTemplate(v *UiTemplateInfo) *DescribeHu type DescribeHyperParameterTuningJobInput struct { _ struct{} `type:"structure"` - // The name of the tuning job to describe. + // The name of the tuning job. // // HyperParameterTuningJobName is a required field HyperParameterTuningJobName *string `min:"1" type:"string" required:"true"` @@ -23606,6 +24688,8 @@ type DescribeHyperParameterTuningJobOutput struct { // of the training jobs that this tuning job launches. TrainingJobDefinition *HyperParameterTrainingJobDefinition `type:"structure"` + // A list of the HyperParameterTrainingJobDefinition objects launched for this + // tuning job. TrainingJobDefinitions []*HyperParameterTrainingJobDefinition `min:"1" type:"list"` // The TrainingJobStatusCounters object that specifies the number of training @@ -25199,6 +26283,7 @@ type DescribeTrainingJobOutput struct { // AlgorithmSpecification is a required field AlgorithmSpecification *AlgorithmSpecification `type:"structure" required:"true"` + // The Amazon Resource Name (ARN) of an AutoML job. AutoMLJobArn *string `min:"1" type:"string"` // The billable time in seconds. @@ -25247,7 +26332,14 @@ type DescribeTrainingJobOutput struct { // have network access. EnableNetworkIsolation *bool `type:"boolean"` - // Configuration for the experiment. + // Associates a SageMaker job as a trial component with an experiment and trial. + // Specified when you call the following APIs: + // + // * CreateProcessingJob + // + // * CreateTrainingJob + // + // * CreateTransformJob ExperimentConfig *ExperimentConfig `type:"structure"` // If the training job failed, the reason it failed. @@ -25684,6 +26776,7 @@ func (s *DescribeTransformJobInput) SetTransformJobName(v string) *DescribeTrans type DescribeTransformJobOutput struct { _ struct{} `type:"structure"` + // The Amazon Resource Name (ARN) of the AutoML transform job. AutoMLJobArn *string `min:"1" type:"string"` // Specifies the number of records to include in a mini-batch for an HTTP inference @@ -25712,7 +26805,14 @@ type DescribeTransformJobOutput struct { // 16 key and values entries in the map. Environment map[string]*string `type:"map"` - // Configuration for the experiment. + // Associates a SageMaker job as a trial component with an experiment and trial. + // Specified when you call the following APIs: + // + // * CreateProcessingJob + // + // * CreateTrainingJob + // + // * CreateTransformJob ExperimentConfig *ExperimentConfig `type:"structure"` // If the transform job failed, FailureReason describes why it failed. A transform @@ -25732,6 +26832,10 @@ type DescribeTransformJobOutput struct { // The maximum payload size, in MB, used in the transform job. MaxPayloadInMB *int64 `type:"integer"` + // The timeout and maximum number of retries for processing a transform job + // invocation. + ModelClientConfig *ModelClientConfig `type:"structure"` + // The name of the model used in the transform job. // // ModelName is a required field @@ -25848,6 +26952,12 @@ func (s *DescribeTransformJobOutput) SetMaxPayloadInMB(v int64) *DescribeTransfo return s } +// SetModelClientConfig sets the ModelClientConfig field's value. +func (s *DescribeTransformJobOutput) SetModelClientConfig(v *ModelClientConfig) *DescribeTransformJobOutput { + s.ModelClientConfig = v + return s +} + // SetModelName sets the ModelName field's value. func (s *DescribeTransformJobOutput) SetModelName(v string) *DescribeTransformJobOutput { s.ModelName = &v @@ -26294,13 +27404,13 @@ type DescribeUserProfileOutput struct { // The creation time. CreationTime *time.Time `type:"timestamp"` - // The domain ID. + // The ID of the domain that contains the profile. DomainId *string `type:"string"` // The failure reason. FailureReason *string `type:"string"` - // The homa Amazon Elastic File System (EFS) Uid. + // The ID of the user's profile in the Amazon Elastic File System (EFS) volume. HomeEfsFileSystemUid *string `type:"string"` // The last modified time. @@ -27098,17 +28208,26 @@ func (s *Experiment) SetTags(v []*Tag) *Experiment { return s } -// Configuration for the experiment. +// Associates a SageMaker job as a trial component with an experiment and trial. +// Specified when you call the following APIs: +// +// * CreateProcessingJob +// +// * CreateTrainingJob +// +// * CreateTransformJob type ExperimentConfig struct { _ struct{} `type:"structure"` - // The name of the experiment. + // The name of an existing experiment to associate the trial component with. ExperimentName *string `min:"1" type:"string"` - // Display name for the trial component. + // The display name for the trial component. If this key isn't specified, the + // display name is the trial component name. TrialComponentDisplayName *string `min:"1" type:"string"` - // The name of the trial. + // The name of an existing trial to associate the trial component with. If not + // specified, a new trial is created. TrialName *string `min:"1" type:"string"` } @@ -27417,6 +28536,14 @@ type Filter struct { // // The value of Name doesn't equal Value. // + // Exists + // + // The Name property exists. + // + // NotExists + // + // The Name property does not exist. + // // GreaterThan // // The value of Name is greater than Value. Not supported for text properties. @@ -27435,23 +28562,44 @@ type Filter struct { // The value of Name is less than or equal to Value. Not supported for text // properties. // + // In + // + // The value of Name is one of the comma delimited strings in Value. Only supported + // for text properties. + // // Contains // - // The value of Name contains the string Value. A SearchExpression can include - // only one Contains operator. Only supported for text properties. + // The value of Name contains the string Value. Only supported for text properties. // - // Exists + // A SearchExpression can include the Contains operator multiple times when + // the value of Name is one of the following: // - // The Name property exists. + // * Experiment.DisplayName // - // NotExists + // * Experiment.ExperimentName // - // The Name property does not exist. + // * Experiment.Tags // - // In + // * Trial.DisplayName // - // The value of Name is one of the comma delimited strings in Value. Only supported - // for text properties. + // * Trial.TrialName + // + // * Trial.Tags + // + // * TrialComponent.DisplayName + // + // * TrialComponent.TrialComponentName + // + // * TrialComponent.Tags + // + // * TrialComponent.InputArtifacts + // + // * TrialComponent.OutputArtifacts + // + // A SearchExpression can include only one Contains operator for all other values + // of Name. In these cases, if you include multiple Contains operators in the + // SearchExpression, the result is the following error message: "'CONTAINS' + // operator usage limit of 1 exceeded." Operator *string `type:"string" enum:"Operator"` // A value used with Name and Operator to determine which resources satisfy @@ -28417,298 +29565,636 @@ type HumanTaskConfig struct { // data object is sent to a human worker. Use this function to provide input // to a custom labeling job. // - // For the built-in bounding box, image classification, semantic segmentation, - // and text classification task types, Amazon SageMaker Ground Truth provides - // the following Lambda functions: + // For built-in task types (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-task-types.html), + // use one of the following Amazon SageMaker Ground Truth Lambda function ARNs + // for PreHumanTaskLambdaArn. For custom labeling workflows, see Pre-annotation + // Lambda (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-custom-templates-step3.html#sms-custom-templates-step3-prelambda). // - // US East (Northern Virginia) (us-east-1): + // Bounding box - Finds the most similar boxes from different workers based + // on the Jaccard index of the boxes. // // * arn:aws:lambda:us-east-1:432418664414:function:PRE-BoundingBox // - // * arn:aws:lambda:us-east-1:432418664414:function:PRE-ImageMultiClass + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-BoundingBox // - // * arn:aws:lambda:us-east-1:432418664414:function:PRE-ImageMultiClassMultiLabel + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-BoundingBox // - // * arn:aws:lambda:us-east-1:432418664414:function:PRE-SemanticSegmentation + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-BoundingBox // - // * arn:aws:lambda:us-east-1:432418664414:function:PRE-TextMultiClass + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-BoundingBox // - // * arn:aws:lambda:us-east-1:432418664414:function:PRE-TextMultiClassMultiLabel + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-BoundingBox // - // * arn:aws:lambda:us-east-1:432418664414:function:PRE-NamedEntityRecognition + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-BoundingBox // - // * arn:aws:lambda:us-east-1:432418664414:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-BoundingBox // - // * arn:aws:lambda:us-east-1:432418664414:function:PRE-VerificationSemanticSegmentation + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-BoundingBox // - // * arn:aws:lambda:us-east-1:432418664414:function:PRE-AdjustmentBoundingBox + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-BoundingBox // - // * arn:aws:lambda:us-east-1:432418664414:function:PRE-AdjustmentSemanticSegmentation + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-BoundingBox // - // US East (Ohio) (us-east-2): + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-BoundingBox // - // * arn:aws:lambda:us-east-2:266458841044:function:PRE-BoundingBox + // Image classification - Uses a variant of the Expectation Maximization approach + // to estimate the true class of an image based on annotations from individual + // workers. + // + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-ImageMultiClass // // * arn:aws:lambda:us-east-2:266458841044:function:PRE-ImageMultiClass // - // * arn:aws:lambda:us-east-2:266458841044:function:PRE-ImageMultiClassMultiLabel + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-ImageMultiClass // - // * arn:aws:lambda:us-east-2:266458841044:function:PRE-SemanticSegmentation + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-ImageMultiClass // - // * arn:aws:lambda:us-east-2:266458841044:function:PRE-TextMultiClass + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-ImageMultiClass // - // * arn:aws:lambda:us-east-2:266458841044:function:PRE-TextMultiClassMultiLabel + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-ImageMultiClass // - // * arn:aws:lambda:us-east-2:266458841044:function:PRE-NamedEntityRecognition + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-ImageMultiClass // - // * arn:aws:lambda:us-east-2:266458841044:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-ImageMultiClass // - // * arn:aws:lambda:us-east-2:266458841044:function:PRE-VerificationSemanticSegmentation + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-ImageMultiClass // - // * arn:aws:lambda:us-east-2:266458841044:function:PRE-AdjustmentBoundingBox + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-ImageMultiClass // - // * arn:aws:lambda:us-east-2:266458841044:function:PRE-AdjustmentSemanticSegmentation + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-ImageMultiClass // - // US West (Oregon) (us-west-2): + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-ImageMultiClass // - // * arn:aws:lambda:us-west-2:081040173940:function:PRE-BoundingBox + // Multi-label image classification - Uses a variant of the Expectation Maximization + // approach to estimate the true classes of an image based on annotations from + // individual workers. // - // * arn:aws:lambda:us-west-2:081040173940:function:PRE-ImageMultiClass + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-ImageMultiClassMultiLabel + // + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-ImageMultiClassMultiLabel // // * arn:aws:lambda:us-west-2:081040173940:function:PRE-ImageMultiClassMultiLabel // - // * arn:aws:lambda:us-west-2:081040173940:function:PRE-SemanticSegmentation + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-ImageMultiClassMultiLabel // - // * arn:aws:lambda:us-west-2:081040173940:function:PRE-TextMultiClass + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-ImageMultiClassMultiLabel // - // * arn:aws:lambda:us-west-2:081040173940:function:PRE-TextMultiClassMultiLabel + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-ImageMultiClassMultiLabel // - // * arn:aws:lambda:us-west-2:081040173940:function:PRE-NamedEntityRecognition + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-ImageMultiClassMultiLabel // - // * arn:aws:lambda:us-west-2:081040173940:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-ImageMultiClassMultiLabel // - // * arn:aws:lambda:us-west-2:081040173940:function:PRE-VerificationSemanticSegmentation + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-ImageMultiClassMultiLabel // - // * arn:aws:lambda:us-west-2:081040173940:function:PRE-AdjustmentBoundingBox + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-ImageMultiClassMultiLabel // - // * arn:aws:lambda:us-west-2:081040173940:function:PRE-AdjustmentSemanticSegmentation + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-ImageMultiClassMultiLabel + // + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-ImageMultiClassMultiLabel // - // Canada (Central) (ca-central-1): + // Semantic segmentation - Treats each pixel in an image as a multi-class classification + // and treats pixel annotations from workers as "votes" for the correct label. // - // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-BoundingBox + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-SemanticSegmentation // - // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-ImageMultiClass + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-SemanticSegmentation // - // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-ImageMultiClassMultiLabel + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-SemanticSegmentation // // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-SemanticSegmentation // - // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-TextMultiClass + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-SemanticSegmentation // - // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-TextMultiClassMultiLabel + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-SemanticSegmentation // - // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-NamedEntityRecognition + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-SemanticSegmentation // - // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-SemanticSegmentation // - // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-VerificationSemanticSegmentation + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-SemanticSegmentation // - // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-AdjustmentBoundingBox + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-SemanticSegmentation // - // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-AdjustmentSemanticSegmentation + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-SemanticSegmentation // - // EU (Ireland) (eu-west-1): + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-SemanticSegmentation // - // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-BoundingBox + // Text classification - Uses a variant of the Expectation Maximization approach + // to estimate the true class of text based on annotations from individual workers. // - // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-ImageMultiClass + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-TextMultiClass // - // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-ImageMultiClassMultiLabel + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-TextMultiClass // - // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-SemanticSegmentation + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-TextMultiClass + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-TextMultiClass // // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-TextMultiClass // - // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-TextMultiClassMultiLabel + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-TextMultiClass // - // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-NamedEntityRecognition + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-TextMultiClass // - // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-TextMultiClass // - // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-VerificationSemanticSegmentation + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-TextMultiClass // - // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-AdjustmentBoundingBox + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-TextMultiClass // - // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-AdjustmentSemanticSegmentation + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-TextMultiClass // - // EU (London) (eu-west-2): + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-TextMultiClass // - // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-BoundingBox + // Multi-label text classification - Uses a variant of the Expectation Maximization + // approach to estimate the true classes of text based on annotations from individual + // workers. // - // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-ImageMultiClass + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-TextMultiClassMultiLabel // - // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-ImageMultiClassMultiLabel + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-TextMultiClassMultiLabel // - // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-SemanticSegmentation + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-TextMultiClassMultiLabel // - // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-TextMultiClass + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-TextMultiClassMultiLabel + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-TextMultiClassMultiLabel // // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-TextMultiClassMultiLabel // - // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-NamedEntityRecognition + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-TextMultiClassMultiLabel // - // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-TextMultiClassMultiLabel // - // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-VerificationSemanticSegmentation + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-TextMultiClassMultiLabel // - // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-AdjustmentBoundingBox + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-TextMultiClassMultiLabel // - // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-AdjustmentSemanticSegmentation + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-TextMultiClassMultiLabel // - // EU Frankfurt (eu-central-1): + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-TextMultiClassMultiLabel // - // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-BoundingBox + // Named entity recognition - Groups similar selections and calculates aggregate + // boundaries, resolving to most-assigned label. // - // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-ImageMultiClass + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-NamedEntityRecognition // - // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-ImageMultiClassMultiLabel + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-NamedEntityRecognition // - // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-SemanticSegmentation + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-NamedEntityRecognition // - // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-TextMultiClass + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-NamedEntityRecognition // - // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-TextMultiClassMultiLabel + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-NamedEntityRecognition + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-NamedEntityRecognition // // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-NamedEntityRecognition // - // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-NamedEntityRecognition // - // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-VerificationSemanticSegmentation + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-NamedEntityRecognition // - // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-AdjustmentBoundingBox + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-NamedEntityRecognition // - // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-AdjustmentSemanticSegmentation + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-NamedEntityRecognition // - // Asia Pacific (Tokyo) (ap-northeast-1): + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-NamedEntityRecognition // - // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-BoundingBox + // Video Classification - Use this task type when you need workers to classify + // videos using predefined labels that you specify. Workers are shown videos + // and are asked to choose one label for each video. // - // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-ImageMultiClass + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-VideoMultiClass // - // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-ImageMultiClassMultiLabel + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-VideoMultiClass // - // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-SemanticSegmentation + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-VideoMultiClass // - // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-TextMultiClass + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-VideoMultiClass // - // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-TextMultiClassMultiLabel + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-VideoMultiClass // - // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-NamedEntityRecognition + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-VideoMultiClass // - // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-VideoMultiClass // - // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-VerificationSemanticSegmentation + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-VideoMultiClass // - // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-AdjustmentBoundingBox + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-VideoMultiClass // - // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-AdjustmentSemanticSegmentation + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-VideoMultiClass // - // Asia Pacific (Seoul) (ap-northeast-2): + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-VideoMultiClass // - // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-BoundingBox + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-VideoMultiClass // - // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-ImageMultiClass + // Video Frame Object Detection - Use this task type to have workers identify + // and locate objects in a sequence of video frames (images extracted from a + // video) using bounding boxes. For example, you can use this task to ask workers + // to identify and localize various objects in a series of video frames, such + // as cars, bikes, and pedestrians. // - // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-ImageMultiClassMultiLabel + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-VideoObjectDetection // - // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-SemanticSegmentation + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-VideoObjectDetection // - // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-TextMultiClass + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-VideoObjectDetection // - // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-TextMultiClassMultiLabel + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-VideoObjectDetection // - // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-NamedEntityRecognition + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-VideoObjectDetection // - // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-VideoObjectDetection // - // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-VerificationSemanticSegmentation + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-VideoObjectDetection // - // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-AdjustmentBoundingBox + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-VideoObjectDetection // - // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-AdjustmentSemanticSegmentation + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-VideoObjectDetection // - // Asia Pacific (Mumbai) (ap-south-1): + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-VideoObjectDetection // - // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-BoundingBox + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-VideoObjectDetection // - // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-ImageMultiClass + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-VideoObjectDetection // - // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-ImageMultiClassMultiLabel + // Video Frame Object Tracking - Use this task type to have workers track the + // movement of objects in a sequence of video frames (images extracted from + // a video) using bounding boxes. For example, you can use this task to ask + // workers to track the movement of objects, such as cars, bikes, and pedestrians. // - // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-SemanticSegmentation + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-VideoObjectTracking // - // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-TextMultiClass + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-VideoObjectTracking // - // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-TextMultiClassMultiLabel + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-VideoObjectTracking // - // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-NamedEntityRecognition + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-VideoObjectTracking // - // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-VideoObjectTracking // - // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-VerificationSemanticSegmentation + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-VideoObjectTracking // - // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-AdjustmentBoundingBox + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-VideoObjectTracking // - // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-AdjustmentSemanticSegmentation + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-VideoObjectTracking // - // Asia Pacific (Singapore) (ap-southeast-1): + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-VideoObjectTracking // - // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-BoundingBox + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-VideoObjectTracking // - // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-ImageMultiClass + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-VideoObjectTracking // - // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-ImageMultiClassMultiLabel + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-VideoObjectTracking // - // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-SemanticSegmentation + // 3D Point Cloud Modalities // - // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-TextMultiClass + // Use the following pre-annotation lambdas for 3D point cloud labeling modality + // tasks. See 3D Point Cloud Task types (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-point-cloud-task-types.html) + // to learn more. // - // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-TextMultiClassMultiLabel + // 3D Point Cloud Object Detection - Use this task type when you want workers + // to classify objects in a 3D point cloud by drawing 3D cuboids around objects. + // For example, you can use this task type to ask workers to identify different + // types of objects in a point cloud, such as cars, bikes, and pedestrians. // - // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-NamedEntityRecognition + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-3DPointCloudObjectDetection // - // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-3DPointCloudObjectDetection // - // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-VerificationSemanticSegmentation + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-3DPointCloudObjectDetection + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-3DPointCloudObjectDetection + // + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-3DPointCloudObjectDetection + // + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-3DPointCloudObjectDetection + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-3DPointCloudObjectDetection + // + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-3DPointCloudObjectDetection + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-3DPointCloudObjectDetection + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-3DPointCloudObjectDetection + // + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-3DPointCloudObjectDetection + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-3DPointCloudObjectDetection + // + // 3D Point Cloud Object Tracking - Use this task type when you want workers + // to draw 3D cuboids around objects that appear in a sequence of 3D point cloud + // frames. For example, you can use this task type to ask workers to track the + // movement of vehicles across multiple point cloud frames. + // + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-3DPointCloudObjectTracking + // + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-3DPointCloudObjectTracking + // + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-3DPointCloudObjectTracking + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-3DPointCloudObjectTracking + // + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-3DPointCloudObjectTracking + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-3DPointCloudObjectTracking + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-3DPointCloudObjectTracking + // + // 3D Point Cloud Semantic Segmentation - Use this task type when you want workers + // to create a point-level semantic segmentation masks by painting objects in + // a 3D point cloud using different colors where each color is assigned to one + // of the classes you specify. + // + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-3DPointCloudSemanticSegmentation + // + // Use the following ARNs for Label Verification and Adjustment Jobs + // + // Use label verification and adjustment jobs to review and adjust labels. To + // learn more, see Verify and Adjust Labels (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-verification-data.html). + // + // Bounding box verification - Uses a variant of the Expectation Maximization + // approach to estimate the true class of verification judgement for bounding + // box labels based on annotations from individual workers. + // + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-Adjustment3DPointCloudObjectTracking + // + // Bounding box adjustment - Finds the most similar boxes from different workers + // based on the Jaccard index of the adjusted annotations. + // + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-AdjustmentBoundingBox + // + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-AdjustmentBoundingBox + // + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-AdjustmentBoundingBox + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-AdjustmentBoundingBox + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-AdjustmentBoundingBox + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-AdjustmentBoundingBox + // + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-AdjustmentBoundingBox + // + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-AdjustmentBoundingBox + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-AdjustmentBoundingBox + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-AdjustmentBoundingBox // // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-AdjustmentBoundingBox // - // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-AdjustmentSemanticSegmentation + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-AdjustmentBoundingBox // - // Asia Pacific (Sydney) (ap-southeast-2): + // Semantic segmentation verification - Uses a variant of the Expectation Maximization + // approach to estimate the true class of verification judgment for semantic + // segmentation labels based on annotations from individual workers. // - // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-BoundingBox + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-VerificationSemanticSegmentation // - // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-ImageMultiClass + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-VerificationSemanticSegmentation // - // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-ImageMultiClassMultiLabel + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-VerificationSemanticSegmentation // - // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-SemanticSegmentation + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-VerificationSemanticSegmentation // - // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-TextMultiClass + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-VerificationSemanticSegmentation // - // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-TextMultiClassMultiLabel + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-VerificationSemanticSegmentation // - // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-NamedEntityRecognition + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-VerificationSemanticSegmentation // - // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-VerificationBoundingBox + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-VerificationSemanticSegmentation + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-VerificationSemanticSegmentation + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-VerificationSemanticSegmentation + // + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-VerificationSemanticSegmentation // // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-VerificationSemanticSegmentation // - // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-AdjustmentBoundingBox + // Semantic segmentation adjustment - Treats each pixel in an image as a multi-class + // classification and treats pixel adjusted annotations from workers as "votes" + // for the correct label. + // + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-AdjustmentSemanticSegmentation + // + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-AdjustmentSemanticSegmentation + // + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-AdjustmentSemanticSegmentation + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-AdjustmentSemanticSegmentation + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-AdjustmentSemanticSegmentation + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-AdjustmentSemanticSegmentation + // + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-AdjustmentSemanticSegmentation + // + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-AdjustmentSemanticSegmentation + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-AdjustmentSemanticSegmentation + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-AdjustmentSemanticSegmentation + // + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-AdjustmentSemanticSegmentation // // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-AdjustmentSemanticSegmentation // + // Video Frame Object Detection Adjustment - Use this task type when you want + // workers to adjust bounding boxes that workers have added to video frames + // to classify and localize objects in a sequence of video frames. + // + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-AdjustmentVideoObjectDetection + // + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-AdjustmentVideoObjectDetection + // + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-AdjustmentVideoObjectDetection + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-AdjustmentVideoObjectDetection + // + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-AdjustmentVideoObjectDetection + // + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-AdjustmentVideoObjectDetection + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-AdjustmentVideoObjectDetection + // + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-AdjustmentVideoObjectDetection + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-AdjustmentVideoObjectDetection + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-AdjustmentVideoObjectDetection + // + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-AdjustmentVideoObjectDetection + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-AdjustmentVideoObjectDetection + // + // Video Frame Object Tracking Adjustment - Use this task type when you want + // workers to adjust bounding boxes that workers have added to video frames + // to track object movement across a sequence of video frames. + // + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-AdjustmentVideoObjectTracking + // + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-AdjustmentVideoObjectTracking + // + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-AdjustmentVideoObjectTracking + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-AdjustmentVideoObjectTracking + // + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-AdjustmentVideoObjectTracking + // + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-AdjustmentVideoObjectTracking + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-AdjustmentVideoObjectTracking + // + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-AdjustmentVideoObjectTracking + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-AdjustmentVideoObjectTracking + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-AdjustmentVideoObjectTracking + // + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-AdjustmentVideoObjectTracking + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-AdjustmentVideoObjectTracking + // + // 3D point cloud object detection adjustment - Adjust 3D cuboids in a point + // cloud frame. + // + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-Adjustment3DPointCloudObjectDetection + // + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-Adjustment3DPointCloudObjectDetection + // + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-Adjustment3DPointCloudObjectDetection + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-Adjustment3DPointCloudObjectDetection + // + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-Adjustment3DPointCloudObjectDetection + // + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-Adjustment3DPointCloudObjectDetection + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-Adjustment3DPointCloudObjectDetection + // + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-Adjustment3DPointCloudObjectDetection + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-Adjustment3DPointCloudObjectDetection + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-Adjustment3DPointCloudObjectDetection + // + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-Adjustment3DPointCloudObjectDetection + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-Adjustment3DPointCloudObjectDetection + // + // 3D point cloud object tracking adjustment - Adjust 3D cuboids across a sequence + // of point cloud frames. + // + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-Adjustment3DPointCloudObjectTracking + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-Adjustment3DPointCloudObjectTracking + // + // 3D point cloud semantic segmentation adjustment - Adjust semantic segmentation + // masks in a 3D point cloud. + // + // * arn:aws:lambda:us-east-1:432418664414:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:us-east-2:266458841044:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:us-west-2:081040173940:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:eu-west-1:568282634449:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ap-northeast-1:477331159723:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ap-southeast-2:454466003867:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ap-south-1:565803892007:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:eu-central-1:203001061592:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ap-northeast-2:845288260483:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:eu-west-2:487402164563:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ap-southeast-1:377565633583:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // + // * arn:aws:lambda:ca-central-1:918755190332:function:PRE-Adjustment3DPointCloudSemanticSegmentation + // // PreHumanTaskLambdaArn is a required field PreHumanTaskLambdaArn *string `type:"string" required:"true"` @@ -28817,11 +30303,6 @@ func (s *HumanTaskConfig) Validate() error { invalidParams.AddNested("AnnotationConsolidationConfig", err.(request.ErrInvalidParams)) } } - if s.UiConfig != nil { - if err := s.UiConfig.Validate(); err != nil { - invalidParams.AddNested("UiConfig", err.(request.ErrInvalidParams)) - } - } if invalidParams.Len() > 0 { return invalidParams @@ -30392,7 +31873,8 @@ func (s *IntegerParameterRangeSpecification) SetMinValue(v string) *IntegerParam type JupyterServerAppSettings struct { _ struct{} `type:"structure"` - // The instance type and quantity. + // The default instance type and the Amazon Resource Name (ARN) of the SageMaker + // image created on the instance. DefaultResourceSpec *ResourceSpec `type:"structure"` } @@ -30416,7 +31898,8 @@ func (s *JupyterServerAppSettings) SetDefaultResourceSpec(v *ResourceSpec) *Jupy type KernelGatewayAppSettings struct { _ struct{} `type:"structure"` - // The instance type and quantity. + // The default instance type and the Amazon Resource Name (ARN) of the SageMaker + // image created on the instance. DefaultResourceSpec *ResourceSpec `type:"structure"` } @@ -30643,9 +32126,7 @@ type LabelingJobDataSource struct { _ struct{} `type:"structure"` // The Amazon S3 location of the input data objects. - // - // S3DataSource is a required field - S3DataSource *LabelingJobS3DataSource `type:"structure" required:"true"` + S3DataSource *LabelingJobS3DataSource `type:"structure"` } // String returns the string representation @@ -30661,9 +32142,6 @@ func (s LabelingJobDataSource) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *LabelingJobDataSource) Validate() error { invalidParams := request.ErrInvalidParams{Context: "LabelingJobDataSource"} - if s.S3DataSource == nil { - invalidParams.Add(request.NewErrParamRequired("S3DataSource")) - } if s.S3DataSource != nil { if err := s.S3DataSource.Validate(); err != nil { invalidParams.AddNested("S3DataSource", err.(request.ErrInvalidParams)) @@ -35366,6 +36844,116 @@ func (s *ListUserProfilesOutput) SetUserProfiles(v []*UserProfileDetails) *ListU return s } +type ListWorkforcesInput struct { + _ struct{} `type:"structure"` + + // The maximum number of workforces returned in the response. + MaxResults *int64 `min:"1" type:"integer"` + + // A filter you can use to search for workforces using part of the workforce + // name. + NameContains *string `min:"1" type:"string"` + + // A token to resume pagination. + NextToken *string `type:"string"` + + // Sort workforces using the workforce name or creation date. + SortBy *string `type:"string" enum:"ListWorkforcesSortByOptions"` + + // Sort workforces in ascending or descending order. + SortOrder *string `type:"string" enum:"SortOrder"` +} + +// String returns the string representation +func (s ListWorkforcesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListWorkforcesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListWorkforcesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListWorkforcesInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.NameContains != nil && len(*s.NameContains) < 1 { + invalidParams.Add(request.NewErrParamMinLen("NameContains", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *ListWorkforcesInput) SetMaxResults(v int64) *ListWorkforcesInput { + s.MaxResults = &v + return s +} + +// SetNameContains sets the NameContains field's value. +func (s *ListWorkforcesInput) SetNameContains(v string) *ListWorkforcesInput { + s.NameContains = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListWorkforcesInput) SetNextToken(v string) *ListWorkforcesInput { + s.NextToken = &v + return s +} + +// SetSortBy sets the SortBy field's value. +func (s *ListWorkforcesInput) SetSortBy(v string) *ListWorkforcesInput { + s.SortBy = &v + return s +} + +// SetSortOrder sets the SortOrder field's value. +func (s *ListWorkforcesInput) SetSortOrder(v string) *ListWorkforcesInput { + s.SortOrder = &v + return s +} + +type ListWorkforcesOutput struct { + _ struct{} `type:"structure"` + + // A token to resume pagination. + NextToken *string `type:"string"` + + // A list containing information about your workforce. + // + // Workforces is a required field + Workforces []*Workforce `type:"list" required:"true"` +} + +// String returns the string representation +func (s ListWorkforcesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListWorkforcesOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListWorkforcesOutput) SetNextToken(v string) *ListWorkforcesOutput { + s.NextToken = &v + return s +} + +// SetWorkforces sets the Workforces field's value. +func (s *ListWorkforcesOutput) SetWorkforces(v []*Workforce) *ListWorkforcesOutput { + s.Workforces = v + return s +} + type ListWorkteamsInput struct { _ struct{} `type:"structure"` @@ -35485,6 +37073,13 @@ type MemberDefinition struct { // The Amazon Cognito user group that is part of the work team. CognitoMemberDefinition *CognitoMemberDefinition `type:"structure"` + + // A list user groups that exist in your OIDC Identity Provider (IdP). One to + // ten groups can be used to create a single private work team. When you add + // a user group to the list of Groups, you can add that user group to one or + // more private work teams. If you add a user group to a private work team, + // all workers in that user group are added to the work team. + OidcMemberDefinition *OidcMemberDefinition `type:"structure"` } // String returns the string representation @@ -35505,6 +37100,11 @@ func (s *MemberDefinition) Validate() error { invalidParams.AddNested("CognitoMemberDefinition", err.(request.ErrInvalidParams)) } } + if s.OidcMemberDefinition != nil { + if err := s.OidcMemberDefinition.Validate(); err != nil { + invalidParams.AddNested("OidcMemberDefinition", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -35518,6 +37118,12 @@ func (s *MemberDefinition) SetCognitoMemberDefinition(v *CognitoMemberDefinition return s } +// SetOidcMemberDefinition sets the OidcMemberDefinition field's value. +func (s *MemberDefinition) SetOidcMemberDefinition(v *OidcMemberDefinition) *MemberDefinition { + s.OidcMemberDefinition = v + return s +} + // The name, value, and date and time of a metric that was emitted to Amazon // CloudWatch. type MetricData struct { @@ -35627,6 +37233,10 @@ func (s *MetricDefinition) SetRegex(v string) *MetricDefinition { // Provides information about the location that is configured for storing model // artifacts. +// +// Model artifacts are the output that results from training a model, and typically +// consist of trained parameters, a model defintion that desribes how to compute +// inferences, and other metadata. type ModelArtifacts struct { _ struct{} `type:"structure"` @@ -35653,6 +37263,53 @@ func (s *ModelArtifacts) SetS3ModelArtifacts(v string) *ModelArtifacts { return s } +// Configures the timeout and maximum number of retries for processing a transform +// job invocation. +type ModelClientConfig struct { + _ struct{} `type:"structure"` + + // The maximum number of retries when invocation requests are failing. + InvocationsMaxRetries *int64 `type:"integer"` + + // The timeout value in seconds for an invocation request. + InvocationsTimeoutInSeconds *int64 `min:"1" type:"integer"` +} + +// String returns the string representation +func (s ModelClientConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModelClientConfig) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ModelClientConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ModelClientConfig"} + if s.InvocationsTimeoutInSeconds != nil && *s.InvocationsTimeoutInSeconds < 1 { + invalidParams.Add(request.NewErrParamMinValue("InvocationsTimeoutInSeconds", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetInvocationsMaxRetries sets the InvocationsMaxRetries field's value. +func (s *ModelClientConfig) SetInvocationsMaxRetries(v int64) *ModelClientConfig { + s.InvocationsMaxRetries = &v + return s +} + +// SetInvocationsTimeoutInSeconds sets the InvocationsTimeoutInSeconds field's value. +func (s *ModelClientConfig) SetInvocationsTimeoutInSeconds(v int64) *ModelClientConfig { + s.InvocationsTimeoutInSeconds = &v + return s +} + // Describes the Docker container for the model package. type ModelPackageContainerDefinition struct { _ struct{} `type:"structure"` @@ -37134,6 +38791,11 @@ func (s *NestedFilters) SetNestedPropertyName(v string) *NestedFilters { type NetworkConfig struct { _ struct{} `type:"structure"` + // Whether to encrypt all communications between distributed processing jobs. + // Choose True to encrypt communications. Encryption provides greater security + // for distributed processing jobs, but the processing might take longer. + EnableInterContainerTrafficEncryption *bool `type:"boolean"` + // Whether to allow inbound and outbound network calls to and from the containers // used for the processing job. EnableNetworkIsolation *bool `type:"boolean"` @@ -37171,6 +38833,12 @@ func (s *NetworkConfig) Validate() error { return nil } +// SetEnableInterContainerTrafficEncryption sets the EnableInterContainerTrafficEncryption field's value. +func (s *NetworkConfig) SetEnableInterContainerTrafficEncryption(v bool) *NetworkConfig { + s.EnableInterContainerTrafficEncryption = &v + return s +} + // SetEnableNetworkIsolation sets the EnableNetworkIsolation field's value. func (s *NetworkConfig) SetEnableNetworkIsolation(v bool) *NetworkConfig { s.EnableNetworkIsolation = &v @@ -37491,22 +39159,349 @@ func (s *ObjectiveStatusCounters) SetSucceeded(v int64) *ObjectiveStatusCounters return s } +// Use this parameter to configure your OIDC Identity Provider (IdP). +type OidcConfig struct { + _ struct{} `type:"structure"` + + // The OIDC IdP authorization endpoint used to configure your private workforce. + // + // AuthorizationEndpoint is a required field + AuthorizationEndpoint *string `type:"string" required:"true"` + + // The OIDC IdP client ID used to configure your private workforce. + // + // ClientId is a required field + ClientId *string `min:"1" type:"string" required:"true"` + + // The OIDC IdP client secret used to configure your private workforce. + // + // ClientSecret is a required field + ClientSecret *string `min:"1" type:"string" required:"true" sensitive:"true"` + + // The OIDC IdP issuer used to configure your private workforce. + // + // Issuer is a required field + Issuer *string `type:"string" required:"true"` + + // The OIDC IdP JSON Web Key Set (Jwks) URI used to configure your private workforce. + // + // JwksUri is a required field + JwksUri *string `type:"string" required:"true"` + + // The OIDC IdP logout endpoint used to configure your private workforce. + // + // LogoutEndpoint is a required field + LogoutEndpoint *string `type:"string" required:"true"` + + // The OIDC IdP token endpoint used to configure your private workforce. + // + // TokenEndpoint is a required field + TokenEndpoint *string `type:"string" required:"true"` + + // The OIDC IdP user information endpoint used to configure your private workforce. + // + // UserInfoEndpoint is a required field + UserInfoEndpoint *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s OidcConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OidcConfig) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *OidcConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OidcConfig"} + if s.AuthorizationEndpoint == nil { + invalidParams.Add(request.NewErrParamRequired("AuthorizationEndpoint")) + } + if s.ClientId == nil { + invalidParams.Add(request.NewErrParamRequired("ClientId")) + } + if s.ClientId != nil && len(*s.ClientId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClientId", 1)) + } + if s.ClientSecret == nil { + invalidParams.Add(request.NewErrParamRequired("ClientSecret")) + } + if s.ClientSecret != nil && len(*s.ClientSecret) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ClientSecret", 1)) + } + if s.Issuer == nil { + invalidParams.Add(request.NewErrParamRequired("Issuer")) + } + if s.JwksUri == nil { + invalidParams.Add(request.NewErrParamRequired("JwksUri")) + } + if s.LogoutEndpoint == nil { + invalidParams.Add(request.NewErrParamRequired("LogoutEndpoint")) + } + if s.TokenEndpoint == nil { + invalidParams.Add(request.NewErrParamRequired("TokenEndpoint")) + } + if s.UserInfoEndpoint == nil { + invalidParams.Add(request.NewErrParamRequired("UserInfoEndpoint")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAuthorizationEndpoint sets the AuthorizationEndpoint field's value. +func (s *OidcConfig) SetAuthorizationEndpoint(v string) *OidcConfig { + s.AuthorizationEndpoint = &v + return s +} + +// SetClientId sets the ClientId field's value. +func (s *OidcConfig) SetClientId(v string) *OidcConfig { + s.ClientId = &v + return s +} + +// SetClientSecret sets the ClientSecret field's value. +func (s *OidcConfig) SetClientSecret(v string) *OidcConfig { + s.ClientSecret = &v + return s +} + +// SetIssuer sets the Issuer field's value. +func (s *OidcConfig) SetIssuer(v string) *OidcConfig { + s.Issuer = &v + return s +} + +// SetJwksUri sets the JwksUri field's value. +func (s *OidcConfig) SetJwksUri(v string) *OidcConfig { + s.JwksUri = &v + return s +} + +// SetLogoutEndpoint sets the LogoutEndpoint field's value. +func (s *OidcConfig) SetLogoutEndpoint(v string) *OidcConfig { + s.LogoutEndpoint = &v + return s +} + +// SetTokenEndpoint sets the TokenEndpoint field's value. +func (s *OidcConfig) SetTokenEndpoint(v string) *OidcConfig { + s.TokenEndpoint = &v + return s +} + +// SetUserInfoEndpoint sets the UserInfoEndpoint field's value. +func (s *OidcConfig) SetUserInfoEndpoint(v string) *OidcConfig { + s.UserInfoEndpoint = &v + return s +} + +// Your Amazon Cognito workforce configuration. +type OidcConfigForResponse struct { + _ struct{} `type:"structure"` + + // The OIDC IdP authorization endpoint used to configure your private workforce. + AuthorizationEndpoint *string `type:"string"` + + // The OIDC IdP client ID used to configure your private workforce. + ClientId *string `min:"1" type:"string"` + + // The OIDC IdP issuer used to configure your private workforce. + Issuer *string `type:"string"` + + // The OIDC IdP JSON Web Key Set (Jwks) URI used to configure your private workforce. + JwksUri *string `type:"string"` + + // The OIDC IdP logout endpoint used to configure your private workforce. + LogoutEndpoint *string `type:"string"` + + // The OIDC IdP token endpoint used to configure your private workforce. + TokenEndpoint *string `type:"string"` + + // The OIDC IdP user information endpoint used to configure your private workforce. + UserInfoEndpoint *string `type:"string"` +} + +// String returns the string representation +func (s OidcConfigForResponse) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OidcConfigForResponse) GoString() string { + return s.String() +} + +// SetAuthorizationEndpoint sets the AuthorizationEndpoint field's value. +func (s *OidcConfigForResponse) SetAuthorizationEndpoint(v string) *OidcConfigForResponse { + s.AuthorizationEndpoint = &v + return s +} + +// SetClientId sets the ClientId field's value. +func (s *OidcConfigForResponse) SetClientId(v string) *OidcConfigForResponse { + s.ClientId = &v + return s +} + +// SetIssuer sets the Issuer field's value. +func (s *OidcConfigForResponse) SetIssuer(v string) *OidcConfigForResponse { + s.Issuer = &v + return s +} + +// SetJwksUri sets the JwksUri field's value. +func (s *OidcConfigForResponse) SetJwksUri(v string) *OidcConfigForResponse { + s.JwksUri = &v + return s +} + +// SetLogoutEndpoint sets the LogoutEndpoint field's value. +func (s *OidcConfigForResponse) SetLogoutEndpoint(v string) *OidcConfigForResponse { + s.LogoutEndpoint = &v + return s +} + +// SetTokenEndpoint sets the TokenEndpoint field's value. +func (s *OidcConfigForResponse) SetTokenEndpoint(v string) *OidcConfigForResponse { + s.TokenEndpoint = &v + return s +} + +// SetUserInfoEndpoint sets the UserInfoEndpoint field's value. +func (s *OidcConfigForResponse) SetUserInfoEndpoint(v string) *OidcConfigForResponse { + s.UserInfoEndpoint = &v + return s +} + +// A list user groups that exist in your OIDC Identity Provider (IdP). One to +// ten groups can be used to create a single private work team. When you add +// a user group to the list of Groups, you can add that user group to one or +// more private work teams. If you add a user group to a private work team, +// all workers in that user group are added to the work team. +type OidcMemberDefinition struct { + _ struct{} `type:"structure"` + + // A list of comma seperated strings that identifies user groups in your OIDC + // IdP. Each user group is made up of a group of private workers. + // + // Groups is a required field + Groups []*string `min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s OidcMemberDefinition) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s OidcMemberDefinition) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *OidcMemberDefinition) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "OidcMemberDefinition"} + if s.Groups == nil { + invalidParams.Add(request.NewErrParamRequired("Groups")) + } + if s.Groups != nil && len(s.Groups) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Groups", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetGroups sets the Groups field's value. +func (s *OidcMemberDefinition) SetGroups(v []*string) *OidcMemberDefinition { + s.Groups = v + return s +} + // Contains information about the output location for the compiled model and -// the device (target) that the model runs on. +// the target device that the model runs on. TargetDevice and TargetPlatform +// are mutually exclusive, so you need to choose one between the two to specify +// your target device or platform. If you cannot find your device you want to +// use from the TargetDevice list, use TargetPlatform to describe the platform +// of your edge device and CompilerOptions if there are specific settings that +// are required or recommended to use for particular TargetPlatform. type OutputConfig struct { _ struct{} `type:"structure"` - // Identifies the S3 path where you want Amazon SageMaker to store the model + // Specifies additional parameters for compiler options in JSON format. The + // compiler options are TargetPlatform specific. It is required for NVIDIA accelerators + // and highly recommended for CPU compliations. For any other cases, it is optional + // to specify CompilerOptions. + // + // * CPU: Compilation for CPU supports the following compiler options. mcpu: + // CPU micro-architecture. For example, {'mcpu': 'skylake-avx512'} mattr: + // CPU flags. For example, {'mattr': ['+neon', '+vfpv4']} + // + // * ARM: Details of ARM CPU compilations. NEON: NEON is an implementation + // of the Advanced SIMD extension used in ARMv7 processors. For example, + // add {'mattr': ['+neon']} to the compiler options if compiling for ARM + // 32-bit platform with the NEON support. + // + // * NVIDIA: Compilation for NVIDIA GPU supports the following compiler options. + // gpu_code: Specifies the targeted architecture. trt-ver: Specifies the + // TensorRT versions in x.y.z. format. cuda-ver: Specifies the CUDA version + // in x.y format. For example, {'gpu-code': 'sm_72', 'trt-ver': '6.0.1', + // 'cuda-ver': '10.1'} + // + // * ANDROID: Compilation for the Android OS supports the following compiler + // options: ANDROID_PLATFORM: Specifies the Android API levels. Available + // levels range from 21 to 29. For example, {'ANDROID_PLATFORM': 28}. mattr: + // Add {'mattr': ['+neon']} to compiler options if compiling for ARM 32-bit + // platform with NEON support. + CompilerOptions *string `min:"7" type:"string"` + + // Identifies the S3 bucket where you want Amazon SageMaker to store the model // artifacts. For example, s3://bucket-name/key-name-prefix. // // S3OutputLocation is a required field S3OutputLocation *string `type:"string" required:"true"` - // Identifies the device that you want to run your model on after it has been - // compiled. For example: ml_c5. + // Identifies the target device or the machine learning instance that you want + // to run your model on after the compilation has completed. Alternatively, + // you can specify OS, architecture, and accelerator using TargetPlatform fields. + // It can be used instead of TargetPlatform. + TargetDevice *string `type:"string" enum:"TargetDevice"` + + // Contains information about a target platform that you want your model to + // run on, such as OS, architecture, and accelerators. It is an alternative + // of TargetDevice. // - // TargetDevice is a required field - TargetDevice *string `type:"string" required:"true" enum:"TargetDevice"` + // The following examples show how to configure the TargetPlatform and CompilerOptions + // JSON strings for popular target platforms: + // + // * Raspberry Pi 3 Model B+ "TargetPlatform": {"Os": "LINUX", "Arch": "ARM_EABIHF"}, + // "CompilerOptions": {'mattr': ['+neon']} + // + // * Jetson TX2 "TargetPlatform": {"Os": "LINUX", "Arch": "ARM64", "Accelerator": + // "NVIDIA"}, "CompilerOptions": {'gpu-code': 'sm_62', 'trt-ver': '6.0.1', + // 'cuda-ver': '10.0'} + // + // * EC2 m5.2xlarge instance OS "TargetPlatform": {"Os": "LINUX", "Arch": + // "X86_64", "Accelerator": "NVIDIA"}, "CompilerOptions": {'mcpu': 'skylake-avx512'} + // + // * RK3399 "TargetPlatform": {"Os": "LINUX", "Arch": "ARM64", "Accelerator": + // "MALI"} + // + // * ARMv7 phone (CPU) "TargetPlatform": {"Os": "ANDROID", "Arch": "ARM_EABI"}, + // "CompilerOptions": {'ANDROID_PLATFORM': 25, 'mattr': ['+neon']} + // + // * ARMv8 phone (CPU) "TargetPlatform": {"Os": "ANDROID", "Arch": "ARM64"}, + // "CompilerOptions": {'ANDROID_PLATFORM': 29} + TargetPlatform *TargetPlatform `type:"structure"` } // String returns the string representation @@ -37522,11 +39517,16 @@ func (s OutputConfig) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *OutputConfig) Validate() error { invalidParams := request.ErrInvalidParams{Context: "OutputConfig"} + if s.CompilerOptions != nil && len(*s.CompilerOptions) < 7 { + invalidParams.Add(request.NewErrParamMinLen("CompilerOptions", 7)) + } if s.S3OutputLocation == nil { invalidParams.Add(request.NewErrParamRequired("S3OutputLocation")) } - if s.TargetDevice == nil { - invalidParams.Add(request.NewErrParamRequired("TargetDevice")) + if s.TargetPlatform != nil { + if err := s.TargetPlatform.Validate(); err != nil { + invalidParams.AddNested("TargetPlatform", err.(request.ErrInvalidParams)) + } } if invalidParams.Len() > 0 { @@ -37535,6 +39535,12 @@ func (s *OutputConfig) Validate() error { return nil } +// SetCompilerOptions sets the CompilerOptions field's value. +func (s *OutputConfig) SetCompilerOptions(v string) *OutputConfig { + s.CompilerOptions = &v + return s +} + // SetS3OutputLocation sets the S3OutputLocation field's value. func (s *OutputConfig) SetS3OutputLocation(v string) *OutputConfig { s.S3OutputLocation = &v @@ -37547,6 +39553,12 @@ func (s *OutputConfig) SetTargetDevice(v string) *OutputConfig { return s } +// SetTargetPlatform sets the TargetPlatform field's value. +func (s *OutputConfig) SetTargetPlatform(v *TargetPlatform) *OutputConfig { + s.TargetPlatform = v + return s +} + // Provides information about how to store model training results (model artifacts). type OutputDataConfig struct { _ struct{} `type:"structure"` @@ -38026,7 +40038,14 @@ type ProcessingJob struct { // container when the processing job exits. ExitMessage *string `type:"string"` - // Configuration for the experiment. + // Associates a SageMaker job as a trial component with an experiment and trial. + // Specified when you call the following APIs: + // + // * CreateProcessingJob + // + // * CreateTrainingJob + // + // * CreateTransformJob ExperimentConfig *ExperimentConfig `type:"structure"` // A string, up to one KB in size, that contains the reason a processing job @@ -39204,6 +41223,12 @@ func (s *PublicWorkforceTaskPrice) SetAmountInUsd(v *USD) *PublicWorkforceTaskPr type RenderUiTemplateInput struct { _ struct{} `type:"structure"` + // The HumanTaskUiArn of the worker UI that you want to render. Do not provide + // a HumanTaskUiArn if you use the UiTemplate parameter. + // + // See a list of available Human Ui Amazon Resource Names (ARNs) in UiConfig. + HumanTaskUiArn *string `type:"string"` + // The Amazon Resource Name (ARN) that has access to the S3 objects that are // used by the template. // @@ -39216,9 +41241,7 @@ type RenderUiTemplateInput struct { Task *RenderableTask `type:"structure" required:"true"` // A Template object containing the worker UI template to render. - // - // UiTemplate is a required field - UiTemplate *UiTemplate `type:"structure" required:"true"` + UiTemplate *UiTemplate `type:"structure"` } // String returns the string representation @@ -39243,9 +41266,6 @@ func (s *RenderUiTemplateInput) Validate() error { if s.Task == nil { invalidParams.Add(request.NewErrParamRequired("Task")) } - if s.UiTemplate == nil { - invalidParams.Add(request.NewErrParamRequired("UiTemplate")) - } if s.Task != nil { if err := s.Task.Validate(); err != nil { invalidParams.AddNested("Task", err.(request.ErrInvalidParams)) @@ -39263,6 +41283,12 @@ func (s *RenderUiTemplateInput) Validate() error { return nil } +// SetHumanTaskUiArn sets the HumanTaskUiArn field's value. +func (s *RenderUiTemplateInput) SetHumanTaskUiArn(v string) *RenderUiTemplateInput { + s.HumanTaskUiArn = &v + return s +} + // SetRoleArn sets the RoleArn field's value. func (s *RenderUiTemplateInput) SetRoleArn(v string) *RenderUiTemplateInput { s.RoleArn = &v @@ -39795,8 +41821,8 @@ func (s *ResourceNotFound) RequestID() string { return s.RespMetadata.RequestID } -// The instance type and the Amazon Resource Name (ARN) of the image created -// on the instance. The ARN is stored as metadata in Amazon SageMaker Studio +// The instance type and the Amazon Resource Name (ARN) of the SageMaker image +// created on the instance. The ARN is stored as metadata in SageMaker Studio // notebooks. type ResourceSpec struct { _ struct{} `type:"structure"` @@ -39804,7 +41830,7 @@ type ResourceSpec struct { // The instance type. InstanceType *string `type:"string" enum:"AppInstanceType"` - // The Amazon Resource Name (ARN) of the image created on the instance. + // The Amazon Resource Name (ARN) of the SageMaker image created on the instance. SageMakerImageArn *string `type:"string"` } @@ -39830,11 +41856,15 @@ func (s *ResourceSpec) SetSageMakerImageArn(v string) *ResourceSpec { return s } -// The retention policy. +// The retention policy for data stored on an Amazon Elastic File System (EFS) +// volume. type RetentionPolicy struct { _ struct{} `type:"structure"` - // The home Amazon Elastic File System (EFS). + // The default is Retain, which specifies to keep the data stored on the EFS + // volume. + // + // Specify Delete to delete the data stored on the EFS volume. HomeEfsFileSystem *string `type:"string" enum:"RetentionType"` } @@ -39900,18 +41930,22 @@ type S3DataSource struct { // Depending on the value specified for the S3DataType, identifies either a // key name prefix or a manifest. For example: // - // * A key name prefix might look like this: s3://bucketname/exampleprefix. + // * A key name prefix might look like this: s3://bucketname/exampleprefix // - // * A manifest might look like this: s3://bucketname/example.manifest The - // manifest is an S3 object which is a JSON file with the following format: - // The preceding JSON matches the following s3Uris: [ {"prefix": "s3://customer_bucket/some/prefix/"}, + // * A manifest might look like this: s3://bucketname/example.manifest A + // manifest is an S3 object which is a JSON file consisting of an array of + // elements. The first element is a prefix which is followed by one or more + // suffixes. SageMaker appends the suffix elements to the prefix to get a + // full set of S3Uri. Note that the prefix must be a valid non-empty S3Uri + // that precludes users from specifying a manifest whose individual S3Uri + // is sourced from different S3 buckets. The following code example shows + // a valid manifest format: [ {"prefix": "s3://customer_bucket/some/prefix/"}, // "relative/path/to/custdata-1", "relative/path/custdata-2", ... "relative/path/custdata-N" - // ] The preceding JSON matches the following s3Uris: s3://customer_bucket/some/prefix/relative/path/to/custdata-1 + // ] This JSON is equivalent to the following S3Uri list: s3://customer_bucket/some/prefix/relative/path/to/custdata-1 // s3://customer_bucket/some/prefix/relative/path/custdata-2 ... s3://customer_bucket/some/prefix/relative/path/custdata-N - // The complete set of s3uris in this manifest is the input data for the - // channel for this datasource. The object that each s3uris points to must - // be readable by the IAM role that Amazon SageMaker uses to perform tasks - // on your behalf. + // The complete set of S3Uri in this manifest is the input data for the channel + // for this data source. The object that each S3Uri points to must be readable + // by the IAM role that Amazon SageMaker uses to perform tasks on your behalf. // // S3Uri is a required field S3Uri *string `type:"string" required:"true"` @@ -40047,8 +42081,7 @@ func (s *ScheduleConfig) SetScheduleExpression(v string) *ScheduleConfig { // A SearchExpression contains the following components: // // * A list of Filter objects. Each filter defines a simple Boolean expression -// comprised of a resource property name, Boolean operator, and value. A -// SearchExpression can include only one Contains operator. +// comprised of a resource property name, Boolean operator, and value. // // * A list of NestedFilter objects. Each nested filter defines a list of // Boolean expressions using a list of resource properties. A nested filter @@ -40490,17 +42523,25 @@ func (s *SecondaryStatusTransition) SetStatusMessage(v string) *SecondaryStatusT return s } -// The sharing settings. +// Specifies options when sharing an Amazon SageMaker Studio notebook. These +// settings are specified as part of DefaultUserSettings when the CreateDomain +// API is called, and as part of UserSettings when the CreateUserProfile API +// is called. type SharingSettings struct { _ struct{} `type:"structure"` - // The notebook output option. + // Whether to include the notebook cell output when sharing the notebook. The + // default is Disabled. NotebookOutputOption *string `type:"string" enum:"NotebookOutputOption"` - // The AWS Key Management Service encryption key ID. + // When NotebookOutputOption is Allowed, the AWS Key Management Service (KMS) + // encryption key ID used to encrypt the notebook cell output in the Amazon + // S3 bucket. S3KmsKeyId *string `type:"string"` - // The Amazon S3 output path. + // When NotebookOutputOption is Allowed, the Amazon S3 bucket used to save the + // notebook cell output. If S3OutputPath isn't specified, a default bucket is + // used. S3OutputPath *string `type:"string"` } @@ -40699,10 +42740,10 @@ func (s *SourceAlgorithmSpecification) SetSourceAlgorithms(v []*SourceAlgorithm) type SourceIpConfig struct { _ struct{} `type:"structure"` - // A list of one to four Classless Inter-Domain Routing (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) + // A list of one to ten Classless Inter-Domain Routing (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html) // (CIDR) values. // - // Maximum: Four CIDR values + // Maximum: Ten CIDR values // // The following Length Constraints apply to individual CIDR values in the CIDR // value list. @@ -41416,6 +43457,7 @@ func (s *StoppingCondition) SetMaxWaitTimeInSeconds(v int64) *StoppingCondition type SubscribedWorkteam struct { _ struct{} `type:"structure"` + // Marketplace product listing ID. ListingId *string `type:"string"` // The description of the vendor from the Amazon Marketplace. @@ -41570,11 +43612,99 @@ func (s *Tag) SetValue(v string) *Tag { return s } +// Contains information about a target platform that you want your model to +// run on, such as OS, architecture, and accelerators. It is an alternative +// of TargetDevice. +type TargetPlatform struct { + _ struct{} `type:"structure"` + + // Specifies a target platform accelerator (optional). + // + // * NVIDIA: Nvidia graphics processing unit. It also requires gpu-code, + // trt-ver, cuda-ver compiler options + // + // * MALI: ARM Mali graphics processor + // + // * INTEL_GRAPHICS: Integrated Intel graphics + Accelerator *string `type:"string" enum:"TargetPlatformAccelerator"` + + // Specifies a target platform architecture. + // + // * X86_64: 64-bit version of the x86 instruction set. + // + // * X86: 32-bit version of the x86 instruction set. + // + // * ARM64: ARMv8 64-bit CPU. + // + // * ARM_EABIHF: ARMv7 32-bit, Hard Float. + // + // * ARM_EABI: ARMv7 32-bit, Soft Float. Used by Android 32-bit ARM platform. + // + // Arch is a required field + Arch *string `type:"string" required:"true" enum:"TargetPlatformArch"` + + // Specifies a target platform OS. + // + // * LINUX: Linux-based operating systems. + // + // * ANDROID: Android operating systems. Android API level can be specified + // using the ANDROID_PLATFORM compiler option. For example, "CompilerOptions": + // {'ANDROID_PLATFORM': 28} + // + // Os is a required field + Os *string `type:"string" required:"true" enum:"TargetPlatformOs"` +} + +// String returns the string representation +func (s TargetPlatform) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TargetPlatform) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TargetPlatform) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TargetPlatform"} + if s.Arch == nil { + invalidParams.Add(request.NewErrParamRequired("Arch")) + } + if s.Os == nil { + invalidParams.Add(request.NewErrParamRequired("Os")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAccelerator sets the Accelerator field's value. +func (s *TargetPlatform) SetAccelerator(v string) *TargetPlatform { + s.Accelerator = &v + return s +} + +// SetArch sets the Arch field's value. +func (s *TargetPlatform) SetArch(v string) *TargetPlatform { + s.Arch = &v + return s +} + +// SetOs sets the Os field's value. +func (s *TargetPlatform) SetOs(v string) *TargetPlatform { + s.Os = &v + return s +} + // The TensorBoard app settings. type TensorBoardAppSettings struct { _ struct{} `type:"structure"` - // The instance type and quantity. + // The default instance type and the Amazon Resource Name (ARN) of the SageMaker + // image created on the instance. DefaultResourceSpec *ResourceSpec `type:"structure"` } @@ -41689,7 +43819,14 @@ type TrainingJob struct { // VPC they run in. EnableNetworkIsolation *bool `type:"boolean"` - // Configuration for the experiment. + // Associates a SageMaker job as a trial component with an experiment and trial. + // Specified when you call the following APIs: + // + // * CreateProcessingJob + // + // * CreateTrainingJob + // + // * CreateTransformJob ExperimentConfig *ExperimentConfig `type:"structure"` // If the training job failed, the reason it failed. @@ -42670,6 +44807,261 @@ func (s *TransformInput) SetSplitType(v string) *TransformInput { return s } +// A batch transform job. For information about SageMaker batch transform, see +// Use Batch Transform (https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform.html). +type TransformJob struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the AutoML job that created the transform + // job. + AutoMLJobArn *string `min:"1" type:"string"` + + // Specifies the number of records to include in a mini-batch for an HTTP inference + // request. A record is a single unit of input data that inference can be made + // on. For example, a single line in a CSV file is a record. + BatchStrategy *string `type:"string" enum:"BatchStrategy"` + + // A timestamp that shows when the transform Job was created. + CreationTime *time.Time `type:"timestamp"` + + // The data structure used to specify the data to be used for inference in a + // batch transform job and to associate the data that is relevant to the prediction + // results in the output. The input filter provided allows you to exclude input + // data that is not needed for inference in a batch transform job. The output + // filter provided allows you to include input data relevant to interpreting + // the predictions in the output from the job. For more information, see Associate + // Prediction Results with their Corresponding Input Records (https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform-data-processing.html). + DataProcessing *DataProcessing `type:"structure"` + + // The environment variables to set in the Docker container. We support up to + // 16 key and values entries in the map. + Environment map[string]*string `type:"map"` + + // Associates a SageMaker job as a trial component with an experiment and trial. + // Specified when you call the following APIs: + // + // * CreateProcessingJob + // + // * CreateTrainingJob + // + // * CreateTransformJob + ExperimentConfig *ExperimentConfig `type:"structure"` + + // If the transform job failed, the reason it failed. + FailureReason *string `type:"string"` + + // The Amazon Resource Name (ARN) of the labeling job that created the transform + // job. + LabelingJobArn *string `type:"string"` + + // The maximum number of parallel requests that can be sent to each instance + // in a transform job. If MaxConcurrentTransforms is set to 0 or left unset, + // SageMaker checks the optional execution-parameters to determine the settings + // for your chosen algorithm. If the execution-parameters endpoint is not enabled, + // the default value is 1. For built-in algorithms, you don't need to set a + // value for MaxConcurrentTransforms. + MaxConcurrentTransforms *int64 `type:"integer"` + + // The maximum allowed size of the payload, in MB. A payload is the data portion + // of a record (without metadata). The value in MaxPayloadInMB must be greater + // than, or equal to, the size of a single record. To estimate the size of a + // record in MB, divide the size of your dataset by the number of records. To + // ensure that the records fit within the maximum payload size, we recommend + // using a slightly larger value. The default value is 6 MB. For cases where + // the payload might be arbitrarily large and is transmitted using HTTP chunked + // encoding, set the value to 0. This feature works only in supported algorithms. + // Currently, SageMaker built-in algorithms do not support HTTP chunked encoding. + MaxPayloadInMB *int64 `type:"integer"` + + // Configures the timeout and maximum number of retries for processing a transform + // job invocation. + ModelClientConfig *ModelClientConfig `type:"structure"` + + // The name of the model associated with the transform job. + ModelName *string `type:"string"` + + // A list of tags associated with the transform job. + Tags []*Tag `type:"list"` + + // Indicates when the transform job has been completed, or has stopped or failed. + // You are billed for the time interval between this time and the value of TransformStartTime. + TransformEndTime *time.Time `type:"timestamp"` + + // Describes the input source of a transform job and the way the transform job + // consumes it. + TransformInput *TransformInput `type:"structure"` + + // The Amazon Resource Name (ARN) of the transform job. + TransformJobArn *string `type:"string"` + + // The name of the transform job. + TransformJobName *string `min:"1" type:"string"` + + // The status of the transform job. + // + // Transform job statuses are: + // + // * InProgress - The job is in progress. + // + // * Completed - The job has completed. + // + // * Failed - The transform job has failed. To see the reason for the failure, + // see the FailureReason field in the response to a DescribeTransformJob + // call. + // + // * Stopping - The transform job is stopping. + // + // * Stopped - The transform job has stopped. + TransformJobStatus *string `type:"string" enum:"TransformJobStatus"` + + // Describes the results of a transform job. + TransformOutput *TransformOutput `type:"structure"` + + // Describes the resources, including ML instance types and ML instance count, + // to use for transform job. + TransformResources *TransformResources `type:"structure"` + + // Indicates when the transform job starts on ML instances. You are billed for + // the time interval between this time and the value of TransformEndTime. + TransformStartTime *time.Time `type:"timestamp"` +} + +// String returns the string representation +func (s TransformJob) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TransformJob) GoString() string { + return s.String() +} + +// SetAutoMLJobArn sets the AutoMLJobArn field's value. +func (s *TransformJob) SetAutoMLJobArn(v string) *TransformJob { + s.AutoMLJobArn = &v + return s +} + +// SetBatchStrategy sets the BatchStrategy field's value. +func (s *TransformJob) SetBatchStrategy(v string) *TransformJob { + s.BatchStrategy = &v + return s +} + +// SetCreationTime sets the CreationTime field's value. +func (s *TransformJob) SetCreationTime(v time.Time) *TransformJob { + s.CreationTime = &v + return s +} + +// SetDataProcessing sets the DataProcessing field's value. +func (s *TransformJob) SetDataProcessing(v *DataProcessing) *TransformJob { + s.DataProcessing = v + return s +} + +// SetEnvironment sets the Environment field's value. +func (s *TransformJob) SetEnvironment(v map[string]*string) *TransformJob { + s.Environment = v + return s +} + +// SetExperimentConfig sets the ExperimentConfig field's value. +func (s *TransformJob) SetExperimentConfig(v *ExperimentConfig) *TransformJob { + s.ExperimentConfig = v + return s +} + +// SetFailureReason sets the FailureReason field's value. +func (s *TransformJob) SetFailureReason(v string) *TransformJob { + s.FailureReason = &v + return s +} + +// SetLabelingJobArn sets the LabelingJobArn field's value. +func (s *TransformJob) SetLabelingJobArn(v string) *TransformJob { + s.LabelingJobArn = &v + return s +} + +// SetMaxConcurrentTransforms sets the MaxConcurrentTransforms field's value. +func (s *TransformJob) SetMaxConcurrentTransforms(v int64) *TransformJob { + s.MaxConcurrentTransforms = &v + return s +} + +// SetMaxPayloadInMB sets the MaxPayloadInMB field's value. +func (s *TransformJob) SetMaxPayloadInMB(v int64) *TransformJob { + s.MaxPayloadInMB = &v + return s +} + +// SetModelClientConfig sets the ModelClientConfig field's value. +func (s *TransformJob) SetModelClientConfig(v *ModelClientConfig) *TransformJob { + s.ModelClientConfig = v + return s +} + +// SetModelName sets the ModelName field's value. +func (s *TransformJob) SetModelName(v string) *TransformJob { + s.ModelName = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *TransformJob) SetTags(v []*Tag) *TransformJob { + s.Tags = v + return s +} + +// SetTransformEndTime sets the TransformEndTime field's value. +func (s *TransformJob) SetTransformEndTime(v time.Time) *TransformJob { + s.TransformEndTime = &v + return s +} + +// SetTransformInput sets the TransformInput field's value. +func (s *TransformJob) SetTransformInput(v *TransformInput) *TransformJob { + s.TransformInput = v + return s +} + +// SetTransformJobArn sets the TransformJobArn field's value. +func (s *TransformJob) SetTransformJobArn(v string) *TransformJob { + s.TransformJobArn = &v + return s +} + +// SetTransformJobName sets the TransformJobName field's value. +func (s *TransformJob) SetTransformJobName(v string) *TransformJob { + s.TransformJobName = &v + return s +} + +// SetTransformJobStatus sets the TransformJobStatus field's value. +func (s *TransformJob) SetTransformJobStatus(v string) *TransformJob { + s.TransformJobStatus = &v + return s +} + +// SetTransformOutput sets the TransformOutput field's value. +func (s *TransformJob) SetTransformOutput(v *TransformOutput) *TransformJob { + s.TransformOutput = v + return s +} + +// SetTransformResources sets the TransformResources field's value. +func (s *TransformJob) SetTransformResources(v *TransformResources) *TransformJob { + s.TransformResources = v + return s +} + +// SetTransformStartTime sets the TransformStartTime field's value. +func (s *TransformJob) SetTransformStartTime(v time.Time) *TransformJob { + s.TransformStartTime = &v + return s +} + // Defines the input needed to run a transform job using the inference specification // specified in the algorithm. type TransformJobDefinition struct { @@ -43098,7 +45490,7 @@ type TransformS3DataSource struct { // manifest is an S3 object which is a JSON file with the following format: // [ {"prefix": "s3://customer_bucket/some/prefix/"}, "relative/path/to/custdata-1", // "relative/path/custdata-2", ... "relative/path/custdata-N" ] The preceding - // JSON matches the following s3Uris: s3://customer_bucket/some/prefix/relative/path/to/custdata-1 + // JSON matches the following S3Uris: s3://customer_bucket/some/prefix/relative/path/to/custdata-1 // s3://customer_bucket/some/prefix/relative/path/custdata-2 ... s3://customer_bucket/some/prefix/relative/path/custdata-N // The complete set of S3Uris in this manifest constitutes the input data // for the channel for this datasource. The object that each S3Uris points @@ -43749,6 +46141,9 @@ type TrialComponentSourceDetail struct { // Information about a training job that's the source of a trial component. TrainingJob *TrainingJob `type:"structure"` + + // Information about a transform job that's the source of the trial component. + TransformJob *TransformJob `type:"structure"` } // String returns the string representation @@ -43779,6 +46174,12 @@ func (s *TrialComponentSourceDetail) SetTrainingJob(v *TrainingJob) *TrialCompon return s } +// SetTransformJob sets the TransformJob field's value. +func (s *TrialComponentSourceDetail) SetTransformJob(v *TransformJob) *TrialComponentSourceDetail { + s.TransformJob = v + return s +} + // The status of the trial component. type TrialComponentStatus struct { _ struct{} `type:"structure"` @@ -44125,12 +46526,50 @@ func (s *USD) SetTenthFractionsOfACent(v int64) *USD { type UiConfig struct { _ struct{} `type:"structure"` - // The Amazon S3 bucket location of the UI template. For more information about - // the contents of a UI template, see Creating Your Custom Labeling Task Template - // (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-custom-templates-step2.html). + // The ARN of the worker task template used to render the worker UI and tools + // for labeling job tasks. + // + // Use this parameter when you are creating a labeling job for 3D point cloud + // and video fram labeling jobs. Use your labeling job task type to select one + // of the following ARN's and use it with this parameter when you create a labeling + // job. Replace aws-region with the AWS region you are creating your labeling + // job in. + // + // 3D Point Cloud HumanTaskUiArns + // + // Use this HumanTaskUiArn for 3D point cloud object detection and 3D point + // cloud object detection adjustment labeling jobs. + // + // * arn:aws:sagemaker:aws-region:394669845002:human-task-ui/PointCloudObjectDetection + // + // Use this HumanTaskUiArn for 3D point cloud object tracking and 3D point cloud + // object tracking adjustment labeling jobs. + // + // * arn:aws:sagemaker:aws-region:394669845002:human-task-ui/PointCloudObjectTracking + // + // Use this HumanTaskUiArn for 3D point cloud semantic segmentation and 3D point + // cloud semantic segmentation adjustment labeling jobs. + // + // * arn:aws:sagemaker:aws-region:394669845002:human-task-ui/PointCloudSemanticSegmentation + // + // Video Frame HumanTaskUiArns // - // UiTemplateS3Uri is a required field - UiTemplateS3Uri *string `type:"string" required:"true"` + // Use this HumanTaskUiArn for video frame object detection and video frame + // object detection adjustment labeling jobs. + // + // * arn:aws:sagemaker:region:394669845002:human-task-ui/VideoObjectDetection + // + // Use this HumanTaskUiArn for video frame object tracking and video frame object + // tracking adjustment labeling jobs. + // + // * arn:aws:sagemaker:aws-region:394669845002:human-task-ui/VideoObjectTracking + HumanTaskUiArn *string `type:"string"` + + // The Amazon S3 bucket location of the UI template, or worker task template. + // This is the template used to render the worker UI and tools for labeling + // job tasks. For more information about the contents of a UI template, see + // Creating Your Custom Labeling Task Template (https://docs.aws.amazon.com/sagemaker/latest/dg/sms-custom-templates-step2.html). + UiTemplateS3Uri *string `type:"string"` } // String returns the string representation @@ -44143,17 +46582,10 @@ func (s UiConfig) GoString() string { return s.String() } -// Validate inspects the fields of the type to determine if they are valid. -func (s *UiConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UiConfig"} - if s.UiTemplateS3Uri == nil { - invalidParams.Add(request.NewErrParamRequired("UiTemplateS3Uri")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil +// SetHumanTaskUiArn sets the HumanTaskUiArn field's value. +func (s *UiConfig) SetHumanTaskUiArn(v string) *UiConfig { + s.HumanTaskUiArn = &v + return s } // SetUiTemplateS3Uri sets the UiTemplateS3Uri field's value. @@ -44328,7 +46760,7 @@ type UpdateDomainInput struct { // A collection of settings. DefaultUserSettings *UserSettings `type:"structure"` - // The domain ID. + // The ID of the domain to be updated. // // DomainId is a required field DomainId *string `type:"string" required:"true"` @@ -44377,7 +46809,7 @@ func (s *UpdateDomainInput) SetDomainId(v string) *UpdateDomainInput { type UpdateDomainOutput struct { _ struct{} `type:"structure"` - // The domain Amazon Resource Name (ARN). + // The Amazon Resource Name (ARN) of the domain. DomainArn *string `type:"string"` } @@ -45426,10 +47858,14 @@ func (s *UpdateUserProfileOutput) SetUserProfileArn(v string) *UpdateUserProfile type UpdateWorkforceInput struct { _ struct{} `type:"structure"` - // A list of one to four worker IP address ranges (CIDRs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html)) + // Use this parameter to update your OIDC Identity Provider (IdP) configuration + // for a workforce made using your own IdP. + OidcConfig *OidcConfig `type:"structure"` + + // A list of one to ten worker IP address ranges (CIDRs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html)) // that can be used to access tasks assigned to this workforce. // - // Maximum: Four CIDR values + // Maximum: Ten CIDR values SourceIpConfig *SourceIpConfig `type:"structure"` // The name of the private workforce whose access you want to restrict. WorkforceName @@ -45459,6 +47895,11 @@ func (s *UpdateWorkforceInput) Validate() error { if s.WorkforceName != nil && len(*s.WorkforceName) < 1 { invalidParams.Add(request.NewErrParamMinLen("WorkforceName", 1)) } + if s.OidcConfig != nil { + if err := s.OidcConfig.Validate(); err != nil { + invalidParams.AddNested("OidcConfig", err.(request.ErrInvalidParams)) + } + } if s.SourceIpConfig != nil { if err := s.SourceIpConfig.Validate(); err != nil { invalidParams.AddNested("SourceIpConfig", err.(request.ErrInvalidParams)) @@ -45471,6 +47912,12 @@ func (s *UpdateWorkforceInput) Validate() error { return nil } +// SetOidcConfig sets the OidcConfig field's value. +func (s *UpdateWorkforceInput) SetOidcConfig(v *OidcConfig) *UpdateWorkforceInput { + s.OidcConfig = v + return s +} + // SetSourceIpConfig sets the SourceIpConfig field's value. func (s *UpdateWorkforceInput) SetSourceIpConfig(v *SourceIpConfig) *UpdateWorkforceInput { s.SourceIpConfig = v @@ -45931,23 +48378,34 @@ func (s *VpcConfig) SetSubnets(v []*string) *VpcConfig { type Workforce struct { _ struct{} `type:"structure"` + // The configuration of an Amazon Cognito workforce. A single Cognito workforce + // is created using and corresponds to a single Amazon Cognito user pool (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html). + CognitoConfig *CognitoConfig `type:"structure"` + + // The date that the workforce is created. + CreateDate *time.Time `type:"timestamp"` + // The most recent date that was used to successfully add one or more IP address // ranges (CIDRs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html)) // to a private workforce's allow list. LastUpdatedDate *time.Time `type:"timestamp"` - // A list of one to four IP address ranges (CIDRs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html)) + // The configuration of an OIDC Identity Provider (IdP) private workforce. + OidcConfig *OidcConfigForResponse `type:"structure"` + + // A list of one to ten IP address ranges (CIDRs (https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html)) // to be added to the workforce allow list. SourceIpConfig *SourceIpConfig `type:"structure"` + // The subdomain for your OIDC Identity Provider. + SubDomain *string `type:"string"` + // The Amazon Resource Name (ARN) of the private workforce. // // WorkforceArn is a required field WorkforceArn *string `type:"string" required:"true"` - // The name of the private workforce whose access you want to restrict. WorkforceName - // is automatically set to default when a workforce is created and cannot be - // modified. + // The name of the private workforce. // // WorkforceName is a required field WorkforceName *string `min:"1" type:"string" required:"true"` @@ -45963,18 +48421,42 @@ func (s Workforce) GoString() string { return s.String() } +// SetCognitoConfig sets the CognitoConfig field's value. +func (s *Workforce) SetCognitoConfig(v *CognitoConfig) *Workforce { + s.CognitoConfig = v + return s +} + +// SetCreateDate sets the CreateDate field's value. +func (s *Workforce) SetCreateDate(v time.Time) *Workforce { + s.CreateDate = &v + return s +} + // SetLastUpdatedDate sets the LastUpdatedDate field's value. func (s *Workforce) SetLastUpdatedDate(v time.Time) *Workforce { s.LastUpdatedDate = &v return s } +// SetOidcConfig sets the OidcConfig field's value. +func (s *Workforce) SetOidcConfig(v *OidcConfigForResponse) *Workforce { + s.OidcConfig = v + return s +} + // SetSourceIpConfig sets the SourceIpConfig field's value. func (s *Workforce) SetSourceIpConfig(v *SourceIpConfig) *Workforce { s.SourceIpConfig = v return s } +// SetSubDomain sets the SubDomain field's value. +func (s *Workforce) SetSubDomain(v string) *Workforce { + s.SubDomain = &v + return s +} + // SetWorkforceArn sets the WorkforceArn field's value. func (s *Workforce) SetWorkforceArn(v string) *Workforce { s.WorkforceArn = &v @@ -46018,6 +48500,9 @@ type Workteam struct { // labeling your data objects. SubDomain *string `type:"string"` + // The Amazon Resource Name (ARN) of the workforce. + WorkforceArn *string `type:"string"` + // The Amazon Resource Name (ARN) that identifies the work team. // // WorkteamArn is a required field @@ -46081,6 +48566,12 @@ func (s *Workteam) SetSubDomain(v string) *Workteam { return s } +// SetWorkforceArn sets the WorkforceArn field's value. +func (s *Workteam) SetWorkforceArn(v string) *Workteam { + s.WorkforceArn = &v + return s +} + // SetWorkteamArn sets the WorkteamArn field's value. func (s *Workteam) SetWorkteamArn(v string) *Workteam { s.WorkteamArn = &v @@ -46101,6 +48592,14 @@ const ( AlgorithmSortByCreationTime = "CreationTime" ) +// AlgorithmSortBy_Values returns all elements of the AlgorithmSortBy enum +func AlgorithmSortBy_Values() []string { + return []string{ + AlgorithmSortByName, + AlgorithmSortByCreationTime, + } +} + const ( // AlgorithmStatusPending is a AlgorithmStatus enum value AlgorithmStatusPending = "Pending" @@ -46118,6 +48617,17 @@ const ( AlgorithmStatusDeleting = "Deleting" ) +// AlgorithmStatus_Values returns all elements of the AlgorithmStatus enum +func AlgorithmStatus_Values() []string { + return []string{ + AlgorithmStatusPending, + AlgorithmStatusInProgress, + AlgorithmStatusCompleted, + AlgorithmStatusFailed, + AlgorithmStatusDeleting, + } +} + const ( // AppInstanceTypeSystem is a AppInstanceType enum value AppInstanceTypeSystem = "system" @@ -46216,11 +48726,56 @@ const ( AppInstanceTypeMlG4dn16xlarge = "ml.g4dn.16xlarge" ) +// AppInstanceType_Values returns all elements of the AppInstanceType enum +func AppInstanceType_Values() []string { + return []string{ + AppInstanceTypeSystem, + AppInstanceTypeMlT3Micro, + AppInstanceTypeMlT3Small, + AppInstanceTypeMlT3Medium, + AppInstanceTypeMlT3Large, + AppInstanceTypeMlT3Xlarge, + AppInstanceTypeMlT32xlarge, + AppInstanceTypeMlM5Large, + AppInstanceTypeMlM5Xlarge, + AppInstanceTypeMlM52xlarge, + AppInstanceTypeMlM54xlarge, + AppInstanceTypeMlM58xlarge, + AppInstanceTypeMlM512xlarge, + AppInstanceTypeMlM516xlarge, + AppInstanceTypeMlM524xlarge, + AppInstanceTypeMlC5Large, + AppInstanceTypeMlC5Xlarge, + AppInstanceTypeMlC52xlarge, + AppInstanceTypeMlC54xlarge, + AppInstanceTypeMlC59xlarge, + AppInstanceTypeMlC512xlarge, + AppInstanceTypeMlC518xlarge, + AppInstanceTypeMlC524xlarge, + AppInstanceTypeMlP32xlarge, + AppInstanceTypeMlP38xlarge, + AppInstanceTypeMlP316xlarge, + AppInstanceTypeMlG4dnXlarge, + AppInstanceTypeMlG4dn2xlarge, + AppInstanceTypeMlG4dn4xlarge, + AppInstanceTypeMlG4dn8xlarge, + AppInstanceTypeMlG4dn12xlarge, + AppInstanceTypeMlG4dn16xlarge, + } +} + const ( // AppSortKeyCreationTime is a AppSortKey enum value AppSortKeyCreationTime = "CreationTime" ) +// AppSortKey_Values returns all elements of the AppSortKey enum +func AppSortKey_Values() []string { + return []string{ + AppSortKeyCreationTime, + } +} + const ( // AppStatusDeleted is a AppStatus enum value AppStatusDeleted = "Deleted" @@ -46238,6 +48793,17 @@ const ( AppStatusPending = "Pending" ) +// AppStatus_Values returns all elements of the AppStatus enum +func AppStatus_Values() []string { + return []string{ + AppStatusDeleted, + AppStatusDeleting, + AppStatusFailed, + AppStatusInService, + AppStatusPending, + } +} + const ( // AppTypeJupyterServer is a AppType enum value AppTypeJupyterServer = "JupyterServer" @@ -46249,6 +48815,15 @@ const ( AppTypeTensorBoard = "TensorBoard" ) +// AppType_Values returns all elements of the AppType enum +func AppType_Values() []string { + return []string{ + AppTypeJupyterServer, + AppTypeKernelGateway, + AppTypeTensorBoard, + } +} + const ( // AssemblyTypeNone is a AssemblyType enum value AssemblyTypeNone = "None" @@ -46257,6 +48832,14 @@ const ( AssemblyTypeLine = "Line" ) +// AssemblyType_Values returns all elements of the AssemblyType enum +func AssemblyType_Values() []string { + return []string{ + AssemblyTypeNone, + AssemblyTypeLine, + } +} + const ( // AuthModeSso is a AuthMode enum value AuthModeSso = "SSO" @@ -46265,6 +48848,14 @@ const ( AuthModeIam = "IAM" ) +// AuthMode_Values returns all elements of the AuthMode enum +func AuthMode_Values() []string { + return []string{ + AuthModeSso, + AuthModeIam, + } +} + const ( // AutoMLJobObjectiveTypeMaximize is a AutoMLJobObjectiveType enum value AutoMLJobObjectiveTypeMaximize = "Maximize" @@ -46273,6 +48864,14 @@ const ( AutoMLJobObjectiveTypeMinimize = "Minimize" ) +// AutoMLJobObjectiveType_Values returns all elements of the AutoMLJobObjectiveType enum +func AutoMLJobObjectiveType_Values() []string { + return []string{ + AutoMLJobObjectiveTypeMaximize, + AutoMLJobObjectiveTypeMinimize, + } +} + const ( // AutoMLJobSecondaryStatusStarting is a AutoMLJobSecondaryStatus enum value AutoMLJobSecondaryStatusStarting = "Starting" @@ -46305,6 +48904,22 @@ const ( AutoMLJobSecondaryStatusCandidateDefinitionsGenerated = "CandidateDefinitionsGenerated" ) +// AutoMLJobSecondaryStatus_Values returns all elements of the AutoMLJobSecondaryStatus enum +func AutoMLJobSecondaryStatus_Values() []string { + return []string{ + AutoMLJobSecondaryStatusStarting, + AutoMLJobSecondaryStatusAnalyzingData, + AutoMLJobSecondaryStatusFeatureEngineering, + AutoMLJobSecondaryStatusModelTuning, + AutoMLJobSecondaryStatusMaxCandidatesReached, + AutoMLJobSecondaryStatusFailed, + AutoMLJobSecondaryStatusStopped, + AutoMLJobSecondaryStatusMaxAutoMljobRuntimeReached, + AutoMLJobSecondaryStatusStopping, + AutoMLJobSecondaryStatusCandidateDefinitionsGenerated, + } +} + const ( // AutoMLJobStatusCompleted is a AutoMLJobStatus enum value AutoMLJobStatusCompleted = "Completed" @@ -46322,6 +48937,17 @@ const ( AutoMLJobStatusStopping = "Stopping" ) +// AutoMLJobStatus_Values returns all elements of the AutoMLJobStatus enum +func AutoMLJobStatus_Values() []string { + return []string{ + AutoMLJobStatusCompleted, + AutoMLJobStatusInProgress, + AutoMLJobStatusFailed, + AutoMLJobStatusStopped, + AutoMLJobStatusStopping, + } +} + const ( // AutoMLMetricEnumAccuracy is a AutoMLMetricEnum enum value AutoMLMetricEnumAccuracy = "Accuracy" @@ -46336,6 +48962,16 @@ const ( AutoMLMetricEnumF1macro = "F1macro" ) +// AutoMLMetricEnum_Values returns all elements of the AutoMLMetricEnum enum +func AutoMLMetricEnum_Values() []string { + return []string{ + AutoMLMetricEnumAccuracy, + AutoMLMetricEnumMse, + AutoMLMetricEnumF1, + AutoMLMetricEnumF1macro, + } +} + const ( // AutoMLS3DataTypeManifestFile is a AutoMLS3DataType enum value AutoMLS3DataTypeManifestFile = "ManifestFile" @@ -46344,6 +48980,14 @@ const ( AutoMLS3DataTypeS3prefix = "S3Prefix" ) +// AutoMLS3DataType_Values returns all elements of the AutoMLS3DataType enum +func AutoMLS3DataType_Values() []string { + return []string{ + AutoMLS3DataTypeManifestFile, + AutoMLS3DataTypeS3prefix, + } +} + const ( // AutoMLSortByName is a AutoMLSortBy enum value AutoMLSortByName = "Name" @@ -46355,6 +48999,15 @@ const ( AutoMLSortByStatus = "Status" ) +// AutoMLSortBy_Values returns all elements of the AutoMLSortBy enum +func AutoMLSortBy_Values() []string { + return []string{ + AutoMLSortByName, + AutoMLSortByCreationTime, + AutoMLSortByStatus, + } +} + const ( // AutoMLSortOrderAscending is a AutoMLSortOrder enum value AutoMLSortOrderAscending = "Ascending" @@ -46363,6 +49016,14 @@ const ( AutoMLSortOrderDescending = "Descending" ) +// AutoMLSortOrder_Values returns all elements of the AutoMLSortOrder enum +func AutoMLSortOrder_Values() []string { + return []string{ + AutoMLSortOrderAscending, + AutoMLSortOrderDescending, + } +} + const ( // AwsManagedHumanLoopRequestSourceAwsRekognitionDetectModerationLabelsImageV3 is a AwsManagedHumanLoopRequestSource enum value AwsManagedHumanLoopRequestSourceAwsRekognitionDetectModerationLabelsImageV3 = "AWS/Rekognition/DetectModerationLabels/Image/V3" @@ -46371,6 +49032,14 @@ const ( AwsManagedHumanLoopRequestSourceAwsTextractAnalyzeDocumentFormsV1 = "AWS/Textract/AnalyzeDocument/Forms/V1" ) +// AwsManagedHumanLoopRequestSource_Values returns all elements of the AwsManagedHumanLoopRequestSource enum +func AwsManagedHumanLoopRequestSource_Values() []string { + return []string{ + AwsManagedHumanLoopRequestSourceAwsRekognitionDetectModerationLabelsImageV3, + AwsManagedHumanLoopRequestSourceAwsTextractAnalyzeDocumentFormsV1, + } +} + const ( // BatchStrategyMultiRecord is a BatchStrategy enum value BatchStrategyMultiRecord = "MultiRecord" @@ -46379,6 +49048,14 @@ const ( BatchStrategySingleRecord = "SingleRecord" ) +// BatchStrategy_Values returns all elements of the BatchStrategy enum +func BatchStrategy_Values() []string { + return []string{ + BatchStrategyMultiRecord, + BatchStrategySingleRecord, + } +} + const ( // BooleanOperatorAnd is a BooleanOperator enum value BooleanOperatorAnd = "And" @@ -46387,6 +49064,14 @@ const ( BooleanOperatorOr = "Or" ) +// BooleanOperator_Values returns all elements of the BooleanOperator enum +func BooleanOperator_Values() []string { + return []string{ + BooleanOperatorAnd, + BooleanOperatorOr, + } +} + const ( // CandidateSortByCreationTime is a CandidateSortBy enum value CandidateSortByCreationTime = "CreationTime" @@ -46398,6 +49083,15 @@ const ( CandidateSortByFinalObjectiveMetricValue = "FinalObjectiveMetricValue" ) +// CandidateSortBy_Values returns all elements of the CandidateSortBy enum +func CandidateSortBy_Values() []string { + return []string{ + CandidateSortByCreationTime, + CandidateSortByStatus, + CandidateSortByFinalObjectiveMetricValue, + } +} + const ( // CandidateStatusCompleted is a CandidateStatus enum value CandidateStatusCompleted = "Completed" @@ -46415,6 +49109,17 @@ const ( CandidateStatusStopping = "Stopping" ) +// CandidateStatus_Values returns all elements of the CandidateStatus enum +func CandidateStatus_Values() []string { + return []string{ + CandidateStatusCompleted, + CandidateStatusInProgress, + CandidateStatusFailed, + CandidateStatusStopped, + CandidateStatusStopping, + } +} + const ( // CandidateStepTypeAwsSageMakerTrainingJob is a CandidateStepType enum value CandidateStepTypeAwsSageMakerTrainingJob = "AWS::SageMaker::TrainingJob" @@ -46426,6 +49131,15 @@ const ( CandidateStepTypeAwsSageMakerProcessingJob = "AWS::SageMaker::ProcessingJob" ) +// CandidateStepType_Values returns all elements of the CandidateStepType enum +func CandidateStepType_Values() []string { + return []string{ + CandidateStepTypeAwsSageMakerTrainingJob, + CandidateStepTypeAwsSageMakerTransformJob, + CandidateStepTypeAwsSageMakerProcessingJob, + } +} + const ( // CaptureModeInput is a CaptureMode enum value CaptureModeInput = "Input" @@ -46434,6 +49148,14 @@ const ( CaptureModeOutput = "Output" ) +// CaptureMode_Values returns all elements of the CaptureMode enum +func CaptureMode_Values() []string { + return []string{ + CaptureModeInput, + CaptureModeOutput, + } +} + const ( // CaptureStatusStarted is a CaptureStatus enum value CaptureStatusStarted = "Started" @@ -46442,6 +49164,14 @@ const ( CaptureStatusStopped = "Stopped" ) +// CaptureStatus_Values returns all elements of the CaptureStatus enum +func CaptureStatus_Values() []string { + return []string{ + CaptureStatusStarted, + CaptureStatusStopped, + } +} + const ( // CodeRepositorySortByName is a CodeRepositorySortBy enum value CodeRepositorySortByName = "Name" @@ -46453,6 +49183,15 @@ const ( CodeRepositorySortByLastModifiedTime = "LastModifiedTime" ) +// CodeRepositorySortBy_Values returns all elements of the CodeRepositorySortBy enum +func CodeRepositorySortBy_Values() []string { + return []string{ + CodeRepositorySortByName, + CodeRepositorySortByCreationTime, + CodeRepositorySortByLastModifiedTime, + } +} + const ( // CodeRepositorySortOrderAscending is a CodeRepositorySortOrder enum value CodeRepositorySortOrderAscending = "Ascending" @@ -46461,6 +49200,14 @@ const ( CodeRepositorySortOrderDescending = "Descending" ) +// CodeRepositorySortOrder_Values returns all elements of the CodeRepositorySortOrder enum +func CodeRepositorySortOrder_Values() []string { + return []string{ + CodeRepositorySortOrderAscending, + CodeRepositorySortOrderDescending, + } +} + const ( // CompilationJobStatusInprogress is a CompilationJobStatus enum value CompilationJobStatusInprogress = "INPROGRESS" @@ -46481,6 +49228,18 @@ const ( CompilationJobStatusStopped = "STOPPED" ) +// CompilationJobStatus_Values returns all elements of the CompilationJobStatus enum +func CompilationJobStatus_Values() []string { + return []string{ + CompilationJobStatusInprogress, + CompilationJobStatusCompleted, + CompilationJobStatusFailed, + CompilationJobStatusStarting, + CompilationJobStatusStopping, + CompilationJobStatusStopped, + } +} + const ( // CompressionTypeNone is a CompressionType enum value CompressionTypeNone = "None" @@ -46489,6 +49248,14 @@ const ( CompressionTypeGzip = "Gzip" ) +// CompressionType_Values returns all elements of the CompressionType enum +func CompressionType_Values() []string { + return []string{ + CompressionTypeNone, + CompressionTypeGzip, + } +} + const ( // ContainerModeSingleModel is a ContainerMode enum value ContainerModeSingleModel = "SingleModel" @@ -46497,6 +49264,14 @@ const ( ContainerModeMultiModel = "MultiModel" ) +// ContainerMode_Values returns all elements of the ContainerMode enum +func ContainerMode_Values() []string { + return []string{ + ContainerModeSingleModel, + ContainerModeMultiModel, + } +} + const ( // ContentClassifierFreeOfPersonallyIdentifiableInformation is a ContentClassifier enum value ContentClassifierFreeOfPersonallyIdentifiableInformation = "FreeOfPersonallyIdentifiableInformation" @@ -46505,6 +49280,14 @@ const ( ContentClassifierFreeOfAdultContent = "FreeOfAdultContent" ) +// ContentClassifier_Values returns all elements of the ContentClassifier enum +func ContentClassifier_Values() []string { + return []string{ + ContentClassifierFreeOfPersonallyIdentifiableInformation, + ContentClassifierFreeOfAdultContent, + } +} + const ( // DetailedAlgorithmStatusNotStarted is a DetailedAlgorithmStatus enum value DetailedAlgorithmStatusNotStarted = "NotStarted" @@ -46519,6 +49302,16 @@ const ( DetailedAlgorithmStatusFailed = "Failed" ) +// DetailedAlgorithmStatus_Values returns all elements of the DetailedAlgorithmStatus enum +func DetailedAlgorithmStatus_Values() []string { + return []string{ + DetailedAlgorithmStatusNotStarted, + DetailedAlgorithmStatusInProgress, + DetailedAlgorithmStatusCompleted, + DetailedAlgorithmStatusFailed, + } +} + const ( // DetailedModelPackageStatusNotStarted is a DetailedModelPackageStatus enum value DetailedModelPackageStatusNotStarted = "NotStarted" @@ -46533,6 +49326,16 @@ const ( DetailedModelPackageStatusFailed = "Failed" ) +// DetailedModelPackageStatus_Values returns all elements of the DetailedModelPackageStatus enum +func DetailedModelPackageStatus_Values() []string { + return []string{ + DetailedModelPackageStatusNotStarted, + DetailedModelPackageStatusInProgress, + DetailedModelPackageStatusCompleted, + DetailedModelPackageStatusFailed, + } +} + const ( // DirectInternetAccessEnabled is a DirectInternetAccess enum value DirectInternetAccessEnabled = "Enabled" @@ -46541,6 +49344,14 @@ const ( DirectInternetAccessDisabled = "Disabled" ) +// DirectInternetAccess_Values returns all elements of the DirectInternetAccess enum +func DirectInternetAccess_Values() []string { + return []string{ + DirectInternetAccessEnabled, + DirectInternetAccessDisabled, + } +} + const ( // DomainStatusDeleting is a DomainStatus enum value DomainStatusDeleting = "Deleting" @@ -46555,6 +49366,16 @@ const ( DomainStatusPending = "Pending" ) +// DomainStatus_Values returns all elements of the DomainStatus enum +func DomainStatus_Values() []string { + return []string{ + DomainStatusDeleting, + DomainStatusFailed, + DomainStatusInService, + DomainStatusPending, + } +} + const ( // EndpointConfigSortKeyName is a EndpointConfigSortKey enum value EndpointConfigSortKeyName = "Name" @@ -46563,6 +49384,14 @@ const ( EndpointConfigSortKeyCreationTime = "CreationTime" ) +// EndpointConfigSortKey_Values returns all elements of the EndpointConfigSortKey enum +func EndpointConfigSortKey_Values() []string { + return []string{ + EndpointConfigSortKeyName, + EndpointConfigSortKeyCreationTime, + } +} + const ( // EndpointSortKeyName is a EndpointSortKey enum value EndpointSortKeyName = "Name" @@ -46574,6 +49403,15 @@ const ( EndpointSortKeyStatus = "Status" ) +// EndpointSortKey_Values returns all elements of the EndpointSortKey enum +func EndpointSortKey_Values() []string { + return []string{ + EndpointSortKeyName, + EndpointSortKeyCreationTime, + EndpointSortKeyStatus, + } +} + const ( // EndpointStatusOutOfService is a EndpointStatus enum value EndpointStatusOutOfService = "OutOfService" @@ -46600,6 +49438,20 @@ const ( EndpointStatusFailed = "Failed" ) +// EndpointStatus_Values returns all elements of the EndpointStatus enum +func EndpointStatus_Values() []string { + return []string{ + EndpointStatusOutOfService, + EndpointStatusCreating, + EndpointStatusUpdating, + EndpointStatusSystemUpdating, + EndpointStatusRollingBack, + EndpointStatusInService, + EndpointStatusDeleting, + EndpointStatusFailed, + } +} + const ( // ExecutionStatusPending is a ExecutionStatus enum value ExecutionStatusPending = "Pending" @@ -46623,6 +49475,19 @@ const ( ExecutionStatusStopped = "Stopped" ) +// ExecutionStatus_Values returns all elements of the ExecutionStatus enum +func ExecutionStatus_Values() []string { + return []string{ + ExecutionStatusPending, + ExecutionStatusCompleted, + ExecutionStatusCompletedWithViolations, + ExecutionStatusInProgress, + ExecutionStatusFailed, + ExecutionStatusStopping, + ExecutionStatusStopped, + } +} + const ( // FileSystemAccessModeRw is a FileSystemAccessMode enum value FileSystemAccessModeRw = "rw" @@ -46631,6 +49496,14 @@ const ( FileSystemAccessModeRo = "ro" ) +// FileSystemAccessMode_Values returns all elements of the FileSystemAccessMode enum +func FileSystemAccessMode_Values() []string { + return []string{ + FileSystemAccessModeRw, + FileSystemAccessModeRo, + } +} + const ( // FileSystemTypeEfs is a FileSystemType enum value FileSystemTypeEfs = "EFS" @@ -46639,6 +49512,14 @@ const ( FileSystemTypeFsxLustre = "FSxLustre" ) +// FileSystemType_Values returns all elements of the FileSystemType enum +func FileSystemType_Values() []string { + return []string{ + FileSystemTypeEfs, + FileSystemTypeFsxLustre, + } +} + const ( // FlowDefinitionStatusInitializing is a FlowDefinitionStatus enum value FlowDefinitionStatusInitializing = "Initializing" @@ -46653,6 +49534,16 @@ const ( FlowDefinitionStatusDeleting = "Deleting" ) +// FlowDefinitionStatus_Values returns all elements of the FlowDefinitionStatus enum +func FlowDefinitionStatus_Values() []string { + return []string{ + FlowDefinitionStatusInitializing, + FlowDefinitionStatusActive, + FlowDefinitionStatusFailed, + FlowDefinitionStatusDeleting, + } +} + const ( // FrameworkTensorflow is a Framework enum value FrameworkTensorflow = "TENSORFLOW" @@ -46676,6 +49567,35 @@ const ( FrameworkTflite = "TFLITE" ) +// Framework_Values returns all elements of the Framework enum +func Framework_Values() []string { + return []string{ + FrameworkTensorflow, + FrameworkKeras, + FrameworkMxnet, + FrameworkOnnx, + FrameworkPytorch, + FrameworkXgboost, + FrameworkTflite, + } +} + +const ( + // HumanTaskUiStatusActive is a HumanTaskUiStatus enum value + HumanTaskUiStatusActive = "Active" + + // HumanTaskUiStatusDeleting is a HumanTaskUiStatus enum value + HumanTaskUiStatusDeleting = "Deleting" +) + +// HumanTaskUiStatus_Values returns all elements of the HumanTaskUiStatus enum +func HumanTaskUiStatus_Values() []string { + return []string{ + HumanTaskUiStatusActive, + HumanTaskUiStatusDeleting, + } +} + const ( // HyperParameterScalingTypeAuto is a HyperParameterScalingType enum value HyperParameterScalingTypeAuto = "Auto" @@ -46690,6 +49610,16 @@ const ( HyperParameterScalingTypeReverseLogarithmic = "ReverseLogarithmic" ) +// HyperParameterScalingType_Values returns all elements of the HyperParameterScalingType enum +func HyperParameterScalingType_Values() []string { + return []string{ + HyperParameterScalingTypeAuto, + HyperParameterScalingTypeLinear, + HyperParameterScalingTypeLogarithmic, + HyperParameterScalingTypeReverseLogarithmic, + } +} + const ( // HyperParameterTuningJobObjectiveTypeMaximize is a HyperParameterTuningJobObjectiveType enum value HyperParameterTuningJobObjectiveTypeMaximize = "Maximize" @@ -46698,6 +49628,14 @@ const ( HyperParameterTuningJobObjectiveTypeMinimize = "Minimize" ) +// HyperParameterTuningJobObjectiveType_Values returns all elements of the HyperParameterTuningJobObjectiveType enum +func HyperParameterTuningJobObjectiveType_Values() []string { + return []string{ + HyperParameterTuningJobObjectiveTypeMaximize, + HyperParameterTuningJobObjectiveTypeMinimize, + } +} + const ( // HyperParameterTuningJobSortByOptionsName is a HyperParameterTuningJobSortByOptions enum value HyperParameterTuningJobSortByOptionsName = "Name" @@ -46709,6 +49647,15 @@ const ( HyperParameterTuningJobSortByOptionsCreationTime = "CreationTime" ) +// HyperParameterTuningJobSortByOptions_Values returns all elements of the HyperParameterTuningJobSortByOptions enum +func HyperParameterTuningJobSortByOptions_Values() []string { + return []string{ + HyperParameterTuningJobSortByOptionsName, + HyperParameterTuningJobSortByOptionsStatus, + HyperParameterTuningJobSortByOptionsCreationTime, + } +} + const ( // HyperParameterTuningJobStatusCompleted is a HyperParameterTuningJobStatus enum value HyperParameterTuningJobStatusCompleted = "Completed" @@ -46726,6 +49673,17 @@ const ( HyperParameterTuningJobStatusStopping = "Stopping" ) +// HyperParameterTuningJobStatus_Values returns all elements of the HyperParameterTuningJobStatus enum +func HyperParameterTuningJobStatus_Values() []string { + return []string{ + HyperParameterTuningJobStatusCompleted, + HyperParameterTuningJobStatusInProgress, + HyperParameterTuningJobStatusFailed, + HyperParameterTuningJobStatusStopped, + HyperParameterTuningJobStatusStopping, + } +} + // The strategy hyperparameter tuning uses to find the best combination of hyperparameters // for your model. Currently, the only supported value is Bayesian. const ( @@ -46736,6 +49694,14 @@ const ( HyperParameterTuningJobStrategyTypeRandom = "Random" ) +// HyperParameterTuningJobStrategyType_Values returns all elements of the HyperParameterTuningJobStrategyType enum +func HyperParameterTuningJobStrategyType_Values() []string { + return []string{ + HyperParameterTuningJobStrategyTypeBayesian, + HyperParameterTuningJobStrategyTypeRandom, + } +} + const ( // HyperParameterTuningJobWarmStartTypeIdenticalDataAndAlgorithm is a HyperParameterTuningJobWarmStartType enum value HyperParameterTuningJobWarmStartTypeIdenticalDataAndAlgorithm = "IdenticalDataAndAlgorithm" @@ -46744,6 +49710,14 @@ const ( HyperParameterTuningJobWarmStartTypeTransferLearning = "TransferLearning" ) +// HyperParameterTuningJobWarmStartType_Values returns all elements of the HyperParameterTuningJobWarmStartType enum +func HyperParameterTuningJobWarmStartType_Values() []string { + return []string{ + HyperParameterTuningJobWarmStartTypeIdenticalDataAndAlgorithm, + HyperParameterTuningJobWarmStartTypeTransferLearning, + } +} + const ( // InstanceTypeMlT2Medium is a InstanceType enum value InstanceTypeMlT2Medium = "ml.t2.medium" @@ -46860,6 +49834,50 @@ const ( InstanceTypeMlP316xlarge = "ml.p3.16xlarge" ) +// InstanceType_Values returns all elements of the InstanceType enum +func InstanceType_Values() []string { + return []string{ + InstanceTypeMlT2Medium, + InstanceTypeMlT2Large, + InstanceTypeMlT2Xlarge, + InstanceTypeMlT22xlarge, + InstanceTypeMlT3Medium, + InstanceTypeMlT3Large, + InstanceTypeMlT3Xlarge, + InstanceTypeMlT32xlarge, + InstanceTypeMlM4Xlarge, + InstanceTypeMlM42xlarge, + InstanceTypeMlM44xlarge, + InstanceTypeMlM410xlarge, + InstanceTypeMlM416xlarge, + InstanceTypeMlM5Xlarge, + InstanceTypeMlM52xlarge, + InstanceTypeMlM54xlarge, + InstanceTypeMlM512xlarge, + InstanceTypeMlM524xlarge, + InstanceTypeMlC4Xlarge, + InstanceTypeMlC42xlarge, + InstanceTypeMlC44xlarge, + InstanceTypeMlC48xlarge, + InstanceTypeMlC5Xlarge, + InstanceTypeMlC52xlarge, + InstanceTypeMlC54xlarge, + InstanceTypeMlC59xlarge, + InstanceTypeMlC518xlarge, + InstanceTypeMlC5dXlarge, + InstanceTypeMlC5d2xlarge, + InstanceTypeMlC5d4xlarge, + InstanceTypeMlC5d9xlarge, + InstanceTypeMlC5d18xlarge, + InstanceTypeMlP2Xlarge, + InstanceTypeMlP28xlarge, + InstanceTypeMlP216xlarge, + InstanceTypeMlP32xlarge, + InstanceTypeMlP38xlarge, + InstanceTypeMlP316xlarge, + } +} + const ( // JoinSourceInput is a JoinSource enum value JoinSourceInput = "Input" @@ -46868,7 +49886,18 @@ const ( JoinSourceNone = "None" ) +// JoinSource_Values returns all elements of the JoinSource enum +func JoinSource_Values() []string { + return []string{ + JoinSourceInput, + JoinSourceNone, + } +} + const ( + // LabelingJobStatusInitializing is a LabelingJobStatus enum value + LabelingJobStatusInitializing = "Initializing" + // LabelingJobStatusInProgress is a LabelingJobStatus enum value LabelingJobStatusInProgress = "InProgress" @@ -46885,6 +49914,18 @@ const ( LabelingJobStatusStopped = "Stopped" ) +// LabelingJobStatus_Values returns all elements of the LabelingJobStatus enum +func LabelingJobStatus_Values() []string { + return []string{ + LabelingJobStatusInitializing, + LabelingJobStatusInProgress, + LabelingJobStatusCompleted, + LabelingJobStatusFailed, + LabelingJobStatusStopping, + LabelingJobStatusStopped, + } +} + const ( // ListCompilationJobsSortByName is a ListCompilationJobsSortBy enum value ListCompilationJobsSortByName = "Name" @@ -46896,11 +49937,43 @@ const ( ListCompilationJobsSortByStatus = "Status" ) +// ListCompilationJobsSortBy_Values returns all elements of the ListCompilationJobsSortBy enum +func ListCompilationJobsSortBy_Values() []string { + return []string{ + ListCompilationJobsSortByName, + ListCompilationJobsSortByCreationTime, + ListCompilationJobsSortByStatus, + } +} + const ( // ListLabelingJobsForWorkteamSortByOptionsCreationTime is a ListLabelingJobsForWorkteamSortByOptions enum value ListLabelingJobsForWorkteamSortByOptionsCreationTime = "CreationTime" ) +// ListLabelingJobsForWorkteamSortByOptions_Values returns all elements of the ListLabelingJobsForWorkteamSortByOptions enum +func ListLabelingJobsForWorkteamSortByOptions_Values() []string { + return []string{ + ListLabelingJobsForWorkteamSortByOptionsCreationTime, + } +} + +const ( + // ListWorkforcesSortByOptionsName is a ListWorkforcesSortByOptions enum value + ListWorkforcesSortByOptionsName = "Name" + + // ListWorkforcesSortByOptionsCreateDate is a ListWorkforcesSortByOptions enum value + ListWorkforcesSortByOptionsCreateDate = "CreateDate" +) + +// ListWorkforcesSortByOptions_Values returns all elements of the ListWorkforcesSortByOptions enum +func ListWorkforcesSortByOptions_Values() []string { + return []string{ + ListWorkforcesSortByOptionsName, + ListWorkforcesSortByOptionsCreateDate, + } +} + const ( // ListWorkteamsSortByOptionsName is a ListWorkteamsSortByOptions enum value ListWorkteamsSortByOptionsName = "Name" @@ -46909,6 +49982,14 @@ const ( ListWorkteamsSortByOptionsCreateDate = "CreateDate" ) +// ListWorkteamsSortByOptions_Values returns all elements of the ListWorkteamsSortByOptions enum +func ListWorkteamsSortByOptions_Values() []string { + return []string{ + ListWorkteamsSortByOptionsName, + ListWorkteamsSortByOptionsCreateDate, + } +} + const ( // ModelPackageSortByName is a ModelPackageSortBy enum value ModelPackageSortByName = "Name" @@ -46917,6 +49998,14 @@ const ( ModelPackageSortByCreationTime = "CreationTime" ) +// ModelPackageSortBy_Values returns all elements of the ModelPackageSortBy enum +func ModelPackageSortBy_Values() []string { + return []string{ + ModelPackageSortByName, + ModelPackageSortByCreationTime, + } +} + const ( // ModelPackageStatusPending is a ModelPackageStatus enum value ModelPackageStatusPending = "Pending" @@ -46934,6 +50023,17 @@ const ( ModelPackageStatusDeleting = "Deleting" ) +// ModelPackageStatus_Values returns all elements of the ModelPackageStatus enum +func ModelPackageStatus_Values() []string { + return []string{ + ModelPackageStatusPending, + ModelPackageStatusInProgress, + ModelPackageStatusCompleted, + ModelPackageStatusFailed, + ModelPackageStatusDeleting, + } +} + const ( // ModelSortKeyName is a ModelSortKey enum value ModelSortKeyName = "Name" @@ -46942,6 +50042,14 @@ const ( ModelSortKeyCreationTime = "CreationTime" ) +// ModelSortKey_Values returns all elements of the ModelSortKey enum +func ModelSortKey_Values() []string { + return []string{ + ModelSortKeyName, + ModelSortKeyCreationTime, + } +} + const ( // MonitoringExecutionSortKeyCreationTime is a MonitoringExecutionSortKey enum value MonitoringExecutionSortKeyCreationTime = "CreationTime" @@ -46953,6 +50061,15 @@ const ( MonitoringExecutionSortKeyStatus = "Status" ) +// MonitoringExecutionSortKey_Values returns all elements of the MonitoringExecutionSortKey enum +func MonitoringExecutionSortKey_Values() []string { + return []string{ + MonitoringExecutionSortKeyCreationTime, + MonitoringExecutionSortKeyScheduledTime, + MonitoringExecutionSortKeyStatus, + } +} + const ( // MonitoringScheduleSortKeyName is a MonitoringScheduleSortKey enum value MonitoringScheduleSortKeyName = "Name" @@ -46964,6 +50081,15 @@ const ( MonitoringScheduleSortKeyStatus = "Status" ) +// MonitoringScheduleSortKey_Values returns all elements of the MonitoringScheduleSortKey enum +func MonitoringScheduleSortKey_Values() []string { + return []string{ + MonitoringScheduleSortKeyName, + MonitoringScheduleSortKeyCreationTime, + MonitoringScheduleSortKeyStatus, + } +} + const ( // NotebookInstanceAcceleratorTypeMlEia1Medium is a NotebookInstanceAcceleratorType enum value NotebookInstanceAcceleratorTypeMlEia1Medium = "ml.eia1.medium" @@ -46984,6 +50110,18 @@ const ( NotebookInstanceAcceleratorTypeMlEia2Xlarge = "ml.eia2.xlarge" ) +// NotebookInstanceAcceleratorType_Values returns all elements of the NotebookInstanceAcceleratorType enum +func NotebookInstanceAcceleratorType_Values() []string { + return []string{ + NotebookInstanceAcceleratorTypeMlEia1Medium, + NotebookInstanceAcceleratorTypeMlEia1Large, + NotebookInstanceAcceleratorTypeMlEia1Xlarge, + NotebookInstanceAcceleratorTypeMlEia2Medium, + NotebookInstanceAcceleratorTypeMlEia2Large, + NotebookInstanceAcceleratorTypeMlEia2Xlarge, + } +} + const ( // NotebookInstanceLifecycleConfigSortKeyName is a NotebookInstanceLifecycleConfigSortKey enum value NotebookInstanceLifecycleConfigSortKeyName = "Name" @@ -46995,6 +50133,15 @@ const ( NotebookInstanceLifecycleConfigSortKeyLastModifiedTime = "LastModifiedTime" ) +// NotebookInstanceLifecycleConfigSortKey_Values returns all elements of the NotebookInstanceLifecycleConfigSortKey enum +func NotebookInstanceLifecycleConfigSortKey_Values() []string { + return []string{ + NotebookInstanceLifecycleConfigSortKeyName, + NotebookInstanceLifecycleConfigSortKeyCreationTime, + NotebookInstanceLifecycleConfigSortKeyLastModifiedTime, + } +} + const ( // NotebookInstanceLifecycleConfigSortOrderAscending is a NotebookInstanceLifecycleConfigSortOrder enum value NotebookInstanceLifecycleConfigSortOrderAscending = "Ascending" @@ -47003,6 +50150,14 @@ const ( NotebookInstanceLifecycleConfigSortOrderDescending = "Descending" ) +// NotebookInstanceLifecycleConfigSortOrder_Values returns all elements of the NotebookInstanceLifecycleConfigSortOrder enum +func NotebookInstanceLifecycleConfigSortOrder_Values() []string { + return []string{ + NotebookInstanceLifecycleConfigSortOrderAscending, + NotebookInstanceLifecycleConfigSortOrderDescending, + } +} + const ( // NotebookInstanceSortKeyName is a NotebookInstanceSortKey enum value NotebookInstanceSortKeyName = "Name" @@ -47014,6 +50169,15 @@ const ( NotebookInstanceSortKeyStatus = "Status" ) +// NotebookInstanceSortKey_Values returns all elements of the NotebookInstanceSortKey enum +func NotebookInstanceSortKey_Values() []string { + return []string{ + NotebookInstanceSortKeyName, + NotebookInstanceSortKeyCreationTime, + NotebookInstanceSortKeyStatus, + } +} + const ( // NotebookInstanceSortOrderAscending is a NotebookInstanceSortOrder enum value NotebookInstanceSortOrderAscending = "Ascending" @@ -47022,6 +50186,14 @@ const ( NotebookInstanceSortOrderDescending = "Descending" ) +// NotebookInstanceSortOrder_Values returns all elements of the NotebookInstanceSortOrder enum +func NotebookInstanceSortOrder_Values() []string { + return []string{ + NotebookInstanceSortOrderAscending, + NotebookInstanceSortOrderDescending, + } +} + const ( // NotebookInstanceStatusPending is a NotebookInstanceStatus enum value NotebookInstanceStatusPending = "Pending" @@ -47045,6 +50217,19 @@ const ( NotebookInstanceStatusUpdating = "Updating" ) +// NotebookInstanceStatus_Values returns all elements of the NotebookInstanceStatus enum +func NotebookInstanceStatus_Values() []string { + return []string{ + NotebookInstanceStatusPending, + NotebookInstanceStatusInService, + NotebookInstanceStatusStopping, + NotebookInstanceStatusStopped, + NotebookInstanceStatusFailed, + NotebookInstanceStatusDeleting, + NotebookInstanceStatusUpdating, + } +} + const ( // NotebookOutputOptionAllowed is a NotebookOutputOption enum value NotebookOutputOptionAllowed = "Allowed" @@ -47053,6 +50238,14 @@ const ( NotebookOutputOptionDisabled = "Disabled" ) +// NotebookOutputOption_Values returns all elements of the NotebookOutputOption enum +func NotebookOutputOption_Values() []string { + return []string{ + NotebookOutputOptionAllowed, + NotebookOutputOptionDisabled, + } +} + const ( // ObjectiveStatusSucceeded is a ObjectiveStatus enum value ObjectiveStatusSucceeded = "Succeeded" @@ -47064,6 +50257,15 @@ const ( ObjectiveStatusFailed = "Failed" ) +// ObjectiveStatus_Values returns all elements of the ObjectiveStatus enum +func ObjectiveStatus_Values() []string { + return []string{ + ObjectiveStatusSucceeded, + ObjectiveStatusPending, + ObjectiveStatusFailed, + } +} + const ( // OperatorEquals is a Operator enum value OperatorEquals = "Equals" @@ -47096,6 +50298,22 @@ const ( OperatorIn = "In" ) +// Operator_Values returns all elements of the Operator enum +func Operator_Values() []string { + return []string{ + OperatorEquals, + OperatorNotEquals, + OperatorGreaterThan, + OperatorGreaterThanOrEqualTo, + OperatorLessThan, + OperatorLessThanOrEqualTo, + OperatorContains, + OperatorExists, + OperatorNotExists, + OperatorIn, + } +} + const ( // OrderKeyAscending is a OrderKey enum value OrderKeyAscending = "Ascending" @@ -47104,6 +50322,14 @@ const ( OrderKeyDescending = "Descending" ) +// OrderKey_Values returns all elements of the OrderKey enum +func OrderKey_Values() []string { + return []string{ + OrderKeyAscending, + OrderKeyDescending, + } +} + const ( // ParameterTypeInteger is a ParameterType enum value ParameterTypeInteger = "Integer" @@ -47118,6 +50344,16 @@ const ( ParameterTypeFreeText = "FreeText" ) +// ParameterType_Values returns all elements of the ParameterType enum +func ParameterType_Values() []string { + return []string{ + ParameterTypeInteger, + ParameterTypeContinuous, + ParameterTypeCategorical, + ParameterTypeFreeText, + } +} + const ( // ProblemTypeBinaryClassification is a ProblemType enum value ProblemTypeBinaryClassification = "BinaryClassification" @@ -47129,6 +50365,15 @@ const ( ProblemTypeRegression = "Regression" ) +// ProblemType_Values returns all elements of the ProblemType enum +func ProblemType_Values() []string { + return []string{ + ProblemTypeBinaryClassification, + ProblemTypeMulticlassClassification, + ProblemTypeRegression, + } +} + const ( // ProcessingInstanceTypeMlT3Medium is a ProcessingInstanceType enum value ProcessingInstanceTypeMlT3Medium = "ml.t3.medium" @@ -47245,6 +50490,50 @@ const ( ProcessingInstanceTypeMlR524xlarge = "ml.r5.24xlarge" ) +// ProcessingInstanceType_Values returns all elements of the ProcessingInstanceType enum +func ProcessingInstanceType_Values() []string { + return []string{ + ProcessingInstanceTypeMlT3Medium, + ProcessingInstanceTypeMlT3Large, + ProcessingInstanceTypeMlT3Xlarge, + ProcessingInstanceTypeMlT32xlarge, + ProcessingInstanceTypeMlM4Xlarge, + ProcessingInstanceTypeMlM42xlarge, + ProcessingInstanceTypeMlM44xlarge, + ProcessingInstanceTypeMlM410xlarge, + ProcessingInstanceTypeMlM416xlarge, + ProcessingInstanceTypeMlC4Xlarge, + ProcessingInstanceTypeMlC42xlarge, + ProcessingInstanceTypeMlC44xlarge, + ProcessingInstanceTypeMlC48xlarge, + ProcessingInstanceTypeMlP2Xlarge, + ProcessingInstanceTypeMlP28xlarge, + ProcessingInstanceTypeMlP216xlarge, + ProcessingInstanceTypeMlP32xlarge, + ProcessingInstanceTypeMlP38xlarge, + ProcessingInstanceTypeMlP316xlarge, + ProcessingInstanceTypeMlC5Xlarge, + ProcessingInstanceTypeMlC52xlarge, + ProcessingInstanceTypeMlC54xlarge, + ProcessingInstanceTypeMlC59xlarge, + ProcessingInstanceTypeMlC518xlarge, + ProcessingInstanceTypeMlM5Large, + ProcessingInstanceTypeMlM5Xlarge, + ProcessingInstanceTypeMlM52xlarge, + ProcessingInstanceTypeMlM54xlarge, + ProcessingInstanceTypeMlM512xlarge, + ProcessingInstanceTypeMlM524xlarge, + ProcessingInstanceTypeMlR5Large, + ProcessingInstanceTypeMlR5Xlarge, + ProcessingInstanceTypeMlR52xlarge, + ProcessingInstanceTypeMlR54xlarge, + ProcessingInstanceTypeMlR58xlarge, + ProcessingInstanceTypeMlR512xlarge, + ProcessingInstanceTypeMlR516xlarge, + ProcessingInstanceTypeMlR524xlarge, + } +} + const ( // ProcessingJobStatusInProgress is a ProcessingJobStatus enum value ProcessingJobStatusInProgress = "InProgress" @@ -47262,6 +50551,17 @@ const ( ProcessingJobStatusStopped = "Stopped" ) +// ProcessingJobStatus_Values returns all elements of the ProcessingJobStatus enum +func ProcessingJobStatus_Values() []string { + return []string{ + ProcessingJobStatusInProgress, + ProcessingJobStatusCompleted, + ProcessingJobStatusFailed, + ProcessingJobStatusStopping, + ProcessingJobStatusStopped, + } +} + const ( // ProcessingS3CompressionTypeNone is a ProcessingS3CompressionType enum value ProcessingS3CompressionTypeNone = "None" @@ -47270,6 +50570,14 @@ const ( ProcessingS3CompressionTypeGzip = "Gzip" ) +// ProcessingS3CompressionType_Values returns all elements of the ProcessingS3CompressionType enum +func ProcessingS3CompressionType_Values() []string { + return []string{ + ProcessingS3CompressionTypeNone, + ProcessingS3CompressionTypeGzip, + } +} + const ( // ProcessingS3DataDistributionTypeFullyReplicated is a ProcessingS3DataDistributionType enum value ProcessingS3DataDistributionTypeFullyReplicated = "FullyReplicated" @@ -47278,6 +50586,14 @@ const ( ProcessingS3DataDistributionTypeShardedByS3key = "ShardedByS3Key" ) +// ProcessingS3DataDistributionType_Values returns all elements of the ProcessingS3DataDistributionType enum +func ProcessingS3DataDistributionType_Values() []string { + return []string{ + ProcessingS3DataDistributionTypeFullyReplicated, + ProcessingS3DataDistributionTypeShardedByS3key, + } +} + const ( // ProcessingS3DataTypeManifestFile is a ProcessingS3DataType enum value ProcessingS3DataTypeManifestFile = "ManifestFile" @@ -47286,6 +50602,14 @@ const ( ProcessingS3DataTypeS3prefix = "S3Prefix" ) +// ProcessingS3DataType_Values returns all elements of the ProcessingS3DataType enum +func ProcessingS3DataType_Values() []string { + return []string{ + ProcessingS3DataTypeManifestFile, + ProcessingS3DataTypeS3prefix, + } +} + const ( // ProcessingS3InputModePipe is a ProcessingS3InputMode enum value ProcessingS3InputModePipe = "Pipe" @@ -47294,6 +50618,14 @@ const ( ProcessingS3InputModeFile = "File" ) +// ProcessingS3InputMode_Values returns all elements of the ProcessingS3InputMode enum +func ProcessingS3InputMode_Values() []string { + return []string{ + ProcessingS3InputModePipe, + ProcessingS3InputModeFile, + } +} + const ( // ProcessingS3UploadModeContinuous is a ProcessingS3UploadMode enum value ProcessingS3UploadModeContinuous = "Continuous" @@ -47302,6 +50634,14 @@ const ( ProcessingS3UploadModeEndOfJob = "EndOfJob" ) +// ProcessingS3UploadMode_Values returns all elements of the ProcessingS3UploadMode enum +func ProcessingS3UploadMode_Values() []string { + return []string{ + ProcessingS3UploadModeContinuous, + ProcessingS3UploadModeEndOfJob, + } +} + const ( // ProductionVariantAcceleratorTypeMlEia1Medium is a ProductionVariantAcceleratorType enum value ProductionVariantAcceleratorTypeMlEia1Medium = "ml.eia1.medium" @@ -47322,6 +50662,18 @@ const ( ProductionVariantAcceleratorTypeMlEia2Xlarge = "ml.eia2.xlarge" ) +// ProductionVariantAcceleratorType_Values returns all elements of the ProductionVariantAcceleratorType enum +func ProductionVariantAcceleratorType_Values() []string { + return []string{ + ProductionVariantAcceleratorTypeMlEia1Medium, + ProductionVariantAcceleratorTypeMlEia1Large, + ProductionVariantAcceleratorTypeMlEia1Xlarge, + ProductionVariantAcceleratorTypeMlEia2Medium, + ProductionVariantAcceleratorTypeMlEia2Large, + ProductionVariantAcceleratorTypeMlEia2Xlarge, + } +} + const ( // ProductionVariantInstanceTypeMlT2Medium is a ProductionVariantInstanceType enum value ProductionVariantInstanceTypeMlT2Medium = "ml.t2.medium" @@ -47522,6 +50874,78 @@ const ( ProductionVariantInstanceTypeMlInf124xlarge = "ml.inf1.24xlarge" ) +// ProductionVariantInstanceType_Values returns all elements of the ProductionVariantInstanceType enum +func ProductionVariantInstanceType_Values() []string { + return []string{ + ProductionVariantInstanceTypeMlT2Medium, + ProductionVariantInstanceTypeMlT2Large, + ProductionVariantInstanceTypeMlT2Xlarge, + ProductionVariantInstanceTypeMlT22xlarge, + ProductionVariantInstanceTypeMlM4Xlarge, + ProductionVariantInstanceTypeMlM42xlarge, + ProductionVariantInstanceTypeMlM44xlarge, + ProductionVariantInstanceTypeMlM410xlarge, + ProductionVariantInstanceTypeMlM416xlarge, + ProductionVariantInstanceTypeMlM5Large, + ProductionVariantInstanceTypeMlM5Xlarge, + ProductionVariantInstanceTypeMlM52xlarge, + ProductionVariantInstanceTypeMlM54xlarge, + ProductionVariantInstanceTypeMlM512xlarge, + ProductionVariantInstanceTypeMlM524xlarge, + ProductionVariantInstanceTypeMlM5dLarge, + ProductionVariantInstanceTypeMlM5dXlarge, + ProductionVariantInstanceTypeMlM5d2xlarge, + ProductionVariantInstanceTypeMlM5d4xlarge, + ProductionVariantInstanceTypeMlM5d12xlarge, + ProductionVariantInstanceTypeMlM5d24xlarge, + ProductionVariantInstanceTypeMlC4Large, + ProductionVariantInstanceTypeMlC4Xlarge, + ProductionVariantInstanceTypeMlC42xlarge, + ProductionVariantInstanceTypeMlC44xlarge, + ProductionVariantInstanceTypeMlC48xlarge, + ProductionVariantInstanceTypeMlP2Xlarge, + ProductionVariantInstanceTypeMlP28xlarge, + ProductionVariantInstanceTypeMlP216xlarge, + ProductionVariantInstanceTypeMlP32xlarge, + ProductionVariantInstanceTypeMlP38xlarge, + ProductionVariantInstanceTypeMlP316xlarge, + ProductionVariantInstanceTypeMlC5Large, + ProductionVariantInstanceTypeMlC5Xlarge, + ProductionVariantInstanceTypeMlC52xlarge, + ProductionVariantInstanceTypeMlC54xlarge, + ProductionVariantInstanceTypeMlC59xlarge, + ProductionVariantInstanceTypeMlC518xlarge, + ProductionVariantInstanceTypeMlC5dLarge, + ProductionVariantInstanceTypeMlC5dXlarge, + ProductionVariantInstanceTypeMlC5d2xlarge, + ProductionVariantInstanceTypeMlC5d4xlarge, + ProductionVariantInstanceTypeMlC5d9xlarge, + ProductionVariantInstanceTypeMlC5d18xlarge, + ProductionVariantInstanceTypeMlG4dnXlarge, + ProductionVariantInstanceTypeMlG4dn2xlarge, + ProductionVariantInstanceTypeMlG4dn4xlarge, + ProductionVariantInstanceTypeMlG4dn8xlarge, + ProductionVariantInstanceTypeMlG4dn12xlarge, + ProductionVariantInstanceTypeMlG4dn16xlarge, + ProductionVariantInstanceTypeMlR5Large, + ProductionVariantInstanceTypeMlR5Xlarge, + ProductionVariantInstanceTypeMlR52xlarge, + ProductionVariantInstanceTypeMlR54xlarge, + ProductionVariantInstanceTypeMlR512xlarge, + ProductionVariantInstanceTypeMlR524xlarge, + ProductionVariantInstanceTypeMlR5dLarge, + ProductionVariantInstanceTypeMlR5dXlarge, + ProductionVariantInstanceTypeMlR5d2xlarge, + ProductionVariantInstanceTypeMlR5d4xlarge, + ProductionVariantInstanceTypeMlR5d12xlarge, + ProductionVariantInstanceTypeMlR5d24xlarge, + ProductionVariantInstanceTypeMlInf1Xlarge, + ProductionVariantInstanceTypeMlInf12xlarge, + ProductionVariantInstanceTypeMlInf16xlarge, + ProductionVariantInstanceTypeMlInf124xlarge, + } +} + const ( // RecordWrapperNone is a RecordWrapper enum value RecordWrapperNone = "None" @@ -47530,6 +50954,14 @@ const ( RecordWrapperRecordIo = "RecordIO" ) +// RecordWrapper_Values returns all elements of the RecordWrapper enum +func RecordWrapper_Values() []string { + return []string{ + RecordWrapperNone, + RecordWrapperRecordIo, + } +} + const ( // ResourceTypeTrainingJob is a ResourceType enum value ResourceTypeTrainingJob = "TrainingJob" @@ -47544,6 +50976,16 @@ const ( ResourceTypeExperimentTrialComponent = "ExperimentTrialComponent" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeTrainingJob, + ResourceTypeExperiment, + ResourceTypeExperimentTrial, + ResourceTypeExperimentTrialComponent, + } +} + const ( // RetentionTypeRetain is a RetentionType enum value RetentionTypeRetain = "Retain" @@ -47552,6 +50994,14 @@ const ( RetentionTypeDelete = "Delete" ) +// RetentionType_Values returns all elements of the RetentionType enum +func RetentionType_Values() []string { + return []string{ + RetentionTypeRetain, + RetentionTypeDelete, + } +} + const ( // RootAccessEnabled is a RootAccess enum value RootAccessEnabled = "Enabled" @@ -47560,6 +51010,14 @@ const ( RootAccessDisabled = "Disabled" ) +// RootAccess_Values returns all elements of the RootAccess enum +func RootAccess_Values() []string { + return []string{ + RootAccessEnabled, + RootAccessDisabled, + } +} + const ( // RuleEvaluationStatusInProgress is a RuleEvaluationStatus enum value RuleEvaluationStatusInProgress = "InProgress" @@ -47580,6 +51038,18 @@ const ( RuleEvaluationStatusStopped = "Stopped" ) +// RuleEvaluationStatus_Values returns all elements of the RuleEvaluationStatus enum +func RuleEvaluationStatus_Values() []string { + return []string{ + RuleEvaluationStatusInProgress, + RuleEvaluationStatusNoIssuesFound, + RuleEvaluationStatusIssuesFound, + RuleEvaluationStatusError, + RuleEvaluationStatusStopping, + RuleEvaluationStatusStopped, + } +} + const ( // S3DataDistributionFullyReplicated is a S3DataDistribution enum value S3DataDistributionFullyReplicated = "FullyReplicated" @@ -47588,6 +51058,14 @@ const ( S3DataDistributionShardedByS3key = "ShardedByS3Key" ) +// S3DataDistribution_Values returns all elements of the S3DataDistribution enum +func S3DataDistribution_Values() []string { + return []string{ + S3DataDistributionFullyReplicated, + S3DataDistributionShardedByS3key, + } +} + const ( // S3DataTypeManifestFile is a S3DataType enum value S3DataTypeManifestFile = "ManifestFile" @@ -47599,6 +51077,15 @@ const ( S3DataTypeAugmentedManifestFile = "AugmentedManifestFile" ) +// S3DataType_Values returns all elements of the S3DataType enum +func S3DataType_Values() []string { + return []string{ + S3DataTypeManifestFile, + S3DataTypeS3prefix, + S3DataTypeAugmentedManifestFile, + } +} + const ( // ScheduleStatusPending is a ScheduleStatus enum value ScheduleStatusPending = "Pending" @@ -47613,6 +51100,16 @@ const ( ScheduleStatusStopped = "Stopped" ) +// ScheduleStatus_Values returns all elements of the ScheduleStatus enum +func ScheduleStatus_Values() []string { + return []string{ + ScheduleStatusPending, + ScheduleStatusFailed, + ScheduleStatusScheduled, + ScheduleStatusStopped, + } +} + const ( // SearchSortOrderAscending is a SearchSortOrder enum value SearchSortOrderAscending = "Ascending" @@ -47621,6 +51118,14 @@ const ( SearchSortOrderDescending = "Descending" ) +// SearchSortOrder_Values returns all elements of the SearchSortOrder enum +func SearchSortOrder_Values() []string { + return []string{ + SearchSortOrderAscending, + SearchSortOrderDescending, + } +} + const ( // SecondaryStatusStarting is a SecondaryStatus enum value SecondaryStatusStarting = "Starting" @@ -47665,6 +51170,26 @@ const ( SecondaryStatusMaxWaitTimeExceeded = "MaxWaitTimeExceeded" ) +// SecondaryStatus_Values returns all elements of the SecondaryStatus enum +func SecondaryStatus_Values() []string { + return []string{ + SecondaryStatusStarting, + SecondaryStatusLaunchingMlinstances, + SecondaryStatusPreparingTrainingStack, + SecondaryStatusDownloading, + SecondaryStatusDownloadingTrainingImage, + SecondaryStatusTraining, + SecondaryStatusUploading, + SecondaryStatusStopping, + SecondaryStatusStopped, + SecondaryStatusMaxRuntimeExceeded, + SecondaryStatusCompleted, + SecondaryStatusFailed, + SecondaryStatusInterrupted, + SecondaryStatusMaxWaitTimeExceeded, + } +} + const ( // SortByName is a SortBy enum value SortByName = "Name" @@ -47676,6 +51201,15 @@ const ( SortByStatus = "Status" ) +// SortBy_Values returns all elements of the SortBy enum +func SortBy_Values() []string { + return []string{ + SortByName, + SortByCreationTime, + SortByStatus, + } +} + const ( // SortExperimentsByName is a SortExperimentsBy enum value SortExperimentsByName = "Name" @@ -47684,6 +51218,14 @@ const ( SortExperimentsByCreationTime = "CreationTime" ) +// SortExperimentsBy_Values returns all elements of the SortExperimentsBy enum +func SortExperimentsBy_Values() []string { + return []string{ + SortExperimentsByName, + SortExperimentsByCreationTime, + } +} + const ( // SortOrderAscending is a SortOrder enum value SortOrderAscending = "Ascending" @@ -47692,6 +51234,14 @@ const ( SortOrderDescending = "Descending" ) +// SortOrder_Values returns all elements of the SortOrder enum +func SortOrder_Values() []string { + return []string{ + SortOrderAscending, + SortOrderDescending, + } +} + const ( // SortTrialComponentsByName is a SortTrialComponentsBy enum value SortTrialComponentsByName = "Name" @@ -47700,6 +51250,14 @@ const ( SortTrialComponentsByCreationTime = "CreationTime" ) +// SortTrialComponentsBy_Values returns all elements of the SortTrialComponentsBy enum +func SortTrialComponentsBy_Values() []string { + return []string{ + SortTrialComponentsByName, + SortTrialComponentsByCreationTime, + } +} + const ( // SortTrialsByName is a SortTrialsBy enum value SortTrialsByName = "Name" @@ -47708,6 +51266,14 @@ const ( SortTrialsByCreationTime = "CreationTime" ) +// SortTrialsBy_Values returns all elements of the SortTrialsBy enum +func SortTrialsBy_Values() []string { + return []string{ + SortTrialsByName, + SortTrialsByCreationTime, + } +} + const ( // SplitTypeNone is a SplitType enum value SplitTypeNone = "None" @@ -47722,6 +51288,16 @@ const ( SplitTypeTfrecord = "TFRecord" ) +// SplitType_Values returns all elements of the SplitType enum +func SplitType_Values() []string { + return []string{ + SplitTypeNone, + SplitTypeLine, + SplitTypeRecordIo, + SplitTypeTfrecord, + } +} + const ( // TargetDeviceLambda is a TargetDevice enum value TargetDeviceLambda = "lambda" @@ -47744,6 +51320,9 @@ const ( // TargetDeviceMlP3 is a TargetDevice enum value TargetDeviceMlP3 = "ml_p3" + // TargetDeviceMlG4dn is a TargetDevice enum value + TargetDeviceMlG4dn = "ml_g4dn" + // TargetDeviceMlInf1 is a TargetDevice enum value TargetDeviceMlInf1 = "ml_inf1" @@ -47791,8 +51370,110 @@ const ( // TargetDeviceAmbaCv22 is a TargetDevice enum value TargetDeviceAmbaCv22 = "amba_cv22" + + // TargetDeviceX86Win32 is a TargetDevice enum value + TargetDeviceX86Win32 = "x86_win32" + + // TargetDeviceX86Win64 is a TargetDevice enum value + TargetDeviceX86Win64 = "x86_win64" +) + +// TargetDevice_Values returns all elements of the TargetDevice enum +func TargetDevice_Values() []string { + return []string{ + TargetDeviceLambda, + TargetDeviceMlM4, + TargetDeviceMlM5, + TargetDeviceMlC4, + TargetDeviceMlC5, + TargetDeviceMlP2, + TargetDeviceMlP3, + TargetDeviceMlG4dn, + TargetDeviceMlInf1, + TargetDeviceJetsonTx1, + TargetDeviceJetsonTx2, + TargetDeviceJetsonNano, + TargetDeviceJetsonXavier, + TargetDeviceRasp3b, + TargetDeviceImx8qm, + TargetDeviceDeeplens, + TargetDeviceRk3399, + TargetDeviceRk3288, + TargetDeviceAisage, + TargetDeviceSbeC, + TargetDeviceQcs605, + TargetDeviceQcs603, + TargetDeviceSitaraAm57x, + TargetDeviceAmbaCv22, + TargetDeviceX86Win32, + TargetDeviceX86Win64, + } +} + +const ( + // TargetPlatformAcceleratorIntelGraphics is a TargetPlatformAccelerator enum value + TargetPlatformAcceleratorIntelGraphics = "INTEL_GRAPHICS" + + // TargetPlatformAcceleratorMali is a TargetPlatformAccelerator enum value + TargetPlatformAcceleratorMali = "MALI" + + // TargetPlatformAcceleratorNvidia is a TargetPlatformAccelerator enum value + TargetPlatformAcceleratorNvidia = "NVIDIA" +) + +// TargetPlatformAccelerator_Values returns all elements of the TargetPlatformAccelerator enum +func TargetPlatformAccelerator_Values() []string { + return []string{ + TargetPlatformAcceleratorIntelGraphics, + TargetPlatformAcceleratorMali, + TargetPlatformAcceleratorNvidia, + } +} + +const ( + // TargetPlatformArchX8664 is a TargetPlatformArch enum value + TargetPlatformArchX8664 = "X86_64" + + // TargetPlatformArchX86 is a TargetPlatformArch enum value + TargetPlatformArchX86 = "X86" + + // TargetPlatformArchArm64 is a TargetPlatformArch enum value + TargetPlatformArchArm64 = "ARM64" + + // TargetPlatformArchArmEabi is a TargetPlatformArch enum value + TargetPlatformArchArmEabi = "ARM_EABI" + + // TargetPlatformArchArmEabihf is a TargetPlatformArch enum value + TargetPlatformArchArmEabihf = "ARM_EABIHF" +) + +// TargetPlatformArch_Values returns all elements of the TargetPlatformArch enum +func TargetPlatformArch_Values() []string { + return []string{ + TargetPlatformArchX8664, + TargetPlatformArchX86, + TargetPlatformArchArm64, + TargetPlatformArchArmEabi, + TargetPlatformArchArmEabihf, + } +} + +const ( + // TargetPlatformOsAndroid is a TargetPlatformOs enum value + TargetPlatformOsAndroid = "ANDROID" + + // TargetPlatformOsLinux is a TargetPlatformOs enum value + TargetPlatformOsLinux = "LINUX" ) +// TargetPlatformOs_Values returns all elements of the TargetPlatformOs enum +func TargetPlatformOs_Values() []string { + return []string{ + TargetPlatformOsAndroid, + TargetPlatformOsLinux, + } +} + const ( // TrainingInputModePipe is a TrainingInputMode enum value TrainingInputModePipe = "Pipe" @@ -47801,6 +51482,14 @@ const ( TrainingInputModeFile = "File" ) +// TrainingInputMode_Values returns all elements of the TrainingInputMode enum +func TrainingInputMode_Values() []string { + return []string{ + TrainingInputModePipe, + TrainingInputModeFile, + } +} + const ( // TrainingInstanceTypeMlM4Xlarge is a TrainingInstanceType enum value TrainingInstanceTypeMlM4Xlarge = "ml.m4.xlarge" @@ -47917,6 +51606,50 @@ const ( TrainingInstanceTypeMlC5n18xlarge = "ml.c5n.18xlarge" ) +// TrainingInstanceType_Values returns all elements of the TrainingInstanceType enum +func TrainingInstanceType_Values() []string { + return []string{ + TrainingInstanceTypeMlM4Xlarge, + TrainingInstanceTypeMlM42xlarge, + TrainingInstanceTypeMlM44xlarge, + TrainingInstanceTypeMlM410xlarge, + TrainingInstanceTypeMlM416xlarge, + TrainingInstanceTypeMlG4dnXlarge, + TrainingInstanceTypeMlG4dn2xlarge, + TrainingInstanceTypeMlG4dn4xlarge, + TrainingInstanceTypeMlG4dn8xlarge, + TrainingInstanceTypeMlG4dn12xlarge, + TrainingInstanceTypeMlG4dn16xlarge, + TrainingInstanceTypeMlM5Large, + TrainingInstanceTypeMlM5Xlarge, + TrainingInstanceTypeMlM52xlarge, + TrainingInstanceTypeMlM54xlarge, + TrainingInstanceTypeMlM512xlarge, + TrainingInstanceTypeMlM524xlarge, + TrainingInstanceTypeMlC4Xlarge, + TrainingInstanceTypeMlC42xlarge, + TrainingInstanceTypeMlC44xlarge, + TrainingInstanceTypeMlC48xlarge, + TrainingInstanceTypeMlP2Xlarge, + TrainingInstanceTypeMlP28xlarge, + TrainingInstanceTypeMlP216xlarge, + TrainingInstanceTypeMlP32xlarge, + TrainingInstanceTypeMlP38xlarge, + TrainingInstanceTypeMlP316xlarge, + TrainingInstanceTypeMlP3dn24xlarge, + TrainingInstanceTypeMlC5Xlarge, + TrainingInstanceTypeMlC52xlarge, + TrainingInstanceTypeMlC54xlarge, + TrainingInstanceTypeMlC59xlarge, + TrainingInstanceTypeMlC518xlarge, + TrainingInstanceTypeMlC5nXlarge, + TrainingInstanceTypeMlC5n2xlarge, + TrainingInstanceTypeMlC5n4xlarge, + TrainingInstanceTypeMlC5n9xlarge, + TrainingInstanceTypeMlC5n18xlarge, + } +} + const ( // TrainingJobEarlyStoppingTypeOff is a TrainingJobEarlyStoppingType enum value TrainingJobEarlyStoppingTypeOff = "Off" @@ -47925,6 +51658,14 @@ const ( TrainingJobEarlyStoppingTypeAuto = "Auto" ) +// TrainingJobEarlyStoppingType_Values returns all elements of the TrainingJobEarlyStoppingType enum +func TrainingJobEarlyStoppingType_Values() []string { + return []string{ + TrainingJobEarlyStoppingTypeOff, + TrainingJobEarlyStoppingTypeAuto, + } +} + const ( // TrainingJobSortByOptionsName is a TrainingJobSortByOptions enum value TrainingJobSortByOptionsName = "Name" @@ -47939,6 +51680,16 @@ const ( TrainingJobSortByOptionsFinalObjectiveMetricValue = "FinalObjectiveMetricValue" ) +// TrainingJobSortByOptions_Values returns all elements of the TrainingJobSortByOptions enum +func TrainingJobSortByOptions_Values() []string { + return []string{ + TrainingJobSortByOptionsName, + TrainingJobSortByOptionsCreationTime, + TrainingJobSortByOptionsStatus, + TrainingJobSortByOptionsFinalObjectiveMetricValue, + } +} + const ( // TrainingJobStatusInProgress is a TrainingJobStatus enum value TrainingJobStatusInProgress = "InProgress" @@ -47956,6 +51707,17 @@ const ( TrainingJobStatusStopped = "Stopped" ) +// TrainingJobStatus_Values returns all elements of the TrainingJobStatus enum +func TrainingJobStatus_Values() []string { + return []string{ + TrainingJobStatusInProgress, + TrainingJobStatusCompleted, + TrainingJobStatusFailed, + TrainingJobStatusStopping, + TrainingJobStatusStopped, + } +} + const ( // TransformInstanceTypeMlM4Xlarge is a TransformInstanceType enum value TransformInstanceTypeMlM4Xlarge = "ml.m4.xlarge" @@ -48036,6 +51798,38 @@ const ( TransformInstanceTypeMlM524xlarge = "ml.m5.24xlarge" ) +// TransformInstanceType_Values returns all elements of the TransformInstanceType enum +func TransformInstanceType_Values() []string { + return []string{ + TransformInstanceTypeMlM4Xlarge, + TransformInstanceTypeMlM42xlarge, + TransformInstanceTypeMlM44xlarge, + TransformInstanceTypeMlM410xlarge, + TransformInstanceTypeMlM416xlarge, + TransformInstanceTypeMlC4Xlarge, + TransformInstanceTypeMlC42xlarge, + TransformInstanceTypeMlC44xlarge, + TransformInstanceTypeMlC48xlarge, + TransformInstanceTypeMlP2Xlarge, + TransformInstanceTypeMlP28xlarge, + TransformInstanceTypeMlP216xlarge, + TransformInstanceTypeMlP32xlarge, + TransformInstanceTypeMlP38xlarge, + TransformInstanceTypeMlP316xlarge, + TransformInstanceTypeMlC5Xlarge, + TransformInstanceTypeMlC52xlarge, + TransformInstanceTypeMlC54xlarge, + TransformInstanceTypeMlC59xlarge, + TransformInstanceTypeMlC518xlarge, + TransformInstanceTypeMlM5Large, + TransformInstanceTypeMlM5Xlarge, + TransformInstanceTypeMlM52xlarge, + TransformInstanceTypeMlM54xlarge, + TransformInstanceTypeMlM512xlarge, + TransformInstanceTypeMlM524xlarge, + } +} + const ( // TransformJobStatusInProgress is a TransformJobStatus enum value TransformJobStatusInProgress = "InProgress" @@ -48053,6 +51847,17 @@ const ( TransformJobStatusStopped = "Stopped" ) +// TransformJobStatus_Values returns all elements of the TransformJobStatus enum +func TransformJobStatus_Values() []string { + return []string{ + TransformJobStatusInProgress, + TransformJobStatusCompleted, + TransformJobStatusFailed, + TransformJobStatusStopping, + TransformJobStatusStopped, + } +} + const ( // TrialComponentPrimaryStatusInProgress is a TrialComponentPrimaryStatus enum value TrialComponentPrimaryStatusInProgress = "InProgress" @@ -48070,6 +51875,17 @@ const ( TrialComponentPrimaryStatusStopped = "Stopped" ) +// TrialComponentPrimaryStatus_Values returns all elements of the TrialComponentPrimaryStatus enum +func TrialComponentPrimaryStatus_Values() []string { + return []string{ + TrialComponentPrimaryStatusInProgress, + TrialComponentPrimaryStatusCompleted, + TrialComponentPrimaryStatusFailed, + TrialComponentPrimaryStatusStopping, + TrialComponentPrimaryStatusStopped, + } +} + const ( // UserProfileSortKeyCreationTime is a UserProfileSortKey enum value UserProfileSortKeyCreationTime = "CreationTime" @@ -48078,6 +51894,14 @@ const ( UserProfileSortKeyLastModifiedTime = "LastModifiedTime" ) +// UserProfileSortKey_Values returns all elements of the UserProfileSortKey enum +func UserProfileSortKey_Values() []string { + return []string{ + UserProfileSortKeyCreationTime, + UserProfileSortKeyLastModifiedTime, + } +} + const ( // UserProfileStatusDeleting is a UserProfileStatus enum value UserProfileStatusDeleting = "Deleting" @@ -48092,6 +51916,16 @@ const ( UserProfileStatusPending = "Pending" ) +// UserProfileStatus_Values returns all elements of the UserProfileStatus enum +func UserProfileStatus_Values() []string { + return []string{ + UserProfileStatusDeleting, + UserProfileStatusFailed, + UserProfileStatusInService, + UserProfileStatusPending, + } +} + const ( // VariantPropertyTypeDesiredInstanceCount is a VariantPropertyType enum value VariantPropertyTypeDesiredInstanceCount = "DesiredInstanceCount" @@ -48102,3 +51936,12 @@ const ( // VariantPropertyTypeDataCaptureConfig is a VariantPropertyType enum value VariantPropertyTypeDataCaptureConfig = "DataCaptureConfig" ) + +// VariantPropertyType_Values returns all elements of the VariantPropertyType enum +func VariantPropertyType_Values() []string { + return []string{ + VariantPropertyTypeDesiredInstanceCount, + VariantPropertyTypeDesiredWeight, + VariantPropertyTypeDataCaptureConfig, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/api.go b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/api.go index 7dfecc65803..b89f513d5cc 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/api.go @@ -58,28 +58,28 @@ func (c *SecretsManager) CancelRotateSecretRequest(input *CancelRotateSecretInpu // CancelRotateSecret API operation for AWS Secrets Manager. // // Disables automatic scheduled rotation and cancels the rotation of a secret -// if one is currently in progress. +// if currently in progress. // // To re-enable scheduled rotation, call RotateSecret with AutomaticallyRotateAfterDays -// set to a value greater than 0. This will immediately rotate your secret and -// then enable the automatic schedule. +// set to a value greater than 0. This immediately rotates your secret and then +// enables the automatic schedule. // -// If you cancel a rotation that is in progress, it can leave the VersionStage -// labels in an unexpected state. Depending on what step of the rotation was -// in progress, you might need to remove the staging label AWSPENDING from the -// partially created version, specified by the VersionId response value. You -// should also evaluate the partially rotated new version to see if it should -// be deleted, which you can do by removing all staging labels from the new -// version's VersionStage field. +// If you cancel a rotation while in progress, it can leave the VersionStage +// labels in an unexpected state. Depending on the step of the rotation in progress, +// you might need to remove the staging label AWSPENDING from the partially +// created version, specified by the VersionId response value. You should also +// evaluate the partially rotated new version to see if it should be deleted, +// which you can do by removing all staging labels from the new version VersionStage +// field. // // To successfully start a rotation, the staging label AWSPENDING must be in // one of the following states: // -// * Not be attached to any version at all +// * Not attached to any version at all // // * Attached to the same version as the staging label AWSCURRENT // -// If the staging label AWSPENDING is attached to a different version than the +// If the staging label AWSPENDING attached to a different version than the // version with AWSCURRENT then the attempt to rotate fails. // // Minimum permissions @@ -205,7 +205,7 @@ func (c *SecretsManager) CreateSecretRequest(input *CreateSecretInput) (req *req // labels" that identify where the version is in the rotation cycle. The SecretVersionsToStages // field of the secret contains the mapping of staging labels to the active // versions of the secret. Versions without a staging label are considered deprecated -// and are not included in the list. +// and not included in the list. // // You provide the secret data to be encrypted by putting text in either the // SecretString parameter or binary data in the SecretBinary parameter, but @@ -213,20 +213,19 @@ func (c *SecretsManager) CreateSecretRequest(input *CreateSecretInput) (req *req // also creates an initial secret version and automatically attaches the staging // label AWSCURRENT to the new version. // -// * If you call an operation that needs to encrypt or decrypt the SecretString -// or SecretBinary for a secret in the same account as the calling user and -// that secret doesn't specify a AWS KMS encryption key, Secrets Manager -// uses the account's default AWS managed customer master key (CMK) with -// the alias aws/secretsmanager. If this key doesn't already exist in your -// account then Secrets Manager creates it for you automatically. All users -// and roles in the same AWS account automatically have access to use the -// default CMK. Note that if an Secrets Manager API call results in AWS having -// to create the account's AWS-managed CMK, it can result in a one-time significant -// delay in returning the result. -// -// * If the secret is in a different AWS account from the credentials calling -// an API that requires encryption or decryption of the secret value then -// you must create and use a custom AWS KMS CMK because you can't access +// * If you call an operation to encrypt or decrypt the SecretString or SecretBinary +// for a secret in the same account as the calling user and that secret doesn't +// specify a AWS KMS encryption key, Secrets Manager uses the account's default +// AWS managed customer master key (CMK) with the alias aws/secretsmanager. +// If this key doesn't already exist in your account then Secrets Manager +// creates it for you automatically. All users and roles in the same AWS +// account automatically have access to use the default CMK. Note that if +// an Secrets Manager API call results in AWS creating the account's AWS-managed +// CMK, it can result in a one-time significant delay in returning the result. +// +// * If the secret resides in a different AWS account from the credentials +// calling an API that requires encryption or decryption of the secret value +// then you must create and use a custom AWS KMS CMK because you can't access // the default CMK for the account using credentials from a different AWS // account. Store the ARN of the CMK in the secret when you create the secret // or when you update it by including it in the KMSKeyId. If you call an @@ -243,10 +242,10 @@ func (c *SecretsManager) CreateSecretRequest(input *CreateSecretInput) (req *req // // * kms:GenerateDataKey - needed only if you use a customer-managed AWS // KMS key to encrypt the secret. You do not need this permission to use -// the account's default AWS managed CMK for Secrets Manager. +// the account default AWS managed CMK for Secrets Manager. // // * kms:Decrypt - needed only if you use a customer-managed AWS KMS key -// to encrypt the secret. You do not need this permission to use the account's +// to encrypt the secret. You do not need this permission to use the account // default AWS managed CMK for Secrets Manager. // // * secretsmanager:TagResource - needed only if you include the Tags parameter. @@ -384,7 +383,7 @@ func (c *SecretsManager) DeleteResourcePolicyRequest(input *DeleteResourcePolicy // DeleteResourcePolicy API operation for AWS Secrets Manager. // -// Deletes the resource-based permission policy that's attached to the secret. +// Deletes the resource-based permission policy attached to the secret. // // Minimum permissions // @@ -628,7 +627,7 @@ func (c *SecretsManager) DescribeSecretRequest(input *DescribeSecretInput) (req // DescribeSecret API operation for AWS Secrets Manager. // // Retrieves the details of a secret. It does not include the encrypted fields. -// Only those fields that are populated with a value are returned in the response. +// Secrets Manager only returns fields populated with a value in the response. // // Minimum permissions // @@ -831,10 +830,10 @@ func (c *SecretsManager) GetResourcePolicyRequest(input *GetResourcePolicyInput) // GetResourcePolicy API operation for AWS Secrets Manager. // -// Retrieves the JSON text of the resource-based policy document that's attached -// to the specified secret. The JSON request string input and response output -// are shown formatted with white space and line breaks for better readability. -// Submit your input as a single line JSON string. +// Retrieves the JSON text of the resource-based policy document attached to +// the specified secret. The JSON request string input and response output displays +// formatted code with white space and line breaks for better readability. Submit +// your input as a single line JSON string. // // Minimum permissions // @@ -846,8 +845,7 @@ func (c *SecretsManager) GetResourcePolicyRequest(input *GetResourcePolicyInput) // // * To attach a resource policy to a secret, use PutResourcePolicy. // -// * To delete the resource-based policy that's attached to a secret, use -// DeleteResourcePolicy. +// * To delete the resource-based policy attached to a secret, use DeleteResourcePolicy. // // * To list all of the currently available secrets, use ListSecrets. // @@ -1077,7 +1075,7 @@ func (c *SecretsManager) ListSecretVersionIdsRequest(input *ListSecretVersionIds // // Always check the NextToken response parameter when calling any of the List* // operations. These operations can occasionally return an empty or shorter -// than expected list of results even when there are more results available. +// than expected list of results even when there more results become available. // When this happens, the NextToken response parameter contains a value to pass // to the next call to the same API to request the next part of the list. // @@ -1239,7 +1237,7 @@ func (c *SecretsManager) ListSecretsRequest(input *ListSecretsInput) (req *reque // // Always check the NextToken response parameter when calling any of the List* // operations. These operations can occasionally return an empty or shorter -// than expected list of results even when there are more results available. +// than expected list of results even when there more results become available. // When this happens, the NextToken response parameter contains a value to pass // to the next call to the same API to request the next part of the list. // @@ -1408,7 +1406,7 @@ func (c *SecretsManager) PutResourcePolicyRequest(input *PutResourcePolicyInput) // // Related operations // -// * To retrieve the resource policy that's attached to a secret, use GetResourcePolicy. +// * To retrieve the resource policy attached to a secret, use GetResourcePolicy. // // * To delete the resource-based policy that's attached to a secret, use // DeleteResourcePolicy. @@ -1448,6 +1446,9 @@ func (c *SecretsManager) PutResourcePolicyRequest(input *PutResourcePolicyInput) // Lambda function ARN configured and you didn't include such an ARN as a // parameter in this call. // +// * PublicPolicyException +// The resource policy did not prevent broad access to the secret. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/PutResourcePolicy func (c *SecretsManager) PutResourcePolicy(input *PutResourcePolicyInput) (*PutResourcePolicyOutput, error) { req, out := c.PutResourcePolicyRequest(input) @@ -1542,20 +1543,19 @@ func (c *SecretsManager) PutSecretValueRequest(input *PutSecretValueInput) (req // However, if the secret data is different, then the operation fails because // you cannot modify an existing version; you can only create new ones. // -// * If you call an operation that needs to encrypt or decrypt the SecretString -// or SecretBinary for a secret in the same account as the calling user and -// that secret doesn't specify a AWS KMS encryption key, Secrets Manager -// uses the account's default AWS managed customer master key (CMK) with -// the alias aws/secretsmanager. If this key doesn't already exist in your -// account then Secrets Manager creates it for you automatically. All users -// and roles in the same AWS account automatically have access to use the -// default CMK. Note that if an Secrets Manager API call results in AWS having -// to create the account's AWS-managed CMK, it can result in a one-time significant -// delay in returning the result. -// -// * If the secret is in a different AWS account from the credentials calling -// an API that requires encryption or decryption of the secret value then -// you must create and use a custom AWS KMS CMK because you can't access +// * If you call an operation to encrypt or decrypt the SecretString or SecretBinary +// for a secret in the same account as the calling user and that secret doesn't +// specify a AWS KMS encryption key, Secrets Manager uses the account's default +// AWS managed customer master key (CMK) with the alias aws/secretsmanager. +// If this key doesn't already exist in your account then Secrets Manager +// creates it for you automatically. All users and roles in the same AWS +// account automatically have access to use the default CMK. Note that if +// an Secrets Manager API call results in AWS creating the account's AWS-managed +// CMK, it can result in a one-time significant delay in returning the result. +// +// * If the secret resides in a different AWS account from the credentials +// calling an API that requires encryption or decryption of the secret value +// then you must create and use a custom AWS KMS CMK because you can't access // the default CMK for the account using credentials from a different AWS // account. Store the ARN of the CMK in the secret when you create the secret // or when you update it by including it in the KMSKeyId. If you call an @@ -1821,7 +1821,7 @@ func (c *SecretsManager) RotateSecretRequest(input *RotateSecretInput) (req *req // (https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html) // in the AWS Secrets Manager User Guide. // -// Secrets Manager schedules the next rotation when the previous one is complete. +// Secrets Manager schedules the next rotation when the previous one completes. // Secrets Manager schedules the date by adding the rotation interval (number // of days) to the actual date of the last rotation. The service chooses the // hour within that 24-hour date window randomly. The minute is also chosen @@ -1836,10 +1836,9 @@ func (c *SecretsManager) RotateSecretRequest(input *RotateSecretInput) (req *req // // * The AWSPENDING staging label is not attached to any version of the secret. // -// If instead the AWSPENDING staging label is present but is not attached to -// the same version as AWSCURRENT then any later invocation of RotateSecret -// assumes that a previous rotation request is still in progress and returns -// an error. +// If the AWSPENDING staging label is present but not attached to the same version +// as AWSCURRENT then any later invocation of RotateSecret assumes that a previous +// rotation request is still in progress and returns an error. // // Minimum permissions // @@ -1973,14 +1972,14 @@ func (c *SecretsManager) TagResourceRequest(input *TagResourceInput) (req *reque // // * Tag keys and values are case sensitive. // -// * Do not use the aws: prefix in your tag names or values because it is -// reserved for AWS use. You can't edit or delete tag names or values with -// this prefix. Tags with this prefix do not count against your tags per -// secret limit. +// * Do not use the aws: prefix in your tag names or values because AWS reserves +// it for AWS use. You can't edit or delete tag names or values with this +// prefix. Tags with this prefix do not count against your tags per secret +// limit. // -// * If your tagging schema will be used across multiple services and resources, -// remember that other services might have restrictions on allowed characters. -// Generally allowed characters are: letters, spaces, and numbers representable +// * If you use your tagging schema across multiple services and resources, +// remember other services might have restrictions on allowed characters. +// Generally allowed characters: letters, spaces, and numbers representable // in UTF-8, plus the following special characters: + - = . _ : / @. // // If you use tags as part of your security strategy, then adding or removing @@ -2236,20 +2235,19 @@ func (c *SecretsManager) UpdateSecretRequest(input *UpdateSecretInput) (req *req // Secrets Manager automatically attaches the staging label AWSCURRENT to // the new version. // -// * If you call an operation that needs to encrypt or decrypt the SecretString -// or SecretBinary for a secret in the same account as the calling user and -// that secret doesn't specify a AWS KMS encryption key, Secrets Manager -// uses the account's default AWS managed customer master key (CMK) with -// the alias aws/secretsmanager. If this key doesn't already exist in your -// account then Secrets Manager creates it for you automatically. All users -// and roles in the same AWS account automatically have access to use the -// default CMK. Note that if an Secrets Manager API call results in AWS having -// to create the account's AWS-managed CMK, it can result in a one-time significant -// delay in returning the result. -// -// * If the secret is in a different AWS account from the credentials calling -// an API that requires encryption or decryption of the secret value then -// you must create and use a custom AWS KMS CMK because you can't access +// * If you call an operation to encrypt or decrypt the SecretString or SecretBinary +// for a secret in the same account as the calling user and that secret doesn't +// specify a AWS KMS encryption key, Secrets Manager uses the account's default +// AWS managed customer master key (CMK) with the alias aws/secretsmanager. +// If this key doesn't already exist in your account then Secrets Manager +// creates it for you automatically. All users and roles in the same AWS +// account automatically have access to use the default CMK. Note that if +// an Secrets Manager API call results in AWS creating the account's AWS-managed +// CMK, it can result in a one-time significant delay in returning the result. +// +// * If the secret resides in a different AWS account from the credentials +// calling an API that requires encryption or decryption of the secret value +// then you must create and use a custom AWS KMS CMK because you can't access // the default CMK for the account using credentials from a different AWS // account. Store the ARN of the CMK in the secret when you create the secret // or when you update it by including it in the KMSKeyId. If you call an @@ -2487,12 +2485,115 @@ func (c *SecretsManager) UpdateSecretVersionStageWithContext(ctx aws.Context, in return out, req.Send() } +const opValidateResourcePolicy = "ValidateResourcePolicy" + +// ValidateResourcePolicyRequest generates a "aws/request.Request" representing the +// client's request for the ValidateResourcePolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ValidateResourcePolicy for more information on using the ValidateResourcePolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ValidateResourcePolicyRequest method. +// req, resp := client.ValidateResourcePolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/ValidateResourcePolicy +func (c *SecretsManager) ValidateResourcePolicyRequest(input *ValidateResourcePolicyInput) (req *request.Request, output *ValidateResourcePolicyOutput) { + op := &request.Operation{ + Name: opValidateResourcePolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ValidateResourcePolicyInput{} + } + + output = &ValidateResourcePolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// ValidateResourcePolicy API operation for AWS Secrets Manager. +// +// Validates the JSON text of the resource-based policy document attached to +// the specified secret. The JSON request string input and response output displays +// formatted code with white space and line breaks for better readability. Submit +// your input as a single line JSON string. A resource-based policy is optional. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Secrets Manager's +// API operation ValidateResourcePolicy for usage and error information. +// +// Returned Error Types: +// * MalformedPolicyDocumentException +// The policy document that you provided isn't valid. +// +// * ResourceNotFoundException +// We can't find the resource that you asked for. +// +// * InvalidParameterException +// You provided an invalid value for a parameter. +// +// * InternalServiceError +// An error occurred on the server side. +// +// * InvalidRequestException +// You provided a parameter value that is not valid for the current state of +// the resource. +// +// Possible causes: +// +// * You tried to perform the operation on a secret that's currently marked +// deleted. +// +// * You tried to enable rotation on a secret that doesn't already have a +// Lambda function ARN configured and you didn't include such an ARN as a +// parameter in this call. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/ValidateResourcePolicy +func (c *SecretsManager) ValidateResourcePolicy(input *ValidateResourcePolicyInput) (*ValidateResourcePolicyOutput, error) { + req, out := c.ValidateResourcePolicyRequest(input) + return out, req.Send() +} + +// ValidateResourcePolicyWithContext is the same as ValidateResourcePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See ValidateResourcePolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SecretsManager) ValidateResourcePolicyWithContext(ctx aws.Context, input *ValidateResourcePolicyInput, opts ...request.Option) (*ValidateResourcePolicyOutput, error) { + req, out := c.ValidateResourcePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + type CancelRotateSecretInput struct { _ struct{} `type:"structure"` - // Specifies the secret for which you want to cancel a rotation request. You - // can specify either the Amazon Resource Name (ARN) or the friendly name of - // the secret. + // Specifies the secret to cancel a rotation request. You can specify either + // the Amazon Resource Name (ARN) or the friendly name of the secret. // // If you specify an ARN, we generally recommend that you specify a complete // ARN. You can specify a partial ARN too—for example, if you don’t include @@ -2504,7 +2605,12 @@ type CancelRotateSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -2551,11 +2657,11 @@ type CancelRotateSecretOutput struct { // The friendly name of the secret for which rotation was canceled. Name *string `min:"1" type:"string"` - // The unique identifier of the version of the secret that was created during - // the rotation. This version might not be complete, and should be evaluated - // for possible deletion. At the very least, you should remove the VersionStage - // value AWSPENDING to enable this version to be deleted. Failing to clean up - // a cancelled rotation can block you from successfully starting future rotations. + // The unique identifier of the version of the secret created during the rotation. + // This version might not be complete, and should be evaluated for possible + // deletion. At the very least, you should remove the VersionStage value AWSPENDING + // to enable this version to be deleted. Failing to clean up a cancelled rotation + // can block you from successfully starting future rotations. VersionId *string `min:"32" type:"string"` } @@ -2599,7 +2705,7 @@ type CreateSecretInput struct { // for you and includes it as the value for this parameter in the request. If // you don't use the SDK and instead generate a raw HTTP request to the Secrets // Manager service endpoint, then you must generate a ClientRequestToken yourself - // for the new version and include that value in the request. + // for the new version and include the value in the request. // // This value helps ensure idempotency. Secrets Manager uses this value to prevent // the accidental creation of duplicate versions if there are failures and retries @@ -2609,9 +2715,9 @@ type CreateSecretInput struct { // * If the ClientRequestToken value isn't already associated with a version // of the secret then a new version of the secret is created. // - // * If a version with this value already exists and that version's SecretString + // * If a version with this value already exists and the version SecretString // and SecretBinary values are the same as those in the request, then the - // request is ignored (the operation is idempotent). + // request is ignored. // // * If a version with this value already exists and that version's SecretString // and SecretBinary values are different from those in the request then the @@ -2638,9 +2744,9 @@ type CreateSecretInput struct { // you automatically the first time it needs to encrypt a version's SecretString // or SecretBinary fields. // - // You can use the account's default CMK to encrypt and decrypt only if you - // call this operation using credentials from the same account that owns the - // secret. If the secret is in a different account, then you must create a custom + // You can use the account default CMK to encrypt and decrypt only if you call + // this operation using credentials from the same account that owns the secret. + // If the secret resides in a different account, then you must create a custom // CMK and specify the ARN in this field. KmsKeyId *string `type:"string"` @@ -2649,10 +2755,10 @@ type CreateSecretInput struct { // The secret name must be ASCII letters, digits, or the following characters // : /_+=.@- // - // Don't end your secret name with a hyphen followed by six characters. If you - // do so, you risk confusion and unexpected results when searching for a secret - // by partial ARN. This is because Secrets Manager automatically adds a hyphen - // and six random characters at the end of the ARN. + // Do not end your secret name with a hyphen followed by six characters. If + // you do so, you risk confusion and unexpected results when searching for a + // secret by partial ARN. Secrets Manager automatically adds a hyphen and six + // random characters at the end of the ARN. // // Name is a required field Name *string `min:"1" type:"string" required:"true"` @@ -2688,7 +2794,7 @@ type CreateSecretInput struct { // JSON for Parameters (https://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#cli-using-param-json) // in the AWS CLI User Guide. For example: // - // [{"username":"bob"},{"password":"abc123xyz456"}] + // {"username":"bob","password":"abc123xyz456"} // // If your command-line tool or SDK requires quotation marks around the parameter, // you should use single quotes to avoid confusion with the double quotes required @@ -2729,14 +2835,14 @@ type CreateSecretInput struct { // // * Tag keys and values are case sensitive. // - // * Do not use the aws: prefix in your tag names or values because it is - // reserved for AWS use. You can't edit or delete tag names or values with - // this prefix. Tags with this prefix do not count against your tags per - // secret limit. + // * Do not use the aws: prefix in your tag names or values because AWS reserves + // it for AWS use. You can't edit or delete tag names or values with this + // prefix. Tags with this prefix do not count against your tags per secret + // limit. // - // * If your tagging schema will be used across multiple services and resources, - // remember that other services might have restrictions on allowed characters. - // Generally allowed characters are: letters, spaces, and numbers representable + // * If you use your tagging schema across multiple services and resources, + // remember other services might have restrictions on allowed characters. + // Generally allowed characters: letters, spaces, and numbers representable // in UTF-8, plus the following special characters: + - = . _ : / @. Tags []*Tag `type:"list"` } @@ -2838,8 +2944,8 @@ type CreateSecretOutput struct { // The friendly name of the secret that you just created. Name *string `min:"1" type:"string"` - // The unique identifier that's associated with the version of the secret you - // just created. + // The unique identifier associated with the version of the secret you just + // created. VersionId *string `min:"32" type:"string"` } @@ -2945,7 +3051,12 @@ type DeleteResourcePolicyInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -3055,7 +3166,12 @@ type DeleteSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -3165,7 +3281,12 @@ type DescribeSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -3209,6 +3330,9 @@ type DescribeSecretOutput struct { // The ARN of the secret. ARN *string `min:"20" type:"string"` + // The date that the secret was created. + CreatedDate *time.Time `type:"timestamp"` + // This value exists if the secret is scheduled for deletion. Some time after // the specified date and time, Secrets Manager deletes the secret and all of // its versions. @@ -3288,6 +3412,12 @@ func (s *DescribeSecretOutput) SetARN(v string) *DescribeSecretOutput { return s } +// SetCreatedDate sets the CreatedDate field's value. +func (s *DescribeSecretOutput) SetCreatedDate(v time.Time) *DescribeSecretOutput { + s.CreatedDate = &v + return s +} + // SetDeletedDate sets the DeletedDate field's value. func (s *DescribeSecretOutput) SetDeletedDate(v time.Time) *DescribeSecretOutput { s.DeletedDate = &v @@ -3425,6 +3555,52 @@ func (s *EncryptionFailure) RequestID() string { return s.RespMetadata.RequestID } +// Allows you to filter your list of secrets. +type Filter struct { + _ struct{} `type:"structure"` + + // Filters your list of secrets by a specific key. + Key *string `type:"string" enum:"FilterNameStringType"` + + // Filters your list of secrets by a specific value. + Values []*string `min:"1" type:"list"` +} + +// String returns the string representation +func (s Filter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Filter) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Filter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Filter"} + if s.Values != nil && len(s.Values) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Values", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKey sets the Key field's value. +func (s *Filter) SetKey(v string) *Filter { + s.Key = &v + return s +} + +// SetValues sets the Values field's value. +func (s *Filter) SetValues(v []*string) *Filter { + s.Values = v + return s +} + type GetRandomPasswordInput struct { _ struct{} `type:"structure"` @@ -3584,7 +3760,12 @@ type GetResourcePolicyInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -3687,7 +3868,12 @@ type GetSecretValueInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -4162,7 +4348,7 @@ type ListSecretVersionIdsInput struct { // deprecated and are subject to deletion by Secrets Manager as needed. IncludeDeprecated *bool `type:"boolean"` - // (Optional) Limits the number of results that you want to include in the response. + // (Optional) Limits the number of results you want to include in the response. // If you don't include this parameter, it defaults to a value that's specific // to the operation. If additional items exist beyond the maximum you specify, // the NextToken response element is present and has a value (isn't null). Include @@ -4174,9 +4360,9 @@ type ListSecretVersionIdsInput struct { MaxResults *int64 `min:"1" type:"integer"` // (Optional) Use this parameter in a request if you receive a NextToken response - // in a previous request that indicates that there's more output available. - // In a subsequent call, set it to the value of the previous call's NextToken - // response to indicate where the output should continue from. + // in a previous request indicating there's more output available. In a subsequent + // call, set it to the value of the previous call NextToken response to indicate + // where the output should continue from. NextToken *string `min:"1" type:"string"` // The identifier for the secret containing the versions you want to list. You @@ -4193,7 +4379,12 @@ type ListSecretVersionIdsInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -4272,8 +4463,8 @@ type ListSecretVersionIdsOutput struct { Name *string `min:"1" type:"string"` // If present in the response, this value indicates that there's more output - // available than what's included in the current response. This can occur even - // when the response includes no values at all, such as when you ask for a filtered + // available than included in the current response. This can occur even when + // the response includes no values at all, such as when you ask for a filtered // view of a very long list. Use this value in the NextToken request parameter // in a subsequent call to the operation to continue processing and get the // next part of the output. You should repeat this until the NextToken response @@ -4321,7 +4512,10 @@ func (s *ListSecretVersionIdsOutput) SetVersions(v []*SecretVersionsListEntry) * type ListSecretsInput struct { _ struct{} `type:"structure"` - // (Optional) Limits the number of results that you want to include in the response. + // Lists the secret request filters. + Filters []*Filter `type:"list"` + + // (Optional) Limits the number of results you want to include in the response. // If you don't include this parameter, it defaults to a value that's specific // to the operation. If additional items exist beyond the maximum you specify, // the NextToken response element is present and has a value (isn't null). Include @@ -4333,10 +4527,13 @@ type ListSecretsInput struct { MaxResults *int64 `min:"1" type:"integer"` // (Optional) Use this parameter in a request if you receive a NextToken response - // in a previous request that indicates that there's more output available. - // In a subsequent call, set it to the value of the previous call's NextToken - // response to indicate where the output should continue from. + // in a previous request indicating there's more output available. In a subsequent + // call, set it to the value of the previous call NextToken response to indicate + // where the output should continue from. NextToken *string `min:"1" type:"string"` + + // Lists secrets in the requested order. + SortOrder *string `type:"string" enum:"SortOrderType"` } // String returns the string representation @@ -4358,6 +4555,16 @@ func (s *ListSecretsInput) Validate() error { if s.NextToken != nil && len(*s.NextToken) < 1 { invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) } + if s.Filters != nil { + for i, v := range s.Filters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -4365,6 +4572,12 @@ func (s *ListSecretsInput) Validate() error { return nil } +// SetFilters sets the Filters field's value. +func (s *ListSecretsInput) SetFilters(v []*Filter) *ListSecretsInput { + s.Filters = v + return s +} + // SetMaxResults sets the MaxResults field's value. func (s *ListSecretsInput) SetMaxResults(v int64) *ListSecretsInput { s.MaxResults = &v @@ -4377,12 +4590,18 @@ func (s *ListSecretsInput) SetNextToken(v string) *ListSecretsInput { return s } +// SetSortOrder sets the SortOrder field's value. +func (s *ListSecretsInput) SetSortOrder(v string) *ListSecretsInput { + s.SortOrder = &v + return s +} + type ListSecretsOutput struct { _ struct{} `type:"structure"` // If present in the response, this value indicates that there's more output - // available than what's included in the current response. This can occur even - // when the response includes no values at all, such as when you ask for a filtered + // available than included in the current response. This can occur even when + // the response includes no values at all, such as when you ask for a filtered // view of a very long list. Use this value in the NextToken request parameter // in a subsequent call to the operation to continue processing and get the // next part of the output. You should repeat this until the NextToken response @@ -4527,9 +4746,69 @@ func (s *PreconditionNotMetException) RequestID() string { return s.RespMetadata.RequestID } +// The resource policy did not prevent broad access to the secret. +type PublicPolicyException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s PublicPolicyException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PublicPolicyException) GoString() string { + return s.String() +} + +func newErrorPublicPolicyException(v protocol.ResponseMetadata) error { + return &PublicPolicyException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *PublicPolicyException) Code() string { + return "PublicPolicyException" +} + +// Message returns the exception's message. +func (s *PublicPolicyException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *PublicPolicyException) OrigErr() error { + return nil +} + +func (s *PublicPolicyException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *PublicPolicyException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *PublicPolicyException) RequestID() string { + return s.RespMetadata.RequestID +} + type PutResourcePolicyInput struct { _ struct{} `type:"structure"` + // Makes an optional API call to Zelkova to validate the Resource Policy to + // prevent broad access to your secret. + BlockPublicPolicy *bool `type:"boolean"` + // A JSON-formatted string that's constructed according to the grammar and syntax // for an AWS resource-based policy. The policy in the string identifies who // can access or manage this secret and its versions. For information on how @@ -4553,7 +4832,12 @@ type PutResourcePolicyInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -4591,6 +4875,12 @@ func (s *PutResourcePolicyInput) Validate() error { return nil } +// SetBlockPublicPolicy sets the BlockPublicPolicy field's value. +func (s *PutResourcePolicyInput) SetBlockPublicPolicy(v bool) *PutResourcePolicyInput { + s.BlockPublicPolicy = &v + return s +} + // SetResourcePolicy sets the ResourcePolicy field's value. func (s *PutResourcePolicyInput) SetResourcePolicy(v string) *PutResourcePolicyInput { s.ResourcePolicy = &v @@ -4606,11 +4896,11 @@ func (s *PutResourcePolicyInput) SetSecretId(v string) *PutResourcePolicyInput { type PutResourcePolicyOutput struct { _ struct{} `type:"structure"` - // The ARN of the secret that the resource-based policy was retrieved for. + // The ARN of the secret retrieved by the resource-based policy. ARN *string `min:"20" type:"string"` - // The friendly name of the secret that the resource-based policy was retrieved - // for. + // The friendly name of the secret that the retrieved by the resource-based + // policy. Name *string `min:"1" type:"string"` } @@ -4661,7 +4951,7 @@ type PutSecretValueInput struct { // or SecretBinary values are the same as those in the request then the request // is ignored (the operation is idempotent). // - // * If a version with this value already exists and that version's SecretString + // * If a version with this value already exists and the version of the SecretString // and SecretBinary values are different from those in the request then the // request fails because you cannot modify an existing secret version. You // can only create new versions to store new secret values. @@ -4696,7 +4986,12 @@ type PutSecretValueInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -4983,7 +5278,12 @@ type RestoreSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -5066,9 +5366,9 @@ type RotateSecretInput struct { // service endpoint, then you must generate a ClientRequestToken yourself for // new versions and include that value in the request. // - // You only need to specify your own value if you are implementing your own - // retry logic and want to ensure that a given secret is not created twice. - // We recommend that you generate a UUID-type (https://wikipedia.org/wiki/Universally_unique_identifier) + // You only need to specify your own value if you implement your own retry logic + // and want to ensure that a given secret is not created twice. We recommend + // that you generate a UUID-type (https://wikipedia.org/wiki/Universally_unique_identifier) // value to ensure uniqueness within the specified secret. // // Secrets Manager uses this value to prevent the accidental creation of duplicate @@ -5095,7 +5395,12 @@ type RotateSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -5259,7 +5564,10 @@ type SecretListEntry struct { // in the AWS Secrets Manager User Guide. ARN *string `min:"20" type:"string"` - // The date and time on which this secret was deleted. Not present on active + // The date and time when a secret was created. + CreatedDate *time.Time `type:"timestamp"` + + // The date and time the deletion of the secret occurred. Not present on active // secrets. The secret can be recovered until the number of days in the recovery // window has passed, as specified in the RecoveryWindowInDays parameter of // the DeleteSecret operation. @@ -5268,10 +5576,10 @@ type SecretListEntry struct { // The user-provided description of the secret. Description *string `type:"string"` - // The ARN or alias of the AWS KMS customer master key (CMK) that's used to - // encrypt the SecretString and SecretBinary fields in each version of the secret. - // If you don't provide a key, then Secrets Manager defaults to encrypting the - // secret fields with the default KMS CMK (the one named awssecretsmanager) + // The ARN or alias of the AWS KMS customer master key (CMK) used to encrypt + // the SecretString and SecretBinary fields in each version of the secret. If + // you don't provide a key, then Secrets Manager defaults to encrypting the + // secret fields with the default KMS CMK, the key named awssecretsmanager, // for this account. KmsKeyId *string `type:"string"` @@ -5297,24 +5605,24 @@ type SecretListEntry struct { // Indicates whether automatic, scheduled rotation is enabled for this secret. RotationEnabled *bool `type:"boolean"` - // The ARN of an AWS Lambda function that's invoked by Secrets Manager to rotate - // and expire the secret either automatically per the schedule or manually by - // a call to RotateSecret. + // The ARN of an AWS Lambda function invoked by Secrets Manager to rotate and + // expire the secret either automatically per the schedule or manually by a + // call to RotateSecret. RotationLambdaARN *string `type:"string"` // A structure that defines the rotation configuration for the secret. RotationRules *RotationRulesType `type:"structure"` // A list of all of the currently assigned SecretVersionStage staging labels - // and the SecretVersionId that each is attached to. Staging labels are used - // to keep track of the different versions during the rotation process. + // and the SecretVersionId attached to each one. Staging labels are used to + // keep track of the different versions during the rotation process. // // A version that does not have any SecretVersionStage is considered deprecated // and subject to deletion. Such versions are not included in this list. SecretVersionsToStages map[string][]*string `type:"map"` - // The list of user-defined tags that are associated with the secret. To add - // tags to a secret, use TagResource. To remove tags, use UntagResource. + // The list of user-defined tags associated with the secret. To add tags to + // a secret, use TagResource. To remove tags, use UntagResource. Tags []*Tag `type:"list"` } @@ -5334,6 +5642,12 @@ func (s *SecretListEntry) SetARN(v string) *SecretListEntry { return s } +// SetCreatedDate sets the CreatedDate field's value. +func (s *SecretListEntry) SetCreatedDate(v time.Time) *SecretListEntry { + s.CreatedDate = &v + return s +} + // SetDeletedDate sets the DeletedDate field's value. func (s *SecretListEntry) SetDeletedDate(v time.Time) *SecretListEntry { s.DeletedDate = &v @@ -5472,7 +5786,7 @@ type Tag struct { // The key identifier, or name, of the tag. Key *string `min:"1" type:"string"` - // The string value that's associated with the key of the tag. + // The string value associated with the key of the tag. Value *string `type:"string"` } @@ -5527,7 +5841,12 @@ type TagResourceInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -5627,7 +5946,12 @@ type UntagResourceInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -5776,7 +6100,12 @@ type UpdateSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -5926,7 +6255,7 @@ func (s *UpdateSecretOutput) SetVersionId(v string) *UpdateSecretOutput { type UpdateSecretVersionStageInput struct { _ struct{} `type:"structure"` - // (Optional) The secret version ID that you want to add the staging label to. + // (Optional) The secret version ID that you want to add the staging label. // If you want to remove a label from a version, then do not specify this parameter. // // If the staging label is already attached to a different version of the secret, @@ -5941,9 +6270,9 @@ type UpdateSecretVersionStageInput struct { // the version ID does not match, then the operation fails. RemoveFromVersionId *string `min:"32" type:"string"` - // Specifies the secret with the version whose list of staging labels you want - // to modify. You can specify either the Amazon Resource Name (ARN) or the friendly - // name of the secret. + // Specifies the secret with the version with the list of staging labels you + // want to modify. You can specify either the Amazon Resource Name (ARN) or + // the friendly name of the secret. // // If you specify an ARN, we generally recommend that you specify a complete // ARN. You can specify a partial ARN too—for example, if you don’t include @@ -5955,7 +6284,12 @@ type UpdateSecretVersionStageInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -6031,10 +6365,10 @@ func (s *UpdateSecretVersionStageInput) SetVersionStage(v string) *UpdateSecretV type UpdateSecretVersionStageOutput struct { _ struct{} `type:"structure"` - // The ARN of the secret with the staging label that was modified. + // The ARN of the secret with the modified staging label. ARN *string `min:"20" type:"string"` - // The friendly name of the secret with the staging label that was modified. + // The friendly name of the secret with the modified staging label. Name *string `min:"1" type:"string"` } @@ -6059,3 +6393,185 @@ func (s *UpdateSecretVersionStageOutput) SetName(v string) *UpdateSecretVersionS s.Name = &v return s } + +type ValidateResourcePolicyInput struct { + _ struct{} `type:"structure"` + + // Identifies the Resource Policy attached to the secret. + // + // ResourcePolicy is a required field + ResourcePolicy *string `min:"1" type:"string" required:"true"` + + // The identifier for the secret that you want to validate a resource policy. + // You can specify either the Amazon Resource Name (ARN) or the friendly name + // of the secret. + // + // If you specify an ARN, we generally recommend that you specify a complete + // ARN. You can specify a partial ARN too—for example, if you don’t include + // the final hyphen and six random characters that Secrets Manager adds at the + // end of the ARN when you created the secret. A partial ARN match can work + // as long as it uniquely matches only one secret. However, if your secret has + // a name that ends in a hyphen followed by six characters (before Secrets Manager + // adds the hyphen and six characters to the ARN) and you try to use that as + // a partial ARN, then those characters cause Secrets Manager to assume that + // you’re specifying a complete ARN. This confusion can cause unexpected results. + // To avoid this situation, we recommend that you don’t create secret names + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. + SecretId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ValidateResourcePolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidateResourcePolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ValidateResourcePolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ValidateResourcePolicyInput"} + if s.ResourcePolicy == nil { + invalidParams.Add(request.NewErrParamRequired("ResourcePolicy")) + } + if s.ResourcePolicy != nil && len(*s.ResourcePolicy) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourcePolicy", 1)) + } + if s.SecretId != nil && len(*s.SecretId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("SecretId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourcePolicy sets the ResourcePolicy field's value. +func (s *ValidateResourcePolicyInput) SetResourcePolicy(v string) *ValidateResourcePolicyInput { + s.ResourcePolicy = &v + return s +} + +// SetSecretId sets the SecretId field's value. +func (s *ValidateResourcePolicyInput) SetSecretId(v string) *ValidateResourcePolicyInput { + s.SecretId = &v + return s +} + +type ValidateResourcePolicyOutput struct { + _ struct{} `type:"structure"` + + // Returns a message stating that your Reource Policy passed validation. + PolicyValidationPassed *bool `type:"boolean"` + + // Returns an error message if your policy doesn't pass validatation. + ValidationErrors []*ValidationErrorsEntry `type:"list"` +} + +// String returns the string representation +func (s ValidateResourcePolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidateResourcePolicyOutput) GoString() string { + return s.String() +} + +// SetPolicyValidationPassed sets the PolicyValidationPassed field's value. +func (s *ValidateResourcePolicyOutput) SetPolicyValidationPassed(v bool) *ValidateResourcePolicyOutput { + s.PolicyValidationPassed = &v + return s +} + +// SetValidationErrors sets the ValidationErrors field's value. +func (s *ValidateResourcePolicyOutput) SetValidationErrors(v []*ValidationErrorsEntry) *ValidateResourcePolicyOutput { + s.ValidationErrors = v + return s +} + +// Displays errors that occurred during validation of the resource policy. +type ValidationErrorsEntry struct { + _ struct{} `type:"structure"` + + // Checks the name of the policy. + CheckName *string `min:"1" type:"string"` + + // Displays error messages if validation encounters problems during validation + // of the resource policy. + ErrorMessage *string `type:"string"` +} + +// String returns the string representation +func (s ValidationErrorsEntry) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationErrorsEntry) GoString() string { + return s.String() +} + +// SetCheckName sets the CheckName field's value. +func (s *ValidationErrorsEntry) SetCheckName(v string) *ValidationErrorsEntry { + s.CheckName = &v + return s +} + +// SetErrorMessage sets the ErrorMessage field's value. +func (s *ValidationErrorsEntry) SetErrorMessage(v string) *ValidationErrorsEntry { + s.ErrorMessage = &v + return s +} + +const ( + // FilterNameStringTypeDescription is a FilterNameStringType enum value + FilterNameStringTypeDescription = "description" + + // FilterNameStringTypeName is a FilterNameStringType enum value + FilterNameStringTypeName = "name" + + // FilterNameStringTypeTagKey is a FilterNameStringType enum value + FilterNameStringTypeTagKey = "tag-key" + + // FilterNameStringTypeTagValue is a FilterNameStringType enum value + FilterNameStringTypeTagValue = "tag-value" + + // FilterNameStringTypeAll is a FilterNameStringType enum value + FilterNameStringTypeAll = "all" +) + +// FilterNameStringType_Values returns all elements of the FilterNameStringType enum +func FilterNameStringType_Values() []string { + return []string{ + FilterNameStringTypeDescription, + FilterNameStringTypeName, + FilterNameStringTypeTagKey, + FilterNameStringTypeTagValue, + FilterNameStringTypeAll, + } +} + +const ( + // SortOrderTypeAsc is a SortOrderType enum value + SortOrderTypeAsc = "asc" + + // SortOrderTypeDesc is a SortOrderType enum value + SortOrderTypeDesc = "desc" +) + +// SortOrderType_Values returns all elements of the SortOrderType enum +func SortOrderType_Values() []string { + return []string{ + SortOrderTypeAsc, + SortOrderTypeDesc, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/doc.go b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/doc.go index b931ba87c0a..71cfce04145 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/doc.go @@ -3,7 +3,7 @@ // Package secretsmanager provides the client and types for making API // requests to AWS Secrets Manager. // -// AWS Secrets Manager is a web service that enables you to store, manage, and +// AWS Secrets Manager provides a service to enable you to store, manage, and // retrieve, secrets. // // This guide provides descriptions of the Secrets Manager API. For more information @@ -14,25 +14,25 @@ // This version of the Secrets Manager API Reference documents the Secrets Manager // API version 2017-10-17. // -// As an alternative to using the API directly, you can use one of the AWS SDKs, -// which consist of libraries and sample code for various programming languages -// and platforms (such as Java, Ruby, .NET, iOS, and Android). The SDKs provide -// a convenient way to create programmatic access to AWS Secrets Manager. For -// example, the SDKs take care of cryptographically signing requests, managing -// errors, and retrying requests automatically. For more information about the -// AWS SDKs, including how to download and install them, see Tools for Amazon -// Web Services (http://aws.amazon.com/tools/). -// -// We recommend that you use the AWS SDKs to make programmatic API calls to -// Secrets Manager. However, you also can use the Secrets Manager HTTP Query -// API to make direct calls to the Secrets Manager web service. To learn more -// about the Secrets Manager HTTP Query API, see Making Query Requests (https://docs.aws.amazon.com/secretsmanager/latest/userguide/query-requests.html) +// As an alternative to using the API, you can use one of the AWS SDKs, which +// consist of libraries and sample code for various programming languages and +// platforms such as Java, Ruby, .NET, iOS, and Android. The SDKs provide a +// convenient way to create programmatic access to AWS Secrets Manager. For +// example, the SDKs provide cryptographically signing requests, managing errors, +// and retrying requests automatically. For more information about the AWS SDKs, +// including downloading and installing them, see Tools for Amazon Web Services +// (http://aws.amazon.com/tools/). +// +// We recommend you use the AWS SDKs to make programmatic API calls to Secrets +// Manager. However, you also can use the Secrets Manager HTTP Query API to +// make direct calls to the Secrets Manager web service. To learn more about +// the Secrets Manager HTTP Query API, see Making Query Requests (https://docs.aws.amazon.com/secretsmanager/latest/userguide/query-requests.html) // in the AWS Secrets Manager User Guide. // -// Secrets Manager supports GET and POST requests for all actions. That is, -// the API doesn't require you to use GET for some actions and POST for others. -// However, GET requests are subject to the limitation size of a URL. Therefore, -// for operations that require larger sizes, use a POST request. +// Secrets Manager API supports GET and POST requests for all actions, and doesn't +// require you to use GET for some actions and POST for others. However, GET +// requests are subject to the limitation size of a URL. Therefore, for operations +// that require larger sizes, use a POST request. // // Support and Feedback for AWS Secrets Manager // @@ -44,25 +44,24 @@ // How examples are presented // // The JSON that AWS Secrets Manager expects as your request parameters and -// that the service returns as a response to HTTP query requests are single, +// the service returns as a response to HTTP query requests contain single, // long strings without line breaks or white space formatting. The JSON shown -// in the examples is formatted with both line breaks and white space to improve -// readability. When example input parameters would also result in long strings -// that extend beyond the screen, we insert line breaks to enhance readability. -// You should always submit the input as a single JSON text string. +// in the examples displays the code formatted with both line breaks and white +// space to improve readability. When example input parameters can also cause +// long strings extending beyond the screen, you can insert line breaks to enhance +// readability. You should always submit the input as a single JSON text string. // // Logging API Requests // // AWS Secrets Manager supports AWS CloudTrail, a service that records AWS API // calls for your AWS account and delivers log files to an Amazon S3 bucket. // By using information that's collected by AWS CloudTrail, you can determine -// which requests were successfully made to Secrets Manager, who made the request, -// when it was made, and so on. For more about AWS Secrets Manager and its support +// the requests successfully made to Secrets Manager, who made the request, +// when it was made, and so on. For more about AWS Secrets Manager and support // for AWS CloudTrail, see Logging AWS Secrets Manager Events with AWS CloudTrail // (http://docs.aws.amazon.com/secretsmanager/latest/userguide/monitoring.html#monitoring_cloudtrail) // in the AWS Secrets Manager User Guide. To learn more about CloudTrail, including -// how to turn it on and find your log files, see the AWS CloudTrail User Guide -// (https://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html). +// enabling it and find your log files, see the AWS CloudTrail User Guide (https://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html). // // See https://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17 for more information on this service. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/errors.go b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/errors.go index df82716bb59..ab90196bb65 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/errors.go @@ -77,6 +77,12 @@ const ( // The request failed because you did not complete all the prerequisite steps. ErrCodePreconditionNotMetException = "PreconditionNotMetException" + // ErrCodePublicPolicyException for service response error code + // "PublicPolicyException". + // + // The resource policy did not prevent broad access to the secret. + ErrCodePublicPolicyException = "PublicPolicyException" + // ErrCodeResourceExistsException for service response error code // "ResourceExistsException". // @@ -100,6 +106,7 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "LimitExceededException": newErrorLimitExceededException, "MalformedPolicyDocumentException": newErrorMalformedPolicyDocumentException, "PreconditionNotMetException": newErrorPreconditionNotMetException, + "PublicPolicyException": newErrorPublicPolicyException, "ResourceExistsException": newErrorResourceExistsException, "ResourceNotFoundException": newErrorResourceNotFoundException, } diff --git a/vendor/github.com/aws/aws-sdk-go/service/securityhub/api.go b/vendor/github.com/aws/aws-sdk-go/service/securityhub/api.go index 5bd00bd6b12..0d105df98c0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/securityhub/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/securityhub/api.go @@ -781,10 +781,10 @@ func (c *SecurityHub) CreateMembersRequest(input *CreateMembersInput) (req *requ // Security Hub and become member accounts in Security Hub. // // If the account owner accepts the invitation, the account becomes a member -// account in Security Hub, and a permission policy is added that permits the -// master account to view the findings generated in the member account. When -// Security Hub is enabled in the invited account, findings start to be sent -// to both the member and master accounts. +// account in Security Hub. A permissions policy is added that permits the master +// account to view the findings generated in the member account. When Security +// Hub is enabled in the invited account, findings start to be sent to both +// the member and master accounts. // // To remove the association between the master and member accounts, use the // DisassociateFromMasterAccount or DisassociateMembers operation. @@ -2418,7 +2418,7 @@ func (c *SecurityHub) EnableImportFindingsForProductRequest(input *EnableImportF // Enables the integration of a partner product with Security Hub. Integrated // products send findings to Security Hub. // -// When you enable a product integration, a permission policy that grants permission +// When you enable a product integration, a permissions policy that grants permission // for the product to send findings to Security Hub is applied. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -2521,9 +2521,17 @@ func (c *SecurityHub) EnableSecurityHubRequest(input *EnableSecurityHubInput) (r // Hub. // // When you use the EnableSecurityHub operation to enable Security Hub, you -// also automatically enable the CIS AWS Foundations standard. You do not enable -// the Payment Card Industry Data Security Standard (PCI DSS) standard. To not -// enable the CIS AWS Foundations standard, set EnableDefaultStandards to false. +// also automatically enable the following standards. +// +// * CIS AWS Foundations +// +// * AWS Foundational Security Best Practices +// +// You do not enable the Payment Card Industry Data Security Standard (PCI DSS) +// standard. +// +// To not enable the automatically enabled standards, set EnableDefaultStandards +// to false. // // After you enable Security Hub, to enable a standard, use the BatchEnableStandards // operation. To disable a standard, use the BatchDisableStandards operation. @@ -4485,6 +4493,100 @@ func (c *SecurityHub) UpdateInsightWithContext(ctx aws.Context, input *UpdateIns return out, req.Send() } +const opUpdateSecurityHubConfiguration = "UpdateSecurityHubConfiguration" + +// UpdateSecurityHubConfigurationRequest generates a "aws/request.Request" representing the +// client's request for the UpdateSecurityHubConfiguration operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateSecurityHubConfiguration for more information on using the UpdateSecurityHubConfiguration +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateSecurityHubConfigurationRequest method. +// req, resp := client.UpdateSecurityHubConfigurationRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/securityhub-2018-10-26/UpdateSecurityHubConfiguration +func (c *SecurityHub) UpdateSecurityHubConfigurationRequest(input *UpdateSecurityHubConfigurationInput) (req *request.Request, output *UpdateSecurityHubConfigurationOutput) { + op := &request.Operation{ + Name: opUpdateSecurityHubConfiguration, + HTTPMethod: "PATCH", + HTTPPath: "/accounts", + } + + if input == nil { + input = &UpdateSecurityHubConfigurationInput{} + } + + output = &UpdateSecurityHubConfigurationOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UpdateSecurityHubConfiguration API operation for AWS SecurityHub. +// +// Updates configuration options for Security Hub. +// +// Returns awserr.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 SecurityHub's +// API operation UpdateSecurityHubConfiguration for usage and error information. +// +// Returned Error Types: +// * InternalException +// Internal server error. +// +// * InvalidInputException +// The request was rejected because you supplied an invalid or out-of-range +// value for an input parameter. +// +// * InvalidAccessException +// AWS Security Hub isn't enabled for the account used to make this request. +// +// * LimitExceededException +// The request was rejected because it attempted to create resources beyond +// the current AWS account limits. The error code describes the limit exceeded. +// +// * ResourceNotFoundException +// The request was rejected because we can't find the specified resource. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/securityhub-2018-10-26/UpdateSecurityHubConfiguration +func (c *SecurityHub) UpdateSecurityHubConfiguration(input *UpdateSecurityHubConfigurationInput) (*UpdateSecurityHubConfigurationOutput, error) { + req, out := c.UpdateSecurityHubConfigurationRequest(input) + return out, req.Send() +} + +// UpdateSecurityHubConfigurationWithContext is the same as UpdateSecurityHubConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateSecurityHubConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SecurityHub) UpdateSecurityHubConfigurationWithContext(ctx aws.Context, input *UpdateSecurityHubConfigurationInput, opts ...request.Option) (*UpdateSecurityHubConfigurationOutput, error) { + req, out := c.UpdateSecurityHubConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opUpdateStandardsControl = "UpdateStandardsControl" // UpdateStandardsControlRequest generates a "aws/request.Request" representing the @@ -4814,6 +4916,67 @@ func (s *AvailabilityZone) SetZoneName(v string) *AvailabilityZone { return s } +// Provides details about an auto scaling group. +type AwsAutoScalingAutoScalingGroupDetails struct { + _ struct{} `type:"structure"` + + // The datetime when the auto scaling group was created. + CreatedTime *string `type:"string"` + + // The amount of time, in seconds, that Amazon EC2 Auto Scaling waits before + // it checks the health status of an EC2 instance that has come into service. + HealthCheckGracePeriod *int64 `type:"integer"` + + // The service to use for the health checks. + HealthCheckType *string `type:"string"` + + // The name of the launch configuration. + LaunchConfigurationName *string `type:"string"` + + // The list of load balancers associated with the group. + LoadBalancerNames []*string `type:"list"` +} + +// String returns the string representation +func (s AwsAutoScalingAutoScalingGroupDetails) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsAutoScalingAutoScalingGroupDetails) GoString() string { + return s.String() +} + +// SetCreatedTime sets the CreatedTime field's value. +func (s *AwsAutoScalingAutoScalingGroupDetails) SetCreatedTime(v string) *AwsAutoScalingAutoScalingGroupDetails { + s.CreatedTime = &v + return s +} + +// SetHealthCheckGracePeriod sets the HealthCheckGracePeriod field's value. +func (s *AwsAutoScalingAutoScalingGroupDetails) SetHealthCheckGracePeriod(v int64) *AwsAutoScalingAutoScalingGroupDetails { + s.HealthCheckGracePeriod = &v + return s +} + +// SetHealthCheckType sets the HealthCheckType field's value. +func (s *AwsAutoScalingAutoScalingGroupDetails) SetHealthCheckType(v string) *AwsAutoScalingAutoScalingGroupDetails { + s.HealthCheckType = &v + return s +} + +// SetLaunchConfigurationName sets the LaunchConfigurationName field's value. +func (s *AwsAutoScalingAutoScalingGroupDetails) SetLaunchConfigurationName(v string) *AwsAutoScalingAutoScalingGroupDetails { + s.LaunchConfigurationName = &v + return s +} + +// SetLoadBalancerNames sets the LoadBalancerNames field's value. +func (s *AwsAutoScalingAutoScalingGroupDetails) SetLoadBalancerNames(v []*string) *AwsAutoScalingAutoScalingGroupDetails { + s.LoadBalancerNames = v + return s +} + // A distribution configuration. type AwsCloudFrontDistributionDetails struct { _ struct{} `type:"structure"` @@ -4946,8 +5109,8 @@ func (s *AwsCloudFrontDistributionLogging) SetPrefix(v string) *AwsCloudFrontDis } // A complex type that describes the Amazon S3 bucket, HTTP server (for example, -// a web server), Amazon MediaStore, or other server from which CloudFront gets -// your files. +// a web server), Amazon Elemental MediaStore, or other server from which CloudFront +// gets your files. type AwsCloudFrontDistributionOriginItem struct { _ struct{} `type:"structure"` @@ -5118,20 +5281,20 @@ type AwsCodeBuildProjectEnvironment struct { // The type of build environment to use for related builds. // - // The environment type ARM_CONTAINER is available only in regions US East (N. + // The environment type ARM_CONTAINER is available only in Regions US East (N. // Virginia), US East (Ohio), US West (Oregon), Europe (Ireland), Asia Pacific // (Mumbai), Asia Pacific (Tokyo), Asia Pacific (Sydney), and Europe (Frankfurt). // // The environment type LINUX_CONTAINER with compute type build.general1.2xlarge - // is available only in regions US East (N. Virginia), US East (N. Virginia), + // is available only in Regions US East (N. Virginia), US East (N. Virginia), // US West (Oregon), Canada (Central), Europe (Ireland), Europe (London), Europe // (Frankfurt), Asia Pacific (Tokyo), Asia Pacific (Seoul), Asia Pacific (Singapore), // Asia Pacific (Sydney), China (Beijing), and China (Ningxia). // - // The environment type LINUX_GPU_CONTAINER is available only in regions US + // The environment type LINUX_GPU_CONTAINER is available only in Regions US // East (N. Virginia), US East (N. Virginia), US West (Oregon), Canada (Central), // Europe (Ireland), Europe (London), Europe (Frankfurt), Asia Pacific (Tokyo), - // Asia Pacific (Seoul), Asia Pacific (Singapore), Asia Pacific (Sydney) , China + // Asia Pacific (Seoul), Asia Pacific (Singapore), Asia Pacific (Sydney), China // (Beijing), and China (Ningxia). // // Valid values: WINDOWS_CONTAINER | LINUX_CONTAINER | LINUX_GPU_CONTAINER | @@ -5232,7 +5395,7 @@ type AwsCodeBuildProjectSource struct { // uses the settings in a pipeline's source action instead of this value. // // * For source code in an AWS CodeCommit repository, the HTTPS clone URL - // to the repository that contains the source code and the buildspec file + // to the repository that contains the source code and the build spec file // (for example, https://git-codecommit.region-ID.amazonaws.com/v1/repos/repo-name // ). // @@ -5241,10 +5404,10 @@ type AwsCodeBuildProjectSource struct { // The path to the folder that contains the source code (for example, bucket-name/path/to/source-code/folder/). // // * For source code in a GitHub repository, the HTTPS clone URL to the repository - // that contains the source and the buildspec file. + // that contains the source and the build spec file. // // * For source code in a Bitbucket repository, the HTTPS clone URL to the - // repository that contains the source and the buildspec file. + // repository that contains the source and the build spec file. Location *string `type:"string"` // The type of repository that contains the source code to be built. Valid values @@ -5775,9 +5938,9 @@ func (s *AwsEc2SecurityGroupIpPermission) SetUserIdGroupPairs(v []*AwsEc2Securit type AwsEc2SecurityGroupIpRange struct { _ struct{} `type:"structure"` - // The IPv4 CIDR range. You can either specify either a CIDR range or a source - // security group, but not both. To specify a single IPv4 address, use the /32 - // prefix length. + // The IPv4 CIDR range. You can specify either a CIDR range or a source security + // group, but not both. To specify a single IPv4 address, use the /32 prefix + // length. CidrIp *string `type:"string"` } @@ -5801,9 +5964,9 @@ func (s *AwsEc2SecurityGroupIpRange) SetCidrIp(v string) *AwsEc2SecurityGroupIpR type AwsEc2SecurityGroupIpv6Range struct { _ struct{} `type:"structure"` - // The IPv6 CIDR range. You can either specify either a CIDR range or a source - // security group, but not both. To specify a single IPv6 address, use the /128 - // prefix length. + // The IPv6 CIDR range. You can specify either a CIDR range or a source security + // group, but not both. To specify a single IPv6 address, use the /128 prefix + // length. CidrIpv6 *string `type:"string"` } @@ -5923,6 +6086,189 @@ func (s *AwsEc2SecurityGroupUserIdGroupPair) SetVpcPeeringConnectionId(v string) return s } +// An attachment to an AWS EC2 volume. +type AwsEc2VolumeAttachment struct { + _ struct{} `type:"structure"` + + // The datetime when the attachment initiated. + AttachTime *string `type:"string"` + + // Whether the EBS volume is deleted when the EC2 instance is terminated. + DeleteOnTermination *bool `type:"boolean"` + + // The identifier of the EC2 instance. + InstanceId *string `type:"string"` + + // The attachment state of the volume. + Status *string `type:"string"` +} + +// String returns the string representation +func (s AwsEc2VolumeAttachment) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsEc2VolumeAttachment) GoString() string { + return s.String() +} + +// SetAttachTime sets the AttachTime field's value. +func (s *AwsEc2VolumeAttachment) SetAttachTime(v string) *AwsEc2VolumeAttachment { + s.AttachTime = &v + return s +} + +// SetDeleteOnTermination sets the DeleteOnTermination field's value. +func (s *AwsEc2VolumeAttachment) SetDeleteOnTermination(v bool) *AwsEc2VolumeAttachment { + s.DeleteOnTermination = &v + return s +} + +// SetInstanceId sets the InstanceId field's value. +func (s *AwsEc2VolumeAttachment) SetInstanceId(v string) *AwsEc2VolumeAttachment { + s.InstanceId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *AwsEc2VolumeAttachment) SetStatus(v string) *AwsEc2VolumeAttachment { + s.Status = &v + return s +} + +// Details about an EC2 volume. +type AwsEc2VolumeDetails struct { + _ struct{} `type:"structure"` + + // The volume attachments. + Attachments []*AwsEc2VolumeAttachment `type:"list"` + + // The datetime when the volume was created. + CreateTime *string `type:"string"` + + // Whether the volume is encrypted. + Encrypted *bool `type:"boolean"` + + // The ARN of the AWS Key Management Service (AWS KMS) customer master key (CMK) + // that was used to protect the volume encryption key for the volume. + KmsKeyId *string `type:"string"` + + // The size of the volume, in GiBs. + Size *int64 `type:"integer"` + + // The snapshot from which the volume was created. + SnapshotId *string `type:"string"` + + // The volume state. + Status *string `type:"string"` +} + +// String returns the string representation +func (s AwsEc2VolumeDetails) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsEc2VolumeDetails) GoString() string { + return s.String() +} + +// SetAttachments sets the Attachments field's value. +func (s *AwsEc2VolumeDetails) SetAttachments(v []*AwsEc2VolumeAttachment) *AwsEc2VolumeDetails { + s.Attachments = v + return s +} + +// SetCreateTime sets the CreateTime field's value. +func (s *AwsEc2VolumeDetails) SetCreateTime(v string) *AwsEc2VolumeDetails { + s.CreateTime = &v + return s +} + +// SetEncrypted sets the Encrypted field's value. +func (s *AwsEc2VolumeDetails) SetEncrypted(v bool) *AwsEc2VolumeDetails { + s.Encrypted = &v + return s +} + +// SetKmsKeyId sets the KmsKeyId field's value. +func (s *AwsEc2VolumeDetails) SetKmsKeyId(v string) *AwsEc2VolumeDetails { + s.KmsKeyId = &v + return s +} + +// SetSize sets the Size field's value. +func (s *AwsEc2VolumeDetails) SetSize(v int64) *AwsEc2VolumeDetails { + s.Size = &v + return s +} + +// SetSnapshotId sets the SnapshotId field's value. +func (s *AwsEc2VolumeDetails) SetSnapshotId(v string) *AwsEc2VolumeDetails { + s.SnapshotId = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *AwsEc2VolumeDetails) SetStatus(v string) *AwsEc2VolumeDetails { + s.Status = &v + return s +} + +// Details about an EC2 VPC. +type AwsEc2VpcDetails struct { + _ struct{} `type:"structure"` + + // Information about the IPv4 CIDR blocks associated with the VPC. + CidrBlockAssociationSet []*CidrBlockAssociation `type:"list"` + + // The identifier of the set of Dynamic Host Configuration Protocol (DHCP) options + // that are associated with the VPC. If the default options are associated with + // the VPC, then this is default. + DhcpOptionsId *string `type:"string"` + + // Information about the IPv6 CIDR blocks associated with the VPC. + Ipv6CidrBlockAssociationSet []*Ipv6CidrBlockAssociation `type:"list"` + + // The current state of the VPC. + State *string `type:"string"` +} + +// String returns the string representation +func (s AwsEc2VpcDetails) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AwsEc2VpcDetails) GoString() string { + return s.String() +} + +// SetCidrBlockAssociationSet sets the CidrBlockAssociationSet field's value. +func (s *AwsEc2VpcDetails) SetCidrBlockAssociationSet(v []*CidrBlockAssociation) *AwsEc2VpcDetails { + s.CidrBlockAssociationSet = v + return s +} + +// SetDhcpOptionsId sets the DhcpOptionsId field's value. +func (s *AwsEc2VpcDetails) SetDhcpOptionsId(v string) *AwsEc2VpcDetails { + s.DhcpOptionsId = &v + return s +} + +// SetIpv6CidrBlockAssociationSet sets the Ipv6CidrBlockAssociationSet field's value. +func (s *AwsEc2VpcDetails) SetIpv6CidrBlockAssociationSet(v []*Ipv6CidrBlockAssociation) *AwsEc2VpcDetails { + s.Ipv6CidrBlockAssociationSet = v + return s +} + +// SetState sets the State field's value. +func (s *AwsEc2VpcDetails) SetState(v string) *AwsEc2VpcDetails { + s.State = &v + return s +} + // Information about an Elasticsearch domain. type AwsElasticsearchDomainDetails struct { _ struct{} `type:"structure"` @@ -6959,7 +7305,7 @@ func (s *AwsLambdaFunctionVpcConfig) SetVpcId(v string) *AwsLambdaFunctionVpcCon type AwsLambdaLayerVersionDetails struct { _ struct{} `type:"structure"` - // The layer's compatible runtimes. Maximum number of 5 items. + // The layer's compatible runtimes. Maximum number of five items. // // Valid values: nodejs10.x | nodejs12.x | java8 | java11 | python2.7 | python3.6 // | python3.7 | python3.8 | dotnetcore1.0 | dotnetcore2.1 | go1.x | ruby2.5 @@ -7015,12 +7361,12 @@ type AwsRdsDbInstanceAssociatedRole struct { // Describes the state of the association between the IAM role and the DB instance. // The Status property returns one of the following values: // - // * ACTIVE - the IAM role ARN is associated with the DB instance and can + // * ACTIVE - The IAM role ARN is associated with the DB instance and can // be used to access other AWS services on your behalf. // - // * PENDING - the IAM role ARN is being associated with the DB instance. + // * PENDING - The IAM role ARN is being associated with the DB instance. // - // * INVALID - the IAM role ARN is associated with the DB instance, but the + // * INVALID - The IAM role ARN is associated with the DB instance. But the // DB instance is unable to assume the IAM role in order to access other // AWS services on your behalf. Status *string `type:"string"` @@ -7466,7 +7812,7 @@ type AwsS3BucketServerSideEncryptionRule struct { _ struct{} `type:"structure"` // Specifies the default server-side encryption to apply to new objects in the - // bucket. If a PUT Object request doesn't specify any server-side encryption, + // bucket. If a PUT object request doesn't specify any server-side encryption, // this default encryption is applied. ApplyServerSideEncryptionByDefault *AwsS3BucketServerSideEncryptionByDefault `type:"structure"` } @@ -7487,7 +7833,7 @@ func (s *AwsS3BucketServerSideEncryptionRule) SetApplyServerSideEncryptionByDefa return s } -// Details about an AWS S3 object. +// Details about an Amazon S3 object. type AwsS3ObjectDetails struct { _ struct{} `type:"structure"` @@ -7611,7 +7957,7 @@ type AwsSecurityFinding struct { // The identifier for the solution-specific component (a discrete unit of logic) // that generated a finding. In various security-findings providers' solutions, - // this generator can be called a rule, a check, a detector, a plug-in, etc. + // this generator can be called a rule, a check, a detector, a plugin, etc. // // GeneratorId is a required field GeneratorId *string `type:"string" required:"true"` @@ -7632,6 +7978,10 @@ type AwsSecurityFinding struct { // The details of network-related information about a finding. Network *Network `type:"structure"` + // Provides information about a network path that is relevant to a finding. + // Each entry under NetworkPath represents a component of that path. + NetworkPath []*NetworkPathComponent `type:"list"` + // A user-defined note added to a finding. Note *Note `type:"structure"` @@ -7710,6 +8060,9 @@ type AwsSecurityFinding struct { // Indicates the veracity of a finding. VerificationState *string `type:"string" enum:"VerificationState"` + // Provides a list of vulnerabilities associated with the findings. + Vulnerabilities []*Vulnerability `type:"list"` + // Provides information about the status of the investigation into a finding. Workflow *Workflow `type:"structure"` @@ -7766,6 +8119,11 @@ func (s *AwsSecurityFinding) Validate() error { if s.UpdatedAt == nil { invalidParams.Add(request.NewErrParamRequired("UpdatedAt")) } + if s.Compliance != nil { + if err := s.Compliance.Validate(); err != nil { + invalidParams.AddNested("Compliance", err.(request.ErrInvalidParams)) + } + } if s.Malware != nil { for i, v := range s.Malware { if v == nil { @@ -7801,6 +8159,16 @@ func (s *AwsSecurityFinding) Validate() error { } } } + if s.Vulnerabilities != nil { + for i, v := range s.Vulnerabilities { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Vulnerabilities", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -7880,6 +8248,12 @@ func (s *AwsSecurityFinding) SetNetwork(v *Network) *AwsSecurityFinding { return s } +// SetNetworkPath sets the NetworkPath field's value. +func (s *AwsSecurityFinding) SetNetworkPath(v []*NetworkPathComponent) *AwsSecurityFinding { + s.NetworkPath = v + return s +} + // SetNote sets the Note field's value. func (s *AwsSecurityFinding) SetNote(v *Note) *AwsSecurityFinding { s.Note = v @@ -7982,6 +8356,12 @@ func (s *AwsSecurityFinding) SetVerificationState(v string) *AwsSecurityFinding return s } +// SetVulnerabilities sets the Vulnerabilities field's value. +func (s *AwsSecurityFinding) SetVulnerabilities(v []*Vulnerability) *AwsSecurityFinding { + s.Vulnerabilities = v + return s +} + // SetWorkflow sets the Workflow field's value. func (s *AwsSecurityFinding) SetWorkflow(v *Workflow) *AwsSecurityFinding { s.Workflow = v @@ -8038,7 +8418,7 @@ type AwsSecurityFindingFilters struct { // The identifier for the solution-specific component (a discrete unit of logic) // that generated a finding. In various security-findings providers' solutions, - // this generator can be called a rule, a check, a detector, a plug-in, etc. + // this generator can be called a rule, a check, a detector, a plugin, etc. GeneratorId []*StringFilter `type:"list"` // The security findings provider-specific identifier for a finding. @@ -8274,6 +8654,9 @@ type AwsSecurityFindingFilters struct { VerificationState []*StringFilter `type:"list"` // The workflow state of a finding. + // + // Note that this field is deprecated. To search for a finding based on its + // workflow status, use WorkflowStatus. WorkflowState []*StringFilter `type:"list"` // The status of the investigation into a finding. Allowed values are the following. @@ -8865,7 +9248,7 @@ func (s *AwsSecurityFindingIdentifier) SetProductArn(v string) *AwsSecurityFindi type AwsSnsTopicDetails struct { _ struct{} `type:"structure"` - // The ID of an AWS-managed customer master key (CMK) for Amazon SNS or a custom + // The ID of an AWS managed customer master key (CMK) for Amazon SNS or a custom // CMK. KmsMasterKeyId *string `type:"string"` @@ -8959,7 +9342,7 @@ type AwsSqsQueueDetails struct { // to encrypt or decrypt messages before calling AWS KMS again. KmsDataKeyReusePeriodSeconds *int64 `type:"integer"` - // The ID of an AWS-managed customer master key (CMK) for Amazon SQS or a custom + // The ID of an AWS managed customer master key (CMK) for Amazon SQS or a custom // CMK. KmsMasterKeyId *string `type:"string"` @@ -9005,7 +9388,7 @@ func (s *AwsSqsQueueDetails) SetQueueName(v string) *AwsSqsQueueDetails { type AwsWafWebAclDetails struct { _ struct{} `type:"structure"` - // The action to perform if none of the Rules contained in the WebACL match. + // The action to perform if none of the rules contained in the WebACL match. DefaultAction *string `type:"string"` // A friendly name or description of the WebACL. You can't change the name of @@ -9059,7 +9442,7 @@ type AwsWafWebAclRule struct { _ struct{} `type:"structure"` // Specifies the action that CloudFront or AWS WAF takes when a web request - // matches the conditions in the Rule. + // matches the conditions in the rule. Action *WafAction `type:"structure"` // Rules to exclude from a rule group. @@ -9081,13 +9464,13 @@ type AwsWafWebAclRule struct { // update requests, ActivatedRule|Action is used instead of ActivatedRule|OverrideAction. OverrideAction *WafOverrideAction `type:"structure"` - // Specifies the order in which the Rules in a WebACL are evaluated. Rules with - // a lower value for Priority are evaluated before Rules with a higher value. - // The value must be a unique integer. If you add multiple Rules to a WebACL, + // Specifies the order in which the rules in a WebACL are evaluated. Rules with + // a lower value for Priority are evaluated before rules with a higher value. + // The value must be a unique integer. If you add multiple rules to a WebACL, // the values do not need to be consecutive. Priority *int64 `type:"integer"` - // The identifier for a Rule. + // The identifier for a rule. RuleId *string `type:"string"` // The rule type. @@ -9648,52 +10031,126 @@ func (s *BatchUpdateFindingsUnprocessedFinding) SetFindingIdentifier(v *AwsSecur return s } -// Exclusive to findings that are generated as the result of a check run against -// a specific rule in a supported security standard, such as CIS AWS Foundations. -// Contains security standard-related finding details. -// -// Values include the following: -// -// * Allowed values are the following: PASSED - Standards check passed for -// all evaluated resources. WARNING - Some information is missing or this -// check is not supported given your configuration. FAILED - Standards check -// failed for at least one evaluated resource. NOT_AVAILABLE - Check could -// not be performed due to a service outage, API error, or because the result -// of the AWS Config evaluation was NOT_APPLICABLE. If the AWS Config evaluation -// result was NOT_APPLICABLE, then after 3 days, Security Hub automatically -// archives the finding. -type Compliance struct { +// An IPv4 CIDR block association. +type CidrBlockAssociation struct { _ struct{} `type:"structure"` - // List of requirements that are related to a standards control. - RelatedRequirements []*string `type:"list"` + // The association ID for the IPv4 CIDR block. + AssociationId *string `type:"string"` - // The result of a standards check. - Status *string `type:"string" enum:"ComplianceStatus"` + // The IPv4 CIDR block. + CidrBlock *string `type:"string"` + + // Information about the state of the IPv4 CIDR block. + CidrBlockState *string `type:"string"` } // String returns the string representation -func (s Compliance) String() string { +func (s CidrBlockAssociation) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s Compliance) GoString() string { +func (s CidrBlockAssociation) GoString() string { return s.String() } -// SetRelatedRequirements sets the RelatedRequirements field's value. -func (s *Compliance) SetRelatedRequirements(v []*string) *Compliance { - s.RelatedRequirements = v +// SetAssociationId sets the AssociationId field's value. +func (s *CidrBlockAssociation) SetAssociationId(v string) *CidrBlockAssociation { + s.AssociationId = &v return s } -// SetStatus sets the Status field's value. -func (s *Compliance) SetStatus(v string) *Compliance { +// SetCidrBlock sets the CidrBlock field's value. +func (s *CidrBlockAssociation) SetCidrBlock(v string) *CidrBlockAssociation { + s.CidrBlock = &v + return s +} + +// SetCidrBlockState sets the CidrBlockState field's value. +func (s *CidrBlockAssociation) SetCidrBlockState(v string) *CidrBlockAssociation { + s.CidrBlockState = &v + return s +} + +// Contains finding details that are specific to control-based findings. Only +// returned for findings generated from controls. +type Compliance struct { + _ struct{} `type:"structure"` + + // For a control, the industry or regulatory framework requirements that are + // related to the control. The check for that control is aligned with these + // requirements. + RelatedRequirements []*string `type:"list"` + + // The result of a standards check. + // + // The valid values for Status are as follows. + // + // * PASSED - Standards check passed for all evaluated resources. WARNING + // - Some information is missing or this check is not supported for your + // configuration. FAILED - Standards check failed for at least one evaluated + // resource. NOT_AVAILABLE - Check could not be performed due to a service + // outage, API error, or because the result of the AWS Config evaluation + // was NOT_APPLICABLE. If the AWS Config evaluation result was NOT_APPLICABLE, + // then after 3 days, Security Hub automatically archives the finding. + Status *string `type:"string" enum:"ComplianceStatus"` + + // For findings generated from controls, a list of reasons behind the value + // of Status. For the list of status reason codes and their meanings, see Standards-related + // information in the ASFF (https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-results.html#securityhub-standards-results-asff) + // in the AWS Security Hub User Guide. + StatusReasons []*StatusReason `type:"list"` +} + +// String returns the string representation +func (s Compliance) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Compliance) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Compliance) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Compliance"} + if s.StatusReasons != nil { + for i, v := range s.StatusReasons { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "StatusReasons", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetRelatedRequirements sets the RelatedRequirements field's value. +func (s *Compliance) SetRelatedRequirements(v []*string) *Compliance { + s.RelatedRequirements = v + return s +} + +// SetStatus sets the Status field's value. +func (s *Compliance) SetStatus(v string) *Compliance { s.Status = &v return s } +// SetStatusReasons sets the StatusReasons field's value. +func (s *Compliance) SetStatusReasons(v []*StatusReason) *Compliance { + s.StatusReasons = v + return s +} + // Container details related to a finding. type ContainerDetails struct { _ struct{} `type:"structure"` @@ -9980,6 +10437,48 @@ func (s *CreateMembersOutput) SetUnprocessedAccounts(v []*Result) *CreateMembers return s } +// CVSS scores from the advisory related to the vulnerability. +type Cvss struct { + _ struct{} `type:"structure"` + + // The base CVSS score. + BaseScore *float64 `type:"double"` + + // The base scoring vector for the CVSS score. + BaseVector *string `type:"string"` + + // The version of CVSS for the CVSS score. + Version *string `type:"string"` +} + +// String returns the string representation +func (s Cvss) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Cvss) GoString() string { + return s.String() +} + +// SetBaseScore sets the BaseScore field's value. +func (s *Cvss) SetBaseScore(v float64) *Cvss { + s.BaseScore = &v + return s +} + +// SetBaseVector sets the BaseVector field's value. +func (s *Cvss) SetBaseVector(v string) *Cvss { + s.BaseVector = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *Cvss) SetVersion(v string) *Cvss { + s.Version = &v + return s +} + // A date filter for querying findings. type DateFilter struct { _ struct{} `type:"structure"` @@ -10478,6 +10977,13 @@ func (s *DescribeHubInput) SetHubArn(v string) *DescribeHubInput { type DescribeHubOutput struct { _ struct{} `type:"structure"` + // Whether to automatically enable new controls when they are added to standards + // that are enabled. + // + // If set to true, then new controls for enabled standards are enabled automatically. + // If set to false, then new controls are not enabled. + AutoEnableControls *bool `type:"boolean"` + // The ARN of the Hub resource that was retrieved. HubArn *string `type:"string"` @@ -10495,6 +11001,12 @@ func (s DescribeHubOutput) GoString() string { return s.String() } +// SetAutoEnableControls sets the AutoEnableControls field's value. +func (s *DescribeHubOutput) SetAutoEnableControls(v bool) *DescribeHubOutput { + s.AutoEnableControls = &v + return s +} + // SetHubArn sets the HubArn field's value. func (s *DescribeHubOutput) SetHubArn(v string) *DescribeHubOutput { s.HubArn = &v @@ -10987,7 +11499,7 @@ type EnableSecurityHubInput struct { // EnableDefaultStandards to false. EnableDefaultStandards *bool `type:"boolean"` - // The tags to add to the Hub resource when you enable Security Hub. + // The tags to add to the hub resource when you enable Security Hub. Tags map[string]*string `min:"1" type:"map"` } @@ -11139,6 +11651,9 @@ type GetFindingsInput struct { // The finding attributes used to define a condition to filter the returned // findings. + // + // Note that in the available filter fields, WorkflowState is deprecated. To + // search for a finding based on its workflow status, use WorkflowStatus. Filters *AwsSecurityFindingFilters `type:"structure"` // The maximum number of findings to return. @@ -12044,6 +12559,48 @@ func (s *IpFilter) SetCidr(v string) *IpFilter { return s } +// An IPV6 CIDR block association. +type Ipv6CidrBlockAssociation struct { + _ struct{} `type:"structure"` + + // The association ID for the IPv6 CIDR block. + AssociationId *string `type:"string"` + + // Information about the state of the CIDR block. + CidrBlockState *string `type:"string"` + + // The IPv6 CIDR block. + Ipv6CidrBlock *string `type:"string"` +} + +// String returns the string representation +func (s Ipv6CidrBlockAssociation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Ipv6CidrBlockAssociation) GoString() string { + return s.String() +} + +// SetAssociationId sets the AssociationId field's value. +func (s *Ipv6CidrBlockAssociation) SetAssociationId(v string) *Ipv6CidrBlockAssociation { + s.AssociationId = &v + return s +} + +// SetCidrBlockState sets the CidrBlockState field's value. +func (s *Ipv6CidrBlockAssociation) SetCidrBlockState(v string) *Ipv6CidrBlockAssociation { + s.CidrBlockState = &v + return s +} + +// SetIpv6CidrBlock sets the Ipv6CidrBlock field's value. +func (s *Ipv6CidrBlockAssociation) SetIpv6CidrBlock(v string) *Ipv6CidrBlockAssociation { + s.Ipv6CidrBlock = &v + return s +} + // A keyword filter for querying findings. type KeywordFilter struct { _ struct{} `type:"structure"` @@ -12688,6 +13245,9 @@ type Network struct { // The direction of network traffic associated with a finding. Direction *string `type:"string" enum:"NetworkDirection"` + // The range of open ports that is present on the network. + OpenPortRange *PortRange `type:"structure"` + // The protocol of network-related information about a finding. Protocol *string `type:"string"` @@ -12748,6 +13308,12 @@ func (s *Network) SetDirection(v string) *Network { return s } +// SetOpenPortRange sets the OpenPortRange field's value. +func (s *Network) SetOpenPortRange(v *PortRange) *Network { + s.OpenPortRange = v + return s +} + // SetProtocol sets the Protocol field's value. func (s *Network) SetProtocol(v string) *Network { s.Protocol = &v @@ -12784,6 +13350,135 @@ func (s *Network) SetSourcePort(v int64) *Network { return s } +// Details about a network path component that occurs before or after the current +// component. +type NetworkHeader struct { + _ struct{} `type:"structure"` + + // Information about the destination of the component. + Destination *NetworkPathComponentDetails `type:"structure"` + + // The protocol used for the component. + Protocol *string `type:"string"` + + // Information about the origin of the component. + Source *NetworkPathComponentDetails `type:"structure"` +} + +// String returns the string representation +func (s NetworkHeader) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s NetworkHeader) GoString() string { + return s.String() +} + +// SetDestination sets the Destination field's value. +func (s *NetworkHeader) SetDestination(v *NetworkPathComponentDetails) *NetworkHeader { + s.Destination = v + return s +} + +// SetProtocol sets the Protocol field's value. +func (s *NetworkHeader) SetProtocol(v string) *NetworkHeader { + s.Protocol = &v + return s +} + +// SetSource sets the Source field's value. +func (s *NetworkHeader) SetSource(v *NetworkPathComponentDetails) *NetworkHeader { + s.Source = v + return s +} + +// Information about a network path component. +type NetworkPathComponent struct { + _ struct{} `type:"structure"` + + // The identifier of a component in the network path. + ComponentId *string `type:"string"` + + // The type of component. + ComponentType *string `type:"string"` + + // Information about the component that comes after the current component in + // the network path. + Egress *NetworkHeader `type:"structure"` + + // Information about the component that comes before the current node in the + // network path. + Ingress *NetworkHeader `type:"structure"` +} + +// String returns the string representation +func (s NetworkPathComponent) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s NetworkPathComponent) GoString() string { + return s.String() +} + +// SetComponentId sets the ComponentId field's value. +func (s *NetworkPathComponent) SetComponentId(v string) *NetworkPathComponent { + s.ComponentId = &v + return s +} + +// SetComponentType sets the ComponentType field's value. +func (s *NetworkPathComponent) SetComponentType(v string) *NetworkPathComponent { + s.ComponentType = &v + return s +} + +// SetEgress sets the Egress field's value. +func (s *NetworkPathComponent) SetEgress(v *NetworkHeader) *NetworkPathComponent { + s.Egress = v + return s +} + +// SetIngress sets the Ingress field's value. +func (s *NetworkPathComponent) SetIngress(v *NetworkHeader) *NetworkPathComponent { + s.Ingress = v + return s +} + +// Information about the destination of the next component in the network path. +type NetworkPathComponentDetails struct { + _ struct{} `type:"structure"` + + // The IP addresses of the destination. + Address []*string `type:"list"` + + // A list of port ranges for the destination. + PortRanges []*PortRange `type:"list"` +} + +// String returns the string representation +func (s NetworkPathComponentDetails) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s NetworkPathComponentDetails) GoString() string { + return s.String() +} + +// SetAddress sets the Address field's value. +func (s *NetworkPathComponentDetails) SetAddress(v []*string) *NetworkPathComponentDetails { + s.Address = v + return s +} + +// SetPortRanges sets the PortRanges field's value. +func (s *NetworkPathComponentDetails) SetPortRanges(v []*PortRange) *NetworkPathComponentDetails { + s.PortRanges = v + return s +} + // A user-defined note added to a finding. type Note struct { _ struct{} `type:"structure"` @@ -12949,6 +13644,39 @@ func (s *NumberFilter) SetLte(v float64) *NumberFilter { return s } +// A range of ports. +type PortRange struct { + _ struct{} `type:"structure"` + + // The first port in the port range. + Begin *int64 `type:"integer"` + + // The last port in the port range. + End *int64 `type:"integer"` +} + +// String returns the string representation +func (s PortRange) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PortRange) GoString() string { + return s.String() +} + +// SetBegin sets the Begin field's value. +func (s *PortRange) SetBegin(v int64) *PortRange { + s.Begin = &v + return s +} + +// SetEnd sets the End field's value. +func (s *PortRange) SetEnd(v int64) *PortRange { + s.End = &v + return s +} + // The details of process-related information about a finding. type ProcessDetails struct { _ struct{} `type:"structure"` @@ -13408,6 +14136,9 @@ func (s *ResourceConflictException) RequestID() string { type ResourceDetails struct { _ struct{} `type:"structure"` + // Details for an autoscaling group. + AwsAutoScalingAutoScalingGroup *AwsAutoScalingAutoScalingGroupDetails `type:"structure"` + // Details about a CloudFront distribution. AwsCloudFrontDistribution *AwsCloudFrontDistributionDetails `type:"structure"` @@ -13417,12 +14148,18 @@ type ResourceDetails struct { // Details about an Amazon EC2 instance related to a finding. AwsEc2Instance *AwsEc2InstanceDetails `type:"structure"` - // Details for an AWS EC2 network interface. + // Details for an Amazon EC2 network interface. AwsEc2NetworkInterface *AwsEc2NetworkInterfaceDetails `type:"structure"` // Details for an EC2 security group. AwsEc2SecurityGroup *AwsEc2SecurityGroupDetails `type:"structure"` + // Details for an EC2 volume. + AwsEc2Volume *AwsEc2VolumeDetails `type:"structure"` + + // Details for an EC2 VPC. + AwsEc2Vpc *AwsEc2VpcDetails `type:"structure"` + // Details for an Elasticsearch domain. AwsElasticsearchDomain *AwsElasticsearchDomainDetails `type:"structure"` @@ -13444,10 +14181,10 @@ type ResourceDetails struct { // Details for a Lambda layer version. AwsLambdaLayerVersion *AwsLambdaLayerVersionDetails `type:"structure"` - // Details for an RDS database instance. + // Details for an Amazon RDS database instance. AwsRdsDbInstance *AwsRdsDbInstanceDetails `type:"structure"` - // Details about an Amazon S3 Bucket related to a finding. + // Details about an Amazon S3 bucket related to a finding. AwsS3Bucket *AwsS3BucketDetails `type:"structure"` // Details about an Amazon S3 object related to a finding. @@ -13503,6 +14240,12 @@ func (s *ResourceDetails) Validate() error { return nil } +// SetAwsAutoScalingAutoScalingGroup sets the AwsAutoScalingAutoScalingGroup field's value. +func (s *ResourceDetails) SetAwsAutoScalingAutoScalingGroup(v *AwsAutoScalingAutoScalingGroupDetails) *ResourceDetails { + s.AwsAutoScalingAutoScalingGroup = v + return s +} + // SetAwsCloudFrontDistribution sets the AwsCloudFrontDistribution field's value. func (s *ResourceDetails) SetAwsCloudFrontDistribution(v *AwsCloudFrontDistributionDetails) *ResourceDetails { s.AwsCloudFrontDistribution = v @@ -13533,6 +14276,18 @@ func (s *ResourceDetails) SetAwsEc2SecurityGroup(v *AwsEc2SecurityGroupDetails) return s } +// SetAwsEc2Volume sets the AwsEc2Volume field's value. +func (s *ResourceDetails) SetAwsEc2Volume(v *AwsEc2VolumeDetails) *ResourceDetails { + s.AwsEc2Volume = v + return s +} + +// SetAwsEc2Vpc sets the AwsEc2Vpc field's value. +func (s *ResourceDetails) SetAwsEc2Vpc(v *AwsEc2VpcDetails) *ResourceDetails { + s.AwsEc2Vpc = v + return s +} + // SetAwsElasticsearchDomain sets the AwsElasticsearchDomain field's value. func (s *ResourceDetails) SetAwsElasticsearchDomain(v *AwsElasticsearchDomainDetails) *ResourceDetails { s.AwsElasticsearchDomain = v @@ -13715,6 +14470,15 @@ func (s *Result) SetProcessingResult(v string) *Result { } // The severity of the finding. +// +// The finding provider can provide the initial severity, but cannot update +// it after that. The severity can only be updated by a master account. It cannot +// be updated by a member account. +// +// The finding must have either Label or Normalized populated. If only one of +// these attributes is populated, then Security Hub automatically populates +// the other one. If neither attribute is populated, then the finding is invalid. +// Label is the preferred attribute. type Severity struct { _ struct{} `type:"structure"` @@ -13729,12 +14493,8 @@ type Severity struct { // * HIGH - The issue must be addressed as a priority. // // * CRITICAL - The issue must be remediated immediately to avoid it escalating. - Label *string `type:"string" enum:"SeverityLabel"` - - // Deprecated. This attribute is being deprecated. Instead of providing Normalized, - // provide Label. // - // If you provide Normalized and do not provide Label, Label is set automatically + // If you provide Normalized and do not provide Label, then Label is set automatically // as follows. // // * 0 - INFORMATIONAL @@ -13746,8 +14506,31 @@ type Severity struct { // * 70–89 - HIGH // // * 90–100 - CRITICAL + Label *string `type:"string" enum:"SeverityLabel"` + + // Deprecated. The normalized severity of a finding. This attribute is being + // deprecated. Instead of providing Normalized, provide Label. + // + // If you provide Label and do not provide Normalized, then Normalized is set + // automatically as follows. + // + // * INFORMATIONAL - 0 + // + // * LOW - 1 + // + // * MEDIUM - 40 + // + // * HIGH - 70 + // + // * CRITICAL - 90 Normalized *int64 `type:"integer"` + // The native severity from the finding product that generated the finding. + Original *string `type:"string"` + + // Deprecated. This attribute is being deprecated. Instead of providing Product, + // provide Original. + // // The native severity as defined by the AWS service or integrated partner product // that generated the finding. Product *float64 `type:"double"` @@ -13775,6 +14558,12 @@ func (s *Severity) SetNormalized(v int64) *Severity { return s } +// SetOriginal sets the Original field's value. +func (s *Severity) SetOriginal(v string) *Severity { + s.Original = &v + return s +} + // SetProduct sets the Product field's value. func (s *Severity) SetProduct(v float64) *Severity { s.Product = &v @@ -13848,6 +14637,66 @@ func (s *SeverityUpdate) SetProduct(v float64) *SeverityUpdate { return s } +// Information about a software package. +type SoftwarePackage struct { + _ struct{} `type:"structure"` + + // The architecture used for the software package. + Architecture *string `type:"string"` + + // The epoch of the software package. + Epoch *string `type:"string"` + + // The name of the software package. + Name *string `type:"string"` + + // The release of the software package. + Release *string `type:"string"` + + // The version of the software package. + Version *string `type:"string"` +} + +// String returns the string representation +func (s SoftwarePackage) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s SoftwarePackage) GoString() string { + return s.String() +} + +// SetArchitecture sets the Architecture field's value. +func (s *SoftwarePackage) SetArchitecture(v string) *SoftwarePackage { + s.Architecture = &v + return s +} + +// SetEpoch sets the Epoch field's value. +func (s *SoftwarePackage) SetEpoch(v string) *SoftwarePackage { + s.Epoch = &v + return s +} + +// SetName sets the Name field's value. +func (s *SoftwarePackage) SetName(v string) *SoftwarePackage { + s.Name = &v + return s +} + +// SetRelease sets the Release field's value. +func (s *SoftwarePackage) SetRelease(v string) *SoftwarePackage { + s.Release = &v + return s +} + +// SetVersion sets the Version field's value. +func (s *SoftwarePackage) SetVersion(v string) *SoftwarePackage { + s.Version = &v + return s +} + // A collection of finding attributes used to sort findings. type SortCriterion struct { _ struct{} `type:"structure"` @@ -14158,6 +15007,57 @@ func (s *StandardsSubscriptionRequest) SetStandardsInput(v map[string]*string) * return s } +// Provides additional context for the value of Compliance.Status. +type StatusReason struct { + _ struct{} `type:"structure"` + + // The corresponding description for the status reason code. + Description *string `type:"string"` + + // A code that represents a reason for the control status. For the list of status + // reason codes and their meanings, see Standards-related information in the + // ASFF (https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-results.html#securityhub-standards-results-asff) + // in the AWS Security Hub User Guide. + // + // ReasonCode is a required field + ReasonCode *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s StatusReason) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StatusReason) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StatusReason) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StatusReason"} + if s.ReasonCode == nil { + invalidParams.Add(request.NewErrParamRequired("ReasonCode")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *StatusReason) SetDescription(v string) *StatusReason { + s.Description = &v + return s +} + +// SetReasonCode sets the ReasonCode field's value. +func (s *StatusReason) SetReasonCode(v string) *StatusReason { + s.ReasonCode = &v + return s +} + // A string filter for querying findings. type StringFilter struct { _ struct{} `type:"structure"` @@ -14636,6 +15536,47 @@ func (s UpdateInsightOutput) GoString() string { return s.String() } +type UpdateSecurityHubConfigurationInput struct { + _ struct{} `type:"structure"` + + // Whether to automatically enable new controls when they are added to standards + // that are enabled. + // + // By default, this is set to true, and new controls are enabled automatically. + // To not automatically enable new controls, set this to false. + AutoEnableControls *bool `type:"boolean"` +} + +// String returns the string representation +func (s UpdateSecurityHubConfigurationInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateSecurityHubConfigurationInput) GoString() string { + return s.String() +} + +// SetAutoEnableControls sets the AutoEnableControls field's value. +func (s *UpdateSecurityHubConfigurationInput) SetAutoEnableControls(v bool) *UpdateSecurityHubConfigurationInput { + s.AutoEnableControls = &v + return s +} + +type UpdateSecurityHubConfigurationOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UpdateSecurityHubConfigurationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateSecurityHubConfigurationOutput) GoString() string { + return s.String() +} + type UpdateStandardsControlInput struct { _ struct{} `type:"structure"` @@ -14643,6 +15584,7 @@ type UpdateStandardsControlInput struct { ControlStatus *string `type:"string" enum:"ControlStatus"` // A description of the reason why you are disabling a security standard control. + // If you are disabling a control, then this is required. DisabledReason *string `type:"string"` // The ARN of the security standard control to enable or disable. @@ -14709,13 +15651,177 @@ func (s UpdateStandardsControlOutput) GoString() string { return s.String() } +// A vulnerability associated with a finding. +type Vulnerability struct { + _ struct{} `type:"structure"` + + // CVSS scores from the advisory related to the vulnerability. + Cvss []*Cvss `type:"list"` + + // The identifier of the vulnerability. + // + // Id is a required field + Id *string `type:"string" required:"true"` + + // A list of URLs that provide additional information about the vulnerability. + ReferenceUrls []*string `type:"list"` + + // List of vulnerabilities that are related to this vulnerability. + RelatedVulnerabilities []*string `type:"list"` + + // Information about the vendor that generates the vulnerability report. + Vendor *VulnerabilityVendor `type:"structure"` + + // List of software packages that have the vulnerability. + VulnerablePackages []*SoftwarePackage `type:"list"` +} + +// String returns the string representation +func (s Vulnerability) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Vulnerability) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Vulnerability) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Vulnerability"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Vendor != nil { + if err := s.Vendor.Validate(); err != nil { + invalidParams.AddNested("Vendor", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCvss sets the Cvss field's value. +func (s *Vulnerability) SetCvss(v []*Cvss) *Vulnerability { + s.Cvss = v + return s +} + +// SetId sets the Id field's value. +func (s *Vulnerability) SetId(v string) *Vulnerability { + s.Id = &v + return s +} + +// SetReferenceUrls sets the ReferenceUrls field's value. +func (s *Vulnerability) SetReferenceUrls(v []*string) *Vulnerability { + s.ReferenceUrls = v + return s +} + +// SetRelatedVulnerabilities sets the RelatedVulnerabilities field's value. +func (s *Vulnerability) SetRelatedVulnerabilities(v []*string) *Vulnerability { + s.RelatedVulnerabilities = v + return s +} + +// SetVendor sets the Vendor field's value. +func (s *Vulnerability) SetVendor(v *VulnerabilityVendor) *Vulnerability { + s.Vendor = v + return s +} + +// SetVulnerablePackages sets the VulnerablePackages field's value. +func (s *Vulnerability) SetVulnerablePackages(v []*SoftwarePackage) *Vulnerability { + s.VulnerablePackages = v + return s +} + +// A vendor that generates a vulnerability report. +type VulnerabilityVendor struct { + _ struct{} `type:"structure"` + + // The name of the vendor. + // + // Name is a required field + Name *string `type:"string" required:"true"` + + // The URL of the vulnerability advisory. + Url *string `type:"string"` + + // The datetime when the vulnerability advisory was created. + VendorCreatedAt *string `type:"string"` + + // The severity that the vendor assigned to the vulnerability. + VendorSeverity *string `type:"string"` + + // The datetime when the vulnerability advisory was last updated. + VendorUpdatedAt *string `type:"string"` +} + +// String returns the string representation +func (s VulnerabilityVendor) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s VulnerabilityVendor) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *VulnerabilityVendor) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "VulnerabilityVendor"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *VulnerabilityVendor) SetName(v string) *VulnerabilityVendor { + s.Name = &v + return s +} + +// SetUrl sets the Url field's value. +func (s *VulnerabilityVendor) SetUrl(v string) *VulnerabilityVendor { + s.Url = &v + return s +} + +// SetVendorCreatedAt sets the VendorCreatedAt field's value. +func (s *VulnerabilityVendor) SetVendorCreatedAt(v string) *VulnerabilityVendor { + s.VendorCreatedAt = &v + return s +} + +// SetVendorSeverity sets the VendorSeverity field's value. +func (s *VulnerabilityVendor) SetVendorSeverity(v string) *VulnerabilityVendor { + s.VendorSeverity = &v + return s +} + +// SetVendorUpdatedAt sets the VendorUpdatedAt field's value. +func (s *VulnerabilityVendor) SetVendorUpdatedAt(v string) *VulnerabilityVendor { + s.VendorUpdatedAt = &v + return s +} + // Details about the action that CloudFront or AWS WAF takes when a web request -// matches the conditions in the Rule. +// matches the conditions in the rule. type WafAction struct { _ struct{} `type:"structure"` // Specifies how you want AWS WAF to respond to requests that match the settings - // in a Rule. + // in a rule. // // Valid settings include the following: // @@ -14878,6 +15984,14 @@ const ( AwsIamAccessKeyStatusInactive = "Inactive" ) +// AwsIamAccessKeyStatus_Values returns all elements of the AwsIamAccessKeyStatus enum +func AwsIamAccessKeyStatus_Values() []string { + return []string{ + AwsIamAccessKeyStatusActive, + AwsIamAccessKeyStatusInactive, + } +} + const ( // ComplianceStatusPassed is a ComplianceStatus enum value ComplianceStatusPassed = "PASSED" @@ -14892,6 +16006,16 @@ const ( ComplianceStatusNotAvailable = "NOT_AVAILABLE" ) +// ComplianceStatus_Values returns all elements of the ComplianceStatus enum +func ComplianceStatus_Values() []string { + return []string{ + ComplianceStatusPassed, + ComplianceStatusWarning, + ComplianceStatusFailed, + ComplianceStatusNotAvailable, + } +} + const ( // ControlStatusEnabled is a ControlStatus enum value ControlStatusEnabled = "ENABLED" @@ -14900,11 +16024,26 @@ const ( ControlStatusDisabled = "DISABLED" ) +// ControlStatus_Values returns all elements of the ControlStatus enum +func ControlStatus_Values() []string { + return []string{ + ControlStatusEnabled, + ControlStatusDisabled, + } +} + const ( // DateRangeUnitDays is a DateRangeUnit enum value DateRangeUnitDays = "DAYS" ) +// DateRangeUnit_Values returns all elements of the DateRangeUnit enum +func DateRangeUnit_Values() []string { + return []string{ + DateRangeUnitDays, + } +} + const ( // IntegrationTypeSendFindingsToSecurityHub is a IntegrationType enum value IntegrationTypeSendFindingsToSecurityHub = "SEND_FINDINGS_TO_SECURITY_HUB" @@ -14913,6 +16052,14 @@ const ( IntegrationTypeReceiveFindingsFromSecurityHub = "RECEIVE_FINDINGS_FROM_SECURITY_HUB" ) +// IntegrationType_Values returns all elements of the IntegrationType enum +func IntegrationType_Values() []string { + return []string{ + IntegrationTypeSendFindingsToSecurityHub, + IntegrationTypeReceiveFindingsFromSecurityHub, + } +} + const ( // MalwareStateObserved is a MalwareState enum value MalwareStateObserved = "OBSERVED" @@ -14924,6 +16071,15 @@ const ( MalwareStateRemoved = "REMOVED" ) +// MalwareState_Values returns all elements of the MalwareState enum +func MalwareState_Values() []string { + return []string{ + MalwareStateObserved, + MalwareStateRemovalFailed, + MalwareStateRemoved, + } +} + const ( // MalwareTypeAdware is a MalwareType enum value MalwareTypeAdware = "ADWARE" @@ -14971,11 +16127,39 @@ const ( MalwareTypeWorm = "WORM" ) +// MalwareType_Values returns all elements of the MalwareType enum +func MalwareType_Values() []string { + return []string{ + MalwareTypeAdware, + MalwareTypeBlendedThreat, + MalwareTypeBotnetAgent, + MalwareTypeCoinMiner, + MalwareTypeExploitKit, + MalwareTypeKeylogger, + MalwareTypeMacro, + MalwareTypePotentiallyUnwanted, + MalwareTypeSpyware, + MalwareTypeRansomware, + MalwareTypeRemoteAccess, + MalwareTypeRootkit, + MalwareTypeTrojan, + MalwareTypeVirus, + MalwareTypeWorm, + } +} + const ( // MapFilterComparisonEquals is a MapFilterComparison enum value MapFilterComparisonEquals = "EQUALS" ) +// MapFilterComparison_Values returns all elements of the MapFilterComparison enum +func MapFilterComparison_Values() []string { + return []string{ + MapFilterComparisonEquals, + } +} + const ( // NetworkDirectionIn is a NetworkDirection enum value NetworkDirectionIn = "IN" @@ -14984,6 +16168,14 @@ const ( NetworkDirectionOut = "OUT" ) +// NetworkDirection_Values returns all elements of the NetworkDirection enum +func NetworkDirection_Values() []string { + return []string{ + NetworkDirectionIn, + NetworkDirectionOut, + } +} + const ( // PartitionAws is a Partition enum value PartitionAws = "aws" @@ -14995,6 +16187,15 @@ const ( PartitionAwsUsGov = "aws-us-gov" ) +// Partition_Values returns all elements of the Partition enum +func Partition_Values() []string { + return []string{ + PartitionAws, + PartitionAwsCn, + PartitionAwsUsGov, + } +} + const ( // RecordStateActive is a RecordState enum value RecordStateActive = "ACTIVE" @@ -15003,6 +16204,14 @@ const ( RecordStateArchived = "ARCHIVED" ) +// RecordState_Values returns all elements of the RecordState enum +func RecordState_Values() []string { + return []string{ + RecordStateActive, + RecordStateArchived, + } +} + const ( // SeverityLabelInformational is a SeverityLabel enum value SeverityLabelInformational = "INFORMATIONAL" @@ -15020,6 +16229,17 @@ const ( SeverityLabelCritical = "CRITICAL" ) +// SeverityLabel_Values returns all elements of the SeverityLabel enum +func SeverityLabel_Values() []string { + return []string{ + SeverityLabelInformational, + SeverityLabelLow, + SeverityLabelMedium, + SeverityLabelHigh, + SeverityLabelCritical, + } +} + const ( // SeverityRatingLow is a SeverityRating enum value SeverityRatingLow = "LOW" @@ -15034,6 +16254,16 @@ const ( SeverityRatingCritical = "CRITICAL" ) +// SeverityRating_Values returns all elements of the SeverityRating enum +func SeverityRating_Values() []string { + return []string{ + SeverityRatingLow, + SeverityRatingMedium, + SeverityRatingHigh, + SeverityRatingCritical, + } +} + const ( // SortOrderAsc is a SortOrder enum value SortOrderAsc = "asc" @@ -15042,6 +16272,14 @@ const ( SortOrderDesc = "desc" ) +// SortOrder_Values returns all elements of the SortOrder enum +func SortOrder_Values() []string { + return []string{ + SortOrderAsc, + SortOrderDesc, + } +} + const ( // StandardsStatusPending is a StandardsStatus enum value StandardsStatusPending = "PENDING" @@ -15059,6 +16297,17 @@ const ( StandardsStatusIncomplete = "INCOMPLETE" ) +// StandardsStatus_Values returns all elements of the StandardsStatus enum +func StandardsStatus_Values() []string { + return []string{ + StandardsStatusPending, + StandardsStatusReady, + StandardsStatusFailed, + StandardsStatusDeleting, + StandardsStatusIncomplete, + } +} + const ( // StringFilterComparisonEquals is a StringFilterComparison enum value StringFilterComparisonEquals = "EQUALS" @@ -15067,6 +16316,14 @@ const ( StringFilterComparisonPrefix = "PREFIX" ) +// StringFilterComparison_Values returns all elements of the StringFilterComparison enum +func StringFilterComparison_Values() []string { + return []string{ + StringFilterComparisonEquals, + StringFilterComparisonPrefix, + } +} + const ( // ThreatIntelIndicatorCategoryBackdoor is a ThreatIntelIndicatorCategory enum value ThreatIntelIndicatorCategoryBackdoor = "BACKDOOR" @@ -15087,6 +16344,18 @@ const ( ThreatIntelIndicatorCategoryKeylogger = "KEYLOGGER" ) +// ThreatIntelIndicatorCategory_Values returns all elements of the ThreatIntelIndicatorCategory enum +func ThreatIntelIndicatorCategory_Values() []string { + return []string{ + ThreatIntelIndicatorCategoryBackdoor, + ThreatIntelIndicatorCategoryCardStealer, + ThreatIntelIndicatorCategoryCommandAndControl, + ThreatIntelIndicatorCategoryDropSite, + ThreatIntelIndicatorCategoryExploitSite, + ThreatIntelIndicatorCategoryKeylogger, + } +} + const ( // ThreatIntelIndicatorTypeDomain is a ThreatIntelIndicatorType enum value ThreatIntelIndicatorTypeDomain = "DOMAIN" @@ -15122,6 +16391,23 @@ const ( ThreatIntelIndicatorTypeUrl = "URL" ) +// ThreatIntelIndicatorType_Values returns all elements of the ThreatIntelIndicatorType enum +func ThreatIntelIndicatorType_Values() []string { + return []string{ + ThreatIntelIndicatorTypeDomain, + ThreatIntelIndicatorTypeEmailAddress, + ThreatIntelIndicatorTypeHashMd5, + ThreatIntelIndicatorTypeHashSha1, + ThreatIntelIndicatorTypeHashSha256, + ThreatIntelIndicatorTypeHashSha512, + ThreatIntelIndicatorTypeIpv4Address, + ThreatIntelIndicatorTypeIpv6Address, + ThreatIntelIndicatorTypeMutex, + ThreatIntelIndicatorTypeProcess, + ThreatIntelIndicatorTypeUrl, + } +} + const ( // VerificationStateUnknown is a VerificationState enum value VerificationStateUnknown = "UNKNOWN" @@ -15136,6 +16422,16 @@ const ( VerificationStateBenignPositive = "BENIGN_POSITIVE" ) +// VerificationState_Values returns all elements of the VerificationState enum +func VerificationState_Values() []string { + return []string{ + VerificationStateUnknown, + VerificationStateTruePositive, + VerificationStateFalsePositive, + VerificationStateBenignPositive, + } +} + const ( // WorkflowStateNew is a WorkflowState enum value WorkflowStateNew = "NEW" @@ -15153,6 +16449,17 @@ const ( WorkflowStateResolved = "RESOLVED" ) +// WorkflowState_Values returns all elements of the WorkflowState enum +func WorkflowState_Values() []string { + return []string{ + WorkflowStateNew, + WorkflowStateAssigned, + WorkflowStateInProgress, + WorkflowStateDeferred, + WorkflowStateResolved, + } +} + const ( // WorkflowStatusNew is a WorkflowStatus enum value WorkflowStatusNew = "NEW" @@ -15166,3 +16473,13 @@ const ( // WorkflowStatusSuppressed is a WorkflowStatus enum value WorkflowStatusSuppressed = "SUPPRESSED" ) + +// WorkflowStatus_Values returns all elements of the WorkflowStatus enum +func WorkflowStatus_Values() []string { + return []string{ + WorkflowStatusNew, + WorkflowStatusNotified, + WorkflowStatusResolved, + WorkflowStatusSuppressed, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/serverlessapplicationrepository/api.go b/vendor/github.com/aws/aws-sdk-go/service/serverlessapplicationrepository/api.go index b87d26a28bc..803a1cef58c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/serverlessapplicationrepository/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/serverlessapplicationrepository/api.go @@ -4520,6 +4520,16 @@ const ( CapabilityCapabilityResourcePolicy = "CAPABILITY_RESOURCE_POLICY" ) +// Capability_Values returns all elements of the Capability enum +func Capability_Values() []string { + return []string{ + CapabilityCapabilityIam, + CapabilityCapabilityNamedIam, + CapabilityCapabilityAutoExpand, + CapabilityCapabilityResourcePolicy, + } +} + const ( // StatusPreparing is a Status enum value StatusPreparing = "PREPARING" @@ -4530,3 +4540,12 @@ const ( // StatusExpired is a Status enum value StatusExpired = "EXPIRED" ) + +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusPreparing, + StatusActive, + StatusExpired, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/servicecatalog/api.go b/vendor/github.com/aws/aws-sdk-go/service/servicecatalog/api.go index ef25beaffd9..8d3b963acab 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/servicecatalog/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/servicecatalog/api.go @@ -327,6 +327,8 @@ func (c *ServiceCatalog) AssociateProductWithPortfolioRequest(input *AssociatePr // // Associates the specified product with the specified portfolio. // +// A delegated admin is authorized to invoke this command. +// // Returns awserr.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. @@ -851,6 +853,8 @@ func (c *ServiceCatalog) CreateConstraintRequest(input *CreateConstraintInput) ( // // Creates a constraint. // +// A delegated admin is authorized to invoke this command. +// // Returns awserr.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. @@ -941,6 +945,8 @@ func (c *ServiceCatalog) CreatePortfolioRequest(input *CreatePortfolioInput) (re // // Creates a portfolio. // +// A delegated admin is authorized to invoke this command. +// // Returns awserr.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. @@ -1030,8 +1036,17 @@ func (c *ServiceCatalog) CreatePortfolioShareRequest(input *CreatePortfolioShare // // Shares the specified portfolio with the specified account or organization // node. Shares to an organization node can only be created by the master account -// of an Organization. AWSOrganizationsAccess must be enabled in order to create -// a portfolio share to an organization node. +// of an organization or by a delegated administrator. You can share portfolios +// to an organization, an organizational unit, or a specific account. +// +// Note that if a delegated admin is de-registered, they can no longer create +// portfolio shares. +// +// AWSOrganizationsAccess must be enabled in order to create a portfolio share +// to an organization node. +// +// You can't share a shared resource. This includes portfolios that contain +// a shared product. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1128,6 +1143,8 @@ func (c *ServiceCatalog) CreateProductRequest(input *CreateProductInput) (req *r // // Creates a product. // +// A delegated admin is authorized to invoke this command. +// // Returns awserr.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. @@ -1577,6 +1594,8 @@ func (c *ServiceCatalog) DeleteConstraintRequest(input *DeleteConstraintInput) ( // // Deletes the specified constraint. // +// A delegated admin is authorized to invoke this command. +// // Returns awserr.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. @@ -1663,6 +1682,8 @@ func (c *ServiceCatalog) DeletePortfolioRequest(input *DeletePortfolioInput) (re // You cannot delete a portfolio if it was shared with you or if it has associated // products, users, constraints, or shared accounts. // +// A delegated admin is authorized to invoke this command. +// // Returns awserr.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. @@ -1754,7 +1775,10 @@ func (c *ServiceCatalog) DeletePortfolioShareRequest(input *DeletePortfolioShare // // Stops sharing the specified portfolio with the specified account or organization // node. Shares to an organization node can only be deleted by the master account -// of an Organization. +// of an organization or by a delegated administrator. +// +// Note that if a delegated admin is de-registered, portfolio shares created +// from that account are removed. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1850,6 +1874,8 @@ func (c *ServiceCatalog) DeleteProductRequest(input *DeleteProductInput) (req *r // You cannot delete a product if it was shared with you or is associated with // a portfolio. // +// A delegated admin is authorized to invoke this command. +// // Returns awserr.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. @@ -2449,6 +2475,8 @@ func (c *ServiceCatalog) DescribePortfolioRequest(input *DescribePortfolioInput) // // Gets information about the specified portfolio. // +// A delegated admin is authorized to invoke this command. +// // Returns awserr.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. @@ -2527,7 +2555,8 @@ func (c *ServiceCatalog) DescribePortfolioShareStatusRequest(input *DescribePort // DescribePortfolioShareStatus API operation for AWS Service Catalog. // // Gets the status of the specified portfolio share operation. This API can -// only be called by the master account in the organization. +// only be called by the master account in the organization or by a delegated +// admin. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2708,6 +2737,9 @@ func (c *ServiceCatalog) DescribeProductAsAdminRequest(input *DescribeProductAsA // * ResourceNotFoundException // The specified resource was not found. // +// * InvalidParametersException +// One or more parameters provided to the operation are not valid. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeProductAsAdmin func (c *ServiceCatalog) DescribeProductAsAdmin(input *DescribeProductAsAdminInput) (*DescribeProductAsAdminOutput, error) { req, out := c.DescribeProductAsAdminRequest(input) @@ -3031,6 +3063,9 @@ func (c *ServiceCatalog) DescribeProvisioningArtifactRequest(input *DescribeProv // * ResourceNotFoundException // The specified resource was not found. // +// * InvalidParametersException +// One or more parameters provided to the operation are not valid. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeProvisioningArtifact func (c *ServiceCatalog) DescribeProvisioningArtifact(input *DescribeProvisioningArtifactInput) (*DescribeProvisioningArtifactOutput, error) { req, out := c.DescribeProvisioningArtifactRequest(input) @@ -3528,6 +3563,11 @@ func (c *ServiceCatalog) DisableAWSOrganizationsAccessRequest(input *DisableAWSO // with your organization structure if it changes after calling this API. This // API can only be called by the master account in the organization. // +// This API can't be invoked if there are active delegated administrators in +// the organization. +// +// Note that a delegated administrator is not authorized to invoke DisableAWSOrganizationsAccess. +// // Returns awserr.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. @@ -3779,6 +3819,8 @@ func (c *ServiceCatalog) DisassociateProductFromPortfolioRequest(input *Disassoc // // Disassociates the specified product from the specified portfolio. // +// A delegated admin is authorized to invoke this command. +// // Returns awserr.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. @@ -4039,6 +4081,8 @@ func (c *ServiceCatalog) EnableAWSOrganizationsAccessRequest(input *EnableAWSOrg // on your behalf so that your shares can be in sync with any changes in your // AWS Organizations structure. // +// Note that a delegated administrator is not authorized to invoke EnableAWSOrganizationsAccess. +// // Returns awserr.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. @@ -4300,7 +4344,8 @@ func (c *ServiceCatalog) GetAWSOrganizationsAccessStatusRequest(input *GetAWSOrg // GetAWSOrganizationsAccessStatus API operation for AWS Service Catalog. // // Get the Access Status for AWS Organization portfolio share feature. This -// API can only be called by the master account in the organization. +// API can only be called by the master account in the organization or by a +// delegated admin. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -4951,7 +4996,10 @@ func (c *ServiceCatalog) ListOrganizationPortfolioAccessRequest(input *ListOrgan // ListOrganizationPortfolioAccess API operation for AWS Service Catalog. // // Lists the organization nodes that have access to the specified portfolio. -// This API can only be called by the master account in the organization. +// This API can only be called by the master account in the organization or +// by a delegated admin. +// +// If a delegated admin is de-registered, they can no longer perform 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 @@ -5096,6 +5144,10 @@ func (c *ServiceCatalog) ListPortfolioAccessRequest(input *ListPortfolioAccessIn // // Lists the account IDs that have access to the specified portfolio. // +// A delegated admin can list the accounts that have access to the shared portfolio. +// Note that if a delegated admin is de-registered, they can no longer perform +// 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. @@ -10256,7 +10308,11 @@ type CreateServiceActionInput struct { // // Name // - // The name of the AWS Systems Manager Document. For example, AWS-RestartEC2Instance. + // The name of the AWS Systems Manager document (SSM document). For example, + // AWS-RestartEC2Instance. + // + // If you are using a shared SSM document, you must provide the ARN instead + // of the name. // // Version // @@ -11491,9 +11547,10 @@ type DescribeProductAsAdminInput struct { AcceptLanguage *string `type:"string"` // The product identifier. - // - // Id is a required field - Id *string `min:"1" type:"string" required:"true"` + Id *string `min:"1" type:"string"` + + // The product name. + Name *string `type:"string"` } // String returns the string representation @@ -11509,9 +11566,6 @@ func (s DescribeProductAsAdminInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeProductAsAdminInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "DescribeProductAsAdminInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } if s.Id != nil && len(*s.Id) < 1 { invalidParams.Add(request.NewErrParamMinLen("Id", 1)) } @@ -11534,6 +11588,12 @@ func (s *DescribeProductAsAdminInput) SetId(v string) *DescribeProductAsAdminInp return s } +// SetName sets the Name field's value. +func (s *DescribeProductAsAdminInput) SetName(v string) *DescribeProductAsAdminInput { + s.Name = &v + return s +} + type DescribeProductAsAdminOutput struct { _ struct{} `type:"structure"` @@ -11607,9 +11667,10 @@ type DescribeProductInput struct { AcceptLanguage *string `type:"string"` // The product identifier. - // - // Id is a required field - Id *string `min:"1" type:"string" required:"true"` + Id *string `min:"1" type:"string"` + + // The product name. + Name *string `type:"string"` } // String returns the string representation @@ -11625,9 +11686,6 @@ func (s DescribeProductInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeProductInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "DescribeProductInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } if s.Id != nil && len(*s.Id) < 1 { invalidParams.Add(request.NewErrParamMinLen("Id", 1)) } @@ -11650,12 +11708,21 @@ func (s *DescribeProductInput) SetId(v string) *DescribeProductInput { return s } +// SetName sets the Name field's value. +func (s *DescribeProductInput) SetName(v string) *DescribeProductInput { + s.Name = &v + return s +} + type DescribeProductOutput struct { _ struct{} `type:"structure"` // Information about the associated budgets. Budgets []*BudgetDetail `type:"list"` + // Information about the associated launch paths. + LaunchPaths []*LaunchPath `type:"list"` + // Summary information about the product view. ProductViewSummary *ProductViewSummary `type:"structure"` @@ -11679,6 +11746,12 @@ func (s *DescribeProductOutput) SetBudgets(v []*BudgetDetail) *DescribeProductOu return s } +// SetLaunchPaths sets the LaunchPaths field's value. +func (s *DescribeProductOutput) SetLaunchPaths(v []*LaunchPath) *DescribeProductOutput { + s.LaunchPaths = v + return s +} + // SetProductViewSummary sets the ProductViewSummary field's value. func (s *DescribeProductOutput) SetProductViewSummary(v *ProductViewSummary) *DescribeProductOutput { s.ProductViewSummary = v @@ -11997,14 +12070,16 @@ type DescribeProvisioningArtifactInput struct { AcceptLanguage *string `type:"string"` // The product identifier. - // - // ProductId is a required field - ProductId *string `min:"1" type:"string" required:"true"` + ProductId *string `min:"1" type:"string"` + + // The product name. + ProductName *string `type:"string"` // The identifier of the provisioning artifact. - // - // ProvisioningArtifactId is a required field - ProvisioningArtifactId *string `min:"1" type:"string" required:"true"` + ProvisioningArtifactId *string `min:"1" type:"string"` + + // The provisioning artifact name. + ProvisioningArtifactName *string `type:"string"` // Indicates whether a verbose level of detail is enabled. Verbose *bool `type:"boolean"` @@ -12023,15 +12098,9 @@ func (s DescribeProvisioningArtifactInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *DescribeProvisioningArtifactInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "DescribeProvisioningArtifactInput"} - if s.ProductId == nil { - invalidParams.Add(request.NewErrParamRequired("ProductId")) - } if s.ProductId != nil && len(*s.ProductId) < 1 { invalidParams.Add(request.NewErrParamMinLen("ProductId", 1)) } - if s.ProvisioningArtifactId == nil { - invalidParams.Add(request.NewErrParamRequired("ProvisioningArtifactId")) - } if s.ProvisioningArtifactId != nil && len(*s.ProvisioningArtifactId) < 1 { invalidParams.Add(request.NewErrParamMinLen("ProvisioningArtifactId", 1)) } @@ -12054,12 +12123,24 @@ func (s *DescribeProvisioningArtifactInput) SetProductId(v string) *DescribeProv return s } +// SetProductName sets the ProductName field's value. +func (s *DescribeProvisioningArtifactInput) SetProductName(v string) *DescribeProvisioningArtifactInput { + s.ProductName = &v + return s +} + // SetProvisioningArtifactId sets the ProvisioningArtifactId field's value. func (s *DescribeProvisioningArtifactInput) SetProvisioningArtifactId(v string) *DescribeProvisioningArtifactInput { s.ProvisioningArtifactId = &v return s } +// SetProvisioningArtifactName sets the ProvisioningArtifactName field's value. +func (s *DescribeProvisioningArtifactInput) SetProvisioningArtifactName(v string) *DescribeProvisioningArtifactInput { + s.ProvisioningArtifactName = &v + return s +} + // SetVerbose sets the Verbose field's value. func (s *DescribeProvisioningArtifactInput) SetVerbose(v bool) *DescribeProvisioningArtifactInput { s.Verbose = &v @@ -12121,18 +12202,27 @@ type DescribeProvisioningParametersInput struct { // The path identifier of the product. This value is optional if the product // has a default path, and required if the product has more than one path. To - // list the paths for a product, use ListLaunchPaths. + // list the paths for a product, use ListLaunchPaths. You must provide the name + // or ID, but not both. PathId *string `min:"1" type:"string"` - // The product identifier. - // - // ProductId is a required field - ProductId *string `min:"1" type:"string" required:"true"` + // The name of the path. You must provide the name or ID, but not both. + PathName *string `min:"1" type:"string"` - // The identifier of the provisioning artifact. - // - // ProvisioningArtifactId is a required field - ProvisioningArtifactId *string `min:"1" type:"string" required:"true"` + // The product identifier. You must provide the product name or ID, but not + // both. + ProductId *string `min:"1" type:"string"` + + // The name of the product. You must provide the name or ID, but not both. + ProductName *string `type:"string"` + + // The identifier of the provisioning artifact. You must provide the name or + // ID, but not both. + ProvisioningArtifactId *string `min:"1" type:"string"` + + // The name of the provisioning artifact. You must provide the name or ID, but + // not both. + ProvisioningArtifactName *string `type:"string"` } // String returns the string representation @@ -12151,15 +12241,12 @@ func (s *DescribeProvisioningParametersInput) Validate() error { if s.PathId != nil && len(*s.PathId) < 1 { invalidParams.Add(request.NewErrParamMinLen("PathId", 1)) } - if s.ProductId == nil { - invalidParams.Add(request.NewErrParamRequired("ProductId")) + if s.PathName != nil && len(*s.PathName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PathName", 1)) } if s.ProductId != nil && len(*s.ProductId) < 1 { invalidParams.Add(request.NewErrParamMinLen("ProductId", 1)) } - if s.ProvisioningArtifactId == nil { - invalidParams.Add(request.NewErrParamRequired("ProvisioningArtifactId")) - } if s.ProvisioningArtifactId != nil && len(*s.ProvisioningArtifactId) < 1 { invalidParams.Add(request.NewErrParamMinLen("ProvisioningArtifactId", 1)) } @@ -12182,24 +12269,45 @@ func (s *DescribeProvisioningParametersInput) SetPathId(v string) *DescribeProvi return s } +// SetPathName sets the PathName field's value. +func (s *DescribeProvisioningParametersInput) SetPathName(v string) *DescribeProvisioningParametersInput { + s.PathName = &v + return s +} + // SetProductId sets the ProductId field's value. func (s *DescribeProvisioningParametersInput) SetProductId(v string) *DescribeProvisioningParametersInput { s.ProductId = &v return s } +// SetProductName sets the ProductName field's value. +func (s *DescribeProvisioningParametersInput) SetProductName(v string) *DescribeProvisioningParametersInput { + s.ProductName = &v + return s +} + // SetProvisioningArtifactId sets the ProvisioningArtifactId field's value. func (s *DescribeProvisioningParametersInput) SetProvisioningArtifactId(v string) *DescribeProvisioningParametersInput { s.ProvisioningArtifactId = &v return s } +// SetProvisioningArtifactName sets the ProvisioningArtifactName field's value. +func (s *DescribeProvisioningParametersInput) SetProvisioningArtifactName(v string) *DescribeProvisioningParametersInput { + s.ProvisioningArtifactName = &v + return s +} + type DescribeProvisioningParametersOutput struct { _ struct{} `type:"structure"` // Information about the constraints used to provision the product. ConstraintSummaries []*ConstraintSummary `type:"list"` + // The output of the provisioning artifact. + ProvisioningArtifactOutputs []*ProvisioningArtifactOutput `type:"list"` + // Information about the parameters used to provision the product. ProvisioningArtifactParameters []*ProvisioningArtifactParameter `type:"list"` @@ -12231,6 +12339,12 @@ func (s *DescribeProvisioningParametersOutput) SetConstraintSummaries(v []*Const return s } +// SetProvisioningArtifactOutputs sets the ProvisioningArtifactOutputs field's value. +func (s *DescribeProvisioningParametersOutput) SetProvisioningArtifactOutputs(v []*ProvisioningArtifactOutput) *DescribeProvisioningParametersOutput { + s.ProvisioningArtifactOutputs = v + return s +} + // SetProvisioningArtifactParameters sets the ProvisioningArtifactParameters field's value. func (s *DescribeProvisioningParametersOutput) SetProvisioningArtifactParameters(v []*ProvisioningArtifactParameter) *DescribeProvisioningParametersOutput { s.ProvisioningArtifactParameters = v @@ -13619,6 +13733,39 @@ func (s *InvalidStateException) RequestID() string { return s.RespMetadata.RequestID } +// A launch path object. +type LaunchPath struct { + _ struct{} `type:"structure"` + + // The identifier of the launch path. + Id *string `min:"1" type:"string"` + + // The name of the launch path. + Name *string `type:"string"` +} + +// String returns the string representation +func (s LaunchPath) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s LaunchPath) GoString() string { + return s.String() +} + +// SetId sets the Id field's value. +func (s *LaunchPath) SetId(v string) *LaunchPath { + s.Id = &v + return s +} + +// SetName sets the Name field's value. +func (s *LaunchPath) SetName(v string) *LaunchPath { + s.Name = &v + return s +} + // Summary information about a product path for a user. type LaunchPathSummary struct { _ struct{} `type:"structure"` @@ -16172,13 +16319,18 @@ type ProvisionProductInput struct { // The path identifier of the product. This value is optional if the product // has a default path, and required if the product has more than one path. To - // list the paths for a product, use ListLaunchPaths. + // list the paths for a product, use ListLaunchPaths. You must provide the name + // or ID, but not both. PathId *string `min:"1" type:"string"` - // The product identifier. - // - // ProductId is a required field - ProductId *string `min:"1" type:"string" required:"true"` + // The name of the path. You must provide the name or ID, but not both. + PathName *string `min:"1" type:"string"` + + // The product identifier. You must provide the name or ID, but not both. + ProductId *string `min:"1" type:"string"` + + // The name of the product. You must provide the name or ID, but not both. + ProductName *string `type:"string"` // An idempotency token that uniquely identifies the provisioning request. ProvisionToken *string `min:"1" type:"string" idempotencyToken:"true"` @@ -16189,10 +16341,13 @@ type ProvisionProductInput struct { // ProvisionedProductName is a required field ProvisionedProductName *string `min:"1" type:"string" required:"true"` - // The identifier of the provisioning artifact. - // - // ProvisioningArtifactId is a required field - ProvisioningArtifactId *string `min:"1" type:"string" required:"true"` + // The identifier of the provisioning artifact. You must provide the name or + // ID, but not both. + ProvisioningArtifactId *string `min:"1" type:"string"` + + // The name of the provisioning artifact. You must provide the name or ID, but + // not both. + ProvisioningArtifactName *string `type:"string"` // Parameters specified by the administrator that are required for provisioning // the product. @@ -16222,8 +16377,8 @@ func (s *ProvisionProductInput) Validate() error { if s.PathId != nil && len(*s.PathId) < 1 { invalidParams.Add(request.NewErrParamMinLen("PathId", 1)) } - if s.ProductId == nil { - invalidParams.Add(request.NewErrParamRequired("ProductId")) + if s.PathName != nil && len(*s.PathName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PathName", 1)) } if s.ProductId != nil && len(*s.ProductId) < 1 { invalidParams.Add(request.NewErrParamMinLen("ProductId", 1)) @@ -16237,9 +16392,6 @@ func (s *ProvisionProductInput) Validate() error { if s.ProvisionedProductName != nil && len(*s.ProvisionedProductName) < 1 { invalidParams.Add(request.NewErrParamMinLen("ProvisionedProductName", 1)) } - if s.ProvisioningArtifactId == nil { - invalidParams.Add(request.NewErrParamRequired("ProvisioningArtifactId")) - } if s.ProvisioningArtifactId != nil && len(*s.ProvisioningArtifactId) < 1 { invalidParams.Add(request.NewErrParamMinLen("ProvisioningArtifactId", 1)) } @@ -16293,12 +16445,24 @@ func (s *ProvisionProductInput) SetPathId(v string) *ProvisionProductInput { return s } +// SetPathName sets the PathName field's value. +func (s *ProvisionProductInput) SetPathName(v string) *ProvisionProductInput { + s.PathName = &v + return s +} + // SetProductId sets the ProductId field's value. func (s *ProvisionProductInput) SetProductId(v string) *ProvisionProductInput { s.ProductId = &v return s } +// SetProductName sets the ProductName field's value. +func (s *ProvisionProductInput) SetProductName(v string) *ProvisionProductInput { + s.ProductName = &v + return s +} + // SetProvisionToken sets the ProvisionToken field's value. func (s *ProvisionProductInput) SetProvisionToken(v string) *ProvisionProductInput { s.ProvisionToken = &v @@ -16317,6 +16481,12 @@ func (s *ProvisionProductInput) SetProvisioningArtifactId(v string) *ProvisionPr return s } +// SetProvisioningArtifactName sets the ProvisioningArtifactName field's value. +func (s *ProvisionProductInput) SetProvisioningArtifactName(v string) *ProvisionProductInput { + s.ProvisioningArtifactName = &v + return s +} + // SetProvisioningParameters sets the ProvisioningParameters field's value. func (s *ProvisionProductInput) SetProvisioningParameters(v []*ProvisioningParameter) *ProvisionProductInput { s.ProvisioningParameters = v @@ -17039,6 +17209,39 @@ func (s *ProvisioningArtifactDetail) SetType(v string) *ProvisioningArtifactDeta return s } +// Provisioning artifact output. +type ProvisioningArtifactOutput struct { + _ struct{} `type:"structure"` + + // Description of the provisioning artifact output key. + Description *string `type:"string"` + + // The provisioning artifact output key. + Key *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ProvisioningArtifactOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ProvisioningArtifactOutput) GoString() string { + return s.String() +} + +// SetDescription sets the Description field's value. +func (s *ProvisioningArtifactOutput) SetDescription(v string) *ProvisioningArtifactOutput { + s.Description = &v + return s +} + +// SetKey sets the Key field's value. +func (s *ProvisioningArtifactOutput) SetKey(v string) *ProvisioningArtifactOutput { + s.Key = &v + return s +} + // Information about a parameter used to provision a product. type ProvisioningArtifactParameter struct { _ struct{} `type:"structure"` @@ -19841,15 +20044,22 @@ type UpdateProvisionedProductInput struct { // * zh - Chinese AcceptLanguage *string `type:"string"` - // The new path identifier. This value is optional if the product has a default - // path, and required if the product has more than one path. + // The path identifier. This value is optional if the product has a default + // path, and required if the product has more than one path. You must provide + // the name or ID, but not both. PathId *string `min:"1" type:"string"` - // The identifier of the product. + // The name of the path. You must provide the name or ID, but not both. + PathName *string `min:"1" type:"string"` + + // The identifier of the product. You must provide the name or ID, but not both. ProductId *string `min:"1" type:"string"` - // The identifier of the provisioned product. You cannot specify both ProvisionedProductName - // and ProvisionedProductId. + // The name of the product. You must provide the name or ID, but not both. + ProductName *string `type:"string"` + + // The identifier of the provisioned product. You must provide the name or ID, + // but not both. ProvisionedProductId *string `min:"1" type:"string"` // The name of the provisioned product. You cannot specify both ProvisionedProductName @@ -19859,6 +20069,10 @@ type UpdateProvisionedProductInput struct { // The identifier of the provisioning artifact. ProvisioningArtifactId *string `min:"1" type:"string"` + // The name of the provisioning artifact. You must provide the name or ID, but + // not both. + ProvisioningArtifactName *string `type:"string"` + // The new parameters. ProvisioningParameters []*UpdateProvisioningParameter `type:"list"` @@ -19890,6 +20104,9 @@ func (s *UpdateProvisionedProductInput) Validate() error { if s.PathId != nil && len(*s.PathId) < 1 { invalidParams.Add(request.NewErrParamMinLen("PathId", 1)) } + if s.PathName != nil && len(*s.PathName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PathName", 1)) + } if s.ProductId != nil && len(*s.ProductId) < 1 { invalidParams.Add(request.NewErrParamMinLen("ProductId", 1)) } @@ -19949,12 +20166,24 @@ func (s *UpdateProvisionedProductInput) SetPathId(v string) *UpdateProvisionedPr return s } +// SetPathName sets the PathName field's value. +func (s *UpdateProvisionedProductInput) SetPathName(v string) *UpdateProvisionedProductInput { + s.PathName = &v + return s +} + // SetProductId sets the ProductId field's value. func (s *UpdateProvisionedProductInput) SetProductId(v string) *UpdateProvisionedProductInput { s.ProductId = &v return s } +// SetProductName sets the ProductName field's value. +func (s *UpdateProvisionedProductInput) SetProductName(v string) *UpdateProvisionedProductInput { + s.ProductName = &v + return s +} + // SetProvisionedProductId sets the ProvisionedProductId field's value. func (s *UpdateProvisionedProductInput) SetProvisionedProductId(v string) *UpdateProvisionedProductInput { s.ProvisionedProductId = &v @@ -19973,6 +20202,12 @@ func (s *UpdateProvisionedProductInput) SetProvisioningArtifactId(v string) *Upd return s } +// SetProvisioningArtifactName sets the ProvisioningArtifactName field's value. +func (s *UpdateProvisionedProductInput) SetProvisioningArtifactName(v string) *UpdateProvisionedProductInput { + s.ProvisioningArtifactName = &v + return s +} + // SetProvisioningParameters sets the ProvisioningParameters field's value. func (s *UpdateProvisionedProductInput) SetProvisioningParameters(v []*UpdateProvisioningParameter) *UpdateProvisionedProductInput { s.ProvisioningParameters = v @@ -20043,9 +20278,9 @@ type UpdateProvisionedProductPropertiesInput struct { // A map that contains the provisioned product properties to be updated. // - // The OWNER key only accepts user ARNs. The owner is the user that is allowed - // to see, update, terminate, and execute service actions in the provisioned - // product. + // The OWNER key accepts user ARNs and role ARNs. The owner is the user that + // is allowed to see, update, terminate, and execute service actions in the + // provisioned product. // // The administrator can change the owner of a provisioned product to another // IAM user within the same account. Both end user owners and administrators @@ -20812,6 +21047,15 @@ const ( AccessLevelFilterKeyUser = "User" ) +// AccessLevelFilterKey_Values returns all elements of the AccessLevelFilterKey enum +func AccessLevelFilterKey_Values() []string { + return []string{ + AccessLevelFilterKeyAccount, + AccessLevelFilterKeyRole, + AccessLevelFilterKeyUser, + } +} + const ( // AccessStatusEnabled is a AccessStatus enum value AccessStatusEnabled = "ENABLED" @@ -20823,6 +21067,15 @@ const ( AccessStatusDisabled = "DISABLED" ) +// AccessStatus_Values returns all elements of the AccessStatus enum +func AccessStatus_Values() []string { + return []string{ + AccessStatusEnabled, + AccessStatusUnderChange, + AccessStatusDisabled, + } +} + const ( // ChangeActionAdd is a ChangeAction enum value ChangeActionAdd = "ADD" @@ -20834,11 +21087,27 @@ const ( ChangeActionRemove = "REMOVE" ) +// ChangeAction_Values returns all elements of the ChangeAction enum +func ChangeAction_Values() []string { + return []string{ + ChangeActionAdd, + ChangeActionModify, + ChangeActionRemove, + } +} + const ( // CopyOptionCopyTags is a CopyOption enum value CopyOptionCopyTags = "CopyTags" ) +// CopyOption_Values returns all elements of the CopyOption enum +func CopyOption_Values() []string { + return []string{ + CopyOptionCopyTags, + } +} + const ( // CopyProductStatusSucceeded is a CopyProductStatus enum value CopyProductStatusSucceeded = "SUCCEEDED" @@ -20850,6 +21119,15 @@ const ( CopyProductStatusFailed = "FAILED" ) +// CopyProductStatus_Values returns all elements of the CopyProductStatus enum +func CopyProductStatus_Values() []string { + return []string{ + CopyProductStatusSucceeded, + CopyProductStatusInProgress, + CopyProductStatusFailed, + } +} + const ( // EvaluationTypeStatic is a EvaluationType enum value EvaluationTypeStatic = "STATIC" @@ -20858,6 +21136,14 @@ const ( EvaluationTypeDynamic = "DYNAMIC" ) +// EvaluationType_Values returns all elements of the EvaluationType enum +func EvaluationType_Values() []string { + return []string{ + EvaluationTypeStatic, + EvaluationTypeDynamic, + } +} + const ( // OrganizationNodeTypeOrganization is a OrganizationNodeType enum value OrganizationNodeTypeOrganization = "ORGANIZATION" @@ -20869,6 +21155,15 @@ const ( OrganizationNodeTypeAccount = "ACCOUNT" ) +// OrganizationNodeType_Values returns all elements of the OrganizationNodeType enum +func OrganizationNodeType_Values() []string { + return []string{ + OrganizationNodeTypeOrganization, + OrganizationNodeTypeOrganizationalUnit, + OrganizationNodeTypeAccount, + } +} + const ( // PortfolioShareTypeImported is a PortfolioShareType enum value PortfolioShareTypeImported = "IMPORTED" @@ -20880,16 +21175,39 @@ const ( PortfolioShareTypeAwsOrganizations = "AWS_ORGANIZATIONS" ) +// PortfolioShareType_Values returns all elements of the PortfolioShareType enum +func PortfolioShareType_Values() []string { + return []string{ + PortfolioShareTypeImported, + PortfolioShareTypeAwsServicecatalog, + PortfolioShareTypeAwsOrganizations, + } +} + const ( // PrincipalTypeIam is a PrincipalType enum value PrincipalTypeIam = "IAM" ) +// PrincipalType_Values returns all elements of the PrincipalType enum +func PrincipalType_Values() []string { + return []string{ + PrincipalTypeIam, + } +} + const ( // ProductSourceAccount is a ProductSource enum value ProductSourceAccount = "ACCOUNT" ) +// ProductSource_Values returns all elements of the ProductSource enum +func ProductSource_Values() []string { + return []string{ + ProductSourceAccount, + } +} + const ( // ProductTypeCloudFormationTemplate is a ProductType enum value ProductTypeCloudFormationTemplate = "CLOUD_FORMATION_TEMPLATE" @@ -20898,6 +21216,14 @@ const ( ProductTypeMarketplace = "MARKETPLACE" ) +// ProductType_Values returns all elements of the ProductType enum +func ProductType_Values() []string { + return []string{ + ProductTypeCloudFormationTemplate, + ProductTypeMarketplace, + } +} + const ( // ProductViewFilterByFullTextSearch is a ProductViewFilterBy enum value ProductViewFilterByFullTextSearch = "FullTextSearch" @@ -20912,6 +21238,16 @@ const ( ProductViewFilterBySourceProductId = "SourceProductId" ) +// ProductViewFilterBy_Values returns all elements of the ProductViewFilterBy enum +func ProductViewFilterBy_Values() []string { + return []string{ + ProductViewFilterByFullTextSearch, + ProductViewFilterByOwner, + ProductViewFilterByProductType, + ProductViewFilterBySourceProductId, + } +} + const ( // ProductViewSortByTitle is a ProductViewSortBy enum value ProductViewSortByTitle = "Title" @@ -20923,11 +21259,27 @@ const ( ProductViewSortByCreationDate = "CreationDate" ) +// ProductViewSortBy_Values returns all elements of the ProductViewSortBy enum +func ProductViewSortBy_Values() []string { + return []string{ + ProductViewSortByTitle, + ProductViewSortByVersionCount, + ProductViewSortByCreationDate, + } +} + const ( // PropertyKeyOwner is a PropertyKey enum value PropertyKeyOwner = "OWNER" ) +// PropertyKey_Values returns all elements of the PropertyKey enum +func PropertyKey_Values() []string { + return []string{ + PropertyKeyOwner, + } +} + const ( // ProvisionedProductPlanStatusCreateInProgress is a ProvisionedProductPlanStatus enum value ProvisionedProductPlanStatusCreateInProgress = "CREATE_IN_PROGRESS" @@ -20948,11 +21300,30 @@ const ( ProvisionedProductPlanStatusExecuteFailed = "EXECUTE_FAILED" ) +// ProvisionedProductPlanStatus_Values returns all elements of the ProvisionedProductPlanStatus enum +func ProvisionedProductPlanStatus_Values() []string { + return []string{ + ProvisionedProductPlanStatusCreateInProgress, + ProvisionedProductPlanStatusCreateSuccess, + ProvisionedProductPlanStatusCreateFailed, + ProvisionedProductPlanStatusExecuteInProgress, + ProvisionedProductPlanStatusExecuteSuccess, + ProvisionedProductPlanStatusExecuteFailed, + } +} + const ( // ProvisionedProductPlanTypeCloudformation is a ProvisionedProductPlanType enum value ProvisionedProductPlanTypeCloudformation = "CLOUDFORMATION" ) +// ProvisionedProductPlanType_Values returns all elements of the ProvisionedProductPlanType enum +func ProvisionedProductPlanType_Values() []string { + return []string{ + ProvisionedProductPlanTypeCloudformation, + } +} + const ( // ProvisionedProductStatusAvailable is a ProvisionedProductStatus enum value ProvisionedProductStatusAvailable = "AVAILABLE" @@ -20970,11 +21341,29 @@ const ( ProvisionedProductStatusPlanInProgress = "PLAN_IN_PROGRESS" ) +// ProvisionedProductStatus_Values returns all elements of the ProvisionedProductStatus enum +func ProvisionedProductStatus_Values() []string { + return []string{ + ProvisionedProductStatusAvailable, + ProvisionedProductStatusUnderChange, + ProvisionedProductStatusTainted, + ProvisionedProductStatusError, + ProvisionedProductStatusPlanInProgress, + } +} + const ( // ProvisionedProductViewFilterBySearchQuery is a ProvisionedProductViewFilterBy enum value ProvisionedProductViewFilterBySearchQuery = "SearchQuery" ) +// ProvisionedProductViewFilterBy_Values returns all elements of the ProvisionedProductViewFilterBy enum +func ProvisionedProductViewFilterBy_Values() []string { + return []string{ + ProvisionedProductViewFilterBySearchQuery, + } +} + const ( // ProvisioningArtifactGuidanceDefault is a ProvisioningArtifactGuidance enum value ProvisioningArtifactGuidanceDefault = "DEFAULT" @@ -20983,11 +21372,26 @@ const ( ProvisioningArtifactGuidanceDeprecated = "DEPRECATED" ) +// ProvisioningArtifactGuidance_Values returns all elements of the ProvisioningArtifactGuidance enum +func ProvisioningArtifactGuidance_Values() []string { + return []string{ + ProvisioningArtifactGuidanceDefault, + ProvisioningArtifactGuidanceDeprecated, + } +} + const ( // ProvisioningArtifactPropertyNameId is a ProvisioningArtifactPropertyName enum value ProvisioningArtifactPropertyNameId = "Id" ) +// ProvisioningArtifactPropertyName_Values returns all elements of the ProvisioningArtifactPropertyName enum +func ProvisioningArtifactPropertyName_Values() []string { + return []string{ + ProvisioningArtifactPropertyNameId, + } +} + const ( // ProvisioningArtifactTypeCloudFormationTemplate is a ProvisioningArtifactType enum value ProvisioningArtifactTypeCloudFormationTemplate = "CLOUD_FORMATION_TEMPLATE" @@ -20999,6 +21403,15 @@ const ( ProvisioningArtifactTypeMarketplaceCar = "MARKETPLACE_CAR" ) +// ProvisioningArtifactType_Values returns all elements of the ProvisioningArtifactType enum +func ProvisioningArtifactType_Values() []string { + return []string{ + ProvisioningArtifactTypeCloudFormationTemplate, + ProvisioningArtifactTypeMarketplaceAmi, + ProvisioningArtifactTypeMarketplaceCar, + } +} + const ( // RecordStatusCreated is a RecordStatus enum value RecordStatusCreated = "CREATED" @@ -21016,6 +21429,17 @@ const ( RecordStatusFailed = "FAILED" ) +// RecordStatus_Values returns all elements of the RecordStatus enum +func RecordStatus_Values() []string { + return []string{ + RecordStatusCreated, + RecordStatusInProgress, + RecordStatusInProgressInError, + RecordStatusSucceeded, + RecordStatusFailed, + } +} + const ( // ReplacementTrue is a Replacement enum value ReplacementTrue = "TRUE" @@ -21027,6 +21451,15 @@ const ( ReplacementConditional = "CONDITIONAL" ) +// Replacement_Values returns all elements of the Replacement enum +func Replacement_Values() []string { + return []string{ + ReplacementTrue, + ReplacementFalse, + ReplacementConditional, + } +} + const ( // RequiresRecreationNever is a RequiresRecreation enum value RequiresRecreationNever = "NEVER" @@ -21038,6 +21471,15 @@ const ( RequiresRecreationAlways = "ALWAYS" ) +// RequiresRecreation_Values returns all elements of the RequiresRecreation enum +func RequiresRecreation_Values() []string { + return []string{ + RequiresRecreationNever, + RequiresRecreationConditionally, + RequiresRecreationAlways, + } +} + const ( // ResourceAttributeProperties is a ResourceAttribute enum value ResourceAttributeProperties = "PROPERTIES" @@ -21058,6 +21500,18 @@ const ( ResourceAttributeTags = "TAGS" ) +// ResourceAttribute_Values returns all elements of the ResourceAttribute enum +func ResourceAttribute_Values() []string { + return []string{ + ResourceAttributeProperties, + ResourceAttributeMetadata, + ResourceAttributeCreationpolicy, + ResourceAttributeUpdatepolicy, + ResourceAttributeDeletionpolicy, + ResourceAttributeTags, + } +} + const ( // ServiceActionAssociationErrorCodeDuplicateResource is a ServiceActionAssociationErrorCode enum value ServiceActionAssociationErrorCodeDuplicateResource = "DUPLICATE_RESOURCE" @@ -21075,6 +21529,17 @@ const ( ServiceActionAssociationErrorCodeThrottling = "THROTTLING" ) +// ServiceActionAssociationErrorCode_Values returns all elements of the ServiceActionAssociationErrorCode enum +func ServiceActionAssociationErrorCode_Values() []string { + return []string{ + ServiceActionAssociationErrorCodeDuplicateResource, + ServiceActionAssociationErrorCodeInternalFailure, + ServiceActionAssociationErrorCodeLimitExceeded, + ServiceActionAssociationErrorCodeResourceNotFound, + ServiceActionAssociationErrorCodeThrottling, + } +} + const ( // ServiceActionDefinitionKeyName is a ServiceActionDefinitionKey enum value ServiceActionDefinitionKeyName = "Name" @@ -21089,11 +21554,28 @@ const ( ServiceActionDefinitionKeyParameters = "Parameters" ) +// ServiceActionDefinitionKey_Values returns all elements of the ServiceActionDefinitionKey enum +func ServiceActionDefinitionKey_Values() []string { + return []string{ + ServiceActionDefinitionKeyName, + ServiceActionDefinitionKeyVersion, + ServiceActionDefinitionKeyAssumeRole, + ServiceActionDefinitionKeyParameters, + } +} + const ( // ServiceActionDefinitionTypeSsmAutomation is a ServiceActionDefinitionType enum value ServiceActionDefinitionTypeSsmAutomation = "SSM_AUTOMATION" ) +// ServiceActionDefinitionType_Values returns all elements of the ServiceActionDefinitionType enum +func ServiceActionDefinitionType_Values() []string { + return []string{ + ServiceActionDefinitionTypeSsmAutomation, + } +} + const ( // ShareStatusNotStarted is a ShareStatus enum value ShareStatusNotStarted = "NOT_STARTED" @@ -21111,6 +21593,17 @@ const ( ShareStatusError = "ERROR" ) +// ShareStatus_Values returns all elements of the ShareStatus enum +func ShareStatus_Values() []string { + return []string{ + ShareStatusNotStarted, + ShareStatusInProgress, + ShareStatusCompleted, + ShareStatusCompletedWithErrors, + ShareStatusError, + } +} + const ( // SortOrderAscending is a SortOrder enum value SortOrderAscending = "ASCENDING" @@ -21119,6 +21612,14 @@ const ( SortOrderDescending = "DESCENDING" ) +// SortOrder_Values returns all elements of the SortOrder enum +func SortOrder_Values() []string { + return []string{ + SortOrderAscending, + SortOrderDescending, + } +} + const ( // StackInstanceStatusCurrent is a StackInstanceStatus enum value StackInstanceStatusCurrent = "CURRENT" @@ -21130,6 +21631,15 @@ const ( StackInstanceStatusInoperable = "INOPERABLE" ) +// StackInstanceStatus_Values returns all elements of the StackInstanceStatus enum +func StackInstanceStatus_Values() []string { + return []string{ + StackInstanceStatusCurrent, + StackInstanceStatusOutdated, + StackInstanceStatusInoperable, + } +} + const ( // StackSetOperationTypeCreate is a StackSetOperationType enum value StackSetOperationTypeCreate = "CREATE" @@ -21141,6 +21651,15 @@ const ( StackSetOperationTypeDelete = "DELETE" ) +// StackSetOperationType_Values returns all elements of the StackSetOperationType enum +func StackSetOperationType_Values() []string { + return []string{ + StackSetOperationTypeCreate, + StackSetOperationTypeUpdate, + StackSetOperationTypeDelete, + } +} + const ( // StatusAvailable is a Status enum value StatusAvailable = "AVAILABLE" @@ -21151,3 +21670,12 @@ const ( // StatusFailed is a Status enum value StatusFailed = "FAILED" ) + +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusAvailable, + StatusCreating, + StatusFailed, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/servicediscovery/api.go b/vendor/github.com/aws/aws-sdk-go/service/servicediscovery/api.go index b6b6d9f17c8..68aaa0b331b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/servicediscovery/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/servicediscovery/api.go @@ -61,8 +61,8 @@ func (c *ServiceDiscovery) CreateHttpNamespaceRequest(input *CreateHttpNamespace // namespace can be discovered using a DiscoverInstances request but can't be // discovered using DNS. // -// For the current limit on the number of namespaces that you can create using -// the same AWS account, see AWS Cloud Map Limits (https://docs.aws.amazon.com/cloud-map/latest/dg/cloud-map-limits.html) +// For the current quota on the number of namespaces that you can create using +// the same AWS account, see AWS Cloud Map quotas (https://docs.aws.amazon.com/cloud-map/latest/dg/cloud-map-limits.html) // in the AWS Cloud Map Developer Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -82,12 +82,16 @@ func (c *ServiceDiscovery) CreateHttpNamespaceRequest(input *CreateHttpNamespace // The namespace that you're trying to create already exists. // // * ResourceLimitExceeded -// The resource can't be created because you've reached the limit on the number +// The resource can't be created because you've reached the quota on the number // of resources. // // * DuplicateRequest // The operation is already in progress. // +// * TooManyTagsException +// The list of tags on the resource is over the quota. The maximum number of +// tags that can be applied to a resource is 50. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreateHttpNamespace func (c *ServiceDiscovery) CreateHttpNamespace(input *CreateHttpNamespaceInput) (*CreateHttpNamespaceOutput, error) { req, out := c.CreateHttpNamespaceRequest(input) @@ -158,7 +162,7 @@ func (c *ServiceDiscovery) CreatePrivateDnsNamespaceRequest(input *CreatePrivate // a specified Amazon VPC. The namespace defines your service naming scheme. // For example, if you name your namespace example.com and name your service // backend, the resulting DNS name for the service will be backend.example.com. -// For the current limit on the number of namespaces that you can create using +// For the current quota on the number of namespaces that you can create using // the same AWS account, see AWS Cloud Map Limits (https://docs.aws.amazon.com/cloud-map/latest/dg/cloud-map-limits.html) // in the AWS Cloud Map Developer Guide. // @@ -179,12 +183,16 @@ func (c *ServiceDiscovery) CreatePrivateDnsNamespaceRequest(input *CreatePrivate // The namespace that you're trying to create already exists. // // * ResourceLimitExceeded -// The resource can't be created because you've reached the limit on the number +// The resource can't be created because you've reached the quota on the number // of resources. // // * DuplicateRequest // The operation is already in progress. // +// * TooManyTagsException +// The list of tags on the resource is over the quota. The maximum number of +// tags that can be applied to a resource is 50. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePrivateDnsNamespace func (c *ServiceDiscovery) CreatePrivateDnsNamespace(input *CreatePrivateDnsNamespaceInput) (*CreatePrivateDnsNamespaceOutput, error) { req, out := c.CreatePrivateDnsNamespaceRequest(input) @@ -254,7 +262,7 @@ func (c *ServiceDiscovery) CreatePublicDnsNamespaceRequest(input *CreatePublicDn // Creates a public namespace based on DNS, which will be visible on the internet. // The namespace defines your service naming scheme. For example, if you name // your namespace example.com and name your service backend, the resulting DNS -// name for the service will be backend.example.com. For the current limit on +// name for the service will be backend.example.com. For the current quota on // the number of namespaces that you can create using the same AWS account, // see AWS Cloud Map Limits (https://docs.aws.amazon.com/cloud-map/latest/dg/cloud-map-limits.html) // in the AWS Cloud Map Developer Guide. @@ -276,12 +284,16 @@ func (c *ServiceDiscovery) CreatePublicDnsNamespaceRequest(input *CreatePublicDn // The namespace that you're trying to create already exists. // // * ResourceLimitExceeded -// The resource can't be created because you've reached the limit on the number +// The resource can't be created because you've reached the quota on the number // of resources. // // * DuplicateRequest // The operation is already in progress. // +// * TooManyTagsException +// The list of tags on the resource is over the quota. The maximum number of +// tags that can be applied to a resource is 50. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreatePublicDnsNamespace func (c *ServiceDiscovery) CreatePublicDnsNamespace(input *CreatePublicDnsNamespaceInput) (*CreatePublicDnsNamespaceOutput, error) { req, out := c.CreatePublicDnsNamespaceRequest(input) @@ -359,7 +371,7 @@ func (c *ServiceDiscovery) CreateServiceRequest(input *CreateServiceInput) (req // request, and AWS Cloud Map uses the values in the configuration to create // the specified entities. // -// For the current limit on the number of instances that you can register using +// For the current quota on the number of instances that you can register using // the same namespace and using the same service, see AWS Cloud Map Limits (https://docs.aws.amazon.com/cloud-map/latest/dg/cloud-map-limits.html) // in the AWS Cloud Map Developer Guide. // @@ -377,7 +389,7 @@ func (c *ServiceDiscovery) CreateServiceRequest(input *CreateServiceInput) (req // a string value might exceed length constraints. // // * ResourceLimitExceeded -// The resource can't be created because you've reached the limit on the number +// The resource can't be created because you've reached the quota on the number // of resources. // // * NamespaceNotFound @@ -387,6 +399,10 @@ func (c *ServiceDiscovery) CreateServiceRequest(input *CreateServiceInput) (req // The service can't be created because a service with the same name already // exists. // +// * TooManyTagsException +// The list of tags on the resource is over the quota. The maximum number of +// tags that can be applied to a resource is 50. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/CreateService func (c *ServiceDiscovery) CreateService(input *CreateServiceInput) (*CreateServiceOutput, error) { req, out := c.CreateServiceRequest(input) @@ -757,6 +773,12 @@ func (c *ServiceDiscovery) DiscoverInstancesRequest(input *DiscoverInstancesInpu // might be missing, a numeric value might be outside the allowed range, or // a string value might exceed length constraints. // +// * RequestLimitExceeded +// The operation can't be completed because you've reached the quota for the +// number of requests. For more information, see AWS Cloud Map API request throttling +// quota (https://docs.aws.amazon.com/cloud-map/latest/dg/throttling.html) in +// the AWS Cloud Map Developer Guide. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/DiscoverInstances func (c *ServiceDiscovery) DiscoverInstances(input *DiscoverInstancesInput) (*DiscoverInstancesOutput, error) { req, out := c.DiscoverInstancesRequest(input) @@ -1835,6 +1857,90 @@ func (c *ServiceDiscovery) ListServicesPagesWithContext(ctx aws.Context, input * return p.Err() } +const opListTagsForResource = "ListTagsForResource" + +// ListTagsForResourceRequest generates a "aws/request.Request" representing the +// client's request for the ListTagsForResource operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListTagsForResource for more information on using the ListTagsForResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListTagsForResourceRequest method. +// req, resp := client.ListTagsForResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListTagsForResource +func (c *ServiceDiscovery) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { + op := &request.Operation{ + Name: opListTagsForResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListTagsForResourceInput{} + } + + output = &ListTagsForResourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListTagsForResource API operation for AWS Cloud Map. +// +// Lists tags 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 Cloud Map's +// API operation ListTagsForResource for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The operation can't be completed because the resource was not found. +// +// * InvalidInput +// One or more specified values aren't valid. For example, a required value +// might be missing, a numeric value might be outside the allowed range, or +// a string value might exceed length constraints. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/ListTagsForResource +func (c *ServiceDiscovery) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + 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 *ServiceDiscovery) 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 opRegisterInstance = "RegisterInstance" // RegisterInstanceRequest generates a "aws/request.Request" representing the @@ -1909,7 +2015,7 @@ func (c *ServiceDiscovery) RegisterInstanceRequest(input *RegisterInstanceInput) // * If you didn't specify a health check configuration: returns all the // records // -// For the current limit on the number of instances that you can register using +// For the current quota on the number of instances that you can register using // the same namespace and using the same service, see AWS Cloud Map Limits (https://docs.aws.amazon.com/cloud-map/latest/dg/cloud-map-limits.html) // in the AWS Cloud Map Developer Guide. // @@ -1934,7 +2040,7 @@ func (c *ServiceDiscovery) RegisterInstanceRequest(input *RegisterInstanceInput) // For example, you can't delete a service that contains any instances. // // * ResourceLimitExceeded -// The resource can't be created because you've reached the limit on the number +// The resource can't be created because you've reached the quota on the number // of resources. // // * ServiceNotFound @@ -1962,6 +2068,180 @@ func (c *ServiceDiscovery) RegisterInstanceWithContext(ctx aws.Context, input *R 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 will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See TagResource for more information on using the TagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the TagResourceRequest method. +// req, resp := client.TagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/TagResource +func (c *ServiceDiscovery) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { + op := &request.Operation{ + Name: opTagResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &TagResourceInput{} + } + + output = &TagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// TagResource API operation for AWS Cloud Map. +// +// Adds one or more tags to 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 Cloud Map's +// API operation TagResource for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The operation can't be completed because the resource was not found. +// +// * TooManyTagsException +// The list of tags on the resource is over the quota. The maximum number of +// tags that can be applied to a resource is 50. +// +// * InvalidInput +// One or more specified values aren't valid. For example, a required value +// might be missing, a numeric value might be outside the allowed range, or +// a string value might exceed length constraints. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/TagResource +func (c *ServiceDiscovery) 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 *ServiceDiscovery) 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 will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UntagResource for more information on using the UntagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UntagResourceRequest method. +// req, resp := client.UntagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/UntagResource +func (c *ServiceDiscovery) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { + op := &request.Operation{ + Name: opUntagResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UntagResourceInput{} + } + + output = &UntagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UntagResource API operation for AWS Cloud Map. +// +// Removes one or more tags 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 Cloud Map's +// API operation UntagResource for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The operation can't be completed because the resource was not found. +// +// * InvalidInput +// One or more specified values aren't valid. For example, a required value +// might be missing, a numeric value might be outside the allowed range, or +// a string value might exceed length constraints. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/servicediscovery-2017-03-14/UntagResource +func (c *ServiceDiscovery) 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 *ServiceDiscovery) 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 opUpdateInstanceCustomHealthStatus = "UpdateInstanceCustomHealthStatus" // UpdateInstanceCustomHealthStatusRequest generates a "aws/request.Request" representing the @@ -2183,6 +2463,11 @@ type CreateHttpNamespaceInput struct { // // Name is a required field Name *string `type:"string" required:"true"` + + // The tags to add to the namespace. Each tag consists of a key and an optional + // value, both of which you define. Tag keys can have a maximum character length + // of 128 characters, and tag values can have a maximum length of 256 characters. + Tags []*Tag `type:"list"` } // String returns the string representation @@ -2201,6 +2486,16 @@ func (s *CreateHttpNamespaceInput) Validate() error { if s.Name == nil { invalidParams.Add(request.NewErrParamRequired("Name")) } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -2226,6 +2521,12 @@ func (s *CreateHttpNamespaceInput) SetName(v string) *CreateHttpNamespaceInput { return s } +// SetTags sets the Tags field's value. +func (s *CreateHttpNamespaceInput) SetTags(v []*Tag) *CreateHttpNamespaceInput { + s.Tags = v + return s +} + type CreateHttpNamespaceOutput struct { _ struct{} `type:"structure"` @@ -2268,6 +2569,11 @@ type CreatePrivateDnsNamespaceInput struct { // Name is a required field Name *string `type:"string" required:"true"` + // The tags to add to the namespace. Each tag consists of a key and an optional + // value, both of which you define. Tag keys can have a maximum character length + // of 128 characters, and tag values can have a maximum length of 256 characters. + Tags []*Tag `type:"list"` + // The ID of the Amazon VPC that you want to associate the namespace with. // // Vpc is a required field @@ -2293,6 +2599,16 @@ func (s *CreatePrivateDnsNamespaceInput) Validate() error { if s.Vpc == nil { invalidParams.Add(request.NewErrParamRequired("Vpc")) } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -2318,6 +2634,12 @@ func (s *CreatePrivateDnsNamespaceInput) SetName(v string) *CreatePrivateDnsName return s } +// SetTags sets the Tags field's value. +func (s *CreatePrivateDnsNamespaceInput) SetTags(v []*Tag) *CreatePrivateDnsNamespaceInput { + s.Tags = v + return s +} + // SetVpc sets the Vpc field's value. func (s *CreatePrivateDnsNamespaceInput) SetVpc(v string) *CreatePrivateDnsNamespaceInput { s.Vpc = &v @@ -2363,6 +2685,11 @@ type CreatePublicDnsNamespaceInput struct { // // Name is a required field Name *string `type:"string" required:"true"` + + // The tags to add to the namespace. Each tag consists of a key and an optional + // value, both of which you define. Tag keys can have a maximum character length + // of 128 characters, and tag values can have a maximum length of 256 characters. + Tags []*Tag `type:"list"` } // String returns the string representation @@ -2381,6 +2708,16 @@ func (s *CreatePublicDnsNamespaceInput) Validate() error { if s.Name == nil { invalidParams.Add(request.NewErrParamRequired("Name")) } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -2406,6 +2743,12 @@ func (s *CreatePublicDnsNamespaceInput) SetName(v string) *CreatePublicDnsNamesp return s } +// SetTags sets the Tags field's value. +func (s *CreatePublicDnsNamespaceInput) SetTags(v []*Tag) *CreatePublicDnsNamespaceInput { + s.Tags = v + return s +} + type CreatePublicDnsNamespaceOutput struct { _ struct{} `type:"structure"` @@ -2488,6 +2831,11 @@ type CreateServiceInput struct { // The ID of the namespace that you want to use to create the service. NamespaceId *string `type:"string"` + + // The tags to add to the service. Each tag consists of a key and an optional + // value, both of which you define. Tag keys can have a maximum character length + // of 128 characters, and tag values can have a maximum length of 256 characters. + Tags []*Tag `type:"list"` } // String returns the string representation @@ -2521,6 +2869,16 @@ func (s *CreateServiceInput) Validate() error { invalidParams.AddNested("HealthCheckCustomConfig", err.(request.ErrInvalidParams)) } } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -2570,6 +2928,12 @@ func (s *CreateServiceInput) SetNamespaceId(v string) *CreateServiceInput { return s } +// SetTags sets the Tags field's value. +func (s *CreateServiceInput) SetTags(v []*Tag) *CreateServiceInput { + s.Tags = v + return s +} + type CreateServiceOutput struct { _ struct{} `type:"structure"` @@ -3735,14 +4099,14 @@ func (s *GetServiceOutput) SetService(v *Service) *GetServiceOutput { // // Note the following about configuring health checks. // -// A and AAAA records +// A and AAAA records // // If DnsConfig includes configurations for both A and AAAA records, AWS Cloud // Map creates a health check that uses the IPv4 address to check the health // of the resource. If the endpoint that is specified by the IPv4 address is // unhealthy, Route 53 considers both the A and AAAA records to be unhealthy. // -// CNAME records +// CNAME records // // You can't specify settings for HealthCheckConfig when the DNSConfig includes // CNAME for the value of Type. If you do, the CreateService request will fail @@ -4092,6 +4456,11 @@ type Instance struct { // * If you specify a value for AWS_ALIAS_DNS_NAME, don't specify values // for any of the AWS_INSTANCE attributes. // + // AWS_EC2_INSTANCE_ID + // + // HTTP namespaces only. The Amazon EC2 instance ID for the instance. The AWS_INSTANCE_IPV4 + // attribute contains the primary private IPv4 address. + // // AWS_INSTANCE_CNAME // // If the service configuration includes a CNAME record, the domain name that @@ -4262,6 +4631,11 @@ type InstanceSummary struct { // Load Balancing load balancer, the DNS name that is associated with the // load balancer. // + // * AWS_EC2_INSTANCE_ID: (HTTP namespaces only) The Amazon EC2 instance + // ID for the instance. When the AWS_EC2_INSTANCE_ID attribute is specified, + // then the AWS_INSTANCE_IPV4 attribute contains the primary private IPv4 + // address. + // // * AWS_INSTANCE_CNAME: For a CNAME record, the domain name that Route 53 // returns in response to DNS queries, for example, example.com. // @@ -4817,22 +5191,87 @@ func (s *ListServicesOutput) SetServices(v []*ServiceSummary) *ListServicesOutpu return s } -// A complex type that contains information about a specified namespace. -type Namespace struct { +type ListTagsForResourceInput struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) that AWS Cloud Map assigns to the namespace - // when you create it. - Arn *string `type:"string"` + // The Amazon Resource Name (ARN) of the resource that you want to retrieve + // tags for. + // + // ResourceARN is a required field + ResourceARN *string `min:"1" type:"string" required:"true"` +} - // The date that the namespace was created, in Unix date/time format and Coordinated - // Universal Time (UTC). The value of CreateDate is accurate to milliseconds. - // For example, the value 1516925490.087 represents Friday, January 26, 2018 - // 12:11:30.087 AM. - CreateDate *time.Time `type:"timestamp"` +// String returns the string representation +func (s ListTagsForResourceInput) String() string { + return awsutil.Prettify(s) +} - // A unique string that identifies the request and that allows failed requests - // to be retried without the risk of executing an operation twice. +// GoString returns the string representation +func (s ListTagsForResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTagsForResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} + 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 *ListTagsForResourceInput) SetResourceARN(v string) *ListTagsForResourceInput { + s.ResourceARN = &v + return s +} + +type ListTagsForResourceOutput struct { + _ struct{} `type:"structure"` + + // The tags that are assigned to the resource. + Tags []*Tag `type:"list"` +} + +// String returns the string representation +func (s ListTagsForResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsForResourceOutput) GoString() string { + return s.String() +} + +// SetTags sets the Tags field's value. +func (s *ListTagsForResourceOutput) SetTags(v []*Tag) *ListTagsForResourceOutput { + s.Tags = v + return s +} + +// A complex type that contains information about a specified namespace. +type Namespace struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) that AWS Cloud Map assigns to the namespace + // when you create it. + Arn *string `type:"string"` + + // The date that the namespace was created, in Unix date/time format and Coordinated + // Universal Time (UTC). The value of CreateDate is accurate to milliseconds. + // For example, the value 1516925490.087 represents Friday, January 26, 2018 + // 12:11:30.087 AM. + CreateDate *time.Time `type:"timestamp"` + + // A unique string that identifies the request and that allows failed requests + // to be retried without the risk of executing an operation twice. CreatorRequestId *string `type:"string"` // The description that you specify for the namespace when you create it. @@ -5604,11 +6043,19 @@ type RegisterInstanceInput struct { // won't associate the health check with the alias record. // // * Auto naming currently doesn't support creating alias records that route - // traffic to AWS resources other than ELB load balancers. + // traffic to AWS resources other than Elastic Load Balancing load balancers. // // * If you specify a value for AWS_ALIAS_DNS_NAME, don't specify values // for any of the AWS_INSTANCE attributes. // + // AWS_EC2_INSTANCE_ID + // + // HTTP namespaces only. The Amazon EC2 instance ID for the instance. If the + // AWS_EC2_INSTANCE_ID attribute is specified, then the only other attribute + // that can be specified is AWS_INIT_HEALTH_STATUS. When the AWS_EC2_INSTANCE_ID + // attribute is specified, then the AWS_INSTANCE_IPV4 attribute will be filled + // out with the primary private IPv4 address. + // // AWS_INIT_HEALTH_STATUS // // If the service configuration includes HealthCheckCustomConfig, you can optionally @@ -5657,7 +6104,8 @@ type RegisterInstanceInput struct { // // You can add up to 30 custom attributes. For each key-value pair, the maximum // length of the attribute name is 255 characters, and the maximum length of - // the attribute value is 1,024 characters. + // the attribute value is 1,024 characters. The total size of all provided attributes + // (sum of all keys and values) must not exceed 5,000 characters. // // Attributes is a required field Attributes map[string]*string `type:"map" required:"true"` @@ -5774,6 +6222,65 @@ func (s *RegisterInstanceOutput) SetOperationId(v string) *RegisterInstanceOutpu return s } +// The operation can't be completed because you've reached the quota for the +// number of requests. For more information, see AWS Cloud Map API request throttling +// quota (https://docs.aws.amazon.com/cloud-map/latest/dg/throttling.html) in +// the AWS Cloud Map Developer Guide. +type RequestLimitExceeded struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s RequestLimitExceeded) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RequestLimitExceeded) GoString() string { + return s.String() +} + +func newErrorRequestLimitExceeded(v protocol.ResponseMetadata) error { + return &RequestLimitExceeded{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *RequestLimitExceeded) Code() string { + return "RequestLimitExceeded" +} + +// Message returns the exception's message. +func (s *RequestLimitExceeded) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *RequestLimitExceeded) OrigErr() error { + return nil +} + +func (s *RequestLimitExceeded) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *RequestLimitExceeded) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *RequestLimitExceeded) RequestID() string { + return s.RespMetadata.RequestID +} + // The specified resource can't be deleted because it contains other resources. // For example, you can't delete a service that contains any instances. type ResourceInUse struct { @@ -5831,7 +6338,7 @@ func (s *ResourceInUse) RequestID() string { return s.RespMetadata.RequestID } -// The resource can't be created because you've reached the limit on the number +// The resource can't be created because you've reached the quota on the number // of resources. type ResourceLimitExceeded struct { _ struct{} `type:"structure"` @@ -5888,6 +6395,62 @@ func (s *ResourceLimitExceeded) RequestID() string { return s.RespMetadata.RequestID } +// The operation can't be completed because the resource was not found. +type ResourceNotFoundException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s ResourceNotFoundException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResourceNotFoundException) GoString() string { + return s.String() +} + +func newErrorResourceNotFoundException(v protocol.ResponseMetadata) error { + return &ResourceNotFoundException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ResourceNotFoundException) Code() string { + return "ResourceNotFoundException" +} + +// Message returns the exception's message. +func (s *ResourceNotFoundException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ResourceNotFoundException) OrigErr() error { + return nil +} + +func (s *ResourceNotFoundException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ResourceNotFoundException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ResourceNotFoundException) RequestID() string { + return s.RespMetadata.RequestID +} + // A complex type that contains information about the specified service. type Service struct { _ struct{} `type:"structure"` @@ -6094,9 +6657,7 @@ type ServiceChange struct { // A complex type that contains information about the Route 53 DNS records that // you want AWS Cloud Map to create when you register an instance. - // - // DnsConfig is a required field - DnsConfig *DnsConfigChange `type:"structure" required:"true"` + DnsConfig *DnsConfigChange `type:"structure"` // Public DNS and HTTP namespaces only. A complex type that contains settings // for an optional health check. If you specify settings for a health check, @@ -6112,14 +6673,14 @@ type ServiceChange struct { // // Note the following about configuring health checks. // - // A and AAAA records + // A and AAAA records // // If DnsConfig includes configurations for both A and AAAA records, AWS Cloud // Map creates a health check that uses the IPv4 address to check the health // of the resource. If the endpoint that is specified by the IPv4 address is // unhealthy, Route 53 considers both the A and AAAA records to be unhealthy. // - // CNAME records + // CNAME records // // You can't specify settings for HealthCheckConfig when the DNSConfig includes // CNAME for the value of Type. If you do, the CreateService request will fail @@ -6173,9 +6734,6 @@ func (s ServiceChange) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *ServiceChange) Validate() error { invalidParams := request.ErrInvalidParams{Context: "ServiceChange"} - if s.DnsConfig == nil { - invalidParams.Add(request.NewErrParamRequired("DnsConfig")) - } if s.DnsConfig != nil { if err := s.DnsConfig.Validate(); err != nil { invalidParams.AddNested("DnsConfig", err.(request.ErrInvalidParams)) @@ -6372,14 +6930,14 @@ type ServiceSummary struct { // // Note the following about configuring health checks. // - // A and AAAA records + // A and AAAA records // // If DnsConfig includes configurations for both A and AAAA records, AWS Cloud // Map creates a health check that uses the IPv4 address to check the health // of the resource. If the endpoint that is specified by the IPv4 address is // unhealthy, Route 53 considers both the A and AAAA records to be unhealthy. // - // CNAME records + // CNAME records // // You can't specify settings for HealthCheckConfig when the DNSConfig includes // CNAME for the value of Type. If you do, the CreateService request will fail @@ -6547,6 +7105,275 @@ func (s *ServiceSummary) SetName(v string) *ServiceSummary { return s } +// A custom key-value pair associated with a resource. +type Tag struct { + _ struct{} `type:"structure"` + + // The key identifier, or name, of the tag. + // + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` + + // The string value associated with the key of the tag. You can set the value + // of a tag to an empty string, but you can't set the value of a tag to null. + // + // Value is a required field + Value *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s Tag) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Tag) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Tag) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Tag"} + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) + } + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) + } + if s.Value == nil { + invalidParams.Add(request.NewErrParamRequired("Value")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKey sets the Key field's value. +func (s *Tag) SetKey(v string) *Tag { + s.Key = &v + return s +} + +// SetValue sets the Value field's value. +func (s *Tag) SetValue(v string) *Tag { + s.Value = &v + return s +} + +type TagResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource that you want to retrieve + // tags for. + // + // ResourceARN is a required field + ResourceARN *string `min:"1" type:"string" required:"true"` + + // The tags to add to the specified resource. Specifying the tag key is required. + // You can set the value of a tag to an empty string, but you can't set the + // value of a tag to null. + // + // Tags is a required field + Tags []*Tag `type:"list" required:"true"` +} + +// String returns the string representation +func (s TagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"} + if s.ResourceARN == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceARN")) + } + if s.ResourceARN != nil && len(*s.ResourceARN) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceARN", 1)) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceARN sets the ResourceARN field's value. +func (s *TagResourceInput) SetResourceARN(v string) *TagResourceInput { + s.ResourceARN = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *TagResourceInput) SetTags(v []*Tag) *TagResourceInput { + s.Tags = v + return s +} + +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 list of tags on the resource is over the quota. The maximum number of +// tags that can be applied to a resource is 50. +type TooManyTagsException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` + + // The name of the resource. + ResourceName *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s TooManyTagsException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TooManyTagsException) GoString() string { + return s.String() +} + +func newErrorTooManyTagsException(v protocol.ResponseMetadata) error { + return &TooManyTagsException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *TooManyTagsException) Code() string { + return "TooManyTagsException" +} + +// Message returns the exception's message. +func (s *TooManyTagsException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *TooManyTagsException) OrigErr() error { + return nil +} + +func (s *TooManyTagsException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *TooManyTagsException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *TooManyTagsException) RequestID() string { + return s.RespMetadata.RequestID +} + +type UntagResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the resource that you want to retrieve + // tags for. + // + // ResourceARN is a required field + ResourceARN *string `min:"1" type:"string" required:"true"` + + // The tag keys to remove from the specified resource. + // + // TagKeys is a required field + TagKeys []*string `type:"list" required:"true"` +} + +// String returns the string representation +func (s UntagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UntagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"} + if s.ResourceARN == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceARN")) + } + if s.ResourceARN != nil && len(*s.ResourceARN) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceARN", 1)) + } + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceARN sets the ResourceARN field's value. +func (s *UntagResourceInput) SetResourceARN(v string) *UntagResourceInput { + s.ResourceARN = &v + return s +} + +// SetTagKeys sets the TagKeys field's value. +func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { + s.TagKeys = v + return s +} + +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 UpdateInstanceCustomHealthStatusInput struct { _ struct{} `type:"structure"` @@ -6717,6 +7544,14 @@ const ( CustomHealthStatusUnhealthy = "UNHEALTHY" ) +// CustomHealthStatus_Values returns all elements of the CustomHealthStatus enum +func CustomHealthStatus_Values() []string { + return []string{ + CustomHealthStatusHealthy, + CustomHealthStatusUnhealthy, + } +} + const ( // FilterConditionEq is a FilterCondition enum value FilterConditionEq = "EQ" @@ -6728,6 +7563,15 @@ const ( FilterConditionBetween = "BETWEEN" ) +// FilterCondition_Values returns all elements of the FilterCondition enum +func FilterCondition_Values() []string { + return []string{ + FilterConditionEq, + FilterConditionIn, + FilterConditionBetween, + } +} + const ( // HealthCheckTypeHttp is a HealthCheckType enum value HealthCheckTypeHttp = "HTTP" @@ -6739,6 +7583,15 @@ const ( HealthCheckTypeTcp = "TCP" ) +// HealthCheckType_Values returns all elements of the HealthCheckType enum +func HealthCheckType_Values() []string { + return []string{ + HealthCheckTypeHttp, + HealthCheckTypeHttps, + HealthCheckTypeTcp, + } +} + const ( // HealthStatusHealthy is a HealthStatus enum value HealthStatusHealthy = "HEALTHY" @@ -6750,6 +7603,15 @@ const ( HealthStatusUnknown = "UNKNOWN" ) +// HealthStatus_Values returns all elements of the HealthStatus enum +func HealthStatus_Values() []string { + return []string{ + HealthStatusHealthy, + HealthStatusUnhealthy, + HealthStatusUnknown, + } +} + const ( // HealthStatusFilterHealthy is a HealthStatusFilter enum value HealthStatusFilterHealthy = "HEALTHY" @@ -6761,11 +7623,27 @@ const ( HealthStatusFilterAll = "ALL" ) +// HealthStatusFilter_Values returns all elements of the HealthStatusFilter enum +func HealthStatusFilter_Values() []string { + return []string{ + HealthStatusFilterHealthy, + HealthStatusFilterUnhealthy, + HealthStatusFilterAll, + } +} + const ( // NamespaceFilterNameType is a NamespaceFilterName enum value NamespaceFilterNameType = "TYPE" ) +// NamespaceFilterName_Values returns all elements of the NamespaceFilterName enum +func NamespaceFilterName_Values() []string { + return []string{ + NamespaceFilterNameType, + } +} + const ( // NamespaceTypeDnsPublic is a NamespaceType enum value NamespaceTypeDnsPublic = "DNS_PUBLIC" @@ -6777,6 +7655,15 @@ const ( NamespaceTypeHttp = "HTTP" ) +// NamespaceType_Values returns all elements of the NamespaceType enum +func NamespaceType_Values() []string { + return []string{ + NamespaceTypeDnsPublic, + NamespaceTypeDnsPrivate, + NamespaceTypeHttp, + } +} + const ( // OperationFilterNameNamespaceId is a OperationFilterName enum value OperationFilterNameNamespaceId = "NAMESPACE_ID" @@ -6794,6 +7681,17 @@ const ( OperationFilterNameUpdateDate = "UPDATE_DATE" ) +// OperationFilterName_Values returns all elements of the OperationFilterName enum +func OperationFilterName_Values() []string { + return []string{ + OperationFilterNameNamespaceId, + OperationFilterNameServiceId, + OperationFilterNameStatus, + OperationFilterNameType, + OperationFilterNameUpdateDate, + } +} + const ( // OperationStatusSubmitted is a OperationStatus enum value OperationStatusSubmitted = "SUBMITTED" @@ -6808,6 +7706,16 @@ const ( OperationStatusFail = "FAIL" ) +// OperationStatus_Values returns all elements of the OperationStatus enum +func OperationStatus_Values() []string { + return []string{ + OperationStatusSubmitted, + OperationStatusPending, + OperationStatusSuccess, + OperationStatusFail, + } +} + const ( // OperationTargetTypeNamespace is a OperationTargetType enum value OperationTargetTypeNamespace = "NAMESPACE" @@ -6819,6 +7727,15 @@ const ( OperationTargetTypeInstance = "INSTANCE" ) +// OperationTargetType_Values returns all elements of the OperationTargetType enum +func OperationTargetType_Values() []string { + return []string{ + OperationTargetTypeNamespace, + OperationTargetTypeService, + OperationTargetTypeInstance, + } +} + const ( // OperationTypeCreateNamespace is a OperationType enum value OperationTypeCreateNamespace = "CREATE_NAMESPACE" @@ -6836,6 +7753,17 @@ const ( OperationTypeDeregisterInstance = "DEREGISTER_INSTANCE" ) +// OperationType_Values returns all elements of the OperationType enum +func OperationType_Values() []string { + return []string{ + OperationTypeCreateNamespace, + OperationTypeDeleteNamespace, + OperationTypeUpdateService, + OperationTypeRegisterInstance, + OperationTypeDeregisterInstance, + } +} + const ( // RecordTypeSrv is a RecordType enum value RecordTypeSrv = "SRV" @@ -6850,6 +7778,16 @@ const ( RecordTypeCname = "CNAME" ) +// RecordType_Values returns all elements of the RecordType enum +func RecordType_Values() []string { + return []string{ + RecordTypeSrv, + RecordTypeA, + RecordTypeAaaa, + RecordTypeCname, + } +} + const ( // RoutingPolicyMultivalue is a RoutingPolicy enum value RoutingPolicyMultivalue = "MULTIVALUE" @@ -6858,7 +7796,22 @@ const ( RoutingPolicyWeighted = "WEIGHTED" ) +// RoutingPolicy_Values returns all elements of the RoutingPolicy enum +func RoutingPolicy_Values() []string { + return []string{ + RoutingPolicyMultivalue, + RoutingPolicyWeighted, + } +} + const ( // ServiceFilterNameNamespaceId is a ServiceFilterName enum value ServiceFilterNameNamespaceId = "NAMESPACE_ID" ) + +// ServiceFilterName_Values returns all elements of the ServiceFilterName enum +func ServiceFilterName_Values() []string { + return []string{ + ServiceFilterNameNamespaceId, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/servicediscovery/errors.go b/vendor/github.com/aws/aws-sdk-go/service/servicediscovery/errors.go index 0e4e0085797..540fb52082b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/servicediscovery/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/servicediscovery/errors.go @@ -54,6 +54,15 @@ const ( // No operation exists with the specified ID. ErrCodeOperationNotFound = "OperationNotFound" + // ErrCodeRequestLimitExceeded for service response error code + // "RequestLimitExceeded". + // + // The operation can't be completed because you've reached the quota for the + // number of requests. For more information, see AWS Cloud Map API request throttling + // quota (https://docs.aws.amazon.com/cloud-map/latest/dg/throttling.html) in + // the AWS Cloud Map Developer Guide. + ErrCodeRequestLimitExceeded = "RequestLimitExceeded" + // ErrCodeResourceInUse for service response error code // "ResourceInUse". // @@ -64,10 +73,16 @@ const ( // ErrCodeResourceLimitExceeded for service response error code // "ResourceLimitExceeded". // - // The resource can't be created because you've reached the limit on the number + // The resource can't be created because you've reached the quota on the number // of resources. ErrCodeResourceLimitExceeded = "ResourceLimitExceeded" + // ErrCodeResourceNotFoundException for service response error code + // "ResourceNotFoundException". + // + // The operation can't be completed because the resource was not found. + ErrCodeResourceNotFoundException = "ResourceNotFoundException" + // ErrCodeServiceAlreadyExists for service response error code // "ServiceAlreadyExists". // @@ -80,18 +95,28 @@ const ( // // No service exists with the specified ID. ErrCodeServiceNotFound = "ServiceNotFound" + + // ErrCodeTooManyTagsException for service response error code + // "TooManyTagsException". + // + // The list of tags on the resource is over the quota. The maximum number of + // tags that can be applied to a resource is 50. + ErrCodeTooManyTagsException = "TooManyTagsException" ) var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ - "CustomHealthNotFound": newErrorCustomHealthNotFound, - "DuplicateRequest": newErrorDuplicateRequest, - "InstanceNotFound": newErrorInstanceNotFound, - "InvalidInput": newErrorInvalidInput, - "NamespaceAlreadyExists": newErrorNamespaceAlreadyExists, - "NamespaceNotFound": newErrorNamespaceNotFound, - "OperationNotFound": newErrorOperationNotFound, - "ResourceInUse": newErrorResourceInUse, - "ResourceLimitExceeded": newErrorResourceLimitExceeded, - "ServiceAlreadyExists": newErrorServiceAlreadyExists, - "ServiceNotFound": newErrorServiceNotFound, + "CustomHealthNotFound": newErrorCustomHealthNotFound, + "DuplicateRequest": newErrorDuplicateRequest, + "InstanceNotFound": newErrorInstanceNotFound, + "InvalidInput": newErrorInvalidInput, + "NamespaceAlreadyExists": newErrorNamespaceAlreadyExists, + "NamespaceNotFound": newErrorNamespaceNotFound, + "OperationNotFound": newErrorOperationNotFound, + "RequestLimitExceeded": newErrorRequestLimitExceeded, + "ResourceInUse": newErrorResourceInUse, + "ResourceLimitExceeded": newErrorResourceLimitExceeded, + "ResourceNotFoundException": newErrorResourceNotFoundException, + "ServiceAlreadyExists": newErrorServiceAlreadyExists, + "ServiceNotFound": newErrorServiceNotFound, + "TooManyTagsException": newErrorTooManyTagsException, } diff --git a/vendor/github.com/aws/aws-sdk-go/service/servicequotas/api.go b/vendor/github.com/aws/aws-sdk-go/service/servicequotas/api.go index 60a0a84ac66..0d705da1a49 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/servicequotas/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/servicequotas/api.go @@ -4791,6 +4791,16 @@ const ( ErrorCodeServiceQuotaNotAvailableError = "SERVICE_QUOTA_NOT_AVAILABLE_ERROR" ) +// ErrorCode_Values returns all elements of the ErrorCode enum +func ErrorCode_Values() []string { + return []string{ + ErrorCodeDependencyAccessDeniedError, + ErrorCodeDependencyThrottlingError, + ErrorCodeDependencyServiceError, + ErrorCodeServiceQuotaNotAvailableError, + } +} + const ( // PeriodUnitMicrosecond is a PeriodUnit enum value PeriodUnitMicrosecond = "MICROSECOND" @@ -4814,6 +4824,19 @@ const ( PeriodUnitWeek = "WEEK" ) +// PeriodUnit_Values returns all elements of the PeriodUnit enum +func PeriodUnit_Values() []string { + return []string{ + PeriodUnitMicrosecond, + PeriodUnitMillisecond, + PeriodUnitSecond, + PeriodUnitMinute, + PeriodUnitHour, + PeriodUnitDay, + PeriodUnitWeek, + } +} + const ( // RequestStatusPending is a RequestStatus enum value RequestStatusPending = "PENDING" @@ -4831,6 +4854,17 @@ const ( RequestStatusCaseClosed = "CASE_CLOSED" ) +// RequestStatus_Values returns all elements of the RequestStatus enum +func RequestStatus_Values() []string { + return []string{ + RequestStatusPending, + RequestStatusCaseOpened, + RequestStatusApproved, + RequestStatusDenied, + RequestStatusCaseClosed, + } +} + const ( // ServiceQuotaTemplateAssociationStatusAssociated is a ServiceQuotaTemplateAssociationStatus enum value ServiceQuotaTemplateAssociationStatusAssociated = "ASSOCIATED" @@ -4838,3 +4872,11 @@ const ( // ServiceQuotaTemplateAssociationStatusDisassociated is a ServiceQuotaTemplateAssociationStatus enum value ServiceQuotaTemplateAssociationStatusDisassociated = "DISASSOCIATED" ) + +// ServiceQuotaTemplateAssociationStatus_Values returns all elements of the ServiceQuotaTemplateAssociationStatus enum +func ServiceQuotaTemplateAssociationStatus_Values() []string { + return []string{ + ServiceQuotaTemplateAssociationStatusAssociated, + ServiceQuotaTemplateAssociationStatusDisassociated, + } +} 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 5a2bc39fdbc..7dc9aef8ab4 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 @@ -15124,6 +15124,14 @@ const ( BehaviorOnMXFailureRejectMessage = "RejectMessage" ) +// BehaviorOnMXFailure_Values returns all elements of the BehaviorOnMXFailure enum +func BehaviorOnMXFailure_Values() []string { + return []string{ + BehaviorOnMXFailureUseDefaultValue, + BehaviorOnMXFailureRejectMessage, + } +} + const ( // BounceTypeDoesNotExist is a BounceType enum value BounceTypeDoesNotExist = "DoesNotExist" @@ -15144,6 +15152,18 @@ const ( BounceTypeTemporaryFailure = "TemporaryFailure" ) +// BounceType_Values returns all elements of the BounceType enum +func BounceType_Values() []string { + return []string{ + BounceTypeDoesNotExist, + BounceTypeMessageTooLarge, + BounceTypeExceededQuota, + BounceTypeContentRejected, + BounceTypeUndefined, + BounceTypeTemporaryFailure, + } +} + const ( // BulkEmailStatusSuccess is a BulkEmailStatus enum value BulkEmailStatusSuccess = "Success" @@ -15188,6 +15208,26 @@ const ( BulkEmailStatusFailed = "Failed" ) +// BulkEmailStatus_Values returns all elements of the BulkEmailStatus enum +func BulkEmailStatus_Values() []string { + return []string{ + BulkEmailStatusSuccess, + BulkEmailStatusMessageRejected, + BulkEmailStatusMailFromDomainNotVerified, + BulkEmailStatusConfigurationSetDoesNotExist, + BulkEmailStatusTemplateDoesNotExist, + BulkEmailStatusAccountSuspended, + BulkEmailStatusAccountThrottled, + BulkEmailStatusAccountDailyQuotaExceeded, + BulkEmailStatusInvalidSendingPoolName, + BulkEmailStatusAccountSendingPaused, + BulkEmailStatusConfigurationSetSendingPaused, + BulkEmailStatusInvalidParameterValue, + BulkEmailStatusTransientFailure, + BulkEmailStatusFailed, + } +} + const ( // ConfigurationSetAttributeEventDestinations is a ConfigurationSetAttribute enum value ConfigurationSetAttributeEventDestinations = "eventDestinations" @@ -15202,6 +15242,16 @@ const ( ConfigurationSetAttributeReputationOptions = "reputationOptions" ) +// ConfigurationSetAttribute_Values returns all elements of the ConfigurationSetAttribute enum +func ConfigurationSetAttribute_Values() []string { + return []string{ + ConfigurationSetAttributeEventDestinations, + ConfigurationSetAttributeTrackingOptions, + ConfigurationSetAttributeDeliveryOptions, + ConfigurationSetAttributeReputationOptions, + } +} + const ( // CustomMailFromStatusPending is a CustomMailFromStatus enum value CustomMailFromStatusPending = "Pending" @@ -15216,6 +15266,16 @@ const ( CustomMailFromStatusTemporaryFailure = "TemporaryFailure" ) +// CustomMailFromStatus_Values returns all elements of the CustomMailFromStatus enum +func CustomMailFromStatus_Values() []string { + return []string{ + CustomMailFromStatusPending, + CustomMailFromStatusSuccess, + CustomMailFromStatusFailed, + CustomMailFromStatusTemporaryFailure, + } +} + const ( // DimensionValueSourceMessageTag is a DimensionValueSource enum value DimensionValueSourceMessageTag = "messageTag" @@ -15227,6 +15287,15 @@ const ( DimensionValueSourceLinkTag = "linkTag" ) +// DimensionValueSource_Values returns all elements of the DimensionValueSource enum +func DimensionValueSource_Values() []string { + return []string{ + DimensionValueSourceMessageTag, + DimensionValueSourceEmailHeader, + DimensionValueSourceLinkTag, + } +} + const ( // DsnActionFailed is a DsnAction enum value DsnActionFailed = "failed" @@ -15244,6 +15313,17 @@ const ( DsnActionExpanded = "expanded" ) +// DsnAction_Values returns all elements of the DsnAction enum +func DsnAction_Values() []string { + return []string{ + DsnActionFailed, + DsnActionDelayed, + DsnActionDelivered, + DsnActionRelayed, + DsnActionExpanded, + } +} + const ( // EventTypeSend is a EventType enum value EventTypeSend = "send" @@ -15270,6 +15350,20 @@ const ( EventTypeRenderingFailure = "renderingFailure" ) +// EventType_Values returns all elements of the EventType enum +func EventType_Values() []string { + return []string{ + EventTypeSend, + EventTypeReject, + EventTypeBounce, + EventTypeComplaint, + EventTypeDelivery, + EventTypeOpen, + EventTypeClick, + EventTypeRenderingFailure, + } +} + const ( // IdentityTypeEmailAddress is a IdentityType enum value IdentityTypeEmailAddress = "EmailAddress" @@ -15278,6 +15372,14 @@ const ( IdentityTypeDomain = "Domain" ) +// IdentityType_Values returns all elements of the IdentityType enum +func IdentityType_Values() []string { + return []string{ + IdentityTypeEmailAddress, + IdentityTypeDomain, + } +} + const ( // InvocationTypeEvent is a InvocationType enum value InvocationTypeEvent = "Event" @@ -15286,6 +15388,14 @@ const ( InvocationTypeRequestResponse = "RequestResponse" ) +// InvocationType_Values returns all elements of the InvocationType enum +func InvocationType_Values() []string { + return []string{ + InvocationTypeEvent, + InvocationTypeRequestResponse, + } +} + const ( // NotificationTypeBounce is a NotificationType enum value NotificationTypeBounce = "Bounce" @@ -15297,6 +15407,15 @@ const ( NotificationTypeDelivery = "Delivery" ) +// NotificationType_Values returns all elements of the NotificationType enum +func NotificationType_Values() []string { + return []string{ + NotificationTypeBounce, + NotificationTypeComplaint, + NotificationTypeDelivery, + } +} + const ( // ReceiptFilterPolicyBlock is a ReceiptFilterPolicy enum value ReceiptFilterPolicyBlock = "Block" @@ -15305,6 +15424,14 @@ const ( ReceiptFilterPolicyAllow = "Allow" ) +// ReceiptFilterPolicy_Values returns all elements of the ReceiptFilterPolicy enum +func ReceiptFilterPolicy_Values() []string { + return []string{ + ReceiptFilterPolicyBlock, + ReceiptFilterPolicyAllow, + } +} + const ( // SNSActionEncodingUtf8 is a SNSActionEncoding enum value SNSActionEncodingUtf8 = "UTF-8" @@ -15313,11 +15440,26 @@ const ( SNSActionEncodingBase64 = "Base64" ) +// SNSActionEncoding_Values returns all elements of the SNSActionEncoding enum +func SNSActionEncoding_Values() []string { + return []string{ + SNSActionEncodingUtf8, + SNSActionEncodingBase64, + } +} + const ( // StopScopeRuleSet is a StopScope enum value StopScopeRuleSet = "RuleSet" ) +// StopScope_Values returns all elements of the StopScope enum +func StopScope_Values() []string { + return []string{ + StopScopeRuleSet, + } +} + const ( // TlsPolicyRequire is a TlsPolicy enum value TlsPolicyRequire = "Require" @@ -15326,6 +15468,14 @@ const ( TlsPolicyOptional = "Optional" ) +// TlsPolicy_Values returns all elements of the TlsPolicy enum +func TlsPolicy_Values() []string { + return []string{ + TlsPolicyRequire, + TlsPolicyOptional, + } +} + const ( // VerificationStatusPending is a VerificationStatus enum value VerificationStatusPending = "Pending" @@ -15342,3 +15492,14 @@ const ( // VerificationStatusNotStarted is a VerificationStatus enum value VerificationStatusNotStarted = "NotStarted" ) + +// VerificationStatus_Values returns all elements of the VerificationStatus enum +func VerificationStatus_Values() []string { + return []string{ + VerificationStatusPending, + VerificationStatusSuccess, + VerificationStatusFailed, + VerificationStatusTemporaryFailure, + VerificationStatusNotStarted, + } +} 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 c93297216c7..30d4443a14e 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 @@ -7678,6 +7678,17 @@ const ( ExecutionStatusAborted = "ABORTED" ) +// ExecutionStatus_Values returns all elements of the ExecutionStatus enum +func ExecutionStatus_Values() []string { + return []string{ + ExecutionStatusRunning, + ExecutionStatusSucceeded, + ExecutionStatusFailed, + ExecutionStatusTimedOut, + ExecutionStatusAborted, + } +} + const ( // HistoryEventTypeActivityFailed is a HistoryEventType enum value HistoryEventTypeActivityFailed = "ActivityFailed" @@ -7845,6 +7856,67 @@ const ( HistoryEventTypeWaitStateExited = "WaitStateExited" ) +// HistoryEventType_Values returns all elements of the HistoryEventType enum +func HistoryEventType_Values() []string { + return []string{ + HistoryEventTypeActivityFailed, + HistoryEventTypeActivityScheduled, + HistoryEventTypeActivityScheduleFailed, + HistoryEventTypeActivityStarted, + HistoryEventTypeActivitySucceeded, + HistoryEventTypeActivityTimedOut, + HistoryEventTypeChoiceStateEntered, + HistoryEventTypeChoiceStateExited, + HistoryEventTypeExecutionAborted, + HistoryEventTypeExecutionFailed, + HistoryEventTypeExecutionStarted, + HistoryEventTypeExecutionSucceeded, + HistoryEventTypeExecutionTimedOut, + HistoryEventTypeFailStateEntered, + HistoryEventTypeLambdaFunctionFailed, + HistoryEventTypeLambdaFunctionScheduled, + HistoryEventTypeLambdaFunctionScheduleFailed, + HistoryEventTypeLambdaFunctionStarted, + HistoryEventTypeLambdaFunctionStartFailed, + HistoryEventTypeLambdaFunctionSucceeded, + HistoryEventTypeLambdaFunctionTimedOut, + HistoryEventTypeMapIterationAborted, + HistoryEventTypeMapIterationFailed, + HistoryEventTypeMapIterationStarted, + HistoryEventTypeMapIterationSucceeded, + HistoryEventTypeMapStateAborted, + HistoryEventTypeMapStateEntered, + HistoryEventTypeMapStateExited, + HistoryEventTypeMapStateFailed, + HistoryEventTypeMapStateStarted, + HistoryEventTypeMapStateSucceeded, + HistoryEventTypeParallelStateAborted, + HistoryEventTypeParallelStateEntered, + HistoryEventTypeParallelStateExited, + HistoryEventTypeParallelStateFailed, + HistoryEventTypeParallelStateStarted, + HistoryEventTypeParallelStateSucceeded, + HistoryEventTypePassStateEntered, + HistoryEventTypePassStateExited, + HistoryEventTypeSucceedStateEntered, + HistoryEventTypeSucceedStateExited, + HistoryEventTypeTaskFailed, + HistoryEventTypeTaskScheduled, + HistoryEventTypeTaskStarted, + HistoryEventTypeTaskStartFailed, + HistoryEventTypeTaskStateAborted, + HistoryEventTypeTaskStateEntered, + HistoryEventTypeTaskStateExited, + HistoryEventTypeTaskSubmitFailed, + HistoryEventTypeTaskSubmitted, + HistoryEventTypeTaskSucceeded, + HistoryEventTypeTaskTimedOut, + HistoryEventTypeWaitStateAborted, + HistoryEventTypeWaitStateEntered, + HistoryEventTypeWaitStateExited, + } +} + const ( // LogLevelAll is a LogLevel enum value LogLevelAll = "ALL" @@ -7859,6 +7931,16 @@ const ( LogLevelOff = "OFF" ) +// LogLevel_Values returns all elements of the LogLevel enum +func LogLevel_Values() []string { + return []string{ + LogLevelAll, + LogLevelError, + LogLevelFatal, + LogLevelOff, + } +} + const ( // StateMachineStatusActive is a StateMachineStatus enum value StateMachineStatusActive = "ACTIVE" @@ -7867,6 +7949,14 @@ const ( StateMachineStatusDeleting = "DELETING" ) +// StateMachineStatus_Values returns all elements of the StateMachineStatus enum +func StateMachineStatus_Values() []string { + return []string{ + StateMachineStatusActive, + StateMachineStatusDeleting, + } +} + const ( // StateMachineTypeStandard is a StateMachineType enum value StateMachineTypeStandard = "STANDARD" @@ -7874,3 +7964,11 @@ const ( // StateMachineTypeExpress is a StateMachineType enum value StateMachineTypeExpress = "EXPRESS" ) + +// StateMachineType_Values returns all elements of the StateMachineType enum +func StateMachineType_Values() []string { + return []string{ + StateMachineTypeStandard, + StateMachineTypeExpress, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/shield/api.go b/vendor/github.com/aws/aws-sdk-go/service/shield/api.go index 0d070f3b51b..bbbfcde82ad 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/shield/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/shield/api.go @@ -58,7 +58,7 @@ func (c *Shield) AssociateDRTLogBucketRequest(input *AssociateDRTLogBucketInput) // AssociateDRTLogBucket API operation for AWS Shield. // -// Authorizes the DDoS Response team (DRT) to access the specified Amazon S3 +// Authorizes the DDoS Response Team (DRT) to access the specified Amazon S3 // bucket containing your AWS WAF logs. You can associate up to 10 Amazon S3 // buckets with your subscription. // @@ -96,14 +96,14 @@ func (c *Shield) AssociateDRTLogBucketRequest(input *AssociateDRTLogBucketInput) // Exception that indicates that the parameters passed to the API are invalid. // // * AccessDeniedForDependencyException -// In order to grant the necessary access to the DDoS Response Team, the user -// submitting the request must have the iam:PassRole permission. This error +// In order to grant the necessary access to the DDoS Response Team (DRT), the +// user submitting the request must have the iam:PassRole permission. This error // indicates the user did not have the appropriate permissions. For more information, // see Granting a User Permissions to Pass a Role to an AWS Service (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html). // // * OptimisticLockException -// Exception that indicates that the protection state has been modified by another -// client. You can retry the request. +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. // // * ResourceNotFoundException // Exception indicating the specified resource does not exist. @@ -175,7 +175,7 @@ func (c *Shield) AssociateDRTRoleRequest(input *AssociateDRTRoleInput) (req *req // AssociateDRTRole API operation for AWS Shield. // -// Authorizes the DDoS Response team (DRT), using the specified role, to access +// Authorizes the DDoS Response Team (DRT), using the specified role, to access // your AWS account to assist with DDoS attack mitigation during potential attacks. // This enables the DRT to inspect your AWS WAF configuration and create or // update AWS WAF rules and web ACLs. @@ -224,14 +224,14 @@ func (c *Shield) AssociateDRTRoleRequest(input *AssociateDRTRoleInput) (req *req // Exception that indicates that the parameters passed to the API are invalid. // // * AccessDeniedForDependencyException -// In order to grant the necessary access to the DDoS Response Team, the user -// submitting the request must have the iam:PassRole permission. This error +// In order to grant the necessary access to the DDoS Response Team (DRT), the +// user submitting the request must have the iam:PassRole permission. This error // indicates the user did not have the appropriate permissions. For more information, // see Granting a User Permissions to Pass a Role to an AWS Service (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html). // // * OptimisticLockException -// Exception that indicates that the protection state has been modified by another -// client. You can retry the request. +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. // // * ResourceNotFoundException // Exception indicating the specified resource does not exist. @@ -338,8 +338,8 @@ func (c *Shield) AssociateHealthCheckRequest(input *AssociateHealthCheckInput) ( // Exception that indicates that the parameters passed to the API are invalid. // // * OptimisticLockException -// Exception that indicates that the protection state has been modified by another -// client. You can retry the request. +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/AssociateHealthCheck func (c *Shield) AssociateHealthCheck(input *AssociateHealthCheckInput) (*AssociateHealthCheckOutput, error) { @@ -363,6 +363,116 @@ func (c *Shield) AssociateHealthCheckWithContext(ctx aws.Context, input *Associa return out, req.Send() } +const opAssociateProactiveEngagementDetails = "AssociateProactiveEngagementDetails" + +// AssociateProactiveEngagementDetailsRequest generates a "aws/request.Request" representing the +// client's request for the AssociateProactiveEngagementDetails operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See AssociateProactiveEngagementDetails for more information on using the AssociateProactiveEngagementDetails +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the AssociateProactiveEngagementDetailsRequest method. +// req, resp := client.AssociateProactiveEngagementDetailsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/AssociateProactiveEngagementDetails +func (c *Shield) AssociateProactiveEngagementDetailsRequest(input *AssociateProactiveEngagementDetailsInput) (req *request.Request, output *AssociateProactiveEngagementDetailsOutput) { + op := &request.Operation{ + Name: opAssociateProactiveEngagementDetails, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &AssociateProactiveEngagementDetailsInput{} + } + + output = &AssociateProactiveEngagementDetailsOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// AssociateProactiveEngagementDetails API operation for AWS Shield. +// +// Initializes proactive engagement and sets the list of contacts for the DDoS +// Response Team (DRT) to use. You must provide at least one phone number in +// the emergency contact list. +// +// After you have initialized proactive engagement using this call, to disable +// or enable proactive engagement, use the calls DisableProactiveEngagement +// and EnableProactiveEngagement. +// +// This call defines the list of email addresses and phone numbers that the +// DDoS Response Team (DRT) can use to contact you for escalations to the DRT +// and to initiate proactive customer support. +// +// The contacts that you provide in the request replace any contacts that were +// already defined. If you already have contacts defined and want to use them, +// retrieve the list using DescribeEmergencyContactSettings and then provide +// it to this call. +// +// Returns awserr.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 Shield's +// API operation AssociateProactiveEngagementDetails for usage and error information. +// +// Returned Error Types: +// * InternalErrorException +// Exception that indicates that a problem occurred with the service infrastructure. +// You can retry the request. +// +// * InvalidOperationException +// Exception that indicates that the operation would not cause any change to +// occur. +// +// * InvalidParameterException +// Exception that indicates that the parameters passed to the API are invalid. +// +// * ResourceNotFoundException +// Exception indicating the specified resource does not exist. +// +// * OptimisticLockException +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/AssociateProactiveEngagementDetails +func (c *Shield) AssociateProactiveEngagementDetails(input *AssociateProactiveEngagementDetailsInput) (*AssociateProactiveEngagementDetailsOutput, error) { + req, out := c.AssociateProactiveEngagementDetailsRequest(input) + return out, req.Send() +} + +// AssociateProactiveEngagementDetailsWithContext is the same as AssociateProactiveEngagementDetails with the addition of +// the ability to pass a context and additional request options. +// +// See AssociateProactiveEngagementDetails for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Shield) AssociateProactiveEngagementDetailsWithContext(ctx aws.Context, input *AssociateProactiveEngagementDetailsInput, opts ...request.Option) (*AssociateProactiveEngagementDetailsOutput, error) { + req, out := c.AssociateProactiveEngagementDetailsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateProtection = "CreateProtection" // CreateProtectionRequest generates a "aws/request.Request" representing the @@ -449,8 +559,8 @@ func (c *Shield) CreateProtectionRequest(input *CreateProtectionInput) (req *req // Exception indicating the specified resource already exists. // // * OptimisticLockException -// Exception that indicates that the protection state has been modified by another -// client. You can retry the request. +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. // // * ResourceNotFoundException // Exception indicating the specified resource does not exist. @@ -524,15 +634,6 @@ func (c *Shield) CreateSubscriptionRequest(input *CreateSubscriptionInput) (req // // Activates AWS Shield Advanced for an account. // -// As part of this request you can specify EmergencySettings that automaticaly -// grant the DDoS response team (DRT) needed permissions to assist you during -// a suspected DDoS attack. For more information see Authorize the DDoS Response -// Team to Create Rules and Web ACLs on Your Behalf (https://docs.aws.amazon.com/waf/latest/developerguide/authorize-DRT.html). -// -// To use the services of the DRT, you must be subscribed to the Business Support -// plan (https://aws.amazon.com/premiumsupport/business-support/) or the Enterprise -// Support plan (https://aws.amazon.com/premiumsupport/enterprise-support/). -// // When you initally create a subscription, your subscription is set to be automatically // renewed at the end of the existing subscription period. You can change this // by submitting an UpdateSubscription request. @@ -637,8 +738,8 @@ func (c *Shield) DeleteProtectionRequest(input *DeleteProtectionInput) (req *req // Exception indicating the specified resource does not exist. // // * OptimisticLockException -// Exception that indicates that the protection state has been modified by another -// client. You can retry the request. +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/DeleteProtection func (c *Shield) DeleteProtection(input *DeleteProtectionInput) (*DeleteProtectionOutput, error) { @@ -892,7 +993,7 @@ func (c *Shield) DescribeDRTAccessRequest(input *DescribeDRTAccessInput) (req *r // DescribeDRTAccess API operation for AWS Shield. // // Returns the current role and list of Amazon S3 log buckets used by the DDoS -// Response team (DRT) to access your AWS account while assisting with attack +// Response Team (DRT) to access your AWS account while assisting with attack // mitigation. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -976,8 +1077,9 @@ func (c *Shield) DescribeEmergencyContactSettingsRequest(input *DescribeEmergenc // DescribeEmergencyContactSettings API operation for AWS Shield. // -// Lists the email addresses that the DRT can use to contact you during a suspected -// attack. +// A list of email addresses and phone numbers that the DDoS Response Team (DRT) +// can use to contact you if you have proactive engagement enabled, for escalations +// to the DRT and to initiate proactive customer support. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1185,6 +1287,102 @@ func (c *Shield) DescribeSubscriptionWithContext(ctx aws.Context, input *Describ return out, req.Send() } +const opDisableProactiveEngagement = "DisableProactiveEngagement" + +// DisableProactiveEngagementRequest generates a "aws/request.Request" representing the +// client's request for the DisableProactiveEngagement operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DisableProactiveEngagement for more information on using the DisableProactiveEngagement +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DisableProactiveEngagementRequest method. +// req, resp := client.DisableProactiveEngagementRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/DisableProactiveEngagement +func (c *Shield) DisableProactiveEngagementRequest(input *DisableProactiveEngagementInput) (req *request.Request, output *DisableProactiveEngagementOutput) { + op := &request.Operation{ + Name: opDisableProactiveEngagement, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DisableProactiveEngagementInput{} + } + + output = &DisableProactiveEngagementOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DisableProactiveEngagement API operation for AWS Shield. +// +// Removes authorization from the DDoS Response Team (DRT) to notify contacts +// about escalations to the DRT and to initiate proactive customer support. +// +// Returns awserr.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 Shield's +// API operation DisableProactiveEngagement for usage and error information. +// +// Returned Error Types: +// * InternalErrorException +// Exception that indicates that a problem occurred with the service infrastructure. +// You can retry the request. +// +// * InvalidOperationException +// Exception that indicates that the operation would not cause any change to +// occur. +// +// * InvalidParameterException +// Exception that indicates that the parameters passed to the API are invalid. +// +// * ResourceNotFoundException +// Exception indicating the specified resource does not exist. +// +// * OptimisticLockException +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/DisableProactiveEngagement +func (c *Shield) DisableProactiveEngagement(input *DisableProactiveEngagementInput) (*DisableProactiveEngagementOutput, error) { + req, out := c.DisableProactiveEngagementRequest(input) + return out, req.Send() +} + +// DisableProactiveEngagementWithContext is the same as DisableProactiveEngagement with the addition of +// the ability to pass a context and additional request options. +// +// See DisableProactiveEngagement for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Shield) DisableProactiveEngagementWithContext(ctx aws.Context, input *DisableProactiveEngagementInput, opts ...request.Option) (*DisableProactiveEngagementOutput, error) { + req, out := c.DisableProactiveEngagementRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDisassociateDRTLogBucket = "DisassociateDRTLogBucket" // DisassociateDRTLogBucketRequest generates a "aws/request.Request" representing the @@ -1230,7 +1428,7 @@ func (c *Shield) DisassociateDRTLogBucketRequest(input *DisassociateDRTLogBucket // DisassociateDRTLogBucket API operation for AWS Shield. // -// Removes the DDoS Response team's (DRT) access to the specified Amazon S3 +// Removes the DDoS Response Team's (DRT) access to the specified Amazon S3 // bucket containing your AWS WAF logs. // // To make a DisassociateDRTLogBucket request, you must be subscribed to the @@ -1260,14 +1458,14 @@ func (c *Shield) DisassociateDRTLogBucketRequest(input *DisassociateDRTLogBucket // The ARN of the role that you specifed does not exist. // // * AccessDeniedForDependencyException -// In order to grant the necessary access to the DDoS Response Team, the user -// submitting the request must have the iam:PassRole permission. This error +// In order to grant the necessary access to the DDoS Response Team (DRT), the +// user submitting the request must have the iam:PassRole permission. This error // indicates the user did not have the appropriate permissions. For more information, // see Granting a User Permissions to Pass a Role to an AWS Service (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html). // // * OptimisticLockException -// Exception that indicates that the protection state has been modified by another -// client. You can retry the request. +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. // // * ResourceNotFoundException // Exception indicating the specified resource does not exist. @@ -1339,7 +1537,7 @@ func (c *Shield) DisassociateDRTRoleRequest(input *DisassociateDRTRoleInput) (re // DisassociateDRTRole API operation for AWS Shield. // -// Removes the DDoS Response team's (DRT) access to your AWS account. +// Removes the DDoS Response Team's (DRT) access to your AWS account. // // To make a DisassociateDRTRole request, you must be subscribed to the Business // Support plan (https://aws.amazon.com/premiumsupport/business-support/) or @@ -1365,8 +1563,8 @@ func (c *Shield) DisassociateDRTRoleRequest(input *DisassociateDRTRoleInput) (re // occur. // // * OptimisticLockException -// Exception that indicates that the protection state has been modified by another -// client. You can retry the request. +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. // // * ResourceNotFoundException // Exception indicating the specified resource does not exist. @@ -1467,8 +1665,8 @@ func (c *Shield) DisassociateHealthCheckRequest(input *DisassociateHealthCheckIn // Exception indicating the specified resource does not exist. // // * OptimisticLockException -// Exception that indicates that the protection state has been modified by another -// client. You can retry the request. +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/DisassociateHealthCheck func (c *Shield) DisassociateHealthCheck(input *DisassociateHealthCheckInput) (*DisassociateHealthCheckOutput, error) { @@ -1492,6 +1690,103 @@ func (c *Shield) DisassociateHealthCheckWithContext(ctx aws.Context, input *Disa return out, req.Send() } +const opEnableProactiveEngagement = "EnableProactiveEngagement" + +// EnableProactiveEngagementRequest generates a "aws/request.Request" representing the +// client's request for the EnableProactiveEngagement operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See EnableProactiveEngagement for more information on using the EnableProactiveEngagement +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the EnableProactiveEngagementRequest method. +// req, resp := client.EnableProactiveEngagementRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/EnableProactiveEngagement +func (c *Shield) EnableProactiveEngagementRequest(input *EnableProactiveEngagementInput) (req *request.Request, output *EnableProactiveEngagementOutput) { + op := &request.Operation{ + Name: opEnableProactiveEngagement, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &EnableProactiveEngagementInput{} + } + + output = &EnableProactiveEngagementOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// EnableProactiveEngagement API operation for AWS Shield. +// +// Authorizes the DDoS Response Team (DRT) to use email and phone to notify +// contacts about escalations to the DRT and to initiate proactive customer +// support. +// +// Returns awserr.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 Shield's +// API operation EnableProactiveEngagement for usage and error information. +// +// Returned Error Types: +// * InternalErrorException +// Exception that indicates that a problem occurred with the service infrastructure. +// You can retry the request. +// +// * InvalidOperationException +// Exception that indicates that the operation would not cause any change to +// occur. +// +// * InvalidParameterException +// Exception that indicates that the parameters passed to the API are invalid. +// +// * ResourceNotFoundException +// Exception indicating the specified resource does not exist. +// +// * OptimisticLockException +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/EnableProactiveEngagement +func (c *Shield) EnableProactiveEngagement(input *EnableProactiveEngagementInput) (*EnableProactiveEngagementOutput, error) { + req, out := c.EnableProactiveEngagementRequest(input) + return out, req.Send() +} + +// EnableProactiveEngagementWithContext is the same as EnableProactiveEngagement with the addition of +// the ability to pass a context and additional request options. +// +// See EnableProactiveEngagement for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Shield) EnableProactiveEngagementWithContext(ctx aws.Context, input *EnableProactiveEngagementInput, opts ...request.Option) (*EnableProactiveEngagementOutput, error) { + req, out := c.EnableProactiveEngagementRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetSubscriptionState = "GetSubscriptionState" // GetSubscriptionStateRequest generates a "aws/request.Request" representing the @@ -1603,6 +1898,12 @@ func (c *Shield) ListAttacksRequest(input *ListAttacksInput) (req *request.Reque Name: opListAttacks, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -1660,6 +1961,58 @@ func (c *Shield) ListAttacksWithContext(ctx aws.Context, input *ListAttacksInput return out, req.Send() } +// ListAttacksPages iterates over the pages of a ListAttacks operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListAttacks 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 ListAttacks operation. +// pageNum := 0 +// err := client.ListAttacksPages(params, +// func(page *shield.ListAttacksOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Shield) ListAttacksPages(input *ListAttacksInput, fn func(*ListAttacksOutput, bool) bool) error { + return c.ListAttacksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAttacksPagesWithContext same as ListAttacksPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Shield) ListAttacksPagesWithContext(ctx aws.Context, input *ListAttacksInput, fn func(*ListAttacksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAttacksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAttacksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListAttacksOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListProtections = "ListProtections" // ListProtectionsRequest generates a "aws/request.Request" representing the @@ -1691,6 +2044,12 @@ func (c *Shield) ListProtectionsRequest(input *ListProtectionsInput) (req *reque Name: opListProtections, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -1747,6 +2106,58 @@ func (c *Shield) ListProtectionsWithContext(ctx aws.Context, input *ListProtecti return out, req.Send() } +// ListProtectionsPages iterates over the pages of a ListProtections operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListProtections 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 ListProtections operation. +// pageNum := 0 +// err := client.ListProtectionsPages(params, +// func(page *shield.ListProtectionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Shield) ListProtectionsPages(input *ListProtectionsInput, fn func(*ListProtectionsOutput, bool) bool) error { + return c.ListProtectionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListProtectionsPagesWithContext same as ListProtectionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Shield) ListProtectionsPagesWithContext(ctx aws.Context, input *ListProtectionsInput, fn func(*ListProtectionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListProtectionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListProtectionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListProtectionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opUpdateEmergencyContactSettings = "UpdateEmergencyContactSettings" // UpdateEmergencyContactSettingsRequest generates a "aws/request.Request" representing the @@ -1792,8 +2203,10 @@ func (c *Shield) UpdateEmergencyContactSettingsRequest(input *UpdateEmergencyCon // UpdateEmergencyContactSettings API operation for AWS Shield. // -// Updates the details of the list of email addresses that the DRT can use to -// contact you during a suspected attack. +// Updates the details of the list of email addresses and phone numbers that +// the DDoS Response Team (DRT) can use to contact you if you have proactive +// engagement enabled, for escalations to the DRT and to initiate proactive +// customer support. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1811,8 +2224,8 @@ func (c *Shield) UpdateEmergencyContactSettingsRequest(input *UpdateEmergencyCon // Exception that indicates that the parameters passed to the API are invalid. // // * OptimisticLockException -// Exception that indicates that the protection state has been modified by another -// client. You can retry the request. +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. // // * ResourceNotFoundException // Exception indicating the specified resource does not exist. @@ -1912,8 +2325,8 @@ func (c *Shield) UpdateSubscriptionRequest(input *UpdateSubscriptionInput) (req // Exception that indicates that the parameters passed to the API are invalid. // // * OptimisticLockException -// Exception that indicates that the protection state has been modified by another -// client. You can retry the request. +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. // // See also, https://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/UpdateSubscription func (c *Shield) UpdateSubscription(input *UpdateSubscriptionInput) (*UpdateSubscriptionOutput, error) { @@ -1994,8 +2407,8 @@ func (s *AccessDeniedException) RequestID() string { return s.RespMetadata.RequestID } -// In order to grant the necessary access to the DDoS Response Team, the user -// submitting the request must have the iam:PassRole permission. This error +// In order to grant the necessary access to the DDoS Response Team (DRT), the +// user submitting the request must have the iam:PassRole permission. This error // indicates the user did not have the appropriate permissions. For more information, // see Granting a User Permissions to Pass a Role to an AWS Service (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html). type AccessDeniedForDependencyException struct { @@ -2243,6 +2656,77 @@ func (s AssociateHealthCheckOutput) GoString() string { return s.String() } +type AssociateProactiveEngagementDetailsInput struct { + _ struct{} `type:"structure"` + + // A list of email addresses and phone numbers that the DDoS Response Team (DRT) + // can use to contact you for escalations to the DRT and to initiate proactive + // customer support. + // + // To enable proactive engagement, the contact list must include at least one + // phone number. + // + // The contacts that you provide here replace any contacts that were already + // defined. If you already have contacts defined and want to use them, retrieve + // the list using DescribeEmergencyContactSettings and then provide it here. + // + // EmergencyContactList is a required field + EmergencyContactList []*EmergencyContact `type:"list" required:"true"` +} + +// String returns the string representation +func (s AssociateProactiveEngagementDetailsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateProactiveEngagementDetailsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AssociateProactiveEngagementDetailsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AssociateProactiveEngagementDetailsInput"} + if s.EmergencyContactList == nil { + invalidParams.Add(request.NewErrParamRequired("EmergencyContactList")) + } + if s.EmergencyContactList != nil { + for i, v := range s.EmergencyContactList { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "EmergencyContactList", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetEmergencyContactList sets the EmergencyContactList field's value. +func (s *AssociateProactiveEngagementDetailsInput) SetEmergencyContactList(v []*EmergencyContact) *AssociateProactiveEngagementDetailsInput { + s.EmergencyContactList = v + return s +} + +type AssociateProactiveEngagementDetailsOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s AssociateProactiveEngagementDetailsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AssociateProactiveEngagementDetailsOutput) GoString() string { + return s.String() +} + // The details of a DDoS attack. type AttackDetail struct { _ struct{} `type:"structure"` @@ -2895,8 +3379,9 @@ func (s DescribeEmergencyContactSettingsInput) GoString() string { type DescribeEmergencyContactSettingsOutput struct { _ struct{} `type:"structure"` - // A list of email addresses that the DRT can use to contact you during a suspected - // attack. + // A list of email addresses and phone numbers that the DDoS Response Team (DRT) + // can use to contact you if you have proactive engagement enabled, for escalations + // to the DRT and to initiate proactive customer support. EmergencyContactList []*EmergencyContact `type:"list"` } @@ -3028,6 +3513,34 @@ func (s *DescribeSubscriptionOutput) SetSubscription(v *Subscription) *DescribeS return s } +type DisableProactiveEngagementInput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DisableProactiveEngagementInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisableProactiveEngagementInput) GoString() string { + return s.String() +} + +type DisableProactiveEngagementOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DisableProactiveEngagementOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DisableProactiveEngagementOutput) GoString() string { + return s.String() +} + type DisassociateDRTLogBucketInput struct { _ struct{} `type:"structure"` @@ -3185,15 +3698,22 @@ func (s DisassociateHealthCheckOutput) GoString() string { return s.String() } -// Contact information that the DRT can use to contact you during a suspected -// attack. +// Contact information that the DRT can use to contact you if you have proactive +// engagement enabled, for escalations to the DRT and to initiate proactive +// customer support. type EmergencyContact struct { _ struct{} `type:"structure"` - // An email address that the DRT can use to contact you during a suspected attack. + // Additional notes regarding the contact. + ContactNotes *string `min:"1" type:"string"` + + // The email address for the contact. // // EmailAddress is a required field EmailAddress *string `min:"1" type:"string" required:"true"` + + // The phone number for the contact. + PhoneNumber *string `min:"1" type:"string"` } // String returns the string representation @@ -3209,12 +3729,18 @@ func (s EmergencyContact) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *EmergencyContact) Validate() error { invalidParams := request.ErrInvalidParams{Context: "EmergencyContact"} + if s.ContactNotes != nil && len(*s.ContactNotes) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ContactNotes", 1)) + } if s.EmailAddress == nil { invalidParams.Add(request.NewErrParamRequired("EmailAddress")) } if s.EmailAddress != nil && len(*s.EmailAddress) < 1 { invalidParams.Add(request.NewErrParamMinLen("EmailAddress", 1)) } + if s.PhoneNumber != nil && len(*s.PhoneNumber) < 1 { + invalidParams.Add(request.NewErrParamMinLen("PhoneNumber", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -3222,12 +3748,52 @@ func (s *EmergencyContact) Validate() error { return nil } +// SetContactNotes sets the ContactNotes field's value. +func (s *EmergencyContact) SetContactNotes(v string) *EmergencyContact { + s.ContactNotes = &v + return s +} + // SetEmailAddress sets the EmailAddress field's value. func (s *EmergencyContact) SetEmailAddress(v string) *EmergencyContact { s.EmailAddress = &v return s } +// SetPhoneNumber sets the PhoneNumber field's value. +func (s *EmergencyContact) SetPhoneNumber(v string) *EmergencyContact { + s.PhoneNumber = &v + return s +} + +type EnableProactiveEngagementInput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s EnableProactiveEngagementInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EnableProactiveEngagementInput) GoString() string { + return s.String() +} + +type EnableProactiveEngagementOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s EnableProactiveEngagementOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EnableProactiveEngagementOutput) GoString() string { + return s.String() +} + type GetSubscriptionStateInput struct { _ struct{} `type:"structure"` } @@ -4006,8 +4572,8 @@ func (s *NoAssociatedRoleException) RequestID() string { return s.RespMetadata.RequestID } -// Exception that indicates that the protection state has been modified by another -// client. You can retry the request. +// Exception that indicates that the resource state has been modified by another +// client. Retrieve the resource and then retry your request. type OptimisticLockException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -4297,6 +4863,17 @@ type Subscription struct { // Specifies how many protections of a given type you can create. Limits []*Limit `type:"list"` + // If ENABLED, the DDoS Response Team (DRT) will use email and phone to notify + // contacts about escalations to the DRT and to initiate proactive customer + // support. + // + // If PENDING, you have requested proactive engagement and the request is pending. + // The status changes to ENABLED when your request is fully processed. + // + // If DISABLED, the DRT will not proactively notify contacts about escalations + // or to initiate proactive customer support. + ProactiveEngagementStatus *string `type:"string" enum:"ProactiveEngagementStatus"` + // The start time of the subscription, in Unix time in seconds. For more information // see timestamp (http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#parameter-types). StartTime *time.Time `type:"timestamp"` @@ -4333,6 +4910,12 @@ func (s *Subscription) SetLimits(v []*Limit) *Subscription { return s } +// SetProactiveEngagementStatus sets the ProactiveEngagementStatus field's value. +func (s *Subscription) SetProactiveEngagementStatus(v string) *Subscription { + s.ProactiveEngagementStatus = &v + return s +} + // SetStartTime sets the StartTime field's value. func (s *Subscription) SetStartTime(v time.Time) *Subscription { s.StartTime = &v @@ -4487,8 +5070,12 @@ func (s *TimeRange) SetToExclusive(v time.Time) *TimeRange { type UpdateEmergencyContactSettingsInput struct { _ struct{} `type:"structure"` - // A list of email addresses that the DRT can use to contact you during a suspected - // attack. + // A list of email addresses and phone numbers that the DDoS Response Team (DRT) + // can use to contact you if you have proactive engagement enabled, for escalations + // to the DRT and to initiate proactive customer support. + // + // If you have proactive engagement enabled, the contact list must include at + // least one phone number. EmergencyContactList []*EmergencyContact `type:"list"` } @@ -4591,6 +5178,14 @@ const ( AttackLayerApplication = "APPLICATION" ) +// AttackLayer_Values returns all elements of the AttackLayer enum +func AttackLayer_Values() []string { + return []string{ + AttackLayerNetwork, + AttackLayerApplication, + } +} + const ( // AttackPropertyIdentifierDestinationUrl is a AttackPropertyIdentifier enum value AttackPropertyIdentifierDestinationUrl = "DESTINATION_URL" @@ -4617,6 +5212,20 @@ const ( AttackPropertyIdentifierWordpressPingbackSource = "WORDPRESS_PINGBACK_SOURCE" ) +// AttackPropertyIdentifier_Values returns all elements of the AttackPropertyIdentifier enum +func AttackPropertyIdentifier_Values() []string { + return []string{ + AttackPropertyIdentifierDestinationUrl, + AttackPropertyIdentifierReferrer, + AttackPropertyIdentifierSourceAsn, + AttackPropertyIdentifierSourceCountry, + AttackPropertyIdentifierSourceIpAddress, + AttackPropertyIdentifierSourceUserAgent, + AttackPropertyIdentifierWordpressPingbackReflector, + AttackPropertyIdentifierWordpressPingbackSource, + } +} + const ( // AutoRenewEnabled is a AutoRenew enum value AutoRenewEnabled = "ENABLED" @@ -4625,6 +5234,34 @@ const ( AutoRenewDisabled = "DISABLED" ) +// AutoRenew_Values returns all elements of the AutoRenew enum +func AutoRenew_Values() []string { + return []string{ + AutoRenewEnabled, + AutoRenewDisabled, + } +} + +const ( + // ProactiveEngagementStatusEnabled is a ProactiveEngagementStatus enum value + ProactiveEngagementStatusEnabled = "ENABLED" + + // ProactiveEngagementStatusDisabled is a ProactiveEngagementStatus enum value + ProactiveEngagementStatusDisabled = "DISABLED" + + // ProactiveEngagementStatusPending is a ProactiveEngagementStatus enum value + ProactiveEngagementStatusPending = "PENDING" +) + +// ProactiveEngagementStatus_Values returns all elements of the ProactiveEngagementStatus enum +func ProactiveEngagementStatus_Values() []string { + return []string{ + ProactiveEngagementStatusEnabled, + ProactiveEngagementStatusDisabled, + ProactiveEngagementStatusPending, + } +} + const ( // SubResourceTypeIp is a SubResourceType enum value SubResourceTypeIp = "IP" @@ -4633,6 +5270,14 @@ const ( SubResourceTypeUrl = "URL" ) +// SubResourceType_Values returns all elements of the SubResourceType enum +func SubResourceType_Values() []string { + return []string{ + SubResourceTypeIp, + SubResourceTypeUrl, + } +} + const ( // SubscriptionStateActive is a SubscriptionState enum value SubscriptionStateActive = "ACTIVE" @@ -4641,6 +5286,14 @@ const ( SubscriptionStateInactive = "INACTIVE" ) +// SubscriptionState_Values returns all elements of the SubscriptionState enum +func SubscriptionState_Values() []string { + return []string{ + SubscriptionStateActive, + SubscriptionStateInactive, + } +} + const ( // UnitBits is a Unit enum value UnitBits = "BITS" @@ -4654,3 +5307,13 @@ const ( // UnitRequests is a Unit enum value UnitRequests = "REQUESTS" ) + +// Unit_Values returns all elements of the Unit enum +func Unit_Values() []string { + return []string{ + UnitBits, + UnitBytes, + UnitPackets, + UnitRequests, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/shield/errors.go b/vendor/github.com/aws/aws-sdk-go/service/shield/errors.go index a0af389f673..c30b5cc6a7a 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/shield/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/shield/errors.go @@ -18,8 +18,8 @@ const ( // ErrCodeAccessDeniedForDependencyException for service response error code // "AccessDeniedForDependencyException". // - // In order to grant the necessary access to the DDoS Response Team, the user - // submitting the request must have the iam:PassRole permission. This error + // In order to grant the necessary access to the DDoS Response Team (DRT), the + // user submitting the request must have the iam:PassRole permission. This error // indicates the user did not have the appropriate permissions. For more information, // see Granting a User Permissions to Pass a Role to an AWS Service (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html). ErrCodeAccessDeniedForDependencyException = "AccessDeniedForDependencyException" @@ -86,8 +86,8 @@ const ( // ErrCodeOptimisticLockException for service response error code // "OptimisticLockException". // - // Exception that indicates that the protection state has been modified by another - // client. You can retry the request. + // Exception that indicates that the resource state has been modified by another + // client. Retrieve the resource and then retry your request. ErrCodeOptimisticLockException = "OptimisticLockException" // ErrCodeResourceAlreadyExistsException for service response error code 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 780b1884323..e78534596b5 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 @@ -341,22 +341,33 @@ func (c *SNS) CreatePlatformApplicationRequest(input *CreatePlatformApplicationI // CreatePlatformApplication API operation for Amazon Simple Notification Service. // // Creates a platform application object for one of the supported push notification -// services, such as APNS and FCM, to which devices and mobile apps may register. -// You must specify PlatformPrincipal and PlatformCredential attributes when -// using the CreatePlatformApplication action. The PlatformPrincipal is received -// from the notification service. For APNS/APNS_SANDBOX, PlatformPrincipal is -// "SSL certificate". For FCM, PlatformPrincipal is not applicable. For ADM, -// PlatformPrincipal is "client id". The PlatformCredential is also received -// from the notification service. For WNS, PlatformPrincipal is "Package Security -// Identifier". For MPNS, PlatformPrincipal is "TLS certificate". For Baidu, -// PlatformPrincipal is "API key". -// -// For APNS/APNS_SANDBOX, PlatformCredential is "private key". For FCM, PlatformCredential -// is "API key". For ADM, PlatformCredential is "client secret". For WNS, PlatformCredential -// is "secret key". For MPNS, PlatformCredential is "private key". For Baidu, -// PlatformCredential is "secret key". The PlatformApplicationArn that is returned -// when using CreatePlatformApplication is then used as an attribute for the -// CreatePlatformEndpoint action. +// services, such as APNS and GCM (Firebase Cloud Messaging), to which devices +// and mobile apps may register. You must specify PlatformPrincipal and PlatformCredential +// attributes when using the CreatePlatformApplication action. +// +// PlatformPrincipal and PlatformCredential are received from the notification +// service. +// +// * For ADM, PlatformPrincipal is client id and PlatformCredential is client +// secret. +// +// * For Baidu, PlatformPrincipal is API key and PlatformCredential is secret +// key. +// +// * For APNS and APNS_SANDBOX, PlatformPrincipal is SSL certificate and +// PlatformCredential is private key. +// +// * For GCM (Firebase Cloud Messaging), there is no PlatformPrincipal and +// the PlatformCredential is API key. +// +// * For MPNS, PlatformPrincipal is TLS certificate and PlatformCredential +// is private key. +// +// * For WNS, PlatformPrincipal is Package Security Identifier and PlatformCredential +// is secret key. +// +// You can use the returned PlatformApplicationArn as an attribute for the CreatePlatformEndpoint +// action. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -442,11 +453,10 @@ func (c *SNS) CreatePlatformEndpointRequest(input *CreatePlatformEndpointInput) // CreatePlatformEndpoint API operation for Amazon Simple Notification Service. // // Creates an endpoint for a device and mobile app on one of the supported push -// notification services, such as FCM and APNS. CreatePlatformEndpoint requires -// the PlatformApplicationArn that is returned from CreatePlatformApplication. -// The EndpointArn that is returned when using CreatePlatformEndpoint can then -// be used by the Publish action to send a message to a mobile app or by the -// Subscribe action for subscription to a topic. The CreatePlatformEndpoint +// notification services, such as GCM (Firebase Cloud Messaging) and APNS. CreatePlatformEndpoint +// requires the PlatformApplicationArn that is returned from CreatePlatformApplication. +// You can use the returned EndpointArn to send a message to a mobile app or +// by the Subscribe action for subscription to a topic. The CreatePlatformEndpoint // action is idempotent, so if the requester already owns an endpoint with the // same device token and attributes, that endpoint's ARN is returned without // creating a new endpoint. For more information, see Using Amazon SNS Mobile @@ -746,8 +756,8 @@ func (c *SNS) DeletePlatformApplicationRequest(input *DeletePlatformApplicationI // DeletePlatformApplication API operation for Amazon Simple Notification Service. // // Deletes a platform application object for one of the supported push notification -// services, such as APNS and FCM. For more information, see Using Amazon SNS -// Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). +// services, such as APNS and GCM (Firebase Cloud Messaging). For more information, +// see Using Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.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 @@ -937,8 +947,8 @@ func (c *SNS) GetEndpointAttributesRequest(input *GetEndpointAttributesInput) (r // GetEndpointAttributes API operation for Amazon Simple Notification Service. // // Retrieves the endpoint attributes for a device on one of the supported push -// notification services, such as FCM and APNS. For more information, see Using -// Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). +// notification services, such as GCM (Firebase Cloud Messaging) and APNS. For +// more information, see Using Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.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 @@ -1027,8 +1037,8 @@ func (c *SNS) GetPlatformApplicationAttributesRequest(input *GetPlatformApplicat // GetPlatformApplicationAttributes API operation for Amazon Simple Notification Service. // // Retrieves the attributes of the platform application object for the supported -// push notification services, such as APNS and FCM. For more information, see -// Using Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). +// push notification services, such as APNS and GCM (Firebase Cloud Messaging). +// For more information, see Using Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.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 @@ -1395,12 +1405,13 @@ func (c *SNS) ListEndpointsByPlatformApplicationRequest(input *ListEndpointsByPl // ListEndpointsByPlatformApplication API operation for Amazon Simple Notification Service. // // Lists the endpoints and endpoint attributes for devices in a supported push -// notification service, such as FCM and APNS. The results for ListEndpointsByPlatformApplication -// are paginated and return a limited list of endpoints, up to 100. If additional -// records are available after the first page results, then a NextToken string -// will be returned. To receive the next page, you call ListEndpointsByPlatformApplication -// again using the NextToken string received from the previous call. When there -// are no more records to return, NextToken will be null. For more information, +// notification service, such as GCM (Firebase Cloud Messaging) and APNS. The +// results for ListEndpointsByPlatformApplication are paginated and return a +// limited list of endpoints, up to 100. If additional records are available +// after the first page results, then a NextToken string will be returned. To +// receive the next page, you call ListEndpointsByPlatformApplication again +// using the NextToken string received from the previous call. When there are +// no more records to return, NextToken will be null. For more information, // see Using Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). // // This action is throttled at 30 transactions per second (TPS). @@ -1647,13 +1658,13 @@ func (c *SNS) ListPlatformApplicationsRequest(input *ListPlatformApplicationsInp // ListPlatformApplications API operation for Amazon Simple Notification Service. // // Lists the platform application objects for the supported push notification -// services, such as APNS and FCM. The results for ListPlatformApplications -// are paginated and return a limited list of applications, up to 100. If additional -// records are available after the first page results, then a NextToken string -// will be returned. To receive the next page, you call ListPlatformApplications -// using the NextToken string received from the previous call. When there are -// no more records to return, NextToken will be null. For more information, -// see Using Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). +// services, such as APNS and GCM (Firebase Cloud Messaging). The results for +// ListPlatformApplications are paginated and return a limited list of applications, +// up to 100. If additional records are available after the first page results, +// then a NextToken string will be returned. To receive the next page, you call +// ListPlatformApplications using the NextToken string received from the previous +// call. When there are no more records to return, NextToken will be null. For +// more information, see Using Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). // // This action is throttled at 15 transactions per second (TPS). // @@ -2426,8 +2437,9 @@ func (c *SNS) PublishRequest(input *PublishInput) (req *request.Request, output // Publish API operation for Amazon Simple Notification Service. // -// Sends a message to an Amazon SNS topic or sends a text message (SMS message) -// directly to a phone number. +// Sends a message to an Amazon SNS topic, a text message (SMS message) directly +// to a phone number, or a message to a mobile platform endpoint (when you specify +// the TargetArn). // // If you send a message to a topic, Amazon SNS delivers the message to each // endpoint that is subscribed to the topic. The format of the message depends @@ -2444,6 +2456,8 @@ func (c *SNS) PublishRequest(input *PublishInput) (req *request.Request, output // For more information about formatting messages, see Send Custom Platform-Specific // Payloads in Messages to Mobile Devices (https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-custommessage.html). // +// You can publish messages only to topics and endpoints in the same AWS Region. +// // Returns awserr.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. @@ -2660,8 +2674,8 @@ func (c *SNS) SetEndpointAttributesRequest(input *SetEndpointAttributesInput) (r // SetEndpointAttributes API operation for Amazon Simple Notification Service. // // Sets the attributes for an endpoint for a device on one of the supported -// push notification services, such as FCM and APNS. For more information, see -// Using Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). +// push notification services, such as GCM (Firebase Cloud Messaging) and APNS. +// For more information, see Using Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.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 @@ -2751,8 +2765,8 @@ func (c *SNS) SetPlatformApplicationAttributesRequest(input *SetPlatformApplicat // SetPlatformApplicationAttributes API operation for Amazon Simple Notification Service. // // Sets the attributes of the platform application object for the supported -// push notification services, such as APNS and FCM. For more information, see -// Using Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). +// push notification services, such as APNS and GCM (Firebase Cloud Messaging). +// For more information, see Using Amazon SNS Mobile Push Notifications (https://docs.aws.amazon.com/sns/latest/dg/SNSMobilePush.html). // For information on configuring attributes for message delivery status, see // Using Amazon SNS Application Attributes for Message Delivery Status (https://docs.aws.amazon.com/sns/latest/dg/sns-msg-status.html). // @@ -3126,10 +3140,12 @@ func (c *SNS) SubscribeRequest(input *SubscribeInput) (req *request.Request, out // Subscribe API operation for Amazon Simple Notification Service. // -// Prepares to subscribe an endpoint by sending the endpoint a confirmation -// message. To actually create a subscription, the endpoint owner must call -// the ConfirmSubscription action with the token from the confirmation message. -// Confirmation tokens are valid for three days. +// Subscribes an endpoint to an Amazon SNS topic. If the endpoint type is HTTP/S +// or email, or if the endpoint and the topic are not in the same AWS account, +// the endpoint owner must the ConfirmSubscription action to confirm the subscription. +// +// You call the ConfirmSubscription action with the token from the subscription +// response. Confirmation tokens are valid for three days. // // This action is throttled at 100 transactions per second (TPS). // @@ -3782,7 +3798,7 @@ type CreatePlatformApplicationInput struct { Name *string `type:"string" required:"true"` // The following platforms are supported: ADM (Amazon Device Messaging), APNS - // (Apple Push Notification Service), APNS_SANDBOX, and FCM (Firebase Cloud + // (Apple Push Notification Service), APNS_SANDBOX, and GCM (Firebase Cloud // Messaging). // // Platform is a required field @@ -3880,8 +3896,9 @@ type CreatePlatformEndpointInput struct { // Unique identifier created by the notification service for an app on a device. // The specific name for Token will vary, depending on which notification service // is being used. For example, when using APNS as the notification service, - // you need the device token. Alternatively, when using FCM or ADM, the device - // token equivalent is called the registration ID. + // you need the device token. Alternatively, when using GCM (Firebase Cloud + // Messaging) or ADM, the device token equivalent is called the registration + // ID. // // Token is a required field Token *string `type:"string" required:"true"` @@ -4531,6 +4548,8 @@ type GetSubscriptionAttributesOutput struct { // account system defaults. // // * FilterPolicy – The filter policy JSON that is assigned to the subscription. + // For more information, see Amazon SNS Message Filtering (https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html) + // in the Amazon SNS Developer Guide. // // * Owner – The AWS account ID of the subscription's owner. // @@ -4636,7 +4655,7 @@ type GetTopicAttributesOutput struct { // // * TopicArn – The topic's ARN. // - // * EffectiveDeliveryPolicy – Yhe JSON serialization of the effective + // * EffectiveDeliveryPolicy – The JSON serialization of the effective // delivery policy, taking system defaults into account. // // The following attribute applies only to server-side-encryption (https://docs.aws.amazon.com/sns/latest/dg/sns-server-side-encryption.html): @@ -5641,27 +5660,27 @@ type SetPlatformApplicationAttributesInput struct { // the following: // // * PlatformCredential – The credential received from the notification - // service. For APNS/APNS_SANDBOX, PlatformCredential is private key. For - // FCM, PlatformCredential is "API key". For ADM, PlatformCredential is "client - // secret". + // service. For APNS and APNS_SANDBOX, PlatformCredential is private key. + // For GCM (Firebase Cloud Messaging), PlatformCredential is API key. For + // ADM, PlatformCredential is client secret. // // * PlatformPrincipal – The principal received from the notification service. - // For APNS/APNS_SANDBOX, PlatformPrincipal is SSL certificate. For FCM, - // PlatformPrincipal is not applicable. For ADM, PlatformPrincipal is "client - // id". + // For APNS and APNS_SANDBOX, PlatformPrincipal is SSL certificate. For GCM + // (Firebase Cloud Messaging), there is no PlatformPrincipal. For ADM, PlatformPrincipal + // is client id. // // * EventEndpointCreated – Topic ARN to which EndpointCreated event notifications - // should be sent. + // are sent. // // * EventEndpointDeleted – Topic ARN to which EndpointDeleted event notifications - // should be sent. + // are sent. // // * EventEndpointUpdated – Topic ARN to which EndpointUpdate event notifications - // should be sent. + // are sent. // // * EventDeliveryFailure – Topic ARN to which DeliveryFailure event notifications - // should be sent upon Direct Publish delivery failure (permanent) to one - // of the application's endpoints. + // are sent upon Direct Publish delivery failure (permanent) to one of the + // application's endpoints. // // * SuccessFeedbackRoleArn – IAM role ARN used to give Amazon SNS write // access to use CloudWatch Logs on your behalf. @@ -6083,9 +6102,11 @@ type SubscribeInput struct { // The endpoint that you want to receive notifications. Endpoints vary by protocol: // - // * For the http protocol, the endpoint is an URL beginning with http:// + // * For the http protocol, the (public) endpoint is a URL beginning with + // http:// // - // * For the https protocol, the endpoint is a URL beginning with https:// + // * For the https protocol, the (public) endpoint is a URL beginning with + // https:// // // * For the email protocol, the endpoint is an email address // @@ -6128,17 +6149,13 @@ type SubscribeInput struct { // Sets whether the response from the Subscribe request includes the subscription // ARN, even if the subscription is not yet confirmed. // - // * If you have the subscription ARN returned, the response includes the - // ARN in all cases, even if the subscription is not yet confirmed. - // - // * If you don't have the subscription ARN returned, in addition to the - // ARN for confirmed subscriptions, the response also includes the pending - // subscription ARN value for subscriptions that aren't yet confirmed. A - // subscription becomes confirmed when the subscriber calls the ConfirmSubscription + // * If you set this parameter to true, the response includes the ARN in + // all cases, even if the subscription is not yet confirmed. In addition + // to the ARN for confirmed subscriptions, the response also includes the + // pending subscription ARN value for subscriptions that aren't yet confirmed. + // A subscription becomes confirmed when the subscriber calls the ConfirmSubscription // action with a confirmation token. // - // If you set this parameter to true, . - // // The default value is false. ReturnSubscriptionArn *bool `type:"boolean"` 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 bc087b5b62e..06e05ee2a13 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 @@ -81,9 +81,9 @@ func (c *SQS) AddPermissionRequest(input *AddPermissionInput) (req *request.Requ // param.n notation. Values of n are integers starting from 1. For example, // a parameter list with two elements looks like this: // -// &Attribute.1=first +// &AttributeName.1=first // -// &Attribute.2=second +// &AttributeName.2=second // // Cross-account permissions don't apply to this action. For more information, // see Grant Cross-Account Permissions to a Role and a User Name (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-customer-managed-policy-examples.html#grant-cross-account-permissions-to-role-and-user-name) @@ -316,9 +316,9 @@ func (c *SQS) ChangeMessageVisibilityBatchRequest(input *ChangeMessageVisibility // param.n notation. Values of n are integers starting from 1. For example, // a parameter list with two elements looks like this: // -// &Attribute.1=first +// &AttributeName.1=first // -// &Attribute.2=second +// &AttributeName.2=second // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -407,7 +407,7 @@ func (c *SQS) CreateQueueRequest(input *CreateQueueInput) (req *request.Request, // CreateQueue API operation for Amazon Simple Queue Service. // // Creates a new standard or FIFO queue. You can pass one or more attributes -// in the request. Keep the following caveats in mind: +// in the request. Keep the following in mind: // // * If you don't specify the FifoQueue attribute, Amazon SQS creates a standard // queue. You can't change the queue type after you create it and you can't @@ -427,6 +427,9 @@ func (c *SQS) CreateQueueRequest(input *CreateQueueInput) (req *request.Request, // to the limits related to queues (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/limits-queues.html) // and is unique within the scope of your queues. // +// After you create a queue, you must wait at least one second after the queue +// is created to be able to use the queue. +// // To get the queue URL, use the GetQueueUrl action. GetQueueUrl requires only // the QueueName parameter. be aware of existing queue names: // @@ -441,9 +444,9 @@ func (c *SQS) CreateQueueRequest(input *CreateQueueInput) (req *request.Request, // param.n notation. Values of n are integers starting from 1. For example, // a parameter list with two elements looks like this: // -// &Attribute.1=first +// &AttributeName.1=first // -// &Attribute.2=second +// &AttributeName.2=second // // Cross-account permissions don't apply to this action. For more information, // see Grant Cross-Account Permissions to a Role and a User Name (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-customer-managed-policy-examples.html#grant-cross-account-permissions-to-role-and-user-name) @@ -646,9 +649,9 @@ func (c *SQS) DeleteMessageBatchRequest(input *DeleteMessageBatchInput) (req *re // param.n notation. Values of n are integers starting from 1. For example, // a parameter list with two elements looks like this: // -// &Attribute.1=first +// &AttributeName.1=first // -// &Attribute.2=second +// &AttributeName.2=second // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -738,7 +741,6 @@ func (c *SQS) DeleteQueueRequest(input *DeleteQueueInput) (req *request.Request, // DeleteQueue API operation for Amazon Simple Queue Service. // // Deletes the queue specified by the QueueUrl, regardless of the queue's contents. -// If the specified queue doesn't exist, Amazon SQS returns a successful response. // // Be careful with the DeleteQueue action: When you delete a queue, any messages // in the queue are no longer available. @@ -832,14 +834,6 @@ func (c *SQS) GetQueueAttributesRequest(input *GetQueueAttributesInput) (req *re // To determine whether a queue is FIFO (https://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: -// -// &Attribute.1=first -// -// &Attribute.2=second -// // Returns awserr.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. @@ -990,6 +984,12 @@ func (c *SQS) ListDeadLetterSourceQueuesRequest(input *ListDeadLetterSourceQueue Name: opListDeadLetterSourceQueues, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -1043,6 +1043,58 @@ func (c *SQS) ListDeadLetterSourceQueuesWithContext(ctx aws.Context, input *List return out, req.Send() } +// ListDeadLetterSourceQueuesPages iterates over the pages of a ListDeadLetterSourceQueues operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListDeadLetterSourceQueues 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 ListDeadLetterSourceQueues operation. +// pageNum := 0 +// err := client.ListDeadLetterSourceQueuesPages(params, +// func(page *sqs.ListDeadLetterSourceQueuesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SQS) ListDeadLetterSourceQueuesPages(input *ListDeadLetterSourceQueuesInput, fn func(*ListDeadLetterSourceQueuesOutput, bool) bool) error { + return c.ListDeadLetterSourceQueuesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDeadLetterSourceQueuesPagesWithContext same as ListDeadLetterSourceQueuesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListDeadLetterSourceQueuesPagesWithContext(ctx aws.Context, input *ListDeadLetterSourceQueuesInput, fn func(*ListDeadLetterSourceQueuesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDeadLetterSourceQueuesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDeadLetterSourceQueuesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListDeadLetterSourceQueuesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListQueueTags = "ListQueueTags" // ListQueueTagsRequest generates a "aws/request.Request" representing the @@ -1154,6 +1206,12 @@ func (c *SQS) ListQueuesRequest(input *ListQueuesInput) (req *request.Request, o Name: opListQueues, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -1203,6 +1261,58 @@ func (c *SQS) ListQueuesWithContext(ctx aws.Context, input *ListQueuesInput, opt return out, req.Send() } +// ListQueuesPages iterates over the pages of a ListQueues operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListQueues 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 ListQueues operation. +// pageNum := 0 +// err := client.ListQueuesPages(params, +// func(page *sqs.ListQueuesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SQS) ListQueuesPages(input *ListQueuesInput, fn func(*ListQueuesOutput, bool) bool) error { + return c.ListQueuesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListQueuesPagesWithContext same as ListQueuesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the 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) ListQueuesPagesWithContext(ctx aws.Context, input *ListQueuesInput, fn func(*ListQueuesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListQueuesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListQueuesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListQueuesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opPurgeQueue = "PurgeQueue" // PurgeQueueRequest generates a "aws/request.Request" representing the @@ -1676,9 +1786,9 @@ func (c *SQS) SendMessageBatchRequest(input *SendMessageBatchInput) (req *reques // param.n notation. Values of n are integers starting from 1. For example, // a parameter list with two elements looks like this: // -// &Attribute.1=first +// &AttributeName.1=first // -// &Attribute.2=second +// &AttributeName.2=second // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2129,7 +2239,7 @@ type BatchResultErrorEntry struct { // A message explaining why the action failed on this entry. Message *string `type:"string"` - // Specifies whether the error happened due to the producer. + // Specifies whether the error happened due to the caller of the batch API action. // // SenderFault is a required field SenderFault *bool `type:"boolean" required:"true"` @@ -2290,7 +2400,10 @@ type ChangeMessageVisibilityBatchRequestEntry struct { // An identifier for this particular receipt handle used to communicate the // result. // - // The Ids of a batch request need to be unique within a request + // The Ids of a batch request need to be unique within a request. + // + // This identifier can have up to 80 characters. The following characters are + // accepted: alphanumeric characters, hyphens(-), and underscores (_). // // Id is a required field Id *string `type:"string" required:"true"` @@ -2466,41 +2579,41 @@ type CreateQueueInput struct { // The following lists the names, descriptions, and values of the special request // parameters that the CreateQueue action uses: // - // * DelaySeconds - The length of time, in seconds, for which the delivery + // * 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). Default: 0. // - // * MaximumMessageSize - The limit of how many bytes a message can contain + // * 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). Default: 262,144 (256 KiB). // - // * 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). Default: 345,600 (4 days). + // * 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). Default: 345,600 (4 days). // - // * Policy - The queue's policy. A valid AWS policy. For more information + // * Policy – The queue's policy. A valid AWS policy. For more information // about policy structure, see Overview of AWS IAM Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html) // in the Amazon IAM User Guide. // - // * ReceiveMessageWaitTimeSeconds - The length of time, in seconds, for + // * 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). Default: 0. // - // * RedrivePolicy - The string that includes the parameters for the dead-letter - // queue functionality of the source queue. For more information about the - // redrive policy and dead-letter queues, see Using Amazon SQS Dead-Letter - // Queues (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) + // * RedrivePolicy – The string that includes the parameters for the dead-letter + // queue functionality of the source queue as a JSON object. For more information + // about the redrive policy and dead-letter queues, see Using Amazon SQS + // Dead-Letter Queues (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) // in the Amazon Simple Queue Service Developer Guide. deadLetterTargetArn - // - The Amazon Resource Name (ARN) of the dead-letter queue to which Amazon + // – The Amazon Resource Name (ARN) of the dead-letter queue to which Amazon // SQS moves messages after the value of maxReceiveCount is exceeded. maxReceiveCount - // - The number of times a message is delivered to the source queue before + // – The number of times a message is delivered to the source queue before // being moved to the dead-letter queue. When the ReceiveCount for a message // exceeds the maxReceiveCount for a queue, Amazon SQS moves the message // to the dead-letter-queue. The dead-letter queue of a FIFO queue must also // be a FIFO queue. Similarly, the dead-letter queue of a standard queue // must also be a standard queue. // - // * VisibilityTimeout - The visibility timeout for the queue, in seconds. + // * VisibilityTimeout – The visibility timeout for the queue, in seconds. // Valid values: An integer from 0 to 43,200 (12 hours). Default: 30. For // more information about the visibility timeout, see Visibility Timeout // (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html) @@ -2508,15 +2621,15 @@ type CreateQueueInput struct { // // The following attributes apply only to server-side-encryption (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html): // - // * KmsMasterKeyId - The ID of an AWS-managed customer master key (CMK) + // * KmsMasterKeyId – The ID of an AWS-managed customer master key (CMK) // for Amazon SQS or a custom CMK. For more information, see Key Terms (https://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/MyAlias . For more // examples, see KeyId (https://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 (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys) + // * KmsDataKeyReusePeriodSeconds – The length of time, in seconds, for + // which Amazon SQS can reuse a data key (https://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). Default: 300 (5 minutes). A shorter time period provides better @@ -2526,15 +2639,15 @@ type CreateQueueInput struct { // // The following attributes apply only to FIFO (first-in-first-out) queues (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html): // - // * FifoQueue - Designates a queue as FIFO. Valid values: true, false. If - // you don't specify the FifoQueue attribute, Amazon SQS creates a standard + // * FifoQueue – Designates a queue as FIFO. Valid values: true, false. + // If you don't specify the FifoQueue attribute, Amazon SQS creates a standard // queue. 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 (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-understanding-logic) // in the Amazon Simple Queue Service Developer Guide. // - // * ContentBasedDeduplication - Enables content-based deduplication. Valid + // * ContentBasedDeduplication – Enables content-based deduplication. Valid // values: true, false. For more information, see Exactly-Once Processing // (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing) // in the Amazon Simple Queue Service Developer Guide. Every message must @@ -2771,7 +2884,10 @@ type DeleteMessageBatchRequestEntry struct { // An identifier for this particular receipt handle. This is used to communicate // the result. // - // The Ids of a batch request need to be unique within a request + // The Ids of a batch request need to be unique within a request. + // + // This identifier can have up to 80 characters. The following characters are + // accepted: alphanumeric characters, hyphens(-), and underscores (_). // // Id is a required field Id *string `type:"string" required:"true"` @@ -2979,79 +3095,84 @@ type GetQueueAttributesInput struct { // // The following attributes are supported: // - // * All - Returns all values. + // The ApproximateNumberOfMessagesDelayed, ApproximateNumberOfMessagesNotVisible, + // and ApproximateNumberOfMessagesVisible metrics may not achieve consistency + // until at least 1 minute after the producers stop sending messages. This period + // is required for the queue metadata to reach eventual consistency. // - // * ApproximateNumberOfMessages - Returns the approximate number of messages + // * All – Returns all values. + // + // * ApproximateNumberOfMessages – Returns the approximate number of messages // available for retrieval from the queue. // - // * ApproximateNumberOfMessagesDelayed - Returns the approximate number + // * ApproximateNumberOfMessagesDelayed – Returns the approximate number // of messages in the queue that are delayed and not available for reading // immediately. This can happen when the queue is configured as a delay queue // or when a message has been sent with a delay parameter. // - // * ApproximateNumberOfMessagesNotVisible - Returns the approximate number + // * ApproximateNumberOfMessagesNotVisible – Returns the approximate number // of messages that are in flight. Messages are considered to be in flight // if they have been sent to a client but have not yet been deleted or have // not yet reached the end of their visibility window. // - // * CreatedTimestamp - Returns the time when the queue was created in seconds - // (epoch time (http://en.wikipedia.org/wiki/Unix_time)). + // * CreatedTimestamp – Returns the time when the queue was created in + // seconds (epoch time (http://en.wikipedia.org/wiki/Unix_time)). // - // * DelaySeconds - Returns the default delay on the queue in seconds. + // * DelaySeconds – Returns the default delay on the queue in seconds. // - // * LastModifiedTimestamp - Returns the time when the queue was last changed + // * LastModifiedTimestamp – Returns the time when the queue was last changed // in seconds (epoch time (http://en.wikipedia.org/wiki/Unix_time)). // - // * MaximumMessageSize - Returns the limit of how many bytes a message can - // contain before Amazon SQS rejects it. + // * MaximumMessageSize – Returns the limit of how many bytes a message + // can contain before Amazon SQS rejects it. // - // * MessageRetentionPeriod - Returns the length of time, in seconds, for + // * MessageRetentionPeriod – Returns the length of time, in seconds, for // which Amazon SQS retains a message. // - // * Policy - Returns the policy of the queue. + // * Policy – Returns the policy of the queue. // - // * QueueArn - Returns the Amazon resource name (ARN) of the queue. + // * QueueArn – Returns the Amazon resource name (ARN) of the queue. // - // * ReceiveMessageWaitTimeSeconds - Returns the length of time, in seconds, + // * ReceiveMessageWaitTimeSeconds – Returns the length of time, in seconds, // for which the ReceiveMessage action waits for a message to arrive. // - // * RedrivePolicy - Returns the string that includes the parameters for - // dead-letter queue functionality of the source queue. For more information + // * RedrivePolicy – The string that includes the parameters for the dead-letter + // queue functionality of the source queue as a JSON object. For more information // about the redrive policy and dead-letter queues, see Using Amazon SQS // Dead-Letter Queues (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) // in the Amazon Simple Queue Service Developer Guide. deadLetterTargetArn - // - The Amazon Resource Name (ARN) of the dead-letter queue to which Amazon + // – The Amazon Resource Name (ARN) of the dead-letter queue to which Amazon // SQS moves messages after the value of maxReceiveCount is exceeded. maxReceiveCount - // - The number of times a message is delivered to the source queue before + // – The number of times a message is delivered to the source queue before // being moved to the dead-letter queue. When the ReceiveCount for a message // exceeds the maxReceiveCount for a queue, Amazon SQS moves the message // to the dead-letter-queue. // - // * VisibilityTimeout - Returns the visibility timeout for the queue. For - // more information about the visibility timeout, see Visibility Timeout + // * VisibilityTimeout – Returns the visibility timeout for the queue. + // For more information about the visibility timeout, see Visibility Timeout // (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html) // in the Amazon Simple Queue Service Developer Guide. // // The following attributes apply only to server-side-encryption (https://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 - // (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-sse-key-terms). + // * 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 (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html#sqs-sse-key-terms). // - // * KmsDataKeyReusePeriodSeconds - Returns the length of time, in seconds, + // * 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. For more information, see How Does the Data // Key Reuse Period Work? (https://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 (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html): // - // * FifoQueue - Returns whether the queue is FIFO. For more information, + // * FifoQueue – Returns whether the queue is FIFO. For more information, // see FIFO Queue Logic (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-understanding-logic) // in the Amazon Simple Queue Service Developer Guide. To determine whether // a queue is FIFO (https://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 + // * ContentBasedDeduplication – Returns whether content-based deduplication // is enabled for the queue. For more information, see Exactly-Once Processing // (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing) // in the Amazon Simple Queue Service Developer Guide. @@ -3202,6 +3323,12 @@ func (s *GetQueueUrlOutput) SetQueueUrl(v string) *GetQueueUrlOutput { type ListDeadLetterSourceQueuesInput struct { _ struct{} `type:"structure"` + // Maximum number of results to include in the response. + MaxResults *int64 `type:"integer"` + + // Pagination token to request the next set of results. + NextToken *string `type:"string"` + // The URL of a dead-letter queue. // // Queue URLs and names are case-sensitive. @@ -3233,6 +3360,18 @@ func (s *ListDeadLetterSourceQueuesInput) Validate() error { return nil } +// SetMaxResults sets the MaxResults field's value. +func (s *ListDeadLetterSourceQueuesInput) SetMaxResults(v int64) *ListDeadLetterSourceQueuesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListDeadLetterSourceQueuesInput) SetNextToken(v string) *ListDeadLetterSourceQueuesInput { + s.NextToken = &v + return s +} + // SetQueueUrl sets the QueueUrl field's value. func (s *ListDeadLetterSourceQueuesInput) SetQueueUrl(v string) *ListDeadLetterSourceQueuesInput { s.QueueUrl = &v @@ -3243,6 +3382,9 @@ func (s *ListDeadLetterSourceQueuesInput) SetQueueUrl(v string) *ListDeadLetterS type ListDeadLetterSourceQueuesOutput struct { _ struct{} `type:"structure"` + // Pagination token to include in the next request. + NextToken *string `type:"string"` + // A list of source queue URLs that have the RedrivePolicy queue attribute configured // with a dead-letter queue. // @@ -3260,6 +3402,12 @@ func (s ListDeadLetterSourceQueuesOutput) GoString() string { return s.String() } +// SetNextToken sets the NextToken field's value. +func (s *ListDeadLetterSourceQueuesOutput) SetNextToken(v string) *ListDeadLetterSourceQueuesOutput { + s.NextToken = &v + return s +} + // SetQueueUrls sets the QueueUrls field's value. func (s *ListDeadLetterSourceQueuesOutput) SetQueueUrls(v []*string) *ListDeadLetterSourceQueuesOutput { s.QueueUrls = v @@ -3330,6 +3478,12 @@ func (s *ListQueueTagsOutput) SetTags(v map[string]*string) *ListQueueTagsOutput type ListQueuesInput struct { _ struct{} `type:"structure"` + // Maximum number of results to include in the response. + MaxResults *int64 `type:"integer"` + + // Pagination token to request the next set of results. + NextToken *string `type:"string"` + // A string to use for filtering the list results. Only those queues whose name // begins with the specified string are returned. // @@ -3347,6 +3501,18 @@ func (s ListQueuesInput) GoString() string { return s.String() } +// SetMaxResults sets the MaxResults field's value. +func (s *ListQueuesInput) SetMaxResults(v int64) *ListQueuesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListQueuesInput) SetNextToken(v string) *ListQueuesInput { + s.NextToken = &v + return s +} + // SetQueueNamePrefix sets the QueueNamePrefix field's value. func (s *ListQueuesInput) SetQueueNamePrefix(v string) *ListQueuesInput { s.QueueNamePrefix = &v @@ -3357,7 +3523,11 @@ func (s *ListQueuesInput) SetQueueNamePrefix(v string) *ListQueuesInput { type ListQueuesOutput struct { _ struct{} `type:"structure"` - // A list of queue URLs, up to 1,000 entries. + // Pagination token to include in the next request. + NextToken *string `type:"string"` + + // A list of queue URLs, up to 1,000 entries, or the value of MaxResults that + // you sent in the request. QueueUrls []*string `locationNameList:"QueueUrl" type:"list" flattened:"true"` } @@ -3371,6 +3541,12 @@ func (s ListQueuesOutput) GoString() string { return s.String() } +// SetNextToken sets the NextToken field's value. +func (s *ListQueuesOutput) SetNextToken(v string) *ListQueuesOutput { + s.NextToken = &v + return s +} + // SetQueueUrls sets the QueueUrls field's value. func (s *ListQueuesOutput) SetQueueUrls(v []*string) *ListQueuesOutput { s.QueueUrls = v @@ -3720,31 +3896,31 @@ type ReceiveMessageInput struct { // A list of attributes that need to be returned along with each message. These // attributes include: // - // * All - Returns all values. + // * All – Returns all values. // - // * ApproximateFirstReceiveTimestamp - Returns the time the message was + // * ApproximateFirstReceiveTimestamp – Returns the time the message was // first received from the queue (epoch time (http://en.wikipedia.org/wiki/Unix_time) // in milliseconds). // - // * ApproximateReceiveCount - Returns the number of times a message has - // been received from the queue but not deleted. + // * ApproximateReceiveCount – Returns the number of times a message has + // been received across all queues but not deleted. // - // * AWSTraceHeader - Returns the AWS X-Ray trace header string. + // * AWSTraceHeader – Returns the AWS X-Ray trace header string. // // * SenderId For an IAM user, returns the IAM user ID, for example ABCDEFGHI1JKLMNOPQ23R. // For an IAM role, returns the IAM role ID, for example ABCDE1F2GH3I4JK5LMNOP:i-a123b456. // - // * SentTimestamp - Returns the time the message was sent to the queue (epoch - // time (http://en.wikipedia.org/wiki/Unix_time) in milliseconds). + // * SentTimestamp – Returns the time the message was sent to the queue + // (epoch time (http://en.wikipedia.org/wiki/Unix_time) in milliseconds). // - // * MessageDeduplicationId - Returns the value provided by the producer + // * MessageDeduplicationId – Returns the value provided by the producer // that calls the SendMessage action. // - // * MessageGroupId - Returns the value provided by the producer that calls + // * MessageGroupId – Returns the value provided by the producer that calls // the SendMessage action. Messages with the same MessageGroupId are returned // in sequence. // - // * SequenceNumber - Returns the value provided by Amazon SQS. + // * SequenceNumber – Returns the value provided by Amazon SQS. AttributeNames []*string `locationNameList:"AttributeName" type:"list" flattened:"true"` // The maximum number of messages to return. Amazon SQS never returns more messages @@ -3785,9 +3961,9 @@ type ReceiveMessageInput struct { // // The token used for deduplication of ReceiveMessage calls. If a networking // issue occurs after a ReceiveMessage action, and instead of a response you - // receive a generic error, you can retry the same action with an identical - // ReceiveRequestAttemptId to retrieve the same set of messages, even if their - // visibility timeout has not yet expired. + // receive a generic error, it is possible to retry the same action with an + // identical ReceiveRequestAttemptId to retrieve the same set of messages, even + // if their visibility timeout has not yet expired. // // * You can use ReceiveRequestAttemptId only for 5 minutes after a ReceiveMessage // action. @@ -3798,7 +3974,7 @@ type ReceiveMessageInput struct { // * If a caller of the ReceiveMessage action doesn't provide a ReceiveRequestAttemptId, // Amazon SQS generates a ReceiveRequestAttemptId. // - // * You can retry the ReceiveMessage action with the same ReceiveRequestAttemptId + // * It is possible to retry the ReceiveMessage action with the same ReceiveRequestAttemptId // if none of the messages have been modified (deleted or had their visibility // changes). // @@ -3825,7 +4001,7 @@ type ReceiveMessageInput struct { // no retries work until the original visibility timeout expires. As a result, // delays might occur but the messages in the queue remain in a strict order. // - // The length of ReceiveRequestAttemptId is 128 characters. ReceiveRequestAttemptId + // The maximum length of ReceiveRequestAttemptId is 128 characters. ReceiveRequestAttemptId // can contain alphanumeric characters (a-z, A-Z, 0-9) and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~). // // For best practices of using ReceiveRequestAttemptId, see Using the ReceiveRequestAttemptId @@ -3841,6 +4017,13 @@ type ReceiveMessageInput struct { // in the queue before returning. If a message is available, the call returns // sooner than WaitTimeSeconds. If no messages are available and the wait time // expires, the call returns successfully with an empty list of messages. + // + // To avoid HTTP errors, ensure that the HTTP response timeout for ReceiveMessage + // requests is longer than the WaitTimeSeconds parameter. For example, with + // the Java SDK, you can set HTTP transport settings using the NettyNioAsyncHttpClient + // (https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/http/nio/netty/NettyNioAsyncHttpClient.html) + // for asynchronous clients, or the ApacheHttpClient (https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/http/apache/ApacheHttpClient.html) + // for synchronous clients. WaitTimeSeconds *int64 `type:"integer"` } @@ -4121,7 +4304,7 @@ type SendMessageBatchRequestEntry struct { // An identifier for a message in this batch used to communicate the result. // - // The Ids of a batch request need to be unique within a request + // The Ids of a batch request need to be unique within a request. // // This identifier can have up to 80 characters. The following characters are // accepted: alphanumeric characters, hyphens(-), and underscores (_). @@ -4216,7 +4399,7 @@ type SendMessageBatchRequestEntry struct { // // * Currently, the only supported message system attribute is AWSTraceHeader. // Its type must be String and its value must be a correctly formatted AWS - // X-Ray trace string. + // X-Ray trace header string. // // * The size of a message system attribute doesn't count towards the total // size of a message. @@ -4467,7 +4650,7 @@ type SendMessageInput struct { // Amazon SQS continues to keep track of the message deduplication ID even after // the message is received and deleted. // - // The length of MessageDeduplicationId is 128 characters. MessageDeduplicationId + // The maximum length of MessageDeduplicationId is 128 characters. MessageDeduplicationId // can contain alphanumeric characters (a-z, A-Z, 0-9) and punctuation (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~). // // For best practices of using MessageDeduplicationId, see Using the MessageDeduplicationId @@ -4508,7 +4691,7 @@ type SendMessageInput struct { // // * Currently, the only supported message system attribute is AWSTraceHeader. // Its type must be String and its value must be a correctly formatted AWS - // X-Ray trace string. + // X-Ray trace header string. // // * The size of a message system attribute doesn't count towards the total // size of a message. @@ -4693,57 +4876,57 @@ type SetQueueAttributesInput struct { // The following lists the names, descriptions, and values of the special request // parameters that the SetQueueAttributes action uses: // - // * DelaySeconds - The length of time, in seconds, for which the delivery + // * 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). Default: 0. // - // * MaximumMessageSize - The limit of how many bytes a message can contain + // * 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). Default: 262,144 (256 KiB). // - // * MessageRetentionPeriod - The length of time, in seconds, for which Amazon - // SQS retains a message. Valid values: An integer representing seconds, + // * 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). Default: 345,600 (4 days). // - // * Policy - The queue's policy. A valid AWS policy. For more information + // * Policy – The queue's policy. A valid AWS policy. For more information // about policy structure, see Overview of AWS IAM Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html) // in the Amazon IAM User Guide. // - // * ReceiveMessageWaitTimeSeconds - The length of time, in seconds, for + // * 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). Default: 0. + // An integer from 0 to 20 (seconds). Default: 0. // - // * RedrivePolicy - The string that includes the parameters for the dead-letter - // queue functionality of the source queue. For more information about the - // redrive policy and dead-letter queues, see Using Amazon SQS Dead-Letter - // Queues (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) + // * RedrivePolicy – The string that includes the parameters for the dead-letter + // queue functionality of the source queue as a JSON object. For more information + // about the redrive policy and dead-letter queues, see Using Amazon SQS + // Dead-Letter Queues (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) // in the Amazon Simple Queue Service Developer Guide. deadLetterTargetArn - // - The Amazon Resource Name (ARN) of the dead-letter queue to which Amazon + // – The Amazon Resource Name (ARN) of the dead-letter queue to which Amazon // SQS moves messages after the value of maxReceiveCount is exceeded. maxReceiveCount - // - The number of times a message is delivered to the source queue before + // – The number of times a message is delivered to the source queue before // being moved to the dead-letter queue. When the ReceiveCount for a message // exceeds the maxReceiveCount for a queue, Amazon SQS moves the message // to the dead-letter-queue. The dead-letter queue of a FIFO queue must also // be a FIFO queue. Similarly, the dead-letter queue of a standard queue // must also be a standard queue. // - // * VisibilityTimeout - The visibility timeout for the queue, in seconds. - // Valid values: an integer from 0 to 43,200 (12 hours). Default: 30. For + // * VisibilityTimeout – The visibility timeout for the queue, in seconds. + // Valid values: An integer from 0 to 43,200 (12 hours). Default: 30. For // more information about the visibility timeout, see Visibility Timeout // (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html) // in the Amazon Simple Queue Service Developer Guide. // // The following attributes apply only to server-side-encryption (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html): // - // * KmsMasterKeyId - The ID of an AWS-managed customer master key (CMK) + // * KmsMasterKeyId – The ID of an AWS-managed customer master key (CMK) // for Amazon SQS or a custom CMK. For more information, see Key Terms (https://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/MyAlias . For more // examples, see KeyId (https://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 (https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys) + // * KmsDataKeyReusePeriodSeconds – The length of time, in seconds, for + // which Amazon SQS can reuse a data key (https://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). Default: 300 (5 minutes). A shorter time period provides better @@ -4754,7 +4937,7 @@ type SetQueueAttributesInput struct { // The following attribute applies only to FIFO (first-in-first-out) queues // (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html): // - // * ContentBasedDeduplication - Enables content-based deduplication. For + // * ContentBasedDeduplication – Enables content-based deduplication. For // more information, see Exactly-Once Processing (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html#FIFO-queues-exactly-once-processing) // in the Amazon Simple Queue Service Developer Guide. Every message must // have a unique MessageDeduplicationId, You may provide a MessageDeduplicationId @@ -4993,11 +5176,32 @@ const ( MessageSystemAttributeNameAwstraceHeader = "AWSTraceHeader" ) +// MessageSystemAttributeName_Values returns all elements of the MessageSystemAttributeName enum +func MessageSystemAttributeName_Values() []string { + return []string{ + MessageSystemAttributeNameSenderId, + MessageSystemAttributeNameSentTimestamp, + MessageSystemAttributeNameApproximateReceiveCount, + MessageSystemAttributeNameApproximateFirstReceiveTimestamp, + MessageSystemAttributeNameSequenceNumber, + MessageSystemAttributeNameMessageDeduplicationId, + MessageSystemAttributeNameMessageGroupId, + MessageSystemAttributeNameAwstraceHeader, + } +} + const ( // MessageSystemAttributeNameForSendsAwstraceHeader is a MessageSystemAttributeNameForSends enum value MessageSystemAttributeNameForSendsAwstraceHeader = "AWSTraceHeader" ) +// MessageSystemAttributeNameForSends_Values returns all elements of the MessageSystemAttributeNameForSends enum +func MessageSystemAttributeNameForSends_Values() []string { + return []string{ + MessageSystemAttributeNameForSendsAwstraceHeader, + } +} + const ( // QueueAttributeNameAll is a QueueAttributeName enum value QueueAttributeNameAll = "All" @@ -5053,3 +5257,27 @@ const ( // QueueAttributeNameKmsDataKeyReusePeriodSeconds is a QueueAttributeName enum value QueueAttributeNameKmsDataKeyReusePeriodSeconds = "KmsDataKeyReusePeriodSeconds" ) + +// QueueAttributeName_Values returns all elements of the QueueAttributeName enum +func QueueAttributeName_Values() []string { + return []string{ + QueueAttributeNameAll, + QueueAttributeNamePolicy, + QueueAttributeNameVisibilityTimeout, + QueueAttributeNameMaximumMessageSize, + QueueAttributeNameMessageRetentionPeriod, + QueueAttributeNameApproximateNumberOfMessages, + QueueAttributeNameApproximateNumberOfMessagesNotVisible, + QueueAttributeNameCreatedTimestamp, + QueueAttributeNameLastModifiedTimestamp, + QueueAttributeNameQueueArn, + QueueAttributeNameApproximateNumberOfMessagesDelayed, + QueueAttributeNameDelaySeconds, + QueueAttributeNameReceiveMessageWaitTimeSeconds, + QueueAttributeNameRedrivePolicy, + QueueAttributeNameFifoQueue, + QueueAttributeNameContentBasedDeduplication, + QueueAttributeNameKmsMasterKeyId, + QueueAttributeNameKmsDataKeyReusePeriodSeconds, + } +} 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 d8bb7c631f2..7e49eff3d9d 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 @@ -449,15 +449,18 @@ func (c *SSM) CreateAssociationRequest(input *CreateAssociationInput) (req *requ // CreateAssociation API operation for Amazon Simple Systems Manager (SSM). // -// Associates the specified Systems Manager document with the specified instances -// or targets. -// -// When you associate a document with one or more instances using instance IDs -// or tags, SSM Agent running on the instance processes the document and configures -// the instance as specified. -// -// If you associate a document with an instance that already has an associated -// document, the system returns the AssociationAlreadyExists exception. +// A State Manager association defines the state that you want to maintain on +// your instances. For example, an association can specify that anti-virus software +// must be installed and running on your instances, or that certain ports must +// be closed. For static targets, the association specifies a schedule for when +// the configuration is reapplied. For dynamic targets, such as an AWS Resource +// Group or an AWS Autoscaling Group, State Manager applies the configuration +// when new instances are added to the group. The association also specifies +// actions to take when applying the configuration. For example, an association +// for anti-virus software might run once a day. If the software is not installed, +// then State Manager installs it. If the software is installed, but the service +// is not running, then the association might instruct State Manager to start +// the service. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2610,6 +2613,12 @@ func (c *SSM) DescribeAssociationExecutionTargetsRequest(input *DescribeAssociat Name: opDescribeAssociationExecutionTargets, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -2668,6 +2677,58 @@ func (c *SSM) DescribeAssociationExecutionTargetsWithContext(ctx aws.Context, in return out, req.Send() } +// DescribeAssociationExecutionTargetsPages iterates over the pages of a DescribeAssociationExecutionTargets operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeAssociationExecutionTargets method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeAssociationExecutionTargets operation. +// pageNum := 0 +// err := client.DescribeAssociationExecutionTargetsPages(params, +// func(page *ssm.DescribeAssociationExecutionTargetsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeAssociationExecutionTargetsPages(input *DescribeAssociationExecutionTargetsInput, fn func(*DescribeAssociationExecutionTargetsOutput, bool) bool) error { + return c.DescribeAssociationExecutionTargetsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAssociationExecutionTargetsPagesWithContext same as DescribeAssociationExecutionTargetsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeAssociationExecutionTargetsPagesWithContext(ctx aws.Context, input *DescribeAssociationExecutionTargetsInput, fn func(*DescribeAssociationExecutionTargetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAssociationExecutionTargetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAssociationExecutionTargetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeAssociationExecutionTargetsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeAssociationExecutions = "DescribeAssociationExecutions" // DescribeAssociationExecutionsRequest generates a "aws/request.Request" representing the @@ -2699,6 +2760,12 @@ func (c *SSM) DescribeAssociationExecutionsRequest(input *DescribeAssociationExe Name: opDescribeAssociationExecutions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -2753,6 +2820,58 @@ func (c *SSM) DescribeAssociationExecutionsWithContext(ctx aws.Context, input *D return out, req.Send() } +// DescribeAssociationExecutionsPages iterates over the pages of a DescribeAssociationExecutions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeAssociationExecutions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeAssociationExecutions operation. +// pageNum := 0 +// err := client.DescribeAssociationExecutionsPages(params, +// func(page *ssm.DescribeAssociationExecutionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeAssociationExecutionsPages(input *DescribeAssociationExecutionsInput, fn func(*DescribeAssociationExecutionsOutput, bool) bool) error { + return c.DescribeAssociationExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAssociationExecutionsPagesWithContext same as DescribeAssociationExecutionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeAssociationExecutionsPagesWithContext(ctx aws.Context, input *DescribeAssociationExecutionsInput, fn func(*DescribeAssociationExecutionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAssociationExecutionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAssociationExecutionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeAssociationExecutionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeAutomationExecutions = "DescribeAutomationExecutions" // DescribeAutomationExecutionsRequest generates a "aws/request.Request" representing the @@ -2784,6 +2903,12 @@ func (c *SSM) DescribeAutomationExecutionsRequest(input *DescribeAutomationExecu Name: opDescribeAutomationExecutions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -2841,6 +2966,58 @@ func (c *SSM) DescribeAutomationExecutionsWithContext(ctx aws.Context, input *De return out, req.Send() } +// DescribeAutomationExecutionsPages iterates over the pages of a DescribeAutomationExecutions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeAutomationExecutions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeAutomationExecutions operation. +// pageNum := 0 +// err := client.DescribeAutomationExecutionsPages(params, +// func(page *ssm.DescribeAutomationExecutionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeAutomationExecutionsPages(input *DescribeAutomationExecutionsInput, fn func(*DescribeAutomationExecutionsOutput, bool) bool) error { + return c.DescribeAutomationExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAutomationExecutionsPagesWithContext same as DescribeAutomationExecutionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeAutomationExecutionsPagesWithContext(ctx aws.Context, input *DescribeAutomationExecutionsInput, fn func(*DescribeAutomationExecutionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAutomationExecutionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAutomationExecutionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeAutomationExecutionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeAutomationStepExecutions = "DescribeAutomationStepExecutions" // DescribeAutomationStepExecutionsRequest generates a "aws/request.Request" representing the @@ -2872,6 +3049,12 @@ func (c *SSM) DescribeAutomationStepExecutionsRequest(input *DescribeAutomationS Name: opDescribeAutomationStepExecutions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -2934,6 +3117,58 @@ func (c *SSM) DescribeAutomationStepExecutionsWithContext(ctx aws.Context, input return out, req.Send() } +// DescribeAutomationStepExecutionsPages iterates over the pages of a DescribeAutomationStepExecutions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeAutomationStepExecutions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeAutomationStepExecutions operation. +// pageNum := 0 +// err := client.DescribeAutomationStepExecutionsPages(params, +// func(page *ssm.DescribeAutomationStepExecutionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeAutomationStepExecutionsPages(input *DescribeAutomationStepExecutionsInput, fn func(*DescribeAutomationStepExecutionsOutput, bool) bool) error { + return c.DescribeAutomationStepExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAutomationStepExecutionsPagesWithContext same as DescribeAutomationStepExecutionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeAutomationStepExecutionsPagesWithContext(ctx aws.Context, input *DescribeAutomationStepExecutionsInput, fn func(*DescribeAutomationStepExecutionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAutomationStepExecutionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAutomationStepExecutionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeAutomationStepExecutionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeAvailablePatches = "DescribeAvailablePatches" // DescribeAvailablePatchesRequest generates a "aws/request.Request" representing the @@ -2965,6 +3200,12 @@ func (c *SSM) DescribeAvailablePatchesRequest(input *DescribeAvailablePatchesInp Name: opDescribeAvailablePatches, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3013,6 +3254,58 @@ func (c *SSM) DescribeAvailablePatchesWithContext(ctx aws.Context, input *Descri return out, req.Send() } +// DescribeAvailablePatchesPages iterates over the pages of a DescribeAvailablePatches operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeAvailablePatches method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeAvailablePatches operation. +// pageNum := 0 +// err := client.DescribeAvailablePatchesPages(params, +// func(page *ssm.DescribeAvailablePatchesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeAvailablePatchesPages(input *DescribeAvailablePatchesInput, fn func(*DescribeAvailablePatchesOutput, bool) bool) error { + return c.DescribeAvailablePatchesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAvailablePatchesPagesWithContext same as DescribeAvailablePatchesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeAvailablePatchesPagesWithContext(ctx aws.Context, input *DescribeAvailablePatchesInput, fn func(*DescribeAvailablePatchesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAvailablePatchesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAvailablePatchesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeAvailablePatchesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeDocument = "DescribeDocument" // DescribeDocumentRequest generates a "aws/request.Request" representing the @@ -3217,6 +3510,12 @@ func (c *SSM) DescribeEffectiveInstanceAssociationsRequest(input *DescribeEffect Name: opDescribeEffectiveInstanceAssociations, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3280,6 +3579,58 @@ func (c *SSM) DescribeEffectiveInstanceAssociationsWithContext(ctx aws.Context, return out, req.Send() } +// DescribeEffectiveInstanceAssociationsPages iterates over the pages of a DescribeEffectiveInstanceAssociations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeEffectiveInstanceAssociations method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeEffectiveInstanceAssociations operation. +// pageNum := 0 +// err := client.DescribeEffectiveInstanceAssociationsPages(params, +// func(page *ssm.DescribeEffectiveInstanceAssociationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeEffectiveInstanceAssociationsPages(input *DescribeEffectiveInstanceAssociationsInput, fn func(*DescribeEffectiveInstanceAssociationsOutput, bool) bool) error { + return c.DescribeEffectiveInstanceAssociationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEffectiveInstanceAssociationsPagesWithContext same as DescribeEffectiveInstanceAssociationsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeEffectiveInstanceAssociationsPagesWithContext(ctx aws.Context, input *DescribeEffectiveInstanceAssociationsInput, fn func(*DescribeEffectiveInstanceAssociationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEffectiveInstanceAssociationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEffectiveInstanceAssociationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeEffectiveInstanceAssociationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeEffectivePatchesForPatchBaseline = "DescribeEffectivePatchesForPatchBaseline" // DescribeEffectivePatchesForPatchBaselineRequest generates a "aws/request.Request" representing the @@ -3311,6 +3662,12 @@ func (c *SSM) DescribeEffectivePatchesForPatchBaselineRequest(input *DescribeEff Name: opDescribeEffectivePatchesForPatchBaseline, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3378,6 +3735,58 @@ func (c *SSM) DescribeEffectivePatchesForPatchBaselineWithContext(ctx aws.Contex return out, req.Send() } +// DescribeEffectivePatchesForPatchBaselinePages iterates over the pages of a DescribeEffectivePatchesForPatchBaseline operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeEffectivePatchesForPatchBaseline method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeEffectivePatchesForPatchBaseline operation. +// pageNum := 0 +// err := client.DescribeEffectivePatchesForPatchBaselinePages(params, +// func(page *ssm.DescribeEffectivePatchesForPatchBaselineOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeEffectivePatchesForPatchBaselinePages(input *DescribeEffectivePatchesForPatchBaselineInput, fn func(*DescribeEffectivePatchesForPatchBaselineOutput, bool) bool) error { + return c.DescribeEffectivePatchesForPatchBaselinePagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEffectivePatchesForPatchBaselinePagesWithContext same as DescribeEffectivePatchesForPatchBaselinePages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeEffectivePatchesForPatchBaselinePagesWithContext(ctx aws.Context, input *DescribeEffectivePatchesForPatchBaselineInput, fn func(*DescribeEffectivePatchesForPatchBaselineOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEffectivePatchesForPatchBaselineInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEffectivePatchesForPatchBaselineRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeEffectivePatchesForPatchBaselineOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInstanceAssociationsStatus = "DescribeInstanceAssociationsStatus" // DescribeInstanceAssociationsStatusRequest generates a "aws/request.Request" representing the @@ -3409,6 +3818,12 @@ func (c *SSM) DescribeInstanceAssociationsStatusRequest(input *DescribeInstanceA Name: opDescribeInstanceAssociationsStatus, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3472,6 +3887,58 @@ func (c *SSM) DescribeInstanceAssociationsStatusWithContext(ctx aws.Context, inp return out, req.Send() } +// DescribeInstanceAssociationsStatusPages iterates over the pages of a DescribeInstanceAssociationsStatus operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInstanceAssociationsStatus method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInstanceAssociationsStatus operation. +// pageNum := 0 +// err := client.DescribeInstanceAssociationsStatusPages(params, +// func(page *ssm.DescribeInstanceAssociationsStatusOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeInstanceAssociationsStatusPages(input *DescribeInstanceAssociationsStatusInput, fn func(*DescribeInstanceAssociationsStatusOutput, bool) bool) error { + return c.DescribeInstanceAssociationsStatusPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstanceAssociationsStatusPagesWithContext same as DescribeInstanceAssociationsStatusPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeInstanceAssociationsStatusPagesWithContext(ctx aws.Context, input *DescribeInstanceAssociationsStatusInput, fn func(*DescribeInstanceAssociationsStatusOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstanceAssociationsStatusInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstanceAssociationsStatusRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInstanceAssociationsStatusOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInstanceInformation = "DescribeInstanceInformation" // DescribeInstanceInformationRequest generates a "aws/request.Request" representing the @@ -3672,6 +4139,12 @@ func (c *SSM) DescribeInstancePatchStatesRequest(input *DescribeInstancePatchSta Name: opDescribeInstancePatchStates, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3723,6 +4196,58 @@ func (c *SSM) DescribeInstancePatchStatesWithContext(ctx aws.Context, input *Des return out, req.Send() } +// DescribeInstancePatchStatesPages iterates over the pages of a DescribeInstancePatchStates operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInstancePatchStates method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInstancePatchStates operation. +// pageNum := 0 +// err := client.DescribeInstancePatchStatesPages(params, +// func(page *ssm.DescribeInstancePatchStatesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeInstancePatchStatesPages(input *DescribeInstancePatchStatesInput, fn func(*DescribeInstancePatchStatesOutput, bool) bool) error { + return c.DescribeInstancePatchStatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstancePatchStatesPagesWithContext same as DescribeInstancePatchStatesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeInstancePatchStatesPagesWithContext(ctx aws.Context, input *DescribeInstancePatchStatesInput, fn func(*DescribeInstancePatchStatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstancePatchStatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancePatchStatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInstancePatchStatesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInstancePatchStatesForPatchGroup = "DescribeInstancePatchStatesForPatchGroup" // DescribeInstancePatchStatesForPatchGroupRequest generates a "aws/request.Request" representing the @@ -3754,6 +4279,12 @@ func (c *SSM) DescribeInstancePatchStatesForPatchGroupRequest(input *DescribeIns Name: opDescribeInstancePatchStatesForPatchGroup, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3810,6 +4341,58 @@ func (c *SSM) DescribeInstancePatchStatesForPatchGroupWithContext(ctx aws.Contex return out, req.Send() } +// DescribeInstancePatchStatesForPatchGroupPages iterates over the pages of a DescribeInstancePatchStatesForPatchGroup operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInstancePatchStatesForPatchGroup method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInstancePatchStatesForPatchGroup operation. +// pageNum := 0 +// err := client.DescribeInstancePatchStatesForPatchGroupPages(params, +// func(page *ssm.DescribeInstancePatchStatesForPatchGroupOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeInstancePatchStatesForPatchGroupPages(input *DescribeInstancePatchStatesForPatchGroupInput, fn func(*DescribeInstancePatchStatesForPatchGroupOutput, bool) bool) error { + return c.DescribeInstancePatchStatesForPatchGroupPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstancePatchStatesForPatchGroupPagesWithContext same as DescribeInstancePatchStatesForPatchGroupPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeInstancePatchStatesForPatchGroupPagesWithContext(ctx aws.Context, input *DescribeInstancePatchStatesForPatchGroupInput, fn func(*DescribeInstancePatchStatesForPatchGroupOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstancePatchStatesForPatchGroupInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancePatchStatesForPatchGroupRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInstancePatchStatesForPatchGroupOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInstancePatches = "DescribeInstancePatches" // DescribeInstancePatchesRequest generates a "aws/request.Request" representing the @@ -3841,6 +4424,12 @@ func (c *SSM) DescribeInstancePatchesRequest(input *DescribeInstancePatchesInput Name: opDescribeInstancePatches, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3909,6 +4498,58 @@ func (c *SSM) DescribeInstancePatchesWithContext(ctx aws.Context, input *Describ return out, req.Send() } +// DescribeInstancePatchesPages iterates over the pages of a DescribeInstancePatches operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInstancePatches method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInstancePatches operation. +// pageNum := 0 +// err := client.DescribeInstancePatchesPages(params, +// func(page *ssm.DescribeInstancePatchesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeInstancePatchesPages(input *DescribeInstancePatchesInput, fn func(*DescribeInstancePatchesOutput, bool) bool) error { + return c.DescribeInstancePatchesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstancePatchesPagesWithContext same as DescribeInstancePatchesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeInstancePatchesPagesWithContext(ctx aws.Context, input *DescribeInstancePatchesInput, fn func(*DescribeInstancePatchesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstancePatchesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancePatchesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInstancePatchesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInventoryDeletions = "DescribeInventoryDeletions" // DescribeInventoryDeletionsRequest generates a "aws/request.Request" representing the @@ -3940,6 +4581,12 @@ func (c *SSM) DescribeInventoryDeletionsRequest(input *DescribeInventoryDeletion Name: opDescribeInventoryDeletions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3995,6 +4642,58 @@ func (c *SSM) DescribeInventoryDeletionsWithContext(ctx aws.Context, input *Desc return out, req.Send() } +// DescribeInventoryDeletionsPages iterates over the pages of a DescribeInventoryDeletions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInventoryDeletions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInventoryDeletions operation. +// pageNum := 0 +// err := client.DescribeInventoryDeletionsPages(params, +// func(page *ssm.DescribeInventoryDeletionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeInventoryDeletionsPages(input *DescribeInventoryDeletionsInput, fn func(*DescribeInventoryDeletionsOutput, bool) bool) error { + return c.DescribeInventoryDeletionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInventoryDeletionsPagesWithContext same as DescribeInventoryDeletionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeInventoryDeletionsPagesWithContext(ctx aws.Context, input *DescribeInventoryDeletionsInput, fn func(*DescribeInventoryDeletionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInventoryDeletionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInventoryDeletionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInventoryDeletionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowExecutionTaskInvocations = "DescribeMaintenanceWindowExecutionTaskInvocations" // DescribeMaintenanceWindowExecutionTaskInvocationsRequest generates a "aws/request.Request" representing the @@ -4026,6 +4725,12 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTaskInvocationsRequest(input *De Name: opDescribeMaintenanceWindowExecutionTaskInvocations, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4083,6 +4788,58 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTaskInvocationsWithContext(ctx a return out, req.Send() } +// DescribeMaintenanceWindowExecutionTaskInvocationsPages iterates over the pages of a DescribeMaintenanceWindowExecutionTaskInvocations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowExecutionTaskInvocations method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowExecutionTaskInvocations operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowExecutionTaskInvocationsPages(params, +// func(page *ssm.DescribeMaintenanceWindowExecutionTaskInvocationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowExecutionTaskInvocationsPages(input *DescribeMaintenanceWindowExecutionTaskInvocationsInput, fn func(*DescribeMaintenanceWindowExecutionTaskInvocationsOutput, bool) bool) error { + return c.DescribeMaintenanceWindowExecutionTaskInvocationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowExecutionTaskInvocationsPagesWithContext same as DescribeMaintenanceWindowExecutionTaskInvocationsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeMaintenanceWindowExecutionTaskInvocationsPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowExecutionTaskInvocationsInput, fn func(*DescribeMaintenanceWindowExecutionTaskInvocationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowExecutionTaskInvocationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowExecutionTaskInvocationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowExecutionTaskInvocationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowExecutionTasks = "DescribeMaintenanceWindowExecutionTasks" // DescribeMaintenanceWindowExecutionTasksRequest generates a "aws/request.Request" representing the @@ -4114,6 +4871,12 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTasksRequest(input *DescribeMain Name: opDescribeMaintenanceWindowExecutionTasks, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4170,6 +4933,58 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTasksWithContext(ctx aws.Context return out, req.Send() } +// DescribeMaintenanceWindowExecutionTasksPages iterates over the pages of a DescribeMaintenanceWindowExecutionTasks operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowExecutionTasks method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowExecutionTasks operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowExecutionTasksPages(params, +// func(page *ssm.DescribeMaintenanceWindowExecutionTasksOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowExecutionTasksPages(input *DescribeMaintenanceWindowExecutionTasksInput, fn func(*DescribeMaintenanceWindowExecutionTasksOutput, bool) bool) error { + return c.DescribeMaintenanceWindowExecutionTasksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowExecutionTasksPagesWithContext same as DescribeMaintenanceWindowExecutionTasksPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeMaintenanceWindowExecutionTasksPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowExecutionTasksInput, fn func(*DescribeMaintenanceWindowExecutionTasksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowExecutionTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowExecutionTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowExecutionTasksOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowExecutions = "DescribeMaintenanceWindowExecutions" // DescribeMaintenanceWindowExecutionsRequest generates a "aws/request.Request" representing the @@ -4201,6 +5016,12 @@ func (c *SSM) DescribeMaintenanceWindowExecutionsRequest(input *DescribeMaintena Name: opDescribeMaintenanceWindowExecutions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4251,6 +5072,58 @@ func (c *SSM) DescribeMaintenanceWindowExecutionsWithContext(ctx aws.Context, in return out, req.Send() } +// DescribeMaintenanceWindowExecutionsPages iterates over the pages of a DescribeMaintenanceWindowExecutions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowExecutions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowExecutions operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowExecutionsPages(params, +// func(page *ssm.DescribeMaintenanceWindowExecutionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowExecutionsPages(input *DescribeMaintenanceWindowExecutionsInput, fn func(*DescribeMaintenanceWindowExecutionsOutput, bool) bool) error { + return c.DescribeMaintenanceWindowExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowExecutionsPagesWithContext same as DescribeMaintenanceWindowExecutionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeMaintenanceWindowExecutionsPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowExecutionsInput, fn func(*DescribeMaintenanceWindowExecutionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowExecutionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowExecutionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowExecutionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowSchedule = "DescribeMaintenanceWindowSchedule" // DescribeMaintenanceWindowScheduleRequest generates a "aws/request.Request" representing the @@ -4282,6 +5155,12 @@ func (c *SSM) DescribeMaintenanceWindowScheduleRequest(input *DescribeMaintenanc Name: opDescribeMaintenanceWindowSchedule, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4338,6 +5217,58 @@ func (c *SSM) DescribeMaintenanceWindowScheduleWithContext(ctx aws.Context, inpu return out, req.Send() } +// DescribeMaintenanceWindowSchedulePages iterates over the pages of a DescribeMaintenanceWindowSchedule operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowSchedule method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowSchedule operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowSchedulePages(params, +// func(page *ssm.DescribeMaintenanceWindowScheduleOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowSchedulePages(input *DescribeMaintenanceWindowScheduleInput, fn func(*DescribeMaintenanceWindowScheduleOutput, bool) bool) error { + return c.DescribeMaintenanceWindowSchedulePagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowSchedulePagesWithContext same as DescribeMaintenanceWindowSchedulePages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeMaintenanceWindowSchedulePagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowScheduleInput, fn func(*DescribeMaintenanceWindowScheduleOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowScheduleInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowScheduleRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowScheduleOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowTargets = "DescribeMaintenanceWindowTargets" // DescribeMaintenanceWindowTargetsRequest generates a "aws/request.Request" representing the @@ -4369,6 +5300,12 @@ func (c *SSM) DescribeMaintenanceWindowTargetsRequest(input *DescribeMaintenance Name: opDescribeMaintenanceWindowTargets, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4425,6 +5362,58 @@ func (c *SSM) DescribeMaintenanceWindowTargetsWithContext(ctx aws.Context, input return out, req.Send() } +// DescribeMaintenanceWindowTargetsPages iterates over the pages of a DescribeMaintenanceWindowTargets operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowTargets method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowTargets operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowTargetsPages(params, +// func(page *ssm.DescribeMaintenanceWindowTargetsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowTargetsPages(input *DescribeMaintenanceWindowTargetsInput, fn func(*DescribeMaintenanceWindowTargetsOutput, bool) bool) error { + return c.DescribeMaintenanceWindowTargetsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowTargetsPagesWithContext same as DescribeMaintenanceWindowTargetsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeMaintenanceWindowTargetsPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowTargetsInput, fn func(*DescribeMaintenanceWindowTargetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowTargetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowTargetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowTargetsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowTasks = "DescribeMaintenanceWindowTasks" // DescribeMaintenanceWindowTasksRequest generates a "aws/request.Request" representing the @@ -4456,6 +5445,12 @@ func (c *SSM) DescribeMaintenanceWindowTasksRequest(input *DescribeMaintenanceWi Name: opDescribeMaintenanceWindowTasks, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4512,6 +5507,58 @@ func (c *SSM) DescribeMaintenanceWindowTasksWithContext(ctx aws.Context, input * return out, req.Send() } +// DescribeMaintenanceWindowTasksPages iterates over the pages of a DescribeMaintenanceWindowTasks operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowTasks method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowTasks operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowTasksPages(params, +// func(page *ssm.DescribeMaintenanceWindowTasksOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowTasksPages(input *DescribeMaintenanceWindowTasksInput, fn func(*DescribeMaintenanceWindowTasksOutput, bool) bool) error { + return c.DescribeMaintenanceWindowTasksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowTasksPagesWithContext same as DescribeMaintenanceWindowTasksPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeMaintenanceWindowTasksPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowTasksInput, fn func(*DescribeMaintenanceWindowTasksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowTasksOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindows = "DescribeMaintenanceWindows" // DescribeMaintenanceWindowsRequest generates a "aws/request.Request" representing the @@ -4543,6 +5590,12 @@ func (c *SSM) DescribeMaintenanceWindowsRequest(input *DescribeMaintenanceWindow Name: opDescribeMaintenanceWindows, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4591,6 +5644,58 @@ func (c *SSM) DescribeMaintenanceWindowsWithContext(ctx aws.Context, input *Desc return out, req.Send() } +// DescribeMaintenanceWindowsPages iterates over the pages of a DescribeMaintenanceWindows operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindows method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindows operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowsPages(params, +// func(page *ssm.DescribeMaintenanceWindowsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowsPages(input *DescribeMaintenanceWindowsInput, fn func(*DescribeMaintenanceWindowsOutput, bool) bool) error { + return c.DescribeMaintenanceWindowsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowsPagesWithContext same as DescribeMaintenanceWindowsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeMaintenanceWindowsPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowsInput, fn func(*DescribeMaintenanceWindowsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowsForTarget = "DescribeMaintenanceWindowsForTarget" // DescribeMaintenanceWindowsForTargetRequest generates a "aws/request.Request" representing the @@ -4622,6 +5727,12 @@ func (c *SSM) DescribeMaintenanceWindowsForTargetRequest(input *DescribeMaintena Name: opDescribeMaintenanceWindowsForTarget, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4671,6 +5782,58 @@ func (c *SSM) DescribeMaintenanceWindowsForTargetWithContext(ctx aws.Context, in return out, req.Send() } +// DescribeMaintenanceWindowsForTargetPages iterates over the pages of a DescribeMaintenanceWindowsForTarget operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowsForTarget method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowsForTarget operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowsForTargetPages(params, +// func(page *ssm.DescribeMaintenanceWindowsForTargetOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowsForTargetPages(input *DescribeMaintenanceWindowsForTargetInput, fn func(*DescribeMaintenanceWindowsForTargetOutput, bool) bool) error { + return c.DescribeMaintenanceWindowsForTargetPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowsForTargetPagesWithContext same as DescribeMaintenanceWindowsForTargetPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeMaintenanceWindowsForTargetPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowsForTargetInput, fn func(*DescribeMaintenanceWindowsForTargetOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowsForTargetInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowsForTargetRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowsForTargetOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeOpsItems = "DescribeOpsItems" // DescribeOpsItemsRequest generates a "aws/request.Request" representing the @@ -4702,6 +5865,12 @@ func (c *SSM) DescribeOpsItemsRequest(input *DescribeOpsItemsInput) (req *reques Name: opDescribeOpsItems, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4759,6 +5928,58 @@ func (c *SSM) DescribeOpsItemsWithContext(ctx aws.Context, input *DescribeOpsIte return out, req.Send() } +// DescribeOpsItemsPages iterates over the pages of a DescribeOpsItems operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeOpsItems method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeOpsItems operation. +// pageNum := 0 +// err := client.DescribeOpsItemsPages(params, +// func(page *ssm.DescribeOpsItemsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeOpsItemsPages(input *DescribeOpsItemsInput, fn func(*DescribeOpsItemsOutput, bool) bool) error { + return c.DescribeOpsItemsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeOpsItemsPagesWithContext same as DescribeOpsItemsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeOpsItemsPagesWithContext(ctx aws.Context, input *DescribeOpsItemsInput, fn func(*DescribeOpsItemsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeOpsItemsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeOpsItemsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeOpsItemsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeParameters = "DescribeParameters" // DescribeParametersRequest generates a "aws/request.Request" representing the @@ -4948,6 +6169,12 @@ func (c *SSM) DescribePatchBaselinesRequest(input *DescribePatchBaselinesInput) Name: opDescribePatchBaselines, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4996,6 +6223,58 @@ func (c *SSM) DescribePatchBaselinesWithContext(ctx aws.Context, input *Describe return out, req.Send() } +// DescribePatchBaselinesPages iterates over the pages of a DescribePatchBaselines operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribePatchBaselines method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribePatchBaselines operation. +// pageNum := 0 +// err := client.DescribePatchBaselinesPages(params, +// func(page *ssm.DescribePatchBaselinesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribePatchBaselinesPages(input *DescribePatchBaselinesInput, fn func(*DescribePatchBaselinesOutput, bool) bool) error { + return c.DescribePatchBaselinesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribePatchBaselinesPagesWithContext same as DescribePatchBaselinesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribePatchBaselinesPagesWithContext(ctx aws.Context, input *DescribePatchBaselinesInput, fn func(*DescribePatchBaselinesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribePatchBaselinesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribePatchBaselinesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribePatchBaselinesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribePatchGroupState = "DescribePatchGroupState" // DescribePatchGroupStateRequest generates a "aws/request.Request" representing the @@ -5109,6 +6388,12 @@ func (c *SSM) DescribePatchGroupsRequest(input *DescribePatchGroupsInput) (req * Name: opDescribePatchGroups, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -5157,6 +6442,58 @@ func (c *SSM) DescribePatchGroupsWithContext(ctx aws.Context, input *DescribePat return out, req.Send() } +// DescribePatchGroupsPages iterates over the pages of a DescribePatchGroups operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribePatchGroups method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribePatchGroups operation. +// pageNum := 0 +// err := client.DescribePatchGroupsPages(params, +// func(page *ssm.DescribePatchGroupsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribePatchGroupsPages(input *DescribePatchGroupsInput, fn func(*DescribePatchGroupsOutput, bool) bool) error { + return c.DescribePatchGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribePatchGroupsPagesWithContext same as DescribePatchGroupsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribePatchGroupsPagesWithContext(ctx aws.Context, input *DescribePatchGroupsInput, fn func(*DescribePatchGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribePatchGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribePatchGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribePatchGroupsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribePatchProperties = "DescribePatchProperties" // DescribePatchPropertiesRequest generates a "aws/request.Request" representing the @@ -5188,6 +6525,12 @@ func (c *SSM) DescribePatchPropertiesRequest(input *DescribePatchPropertiesInput Name: opDescribePatchProperties, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -5271,6 +6614,58 @@ func (c *SSM) DescribePatchPropertiesWithContext(ctx aws.Context, input *Describ return out, req.Send() } +// DescribePatchPropertiesPages iterates over the pages of a DescribePatchProperties operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribePatchProperties method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribePatchProperties operation. +// pageNum := 0 +// err := client.DescribePatchPropertiesPages(params, +// func(page *ssm.DescribePatchPropertiesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribePatchPropertiesPages(input *DescribePatchPropertiesInput, fn func(*DescribePatchPropertiesOutput, bool) bool) error { + return c.DescribePatchPropertiesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribePatchPropertiesPagesWithContext same as DescribePatchPropertiesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribePatchPropertiesPagesWithContext(ctx aws.Context, input *DescribePatchPropertiesInput, fn func(*DescribePatchPropertiesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribePatchPropertiesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribePatchPropertiesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribePatchPropertiesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeSessions = "DescribeSessions" // DescribeSessionsRequest generates a "aws/request.Request" representing the @@ -5302,6 +6697,12 @@ func (c *SSM) DescribeSessionsRequest(input *DescribeSessionsInput) (req *reques Name: opDescribeSessions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -5357,6 +6758,58 @@ func (c *SSM) DescribeSessionsWithContext(ctx aws.Context, input *DescribeSessio return out, req.Send() } +// DescribeSessionsPages iterates over the pages of a DescribeSessions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeSessions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeSessions operation. +// pageNum := 0 +// err := client.DescribeSessionsPages(params, +// func(page *ssm.DescribeSessionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeSessionsPages(input *DescribeSessionsInput, fn func(*DescribeSessionsOutput, bool) bool) error { + return c.DescribeSessionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeSessionsPagesWithContext same as DescribeSessionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) DescribeSessionsPagesWithContext(ctx aws.Context, input *DescribeSessionsInput, fn func(*DescribeSessionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeSessionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeSessionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeSessionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetAutomationExecution = "GetAutomationExecution" // GetAutomationExecutionRequest generates a "aws/request.Request" representing the @@ -6010,6 +7463,12 @@ func (c *SSM) GetInventoryRequest(input *GetInventoryInput) (req *request.Reques Name: opGetInventory, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -6078,6 +7537,58 @@ func (c *SSM) GetInventoryWithContext(ctx aws.Context, input *GetInventoryInput, return out, req.Send() } +// GetInventoryPages iterates over the pages of a GetInventory operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetInventory method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetInventory operation. +// pageNum := 0 +// err := client.GetInventoryPages(params, +// func(page *ssm.GetInventoryOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) GetInventoryPages(input *GetInventoryInput, fn func(*GetInventoryOutput, bool) bool) error { + return c.GetInventoryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetInventoryPagesWithContext same as GetInventoryPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) GetInventoryPagesWithContext(ctx aws.Context, input *GetInventoryInput, fn func(*GetInventoryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetInventoryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetInventoryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetInventoryOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetInventorySchema = "GetInventorySchema" // GetInventorySchemaRequest generates a "aws/request.Request" representing the @@ -6109,6 +7620,12 @@ func (c *SSM) GetInventorySchemaRequest(input *GetInventorySchemaInput) (req *re Name: opGetInventorySchema, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -6164,6 +7681,58 @@ func (c *SSM) GetInventorySchemaWithContext(ctx aws.Context, input *GetInventory return out, req.Send() } +// GetInventorySchemaPages iterates over the pages of a GetInventorySchema operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetInventorySchema method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetInventorySchema operation. +// pageNum := 0 +// err := client.GetInventorySchemaPages(params, +// func(page *ssm.GetInventorySchemaOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) GetInventorySchemaPages(input *GetInventorySchemaInput, fn func(*GetInventorySchemaOutput, bool) bool) error { + return c.GetInventorySchemaPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetInventorySchemaPagesWithContext same as GetInventorySchemaPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) GetInventorySchemaPagesWithContext(ctx aws.Context, input *GetInventorySchemaInput, fn func(*GetInventorySchemaOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetInventorySchemaInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetInventorySchemaRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetInventorySchemaOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetMaintenanceWindow = "GetMaintenanceWindow" // GetMaintenanceWindowRequest generates a "aws/request.Request" representing the @@ -6722,6 +8291,12 @@ func (c *SSM) GetOpsSummaryRequest(input *GetOpsSummaryInput) (req *request.Requ Name: opGetOpsSummary, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -6787,6 +8362,58 @@ func (c *SSM) GetOpsSummaryWithContext(ctx aws.Context, input *GetOpsSummaryInpu return out, req.Send() } +// GetOpsSummaryPages iterates over the pages of a GetOpsSummary operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetOpsSummary method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetOpsSummary operation. +// pageNum := 0 +// err := client.GetOpsSummaryPages(params, +// func(page *ssm.GetOpsSummaryOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) GetOpsSummaryPages(input *GetOpsSummaryInput, fn func(*GetOpsSummaryOutput, bool) bool) error { + return c.GetOpsSummaryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetOpsSummaryPagesWithContext same as GetOpsSummaryPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) GetOpsSummaryPagesWithContext(ctx aws.Context, input *GetOpsSummaryInput, fn func(*GetOpsSummaryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetOpsSummaryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetOpsSummaryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetOpsSummaryOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetParameter = "GetParameter" // GetParameterRequest generates a "aws/request.Request" representing the @@ -7687,6 +9314,12 @@ func (c *SSM) ListAssociationVersionsRequest(input *ListAssociationVersionsInput Name: opListAssociationVersions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -7741,6 +9374,58 @@ func (c *SSM) ListAssociationVersionsWithContext(ctx aws.Context, input *ListAss return out, req.Send() } +// ListAssociationVersionsPages iterates over the pages of a ListAssociationVersions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListAssociationVersions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListAssociationVersions operation. +// pageNum := 0 +// err := client.ListAssociationVersionsPages(params, +// func(page *ssm.ListAssociationVersionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListAssociationVersionsPages(input *ListAssociationVersionsInput, fn func(*ListAssociationVersionsOutput, bool) bool) error { + return c.ListAssociationVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAssociationVersionsPagesWithContext same as ListAssociationVersionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) ListAssociationVersionsPagesWithContext(ctx aws.Context, input *ListAssociationVersionsInput, fn func(*ListAssociationVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAssociationVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAssociationVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListAssociationVersionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListAssociations = "ListAssociations" // ListAssociationsRequest generates a "aws/request.Request" representing the @@ -8232,6 +9917,12 @@ func (c *SSM) ListComplianceItemsRequest(input *ListComplianceItemsInput) (req * Name: opListComplianceItems, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -8298,6 +9989,58 @@ func (c *SSM) ListComplianceItemsWithContext(ctx aws.Context, input *ListComplia return out, req.Send() } +// ListComplianceItemsPages iterates over the pages of a ListComplianceItems operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListComplianceItems method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListComplianceItems operation. +// pageNum := 0 +// err := client.ListComplianceItemsPages(params, +// func(page *ssm.ListComplianceItemsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListComplianceItemsPages(input *ListComplianceItemsInput, fn func(*ListComplianceItemsOutput, bool) bool) error { + return c.ListComplianceItemsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListComplianceItemsPagesWithContext same as ListComplianceItemsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) ListComplianceItemsPagesWithContext(ctx aws.Context, input *ListComplianceItemsInput, fn func(*ListComplianceItemsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListComplianceItemsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListComplianceItemsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListComplianceItemsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListComplianceSummaries = "ListComplianceSummaries" // ListComplianceSummariesRequest generates a "aws/request.Request" representing the @@ -8329,6 +10072,12 @@ func (c *SSM) ListComplianceSummariesRequest(input *ListComplianceSummariesInput Name: opListComplianceSummaries, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -8386,6 +10135,58 @@ func (c *SSM) ListComplianceSummariesWithContext(ctx aws.Context, input *ListCom return out, req.Send() } +// ListComplianceSummariesPages iterates over the pages of a ListComplianceSummaries operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListComplianceSummaries method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListComplianceSummaries operation. +// pageNum := 0 +// err := client.ListComplianceSummariesPages(params, +// func(page *ssm.ListComplianceSummariesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListComplianceSummariesPages(input *ListComplianceSummariesInput, fn func(*ListComplianceSummariesOutput, bool) bool) error { + return c.ListComplianceSummariesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListComplianceSummariesPagesWithContext same as ListComplianceSummariesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) ListComplianceSummariesPagesWithContext(ctx aws.Context, input *ListComplianceSummariesInput, fn func(*ListComplianceSummariesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListComplianceSummariesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListComplianceSummariesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListComplianceSummariesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListDocumentVersions = "ListDocumentVersions" // ListDocumentVersionsRequest generates a "aws/request.Request" representing the @@ -8417,6 +10218,12 @@ func (c *SSM) ListDocumentVersionsRequest(input *ListDocumentVersionsInput) (req Name: opListDocumentVersions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -8471,6 +10278,58 @@ func (c *SSM) ListDocumentVersionsWithContext(ctx aws.Context, input *ListDocume return out, req.Send() } +// ListDocumentVersionsPages iterates over the pages of a ListDocumentVersions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListDocumentVersions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListDocumentVersions operation. +// pageNum := 0 +// err := client.ListDocumentVersionsPages(params, +// func(page *ssm.ListDocumentVersionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListDocumentVersionsPages(input *ListDocumentVersionsInput, fn func(*ListDocumentVersionsOutput, bool) bool) error { + return c.ListDocumentVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDocumentVersionsPagesWithContext same as ListDocumentVersionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) ListDocumentVersionsPagesWithContext(ctx aws.Context, input *ListDocumentVersionsInput, fn func(*ListDocumentVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDocumentVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDocumentVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListDocumentVersionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListDocuments = "ListDocuments" // ListDocumentsRequest generates a "aws/request.Request" representing the @@ -8747,6 +10606,12 @@ func (c *SSM) ListResourceComplianceSummariesRequest(input *ListResourceComplian Name: opListResourceComplianceSummaries, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -8804,6 +10669,58 @@ func (c *SSM) ListResourceComplianceSummariesWithContext(ctx aws.Context, input return out, req.Send() } +// ListResourceComplianceSummariesPages iterates over the pages of a ListResourceComplianceSummaries operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListResourceComplianceSummaries method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListResourceComplianceSummaries operation. +// pageNum := 0 +// err := client.ListResourceComplianceSummariesPages(params, +// func(page *ssm.ListResourceComplianceSummariesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListResourceComplianceSummariesPages(input *ListResourceComplianceSummariesInput, fn func(*ListResourceComplianceSummariesOutput, bool) bool) error { + return c.ListResourceComplianceSummariesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListResourceComplianceSummariesPagesWithContext same as ListResourceComplianceSummariesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) ListResourceComplianceSummariesPagesWithContext(ctx aws.Context, input *ListResourceComplianceSummariesInput, fn func(*ListResourceComplianceSummariesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListResourceComplianceSummariesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListResourceComplianceSummariesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListResourceComplianceSummariesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListResourceDataSync = "ListResourceDataSync" // ListResourceDataSyncRequest generates a "aws/request.Request" representing the @@ -8835,6 +10752,12 @@ func (c *SSM) ListResourceDataSyncRequest(input *ListResourceDataSyncInput) (req Name: opListResourceDataSync, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -8898,6 +10821,58 @@ func (c *SSM) ListResourceDataSyncWithContext(ctx aws.Context, input *ListResour return out, req.Send() } +// ListResourceDataSyncPages iterates over the pages of a ListResourceDataSync operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListResourceDataSync method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListResourceDataSync operation. +// pageNum := 0 +// err := client.ListResourceDataSyncPages(params, +// func(page *ssm.ListResourceDataSyncOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListResourceDataSyncPages(input *ListResourceDataSyncInput, fn func(*ListResourceDataSyncOutput, bool) bool) error { + return c.ListResourceDataSyncPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListResourceDataSyncPagesWithContext same as ListResourceDataSyncPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) ListResourceDataSyncPagesWithContext(ctx aws.Context, input *ListResourceDataSyncInput, fn func(*ListResourceDataSyncOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListResourceDataSyncInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListResourceDataSyncRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListResourceDataSyncOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListTagsForResource = "ListTagsForResource" // ListTagsForResourceRequest generates a "aws/request.Request" representing the @@ -12610,6 +14585,12 @@ func (s *AssociationAlreadyExists) RequestID() string { type AssociationDescription struct { _ struct{} `type:"structure"` + // By default, when you create a new associations, the system runs it immediately + // after it is created and then according to the schedule you specified. Specify + // this option if you don't want an association to run immediately after you + // create it. + ApplyOnlyAtCronInterval *bool `type:"boolean"` + // The association ID. AssociationId *string `type:"string"` @@ -12716,6 +14697,12 @@ func (s AssociationDescription) GoString() string { return s.String() } +// SetApplyOnlyAtCronInterval sets the ApplyOnlyAtCronInterval field's value. +func (s *AssociationDescription) SetApplyOnlyAtCronInterval(v bool) *AssociationDescription { + s.ApplyOnlyAtCronInterval = &v + return s +} + // SetAssociationId sets the AssociationId field's value. func (s *AssociationDescription) SetAssociationId(v string) *AssociationDescription { s.AssociationId = &v @@ -13503,6 +15490,12 @@ func (s *AssociationStatus) SetName(v string) *AssociationStatus { type AssociationVersionInfo struct { _ struct{} `type:"structure"` + // By default, when you create a new associations, the system runs it immediately + // after it is created and then according to the schedule you specified. Specify + // this option if you don't want an association to run immediately after you + // create it. + ApplyOnlyAtCronInterval *bool `type:"boolean"` + // The ID created by the system when the association was created. AssociationId *string `type:"string"` @@ -13592,6 +15585,12 @@ func (s AssociationVersionInfo) GoString() string { return s.String() } +// SetApplyOnlyAtCronInterval sets the ApplyOnlyAtCronInterval field's value. +func (s *AssociationVersionInfo) SetApplyOnlyAtCronInterval(v bool) *AssociationVersionInfo { + s.ApplyOnlyAtCronInterval = &v + return s +} + // SetAssociationId sets the AssociationId field's value. func (s *AssociationVersionInfo) SetAssociationId(v string) *AssociationVersionInfo { s.AssociationId = &v @@ -15168,6 +17167,9 @@ func (s *Command) SetTimeoutSeconds(v int64) *Command { } // Describes a command filter. +// +// An instance ID can't be specified when a command status is Pending because +// the command hasn't run on the instance yet. type CommandFilter struct { _ struct{} `type:"structure"` @@ -16348,6 +18350,12 @@ func (s *CreateAssociationBatchOutput) SetSuccessful(v []*AssociationDescription type CreateAssociationBatchRequestEntry struct { _ struct{} `type:"structure"` + // By default, when you create a new associations, the system runs it immediately + // after it is created and then according to the schedule you specified. Specify + // this option if you don't want an association to run immediately after you + // create it. + ApplyOnlyAtCronInterval *bool `type:"boolean"` + // Specify a descriptive name for the association. AssociationName *string `type:"string"` @@ -16489,6 +18497,12 @@ func (s *CreateAssociationBatchRequestEntry) Validate() error { return nil } +// SetApplyOnlyAtCronInterval sets the ApplyOnlyAtCronInterval field's value. +func (s *CreateAssociationBatchRequestEntry) SetApplyOnlyAtCronInterval(v bool) *CreateAssociationBatchRequestEntry { + s.ApplyOnlyAtCronInterval = &v + return s +} + // SetAssociationName sets the AssociationName field's value. func (s *CreateAssociationBatchRequestEntry) SetAssociationName(v string) *CreateAssociationBatchRequestEntry { s.AssociationName = &v @@ -16570,6 +18584,12 @@ func (s *CreateAssociationBatchRequestEntry) SetTargets(v []*Target) *CreateAsso type CreateAssociationInput struct { _ struct{} `type:"structure"` + // By default, when you create a new associations, the system runs it immediately + // after it is created and then according to the schedule you specified. Specify + // this option if you don't want an association to run immediately after you + // create it. + ApplyOnlyAtCronInterval *bool `type:"boolean"` + // Specify a descriptive name for the association. AssociationName *string `type:"string"` @@ -16723,6 +18743,12 @@ func (s *CreateAssociationInput) Validate() error { return nil } +// SetApplyOnlyAtCronInterval sets the ApplyOnlyAtCronInterval field's value. +func (s *CreateAssociationInput) SetApplyOnlyAtCronInterval(v bool) *CreateAssociationInput { + s.ApplyOnlyAtCronInterval = &v + return s +} + // SetAssociationName sets the AssociationName field's value. func (s *CreateAssociationInput) SetAssociationName(v string) *CreateAssociationInput { s.AssociationName = &v @@ -16858,7 +18884,7 @@ type CreateDocumentInput struct { // You can't use the following strings as document name prefixes. These are // reserved by AWS for use as document name prefixes: // - // * aws + // * aws- // // * amazon // @@ -17090,6 +19116,18 @@ type CreateMaintenanceWindowInput struct { // Schedule is a required field Schedule *string `min:"1" type:"string" required:"true"` + // The number of days to wait after the date and time specified by a CRON expression + // before running the maintenance window. + // + // For example, the following cron expression schedules a maintenance window + // to run on the third Tuesday of every month at 11:30 PM. + // + // cron(0 30 23 ? * TUE#3 *) + // + // If the schedule offset is 2, the maintenance window won't run until two days + // later. + ScheduleOffset *int64 `min:"1" type:"integer"` + // The time zone that the scheduled maintenance window executions are based // on, in Internet Assigned Numbers Authority (IANA) format. For example: "America/Los_Angeles", // "etc/UTC", or "Asia/Seoul". For more information, see the Time Zone Database @@ -17161,6 +19199,9 @@ func (s *CreateMaintenanceWindowInput) Validate() error { if s.Schedule != nil && len(*s.Schedule) < 1 { invalidParams.Add(request.NewErrParamMinLen("Schedule", 1)) } + if s.ScheduleOffset != nil && *s.ScheduleOffset < 1 { + invalidParams.Add(request.NewErrParamMinValue("ScheduleOffset", 1)) + } if s.Tags != nil { for i, v := range s.Tags { if v == nil { @@ -17226,6 +19267,12 @@ func (s *CreateMaintenanceWindowInput) SetSchedule(v string) *CreateMaintenanceW return s } +// SetScheduleOffset sets the ScheduleOffset field's value. +func (s *CreateMaintenanceWindowInput) SetScheduleOffset(v int64) *CreateMaintenanceWindowInput { + s.ScheduleOffset = &v + return s +} + // SetScheduleTimezone sets the ScheduleTimezone field's value. func (s *CreateMaintenanceWindowInput) SetScheduleTimezone(v string) *CreateMaintenanceWindowInput { s.ScheduleTimezone = &v @@ -22164,6 +24211,15 @@ type DescribePatchGroupsInput struct { _ struct{} `type:"structure"` // One or more filters. Use a filter to return a more specific list of results. + // + // For DescribePatchGroups,valid filter keys include the following: + // + // * NAME_PREFIX: The name of the patch group. Wildcards (*) are accepted. + // + // * OPERATING_SYSTEM: The supported operating system type to return results + // for. For valid operating system values, see GetDefaultPatchBaselineRequest$OperatingSystem + // in CreatePatchBaseline. Examples: --filters Key=NAME_PREFIX,Values=MyPatchGroup* + // --filters Key=OPERATING_SYSTEM,Values=AMAZON_LINUX_2 Filters []*PatchOrchestratorFilter `type:"list"` // The maximum number of patch groups to return (per page). @@ -24032,6 +26088,8 @@ type GetCommandInvocationInput struct { // (Optional) The name of the plugin for which you want detailed results. If // the document contains only one plugin, the name can be omitted and the details // will be returned. + // + // Plugin names are also referred to as step names in Systems Manager documents. PluginName *string `min:"4" type:"string"` } @@ -25592,6 +27650,10 @@ type GetMaintenanceWindowOutput struct { // The schedule of the maintenance window in the form of a cron or rate expression. Schedule *string `min:"1" type:"string"` + // The number of days to wait to run a maintenance window after the scheduled + // CRON expression date and time. + ScheduleOffset *int64 `min:"1" type:"integer"` + // The time zone that the scheduled maintenance window executions are based // on, in Internet Assigned Numbers Authority (IANA) format. For example: "America/Los_Angeles", // "etc/UTC", or "Asia/Seoul". For more information, see the Time Zone Database @@ -25683,6 +27745,12 @@ func (s *GetMaintenanceWindowOutput) SetSchedule(v string) *GetMaintenanceWindow return s } +// SetScheduleOffset sets the ScheduleOffset field's value. +func (s *GetMaintenanceWindowOutput) SetScheduleOffset(v int64) *GetMaintenanceWindowOutput { + s.ScheduleOffset = &v + return s +} + // SetScheduleTimezone sets the ScheduleTimezone field's value. func (s *GetMaintenanceWindowOutput) SetScheduleTimezone(v string) *GetMaintenanceWindowOutput { s.ScheduleTimezone = &v @@ -27428,8 +29496,12 @@ type InstanceInformation struct { IPAddress *string `min:"1" type:"string"` // The Amazon Identity and Access Management (IAM) role assigned to the on-premises - // Systems Manager managed instances. This call does not return the IAM role - // for EC2 instances. + // Systems Manager managed instance. This call does not return the IAM role + // for EC2 instances. To retrieve the IAM role for an EC2 instance, use the + // Amazon EC2 DescribeInstances action. For information, see DescribeInstances + // (http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) + // in the Amazon EC2 API Reference or describe-instances (http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) + // in the AWS CLI Command Reference. IamRole *string `type:"string"` // The instance ID. @@ -27450,7 +29522,17 @@ type InstanceInformation struct { // The last date the association was successfully run. LastSuccessfulAssociationExecutionDate *time.Time `type:"timestamp"` - // The name of the managed instance. + // The name assigned to an on-premises server or virtual machine (VM) when it + // is activated as a Systems Manager managed instance. The name is specified + // as the DefaultInstanceName property using the CreateActivation command. It + // is applied to the managed instance by specifying the Activation Code and + // Activation ID when you install SSM Agent on the instance, as explained in + // Install SSM Agent for a hybrid environment (Linux) (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-managed-linux.html) + // and Install SSM Agent for a hybrid environment (Windows) (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-managed-win.html). + // To retrieve the Name tag of an EC2 instance, use the Amazon EC2 DescribeInstances + // action. For information, see DescribeInstances (http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) + // in the Amazon EC2 API Reference or describe-instances (http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) + // in the AWS CLI Command Reference. Name *string `type:"string"` // Connection status of SSM Agent. @@ -32091,6 +34173,9 @@ type ListCommandsInput struct { Filters []*CommandFilter `min:"1" type:"list"` // (Optional) Lists commands issued against this instance ID. + // + // You can't specify an instance ID in the same command that you specify Status + // = Pending. This is because the command has not reached the instance yet. InstanceId *string `type:"string"` // (Optional) The maximum number of items to return for this call. The call @@ -33595,6 +35680,10 @@ type MaintenanceWindowIdentity struct { // The schedule of the maintenance window in the form of a cron or rate expression. Schedule *string `min:"1" type:"string"` + // The number of days to wait to run a maintenance window after the scheduled + // CRON expression date and time. + ScheduleOffset *int64 `min:"1" type:"integer"` + // The time zone that the scheduled maintenance window executions are based // on, in Internet Assigned Numbers Authority (IANA) format. ScheduleTimezone *string `type:"string"` @@ -33665,6 +35754,12 @@ func (s *MaintenanceWindowIdentity) SetSchedule(v string) *MaintenanceWindowIden return s } +// SetScheduleOffset sets the ScheduleOffset field's value. +func (s *MaintenanceWindowIdentity) SetScheduleOffset(v int64) *MaintenanceWindowIdentity { + s.ScheduleOffset = &v + return s +} + // SetScheduleTimezone sets the ScheduleTimezone field's value. func (s *MaintenanceWindowIdentity) SetScheduleTimezone(v string) *MaintenanceWindowIdentity { s.ScheduleTimezone = &v @@ -37706,9 +39801,9 @@ type PutParameterInput struct { // * aws:ec2:image // // When you create a String parameter and specify aws:ec2:image, Systems Manager - // validates the parameter value you provide against that data type. The required - // format is ami-12345abcdeEXAMPLE. For more information, see Native parameter - // support for Amazon Machine Image IDs (http://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-ec2-aliases.html) + // validates the parameter value is in the required format, such as ami-12345abcdeEXAMPLE, + // and that the specified AMI is available in your AWS account. For more information, + // see Native parameter support for Amazon Machine Image IDs (http://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-ec2-aliases.html) // in the AWS Systems Manager User Guide. DataType *string `type:"string"` @@ -37879,12 +39974,15 @@ type PutParameterInput struct { // The type of parameter that you want to add to the system. // + // SecureString is not currently supported for AWS CloudFormation templates + // or in the China Regions. + // // Items in a StringList must be separated by a comma (,). You can't use other // punctuation or special character to escape items in the list. If you have // a parameter value that requires a comma, then use the String data type. // - // SecureString is not currently supported for AWS CloudFormation templates - // or in the China Regions. + // Specifying a parameter type is not required when updating a parameter. You + // must specify a parameter type when creating a parameter. Type *string `type:"string" enum:"ParameterType"` // The parameter value that you want to add to the system. Standard parameters @@ -40328,11 +42426,18 @@ type SendCommandInput struct { // --document-version "3" DocumentVersion *string `type:"string"` - // The instance IDs where the command should run. You can specify a maximum - // of 50 IDs. If you prefer not to list individual instance IDs, you can instead - // send commands to a fleet of instances using the Targets parameter, which - // accepts EC2 tags. For more information about how to use targets, see Using - // targets and rate controls to send commands to a fleet (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html) + // The IDs of the instances where the command should run. Specifying instance + // IDs is most useful when you are targeting a limited number of instances, + // though you can specify up to 50 IDs. + // + // To target a larger number of instances, or if you prefer not to list individual + // instance IDs, we recommend using the Targets option instead. Using Targets, + // which accepts tag key-value pairs to identify the instances to send commands + // to, you can a send command to tens, hundreds, or thousands of instances at + // once. + // + // For more information about how to use targets, see Using targets and rate + // controls to send commands to a fleet (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html) // in the AWS Systems Manager User Guide. InstanceIds []*string `type:"list"` @@ -40373,10 +42478,17 @@ type SendCommandInput struct { // Service (Amazon SNS) notifications for Run Command commands. ServiceRoleArn *string `type:"string"` - // (Optional) An array of search criteria that targets instances using a Key,Value - // combination that you specify. Targets is required if you don't provide one - // or more instance IDs in the call. For more information about how to use targets, - // see Sending commands to a fleet (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html) + // An array of search criteria that targets instances using a Key,Value combination + // that you specify. Specifying targets is most useful when you want to send + // a command to a large number of instances at once. Using Targets, which accepts + // tag key-value pairs to identify instances, you can send a command to tens, + // hundreds, or thousands of instances at once. + // + // To send a command to a smaller number of instances, you can use the InstanceIds + // option instead. + // + // For more information about how to use targets, see Sending commands to a + // fleet (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html) // in the AWS Systems Manager User Guide. Targets []*Target `type:"list"` @@ -41301,8 +43413,10 @@ type StartSessionInput struct { _ struct{} `type:"structure"` // The name of the SSM document to define the parameters and plugin settings - // for the session. For example, SSM-SessionManagerRunShell. If no document - // name is provided, a shell to the instance is launched by default. + // for the session. For example, SSM-SessionManagerRunShell. You can call the + // GetDocument API to verify the document exists before attempting to start + // a session. If no document name is provided, a shell to the instance is launched + // by default. DocumentName *string `type:"string"` // Reserved for future use. @@ -41942,9 +44056,11 @@ func (s *Tag) SetValue(v string) *Tag { // // * Key=tag-key,Values=my-tag-key-1,my-tag-key-2 // -// * (Maintenance window targets only) Key=resource-groups:Name,Values=resource-group-name +// * Run Command and Maintenance window targets only: Key=resource-groups:Name,Values=resource-group-name +// +// * Maintenance window targets only: Key=resource-groups:ResourceTypeFilters,Values=resource-type-1,resource-type-2 // -// * (Maintenance window targets only) Key=resource-groups:ResourceTypeFilters,Values=resource-type-1,resource-type-2 +// * Automation targets only: Key=ResourceGroup;Values=resource-group-name // // For example: // @@ -41954,20 +44070,22 @@ func (s *Tag) SetValue(v string) *Tag { // // * Key=tag-key,Values=Name,Instance-Type,CostCenter // -// * (Maintenance window targets only) Key=resource-groups:Name,Values=ProductionResourceGroup +// * Run Command and Maintenance window targets only: Key=resource-groups:Name,Values=ProductionResourceGroup // This example demonstrates how to target all resources in the resource // group ProductionResourceGroup in your maintenance window. // -// * (Maintenance window targets only) Key=resource-groups:ResourceTypeFilters,Values=AWS::EC2::INSTANCE,AWS::EC2::VPC +// * Maintenance window targets only: Key=resource-groups:ResourceTypeFilters,Values=AWS::EC2::INSTANCE,AWS::EC2::VPC // This example demonstrates how to target only EC2 instances and VPCs in // your maintenance window. // -// * (State Manager association targets only) Key=InstanceIds,Values=* This +// * Automation targets only: Key=ResourceGroup,Values=MyResourceGroup +// +// * State Manager association targets only: Key=InstanceIds,Values=* This // example demonstrates how to target all managed instances in the AWS Region // where the association was created. // -// For information about how to send commands that target instances using Key,Value -// parameters, see Targeting multiple instances (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html#send-commands-targeting) +// For more information about how to send commands that target instances using +// Key,Value parameters, see Targeting multiple instances (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html#send-commands-targeting) // in the AWS Systems Manager User Guide. type Target struct { _ struct{} `type:"structure"` @@ -42864,6 +44982,18 @@ func (s *UnsupportedPlatformType) RequestID() string { type UpdateAssociationInput struct { _ struct{} `type:"structure"` + // By default, when you update an association, the system runs it immediately + // after it is updated and then according to the schedule you specified. Specify + // this option if you don't want an association to run immediately after you + // update it. + // + // Also, if you specified this option when you created the association, you + // can reset it. To do so, specify the no-apply-only-at-cron-interval parameter + // when you update the association from the command line. This parameter forces + // the association to run immediately after updating it and according to the + // interval specified. + ApplyOnlyAtCronInterval *bool `type:"boolean"` + // The ID of the association you want to update. // // AssociationId is a required field @@ -43011,6 +45141,12 @@ func (s *UpdateAssociationInput) Validate() error { return nil } +// SetApplyOnlyAtCronInterval sets the ApplyOnlyAtCronInterval field's value. +func (s *UpdateAssociationInput) SetApplyOnlyAtCronInterval(v bool) *UpdateAssociationInput { + s.ApplyOnlyAtCronInterval = &v + return s +} + // SetAssociationId sets the AssociationId field's value. func (s *UpdateAssociationInput) SetAssociationId(v string) *UpdateAssociationInput { s.AssociationId = &v @@ -43463,6 +45599,18 @@ type UpdateMaintenanceWindowInput struct { // The schedule of the maintenance window in the form of a cron or rate expression. Schedule *string `min:"1" type:"string"` + // The number of days to wait after the date and time specified by a CRON expression + // before running the maintenance window. + // + // For example, the following cron expression schedules a maintenance window + // to run the third Tuesday of every month at 11:30 PM. + // + // cron(0 30 23 ? * TUE#3 *) + // + // If the schedule offset is 2, the maintenance window won't run until two days + // later. + ScheduleOffset *int64 `min:"1" type:"integer"` + // The time zone that the scheduled maintenance window executions are based // on, in Internet Assigned Numbers Authority (IANA) format. For example: "America/Los_Angeles", // "etc/UTC", or "Asia/Seoul". For more information, see the Time Zone Database @@ -43506,6 +45654,9 @@ func (s *UpdateMaintenanceWindowInput) Validate() error { if s.Schedule != nil && len(*s.Schedule) < 1 { invalidParams.Add(request.NewErrParamMinLen("Schedule", 1)) } + if s.ScheduleOffset != nil && *s.ScheduleOffset < 1 { + invalidParams.Add(request.NewErrParamMinValue("ScheduleOffset", 1)) + } if s.WindowId == nil { invalidParams.Add(request.NewErrParamRequired("WindowId")) } @@ -43573,6 +45724,12 @@ func (s *UpdateMaintenanceWindowInput) SetSchedule(v string) *UpdateMaintenanceW return s } +// SetScheduleOffset sets the ScheduleOffset field's value. +func (s *UpdateMaintenanceWindowInput) SetScheduleOffset(v int64) *UpdateMaintenanceWindowInput { + s.ScheduleOffset = &v + return s +} + // SetScheduleTimezone sets the ScheduleTimezone field's value. func (s *UpdateMaintenanceWindowInput) SetScheduleTimezone(v string) *UpdateMaintenanceWindowInput { s.ScheduleTimezone = &v @@ -43622,6 +45779,10 @@ type UpdateMaintenanceWindowOutput struct { // The schedule of the maintenance window in the form of a cron or rate expression. Schedule *string `min:"1" type:"string"` + // The number of days to wait to run a maintenance window after the scheduled + // CRON expression date and time. + ScheduleOffset *int64 `min:"1" type:"integer"` + // The time zone that the scheduled maintenance window executions are based // on, in Internet Assigned Numbers Authority (IANA) format. For example: "America/Los_Angeles", // "etc/UTC", or "Asia/Seoul". For more information, see the Time Zone Database @@ -43695,6 +45856,12 @@ func (s *UpdateMaintenanceWindowOutput) SetSchedule(v string) *UpdateMaintenance return s } +// SetScheduleOffset sets the ScheduleOffset field's value. +func (s *UpdateMaintenanceWindowOutput) SetScheduleOffset(v int64) *UpdateMaintenanceWindowOutput { + s.ScheduleOffset = &v + return s +} + // SetScheduleTimezone sets the ScheduleTimezone field's value. func (s *UpdateMaintenanceWindowOutput) SetScheduleTimezone(v string) *UpdateMaintenanceWindowOutput { s.ScheduleTimezone = &v @@ -45086,6 +47253,17 @@ const ( AssociationComplianceSeverityUnspecified = "UNSPECIFIED" ) +// AssociationComplianceSeverity_Values returns all elements of the AssociationComplianceSeverity enum +func AssociationComplianceSeverity_Values() []string { + return []string{ + AssociationComplianceSeverityCritical, + AssociationComplianceSeverityHigh, + AssociationComplianceSeverityMedium, + AssociationComplianceSeverityLow, + AssociationComplianceSeverityUnspecified, + } +} + const ( // AssociationExecutionFilterKeyExecutionId is a AssociationExecutionFilterKey enum value AssociationExecutionFilterKeyExecutionId = "ExecutionId" @@ -45097,6 +47275,15 @@ const ( AssociationExecutionFilterKeyCreatedTime = "CreatedTime" ) +// AssociationExecutionFilterKey_Values returns all elements of the AssociationExecutionFilterKey enum +func AssociationExecutionFilterKey_Values() []string { + return []string{ + AssociationExecutionFilterKeyExecutionId, + AssociationExecutionFilterKeyStatus, + AssociationExecutionFilterKeyCreatedTime, + } +} + const ( // AssociationExecutionTargetsFilterKeyStatus is a AssociationExecutionTargetsFilterKey enum value AssociationExecutionTargetsFilterKeyStatus = "Status" @@ -45108,6 +47295,15 @@ const ( AssociationExecutionTargetsFilterKeyResourceType = "ResourceType" ) +// AssociationExecutionTargetsFilterKey_Values returns all elements of the AssociationExecutionTargetsFilterKey enum +func AssociationExecutionTargetsFilterKey_Values() []string { + return []string{ + AssociationExecutionTargetsFilterKeyStatus, + AssociationExecutionTargetsFilterKeyResourceId, + AssociationExecutionTargetsFilterKeyResourceType, + } +} + const ( // AssociationFilterKeyInstanceId is a AssociationFilterKey enum value AssociationFilterKeyInstanceId = "InstanceId" @@ -45134,6 +47330,20 @@ const ( AssociationFilterKeyResourceGroupName = "ResourceGroupName" ) +// AssociationFilterKey_Values returns all elements of the AssociationFilterKey enum +func AssociationFilterKey_Values() []string { + return []string{ + AssociationFilterKeyInstanceId, + AssociationFilterKeyName, + AssociationFilterKeyAssociationId, + AssociationFilterKeyAssociationStatusName, + AssociationFilterKeyLastExecutedBefore, + AssociationFilterKeyLastExecutedAfter, + AssociationFilterKeyAssociationName, + AssociationFilterKeyResourceGroupName, + } +} + const ( // AssociationFilterOperatorTypeEqual is a AssociationFilterOperatorType enum value AssociationFilterOperatorTypeEqual = "EQUAL" @@ -45145,6 +47355,15 @@ const ( AssociationFilterOperatorTypeGreaterThan = "GREATER_THAN" ) +// AssociationFilterOperatorType_Values returns all elements of the AssociationFilterOperatorType enum +func AssociationFilterOperatorType_Values() []string { + return []string{ + AssociationFilterOperatorTypeEqual, + AssociationFilterOperatorTypeLessThan, + AssociationFilterOperatorTypeGreaterThan, + } +} + const ( // AssociationStatusNamePending is a AssociationStatusName enum value AssociationStatusNamePending = "Pending" @@ -45156,6 +47375,15 @@ const ( AssociationStatusNameFailed = "Failed" ) +// AssociationStatusName_Values returns all elements of the AssociationStatusName enum +func AssociationStatusName_Values() []string { + return []string{ + AssociationStatusNamePending, + AssociationStatusNameSuccess, + AssociationStatusNameFailed, + } +} + const ( // AssociationSyncComplianceAuto is a AssociationSyncCompliance enum value AssociationSyncComplianceAuto = "AUTO" @@ -45164,11 +47392,26 @@ const ( AssociationSyncComplianceManual = "MANUAL" ) +// AssociationSyncCompliance_Values returns all elements of the AssociationSyncCompliance enum +func AssociationSyncCompliance_Values() []string { + return []string{ + AssociationSyncComplianceAuto, + AssociationSyncComplianceManual, + } +} + const ( // AttachmentHashTypeSha256 is a AttachmentHashType enum value AttachmentHashTypeSha256 = "Sha256" ) +// AttachmentHashType_Values returns all elements of the AttachmentHashType enum +func AttachmentHashType_Values() []string { + return []string{ + AttachmentHashTypeSha256, + } +} + const ( // AttachmentsSourceKeySourceUrl is a AttachmentsSourceKey enum value AttachmentsSourceKeySourceUrl = "SourceUrl" @@ -45180,6 +47423,15 @@ const ( AttachmentsSourceKeyAttachmentReference = "AttachmentReference" ) +// AttachmentsSourceKey_Values returns all elements of the AttachmentsSourceKey enum +func AttachmentsSourceKey_Values() []string { + return []string{ + AttachmentsSourceKeySourceUrl, + AttachmentsSourceKeyS3fileUrl, + AttachmentsSourceKeyAttachmentReference, + } +} + const ( // AutomationExecutionFilterKeyDocumentNamePrefix is a AutomationExecutionFilterKey enum value AutomationExecutionFilterKeyDocumentNamePrefix = "DocumentNamePrefix" @@ -45209,6 +47461,21 @@ const ( AutomationExecutionFilterKeyTagKey = "TagKey" ) +// AutomationExecutionFilterKey_Values returns all elements of the AutomationExecutionFilterKey enum +func AutomationExecutionFilterKey_Values() []string { + return []string{ + AutomationExecutionFilterKeyDocumentNamePrefix, + AutomationExecutionFilterKeyExecutionStatus, + AutomationExecutionFilterKeyExecutionId, + AutomationExecutionFilterKeyParentExecutionId, + AutomationExecutionFilterKeyCurrentAction, + AutomationExecutionFilterKeyStartTimeBefore, + AutomationExecutionFilterKeyStartTimeAfter, + AutomationExecutionFilterKeyAutomationType, + AutomationExecutionFilterKeyTagKey, + } +} + const ( // AutomationExecutionStatusPending is a AutomationExecutionStatus enum value AutomationExecutionStatusPending = "Pending" @@ -45235,6 +47502,20 @@ const ( AutomationExecutionStatusFailed = "Failed" ) +// AutomationExecutionStatus_Values returns all elements of the AutomationExecutionStatus enum +func AutomationExecutionStatus_Values() []string { + return []string{ + AutomationExecutionStatusPending, + AutomationExecutionStatusInProgress, + AutomationExecutionStatusWaiting, + AutomationExecutionStatusSuccess, + AutomationExecutionStatusTimedOut, + AutomationExecutionStatusCancelling, + AutomationExecutionStatusCancelled, + AutomationExecutionStatusFailed, + } +} + const ( // AutomationTypeCrossAccount is a AutomationType enum value AutomationTypeCrossAccount = "CrossAccount" @@ -45243,6 +47524,14 @@ const ( AutomationTypeLocal = "Local" ) +// AutomationType_Values returns all elements of the AutomationType enum +func AutomationType_Values() []string { + return []string{ + AutomationTypeCrossAccount, + AutomationTypeLocal, + } +} + const ( // CalendarStateOpen is a CalendarState enum value CalendarStateOpen = "OPEN" @@ -45251,6 +47540,14 @@ const ( CalendarStateClosed = "CLOSED" ) +// CalendarState_Values returns all elements of the CalendarState enum +func CalendarState_Values() []string { + return []string{ + CalendarStateOpen, + CalendarStateClosed, + } +} + const ( // CommandFilterKeyInvokedAfter is a CommandFilterKey enum value CommandFilterKeyInvokedAfter = "InvokedAfter" @@ -45268,6 +47565,17 @@ const ( CommandFilterKeyDocumentName = "DocumentName" ) +// CommandFilterKey_Values returns all elements of the CommandFilterKey enum +func CommandFilterKey_Values() []string { + return []string{ + CommandFilterKeyInvokedAfter, + CommandFilterKeyInvokedBefore, + CommandFilterKeyStatus, + CommandFilterKeyExecutionStage, + CommandFilterKeyDocumentName, + } +} + const ( // CommandInvocationStatusPending is a CommandInvocationStatus enum value CommandInvocationStatusPending = "Pending" @@ -45294,6 +47602,20 @@ const ( CommandInvocationStatusCancelling = "Cancelling" ) +// CommandInvocationStatus_Values returns all elements of the CommandInvocationStatus enum +func CommandInvocationStatus_Values() []string { + return []string{ + CommandInvocationStatusPending, + CommandInvocationStatusInProgress, + CommandInvocationStatusDelayed, + CommandInvocationStatusSuccess, + CommandInvocationStatusCancelled, + CommandInvocationStatusTimedOut, + CommandInvocationStatusFailed, + CommandInvocationStatusCancelling, + } +} + const ( // CommandPluginStatusPending is a CommandPluginStatus enum value CommandPluginStatusPending = "Pending" @@ -45314,6 +47636,18 @@ const ( CommandPluginStatusFailed = "Failed" ) +// CommandPluginStatus_Values returns all elements of the CommandPluginStatus enum +func CommandPluginStatus_Values() []string { + return []string{ + CommandPluginStatusPending, + CommandPluginStatusInProgress, + CommandPluginStatusSuccess, + CommandPluginStatusTimedOut, + CommandPluginStatusCancelled, + CommandPluginStatusFailed, + } +} + const ( // CommandStatusPending is a CommandStatus enum value CommandStatusPending = "Pending" @@ -45337,6 +47671,19 @@ const ( CommandStatusCancelling = "Cancelling" ) +// CommandStatus_Values returns all elements of the CommandStatus enum +func CommandStatus_Values() []string { + return []string{ + CommandStatusPending, + CommandStatusInProgress, + CommandStatusSuccess, + CommandStatusCancelled, + CommandStatusFailed, + CommandStatusTimedOut, + CommandStatusCancelling, + } +} + const ( // ComplianceQueryOperatorTypeEqual is a ComplianceQueryOperatorType enum value ComplianceQueryOperatorTypeEqual = "EQUAL" @@ -45354,6 +47701,17 @@ const ( ComplianceQueryOperatorTypeGreaterThan = "GREATER_THAN" ) +// ComplianceQueryOperatorType_Values returns all elements of the ComplianceQueryOperatorType enum +func ComplianceQueryOperatorType_Values() []string { + return []string{ + ComplianceQueryOperatorTypeEqual, + ComplianceQueryOperatorTypeNotEqual, + ComplianceQueryOperatorTypeBeginWith, + ComplianceQueryOperatorTypeLessThan, + ComplianceQueryOperatorTypeGreaterThan, + } +} + const ( // ComplianceSeverityCritical is a ComplianceSeverity enum value ComplianceSeverityCritical = "CRITICAL" @@ -45374,6 +47732,18 @@ const ( ComplianceSeverityUnspecified = "UNSPECIFIED" ) +// ComplianceSeverity_Values returns all elements of the ComplianceSeverity enum +func ComplianceSeverity_Values() []string { + return []string{ + ComplianceSeverityCritical, + ComplianceSeverityHigh, + ComplianceSeverityMedium, + ComplianceSeverityLow, + ComplianceSeverityInformational, + ComplianceSeverityUnspecified, + } +} + const ( // ComplianceStatusCompliant is a ComplianceStatus enum value ComplianceStatusCompliant = "COMPLIANT" @@ -45382,6 +47752,14 @@ const ( ComplianceStatusNonCompliant = "NON_COMPLIANT" ) +// ComplianceStatus_Values returns all elements of the ComplianceStatus enum +func ComplianceStatus_Values() []string { + return []string{ + ComplianceStatusCompliant, + ComplianceStatusNonCompliant, + } +} + const ( // ComplianceUploadTypeComplete is a ComplianceUploadType enum value ComplianceUploadTypeComplete = "COMPLETE" @@ -45390,6 +47768,14 @@ const ( ComplianceUploadTypePartial = "PARTIAL" ) +// ComplianceUploadType_Values returns all elements of the ComplianceUploadType enum +func ComplianceUploadType_Values() []string { + return []string{ + ComplianceUploadTypeComplete, + ComplianceUploadTypePartial, + } +} + const ( // ConnectionStatusConnected is a ConnectionStatus enum value ConnectionStatusConnected = "Connected" @@ -45398,6 +47784,14 @@ const ( ConnectionStatusNotConnected = "NotConnected" ) +// ConnectionStatus_Values returns all elements of the ConnectionStatus enum +func ConnectionStatus_Values() []string { + return []string{ + ConnectionStatusConnected, + ConnectionStatusNotConnected, + } +} + const ( // DescribeActivationsFilterKeysActivationIds is a DescribeActivationsFilterKeys enum value DescribeActivationsFilterKeysActivationIds = "ActivationIds" @@ -45409,6 +47803,15 @@ const ( DescribeActivationsFilterKeysIamRole = "IamRole" ) +// DescribeActivationsFilterKeys_Values returns all elements of the DescribeActivationsFilterKeys enum +func DescribeActivationsFilterKeys_Values() []string { + return []string{ + DescribeActivationsFilterKeysActivationIds, + DescribeActivationsFilterKeysDefaultInstanceName, + DescribeActivationsFilterKeysIamRole, + } +} + const ( // DocumentFilterKeyName is a DocumentFilterKey enum value DocumentFilterKeyName = "Name" @@ -45423,6 +47826,16 @@ const ( DocumentFilterKeyDocumentType = "DocumentType" ) +// DocumentFilterKey_Values returns all elements of the DocumentFilterKey enum +func DocumentFilterKey_Values() []string { + return []string{ + DocumentFilterKeyName, + DocumentFilterKeyOwner, + DocumentFilterKeyPlatformTypes, + DocumentFilterKeyDocumentType, + } +} + const ( // DocumentFormatYaml is a DocumentFormat enum value DocumentFormatYaml = "YAML" @@ -45434,6 +47847,15 @@ const ( DocumentFormatText = "TEXT" ) +// DocumentFormat_Values returns all elements of the DocumentFormat enum +func DocumentFormat_Values() []string { + return []string{ + DocumentFormatYaml, + DocumentFormatJson, + DocumentFormatText, + } +} + const ( // DocumentHashTypeSha256 is a DocumentHashType enum value DocumentHashTypeSha256 = "Sha256" @@ -45442,6 +47864,14 @@ const ( DocumentHashTypeSha1 = "Sha1" ) +// DocumentHashType_Values returns all elements of the DocumentHashType enum +func DocumentHashType_Values() []string { + return []string{ + DocumentHashTypeSha256, + DocumentHashTypeSha1, + } +} + const ( // DocumentParameterTypeString is a DocumentParameterType enum value DocumentParameterTypeString = "String" @@ -45450,11 +47880,26 @@ const ( DocumentParameterTypeStringList = "StringList" ) +// DocumentParameterType_Values returns all elements of the DocumentParameterType enum +func DocumentParameterType_Values() []string { + return []string{ + DocumentParameterTypeString, + DocumentParameterTypeStringList, + } +} + const ( // DocumentPermissionTypeShare is a DocumentPermissionType enum value DocumentPermissionTypeShare = "Share" ) +// DocumentPermissionType_Values returns all elements of the DocumentPermissionType enum +func DocumentPermissionType_Values() []string { + return []string{ + DocumentPermissionTypeShare, + } +} + // The status of a document. const ( // DocumentStatusCreating is a DocumentStatus enum value @@ -45473,6 +47918,17 @@ const ( DocumentStatusFailed = "Failed" ) +// DocumentStatus_Values returns all elements of the DocumentStatus enum +func DocumentStatus_Values() []string { + return []string{ + DocumentStatusCreating, + DocumentStatusActive, + DocumentStatusUpdating, + DocumentStatusDeleting, + DocumentStatusFailed, + } +} + const ( // DocumentTypeCommand is a DocumentType enum value DocumentTypeCommand = "Command" @@ -45502,6 +47958,21 @@ const ( DocumentTypeChangeCalendar = "ChangeCalendar" ) +// DocumentType_Values returns all elements of the DocumentType enum +func DocumentType_Values() []string { + return []string{ + DocumentTypeCommand, + DocumentTypePolicy, + DocumentTypeAutomation, + DocumentTypeSession, + DocumentTypePackage, + DocumentTypeApplicationConfiguration, + DocumentTypeApplicationConfigurationSchema, + DocumentTypeDeploymentStrategy, + DocumentTypeChangeCalendar, + } +} + const ( // ExecutionModeAuto is a ExecutionMode enum value ExecutionModeAuto = "Auto" @@ -45510,6 +47981,14 @@ const ( ExecutionModeInteractive = "Interactive" ) +// ExecutionMode_Values returns all elements of the ExecutionMode enum +func ExecutionMode_Values() []string { + return []string{ + ExecutionModeAuto, + ExecutionModeInteractive, + } +} + const ( // FaultClient is a Fault enum value FaultClient = "Client" @@ -45521,6 +48000,15 @@ const ( FaultUnknown = "Unknown" ) +// Fault_Values returns all elements of the Fault enum +func Fault_Values() []string { + return []string{ + FaultClient, + FaultServer, + FaultUnknown, + } +} + const ( // InstanceInformationFilterKeyInstanceIds is a InstanceInformationFilterKey enum value InstanceInformationFilterKeyInstanceIds = "InstanceIds" @@ -45547,6 +48035,20 @@ const ( InstanceInformationFilterKeyAssociationStatus = "AssociationStatus" ) +// InstanceInformationFilterKey_Values returns all elements of the InstanceInformationFilterKey enum +func InstanceInformationFilterKey_Values() []string { + return []string{ + InstanceInformationFilterKeyInstanceIds, + InstanceInformationFilterKeyAgentVersion, + InstanceInformationFilterKeyPingStatus, + InstanceInformationFilterKeyPlatformTypes, + InstanceInformationFilterKeyActivationIds, + InstanceInformationFilterKeyIamRole, + InstanceInformationFilterKeyResourceType, + InstanceInformationFilterKeyAssociationStatus, + } +} + const ( // InstancePatchStateOperatorTypeEqual is a InstancePatchStateOperatorType enum value InstancePatchStateOperatorTypeEqual = "Equal" @@ -45561,6 +48063,16 @@ const ( InstancePatchStateOperatorTypeGreaterThan = "GreaterThan" ) +// InstancePatchStateOperatorType_Values returns all elements of the InstancePatchStateOperatorType enum +func InstancePatchStateOperatorType_Values() []string { + return []string{ + InstancePatchStateOperatorTypeEqual, + InstancePatchStateOperatorTypeNotEqual, + InstancePatchStateOperatorTypeLessThan, + InstancePatchStateOperatorTypeGreaterThan, + } +} + const ( // InventoryAttributeDataTypeString is a InventoryAttributeDataType enum value InventoryAttributeDataTypeString = "string" @@ -45569,6 +48081,14 @@ const ( InventoryAttributeDataTypeNumber = "number" ) +// InventoryAttributeDataType_Values returns all elements of the InventoryAttributeDataType enum +func InventoryAttributeDataType_Values() []string { + return []string{ + InventoryAttributeDataTypeString, + InventoryAttributeDataTypeNumber, + } +} + const ( // InventoryDeletionStatusInProgress is a InventoryDeletionStatus enum value InventoryDeletionStatusInProgress = "InProgress" @@ -45577,6 +48097,14 @@ const ( InventoryDeletionStatusComplete = "Complete" ) +// InventoryDeletionStatus_Values returns all elements of the InventoryDeletionStatus enum +func InventoryDeletionStatus_Values() []string { + return []string{ + InventoryDeletionStatusInProgress, + InventoryDeletionStatusComplete, + } +} + const ( // InventoryQueryOperatorTypeEqual is a InventoryQueryOperatorType enum value InventoryQueryOperatorTypeEqual = "Equal" @@ -45597,6 +48125,18 @@ const ( InventoryQueryOperatorTypeExists = "Exists" ) +// InventoryQueryOperatorType_Values returns all elements of the InventoryQueryOperatorType enum +func InventoryQueryOperatorType_Values() []string { + return []string{ + InventoryQueryOperatorTypeEqual, + InventoryQueryOperatorTypeNotEqual, + InventoryQueryOperatorTypeBeginWith, + InventoryQueryOperatorTypeLessThan, + InventoryQueryOperatorTypeGreaterThan, + InventoryQueryOperatorTypeExists, + } +} + const ( // InventorySchemaDeleteOptionDisableSchema is a InventorySchemaDeleteOption enum value InventorySchemaDeleteOptionDisableSchema = "DisableSchema" @@ -45605,6 +48145,14 @@ const ( InventorySchemaDeleteOptionDeleteSchema = "DeleteSchema" ) +// InventorySchemaDeleteOption_Values returns all elements of the InventorySchemaDeleteOption enum +func InventorySchemaDeleteOption_Values() []string { + return []string{ + InventorySchemaDeleteOptionDisableSchema, + InventorySchemaDeleteOptionDeleteSchema, + } +} + const ( // LastResourceDataSyncStatusSuccessful is a LastResourceDataSyncStatus enum value LastResourceDataSyncStatusSuccessful = "Successful" @@ -45616,6 +48164,15 @@ const ( LastResourceDataSyncStatusInProgress = "InProgress" ) +// LastResourceDataSyncStatus_Values returns all elements of the LastResourceDataSyncStatus enum +func LastResourceDataSyncStatus_Values() []string { + return []string{ + LastResourceDataSyncStatusSuccessful, + LastResourceDataSyncStatusFailed, + LastResourceDataSyncStatusInProgress, + } +} + const ( // MaintenanceWindowExecutionStatusPending is a MaintenanceWindowExecutionStatus enum value MaintenanceWindowExecutionStatusPending = "PENDING" @@ -45642,6 +48199,20 @@ const ( MaintenanceWindowExecutionStatusSkippedOverlapping = "SKIPPED_OVERLAPPING" ) +// MaintenanceWindowExecutionStatus_Values returns all elements of the MaintenanceWindowExecutionStatus enum +func MaintenanceWindowExecutionStatus_Values() []string { + return []string{ + MaintenanceWindowExecutionStatusPending, + MaintenanceWindowExecutionStatusInProgress, + MaintenanceWindowExecutionStatusSuccess, + MaintenanceWindowExecutionStatusFailed, + MaintenanceWindowExecutionStatusTimedOut, + MaintenanceWindowExecutionStatusCancelling, + MaintenanceWindowExecutionStatusCancelled, + MaintenanceWindowExecutionStatusSkippedOverlapping, + } +} + const ( // MaintenanceWindowResourceTypeInstance is a MaintenanceWindowResourceType enum value MaintenanceWindowResourceTypeInstance = "INSTANCE" @@ -45650,6 +48221,14 @@ const ( MaintenanceWindowResourceTypeResourceGroup = "RESOURCE_GROUP" ) +// MaintenanceWindowResourceType_Values returns all elements of the MaintenanceWindowResourceType enum +func MaintenanceWindowResourceType_Values() []string { + return []string{ + MaintenanceWindowResourceTypeInstance, + MaintenanceWindowResourceTypeResourceGroup, + } +} + const ( // MaintenanceWindowTaskTypeRunCommand is a MaintenanceWindowTaskType enum value MaintenanceWindowTaskTypeRunCommand = "RUN_COMMAND" @@ -45664,6 +48243,16 @@ const ( MaintenanceWindowTaskTypeLambda = "LAMBDA" ) +// MaintenanceWindowTaskType_Values returns all elements of the MaintenanceWindowTaskType enum +func MaintenanceWindowTaskType_Values() []string { + return []string{ + MaintenanceWindowTaskTypeRunCommand, + MaintenanceWindowTaskTypeAutomation, + MaintenanceWindowTaskTypeStepFunctions, + MaintenanceWindowTaskTypeLambda, + } +} + const ( // NotificationEventAll is a NotificationEvent enum value NotificationEventAll = "All" @@ -45684,6 +48273,18 @@ const ( NotificationEventFailed = "Failed" ) +// NotificationEvent_Values returns all elements of the NotificationEvent enum +func NotificationEvent_Values() []string { + return []string{ + NotificationEventAll, + NotificationEventInProgress, + NotificationEventSuccess, + NotificationEventTimedOut, + NotificationEventCancelled, + NotificationEventFailed, + } +} + const ( // NotificationTypeCommand is a NotificationType enum value NotificationTypeCommand = "Command" @@ -45692,6 +48293,14 @@ const ( NotificationTypeInvocation = "Invocation" ) +// NotificationType_Values returns all elements of the NotificationType enum +func NotificationType_Values() []string { + return []string{ + NotificationTypeCommand, + NotificationTypeInvocation, + } +} + const ( // OperatingSystemWindows is a OperatingSystem enum value OperatingSystemWindows = "WINDOWS" @@ -45713,8 +48322,29 @@ const ( // OperatingSystemCentos is a OperatingSystem enum value OperatingSystemCentos = "CENTOS" + + // OperatingSystemOracleLinux is a OperatingSystem enum value + OperatingSystemOracleLinux = "ORACLE_LINUX" + + // OperatingSystemDebian is a OperatingSystem enum value + OperatingSystemDebian = "DEBIAN" ) +// OperatingSystem_Values returns all elements of the OperatingSystem enum +func OperatingSystem_Values() []string { + return []string{ + OperatingSystemWindows, + OperatingSystemAmazonLinux, + OperatingSystemAmazonLinux2, + OperatingSystemUbuntu, + OperatingSystemRedhatEnterpriseLinux, + OperatingSystemSuse, + OperatingSystemCentos, + OperatingSystemOracleLinux, + OperatingSystemDebian, + } +} + const ( // OpsFilterOperatorTypeEqual is a OpsFilterOperatorType enum value OpsFilterOperatorTypeEqual = "Equal" @@ -45735,6 +48365,18 @@ const ( OpsFilterOperatorTypeExists = "Exists" ) +// OpsFilterOperatorType_Values returns all elements of the OpsFilterOperatorType enum +func OpsFilterOperatorType_Values() []string { + return []string{ + OpsFilterOperatorTypeEqual, + OpsFilterOperatorTypeNotEqual, + OpsFilterOperatorTypeBeginWith, + OpsFilterOperatorTypeLessThan, + OpsFilterOperatorTypeGreaterThan, + OpsFilterOperatorTypeExists, + } +} + const ( // OpsItemDataTypeSearchableString is a OpsItemDataType enum value OpsItemDataTypeSearchableString = "SearchableString" @@ -45743,6 +48385,14 @@ const ( OpsItemDataTypeString = "String" ) +// OpsItemDataType_Values returns all elements of the OpsItemDataType enum +func OpsItemDataType_Values() []string { + return []string{ + OpsItemDataTypeSearchableString, + OpsItemDataTypeString, + } +} + const ( // OpsItemFilterKeyStatus is a OpsItemFilterKey enum value OpsItemFilterKeyStatus = "Status" @@ -45790,6 +48440,27 @@ const ( OpsItemFilterKeySeverity = "Severity" ) +// OpsItemFilterKey_Values returns all elements of the OpsItemFilterKey enum +func OpsItemFilterKey_Values() []string { + return []string{ + OpsItemFilterKeyStatus, + OpsItemFilterKeyCreatedBy, + OpsItemFilterKeySource, + OpsItemFilterKeyPriority, + OpsItemFilterKeyTitle, + OpsItemFilterKeyOpsItemId, + OpsItemFilterKeyCreatedTime, + OpsItemFilterKeyLastModifiedTime, + OpsItemFilterKeyOperationalData, + OpsItemFilterKeyOperationalDataKey, + OpsItemFilterKeyOperationalDataValue, + OpsItemFilterKeyResourceId, + OpsItemFilterKeyAutomationId, + OpsItemFilterKeyCategory, + OpsItemFilterKeySeverity, + } +} + const ( // OpsItemFilterOperatorEqual is a OpsItemFilterOperator enum value OpsItemFilterOperatorEqual = "Equal" @@ -45804,6 +48475,16 @@ const ( OpsItemFilterOperatorLessThan = "LessThan" ) +// OpsItemFilterOperator_Values returns all elements of the OpsItemFilterOperator enum +func OpsItemFilterOperator_Values() []string { + return []string{ + OpsItemFilterOperatorEqual, + OpsItemFilterOperatorContains, + OpsItemFilterOperatorGreaterThan, + OpsItemFilterOperatorLessThan, + } +} + const ( // OpsItemStatusOpen is a OpsItemStatus enum value OpsItemStatusOpen = "Open" @@ -45815,6 +48496,15 @@ const ( OpsItemStatusResolved = "Resolved" ) +// OpsItemStatus_Values returns all elements of the OpsItemStatus enum +func OpsItemStatus_Values() []string { + return []string{ + OpsItemStatusOpen, + OpsItemStatusInProgress, + OpsItemStatusResolved, + } +} + const ( // ParameterTierStandard is a ParameterTier enum value ParameterTierStandard = "Standard" @@ -45826,6 +48516,15 @@ const ( ParameterTierIntelligentTiering = "Intelligent-Tiering" ) +// ParameterTier_Values returns all elements of the ParameterTier enum +func ParameterTier_Values() []string { + return []string{ + ParameterTierStandard, + ParameterTierAdvanced, + ParameterTierIntelligentTiering, + } +} + const ( // ParameterTypeString is a ParameterType enum value ParameterTypeString = "String" @@ -45837,6 +48536,15 @@ const ( ParameterTypeSecureString = "SecureString" ) +// ParameterType_Values returns all elements of the ParameterType enum +func ParameterType_Values() []string { + return []string{ + ParameterTypeString, + ParameterTypeStringList, + ParameterTypeSecureString, + } +} + const ( // ParametersFilterKeyName is a ParametersFilterKey enum value ParametersFilterKeyName = "Name" @@ -45848,6 +48556,15 @@ const ( ParametersFilterKeyKeyId = "KeyId" ) +// ParametersFilterKey_Values returns all elements of the ParametersFilterKey enum +func ParametersFilterKey_Values() []string { + return []string{ + ParametersFilterKeyName, + ParametersFilterKeyType, + ParametersFilterKeyKeyId, + } +} + const ( // PatchActionAllowAsDependency is a PatchAction enum value PatchActionAllowAsDependency = "ALLOW_AS_DEPENDENCY" @@ -45856,6 +48573,14 @@ const ( PatchActionBlock = "BLOCK" ) +// PatchAction_Values returns all elements of the PatchAction enum +func PatchAction_Values() []string { + return []string{ + PatchActionAllowAsDependency, + PatchActionBlock, + } +} + const ( // PatchComplianceDataStateInstalled is a PatchComplianceDataState enum value PatchComplianceDataStateInstalled = "INSTALLED" @@ -45879,6 +48604,19 @@ const ( PatchComplianceDataStateFailed = "FAILED" ) +// PatchComplianceDataState_Values returns all elements of the PatchComplianceDataState enum +func PatchComplianceDataState_Values() []string { + return []string{ + PatchComplianceDataStateInstalled, + PatchComplianceDataStateInstalledOther, + PatchComplianceDataStateInstalledPendingReboot, + PatchComplianceDataStateInstalledRejected, + PatchComplianceDataStateMissing, + PatchComplianceDataStateNotApplicable, + PatchComplianceDataStateFailed, + } +} + const ( // PatchComplianceLevelCritical is a PatchComplianceLevel enum value PatchComplianceLevelCritical = "CRITICAL" @@ -45899,6 +48637,18 @@ const ( PatchComplianceLevelUnspecified = "UNSPECIFIED" ) +// PatchComplianceLevel_Values returns all elements of the PatchComplianceLevel enum +func PatchComplianceLevel_Values() []string { + return []string{ + PatchComplianceLevelCritical, + PatchComplianceLevelHigh, + PatchComplianceLevelMedium, + PatchComplianceLevelLow, + PatchComplianceLevelInformational, + PatchComplianceLevelUnspecified, + } +} + const ( // PatchDeploymentStatusApproved is a PatchDeploymentStatus enum value PatchDeploymentStatusApproved = "APPROVED" @@ -45913,6 +48663,16 @@ const ( PatchDeploymentStatusExplicitRejected = "EXPLICIT_REJECTED" ) +// PatchDeploymentStatus_Values returns all elements of the PatchDeploymentStatus enum +func PatchDeploymentStatus_Values() []string { + return []string{ + PatchDeploymentStatusApproved, + PatchDeploymentStatusPendingApproval, + PatchDeploymentStatusExplicitApproved, + PatchDeploymentStatusExplicitRejected, + } +} + const ( // PatchFilterKeyPatchSet is a PatchFilterKey enum value PatchFilterKeyPatchSet = "PATCH_SET" @@ -45942,6 +48702,21 @@ const ( PatchFilterKeySeverity = "SEVERITY" ) +// PatchFilterKey_Values returns all elements of the PatchFilterKey enum +func PatchFilterKey_Values() []string { + return []string{ + PatchFilterKeyPatchSet, + PatchFilterKeyProduct, + PatchFilterKeyProductFamily, + PatchFilterKeyClassification, + PatchFilterKeyMsrcSeverity, + PatchFilterKeyPatchId, + PatchFilterKeySection, + PatchFilterKeyPriority, + PatchFilterKeySeverity, + } +} + const ( // PatchOperationTypeScan is a PatchOperationType enum value PatchOperationTypeScan = "Scan" @@ -45950,6 +48725,14 @@ const ( PatchOperationTypeInstall = "Install" ) +// PatchOperationType_Values returns all elements of the PatchOperationType enum +func PatchOperationType_Values() []string { + return []string{ + PatchOperationTypeScan, + PatchOperationTypeInstall, + } +} + const ( // PatchPropertyProduct is a PatchProperty enum value PatchPropertyProduct = "PRODUCT" @@ -45970,6 +48753,18 @@ const ( PatchPropertySeverity = "SEVERITY" ) +// PatchProperty_Values returns all elements of the PatchProperty enum +func PatchProperty_Values() []string { + return []string{ + PatchPropertyProduct, + PatchPropertyProductFamily, + PatchPropertyClassification, + PatchPropertyMsrcSeverity, + PatchPropertyPriority, + PatchPropertySeverity, + } +} + const ( // PatchSetOs is a PatchSet enum value PatchSetOs = "OS" @@ -45978,6 +48773,14 @@ const ( PatchSetApplication = "APPLICATION" ) +// PatchSet_Values returns all elements of the PatchSet enum +func PatchSet_Values() []string { + return []string{ + PatchSetOs, + PatchSetApplication, + } +} + const ( // PingStatusOnline is a PingStatus enum value PingStatusOnline = "Online" @@ -45989,6 +48792,15 @@ const ( PingStatusInactive = "Inactive" ) +// PingStatus_Values returns all elements of the PingStatus enum +func PingStatus_Values() []string { + return []string{ + PingStatusOnline, + PingStatusConnectionLost, + PingStatusInactive, + } +} + const ( // PlatformTypeWindows is a PlatformType enum value PlatformTypeWindows = "Windows" @@ -45997,6 +48809,14 @@ const ( PlatformTypeLinux = "Linux" ) +// PlatformType_Values returns all elements of the PlatformType enum +func PlatformType_Values() []string { + return []string{ + PlatformTypeWindows, + PlatformTypeLinux, + } +} + const ( // RebootOptionRebootIfNeeded is a RebootOption enum value RebootOptionRebootIfNeeded = "RebootIfNeeded" @@ -46005,11 +48825,26 @@ const ( RebootOptionNoReboot = "NoReboot" ) +// RebootOption_Values returns all elements of the RebootOption enum +func RebootOption_Values() []string { + return []string{ + RebootOptionRebootIfNeeded, + RebootOptionNoReboot, + } +} + const ( // ResourceDataSyncS3FormatJsonSerDe is a ResourceDataSyncS3Format enum value ResourceDataSyncS3FormatJsonSerDe = "JsonSerDe" ) +// ResourceDataSyncS3Format_Values returns all elements of the ResourceDataSyncS3Format enum +func ResourceDataSyncS3Format_Values() []string { + return []string{ + ResourceDataSyncS3FormatJsonSerDe, + } +} + const ( // ResourceTypeManagedInstance is a ResourceType enum value ResourceTypeManagedInstance = "ManagedInstance" @@ -46021,6 +48856,15 @@ const ( ResourceTypeEc2instance = "EC2Instance" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeManagedInstance, + ResourceTypeDocument, + ResourceTypeEc2instance, + } +} + const ( // ResourceTypeForTaggingDocument is a ResourceTypeForTagging enum value ResourceTypeForTaggingDocument = "Document" @@ -46041,6 +48885,18 @@ const ( ResourceTypeForTaggingOpsItem = "OpsItem" ) +// ResourceTypeForTagging_Values returns all elements of the ResourceTypeForTagging enum +func ResourceTypeForTagging_Values() []string { + return []string{ + ResourceTypeForTaggingDocument, + ResourceTypeForTaggingManagedInstance, + ResourceTypeForTaggingMaintenanceWindow, + ResourceTypeForTaggingParameter, + ResourceTypeForTaggingPatchBaseline, + ResourceTypeForTaggingOpsItem, + } +} + const ( // SessionFilterKeyInvokedAfter is a SessionFilterKey enum value SessionFilterKeyInvokedAfter = "InvokedAfter" @@ -46058,6 +48914,17 @@ const ( SessionFilterKeyStatus = "Status" ) +// SessionFilterKey_Values returns all elements of the SessionFilterKey enum +func SessionFilterKey_Values() []string { + return []string{ + SessionFilterKeyInvokedAfter, + SessionFilterKeyInvokedBefore, + SessionFilterKeyTarget, + SessionFilterKeyOwner, + SessionFilterKeyStatus, + } +} + const ( // SessionStateActive is a SessionState enum value SessionStateActive = "Active" @@ -46066,6 +48933,14 @@ const ( SessionStateHistory = "History" ) +// SessionState_Values returns all elements of the SessionState enum +func SessionState_Values() []string { + return []string{ + SessionStateActive, + SessionStateHistory, + } +} + const ( // SessionStatusConnected is a SessionStatus enum value SessionStatusConnected = "Connected" @@ -46086,6 +48961,18 @@ const ( SessionStatusFailed = "Failed" ) +// SessionStatus_Values returns all elements of the SessionStatus enum +func SessionStatus_Values() []string { + return []string{ + SessionStatusConnected, + SessionStatusConnecting, + SessionStatusDisconnected, + SessionStatusTerminated, + SessionStatusTerminating, + SessionStatusFailed, + } +} + const ( // SignalTypeApprove is a SignalType enum value SignalTypeApprove = "Approve" @@ -46103,6 +48990,17 @@ const ( SignalTypeResume = "Resume" ) +// SignalType_Values returns all elements of the SignalType enum +func SignalType_Values() []string { + return []string{ + SignalTypeApprove, + SignalTypeReject, + SignalTypeStartStep, + SignalTypeStopStep, + SignalTypeResume, + } +} + const ( // StepExecutionFilterKeyStartTimeBefore is a StepExecutionFilterKey enum value StepExecutionFilterKeyStartTimeBefore = "StartTimeBefore" @@ -46123,6 +49021,18 @@ const ( StepExecutionFilterKeyAction = "Action" ) +// StepExecutionFilterKey_Values returns all elements of the StepExecutionFilterKey enum +func StepExecutionFilterKey_Values() []string { + return []string{ + StepExecutionFilterKeyStartTimeBefore, + StepExecutionFilterKeyStartTimeAfter, + StepExecutionFilterKeyStepExecutionStatus, + StepExecutionFilterKeyStepExecutionId, + StepExecutionFilterKeyStepName, + StepExecutionFilterKeyAction, + } +} + const ( // StopTypeComplete is a StopType enum value StopTypeComplete = "Complete" @@ -46130,3 +49040,11 @@ const ( // StopTypeCancel is a StopType enum value StopTypeCancel = "Cancel" ) + +// StopType_Values returns all elements of the StopType enum +func StopType_Values() []string { + return []string{ + StopTypeComplete, + StopTypeCancel, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssm/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/ssm/waiters.go new file mode 100644 index 00000000000..4bc0d1401d9 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/ssm/waiters.go @@ -0,0 +1,91 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package ssm + +import ( + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" +) + +// WaitUntilCommandExecuted uses the Amazon SSM API operation +// GetCommandInvocation to wait for a condition to be met before returning. +// If the condition is not met within the max attempt window, an error will +// be returned. +func (c *SSM) WaitUntilCommandExecuted(input *GetCommandInvocationInput) error { + return c.WaitUntilCommandExecutedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilCommandExecutedWithContext is an extended version of WaitUntilCommandExecuted. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *SSM) WaitUntilCommandExecutedWithContext(ctx aws.Context, input *GetCommandInvocationInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilCommandExecuted", + MaxAttempts: 20, + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Pending", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "InProgress", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Delayed", + }, + { + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Success", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Cancelled", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "TimedOut", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Failed", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Cancelling", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *GetCommandInvocationInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetCommandInvocationRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + w.ApplyOptions(opts...) + + return w.WaitWithContext(ctx) +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/storagegateway/api.go b/vendor/github.com/aws/aws-sdk-go/service/storagegateway/api.go index b05c45073b4..c37fd26b4cf 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/storagegateway/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/storagegateway/api.go @@ -60,8 +60,8 @@ func (c *StorageGateway) ActivateGatewayRequest(input *ActivateGatewayInput) (re // process, you specify information such as the AWS Region that you want to // use for storing snapshots or tapes, the time zone for scheduled snapshots // the gateway snapshot schedule window, an activation key, and a name for your -// gateway. The activation process also associates your gateway with your account; -// for more information, see UpdateGatewayInformation. +// gateway. The activation process also associates your gateway with your account. +// For more information, see UpdateGatewayInformation. // // You must turn on the gateway VM before you can activate your gateway. // @@ -148,8 +148,8 @@ func (c *StorageGateway) AddCacheRequest(input *AddCacheInput) (req *request.Req // AddCache API operation for AWS Storage Gateway. // // Configures one or more gateway local disks as cache for a gateway. This operation -// is only supported in the cached volume, tape and file gateway type (see Storage -// Gateway Concepts (https://docs.aws.amazon.com/storagegateway/latest/userguide/StorageGatewayConcepts.html)). +// is only supported in the cached volume, tape, and file gateway type (see +// How AWS Storage Gateway works (architecture) (https://docs.aws.amazon.com/storagegateway/latest/userguide/StorageGatewayConcepts.html). // // In the request, you specify the gateway Amazon Resource Name (ARN) to which // you want to add cache, and one or more disk IDs that you want to configure @@ -526,7 +526,7 @@ func (c *StorageGateway) AssignTapePoolRequest(input *AssignTapePoolInput) (req // into the S3 storage class (S3 Glacier or S3 Glacier Deep Archive) that corresponds // to the pool. // -// Valid values: "GLACIER", "DEEP_ARCHIVE" +// Valid Values: GLACIER | DEEP_ARCHIVE // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -979,8 +979,8 @@ func (c *StorageGateway) CreateNFSFileShareRequest(input *CreateNFSFileShareInpu // to enable you to create a file share. Make sure AWS STS is activated in the // AWS Region you are creating your file gateway in. If AWS STS is not activated // in the AWS Region, activate it. For information about how to activate AWS -// STS, see Activating and Deactivating AWS STS in an AWS Region in the AWS -// Identity and Access Management User Guide. +// STS, see Activating and deactivating AWS STS in an AWS Region (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) +// in the AWS Identity and Access Management User Guide. // // File gateway does not support creating hard or symbolic links on a file share. // @@ -1075,7 +1075,7 @@ func (c *StorageGateway) CreateSMBFileShareRequest(input *CreateSMBFileShareInpu // to enable you to create a file share. Make sure that AWS STS is activated // in the AWS Region you are creating your file gateway in. If AWS STS is not // activated in this AWS Region, activate it. For information about how to activate -// AWS STS, see Activating and Deactivating AWS STS in an AWS Region (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) +// AWS STS, see Activating and deactivating AWS STS in an AWS Region (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) // in the AWS Identity and Access Management User Guide. // // File gateways don't support creating hard or symbolic links on a file share. @@ -1165,12 +1165,11 @@ func (c *StorageGateway) CreateSnapshotRequest(input *CreateSnapshotInput) (req // Initiates a snapshot of a volume. // // AWS Storage Gateway provides the ability to back up point-in-time snapshots -// of your data to Amazon Simple Storage Service (Amazon S3) for durable off-site -// recovery, as well as import the data to an Amazon Elastic Block Store (EBS) -// volume in Amazon Elastic Compute Cloud (EC2). You can take snapshots of your -// gateway volume on a scheduled or ad hoc basis. This API enables you to take -// an ad hoc snapshot. For more information, see Editing a Snapshot Schedule -// (https://docs.aws.amazon.com/storagegateway/latest/userguide/managing-volumes.html#SchedulingSnapshot). +// of your data to Amazon Simple Storage (Amazon S3) for durable off-site recovery, +// as well as import the data to an Amazon Elastic Block Store (EBS) volume +// in Amazon Elastic Compute Cloud (EC2). You can take snapshots of your gateway +// volume on a scheduled or ad hoc basis. This API enables you to take ad-hoc +// snapshot. For more information, see Editing a snapshot schedule (https://docs.aws.amazon.com/storagegateway/latest/userguide/managing-volumes.html#SchedulingSnapshot). // // In the CreateSnapshot request you identify the volume by providing its Amazon // Resource Name (ARN). You must also provide description for the snapshot. @@ -1182,7 +1181,9 @@ func (c *StorageGateway) CreateSnapshotRequest(input *CreateSnapshotInput) (req // cached volume gateway type. // // To list or delete a snapshot, you must use the Amazon EC2 API. For more information, -// see DescribeSnapshots or DeleteSnapshot in the EC2 API reference (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Operations.html). +// see DescribeSnapshots (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSnapshots.html) +// or DeleteSnapshot (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteSnapshot.html) +// in the Amazon Elastic Compute Cloud API Reference. // // Volume and snapshot IDs are changing to a longer length ID format. For more // information, see the important note on the Welcome (https://docs.aws.amazon.com/storagegateway/latest/APIReference/Welcome.html) @@ -1290,7 +1291,9 @@ func (c *StorageGateway) CreateSnapshotFromVolumeRecoveryPointRequest(input *Cre // a volume from a snapshot. // // To list or delete a snapshot, you must use the Amazon EC2 API. For more information, -// in Amazon Elastic Compute Cloud API Reference. +// see DescribeSnapshots (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSnapshots.html) +// or DeleteSnapshot (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteSnapshot.html) +// in the Amazon Elastic Compute Cloud API Reference. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1475,7 +1478,7 @@ func (c *StorageGateway) CreateTapeWithBarcodeRequest(input *CreateTapeWithBarco // CreateTapeWithBarcode API operation for AWS Storage Gateway. // // Creates a virtual tape by using your own barcode. You write data to the virtual -// tape and then archive the tape. A barcode is unique and cannot be reused +// tape and then archive the tape. A barcode is unique and can not be reused // if it has already been used on a tape. This applies to barcodes used on deleted // tapes. This operation is only supported in the tape gateway type. // @@ -2014,7 +2017,7 @@ func (c *StorageGateway) DeleteGatewayRequest(input *DeleteGatewayInput) (req *r // for these snapshots. You can choose to remove all remaining Amazon EBS snapshots // by canceling your Amazon EC2 subscription. If you prefer not to cancel your // Amazon EC2 subscription, you can delete your snapshots using the Amazon EC2 -// console. For more information, see the AWS Storage Gateway Detail Page (http://aws.amazon.com/storagegateway). +// console. For more information, see the AWS Storage Gateway detail page (http://aws.amazon.com/storagegateway). // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -2102,7 +2105,7 @@ func (c *StorageGateway) DeleteSnapshotScheduleRequest(input *DeleteSnapshotSche // // You can take snapshots of your gateway volumes on a scheduled or ad hoc basis. // This API action enables you to delete a snapshot schedule for a volume. For -// more information, see Working with Snapshots (https://docs.aws.amazon.com/storagegateway/latest/userguide/WorkingWithSnapshots.html). +// more information, see Backing up your volumes (https://docs.aws.amazon.com/storagegatewaylatest/userguide/backing-up-volumes.html). // In the DeleteSnapshotSchedule request, you identify the volume by providing // its Amazon Resource Name (ARN). This operation is only supported in stored // and cached volume gateway types. @@ -2549,7 +2552,7 @@ func (c *StorageGateway) DescribeBandwidthRateLimitRequest(input *DescribeBandwi // // Returns the bandwidth rate limits of a gateway. By default, these limits // are not set, which means no bandwidth rate limiting is in effect. This operation -// is supported for the stored volume, cached volume and tape gateway types.' +// is supported for the stored volume, cached volume and tape gateway types. // // This operation only returns a value for a bandwidth rate limit only if the // limit is set. If no limits are set for the gateway, then this operation returns @@ -3417,7 +3420,7 @@ func (c *StorageGateway) DescribeStorediSCSIVolumesRequest(input *DescribeStored // // Returns the description of the gateway volumes specified in the request. // The list of gateway volumes in the request must be from one gateway. In the -// response AWS Storage Gateway returns volume information sorted by volume +// response, AWS Storage Gateway returns volume information sorted by volume // ARNs. This operation is only supported in stored volume gateway type. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -3942,7 +3945,7 @@ func (c *StorageGateway) DescribeUploadBufferRequest(input *DescribeUploadBuffer // DescribeUploadBuffer API operation for AWS Storage Gateway. // // Returns information about the upload buffer of a gateway. This operation -// is supported for the stored volume, cached volume and tape gateway types. +// is supported for the stored volume, cached volume, and tape gateway types. // // The response includes disk IDs that are configured as upload buffer space, // and it includes the amount of upload buffer space allocated and used. @@ -5644,8 +5647,8 @@ func (c *StorageGateway) NotifyWhenUploadedRequest(input *NotifyWhenUploadedInpu // event targets such as Amazon SNS or AWS Lambda function. This operation is // only supported for file gateways. // -// For more information, see Getting File Upload Notification in the Storage -// Gateway User Guide (https://docs.aws.amazon.com/storagegateway/latest/userguide/monitoring-file-gateway.html#get-upload-notification). +// For more information, see Getting file upload notification (https://docs.aws.amazon.com/storagegateway/latest/userguide/monitoring-file-gateway.html#get-upload-notification) +// in the AWS Storage Gateway 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 @@ -5730,11 +5733,12 @@ func (c *StorageGateway) RefreshCacheRequest(input *RefreshCacheInput) (req *req // RefreshCache API operation for AWS Storage Gateway. // // Refreshes the cache for the specified file share. This operation finds objects -// in the Amazon S3 bucket that were added, removed or replaced since the gateway +// in the Amazon S3 bucket that were added, removed, or replaced since the gateway // last listed the bucket's contents and cached the results. This operation // is only supported in the file gateway type. You can subscribe to be notified // through an Amazon CloudWatch event when your RefreshCache operation completes. -// For more information, see Getting Notified About File Operations (https://docs.aws.amazon.com/storagegateway/latest/userguide/monitoring-file-gateway.html#get-notification). +// For more information, see Getting notified about file operations (https://docs.aws.amazon.com/storagegateway/latest/userguide/monitoring-file-gateway.html#get-notification) +// in the AWS Storage Gateway User Guide. // // When this API is called, it only initiates the refresh operation. When the // API call completes and returns a success code, it doesn't necessarily mean @@ -5746,13 +5750,15 @@ func (c *StorageGateway) RefreshCacheRequest(input *RefreshCacheInput) (req *req // Throttle limit: This API is asynchronous so the gateway will accept no more // than two refreshes at any time. We recommend using the refresh-complete CloudWatch // event notification before issuing additional requests. For more information, -// see Getting Notified About File Operations (https://docs.aws.amazon.com/storagegateway/latest/userguide/monitoring-file-gateway.html#get-notification). +// see Getting notified about file operations (https://docs.aws.amazon.com/storagegateway/latest/userguide/monitoring-file-gateway.html#get-notification) +// in the AWS Storage Gateway User Guide. // // If you invoke the RefreshCache API when two requests are already being processed, // any new request will cause an InvalidGatewayRequestException error because // too many requests were sent to the server. // -// For more information, see "https://docs.aws.amazon.com/storagegateway/latest/userguide/monitoring-file-gateway.html#get-notification". +// For more information, see Getting notified about file operations (https://docs.aws.amazon.com/storagegateway/latest/userguide/monitoring-file-gateway.html#get-notification) +// in the AWS Storage Gateway 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 @@ -6384,7 +6390,7 @@ func (c *StorageGateway) ShutdownGatewayRequest(input *ShutdownGatewayInput) (re // the gateway component in the VM to avoid unpredictable conditions. // // After the gateway is shutdown, you cannot call any other API except StartGateway, -// DescribeGatewayInformation and ListGateways. For more information, see ActivateGateway. +// DescribeGatewayInformation, and ListGateways. For more information, see ActivateGateway. // Your applications cannot read from or write to the gateway's storage volumes, // and there are no snapshots taken. // @@ -6756,7 +6762,7 @@ func (c *StorageGateway) UpdateBandwidthRateLimitRequest(input *UpdateBandwidthR // Updates the bandwidth rate limits of a gateway. You can update both the upload // and download bandwidth rate limit or specify only one of the two. If you // don't set a bandwidth rate limit, the existing rate limit remains. This operation -// is supported for the stored volume, cached volume and tape gateway types.' +// is supported for the stored volume, cached volume, and tape gateway types. // // By default, a gateway's bandwidth rate limits are not set. If you don't set // any limit, the gateway does not have any limitations on its bandwidth usage @@ -7038,9 +7044,9 @@ func (c *StorageGateway) UpdateGatewaySoftwareNowRequest(input *UpdateGatewaySof // A software update forces a system restart of your gateway. You can minimize // the chance of any disruption to your applications by increasing your iSCSI // Initiators' timeouts. For more information about increasing iSCSI Initiator -// timeouts for Windows and Linux, see Customizing Your Windows iSCSI Settings +// timeouts for Windows and Linux, see Customizing your Windows iSCSI settings // (https://docs.aws.amazon.com/storagegateway/latest/userguide/ConfiguringiSCSIClientInitiatorWindowsClient.html#CustomizeWindowsiSCSISettings) -// and Customizing Your Linux iSCSI Settings (https://docs.aws.amazon.com/storagegateway/latest/userguide/ConfiguringiSCSIClientInitiatorRedHatClient.html#CustomizeLinuxiSCSISettings), +// and Customizing your Linux iSCSI settings (https://docs.aws.amazon.com/storagegateway/latest/userguide/ConfiguringiSCSIClientInitiatorRedHatClient.html#CustomizeLinuxiSCSISettings), // respectively. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -7323,7 +7329,7 @@ func (c *StorageGateway) UpdateSMBFileShareRequest(input *UpdateSMBFileShareInpu // to enable you to create a file share. Make sure that AWS STS is activated // in the AWS Region you are creating your file gateway in. If AWS STS is not // activated in this AWS Region, activate it. For information about how to activate -// AWS STS, see Activating and Deactivating AWS STS in an AWS Region (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) +// AWS STS, see Activating and deactivating AWS STS in an AWS Region (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) // in the AWS Identity and Access Management User Guide. // // File gateways don't support creating hard or symbolic links on a file share. @@ -7648,9 +7654,9 @@ func (c *StorageGateway) UpdateVTLDeviceTypeWithContext(ctx aws.Context, input * // // * ActivateGatewayInput$GatewayType // -// * ActivateGatewayInput$TapeDriveType -// // * ActivateGatewayInput$MediumChangerType +// +// * ActivateGatewayInput$TapeDriveType type ActivateGatewayInput struct { _ struct{} `type:"structure"` @@ -7662,8 +7668,8 @@ type ActivateGatewayInput struct { // defaults -- the arguments you pass to the ActivateGateway API call determine // the actual configuration of your gateway. // - // For more information, see https://docs.aws.amazon.com/storagegateway/latest/userguide/get-activation-key.html - // in the Storage Gateway User Guide. + // For more information, see Getting activation key (https://docs.aws.amazon.com/storagegateway/latest/userguide/get-activation-key.html) + // in the AWS Storage Gateway User Guide. // // ActivationKey is a required field ActivationKey *string `min:"1" type:"string" required:"true"` @@ -7676,11 +7682,11 @@ type ActivateGatewayInput struct { // A value that indicates the AWS Region where you want to store your data. // The gateway AWS Region specified must be the same AWS Region as the AWS Region // in your Host header in the request. For more information about available - // AWS Regions and endpoints for AWS Storage Gateway, see Regions and Endpoints - // (https://docs.aws.amazon.com/general/latest/gr/rande.html#sg_region) in the - // Amazon Web Services Glossary. + // AWS Regions and endpoints for AWS Storage Gateway, see AWS Storage Gateway + // endpoints and quotas (https://docs.aws.amazon.com/general/latest/gr/sg.html) + // in the AWS General Reference. // - // Valid Values: See AWS Storage Gateway Regions and Endpoints (https://docs.aws.amazon.com/general/latest/gr/rande.html#sg_region) + // Valid Values: See AWS Storage Gateway endpoints and quotas (https://docs.aws.amazon.com/general/latest/gr/sg.html) // in the AWS General Reference. // // GatewayRegion is a required field @@ -7699,13 +7705,13 @@ type ActivateGatewayInput struct { // is critical to all later functions of the gateway and cannot be changed after // activation. The default value is CACHED. // - // Valid Values: "STORED", "CACHED", "VTL", "FILE_S3" + // Valid Values: STORED | CACHED | VTL | FILE_S3 GatewayType *string `min:"2" type:"string"` // The value that indicates the type of medium changer to use for tape gateway. // This field is optional. // - // Valid Values: "STK-L700", "AWS-Gateway-VTL" + // Valid Values: STK-L700 | AWS-Gateway-VTL MediumChangerType *string `min:"2" type:"string"` // A list of up to 50 tags that you can assign to the gateway. Each tag is a @@ -7720,7 +7726,7 @@ type ActivateGatewayInput struct { // The value that indicates the type of tape drive to use for tape gateway. // This field is optional. // - // Valid Values: "IBM-ULT3580-TD5" + // Valid Values: IBM-ULT3580-TD5 TapeDriveType *string `min:"2" type:"string"` } @@ -8223,7 +8229,7 @@ type AssignTapePoolInput struct { // is archived directly into the storage class (S3 Glacier or S3 Glacier Deep // Archive) that corresponds to the pool. // - // Valid values: "GLACIER", "DEEP_ARCHIVE" + // Valid Values: GLACIER | DEEP_ARCHIVE // // PoolId is a required field PoolId *string `min:"1" type:"string" required:"true"` @@ -8503,7 +8509,7 @@ type AutomaticTapeCreationRule struct { // tape is archived directly into the storage class (S3 Glacier or S3 Glacier // Deep Archive) that corresponds to the pool. // - // Valid values: "GLACIER", "DEEP_ARCHIVE" + // Valid Values: GLACIER | DEEP_ARCHIVE // // PoolId is a required field PoolId *string `min:"1" type:"string" required:"true"` @@ -8588,6 +8594,35 @@ func (s *AutomaticTapeCreationRule) SetTapeSizeInBytes(v int64) *AutomaticTapeCr return s } +// Lists refresh cache information. +type CacheAttributes struct { + _ struct{} `type:"structure"` + + // Refreshes a file share's cache by using Time To Live (TTL). TTL is the length + // of time since the last refresh after which access to the directory would + // cause the file gateway to first refresh that directory's contents from the + // Amazon S3 bucket. The TTL duration is in seconds. + // + // Valid Values: 300 to 2,592,000 seconds (5 minutes to 30 days) + CacheStaleTimeoutInSeconds *int64 `type:"integer"` +} + +// String returns the string representation +func (s CacheAttributes) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CacheAttributes) GoString() string { + return s.String() +} + +// SetCacheStaleTimeoutInSeconds sets the CacheStaleTimeoutInSeconds field's value. +func (s *CacheAttributes) SetCacheStaleTimeoutInSeconds(v int64) *CacheAttributes { + s.CacheStaleTimeoutInSeconds = &v + return s +} + // Describes an iSCSI cached volume. type CachediSCSIVolume struct { _ struct{} `type:"structure"` @@ -8596,8 +8631,9 @@ type CachediSCSIVolume struct { // don’t have this time stamp. CreatedDate *time.Time `type:"timestamp"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` // If the cached volume was created from a snapshot, this field contains the @@ -8617,8 +8653,8 @@ type CachediSCSIVolume struct { VolumeARN *string `min:"50" type:"string"` // A value that indicates whether a storage volume is attached to or detached - // from a gateway. For more information, see Moving Your Volumes to a Different - // Gateway (https://docs.aws.amazon.com/storagegateway/latest/userguide/managing-volumes.html#attach-detach-volume). + // from a gateway. For more information, see Moving your volumes to a different + // gateway (https://docs.aws.amazon.com/storagegateway/latest/userguide/managing-volumes.html#attach-detach-volume). VolumeAttachmentStatus *string `min:"3" type:"string"` // The unique identifier of the volume, e.g. vol-AE4B946D. @@ -8986,12 +9022,15 @@ type CreateCachediSCSIVolumeInput struct { // GatewayARN is a required field GatewayARN *string `min:"50" type:"string" required:"true"` - // True to use Amazon S3 server-side encryption with your own AWS KMS key, or - // false to use a key managed by Amazon S3. Optional. + // Set to true to use Amazon S3 server-side encryption with your own AWS KMS + // key, or false to use a key managed by Amazon S3. Optional. + // + // Valid Values: true | false KMSEncrypted *bool `type:"boolean"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` // The network interface of the gateway on which to expose the iSCSI target. @@ -9005,7 +9044,7 @@ type CreateCachediSCSIVolumeInput struct { // The snapshot ID (e.g. "snap-1122aabb") of the snapshot to restore as the // new cached volume. Specify this field if you want to create the iSCSI storage - // volume from a snapshot otherwise do not include this field. To list snapshots + // volume from a snapshot; otherwise, do not include this field. To list snapshots // for your account use DescribeSnapshots (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshots.html) // in the Amazon Elastic Compute Cloud API Reference. SnapshotId *string `type:"string"` @@ -9199,6 +9238,9 @@ func (s *CreateCachediSCSIVolumeOutput) SetVolumeARN(v string) *CreateCachediSCS type CreateNFSFileShareInput struct { _ struct{} `type:"structure"` + // Refresh cache information. + CacheAttributes *CacheAttributes `type:"structure"` + // The list of clients that are allowed to access the file gateway. The list // must contain either valid IP addresses or valid CIDR blocks. ClientList []*string `min:"1" type:"list"` @@ -9210,10 +9252,16 @@ type CreateNFSFileShareInput struct { ClientToken *string `min:"5" type:"string" required:"true"` // The default storage class for objects put into an Amazon S3 bucket by the - // file gateway. Possible values are S3_STANDARD, S3_STANDARD_IA, or S3_ONEZONE_IA. - // If this field is not populated, the default value S3_STANDARD is used. Optional. + // file gateway. The default value is S3_INTELLIGENT_TIERING. Optional. + // + // Valid Values: S3_STANDARD | S3_INTELLIGENT_TIERING | S3_STANDARD_IA | S3_ONEZONE_IA DefaultStorageClass *string `min:"5" type:"string"` + // The name of the file share. Optional. + // + // FileShareName must be set if an S3 prefix name is set in LocationARN. + FileShareName *string `min:"1" type:"string"` + // The Amazon Resource Name (ARN) of the file gateway on which you want to create // a file share. // @@ -9222,18 +9270,24 @@ type CreateNFSFileShareInput struct { // A value that enables guessing of the MIME type for uploaded objects based // on file extensions. Set this value to true to enable MIME type guessing, - // and otherwise to false. The default value is true. + // otherwise set to false. The default value is true. + // + // Valid Values: true | false GuessMIMETypeEnabled *bool `type:"boolean"` - // True to use Amazon S3 server-side encryption with your own AWS KMS key, or - // false to use a key managed by Amazon S3. Optional. + // Set to true to use Amazon S3 server-side encryption with your own AWS KMS + // key, or false to use a key managed by Amazon S3. Optional. + // + // Valid Values: true | false KMSEncrypted *bool `type:"boolean"` - // The Amazon Resource Name (ARN) AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` - // The ARN of the backed storage used for storing file data. + // The ARN of the backend storage used for storing file data. A prefix name + // can be added to the S3 bucket name. It must end with a "/". // // LocationARN is a required field LocationARN *string `min:"16" type:"string" required:"true"` @@ -9241,22 +9295,27 @@ type CreateNFSFileShareInput struct { // File share default values. Optional. NFSFileShareDefaults *NFSFileShareDefaults `type:"structure"` - // A value that sets the access control list permission for objects in the S3 - // bucket that a file gateway puts objects into. The default value is "private". + // A value that sets the access control list (ACL) permission for objects in + // the S3 bucket that a file gateway puts objects into. The default value is + // private. ObjectACL *string `type:"string" enum:"ObjectACL"` - // A value that sets the write status of a file share. This value is true if - // the write status is read-only, and otherwise false. + // A value that sets the write status of a file share. Set this value to true + // to set the write status to read-only, otherwise set to false. + // + // Valid Values: true | false ReadOnly *bool `type:"boolean"` // A value that sets who pays the cost of the request and the cost associated // with data download from the S3 bucket. If this value is set to true, the - // requester pays the costs. Otherwise the S3 bucket owner pays. However, the + // requester pays the costs; otherwise, the S3 bucket owner pays. However, the // S3 bucket owner always pays the cost of storing data. // // RequesterPays is a configuration for the S3 bucket that backs the file share, // so make sure that the configuration on the file share is the same as the // S3 bucket configuration. + // + // Valid Values: true | false RequesterPays *bool `type:"boolean"` // The ARN of the AWS Identity and Access Management (IAM) role that a file @@ -9265,13 +9324,15 @@ type CreateNFSFileShareInput struct { // Role is a required field Role *string `min:"20" type:"string" required:"true"` - // A value that maps a user to anonymous user. Valid options are the following: + // A value that maps a user to anonymous user. // - // * RootSquash - Only root is mapped to anonymous user. + // Valid values are the following: // - // * NoSquash - No one is mapped to anonymous user + // * RootSquash: Only root is mapped to anonymous user. // - // * AllSquash - Everyone is mapped to anonymous user. + // * NoSquash: No one is mapped to anonymous user. + // + // * AllSquash: Everyone is mapped to anonymous user. Squash *string `min:"5" type:"string"` // A list of up to 50 tags that can be assigned to the NFS file share. Each @@ -9309,6 +9370,9 @@ func (s *CreateNFSFileShareInput) Validate() error { if s.DefaultStorageClass != nil && len(*s.DefaultStorageClass) < 5 { invalidParams.Add(request.NewErrParamMinLen("DefaultStorageClass", 5)) } + if s.FileShareName != nil && len(*s.FileShareName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("FileShareName", 1)) + } if s.GatewayARN == nil { invalidParams.Add(request.NewErrParamRequired("GatewayARN")) } @@ -9355,6 +9419,12 @@ func (s *CreateNFSFileShareInput) Validate() error { return nil } +// SetCacheAttributes sets the CacheAttributes field's value. +func (s *CreateNFSFileShareInput) SetCacheAttributes(v *CacheAttributes) *CreateNFSFileShareInput { + s.CacheAttributes = v + return s +} + // SetClientList sets the ClientList field's value. func (s *CreateNFSFileShareInput) SetClientList(v []*string) *CreateNFSFileShareInput { s.ClientList = v @@ -9373,6 +9443,12 @@ func (s *CreateNFSFileShareInput) SetDefaultStorageClass(v string) *CreateNFSFil return s } +// SetFileShareName sets the FileShareName field's value. +func (s *CreateNFSFileShareInput) SetFileShareName(v string) *CreateNFSFileShareInput { + s.FileShareName = &v + return s +} + // SetGatewayARN sets the GatewayARN field's value. func (s *CreateNFSFileShareInput) SetGatewayARN(v string) *CreateNFSFileShareInput { s.GatewayARN = &v @@ -9473,9 +9549,10 @@ func (s *CreateNFSFileShareOutput) SetFileShareARN(v string) *CreateNFSFileShare type CreateSMBFileShareInput struct { _ struct{} `type:"structure"` - // A list of users in the Active Directory that will be granted administrator + // A list of users or groups in the Active Directory that will be granted administrator // privileges on the file share. These users can do all file operations as the - // super-user. + // super-user. Acceptable formats include: DOMAIN\User1, user1, @group1, and + // @DOMAIN\group1. // // Use this option very carefully, because any user in this list can do anything // they like on the file share, regardless of file permissions. @@ -9484,11 +9561,20 @@ type CreateSMBFileShareInput struct { // The Amazon Resource Name (ARN) of the storage used for the audit logs. AuditDestinationARN *string `type:"string"` - // The authentication method that users use to access the file share. + // The authentication method that users use to access the file share. The default + // is ActiveDirectory. // - // Valid values are ActiveDirectory or GuestAccess. The default is ActiveDirectory. + // Valid Values: ActiveDirectory | GuestAccess Authentication *string `min:"5" type:"string"` + // Refresh cache information. + CacheAttributes *CacheAttributes `type:"structure"` + + // The case of an object name in an Amazon S3 bucket. For ClientSpecified, the + // client determines the case sensitivity. For CaseSensitive, the gateway determines + // the case sensitivity. The default value is ClientSpecified. + CaseSensitivity *string `type:"string" enum:"CaseSensitivity"` + // A unique string value that you supply that is used by file gateway to ensure // idempotent file share creation. // @@ -9496,10 +9582,16 @@ type CreateSMBFileShareInput struct { ClientToken *string `min:"5" type:"string" required:"true"` // The default storage class for objects put into an Amazon S3 bucket by the - // file gateway. Possible values are S3_STANDARD, S3_STANDARD_IA, or S3_ONEZONE_IA. - // If this field is not populated, the default value S3_STANDARD is used. Optional. + // file gateway. The default value is S3_INTELLIGENT_TIERING. Optional. + // + // Valid Values: S3_STANDARD | S3_INTELLIGENT_TIERING | S3_STANDARD_IA | S3_ONEZONE_IA DefaultStorageClass *string `min:"5" type:"string"` + // The name of the file share. Optional. + // + // FileShareName must be set if an S3 prefix name is set in LocationARN. + FileShareName *string `min:"1" type:"string"` + // The ARN of the file gateway on which you want to create a file share. // // GatewayARN is a required field @@ -9507,43 +9599,55 @@ type CreateSMBFileShareInput struct { // A value that enables guessing of the MIME type for uploaded objects based // on file extensions. Set this value to true to enable MIME type guessing, - // and otherwise to false. The default value is true. + // otherwise set to false. The default value is true. + // + // Valid Values: true | false GuessMIMETypeEnabled *bool `type:"boolean"` // A list of users or groups in the Active Directory that are not allowed to - // access the file share. A group must be prefixed with the @ character. For - // example, @group1. Can only be set if Authentication is set to ActiveDirectory. + // access the file share. A group must be prefixed with the @ character. Acceptable + // formats include: DOMAIN\User1, user1, @group1, and @DOMAIN\group1. Can only + // be set if Authentication is set to ActiveDirectory. InvalidUserList []*string `type:"list"` - // True to use Amazon S3 server-side encryption with your own AWS KMS key, or - // false to use a key managed by Amazon S3. Optional. + // Set to true to use Amazon S3 server-side encryption with your own AWS KMS + // key, or false to use a key managed by Amazon S3. Optional. + // + // Valid Values: true | false KMSEncrypted *bool `type:"boolean"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` - // The ARN of the backed storage used for storing file data. + // The ARN of the backend storage used for storing file data. A prefix name + // can be added to the S3 bucket name. It must end with a "/". // // LocationARN is a required field LocationARN *string `min:"16" type:"string" required:"true"` - // A value that sets the access control list permission for objects in the S3 - // bucket that a file gateway puts objects into. The default value is "private". + // A value that sets the access control list (ACL) permission for objects in + // the S3 bucket that a file gateway puts objects into. The default value is + // private. ObjectACL *string `type:"string" enum:"ObjectACL"` - // A value that sets the write status of a file share. This value is true if - // the write status is read-only, and otherwise false. + // A value that sets the write status of a file share. Set this value to true + // to set the write status to read-only, otherwise set to false. + // + // Valid Values: true | false ReadOnly *bool `type:"boolean"` // A value that sets who pays the cost of the request and the cost associated // with data download from the S3 bucket. If this value is set to true, the - // requester pays the costs. Otherwise the S3 bucket owner pays. However, the + // requester pays the costs; otherwise, the S3 bucket owner pays. However, the // S3 bucket owner always pays the cost of storing data. // // RequesterPays is a configuration for the S3 bucket that backs the file share, // so make sure that the configuration on the file share is the same as the // S3 bucket configuration. + // + // Valid Values: true | false RequesterPays *bool `type:"boolean"` // The ARN of the AWS Identity and Access Management (IAM) role that a file @@ -9552,12 +9656,15 @@ type CreateSMBFileShareInput struct { // Role is a required field Role *string `min:"20" type:"string" required:"true"` - // Set this value to "true to enable ACL (access control list) on the SMB file - // share. Set it to "false" to map file and directory permissions to the POSIX + // Set this value to true to enable access control list (ACL) on the SMB file + // share. Set it to false to map file and directory permissions to the POSIX // permissions. // - // For more information, see https://docs.aws.amazon.com/storagegateway/latest/userguide/smb-acl.html - // in the Storage Gateway User Guide. + // For more information, see Using Microsoft Windows ACLs to control access + // to an SMB file share (https://docs.aws.amazon.com/storagegateway/latest/userguide/smb-acl.html) + // in the AWS Storage Gateway User Guide. + // + // Valid Values: true | false SMBACLEnabled *bool `type:"boolean"` // A list of up to 50 tags that can be assigned to the NFS file share. Each @@ -9570,8 +9677,9 @@ type CreateSMBFileShareInput struct { Tags []*Tag `type:"list"` // A list of users or groups in the Active Directory that are allowed to access - // the file share. A group must be prefixed with the @ character. For example - // @group1. Can only be set if Authentication is set to ActiveDirectory. + // the file share. A group must be prefixed with the @ character. Acceptable + // formats include: DOMAIN\User1, user1, @group1, and @DOMAIN\group1. Can only + // be set if Authentication is set to ActiveDirectory. ValidUserList []*string `type:"list"` } @@ -9600,6 +9708,9 @@ func (s *CreateSMBFileShareInput) Validate() error { if s.DefaultStorageClass != nil && len(*s.DefaultStorageClass) < 5 { invalidParams.Add(request.NewErrParamMinLen("DefaultStorageClass", 5)) } + if s.FileShareName != nil && len(*s.FileShareName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("FileShareName", 1)) + } if s.GatewayARN == nil { invalidParams.Add(request.NewErrParamRequired("GatewayARN")) } @@ -9656,6 +9767,18 @@ func (s *CreateSMBFileShareInput) SetAuthentication(v string) *CreateSMBFileShar return s } +// SetCacheAttributes sets the CacheAttributes field's value. +func (s *CreateSMBFileShareInput) SetCacheAttributes(v *CacheAttributes) *CreateSMBFileShareInput { + s.CacheAttributes = v + return s +} + +// SetCaseSensitivity sets the CaseSensitivity field's value. +func (s *CreateSMBFileShareInput) SetCaseSensitivity(v string) *CreateSMBFileShareInput { + s.CaseSensitivity = &v + return s +} + // SetClientToken sets the ClientToken field's value. func (s *CreateSMBFileShareInput) SetClientToken(v string) *CreateSMBFileShareInput { s.ClientToken = &v @@ -9668,6 +9791,12 @@ func (s *CreateSMBFileShareInput) SetDefaultStorageClass(v string) *CreateSMBFil return s } +// SetFileShareName sets the FileShareName field's value. +func (s *CreateSMBFileShareInput) SetFileShareName(v string) *CreateSMBFileShareInput { + s.FileShareName = &v + return s +} + // SetGatewayARN sets the GatewayARN field's value. func (s *CreateSMBFileShareInput) SetGatewayARN(v string) *CreateSMBFileShareInput { s.GatewayARN = &v @@ -9775,7 +9904,7 @@ type CreateSnapshotFromVolumeRecoveryPointInput struct { // Textual description of the snapshot that appears in the Amazon EC2 console, // Elastic Block Store snapshots panel in the Description field, and in the - // AWS Storage Gateway snapshot Details pane, Description field + // AWS Storage Gateway snapshot Details pane, Description field. // // SnapshotDescription is a required field SnapshotDescription *string `min:"1" type:"string" required:"true"` @@ -9908,7 +10037,7 @@ type CreateSnapshotInput struct { // Textual description of the snapshot that appears in the Amazon EC2 console, // Elastic Block Store snapshots panel in the Description field, and in the - // AWS Storage Gateway snapshot Details pane, Description field + // AWS Storage Gateway snapshot Details pane, Description field. // // SnapshotDescription is a required field SnapshotDescription *string `min:"1" type:"string" required:"true"` @@ -10051,12 +10180,15 @@ type CreateStorediSCSIVolumeInput struct { // GatewayARN is a required field GatewayARN *string `min:"50" type:"string" required:"true"` - // True to use Amazon S3 server-side encryption with your own AWS KMS key, or - // false to use a key managed by Amazon S3. Optional. + // Set to true to use Amazon S3 server-side encryption with your own AWS KMS + // key, or false to use a key managed by Amazon S3. Optional. + // + // Valid Values: true | false KMSEncrypted *bool `type:"boolean"` - // The Amazon Resource Name (ARN) of the KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` // The network interface of the gateway on which to expose the iSCSI target. @@ -10068,17 +10200,17 @@ type CreateStorediSCSIVolumeInput struct { // NetworkInterfaceId is a required field NetworkInterfaceId *string `type:"string" required:"true"` - // Specify this field as true if you want to preserve the data on the local - // disk. Otherwise, specifying this field as false creates an empty volume. + // Set to true true if you want to preserve the data on the local disk. Otherwise, + // set to false to create an empty volume. // - // Valid Values: true, false + // Valid Values: true | false // // PreserveExistingData is a required field PreserveExistingData *bool `type:"boolean" required:"true"` // The snapshot ID (e.g. "snap-1122aabb") of the snapshot to restore as the // new stored volume. Specify this field if you want to create the iSCSI storage - // volume from a snapshot otherwise do not include this field. To list snapshots + // volume from a snapshot; otherwise, do not include this field. To list snapshots // for your account use DescribeSnapshots (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshots.html) // in the Amazon Elastic Compute Cloud API Reference. SnapshotId *string `type:"string"` @@ -10269,21 +10401,24 @@ type CreateTapeWithBarcodeInput struct { // GatewayARN is a required field GatewayARN *string `min:"50" type:"string" required:"true"` - // True to use Amazon S3 server-side encryption with your own AWS KMS key, or - // false to use a key managed by Amazon S3. Optional. + // Set to true to use Amazon S3 server-side encryption with your own AWS KMS + // key, or false to use a key managed by Amazon S3. Optional. + // + // Valid Values: true | false KMSEncrypted *bool `type:"boolean"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` // The ID of the pool that you want to add your tape to for archiving. The tape // in this pool is archived in the S3 storage class that is associated with // the pool. When you use your backup application to eject the tape, the tape - // is archived directly into the storage class (S3 Glacier or S3 Glacier Deep - // Archive) that corresponds to the pool. + // is archived directly into the storage class (S3 Glacier or S3 Deep Archive) + // that corresponds to the pool. // - // Valid values: "GLACIER", "DEEP_ARCHIVE" + // Valid Values: GLACIER | DEEP_ARCHIVE PoolId *string `min:"1" type:"string"` // A list of up to 50 tags that can be assigned to a virtual tape that has a @@ -10448,12 +10583,15 @@ type CreateTapesInput struct { // GatewayARN is a required field GatewayARN *string `min:"50" type:"string" required:"true"` - // True to use Amazon S3 server-side encryption with your own AWS KMS key, or - // false to use a key managed by Amazon S3. Optional. + // Set to true to use Amazon S3 server-side encryption with your own AWS KMS + // key, or false to use a key managed by Amazon S3. Optional. + // + // Valid Values: true | false KMSEncrypted *bool `type:"boolean"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` // The number of virtual tapes that you want to create. @@ -10467,7 +10605,7 @@ type CreateTapesInput struct { // is archived directly into the storage class (S3 Glacier or S3 Glacier Deep // Archive) that corresponds to the pool. // - // Valid values: "GLACIER", "DEEP_ARCHIVE" + // Valid Values: GLACIER | DEEP_ARCHIVE PoolId *string `min:"1" type:"string"` // A list of up to 50 tags that can be assigned to a virtual tape. Each tag @@ -10713,7 +10851,7 @@ type DeleteBandwidthRateLimitInput struct { // One of the BandwidthType values that indicates the gateway bandwidth rate // limit to delete. // - // Valid Values: Upload, Download, All. + // Valid Values: Upload | Download | All // // BandwidthType is a required field BandwidthType *string `min:"3" type:"string" required:"true"` @@ -10905,6 +11043,8 @@ type DeleteFileShareInput struct { // and aborts all data uploads to AWS. Otherwise, the file share is not deleted // until all data is uploaded to AWS. This process aborts the data upload process, // and the file share enters the FORCE_DELETING status. + // + // Valid Values: true | false ForceDelete *bool `type:"boolean"` } @@ -11299,7 +11439,7 @@ func (s *DeleteVolumeInput) SetVolumeARN(v string) *DeleteVolumeInput { } // A JSON object containing the Amazon Resource Name (ARN) of the storage volume -// that was deleted +// that was deleted. type DeleteVolumeOutput struct { _ struct{} `type:"structure"` @@ -11735,7 +11875,7 @@ func (s *DescribeChapCredentialsInput) SetTargetARN(v string) *DescribeChapCrede return s } -// A JSON object containing a . +// A JSON object containing the following fields: type DescribeChapCredentialsOutput struct { _ struct{} `type:"structure"` @@ -11824,12 +11964,21 @@ type DescribeGatewayInformationOutput struct { // used to monitor events in the gateway. CloudWatchLogGroupARN *string `type:"string"` + // Date after which this gateway will not receive software updates for new features + // and bug fixes. + DeprecationDate *string `min:"1" type:"string"` + // The ID of the Amazon EC2 instance that was used to launch the gateway. Ec2InstanceId *string `type:"string"` // The AWS Region where the Amazon EC2 instance is located. Ec2InstanceRegion *string `type:"string"` + // The type of endpoint for your gateway. + // + // Valid Values: STANDARD | FIPS + EndpointType *string `min:"4" type:"string"` + // The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation // to return a list of gateways for your account and AWS Region. GatewayARN *string `min:"50" type:"string"` @@ -11868,6 +12017,9 @@ type DescribeGatewayInformationOutput struct { // this field is not returned in the response. NextUpdateAvailabilityDate *string `min:"1" type:"string"` + // Date after which this gateway will not receive software updates for new features. + SoftwareUpdatesEndDate *string `min:"1" type:"string"` + // A list of up to 50 tags assigned to the gateway, sorted alphabetically by // key name. Each tag is a key-value pair. For a gateway with more than 10 tags // assigned, you can view all tags using the ListTagsForResource API operation. @@ -11894,6 +12046,12 @@ func (s *DescribeGatewayInformationOutput) SetCloudWatchLogGroupARN(v string) *D return s } +// SetDeprecationDate sets the DeprecationDate field's value. +func (s *DescribeGatewayInformationOutput) SetDeprecationDate(v string) *DescribeGatewayInformationOutput { + s.DeprecationDate = &v + return s +} + // SetEc2InstanceId sets the Ec2InstanceId field's value. func (s *DescribeGatewayInformationOutput) SetEc2InstanceId(v string) *DescribeGatewayInformationOutput { s.Ec2InstanceId = &v @@ -11906,6 +12064,12 @@ func (s *DescribeGatewayInformationOutput) SetEc2InstanceRegion(v string) *Descr return s } +// SetEndpointType sets the EndpointType field's value. +func (s *DescribeGatewayInformationOutput) SetEndpointType(v string) *DescribeGatewayInformationOutput { + s.EndpointType = &v + return s +} + // SetGatewayARN sets the GatewayARN field's value. func (s *DescribeGatewayInformationOutput) SetGatewayARN(v string) *DescribeGatewayInformationOutput { s.GatewayARN = &v @@ -11966,6 +12130,12 @@ func (s *DescribeGatewayInformationOutput) SetNextUpdateAvailabilityDate(v strin return s } +// SetSoftwareUpdatesEndDate sets the SoftwareUpdatesEndDate field's value. +func (s *DescribeGatewayInformationOutput) SetSoftwareUpdatesEndDate(v string) *DescribeGatewayInformationOutput { + s.SoftwareUpdatesEndDate = &v + return s +} + // SetTags sets the Tags field's value. func (s *DescribeGatewayInformationOutput) SetTags(v []*Tag) *DescribeGatewayInformationOutput { s.Tags = v @@ -12038,8 +12208,6 @@ type DescribeMaintenanceStartTimeOutput struct { // The day of the month component of the maintenance start time represented // as an ordinal number from 1 to 28, where 1 represents the first day of the // month and 28 represents the last day of the month. - // - // This value is only available for tape and volume gateways. DayOfMonth *int64 `min:"1" type:"integer"` // An ordinal number between 0 and 6 that represents the day of the week, where @@ -12320,24 +12488,27 @@ type DescribeSMBSettingsOutput struct { // to return a list of gateways for your account and AWS Region. GatewayARN *string `min:"50" type:"string"` - // This value is true if a password for the guest user “smbguest” is set, - // and otherwise false. + // This value is true if a password for the guest user smbguest is set, otherwise + // false. + // + // Valid Values: true | false SMBGuestPasswordSet *bool `type:"boolean"` // The type of security strategy that was specified for file gateway. // - // ClientSpecified: if you use this option, requests are established based on - // what is negotiated by the client. This option is recommended when you want - // to maximize compatibility across different clients in your environment. + // * ClientSpecified: If you use this option, requests are established based + // on what is negotiated by the client. This option is recommended when you + // want to maximize compatibility across different clients in your environment. // - // MandatorySigning: if you use this option, file gateway only allows connections - // from SMBv2 or SMBv3 clients that have signing enabled. This option works - // with SMB clients on Microsoft Windows Vista, Windows Server 2008 or newer. + // * MandatorySigning: If you use this option, file gateway only allows connections + // from SMBv2 or SMBv3 clients that have signing enabled. This option works + // with SMB clients on Microsoft Windows Vista, Windows Server 2008 or newer. // - // MandatoryEncryption: if you use this option, file gateway only allows connections - // from SMBv3 clients that have encryption enabled. This option is highly recommended - // for environments that handle sensitive data. This option works with SMB clients - // on Microsoft Windows 8, Windows Server 2012 or newer. + // * MandatoryEncryption: If you use this option, file gateway only allows + // connections from SMBv3 clients that have encryption enabled. This option + // is highly recommended for environments that handle sensitive data. This + // option works with SMB clients on Microsoft Windows 8, Windows Server 2012 + // or newer. SMBSecurityStrategy *string `type:"string" enum:"SMBSecurityStrategy"` } @@ -12554,7 +12725,7 @@ type DescribeStorediSCSIVolumesOutput struct { // // * NetworkInterfacePort: The port used to communicate with iSCSI targets. // - // * PreservedExistingData: Indicates if when the stored volume was created, + // * PreservedExistingData: Indicates when the stored volume was created, // existing data on the underlying local disk was preserved. // // * SourceSnapshotId: If the stored volume was created from a snapshot, @@ -12587,7 +12758,7 @@ type DescribeStorediSCSIVolumesOutput struct { // of the volume. // // * VolumeType: One of the enumeration values describing the type of the - // volume. Currently, on STORED volumes are supported. + // volume. Currently, only STORED volumes are supported. StorediSCSIVolumes []*StorediSCSIVolume `type:"list"` } @@ -12682,7 +12853,7 @@ type DescribeTapeArchivesOutput struct { // An array of virtual tape objects in the virtual tape shelf (VTS). The description // includes of the Amazon Resource Name (ARN) of the virtual tapes. The information // returned includes the Amazon Resource Names (ARNs) of the tapes, size of - // the tapes, status of the tapes, progress of the description and tape barcode. + // the tapes, status of the tapes, progress of the description, and tape barcode. TapeArchives []*TapeArchive `type:"list"` } @@ -13280,6 +13451,8 @@ type DetachVolumeInput struct { // Set to true to forcibly remove the iSCSI connection of the target volume // and detach the volume. The default is false. If this value is set to false, // you must manually disconnect the iSCSI connection from the target volume. + // + // Valid Values: true | false ForceDetach *bool `type:"boolean"` // The Amazon Resource Name (ARN) of the volume to detach from the gateway. @@ -13479,7 +13652,9 @@ type Disk struct { DiskAllocationResource *string `type:"string"` // One of the DiskAllocationType enumeration values that identifies how a local - // disk is used. Valid values: UPLOAD_BUFFER, CACHE_STORAGE + // disk is used. + // + // Valid Values: UPLOAD_BUFFER | CACHE_STORAGE DiskAllocationType *string `min:"3" type:"string"` // A list of values that represents attributes of a local disk. @@ -13605,8 +13780,9 @@ type FileShareInfo struct { // The ID of the file share. FileShareId *string `min:"12" type:"string"` - // The status of the file share. Possible values are CREATING, UPDATING, AVAILABLE - // and DELETING. + // The status of the file share. + // + // Valid Values: CREATING | UPDATING | AVAILABLE | DELETING FileShareStatus *string `min:"3" type:"string"` // The type of the file share. @@ -13681,7 +13857,7 @@ type GatewayInfo struct { // The state of the gateway. // - // Valid Values: DISABLED or ACTIVE + // Valid Values: DISABLED | ACTIVE GatewayOperationalState *string `min:"2" type:"string"` // The type of the gateway. @@ -14880,13 +15056,13 @@ func (s *ListVolumesOutput) SetVolumeInfos(v []*VolumeInfo) *ListVolumesOutput { type NFSFileShareDefaults struct { _ struct{} `type:"structure"` - // The Unix directory mode in the form "nnnn". For example, "0666" represents + // The Unix directory mode in the form "nnnn". For example, 0666 represents // the default access mode for all directories inside the file share. The default // value is 0777. DirectoryMode *string `min:"1" type:"string"` - // The Unix file mode in the form "nnnn". For example, "0666" represents the - // default file mode inside the file share. The default value is 0666. + // The Unix file mode in the form "nnnn". For example, 0666 represents the default + // file mode inside the file share. The default value is 0666. FileMode *string `min:"1" type:"string"` // The default group ID for the file share (unless the files have another group @@ -14954,13 +15130,17 @@ func (s *NFSFileShareDefaults) SetOwnerId(v int64) *NFSFileShareDefaults { type NFSFileShareInfo struct { _ struct{} `type:"structure"` + // Refresh cache information. + CacheAttributes *CacheAttributes `type:"structure"` + // The list of clients that are allowed to access the file gateway. The list // must contain either valid IP addresses or valid CIDR blocks. ClientList []*string `min:"1" type:"list"` // The default storage class for objects put into an Amazon S3 bucket by the - // file gateway. Possible values are S3_STANDARD, S3_STANDARD_IA, or S3_ONEZONE_IA. - // If this field is not populated, the default value S3_STANDARD is used. Optional. + // file gateway. The default value is S3_INTELLIGENT_TIERING. Optional. + // + // Valid Values: S3_STANDARD | S3_INTELLIGENT_TIERING | S3_STANDARD_IA | S3_ONEZONE_IA DefaultStorageClass *string `min:"5" type:"string"` // The Amazon Resource Name (ARN) of the file share. @@ -14969,8 +15149,14 @@ type NFSFileShareInfo struct { // The ID of the file share. FileShareId *string `min:"12" type:"string"` - // The status of the file share. Possible values are CREATING, UPDATING, AVAILABLE - // and DELETING. + // The name of the file share. Optional. + // + // FileShareName must be set if an S3 prefix name is set in LocationARN. + FileShareName *string `min:"1" type:"string"` + + // The status of the file share. + // + // Valid Values: CREATING | UPDATING | AVAILABLE | DELETING FileShareStatus *string `min:"3" type:"string"` // The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation @@ -14979,18 +15165,24 @@ type NFSFileShareInfo struct { // A value that enables guessing of the MIME type for uploaded objects based // on file extensions. Set this value to true to enable MIME type guessing, - // and otherwise to false. The default value is true. + // otherwise set to false. The default value is true. + // + // Valid Values: true | false GuessMIMETypeEnabled *bool `type:"boolean"` - // True to use Amazon S3 server-side encryption with your own AWS KMS key, or - // false to use a key managed by Amazon S3. Optional. + // Set to true to use Amazon S3 server-side encryption with your own AWS KMS + // key, or false to use a key managed by Amazon S3. Optional. + // + // Valid Values: true | false KMSEncrypted *bool `type:"boolean"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` - // The ARN of the backend storage used for storing file data. + // The ARN of the backend storage used for storing file data. A prefix name + // can be added to the S3 bucket name. It must end with a "/". LocationARN *string `min:"16" type:"string"` // Describes Network File System (NFS) file share default values. Files and @@ -15001,25 +15193,30 @@ type NFSFileShareInfo struct { // gateways. NFSFileShareDefaults *NFSFileShareDefaults `type:"structure"` - // A value that sets the access control list permission for objects in the S3 - // bucket that a file gateway puts objects into. The default value is "private". + // A value that sets the access control list (ACL) permission for objects in + // the S3 bucket that a file gateway puts objects into. The default value is + // private. ObjectACL *string `type:"string" enum:"ObjectACL"` // The file share path used by the NFS client to identify the mount point. Path *string `type:"string"` - // A value that sets the write status of a file share. This value is true if - // the write status is read-only, and otherwise false. + // A value that sets the write status of a file share. Set this value to true + // to set the write status to read-only, otherwise set to false. + // + // Valid Values: true | false ReadOnly *bool `type:"boolean"` // A value that sets who pays the cost of the request and the cost associated // with data download from the S3 bucket. If this value is set to true, the - // requester pays the costs. Otherwise the S3 bucket owner pays. However, the + // requester pays the costs; otherwise, the S3 bucket owner pays. However, the // S3 bucket owner always pays the cost of storing data. // // RequesterPays is a configuration for the S3 bucket that backs the file share, // so make sure that the configuration on the file share is the same as the // S3 bucket configuration. + // + // Valid Values: true | false RequesterPays *bool `type:"boolean"` // The ARN of the IAM role that file gateway assumes when it accesses the underlying @@ -15028,11 +15225,11 @@ type NFSFileShareInfo struct { // The user mapped to anonymous user. Valid options are the following: // - // * RootSquash - Only root is mapped to anonymous user. + // * RootSquash: Only root is mapped to anonymous user. // - // * NoSquash - No one is mapped to anonymous user + // * NoSquash: No one is mapped to anonymous user. // - // * AllSquash - Everyone is mapped to anonymous user. + // * AllSquash: Everyone is mapped to anonymous user. Squash *string `min:"5" type:"string"` // A list of up to 50 tags assigned to the NFS file share, sorted alphabetically @@ -15051,6 +15248,12 @@ func (s NFSFileShareInfo) GoString() string { return s.String() } +// SetCacheAttributes sets the CacheAttributes field's value. +func (s *NFSFileShareInfo) SetCacheAttributes(v *CacheAttributes) *NFSFileShareInfo { + s.CacheAttributes = v + return s +} + // SetClientList sets the ClientList field's value. func (s *NFSFileShareInfo) SetClientList(v []*string) *NFSFileShareInfo { s.ClientList = v @@ -15075,6 +15278,12 @@ func (s *NFSFileShareInfo) SetFileShareId(v string) *NFSFileShareInfo { return s } +// SetFileShareName sets the FileShareName field's value. +func (s *NFSFileShareInfo) SetFileShareName(v string) *NFSFileShareInfo { + s.FileShareName = &v + return s +} + // SetFileShareStatus sets the FileShareStatus field's value. func (s *NFSFileShareInfo) SetFileShareStatus(v string) *NFSFileShareInfo { s.FileShareStatus = &v @@ -15289,17 +15498,19 @@ type RefreshCacheInput struct { // A comma-separated list of the paths of folders to refresh in the cache. The // default is ["/"]. The default refreshes objects and folders at the root of - // the Amazon S3 bucket. If Recursive is set to "true", the entire S3 bucket - // that the file share has access to is refreshed. + // the Amazon S3 bucket. If Recursive is set to true, the entire S3 bucket that + // the file share has access to is refreshed. FolderList []*string `min:"1" type:"list"` // A value that specifies whether to recursively refresh folders in the cache. // The refresh includes folders that were in the cache the last time the gateway - // listed the folder's contents. If this value set to "true", each folder that + // listed the folder's contents. If this value set to true, each folder that // is listed in FolderList is recursively updated. Otherwise, subfolders listed // in FolderList are not refreshed. Only objects that are in folders listed // directly under FolderList are found and used for the update. The default - // is "true". + // is true. + // + // Valid Values: true | false Recursive *bool `type:"boolean"` } @@ -15716,20 +15927,30 @@ type SMBFileShareInfo struct { // A list of users or groups in the Active Directory that have administrator // rights to the file share. A group must be prefixed with the @ character. - // For example @group1. Can only be set if Authentication is set to ActiveDirectory. + // Acceptable formats include: DOMAIN\User1, user1, @group1, and @DOMAIN\group1. + // Can only be set if Authentication is set to ActiveDirectory. AdminUserList []*string `type:"list"` // The Amazon Resource Name (ARN) of the storage used for the audit logs. AuditDestinationARN *string `type:"string"` - // The authentication method of the file share. + // The authentication method of the file share. The default is ActiveDirectory. // - // Valid values are ActiveDirectory or GuestAccess. The default is ActiveDirectory. + // Valid Values: ActiveDirectory | GuestAccess Authentication *string `min:"5" type:"string"` + // Refresh cache information. + CacheAttributes *CacheAttributes `type:"structure"` + + // The case of an object name in an Amazon S3 bucket. For ClientSpecified, the + // client determines the case sensitivity. For CaseSensitive, the gateway determines + // the case sensitivity. The default value is ClientSpecified. + CaseSensitivity *string `type:"string" enum:"CaseSensitivity"` + // The default storage class for objects put into an Amazon S3 bucket by the - // file gateway. Possible values are S3_STANDARD, S3_STANDARD_IA, or S3_ONEZONE_IA. - // If this field is not populated, the default value S3_STANDARD is used. Optional. + // file gateway. The default value is S3_INTELLIGENT_TIERING. Optional. + // + // Valid Values: S3_STANDARD | S3_INTELLIGENT_TIERING | S3_STANDARD_IA | S3_ONEZONE_IA DefaultStorageClass *string `min:"5" type:"string"` // The Amazon Resource Name (ARN) of the file share. @@ -15738,8 +15959,14 @@ type SMBFileShareInfo struct { // The ID of the file share. FileShareId *string `min:"12" type:"string"` - // The status of the file share. Possible values are CREATING, UPDATING, AVAILABLE - // and DELETING. + // The name of the file share. Optional. + // + // FileShareName must be set if an S3 prefix name is set in LocationARN. + FileShareName *string `min:"1" type:"string"` + + // The status of the file share. + // + // Valid Values: CREATING | UPDATING | AVAILABLE | DELETING FileShareStatus *string `min:"3" type:"string"` // The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation @@ -15748,56 +15975,69 @@ type SMBFileShareInfo struct { // A value that enables guessing of the MIME type for uploaded objects based // on file extensions. Set this value to true to enable MIME type guessing, - // and otherwise to false. The default value is true. + // otherwise set to false. The default value is true. + // + // Valid Values: true | false GuessMIMETypeEnabled *bool `type:"boolean"` // A list of users or groups in the Active Directory that are not allowed to - // access the file share. A group must be prefixed with the @ character. For - // example @group1. Can only be set if Authentication is set to ActiveDirectory. + // access the file share. A group must be prefixed with the @ character. Acceptable + // formats include: DOMAIN\User1, user1, @group1, and @DOMAIN\group1. Can only + // be set if Authentication is set to ActiveDirectory. InvalidUserList []*string `type:"list"` - // True to use Amazon S3 server-side encryption with your own AWS KMS key, or - // false to use a key managed by Amazon S3. Optional. + // Set to true to use Amazon S3 server-side encryption with your own AWS KMS + // key, or false to use a key managed by Amazon S3. Optional. + // + // Valid Values: true | false KMSEncrypted *bool `type:"boolean"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` - // The ARN of the backend storage used for storing file data. + // The ARN of the backend storage used for storing file data. A prefix name + // can be added to the S3 bucket name. It must end with a "/". LocationARN *string `min:"16" type:"string"` - // A value that sets the access control list permission for objects in the S3 - // bucket that a file gateway puts objects into. The default value is "private". + // A value that sets the access control list (ACL) permission for objects in + // the S3 bucket that a file gateway puts objects into. The default value is + // private. ObjectACL *string `type:"string" enum:"ObjectACL"` // The file share path used by the SMB client to identify the mount point. Path *string `type:"string"` - // A value that sets the write status of a file share. This value is true if - // the write status is read-only, and otherwise false. + // A value that sets the write status of a file share. Set this value to true + // to set the write status to read-only, otherwise set to false. + // + // Valid Values: true | false ReadOnly *bool `type:"boolean"` // A value that sets who pays the cost of the request and the cost associated // with data download from the S3 bucket. If this value is set to true, the - // requester pays the costs. Otherwise the S3 bucket owner pays. However, the + // requester pays the costs; otherwise, the S3 bucket owner pays. However, the // S3 bucket owner always pays the cost of storing data. // // RequesterPays is a configuration for the S3 bucket that backs the file share, // so make sure that the configuration on the file share is the same as the // S3 bucket configuration. + // + // Valid Values: true | false RequesterPays *bool `type:"boolean"` // The ARN of the IAM role that file gateway assumes when it accesses the underlying // storage. Role *string `min:"20" type:"string"` - // If this value is set to "true", indicates that ACL (access control list) - // is enabled on the SMB file share. If it is set to "false", it indicates that + // If this value is set to true, it indicates that access control list (ACL) + // is enabled on the SMB file share. If it is set to false, it indicates that // file and directory permissions are mapped to the POSIX permission. // - // For more information, see https://docs.aws.amazon.com/storagegateway/latest/userguide/smb-acl.html - // in the Storage Gateway User Guide. + // For more information, see Using Microsoft Windows ACLs to control access + // to an SMB file share (https://docs.aws.amazon.com/storagegateway/latest/userguide/smb-acl.html) + // in the AWS Storage Gateway User Guide. SMBACLEnabled *bool `type:"boolean"` // A list of up to 50 tags assigned to the SMB file share, sorted alphabetically @@ -15806,8 +16046,9 @@ type SMBFileShareInfo struct { Tags []*Tag `type:"list"` // A list of users or groups in the Active Directory that are allowed to access - // the file share. A group must be prefixed with the @ character. For example - // @group1. Can only be set if Authentication is set to ActiveDirectory. + // the file share. A group must be prefixed with the @ character. Acceptable + // formats include: DOMAIN\User1, user1, @group1, and @DOMAIN\group1. Can only + // be set if Authentication is set to ActiveDirectory. ValidUserList []*string `type:"list"` } @@ -15839,6 +16080,18 @@ func (s *SMBFileShareInfo) SetAuthentication(v string) *SMBFileShareInfo { return s } +// SetCacheAttributes sets the CacheAttributes field's value. +func (s *SMBFileShareInfo) SetCacheAttributes(v *CacheAttributes) *SMBFileShareInfo { + s.CacheAttributes = v + return s +} + +// SetCaseSensitivity sets the CaseSensitivity field's value. +func (s *SMBFileShareInfo) SetCaseSensitivity(v string) *SMBFileShareInfo { + s.CaseSensitivity = &v + return s +} + // SetDefaultStorageClass sets the DefaultStorageClass field's value. func (s *SMBFileShareInfo) SetDefaultStorageClass(v string) *SMBFileShareInfo { s.DefaultStorageClass = &v @@ -15857,6 +16110,12 @@ func (s *SMBFileShareInfo) SetFileShareId(v string) *SMBFileShareInfo { return s } +// SetFileShareName sets the FileShareName field's value. +func (s *SMBFileShareInfo) SetFileShareName(v string) *SMBFileShareInfo { + s.FileShareName = &v + return s +} + // SetFileShareStatus sets the FileShareStatus field's value. func (s *SMBFileShareInfo) SetFileShareStatus(v string) *SMBFileShareInfo { s.FileShareStatus = &v @@ -16103,7 +16362,7 @@ type SetSMBGuestPasswordInput struct { // GatewayARN is a required field GatewayARN *string `min:"50" type:"string" required:"true"` - // The password that you want to set for your SMB Server. + // The password that you want to set for your SMB server. // // Password is a required field Password *string `min:"6" type:"string" required:"true" sensitive:"true"` @@ -16391,14 +16650,15 @@ type StorediSCSIVolume struct { // don’t have this time stamp. CreatedDate *time.Time `type:"timestamp"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` // Indicates if when the stored volume was created, existing data on the underlying // local disk was preserved. // - // Valid Values: true, false + // Valid Values: true | false PreservedExistingData *bool `type:"boolean"` // If the stored volume was created from a snapshot, this field contains the @@ -16419,7 +16679,7 @@ type StorediSCSIVolume struct { // A value that indicates whether a storage volume is attached to, detached // from, or is in the process of detaching from a gateway. For more information, - // see Moving Your Volumes to a Different Gateway (https://docs.aws.amazon.com/storagegateway/latest/userguide/managing-volumes.html#attach-detach-volume). + // see Moving your volumes to a different gateway (https://docs.aws.amazon.com/storagegateway/latest/userguide/managing-volumes.html#attach-detach-volume). VolumeAttachmentStatus *string `min:"3" type:"string"` // The ID of the local disk that was specified in the CreateStorediSCSIVolume @@ -16561,11 +16821,11 @@ func (s *StorediSCSIVolume) SetVolumeiSCSIAttributes(v *VolumeiSCSIAttributes) * // A key-value pair that helps you manage, filter, and search for your resource. // Allowed characters: letters, white space, and numbers, representable in UTF-8, -// and the following characters: + - = . _ : / +// and the following characters: + - = . _ : /. type Tag struct { _ struct{} `type:"structure"` - // Tag key (String). The key can't start with aws:. + // Tag key. The key can't start with aws:. // // Key is a required field Key *string `min:"1" type:"string" required:"true"` @@ -16621,17 +16881,18 @@ func (s *Tag) SetValue(v string) *Tag { type Tape struct { _ struct{} `type:"structure"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` // The ID of the pool that contains tapes that will be archived. The tapes in // this pool are archived in the S3 storage class that is associated with the // pool. When you use your backup application to eject the tape, the tape is - // archived directly into the storage class (S3 Glacier or S# Glacier Deep Archive) + // archived directly into the storage class (S3 Glacier or S3 Glacier Deep Archive) // that corresponds to the pool. // - // Valid values: "GLACIER", "DEEP_ARCHIVE" + // Valid Values: GLACIER | DEEP_ARCHIVE PoolId *string `min:"1" type:"string"` // For archiving virtual tapes, indicates how much data remains to be uploaded @@ -16745,14 +17006,15 @@ type TapeArchive struct { // format. CompletionTime *time.Time `type:"timestamp"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` // The ID of the pool that was used to archive the tape. The tapes in this pool // are archived in the S3 storage class that is associated with the pool. // - // Valid values: "GLACIER", "DEEP_ARCHIVE" + // Valid Values: GLACIER | DEEP_ARCHIVE PoolId *string `min:"1" type:"string"` // The Amazon Resource Name (ARN) of the tape gateway that the virtual tape @@ -16866,7 +17128,7 @@ type TapeInfo struct { // is archived directly into the storage class (S3 Glacier or S3 Glacier Deep // Archive) that corresponds to the pool. // - // Valid values: "GLACIER", "DEEP_ARCHIVE" + // Valid Values: GLACIER | DEEP_ARCHIVE PoolId *string `min:"1" type:"string"` // The Amazon Resource Name (ARN) of a virtual tape. @@ -17320,7 +17582,7 @@ type UpdateGatewayInformationInput struct { // The Amazon Resource Name (ARN) of the Amazon CloudWatch log group that you // want to use to monitor and log events in the gateway. // - // For more information, see What Is Amazon CloudWatch Logs? (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html). + // For more information, see What is Amazon CloudWatch logs? (https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html). CloudWatchLogGroupARN *string `type:"string"` // The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation @@ -17392,7 +17654,8 @@ func (s *UpdateGatewayInformationInput) SetGatewayTimezone(v string) *UpdateGate return s } -// A JSON object containing the ARN of the gateway that was updated. +// A JSON object containing the Amazon Resource Name (ARN) of the gateway that +// was updated. type UpdateGatewayInformationOutput struct { _ struct{} `type:"structure"` @@ -17511,8 +17774,6 @@ type UpdateMaintenanceStartTimeInput struct { // The day of the month component of the maintenance start time represented // as an ordinal number from 1 to 28, where 1 represents the first day of the // month and 28 represents the last day of the month. - // - // This value is only available for tape and volume gateways. DayOfMonth *int64 `min:"1" type:"integer"` // The day of the week component of the maintenance start time week represented @@ -17635,13 +17896,17 @@ func (s *UpdateMaintenanceStartTimeOutput) SetGatewayARN(v string) *UpdateMainte type UpdateNFSFileShareInput struct { _ struct{} `type:"structure"` + // Refresh cache information. + CacheAttributes *CacheAttributes `type:"structure"` + // The list of clients that are allowed to access the file gateway. The list // must contain either valid IP addresses or valid CIDR blocks. ClientList []*string `min:"1" type:"list"` // The default storage class for objects put into an Amazon S3 bucket by the - // file gateway. Possible values are S3_STANDARD, S3_STANDARD_IA, or S3_ONEZONE_IA. - // If this field is not populated, the default value S3_STANDARD is used. Optional. + // file gateway. The default value is S3_INTELLIGENT_TIERING. Optional. + // + // Valid Values: S3_STANDARD | S3_INTELLIGENT_TIERING | S3_STANDARD_IA | S3_ONEZONE_IA DefaultStorageClass *string `min:"5" type:"string"` // The Amazon Resource Name (ARN) of the file share to be updated. @@ -17649,47 +17914,64 @@ type UpdateNFSFileShareInput struct { // FileShareARN is a required field FileShareARN *string `min:"50" type:"string" required:"true"` + // The name of the file share. Optional. + // + // FileShareName must be set if an S3 prefix name is set in LocationARN. + FileShareName *string `min:"1" type:"string"` + // A value that enables guessing of the MIME type for uploaded objects based // on file extensions. Set this value to true to enable MIME type guessing, - // and otherwise to false. The default value is true. + // otherwise set to false. The default value is true. + // + // Valid Values: true | false GuessMIMETypeEnabled *bool `type:"boolean"` - // True to use Amazon S3 server-side encryption with your own AWS KMS key, or - // false to use a key managed by Amazon S3. Optional. + // Set to true to use Amazon S3 server-side encryption with your own AWS KMS + // key, or false to use a key managed by Amazon S3. Optional. + // + // Valid Values: true | false KMSEncrypted *bool `type:"boolean"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` // The default values for the file share. Optional. NFSFileShareDefaults *NFSFileShareDefaults `type:"structure"` - // A value that sets the access control list permission for objects in the S3 - // bucket that a file gateway puts objects into. The default value is "private". + // A value that sets the access control list (ACL) permission for objects in + // the S3 bucket that a file gateway puts objects into. The default value is + // private. ObjectACL *string `type:"string" enum:"ObjectACL"` - // A value that sets the write status of a file share. This value is true if - // the write status is read-only, and otherwise false. + // A value that sets the write status of a file share. Set this value to true + // to set the write status to read-only, otherwise set to false. + // + // Valid Values: true | false ReadOnly *bool `type:"boolean"` // A value that sets who pays the cost of the request and the cost associated // with data download from the S3 bucket. If this value is set to true, the - // requester pays the costs. Otherwise the S3 bucket owner pays. However, the + // requester pays the costs; otherwise, the S3 bucket owner pays. However, the // S3 bucket owner always pays the cost of storing data. // // RequesterPays is a configuration for the S3 bucket that backs the file share, // so make sure that the configuration on the file share is the same as the // S3 bucket configuration. + // + // Valid Values: true | false RequesterPays *bool `type:"boolean"` - // The user mapped to anonymous user. Valid options are the following: + // The user mapped to anonymous user. + // + // Valid values are the following: // - // * RootSquash - Only root is mapped to anonymous user. + // * RootSquash: Only root is mapped to anonymous user. // - // * NoSquash - No one is mapped to anonymous user + // * NoSquash: No one is mapped to anonymous user. // - // * AllSquash - Everyone is mapped to anonymous user. + // * AllSquash: Everyone is mapped to anonymous user. Squash *string `min:"5" type:"string"` } @@ -17718,6 +18000,9 @@ func (s *UpdateNFSFileShareInput) Validate() error { if s.FileShareARN != nil && len(*s.FileShareARN) < 50 { invalidParams.Add(request.NewErrParamMinLen("FileShareARN", 50)) } + if s.FileShareName != nil && len(*s.FileShareName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("FileShareName", 1)) + } if s.KMSKey != nil && len(*s.KMSKey) < 7 { invalidParams.Add(request.NewErrParamMinLen("KMSKey", 7)) } @@ -17736,6 +18021,12 @@ func (s *UpdateNFSFileShareInput) Validate() error { return nil } +// SetCacheAttributes sets the CacheAttributes field's value. +func (s *UpdateNFSFileShareInput) SetCacheAttributes(v *CacheAttributes) *UpdateNFSFileShareInput { + s.CacheAttributes = v + return s +} + // SetClientList sets the ClientList field's value. func (s *UpdateNFSFileShareInput) SetClientList(v []*string) *UpdateNFSFileShareInput { s.ClientList = v @@ -17754,6 +18045,12 @@ func (s *UpdateNFSFileShareInput) SetFileShareARN(v string) *UpdateNFSFileShareI return s } +// SetFileShareName sets the FileShareName field's value. +func (s *UpdateNFSFileShareInput) SetFileShareName(v string) *UpdateNFSFileShareInput { + s.FileShareName = &v + return s +} + // SetGuessMIMETypeEnabled sets the GuessMIMETypeEnabled field's value. func (s *UpdateNFSFileShareInput) SetGuessMIMETypeEnabled(v bool) *UpdateNFSFileShareInput { s.GuessMIMETypeEnabled = &v @@ -17830,17 +18127,27 @@ func (s *UpdateNFSFileShareOutput) SetFileShareARN(v string) *UpdateNFSFileShare type UpdateSMBFileShareInput struct { _ struct{} `type:"structure"` - // A list of users in the Active Directory that have administrator rights to - // the file share. A group must be prefixed with the @ character. For example - // @group1. Can only be set if Authentication is set to ActiveDirectory. + // A list of users or groups in the Active Directory that have administrator + // rights to the file share. A group must be prefixed with the @ character. + // Acceptable formats include: DOMAIN\User1, user1, @group1, and @DOMAIN\group1. + // Can only be set if Authentication is set to ActiveDirectory. AdminUserList []*string `type:"list"` // The Amazon Resource Name (ARN) of the storage used for the audit logs. AuditDestinationARN *string `type:"string"` + // Refresh cache information. + CacheAttributes *CacheAttributes `type:"structure"` + + // The case of an object name in an Amazon S3 bucket. For ClientSpecified, the + // client determines the case sensitivity. For CaseSensitive, the gateway determines + // the case sensitivity. The default value is ClientSpecified. + CaseSensitivity *string `type:"string" enum:"CaseSensitivity"` + // The default storage class for objects put into an Amazon S3 bucket by the - // file gateway. Possible values are S3_STANDARD, S3_STANDARD_IA, or S3_ONEZONE_IA. - // If this field is not populated, the default value S3_STANDARD is used. Optional. + // file gateway. The default value is S3_INTELLIGENT_TIERING. Optional. + // + // Valid Values: S3_STANDARD | S3_INTELLIGENT_TIERING | S3_STANDARD_IA | S3_ONEZONE_IA DefaultStorageClass *string `min:"5" type:"string"` // The Amazon Resource Name (ARN) of the SMB file share that you want to update. @@ -17848,53 +18155,73 @@ type UpdateSMBFileShareInput struct { // FileShareARN is a required field FileShareARN *string `min:"50" type:"string" required:"true"` + // The name of the file share. Optional. + // + // FileShareName must be set if an S3 prefix name is set in LocationARN. + FileShareName *string `min:"1" type:"string"` + // A value that enables guessing of the MIME type for uploaded objects based // on file extensions. Set this value to true to enable MIME type guessing, - // and otherwise to false. The default value is true. + // otherwise set to false. The default value is true. + // + // Valid Values: true | false GuessMIMETypeEnabled *bool `type:"boolean"` // A list of users or groups in the Active Directory that are not allowed to - // access the file share. A group must be prefixed with the @ character. For - // example @group1. Can only be set if Authentication is set to ActiveDirectory. + // access the file share. A group must be prefixed with the @ character. Acceptable + // formats include: DOMAIN\User1, user1, @group1, and @DOMAIN\group1. Can only + // be set if Authentication is set to ActiveDirectory. InvalidUserList []*string `type:"list"` - // True to use Amazon S3 server-side encryption with your own AWS KMS key, or - // false to use a key managed by Amazon S3. Optional. + // Set to true to use Amazon S3 server-side encryption with your own AWS KMS + // key, or false to use a key managed by Amazon S3. Optional. + // + // Valid Values: true | false KMSEncrypted *bool `type:"boolean"` - // The Amazon Resource Name (ARN) of the AWS KMS key used for Amazon S3 server-side - // encryption. This value can only be set when KMSEncrypted is true. Optional. + // The Amazon Resource Name (ARN) of a symmetric customer master key (CMK) used + // for Amazon S3 server-side encryption. Storage Gateway does not support asymmetric + // CMKs. This value can only be set when KMSEncrypted is true. Optional. KMSKey *string `min:"7" type:"string"` - // A value that sets the access control list permission for objects in the S3 - // bucket that a file gateway puts objects into. The default value is "private". + // A value that sets the access control list (ACL) permission for objects in + // the S3 bucket that a file gateway puts objects into. The default value is + // private. ObjectACL *string `type:"string" enum:"ObjectACL"` - // A value that sets the write status of a file share. This value is true if - // the write status is read-only, and otherwise false. + // A value that sets the write status of a file share. Set this value to true + // to set write status to read-only, otherwise set to false. + // + // Valid Values: true | false ReadOnly *bool `type:"boolean"` // A value that sets who pays the cost of the request and the cost associated // with data download from the S3 bucket. If this value is set to true, the - // requester pays the costs. Otherwise the S3 bucket owner pays. However, the + // requester pays the costs; otherwise, the S3 bucket owner pays. However, the // S3 bucket owner always pays the cost of storing data. // // RequesterPays is a configuration for the S3 bucket that backs the file share, // so make sure that the configuration on the file share is the same as the // S3 bucket configuration. + // + // Valid Values: true | false RequesterPays *bool `type:"boolean"` - // Set this value to "true to enable ACL (access control list) on the SMB file - // share. Set it to "false" to map file and directory permissions to the POSIX + // Set this value to true to enable access control list (ACL) on the SMB file + // share. Set it to false to map file and directory permissions to the POSIX // permissions. // - // For more information, see https://docs.aws.amazon.com/storagegateway/latest/userguide/smb-acl.htmlin - // the Storage Gateway User Guide. + // For more information, see Using Microsoft Windows ACLs to control access + // to an SMB file share (https://docs.aws.amazon.com/storagegateway/latest/userguide/smb-acl.html) + // in the AWS Storage Gateway User Guide. + // + // Valid Values: true | false SMBACLEnabled *bool `type:"boolean"` // A list of users or groups in the Active Directory that are allowed to access - // the file share. A group must be prefixed with the @ character. For example - // @group1. Can only be set if Authentication is set to ActiveDirectory. + // the file share. A group must be prefixed with the @ character. Acceptable + // formats include: DOMAIN\User1, user1, @group1, and @DOMAIN\group1. Can only + // be set if Authentication is set to ActiveDirectory. ValidUserList []*string `type:"list"` } @@ -17920,6 +18247,9 @@ func (s *UpdateSMBFileShareInput) Validate() error { if s.FileShareARN != nil && len(*s.FileShareARN) < 50 { invalidParams.Add(request.NewErrParamMinLen("FileShareARN", 50)) } + if s.FileShareName != nil && len(*s.FileShareName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("FileShareName", 1)) + } if s.KMSKey != nil && len(*s.KMSKey) < 7 { invalidParams.Add(request.NewErrParamMinLen("KMSKey", 7)) } @@ -17942,6 +18272,18 @@ func (s *UpdateSMBFileShareInput) SetAuditDestinationARN(v string) *UpdateSMBFil return s } +// SetCacheAttributes sets the CacheAttributes field's value. +func (s *UpdateSMBFileShareInput) SetCacheAttributes(v *CacheAttributes) *UpdateSMBFileShareInput { + s.CacheAttributes = v + return s +} + +// SetCaseSensitivity sets the CaseSensitivity field's value. +func (s *UpdateSMBFileShareInput) SetCaseSensitivity(v string) *UpdateSMBFileShareInput { + s.CaseSensitivity = &v + return s +} + // SetDefaultStorageClass sets the DefaultStorageClass field's value. func (s *UpdateSMBFileShareInput) SetDefaultStorageClass(v string) *UpdateSMBFileShareInput { s.DefaultStorageClass = &v @@ -17954,6 +18296,12 @@ func (s *UpdateSMBFileShareInput) SetFileShareARN(v string) *UpdateSMBFileShareI return s } +// SetFileShareName sets the FileShareName field's value. +func (s *UpdateSMBFileShareInput) SetFileShareName(v string) *UpdateSMBFileShareInput { + s.FileShareName = &v + return s +} + // SetGuessMIMETypeEnabled sets the GuessMIMETypeEnabled field's value. func (s *UpdateSMBFileShareInput) SetGuessMIMETypeEnabled(v bool) *UpdateSMBFileShareInput { s.GuessMIMETypeEnabled = &v @@ -18277,7 +18625,7 @@ type UpdateVTLDeviceTypeInput struct { // The type of medium changer you want to select. // - // Valid Values: "STK-L700", "AWS-Gateway-VTL" + // Valid Values: STK-L700 | AWS-Gateway-VTL // // DeviceType is a required field DeviceType *string `min:"2" type:"string" required:"true"` @@ -18651,6 +18999,19 @@ const ( ActiveDirectoryStatusUnknownError = "UNKNOWN_ERROR" ) +// ActiveDirectoryStatus_Values returns all elements of the ActiveDirectoryStatus enum +func ActiveDirectoryStatus_Values() []string { + return []string{ + ActiveDirectoryStatusAccessDenied, + ActiveDirectoryStatusDetached, + ActiveDirectoryStatusJoined, + ActiveDirectoryStatusJoining, + ActiveDirectoryStatusNetworkError, + ActiveDirectoryStatusTimeout, + ActiveDirectoryStatusUnknownError, + } +} + const ( // AvailabilityMonitorTestStatusComplete is a AvailabilityMonitorTestStatus enum value AvailabilityMonitorTestStatusComplete = "COMPLETE" @@ -18662,6 +19023,31 @@ const ( AvailabilityMonitorTestStatusPending = "PENDING" ) +// AvailabilityMonitorTestStatus_Values returns all elements of the AvailabilityMonitorTestStatus enum +func AvailabilityMonitorTestStatus_Values() []string { + return []string{ + AvailabilityMonitorTestStatusComplete, + AvailabilityMonitorTestStatusFailed, + AvailabilityMonitorTestStatusPending, + } +} + +const ( + // CaseSensitivityClientSpecified is a CaseSensitivity enum value + CaseSensitivityClientSpecified = "ClientSpecified" + + // CaseSensitivityCaseSensitive is a CaseSensitivity enum value + CaseSensitivityCaseSensitive = "CaseSensitive" +) + +// CaseSensitivity_Values returns all elements of the CaseSensitivity enum +func CaseSensitivity_Values() []string { + return []string{ + CaseSensitivityClientSpecified, + CaseSensitivityCaseSensitive, + } +} + const ( // ErrorCodeActivationKeyExpired is a ErrorCode enum value ErrorCodeActivationKeyExpired = "ActivationKeyExpired" @@ -18850,6 +19236,74 @@ const ( ErrorCodeVolumeNotReady = "VolumeNotReady" ) +// ErrorCode_Values returns all elements of the ErrorCode enum +func ErrorCode_Values() []string { + return []string{ + ErrorCodeActivationKeyExpired, + ErrorCodeActivationKeyInvalid, + ErrorCodeActivationKeyNotFound, + ErrorCodeGatewayInternalError, + ErrorCodeGatewayNotConnected, + ErrorCodeGatewayNotFound, + ErrorCodeGatewayProxyNetworkConnectionBusy, + ErrorCodeAuthenticationFailure, + ErrorCodeBandwidthThrottleScheduleNotFound, + ErrorCodeBlocked, + ErrorCodeCannotExportSnapshot, + ErrorCodeChapCredentialNotFound, + ErrorCodeDiskAlreadyAllocated, + ErrorCodeDiskDoesNotExist, + ErrorCodeDiskSizeGreaterThanVolumeMaxSize, + ErrorCodeDiskSizeLessThanVolumeSize, + ErrorCodeDiskSizeNotGigAligned, + ErrorCodeDuplicateCertificateInfo, + ErrorCodeDuplicateSchedule, + ErrorCodeEndpointNotFound, + ErrorCodeIamnotSupported, + ErrorCodeInitiatorInvalid, + ErrorCodeInitiatorNotFound, + ErrorCodeInternalError, + ErrorCodeInvalidGateway, + ErrorCodeInvalidEndpoint, + ErrorCodeInvalidParameters, + ErrorCodeInvalidSchedule, + ErrorCodeLocalStorageLimitExceeded, + ErrorCodeLunAlreadyAllocated, + ErrorCodeLunInvalid, + ErrorCodeJoinDomainInProgress, + ErrorCodeMaximumContentLengthExceeded, + ErrorCodeMaximumTapeCartridgeCountExceeded, + ErrorCodeMaximumVolumeCountExceeded, + ErrorCodeNetworkConfigurationChanged, + ErrorCodeNoDisksAvailable, + ErrorCodeNotImplemented, + ErrorCodeNotSupported, + ErrorCodeOperationAborted, + ErrorCodeOutdatedGateway, + ErrorCodeParametersNotImplemented, + ErrorCodeRegionInvalid, + ErrorCodeRequestTimeout, + ErrorCodeServiceUnavailable, + ErrorCodeSnapshotDeleted, + ErrorCodeSnapshotIdInvalid, + ErrorCodeSnapshotInProgress, + ErrorCodeSnapshotNotFound, + ErrorCodeSnapshotScheduleNotFound, + ErrorCodeStagingAreaFull, + ErrorCodeStorageFailure, + ErrorCodeTapeCartridgeNotFound, + ErrorCodeTargetAlreadyExists, + ErrorCodeTargetInvalid, + ErrorCodeTargetNotFound, + ErrorCodeUnauthorizedOperation, + ErrorCodeVolumeAlreadyExists, + ErrorCodeVolumeIdInvalid, + ErrorCodeVolumeInUse, + ErrorCodeVolumeNotFound, + ErrorCodeVolumeNotReady, + } +} + // The type of the file share. const ( // FileShareTypeNfs is a FileShareType enum value @@ -18859,6 +19313,14 @@ const ( FileShareTypeSmb = "SMB" ) +// FileShareType_Values returns all elements of the FileShareType enum +func FileShareType_Values() []string { + return []string{ + FileShareTypeNfs, + FileShareTypeSmb, + } +} + const ( // HostEnvironmentVmware is a HostEnvironment enum value HostEnvironmentVmware = "VMWARE" @@ -18876,8 +19338,20 @@ const ( HostEnvironmentOther = "OTHER" ) -// A value that sets the access control list permission for objects in the S3 -// bucket that a file gateway puts objects into. The default value is "private". +// HostEnvironment_Values returns all elements of the HostEnvironment enum +func HostEnvironment_Values() []string { + return []string{ + HostEnvironmentVmware, + HostEnvironmentHyperV, + HostEnvironmentEc2, + HostEnvironmentKvm, + HostEnvironmentOther, + } +} + +// A value that sets the access control list (ACL) permission for objects in +// the S3 bucket that a file gateway puts objects into. The default value is +// private. const ( // ObjectACLPrivate is a ObjectACL enum value ObjectACLPrivate = "private" @@ -18901,6 +19375,19 @@ const ( ObjectACLAwsExecRead = "aws-exec-read" ) +// ObjectACL_Values returns all elements of the ObjectACL enum +func ObjectACL_Values() []string { + return []string{ + ObjectACLPrivate, + ObjectACLPublicRead, + ObjectACLPublicReadWrite, + ObjectACLAuthenticatedRead, + ObjectACLBucketOwnerRead, + ObjectACLBucketOwnerFullControl, + ObjectACLAwsExecRead, + } +} + const ( // SMBSecurityStrategyClientSpecified is a SMBSecurityStrategy enum value SMBSecurityStrategyClientSpecified = "ClientSpecified" @@ -18911,3 +19398,12 @@ const ( // SMBSecurityStrategyMandatoryEncryption is a SMBSecurityStrategy enum value SMBSecurityStrategyMandatoryEncryption = "MandatoryEncryption" ) + +// SMBSecurityStrategy_Values returns all elements of the SMBSecurityStrategy enum +func SMBSecurityStrategy_Values() []string { + return []string{ + SMBSecurityStrategyClientSpecified, + SMBSecurityStrategyMandatorySigning, + SMBSecurityStrategyMandatoryEncryption, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/storagegateway/doc.go b/vendor/github.com/aws/aws-sdk-go/service/storagegateway/doc.go index 61d492bc29b..773ea9ee1c5 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/storagegateway/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/storagegateway/doc.go @@ -12,15 +12,15 @@ // Use the following links to get started using the AWS Storage Gateway Service // API Reference: // -// * AWS Storage Gateway Required Request Headers (https://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#AWSStorageGatewayHTTPRequestsHeaders): +// * AWS Storage Gateway required request headers (https://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#AWSStorageGatewayHTTPRequestsHeaders): // Describes the required headers that you must send with every POST request // to AWS Storage Gateway. // -// * Signing Requests (https://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#AWSStorageGatewaySigningRequests): +// * Signing requests (https://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#AWSStorageGatewaySigningRequests): // AWS Storage Gateway requires that you authenticate every request you send; // this topic describes how sign such a request. // -// * Error Responses (https://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#APIErrorResponses): +// * Error responses (https://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html#APIErrorResponses): // Provides reference information about AWS Storage Gateway errors. // // * Operations in AWS Storage Gateway (https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_Operations.html): @@ -28,7 +28,7 @@ // their request parameters, response elements, possible errors, and examples // of requests and responses. // -// * AWS Storage Gateway Regions and Endpoints: (http://docs.aws.amazon.com/general/latest/gr/rande.html#sg_region) +// * AWS Storage Gateway endpoints and quotas: (https://docs.aws.amazon.com/general/latest/gr/sg.html) // Provides a list of each AWS Region and the endpoints available for use // with AWS Storage Gateway. // @@ -44,7 +44,7 @@ // volumes and snapshots will be created with a 17-character string. Starting // in April 2016, you will be able to use these longer IDs so you can test your // systems with the new format. For more information, see Longer EC2 and EBS -// Resource IDs (https://aws.amazon.com/ec2/faqs/#longer-ids). +// resource IDs (http://aws.amazon.com/ec2/faqs/#longer-ids). // // For example, a volume Amazon Resource Name (ARN) with the longer volume ID // format looks like the following: @@ -54,7 +54,7 @@ // A snapshot ID with the longer ID format looks like the following: snap-78e226633445566ee. // // For more information, see Announcement: Heads-up – Longer AWS Storage Gateway -// volume and snapshot IDs coming in 2016 (https://forums.aws.amazon.com/ann.jspa?annID=3557). +// volume and snapshot IDs coming in 2016 (http://forums.aws.amazon.com/ann.jspa?annID=3557). // // See https://docs.aws.amazon.com/goto/WebAPI/storagegateway-2013-06-30 for more information on this service. // 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 7f60d4aa185..550b5f687f9 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go @@ -1788,7 +1788,7 @@ type AssumeRoleWithSAMLInput struct { // in the IAM User Guide. // // SAMLAssertion is a required field - SAMLAssertion *string `min:"4" type:"string" required:"true"` + SAMLAssertion *string `min:"4" type:"string" required:"true" sensitive:"true"` } // String returns the string representation @@ -2100,7 +2100,7 @@ type AssumeRoleWithWebIdentityInput struct { // the application makes an AssumeRoleWithWebIdentity call. // // WebIdentityToken is a required field - WebIdentityToken *string `min:"4" type:"string" required:"true"` + WebIdentityToken *string `min:"4" type:"string" required:"true" sensitive:"true"` } // String returns the string representation diff --git a/vendor/github.com/aws/aws-sdk-go/service/swf/api.go b/vendor/github.com/aws/aws-sdk-go/service/swf/api.go index bd25e12c8fa..746d05b1121 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/swf/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/swf/api.go @@ -16607,6 +16607,16 @@ const ( ActivityTaskTimeoutTypeHeartbeat = "HEARTBEAT" ) +// ActivityTaskTimeoutType_Values returns all elements of the ActivityTaskTimeoutType enum +func ActivityTaskTimeoutType_Values() []string { + return []string{ + ActivityTaskTimeoutTypeStartToClose, + ActivityTaskTimeoutTypeScheduleToStart, + ActivityTaskTimeoutTypeScheduleToClose, + ActivityTaskTimeoutTypeHeartbeat, + } +} + const ( // CancelTimerFailedCauseTimerIdUnknown is a CancelTimerFailedCause enum value CancelTimerFailedCauseTimerIdUnknown = "TIMER_ID_UNKNOWN" @@ -16615,6 +16625,14 @@ const ( CancelTimerFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// CancelTimerFailedCause_Values returns all elements of the CancelTimerFailedCause enum +func CancelTimerFailedCause_Values() []string { + return []string{ + CancelTimerFailedCauseTimerIdUnknown, + CancelTimerFailedCauseOperationNotPermitted, + } +} + const ( // CancelWorkflowExecutionFailedCauseUnhandledDecision is a CancelWorkflowExecutionFailedCause enum value CancelWorkflowExecutionFailedCauseUnhandledDecision = "UNHANDLED_DECISION" @@ -16623,6 +16641,14 @@ const ( CancelWorkflowExecutionFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// CancelWorkflowExecutionFailedCause_Values returns all elements of the CancelWorkflowExecutionFailedCause enum +func CancelWorkflowExecutionFailedCause_Values() []string { + return []string{ + CancelWorkflowExecutionFailedCauseUnhandledDecision, + CancelWorkflowExecutionFailedCauseOperationNotPermitted, + } +} + const ( // ChildPolicyTerminate is a ChildPolicy enum value ChildPolicyTerminate = "TERMINATE" @@ -16634,6 +16660,15 @@ const ( ChildPolicyAbandon = "ABANDON" ) +// ChildPolicy_Values returns all elements of the ChildPolicy enum +func ChildPolicy_Values() []string { + return []string{ + ChildPolicyTerminate, + ChildPolicyRequestCancel, + ChildPolicyAbandon, + } +} + const ( // CloseStatusCompleted is a CloseStatus enum value CloseStatusCompleted = "COMPLETED" @@ -16654,6 +16689,18 @@ const ( CloseStatusTimedOut = "TIMED_OUT" ) +// CloseStatus_Values returns all elements of the CloseStatus enum +func CloseStatus_Values() []string { + return []string{ + CloseStatusCompleted, + CloseStatusFailed, + CloseStatusCanceled, + CloseStatusTerminated, + CloseStatusContinuedAsNew, + CloseStatusTimedOut, + } +} + const ( // CompleteWorkflowExecutionFailedCauseUnhandledDecision is a CompleteWorkflowExecutionFailedCause enum value CompleteWorkflowExecutionFailedCauseUnhandledDecision = "UNHANDLED_DECISION" @@ -16662,6 +16709,14 @@ const ( CompleteWorkflowExecutionFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// CompleteWorkflowExecutionFailedCause_Values returns all elements of the CompleteWorkflowExecutionFailedCause enum +func CompleteWorkflowExecutionFailedCause_Values() []string { + return []string{ + CompleteWorkflowExecutionFailedCauseUnhandledDecision, + CompleteWorkflowExecutionFailedCauseOperationNotPermitted, + } +} + const ( // ContinueAsNewWorkflowExecutionFailedCauseUnhandledDecision is a ContinueAsNewWorkflowExecutionFailedCause enum value ContinueAsNewWorkflowExecutionFailedCauseUnhandledDecision = "UNHANDLED_DECISION" @@ -16691,11 +16746,33 @@ const ( ContinueAsNewWorkflowExecutionFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// ContinueAsNewWorkflowExecutionFailedCause_Values returns all elements of the ContinueAsNewWorkflowExecutionFailedCause enum +func ContinueAsNewWorkflowExecutionFailedCause_Values() []string { + return []string{ + ContinueAsNewWorkflowExecutionFailedCauseUnhandledDecision, + ContinueAsNewWorkflowExecutionFailedCauseWorkflowTypeDeprecated, + ContinueAsNewWorkflowExecutionFailedCauseWorkflowTypeDoesNotExist, + ContinueAsNewWorkflowExecutionFailedCauseDefaultExecutionStartToCloseTimeoutUndefined, + ContinueAsNewWorkflowExecutionFailedCauseDefaultTaskStartToCloseTimeoutUndefined, + ContinueAsNewWorkflowExecutionFailedCauseDefaultTaskListUndefined, + ContinueAsNewWorkflowExecutionFailedCauseDefaultChildPolicyUndefined, + ContinueAsNewWorkflowExecutionFailedCauseContinueAsNewWorkflowExecutionRateExceeded, + ContinueAsNewWorkflowExecutionFailedCauseOperationNotPermitted, + } +} + const ( // DecisionTaskTimeoutTypeStartToClose is a DecisionTaskTimeoutType enum value DecisionTaskTimeoutTypeStartToClose = "START_TO_CLOSE" ) +// DecisionTaskTimeoutType_Values returns all elements of the DecisionTaskTimeoutType enum +func DecisionTaskTimeoutType_Values() []string { + return []string{ + DecisionTaskTimeoutTypeStartToClose, + } +} + const ( // DecisionTypeScheduleActivityTask is a DecisionType enum value DecisionTypeScheduleActivityTask = "ScheduleActivityTask" @@ -16737,6 +16814,25 @@ const ( DecisionTypeScheduleLambdaFunction = "ScheduleLambdaFunction" ) +// DecisionType_Values returns all elements of the DecisionType enum +func DecisionType_Values() []string { + return []string{ + DecisionTypeScheduleActivityTask, + DecisionTypeRequestCancelActivityTask, + DecisionTypeCompleteWorkflowExecution, + DecisionTypeFailWorkflowExecution, + DecisionTypeCancelWorkflowExecution, + DecisionTypeContinueAsNewWorkflowExecution, + DecisionTypeRecordMarker, + DecisionTypeStartTimer, + DecisionTypeCancelTimer, + DecisionTypeSignalExternalWorkflowExecution, + DecisionTypeRequestCancelExternalWorkflowExecution, + DecisionTypeStartChildWorkflowExecution, + DecisionTypeScheduleLambdaFunction, + } +} + const ( // EventTypeWorkflowExecutionStarted is a EventType enum value EventTypeWorkflowExecutionStarted = "WorkflowExecutionStarted" @@ -16901,6 +16997,66 @@ const ( EventTypeStartLambdaFunctionFailed = "StartLambdaFunctionFailed" ) +// EventType_Values returns all elements of the EventType enum +func EventType_Values() []string { + return []string{ + EventTypeWorkflowExecutionStarted, + EventTypeWorkflowExecutionCancelRequested, + EventTypeWorkflowExecutionCompleted, + EventTypeCompleteWorkflowExecutionFailed, + EventTypeWorkflowExecutionFailed, + EventTypeFailWorkflowExecutionFailed, + EventTypeWorkflowExecutionTimedOut, + EventTypeWorkflowExecutionCanceled, + EventTypeCancelWorkflowExecutionFailed, + EventTypeWorkflowExecutionContinuedAsNew, + EventTypeContinueAsNewWorkflowExecutionFailed, + EventTypeWorkflowExecutionTerminated, + EventTypeDecisionTaskScheduled, + EventTypeDecisionTaskStarted, + EventTypeDecisionTaskCompleted, + EventTypeDecisionTaskTimedOut, + EventTypeActivityTaskScheduled, + EventTypeScheduleActivityTaskFailed, + EventTypeActivityTaskStarted, + EventTypeActivityTaskCompleted, + EventTypeActivityTaskFailed, + EventTypeActivityTaskTimedOut, + EventTypeActivityTaskCanceled, + EventTypeActivityTaskCancelRequested, + EventTypeRequestCancelActivityTaskFailed, + EventTypeWorkflowExecutionSignaled, + EventTypeMarkerRecorded, + EventTypeRecordMarkerFailed, + EventTypeTimerStarted, + EventTypeStartTimerFailed, + EventTypeTimerFired, + EventTypeTimerCanceled, + EventTypeCancelTimerFailed, + EventTypeStartChildWorkflowExecutionInitiated, + EventTypeStartChildWorkflowExecutionFailed, + EventTypeChildWorkflowExecutionStarted, + EventTypeChildWorkflowExecutionCompleted, + EventTypeChildWorkflowExecutionFailed, + EventTypeChildWorkflowExecutionTimedOut, + EventTypeChildWorkflowExecutionCanceled, + EventTypeChildWorkflowExecutionTerminated, + EventTypeSignalExternalWorkflowExecutionInitiated, + EventTypeSignalExternalWorkflowExecutionFailed, + EventTypeExternalWorkflowExecutionSignaled, + EventTypeRequestCancelExternalWorkflowExecutionInitiated, + EventTypeRequestCancelExternalWorkflowExecutionFailed, + EventTypeExternalWorkflowExecutionCancelRequested, + EventTypeLambdaFunctionScheduled, + EventTypeLambdaFunctionStarted, + EventTypeLambdaFunctionCompleted, + EventTypeLambdaFunctionFailed, + EventTypeLambdaFunctionTimedOut, + EventTypeScheduleLambdaFunctionFailed, + EventTypeStartLambdaFunctionFailed, + } +} + const ( // ExecutionStatusOpen is a ExecutionStatus enum value ExecutionStatusOpen = "OPEN" @@ -16909,6 +17065,14 @@ const ( ExecutionStatusClosed = "CLOSED" ) +// ExecutionStatus_Values returns all elements of the ExecutionStatus enum +func ExecutionStatus_Values() []string { + return []string{ + ExecutionStatusOpen, + ExecutionStatusClosed, + } +} + const ( // FailWorkflowExecutionFailedCauseUnhandledDecision is a FailWorkflowExecutionFailedCause enum value FailWorkflowExecutionFailedCauseUnhandledDecision = "UNHANDLED_DECISION" @@ -16917,16 +17081,38 @@ const ( FailWorkflowExecutionFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// FailWorkflowExecutionFailedCause_Values returns all elements of the FailWorkflowExecutionFailedCause enum +func FailWorkflowExecutionFailedCause_Values() []string { + return []string{ + FailWorkflowExecutionFailedCauseUnhandledDecision, + FailWorkflowExecutionFailedCauseOperationNotPermitted, + } +} + const ( // LambdaFunctionTimeoutTypeStartToClose is a LambdaFunctionTimeoutType enum value LambdaFunctionTimeoutTypeStartToClose = "START_TO_CLOSE" ) +// LambdaFunctionTimeoutType_Values returns all elements of the LambdaFunctionTimeoutType enum +func LambdaFunctionTimeoutType_Values() []string { + return []string{ + LambdaFunctionTimeoutTypeStartToClose, + } +} + const ( // RecordMarkerFailedCauseOperationNotPermitted is a RecordMarkerFailedCause enum value RecordMarkerFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// RecordMarkerFailedCause_Values returns all elements of the RecordMarkerFailedCause enum +func RecordMarkerFailedCause_Values() []string { + return []string{ + RecordMarkerFailedCauseOperationNotPermitted, + } +} + const ( // RegistrationStatusRegistered is a RegistrationStatus enum value RegistrationStatusRegistered = "REGISTERED" @@ -16935,6 +17121,14 @@ const ( RegistrationStatusDeprecated = "DEPRECATED" ) +// RegistrationStatus_Values returns all elements of the RegistrationStatus enum +func RegistrationStatus_Values() []string { + return []string{ + RegistrationStatusRegistered, + RegistrationStatusDeprecated, + } +} + const ( // RequestCancelActivityTaskFailedCauseActivityIdUnknown is a RequestCancelActivityTaskFailedCause enum value RequestCancelActivityTaskFailedCauseActivityIdUnknown = "ACTIVITY_ID_UNKNOWN" @@ -16943,6 +17137,14 @@ const ( RequestCancelActivityTaskFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// RequestCancelActivityTaskFailedCause_Values returns all elements of the RequestCancelActivityTaskFailedCause enum +func RequestCancelActivityTaskFailedCause_Values() []string { + return []string{ + RequestCancelActivityTaskFailedCauseActivityIdUnknown, + RequestCancelActivityTaskFailedCauseOperationNotPermitted, + } +} + const ( // RequestCancelExternalWorkflowExecutionFailedCauseUnknownExternalWorkflowExecution is a RequestCancelExternalWorkflowExecutionFailedCause enum value RequestCancelExternalWorkflowExecutionFailedCauseUnknownExternalWorkflowExecution = "UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION" @@ -16954,6 +17156,15 @@ const ( RequestCancelExternalWorkflowExecutionFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// RequestCancelExternalWorkflowExecutionFailedCause_Values returns all elements of the RequestCancelExternalWorkflowExecutionFailedCause enum +func RequestCancelExternalWorkflowExecutionFailedCause_Values() []string { + return []string{ + RequestCancelExternalWorkflowExecutionFailedCauseUnknownExternalWorkflowExecution, + RequestCancelExternalWorkflowExecutionFailedCauseRequestCancelExternalWorkflowExecutionRateExceeded, + RequestCancelExternalWorkflowExecutionFailedCauseOperationNotPermitted, + } +} + const ( // ScheduleActivityTaskFailedCauseActivityTypeDeprecated is a ScheduleActivityTaskFailedCause enum value ScheduleActivityTaskFailedCauseActivityTypeDeprecated = "ACTIVITY_TYPE_DEPRECATED" @@ -16989,6 +17200,23 @@ const ( ScheduleActivityTaskFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// ScheduleActivityTaskFailedCause_Values returns all elements of the ScheduleActivityTaskFailedCause enum +func ScheduleActivityTaskFailedCause_Values() []string { + return []string{ + ScheduleActivityTaskFailedCauseActivityTypeDeprecated, + ScheduleActivityTaskFailedCauseActivityTypeDoesNotExist, + ScheduleActivityTaskFailedCauseActivityIdAlreadyInUse, + ScheduleActivityTaskFailedCauseOpenActivitiesLimitExceeded, + ScheduleActivityTaskFailedCauseActivityCreationRateExceeded, + ScheduleActivityTaskFailedCauseDefaultScheduleToCloseTimeoutUndefined, + ScheduleActivityTaskFailedCauseDefaultTaskListUndefined, + ScheduleActivityTaskFailedCauseDefaultScheduleToStartTimeoutUndefined, + ScheduleActivityTaskFailedCauseDefaultStartToCloseTimeoutUndefined, + ScheduleActivityTaskFailedCauseDefaultHeartbeatTimeoutUndefined, + ScheduleActivityTaskFailedCauseOperationNotPermitted, + } +} + const ( // ScheduleLambdaFunctionFailedCauseIdAlreadyInUse is a ScheduleLambdaFunctionFailedCause enum value ScheduleLambdaFunctionFailedCauseIdAlreadyInUse = "ID_ALREADY_IN_USE" @@ -17003,6 +17231,16 @@ const ( ScheduleLambdaFunctionFailedCauseLambdaServiceNotAvailableInRegion = "LAMBDA_SERVICE_NOT_AVAILABLE_IN_REGION" ) +// ScheduleLambdaFunctionFailedCause_Values returns all elements of the ScheduleLambdaFunctionFailedCause enum +func ScheduleLambdaFunctionFailedCause_Values() []string { + return []string{ + ScheduleLambdaFunctionFailedCauseIdAlreadyInUse, + ScheduleLambdaFunctionFailedCauseOpenLambdaFunctionsLimitExceeded, + ScheduleLambdaFunctionFailedCauseLambdaFunctionCreationRateExceeded, + ScheduleLambdaFunctionFailedCauseLambdaServiceNotAvailableInRegion, + } +} + const ( // SignalExternalWorkflowExecutionFailedCauseUnknownExternalWorkflowExecution is a SignalExternalWorkflowExecutionFailedCause enum value SignalExternalWorkflowExecutionFailedCauseUnknownExternalWorkflowExecution = "UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION" @@ -17014,6 +17252,15 @@ const ( SignalExternalWorkflowExecutionFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// SignalExternalWorkflowExecutionFailedCause_Values returns all elements of the SignalExternalWorkflowExecutionFailedCause enum +func SignalExternalWorkflowExecutionFailedCause_Values() []string { + return []string{ + SignalExternalWorkflowExecutionFailedCauseUnknownExternalWorkflowExecution, + SignalExternalWorkflowExecutionFailedCauseSignalExternalWorkflowExecutionRateExceeded, + SignalExternalWorkflowExecutionFailedCauseOperationNotPermitted, + } +} + const ( // StartChildWorkflowExecutionFailedCauseWorkflowTypeDoesNotExist is a StartChildWorkflowExecutionFailedCause enum value StartChildWorkflowExecutionFailedCauseWorkflowTypeDoesNotExist = "WORKFLOW_TYPE_DOES_NOT_EXIST" @@ -17049,11 +17296,35 @@ const ( StartChildWorkflowExecutionFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// StartChildWorkflowExecutionFailedCause_Values returns all elements of the StartChildWorkflowExecutionFailedCause enum +func StartChildWorkflowExecutionFailedCause_Values() []string { + return []string{ + StartChildWorkflowExecutionFailedCauseWorkflowTypeDoesNotExist, + StartChildWorkflowExecutionFailedCauseWorkflowTypeDeprecated, + StartChildWorkflowExecutionFailedCauseOpenChildrenLimitExceeded, + StartChildWorkflowExecutionFailedCauseOpenWorkflowsLimitExceeded, + StartChildWorkflowExecutionFailedCauseChildCreationRateExceeded, + StartChildWorkflowExecutionFailedCauseWorkflowAlreadyRunning, + StartChildWorkflowExecutionFailedCauseDefaultExecutionStartToCloseTimeoutUndefined, + StartChildWorkflowExecutionFailedCauseDefaultTaskListUndefined, + StartChildWorkflowExecutionFailedCauseDefaultTaskStartToCloseTimeoutUndefined, + StartChildWorkflowExecutionFailedCauseDefaultChildPolicyUndefined, + StartChildWorkflowExecutionFailedCauseOperationNotPermitted, + } +} + const ( // StartLambdaFunctionFailedCauseAssumeRoleFailed is a StartLambdaFunctionFailedCause enum value StartLambdaFunctionFailedCauseAssumeRoleFailed = "ASSUME_ROLE_FAILED" ) +// StartLambdaFunctionFailedCause_Values returns all elements of the StartLambdaFunctionFailedCause enum +func StartLambdaFunctionFailedCause_Values() []string { + return []string{ + StartLambdaFunctionFailedCauseAssumeRoleFailed, + } +} + const ( // StartTimerFailedCauseTimerIdAlreadyInUse is a StartTimerFailedCause enum value StartTimerFailedCauseTimerIdAlreadyInUse = "TIMER_ID_ALREADY_IN_USE" @@ -17068,11 +17339,28 @@ const ( StartTimerFailedCauseOperationNotPermitted = "OPERATION_NOT_PERMITTED" ) +// StartTimerFailedCause_Values returns all elements of the StartTimerFailedCause enum +func StartTimerFailedCause_Values() []string { + return []string{ + StartTimerFailedCauseTimerIdAlreadyInUse, + StartTimerFailedCauseOpenTimersLimitExceeded, + StartTimerFailedCauseTimerCreationRateExceeded, + StartTimerFailedCauseOperationNotPermitted, + } +} + const ( // WorkflowExecutionCancelRequestedCauseChildPolicyApplied is a WorkflowExecutionCancelRequestedCause enum value WorkflowExecutionCancelRequestedCauseChildPolicyApplied = "CHILD_POLICY_APPLIED" ) +// WorkflowExecutionCancelRequestedCause_Values returns all elements of the WorkflowExecutionCancelRequestedCause enum +func WorkflowExecutionCancelRequestedCause_Values() []string { + return []string{ + WorkflowExecutionCancelRequestedCauseChildPolicyApplied, + } +} + const ( // WorkflowExecutionTerminatedCauseChildPolicyApplied is a WorkflowExecutionTerminatedCause enum value WorkflowExecutionTerminatedCauseChildPolicyApplied = "CHILD_POLICY_APPLIED" @@ -17084,7 +17372,23 @@ const ( WorkflowExecutionTerminatedCauseOperatorInitiated = "OPERATOR_INITIATED" ) +// WorkflowExecutionTerminatedCause_Values returns all elements of the WorkflowExecutionTerminatedCause enum +func WorkflowExecutionTerminatedCause_Values() []string { + return []string{ + WorkflowExecutionTerminatedCauseChildPolicyApplied, + WorkflowExecutionTerminatedCauseEventLimitExceeded, + WorkflowExecutionTerminatedCauseOperatorInitiated, + } +} + const ( // WorkflowExecutionTimeoutTypeStartToClose is a WorkflowExecutionTimeoutType enum value WorkflowExecutionTimeoutTypeStartToClose = "START_TO_CLOSE" ) + +// WorkflowExecutionTimeoutType_Values returns all elements of the WorkflowExecutionTimeoutType enum +func WorkflowExecutionTimeoutType_Values() []string { + return []string{ + WorkflowExecutionTimeoutTypeStartToClose, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/synthetics/api.go b/vendor/github.com/aws/aws-sdk-go/service/synthetics/api.go new file mode 100644 index 00000000000..107217f226f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/synthetics/api.go @@ -0,0 +1,3856 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package synthetics + +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/restjson" +) + +const opCreateCanary = "CreateCanary" + +// CreateCanaryRequest generates a "aws/request.Request" representing the +// client's request for the CreateCanary operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateCanary for more information on using the CreateCanary +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateCanaryRequest method. +// req, resp := client.CreateCanaryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CreateCanary +func (c *Synthetics) CreateCanaryRequest(input *CreateCanaryInput) (req *request.Request, output *CreateCanaryOutput) { + op := &request.Operation{ + Name: opCreateCanary, + HTTPMethod: "POST", + HTTPPath: "/canary", + } + + if input == nil { + input = &CreateCanaryInput{} + } + + output = &CreateCanaryOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateCanary API operation for Synthetics. +// +// Creates a canary. Canaries are scripts that monitor your endpoints and APIs +// from the outside-in. Canaries help you check the availability and latency +// of your web services and troubleshoot anomalies by investigating load time +// data, screenshots of the UI, logs, and metrics. You can set up a canary to +// run continuously or just once. +// +// Do not use CreateCanary to modify an existing canary. Use UpdateCanary (https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_UpdateCanary.html) +// instead. +// +// To create canaries, you must have the CloudWatchSyntheticsFullAccess policy. +// If you are creating a new IAM role for the canary, you also need the the +// iam:CreateRole, iam:CreatePolicy and iam:AttachRolePolicy permissions. For +// more information, see Necessary Roles and Permissions (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Roles). +// +// Do not include secrets or proprietary information in your canary names. The +// canary name makes up part of the Amazon Resource Name (ARN) for the canary, +// and the ARN is included in outbound calls over the internet. For more information, +// see Security Considerations for Synthetics Canaries (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Synthetics's +// API operation CreateCanary for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ValidationException +// A parameter could not be validated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CreateCanary +func (c *Synthetics) CreateCanary(input *CreateCanaryInput) (*CreateCanaryOutput, error) { + req, out := c.CreateCanaryRequest(input) + return out, req.Send() +} + +// CreateCanaryWithContext is the same as CreateCanary with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCanary for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) CreateCanaryWithContext(ctx aws.Context, input *CreateCanaryInput, opts ...request.Option) (*CreateCanaryOutput, error) { + req, out := c.CreateCanaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDeleteCanary = "DeleteCanary" + +// DeleteCanaryRequest generates a "aws/request.Request" representing the +// client's request for the DeleteCanary operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteCanary for more information on using the DeleteCanary +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteCanaryRequest method. +// req, resp := client.DeleteCanaryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DeleteCanary +func (c *Synthetics) DeleteCanaryRequest(input *DeleteCanaryInput) (req *request.Request, output *DeleteCanaryOutput) { + op := &request.Operation{ + Name: opDeleteCanary, + HTTPMethod: "DELETE", + HTTPPath: "/canary/{name}", + } + + if input == nil { + input = &DeleteCanaryInput{} + } + + output = &DeleteCanaryOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteCanary API operation for Synthetics. +// +// Permanently deletes the specified canary. +// +// When you delete a canary, resources used and created by the canary are not +// automatically deleted. After you delete a canary that you do not intend to +// use again, you should also delete the following: +// +// * The Lambda functions and layers used by this canary. These have the +// prefix cwsyn-MyCanaryName . +// +// * The CloudWatch alarms created for this canary. These alarms have a name +// of Synthetics-SharpDrop-Alarm-MyCanaryName . +// +// * Amazon S3 objects and buckets, such as the canary's artifact location. +// +// * IAM roles created for the canary. If they were created in the console, +// these roles have the name role/service-role/CloudWatchSyntheticsRole-MyCanaryName . +// +// * CloudWatch Logs log groups created for the canary. These logs groups +// have the name /aws/lambda/cwsyn-MyCanaryName . +// +// Before you delete a canary, you might want to use GetCanary to display the +// information about this canary. Make note of the information returned by this +// operation so that you can delete these resources after you delete the canary. +// +// Returns awserr.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 Synthetics's +// API operation DeleteCanary for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ValidationException +// A parameter could not be validated. +// +// * ResourceNotFoundException +// One of the specified resources was not found. +// +// * ConflictException +// A conflicting operation is already in progress. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DeleteCanary +func (c *Synthetics) DeleteCanary(input *DeleteCanaryInput) (*DeleteCanaryOutput, error) { + req, out := c.DeleteCanaryRequest(input) + return out, req.Send() +} + +// DeleteCanaryWithContext is the same as DeleteCanary with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCanary for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) DeleteCanaryWithContext(ctx aws.Context, input *DeleteCanaryInput, opts ...request.Option) (*DeleteCanaryOutput, error) { + req, out := c.DeleteCanaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDescribeCanaries = "DescribeCanaries" + +// DescribeCanariesRequest generates a "aws/request.Request" representing the +// client's request for the DescribeCanaries operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeCanaries for more information on using the DescribeCanaries +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeCanariesRequest method. +// req, resp := client.DescribeCanariesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeCanaries +func (c *Synthetics) DescribeCanariesRequest(input *DescribeCanariesInput) (req *request.Request, output *DescribeCanariesOutput) { + op := &request.Operation{ + Name: opDescribeCanaries, + HTTPMethod: "POST", + HTTPPath: "/canaries", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeCanariesInput{} + } + + output = &DescribeCanariesOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeCanaries API operation for Synthetics. +// +// This operation returns a list of the canaries in your account, along with +// full details about each canary. +// +// This operation does not have resource-level authorization, so if a user is +// able to use DescribeCanaries, the user can see all of the canaries in the +// account. A deny policy can only be used to restrict access to all canaries. +// It cannot be used on specific resources. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Synthetics's +// API operation DescribeCanaries for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ValidationException +// A parameter could not be validated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeCanaries +func (c *Synthetics) DescribeCanaries(input *DescribeCanariesInput) (*DescribeCanariesOutput, error) { + req, out := c.DescribeCanariesRequest(input) + return out, req.Send() +} + +// DescribeCanariesWithContext is the same as DescribeCanaries with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCanaries for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) DescribeCanariesWithContext(ctx aws.Context, input *DescribeCanariesInput, opts ...request.Option) (*DescribeCanariesOutput, error) { + req, out := c.DescribeCanariesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeCanariesPages iterates over the pages of a DescribeCanaries operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeCanaries 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 DescribeCanaries operation. +// pageNum := 0 +// err := client.DescribeCanariesPages(params, +// func(page *synthetics.DescribeCanariesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Synthetics) DescribeCanariesPages(input *DescribeCanariesInput, fn func(*DescribeCanariesOutput, bool) bool) error { + return c.DescribeCanariesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCanariesPagesWithContext same as DescribeCanariesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) DescribeCanariesPagesWithContext(ctx aws.Context, input *DescribeCanariesInput, fn func(*DescribeCanariesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCanariesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCanariesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeCanariesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opDescribeCanariesLastRun = "DescribeCanariesLastRun" + +// DescribeCanariesLastRunRequest generates a "aws/request.Request" representing the +// client's request for the DescribeCanariesLastRun operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeCanariesLastRun for more information on using the DescribeCanariesLastRun +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeCanariesLastRunRequest method. +// req, resp := client.DescribeCanariesLastRunRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeCanariesLastRun +func (c *Synthetics) DescribeCanariesLastRunRequest(input *DescribeCanariesLastRunInput) (req *request.Request, output *DescribeCanariesLastRunOutput) { + op := &request.Operation{ + Name: opDescribeCanariesLastRun, + HTTPMethod: "POST", + HTTPPath: "/canaries/last-run", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeCanariesLastRunInput{} + } + + output = &DescribeCanariesLastRunOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeCanariesLastRun API operation for Synthetics. +// +// Use this operation to see information from the most recent run of each canary +// that you have 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 +// the error. +// +// See the AWS API reference guide for Synthetics's +// API operation DescribeCanariesLastRun for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ValidationException +// A parameter could not be validated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeCanariesLastRun +func (c *Synthetics) DescribeCanariesLastRun(input *DescribeCanariesLastRunInput) (*DescribeCanariesLastRunOutput, error) { + req, out := c.DescribeCanariesLastRunRequest(input) + return out, req.Send() +} + +// DescribeCanariesLastRunWithContext is the same as DescribeCanariesLastRun with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCanariesLastRun for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) DescribeCanariesLastRunWithContext(ctx aws.Context, input *DescribeCanariesLastRunInput, opts ...request.Option) (*DescribeCanariesLastRunOutput, error) { + req, out := c.DescribeCanariesLastRunRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeCanariesLastRunPages iterates over the pages of a DescribeCanariesLastRun operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeCanariesLastRun 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 DescribeCanariesLastRun operation. +// pageNum := 0 +// err := client.DescribeCanariesLastRunPages(params, +// func(page *synthetics.DescribeCanariesLastRunOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Synthetics) DescribeCanariesLastRunPages(input *DescribeCanariesLastRunInput, fn func(*DescribeCanariesLastRunOutput, bool) bool) error { + return c.DescribeCanariesLastRunPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCanariesLastRunPagesWithContext same as DescribeCanariesLastRunPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) DescribeCanariesLastRunPagesWithContext(ctx aws.Context, input *DescribeCanariesLastRunInput, fn func(*DescribeCanariesLastRunOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCanariesLastRunInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCanariesLastRunRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeCanariesLastRunOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opDescribeRuntimeVersions = "DescribeRuntimeVersions" + +// DescribeRuntimeVersionsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeRuntimeVersions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeRuntimeVersions for more information on using the DescribeRuntimeVersions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeRuntimeVersionsRequest method. +// req, resp := client.DescribeRuntimeVersionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeRuntimeVersions +func (c *Synthetics) DescribeRuntimeVersionsRequest(input *DescribeRuntimeVersionsInput) (req *request.Request, output *DescribeRuntimeVersionsOutput) { + op := &request.Operation{ + Name: opDescribeRuntimeVersions, + HTTPMethod: "POST", + HTTPPath: "/runtime-versions", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeRuntimeVersionsInput{} + } + + output = &DescribeRuntimeVersionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeRuntimeVersions API operation for Synthetics. +// +// Returns a list of Synthetics canary runtime versions. For more information, +// see Canary Runtime Versions (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Synthetics's +// API operation DescribeRuntimeVersions for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ValidationException +// A parameter could not be validated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeRuntimeVersions +func (c *Synthetics) DescribeRuntimeVersions(input *DescribeRuntimeVersionsInput) (*DescribeRuntimeVersionsOutput, error) { + req, out := c.DescribeRuntimeVersionsRequest(input) + return out, req.Send() +} + +// DescribeRuntimeVersionsWithContext is the same as DescribeRuntimeVersions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeRuntimeVersions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) DescribeRuntimeVersionsWithContext(ctx aws.Context, input *DescribeRuntimeVersionsInput, opts ...request.Option) (*DescribeRuntimeVersionsOutput, error) { + req, out := c.DescribeRuntimeVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeRuntimeVersionsPages iterates over the pages of a DescribeRuntimeVersions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeRuntimeVersions 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 DescribeRuntimeVersions operation. +// pageNum := 0 +// err := client.DescribeRuntimeVersionsPages(params, +// func(page *synthetics.DescribeRuntimeVersionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Synthetics) DescribeRuntimeVersionsPages(input *DescribeRuntimeVersionsInput, fn func(*DescribeRuntimeVersionsOutput, bool) bool) error { + return c.DescribeRuntimeVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeRuntimeVersionsPagesWithContext same as DescribeRuntimeVersionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) DescribeRuntimeVersionsPagesWithContext(ctx aws.Context, input *DescribeRuntimeVersionsInput, fn func(*DescribeRuntimeVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeRuntimeVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeRuntimeVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeRuntimeVersionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opGetCanary = "GetCanary" + +// GetCanaryRequest generates a "aws/request.Request" representing the +// client's request for the GetCanary operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetCanary for more information on using the GetCanary +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetCanaryRequest method. +// req, resp := client.GetCanaryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/GetCanary +func (c *Synthetics) GetCanaryRequest(input *GetCanaryInput) (req *request.Request, output *GetCanaryOutput) { + op := &request.Operation{ + Name: opGetCanary, + HTTPMethod: "GET", + HTTPPath: "/canary/{name}", + } + + if input == nil { + input = &GetCanaryInput{} + } + + output = &GetCanaryOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetCanary API operation for Synthetics. +// +// Retrieves complete information about one canary. You must specify the name +// of the canary that you want. To get a list of canaries and their names, use +// DescribeCanaries (https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Synthetics's +// API operation GetCanary for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ValidationException +// A parameter could not be validated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/GetCanary +func (c *Synthetics) GetCanary(input *GetCanaryInput) (*GetCanaryOutput, error) { + req, out := c.GetCanaryRequest(input) + return out, req.Send() +} + +// GetCanaryWithContext is the same as GetCanary with the addition of +// the ability to pass a context and additional request options. +// +// See GetCanary for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) GetCanaryWithContext(ctx aws.Context, input *GetCanaryInput, opts ...request.Option) (*GetCanaryOutput, error) { + req, out := c.GetCanaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetCanaryRuns = "GetCanaryRuns" + +// GetCanaryRunsRequest generates a "aws/request.Request" representing the +// client's request for the GetCanaryRuns operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetCanaryRuns for more information on using the GetCanaryRuns +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetCanaryRunsRequest method. +// req, resp := client.GetCanaryRunsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/GetCanaryRuns +func (c *Synthetics) GetCanaryRunsRequest(input *GetCanaryRunsInput) (req *request.Request, output *GetCanaryRunsOutput) { + op := &request.Operation{ + Name: opGetCanaryRuns, + HTTPMethod: "POST", + HTTPPath: "/canary/{name}/runs", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetCanaryRunsInput{} + } + + output = &GetCanaryRunsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetCanaryRuns API operation for Synthetics. +// +// Retrieves a list of runs for a specified canary. +// +// Returns awserr.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 Synthetics's +// API operation GetCanaryRuns for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ValidationException +// A parameter could not be validated. +// +// * ResourceNotFoundException +// One of the specified resources was not found. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/GetCanaryRuns +func (c *Synthetics) GetCanaryRuns(input *GetCanaryRunsInput) (*GetCanaryRunsOutput, error) { + req, out := c.GetCanaryRunsRequest(input) + return out, req.Send() +} + +// GetCanaryRunsWithContext is the same as GetCanaryRuns with the addition of +// the ability to pass a context and additional request options. +// +// See GetCanaryRuns for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) GetCanaryRunsWithContext(ctx aws.Context, input *GetCanaryRunsInput, opts ...request.Option) (*GetCanaryRunsOutput, error) { + req, out := c.GetCanaryRunsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetCanaryRunsPages iterates over the pages of a GetCanaryRuns operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetCanaryRuns 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 GetCanaryRuns operation. +// pageNum := 0 +// err := client.GetCanaryRunsPages(params, +// func(page *synthetics.GetCanaryRunsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Synthetics) GetCanaryRunsPages(input *GetCanaryRunsInput, fn func(*GetCanaryRunsOutput, bool) bool) error { + return c.GetCanaryRunsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetCanaryRunsPagesWithContext same as GetCanaryRunsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) GetCanaryRunsPagesWithContext(ctx aws.Context, input *GetCanaryRunsInput, fn func(*GetCanaryRunsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetCanaryRunsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetCanaryRunsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetCanaryRunsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opListTagsForResource = "ListTagsForResource" + +// ListTagsForResourceRequest generates a "aws/request.Request" representing the +// client's request for the ListTagsForResource operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListTagsForResource for more information on using the ListTagsForResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListTagsForResourceRequest method. +// req, resp := client.ListTagsForResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/ListTagsForResource +func (c *Synthetics) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { + op := &request.Operation{ + Name: opListTagsForResource, + HTTPMethod: "GET", + HTTPPath: "/tags/{resourceArn}", + } + + if input == nil { + input = &ListTagsForResourceInput{} + } + + output = &ListTagsForResourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListTagsForResource API operation for Synthetics. +// +// Displays the tags associated with a canary. +// +// Returns awserr.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 Synthetics's +// API operation ListTagsForResource for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ResourceNotFoundException +// One of the specified resources was not found. +// +// * ValidationException +// A parameter could not be validated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/ListTagsForResource +func (c *Synthetics) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + 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 *Synthetics) 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 opStartCanary = "StartCanary" + +// StartCanaryRequest generates a "aws/request.Request" representing the +// client's request for the StartCanary operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See StartCanary for more information on using the StartCanary +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the StartCanaryRequest method. +// req, resp := client.StartCanaryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/StartCanary +func (c *Synthetics) StartCanaryRequest(input *StartCanaryInput) (req *request.Request, output *StartCanaryOutput) { + op := &request.Operation{ + Name: opStartCanary, + HTTPMethod: "POST", + HTTPPath: "/canary/{name}/start", + } + + if input == nil { + input = &StartCanaryInput{} + } + + output = &StartCanaryOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// StartCanary API operation for Synthetics. +// +// Use this operation to run a canary that has already been created. The frequency +// of the canary runs is determined by the value of the canary's Schedule. To +// see a canary's schedule, use GetCanary (https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_GetCanary.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Synthetics's +// API operation StartCanary for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ValidationException +// A parameter could not be validated. +// +// * ResourceNotFoundException +// One of the specified resources was not found. +// +// * ConflictException +// A conflicting operation is already in progress. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/StartCanary +func (c *Synthetics) StartCanary(input *StartCanaryInput) (*StartCanaryOutput, error) { + req, out := c.StartCanaryRequest(input) + return out, req.Send() +} + +// StartCanaryWithContext is the same as StartCanary with the addition of +// the ability to pass a context and additional request options. +// +// See StartCanary for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) StartCanaryWithContext(ctx aws.Context, input *StartCanaryInput, opts ...request.Option) (*StartCanaryOutput, error) { + req, out := c.StartCanaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opStopCanary = "StopCanary" + +// StopCanaryRequest generates a "aws/request.Request" representing the +// client's request for the StopCanary operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See StopCanary for more information on using the StopCanary +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the StopCanaryRequest method. +// req, resp := client.StopCanaryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/StopCanary +func (c *Synthetics) StopCanaryRequest(input *StopCanaryInput) (req *request.Request, output *StopCanaryOutput) { + op := &request.Operation{ + Name: opStopCanary, + HTTPMethod: "POST", + HTTPPath: "/canary/{name}/stop", + } + + if input == nil { + input = &StopCanaryInput{} + } + + output = &StopCanaryOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// StopCanary API operation for Synthetics. +// +// Stops the canary to prevent all future runs. If the canary is currently running, +// Synthetics stops waiting for the current run of the specified canary to complete. +// The run that is in progress completes on its own, publishes metrics, and +// uploads artifacts, but it is not recorded in Synthetics as a completed run. +// +// You can use StartCanary to start it running again with the canary’s current +// schedule at any point in the future. +// +// Returns awserr.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 Synthetics's +// API operation StopCanary for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ValidationException +// A parameter could not be validated. +// +// * ResourceNotFoundException +// One of the specified resources was not found. +// +// * ConflictException +// A conflicting operation is already in progress. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/StopCanary +func (c *Synthetics) StopCanary(input *StopCanaryInput) (*StopCanaryOutput, error) { + req, out := c.StopCanaryRequest(input) + return out, req.Send() +} + +// StopCanaryWithContext is the same as StopCanary with the addition of +// the ability to pass a context and additional request options. +// +// See StopCanary for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) StopCanaryWithContext(ctx aws.Context, input *StopCanaryInput, opts ...request.Option) (*StopCanaryOutput, error) { + req, out := c.StopCanaryRequest(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 will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See TagResource for more information on using the TagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the TagResourceRequest method. +// req, resp := client.TagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/TagResource +func (c *Synthetics) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { + op := &request.Operation{ + Name: opTagResource, + HTTPMethod: "POST", + HTTPPath: "/tags/{resourceArn}", + } + + if input == nil { + input = &TagResourceInput{} + } + + output = &TagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// TagResource API operation for Synthetics. +// +// Assigns one or more tags (key-value pairs) to the specified canary. +// +// Tags can help you organize and categorize your resources. You can also use +// them to scope user permissions, by granting a user permission to access or +// change only resources with certain tag values. +// +// Tags don't have any semantic meaning to AWS and are interpreted strictly +// as strings of characters. +// +// You can use the TagResource action with a canary that already has tags. If +// you specify a new tag key for the alarm, this tag is appended to the list +// of tags associated with the alarm. If you specify a tag key that is already +// associated with the alarm, the new tag value that you specify replaces the +// previous value for that tag. +// +// You can associate as many as 50 tags with a canary. +// +// Returns awserr.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 Synthetics's +// API operation TagResource for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ResourceNotFoundException +// One of the specified resources was not found. +// +// * ValidationException +// A parameter could not be validated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/TagResource +func (c *Synthetics) 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 *Synthetics) 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 will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UntagResource for more information on using the UntagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UntagResourceRequest method. +// req, resp := client.UntagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/UntagResource +func (c *Synthetics) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { + op := &request.Operation{ + Name: opUntagResource, + HTTPMethod: "DELETE", + HTTPPath: "/tags/{resourceArn}", + } + + if input == nil { + input = &UntagResourceInput{} + } + + output = &UntagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UntagResource API operation for Synthetics. +// +// Removes one or more tags from the specified canary. +// +// Returns awserr.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 Synthetics's +// API operation UntagResource for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ResourceNotFoundException +// One of the specified resources was not found. +// +// * ValidationException +// A parameter could not be validated. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/UntagResource +func (c *Synthetics) 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 *Synthetics) 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 opUpdateCanary = "UpdateCanary" + +// UpdateCanaryRequest generates a "aws/request.Request" representing the +// client's request for the UpdateCanary operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateCanary for more information on using the UpdateCanary +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateCanaryRequest method. +// req, resp := client.UpdateCanaryRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/UpdateCanary +func (c *Synthetics) UpdateCanaryRequest(input *UpdateCanaryInput) (req *request.Request, output *UpdateCanaryOutput) { + op := &request.Operation{ + Name: opUpdateCanary, + HTTPMethod: "PATCH", + HTTPPath: "/canary/{name}", + } + + if input == nil { + input = &UpdateCanaryInput{} + } + + output = &UpdateCanaryOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UpdateCanary API operation for Synthetics. +// +// Use this operation to change the settings of a canary that has already been +// created. +// +// You can't use this operation to update the tags of an existing canary. To +// change the tags of an existing canary, use TagResource (https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_TagResource.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Synthetics's +// API operation UpdateCanary for usage and error information. +// +// Returned Error Types: +// * InternalServerException +// An unknown internal error occurred. +// +// * ValidationException +// A parameter could not be validated. +// +// * ResourceNotFoundException +// One of the specified resources was not found. +// +// * ConflictException +// A conflicting operation is already in progress. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/UpdateCanary +func (c *Synthetics) UpdateCanary(input *UpdateCanaryInput) (*UpdateCanaryOutput, error) { + req, out := c.UpdateCanaryRequest(input) + return out, req.Send() +} + +// UpdateCanaryWithContext is the same as UpdateCanary with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateCanary for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Synthetics) UpdateCanaryWithContext(ctx aws.Context, input *UpdateCanaryInput, opts ...request.Option) (*UpdateCanaryOutput, error) { + req, out := c.UpdateCanaryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// This structure contains all information about one canary in your account. +type Canary struct { + _ struct{} `type:"structure"` + + // The location in Amazon S3 where Synthetics stores artifacts from the runs + // of this canary. Artifacts include the log file, screenshots, and HAR files. + ArtifactS3Location *string `min:"1" type:"string"` + + // This structure contains information about the canary's Lambda handler and + // where its code is stored by CloudWatch Synthetics. + Code *CanaryCodeOutput `type:"structure"` + + // The ARN of the Lambda function that is used as your canary's engine. For + // more information about Lambda ARN format, see Resources and Conditions for + // Lambda Actions (https://docs.aws.amazon.com/lambda/latest/dg/lambda-api-permissions-ref.html). + EngineArn *string `type:"string"` + + // The ARN of the IAM role used to run the canary. This role must include lambda.amazonaws.com + // as a principal in the trust policy. + ExecutionRoleArn *string `type:"string"` + + // The number of days to retain data about failed runs of this canary. + FailureRetentionPeriodInDays *int64 `min:"1" type:"integer"` + + // The unique ID of this canary. + Id *string `type:"string"` + + // The name of the canary. + Name *string `min:"1" type:"string"` + + // A structure that contains information for a canary run. + RunConfig *CanaryRunConfigOutput `type:"structure"` + + // Specifies the runtime version to use for the canary. Currently, the only + // valid value is syn-1.0. For more information about runtime versions, see + // Canary Runtime Versions (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html). + RuntimeVersion *string `min:"1" type:"string"` + + // A structure that contains information about how often the canary is to run, + // and when these runs are to stop. + Schedule *CanaryScheduleOutput `type:"structure"` + + // A structure that contains information about the canary's status. + Status *CanaryStatus `type:"structure"` + + // The number of days to retain data about successful runs of this canary. + SuccessRetentionPeriodInDays *int64 `min:"1" type:"integer"` + + // The list of key-value pairs that are associated with the canary. + Tags map[string]*string `min:"1" type:"map"` + + // A structure that contains information about when the canary was created, + // modified, and most recently run. + Timeline *CanaryTimeline `type:"structure"` + + // If this canary is to test an endpoint in a VPC, this structure contains information + // about the subnets and security groups of the VPC endpoint. For more information, + // see Running a Canary in a VPC (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html). + VpcConfig *VpcConfigOutput `type:"structure"` +} + +// String returns the string representation +func (s Canary) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Canary) GoString() string { + return s.String() +} + +// SetArtifactS3Location sets the ArtifactS3Location field's value. +func (s *Canary) SetArtifactS3Location(v string) *Canary { + s.ArtifactS3Location = &v + return s +} + +// SetCode sets the Code field's value. +func (s *Canary) SetCode(v *CanaryCodeOutput) *Canary { + s.Code = v + return s +} + +// SetEngineArn sets the EngineArn field's value. +func (s *Canary) SetEngineArn(v string) *Canary { + s.EngineArn = &v + return s +} + +// SetExecutionRoleArn sets the ExecutionRoleArn field's value. +func (s *Canary) SetExecutionRoleArn(v string) *Canary { + s.ExecutionRoleArn = &v + return s +} + +// SetFailureRetentionPeriodInDays sets the FailureRetentionPeriodInDays field's value. +func (s *Canary) SetFailureRetentionPeriodInDays(v int64) *Canary { + s.FailureRetentionPeriodInDays = &v + return s +} + +// SetId sets the Id field's value. +func (s *Canary) SetId(v string) *Canary { + s.Id = &v + return s +} + +// SetName sets the Name field's value. +func (s *Canary) SetName(v string) *Canary { + s.Name = &v + return s +} + +// SetRunConfig sets the RunConfig field's value. +func (s *Canary) SetRunConfig(v *CanaryRunConfigOutput) *Canary { + s.RunConfig = v + return s +} + +// SetRuntimeVersion sets the RuntimeVersion field's value. +func (s *Canary) SetRuntimeVersion(v string) *Canary { + s.RuntimeVersion = &v + return s +} + +// SetSchedule sets the Schedule field's value. +func (s *Canary) SetSchedule(v *CanaryScheduleOutput) *Canary { + s.Schedule = v + return s +} + +// SetStatus sets the Status field's value. +func (s *Canary) SetStatus(v *CanaryStatus) *Canary { + s.Status = v + return s +} + +// SetSuccessRetentionPeriodInDays sets the SuccessRetentionPeriodInDays field's value. +func (s *Canary) SetSuccessRetentionPeriodInDays(v int64) *Canary { + s.SuccessRetentionPeriodInDays = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *Canary) SetTags(v map[string]*string) *Canary { + s.Tags = v + return s +} + +// SetTimeline sets the Timeline field's value. +func (s *Canary) SetTimeline(v *CanaryTimeline) *Canary { + s.Timeline = v + return s +} + +// SetVpcConfig sets the VpcConfig field's value. +func (s *Canary) SetVpcConfig(v *VpcConfigOutput) *Canary { + s.VpcConfig = v + return s +} + +// Use this structure to input your script code for the canary. This structure +// contains the Lambda handler with the location where the canary should start +// running the script. If the script is stored in an S3 bucket, the bucket name, +// key, and version are also included. If the script was passed into the canary +// directly, the script code is contained in the value of Zipfile. +type CanaryCodeInput struct { + _ struct{} `type:"structure"` + + // The entry point to use for the source code when running the canary. This + // value must end with the string .handler. + // + // Handler is a required field + Handler *string `min:"1" type:"string" required:"true"` + + // If your canary script is located in S3, specify the full bucket name here. + // The bucket must already exist. Specify the full bucket name, including s3:// + // as the start of the bucket name. + S3Bucket *string `min:"1" type:"string"` + + // The S3 key of your script. For more information, see Working with Amazon + // S3 Objects (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingObjects.html). + S3Key *string `min:"1" type:"string"` + + // The S3 version ID of your script. + S3Version *string `min:"1" type:"string"` + + // If you input your canary script directly into the canary instead of referring + // to an S3 location, the value of this parameter is the .zip file that contains + // the script. It can be up to 5 MB. + // + // ZipFile is automatically base64 encoded/decoded by the SDK. + ZipFile []byte `min:"1" type:"blob"` +} + +// String returns the string representation +func (s CanaryCodeInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryCodeInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CanaryCodeInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CanaryCodeInput"} + if s.Handler == nil { + invalidParams.Add(request.NewErrParamRequired("Handler")) + } + if s.Handler != nil && len(*s.Handler) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Handler", 1)) + } + if s.S3Bucket != nil && len(*s.S3Bucket) < 1 { + invalidParams.Add(request.NewErrParamMinLen("S3Bucket", 1)) + } + if s.S3Key != nil && len(*s.S3Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("S3Key", 1)) + } + if s.S3Version != nil && len(*s.S3Version) < 1 { + invalidParams.Add(request.NewErrParamMinLen("S3Version", 1)) + } + if s.ZipFile != nil && len(s.ZipFile) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ZipFile", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetHandler sets the Handler field's value. +func (s *CanaryCodeInput) SetHandler(v string) *CanaryCodeInput { + s.Handler = &v + return s +} + +// SetS3Bucket sets the S3Bucket field's value. +func (s *CanaryCodeInput) SetS3Bucket(v string) *CanaryCodeInput { + s.S3Bucket = &v + return s +} + +// SetS3Key sets the S3Key field's value. +func (s *CanaryCodeInput) SetS3Key(v string) *CanaryCodeInput { + s.S3Key = &v + return s +} + +// SetS3Version sets the S3Version field's value. +func (s *CanaryCodeInput) SetS3Version(v string) *CanaryCodeInput { + s.S3Version = &v + return s +} + +// SetZipFile sets the ZipFile field's value. +func (s *CanaryCodeInput) SetZipFile(v []byte) *CanaryCodeInput { + s.ZipFile = v + return s +} + +// This structure contains information about the canary's Lambda handler and +// where its code is stored by CloudWatch Synthetics. +type CanaryCodeOutput struct { + _ struct{} `type:"structure"` + + // The entry point to use for the source code when running the canary. + Handler *string `min:"1" type:"string"` + + // The ARN of the Lambda layer where Synthetics stores the canary script code. + SourceLocationArn *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s CanaryCodeOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryCodeOutput) GoString() string { + return s.String() +} + +// SetHandler sets the Handler field's value. +func (s *CanaryCodeOutput) SetHandler(v string) *CanaryCodeOutput { + s.Handler = &v + return s +} + +// SetSourceLocationArn sets the SourceLocationArn field's value. +func (s *CanaryCodeOutput) SetSourceLocationArn(v string) *CanaryCodeOutput { + s.SourceLocationArn = &v + return s +} + +// This structure contains information about the most recent run of a single +// canary. +type CanaryLastRun struct { + _ struct{} `type:"structure"` + + // The name of the canary. + CanaryName *string `min:"1" type:"string"` + + // The results from this canary's most recent run. + LastRun *CanaryRun `type:"structure"` +} + +// String returns the string representation +func (s CanaryLastRun) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryLastRun) GoString() string { + return s.String() +} + +// SetCanaryName sets the CanaryName field's value. +func (s *CanaryLastRun) SetCanaryName(v string) *CanaryLastRun { + s.CanaryName = &v + return s +} + +// SetLastRun sets the LastRun field's value. +func (s *CanaryLastRun) SetLastRun(v *CanaryRun) *CanaryLastRun { + s.LastRun = v + return s +} + +// This structure contains the details about one run of one canary. +type CanaryRun struct { + _ struct{} `type:"structure"` + + // The location where the canary stored artifacts from the run. Artifacts include + // the log file, screenshots, and HAR files. + ArtifactS3Location *string `min:"1" type:"string"` + + // The name of the canary. + Name *string `min:"1" type:"string"` + + // The status of this run. + Status *CanaryRunStatus `type:"structure"` + + // A structure that contains the start and end times of this run. + Timeline *CanaryRunTimeline `type:"structure"` +} + +// String returns the string representation +func (s CanaryRun) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryRun) GoString() string { + return s.String() +} + +// SetArtifactS3Location sets the ArtifactS3Location field's value. +func (s *CanaryRun) SetArtifactS3Location(v string) *CanaryRun { + s.ArtifactS3Location = &v + return s +} + +// SetName sets the Name field's value. +func (s *CanaryRun) SetName(v string) *CanaryRun { + s.Name = &v + return s +} + +// SetStatus sets the Status field's value. +func (s *CanaryRun) SetStatus(v *CanaryRunStatus) *CanaryRun { + s.Status = v + return s +} + +// SetTimeline sets the Timeline field's value. +func (s *CanaryRun) SetTimeline(v *CanaryRunTimeline) *CanaryRun { + s.Timeline = v + return s +} + +// A structure that contains input information for a canary run. +type CanaryRunConfigInput struct { + _ struct{} `type:"structure"` + + // The maximum amount of memory available to the canary while it is running, + // in MB. The value you specify must be a multiple of 64. + MemoryInMB *int64 `min:"960" type:"integer"` + + // How long the canary is allowed to run before it must stop. If you omit this + // field, the frequency of the canary is used as this value, up to a maximum + // of 14 minutes. + // + // TimeoutInSeconds is a required field + TimeoutInSeconds *int64 `min:"60" type:"integer" required:"true"` +} + +// String returns the string representation +func (s CanaryRunConfigInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryRunConfigInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CanaryRunConfigInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CanaryRunConfigInput"} + if s.MemoryInMB != nil && *s.MemoryInMB < 960 { + invalidParams.Add(request.NewErrParamMinValue("MemoryInMB", 960)) + } + if s.TimeoutInSeconds == nil { + invalidParams.Add(request.NewErrParamRequired("TimeoutInSeconds")) + } + if s.TimeoutInSeconds != nil && *s.TimeoutInSeconds < 60 { + invalidParams.Add(request.NewErrParamMinValue("TimeoutInSeconds", 60)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMemoryInMB sets the MemoryInMB field's value. +func (s *CanaryRunConfigInput) SetMemoryInMB(v int64) *CanaryRunConfigInput { + s.MemoryInMB = &v + return s +} + +// SetTimeoutInSeconds sets the TimeoutInSeconds field's value. +func (s *CanaryRunConfigInput) SetTimeoutInSeconds(v int64) *CanaryRunConfigInput { + s.TimeoutInSeconds = &v + return s +} + +// A structure that contains information for a canary run. +type CanaryRunConfigOutput struct { + _ struct{} `type:"structure"` + + // The maximum amount of memory available to the canary while it is running, + // in MB. The value you must be a multiple of 64. + MemoryInMB *int64 `min:"960" type:"integer"` + + // How long the canary is allowed to run before it must stop. + TimeoutInSeconds *int64 `min:"60" type:"integer"` +} + +// String returns the string representation +func (s CanaryRunConfigOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryRunConfigOutput) GoString() string { + return s.String() +} + +// SetMemoryInMB sets the MemoryInMB field's value. +func (s *CanaryRunConfigOutput) SetMemoryInMB(v int64) *CanaryRunConfigOutput { + s.MemoryInMB = &v + return s +} + +// SetTimeoutInSeconds sets the TimeoutInSeconds field's value. +func (s *CanaryRunConfigOutput) SetTimeoutInSeconds(v int64) *CanaryRunConfigOutput { + s.TimeoutInSeconds = &v + return s +} + +// This structure contains the status information about a canary run. +type CanaryRunStatus struct { + _ struct{} `type:"structure"` + + // The current state of the run. + State *string `type:"string" enum:"CanaryRunState"` + + // If run of the canary failed, this field contains the reason for the error. + StateReason *string `min:"1" type:"string"` + + // If this value is CANARY_FAILURE, an exception occurred in the canary code. + // If this value is EXECUTION_FAILURE, an exception occurred in CloudWatch Synthetics. + StateReasonCode *string `type:"string" enum:"CanaryRunStateReasonCode"` +} + +// String returns the string representation +func (s CanaryRunStatus) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryRunStatus) GoString() string { + return s.String() +} + +// SetState sets the State field's value. +func (s *CanaryRunStatus) SetState(v string) *CanaryRunStatus { + s.State = &v + return s +} + +// SetStateReason sets the StateReason field's value. +func (s *CanaryRunStatus) SetStateReason(v string) *CanaryRunStatus { + s.StateReason = &v + return s +} + +// SetStateReasonCode sets the StateReasonCode field's value. +func (s *CanaryRunStatus) SetStateReasonCode(v string) *CanaryRunStatus { + s.StateReasonCode = &v + return s +} + +// This structure contains the start and end times of a single canary run. +type CanaryRunTimeline struct { + _ struct{} `type:"structure"` + + // The end time of the run. + Completed *time.Time `type:"timestamp"` + + // The start time of the run. + Started *time.Time `type:"timestamp"` +} + +// String returns the string representation +func (s CanaryRunTimeline) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryRunTimeline) GoString() string { + return s.String() +} + +// SetCompleted sets the Completed field's value. +func (s *CanaryRunTimeline) SetCompleted(v time.Time) *CanaryRunTimeline { + s.Completed = &v + return s +} + +// SetStarted sets the Started field's value. +func (s *CanaryRunTimeline) SetStarted(v time.Time) *CanaryRunTimeline { + s.Started = &v + return s +} + +// This structure specifies how often a canary is to make runs and the date +// and time when it should stop making runs. +type CanaryScheduleInput struct { + _ struct{} `type:"structure"` + + // How long, in seconds, for the canary to continue making regular runs according + // to the schedule in the Expression value. If you specify 0, the canary continues + // making runs until you stop it. If you omit this field, the default of 0 is + // used. + DurationInSeconds *int64 `type:"long"` + + // A rate expression that defines how often the canary is to run. The syntax + // is rate(number unit). unit can be minute, minutes, or hour. + // + // For example, rate(1 minute) runs the canary once a minute, rate(10 minutes) + // runs it once every 10 minutes, and rate(1 hour) runs it once every hour. + // You can specify a frequency between rate(1 minute) and rate(1 hour). + // + // Specifying rate(0 minute) or rate(0 hour) is a special value that causes + // the canary to run only once when it is started. + // + // Expression is a required field + Expression *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s CanaryScheduleInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryScheduleInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CanaryScheduleInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CanaryScheduleInput"} + if s.Expression == nil { + invalidParams.Add(request.NewErrParamRequired("Expression")) + } + if s.Expression != nil && len(*s.Expression) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Expression", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDurationInSeconds sets the DurationInSeconds field's value. +func (s *CanaryScheduleInput) SetDurationInSeconds(v int64) *CanaryScheduleInput { + s.DurationInSeconds = &v + return s +} + +// SetExpression sets the Expression field's value. +func (s *CanaryScheduleInput) SetExpression(v string) *CanaryScheduleInput { + s.Expression = &v + return s +} + +// How long, in seconds, for the canary to continue making regular runs according +// to the schedule in the Expression value. +type CanaryScheduleOutput struct { + _ struct{} `type:"structure"` + + // How long, in seconds, for the canary to continue making regular runs after + // it was created. The runs are performed according to the schedule in the Expression + // value. + DurationInSeconds *int64 `type:"long"` + + // A rate expression that defines how often the canary is to run. The syntax + // is rate(number unit). unit can be minute, minutes, or hour. + // + // For example, rate(1 minute) runs the canary once a minute, rate(10 minutes) + // runs it once every 10 minutes, and rate(1 hour) runs it once every hour. + // + // Specifying rate(0 minute) or rate(0 hour) is a special value that causes + // the canary to run only once when it is started. + Expression *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s CanaryScheduleOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryScheduleOutput) GoString() string { + return s.String() +} + +// SetDurationInSeconds sets the DurationInSeconds field's value. +func (s *CanaryScheduleOutput) SetDurationInSeconds(v int64) *CanaryScheduleOutput { + s.DurationInSeconds = &v + return s +} + +// SetExpression sets the Expression field's value. +func (s *CanaryScheduleOutput) SetExpression(v string) *CanaryScheduleOutput { + s.Expression = &v + return s +} + +// A structure that contains the current state of the canary. +type CanaryStatus struct { + _ struct{} `type:"structure"` + + // The current state of the canary. + State *string `type:"string" enum:"CanaryState"` + + // If the canary has insufficient permissions to run, this field provides more + // details. + StateReason *string `min:"1" type:"string"` + + // If the canary cannot run or has failed, this field displays the reason. + StateReasonCode *string `type:"string" enum:"CanaryStateReasonCode"` +} + +// String returns the string representation +func (s CanaryStatus) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryStatus) GoString() string { + return s.String() +} + +// SetState sets the State field's value. +func (s *CanaryStatus) SetState(v string) *CanaryStatus { + s.State = &v + return s +} + +// SetStateReason sets the StateReason field's value. +func (s *CanaryStatus) SetStateReason(v string) *CanaryStatus { + s.StateReason = &v + return s +} + +// SetStateReasonCode sets the StateReasonCode field's value. +func (s *CanaryStatus) SetStateReasonCode(v string) *CanaryStatus { + s.StateReasonCode = &v + return s +} + +// This structure contains information about when the canary was created and +// modified. +type CanaryTimeline struct { + _ struct{} `type:"structure"` + + // The date and time the canary was created. + Created *time.Time `type:"timestamp"` + + // The date and time the canary was most recently modified. + LastModified *time.Time `type:"timestamp"` + + // The date and time that the canary's most recent run started. + LastStarted *time.Time `type:"timestamp"` + + // The date and time that the canary's most recent run ended. + LastStopped *time.Time `type:"timestamp"` +} + +// String returns the string representation +func (s CanaryTimeline) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CanaryTimeline) GoString() string { + return s.String() +} + +// SetCreated sets the Created field's value. +func (s *CanaryTimeline) SetCreated(v time.Time) *CanaryTimeline { + s.Created = &v + return s +} + +// SetLastModified sets the LastModified field's value. +func (s *CanaryTimeline) SetLastModified(v time.Time) *CanaryTimeline { + s.LastModified = &v + return s +} + +// SetLastStarted sets the LastStarted field's value. +func (s *CanaryTimeline) SetLastStarted(v time.Time) *CanaryTimeline { + s.LastStarted = &v + return s +} + +// SetLastStopped sets the LastStopped field's value. +func (s *CanaryTimeline) SetLastStopped(v time.Time) *CanaryTimeline { + s.LastStopped = &v + return s +} + +// A conflicting operation is already in progress. +type ConflictException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s ConflictException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ConflictException) GoString() string { + return s.String() +} + +func newErrorConflictException(v protocol.ResponseMetadata) error { + return &ConflictException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ConflictException) Code() string { + return "ConflictException" +} + +// Message returns the exception's message. +func (s *ConflictException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ConflictException) OrigErr() error { + return nil +} + +func (s *ConflictException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ConflictException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ConflictException) RequestID() string { + return s.RespMetadata.RequestID +} + +type CreateCanaryInput struct { + _ struct{} `type:"structure"` + + // The location in Amazon S3 where Synthetics stores artifacts from the test + // runs of this canary. Artifacts include the log file, screenshots, and HAR + // files. + // + // ArtifactS3Location is a required field + ArtifactS3Location *string `min:"1" type:"string" required:"true"` + + // A structure that includes the entry point from which the canary should start + // running your script. If the script is stored in an S3 bucket, the bucket + // name, key, and version are also included. + // + // Code is a required field + Code *CanaryCodeInput `type:"structure" required:"true"` + + // The ARN of the IAM role to be used to run the canary. This role must already + // exist, and must include lambda.amazonaws.com as a principal in the trust + // policy. The role must also have the following permissions: + // + // * s3:PutObject + // + // * s3:GetBucketLocation + // + // * s3:ListAllMyBuckets + // + // * cloudwatch:PutMetricData + // + // * logs:CreateLogGroup + // + // * logs:CreateLogStream + // + // * logs:CreateLogStream + // + // ExecutionRoleArn is a required field + ExecutionRoleArn *string `type:"string" required:"true"` + + // The number of days to retain data about failed runs of this canary. If you + // omit this field, the default of 31 days is used. The valid range is 1 to + // 455 days. + FailureRetentionPeriodInDays *int64 `min:"1" type:"integer"` + + // The name for this canary. Be sure to give it a descriptive name that distinguishes + // it from other canaries in your account. + // + // Do not include secrets or proprietary information in your canary names. The + // canary name makes up part of the canary ARN, and the ARN is included in outbound + // calls over the internet. For more information, see Security Considerations + // for Synthetics Canaries (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html). + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // A structure that contains the configuration for individual canary runs, such + // as timeout value. + RunConfig *CanaryRunConfigInput `type:"structure"` + + // Specifies the runtime version to use for the canary. Currently, the only + // valid value is syn-1.0. For more information about runtime versions, see + // Canary Runtime Versions (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html). + // + // RuntimeVersion is a required field + RuntimeVersion *string `min:"1" type:"string" required:"true"` + + // A structure that contains information about how often the canary is to run + // and when these test runs are to stop. + // + // Schedule is a required field + Schedule *CanaryScheduleInput `type:"structure" required:"true"` + + // The number of days to retain data about successful runs of this canary. If + // you omit this field, the default of 31 days is used. The valid range is 1 + // to 455 days. + SuccessRetentionPeriodInDays *int64 `min:"1" type:"integer"` + + // A list of key-value pairs to associate with the canary. You can associate + // as many as 50 tags with a canary. + // + // Tags can help you organize and categorize your resources. You can also use + // them to scope user permissions, by granting a user permission to access or + // change only the resources that have certain tag values. + Tags map[string]*string `min:"1" type:"map"` + + // If this canary is to test an endpoint in a VPC, this structure contains information + // about the subnet and security groups of the VPC endpoint. For more information, + // see Running a Canary in a VPC (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html). + VpcConfig *VpcConfigInput `type:"structure"` +} + +// String returns the string representation +func (s CreateCanaryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateCanaryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateCanaryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateCanaryInput"} + if s.ArtifactS3Location == nil { + invalidParams.Add(request.NewErrParamRequired("ArtifactS3Location")) + } + if s.ArtifactS3Location != nil && len(*s.ArtifactS3Location) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ArtifactS3Location", 1)) + } + if s.Code == nil { + invalidParams.Add(request.NewErrParamRequired("Code")) + } + if s.ExecutionRoleArn == nil { + invalidParams.Add(request.NewErrParamRequired("ExecutionRoleArn")) + } + if s.FailureRetentionPeriodInDays != nil && *s.FailureRetentionPeriodInDays < 1 { + invalidParams.Add(request.NewErrParamMinValue("FailureRetentionPeriodInDays", 1)) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.RuntimeVersion == nil { + invalidParams.Add(request.NewErrParamRequired("RuntimeVersion")) + } + if s.RuntimeVersion != nil && len(*s.RuntimeVersion) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RuntimeVersion", 1)) + } + if s.Schedule == nil { + invalidParams.Add(request.NewErrParamRequired("Schedule")) + } + if s.SuccessRetentionPeriodInDays != nil && *s.SuccessRetentionPeriodInDays < 1 { + invalidParams.Add(request.NewErrParamMinValue("SuccessRetentionPeriodInDays", 1)) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + } + if s.Code != nil { + if err := s.Code.Validate(); err != nil { + invalidParams.AddNested("Code", err.(request.ErrInvalidParams)) + } + } + if s.RunConfig != nil { + if err := s.RunConfig.Validate(); err != nil { + invalidParams.AddNested("RunConfig", err.(request.ErrInvalidParams)) + } + } + if s.Schedule != nil { + if err := s.Schedule.Validate(); err != nil { + invalidParams.AddNested("Schedule", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetArtifactS3Location sets the ArtifactS3Location field's value. +func (s *CreateCanaryInput) SetArtifactS3Location(v string) *CreateCanaryInput { + s.ArtifactS3Location = &v + return s +} + +// SetCode sets the Code field's value. +func (s *CreateCanaryInput) SetCode(v *CanaryCodeInput) *CreateCanaryInput { + s.Code = v + return s +} + +// SetExecutionRoleArn sets the ExecutionRoleArn field's value. +func (s *CreateCanaryInput) SetExecutionRoleArn(v string) *CreateCanaryInput { + s.ExecutionRoleArn = &v + return s +} + +// SetFailureRetentionPeriodInDays sets the FailureRetentionPeriodInDays field's value. +func (s *CreateCanaryInput) SetFailureRetentionPeriodInDays(v int64) *CreateCanaryInput { + s.FailureRetentionPeriodInDays = &v + return s +} + +// SetName sets the Name field's value. +func (s *CreateCanaryInput) SetName(v string) *CreateCanaryInput { + s.Name = &v + return s +} + +// SetRunConfig sets the RunConfig field's value. +func (s *CreateCanaryInput) SetRunConfig(v *CanaryRunConfigInput) *CreateCanaryInput { + s.RunConfig = v + return s +} + +// SetRuntimeVersion sets the RuntimeVersion field's value. +func (s *CreateCanaryInput) SetRuntimeVersion(v string) *CreateCanaryInput { + s.RuntimeVersion = &v + return s +} + +// SetSchedule sets the Schedule field's value. +func (s *CreateCanaryInput) SetSchedule(v *CanaryScheduleInput) *CreateCanaryInput { + s.Schedule = v + return s +} + +// SetSuccessRetentionPeriodInDays sets the SuccessRetentionPeriodInDays field's value. +func (s *CreateCanaryInput) SetSuccessRetentionPeriodInDays(v int64) *CreateCanaryInput { + s.SuccessRetentionPeriodInDays = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CreateCanaryInput) SetTags(v map[string]*string) *CreateCanaryInput { + s.Tags = v + return s +} + +// SetVpcConfig sets the VpcConfig field's value. +func (s *CreateCanaryInput) SetVpcConfig(v *VpcConfigInput) *CreateCanaryInput { + s.VpcConfig = v + return s +} + +type CreateCanaryOutput struct { + _ struct{} `type:"structure"` + + // The full details about the canary you have created. + Canary *Canary `type:"structure"` +} + +// String returns the string representation +func (s CreateCanaryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateCanaryOutput) GoString() string { + return s.String() +} + +// SetCanary sets the Canary field's value. +func (s *CreateCanaryOutput) SetCanary(v *Canary) *CreateCanaryOutput { + s.Canary = v + return s +} + +type DeleteCanaryInput struct { + _ struct{} `type:"structure"` + + // The name of the canary that you want to delete. To find the names of your + // canaries, use DescribeCanaries (https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html). + // + // Name is a required field + Name *string `location:"uri" locationName:"name" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteCanaryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCanaryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteCanaryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteCanaryInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *DeleteCanaryInput) SetName(v string) *DeleteCanaryInput { + s.Name = &v + return s +} + +type DeleteCanaryOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteCanaryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCanaryOutput) GoString() string { + return s.String() +} + +type DescribeCanariesInput struct { + _ struct{} `type:"structure"` + + // Specify this parameter to limit how many canaries are returned each time + // you use the DescribeCanaries operation. If you omit this parameter, the default + // of 100 is used. + MaxResults *int64 `min:"1" type:"integer"` + + // A token that indicates that there is more data available. You can use this + // token in a subsequent operation to retrieve the next set of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeCanariesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCanariesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeCanariesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeCanariesInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeCanariesInput) SetMaxResults(v int64) *DescribeCanariesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeCanariesInput) SetNextToken(v string) *DescribeCanariesInput { + s.NextToken = &v + return s +} + +type DescribeCanariesLastRunInput struct { + _ struct{} `type:"structure"` + + // Specify this parameter to limit how many runs are returned each time you + // use the DescribeLastRun operation. If you omit this parameter, the default + // of 100 is used. + MaxResults *int64 `min:"1" type:"integer"` + + // A token that indicates that there is more data available. You can use this + // token in a subsequent DescribeCanaries operation to retrieve the next set + // of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeCanariesLastRunInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCanariesLastRunInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeCanariesLastRunInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeCanariesLastRunInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeCanariesLastRunInput) SetMaxResults(v int64) *DescribeCanariesLastRunInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeCanariesLastRunInput) SetNextToken(v string) *DescribeCanariesLastRunInput { + s.NextToken = &v + return s +} + +type DescribeCanariesLastRunOutput struct { + _ struct{} `type:"structure"` + + // An array that contains the information from the most recent run of each canary. + CanariesLastRun []*CanaryLastRun `type:"list"` + + // A token that indicates that there is more data available. You can use this + // token in a subsequent DescribeCanariesLastRun operation to retrieve the next + // set of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeCanariesLastRunOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCanariesLastRunOutput) GoString() string { + return s.String() +} + +// SetCanariesLastRun sets the CanariesLastRun field's value. +func (s *DescribeCanariesLastRunOutput) SetCanariesLastRun(v []*CanaryLastRun) *DescribeCanariesLastRunOutput { + s.CanariesLastRun = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeCanariesLastRunOutput) SetNextToken(v string) *DescribeCanariesLastRunOutput { + s.NextToken = &v + return s +} + +type DescribeCanariesOutput struct { + _ struct{} `type:"structure"` + + // Returns an array. Each item in the array contains the full information about + // one canary. + Canaries []*Canary `type:"list"` + + // A token that indicates that there is more data available. You can use this + // token in a subsequent DescribeCanaries operation to retrieve the next set + // of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeCanariesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCanariesOutput) GoString() string { + return s.String() +} + +// SetCanaries sets the Canaries field's value. +func (s *DescribeCanariesOutput) SetCanaries(v []*Canary) *DescribeCanariesOutput { + s.Canaries = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeCanariesOutput) SetNextToken(v string) *DescribeCanariesOutput { + s.NextToken = &v + return s +} + +type DescribeRuntimeVersionsInput struct { + _ struct{} `type:"structure"` + + // Specify this parameter to limit how many runs are returned each time you + // use the DescribeRuntimeVersions operation. If you omit this parameter, the + // default of 100 is used. + MaxResults *int64 `min:"1" type:"integer"` + + // A token that indicates that there is more data available. You can use this + // token in a subsequent DescribeRuntimeVersions operation to retrieve the next + // set of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeRuntimeVersionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeRuntimeVersionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeRuntimeVersionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeRuntimeVersionsInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeRuntimeVersionsInput) SetMaxResults(v int64) *DescribeRuntimeVersionsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeRuntimeVersionsInput) SetNextToken(v string) *DescribeRuntimeVersionsInput { + s.NextToken = &v + return s +} + +type DescribeRuntimeVersionsOutput struct { + _ struct{} `type:"structure"` + + // A token that indicates that there is more data available. You can use this + // token in a subsequent DescribeRuntimeVersions operation to retrieve the next + // set of results. + NextToken *string `type:"string"` + + // An array of objects that display the details about each Synthetics canary + // runtime version. + RuntimeVersions []*RuntimeVersion `type:"list"` +} + +// String returns the string representation +func (s DescribeRuntimeVersionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeRuntimeVersionsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeRuntimeVersionsOutput) SetNextToken(v string) *DescribeRuntimeVersionsOutput { + s.NextToken = &v + return s +} + +// SetRuntimeVersions sets the RuntimeVersions field's value. +func (s *DescribeRuntimeVersionsOutput) SetRuntimeVersions(v []*RuntimeVersion) *DescribeRuntimeVersionsOutput { + s.RuntimeVersions = v + return s +} + +type GetCanaryInput struct { + _ struct{} `type:"structure"` + + // The name of the canary that you want details for. + // + // Name is a required field + Name *string `location:"uri" locationName:"name" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s GetCanaryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCanaryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetCanaryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetCanaryInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *GetCanaryInput) SetName(v string) *GetCanaryInput { + s.Name = &v + return s +} + +type GetCanaryOutput struct { + _ struct{} `type:"structure"` + + // A strucure that contains the full information about the canary. + Canary *Canary `type:"structure"` +} + +// String returns the string representation +func (s GetCanaryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCanaryOutput) GoString() string { + return s.String() +} + +// SetCanary sets the Canary field's value. +func (s *GetCanaryOutput) SetCanary(v *Canary) *GetCanaryOutput { + s.Canary = v + return s +} + +type GetCanaryRunsInput struct { + _ struct{} `type:"structure"` + + // Specify this parameter to limit how many runs are returned each time you + // use the GetCanaryRuns operation. If you omit this parameter, the default + // of 100 is used. + MaxResults *int64 `min:"1" type:"integer"` + + // The name of the canary that you want to see runs for. + // + // Name is a required field + Name *string `location:"uri" locationName:"name" min:"1" type:"string" required:"true"` + + // A token that indicates that there is more data available. You can use this + // token in a subsequent GetCanaryRuns operation to retrieve the next set of + // results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s GetCanaryRunsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCanaryRunsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetCanaryRunsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetCanaryRunsInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetCanaryRunsInput) SetMaxResults(v int64) *GetCanaryRunsInput { + s.MaxResults = &v + return s +} + +// SetName sets the Name field's value. +func (s *GetCanaryRunsInput) SetName(v string) *GetCanaryRunsInput { + s.Name = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetCanaryRunsInput) SetNextToken(v string) *GetCanaryRunsInput { + s.NextToken = &v + return s +} + +type GetCanaryRunsOutput struct { + _ struct{} `type:"structure"` + + // An array of structures. Each structure contains the details of one of the + // retrieved canary runs. + CanaryRuns []*CanaryRun `type:"list"` + + // A token that indicates that there is more data available. You can use this + // token in a subsequent GetCanaryRuns operation to retrieve the next set of + // results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s GetCanaryRunsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetCanaryRunsOutput) GoString() string { + return s.String() +} + +// SetCanaryRuns sets the CanaryRuns field's value. +func (s *GetCanaryRunsOutput) SetCanaryRuns(v []*CanaryRun) *GetCanaryRunsOutput { + s.CanaryRuns = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetCanaryRunsOutput) SetNextToken(v string) *GetCanaryRunsOutput { + s.NextToken = &v + return s +} + +// An unknown internal error occurred. +type InternalServerException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s InternalServerException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s InternalServerException) GoString() string { + return s.String() +} + +func newErrorInternalServerException(v protocol.ResponseMetadata) error { + return &InternalServerException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *InternalServerException) Code() string { + return "InternalServerException" +} + +// Message returns the exception's message. +func (s *InternalServerException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *InternalServerException) OrigErr() error { + return nil +} + +func (s *InternalServerException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *InternalServerException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *InternalServerException) RequestID() string { + return s.RespMetadata.RequestID +} + +type ListTagsForResourceInput struct { + _ struct{} `type:"structure"` + + // The ARN of the canary that you want to view tags for. + // + // The ARN format of a canary is arn:aws:synthetics:Region:account-id:canary:canary-name . + // + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"resourceArn" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListTagsForResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsForResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTagsForResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} + 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 *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResourceInput { + s.ResourceArn = &v + return s +} + +type ListTagsForResourceOutput struct { + _ struct{} `type:"structure"` + + // The list of tag keys and values associated with the canary that you specified. + Tags map[string]*string `min:"1" type:"map"` +} + +// String returns the string representation +func (s ListTagsForResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsForResourceOutput) GoString() string { + return s.String() +} + +// SetTags sets the Tags field's value. +func (s *ListTagsForResourceOutput) SetTags(v map[string]*string) *ListTagsForResourceOutput { + s.Tags = v + return s +} + +// One of the specified resources was not found. +type ResourceNotFoundException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s ResourceNotFoundException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ResourceNotFoundException) GoString() string { + return s.String() +} + +func newErrorResourceNotFoundException(v protocol.ResponseMetadata) error { + return &ResourceNotFoundException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ResourceNotFoundException) Code() string { + return "ResourceNotFoundException" +} + +// Message returns the exception's message. +func (s *ResourceNotFoundException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ResourceNotFoundException) OrigErr() error { + return nil +} + +func (s *ResourceNotFoundException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ResourceNotFoundException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ResourceNotFoundException) RequestID() string { + return s.RespMetadata.RequestID +} + +// This structure contains information about one canary runtime version. For +// more information about runtime versions, see Canary Runtime Versions (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html). +type RuntimeVersion struct { + _ struct{} `type:"structure"` + + // If this runtime version is deprecated, this value is the date of deprecation. + DeprecationDate *time.Time `type:"timestamp"` + + // A description of the runtime version, created by Amazon. + Description *string `min:"1" type:"string"` + + // The date that the runtime version was released. + ReleaseDate *time.Time `type:"timestamp"` + + // The name of the runtime version. Currently, the only valid value is syn-1.0. + // + // Specifies the runtime version to use for the canary. Currently, the only + // valid value is syn-1.0. + VersionName *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s RuntimeVersion) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RuntimeVersion) GoString() string { + return s.String() +} + +// SetDeprecationDate sets the DeprecationDate field's value. +func (s *RuntimeVersion) SetDeprecationDate(v time.Time) *RuntimeVersion { + s.DeprecationDate = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *RuntimeVersion) SetDescription(v string) *RuntimeVersion { + s.Description = &v + return s +} + +// SetReleaseDate sets the ReleaseDate field's value. +func (s *RuntimeVersion) SetReleaseDate(v time.Time) *RuntimeVersion { + s.ReleaseDate = &v + return s +} + +// SetVersionName sets the VersionName field's value. +func (s *RuntimeVersion) SetVersionName(v string) *RuntimeVersion { + s.VersionName = &v + return s +} + +type StartCanaryInput struct { + _ struct{} `type:"structure"` + + // The name of the canary that you want to run. To find canary names, use DescribeCanaries + // (https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html). + // + // Name is a required field + Name *string `location:"uri" locationName:"name" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s StartCanaryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StartCanaryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StartCanaryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StartCanaryInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *StartCanaryInput) SetName(v string) *StartCanaryInput { + s.Name = &v + return s +} + +type StartCanaryOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s StartCanaryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StartCanaryOutput) GoString() string { + return s.String() +} + +type StopCanaryInput struct { + _ struct{} `type:"structure"` + + // The name of the canary that you want to stop. To find the names of your canaries, + // use DescribeCanaries (https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html). + // + // Name is a required field + Name *string `location:"uri" locationName:"name" min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s StopCanaryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopCanaryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *StopCanaryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "StopCanaryInput"} + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetName sets the Name field's value. +func (s *StopCanaryInput) SetName(v string) *StopCanaryInput { + s.Name = &v + return s +} + +type StopCanaryOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s StopCanaryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s StopCanaryOutput) GoString() string { + return s.String() +} + +type TagResourceInput struct { + _ struct{} `type:"structure"` + + // The ARN of the canary that you're adding tags to. + // + // The ARN format of a canary is arn:aws:synthetics:Region:account-id:canary:canary-name . + // + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"resourceArn" type:"string" required:"true"` + + // The list of key-value pairs to associate with the canary. + // + // Tags is a required field + Tags map[string]*string `min:"1" 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.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *TagResourceInput) SetTags(v 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() +} + +type UntagResourceInput struct { + _ struct{} `type:"structure"` + + // The ARN of the canary that you're removing tags from. + // + // The ARN format of a canary is arn:aws:synthetics:Region:account-id:canary:canary-name . + // + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"resourceArn" type:"string" required:"true"` + + // The list of tag keys to remove from the resource. + // + // TagKeys is a required field + TagKeys []*string `location:"querystring" locationName:"tagKeys" min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s UntagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UntagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + if s.TagKeys != nil && len(s.TagKeys) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TagKeys", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTagKeys sets the TagKeys field's value. +func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { + s.TagKeys = v + return s +} + +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 UpdateCanaryInput struct { + _ struct{} `type:"structure"` + + // A structure that includes the entry point from which the canary should start + // running your script. If the script is stored in an S3 bucket, the bucket + // name, key, and version are also included. + Code *CanaryCodeInput `type:"structure"` + + // The ARN of the IAM role to be used to run the canary. This role must already + // exist, and must include lambda.amazonaws.com as a principal in the trust + // policy. The role must also have the following permissions: + // + // * s3:PutObject + // + // * s3:GetBucketLocation + // + // * s3:ListAllMyBuckets + // + // * cloudwatch:PutMetricData + // + // * logs:CreateLogGroup + // + // * logs:CreateLogStream + // + // * logs:CreateLogStream + ExecutionRoleArn *string `type:"string"` + + // The number of days to retain data about failed runs of this canary. + FailureRetentionPeriodInDays *int64 `min:"1" type:"integer"` + + // The name of the canary that you want to update. To find the names of your + // canaries, use DescribeCanaries (https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html). + // + // You cannot change the name of a canary that has already been created. + // + // Name is a required field + Name *string `location:"uri" locationName:"name" min:"1" type:"string" required:"true"` + + // A structure that contains the timeout value that is used for each individual + // run of the canary. + RunConfig *CanaryRunConfigInput `type:"structure"` + + // Specifies the runtime version to use for the canary. Currently, the only + // valid value is syn-1.0. For more information about runtime versions, see + // Canary Runtime Versions (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html). + RuntimeVersion *string `min:"1" type:"string"` + + // A structure that contains information about how often the canary is to run, + // and when these runs are to stop. + Schedule *CanaryScheduleInput `type:"structure"` + + // The number of days to retain data about successful runs of this canary. + SuccessRetentionPeriodInDays *int64 `min:"1" type:"integer"` + + // If this canary is to test an endpoint in a VPC, this structure contains information + // about the subnet and security groups of the VPC endpoint. For more information, + // see Running a Canary in a VPC (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html). + VpcConfig *VpcConfigInput `type:"structure"` +} + +// String returns the string representation +func (s UpdateCanaryInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateCanaryInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateCanaryInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateCanaryInput"} + if s.FailureRetentionPeriodInDays != nil && *s.FailureRetentionPeriodInDays < 1 { + invalidParams.Add(request.NewErrParamMinValue("FailureRetentionPeriodInDays", 1)) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.RuntimeVersion != nil && len(*s.RuntimeVersion) < 1 { + invalidParams.Add(request.NewErrParamMinLen("RuntimeVersion", 1)) + } + if s.SuccessRetentionPeriodInDays != nil && *s.SuccessRetentionPeriodInDays < 1 { + invalidParams.Add(request.NewErrParamMinValue("SuccessRetentionPeriodInDays", 1)) + } + if s.Code != nil { + if err := s.Code.Validate(); err != nil { + invalidParams.AddNested("Code", err.(request.ErrInvalidParams)) + } + } + if s.RunConfig != nil { + if err := s.RunConfig.Validate(); err != nil { + invalidParams.AddNested("RunConfig", err.(request.ErrInvalidParams)) + } + } + if s.Schedule != nil { + if err := s.Schedule.Validate(); err != nil { + invalidParams.AddNested("Schedule", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCode sets the Code field's value. +func (s *UpdateCanaryInput) SetCode(v *CanaryCodeInput) *UpdateCanaryInput { + s.Code = v + return s +} + +// SetExecutionRoleArn sets the ExecutionRoleArn field's value. +func (s *UpdateCanaryInput) SetExecutionRoleArn(v string) *UpdateCanaryInput { + s.ExecutionRoleArn = &v + return s +} + +// SetFailureRetentionPeriodInDays sets the FailureRetentionPeriodInDays field's value. +func (s *UpdateCanaryInput) SetFailureRetentionPeriodInDays(v int64) *UpdateCanaryInput { + s.FailureRetentionPeriodInDays = &v + return s +} + +// SetName sets the Name field's value. +func (s *UpdateCanaryInput) SetName(v string) *UpdateCanaryInput { + s.Name = &v + return s +} + +// SetRunConfig sets the RunConfig field's value. +func (s *UpdateCanaryInput) SetRunConfig(v *CanaryRunConfigInput) *UpdateCanaryInput { + s.RunConfig = v + return s +} + +// SetRuntimeVersion sets the RuntimeVersion field's value. +func (s *UpdateCanaryInput) SetRuntimeVersion(v string) *UpdateCanaryInput { + s.RuntimeVersion = &v + return s +} + +// SetSchedule sets the Schedule field's value. +func (s *UpdateCanaryInput) SetSchedule(v *CanaryScheduleInput) *UpdateCanaryInput { + s.Schedule = v + return s +} + +// SetSuccessRetentionPeriodInDays sets the SuccessRetentionPeriodInDays field's value. +func (s *UpdateCanaryInput) SetSuccessRetentionPeriodInDays(v int64) *UpdateCanaryInput { + s.SuccessRetentionPeriodInDays = &v + return s +} + +// SetVpcConfig sets the VpcConfig field's value. +func (s *UpdateCanaryInput) SetVpcConfig(v *VpcConfigInput) *UpdateCanaryInput { + s.VpcConfig = v + return s +} + +type UpdateCanaryOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UpdateCanaryOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateCanaryOutput) GoString() string { + return s.String() +} + +// A parameter could not be validated. +type ValidationException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s ValidationException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationException) GoString() string { + return s.String() +} + +func newErrorValidationException(v protocol.ResponseMetadata) error { + return &ValidationException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ValidationException) Code() string { + return "ValidationException" +} + +// Message returns the exception's message. +func (s *ValidationException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ValidationException) OrigErr() error { + return nil +} + +func (s *ValidationException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ValidationException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ValidationException) RequestID() string { + return s.RespMetadata.RequestID +} + +// If this canary is to test an endpoint in a VPC, this structure contains information +// about the subnets and security groups of the VPC endpoint. For more information, +// see Running a Canary in a VPC (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html). +type VpcConfigInput struct { + _ struct{} `type:"structure"` + + // The IDs of the security groups for this canary. + SecurityGroupIds []*string `type:"list"` + + // The IDs of the subnets where this canary is to run. + SubnetIds []*string `type:"list"` +} + +// String returns the string representation +func (s VpcConfigInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s VpcConfigInput) GoString() string { + return s.String() +} + +// SetSecurityGroupIds sets the SecurityGroupIds field's value. +func (s *VpcConfigInput) SetSecurityGroupIds(v []*string) *VpcConfigInput { + s.SecurityGroupIds = v + return s +} + +// SetSubnetIds sets the SubnetIds field's value. +func (s *VpcConfigInput) SetSubnetIds(v []*string) *VpcConfigInput { + s.SubnetIds = v + return s +} + +// If this canary is to test an endpoint in a VPC, this structure contains information +// about the subnets and security groups of the VPC endpoint. For more information, +// see Running a Canary in a VPC (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html). +type VpcConfigOutput struct { + _ struct{} `type:"structure"` + + // The IDs of the security groups for this canary. + SecurityGroupIds []*string `type:"list"` + + // The IDs of the subnets where this canary is to run. + SubnetIds []*string `type:"list"` + + // The IDs of the VPC where this canary is to run. + VpcId *string `type:"string"` +} + +// String returns the string representation +func (s VpcConfigOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s VpcConfigOutput) GoString() string { + return s.String() +} + +// SetSecurityGroupIds sets the SecurityGroupIds field's value. +func (s *VpcConfigOutput) SetSecurityGroupIds(v []*string) *VpcConfigOutput { + s.SecurityGroupIds = v + return s +} + +// SetSubnetIds sets the SubnetIds field's value. +func (s *VpcConfigOutput) SetSubnetIds(v []*string) *VpcConfigOutput { + s.SubnetIds = v + return s +} + +// SetVpcId sets the VpcId field's value. +func (s *VpcConfigOutput) SetVpcId(v string) *VpcConfigOutput { + s.VpcId = &v + return s +} + +const ( + // CanaryRunStateRunning is a CanaryRunState enum value + CanaryRunStateRunning = "RUNNING" + + // CanaryRunStatePassed is a CanaryRunState enum value + CanaryRunStatePassed = "PASSED" + + // CanaryRunStateFailed is a CanaryRunState enum value + CanaryRunStateFailed = "FAILED" +) + +// CanaryRunState_Values returns all elements of the CanaryRunState enum +func CanaryRunState_Values() []string { + return []string{ + CanaryRunStateRunning, + CanaryRunStatePassed, + CanaryRunStateFailed, + } +} + +const ( + // CanaryRunStateReasonCodeCanaryFailure is a CanaryRunStateReasonCode enum value + CanaryRunStateReasonCodeCanaryFailure = "CANARY_FAILURE" + + // CanaryRunStateReasonCodeExecutionFailure is a CanaryRunStateReasonCode enum value + CanaryRunStateReasonCodeExecutionFailure = "EXECUTION_FAILURE" +) + +// CanaryRunStateReasonCode_Values returns all elements of the CanaryRunStateReasonCode enum +func CanaryRunStateReasonCode_Values() []string { + return []string{ + CanaryRunStateReasonCodeCanaryFailure, + CanaryRunStateReasonCodeExecutionFailure, + } +} + +const ( + // CanaryStateCreating is a CanaryState enum value + CanaryStateCreating = "CREATING" + + // CanaryStateReady is a CanaryState enum value + CanaryStateReady = "READY" + + // CanaryStateStarting is a CanaryState enum value + CanaryStateStarting = "STARTING" + + // CanaryStateRunning is a CanaryState enum value + CanaryStateRunning = "RUNNING" + + // CanaryStateUpdating is a CanaryState enum value + CanaryStateUpdating = "UPDATING" + + // CanaryStateStopping is a CanaryState enum value + CanaryStateStopping = "STOPPING" + + // CanaryStateStopped is a CanaryState enum value + CanaryStateStopped = "STOPPED" + + // CanaryStateError is a CanaryState enum value + CanaryStateError = "ERROR" + + // CanaryStateDeleting is a CanaryState enum value + CanaryStateDeleting = "DELETING" +) + +// CanaryState_Values returns all elements of the CanaryState enum +func CanaryState_Values() []string { + return []string{ + CanaryStateCreating, + CanaryStateReady, + CanaryStateStarting, + CanaryStateRunning, + CanaryStateUpdating, + CanaryStateStopping, + CanaryStateStopped, + CanaryStateError, + CanaryStateDeleting, + } +} + +const ( + // CanaryStateReasonCodeInvalidPermissions is a CanaryStateReasonCode enum value + CanaryStateReasonCodeInvalidPermissions = "INVALID_PERMISSIONS" +) + +// CanaryStateReasonCode_Values returns all elements of the CanaryStateReasonCode enum +func CanaryStateReasonCode_Values() []string { + return []string{ + CanaryStateReasonCodeInvalidPermissions, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/synthetics/doc.go b/vendor/github.com/aws/aws-sdk-go/service/synthetics/doc.go new file mode 100644 index 00000000000..8a25de917d0 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/synthetics/doc.go @@ -0,0 +1,42 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +// Package synthetics provides the client and types for making API +// requests to Synthetics. +// +// You can use Amazon CloudWatch Synthetics to continually monitor your services. +// You can create and manage canaries, which are modular, lightweight scripts +// that monitor your endpoints and APIs from the outside-in. You can set up +// your canaries to run 24 hours a day, once per minute. The canaries help you +// check the availability and latency of your web services and troubleshoot +// anomalies by investigating load time data, screenshots of the UI, logs, and +// metrics. The canaries seamlessly integrate with CloudWatch ServiceLens to +// help you trace the causes of impacted nodes in your applications. For more +// information, see Using ServiceLens to Monitor the Health of Your Applications +// (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ServiceLens.html) +// in the Amazon CloudWatch User Guide. +// +// Before you create and manage canaries, be aware of the security considerations. +// For more information, see Security Considerations for Synthetics Canaries +// (https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html). +// +// See https://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11 for more information on this service. +// +// See synthetics package documentation for more information. +// https://docs.aws.amazon.com/sdk-for-go/api/service/synthetics/ +// +// Using the Client +// +// To contact Synthetics with the SDK use the New function to create +// a new service client. With that client you can make API requests to the service. +// These clients are safe to use concurrently. +// +// See the SDK's documentation for more information on how to use the SDK. +// https://docs.aws.amazon.com/sdk-for-go/api/ +// +// See aws.Config documentation for more information on configuring SDK clients. +// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config +// +// See the Synthetics client Synthetics for more +// information on creating client for this service. +// https://docs.aws.amazon.com/sdk-for-go/api/service/synthetics/#New +package synthetics diff --git a/vendor/github.com/aws/aws-sdk-go/service/synthetics/errors.go b/vendor/github.com/aws/aws-sdk-go/service/synthetics/errors.go new file mode 100644 index 00000000000..28559807882 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/synthetics/errors.go @@ -0,0 +1,41 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package synthetics + +import ( + "github.com/aws/aws-sdk-go/private/protocol" +) + +const ( + + // ErrCodeConflictException for service response error code + // "ConflictException". + // + // A conflicting operation is already in progress. + ErrCodeConflictException = "ConflictException" + + // ErrCodeInternalServerException for service response error code + // "InternalServerException". + // + // An unknown internal error occurred. + ErrCodeInternalServerException = "InternalServerException" + + // ErrCodeResourceNotFoundException for service response error code + // "ResourceNotFoundException". + // + // One of the specified resources was not found. + ErrCodeResourceNotFoundException = "ResourceNotFoundException" + + // ErrCodeValidationException for service response error code + // "ValidationException". + // + // A parameter could not be validated. + ErrCodeValidationException = "ValidationException" +) + +var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ + "ConflictException": newErrorConflictException, + "InternalServerException": newErrorInternalServerException, + "ResourceNotFoundException": newErrorResourceNotFoundException, + "ValidationException": newErrorValidationException, +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/synthetics/service.go b/vendor/github.com/aws/aws-sdk-go/service/synthetics/service.go new file mode 100644 index 00000000000..e957283a593 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/synthetics/service.go @@ -0,0 +1,104 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package synthetics + +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" + "github.com/aws/aws-sdk-go/private/protocol/restjson" +) + +// Synthetics provides the API operation methods for making requests to +// Synthetics. See this package's package overview docs +// for details on the service. +// +// Synthetics methods are safe to use concurrently. It is not safe to +// modify mutate any of the struct's properties though. +type Synthetics 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 = "synthetics" // Name of service. + EndpointsID = ServiceName // ID to lookup a service endpoint with. + ServiceID = "synthetics" // ServiceID is a unique identifier of a specific service. +) + +// New creates a new instance of the Synthetics 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: +// mySession := session.Must(session.NewSession()) +// +// // Create a Synthetics client from just a session. +// svc := synthetics.New(mySession) +// +// // Create a Synthetics client with additional configuration +// svc := synthetics.New(mySession, aws.NewConfig().WithRegion("us-west-2")) +func New(p client.ConfigProvider, cfgs ...*aws.Config) *Synthetics { + c := p.ClientConfig(EndpointsID, cfgs...) + if c.SigningNameDerived || len(c.SigningName) == 0 { + c.SigningName = "synthetics" + } + return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName) +} + +// newClient creates, initializes and returns a new service client instance. +func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *Synthetics { + svc := &Synthetics{ + Client: client.New( + cfg, + metadata.ClientInfo{ + ServiceName: ServiceName, + ServiceID: ServiceID, + SigningName: signingName, + SigningRegion: signingRegion, + PartitionID: partitionID, + Endpoint: endpoint, + APIVersion: "2017-10-11", + }, + handlers, + ), + } + + // Handlers + svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) + svc.Handlers.Build.PushBackNamed(restjson.BuildHandler) + svc.Handlers.Unmarshal.PushBackNamed(restjson.UnmarshalHandler) + svc.Handlers.UnmarshalMeta.PushBackNamed(restjson.UnmarshalMetaHandler) + svc.Handlers.UnmarshalError.PushBackNamed( + protocol.NewUnmarshalErrorHandler(restjson.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(), + ) + + // Run custom client initialization if present + if initClient != nil { + initClient(svc.Client) + } + + return svc +} + +// newRequest creates a new request for a Synthetics operation and runs any +// custom request initialization. +func (c *Synthetics) 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/transfer/api.go b/vendor/github.com/aws/aws-sdk-go/service/transfer/api.go index 2bb9c8f3628..1a8170f85fc 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/transfer/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/transfer/api.go @@ -502,6 +502,99 @@ func (c *Transfer) DeleteUserWithContext(ctx aws.Context, input *DeleteUserInput return out, req.Send() } +const opDescribeSecurityPolicy = "DescribeSecurityPolicy" + +// DescribeSecurityPolicyRequest generates a "aws/request.Request" representing the +// client's request for the DescribeSecurityPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeSecurityPolicy for more information on using the DescribeSecurityPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeSecurityPolicyRequest method. +// req, resp := client.DescribeSecurityPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DescribeSecurityPolicy +func (c *Transfer) DescribeSecurityPolicyRequest(input *DescribeSecurityPolicyInput) (req *request.Request, output *DescribeSecurityPolicyOutput) { + op := &request.Operation{ + Name: opDescribeSecurityPolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeSecurityPolicyInput{} + } + + output = &DescribeSecurityPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeSecurityPolicy API operation for AWS Transfer Family. +// +// Describes the security policy that is attached to your file transfer protocol-enabled +// server. The response contains a description of the security policy's properties. +// For more information about security policies, see Working with security policies +// (https://docs.aws.amazon.com/transfer/latest/userguide/security-policies.html). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Transfer Family's +// API operation DescribeSecurityPolicy for usage and error information. +// +// Returned Error Types: +// * ServiceUnavailableException +// The request has failed because the AWS Transfer Family service is not available. +// +// * InternalServiceError +// This exception is thrown when an error occurs in the AWS Transfer Family +// service. +// +// * InvalidRequestException +// This exception is thrown when the client submits a malformed request. +// +// * ResourceNotFoundException +// This exception is thrown when a resource is not found by the AWS Transfer +// Family service. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/DescribeSecurityPolicy +func (c *Transfer) DescribeSecurityPolicy(input *DescribeSecurityPolicyInput) (*DescribeSecurityPolicyOutput, error) { + req, out := c.DescribeSecurityPolicyRequest(input) + return out, req.Send() +} + +// DescribeSecurityPolicyWithContext is the same as DescribeSecurityPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeSecurityPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Transfer) DescribeSecurityPolicyWithContext(ctx aws.Context, input *DescribeSecurityPolicyInput, opts ...request.Option) (*DescribeSecurityPolicyOutput, error) { + req, out := c.DescribeSecurityPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeServer = "DescribeServer" // DescribeServerRequest generates a "aws/request.Request" representing the @@ -793,6 +886,154 @@ func (c *Transfer) ImportSshPublicKeyWithContext(ctx aws.Context, input *ImportS return out, req.Send() } +const opListSecurityPolicies = "ListSecurityPolicies" + +// ListSecurityPoliciesRequest generates a "aws/request.Request" representing the +// client's request for the ListSecurityPolicies operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListSecurityPolicies for more information on using the ListSecurityPolicies +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListSecurityPoliciesRequest method. +// req, resp := client.ListSecurityPoliciesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListSecurityPolicies +func (c *Transfer) ListSecurityPoliciesRequest(input *ListSecurityPoliciesInput) (req *request.Request, output *ListSecurityPoliciesOutput) { + op := &request.Operation{ + Name: opListSecurityPolicies, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &ListSecurityPoliciesInput{} + } + + output = &ListSecurityPoliciesOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListSecurityPolicies API operation for AWS Transfer Family. +// +// Lists the security policies that are attached to your file transfer protocol-enabled +// servers. +// +// Returns awserr.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 Transfer Family's +// API operation ListSecurityPolicies for usage and error information. +// +// Returned Error Types: +// * ServiceUnavailableException +// The request has failed because the AWS Transfer Family service is not available. +// +// * InternalServiceError +// This exception is thrown when an error occurs in the AWS Transfer Family +// service. +// +// * InvalidNextTokenException +// The NextToken parameter that was passed is invalid. +// +// * InvalidRequestException +// This exception is thrown when the client submits a malformed request. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListSecurityPolicies +func (c *Transfer) ListSecurityPolicies(input *ListSecurityPoliciesInput) (*ListSecurityPoliciesOutput, error) { + req, out := c.ListSecurityPoliciesRequest(input) + return out, req.Send() +} + +// ListSecurityPoliciesWithContext is the same as ListSecurityPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListSecurityPolicies for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Transfer) ListSecurityPoliciesWithContext(ctx aws.Context, input *ListSecurityPoliciesInput, opts ...request.Option) (*ListSecurityPoliciesOutput, error) { + req, out := c.ListSecurityPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// ListSecurityPoliciesPages iterates over the pages of a ListSecurityPolicies operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListSecurityPolicies 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 ListSecurityPolicies operation. +// pageNum := 0 +// err := client.ListSecurityPoliciesPages(params, +// func(page *transfer.ListSecurityPoliciesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *Transfer) ListSecurityPoliciesPages(input *ListSecurityPoliciesInput, fn func(*ListSecurityPoliciesOutput, bool) bool) error { + return c.ListSecurityPoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListSecurityPoliciesPagesWithContext same as ListSecurityPoliciesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *Transfer) ListSecurityPoliciesPagesWithContext(ctx aws.Context, input *ListSecurityPoliciesInput, fn func(*ListSecurityPoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListSecurityPoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListSecurityPoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListSecurityPoliciesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListServers = "ListServers" // ListServersRequest generates a "aws/request.Request" representing the @@ -2061,6 +2302,33 @@ type CreateServerInput struct { // The Amazon Resource Name (ARN) of the AWS Certificate Manager (ACM) certificate. // Required when Protocols is set to FTPS. + // + // To request a new public certificate, see Request a public certificate (https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request-public.html) + // in the AWS Certificate Manager User Guide. + // + // To import an existing certificate into ACM, see Importing certificates into + // ACM (https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html) + // in the AWS Certificate Manager User Guide. + // + // To request a private certificate to use FTPS through private IP addresses, + // see Request a private certificate (https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request-private.html) + // in the AWS Certificate Manager User Guide. + // + // Certificates with the following cryptographic algorithms and key sizes are + // supported: + // + // * 2048-bit RSA (RSA_2048) + // + // * 4096-bit RSA (RSA_4096) + // + // * Elliptic Prime Curve 256 bit (EC_prime256v1) + // + // * Elliptic Prime Curve 384 bit (EC_secp384r1) + // + // * Elliptic Prime Curve 521 bit (EC_secp521r1) + // + // The certificate must be a valid SSL/TLS X.509 version 3 certificate with + // FQDN or IP address specified and information about the issuer. Certificate *string `type:"string"` // The virtual private cloud (VPC) endpoint settings that are configured for @@ -2072,19 +2340,25 @@ type CreateServerInput struct { // The type of VPC endpoint that you want your file transfer protocol-enabled // server to connect to. You can choose to connect to the public internet or - // a virtual private cloud (VPC) endpoint. With a VPC endpoint, you can restrict - // access to your server and resources only within your VPC. + // a VPC endpoint. With a VPC endpoint, you can restrict access to your server + // and resources only within your VPC. + // + // It is recommended that you use VPC as the EndpointType. With this endpoint + // type, you have the option to directly associate up to three Elastic IPv4 + // addresses (BYO IP included) with your server's endpoint and use VPC security + // groups to restrict traffic by the client's public IP address. This is not + // possible with EndpointType set to VPC_ENDPOINT. EndpointType *string `type:"string" enum:"EndpointType"` - // The RSA private key as generated by the ssh-keygen -N "" -f my-new-server-key + // The RSA private key as generated by the ssh-keygen -N "" -m PEM -f my-new-server-key // command. // // If you aren't planning to migrate existing users from an existing SFTP-enabled // server to a new server, don't update the host key. Accidentally changing // a server's host key can be disruptive. // - // For more information, see Changing the Host Key for Your AWS Transfer Family - // Server (https://docs.aws.amazon.com/transfer/latest/userguide/configuring-servers.html#change-host-key) + // For more information, see Change the host key for your SFTP-enabled server + // (https://docs.aws.amazon.com/transfer/latest/userguide/edit-server-config.html#configuring-servers-change-host-key) // in the AWS Transfer Family User Guide. HostKey *string `type:"string" sensitive:"true"` @@ -2110,14 +2384,29 @@ type CreateServerInput struct { // protocol client can connect to your server's endpoint. The available protocols // are: // - // * Secure Shell (SSH) File Transfer Protocol (SFTP): File transfer over + // * SFTP (Secure Shell (SSH) File Transfer Protocol): File transfer over // SSH // - // * File Transfer Protocol Secure (FTPS): File transfer with TLS encryption + // * FTPS (File Transfer Protocol Secure): File transfer with TLS encryption // - // * File Transfer Protocol (FTP): Unencrypted file transfer + // * FTP (File Transfer Protocol): Unencrypted file transfer + // + // If you select FTPS, you must choose a certificate stored in AWS Certificate + // Manager (ACM) which will be used to identify your file transfer protocol-enabled + // server when clients connect to it over FTPS. + // + // If Protocol includes either FTP or FTPS, then the EndpointType must be VPC + // and the IdentityProviderType must be API_GATEWAY. + // + // If Protocol includes FTP, then AddressAllocationIds cannot be associated. + // + // If Protocol is set only to SFTP, the EndpointType can be set to PUBLIC and + // the IdentityProviderType can be set to SERVICE_MANAGED. Protocols []*string `min:"1" type:"list"` + // Specifies the name of the security policy that is attached to the server. + SecurityPolicyName *string `type:"string"` + // Key-value pairs that can be used to group and search for file transfer protocol-enabled // servers. Tags []*Tag `min:"1" type:"list"` @@ -2220,6 +2509,12 @@ func (s *CreateServerInput) SetProtocols(v []*string) *CreateServerInput { return s } +// SetSecurityPolicyName sets the SecurityPolicyName field's value. +func (s *CreateServerInput) SetSecurityPolicyName(v string) *CreateServerInput { + s.SecurityPolicyName = &v + return s +} + // SetTags sets the Tags field's value. func (s *CreateServerInput) SetTags(v []*Tag) *CreateServerInput { s.Tags = v @@ -2258,7 +2553,7 @@ type CreateUserInput struct { // The landing directory (folder) for a user when they log in to the file transfer // protocol-enabled server using the client. // - // An example is your-Amazon-S3-bucket-name>/home/username. + // An example is your-Amazon-S3-bucket-name>/home/username . HomeDirectory *string `type:"string"` // Logical directory mappings that specify what Amazon S3 paths and keys should @@ -2266,8 +2561,7 @@ type CreateUserInput struct { // to specify the "Entry" and "Target" pair, where Entry shows how the path // is made visible and Target is the actual Amazon S3 path. If you only specify // a target, it will be displayed as is. You will need to also make sure that - // your AWS IAM Role provides access to paths in Target. The following is an - // example. + // your IAM role provides access to paths in Target. The following is an example. // // '[ "/bucket2/documentation", { "Entry": "your-personal-report.pdf", "Target": // "/bucket3/customized-reports/${transfer:UserName}.pdf" } ]' @@ -2277,7 +2571,7 @@ type CreateUserInput struct { // you can set Entry to '/' and set Target to the HomeDirectory parameter value. // // If the target of a logical directory entry does not exist in Amazon S3, the - // entry will be ignored. As a workaround, you can use the Amazon S3 api to + // entry will be ignored. As a workaround, you can use the Amazon S3 API to // create 0 byte objects as place holders for your directory. If using the CLI, // use the s3api call instead of s3 so you can use the put-object operation. // For example, you use the following: aws s3api put-object --bucket bucketname @@ -2302,7 +2596,7 @@ type CreateUserInput struct { // blob, instead of the Amazon Resource Name (ARN) of the policy. You save the // policy as a JSON blob and pass it in the Policy argument. // - // For an example of a scope-down policy, see Creating a Scope-Down Policy (https://docs.aws.amazon.com/transfer/latest/userguide/users.html#users-policies-scope-down). + // For an example of a scope-down policy, see Creating a scope-down policy (https://docs.aws.amazon.com/transfer/latest/userguide/users.html#users-policies-scope-down). // // For more information, see AssumeRole (https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) // in the AWS Security Token Service API Reference. @@ -2334,9 +2628,10 @@ type CreateUserInput struct { // A unique string that identifies a user and is associated with a file transfer // protocol-enabled server as specified by the ServerId. This user name must - // be a minimum of 3 and a maximum of 32 characters long. The following are - // valid characters: a-z, A-Z, 0-9, underscore, and hyphen. The user name can't - // start with a hyphen. + // be a minimum of 3 and a maximum of 100 characters long. The following are + // valid characters: a-z, A-Z, 0-9, underscore '_', hyphen '-', period '.', + // and at sign '@'. The user name can't start with a hyphen, period, and at + // sign. // // UserName is a required field UserName *string `min:"3" type:"string" required:"true"` @@ -2718,6 +3013,69 @@ func (s DeleteUserOutput) GoString() string { return s.String() } +type DescribeSecurityPolicyInput struct { + _ struct{} `type:"structure"` + + // Specifies the name of the security policy that is attached to the server. + // + // SecurityPolicyName is a required field + SecurityPolicyName *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeSecurityPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeSecurityPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeSecurityPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeSecurityPolicyInput"} + if s.SecurityPolicyName == nil { + invalidParams.Add(request.NewErrParamRequired("SecurityPolicyName")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetSecurityPolicyName sets the SecurityPolicyName field's value. +func (s *DescribeSecurityPolicyInput) SetSecurityPolicyName(v string) *DescribeSecurityPolicyInput { + s.SecurityPolicyName = &v + return s +} + +type DescribeSecurityPolicyOutput struct { + _ struct{} `type:"structure"` + + // An array containing the properties of the security policy. + // + // SecurityPolicy is a required field + SecurityPolicy *DescribedSecurityPolicy `type:"structure" required:"true"` +} + +// String returns the string representation +func (s DescribeSecurityPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeSecurityPolicyOutput) GoString() string { + return s.String() +} + +// SetSecurityPolicy sets the SecurityPolicy field's value. +func (s *DescribeSecurityPolicyOutput) SetSecurityPolicy(v *DescribedSecurityPolicy) *DescribeSecurityPolicyOutput { + s.SecurityPolicy = v + return s +} + type DescribeServerInput struct { _ struct{} `type:"structure"` @@ -2885,35 +3243,110 @@ func (s *DescribeUserOutput) SetUser(v *DescribedUser) *DescribeUserOutput { return s } +// Describes the properties of a security policy that was specified. For more +// information about security policies, see Working with security policies (https://docs.aws.amazon.com/transfer/latest/userguide/security-policies.html). +type DescribedSecurityPolicy struct { + _ struct{} `type:"structure"` + + // Specifies whether this policy enables Federal Information Processing Standards + // (FIPS). + Fips *bool `type:"boolean"` + + // Specifies the name of the security policy that is attached to the server. + // + // SecurityPolicyName is a required field + SecurityPolicyName *string `type:"string" required:"true"` + + // Specifies the enabled Secure Shell (SSH) cipher encryption algorithms in + // the security policy that is attached to the server. + SshCiphers []*string `type:"list"` + + // Specifies the enabled SSH key exchange (KEX) encryption algorithms in the + // security policy that is attached to the server. + SshKexs []*string `type:"list"` + + // Specifies the enabled SSH message authentication code (MAC) encryption algorithms + // in the security policy that is attached to the server. + SshMacs []*string `type:"list"` + + // Specifies the enabled Transport Layer Security (TLS) cipher encryption algorithms + // in the security policy that is attached to the server. + TlsCiphers []*string `type:"list"` +} + +// String returns the string representation +func (s DescribedSecurityPolicy) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribedSecurityPolicy) GoString() string { + return s.String() +} + +// SetFips sets the Fips field's value. +func (s *DescribedSecurityPolicy) SetFips(v bool) *DescribedSecurityPolicy { + s.Fips = &v + return s +} + +// SetSecurityPolicyName sets the SecurityPolicyName field's value. +func (s *DescribedSecurityPolicy) SetSecurityPolicyName(v string) *DescribedSecurityPolicy { + s.SecurityPolicyName = &v + return s +} + +// SetSshCiphers sets the SshCiphers field's value. +func (s *DescribedSecurityPolicy) SetSshCiphers(v []*string) *DescribedSecurityPolicy { + s.SshCiphers = v + return s +} + +// SetSshKexs sets the SshKexs field's value. +func (s *DescribedSecurityPolicy) SetSshKexs(v []*string) *DescribedSecurityPolicy { + s.SshKexs = v + return s +} + +// SetSshMacs sets the SshMacs field's value. +func (s *DescribedSecurityPolicy) SetSshMacs(v []*string) *DescribedSecurityPolicy { + s.SshMacs = v + return s +} + +// SetTlsCiphers sets the TlsCiphers field's value. +func (s *DescribedSecurityPolicy) SetTlsCiphers(v []*string) *DescribedSecurityPolicy { + s.TlsCiphers = v + return s +} + // Describes the properties of a file transfer protocol-enabled server that -// was specified. Information returned includes the following: the server Amazon -// Resource Name (ARN), the authentication configuration and type, the logging -// role, the server ID and state, and assigned tags or metadata. +// was specified. type DescribedServer struct { _ struct{} `type:"structure"` - // Specifies the unique Amazon Resource Name (ARN) for a file transfer protocol-enabled - // server to be described. + // Specifies the unique Amazon Resource Name (ARN) of the file transfer protocol-enabled + // server. // // Arn is a required field Arn *string `min:"20" type:"string" required:"true"` - // The Amazon Resource Name (ARN) of the AWS Certificate Manager (ACM) certificate. - // Required when Protocols is set to FTPS. + // Specifies the ARN of the AWS Certificate Manager (ACM) certificate. Required + // when Protocols is set to FTPS. Certificate *string `type:"string"` - // The virtual private cloud (VPC) endpoint settings that you configured for - // your file transfer protocol-enabled server. + // Specifies the virtual private cloud (VPC) endpoint settings that you configured + // for your file transfer protocol-enabled server. EndpointDetails *EndpointDetails `type:"structure"` - // The type of endpoint that your file transfer protocol-enabled server is connected - // to. If your server is connected to a VPC endpoint, your server isn't accessible - // over the public internet. + // Defines the type of endpoint that your file transfer protocol-enabled server + // is connected to. If your server is connected to a VPC endpoint, your server + // isn't accessible over the public internet. EndpointType *string `type:"string" enum:"EndpointType"` - // Contains the message-digest algorithm (MD5) hash of a file transfer protocol-enabled - // server's host key. This value is equivalent to the output of the ssh-keygen - // -l -E md5 -f my-new-server-key command. + // Specifies the Base64-encoded SHA256 fingerprint of the server's host key. + // This value is equivalent to the output of the ssh-keygen -l -f my-new-server-key + // command. HostKeyFingerprint *string `type:"string"` // Specifies information to call a customer-supplied authentication API. This @@ -2921,50 +3354,54 @@ type DescribedServer struct { // server is SERVICE_MANAGED. IdentityProviderDetails *IdentityProviderDetails `type:"structure"` - // Defines the mode of authentication method enabled for this service. A value + // Specifies the mode of authentication method enabled for this service. A value // of SERVICE_MANAGED means that you are using this file transfer protocol-enabled // server to store and access user credentials within the service. A value of // API_GATEWAY indicates that you have integrated an API Gateway endpoint that // will be invoked for authenticating your user into the service. IdentityProviderType *string `type:"string" enum:"IdentityProviderType"` - // An AWS Identity and Access Management (IAM) entity that allows a file transfer - // protocol-enabled server to turn on Amazon CloudWatch logging for Amazon S3 - // events. When set, user activity can be viewed in your CloudWatch logs. + // Specifies the AWS Identity and Access Management (IAM) role that allows a + // file transfer protocol-enabled server to turn on Amazon CloudWatch logging + // for Amazon S3 events. When set, user activity can be viewed in your CloudWatch + // logs. LoggingRole *string `min:"20" type:"string"` // Specifies the file transfer protocol or protocols over which your file transfer // protocol client can connect to your server's endpoint. The available protocols // are: // - // * Secure Shell (SSH) File Transfer Protocol (SFTP): File transfer over + // * SFTP (Secure Shell (SSH) File Transfer Protocol): File transfer over // SSH // - // * File Transfer Protocol Secure (FTPS): File transfer with TLS encryption + // * FTPS (File Transfer Protocol Secure): File transfer with TLS encryption // - // * File Transfer Protocol (FTP): Unencrypted file transfer + // * FTP (File Transfer Protocol): Unencrypted file transfer Protocols []*string `min:"1" type:"list"` - // Unique system-assigned identifier for a file transfer protocol-enabled server - // that you instantiate. + // Specifies the name of the security policy that is attached to the server. + SecurityPolicyName *string `type:"string"` + + // Specifies the unique system-assigned identifier for a file transfer protocol-enabled + // server that you instantiate. ServerId *string `min:"19" type:"string"` - // The condition of a file transfer protocol-enabled server for the server that - // was described. A value of ONLINE indicates that the server can accept jobs - // and transfer files. A State value of OFFLINE means that the server cannot - // perform file transfer operations. + // Specifies the condition of a file transfer protocol-enabled server for the + // server that was described. A value of ONLINE indicates that the server can + // accept jobs and transfer files. A State value of OFFLINE means that the server + // cannot perform file transfer operations. // // The states of STARTING and STOPPING indicate that the server is in an intermediate // state, either not fully able to respond, or not fully offline. The values // of START_FAILED or STOP_FAILED can indicate an error condition. State *string `type:"string" enum:"State"` - // Contains the key-value pairs that you can use to search for and group file + // Specifies the key-value pairs that you can use to search for and group file // transfer protocol-enabled servers that were assigned to the server that was // described. Tags []*Tag `min:"1" type:"list"` - // The number of users that are assigned to a file transfer protocol-enabled + // Specifies the number of users that are assigned to a file transfer protocol-enabled // server you specified with the ServerId. UserCount *int64 `type:"integer"` } @@ -3033,6 +3470,12 @@ func (s *DescribedServer) SetProtocols(v []*string) *DescribedServer { return s } +// SetSecurityPolicyName sets the SecurityPolicyName field's value. +func (s *DescribedServer) SetSecurityPolicyName(v string) *DescribedServer { + s.SecurityPolicyName = &v + return s +} + // SetServerId sets the ServerId field's value. func (s *DescribedServer) SetServerId(v string) *DescribedServer { s.ServerId = &v @@ -3057,39 +3500,40 @@ func (s *DescribedServer) SetUserCount(v int64) *DescribedServer { return s } -// Returns properties of the user that you want to describe. +// Describes the properties of a user that was specified. type DescribedUser struct { _ struct{} `type:"structure"` - // Contains the unique Amazon Resource Name (ARN) for the user that was requested + // Specifies the unique Amazon Resource Name (ARN) for the user that was requested // to be described. // // Arn is a required field Arn *string `min:"20" type:"string" required:"true"` // Specifies the landing directory (or folder), which is the location that files - // are written to or read from in an Amazon S3 bucket for the described user. - // An example is /your s3 bucket name/home/username . + // are written to or read from in an Amazon S3 bucket, for the described user. + // An example is your-Amazon-S3-bucket-name>/home/username . HomeDirectory *string `type:"string"` - // Logical directory mappings that you specified for what Amazon S3 paths and - // keys should be visible to your user and how you want to make them visible. + // Specifies the logical directory mappings that specify what Amazon S3 paths + // and keys should be visible to your user and how you want to make them visible. // You will need to specify the "Entry" and "Target" pair, where Entry shows // how the path is made visible and Target is the actual Amazon S3 path. If // you only specify a target, it will be displayed as is. You will need to also - // make sure that your AWS IAM Role provides access to paths in Target. + // make sure that your AWS Identity and Access Management (IAM) role provides + // access to paths in Target. // // In most cases, you can use this value instead of the scope-down policy to // lock your user down to the designated home directory ("chroot"). To do this, // you can set Entry to '/' and set Target to the HomeDirectory parameter value. HomeDirectoryMappings []*HomeDirectoryMapEntry `min:"1" type:"list"` - // The type of landing directory (folder) you mapped for your users to see when - // they log into the file transfer protocol-enabled server. If you set it to - // PATH, the user will see the absolute Amazon S3 bucket paths as is in their - // file transfer protocol clients. If you set it LOGICAL, you will need to provide - // mappings in the HomeDirectoryMappings for how you want to make Amazon S3 - // paths visible to your users. + // Specifies the type of landing directory (folder) you mapped for your users + // to see when they log into the file transfer protocol-enabled server. If you + // set it to PATH, the user will see the absolute Amazon S3 bucket paths as + // is in their file transfer protocol clients. If you set it LOGICAL, you will + // need to provide mappings in the HomeDirectoryMappings for how you want to + // make Amazon S3 paths visible to your users. HomeDirectoryType *string `type:"string" enum:"HomeDirectoryType"` // Specifies the name of the policy in use for the described user. @@ -3103,17 +3547,17 @@ type DescribedUser struct { // when servicing your users' transfer requests. Role *string `min:"20" type:"string"` - // Contains the public key portion of the Secure Shell (SSH) keys stored for + // Specifies the public key portion of the Secure Shell (SSH) keys stored for // the described user. SshPublicKeys []*SshPublicKey `type:"list"` - // Contains the key-value pairs for the user requested. Tag can be used to search - // for and group users for a variety of purposes. + // Specifies the key-value pairs for the user requested. Tag can be used to + // search for and group users for a variety of purposes. Tags []*Tag `min:"1" type:"list"` - // The name of the user that was requested to be described. User names are used - // for authentication purposes. This is the string that will be used by your - // user when they log in to your file transfer protocol-enabled server. + // Specifies the name of the user that was requested to be described. User names + // are used for authentication purposes. This is the string that will be used + // by your user when they log in to your file transfer protocol-enabled server. UserName *string `min:"3" type:"string"` } @@ -3198,13 +3642,19 @@ type EndpointDetails struct { // A list of subnet IDs that are required to host your file transfer protocol-enabled // server endpoint in your VPC. + // + // This property can only be used when EndpointType is set to VPC. SubnetIds []*string `type:"list"` // The ID of the VPC endpoint. + // + // This property can only be used when EndpointType is set to VPC_ENDPOINT. VpcEndpointId *string `min:"22" type:"string"` // The VPC ID of the VPC in which a file transfer protocol-enabled server's // endpoint will be hosted. + // + // This property can only be used when EndpointType is set to VPC. VpcId *string `type:"string"` } @@ -3255,7 +3705,7 @@ func (s *EndpointDetails) SetVpcId(v string) *EndpointDetails { return s } -// Represents an object that contains entries and a targets for HomeDirectoryMappings. +// Represents an object that contains entries and targets for HomeDirectoryMappings. type HomeDirectoryMapEntry struct { _ struct{} `type:"structure"` @@ -3317,7 +3767,7 @@ type IdentityProviderDetails struct { // Provides the type of InvocationRole used to authenticate the user account. InvocationRole *string `min:"20" type:"string"` - // Contains the location of the service endpoint used to authenticate users. + // Provides the location of the service endpoint used to authenticate users. Url *string `type:"string"` } @@ -3650,6 +4100,94 @@ func (s *InvalidRequestException) RequestID() string { return s.RespMetadata.RequestID } +type ListSecurityPoliciesInput struct { + _ struct{} `type:"structure"` + + // Specifies the number of security policies to return as a response to the + // ListSecurityPolicies query. + MaxResults *int64 `min:"1" type:"integer"` + + // When additional results are obtained from the ListSecurityPolicies command, + // a NextToken parameter is returned in the output. You can then pass the NextToken + // parameter in a subsequent command to continue listing additional security + // policies. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListSecurityPoliciesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListSecurityPoliciesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListSecurityPoliciesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListSecurityPoliciesInput"} + 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 *ListSecurityPoliciesInput) SetMaxResults(v int64) *ListSecurityPoliciesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *ListSecurityPoliciesInput) SetNextToken(v string) *ListSecurityPoliciesInput { + s.NextToken = &v + return s +} + +type ListSecurityPoliciesOutput struct { + _ struct{} `type:"structure"` + + // When you can get additional results from the ListSecurityPolicies operation, + // a NextToken parameter is returned in the output. In a following command, + // you can pass in the NextToken parameter to continue listing security policies. + NextToken *string `min:"1" type:"string"` + + // An array of security policies that were listed. + // + // SecurityPolicyNames is a required field + SecurityPolicyNames []*string `type:"list" required:"true"` +} + +// String returns the string representation +func (s ListSecurityPoliciesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListSecurityPoliciesOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListSecurityPoliciesOutput) SetNextToken(v string) *ListSecurityPoliciesOutput { + s.NextToken = &v + return s +} + +// SetSecurityPolicyNames sets the SecurityPolicyNames field's value. +func (s *ListSecurityPoliciesOutput) SetSecurityPolicyNames(v []*string) *ListSecurityPoliciesOutput { + s.SecurityPolicyNames = v + return s +} + type ListServersInput struct { _ struct{} `type:"structure"` @@ -3657,7 +4195,7 @@ type ListServersInput struct { // as a response to the ListServers query. MaxResults *int64 `min:"1" type:"integer"` - // When additional results are obtained from theListServers command, a NextToken + // When additional results are obtained from the ListServers command, a NextToken // parameter is returned in the output. You can then pass the NextToken parameter // in a subsequent command to continue listing additional file transfer protocol-enabled // servers. @@ -3974,32 +4512,32 @@ func (s *ListUsersOutput) SetUsers(v []*ListedUser) *ListUsersOutput { type ListedServer struct { _ struct{} `type:"structure"` - // The unique Amazon Resource Name (ARN) for a file transfer protocol-enabled + // Specifies the unique Amazon Resource Name (ARN) for a file transfer protocol-enabled // server to be listed. // // Arn is a required field Arn *string `min:"20" type:"string" required:"true"` - // The type of VPC endpoint that your file transfer protocol-enabled server - // is connected to. If your server is connected to a VPC endpoint, your server - // isn't accessible over the public internet. + // Specifies the type of VPC endpoint that your file transfer protocol-enabled + // server is connected to. If your server is connected to a VPC endpoint, your + // server isn't accessible over the public internet. EndpointType *string `type:"string" enum:"EndpointType"` - // The authentication method used to validate a user for a file transfer protocol-enabled - // server that was specified. This can include Secure Shell (SSH), user name - // and password combinations, or your own custom authentication method. Valid - // values include SERVICE_MANAGED or API_GATEWAY. + // Specifies the authentication method used to validate a user for a file transfer + // protocol-enabled server that was specified. This can include Secure Shell + // (SSH), user name and password combinations, or your own custom authentication + // method. Valid values include SERVICE_MANAGED or API_GATEWAY. IdentityProviderType *string `type:"string" enum:"IdentityProviderType"` - // The AWS Identity and Access Management (IAM) entity that allows a file transfer - // protocol-enabled server to turn on Amazon CloudWatch logging. + // Specifies the AWS Identity and Access Management (IAM) role that allows a + // file transfer protocol-enabled server to turn on Amazon CloudWatch logging. LoggingRole *string `min:"20" type:"string"` - // The unique system assigned identifier for a file transfer protocol-enabled + // Specifies the unique system assigned identifier for a file transfer protocol-enabled // servers that were listed. ServerId *string `min:"19" type:"string"` - // Describes the condition of a file transfer protocol-enabled server for the + // Specifies the condition of a file transfer protocol-enabled server for the // server that was described. A value of ONLINE indicates that the server can // accept jobs and transfer files. A State value of OFFLINE means that the server // cannot perform file transfer operations. @@ -4009,8 +4547,8 @@ type ListedServer struct { // of START_FAILED or STOP_FAILED can indicate an error condition. State *string `type:"string" enum:"State"` - // A numeric value that indicates the number of users that are assigned to a - // file transfer protocol-enabled server you specified with the ServerId. + // Specifies the number of users that are assigned to a file transfer protocol-enabled + // server you specified with the ServerId. UserCount *int64 `type:"integer"` } @@ -4070,8 +4608,8 @@ func (s *ListedServer) SetUserCount(v int64) *ListedServer { type ListedUser struct { _ struct{} `type:"structure"` - // The unique Amazon Resource Name (ARN) for the user that you want to learn - // about. + // Provides the unique Amazon Resource Name (ARN) for the user that you want + // to learn about. // // Arn is a required field Arn *string `min:"20" type:"string" required:"true"` @@ -4080,25 +4618,25 @@ type ListedUser struct { // bucket for the user you specify by their ARN. HomeDirectory *string `type:"string"` - // The type of landing directory (folder) you mapped for your users' home directory. - // If you set it to PATH, the user will see the absolute Amazon S3 bucket paths - // as is in their file transfer protocol clients. If you set it LOGICAL, you - // will need to provide mappings in the HomeDirectoryMappings for how you want - // to make Amazon S3 paths visible to your users. + // Specifies the type of landing directory (folder) you mapped for your users' + // home directory. If you set it to PATH, the user will see the absolute Amazon + // S3 bucket paths as is in their file transfer protocol clients. If you set + // it LOGICAL, you will need to provide mappings in the HomeDirectoryMappings + // for how you want to make Amazon S3 paths visible to your users. HomeDirectoryType *string `type:"string" enum:"HomeDirectoryType"` - // The role in use by this user. A role is an AWS Identity and Access Management - // (IAM) entity that, in this case, allows a file transfer protocol-enabled - // server to act on a user's behalf. It allows the server to inherit the trust - // relationship that enables that user to perform file operations to their Amazon - // S3 bucket. + // Specifies the role that is in use by this user. A role is an AWS Identity + // and Access Management (IAM) entity that, in this case, allows a file transfer + // protocol-enabled server to act on a user's behalf. It allows the server to + // inherit the trust relationship that enables that user to perform file operations + // to their Amazon S3 bucket. Role *string `min:"20" type:"string"` - // The number of SSH public keys stored for the user you specified. + // Specifies the number of SSH public keys stored for the user you specified. SshPublicKeyCount *int64 `type:"integer"` - // The name of the user whose ARN was specified. User names are used for authentication - // purposes. + // Specifies the name of the user whose ARN was specified. User names are used + // for authentication purposes. UserName *string `min:"3" type:"string"` } @@ -4338,17 +4876,18 @@ func (s *ServiceUnavailableException) RequestID() string { type SshPublicKey struct { _ struct{} `type:"structure"` - // The date that the public key was added to the user account. + // Specifies the date that the public key was added to the user account. // // DateImported is a required field DateImported *time.Time `type:"timestamp" required:"true"` - // The content of the SSH public key as specified by the PublicKeyId. + // Specifies the content of the SSH public key as specified by the PublicKeyId. // // SshPublicKeyBody is a required field SshPublicKeyBody *string `type:"string" required:"true"` - // The SshPublicKeyId parameter contains the identifier of the public key. + // Specifies the SshPublicKeyId parameter contains the identifier of the public + // key. // // SshPublicKeyId is a required field SshPublicKeyId *string `min:"21" type:"string" required:"true"` @@ -4658,6 +5197,9 @@ type TestIdentityProviderInput struct { // * File Transfer Protocol (FTP) ServerProtocol *string `type:"string" enum:"Protocol"` + // The source IP address of the user account to be tested. + SourceIp *string `type:"string"` + // The name of the user account to be tested. // // UserName is a required field @@ -4711,6 +5253,12 @@ func (s *TestIdentityProviderInput) SetServerProtocol(v string) *TestIdentityPro return s } +// SetSourceIp sets the SourceIp field's value. +func (s *TestIdentityProviderInput) SetSourceIp(v string) *TestIdentityProviderInput { + s.SourceIp = &v + return s +} + // SetUserName sets the UserName field's value. func (s *TestIdentityProviderInput) SetUserName(v string) *TestIdentityProviderInput { s.UserName = &v @@ -4918,6 +5466,33 @@ type UpdateServerInput struct { // The Amazon Resource Name (ARN) of the AWS Certificate Manager (ACM) certificate. // Required when Protocols is set to FTPS. + // + // To request a new public certificate, see Request a public certificate (https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request-public.html) + // in the AWS Certificate Manager User Guide. + // + // To import an existing certificate into ACM, see Importing certificates into + // ACM (https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html) + // in the AWS Certificate Manager User Guide. + // + // To request a private certificate to use FTPS through private IP addresses, + // see Request a private certificate (https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request-private.html) + // in the AWS Certificate Manager User Guide. + // + // Certificates with the following cryptographic algorithms and key sizes are + // supported: + // + // * 2048-bit RSA (RSA_2048) + // + // * 4096-bit RSA (RSA_4096) + // + // * Elliptic Prime Curve 256 bit (EC_prime256v1) + // + // * Elliptic Prime Curve 384 bit (EC_secp384r1) + // + // * Elliptic Prime Curve 521 bit (EC_secp521r1) + // + // The certificate must be a valid SSL/TLS X.509 version 3 certificate with + // FQDN or IP address specified and information about the issuer. Certificate *string `type:"string"` // The virtual private cloud (VPC) endpoint settings that are configured for @@ -4929,18 +5504,24 @@ type UpdateServerInput struct { // The type of endpoint that you want your file transfer protocol-enabled server // to connect to. You can choose to connect to the public internet or a VPC - // endpoint. With a VPC endpoint, your server isn't accessible over the public - // internet. + // endpoint. With a VPC endpoint, you can restrict access to your server and + // resources only within your VPC. + // + // It is recommended that you use VPC as the EndpointType. With this endpoint + // type, you have the option to directly associate up to three Elastic IPv4 + // addresses (BYO IP included) with your server's endpoint and use VPC security + // groups to restrict traffic by the client's public IP address. This is not + // possible with EndpointType set to VPC_ENDPOINT. EndpointType *string `type:"string" enum:"EndpointType"` - // The RSA private key as generated by ssh-keygen -N "" -f my-new-server-key. + // The RSA private key as generated by ssh-keygen -N "" -m PEM -f my-new-server-key. // // If you aren't planning to migrate existing users from an existing file transfer // protocol-enabled server to a new server, don't update the host key. Accidentally // changing a server's host key can be disruptive. // - // For more information, see Changing the Host Key for Your AWS Transfer Family - // Server (https://docs.aws.amazon.com/transfer/latest/userguide/configuring-servers.html#change-host-key) + // For more information, see Change the host key for your SFTP-enabled server + // (https://docs.aws.amazon.com/transfer/latest/userguide/edit-server-config.html#configuring-servers-change-host-key) // in the AWS Transfer Family User Guide. HostKey *string `type:"string" sensitive:"true"` @@ -4962,8 +5543,23 @@ type UpdateServerInput struct { // * File Transfer Protocol Secure (FTPS): File transfer with TLS encryption // // * File Transfer Protocol (FTP): Unencrypted file transfer + // + // If you select FTPS, you must choose a certificate stored in AWS Certificate + // Manager (ACM) which will be used to identify your server when clients connect + // to it over FTPS. + // + // If Protocol includes either FTP or FTPS, then the EndpointType must be VPC + // and the IdentityProviderType must be API_GATEWAY. + // + // If Protocol includes FTP, then AddressAllocationIds cannot be associated. + // + // If Protocol is set only to SFTP, the EndpointType can be set to PUBLIC and + // the IdentityProviderType can be set to SERVICE_MANAGED. Protocols []*string `min:"1" type:"list"` + // Specifies the name of the security policy that is attached to the server. + SecurityPolicyName *string `type:"string"` + // A system-assigned unique identifier for a file transfer protocol-enabled // server instance that the user account is assigned to. // @@ -5052,6 +5648,12 @@ func (s *UpdateServerInput) SetProtocols(v []*string) *UpdateServerInput { return s } +// SetSecurityPolicyName sets the SecurityPolicyName field's value. +func (s *UpdateServerInput) SetSecurityPolicyName(v string) *UpdateServerInput { + s.SecurityPolicyName = &v + return s +} + // SetServerId sets the ServerId field's value. func (s *UpdateServerInput) SetServerId(v string) *UpdateServerInput { s.ServerId = &v @@ -5099,8 +5701,7 @@ type UpdateUserInput struct { // to specify the "Entry" and "Target" pair, where Entry shows how the path // is made visible and Target is the actual Amazon S3 path. If you only specify // a target, it will be displayed as is. You will need to also make sure that - // your AWS IAM Role provides access to paths in Target. The following is an - // example. + // your IAM role provides access to paths in Target. The following is an example. // // '[ "/bucket2/documentation", { "Entry": "your-personal-report.pdf", "Target": // "/bucket3/customized-reports/${transfer:UserName}.pdf" } ]' @@ -5110,7 +5711,7 @@ type UpdateUserInput struct { // you can set Entry to '/' and set Target to the HomeDirectory parameter value. // // If the target of a logical directory entry does not exist in Amazon S3, the - // entry will be ignored. As a workaround, you can use the Amazon S3 api to + // entry will be ignored. As a workaround, you can use the Amazon S3 API to // create 0 byte objects as place holders for your directory. If using the CLI, // use the s3api call instead of s3 so you can use the put-object operation. // For example, you use the following: aws s3api put-object --bucket bucketname @@ -5127,16 +5728,15 @@ type UpdateUserInput struct { HomeDirectoryType *string `type:"string" enum:"HomeDirectoryType"` // Allows you to supply a scope-down policy for your user so you can use the - // same AWS Identity and Access Management (IAM) role across multiple users. - // The policy scopes down user access to portions of your Amazon S3 bucket. - // Variables you can use inside this policy include ${Transfer:UserName}, ${Transfer:HomeDirectory}, - // and ${Transfer:HomeBucket}. + // same IAM role across multiple users. The policy scopes down user access to + // portions of your Amazon S3 bucket. Variables you can use inside this policy + // include ${Transfer:UserName}, ${Transfer:HomeDirectory}, and ${Transfer:HomeBucket}. // // For scope-down policies, AWS Transfer Family stores the policy as a JSON // blob, instead of the Amazon Resource Name (ARN) of the policy. You save the // policy as a JSON blob and pass it in the Policy argument. // - // For an example of a scope-down policy, see Creating a Scope-Down Policy (https://docs.aws.amazon.com/transfer/latest/userguide/users.html#users-policies-scope-down). + // For an example of a scope-down policy, see Creating a scope-down policy (https://docs.aws.amazon.com/transfer/latest/userguide/users.html#users-policies-scope-down). // // For more information, see AssumeRole (https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) // in the AWS Security Token Service API Reference. @@ -5157,11 +5757,11 @@ type UpdateUserInput struct { ServerId *string `min:"19" type:"string" required:"true"` // A unique string that identifies a user and is associated with a file transfer - // protocol-enabled server as specified by the ServerId. This is the string - // that will be used by your user when they log in to your server. This user - // name is a minimum of 3 and a maximum of 32 characters long. The following - // are valid characters: a-z, A-Z, 0-9, underscore, and hyphen. The user name - // can't start with a hyphen. + // protocol-enabled server as specified by the ServerId. This user name must + // be a minimum of 3 and a maximum of 100 characters long. The following are + // valid characters: a-z, A-Z, 0-9, underscore '_', hyphen '-', period '.', + // and at sign '@'. The user name can't start with a hyphen, period, and at + // sign. // // UserName is a required field UserName *string `min:"3" type:"string" required:"true"` @@ -5308,6 +5908,15 @@ const ( EndpointTypeVpcEndpoint = "VPC_ENDPOINT" ) +// EndpointType_Values returns all elements of the EndpointType enum +func EndpointType_Values() []string { + return []string{ + EndpointTypePublic, + EndpointTypeVpc, + EndpointTypeVpcEndpoint, + } +} + const ( // HomeDirectoryTypePath is a HomeDirectoryType enum value HomeDirectoryTypePath = "PATH" @@ -5316,6 +5925,14 @@ const ( HomeDirectoryTypeLogical = "LOGICAL" ) +// HomeDirectoryType_Values returns all elements of the HomeDirectoryType enum +func HomeDirectoryType_Values() []string { + return []string{ + HomeDirectoryTypePath, + HomeDirectoryTypeLogical, + } +} + // Returns information related to the type of user authentication that is in // use for a file transfer protocol-enabled server's users. For SERVICE_MANAGED // authentication, the Secure Shell (SSH) public keys are stored with a user @@ -5330,6 +5947,14 @@ const ( IdentityProviderTypeApiGateway = "API_GATEWAY" ) +// IdentityProviderType_Values returns all elements of the IdentityProviderType enum +func IdentityProviderType_Values() []string { + return []string{ + IdentityProviderTypeServiceManaged, + IdentityProviderTypeApiGateway, + } +} + const ( // ProtocolSftp is a Protocol enum value ProtocolSftp = "SFTP" @@ -5341,6 +5966,15 @@ const ( ProtocolFtps = "FTPS" ) +// Protocol_Values returns all elements of the Protocol enum +func Protocol_Values() []string { + return []string{ + ProtocolSftp, + ProtocolFtp, + ProtocolFtps, + } +} + // Describes the condition of a file transfer protocol-enabled server with respect // to its ability to perform file operations. There are six possible states: // OFFLINE, ONLINE, STARTING, STOPPING, START_FAILED, and STOP_FAILED. @@ -5370,3 +6004,15 @@ const ( // StateStopFailed is a State enum value StateStopFailed = "STOP_FAILED" ) + +// State_Values returns all elements of the State enum +func State_Values() []string { + return []string{ + StateOffline, + StateOnline, + StateStarting, + StateStopping, + StateStartFailed, + StateStopFailed, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/transfer/doc.go b/vendor/github.com/aws/aws-sdk-go/service/transfer/doc.go index 407175dd222..fcbf894a252 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/transfer/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/transfer/doc.go @@ -4,8 +4,8 @@ // requests to AWS Transfer Family. // // AWS Transfer Family is a fully managed service that enables the transfer -// of files over the the File Transfer Protocol (FTP), File Transfer Protocol -// over SSL (FTPS), or Secure Shell (SSH) File Transfer Protocol (SFTP) directly +// of files over the File Transfer Protocol (FTP), File Transfer Protocol over +// SSL (FTPS), or Secure Shell (SSH) File Transfer Protocol (SFTP) directly // into and out of Amazon Simple Storage Service (Amazon S3). AWS helps you // seamlessly migrate your file transfer workflows to AWS Transfer Family by // integrating with existing authentication systems, and providing DNS routing 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 8abf0df8933..bf68bfcee25 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 @@ -23047,6 +23047,14 @@ const ( ChangeActionDelete = "DELETE" ) +// ChangeAction_Values returns all elements of the ChangeAction enum +func ChangeAction_Values() []string { + return []string{ + ChangeActionInsert, + ChangeActionDelete, + } +} + const ( // ChangeTokenStatusProvisioned is a ChangeTokenStatus enum value ChangeTokenStatusProvisioned = "PROVISIONED" @@ -23058,6 +23066,15 @@ const ( ChangeTokenStatusInsync = "INSYNC" ) +// ChangeTokenStatus_Values returns all elements of the ChangeTokenStatus enum +func ChangeTokenStatus_Values() []string { + return []string{ + ChangeTokenStatusProvisioned, + ChangeTokenStatusPending, + ChangeTokenStatusInsync, + } +} + const ( // ComparisonOperatorEq is a ComparisonOperator enum value ComparisonOperatorEq = "EQ" @@ -23078,11 +23095,30 @@ const ( ComparisonOperatorGt = "GT" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorEq, + ComparisonOperatorNe, + ComparisonOperatorLe, + ComparisonOperatorLt, + ComparisonOperatorGe, + ComparisonOperatorGt, + } +} + const ( // GeoMatchConstraintTypeCountry is a GeoMatchConstraintType enum value GeoMatchConstraintTypeCountry = "Country" ) +// GeoMatchConstraintType_Values returns all elements of the GeoMatchConstraintType enum +func GeoMatchConstraintType_Values() []string { + return []string{ + GeoMatchConstraintTypeCountry, + } +} + const ( // GeoMatchConstraintValueAf is a GeoMatchConstraintValue enum value GeoMatchConstraintValueAf = "AF" @@ -23832,6 +23868,261 @@ const ( GeoMatchConstraintValueZw = "ZW" ) +// GeoMatchConstraintValue_Values returns all elements of the GeoMatchConstraintValue enum +func GeoMatchConstraintValue_Values() []string { + return []string{ + GeoMatchConstraintValueAf, + GeoMatchConstraintValueAx, + GeoMatchConstraintValueAl, + GeoMatchConstraintValueDz, + GeoMatchConstraintValueAs, + GeoMatchConstraintValueAd, + GeoMatchConstraintValueAo, + GeoMatchConstraintValueAi, + GeoMatchConstraintValueAq, + GeoMatchConstraintValueAg, + GeoMatchConstraintValueAr, + GeoMatchConstraintValueAm, + GeoMatchConstraintValueAw, + GeoMatchConstraintValueAu, + GeoMatchConstraintValueAt, + GeoMatchConstraintValueAz, + GeoMatchConstraintValueBs, + GeoMatchConstraintValueBh, + GeoMatchConstraintValueBd, + GeoMatchConstraintValueBb, + GeoMatchConstraintValueBy, + GeoMatchConstraintValueBe, + GeoMatchConstraintValueBz, + GeoMatchConstraintValueBj, + GeoMatchConstraintValueBm, + GeoMatchConstraintValueBt, + GeoMatchConstraintValueBo, + GeoMatchConstraintValueBq, + GeoMatchConstraintValueBa, + GeoMatchConstraintValueBw, + GeoMatchConstraintValueBv, + GeoMatchConstraintValueBr, + GeoMatchConstraintValueIo, + GeoMatchConstraintValueBn, + GeoMatchConstraintValueBg, + GeoMatchConstraintValueBf, + GeoMatchConstraintValueBi, + GeoMatchConstraintValueKh, + GeoMatchConstraintValueCm, + GeoMatchConstraintValueCa, + GeoMatchConstraintValueCv, + GeoMatchConstraintValueKy, + GeoMatchConstraintValueCf, + GeoMatchConstraintValueTd, + GeoMatchConstraintValueCl, + GeoMatchConstraintValueCn, + GeoMatchConstraintValueCx, + GeoMatchConstraintValueCc, + GeoMatchConstraintValueCo, + GeoMatchConstraintValueKm, + GeoMatchConstraintValueCg, + GeoMatchConstraintValueCd, + GeoMatchConstraintValueCk, + GeoMatchConstraintValueCr, + GeoMatchConstraintValueCi, + GeoMatchConstraintValueHr, + GeoMatchConstraintValueCu, + GeoMatchConstraintValueCw, + GeoMatchConstraintValueCy, + GeoMatchConstraintValueCz, + GeoMatchConstraintValueDk, + GeoMatchConstraintValueDj, + GeoMatchConstraintValueDm, + GeoMatchConstraintValueDo, + GeoMatchConstraintValueEc, + GeoMatchConstraintValueEg, + GeoMatchConstraintValueSv, + GeoMatchConstraintValueGq, + GeoMatchConstraintValueEr, + GeoMatchConstraintValueEe, + GeoMatchConstraintValueEt, + GeoMatchConstraintValueFk, + GeoMatchConstraintValueFo, + GeoMatchConstraintValueFj, + GeoMatchConstraintValueFi, + GeoMatchConstraintValueFr, + GeoMatchConstraintValueGf, + GeoMatchConstraintValuePf, + GeoMatchConstraintValueTf, + GeoMatchConstraintValueGa, + GeoMatchConstraintValueGm, + GeoMatchConstraintValueGe, + GeoMatchConstraintValueDe, + GeoMatchConstraintValueGh, + GeoMatchConstraintValueGi, + GeoMatchConstraintValueGr, + GeoMatchConstraintValueGl, + GeoMatchConstraintValueGd, + GeoMatchConstraintValueGp, + GeoMatchConstraintValueGu, + GeoMatchConstraintValueGt, + GeoMatchConstraintValueGg, + GeoMatchConstraintValueGn, + GeoMatchConstraintValueGw, + GeoMatchConstraintValueGy, + GeoMatchConstraintValueHt, + GeoMatchConstraintValueHm, + GeoMatchConstraintValueVa, + GeoMatchConstraintValueHn, + GeoMatchConstraintValueHk, + GeoMatchConstraintValueHu, + GeoMatchConstraintValueIs, + GeoMatchConstraintValueIn, + GeoMatchConstraintValueId, + GeoMatchConstraintValueIr, + GeoMatchConstraintValueIq, + GeoMatchConstraintValueIe, + GeoMatchConstraintValueIm, + GeoMatchConstraintValueIl, + GeoMatchConstraintValueIt, + GeoMatchConstraintValueJm, + GeoMatchConstraintValueJp, + GeoMatchConstraintValueJe, + GeoMatchConstraintValueJo, + GeoMatchConstraintValueKz, + GeoMatchConstraintValueKe, + GeoMatchConstraintValueKi, + GeoMatchConstraintValueKp, + GeoMatchConstraintValueKr, + GeoMatchConstraintValueKw, + GeoMatchConstraintValueKg, + GeoMatchConstraintValueLa, + GeoMatchConstraintValueLv, + GeoMatchConstraintValueLb, + GeoMatchConstraintValueLs, + GeoMatchConstraintValueLr, + GeoMatchConstraintValueLy, + GeoMatchConstraintValueLi, + GeoMatchConstraintValueLt, + GeoMatchConstraintValueLu, + GeoMatchConstraintValueMo, + GeoMatchConstraintValueMk, + GeoMatchConstraintValueMg, + GeoMatchConstraintValueMw, + GeoMatchConstraintValueMy, + GeoMatchConstraintValueMv, + GeoMatchConstraintValueMl, + GeoMatchConstraintValueMt, + GeoMatchConstraintValueMh, + GeoMatchConstraintValueMq, + GeoMatchConstraintValueMr, + GeoMatchConstraintValueMu, + GeoMatchConstraintValueYt, + GeoMatchConstraintValueMx, + GeoMatchConstraintValueFm, + GeoMatchConstraintValueMd, + GeoMatchConstraintValueMc, + GeoMatchConstraintValueMn, + GeoMatchConstraintValueMe, + GeoMatchConstraintValueMs, + GeoMatchConstraintValueMa, + GeoMatchConstraintValueMz, + GeoMatchConstraintValueMm, + GeoMatchConstraintValueNa, + GeoMatchConstraintValueNr, + GeoMatchConstraintValueNp, + GeoMatchConstraintValueNl, + GeoMatchConstraintValueNc, + GeoMatchConstraintValueNz, + GeoMatchConstraintValueNi, + GeoMatchConstraintValueNe, + GeoMatchConstraintValueNg, + GeoMatchConstraintValueNu, + GeoMatchConstraintValueNf, + GeoMatchConstraintValueMp, + GeoMatchConstraintValueNo, + GeoMatchConstraintValueOm, + GeoMatchConstraintValuePk, + GeoMatchConstraintValuePw, + GeoMatchConstraintValuePs, + GeoMatchConstraintValuePa, + GeoMatchConstraintValuePg, + GeoMatchConstraintValuePy, + GeoMatchConstraintValuePe, + GeoMatchConstraintValuePh, + GeoMatchConstraintValuePn, + GeoMatchConstraintValuePl, + GeoMatchConstraintValuePt, + GeoMatchConstraintValuePr, + GeoMatchConstraintValueQa, + GeoMatchConstraintValueRe, + GeoMatchConstraintValueRo, + GeoMatchConstraintValueRu, + GeoMatchConstraintValueRw, + GeoMatchConstraintValueBl, + GeoMatchConstraintValueSh, + GeoMatchConstraintValueKn, + GeoMatchConstraintValueLc, + GeoMatchConstraintValueMf, + GeoMatchConstraintValuePm, + GeoMatchConstraintValueVc, + GeoMatchConstraintValueWs, + GeoMatchConstraintValueSm, + GeoMatchConstraintValueSt, + GeoMatchConstraintValueSa, + GeoMatchConstraintValueSn, + GeoMatchConstraintValueRs, + GeoMatchConstraintValueSc, + GeoMatchConstraintValueSl, + GeoMatchConstraintValueSg, + GeoMatchConstraintValueSx, + GeoMatchConstraintValueSk, + GeoMatchConstraintValueSi, + GeoMatchConstraintValueSb, + GeoMatchConstraintValueSo, + GeoMatchConstraintValueZa, + GeoMatchConstraintValueGs, + GeoMatchConstraintValueSs, + GeoMatchConstraintValueEs, + GeoMatchConstraintValueLk, + GeoMatchConstraintValueSd, + GeoMatchConstraintValueSr, + GeoMatchConstraintValueSj, + GeoMatchConstraintValueSz, + GeoMatchConstraintValueSe, + GeoMatchConstraintValueCh, + GeoMatchConstraintValueSy, + GeoMatchConstraintValueTw, + GeoMatchConstraintValueTj, + GeoMatchConstraintValueTz, + GeoMatchConstraintValueTh, + GeoMatchConstraintValueTl, + GeoMatchConstraintValueTg, + GeoMatchConstraintValueTk, + GeoMatchConstraintValueTo, + GeoMatchConstraintValueTt, + GeoMatchConstraintValueTn, + GeoMatchConstraintValueTr, + GeoMatchConstraintValueTm, + GeoMatchConstraintValueTc, + GeoMatchConstraintValueTv, + GeoMatchConstraintValueUg, + GeoMatchConstraintValueUa, + GeoMatchConstraintValueAe, + GeoMatchConstraintValueGb, + GeoMatchConstraintValueUs, + GeoMatchConstraintValueUm, + GeoMatchConstraintValueUy, + GeoMatchConstraintValueUz, + GeoMatchConstraintValueVu, + GeoMatchConstraintValueVe, + GeoMatchConstraintValueVn, + GeoMatchConstraintValueVg, + GeoMatchConstraintValueVi, + GeoMatchConstraintValueWf, + GeoMatchConstraintValueEh, + GeoMatchConstraintValueYe, + GeoMatchConstraintValueZm, + GeoMatchConstraintValueZw, + } +} + const ( // IPSetDescriptorTypeIpv4 is a IPSetDescriptorType enum value IPSetDescriptorTypeIpv4 = "IPV4" @@ -23840,6 +24131,14 @@ const ( IPSetDescriptorTypeIpv6 = "IPV6" ) +// IPSetDescriptorType_Values returns all elements of the IPSetDescriptorType enum +func IPSetDescriptorType_Values() []string { + return []string{ + IPSetDescriptorTypeIpv4, + IPSetDescriptorTypeIpv6, + } +} + const ( // MatchFieldTypeUri is a MatchFieldType enum value MatchFieldTypeUri = "URI" @@ -23863,6 +24162,19 @@ const ( MatchFieldTypeAllQueryArgs = "ALL_QUERY_ARGS" ) +// MatchFieldType_Values returns all elements of the MatchFieldType enum +func MatchFieldType_Values() []string { + return []string{ + MatchFieldTypeUri, + MatchFieldTypeQueryString, + MatchFieldTypeHeader, + MatchFieldTypeMethod, + MatchFieldTypeBody, + MatchFieldTypeSingleQueryArg, + MatchFieldTypeAllQueryArgs, + } +} + const ( // MigrationErrorTypeEntityNotSupported is a MigrationErrorType enum value MigrationErrorTypeEntityNotSupported = "ENTITY_NOT_SUPPORTED" @@ -23886,6 +24198,19 @@ const ( MigrationErrorTypeS3InternalError = "S3_INTERNAL_ERROR" ) +// MigrationErrorType_Values returns all elements of the MigrationErrorType enum +func MigrationErrorType_Values() []string { + return []string{ + MigrationErrorTypeEntityNotSupported, + MigrationErrorTypeEntityNotFound, + MigrationErrorTypeS3BucketNoPermission, + MigrationErrorTypeS3BucketNotAccessible, + MigrationErrorTypeS3BucketNotFound, + MigrationErrorTypeS3BucketInvalidRegion, + MigrationErrorTypeS3InternalError, + } +} + const ( // ParameterExceptionFieldChangeAction is a ParameterExceptionField enum value ParameterExceptionFieldChangeAction = "CHANGE_ACTION" @@ -23942,6 +24267,30 @@ const ( ParameterExceptionFieldTagKeys = "TAG_KEYS" ) +// ParameterExceptionField_Values returns all elements of the ParameterExceptionField enum +func ParameterExceptionField_Values() []string { + return []string{ + ParameterExceptionFieldChangeAction, + ParameterExceptionFieldWafAction, + ParameterExceptionFieldWafOverrideAction, + ParameterExceptionFieldPredicateType, + ParameterExceptionFieldIpsetType, + ParameterExceptionFieldByteMatchFieldType, + ParameterExceptionFieldSqlInjectionMatchFieldType, + ParameterExceptionFieldByteMatchTextTransformation, + ParameterExceptionFieldByteMatchPositionalConstraint, + ParameterExceptionFieldSizeConstraintComparisonOperator, + ParameterExceptionFieldGeoMatchLocationType, + ParameterExceptionFieldGeoMatchLocationValue, + ParameterExceptionFieldRateKey, + ParameterExceptionFieldRuleType, + ParameterExceptionFieldNextMarker, + ParameterExceptionFieldResourceArn, + ParameterExceptionFieldTags, + ParameterExceptionFieldTagKeys, + } +} + const ( // ParameterExceptionReasonInvalidOption is a ParameterExceptionReason enum value ParameterExceptionReasonInvalidOption = "INVALID_OPTION" @@ -23956,6 +24305,16 @@ const ( ParameterExceptionReasonInvalidTagKey = "INVALID_TAG_KEY" ) +// ParameterExceptionReason_Values returns all elements of the ParameterExceptionReason enum +func ParameterExceptionReason_Values() []string { + return []string{ + ParameterExceptionReasonInvalidOption, + ParameterExceptionReasonIllegalCombination, + ParameterExceptionReasonIllegalArgument, + ParameterExceptionReasonInvalidTagKey, + } +} + const ( // PositionalConstraintExactly is a PositionalConstraint enum value PositionalConstraintExactly = "EXACTLY" @@ -23973,6 +24332,17 @@ const ( PositionalConstraintContainsWord = "CONTAINS_WORD" ) +// PositionalConstraint_Values returns all elements of the PositionalConstraint enum +func PositionalConstraint_Values() []string { + return []string{ + PositionalConstraintExactly, + PositionalConstraintStartsWith, + PositionalConstraintEndsWith, + PositionalConstraintContains, + PositionalConstraintContainsWord, + } +} + const ( // PredicateTypeIpmatch is a PredicateType enum value PredicateTypeIpmatch = "IPMatch" @@ -23996,11 +24366,31 @@ const ( PredicateTypeRegexMatch = "RegexMatch" ) +// PredicateType_Values returns all elements of the PredicateType enum +func PredicateType_Values() []string { + return []string{ + PredicateTypeIpmatch, + PredicateTypeByteMatch, + PredicateTypeSqlInjectionMatch, + PredicateTypeGeoMatch, + PredicateTypeSizeConstraint, + PredicateTypeXssMatch, + PredicateTypeRegexMatch, + } +} + const ( // RateKeyIp is a RateKey enum value RateKeyIp = "IP" ) +// RateKey_Values returns all elements of the RateKey enum +func RateKey_Values() []string { + return []string{ + RateKeyIp, + } +} + const ( // TextTransformationNone is a TextTransformation enum value TextTransformationNone = "NONE" @@ -24021,6 +24411,18 @@ const ( TextTransformationUrlDecode = "URL_DECODE" ) +// TextTransformation_Values returns all elements of the TextTransformation enum +func TextTransformation_Values() []string { + return []string{ + TextTransformationNone, + TextTransformationCompressWhiteSpace, + TextTransformationHtmlEntityDecode, + TextTransformationLowercase, + TextTransformationCmdLine, + TextTransformationUrlDecode, + } +} + const ( // WafActionTypeBlock is a WafActionType enum value WafActionTypeBlock = "BLOCK" @@ -24032,6 +24434,15 @@ const ( WafActionTypeCount = "COUNT" ) +// WafActionType_Values returns all elements of the WafActionType enum +func WafActionType_Values() []string { + return []string{ + WafActionTypeBlock, + WafActionTypeAllow, + WafActionTypeCount, + } +} + const ( // WafOverrideActionTypeNone is a WafOverrideActionType enum value WafOverrideActionTypeNone = "NONE" @@ -24040,6 +24451,14 @@ const ( WafOverrideActionTypeCount = "COUNT" ) +// WafOverrideActionType_Values returns all elements of the WafOverrideActionType enum +func WafOverrideActionType_Values() []string { + return []string{ + WafOverrideActionTypeNone, + WafOverrideActionTypeCount, + } +} + const ( // WafRuleTypeRegular is a WafRuleType enum value WafRuleTypeRegular = "REGULAR" @@ -24050,3 +24469,12 @@ const ( // WafRuleTypeGroup is a WafRuleType enum value WafRuleTypeGroup = "GROUP" ) + +// WafRuleType_Values returns all elements of the WafRuleType enum +func WafRuleType_Values() []string { + return []string{ + WafRuleTypeRegular, + WafRuleTypeRateBased, + WafRuleTypeGroup, + } +} 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 index 81b86a223f5..0d42f296326 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/wafregional/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/wafregional/api.go @@ -12338,6 +12338,14 @@ const ( ChangeActionDelete = "DELETE" ) +// ChangeAction_Values returns all elements of the ChangeAction enum +func ChangeAction_Values() []string { + return []string{ + ChangeActionInsert, + ChangeActionDelete, + } +} + const ( // ChangeTokenStatusProvisioned is a ChangeTokenStatus enum value ChangeTokenStatusProvisioned = "PROVISIONED" @@ -12349,6 +12357,15 @@ const ( ChangeTokenStatusInsync = "INSYNC" ) +// ChangeTokenStatus_Values returns all elements of the ChangeTokenStatus enum +func ChangeTokenStatus_Values() []string { + return []string{ + ChangeTokenStatusProvisioned, + ChangeTokenStatusPending, + ChangeTokenStatusInsync, + } +} + const ( // ComparisonOperatorEq is a ComparisonOperator enum value ComparisonOperatorEq = "EQ" @@ -12369,11 +12386,30 @@ const ( ComparisonOperatorGt = "GT" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorEq, + ComparisonOperatorNe, + ComparisonOperatorLe, + ComparisonOperatorLt, + ComparisonOperatorGe, + ComparisonOperatorGt, + } +} + const ( // GeoMatchConstraintTypeCountry is a GeoMatchConstraintType enum value GeoMatchConstraintTypeCountry = "Country" ) +// GeoMatchConstraintType_Values returns all elements of the GeoMatchConstraintType enum +func GeoMatchConstraintType_Values() []string { + return []string{ + GeoMatchConstraintTypeCountry, + } +} + const ( // GeoMatchConstraintValueAf is a GeoMatchConstraintValue enum value GeoMatchConstraintValueAf = "AF" @@ -13123,6 +13159,261 @@ const ( GeoMatchConstraintValueZw = "ZW" ) +// GeoMatchConstraintValue_Values returns all elements of the GeoMatchConstraintValue enum +func GeoMatchConstraintValue_Values() []string { + return []string{ + GeoMatchConstraintValueAf, + GeoMatchConstraintValueAx, + GeoMatchConstraintValueAl, + GeoMatchConstraintValueDz, + GeoMatchConstraintValueAs, + GeoMatchConstraintValueAd, + GeoMatchConstraintValueAo, + GeoMatchConstraintValueAi, + GeoMatchConstraintValueAq, + GeoMatchConstraintValueAg, + GeoMatchConstraintValueAr, + GeoMatchConstraintValueAm, + GeoMatchConstraintValueAw, + GeoMatchConstraintValueAu, + GeoMatchConstraintValueAt, + GeoMatchConstraintValueAz, + GeoMatchConstraintValueBs, + GeoMatchConstraintValueBh, + GeoMatchConstraintValueBd, + GeoMatchConstraintValueBb, + GeoMatchConstraintValueBy, + GeoMatchConstraintValueBe, + GeoMatchConstraintValueBz, + GeoMatchConstraintValueBj, + GeoMatchConstraintValueBm, + GeoMatchConstraintValueBt, + GeoMatchConstraintValueBo, + GeoMatchConstraintValueBq, + GeoMatchConstraintValueBa, + GeoMatchConstraintValueBw, + GeoMatchConstraintValueBv, + GeoMatchConstraintValueBr, + GeoMatchConstraintValueIo, + GeoMatchConstraintValueBn, + GeoMatchConstraintValueBg, + GeoMatchConstraintValueBf, + GeoMatchConstraintValueBi, + GeoMatchConstraintValueKh, + GeoMatchConstraintValueCm, + GeoMatchConstraintValueCa, + GeoMatchConstraintValueCv, + GeoMatchConstraintValueKy, + GeoMatchConstraintValueCf, + GeoMatchConstraintValueTd, + GeoMatchConstraintValueCl, + GeoMatchConstraintValueCn, + GeoMatchConstraintValueCx, + GeoMatchConstraintValueCc, + GeoMatchConstraintValueCo, + GeoMatchConstraintValueKm, + GeoMatchConstraintValueCg, + GeoMatchConstraintValueCd, + GeoMatchConstraintValueCk, + GeoMatchConstraintValueCr, + GeoMatchConstraintValueCi, + GeoMatchConstraintValueHr, + GeoMatchConstraintValueCu, + GeoMatchConstraintValueCw, + GeoMatchConstraintValueCy, + GeoMatchConstraintValueCz, + GeoMatchConstraintValueDk, + GeoMatchConstraintValueDj, + GeoMatchConstraintValueDm, + GeoMatchConstraintValueDo, + GeoMatchConstraintValueEc, + GeoMatchConstraintValueEg, + GeoMatchConstraintValueSv, + GeoMatchConstraintValueGq, + GeoMatchConstraintValueEr, + GeoMatchConstraintValueEe, + GeoMatchConstraintValueEt, + GeoMatchConstraintValueFk, + GeoMatchConstraintValueFo, + GeoMatchConstraintValueFj, + GeoMatchConstraintValueFi, + GeoMatchConstraintValueFr, + GeoMatchConstraintValueGf, + GeoMatchConstraintValuePf, + GeoMatchConstraintValueTf, + GeoMatchConstraintValueGa, + GeoMatchConstraintValueGm, + GeoMatchConstraintValueGe, + GeoMatchConstraintValueDe, + GeoMatchConstraintValueGh, + GeoMatchConstraintValueGi, + GeoMatchConstraintValueGr, + GeoMatchConstraintValueGl, + GeoMatchConstraintValueGd, + GeoMatchConstraintValueGp, + GeoMatchConstraintValueGu, + GeoMatchConstraintValueGt, + GeoMatchConstraintValueGg, + GeoMatchConstraintValueGn, + GeoMatchConstraintValueGw, + GeoMatchConstraintValueGy, + GeoMatchConstraintValueHt, + GeoMatchConstraintValueHm, + GeoMatchConstraintValueVa, + GeoMatchConstraintValueHn, + GeoMatchConstraintValueHk, + GeoMatchConstraintValueHu, + GeoMatchConstraintValueIs, + GeoMatchConstraintValueIn, + GeoMatchConstraintValueId, + GeoMatchConstraintValueIr, + GeoMatchConstraintValueIq, + GeoMatchConstraintValueIe, + GeoMatchConstraintValueIm, + GeoMatchConstraintValueIl, + GeoMatchConstraintValueIt, + GeoMatchConstraintValueJm, + GeoMatchConstraintValueJp, + GeoMatchConstraintValueJe, + GeoMatchConstraintValueJo, + GeoMatchConstraintValueKz, + GeoMatchConstraintValueKe, + GeoMatchConstraintValueKi, + GeoMatchConstraintValueKp, + GeoMatchConstraintValueKr, + GeoMatchConstraintValueKw, + GeoMatchConstraintValueKg, + GeoMatchConstraintValueLa, + GeoMatchConstraintValueLv, + GeoMatchConstraintValueLb, + GeoMatchConstraintValueLs, + GeoMatchConstraintValueLr, + GeoMatchConstraintValueLy, + GeoMatchConstraintValueLi, + GeoMatchConstraintValueLt, + GeoMatchConstraintValueLu, + GeoMatchConstraintValueMo, + GeoMatchConstraintValueMk, + GeoMatchConstraintValueMg, + GeoMatchConstraintValueMw, + GeoMatchConstraintValueMy, + GeoMatchConstraintValueMv, + GeoMatchConstraintValueMl, + GeoMatchConstraintValueMt, + GeoMatchConstraintValueMh, + GeoMatchConstraintValueMq, + GeoMatchConstraintValueMr, + GeoMatchConstraintValueMu, + GeoMatchConstraintValueYt, + GeoMatchConstraintValueMx, + GeoMatchConstraintValueFm, + GeoMatchConstraintValueMd, + GeoMatchConstraintValueMc, + GeoMatchConstraintValueMn, + GeoMatchConstraintValueMe, + GeoMatchConstraintValueMs, + GeoMatchConstraintValueMa, + GeoMatchConstraintValueMz, + GeoMatchConstraintValueMm, + GeoMatchConstraintValueNa, + GeoMatchConstraintValueNr, + GeoMatchConstraintValueNp, + GeoMatchConstraintValueNl, + GeoMatchConstraintValueNc, + GeoMatchConstraintValueNz, + GeoMatchConstraintValueNi, + GeoMatchConstraintValueNe, + GeoMatchConstraintValueNg, + GeoMatchConstraintValueNu, + GeoMatchConstraintValueNf, + GeoMatchConstraintValueMp, + GeoMatchConstraintValueNo, + GeoMatchConstraintValueOm, + GeoMatchConstraintValuePk, + GeoMatchConstraintValuePw, + GeoMatchConstraintValuePs, + GeoMatchConstraintValuePa, + GeoMatchConstraintValuePg, + GeoMatchConstraintValuePy, + GeoMatchConstraintValuePe, + GeoMatchConstraintValuePh, + GeoMatchConstraintValuePn, + GeoMatchConstraintValuePl, + GeoMatchConstraintValuePt, + GeoMatchConstraintValuePr, + GeoMatchConstraintValueQa, + GeoMatchConstraintValueRe, + GeoMatchConstraintValueRo, + GeoMatchConstraintValueRu, + GeoMatchConstraintValueRw, + GeoMatchConstraintValueBl, + GeoMatchConstraintValueSh, + GeoMatchConstraintValueKn, + GeoMatchConstraintValueLc, + GeoMatchConstraintValueMf, + GeoMatchConstraintValuePm, + GeoMatchConstraintValueVc, + GeoMatchConstraintValueWs, + GeoMatchConstraintValueSm, + GeoMatchConstraintValueSt, + GeoMatchConstraintValueSa, + GeoMatchConstraintValueSn, + GeoMatchConstraintValueRs, + GeoMatchConstraintValueSc, + GeoMatchConstraintValueSl, + GeoMatchConstraintValueSg, + GeoMatchConstraintValueSx, + GeoMatchConstraintValueSk, + GeoMatchConstraintValueSi, + GeoMatchConstraintValueSb, + GeoMatchConstraintValueSo, + GeoMatchConstraintValueZa, + GeoMatchConstraintValueGs, + GeoMatchConstraintValueSs, + GeoMatchConstraintValueEs, + GeoMatchConstraintValueLk, + GeoMatchConstraintValueSd, + GeoMatchConstraintValueSr, + GeoMatchConstraintValueSj, + GeoMatchConstraintValueSz, + GeoMatchConstraintValueSe, + GeoMatchConstraintValueCh, + GeoMatchConstraintValueSy, + GeoMatchConstraintValueTw, + GeoMatchConstraintValueTj, + GeoMatchConstraintValueTz, + GeoMatchConstraintValueTh, + GeoMatchConstraintValueTl, + GeoMatchConstraintValueTg, + GeoMatchConstraintValueTk, + GeoMatchConstraintValueTo, + GeoMatchConstraintValueTt, + GeoMatchConstraintValueTn, + GeoMatchConstraintValueTr, + GeoMatchConstraintValueTm, + GeoMatchConstraintValueTc, + GeoMatchConstraintValueTv, + GeoMatchConstraintValueUg, + GeoMatchConstraintValueUa, + GeoMatchConstraintValueAe, + GeoMatchConstraintValueGb, + GeoMatchConstraintValueUs, + GeoMatchConstraintValueUm, + GeoMatchConstraintValueUy, + GeoMatchConstraintValueUz, + GeoMatchConstraintValueVu, + GeoMatchConstraintValueVe, + GeoMatchConstraintValueVn, + GeoMatchConstraintValueVg, + GeoMatchConstraintValueVi, + GeoMatchConstraintValueWf, + GeoMatchConstraintValueEh, + GeoMatchConstraintValueYe, + GeoMatchConstraintValueZm, + GeoMatchConstraintValueZw, + } +} + const ( // IPSetDescriptorTypeIpv4 is a IPSetDescriptorType enum value IPSetDescriptorTypeIpv4 = "IPV4" @@ -13131,6 +13422,14 @@ const ( IPSetDescriptorTypeIpv6 = "IPV6" ) +// IPSetDescriptorType_Values returns all elements of the IPSetDescriptorType enum +func IPSetDescriptorType_Values() []string { + return []string{ + IPSetDescriptorTypeIpv4, + IPSetDescriptorTypeIpv6, + } +} + const ( // MatchFieldTypeUri is a MatchFieldType enum value MatchFieldTypeUri = "URI" @@ -13154,6 +13453,19 @@ const ( MatchFieldTypeAllQueryArgs = "ALL_QUERY_ARGS" ) +// MatchFieldType_Values returns all elements of the MatchFieldType enum +func MatchFieldType_Values() []string { + return []string{ + MatchFieldTypeUri, + MatchFieldTypeQueryString, + MatchFieldTypeHeader, + MatchFieldTypeMethod, + MatchFieldTypeBody, + MatchFieldTypeSingleQueryArg, + MatchFieldTypeAllQueryArgs, + } +} + const ( // MigrationErrorTypeEntityNotSupported is a MigrationErrorType enum value MigrationErrorTypeEntityNotSupported = "ENTITY_NOT_SUPPORTED" @@ -13177,6 +13489,19 @@ const ( MigrationErrorTypeS3InternalError = "S3_INTERNAL_ERROR" ) +// MigrationErrorType_Values returns all elements of the MigrationErrorType enum +func MigrationErrorType_Values() []string { + return []string{ + MigrationErrorTypeEntityNotSupported, + MigrationErrorTypeEntityNotFound, + MigrationErrorTypeS3BucketNoPermission, + MigrationErrorTypeS3BucketNotAccessible, + MigrationErrorTypeS3BucketNotFound, + MigrationErrorTypeS3BucketInvalidRegion, + MigrationErrorTypeS3InternalError, + } +} + const ( // ParameterExceptionFieldChangeAction is a ParameterExceptionField enum value ParameterExceptionFieldChangeAction = "CHANGE_ACTION" @@ -13233,6 +13558,30 @@ const ( ParameterExceptionFieldTagKeys = "TAG_KEYS" ) +// ParameterExceptionField_Values returns all elements of the ParameterExceptionField enum +func ParameterExceptionField_Values() []string { + return []string{ + ParameterExceptionFieldChangeAction, + ParameterExceptionFieldWafAction, + ParameterExceptionFieldWafOverrideAction, + ParameterExceptionFieldPredicateType, + ParameterExceptionFieldIpsetType, + ParameterExceptionFieldByteMatchFieldType, + ParameterExceptionFieldSqlInjectionMatchFieldType, + ParameterExceptionFieldByteMatchTextTransformation, + ParameterExceptionFieldByteMatchPositionalConstraint, + ParameterExceptionFieldSizeConstraintComparisonOperator, + ParameterExceptionFieldGeoMatchLocationType, + ParameterExceptionFieldGeoMatchLocationValue, + ParameterExceptionFieldRateKey, + ParameterExceptionFieldRuleType, + ParameterExceptionFieldNextMarker, + ParameterExceptionFieldResourceArn, + ParameterExceptionFieldTags, + ParameterExceptionFieldTagKeys, + } +} + const ( // ParameterExceptionReasonInvalidOption is a ParameterExceptionReason enum value ParameterExceptionReasonInvalidOption = "INVALID_OPTION" @@ -13247,6 +13596,16 @@ const ( ParameterExceptionReasonInvalidTagKey = "INVALID_TAG_KEY" ) +// ParameterExceptionReason_Values returns all elements of the ParameterExceptionReason enum +func ParameterExceptionReason_Values() []string { + return []string{ + ParameterExceptionReasonInvalidOption, + ParameterExceptionReasonIllegalCombination, + ParameterExceptionReasonIllegalArgument, + ParameterExceptionReasonInvalidTagKey, + } +} + const ( // PositionalConstraintExactly is a PositionalConstraint enum value PositionalConstraintExactly = "EXACTLY" @@ -13264,6 +13623,17 @@ const ( PositionalConstraintContainsWord = "CONTAINS_WORD" ) +// PositionalConstraint_Values returns all elements of the PositionalConstraint enum +func PositionalConstraint_Values() []string { + return []string{ + PositionalConstraintExactly, + PositionalConstraintStartsWith, + PositionalConstraintEndsWith, + PositionalConstraintContains, + PositionalConstraintContainsWord, + } +} + const ( // PredicateTypeIpmatch is a PredicateType enum value PredicateTypeIpmatch = "IPMatch" @@ -13287,11 +13657,31 @@ const ( PredicateTypeRegexMatch = "RegexMatch" ) +// PredicateType_Values returns all elements of the PredicateType enum +func PredicateType_Values() []string { + return []string{ + PredicateTypeIpmatch, + PredicateTypeByteMatch, + PredicateTypeSqlInjectionMatch, + PredicateTypeGeoMatch, + PredicateTypeSizeConstraint, + PredicateTypeXssMatch, + PredicateTypeRegexMatch, + } +} + const ( // RateKeyIp is a RateKey enum value RateKeyIp = "IP" ) +// RateKey_Values returns all elements of the RateKey enum +func RateKey_Values() []string { + return []string{ + RateKeyIp, + } +} + const ( // ResourceTypeApplicationLoadBalancer is a ResourceType enum value ResourceTypeApplicationLoadBalancer = "APPLICATION_LOAD_BALANCER" @@ -13300,6 +13690,14 @@ const ( ResourceTypeApiGateway = "API_GATEWAY" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeApplicationLoadBalancer, + ResourceTypeApiGateway, + } +} + const ( // TextTransformationNone is a TextTransformation enum value TextTransformationNone = "NONE" @@ -13320,6 +13718,18 @@ const ( TextTransformationUrlDecode = "URL_DECODE" ) +// TextTransformation_Values returns all elements of the TextTransformation enum +func TextTransformation_Values() []string { + return []string{ + TextTransformationNone, + TextTransformationCompressWhiteSpace, + TextTransformationHtmlEntityDecode, + TextTransformationLowercase, + TextTransformationCmdLine, + TextTransformationUrlDecode, + } +} + const ( // WafActionTypeBlock is a WafActionType enum value WafActionTypeBlock = "BLOCK" @@ -13331,6 +13741,15 @@ const ( WafActionTypeCount = "COUNT" ) +// WafActionType_Values returns all elements of the WafActionType enum +func WafActionType_Values() []string { + return []string{ + WafActionTypeBlock, + WafActionTypeAllow, + WafActionTypeCount, + } +} + const ( // WafOverrideActionTypeNone is a WafOverrideActionType enum value WafOverrideActionTypeNone = "NONE" @@ -13339,6 +13758,14 @@ const ( WafOverrideActionTypeCount = "COUNT" ) +// WafOverrideActionType_Values returns all elements of the WafOverrideActionType enum +func WafOverrideActionType_Values() []string { + return []string{ + WafOverrideActionTypeNone, + WafOverrideActionTypeCount, + } +} + const ( // WafRuleTypeRegular is a WafRuleType enum value WafRuleTypeRegular = "REGULAR" @@ -13349,3 +13776,12 @@ const ( // WafRuleTypeGroup is a WafRuleType enum value WafRuleTypeGroup = "GROUP" ) + +// WafRuleType_Values returns all elements of the WafRuleType enum +func WafRuleType_Values() []string { + return []string{ + WafRuleTypeRegular, + WafRuleTypeRateBased, + WafRuleTypeGroup, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/wafv2/api.go b/vendor/github.com/aws/aws-sdk-go/service/wafv2/api.go index 68de2cffaa7..0a282e62bb2 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/wafv2/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/wafv2/api.go @@ -3509,7 +3509,15 @@ func (c *WAFV2) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req // 2019. For information, including how to migrate your AWS WAF resources from // the prior release, see the AWS WAF Developer Guide (https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html). // -// Retrieves the TagInfoForResource for the specified resource. +// Retrieves the TagInfoForResource for the specified resource. Tags are key:value +// pairs that you can use to categorize and manage your resources, for purposes +// like billing. For example, you might set the tag key to "customer" and the +// value to the customer name or ID. You can specify one or more tags to add +// to each AWS resource, up to 50 tags for a resource. +// +// You can tag the AWS resources that you manage through AWS WAF: web ACLs, +// rule groups, IP sets, and regex pattern sets. You can't manage or view tags +// through the AWS WAF console. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3738,6 +3746,9 @@ func (c *WAFV2) PutLoggingConfigurationRequest(input *PutLoggingConfigurationInp // operating. If you are capturing logs for Amazon CloudFront, always create // the firehose in US East (N. Virginia). // +// Give the data firehose a name that starts with the prefix aws-waf-logs-. +// For example, aws-waf-logs-us-east-2-analytics. +// // Do not create the data firehose using a Kinesis stream as your source. // // Associate that firehose to your web ACL using a PutLoggingConfiguration request. @@ -3798,6 +3809,12 @@ func (c *WAFV2) PutLoggingConfigurationRequest(input *PutLoggingConfigurationInp // * WAFInvalidOperationException // The operation isn't valid. // +// * WAFLimitsExceededException +// AWS WAF couldn’t perform the operation because you exceeded your resource +// limit. For example, the maximum number of WebACL objects that you can create +// for an AWS account. For more information, see Limits (https://docs.aws.amazon.com/waf/latest/developerguide/limits.html) +// in the AWS WAF Developer Guide. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/wafv2-2019-07-29/PutLoggingConfiguration func (c *WAFV2) PutLoggingConfiguration(input *PutLoggingConfigurationInput) (*PutLoggingConfigurationOutput, error) { req, out := c.PutLoggingConfigurationRequest(input) @@ -4002,10 +4019,14 @@ func (c *WAFV2) TagResourceRequest(input *TagResourceInput) (req *request.Reques // the prior release, see the AWS WAF Developer Guide (https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html). // // Associates tags with the specified AWS resource. Tags are key:value pairs -// that you can associate with AWS resources. For example, the tag key might -// be "customer" and the tag value might be "companyA." You can specify one -// or more tags to add to each container. You can add up to 50 tags to each -// AWS resource. +// that you can use to categorize and manage your resources, for purposes like +// billing. For example, you might set the tag key to "customer" and the value +// to the customer name or ID. You can specify one or more tags to add to each +// AWS resource, up to 50 tags for a resource. +// +// You can tag the AWS resources that you manage through AWS WAF: web ACLs, +// rule groups, IP sets, and regex pattern sets. You can't manage or view tags +// through the AWS WAF console. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -7183,6 +7204,88 @@ func (s *FirewallManagerStatement) SetRuleGroupReferenceStatement(v *RuleGroupRe return s } +// The configuration for inspecting IP addresses in an HTTP header that you +// specify, instead of using the IP address that's reported by the web request +// origin. Commonly, this is the X-Forwarded-For (XFF) header, but you can specify +// any header name. +// +// If the specified header isn't present in the request, AWS WAF doesn't apply +// the rule to the web request at all. +// +// This configuration is used for GeoMatchStatement and RateBasedStatement. +// For IPSetReferenceStatement, use IPSetForwardedIPConfig instead. +// +// AWS WAF only evaluates the first IP address found in the specified HTTP header. +type ForwardedIPConfig struct { + _ struct{} `type:"structure"` + + // The match status to assign to the web request if the request doesn't have + // a valid IP address in the specified position. + // + // If the specified header isn't present in the request, AWS WAF doesn't apply + // the rule to the web request at all. + // + // You can specify the following fallback behaviors: + // + // * MATCH - Treat the web request as matching the rule statement. AWS WAF + // applies the rule action to the request. + // + // * NO_MATCH - Treat the web request as not matching the rule statement. + // + // FallbackBehavior is a required field + FallbackBehavior *string `type:"string" required:"true" enum:"FallbackBehavior"` + + // The name of the HTTP header to use for the IP address. For example, to use + // the X-Forwarded-For (XFF) header, set this to X-Forwarded-For. + // + // If the specified header isn't present in the request, AWS WAF doesn't apply + // the rule to the web request at all. + // + // HeaderName is a required field + HeaderName *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s ForwardedIPConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ForwardedIPConfig) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ForwardedIPConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ForwardedIPConfig"} + if s.FallbackBehavior == nil { + invalidParams.Add(request.NewErrParamRequired("FallbackBehavior")) + } + if s.HeaderName == nil { + invalidParams.Add(request.NewErrParamRequired("HeaderName")) + } + if s.HeaderName != nil && len(*s.HeaderName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("HeaderName", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetFallbackBehavior sets the FallbackBehavior field's value. +func (s *ForwardedIPConfig) SetFallbackBehavior(v string) *ForwardedIPConfig { + s.FallbackBehavior = &v + return s +} + +// SetHeaderName sets the HeaderName field's value. +func (s *ForwardedIPConfig) SetHeaderName(v string) *ForwardedIPConfig { + s.HeaderName = &v + return s +} + // // This is the latest version of AWS WAF, named AWS WAFV2, released in November, // 2019. For information, including how to migrate your AWS WAF resources from @@ -7195,6 +7298,15 @@ type GeoMatchStatement struct { // An array of two-character country codes, for example, [ "US", "CN" ], from // the alpha-2 country ISO codes of the ISO 3166 international standard. CountryCodes []*string `min:"1" type:"list"` + + // The configuration for inspecting IP addresses in an HTTP header that you + // specify, instead of using the IP address that's reported by the web request + // origin. Commonly, this is the X-Forwarded-For (XFF) header, but you can specify + // any header name. + // + // If the specified header isn't present in the request, AWS WAF doesn't apply + // the rule to the web request at all. + ForwardedIPConfig *ForwardedIPConfig `type:"structure"` } // String returns the string representation @@ -7213,6 +7325,11 @@ func (s *GeoMatchStatement) Validate() error { if s.CountryCodes != nil && len(s.CountryCodes) < 1 { invalidParams.Add(request.NewErrParamMinLen("CountryCodes", 1)) } + if s.ForwardedIPConfig != nil { + if err := s.ForwardedIPConfig.Validate(); err != nil { + invalidParams.AddNested("ForwardedIPConfig", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -7226,6 +7343,12 @@ func (s *GeoMatchStatement) SetCountryCodes(v []*string) *GeoMatchStatement { return s } +// SetForwardedIPConfig sets the ForwardedIPConfig field's value. +func (s *GeoMatchStatement) SetForwardedIPConfig(v *ForwardedIPConfig) *GeoMatchStatement { + s.ForwardedIPConfig = v + return s +} + type GetIPSetInput struct { _ struct{} `type:"structure"` @@ -7920,9 +8043,10 @@ type GetSampledRequestsInput struct { Scope *string `type:"string" required:"true" enum:"Scope"` // The start date and time and the end date and time of the range for which - // you want GetSampledRequests to return a sample of requests. Specify the date - // and time in the following format: "2016-09-27T14:50Z". You can specify any - // time range in the previous three hours. + // you want GetSampledRequests to return a sample of requests. You must specify + // the times in Coordinated Universal Time (UTC) format. UTC format includes + // the special designator, Z. For example, "2016-09-27T14:50Z". You can specify + // any time range in the previous three hours. // // TimeWindow is a required field TimeWindow *TimeWindow `type:"structure" required:"true"` @@ -8028,7 +8152,8 @@ type GetSampledRequestsOutput struct { // Usually, TimeWindow is the time range that you specified in the GetSampledRequests // request. However, if your AWS resource received more than 5,000 requests // during the time range that you specified in the request, GetSampledRequests - // returns the time range for the first 5,000 requests. + // returns the time range for the first 5,000 requests. Times are in Coordinated + // Universal Time (UTC) format. TimeWindow *TimeWindow `type:"structure"` } @@ -8491,6 +8616,115 @@ func (s *IPSet) SetName(v string) *IPSet { return s } +// The configuration for inspecting IP addresses in an HTTP header that you +// specify, instead of using the IP address that's reported by the web request +// origin. Commonly, this is the X-Forwarded-For (XFF) header, but you can specify +// any header name. +// +// If the specified header isn't present in the request, AWS WAF doesn't apply +// the rule to the web request at all. +// +// This configuration is used only for IPSetReferenceStatement. For GeoMatchStatement +// and RateBasedStatement, use ForwardedIPConfig instead. +type IPSetForwardedIPConfig struct { + _ struct{} `type:"structure"` + + // The match status to assign to the web request if the request doesn't have + // a valid IP address in the specified position. + // + // If the specified header isn't present in the request, AWS WAF doesn't apply + // the rule to the web request at all. + // + // You can specify the following fallback behaviors: + // + // * MATCH - Treat the web request as matching the rule statement. AWS WAF + // applies the rule action to the request. + // + // * NO_MATCH - Treat the web request as not matching the rule statement. + // + // FallbackBehavior is a required field + FallbackBehavior *string `type:"string" required:"true" enum:"FallbackBehavior"` + + // The name of the HTTP header to use for the IP address. For example, to use + // the X-Forwarded-For (XFF) header, set this to X-Forwarded-For. + // + // If the specified header isn't present in the request, AWS WAF doesn't apply + // the rule to the web request at all. + // + // HeaderName is a required field + HeaderName *string `min:"1" type:"string" required:"true"` + + // The position in the header to search for the IP address. The header can contain + // IP addresses of the original client and also of proxies. For example, the + // header value could be 10.1.1.1, 127.0.0.0, 10.10.10.10 where the first IP + // address identifies the original client and the rest identify proxies that + // the request went through. + // + // The options for this setting are the following: + // + // * FIRST - Inspect the first IP address in the list of IP addresses in + // the header. This is usually the client's original IP. + // + // * LAST - Inspect the last IP address in the list of IP addresses in the + // header. + // + // * ANY - Inspect all IP addresses in the header for a match. If the header + // contains more than 10 IP addresses, AWS WAF inspects the last 10. + // + // Position is a required field + Position *string `type:"string" required:"true" enum:"ForwardedIPPosition"` +} + +// String returns the string representation +func (s IPSetForwardedIPConfig) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s IPSetForwardedIPConfig) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *IPSetForwardedIPConfig) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "IPSetForwardedIPConfig"} + if s.FallbackBehavior == nil { + invalidParams.Add(request.NewErrParamRequired("FallbackBehavior")) + } + if s.HeaderName == nil { + invalidParams.Add(request.NewErrParamRequired("HeaderName")) + } + if s.HeaderName != nil && len(*s.HeaderName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("HeaderName", 1)) + } + if s.Position == nil { + invalidParams.Add(request.NewErrParamRequired("Position")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetFallbackBehavior sets the FallbackBehavior field's value. +func (s *IPSetForwardedIPConfig) SetFallbackBehavior(v string) *IPSetForwardedIPConfig { + s.FallbackBehavior = &v + return s +} + +// SetHeaderName sets the HeaderName field's value. +func (s *IPSetForwardedIPConfig) SetHeaderName(v string) *IPSetForwardedIPConfig { + s.HeaderName = &v + return s +} + +// SetPosition sets the Position field's value. +func (s *IPSetForwardedIPConfig) SetPosition(v string) *IPSetForwardedIPConfig { + s.Position = &v + return s +} + // // This is the latest version of AWS WAF, named AWS WAFV2, released in November, // 2019. For information, including how to migrate your AWS WAF resources from @@ -8512,6 +8746,15 @@ type IPSetReferenceStatement struct { // // ARN is a required field ARN *string `min:"20" type:"string" required:"true"` + + // The configuration for inspecting IP addresses in an HTTP header that you + // specify, instead of using the IP address that's reported by the web request + // origin. Commonly, this is the X-Forwarded-For (XFF) header, but you can specify + // any header name. + // + // If the specified header isn't present in the request, AWS WAF doesn't apply + // the rule to the web request at all. + IPSetForwardedIPConfig *IPSetForwardedIPConfig `type:"structure"` } // String returns the string representation @@ -8533,6 +8776,11 @@ func (s *IPSetReferenceStatement) Validate() error { if s.ARN != nil && len(*s.ARN) < 20 { invalidParams.Add(request.NewErrParamMinLen("ARN", 20)) } + if s.IPSetForwardedIPConfig != nil { + if err := s.IPSetForwardedIPConfig.Validate(); err != nil { + invalidParams.AddNested("IPSetForwardedIPConfig", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -8546,6 +8794,12 @@ func (s *IPSetReferenceStatement) SetARN(v string) *IPSetReferenceStatement { return s } +// SetIPSetForwardedIPConfig sets the IPSetForwardedIPConfig field's value. +func (s *IPSetReferenceStatement) SetIPSetForwardedIPConfig(v *IPSetForwardedIPConfig) *IPSetReferenceStatement { + s.IPSetForwardedIPConfig = v + return s +} + // // This is the latest version of AWS WAF, named AWS WAFV2, released in November, // 2019. For information, including how to migrate your AWS WAF resources from @@ -9483,9 +9737,16 @@ type LoggingConfiguration struct { // LogDestinationConfigs is a required field LogDestinationConfigs []*string `min:"1" type:"list" required:"true"` + // Indicates whether the logging configuration was created by AWS Firewall Manager, + // as part of an AWS WAF policy configuration. If true, only Firewall Manager + // can modify or delete the configuration. + ManagedByFirewallManager *bool `type:"boolean"` + // The parts of the request that you want to keep out of the logs. For example, - // if you redact the cookie field, the cookie field in the firehose will be + // if you redact the HEADER field, the HEADER field in the firehose will be // xxx. + // + // You must use one of the following values: URI, QUERY_STRING, HEADER, or METHOD. RedactedFields []*FieldToMatch `type:"list"` // The Amazon Resource Name (ARN) of the web ACL that you want to associate @@ -9543,6 +9804,12 @@ func (s *LoggingConfiguration) SetLogDestinationConfigs(v []*string) *LoggingCon return s } +// SetManagedByFirewallManager sets the ManagedByFirewallManager field's value. +func (s *LoggingConfiguration) SetManagedByFirewallManager(v bool) *LoggingConfiguration { + s.ManagedByFirewallManager = &v + return s +} + // SetRedactedFields sets the RedactedFields field's value. func (s *LoggingConfiguration) SetRedactedFields(v []*FieldToMatch) *LoggingConfiguration { s.RedactedFields = v @@ -10135,14 +10402,32 @@ func (s QueryString) GoString() string { type RateBasedStatement struct { _ struct{} `type:"structure"` - // Setting that indicates how to aggregate the request counts. Currently, you - // must set this to IP. The request counts are aggregated on IP addresses. + // Setting that indicates how to aggregate the request counts. The options are + // the following: + // + // * IP - Aggregate the request counts on the IP address from the web request + // origin. + // + // * FORWARDED_IP - Aggregate the request counts on the first IP address + // in an HTTP header. If you use this, configure the ForwardedIPConfig, to + // specify the header to use. // // AggregateKeyType is a required field AggregateKeyType *string `type:"string" required:"true" enum:"RateBasedStatementAggregateKeyType"` + // The configuration for inspecting IP addresses in an HTTP header that you + // specify, instead of using the IP address that's reported by the web request + // origin. Commonly, this is the X-Forwarded-For (XFF) header, but you can specify + // any header name. + // + // If the specified header isn't present in the request, AWS WAF doesn't apply + // the rule to the web request at all. + // + // This is required if AggregateKeyType is set to FORWARDED_IP. + ForwardedIPConfig *ForwardedIPConfig `type:"structure"` + // The limit on requests per 5-minute period for a single originating IP address. - // If the statement includes a ScopDownStatement, this limit is applied only + // If the statement includes a ScopeDownStatement, this limit is applied only // to the requests that match the statement. // // Limit is a required field @@ -10176,6 +10461,11 @@ func (s *RateBasedStatement) Validate() error { if s.Limit != nil && *s.Limit < 100 { invalidParams.Add(request.NewErrParamMinValue("Limit", 100)) } + if s.ForwardedIPConfig != nil { + if err := s.ForwardedIPConfig.Validate(); err != nil { + invalidParams.AddNested("ForwardedIPConfig", err.(request.ErrInvalidParams)) + } + } if s.ScopeDownStatement != nil { if err := s.ScopeDownStatement.Validate(); err != nil { invalidParams.AddNested("ScopeDownStatement", err.(request.ErrInvalidParams)) @@ -10194,6 +10484,12 @@ func (s *RateBasedStatement) SetAggregateKeyType(v string) *RateBasedStatement { return s } +// SetForwardedIPConfig sets the ForwardedIPConfig field's value. +func (s *RateBasedStatement) SetForwardedIPConfig(v *ForwardedIPConfig) *RateBasedStatement { + s.ForwardedIPConfig = v + return s +} + // SetLimit sets the Limit field's value. func (s *RateBasedStatement) SetLimit(v int64) *RateBasedStatement { s.Limit = &v @@ -11083,7 +11379,7 @@ type SampledHTTPRequest struct { // The name of the Rule that the request matched. For managed rule groups, the // format for this name is ##. // For your own rule groups, the format for this name is #. If the rule is not in a rule group, the format is . + // name>. If the rule is not in a rule group, this field is absent. RuleNameWithinRuleGroup *string `min:"1" type:"string"` // The time at which AWS WAF received the request from your AWS resource, in @@ -11754,11 +12050,18 @@ func (s *Statement) SetXssMatchStatement(v *XssMatchStatement) *Statement { // 2019. For information, including how to migrate your AWS WAF resources from // the prior release, see the AWS WAF Developer Guide (https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html). // -// A collection of key:value pairs associated with an AWS resource. The key:value -// pair can be anything you define. Typically, the tag key represents a category -// (such as "environment") and the tag value represents a specific value within -// that category (such as "test," "development," or "production"). You can add -// up to 50 tags to each AWS resource. +// A tag associated with an AWS resource. Tags are key:value pairs that you +// can use to categorize and manage your resources, for purposes like billing +// or other management. Typically, the tag key represents a category, such as +// "environment", and the tag value represents a specific value within that +// category, such as "test," "development," or "production". Or you might set +// the tag key to "customer" and the value to the customer name or ID. You can +// specify one or more tags to add to each AWS resource, up to 50 tags for a +// resource. +// +// You can tag the AWS resources that you manage through AWS WAF: web ACLs, +// rule groups, IP sets, and regex pattern sets. You can't manage or view tags +// through the AWS WAF console. type Tag struct { _ struct{} `type:"structure"` @@ -11822,7 +12125,18 @@ func (s *Tag) SetValue(v string) *Tag { // 2019. For information, including how to migrate your AWS WAF resources from // the prior release, see the AWS WAF Developer Guide (https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html). // -// The collection of tagging definitions for an AWS resource. +// The collection of tagging definitions for an AWS resource. Tags are key:value +// pairs that you can use to categorize and manage your resources, for purposes +// like billing or other management. Typically, the tag key represents a category, +// such as "environment", and the tag value represents a specific value within +// that category, such as "test," "development," or "production". Or you might +// set the tag key to "customer" and the value to the customer name or ID. You +// can specify one or more tags to add to each AWS resource, up to 50 tags for +// a resource. +// +// You can tag the AWS resources that you manage through AWS WAF: web ACLs, +// rule groups, IP sets, and regex pattern sets. You can't manage or view tags +// through the AWS WAF console. type TagInfoForResource struct { _ struct{} `type:"structure"` @@ -12073,6 +12387,10 @@ func (s *TextTransformation) SetType(v string) *TextTransformation { // In a GetSampledRequests request, the StartTime and EndTime objects specify // the time range for which you want AWS WAF to return a sample of web requests. // +// You must specify the times in Coordinated Universal Time (UTC) format. UTC +// format includes the special designator, Z. For example, "2016-09-27T14:50Z". +// You can specify any time range in the previous three hours. +// // In a GetSampledRequests response, the StartTime and EndTime objects specify // the time range for which AWS WAF actually returned a sample of web requests. // AWS WAF gets the specified number of requests from among the first 5,000 @@ -12084,17 +12402,19 @@ type TimeWindow struct { _ struct{} `type:"structure"` // The end of the time range from which you want GetSampledRequests to return - // a sample of the requests that your AWS resource received. Specify the date - // and time in the following format: "2016-09-27T14:50Z". You can specify any - // time range in the previous three hours. + // a sample of the requests that your AWS resource received. You must specify + // the times in Coordinated Universal Time (UTC) format. UTC format includes + // the special designator, Z. For example, "2016-09-27T14:50Z". You can specify + // any time range in the previous three hours. // // EndTime is a required field EndTime *time.Time `type:"timestamp" required:"true"` // The beginning of the time range from which you want GetSampledRequests to - // return a sample of the requests that your AWS resource received. Specify - // the date and time in the following format: "2016-09-27T14:50Z". You can specify - // any time range in the previous three hours. + // return a sample of the requests that your AWS resource received. You must + // specify the times in Coordinated Universal Time (UTC) format. UTC format + // includes the special designator, Z. For example, "2016-09-27T14:50Z". You + // can specify any time range in the previous three hours. // // StartTime is a required field StartTime *time.Time `type:"timestamp" required:"true"` @@ -12982,10 +13302,10 @@ type VisibilityConfig struct { // CloudWatchMetricsEnabled is a required field CloudWatchMetricsEnabled *bool `type:"boolean" required:"true"` - // A name of the CloudWatch metric. The name can contain only alphanumeric characters - // (A-Z, a-z, 0-9), with length from one to 128 characters. It can't contain - // whitespace or metric names reserved for AWS WAF, for example "All" and "Default_Action." - // You can't change a MetricName after you create a VisibilityConfig. + // A name of the CloudWatch metric. The name can contain only the characters: + // A-Z, a-z, 0-9, - (hyphen), and _ (underscore). The name can be from one to + // 128 characters long. It can't contain whitespace or metric names reserved + // for AWS WAF, for example "All" and "Default_Action." // // MetricName is a required field MetricName *string `min:"1" type:"string" required:"true"` @@ -14295,6 +14615,18 @@ const ( ComparisonOperatorGt = "GT" ) +// ComparisonOperator_Values returns all elements of the ComparisonOperator enum +func ComparisonOperator_Values() []string { + return []string{ + ComparisonOperatorEq, + ComparisonOperatorNe, + ComparisonOperatorLe, + ComparisonOperatorLt, + ComparisonOperatorGe, + ComparisonOperatorGt, + } +} + const ( // CountryCodeAf is a CountryCode enum value CountryCodeAf = "AF" @@ -15044,6 +15376,297 @@ const ( CountryCodeZw = "ZW" ) +// CountryCode_Values returns all elements of the CountryCode enum +func CountryCode_Values() []string { + return []string{ + CountryCodeAf, + CountryCodeAx, + CountryCodeAl, + CountryCodeDz, + CountryCodeAs, + CountryCodeAd, + CountryCodeAo, + CountryCodeAi, + CountryCodeAq, + CountryCodeAg, + CountryCodeAr, + CountryCodeAm, + CountryCodeAw, + CountryCodeAu, + CountryCodeAt, + CountryCodeAz, + CountryCodeBs, + CountryCodeBh, + CountryCodeBd, + CountryCodeBb, + CountryCodeBy, + CountryCodeBe, + CountryCodeBz, + CountryCodeBj, + CountryCodeBm, + CountryCodeBt, + CountryCodeBo, + CountryCodeBq, + CountryCodeBa, + CountryCodeBw, + CountryCodeBv, + CountryCodeBr, + CountryCodeIo, + CountryCodeBn, + CountryCodeBg, + CountryCodeBf, + CountryCodeBi, + CountryCodeKh, + CountryCodeCm, + CountryCodeCa, + CountryCodeCv, + CountryCodeKy, + CountryCodeCf, + CountryCodeTd, + CountryCodeCl, + CountryCodeCn, + CountryCodeCx, + CountryCodeCc, + CountryCodeCo, + CountryCodeKm, + CountryCodeCg, + CountryCodeCd, + CountryCodeCk, + CountryCodeCr, + CountryCodeCi, + CountryCodeHr, + CountryCodeCu, + CountryCodeCw, + CountryCodeCy, + CountryCodeCz, + CountryCodeDk, + CountryCodeDj, + CountryCodeDm, + CountryCodeDo, + CountryCodeEc, + CountryCodeEg, + CountryCodeSv, + CountryCodeGq, + CountryCodeEr, + CountryCodeEe, + CountryCodeEt, + CountryCodeFk, + CountryCodeFo, + CountryCodeFj, + CountryCodeFi, + CountryCodeFr, + CountryCodeGf, + CountryCodePf, + CountryCodeTf, + CountryCodeGa, + CountryCodeGm, + CountryCodeGe, + CountryCodeDe, + CountryCodeGh, + CountryCodeGi, + CountryCodeGr, + CountryCodeGl, + CountryCodeGd, + CountryCodeGp, + CountryCodeGu, + CountryCodeGt, + CountryCodeGg, + CountryCodeGn, + CountryCodeGw, + CountryCodeGy, + CountryCodeHt, + CountryCodeHm, + CountryCodeVa, + CountryCodeHn, + CountryCodeHk, + CountryCodeHu, + CountryCodeIs, + CountryCodeIn, + CountryCodeId, + CountryCodeIr, + CountryCodeIq, + CountryCodeIe, + CountryCodeIm, + CountryCodeIl, + CountryCodeIt, + CountryCodeJm, + CountryCodeJp, + CountryCodeJe, + CountryCodeJo, + CountryCodeKz, + CountryCodeKe, + CountryCodeKi, + CountryCodeKp, + CountryCodeKr, + CountryCodeKw, + CountryCodeKg, + CountryCodeLa, + CountryCodeLv, + CountryCodeLb, + CountryCodeLs, + CountryCodeLr, + CountryCodeLy, + CountryCodeLi, + CountryCodeLt, + CountryCodeLu, + CountryCodeMo, + CountryCodeMk, + CountryCodeMg, + CountryCodeMw, + CountryCodeMy, + CountryCodeMv, + CountryCodeMl, + CountryCodeMt, + CountryCodeMh, + CountryCodeMq, + CountryCodeMr, + CountryCodeMu, + CountryCodeYt, + CountryCodeMx, + CountryCodeFm, + CountryCodeMd, + CountryCodeMc, + CountryCodeMn, + CountryCodeMe, + CountryCodeMs, + CountryCodeMa, + CountryCodeMz, + CountryCodeMm, + CountryCodeNa, + CountryCodeNr, + CountryCodeNp, + CountryCodeNl, + CountryCodeNc, + CountryCodeNz, + CountryCodeNi, + CountryCodeNe, + CountryCodeNg, + CountryCodeNu, + CountryCodeNf, + CountryCodeMp, + CountryCodeNo, + CountryCodeOm, + CountryCodePk, + CountryCodePw, + CountryCodePs, + CountryCodePa, + CountryCodePg, + CountryCodePy, + CountryCodePe, + CountryCodePh, + CountryCodePn, + CountryCodePl, + CountryCodePt, + CountryCodePr, + CountryCodeQa, + CountryCodeRe, + CountryCodeRo, + CountryCodeRu, + CountryCodeRw, + CountryCodeBl, + CountryCodeSh, + CountryCodeKn, + CountryCodeLc, + CountryCodeMf, + CountryCodePm, + CountryCodeVc, + CountryCodeWs, + CountryCodeSm, + CountryCodeSt, + CountryCodeSa, + CountryCodeSn, + CountryCodeRs, + CountryCodeSc, + CountryCodeSl, + CountryCodeSg, + CountryCodeSx, + CountryCodeSk, + CountryCodeSi, + CountryCodeSb, + CountryCodeSo, + CountryCodeZa, + CountryCodeGs, + CountryCodeSs, + CountryCodeEs, + CountryCodeLk, + CountryCodeSd, + CountryCodeSr, + CountryCodeSj, + CountryCodeSz, + CountryCodeSe, + CountryCodeCh, + CountryCodeSy, + CountryCodeTw, + CountryCodeTj, + CountryCodeTz, + CountryCodeTh, + CountryCodeTl, + CountryCodeTg, + CountryCodeTk, + CountryCodeTo, + CountryCodeTt, + CountryCodeTn, + CountryCodeTr, + CountryCodeTm, + CountryCodeTc, + CountryCodeTv, + CountryCodeUg, + CountryCodeUa, + CountryCodeAe, + CountryCodeGb, + CountryCodeUs, + CountryCodeUm, + CountryCodeUy, + CountryCodeUz, + CountryCodeVu, + CountryCodeVe, + CountryCodeVn, + CountryCodeVg, + CountryCodeVi, + CountryCodeWf, + CountryCodeEh, + CountryCodeYe, + CountryCodeZm, + CountryCodeZw, + } +} + +const ( + // FallbackBehaviorMatch is a FallbackBehavior enum value + FallbackBehaviorMatch = "MATCH" + + // FallbackBehaviorNoMatch is a FallbackBehavior enum value + FallbackBehaviorNoMatch = "NO_MATCH" +) + +// FallbackBehavior_Values returns all elements of the FallbackBehavior enum +func FallbackBehavior_Values() []string { + return []string{ + FallbackBehaviorMatch, + FallbackBehaviorNoMatch, + } +} + +const ( + // ForwardedIPPositionFirst is a ForwardedIPPosition enum value + ForwardedIPPositionFirst = "FIRST" + + // ForwardedIPPositionLast is a ForwardedIPPosition enum value + ForwardedIPPositionLast = "LAST" + + // ForwardedIPPositionAny is a ForwardedIPPosition enum value + ForwardedIPPositionAny = "ANY" +) + +// ForwardedIPPosition_Values returns all elements of the ForwardedIPPosition enum +func ForwardedIPPosition_Values() []string { + return []string{ + ForwardedIPPositionFirst, + ForwardedIPPositionLast, + ForwardedIPPositionAny, + } +} + const ( // IPAddressVersionIpv4 is a IPAddressVersion enum value IPAddressVersionIpv4 = "IPV4" @@ -15052,6 +15675,14 @@ const ( IPAddressVersionIpv6 = "IPV6" ) +// IPAddressVersion_Values returns all elements of the IPAddressVersion enum +func IPAddressVersion_Values() []string { + return []string{ + IPAddressVersionIpv4, + IPAddressVersionIpv6, + } +} + const ( // ParameterExceptionFieldWebAcl is a ParameterExceptionField enum value ParameterExceptionFieldWebAcl = "WEB_ACL" @@ -15166,8 +15797,72 @@ const ( // ParameterExceptionFieldFirewallManagerStatement is a ParameterExceptionField enum value ParameterExceptionFieldFirewallManagerStatement = "FIREWALL_MANAGER_STATEMENT" + + // ParameterExceptionFieldFallbackBehavior is a ParameterExceptionField enum value + ParameterExceptionFieldFallbackBehavior = "FALLBACK_BEHAVIOR" + + // ParameterExceptionFieldPosition is a ParameterExceptionField enum value + ParameterExceptionFieldPosition = "POSITION" + + // ParameterExceptionFieldForwardedIpConfig is a ParameterExceptionField enum value + ParameterExceptionFieldForwardedIpConfig = "FORWARDED_IP_CONFIG" + + // ParameterExceptionFieldIpSetForwardedIpConfig is a ParameterExceptionField enum value + ParameterExceptionFieldIpSetForwardedIpConfig = "IP_SET_FORWARDED_IP_CONFIG" + + // ParameterExceptionFieldHeaderName is a ParameterExceptionField enum value + ParameterExceptionFieldHeaderName = "HEADER_NAME" ) +// ParameterExceptionField_Values returns all elements of the ParameterExceptionField enum +func ParameterExceptionField_Values() []string { + return []string{ + ParameterExceptionFieldWebAcl, + ParameterExceptionFieldRuleGroup, + ParameterExceptionFieldRegexPatternSet, + ParameterExceptionFieldIpSet, + ParameterExceptionFieldManagedRuleSet, + ParameterExceptionFieldRule, + ParameterExceptionFieldExcludedRule, + ParameterExceptionFieldStatement, + ParameterExceptionFieldByteMatchStatement, + ParameterExceptionFieldSqliMatchStatement, + ParameterExceptionFieldXssMatchStatement, + ParameterExceptionFieldSizeConstraintStatement, + ParameterExceptionFieldGeoMatchStatement, + ParameterExceptionFieldRateBasedStatement, + ParameterExceptionFieldRuleGroupReferenceStatement, + ParameterExceptionFieldRegexPatternReferenceStatement, + ParameterExceptionFieldIpSetReferenceStatement, + ParameterExceptionFieldManagedRuleSetStatement, + ParameterExceptionFieldAndStatement, + ParameterExceptionFieldOrStatement, + ParameterExceptionFieldNotStatement, + ParameterExceptionFieldIpAddress, + ParameterExceptionFieldIpAddressVersion, + ParameterExceptionFieldFieldToMatch, + ParameterExceptionFieldTextTransformation, + ParameterExceptionFieldSingleQueryArgument, + ParameterExceptionFieldSingleHeader, + ParameterExceptionFieldDefaultAction, + ParameterExceptionFieldRuleAction, + ParameterExceptionFieldEntityLimit, + ParameterExceptionFieldOverrideAction, + ParameterExceptionFieldScopeValue, + ParameterExceptionFieldResourceArn, + ParameterExceptionFieldResourceType, + ParameterExceptionFieldTags, + ParameterExceptionFieldTagKeys, + ParameterExceptionFieldMetricName, + ParameterExceptionFieldFirewallManagerStatement, + ParameterExceptionFieldFallbackBehavior, + ParameterExceptionFieldPosition, + ParameterExceptionFieldForwardedIpConfig, + ParameterExceptionFieldIpSetForwardedIpConfig, + ParameterExceptionFieldHeaderName, + } +} + const ( // PositionalConstraintExactly is a PositionalConstraint enum value PositionalConstraintExactly = "EXACTLY" @@ -15185,11 +15880,33 @@ const ( PositionalConstraintContainsWord = "CONTAINS_WORD" ) +// PositionalConstraint_Values returns all elements of the PositionalConstraint enum +func PositionalConstraint_Values() []string { + return []string{ + PositionalConstraintExactly, + PositionalConstraintStartsWith, + PositionalConstraintEndsWith, + PositionalConstraintContains, + PositionalConstraintContainsWord, + } +} + const ( // RateBasedStatementAggregateKeyTypeIp is a RateBasedStatementAggregateKeyType enum value RateBasedStatementAggregateKeyTypeIp = "IP" + + // RateBasedStatementAggregateKeyTypeForwardedIp is a RateBasedStatementAggregateKeyType enum value + RateBasedStatementAggregateKeyTypeForwardedIp = "FORWARDED_IP" ) +// RateBasedStatementAggregateKeyType_Values returns all elements of the RateBasedStatementAggregateKeyType enum +func RateBasedStatementAggregateKeyType_Values() []string { + return []string{ + RateBasedStatementAggregateKeyTypeIp, + RateBasedStatementAggregateKeyTypeForwardedIp, + } +} + const ( // ResourceTypeApplicationLoadBalancer is a ResourceType enum value ResourceTypeApplicationLoadBalancer = "APPLICATION_LOAD_BALANCER" @@ -15198,6 +15915,14 @@ const ( ResourceTypeApiGateway = "API_GATEWAY" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeApplicationLoadBalancer, + ResourceTypeApiGateway, + } +} + const ( // ScopeCloudfront is a Scope enum value ScopeCloudfront = "CLOUDFRONT" @@ -15206,6 +15931,14 @@ const ( ScopeRegional = "REGIONAL" ) +// Scope_Values returns all elements of the Scope enum +func Scope_Values() []string { + return []string{ + ScopeCloudfront, + ScopeRegional, + } +} + const ( // TextTransformationTypeNone is a TextTransformationType enum value TextTransformationTypeNone = "NONE" @@ -15225,3 +15958,15 @@ const ( // TextTransformationTypeUrlDecode is a TextTransformationType enum value TextTransformationTypeUrlDecode = "URL_DECODE" ) + +// TextTransformationType_Values returns all elements of the TextTransformationType enum +func TextTransformationType_Values() []string { + return []string{ + TextTransformationTypeNone, + TextTransformationTypeCompressWhiteSpace, + TextTransformationTypeHtmlEntityDecode, + TextTransformationTypeLowercase, + TextTransformationTypeCmdLine, + TextTransformationTypeUrlDecode, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/worklink/api.go b/vendor/github.com/aws/aws-sdk-go/service/worklink/api.go index 517b093fece..e7cba85d4a6 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/worklink/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/worklink/api.go @@ -1717,6 +1717,9 @@ func (c *WorkLink) ListDomainsRequest(input *ListDomainsInput) (req *request.Req // * InvalidRequestException // The request is not valid. // +// * ResourceNotFoundException +// The requested resource was not found. +// // * TooManyRequestsException // The number of requests exceeds the limit. // @@ -1940,6 +1943,85 @@ func (c *WorkLink) ListFleetsPagesWithContext(ctx aws.Context, input *ListFleets return p.Err() } +const opListTagsForResource = "ListTagsForResource" + +// ListTagsForResourceRequest generates a "aws/request.Request" representing the +// client's request for the ListTagsForResource operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ListTagsForResource for more information on using the ListTagsForResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ListTagsForResourceRequest method. +// req, resp := client.ListTagsForResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/worklink-2018-09-25/ListTagsForResource +func (c *WorkLink) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { + op := &request.Operation{ + Name: opListTagsForResource, + HTTPMethod: "GET", + HTTPPath: "/tags/{ResourceArn}", + } + + if input == nil { + input = &ListTagsForResourceInput{} + } + + output = &ListTagsForResourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListTagsForResource API operation for Amazon WorkLink. +// +// Retrieves a list of tags 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 Amazon WorkLink's +// API operation ListTagsForResource for usage and error information. +// +// Returned Error Types: +// * InvalidRequestException +// The request is not valid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/worklink-2018-09-25/ListTagsForResource +func (c *WorkLink) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { + req, out := c.ListTagsForResourceRequest(input) + 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 *WorkLink) 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 opListWebsiteAuthorizationProviders = "ListWebsiteAuthorizationProviders" // ListWebsiteAuthorizationProvidersRequest generates a "aws/request.Request" representing the @@ -2514,6 +2596,168 @@ func (c *WorkLink) SignOutUserWithContext(ctx aws.Context, input *SignOutUserInp 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 will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See TagResource for more information on using the TagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the TagResourceRequest method. +// req, resp := client.TagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/worklink-2018-09-25/TagResource +func (c *WorkLink) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { + op := &request.Operation{ + Name: opTagResource, + HTTPMethod: "POST", + HTTPPath: "/tags/{ResourceArn}", + } + + if input == nil { + input = &TagResourceInput{} + } + + output = &TagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// TagResource API operation for Amazon WorkLink. +// +// Adds or overwrites one or more tags for the specified resource, such as a +// fleet. Each tag consists of a key and an optional value. If a resource already +// has a tag with the same key, this operation updates its value. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon WorkLink's +// API operation TagResource for usage and error information. +// +// Returned Error Types: +// * InvalidRequestException +// The request is not valid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/worklink-2018-09-25/TagResource +func (c *WorkLink) 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 *WorkLink) 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 will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UntagResource for more information on using the UntagResource +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UntagResourceRequest method. +// req, resp := client.UntagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/worklink-2018-09-25/UntagResource +func (c *WorkLink) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { + op := &request.Operation{ + Name: opUntagResource, + HTTPMethod: "DELETE", + HTTPPath: "/tags/{ResourceArn}", + } + + if input == nil { + input = &UntagResourceInput{} + } + + output = &UntagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(restjson.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UntagResource API operation for Amazon WorkLink. +// +// Removes one or more tags 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 Amazon WorkLink's +// API operation UntagResource for usage and error information. +// +// Returned Error Types: +// * InvalidRequestException +// The request is not valid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/worklink-2018-09-25/UntagResource +func (c *WorkLink) 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 *WorkLink) 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 opUpdateAuditStreamConfiguration = "UpdateAuditStreamConfiguration" // UpdateAuditStreamConfigurationRequest generates a "aws/request.Request" representing the @@ -3356,6 +3600,9 @@ type CreateFleetInput struct { // The option to optimize for better performance by routing traffic through // the closest AWS Region to users, which may be outside of your home Region. OptimizeForEndUserLocation *bool `type:"boolean"` + + // The tags to add to the resource. A tag is a key-value pair. + Tags map[string]*string `min:"1" type:"map"` } // String returns the string representation @@ -3377,6 +3624,9 @@ func (s *CreateFleetInput) Validate() error { if s.FleetName != nil && len(*s.FleetName) < 1 { invalidParams.Add(request.NewErrParamMinLen("FleetName", 1)) } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + } if invalidParams.Len() > 0 { return invalidParams @@ -3402,10 +3652,16 @@ func (s *CreateFleetInput) SetOptimizeForEndUserLocation(v bool) *CreateFleetInp return s } +// SetTags sets the Tags field's value. +func (s *CreateFleetInput) SetTags(v map[string]*string) *CreateFleetInput { + s.Tags = v + return s +} + type CreateFleetOutput struct { _ struct{} `type:"structure"` - // The ARN of the fleet. + // The Amazon Resource Name (ARN) of the fleet. FleetArn *string `min:"20" type:"string"` } @@ -3964,7 +4220,7 @@ func (s *DescribeDomainOutput) SetDomainStatus(v string) *DescribeDomainOutput { type DescribeFleetMetadataInput struct { _ struct{} `type:"structure"` - // The ARN of the fleet. + // The Amazon Resource Name (ARN) of the fleet. // // FleetArn is a required field FleetArn *string `min:"20" type:"string" required:"true"` @@ -4026,6 +4282,9 @@ type DescribeFleetMetadataOutput struct { // The option to optimize for better performance by routing traffic through // the closest AWS Region to users, which may be outside of your home Region. OptimizeForEndUserLocation *bool `type:"boolean"` + + // The tags attached to the resource. A tag is a key-value pair. + Tags map[string]*string `min:"1" type:"map"` } // String returns the string representation @@ -4080,6 +4339,12 @@ func (s *DescribeFleetMetadataOutput) SetOptimizeForEndUserLocation(v bool) *Des return s } +// SetTags sets the Tags field's value. +func (s *DescribeFleetMetadataOutput) SetTags(v map[string]*string) *DescribeFleetMetadataOutput { + s.Tags = v + return s +} + type DescribeIdentityProviderConfigurationInput struct { _ struct{} `type:"structure"` @@ -4577,10 +4842,10 @@ type FleetSummary struct { // The time when the fleet was created. CreatedTime *time.Time `type:"timestamp"` - // The name to display. + // The name of the fleet to display. DisplayName *string `type:"string"` - // The ARN of the fleet. + // The Amazon Resource Name (ARN) of the fleet. FleetArn *string `min:"20" type:"string"` // The name of the fleet. @@ -4591,6 +4856,9 @@ type FleetSummary struct { // The time when the fleet was last updated. LastUpdatedTime *time.Time `type:"timestamp"` + + // The tags attached to the resource. A tag is a key-value pair. + Tags map[string]*string `min:"1" type:"map"` } // String returns the string representation @@ -4645,6 +4913,12 @@ func (s *FleetSummary) SetLastUpdatedTime(v time.Time) *FleetSummary { return s } +// SetTags sets the Tags field's value. +func (s *FleetSummary) SetTags(v map[string]*string) *FleetSummary { + s.Tags = v + return s +} + // The service is temporarily unavailable. type InternalServerErrorException struct { _ struct{} `type:"structure"` @@ -5037,6 +5311,70 @@ func (s *ListFleetsOutput) SetNextToken(v string) *ListFleetsOutput { return s } +type ListTagsForResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the fleet. + // + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"ResourceArn" min:"20" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListTagsForResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsForResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTagsForResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 20 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 20)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *ListTagsForResourceInput) SetResourceArn(v string) *ListTagsForResourceInput { + s.ResourceArn = &v + return s +} + +type ListTagsForResourceOutput struct { + _ struct{} `type:"structure"` + + // The tags attached to the resource. A tag is a key-value pair. + Tags map[string]*string `min:"1" type:"map"` +} + +// String returns the string representation +func (s ListTagsForResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsForResourceOutput) GoString() string { + return s.String() +} + +// SetTags sets the Tags field's value. +func (s *ListTagsForResourceOutput) SetTags(v map[string]*string) *ListTagsForResourceOutput { + s.Tags = v + return s +} + type ListWebsiteAuthorizationProvidersInput struct { _ struct{} `type:"structure"` @@ -5563,6 +5901,78 @@ func (s SignOutUserOutput) GoString() string { return s.String() } +type TagResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the fleet. + // + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"ResourceArn" min:"20" type:"string" required:"true"` + + // The tags to add to the resource. A tag is a key-value pair. + // + // Tags is a required field + Tags map[string]*string `min:"1" 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.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 20 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 20)) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + if s.Tags != nil && len(s.Tags) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Tags", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *TagResourceInput) SetTags(v 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 number of requests exceeds the limit. type TooManyRequestsException struct { _ struct{} `type:"structure"` @@ -5675,6 +6085,78 @@ func (s *UnauthorizedException) RequestID() string { return s.RespMetadata.RequestID } +type UntagResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the fleet. + // + // ResourceArn is a required field + ResourceArn *string `location:"uri" locationName:"ResourceArn" min:"20" type:"string" required:"true"` + + // The list of tag keys to remove from the resource. + // + // TagKeys is a required field + TagKeys []*string `location:"querystring" locationName:"tagKeys" min:"1" type:"list" required:"true"` +} + +// String returns the string representation +func (s UntagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UntagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 20 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 20)) + } + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + if s.TagKeys != nil && len(s.TagKeys) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TagKeys", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTagKeys sets the TagKeys field's value. +func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { + s.TagKeys = v + return s +} + +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 UpdateAuditStreamConfigurationInput struct { _ struct{} `type:"structure"` @@ -6242,6 +6724,13 @@ const ( AuthorizationProviderTypeSaml = "SAML" ) +// AuthorizationProviderType_Values returns all elements of the AuthorizationProviderType enum +func AuthorizationProviderType_Values() []string { + return []string{ + AuthorizationProviderTypeSaml, + } +} + const ( // DeviceStatusActive is a DeviceStatus enum value DeviceStatusActive = "ACTIVE" @@ -6250,6 +6739,14 @@ const ( DeviceStatusSignedOut = "SIGNED_OUT" ) +// DeviceStatus_Values returns all elements of the DeviceStatus enum +func DeviceStatus_Values() []string { + return []string{ + DeviceStatusActive, + DeviceStatusSignedOut, + } +} + const ( // DomainStatusPendingValidation is a DomainStatus enum value DomainStatusPendingValidation = "PENDING_VALIDATION" @@ -6276,6 +6773,20 @@ const ( DomainStatusFailedToDisassociate = "FAILED_TO_DISASSOCIATE" ) +// DomainStatus_Values returns all elements of the DomainStatus enum +func DomainStatus_Values() []string { + return []string{ + DomainStatusPendingValidation, + DomainStatusAssociating, + DomainStatusActive, + DomainStatusInactive, + DomainStatusDisassociating, + DomainStatusDisassociated, + DomainStatusFailedToAssociate, + DomainStatusFailedToDisassociate, + } +} + const ( // FleetStatusCreating is a FleetStatus enum value FleetStatusCreating = "CREATING" @@ -6296,7 +6807,26 @@ const ( FleetStatusFailedToDelete = "FAILED_TO_DELETE" ) +// FleetStatus_Values returns all elements of the FleetStatus enum +func FleetStatus_Values() []string { + return []string{ + FleetStatusCreating, + FleetStatusActive, + FleetStatusDeleting, + FleetStatusDeleted, + FleetStatusFailedToCreate, + FleetStatusFailedToDelete, + } +} + const ( // IdentityProviderTypeSaml is a IdentityProviderType enum value IdentityProviderTypeSaml = "SAML" ) + +// IdentityProviderType_Values returns all elements of the IdentityProviderType enum +func IdentityProviderType_Values() []string { + return []string{ + IdentityProviderTypeSaml, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/worklink/doc.go b/vendor/github.com/aws/aws-sdk-go/service/worklink/doc.go index 691b270395a..dcde2c87d96 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/worklink/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/worklink/doc.go @@ -4,10 +4,10 @@ // requests to Amazon WorkLink. // // Amazon WorkLink is a cloud-based service that provides secure access to internal -// websites and web apps from iOS phones. In a single step, your users, such -// as employees, can access internal websites as efficiently as they access -// any other public website. They enter a URL in their web browser, or choose -// a link to an internal website in an email. Amazon WorkLink authenticates +// websites and web apps from iOS and Android phones. In a single step, your +// users, such as employees, can access internal websites as efficiently as +// they access any other public website. They enter a URL in their web browser, +// or choose a link to an internal website in an email. Amazon WorkLink authenticates // the user's access and securely renders authorized internal web content in // a secure rendering service in the AWS cloud. Amazon WorkLink doesn't download // or store any internal web content on mobile devices. diff --git a/vendor/github.com/aws/aws-sdk-go/service/workmail/api.go b/vendor/github.com/aws/aws-sdk-go/service/workmail/api.go index 24766b693f2..312744fcb9f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/workmail/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/workmail/api.go @@ -1104,6 +1104,94 @@ func (c *WorkMail) DeleteResourceWithContext(ctx aws.Context, input *DeleteResou return out, req.Send() } +const opDeleteRetentionPolicy = "DeleteRetentionPolicy" + +// DeleteRetentionPolicyRequest generates a "aws/request.Request" representing the +// client's request for the DeleteRetentionPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteRetentionPolicy for more information on using the DeleteRetentionPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteRetentionPolicyRequest method. +// req, resp := client.DeleteRetentionPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/workmail-2017-10-01/DeleteRetentionPolicy +func (c *WorkMail) DeleteRetentionPolicyRequest(input *DeleteRetentionPolicyInput) (req *request.Request, output *DeleteRetentionPolicyOutput) { + op := &request.Operation{ + Name: opDeleteRetentionPolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteRetentionPolicyInput{} + } + + output = &DeleteRetentionPolicyOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// DeleteRetentionPolicy API operation for Amazon WorkMail. +// +// Deletes the specified retention policy from the specified organization. +// +// Returns awserr.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 WorkMail's +// API operation DeleteRetentionPolicy for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// One or more of the input parameters don't match the service's restrictions. +// +// * OrganizationNotFoundException +// An operation received a valid organization identifier that either doesn't +// belong or exist in the system. +// +// * OrganizationStateException +// The organization must have a valid state (Active or Synchronizing) to perform +// certain operations on the organization or its members. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/workmail-2017-10-01/DeleteRetentionPolicy +func (c *WorkMail) DeleteRetentionPolicy(input *DeleteRetentionPolicyInput) (*DeleteRetentionPolicyOutput, error) { + req, out := c.DeleteRetentionPolicyRequest(input) + 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 *WorkMail) 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 opDeleteUser = "DeleteUser" // DeleteUserRequest generates a "aws/request.Request" representing the @@ -1958,6 +2046,97 @@ func (c *WorkMail) GetAccessControlEffectWithContext(ctx aws.Context, input *Get return out, req.Send() } +const opGetDefaultRetentionPolicy = "GetDefaultRetentionPolicy" + +// GetDefaultRetentionPolicyRequest generates a "aws/request.Request" representing the +// client's request for the GetDefaultRetentionPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetDefaultRetentionPolicy for more information on using the GetDefaultRetentionPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetDefaultRetentionPolicyRequest method. +// req, resp := client.GetDefaultRetentionPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/workmail-2017-10-01/GetDefaultRetentionPolicy +func (c *WorkMail) GetDefaultRetentionPolicyRequest(input *GetDefaultRetentionPolicyInput) (req *request.Request, output *GetDefaultRetentionPolicyOutput) { + op := &request.Operation{ + Name: opGetDefaultRetentionPolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &GetDefaultRetentionPolicyInput{} + } + + output = &GetDefaultRetentionPolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetDefaultRetentionPolicy API operation for Amazon WorkMail. +// +// Gets the default retention policy details for the specified organization. +// +// Returns awserr.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 WorkMail's +// API operation GetDefaultRetentionPolicy for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// One or more of the input parameters don't match the service's restrictions. +// +// * OrganizationNotFoundException +// An operation received a valid organization identifier that either doesn't +// belong or exist in the system. +// +// * OrganizationStateException +// The organization must have a valid state (Active or Synchronizing) to perform +// certain operations on the organization or its members. +// +// * EntityNotFoundException +// The identifier supplied for the user, group, or resource does not exist in +// your organization. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/workmail-2017-10-01/GetDefaultRetentionPolicy +func (c *WorkMail) GetDefaultRetentionPolicy(input *GetDefaultRetentionPolicyInput) (*GetDefaultRetentionPolicyOutput, error) { + req, out := c.GetDefaultRetentionPolicyRequest(input) + return out, req.Send() +} + +// GetDefaultRetentionPolicyWithContext is the same as GetDefaultRetentionPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetDefaultRetentionPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *WorkMail) GetDefaultRetentionPolicyWithContext(ctx aws.Context, input *GetDefaultRetentionPolicyInput, opts ...request.Option) (*GetDefaultRetentionPolicyOutput, error) { + req, out := c.GetDefaultRetentionPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opGetMailboxDetails = "GetMailboxDetails" // GetMailboxDetailsRequest generates a "aws/request.Request" representing the @@ -2786,7 +2965,7 @@ func (c *WorkMail) ListOrganizationsRequest(input *ListOrganizationsInput) (req // ListOrganizations API operation for Amazon WorkMail. // -// Returns summaries of the customer's non-deleted organizations. +// Returns summaries of the customer's organizations. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -3591,6 +3770,97 @@ func (c *WorkMail) PutMailboxPermissionsWithContext(ctx aws.Context, input *PutM return out, req.Send() } +const opPutRetentionPolicy = "PutRetentionPolicy" + +// PutRetentionPolicyRequest generates a "aws/request.Request" representing the +// client's request for the PutRetentionPolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See PutRetentionPolicy for more information on using the PutRetentionPolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the PutRetentionPolicyRequest method. +// req, resp := client.PutRetentionPolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/workmail-2017-10-01/PutRetentionPolicy +func (c *WorkMail) PutRetentionPolicyRequest(input *PutRetentionPolicyInput) (req *request.Request, output *PutRetentionPolicyOutput) { + op := &request.Operation{ + Name: opPutRetentionPolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &PutRetentionPolicyInput{} + } + + output = &PutRetentionPolicyOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// PutRetentionPolicy API operation for Amazon WorkMail. +// +// Puts a retention policy to the specified organization. +// +// Returns awserr.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 WorkMail's +// API operation PutRetentionPolicy for usage and error information. +// +// Returned Error Types: +// * InvalidParameterException +// One or more of the input parameters don't match the service's restrictions. +// +// * OrganizationNotFoundException +// An operation received a valid organization identifier that either doesn't +// belong or exist in the system. +// +// * OrganizationStateException +// The organization must have a valid state (Active or Synchronizing) to perform +// certain operations on the organization or its members. +// +// * LimitExceededException +// The request exceeds the limit of the resource. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/workmail-2017-10-01/PutRetentionPolicy +func (c *WorkMail) PutRetentionPolicy(input *PutRetentionPolicyInput) (*PutRetentionPolicyOutput, error) { + req, out := c.PutRetentionPolicyRequest(input) + 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 *WorkMail) 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 opRegisterToWorkMail = "RegisterToWorkMail" // RegisterToWorkMailRequest generates a "aws/request.Request" representing the @@ -5071,7 +5341,9 @@ type DeleteAccessControlRuleInput struct { Name *string `min:"1" type:"string" required:"true"` // The identifier for the organization. - OrganizationId *string `type:"string"` + // + // OrganizationId is a required field + OrganizationId *string `type:"string" required:"true"` } // String returns the string representation @@ -5093,6 +5365,9 @@ func (s *DeleteAccessControlRuleInput) Validate() error { if s.Name != nil && len(*s.Name) < 1 { invalidParams.Add(request.NewErrParamMinLen("Name", 1)) } + if s.OrganizationId == nil { + invalidParams.Add(request.NewErrParamRequired("OrganizationId")) + } if invalidParams.Len() > 0 { return invalidParams @@ -5439,6 +5714,75 @@ func (s DeleteResourceOutput) GoString() string { return s.String() } +type DeleteRetentionPolicyInput struct { + _ struct{} `type:"structure"` + + // The retention policy ID. + // + // Id is a required field + Id *string `min:"1" type:"string" required:"true"` + + // The organization ID. + // + // OrganizationId is a required field + OrganizationId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteRetentionPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRetentionPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteRetentionPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteRetentionPolicyInput"} + if s.Id == nil { + invalidParams.Add(request.NewErrParamRequired("Id")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + if s.OrganizationId == nil { + invalidParams.Add(request.NewErrParamRequired("OrganizationId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetId sets the Id field's value. +func (s *DeleteRetentionPolicyInput) SetId(v string) *DeleteRetentionPolicyInput { + s.Id = &v + return s +} + +// SetOrganizationId sets the OrganizationId field's value. +func (s *DeleteRetentionPolicyInput) SetOrganizationId(v string) *DeleteRetentionPolicyInput { + s.OrganizationId = &v + return s +} + +type DeleteRetentionPolicyOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s DeleteRetentionPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteRetentionPolicyOutput) GoString() string { + return s.String() +} + type DeleteUserInput struct { _ struct{} `type:"structure"` @@ -6639,6 +6983,72 @@ func (s *EntityStateException) RequestID() string { return s.RespMetadata.RequestID } +// The configuration applied to an organization's folders by its retention policy. +type FolderConfiguration struct { + _ struct{} `type:"structure"` + + // The action to take on the folder contents at the end of the folder configuration + // period. + // + // Action is a required field + Action *string `type:"string" required:"true" enum:"RetentionAction"` + + // The folder name. + // + // Name is a required field + Name *string `type:"string" required:"true" enum:"FolderName"` + + // The period of time at which the folder configuration action is applied. + Period *int64 `min:"1" type:"integer"` +} + +// String returns the string representation +func (s FolderConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FolderConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *FolderConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "FolderConfiguration"} + if s.Action == nil { + invalidParams.Add(request.NewErrParamRequired("Action")) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Period != nil && *s.Period < 1 { + invalidParams.Add(request.NewErrParamMinValue("Period", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAction sets the Action field's value. +func (s *FolderConfiguration) SetAction(v string) *FolderConfiguration { + s.Action = &v + return s +} + +// SetName sets the Name field's value. +func (s *FolderConfiguration) SetName(v string) *FolderConfiguration { + s.Name = &v + return s +} + +// SetPeriod sets the Period field's value. +func (s *FolderConfiguration) SetPeriod(v int64) *FolderConfiguration { + s.Period = &v + return s +} + type GetAccessControlEffectInput struct { _ struct{} `type:"structure"` @@ -6761,6 +7171,94 @@ func (s *GetAccessControlEffectOutput) SetMatchedRules(v []*string) *GetAccessCo return s } +type GetDefaultRetentionPolicyInput struct { + _ struct{} `type:"structure"` + + // The organization ID. + // + // OrganizationId is a required field + OrganizationId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s GetDefaultRetentionPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDefaultRetentionPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetDefaultRetentionPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetDefaultRetentionPolicyInput"} + if s.OrganizationId == nil { + invalidParams.Add(request.NewErrParamRequired("OrganizationId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetOrganizationId sets the OrganizationId field's value. +func (s *GetDefaultRetentionPolicyInput) SetOrganizationId(v string) *GetDefaultRetentionPolicyInput { + s.OrganizationId = &v + return s +} + +type GetDefaultRetentionPolicyOutput struct { + _ struct{} `type:"structure"` + + // The retention policy description. + Description *string `type:"string"` + + // The retention policy folder configurations. + FolderConfigurations []*FolderConfiguration `type:"list"` + + // The retention policy ID. + Id *string `min:"1" type:"string"` + + // The retention policy name. + Name *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s GetDefaultRetentionPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetDefaultRetentionPolicyOutput) GoString() string { + return s.String() +} + +// SetDescription sets the Description field's value. +func (s *GetDefaultRetentionPolicyOutput) SetDescription(v string) *GetDefaultRetentionPolicyOutput { + s.Description = &v + return s +} + +// SetFolderConfigurations sets the FolderConfigurations field's value. +func (s *GetDefaultRetentionPolicyOutput) SetFolderConfigurations(v []*FolderConfiguration) *GetDefaultRetentionPolicyOutput { + s.FolderConfigurations = v + return s +} + +// SetId sets the Id field's value. +func (s *GetDefaultRetentionPolicyOutput) SetId(v string) *GetDefaultRetentionPolicyOutput { + s.Id = &v + return s +} + +// SetName sets the Name field's value. +func (s *GetDefaultRetentionPolicyOutput) SetName(v string) *GetDefaultRetentionPolicyOutput { + s.Name = &v + return s +} + type GetMailboxDetailsInput struct { _ struct{} `type:"structure"` @@ -8817,6 +9315,120 @@ func (s PutMailboxPermissionsOutput) GoString() string { return s.String() } +type PutRetentionPolicyInput struct { + _ struct{} `type:"structure"` + + // The retention policy description. + Description *string `type:"string"` + + // The retention policy folder configurations. + // + // FolderConfigurations is a required field + FolderConfigurations []*FolderConfiguration `type:"list" required:"true"` + + // The retention policy ID. + Id *string `min:"1" type:"string"` + + // The retention policy name. + // + // Name is a required field + Name *string `min:"1" type:"string" required:"true"` + + // The organization ID. + // + // OrganizationId is a required field + OrganizationId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s PutRetentionPolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutRetentionPolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *PutRetentionPolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "PutRetentionPolicyInput"} + if s.FolderConfigurations == nil { + invalidParams.Add(request.NewErrParamRequired("FolderConfigurations")) + } + if s.Id != nil && len(*s.Id) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Id", 1)) + } + if s.Name == nil { + invalidParams.Add(request.NewErrParamRequired("Name")) + } + if s.Name != nil && len(*s.Name) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Name", 1)) + } + if s.OrganizationId == nil { + invalidParams.Add(request.NewErrParamRequired("OrganizationId")) + } + if s.FolderConfigurations != nil { + for i, v := range s.FolderConfigurations { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "FolderConfigurations", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *PutRetentionPolicyInput) SetDescription(v string) *PutRetentionPolicyInput { + s.Description = &v + return s +} + +// SetFolderConfigurations sets the FolderConfigurations field's value. +func (s *PutRetentionPolicyInput) SetFolderConfigurations(v []*FolderConfiguration) *PutRetentionPolicyInput { + s.FolderConfigurations = v + return s +} + +// SetId sets the Id field's value. +func (s *PutRetentionPolicyInput) SetId(v string) *PutRetentionPolicyInput { + s.Id = &v + return s +} + +// SetName sets the Name field's value. +func (s *PutRetentionPolicyInput) SetName(v string) *PutRetentionPolicyInput { + s.Name = &v + return s +} + +// SetOrganizationId sets the OrganizationId field's value. +func (s *PutRetentionPolicyInput) SetOrganizationId(v string) *PutRetentionPolicyInput { + s.OrganizationId = &v + return s +} + +type PutRetentionPolicyOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s PutRetentionPolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PutRetentionPolicyOutput) GoString() string { + return s.String() +} + type RegisterToWorkMailInput struct { _ struct{} `type:"structure"` @@ -9850,6 +10462,14 @@ const ( AccessControlRuleEffectDeny = "DENY" ) +// AccessControlRuleEffect_Values returns all elements of the AccessControlRuleEffect enum +func AccessControlRuleEffect_Values() []string { + return []string{ + AccessControlRuleEffectAllow, + AccessControlRuleEffectDeny, + } +} + const ( // EntityStateEnabled is a EntityState enum value EntityStateEnabled = "ENABLED" @@ -9861,6 +10481,43 @@ const ( EntityStateDeleted = "DELETED" ) +// EntityState_Values returns all elements of the EntityState enum +func EntityState_Values() []string { + return []string{ + EntityStateEnabled, + EntityStateDisabled, + EntityStateDeleted, + } +} + +const ( + // FolderNameInbox is a FolderName enum value + FolderNameInbox = "INBOX" + + // FolderNameDeletedItems is a FolderName enum value + FolderNameDeletedItems = "DELETED_ITEMS" + + // FolderNameSentItems is a FolderName enum value + FolderNameSentItems = "SENT_ITEMS" + + // FolderNameDrafts is a FolderName enum value + FolderNameDrafts = "DRAFTS" + + // FolderNameJunkEmail is a FolderName enum value + FolderNameJunkEmail = "JUNK_EMAIL" +) + +// FolderName_Values returns all elements of the FolderName enum +func FolderName_Values() []string { + return []string{ + FolderNameInbox, + FolderNameDeletedItems, + FolderNameSentItems, + FolderNameDrafts, + FolderNameJunkEmail, + } +} + const ( // MemberTypeGroup is a MemberType enum value MemberTypeGroup = "GROUP" @@ -9869,6 +10526,14 @@ const ( MemberTypeUser = "USER" ) +// MemberType_Values returns all elements of the MemberType enum +func MemberType_Values() []string { + return []string{ + MemberTypeGroup, + MemberTypeUser, + } +} + const ( // PermissionTypeFullAccess is a PermissionType enum value PermissionTypeFullAccess = "FULL_ACCESS" @@ -9880,6 +10545,15 @@ const ( PermissionTypeSendOnBehalf = "SEND_ON_BEHALF" ) +// PermissionType_Values returns all elements of the PermissionType enum +func PermissionType_Values() []string { + return []string{ + PermissionTypeFullAccess, + PermissionTypeSendAs, + PermissionTypeSendOnBehalf, + } +} + const ( // ResourceTypeRoom is a ResourceType enum value ResourceTypeRoom = "ROOM" @@ -9888,6 +10562,34 @@ const ( ResourceTypeEquipment = "EQUIPMENT" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeRoom, + ResourceTypeEquipment, + } +} + +const ( + // RetentionActionNone is a RetentionAction enum value + RetentionActionNone = "NONE" + + // RetentionActionDelete is a RetentionAction enum value + RetentionActionDelete = "DELETE" + + // RetentionActionPermanentlyDelete is a RetentionAction enum value + RetentionActionPermanentlyDelete = "PERMANENTLY_DELETE" +) + +// RetentionAction_Values returns all elements of the RetentionAction enum +func RetentionAction_Values() []string { + return []string{ + RetentionActionNone, + RetentionActionDelete, + RetentionActionPermanentlyDelete, + } +} + const ( // UserRoleUser is a UserRole enum value UserRoleUser = "USER" @@ -9898,3 +10600,12 @@ const ( // UserRoleSystemUser is a UserRole enum value UserRoleSystemUser = "SYSTEM_USER" ) + +// UserRole_Values returns all elements of the UserRole enum +func UserRole_Values() []string { + return []string{ + UserRoleUser, + UserRoleResource, + UserRoleSystemUser, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/workspaces/api.go b/vendor/github.com/aws/aws-sdk-go/service/workspaces/api.go index 16866ca6bec..b8ccae6fefd 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/workspaces/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/workspaces/api.go @@ -793,8 +793,8 @@ func (c *WorkSpaces) DeleteWorkspaceImageRequest(input *DeleteWorkspaceImageInpu // DeleteWorkspaceImage API operation for Amazon WorkSpaces. // // Deletes the specified image from your account. To delete an image, you must -// first delete any bundles that are associated with the image and un-share -// the image if it is shared with other accounts. +// first delete any bundles that are associated with the image and unshare the +// image if it is shared with other accounts. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -1611,6 +1611,92 @@ func (c *WorkSpaces) DescribeWorkspaceDirectoriesPagesWithContext(ctx aws.Contex return p.Err() } +const opDescribeWorkspaceImagePermissions = "DescribeWorkspaceImagePermissions" + +// DescribeWorkspaceImagePermissionsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeWorkspaceImagePermissions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeWorkspaceImagePermissions for more information on using the DescribeWorkspaceImagePermissions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeWorkspaceImagePermissionsRequest method. +// req, resp := client.DescribeWorkspaceImagePermissionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/DescribeWorkspaceImagePermissions +func (c *WorkSpaces) DescribeWorkspaceImagePermissionsRequest(input *DescribeWorkspaceImagePermissionsInput) (req *request.Request, output *DescribeWorkspaceImagePermissionsOutput) { + op := &request.Operation{ + Name: opDescribeWorkspaceImagePermissions, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeWorkspaceImagePermissionsInput{} + } + + output = &DescribeWorkspaceImagePermissionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeWorkspaceImagePermissions API operation for Amazon WorkSpaces. +// +// Describes the permissions that the owner of an image has granted to other +// AWS accounts for an image. +// +// Returns awserr.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 WorkSpaces's +// API operation DescribeWorkspaceImagePermissions for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The resource could not be found. +// +// * AccessDeniedException +// The user is not authorized to access a resource. +// +// * InvalidParameterValuesException +// One or more parameter values are not valid. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/DescribeWorkspaceImagePermissions +func (c *WorkSpaces) DescribeWorkspaceImagePermissions(input *DescribeWorkspaceImagePermissionsInput) (*DescribeWorkspaceImagePermissionsOutput, error) { + req, out := c.DescribeWorkspaceImagePermissionsRequest(input) + return out, req.Send() +} + +// DescribeWorkspaceImagePermissionsWithContext is the same as DescribeWorkspaceImagePermissions with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeWorkspaceImagePermissions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *WorkSpaces) DescribeWorkspaceImagePermissionsWithContext(ctx aws.Context, input *DescribeWorkspaceImagePermissionsInput, opts ...request.Option) (*DescribeWorkspaceImagePermissionsOutput, error) { + req, out := c.DescribeWorkspaceImagePermissionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDescribeWorkspaceImages = "DescribeWorkspaceImages" // DescribeWorkspaceImagesRequest generates a "aws/request.Request" representing the @@ -2793,6 +2879,9 @@ func (c *WorkSpaces) ModifyWorkspaceCreationPropertiesRequest(input *ModifyWorks // * ResourceNotFoundException // The resource could not be found. // +// * OperationNotSupportedException +// This operation is not supported. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/ModifyWorkspaceCreationProperties func (c *WorkSpaces) ModifyWorkspaceCreationProperties(input *ModifyWorkspaceCreationPropertiesInput) (*ModifyWorkspaceCreationPropertiesOutput, error) { req, out := c.ModifyWorkspaceCreationPropertiesRequest(input) @@ -2860,7 +2949,9 @@ func (c *WorkSpaces) ModifyWorkspacePropertiesRequest(input *ModifyWorkspaceProp // ModifyWorkspaceProperties API operation for Amazon WorkSpaces. // -// Modifies the specified WorkSpace properties. +// Modifies the specified WorkSpace properties. For important information about +// how to modify the size of the root and user volumes, see Modify a WorkSpace +// (https://docs.aws.amazon.com/workspaces/latest/adminguide/modify-workspaces.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 @@ -3133,7 +3224,7 @@ func (c *WorkSpaces) RebuildWorkspacesRequest(input *RebuildWorkspacesInput) (re // Rebuilds the specified WorkSpace. // // You cannot rebuild a WorkSpace unless its state is AVAILABLE, ERROR, UNHEALTHY, -// or STOPPED. +// STOPPED, or REBOOTING. // // Rebuilding a WorkSpace is a potentially destructive action that can result // in the loss of data. For more information, see Rebuild a WorkSpace (https://docs.aws.amazon.com/workspaces/latest/adminguide/reset-workspace.html). @@ -3794,6 +3885,109 @@ func (c *WorkSpaces) UpdateRulesOfIpGroupWithContext(ctx aws.Context, input *Upd return out, req.Send() } +const opUpdateWorkspaceImagePermission = "UpdateWorkspaceImagePermission" + +// UpdateWorkspaceImagePermissionRequest generates a "aws/request.Request" representing the +// client's request for the UpdateWorkspaceImagePermission operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See UpdateWorkspaceImagePermission for more information on using the UpdateWorkspaceImagePermission +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the UpdateWorkspaceImagePermissionRequest method. +// req, resp := client.UpdateWorkspaceImagePermissionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/UpdateWorkspaceImagePermission +func (c *WorkSpaces) UpdateWorkspaceImagePermissionRequest(input *UpdateWorkspaceImagePermissionInput) (req *request.Request, output *UpdateWorkspaceImagePermissionOutput) { + op := &request.Operation{ + Name: opUpdateWorkspaceImagePermission, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateWorkspaceImagePermissionInput{} + } + + output = &UpdateWorkspaceImagePermissionOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Swap(jsonrpc.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + return +} + +// UpdateWorkspaceImagePermission API operation for Amazon WorkSpaces. +// +// Shares or unshares an image with one account by specifying whether that account +// has permission to copy the image. If the copy image permission is granted, +// the image is shared with that account. If the copy image permission is revoked, +// the image is unshared with the account. +// +// * To delete an image that has been shared, you must unshare the image +// before you delete it. +// +// * Sharing Bring Your Own License (BYOL) images across AWS accounts isn't +// supported at this time in the AWS GovCloud (US-West) Region. To share +// BYOL images across accounts in the AWS GovCloud (US-West) Region, contact +// AWS Support. +// +// Returns awserr.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 WorkSpaces's +// API operation UpdateWorkspaceImagePermission for usage and error information. +// +// Returned Error Types: +// * ResourceNotFoundException +// The resource could not be found. +// +// * ResourceUnavailableException +// The specified resource is not available. +// +// * AccessDeniedException +// The user is not authorized to access a resource. +// +// * InvalidParameterValuesException +// One or more parameter values are not valid. +// +// * OperationNotSupportedException +// This operation is not supported. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/UpdateWorkspaceImagePermission +func (c *WorkSpaces) UpdateWorkspaceImagePermission(input *UpdateWorkspaceImagePermissionInput) (*UpdateWorkspaceImagePermissionOutput, error) { + req, out := c.UpdateWorkspaceImagePermissionRequest(input) + return out, req.Send() +} + +// UpdateWorkspaceImagePermissionWithContext is the same as UpdateWorkspaceImagePermission with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateWorkspaceImagePermission for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *WorkSpaces) UpdateWorkspaceImagePermissionWithContext(ctx aws.Context, input *UpdateWorkspaceImagePermissionInput, opts ...request.Option) (*UpdateWorkspaceImagePermissionOutput, error) { + req, out := c.UpdateWorkspaceImagePermissionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + // The user is not authorized to access a resource. type AccessDeniedException struct { _ struct{} `type:"structure"` @@ -4539,8 +4733,9 @@ func (s *CreateWorkspacesOutput) SetPendingRequests(v []*Workspace) *CreateWorks type DefaultWorkspaceCreationProperties struct { _ struct{} `type:"structure"` - // The identifier of any security groups to apply to WorkSpaces when they are - // created. + // The identifier of the default security group to apply to WorkSpaces when + // they are created. For more information, see Security Groups for Your WorkSpaces + // (https://docs.aws.amazon.com/workspaces/latest/adminguide/amazon-workspaces-security-groups.html). CustomSecurityGroupId *string `min:"11" type:"string"` // The organizational unit (OU) in the directory for the WorkSpace machine accounts. @@ -5382,12 +5577,120 @@ func (s *DescribeWorkspaceDirectoriesOutput) SetNextToken(v string) *DescribeWor return s } +type DescribeWorkspaceImagePermissionsInput struct { + _ struct{} `type:"structure"` + + // The identifier of the image. + // + // ImageId is a required field + ImageId *string `type:"string" required:"true"` + + // The maximum number of items to return. + MaxResults *int64 `min:"1" type:"integer"` + + // If you received a NextToken from a previous call that was paginated, provide + // this token to receive the next set of results. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s DescribeWorkspaceImagePermissionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeWorkspaceImagePermissionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeWorkspaceImagePermissionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeWorkspaceImagePermissionsInput"} + if s.ImageId == nil { + invalidParams.Add(request.NewErrParamRequired("ImageId")) + } + 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 +} + +// SetImageId sets the ImageId field's value. +func (s *DescribeWorkspaceImagePermissionsInput) SetImageId(v string) *DescribeWorkspaceImagePermissionsInput { + s.ImageId = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeWorkspaceImagePermissionsInput) SetMaxResults(v int64) *DescribeWorkspaceImagePermissionsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeWorkspaceImagePermissionsInput) SetNextToken(v string) *DescribeWorkspaceImagePermissionsInput { + s.NextToken = &v + return s +} + +type DescribeWorkspaceImagePermissionsOutput struct { + _ struct{} `type:"structure"` + + // The identifier of the image. + ImageId *string `type:"string"` + + // The identifiers of the AWS accounts that the image has been shared with. + ImagePermissions []*ImagePermission `type:"list"` + + // The token to use to retrieve the next set of results, or null if no more + // results are available. + NextToken *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s DescribeWorkspaceImagePermissionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeWorkspaceImagePermissionsOutput) GoString() string { + return s.String() +} + +// SetImageId sets the ImageId field's value. +func (s *DescribeWorkspaceImagePermissionsOutput) SetImageId(v string) *DescribeWorkspaceImagePermissionsOutput { + s.ImageId = &v + return s +} + +// SetImagePermissions sets the ImagePermissions field's value. +func (s *DescribeWorkspaceImagePermissionsOutput) SetImagePermissions(v []*ImagePermission) *DescribeWorkspaceImagePermissionsOutput { + s.ImagePermissions = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeWorkspaceImagePermissionsOutput) SetNextToken(v string) *DescribeWorkspaceImagePermissionsOutput { + s.NextToken = &v + return s +} + type DescribeWorkspaceImagesInput struct { _ struct{} `type:"structure"` // The identifier of the image. ImageIds []*string `min:"1" type:"list"` + // The type (owned or shared) of the image. + ImageType *string `type:"string" enum:"ImageType"` + // The maximum number of items to return. MaxResults *int64 `min:"1" type:"integer"` @@ -5431,6 +5734,12 @@ func (s *DescribeWorkspaceImagesInput) SetImageIds(v []*string) *DescribeWorkspa return s } +// SetImageType sets the ImageType field's value. +func (s *DescribeWorkspaceImagesInput) SetImageType(v string) *DescribeWorkspaceImagesInput { + s.ImageType = &v + return s +} + // SetMaxResults sets the MaxResults field's value. func (s *DescribeWorkspaceImagesInput) SetMaxResults(v int64) *DescribeWorkspaceImagesInput { s.MaxResults = &v @@ -5925,6 +6234,31 @@ func (s *FailedWorkspaceChangeRequest) SetWorkspaceId(v string) *FailedWorkspace return s } +// Describes the AWS accounts that have been granted permission to use a shared +// image. +type ImagePermission struct { + _ struct{} `type:"structure"` + + // The identifier of the AWS account that an image has been shared with. + SharedAccountId *string `type:"string"` +} + +// String returns the string representation +func (s ImagePermission) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ImagePermission) GoString() string { + return s.String() +} + +// SetSharedAccountId sets the SharedAccountId field's value. +func (s *ImagePermission) SetSharedAccountId(v string) *ImagePermission { + s.SharedAccountId = &v + return s +} + type ImportWorkspaceImageInput struct { _ struct{} `type:"structure"` @@ -8523,6 +8857,87 @@ func (s UpdateRulesOfIpGroupOutput) GoString() string { return s.String() } +type UpdateWorkspaceImagePermissionInput struct { + _ struct{} `type:"structure"` + + // The permission to copy the image. This permission can be revoked only after + // an image has been shared. + // + // AllowCopyImage is a required field + AllowCopyImage *bool `type:"boolean" required:"true"` + + // The identifier of the image. + // + // ImageId is a required field + ImageId *string `type:"string" required:"true"` + + // The identifier of the AWS account to share or unshare the image with. + // + // SharedAccountId is a required field + SharedAccountId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s UpdateWorkspaceImagePermissionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateWorkspaceImagePermissionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateWorkspaceImagePermissionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateWorkspaceImagePermissionInput"} + if s.AllowCopyImage == nil { + invalidParams.Add(request.NewErrParamRequired("AllowCopyImage")) + } + if s.ImageId == nil { + invalidParams.Add(request.NewErrParamRequired("ImageId")) + } + if s.SharedAccountId == nil { + invalidParams.Add(request.NewErrParamRequired("SharedAccountId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAllowCopyImage sets the AllowCopyImage field's value. +func (s *UpdateWorkspaceImagePermissionInput) SetAllowCopyImage(v bool) *UpdateWorkspaceImagePermissionInput { + s.AllowCopyImage = &v + return s +} + +// SetImageId sets the ImageId field's value. +func (s *UpdateWorkspaceImagePermissionInput) SetImageId(v string) *UpdateWorkspaceImagePermissionInput { + s.ImageId = &v + return s +} + +// SetSharedAccountId sets the SharedAccountId field's value. +func (s *UpdateWorkspaceImagePermissionInput) SetSharedAccountId(v string) *UpdateWorkspaceImagePermissionInput { + s.SharedAccountId = &v + return s +} + +type UpdateWorkspaceImagePermissionOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UpdateWorkspaceImagePermissionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateWorkspaceImagePermissionOutput) GoString() string { + return s.String() +} + // Describes the user storage for a WorkSpace bundle. type UserStorage struct { _ struct{} `type:"structure"` @@ -8554,7 +8969,8 @@ type Workspace struct { // The identifier of the bundle used to create the WorkSpace. BundleId *string `type:"string"` - // The name of the WorkSpace, as seen by the operating system. + // The name of the WorkSpace, as seen by the operating system. The format of + // this name varies. For more information, see Launch a WorkSpace (https://docs.aws.amazon.com/workspaces/latest/adminguide/launch-workspaces-tutorials.html). ComputerName *string `type:"string"` // The identifier of the AWS Directory Service directory for the WorkSpace. @@ -8951,6 +9367,22 @@ type WorkspaceCreationProperties struct { // information, see WorkSpace Maintenance (https://docs.aws.amazon.com/workspaces/latest/adminguide/workspace-maintenance.html). EnableMaintenanceMode *bool `type:"boolean"` + // Indicates whether Amazon WorkDocs is enabled for your WorkSpaces. + // + // If WorkDocs is already enabled for a WorkSpaces directory and you disable + // it, new WorkSpaces launched in the directory will not have WorkDocs enabled. + // However, WorkDocs remains enabled for any existing WorkSpaces, unless you + // either disable users' access to WorkDocs or you delete the WorkDocs site. + // To disable users' access to WorkDocs, see Disabling Users (https://docs.aws.amazon.com/workdocs/latest/adminguide/inactive-user.html) + // in the Amazon WorkDocs Administration Guide. To delete a WorkDocs site, see + // Deleting a Site (https://docs.aws.amazon.com/workdocs/latest/adminguide/manage-sites.html) + // in the Amazon WorkDocs Administration Guide. + // + // If you enable WorkDocs on a directory that already has existing WorkSpaces, + // the existing WorkSpaces and any new WorkSpaces that are launched in the directory + // will have WorkDocs enabled. + EnableWorkDocs *bool `type:"boolean"` + // Indicates whether users are local administrators of their WorkSpaces. UserEnabledAsLocalAdministrator *bool `type:"boolean"` } @@ -9002,6 +9434,12 @@ func (s *WorkspaceCreationProperties) SetEnableMaintenanceMode(v bool) *Workspac return s } +// SetEnableWorkDocs sets the EnableWorkDocs field's value. +func (s *WorkspaceCreationProperties) SetEnableWorkDocs(v bool) *WorkspaceCreationProperties { + s.EnableWorkDocs = &v + return s +} + // SetUserEnabledAsLocalAdministrator sets the UserEnabledAsLocalAdministrator field's value. func (s *WorkspaceCreationProperties) SetUserEnabledAsLocalAdministrator(v bool) *WorkspaceCreationProperties { s.UserEnabledAsLocalAdministrator = &v @@ -9175,6 +9613,11 @@ func (s *WorkspaceDirectory) SetWorkspaceSecurityGroupId(v string) *WorkspaceDir type WorkspaceImage struct { _ struct{} `type:"structure"` + // The date when the image was created. If the image has been shared, the AWS + // account that the image has been shared with sees the original creation date + // of the image. + Created *time.Time `type:"timestamp"` + // The description of the image. Description *string `min:"1" type:"string"` @@ -9193,6 +9636,9 @@ type WorkspaceImage struct { // The operating system that the image is running. OperatingSystem *OperatingSystem `type:"structure"` + // The identifier of the AWS account that owns the image. + OwnerAccountId *string `type:"string"` + // Specifies whether the image is running on dedicated hardware. When Bring // Your Own License (BYOL) is enabled, this value is set to DEDICATED. For more // information, see Bring Your Own Windows Desktop Images (https://docs.aws.amazon.com/workspaces/latest/adminguide/byol-windows-images.html). @@ -9212,6 +9658,12 @@ func (s WorkspaceImage) GoString() string { return s.String() } +// SetCreated sets the Created field's value. +func (s *WorkspaceImage) SetCreated(v time.Time) *WorkspaceImage { + s.Created = &v + return s +} + // SetDescription sets the Description field's value. func (s *WorkspaceImage) SetDescription(v string) *WorkspaceImage { s.Description = &v @@ -9248,6 +9700,12 @@ func (s *WorkspaceImage) SetOperatingSystem(v *OperatingSystem) *WorkspaceImage return s } +// SetOwnerAccountId sets the OwnerAccountId field's value. +func (s *WorkspaceImage) SetOwnerAccountId(v string) *WorkspaceImage { + s.OwnerAccountId = &v + return s +} + // SetRequiredTenancy sets the RequiredTenancy field's value. func (s *WorkspaceImage) SetRequiredTenancy(v string) *WorkspaceImage { s.RequiredTenancy = &v @@ -9267,7 +9725,8 @@ type WorkspaceProperties struct { // The compute type. For more information, see Amazon WorkSpaces Bundles (http://aws.amazon.com/workspaces/details/#Amazon_WorkSpaces_Bundles). ComputeTypeName *string `type:"string" enum:"Compute"` - // The size of the root volume. + // The size of the root volume. For important information about how to modify + // the size of the root and user volumes, see Modify a WorkSpace (https://docs.aws.amazon.com/workspaces/latest/adminguide/modify-workspaces.html). RootVolumeSizeGib *int64 `type:"integer"` // The running mode. For more information, see Manage the WorkSpace Running @@ -9278,7 +9737,8 @@ type WorkspaceProperties struct { // Configured in 60-minute intervals. RunningModeAutoStopTimeoutInMinutes *int64 `type:"integer"` - // The size of the user storage. + // The size of the user storage. For important information about how to modify + // the size of the root and user volumes, see Modify a WorkSpace (https://docs.aws.amazon.com/workspaces/latest/adminguide/modify-workspaces.html). UserVolumeSizeGib *int64 `type:"integer"` } @@ -9521,6 +9981,14 @@ const ( AccessPropertyValueDeny = "DENY" ) +// AccessPropertyValue_Values returns all elements of the AccessPropertyValue enum +func AccessPropertyValue_Values() []string { + return []string{ + AccessPropertyValueAllow, + AccessPropertyValueDeny, + } +} + const ( // ComputeValue is a Compute enum value ComputeValue = "VALUE" @@ -9544,6 +10012,19 @@ const ( ComputeGraphicspro = "GRAPHICSPRO" ) +// Compute_Values returns all elements of the Compute enum +func Compute_Values() []string { + return []string{ + ComputeValue, + ComputeStandard, + ComputePerformance, + ComputePower, + ComputeGraphics, + ComputePowerpro, + ComputeGraphicspro, + } +} + const ( // ConnectionStateConnected is a ConnectionState enum value ConnectionStateConnected = "CONNECTED" @@ -9555,6 +10036,15 @@ const ( ConnectionStateUnknown = "UNKNOWN" ) +// ConnectionState_Values returns all elements of the ConnectionState enum +func ConnectionState_Values() []string { + return []string{ + ConnectionStateConnected, + ConnectionStateDisconnected, + ConnectionStateUnknown, + } +} + const ( // DedicatedTenancyModificationStateEnumPending is a DedicatedTenancyModificationStateEnum enum value DedicatedTenancyModificationStateEnumPending = "PENDING" @@ -9566,11 +10056,27 @@ const ( DedicatedTenancyModificationStateEnumFailed = "FAILED" ) +// DedicatedTenancyModificationStateEnum_Values returns all elements of the DedicatedTenancyModificationStateEnum enum +func DedicatedTenancyModificationStateEnum_Values() []string { + return []string{ + DedicatedTenancyModificationStateEnumPending, + DedicatedTenancyModificationStateEnumCompleted, + DedicatedTenancyModificationStateEnumFailed, + } +} + const ( // DedicatedTenancySupportEnumEnabled is a DedicatedTenancySupportEnum enum value DedicatedTenancySupportEnumEnabled = "ENABLED" ) +// DedicatedTenancySupportEnum_Values returns all elements of the DedicatedTenancySupportEnum enum +func DedicatedTenancySupportEnum_Values() []string { + return []string{ + DedicatedTenancySupportEnumEnabled, + } +} + const ( // DedicatedTenancySupportResultEnumEnabled is a DedicatedTenancySupportResultEnum enum value DedicatedTenancySupportResultEnumEnabled = "ENABLED" @@ -9579,6 +10085,30 @@ const ( DedicatedTenancySupportResultEnumDisabled = "DISABLED" ) +// DedicatedTenancySupportResultEnum_Values returns all elements of the DedicatedTenancySupportResultEnum enum +func DedicatedTenancySupportResultEnum_Values() []string { + return []string{ + DedicatedTenancySupportResultEnumEnabled, + DedicatedTenancySupportResultEnumDisabled, + } +} + +const ( + // ImageTypeOwned is a ImageType enum value + ImageTypeOwned = "OWNED" + + // ImageTypeShared is a ImageType enum value + ImageTypeShared = "SHARED" +) + +// ImageType_Values returns all elements of the ImageType enum +func ImageType_Values() []string { + return []string{ + ImageTypeOwned, + ImageTypeShared, + } +} + const ( // ModificationResourceEnumRootVolume is a ModificationResourceEnum enum value ModificationResourceEnumRootVolume = "ROOT_VOLUME" @@ -9590,6 +10120,15 @@ const ( ModificationResourceEnumComputeType = "COMPUTE_TYPE" ) +// ModificationResourceEnum_Values returns all elements of the ModificationResourceEnum enum +func ModificationResourceEnum_Values() []string { + return []string{ + ModificationResourceEnumRootVolume, + ModificationResourceEnumUserVolume, + ModificationResourceEnumComputeType, + } +} + const ( // ModificationStateEnumUpdateInitiated is a ModificationStateEnum enum value ModificationStateEnumUpdateInitiated = "UPDATE_INITIATED" @@ -9598,6 +10137,14 @@ const ( ModificationStateEnumUpdateInProgress = "UPDATE_IN_PROGRESS" ) +// ModificationStateEnum_Values returns all elements of the ModificationStateEnum enum +func ModificationStateEnum_Values() []string { + return []string{ + ModificationStateEnumUpdateInitiated, + ModificationStateEnumUpdateInProgress, + } +} + const ( // OperatingSystemTypeWindows is a OperatingSystemType enum value OperatingSystemTypeWindows = "WINDOWS" @@ -9606,6 +10153,14 @@ const ( OperatingSystemTypeLinux = "LINUX" ) +// OperatingSystemType_Values returns all elements of the OperatingSystemType enum +func OperatingSystemType_Values() []string { + return []string{ + OperatingSystemTypeWindows, + OperatingSystemTypeLinux, + } +} + const ( // ReconnectEnumEnabled is a ReconnectEnum enum value ReconnectEnumEnabled = "ENABLED" @@ -9614,6 +10169,14 @@ const ( ReconnectEnumDisabled = "DISABLED" ) +// ReconnectEnum_Values returns all elements of the ReconnectEnum enum +func ReconnectEnum_Values() []string { + return []string{ + ReconnectEnumEnabled, + ReconnectEnumDisabled, + } +} + const ( // RunningModeAutoStop is a RunningMode enum value RunningModeAutoStop = "AUTO_STOP" @@ -9622,6 +10185,14 @@ const ( RunningModeAlwaysOn = "ALWAYS_ON" ) +// RunningMode_Values returns all elements of the RunningMode enum +func RunningMode_Values() []string { + return []string{ + RunningModeAutoStop, + RunningModeAlwaysOn, + } +} + const ( // TargetWorkspaceStateAvailable is a TargetWorkspaceState enum value TargetWorkspaceStateAvailable = "AVAILABLE" @@ -9630,6 +10201,14 @@ const ( TargetWorkspaceStateAdminMaintenance = "ADMIN_MAINTENANCE" ) +// TargetWorkspaceState_Values returns all elements of the TargetWorkspaceState enum +func TargetWorkspaceState_Values() []string { + return []string{ + TargetWorkspaceStateAvailable, + TargetWorkspaceStateAdminMaintenance, + } +} + const ( // TenancyDedicated is a Tenancy enum value TenancyDedicated = "DEDICATED" @@ -9638,6 +10217,14 @@ const ( TenancyShared = "SHARED" ) +// Tenancy_Values returns all elements of the Tenancy enum +func Tenancy_Values() []string { + return []string{ + TenancyDedicated, + TenancyShared, + } +} + const ( // WorkspaceDirectoryStateRegistering is a WorkspaceDirectoryState enum value WorkspaceDirectoryStateRegistering = "REGISTERING" @@ -9655,6 +10242,17 @@ const ( WorkspaceDirectoryStateError = "ERROR" ) +// WorkspaceDirectoryState_Values returns all elements of the WorkspaceDirectoryState enum +func WorkspaceDirectoryState_Values() []string { + return []string{ + WorkspaceDirectoryStateRegistering, + WorkspaceDirectoryStateRegistered, + WorkspaceDirectoryStateDeregistering, + WorkspaceDirectoryStateDeregistered, + WorkspaceDirectoryStateError, + } +} + const ( // WorkspaceDirectoryTypeSimpleAd is a WorkspaceDirectoryType enum value WorkspaceDirectoryTypeSimpleAd = "SIMPLE_AD" @@ -9663,6 +10261,14 @@ const ( WorkspaceDirectoryTypeAdConnector = "AD_CONNECTOR" ) +// WorkspaceDirectoryType_Values returns all elements of the WorkspaceDirectoryType enum +func WorkspaceDirectoryType_Values() []string { + return []string{ + WorkspaceDirectoryTypeSimpleAd, + WorkspaceDirectoryTypeAdConnector, + } +} + const ( // WorkspaceImageIngestionProcessByolRegular is a WorkspaceImageIngestionProcess enum value WorkspaceImageIngestionProcessByolRegular = "BYOL_REGULAR" @@ -9674,6 +10280,15 @@ const ( WorkspaceImageIngestionProcessByolGraphicspro = "BYOL_GRAPHICSPRO" ) +// WorkspaceImageIngestionProcess_Values returns all elements of the WorkspaceImageIngestionProcess enum +func WorkspaceImageIngestionProcess_Values() []string { + return []string{ + WorkspaceImageIngestionProcessByolRegular, + WorkspaceImageIngestionProcessByolGraphics, + WorkspaceImageIngestionProcessByolGraphicspro, + } +} + const ( // WorkspaceImageRequiredTenancyDefault is a WorkspaceImageRequiredTenancy enum value WorkspaceImageRequiredTenancyDefault = "DEFAULT" @@ -9682,6 +10297,14 @@ const ( WorkspaceImageRequiredTenancyDedicated = "DEDICATED" ) +// WorkspaceImageRequiredTenancy_Values returns all elements of the WorkspaceImageRequiredTenancy enum +func WorkspaceImageRequiredTenancy_Values() []string { + return []string{ + WorkspaceImageRequiredTenancyDefault, + WorkspaceImageRequiredTenancyDedicated, + } +} + const ( // WorkspaceImageStateAvailable is a WorkspaceImageState enum value WorkspaceImageStateAvailable = "AVAILABLE" @@ -9693,6 +10316,15 @@ const ( WorkspaceImageStateError = "ERROR" ) +// WorkspaceImageState_Values returns all elements of the WorkspaceImageState enum +func WorkspaceImageState_Values() []string { + return []string{ + WorkspaceImageStateAvailable, + WorkspaceImageStatePending, + WorkspaceImageStateError, + } +} + const ( // WorkspaceStatePending is a WorkspaceState enum value WorkspaceStatePending = "PENDING" @@ -9745,3 +10377,26 @@ const ( // WorkspaceStateError is a WorkspaceState enum value WorkspaceStateError = "ERROR" ) + +// WorkspaceState_Values returns all elements of the WorkspaceState enum +func WorkspaceState_Values() []string { + return []string{ + WorkspaceStatePending, + WorkspaceStateAvailable, + WorkspaceStateImpaired, + WorkspaceStateUnhealthy, + WorkspaceStateRebooting, + WorkspaceStateStarting, + WorkspaceStateRebuilding, + WorkspaceStateRestoring, + WorkspaceStateMaintenance, + WorkspaceStateAdminMaintenance, + WorkspaceStateTerminating, + WorkspaceStateTerminated, + WorkspaceStateSuspended, + WorkspaceStateUpdating, + WorkspaceStateStopping, + WorkspaceStateStopped, + WorkspaceStateError, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/xray/api.go b/vendor/github.com/aws/aws-sdk-go/service/xray/api.go index 9092ddb1b4d..18ff3dd6e38 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/xray/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/xray/api.go @@ -6603,6 +6603,14 @@ const ( EncryptionStatusActive = "ACTIVE" ) +// EncryptionStatus_Values returns all elements of the EncryptionStatus enum +func EncryptionStatus_Values() []string { + return []string{ + EncryptionStatusUpdating, + EncryptionStatusActive, + } +} + const ( // EncryptionTypeNone is a EncryptionType enum value EncryptionTypeNone = "NONE" @@ -6611,6 +6619,14 @@ const ( EncryptionTypeKms = "KMS" ) +// EncryptionType_Values returns all elements of the EncryptionType enum +func EncryptionType_Values() []string { + return []string{ + EncryptionTypeNone, + EncryptionTypeKms, + } +} + const ( // SamplingStrategyNamePartialScan is a SamplingStrategyName enum value SamplingStrategyNamePartialScan = "PartialScan" @@ -6619,6 +6635,14 @@ const ( SamplingStrategyNameFixedRate = "FixedRate" ) +// SamplingStrategyName_Values returns all elements of the SamplingStrategyName enum +func SamplingStrategyName_Values() []string { + return []string{ + SamplingStrategyNamePartialScan, + SamplingStrategyNameFixedRate, + } +} + const ( // TimeRangeTypeTraceId is a TimeRangeType enum value TimeRangeTypeTraceId = "TraceId" @@ -6626,3 +6650,11 @@ const ( // TimeRangeTypeEvent is a TimeRangeType enum value TimeRangeTypeEvent = "Event" ) + +// TimeRangeType_Values returns all elements of the TimeRangeType enum +func TimeRangeType_Values() []string { + return []string{ + TimeRangeTypeTraceId, + TimeRangeTypeEvent, + } +} diff --git a/vendor/github.com/bflad/tfproviderdocs/.goreleaser.yml b/vendor/github.com/bflad/tfproviderdocs/.goreleaser.yml index dccedaf10c3..d4a23662ffe 100644 --- a/vendor/github.com/bflad/tfproviderdocs/.goreleaser.yml +++ b/vendor/github.com/bflad/tfproviderdocs/.goreleaser.yml @@ -12,7 +12,7 @@ brews: - go description: Terraform Provider Documentation Tool folder: Formula - github: + tap: owner: bflad name: homebrew-tap homepage: https://github.com/bflad/tfproviderdocs @@ -46,6 +46,9 @@ dockers: - 'bflad/tfproviderdocs:{{ .Version }}' - 'bflad/tfproviderdocs:{{ .Major }}.{{ .Minor }}' - 'bflad/tfproviderdocs:latest' +milestones: +- + close: true signs: - artifacts: checksum diff --git a/vendor/github.com/bflad/tfproviderdocs/CHANGELOG.md b/vendor/github.com/bflad/tfproviderdocs/CHANGELOG.md index 515bfc5325e..42b193d0cf4 100644 --- a/vendor/github.com/bflad/tfproviderdocs/CHANGELOG.md +++ b/vendor/github.com/bflad/tfproviderdocs/CHANGELOG.md @@ -1,3 +1,23 @@ +# v0.7.0 + +ENHANCEMENTS + +* check: Match increased registry max number of files limit from 1000 to 2000 + +BUG FIXES + +* check: Allow legacy directory structure without side navigation (use `-require-side-navigation` flag to keep deprecated old behavior) +* check: Return correct valid extensions list with registry directory structure (#38) + +# v0.6.0 + +ENHANCEMENTS + +* check: Add `-ignore-file-mismatch-data-sources` option +* check: Add `-ignore-file-mismatch-resources` option +* check: Add `-ignore-file-missing-data-sources` option +* check: Add `-ignore-file-missing-resources` option + # v0.5.3 BUG FIXES diff --git a/vendor/github.com/bflad/tfproviderdocs/check/check.go b/vendor/github.com/bflad/tfproviderdocs/check/check.go index fabca3661d3..ec68e5af9b7 100644 --- a/vendor/github.com/bflad/tfproviderdocs/check/check.go +++ b/vendor/github.com/bflad/tfproviderdocs/check/check.go @@ -4,7 +4,6 @@ import ( "sort" "github.com/hashicorp/go-multierror" - tfjson "github.com/hashicorp/terraform-json" ) const ( @@ -13,7 +12,7 @@ const ( // Terraform Registry Storage Limits // https://www.terraform.io/docs/registry/providers/docs.html#storage-limits - RegistryMaximumNumberOfFiles = 1000 + RegistryMaximumNumberOfFiles = 2000 RegistryMaximumSizeOfFile = 500000 // 500KB ) @@ -22,6 +21,8 @@ type Check struct { } type CheckOptions struct { + DataSourceFileMismatch *FileMismatchOptions + LegacyDataSourceFile *LegacyDataSourceFileOptions LegacyGuideFile *LegacyGuideFileOptions LegacyIndexFile *LegacyIndexFileOptions @@ -34,8 +35,7 @@ type CheckOptions struct { RegistryIndexFile *RegistryIndexFileOptions RegistryResourceFile *RegistryResourceFileOptions - SchemaDataSources map[string]*tfjson.Schema - SchemaResources map[string]*tfjson.Schema + ResourceFileMismatch *FileMismatchOptions SideNavigation *SideNavigationOptions } @@ -65,37 +65,13 @@ func (check *Check) Run(directories map[string][]string) error { return err } - if len(check.Options.SchemaDataSources) > 0 && false { - var dataSourceFiles []string - - if files, ok := directories[RegistryDataSourcesDirectory]; ok { - dataSourceFiles = files - } else if files, ok := directories[LegacyDataSourcesDirectory]; ok { - dataSourceFiles = files - } - - if err := ResourceFileMismatchCheck(check.Options.ProviderName, ResourceTypeDataSource, check.Options.SchemaDataSources, dataSourceFiles); err != nil { - return err - } - } - - if len(check.Options.SchemaResources) > 0 { - var resourceFiles []string - - if files, ok := directories[RegistryResourcesDirectory]; ok { - resourceFiles = files - } else if files, ok := directories[LegacyResourcesDirectory]; ok { - resourceFiles = files - } - - if err := ResourceFileMismatchCheck(check.Options.ProviderName, ResourceTypeResource, check.Options.SchemaResources, resourceFiles); err != nil { - return err - } - } - var result *multierror.Error if files, ok := directories[RegistryDataSourcesDirectory]; ok { + if err := NewFileMismatchCheck(check.Options.DataSourceFileMismatch).Run(files); err != nil { + result = multierror.Append(result, err) + } + if err := NewRegistryDataSourceFileCheck(check.Options.RegistryDataSourceFile).RunAll(files); err != nil { result = multierror.Append(result, err) } @@ -114,6 +90,10 @@ func (check *Check) Run(directories map[string][]string) error { } if files, ok := directories[RegistryResourcesDirectory]; ok { + if err := NewFileMismatchCheck(check.Options.ResourceFileMismatch).Run(files); err != nil { + result = multierror.Append(result, err) + } + if err := NewRegistryResourceFileCheck(check.Options.RegistryResourceFile).RunAll(files); err != nil { result = multierror.Append(result, err) } @@ -123,6 +103,10 @@ func (check *Check) Run(directories map[string][]string) error { legacyResourcesFiles, legacyResourcesOk := directories[LegacyResourcesDirectory] if legacyDataSourcesOk { + if err := NewFileMismatchCheck(check.Options.DataSourceFileMismatch).Run(legacyDataSourcesFiles); err != nil { + result = multierror.Append(result, err) + } + if err := NewLegacyDataSourceFileCheck(check.Options.LegacyDataSourceFile).RunAll(legacyDataSourcesFiles); err != nil { result = multierror.Append(result, err) } @@ -141,6 +125,10 @@ func (check *Check) Run(directories map[string][]string) error { } if legacyResourcesOk { + if err := NewFileMismatchCheck(check.Options.ResourceFileMismatch).Run(legacyResourcesFiles); err != nil { + result = multierror.Append(result, err) + } + if err := NewLegacyResourceFileCheck(check.Options.LegacyResourceFile).RunAll(legacyResourcesFiles); err != nil { result = multierror.Append(result, err) } diff --git a/vendor/github.com/bflad/tfproviderdocs/check/file_extension.go b/vendor/github.com/bflad/tfproviderdocs/check/file_extension.go index 01ee1454a6f..fb0702eecfb 100644 --- a/vendor/github.com/bflad/tfproviderdocs/check/file_extension.go +++ b/vendor/github.com/bflad/tfproviderdocs/check/file_extension.go @@ -35,7 +35,7 @@ func LegacyFileExtensionCheck(path string) error { func RegistryFileExtensionCheck(path string) error { if !FilePathEndsWithExtensionFrom(path, ValidRegistryFileExtensions) { - return fmt.Errorf("file does not end with a valid extension, valid extensions: %v", ValidLegacyFileExtensions) + return fmt.Errorf("file does not end with a valid extension, valid extensions: %v", ValidRegistryFileExtensions) } return nil diff --git a/vendor/github.com/bflad/tfproviderdocs/check/file_mismatch.go b/vendor/github.com/bflad/tfproviderdocs/check/file_mismatch.go index b5c4868dd36..85898240300 100644 --- a/vendor/github.com/bflad/tfproviderdocs/check/file_mismatch.go +++ b/vendor/github.com/bflad/tfproviderdocs/check/file_mismatch.go @@ -2,26 +2,79 @@ package check import ( "fmt" + "log" "sort" "github.com/hashicorp/go-multierror" tfjson "github.com/hashicorp/terraform-json" ) -func ResourceFileMismatchCheck(providerName string, resourceType string, schemaResources map[string]*tfjson.Schema, files []string) error { +type FileMismatchOptions struct { + *FileOptions + + IgnoreFileMismatch []string + + IgnoreFileMissing []string + + ProviderName string + + ResourceType string + + Schemas map[string]*tfjson.Schema +} + +type FileMismatchCheck struct { + Options *FileMismatchOptions +} + +func NewFileMismatchCheck(opts *FileMismatchOptions) *FileMismatchCheck { + check := &FileMismatchCheck{ + Options: opts, + } + + if check.Options == nil { + check.Options = &FileMismatchOptions{} + } + + if check.Options.FileOptions == nil { + check.Options.FileOptions = &FileOptions{} + } + + return check +} + +func (check *FileMismatchCheck) Run(files []string) error { + if len(files) == 0 { + log.Printf("[DEBUG] Skipping %s file mismatch checks due to missing file list", check.Options.ResourceType) + return nil + } + + if len(check.Options.Schemas) == 0 { + log.Printf("[DEBUG] Skipping %s file mismatch checks due to missing schemas", check.Options.ResourceType) + return nil + } + var extraFiles []string var missingFiles []string for _, file := range files { - if fileHasResource(schemaResources, providerName, file) { + if fileHasResource(check.Options.Schemas, check.Options.ProviderName, file) { + continue + } + + if check.IgnoreFileMismatch(file) { continue } extraFiles = append(extraFiles, file) } - for _, resourceName := range resourceNames(schemaResources) { - if resourceHasFile(files, providerName, resourceName) { + for _, resourceName := range resourceNames(check.Options.Schemas) { + if resourceHasFile(files, check.Options.ProviderName, resourceName) { + continue + } + + if check.IgnoreFileMissing(resourceName) { continue } @@ -31,18 +84,38 @@ func ResourceFileMismatchCheck(providerName string, resourceType string, schemaR var result *multierror.Error for _, extraFile := range extraFiles { - err := fmt.Errorf("matching %s for documentation file (%s) not found, file is extraneous or incorrectly named", resourceType, extraFile) + err := fmt.Errorf("matching %s for documentation file (%s) not found, file is extraneous or incorrectly named", check.Options.ResourceType, extraFile) result = multierror.Append(result, err) } for _, missingFile := range missingFiles { - err := fmt.Errorf("missing documentation file for %s: %s", resourceType, missingFile) + err := fmt.Errorf("missing documentation file for %s: %s", check.Options.ResourceType, missingFile) result = multierror.Append(result, err) } return result.ErrorOrNil() } +func (check *FileMismatchCheck) IgnoreFileMismatch(file string) bool { + for _, ignoreResourceName := range check.Options.IgnoreFileMismatch { + if ignoreResourceName == fileResourceName(check.Options.ProviderName, file) { + return true + } + } + + return false +} + +func (check *FileMismatchCheck) IgnoreFileMissing(resourceName string) bool { + for _, ignoreResourceName := range check.Options.IgnoreFileMissing { + if ignoreResourceName == resourceName { + return true + } + } + + return false +} + func fileHasResource(schemaResources map[string]*tfjson.Schema, providerName, file string) bool { if _, ok := schemaResources[fileResourceName(providerName, file)]; ok { return true diff --git a/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation/sidenavigation.go b/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation/sidenavigation.go index e64fb7d8c95..ebf6d43fc89 100644 --- a/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation/sidenavigation.go +++ b/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation/sidenavigation.go @@ -3,7 +3,6 @@ package sidenavigation import ( "fmt" "io/ioutil" - "log" "regexp" "strings" @@ -48,7 +47,7 @@ func FindFile(path string) (*SideNavigation, error) { fileContents, err := ioutil.ReadFile(path) if err != nil { - log.Fatalf("error opening file (%s): %s", path, err) + return nil, fmt.Errorf("error opening file (%s): %w", path, err) } return FindString(string(fileContents)) diff --git a/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_link.go b/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_link.go index 99e61a7a849..979a78e860c 100644 --- a/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_link.go +++ b/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_link.go @@ -8,7 +8,7 @@ import ( ) func SideNavigationLinkCheck(opts *SideNavigationOptions) error { - if opts == nil || opts.ProviderName == "" { + if opts == nil || opts.ProviderName == "" || !opts.Require { return nil } diff --git a/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_mismatch.go b/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_mismatch.go index be030ed164f..16185a6818d 100644 --- a/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_mismatch.go +++ b/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_mismatch.go @@ -8,7 +8,7 @@ import ( ) func SideNavigationMismatchCheck(opts *SideNavigationOptions, dataSourceFiles []string, resourceFiles []string) error { - if opts == nil || opts.ProviderName == "" { + if opts == nil || opts.ProviderName == "" || !opts.Require { return nil } diff --git a/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_options.go b/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_options.go index df9140cf5eb..dd4ff710d85 100644 --- a/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_options.go +++ b/vendor/github.com/bflad/tfproviderdocs/check/sidenavigation_options.go @@ -6,6 +6,8 @@ type SideNavigationOptions struct { IgnoreDataSources []string IgnoreResources []string + Require bool + ProviderName string } diff --git a/vendor/github.com/bflad/tfproviderdocs/command/check.go b/vendor/github.com/bflad/tfproviderdocs/command/check.go index d83d8aca8f0..c5a305b4516 100644 --- a/vendor/github.com/bflad/tfproviderdocs/command/check.go +++ b/vendor/github.com/bflad/tfproviderdocs/command/check.go @@ -24,6 +24,10 @@ type CheckCommandConfig struct { AllowedGuideSubcategoriesFile string AllowedResourceSubcategories string AllowedResourceSubcategoriesFile string + IgnoreFileMismatchDataSources string + IgnoreFileMismatchResources string + IgnoreFileMissingDataSources string + IgnoreFileMissingResources string IgnoreSideNavigationDataSources string IgnoreSideNavigationResources string LogLevel string @@ -32,6 +36,7 @@ type CheckCommandConfig struct { ProvidersSchemaJson string RequireGuideSubcategory bool RequireResourceSubcategory bool + RequireSideNavigation bool } // CheckCommand is a Command implementation @@ -47,12 +52,17 @@ func (*CheckCommand) Help() string { fmt.Fprintf(opts, CommandHelpOptionFormat, "-allowed-guide-subcategories-file", "Path to newline separated file of allowed guide frontmatter subcategories.") fmt.Fprintf(opts, CommandHelpOptionFormat, "-allowed-resource-subcategories", "Comma separated list of allowed data source and resource frontmatter subcategories.") fmt.Fprintf(opts, CommandHelpOptionFormat, "-allowed-resource-subcategories-file", "Path to newline separated file of allowed data source and resource frontmatter subcategories.") - fmt.Fprintf(opts, CommandHelpOptionFormat, "-ignore-side-navigation-data-sources", "Comma separated list of data sources to ignore side navigation validation.") - fmt.Fprintf(opts, CommandHelpOptionFormat, "-ignore-side-navigation-resources", "Comma separated list of resources to ignore side navigation validation.") + fmt.Fprintf(opts, CommandHelpOptionFormat, "-ignore-file-mismatch-data-sources", "Comma separated list of data sources to ignore mismatched/extra files.") + fmt.Fprintf(opts, CommandHelpOptionFormat, "-ignore-file-mismatch-resources", "Comma separated list of resources to ignore mismatched/extra files.") + fmt.Fprintf(opts, CommandHelpOptionFormat, "-ignore-file-missing-data-sources", "Comma separated list of data sources to ignore missing files.") + fmt.Fprintf(opts, CommandHelpOptionFormat, "-ignore-file-missing-resources", "Comma separated list of resources to ignore missing files.") + fmt.Fprintf(opts, CommandHelpOptionFormat, "-ignore-side-navigation-data-sources", "Comma separated list of data sources to ignore side navigation (legacy terraform.io ERB file) validation.") + fmt.Fprintf(opts, CommandHelpOptionFormat, "-ignore-side-navigation-resources", "Comma separated list of resources to ignore side navigation (legacy terraform.io ERB file) validation.") fmt.Fprintf(opts, CommandHelpOptionFormat, "-provider-name", "Terraform Provider name. Automatically determined if current working directory or provided path is prefixed with terraform-provider-*.") fmt.Fprintf(opts, CommandHelpOptionFormat, "-providers-schema-json", "Path to terraform providers schema -json file. Enables enhanced validations.") fmt.Fprintf(opts, CommandHelpOptionFormat, "-require-guide-subcategory", "Require guide frontmatter subcategory.") fmt.Fprintf(opts, CommandHelpOptionFormat, "-require-resource-subcategory", "Require data source and resource frontmatter subcategory.") + fmt.Fprintf(opts, CommandHelpOptionFormat, "-require-side-navigation", "Require side navigation (legacy terraform.io ERB file).") opts.Flush() helpText := fmt.Sprintf(` @@ -80,12 +90,17 @@ func (c *CheckCommand) Run(args []string) int { flags.StringVar(&config.AllowedGuideSubcategoriesFile, "allowed-guide-subcategories-file", "", "") flags.StringVar(&config.AllowedResourceSubcategories, "allowed-resource-subcategories", "", "") flags.StringVar(&config.AllowedResourceSubcategoriesFile, "allowed-resource-subcategories-file", "", "") + flags.StringVar(&config.IgnoreFileMismatchDataSources, "ignore-file-mismatch-data-sources", "", "") + flags.StringVar(&config.IgnoreFileMismatchResources, "ignore-file-mismatch-resources", "", "") + flags.StringVar(&config.IgnoreFileMissingDataSources, "ignore-file-missing-data-sources", "", "") + flags.StringVar(&config.IgnoreFileMissingResources, "ignore-file-missing-resources", "", "") flags.StringVar(&config.IgnoreSideNavigationDataSources, "ignore-side-navigation-data-sources", "", "") flags.StringVar(&config.IgnoreSideNavigationResources, "ignore-side-navigation-resources", "", "") flags.StringVar(&config.ProviderName, "provider-name", "", "") flags.StringVar(&config.ProvidersSchemaJson, "providers-schema-json", "", "") flags.BoolVar(&config.RequireGuideSubcategory, "require-guide-subcategory", false, "") flags.BoolVar(&config.RequireResourceSubcategory, "require-resource-subcategory", false, "") + flags.BoolVar(&config.RequireSideNavigation, "require-side-navigation", false, "") if err := flags.Parse(args); err != nil { flags.Usage() @@ -131,8 +146,7 @@ func (c *CheckCommand) Run(args []string) int { return 1 } - var allowedGuideSubcategories, allowedResourceSubcategories, ignoreSideNavigationDataSources, ignoreSideNavigationResources []string - + var allowedGuideSubcategories []string if v := config.AllowedGuideSubcategories; v != "" { allowedGuideSubcategories = strings.Split(v, ",") } @@ -147,6 +161,7 @@ func (c *CheckCommand) Run(args []string) int { } } + var allowedResourceSubcategories []string if v := config.AllowedResourceSubcategories; v != "" { allowedResourceSubcategories = strings.Split(v, ",") } @@ -161,18 +176,68 @@ func (c *CheckCommand) Run(args []string) int { } } + var ignoreFileMismatchDataSources []string + if v := config.IgnoreFileMismatchDataSources; v != "" { + ignoreFileMismatchDataSources = strings.Split(v, ",") + } + + var ignoreFileMismatchResources []string + if v := config.IgnoreFileMismatchResources; v != "" { + ignoreFileMismatchResources = strings.Split(v, ",") + } + + var ignoreFileMissingDataSources []string + if v := config.IgnoreFileMissingDataSources; v != "" { + ignoreFileMissingDataSources = strings.Split(v, ",") + } + + var ignoreFileMissingResources []string + if v := config.IgnoreFileMissingResources; v != "" { + ignoreFileMissingResources = strings.Split(v, ",") + } + + var ignoreSideNavigationDataSources []string if v := config.IgnoreSideNavigationDataSources; v != "" { ignoreSideNavigationDataSources = strings.Split(v, ",") } + var ignoreSideNavigationResources []string if v := config.IgnoreSideNavigationResources; v != "" { ignoreSideNavigationResources = strings.Split(v, ",") } + var schemaDataSources, schemaResources map[string]*tfjson.Schema + if config.ProvidersSchemaJson != "" { + ps, err := providerSchemas(config.ProvidersSchemaJson) + + if err != nil { + c.Ui.Error(fmt.Sprintf("Error enabling Terraform Provider schema checks: %s", err)) + return 1 + } + + if config.ProviderName == "" { + msg := `Unknown provider name for enabling Terraform Provider schema checks. + +Check that the current working directory or provided path is prefixed with terraform-provider-*.` + c.Ui.Error(msg) + return 1 + } + + schemaDataSources = providerSchemasDataSources(ps, config.ProviderName) + schemaResources = providerSchemasResources(ps, config.ProviderName) + } + fileOpts := &check.FileOptions{ BasePath: config.Path, } checkOpts := &check.CheckOptions{ + DataSourceFileMismatch: &check.FileMismatchOptions{ + IgnoreFileMismatch: ignoreFileMismatchDataSources, + IgnoreFileMissing: ignoreFileMissingDataSources, + ProviderName: config.ProviderName, + ResourceType: check.ResourceTypeDataSource, + Schemas: schemaDataSources, + }, LegacyDataSourceFile: &check.LegacyDataSourceFileOptions{ FileOptions: fileOpts, FrontMatter: &check.FrontMatterOptions{ @@ -222,34 +287,22 @@ func (c *CheckCommand) Run(args []string) int { RequireSubcategory: config.RequireResourceSubcategory, }, }, + ResourceFileMismatch: &check.FileMismatchOptions{ + IgnoreFileMismatch: ignoreFileMismatchResources, + IgnoreFileMissing: ignoreFileMissingResources, + ProviderName: config.ProviderName, + ResourceType: check.ResourceTypeResource, + Schemas: schemaResources, + }, SideNavigation: &check.SideNavigationOptions{ FileOptions: fileOpts, IgnoreDataSources: ignoreSideNavigationDataSources, IgnoreResources: ignoreSideNavigationResources, + Require: config.RequireSideNavigation, ProviderName: config.ProviderName, }, } - if config.ProvidersSchemaJson != "" { - ps, err := providerSchemas(config.ProvidersSchemaJson) - - if err != nil { - c.Ui.Error(fmt.Sprintf("Error enabling Terraform Provider schema checks: %s", err)) - return 1 - } - - if config.ProviderName == "" { - msg := `Unknown provider name for enabling Terraform Provider schema checks. - -Check that the current working directory or provided path is prefixed with terraform-provider-*.` - c.Ui.Error(msg) - return 1 - } - - checkOpts.SchemaDataSources = providerSchemasDataSources(ps, config.ProviderName) - checkOpts.SchemaResources = providerSchemasResources(ps, config.ProviderName) - } - if err := check.NewCheck(checkOpts).Run(directories); err != nil { c.Ui.Error(fmt.Sprintf("Error checking Terraform Provider documentation: %s", err)) return 1 diff --git a/vendor/github.com/bflad/tfproviderdocs/go.mod b/vendor/github.com/bflad/tfproviderdocs/go.mod index 11196dd4f7a..94e895337aa 100644 --- a/vendor/github.com/bflad/tfproviderdocs/go.mod +++ b/vendor/github.com/bflad/tfproviderdocs/go.mod @@ -6,7 +6,7 @@ require ( github.com/bmatcuk/doublestar v1.2.1 github.com/hashicorp/go-hclog v0.10.0 github.com/hashicorp/go-multierror v1.0.0 - github.com/hashicorp/terraform-json v0.3.1 + github.com/hashicorp/terraform-json v0.5.0 github.com/mattn/go-colorable v0.1.4 github.com/mitchellh/cli v1.0.0 golang.org/x/net v0.0.0-20180811021610-c39426892332 diff --git a/vendor/github.com/bflad/tfproviderdocs/go.sum b/vendor/github.com/bflad/tfproviderdocs/go.sum index 915d3453fb2..ed5ba548b98 100644 --- a/vendor/github.com/bflad/tfproviderdocs/go.sum +++ b/vendor/github.com/bflad/tfproviderdocs/go.sum @@ -10,14 +10,16 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-hclog v0.10.0 h1:b86HUuA126IcSHyC55WjPo7KtCOVeTCKIjr+3lBhPxI= github.com/hashicorp/go-hclog v0.10.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= -github.com/hashicorp/terraform-json v0.3.1 h1:vRiOLck4YX4UqzljVhdQKsVLixX4L+Pgnm/q+xu6QvE= -github.com/hashicorp/terraform-json v0.3.1/go.mod h1:MdwQStcJb00ht55L/2YH0ypAO9RNtczJ1MaUlf+gJcg= +github.com/hashicorp/terraform-json v0.5.0 h1:7TV3/F3y7QVSuN4r9BEXqnWqrAyeOtON8f0wvREtyzs= +github.com/hashicorp/terraform-json v0.5.0/go.mod h1:eAbqb4w0pSlRmdvl8fOyHAi/+8jnkVYN28gJkSJrLhU= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= @@ -40,8 +42,8 @@ github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndr github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= -github.com/zclconf/go-cty v0.0.0-20190430221426-d36a6f0dbffd h1:NZOOU7h+pDtcKo6xlqm8PwnarS8nJ+6+I83jT8ZfLPI= -github.com/zclconf/go-cty v0.0.0-20190430221426-d36a6f0dbffd/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= +github.com/zclconf/go-cty v1.2.1 h1:vGMsygfmeCl4Xb6OA5U5XVAaQZ69FvoG7X2jUtQujb8= +github.com/zclconf/go-cty v1.2.1/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= golang.org/x/net v0.0.0-20180811021610-c39426892332 h1:efGso+ep0DjyCBJPjvoz0HI6UldX4Md2F1rZFe1ir0E= golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= diff --git a/vendor/github.com/bflad/tfproviderdocs/version/version.go b/vendor/github.com/bflad/tfproviderdocs/version/version.go index 97f2848c8b4..cb929eeb22d 100644 --- a/vendor/github.com/bflad/tfproviderdocs/version/version.go +++ b/vendor/github.com/bflad/tfproviderdocs/version/version.go @@ -11,7 +11,7 @@ var ( GitDescribe string // The main version number that is being run at the moment. - Version = "0.5.3" + Version = "0.7.0" // 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/vendor/github.com/bflad/tfproviderlint/helper/analysisutils/stdlib_analyzers.go b/vendor/github.com/bflad/tfproviderlint/helper/analysisutils/stdlib_analyzers.go new file mode 100644 index 00000000000..df0a1dbd238 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/helper/analysisutils/stdlib_analyzers.go @@ -0,0 +1,23 @@ +package analysisutils + +import ( + "fmt" + "go/ast" + "reflect" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" +) + +// StdlibFunctionCallExprAnalyzer returns an Analyzer for standard library function *ast.CallExpr +func StdlibFunctionCallExprAnalyzer(analyzerName string, packagePath string, functionName string) *analysis.Analyzer { + return &analysis.Analyzer{ + Name: analyzerName, + Doc: fmt.Sprintf("find %s.%s() calls for later passes", packagePath, functionName), + Requires: []*analysis.Analyzer{ + inspect.Analyzer, + }, + Run: StdlibFunctionCallExprRunner(packagePath, functionName), + ResultType: reflect.TypeOf([]*ast.CallExpr{}), + } +} diff --git a/vendor/github.com/bflad/tfproviderlint/helper/analysisutils/stdlib_runners.go b/vendor/github.com/bflad/tfproviderlint/helper/analysisutils/stdlib_runners.go new file mode 100644 index 00000000000..36ad4bf8687 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/helper/analysisutils/stdlib_runners.go @@ -0,0 +1,33 @@ +package analysisutils + +import ( + "go/ast" + + "github.com/bflad/tfproviderlint/helper/astutils" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +// StdlibFunctionCallExprRunner returns an Analyzer runner for function *ast.CallExpr +func StdlibFunctionCallExprRunner(packagePath string, functionName string) func(*analysis.Pass) (interface{}, error) { + return func(pass *analysis.Pass) (interface{}, error) { + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + nodeFilter := []ast.Node{ + (*ast.CallExpr)(nil), + } + var result []*ast.CallExpr + + inspect.Preorder(nodeFilter, func(n ast.Node) { + callExpr := n.(*ast.CallExpr) + + if !astutils.IsStdlibPackageFunc(callExpr.Fun, pass.TypesInfo, packagePath, functionName) { + return + } + + result = append(result, callExpr) + }) + + return result, nil + } +} diff --git a/vendor/github.com/bflad/tfproviderlint/helper/astutils/fieldlist.go b/vendor/github.com/bflad/tfproviderlint/helper/astutils/fieldlist.go index 4b6c45802e5..b44d3b9d23d 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/astutils/fieldlist.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/astutils/fieldlist.go @@ -77,7 +77,20 @@ func IsFieldListType(fieldList *ast.FieldList, position int, exprFunc func(ast.E return t != nil && exprFunc(*t) } +// IsFieldListTypeModulePackageType returns true if the field at position is present and matches expected module and package type +// +// This function automatically handles Go module versioning in import paths. +// To explicitly check an import path, use IsFieldListTypePackageType instead. +func IsFieldListTypeModulePackageType(fieldList *ast.FieldList, position int, info *types.Info, module string, packageSuffix string, typeName string) bool { + t := FieldListType(fieldList, position) + + return t != nil && IsModulePackageFunctionFieldListType(*t, info, module, packageSuffix, typeName) +} + // IsFieldListTypePackageType returns true if the field at position is present and matches expected package type +// +// This function checks an explicit import path. To allow any Go module version +// in the import path, use IsFieldListTypeModulePackageType instead. func IsFieldListTypePackageType(fieldList *ast.FieldList, position int, info *types.Info, packageSuffix string, typeName string) bool { t := FieldListType(fieldList, position) diff --git a/vendor/github.com/bflad/tfproviderlint/helper/astutils/package.go b/vendor/github.com/bflad/tfproviderlint/helper/astutils/package.go index 00eaa78a787..e0de1b29396 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/astutils/package.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/astutils/package.go @@ -1,12 +1,105 @@ package astutils import ( + "fmt" "go/ast" "go/types" + "regexp" "strings" ) +// IsModulePackageReceiverMethod returns true if the module and package suffix (for vendoring), receiver name, and method name match +// +// This function automatically handles Go module versioning in import paths. +// To explicitly check an import path, use IsPackageReceiverMethod instead. +func IsModulePackageReceiverMethod(e ast.Expr, info *types.Info, module string, packageSuffix string, receiverName string, methodName string) bool { + switch e := e.(type) { + case *ast.SelectorExpr: + if e.Sel.Name != methodName { + return false + } + + return IsModulePackageType(info.TypeOf(e.X), module, packageSuffix, receiverName) + } + + return false +} + +// IsModulePackageFunc returns true if the function package suffix (for vendoring) and name matches +// +// This function automatically handles Go module versioning in import paths. +// To explicitly check an import path, use IsPackageFunc instead. +func IsModulePackageFunc(e ast.Expr, info *types.Info, module string, packageSuffix string, funcName string) bool { + switch e := e.(type) { + case *ast.SelectorExpr: + if e.Sel.Name != funcName { + return false + } + + switch x := e.X.(type) { + case *ast.Ident: + return isModulePackagePath(module, packageSuffix, info.ObjectOf(x).(*types.PkgName).Imported().Path()) + } + case *ast.StarExpr: + return IsModulePackageFunc(e.X, info, module, packageSuffix, funcName) + } + + return false +} + +// IsModulePackageFunctionFieldListType returns true if the function parameter package suffix (for vendoring) and name matches +// +// This function automatically handles Go module versioning in import paths. +// To explicitly check an import path, use IsPackageFunctionFieldListType instead. +func IsModulePackageFunctionFieldListType(e ast.Expr, info *types.Info, module string, packageSuffix string, typeName string) bool { + switch e := e.(type) { + case *ast.SelectorExpr: + if e.Sel.Name != typeName { + return false + } + + switch x := e.X.(type) { + case *ast.Ident: + return isModulePackagePath(module, packageSuffix, info.ObjectOf(x).(*types.PkgName).Imported().Path()) + } + case *ast.StarExpr: + return IsModulePackageFunctionFieldListType(e.X, info, module, packageSuffix, typeName) + } + + return false +} + +// IsModulePackageNamedType returns if the type name matches and is from the package suffix +// +// This function automatically handles Go module versioning in import paths. +// To explicitly check an import path, use IsPackageNamedType instead. +func IsModulePackageNamedType(t *types.Named, module string, packageSuffix string, typeName string) bool { + if t.Obj().Name() != typeName { + return false + } + + return isModulePackagePath(module, packageSuffix, t.Obj().Pkg().Path()) +} + +// IsModulePackageType returns true if the type name can be matched and is from the package suffix +// +// This function automatically handles Go module versioning in import paths. +// To explicitly check an import path, use IsPackageType instead. +func IsModulePackageType(t types.Type, module string, packageSuffix string, typeName string) bool { + switch t := t.(type) { + case *types.Named: + return IsModulePackageNamedType(t, module, packageSuffix, typeName) + case *types.Pointer: + return IsModulePackageType(t.Elem(), module, packageSuffix, typeName) + } + + return false +} + // IsPackageReceiverMethod returns true if the package suffix (for vendoring), receiver name, and method name match +// +// This function checks an explicit import path. To allow any Go module version +// in the import path, use IsModulePackageReceiverMethod instead. func IsPackageReceiverMethod(e ast.Expr, info *types.Info, packageSuffix string, receiverName, methodName string) bool { switch e := e.(type) { case *ast.SelectorExpr: @@ -21,6 +114,9 @@ func IsPackageReceiverMethod(e ast.Expr, info *types.Info, packageSuffix string, } // IsPackageFunc returns true if the function package suffix (for vendoring) and name matches +// +// This function checks an explicit import path. To allow any Go module version +// in the import path, use IsModulePackageFunc instead. func IsPackageFunc(e ast.Expr, info *types.Info, packageSuffix string, funcName string) bool { switch e := e.(type) { case *ast.SelectorExpr: @@ -40,6 +136,9 @@ func IsPackageFunc(e ast.Expr, info *types.Info, packageSuffix string, funcName } // IsPackageFunctionFieldListType returns true if the function parameter package suffix (for vendoring) and name matches +// +// This function checks an explicit import path. To allow any Go module version +// in the import path, use IsModuleFunctionFieldListType instead. func IsPackageFunctionFieldListType(e ast.Expr, info *types.Info, packageSuffix string, typeName string) bool { switch e := e.(type) { case *ast.SelectorExpr: @@ -59,6 +158,9 @@ func IsPackageFunctionFieldListType(e ast.Expr, info *types.Info, packageSuffix } // IsPackageNamedType returns if the type name matches and is from the package suffix +// +// This function checks an explicit import path. To allow any Go module version +// in the import path, use IsModulePackageNamedType instead. func IsPackageNamedType(t *types.Named, packageSuffix string, typeName string) bool { if t.Obj().Name() != typeName { return false @@ -69,6 +171,9 @@ func IsPackageNamedType(t *types.Named, packageSuffix string, typeName string) b } // IsPackageType returns true if the type name can be matched and is from the package suffix +// +// This function checks an explicit import path. To allow any Go module version +// in the import path, use IsModulePackageType instead. func IsPackageType(t types.Type, packageSuffix string, typeName string) bool { switch t := t.(type) { case *types.Named: @@ -79,3 +184,97 @@ func IsPackageType(t types.Type, packageSuffix string, typeName string) bool { return false } + +// IsStdlibPackageReceiverMethod returns true if the package suffix (for vendoring), receiver name, and method name match +// +// This function checks an explicit import path without vendoring. To allow +// vendored paths, use IsPackageReceiverMethod instead. +func IsStdlibPackageReceiverMethod(e ast.Expr, info *types.Info, packagePath string, receiverName, methodName string) bool { + switch e := e.(type) { + case *ast.SelectorExpr: + if e.Sel.Name != methodName { + return false + } + + return IsStdlibPackageType(info.TypeOf(e.X), packagePath, receiverName) + } + + return false +} + +// IsStdlibPackageFunc returns true if the function package suffix (for vendoring) and name matches +// +// This function checks an explicit import path without vendoring. To allow +// vendored paths, use IsPackageFunc instead. +func IsStdlibPackageFunc(e ast.Expr, info *types.Info, packagePath string, funcName string) bool { + switch e := e.(type) { + case *ast.SelectorExpr: + if e.Sel.Name != funcName { + return false + } + + switch x := e.X.(type) { + case *ast.Ident: + return info.ObjectOf(x).(*types.PkgName).Imported().Path() == packagePath + } + case *ast.StarExpr: + return IsStdlibPackageFunc(e.X, info, packagePath, funcName) + } + + return false +} + +// IsStdlibPackageFunctionFieldListType returns true if the function parameter package suffix (for vendoring) and name matches +// +// This function checks an explicit import path without vendoring. To allow +// vendored paths, use IsPackageFunctionFieldListType instead. +func IsStdlibPackageFunctionFieldListType(e ast.Expr, info *types.Info, packagePath string, typeName string) bool { + switch e := e.(type) { + case *ast.SelectorExpr: + if e.Sel.Name != typeName { + return false + } + + switch x := e.X.(type) { + case *ast.Ident: + return info.ObjectOf(x).(*types.PkgName).Imported().Path() == packagePath + } + case *ast.StarExpr: + return IsStdlibPackageFunctionFieldListType(e.X, info, packagePath, typeName) + } + + return false +} + +// IsStdlibPackageNamedType returns if the type name matches and is from the package suffix +// +// This function checks an explicit import path without vendoring. To allow +// vendored paths, use IsPackageNamedType instead. +func IsStdlibPackageNamedType(t *types.Named, packagePath string, typeName string) bool { + if t.Obj().Name() != typeName { + return false + } + + return t.Obj().Pkg().Path() == packagePath +} + +// IsStdlibPackageType returns true if the type name can be matched and is from the package suffix +// +// This function checks an explicit import path without vendoring. To allow +// vendored paths, use IsPackageType instead. +func IsStdlibPackageType(t types.Type, packagePath string, typeName string) bool { + switch t := t.(type) { + case *types.Named: + return IsStdlibPackageNamedType(t, packagePath, typeName) + case *types.Pointer: + return IsStdlibPackageType(t.Elem(), packagePath, typeName) + } + + return false +} + +func isModulePackagePath(module string, packageSuffix string, path string) bool { + // Only check end of path due to vendoring + r := regexp.MustCompile(fmt.Sprintf("%s(/v[1-9][0-9]*)?/%s$", module, packageSuffix)) + return r.MatchString(path) +} diff --git a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/funcs.go b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/funcs.go index 81f78185dd4..1a9324a06fc 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/funcs.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/funcs.go @@ -5,6 +5,7 @@ const ( FuncNameComposeTestCheckFunc = `ComposeTestCheckFunc` FuncNameNonRetryableError = `NonRetryableError` FuncNameParallelTest = `ParallelTest` + FuncNamePrefixedUniqueId = `PrefixedUniqueId` FuncNameRetryableError = `RetryableError` FuncNameTest = `Test` FuncNameTestCheckNoResourceAttr = `TestCheckNoResourceAttr` @@ -14,4 +15,5 @@ const ( FuncNameTestCheckResourceAttrPtr = `TestCheckResourceAttrPtr` FuncNameTestCheckResourceAttrSet = `TestCheckResourceAttrSet` FuncNameTestMatchResourceAttr = `TestMatchResourceAttr` + FuncNameUniqueId = `UniqueId` ) diff --git a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/package.go b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/package.go index 522db1ec728..159526a3c79 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/package.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/package.go @@ -1,23 +1,37 @@ package resource import ( + "fmt" "go/ast" "go/types" "github.com/bflad/tfproviderlint/helper/astutils" + "github.com/bflad/tfproviderlint/helper/terraformtype" ) const ( - PackageName = `resource` - PackagePath = `github.com/hashicorp/terraform-plugin-sdk/helper/resource` + PackageModule = terraformtype.ModuleTerraformPluginSdk + PackageModulePath = `helper/resource` + PackageName = `resource` + PackagePath = PackageModule + `/` + PackageModulePath ) // IsFunc returns if the function call is in the resource package func IsFunc(e ast.Expr, info *types.Info, funcName string) bool { - return astutils.IsPackageFunc(e, info, PackagePath, funcName) + return astutils.IsModulePackageFunc(e, info, PackageModule, PackageModulePath, funcName) } // IsNamedType returns if the type name matches and is from the helper/resource package func IsNamedType(t *types.Named, typeName string) bool { - return astutils.IsPackageNamedType(t, PackagePath, typeName) + return astutils.IsModulePackageNamedType(t, PackageModule, PackageModulePath, typeName) +} + +// PackagePathVersion returns the import path for a module version +func PackagePathVersion(moduleVersion int) string { + switch moduleVersion { + case 0, 1: + return PackagePath + default: + return fmt.Sprintf("%s/v%d/%s", PackageModule, moduleVersion, PackageModulePath) + } } diff --git a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_retryerror.go b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_retryerror.go index 71c5b10af3a..1cbaa471f12 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_retryerror.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_retryerror.go @@ -5,7 +5,6 @@ import ( "go/types" "github.com/bflad/tfproviderlint/helper/astutils" - tfresource "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) const ( @@ -15,11 +14,21 @@ const ( TypeNameRetryError = `RetryError` ) +// retryErrorType is an internal representation of the SDK helper/resource.RetryError type +// +// This is used to prevent importing the real type since the project supports +// multiple versions of the Terraform Plugin SDK, while allowing passes to +// access the data in a familiar manner. +type retryErrorType struct { + Err error + Retryable bool +} + // RetryErrorInfo represents all gathered RetryError data for easier access type RetryErrorInfo struct { AstCompositeLit *ast.CompositeLit Fields map[string]*ast.KeyValueExpr - RetryError *tfresource.RetryError + RetryError *retryErrorType TypesInfo *types.Info } @@ -28,7 +37,7 @@ func NewRetryErrorInfo(cl *ast.CompositeLit, info *types.Info) *RetryErrorInfo { result := &RetryErrorInfo{ AstCompositeLit: cl, Fields: astutils.CompositeLitFields(cl), - RetryError: &tfresource.RetryError{}, + RetryError: &retryErrorType{}, TypesInfo: info, } diff --git a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_testcase.go b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_testcase.go index aeace7e1c62..bbad5f99725 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_testcase.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_testcase.go @@ -5,7 +5,6 @@ import ( "go/types" "github.com/bflad/tfproviderlint/helper/astutils" - tfresource "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) const ( @@ -22,11 +21,18 @@ const ( TypeNameTestCase = `TestCase` ) +// testCaseType is an internal representation of the SDK helper/resource.TestCase type +// +// This is used to prevent importing the real type since the project supports +// multiple versions of the Terraform Plugin SDK, while allowing passes to +// access the data in a familiar manner. +type testCaseType struct{} + // TestCaseInfo represents all gathered TestCase data for easier access type TestCaseInfo struct { AstCompositeLit *ast.CompositeLit Fields map[string]*ast.KeyValueExpr - TestCase *tfresource.TestCase + TestCase *testCaseType TypesInfo *types.Info } @@ -35,7 +41,7 @@ func NewTestCaseInfo(cl *ast.CompositeLit, info *types.Info) *TestCaseInfo { result := &TestCaseInfo{ AstCompositeLit: cl, Fields: astutils.CompositeLitFields(cl), - TestCase: &tfresource.TestCase{}, + TestCase: &testCaseType{}, TypesInfo: info, } diff --git a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_teststep.go b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_teststep.go index 7381cee76c3..d711ee533b7 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_teststep.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource/type_teststep.go @@ -5,7 +5,6 @@ import ( "go/types" "github.com/bflad/tfproviderlint/helper/astutils" - tfresource "github.com/hashicorp/terraform-plugin-sdk/helper/resource" ) const ( @@ -32,11 +31,18 @@ const ( TypeNameTestStep = `TestStep` ) +// testStepType is an internal representation of the SDK helper/resource.TestStep type +// +// This is used to prevent importing the real type since the project supports +// multiple versions of the Terraform Plugin SDK, while allowing passes to +// access the data in a familiar manner. +type testStepType struct{} + // TestStepInfo represents all gathered TestStep data for easier access type TestStepInfo struct { AstCompositeLit *ast.CompositeLit Fields map[string]*ast.KeyValueExpr - TestStep *tfresource.TestStep + TestStep *testStepType TypesInfo *types.Info } @@ -45,7 +51,7 @@ func NewTestStepInfo(cl *ast.CompositeLit, info *types.Info) *TestStepInfo { result := &TestStepInfo{ AstCompositeLit: cl, Fields: astutils.CompositeLitFields(cl), - TestStep: &tfresource.TestStep{}, + TestStep: &testStepType{}, TypesInfo: info, } diff --git a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/package.go b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/package.go index c731a9cc7a6..a311071f112 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/package.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/package.go @@ -1,28 +1,42 @@ package schema import ( + "fmt" "go/ast" "go/types" "github.com/bflad/tfproviderlint/helper/astutils" + "github.com/bflad/tfproviderlint/helper/terraformtype" ) const ( - PackageName = `schema` - PackagePath = `github.com/hashicorp/terraform-plugin-sdk/helper/schema` + PackageModule = terraformtype.ModuleTerraformPluginSdk + PackageModulePath = `helper/schema` + PackageName = `schema` + PackagePath = PackageModule + `/` + PackageModulePath ) // IsFunc returns if the function call is in the package func IsFunc(e ast.Expr, info *types.Info, funcName string) bool { - return astutils.IsPackageFunc(e, info, PackagePath, funcName) + return astutils.IsModulePackageFunc(e, info, PackageModule, PackageModulePath, funcName) } // IsNamedType returns if the type name matches and is from the package func IsNamedType(t *types.Named, typeName string) bool { - return astutils.IsPackageNamedType(t, PackagePath, typeName) + return astutils.IsModulePackageNamedType(t, PackageModule, PackageModulePath, typeName) } // IsReceiverMethod returns if the receiver method call is in the package func IsReceiverMethod(e ast.Expr, info *types.Info, receiverName string, methodName string) bool { - return astutils.IsPackageReceiverMethod(e, info, PackagePath, receiverName, methodName) + return astutils.IsModulePackageReceiverMethod(e, info, PackageModule, PackageModulePath, receiverName, methodName) +} + +// PackagePathVersion returns the import path for a module version +func PackagePathVersion(moduleVersion int) string { + switch moduleVersion { + case 0, 1: + return PackagePath + default: + return fmt.Sprintf("%s/v%d/%s", PackageModule, moduleVersion, PackageModulePath) + } } diff --git a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_customizedifffunc.go b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_customizedifffunc.go index c90186db149..8ff8c6331ac 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_customizedifffunc.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_customizedifffunc.go @@ -20,11 +20,28 @@ func IsFuncTypeCustomizeDiffFunc(node ast.Node, info *types.Info) bool { return false } + return isFuncTypeCustomizeDiffFuncV1(funcType, info) || isFuncTypeCustomizeDiffFuncV2(funcType, info) +} + +// IsTypeCustomizeDiffFunc returns if the type is CustomizeDiffFunc from the customdiff package +func IsTypeCustomizeDiffFunc(t types.Type) bool { + switch t := t.(type) { + case *types.Named: + return IsNamedType(t, TypeNameCustomizeDiffFunc) + case *types.Pointer: + return IsTypeCustomizeDiffFunc(t.Elem()) + default: + return false + } +} + +// isFuncTypeCustomizeDiffFuncV1 returns true if the FuncType matches expected parameters and results types of V1 +func isFuncTypeCustomizeDiffFuncV1(funcType *ast.FuncType, info *types.Info) bool { if !astutils.HasFieldListLength(funcType.Params, 2) { return false } - if !astutils.IsFieldListTypePackageType(funcType.Params, 0, info, PackagePath, TypeNameResourceDiff) { + if !astutils.IsFieldListTypePackageType(funcType.Params, 0, info, PackagePathVersion(1), TypeNameResourceDiff) { return false } @@ -39,16 +56,29 @@ func IsFuncTypeCustomizeDiffFunc(node ast.Node, info *types.Info) bool { return astutils.IsFieldListType(funcType.Results, 0, astutils.IsExprTypeError) } -// IsTypeCustomizeDiffFunc returns if the type is CustomizeDiffFunc from the customdiff package -func IsTypeCustomizeDiffFunc(t types.Type) bool { - switch t := t.(type) { - case *types.Named: - return IsNamedType(t, TypeNameCustomizeDiffFunc) - case *types.Pointer: - return IsTypeCustomizeDiffFunc(t.Elem()) - default: +// isFuncTypeCustomizeDiffFuncV2 returns true if the FuncType matches expected parameters and results types of V2 +func isFuncTypeCustomizeDiffFuncV2(funcType *ast.FuncType, info *types.Info) bool { + if !astutils.HasFieldListLength(funcType.Params, 3) { + return false + } + + if !astutils.IsFieldListTypePackageType(funcType.Params, 0, info, "context", "Context") { + return false + } + + if !astutils.IsFieldListTypePackageType(funcType.Params, 1, info, PackagePathVersion(2), TypeNameResourceDiff) { return false } + + if !astutils.IsFieldListType(funcType.Params, 2, astutils.IsExprTypeInterface) { + return false + } + + if !astutils.HasFieldListLength(funcType.Results, 1) { + return false + } + + return astutils.IsFieldListType(funcType.Results, 0, astutils.IsExprTypeError) } // CustomizeDiffFuncInfo represents all gathered CustomizeDiffFunc data for easier access diff --git a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_resource.go b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_resource.go index a7307477f6f..334a66aff93 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_resource.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_resource.go @@ -5,8 +5,6 @@ import ( "go/types" "github.com/bflad/tfproviderlint/helper/astutils" - tfschema "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" ) const ( @@ -14,6 +12,7 @@ const ( ResourceFieldCustomizeDiff = `CustomizeDiff` ResourceFieldDelete = `Delete` ResourceFieldDeprecationMessage = `DeprecationMessage` + ResourceFieldDescription = `Description` ResourceFieldExists = `Exists` ResourceFieldImporter = `Importer` ResourceFieldMigrateState = `MigrateState` @@ -27,11 +26,22 @@ const ( TypeNameResource = `Resource` ) +// resourceType is an internal representation of the SDK helper/schema.Resource type +// +// This is used to prevent importing the real type since the project supports +// multiple versions of the Terraform Plugin SDK, while allowing passes to +// access the data in a familiar manner. +type resourceType struct { + Description string + MigrateState func(int, interface{}, interface{}) (interface{}, error) + Schema map[string]*schemaType +} + // ResourceInfo represents all gathered Resource data for easier access type ResourceInfo struct { AstCompositeLit *ast.CompositeLit Fields map[string]*ast.KeyValueExpr - Resource *tfschema.Resource + Resource *resourceType TypesInfo *types.Info } @@ -40,12 +50,48 @@ func NewResourceInfo(cl *ast.CompositeLit, info *types.Info) *ResourceInfo { result := &ResourceInfo{ AstCompositeLit: cl, Fields: astutils.CompositeLitFields(cl), - Resource: &tfschema.Resource{}, + Resource: &resourceType{}, TypesInfo: info, } + if kvExpr := result.Fields[ResourceFieldDescription]; kvExpr != nil && astutils.ExprStringValue(kvExpr.Value) != nil { + result.Resource.Description = *astutils.ExprStringValue(kvExpr.Value) + } + if kvExpr := result.Fields[ResourceFieldMigrateState]; kvExpr != nil && astutils.ExprValue(kvExpr.Value) != nil { - result.Resource.MigrateState = func(int, *terraform.InstanceState, interface{}) (*terraform.InstanceState, error) { return nil, nil } + result.Resource.MigrateState = func(int, interface{}, interface{}) (interface{}, error) { return nil, nil } + } + + if kvExpr := result.Fields[ResourceFieldSchema]; kvExpr != nil && astutils.ExprValue(kvExpr.Value) != nil { + result.Resource.Schema = map[string]*schemaType{} + if smap, ok := kvExpr.Value.(*ast.CompositeLit); ok { + for _, expr := range smap.Elts { + switch elt := expr.(type) { + case *ast.KeyValueExpr: + var key string + + switch keyExpr := elt.Key.(type) { + case *ast.BasicLit: + keyPtr := astutils.ExprStringValue(keyExpr) + + if keyPtr == nil { + continue + } + + key = *keyPtr + } + + if key == "" { + continue + } + + switch valueExpr := elt.Value.(type) { + case *ast.CompositeLit: + result.Resource.Schema[key] = NewSchemaInfo(valueExpr, info).Schema + } + } + } + } } return result diff --git a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_schema.go b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_schema.go index 1ebc0388daa..e14e027005a 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_schema.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema/type_schema.go @@ -2,10 +2,10 @@ package schema import ( "go/ast" + "go/constant" "go/types" "github.com/bflad/tfproviderlint/helper/astutils" - tfschema "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) const ( @@ -48,11 +48,59 @@ const ( TypeNameValueType = `ValueType` ) +// schemaType is an internal representation of the SDK helper/schema.Schema type +// +// This is used to prevent importing the real type since the project supports +// multiple versions of the Terraform Plugin SDK, while allowing passes to +// access the data in a familiar manner. +type schemaType struct { + AtLeastOneOf []string + Computed bool + ConflictsWith []string + Default interface{} + DefaultFunc func() (interface{}, error) + DiffSuppressFunc func(string, string, string, interface{}) bool + Description string + Elem interface{} + ExactlyOneOf []string + ForceNew bool + InputDefault string + MaxItems int + MinItems int + Optional bool + PromoteSingle bool + Required bool + RequiredWith []string + Sensitive bool + StateFunc func(interface{}) string + Type valueType + ValidateFunc func(interface{}, string) ([]string, []error) +} + +// ValueType is an internal representation of the SDK helper/schema.ValueType type +// +// This is used to prevent importing the real type since the project supports +// multiple versions of the Terraform Plugin SDK, while allowing passes to +// access the data in a familiar manner. +type valueType int + +const ( + typeInvalid valueType = iota + typeBool + typeInt + typeFloat + typeString + typeList + typeMap + typeSet + typeObject +) + // SchemaInfo represents all gathered Schema data for easier access type SchemaInfo struct { AstCompositeLit *ast.CompositeLit Fields map[string]*ast.KeyValueExpr - Schema *tfschema.Schema + Schema *schemaType SchemaValueType string TypesInfo *types.Info } @@ -62,11 +110,15 @@ func NewSchemaInfo(cl *ast.CompositeLit, info *types.Info) *SchemaInfo { result := &SchemaInfo{ AstCompositeLit: cl, Fields: astutils.CompositeLitFields(cl), - Schema: &tfschema.Schema{}, + Schema: &schemaType{}, SchemaValueType: typeSchemaType(cl, info), TypesInfo: info, } + if kvExpr := result.Fields[SchemaFieldType]; kvExpr != nil && astutils.ExprValue(kvExpr.Value) != nil { + result.Schema.Type = ValueType(kvExpr.Value, info) + } + if kvExpr := result.Fields[SchemaFieldAtLeastOneOf]; kvExpr != nil && astutils.ExprValue(kvExpr.Value) != nil { result.Schema.AtLeastOneOf = []string{} } @@ -80,7 +132,22 @@ func NewSchemaInfo(cl *ast.CompositeLit, info *types.Info) *SchemaInfo { } if kvExpr := result.Fields[SchemaFieldDefault]; kvExpr != nil && astutils.ExprValue(kvExpr.Value) != nil { - result.Schema.Default = func() (interface{}, error) { return nil, nil } + switch result.Schema.Type { + case typeBool: + if ptr := astutils.ExprBoolValue(kvExpr.Value); ptr != nil { + result.Schema.Default = *ptr + } + case typeInt: + if ptr := astutils.ExprIntValue(kvExpr.Value); ptr != nil { + result.Schema.Default = *ptr + } + case typeString: + if ptr := astutils.ExprStringValue(kvExpr.Value); ptr != nil { + result.Schema.Default = *ptr + } + default: + result.Schema.Default = func() (interface{}, error) { return nil, nil } + } } if kvExpr := result.Fields[SchemaFieldDefaultFunc]; kvExpr != nil && astutils.ExprValue(kvExpr.Value) != nil { @@ -96,7 +163,7 @@ func NewSchemaInfo(cl *ast.CompositeLit, info *types.Info) *SchemaInfo { } if kvExpr := result.Fields[SchemaFieldDiffSuppressFunc]; kvExpr != nil && astutils.ExprValue(kvExpr.Value) != nil { - result.Schema.DiffSuppressFunc = func(k, old, new string, d *tfschema.ResourceData) bool { return false } + result.Schema.DiffSuppressFunc = func(k, old, new string, d interface{}) bool { return false } } if kvExpr := result.Fields[SchemaFieldForceNew]; kvExpr != nil && astutils.ExprBoolValue(kvExpr.Value) != nil { @@ -139,6 +206,21 @@ func NewSchemaInfo(cl *ast.CompositeLit, info *types.Info) *SchemaInfo { result.Schema.ValidateFunc = func(interface{}, string) ([]string, []error) { return nil, nil } } + if kvExpr := result.Fields[SchemaFieldElem]; kvExpr != nil && astutils.ExprValue(kvExpr.Value) != nil { + if uexpr, ok := kvExpr.Value.(*ast.UnaryExpr); ok { + if cl := uexpr.X.(*ast.CompositeLit); ok { + switch { + case IsTypeResource(info.TypeOf(cl.Type)): + resourceInfo := NewResourceInfo(cl, info) + result.Schema.Elem = resourceInfo.Resource + case IsTypeSchema(info.TypeOf(cl.Type)): + schemaInfo := NewSchemaInfo(cl, info) + result.Schema.Elem = schemaInfo.Schema + } + } + } + } + return result } @@ -240,6 +322,25 @@ func IsValueType(e ast.Expr, info *types.Info) bool { } } +// ValueType returns the schema value type +func ValueType(e ast.Expr, info *types.Info) valueType { + switch e := e.(type) { + case *ast.SelectorExpr: + switch t := info.ObjectOf(e.Sel).(type) { + case *types.Const: + v, ok := constant.Int64Val(t.Val()) + if !ok { + return typeInvalid + } + return valueType(v) + default: + return typeInvalid + } + default: + return typeInvalid + } +} + // IsTypeSet returns if the type is Set from the helper/schema package // Use IsTypeSchemaFieldType for verifying Type: schema.TypeSet ValueType func IsTypeSet(t types.Type) bool { diff --git a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/validation/package.go b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/validation/package.go index ad5ce2ed792..44183b84494 100644 --- a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/validation/package.go +++ b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/helper/validation/package.go @@ -1,18 +1,32 @@ package validation import ( + "fmt" "go/ast" "go/types" "github.com/bflad/tfproviderlint/helper/astutils" + "github.com/bflad/tfproviderlint/helper/terraformtype" ) const ( - PackageName = `validation` - PackagePath = `github.com/hashicorp/terraform-plugin-sdk/helper/validation` + PackageModule = terraformtype.ModuleTerraformPluginSdk + PackageModulePath = `helper/validation` + PackageName = `validation` + PackagePath = PackageModule + `/` + PackageModulePath ) // IsFunc returns if the function call is in the package func IsFunc(e ast.Expr, info *types.Info, funcName string) bool { - return astutils.IsPackageFunc(e, info, PackagePath, funcName) + return astutils.IsModulePackageFunc(e, info, PackageModule, PackageModulePath, funcName) +} + +// PackagePathVersion returns the import path for a module version +func PackagePathVersion(moduleVersion int) string { + switch moduleVersion { + case 0, 1: + return PackagePath + default: + return fmt.Sprintf("%s/v%d/%s", PackageModule, moduleVersion, PackageModulePath) + } } diff --git a/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/module.go b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/module.go new file mode 100644 index 00000000000..c9bf7727afc --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/helper/terraformtype/module.go @@ -0,0 +1,5 @@ +package terraformtype + +const ( + ModuleTerraformPluginSdk = `github.com/hashicorp/terraform-plugin-sdk` +) diff --git a/vendor/github.com/bflad/tfproviderlint/passes/R015/R015.go b/vendor/github.com/bflad/tfproviderlint/passes/R015/R015.go new file mode 100644 index 00000000000..0430b0df5dc --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/passes/R015/R015.go @@ -0,0 +1,58 @@ +package R015 + +import ( + "go/ast" + + "golang.org/x/tools/go/analysis" + + "github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource" + "github.com/bflad/tfproviderlint/passes/commentignore" + "github.com/bflad/tfproviderlint/passes/helper/schema/resourcedatasetidcallexpr" +) + +const Doc = `check for (*schema.ResourceData).SetId() usage with unstable resource.UniqueId() value + +Schema attributes should be stable across Terraform runs.` + +const analyzerName = "R015" + +var Analyzer = &analysis.Analyzer{ + Name: analyzerName, + Doc: Doc, + Requires: []*analysis.Analyzer{ + commentignore.Analyzer, + resourcedatasetidcallexpr.Analyzer, + }, + Run: run, +} + +func run(pass *analysis.Pass) (interface{}, error) { + ignorer := pass.ResultOf[commentignore.Analyzer].(*commentignore.Ignorer) + callExprs := pass.ResultOf[resourcedatasetidcallexpr.Analyzer].([]*ast.CallExpr) + for _, callExpr := range callExprs { + if ignorer.ShouldIgnore(analyzerName, callExpr) { + continue + } + + if len(callExpr.Args) < 1 { + continue + } + + ast.Inspect(callExpr.Args[0], func(n ast.Node) bool { + callExpr, ok := n.(*ast.CallExpr) + + if !ok { + return true + } + + if resource.IsFunc(callExpr.Fun, pass.TypesInfo, resource.FuncNameUniqueId) { + pass.Reportf(callExpr.Pos(), "%s: schema attributes should be stable across Terraform runs", analyzerName) + return false + } + + return true + }) + } + + return nil, nil +} diff --git a/vendor/github.com/bflad/tfproviderlint/passes/R015/README.md b/vendor/github.com/bflad/tfproviderlint/passes/R015/README.md new file mode 100644 index 00000000000..8d77815f339 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/passes/R015/README.md @@ -0,0 +1,24 @@ +# R015 + +The R015 analyzer reports [`(*schema.ResourceData).SetId()`](https://godoc.org/github.com/hashicorp/terraform-plugin-sdk/helper/schema#ResourceData.Set) usage with unstable `resource.UniqueId()` value. Schema attributes should be stable across Terraform runs. + +## Flagged Code + +```go +d.SetId(resource.UniqueId()) +``` + +## Passing Code + +```go +d.SetId("stablestring") +``` + +## Ignoring Reports + +Singular reports can be ignored by adding the a `//lintignore:R015` Go code comment at the end of the offending line or on the line immediately proceding, e.g. + +```go +//lintignore:R015 +d.SetId(resource.UniqueId()) +``` diff --git a/vendor/github.com/bflad/tfproviderlint/passes/R016/R016.go b/vendor/github.com/bflad/tfproviderlint/passes/R016/R016.go new file mode 100644 index 00000000000..fdac29c304d --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/passes/R016/R016.go @@ -0,0 +1,58 @@ +package R016 + +import ( + "go/ast" + + "golang.org/x/tools/go/analysis" + + "github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource" + "github.com/bflad/tfproviderlint/passes/commentignore" + "github.com/bflad/tfproviderlint/passes/helper/schema/resourcedatasetidcallexpr" +) + +const Doc = `check for (*schema.ResourceData).SetId() usage with unstable resource.PrefixedUniqueId() value + +Schema attributes should be stable across Terraform runs.` + +const analyzerName = "R016" + +var Analyzer = &analysis.Analyzer{ + Name: analyzerName, + Doc: Doc, + Requires: []*analysis.Analyzer{ + commentignore.Analyzer, + resourcedatasetidcallexpr.Analyzer, + }, + Run: run, +} + +func run(pass *analysis.Pass) (interface{}, error) { + ignorer := pass.ResultOf[commentignore.Analyzer].(*commentignore.Ignorer) + callExprs := pass.ResultOf[resourcedatasetidcallexpr.Analyzer].([]*ast.CallExpr) + for _, callExpr := range callExprs { + if ignorer.ShouldIgnore(analyzerName, callExpr) { + continue + } + + if len(callExpr.Args) < 1 { + continue + } + + ast.Inspect(callExpr.Args[0], func(n ast.Node) bool { + callExpr, ok := n.(*ast.CallExpr) + + if !ok { + return true + } + + if resource.IsFunc(callExpr.Fun, pass.TypesInfo, resource.FuncNamePrefixedUniqueId) { + pass.Reportf(callExpr.Pos(), "%s: schema attributes should be stable across Terraform runs", analyzerName) + return false + } + + return true + }) + } + + return nil, nil +} diff --git a/vendor/github.com/bflad/tfproviderlint/passes/R016/README.md b/vendor/github.com/bflad/tfproviderlint/passes/R016/README.md new file mode 100644 index 00000000000..461a847eee9 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/passes/R016/README.md @@ -0,0 +1,24 @@ +# R016 + +The R016 analyzer reports [`(*schema.ResourceData).SetId()`](https://godoc.org/github.com/hashicorp/terraform-plugin-sdk/helper/schema#ResourceData.Set) usage with unstable `resource.PrefixedUniqueId()` value. Schema attributes should be stable across Terraform runs. + +## Flagged Code + +```go +d.SetId(resource.PrefixedUniqueId("example")) +``` + +## Passing Code + +```go +d.SetId("stablestring") +``` + +## Ignoring Reports + +Singular reports can be ignored by adding the a `//lintignore:R016` Go code comment at the end of the offending line or on the line immediately proceding, e.g. + +```go +//lintignore:R016 +d.SetId(resource.PrefixedUniqueId("example")) +``` diff --git a/vendor/github.com/bflad/tfproviderlint/passes/R017/R017.go b/vendor/github.com/bflad/tfproviderlint/passes/R017/R017.go new file mode 100644 index 00000000000..d8b6c490576 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/passes/R017/R017.go @@ -0,0 +1,58 @@ +package R017 + +import ( + "go/ast" + + "golang.org/x/tools/go/analysis" + + "github.com/bflad/tfproviderlint/helper/astutils" + "github.com/bflad/tfproviderlint/passes/commentignore" + "github.com/bflad/tfproviderlint/passes/helper/schema/resourcedatasetidcallexpr" +) + +const Doc = `check for (*schema.ResourceData).SetId() usage with unstable time.Now() value + +Schema attributes should be stable across Terraform runs.` + +const analyzerName = "R017" + +var Analyzer = &analysis.Analyzer{ + Name: analyzerName, + Doc: Doc, + Requires: []*analysis.Analyzer{ + commentignore.Analyzer, + resourcedatasetidcallexpr.Analyzer, + }, + Run: run, +} + +func run(pass *analysis.Pass) (interface{}, error) { + ignorer := pass.ResultOf[commentignore.Analyzer].(*commentignore.Ignorer) + callExprs := pass.ResultOf[resourcedatasetidcallexpr.Analyzer].([]*ast.CallExpr) + for _, callExpr := range callExprs { + if ignorer.ShouldIgnore(analyzerName, callExpr) { + continue + } + + if len(callExpr.Args) < 1 { + continue + } + + ast.Inspect(callExpr.Args[0], func(n ast.Node) bool { + callExpr, ok := n.(*ast.CallExpr) + + if !ok { + return true + } + + if astutils.IsStdlibPackageFunc(callExpr.Fun, pass.TypesInfo, "time", "Now") { + pass.Reportf(callExpr.Pos(), "%s: schema attributes should be stable across Terraform runs", analyzerName) + return false + } + + return true + }) + } + + return nil, nil +} diff --git a/vendor/github.com/bflad/tfproviderlint/passes/R017/README.md b/vendor/github.com/bflad/tfproviderlint/passes/R017/README.md new file mode 100644 index 00000000000..1987c9718f7 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/passes/R017/README.md @@ -0,0 +1,24 @@ +# R017 + +The R017 analyzer reports [`(*schema.ResourceData).SetId()`](https://godoc.org/github.com/hashicorp/terraform-plugin-sdk/helper/schema#ResourceData.Set) usage with unstable `time.Now()` value. Schema attributes should be stable across Terraform runs. + +## Flagged Code + +```go +d.SetId(time.Now().Format(time.RFC3339)) +``` + +## Passing Code + +```go +d.SetId("stablestring") +``` + +## Ignoring Reports + +Singular reports can be ignored by adding the a `//lintignore:R017` Go code comment at the end of the offending line or on the line immediately proceding, e.g. + +```go +//lintignore:R017 +d.SetId(time.Now().Format(time.RFC3339)) +``` diff --git a/vendor/github.com/bflad/tfproviderlint/passes/checks.go b/vendor/github.com/bflad/tfproviderlint/passes/checks.go index e42e9570cb8..847e4cae169 100644 --- a/vendor/github.com/bflad/tfproviderlint/passes/checks.go +++ b/vendor/github.com/bflad/tfproviderlint/passes/checks.go @@ -23,6 +23,9 @@ import ( "github.com/bflad/tfproviderlint/passes/R012" "github.com/bflad/tfproviderlint/passes/R013" "github.com/bflad/tfproviderlint/passes/R014" + "github.com/bflad/tfproviderlint/passes/R015" + "github.com/bflad/tfproviderlint/passes/R016" + "github.com/bflad/tfproviderlint/passes/R017" "github.com/bflad/tfproviderlint/passes/S001" "github.com/bflad/tfproviderlint/passes/S002" "github.com/bflad/tfproviderlint/passes/S003" @@ -97,6 +100,9 @@ var AllChecks = []*analysis.Analyzer{ R012.Analyzer, R013.Analyzer, R014.Analyzer, + R015.Analyzer, + R016.Analyzer, + R017.Analyzer, S001.Analyzer, S002.Analyzer, S003.Analyzer, diff --git a/vendor/github.com/bflad/tfproviderlint/passes/helper/resource/testcheckresourceattrcallexpr/testcheckresourceattrcallexpr.go b/vendor/github.com/bflad/tfproviderlint/passes/helper/resource/testcheckresourceattrcallexpr/testcheckresourceattrcallexpr.go new file mode 100644 index 00000000000..a88136ed309 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/passes/helper/resource/testcheckresourceattrcallexpr/testcheckresourceattrcallexpr.go @@ -0,0 +1,13 @@ +package testcheckresourceattrcallexpr + +import ( + "github.com/bflad/tfproviderlint/helper/analysisutils" + "github.com/bflad/tfproviderlint/helper/terraformtype/helper/resource" +) + +var Analyzer = analysisutils.FunctionCallExprAnalyzer( + "testcheckresourceattrcallexpr", + resource.IsFunc, + resource.PackagePath, + resource.FuncNameTestCheckResourceAttr, +) diff --git a/vendor/github.com/bflad/tfproviderlint/passes/helper/schema/crudfuncinfo/crudfuncinfo.go b/vendor/github.com/bflad/tfproviderlint/passes/helper/schema/crudfuncinfo/crudfuncinfo.go index 9ad00f0092c..4e89246b3bb 100644 --- a/vendor/github.com/bflad/tfproviderlint/passes/helper/schema/crudfuncinfo/crudfuncinfo.go +++ b/vendor/github.com/bflad/tfproviderlint/passes/helper/schema/crudfuncinfo/crudfuncinfo.go @@ -36,7 +36,7 @@ func run(pass *analysis.Pass) (interface{}, error) { return } - if !astutils.IsFieldListTypePackageType(funcType.Params, 0, pass.TypesInfo, schema.PackagePath, schema.TypeNameResourceData) { + if !astutils.IsFieldListTypeModulePackageType(funcType.Params, 0, pass.TypesInfo, schema.PackageModule, schema.PackageModulePath, schema.TypeNameResourceData) { return } diff --git a/vendor/github.com/bflad/tfproviderlint/passes/helper/schema/resourcedatasetidcallexpr/resourcedatasetidcallexpr.go b/vendor/github.com/bflad/tfproviderlint/passes/helper/schema/resourcedatasetidcallexpr/resourcedatasetidcallexpr.go new file mode 100644 index 00000000000..0c4c909c921 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/passes/helper/schema/resourcedatasetidcallexpr/resourcedatasetidcallexpr.go @@ -0,0 +1,14 @@ +package resourcedatasetidcallexpr + +import ( + "github.com/bflad/tfproviderlint/helper/analysisutils" + "github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema" +) + +var Analyzer = analysisutils.ReceiverMethodCallExprAnalyzer( + "resourcedatasetidcallexpr", + schema.IsReceiverMethod, + schema.PackagePath, + schema.TypeNameResourceData, + "SetId", +) diff --git a/vendor/github.com/bflad/tfproviderlint/version/version.go b/vendor/github.com/bflad/tfproviderlint/version/version.go index e167f14be56..fc396588c6f 100644 --- a/vendor/github.com/bflad/tfproviderlint/version/version.go +++ b/vendor/github.com/bflad/tfproviderlint/version/version.go @@ -10,7 +10,7 @@ var ( GitCommit string // The main version number that is being run at the moment. - Version = "0.13.0" + Version = "0.15.0" // 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/vendor/github.com/bflad/tfproviderlint/xpasses/XR005/README.md b/vendor/github.com/bflad/tfproviderlint/xpasses/XR005/README.md new file mode 100644 index 00000000000..bd375fbb4c0 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/xpasses/XR005/README.md @@ -0,0 +1,36 @@ +# XR005 + +The XR005 analyzer reports cases of resources where `Description` is not configured, which is generally useful for providers that wish to automatically generate documentation based on the schema information. + +This analyzer automatically ignores schema attribute `Elem` of type `schema.Resource`. + +## Flagged Code + +```go +&schema.Resource{ + Read: /* ... */, + Schema: map[string]*schema.Schema{/* ... */}, +} +``` + +## Passing Code + +```go +&schema.Resource{ + Description: "manages a widget", + Read: /* ... */, + Schema: map[string]*schema.Schema{/* ... */}, +} +``` + +## Ignoring Reports + +Singular reports can be ignored by adding the a `//lintignore:XR005` Go code comment at the end of the offending line or on the line immediately proceding, e.g. + +```go +//lintignore:XR005 +&schema.Resource{ + Read: /* ... */, + Schema: map[string]*schema.Schema{/* ... */}, +} +``` diff --git a/vendor/github.com/bflad/tfproviderlint/xpasses/XR005/XR005.go b/vendor/github.com/bflad/tfproviderlint/xpasses/XR005/XR005.go new file mode 100644 index 00000000000..07829bfb779 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/xpasses/XR005/XR005.go @@ -0,0 +1,56 @@ +package XR005 + +import ( + "go/ast" + + "github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema" + "github.com/bflad/tfproviderlint/passes/commentignore" + "github.com/bflad/tfproviderlint/passes/helper/schema/resourceinfo" + "golang.org/x/tools/go/analysis" +) + +const Doc = `check for Resource that Description is configured + +The XR005 analyzer reports cases of resources where Description is not +configured, which is generally useful for providers that wish to +automatically generate documentation based on the schema information.` + +const analyzerName = "XR005" + +var Analyzer = &analysis.Analyzer{ + Name: analyzerName, + Doc: Doc, + Requires: []*analysis.Analyzer{ + commentignore.Analyzer, + resourceinfo.Analyzer, + }, + Run: run, +} + +func run(pass *analysis.Pass) (interface{}, error) { + ignorer := pass.ResultOf[commentignore.Analyzer].(*commentignore.Ignorer) + resourceInfos := pass.ResultOf[resourceinfo.Analyzer].([]*schema.ResourceInfo) + for _, resourceInfo := range resourceInfos { + if ignorer.ShouldIgnore(analyzerName, resourceInfo.AstCompositeLit) { + continue + } + + // Skip configuration block Elem + if !resourceInfo.IsDataSource() && !resourceInfo.IsResource() { + continue + } + + if resourceInfo.Resource.Description != "" { + continue + } + + switch t := resourceInfo.AstCompositeLit.Type.(type) { + default: + pass.Reportf(resourceInfo.AstCompositeLit.Lbrace, "%s: resource should configure Description", analyzerName) + case *ast.SelectorExpr: + pass.Reportf(t.Sel.Pos(), "%s: resource should configure Description", analyzerName) + } + } + + return nil, nil +} diff --git a/vendor/github.com/bflad/tfproviderlint/xpasses/XS002/README.md b/vendor/github.com/bflad/tfproviderlint/xpasses/XS002/README.md new file mode 100644 index 00000000000..b8457494ef1 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/xpasses/XS002/README.md @@ -0,0 +1,36 @@ +# XS002 + +The XS002 analyzer reports cases of schemas where attributes are not listed in alphabetical order. + +## Flagged Code + +```go +map[string]*schema.Schema{ + "name": { /* ... */ }, + "arn": { /* ... */ }, + }, +} +``` + +## Passing Code + +```go +map[string]*schema.Schema{ + "arn": { /* ... */ }, + "name": { /* ... */ }, + }, +} +``` + +## Ignoring Reports + +Singular reports can be ignored by adding the a `//lintignore:XS002` Go code comment at the end of the offending line or on the line immediately proceding, e.g. + +```go +//lintignore:XS002 +map[string]*schema.Schema{ + "name": { /* ... */ }, + "arn": { /* ... */ }, + }, +} +``` diff --git a/vendor/github.com/bflad/tfproviderlint/xpasses/XS002/XS002.go b/vendor/github.com/bflad/tfproviderlint/xpasses/XS002/XS002.go new file mode 100644 index 00000000000..55eb6b4bf05 --- /dev/null +++ b/vendor/github.com/bflad/tfproviderlint/xpasses/XS002/XS002.go @@ -0,0 +1,53 @@ +package XS002 + +import ( + "go/ast" + "sort" + + "github.com/bflad/tfproviderlint/helper/astutils" + "github.com/bflad/tfproviderlint/helper/terraformtype/helper/schema" + "github.com/bflad/tfproviderlint/passes/commentignore" + "github.com/bflad/tfproviderlint/passes/helper/schema/schemamapcompositelit" + "golang.org/x/tools/go/analysis" +) + +const Doc = `check for Schema that attribute names are in alphabetical order + +The XS002 analyzer reports cases of schemas where attribute names +are not in alphabetical order.` + +const analyzerName = "XS002" + +var Analyzer = &analysis.Analyzer{ + Name: analyzerName, + Doc: Doc, + Requires: []*analysis.Analyzer{ + schemamapcompositelit.Analyzer, + commentignore.Analyzer, + }, + Run: run, +} + +func run(pass *analysis.Pass) (interface{}, error) { + ignorer := pass.ResultOf[commentignore.Analyzer].(*commentignore.Ignorer) + schemamapcompositelits := pass.ResultOf[schemamapcompositelit.Analyzer].([]*ast.CompositeLit) + + for _, smap := range schemamapcompositelits { + if ignorer.ShouldIgnore(analyzerName, smap) { + continue + } + + schemaKeys := make([]string, 0 , len(schema.GetSchemaMapAttributeNames(smap))) + for _, attributeName := range schema.GetSchemaMapAttributeNames(smap) { + if v := astutils.ExprStringValue(attributeName); v != nil { + schemaKeys = append(schemaKeys, *v) + } + } + + if !sort.StringsAreSorted(schemaKeys) { + pass.Reportf(smap.Pos(), "%s: schema attributes should be in alphabetical order", analyzerName) + } + } + + return nil, nil +} diff --git a/vendor/github.com/bflad/tfproviderlint/xpasses/checks.go b/vendor/github.com/bflad/tfproviderlint/xpasses/checks.go index 0b1023e7edb..7efdc2e60e8 100644 --- a/vendor/github.com/bflad/tfproviderlint/xpasses/checks.go +++ b/vendor/github.com/bflad/tfproviderlint/xpasses/checks.go @@ -5,7 +5,9 @@ import ( "github.com/bflad/tfproviderlint/xpasses/XR002" "github.com/bflad/tfproviderlint/xpasses/XR003" "github.com/bflad/tfproviderlint/xpasses/XR004" + "github.com/bflad/tfproviderlint/xpasses/XR005" "github.com/bflad/tfproviderlint/xpasses/XS001" + "github.com/bflad/tfproviderlint/xpasses/XS002" "golang.org/x/tools/go/analysis" ) @@ -17,5 +19,7 @@ var AllChecks = []*analysis.Analyzer{ XR002.Analyzer, XR003.Analyzer, XR004.Analyzer, + XR005.Analyzer, XS001.Analyzer, + XS002.Analyzer, } diff --git a/vendor/github.com/bombsimon/wsl/v3/wsl.go b/vendor/github.com/bombsimon/wsl/v3/wsl.go index 3b4a4e9a1a4..31520fb43f5 100644 --- a/vendor/github.com/bombsimon/wsl/v3/wsl.go +++ b/vendor/github.com/bombsimon/wsl/v3/wsl.go @@ -398,6 +398,18 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { if !cuddledWithLastStmt { checkingErr := atLeastOneInListsMatch(rightAndLeftHandSide, p.config.ErrorVariableNames) if checkingErr { + // We only want to enforce cuddling error checks if the + // error was assigned on the line above. See + // https://github.com/bombsimon/wsl/issues/78. + // This is needed since `assignedOnLineAbove` is not + // actually just assignments but everything from LHS in the + // previous statement. This means that if previous line was + // `if err ...`, `err` will now be in the list + // `assignedOnLineAbove`. + if _, ok := previousStatement.(*ast.AssignStmt); !ok { + continue + } + if checkingErrInitializedInline() { continue } diff --git a/vendor/github.com/denis-tingajkin/go-header/.gitignore b/vendor/github.com/denis-tingajkin/go-header/.gitignore new file mode 100644 index 00000000000..62c893550ad --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/.gitignore @@ -0,0 +1 @@ +.idea/ \ No newline at end of file diff --git a/vendor/github.com/denis-tingajkin/go-header/LICENSE b/vendor/github.com/denis-tingajkin/go-header/LICENSE new file mode 100644 index 00000000000..a2c9fda21f7 --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/vendor/github.com/denis-tingajkin/go-header/README.md b/vendor/github.com/denis-tingajkin/go-header/README.md new file mode 100644 index 00000000000..43348b8bec7 --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/README.md @@ -0,0 +1,69 @@ +# go-header +[![Actions Status](https://github.com/denis-tingajkin/go-header/workflows/ci/badge.svg)](https://github.com/denis-tingajkin/go-header/actions) + +Go source code linter providing checks for license headers. + +# Installation + +For installation you can simply use `go get`. + +``` +go get github.com/denis-tingajkin/go-header/cmd/go-header +``` + +# Configuration + +To configuring `go-header.yml` linter you simply need to fill the next structures in YAML format. +```go +// Configuration represents go-header linter setup parameters +type Configuration struct { + // Values is map of values. Supports two types 'const` and `regexp`. Values can be used recursively. + Values map[string]map[string]string `yaml:"values"'` + // Template is template for checking. Uses values. + Template string `yaml:"template"` + // TemplatePath path to the template file. Useful if need to load the template from a specific file. + TemplatePath string `yaml:"template-path"` +} +``` +Where supported two kinds of values: `const` and `regexp`. NOTE: values can be used recursively. +Values ​​with type `const` checks on equality. +Values ​​with type `regexp` checks on the match. + +# Execution + +`go-header` linter expects file path on input. If you want to run `go-header` only on diff files, then you can use this command +```bash +go-header $(git diff --name-only) +``` + +# Setup example + +## Step 1 +Create configuration file `.go-header.yaml` in the root of project. +```yaml +--- +values: + const: + MY COMPANY: mycompany.com +template-path: ./mypath/mytemplate.txt +``` +## Step 2 +Write the template file. For example for config above `mytemplate.txt` could be +```text +{{ MY COMPANY }} +SPDX-License-Identifier: Apache-2.0 + +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. +``` +## Step 3 +You are ready! Execute `go-header {FILES}` from the root of the project. diff --git a/vendor/github.com/denis-tingajkin/go-header/analyzer.go b/vendor/github.com/denis-tingajkin/go-header/analyzer.go new file mode 100644 index 00000000000..f4efe75a734 --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/analyzer.go @@ -0,0 +1,98 @@ +package goheader + +import ( + "fmt" + "go/ast" + "strings" +) + +type Analyzer interface { + Analyze(file *ast.File) Issue +} + +type analyzer struct { + values map[string]Value + template string +} + +func (a *analyzer) Analyze(file *ast.File) Issue { + if a.template == "" { + return NewIssue("Missed template for check") + } + var header string + if len(file.Comments) > 0 && file.Comments[0].Pos() < file.Package { + if strings.HasPrefix(file.Comments[0].List[0].Text, "/*") { + header = (&ast.CommentGroup{List: []*ast.Comment{file.Comments[0].List[0]}}).Text() + } else { + header = file.Comments[0].Text() + } + } + header = strings.TrimSpace(header) + if header == "" { + return NewIssue("Missed header for check") + } + s := NewReader(header) + t := NewReader(a.template) + for !s.Done() && !t.Done() { + templateCh := t.Peek() + if templateCh == '{' { + name := a.readField(t) + if a.values[name] == nil { + return NewIssue(fmt.Sprintf("Template has unknown value: %v", name)) + } + if i := a.values[name].Read(s); i != nil { + return i + } + continue + } + sourceCh := s.Peek() + if sourceCh != templateCh { + l := s.Location() + notNextLine := func(r rune) bool { + return r != '\n' + } + actual := s.ReadWhile(notNextLine) + expected := t.ReadWhile(notNextLine) + return NewIssueWithLocation(fmt.Sprintf("Actual: %v\nExpected:%v", actual, expected), l) + } + s.Next() + t.Next() + } + if !s.Done() { + l := s.Location() + return NewIssueWithLocation(fmt.Sprintf("Unexpected string: %v", s.Finish()), l) + } + if !t.Done() { + l := s.Location() + return NewIssueWithLocation(fmt.Sprintf("Missed string: %v", t.Finish()), l) + } + return nil +} + +func (a *analyzer) readField(reader Reader) string { + _ = reader.Next() + _ = reader.Next() + + r := reader.ReadWhile(func(r rune) bool { + return r != '}' + }) + + _ = reader.Next() + _ = reader.Next() + + return strings.ToLower(strings.TrimSpace(r)) +} + +func New(options ...AnalyzerOption) Analyzer { + a := &analyzer{} + for _, o := range options { + o.apply(a) + } + for _, v := range a.values { + err := v.Calculate(a.values) + if err != nil { + panic(err.Error()) + } + } + return a +} diff --git a/vendor/github.com/denis-tingajkin/go-header/config.go b/vendor/github.com/denis-tingajkin/go-header/config.go new file mode 100644 index 00000000000..67e273b9bb4 --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/config.go @@ -0,0 +1,69 @@ +package goheader + +import ( + "errors" + "fmt" + "gopkg.in/yaml.v2" + "io/ioutil" + "strings" +) + +// Configuration represents go-header linter setup parameters +type Configuration struct { + // Values is map of values. Supports two types 'const` and `regexp`. Values can be used recursively. + Values map[string]map[string]string `yaml:"values"'` + // Template is template for checking. Uses values. + Template string `yaml:"template"` + // TemplatePath path to the template file. Useful if need to load the template from a specific file. + TemplatePath string `yaml:"template-path"` +} + +func (c *Configuration) GetValues() (map[string]Value, error) { + var result = make(map[string]Value) + createConst := func(raw string) Value { + return &ConstValue{RawValue: raw} + } + createRegexp := func(raw string) Value { + return &RegexpValue{RawValue: raw} + } + appendValues := func(m map[string]string, create func(string) Value) { + for k, v := range m { + key := strings.ToLower(k) + result[key] = create(v) + } + } + for k, v := range c.Values { + switch k { + case "const": + appendValues(v, createConst) + case "regexp": + appendValues(v, createRegexp) + default: + return nil, fmt.Errorf("unknown value type %v", k) + } + } + return result, nil +} + +func (c *Configuration) GetTemplate() (string, error) { + if c.Template != "" { + return c.Template, nil + } + if c.TemplatePath == "" { + return "", errors.New("template has not passed") + } + if b, err := ioutil.ReadFile(c.TemplatePath); err != nil { + return "", err + } else { + c.Template = string(b) + return c.Template, nil + } +} + +func (c *Configuration) Parse(p string) error { + b, err := ioutil.ReadFile(p) + if err != nil { + return err + } + return yaml.Unmarshal(b, c) +} diff --git a/vendor/github.com/denis-tingajkin/go-header/go.mod b/vendor/github.com/denis-tingajkin/go-header/go.mod new file mode 100644 index 00000000000..c557afeb4f3 --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/go.mod @@ -0,0 +1,10 @@ +module github.com/denis-tingajkin/go-header + +go 1.13 + +require ( + github.com/fatih/color v1.9.0 + github.com/sirupsen/logrus v1.6.0 + github.com/stretchr/testify v1.5.1 + gopkg.in/yaml.v2 v2.2.2 +) diff --git a/vendor/github.com/denis-tingajkin/go-header/go.sum b/vendor/github.com/denis-tingajkin/go-header/go.sum new file mode 100644 index 00000000000..4033b08f05c --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/go.sum @@ -0,0 +1,31 @@ +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= +github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= +github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM= +github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= +github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/denis-tingajkin/go-header/issue.go b/vendor/github.com/denis-tingajkin/go-header/issue.go new file mode 100644 index 00000000000..d4921966a4d --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/issue.go @@ -0,0 +1,32 @@ +package goheader + +type Issue interface { + Location() Location + Message() string +} + +type issue struct { + msg string + location Location +} + +func (i *issue) Location() Location { + return i.location +} + +func (i *issue) Message() string { + return i.msg +} + +func NewIssueWithLocation(msg string, location Location) Issue { + return &issue{ + msg: msg, + location: location, + } +} + +func NewIssue(msg string) Issue { + return &issue{ + msg: msg, + } +} diff --git a/vendor/github.com/denis-tingajkin/go-header/location.go b/vendor/github.com/denis-tingajkin/go-header/location.go new file mode 100644 index 00000000000..fc33e48d8c1 --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/location.go @@ -0,0 +1,12 @@ +package goheader + +import "fmt" + +type Location struct { + Line int + Position int +} + +func (l Location) String() string { + return fmt.Sprintf("%v:%v", l.Line+1, l.Position) +} diff --git a/vendor/github.com/denis-tingajkin/go-header/option.go b/vendor/github.com/denis-tingajkin/go-header/option.go new file mode 100644 index 00000000000..2adaa9a9181 --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/option.go @@ -0,0 +1,28 @@ +package goheader + +import "strings" + +type AnalyzerOption interface { + apply(*analyzer) +} + +type applyAnalyzerOptionFunc func(*analyzer) + +func (f applyAnalyzerOptionFunc) apply(a *analyzer) { + f(a) +} + +func WithValues(values map[string]Value) AnalyzerOption { + return applyAnalyzerOptionFunc(func(a *analyzer) { + a.values = make(map[string]Value) + for k, v := range values { + a.values[strings.ToLower(k)] = v + } + }) +} + +func WithTemplate(template string) AnalyzerOption { + return applyAnalyzerOptionFunc(func(a *analyzer) { + a.template = template + }) +} diff --git a/vendor/github.com/denis-tingajkin/go-header/reader.go b/vendor/github.com/denis-tingajkin/go-header/reader.go new file mode 100644 index 00000000000..4386f30da78 --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/reader.go @@ -0,0 +1,105 @@ +package goheader + +type Reader interface { + Peek() rune + Next() rune + Done() bool + Finish() string + Position() int + Location() Location + SetPosition(int) + ReadWhile(func(rune) bool) string +} + +func NewReader(text string) Reader { + return &reader{source: text} +} + +type reader struct { + source string + position int + location Location +} + +func (r *reader) Position() int { + return r.position +} + +func (r *reader) Location() Location { + return r.location +} + +func (r *reader) Peek() rune { + if r.Done() { + return rune(0) + } + return rune(r.source[r.position]) +} + +func (r *reader) Done() bool { + return r.position >= len(r.source) +} + +func (r *reader) Next() rune { + if r.Done() { + return rune(0) + } + reuslt := r.Peek() + if reuslt == '\n' { + r.location.Line++ + r.location.Position = 0 + } else { + r.location.Position++ + } + r.position++ + return reuslt +} + +func (r *reader) Finish() string { + if r.position >= len(r.source) { + return "" + } + defer r.till() + return r.source[r.position:] +} + +func (r *reader) SetPosition(pos int) { + if pos < 0 { + r.position = 0 + } + r.position = pos + r.location = r.calculateLocation() +} + +func (r *reader) ReadWhile(match func(rune) bool) string { + if match == nil { + return "" + } + start := r.position + for !r.Done() && match(r.Peek()) { + r.Next() + } + return r.source[start:r.position] +} + +func (r *reader) till() { + r.position = len(r.source) + r.location = r.calculateLocation() +} + +func (r *reader) calculateLocation() Location { + min := len(r.source) + if min > r.position { + min = r.position + } + x, y := 0, 0 + for i := 0; i < min; i++ { + if r.source[i] == '\n' { + y++ + x = 0 + } else { + x++ + } + } + return Location{Line: y, Position: x} +} diff --git a/vendor/github.com/denis-tingajkin/go-header/value.go b/vendor/github.com/denis-tingajkin/go-header/value.go new file mode 100644 index 00000000000..bebc03b6e5b --- /dev/null +++ b/vendor/github.com/denis-tingajkin/go-header/value.go @@ -0,0 +1,112 @@ +package goheader + +import ( + "errors" + "fmt" + "regexp" + "strings" +) + +type Calculable interface { + Calculate(map[string]Value) error + Get() string +} + +type Value interface { + Calculable + Read(Reader) Issue +} + +func calculateValue(calculable Calculable, values map[string]Value) (string, error) { + sb := strings.Builder{} + r := calculable.Get() + var endIndex int + var startIndex int + for startIndex = strings.Index(r, "{{"); startIndex >= 0; startIndex = strings.Index(r, "{{") { + _, _ = sb.WriteString(r[:startIndex]) + endIndex = strings.Index(r, "}}") + if endIndex < 0 { + return "", errors.New("missed value ending") + } + subVal := strings.ToLower(strings.TrimSpace(r[startIndex+2 : endIndex])) + if val := values[subVal]; val != nil { + if err := val.Calculate(values); err != nil { + return "", err + } + sb.WriteString(val.Get()) + } else { + return "", fmt.Errorf("unknown value name %v", subVal) + } + endIndex += 2 + r = r[endIndex:] + } + _, _ = sb.WriteString(r) + return sb.String(), nil +} + +type ConstValue struct { + RawValue string +} + +func (c *ConstValue) Calculate(values map[string]Value) error { + v, err := calculateValue(c, values) + if err != nil { + return err + } + c.RawValue = v + return nil +} + +func (c *ConstValue) Get() string { + return c.RawValue +} + +func (c *ConstValue) Read(s Reader) Issue { + l := s.Location() + p := s.Position() + for _, ch := range c.Get() { + if ch != s.Peek() { + s.SetPosition(p) + f := s.ReadWhile(func(r rune) bool { + return r != '\n' + }) + return NewIssueWithLocation(fmt.Sprintf("Expected:%v, Actual: %v", c.Get(), f), l) + } + s.Next() + } + return nil +} + +type RegexpValue struct { + RawValue string +} + +func (r *RegexpValue) Calculate(values map[string]Value) error { + v, err := calculateValue(r, values) + if err != nil { + return err + } + r.RawValue = v + return nil +} + +func (r *RegexpValue) Get() string { + return r.RawValue +} + +func (r *RegexpValue) Read(s Reader) Issue { + l := s.Location() + p := regexp.MustCompile(r.Get()) + pos := s.Position() + str := s.Finish() + s.SetPosition(pos) + indexes := p.FindAllIndex([]byte(str), -1) + if len(indexes) == 0 { + return NewIssueWithLocation(fmt.Sprintf("Pattern %v doesn't match.", p.String()), l) + } + s.SetPosition(pos + indexes[0][1]) + return nil +} + +var _ Value = &ConstValue{} +var _ Value = &RegexpValue{} diff --git a/vendor/github.com/fatih/color/.travis.yml b/vendor/github.com/fatih/color/.travis.yml deleted file mode 100644 index 95f8a1ff5c7..00000000000 --- a/vendor/github.com/fatih/color/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: go -go: - - 1.8.x - - tip - diff --git a/vendor/github.com/fatih/color/Gopkg.lock b/vendor/github.com/fatih/color/Gopkg.lock deleted file mode 100644 index 7d879e9caf0..00000000000 --- a/vendor/github.com/fatih/color/Gopkg.lock +++ /dev/null @@ -1,27 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - name = "github.com/mattn/go-colorable" - packages = ["."] - revision = "167de6bfdfba052fa6b2d3664c8f5272e23c9072" - version = "v0.0.9" - -[[projects]] - name = "github.com/mattn/go-isatty" - packages = ["."] - revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" - version = "v0.0.3" - -[[projects]] - branch = "master" - name = "golang.org/x/sys" - packages = ["unix"] - revision = "37707fdb30a5b38865cfb95e5aab41707daec7fd" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "e8a50671c3cb93ea935bf210b1cd20702876b9d9226129be581ef646d1565cdc" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/fatih/color/Gopkg.toml b/vendor/github.com/fatih/color/Gopkg.toml deleted file mode 100644 index ff1617f71da..00000000000 --- a/vendor/github.com/fatih/color/Gopkg.toml +++ /dev/null @@ -1,30 +0,0 @@ - -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" - - -[[constraint]] - name = "github.com/mattn/go-colorable" - version = "0.0.9" - -[[constraint]] - name = "github.com/mattn/go-isatty" - version = "0.0.3" diff --git a/vendor/github.com/fatih/color/README.md b/vendor/github.com/fatih/color/README.md index 3fc95446028..42d9abc07ed 100644 --- a/vendor/github.com/fatih/color/README.md +++ b/vendor/github.com/fatih/color/README.md @@ -1,6 +1,12 @@ -# Color [![GoDoc](https://godoc.org/github.com/fatih/color?status.svg)](https://godoc.org/github.com/fatih/color) [![Build Status](https://img.shields.io/travis/fatih/color.svg?style=flat-square)](https://travis-ci.org/fatih/color) +# Archived project. No maintenance. +This project is not maintained anymore and is archived. Feel free to fork and +make your own changes if needed. For more detail read my blog post: [Taking an indefinite sabbatical from my projects](https://arslan.io/2018/10/09/taking-an-indefinite-sabbatical-from-my-projects/) +Thanks to everyone for their valuable feedback and contributions. + + +# Color [![GoDoc](https://godoc.org/github.com/fatih/color?status.svg)](https://godoc.org/github.com/fatih/color) Color lets you use colorized outputs in terms of [ANSI Escape Codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) in Go (Golang). It @@ -17,9 +23,6 @@ suits you. go get github.com/fatih/color ``` -Note that the `vendor` folder is here for stability. Remove the folder if you -already have the dependencies in your GOPATH. - ## Examples ### Standard colors diff --git a/vendor/github.com/fatih/color/go.mod b/vendor/github.com/fatih/color/go.mod new file mode 100644 index 00000000000..bc0df754586 --- /dev/null +++ b/vendor/github.com/fatih/color/go.mod @@ -0,0 +1,8 @@ +module github.com/fatih/color + +go 1.13 + +require ( + github.com/mattn/go-colorable v0.1.4 + github.com/mattn/go-isatty v0.0.11 +) diff --git a/vendor/github.com/fatih/color/go.sum b/vendor/github.com/fatih/color/go.sum new file mode 100644 index 00000000000..44328a8db54 --- /dev/null +++ b/vendor/github.com/fatih/color/go.sum @@ -0,0 +1,8 @@ +github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM= +github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/vendor/github.com/go-critic/go-critic/checkers/appendAssign_checker.go b/vendor/github.com/go-critic/go-critic/checkers/appendAssign_checker.go index 47d12f01426..d269217706e 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/appendAssign_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/appendAssign_checker.go @@ -5,15 +5,15 @@ import ( "go/token" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astequal" "github.com/go-toolsmith/astp" "golang.org/x/tools/go/ast/astutil" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "appendAssign" info.Tags = []string{"diagnostic"} info.Summary = "Detects suspicious append result assignments" @@ -24,14 +24,14 @@ p.negatives = append(p.negatives, y)` p.positives = append(p.positives, x) p.negatives = append(p.negatives, y)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&appendAssignChecker{ctx: ctx}) }) } type appendAssignChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *appendAssignChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/appendCombine_checker.go b/vendor/github.com/go-critic/go-critic/checkers/appendCombine_checker.go index 63f5d9fea4e..a761f2a8f55 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/appendCombine_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/appendCombine_checker.go @@ -4,14 +4,14 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astequal" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "appendCombine" info.Tags = []string{"performance"} info.Summary = "Detects `append` chains to the same slice that can be done in a single `append` call" @@ -20,14 +20,14 @@ xs = append(xs, 1) xs = append(xs, 2)` info.After = `xs = append(xs, 1, 2)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmtList(&appendCombineChecker{ctx: ctx}) }) } type appendCombineChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *appendCombineChecker) VisitStmtList(list []ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/argOrder_checker.go b/vendor/github.com/go-critic/go-critic/checkers/argOrder_checker.go index 85a6f7c664e..3b8bf9f5205 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/argOrder_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/argOrder_checker.go @@ -4,8 +4,8 @@ import ( "go/ast" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/astp" @@ -13,21 +13,21 @@ import ( ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "argOrder" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects suspicious arguments order" info.Before = `strings.HasPrefix("#", userpass)` info.After = `strings.HasPrefix(userpass, "#")` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&argOrderChecker{ctx: ctx}) }) } type argOrderChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *argOrderChecker) VisitExpr(expr ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/assignOp_checker.go b/vendor/github.com/go-critic/go-critic/checkers/assignOp_checker.go index eb34286636c..e3acd09ef61 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/assignOp_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/assignOp_checker.go @@ -4,29 +4,29 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/astequal" "github.com/go-toolsmith/typep" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "assignOp" info.Tags = []string{"style"} info.Summary = "Detects assignments that can be simplified by using assignment operators" info.Before = `x = x * 2` info.After = `x *= 2` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&assignOpChecker{ctx: ctx}) }) } type assignOpChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *assignOpChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/badCall_checker.go b/vendor/github.com/go-critic/go-critic/checkers/badCall_checker.go index 150cc690426..278e3b1e76f 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/badCall_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/badCall_checker.go @@ -3,28 +3,28 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astcopy" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "badCall" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects suspicious function calls" info.Before = `strings.Replace(s, from, to, 0)` info.After = `strings.Replace(s, from, to, -1)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&badCallChecker{ctx: ctx}) }) } type badCallChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *badCallChecker) VisitExpr(expr ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/badCond_checker.go b/vendor/github.com/go-critic/go-critic/checkers/badCond_checker.go index 466a89cc374..8d664366da8 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/badCond_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/badCond_checker.go @@ -5,9 +5,9 @@ import ( "go/constant" "go/token" + "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/checkers/internal/lintutil" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/astequal" @@ -16,7 +16,7 @@ import ( ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "badCond" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects suspicious condition expressions" @@ -29,14 +29,14 @@ for i := 0; i < n; i++ { xs[i] = 0 }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForFuncDecl(&badCondChecker{ctx: ctx}) }) } type badCondChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *badCondChecker) VisitFuncDecl(decl *ast.FuncDecl) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/badRegexp_checker.go b/vendor/github.com/go-critic/go-critic/checkers/badRegexp_checker.go new file mode 100644 index 00000000000..1025454df1a --- /dev/null +++ b/vendor/github.com/go-critic/go-critic/checkers/badRegexp_checker.go @@ -0,0 +1,445 @@ +package checkers + +import ( + "go/ast" + "go/constant" + "sort" + "strconv" + "unicode" + "unicode/utf8" + + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" + "github.com/quasilyte/regex/syntax" +) + +func init() { + var info linter.CheckerInfo + info.Name = "badRegexp" + info.Tags = []string{"diagnostic", "experimental"} + info.Summary = "Detects suspicious regexp patterns" + info.Before = "regexp.MustCompile(`(?:^aa|bb|cc)foo[aba]`)" + info.After = "regexp.MustCompile(`^(?:aa|bb|cc)foo[ab]`)" + + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { + opts := &syntax.ParserOptions{} + c := &badRegexpChecker{ + ctx: ctx, + parser: syntax.NewParser(opts), + } + return astwalk.WalkerForExpr(c) + }) +} + +type badRegexpChecker struct { + astwalk.WalkHandler + ctx *linter.CheckerContext + + parser *syntax.Parser + cause ast.Expr + + flagStates []regexpFlagState + goodAnchors []syntax.Position +} + +type regexpFlagState [utf8.RuneSelf]bool + +func (c *badRegexpChecker) VisitExpr(x ast.Expr) { + call, ok := x.(*ast.CallExpr) + if !ok { + return + } + + switch qualifiedName(call.Fun) { + case "regexp.Compile", "regexp.MustCompile": + cv := c.ctx.TypesInfo.Types[call.Args[0]].Value + if cv == nil || cv.Kind() != constant.String { + return + } + pat := constant.StringVal(cv) + c.cause = call.Args[0] + c.checkPattern(pat) + } +} + +func (c *badRegexpChecker) checkPattern(pat string) { + re, err := c.parser.Parse(pat) + if err != nil { + return + } + + c.flagStates = c.flagStates[:0] + c.goodAnchors = c.goodAnchors[:0] + + // In Go all flags (modifiers) are set to false by default, + // so we start from the empty flag set. + c.flagStates = append(c.flagStates, regexpFlagState{}) + + c.markGoodCarets(re.Expr) + c.walk(re.Expr) +} + +func (c *badRegexpChecker) markGoodCarets(e syntax.Expr) { + canSkip := func(e syntax.Expr) bool { + switch e.Op { + case syntax.OpFlagOnlyGroup: + return true + case syntax.OpGroup: + x := e.Args[0] + return x.Op == syntax.OpConcat && len(x.Args) == 0 + } + return false + } + + if e.Op == syntax.OpConcat && len(e.Args) > 1 { + i := 0 + for i < len(e.Args) && canSkip(e.Args[i]) { + i++ + } + if i < len(e.Args) { + c.markGoodCarets(e.Args[i]) + } + return + } + if e.Op == syntax.OpCaret { + c.addGoodAnchor(e.Pos) + } + for _, a := range e.Args { + c.markGoodCarets(a) + } +} + +func (c *badRegexpChecker) walk(e syntax.Expr) { + switch e.Op { + case syntax.OpAlt: + c.checkAltAnchor(e) + c.checkAltDups(e) + for _, a := range e.Args { + c.walk(a) + } + + case syntax.OpCharClass, syntax.OpNegCharClass: + if c.checkCharClassRanges(e) { + c.checkCharClassDups(e) + } + + case syntax.OpStar, syntax.OpPlus: + c.checkNestedQuantifier(e) + c.walk(e.Args[0]) + + case syntax.OpFlagOnlyGroup: + c.updateFlagState(c.currentFlagState(), e, e.Args[0].Value) + case syntax.OpGroupWithFlags: + // Creates a new context using the current context copy. + // New flags are evaluated inside a new context. + // After nested expressions are processed, previous context is restored. + nflags := len(c.flagStates) + c.flagStates = append(c.flagStates, *c.currentFlagState()) + c.updateFlagState(c.currentFlagState(), e, e.Args[1].Value) + c.walk(e.Args[0]) + c.flagStates = c.flagStates[:nflags] + case syntax.OpGroup, syntax.OpCapture, syntax.OpNamedCapture: + // Like with OpGroupWithFlags, but doesn't evaluate any new flags. + nflags := len(c.flagStates) + c.flagStates = append(c.flagStates, *c.currentFlagState()) + c.walk(e.Args[0]) + c.flagStates = c.flagStates[:nflags] + + case syntax.OpCaret: + if !c.isGoodAnchor(e) { + c.warn("dangling or redundant ^, maybe \\^ is intended?") + } + + default: + for _, a := range e.Args { + c.walk(a) + } + } +} + +func (c *badRegexpChecker) currentFlagState() *regexpFlagState { + return &c.flagStates[len(c.flagStates)-1] +} + +func (c *badRegexpChecker) updateFlagState(state *regexpFlagState, e syntax.Expr, flagString string) { + clearing := false + for i := 0; i < len(flagString); i++ { + ch := flagString[i] + if ch == '-' { + clearing = true + continue + } + if int(ch) >= len(state) { + continue // Should never happen in practice, but we don't want a panic + } + + if clearing { + if !state[ch] { + c.warn("clearing unset flag %c in %s", ch, e.Value) + } + } else { + if state[ch] { + c.warn("redundant flag %c in %s", ch, e.Value) + } + } + state[ch] = !clearing + } +} + +func (c *badRegexpChecker) checkNestedQuantifier(e syntax.Expr) { + x := e.Args[0] + switch x.Op { + case syntax.OpGroup, syntax.OpCapture, syntax.OpGroupWithFlags: + if len(e.Args) == 1 { + x = x.Args[0] + } + } + + switch x.Op { + case syntax.OpPlus, syntax.OpStar: + c.warn("repeated greedy quantifier in %s", e.Value) + } +} + +func (c *badRegexpChecker) checkAltDups(alt syntax.Expr) { + // Seek duplicated alternation expressions. + + set := make(map[string]struct{}, len(alt.Args)) + for _, a := range alt.Args { + if _, ok := set[a.Value]; ok { + c.warn("`%s` is duplicated in %s", a.Value, alt.Value) + } + set[a.Value] = struct{}{} + } +} + +func (c *badRegexpChecker) isCharOrLit(e syntax.Expr) bool { + return e.Op == syntax.OpChar || e.Op == syntax.OpLiteral +} + +func (c *badRegexpChecker) checkAltAnchor(alt syntax.Expr) { + // Seek suspicious anchors. + + // Case 1: an alternation of literals where 1st expr begins with ^ anchor. + first := alt.Args[0] + if first.Op == syntax.OpConcat && len(first.Args) == 2 && first.Args[0].Op == syntax.OpCaret && c.isCharOrLit(first.Args[1]) { + matched := true + for _, a := range alt.Args[1:] { + if !c.isCharOrLit(a) { + matched = false + break + } + } + if matched { + c.warn("^ applied only to `%s` in %s", first.Value[len(`^`):], alt.Value) + } + } + + // Case 2: an alternation of literals where last expr ends with $ anchor. + last := alt.Args[len(alt.Args)-1] + if last.Op == syntax.OpConcat && len(last.Args) == 2 && last.Args[1].Op == syntax.OpDollar && c.isCharOrLit(last.Args[0]) { + matched := true + for _, a := range alt.Args[:len(alt.Args)-1] { + if !c.isCharOrLit(a) { + matched = false + break + } + } + if matched { + c.warn("$ applied only to `%s` in %s", last.Value[:len(last.Value)-len(`$`)], alt.Value) + } + } +} + +func (c *badRegexpChecker) checkCharClassRanges(cc syntax.Expr) bool { + // Seek for suspicious ranges like `!-_`. + // + // We permit numerical ranges (0-9, hex and octal literals) + // and simple ascii letter ranges. + + for _, e := range cc.Args { + if e.Op != syntax.OpCharRange { + continue + } + switch e.Args[0].Op { + case syntax.OpEscapeOctal, syntax.OpEscapeHex: + continue + } + ch := c.charClassBoundRune(e.Args[0]) + if ch == 0 { + return false + } + good := unicode.IsLetter(ch) || (ch >= '0' && ch <= '9') + if !good { + c.warnSloppyCharRange(e.Value, cc.Value) + } + } + + return true +} + +func (c *badRegexpChecker) checkCharClassDups(cc syntax.Expr) { + // Seek for excessive elements inside a character class. + // Report them as intersections. + + if len(cc.Args) == 1 { + return // Can't had duplicates. + } + + type charRange struct { + low rune + high rune + source string + } + ranges := make([]charRange, 0, 8) + addRange := func(source string, low, high rune) { + ranges = append(ranges, charRange{source: source, low: low, high: high}) + } + addRange1 := func(source string, ch rune) { + addRange(source, ch, ch) + } + + // 1. Collect ranges, O(n). + for _, e := range cc.Args { + switch e.Op { + case syntax.OpEscapeOctal: + addRange1(e.Value, c.octalToRune(e)) + case syntax.OpEscapeHex: + addRange1(e.Value, c.hexToRune(e)) + case syntax.OpChar: + addRange1(e.Value, c.stringToRune(e.Value)) + case syntax.OpCharRange: + addRange(e.Value, c.charClassBoundRune(e.Args[0]), c.charClassBoundRune(e.Args[1])) + case syntax.OpEscapeMeta: + addRange1(e.Value, rune(e.Value[1])) + case syntax.OpEscapeChar: + ch := c.stringToRune(e.Value[len(`\`):]) + if unicode.IsPunct(ch) { + addRange1(e.Value, ch) + break + } + switch e.Value { + case `\|`, `\<`, `\>`, `\+`, `\=`: // How to cover all symbols? + addRange1(e.Value, c.stringToRune(e.Value[len(`\`):])) + case `\t`: + addRange1(e.Value, '\t') + case `\n`: + addRange1(e.Value, '\n') + case `\r`: + addRange1(e.Value, '\r') + case `\v`: + addRange1(e.Value, '\v') + case `\d`: + addRange(e.Value, '0', '9') + case `\D`: + addRange(e.Value, 0, '0'-1) + addRange(e.Value, '9'+1, utf8.MaxRune) + case `\s`: + addRange(e.Value, '\t', '\n') // 9-10 + addRange(e.Value, '\f', '\r') // 12-13 + addRange1(e.Value, ' ') // 32 + case `\S`: + addRange(e.Value, 0, '\t'-1) + addRange(e.Value, '\n'+1, '\f'-1) + addRange(e.Value, '\r'+1, ' '-1) + addRange(e.Value, ' '+1, utf8.MaxRune) + case `\w`: + addRange(e.Value, '0', '9') // 48-57 + addRange(e.Value, 'A', 'Z') // 65-90 + addRange1(e.Value, '_') // 95 + addRange(e.Value, 'a', 'z') // 97-122 + case `\W`: + addRange(e.Value, 0, '0'-1) + addRange(e.Value, '9'+1, 'A'-1) + addRange(e.Value, 'Z'+1, '_'-1) + addRange(e.Value, '_'+1, 'a'-1) + addRange(e.Value, 'z'+1, utf8.MaxRune) + default: + // Give up: unknown escape sequence. + return + } + default: + // Give up: unexpected operation inside char class. + return + } + } + + // 2. Sort ranges, O(nlogn). + sort.Slice(ranges, func(i, j int) bool { + return ranges[i].low < ranges[j].low + }) + + // 3. Search for duplicates, O(n). + for i := 0; i < len(ranges)-1; i++ { + x := ranges[i+0] + y := ranges[i+1] + if x.high >= y.low { + c.warnCharClassDup(x.source, y.source, cc.Value) + break + } + } +} + +func (c *badRegexpChecker) charClassBoundRune(e syntax.Expr) rune { + switch e.Op { + case syntax.OpChar: + return c.stringToRune(e.Value) + case syntax.OpEscapeHex: + return c.hexToRune(e) + case syntax.OpEscapeOctal: + return c.octalToRune(e) + default: + return 0 + } +} + +func (c *badRegexpChecker) octalToRune(e syntax.Expr) rune { + v, _ := strconv.ParseInt(e.Value[len(`\`):], 8, 32) + return rune(v) +} + +func (c *badRegexpChecker) hexToRune(e syntax.Expr) rune { + var s string + switch e.Form { + case syntax.FormEscapeHexFull: + s = e.Value[len(`\x{`) : len(e.Value)-len(`}`)] + default: + s = e.Value[len(`\x`):] + } + v, _ := strconv.ParseInt(s, 16, 32) + return rune(v) +} + +func (c *badRegexpChecker) stringToRune(s string) rune { + ch, _ := utf8.DecodeRuneInString(s) + return ch +} + +func (c *badRegexpChecker) addGoodAnchor(pos syntax.Position) { + c.goodAnchors = append(c.goodAnchors, pos) +} + +func (c *badRegexpChecker) isGoodAnchor(e syntax.Expr) bool { + for _, pos := range c.goodAnchors { + if e.Pos == pos { + return true + } + } + return false +} + +func (c *badRegexpChecker) warn(format string, args ...interface{}) { + c.ctx.Warn(c.cause, format, args...) +} + +func (c *badRegexpChecker) warnSloppyCharRange(rng, charClass string) { + c.ctx.Warn(c.cause, "suspicious char range `%s` in %s", rng, charClass) +} + +func (c *badRegexpChecker) warnCharClassDup(x, y, charClass string) { + if x == y { + c.ctx.Warn(c.cause, "`%s` is duplicated in %s", x, charClass) + } else { + c.ctx.Warn(c.cause, "`%s` intersects with `%s` in %s", x, y, charClass) + } +} diff --git a/vendor/github.com/go-critic/go-critic/checkers/boolExprSimplify_checker.go b/vendor/github.com/go-critic/go-critic/checkers/boolExprSimplify_checker.go index f4eb9ed7394..8c599031dba 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/boolExprSimplify_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/boolExprSimplify_checker.go @@ -6,9 +6,9 @@ import ( "go/token" "strconv" + "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/checkers/internal/lintutil" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/astequal" @@ -18,7 +18,7 @@ import ( ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "boolExprSimplify" info.Tags = []string{"style", "experimental"} info.Summary = "Detects bool expressions that can be simplified" @@ -29,14 +29,14 @@ b := !(x) == !(y)` a := elapsed < expectElapsedMin b := (x) == (y)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&boolExprSimplifyChecker{ctx: ctx}) }) } type boolExprSimplifyChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext hasFloats bool } diff --git a/vendor/github.com/go-critic/go-critic/checkers/builtinShadow_checker.go b/vendor/github.com/go-critic/go-critic/checkers/builtinShadow_checker.go index 24d8b7fff4f..ff5e517464a 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/builtinShadow_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/builtinShadow_checker.go @@ -3,26 +3,26 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "builtinShadow" info.Tags = []string{"style", "opinionated"} info.Summary = "Detects when predeclared identifiers shadowed in assignments" info.Before = `len := 10` info.After = `length := 10` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForLocalDef(&builtinShadowChecker{ctx: ctx}, ctx.TypesInfo) }) } type builtinShadowChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *builtinShadowChecker) VisitLocalDef(name astwalk.Name, _ ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/captLocal_checker.go b/vendor/github.com/go-critic/go-critic/checkers/captLocal_checker.go index bc9a2115f2f..76b6fb4fc3c 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/captLocal_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/captLocal_checker.go @@ -3,15 +3,15 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "captLocal" info.Tags = []string{"style"} - info.Params = lintpack.CheckerParams{ + info.Params = linter.CheckerParams{ "paramsOnly": { Value: true, Usage: "whether to restrict checker to params only", @@ -21,7 +21,7 @@ func init() { info.Before = `func f(IN int, OUT *int) (ERR error) {}` info.After = `func f(in int, out *int) (err error) {}` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &captLocalChecker{ctx: ctx} c.paramsOnly = info.Params.Bool("paramsOnly") return astwalk.WalkerForLocalDef(c, ctx.TypesInfo) @@ -30,7 +30,7 @@ func init() { type captLocalChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext paramsOnly bool } diff --git a/vendor/github.com/go-critic/go-critic/checkers/caseOrder_checker.go b/vendor/github.com/go-critic/go-critic/checkers/caseOrder_checker.go index 1ef4b53b7ff..95036752038 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/caseOrder_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/caseOrder_checker.go @@ -4,12 +4,12 @@ import ( "go/ast" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "caseOrder" info.Tags = []string{"diagnostic"} info.Summary = "Detects erroneous case order inside switch statements" @@ -28,14 +28,14 @@ case ast.Expr: fmt.Println("expr") }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&caseOrderChecker{ctx: ctx}) }) } type caseOrderChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *caseOrderChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/checkers.go b/vendor/github.com/go-critic/go-critic/checkers/checkers.go index 96202221e2b..0c2ebc00cac 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/checkers.go +++ b/vendor/github.com/go-critic/go-critic/checkers/checkers.go @@ -2,9 +2,18 @@ package checkers import ( - "github.com/go-lintpack/lintpack" + "os" + + "github.com/go-critic/go-critic/framework/linter" ) -var collection = &lintpack.CheckerCollection{ +var collection = &linter.CheckerCollection{ URL: "https://github.com/go-critic/go-critic/checkers", } + +var debug = func() func() bool { + v := os.Getenv("DEBUG") != "" + return func() bool { + return v + } +}() diff --git a/vendor/github.com/go-critic/go-critic/checkers/codegenComment_checker.go b/vendor/github.com/go-critic/go-critic/checkers/codegenComment_checker.go index 14d89da374b..377895386ec 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/codegenComment_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/codegenComment_checker.go @@ -5,19 +5,19 @@ import ( "regexp" "strings" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "codegenComment" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects malformed 'code generated' file comments" info.Before = `// This file was automatically generated by foogen` info.After = `// Code generated by foogen. DO NOT EDIT.` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { patterns := []string{ "this (?:file|code) (?:was|is) auto(?:matically)? generated", "this (?:file|code) (?:was|is) generated automatically", @@ -38,7 +38,7 @@ func init() { type codegenCommentChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext badCommentRE *regexp.Regexp } diff --git a/vendor/github.com/go-critic/go-critic/checkers/commentFormatting_checker.go b/vendor/github.com/go-critic/go-critic/checkers/commentFormatting_checker.go index ed75015e095..cb69331bea5 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/commentFormatting_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/commentFormatting_checker.go @@ -7,23 +7,25 @@ import ( "unicode" "unicode/utf8" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "commentFormatting" info.Tags = []string{"style", "experimental"} info.Summary = "Detects comments with non-idiomatic formatting" info.Before = `//This is a comment` info.After = `// This is a comment` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { parts := []string{ - `^//\w+:.*$`, //key: value - `^//nolint$`, //nolint - `^//line /.*:\d+`, //line /path/to/file:123 + `^//go:generate .*$`, // e.g.: go:generate value + `^//\w+:.*$`, // e.g.: key: value + `^//nolint$`, // e.g.: nolint + `^//line /.*:\d+`, // e.g.: line /path/to/file:123 + `^//export \w+$`, // e.g.: export Foo } pat := "(?m)" + strings.Join(parts, "|") pragmaRE := regexp.MustCompile(pat) @@ -36,7 +38,7 @@ func init() { type commentFormattingChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext pragmaRE *regexp.Regexp } diff --git a/vendor/github.com/go-critic/go-critic/checkers/commentedOutCode_checker.go b/vendor/github.com/go-critic/go-critic/checkers/commentedOutCode_checker.go index 0554e365ed3..8d93870459b 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/commentedOutCode_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/commentedOutCode_checker.go @@ -7,13 +7,13 @@ import ( "regexp" "strings" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/strparse" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "commentedOutCode" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects commented-out code inside function bodies" @@ -22,7 +22,7 @@ func init() { foo(1, 2)` info.After = `foo(1, 2)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForLocalComment(&commentedOutCodeChecker{ ctx: ctx, notQuiteFuncCall: regexp.MustCompile(`\w+\s+\([^)]*\)\s*$`), @@ -32,7 +32,7 @@ foo(1, 2)` type commentedOutCodeChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext fn *ast.FuncDecl notQuiteFuncCall *regexp.Regexp diff --git a/vendor/github.com/go-critic/go-critic/checkers/commentedOutImport_checker.go b/vendor/github.com/go-critic/go-critic/checkers/commentedOutImport_checker.go index 5aeb86c0765..096a9024153 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/commentedOutImport_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/commentedOutImport_checker.go @@ -5,12 +5,12 @@ import ( "go/token" "regexp" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "commentedOutImport" info.Tags = []string{"style", "experimental"} info.Summary = "Detects commented-out imports" @@ -24,7 +24,7 @@ import ( "fmt" )` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { const pattern = `(?m)^(?://|/\*)?\s*"([a-zA-Z0-9_/]+)"\s*(?:\*/)?$` return &commentedOutImportChecker{ ctx: ctx, @@ -35,7 +35,7 @@ import ( type commentedOutImportChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext importStringRE *regexp.Regexp } diff --git a/vendor/github.com/go-critic/go-critic/checkers/defaultCaseOrder_checker.go b/vendor/github.com/go-critic/go-critic/checkers/defaultCaseOrder_checker.go index caa0de65720..755449e07ef 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/defaultCaseOrder_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/defaultCaseOrder_checker.go @@ -3,12 +3,12 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "defaultCaseOrder" info.Tags = []string{"style"} info.Summary = "Detects when default case in switch isn't on 1st or last position" @@ -31,14 +31,14 @@ default: // <- last case (could also be the first one) // ... }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&defaultCaseOrderChecker{ctx: ctx}) }) } type defaultCaseOrderChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *defaultCaseOrderChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/deferUnlambda_checker.go b/vendor/github.com/go-critic/go-critic/checkers/deferUnlambda_checker.go new file mode 100644 index 00000000000..3cab7827c98 --- /dev/null +++ b/vendor/github.com/go-critic/go-critic/checkers/deferUnlambda_checker.go @@ -0,0 +1,94 @@ +package checkers + +import ( + "go/ast" + "go/types" + + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" + "github.com/go-toolsmith/astcast" +) + +func init() { + var info linter.CheckerInfo + info.Name = "deferUnlambda" + info.Tags = []string{"style", "experimental"} + info.Summary = "Detects deferred function literals that can be simplified" + info.Before = `defer func() { f() }()` + info.After = `f()` + + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { + return astwalk.WalkerForStmt(&deferUnlambdaChecker{ctx: ctx}) + }) +} + +type deferUnlambdaChecker struct { + astwalk.WalkHandler + ctx *linter.CheckerContext +} + +func (c *deferUnlambdaChecker) VisitStmt(x ast.Stmt) { + def, ok := x.(*ast.DeferStmt) + if !ok { + return + } + + // We don't analyze deferred function args. + // Most deferred calls don't have them, so it's not a big deal to skip them. + if len(def.Call.Args) != 0 { + return + } + + fn, ok := def.Call.Fun.(*ast.FuncLit) + if !ok { + return + } + + if len(fn.Body.List) != 1 { + return + } + + call, ok := astcast.ToExprStmt(fn.Body.List[0]).X.(*ast.CallExpr) + if !ok || !c.isFunctionCall(call) { + return + } + + // Skip recover() as it can't be moved outside of the lambda. + // Skip panic() to avoid affecting the stack trace. + switch qualifiedName(call.Fun) { + case "recover", "panic": + return + } + + for _, arg := range call.Args { + if !c.isConstExpr(arg) { + return + } + } + + c.warn(def, call) +} + +func (c *deferUnlambdaChecker) isFunctionCall(e *ast.CallExpr) bool { + switch fnExpr := e.Fun.(type) { + case *ast.Ident: + return true + case *ast.SelectorExpr: + x, ok := fnExpr.X.(*ast.Ident) + if !ok { + return false + } + _, ok = c.ctx.TypesInfo.ObjectOf(x).(*types.PkgName) + return ok + default: + return false + } +} + +func (c *deferUnlambdaChecker) isConstExpr(e ast.Expr) bool { + return c.ctx.TypesInfo.Types[e].Value != nil +} + +func (c *deferUnlambdaChecker) warn(cause, suggestion ast.Node) { + c.ctx.Warn(cause, "can rewrite as `defer %s`", suggestion) +} diff --git a/vendor/github.com/go-critic/go-critic/checkers/deprecatedComment_checker.go b/vendor/github.com/go-critic/go-critic/checkers/deprecatedComment_checker.go index 37675735b86..aec237ca986 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/deprecatedComment_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/deprecatedComment_checker.go @@ -5,12 +5,12 @@ import ( "regexp" "strings" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "deprecatedComment" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects malformed 'deprecated' doc-comments" @@ -21,7 +21,7 @@ func FuncOld() int` // Deprecated: use FuncNew instead func FuncOld() int` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &deprecatedCommentChecker{ctx: ctx} c.commonPatterns = []*regexp.Regexp{ @@ -61,7 +61,7 @@ func FuncOld() int` type deprecatedCommentChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext commonPatterns []*regexp.Regexp commonTypos []string diff --git a/vendor/github.com/go-critic/go-critic/checkers/docStub_checker.go b/vendor/github.com/go-critic/go-critic/checkers/docStub_checker.go index 5c771b31cfb..2a3b393a0db 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/docStub_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/docStub_checker.go @@ -6,12 +6,12 @@ import ( "regexp" "strings" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "docStub" info.Tags = []string{"style", "experimental"} info.Summary = "Detects comments that silence go lint complaints about doc-comment" @@ -26,7 +26,7 @@ func Foo() {} // Foo is a demonstration-only function. func Foo() {}` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { re := `(?i)^\.\.\.$|^\.$|^xxx\.?$|^whatever\.?$` c := &docStubChecker{ ctx: ctx, @@ -38,7 +38,7 @@ func Foo() {}` type docStubChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext stubCommentRE *regexp.Regexp } diff --git a/vendor/github.com/go-critic/go-critic/checkers/dupArg_checker.go b/vendor/github.com/go-critic/go-critic/checkers/dupArg_checker.go index 819759403e2..24e921b093a 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/dupArg_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/dupArg_checker.go @@ -4,21 +4,21 @@ import ( "go/ast" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astequal" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "dupArg" info.Tags = []string{"diagnostic"} info.Summary = "Detects suspicious duplicated arguments" info.Before = `copy(dst, dst)` info.After = `copy(dst, src)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &dupArgChecker{ctx: ctx} // newMatcherFunc returns a function that matches a call if // args[xIndex] and args[yIndex] are equal. @@ -101,7 +101,7 @@ func init() { type dupArgChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext matchers map[string]func(*ast.CallExpr) bool } diff --git a/vendor/github.com/go-critic/go-critic/checkers/dupBranchBody_checker.go b/vendor/github.com/go-critic/go-critic/checkers/dupBranchBody_checker.go index a13884873c1..3399f05317c 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/dupBranchBody_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/dupBranchBody_checker.go @@ -3,13 +3,13 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astequal" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "dupBranchBody" info.Tags = []string{"diagnostic"} info.Summary = "Detects duplicated branch bodies inside conditional statements" @@ -26,14 +26,14 @@ if cond { println("cond=false") }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&dupBranchBodyChecker{ctx: ctx}) }) } type dupBranchBodyChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *dupBranchBodyChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/dupCase_checker.go b/vendor/github.com/go-critic/go-critic/checkers/dupCase_checker.go index 26ef17398f8..89ec66bbf02 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/dupCase_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/dupCase_checker.go @@ -3,13 +3,13 @@ package checkers import ( "go/ast" + "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/checkers/internal/lintutil" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "dupCase" info.Tags = []string{"diagnostic"} info.Summary = "Detects duplicated case clauses inside switch statements" @@ -22,14 +22,14 @@ switch x { case ys[0], ys[1], ys[2], ys[3], ys[4]: }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&dupCaseChecker{ctx: ctx}) }) } type dupCaseChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext astSet lintutil.AstSet } diff --git a/vendor/github.com/go-critic/go-critic/checkers/dupImports_checker.go b/vendor/github.com/go-critic/go-critic/checkers/dupImports_checker.go index d531413a11c..27b796cdc1e 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/dupImports_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/dupImports_checker.go @@ -4,11 +4,11 @@ import ( "fmt" "go/ast" - "github.com/go-lintpack/lintpack" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "dupImport" info.Tags = []string{"style", "experimental"} info.Summary = "Detects multiple imports of the same package under different aliases" @@ -22,13 +22,13 @@ import( "fmt" )` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return &dupImportChecker{ctx: ctx} }) } type dupImportChecker struct { - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *dupImportChecker) WalkFile(f *ast.File) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/dupSubExpr_checker.go b/vendor/github.com/go-critic/go-critic/checkers/dupSubExpr_checker.go index 24bb52434f3..4966cd2a5ac 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/dupSubExpr_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/dupSubExpr_checker.go @@ -5,14 +5,14 @@ import ( "go/token" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astequal" "github.com/go-toolsmith/typep" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "dupSubExpr" info.Tags = []string{"diagnostic"} info.Summary = "Detects suspicious duplicated sub-expressions" @@ -25,7 +25,7 @@ sort.Slice(xs, func(i, j int) bool { return xs[i].v < xs[j].v })` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &dupSubExprChecker{ctx: ctx} ops := []struct { @@ -65,7 +65,7 @@ sort.Slice(xs, func(i, j int) bool { type dupSubExprChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext // opSet is a set of binary operations that do not make // sense with duplicated (same) RHS and LHS. diff --git a/vendor/github.com/go-critic/go-critic/checkers/elseif_checker.go b/vendor/github.com/go-critic/go-critic/checkers/elseif_checker.go index c3a9546bf07..9e56d1c408a 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/elseif_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/elseif_checker.go @@ -3,16 +3,16 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astp" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "elseif" info.Tags = []string{"style"} - info.Params = lintpack.CheckerParams{ + info.Params = linter.CheckerParams{ "skipBalanced": { Value: true, Usage: "whether to skip balanced if-else pairs", @@ -30,7 +30,7 @@ if cond1 { } else if x := cond2; x { }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &elseifChecker{ctx: ctx} c.skipBalanced = info.Params.Bool("skipBalanced") return astwalk.WalkerForStmt(c) @@ -39,7 +39,7 @@ if cond1 { type elseifChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext skipBalanced bool } diff --git a/vendor/github.com/go-critic/go-critic/checkers/emptyFallthrough_checker.go b/vendor/github.com/go-critic/go-critic/checkers/emptyFallthrough_checker.go index 5908dfa3167..16bfa7e4579 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/emptyFallthrough_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/emptyFallthrough_checker.go @@ -4,12 +4,12 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "emptyFallthrough" info.Tags = []string{"style", "experimental"} info.Summary = "Detects fallthrough that can be avoided by using multi case values" @@ -24,14 +24,14 @@ case reflect.Int, reflect.Int32: return Int }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&emptyFallthroughChecker{ctx: ctx}) }) } type emptyFallthroughChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *emptyFallthroughChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/emptyStringTest_checker.go b/vendor/github.com/go-critic/go-critic/checkers/emptyStringTest_checker.go index a7be906ed08..20d647ffab2 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/emptyStringTest_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/emptyStringTest_checker.go @@ -4,15 +4,15 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/typep" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "emptyStringTest" info.Tags = []string{"style", "experimental"} info.Summary = "Detects empty string checks that can be written more idiomatically" @@ -20,14 +20,14 @@ func init() { info.After = `s == ""` info.Note = "See https://dmitri.shuralyov.com/idiomatic-go#empty-string-check." - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&emptyStringTestChecker{ctx: ctx}) }) } type emptyStringTestChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *emptyStringTestChecker) VisitExpr(e ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/equalFold_checker.go b/vendor/github.com/go-critic/go-critic/checkers/equalFold_checker.go index 265b2f79bee..b8dfdc02fd8 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/equalFold_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/equalFold_checker.go @@ -4,28 +4,28 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astequal" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "equalFold" info.Tags = []string{"performance", "experimental"} info.Summary = "Detects unoptimal strings/bytes case-insensitive comparison" info.Before = `strings.ToLower(x) == strings.ToLower(y)` info.After = `strings.EqualFold(x, y)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&equalFoldChecker{ctx: ctx}) }) } type equalFoldChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *equalFoldChecker) VisitExpr(e ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/evalOrder_checker.go b/vendor/github.com/go-critic/go-critic/checkers/evalOrder_checker.go index f76519cd7c8..0bec0e83a71 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/evalOrder_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/evalOrder_checker.go @@ -5,16 +5,16 @@ import ( "go/token" "go/types" + "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/checkers/internal/lintutil" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astequal" "github.com/go-toolsmith/typep" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "evalOrder" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects unwanted dependencies on the evaluation order" @@ -24,14 +24,14 @@ err := f(&x) return x, err ` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&evalOrderChecker{ctx: ctx}) }) } type evalOrderChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *evalOrderChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/exitAfterDefer_checker.go b/vendor/github.com/go-critic/go-critic/checkers/exitAfterDefer_checker.go index 05ed6ae9e1a..524c8f2c9fd 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/exitAfterDefer_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/exitAfterDefer_checker.go @@ -3,15 +3,15 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astfmt" "github.com/go-toolsmith/astp" "golang.org/x/tools/go/ast/astutil" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "exitAfterDefer" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects calls to exit/fatal inside functions that use defer" @@ -27,14 +27,14 @@ if bad { return }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForFuncDecl(&exitAfterDeferChecker{ctx: ctx}) }) } type exitAfterDeferChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *exitAfterDeferChecker) VisitFuncDecl(fn *ast.FuncDecl) { @@ -66,13 +66,11 @@ func (c *exitAfterDeferChecker) VisitFuncDecl(fn *ast.FuncDecl) { } func (c *exitAfterDeferChecker) warn(cause *ast.CallExpr, deferStmt *ast.DeferStmt) { - var s string + s := astfmt.Sprint(deferStmt) if fnlit, ok := deferStmt.Call.Fun.(*ast.FuncLit); ok { // To avoid long and multi-line warning messages, // collapse the function literals. s = "defer " + astfmt.Sprint(fnlit.Type) + "{...}(...)" - } else { - s = astfmt.Sprint(deferStmt) } c.ctx.Warn(cause, "%s clutters `%s`", cause.Fun, s) } diff --git a/vendor/github.com/go-critic/go-critic/checkers/filepathJoin_checker.go b/vendor/github.com/go-critic/go-critic/checkers/filepathJoin_checker.go new file mode 100644 index 00000000000..b11dc247023 --- /dev/null +++ b/vendor/github.com/go-critic/go-critic/checkers/filepathJoin_checker.go @@ -0,0 +1,50 @@ +package checkers + +import ( + "go/ast" + "strings" + + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" + "github.com/go-toolsmith/astcast" +) + +func init() { + var info linter.CheckerInfo + info.Name = "filepathJoin" + info.Tags = []string{"diagnostic", "experimental"} + info.Summary = "Detects problems in filepath.Join() function calls" + info.Before = `filepath.Join("dir/", filename)` + info.After = `filepath.Join("dir", filename)` + + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { + return astwalk.WalkerForExpr(&filepathJoinChecker{ctx: ctx}) + }) +} + +type filepathJoinChecker struct { + astwalk.WalkHandler + ctx *linter.CheckerContext +} + +func (c *filepathJoinChecker) VisitExpr(expr ast.Expr) { + call := astcast.ToCallExpr(expr) + if qualifiedName(call.Fun) != "filepath.Join" { + return + } + + for _, arg := range call.Args { + arg, ok := arg.(*ast.BasicLit) + if ok && c.hasSeparator(arg) { + c.warnSeparator(arg) + } + } +} + +func (c *filepathJoinChecker) hasSeparator(v *ast.BasicLit) bool { + return strings.ContainsAny(v.Value, `/\`) +} + +func (c *filepathJoinChecker) warnSeparator(sep ast.Expr) { + c.ctx.Warn(sep, "%s contains a path separator", sep) +} diff --git a/vendor/github.com/go-critic/go-critic/checkers/flagDeref_checker.go b/vendor/github.com/go-critic/go-critic/checkers/flagDeref_checker.go index cb9faee716d..393274c4350 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/flagDeref_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/flagDeref_checker.go @@ -3,12 +3,12 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "flagDeref" info.Tags = []string{"diagnostic"} info.Summary = "Detects immediate dereferencing of `flag` package pointers" @@ -21,7 +21,7 @@ flag.BoolVar(&b, "b", false, "b docs")` Dereferencing returned pointers will lead to hard to find errors where flag values are not updated after flag.Parse().` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &flagDerefChecker{ ctx: ctx, flagPtrFuncs: map[string]bool{ @@ -41,7 +41,7 @@ where flag values are not updated after flag.Parse().` type flagDerefChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext flagPtrFuncs map[string]bool } diff --git a/vendor/github.com/go-critic/go-critic/checkers/flagName_checker.go b/vendor/github.com/go-critic/go-critic/checkers/flagName_checker.go index 1d43ba52113..a3bb1c7cd1b 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/flagName_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/flagName_checker.go @@ -6,27 +6,27 @@ import ( "go/types" "strings" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "flagName" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects flag names with whitespace" info.Before = `b := flag.Bool(" foo ", false, "description")` info.After = `b := flag.Bool("foo", false, "description")` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&flagNameChecker{ctx: ctx}) }) } type flagNameChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *flagNameChecker) VisitExpr(expr ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/hexLiteral_checker.go b/vendor/github.com/go-critic/go-critic/checkers/hexLiteral_checker.go index a700314cf3d..f3f9c535c69 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/hexLiteral_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/hexLiteral_checker.go @@ -5,13 +5,13 @@ import ( "go/token" "strings" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "hexLiteral" info.Tags = []string{"style", "experimental"} info.Summary = "Detects hex literals that have mixed case letter digits" @@ -25,14 +25,14 @@ y := 0xff // (B) y := 0xFF` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&hexLiteralChecker{ctx: ctx}) }) } type hexLiteralChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *hexLiteralChecker) warn0X(lit *ast.BasicLit) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/hugeParam_checker.go b/vendor/github.com/go-critic/go-critic/checkers/hugeParam_checker.go index 656b4cc2d79..54be776387a 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/hugeParam_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/hugeParam_checker.go @@ -3,15 +3,15 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "hugeParam" info.Tags = []string{"performance"} - info.Params = lintpack.CheckerParams{ + info.Params = linter.CheckerParams{ "sizeThreshold": { Value: 80, Usage: "size in bytes that makes the warning trigger", @@ -21,7 +21,7 @@ func init() { info.Before = `func f(x [1024]int) {}` info.After = `func f(x *[1024]int) {}` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForFuncDecl(&hugeParamChecker{ ctx: ctx, sizeThreshold: int64(info.Params.Int("sizeThreshold")), @@ -31,7 +31,7 @@ func init() { type hugeParamChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext sizeThreshold int64 } diff --git a/vendor/github.com/go-critic/go-critic/checkers/ifElseChain_checker.go b/vendor/github.com/go-critic/go-critic/checkers/ifElseChain_checker.go index c0a456afd21..91e1cfb39e0 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/ifElseChain_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/ifElseChain_checker.go @@ -3,12 +3,12 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "ifElseChain" info.Tags = []string{"style"} info.Summary = "Detects repeated if-else statements and suggests to replace them with switch statement" @@ -34,14 +34,14 @@ Permits single else or else-if; repeated else-if or else + else-if will trigger suggestion to use switch statement. See [EffectiveGo#switch](https://golang.org/doc/effective_go.html#switch).` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&ifElseChainChecker{ctx: ctx}) }) } type ifElseChainChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext cause *ast.IfStmt visited map[*ast.IfStmt]bool diff --git a/vendor/github.com/go-critic/go-critic/checkers/importShadow_checker.go b/vendor/github.com/go-critic/go-critic/checkers/importShadow_checker.go index 9a2ccc55ecd..60c0ab21e9c 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/importShadow_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/importShadow_checker.go @@ -4,12 +4,12 @@ import ( "go/ast" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "importShadow" info.Tags = []string{"style", "opinionated"} info.Summary = "Detects when imported package names shadowed in the assignments" @@ -19,7 +19,7 @@ filepath := "foo.txt"` info.After = ` filename := "foo.txt"` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { ctx.Require.PkgObjects = true return astwalk.WalkerForLocalDef(&importShadowChecker{ctx: ctx}, ctx.TypesInfo) }) @@ -27,7 +27,7 @@ filename := "foo.txt"` type importShadowChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *importShadowChecker) VisitLocalDef(def astwalk.Name, _ ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/indexAlloc_checker.go b/vendor/github.com/go-critic/go-critic/checkers/indexAlloc_checker.go index 8fbe98c9d2b..73399887391 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/indexAlloc_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/indexAlloc_checker.go @@ -3,14 +3,14 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/typep" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "indexAlloc" info.Tags = []string{"performance"} info.Summary = "Detects strings.Index calls that may cause unwanted allocs" @@ -18,14 +18,14 @@ func init() { info.After = `bytes.Index(x, []byte(y))` info.Note = `See Go issue for details: https://github.com/golang/go/issues/25864` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&indexAllocChecker{ctx: ctx}) }) } type indexAllocChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *indexAllocChecker) VisitExpr(e ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/initClause_checker.go b/vendor/github.com/go-critic/go-critic/checkers/initClause_checker.go index bfbd661b245..91e8816d238 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/initClause_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/initClause_checker.go @@ -3,13 +3,13 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astp" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "initClause" info.Tags = []string{"style", "opinionated", "experimental"} info.Summary = "Detects non-assignment statements inside if/switch init clause" @@ -19,14 +19,14 @@ func init() { if cond { }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&initClauseChecker{ctx: ctx}) }) } type initClauseChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *initClauseChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/comment_walker.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/comment_walker.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/comment_walker.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/comment_walker.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/doc_comment_walker.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/doc_comment_walker.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/doc_comment_walker.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/doc_comment_walker.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/expr_walker.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/expr_walker.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/expr_walker.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/expr_walker.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/func_decl_walker.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/func_decl_walker.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/func_decl_walker.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/func_decl_walker.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/local_comment_walker.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/local_comment_walker.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/local_comment_walker.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/local_comment_walker.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/local_def_visitor.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/local_def_visitor.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/local_def_visitor.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/local_def_visitor.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/local_def_walker.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/local_def_walker.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/local_def_walker.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/local_def_walker.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/local_expr_walker.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/local_expr_walker.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/local_expr_walker.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/local_expr_walker.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/stmt_list_walker.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/stmt_list_walker.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/stmt_list_walker.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/stmt_list_walker.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/stmt_walker.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/stmt_walker.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/stmt_walker.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/stmt_walker.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/type_expr_walker.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/type_expr_walker.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/type_expr_walker.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/type_expr_walker.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/visitor.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/visitor.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/visitor.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/visitor.go diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/walk_handler.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/walk_handler.go similarity index 100% rename from vendor/github.com/go-lintpack/lintpack/astwalk/walk_handler.go rename to vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/walk_handler.go diff --git a/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/walker.go b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/walker.go new file mode 100644 index 00000000000..cd5e1c9793c --- /dev/null +++ b/vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/walker.go @@ -0,0 +1,57 @@ +package astwalk + +import ( + "go/types" + + "github.com/go-critic/go-critic/framework/linter" +) + +// WalkerForFuncDecl returns file walker implementation for FuncDeclVisitor. +func WalkerForFuncDecl(v FuncDeclVisitor) linter.FileWalker { + return &funcDeclWalker{visitor: v} +} + +// WalkerForExpr returns file walker implementation for ExprVisitor. +func WalkerForExpr(v ExprVisitor) linter.FileWalker { + return &exprWalker{visitor: v} +} + +// WalkerForLocalExpr returns file walker implementation for LocalExprVisitor. +func WalkerForLocalExpr(v LocalExprVisitor) linter.FileWalker { + return &localExprWalker{visitor: v} +} + +// WalkerForStmtList returns file walker implementation for StmtListVisitor. +func WalkerForStmtList(v StmtListVisitor) linter.FileWalker { + return &stmtListWalker{visitor: v} +} + +// WalkerForStmt returns file walker implementation for StmtVisitor. +func WalkerForStmt(v StmtVisitor) linter.FileWalker { + return &stmtWalker{visitor: v} +} + +// WalkerForTypeExpr returns file walker implementation for TypeExprVisitor. +func WalkerForTypeExpr(v TypeExprVisitor, info *types.Info) linter.FileWalker { + return &typeExprWalker{visitor: v, info: info} +} + +// WalkerForLocalComment returns file walker implementation for LocalCommentVisitor. +func WalkerForLocalComment(v LocalCommentVisitor) linter.FileWalker { + return &localCommentWalker{visitor: v} +} + +// WalkerForComment returns file walker implementation for CommentVisitor. +func WalkerForComment(v CommentVisitor) linter.FileWalker { + return &commentWalker{visitor: v} +} + +// WalkerForDocComment returns file walker implementation for DocCommentVisitor. +func WalkerForDocComment(v DocCommentVisitor) linter.FileWalker { + return &docCommentWalker{visitor: v} +} + +// WalkerForLocalDef returns file walker implementation for LocalDefVisitor. +func WalkerForLocalDef(v LocalDefVisitor, info *types.Info) linter.FileWalker { + return &localDefWalker{visitor: v, info: info} +} diff --git a/vendor/github.com/go-critic/go-critic/checkers/mapKey_checker.go b/vendor/github.com/go-critic/go-critic/checkers/mapKey_checker.go index de3e781e52a..0b7100c721e 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/mapKey_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/mapKey_checker.go @@ -5,16 +5,16 @@ import ( "go/types" "strings" + "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/checkers/internal/lintutil" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astp" "github.com/go-toolsmith/typep" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "mapKey" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects suspicious map literal keys" @@ -29,14 +29,14 @@ _ = map[string]int{ "bar": 2, }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&mapKeyChecker{ctx: ctx}) }) } type mapKeyChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext astSet lintutil.AstSet } diff --git a/vendor/github.com/go-critic/go-critic/checkers/methodExprCall_checker.go b/vendor/github.com/go-critic/go-critic/checkers/methodExprCall_checker.go index 60da116559c..efd631143f5 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/methodExprCall_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/methodExprCall_checker.go @@ -4,15 +4,15 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/typep" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "methodExprCall" info.Tags = []string{"style", "experimental"} info.Summary = "Detects method expression call that can be replaced with a method call" @@ -21,14 +21,14 @@ foo.bar(f)` info.After = `f := foo{} f.bar()` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&methodExprCallChecker{ctx: ctx}) }) } type methodExprCallChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *methodExprCallChecker) VisitExpr(x ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/nestingReduce_checker.go b/vendor/github.com/go-critic/go-critic/checkers/nestingReduce_checker.go index 4a0331d5c72..de02c7eec78 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/nestingReduce_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/nestingReduce_checker.go @@ -3,15 +3,15 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "nestingReduce" info.Tags = []string{"style", "opinionated", "experimental"} - info.Params = lintpack.CheckerParams{ + info.Params = linter.CheckerParams{ "bodyWidth": { Value: 5, Usage: "min number of statements inside a branch to trigger a warning", @@ -32,7 +32,7 @@ for _, v := range a { body() }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &nestingReduceChecker{ctx: ctx} c.bodyWidth = info.Params.Int("bodyWidth") return astwalk.WalkerForStmt(c) @@ -41,7 +41,7 @@ for _, v := range a { type nestingReduceChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext bodyWidth int } diff --git a/vendor/github.com/go-critic/go-critic/checkers/newDeref_checker.go b/vendor/github.com/go-critic/go-critic/checkers/newDeref_checker.go index 75e7f642824..e03ec9514fd 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/newDeref_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/newDeref_checker.go @@ -3,29 +3,29 @@ package checkers import ( "go/ast" + "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/checkers/internal/lintutil" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "golang.org/x/tools/go/ast/astutil" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "newDeref" info.Tags = []string{"style", "experimental"} info.Summary = "Detects immediate dereferencing of `new` expressions" info.Before = `x := *new(bool)` info.After = `x := false` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&newDerefChecker{ctx: ctx}) }) } type newDerefChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *newDerefChecker) VisitExpr(expr ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/nilValReturn_checker.go b/vendor/github.com/go-critic/go-critic/checkers/nilValReturn_checker.go index 231e25800fa..37f964f7087 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/nilValReturn_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/nilValReturn_checker.go @@ -4,14 +4,14 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astequal" "github.com/go-toolsmith/typep" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "nilValReturn" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects return statements those results evaluate to nil" @@ -29,14 +29,14 @@ if err != nil { return err }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&nilValReturnChecker{ctx: ctx}) }) } type nilValReturnChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *nilValReturnChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/octalLiteral_checker.go b/vendor/github.com/go-critic/go-critic/checkers/octalLiteral_checker.go index e40ec6db5e3..a1d96804301 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/octalLiteral_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/octalLiteral_checker.go @@ -5,20 +5,20 @@ import ( "go/token" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "octalLiteral" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects octal literals passed to functions" info.Before = `foo(02)` info.After = `foo(2)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &octalLiteralChecker{ ctx: ctx, octFriendlyPkg: map[string]bool{ @@ -32,7 +32,7 @@ func init() { type octalLiteralChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext octFriendlyPkg map[string]bool } diff --git a/vendor/github.com/go-critic/go-critic/checkers/offBy1_checker.go b/vendor/github.com/go-critic/go-critic/checkers/offBy1_checker.go index d5c8de0b796..1d8a45e328e 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/offBy1_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/offBy1_checker.go @@ -4,8 +4,8 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/astequal" @@ -13,21 +13,21 @@ import ( ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "offBy1" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects various off-by-one kind of errors" info.Before = `xs[len(xs)]` info.After = `xs[len(xs)-1]` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&offBy1Checker{ctx: ctx}) }) } type offBy1Checker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *offBy1Checker) VisitExpr(e ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/paramTypeCombine_checker.go b/vendor/github.com/go-critic/go-critic/checkers/paramTypeCombine_checker.go index ffa74061e67..e13ea900684 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/paramTypeCombine_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/paramTypeCombine_checker.go @@ -3,27 +3,27 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astequal" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "paramTypeCombine" info.Tags = []string{"style", "opinionated"} info.Summary = "Detects if function parameters could be combined by type and suggest the way to do it" info.Before = `func foo(a, b int, c, d int, e, f int, g int) {}` info.After = `func foo(a, b, c, d, e, f, g int) {}` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForFuncDecl(¶mTypeCombineChecker{ctx: ctx}) }) } type paramTypeCombineChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *paramTypeCombineChecker) EnterFunc(*ast.FuncDecl) bool { diff --git a/vendor/github.com/go-critic/go-critic/checkers/ptrToRefParam_checker.go b/vendor/github.com/go-critic/go-critic/checkers/ptrToRefParam_checker.go index dacffc85ab4..2716fe04b80 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/ptrToRefParam_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/ptrToRefParam_checker.go @@ -4,26 +4,26 @@ import ( "go/ast" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "ptrToRefParam" info.Tags = []string{"style", "opinionated", "experimental"} info.Summary = "Detects input and output parameters that have a type of pointer to referential type" info.Before = `func f(m *map[string]int) (*chan *int)` info.After = `func f(m map[string]int) (chan *int)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForFuncDecl(&ptrToRefParamChecker{ctx: ctx}) }) } type ptrToRefParamChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *ptrToRefParamChecker) VisitFuncDecl(fn *ast.FuncDecl) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/rangeExprCopy_checker.go b/vendor/github.com/go-critic/go-critic/checkers/rangeExprCopy_checker.go index 387d1bbbcc0..90b5987abb7 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/rangeExprCopy_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/rangeExprCopy_checker.go @@ -4,15 +4,15 @@ import ( "go/ast" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "rangeExprCopy" info.Tags = []string{"performance"} - info.Params = lintpack.CheckerParams{ + info.Params = linter.CheckerParams{ "sizeThreshold": { Value: 512, Usage: "size in bytes that makes the warning trigger", @@ -36,7 +36,7 @@ for _, x := range &xs { // No copy }` info.Note = "See Go issue for details: https://github.com/golang/go/issues/15812." - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &rangeExprCopyChecker{ctx: ctx} c.sizeThreshold = int64(info.Params.Int("sizeThreshold")) c.skipTestFuncs = info.Params.Bool("skipTestFuncs") @@ -46,7 +46,7 @@ for _, x := range &xs { // No copy type rangeExprCopyChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext sizeThreshold int64 skipTestFuncs bool diff --git a/vendor/github.com/go-critic/go-critic/checkers/rangeValCopy_checker.go b/vendor/github.com/go-critic/go-critic/checkers/rangeValCopy_checker.go index 182538a9f0a..57dcc315128 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/rangeValCopy_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/rangeValCopy_checker.go @@ -3,15 +3,15 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "rangeValCopy" info.Tags = []string{"performance"} - info.Params = lintpack.CheckerParams{ + info.Params = linter.CheckerParams{ "sizeThreshold": { Value: 128, Usage: "size in bytes that makes the warning trigger", @@ -35,7 +35,7 @@ for i := range xs { // Loop body. }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &rangeValCopyChecker{ctx: ctx} c.sizeThreshold = int64(info.Params.Int("sizeThreshold")) c.skipTestFuncs = info.Params.Bool("skipTestFuncs") @@ -45,7 +45,7 @@ for i := range xs { type rangeValCopyChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext sizeThreshold int64 skipTestFuncs bool diff --git a/vendor/github.com/go-critic/go-critic/checkers/regexpMust_checker.go b/vendor/github.com/go-critic/go-critic/checkers/regexpMust_checker.go index ef7a397877c..411932ee5df 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/regexpMust_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/regexpMust_checker.go @@ -4,28 +4,28 @@ import ( "go/ast" "strings" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astp" "golang.org/x/tools/go/ast/astutil" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "regexpMust" info.Tags = []string{"style"} info.Summary = "Detects `regexp.Compile*` that can be replaced with `regexp.MustCompile*`" info.Before = `re, _ := regexp.Compile("const pattern")` info.After = `re := regexp.MustCompile("const pattern")` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(®expMustChecker{ctx: ctx}) }) } type regexpMustChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *regexpMustChecker) VisitExpr(x ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/regexpPattern_checker.go b/vendor/github.com/go-critic/go-critic/checkers/regexpPattern_checker.go index 383deb5d446..018ab42d196 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/regexpPattern_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/regexpPattern_checker.go @@ -6,19 +6,19 @@ import ( "regexp" "strings" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "regexpPattern" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects suspicious regexp patterns" info.Before = "regexp.MustCompile(`google.com|yandex.ru`)" info.After = "regexp.MustCompile(`google\\.com|yandex\\.ru`)" - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { domains := []string{ "com", "org", @@ -39,7 +39,7 @@ func init() { type regexpPatternChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext domainRE *regexp.Regexp } diff --git a/vendor/github.com/go-critic/go-critic/checkers/regexpSimplify_checker.go b/vendor/github.com/go-critic/go-critic/checkers/regexpSimplify_checker.go new file mode 100644 index 00000000000..10dcb327f1b --- /dev/null +++ b/vendor/github.com/go-critic/go-critic/checkers/regexpSimplify_checker.go @@ -0,0 +1,511 @@ +package checkers + +import ( + "fmt" + "go/ast" + "go/constant" + "log" + "strings" + "unicode/utf8" + + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" + "github.com/quasilyte/regex/syntax" +) + +func init() { + var info linter.CheckerInfo + info.Name = "regexpSimplify" + info.Tags = []string{"style", "experimental", "opinionated"} + info.Summary = "Detects regexp patterns that can be simplified" + info.Before = "regexp.MustCompile(`(?:a|b|c) [a-z][a-z]*`)" + info.After = "regexp.MustCompile(`[abc] {3}[a-z]+`)" + + // TODO(quasilyte): add params to control most opinionated replacements + // like `[0-9] -> \d` + // `[[:digit:]] -> \d` + // `[A-Za-z0-9_]` -> `\w` + + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { + opts := &syntax.ParserOptions{ + NoLiterals: true, + } + c := ®expSimplifyChecker{ + ctx: ctx, + parser: syntax.NewParser(opts), + out: &strings.Builder{}, + } + return astwalk.WalkerForExpr(c) + }) +} + +type regexpSimplifyChecker struct { + astwalk.WalkHandler + ctx *linter.CheckerContext + parser *syntax.Parser + + // out is a tmp buffer where we build a simplified regexp pattern. + out *strings.Builder + // score is a number of applied simplifications + score int +} + +func (c *regexpSimplifyChecker) VisitExpr(x ast.Expr) { + call, ok := x.(*ast.CallExpr) + if !ok { + return + } + + switch qualifiedName(call.Fun) { + case "regexp.Compile", "regexp.MustCompile": + cv := c.ctx.TypesInfo.Types[call.Args[0]].Value + if cv == nil || cv.Kind() != constant.String { + return + } + pat := constant.StringVal(cv) + if len(pat) > 60 { + // Skip scary regexp patterns for now. + break + } + + // Only do 2 passes. + simplified := pat + for pass := 0; pass < 2; pass++ { + candidate := c.simplify(pass, simplified) + if candidate == "" { + break + } + simplified = candidate + } + if simplified != "" && simplified != pat { + c.warn(call.Args[0], pat, simplified) + } + } +} + +func (c *regexpSimplifyChecker) simplify(pass int, pat string) string { + re, err := c.parser.Parse(pat) + if err != nil { + return "" + } + + c.score = 0 + c.out.Reset() + + // TODO(quasilyte): suggest char ranges for things like [012345689]? + // TODO(quasilyte): evaluate char range to suggest better replacements. + // TODO(quasilyte): (?:ab|ac) -> a[bc] + // TODO(quasilyte): suggest "s" and "." flag if things like [\w\W] are used. + // TODO(quasilyte): x{n}x? -> x{n,n+1} + + c.walk(re.Expr) + + if debug() { + // This happens only in one of two cases: + // 1. Parser has a bug and we got invalid AST for the given pattern. + // 2. Simplifier incorrectly built a replacement string from the AST. + if c.score == 0 && c.out.String() != pat { + log.Printf("pass %d: unexpected pattern diff:\n\thave: %q\n\twant: %q", + pass, c.out.String(), pat) + } + } + + if c.score > 0 { + return c.out.String() + } + return "" +} + +func (c *regexpSimplifyChecker) walk(e syntax.Expr) { + out := c.out + + switch e.Op { + case syntax.OpConcat: + c.walkConcat(e) + + case syntax.OpAlt: + c.walkAlt(e) + + case syntax.OpCharRange: + s := c.simplifyCharRange(e) + if s != "" { + out.WriteString(s) + c.score++ + } else { + out.WriteString(e.Value) + } + + case syntax.OpGroupWithFlags: + out.WriteString("(") + out.WriteString(e.Args[1].Value) + out.WriteString(":") + c.walk(e.Args[0]) + out.WriteString(")") + case syntax.OpGroup: + c.walkGroup(e) + case syntax.OpCapture: + out.WriteString("(") + c.walk(e.Args[0]) + out.WriteString(")") + case syntax.OpNamedCapture: + out.WriteString("(?P<") + out.WriteString(e.Args[1].Value) + out.WriteString(">") + c.walk(e.Args[0]) + out.WriteString(")") + + case syntax.OpRepeat: + // TODO(quasilyte): is it worth it to analyze repeat argument + // more closely and handle `{n,n} -> {n}` cases? + rep := e.Args[1].Value + switch rep { + case "{0,1}": + c.walk(e.Args[0]) + out.WriteString("?") + c.score++ + case "{1,}": + c.walk(e.Args[0]) + out.WriteString("+") + c.score++ + case "{0,}": + c.walk(e.Args[0]) + out.WriteString("*") + c.score++ + case "{0}": + // Maybe {0} should be reported by another check, regexpLint? + c.score++ + case "{1}": + c.walk(e.Args[0]) + c.score++ + default: + c.walk(e.Args[0]) + out.WriteString(rep) + } + + case syntax.OpPosixClass: + out.WriteString(e.Value) + + case syntax.OpNegCharClass: + s := c.simplifyNegCharClass(e) + if s != "" { + c.out.WriteString(s) + c.score++ + } else { + out.WriteString("[^") + for _, e := range e.Args { + c.walk(e) + } + out.WriteString("]") + } + + case syntax.OpCharClass: + s := c.simplifyCharClass(e) + if s != "" { + c.out.WriteString(s) + c.score++ + } else { + out.WriteString("[") + for _, e := range e.Args { + c.walk(e) + } + out.WriteString("]") + } + + case syntax.OpEscapeChar: + switch e.Value { + case `\&`, `\#`, `\!`, `\@`, `\%`, `\<`, `\>`, `\:`, `\;`, `\/`, `\,`, `\=`, `\.`: + c.score++ + out.WriteString(e.Value[len(`\`):]) + default: + out.WriteString(e.Value) + } + + case syntax.OpQuestion, syntax.OpNonGreedy: + c.walk(e.Args[0]) + out.WriteString("?") + case syntax.OpStar: + c.walk(e.Args[0]) + out.WriteString("*") + case syntax.OpPlus: + c.walk(e.Args[0]) + out.WriteString("+") + + default: + out.WriteString(e.Value) + } +} + +func (c *regexpSimplifyChecker) walkGroup(g syntax.Expr) { + switch g.Args[0].Op { + case syntax.OpChar, syntax.OpEscapeChar, syntax.OpEscapeMeta, syntax.OpCharClass: + c.walk(g.Args[0]) + c.score++ + return + } + + c.out.WriteString("(?:") + c.walk(g.Args[0]) + c.out.WriteString(")") +} + +func (c *regexpSimplifyChecker) simplifyNegCharClass(e syntax.Expr) string { + switch e.Value { + case `[^0-9]`: + return `\D` + case `[^\s]`: + return `\S` + case `[^\S]`: + return `\s` + case `[^\w]`: + return `\W` + case `[^\W]`: + return `\w` + case `[^\d]`: + return `\D` + case `[^\D]`: + return `\d` + case `[^[:^space:]]`: + return `\s` + case `[^[:space:]]`: + return `\S` + case `[^[:^word:]]`: + return `\w` + case `[^[:word:]]`: + return `\W` + case `[^[:^digit:]]`: + return `\d` + case `[^[:digit:]]`: + return `\D` + } + + return "" +} + +func (c *regexpSimplifyChecker) simplifyCharClass(e syntax.Expr) string { + switch e.Value { + case `[0-9]`: + return `\d` + case `[[:word:]]`: + return `\w` + case `[[:^word:]]`: + return `\W` + case `[[:digit:]]`: + return `\d` + case `[[:^digit:]]`: + return `\D` + case `[[:space:]]`: + return `\s` + case `[[:^space:]]`: + return `\S` + case `[][]`: + return `\]\[` + case `[]]`: + return `\]` + } + + if len(e.Args) == 1 { + switch e.Args[0].Op { + case syntax.OpChar: + switch v := e.Args[0].Value; v { + case "|", "*", "+", "?", ".", "[", "^", "$", "(", ")": + // Can't take outside of the char group without escaping. + default: + return v + } + case syntax.OpEscapeChar: + return e.Args[0].Value + } + } + + return "" +} + +func (c *regexpSimplifyChecker) canMerge(x, y syntax.Expr) bool { + if x.Op != y.Op { + return false + } + switch x.Op { + case syntax.OpChar, syntax.OpCharClass, syntax.OpEscapeMeta, syntax.OpEscapeChar, syntax.OpNegCharClass, syntax.OpGroup: + return x.Value == y.Value + default: + return false + } +} + +func (c *regexpSimplifyChecker) canCombine(x, y syntax.Expr) (threshold int, ok bool) { + if x.Op != y.Op { + return 0, false + } + + switch x.Op { + case syntax.OpDot: + return 3, true + + case syntax.OpChar: + if x.Value != y.Value { + return 0, false + } + if x.Value == " " { + return 1, true + } + return 4, true + + case syntax.OpEscapeMeta, syntax.OpEscapeChar: + if x.Value == y.Value { + return 2, true + } + + case syntax.OpCharClass, syntax.OpNegCharClass, syntax.OpGroup: + if x.Value == y.Value { + return 1, true + } + } + + return 0, false +} + +func (c *regexpSimplifyChecker) concatLiteral(e syntax.Expr) string { + if e.Op == syntax.OpConcat && c.allChars(e) { + return e.Value + } + return "" +} + +func (c *regexpSimplifyChecker) allChars(e syntax.Expr) bool { + for _, a := range e.Args { + if a.Op != syntax.OpChar { + return false + } + } + return true +} + +func (c *regexpSimplifyChecker) factorPrefixSuffix(alt syntax.Expr) bool { + // TODO: more forms of prefixes/suffixes? + // + // A more generalized algorithm could handle `fo|fo1|fo2` -> `fo[12]?`. + // but it's an open question whether the latter form universally better. + // + // Right now it handles only the simplest cases: + // `http|https` -> `https?` + // `xfoo|foo` -> `x?foo` + if len(alt.Args) != 2 { + return false + } + x := c.concatLiteral(alt.Args[0]) + y := c.concatLiteral(alt.Args[1]) + if x == y { + return false // Reject non-literals and identical strings early + } + + // Let x be a shorter string. + if len(x) > len(y) { + x, y = y, x + } + // Do we have a common prefix? + tail := strings.TrimPrefix(y, x) + if len(tail) <= utf8.UTFMax && utf8.RuneCountInString(tail) == 1 { + c.out.WriteString(x + tail + "?") + c.score++ + return true + } + // Do we have a common suffix? + head := strings.TrimSuffix(y, x) + if len(head) <= utf8.UTFMax && utf8.RuneCountInString(head) == 1 { + c.out.WriteString(head + "?" + x) + c.score++ + return true + } + return false +} + +func (c *regexpSimplifyChecker) walkAlt(alt syntax.Expr) { + // `x|y|z` -> `[xyz]`. + if c.allChars(alt) { + c.score++ + c.out.WriteString("[") + for _, e := range alt.Args { + c.out.WriteString(e.Value) + } + c.out.WriteString("]") + return + } + + if c.factorPrefixSuffix(alt) { + return + } + + for i, e := range alt.Args { + c.walk(e) + if i != len(alt.Args)-1 { + c.out.WriteString("|") + } + } +} + +func (c *regexpSimplifyChecker) walkConcat(concat syntax.Expr) { + i := 0 + for i < len(concat.Args) { + x := concat.Args[i] + c.walk(x) + i++ + + if i >= len(concat.Args) { + break + } + + // Try merging `xy*` into `x+` where x=y. + if concat.Args[i].Op == syntax.OpStar { + if c.canMerge(x, concat.Args[i].Args[0]) { + c.out.WriteString("+") + c.score++ + i++ + continue + } + } + + // Try combining `xy` into `x{2}` where x=y. + threshold, ok := c.canCombine(x, concat.Args[i]) + if !ok { + continue + } + n := 1 // Can combine at least 1 pair. + for j := i + 1; j < len(concat.Args); j++ { + _, ok := c.canCombine(x, concat.Args[j]) + if !ok { + break + } + n++ + } + if n >= threshold { + fmt.Fprintf(c.out, "{%d}", n+1) + c.score++ + i += n + } + } +} + +func (c *regexpSimplifyChecker) simplifyCharRange(rng syntax.Expr) string { + if rng.Args[0].Op != syntax.OpChar || rng.Args[1].Op != syntax.OpChar { + return "" + } + + lo := rng.Args[0].Value + hi := rng.Args[1].Value + if len(lo) == 1 && len(hi) == 1 { + switch hi[0] - lo[0] { + case 0: + return lo + case 1: + return fmt.Sprintf("%s%s", lo, hi) + case 2: + return fmt.Sprintf("%s%s%s", lo, string(lo[0]+1), hi) + } + } + + return "" +} + +func (c *regexpSimplifyChecker) warn(cause ast.Expr, orig, suggest string) { + c.ctx.Warn(cause, "can re-write `%s` as `%s`", orig, suggest) +} diff --git a/vendor/github.com/go-critic/go-critic/checkers/ruleguard_checker.go b/vendor/github.com/go-critic/go-critic/checkers/ruleguard_checker.go new file mode 100644 index 00000000000..5a9fc46d89b --- /dev/null +++ b/vendor/github.com/go-critic/go-critic/checkers/ruleguard_checker.go @@ -0,0 +1,95 @@ +package checkers + +import ( + "bytes" + "go/ast" + "go/token" + "io/ioutil" + "log" + + "github.com/go-critic/go-critic/framework/linter" + "github.com/quasilyte/go-ruleguard/ruleguard" +) + +func init() { + var info linter.CheckerInfo + info.Name = "ruleguard" + info.Tags = []string{"style", "experimental"} + info.Params = linter.CheckerParams{ + "rules": { + Value: "", + Usage: "path to a gorules file", + }, + } + info.Summary = "Runs user-defined rules using ruleguard linter" + info.Details = "Reads a rules file and turns them into go-critic checkers." + info.Before = `N/A` + info.After = `N/A` + info.Note = "See https://github.com/quasilyte/go-ruleguard." + + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { + return newRuleguardChecker(&info, ctx) + }) +} + +func newRuleguardChecker(info *linter.CheckerInfo, ctx *linter.CheckerContext) *ruleguardChecker { + c := &ruleguardChecker{ctx: ctx} + rulesFilename := info.Params.String("rules") + if rulesFilename == "" { + return c + } + + // TODO(quasilyte): handle initialization errors better when we make + // a transition to the go/analysis framework. + // + // For now, we log error messages and return a ruleguard checker + // with an empty rules set. + + data, err := ioutil.ReadFile(rulesFilename) + if err != nil { + log.Printf("ruleguard init error: %+v", err) + return c + } + + fset := token.NewFileSet() + rset, err := ruleguard.ParseRules(rulesFilename, fset, bytes.NewReader(data)) + if err != nil { + log.Printf("ruleguard init error: %+v", err) + return c + } + + c.rset = rset + return c +} + +type ruleguardChecker struct { + ctx *linter.CheckerContext + + rset *ruleguard.GoRuleSet +} + +func (c *ruleguardChecker) WalkFile(f *ast.File) { + if c.rset == nil { + return + } + + ctx := &ruleguard.Context{ + Pkg: c.ctx.Pkg, + Types: c.ctx.TypesInfo, + Sizes: c.ctx.SizesInfo, + Fset: c.ctx.FileSet, + Report: func(n ast.Node, msg string, _ *ruleguard.Suggestion) { + // TODO(quasilyte): investigate whether we should add a rule name as + // a message prefix here. + c.ctx.Warn(n, msg) + }, + } + + err := ruleguard.RunRules(ctx, f, c.rset) + if err != nil { + // Normally this should never happen, but since + // we don't have a better mechanism to report errors, + // emit a warning. + c.ctx.Warn(f, "execution error: %v", err) + } +} diff --git a/vendor/github.com/go-critic/go-critic/checkers/singleCaseSwitch_checker.go b/vendor/github.com/go-critic/go-critic/checkers/singleCaseSwitch_checker.go index 6cdb06aefc4..e8dc5800c66 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/singleCaseSwitch_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/singleCaseSwitch_checker.go @@ -3,12 +3,12 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "singleCaseSwitch" info.Tags = []string{"style"} info.Summary = "Detects switch statements that could be better written as if statement" @@ -22,14 +22,14 @@ if x, ok := x.(int); ok { body() }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&singleCaseSwitchChecker{ctx: ctx}) }) } type singleCaseSwitchChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *singleCaseSwitchChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/sloppyLen_checker.go b/vendor/github.com/go-critic/go-critic/checkers/sloppyLen_checker.go index 45123ec6bdc..e12545ffe62 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/sloppyLen_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/sloppyLen_checker.go @@ -4,14 +4,14 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/astfmt" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "sloppyLen" info.Tags = []string{"style"} info.Summary = "Detects usage of `len` when result is obvious or doesn't make sense" @@ -23,14 +23,14 @@ len(arr) < 0 // Doesn't make sense at all` len(arr) > 0 len(arr) == 0` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&sloppyLenChecker{ctx: ctx}) }) } type sloppyLenChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *sloppyLenChecker) VisitExpr(x ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/sloppyReassign_checker.go b/vendor/github.com/go-critic/go-critic/checkers/sloppyReassign_checker.go index 1a7c198774e..d099450d1fc 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/sloppyReassign_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/sloppyReassign_checker.go @@ -4,29 +4,29 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/astequal" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "sloppyReassign" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects suspicious/confusing re-assignments" info.Before = `if err = f(); err != nil { return err }` info.After = `if err := f(); err != nil { return err }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&sloppyReassignChecker{ctx: ctx}) }) } type sloppyReassignChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *sloppyReassignChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/sloppyTypeAssert_checker.go b/vendor/github.com/go-critic/go-critic/checkers/sloppyTypeAssert_checker.go new file mode 100644 index 00000000000..4abfcbab496 --- /dev/null +++ b/vendor/github.com/go-critic/go-critic/checkers/sloppyTypeAssert_checker.go @@ -0,0 +1,75 @@ +package checkers + +import ( + "go/ast" + "go/types" + + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" + "github.com/go-toolsmith/astcast" +) + +func init() { + var info linter.CheckerInfo + info.Name = "sloppyTypeAssert" + info.Tags = []string{"diagnostic", "experimental"} + info.Summary = "Detects redundant type assertions" + info.Before = ` +function f(r io.Reader) interface{} { + return r.(interface{}) +} +` + info.After = ` +function f(r io.Reader) interface{} { + return r +} +` + + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { + return astwalk.WalkerForExpr(&sloppyTypeAssertChecker{ctx: ctx}) + }) +} + +type sloppyTypeAssertChecker struct { + astwalk.WalkHandler + ctx *linter.CheckerContext +} + +func (c *sloppyTypeAssertChecker) VisitExpr(expr ast.Expr) { + assert := astcast.ToTypeAssertExpr(expr) + if assert.Type == nil { + return + } + + toType := c.ctx.TypesInfo.TypeOf(expr) + fromType := c.ctx.TypesInfo.TypeOf(assert.X) + + if types.Identical(toType, fromType) { + c.warnIdentical(expr) + return + } + + toIface, ok := toType.Underlying().(*types.Interface) + if !ok { + return + } + + switch { + case toIface.Empty(): + c.warnEmpty(expr) + case types.Implements(fromType, toIface): + c.warnImplements(expr, assert.X) + } +} + +func (c *sloppyTypeAssertChecker) warnIdentical(cause ast.Expr) { + c.ctx.Warn(cause, "type assertion from/to types are identical") +} + +func (c *sloppyTypeAssertChecker) warnEmpty(cause ast.Expr) { + c.ctx.Warn(cause, "type assertion to interface{} may be redundant") +} + +func (c *sloppyTypeAssertChecker) warnImplements(cause, val ast.Expr) { + c.ctx.Warn(cause, "type assertion may be redundant as %s always implements selected interface", val) +} diff --git a/vendor/github.com/go-critic/go-critic/checkers/sortSlice_checker.go b/vendor/github.com/go-critic/go-critic/checkers/sortSlice_checker.go new file mode 100644 index 00000000000..b80c1787384 --- /dev/null +++ b/vendor/github.com/go-critic/go-critic/checkers/sortSlice_checker.go @@ -0,0 +1,135 @@ +package checkers + +import ( + "go/ast" + "go/token" + + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/checkers/internal/lintutil" + "github.com/go-critic/go-critic/framework/linter" + "github.com/go-toolsmith/astcast" + "github.com/go-toolsmith/astequal" + "github.com/go-toolsmith/typep" + "golang.org/x/tools/go/ast/astutil" +) + +func init() { + var info linter.CheckerInfo + info.Name = "sortSlice" + info.Tags = []string{"diagnostic", "experimental"} + info.Summary = "Detects suspicious sort.Slice calls" + info.Before = `sort.Slice(xs, func(i, j) bool { return keys[i] < keys[j] })` + info.After = `sort.Slice(kv, func(i, j) bool { return kv[i].key < kv[j].key })` + + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { + return astwalk.WalkerForExpr(&sortSliceChecker{ctx: ctx}) + }) +} + +type sortSliceChecker struct { + astwalk.WalkHandler + ctx *linter.CheckerContext +} + +func (c *sortSliceChecker) VisitExpr(expr ast.Expr) { + call := astcast.ToCallExpr(expr) + if len(call.Args) != 2 { + return + } + switch qualifiedName(call.Fun) { + case "sort.Slice", "sort.SliceStable": + // OK. + default: + return + } + + slice := c.unwrapSlice(call.Args[0]) + lessFunc, ok := call.Args[1].(*ast.FuncLit) + if !ok { + return + } + if !typep.SideEffectFree(c.ctx.TypesInfo, slice) { + return // Don't check unpredictable slice values + } + + ivar, jvar := c.paramIdents(lessFunc.Type) + if ivar == nil || jvar == nil { + return + } + + if len(lessFunc.Body.List) != 1 { + return + } + ret, ok := lessFunc.Body.List[0].(*ast.ReturnStmt) + if !ok { + return + } + cmp := astcast.ToBinaryExpr(astutil.Unparen(ret.Results[0])) + if !typep.SideEffectFree(c.ctx.TypesInfo, cmp) { + return + } + switch cmp.Op { + case token.LSS, token.LEQ, token.GTR, token.GEQ: + // Both cmp.X and cmp.Y are expected to be some expressions + // over the `slice` expression. In the simplest case, + // it's a `slice[i] slice[j]`. + if !c.containsSlice(cmp.X, slice) && !c.containsSlice(cmp.Y, slice) { + c.warnSlice(cmp, slice) + } + + // This one is more about the style, but can reveal potential issue + // or misprint in sorting condition. + // We give a warn if X contains indexing with `i` index and Y + // contains indexing with `j`. + if c.containsIndex(cmp.X, jvar) && c.containsIndex(cmp.Y, ivar) { + c.warnIndex(cmp, ivar, jvar) + } + } +} + +func (c *sortSliceChecker) paramIdents(e *ast.FuncType) (*ast.Ident, *ast.Ident) { + // Covers both `i, j int` and `i int, j int`. + idents := make([]*ast.Ident, 0, 2) + for _, field := range e.Params.List { + idents = append(idents, field.Names...) + } + if len(idents) == 2 { + return idents[0], idents[1] + } + return nil, nil +} + +func (c *sortSliceChecker) unwrapSlice(e ast.Expr) ast.Expr { + switch e := e.(type) { + case *ast.ParenExpr: + return c.unwrapSlice(e.X) + case *ast.SliceExpr: + return e.X + default: + return e + } +} + +func (c *sortSliceChecker) containsIndex(e, index ast.Expr) bool { + return lintutil.ContainsNode(e, func(n ast.Node) bool { + indexing, ok := n.(*ast.IndexExpr) + if !ok { + return false + } + return astequal.Expr(indexing.Index, index) + }) +} + +func (c *sortSliceChecker) containsSlice(e, slice ast.Expr) bool { + return lintutil.ContainsNode(e, func(n ast.Node) bool { + return astequal.Node(n, slice) + }) +} + +func (c *sortSliceChecker) warnSlice(cause ast.Node, slice ast.Expr) { + c.ctx.Warn(cause, "cmp func must use %s slice in comparison", slice) +} + +func (c *sortSliceChecker) warnIndex(cause ast.Node, ivar, jvar *ast.Ident) { + c.ctx.Warn(cause, "unusual order of {%s,%s} params in comparison", ivar, jvar) +} diff --git a/vendor/github.com/go-critic/go-critic/checkers/sqlQuery_checker.go b/vendor/github.com/go-critic/go-critic/checkers/sqlQuery_checker.go new file mode 100644 index 00000000000..697a82ccf5f --- /dev/null +++ b/vendor/github.com/go-critic/go-critic/checkers/sqlQuery_checker.go @@ -0,0 +1,167 @@ +package checkers + +import ( + "go/ast" + "go/types" + + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" + "github.com/go-toolsmith/astcast" +) + +func init() { + var info linter.CheckerInfo + info.Name = "sqlQuery" + info.Tags = []string{"diagnostic", "experimental"} + info.Summary = "Detects issue in Query() and Exec() calls" + info.Before = `_, err := db.Query("UPDATE ...")` + info.After = `_, err := db.Exec("UPDATE ...")` + + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { + return astwalk.WalkerForStmt(&sqlQueryChecker{ctx: ctx}) + }) +} + +type sqlQueryChecker struct { + astwalk.WalkHandler + ctx *linter.CheckerContext +} + +func (c *sqlQueryChecker) VisitStmt(stmt ast.Stmt) { + assign := astcast.ToAssignStmt(stmt) + if len(assign.Lhs) != 2 { // Query() has 2 return values. + return + } + if len(assign.Rhs) != 1 { + return + } + + // If Query() is called, but first return value is ignored, + // there is no way to close/read the returned rows. + // This can cause a connection leak. + if id, ok := assign.Lhs[0].(*ast.Ident); ok && id.Name != "_" { + return + } + + call := astcast.ToCallExpr(assign.Rhs[0]) + funcExpr := astcast.ToSelectorExpr(call.Fun) + if !c.funcIsQuery(funcExpr) { + return + } + + if c.typeHasExecMethod(c.ctx.TypesInfo.TypeOf(funcExpr.X)) { + c.warnAndSuggestExec(funcExpr) + } else { + c.warnRowsIgnored(funcExpr) + } +} + +func (c *sqlQueryChecker) funcIsQuery(funcExpr *ast.SelectorExpr) bool { + if funcExpr.Sel == nil { + return false + } + switch funcExpr.Sel.Name { + case "Query", "QueryContext": + // Stdlib and friends. + case "Queryx", "QueryxContext": + // sqlx. + default: + return false + } + + // To avoid false positives (unrelated types can have Query method) + // check that the 1st returned type has Row-like name. + typ, ok := c.ctx.TypesInfo.TypeOf(funcExpr).Underlying().(*types.Signature) + if !ok || typ.Results() == nil || typ.Results().Len() != 2 { + return false + } + if !c.typeIsRowsLike(typ.Results().At(0).Type()) { + return false + } + + return true +} + +func (c *sqlQueryChecker) typeIsRowsLike(typ types.Type) bool { + switch typ := typ.(type) { + case *types.Pointer: + return c.typeIsRowsLike(typ.Elem()) + case *types.Named: + return typ.Obj().Name() == "Rows" + default: + return false + } +} + +func (c *sqlQueryChecker) funcIsExec(fn *types.Func) bool { + if fn.Name() != "Exec" { + return false + } + + // Expect exactly 2 results. + sig := fn.Type().(*types.Signature) + if sig.Results() == nil || sig.Results().Len() != 2 { + return false + } + + // Expect at least 1 param and it should be a string (query). + params := sig.Params() + if params == nil || params.Len() == 0 { + return false + } + if typ, ok := params.At(0).Type().(*types.Basic); !ok || typ.Kind() != types.String { + return false + } + + return true +} + +func (c *sqlQueryChecker) typeHasExecMethod(typ types.Type) bool { + switch typ := typ.(type) { + case *types.Struct: + for i := 0; i < typ.NumFields(); i++ { + if c.typeHasExecMethod(typ.Field(i).Type()) { + return true + } + } + case *types.Interface: + for i := 0; i < typ.NumMethods(); i++ { + if c.funcIsExec(typ.Method(i)) { + return true + } + } + case *types.Pointer: + return c.typeHasExecMethod(typ.Elem()) + case *types.Named: + for i := 0; i < typ.NumMethods(); i++ { + if c.funcIsExec(typ.Method(i)) { + return true + } + } + switch ut := typ.Underlying().(type) { + case *types.Interface: + return c.typeHasExecMethod(ut) + case *types.Struct: + // Check embedded types. + for i := 0; i < ut.NumFields(); i++ { + field := ut.Field(i) + if !field.Embedded() { + continue + } + if c.typeHasExecMethod(field.Type()) { + return true + } + } + } + } + + return false +} + +func (c *sqlQueryChecker) warnAndSuggestExec(funcExpr *ast.SelectorExpr) { + c.ctx.Warn(funcExpr, "use %s.Exec() if returned result is not needed", funcExpr.X) +} + +func (c *sqlQueryChecker) warnRowsIgnored(funcExpr *ast.SelectorExpr) { + c.ctx.Warn(funcExpr, "ignoring Query() rows result may lead to a connection leak") +} diff --git a/vendor/github.com/go-critic/go-critic/checkers/stringXbytes_checker.go b/vendor/github.com/go-critic/go-critic/checkers/stringXbytes_checker.go index 74570108e69..5108b478774 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/stringXbytes_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/stringXbytes_checker.go @@ -3,27 +3,27 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/typep" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "stringXbytes" info.Tags = []string{"style", "experimental"} info.Summary = "Detects redundant conversions between string and []byte" info.Before = `copy(b, []byte(s))` info.After = `copy(b, s)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&stringXbytes{ctx: ctx}) }) } type stringXbytes struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *stringXbytes) VisitExpr(expr ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/switchTrue_checker.go b/vendor/github.com/go-critic/go-critic/checkers/switchTrue_checker.go index 3b276627697..5390360c53c 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/switchTrue_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/switchTrue_checker.go @@ -3,12 +3,12 @@ package checkers import ( "go/ast" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "switchTrue" info.Tags = []string{"style"} info.Summary = "Detects switch-over-bool statements that use explicit `true` tag value" @@ -21,14 +21,14 @@ switch { case x > y: }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&switchTrueChecker{ctx: ctx}) }) } type switchTrueChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *switchTrueChecker) VisitStmt(stmt ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/truncateCmp_checker.go b/vendor/github.com/go-critic/go-critic/checkers/truncateCmp_checker.go index f4cb9e8662d..a5b7bdd3275 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/truncateCmp_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/truncateCmp_checker.go @@ -5,17 +5,17 @@ import ( "go/token" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astp" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "truncateCmp" info.Tags = []string{"diagnostic", "experimental"} - info.Params = lintpack.CheckerParams{ + info.Params = linter.CheckerParams{ "skipArchDependent": { Value: true, Usage: "whether to skip int/uint/uintptr types", @@ -31,7 +31,7 @@ func f(x int32, int16) bool { return x < int32(y) }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &truncateCmpChecker{ctx: ctx} c.skipArchDependent = info.Params.Bool("skipArchDependent") return astwalk.WalkerForExpr(c) @@ -40,7 +40,7 @@ func f(x int32, int16) bool { type truncateCmpChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext skipArchDependent bool } diff --git a/vendor/github.com/go-critic/go-critic/checkers/typeAssertChain_checker.go b/vendor/github.com/go-critic/go-critic/checkers/typeAssertChain_checker.go index c0c42e3511c..2940e57f9a7 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/typeAssertChain_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/typeAssertChain_checker.go @@ -4,16 +4,16 @@ import ( "go/ast" "go/token" + "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/checkers/internal/lintutil" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astequal" "github.com/go-toolsmith/astp" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "typeAssertChain" info.Tags = []string{"style", "experimental"} info.Summary = "Detects repeated type assertions and suggests to replace them with type switch statement" @@ -35,14 +35,14 @@ default: // Code C, uses x. }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&typeAssertChainChecker{ctx: ctx}) }) } type typeAssertChainChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext cause *ast.IfStmt visited map[*ast.IfStmt]bool diff --git a/vendor/github.com/go-critic/go-critic/checkers/typeSwitchVar_checker.go b/vendor/github.com/go-critic/go-critic/checkers/typeSwitchVar_checker.go index a113597b6a7..2ade4a954d6 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/typeSwitchVar_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/typeSwitchVar_checker.go @@ -3,15 +3,15 @@ package checkers import ( "go/ast" + "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/checkers/internal/lintutil" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astequal" "github.com/go-toolsmith/astp" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "typeSwitchVar" info.Tags = []string{"style"} info.Summary = "Detects type switches that can benefit from type guard clause with variable" @@ -34,18 +34,20 @@ default: return 0 }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&typeSwitchVarChecker{ctx: ctx}) }) } type typeSwitchVarChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext + count int } func (c *typeSwitchVarChecker) VisitStmt(stmt ast.Stmt) { if stmt, ok := stmt.(*ast.TypeSwitchStmt); ok { + c.count = 0 c.checkTypeSwitch(stmt) } } @@ -61,7 +63,7 @@ func (c *typeSwitchVarChecker) checkTypeSwitch(root *ast.TypeSwitchStmt) { return // Give up: can't handle shadowing without object } - for i, clause := range root.Body.List { + for _, clause := range root.Body.List { clause := clause.(*ast.CaseClause) // Multiple types in a list mean that assert.X will have // a type of interface{} inside clause body. @@ -76,13 +78,20 @@ func (c *typeSwitchVarChecker) checkTypeSwitch(root *ast.TypeSwitchStmt) { return astequal.Node(&assert1, x) }) if object == c.ctx.TypesInfo.ObjectOf(identOf(assert2)) { - c.warn(root, i) + c.count++ break } } } + if c.count > 0 { + c.warn(root) + } } -func (c *typeSwitchVarChecker) warn(n ast.Node, caseIndex int) { - c.ctx.Warn(n, "case %d can benefit from type switch with assignment", caseIndex) +func (c *typeSwitchVarChecker) warn(n ast.Node) { + msg := "case" + if c.count > 1 { + msg = "cases" + } + c.ctx.Warn(n, "%d "+msg+" can benefit from type switch with assignment", c.count) } diff --git a/vendor/github.com/go-critic/go-critic/checkers/typeUnparen_checker.go b/vendor/github.com/go-critic/go-critic/checkers/typeUnparen_checker.go index a17c77b4969..620d2d79748 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/typeUnparen_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/typeUnparen_checker.go @@ -3,30 +3,30 @@ package checkers import ( "go/ast" + "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/checkers/internal/lintutil" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/astp" "golang.org/x/tools/go/ast/astutil" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "typeUnparen" info.Tags = []string{"style", "opinionated"} info.Summary = "Detects unneded parenthesis inside type expressions and suggests to remove them" info.Before = `type foo [](func([](func())))` info.After = `type foo []func([]func())` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForTypeExpr(&typeUnparenChecker{ctx: ctx}, ctx.TypesInfo) }) } type typeUnparenChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *typeUnparenChecker) VisitTypeExpr(x ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/underef_checker.go b/vendor/github.com/go-critic/go-critic/checkers/underef_checker.go index dfc6077bbf1..561270c7c1c 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/underef_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/underef_checker.go @@ -4,17 +4,17 @@ import ( "go/ast" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astp" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "underef" info.Tags = []string{"style"} - info.Params = lintpack.CheckerParams{ + info.Params = linter.CheckerParams{ "skipRecvDeref": { Value: true, Usage: "whether to skip (*x).method() calls where x is a pointer receiver", @@ -28,7 +28,7 @@ v := (*a)[5] // only if a is array` k.field = 5 v := a[5]` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &underefChecker{ctx: ctx} c.skipRecvDeref = info.Params.Bool("skipRecvDeref") return astwalk.WalkerForExpr(c) @@ -37,7 +37,7 @@ v := a[5]` type underefChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext skipRecvDeref bool } diff --git a/vendor/github.com/go-critic/go-critic/checkers/unlabelStmt_checker.go b/vendor/github.com/go-critic/go-critic/checkers/unlabelStmt_checker.go index d90c65c2ce1..83c5b14841b 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/unlabelStmt_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/unlabelStmt_checker.go @@ -4,13 +4,13 @@ import ( "go/ast" "go/token" + "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/checkers/internal/lintutil" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "unlabelStmt" info.Tags = []string{"style", "experimental"} info.Summary = "Detects redundant statement labels" @@ -28,14 +28,14 @@ for x := range xs { } }` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmt(&unlabelStmtChecker{ctx: ctx}) }) } type unlabelStmtChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *unlabelStmtChecker) EnterFunc(fn *ast.FuncDecl) bool { diff --git a/vendor/github.com/go-critic/go-critic/checkers/unlambda_checker.go b/vendor/github.com/go-critic/go-critic/checkers/unlambda_checker.go index 9e01299bff9..946227c2f1a 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/unlambda_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/unlambda_checker.go @@ -4,28 +4,28 @@ import ( "go/ast" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astequal" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "unlambda" info.Tags = []string{"style"} info.Summary = "Detects function literals that can be simplified" info.Before = `func(x int) int { return fn(x) }` info.After = `fn` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&unlambdaChecker{ctx: ctx}) }) } type unlambdaChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *unlambdaChecker) VisitExpr(x ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/unnamedResult_checker.go b/vendor/github.com/go-critic/go-critic/checkers/unnamedResult_checker.go index 09423250ad4..f053842ec94 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/unnamedResult_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/unnamedResult_checker.go @@ -4,15 +4,15 @@ import ( "go/ast" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "unnamedResult" info.Tags = []string{"style", "opinionated", "experimental"} - info.Params = lintpack.CheckerParams{ + info.Params = linter.CheckerParams{ "checkExported": { Value: false, Usage: "whether to check exported functions", @@ -22,7 +22,7 @@ func init() { info.Before = `func f() (float64, float64)` info.After = `func f() (x, y float64)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { c := &unnamedResultChecker{ctx: ctx} c.checkExported = info.Params.Bool("checkExported") return astwalk.WalkerForFuncDecl(c) @@ -31,7 +31,7 @@ func init() { type unnamedResultChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext checkExported bool } diff --git a/vendor/github.com/go-critic/go-critic/checkers/unnecessaryBlock_checker.go b/vendor/github.com/go-critic/go-critic/checkers/unnecessaryBlock_checker.go index e5dc45f7ef0..acc9fadbf91 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/unnecessaryBlock_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/unnecessaryBlock_checker.go @@ -4,12 +4,12 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "unnecessaryBlock" info.Tags = []string{"style", "opinionated", "experimental"} info.Summary = "Detects unnecessary braced statement blocks" @@ -22,14 +22,14 @@ x := 1 x := 1 print(x)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmtList(&unnecessaryBlockChecker{ctx: ctx}) }) } type unnecessaryBlockChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *unnecessaryBlockChecker) VisitStmtList(statements []ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/unnecessaryDefer_checker.go b/vendor/github.com/go-critic/go-critic/checkers/unnecessaryDefer_checker.go new file mode 100644 index 00000000000..ce25a07cafc --- /dev/null +++ b/vendor/github.com/go-critic/go-critic/checkers/unnecessaryDefer_checker.go @@ -0,0 +1,101 @@ +package checkers + +import ( + "go/ast" + + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/checkers/internal/lintutil" + "github.com/go-critic/go-critic/framework/linter" + "github.com/go-toolsmith/astfmt" + "github.com/go-toolsmith/astp" +) + +func init() { + var info linter.CheckerInfo + info.Name = "unnecessaryDefer" + info.Tags = []string{"diagnostic", "experimental"} + info.Summary = "Detects redundantly deferred calls" + info.Before = ` +func() { + defer os.Remove(filename) +}` + info.After = ` +func() { + os.Remove(filename) +}` + + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { + return astwalk.WalkerForFuncDecl(&unnecessaryDeferChecker{ctx: ctx}) + }) +} + +type unnecessaryDeferChecker struct { + astwalk.WalkHandler + ctx *linter.CheckerContext + isFunc bool +} + +// Visit implements the ast.Visitor. This visitor keeps track of the block +// statement belongs to a function or any other block. If the block is not a +// function and ends with a defer statement that should be OK since it's +// defering the outer function. +func (c *unnecessaryDeferChecker) Visit(node ast.Node) ast.Visitor { + switch n := node.(type) { + case *ast.FuncDecl, *ast.FuncLit: + c.isFunc = true + case *ast.BlockStmt: + c.checkDeferBeforeReturn(n) + default: + c.isFunc = false + } + + return c +} + +func (c *unnecessaryDeferChecker) VisitFuncDecl(funcDecl *ast.FuncDecl) { + // We always start as a function (*ast.FuncDecl.Body passed) + c.isFunc = true + + ast.Walk(c, funcDecl.Body) +} + +func (c *unnecessaryDeferChecker) checkDeferBeforeReturn(funcDecl *ast.BlockStmt) { + // Check if we have an explicit return or if it's just the end of the scope. + explicitReturn := false + retIndex := len(funcDecl.List) + for i, stmt := range funcDecl.List { + retStmt, ok := stmt.(*ast.ReturnStmt) + if !ok { + continue + } + explicitReturn = true + if lintutil.ContainsNode(retStmt, astp.IsCallExpr) { + continue + } + retIndex = i + break + + } + if retIndex == 0 { + return + } + + if deferStmt, ok := funcDecl.List[retIndex-1].(*ast.DeferStmt); ok { + // If the block is a function and ending with return or if we have an + // explicit return in any other block we should warn about + // unnecessary defer. + if c.isFunc || explicitReturn { + c.warn(deferStmt) + } + } +} + +func (c *unnecessaryDeferChecker) warn(deferStmt *ast.DeferStmt) { + s := astfmt.Sprint(deferStmt) + if fnlit, ok := deferStmt.Call.Fun.(*ast.FuncLit); ok { + // To avoid long and multi-line warning messages, + // collapse the function literals. + s = "defer " + astfmt.Sprint(fnlit.Type) + "{...}(...)" + } + c.ctx.Warn(deferStmt, "%s is placed just before return", s) +} diff --git a/vendor/github.com/go-critic/go-critic/checkers/unslice_checker.go b/vendor/github.com/go-critic/go-critic/checkers/unslice_checker.go index 06d90819c9a..73f67bc8ee1 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/unslice_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/unslice_checker.go @@ -4,13 +4,13 @@ import ( "go/ast" "go/types" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astequal" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "unslice" info.Tags = []string{"style"} info.Summary = "Detects slice expressions that can be simplified to sliced expression itself" @@ -21,14 +21,14 @@ copy(b[:], values...) // b is []byte` f(s) copy(b, values...)` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&unsliceChecker{ctx: ctx}) }) } type unsliceChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *unsliceChecker) VisitExpr(expr ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/utils.go b/vendor/github.com/go-critic/go-critic/checkers/utils.go index ba4777dbdda..b71f24d7490 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/utils.go +++ b/vendor/github.com/go-critic/go-critic/checkers/utils.go @@ -5,7 +5,7 @@ import ( "go/types" "strings" - "github.com/go-lintpack/lintpack" + "github.com/go-critic/go-critic/framework/linter" ) // goStdlib contains `go list std` command output list. @@ -247,7 +247,7 @@ func isExampleTestFunc(fn *ast.FuncDecl) bool { } // isUnitTestFunc reports whether FuncDecl declares testing function. -func isUnitTestFunc(ctx *lintpack.CheckerContext, fn *ast.FuncDecl) bool { +func isUnitTestFunc(ctx *linter.CheckerContext, fn *ast.FuncDecl) bool { if !strings.HasPrefix(fn.Name.Name, "Test") { return false } diff --git a/vendor/github.com/go-critic/go-critic/checkers/valSwap_checker.go b/vendor/github.com/go-critic/go-critic/checkers/valSwap_checker.go index ab27f920079..8a8c9f74337 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/valSwap_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/valSwap_checker.go @@ -4,14 +4,14 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astequal" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "valSwap" info.Tags = []string{"style", "experimental"} info.Summary = "Detects value swapping code that are not using parallel assignment" @@ -21,14 +21,14 @@ tmp := *x *y = tmp` info.After = `*x, *y = *y, *x` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForStmtList(&valSwapChecker{ctx: ctx}) }) } type valSwapChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *valSwapChecker) VisitStmtList(list []ast.Stmt) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/weakCond_checker.go b/vendor/github.com/go-critic/go-critic/checkers/weakCond_checker.go index fcd9aee527e..1d6ee58efed 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/weakCond_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/weakCond_checker.go @@ -4,9 +4,9 @@ import ( "go/ast" "go/token" + "github.com/go-critic/go-critic/checkers/internal/astwalk" "github.com/go-critic/go-critic/checkers/internal/lintutil" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" "github.com/go-toolsmith/astequal" "github.com/go-toolsmith/typep" @@ -14,21 +14,21 @@ import ( ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "weakCond" info.Tags = []string{"diagnostic", "experimental"} info.Summary = "Detects conditions that are unsafe due to not being exhaustive" info.Before = `xs != nil && xs[0] != nil` info.After = `len(xs) != 0 && xs[0] != nil` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForExpr(&weakCondChecker{ctx: ctx}) }) } type weakCondChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *weakCondChecker) VisitExpr(expr ast.Expr) { diff --git a/vendor/github.com/go-critic/go-critic/checkers/whyNoLint_checker.go b/vendor/github.com/go-critic/go-critic/checkers/whyNoLint_checker.go index 52fefb82c45..cc5c5172e17 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/whyNoLint_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/whyNoLint_checker.go @@ -5,12 +5,12 @@ import ( "regexp" "strings" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" ) func init() { - info := lintpack.CheckerInfo{ + info := linter.CheckerInfo{ Name: "whyNoLint", Tags: []string{"style", "experimental"}, Summary: "Ensures that `//nolint` comments include an explanation", @@ -19,7 +19,7 @@ func init() { } re := regexp.MustCompile(`^// *nolint(?::[^ ]+)? *(.*)$`) - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForComment(&whyNoLintChecker{ ctx: ctx, re: re, @@ -30,7 +30,7 @@ func init() { type whyNoLintChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext re *regexp.Regexp } diff --git a/vendor/github.com/go-critic/go-critic/checkers/wrapperFunc_checker.go b/vendor/github.com/go-critic/go-critic/checkers/wrapperFunc_checker.go index bba82e5ee85..05e633d3d12 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/wrapperFunc_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/wrapperFunc_checker.go @@ -6,20 +6,20 @@ import ( "go/types" "strings" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcast" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "wrapperFunc" info.Tags = []string{"style", "experimental"} info.Summary = "Detects function calls that can be replaced with convenience wrappers" info.Before = `wg.Add(-1)` info.After = `wg.Done()` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { type arg struct { index int value string @@ -81,6 +81,11 @@ func init() { "bytes.Map => bytes.ToTitle": { {0, "unicode.ToTitle"}, }, + + "draw.DrawMask => draw.Draw": { + {4, "nil"}, + {5, "image.Point{}"}, + }, } matchers := make(map[string]*matcher) @@ -203,7 +208,7 @@ func init() { type wrapperFuncChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext findSuggestion func(*ast.CallExpr) string } diff --git a/vendor/github.com/go-critic/go-critic/checkers/yodaStyleExpr_checker.go b/vendor/github.com/go-critic/go-critic/checkers/yodaStyleExpr_checker.go index ddd3099fd0b..b4672fcca17 100644 --- a/vendor/github.com/go-critic/go-critic/checkers/yodaStyleExpr_checker.go +++ b/vendor/github.com/go-critic/go-critic/checkers/yodaStyleExpr_checker.go @@ -4,28 +4,28 @@ import ( "go/ast" "go/token" - "github.com/go-lintpack/lintpack" - "github.com/go-lintpack/lintpack/astwalk" + "github.com/go-critic/go-critic/checkers/internal/astwalk" + "github.com/go-critic/go-critic/framework/linter" "github.com/go-toolsmith/astcopy" "github.com/go-toolsmith/astp" ) func init() { - var info lintpack.CheckerInfo + var info linter.CheckerInfo info.Name = "yodaStyleExpr" info.Tags = []string{"style", "experimental"} info.Summary = "Detects Yoda style expressions and suggests to replace them" info.Before = `return nil != ptr` info.After = `return ptr != nil` - collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker { + collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker { return astwalk.WalkerForLocalExpr(&yodaStyleExprChecker{ctx: ctx}) }) } type yodaStyleExprChecker struct { astwalk.WalkHandler - ctx *lintpack.CheckerContext + ctx *linter.CheckerContext } func (c *yodaStyleExprChecker) VisitLocalExpr(expr ast.Expr) { diff --git a/vendor/github.com/go-lintpack/lintpack/checkers_db.go b/vendor/github.com/go-critic/go-critic/framework/linter/checkers_db.go similarity index 99% rename from vendor/github.com/go-lintpack/lintpack/checkers_db.go rename to vendor/github.com/go-critic/go-critic/framework/linter/checkers_db.go index 83d41b4e4c0..b4bebe44355 100644 --- a/vendor/github.com/go-lintpack/lintpack/checkers_db.go +++ b/vendor/github.com/go-critic/go-critic/framework/linter/checkers_db.go @@ -1,4 +1,4 @@ -package lintpack +package linter import ( "fmt" diff --git a/vendor/github.com/go-critic/go-critic/framework/linter/context.go b/vendor/github.com/go-critic/go-critic/framework/linter/context.go new file mode 100644 index 00000000000..6e108ab6a5d --- /dev/null +++ b/vendor/github.com/go-critic/go-critic/framework/linter/context.go @@ -0,0 +1,35 @@ +package linter + +import ( + "go/ast" + "go/types" + "strconv" +) + +func resolvePkgObjects(ctx *Context, f *ast.File) { + ctx.PkgObjects = make(map[*types.PkgName]string, len(f.Imports)) + + for _, spec := range f.Imports { + if spec.Name != nil { + obj := ctx.TypesInfo.ObjectOf(spec.Name) + ctx.PkgObjects[obj.(*types.PkgName)] = spec.Name.Name + } else { + obj := ctx.TypesInfo.Implicits[spec] + ctx.PkgObjects[obj.(*types.PkgName)] = obj.Name() + } + } +} + +func resolvePkgRenames(ctx *Context, f *ast.File) { + ctx.PkgRenames = make(map[string]string) + + for _, spec := range f.Imports { + if spec.Name != nil { + path, err := strconv.Unquote(spec.Path.Value) + if err != nil { + panic(err) + } + ctx.PkgRenames[path] = spec.Name.Name + } + } +} diff --git a/vendor/github.com/go-lintpack/lintpack/lintpack.go b/vendor/github.com/go-critic/go-critic/framework/linter/lintpack.go similarity index 98% rename from vendor/github.com/go-lintpack/lintpack/lintpack.go rename to vendor/github.com/go-critic/go-critic/framework/linter/lintpack.go index 28c3a6354eb..1f984d146ee 100644 --- a/vendor/github.com/go-lintpack/lintpack/lintpack.go +++ b/vendor/github.com/go-critic/go-critic/framework/linter/lintpack.go @@ -1,7 +1,6 @@ -package lintpack +package linter import ( - "fmt" "go/ast" "go/token" "go/types" @@ -25,7 +24,7 @@ type CheckerCollection struct { // constructor will not be called. func (coll *CheckerCollection) AddChecker(info *CheckerInfo, constructor func(*CheckerContext) FileWalker) { if coll == nil { - panic(fmt.Sprintf("adding checker to a nil collection")) + panic("adding checker to a nil collection") } info.Collection = coll addChecker(info, constructor) diff --git a/vendor/github.com/go-lintpack/lintpack/.travis.yml b/vendor/github.com/go-lintpack/lintpack/.travis.yml deleted file mode 100644 index 41a0cbac510..00000000000 --- a/vendor/github.com/go-lintpack/lintpack/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: go -go: - - 1.x -install: - - # Prevent default install action "go get -t -v ./...". -script: - - make ci diff --git a/vendor/github.com/go-lintpack/lintpack/LICENSE b/vendor/github.com/go-lintpack/lintpack/LICENSE deleted file mode 100644 index de0abccdf3d..00000000000 --- a/vendor/github.com/go-lintpack/lintpack/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2018, go-lintpack maintainers - -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 Intel Corporation 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/go-lintpack/lintpack/Makefile b/vendor/github.com/go-lintpack/lintpack/Makefile deleted file mode 100644 index 63f21d2f93d..00000000000 --- a/vendor/github.com/go-lintpack/lintpack/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -.PHONY: test ci - -%: # stubs to get makefile param for `test-checker` command - @: # see: https://stackoverflow.com/a/6273809/433041 - -build: - go build cmd/lintpack/build.go cmd/lintpack/main.go - -test: - go test -v -count=1 ./... - -ci: - go get -t -v ./... - go test -v -count=1 ./... diff --git a/vendor/github.com/go-lintpack/lintpack/README.md b/vendor/github.com/go-lintpack/lintpack/README.md deleted file mode 100644 index 5702228ebce..00000000000 --- a/vendor/github.com/go-lintpack/lintpack/README.md +++ /dev/null @@ -1,32 +0,0 @@ -[![Build Status][travis-image]][travis-url] -[![Go Report Card][go-report-image]][go-report-url] - -[travis-image]: https://travis-ci.org/go-critic/go-critic.svg?branch=master -[travis-url]: https://travis-ci.org/go-critic/go-critic -[go-report-image]: https://goreportcard.com/badge/github.com/go-critic/go-critic -[go-report-url]: https://goreportcard.com/report/github.com/go-critic/go-critic - -## Quick start / Installation / Usage - -Install `lintpack`: - -```bash -go get -v -u github.com/go-lintpack/lintpack/... -``` - -Install checkers from [go-critic/checkers](https://github.com/go-critic/checkers): - -```bash -# You'll need to have sources under your Go workspace first: -go get -v -u github.com/go-critic/checkers -# Now build a linter that includes all checks from that package: -lintpack build -o gocritic github.com/go-critic/checkers -# Executable gocritic is created and can be used as a standalone linter. -``` - -Produced binary includes basic help as well as supported checks documentation. - -So, the process is simple: - -* Get the `lintpack` linter builder -* Build linter from checks implemented in different repos, by various vendors diff --git a/vendor/github.com/go-lintpack/lintpack/astwalk/walker.go b/vendor/github.com/go-lintpack/lintpack/astwalk/walker.go deleted file mode 100644 index fddae710ad9..00000000000 --- a/vendor/github.com/go-lintpack/lintpack/astwalk/walker.go +++ /dev/null @@ -1,57 +0,0 @@ -package astwalk - -import ( - "go/types" - - "github.com/go-lintpack/lintpack" -) - -// WalkerForFuncDecl returns file walker implementation for FuncDeclVisitor. -func WalkerForFuncDecl(v FuncDeclVisitor) lintpack.FileWalker { - return &funcDeclWalker{visitor: v} -} - -// WalkerForExpr returns file walker implementation for ExprVisitor. -func WalkerForExpr(v ExprVisitor) lintpack.FileWalker { - return &exprWalker{visitor: v} -} - -// WalkerForLocalExpr returns file walker implementation for LocalExprVisitor. -func WalkerForLocalExpr(v LocalExprVisitor) lintpack.FileWalker { - return &localExprWalker{visitor: v} -} - -// WalkerForStmtList returns file walker implementation for StmtListVisitor. -func WalkerForStmtList(v StmtListVisitor) lintpack.FileWalker { - return &stmtListWalker{visitor: v} -} - -// WalkerForStmt returns file walker implementation for StmtVisitor. -func WalkerForStmt(v StmtVisitor) lintpack.FileWalker { - return &stmtWalker{visitor: v} -} - -// WalkerForTypeExpr returns file walker implementation for TypeExprVisitor. -func WalkerForTypeExpr(v TypeExprVisitor, info *types.Info) lintpack.FileWalker { - return &typeExprWalker{visitor: v, info: info} -} - -// WalkerForLocalComment returns file walker implementation for LocalCommentVisitor. -func WalkerForLocalComment(v LocalCommentVisitor) lintpack.FileWalker { - return &localCommentWalker{visitor: v} -} - -// WalkerForComment returns file walker implementation for CommentVisitor. -func WalkerForComment(v CommentVisitor) lintpack.FileWalker { - return &commentWalker{visitor: v} -} - -// WalkerForDocComment returns file walker implementation for DocCommentVisitor. -func WalkerForDocComment(v DocCommentVisitor) lintpack.FileWalker { - return &docCommentWalker{visitor: v} -} - -// WalkerForLocalDef returns file walker implementation for LocalDefVisitor. -func WalkerForLocalDef(v LocalDefVisitor, info *types.Info) lintpack.FileWalker { - return &localDefWalker{visitor: v, info: info} -} diff --git a/vendor/github.com/go-lintpack/lintpack/context.go b/vendor/github.com/go-lintpack/lintpack/context.go deleted file mode 100644 index 8671e175ca3..00000000000 --- a/vendor/github.com/go-lintpack/lintpack/context.go +++ /dev/null @@ -1,35 +0,0 @@ -package lintpack - -import ( - "go/ast" - "go/types" - "strconv" -) - -func resolvePkgObjects(ctx *Context, f *ast.File) { - ctx.PkgObjects = make(map[*types.PkgName]string, len(f.Imports)) - - for _, spec := range f.Imports { - if spec.Name != nil { - obj := ctx.TypesInfo.ObjectOf(spec.Name) - ctx.PkgObjects[obj.(*types.PkgName)] = spec.Name.Name - } else { - obj := ctx.TypesInfo.Implicits[spec] - ctx.PkgObjects[obj.(*types.PkgName)] = obj.Name() - } - } -} - -func resolvePkgRenames(ctx *Context, f *ast.File) { - ctx.PkgRenames = make(map[string]string) - - for _, spec := range f.Imports { - if spec.Name != nil { - path, err := strconv.Unquote(spec.Path.Value) - if err != nil { - panic(err) - } - ctx.PkgRenames[path] = spec.Name.Name - } - } -} diff --git a/vendor/github.com/go-lintpack/lintpack/doc.go b/vendor/github.com/go-lintpack/lintpack/doc.go deleted file mode 100644 index 4aba342f536..00000000000 --- a/vendor/github.com/go-lintpack/lintpack/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package lintpack provides shared API between the linter and its checkers. -// -// Linter is usually implemented by creating instances of registered checkers. -// Checkers are registered by the AddChecker call. -package lintpack diff --git a/vendor/github.com/go-lintpack/lintpack/go.mod b/vendor/github.com/go-lintpack/lintpack/go.mod deleted file mode 100644 index b2e4cd984d7..00000000000 --- a/vendor/github.com/go-lintpack/lintpack/go.mod +++ /dev/null @@ -1,11 +0,0 @@ -module github.com/go-lintpack/lintpack - -require ( - github.com/go-toolsmith/astequal v0.0.0-20180903214952-dcb477bfacd6 - github.com/go-toolsmith/astfmt v0.0.0-20180903215011-8f8ee99c3086 - github.com/go-toolsmith/astp v0.0.0-20180903215135-0af7e3c24f30 - github.com/go-toolsmith/pkgload v0.0.0-20181119091011-e9e65178eee8 - github.com/google/go-cmp v0.2.0 - github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e - golang.org/x/tools v0.0.0-20181117154741-2ddaf7f79a09 -) diff --git a/vendor/github.com/go-lintpack/lintpack/go.sum b/vendor/github.com/go-lintpack/lintpack/go.sum deleted file mode 100644 index bd9f5dcb95e..00000000000 --- a/vendor/github.com/go-lintpack/lintpack/go.sum +++ /dev/null @@ -1,14 +0,0 @@ -github.com/go-toolsmith/astequal v0.0.0-20180903214952-dcb477bfacd6 h1:aTBUNRTatDDU24gbOEKEoLiDwxtc98ga6K/iMTm6fvs= -github.com/go-toolsmith/astequal v0.0.0-20180903214952-dcb477bfacd6/go.mod h1:H+xSiq0+LtiDC11+h1G32h7Of5O3CYFJ99GVbS5lDKY= -github.com/go-toolsmith/astfmt v0.0.0-20180903215011-8f8ee99c3086 h1:EIMuvbE9fbtQtimdLe5yeXjuC5CeKbQt8zH6GwtIrhM= -github.com/go-toolsmith/astfmt v0.0.0-20180903215011-8f8ee99c3086/go.mod h1:mP93XdblcopXwlyN4X4uodxXQhldPGZbcEJIimQHrkg= -github.com/go-toolsmith/astp v0.0.0-20180903215135-0af7e3c24f30 h1:zRJPftZJNLPDiOtvYbFRwjSbaJAcVOf80TeEmWGe2kQ= -github.com/go-toolsmith/astp v0.0.0-20180903215135-0af7e3c24f30/go.mod h1:SV2ur98SGypH1UjcPpCatrV5hPazG6+IfNHbkDXBRrk= -github.com/go-toolsmith/pkgload v0.0.0-20181119091011-e9e65178eee8 h1:vVouagbdmqTVlCIAxpyYsNNTbkKZ3V66VpKOLU/s6W4= -github.com/go-toolsmith/pkgload v0.0.0-20181119091011-e9e65178eee8/go.mod h1:WoMrjiy4zvdS+Bg6z9jZH82QXwkcgCBX6nOfnmdaHks= -github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e h1:9MlwzLdW7QSDrhDjFlsEYmxpFyIoXmYRon3dt0io31k= -github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= -golang.org/x/tools v0.0.0-20181117154741-2ddaf7f79a09 h1:QJFxMApN9XdBRwtqXfOidB2azUCA4ziuiMTrQ1uBGxw= -golang.org/x/tools v0.0.0-20181117154741-2ddaf7f79a09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/vendor/github.com/go-toolsmith/typep/.travis.yml b/vendor/github.com/go-toolsmith/typep/.travis.yml index c32ac00627d..d3ff3cca8be 100644 --- a/vendor/github.com/go-toolsmith/typep/.travis.yml +++ b/vendor/github.com/go-toolsmith/typep/.travis.yml @@ -5,5 +5,5 @@ install: - # Prevent default install action "go get -t -v ./...". script: - go get -t -v ./... - - go tool vet . + - go vet ./... - go test -v -race ./... diff --git a/vendor/github.com/go-toolsmith/typep/README.md b/vendor/github.com/go-toolsmith/typep/README.md index 73665801280..f7979148fa3 100644 --- a/vendor/github.com/go-toolsmith/typep/README.md +++ b/vendor/github.com/go-toolsmith/typep/README.md @@ -1,6 +1,6 @@ [![Go Report Card](https://goreportcard.com/badge/github.com/go-toolsmith/typep)](https://goreportcard.com/report/github.com/go-toolsmith/typep) [![GoDoc](https://godoc.org/github.com/go-toolsmith/typep?status.svg)](https://godoc.org/github.com/go-toolsmith/typep) - +[![Build Status](https://travis-ci.org/go-toolsmith/typep.svg?branch=master)](https://travis-ci.org/go-toolsmith/typep) # typep diff --git a/vendor/github.com/go-toolsmith/typep/predicates.go b/vendor/github.com/go-toolsmith/typep/predicates.go index 70e5b55cd17..b07325a726c 100644 --- a/vendor/github.com/go-toolsmith/typep/predicates.go +++ b/vendor/github.com/go-toolsmith/typep/predicates.go @@ -27,7 +27,7 @@ func IsTypeExpr(info *types.Info, x ast.Expr) bool { _, ok := info.ObjectOf(x).(*types.TypeName) return ok - case *ast.FuncType, *ast.StructType, *ast.InterfaceType, *ast.ArrayType, *ast.MapType: + case *ast.FuncType, *ast.StructType, *ast.InterfaceType, *ast.ArrayType, *ast.MapType, *ast.ChanType: return true default: diff --git a/vendor/github.com/go-toolsmith/typep/safeExpr.go b/vendor/github.com/go-toolsmith/typep/safeExpr.go index 7236e6e037e..d5835d97bb1 100644 --- a/vendor/github.com/go-toolsmith/typep/safeExpr.go +++ b/vendor/github.com/go-toolsmith/typep/safeExpr.go @@ -20,6 +20,10 @@ func SideEffectFree(info *types.Info, expr ast.Expr) bool { // whitelist to be on the conservative side. // Can be extended as needed. + if expr == nil { + return true + } + switch expr := expr.(type) { case *ast.StarExpr: return SideEffectFree(info, expr.X) @@ -31,6 +35,11 @@ func SideEffectFree(info *types.Info, expr ast.Expr) bool { SideEffectFree(info, expr.X) case *ast.BasicLit, *ast.Ident: return true + case *ast.SliceExpr: + return SideEffectFree(info, expr.X) && + SideEffectFree(info, expr.Low) && + SideEffectFree(info, expr.High) && + SideEffectFree(info, expr.Max) case *ast.IndexExpr: return SideEffectFree(info, expr.X) && SideEffectFree(info, expr.Index) @@ -38,6 +47,8 @@ func SideEffectFree(info *types.Info, expr ast.Expr) bool { return SideEffectFree(info, expr.X) case *ast.ParenExpr: return SideEffectFree(info, expr.X) + case *ast.TypeAssertExpr: + return SideEffectFree(info, expr.X) case *ast.CompositeLit: return SideEffectFreeList(info, expr.Elts) case *ast.CallExpr: diff --git a/vendor/github.com/go-xmlfmt/xmlfmt/LICENSE b/vendor/github.com/go-xmlfmt/xmlfmt/LICENSE new file mode 100644 index 00000000000..890776ab7c7 --- /dev/null +++ b/vendor/github.com/go-xmlfmt/xmlfmt/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 go-xmlfmt + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/go-xmlfmt/xmlfmt/README.md b/vendor/github.com/go-xmlfmt/xmlfmt/README.md new file mode 100644 index 00000000000..4eb6d69a03c --- /dev/null +++ b/vendor/github.com/go-xmlfmt/xmlfmt/README.md @@ -0,0 +1,178 @@ +# Go XML Formatter + +[![MIT License](http://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) +[![Go Doc](https://img.shields.io/badge/godoc-reference-4b68a3.svg)](https://godoc.org/github.com/go-xmlfmt/xmlfmt) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-xmlfmt/xmlfmt)](https://goreportcard.com/report/github.com/go-xmlfmt/xmlfmt) +[![Codeship Status](https://codeship.com/projects/c49f02b0-a384-0134-fb20-2e0351080565/status?branch=master)](https://codeship.com/projects/190297) + +## Synopsis + +The Go XML Formatter, xmlfmt, will format the XML string in a readable way. + +```go +package main + +import "github.com/go-xmlfmt/xmlfmt" + +func main() { + xml1 := `aSome org-or-otherWouldnt you like to knowPatCalifia` + x := xmlfmt.FormatXML(xml1, "\t", " ") + print(x) +} + +``` + +Output: + +```xml + + + a + + + + + + Some org-or-other + + Wouldnt you like to know + + + + Pat + + Califia + + + + + +``` + +There is no XML decoding and encoding involved, only pure regular expression matching and replacing. So it is much faster than going through decoding and encoding procedures. Moreover, the exact XML source string is preserved, instead of being changed by the encoder. This is why this package exists in the first place. + +## Command + +To use it on command line, check out [xmlfmt](https://github.com/AntonioSun/xmlfmt): + + +``` +$ xmlfmt +XML Formatter +built on 2019-12-08 + +The xmlfmt will format the XML string without rewriting the document + +Options: + + -h, --help display help information + -f, --file *The xml file to read from (or stdin) + -p, --prefix each element begins on a new line and this prefix + -i, --indent[= ] indent string for nested elements +``` + + +## Justification + +### The format + +The Go XML Formatter is not called XML Beautifier because the result is not *exactly* as what people would expect -- some, but not all, closing tags stays on the same line, just as shown above. Having been looking at the result and thinking over it, I now think it is actually a better way to present it, as those closing tags on the same line are better stay that way in my opinion. I.e., + +When it comes to very big XML strings, which is what I’m dealing every day, saving spaces by not allowing those closing tags taking extra lines is plus instead of negative to me. + +### The alternative + +To format it “properly”, i.e., as what people would normally see, is very hard using pure regular expression. In fact, according to Sam Whited from the go-nuts mlist, + +> Regular expression is, well, regular. This means that they can parse regular grammars, but can't parse context free grammars (like XML). It is actually impossible to use a regex to do this task; it will always be fragile, unfortunately. + +So if the output format is so important to you, then unfortunately you have to go through decoding and encoding procedures. But there are some drawbacks as well, as put by James McGill, in http://stackoverflow.com/questions/21117161, besides such method being slow: + +> I like this solution, but am still in search of a Golang XML formatter/prettyprinter that doesn't rewrite the document (other than formatting whitespace). Marshalling or using the Encoder will change namespace declarations. +> +> For example an element like "< ns1:Element />" will be translated to something like '< Element xmlns="http://bla...bla/ns1" >< /Element >' which seems harmless enough except when the intent is to not alter the xml other than formatting. -- James McGill Nov 12 '15 + +Using Sam's code as an example, + +https://play.golang.org/p/JUqQY3WpW5 + +The above code formats the following XML + +```xml + + + + + + 123 + John Brown + + + + +``` + +into this: + +```xml + +
+ + + + 123 + John Brown + + + +
+``` + +I know they are syntactically the same, however the problem is that they *look* totally different. + +That's why there is this package, an XML Beautifier that doesn't rewrite the document. + +## Credit + +The credit goes to **diotalevi** from his post at http://www.perlmonks.org/?node_id=261292. + +However, it does not work for all cases. For example, + +```sh +$ echo '
123John Brown
' | perl -pe 's/(?<=>)\s+(?=<)//g; s(<(/?)([^/>]+)(/?)>\s*(?=(".($1&&($4 eq"
+123 +John Brown + + + + +``` + +I simplified the algorithm, and now it should work for all cases: + +```sh +echo '
123John Brown
' | perl -pe 's/(?<=>)\s+(?=<)//g; s(<(/?)([^>]+)(/?)>)($indent+=$3?0:$1?-1:1;"<$1$2$3>"."\n".(" "x$indent))ge' +``` +```xml + +
+
+ + + + + 123 + + John Brown + + + +
+``` + +This package is a direct translate from above Perl code into Go, +then further enhanced by @ruandao. diff --git a/vendor/github.com/go-xmlfmt/xmlfmt/xmlfmt.go b/vendor/github.com/go-xmlfmt/xmlfmt/xmlfmt.go new file mode 100644 index 00000000000..b744f5b3506 --- /dev/null +++ b/vendor/github.com/go-xmlfmt/xmlfmt/xmlfmt.go @@ -0,0 +1,56 @@ +//////////////////////////////////////////////////////////////////////////// +// Porgram: xmlfmt.go +// Purpose: Go XML Beautify from XML string using pure string manipulation +// Authors: Antonio Sun (c) 2016-2019, All rights reserved +//////////////////////////////////////////////////////////////////////////// + +package xmlfmt + +import ( + "regexp" + "strings" +) + +var ( + reg = regexp.MustCompile(`<([/!]?)([^>]+?)(/?)>`) + // NL is the newline string used in XML output, define for DOS-convenient. + NL = "\r\n" +) + +// FormatXML will (purly) reformat the XML string in a readable way, without any rewriting/altering the structure +func FormatXML(xmls, prefix, indent string) string { + src := regexp.MustCompile(`(?s)>\s+<`).ReplaceAllString(xmls, "><") + + rf := replaceTag(prefix, indent) + return (prefix + reg.ReplaceAllStringFunc(src, rf)) +} + +// replaceTag returns a closure function to do 's/(?<=>)\s+(?=<)//g; s(<(/?)([^>]+?)(/?)>)($indent+=$3?0:$1?-1:1;"<$1$2$3>"."\n".(" "x$indent))ge' as in Perl +// and deal with comments as well +func replaceTag(prefix, indent string) func(string) string { + indentLevel := 0 + return func(m string) string { + // head elem + if strings.HasPrefix(m, "") { + return NL + prefix + strings.Repeat(indent, indentLevel) + m + } + // comment elem + if strings.HasPrefix(m, " c.MaxEntries { + c.RemoveOldest() + } +} + +// Get looks up a key's value from the cache. +func (c *Cache) Get(key Key) (value interface{}, ok bool) { + if c.cache == nil { + return + } + if ele, hit := c.cache[key]; hit { + c.ll.MoveToFront(ele) + return ele.Value.(*entry).value, true + } + return +} + +// Remove removes the provided key from the cache. +func (c *Cache) Remove(key Key) { + if c.cache == nil { + return + } + if ele, hit := c.cache[key]; hit { + c.removeElement(ele) + } +} + +// RemoveOldest removes the oldest item from the cache. +func (c *Cache) RemoveOldest() { + if c.cache == nil { + return + } + ele := c.ll.Back() + if ele != nil { + c.removeElement(ele) + } +} + +func (c *Cache) removeElement(e *list.Element) { + c.ll.Remove(e) + kv := e.Value.(*entry) + delete(c.cache, kv.key) + if c.OnEvicted != nil { + c.OnEvicted(kv.key, kv.value) + } +} + +// Len returns the number of items in the cache. +func (c *Cache) Len() int { + if c.cache == nil { + return 0 + } + return c.ll.Len() +} + +// Clear purges all stored items from the cache. +func (c *Cache) Clear() { + if c.OnEvicted != nil { + for _, e := range c.cache { + kv := e.Value.(*entry) + c.OnEvicted(kv.key, kv.value) + } + } + c.ll = nil + c.cache = nil +} diff --git a/vendor/github.com/golang/protobuf/internal/gengogrpc/grpc.go b/vendor/github.com/golang/protobuf/internal/gengogrpc/grpc.go new file mode 100644 index 00000000000..fd2f51d8901 --- /dev/null +++ b/vendor/github.com/golang/protobuf/internal/gengogrpc/grpc.go @@ -0,0 +1,398 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package gengogrpc contains the gRPC code generator. +package gengogrpc + +import ( + "fmt" + "strconv" + "strings" + + "google.golang.org/protobuf/compiler/protogen" + + "google.golang.org/protobuf/types/descriptorpb" +) + +const ( + contextPackage = protogen.GoImportPath("context") + grpcPackage = protogen.GoImportPath("google.golang.org/grpc") + codesPackage = protogen.GoImportPath("google.golang.org/grpc/codes") + statusPackage = protogen.GoImportPath("google.golang.org/grpc/status") +) + +// GenerateFile generates a _grpc.pb.go file containing gRPC service definitions. +func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile { + if len(file.Services) == 0 { + return nil + } + filename := file.GeneratedFilenamePrefix + "_grpc.pb.go" + g := gen.NewGeneratedFile(filename, file.GoImportPath) + g.P("// Code generated by protoc-gen-go-grpc. DO NOT EDIT.") + g.P() + g.P("package ", file.GoPackageName) + g.P() + GenerateFileContent(gen, file, g) + return g +} + +// GenerateFileContent generates the gRPC service definitions, excluding the package statement. +func GenerateFileContent(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) { + if len(file.Services) == 0 { + return + } + + // TODO: Remove this. We don't need to include these references any more. + g.P("// Reference imports to suppress errors if they are not otherwise used.") + g.P("var _ ", contextPackage.Ident("Context")) + g.P("var _ ", grpcPackage.Ident("ClientConnInterface")) + g.P() + + g.P("// This is a compile-time assertion to ensure that this generated file") + g.P("// is compatible with the grpc package it is being compiled against.") + g.P("const _ = ", grpcPackage.Ident("SupportPackageIsVersion6")) + g.P() + for _, service := range file.Services { + genService(gen, file, g, service) + } +} + +func genService(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { + clientName := service.GoName + "Client" + + g.P("// ", clientName, " is the client API for ", service.GoName, " service.") + g.P("//") + g.P("// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.") + + // Client interface. + if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { + g.P("//") + g.P(deprecationComment) + } + g.Annotate(clientName, service.Location) + g.P("type ", clientName, " interface {") + for _, method := range service.Methods { + g.Annotate(clientName+"."+method.GoName, method.Location) + if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() { + g.P(deprecationComment) + } + g.P(method.Comments.Leading, + clientSignature(g, method)) + } + g.P("}") + g.P() + + // Client structure. + g.P("type ", unexport(clientName), " struct {") + g.P("cc ", grpcPackage.Ident("ClientConnInterface")) + g.P("}") + g.P() + + // NewClient factory. + if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { + g.P(deprecationComment) + } + g.P("func New", clientName, " (cc ", grpcPackage.Ident("ClientConnInterface"), ") ", clientName, " {") + g.P("return &", unexport(clientName), "{cc}") + g.P("}") + g.P() + + var methodIndex, streamIndex int + // Client method implementations. + for _, method := range service.Methods { + if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() { + // Unary RPC method + genClientMethod(gen, file, g, method, methodIndex) + methodIndex++ + } else { + // Streaming RPC method + genClientMethod(gen, file, g, method, streamIndex) + streamIndex++ + } + } + + // Server interface. + serverType := service.GoName + "Server" + g.P("// ", serverType, " is the server API for ", service.GoName, " service.") + if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { + g.P("//") + g.P(deprecationComment) + } + g.Annotate(serverType, service.Location) + g.P("type ", serverType, " interface {") + for _, method := range service.Methods { + g.Annotate(serverType+"."+method.GoName, method.Location) + if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() { + g.P(deprecationComment) + } + g.P(method.Comments.Leading, + serverSignature(g, method)) + } + g.P("}") + g.P() + + // Server Unimplemented struct for forward compatibility. + g.P("// Unimplemented", serverType, " can be embedded to have forward compatible implementations.") + g.P("type Unimplemented", serverType, " struct {") + g.P("}") + g.P() + for _, method := range service.Methods { + nilArg := "" + if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { + nilArg = "nil," + } + g.P("func (*Unimplemented", serverType, ") ", serverSignature(g, method), "{") + g.P("return ", nilArg, statusPackage.Ident("Errorf"), "(", codesPackage.Ident("Unimplemented"), `, "method `, method.GoName, ` not implemented")`) + g.P("}") + } + g.P() + + // Server registration. + if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { + g.P(deprecationComment) + } + serviceDescVar := "_" + service.GoName + "_serviceDesc" + g.P("func Register", service.GoName, "Server(s *", grpcPackage.Ident("Server"), ", srv ", serverType, ") {") + g.P("s.RegisterService(&", serviceDescVar, `, srv)`) + g.P("}") + g.P() + + // Server handler implementations. + var handlerNames []string + for _, method := range service.Methods { + hname := genServerMethod(gen, file, g, method) + handlerNames = append(handlerNames, hname) + } + + // Service descriptor. + g.P("var ", serviceDescVar, " = ", grpcPackage.Ident("ServiceDesc"), " {") + g.P("ServiceName: ", strconv.Quote(string(service.Desc.FullName())), ",") + g.P("HandlerType: (*", serverType, ")(nil),") + g.P("Methods: []", grpcPackage.Ident("MethodDesc"), "{") + for i, method := range service.Methods { + if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() { + continue + } + g.P("{") + g.P("MethodName: ", strconv.Quote(string(method.Desc.Name())), ",") + g.P("Handler: ", handlerNames[i], ",") + g.P("},") + } + g.P("},") + g.P("Streams: []", grpcPackage.Ident("StreamDesc"), "{") + for i, method := range service.Methods { + if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { + continue + } + g.P("{") + g.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",") + g.P("Handler: ", handlerNames[i], ",") + if method.Desc.IsStreamingServer() { + g.P("ServerStreams: true,") + } + if method.Desc.IsStreamingClient() { + g.P("ClientStreams: true,") + } + g.P("},") + } + g.P("},") + g.P("Metadata: \"", file.Desc.Path(), "\",") + g.P("}") + g.P() +} + +func clientSignature(g *protogen.GeneratedFile, method *protogen.Method) string { + s := method.GoName + "(ctx " + g.QualifiedGoIdent(contextPackage.Ident("Context")) + if !method.Desc.IsStreamingClient() { + s += ", in *" + g.QualifiedGoIdent(method.Input.GoIdent) + } + s += ", opts ..." + g.QualifiedGoIdent(grpcPackage.Ident("CallOption")) + ") (" + if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { + s += "*" + g.QualifiedGoIdent(method.Output.GoIdent) + } else { + s += method.Parent.GoName + "_" + method.GoName + "Client" + } + s += ", error)" + return s +} + +func genClientMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method, index int) { + service := method.Parent + sname := fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.Desc.Name()) + + if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() { + g.P(deprecationComment) + } + g.P("func (c *", unexport(service.GoName), "Client) ", clientSignature(g, method), "{") + if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() { + g.P("out := new(", method.Output.GoIdent, ")") + g.P(`err := c.cc.Invoke(ctx, "`, sname, `", in, out, opts...)`) + g.P("if err != nil { return nil, err }") + g.P("return out, nil") + g.P("}") + g.P() + return + } + streamType := unexport(service.GoName) + method.GoName + "Client" + serviceDescVar := "_" + service.GoName + "_serviceDesc" + g.P("stream, err := c.cc.NewStream(ctx, &", serviceDescVar, ".Streams[", index, `], "`, sname, `", opts...)`) + g.P("if err != nil { return nil, err }") + g.P("x := &", streamType, "{stream}") + if !method.Desc.IsStreamingClient() { + g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }") + g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") + } + g.P("return x, nil") + g.P("}") + g.P() + + genSend := method.Desc.IsStreamingClient() + genRecv := method.Desc.IsStreamingServer() + genCloseAndRecv := !method.Desc.IsStreamingServer() + + // Stream auxiliary types and methods. + g.P("type ", service.GoName, "_", method.GoName, "Client interface {") + if genSend { + g.P("Send(*", method.Input.GoIdent, ") error") + } + if genRecv { + g.P("Recv() (*", method.Output.GoIdent, ", error)") + } + if genCloseAndRecv { + g.P("CloseAndRecv() (*", method.Output.GoIdent, ", error)") + } + g.P(grpcPackage.Ident("ClientStream")) + g.P("}") + g.P() + + g.P("type ", streamType, " struct {") + g.P(grpcPackage.Ident("ClientStream")) + g.P("}") + g.P() + + if genSend { + g.P("func (x *", streamType, ") Send(m *", method.Input.GoIdent, ") error {") + g.P("return x.ClientStream.SendMsg(m)") + g.P("}") + g.P() + } + if genRecv { + g.P("func (x *", streamType, ") Recv() (*", method.Output.GoIdent, ", error) {") + g.P("m := new(", method.Output.GoIdent, ")") + g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") + g.P("return m, nil") + g.P("}") + g.P() + } + if genCloseAndRecv { + g.P("func (x *", streamType, ") CloseAndRecv() (*", method.Output.GoIdent, ", error) {") + g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") + g.P("m := new(", method.Output.GoIdent, ")") + g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") + g.P("return m, nil") + g.P("}") + g.P() + } +} + +func serverSignature(g *protogen.GeneratedFile, method *protogen.Method) string { + var reqArgs []string + ret := "error" + if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { + reqArgs = append(reqArgs, g.QualifiedGoIdent(contextPackage.Ident("Context"))) + ret = "(*" + g.QualifiedGoIdent(method.Output.GoIdent) + ", error)" + } + if !method.Desc.IsStreamingClient() { + reqArgs = append(reqArgs, "*"+g.QualifiedGoIdent(method.Input.GoIdent)) + } + if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() { + reqArgs = append(reqArgs, method.Parent.GoName+"_"+method.GoName+"Server") + } + return method.GoName + "(" + strings.Join(reqArgs, ", ") + ") " + ret +} + +func genServerMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method) string { + service := method.Parent + hname := fmt.Sprintf("_%s_%s_Handler", service.GoName, method.GoName) + + if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { + g.P("func ", hname, "(srv interface{}, ctx ", contextPackage.Ident("Context"), ", dec func(interface{}) error, interceptor ", grpcPackage.Ident("UnaryServerInterceptor"), ") (interface{}, error) {") + g.P("in := new(", method.Input.GoIdent, ")") + g.P("if err := dec(in); err != nil { return nil, err }") + g.P("if interceptor == nil { return srv.(", service.GoName, "Server).", method.GoName, "(ctx, in) }") + g.P("info := &", grpcPackage.Ident("UnaryServerInfo"), "{") + g.P("Server: srv,") + g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.GoName)), ",") + g.P("}") + g.P("handler := func(ctx ", contextPackage.Ident("Context"), ", req interface{}) (interface{}, error) {") + g.P("return srv.(", service.GoName, "Server).", method.GoName, "(ctx, req.(*", method.Input.GoIdent, "))") + g.P("}") + g.P("return interceptor(ctx, in, info, handler)") + g.P("}") + g.P() + return hname + } + streamType := unexport(service.GoName) + method.GoName + "Server" + g.P("func ", hname, "(srv interface{}, stream ", grpcPackage.Ident("ServerStream"), ") error {") + if !method.Desc.IsStreamingClient() { + g.P("m := new(", method.Input.GoIdent, ")") + g.P("if err := stream.RecvMsg(m); err != nil { return err }") + g.P("return srv.(", service.GoName, "Server).", method.GoName, "(m, &", streamType, "{stream})") + } else { + g.P("return srv.(", service.GoName, "Server).", method.GoName, "(&", streamType, "{stream})") + } + g.P("}") + g.P() + + genSend := method.Desc.IsStreamingServer() + genSendAndClose := !method.Desc.IsStreamingServer() + genRecv := method.Desc.IsStreamingClient() + + // Stream auxiliary types and methods. + g.P("type ", service.GoName, "_", method.GoName, "Server interface {") + if genSend { + g.P("Send(*", method.Output.GoIdent, ") error") + } + if genSendAndClose { + g.P("SendAndClose(*", method.Output.GoIdent, ") error") + } + if genRecv { + g.P("Recv() (*", method.Input.GoIdent, ", error)") + } + g.P(grpcPackage.Ident("ServerStream")) + g.P("}") + g.P() + + g.P("type ", streamType, " struct {") + g.P(grpcPackage.Ident("ServerStream")) + g.P("}") + g.P() + + if genSend { + g.P("func (x *", streamType, ") Send(m *", method.Output.GoIdent, ") error {") + g.P("return x.ServerStream.SendMsg(m)") + g.P("}") + g.P() + } + if genSendAndClose { + g.P("func (x *", streamType, ") SendAndClose(m *", method.Output.GoIdent, ") error {") + g.P("return x.ServerStream.SendMsg(m)") + g.P("}") + g.P() + } + if genRecv { + g.P("func (x *", streamType, ") Recv() (*", method.Input.GoIdent, ", error) {") + g.P("m := new(", method.Input.GoIdent, ")") + g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }") + g.P("return m, nil") + g.P("}") + g.P() + } + + return hname +} + +const deprecationComment = "// Deprecated: Do not use." + +func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] } diff --git a/vendor/github.com/golang/protobuf/proto/buffer.go b/vendor/github.com/golang/protobuf/proto/buffer.go new file mode 100644 index 00000000000..e810e6fea12 --- /dev/null +++ b/vendor/github.com/golang/protobuf/proto/buffer.go @@ -0,0 +1,324 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "errors" + "fmt" + + "google.golang.org/protobuf/encoding/prototext" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/runtime/protoimpl" +) + +const ( + WireVarint = 0 + WireFixed32 = 5 + WireFixed64 = 1 + WireBytes = 2 + WireStartGroup = 3 + WireEndGroup = 4 +) + +// EncodeVarint returns the varint encoded bytes of v. +func EncodeVarint(v uint64) []byte { + return protowire.AppendVarint(nil, v) +} + +// SizeVarint returns the length of the varint encoded bytes of v. +// This is equal to len(EncodeVarint(v)). +func SizeVarint(v uint64) int { + return protowire.SizeVarint(v) +} + +// DecodeVarint parses a varint encoded integer from b, +// returning the integer value and the length of the varint. +// It returns (0, 0) if there is a parse error. +func DecodeVarint(b []byte) (uint64, int) { + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return 0, 0 + } + return v, n +} + +// Buffer is a buffer for encoding and decoding the protobuf wire format. +// It may be reused between invocations to reduce memory usage. +type Buffer struct { + buf []byte + idx int + deterministic bool +} + +// NewBuffer allocates a new Buffer initialized with buf, +// where the contents of buf are considered the unread portion of the buffer. +func NewBuffer(buf []byte) *Buffer { + return &Buffer{buf: buf} +} + +// SetDeterministic specifies whether to use deterministic serialization. +// +// Deterministic serialization guarantees that for a given binary, equal +// messages will always be serialized to the same bytes. This implies: +// +// - Repeated serialization of a message will return the same bytes. +// - Different processes of the same binary (which may be executing on +// different machines) will serialize equal messages to the same bytes. +// +// Note that the deterministic serialization is NOT canonical across +// languages. It is not guaranteed to remain stable over time. It is unstable +// across different builds with schema changes due to unknown fields. +// Users who need canonical serialization (e.g., persistent storage in a +// canonical form, fingerprinting, etc.) should define their own +// canonicalization specification and implement their own serializer rather +// than relying on this API. +// +// If deterministic serialization is requested, map entries will be sorted +// by keys in lexographical order. This is an implementation detail and +// subject to change. +func (b *Buffer) SetDeterministic(deterministic bool) { + b.deterministic = deterministic +} + +// SetBuf sets buf as the internal buffer, +// where the contents of buf are considered the unread portion of the buffer. +func (b *Buffer) SetBuf(buf []byte) { + b.buf = buf + b.idx = 0 +} + +// Reset clears the internal buffer of all written and unread data. +func (b *Buffer) Reset() { + b.buf = b.buf[:0] + b.idx = 0 +} + +// Bytes returns the internal buffer. +func (b *Buffer) Bytes() []byte { + return b.buf +} + +// Unread returns the unread portion of the buffer. +func (b *Buffer) Unread() []byte { + return b.buf[b.idx:] +} + +// Marshal appends the wire-format encoding of m to the buffer. +func (b *Buffer) Marshal(m Message) error { + var err error + b.buf, err = marshalAppend(b.buf, m, b.deterministic) + return err +} + +// Unmarshal parses the wire-format message in the buffer and +// places the decoded results in m. +// It does not reset m before unmarshaling. +func (b *Buffer) Unmarshal(m Message) error { + err := UnmarshalMerge(b.Unread(), m) + b.idx = len(b.buf) + return err +} + +type unknownFields struct{ XXX_unrecognized protoimpl.UnknownFields } + +func (m *unknownFields) String() string { panic("not implemented") } +func (m *unknownFields) Reset() { panic("not implemented") } +func (m *unknownFields) ProtoMessage() { panic("not implemented") } + +// DebugPrint dumps the encoded bytes of b with a header and footer including s +// to stdout. This is only intended for debugging. +func (*Buffer) DebugPrint(s string, b []byte) { + m := MessageReflect(new(unknownFields)) + m.SetUnknown(b) + b, _ = prototext.MarshalOptions{AllowPartial: true, Indent: "\t"}.Marshal(m.Interface()) + fmt.Printf("==== %s ====\n%s==== %s ====\n", s, b, s) +} + +// EncodeVarint appends an unsigned varint encoding to the buffer. +func (b *Buffer) EncodeVarint(v uint64) error { + b.buf = protowire.AppendVarint(b.buf, v) + return nil +} + +// EncodeZigzag32 appends a 32-bit zig-zag varint encoding to the buffer. +func (b *Buffer) EncodeZigzag32(v uint64) error { + return b.EncodeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) +} + +// EncodeZigzag64 appends a 64-bit zig-zag varint encoding to the buffer. +func (b *Buffer) EncodeZigzag64(v uint64) error { + return b.EncodeVarint(uint64((uint64(v) << 1) ^ uint64((int64(v) >> 63)))) +} + +// EncodeFixed32 appends a 32-bit little-endian integer to the buffer. +func (b *Buffer) EncodeFixed32(v uint64) error { + b.buf = protowire.AppendFixed32(b.buf, uint32(v)) + return nil +} + +// EncodeFixed64 appends a 64-bit little-endian integer to the buffer. +func (b *Buffer) EncodeFixed64(v uint64) error { + b.buf = protowire.AppendFixed64(b.buf, uint64(v)) + return nil +} + +// EncodeRawBytes appends a length-prefixed raw bytes to the buffer. +func (b *Buffer) EncodeRawBytes(v []byte) error { + b.buf = protowire.AppendBytes(b.buf, v) + return nil +} + +// EncodeStringBytes appends a length-prefixed raw bytes to the buffer. +// It does not validate whether v contains valid UTF-8. +func (b *Buffer) EncodeStringBytes(v string) error { + b.buf = protowire.AppendString(b.buf, v) + return nil +} + +// EncodeMessage appends a length-prefixed encoded message to the buffer. +func (b *Buffer) EncodeMessage(m Message) error { + var err error + b.buf = protowire.AppendVarint(b.buf, uint64(Size(m))) + b.buf, err = marshalAppend(b.buf, m, b.deterministic) + return err +} + +// DecodeVarint consumes an encoded unsigned varint from the buffer. +func (b *Buffer) DecodeVarint() (uint64, error) { + v, n := protowire.ConsumeVarint(b.buf[b.idx:]) + if n < 0 { + return 0, protowire.ParseError(n) + } + b.idx += n + return uint64(v), nil +} + +// DecodeZigzag32 consumes an encoded 32-bit zig-zag varint from the buffer. +func (b *Buffer) DecodeZigzag32() (uint64, error) { + v, err := b.DecodeVarint() + if err != nil { + return 0, err + } + return uint64((uint32(v) >> 1) ^ uint32((int32(v&1)<<31)>>31)), nil +} + +// DecodeZigzag64 consumes an encoded 64-bit zig-zag varint from the buffer. +func (b *Buffer) DecodeZigzag64() (uint64, error) { + v, err := b.DecodeVarint() + if err != nil { + return 0, err + } + return uint64((uint64(v) >> 1) ^ uint64((int64(v&1)<<63)>>63)), nil +} + +// DecodeFixed32 consumes a 32-bit little-endian integer from the buffer. +func (b *Buffer) DecodeFixed32() (uint64, error) { + v, n := protowire.ConsumeFixed32(b.buf[b.idx:]) + if n < 0 { + return 0, protowire.ParseError(n) + } + b.idx += n + return uint64(v), nil +} + +// DecodeFixed64 consumes a 64-bit little-endian integer from the buffer. +func (b *Buffer) DecodeFixed64() (uint64, error) { + v, n := protowire.ConsumeFixed64(b.buf[b.idx:]) + if n < 0 { + return 0, protowire.ParseError(n) + } + b.idx += n + return uint64(v), nil +} + +// DecodeRawBytes consumes a length-prefixed raw bytes from the buffer. +// If alloc is specified, it returns a copy the raw bytes +// rather than a sub-slice of the buffer. +func (b *Buffer) DecodeRawBytes(alloc bool) ([]byte, error) { + v, n := protowire.ConsumeBytes(b.buf[b.idx:]) + if n < 0 { + return nil, protowire.ParseError(n) + } + b.idx += n + if alloc { + v = append([]byte(nil), v...) + } + return v, nil +} + +// DecodeStringBytes consumes a length-prefixed raw bytes from the buffer. +// It does not validate whether the raw bytes contain valid UTF-8. +func (b *Buffer) DecodeStringBytes() (string, error) { + v, n := protowire.ConsumeString(b.buf[b.idx:]) + if n < 0 { + return "", protowire.ParseError(n) + } + b.idx += n + return v, nil +} + +// DecodeMessage consumes a length-prefixed message from the buffer. +// It does not reset m before unmarshaling. +func (b *Buffer) DecodeMessage(m Message) error { + v, err := b.DecodeRawBytes(false) + if err != nil { + return err + } + return UnmarshalMerge(v, m) +} + +// DecodeGroup consumes a message group from the buffer. +// It assumes that the start group marker has already been consumed and +// consumes all bytes until (and including the end group marker). +// It does not reset m before unmarshaling. +func (b *Buffer) DecodeGroup(m Message) error { + v, n, err := consumeGroup(b.buf[b.idx:]) + if err != nil { + return err + } + b.idx += n + return UnmarshalMerge(v, m) +} + +// consumeGroup parses b until it finds an end group marker, returning +// the raw bytes of the message (excluding the end group marker) and the +// the total length of the message (including the end group marker). +func consumeGroup(b []byte) ([]byte, int, error) { + b0 := b + depth := 1 // assume this follows a start group marker + for { + _, wtyp, tagLen := protowire.ConsumeTag(b) + if tagLen < 0 { + return nil, 0, protowire.ParseError(tagLen) + } + b = b[tagLen:] + + var valLen int + switch wtyp { + case protowire.VarintType: + _, valLen = protowire.ConsumeVarint(b) + case protowire.Fixed32Type: + _, valLen = protowire.ConsumeFixed32(b) + case protowire.Fixed64Type: + _, valLen = protowire.ConsumeFixed64(b) + case protowire.BytesType: + _, valLen = protowire.ConsumeBytes(b) + case protowire.StartGroupType: + depth++ + case protowire.EndGroupType: + depth-- + default: + return nil, 0, errors.New("proto: cannot parse reserved wire type") + } + if valLen < 0 { + return nil, 0, protowire.ParseError(valLen) + } + b = b[valLen:] + + if depth == 0 { + return b0[:len(b0)-len(b)-tagLen], len(b0) - len(b), nil + } + } +} diff --git a/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/golang/protobuf/proto/clone.go deleted file mode 100644 index 3cd3249f706..00000000000 --- a/vendor/github.com/golang/protobuf/proto/clone.go +++ /dev/null @@ -1,253 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Protocol buffer deep copy and merge. -// TODO: RawMessage. - -package proto - -import ( - "fmt" - "log" - "reflect" - "strings" -) - -// Clone returns a deep copy of a protocol buffer. -func Clone(src Message) Message { - in := reflect.ValueOf(src) - if in.IsNil() { - return src - } - out := reflect.New(in.Type().Elem()) - dst := out.Interface().(Message) - Merge(dst, src) - return dst -} - -// Merger is the interface representing objects that can merge messages of the same type. -type Merger interface { - // Merge merges src into this message. - // Required and optional fields that are set in src will be set to that value in dst. - // Elements of repeated fields will be appended. - // - // Merge may panic if called with a different argument type than the receiver. - Merge(src Message) -} - -// generatedMerger is the custom merge method that generated protos will have. -// We must add this method since a generate Merge method will conflict with -// many existing protos that have a Merge data field already defined. -type generatedMerger interface { - XXX_Merge(src Message) -} - -// Merge merges src into dst. -// Required and optional fields that are set in src will be set to that value in dst. -// Elements of repeated fields will be appended. -// Merge panics if src and dst are not the same type, or if dst is nil. -func Merge(dst, src Message) { - if m, ok := dst.(Merger); ok { - m.Merge(src) - return - } - - in := reflect.ValueOf(src) - out := reflect.ValueOf(dst) - if out.IsNil() { - panic("proto: nil destination") - } - if in.Type() != out.Type() { - panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src)) - } - if in.IsNil() { - return // Merge from nil src is a noop - } - if m, ok := dst.(generatedMerger); ok { - m.XXX_Merge(src) - return - } - mergeStruct(out.Elem(), in.Elem()) -} - -func mergeStruct(out, in reflect.Value) { - sprop := GetProperties(in.Type()) - for i := 0; i < in.NumField(); i++ { - f := in.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) - } - - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - uf := in.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return - } - uin := uf.Bytes() - if len(uin) > 0 { - out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) - } -} - -// mergeAny performs a merge between two values of the same type. -// viaPtr indicates whether the values were indirected through a pointer (implying proto2). -// prop is set if this is a struct field (it may be nil). -func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { - if in.Type() == protoMessageType { - if !in.IsNil() { - if out.IsNil() { - out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) - } else { - Merge(out.Interface().(Message), in.Interface().(Message)) - } - } - return - } - switch in.Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - if !viaPtr && isProto3Zero(in) { - return - } - out.Set(in) - case reflect.Interface: - // Probably a oneof field; copy non-nil values. - if in.IsNil() { - return - } - // Allocate destination if it is not set, or set to a different type. - // Otherwise we will merge as normal. - if out.IsNil() || out.Elem().Type() != in.Elem().Type() { - out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) - } - mergeAny(out.Elem(), in.Elem(), false, nil) - case reflect.Map: - if in.Len() == 0 { - return - } - if out.IsNil() { - out.Set(reflect.MakeMap(in.Type())) - } - // For maps with value types of *T or []byte we need to deep copy each value. - elemKind := in.Type().Elem().Kind() - for _, key := range in.MapKeys() { - var val reflect.Value - switch elemKind { - case reflect.Ptr: - val = reflect.New(in.Type().Elem().Elem()) - mergeAny(val, in.MapIndex(key), false, nil) - case reflect.Slice: - val = in.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - default: - val = in.MapIndex(key) - } - out.SetMapIndex(key, val) - } - case reflect.Ptr: - if in.IsNil() { - return - } - if out.IsNil() { - out.Set(reflect.New(in.Elem().Type())) - } - mergeAny(out.Elem(), in.Elem(), true, nil) - case reflect.Slice: - if in.IsNil() { - return - } - if in.Type().Elem().Kind() == reflect.Uint8 { - // []byte is a scalar bytes field, not a repeated field. - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value, and should not - // be merged. - if prop != nil && prop.proto3 && in.Len() == 0 { - return - } - - // Make a deep copy. - // Append to []byte{} instead of []byte(nil) so that we never end up - // with a nil result. - out.SetBytes(append([]byte{}, in.Bytes()...)) - return - } - n := in.Len() - if out.IsNil() { - out.Set(reflect.MakeSlice(in.Type(), 0, n)) - } - switch in.Type().Elem().Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - out.Set(reflect.AppendSlice(out, in)) - default: - for i := 0; i < n; i++ { - x := reflect.Indirect(reflect.New(in.Type().Elem())) - mergeAny(x, in.Index(i), false, nil) - out.Set(reflect.Append(out, x)) - } - } - case reflect.Struct: - mergeStruct(out, in) - default: - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to copy %v", in) - } -} - -func mergeExtension(out, in map[int32]Extension) { - for extNum, eIn := range in { - eOut := Extension{desc: eIn.desc} - if eIn.value != nil { - v := reflect.New(reflect.TypeOf(eIn.value)).Elem() - mergeAny(v, reflect.ValueOf(eIn.value), false, nil) - eOut.value = v.Interface() - } - if eIn.enc != nil { - eOut.enc = make([]byte, len(eIn.enc)) - copy(eOut.enc, eIn.enc) - } - - out[extNum] = eOut - } -} diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go deleted file mode 100644 index 63b0f08bef2..00000000000 --- a/vendor/github.com/golang/protobuf/proto/decode.go +++ /dev/null @@ -1,427 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for decoding protocol buffer data to construct in-memory representations. - */ - -import ( - "errors" - "fmt" - "io" -) - -// errOverflow is returned when an integer is too large to be represented. -var errOverflow = errors.New("proto: integer overflow") - -// ErrInternalBadWireType is returned by generated code when an incorrect -// wire type is encountered. It does not get returned to user code. -var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") - -// DecodeVarint reads a varint-encoded integer from the slice. -// It returns the integer and the number of bytes consumed, or -// zero if there is not enough. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func DecodeVarint(buf []byte) (x uint64, n int) { - for shift := uint(0); shift < 64; shift += 7 { - if n >= len(buf) { - return 0, 0 - } - b := uint64(buf[n]) - n++ - x |= (b & 0x7F) << shift - if (b & 0x80) == 0 { - return x, n - } - } - - // The number is too large to represent in a 64-bit value. - return 0, 0 -} - -func (p *Buffer) decodeVarintSlow() (x uint64, err error) { - i := p.index - l := len(p.buf) - - for shift := uint(0); shift < 64; shift += 7 { - if i >= l { - err = io.ErrUnexpectedEOF - return - } - b := p.buf[i] - i++ - x |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - p.index = i - return - } - } - - // The number is too large to represent in a 64-bit value. - err = errOverflow - return -} - -// DecodeVarint reads a varint-encoded integer from the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) DecodeVarint() (x uint64, err error) { - i := p.index - buf := p.buf - - if i >= len(buf) { - return 0, io.ErrUnexpectedEOF - } else if buf[i] < 0x80 { - p.index++ - return uint64(buf[i]), nil - } else if len(buf)-i < 10 { - return p.decodeVarintSlow() - } - - var b uint64 - // we already checked the first byte - x = uint64(buf[i]) - 0x80 - i++ - - b = uint64(buf[i]) - i++ - x += b << 7 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 7 - - b = uint64(buf[i]) - i++ - x += b << 14 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 14 - - b = uint64(buf[i]) - i++ - x += b << 21 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 21 - - b = uint64(buf[i]) - i++ - x += b << 28 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 28 - - b = uint64(buf[i]) - i++ - x += b << 35 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 35 - - b = uint64(buf[i]) - i++ - x += b << 42 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 42 - - b = uint64(buf[i]) - i++ - x += b << 49 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 49 - - b = uint64(buf[i]) - i++ - x += b << 56 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 56 - - b = uint64(buf[i]) - i++ - x += b << 63 - if b&0x80 == 0 { - goto done - } - - return 0, errOverflow - -done: - p.index = i - return x, nil -} - -// DecodeFixed64 reads a 64-bit integer from the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) DecodeFixed64() (x uint64, err error) { - // x, err already 0 - i := p.index + 8 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-8]) - x |= uint64(p.buf[i-7]) << 8 - x |= uint64(p.buf[i-6]) << 16 - x |= uint64(p.buf[i-5]) << 24 - x |= uint64(p.buf[i-4]) << 32 - x |= uint64(p.buf[i-3]) << 40 - x |= uint64(p.buf[i-2]) << 48 - x |= uint64(p.buf[i-1]) << 56 - return -} - -// DecodeFixed32 reads a 32-bit integer from the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) DecodeFixed32() (x uint64, err error) { - // x, err already 0 - i := p.index + 4 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-4]) - x |= uint64(p.buf[i-3]) << 8 - x |= uint64(p.buf[i-2]) << 16 - x |= uint64(p.buf[i-1]) << 24 - return -} - -// DecodeZigzag64 reads a zigzag-encoded 64-bit integer -// from the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) DecodeZigzag64() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) - return -} - -// DecodeZigzag32 reads a zigzag-encoded 32-bit integer -// from the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) DecodeZigzag32() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) - return -} - -// DecodeRawBytes reads a count-delimited byte buffer from the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { - n, err := p.DecodeVarint() - if err != nil { - return nil, err - } - - nb := int(n) - if nb < 0 { - return nil, fmt.Errorf("proto: bad byte length %d", nb) - } - end := p.index + nb - if end < p.index || end > len(p.buf) { - return nil, io.ErrUnexpectedEOF - } - - if !alloc { - // todo: check if can get more uses of alloc=false - buf = p.buf[p.index:end] - p.index += nb - return - } - - buf = make([]byte, nb) - copy(buf, p.buf[p.index:]) - p.index += nb - return -} - -// DecodeStringBytes reads an encoded string from the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) DecodeStringBytes() (s string, err error) { - buf, err := p.DecodeRawBytes(false) - if err != nil { - return - } - return string(buf), nil -} - -// Unmarshaler is the interface representing objects that can -// unmarshal themselves. The argument points to data that may be -// overwritten, so implementations should not keep references to the -// buffer. -// Unmarshal implementations should not clear the receiver. -// Any unmarshaled data should be merged into the receiver. -// Callers of Unmarshal that do not want to retain existing data -// should Reset the receiver before calling Unmarshal. -type Unmarshaler interface { - Unmarshal([]byte) error -} - -// newUnmarshaler is the interface representing objects that can -// unmarshal themselves. The semantics are identical to Unmarshaler. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newUnmarshaler interface { - XXX_Unmarshal([]byte) error -} - -// Unmarshal parses the protocol buffer representation in buf and places the -// decoded result in pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// Unmarshal resets pb before starting to unmarshal, so any -// existing data in pb is always removed. Use UnmarshalMerge -// to preserve and append to existing data. -func Unmarshal(buf []byte, pb Message) error { - pb.Reset() - if u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// UnmarshalMerge parses the protocol buffer representation in buf and -// writes the decoded result to pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// UnmarshalMerge merges into existing data in pb. -// Most code should use Unmarshal instead. -func UnmarshalMerge(buf []byte, pb Message) error { - if u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// DecodeMessage reads a count-delimited message from the Buffer. -func (p *Buffer) DecodeMessage(pb Message) error { - enc, err := p.DecodeRawBytes(false) - if err != nil { - return err - } - return NewBuffer(enc).Unmarshal(pb) -} - -// DecodeGroup reads a tag-delimited group from the Buffer. -// StartGroup tag is already consumed. This function consumes -// EndGroup tag. -func (p *Buffer) DecodeGroup(pb Message) error { - b := p.buf[p.index:] - x, y := findEndGroup(b) - if x < 0 { - return io.ErrUnexpectedEOF - } - err := Unmarshal(b[:x], pb) - p.index += y - return err -} - -// Unmarshal parses the protocol buffer representation in the -// Buffer and places the decoded result in pb. If the struct -// underlying pb does not match the data in the buffer, the results can be -// unpredictable. -// -// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. -func (p *Buffer) Unmarshal(pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(newUnmarshaler); ok { - err := u.XXX_Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - err := u.Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - - // Slow workaround for messages that aren't Unmarshalers. - // This includes some hand-coded .pb.go files and - // bootstrap protos. - // TODO: fix all of those and then add Unmarshal to - // the Message interface. Then: - // The cast above and code below can be deleted. - // The old unmarshaler can be deleted. - // Clients can call Unmarshal directly (can already do that, actually). - var info InternalMessageInfo - err := info.Unmarshal(pb, p.buf[p.index:]) - p.index = len(p.buf) - return err -} diff --git a/vendor/github.com/golang/protobuf/proto/defaults.go b/vendor/github.com/golang/protobuf/proto/defaults.go new file mode 100644 index 00000000000..d399bf069c3 --- /dev/null +++ b/vendor/github.com/golang/protobuf/proto/defaults.go @@ -0,0 +1,63 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "google.golang.org/protobuf/reflect/protoreflect" +) + +// SetDefaults sets unpopulated scalar fields to their default values. +// Fields within a oneof are not set even if they have a default value. +// SetDefaults is recursively called upon any populated message fields. +func SetDefaults(m Message) { + if m != nil { + setDefaults(MessageReflect(m)) + } +} + +func setDefaults(m protoreflect.Message) { + fds := m.Descriptor().Fields() + for i := 0; i < fds.Len(); i++ { + fd := fds.Get(i) + if !m.Has(fd) { + if fd.HasDefault() && fd.ContainingOneof() == nil { + v := fd.Default() + if fd.Kind() == protoreflect.BytesKind { + v = protoreflect.ValueOf(append([]byte(nil), v.Bytes()...)) // copy the default bytes + } + m.Set(fd, v) + } + continue + } + } + + m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + switch { + // Handle singular message. + case fd.Cardinality() != protoreflect.Repeated: + if fd.Message() != nil { + setDefaults(m.Get(fd).Message()) + } + // Handle list of messages. + case fd.IsList(): + if fd.Message() != nil { + ls := m.Get(fd).List() + for i := 0; i < ls.Len(); i++ { + setDefaults(ls.Get(i).Message()) + } + } + // Handle map of messages. + case fd.IsMap(): + if fd.MapValue().Message() != nil { + ms := m.Get(fd).Map() + ms.Range(func(_ protoreflect.MapKey, v protoreflect.Value) bool { + setDefaults(v.Message()) + return true + }) + } + } + return true + }) +} diff --git a/vendor/github.com/golang/protobuf/proto/deprecated.go b/vendor/github.com/golang/protobuf/proto/deprecated.go index 35b882c09aa..e8db57e097a 100644 --- a/vendor/github.com/golang/protobuf/proto/deprecated.go +++ b/vendor/github.com/golang/protobuf/proto/deprecated.go @@ -1,63 +1,113 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2018 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. package proto -import "errors" +import ( + "encoding/json" + "errors" + "fmt" + "strconv" -// Deprecated: do not use. + protoV2 "google.golang.org/protobuf/proto" +) + +var ( + // Deprecated: No longer returned. + ErrNil = errors.New("proto: Marshal called with nil") + + // Deprecated: No longer returned. + ErrTooLarge = errors.New("proto: message encodes to over 2 GB") + + // Deprecated: No longer returned. + ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") +) + +// Deprecated: Do not use. type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 } -// Deprecated: do not use. +// Deprecated: Do not use. func GetStats() Stats { return Stats{} } -// Deprecated: do not use. +// Deprecated: Do not use. func MarshalMessageSet(interface{}) ([]byte, error) { return nil, errors.New("proto: not implemented") } -// Deprecated: do not use. +// Deprecated: Do not use. func UnmarshalMessageSet([]byte, interface{}) error { return errors.New("proto: not implemented") } -// Deprecated: do not use. +// Deprecated: Do not use. func MarshalMessageSetJSON(interface{}) ([]byte, error) { return nil, errors.New("proto: not implemented") } -// Deprecated: do not use. +// Deprecated: Do not use. func UnmarshalMessageSetJSON([]byte, interface{}) error { return errors.New("proto: not implemented") } -// Deprecated: do not use. +// Deprecated: Do not use. func RegisterMessageSetType(Message, int32, string) {} + +// Deprecated: Do not use. +func EnumName(m map[int32]string, v int32) string { + s, ok := m[v] + if ok { + return s + } + return strconv.Itoa(int(v)) +} + +// Deprecated: Do not use. +func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { + if data[0] == '"' { + // New style: enums are strings. + var repr string + if err := json.Unmarshal(data, &repr); err != nil { + return -1, err + } + val, ok := m[repr] + if !ok { + return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) + } + return val, nil + } + // Old style: enums are ints. + var val int32 + if err := json.Unmarshal(data, &val); err != nil { + return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) + } + return val, nil +} + +// Deprecated: Do not use; this type existed for intenal-use only. +type InternalMessageInfo struct{} + +// Deprecated: Do not use; this method existed for intenal-use only. +func (*InternalMessageInfo) DiscardUnknown(m Message) { + DiscardUnknown(m) +} + +// Deprecated: Do not use; this method existed for intenal-use only. +func (*InternalMessageInfo) Marshal(b []byte, m Message, deterministic bool) ([]byte, error) { + return protoV2.MarshalOptions{Deterministic: deterministic}.MarshalAppend(b, MessageV2(m)) +} + +// Deprecated: Do not use; this method existed for intenal-use only. +func (*InternalMessageInfo) Merge(dst, src Message) { + protoV2.Merge(MessageV2(dst), MessageV2(src)) +} + +// Deprecated: Do not use; this method existed for intenal-use only. +func (*InternalMessageInfo) Size(m Message) int { + return protoV2.Size(MessageV2(m)) +} + +// Deprecated: Do not use; this method existed for intenal-use only. +func (*InternalMessageInfo) Unmarshal(m Message, b []byte) error { + return protoV2.UnmarshalOptions{Merge: true}.Unmarshal(b, MessageV2(m)) +} diff --git a/vendor/github.com/golang/protobuf/proto/discard.go b/vendor/github.com/golang/protobuf/proto/discard.go index dea2617ced3..2187e877fa4 100644 --- a/vendor/github.com/golang/protobuf/proto/discard.go +++ b/vendor/github.com/golang/protobuf/proto/discard.go @@ -1,48 +1,13 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2017 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. package proto import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" + "google.golang.org/protobuf/reflect/protoreflect" ) -type generatedDiscarder interface { - XXX_DiscardUnknown() -} - // DiscardUnknown recursively discards all unknown fields from this message // and all embedded messages. // @@ -51,300 +16,43 @@ type generatedDiscarder interface { // marshal to be able to produce a message that continues to have those // unrecognized fields. To avoid this, DiscardUnknown is used to // explicitly clear the unknown fields after unmarshaling. -// -// For proto2 messages, the unknown fields of message extensions are only -// discarded from messages that have been accessed via GetExtension. func DiscardUnknown(m Message) { - if m, ok := m.(generatedDiscarder); ok { - m.XXX_DiscardUnknown() - return - } - // TODO: Dynamically populate a InternalMessageInfo for legacy messages, - // but the master branch has no implementation for InternalMessageInfo, - // so it would be more work to replicate that approach. - discardLegacy(m) -} - -// DiscardUnknown recursively discards all unknown fields. -func (a *InternalMessageInfo) DiscardUnknown(m Message) { - di := atomicLoadDiscardInfo(&a.discard) - if di == nil { - di = getDiscardInfo(reflect.TypeOf(m).Elem()) - atomicStoreDiscardInfo(&a.discard, di) - } - di.discard(toPointer(&m)) -} - -type discardInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []discardFieldInfo - unrecognized field -} - -type discardFieldInfo struct { - field field // Offset of field, guaranteed to be valid - discard func(src pointer) -} - -var ( - discardInfoMap = map[reflect.Type]*discardInfo{} - discardInfoLock sync.Mutex -) - -func getDiscardInfo(t reflect.Type) *discardInfo { - discardInfoLock.Lock() - defer discardInfoLock.Unlock() - di := discardInfoMap[t] - if di == nil { - di = &discardInfo{typ: t} - discardInfoMap[t] = di + if m != nil { + discardUnknown(MessageReflect(m)) } - return di } -func (di *discardInfo) discard(src pointer) { - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&di.initialized) == 0 { - di.computeDiscardInfo() - } - - for _, fi := range di.fields { - sfp := src.offset(fi.field) - fi.discard(sfp) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil { - // Ignore lock since DiscardUnknown is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - DiscardUnknown(m) +func discardUnknown(m protoreflect.Message) { + m.Range(func(fd protoreflect.FieldDescriptor, val protoreflect.Value) bool { + switch { + // Handle singular message. + case fd.Cardinality() != protoreflect.Repeated: + if fd.Message() != nil { + discardUnknown(m.Get(fd).Message()) } - } - } - - if di.unrecognized.IsValid() { - *src.offset(di.unrecognized).toBytes() = nil - } -} - -func (di *discardInfo) computeDiscardInfo() { - di.lock.Lock() - defer di.lock.Unlock() - if di.initialized != 0 { - return - } - t := di.typ - n := t.NumField() - - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - dfi := discardFieldInfo{field: toField(&f)} - tf := f.Type - - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name)) - case isSlice: // E.g., []*pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sps := src.getPointerSlice() - for _, sp := range sps { - if !sp.isNil() { - di.discard(sp) - } - } - } - default: // E.g., *pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sp := src.getPointer() - if !sp.isNil() { - di.discard(sp) - } + // Handle list of messages. + case fd.IsList(): + if fd.Message() != nil { + ls := m.Get(fd).List() + for i := 0; i < ls.Len(); i++ { + discardUnknown(ls.Get(i).Message()) } } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name)) - default: // E.g., map[K]V - if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T) - dfi.discard = func(src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - DiscardUnknown(val.Interface().(Message)) - } - } - } else { - dfi.discard = func(pointer) {} // Noop - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name)) - default: // E.g., interface{} - // TODO: Make this faster? - dfi.discard = func(src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - DiscardUnknown(sv.Interface().(Message)) - } - } - } + // Handle map of messages. + case fd.IsMap(): + if fd.MapValue().Message() != nil { + ms := m.Get(fd).Map() + ms.Range(func(_ protoreflect.MapKey, v protoreflect.Value) bool { + discardUnknown(v.Message()) + return true + }) } - default: - continue - } - di.fields = append(di.fields, dfi) - } - - di.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - di.unrecognized = toField(&f) - } - - atomic.StoreInt32(&di.initialized, 1) -} - -func discardLegacy(m Message) { - v := reflect.ValueOf(m) - if v.Kind() != reflect.Ptr || v.IsNil() { - return - } - v = v.Elem() - if v.Kind() != reflect.Struct { - return - } - t := v.Type() - - for i := 0; i < v.NumField(); i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue } - vf := v.Field(i) - tf := f.Type + return true + }) - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name)) - case isSlice: // E.g., []*pb.T - for j := 0; j < vf.Len(); j++ { - discardLegacy(vf.Index(j).Interface().(Message)) - } - default: // E.g., *pb.T - discardLegacy(vf.Interface().(Message)) - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name)) - default: // E.g., map[K]V - tv := vf.Type().Elem() - if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T) - for _, key := range vf.MapKeys() { - val := vf.MapIndex(key) - discardLegacy(val.Interface().(Message)) - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name)) - default: // E.g., test_proto.isCommunique_Union interface - if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" { - vf = vf.Elem() // E.g., *test_proto.Communique_Msg - if !vf.IsNil() { - vf = vf.Elem() // E.g., test_proto.Communique_Msg - vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value - if vf.Kind() == reflect.Ptr { - discardLegacy(vf.Interface().(Message)) - } - } - } - } - } - } - - if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() { - if vf.Type() != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - vf.Set(reflect.ValueOf([]byte(nil))) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(m); err == nil { - // Ignore lock since discardLegacy is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - discardLegacy(m) - } - } + // Discard unknown fields. + if len(m.GetUnknown()) > 0 { + m.SetUnknown(nil) } } diff --git a/vendor/github.com/golang/protobuf/proto/encode.go b/vendor/github.com/golang/protobuf/proto/encode.go deleted file mode 100644 index 3abfed2cff0..00000000000 --- a/vendor/github.com/golang/protobuf/proto/encode.go +++ /dev/null @@ -1,203 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "errors" - "reflect" -) - -var ( - // errRepeatedHasNil is the error returned if Marshal is called with - // a struct with a repeated field containing a nil element. - errRepeatedHasNil = errors.New("proto: repeated field has nil element") - - // errOneofHasNil is the error returned if Marshal is called with - // a struct with a oneof field containing a nil element. - errOneofHasNil = errors.New("proto: oneof field has nil value") - - // ErrNil is the error returned if Marshal is called with nil. - ErrNil = errors.New("proto: Marshal called with nil") - - // ErrTooLarge is the error returned if Marshal is called with a - // message that encodes to >2GB. - ErrTooLarge = errors.New("proto: message encodes to over 2 GB") -) - -// The fundamental encoders that put bytes on the wire. -// Those that take integer types all accept uint64 and are -// therefore of type valueEncoder. - -const maxVarintBytes = 10 // maximum length of a varint - -// EncodeVarint returns the varint encoding of x. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -// Not used by the package itself, but helpful to clients -// wishing to use the same encoding. -func EncodeVarint(x uint64) []byte { - var buf [maxVarintBytes]byte - var n int - for n = 0; x > 127; n++ { - buf[n] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - buf[n] = uint8(x) - n++ - return buf[0:n] -} - -// EncodeVarint writes a varint-encoded integer to the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) EncodeVarint(x uint64) error { - for x >= 1<<7 { - p.buf = append(p.buf, uint8(x&0x7f|0x80)) - x >>= 7 - } - p.buf = append(p.buf, uint8(x)) - return nil -} - -// SizeVarint returns the varint encoding size of an integer. -func SizeVarint(x uint64) int { - switch { - case x < 1<<7: - return 1 - case x < 1<<14: - return 2 - case x < 1<<21: - return 3 - case x < 1<<28: - return 4 - case x < 1<<35: - return 5 - case x < 1<<42: - return 6 - case x < 1<<49: - return 7 - case x < 1<<56: - return 8 - case x < 1<<63: - return 9 - } - return 10 -} - -// EncodeFixed64 writes a 64-bit integer to the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) EncodeFixed64(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24), - uint8(x>>32), - uint8(x>>40), - uint8(x>>48), - uint8(x>>56)) - return nil -} - -// EncodeFixed32 writes a 32-bit integer to the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) EncodeFixed32(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24)) - return nil -} - -// EncodeZigzag64 writes a zigzag-encoded 64-bit integer -// to the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) EncodeZigzag64(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -// EncodeZigzag32 writes a zigzag-encoded 32-bit integer -// to the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) EncodeZigzag32(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - -// EncodeRawBytes writes a count-delimited byte buffer to the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) EncodeRawBytes(b []byte) error { - p.EncodeVarint(uint64(len(b))) - p.buf = append(p.buf, b...) - return nil -} - -// EncodeStringBytes writes an encoded string to the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) EncodeStringBytes(s string) error { - p.EncodeVarint(uint64(len(s))) - p.buf = append(p.buf, s...) - return nil -} - -// Marshaler is the interface representing objects that can marshal themselves. -type Marshaler interface { - Marshal() ([]byte, error) -} - -// EncodeMessage writes the protocol buffer to the Buffer, -// prefixed by a varint-encoded length. -func (p *Buffer) EncodeMessage(pb Message) error { - siz := Size(pb) - p.EncodeVarint(uint64(siz)) - return p.Marshal(pb) -} - -// All protocol buffer fields are nillable, but be careful. -func isNil(v reflect.Value) bool { - switch v.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - return false -} diff --git a/vendor/github.com/golang/protobuf/proto/equal.go b/vendor/github.com/golang/protobuf/proto/equal.go deleted file mode 100644 index f9b6e41b3c1..00000000000 --- a/vendor/github.com/golang/protobuf/proto/equal.go +++ /dev/null @@ -1,301 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Protocol buffer comparison. - -package proto - -import ( - "bytes" - "log" - "reflect" - "strings" -) - -/* -Equal returns true iff protocol buffers a and b are equal. -The arguments must both be pointers to protocol buffer structs. - -Equality is defined in this way: - - Two messages are equal iff they are the same type, - corresponding fields are equal, unknown field sets - are equal, and extensions sets are equal. - - Two set scalar fields are equal iff their values are equal. - If the fields are of a floating-point type, remember that - NaN != x for all x, including NaN. If the message is defined - in a proto3 .proto file, fields are not "set"; specifically, - zero length proto3 "bytes" fields are equal (nil == {}). - - Two repeated fields are equal iff their lengths are the same, - and their corresponding elements are equal. Note a "bytes" field, - although represented by []byte, is not a repeated field and the - rule for the scalar fields described above applies. - - Two unset fields are equal. - - Two unknown field sets are equal if their current - encoded state is equal. - - Two extension sets are equal iff they have corresponding - elements that are pairwise equal. - - Two map fields are equal iff their lengths are the same, - and they contain the same set of elements. Zero-length map - fields are equal. - - Every other combination of things are not equal. - -The return value is undefined if a and b are not protocol buffers. -*/ -func Equal(a, b Message) bool { - if a == nil || b == nil { - return a == b - } - v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) - if v1.Type() != v2.Type() { - return false - } - if v1.Kind() == reflect.Ptr { - if v1.IsNil() { - return v2.IsNil() - } - if v2.IsNil() { - return false - } - v1, v2 = v1.Elem(), v2.Elem() - } - if v1.Kind() != reflect.Struct { - return false - } - return equalStruct(v1, v2) -} - -// v1 and v2 are known to have the same type. -func equalStruct(v1, v2 reflect.Value) bool { - sprop := GetProperties(v1.Type()) - for i := 0; i < v1.NumField(); i++ { - f := v1.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - f1, f2 := v1.Field(i), v2.Field(i) - if f.Type.Kind() == reflect.Ptr { - if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { - // both unset - continue - } else if n1 != n2 { - // set/unset mismatch - return false - } - f1, f2 = f1.Elem(), f2.Elem() - } - if !equalAny(f1, f2, sprop.Prop[i]) { - return false - } - } - - if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_InternalExtensions") - if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { - return false - } - } - - if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_extensions") - if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { - return false - } - } - - uf := v1.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return true - } - - u1 := uf.Bytes() - u2 := v2.FieldByName("XXX_unrecognized").Bytes() - return bytes.Equal(u1, u2) -} - -// v1 and v2 are known to have the same type. -// prop may be nil. -func equalAny(v1, v2 reflect.Value, prop *Properties) bool { - if v1.Type() == protoMessageType { - m1, _ := v1.Interface().(Message) - m2, _ := v2.Interface().(Message) - return Equal(m1, m2) - } - switch v1.Kind() { - case reflect.Bool: - return v1.Bool() == v2.Bool() - case reflect.Float32, reflect.Float64: - return v1.Float() == v2.Float() - case reflect.Int32, reflect.Int64: - return v1.Int() == v2.Int() - case reflect.Interface: - // Probably a oneof field; compare the inner values. - n1, n2 := v1.IsNil(), v2.IsNil() - if n1 || n2 { - return n1 == n2 - } - e1, e2 := v1.Elem(), v2.Elem() - if e1.Type() != e2.Type() { - return false - } - return equalAny(e1, e2, nil) - case reflect.Map: - if v1.Len() != v2.Len() { - return false - } - for _, key := range v1.MapKeys() { - val2 := v2.MapIndex(key) - if !val2.IsValid() { - // This key was not found in the second map. - return false - } - if !equalAny(v1.MapIndex(key), val2, nil) { - return false - } - } - return true - case reflect.Ptr: - // Maps may have nil values in them, so check for nil. - if v1.IsNil() && v2.IsNil() { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return equalAny(v1.Elem(), v2.Elem(), prop) - case reflect.Slice: - if v1.Type().Elem().Kind() == reflect.Uint8 { - // short circuit: []byte - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value. - if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) - } - - if v1.Len() != v2.Len() { - return false - } - for i := 0; i < v1.Len(); i++ { - if !equalAny(v1.Index(i), v2.Index(i), prop) { - return false - } - } - return true - case reflect.String: - return v1.Interface().(string) == v2.Interface().(string) - case reflect.Struct: - return equalStruct(v1, v2) - case reflect.Uint32, reflect.Uint64: - return v1.Uint() == v2.Uint() - } - - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to compare %v", v1) - return false -} - -// base is the struct type that the extensions are based on. -// x1 and x2 are InternalExtensions. -func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { - em1, _ := x1.extensionsRead() - em2, _ := x2.extensionsRead() - return equalExtMap(base, em1, em2) -} - -func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { - if len(em1) != len(em2) { - return false - } - - for extNum, e1 := range em1 { - e2, ok := em2[extNum] - if !ok { - return false - } - - m1 := extensionAsLegacyType(e1.value) - m2 := extensionAsLegacyType(e2.value) - - if m1 == nil && m2 == nil { - // Both have only encoded form. - if bytes.Equal(e1.enc, e2.enc) { - continue - } - // The bytes are different, but the extensions might still be - // equal. We need to decode them to compare. - } - - if m1 != nil && m2 != nil { - // Both are unencoded. - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - continue - } - - // At least one is encoded. To do a semantically correct comparison - // we need to unmarshal them first. - var desc *ExtensionDesc - if m := extensionMaps[base]; m != nil { - desc = m[extNum] - } - if desc == nil { - // If both have only encoded form and the bytes are the same, - // it is handled above. We get here when the bytes are different. - // We don't know how to decode it, so just compare them as byte - // slices. - log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) - return false - } - var err error - if m1 == nil { - m1, err = decodeExtension(e1.enc, desc) - } - if m2 == nil && err == nil { - m2, err = decodeExtension(e2.enc, desc) - } - if err != nil { - // The encoded form is invalid. - log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) - return false - } - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - } - - return true -} diff --git a/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/golang/protobuf/proto/extensions.go index fa88add30a4..42fc120c972 100644 --- a/vendor/github.com/golang/protobuf/proto/extensions.go +++ b/vendor/github.com/golang/protobuf/proto/extensions.go @@ -1,607 +1,356 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. package proto -/* - * Types and routines for supporting protocol buffer extensions. - */ - import ( "errors" "fmt" - "io" "reflect" - "strconv" - "sync" -) - -// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. -var ErrMissingExtension = errors.New("proto: missing extension") - -// ExtensionRange represents a range of message extensions for a protocol buffer. -// Used in code generated by the protocol compiler. -type ExtensionRange struct { - Start, End int32 // both inclusive -} - -// extendableProto is an interface implemented by any protocol buffer generated by the current -// proto compiler that may be extended. -type extendableProto interface { - Message - ExtensionRangeArray() []ExtensionRange - extensionsWrite() map[int32]Extension - extensionsRead() (map[int32]Extension, sync.Locker) -} - -// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous -// version of the proto compiler that may be extended. -type extendableProtoV1 interface { - Message - ExtensionRangeArray() []ExtensionRange - ExtensionMap() map[int32]Extension -} -// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto. -type extensionAdapter struct { - extendableProtoV1 -} + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + "google.golang.org/protobuf/runtime/protoiface" + "google.golang.org/protobuf/runtime/protoimpl" +) -func (e extensionAdapter) extensionsWrite() map[int32]Extension { - return e.ExtensionMap() -} +type ( + // ExtensionDesc represents an extension descriptor and + // is used to interact with an extension field in a message. + // + // Variables of this type are generated in code by protoc-gen-go. + ExtensionDesc = protoimpl.ExtensionInfo -func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { - return e.ExtensionMap(), notLocker{} -} + // ExtensionRange represents a range of message extensions. + // Used in code generated by protoc-gen-go. + ExtensionRange = protoiface.ExtensionRangeV1 -// notLocker is a sync.Locker whose Lock and Unlock methods are nops. -type notLocker struct{} + // Deprecated: Do not use; this is an internal type. + Extension = protoimpl.ExtensionFieldV1 -func (n notLocker) Lock() {} -func (n notLocker) Unlock() {} + // Deprecated: Do not use; this is an internal type. + XXX_InternalExtensions = protoimpl.ExtensionFields +) -// extendable returns the extendableProto interface for the given generated proto message. -// If the proto message has the old extension format, it returns a wrapper that implements -// the extendableProto interface. -func extendable(p interface{}) (extendableProto, error) { - switch p := p.(type) { - case extendableProto: - if isNilPtr(p) { - return nil, fmt.Errorf("proto: nil %T is not extendable", p) - } - return p, nil - case extendableProtoV1: - if isNilPtr(p) { - return nil, fmt.Errorf("proto: nil %T is not extendable", p) - } - return extensionAdapter{p}, nil - } - // Don't allocate a specific error containing %T: - // this is the hot path for Clone and MarshalText. - return nil, errNotExtendable -} +// ErrMissingExtension reports whether the extension was not present. +var ErrMissingExtension = errors.New("proto: missing extension") var errNotExtendable = errors.New("proto: not an extendable proto.Message") -func isNilPtr(x interface{}) bool { - v := reflect.ValueOf(x) - return v.Kind() == reflect.Ptr && v.IsNil() -} - -// XXX_InternalExtensions is an internal representation of proto extensions. -// -// Each generated message struct type embeds an anonymous XXX_InternalExtensions field, -// thus gaining the unexported 'extensions' method, which can be called only from the proto package. -// -// The methods of XXX_InternalExtensions are not concurrency safe in general, -// but calls to logically read-only methods such as has and get may be executed concurrently. -type XXX_InternalExtensions struct { - // The struct must be indirect so that if a user inadvertently copies a - // generated message and its embedded XXX_InternalExtensions, they - // avoid the mayhem of a copied mutex. - // - // The mutex serializes all logically read-only operations to p.extensionMap. - // It is up to the client to ensure that write operations to p.extensionMap are - // mutually exclusive with other accesses. - p *struct { - mu sync.Mutex - extensionMap map[int32]Extension +// HasExtension reports whether the extension field is present in m +// either as an explicitly populated field or as an unknown field. +func HasExtension(m Message, xt *ExtensionDesc) (has bool) { + mr := MessageReflect(m) + if mr == nil || !mr.IsValid() { + return false } -} -// extensionsWrite returns the extension map, creating it on first use. -func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension { - if e.p == nil { - e.p = new(struct { - mu sync.Mutex - extensionMap map[int32]Extension + // Check whether any populated known field matches the field number. + xtd := xt.TypeDescriptor() + if isValidExtension(mr.Descriptor(), xtd) { + has = mr.Has(xtd) + } else { + mr.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { + has = int32(fd.Number()) == xt.Field + return !has }) - e.p.extensionMap = make(map[int32]Extension) } - return e.p.extensionMap -} -// extensionsRead returns the extensions map for read-only use. It may be nil. -// The caller must hold the returned mutex's lock when accessing Elements within the map. -func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) { - if e.p == nil { - return nil, nil + // Check whether any unknown field matches the field number. + for b := mr.GetUnknown(); !has && len(b) > 0; { + num, _, n := protowire.ConsumeField(b) + has = int32(num) == xt.Field + b = b[n:] } - return e.p.extensionMap, &e.p.mu -} - -// ExtensionDesc represents an extension specification. -// Used in generated code from the protocol compiler. -type ExtensionDesc struct { - ExtendedType Message // nil pointer to the type that is being extended - ExtensionType interface{} // nil pointer to the extension type - Field int32 // field number - Name string // fully-qualified name of extension, for text formatting - Tag string // protobuf tag style - Filename string // name of the file in which the extension is defined -} - -func (ed *ExtensionDesc) repeated() bool { - t := reflect.TypeOf(ed.ExtensionType) - return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 -} - -// Extension represents an extension in a message. -type Extension struct { - // When an extension is stored in a message using SetExtension - // only desc and value are set. When the message is marshaled - // enc will be set to the encoded form of the message. - // - // When a message is unmarshaled and contains extensions, each - // extension will have only enc set. When such an extension is - // accessed using GetExtension (or GetExtensions) desc and value - // will be set. - desc *ExtensionDesc - - // value is a concrete value for the extension field. Let the type of - // desc.ExtensionType be the "API type" and the type of Extension.value - // be the "storage type". The API type and storage type are the same except: - // * For scalars (except []byte), the API type uses *T, - // while the storage type uses T. - // * For repeated fields, the API type uses []T, while the storage type - // uses *[]T. - // - // The reason for the divergence is so that the storage type more naturally - // matches what is expected of when retrieving the values through the - // protobuf reflection APIs. - // - // The value may only be populated if desc is also populated. - value interface{} - - // enc is the raw bytes for the extension field. - enc []byte + return has } -// SetRawExtension is for testing only. -func SetRawExtension(base Message, id int32, b []byte) { - epb, err := extendable(base) - if err != nil { +// ClearExtension removes the extension field from m +// either as an explicitly populated field or as an unknown field. +func ClearExtension(m Message, xt *ExtensionDesc) { + mr := MessageReflect(m) + if mr == nil || !mr.IsValid() { return } - extmap := epb.extensionsWrite() - extmap[id] = Extension{enc: b} -} -// isExtensionField returns true iff the given field number is in an extension range. -func isExtensionField(pb extendableProto, field int32) bool { - for _, er := range pb.ExtensionRangeArray() { - if er.Start <= field && field <= er.End { + xtd := xt.TypeDescriptor() + if isValidExtension(mr.Descriptor(), xtd) { + mr.Clear(xtd) + } else { + mr.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { + if int32(fd.Number()) == xt.Field { + mr.Clear(fd) + return false + } return true - } - } - return false -} - -// checkExtensionTypes checks that the given extension is valid for pb. -func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { - var pbi interface{} = pb - // Check the extended type. - if ea, ok := pbi.(extensionAdapter); ok { - pbi = ea.extendableProtoV1 - } - if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b { - return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a) - } - // Check the range. - if !isExtensionField(pb, extension.Field) { - return errors.New("proto: bad extension number; not in declared ranges") - } - return nil -} - -// extPropKey is sufficient to uniquely identify an extension. -type extPropKey struct { - base reflect.Type - field int32 -} - -var extProp = struct { - sync.RWMutex - m map[extPropKey]*Properties -}{ - m: make(map[extPropKey]*Properties), -} - -func extensionProperties(ed *ExtensionDesc) *Properties { - key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field} - - extProp.RLock() - if prop, ok := extProp.m[key]; ok { - extProp.RUnlock() - return prop - } - extProp.RUnlock() - - extProp.Lock() - defer extProp.Unlock() - // Check again. - if prop, ok := extProp.m[key]; ok { - return prop - } - - prop := new(Properties) - prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil) - extProp.m[key] = prop - return prop -} - -// HasExtension returns whether the given extension is present in pb. -func HasExtension(pb Message, extension *ExtensionDesc) bool { - // TODO: Check types, field numbers, etc.? - epb, err := extendable(pb) - if err != nil { - return false - } - extmap, mu := epb.extensionsRead() - if extmap == nil { - return false + }) } - mu.Lock() - _, ok := extmap[extension.Field] - mu.Unlock() - return ok + clearUnknown(mr, fieldNum(xt.Field)) } -// ClearExtension removes the given extension from pb. -func ClearExtension(pb Message, extension *ExtensionDesc) { - epb, err := extendable(pb) - if err != nil { +// ClearAllExtensions clears all extensions from m. +// This includes populated fields and unknown fields in the extension range. +func ClearAllExtensions(m Message) { + mr := MessageReflect(m) + if mr == nil || !mr.IsValid() { return } - // TODO: Check types, field numbers, etc.? - extmap := epb.extensionsWrite() - delete(extmap, extension.Field) + + mr.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { + if fd.IsExtension() { + mr.Clear(fd) + } + return true + }) + clearUnknown(mr, mr.Descriptor().ExtensionRanges()) } -// GetExtension retrieves a proto2 extended field from pb. +// GetExtension retrieves a proto2 extended field from m. // // If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil), // then GetExtension parses the encoded field and returns a Go value of the specified type. // If the field is not present, then the default value is returned (if one is specified), // otherwise ErrMissingExtension is reported. // -// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil), -// then GetExtension returns the raw encoded bytes of the field extension. -func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - - if extension.ExtendedType != nil { - // can only check type if this is a complete descriptor - if err := checkExtensionTypes(epb, extension); err != nil { - return nil, err +// If the descriptor is type incomplete (i.e., ExtensionDesc.ExtensionType is nil), +// then GetExtension returns the raw encoded bytes for the extension field. +func GetExtension(m Message, xt *ExtensionDesc) (interface{}, error) { + mr := MessageReflect(m) + if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 { + return nil, errNotExtendable + } + + // Retrieve the unknown fields for this extension field. + var bo protoreflect.RawFields + for bi := mr.GetUnknown(); len(bi) > 0; { + num, _, n := protowire.ConsumeField(bi) + if int32(num) == xt.Field { + bo = append(bo, bi[:n]...) } + bi = bi[n:] } - emap, mu := epb.extensionsRead() - if emap == nil { - return defaultExtensionValue(extension) - } - mu.Lock() - defer mu.Unlock() - e, ok := emap[extension.Field] - if !ok { - // defaultExtensionValue returns the default value or - // ErrMissingExtension if there is no default. - return defaultExtensionValue(extension) - } - - if e.value != nil { - // Already decoded. Check the descriptor, though. - if e.desc != extension { - // This shouldn't happen. If it does, it means that - // GetExtension was called twice with two different - // descriptors with the same field number. - return nil, errors.New("proto: descriptor conflict") - } - return extensionAsLegacyType(e.value), nil + // For type incomplete descriptors, only retrieve the unknown fields. + if xt.ExtensionType == nil { + return []byte(bo), nil } - if extension.ExtensionType == nil { - // incomplete descriptor - return e.enc, nil + // If the extension field only exists as unknown fields, unmarshal it. + // This is rarely done since proto.Unmarshal eagerly unmarshals extensions. + xtd := xt.TypeDescriptor() + if !isValidExtension(mr.Descriptor(), xtd) { + return nil, fmt.Errorf("proto: bad extended type; %T does not extend %T", xt.ExtendedType, m) } - - v, err := decodeExtension(e.enc, extension) - if err != nil { - return nil, err + if !mr.Has(xtd) && len(bo) > 0 { + m2 := mr.New() + if err := (proto.UnmarshalOptions{ + Resolver: extensionResolver{xt}, + }.Unmarshal(bo, m2.Interface())); err != nil { + return nil, err + } + if m2.Has(xtd) { + mr.Set(xtd, m2.Get(xtd)) + clearUnknown(mr, fieldNum(xt.Field)) + } } - // Remember the decoded version and drop the encoded version. - // That way it is safe to mutate what we return. - e.value = extensionAsStorageType(v) - e.desc = extension - e.enc = nil - emap[extension.Field] = e - return extensionAsLegacyType(e.value), nil -} - -// defaultExtensionValue returns the default value for extension. -// If no default for an extension is defined ErrMissingExtension is returned. -func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { - if extension.ExtensionType == nil { - // incomplete descriptor, so no default + // Check whether the message has the extension field set or a default. + var pv protoreflect.Value + switch { + case mr.Has(xtd): + pv = mr.Get(xtd) + case xtd.HasDefault(): + pv = xtd.Default() + default: return nil, ErrMissingExtension } - t := reflect.TypeOf(extension.ExtensionType) - props := extensionProperties(extension) - - sf, _, err := fieldDefault(t, props) - if err != nil { - return nil, err - } - - if sf == nil || sf.value == nil { - // There is no default value. - return nil, ErrMissingExtension + v := xt.InterfaceOf(pv) + rv := reflect.ValueOf(v) + if isScalarKind(rv.Kind()) { + rv2 := reflect.New(rv.Type()) + rv2.Elem().Set(rv) + v = rv2.Interface() } + return v, nil +} - if t.Kind() != reflect.Ptr { - // We do not need to return a Ptr, we can directly return sf.value. - return sf.value, nil - } +// extensionResolver is a custom extension resolver that stores a single +// extension type that takes precedence over the global registry. +type extensionResolver struct{ xt protoreflect.ExtensionType } - // We need to return an interface{} that is a pointer to sf.value. - value := reflect.New(t).Elem() - value.Set(reflect.New(value.Type().Elem())) - if sf.kind == reflect.Int32 { - // We may have an int32 or an enum, but the underlying data is int32. - // Since we can't set an int32 into a non int32 reflect.value directly - // set it as a int32. - value.Elem().SetInt(int64(sf.value.(int32))) - } else { - value.Elem().Set(reflect.ValueOf(sf.value)) +func (r extensionResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) { + if xtd := r.xt.TypeDescriptor(); xtd.FullName() == field { + return r.xt, nil } - return value.Interface(), nil + return protoregistry.GlobalTypes.FindExtensionByName(field) } -// decodeExtension decodes an extension encoded in b. -func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { - t := reflect.TypeOf(extension.ExtensionType) - unmarshal := typeUnmarshaler(t, extension.Tag) - - // t is a pointer to a struct, pointer to basic type or a slice. - // Allocate space to store the pointer/slice. - value := reflect.New(t).Elem() - - var err error - for { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - wire := int(x) & 7 - - b, err = unmarshal(b, valToPointer(value.Addr()), wire) - if err != nil { - return nil, err - } - - if len(b) == 0 { - break - } +func (r extensionResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) { + if xtd := r.xt.TypeDescriptor(); xtd.ContainingMessage().FullName() == message && xtd.Number() == field { + return r.xt, nil } - return value.Interface(), nil + return protoregistry.GlobalTypes.FindExtensionByNumber(message, field) } -// GetExtensions returns a slice of the extensions present in pb that are also listed in es. -// The returned slice has the same length as es; missing extensions will appear as nil elements. -func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { - epb, err := extendable(pb) - if err != nil { - return nil, err +// GetExtensions returns a list of the extensions values present in m, +// corresponding with the provided list of extension descriptors, xts. +// If an extension is missing in m, the corresponding value is nil. +func GetExtensions(m Message, xts []*ExtensionDesc) ([]interface{}, error) { + mr := MessageReflect(m) + if mr == nil || !mr.IsValid() { + return nil, errNotExtendable } - extensions = make([]interface{}, len(es)) - for i, e := range es { - extensions[i], err = GetExtension(epb, e) - if err == ErrMissingExtension { - err = nil - } + + vs := make([]interface{}, len(xts)) + for i, xt := range xts { + v, err := GetExtension(m, xt) if err != nil { - return + if err == ErrMissingExtension { + continue + } + return vs, err } + vs[i] = v } - return + return vs, nil } -// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. -// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing -// just the Field field, which defines the extension's field number. -func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { - epb, err := extendable(pb) - if err != nil { - return nil, err +// SetExtension sets an extension field in m to the provided value. +func SetExtension(m Message, xt *ExtensionDesc, v interface{}) error { + mr := MessageReflect(m) + if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 { + return errNotExtendable } - registeredExtensions := RegisteredExtensions(pb) - emap, mu := epb.extensionsRead() - if emap == nil { - return nil, nil + rv := reflect.ValueOf(v) + if reflect.TypeOf(v) != reflect.TypeOf(xt.ExtensionType) { + return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", v, xt.ExtensionType) } - mu.Lock() - defer mu.Unlock() - extensions := make([]*ExtensionDesc, 0, len(emap)) - for extid, e := range emap { - desc := e.desc - if desc == nil { - desc = registeredExtensions[extid] - if desc == nil { - desc = &ExtensionDesc{Field: extid} - } + if rv.Kind() == reflect.Ptr { + if rv.IsNil() { + return fmt.Errorf("proto: SetExtension called with nil value of type %T", v) + } + if isScalarKind(rv.Elem().Kind()) { + v = rv.Elem().Interface() } - - extensions = append(extensions, desc) } - return extensions, nil -} -// SetExtension sets the specified extension of pb to the specified value. -func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { - epb, err := extendable(pb) - if err != nil { - return err - } - if err := checkExtensionTypes(epb, extension); err != nil { - return err - } - typ := reflect.TypeOf(extension.ExtensionType) - if typ != reflect.TypeOf(value) { - return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", value, extension.ExtensionType) + xtd := xt.TypeDescriptor() + if !isValidExtension(mr.Descriptor(), xtd) { + return fmt.Errorf("proto: bad extended type; %T does not extend %T", xt.ExtendedType, m) } - // nil extension values need to be caught early, because the - // encoder can't distinguish an ErrNil due to a nil extension - // from an ErrNil due to a missing field. Extensions are - // always optional, so the encoder would just swallow the error - // and drop all the extensions from the encoded message. - if reflect.ValueOf(value).IsNil() { - return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) - } - - extmap := epb.extensionsWrite() - extmap[extension.Field] = Extension{desc: extension, value: extensionAsStorageType(value)} + mr.Set(xtd, xt.ValueOf(v)) + clearUnknown(mr, fieldNum(xt.Field)) return nil } -// ClearAllExtensions clears all extensions from pb. -func ClearAllExtensions(pb Message) { - epb, err := extendable(pb) - if err != nil { +// SetRawExtension inserts b into the unknown fields of m. +// +// Deprecated: Use Message.ProtoReflect.SetUnknown instead. +func SetRawExtension(m Message, fnum int32, b []byte) { + mr := MessageReflect(m) + if mr == nil || !mr.IsValid() { return } - m := epb.extensionsWrite() - for k := range m { - delete(m, k) + + // Verify that the raw field is valid. + for b0 := b; len(b0) > 0; { + num, _, n := protowire.ConsumeField(b0) + if int32(num) != fnum { + panic(fmt.Sprintf("mismatching field number: got %d, want %d", num, fnum)) + } + b0 = b0[n:] } -} -// A global registry of extensions. -// The generated code will register the generated descriptors by calling RegisterExtension. + ClearExtension(m, &ExtensionDesc{Field: fnum}) + mr.SetUnknown(append(mr.GetUnknown(), b...)) +} -var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) +// ExtensionDescs returns a list of extension descriptors found in m, +// containing descriptors for both populated extension fields in m and +// also unknown fields of m that are in the extension range. +// For the later case, an type incomplete descriptor is provided where only +// the ExtensionDesc.Field field is populated. +// The order of the extension descriptors is undefined. +func ExtensionDescs(m Message) ([]*ExtensionDesc, error) { + mr := MessageReflect(m) + if mr == nil || !mr.IsValid() || mr.Descriptor().ExtensionRanges().Len() == 0 { + return nil, errNotExtendable + } -// RegisterExtension is called from the generated code. -func RegisterExtension(desc *ExtensionDesc) { - st := reflect.TypeOf(desc.ExtendedType).Elem() - m := extensionMaps[st] - if m == nil { - m = make(map[int32]*ExtensionDesc) - extensionMaps[st] = m + // Collect a set of known extension descriptors. + extDescs := make(map[protoreflect.FieldNumber]*ExtensionDesc) + mr.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + if fd.IsExtension() { + xt := fd.(protoreflect.ExtensionTypeDescriptor) + if xd, ok := xt.Type().(*ExtensionDesc); ok { + extDescs[fd.Number()] = xd + } + } + return true + }) + + // Collect a set of unknown extension descriptors. + extRanges := mr.Descriptor().ExtensionRanges() + for b := mr.GetUnknown(); len(b) > 0; { + num, _, n := protowire.ConsumeField(b) + if extRanges.Has(num) && extDescs[num] == nil { + extDescs[num] = nil + } + b = b[n:] } - if _, ok := m[desc.Field]; ok { - panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) + + // Transpose the set of descriptors into a list. + var xts []*ExtensionDesc + for num, xt := range extDescs { + if xt == nil { + xt = &ExtensionDesc{Field: int32(num)} + } + xts = append(xts, xt) } - m[desc.Field] = desc + return xts, nil } -// RegisteredExtensions returns a map of the registered extensions of a -// protocol buffer struct, indexed by the extension number. -// The argument pb should be a nil pointer to the struct type. -func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { - return extensionMaps[reflect.TypeOf(pb).Elem()] +// isValidExtension reports whether xtd is a valid extension descriptor for md. +func isValidExtension(md protoreflect.MessageDescriptor, xtd protoreflect.ExtensionTypeDescriptor) bool { + return xtd.ContainingMessage() == md && md.ExtensionRanges().Has(xtd.Number()) } -// extensionAsLegacyType converts an value in the storage type as the API type. -// See Extension.value. -func extensionAsLegacyType(v interface{}) interface{} { - switch rv := reflect.ValueOf(v); rv.Kind() { +// isScalarKind reports whether k is a protobuf scalar kind (except bytes). +// This function exists for historical reasons since the representation of +// scalars differs between v1 and v2, where v1 uses *T and v2 uses T. +func isScalarKind(k reflect.Kind) bool { + switch k { case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: - // Represent primitive types as a pointer to the value. - rv2 := reflect.New(rv.Type()) - rv2.Elem().Set(rv) - v = rv2.Interface() - case reflect.Ptr: - // Represent slice types as the value itself. - switch rv.Type().Elem().Kind() { - case reflect.Slice: - if rv.IsNil() { - v = reflect.Zero(rv.Type().Elem()).Interface() - } else { - v = rv.Elem().Interface() - } - } + return true + default: + return false } - return v } -// extensionAsStorageType converts an value in the API type as the storage type. -// See Extension.value. -func extensionAsStorageType(v interface{}) interface{} { - switch rv := reflect.ValueOf(v); rv.Kind() { - case reflect.Ptr: - // Represent slice types as the value itself. - switch rv.Type().Elem().Kind() { - case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: - if rv.IsNil() { - v = reflect.Zero(rv.Type().Elem()).Interface() - } else { - v = rv.Elem().Interface() - } - } - case reflect.Slice: - // Represent slice types as a pointer to the value. - if rv.Type().Elem().Kind() != reflect.Uint8 { - rv2 := reflect.New(rv.Type()) - rv2.Elem().Set(rv) - v = rv2.Interface() +// clearUnknown removes unknown fields from m where remover.Has reports true. +func clearUnknown(m protoreflect.Message, remover interface { + Has(protoreflect.FieldNumber) bool +}) { + var bo protoreflect.RawFields + for bi := m.GetUnknown(); len(bi) > 0; { + num, _, n := protowire.ConsumeField(bi) + if !remover.Has(num) { + bo = append(bo, bi[:n]...) } + bi = bi[n:] } - return v + if bi := m.GetUnknown(); len(bi) != len(bo) { + m.SetUnknown(bo) + } +} + +type fieldNum protoreflect.FieldNumber + +func (n1 fieldNum) Has(n2 protoreflect.FieldNumber) bool { + return protoreflect.FieldNumber(n1) == n2 } diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go deleted file mode 100644 index 70fbda5329c..00000000000 --- a/vendor/github.com/golang/protobuf/proto/lib.go +++ /dev/null @@ -1,965 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* -Package proto converts data structures to and from the wire format of -protocol buffers. It works in concert with the Go source code generated -for .proto files by the protocol compiler. - -A summary of the properties of the protocol buffer interface -for a protocol buffer variable v: - - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed by the enclosing message's name, or by the - enum's type name if it is a top-level enum. Enum types have a String - method, and a Enum method to assist in message construction. - - Nested messages, groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Oneof field sets are given a single field in their message, - with distinguished wrapper types for each possible field value. - - Marshal and Unmarshal are functions to encode and decode the wire format. - -When the .proto file specifies `syntax="proto3"`, there are some differences: - - - Non-repeated fields of non-message type are values instead of pointers. - - Enum types do not get an Enum method. - -The simplest way to describe this is to see an example. -Given file test.proto, containing - - package example; - - enum FOO { X = 17; } - - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } - oneof union { - int32 number = 6; - string name = 7; - } - } - -The resulting file, test.pb.go, is: - - package example - - import proto "github.com/golang/protobuf/proto" - import math "math" - - type FOO int32 - const ( - FOO_X FOO = 17 - ) - var FOO_name = map[int32]string{ - 17: "X", - } - var FOO_value = map[string]int32{ - "X": 17, - } - - func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p - } - func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) - } - func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data) - if err != nil { - return err - } - *x = FOO(value) - return nil - } - - type Test struct { - Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` - Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` - Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` - Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - // Types that are valid to be assigned to Union: - // *Test_Number - // *Test_Name - Union isTest_Union `protobuf_oneof:"union"` - XXX_unrecognized []byte `json:"-"` - } - func (m *Test) Reset() { *m = Test{} } - func (m *Test) String() string { return proto.CompactTextString(m) } - func (*Test) ProtoMessage() {} - - type isTest_Union interface { - isTest_Union() - } - - type Test_Number struct { - Number int32 `protobuf:"varint,6,opt,name=number"` - } - type Test_Name struct { - Name string `protobuf:"bytes,7,opt,name=name"` - } - - func (*Test_Number) isTest_Union() {} - func (*Test_Name) isTest_Union() {} - - func (m *Test) GetUnion() isTest_Union { - if m != nil { - return m.Union - } - return nil - } - const Default_Test_Type int32 = 77 - - func (m *Test) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" - } - - func (m *Test) GetType() int32 { - if m != nil && m.Type != nil { - return *m.Type - } - return Default_Test_Type - } - - func (m *Test) GetOptionalgroup() *Test_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil - } - - type Test_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` - } - func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } - func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } - - func (m *Test_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" - } - - func (m *Test) GetNumber() int32 { - if x, ok := m.GetUnion().(*Test_Number); ok { - return x.Number - } - return 0 - } - - func (m *Test) GetName() string { - if x, ok := m.GetUnion().(*Test_Name); ok { - return x.Name - } - return "" - } - - func init() { - proto.RegisterEnum("example.FOO", FOO_name, FOO_value) - } - -To create and play with a Test object: - - package main - - import ( - "log" - - "github.com/golang/protobuf/proto" - pb "./example.pb" - ) - - func main() { - test := &pb.Test{ - Label: proto.String("hello"), - Type: proto.Int32(17), - Reps: []int64{1, 2, 3}, - Optionalgroup: &pb.Test_OptionalGroup{ - RequiredField: proto.String("good bye"), - }, - Union: &pb.Test_Name{"fred"}, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := &pb.Test{} - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // Use a type switch to determine which oneof was set. - switch u := test.Union.(type) { - case *pb.Test_Number: // u.Number contains the number. - case *pb.Test_Name: // u.Name contains the string. - } - // etc. - } -*/ -package proto - -import ( - "encoding/json" - "fmt" - "log" - "reflect" - "sort" - "strconv" - "sync" -) - -// RequiredNotSetError is an error type returned by either Marshal or Unmarshal. -// Marshal reports this when a required field is not initialized. -// Unmarshal reports this when a required field is missing from the wire data. -type RequiredNotSetError struct{ field string } - -func (e *RequiredNotSetError) Error() string { - if e.field == "" { - return fmt.Sprintf("proto: required field not set") - } - return fmt.Sprintf("proto: required field %q not set", e.field) -} -func (e *RequiredNotSetError) RequiredNotSet() bool { - return true -} - -type invalidUTF8Error struct{ field string } - -func (e *invalidUTF8Error) Error() string { - if e.field == "" { - return "proto: invalid UTF-8 detected" - } - return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field) -} -func (e *invalidUTF8Error) InvalidUTF8() bool { - return true -} - -// errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8. -// This error should not be exposed to the external API as such errors should -// be recreated with the field information. -var errInvalidUTF8 = &invalidUTF8Error{} - -// isNonFatal reports whether the error is either a RequiredNotSet error -// or a InvalidUTF8 error. -func isNonFatal(err error) bool { - if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() { - return true - } - if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() { - return true - } - return false -} - -type nonFatal struct{ E error } - -// Merge merges err into nf and reports whether it was successful. -// Otherwise it returns false for any fatal non-nil errors. -func (nf *nonFatal) Merge(err error) (ok bool) { - if err == nil { - return true // not an error - } - if !isNonFatal(err) { - return false // fatal error - } - if nf.E == nil { - nf.E = err // store first instance of non-fatal error - } - return true -} - -// Message is implemented by generated protocol buffer messages. -type Message interface { - Reset() - String() string - ProtoMessage() -} - -// A Buffer is a buffer manager for marshaling and unmarshaling -// protocol buffers. It may be reused between invocations to -// reduce memory usage. It is not necessary to use a Buffer; -// the global functions Marshal and Unmarshal create a -// temporary Buffer and are fine for most applications. -type Buffer struct { - buf []byte // encode/decode byte stream - index int // read point - - deterministic bool -} - -// NewBuffer allocates a new Buffer and initializes its internal data to -// the contents of the argument slice. -func NewBuffer(e []byte) *Buffer { - return &Buffer{buf: e} -} - -// Reset resets the Buffer, ready for marshaling a new protocol buffer. -func (p *Buffer) Reset() { - p.buf = p.buf[0:0] // for reading/writing - p.index = 0 // for reading -} - -// SetBuf replaces the internal buffer with the slice, -// ready for unmarshaling the contents of the slice. -func (p *Buffer) SetBuf(s []byte) { - p.buf = s - p.index = 0 -} - -// Bytes returns the contents of the Buffer. -func (p *Buffer) Bytes() []byte { return p.buf } - -// SetDeterministic sets whether to use deterministic serialization. -// -// Deterministic serialization guarantees that for a given binary, equal -// messages will always be serialized to the same bytes. This implies: -// -// - Repeated serialization of a message will return the same bytes. -// - Different processes of the same binary (which may be executing on -// different machines) will serialize equal messages to the same bytes. -// -// Note that the deterministic serialization is NOT canonical across -// languages. It is not guaranteed to remain stable over time. It is unstable -// across different builds with schema changes due to unknown fields. -// Users who need canonical serialization (e.g., persistent storage in a -// canonical form, fingerprinting, etc.) should define their own -// canonicalization specification and implement their own serializer rather -// than relying on this API. -// -// If deterministic serialization is requested, map entries will be sorted -// by keys in lexicographical order. This is an implementation detail and -// subject to change. -func (p *Buffer) SetDeterministic(deterministic bool) { - p.deterministic = deterministic -} - -/* - * Helper routines for simplifying the creation of optional fields of basic type. - */ - -// 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 { - return &v -} - -// Int32 is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it. -func Int32(v int32) *int32 { - return &v -} - -// 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) *int32 { - p := new(int32) - *p = int32(v) - return p -} - -// Int64 is a helper routine that allocates a new int64 value -// to store v and returns a pointer to it. -func Int64(v int64) *int64 { - return &v -} - -// Float32 is a helper routine that allocates a new float32 value -// to store v and returns a pointer to it. -func Float32(v float32) *float32 { - return &v -} - -// Float64 is a helper routine that allocates a new float64 value -// to store v and returns a pointer to it. -func Float64(v float64) *float64 { - return &v -} - -// Uint32 is a helper routine that allocates a new uint32 value -// to store v and returns a pointer to it. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint64 is a helper routine that allocates a new uint64 value -// to store v and returns a pointer to it. -func Uint64(v uint64) *uint64 { - return &v -} - -// 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 { - return &v -} - -// EnumName is a helper function to simplify printing protocol buffer enums -// by name. Given an enum map and a value, it returns a useful string. -func EnumName(m map[int32]string, v int32) string { - s, ok := m[v] - if ok { - return s - } - return strconv.Itoa(int(v)) -} - -// UnmarshalJSONEnum is a helper function to simplify recovering enum int values -// from their JSON-encoded representation. Given a map from the enum's symbolic -// names to its int values, and a byte buffer containing the JSON-encoded -// value, it returns an int32 that can be cast to the enum type by the caller. -// -// The function can deal with both JSON representations, numeric and symbolic. -func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { - if data[0] == '"' { - // New style: enums are strings. - var repr string - if err := json.Unmarshal(data, &repr); err != nil { - return -1, err - } - val, ok := m[repr] - if !ok { - return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) - } - return val, nil - } - // Old style: enums are ints. - var val int32 - if err := json.Unmarshal(data, &val); err != nil { - return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) - } - return val, nil -} - -// DebugPrint dumps the encoded data in b in a debugging format with a header -// including the string s. Used in testing but made available for general debugging. -func (p *Buffer) DebugPrint(s string, b []byte) { - var u uint64 - - obuf := p.buf - index := p.index - p.buf = b - p.index = 0 - depth := 0 - - fmt.Printf("\n--- %s ---\n", s) - -out: - for { - for i := 0; i < depth; i++ { - fmt.Print(" ") - } - - index := p.index - if index == len(p.buf) { - break - } - - op, err := p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: fetching op err %v\n", index, err) - break out - } - tag := op >> 3 - wire := op & 7 - - switch wire { - default: - fmt.Printf("%3d: t=%3d unknown wire=%d\n", - index, tag, wire) - break out - - case WireBytes: - var r []byte - - r, err = p.DecodeRawBytes(false) - if err != nil { - break out - } - fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) - if len(r) <= 6 { - for i := 0; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } else { - for i := 0; i < 3; i++ { - fmt.Printf(" %.2x", r[i]) - } - fmt.Printf(" ..") - for i := len(r) - 3; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } - fmt.Printf("\n") - - case WireFixed32: - u, err = p.DecodeFixed32() - if err != nil { - fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) - - case WireFixed64: - u, err = p.DecodeFixed64() - if err != nil { - fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) - - case WireVarint: - u, err = p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) - - case WireStartGroup: - fmt.Printf("%3d: t=%3d start\n", index, tag) - depth++ - - case WireEndGroup: - depth-- - fmt.Printf("%3d: t=%3d end\n", index, tag) - } - } - - if depth != 0 { - fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) - } - fmt.Printf("\n") - - p.buf = obuf - p.index = index -} - -// SetDefaults sets unset protocol buffer fields to their default values. -// It only modifies fields that are both unset and have defined defaults. -// It recursively sets default values in any non-nil sub-messages. -func SetDefaults(pb Message) { - setDefaults(reflect.ValueOf(pb), true, false) -} - -// v is a pointer to a struct. -func setDefaults(v reflect.Value, recur, zeros bool) { - v = v.Elem() - - defaultMu.RLock() - dm, ok := defaults[v.Type()] - defaultMu.RUnlock() - if !ok { - dm = buildDefaultMessage(v.Type()) - defaultMu.Lock() - defaults[v.Type()] = dm - defaultMu.Unlock() - } - - for _, sf := range dm.scalars { - f := v.Field(sf.index) - if !f.IsNil() { - // field already set - continue - } - dv := sf.value - if dv == nil && !zeros { - // no explicit default, and don't want to set zeros - continue - } - fptr := f.Addr().Interface() // **T - // TODO: Consider batching the allocations we do here. - switch sf.kind { - case reflect.Bool: - b := new(bool) - if dv != nil { - *b = dv.(bool) - } - *(fptr.(**bool)) = b - case reflect.Float32: - f := new(float32) - if dv != nil { - *f = dv.(float32) - } - *(fptr.(**float32)) = f - case reflect.Float64: - f := new(float64) - if dv != nil { - *f = dv.(float64) - } - *(fptr.(**float64)) = f - case reflect.Int32: - // might be an enum - if ft := f.Type(); ft != int32PtrType { - // enum - f.Set(reflect.New(ft.Elem())) - if dv != nil { - f.Elem().SetInt(int64(dv.(int32))) - } - } else { - // int32 field - i := new(int32) - if dv != nil { - *i = dv.(int32) - } - *(fptr.(**int32)) = i - } - case reflect.Int64: - i := new(int64) - if dv != nil { - *i = dv.(int64) - } - *(fptr.(**int64)) = i - case reflect.String: - s := new(string) - if dv != nil { - *s = dv.(string) - } - *(fptr.(**string)) = s - case reflect.Uint8: - // exceptional case: []byte - var b []byte - if dv != nil { - db := dv.([]byte) - b = make([]byte, len(db)) - copy(b, db) - } else { - b = []byte{} - } - *(fptr.(*[]byte)) = b - case reflect.Uint32: - u := new(uint32) - if dv != nil { - *u = dv.(uint32) - } - *(fptr.(**uint32)) = u - case reflect.Uint64: - u := new(uint64) - if dv != nil { - *u = dv.(uint64) - } - *(fptr.(**uint64)) = u - default: - log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) - } - } - - for _, ni := range dm.nested { - f := v.Field(ni) - // f is *T or []*T or map[T]*T - switch f.Kind() { - case reflect.Ptr: - if f.IsNil() { - continue - } - setDefaults(f, recur, zeros) - - case reflect.Slice: - for i := 0; i < f.Len(); i++ { - e := f.Index(i) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - - case reflect.Map: - for _, k := range f.MapKeys() { - e := f.MapIndex(k) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - } - } -} - -var ( - // defaults maps a protocol buffer struct type to a slice of the fields, - // with its scalar fields set to their proto-declared non-zero default values. - defaultMu sync.RWMutex - defaults = make(map[reflect.Type]defaultMessage) - - int32PtrType = reflect.TypeOf((*int32)(nil)) -) - -// defaultMessage represents information about the default values of a message. -type defaultMessage struct { - scalars []scalarField - nested []int // struct field index of nested messages -} - -type scalarField struct { - index int // struct field index - kind reflect.Kind // element type (the T in *T or []T) - value interface{} // the proto-declared default value, or nil -} - -// t is a struct type. -func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { - sprop := GetProperties(t) - for _, prop := range sprop.Prop { - fi, ok := sprop.decoderTags.get(prop.Tag) - if !ok { - // XXX_unrecognized - continue - } - ft := t.Field(fi).Type - - sf, nested, err := fieldDefault(ft, prop) - switch { - case err != nil: - log.Print(err) - case nested: - dm.nested = append(dm.nested, fi) - case sf != nil: - sf.index = fi - dm.scalars = append(dm.scalars, *sf) - } - } - - return dm -} - -// fieldDefault returns the scalarField for field type ft. -// sf will be nil if the field can not have a default. -// nestedMessage will be true if this is a nested message. -// Note that sf.index is not set on return. -func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { - var canHaveDefault bool - switch ft.Kind() { - case reflect.Ptr: - if ft.Elem().Kind() == reflect.Struct { - nestedMessage = true - } else { - canHaveDefault = true // proto2 scalar field - } - - case reflect.Slice: - switch ft.Elem().Kind() { - case reflect.Ptr: - nestedMessage = true // repeated message - case reflect.Uint8: - canHaveDefault = true // bytes field - } - - case reflect.Map: - if ft.Elem().Kind() == reflect.Ptr { - nestedMessage = true // map with message values - } - } - - if !canHaveDefault { - if nestedMessage { - return nil, true, nil - } - return nil, false, nil - } - - // We now know that ft is a pointer or slice. - sf = &scalarField{kind: ft.Elem().Kind()} - - // scalar fields without defaults - if !prop.HasDefault { - return sf, false, nil - } - - // a scalar field: either *T or []byte - switch ft.Elem().Kind() { - case reflect.Bool: - x, err := strconv.ParseBool(prop.Default) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Float32: - x, err := strconv.ParseFloat(prop.Default, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) - } - sf.value = float32(x) - case reflect.Float64: - x, err := strconv.ParseFloat(prop.Default, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Int32: - x, err := strconv.ParseInt(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) - } - sf.value = int32(x) - case reflect.Int64: - x, err := strconv.ParseInt(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.String: - sf.value = prop.Default - case reflect.Uint8: - // []byte (not *uint8) - sf.value = []byte(prop.Default) - case reflect.Uint32: - x, err := strconv.ParseUint(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) - } - sf.value = uint32(x) - case reflect.Uint64: - x, err := strconv.ParseUint(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) - } - sf.value = x - default: - return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) - } - - return sf, false, nil -} - -// mapKeys returns a sort.Interface to be used for sorting the map keys. -// Map fields may have key types of non-float scalars, strings and enums. -func mapKeys(vs []reflect.Value) sort.Interface { - s := mapKeySorter{vs: vs} - - // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps. - if len(vs) == 0 { - return s - } - switch vs[0].Kind() { - case reflect.Int32, reflect.Int64: - s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } - case reflect.Uint32, reflect.Uint64: - s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } - case reflect.Bool: - s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true - case reflect.String: - s.less = func(a, b reflect.Value) bool { return a.String() < b.String() } - default: - panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind())) - } - - return s -} - -type mapKeySorter struct { - vs []reflect.Value - less func(a, b reflect.Value) bool -} - -func (s mapKeySorter) Len() int { return len(s.vs) } -func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } -func (s mapKeySorter) Less(i, j int) bool { - return s.less(s.vs[i], s.vs[j]) -} - -// isProto3Zero reports whether v is a zero proto3 value. -func isProto3Zero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return !v.Bool() - case reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint32, reflect.Uint64: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.String: - return v.String() == "" - } - return false -} - -const ( - // ProtoPackageIsVersion3 is referenced from generated protocol buffer files - // to assert that that code is compatible with this version of the proto package. - ProtoPackageIsVersion3 = true - - // ProtoPackageIsVersion2 is referenced from generated protocol buffer files - // to assert that that code is compatible with this version of the proto package. - ProtoPackageIsVersion2 = true - - // ProtoPackageIsVersion1 is referenced from generated protocol buffer files - // to assert that that code is compatible with this version of the proto package. - ProtoPackageIsVersion1 = true -) - -// InternalMessageInfo is a type used internally by generated .pb.go files. -// This type is not intended to be used by non-generated code. -// This type is not subject to any compatibility guarantee. -type InternalMessageInfo struct { - marshal *marshalInfo - unmarshal *unmarshalInfo - merge *mergeInfo - discard *discardInfo -} diff --git a/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/golang/protobuf/proto/message_set.go deleted file mode 100644 index f48a756761e..00000000000 --- a/vendor/github.com/golang/protobuf/proto/message_set.go +++ /dev/null @@ -1,181 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Support for message sets. - */ - -import ( - "errors" -) - -// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. -// A message type ID is required for storing a protocol buffer in a message set. -var errNoMessageTypeID = errors.New("proto does not have a message type ID") - -// The first two types (_MessageSet_Item and messageSet) -// model what the protocol compiler produces for the following protocol message: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } -// That is the MessageSet wire format. We can't use a proto to generate these -// because that would introduce a circular dependency between it and this package. - -type _MessageSet_Item struct { - TypeId *int32 `protobuf:"varint,2,req,name=type_id"` - Message []byte `protobuf:"bytes,3,req,name=message"` -} - -type messageSet struct { - Item []*_MessageSet_Item `protobuf:"group,1,rep"` - XXX_unrecognized []byte - // TODO: caching? -} - -// Make sure messageSet is a Message. -var _ Message = (*messageSet)(nil) - -// messageTypeIder is an interface satisfied by a protocol buffer type -// that may be stored in a MessageSet. -type messageTypeIder interface { - MessageTypeId() int32 -} - -func (ms *messageSet) find(pb Message) *_MessageSet_Item { - mti, ok := pb.(messageTypeIder) - if !ok { - return nil - } - id := mti.MessageTypeId() - for _, item := range ms.Item { - if *item.TypeId == id { - return item - } - } - return nil -} - -func (ms *messageSet) Has(pb Message) bool { - return ms.find(pb) != nil -} - -func (ms *messageSet) Unmarshal(pb Message) error { - if item := ms.find(pb); item != nil { - return Unmarshal(item.Message, pb) - } - if _, ok := pb.(messageTypeIder); !ok { - return errNoMessageTypeID - } - return nil // TODO: return error instead? -} - -func (ms *messageSet) Marshal(pb Message) error { - msg, err := Marshal(pb) - if err != nil { - return err - } - if item := ms.find(pb); item != nil { - // reuse existing item - item.Message = msg - return nil - } - - mti, ok := pb.(messageTypeIder) - if !ok { - return errNoMessageTypeID - } - - mtid := mti.MessageTypeId() - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: &mtid, - Message: msg, - }) - return nil -} - -func (ms *messageSet) Reset() { *ms = messageSet{} } -func (ms *messageSet) String() string { return CompactTextString(ms) } -func (*messageSet) ProtoMessage() {} - -// Support for the message_set_wire_format message option. - -func skipVarint(buf []byte) []byte { - i := 0 - for ; buf[i]&0x80 != 0; i++ { - } - return buf[i+1:] -} - -// unmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. -// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option. -func unmarshalMessageSet(buf []byte, exts interface{}) error { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - m = exts.extensionsWrite() - case map[int32]Extension: - m = exts - default: - return errors.New("proto: not an extension map") - } - - ms := new(messageSet) - if err := Unmarshal(buf, ms); err != nil { - return err - } - for _, item := range ms.Item { - id := *item.TypeId - msg := item.Message - - // Restore wire type and field number varint, plus length varint. - // Be careful to preserve duplicate items. - b := EncodeVarint(uint64(id)<<3 | WireBytes) - if ext, ok := m[id]; ok { - // Existing data; rip off the tag and length varint - // so we join the new data correctly. - // We can assume that ext.enc is set because we are unmarshaling. - o := ext.enc[len(b):] // skip wire type and field number - _, n := DecodeVarint(o) // calculate length of length varint - o = o[n:] // skip length varint - msg = append(o, msg...) // join old data and new data - } - b = append(b, EncodeVarint(uint64(len(msg)))...) - b = append(b, msg...) - - m[id] = Extension{enc: b} - } - return nil -} diff --git a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go deleted file mode 100644 index 94fa9194a88..00000000000 --- a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go +++ /dev/null @@ -1,360 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build purego appengine js - -// This file contains an implementation of proto field accesses using package reflect. -// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can -// be used on App Engine. - -package proto - -import ( - "reflect" - "sync" -) - -const unsafeAllowed = false - -// A field identifies a field in a struct, accessible from a pointer. -// In this implementation, a field is identified by the sequence of field indices -// passed to reflect's FieldByIndex. -type field []int - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return f.Index -} - -// invalidField is an invalid field identifier. -var invalidField = field(nil) - -// zeroField is a noop when calling pointer.offset. -var zeroField = field([]int{}) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { return f != nil } - -// The pointer type is for the table-driven decoder. -// The implementation here uses a reflect.Value of pointer type to -// create a generic pointer. In pointer_unsafe.go we use unsafe -// instead of reflect to implement the same (but faster) interface. -type pointer struct { - v reflect.Value -} - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - return pointer{v: reflect.ValueOf(*i)} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr, deref bool) pointer { - v := reflect.ValueOf(*i) - u := reflect.New(v.Type()) - u.Elem().Set(v) - if deref { - u = u.Elem() - } - return pointer{v: u} -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{v: v} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - return pointer{v: p.v.Elem().FieldByIndex(f).Addr()} -} - -func (p pointer) isNil() bool { - return p.v.IsNil() -} - -// grow updates the slice s in place to make it one element longer. -// s must be addressable. -// Returns the (addressable) new element. -func grow(s reflect.Value) reflect.Value { - n, m := s.Len(), s.Cap() - if n < m { - s.SetLen(n + 1) - } else { - s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem()))) - } - return s.Index(n) -} - -func (p pointer) toInt64() *int64 { - return p.v.Interface().(*int64) -} -func (p pointer) toInt64Ptr() **int64 { - return p.v.Interface().(**int64) -} -func (p pointer) toInt64Slice() *[]int64 { - return p.v.Interface().(*[]int64) -} - -var int32ptr = reflect.TypeOf((*int32)(nil)) - -func (p pointer) toInt32() *int32 { - return p.v.Convert(int32ptr).Interface().(*int32) -} - -// The toInt32Ptr/Slice methods don't work because of enums. -// Instead, we must use set/get methods for the int32ptr/slice case. -/* - func (p pointer) toInt32Ptr() **int32 { - return p.v.Interface().(**int32) -} - func (p pointer) toInt32Slice() *[]int32 { - return p.v.Interface().(*[]int32) -} -*/ -func (p pointer) getInt32Ptr() *int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().(*int32) - } - // an enum - return p.v.Elem().Convert(int32PtrType).Interface().(*int32) -} -func (p pointer) setInt32Ptr(v int32) { - // Allocate value in a *int32. Possibly convert that to a *enum. - // Then assign it to a **int32 or **enum. - // Note: we can convert *int32 to *enum, but we can't convert - // **int32 to **enum! - p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem())) -} - -// getInt32Slice copies []int32 from p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getInt32Slice() []int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().([]int32) - } - // an enum - // Allocate a []int32, then assign []enum's values into it. - // Note: we can't convert []enum to []int32. - slice := p.v.Elem() - s := make([]int32, slice.Len()) - for i := 0; i < slice.Len(); i++ { - s[i] = int32(slice.Index(i).Int()) - } - return s -} - -// setInt32Slice copies []int32 into p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setInt32Slice(v []int32) { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - p.v.Elem().Set(reflect.ValueOf(v)) - return - } - // an enum - // Allocate a []enum, then assign []int32's values into it. - // Note: we can't convert []enum to []int32. - slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v)) - for i, x := range v { - slice.Index(i).SetInt(int64(x)) - } - p.v.Elem().Set(slice) -} -func (p pointer) appendInt32Slice(v int32) { - grow(p.v.Elem()).SetInt(int64(v)) -} - -func (p pointer) toUint64() *uint64 { - return p.v.Interface().(*uint64) -} -func (p pointer) toUint64Ptr() **uint64 { - return p.v.Interface().(**uint64) -} -func (p pointer) toUint64Slice() *[]uint64 { - return p.v.Interface().(*[]uint64) -} -func (p pointer) toUint32() *uint32 { - return p.v.Interface().(*uint32) -} -func (p pointer) toUint32Ptr() **uint32 { - return p.v.Interface().(**uint32) -} -func (p pointer) toUint32Slice() *[]uint32 { - return p.v.Interface().(*[]uint32) -} -func (p pointer) toBool() *bool { - return p.v.Interface().(*bool) -} -func (p pointer) toBoolPtr() **bool { - return p.v.Interface().(**bool) -} -func (p pointer) toBoolSlice() *[]bool { - return p.v.Interface().(*[]bool) -} -func (p pointer) toFloat64() *float64 { - return p.v.Interface().(*float64) -} -func (p pointer) toFloat64Ptr() **float64 { - return p.v.Interface().(**float64) -} -func (p pointer) toFloat64Slice() *[]float64 { - return p.v.Interface().(*[]float64) -} -func (p pointer) toFloat32() *float32 { - return p.v.Interface().(*float32) -} -func (p pointer) toFloat32Ptr() **float32 { - return p.v.Interface().(**float32) -} -func (p pointer) toFloat32Slice() *[]float32 { - return p.v.Interface().(*[]float32) -} -func (p pointer) toString() *string { - return p.v.Interface().(*string) -} -func (p pointer) toStringPtr() **string { - return p.v.Interface().(**string) -} -func (p pointer) toStringSlice() *[]string { - return p.v.Interface().(*[]string) -} -func (p pointer) toBytes() *[]byte { - return p.v.Interface().(*[]byte) -} -func (p pointer) toBytesSlice() *[][]byte { - return p.v.Interface().(*[][]byte) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return p.v.Interface().(*XXX_InternalExtensions) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return p.v.Interface().(*map[int32]Extension) -} -func (p pointer) getPointer() pointer { - return pointer{v: p.v.Elem()} -} -func (p pointer) setPointer(q pointer) { - p.v.Elem().Set(q.v) -} -func (p pointer) appendPointer(q pointer) { - grow(p.v.Elem()).Set(q.v) -} - -// getPointerSlice copies []*T from p as a new []pointer. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getPointerSlice() []pointer { - if p.v.IsNil() { - return nil - } - n := p.v.Elem().Len() - s := make([]pointer, n) - for i := 0; i < n; i++ { - s[i] = pointer{v: p.v.Elem().Index(i)} - } - return s -} - -// setPointerSlice copies []pointer into p as a new []*T. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setPointerSlice(v []pointer) { - if v == nil { - p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem()) - return - } - s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v)) - for _, p := range v { - s = reflect.Append(s, p.v) - } - p.v.Elem().Set(s) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - if p.v.Elem().IsNil() { - return pointer{v: p.v.Elem()} - } - return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct -} - -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - // TODO: check that p.v.Type().Elem() == t? - return p.v -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} - -var atomicLock sync.Mutex diff --git a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go deleted file mode 100644 index dbfffe071b8..00000000000 --- a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go +++ /dev/null @@ -1,313 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build !purego,!appengine,!js - -// This file contains the implementation of the proto field accesses using package unsafe. - -package proto - -import ( - "reflect" - "sync/atomic" - "unsafe" -) - -const unsafeAllowed = true - -// A field identifies a field in a struct, accessible from a pointer. -// In this implementation, a field is identified by its byte offset from the start of the struct. -type field uintptr - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return field(f.Offset) -} - -// invalidField is an invalid field identifier. -const invalidField = ^field(0) - -// zeroField is a noop when calling pointer.offset. -const zeroField = field(0) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { - return f != invalidField -} - -// The pointer type below is for the new table-driven encoder/decoder. -// The implementation here uses unsafe.Pointer to create a generic pointer. -// In pointer_reflect.go we use reflect instead of unsafe to implement -// the same (but slower) interface. -type pointer struct { - p unsafe.Pointer -} - -// size of pointer -var ptrSize = unsafe.Sizeof(uintptr(0)) - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - // Super-tricky - read pointer out of data word of interface value. - // Saves ~25ns over the equivalent: - // return valToPointer(reflect.ValueOf(*i)) - return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr, deref bool) (p pointer) { - // Super-tricky - read or get the address of data word of interface value. - if isptr { - // The interface is of pointer type, thus it is a direct interface. - // The data word is the pointer data itself. We take its address. - p = pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)} - } else { - // The interface is not of pointer type. The data word is the pointer - // to the data. - p = pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} - } - if deref { - p.p = *(*unsafe.Pointer)(p.p) - } - return p -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{p: unsafe.Pointer(v.Pointer())} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - // For safety, we should panic if !f.IsValid, however calling panic causes - // this to no longer be inlineable, which is a serious performance cost. - /* - if !f.IsValid() { - panic("invalid field") - } - */ - return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} -} - -func (p pointer) isNil() bool { - return p.p == nil -} - -func (p pointer) toInt64() *int64 { - return (*int64)(p.p) -} -func (p pointer) toInt64Ptr() **int64 { - return (**int64)(p.p) -} -func (p pointer) toInt64Slice() *[]int64 { - return (*[]int64)(p.p) -} -func (p pointer) toInt32() *int32 { - return (*int32)(p.p) -} - -// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist. -/* - func (p pointer) toInt32Ptr() **int32 { - return (**int32)(p.p) - } - func (p pointer) toInt32Slice() *[]int32 { - return (*[]int32)(p.p) - } -*/ -func (p pointer) getInt32Ptr() *int32 { - return *(**int32)(p.p) -} -func (p pointer) setInt32Ptr(v int32) { - *(**int32)(p.p) = &v -} - -// getInt32Slice loads a []int32 from p. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getInt32Slice() []int32 { - return *(*[]int32)(p.p) -} - -// setInt32Slice stores a []int32 to p. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setInt32Slice(v []int32) { - *(*[]int32)(p.p) = v -} - -// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead? -func (p pointer) appendInt32Slice(v int32) { - s := (*[]int32)(p.p) - *s = append(*s, v) -} - -func (p pointer) toUint64() *uint64 { - return (*uint64)(p.p) -} -func (p pointer) toUint64Ptr() **uint64 { - return (**uint64)(p.p) -} -func (p pointer) toUint64Slice() *[]uint64 { - return (*[]uint64)(p.p) -} -func (p pointer) toUint32() *uint32 { - return (*uint32)(p.p) -} -func (p pointer) toUint32Ptr() **uint32 { - return (**uint32)(p.p) -} -func (p pointer) toUint32Slice() *[]uint32 { - return (*[]uint32)(p.p) -} -func (p pointer) toBool() *bool { - return (*bool)(p.p) -} -func (p pointer) toBoolPtr() **bool { - return (**bool)(p.p) -} -func (p pointer) toBoolSlice() *[]bool { - return (*[]bool)(p.p) -} -func (p pointer) toFloat64() *float64 { - return (*float64)(p.p) -} -func (p pointer) toFloat64Ptr() **float64 { - return (**float64)(p.p) -} -func (p pointer) toFloat64Slice() *[]float64 { - return (*[]float64)(p.p) -} -func (p pointer) toFloat32() *float32 { - return (*float32)(p.p) -} -func (p pointer) toFloat32Ptr() **float32 { - return (**float32)(p.p) -} -func (p pointer) toFloat32Slice() *[]float32 { - return (*[]float32)(p.p) -} -func (p pointer) toString() *string { - return (*string)(p.p) -} -func (p pointer) toStringPtr() **string { - return (**string)(p.p) -} -func (p pointer) toStringSlice() *[]string { - return (*[]string)(p.p) -} -func (p pointer) toBytes() *[]byte { - return (*[]byte)(p.p) -} -func (p pointer) toBytesSlice() *[][]byte { - return (*[][]byte)(p.p) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return (*XXX_InternalExtensions)(p.p) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return (*map[int32]Extension)(p.p) -} - -// getPointerSlice loads []*T from p as a []pointer. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getPointerSlice() []pointer { - // Super-tricky - p should point to a []*T where T is a - // message type. We load it as []pointer. - return *(*[]pointer)(p.p) -} - -// setPointerSlice stores []pointer into p as a []*T. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setPointerSlice(v []pointer) { - // Super-tricky - p should point to a []*T where T is a - // message type. We store it as []pointer. - *(*[]pointer)(p.p) = v -} - -// getPointer loads the pointer at p and returns it. -func (p pointer) getPointer() pointer { - return pointer{p: *(*unsafe.Pointer)(p.p)} -} - -// setPointer stores the pointer q at p. -func (p pointer) setPointer(q pointer) { - *(*unsafe.Pointer)(p.p) = q.p -} - -// append q to the slice pointed to by p. -func (p pointer) appendPointer(q pointer) { - s := (*[]unsafe.Pointer)(p.p) - *s = append(*s, q.p) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - // Super-tricky - read pointer out of data word of interface value. - return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]} -} - -// asPointerTo returns a reflect.Value that is a pointer to an -// object of type t stored at p. -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - return reflect.NewAt(t, p.p) -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go index a4b8c0cd3a8..dcdc2202fad 100644 --- a/vendor/github.com/golang/protobuf/proto/properties.go +++ b/vendor/github.com/golang/protobuf/proto/properties.go @@ -1,162 +1,104 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. package proto -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - import ( "fmt" - "log" "reflect" - "sort" "strconv" "strings" "sync" -) - -const debug bool = false -// Constants that identify the encoding of a value on the wire. -const ( - WireVarint = 0 - WireFixed64 = 1 - WireBytes = 2 - WireStartGroup = 3 - WireEndGroup = 4 - WireFixed32 = 5 + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoimpl" ) -// tagMap is an optimization over map[int]int for typical protocol buffer -// use-cases. Encoded protocol buffers are often in tag order with small tag -// numbers. -type tagMap struct { - fastTags []int - slowTags map[int]int -} - -// tagMapFastLimit is the upper bound on the tag number that will be stored in -// the tagMap slice rather than its map. -const tagMapFastLimit = 1024 - -func (p *tagMap) get(t int) (int, bool) { - if t > 0 && t < tagMapFastLimit { - if t >= len(p.fastTags) { - return 0, false - } - fi := p.fastTags[t] - return fi, fi >= 0 - } - fi, ok := p.slowTags[t] - return fi, ok -} - -func (p *tagMap) put(t int, fi int) { - if t > 0 && t < tagMapFastLimit { - for len(p.fastTags) < t+1 { - p.fastTags = append(p.fastTags, -1) - } - p.fastTags[t] = fi - return - } - if p.slowTags == nil { - p.slowTags = make(map[int]int) - } - p.slowTags[t] = fi -} - -// StructProperties represents properties for all the fields of a struct. -// decoderTags and decoderOrigNames should only be used by the decoder. +// StructProperties represents protocol buffer type information for a +// generated protobuf message in the open-struct API. +// +// Deprecated: Do not use. type StructProperties struct { - Prop []*Properties // properties for each field - reqCount int // required count - decoderTags tagMap // map from proto tag to struct field number - decoderOrigNames map[string]int // map from original name to struct field number - order []int // list of struct field numbers in tag order + // Prop are the properties for each field. + // + // Fields belonging to a oneof are stored in OneofTypes instead, with a + // single Properties representing the parent oneof held here. + // + // The order of Prop matches the order of fields in the Go struct. + // Struct fields that are not related to protobufs have a "XXX_" prefix + // in the Properties.Name and must be ignored by the user. + Prop []*Properties // OneofTypes contains information about the oneof fields in this message. - // It is keyed by the original name of a field. + // It is keyed by the protobuf field name. OneofTypes map[string]*OneofProperties } -// OneofProperties represents information about a specific field in a oneof. -type OneofProperties struct { - Type reflect.Type // pointer to generated struct type for this oneof field - Field int // struct field number of the containing oneof in the message - Prop *Properties -} - -// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. -// See encode.go, (*Buffer).enc_struct. - -func (sp *StructProperties) Len() int { return len(sp.order) } -func (sp *StructProperties) Less(i, j int) bool { - return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag -} -func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } - -// Properties represents the protocol-specific behavior of a single struct field. +// Properties represents the type information for a protobuf message field. +// +// Deprecated: Do not use. type Properties struct { - Name string // name of the field, for error messages - OrigName string // original name before protocol compiler (always set) - JSONName string // name to use for JSON; determined by protoc - Wire string + // Name is a placeholder name with little meaningful semantic value. + // If the name has an "XXX_" prefix, the entire Properties must be ignored. + Name string + // OrigName is the protobuf field name or oneof name. + OrigName string + // JSONName is the JSON name for the protobuf field. + JSONName string + // Enum is a placeholder name for enums. + // For historical reasons, this is neither the Go name for the enum, + // nor the protobuf name for the enum. + Enum string // Deprecated: Do not use. + // Weak contains the full name of the weakly referenced message. + Weak string + // Wire is a string representation of the wire type. + Wire string + // WireType is the protobuf wire type for the field. WireType int - Tag int + // Tag is the protobuf field number. + Tag int + // Required reports whether this is a required field. Required bool + // Optional reports whether this is a optional field. Optional bool + // Repeated reports whether this is a repeated field. Repeated bool - Packed bool // relevant for repeated primitives only - Enum string // set for enum types only - proto3 bool // whether this is known to be a proto3 field - oneof bool // whether this is a oneof field - - Default string // default value - HasDefault bool // whether an explicit default was provided - - stype reflect.Type // set for struct types only - sprop *StructProperties // set for struct types only + // Packed reports whether this is a packed repeated field of scalars. + Packed bool + // Proto3 reports whether this field operates under the proto3 syntax. + Proto3 bool + // Oneof reports whether this field belongs within a oneof. + Oneof bool + + // Default is the default value in string form. + Default string + // HasDefault reports whether the field has a default value. + HasDefault bool + + // MapKeyProp is the properties for the key field for a map field. + MapKeyProp *Properties + // MapValProp is the properties for the value field for a map field. + MapValProp *Properties +} - mtype reflect.Type // set for map types only - MapKeyProp *Properties // set for map types only - MapValProp *Properties // set for map types only +// OneofProperties represents the type information for a protobuf oneof. +// +// Deprecated: Do not use. +type OneofProperties struct { + // Type is a pointer to the generated wrapper type for the field value. + // This is nil for messages that are not in the open-struct API. + Type reflect.Type + // Field is the index into StructProperties.Prop for the containing oneof. + Field int + // Prop is the properties for the field. + Prop *Properties } // String formats the properties in the protobuf struct field tag style. func (p *Properties) String() string { s := p.Wire - s += "," - s += strconv.Itoa(p.Tag) + s += "," + strconv.Itoa(p.Tag) if p.Required { s += ",req" } @@ -170,18 +112,21 @@ func (p *Properties) String() string { s += ",packed" } s += ",name=" + p.OrigName - if p.JSONName != p.OrigName { + if p.JSONName != "" { s += ",json=" + p.JSONName } - if p.proto3 { + if len(p.Enum) > 0 { + s += ",enum=" + p.Enum + } + if len(p.Weak) > 0 { + s += ",weak=" + p.Weak + } + if p.Proto3 { s += ",proto3" } - if p.oneof { + if p.Oneof { s += ",oneof" } - if len(p.Enum) > 0 { - s += ",enum=" + p.Enum - } if p.HasDefault { s += ",def=" + p.Default } @@ -189,356 +134,173 @@ func (p *Properties) String() string { } // Parse populates p by parsing a string in the protobuf struct field tag style. -func (p *Properties) Parse(s string) { - // "bytes,49,opt,name=foo,def=hello!" - fields := strings.Split(s, ",") // breaks def=, but handled below. - if len(fields) < 2 { - log.Printf("proto: tag has too few fields: %q", s) - return - } - - p.Wire = fields[0] - switch p.Wire { - case "varint": - p.WireType = WireVarint - case "fixed32": - p.WireType = WireFixed32 - case "fixed64": - p.WireType = WireFixed64 - case "zigzag32": - p.WireType = WireVarint - case "zigzag64": - p.WireType = WireVarint - case "bytes", "group": - p.WireType = WireBytes - // no numeric converter for non-numeric types - default: - log.Printf("proto: tag has unknown wire type: %q", s) - return - } - - var err error - p.Tag, err = strconv.Atoi(fields[1]) - if err != nil { - return - } - -outer: - for i := 2; i < len(fields); i++ { - f := fields[i] - switch { - case f == "req": - p.Required = true - case f == "opt": +func (p *Properties) Parse(tag string) { + // For example: "bytes,49,opt,name=foo,def=hello!" + for len(tag) > 0 { + i := strings.IndexByte(tag, ',') + if i < 0 { + i = len(tag) + } + switch s := tag[:i]; { + case strings.HasPrefix(s, "name="): + p.OrigName = s[len("name="):] + case strings.HasPrefix(s, "json="): + p.JSONName = s[len("json="):] + case strings.HasPrefix(s, "enum="): + p.Enum = s[len("enum="):] + case strings.HasPrefix(s, "weak="): + p.Weak = s[len("weak="):] + case strings.Trim(s, "0123456789") == "": + n, _ := strconv.ParseUint(s, 10, 32) + p.Tag = int(n) + case s == "opt": p.Optional = true - case f == "rep": + case s == "req": + p.Required = true + case s == "rep": p.Repeated = true - case f == "packed": + case s == "varint" || s == "zigzag32" || s == "zigzag64": + p.Wire = s + p.WireType = WireVarint + case s == "fixed32": + p.Wire = s + p.WireType = WireFixed32 + case s == "fixed64": + p.Wire = s + p.WireType = WireFixed64 + case s == "bytes": + p.Wire = s + p.WireType = WireBytes + case s == "group": + p.Wire = s + p.WireType = WireStartGroup + case s == "packed": p.Packed = true - case strings.HasPrefix(f, "name="): - p.OrigName = f[5:] - case strings.HasPrefix(f, "json="): - p.JSONName = f[5:] - case strings.HasPrefix(f, "enum="): - p.Enum = f[5:] - case f == "proto3": - p.proto3 = true - case f == "oneof": - p.oneof = true - case strings.HasPrefix(f, "def="): + case s == "proto3": + p.Proto3 = true + case s == "oneof": + p.Oneof = true + case strings.HasPrefix(s, "def="): + // The default tag is special in that everything afterwards is the + // default regardless of the presence of commas. p.HasDefault = true - p.Default = f[4:] // rest of string - if i+1 < len(fields) { - // Commas aren't escaped, and def is always last. - p.Default += "," + strings.Join(fields[i+1:], ",") - break outer - } - } - } -} - -var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() - -// setFieldProps initializes the field properties for submessages and maps. -func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { - switch t1 := typ; t1.Kind() { - case reflect.Ptr: - if t1.Elem().Kind() == reflect.Struct { - p.stype = t1.Elem() - } - - case reflect.Slice: - if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct { - p.stype = t2.Elem() - } - - case reflect.Map: - p.mtype = t1 - p.MapKeyProp = &Properties{} - p.MapKeyProp.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) - p.MapValProp = &Properties{} - vtype := p.mtype.Elem() - if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { - // The value type is not a message (*T) or bytes ([]byte), - // so we need encoders for the pointer to this type. - vtype = reflect.PtrTo(vtype) - } - p.MapValProp.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) - } - - if p.stype != nil { - if lockGetProp { - p.sprop = GetProperties(p.stype) - } else { - p.sprop = getPropertiesLocked(p.stype) + p.Default, i = tag[len("def="):], len(tag) } + tag = strings.TrimPrefix(tag[i:], ",") } } -var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() -) - // Init populates the properties from a protocol buffer struct tag. +// +// Deprecated: Do not use. func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { - p.init(typ, name, tag, f, true) -} - -func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { - // "bytes,49,opt,def=hello!" p.Name = name p.OrigName = name if tag == "" { return } p.Parse(tag) - p.setFieldProps(typ, f, lockGetProp) + + if typ != nil && typ.Kind() == reflect.Map { + p.MapKeyProp = new(Properties) + p.MapKeyProp.Init(nil, "Key", f.Tag.Get("protobuf_key"), nil) + p.MapValProp = new(Properties) + p.MapValProp.Init(nil, "Value", f.Tag.Get("protobuf_val"), nil) + } } -var ( - propertiesMu sync.RWMutex - propertiesMap = make(map[reflect.Type]*StructProperties) -) +var propertiesCache sync.Map // map[reflect.Type]*StructProperties -// GetProperties returns the list of properties for the type represented by t. -// t must represent a generated struct type of a protocol message. +// GetProperties returns the list of properties for the type represented by t, +// which must be a generated protocol buffer message in the open-struct API, +// where protobuf message fields are represented by exported Go struct fields. +// +// Deprecated: Use protobuf reflection instead. func GetProperties(t reflect.Type) *StructProperties { - if t.Kind() != reflect.Struct { - panic("proto: type must have kind struct") - } - - // Most calls to GetProperties in a long-running program will be - // retrieving details for types we have seen before. - propertiesMu.RLock() - sprop, ok := propertiesMap[t] - propertiesMu.RUnlock() - if ok { - return sprop + if p, ok := propertiesCache.Load(t); ok { + return p.(*StructProperties) } - - propertiesMu.Lock() - sprop = getPropertiesLocked(t) - propertiesMu.Unlock() - return sprop + p, _ := propertiesCache.LoadOrStore(t, newProperties(t)) + return p.(*StructProperties) } -type ( - oneofFuncsIface interface { - XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) - } - oneofWrappersIface interface { - XXX_OneofWrappers() []interface{} - } -) - -// getPropertiesLocked requires that propertiesMu is held. -func getPropertiesLocked(t reflect.Type) *StructProperties { - if prop, ok := propertiesMap[t]; ok { - return prop +func newProperties(t reflect.Type) *StructProperties { + if t.Kind() != reflect.Struct { + panic(fmt.Sprintf("%v is not a generated message in the open-struct API", t)) } + var hasOneof bool prop := new(StructProperties) - // in case of recursive protos, fill this in now. - propertiesMap[t] = prop - - // build properties - prop.Prop = make([]*Properties, t.NumField()) - prop.order = make([]int, t.NumField()) + // Construct a list of properties for each field in the struct. for i := 0; i < t.NumField(); i++ { - f := t.Field(i) p := new(Properties) - name := f.Name - p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) + f := t.Field(i) + tagField := f.Tag.Get("protobuf") + p.Init(f.Type, f.Name, tagField, &f) - oneof := f.Tag.Get("protobuf_oneof") // special case - if oneof != "" { - // Oneof fields don't use the traditional protobuf tag. - p.OrigName = oneof + tagOneof := f.Tag.Get("protobuf_oneof") + if tagOneof != "" { + hasOneof = true + p.OrigName = tagOneof } - prop.Prop[i] = p - prop.order[i] = i - if debug { - print(i, " ", f.Name, " ", t.String(), " ") - if p.Tag > 0 { - print(p.String()) - } - print("\n") + + // Rename unrelated struct fields with the "XXX_" prefix since so much + // user code simply checks for this to exclude special fields. + if tagField == "" && tagOneof == "" && !strings.HasPrefix(p.Name, "XXX_") { + p.Name = "XXX_" + p.Name + p.OrigName = "XXX_" + p.OrigName + } else if p.Weak != "" { + p.Name = p.OrigName // avoid possible "XXX_" prefix on weak field } + + prop.Prop = append(prop.Prop, p) } - // Re-order prop.order. - sort.Sort(prop) + // Construct a mapping of oneof field names to properties. + if hasOneof { + var oneofWrappers []interface{} + if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok { + oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3].Interface().([]interface{}) + } + if fn, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok { + oneofWrappers = fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0].Interface().([]interface{}) + } + if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(protoreflect.ProtoMessage); ok { + if m, ok := m.ProtoReflect().(interface{ ProtoMessageInfo() *protoimpl.MessageInfo }); ok { + oneofWrappers = m.ProtoMessageInfo().OneofWrappers + } + } - var oots []interface{} - switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) { - case oneofFuncsIface: - _, _, _, oots = m.XXX_OneofFuncs() - case oneofWrappersIface: - oots = m.XXX_OneofWrappers() - } - if len(oots) > 0 { - // Interpret oneof metadata. prop.OneofTypes = make(map[string]*OneofProperties) - for _, oot := range oots { - oop := &OneofProperties{ - Type: reflect.ValueOf(oot).Type(), // *T + for _, wrapper := range oneofWrappers { + p := &OneofProperties{ + Type: reflect.ValueOf(wrapper).Type(), // *T Prop: new(Properties), } - sft := oop.Type.Elem().Field(0) - oop.Prop.Name = sft.Name - oop.Prop.Parse(sft.Tag.Get("protobuf")) - // There will be exactly one interface field that - // this new value is assignable to. - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if f.Type.Kind() != reflect.Interface { - continue + f := p.Type.Elem().Field(0) + p.Prop.Name = f.Name + p.Prop.Parse(f.Tag.Get("protobuf")) + + // Determine the struct field that contains this oneof. + // Each wrapper is assignable to exactly one parent field. + var foundOneof bool + for i := 0; i < t.NumField() && !foundOneof; i++ { + if p.Type.AssignableTo(t.Field(i).Type) { + p.Field = i + foundOneof = true } - if !oop.Type.AssignableTo(f.Type) { - continue - } - oop.Field = i - break } - prop.OneofTypes[oop.Prop.OrigName] = oop - } - } - - // build required counts - // build tags - reqCount := 0 - prop.decoderOrigNames = make(map[string]int) - for i, p := range prop.Prop { - if strings.HasPrefix(p.Name, "XXX_") { - // Internal fields should not appear in tags/origNames maps. - // They are handled specially when encoding and decoding. - continue - } - if p.Required { - reqCount++ + if !foundOneof { + panic(fmt.Sprintf("%v is not a generated message in the open-struct API", t)) + } + prop.OneofTypes[p.Prop.OrigName] = p } - prop.decoderTags.put(p.Tag, i) - prop.decoderOrigNames[p.OrigName] = i } - prop.reqCount = reqCount return prop } -// A global registry of enum types. -// The generated code will register the generated maps by calling RegisterEnum. - -var enumValueMaps = make(map[string]map[string]int32) - -// RegisterEnum is called from the generated code to install the enum descriptor -// maps into the global table to aid parsing text format protocol buffers. -func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { - if _, ok := enumValueMaps[typeName]; ok { - panic("proto: duplicate enum registered: " + typeName) - } - enumValueMaps[typeName] = valueMap -} - -// EnumValueMap returns the mapping from names to integers of the -// enum type enumType, or a nil if not found. -func EnumValueMap(enumType string) map[string]int32 { - return enumValueMaps[enumType] -} - -// A registry of all linked message types. -// The string is a fully-qualified proto name ("pkg.Message"). -var ( - protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers - protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types - revProtoTypes = make(map[reflect.Type]string) -) - -// RegisterType is called from generated code and maps from the fully qualified -// proto name to the type (pointer to struct) of the protocol buffer. -func RegisterType(x Message, name string) { - if _, ok := protoTypedNils[name]; ok { - // TODO: Some day, make this a panic. - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 { - // Generated code always calls RegisterType with nil x. - // This check is just for extra safety. - protoTypedNils[name] = x - } else { - protoTypedNils[name] = reflect.Zero(t).Interface().(Message) - } - revProtoTypes[t] = name -} - -// RegisterMapType is called from generated code and maps from the fully qualified -// proto name to the native map type of the proto map definition. -func RegisterMapType(x interface{}, name string) { - if reflect.TypeOf(x).Kind() != reflect.Map { - panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name)) - } - if _, ok := protoMapTypes[name]; ok { - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - protoMapTypes[name] = t - revProtoTypes[t] = name -} - -// MessageName returns the fully-qualified proto name for the given message type. -func MessageName(x Message) string { - type xname interface { - XXX_MessageName() string - } - if m, ok := x.(xname); ok { - return m.XXX_MessageName() - } - return revProtoTypes[reflect.TypeOf(x)] -} - -// MessageType returns the message type (pointer to struct) for a named message. -// The type is not guaranteed to implement proto.Message if the name refers to a -// map entry. -func MessageType(name string) reflect.Type { - if t, ok := protoTypedNils[name]; ok { - return reflect.TypeOf(t) - } - return protoMapTypes[name] -} - -// A registry of all linked proto files. -var ( - protoFiles = make(map[string][]byte) // file name => fileDescriptor -) - -// RegisterFile is called from generated code and maps from the -// full file name of a .proto file to its compressed FileDescriptorProto. -func RegisterFile(filename string, fileDescriptor []byte) { - protoFiles[filename] = fileDescriptor -} - -// FileDescriptor returns the compressed FileDescriptorProto for a .proto file. -func FileDescriptor(filename string) []byte { return protoFiles[filename] } +func (sp *StructProperties) Len() int { return len(sp.Prop) } +func (sp *StructProperties) Less(i, j int) bool { return false } +func (sp *StructProperties) Swap(i, j int) { return } diff --git a/vendor/github.com/golang/protobuf/proto/proto.go b/vendor/github.com/golang/protobuf/proto/proto.go new file mode 100644 index 00000000000..5aee89c323e --- /dev/null +++ b/vendor/github.com/golang/protobuf/proto/proto.go @@ -0,0 +1,167 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package proto provides functionality for handling protocol buffer messages. +// In particular, it provides marshaling and unmarshaling between a protobuf +// message and the binary wire format. +// +// See https://developers.google.com/protocol-buffers/docs/gotutorial for +// more information. +// +// Deprecated: Use the "google.golang.org/protobuf/proto" package instead. +package proto + +import ( + protoV2 "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoiface" + "google.golang.org/protobuf/runtime/protoimpl" +) + +const ( + ProtoPackageIsVersion1 = true + ProtoPackageIsVersion2 = true + ProtoPackageIsVersion3 = true + ProtoPackageIsVersion4 = true +) + +// GeneratedEnum is any enum type generated by protoc-gen-go +// which is a named int32 kind. +// This type exists for documentation purposes. +type GeneratedEnum interface{} + +// GeneratedMessage is any message type generated by protoc-gen-go +// which is a pointer to a named struct kind. +// This type exists for documentation purposes. +type GeneratedMessage interface{} + +// Message is a protocol buffer message. +// +// This is the v1 version of the message interface and is marginally better +// than an empty interface as it lacks any method to programatically interact +// with the contents of the message. +// +// A v2 message is declared in "google.golang.org/protobuf/proto".Message and +// exposes protobuf reflection as a first-class feature of the interface. +// +// To convert a v1 message to a v2 message, use the MessageV2 function. +// To convert a v2 message to a v1 message, use the MessageV1 function. +type Message = protoiface.MessageV1 + +// MessageV1 converts either a v1 or v2 message to a v1 message. +// It returns nil if m is nil. +func MessageV1(m GeneratedMessage) protoiface.MessageV1 { + return protoimpl.X.ProtoMessageV1Of(m) +} + +// MessageV2 converts either a v1 or v2 message to a v2 message. +// It returns nil if m is nil. +func MessageV2(m GeneratedMessage) protoV2.Message { + return protoimpl.X.ProtoMessageV2Of(m) +} + +// MessageReflect returns a reflective view for a message. +// It returns nil if m is nil. +func MessageReflect(m Message) protoreflect.Message { + return protoimpl.X.MessageOf(m) +} + +// Marshaler is implemented by messages that can marshal themselves. +// This interface is used by the following functions: Size, Marshal, +// Buffer.Marshal, and Buffer.EncodeMessage. +// +// Deprecated: Do not implement. +type Marshaler interface { + // Marshal formats the encoded bytes of the message. + // It should be deterministic and emit valid protobuf wire data. + // The caller takes ownership of the returned buffer. + Marshal() ([]byte, error) +} + +// Unmarshaler is implemented by messages that can unmarshal themselves. +// This interface is used by the following functions: Unmarshal, UnmarshalMerge, +// Buffer.Unmarshal, Buffer.DecodeMessage, and Buffer.DecodeGroup. +// +// Deprecated: Do not implement. +type Unmarshaler interface { + // Unmarshal parses the encoded bytes of the protobuf wire input. + // The provided buffer is only valid for during method call. + // It should not reset the receiver message. + Unmarshal([]byte) error +} + +// Merger is implemented by messages that can merge themselves. +// This interface is used by the following functions: Clone and Merge. +// +// Deprecated: Do not implement. +type Merger interface { + // Merge merges the contents of src into the receiver message. + // It clones all data structures in src such that it aliases no mutable + // memory referenced by src. + Merge(src Message) +} + +// RequiredNotSetError is an error type returned when +// marshaling or unmarshaling a message with missing required fields. +type RequiredNotSetError struct { + err error +} + +func (e *RequiredNotSetError) Error() string { + if e.err != nil { + return e.err.Error() + } + return "proto: required field not set" +} +func (e *RequiredNotSetError) RequiredNotSet() bool { + return true +} + +func checkRequiredNotSet(m protoV2.Message) error { + if err := protoV2.CheckInitialized(m); err != nil { + return &RequiredNotSetError{err: err} + } + return nil +} + +// Clone returns a deep copy of src. +func Clone(src Message) Message { + return MessageV1(protoV2.Clone(MessageV2(src))) +} + +// Merge merges src into dst, which must be messages of the same type. +// +// Populated scalar fields in src are copied to dst, while populated +// singular messages in src are merged into dst by recursively calling Merge. +// The elements of every list field in src is appended to the corresponded +// list fields in dst. The entries of every map field in src is copied into +// the corresponding map field in dst, possibly replacing existing entries. +// The unknown fields of src are appended to the unknown fields of dst. +func Merge(dst, src Message) { + protoV2.Merge(MessageV2(dst), MessageV2(src)) +} + +// Equal reports whether two messages are equal. +// If two messages marshal to the same bytes under deterministic serialization, +// then Equal is guaranteed to report true. +// +// Two messages are equal if they are the same protobuf message type, +// have the same set of populated known and extension field values, +// and the same set of unknown fields values. +// +// Scalar values are compared with the equivalent of the == operator in Go, +// except bytes values which are compared using bytes.Equal and +// floating point values which specially treat NaNs as equal. +// Message values are compared by recursively calling Equal. +// Lists are equal if each element value is also equal. +// Maps are equal if they have the same set of keys, where the pair of values +// for each key is also equal. +func Equal(x, y Message) bool { + return protoV2.Equal(MessageV2(x), MessageV2(y)) +} + +func isMessageSet(md protoreflect.MessageDescriptor) bool { + ms, ok := md.(interface{ IsMessageSet() bool }) + return ok && ms.IsMessageSet() +} diff --git a/vendor/github.com/golang/protobuf/proto/registry.go b/vendor/github.com/golang/protobuf/proto/registry.go new file mode 100644 index 00000000000..1e7ff642057 --- /dev/null +++ b/vendor/github.com/golang/protobuf/proto/registry.go @@ -0,0 +1,323 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "bytes" + "compress/gzip" + "fmt" + "io/ioutil" + "reflect" + "strings" + "sync" + + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + "google.golang.org/protobuf/runtime/protoimpl" +) + +// filePath is the path to the proto source file. +type filePath = string // e.g., "google/protobuf/descriptor.proto" + +// fileDescGZIP is the compressed contents of the encoded FileDescriptorProto. +type fileDescGZIP = []byte + +var fileCache sync.Map // map[filePath]fileDescGZIP + +// RegisterFile is called from generated code to register the compressed +// FileDescriptorProto with the file path for a proto source file. +// +// Deprecated: Use protoregistry.GlobalFiles.RegisterFile instead. +func RegisterFile(s filePath, d fileDescGZIP) { + // Decompress the descriptor. + zr, err := gzip.NewReader(bytes.NewReader(d)) + if err != nil { + panic(fmt.Sprintf("proto: invalid compressed file descriptor: %v", err)) + } + b, err := ioutil.ReadAll(zr) + if err != nil { + panic(fmt.Sprintf("proto: invalid compressed file descriptor: %v", err)) + } + + // Construct a protoreflect.FileDescriptor from the raw descriptor. + // Note that DescBuilder.Build automatically registers the constructed + // file descriptor with the v2 registry. + protoimpl.DescBuilder{RawDescriptor: b}.Build() + + // Locally cache the raw descriptor form for the file. + fileCache.Store(s, d) +} + +// FileDescriptor returns the compressed FileDescriptorProto given the file path +// for a proto source file. It returns nil if not found. +// +// Deprecated: Use protoregistry.GlobalFiles.FindFileByPath instead. +func FileDescriptor(s filePath) fileDescGZIP { + if v, ok := fileCache.Load(s); ok { + return v.(fileDescGZIP) + } + + // Find the descriptor in the v2 registry. + var b []byte + if fd, _ := protoregistry.GlobalFiles.FindFileByPath(s); fd != nil { + if fd, ok := fd.(interface{ ProtoLegacyRawDesc() []byte }); ok { + b = fd.ProtoLegacyRawDesc() + } else { + // TODO: Use protodesc.ToFileDescriptorProto to construct + // a descriptorpb.FileDescriptorProto and marshal it. + // However, doing so causes the proto package to have a dependency + // on descriptorpb, leading to cyclic dependency issues. + } + } + + // Locally cache the raw descriptor form for the file. + if len(b) > 0 { + v, _ := fileCache.LoadOrStore(s, protoimpl.X.CompressGZIP(b)) + return v.(fileDescGZIP) + } + return nil +} + +// enumName is the name of an enum. For historical reasons, the enum name is +// neither the full Go name nor the full protobuf name of the enum. +// The name is the dot-separated combination of just the proto package that the +// enum is declared within followed by the Go type name of the generated enum. +type enumName = string // e.g., "my.proto.package.GoMessage_GoEnum" + +// enumsByName maps enum values by name to their numeric counterpart. +type enumsByName = map[string]int32 + +// enumsByNumber maps enum values by number to their name counterpart. +type enumsByNumber = map[int32]string + +var enumCache sync.Map // map[enumName]enumsByName +var numFilesCache sync.Map // map[protoreflect.FullName]int + +// RegisterEnum is called from the generated code to register the mapping of +// enum value names to enum numbers for the enum identified by s. +// +// Deprecated: Use protoregistry.GlobalTypes.RegisterEnum instead. +func RegisterEnum(s enumName, _ enumsByNumber, m enumsByName) { + if _, ok := enumCache.Load(s); ok { + panic("proto: duplicate enum registered: " + s) + } + enumCache.Store(s, m) + + // This does not forward registration to the v2 registry since this API + // lacks sufficient information to construct a complete v2 enum descriptor. +} + +// EnumValueMap returns the mapping from enum value names to enum numbers for +// the enum of the given name. It returns nil if not found. +// +// Deprecated: Use protoregistry.GlobalTypes.FindEnumByName instead. +func EnumValueMap(s enumName) enumsByName { + if v, ok := enumCache.Load(s); ok { + return v.(enumsByName) + } + + // Check whether the cache is stale. If the number of files in the current + // package differs, then it means that some enums may have been recently + // registered upstream that we do not know about. + var protoPkg protoreflect.FullName + if i := strings.LastIndexByte(s, '.'); i >= 0 { + protoPkg = protoreflect.FullName(s[:i]) + } + v, _ := numFilesCache.Load(protoPkg) + numFiles, _ := v.(int) + if protoregistry.GlobalFiles.NumFilesByPackage(protoPkg) == numFiles { + return nil // cache is up-to-date; was not found earlier + } + + // Update the enum cache for all enums declared in the given proto package. + numFiles = 0 + protoregistry.GlobalFiles.RangeFilesByPackage(protoPkg, func(fd protoreflect.FileDescriptor) bool { + walkEnums(fd, func(ed protoreflect.EnumDescriptor) { + name := protoimpl.X.LegacyEnumName(ed) + if _, ok := enumCache.Load(name); !ok { + m := make(enumsByName) + evs := ed.Values() + for i := evs.Len() - 1; i >= 0; i-- { + ev := evs.Get(i) + m[string(ev.Name())] = int32(ev.Number()) + } + enumCache.LoadOrStore(name, m) + } + }) + numFiles++ + return true + }) + numFilesCache.Store(protoPkg, numFiles) + + // Check cache again for enum map. + if v, ok := enumCache.Load(s); ok { + return v.(enumsByName) + } + return nil +} + +// walkEnums recursively walks all enums declared in d. +func walkEnums(d interface { + Enums() protoreflect.EnumDescriptors + Messages() protoreflect.MessageDescriptors +}, f func(protoreflect.EnumDescriptor)) { + eds := d.Enums() + for i := eds.Len() - 1; i >= 0; i-- { + f(eds.Get(i)) + } + mds := d.Messages() + for i := mds.Len() - 1; i >= 0; i-- { + walkEnums(mds.Get(i), f) + } +} + +// messageName is the full name of protobuf message. +type messageName = string + +var messageTypeCache sync.Map // map[messageName]reflect.Type + +// RegisterType is called from generated code to register the message Go type +// for a message of the given name. +// +// Deprecated: Use protoregistry.GlobalTypes.RegisterMessage instead. +func RegisterType(m Message, s messageName) { + mt := protoimpl.X.LegacyMessageTypeOf(m, protoreflect.FullName(s)) + if err := protoregistry.GlobalTypes.RegisterMessage(mt); err != nil { + panic(err) + } + messageTypeCache.Store(s, reflect.TypeOf(m)) +} + +// RegisterMapType is called from generated code to register the Go map type +// for a protobuf message representing a map entry. +// +// Deprecated: Do not use. +func RegisterMapType(m interface{}, s messageName) { + t := reflect.TypeOf(m) + if t.Kind() != reflect.Map { + panic(fmt.Sprintf("invalid map kind: %v", t)) + } + if _, ok := messageTypeCache.Load(s); ok { + panic(fmt.Errorf("proto: duplicate proto message registered: %s", s)) + } + messageTypeCache.Store(s, t) +} + +// MessageType returns the message type for a named message. +// It returns nil if not found. +// +// Deprecated: Use protoregistry.GlobalTypes.FindMessageByName instead. +func MessageType(s messageName) reflect.Type { + if v, ok := messageTypeCache.Load(s); ok { + return v.(reflect.Type) + } + + // Derive the message type from the v2 registry. + var t reflect.Type + if mt, _ := protoregistry.GlobalTypes.FindMessageByName(protoreflect.FullName(s)); mt != nil { + t = messageGoType(mt) + } + + // If we could not get a concrete type, it is possible that it is a + // pseudo-message for a map entry. + if t == nil { + d, _ := protoregistry.GlobalFiles.FindDescriptorByName(protoreflect.FullName(s)) + if md, _ := d.(protoreflect.MessageDescriptor); md != nil && md.IsMapEntry() { + kt := goTypeForField(md.Fields().ByNumber(1)) + vt := goTypeForField(md.Fields().ByNumber(2)) + t = reflect.MapOf(kt, vt) + } + } + + // Locally cache the message type for the given name. + if t != nil { + v, _ := messageTypeCache.LoadOrStore(s, t) + return v.(reflect.Type) + } + return nil +} + +func goTypeForField(fd protoreflect.FieldDescriptor) reflect.Type { + switch k := fd.Kind(); k { + case protoreflect.EnumKind: + if et, _ := protoregistry.GlobalTypes.FindEnumByName(fd.Enum().FullName()); et != nil { + return enumGoType(et) + } + return reflect.TypeOf(protoreflect.EnumNumber(0)) + case protoreflect.MessageKind, protoreflect.GroupKind: + if mt, _ := protoregistry.GlobalTypes.FindMessageByName(fd.Message().FullName()); mt != nil { + return messageGoType(mt) + } + return reflect.TypeOf((*protoreflect.Message)(nil)).Elem() + default: + return reflect.TypeOf(fd.Default().Interface()) + } +} + +func enumGoType(et protoreflect.EnumType) reflect.Type { + return reflect.TypeOf(et.New(0)) +} + +func messageGoType(mt protoreflect.MessageType) reflect.Type { + return reflect.TypeOf(MessageV1(mt.Zero().Interface())) +} + +// MessageName returns the full protobuf name for the given message type. +// +// Deprecated: Use protoreflect.MessageDescriptor.FullName instead. +func MessageName(m Message) messageName { + if m == nil { + return "" + } + if m, ok := m.(interface{ XXX_MessageName() messageName }); ok { + return m.XXX_MessageName() + } + return messageName(protoimpl.X.MessageDescriptorOf(m).FullName()) +} + +// RegisterExtension is called from the generated code to register +// the extension descriptor. +// +// Deprecated: Use protoregistry.GlobalTypes.RegisterExtension instead. +func RegisterExtension(d *ExtensionDesc) { + if err := protoregistry.GlobalTypes.RegisterExtension(d); err != nil { + panic(err) + } +} + +type extensionsByNumber = map[int32]*ExtensionDesc + +var extensionCache sync.Map // map[messageName]extensionsByNumber + +// RegisteredExtensions returns a map of the registered extensions for the +// provided protobuf message, indexed by the extension field number. +// +// Deprecated: Use protoregistry.GlobalTypes.RangeExtensionsByMessage instead. +func RegisteredExtensions(m Message) extensionsByNumber { + // Check whether the cache is stale. If the number of extensions for + // the given message differs, then it means that some extensions were + // recently registered upstream that we do not know about. + s := MessageName(m) + v, _ := extensionCache.Load(s) + xs, _ := v.(extensionsByNumber) + if protoregistry.GlobalTypes.NumExtensionsByMessage(protoreflect.FullName(s)) == len(xs) { + return xs // cache is up-to-date + } + + // Cache is stale, re-compute the extensions map. + xs = make(extensionsByNumber) + protoregistry.GlobalTypes.RangeExtensionsByMessage(protoreflect.FullName(s), func(xt protoreflect.ExtensionType) bool { + if xd, ok := xt.(*ExtensionDesc); ok { + xs[int32(xt.TypeDescriptor().Number())] = xd + } else { + // TODO: This implies that the protoreflect.ExtensionType is a + // custom type not generated by protoc-gen-go. We could try and + // convert the type to an ExtensionDesc. + } + return true + }) + extensionCache.Store(s, xs) + return xs +} diff --git a/vendor/github.com/golang/protobuf/proto/table_marshal.go b/vendor/github.com/golang/protobuf/proto/table_marshal.go deleted file mode 100644 index 5cb11fa955e..00000000000 --- a/vendor/github.com/golang/protobuf/proto/table_marshal.go +++ /dev/null @@ -1,2776 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// a sizer takes a pointer to a field and the size of its tag, computes the size of -// the encoded data. -type sizer func(pointer, int) int - -// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format), -// marshals the field to the end of the slice, returns the slice and error (if any). -type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) - -// marshalInfo is the information used for marshaling a message. -type marshalInfo struct { - typ reflect.Type - fields []*marshalFieldInfo - unrecognized field // offset of XXX_unrecognized - extensions field // offset of XXX_InternalExtensions - v1extensions field // offset of XXX_extensions - sizecache field // offset of XXX_sizecache - initialized int32 // 0 -- only typ is set, 1 -- fully initialized - messageset bool // uses message set wire format - hasmarshaler bool // has custom marshaler - sync.RWMutex // protect extElems map, also for initialization - extElems map[int32]*marshalElemInfo // info of extension elements -} - -// marshalFieldInfo is the information used for marshaling a field of a message. -type marshalFieldInfo struct { - field field - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isPointer bool - required bool // field is required - name string // name of the field, for error reporting - oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements -} - -// marshalElemInfo is the information used for marshaling an extension or oneof element. -type marshalElemInfo struct { - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only) - deref bool // dereference the pointer before operating on it; implies isptr -} - -var ( - marshalInfoMap = map[reflect.Type]*marshalInfo{} - marshalInfoLock sync.Mutex -) - -// getMarshalInfo returns the information to marshal a given type of message. -// The info it returns may not necessarily initialized. -// t is the type of the message (NOT the pointer to it). -func getMarshalInfo(t reflect.Type) *marshalInfo { - marshalInfoLock.Lock() - u, ok := marshalInfoMap[t] - if !ok { - u = &marshalInfo{typ: t} - marshalInfoMap[t] = u - } - marshalInfoLock.Unlock() - return u -} - -// Size is the entry point from generated code, -// and should be ONLY called by generated code. -// It computes the size of encoded data of msg. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Size(msg Message) int { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return 0 - } - return u.size(ptr) -} - -// Marshal is the entry point from generated code, -// and should be ONLY called by generated code. -// It marshals msg to the end of b. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return b, ErrNil - } - return u.marshal(b, ptr, deterministic) -} - -func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo { - // u := a.marshal, but atomically. - // We use an atomic here to ensure memory consistency. - u := atomicLoadMarshalInfo(&a.marshal) - if u == nil { - // Get marshal information from type of message. - t := reflect.ValueOf(msg).Type() - if t.Kind() != reflect.Ptr { - panic(fmt.Sprintf("cannot handle non-pointer message type %v", t)) - } - u = getMarshalInfo(t.Elem()) - // Store it in the cache for later users. - // a.marshal = u, but atomically. - atomicStoreMarshalInfo(&a.marshal, u) - } - return u -} - -// size is the main function to compute the size of the encoded data of a message. -// ptr is the pointer to the message. -func (u *marshalInfo) size(ptr pointer) int { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b, _ := m.Marshal() - return len(b) - } - - n := 0 - for _, f := range u.fields { - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - n += f.sizer(ptr.offset(f.field), f.tagsize) - } - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - n += u.sizeMessageSet(e) - } else { - n += u.sizeExtensions(e) - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - n += u.sizeV1Extensions(m) - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - n += len(s) - } - // cache the result for use in marshal - if u.sizecache.IsValid() { - atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n)) - } - return n -} - -// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated), -// fall back to compute the size. -func (u *marshalInfo) cachedsize(ptr pointer) int { - if u.sizecache.IsValid() { - return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32())) - } - return u.size(ptr) -} - -// marshal is the main function to marshal a message. It takes a byte slice and appends -// the encoded data to the end of the slice, returns the slice and error (if any). -// ptr is the pointer to the message. -// If deterministic is true, map is marshaled in deterministic order. -func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b1, err := m.Marshal() - b = append(b, b1...) - return b, err - } - - var err, errLater error - // The old marshaler encodes extensions at beginning. - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - b, err = u.appendMessageSet(b, e, deterministic) - } else { - b, err = u.appendExtensions(b, e, deterministic) - } - if err != nil { - return b, err - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - b, err = u.appendV1Extensions(b, m, deterministic) - if err != nil { - return b, err - } - } - for _, f := range u.fields { - if f.required { - if ptr.offset(f.field).getPointer().isNil() { - // Required field is not set. - // We record the error but keep going, to give a complete marshaling. - if errLater == nil { - errLater = &RequiredNotSetError{f.name} - } - continue - } - } - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic) - if err != nil { - if err1, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errLater == nil { - errLater = &RequiredNotSetError{f.name + "." + err1.field} - } - continue - } - if err == errRepeatedHasNil { - err = errors.New("proto: repeated field " + f.name + " has nil element") - } - if err == errInvalidUTF8 { - if errLater == nil { - fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name - errLater = &invalidUTF8Error{fullName} - } - continue - } - return b, err - } - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - b = append(b, s...) - } - return b, errLater -} - -// computeMarshalInfo initializes the marshal info. -func (u *marshalInfo) computeMarshalInfo() { - u.Lock() - defer u.Unlock() - if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock - return - } - - t := u.typ - u.unrecognized = invalidField - u.extensions = invalidField - u.v1extensions = invalidField - u.sizecache = invalidField - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if reflect.PtrTo(t).Implements(marshalerType) { - u.hasmarshaler = true - atomic.StoreInt32(&u.initialized, 1) - return - } - - // get oneof implementers - var oneofImplementers []interface{} - switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) { - case oneofFuncsIface: - _, _, _, oneofImplementers = m.XXX_OneofFuncs() - case oneofWrappersIface: - oneofImplementers = m.XXX_OneofWrappers() - } - - n := t.NumField() - - // deal with XXX fields first - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if !strings.HasPrefix(f.Name, "XXX_") { - continue - } - switch f.Name { - case "XXX_sizecache": - u.sizecache = toField(&f) - case "XXX_unrecognized": - u.unrecognized = toField(&f) - case "XXX_InternalExtensions": - u.extensions = toField(&f) - u.messageset = f.Tag.Get("protobuf_messageset") == "1" - case "XXX_extensions": - u.v1extensions = toField(&f) - case "XXX_NoUnkeyedLiteral": - // nothing to do - default: - panic("unknown XXX field: " + f.Name) - } - n-- - } - - // normal fields - fields := make([]marshalFieldInfo, n) // batch allocation - u.fields = make([]*marshalFieldInfo, 0, n) - for i, j := 0, 0; i < t.NumField(); i++ { - f := t.Field(i) - - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - field := &fields[j] - j++ - field.name = f.Name - u.fields = append(u.fields, field) - if f.Tag.Get("protobuf_oneof") != "" { - field.computeOneofFieldInfo(&f, oneofImplementers) - continue - } - if f.Tag.Get("protobuf") == "" { - // field has no tag (not in generated message), ignore it - u.fields = u.fields[:len(u.fields)-1] - j-- - continue - } - field.computeMarshalFieldInfo(&f) - } - - // fields are marshaled in tag order on the wire. - sort.Sort(byTag(u.fields)) - - atomic.StoreInt32(&u.initialized, 1) -} - -// helper for sorting fields by tag -type byTag []*marshalFieldInfo - -func (a byTag) Len() int { return len(a) } -func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag } - -// getExtElemInfo returns the information to marshal an extension element. -// The info it returns is initialized. -func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo { - // get from cache first - u.RLock() - e, ok := u.extElems[desc.Field] - u.RUnlock() - if ok { - return e - } - - t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct - tags := strings.Split(desc.Tag, ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - if t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct { - t = t.Elem() - } - sizer, marshaler := typeMarshaler(t, tags, false, false) - var deref bool - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - t = reflect.PtrTo(t) - deref = true - } - e = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - isptr: t.Kind() == reflect.Ptr, - deref: deref, - } - - // update cache - u.Lock() - if u.extElems == nil { - u.extElems = make(map[int32]*marshalElemInfo) - } - u.extElems[desc.Field] = e - u.Unlock() - return e -} - -// computeMarshalFieldInfo fills up the information to marshal a field. -func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { - // parse protobuf tag of the field. - // tag has format of "bytes,49,opt,name=foo,def=hello!" - tags := strings.Split(f.Tag.Get("protobuf"), ",") - if tags[0] == "" { - return - } - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - if tags[2] == "req" { - fi.required = true - } - fi.setTag(f, tag, wt) - fi.setMarshaler(f, tags) -} - -func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { - fi.field = toField(f) - fi.wiretag = math.MaxInt32 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. - fi.isPointer = true - fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) - fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) - - ityp := f.Type // interface type - for _, o := range oneofImplementers { - t := reflect.TypeOf(o) - if !t.Implements(ityp) { - continue - } - sf := t.Elem().Field(0) // oneof implementer is a struct with a single field - tags := strings.Split(sf.Tag.Get("protobuf"), ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value - fi.oneofElems[t.Elem()] = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - } - } -} - -// wiretype returns the wire encoding of the type. -func wiretype(encoding string) uint64 { - switch encoding { - case "fixed32": - return WireFixed32 - case "fixed64": - return WireFixed64 - case "varint", "zigzag32", "zigzag64": - return WireVarint - case "bytes": - return WireBytes - case "group": - return WireStartGroup - } - panic("unknown wire type " + encoding) -} - -// setTag fills up the tag (in wire format) and its size in the info of a field. -func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) { - fi.field = toField(f) - fi.wiretag = uint64(tag)<<3 | wt - fi.tagsize = SizeVarint(uint64(tag) << 3) -} - -// setMarshaler fills up the sizer and marshaler in the info of a field. -func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) { - switch f.Type.Kind() { - case reflect.Map: - // map field - fi.isPointer = true - fi.sizer, fi.marshaler = makeMapMarshaler(f) - return - case reflect.Ptr, reflect.Slice: - fi.isPointer = true - } - fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false) -} - -// typeMarshaler returns the sizer and marshaler of a given field. -// t is the type of the field. -// tags is the generated "protobuf" tag of the field. -// If nozero is true, zero value is not marshaled to the wire. -// If oneof is true, it is a oneof field. -func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) { - encoding := tags[0] - - pointer := false - slice := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - packed := false - proto3 := false - validateUTF8 := true - for i := 2; i < len(tags); i++ { - if tags[i] == "packed" { - packed = true - } - if tags[i] == "proto3" { - proto3 = true - } - } - validateUTF8 = validateUTF8 && proto3 - - switch t.Kind() { - case reflect.Bool: - if pointer { - return sizeBoolPtr, appendBoolPtr - } - if slice { - if packed { - return sizeBoolPackedSlice, appendBoolPackedSlice - } - return sizeBoolSlice, appendBoolSlice - } - if nozero { - return sizeBoolValueNoZero, appendBoolValueNoZero - } - return sizeBoolValue, appendBoolValue - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixed32Ptr, appendFixed32Ptr - } - if slice { - if packed { - return sizeFixed32PackedSlice, appendFixed32PackedSlice - } - return sizeFixed32Slice, appendFixed32Slice - } - if nozero { - return sizeFixed32ValueNoZero, appendFixed32ValueNoZero - } - return sizeFixed32Value, appendFixed32Value - case "varint": - if pointer { - return sizeVarint32Ptr, appendVarint32Ptr - } - if slice { - if packed { - return sizeVarint32PackedSlice, appendVarint32PackedSlice - } - return sizeVarint32Slice, appendVarint32Slice - } - if nozero { - return sizeVarint32ValueNoZero, appendVarint32ValueNoZero - } - return sizeVarint32Value, appendVarint32Value - } - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixedS32Ptr, appendFixedS32Ptr - } - if slice { - if packed { - return sizeFixedS32PackedSlice, appendFixedS32PackedSlice - } - return sizeFixedS32Slice, appendFixedS32Slice - } - if nozero { - return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero - } - return sizeFixedS32Value, appendFixedS32Value - case "varint": - if pointer { - return sizeVarintS32Ptr, appendVarintS32Ptr - } - if slice { - if packed { - return sizeVarintS32PackedSlice, appendVarintS32PackedSlice - } - return sizeVarintS32Slice, appendVarintS32Slice - } - if nozero { - return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero - } - return sizeVarintS32Value, appendVarintS32Value - case "zigzag32": - if pointer { - return sizeZigzag32Ptr, appendZigzag32Ptr - } - if slice { - if packed { - return sizeZigzag32PackedSlice, appendZigzag32PackedSlice - } - return sizeZigzag32Slice, appendZigzag32Slice - } - if nozero { - return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero - } - return sizeZigzag32Value, appendZigzag32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixed64Ptr, appendFixed64Ptr - } - if slice { - if packed { - return sizeFixed64PackedSlice, appendFixed64PackedSlice - } - return sizeFixed64Slice, appendFixed64Slice - } - if nozero { - return sizeFixed64ValueNoZero, appendFixed64ValueNoZero - } - return sizeFixed64Value, appendFixed64Value - case "varint": - if pointer { - return sizeVarint64Ptr, appendVarint64Ptr - } - if slice { - if packed { - return sizeVarint64PackedSlice, appendVarint64PackedSlice - } - return sizeVarint64Slice, appendVarint64Slice - } - if nozero { - return sizeVarint64ValueNoZero, appendVarint64ValueNoZero - } - return sizeVarint64Value, appendVarint64Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixedS64Ptr, appendFixedS64Ptr - } - if slice { - if packed { - return sizeFixedS64PackedSlice, appendFixedS64PackedSlice - } - return sizeFixedS64Slice, appendFixedS64Slice - } - if nozero { - return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero - } - return sizeFixedS64Value, appendFixedS64Value - case "varint": - if pointer { - return sizeVarintS64Ptr, appendVarintS64Ptr - } - if slice { - if packed { - return sizeVarintS64PackedSlice, appendVarintS64PackedSlice - } - return sizeVarintS64Slice, appendVarintS64Slice - } - if nozero { - return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero - } - return sizeVarintS64Value, appendVarintS64Value - case "zigzag64": - if pointer { - return sizeZigzag64Ptr, appendZigzag64Ptr - } - if slice { - if packed { - return sizeZigzag64PackedSlice, appendZigzag64PackedSlice - } - return sizeZigzag64Slice, appendZigzag64Slice - } - if nozero { - return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero - } - return sizeZigzag64Value, appendZigzag64Value - } - case reflect.Float32: - if pointer { - return sizeFloat32Ptr, appendFloat32Ptr - } - if slice { - if packed { - return sizeFloat32PackedSlice, appendFloat32PackedSlice - } - return sizeFloat32Slice, appendFloat32Slice - } - if nozero { - return sizeFloat32ValueNoZero, appendFloat32ValueNoZero - } - return sizeFloat32Value, appendFloat32Value - case reflect.Float64: - if pointer { - return sizeFloat64Ptr, appendFloat64Ptr - } - if slice { - if packed { - return sizeFloat64PackedSlice, appendFloat64PackedSlice - } - return sizeFloat64Slice, appendFloat64Slice - } - if nozero { - return sizeFloat64ValueNoZero, appendFloat64ValueNoZero - } - return sizeFloat64Value, appendFloat64Value - case reflect.String: - if validateUTF8 { - if pointer { - return sizeStringPtr, appendUTF8StringPtr - } - if slice { - return sizeStringSlice, appendUTF8StringSlice - } - if nozero { - return sizeStringValueNoZero, appendUTF8StringValueNoZero - } - return sizeStringValue, appendUTF8StringValue - } - if pointer { - return sizeStringPtr, appendStringPtr - } - if slice { - return sizeStringSlice, appendStringSlice - } - if nozero { - return sizeStringValueNoZero, appendStringValueNoZero - } - return sizeStringValue, appendStringValue - case reflect.Slice: - if slice { - return sizeBytesSlice, appendBytesSlice - } - if oneof { - // Oneof bytes field may also have "proto3" tag. - // We want to marshal it as a oneof field. Do this - // check before the proto3 check. - return sizeBytesOneof, appendBytesOneof - } - if proto3 { - return sizeBytes3, appendBytes3 - } - return sizeBytes, appendBytes - case reflect.Struct: - switch encoding { - case "group": - if slice { - return makeGroupSliceMarshaler(getMarshalInfo(t)) - } - return makeGroupMarshaler(getMarshalInfo(t)) - case "bytes": - if slice { - return makeMessageSliceMarshaler(getMarshalInfo(t)) - } - return makeMessageMarshaler(getMarshalInfo(t)) - } - } - panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding)) -} - -// Below are functions to size/marshal a specific type of a field. -// They are stored in the field's info, and called by function pointers. -// They have type sizer or marshaler. - -func sizeFixed32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixed32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixedS32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFloat32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - return (4 + tagsize) * len(s) -} -func sizeFloat32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixed64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixed64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFixedS64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFloat64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - return (8 + tagsize) * len(s) -} -func sizeFloat64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeVarint32Value(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarint32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarint32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarint64Value(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - return SizeVarint(v) + tagsize -} -func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return SizeVarint(v) + tagsize -} -func sizeVarint64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return SizeVarint(*p) + tagsize -} -func sizeVarint64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(v) + tagsize - } - return n -} -func sizeVarint64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize - } - return n -} -func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize - } - return n -} -func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeBoolValue(_ pointer, tagsize int) int { - return 1 + tagsize -} -func sizeBoolValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toBool() - if !v { - return 0 - } - return 1 + tagsize -} -func sizeBoolPtr(ptr pointer, tagsize int) int { - p := *ptr.toBoolPtr() - if p == nil { - return 0 - } - return 1 + tagsize -} -func sizeBoolSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - return (1 + tagsize) * len(s) -} -func sizeBoolPackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return 0 - } - return len(s) + SizeVarint(uint64(len(s))) + tagsize -} -func sizeStringValue(ptr pointer, tagsize int) int { - v := *ptr.toString() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toString() - if v == "" { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringPtr(ptr pointer, tagsize int) int { - p := *ptr.toStringPtr() - if p == nil { - return 0 - } - v := *p - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringSlice(ptr pointer, tagsize int) int { - s := *ptr.toStringSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} -func sizeBytes(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if v == nil { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytes3(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if len(v) == 0 { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesOneof(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesSlice(ptr pointer, tagsize int) int { - s := *ptr.toBytesSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} - -// appendFixed32 appends an encoded fixed32 to b. -func appendFixed32(b []byte, v uint32) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24)) - return b -} - -// appendFixed64 appends an encoded fixed64 to b. -func appendFixed64(b []byte, v uint64) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24), - byte(v>>32), - byte(v>>40), - byte(v>>48), - byte(v>>56)) - return b -} - -// appendVarint appends an encoded varint to b. -func appendVarint(b []byte, v uint64) []byte { - // TODO: make 1-byte (maybe 2-byte) case inline-able, once we - // have non-leaf inliner. - switch { - case v < 1<<7: - b = append(b, byte(v)) - case v < 1<<14: - b = append(b, - byte(v&0x7f|0x80), - byte(v>>7)) - case v < 1<<21: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte(v>>14)) - case v < 1<<28: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte(v>>21)) - case v < 1<<35: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte(v>>28)) - case v < 1<<42: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte(v>>35)) - case v < 1<<49: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte(v>>42)) - case v < 1<<56: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte(v>>49)) - case v < 1<<63: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte(v>>56)) - default: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte((v>>56)&0x7f|0x80), - 1) - } - return b -} - -func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, *p) - return b, nil -} -func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(*p)) - return b, nil -} -func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(*p)) - return b, nil -} -func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, *p) - return b, nil -} -func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(*p)) - return b, nil -} -func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(*p)) - return b, nil -} -func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, *p) - return b, nil -} -func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - } - return b, nil -} -func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, v) - } - return b, nil -} -func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - if !v { - return b, nil - } - b = appendVarint(b, wiretag) - b = append(b, 1) - return b, nil -} - -func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toBoolPtr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - if *p { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(len(s))) - for _, v := range s { - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - if v == "" { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toStringPtr() - if p == nil { - return b, nil - } - v := *p - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toStringSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} -func appendUTF8StringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - v := *ptr.toString() - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - v := *ptr.toString() - if v == "" { - return b, nil - } - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - p := *ptr.toStringPtr() - if p == nil { - return b, nil - } - v := *p - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendUTF8StringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - var invalidUTF8 bool - s := *ptr.toStringSlice() - for _, v := range s { - if !utf8.ValidString(v) { - invalidUTF8 = true - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - if invalidUTF8 { - return b, errInvalidUTF8 - } - return b, nil -} -func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if v == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if len(v) == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBytesSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} - -// makeGroupMarshaler returns the sizer and marshaler for a group. -// u is the marshal info of the underlying message. -func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - return u.size(p) + 2*tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - var err error - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, p, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - return b, err - } -} - -// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice. -// u is the marshal info of the underlying message. -func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - n += u.size(v) + 2*tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err error - var nerr nonFatal - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, v, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - if !nerr.Merge(err) { - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, nerr.E - } -} - -// makeMessageMarshaler returns the sizer and marshaler for a message field. -// u is the marshal info of the message. -func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - siz := u.size(p) - return siz + SizeVarint(uint64(siz)) + tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(p) - b = appendVarint(b, uint64(siz)) - return u.marshal(b, p, deterministic) - } -} - -// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice. -// u is the marshal info of the message. -func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - siz := u.size(v) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err error - var nerr nonFatal - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(v) - b = appendVarint(b, uint64(siz)) - b, err = u.marshal(b, v, deterministic) - - if !nerr.Merge(err) { - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, nerr.E - } -} - -// makeMapMarshaler returns the sizer and marshaler for a map field. -// f is the pointer to the reflect data structure of the field. -func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) { - // figure out key and value type - t := f.Type - keyType := t.Key() - valType := t.Elem() - keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",") - valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") - keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map - valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map - keyWireTag := 1<<3 | wiretype(keyTags[0]) - valWireTag := 2<<3 | wiretype(valTags[0]) - - // We create an interface to get the addresses of the map key and value. - // If value is pointer-typed, the interface is a direct interface, the - // idata itself is the value. Otherwise, the idata is the pointer to the - // value. - // Key cannot be pointer-typed. - valIsPtr := valType.Kind() == reflect.Ptr - - // If value is a message with nested maps, calling - // valSizer in marshal may be quadratic. We should use - // cached version in marshal (but not in size). - // If value is not message type, we don't have size cache, - // but it cannot be nested either. Just use valSizer. - valCachedSizer := valSizer - if valIsPtr && valType.Elem().Kind() == reflect.Struct { - u := getMarshalInfo(valType.Elem()) - valCachedSizer = func(ptr pointer, tagsize int) int { - // Same as message sizer, but use cache. - p := ptr.getPointer() - if p.isNil() { - return 0 - } - siz := u.cachedsize(p) - return siz + SizeVarint(uint64(siz)) + tagsize - } - } - return func(ptr pointer, tagsize int) int { - m := ptr.asPointerTo(t).Elem() // the map - n := 0 - for _, k := range m.MapKeys() { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr, false) // pointer to value - siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) { - m := ptr.asPointerTo(t).Elem() // the map - var err error - keys := m.MapKeys() - if len(keys) > 1 && deterministic { - sort.Sort(mapKeys(keys)) - } - - var nerr nonFatal - for _, k := range keys { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr, false) // pointer to value - b = appendVarint(b, tag) - siz := keySizer(kaddr, 1) + valCachedSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - b = appendVarint(b, uint64(siz)) - b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic) - if !nerr.Merge(err) { - return b, err - } - b, err = valMarshaler(b, vaddr, valWireTag, deterministic) - if err != ErrNil && !nerr.Merge(err) { // allow nil value in map - return b, err - } - } - return b, nerr.E - } -} - -// makeOneOfMarshaler returns the sizer and marshaler for a oneof field. -// fi is the marshal info of the field. -// f is the pointer to the reflect data structure of the field. -func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) { - // Oneof field is an interface. We need to get the actual data type on the fly. - t := f.Type - return func(ptr pointer, _ int) int { - p := ptr.getInterfacePointer() - if p.isNil() { - return 0 - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - e := fi.oneofElems[telem] - return e.sizer(p, e.tagsize) - }, - func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) { - p := ptr.getInterfacePointer() - if p.isNil() { - return b, nil - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() { - return b, errOneofHasNil - } - e := fi.oneofElems[telem] - return e.marshaler(b, p, e.wiretag, deterministic) - } -} - -// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field. -func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - n += ei.sizer(p, ei.tagsize) - } - mu.Unlock() - return n -} - -// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b. -func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - var nerr nonFatal - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E - } - - // Sort the keys to provide a deterministic encoding. - // Not sure this is required, but the old code does it. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// message set format is: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } - -// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field -// in message set format (above). -func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for id, e := range m { - n += 2 // start group, end group. tag = 1 (size=1) - n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - siz := len(msgWithLen) - n += siz + 1 // message, tag = 3 (size=1) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - n += ei.sizer(p, 1) // message, tag = 3 (size=1) - } - mu.Unlock() - return n -} - -// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above) -// to the end of byte slice b. -func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - var nerr nonFatal - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for id, e := range m { - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - if !nerr.Merge(err) { - return b, err - } - b = append(b, 1<<3|WireEndGroup) - } - return b, nerr.E - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, id := range keys { - e := m[int32(id)] - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - b = append(b, 1<<3|WireEndGroup) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// sizeV1Extensions computes the size of encoded data for a V1-API extension field. -func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int { - if m == nil { - return 0 - } - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - n += ei.sizer(p, ei.tagsize) - } - return n -} - -// appendV1Extensions marshals a V1-API extension field to the end of byte slice b. -func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) { - if m == nil { - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - var err error - var nerr nonFatal - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr, ei.deref) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if !nerr.Merge(err) { - return b, err - } - } - return b, nerr.E -} - -// newMarshaler is the interface representing objects that can marshal themselves. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newMarshaler interface { - XXX_Size() int - XXX_Marshal(b []byte, deterministic bool) ([]byte, error) -} - -// Size returns the encoded size of a protocol buffer message. -// This is the main entry point. -func Size(pb Message) int { - if m, ok := pb.(newMarshaler); ok { - return m.XXX_Size() - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, _ := m.Marshal() - return len(b) - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return 0 - } - var info InternalMessageInfo - return info.Size(pb) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, returning the data. -// This is the main entry point. -func Marshal(pb Message) ([]byte, error) { - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - b := make([]byte, 0, siz) - return m.XXX_Marshal(b, false) - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - return m.Marshal() - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return nil, ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - b := make([]byte, 0, siz) - return info.Marshal(b, pb, false) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, writing the result to the -// Buffer. -// This is an alternative entry point. It is not necessary to use -// a Buffer for most applications. -func (p *Buffer) Marshal(pb Message) error { - var err error - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - p.grow(siz) // make sure buf has enough capacity - p.buf, err = m.XXX_Marshal(p.buf, p.deterministic) - return err - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, err := m.Marshal() - p.buf = append(p.buf, b...) - return err - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - p.grow(siz) // make sure buf has enough capacity - p.buf, err = info.Marshal(p.buf, pb, p.deterministic) - return err -} - -// grow grows the buffer's capacity, if necessary, to guarantee space for -// another n bytes. After grow(n), at least n bytes can be written to the -// buffer without another allocation. -func (p *Buffer) grow(n int) { - need := len(p.buf) + n - if need <= cap(p.buf) { - return - } - newCap := len(p.buf) * 2 - if newCap < need { - newCap = need - } - p.buf = append(make([]byte, 0, newCap), p.buf...) -} diff --git a/vendor/github.com/golang/protobuf/proto/table_merge.go b/vendor/github.com/golang/protobuf/proto/table_merge.go deleted file mode 100644 index 5525def6a5d..00000000000 --- a/vendor/github.com/golang/protobuf/proto/table_merge.go +++ /dev/null @@ -1,654 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -// Merge merges the src message into dst. -// This assumes that dst and src of the same type and are non-nil. -func (a *InternalMessageInfo) Merge(dst, src Message) { - mi := atomicLoadMergeInfo(&a.merge) - if mi == nil { - mi = getMergeInfo(reflect.TypeOf(dst).Elem()) - atomicStoreMergeInfo(&a.merge, mi) - } - mi.merge(toPointer(&dst), toPointer(&src)) -} - -type mergeInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []mergeFieldInfo - unrecognized field // Offset of XXX_unrecognized -} - -type mergeFieldInfo struct { - field field // Offset of field, guaranteed to be valid - - // isPointer reports whether the value in the field is a pointer. - // This is true for the following situations: - // * Pointer to struct - // * Pointer to basic type (proto2 only) - // * Slice (first value in slice header is a pointer) - // * String (first value in string header is a pointer) - isPointer bool - - // basicWidth reports the width of the field assuming that it is directly - // embedded in the struct (as is the case for basic types in proto3). - // The possible values are: - // 0: invalid - // 1: bool - // 4: int32, uint32, float32 - // 8: int64, uint64, float64 - basicWidth int - - // Where dst and src are pointers to the types being merged. - merge func(dst, src pointer) -} - -var ( - mergeInfoMap = map[reflect.Type]*mergeInfo{} - mergeInfoLock sync.Mutex -) - -func getMergeInfo(t reflect.Type) *mergeInfo { - mergeInfoLock.Lock() - defer mergeInfoLock.Unlock() - mi := mergeInfoMap[t] - if mi == nil { - mi = &mergeInfo{typ: t} - mergeInfoMap[t] = mi - } - return mi -} - -// merge merges src into dst assuming they are both of type *mi.typ. -func (mi *mergeInfo) merge(dst, src pointer) { - if dst.isNil() { - panic("proto: nil destination") - } - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&mi.initialized) == 0 { - mi.computeMergeInfo() - } - - for _, fi := range mi.fields { - sfp := src.offset(fi.field) - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string - continue - } - if fi.basicWidth > 0 { - switch { - case fi.basicWidth == 1 && !*sfp.toBool(): - continue - case fi.basicWidth == 4 && *sfp.toUint32() == 0: - continue - case fi.basicWidth == 8 && *sfp.toUint64() == 0: - continue - } - } - } - - dfp := dst.offset(fi.field) - fi.merge(dfp, sfp) - } - - // TODO: Make this faster? - out := dst.asPointerTo(mi.typ).Elem() - in := src.asPointerTo(mi.typ).Elem() - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - if mi.unrecognized.IsValid() { - if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 { - *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...) - } - } -} - -func (mi *mergeInfo) computeMergeInfo() { - mi.lock.Lock() - defer mi.lock.Unlock() - if mi.initialized != 0 { - return - } - t := mi.typ - n := t.NumField() - - props := GetProperties(t) - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - mfi := mergeFieldInfo{field: toField(&f)} - tf := f.Type - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - switch tf.Kind() { - case reflect.Ptr, reflect.Slice, reflect.String: - // As a special case, we assume slices and strings are pointers - // since we know that the first field in the SliceSlice or - // StringHeader is a data pointer. - mfi.isPointer = true - case reflect.Bool: - mfi.basicWidth = 1 - case reflect.Int32, reflect.Uint32, reflect.Float32: - mfi.basicWidth = 4 - case reflect.Int64, reflect.Uint64, reflect.Float64: - mfi.basicWidth = 8 - } - } - - // Unwrap tf to get at its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + tf.Name()) - } - - switch tf.Kind() { - case reflect.Int32: - switch { - case isSlice: // E.g., []int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Slice is not defined (see pointer_reflect.go). - /* - sfsp := src.toInt32Slice() - if *sfsp != nil { - dfsp := dst.toInt32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - */ - sfs := src.getInt32Slice() - if sfs != nil { - dfs := dst.getInt32Slice() - dfs = append(dfs, sfs...) - if dfs == nil { - dfs = []int32{} - } - dst.setInt32Slice(dfs) - } - } - case isPointer: // E.g., *int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Ptr is not defined (see pointer_reflect.go). - /* - sfpp := src.toInt32Ptr() - if *sfpp != nil { - dfpp := dst.toInt32Ptr() - if *dfpp == nil { - *dfpp = Int32(**sfpp) - } else { - **dfpp = **sfpp - } - } - */ - sfp := src.getInt32Ptr() - if sfp != nil { - dfp := dst.getInt32Ptr() - if dfp == nil { - dst.setInt32Ptr(*sfp) - } else { - *dfp = *sfp - } - } - } - default: // E.g., int32 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt32(); v != 0 { - *dst.toInt32() = v - } - } - } - case reflect.Int64: - switch { - case isSlice: // E.g., []int64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toInt64Slice() - if *sfsp != nil { - dfsp := dst.toInt64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - } - case isPointer: // E.g., *int64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toInt64Ptr() - if *sfpp != nil { - dfpp := dst.toInt64Ptr() - if *dfpp == nil { - *dfpp = Int64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., int64 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt64(); v != 0 { - *dst.toInt64() = v - } - } - } - case reflect.Uint32: - switch { - case isSlice: // E.g., []uint32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint32Slice() - if *sfsp != nil { - dfsp := dst.toUint32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint32{} - } - } - } - case isPointer: // E.g., *uint32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint32Ptr() - if *sfpp != nil { - dfpp := dst.toUint32Ptr() - if *dfpp == nil { - *dfpp = Uint32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint32 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint32(); v != 0 { - *dst.toUint32() = v - } - } - } - case reflect.Uint64: - switch { - case isSlice: // E.g., []uint64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint64Slice() - if *sfsp != nil { - dfsp := dst.toUint64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint64{} - } - } - } - case isPointer: // E.g., *uint64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint64Ptr() - if *sfpp != nil { - dfpp := dst.toUint64Ptr() - if *dfpp == nil { - *dfpp = Uint64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint64 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint64(); v != 0 { - *dst.toUint64() = v - } - } - } - case reflect.Float32: - switch { - case isSlice: // E.g., []float32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat32Slice() - if *sfsp != nil { - dfsp := dst.toFloat32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float32{} - } - } - } - case isPointer: // E.g., *float32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat32Ptr() - if *sfpp != nil { - dfpp := dst.toFloat32Ptr() - if *dfpp == nil { - *dfpp = Float32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float32 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat32(); v != 0 { - *dst.toFloat32() = v - } - } - } - case reflect.Float64: - switch { - case isSlice: // E.g., []float64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat64Slice() - if *sfsp != nil { - dfsp := dst.toFloat64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float64{} - } - } - } - case isPointer: // E.g., *float64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat64Ptr() - if *sfpp != nil { - dfpp := dst.toFloat64Ptr() - if *dfpp == nil { - *dfpp = Float64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float64 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat64(); v != 0 { - *dst.toFloat64() = v - } - } - } - case reflect.Bool: - switch { - case isSlice: // E.g., []bool - mfi.merge = func(dst, src pointer) { - sfsp := src.toBoolSlice() - if *sfsp != nil { - dfsp := dst.toBoolSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []bool{} - } - } - } - case isPointer: // E.g., *bool - mfi.merge = func(dst, src pointer) { - sfpp := src.toBoolPtr() - if *sfpp != nil { - dfpp := dst.toBoolPtr() - if *dfpp == nil { - *dfpp = Bool(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., bool - mfi.merge = func(dst, src pointer) { - if v := *src.toBool(); v { - *dst.toBool() = v - } - } - } - case reflect.String: - switch { - case isSlice: // E.g., []string - mfi.merge = func(dst, src pointer) { - sfsp := src.toStringSlice() - if *sfsp != nil { - dfsp := dst.toStringSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []string{} - } - } - } - case isPointer: // E.g., *string - mfi.merge = func(dst, src pointer) { - sfpp := src.toStringPtr() - if *sfpp != nil { - dfpp := dst.toStringPtr() - if *dfpp == nil { - *dfpp = String(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., string - mfi.merge = func(dst, src pointer) { - if v := *src.toString(); v != "" { - *dst.toString() = v - } - } - } - case reflect.Slice: - isProto3 := props.Prop[i].proto3 - switch { - case isPointer: - panic("bad pointer in byte slice case in " + tf.Name()) - case tf.Elem().Kind() != reflect.Uint8: - panic("bad element kind in byte slice case in " + tf.Name()) - case isSlice: // E.g., [][]byte - mfi.merge = func(dst, src pointer) { - sbsp := src.toBytesSlice() - if *sbsp != nil { - dbsp := dst.toBytesSlice() - for _, sb := range *sbsp { - if sb == nil { - *dbsp = append(*dbsp, nil) - } else { - *dbsp = append(*dbsp, append([]byte{}, sb...)) - } - } - if *dbsp == nil { - *dbsp = [][]byte{} - } - } - } - default: // E.g., []byte - mfi.merge = func(dst, src pointer) { - sbp := src.toBytes() - if *sbp != nil { - dbp := dst.toBytes() - if !isProto3 || len(*sbp) > 0 { - *dbp = append([]byte{}, *sbp...) - } - } - } - } - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("message field %s without pointer", tf)) - case isSlice: // E.g., []*pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sps := src.getPointerSlice() - if sps != nil { - dps := dst.getPointerSlice() - for _, sp := range sps { - var dp pointer - if !sp.isNil() { - dp = valToPointer(reflect.New(tf)) - mi.merge(dp, sp) - } - dps = append(dps, dp) - } - if dps == nil { - dps = []pointer{} - } - dst.setPointerSlice(dps) - } - } - default: // E.g., *pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sp := src.getPointer() - if !sp.isNil() { - dp := dst.getPointer() - if dp.isNil() { - dp = valToPointer(reflect.New(tf)) - dst.setPointer(dp) - } - mi.merge(dp, sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic("bad pointer or slice in map case in " + tf.Name()) - default: // E.g., map[K]V - mfi.merge = func(dst, src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - dm := dst.asPointerTo(tf).Elem() - if dm.IsNil() { - dm.Set(reflect.MakeMap(tf)) - } - - switch tf.Elem().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(Clone(val.Interface().(Message))) - dm.SetMapIndex(key, val) - } - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - dm.SetMapIndex(key, val) - } - default: // Basic type (e.g., string) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - dm.SetMapIndex(key, val) - } - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic("bad pointer or slice in interface case in " + tf.Name()) - default: // E.g., interface{} - // TODO: Make this faster? - mfi.merge = func(dst, src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - du := dst.asPointerTo(tf).Elem() - typ := su.Elem().Type() - if du.IsNil() || du.Elem().Type() != typ { - du.Set(reflect.New(typ.Elem())) // Initialize interface if empty - } - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - dv := du.Elem().Elem().Field(0) - if dv.Kind() == reflect.Ptr && dv.IsNil() { - dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - Merge(dv.Interface().(Message), sv.Interface().(Message)) - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...))) - default: // Basic type (e.g., string) - dv.Set(sv) - } - } - } - } - default: - panic(fmt.Sprintf("merger not found for type:%s", tf)) - } - mi.fields = append(mi.fields, mfi) - } - - mi.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - mi.unrecognized = toField(&f) - } - - atomic.StoreInt32(&mi.initialized, 1) -} diff --git a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go b/vendor/github.com/golang/protobuf/proto/table_unmarshal.go deleted file mode 100644 index acee2fc5296..00000000000 --- a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go +++ /dev/null @@ -1,2053 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -import ( - "errors" - "fmt" - "io" - "math" - "reflect" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// Unmarshal is the entry point from the generated .pb.go files. -// This function is not intended to be used by non-generated code. -// This function is not subject to any compatibility guarantee. -// msg contains a pointer to a protocol buffer struct. -// b is the data to be unmarshaled into the protocol buffer. -// a is a pointer to a place to store cached unmarshal information. -func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error { - // Load the unmarshal information for this message type. - // The atomic load ensures memory consistency. - u := atomicLoadUnmarshalInfo(&a.unmarshal) - if u == nil { - // Slow path: find unmarshal info for msg, update a with it. - u = getUnmarshalInfo(reflect.TypeOf(msg).Elem()) - atomicStoreUnmarshalInfo(&a.unmarshal, u) - } - // Then do the unmarshaling. - err := u.unmarshal(toPointer(&msg), b) - return err -} - -type unmarshalInfo struct { - typ reflect.Type // type of the protobuf struct - - // 0 = only typ field is initialized - // 1 = completely initialized - initialized int32 - lock sync.Mutex // prevents double initialization - dense []unmarshalFieldInfo // fields indexed by tag # - sparse map[uint64]unmarshalFieldInfo // fields indexed by tag # - reqFields []string // names of required fields - reqMask uint64 // 1< 0 { - // Read tag and wire type. - // Special case 1 and 2 byte varints. - var x uint64 - if b[0] < 128 { - x = uint64(b[0]) - b = b[1:] - } else if len(b) >= 2 && b[1] < 128 { - x = uint64(b[0]&0x7f) + uint64(b[1])<<7 - b = b[2:] - } else { - var n int - x, n = decodeVarint(b) - if n == 0 { - return io.ErrUnexpectedEOF - } - b = b[n:] - } - tag := x >> 3 - wire := int(x) & 7 - - // Dispatch on the tag to one of the unmarshal* functions below. - var f unmarshalFieldInfo - if tag < uint64(len(u.dense)) { - f = u.dense[tag] - } else { - f = u.sparse[tag] - } - if fn := f.unmarshal; fn != nil { - var err error - b, err = fn(b, m.offset(f.field), wire) - if err == nil { - reqMask |= f.reqMask - continue - } - if r, ok := err.(*RequiredNotSetError); ok { - // Remember this error, but keep parsing. We need to produce - // a full parse even if a required field is missing. - if errLater == nil { - errLater = r - } - reqMask |= f.reqMask - continue - } - if err != errInternalBadWireType { - if err == errInvalidUTF8 { - if errLater == nil { - fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name - errLater = &invalidUTF8Error{fullName} - } - continue - } - return err - } - // Fragments with bad wire type are treated as unknown fields. - } - - // Unknown tag. - if !u.unrecognized.IsValid() { - // Don't keep unrecognized data; just skip it. - var err error - b, err = skipField(b, wire) - if err != nil { - return err - } - continue - } - // Keep unrecognized data around. - // maybe in extensions, maybe in the unrecognized field. - z := m.offset(u.unrecognized).toBytes() - var emap map[int32]Extension - var e Extension - for _, r := range u.extensionRanges { - if uint64(r.Start) <= tag && tag <= uint64(r.End) { - if u.extensions.IsValid() { - mp := m.offset(u.extensions).toExtensions() - emap = mp.extensionsWrite() - e = emap[int32(tag)] - z = &e.enc - break - } - if u.oldExtensions.IsValid() { - p := m.offset(u.oldExtensions).toOldExtensions() - emap = *p - if emap == nil { - emap = map[int32]Extension{} - *p = emap - } - e = emap[int32(tag)] - z = &e.enc - break - } - panic("no extensions field available") - } - } - - // Use wire type to skip data. - var err error - b0 := b - b, err = skipField(b, wire) - if err != nil { - return err - } - *z = encodeVarint(*z, tag<<3|uint64(wire)) - *z = append(*z, b0[:len(b0)-len(b)]...) - - if emap != nil { - emap[int32(tag)] = e - } - } - if reqMask != u.reqMask && errLater == nil { - // A required field of this message is missing. - for _, n := range u.reqFields { - if reqMask&1 == 0 { - errLater = &RequiredNotSetError{n} - } - reqMask >>= 1 - } - } - return errLater -} - -// computeUnmarshalInfo fills in u with information for use -// in unmarshaling protocol buffers of type u.typ. -func (u *unmarshalInfo) computeUnmarshalInfo() { - u.lock.Lock() - defer u.lock.Unlock() - if u.initialized != 0 { - return - } - t := u.typ - n := t.NumField() - - // Set up the "not found" value for the unrecognized byte buffer. - // This is the default for proto3. - u.unrecognized = invalidField - u.extensions = invalidField - u.oldExtensions = invalidField - - // List of the generated type and offset for each oneof field. - type oneofField struct { - ityp reflect.Type // interface type of oneof field - field field // offset in containing message - } - var oneofFields []oneofField - - for i := 0; i < n; i++ { - f := t.Field(i) - if f.Name == "XXX_unrecognized" { - // The byte slice used to hold unrecognized input is special. - if f.Type != reflect.TypeOf(([]byte)(nil)) { - panic("bad type for XXX_unrecognized field: " + f.Type.Name()) - } - u.unrecognized = toField(&f) - continue - } - if f.Name == "XXX_InternalExtensions" { - // Ditto here. - if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) { - panic("bad type for XXX_InternalExtensions field: " + f.Type.Name()) - } - u.extensions = toField(&f) - if f.Tag.Get("protobuf_messageset") == "1" { - u.isMessageSet = true - } - continue - } - if f.Name == "XXX_extensions" { - // An older form of the extensions field. - if f.Type != reflect.TypeOf((map[int32]Extension)(nil)) { - panic("bad type for XXX_extensions field: " + f.Type.Name()) - } - u.oldExtensions = toField(&f) - continue - } - if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" { - continue - } - - oneof := f.Tag.Get("protobuf_oneof") - if oneof != "" { - oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)}) - // The rest of oneof processing happens below. - continue - } - - tags := f.Tag.Get("protobuf") - tagArray := strings.Split(tags, ",") - if len(tagArray) < 2 { - panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags) - } - tag, err := strconv.Atoi(tagArray[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tagArray[1]) - } - - name := "" - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - } - - // Extract unmarshaling function from the field (its type and tags). - unmarshal := fieldUnmarshaler(&f) - - // Required field? - var reqMask uint64 - if tagArray[2] == "req" { - bit := len(u.reqFields) - u.reqFields = append(u.reqFields, name) - reqMask = uint64(1) << uint(bit) - // TODO: if we have more than 64 required fields, we end up - // not verifying that all required fields are present. - // Fix this, perhaps using a count of required fields? - } - - // Store the info in the correct slot in the message. - u.setTag(tag, toField(&f), unmarshal, reqMask, name) - } - - // Find any types associated with oneof fields. - var oneofImplementers []interface{} - switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) { - case oneofFuncsIface: - _, _, _, oneofImplementers = m.XXX_OneofFuncs() - case oneofWrappersIface: - oneofImplementers = m.XXX_OneofWrappers() - } - for _, v := range oneofImplementers { - tptr := reflect.TypeOf(v) // *Msg_X - typ := tptr.Elem() // Msg_X - - f := typ.Field(0) // oneof implementers have one field - baseUnmarshal := fieldUnmarshaler(&f) - tags := strings.Split(f.Tag.Get("protobuf"), ",") - fieldNum, err := strconv.Atoi(tags[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tags[1]) - } - var name string - for _, tag := range tags { - if strings.HasPrefix(tag, "name=") { - name = strings.TrimPrefix(tag, "name=") - break - } - } - - // Find the oneof field that this struct implements. - // Might take O(n^2) to process all of the oneofs, but who cares. - for _, of := range oneofFields { - if tptr.Implements(of.ityp) { - // We have found the corresponding interface for this struct. - // That lets us know where this struct should be stored - // when we encounter it during unmarshaling. - unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal) - u.setTag(fieldNum, of.field, unmarshal, 0, name) - } - } - - } - - // Get extension ranges, if any. - fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray") - if fn.IsValid() { - if !u.extensions.IsValid() && !u.oldExtensions.IsValid() { - panic("a message with extensions, but no extensions field in " + t.Name()) - } - u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange) - } - - // Explicitly disallow tag 0. This will ensure we flag an error - // when decoding a buffer of all zeros. Without this code, we - // would decode and skip an all-zero buffer of even length. - // [0 0] is [tag=0/wiretype=varint varint-encoded-0]. - u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) { - return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w) - }, 0, "") - - // Set mask for required field check. - u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here? - for len(u.dense) <= tag { - u.dense = append(u.dense, unmarshalFieldInfo{}) - } - u.dense[tag] = i - return - } - if u.sparse == nil { - u.sparse = map[uint64]unmarshalFieldInfo{} - } - u.sparse[uint64(tag)] = i -} - -// fieldUnmarshaler returns an unmarshaler for the given field. -func fieldUnmarshaler(f *reflect.StructField) unmarshaler { - if f.Type.Kind() == reflect.Map { - return makeUnmarshalMap(f) - } - return typeUnmarshaler(f.Type, f.Tag.Get("protobuf")) -} - -// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. -func typeUnmarshaler(t reflect.Type, tags string) unmarshaler { - tagArray := strings.Split(tags, ",") - encoding := tagArray[0] - name := "unknown" - proto3 := false - validateUTF8 := true - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - if tag == "proto3" { - proto3 = true - } - } - validateUTF8 = validateUTF8 && proto3 - - // Figure out packaging (pointer, slice, or both) - slice := false - pointer := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - // We'll never have both pointer and slice for basic types. - if pointer && slice && t.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + t.Name()) - } - - switch t.Kind() { - case reflect.Bool: - if pointer { - return unmarshalBoolPtr - } - if slice { - return unmarshalBoolSlice - } - return unmarshalBoolValue - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixedS32Ptr - } - if slice { - return unmarshalFixedS32Slice - } - return unmarshalFixedS32Value - case "varint": - // this could be int32 or enum - if pointer { - return unmarshalInt32Ptr - } - if slice { - return unmarshalInt32Slice - } - return unmarshalInt32Value - case "zigzag32": - if pointer { - return unmarshalSint32Ptr - } - if slice { - return unmarshalSint32Slice - } - return unmarshalSint32Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixedS64Ptr - } - if slice { - return unmarshalFixedS64Slice - } - return unmarshalFixedS64Value - case "varint": - if pointer { - return unmarshalInt64Ptr - } - if slice { - return unmarshalInt64Slice - } - return unmarshalInt64Value - case "zigzag64": - if pointer { - return unmarshalSint64Ptr - } - if slice { - return unmarshalSint64Slice - } - return unmarshalSint64Value - } - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixed32Ptr - } - if slice { - return unmarshalFixed32Slice - } - return unmarshalFixed32Value - case "varint": - if pointer { - return unmarshalUint32Ptr - } - if slice { - return unmarshalUint32Slice - } - return unmarshalUint32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixed64Ptr - } - if slice { - return unmarshalFixed64Slice - } - return unmarshalFixed64Value - case "varint": - if pointer { - return unmarshalUint64Ptr - } - if slice { - return unmarshalUint64Slice - } - return unmarshalUint64Value - } - case reflect.Float32: - if pointer { - return unmarshalFloat32Ptr - } - if slice { - return unmarshalFloat32Slice - } - return unmarshalFloat32Value - case reflect.Float64: - if pointer { - return unmarshalFloat64Ptr - } - if slice { - return unmarshalFloat64Slice - } - return unmarshalFloat64Value - case reflect.Map: - panic("map type in typeUnmarshaler in " + t.Name()) - case reflect.Slice: - if pointer { - panic("bad pointer in slice case in " + t.Name()) - } - if slice { - return unmarshalBytesSlice - } - return unmarshalBytesValue - case reflect.String: - if validateUTF8 { - if pointer { - return unmarshalUTF8StringPtr - } - if slice { - return unmarshalUTF8StringSlice - } - return unmarshalUTF8StringValue - } - if pointer { - return unmarshalStringPtr - } - if slice { - return unmarshalStringSlice - } - return unmarshalStringValue - case reflect.Struct: - // message or group field - if !pointer { - panic(fmt.Sprintf("message/group field %s:%s without pointer", t, encoding)) - } - switch encoding { - case "bytes": - if slice { - return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name) - case "group": - if slice { - return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name) - } - } - panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding)) -} - -// Below are all the unmarshalers for individual fields of various types. - -func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64() = v - return b, nil -} - -func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64() = v - return b, nil -} - -func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64() = v - return b, nil -} - -func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64Ptr() = &v - return b, nil -} - -func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - *f.toInt32() = v - return b, nil -} - -func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - *f.toInt32() = v - return b, nil -} - -func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32() = v - return b, nil -} - -func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32Ptr() = &v - return b, nil -} - -func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64() = v - return b[8:], nil -} - -func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64() = v - return b[8:], nil -} - -func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32() = v - return b[4:], nil -} - -func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32Ptr() = &v - return b[4:], nil -} - -func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - *f.toInt32() = v - return b[4:], nil -} - -func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.setInt32Ptr(v) - return b[4:], nil -} - -func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - return b[4:], nil -} - -func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - // Note: any length varint is allowed, even though any sane - // encoder will use one byte. - // See https://github.com/golang/protobuf/issues/76 - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - // TODO: check if x>1? Tests seem to indicate no. - v := x != 0 - *f.toBool() = v - return b[n:], nil -} - -func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - *f.toBoolPtr() = &v - return b[n:], nil -} - -func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - b = b[n:] - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - return b[n:], nil -} - -func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64() = v - return b[8:], nil -} - -func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64Ptr() = &v - return b[8:], nil -} - -func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32() = v - return b[4:], nil -} - -func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32Ptr() = &v - return b[4:], nil -} - -func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toString() = v - return b[x:], nil -} - -func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toStringPtr() = &v - return b[x:], nil -} - -func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - s := f.toStringSlice() - *s = append(*s, v) - return b[x:], nil -} - -func unmarshalUTF8StringValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toString() = v - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -func unmarshalUTF8StringPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - *f.toStringPtr() = &v - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -func unmarshalUTF8StringSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - s := f.toStringSlice() - *s = append(*s, v) - if !utf8.ValidString(v) { - return b[x:], errInvalidUTF8 - } - return b[x:], nil -} - -var emptyBuf [0]byte - -func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // The use of append here is a trick which avoids the zeroing - // that would be required if we used a make/copy pair. - // We append to emptyBuf instead of nil because we want - // a non-nil result even when the length is 0. - v := append(emptyBuf[:], b[:x]...) - *f.toBytes() = v - return b[x:], nil -} - -func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := append(emptyBuf[:], b[:x]...) - s := f.toBytesSlice() - *s = append(*s, v) - return b[x:], nil -} - -func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // First read the message field to see if something is there. - // The semantics of multiple submessages are weird. Instead of - // the last one winning (as it is for all other fields), multiple - // submessages are merged. - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[x:], err - } -} - -func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[x:], err - } -} - -func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[y:], err - } -} - -func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[y:], err - } -} - -func makeUnmarshalMap(f *reflect.StructField) unmarshaler { - t := f.Type - kt := t.Key() - vt := t.Elem() - unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key")) - unmarshalVal := typeUnmarshaler(vt, f.Tag.Get("protobuf_val")) - return func(b []byte, f pointer, w int) ([]byte, error) { - // The map entry is a submessage. Figure out how big it is. - if w != WireBytes { - return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes) - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - r := b[x:] // unused data to return - b = b[:x] // data for map entry - - // Note: we could use #keys * #values ~= 200 functions - // to do map decoding without reflection. Probably not worth it. - // Maps will be somewhat slow. Oh well. - - // Read key and value from data. - var nerr nonFatal - k := reflect.New(kt) - v := reflect.New(vt) - for len(b) > 0 { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - wire := int(x) & 7 - b = b[n:] - - var err error - switch x >> 3 { - case 1: - b, err = unmarshalKey(b, valToPointer(k), wire) - case 2: - b, err = unmarshalVal(b, valToPointer(v), wire) - default: - err = errInternalBadWireType // skip unknown tag - } - - if nerr.Merge(err) { - continue - } - if err != errInternalBadWireType { - return nil, err - } - - // Skip past unknown fields. - b, err = skipField(b, wire) - if err != nil { - return nil, err - } - } - - // Get map, allocate if needed. - m := f.asPointerTo(t).Elem() // an addressable map[K]T - if m.IsNil() { - m.Set(reflect.MakeMap(t)) - } - - // Insert into map. - m.SetMapIndex(k.Elem(), v.Elem()) - - return r, nerr.E - } -} - -// makeUnmarshalOneof makes an unmarshaler for oneof fields. -// for: -// message Msg { -// oneof F { -// int64 X = 1; -// float64 Y = 2; -// } -// } -// typ is the type of the concrete entry for a oneof case (e.g. Msg_X). -// ityp is the interface type of the oneof field (e.g. isMsg_F). -// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64). -// Note that this function will be called once for each case in the oneof. -func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler { - sf := typ.Field(0) - field0 := toField(&sf) - return func(b []byte, f pointer, w int) ([]byte, error) { - // Allocate holder for value. - v := reflect.New(typ) - - // Unmarshal data into holder. - // We unmarshal into the first field of the holder object. - var err error - var nerr nonFatal - b, err = unmarshal(b, valToPointer(v).offset(field0), w) - if !nerr.Merge(err) { - return nil, err - } - - // Write pointer to holder into target field. - f.asPointerTo(ityp).Elem().Set(v) - - return b, nerr.E - } -} - -// Error used by decode internally. -var errInternalBadWireType = errors.New("proto: internal error: bad wiretype") - -// skipField skips past a field of type wire and returns the remaining bytes. -func skipField(b []byte, wire int) ([]byte, error) { - switch wire { - case WireVarint: - _, k := decodeVarint(b) - if k == 0 { - return b, io.ErrUnexpectedEOF - } - b = b[k:] - case WireFixed32: - if len(b) < 4 { - return b, io.ErrUnexpectedEOF - } - b = b[4:] - case WireFixed64: - if len(b) < 8 { - return b, io.ErrUnexpectedEOF - } - b = b[8:] - case WireBytes: - m, k := decodeVarint(b) - if k == 0 || uint64(len(b)-k) < m { - return b, io.ErrUnexpectedEOF - } - b = b[uint64(k)+m:] - case WireStartGroup: - _, i := findEndGroup(b) - if i == -1 { - return b, io.ErrUnexpectedEOF - } - b = b[i:] - default: - return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire) - } - return b, nil -} - -// findEndGroup finds the index of the next EndGroup tag. -// Groups may be nested, so the "next" EndGroup tag is the first -// unpaired EndGroup. -// findEndGroup returns the indexes of the start and end of the EndGroup tag. -// Returns (-1,-1) if it can't find one. -func findEndGroup(b []byte) (int, int) { - depth := 1 - i := 0 - for { - x, n := decodeVarint(b[i:]) - if n == 0 { - return -1, -1 - } - j := i - i += n - switch x & 7 { - case WireVarint: - _, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - case WireFixed32: - if len(b)-4 < i { - return -1, -1 - } - i += 4 - case WireFixed64: - if len(b)-8 < i { - return -1, -1 - } - i += 8 - case WireBytes: - m, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - if uint64(len(b)-i) < m { - return -1, -1 - } - i += int(m) - case WireStartGroup: - depth++ - case WireEndGroup: - depth-- - if depth == 0 { - return j, i - } - default: - return -1, -1 - } - } -} - -// encodeVarint appends a varint-encoded integer to b and returns the result. -func encodeVarint(b []byte, x uint64) []byte { - for x >= 1<<7 { - b = append(b, byte(x&0x7f|0x80)) - x >>= 7 - } - return append(b, byte(x)) -} - -// decodeVarint reads a varint-encoded integer from b. -// Returns the decoded integer and the number of bytes read. -// If there is an error, it returns 0,0. -func decodeVarint(b []byte) (uint64, int) { - var x, y uint64 - if len(b) == 0 { - goto bad - } - x = uint64(b[0]) - if x < 0x80 { - return x, 1 - } - x -= 0x80 - - if len(b) <= 1 { - goto bad - } - y = uint64(b[1]) - x += y << 7 - if y < 0x80 { - return x, 2 - } - x -= 0x80 << 7 - - if len(b) <= 2 { - goto bad - } - y = uint64(b[2]) - x += y << 14 - if y < 0x80 { - return x, 3 - } - x -= 0x80 << 14 - - if len(b) <= 3 { - goto bad - } - y = uint64(b[3]) - x += y << 21 - if y < 0x80 { - return x, 4 - } - x -= 0x80 << 21 - - if len(b) <= 4 { - goto bad - } - y = uint64(b[4]) - x += y << 28 - if y < 0x80 { - return x, 5 - } - x -= 0x80 << 28 - - if len(b) <= 5 { - goto bad - } - y = uint64(b[5]) - x += y << 35 - if y < 0x80 { - return x, 6 - } - x -= 0x80 << 35 - - if len(b) <= 6 { - goto bad - } - y = uint64(b[6]) - x += y << 42 - if y < 0x80 { - return x, 7 - } - x -= 0x80 << 42 - - if len(b) <= 7 { - goto bad - } - y = uint64(b[7]) - x += y << 49 - if y < 0x80 { - return x, 8 - } - x -= 0x80 << 49 - - if len(b) <= 8 { - goto bad - } - y = uint64(b[8]) - x += y << 56 - if y < 0x80 { - return x, 9 - } - x -= 0x80 << 56 - - if len(b) <= 9 { - goto bad - } - y = uint64(b[9]) - x += y << 63 - if y < 2 { - return x, 10 - } - -bad: - return 0, 0 -} diff --git a/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/golang/protobuf/proto/text.go deleted file mode 100644 index d97f9b3563e..00000000000 --- a/vendor/github.com/golang/protobuf/proto/text.go +++ /dev/null @@ -1,845 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for writing the text protocol buffer format. - -import ( - "bufio" - "bytes" - "encoding" - "errors" - "fmt" - "io" - "log" - "math" - "reflect" - "sort" - "strings" -) - -var ( - newline = []byte("\n") - spaces = []byte(" ") - endBraceNewline = []byte("}\n") - backslashN = []byte{'\\', 'n'} - backslashR = []byte{'\\', 'r'} - backslashT = []byte{'\\', 't'} - backslashDQ = []byte{'\\', '"'} - backslashBS = []byte{'\\', '\\'} - posInf = []byte("inf") - negInf = []byte("-inf") - nan = []byte("nan") -) - -type writer interface { - io.Writer - WriteByte(byte) error -} - -// textWriter is an io.Writer that tracks its indentation level. -type textWriter struct { - ind int - complete bool // if the current position is a complete line - compact bool // whether to write out as a one-liner - w writer -} - -func (w *textWriter) WriteString(s string) (n int, err error) { - if !strings.Contains(s, "\n") { - if !w.compact && w.complete { - w.writeIndent() - } - w.complete = false - return io.WriteString(w.w, s) - } - // WriteString is typically called without newlines, so this - // codepath and its copy are rare. We copy to avoid - // duplicating all of Write's logic here. - return w.Write([]byte(s)) -} - -func (w *textWriter) Write(p []byte) (n int, err error) { - newlines := bytes.Count(p, newline) - if newlines == 0 { - if !w.compact && w.complete { - w.writeIndent() - } - n, err = w.w.Write(p) - w.complete = false - return n, err - } - - frags := bytes.SplitN(p, newline, newlines+1) - if w.compact { - for i, frag := range frags { - if i > 0 { - if err := w.w.WriteByte(' '); err != nil { - return n, err - } - n++ - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - } - return n, nil - } - - for i, frag := range frags { - if w.complete { - w.writeIndent() - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - if i+1 < len(frags) { - if err := w.w.WriteByte('\n'); err != nil { - return n, err - } - n++ - } - } - w.complete = len(frags[len(frags)-1]) == 0 - return n, nil -} - -func (w *textWriter) WriteByte(c byte) error { - if w.compact && c == '\n' { - c = ' ' - } - if !w.compact && w.complete { - w.writeIndent() - } - err := w.w.WriteByte(c) - w.complete = c == '\n' - return err -} - -func (w *textWriter) indent() { w.ind++ } - -func (w *textWriter) unindent() { - if w.ind == 0 { - log.Print("proto: textWriter unindented too far") - return - } - w.ind-- -} - -func writeName(w *textWriter, props *Properties) error { - if _, err := w.WriteString(props.OrigName); err != nil { - return err - } - if props.Wire != "group" { - return w.WriteByte(':') - } - return nil -} - -func requiresQuotes(u string) bool { - // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. - for _, ch := range u { - switch { - case ch == '.' || ch == '/' || ch == '_': - continue - case '0' <= ch && ch <= '9': - continue - case 'A' <= ch && ch <= 'Z': - continue - case 'a' <= ch && ch <= 'z': - continue - default: - return true - } - } - return false -} - -// isAny reports whether sv is a google.protobuf.Any message -func isAny(sv reflect.Value) bool { - type wkt interface { - XXX_WellKnownType() string - } - t, ok := sv.Addr().Interface().(wkt) - return ok && t.XXX_WellKnownType() == "Any" -} - -// writeProto3Any writes an expanded google.protobuf.Any message. -// -// It returns (false, nil) if sv value can't be unmarshaled (e.g. because -// required messages are not linked in). -// -// It returns (true, error) when sv was written in expanded format or an error -// was encountered. -func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { - turl := sv.FieldByName("TypeUrl") - val := sv.FieldByName("Value") - if !turl.IsValid() || !val.IsValid() { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - b, ok := val.Interface().([]byte) - if !ok { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - parts := strings.Split(turl.String(), "/") - mt := MessageType(parts[len(parts)-1]) - if mt == nil { - return false, nil - } - m := reflect.New(mt.Elem()) - if err := Unmarshal(b, m.Interface().(Message)); err != nil { - return false, nil - } - w.Write([]byte("[")) - u := turl.String() - if requiresQuotes(u) { - writeString(w, u) - } else { - w.Write([]byte(u)) - } - if w.compact { - w.Write([]byte("]:<")) - } else { - w.Write([]byte("]: <\n")) - w.ind++ - } - if err := tm.writeStruct(w, m.Elem()); err != nil { - return true, err - } - if w.compact { - w.Write([]byte("> ")) - } else { - w.ind-- - w.Write([]byte(">\n")) - } - return true, nil -} - -func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { - if tm.ExpandAny && isAny(sv) { - if canExpand, err := tm.writeProto3Any(w, sv); canExpand { - return err - } - } - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < sv.NumField(); i++ { - fv := sv.Field(i) - props := sprops.Prop[i] - name := st.Field(i).Name - - if name == "XXX_NoUnkeyedLiteral" { - continue - } - - if strings.HasPrefix(name, "XXX_") { - // There are two XXX_ fields: - // XXX_unrecognized []byte - // XXX_extensions map[int32]proto.Extension - // The first is handled here; - // the second is handled at the bottom of this function. - if name == "XXX_unrecognized" && !fv.IsNil() { - if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Field not filled in. This could be an optional field or - // a required field that wasn't filled in. Either way, there - // isn't anything we can show for it. - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - // Repeated field that is empty, or a bytes field that is unused. - continue - } - - if props.Repeated && fv.Kind() == reflect.Slice { - // Repeated field. - for j := 0; j < fv.Len(); j++ { - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - v := fv.Index(j) - if v.Kind() == reflect.Ptr && v.IsNil() { - // A nil message in a repeated field is not valid, - // but we can handle that more gracefully than panicking. - if _, err := w.Write([]byte("\n")); err != nil { - return err - } - continue - } - if err := tm.writeAny(w, v, props); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Map { - // Map fields are rendered as a repeated struct with key/value fields. - keys := fv.MapKeys() - sort.Sort(mapKeys(keys)) - for _, key := range keys { - val := fv.MapIndex(key) - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - // open struct - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - // key - if _, err := w.WriteString("key:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, key, props.MapKeyProp); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - // nil values aren't legal, but we can avoid panicking because of them. - if val.Kind() != reflect.Ptr || !val.IsNil() { - // value - if _, err := w.WriteString("value:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, val, props.MapValProp); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - // close struct - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { - // empty bytes field - continue - } - if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { - // proto3 non-repeated scalar field; skip if zero value - if isProto3Zero(fv) { - continue - } - } - - if fv.Kind() == reflect.Interface { - // Check if it is a oneof. - if st.Field(i).Tag.Get("protobuf_oneof") != "" { - // fv is nil, or holds a pointer to generated struct. - // That generated struct has exactly one field, - // which has a protobuf struct tag. - if fv.IsNil() { - continue - } - inner := fv.Elem().Elem() // interface -> *T -> T - tag := inner.Type().Field(0).Tag.Get("protobuf") - props = new(Properties) // Overwrite the outer props var, but not its pointee. - props.Parse(tag) - // Write the value in the oneof, not the oneof itself. - fv = inner.Field(0) - - // Special case to cope with malformed messages gracefully: - // If the value in the oneof is a nil pointer, don't panic - // in writeAny. - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Use errors.New so writeAny won't render quotes. - msg := errors.New("/* nil */") - fv = reflect.ValueOf(&msg).Elem() - } - } - } - - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - - // Enums have a String method, so writeAny will work fine. - if err := tm.writeAny(w, fv, props); err != nil { - return err - } - - if err := w.WriteByte('\n'); err != nil { - return err - } - } - - // Extensions (the XXX_extensions field). - pv := sv.Addr() - if _, err := extendable(pv.Interface()); err == nil { - if err := tm.writeExtensions(w, pv); err != nil { - return err - } - } - - return nil -} - -var textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() - -// writeAny writes an arbitrary field. -func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { - v = reflect.Indirect(v) - - // Floats have special cases. - if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { - x := v.Float() - var b []byte - switch { - case math.IsInf(x, 1): - b = posInf - case math.IsInf(x, -1): - b = negInf - case math.IsNaN(x): - b = nan - } - if b != nil { - _, err := w.Write(b) - return err - } - // Other values are handled below. - } - - // We don't attempt to serialise every possible value type; only those - // that can occur in protocol buffers. - switch v.Kind() { - case reflect.Slice: - // Should only be a []byte; repeated fields are handled in writeStruct. - if err := writeString(w, string(v.Bytes())); err != nil { - return err - } - case reflect.String: - if err := writeString(w, v.String()); err != nil { - return err - } - case reflect.Struct: - // Required/optional group/message. - var bra, ket byte = '<', '>' - if props != nil && props.Wire == "group" { - bra, ket = '{', '}' - } - if err := w.WriteByte(bra); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if v.CanAddr() { - // Calling v.Interface on a struct causes the reflect package to - // copy the entire struct. This is racy with the new Marshaler - // since we atomically update the XXX_sizecache. - // - // Thus, we retrieve a pointer to the struct if possible to avoid - // a race since v.Interface on the pointer doesn't copy the struct. - // - // If v is not addressable, then we are not worried about a race - // since it implies that the binary Marshaler cannot possibly be - // mutating this value. - v = v.Addr() - } - if v.Type().Implements(textMarshalerType) { - text, err := v.Interface().(encoding.TextMarshaler).MarshalText() - if err != nil { - return err - } - if _, err = w.Write(text); err != nil { - return err - } - } else { - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - if err := tm.writeStruct(w, v); err != nil { - return err - } - } - w.unindent() - if err := w.WriteByte(ket); err != nil { - return err - } - default: - _, err := fmt.Fprint(w, v.Interface()) - return err - } - return nil -} - -// equivalent to C's isprint. -func isprint(c byte) bool { - return c >= 0x20 && c < 0x7f -} - -// writeString writes a string in the protocol buffer text format. -// It is similar to strconv.Quote except we don't use Go escape sequences, -// we treat the string as a byte sequence, and we use octal escapes. -// These differences are to maintain interoperability with the other -// languages' implementations of the text format. -func writeString(w *textWriter, s string) error { - // use WriteByte here to get any needed indent - if err := w.WriteByte('"'); err != nil { - return err - } - // Loop over the bytes, not the runes. - for i := 0; i < len(s); i++ { - var err error - // Divergence from C++: we don't escape apostrophes. - // There's no need to escape them, and the C++ parser - // copes with a naked apostrophe. - switch c := s[i]; c { - case '\n': - _, err = w.w.Write(backslashN) - case '\r': - _, err = w.w.Write(backslashR) - case '\t': - _, err = w.w.Write(backslashT) - case '"': - _, err = w.w.Write(backslashDQ) - case '\\': - _, err = w.w.Write(backslashBS) - default: - if isprint(c) { - err = w.w.WriteByte(c) - } else { - _, err = fmt.Fprintf(w.w, "\\%03o", c) - } - } - if err != nil { - return err - } - } - return w.WriteByte('"') -} - -func writeUnknownStruct(w *textWriter, data []byte) (err error) { - if !w.compact { - if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { - return err - } - } - b := NewBuffer(data) - for b.index < len(b.buf) { - x, err := b.DecodeVarint() - if err != nil { - _, err := fmt.Fprintf(w, "/* %v */\n", err) - return err - } - wire, tag := x&7, x>>3 - if wire == WireEndGroup { - w.unindent() - if _, err := w.Write(endBraceNewline); err != nil { - return err - } - continue - } - if _, err := fmt.Fprint(w, tag); err != nil { - return err - } - if wire != WireStartGroup { - if err := w.WriteByte(':'); err != nil { - return err - } - } - if !w.compact || wire == WireStartGroup { - if err := w.WriteByte(' '); err != nil { - return err - } - } - switch wire { - case WireBytes: - buf, e := b.DecodeRawBytes(false) - if e == nil { - _, err = fmt.Fprintf(w, "%q", buf) - } else { - _, err = fmt.Fprintf(w, "/* %v */", e) - } - case WireFixed32: - x, err = b.DecodeFixed32() - err = writeUnknownInt(w, x, err) - case WireFixed64: - x, err = b.DecodeFixed64() - err = writeUnknownInt(w, x, err) - case WireStartGroup: - err = w.WriteByte('{') - w.indent() - case WireVarint: - x, err = b.DecodeVarint() - err = writeUnknownInt(w, x, err) - default: - _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) - } - if err != nil { - return err - } - if err = w.WriteByte('\n'); err != nil { - return err - } - } - return nil -} - -func writeUnknownInt(w *textWriter, x uint64, err error) error { - if err == nil { - _, err = fmt.Fprint(w, x) - } else { - _, err = fmt.Fprintf(w, "/* %v */", err) - } - return err -} - -type int32Slice []int32 - -func (s int32Slice) Len() int { return len(s) } -func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } -func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// writeExtensions writes all the extensions in pv. -// pv is assumed to be a pointer to a protocol message struct that is extendable. -func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { - emap := extensionMaps[pv.Type().Elem()] - ep, _ := extendable(pv.Interface()) - - // Order the extensions by ID. - // This isn't strictly necessary, but it will give us - // canonical output, which will also make testing easier. - m, mu := ep.extensionsRead() - if m == nil { - return nil - } - mu.Lock() - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) - mu.Unlock() - - for _, extNum := range ids { - ext := m[extNum] - var desc *ExtensionDesc - if emap != nil { - desc = emap[extNum] - } - if desc == nil { - // Unknown extension. - if err := writeUnknownStruct(w, ext.enc); err != nil { - return err - } - continue - } - - pb, err := GetExtension(ep, desc) - if err != nil { - return fmt.Errorf("failed getting extension: %v", err) - } - - // Repeated extensions will appear as a slice. - if !desc.repeated() { - if err := tm.writeExtension(w, desc.Name, pb); err != nil { - return err - } - } else { - v := reflect.ValueOf(pb) - for i := 0; i < v.Len(); i++ { - if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { - return err - } - } - } - } - return nil -} - -func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { - if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - return nil -} - -func (w *textWriter) writeIndent() { - if !w.complete { - return - } - remain := w.ind * 2 - for remain > 0 { - n := remain - if n > len(spaces) { - n = len(spaces) - } - w.w.Write(spaces[:n]) - remain -= n - } - w.complete = false -} - -// TextMarshaler is a configurable text format marshaler. -type TextMarshaler struct { - Compact bool // use compact text format (one line). - ExpandAny bool // expand google.protobuf.Any messages of known types -} - -// Marshal writes a given protocol buffer in text format. -// The only errors returned are from w. -func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { - val := reflect.ValueOf(pb) - if pb == nil || val.IsNil() { - w.Write([]byte("")) - return nil - } - var bw *bufio.Writer - ww, ok := w.(writer) - if !ok { - bw = bufio.NewWriter(w) - ww = bw - } - aw := &textWriter{ - w: ww, - complete: true, - compact: tm.Compact, - } - - if etm, ok := pb.(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = aw.Write(text); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil - } - // Dereference the received pointer so we don't have outer < and >. - v := reflect.Indirect(val) - if err := tm.writeStruct(aw, v); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil -} - -// Text is the same as Marshal, but returns the string directly. -func (tm *TextMarshaler) Text(pb Message) string { - var buf bytes.Buffer - tm.Marshal(&buf, pb) - return buf.String() -} - -var ( - defaultTextMarshaler = TextMarshaler{} - compactTextMarshaler = TextMarshaler{Compact: true} -) - -// TODO: consider removing some of the Marshal functions below. - -// MarshalText writes a given protocol buffer in text format. -// The only errors returned are from w. -func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } - -// MarshalTextString is the same as MarshalText, but returns the string directly. -func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } - -// CompactText writes a given protocol buffer in compact text format (one line). -func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } - -// CompactTextString is the same as CompactText, but returns the string directly. -func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } diff --git a/vendor/github.com/golang/protobuf/proto/text_decode.go b/vendor/github.com/golang/protobuf/proto/text_decode.go new file mode 100644 index 00000000000..4a593100987 --- /dev/null +++ b/vendor/github.com/golang/protobuf/proto/text_decode.go @@ -0,0 +1,801 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "encoding" + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "unicode/utf8" + + "google.golang.org/protobuf/encoding/prototext" + protoV2 "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +const wrapTextUnmarshalV2 = false + +// ParseError is returned by UnmarshalText. +type ParseError struct { + Message string + + // Deprecated: Do not use. + Line, Offset int +} + +func (e *ParseError) Error() string { + if wrapTextUnmarshalV2 { + return e.Message + } + if e.Line == 1 { + return fmt.Sprintf("line 1.%d: %v", e.Offset, e.Message) + } + return fmt.Sprintf("line %d: %v", e.Line, e.Message) +} + +// UnmarshalText parses a proto text formatted string into m. +func UnmarshalText(s string, m Message) error { + if u, ok := m.(encoding.TextUnmarshaler); ok { + return u.UnmarshalText([]byte(s)) + } + + m.Reset() + mi := MessageV2(m) + + if wrapTextUnmarshalV2 { + err := prototext.UnmarshalOptions{ + AllowPartial: true, + }.Unmarshal([]byte(s), mi) + if err != nil { + return &ParseError{Message: err.Error()} + } + return checkRequiredNotSet(mi) + } else { + if err := newTextParser(s).unmarshalMessage(mi.ProtoReflect(), ""); err != nil { + return err + } + return checkRequiredNotSet(mi) + } +} + +type textParser struct { + s string // remaining input + done bool // whether the parsing is finished (success or error) + backed bool // whether back() was called + offset, line int + cur token +} + +type token struct { + value string + err *ParseError + line int // line number + offset int // byte number from start of input, not start of line + unquoted string // the unquoted version of value, if it was a quoted string +} + +func newTextParser(s string) *textParser { + p := new(textParser) + p.s = s + p.line = 1 + p.cur.line = 1 + return p +} + +func (p *textParser) unmarshalMessage(m protoreflect.Message, terminator string) (err error) { + md := m.Descriptor() + fds := md.Fields() + + // A struct is a sequence of "name: value", terminated by one of + // '>' or '}', or the end of the input. A name may also be + // "[extension]" or "[type/url]". + // + // The whole struct can also be an expanded Any message, like: + // [type/url] < ... struct contents ... > + seen := make(map[protoreflect.FieldNumber]bool) + for { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == terminator { + break + } + if tok.value == "[" { + if err := p.unmarshalExtensionOrAny(m, seen); err != nil { + return err + } + continue + } + + // This is a normal, non-extension field. + name := protoreflect.Name(tok.value) + fd := fds.ByName(name) + switch { + case fd == nil: + gd := fds.ByName(protoreflect.Name(strings.ToLower(string(name)))) + if gd != nil && gd.Kind() == protoreflect.GroupKind && gd.Message().Name() == name { + fd = gd + } + case fd.Kind() == protoreflect.GroupKind && fd.Message().Name() != name: + fd = nil + case fd.IsWeak() && fd.Message().IsPlaceholder(): + fd = nil + } + if fd == nil { + typeName := string(md.FullName()) + if m, ok := m.Interface().(Message); ok { + t := reflect.TypeOf(m) + if t.Kind() == reflect.Ptr { + typeName = t.Elem().String() + } + } + return p.errorf("unknown field name %q in %v", name, typeName) + } + if od := fd.ContainingOneof(); od != nil && m.WhichOneof(od) != nil { + return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, od.Name()) + } + if fd.Cardinality() != protoreflect.Repeated && seen[fd.Number()] { + return p.errorf("non-repeated field %q was repeated", fd.Name()) + } + seen[fd.Number()] = true + + // Consume any colon. + if err := p.checkForColon(fd); err != nil { + return err + } + + // Parse into the field. + v := m.Get(fd) + if !m.Has(fd) && (fd.IsList() || fd.IsMap() || fd.Message() != nil) { + v = m.Mutable(fd) + } + if v, err = p.unmarshalValue(v, fd); err != nil { + return err + } + m.Set(fd, v) + + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + } + return nil +} + +func (p *textParser) unmarshalExtensionOrAny(m protoreflect.Message, seen map[protoreflect.FieldNumber]bool) error { + name, err := p.consumeExtensionOrAnyName() + if err != nil { + return err + } + + // If it contains a slash, it's an Any type URL. + if slashIdx := strings.LastIndex(name, "/"); slashIdx >= 0 { + tok := p.next() + if tok.err != nil { + return tok.err + } + // consume an optional colon + if tok.value == ":" { + tok = p.next() + if tok.err != nil { + return tok.err + } + } + + var terminator string + switch tok.value { + case "<": + terminator = ">" + case "{": + terminator = "}" + default: + return p.errorf("expected '{' or '<', found %q", tok.value) + } + + mt, err := protoregistry.GlobalTypes.FindMessageByURL(name) + if err != nil { + return p.errorf("unrecognized message %q in google.protobuf.Any", name[slashIdx+len("/"):]) + } + m2 := mt.New() + if err := p.unmarshalMessage(m2, terminator); err != nil { + return err + } + b, err := protoV2.Marshal(m2.Interface()) + if err != nil { + return p.errorf("failed to marshal message of type %q: %v", name[slashIdx+len("/"):], err) + } + + urlFD := m.Descriptor().Fields().ByName("type_url") + valFD := m.Descriptor().Fields().ByName("value") + if seen[urlFD.Number()] { + return p.errorf("Any message unpacked multiple times, or %q already set", urlFD.Name()) + } + if seen[valFD.Number()] { + return p.errorf("Any message unpacked multiple times, or %q already set", valFD.Name()) + } + m.Set(urlFD, protoreflect.ValueOfString(name)) + m.Set(valFD, protoreflect.ValueOfBytes(b)) + seen[urlFD.Number()] = true + seen[valFD.Number()] = true + return nil + } + + xname := protoreflect.FullName(name) + xt, _ := protoregistry.GlobalTypes.FindExtensionByName(xname) + if xt == nil && isMessageSet(m.Descriptor()) { + xt, _ = protoregistry.GlobalTypes.FindExtensionByName(xname.Append("message_set_extension")) + } + if xt == nil { + return p.errorf("unrecognized extension %q", name) + } + fd := xt.TypeDescriptor() + if fd.ContainingMessage().FullName() != m.Descriptor().FullName() { + return p.errorf("extension field %q does not extend message %q", name, m.Descriptor().FullName()) + } + + if err := p.checkForColon(fd); err != nil { + return err + } + + v := m.Get(fd) + if !m.Has(fd) && (fd.IsList() || fd.IsMap() || fd.Message() != nil) { + v = m.Mutable(fd) + } + v, err = p.unmarshalValue(v, fd) + if err != nil { + return err + } + m.Set(fd, v) + return p.consumeOptionalSeparator() +} + +func (p *textParser) unmarshalValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { + tok := p.next() + if tok.err != nil { + return v, tok.err + } + if tok.value == "" { + return v, p.errorf("unexpected EOF") + } + + switch { + case fd.IsList(): + lv := v.List() + var err error + if tok.value == "[" { + // Repeated field with list notation, like [1,2,3]. + for { + vv := lv.NewElement() + vv, err = p.unmarshalSingularValue(vv, fd) + if err != nil { + return v, err + } + lv.Append(vv) + + tok := p.next() + if tok.err != nil { + return v, tok.err + } + if tok.value == "]" { + break + } + if tok.value != "," { + return v, p.errorf("Expected ']' or ',' found %q", tok.value) + } + } + return v, nil + } + + // One value of the repeated field. + p.back() + vv := lv.NewElement() + vv, err = p.unmarshalSingularValue(vv, fd) + if err != nil { + return v, err + } + lv.Append(vv) + return v, nil + case fd.IsMap(): + // The map entry should be this sequence of tokens: + // < key : KEY value : VALUE > + // However, implementations may omit key or value, and technically + // we should support them in any order. + var terminator string + switch tok.value { + case "<": + terminator = ">" + case "{": + terminator = "}" + default: + return v, p.errorf("expected '{' or '<', found %q", tok.value) + } + + keyFD := fd.MapKey() + valFD := fd.MapValue() + + mv := v.Map() + kv := keyFD.Default() + vv := mv.NewValue() + for { + tok := p.next() + if tok.err != nil { + return v, tok.err + } + if tok.value == terminator { + break + } + var err error + switch tok.value { + case "key": + if err := p.consumeToken(":"); err != nil { + return v, err + } + if kv, err = p.unmarshalSingularValue(kv, keyFD); err != nil { + return v, err + } + if err := p.consumeOptionalSeparator(); err != nil { + return v, err + } + case "value": + if err := p.checkForColon(valFD); err != nil { + return v, err + } + if vv, err = p.unmarshalSingularValue(vv, valFD); err != nil { + return v, err + } + if err := p.consumeOptionalSeparator(); err != nil { + return v, err + } + default: + p.back() + return v, p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) + } + } + mv.Set(kv.MapKey(), vv) + return v, nil + default: + p.back() + return p.unmarshalSingularValue(v, fd) + } +} + +func (p *textParser) unmarshalSingularValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { + tok := p.next() + if tok.err != nil { + return v, tok.err + } + if tok.value == "" { + return v, p.errorf("unexpected EOF") + } + + switch fd.Kind() { + case protoreflect.BoolKind: + switch tok.value { + case "true", "1", "t", "True": + return protoreflect.ValueOfBool(true), nil + case "false", "0", "f", "False": + return protoreflect.ValueOfBool(false), nil + } + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: + if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { + return protoreflect.ValueOfInt32(int32(x)), nil + } + + // The C++ parser accepts large positive hex numbers that uses + // two's complement arithmetic to represent negative numbers. + // This feature is here for backwards compatibility with C++. + if strings.HasPrefix(tok.value, "0x") { + if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { + return protoreflect.ValueOfInt32(int32(-(int64(^x) + 1))), nil + } + } + case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: + if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { + return protoreflect.ValueOfInt64(int64(x)), nil + } + + // The C++ parser accepts large positive hex numbers that uses + // two's complement arithmetic to represent negative numbers. + // This feature is here for backwards compatibility with C++. + if strings.HasPrefix(tok.value, "0x") { + if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { + return protoreflect.ValueOfInt64(int64(-(int64(^x) + 1))), nil + } + } + case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: + if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { + return protoreflect.ValueOfUint32(uint32(x)), nil + } + case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: + if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { + return protoreflect.ValueOfUint64(uint64(x)), nil + } + case protoreflect.FloatKind: + // Ignore 'f' for compatibility with output generated by C++, + // but don't remove 'f' when the value is "-inf" or "inf". + v := tok.value + if strings.HasSuffix(v, "f") && v != "-inf" && v != "inf" { + v = v[:len(v)-len("f")] + } + if x, err := strconv.ParseFloat(v, 32); err == nil { + return protoreflect.ValueOfFloat32(float32(x)), nil + } + case protoreflect.DoubleKind: + // Ignore 'f' for compatibility with output generated by C++, + // but don't remove 'f' when the value is "-inf" or "inf". + v := tok.value + if strings.HasSuffix(v, "f") && v != "-inf" && v != "inf" { + v = v[:len(v)-len("f")] + } + if x, err := strconv.ParseFloat(v, 64); err == nil { + return protoreflect.ValueOfFloat64(float64(x)), nil + } + case protoreflect.StringKind: + if isQuote(tok.value[0]) { + return protoreflect.ValueOfString(tok.unquoted), nil + } + case protoreflect.BytesKind: + if isQuote(tok.value[0]) { + return protoreflect.ValueOfBytes([]byte(tok.unquoted)), nil + } + case protoreflect.EnumKind: + if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { + return protoreflect.ValueOfEnum(protoreflect.EnumNumber(x)), nil + } + vd := fd.Enum().Values().ByName(protoreflect.Name(tok.value)) + if vd != nil { + return protoreflect.ValueOfEnum(vd.Number()), nil + } + case protoreflect.MessageKind, protoreflect.GroupKind: + var terminator string + switch tok.value { + case "{": + terminator = "}" + case "<": + terminator = ">" + default: + return v, p.errorf("expected '{' or '<', found %q", tok.value) + } + err := p.unmarshalMessage(v.Message(), terminator) + return v, err + default: + panic(fmt.Sprintf("invalid kind %v", fd.Kind())) + } + return v, p.errorf("invalid %v: %v", fd.Kind(), tok.value) +} + +// Consume a ':' from the input stream (if the next token is a colon), +// returning an error if a colon is needed but not present. +func (p *textParser) checkForColon(fd protoreflect.FieldDescriptor) *ParseError { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != ":" { + if fd.Message() == nil { + return p.errorf("expected ':', found %q", tok.value) + } + p.back() + } + return nil +} + +// consumeExtensionOrAnyName consumes an extension name or an Any type URL and +// the following ']'. It returns the name or URL consumed. +func (p *textParser) consumeExtensionOrAnyName() (string, error) { + tok := p.next() + if tok.err != nil { + return "", tok.err + } + + // If extension name or type url is quoted, it's a single token. + if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { + name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) + if err != nil { + return "", err + } + return name, p.consumeToken("]") + } + + // Consume everything up to "]" + var parts []string + for tok.value != "]" { + parts = append(parts, tok.value) + tok = p.next() + if tok.err != nil { + return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) + } + if p.done && tok.value != "]" { + return "", p.errorf("unclosed type_url or extension name") + } + } + return strings.Join(parts, ""), nil +} + +// consumeOptionalSeparator consumes an optional semicolon or comma. +// It is used in unmarshalMessage to provide backward compatibility. +func (p *textParser) consumeOptionalSeparator() error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != ";" && tok.value != "," { + p.back() + } + return nil +} + +func (p *textParser) errorf(format string, a ...interface{}) *ParseError { + pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} + p.cur.err = pe + p.done = true + return pe +} + +func (p *textParser) skipWhitespace() { + i := 0 + for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { + if p.s[i] == '#' { + // comment; skip to end of line or input + for i < len(p.s) && p.s[i] != '\n' { + i++ + } + if i == len(p.s) { + break + } + } + if p.s[i] == '\n' { + p.line++ + } + i++ + } + p.offset += i + p.s = p.s[i:len(p.s)] + if len(p.s) == 0 { + p.done = true + } +} + +func (p *textParser) advance() { + // Skip whitespace + p.skipWhitespace() + if p.done { + return + } + + // Start of non-whitespace + p.cur.err = nil + p.cur.offset, p.cur.line = p.offset, p.line + p.cur.unquoted = "" + switch p.s[0] { + case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': + // Single symbol + p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] + case '"', '\'': + // Quoted string + i := 1 + for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { + if p.s[i] == '\\' && i+1 < len(p.s) { + // skip escaped char + i++ + } + i++ + } + if i >= len(p.s) || p.s[i] != p.s[0] { + p.errorf("unmatched quote") + return + } + unq, err := unquoteC(p.s[1:i], rune(p.s[0])) + if err != nil { + p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) + return + } + p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] + p.cur.unquoted = unq + default: + i := 0 + for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { + i++ + } + if i == 0 { + p.errorf("unexpected byte %#x", p.s[0]) + return + } + p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] + } + p.offset += len(p.cur.value) +} + +// Back off the parser by one token. Can only be done between calls to next(). +// It makes the next advance() a no-op. +func (p *textParser) back() { p.backed = true } + +// Advances the parser and returns the new current token. +func (p *textParser) next() *token { + if p.backed || p.done { + p.backed = false + return &p.cur + } + p.advance() + if p.done { + p.cur.value = "" + } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { + // Look for multiple quoted strings separated by whitespace, + // and concatenate them. + cat := p.cur + for { + p.skipWhitespace() + if p.done || !isQuote(p.s[0]) { + break + } + p.advance() + if p.cur.err != nil { + return &p.cur + } + cat.value += " " + p.cur.value + cat.unquoted += p.cur.unquoted + } + p.done = false // parser may have seen EOF, but we want to return cat + p.cur = cat + } + return &p.cur +} + +func (p *textParser) consumeToken(s string) error { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value != s { + p.back() + return p.errorf("expected %q, found %q", s, tok.value) + } + return nil +} + +var errBadUTF8 = errors.New("proto: bad UTF-8") + +func unquoteC(s string, quote rune) (string, error) { + // This is based on C++'s tokenizer.cc. + // Despite its name, this is *not* parsing C syntax. + // For instance, "\0" is an invalid quoted string. + + // Avoid allocation in trivial cases. + simple := true + for _, r := range s { + if r == '\\' || r == quote { + simple = false + break + } + } + if simple { + return s, nil + } + + buf := make([]byte, 0, 3*len(s)/2) + for len(s) > 0 { + r, n := utf8.DecodeRuneInString(s) + if r == utf8.RuneError && n == 1 { + return "", errBadUTF8 + } + s = s[n:] + if r != '\\' { + if r < utf8.RuneSelf { + buf = append(buf, byte(r)) + } else { + buf = append(buf, string(r)...) + } + continue + } + + ch, tail, err := unescape(s) + if err != nil { + return "", err + } + buf = append(buf, ch...) + s = tail + } + return string(buf), nil +} + +func unescape(s string) (ch string, tail string, err error) { + r, n := utf8.DecodeRuneInString(s) + if r == utf8.RuneError && n == 1 { + return "", "", errBadUTF8 + } + s = s[n:] + switch r { + case 'a': + return "\a", s, nil + case 'b': + return "\b", s, nil + case 'f': + return "\f", s, nil + case 'n': + return "\n", s, nil + case 'r': + return "\r", s, nil + case 't': + return "\t", s, nil + case 'v': + return "\v", s, nil + case '?': + return "?", s, nil // trigraph workaround + case '\'', '"', '\\': + return string(r), s, nil + case '0', '1', '2', '3', '4', '5', '6', '7': + if len(s) < 2 { + return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) + } + ss := string(r) + s[:2] + s = s[2:] + i, err := strconv.ParseUint(ss, 8, 8) + if err != nil { + return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) + } + return string([]byte{byte(i)}), s, nil + case 'x', 'X', 'u', 'U': + var n int + switch r { + case 'x', 'X': + n = 2 + case 'u': + n = 4 + case 'U': + n = 8 + } + if len(s) < n { + return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) + } + ss := s[:n] + s = s[n:] + i, err := strconv.ParseUint(ss, 16, 64) + if err != nil { + return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) + } + if r == 'x' || r == 'X' { + return string([]byte{byte(i)}), s, nil + } + if i > utf8.MaxRune { + return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) + } + return string(i), s, nil + } + return "", "", fmt.Errorf(`unknown escape \%c`, r) +} + +func isIdentOrNumberChar(c byte) bool { + switch { + case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': + return true + case '0' <= c && c <= '9': + return true + } + switch c { + case '-', '+', '.', '_': + return true + } + return false +} + +func isWhitespace(c byte) bool { + switch c { + case ' ', '\t', '\n', '\r': + return true + } + return false +} + +func isQuote(c byte) bool { + switch c { + case '"', '\'': + return true + } + return false +} diff --git a/vendor/github.com/golang/protobuf/proto/text_encode.go b/vendor/github.com/golang/protobuf/proto/text_encode.go new file mode 100644 index 00000000000..a31134eeb3b --- /dev/null +++ b/vendor/github.com/golang/protobuf/proto/text_encode.go @@ -0,0 +1,560 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "bytes" + "encoding" + "fmt" + "io" + "math" + "sort" + "strings" + + "google.golang.org/protobuf/encoding/prototext" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +const wrapTextMarshalV2 = false + +// TextMarshaler is a configurable text format marshaler. +type TextMarshaler struct { + Compact bool // use compact text format (one line) + ExpandAny bool // expand google.protobuf.Any messages of known types +} + +// Marshal writes the proto text format of m to w. +func (tm *TextMarshaler) Marshal(w io.Writer, m Message) error { + b, err := tm.marshal(m) + if len(b) > 0 { + if _, err := w.Write(b); err != nil { + return err + } + } + return err +} + +// Text returns a proto text formatted string of m. +func (tm *TextMarshaler) Text(m Message) string { + b, _ := tm.marshal(m) + return string(b) +} + +func (tm *TextMarshaler) marshal(m Message) ([]byte, error) { + mr := MessageReflect(m) + if mr == nil || !mr.IsValid() { + return []byte(""), nil + } + + if wrapTextMarshalV2 { + if m, ok := m.(encoding.TextMarshaler); ok { + return m.MarshalText() + } + + opts := prototext.MarshalOptions{ + AllowPartial: true, + EmitUnknown: true, + } + if !tm.Compact { + opts.Indent = " " + } + if !tm.ExpandAny { + opts.Resolver = (*protoregistry.Types)(nil) + } + return opts.Marshal(mr.Interface()) + } else { + w := &textWriter{ + compact: tm.Compact, + expandAny: tm.ExpandAny, + complete: true, + } + + if m, ok := m.(encoding.TextMarshaler); ok { + b, err := m.MarshalText() + if err != nil { + return nil, err + } + w.Write(b) + return w.buf, nil + } + + err := w.writeMessage(mr) + return w.buf, err + } +} + +var ( + defaultTextMarshaler = TextMarshaler{} + compactTextMarshaler = TextMarshaler{Compact: true} +) + +// MarshalText writes the proto text format of m to w. +func MarshalText(w io.Writer, m Message) error { return defaultTextMarshaler.Marshal(w, m) } + +// MarshalTextString returns a proto text formatted string of m. +func MarshalTextString(m Message) string { return defaultTextMarshaler.Text(m) } + +// CompactText writes the compact proto text format of m to w. +func CompactText(w io.Writer, m Message) error { return compactTextMarshaler.Marshal(w, m) } + +// CompactTextString returns a compact proto text formatted string of m. +func CompactTextString(m Message) string { return compactTextMarshaler.Text(m) } + +var ( + newline = []byte("\n") + endBraceNewline = []byte("}\n") + posInf = []byte("inf") + negInf = []byte("-inf") + nan = []byte("nan") +) + +// textWriter is an io.Writer that tracks its indentation level. +type textWriter struct { + compact bool // same as TextMarshaler.Compact + expandAny bool // same as TextMarshaler.ExpandAny + complete bool // whether the current position is a complete line + indent int // indentation level; never negative + buf []byte +} + +func (w *textWriter) Write(p []byte) (n int, _ error) { + newlines := bytes.Count(p, newline) + if newlines == 0 { + if !w.compact && w.complete { + w.writeIndent() + } + w.buf = append(w.buf, p...) + w.complete = false + return len(p), nil + } + + frags := bytes.SplitN(p, newline, newlines+1) + if w.compact { + for i, frag := range frags { + if i > 0 { + w.buf = append(w.buf, ' ') + n++ + } + w.buf = append(w.buf, frag...) + n += len(frag) + } + return n, nil + } + + for i, frag := range frags { + if w.complete { + w.writeIndent() + } + w.buf = append(w.buf, frag...) + n += len(frag) + if i+1 < len(frags) { + w.buf = append(w.buf, '\n') + n++ + } + } + w.complete = len(frags[len(frags)-1]) == 0 + return n, nil +} + +func (w *textWriter) WriteByte(c byte) error { + if w.compact && c == '\n' { + c = ' ' + } + if !w.compact && w.complete { + w.writeIndent() + } + w.buf = append(w.buf, c) + w.complete = c == '\n' + return nil +} + +func (w *textWriter) writeName(fd protoreflect.FieldDescriptor) { + if !w.compact && w.complete { + w.writeIndent() + } + w.complete = false + + if fd.Kind() != protoreflect.GroupKind { + w.buf = append(w.buf, fd.Name()...) + w.WriteByte(':') + } else { + // Use message type name for group field name. + w.buf = append(w.buf, fd.Message().Name()...) + } + + if !w.compact { + w.WriteByte(' ') + } +} + +func requiresQuotes(u string) bool { + // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. + for _, ch := range u { + switch { + case ch == '.' || ch == '/' || ch == '_': + continue + case '0' <= ch && ch <= '9': + continue + case 'A' <= ch && ch <= 'Z': + continue + case 'a' <= ch && ch <= 'z': + continue + default: + return true + } + } + return false +} + +// writeProto3Any writes an expanded google.protobuf.Any message. +// +// It returns (false, nil) if sv value can't be unmarshaled (e.g. because +// required messages are not linked in). +// +// It returns (true, error) when sv was written in expanded format or an error +// was encountered. +func (w *textWriter) writeProto3Any(m protoreflect.Message) (bool, error) { + md := m.Descriptor() + fdURL := md.Fields().ByName("type_url") + fdVal := md.Fields().ByName("value") + + url := m.Get(fdURL).String() + mt, err := protoregistry.GlobalTypes.FindMessageByURL(url) + if err != nil { + return false, nil + } + + b := m.Get(fdVal).Bytes() + m2 := mt.New() + if err := proto.Unmarshal(b, m2.Interface()); err != nil { + return false, nil + } + w.Write([]byte("[")) + if requiresQuotes(url) { + w.writeQuotedString(url) + } else { + w.Write([]byte(url)) + } + if w.compact { + w.Write([]byte("]:<")) + } else { + w.Write([]byte("]: <\n")) + w.indent++ + } + if err := w.writeMessage(m2); err != nil { + return true, err + } + if w.compact { + w.Write([]byte("> ")) + } else { + w.indent-- + w.Write([]byte(">\n")) + } + return true, nil +} + +func (w *textWriter) writeMessage(m protoreflect.Message) error { + md := m.Descriptor() + if w.expandAny && md.FullName() == "google.protobuf.Any" { + if canExpand, err := w.writeProto3Any(m); canExpand { + return err + } + } + + fds := md.Fields() + for i := 0; i < fds.Len(); { + fd := fds.Get(i) + if od := fd.ContainingOneof(); od != nil { + fd = m.WhichOneof(od) + i += od.Fields().Len() + } else { + i++ + } + if fd == nil || !m.Has(fd) { + continue + } + + switch { + case fd.IsList(): + lv := m.Get(fd).List() + for j := 0; j < lv.Len(); j++ { + w.writeName(fd) + v := lv.Get(j) + if err := w.writeSingularValue(v, fd); err != nil { + return err + } + w.WriteByte('\n') + } + case fd.IsMap(): + kfd := fd.MapKey() + vfd := fd.MapValue() + mv := m.Get(fd).Map() + + type entry struct{ key, val protoreflect.Value } + var entries []entry + mv.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { + entries = append(entries, entry{k.Value(), v}) + return true + }) + sort.Slice(entries, func(i, j int) bool { + switch kfd.Kind() { + case protoreflect.BoolKind: + return !entries[i].key.Bool() && entries[j].key.Bool() + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: + return entries[i].key.Int() < entries[j].key.Int() + case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, protoreflect.Uint64Kind, protoreflect.Fixed64Kind: + return entries[i].key.Uint() < entries[j].key.Uint() + case protoreflect.StringKind: + return entries[i].key.String() < entries[j].key.String() + default: + panic("invalid kind") + } + }) + for _, entry := range entries { + w.writeName(fd) + w.WriteByte('<') + if !w.compact { + w.WriteByte('\n') + } + w.indent++ + w.writeName(kfd) + if err := w.writeSingularValue(entry.key, kfd); err != nil { + return err + } + w.WriteByte('\n') + w.writeName(vfd) + if err := w.writeSingularValue(entry.val, vfd); err != nil { + return err + } + w.WriteByte('\n') + w.indent-- + w.WriteByte('>') + w.WriteByte('\n') + } + default: + w.writeName(fd) + if err := w.writeSingularValue(m.Get(fd), fd); err != nil { + return err + } + w.WriteByte('\n') + } + } + + if b := m.GetUnknown(); len(b) > 0 { + w.writeUnknownFields(b) + } + return w.writeExtensions(m) +} + +func (w *textWriter) writeSingularValue(v protoreflect.Value, fd protoreflect.FieldDescriptor) error { + switch fd.Kind() { + case protoreflect.FloatKind, protoreflect.DoubleKind: + switch vf := v.Float(); { + case math.IsInf(vf, +1): + w.Write(posInf) + case math.IsInf(vf, -1): + w.Write(negInf) + case math.IsNaN(vf): + w.Write(nan) + default: + fmt.Fprint(w, v.Interface()) + } + case protoreflect.StringKind: + // NOTE: This does not validate UTF-8 for historical reasons. + w.writeQuotedString(string(v.String())) + case protoreflect.BytesKind: + w.writeQuotedString(string(v.Bytes())) + case protoreflect.MessageKind, protoreflect.GroupKind: + var bra, ket byte = '<', '>' + if fd.Kind() == protoreflect.GroupKind { + bra, ket = '{', '}' + } + w.WriteByte(bra) + if !w.compact { + w.WriteByte('\n') + } + w.indent++ + m := v.Message() + if m2, ok := m.Interface().(encoding.TextMarshaler); ok { + b, err := m2.MarshalText() + if err != nil { + return err + } + w.Write(b) + } else { + w.writeMessage(m) + } + w.indent-- + w.WriteByte(ket) + case protoreflect.EnumKind: + if ev := fd.Enum().Values().ByNumber(v.Enum()); ev != nil { + fmt.Fprint(w, ev.Name()) + } else { + fmt.Fprint(w, v.Enum()) + } + default: + fmt.Fprint(w, v.Interface()) + } + return nil +} + +// writeQuotedString writes a quoted string in the protocol buffer text format. +func (w *textWriter) writeQuotedString(s string) { + w.WriteByte('"') + for i := 0; i < len(s); i++ { + switch c := s[i]; c { + case '\n': + w.buf = append(w.buf, `\n`...) + case '\r': + w.buf = append(w.buf, `\r`...) + case '\t': + w.buf = append(w.buf, `\t`...) + case '"': + w.buf = append(w.buf, `\"`...) + case '\\': + w.buf = append(w.buf, `\\`...) + default: + if isPrint := c >= 0x20 && c < 0x7f; isPrint { + w.buf = append(w.buf, c) + } else { + w.buf = append(w.buf, fmt.Sprintf(`\%03o`, c)...) + } + } + } + w.WriteByte('"') +} + +func (w *textWriter) writeUnknownFields(b []byte) { + if !w.compact { + fmt.Fprintf(w, "/* %d unknown bytes */\n", len(b)) + } + + for len(b) > 0 { + num, wtyp, n := protowire.ConsumeTag(b) + if n < 0 { + return + } + b = b[n:] + + if wtyp == protowire.EndGroupType { + w.indent-- + w.Write(endBraceNewline) + continue + } + fmt.Fprint(w, num) + if wtyp != protowire.StartGroupType { + w.WriteByte(':') + } + if !w.compact || wtyp == protowire.StartGroupType { + w.WriteByte(' ') + } + switch wtyp { + case protowire.VarintType: + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return + } + b = b[n:] + fmt.Fprint(w, v) + case protowire.Fixed32Type: + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return + } + b = b[n:] + fmt.Fprint(w, v) + case protowire.Fixed64Type: + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return + } + b = b[n:] + fmt.Fprint(w, v) + case protowire.BytesType: + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return + } + b = b[n:] + fmt.Fprintf(w, "%q", v) + case protowire.StartGroupType: + w.WriteByte('{') + w.indent++ + default: + fmt.Fprintf(w, "/* unknown wire type %d */", wtyp) + } + w.WriteByte('\n') + } +} + +// writeExtensions writes all the extensions in m. +func (w *textWriter) writeExtensions(m protoreflect.Message) error { + md := m.Descriptor() + if md.ExtensionRanges().Len() == 0 { + return nil + } + + type ext struct { + desc protoreflect.FieldDescriptor + val protoreflect.Value + } + var exts []ext + m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + if fd.IsExtension() { + exts = append(exts, ext{fd, v}) + } + return true + }) + sort.Slice(exts, func(i, j int) bool { + return exts[i].desc.Number() < exts[j].desc.Number() + }) + + for _, ext := range exts { + // For message set, use the name of the message as the extension name. + name := string(ext.desc.FullName()) + if isMessageSet(ext.desc.ContainingMessage()) { + name = strings.TrimSuffix(name, ".message_set_extension") + } + + if !ext.desc.IsList() { + if err := w.writeSingularExtension(name, ext.val, ext.desc); err != nil { + return err + } + } else { + lv := ext.val.List() + for i := 0; i < lv.Len(); i++ { + if err := w.writeSingularExtension(name, lv.Get(i), ext.desc); err != nil { + return err + } + } + } + } + return nil +} + +func (w *textWriter) writeSingularExtension(name string, v protoreflect.Value, fd protoreflect.FieldDescriptor) error { + fmt.Fprintf(w, "[%s]:", name) + if !w.compact { + w.WriteByte(' ') + } + if err := w.writeSingularValue(v, fd); err != nil { + return err + } + w.WriteByte('\n') + return nil +} + +func (w *textWriter) writeIndent() { + if !w.complete { + return + } + for i := 0; i < w.indent*2; i++ { + w.buf = append(w.buf, ' ') + } + w.complete = false +} diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go deleted file mode 100644 index bb55a3af276..00000000000 --- a/vendor/github.com/golang/protobuf/proto/text_parser.go +++ /dev/null @@ -1,880 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for parsing the Text protocol buffer format. -// TODO: message sets. - -import ( - "encoding" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" -) - -// Error string emitted when deserializing Any and fields are already set -const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" - -type ParseError struct { - Message string - Line int // 1-based line number - Offset int // 0-based byte offset from start of input -} - -func (p *ParseError) Error() string { - if p.Line == 1 { - // show offset only for first line - return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) - } - return fmt.Sprintf("line %d: %v", p.Line, p.Message) -} - -type token struct { - value string - err *ParseError - line int // line number - offset int // byte number from start of input, not start of line - unquoted string // the unquoted version of value, if it was a quoted string -} - -func (t *token) String() string { - if t.err == nil { - return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) - } - return fmt.Sprintf("parse error: %v", t.err) -} - -type textParser struct { - s string // remaining input - done bool // whether the parsing is finished (success or error) - backed bool // whether back() was called - offset, line int - cur token -} - -func newTextParser(s string) *textParser { - p := new(textParser) - p.s = s - p.line = 1 - p.cur.line = 1 - return p -} - -func (p *textParser) errorf(format string, a ...interface{}) *ParseError { - pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} - p.cur.err = pe - p.done = true - return pe -} - -// Numbers and identifiers are matched by [-+._A-Za-z0-9] -func isIdentOrNumberChar(c byte) bool { - switch { - case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': - return true - case '0' <= c && c <= '9': - return true - } - switch c { - case '-', '+', '.', '_': - return true - } - return false -} - -func isWhitespace(c byte) bool { - switch c { - case ' ', '\t', '\n', '\r': - return true - } - return false -} - -func isQuote(c byte) bool { - switch c { - case '"', '\'': - return true - } - return false -} - -func (p *textParser) skipWhitespace() { - i := 0 - for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { - if p.s[i] == '#' { - // comment; skip to end of line or input - for i < len(p.s) && p.s[i] != '\n' { - i++ - } - if i == len(p.s) { - break - } - } - if p.s[i] == '\n' { - p.line++ - } - i++ - } - p.offset += i - p.s = p.s[i:len(p.s)] - if len(p.s) == 0 { - p.done = true - } -} - -func (p *textParser) advance() { - // Skip whitespace - p.skipWhitespace() - if p.done { - return - } - - // Start of non-whitespace - p.cur.err = nil - p.cur.offset, p.cur.line = p.offset, p.line - p.cur.unquoted = "" - switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': - // Single symbol - p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] - case '"', '\'': - // Quoted string - i := 1 - for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { - if p.s[i] == '\\' && i+1 < len(p.s) { - // skip escaped char - i++ - } - i++ - } - if i >= len(p.s) || p.s[i] != p.s[0] { - p.errorf("unmatched quote") - return - } - unq, err := unquoteC(p.s[1:i], rune(p.s[0])) - if err != nil { - p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) - return - } - p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] - p.cur.unquoted = unq - default: - i := 0 - for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { - i++ - } - if i == 0 { - p.errorf("unexpected byte %#x", p.s[0]) - return - } - p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] - } - p.offset += len(p.cur.value) -} - -var ( - errBadUTF8 = errors.New("proto: bad UTF-8") -) - -func unquoteC(s string, quote rune) (string, error) { - // This is based on C++'s tokenizer.cc. - // Despite its name, this is *not* parsing C syntax. - // For instance, "\0" is an invalid quoted string. - - // Avoid allocation in trivial cases. - simple := true - for _, r := range s { - if r == '\\' || r == quote { - simple = false - break - } - } - if simple { - return s, nil - } - - buf := make([]byte, 0, 3*len(s)/2) - for len(s) > 0 { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", errBadUTF8 - } - s = s[n:] - if r != '\\' { - if r < utf8.RuneSelf { - buf = append(buf, byte(r)) - } else { - buf = append(buf, string(r)...) - } - continue - } - - ch, tail, err := unescape(s) - if err != nil { - return "", err - } - buf = append(buf, ch...) - s = tail - } - return string(buf), nil -} - -func unescape(s string) (ch string, tail string, err error) { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", "", errBadUTF8 - } - s = s[n:] - switch r { - case 'a': - return "\a", s, nil - case 'b': - return "\b", s, nil - case 'f': - return "\f", s, nil - case 'n': - return "\n", s, nil - case 'r': - return "\r", s, nil - case 't': - return "\t", s, nil - case 'v': - return "\v", s, nil - case '?': - return "?", s, nil // trigraph workaround - case '\'', '"', '\\': - return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7': - if len(s) < 2 { - return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) - } - ss := string(r) + s[:2] - s = s[2:] - i, err := strconv.ParseUint(ss, 8, 8) - if err != nil { - return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) - } - return string([]byte{byte(i)}), s, nil - case 'x', 'X', 'u', 'U': - var n int - switch r { - case 'x', 'X': - n = 2 - case 'u': - n = 4 - case 'U': - n = 8 - } - if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) - } - ss := s[:n] - s = s[n:] - i, err := strconv.ParseUint(ss, 16, 64) - if err != nil { - return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) - } - if r == 'x' || r == 'X' { - return string([]byte{byte(i)}), s, nil - } - if i > utf8.MaxRune { - return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) - } - return string(i), s, nil - } - return "", "", fmt.Errorf(`unknown escape \%c`, r) -} - -// Back off the parser by one token. Can only be done between calls to next(). -// It makes the next advance() a no-op. -func (p *textParser) back() { p.backed = true } - -// Advances the parser and returns the new current token. -func (p *textParser) next() *token { - if p.backed || p.done { - p.backed = false - return &p.cur - } - p.advance() - if p.done { - p.cur.value = "" - } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { - // Look for multiple quoted strings separated by whitespace, - // and concatenate them. - cat := p.cur - for { - p.skipWhitespace() - if p.done || !isQuote(p.s[0]) { - break - } - p.advance() - if p.cur.err != nil { - return &p.cur - } - cat.value += " " + p.cur.value - cat.unquoted += p.cur.unquoted - } - p.done = false // parser may have seen EOF, but we want to return cat - p.cur = cat - } - return &p.cur -} - -func (p *textParser) consumeToken(s string) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != s { - p.back() - return p.errorf("expected %q, found %q", s, tok.value) - } - return nil -} - -// Return a RequiredNotSetError indicating which required field was not set. -func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < st.NumField(); i++ { - if !isNil(sv.Field(i)) { - continue - } - - props := sprops.Prop[i] - if props.Required { - return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} - } - } - return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen -} - -// Returns the index in the struct for the named field, as well as the parsed tag properties. -func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { - i, ok := sprops.decoderOrigNames[name] - if ok { - return i, sprops.Prop[i], true - } - return -1, nil, false -} - -// Consume a ':' from the input stream (if the next token is a colon), -// returning an error if a colon is needed but not present. -func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ":" { - // Colon is optional when the field is a group or message. - needColon := true - switch props.Wire { - case "group": - needColon = false - case "bytes": - // A "bytes" field is either a message, a string, or a repeated field; - // those three become *T, *string and []T respectively, so we can check for - // this field being a pointer to a non-string. - if typ.Kind() == reflect.Ptr { - // *T or *string - if typ.Elem().Kind() == reflect.String { - break - } - } else if typ.Kind() == reflect.Slice { - // []T or []*T - if typ.Elem().Kind() != reflect.Ptr { - break - } - } else if typ.Kind() == reflect.String { - // The proto3 exception is for a string field, - // which requires a colon. - break - } - needColon = false - } - if needColon { - return p.errorf("expected ':', found %q", tok.value) - } - p.back() - } - return nil -} - -func (p *textParser) readStruct(sv reflect.Value, terminator string) error { - st := sv.Type() - sprops := GetProperties(st) - reqCount := sprops.reqCount - var reqFieldErr error - fieldSet := make(map[string]bool) - // A struct is a sequence of "name: value", terminated by one of - // '>' or '}', or the end of the input. A name may also be - // "[extension]" or "[type/url]". - // - // The whole struct can also be an expanded Any message, like: - // [type/url] < ... struct contents ... > - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - if tok.value == "[" { - // Looks like an extension or an Any. - // - // TODO: Check whether we need to handle - // namespace rooted names (e.g. ".something.Foo"). - extName, err := p.consumeExtName() - if err != nil { - return err - } - - if s := strings.LastIndex(extName, "/"); s >= 0 { - // If it contains a slash, it's an Any type URL. - messageName := extName[s+1:] - mt := MessageType(messageName) - if mt == nil { - return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) - } - tok = p.next() - if tok.err != nil { - return tok.err - } - // consume an optional colon - if tok.value == ":" { - tok = p.next() - if tok.err != nil { - return tok.err - } - } - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - v := reflect.New(mt.Elem()) - if pe := p.readStruct(v.Elem(), terminator); pe != nil { - return pe - } - b, err := Marshal(v.Interface().(Message)) - if err != nil { - return p.errorf("failed to marshal message of type %q: %v", messageName, err) - } - if fieldSet["type_url"] { - return p.errorf(anyRepeatedlyUnpacked, "type_url") - } - if fieldSet["value"] { - return p.errorf(anyRepeatedlyUnpacked, "value") - } - sv.FieldByName("TypeUrl").SetString(extName) - sv.FieldByName("Value").SetBytes(b) - fieldSet["type_url"] = true - fieldSet["value"] = true - continue - } - - var desc *ExtensionDesc - // This could be faster, but it's functional. - // TODO: Do something smarter than a linear scan. - for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { - if d.Name == extName { - desc = d - break - } - } - if desc == nil { - return p.errorf("unrecognized extension %q", extName) - } - - props := &Properties{} - props.Parse(desc.Tag) - - typ := reflect.TypeOf(desc.ExtensionType) - if err := p.checkForColon(props, typ); err != nil { - return err - } - - rep := desc.repeated() - - // Read the extension structure, and set it in - // the value we're constructing. - var ext reflect.Value - if !rep { - ext = reflect.New(typ).Elem() - } else { - ext = reflect.New(typ.Elem()).Elem() - } - if err := p.readAny(ext, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - ep := sv.Addr().Interface().(Message) - if !rep { - SetExtension(ep, desc, ext.Interface()) - } else { - old, err := GetExtension(ep, desc) - var sl reflect.Value - if err == nil { - sl = reflect.ValueOf(old) // existing slice - } else { - sl = reflect.MakeSlice(typ, 0, 1) - } - sl = reflect.Append(sl, ext) - SetExtension(ep, desc, sl.Interface()) - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - continue - } - - // This is a normal, non-extension field. - name := tok.value - var dst reflect.Value - fi, props, ok := structFieldByName(sprops, name) - if ok { - dst = sv.Field(fi) - } else if oop, ok := sprops.OneofTypes[name]; ok { - // It is a oneof. - props = oop.Prop - nv := reflect.New(oop.Type.Elem()) - dst = nv.Elem().Field(0) - field := sv.Field(oop.Field) - if !field.IsNil() { - return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) - } - field.Set(nv) - } - if !dst.IsValid() { - return p.errorf("unknown field name %q in %v", name, st) - } - - if dst.Kind() == reflect.Map { - // Consume any colon. - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Construct the map if it doesn't already exist. - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - key := reflect.New(dst.Type().Key()).Elem() - val := reflect.New(dst.Type().Elem()).Elem() - - // The map entry should be this sequence of tokens: - // < key : KEY value : VALUE > - // However, implementations may omit key or value, and technically - // we should support them in any order. See b/28924776 for a time - // this went wrong. - - tok := p.next() - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - switch tok.value { - case "key": - if err := p.consumeToken(":"); err != nil { - return err - } - if err := p.readAny(key, props.MapKeyProp); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - case "value": - if err := p.checkForColon(props.MapValProp, dst.Type().Elem()); err != nil { - return err - } - if err := p.readAny(val, props.MapValProp); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - default: - p.back() - return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) - } - } - - dst.SetMapIndex(key, val) - continue - } - - // Check that it's not already set if it's not a repeated field. - if !props.Repeated && fieldSet[name] { - return p.errorf("non-repeated field %q was repeated", name) - } - - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Parse into the field. - fieldSet[name] = true - if err := p.readAny(dst, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - if props.Required { - reqCount-- - } - - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - - } - - if reqCount > 0 { - return p.missingRequiredFieldError(sv) - } - return reqFieldErr -} - -// consumeExtName consumes extension name or expanded Any type URL and the -// following ']'. It returns the name or URL consumed. -func (p *textParser) consumeExtName() (string, error) { - tok := p.next() - if tok.err != nil { - return "", tok.err - } - - // If extension name or type url is quoted, it's a single token. - if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { - name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) - if err != nil { - return "", err - } - return name, p.consumeToken("]") - } - - // Consume everything up to "]" - var parts []string - for tok.value != "]" { - parts = append(parts, tok.value) - tok = p.next() - if tok.err != nil { - return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) - } - if p.done && tok.value != "]" { - return "", p.errorf("unclosed type_url or extension name") - } - } - return strings.Join(parts, ""), nil -} - -// consumeOptionalSeparator consumes an optional semicolon or comma. -// It is used in readStruct to provide backward compatibility. -func (p *textParser) consumeOptionalSeparator() error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ";" && tok.value != "," { - p.back() - } - return nil -} - -func (p *textParser) readAny(v reflect.Value, props *Properties) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "" { - return p.errorf("unexpected EOF") - } - - switch fv := v; fv.Kind() { - case reflect.Slice: - at := v.Type() - if at.Elem().Kind() == reflect.Uint8 { - // Special case for []byte - if tok.value[0] != '"' && tok.value[0] != '\'' { - // Deliberately written out here, as the error after - // this switch statement would write "invalid []byte: ...", - // which is not as user-friendly. - return p.errorf("invalid string: %v", tok.value) - } - bytes := []byte(tok.unquoted) - fv.Set(reflect.ValueOf(bytes)) - return nil - } - // Repeated field. - if tok.value == "[" { - // Repeated field with list notation, like [1,2,3]. - for { - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - err := p.readAny(fv.Index(fv.Len()-1), props) - if err != nil { - return err - } - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "]" { - break - } - if tok.value != "," { - return p.errorf("Expected ']' or ',' found %q", tok.value) - } - } - return nil - } - // One value of the repeated field. - p.back() - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - return p.readAny(fv.Index(fv.Len()-1), props) - case reflect.Bool: - // true/1/t/True or false/f/0/False. - switch tok.value { - case "true", "1", "t", "True": - fv.SetBool(true) - return nil - case "false", "0", "f", "False": - fv.SetBool(false) - return nil - } - case reflect.Float32, reflect.Float64: - v := tok.value - // Ignore 'f' for compatibility with output generated by C++, but don't - // remove 'f' when the value is "-inf" or "inf". - if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { - v = v[:len(v)-1] - } - if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { - fv.SetFloat(f) - return nil - } - case reflect.Int32: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - fv.SetInt(x) - return nil - } - - if len(props.Enum) == 0 { - break - } - m, ok := enumValueMaps[props.Enum] - if !ok { - break - } - x, ok := m[tok.value] - if !ok { - break - } - fv.SetInt(int64(x)) - return nil - case reflect.Int64: - if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { - fv.SetInt(x) - return nil - } - - case reflect.Ptr: - // A basic field (indirected through pointer), or a repeated message/group - p.back() - fv.Set(reflect.New(fv.Type().Elem())) - return p.readAny(fv.Elem(), props) - case reflect.String: - if tok.value[0] == '"' || tok.value[0] == '\'' { - fv.SetString(tok.unquoted) - return nil - } - case reflect.Struct: - var terminator string - switch tok.value { - case "{": - terminator = "}" - case "<": - terminator = ">" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - // TODO: Handle nested messages which implement encoding.TextUnmarshaler. - return p.readStruct(fv, terminator) - case reflect.Uint32: - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(uint64(x)) - return nil - } - case reflect.Uint64: - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - fv.SetUint(x) - return nil - } - } - return p.errorf("invalid %v: %v", v.Type(), tok.value) -} - -// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb -// before starting to unmarshal, so any existing data in pb is always removed. -// If a required field is not set and no other error occurs, -// UnmarshalText returns *RequiredNotSetError. -func UnmarshalText(s string, pb Message) error { - if um, ok := pb.(encoding.TextUnmarshaler); ok { - return um.UnmarshalText([]byte(s)) - } - pb.Reset() - v := reflect.ValueOf(pb) - return newTextParser(s).readStruct(v.Elem(), "") -} diff --git a/vendor/github.com/golang/protobuf/proto/wire.go b/vendor/github.com/golang/protobuf/proto/wire.go new file mode 100644 index 00000000000..d7c28da5a75 --- /dev/null +++ b/vendor/github.com/golang/protobuf/proto/wire.go @@ -0,0 +1,78 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + protoV2 "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/runtime/protoiface" +) + +// Size returns the size in bytes of the wire-format encoding of m. +func Size(m Message) int { + if m == nil { + return 0 + } + mi := MessageV2(m) + return protoV2.Size(mi) +} + +// Marshal returns the wire-format encoding of m. +func Marshal(m Message) ([]byte, error) { + b, err := marshalAppend(nil, m, false) + if b == nil { + b = zeroBytes + } + return b, err +} + +var zeroBytes = make([]byte, 0, 0) + +func marshalAppend(buf []byte, m Message, deterministic bool) ([]byte, error) { + if m == nil { + return nil, ErrNil + } + mi := MessageV2(m) + nbuf, err := protoV2.MarshalOptions{ + Deterministic: deterministic, + AllowPartial: true, + }.MarshalAppend(buf, mi) + if err != nil { + return buf, err + } + if len(buf) == len(nbuf) { + if !mi.ProtoReflect().IsValid() { + return buf, ErrNil + } + } + return nbuf, checkRequiredNotSet(mi) +} + +// Unmarshal parses a wire-format message in b and places the decoded results in m. +// +// Unmarshal resets m before starting to unmarshal, so any existing data in m is always +// removed. Use UnmarshalMerge to preserve and append to existing data. +func Unmarshal(b []byte, m Message) error { + m.Reset() + return UnmarshalMerge(b, m) +} + +// UnmarshalMerge parses a wire-format message in b and places the decoded results in m. +func UnmarshalMerge(b []byte, m Message) error { + mi := MessageV2(m) + out, err := protoV2.UnmarshalOptions{ + AllowPartial: true, + Merge: true, + }.UnmarshalState(protoiface.UnmarshalInput{ + Buf: b, + Message: mi.ProtoReflect(), + }) + if err != nil { + return err + } + if out.Flags&protoiface.UnmarshalInitialized > 0 { + return nil + } + return checkRequiredNotSet(mi) +} diff --git a/vendor/github.com/golang/protobuf/proto/wrappers.go b/vendor/github.com/golang/protobuf/proto/wrappers.go new file mode 100644 index 00000000000..398e348599b --- /dev/null +++ b/vendor/github.com/golang/protobuf/proto/wrappers.go @@ -0,0 +1,34 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +// Bool stores v in a new bool value and returns a pointer to it. +func Bool(v bool) *bool { return &v } + +// Int stores v in a new int32 value and returns a pointer to it. +// +// Deprecated: Use Int32 instead. +func Int(v int) *int32 { return Int32(int32(v)) } + +// Int32 stores v in a new int32 value and returns a pointer to it. +func Int32(v int32) *int32 { return &v } + +// Int64 stores v in a new int64 value and returns a pointer to it. +func Int64(v int64) *int64 { return &v } + +// Uint32 stores v in a new uint32 value and returns a pointer to it. +func Uint32(v uint32) *uint32 { return &v } + +// Uint64 stores v in a new uint64 value and returns a pointer to it. +func Uint64(v uint64) *uint64 { return &v } + +// Float32 stores v in a new float32 value and returns a pointer to it. +func Float32(v float32) *float32 { return &v } + +// Float64 stores v in a new float64 value and returns a pointer to it. +func Float64(v float64) *float64 { return &v } + +// String stores v in a new string value and returns a pointer to it. +func String(v string) *string { return &v } diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go index d371d56974b..63dc0578514 100644 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go +++ b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go @@ -1,2889 +1,200 @@ // Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/descriptor.proto +// source: github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto package descriptor import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + descriptorpb "google.golang.org/protobuf/types/descriptorpb" + reflect "reflect" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +// Symbols defined in public import of google/protobuf/descriptor.proto. -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +type FieldDescriptorProto_Type = descriptorpb.FieldDescriptorProto_Type -type FieldDescriptorProto_Type int32 +const FieldDescriptorProto_TYPE_DOUBLE = descriptorpb.FieldDescriptorProto_TYPE_DOUBLE +const FieldDescriptorProto_TYPE_FLOAT = descriptorpb.FieldDescriptorProto_TYPE_FLOAT +const FieldDescriptorProto_TYPE_INT64 = descriptorpb.FieldDescriptorProto_TYPE_INT64 +const FieldDescriptorProto_TYPE_UINT64 = descriptorpb.FieldDescriptorProto_TYPE_UINT64 +const FieldDescriptorProto_TYPE_INT32 = descriptorpb.FieldDescriptorProto_TYPE_INT32 +const FieldDescriptorProto_TYPE_FIXED64 = descriptorpb.FieldDescriptorProto_TYPE_FIXED64 +const FieldDescriptorProto_TYPE_FIXED32 = descriptorpb.FieldDescriptorProto_TYPE_FIXED32 +const FieldDescriptorProto_TYPE_BOOL = descriptorpb.FieldDescriptorProto_TYPE_BOOL +const FieldDescriptorProto_TYPE_STRING = descriptorpb.FieldDescriptorProto_TYPE_STRING +const FieldDescriptorProto_TYPE_GROUP = descriptorpb.FieldDescriptorProto_TYPE_GROUP +const FieldDescriptorProto_TYPE_MESSAGE = descriptorpb.FieldDescriptorProto_TYPE_MESSAGE +const FieldDescriptorProto_TYPE_BYTES = descriptorpb.FieldDescriptorProto_TYPE_BYTES +const FieldDescriptorProto_TYPE_UINT32 = descriptorpb.FieldDescriptorProto_TYPE_UINT32 +const FieldDescriptorProto_TYPE_ENUM = descriptorpb.FieldDescriptorProto_TYPE_ENUM +const FieldDescriptorProto_TYPE_SFIXED32 = descriptorpb.FieldDescriptorProto_TYPE_SFIXED32 +const FieldDescriptorProto_TYPE_SFIXED64 = descriptorpb.FieldDescriptorProto_TYPE_SFIXED64 +const FieldDescriptorProto_TYPE_SINT32 = descriptorpb.FieldDescriptorProto_TYPE_SINT32 +const FieldDescriptorProto_TYPE_SINT64 = descriptorpb.FieldDescriptorProto_TYPE_SINT64 -const ( - // 0 is reserved for errors. - // Order is weird for historical reasons. - FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 - FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 - FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 - FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 - FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 - FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 - FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 - FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 - // New in version 2. - FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 - FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 - FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 - FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 - FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 - FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 - FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 -) - -var FieldDescriptorProto_Type_name = map[int32]string{ - 1: "TYPE_DOUBLE", - 2: "TYPE_FLOAT", - 3: "TYPE_INT64", - 4: "TYPE_UINT64", - 5: "TYPE_INT32", - 6: "TYPE_FIXED64", - 7: "TYPE_FIXED32", - 8: "TYPE_BOOL", - 9: "TYPE_STRING", - 10: "TYPE_GROUP", - 11: "TYPE_MESSAGE", - 12: "TYPE_BYTES", - 13: "TYPE_UINT32", - 14: "TYPE_ENUM", - 15: "TYPE_SFIXED32", - 16: "TYPE_SFIXED64", - 17: "TYPE_SINT32", - 18: "TYPE_SINT64", -} - -var FieldDescriptorProto_Type_value = map[string]int32{ - "TYPE_DOUBLE": 1, - "TYPE_FLOAT": 2, - "TYPE_INT64": 3, - "TYPE_UINT64": 4, - "TYPE_INT32": 5, - "TYPE_FIXED64": 6, - "TYPE_FIXED32": 7, - "TYPE_BOOL": 8, - "TYPE_STRING": 9, - "TYPE_GROUP": 10, - "TYPE_MESSAGE": 11, - "TYPE_BYTES": 12, - "TYPE_UINT32": 13, - "TYPE_ENUM": 14, - "TYPE_SFIXED32": 15, - "TYPE_SFIXED64": 16, - "TYPE_SINT32": 17, - "TYPE_SINT64": 18, -} - -func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { - p := new(FieldDescriptorProto_Type) - *p = x - return p -} - -func (x FieldDescriptorProto_Type) String() string { - return proto.EnumName(FieldDescriptorProto_Type_name, int32(x)) -} - -func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type") - if err != nil { - return err - } - *x = FieldDescriptorProto_Type(value) - return nil -} - -func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{4, 0} -} - -type FieldDescriptorProto_Label int32 - -const ( - // 0 is reserved for errors - FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 - FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 - FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 -) - -var FieldDescriptorProto_Label_name = map[int32]string{ - 1: "LABEL_OPTIONAL", - 2: "LABEL_REQUIRED", - 3: "LABEL_REPEATED", -} - -var FieldDescriptorProto_Label_value = map[string]int32{ - "LABEL_OPTIONAL": 1, - "LABEL_REQUIRED": 2, - "LABEL_REPEATED": 3, -} - -func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { - p := new(FieldDescriptorProto_Label) - *p = x - return p -} - -func (x FieldDescriptorProto_Label) String() string { - return proto.EnumName(FieldDescriptorProto_Label_name, int32(x)) -} - -func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label") - if err != nil { - return err - } - *x = FieldDescriptorProto_Label(value) - return nil -} - -func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{4, 1} -} - -// Generated classes can be optimized for speed or code size. -type FileOptions_OptimizeMode int32 - -const ( - FileOptions_SPEED FileOptions_OptimizeMode = 1 - // etc. - FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 - FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 -) - -var FileOptions_OptimizeMode_name = map[int32]string{ - 1: "SPEED", - 2: "CODE_SIZE", - 3: "LITE_RUNTIME", -} - -var FileOptions_OptimizeMode_value = map[string]int32{ - "SPEED": 1, - "CODE_SIZE": 2, - "LITE_RUNTIME": 3, -} - -func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { - p := new(FileOptions_OptimizeMode) - *p = x - return p -} - -func (x FileOptions_OptimizeMode) String() string { - return proto.EnumName(FileOptions_OptimizeMode_name, int32(x)) -} - -func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode") - if err != nil { - return err - } - *x = FileOptions_OptimizeMode(value) - return nil -} - -func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{10, 0} -} - -type FieldOptions_CType int32 - -const ( - // Default mode. - FieldOptions_STRING FieldOptions_CType = 0 - FieldOptions_CORD FieldOptions_CType = 1 - FieldOptions_STRING_PIECE FieldOptions_CType = 2 -) - -var FieldOptions_CType_name = map[int32]string{ - 0: "STRING", - 1: "CORD", - 2: "STRING_PIECE", -} - -var FieldOptions_CType_value = map[string]int32{ - "STRING": 0, - "CORD": 1, - "STRING_PIECE": 2, -} - -func (x FieldOptions_CType) Enum() *FieldOptions_CType { - p := new(FieldOptions_CType) - *p = x - return p -} - -func (x FieldOptions_CType) String() string { - return proto.EnumName(FieldOptions_CType_name, int32(x)) -} - -func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType") - if err != nil { - return err - } - *x = FieldOptions_CType(value) - return nil -} - -func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{12, 0} -} - -type FieldOptions_JSType int32 - -const ( - // Use the default type. - FieldOptions_JS_NORMAL FieldOptions_JSType = 0 - // Use JavaScript strings. - FieldOptions_JS_STRING FieldOptions_JSType = 1 - // Use JavaScript numbers. - FieldOptions_JS_NUMBER FieldOptions_JSType = 2 -) - -var FieldOptions_JSType_name = map[int32]string{ - 0: "JS_NORMAL", - 1: "JS_STRING", - 2: "JS_NUMBER", -} - -var FieldOptions_JSType_value = map[string]int32{ - "JS_NORMAL": 0, - "JS_STRING": 1, - "JS_NUMBER": 2, -} - -func (x FieldOptions_JSType) Enum() *FieldOptions_JSType { - p := new(FieldOptions_JSType) - *p = x - return p -} - -func (x FieldOptions_JSType) String() string { - return proto.EnumName(FieldOptions_JSType_name, int32(x)) -} - -func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType") - if err != nil { - return err - } - *x = FieldOptions_JSType(value) - return nil -} - -func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{12, 1} -} - -// Is this method side-effect-free (or safe in HTTP parlance), or idempotent, -// or neither? HTTP based RPC implementation may choose GET verb for safe -// methods, and PUT verb for idempotent methods instead of the default POST. -type MethodOptions_IdempotencyLevel int32 - -const ( - MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0 - MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1 - MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2 -) - -var MethodOptions_IdempotencyLevel_name = map[int32]string{ - 0: "IDEMPOTENCY_UNKNOWN", - 1: "NO_SIDE_EFFECTS", - 2: "IDEMPOTENT", -} - -var MethodOptions_IdempotencyLevel_value = map[string]int32{ - "IDEMPOTENCY_UNKNOWN": 0, - "NO_SIDE_EFFECTS": 1, - "IDEMPOTENT": 2, -} - -func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel { - p := new(MethodOptions_IdempotencyLevel) - *p = x - return p -} - -func (x MethodOptions_IdempotencyLevel) String() string { - return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x)) -} - -func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel") - if err != nil { - return err - } - *x = MethodOptions_IdempotencyLevel(value) - return nil -} - -func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{17, 0} -} - -// The protocol compiler can output a FileDescriptorSet containing the .proto -// files it parses. -type FileDescriptorSet struct { - File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} } -func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorSet) ProtoMessage() {} -func (*FileDescriptorSet) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{0} -} - -func (m *FileDescriptorSet) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorSet.Unmarshal(m, b) -} -func (m *FileDescriptorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorSet.Marshal(b, m, deterministic) -} -func (m *FileDescriptorSet) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorSet.Merge(m, src) -} -func (m *FileDescriptorSet) XXX_Size() int { - return xxx_messageInfo_FileDescriptorSet.Size(m) -} -func (m *FileDescriptorSet) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorSet.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorSet proto.InternalMessageInfo - -func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto { - if m != nil { - return m.File - } - return nil -} - -// Describes a complete .proto file. -type FileDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"` - // Names of files imported by this file. - Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"` - // Indexes of the public imported files in the dependency list above. - PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"` - // Indexes of the weak imported files in the dependency list. - // For Google-internal migration only. Do not use. - WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"` - // All top-level definitions in this file. - MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"` - Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - // This field contains optional information about the original source code. - // You may safely remove this entire field without harming runtime - // functionality of the descriptors -- the information is needed only by - // development tools. - SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"` - // The syntax of the proto file. - // The supported values are "proto2" and "proto3". - Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} } -func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorProto) ProtoMessage() {} -func (*FileDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{1} -} - -func (m *FileDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorProto.Unmarshal(m, b) -} -func (m *FileDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorProto.Marshal(b, m, deterministic) -} -func (m *FileDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorProto.Merge(m, src) -} -func (m *FileDescriptorProto) XXX_Size() int { - return xxx_messageInfo_FileDescriptorProto.Size(m) -} -func (m *FileDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorProto proto.InternalMessageInfo - -func (m *FileDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FileDescriptorProto) GetPackage() string { - if m != nil && m.Package != nil { - return *m.Package - } - return "" -} - -func (m *FileDescriptorProto) GetDependency() []string { - if m != nil { - return m.Dependency - } - return nil -} - -func (m *FileDescriptorProto) GetPublicDependency() []int32 { - if m != nil { - return m.PublicDependency - } - return nil -} - -func (m *FileDescriptorProto) GetWeakDependency() []int32 { - if m != nil { - return m.WeakDependency - } - return nil -} - -func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto { - if m != nil { - return m.MessageType - } - return nil -} - -func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto { - if m != nil { - return m.Service - } - return nil -} - -func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *FileDescriptorProto) GetOptions() *FileOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo { - if m != nil { - return m.SourceCodeInfo - } - return nil -} - -func (m *FileDescriptorProto) GetSyntax() string { - if m != nil && m.Syntax != nil { - return *m.Syntax - } - return "" -} - -// Describes a message type. -type DescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"` - NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"` - OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"` - Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"` - ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` - // Reserved field names, which may not be used by fields in the same message. - // A given name may only be reserved once. - ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto) Reset() { *m = DescriptorProto{} } -func (m *DescriptorProto) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto) ProtoMessage() {} -func (*DescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{2} -} - -func (m *DescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto.Unmarshal(m, b) -} -func (m *DescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto.Marshal(b, m, deterministic) -} -func (m *DescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto.Merge(m, src) -} -func (m *DescriptorProto) XXX_Size() int { - return xxx_messageInfo_DescriptorProto.Size(m) -} -func (m *DescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto proto.InternalMessageInfo - -func (m *DescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *DescriptorProto) GetField() []*FieldDescriptorProto { - if m != nil { - return m.Field - } - return nil -} - -func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *DescriptorProto) GetNestedType() []*DescriptorProto { - if m != nil { - return m.NestedType - } - return nil -} - -func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange { - if m != nil { - return m.ExtensionRange - } - return nil -} - -func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto { - if m != nil { - return m.OneofDecl - } - return nil -} - -func (m *DescriptorProto) GetOptions() *MessageOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange { - if m != nil { - return m.ReservedRange - } - return nil -} - -func (m *DescriptorProto) GetReservedName() []string { - if m != nil { - return m.ReservedName - } - return nil -} - -type DescriptorProto_ExtensionRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} } -func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ExtensionRange) ProtoMessage() {} -func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{2, 0} -} - -func (m *DescriptorProto_ExtensionRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Unmarshal(m, b) -} -func (m *DescriptorProto_ExtensionRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Marshal(b, m, deterministic) -} -func (m *DescriptorProto_ExtensionRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto_ExtensionRange.Merge(m, src) -} -func (m *DescriptorProto_ExtensionRange) XXX_Size() int { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Size(m) -} -func (m *DescriptorProto_ExtensionRange) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto_ExtensionRange.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto_ExtensionRange proto.InternalMessageInfo - -func (m *DescriptorProto_ExtensionRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions { - if m != nil { - return m.Options - } - return nil -} - -// Range of reserved tag numbers. Reserved tag numbers may not be used by -// fields or extension ranges in the same message. Reserved ranges may -// not overlap. -type DescriptorProto_ReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} } -func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ReservedRange) ProtoMessage() {} -func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{2, 1} -} - -func (m *DescriptorProto_ReservedRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto_ReservedRange.Unmarshal(m, b) -} -func (m *DescriptorProto_ReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto_ReservedRange.Marshal(b, m, deterministic) -} -func (m *DescriptorProto_ReservedRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto_ReservedRange.Merge(m, src) -} -func (m *DescriptorProto_ReservedRange) XXX_Size() int { - return xxx_messageInfo_DescriptorProto_ReservedRange.Size(m) -} -func (m *DescriptorProto_ReservedRange) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto_ReservedRange.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto_ReservedRange proto.InternalMessageInfo - -func (m *DescriptorProto_ReservedRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ReservedRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -type ExtensionRangeOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} } -func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) } -func (*ExtensionRangeOptions) ProtoMessage() {} -func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{3} -} - -var extRange_ExtensionRangeOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ExtensionRangeOptions -} - -func (m *ExtensionRangeOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExtensionRangeOptions.Unmarshal(m, b) -} -func (m *ExtensionRangeOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExtensionRangeOptions.Marshal(b, m, deterministic) -} -func (m *ExtensionRangeOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExtensionRangeOptions.Merge(m, src) -} -func (m *ExtensionRangeOptions) XXX_Size() int { - return xxx_messageInfo_ExtensionRangeOptions.Size(m) -} -func (m *ExtensionRangeOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ExtensionRangeOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ExtensionRangeOptions proto.InternalMessageInfo - -func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// Describes a field within a message. -type FieldDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"` - Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"` - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. - Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"` - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"` - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"` - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - // TODO(kenton): Base-64 encode? - DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"` - // If set, gives the index of a oneof in the containing type's oneof_decl - // list. This field is a member of that oneof. - OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"` - // JSON name of this field. The value is set by protocol compiler. If the - // user has set a "json_name" option on this field, that option's value - // will be used. Otherwise, it's deduced from the field's name by converting - // it to camelCase. - JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"` - Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} } -func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FieldDescriptorProto) ProtoMessage() {} -func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{4} -} - -func (m *FieldDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FieldDescriptorProto.Unmarshal(m, b) -} -func (m *FieldDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FieldDescriptorProto.Marshal(b, m, deterministic) -} -func (m *FieldDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_FieldDescriptorProto.Merge(m, src) -} -func (m *FieldDescriptorProto) XXX_Size() int { - return xxx_messageInfo_FieldDescriptorProto.Size(m) -} -func (m *FieldDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_FieldDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_FieldDescriptorProto proto.InternalMessageInfo - -func (m *FieldDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FieldDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label { - if m != nil && m.Label != nil { - return *m.Label - } - return FieldDescriptorProto_LABEL_OPTIONAL -} - -func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type { - if m != nil && m.Type != nil { - return *m.Type - } - return FieldDescriptorProto_TYPE_DOUBLE -} - -func (m *FieldDescriptorProto) GetTypeName() string { - if m != nil && m.TypeName != nil { - return *m.TypeName - } - return "" -} - -func (m *FieldDescriptorProto) GetExtendee() string { - if m != nil && m.Extendee != nil { - return *m.Extendee - } - return "" -} - -func (m *FieldDescriptorProto) GetDefaultValue() string { - if m != nil && m.DefaultValue != nil { - return *m.DefaultValue - } - return "" -} - -func (m *FieldDescriptorProto) GetOneofIndex() int32 { - if m != nil && m.OneofIndex != nil { - return *m.OneofIndex - } - return 0 -} - -func (m *FieldDescriptorProto) GetJsonName() string { - if m != nil && m.JsonName != nil { - return *m.JsonName - } - return "" -} - -func (m *FieldDescriptorProto) GetOptions() *FieldOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a oneof. -type OneofDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} } -func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*OneofDescriptorProto) ProtoMessage() {} -func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{5} -} - -func (m *OneofDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OneofDescriptorProto.Unmarshal(m, b) -} -func (m *OneofDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OneofDescriptorProto.Marshal(b, m, deterministic) -} -func (m *OneofDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_OneofDescriptorProto.Merge(m, src) -} -func (m *OneofDescriptorProto) XXX_Size() int { - return xxx_messageInfo_OneofDescriptorProto.Size(m) -} -func (m *OneofDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_OneofDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_OneofDescriptorProto proto.InternalMessageInfo - -func (m *OneofDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *OneofDescriptorProto) GetOptions() *OneofOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes an enum type. -type EnumDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` - Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - // Range of reserved numeric values. Reserved numeric values may not be used - // by enum values in the same enum declaration. Reserved ranges may not - // overlap. - ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` - // Reserved enum value names, which may not be reused. A given name may only - // be reserved once. - ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } -func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto) ProtoMessage() {} -func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{6} -} - -func (m *EnumDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumDescriptorProto.Unmarshal(m, b) -} -func (m *EnumDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumDescriptorProto.Marshal(b, m, deterministic) -} -func (m *EnumDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumDescriptorProto.Merge(m, src) -} -func (m *EnumDescriptorProto) XXX_Size() int { - return xxx_messageInfo_EnumDescriptorProto.Size(m) -} -func (m *EnumDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_EnumDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumDescriptorProto proto.InternalMessageInfo - -func (m *EnumDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto { - if m != nil { - return m.Value - } - return nil -} - -func (m *EnumDescriptorProto) GetOptions() *EnumOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *EnumDescriptorProto) GetReservedRange() []*EnumDescriptorProto_EnumReservedRange { - if m != nil { - return m.ReservedRange - } - return nil -} - -func (m *EnumDescriptorProto) GetReservedName() []string { - if m != nil { - return m.ReservedName - } - return nil -} - -// Range of reserved numeric values. Reserved values may not be used by -// entries in the same enum. Reserved ranges may not overlap. -// -// Note that this is distinct from DescriptorProto.ReservedRange in that it -// is inclusive such that it can appropriately represent the entire int32 -// domain. -type EnumDescriptorProto_EnumReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumDescriptorProto_EnumReservedRange) Reset() { *m = EnumDescriptorProto_EnumReservedRange{} } -func (m *EnumDescriptorProto_EnumReservedRange) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {} -func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{6, 0} -} - -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Unmarshal(m, b) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Marshal(b, m, deterministic) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Merge(m, src) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Size() int { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Size(m) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_DiscardUnknown() { - xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumDescriptorProto_EnumReservedRange proto.InternalMessageInfo - -func (m *EnumDescriptorProto_EnumReservedRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -// Describes a value within an enum. -type EnumValueDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` - Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} } -func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumValueDescriptorProto) ProtoMessage() {} -func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{7} -} - -func (m *EnumValueDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumValueDescriptorProto.Unmarshal(m, b) -} -func (m *EnumValueDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumValueDescriptorProto.Marshal(b, m, deterministic) -} -func (m *EnumValueDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumValueDescriptorProto.Merge(m, src) -} -func (m *EnumValueDescriptorProto) XXX_Size() int { - return xxx_messageInfo_EnumValueDescriptorProto.Size(m) -} -func (m *EnumValueDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_EnumValueDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumValueDescriptorProto proto.InternalMessageInfo - -func (m *EnumValueDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumValueDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a service. -type ServiceDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` - Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} } -func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*ServiceDescriptorProto) ProtoMessage() {} -func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{8} -} - -func (m *ServiceDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceDescriptorProto.Unmarshal(m, b) -} -func (m *ServiceDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceDescriptorProto.Marshal(b, m, deterministic) -} -func (m *ServiceDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceDescriptorProto.Merge(m, src) -} -func (m *ServiceDescriptorProto) XXX_Size() int { - return xxx_messageInfo_ServiceDescriptorProto.Size(m) -} -func (m *ServiceDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceDescriptorProto proto.InternalMessageInfo - -func (m *ServiceDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto { - if m != nil { - return m.Method - } - return nil -} - -func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a method of a service. -type MethodDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"` - OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"` - Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"` - // Identifies if client streams multiple client messages - ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"` - // Identifies if server streams multiple server messages - ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} } -func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*MethodDescriptorProto) ProtoMessage() {} -func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{9} -} - -func (m *MethodDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MethodDescriptorProto.Unmarshal(m, b) -} -func (m *MethodDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MethodDescriptorProto.Marshal(b, m, deterministic) -} -func (m *MethodDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_MethodDescriptorProto.Merge(m, src) -} -func (m *MethodDescriptorProto) XXX_Size() int { - return xxx_messageInfo_MethodDescriptorProto.Size(m) -} -func (m *MethodDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_MethodDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_MethodDescriptorProto proto.InternalMessageInfo - -const Default_MethodDescriptorProto_ClientStreaming bool = false -const Default_MethodDescriptorProto_ServerStreaming bool = false - -func (m *MethodDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MethodDescriptorProto) GetInputType() string { - if m != nil && m.InputType != nil { - return *m.InputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOutputType() string { - if m != nil && m.OutputType != nil { - return *m.OutputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOptions() *MethodOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *MethodDescriptorProto) GetClientStreaming() bool { - if m != nil && m.ClientStreaming != nil { - return *m.ClientStreaming - } - return Default_MethodDescriptorProto_ClientStreaming -} - -func (m *MethodDescriptorProto) GetServerStreaming() bool { - if m != nil && m.ServerStreaming != nil { - return *m.ServerStreaming - } - return Default_MethodDescriptorProto_ServerStreaming -} - -type FileOptions struct { - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"` - // If set, all the classes from the .proto file are wrapped in a single - // outer class with the given name. This applies to both Proto1 - // (equivalent to the old "--one_java_file" option) and Proto2 (where - // a .proto always translates to a single class, but you may want to - // explicitly choose the class name). - JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"` - // If set true, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the outer class - // named by java_outer_classname. However, the outer class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"` - // This option does nothing. - JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // Deprecated: Do not use. - // If set true, then the Java2 code generator will generate code that - // throws an exception whenever an attempt is made to assign a non-UTF-8 - // byte sequence to a string field. - // Message reflection will do the same. - // However, an extension field still accepts non-UTF-8 byte sequences. - // This option has no effect on when used with the lite runtime. - JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"` - OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"` - // Sets the Go package where structs generated from this .proto will be - // placed. If omitted, the Go package will be derived from the following: - // - The basename of the package import path, if provided. - // - Otherwise, the package statement in the .proto file, if present. - // - Otherwise, the basename of the .proto file, without extension. - GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"` - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of google.protobuf. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. Therefore, - // these default to false. Old code which depends on generic services should - // explicitly set them to true. - CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"` - JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"` - PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"` - PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"` - // Is this file deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for everything in the file, or it will be completely ignored; in the very - // least, this is a formalization for deprecating files. - Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Enables the use of arenas for the proto messages in this file. This applies - // only to generated classes for C++. - CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"` - // Sets the objective c class prefix which is prepended to all objective c - // generated classes from this .proto. There is no default. - ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"` - // Namespace for generated classes; defaults to the package. - CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"` - // By default Swift generators will take the proto package and CamelCase it - // replacing '.' with underscore and use that to prefix the types/symbols - // defined. When this options is provided, they will use this value instead - // to prefix the types/symbols defined. - SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"` - // Sets the php class prefix which is prepended to all php generated classes - // from this .proto. Default is empty. - PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"` - // Use this option to change the namespace of php generated classes. Default - // is empty. When this option is empty, the package name will be used for - // determining the namespace. - PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"` - // Use this option to change the namespace of php generated metadata classes. - // Default is empty. When this option is empty, the proto file name will be - // used for determining the namespace. - PhpMetadataNamespace *string `protobuf:"bytes,44,opt,name=php_metadata_namespace,json=phpMetadataNamespace" json:"php_metadata_namespace,omitempty"` - // Use this option to change the package of ruby generated classes. Default - // is empty. When this option is not set, the package name will be used for - // determining the ruby package. - RubyPackage *string `protobuf:"bytes,45,opt,name=ruby_package,json=rubyPackage" json:"ruby_package,omitempty"` - // The parser stores options it doesn't recognize here. - // See the documentation for the "Options" section above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileOptions) Reset() { *m = FileOptions{} } -func (m *FileOptions) String() string { return proto.CompactTextString(m) } -func (*FileOptions) ProtoMessage() {} -func (*FileOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{10} -} - -var extRange_FileOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FileOptions -} - -func (m *FileOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileOptions.Unmarshal(m, b) -} -func (m *FileOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileOptions.Marshal(b, m, deterministic) -} -func (m *FileOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileOptions.Merge(m, src) -} -func (m *FileOptions) XXX_Size() int { - return xxx_messageInfo_FileOptions.Size(m) -} -func (m *FileOptions) XXX_DiscardUnknown() { - xxx_messageInfo_FileOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_FileOptions proto.InternalMessageInfo - -const Default_FileOptions_JavaMultipleFiles bool = false -const Default_FileOptions_JavaStringCheckUtf8 bool = false -const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED -const Default_FileOptions_CcGenericServices bool = false -const Default_FileOptions_JavaGenericServices bool = false -const Default_FileOptions_PyGenericServices bool = false -const Default_FileOptions_PhpGenericServices bool = false -const Default_FileOptions_Deprecated bool = false -const Default_FileOptions_CcEnableArenas bool = false - -func (m *FileOptions) GetJavaPackage() string { - if m != nil && m.JavaPackage != nil { - return *m.JavaPackage - } - return "" -} - -func (m *FileOptions) GetJavaOuterClassname() string { - if m != nil && m.JavaOuterClassname != nil { - return *m.JavaOuterClassname - } - return "" -} - -func (m *FileOptions) GetJavaMultipleFiles() bool { - if m != nil && m.JavaMultipleFiles != nil { - return *m.JavaMultipleFiles - } - return Default_FileOptions_JavaMultipleFiles -} - -// Deprecated: Do not use. -func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool { - if m != nil && m.JavaGenerateEqualsAndHash != nil { - return *m.JavaGenerateEqualsAndHash - } - return false -} - -func (m *FileOptions) GetJavaStringCheckUtf8() bool { - if m != nil && m.JavaStringCheckUtf8 != nil { - return *m.JavaStringCheckUtf8 - } - return Default_FileOptions_JavaStringCheckUtf8 -} - -func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode { - if m != nil && m.OptimizeFor != nil { - return *m.OptimizeFor - } - return Default_FileOptions_OptimizeFor -} - -func (m *FileOptions) GetGoPackage() string { - if m != nil && m.GoPackage != nil { - return *m.GoPackage - } - return "" -} - -func (m *FileOptions) GetCcGenericServices() bool { - if m != nil && m.CcGenericServices != nil { - return *m.CcGenericServices - } - return Default_FileOptions_CcGenericServices -} - -func (m *FileOptions) GetJavaGenericServices() bool { - if m != nil && m.JavaGenericServices != nil { - return *m.JavaGenericServices - } - return Default_FileOptions_JavaGenericServices -} - -func (m *FileOptions) GetPyGenericServices() bool { - if m != nil && m.PyGenericServices != nil { - return *m.PyGenericServices - } - return Default_FileOptions_PyGenericServices -} - -func (m *FileOptions) GetPhpGenericServices() bool { - if m != nil && m.PhpGenericServices != nil { - return *m.PhpGenericServices - } - return Default_FileOptions_PhpGenericServices -} - -func (m *FileOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FileOptions_Deprecated -} - -func (m *FileOptions) GetCcEnableArenas() bool { - if m != nil && m.CcEnableArenas != nil { - return *m.CcEnableArenas - } - return Default_FileOptions_CcEnableArenas -} - -func (m *FileOptions) GetObjcClassPrefix() string { - if m != nil && m.ObjcClassPrefix != nil { - return *m.ObjcClassPrefix - } - return "" -} - -func (m *FileOptions) GetCsharpNamespace() string { - if m != nil && m.CsharpNamespace != nil { - return *m.CsharpNamespace - } - return "" -} - -func (m *FileOptions) GetSwiftPrefix() string { - if m != nil && m.SwiftPrefix != nil { - return *m.SwiftPrefix - } - return "" -} - -func (m *FileOptions) GetPhpClassPrefix() string { - if m != nil && m.PhpClassPrefix != nil { - return *m.PhpClassPrefix - } - return "" -} - -func (m *FileOptions) GetPhpNamespace() string { - if m != nil && m.PhpNamespace != nil { - return *m.PhpNamespace - } - return "" -} - -func (m *FileOptions) GetPhpMetadataNamespace() string { - if m != nil && m.PhpMetadataNamespace != nil { - return *m.PhpMetadataNamespace - } - return "" -} - -func (m *FileOptions) GetRubyPackage() string { - if m != nil && m.RubyPackage != nil { - return *m.RubyPackage - } - return "" -} - -func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MessageOptions struct { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"` - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"` - // Is this message deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the message, or it will be completely ignored; in the very least, - // this is a formalization for deprecating messages. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementations still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MessageOptions) Reset() { *m = MessageOptions{} } -func (m *MessageOptions) String() string { return proto.CompactTextString(m) } -func (*MessageOptions) ProtoMessage() {} -func (*MessageOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{11} -} - -var extRange_MessageOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MessageOptions -} - -func (m *MessageOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MessageOptions.Unmarshal(m, b) -} -func (m *MessageOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MessageOptions.Marshal(b, m, deterministic) -} -func (m *MessageOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_MessageOptions.Merge(m, src) -} -func (m *MessageOptions) XXX_Size() int { - return xxx_messageInfo_MessageOptions.Size(m) -} -func (m *MessageOptions) XXX_DiscardUnknown() { - xxx_messageInfo_MessageOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_MessageOptions proto.InternalMessageInfo - -const Default_MessageOptions_MessageSetWireFormat bool = false -const Default_MessageOptions_NoStandardDescriptorAccessor bool = false -const Default_MessageOptions_Deprecated bool = false - -func (m *MessageOptions) GetMessageSetWireFormat() bool { - if m != nil && m.MessageSetWireFormat != nil { - return *m.MessageSetWireFormat - } - return Default_MessageOptions_MessageSetWireFormat -} - -func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool { - if m != nil && m.NoStandardDescriptorAccessor != nil { - return *m.NoStandardDescriptorAccessor - } - return Default_MessageOptions_NoStandardDescriptorAccessor -} - -func (m *MessageOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MessageOptions_Deprecated -} - -func (m *MessageOptions) GetMapEntry() bool { - if m != nil && m.MapEntry != nil { - return *m.MapEntry - } - return false -} - -func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type FieldOptions struct { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"` - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. In proto3, only explicit setting it to - // false will avoid using packed encoding. - Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"` - // The jstype option determines the JavaScript type used for values of the - // field. The option is permitted only for 64 bit integral and fixed types - // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING - // is represented as JavaScript string, which avoids loss of precision that - // can happen when a large value is converted to a floating point JavaScript. - // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to - // use the JavaScript "number" type. The behavior of the default option - // JS_NORMAL is implementation dependent. - // - // This option is an enum to permit additional types to be added, e.g. - // goog.math.Integer. - Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"` - // Should this field be parsed lazily? Lazy applies only to message-type - // fields. It means that when the outer message is initially parsed, the - // inner message's contents will not be parsed but instead stored in encoded - // form. The inner message will actually be parsed when it is first accessed. - // - // This is only a hint. Implementations are free to choose whether to use - // eager or lazy parsing regardless of the value of this option. However, - // setting this option true suggests that the protocol author believes that - // using lazy parsing on this field is worth the additional bookkeeping - // overhead typically needed to implement it. - // - // This option does not affect the public interface of any generated code; - // all method signatures remain the same. Furthermore, thread-safety of the - // interface is not affected by this option; const methods remain safe to - // call from multiple threads concurrently, while non-const methods continue - // to require exclusive access. - // - // - // Note that implementations may choose not to check required fields within - // a lazy sub-message. That is, calling IsInitialized() on the outer message - // may return true even if the inner message has missing required fields. - // This is necessary because otherwise the inner message would have to be - // parsed in order to perform the check, defeating the purpose of lazy - // parsing. An implementation which chooses not to check required fields - // must be consistent about it. That is, for any particular sub-message, the - // implementation must either *always* check its required fields, or *never* - // check its required fields, regardless of whether or not the message has - // been parsed. - Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"` - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // For Google-internal migration only. Do not use. - Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FieldOptions) Reset() { *m = FieldOptions{} } -func (m *FieldOptions) String() string { return proto.CompactTextString(m) } -func (*FieldOptions) ProtoMessage() {} -func (*FieldOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{12} -} - -var extRange_FieldOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FieldOptions -} +var FieldDescriptorProto_Type_name = descriptorpb.FieldDescriptorProto_Type_name +var FieldDescriptorProto_Type_value = descriptorpb.FieldDescriptorProto_Type_value -func (m *FieldOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FieldOptions.Unmarshal(m, b) -} -func (m *FieldOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FieldOptions.Marshal(b, m, deterministic) -} -func (m *FieldOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_FieldOptions.Merge(m, src) -} -func (m *FieldOptions) XXX_Size() int { - return xxx_messageInfo_FieldOptions.Size(m) -} -func (m *FieldOptions) XXX_DiscardUnknown() { - xxx_messageInfo_FieldOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_FieldOptions proto.InternalMessageInfo - -const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING -const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL -const Default_FieldOptions_Lazy bool = false -const Default_FieldOptions_Deprecated bool = false -const Default_FieldOptions_Weak bool = false - -func (m *FieldOptions) GetCtype() FieldOptions_CType { - if m != nil && m.Ctype != nil { - return *m.Ctype - } - return Default_FieldOptions_Ctype -} - -func (m *FieldOptions) GetPacked() bool { - if m != nil && m.Packed != nil { - return *m.Packed - } - return false -} - -func (m *FieldOptions) GetJstype() FieldOptions_JSType { - if m != nil && m.Jstype != nil { - return *m.Jstype - } - return Default_FieldOptions_Jstype -} - -func (m *FieldOptions) GetLazy() bool { - if m != nil && m.Lazy != nil { - return *m.Lazy - } - return Default_FieldOptions_Lazy -} - -func (m *FieldOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FieldOptions_Deprecated -} - -func (m *FieldOptions) GetWeak() bool { - if m != nil && m.Weak != nil { - return *m.Weak - } - return Default_FieldOptions_Weak -} - -func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type OneofOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OneofOptions) Reset() { *m = OneofOptions{} } -func (m *OneofOptions) String() string { return proto.CompactTextString(m) } -func (*OneofOptions) ProtoMessage() {} -func (*OneofOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{13} -} - -var extRange_OneofOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_OneofOptions -} - -func (m *OneofOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OneofOptions.Unmarshal(m, b) -} -func (m *OneofOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OneofOptions.Marshal(b, m, deterministic) -} -func (m *OneofOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_OneofOptions.Merge(m, src) -} -func (m *OneofOptions) XXX_Size() int { - return xxx_messageInfo_OneofOptions.Size(m) -} -func (m *OneofOptions) XXX_DiscardUnknown() { - xxx_messageInfo_OneofOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_OneofOptions proto.InternalMessageInfo - -func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumOptions struct { - // Set this option to true to allow mapping different tag names to the same - // value. - AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"` - // Is this enum deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum, or it will be completely ignored; in the very least, this - // is a formalization for deprecating enums. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumOptions) Reset() { *m = EnumOptions{} } -func (m *EnumOptions) String() string { return proto.CompactTextString(m) } -func (*EnumOptions) ProtoMessage() {} -func (*EnumOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{14} -} - -var extRange_EnumOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumOptions -} - -func (m *EnumOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumOptions.Unmarshal(m, b) -} -func (m *EnumOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumOptions.Marshal(b, m, deterministic) -} -func (m *EnumOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumOptions.Merge(m, src) -} -func (m *EnumOptions) XXX_Size() int { - return xxx_messageInfo_EnumOptions.Size(m) -} -func (m *EnumOptions) XXX_DiscardUnknown() { - xxx_messageInfo_EnumOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumOptions proto.InternalMessageInfo - -const Default_EnumOptions_Deprecated bool = false - -func (m *EnumOptions) GetAllowAlias() bool { - if m != nil && m.AllowAlias != nil { - return *m.AllowAlias - } - return false -} - -func (m *EnumOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumOptions_Deprecated -} - -func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumValueOptions struct { - // Is this enum value deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum value, or it will be completely ignored; in the very least, - // this is a formalization for deprecating enum values. - Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} } -func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) } -func (*EnumValueOptions) ProtoMessage() {} -func (*EnumValueOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{15} -} - -var extRange_EnumValueOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumValueOptions -} - -func (m *EnumValueOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumValueOptions.Unmarshal(m, b) -} -func (m *EnumValueOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumValueOptions.Marshal(b, m, deterministic) -} -func (m *EnumValueOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumValueOptions.Merge(m, src) -} -func (m *EnumValueOptions) XXX_Size() int { - return xxx_messageInfo_EnumValueOptions.Size(m) -} -func (m *EnumValueOptions) XXX_DiscardUnknown() { - xxx_messageInfo_EnumValueOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumValueOptions proto.InternalMessageInfo - -const Default_EnumValueOptions_Deprecated bool = false - -func (m *EnumValueOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumValueOptions_Deprecated -} - -func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type ServiceOptions struct { - // Is this service deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the service, or it will be completely ignored; in the very least, - // this is a formalization for deprecating services. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceOptions) Reset() { *m = ServiceOptions{} } -func (m *ServiceOptions) String() string { return proto.CompactTextString(m) } -func (*ServiceOptions) ProtoMessage() {} -func (*ServiceOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{16} -} - -var extRange_ServiceOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ServiceOptions -} - -func (m *ServiceOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceOptions.Unmarshal(m, b) -} -func (m *ServiceOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceOptions.Marshal(b, m, deterministic) -} -func (m *ServiceOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceOptions.Merge(m, src) -} -func (m *ServiceOptions) XXX_Size() int { - return xxx_messageInfo_ServiceOptions.Size(m) -} -func (m *ServiceOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceOptions proto.InternalMessageInfo - -const Default_ServiceOptions_Deprecated bool = false - -func (m *ServiceOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_ServiceOptions_Deprecated -} - -func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MethodOptions struct { - // Is this method deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the method, or it will be completely ignored; in the very least, - // this is a formalization for deprecating methods. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MethodOptions) Reset() { *m = MethodOptions{} } -func (m *MethodOptions) String() string { return proto.CompactTextString(m) } -func (*MethodOptions) ProtoMessage() {} -func (*MethodOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{17} -} - -var extRange_MethodOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MethodOptions -} - -func (m *MethodOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MethodOptions.Unmarshal(m, b) -} -func (m *MethodOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MethodOptions.Marshal(b, m, deterministic) -} -func (m *MethodOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_MethodOptions.Merge(m, src) -} -func (m *MethodOptions) XXX_Size() int { - return xxx_messageInfo_MethodOptions.Size(m) -} -func (m *MethodOptions) XXX_DiscardUnknown() { - xxx_messageInfo_MethodOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_MethodOptions proto.InternalMessageInfo - -const Default_MethodOptions_Deprecated bool = false -const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN - -func (m *MethodOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MethodOptions_Deprecated -} - -func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel { - if m != nil && m.IdempotencyLevel != nil { - return *m.IdempotencyLevel - } - return Default_MethodOptions_IdempotencyLevel -} - -func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// A message representing a option the parser does not recognize. This only -// appears in options protos created by the compiler::Parser class. -// DescriptorPool resolves these when building Descriptor objects. Therefore, -// options protos in descriptor objects (e.g. returned by Descriptor::options(), -// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions -// in them. -type UninterpretedOption struct { - Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"` - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"` - PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"` - NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"` - DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} } -func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption) ProtoMessage() {} -func (*UninterpretedOption) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{18} -} - -func (m *UninterpretedOption) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UninterpretedOption.Unmarshal(m, b) -} -func (m *UninterpretedOption) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UninterpretedOption.Marshal(b, m, deterministic) -} -func (m *UninterpretedOption) XXX_Merge(src proto.Message) { - xxx_messageInfo_UninterpretedOption.Merge(m, src) -} -func (m *UninterpretedOption) XXX_Size() int { - return xxx_messageInfo_UninterpretedOption.Size(m) -} -func (m *UninterpretedOption) XXX_DiscardUnknown() { - xxx_messageInfo_UninterpretedOption.DiscardUnknown(m) -} - -var xxx_messageInfo_UninterpretedOption proto.InternalMessageInfo - -func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart { - if m != nil { - return m.Name - } - return nil -} - -func (m *UninterpretedOption) GetIdentifierValue() string { - if m != nil && m.IdentifierValue != nil { - return *m.IdentifierValue - } - return "" -} - -func (m *UninterpretedOption) GetPositiveIntValue() uint64 { - if m != nil && m.PositiveIntValue != nil { - return *m.PositiveIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetNegativeIntValue() int64 { - if m != nil && m.NegativeIntValue != nil { - return *m.NegativeIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetDoubleValue() float64 { - if m != nil && m.DoubleValue != nil { - return *m.DoubleValue - } - return 0 -} - -func (m *UninterpretedOption) GetStringValue() []byte { - if m != nil { - return m.StringValue - } - return nil -} - -func (m *UninterpretedOption) GetAggregateValue() string { - if m != nil && m.AggregateValue != nil { - return *m.AggregateValue - } - return "" -} - -// The name of the uninterpreted option. Each string represents a segment in -// a dot-separated name. is_extension is true iff a segment represents an -// extension (denoted with parentheses in options specs in .proto files). -// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents -// "foo.(bar.baz).qux". -type UninterpretedOption_NamePart struct { - NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"` - IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} } -func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption_NamePart) ProtoMessage() {} -func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{18, 0} -} - -func (m *UninterpretedOption_NamePart) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UninterpretedOption_NamePart.Unmarshal(m, b) -} -func (m *UninterpretedOption_NamePart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UninterpretedOption_NamePart.Marshal(b, m, deterministic) -} -func (m *UninterpretedOption_NamePart) XXX_Merge(src proto.Message) { - xxx_messageInfo_UninterpretedOption_NamePart.Merge(m, src) -} -func (m *UninterpretedOption_NamePart) XXX_Size() int { - return xxx_messageInfo_UninterpretedOption_NamePart.Size(m) -} -func (m *UninterpretedOption_NamePart) XXX_DiscardUnknown() { - xxx_messageInfo_UninterpretedOption_NamePart.DiscardUnknown(m) -} - -var xxx_messageInfo_UninterpretedOption_NamePart proto.InternalMessageInfo - -func (m *UninterpretedOption_NamePart) GetNamePart() string { - if m != nil && m.NamePart != nil { - return *m.NamePart - } - return "" -} - -func (m *UninterpretedOption_NamePart) GetIsExtension() bool { - if m != nil && m.IsExtension != nil { - return *m.IsExtension - } - return false -} - -// Encapsulates information about the original source file from which a -// FileDescriptorProto was generated. -type SourceCodeInfo struct { - // A Location identifies a piece of source code in a .proto file which - // corresponds to a particular definition. This information is intended - // to be useful to IDEs, code indexers, documentation generators, and similar - // tools. - // - // For example, say we have a file like: - // message Foo { - // optional string foo = 1; - // } - // Let's look at just the field definition: - // optional string foo = 1; - // ^ ^^ ^^ ^ ^^^ - // a bc de f ghi - // We have the following locations: - // span path represents - // [a,i) [ 4, 0, 2, 0 ] The whole field definition. - // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). - // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). - // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). - // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). - // - // Notes: - // - A location may refer to a repeated field itself (i.e. not to any - // particular index within it). This is used whenever a set of elements are - // logically enclosed in a single code segment. For example, an entire - // extend block (possibly containing multiple extension definitions) will - // have an outer location whose path refers to the "extensions" repeated - // field without an index. - // - Multiple locations may have the same path. This happens when a single - // logical declaration is spread out across multiple places. The most - // obvious example is the "extend" block again -- there may be multiple - // extend blocks in the same scope, each of which will have the same path. - // - A location's span is not always a subset of its parent's span. For - // example, the "extendee" of an extension declaration appears at the - // beginning of the "extend" block and is shared by all extensions within - // the block. - // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendant. For example, a "group" defines - // both a type and a field in a single declaration. Thus, the locations - // corresponding to the type and field and their components will overlap. - // - Code which tries to interpret locations should probably be designed to - // ignore those that it doesn't understand, as more types of locations could - // be recorded in the future. - Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} } -func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo) ProtoMessage() {} -func (*SourceCodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{19} -} - -func (m *SourceCodeInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SourceCodeInfo.Unmarshal(m, b) -} -func (m *SourceCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SourceCodeInfo.Marshal(b, m, deterministic) -} -func (m *SourceCodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_SourceCodeInfo.Merge(m, src) -} -func (m *SourceCodeInfo) XXX_Size() int { - return xxx_messageInfo_SourceCodeInfo.Size(m) -} -func (m *SourceCodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_SourceCodeInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_SourceCodeInfo proto.InternalMessageInfo - -func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location { - if m != nil { - return m.Location - } - return nil -} - -type SourceCodeInfo_Location struct { - // Identifies which part of the FileDescriptorProto was defined at this - // location. - // - // Each element is a field number or an index. They form a path from - // the root FileDescriptorProto to the place where the definition. For - // example, this path: - // [ 4, 3, 2, 7, 1 ] - // refers to: - // file.message_type(3) // 4, 3 - // .field(7) // 2, 7 - // .name() // 1 - // This is because FileDescriptorProto.message_type has field number 4: - // repeated DescriptorProto message_type = 4; - // and DescriptorProto.field has field number 2: - // repeated FieldDescriptorProto field = 2; - // and FieldDescriptorProto.name has field number 1: - // optional string name = 1; - // - // Thus, the above path gives the location of a field name. If we removed - // the last element: - // [ 4, 3, 2, 7 ] - // this path refers to the whole field declaration (from the beginning - // of the label to the terminating semicolon). - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Always has exactly three or four elements: start line, start column, - // end line (optional, otherwise assumed same as start line), end column. - // These are packed into a single field for efficiency. Note that line - // and column numbers are zero-based -- typically you will want to add - // 1 to each before displaying to a user. - Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"` - // If this SourceCodeInfo represents a complete declaration, these are any - // comments appearing before and after the declaration which appear to be - // attached to the declaration. - // - // A series of line comments appearing on consecutive lines, with no other - // tokens appearing on those lines, will be treated as a single comment. - // - // leading_detached_comments will keep paragraphs of comments that appear - // before (but not connected to) the current element. Each paragraph, - // separated by empty lines, will be one comment element in the repeated - // field. - // - // Only the comment content is provided; comment markers (e.g. //) are - // stripped out. For block comments, leading whitespace and an asterisk - // will be stripped from the beginning of each line other than the first. - // Newlines are included in the output. - // - // Examples: - // - // optional int32 foo = 1; // Comment attached to foo. - // // Comment attached to bar. - // optional int32 bar = 2; - // - // optional string baz = 3; - // // Comment attached to baz. - // // Another line attached to baz. - // - // // Comment attached to qux. - // // - // // Another line attached to qux. - // optional double qux = 4; - // - // // Detached comment for corge. This is not leading or trailing comments - // // to qux or corge because there are blank lines separating it from - // // both. - // - // // Detached comment for corge paragraph 2. - // - // optional string corge = 5; - // /* Block comment attached - // * to corge. Leading asterisks - // * will be removed. */ - // /* Block comment attached to - // * grault. */ - // optional int32 grault = 6; - // - // // ignored detached comments. - LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"` - TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"` - LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} } -func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo_Location) ProtoMessage() {} -func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{19, 0} -} - -func (m *SourceCodeInfo_Location) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SourceCodeInfo_Location.Unmarshal(m, b) -} -func (m *SourceCodeInfo_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SourceCodeInfo_Location.Marshal(b, m, deterministic) -} -func (m *SourceCodeInfo_Location) XXX_Merge(src proto.Message) { - xxx_messageInfo_SourceCodeInfo_Location.Merge(m, src) -} -func (m *SourceCodeInfo_Location) XXX_Size() int { - return xxx_messageInfo_SourceCodeInfo_Location.Size(m) -} -func (m *SourceCodeInfo_Location) XXX_DiscardUnknown() { - xxx_messageInfo_SourceCodeInfo_Location.DiscardUnknown(m) -} - -var xxx_messageInfo_SourceCodeInfo_Location proto.InternalMessageInfo - -func (m *SourceCodeInfo_Location) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} - -func (m *SourceCodeInfo_Location) GetSpan() []int32 { - if m != nil { - return m.Span - } - return nil -} - -func (m *SourceCodeInfo_Location) GetLeadingComments() string { - if m != nil && m.LeadingComments != nil { - return *m.LeadingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetTrailingComments() string { - if m != nil && m.TrailingComments != nil { - return *m.TrailingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string { - if m != nil { - return m.LeadingDetachedComments - } - return nil -} - -// Describes the relationship between generated code and its original source -// file. A GeneratedCodeInfo message is associated with only one generated -// source file, but may contain references to different source .proto files. -type GeneratedCodeInfo struct { - // An Annotation connects some span of text in generated code to an element - // of its generating .proto file. - Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} +type FieldDescriptorProto_Label = descriptorpb.FieldDescriptorProto_Label -func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} } -func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo) ProtoMessage() {} -func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{20} -} +const FieldDescriptorProto_LABEL_OPTIONAL = descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL +const FieldDescriptorProto_LABEL_REQUIRED = descriptorpb.FieldDescriptorProto_LABEL_REQUIRED +const FieldDescriptorProto_LABEL_REPEATED = descriptorpb.FieldDescriptorProto_LABEL_REPEATED -func (m *GeneratedCodeInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GeneratedCodeInfo.Unmarshal(m, b) -} -func (m *GeneratedCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GeneratedCodeInfo.Marshal(b, m, deterministic) -} -func (m *GeneratedCodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_GeneratedCodeInfo.Merge(m, src) -} -func (m *GeneratedCodeInfo) XXX_Size() int { - return xxx_messageInfo_GeneratedCodeInfo.Size(m) -} -func (m *GeneratedCodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_GeneratedCodeInfo.DiscardUnknown(m) -} +var FieldDescriptorProto_Label_name = descriptorpb.FieldDescriptorProto_Label_name +var FieldDescriptorProto_Label_value = descriptorpb.FieldDescriptorProto_Label_value -var xxx_messageInfo_GeneratedCodeInfo proto.InternalMessageInfo +type FileOptions_OptimizeMode = descriptorpb.FileOptions_OptimizeMode -func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation { - if m != nil { - return m.Annotation - } - return nil -} +const FileOptions_SPEED = descriptorpb.FileOptions_SPEED +const FileOptions_CODE_SIZE = descriptorpb.FileOptions_CODE_SIZE +const FileOptions_LITE_RUNTIME = descriptorpb.FileOptions_LITE_RUNTIME -type GeneratedCodeInfo_Annotation struct { - // Identifies the element in the original source .proto file. This field - // is formatted the same as SourceCodeInfo.Location.path. - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Identifies the filesystem path to the original source .proto. - SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"` - // Identifies the starting offset in bytes in the generated code - // that relates to the identified object. - Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"` - // Identifies the ending offset in bytes in the generated code that - // relates to the identified offset. The end offset should be one past - // the last relevant byte (so the length of the text = end - begin). - End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} +var FileOptions_OptimizeMode_name = descriptorpb.FileOptions_OptimizeMode_name +var FileOptions_OptimizeMode_value = descriptorpb.FileOptions_OptimizeMode_value -func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} } -func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo_Annotation) ProtoMessage() {} -func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) { - return fileDescriptor_e5baabe45344a177, []int{20, 0} -} +type FieldOptions_CType = descriptorpb.FieldOptions_CType -func (m *GeneratedCodeInfo_Annotation) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Unmarshal(m, b) -} -func (m *GeneratedCodeInfo_Annotation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Marshal(b, m, deterministic) -} -func (m *GeneratedCodeInfo_Annotation) XXX_Merge(src proto.Message) { - xxx_messageInfo_GeneratedCodeInfo_Annotation.Merge(m, src) -} -func (m *GeneratedCodeInfo_Annotation) XXX_Size() int { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Size(m) -} -func (m *GeneratedCodeInfo_Annotation) XXX_DiscardUnknown() { - xxx_messageInfo_GeneratedCodeInfo_Annotation.DiscardUnknown(m) -} +const FieldOptions_STRING = descriptorpb.FieldOptions_STRING +const FieldOptions_CORD = descriptorpb.FieldOptions_CORD +const FieldOptions_STRING_PIECE = descriptorpb.FieldOptions_STRING_PIECE -var xxx_messageInfo_GeneratedCodeInfo_Annotation proto.InternalMessageInfo +var FieldOptions_CType_name = descriptorpb.FieldOptions_CType_name +var FieldOptions_CType_value = descriptorpb.FieldOptions_CType_value -func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} +type FieldOptions_JSType = descriptorpb.FieldOptions_JSType -func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string { - if m != nil && m.SourceFile != nil { - return *m.SourceFile - } - return "" -} +const FieldOptions_JS_NORMAL = descriptorpb.FieldOptions_JS_NORMAL +const FieldOptions_JS_STRING = descriptorpb.FieldOptions_JS_STRING +const FieldOptions_JS_NUMBER = descriptorpb.FieldOptions_JS_NUMBER -func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 { - if m != nil && m.Begin != nil { - return *m.Begin - } - return 0 -} +var FieldOptions_JSType_name = descriptorpb.FieldOptions_JSType_name +var FieldOptions_JSType_value = descriptorpb.FieldOptions_JSType_value -func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} +type MethodOptions_IdempotencyLevel = descriptorpb.MethodOptions_IdempotencyLevel -func init() { - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value) - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value) - proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value) - proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value) - proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value) - proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value) - proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet") - proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto") - proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto") - proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange") - proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange") - proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions") - proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto") - proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto") - proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto") - proto.RegisterType((*EnumDescriptorProto_EnumReservedRange)(nil), "google.protobuf.EnumDescriptorProto.EnumReservedRange") - proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto") - proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto") - proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto") - proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions") - proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions") - proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions") - proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions") - proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions") - proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions") - proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions") - proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions") - proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption") - proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart") - proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo") - proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location") - proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo") - proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation") -} +const MethodOptions_IDEMPOTENCY_UNKNOWN = descriptorpb.MethodOptions_IDEMPOTENCY_UNKNOWN +const MethodOptions_NO_SIDE_EFFECTS = descriptorpb.MethodOptions_NO_SIDE_EFFECTS +const MethodOptions_IDEMPOTENT = descriptorpb.MethodOptions_IDEMPOTENT -func init() { - proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor_e5baabe45344a177) -} +var MethodOptions_IdempotencyLevel_name = descriptorpb.MethodOptions_IdempotencyLevel_name +var MethodOptions_IdempotencyLevel_value = descriptorpb.MethodOptions_IdempotencyLevel_value -var fileDescriptor_e5baabe45344a177 = []byte{ - // 2589 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xdd, 0x8e, 0xdb, 0xc6, - 0x15, 0x0e, 0xf5, 0xb7, 0xd2, 0x91, 0x56, 0x3b, 0x3b, 0xbb, 0xb1, 0xe9, 0xcd, 0x8f, 0xd7, 0xca, - 0x8f, 0xd7, 0x4e, 0xac, 0x0d, 0x1c, 0xdb, 0x71, 0xd6, 0x45, 0x5a, 0xad, 0x44, 0x6f, 0xe4, 0xee, - 0x4a, 0x2a, 0xa5, 0x6d, 0x7e, 0x80, 0x82, 0x98, 0x25, 0x47, 0x12, 0x6d, 0x8a, 0x64, 0x48, 0xca, - 0xf6, 0x06, 0xbd, 0x30, 0xd0, 0xab, 0x5e, 0x15, 0xe8, 0x55, 0x51, 0x14, 0xbd, 0xe8, 0x4d, 0x80, - 0x3e, 0x40, 0x81, 0xde, 0xf5, 0x09, 0x0a, 0xe4, 0x0d, 0x8a, 0xb6, 0x40, 0xfb, 0x08, 0xbd, 0x2c, - 0x66, 0x86, 0xa4, 0x48, 0x49, 0x1b, 0x6f, 0x02, 0xc4, 0xb9, 0x92, 0xe6, 0x3b, 0xdf, 0x39, 0x73, - 0xe6, 0xcc, 0x99, 0x99, 0x33, 0x43, 0xd8, 0x1e, 0x39, 0xce, 0xc8, 0xa2, 0xbb, 0xae, 0xe7, 0x04, - 0xce, 0xc9, 0x74, 0xb8, 0x6b, 0x50, 0x5f, 0xf7, 0x4c, 0x37, 0x70, 0xbc, 0x3a, 0xc7, 0xf0, 0x9a, - 0x60, 0xd4, 0x23, 0x46, 0xed, 0x08, 0xd6, 0xef, 0x9b, 0x16, 0x6d, 0xc5, 0xc4, 0x3e, 0x0d, 0xf0, - 0x5d, 0xc8, 0x0d, 0x4d, 0x8b, 0xca, 0xd2, 0x76, 0x76, 0xa7, 0x7c, 0xf3, 0xcd, 0xfa, 0x9c, 0x52, - 0x3d, 0xad, 0xd1, 0x63, 0xb0, 0xca, 0x35, 0x6a, 0xff, 0xce, 0xc1, 0xc6, 0x12, 0x29, 0xc6, 0x90, - 0xb3, 0xc9, 0x84, 0x59, 0x94, 0x76, 0x4a, 0x2a, 0xff, 0x8f, 0x65, 0x58, 0x71, 0x89, 0xfe, 0x88, - 0x8c, 0xa8, 0x9c, 0xe1, 0x70, 0xd4, 0xc4, 0xaf, 0x03, 0x18, 0xd4, 0xa5, 0xb6, 0x41, 0x6d, 0xfd, - 0x54, 0xce, 0x6e, 0x67, 0x77, 0x4a, 0x6a, 0x02, 0xc1, 0xef, 0xc0, 0xba, 0x3b, 0x3d, 0xb1, 0x4c, - 0x5d, 0x4b, 0xd0, 0x60, 0x3b, 0xbb, 0x93, 0x57, 0x91, 0x10, 0xb4, 0x66, 0xe4, 0xab, 0xb0, 0xf6, - 0x84, 0x92, 0x47, 0x49, 0x6a, 0x99, 0x53, 0xab, 0x0c, 0x4e, 0x10, 0x9b, 0x50, 0x99, 0x50, 0xdf, - 0x27, 0x23, 0xaa, 0x05, 0xa7, 0x2e, 0x95, 0x73, 0x7c, 0xf4, 0xdb, 0x0b, 0xa3, 0x9f, 0x1f, 0x79, - 0x39, 0xd4, 0x1a, 0x9c, 0xba, 0x14, 0x37, 0xa0, 0x44, 0xed, 0xe9, 0x44, 0x58, 0xc8, 0x9f, 0x11, - 0x3f, 0xc5, 0x9e, 0x4e, 0xe6, 0xad, 0x14, 0x99, 0x5a, 0x68, 0x62, 0xc5, 0xa7, 0xde, 0x63, 0x53, - 0xa7, 0x72, 0x81, 0x1b, 0xb8, 0xba, 0x60, 0xa0, 0x2f, 0xe4, 0xf3, 0x36, 0x22, 0x3d, 0xdc, 0x84, - 0x12, 0x7d, 0x1a, 0x50, 0xdb, 0x37, 0x1d, 0x5b, 0x5e, 0xe1, 0x46, 0xde, 0x5a, 0x32, 0x8b, 0xd4, - 0x32, 0xe6, 0x4d, 0xcc, 0xf4, 0xf0, 0x1d, 0x58, 0x71, 0xdc, 0xc0, 0x74, 0x6c, 0x5f, 0x2e, 0x6e, - 0x4b, 0x3b, 0xe5, 0x9b, 0xaf, 0x2e, 0x4d, 0x84, 0xae, 0xe0, 0xa8, 0x11, 0x19, 0xb7, 0x01, 0xf9, - 0xce, 0xd4, 0xd3, 0xa9, 0xa6, 0x3b, 0x06, 0xd5, 0x4c, 0x7b, 0xe8, 0xc8, 0x25, 0x6e, 0xe0, 0xf2, - 0xe2, 0x40, 0x38, 0xb1, 0xe9, 0x18, 0xb4, 0x6d, 0x0f, 0x1d, 0xb5, 0xea, 0xa7, 0xda, 0xf8, 0x02, - 0x14, 0xfc, 0x53, 0x3b, 0x20, 0x4f, 0xe5, 0x0a, 0xcf, 0x90, 0xb0, 0x55, 0xfb, 0x6b, 0x01, 0xd6, - 0xce, 0x93, 0x62, 0xf7, 0x20, 0x3f, 0x64, 0xa3, 0x94, 0x33, 0xdf, 0x26, 0x06, 0x42, 0x27, 0x1d, - 0xc4, 0xc2, 0x77, 0x0c, 0x62, 0x03, 0xca, 0x36, 0xf5, 0x03, 0x6a, 0x88, 0x8c, 0xc8, 0x9e, 0x33, - 0xa7, 0x40, 0x28, 0x2d, 0xa6, 0x54, 0xee, 0x3b, 0xa5, 0xd4, 0xa7, 0xb0, 0x16, 0xbb, 0xa4, 0x79, - 0xc4, 0x1e, 0x45, 0xb9, 0xb9, 0xfb, 0x3c, 0x4f, 0xea, 0x4a, 0xa4, 0xa7, 0x32, 0x35, 0xb5, 0x4a, - 0x53, 0x6d, 0xdc, 0x02, 0x70, 0x6c, 0xea, 0x0c, 0x35, 0x83, 0xea, 0x96, 0x5c, 0x3c, 0x23, 0x4a, - 0x5d, 0x46, 0x59, 0x88, 0x92, 0x23, 0x50, 0xdd, 0xc2, 0x1f, 0xce, 0x52, 0x6d, 0xe5, 0x8c, 0x4c, - 0x39, 0x12, 0x8b, 0x6c, 0x21, 0xdb, 0x8e, 0xa1, 0xea, 0x51, 0x96, 0xf7, 0xd4, 0x08, 0x47, 0x56, - 0xe2, 0x4e, 0xd4, 0x9f, 0x3b, 0x32, 0x35, 0x54, 0x13, 0x03, 0x5b, 0xf5, 0x92, 0x4d, 0xfc, 0x06, - 0xc4, 0x80, 0xc6, 0xd3, 0x0a, 0xf8, 0x2e, 0x54, 0x89, 0xc0, 0x0e, 0x99, 0xd0, 0xad, 0x2f, 0xa1, - 0x9a, 0x0e, 0x0f, 0xde, 0x84, 0xbc, 0x1f, 0x10, 0x2f, 0xe0, 0x59, 0x98, 0x57, 0x45, 0x03, 0x23, - 0xc8, 0x52, 0xdb, 0xe0, 0xbb, 0x5c, 0x5e, 0x65, 0x7f, 0xf1, 0x4f, 0x66, 0x03, 0xce, 0xf2, 0x01, - 0xbf, 0xbd, 0x38, 0xa3, 0x29, 0xcb, 0xf3, 0xe3, 0xde, 0xfa, 0x00, 0x56, 0x53, 0x03, 0x38, 0x6f, - 0xd7, 0xb5, 0x5f, 0xc2, 0xcb, 0x4b, 0x4d, 0xe3, 0x4f, 0x61, 0x73, 0x6a, 0x9b, 0x76, 0x40, 0x3d, - 0xd7, 0xa3, 0x2c, 0x63, 0x45, 0x57, 0xf2, 0x7f, 0x56, 0xce, 0xc8, 0xb9, 0xe3, 0x24, 0x5b, 0x58, - 0x51, 0x37, 0xa6, 0x8b, 0xe0, 0xf5, 0x52, 0xf1, 0xbf, 0x2b, 0xe8, 0xd9, 0xb3, 0x67, 0xcf, 0x32, - 0xb5, 0xdf, 0x15, 0x60, 0x73, 0xd9, 0x9a, 0x59, 0xba, 0x7c, 0x2f, 0x40, 0xc1, 0x9e, 0x4e, 0x4e, - 0xa8, 0xc7, 0x83, 0x94, 0x57, 0xc3, 0x16, 0x6e, 0x40, 0xde, 0x22, 0x27, 0xd4, 0x92, 0x73, 0xdb, - 0xd2, 0x4e, 0xf5, 0xe6, 0x3b, 0xe7, 0x5a, 0x95, 0xf5, 0x43, 0xa6, 0xa2, 0x0a, 0x4d, 0xfc, 0x11, - 0xe4, 0xc2, 0x2d, 0x9a, 0x59, 0xb8, 0x7e, 0x3e, 0x0b, 0x6c, 0x2d, 0xa9, 0x5c, 0x0f, 0xbf, 0x02, - 0x25, 0xf6, 0x2b, 0x72, 0xa3, 0xc0, 0x7d, 0x2e, 0x32, 0x80, 0xe5, 0x05, 0xde, 0x82, 0x22, 0x5f, - 0x26, 0x06, 0x8d, 0x8e, 0xb6, 0xb8, 0xcd, 0x12, 0xcb, 0xa0, 0x43, 0x32, 0xb5, 0x02, 0xed, 0x31, - 0xb1, 0xa6, 0x94, 0x27, 0x7c, 0x49, 0xad, 0x84, 0xe0, 0xcf, 0x19, 0x86, 0x2f, 0x43, 0x59, 0xac, - 0x2a, 0xd3, 0x36, 0xe8, 0x53, 0xbe, 0x7b, 0xe6, 0x55, 0xb1, 0xd0, 0xda, 0x0c, 0x61, 0xdd, 0x3f, - 0xf4, 0x1d, 0x3b, 0x4a, 0x4d, 0xde, 0x05, 0x03, 0x78, 0xf7, 0x1f, 0xcc, 0x6f, 0xdc, 0xaf, 0x2d, - 0x1f, 0xde, 0x7c, 0x4e, 0xd5, 0xfe, 0x92, 0x81, 0x1c, 0xdf, 0x2f, 0xd6, 0xa0, 0x3c, 0xf8, 0xac, - 0xa7, 0x68, 0xad, 0xee, 0xf1, 0xfe, 0xa1, 0x82, 0x24, 0x5c, 0x05, 0xe0, 0xc0, 0xfd, 0xc3, 0x6e, - 0x63, 0x80, 0x32, 0x71, 0xbb, 0xdd, 0x19, 0xdc, 0xb9, 0x85, 0xb2, 0xb1, 0xc2, 0xb1, 0x00, 0x72, - 0x49, 0xc2, 0xfb, 0x37, 0x51, 0x1e, 0x23, 0xa8, 0x08, 0x03, 0xed, 0x4f, 0x95, 0xd6, 0x9d, 0x5b, - 0xa8, 0x90, 0x46, 0xde, 0xbf, 0x89, 0x56, 0xf0, 0x2a, 0x94, 0x38, 0xb2, 0xdf, 0xed, 0x1e, 0xa2, - 0x62, 0x6c, 0xb3, 0x3f, 0x50, 0xdb, 0x9d, 0x03, 0x54, 0x8a, 0x6d, 0x1e, 0xa8, 0xdd, 0xe3, 0x1e, - 0x82, 0xd8, 0xc2, 0x91, 0xd2, 0xef, 0x37, 0x0e, 0x14, 0x54, 0x8e, 0x19, 0xfb, 0x9f, 0x0d, 0x94, - 0x3e, 0xaa, 0xa4, 0xdc, 0x7a, 0xff, 0x26, 0x5a, 0x8d, 0xbb, 0x50, 0x3a, 0xc7, 0x47, 0xa8, 0x8a, - 0xd7, 0x61, 0x55, 0x74, 0x11, 0x39, 0xb1, 0x36, 0x07, 0xdd, 0xb9, 0x85, 0xd0, 0xcc, 0x11, 0x61, - 0x65, 0x3d, 0x05, 0xdc, 0xb9, 0x85, 0x70, 0xad, 0x09, 0x79, 0x9e, 0x5d, 0x18, 0x43, 0xf5, 0xb0, - 0xb1, 0xaf, 0x1c, 0x6a, 0xdd, 0xde, 0xa0, 0xdd, 0xed, 0x34, 0x0e, 0x91, 0x34, 0xc3, 0x54, 0xe5, - 0x67, 0xc7, 0x6d, 0x55, 0x69, 0xa1, 0x4c, 0x12, 0xeb, 0x29, 0x8d, 0x81, 0xd2, 0x42, 0xd9, 0x9a, - 0x0e, 0x9b, 0xcb, 0xf6, 0xc9, 0xa5, 0x2b, 0x23, 0x31, 0xc5, 0x99, 0x33, 0xa6, 0x98, 0xdb, 0x5a, - 0x98, 0xe2, 0x7f, 0x65, 0x60, 0x63, 0xc9, 0x59, 0xb1, 0xb4, 0x93, 0x1f, 0x43, 0x5e, 0xa4, 0xa8, - 0x38, 0x3d, 0xaf, 0x2d, 0x3d, 0x74, 0x78, 0xc2, 0x2e, 0x9c, 0xa0, 0x5c, 0x2f, 0x59, 0x41, 0x64, - 0xcf, 0xa8, 0x20, 0x98, 0x89, 0x85, 0x3d, 0xfd, 0x17, 0x0b, 0x7b, 0xba, 0x38, 0xf6, 0xee, 0x9c, - 0xe7, 0xd8, 0xe3, 0xd8, 0xb7, 0xdb, 0xdb, 0xf3, 0x4b, 0xf6, 0xf6, 0x7b, 0xb0, 0xbe, 0x60, 0xe8, - 0xdc, 0x7b, 0xec, 0xaf, 0x24, 0x90, 0xcf, 0x0a, 0xce, 0x73, 0x76, 0xba, 0x4c, 0x6a, 0xa7, 0xbb, - 0x37, 0x1f, 0xc1, 0x2b, 0x67, 0x4f, 0xc2, 0xc2, 0x5c, 0x7f, 0x25, 0xc1, 0x85, 0xe5, 0x95, 0xe2, - 0x52, 0x1f, 0x3e, 0x82, 0xc2, 0x84, 0x06, 0x63, 0x27, 0xaa, 0x96, 0xde, 0x5e, 0x72, 0x06, 0x33, - 0xf1, 0xfc, 0x64, 0x87, 0x5a, 0xc9, 0x43, 0x3c, 0x7b, 0x56, 0xb9, 0x27, 0xbc, 0x59, 0xf0, 0xf4, - 0xd7, 0x19, 0x78, 0x79, 0xa9, 0xf1, 0xa5, 0x8e, 0xbe, 0x06, 0x60, 0xda, 0xee, 0x34, 0x10, 0x15, - 0x91, 0xd8, 0x60, 0x4b, 0x1c, 0xe1, 0x9b, 0x17, 0xdb, 0x3c, 0xa7, 0x41, 0x2c, 0xcf, 0x72, 0x39, - 0x08, 0x88, 0x13, 0xee, 0xce, 0x1c, 0xcd, 0x71, 0x47, 0x5f, 0x3f, 0x63, 0xa4, 0x0b, 0x89, 0xf9, - 0x1e, 0x20, 0xdd, 0x32, 0xa9, 0x1d, 0x68, 0x7e, 0xe0, 0x51, 0x32, 0x31, 0xed, 0x11, 0x3f, 0x41, - 0x8a, 0x7b, 0xf9, 0x21, 0xb1, 0x7c, 0xaa, 0xae, 0x09, 0x71, 0x3f, 0x92, 0x32, 0x0d, 0x9e, 0x40, - 0x5e, 0x42, 0xa3, 0x90, 0xd2, 0x10, 0xe2, 0x58, 0xa3, 0xf6, 0xdb, 0x12, 0x94, 0x13, 0x75, 0x35, - 0xbe, 0x02, 0x95, 0x87, 0xe4, 0x31, 0xd1, 0xa2, 0xbb, 0x92, 0x88, 0x44, 0x99, 0x61, 0xbd, 0xf0, - 0xbe, 0xf4, 0x1e, 0x6c, 0x72, 0x8a, 0x33, 0x0d, 0xa8, 0xa7, 0xe9, 0x16, 0xf1, 0x7d, 0x1e, 0xb4, - 0x22, 0xa7, 0x62, 0x26, 0xeb, 0x32, 0x51, 0x33, 0x92, 0xe0, 0xdb, 0xb0, 0xc1, 0x35, 0x26, 0x53, - 0x2b, 0x30, 0x5d, 0x8b, 0x6a, 0xec, 0xf6, 0xe6, 0xf3, 0x93, 0x24, 0xf6, 0x6c, 0x9d, 0x31, 0x8e, - 0x42, 0x02, 0xf3, 0xc8, 0xc7, 0x2d, 0x78, 0x8d, 0xab, 0x8d, 0xa8, 0x4d, 0x3d, 0x12, 0x50, 0x8d, - 0x7e, 0x31, 0x25, 0x96, 0xaf, 0x11, 0xdb, 0xd0, 0xc6, 0xc4, 0x1f, 0xcb, 0x9b, 0xcc, 0xc0, 0x7e, - 0x46, 0x96, 0xd4, 0x4b, 0x8c, 0x78, 0x10, 0xf2, 0x14, 0x4e, 0x6b, 0xd8, 0xc6, 0xc7, 0xc4, 0x1f, - 0xe3, 0x3d, 0xb8, 0xc0, 0xad, 0xf8, 0x81, 0x67, 0xda, 0x23, 0x4d, 0x1f, 0x53, 0xfd, 0x91, 0x36, - 0x0d, 0x86, 0x77, 0xe5, 0x57, 0x92, 0xfd, 0x73, 0x0f, 0xfb, 0x9c, 0xd3, 0x64, 0x94, 0xe3, 0x60, - 0x78, 0x17, 0xf7, 0xa1, 0xc2, 0x26, 0x63, 0x62, 0x7e, 0x49, 0xb5, 0xa1, 0xe3, 0xf1, 0xa3, 0xb1, - 0xba, 0x64, 0x6b, 0x4a, 0x44, 0xb0, 0xde, 0x0d, 0x15, 0x8e, 0x1c, 0x83, 0xee, 0xe5, 0xfb, 0x3d, - 0x45, 0x69, 0xa9, 0xe5, 0xc8, 0xca, 0x7d, 0xc7, 0x63, 0x09, 0x35, 0x72, 0xe2, 0x00, 0x97, 0x45, - 0x42, 0x8d, 0x9c, 0x28, 0xbc, 0xb7, 0x61, 0x43, 0xd7, 0xc5, 0x98, 0x4d, 0x5d, 0x0b, 0xef, 0x58, - 0xbe, 0x8c, 0x52, 0xc1, 0xd2, 0xf5, 0x03, 0x41, 0x08, 0x73, 0xdc, 0xc7, 0x1f, 0xc2, 0xcb, 0xb3, - 0x60, 0x25, 0x15, 0xd7, 0x17, 0x46, 0x39, 0xaf, 0x7a, 0x1b, 0x36, 0xdc, 0xd3, 0x45, 0x45, 0x9c, - 0xea, 0xd1, 0x3d, 0x9d, 0x57, 0xfb, 0x00, 0x36, 0xdd, 0xb1, 0xbb, 0xa8, 0x77, 0x3d, 0xa9, 0x87, - 0xdd, 0xb1, 0x3b, 0xaf, 0xf8, 0x16, 0xbf, 0x70, 0x7b, 0x54, 0x27, 0x01, 0x35, 0xe4, 0x8b, 0x49, - 0x7a, 0x42, 0x80, 0x77, 0x01, 0xe9, 0xba, 0x46, 0x6d, 0x72, 0x62, 0x51, 0x8d, 0x78, 0xd4, 0x26, - 0xbe, 0x7c, 0x39, 0x49, 0xae, 0xea, 0xba, 0xc2, 0xa5, 0x0d, 0x2e, 0xc4, 0xd7, 0x61, 0xdd, 0x39, - 0x79, 0xa8, 0x8b, 0x94, 0xd4, 0x5c, 0x8f, 0x0e, 0xcd, 0xa7, 0xf2, 0x9b, 0x3c, 0xbe, 0x6b, 0x4c, - 0xc0, 0x13, 0xb2, 0xc7, 0x61, 0x7c, 0x0d, 0x90, 0xee, 0x8f, 0x89, 0xe7, 0xf2, 0x3d, 0xd9, 0x77, - 0x89, 0x4e, 0xe5, 0xb7, 0x04, 0x55, 0xe0, 0x9d, 0x08, 0x66, 0x4b, 0xc2, 0x7f, 0x62, 0x0e, 0x83, - 0xc8, 0xe2, 0x55, 0xb1, 0x24, 0x38, 0x16, 0x5a, 0xdb, 0x01, 0xc4, 0x42, 0x91, 0xea, 0x78, 0x87, - 0xd3, 0xaa, 0xee, 0xd8, 0x4d, 0xf6, 0xfb, 0x06, 0xac, 0x32, 0xe6, 0xac, 0xd3, 0x6b, 0xa2, 0x20, - 0x73, 0xc7, 0x89, 0x1e, 0x6f, 0xc1, 0x05, 0x46, 0x9a, 0xd0, 0x80, 0x18, 0x24, 0x20, 0x09, 0xf6, - 0xbb, 0x9c, 0xcd, 0xe2, 0x7e, 0x14, 0x0a, 0x53, 0x7e, 0x7a, 0xd3, 0x93, 0xd3, 0x38, 0xb3, 0x6e, - 0x08, 0x3f, 0x19, 0x16, 0xe5, 0xd6, 0xf7, 0x56, 0x74, 0xd7, 0xf6, 0xa0, 0x92, 0x4c, 0x7c, 0x5c, - 0x02, 0x91, 0xfa, 0x48, 0x62, 0x55, 0x50, 0xb3, 0xdb, 0x62, 0xf5, 0xcb, 0xe7, 0x0a, 0xca, 0xb0, - 0x3a, 0xea, 0xb0, 0x3d, 0x50, 0x34, 0xf5, 0xb8, 0x33, 0x68, 0x1f, 0x29, 0x28, 0x9b, 0x28, 0xd8, - 0x1f, 0xe4, 0x8a, 0x6f, 0xa3, 0xab, 0xb5, 0xaf, 0x33, 0x50, 0x4d, 0xdf, 0xc0, 0xf0, 0x8f, 0xe0, - 0x62, 0xf4, 0x5c, 0xe2, 0xd3, 0x40, 0x7b, 0x62, 0x7a, 0x7c, 0x45, 0x4e, 0x88, 0x38, 0x1d, 0xe3, - 0x9c, 0xd8, 0x0c, 0x59, 0x7d, 0x1a, 0x7c, 0x62, 0x7a, 0x6c, 0xbd, 0x4d, 0x48, 0x80, 0x0f, 0xe1, - 0xb2, 0xed, 0x68, 0x7e, 0x40, 0x6c, 0x83, 0x78, 0x86, 0x36, 0x7b, 0xa8, 0xd2, 0x88, 0xae, 0x53, - 0xdf, 0x77, 0xc4, 0x49, 0x18, 0x5b, 0x79, 0xd5, 0x76, 0xfa, 0x21, 0x79, 0x76, 0x44, 0x34, 0x42, - 0xea, 0x5c, 0xfe, 0x66, 0xcf, 0xca, 0xdf, 0x57, 0xa0, 0x34, 0x21, 0xae, 0x46, 0xed, 0xc0, 0x3b, - 0xe5, 0x75, 0x77, 0x51, 0x2d, 0x4e, 0x88, 0xab, 0xb0, 0xf6, 0x0b, 0xb9, 0xfe, 0x3c, 0xc8, 0x15, - 0x8b, 0xa8, 0xf4, 0x20, 0x57, 0x2c, 0x21, 0xa8, 0xfd, 0x33, 0x0b, 0x95, 0x64, 0x1d, 0xce, 0xae, - 0x35, 0x3a, 0x3f, 0xb2, 0x24, 0xbe, 0xa9, 0xbd, 0xf1, 0x8d, 0x55, 0x7b, 0xbd, 0xc9, 0xce, 0xb2, - 0xbd, 0x82, 0xa8, 0x8e, 0x55, 0xa1, 0xc9, 0xea, 0x08, 0x96, 0x6c, 0x54, 0x54, 0x23, 0x45, 0x35, - 0x6c, 0xe1, 0x03, 0x28, 0x3c, 0xf4, 0xb9, 0xed, 0x02, 0xb7, 0xfd, 0xe6, 0x37, 0xdb, 0x7e, 0xd0, - 0xe7, 0xc6, 0x4b, 0x0f, 0xfa, 0x5a, 0xa7, 0xab, 0x1e, 0x35, 0x0e, 0xd5, 0x50, 0x1d, 0x5f, 0x82, - 0x9c, 0x45, 0xbe, 0x3c, 0x4d, 0x9f, 0x7a, 0x1c, 0x3a, 0xef, 0x24, 0x5c, 0x82, 0xdc, 0x13, 0x4a, - 0x1e, 0xa5, 0xcf, 0x1a, 0x0e, 0x7d, 0x8f, 0x8b, 0x61, 0x17, 0xf2, 0x3c, 0x5e, 0x18, 0x20, 0x8c, - 0x18, 0x7a, 0x09, 0x17, 0x21, 0xd7, 0xec, 0xaa, 0x6c, 0x41, 0x20, 0xa8, 0x08, 0x54, 0xeb, 0xb5, - 0x95, 0xa6, 0x82, 0x32, 0xb5, 0xdb, 0x50, 0x10, 0x41, 0x60, 0x8b, 0x25, 0x0e, 0x03, 0x7a, 0x29, - 0x6c, 0x86, 0x36, 0xa4, 0x48, 0x7a, 0x7c, 0xb4, 0xaf, 0xa8, 0x28, 0x93, 0x9e, 0xea, 0x1c, 0xca, - 0xd7, 0x7c, 0xa8, 0x24, 0x0b, 0xf1, 0x17, 0x73, 0xc9, 0xfe, 0x9b, 0x04, 0xe5, 0x44, 0x61, 0xcd, - 0x2a, 0x22, 0x62, 0x59, 0xce, 0x13, 0x8d, 0x58, 0x26, 0xf1, 0xc3, 0xd4, 0x00, 0x0e, 0x35, 0x18, - 0x72, 0xde, 0xa9, 0x7b, 0x41, 0x4b, 0x24, 0x8f, 0x0a, 0xb5, 0x3f, 0x4a, 0x80, 0xe6, 0x2b, 0xdb, - 0x39, 0x37, 0xa5, 0x1f, 0xd2, 0xcd, 0xda, 0x1f, 0x24, 0xa8, 0xa6, 0xcb, 0xd9, 0x39, 0xf7, 0xae, - 0xfc, 0xa0, 0xee, 0xfd, 0x23, 0x03, 0xab, 0xa9, 0x22, 0xf6, 0xbc, 0xde, 0x7d, 0x01, 0xeb, 0xa6, - 0x41, 0x27, 0xae, 0x13, 0x50, 0x5b, 0x3f, 0xd5, 0x2c, 0xfa, 0x98, 0x5a, 0x72, 0x8d, 0x6f, 0x1a, - 0xbb, 0xdf, 0x5c, 0x26, 0xd7, 0xdb, 0x33, 0xbd, 0x43, 0xa6, 0xb6, 0xb7, 0xd1, 0x6e, 0x29, 0x47, - 0xbd, 0xee, 0x40, 0xe9, 0x34, 0x3f, 0xd3, 0x8e, 0x3b, 0x3f, 0xed, 0x74, 0x3f, 0xe9, 0xa8, 0xc8, - 0x9c, 0xa3, 0x7d, 0x8f, 0xcb, 0xbe, 0x07, 0x68, 0xde, 0x29, 0x7c, 0x11, 0x96, 0xb9, 0x85, 0x5e, - 0xc2, 0x1b, 0xb0, 0xd6, 0xe9, 0x6a, 0xfd, 0x76, 0x4b, 0xd1, 0x94, 0xfb, 0xf7, 0x95, 0xe6, 0xa0, - 0x2f, 0x1e, 0x3e, 0x62, 0xf6, 0x20, 0xb5, 0xc0, 0x6b, 0xbf, 0xcf, 0xc2, 0xc6, 0x12, 0x4f, 0x70, - 0x23, 0xbc, 0xb2, 0x88, 0x5b, 0xd4, 0x8d, 0xf3, 0x78, 0x5f, 0x67, 0x35, 0x43, 0x8f, 0x78, 0x41, - 0x78, 0xc3, 0xb9, 0x06, 0x2c, 0x4a, 0x76, 0x60, 0x0e, 0x4d, 0xea, 0x85, 0xef, 0x44, 0xe2, 0x1e, - 0xb3, 0x36, 0xc3, 0xc5, 0x53, 0xd1, 0xbb, 0x80, 0x5d, 0xc7, 0x37, 0x03, 0xf3, 0x31, 0xd5, 0x4c, - 0x3b, 0x7a, 0x54, 0x62, 0xf7, 0x9a, 0x9c, 0x8a, 0x22, 0x49, 0xdb, 0x0e, 0x62, 0xb6, 0x4d, 0x47, - 0x64, 0x8e, 0xcd, 0x36, 0xf3, 0xac, 0x8a, 0x22, 0x49, 0xcc, 0xbe, 0x02, 0x15, 0xc3, 0x99, 0xb2, - 0x62, 0x4f, 0xf0, 0xd8, 0xd9, 0x21, 0xa9, 0x65, 0x81, 0xc5, 0x94, 0xb0, 0x8c, 0x9f, 0xbd, 0x66, - 0x55, 0xd4, 0xb2, 0xc0, 0x04, 0xe5, 0x2a, 0xac, 0x91, 0xd1, 0xc8, 0x63, 0xc6, 0x23, 0x43, 0xe2, - 0x62, 0x52, 0x8d, 0x61, 0x4e, 0xdc, 0x7a, 0x00, 0xc5, 0x28, 0x0e, 0xec, 0xa8, 0x66, 0x91, 0xd0, - 0x5c, 0x71, 0xdb, 0xce, 0xec, 0x94, 0xd4, 0xa2, 0x1d, 0x09, 0xaf, 0x40, 0xc5, 0xf4, 0xb5, 0xd9, - 0xe3, 0x7c, 0x66, 0x3b, 0xb3, 0x53, 0x54, 0xcb, 0xa6, 0x1f, 0x3f, 0x6c, 0xd6, 0xbe, 0xca, 0x40, - 0x35, 0xfd, 0x71, 0x01, 0xb7, 0xa0, 0x68, 0x39, 0x3a, 0xe1, 0xa9, 0x25, 0xbe, 0x6c, 0xed, 0x3c, - 0xe7, 0x7b, 0x44, 0xfd, 0x30, 0xe4, 0xab, 0xb1, 0xe6, 0xd6, 0xdf, 0x25, 0x28, 0x46, 0x30, 0xbe, - 0x00, 0x39, 0x97, 0x04, 0x63, 0x6e, 0x2e, 0xbf, 0x9f, 0x41, 0x92, 0xca, 0xdb, 0x0c, 0xf7, 0x5d, - 0x62, 0xf3, 0x14, 0x08, 0x71, 0xd6, 0x66, 0xf3, 0x6a, 0x51, 0x62, 0xf0, 0x5b, 0x8f, 0x33, 0x99, - 0x50, 0x3b, 0xf0, 0xa3, 0x79, 0x0d, 0xf1, 0x66, 0x08, 0xe3, 0x77, 0x60, 0x3d, 0xf0, 0x88, 0x69, - 0xa5, 0xb8, 0x39, 0xce, 0x45, 0x91, 0x20, 0x26, 0xef, 0xc1, 0xa5, 0xc8, 0xae, 0x41, 0x03, 0xa2, - 0x8f, 0xa9, 0x31, 0x53, 0x2a, 0xf0, 0xd7, 0x8d, 0x8b, 0x21, 0xa1, 0x15, 0xca, 0x23, 0xdd, 0xda, - 0xd7, 0x12, 0xac, 0x47, 0xf7, 0x34, 0x23, 0x0e, 0xd6, 0x11, 0x00, 0xb1, 0x6d, 0x27, 0x48, 0x86, - 0x6b, 0x31, 0x95, 0x17, 0xf4, 0xea, 0x8d, 0x58, 0x49, 0x4d, 0x18, 0xd8, 0x9a, 0x00, 0xcc, 0x24, - 0x67, 0x86, 0xed, 0x32, 0x94, 0xc3, 0x2f, 0x47, 0xfc, 0xf3, 0xa3, 0xb8, 0xd9, 0x83, 0x80, 0xd8, - 0x85, 0x0e, 0x6f, 0x42, 0xfe, 0x84, 0x8e, 0x4c, 0x3b, 0x7c, 0x0f, 0x16, 0x8d, 0xe8, 0xfd, 0x25, - 0x17, 0xbf, 0xbf, 0xec, 0xff, 0x46, 0x82, 0x0d, 0xdd, 0x99, 0xcc, 0xfb, 0xbb, 0x8f, 0xe6, 0x9e, - 0x17, 0xfc, 0x8f, 0xa5, 0xcf, 0x3f, 0x1a, 0x99, 0xc1, 0x78, 0x7a, 0x52, 0xd7, 0x9d, 0xc9, 0xee, - 0xc8, 0xb1, 0x88, 0x3d, 0x9a, 0x7d, 0x3f, 0xe5, 0x7f, 0xf4, 0x1b, 0x23, 0x6a, 0xdf, 0x18, 0x39, - 0x89, 0xaf, 0xa9, 0xf7, 0x66, 0x7f, 0xff, 0x27, 0x49, 0x7f, 0xca, 0x64, 0x0f, 0x7a, 0xfb, 0x7f, - 0xce, 0x6c, 0x1d, 0x88, 0xee, 0x7a, 0x51, 0x78, 0x54, 0x3a, 0xb4, 0xa8, 0xce, 0x86, 0xfc, 0xff, - 0x00, 0x00, 0x00, 0xff, 0xff, 0x3e, 0xe8, 0xef, 0xc4, 0x9b, 0x1d, 0x00, 0x00, +type FileDescriptorSet = descriptorpb.FileDescriptorSet +type FileDescriptorProto = descriptorpb.FileDescriptorProto +type DescriptorProto = descriptorpb.DescriptorProto +type ExtensionRangeOptions = descriptorpb.ExtensionRangeOptions +type FieldDescriptorProto = descriptorpb.FieldDescriptorProto +type OneofDescriptorProto = descriptorpb.OneofDescriptorProto +type EnumDescriptorProto = descriptorpb.EnumDescriptorProto +type EnumValueDescriptorProto = descriptorpb.EnumValueDescriptorProto +type ServiceDescriptorProto = descriptorpb.ServiceDescriptorProto +type MethodDescriptorProto = descriptorpb.MethodDescriptorProto + +const Default_MethodDescriptorProto_ClientStreaming = descriptorpb.Default_MethodDescriptorProto_ClientStreaming +const Default_MethodDescriptorProto_ServerStreaming = descriptorpb.Default_MethodDescriptorProto_ServerStreaming + +type FileOptions = descriptorpb.FileOptions + +const Default_FileOptions_JavaMultipleFiles = descriptorpb.Default_FileOptions_JavaMultipleFiles +const Default_FileOptions_JavaStringCheckUtf8 = descriptorpb.Default_FileOptions_JavaStringCheckUtf8 +const Default_FileOptions_OptimizeFor = descriptorpb.Default_FileOptions_OptimizeFor +const Default_FileOptions_CcGenericServices = descriptorpb.Default_FileOptions_CcGenericServices +const Default_FileOptions_JavaGenericServices = descriptorpb.Default_FileOptions_JavaGenericServices +const Default_FileOptions_PyGenericServices = descriptorpb.Default_FileOptions_PyGenericServices +const Default_FileOptions_PhpGenericServices = descriptorpb.Default_FileOptions_PhpGenericServices +const Default_FileOptions_Deprecated = descriptorpb.Default_FileOptions_Deprecated +const Default_FileOptions_CcEnableArenas = descriptorpb.Default_FileOptions_CcEnableArenas + +type MessageOptions = descriptorpb.MessageOptions + +const Default_MessageOptions_MessageSetWireFormat = descriptorpb.Default_MessageOptions_MessageSetWireFormat +const Default_MessageOptions_NoStandardDescriptorAccessor = descriptorpb.Default_MessageOptions_NoStandardDescriptorAccessor +const Default_MessageOptions_Deprecated = descriptorpb.Default_MessageOptions_Deprecated + +type FieldOptions = descriptorpb.FieldOptions + +const Default_FieldOptions_Ctype = descriptorpb.Default_FieldOptions_Ctype +const Default_FieldOptions_Jstype = descriptorpb.Default_FieldOptions_Jstype +const Default_FieldOptions_Lazy = descriptorpb.Default_FieldOptions_Lazy +const Default_FieldOptions_Deprecated = descriptorpb.Default_FieldOptions_Deprecated +const Default_FieldOptions_Weak = descriptorpb.Default_FieldOptions_Weak + +type OneofOptions = descriptorpb.OneofOptions +type EnumOptions = descriptorpb.EnumOptions + +const Default_EnumOptions_Deprecated = descriptorpb.Default_EnumOptions_Deprecated + +type EnumValueOptions = descriptorpb.EnumValueOptions + +const Default_EnumValueOptions_Deprecated = descriptorpb.Default_EnumValueOptions_Deprecated + +type ServiceOptions = descriptorpb.ServiceOptions + +const Default_ServiceOptions_Deprecated = descriptorpb.Default_ServiceOptions_Deprecated + +type MethodOptions = descriptorpb.MethodOptions + +const Default_MethodOptions_Deprecated = descriptorpb.Default_MethodOptions_Deprecated +const Default_MethodOptions_IdempotencyLevel = descriptorpb.Default_MethodOptions_IdempotencyLevel + +type UninterpretedOption = descriptorpb.UninterpretedOption +type SourceCodeInfo = descriptorpb.SourceCodeInfo +type GeneratedCodeInfo = descriptorpb.GeneratedCodeInfo +type DescriptorProto_ExtensionRange = descriptorpb.DescriptorProto_ExtensionRange +type DescriptorProto_ReservedRange = descriptorpb.DescriptorProto_ReservedRange +type EnumDescriptorProto_EnumReservedRange = descriptorpb.EnumDescriptorProto_EnumReservedRange +type UninterpretedOption_NamePart = descriptorpb.UninterpretedOption_NamePart +type SourceCodeInfo_Location = descriptorpb.SourceCodeInfo_Location +type GeneratedCodeInfo_Annotation = descriptorpb.GeneratedCodeInfo_Annotation + +var File_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto protoreflect.FileDescriptor + +var file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_rawDesc = []byte{ + 0x0a, 0x44, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, + 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, 0x6e, 0x2d, 0x67, 0x6f, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, + 0x69, 0x70, 0x74, 0x6f, 0x72, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, + 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x40, 0x5a, 0x3e, 0x67, 0x69, 0x74, 0x68, + 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, + 0x6e, 0x2d, 0x67, 0x6f, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x3b, + 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x32, +} + +var file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_goTypes = []interface{}{} +var file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_init() } +func file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_init() { + if File_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_rawDesc, + NumEnums: 0, + NumMessages: 0, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_goTypes, + DependencyIndexes: file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_depIdxs, + }.Build() + File_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto = out.File + file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_rawDesc = nil + file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_goTypes = nil + file_github_com_golang_protobuf_protoc_gen_go_descriptor_descriptor_proto_depIdxs = nil } diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto deleted file mode 100644 index a2102d7aa99..00000000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto +++ /dev/null @@ -1,885 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// The messages in this file describe the definitions found in .proto files. -// A valid .proto file can be translated directly to a FileDescriptorProto -// without any other information (e.g. without reading its imports). - - -syntax = "proto2"; - -package google.protobuf; - -option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "DescriptorProtos"; -option csharp_namespace = "Google.Protobuf.Reflection"; -option objc_class_prefix = "GPB"; -option cc_enable_arenas = true; - -// descriptor.proto must be optimized for speed because reflection-based -// algorithms don't work during bootstrapping. -option optimize_for = SPEED; - -// The protocol compiler can output a FileDescriptorSet containing the .proto -// files it parses. -message FileDescriptorSet { - repeated FileDescriptorProto file = 1; -} - -// Describes a complete .proto file. -message FileDescriptorProto { - optional string name = 1; // file name, relative to root of source tree - optional string package = 2; // e.g. "foo", "foo.bar", etc. - - // Names of files imported by this file. - repeated string dependency = 3; - // Indexes of the public imported files in the dependency list above. - repeated int32 public_dependency = 10; - // Indexes of the weak imported files in the dependency list. - // For Google-internal migration only. Do not use. - repeated int32 weak_dependency = 11; - - // All top-level definitions in this file. - repeated DescriptorProto message_type = 4; - repeated EnumDescriptorProto enum_type = 5; - repeated ServiceDescriptorProto service = 6; - repeated FieldDescriptorProto extension = 7; - - optional FileOptions options = 8; - - // This field contains optional information about the original source code. - // You may safely remove this entire field without harming runtime - // functionality of the descriptors -- the information is needed only by - // development tools. - optional SourceCodeInfo source_code_info = 9; - - // The syntax of the proto file. - // The supported values are "proto2" and "proto3". - optional string syntax = 12; -} - -// Describes a message type. -message DescriptorProto { - optional string name = 1; - - repeated FieldDescriptorProto field = 2; - repeated FieldDescriptorProto extension = 6; - - repeated DescriptorProto nested_type = 3; - repeated EnumDescriptorProto enum_type = 4; - - message ExtensionRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Exclusive. - - optional ExtensionRangeOptions options = 3; - } - repeated ExtensionRange extension_range = 5; - - repeated OneofDescriptorProto oneof_decl = 8; - - optional MessageOptions options = 7; - - // Range of reserved tag numbers. Reserved tag numbers may not be used by - // fields or extension ranges in the same message. Reserved ranges may - // not overlap. - message ReservedRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Exclusive. - } - repeated ReservedRange reserved_range = 9; - // Reserved field names, which may not be used by fields in the same message. - // A given name may only be reserved once. - repeated string reserved_name = 10; -} - -message ExtensionRangeOptions { - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -// Describes a field within a message. -message FieldDescriptorProto { - enum Type { - // 0 is reserved for errors. - // Order is weird for historical reasons. - TYPE_DOUBLE = 1; - TYPE_FLOAT = 2; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - TYPE_INT64 = 3; - TYPE_UINT64 = 4; - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - TYPE_INT32 = 5; - TYPE_FIXED64 = 6; - TYPE_FIXED32 = 7; - TYPE_BOOL = 8; - TYPE_STRING = 9; - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - TYPE_GROUP = 10; - TYPE_MESSAGE = 11; // Length-delimited aggregate. - - // New in version 2. - TYPE_BYTES = 12; - TYPE_UINT32 = 13; - TYPE_ENUM = 14; - TYPE_SFIXED32 = 15; - TYPE_SFIXED64 = 16; - TYPE_SINT32 = 17; // Uses ZigZag encoding. - TYPE_SINT64 = 18; // Uses ZigZag encoding. - } - - enum Label { - // 0 is reserved for errors - LABEL_OPTIONAL = 1; - LABEL_REQUIRED = 2; - LABEL_REPEATED = 3; - } - - optional string name = 1; - optional int32 number = 3; - optional Label label = 4; - - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. - optional Type type = 5; - - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - optional string type_name = 6; - - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - optional string extendee = 2; - - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - // TODO(kenton): Base-64 encode? - optional string default_value = 7; - - // If set, gives the index of a oneof in the containing type's oneof_decl - // list. This field is a member of that oneof. - optional int32 oneof_index = 9; - - // JSON name of this field. The value is set by protocol compiler. If the - // user has set a "json_name" option on this field, that option's value - // will be used. Otherwise, it's deduced from the field's name by converting - // it to camelCase. - optional string json_name = 10; - - optional FieldOptions options = 8; -} - -// Describes a oneof. -message OneofDescriptorProto { - optional string name = 1; - optional OneofOptions options = 2; -} - -// Describes an enum type. -message EnumDescriptorProto { - optional string name = 1; - - repeated EnumValueDescriptorProto value = 2; - - optional EnumOptions options = 3; - - // Range of reserved numeric values. Reserved values may not be used by - // entries in the same enum. Reserved ranges may not overlap. - // - // Note that this is distinct from DescriptorProto.ReservedRange in that it - // is inclusive such that it can appropriately represent the entire int32 - // domain. - message EnumReservedRange { - optional int32 start = 1; // Inclusive. - optional int32 end = 2; // Inclusive. - } - - // Range of reserved numeric values. Reserved numeric values may not be used - // by enum values in the same enum declaration. Reserved ranges may not - // overlap. - repeated EnumReservedRange reserved_range = 4; - - // Reserved enum value names, which may not be reused. A given name may only - // be reserved once. - repeated string reserved_name = 5; -} - -// Describes a value within an enum. -message EnumValueDescriptorProto { - optional string name = 1; - optional int32 number = 2; - - optional EnumValueOptions options = 3; -} - -// Describes a service. -message ServiceDescriptorProto { - optional string name = 1; - repeated MethodDescriptorProto method = 2; - - optional ServiceOptions options = 3; -} - -// Describes a method of a service. -message MethodDescriptorProto { - optional string name = 1; - - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - optional string input_type = 2; - optional string output_type = 3; - - optional MethodOptions options = 4; - - // Identifies if client streams multiple client messages - optional bool client_streaming = 5 [default = false]; - // Identifies if server streams multiple server messages - optional bool server_streaming = 6 [default = false]; -} - - -// =================================================================== -// Options - -// Each of the definitions above may have "options" attached. These are -// just annotations which may cause code to be generated slightly differently -// or may contain hints for code that manipulates protocol messages. -// -// Clients may define custom options as extensions of the *Options messages. -// These extensions may not yet be known at parsing time, so the parser cannot -// store the values in them. Instead it stores them in a field in the *Options -// message called uninterpreted_option. This field must have the same name -// across all *Options messages. We then use this field to populate the -// extensions when we build a descriptor, at which point all protos have been -// parsed and so all extensions are known. -// -// Extension numbers for custom options may be chosen as follows: -// * For options which will only be used within a single application or -// organization, or for experimental options, use field numbers 50000 -// through 99999. It is up to you to ensure that you do not use the -// same number for multiple options. -// * For options which will be published and used publicly by multiple -// independent entities, e-mail protobuf-global-extension-registry@google.com -// to reserve extension numbers. Simply provide your project name (e.g. -// Objective-C plugin) and your project website (if available) -- there's no -// need to explain how you intend to use them. Usually you only need one -// extension number. You can declare multiple options with only one extension -// number by putting them in a sub-message. See the Custom Options section of -// the docs for examples: -// https://developers.google.com/protocol-buffers/docs/proto#options -// If this turns out to be popular, a web service will be set up -// to automatically assign option numbers. - -message FileOptions { - - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - optional string java_package = 1; - - - // If set, all the classes from the .proto file are wrapped in a single - // outer class with the given name. This applies to both Proto1 - // (equivalent to the old "--one_java_file" option) and Proto2 (where - // a .proto always translates to a single class, but you may want to - // explicitly choose the class name). - optional string java_outer_classname = 8; - - // If set true, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the outer class - // named by java_outer_classname. However, the outer class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - optional bool java_multiple_files = 10 [default = false]; - - // This option does nothing. - optional bool java_generate_equals_and_hash = 20 [deprecated=true]; - - // If set true, then the Java2 code generator will generate code that - // throws an exception whenever an attempt is made to assign a non-UTF-8 - // byte sequence to a string field. - // Message reflection will do the same. - // However, an extension field still accepts non-UTF-8 byte sequences. - // This option has no effect on when used with the lite runtime. - optional bool java_string_check_utf8 = 27 [default = false]; - - - // Generated classes can be optimized for speed or code size. - enum OptimizeMode { - SPEED = 1; // Generate complete code for parsing, serialization, - // etc. - CODE_SIZE = 2; // Use ReflectionOps to implement these methods. - LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. - } - optional OptimizeMode optimize_for = 9 [default = SPEED]; - - // Sets the Go package where structs generated from this .proto will be - // placed. If omitted, the Go package will be derived from the following: - // - The basename of the package import path, if provided. - // - Otherwise, the package statement in the .proto file, if present. - // - Otherwise, the basename of the .proto file, without extension. - optional string go_package = 11; - - - - - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of google.protobuf. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. Therefore, - // these default to false. Old code which depends on generic services should - // explicitly set them to true. - optional bool cc_generic_services = 16 [default = false]; - optional bool java_generic_services = 17 [default = false]; - optional bool py_generic_services = 18 [default = false]; - optional bool php_generic_services = 42 [default = false]; - - // Is this file deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for everything in the file, or it will be completely ignored; in the very - // least, this is a formalization for deprecating files. - optional bool deprecated = 23 [default = false]; - - // Enables the use of arenas for the proto messages in this file. This applies - // only to generated classes for C++. - optional bool cc_enable_arenas = 31 [default = false]; - - - // Sets the objective c class prefix which is prepended to all objective c - // generated classes from this .proto. There is no default. - optional string objc_class_prefix = 36; - - // Namespace for generated classes; defaults to the package. - optional string csharp_namespace = 37; - - // By default Swift generators will take the proto package and CamelCase it - // replacing '.' with underscore and use that to prefix the types/symbols - // defined. When this options is provided, they will use this value instead - // to prefix the types/symbols defined. - optional string swift_prefix = 39; - - // Sets the php class prefix which is prepended to all php generated classes - // from this .proto. Default is empty. - optional string php_class_prefix = 40; - - // Use this option to change the namespace of php generated classes. Default - // is empty. When this option is empty, the package name will be used for - // determining the namespace. - optional string php_namespace = 41; - - // Use this option to change the namespace of php generated metadata classes. - // Default is empty. When this option is empty, the proto file name will be - // used for determining the namespace. - optional string php_metadata_namespace = 44; - - // Use this option to change the package of ruby generated classes. Default - // is empty. When this option is not set, the package name will be used for - // determining the ruby package. - optional string ruby_package = 45; - - - // The parser stores options it doesn't recognize here. - // See the documentation for the "Options" section above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. - // See the documentation for the "Options" section above. - extensions 1000 to max; - - reserved 38; -} - -message MessageOptions { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - optional bool message_set_wire_format = 1 [default = false]; - - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - optional bool no_standard_descriptor_accessor = 2 [default = false]; - - // Is this message deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the message, or it will be completely ignored; in the very least, - // this is a formalization for deprecating messages. - optional bool deprecated = 3 [default = false]; - - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementations still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - optional bool map_entry = 7; - - reserved 8; // javalite_serializable - reserved 9; // javanano_as_lite - - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message FieldOptions { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - optional CType ctype = 1 [default = STRING]; - enum CType { - // Default mode. - STRING = 0; - - CORD = 1; - - STRING_PIECE = 2; - } - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. In proto3, only explicit setting it to - // false will avoid using packed encoding. - optional bool packed = 2; - - // The jstype option determines the JavaScript type used for values of the - // field. The option is permitted only for 64 bit integral and fixed types - // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING - // is represented as JavaScript string, which avoids loss of precision that - // can happen when a large value is converted to a floating point JavaScript. - // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to - // use the JavaScript "number" type. The behavior of the default option - // JS_NORMAL is implementation dependent. - // - // This option is an enum to permit additional types to be added, e.g. - // goog.math.Integer. - optional JSType jstype = 6 [default = JS_NORMAL]; - enum JSType { - // Use the default type. - JS_NORMAL = 0; - - // Use JavaScript strings. - JS_STRING = 1; - - // Use JavaScript numbers. - JS_NUMBER = 2; - } - - // Should this field be parsed lazily? Lazy applies only to message-type - // fields. It means that when the outer message is initially parsed, the - // inner message's contents will not be parsed but instead stored in encoded - // form. The inner message will actually be parsed when it is first accessed. - // - // This is only a hint. Implementations are free to choose whether to use - // eager or lazy parsing regardless of the value of this option. However, - // setting this option true suggests that the protocol author believes that - // using lazy parsing on this field is worth the additional bookkeeping - // overhead typically needed to implement it. - // - // This option does not affect the public interface of any generated code; - // all method signatures remain the same. Furthermore, thread-safety of the - // interface is not affected by this option; const methods remain safe to - // call from multiple threads concurrently, while non-const methods continue - // to require exclusive access. - // - // - // Note that implementations may choose not to check required fields within - // a lazy sub-message. That is, calling IsInitialized() on the outer message - // may return true even if the inner message has missing required fields. - // This is necessary because otherwise the inner message would have to be - // parsed in order to perform the check, defeating the purpose of lazy - // parsing. An implementation which chooses not to check required fields - // must be consistent about it. That is, for any particular sub-message, the - // implementation must either *always* check its required fields, or *never* - // check its required fields, regardless of whether or not the message has - // been parsed. - optional bool lazy = 5 [default = false]; - - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - optional bool deprecated = 3 [default = false]; - - // For Google-internal migration only. Do not use. - optional bool weak = 10 [default = false]; - - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; - - reserved 4; // removed jtype -} - -message OneofOptions { - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message EnumOptions { - - // Set this option to true to allow mapping different tag names to the same - // value. - optional bool allow_alias = 2; - - // Is this enum deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum, or it will be completely ignored; in the very least, this - // is a formalization for deprecating enums. - optional bool deprecated = 3 [default = false]; - - reserved 5; // javanano_as_lite - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message EnumValueOptions { - // Is this enum value deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum value, or it will be completely ignored; in the very least, - // this is a formalization for deprecating enum values. - optional bool deprecated = 1 [default = false]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message ServiceOptions { - - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. - - // Is this service deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the service, or it will be completely ignored; in the very least, - // this is a formalization for deprecating services. - optional bool deprecated = 33 [default = false]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message MethodOptions { - - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. - - // Is this method deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the method, or it will be completely ignored; in the very least, - // this is a formalization for deprecating methods. - optional bool deprecated = 33 [default = false]; - - // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, - // or neither? HTTP based RPC implementation may choose GET verb for safe - // methods, and PUT verb for idempotent methods instead of the default POST. - enum IdempotencyLevel { - IDEMPOTENCY_UNKNOWN = 0; - NO_SIDE_EFFECTS = 1; // implies idempotent - IDEMPOTENT = 2; // idempotent, but may have side effects - } - optional IdempotencyLevel idempotency_level = 34 - [default = IDEMPOTENCY_UNKNOWN]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - - -// A message representing a option the parser does not recognize. This only -// appears in options protos created by the compiler::Parser class. -// DescriptorPool resolves these when building Descriptor objects. Therefore, -// options protos in descriptor objects (e.g. returned by Descriptor::options(), -// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions -// in them. -message UninterpretedOption { - // The name of the uninterpreted option. Each string represents a segment in - // a dot-separated name. is_extension is true iff a segment represents an - // extension (denoted with parentheses in options specs in .proto files). - // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents - // "foo.(bar.baz).qux". - message NamePart { - required string name_part = 1; - required bool is_extension = 2; - } - repeated NamePart name = 2; - - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - optional string identifier_value = 3; - optional uint64 positive_int_value = 4; - optional int64 negative_int_value = 5; - optional double double_value = 6; - optional bytes string_value = 7; - optional string aggregate_value = 8; -} - -// =================================================================== -// Optional source code info - -// Encapsulates information about the original source file from which a -// FileDescriptorProto was generated. -message SourceCodeInfo { - // A Location identifies a piece of source code in a .proto file which - // corresponds to a particular definition. This information is intended - // to be useful to IDEs, code indexers, documentation generators, and similar - // tools. - // - // For example, say we have a file like: - // message Foo { - // optional string foo = 1; - // } - // Let's look at just the field definition: - // optional string foo = 1; - // ^ ^^ ^^ ^ ^^^ - // a bc de f ghi - // We have the following locations: - // span path represents - // [a,i) [ 4, 0, 2, 0 ] The whole field definition. - // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). - // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). - // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). - // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). - // - // Notes: - // - A location may refer to a repeated field itself (i.e. not to any - // particular index within it). This is used whenever a set of elements are - // logically enclosed in a single code segment. For example, an entire - // extend block (possibly containing multiple extension definitions) will - // have an outer location whose path refers to the "extensions" repeated - // field without an index. - // - Multiple locations may have the same path. This happens when a single - // logical declaration is spread out across multiple places. The most - // obvious example is the "extend" block again -- there may be multiple - // extend blocks in the same scope, each of which will have the same path. - // - A location's span is not always a subset of its parent's span. For - // example, the "extendee" of an extension declaration appears at the - // beginning of the "extend" block and is shared by all extensions within - // the block. - // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendant. For example, a "group" defines - // both a type and a field in a single declaration. Thus, the locations - // corresponding to the type and field and their components will overlap. - // - Code which tries to interpret locations should probably be designed to - // ignore those that it doesn't understand, as more types of locations could - // be recorded in the future. - repeated Location location = 1; - message Location { - // Identifies which part of the FileDescriptorProto was defined at this - // location. - // - // Each element is a field number or an index. They form a path from - // the root FileDescriptorProto to the place where the definition. For - // example, this path: - // [ 4, 3, 2, 7, 1 ] - // refers to: - // file.message_type(3) // 4, 3 - // .field(7) // 2, 7 - // .name() // 1 - // This is because FileDescriptorProto.message_type has field number 4: - // repeated DescriptorProto message_type = 4; - // and DescriptorProto.field has field number 2: - // repeated FieldDescriptorProto field = 2; - // and FieldDescriptorProto.name has field number 1: - // optional string name = 1; - // - // Thus, the above path gives the location of a field name. If we removed - // the last element: - // [ 4, 3, 2, 7 ] - // this path refers to the whole field declaration (from the beginning - // of the label to the terminating semicolon). - repeated int32 path = 1 [packed = true]; - - // Always has exactly three or four elements: start line, start column, - // end line (optional, otherwise assumed same as start line), end column. - // These are packed into a single field for efficiency. Note that line - // and column numbers are zero-based -- typically you will want to add - // 1 to each before displaying to a user. - repeated int32 span = 2 [packed = true]; - - // If this SourceCodeInfo represents a complete declaration, these are any - // comments appearing before and after the declaration which appear to be - // attached to the declaration. - // - // A series of line comments appearing on consecutive lines, with no other - // tokens appearing on those lines, will be treated as a single comment. - // - // leading_detached_comments will keep paragraphs of comments that appear - // before (but not connected to) the current element. Each paragraph, - // separated by empty lines, will be one comment element in the repeated - // field. - // - // Only the comment content is provided; comment markers (e.g. //) are - // stripped out. For block comments, leading whitespace and an asterisk - // will be stripped from the beginning of each line other than the first. - // Newlines are included in the output. - // - // Examples: - // - // optional int32 foo = 1; // Comment attached to foo. - // // Comment attached to bar. - // optional int32 bar = 2; - // - // optional string baz = 3; - // // Comment attached to baz. - // // Another line attached to baz. - // - // // Comment attached to qux. - // // - // // Another line attached to qux. - // optional double qux = 4; - // - // // Detached comment for corge. This is not leading or trailing comments - // // to qux or corge because there are blank lines separating it from - // // both. - // - // // Detached comment for corge paragraph 2. - // - // optional string corge = 5; - // /* Block comment attached - // * to corge. Leading asterisks - // * will be removed. */ - // /* Block comment attached to - // * grault. */ - // optional int32 grault = 6; - // - // // ignored detached comments. - optional string leading_comments = 3; - optional string trailing_comments = 4; - repeated string leading_detached_comments = 6; - } -} - -// Describes the relationship between generated code and its original source -// file. A GeneratedCodeInfo message is associated with only one generated -// source file, but may contain references to different source .proto files. -message GeneratedCodeInfo { - // An Annotation connects some span of text in generated code to an element - // of its generating .proto file. - repeated Annotation annotation = 1; - message Annotation { - // Identifies the element in the original source .proto file. This field - // is formatted the same as SourceCodeInfo.Location.path. - repeated int32 path = 1 [packed = true]; - - // Identifies the filesystem path to the original source .proto. - optional string source_file = 2; - - // Identifies the starting offset in bytes in the generated code - // that relates to the identified object. - optional int32 begin = 3; - - // Identifies the ending offset in bytes in the generated code that - // relates to the identified offset. The end offset should be one past - // the last relevant byte (so the length of the text = end - begin). - optional int32 end = 4; - } -} diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/main.go b/vendor/github.com/golang/protobuf/protoc-gen-go/main.go new file mode 100644 index 00000000000..d45b719d1c6 --- /dev/null +++ b/vendor/github.com/golang/protobuf/protoc-gen-go/main.go @@ -0,0 +1,74 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// protoc-gen-go is a plugin for the Google protocol buffer compiler to generate +// Go code. Install it by building this program and making it accessible within +// your PATH with the name: +// protoc-gen-go +// +// The 'go' suffix becomes part of the argument for the protocol compiler, +// such that it can be invoked as: +// protoc --go_out=paths=source_relative:. path/to/file.proto +// +// This generates Go bindings for the protocol buffer defined by file.proto. +// With that input, the output will be written to: +// path/to/file.pb.go +// +// See the README and documentation for protocol buffers to learn more: +// https://developers.google.com/protocol-buffers/ +package main + +import ( + "flag" + "fmt" + "strings" + + "github.com/golang/protobuf/internal/gengogrpc" + gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo" + "google.golang.org/protobuf/compiler/protogen" +) + +func main() { + var ( + flags flag.FlagSet + plugins = flags.String("plugins", "", "list of plugins to enable (supported values: grpc)") + importPrefix = flags.String("import_prefix", "", "prefix to prepend to import paths") + ) + importRewriteFunc := func(importPath protogen.GoImportPath) protogen.GoImportPath { + switch importPath { + case "context", "fmt", "math": + return importPath + } + if *importPrefix != "" { + return protogen.GoImportPath(*importPrefix) + importPath + } + return importPath + } + protogen.Options{ + ParamFunc: flags.Set, + ImportRewriteFunc: importRewriteFunc, + }.Run(func(gen *protogen.Plugin) error { + grpc := false + for _, plugin := range strings.Split(*plugins, ",") { + switch plugin { + case "grpc": + grpc = true + case "": + default: + return fmt.Errorf("protoc-gen-go: unknown plugin %q", plugin) + } + } + for _, f := range gen.Files { + if !f.Generate { + continue + } + g := gengo.GenerateFile(gen, f) + if grpc { + gengogrpc.GenerateFileContent(gen, f, g) + } + } + gen.SupportedFeatures = gengo.SupportedFeatures + return nil + }) +} diff --git a/vendor/github.com/golang/protobuf/ptypes/any.go b/vendor/github.com/golang/protobuf/ptypes/any.go index 70276e8f5c9..e729dcff13c 100644 --- a/vendor/github.com/golang/protobuf/ptypes/any.go +++ b/vendor/github.com/golang/protobuf/ptypes/any.go @@ -1,141 +1,165 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. package ptypes -// This file implements functions to marshal proto.Message to/from -// google.protobuf.Any message. - import ( "fmt" - "reflect" "strings" "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/any" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + + anypb "github.com/golang/protobuf/ptypes/any" ) -const googleApis = "type.googleapis.com/" +const urlPrefix = "type.googleapis.com/" -// AnyMessageName returns the name of the message contained in a google.protobuf.Any message. -// -// Note that regular type assertions should be done using the Is -// function. AnyMessageName is provided for less common use cases like filtering a -// sequence of Any messages based on a set of allowed message type names. -func AnyMessageName(any *any.Any) (string, error) { +// AnyMessageName returns the message name contained in an anypb.Any message. +// Most type assertions should use the Is function instead. +func AnyMessageName(any *anypb.Any) (string, error) { + name, err := anyMessageName(any) + return string(name), err +} +func anyMessageName(any *anypb.Any) (protoreflect.FullName, error) { if any == nil { return "", fmt.Errorf("message is nil") } - slash := strings.LastIndex(any.TypeUrl, "/") - if slash < 0 { + name := protoreflect.FullName(any.TypeUrl) + if i := strings.LastIndex(any.TypeUrl, "/"); i >= 0 { + name = name[i+len("/"):] + } + if !name.IsValid() { return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl) } - return any.TypeUrl[slash+1:], nil + return name, nil } -// MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any. -func MarshalAny(pb proto.Message) (*any.Any, error) { - value, err := proto.Marshal(pb) +// MarshalAny marshals the given message m into an anypb.Any message. +func MarshalAny(m proto.Message) (*anypb.Any, error) { + switch dm := m.(type) { + case DynamicAny: + m = dm.Message + case *DynamicAny: + if dm == nil { + return nil, proto.ErrNil + } + m = dm.Message + } + b, err := proto.Marshal(m) if err != nil { return nil, err } - return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil -} - -// DynamicAny is a value that can be passed to UnmarshalAny to automatically -// allocate a proto.Message for the type specified in a google.protobuf.Any -// message. The allocated message is stored in the embedded proto.Message. -// -// Example: -// -// var x ptypes.DynamicAny -// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... } -// fmt.Printf("unmarshaled message: %v", x.Message) -type DynamicAny struct { - proto.Message + return &anypb.Any{TypeUrl: urlPrefix + proto.MessageName(m), Value: b}, nil } -// Empty returns a new proto.Message of the type specified in a -// google.protobuf.Any message. It returns an error if corresponding message -// type isn't linked in. -func Empty(any *any.Any) (proto.Message, error) { - aname, err := AnyMessageName(any) +// Empty returns a new message of the type specified in an anypb.Any message. +// It returns protoregistry.NotFound if the corresponding message type could not +// be resolved in the global registry. +func Empty(any *anypb.Any) (proto.Message, error) { + name, err := anyMessageName(any) if err != nil { return nil, err } - - t := proto.MessageType(aname) - if t == nil { - return nil, fmt.Errorf("any: message type %q isn't linked in", aname) + mt, err := protoregistry.GlobalTypes.FindMessageByName(name) + if err != nil { + return nil, err } - return reflect.New(t.Elem()).Interface().(proto.Message), nil + return proto.MessageV1(mt.New().Interface()), nil } -// UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any -// message and places the decoded result in pb. It returns an error if type of -// contents of Any message does not match type of pb message. +// UnmarshalAny unmarshals the encoded value contained in the anypb.Any message +// into the provided message m. It returns an error if the target message +// does not match the type in the Any message or if an unmarshal error occurs. // -// pb can be a proto.Message, or a *DynamicAny. -func UnmarshalAny(any *any.Any, pb proto.Message) error { - if d, ok := pb.(*DynamicAny); ok { - if d.Message == nil { +// The target message m may be a *DynamicAny message. If the underlying message +// type could not be resolved, then this returns protoregistry.NotFound. +func UnmarshalAny(any *anypb.Any, m proto.Message) error { + if dm, ok := m.(*DynamicAny); ok { + if dm.Message == nil { var err error - d.Message, err = Empty(any) + dm.Message, err = Empty(any) if err != nil { return err } } - return UnmarshalAny(any, d.Message) + m = dm.Message } - aname, err := AnyMessageName(any) + anyName, err := AnyMessageName(any) if err != nil { return err } - - mname := proto.MessageName(pb) - if aname != mname { - return fmt.Errorf("mismatched message type: got %q want %q", aname, mname) + msgName := proto.MessageName(m) + if anyName != msgName { + return fmt.Errorf("mismatched message type: got %q want %q", anyName, msgName) } - return proto.Unmarshal(any.Value, pb) + return proto.Unmarshal(any.Value, m) } -// Is returns true if any value contains a given message type. -func Is(any *any.Any, pb proto.Message) bool { - // The following is equivalent to AnyMessageName(any) == proto.MessageName(pb), - // but it avoids scanning TypeUrl for the slash. - if any == nil { +// Is reports whether the Any message contains a message of the specified type. +func Is(any *anypb.Any, m proto.Message) bool { + if any == nil || m == nil { return false } - name := proto.MessageName(pb) - prefix := len(any.TypeUrl) - len(name) - return prefix >= 1 && any.TypeUrl[prefix-1] == '/' && any.TypeUrl[prefix:] == name + name := proto.MessageName(m) + if !strings.HasSuffix(any.TypeUrl, name) { + return false + } + return len(any.TypeUrl) == len(name) || any.TypeUrl[len(any.TypeUrl)-len(name)-1] == '/' +} + +// DynamicAny is a value that can be passed to UnmarshalAny to automatically +// allocate a proto.Message for the type specified in an anypb.Any message. +// The allocated message is stored in the embedded proto.Message. +// +// Example: +// var x ptypes.DynamicAny +// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... } +// fmt.Printf("unmarshaled message: %v", x.Message) +type DynamicAny struct{ proto.Message } + +func (m DynamicAny) String() string { + if m.Message == nil { + return "" + } + return m.Message.String() +} +func (m DynamicAny) Reset() { + if m.Message == nil { + return + } + m.Message.Reset() +} +func (m DynamicAny) ProtoMessage() { + return +} +func (m DynamicAny) ProtoReflect() protoreflect.Message { + if m.Message == nil { + return nil + } + return dynamicAny{proto.MessageReflect(m.Message)} +} + +type dynamicAny struct{ protoreflect.Message } + +func (m dynamicAny) Type() protoreflect.MessageType { + return dynamicAnyType{m.Message.Type()} +} +func (m dynamicAny) New() protoreflect.Message { + return dynamicAnyType{m.Message.Type()}.New() +} +func (m dynamicAny) Interface() protoreflect.ProtoMessage { + return DynamicAny{proto.MessageV1(m.Message.Interface())} +} + +type dynamicAnyType struct{ protoreflect.MessageType } + +func (t dynamicAnyType) New() protoreflect.Message { + return dynamicAny{t.MessageType.New()} +} +func (t dynamicAnyType) Zero() protoreflect.Message { + return dynamicAny{t.MessageType.Zero()} } diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go index 7b0ad1ad86c..0ef27d33deb 100644 --- a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go +++ b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go @@ -1,203 +1,62 @@ // Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/any.proto +// source: github.com/golang/protobuf/ptypes/any/any.proto package any import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + anypb "google.golang.org/protobuf/types/known/anypb" + reflect "reflect" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +// Symbols defined in public import of google/protobuf/any.proto. -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +type Any = anypb.Any -// `Any` contains an arbitrary serialized protocol buffer message along with a -// URL that describes the type of the serialized message. -// -// Protobuf library provides support to pack/unpack Any values in the form -// of utility functions or additional generated methods of the Any type. -// -// Example 1: Pack and unpack a message in C++. -// -// Foo foo = ...; -// Any any; -// any.PackFrom(foo); -// ... -// if (any.UnpackTo(&foo)) { -// ... -// } -// -// Example 2: Pack and unpack a message in Java. -// -// Foo foo = ...; -// Any any = Any.pack(foo); -// ... -// if (any.is(Foo.class)) { -// foo = any.unpack(Foo.class); -// } -// -// Example 3: Pack and unpack a message in Python. -// -// foo = Foo(...) -// any = Any() -// any.Pack(foo) -// ... -// if any.Is(Foo.DESCRIPTOR): -// any.Unpack(foo) -// ... -// -// Example 4: Pack and unpack a message in Go -// -// foo := &pb.Foo{...} -// any, err := ptypes.MarshalAny(foo) -// ... -// foo := &pb.Foo{} -// if err := ptypes.UnmarshalAny(any, foo); err != nil { -// ... -// } -// -// The pack methods provided by protobuf library will by default use -// 'type.googleapis.com/full.type.name' as the type URL and the unpack -// methods only use the fully qualified type name after the last '/' -// in the type URL, for example "foo.bar.com/x/y.z" will yield type -// name "y.z". -// -// -// JSON -// ==== -// The JSON representation of an `Any` value uses the regular -// representation of the deserialized, embedded message, with an -// additional field `@type` which contains the type URL. Example: -// -// package google.profile; -// message Person { -// string first_name = 1; -// string last_name = 2; -// } -// -// { -// "@type": "type.googleapis.com/google.profile.Person", -// "firstName": , -// "lastName": -// } -// -// If the embedded message type is well-known and has a custom JSON -// representation, that representation will be embedded adding a field -// `value` which holds the custom JSON in addition to the `@type` -// field. Example (for message [google.protobuf.Duration][]): -// -// { -// "@type": "type.googleapis.com/google.protobuf.Duration", -// "value": "1.212s" -// } -// -type Any struct { - // A URL/resource name that uniquely identifies the type of the serialized - // protocol buffer message. This string must contain at least - // one "/" character. The last segment of the URL's path must represent - // the fully qualified name of the type (as in - // `path/google.protobuf.Duration`). The name should be in a canonical form - // (e.g., leading "." is not accepted). - // - // In practice, teams usually precompile into the binary all types that they - // expect it to use in the context of Any. However, for URLs which use the - // scheme `http`, `https`, or no scheme, one can optionally set up a type - // server that maps type URLs to message definitions as follows: - // - // * If no scheme is provided, `https` is assumed. - // * An HTTP GET on the URL must yield a [google.protobuf.Type][] - // value in binary format, or produce an error. - // * Applications are allowed to cache lookup results based on the - // URL, or have them precompiled into a binary to avoid any - // lookup. Therefore, binary compatibility needs to be preserved - // on changes to types. (Use versioned type names to manage - // breaking changes.) - // - // Note: this functionality is not currently available in the official - // protobuf release, and it is not used for type URLs beginning with - // type.googleapis.com. - // - // Schemes other than `http`, `https` (or the empty scheme) might be - // used with implementation specific semantics. - // - TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"` - // Must be a valid serialized protocol buffer of the above specified type. - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Any) Reset() { *m = Any{} } -func (m *Any) String() string { return proto.CompactTextString(m) } -func (*Any) ProtoMessage() {} -func (*Any) Descriptor() ([]byte, []int) { - return fileDescriptor_b53526c13ae22eb4, []int{0} -} - -func (*Any) XXX_WellKnownType() string { return "Any" } +var File_github_com_golang_protobuf_ptypes_any_any_proto protoreflect.FileDescriptor -func (m *Any) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Any.Unmarshal(m, b) -} -func (m *Any) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Any.Marshal(b, m, deterministic) -} -func (m *Any) XXX_Merge(src proto.Message) { - xxx_messageInfo_Any.Merge(m, src) -} -func (m *Any) XXX_Size() int { - return xxx_messageInfo_Any.Size(m) -} -func (m *Any) XXX_DiscardUnknown() { - xxx_messageInfo_Any.DiscardUnknown(m) +var file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc = []byte{ + 0x0a, 0x2f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, + 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, + 0x70, 0x65, 0x73, 0x2f, 0x61, 0x6e, 0x79, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x2b, 0x5a, 0x29, + 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, + 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, + 0x73, 0x2f, 0x61, 0x6e, 0x79, 0x3b, 0x61, 0x6e, 0x79, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, } -var xxx_messageInfo_Any proto.InternalMessageInfo - -func (m *Any) GetTypeUrl() string { - if m != nil { - return m.TypeUrl - } - return "" +var file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes = []interface{}{} +var file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name } -func (m *Any) GetValue() []byte { - if m != nil { - return m.Value +func init() { file_github_com_golang_protobuf_ptypes_any_any_proto_init() } +func file_github_com_golang_protobuf_ptypes_any_any_proto_init() { + if File_github_com_golang_protobuf_ptypes_any_any_proto != nil { + return } - return nil -} - -func init() { - proto.RegisterType((*Any)(nil), "google.protobuf.Any") -} - -func init() { - proto.RegisterFile("google/protobuf/any.proto", fileDescriptor_b53526c13ae22eb4) -} - -var fileDescriptor_b53526c13ae22eb4 = []byte{ - // 185 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4, - 0x03, 0x73, 0x84, 0xf8, 0x21, 0x52, 0x7a, 0x30, 0x29, 0x25, 0x33, 0x2e, 0x66, 0xc7, 0xbc, 0x4a, - 0x21, 0x49, 0x2e, 0x8e, 0x92, 0xca, 0x82, 0xd4, 0xf8, 0xd2, 0xa2, 0x1c, 0x09, 0x46, 0x05, 0x46, - 0x0d, 0xce, 0x20, 0x76, 0x10, 0x3f, 0xb4, 0x28, 0x47, 0x48, 0x84, 0x8b, 0xb5, 0x2c, 0x31, 0xa7, - 0x34, 0x55, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xc2, 0x71, 0xca, 0xe7, 0x12, 0x4e, 0xce, - 0xcf, 0xd5, 0x43, 0x33, 0xce, 0x89, 0xc3, 0x31, 0xaf, 0x32, 0x00, 0xc4, 0x09, 0x60, 0x8c, 0x52, - 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, - 0x4b, 0x47, 0xb8, 0xa8, 0x00, 0x64, 0x7a, 0x31, 0xc8, 0x61, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c, - 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x8c, 0x0a, 0x80, 0x2a, 0xd1, 0x0b, 0x4f, 0xcd, 0xc9, 0xf1, 0xce, - 0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0x29, 0x4d, 0x62, 0x03, 0xeb, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff, - 0xff, 0x13, 0xf8, 0xe8, 0x42, 0xdd, 0x00, 0x00, 0x00, + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc, + NumEnums: 0, + NumMessages: 0, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes, + DependencyIndexes: file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs, + }.Build() + File_github_com_golang_protobuf_ptypes_any_any_proto = out.File + file_github_com_golang_protobuf_ptypes_any_any_proto_rawDesc = nil + file_github_com_golang_protobuf_ptypes_any_any_proto_goTypes = nil + file_github_com_golang_protobuf_ptypes_any_any_proto_depIdxs = nil } diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.proto b/vendor/github.com/golang/protobuf/ptypes/any/any.proto deleted file mode 100644 index c9be8541673..00000000000 --- a/vendor/github.com/golang/protobuf/ptypes/any/any.proto +++ /dev/null @@ -1,155 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option go_package = "github.com/golang/protobuf/ptypes/any"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "AnyProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// `Any` contains an arbitrary serialized protocol buffer message along with a -// URL that describes the type of the serialized message. -// -// Protobuf library provides support to pack/unpack Any values in the form -// of utility functions or additional generated methods of the Any type. -// -// Example 1: Pack and unpack a message in C++. -// -// Foo foo = ...; -// Any any; -// any.PackFrom(foo); -// ... -// if (any.UnpackTo(&foo)) { -// ... -// } -// -// Example 2: Pack and unpack a message in Java. -// -// Foo foo = ...; -// Any any = Any.pack(foo); -// ... -// if (any.is(Foo.class)) { -// foo = any.unpack(Foo.class); -// } -// -// Example 3: Pack and unpack a message in Python. -// -// foo = Foo(...) -// any = Any() -// any.Pack(foo) -// ... -// if any.Is(Foo.DESCRIPTOR): -// any.Unpack(foo) -// ... -// -// Example 4: Pack and unpack a message in Go -// -// foo := &pb.Foo{...} -// any, err := ptypes.MarshalAny(foo) -// ... -// foo := &pb.Foo{} -// if err := ptypes.UnmarshalAny(any, foo); err != nil { -// ... -// } -// -// The pack methods provided by protobuf library will by default use -// 'type.googleapis.com/full.type.name' as the type URL and the unpack -// methods only use the fully qualified type name after the last '/' -// in the type URL, for example "foo.bar.com/x/y.z" will yield type -// name "y.z". -// -// -// JSON -// ==== -// The JSON representation of an `Any` value uses the regular -// representation of the deserialized, embedded message, with an -// additional field `@type` which contains the type URL. Example: -// -// package google.profile; -// message Person { -// string first_name = 1; -// string last_name = 2; -// } -// -// { -// "@type": "type.googleapis.com/google.profile.Person", -// "firstName": , -// "lastName": -// } -// -// If the embedded message type is well-known and has a custom JSON -// representation, that representation will be embedded adding a field -// `value` which holds the custom JSON in addition to the `@type` -// field. Example (for message [google.protobuf.Duration][]): -// -// { -// "@type": "type.googleapis.com/google.protobuf.Duration", -// "value": "1.212s" -// } -// -message Any { - // A URL/resource name that uniquely identifies the type of the serialized - // protocol buffer message. This string must contain at least - // one "/" character. The last segment of the URL's path must represent - // the fully qualified name of the type (as in - // `path/google.protobuf.Duration`). The name should be in a canonical form - // (e.g., leading "." is not accepted). - // - // In practice, teams usually precompile into the binary all types that they - // expect it to use in the context of Any. However, for URLs which use the - // scheme `http`, `https`, or no scheme, one can optionally set up a type - // server that maps type URLs to message definitions as follows: - // - // * If no scheme is provided, `https` is assumed. - // * An HTTP GET on the URL must yield a [google.protobuf.Type][] - // value in binary format, or produce an error. - // * Applications are allowed to cache lookup results based on the - // URL, or have them precompiled into a binary to avoid any - // lookup. Therefore, binary compatibility needs to be preserved - // on changes to types. (Use versioned type names to manage - // breaking changes.) - // - // Note: this functionality is not currently available in the official - // protobuf release, and it is not used for type URLs beginning with - // type.googleapis.com. - // - // Schemes other than `http`, `https` (or the empty scheme) might be - // used with implementation specific semantics. - // - string type_url = 1; - - // Must be a valid serialized protocol buffer of the above specified type. - bytes value = 2; -} diff --git a/vendor/github.com/golang/protobuf/ptypes/doc.go b/vendor/github.com/golang/protobuf/ptypes/doc.go index c0d595da7ab..fb9edd5c627 100644 --- a/vendor/github.com/golang/protobuf/ptypes/doc.go +++ b/vendor/github.com/golang/protobuf/ptypes/doc.go @@ -1,35 +1,6 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. -/* -Package ptypes contains code for interacting with well-known types. -*/ +// Package ptypes provides functionality for interacting with well-known types. package ptypes diff --git a/vendor/github.com/golang/protobuf/ptypes/duration.go b/vendor/github.com/golang/protobuf/ptypes/duration.go index 26d1ca2fb58..6110ae8a41d 100644 --- a/vendor/github.com/golang/protobuf/ptypes/duration.go +++ b/vendor/github.com/golang/protobuf/ptypes/duration.go @@ -1,102 +1,72 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. package ptypes -// This file implements conversions between google.protobuf.Duration -// and time.Duration. - import ( "errors" "fmt" "time" - durpb "github.com/golang/protobuf/ptypes/duration" + durationpb "github.com/golang/protobuf/ptypes/duration" ) +// Range of google.protobuf.Duration as specified in duration.proto. +// This is about 10,000 years in seconds. const ( - // Range of a durpb.Duration in seconds, as specified in - // google/protobuf/duration.proto. This is about 10,000 years in seconds. maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60) minSeconds = -maxSeconds ) -// validateDuration determines whether the durpb.Duration is valid according to the -// definition in google/protobuf/duration.proto. A valid durpb.Duration -// may still be too large to fit into a time.Duration (the range of durpb.Duration -// is about 10,000 years, and the range of time.Duration is about 290). -func validateDuration(d *durpb.Duration) error { - if d == nil { - return errors.New("duration: nil Duration") - } - if d.Seconds < minSeconds || d.Seconds > maxSeconds { - return fmt.Errorf("duration: %v: seconds out of range", d) - } - if d.Nanos <= -1e9 || d.Nanos >= 1e9 { - return fmt.Errorf("duration: %v: nanos out of range", d) - } - // Seconds and Nanos must have the same sign, unless d.Nanos is zero. - if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) { - return fmt.Errorf("duration: %v: seconds and nanos have different signs", d) - } - return nil -} - -// Duration converts a durpb.Duration to a time.Duration. Duration -// returns an error if the durpb.Duration is invalid or is too large to be -// represented in a time.Duration. -func Duration(p *durpb.Duration) (time.Duration, error) { - if err := validateDuration(p); err != nil { +// Duration converts a durationpb.Duration to a time.Duration. +// Duration returns an error if dur is invalid or overflows a time.Duration. +func Duration(dur *durationpb.Duration) (time.Duration, error) { + if err := validateDuration(dur); err != nil { return 0, err } - d := time.Duration(p.Seconds) * time.Second - if int64(d/time.Second) != p.Seconds { - return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) + d := time.Duration(dur.Seconds) * time.Second + if int64(d/time.Second) != dur.Seconds { + return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur) } - if p.Nanos != 0 { - d += time.Duration(p.Nanos) * time.Nanosecond - if (d < 0) != (p.Nanos < 0) { - return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) + if dur.Nanos != 0 { + d += time.Duration(dur.Nanos) * time.Nanosecond + if (d < 0) != (dur.Nanos < 0) { + return 0, fmt.Errorf("duration: %v is out of range for time.Duration", dur) } } return d, nil } -// DurationProto converts a time.Duration to a durpb.Duration. -func DurationProto(d time.Duration) *durpb.Duration { +// DurationProto converts a time.Duration to a durationpb.Duration. +func DurationProto(d time.Duration) *durationpb.Duration { nanos := d.Nanoseconds() secs := nanos / 1e9 nanos -= secs * 1e9 - return &durpb.Duration{ - Seconds: secs, + return &durationpb.Duration{ + Seconds: int64(secs), Nanos: int32(nanos), } } + +// validateDuration determines whether the durationpb.Duration is valid +// according to the definition in google/protobuf/duration.proto. +// A valid durpb.Duration may still be too large to fit into a time.Duration +// Note that the range of durationpb.Duration is about 10,000 years, +// while the range of time.Duration is about 290 years. +func validateDuration(dur *durationpb.Duration) error { + if dur == nil { + return errors.New("duration: nil Duration") + } + if dur.Seconds < minSeconds || dur.Seconds > maxSeconds { + return fmt.Errorf("duration: %v: seconds out of range", dur) + } + if dur.Nanos <= -1e9 || dur.Nanos >= 1e9 { + return fmt.Errorf("duration: %v: nanos out of range", dur) + } + // Seconds and Nanos must have the same sign, unless d.Nanos is zero. + if (dur.Seconds < 0 && dur.Nanos > 0) || (dur.Seconds > 0 && dur.Nanos < 0) { + return fmt.Errorf("duration: %v: seconds and nanos have different signs", dur) + } + return nil +} diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go index 58b0786990d..d0079ee3ef3 100644 --- a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go +++ b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go @@ -1,163 +1,63 @@ // Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/duration.proto +// source: github.com/golang/protobuf/ptypes/duration/duration.proto package duration import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + durationpb "google.golang.org/protobuf/types/known/durationpb" + reflect "reflect" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +// Symbols defined in public import of google/protobuf/duration.proto. -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +type Duration = durationpb.Duration -// A Duration represents a signed, fixed-length span of time represented -// as a count of seconds and fractions of seconds at nanosecond -// resolution. It is independent of any calendar and concepts like "day" -// or "month". It is related to Timestamp in that the difference between -// two Timestamp values is a Duration and it can be added or subtracted -// from a Timestamp. Range is approximately +-10,000 years. -// -// # Examples -// -// Example 1: Compute Duration from two Timestamps in pseudo code. -// -// Timestamp start = ...; -// Timestamp end = ...; -// Duration duration = ...; -// -// duration.seconds = end.seconds - start.seconds; -// duration.nanos = end.nanos - start.nanos; -// -// if (duration.seconds < 0 && duration.nanos > 0) { -// duration.seconds += 1; -// duration.nanos -= 1000000000; -// } else if (duration.seconds > 0 && duration.nanos < 0) { -// duration.seconds -= 1; -// duration.nanos += 1000000000; -// } -// -// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. -// -// Timestamp start = ...; -// Duration duration = ...; -// Timestamp end = ...; -// -// end.seconds = start.seconds + duration.seconds; -// end.nanos = start.nanos + duration.nanos; -// -// if (end.nanos < 0) { -// end.seconds -= 1; -// end.nanos += 1000000000; -// } else if (end.nanos >= 1000000000) { -// end.seconds += 1; -// end.nanos -= 1000000000; -// } -// -// Example 3: Compute Duration from datetime.timedelta in Python. -// -// td = datetime.timedelta(days=3, minutes=10) -// duration = Duration() -// duration.FromTimedelta(td) -// -// # JSON Mapping -// -// In JSON format, the Duration type is encoded as a string rather than an -// object, where the string ends in the suffix "s" (indicating seconds) and -// is preceded by the number of seconds, with nanoseconds expressed as -// fractional seconds. For example, 3 seconds with 0 nanoseconds should be -// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should -// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 -// microsecond should be expressed in JSON format as "3.000001s". -// -// -type Duration struct { - // Signed seconds of the span of time. Must be from -315,576,000,000 - // to +315,576,000,000 inclusive. Note: these bounds are computed from: - // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years - Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` - // Signed fractions of a second at nanosecond resolution of the span - // of time. Durations less than one second are represented with a 0 - // `seconds` field and a positive or negative `nanos` field. For durations - // of one second or more, a non-zero value for the `nanos` field must be - // of the same sign as the `seconds` field. Must be from -999,999,999 - // to +999,999,999 inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Duration) Reset() { *m = Duration{} } -func (m *Duration) String() string { return proto.CompactTextString(m) } -func (*Duration) ProtoMessage() {} -func (*Duration) Descriptor() ([]byte, []int) { - return fileDescriptor_23597b2ebd7ac6c5, []int{0} -} - -func (*Duration) XXX_WellKnownType() string { return "Duration" } +var File_github_com_golang_protobuf_ptypes_duration_duration_proto protoreflect.FileDescriptor -func (m *Duration) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Duration.Unmarshal(m, b) -} -func (m *Duration) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Duration.Marshal(b, m, deterministic) -} -func (m *Duration) XXX_Merge(src proto.Message) { - xxx_messageInfo_Duration.Merge(m, src) -} -func (m *Duration) XXX_Size() int { - return xxx_messageInfo_Duration.Size(m) -} -func (m *Duration) XXX_DiscardUnknown() { - xxx_messageInfo_Duration.DiscardUnknown(m) +var file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc = []byte{ + 0x0a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, + 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, + 0x70, 0x65, 0x73, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x64, 0x75, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x75, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x35, 0x5a, 0x33, 0x67, + 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, + 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, + 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } -var xxx_messageInfo_Duration proto.InternalMessageInfo - -func (m *Duration) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 +var file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes = []interface{}{} +var file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name } -func (m *Duration) GetNanos() int32 { - if m != nil { - return m.Nanos +func init() { file_github_com_golang_protobuf_ptypes_duration_duration_proto_init() } +func file_github_com_golang_protobuf_ptypes_duration_duration_proto_init() { + if File_github_com_golang_protobuf_ptypes_duration_duration_proto != nil { + return } - return 0 -} - -func init() { - proto.RegisterType((*Duration)(nil), "google.protobuf.Duration") -} - -func init() { - proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor_23597b2ebd7ac6c5) -} - -var fileDescriptor_23597b2ebd7ac6c5 = []byte{ - // 190 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a, - 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0x56, - 0x5c, 0x1c, 0x2e, 0x50, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0xc9, 0xf9, 0x79, 0x29, 0xc5, - 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x41, 0x30, 0xae, 0x90, 0x08, 0x17, 0x6b, 0x5e, 0x62, 0x5e, - 0x7e, 0xb1, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x84, 0xe3, 0x54, 0xc3, 0x25, 0x9c, 0x9c, - 0x9f, 0xab, 0x87, 0x66, 0xa4, 0x13, 0x2f, 0xcc, 0xc0, 0x00, 0x90, 0x48, 0x00, 0x63, 0x94, 0x56, - 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e, - 0x3a, 0xc2, 0x7d, 0x05, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x70, 0x67, 0xfe, 0x60, 0x64, 0x5c, 0xc4, - 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78, - 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63, - 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x30, 0xff, 0xf3, 0x00, 0x00, 0x00, + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc, + NumEnums: 0, + NumMessages: 0, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes, + DependencyIndexes: file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs, + }.Build() + File_github_com_golang_protobuf_ptypes_duration_duration_proto = out.File + file_github_com_golang_protobuf_ptypes_duration_duration_proto_rawDesc = nil + file_github_com_golang_protobuf_ptypes_duration_duration_proto_goTypes = nil + file_github_com_golang_protobuf_ptypes_duration_duration_proto_depIdxs = nil } diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto b/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto deleted file mode 100644 index 99cb102c353..00000000000 --- a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto +++ /dev/null @@ -1,116 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "github.com/golang/protobuf/ptypes/duration"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "DurationProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// A Duration represents a signed, fixed-length span of time represented -// as a count of seconds and fractions of seconds at nanosecond -// resolution. It is independent of any calendar and concepts like "day" -// or "month". It is related to Timestamp in that the difference between -// two Timestamp values is a Duration and it can be added or subtracted -// from a Timestamp. Range is approximately +-10,000 years. -// -// # Examples -// -// Example 1: Compute Duration from two Timestamps in pseudo code. -// -// Timestamp start = ...; -// Timestamp end = ...; -// Duration duration = ...; -// -// duration.seconds = end.seconds - start.seconds; -// duration.nanos = end.nanos - start.nanos; -// -// if (duration.seconds < 0 && duration.nanos > 0) { -// duration.seconds += 1; -// duration.nanos -= 1000000000; -// } else if (duration.seconds > 0 && duration.nanos < 0) { -// duration.seconds -= 1; -// duration.nanos += 1000000000; -// } -// -// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. -// -// Timestamp start = ...; -// Duration duration = ...; -// Timestamp end = ...; -// -// end.seconds = start.seconds + duration.seconds; -// end.nanos = start.nanos + duration.nanos; -// -// if (end.nanos < 0) { -// end.seconds -= 1; -// end.nanos += 1000000000; -// } else if (end.nanos >= 1000000000) { -// end.seconds += 1; -// end.nanos -= 1000000000; -// } -// -// Example 3: Compute Duration from datetime.timedelta in Python. -// -// td = datetime.timedelta(days=3, minutes=10) -// duration = Duration() -// duration.FromTimedelta(td) -// -// # JSON Mapping -// -// In JSON format, the Duration type is encoded as a string rather than an -// object, where the string ends in the suffix "s" (indicating seconds) and -// is preceded by the number of seconds, with nanoseconds expressed as -// fractional seconds. For example, 3 seconds with 0 nanoseconds should be -// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should -// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 -// microsecond should be expressed in JSON format as "3.000001s". -// -// -message Duration { - // Signed seconds of the span of time. Must be from -315,576,000,000 - // to +315,576,000,000 inclusive. Note: these bounds are computed from: - // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years - int64 seconds = 1; - - // Signed fractions of a second at nanosecond resolution of the span - // of time. Durations less than one second are represented with a 0 - // `seconds` field and a positive or negative `nanos` field. For durations - // of one second or more, a non-zero value for the `nanos` field must be - // of the same sign as the `seconds` field. Must be from -999,999,999 - // to +999,999,999 inclusive. - int32 nanos = 2; -} diff --git a/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go b/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go new file mode 100644 index 00000000000..16686a65523 --- /dev/null +++ b/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go @@ -0,0 +1,62 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: github.com/golang/protobuf/ptypes/empty/empty.proto + +package empty + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + emptypb "google.golang.org/protobuf/types/known/emptypb" + reflect "reflect" +) + +// Symbols defined in public import of google/protobuf/empty.proto. + +type Empty = emptypb.Empty + +var File_github_com_golang_protobuf_ptypes_empty_empty_proto protoreflect.FileDescriptor + +var file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc = []byte{ + 0x0a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, + 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, + 0x70, 0x65, 0x73, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x42, 0x2f, 0x5a, 0x2d, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, + 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x3b, 0x65, 0x6d, + 0x70, 0x74, 0x79, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes = []interface{}{} +var file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_github_com_golang_protobuf_ptypes_empty_empty_proto_init() } +func file_github_com_golang_protobuf_ptypes_empty_empty_proto_init() { + if File_github_com_golang_protobuf_ptypes_empty_empty_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc, + NumEnums: 0, + NumMessages: 0, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes, + DependencyIndexes: file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs, + }.Build() + File_github_com_golang_protobuf_ptypes_empty_empty_proto = out.File + file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc = nil + file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes = nil + file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs = nil +} diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp.go b/vendor/github.com/golang/protobuf/ptypes/timestamp.go index 8da0df01acd..026d0d49155 100644 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp.go +++ b/vendor/github.com/golang/protobuf/ptypes/timestamp.go @@ -1,46 +1,18 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. package ptypes -// This file implements operations on google.protobuf.Timestamp. - import ( "errors" "fmt" "time" - tspb "github.com/golang/protobuf/ptypes/timestamp" + timestamppb "github.com/golang/protobuf/ptypes/timestamp" ) +// Range of google.protobuf.Duration as specified in timestamp.proto. const ( // Seconds field of the earliest valid Timestamp. // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). @@ -50,44 +22,18 @@ const ( maxValidSeconds = 253402300800 ) -// validateTimestamp determines whether a Timestamp is valid. -// A valid timestamp represents a time in the range -// [0001-01-01, 10000-01-01) and has a Nanos field -// in the range [0, 1e9). -// -// If the Timestamp is valid, validateTimestamp returns nil. -// Otherwise, it returns an error that describes -// the problem. -// -// Every valid Timestamp can be represented by a time.Time, but the converse is not true. -func validateTimestamp(ts *tspb.Timestamp) error { - if ts == nil { - return errors.New("timestamp: nil Timestamp") - } - if ts.Seconds < minValidSeconds { - return fmt.Errorf("timestamp: %v before 0001-01-01", ts) - } - if ts.Seconds >= maxValidSeconds { - return fmt.Errorf("timestamp: %v after 10000-01-01", ts) - } - if ts.Nanos < 0 || ts.Nanos >= 1e9 { - return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts) - } - return nil -} - -// Timestamp converts a google.protobuf.Timestamp proto to a time.Time. +// Timestamp converts a timestamppb.Timestamp to a time.Time. // It returns an error if the argument is invalid. // -// Unlike most Go functions, if Timestamp returns an error, the first return value -// is not the zero time.Time. Instead, it is the value obtained from the +// Unlike most Go functions, if Timestamp returns an error, the first return +// value is not the zero time.Time. Instead, it is the value obtained from the // time.Unix function when passed the contents of the Timestamp, in the UTC // locale. This may or may not be a meaningful time; many invalid Timestamps // do map to valid time.Times. // // A nil Timestamp returns an error. The first return value in that case is // undefined. -func Timestamp(ts *tspb.Timestamp) (time.Time, error) { +func Timestamp(ts *timestamppb.Timestamp) (time.Time, error) { // Don't return the zero value on error, because corresponds to a valid // timestamp. Instead return whatever time.Unix gives us. var t time.Time @@ -100,7 +46,7 @@ func Timestamp(ts *tspb.Timestamp) (time.Time, error) { } // TimestampNow returns a google.protobuf.Timestamp for the current time. -func TimestampNow() *tspb.Timestamp { +func TimestampNow() *timestamppb.Timestamp { ts, err := TimestampProto(time.Now()) if err != nil { panic("ptypes: time.Now() out of Timestamp range") @@ -110,8 +56,8 @@ func TimestampNow() *tspb.Timestamp { // TimestampProto converts the time.Time to a google.protobuf.Timestamp proto. // It returns an error if the resulting Timestamp is invalid. -func TimestampProto(t time.Time) (*tspb.Timestamp, error) { - ts := &tspb.Timestamp{ +func TimestampProto(t time.Time) (*timestamppb.Timestamp, error) { + ts := ×tamppb.Timestamp{ Seconds: t.Unix(), Nanos: int32(t.Nanosecond()), } @@ -121,12 +67,37 @@ func TimestampProto(t time.Time) (*tspb.Timestamp, error) { return ts, nil } -// TimestampString returns the RFC 3339 string for valid Timestamps. For invalid -// Timestamps, it returns an error message in parentheses. -func TimestampString(ts *tspb.Timestamp) string { +// TimestampString returns the RFC 3339 string for valid Timestamps. +// For invalid Timestamps, it returns an error message in parentheses. +func TimestampString(ts *timestamppb.Timestamp) string { t, err := Timestamp(ts) if err != nil { return fmt.Sprintf("(%v)", err) } return t.Format(time.RFC3339Nano) } + +// validateTimestamp determines whether a Timestamp is valid. +// A valid timestamp represents a time in the range [0001-01-01, 10000-01-01) +// and has a Nanos field in the range [0, 1e9). +// +// If the Timestamp is valid, validateTimestamp returns nil. +// Otherwise, it returns an error that describes the problem. +// +// Every valid Timestamp can be represented by a time.Time, +// but the converse is not true. +func validateTimestamp(ts *timestamppb.Timestamp) error { + if ts == nil { + return errors.New("timestamp: nil Timestamp") + } + if ts.Seconds < minValidSeconds { + return fmt.Errorf("timestamp: %v before 0001-01-01", ts) + } + if ts.Seconds >= maxValidSeconds { + return fmt.Errorf("timestamp: %v after 10000-01-01", ts) + } + if ts.Nanos < 0 || ts.Nanos >= 1e9 { + return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts) + } + return nil +} diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go index 7a3b1e40e29..a76f8076009 100644 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go +++ b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go @@ -1,185 +1,64 @@ // Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/timestamp.proto +// source: github.com/golang/protobuf/ptypes/timestamp/timestamp.proto package timestamp import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + reflect "reflect" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +// Symbols defined in public import of google/protobuf/timestamp.proto. -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +type Timestamp = timestamppb.Timestamp -// A Timestamp represents a point in time independent of any time zone or local -// calendar, encoded as a count of seconds and fractions of seconds at -// nanosecond resolution. The count is relative to an epoch at UTC midnight on -// January 1, 1970, in the proleptic Gregorian calendar which extends the -// Gregorian calendar backwards to year one. -// -// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap -// second table is needed for interpretation, using a [24-hour linear -// smear](https://developers.google.com/time/smear). -// -// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By -// restricting to that range, we ensure that we can convert to and from [RFC -// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. -// -// # Examples -// -// Example 1: Compute Timestamp from POSIX `time()`. -// -// Timestamp timestamp; -// timestamp.set_seconds(time(NULL)); -// timestamp.set_nanos(0); -// -// Example 2: Compute Timestamp from POSIX `gettimeofday()`. -// -// struct timeval tv; -// gettimeofday(&tv, NULL); -// -// Timestamp timestamp; -// timestamp.set_seconds(tv.tv_sec); -// timestamp.set_nanos(tv.tv_usec * 1000); -// -// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. -// -// FILETIME ft; -// GetSystemTimeAsFileTime(&ft); -// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; -// -// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z -// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. -// Timestamp timestamp; -// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); -// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); -// -// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. -// -// long millis = System.currentTimeMillis(); -// -// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) -// .setNanos((int) ((millis % 1000) * 1000000)).build(); -// -// -// Example 5: Compute Timestamp from current time in Python. -// -// timestamp = Timestamp() -// timestamp.GetCurrentTime() -// -// # JSON Mapping -// -// In JSON format, the Timestamp type is encoded as a string in the -// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the -// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" -// where {year} is always expressed using four digits while {month}, {day}, -// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional -// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), -// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone -// is required. A proto3 JSON serializer should always use UTC (as indicated by -// "Z") when printing the Timestamp type and a proto3 JSON parser should be -// able to accept both UTC and other timezones (as indicated by an offset). -// -// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past -// 01:30 UTC on January 15, 2017. -// -// In JavaScript, one can convert a Date object to this format using the -// standard -// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) -// method. In Python, a standard `datetime.datetime` object can be converted -// to this format using -// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with -// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use -// the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D -// ) to obtain a formatter capable of generating timestamps in this format. -// -// -type Timestamp struct { - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Timestamp) Reset() { *m = Timestamp{} } -func (m *Timestamp) String() string { return proto.CompactTextString(m) } -func (*Timestamp) ProtoMessage() {} -func (*Timestamp) Descriptor() ([]byte, []int) { - return fileDescriptor_292007bbfe81227e, []int{0} -} - -func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" } +var File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto protoreflect.FileDescriptor -func (m *Timestamp) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Timestamp.Unmarshal(m, b) -} -func (m *Timestamp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Timestamp.Marshal(b, m, deterministic) -} -func (m *Timestamp) XXX_Merge(src proto.Message) { - xxx_messageInfo_Timestamp.Merge(m, src) -} -func (m *Timestamp) XXX_Size() int { - return xxx_messageInfo_Timestamp.Size(m) -} -func (m *Timestamp) XXX_DiscardUnknown() { - xxx_messageInfo_Timestamp.DiscardUnknown(m) +var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc = []byte{ + 0x0a, 0x3b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, + 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, + 0x70, 0x65, 0x73, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2f, 0x74, 0x69, + 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, + 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x42, 0x37, + 0x5a, 0x35, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, + 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, + 0x70, 0x65, 0x73, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x3b, 0x74, 0x69, + 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x33, } -var xxx_messageInfo_Timestamp proto.InternalMessageInfo - -func (m *Timestamp) GetSeconds() int64 { - if m != nil { - return m.Seconds - } - return 0 +var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes = []interface{}{} +var file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name } -func (m *Timestamp) GetNanos() int32 { - if m != nil { - return m.Nanos +func init() { file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_init() } +func file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_init() { + if File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto != nil { + return } - return 0 -} - -func init() { - proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp") -} - -func init() { - proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor_292007bbfe81227e) -} - -var fileDescriptor_292007bbfe81227e = []byte{ - // 191 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d, - 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x03, 0x0b, 0x09, 0xf1, 0x43, 0x14, 0xe8, 0xc1, 0x14, 0x28, - 0x59, 0x73, 0x71, 0x86, 0xc0, 0xd4, 0x08, 0x49, 0x70, 0xb1, 0x17, 0xa7, 0x26, 0xe7, 0xe7, 0xa5, - 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x22, 0x5c, 0xac, 0x79, 0x89, - 0x79, 0xf9, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x53, 0x1d, 0x97, 0x70, - 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0x99, 0x4e, 0x7c, 0x70, 0x13, 0x03, 0x40, 0x42, 0x01, 0x8c, 0x51, - 0xda, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89, - 0x79, 0xe9, 0x08, 0x27, 0x16, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x23, 0x5c, 0xfa, 0x83, 0x91, 0x71, - 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xc9, 0x01, 0x50, 0xb5, 0x7a, - 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x3d, 0x49, 0x6c, 0x60, 0x43, - 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x77, 0x4a, 0x07, 0xf7, 0x00, 0x00, 0x00, + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc, + NumEnums: 0, + NumMessages: 0, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes, + DependencyIndexes: file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs, + }.Build() + File_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto = out.File + file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_rawDesc = nil + file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_goTypes = nil + file_github_com_golang_protobuf_ptypes_timestamp_timestamp_proto_depIdxs = nil } diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto deleted file mode 100644 index cd357864a9e..00000000000 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto +++ /dev/null @@ -1,138 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option cc_enable_arenas = true; -option go_package = "github.com/golang/protobuf/ptypes/timestamp"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "TimestampProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// A Timestamp represents a point in time independent of any time zone or local -// calendar, encoded as a count of seconds and fractions of seconds at -// nanosecond resolution. The count is relative to an epoch at UTC midnight on -// January 1, 1970, in the proleptic Gregorian calendar which extends the -// Gregorian calendar backwards to year one. -// -// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap -// second table is needed for interpretation, using a [24-hour linear -// smear](https://developers.google.com/time/smear). -// -// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By -// restricting to that range, we ensure that we can convert to and from [RFC -// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. -// -// # Examples -// -// Example 1: Compute Timestamp from POSIX `time()`. -// -// Timestamp timestamp; -// timestamp.set_seconds(time(NULL)); -// timestamp.set_nanos(0); -// -// Example 2: Compute Timestamp from POSIX `gettimeofday()`. -// -// struct timeval tv; -// gettimeofday(&tv, NULL); -// -// Timestamp timestamp; -// timestamp.set_seconds(tv.tv_sec); -// timestamp.set_nanos(tv.tv_usec * 1000); -// -// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. -// -// FILETIME ft; -// GetSystemTimeAsFileTime(&ft); -// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; -// -// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z -// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. -// Timestamp timestamp; -// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); -// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); -// -// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. -// -// long millis = System.currentTimeMillis(); -// -// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) -// .setNanos((int) ((millis % 1000) * 1000000)).build(); -// -// -// Example 5: Compute Timestamp from current time in Python. -// -// timestamp = Timestamp() -// timestamp.GetCurrentTime() -// -// # JSON Mapping -// -// In JSON format, the Timestamp type is encoded as a string in the -// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the -// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" -// where {year} is always expressed using four digits while {month}, {day}, -// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional -// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), -// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone -// is required. A proto3 JSON serializer should always use UTC (as indicated by -// "Z") when printing the Timestamp type and a proto3 JSON parser should be -// able to accept both UTC and other timezones (as indicated by an offset). -// -// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past -// 01:30 UTC on January 15, 2017. -// -// In JavaScript, one can convert a Date object to this format using the -// standard -// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) -// method. In Python, a standard `datetime.datetime` object can be converted -// to this format using -// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with -// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use -// the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D -// ) to obtain a formatter capable of generating timestamps in this format. -// -// -message Timestamp { - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - int64 seconds = 1; - - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - int32 nanos = 2; -} diff --git a/vendor/github.com/golang/snappy/.gitignore b/vendor/github.com/golang/snappy/.gitignore deleted file mode 100644 index 042091d9b3b..00000000000 --- a/vendor/github.com/golang/snappy/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -cmd/snappytool/snappytool -testdata/bench - -# These explicitly listed benchmark data files are for an obsolete version of -# snappy_test.go. -testdata/alice29.txt -testdata/asyoulik.txt -testdata/fireworks.jpeg -testdata/geo.protodata -testdata/html -testdata/html_x_4 -testdata/kppkn.gtb -testdata/lcet10.txt -testdata/paper-100k.pdf -testdata/plrabn12.txt -testdata/urls.10K diff --git a/vendor/github.com/golang/snappy/AUTHORS b/vendor/github.com/golang/snappy/AUTHORS deleted file mode 100644 index bcfa19520af..00000000000 --- a/vendor/github.com/golang/snappy/AUTHORS +++ /dev/null @@ -1,15 +0,0 @@ -# This is the official list of Snappy-Go authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. - -# Names should be added to this file as -# Name or Organization -# The email address is not required for organizations. - -# Please keep the list sorted. - -Damian Gryski -Google Inc. -Jan Mercl <0xjnml@gmail.com> -Rodolfo Carvalho -Sebastien Binet diff --git a/vendor/github.com/golang/snappy/CONTRIBUTORS b/vendor/github.com/golang/snappy/CONTRIBUTORS deleted file mode 100644 index 931ae31606f..00000000000 --- a/vendor/github.com/golang/snappy/CONTRIBUTORS +++ /dev/null @@ -1,37 +0,0 @@ -# This is the official list of people who can contribute -# (and typically have contributed) code to the Snappy-Go repository. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# The submission process automatically checks to make sure -# that people submitting code are listed in this file (by email address). -# -# Names should be added to this file only after verifying that -# the individual or the individual's organization has agreed to -# the appropriate Contributor License Agreement, found here: -# -# http://code.google.com/legal/individual-cla-v1.0.html -# http://code.google.com/legal/corporate-cla-v1.0.html -# -# The agreement for individuals can be filled out on the web. -# -# When adding J Random Contributor's name to this file, -# either J's name or J's organization's name should be -# added to the AUTHORS file, depending on whether the -# individual or corporate CLA was used. - -# Names should be added to this file like so: -# Name - -# Please keep the list sorted. - -Damian Gryski -Jan Mercl <0xjnml@gmail.com> -Kai Backman -Marc-Antoine Ruel -Nigel Tao -Rob Pike -Rodolfo Carvalho -Russ Cox -Sebastien Binet diff --git a/vendor/github.com/golang/snappy/LICENSE b/vendor/github.com/golang/snappy/LICENSE deleted file mode 100644 index 6050c10f4c8..00000000000 --- a/vendor/github.com/golang/snappy/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2011 The Snappy-Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/golang/snappy/README b/vendor/github.com/golang/snappy/README deleted file mode 100644 index cea12879a0e..00000000000 --- a/vendor/github.com/golang/snappy/README +++ /dev/null @@ -1,107 +0,0 @@ -The Snappy compression format in the Go programming language. - -To download and install from source: -$ go get github.com/golang/snappy - -Unless otherwise noted, the Snappy-Go source files are distributed -under the BSD-style license found in the LICENSE file. - - - -Benchmarks. - -The golang/snappy benchmarks include compressing (Z) and decompressing (U) ten -or so files, the same set used by the C++ Snappy code (github.com/google/snappy -and note the "google", not "golang"). On an "Intel(R) Core(TM) i7-3770 CPU @ -3.40GHz", Go's GOARCH=amd64 numbers as of 2016-05-29: - -"go test -test.bench=." - -_UFlat0-8 2.19GB/s ± 0% html -_UFlat1-8 1.41GB/s ± 0% urls -_UFlat2-8 23.5GB/s ± 2% jpg -_UFlat3-8 1.91GB/s ± 0% jpg_200 -_UFlat4-8 14.0GB/s ± 1% pdf -_UFlat5-8 1.97GB/s ± 0% html4 -_UFlat6-8 814MB/s ± 0% txt1 -_UFlat7-8 785MB/s ± 0% txt2 -_UFlat8-8 857MB/s ± 0% txt3 -_UFlat9-8 719MB/s ± 1% txt4 -_UFlat10-8 2.84GB/s ± 0% pb -_UFlat11-8 1.05GB/s ± 0% gaviota - -_ZFlat0-8 1.04GB/s ± 0% html -_ZFlat1-8 534MB/s ± 0% urls -_ZFlat2-8 15.7GB/s ± 1% jpg -_ZFlat3-8 740MB/s ± 3% jpg_200 -_ZFlat4-8 9.20GB/s ± 1% pdf -_ZFlat5-8 991MB/s ± 0% html4 -_ZFlat6-8 379MB/s ± 0% txt1 -_ZFlat7-8 352MB/s ± 0% txt2 -_ZFlat8-8 396MB/s ± 1% txt3 -_ZFlat9-8 327MB/s ± 1% txt4 -_ZFlat10-8 1.33GB/s ± 1% pb -_ZFlat11-8 605MB/s ± 1% gaviota - - - -"go test -test.bench=. -tags=noasm" - -_UFlat0-8 621MB/s ± 2% html -_UFlat1-8 494MB/s ± 1% urls -_UFlat2-8 23.2GB/s ± 1% jpg -_UFlat3-8 1.12GB/s ± 1% jpg_200 -_UFlat4-8 4.35GB/s ± 1% pdf -_UFlat5-8 609MB/s ± 0% html4 -_UFlat6-8 296MB/s ± 0% txt1 -_UFlat7-8 288MB/s ± 0% txt2 -_UFlat8-8 309MB/s ± 1% txt3 -_UFlat9-8 280MB/s ± 1% txt4 -_UFlat10-8 753MB/s ± 0% pb -_UFlat11-8 400MB/s ± 0% gaviota - -_ZFlat0-8 409MB/s ± 1% html -_ZFlat1-8 250MB/s ± 1% urls -_ZFlat2-8 12.3GB/s ± 1% jpg -_ZFlat3-8 132MB/s ± 0% jpg_200 -_ZFlat4-8 2.92GB/s ± 0% pdf -_ZFlat5-8 405MB/s ± 1% html4 -_ZFlat6-8 179MB/s ± 1% txt1 -_ZFlat7-8 170MB/s ± 1% txt2 -_ZFlat8-8 189MB/s ± 1% txt3 -_ZFlat9-8 164MB/s ± 1% txt4 -_ZFlat10-8 479MB/s ± 1% pb -_ZFlat11-8 270MB/s ± 1% gaviota - - - -For comparison (Go's encoded output is byte-for-byte identical to C++'s), here -are the numbers from C++ Snappy's - -make CXXFLAGS="-O2 -DNDEBUG -g" clean snappy_unittest.log && cat snappy_unittest.log - -BM_UFlat/0 2.4GB/s html -BM_UFlat/1 1.4GB/s urls -BM_UFlat/2 21.8GB/s jpg -BM_UFlat/3 1.5GB/s jpg_200 -BM_UFlat/4 13.3GB/s pdf -BM_UFlat/5 2.1GB/s html4 -BM_UFlat/6 1.0GB/s txt1 -BM_UFlat/7 959.4MB/s txt2 -BM_UFlat/8 1.0GB/s txt3 -BM_UFlat/9 864.5MB/s txt4 -BM_UFlat/10 2.9GB/s pb -BM_UFlat/11 1.2GB/s gaviota - -BM_ZFlat/0 944.3MB/s html (22.31 %) -BM_ZFlat/1 501.6MB/s urls (47.78 %) -BM_ZFlat/2 14.3GB/s jpg (99.95 %) -BM_ZFlat/3 538.3MB/s jpg_200 (73.00 %) -BM_ZFlat/4 8.3GB/s pdf (83.30 %) -BM_ZFlat/5 903.5MB/s html4 (22.52 %) -BM_ZFlat/6 336.0MB/s txt1 (57.88 %) -BM_ZFlat/7 312.3MB/s txt2 (61.91 %) -BM_ZFlat/8 353.1MB/s txt3 (54.99 %) -BM_ZFlat/9 289.9MB/s txt4 (66.26 %) -BM_ZFlat/10 1.2GB/s pb (19.68 %) -BM_ZFlat/11 527.4MB/s gaviota (37.72 %) diff --git a/vendor/github.com/golang/snappy/decode.go b/vendor/github.com/golang/snappy/decode.go deleted file mode 100644 index 72efb0353dd..00000000000 --- a/vendor/github.com/golang/snappy/decode.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package snappy - -import ( - "encoding/binary" - "errors" - "io" -) - -var ( - // ErrCorrupt reports that the input is invalid. - ErrCorrupt = errors.New("snappy: corrupt input") - // ErrTooLarge reports that the uncompressed length is too large. - ErrTooLarge = errors.New("snappy: decoded block is too large") - // ErrUnsupported reports that the input isn't supported. - ErrUnsupported = errors.New("snappy: unsupported input") - - errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length") -) - -// DecodedLen returns the length of the decoded block. -func DecodedLen(src []byte) (int, error) { - v, _, err := decodedLen(src) - return v, err -} - -// decodedLen returns the length of the decoded block and the number of bytes -// that the length header occupied. -func decodedLen(src []byte) (blockLen, headerLen int, err error) { - v, n := binary.Uvarint(src) - if n <= 0 || v > 0xffffffff { - return 0, 0, ErrCorrupt - } - - const wordSize = 32 << (^uint(0) >> 32 & 1) - if wordSize == 32 && v > 0x7fffffff { - return 0, 0, ErrTooLarge - } - return int(v), n, nil -} - -const ( - decodeErrCodeCorrupt = 1 - decodeErrCodeUnsupportedLiteralLength = 2 -) - -// Decode returns the decoded form of src. The returned slice may be a sub- -// slice of dst if dst was large enough to hold the entire decoded block. -// Otherwise, a newly allocated slice will be returned. -// -// The dst and src must not overlap. It is valid to pass a nil dst. -func Decode(dst, src []byte) ([]byte, error) { - dLen, s, err := decodedLen(src) - if err != nil { - return nil, err - } - if dLen <= len(dst) { - dst = dst[:dLen] - } else { - dst = make([]byte, dLen) - } - switch decode(dst, src[s:]) { - case 0: - return dst, nil - case decodeErrCodeUnsupportedLiteralLength: - return nil, errUnsupportedLiteralLength - } - return nil, ErrCorrupt -} - -// NewReader returns a new Reader that decompresses from r, using the framing -// format described at -// https://github.com/google/snappy/blob/master/framing_format.txt -func NewReader(r io.Reader) *Reader { - return &Reader{ - r: r, - decoded: make([]byte, maxBlockSize), - buf: make([]byte, maxEncodedLenOfMaxBlockSize+checksumSize), - } -} - -// Reader is an io.Reader that can read Snappy-compressed bytes. -type Reader struct { - r io.Reader - err error - decoded []byte - buf []byte - // decoded[i:j] contains decoded bytes that have not yet been passed on. - i, j int - readHeader bool -} - -// Reset discards any buffered data, resets all state, and switches the Snappy -// reader to read from r. This permits reusing a Reader rather than allocating -// a new one. -func (r *Reader) Reset(reader io.Reader) { - r.r = reader - r.err = nil - r.i = 0 - r.j = 0 - r.readHeader = false -} - -func (r *Reader) readFull(p []byte, allowEOF bool) (ok bool) { - if _, r.err = io.ReadFull(r.r, p); r.err != nil { - if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) { - r.err = ErrCorrupt - } - return false - } - return true -} - -// Read satisfies the io.Reader interface. -func (r *Reader) Read(p []byte) (int, error) { - if r.err != nil { - return 0, r.err - } - for { - if r.i < r.j { - n := copy(p, r.decoded[r.i:r.j]) - r.i += n - return n, nil - } - if !r.readFull(r.buf[:4], true) { - return 0, r.err - } - chunkType := r.buf[0] - if !r.readHeader { - if chunkType != chunkTypeStreamIdentifier { - r.err = ErrCorrupt - return 0, r.err - } - r.readHeader = true - } - chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16 - if chunkLen > len(r.buf) { - r.err = ErrUnsupported - return 0, r.err - } - - // The chunk types are specified at - // https://github.com/google/snappy/blob/master/framing_format.txt - switch chunkType { - case chunkTypeCompressedData: - // Section 4.2. Compressed data (chunk type 0x00). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return 0, r.err - } - buf := r.buf[:chunkLen] - if !r.readFull(buf, false) { - return 0, r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - buf = buf[checksumSize:] - - n, err := DecodedLen(buf) - if err != nil { - r.err = err - return 0, r.err - } - if n > len(r.decoded) { - r.err = ErrCorrupt - return 0, r.err - } - if _, err := Decode(r.decoded, buf); err != nil { - r.err = err - return 0, r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return 0, r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeUncompressedData: - // Section 4.3. Uncompressed data (chunk type 0x01). - if chunkLen < checksumSize { - r.err = ErrCorrupt - return 0, r.err - } - buf := r.buf[:checksumSize] - if !r.readFull(buf, false) { - return 0, r.err - } - checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24 - // Read directly into r.decoded instead of via r.buf. - n := chunkLen - checksumSize - if n > len(r.decoded) { - r.err = ErrCorrupt - return 0, r.err - } - if !r.readFull(r.decoded[:n], false) { - return 0, r.err - } - if crc(r.decoded[:n]) != checksum { - r.err = ErrCorrupt - return 0, r.err - } - r.i, r.j = 0, n - continue - - case chunkTypeStreamIdentifier: - // Section 4.1. Stream identifier (chunk type 0xff). - if chunkLen != len(magicBody) { - r.err = ErrCorrupt - return 0, r.err - } - if !r.readFull(r.buf[:len(magicBody)], false) { - return 0, r.err - } - for i := 0; i < len(magicBody); i++ { - if r.buf[i] != magicBody[i] { - r.err = ErrCorrupt - return 0, r.err - } - } - continue - } - - if chunkType <= 0x7f { - // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f). - r.err = ErrUnsupported - return 0, r.err - } - // Section 4.4 Padding (chunk type 0xfe). - // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd). - if !r.readFull(r.buf[:chunkLen], false) { - return 0, r.err - } - } -} diff --git a/vendor/github.com/golang/snappy/decode_amd64.go b/vendor/github.com/golang/snappy/decode_amd64.go deleted file mode 100644 index fcd192b849e..00000000000 --- a/vendor/github.com/golang/snappy/decode_amd64.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2016 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine -// +build gc -// +build !noasm - -package snappy - -// decode has the same semantics as in decode_other.go. -// -//go:noescape -func decode(dst, src []byte) int diff --git a/vendor/github.com/golang/snappy/decode_amd64.s b/vendor/github.com/golang/snappy/decode_amd64.s deleted file mode 100644 index e6179f65e35..00000000000 --- a/vendor/github.com/golang/snappy/decode_amd64.s +++ /dev/null @@ -1,490 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine -// +build gc -// +build !noasm - -#include "textflag.h" - -// The asm code generally follows the pure Go code in decode_other.go, except -// where marked with a "!!!". - -// func decode(dst, src []byte) int -// -// All local variables fit into registers. The non-zero stack size is only to -// spill registers and push args when issuing a CALL. The register allocation: -// - AX scratch -// - BX scratch -// - CX length or x -// - DX offset -// - SI &src[s] -// - DI &dst[d] -// + R8 dst_base -// + R9 dst_len -// + R10 dst_base + dst_len -// + R11 src_base -// + R12 src_len -// + R13 src_base + src_len -// - R14 used by doCopy -// - R15 used by doCopy -// -// The registers R8-R13 (marked with a "+") are set at the start of the -// function, and after a CALL returns, and are not otherwise modified. -// -// The d variable is implicitly DI - R8, and len(dst)-d is R10 - DI. -// The s variable is implicitly SI - R11, and len(src)-s is R13 - SI. -TEXT ·decode(SB), NOSPLIT, $48-56 - // Initialize SI, DI and R8-R13. - MOVQ dst_base+0(FP), R8 - MOVQ dst_len+8(FP), R9 - MOVQ R8, DI - MOVQ R8, R10 - ADDQ R9, R10 - MOVQ src_base+24(FP), R11 - MOVQ src_len+32(FP), R12 - MOVQ R11, SI - MOVQ R11, R13 - ADDQ R12, R13 - -loop: - // for s < len(src) - CMPQ SI, R13 - JEQ end - - // CX = uint32(src[s]) - // - // switch src[s] & 0x03 - MOVBLZX (SI), CX - MOVL CX, BX - ANDL $3, BX - CMPL BX, $1 - JAE tagCopy - - // ---------------------------------------- - // The code below handles literal tags. - - // case tagLiteral: - // x := uint32(src[s] >> 2) - // switch - SHRL $2, CX - CMPL CX, $60 - JAE tagLit60Plus - - // case x < 60: - // s++ - INCQ SI - -doLit: - // This is the end of the inner "switch", when we have a literal tag. - // - // We assume that CX == x and x fits in a uint32, where x is the variable - // used in the pure Go decode_other.go code. - - // length = int(x) + 1 - // - // Unlike the pure Go code, we don't need to check if length <= 0 because - // CX can hold 64 bits, so the increment cannot overflow. - INCQ CX - - // Prepare to check if copying length bytes will run past the end of dst or - // src. - // - // AX = len(dst) - d - // BX = len(src) - s - MOVQ R10, AX - SUBQ DI, AX - MOVQ R13, BX - SUBQ SI, BX - - // !!! Try a faster technique for short (16 or fewer bytes) copies. - // - // if length > 16 || len(dst)-d < 16 || len(src)-s < 16 { - // goto callMemmove // Fall back on calling runtime·memmove. - // } - // - // The C++ snappy code calls this TryFastAppend. It also checks len(src)-s - // against 21 instead of 16, because it cannot assume that all of its input - // is contiguous in memory and so it needs to leave enough source bytes to - // read the next tag without refilling buffers, but Go's Decode assumes - // contiguousness (the src argument is a []byte). - CMPQ CX, $16 - JGT callMemmove - CMPQ AX, $16 - JLT callMemmove - CMPQ BX, $16 - JLT callMemmove - - // !!! Implement the copy from src to dst as a 16-byte load and store. - // (Decode's documentation says that dst and src must not overlap.) - // - // This always copies 16 bytes, instead of only length bytes, but that's - // OK. If the input is a valid Snappy encoding then subsequent iterations - // will fix up the overrun. Otherwise, Decode returns a nil []byte (and a - // non-nil error), so the overrun will be ignored. - // - // Note that on amd64, it is legal and cheap to issue unaligned 8-byte or - // 16-byte loads and stores. This technique probably wouldn't be as - // effective on architectures that are fussier about alignment. - MOVOU 0(SI), X0 - MOVOU X0, 0(DI) - - // d += length - // s += length - ADDQ CX, DI - ADDQ CX, SI - JMP loop - -callMemmove: - // if length > len(dst)-d || length > len(src)-s { etc } - CMPQ CX, AX - JGT errCorrupt - CMPQ CX, BX - JGT errCorrupt - - // copy(dst[d:], src[s:s+length]) - // - // This means calling runtime·memmove(&dst[d], &src[s], length), so we push - // DI, SI and CX as arguments. Coincidentally, we also need to spill those - // three registers to the stack, to save local variables across the CALL. - MOVQ DI, 0(SP) - MOVQ SI, 8(SP) - MOVQ CX, 16(SP) - MOVQ DI, 24(SP) - MOVQ SI, 32(SP) - MOVQ CX, 40(SP) - CALL runtime·memmove(SB) - - // Restore local variables: unspill registers from the stack and - // re-calculate R8-R13. - MOVQ 24(SP), DI - MOVQ 32(SP), SI - MOVQ 40(SP), CX - MOVQ dst_base+0(FP), R8 - MOVQ dst_len+8(FP), R9 - MOVQ R8, R10 - ADDQ R9, R10 - MOVQ src_base+24(FP), R11 - MOVQ src_len+32(FP), R12 - MOVQ R11, R13 - ADDQ R12, R13 - - // d += length - // s += length - ADDQ CX, DI - ADDQ CX, SI - JMP loop - -tagLit60Plus: - // !!! This fragment does the - // - // s += x - 58; if uint(s) > uint(len(src)) { etc } - // - // checks. In the asm version, we code it once instead of once per switch case. - ADDQ CX, SI - SUBQ $58, SI - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // case x == 60: - CMPL CX, $61 - JEQ tagLit61 - JA tagLit62Plus - - // x = uint32(src[s-1]) - MOVBLZX -1(SI), CX - JMP doLit - -tagLit61: - // case x == 61: - // x = uint32(src[s-2]) | uint32(src[s-1])<<8 - MOVWLZX -2(SI), CX - JMP doLit - -tagLit62Plus: - CMPL CX, $62 - JA tagLit63 - - // case x == 62: - // x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 - MOVWLZX -3(SI), CX - MOVBLZX -1(SI), BX - SHLL $16, BX - ORL BX, CX - JMP doLit - -tagLit63: - // case x == 63: - // x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - MOVL -4(SI), CX - JMP doLit - -// The code above handles literal tags. -// ---------------------------------------- -// The code below handles copy tags. - -tagCopy4: - // case tagCopy4: - // s += 5 - ADDQ $5, SI - - // if uint(s) > uint(len(src)) { etc } - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // length = 1 + int(src[s-5])>>2 - SHRQ $2, CX - INCQ CX - - // offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) - MOVLQZX -4(SI), DX - JMP doCopy - -tagCopy2: - // case tagCopy2: - // s += 3 - ADDQ $3, SI - - // if uint(s) > uint(len(src)) { etc } - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // length = 1 + int(src[s-3])>>2 - SHRQ $2, CX - INCQ CX - - // offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) - MOVWQZX -2(SI), DX - JMP doCopy - -tagCopy: - // We have a copy tag. We assume that: - // - BX == src[s] & 0x03 - // - CX == src[s] - CMPQ BX, $2 - JEQ tagCopy2 - JA tagCopy4 - - // case tagCopy1: - // s += 2 - ADDQ $2, SI - - // if uint(s) > uint(len(src)) { etc } - MOVQ SI, BX - SUBQ R11, BX - CMPQ BX, R12 - JA errCorrupt - - // offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) - MOVQ CX, DX - ANDQ $0xe0, DX - SHLQ $3, DX - MOVBQZX -1(SI), BX - ORQ BX, DX - - // length = 4 + int(src[s-2])>>2&0x7 - SHRQ $2, CX - ANDQ $7, CX - ADDQ $4, CX - -doCopy: - // This is the end of the outer "switch", when we have a copy tag. - // - // We assume that: - // - CX == length && CX > 0 - // - DX == offset - - // if offset <= 0 { etc } - CMPQ DX, $0 - JLE errCorrupt - - // if d < offset { etc } - MOVQ DI, BX - SUBQ R8, BX - CMPQ BX, DX - JLT errCorrupt - - // if length > len(dst)-d { etc } - MOVQ R10, BX - SUBQ DI, BX - CMPQ CX, BX - JGT errCorrupt - - // forwardCopy(dst[d:d+length], dst[d-offset:]); d += length - // - // Set: - // - R14 = len(dst)-d - // - R15 = &dst[d-offset] - MOVQ R10, R14 - SUBQ DI, R14 - MOVQ DI, R15 - SUBQ DX, R15 - - // !!! Try a faster technique for short (16 or fewer bytes) forward copies. - // - // First, try using two 8-byte load/stores, similar to the doLit technique - // above. Even if dst[d:d+length] and dst[d-offset:] can overlap, this is - // still OK if offset >= 8. Note that this has to be two 8-byte load/stores - // and not one 16-byte load/store, and the first store has to be before the - // second load, due to the overlap if offset is in the range [8, 16). - // - // if length > 16 || offset < 8 || len(dst)-d < 16 { - // goto slowForwardCopy - // } - // copy 16 bytes - // d += length - CMPQ CX, $16 - JGT slowForwardCopy - CMPQ DX, $8 - JLT slowForwardCopy - CMPQ R14, $16 - JLT slowForwardCopy - MOVQ 0(R15), AX - MOVQ AX, 0(DI) - MOVQ 8(R15), BX - MOVQ BX, 8(DI) - ADDQ CX, DI - JMP loop - -slowForwardCopy: - // !!! If the forward copy is longer than 16 bytes, or if offset < 8, we - // can still try 8-byte load stores, provided we can overrun up to 10 extra - // bytes. As above, the overrun will be fixed up by subsequent iterations - // of the outermost loop. - // - // The C++ snappy code calls this technique IncrementalCopyFastPath. Its - // commentary says: - // - // ---- - // - // The main part of this loop is a simple copy of eight bytes at a time - // until we've copied (at least) the requested amount of bytes. However, - // if d and d-offset are less than eight bytes apart (indicating a - // repeating pattern of length < 8), we first need to expand the pattern in - // order to get the correct results. For instance, if the buffer looks like - // this, with the eight-byte and patterns marked as - // intervals: - // - // abxxxxxxxxxxxx - // [------] d-offset - // [------] d - // - // a single eight-byte copy from to will repeat the pattern - // once, after which we can move two bytes without moving : - // - // ababxxxxxxxxxx - // [------] d-offset - // [------] d - // - // and repeat the exercise until the two no longer overlap. - // - // This allows us to do very well in the special case of one single byte - // repeated many times, without taking a big hit for more general cases. - // - // The worst case of extra writing past the end of the match occurs when - // offset == 1 and length == 1; the last copy will read from byte positions - // [0..7] and write to [4..11], whereas it was only supposed to write to - // position 1. Thus, ten excess bytes. - // - // ---- - // - // That "10 byte overrun" worst case is confirmed by Go's - // TestSlowForwardCopyOverrun, which also tests the fixUpSlowForwardCopy - // and finishSlowForwardCopy algorithm. - // - // if length > len(dst)-d-10 { - // goto verySlowForwardCopy - // } - SUBQ $10, R14 - CMPQ CX, R14 - JGT verySlowForwardCopy - -makeOffsetAtLeast8: - // !!! As above, expand the pattern so that offset >= 8 and we can use - // 8-byte load/stores. - // - // for offset < 8 { - // copy 8 bytes from dst[d-offset:] to dst[d:] - // length -= offset - // d += offset - // offset += offset - // // The two previous lines together means that d-offset, and therefore - // // R15, is unchanged. - // } - CMPQ DX, $8 - JGE fixUpSlowForwardCopy - MOVQ (R15), BX - MOVQ BX, (DI) - SUBQ DX, CX - ADDQ DX, DI - ADDQ DX, DX - JMP makeOffsetAtLeast8 - -fixUpSlowForwardCopy: - // !!! Add length (which might be negative now) to d (implied by DI being - // &dst[d]) so that d ends up at the right place when we jump back to the - // top of the loop. Before we do that, though, we save DI to AX so that, if - // length is positive, copying the remaining length bytes will write to the - // right place. - MOVQ DI, AX - ADDQ CX, DI - -finishSlowForwardCopy: - // !!! Repeat 8-byte load/stores until length <= 0. Ending with a negative - // length means that we overrun, but as above, that will be fixed up by - // subsequent iterations of the outermost loop. - CMPQ CX, $0 - JLE loop - MOVQ (R15), BX - MOVQ BX, (AX) - ADDQ $8, R15 - ADDQ $8, AX - SUBQ $8, CX - JMP finishSlowForwardCopy - -verySlowForwardCopy: - // verySlowForwardCopy is a simple implementation of forward copy. In C - // parlance, this is a do/while loop instead of a while loop, since we know - // that length > 0. In Go syntax: - // - // for { - // dst[d] = dst[d - offset] - // d++ - // length-- - // if length == 0 { - // break - // } - // } - MOVB (R15), BX - MOVB BX, (DI) - INCQ R15 - INCQ DI - DECQ CX - JNZ verySlowForwardCopy - JMP loop - -// The code above handles copy tags. -// ---------------------------------------- - -end: - // This is the end of the "for s < len(src)". - // - // if d != len(dst) { etc } - CMPQ DI, R10 - JNE errCorrupt - - // return 0 - MOVQ $0, ret+48(FP) - RET - -errCorrupt: - // return decodeErrCodeCorrupt - MOVQ $1, ret+48(FP) - RET diff --git a/vendor/github.com/golang/snappy/decode_other.go b/vendor/github.com/golang/snappy/decode_other.go deleted file mode 100644 index 8c9f2049bc7..00000000000 --- a/vendor/github.com/golang/snappy/decode_other.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2016 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !amd64 appengine !gc noasm - -package snappy - -// decode writes the decoding of src to dst. It assumes that the varint-encoded -// length of the decompressed bytes has already been read, and that len(dst) -// equals that length. -// -// It returns 0 on success or a decodeErrCodeXxx error code on failure. -func decode(dst, src []byte) int { - var d, s, offset, length int - for s < len(src) { - switch src[s] & 0x03 { - case tagLiteral: - x := uint32(src[s] >> 2) - switch { - case x < 60: - s++ - case x == 60: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-1]) - case x == 61: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-2]) | uint32(src[s-1])<<8 - case x == 62: - s += 4 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16 - case x == 63: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24 - } - length = int(x) + 1 - if length <= 0 { - return decodeErrCodeUnsupportedLiteralLength - } - if length > len(dst)-d || length > len(src)-s { - return decodeErrCodeCorrupt - } - copy(dst[d:], src[s:s+length]) - d += length - s += length - continue - - case tagCopy1: - s += 2 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 4 + int(src[s-2])>>2&0x7 - offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1])) - - case tagCopy2: - s += 3 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 1 + int(src[s-3])>>2 - offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8) - - case tagCopy4: - s += 5 - if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line. - return decodeErrCodeCorrupt - } - length = 1 + int(src[s-5])>>2 - offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24) - } - - if offset <= 0 || d < offset || length > len(dst)-d { - return decodeErrCodeCorrupt - } - // Copy from an earlier sub-slice of dst to a later sub-slice. Unlike - // the built-in copy function, this byte-by-byte copy always runs - // forwards, even if the slices overlap. Conceptually, this is: - // - // d += forwardCopy(dst[d:d+length], dst[d-offset:]) - for end := d + length; d != end; d++ { - dst[d] = dst[d-offset] - } - } - if d != len(dst) { - return decodeErrCodeCorrupt - } - return 0 -} diff --git a/vendor/github.com/golang/snappy/encode.go b/vendor/github.com/golang/snappy/encode.go deleted file mode 100644 index 8d393e904bb..00000000000 --- a/vendor/github.com/golang/snappy/encode.go +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package snappy - -import ( - "encoding/binary" - "errors" - "io" -) - -// Encode returns the encoded form of src. The returned slice may be a sub- -// slice of dst if dst was large enough to hold the entire encoded block. -// Otherwise, a newly allocated slice will be returned. -// -// The dst and src must not overlap. It is valid to pass a nil dst. -func Encode(dst, src []byte) []byte { - if n := MaxEncodedLen(len(src)); n < 0 { - panic(ErrTooLarge) - } else if len(dst) < n { - dst = make([]byte, n) - } - - // The block starts with the varint-encoded length of the decompressed bytes. - d := binary.PutUvarint(dst, uint64(len(src))) - - for len(src) > 0 { - p := src - src = nil - if len(p) > maxBlockSize { - p, src = p[:maxBlockSize], p[maxBlockSize:] - } - if len(p) < minNonLiteralBlockSize { - d += emitLiteral(dst[d:], p) - } else { - d += encodeBlock(dst[d:], p) - } - } - return dst[:d] -} - -// inputMargin is the minimum number of extra input bytes to keep, inside -// encodeBlock's inner loop. On some architectures, this margin lets us -// implement a fast path for emitLiteral, where the copy of short (<= 16 byte) -// literals can be implemented as a single load to and store from a 16-byte -// register. That literal's actual length can be as short as 1 byte, so this -// can copy up to 15 bytes too much, but that's OK as subsequent iterations of -// the encoding loop will fix up the copy overrun, and this inputMargin ensures -// that we don't overrun the dst and src buffers. -const inputMargin = 16 - 1 - -// minNonLiteralBlockSize is the minimum size of the input to encodeBlock that -// could be encoded with a copy tag. This is the minimum with respect to the -// algorithm used by encodeBlock, not a minimum enforced by the file format. -// -// The encoded output must start with at least a 1 byte literal, as there are -// no previous bytes to copy. A minimal (1 byte) copy after that, generated -// from an emitCopy call in encodeBlock's main loop, would require at least -// another inputMargin bytes, for the reason above: we want any emitLiteral -// calls inside encodeBlock's main loop to use the fast path if possible, which -// requires being able to overrun by inputMargin bytes. Thus, -// minNonLiteralBlockSize equals 1 + 1 + inputMargin. -// -// The C++ code doesn't use this exact threshold, but it could, as discussed at -// https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion -// The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an -// optimization. It should not affect the encoded form. This is tested by -// TestSameEncodingAsCppShortCopies. -const minNonLiteralBlockSize = 1 + 1 + inputMargin - -// MaxEncodedLen returns the maximum length of a snappy block, given its -// uncompressed length. -// -// It will return a negative value if srcLen is too large to encode. -func MaxEncodedLen(srcLen int) int { - n := uint64(srcLen) - if n > 0xffffffff { - return -1 - } - // Compressed data can be defined as: - // compressed := item* literal* - // item := literal* copy - // - // The trailing literal sequence has a space blowup of at most 62/60 - // since a literal of length 60 needs one tag byte + one extra byte - // for length information. - // - // Item blowup is trickier to measure. Suppose the "copy" op copies - // 4 bytes of data. Because of a special check in the encoding code, - // we produce a 4-byte copy only if the offset is < 65536. Therefore - // the copy op takes 3 bytes to encode, and this type of item leads - // to at most the 62/60 blowup for representing literals. - // - // Suppose the "copy" op copies 5 bytes of data. If the offset is big - // enough, it will take 5 bytes to encode the copy op. Therefore the - // worst case here is a one-byte literal followed by a five-byte copy. - // That is, 6 bytes of input turn into 7 bytes of "compressed" data. - // - // This last factor dominates the blowup, so the final estimate is: - n = 32 + n + n/6 - if n > 0xffffffff { - return -1 - } - return int(n) -} - -var errClosed = errors.New("snappy: Writer is closed") - -// NewWriter returns a new Writer that compresses to w. -// -// The Writer returned does not buffer writes. There is no need to Flush or -// Close such a Writer. -// -// Deprecated: the Writer returned is not suitable for many small writes, only -// for few large writes. Use NewBufferedWriter instead, which is efficient -// regardless of the frequency and shape of the writes, and remember to Close -// that Writer when done. -func NewWriter(w io.Writer) *Writer { - return &Writer{ - w: w, - obuf: make([]byte, obufLen), - } -} - -// NewBufferedWriter returns a new Writer that compresses to w, using the -// framing format described at -// https://github.com/google/snappy/blob/master/framing_format.txt -// -// The Writer returned buffers writes. Users must call Close to guarantee all -// data has been forwarded to the underlying io.Writer. They may also call -// Flush zero or more times before calling Close. -func NewBufferedWriter(w io.Writer) *Writer { - return &Writer{ - w: w, - ibuf: make([]byte, 0, maxBlockSize), - obuf: make([]byte, obufLen), - } -} - -// Writer is an io.Writer that can write Snappy-compressed bytes. -type Writer struct { - w io.Writer - err error - - // ibuf is a buffer for the incoming (uncompressed) bytes. - // - // Its use is optional. For backwards compatibility, Writers created by the - // NewWriter function have ibuf == nil, do not buffer incoming bytes, and - // therefore do not need to be Flush'ed or Close'd. - ibuf []byte - - // obuf is a buffer for the outgoing (compressed) bytes. - obuf []byte - - // wroteStreamHeader is whether we have written the stream header. - wroteStreamHeader bool -} - -// Reset discards the writer's state and switches the Snappy writer to write to -// w. This permits reusing a Writer rather than allocating a new one. -func (w *Writer) Reset(writer io.Writer) { - w.w = writer - w.err = nil - if w.ibuf != nil { - w.ibuf = w.ibuf[:0] - } - w.wroteStreamHeader = false -} - -// Write satisfies the io.Writer interface. -func (w *Writer) Write(p []byte) (nRet int, errRet error) { - if w.ibuf == nil { - // Do not buffer incoming bytes. This does not perform or compress well - // if the caller of Writer.Write writes many small slices. This - // behavior is therefore deprecated, but still supported for backwards - // compatibility with code that doesn't explicitly Flush or Close. - return w.write(p) - } - - // The remainder of this method is based on bufio.Writer.Write from the - // standard library. - - for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil { - var n int - if len(w.ibuf) == 0 { - // Large write, empty buffer. - // Write directly from p to avoid copy. - n, _ = w.write(p) - } else { - n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) - w.ibuf = w.ibuf[:len(w.ibuf)+n] - w.Flush() - } - nRet += n - p = p[n:] - } - if w.err != nil { - return nRet, w.err - } - n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p) - w.ibuf = w.ibuf[:len(w.ibuf)+n] - nRet += n - return nRet, nil -} - -func (w *Writer) write(p []byte) (nRet int, errRet error) { - if w.err != nil { - return 0, w.err - } - for len(p) > 0 { - obufStart := len(magicChunk) - if !w.wroteStreamHeader { - w.wroteStreamHeader = true - copy(w.obuf, magicChunk) - obufStart = 0 - } - - var uncompressed []byte - if len(p) > maxBlockSize { - uncompressed, p = p[:maxBlockSize], p[maxBlockSize:] - } else { - uncompressed, p = p, nil - } - checksum := crc(uncompressed) - - // Compress the buffer, discarding the result if the improvement - // isn't at least 12.5%. - compressed := Encode(w.obuf[obufHeaderLen:], uncompressed) - chunkType := uint8(chunkTypeCompressedData) - chunkLen := 4 + len(compressed) - obufEnd := obufHeaderLen + len(compressed) - if len(compressed) >= len(uncompressed)-len(uncompressed)/8 { - chunkType = chunkTypeUncompressedData - chunkLen = 4 + len(uncompressed) - obufEnd = obufHeaderLen - } - - // Fill in the per-chunk header that comes before the body. - w.obuf[len(magicChunk)+0] = chunkType - w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0) - w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8) - w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16) - w.obuf[len(magicChunk)+4] = uint8(checksum >> 0) - w.obuf[len(magicChunk)+5] = uint8(checksum >> 8) - w.obuf[len(magicChunk)+6] = uint8(checksum >> 16) - w.obuf[len(magicChunk)+7] = uint8(checksum >> 24) - - if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil { - w.err = err - return nRet, err - } - if chunkType == chunkTypeUncompressedData { - if _, err := w.w.Write(uncompressed); err != nil { - w.err = err - return nRet, err - } - } - nRet += len(uncompressed) - } - return nRet, nil -} - -// Flush flushes the Writer to its underlying io.Writer. -func (w *Writer) Flush() error { - if w.err != nil { - return w.err - } - if len(w.ibuf) == 0 { - return nil - } - w.write(w.ibuf) - w.ibuf = w.ibuf[:0] - return w.err -} - -// Close calls Flush and then closes the Writer. -func (w *Writer) Close() error { - w.Flush() - ret := w.err - if w.err == nil { - w.err = errClosed - } - return ret -} diff --git a/vendor/github.com/golang/snappy/encode_amd64.go b/vendor/github.com/golang/snappy/encode_amd64.go deleted file mode 100644 index 150d91bc8be..00000000000 --- a/vendor/github.com/golang/snappy/encode_amd64.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2016 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine -// +build gc -// +build !noasm - -package snappy - -// emitLiteral has the same semantics as in encode_other.go. -// -//go:noescape -func emitLiteral(dst, lit []byte) int - -// emitCopy has the same semantics as in encode_other.go. -// -//go:noescape -func emitCopy(dst []byte, offset, length int) int - -// extendMatch has the same semantics as in encode_other.go. -// -//go:noescape -func extendMatch(src []byte, i, j int) int - -// encodeBlock has the same semantics as in encode_other.go. -// -//go:noescape -func encodeBlock(dst, src []byte) (d int) diff --git a/vendor/github.com/golang/snappy/encode_amd64.s b/vendor/github.com/golang/snappy/encode_amd64.s deleted file mode 100644 index adfd979fe27..00000000000 --- a/vendor/github.com/golang/snappy/encode_amd64.s +++ /dev/null @@ -1,730 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine -// +build gc -// +build !noasm - -#include "textflag.h" - -// The XXX lines assemble on Go 1.4, 1.5 and 1.7, but not 1.6, due to a -// Go toolchain regression. See https://github.com/golang/go/issues/15426 and -// https://github.com/golang/snappy/issues/29 -// -// As a workaround, the package was built with a known good assembler, and -// those instructions were disassembled by "objdump -d" to yield the -// 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 -// style comments, in AT&T asm syntax. Note that rsp here is a physical -// register, not Go/asm's SP pseudo-register (see https://golang.org/doc/asm). -// The instructions were then encoded as "BYTE $0x.." sequences, which assemble -// fine on Go 1.6. - -// The asm code generally follows the pure Go code in encode_other.go, except -// where marked with a "!!!". - -// ---------------------------------------------------------------------------- - -// func emitLiteral(dst, lit []byte) int -// -// All local variables fit into registers. The register allocation: -// - AX len(lit) -// - BX n -// - DX return value -// - DI &dst[i] -// - R10 &lit[0] -// -// The 24 bytes of stack space is to call runtime·memmove. -// -// The unusual register allocation of local variables, such as R10 for the -// source pointer, matches the allocation used at the call site in encodeBlock, -// which makes it easier to manually inline this function. -TEXT ·emitLiteral(SB), NOSPLIT, $24-56 - MOVQ dst_base+0(FP), DI - MOVQ lit_base+24(FP), R10 - MOVQ lit_len+32(FP), AX - MOVQ AX, DX - MOVL AX, BX - SUBL $1, BX - - CMPL BX, $60 - JLT oneByte - CMPL BX, $256 - JLT twoBytes - -threeBytes: - MOVB $0xf4, 0(DI) - MOVW BX, 1(DI) - ADDQ $3, DI - ADDQ $3, DX - JMP memmove - -twoBytes: - MOVB $0xf0, 0(DI) - MOVB BX, 1(DI) - ADDQ $2, DI - ADDQ $2, DX - JMP memmove - -oneByte: - SHLB $2, BX - MOVB BX, 0(DI) - ADDQ $1, DI - ADDQ $1, DX - -memmove: - MOVQ DX, ret+48(FP) - - // copy(dst[i:], lit) - // - // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push - // DI, R10 and AX as arguments. - MOVQ DI, 0(SP) - MOVQ R10, 8(SP) - MOVQ AX, 16(SP) - CALL runtime·memmove(SB) - RET - -// ---------------------------------------------------------------------------- - -// func emitCopy(dst []byte, offset, length int) int -// -// All local variables fit into registers. The register allocation: -// - AX length -// - SI &dst[0] -// - DI &dst[i] -// - R11 offset -// -// The unusual register allocation of local variables, such as R11 for the -// offset, matches the allocation used at the call site in encodeBlock, which -// makes it easier to manually inline this function. -TEXT ·emitCopy(SB), NOSPLIT, $0-48 - MOVQ dst_base+0(FP), DI - MOVQ DI, SI - MOVQ offset+24(FP), R11 - MOVQ length+32(FP), AX - -loop0: - // for length >= 68 { etc } - CMPL AX, $68 - JLT step1 - - // Emit a length 64 copy, encoded as 3 bytes. - MOVB $0xfe, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $64, AX - JMP loop0 - -step1: - // if length > 64 { etc } - CMPL AX, $64 - JLE step2 - - // Emit a length 60 copy, encoded as 3 bytes. - MOVB $0xee, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $60, AX - -step2: - // if length >= 12 || offset >= 2048 { goto step3 } - CMPL AX, $12 - JGE step3 - CMPL R11, $2048 - JGE step3 - - // Emit the remaining copy, encoded as 2 bytes. - MOVB R11, 1(DI) - SHRL $8, R11 - SHLB $5, R11 - SUBB $4, AX - SHLB $2, AX - ORB AX, R11 - ORB $1, R11 - MOVB R11, 0(DI) - ADDQ $2, DI - - // Return the number of bytes written. - SUBQ SI, DI - MOVQ DI, ret+40(FP) - RET - -step3: - // Emit the remaining copy, encoded as 3 bytes. - SUBL $1, AX - SHLB $2, AX - ORB $2, AX - MOVB AX, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - - // Return the number of bytes written. - SUBQ SI, DI - MOVQ DI, ret+40(FP) - RET - -// ---------------------------------------------------------------------------- - -// func extendMatch(src []byte, i, j int) int -// -// All local variables fit into registers. The register allocation: -// - DX &src[0] -// - SI &src[j] -// - R13 &src[len(src) - 8] -// - R14 &src[len(src)] -// - R15 &src[i] -// -// The unusual register allocation of local variables, such as R15 for a source -// pointer, matches the allocation used at the call site in encodeBlock, which -// makes it easier to manually inline this function. -TEXT ·extendMatch(SB), NOSPLIT, $0-48 - MOVQ src_base+0(FP), DX - MOVQ src_len+8(FP), R14 - MOVQ i+24(FP), R15 - MOVQ j+32(FP), SI - ADDQ DX, R14 - ADDQ DX, R15 - ADDQ DX, SI - MOVQ R14, R13 - SUBQ $8, R13 - -cmp8: - // As long as we are 8 or more bytes before the end of src, we can load and - // compare 8 bytes at a time. If those 8 bytes are equal, repeat. - CMPQ SI, R13 - JA cmp1 - MOVQ (R15), AX - MOVQ (SI), BX - CMPQ AX, BX - JNE bsf - ADDQ $8, R15 - ADDQ $8, SI - JMP cmp8 - -bsf: - // If those 8 bytes were not equal, XOR the two 8 byte values, and return - // the index of the first byte that differs. The BSF instruction finds the - // least significant 1 bit, the amd64 architecture is little-endian, and - // the shift by 3 converts a bit index to a byte index. - XORQ AX, BX - BSFQ BX, BX - SHRQ $3, BX - ADDQ BX, SI - - // Convert from &src[ret] to ret. - SUBQ DX, SI - MOVQ SI, ret+40(FP) - RET - -cmp1: - // In src's tail, compare 1 byte at a time. - CMPQ SI, R14 - JAE extendMatchEnd - MOVB (R15), AX - MOVB (SI), BX - CMPB AX, BX - JNE extendMatchEnd - ADDQ $1, R15 - ADDQ $1, SI - JMP cmp1 - -extendMatchEnd: - // Convert from &src[ret] to ret. - SUBQ DX, SI - MOVQ SI, ret+40(FP) - RET - -// ---------------------------------------------------------------------------- - -// func encodeBlock(dst, src []byte) (d int) -// -// All local variables fit into registers, other than "var table". The register -// allocation: -// - AX . . -// - BX . . -// - CX 56 shift (note that amd64 shifts by non-immediates must use CX). -// - DX 64 &src[0], tableSize -// - SI 72 &src[s] -// - DI 80 &dst[d] -// - R9 88 sLimit -// - R10 . &src[nextEmit] -// - R11 96 prevHash, currHash, nextHash, offset -// - R12 104 &src[base], skip -// - R13 . &src[nextS], &src[len(src) - 8] -// - R14 . len(src), bytesBetweenHashLookups, &src[len(src)], x -// - R15 112 candidate -// -// The second column (56, 64, etc) is the stack offset to spill the registers -// when calling other functions. We could pack this slightly tighter, but it's -// simpler to have a dedicated spill map independent of the function called. -// -// "var table [maxTableSize]uint16" takes up 32768 bytes of stack space. An -// extra 56 bytes, to call other functions, and an extra 64 bytes, to spill -// local variables (registers) during calls gives 32768 + 56 + 64 = 32888. -TEXT ·encodeBlock(SB), 0, $32888-56 - MOVQ dst_base+0(FP), DI - MOVQ src_base+24(FP), SI - MOVQ src_len+32(FP), R14 - - // shift, tableSize := uint32(32-8), 1<<8 - MOVQ $24, CX - MOVQ $256, DX - -calcShift: - // for ; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { - // shift-- - // } - CMPQ DX, $16384 - JGE varTable - CMPQ DX, R14 - JGE varTable - SUBQ $1, CX - SHLQ $1, DX - JMP calcShift - -varTable: - // var table [maxTableSize]uint16 - // - // In the asm code, unlike the Go code, we can zero-initialize only the - // first tableSize elements. Each uint16 element is 2 bytes and each MOVOU - // writes 16 bytes, so we can do only tableSize/8 writes instead of the - // 2048 writes that would zero-initialize all of table's 32768 bytes. - SHRQ $3, DX - LEAQ table-32768(SP), BX - PXOR X0, X0 - -memclr: - MOVOU X0, 0(BX) - ADDQ $16, BX - SUBQ $1, DX - JNZ memclr - - // !!! DX = &src[0] - MOVQ SI, DX - - // sLimit := len(src) - inputMargin - MOVQ R14, R9 - SUBQ $15, R9 - - // !!! Pre-emptively spill CX, DX and R9 to the stack. Their values don't - // change for the rest of the function. - MOVQ CX, 56(SP) - MOVQ DX, 64(SP) - MOVQ R9, 88(SP) - - // nextEmit := 0 - MOVQ DX, R10 - - // s := 1 - ADDQ $1, SI - - // nextHash := hash(load32(src, s), shift) - MOVL 0(SI), R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - -outer: - // for { etc } - - // skip := 32 - MOVQ $32, R12 - - // nextS := s - MOVQ SI, R13 - - // candidate := 0 - MOVQ $0, R15 - -inner0: - // for { etc } - - // s := nextS - MOVQ R13, SI - - // bytesBetweenHashLookups := skip >> 5 - MOVQ R12, R14 - SHRQ $5, R14 - - // nextS = s + bytesBetweenHashLookups - ADDQ R14, R13 - - // skip += bytesBetweenHashLookups - ADDQ R14, R12 - - // if nextS > sLimit { goto emitRemainder } - MOVQ R13, AX - SUBQ DX, AX - CMPQ AX, R9 - JA emitRemainder - - // candidate = int(table[nextHash]) - // XXX: MOVWQZX table-32768(SP)(R11*2), R15 - // XXX: 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 - BYTE $0x4e - BYTE $0x0f - BYTE $0xb7 - BYTE $0x7c - BYTE $0x5c - BYTE $0x78 - - // table[nextHash] = uint16(s) - MOVQ SI, AX - SUBQ DX, AX - - // XXX: MOVW AX, table-32768(SP)(R11*2) - // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) - BYTE $0x66 - BYTE $0x42 - BYTE $0x89 - BYTE $0x44 - BYTE $0x5c - BYTE $0x78 - - // nextHash = hash(load32(src, nextS), shift) - MOVL 0(R13), R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // if load32(src, s) != load32(src, candidate) { continue } break - MOVL 0(SI), AX - MOVL (DX)(R15*1), BX - CMPL AX, BX - JNE inner0 - -fourByteMatch: - // As per the encode_other.go code: - // - // A 4-byte match has been found. We'll later see etc. - - // !!! Jump to a fast path for short (<= 16 byte) literals. See the comment - // on inputMargin in encode.go. - MOVQ SI, AX - SUBQ R10, AX - CMPQ AX, $16 - JLE emitLiteralFastPath - - // ---------------------------------------- - // Begin inline of the emitLiteral call. - // - // d += emitLiteral(dst[d:], src[nextEmit:s]) - - MOVL AX, BX - SUBL $1, BX - - CMPL BX, $60 - JLT inlineEmitLiteralOneByte - CMPL BX, $256 - JLT inlineEmitLiteralTwoBytes - -inlineEmitLiteralThreeBytes: - MOVB $0xf4, 0(DI) - MOVW BX, 1(DI) - ADDQ $3, DI - JMP inlineEmitLiteralMemmove - -inlineEmitLiteralTwoBytes: - MOVB $0xf0, 0(DI) - MOVB BX, 1(DI) - ADDQ $2, DI - JMP inlineEmitLiteralMemmove - -inlineEmitLiteralOneByte: - SHLB $2, BX - MOVB BX, 0(DI) - ADDQ $1, DI - -inlineEmitLiteralMemmove: - // Spill local variables (registers) onto the stack; call; unspill. - // - // copy(dst[i:], lit) - // - // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push - // DI, R10 and AX as arguments. - MOVQ DI, 0(SP) - MOVQ R10, 8(SP) - MOVQ AX, 16(SP) - ADDQ AX, DI // Finish the "d +=" part of "d += emitLiteral(etc)". - MOVQ SI, 72(SP) - MOVQ DI, 80(SP) - MOVQ R15, 112(SP) - CALL runtime·memmove(SB) - MOVQ 56(SP), CX - MOVQ 64(SP), DX - MOVQ 72(SP), SI - MOVQ 80(SP), DI - MOVQ 88(SP), R9 - MOVQ 112(SP), R15 - JMP inner1 - -inlineEmitLiteralEnd: - // End inline of the emitLiteral call. - // ---------------------------------------- - -emitLiteralFastPath: - // !!! Emit the 1-byte encoding "uint8(len(lit)-1)<<2". - MOVB AX, BX - SUBB $1, BX - SHLB $2, BX - MOVB BX, (DI) - ADDQ $1, DI - - // !!! Implement the copy from lit to dst as a 16-byte load and store. - // (Encode's documentation says that dst and src must not overlap.) - // - // This always copies 16 bytes, instead of only len(lit) bytes, but that's - // OK. Subsequent iterations will fix up the overrun. - // - // Note that on amd64, it is legal and cheap to issue unaligned 8-byte or - // 16-byte loads and stores. This technique probably wouldn't be as - // effective on architectures that are fussier about alignment. - MOVOU 0(R10), X0 - MOVOU X0, 0(DI) - ADDQ AX, DI - -inner1: - // for { etc } - - // base := s - MOVQ SI, R12 - - // !!! offset := base - candidate - MOVQ R12, R11 - SUBQ R15, R11 - SUBQ DX, R11 - - // ---------------------------------------- - // Begin inline of the extendMatch call. - // - // s = extendMatch(src, candidate+4, s+4) - - // !!! R14 = &src[len(src)] - MOVQ src_len+32(FP), R14 - ADDQ DX, R14 - - // !!! R13 = &src[len(src) - 8] - MOVQ R14, R13 - SUBQ $8, R13 - - // !!! R15 = &src[candidate + 4] - ADDQ $4, R15 - ADDQ DX, R15 - - // !!! s += 4 - ADDQ $4, SI - -inlineExtendMatchCmp8: - // As long as we are 8 or more bytes before the end of src, we can load and - // compare 8 bytes at a time. If those 8 bytes are equal, repeat. - CMPQ SI, R13 - JA inlineExtendMatchCmp1 - MOVQ (R15), AX - MOVQ (SI), BX - CMPQ AX, BX - JNE inlineExtendMatchBSF - ADDQ $8, R15 - ADDQ $8, SI - JMP inlineExtendMatchCmp8 - -inlineExtendMatchBSF: - // If those 8 bytes were not equal, XOR the two 8 byte values, and return - // the index of the first byte that differs. The BSF instruction finds the - // least significant 1 bit, the amd64 architecture is little-endian, and - // the shift by 3 converts a bit index to a byte index. - XORQ AX, BX - BSFQ BX, BX - SHRQ $3, BX - ADDQ BX, SI - JMP inlineExtendMatchEnd - -inlineExtendMatchCmp1: - // In src's tail, compare 1 byte at a time. - CMPQ SI, R14 - JAE inlineExtendMatchEnd - MOVB (R15), AX - MOVB (SI), BX - CMPB AX, BX - JNE inlineExtendMatchEnd - ADDQ $1, R15 - ADDQ $1, SI - JMP inlineExtendMatchCmp1 - -inlineExtendMatchEnd: - // End inline of the extendMatch call. - // ---------------------------------------- - - // ---------------------------------------- - // Begin inline of the emitCopy call. - // - // d += emitCopy(dst[d:], base-candidate, s-base) - - // !!! length := s - base - MOVQ SI, AX - SUBQ R12, AX - -inlineEmitCopyLoop0: - // for length >= 68 { etc } - CMPL AX, $68 - JLT inlineEmitCopyStep1 - - // Emit a length 64 copy, encoded as 3 bytes. - MOVB $0xfe, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $64, AX - JMP inlineEmitCopyLoop0 - -inlineEmitCopyStep1: - // if length > 64 { etc } - CMPL AX, $64 - JLE inlineEmitCopyStep2 - - // Emit a length 60 copy, encoded as 3 bytes. - MOVB $0xee, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - SUBL $60, AX - -inlineEmitCopyStep2: - // if length >= 12 || offset >= 2048 { goto inlineEmitCopyStep3 } - CMPL AX, $12 - JGE inlineEmitCopyStep3 - CMPL R11, $2048 - JGE inlineEmitCopyStep3 - - // Emit the remaining copy, encoded as 2 bytes. - MOVB R11, 1(DI) - SHRL $8, R11 - SHLB $5, R11 - SUBB $4, AX - SHLB $2, AX - ORB AX, R11 - ORB $1, R11 - MOVB R11, 0(DI) - ADDQ $2, DI - JMP inlineEmitCopyEnd - -inlineEmitCopyStep3: - // Emit the remaining copy, encoded as 3 bytes. - SUBL $1, AX - SHLB $2, AX - ORB $2, AX - MOVB AX, 0(DI) - MOVW R11, 1(DI) - ADDQ $3, DI - -inlineEmitCopyEnd: - // End inline of the emitCopy call. - // ---------------------------------------- - - // nextEmit = s - MOVQ SI, R10 - - // if s >= sLimit { goto emitRemainder } - MOVQ SI, AX - SUBQ DX, AX - CMPQ AX, R9 - JAE emitRemainder - - // As per the encode_other.go code: - // - // We could immediately etc. - - // x := load64(src, s-1) - MOVQ -1(SI), R14 - - // prevHash := hash(uint32(x>>0), shift) - MOVL R14, R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // table[prevHash] = uint16(s-1) - MOVQ SI, AX - SUBQ DX, AX - SUBQ $1, AX - - // XXX: MOVW AX, table-32768(SP)(R11*2) - // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) - BYTE $0x66 - BYTE $0x42 - BYTE $0x89 - BYTE $0x44 - BYTE $0x5c - BYTE $0x78 - - // currHash := hash(uint32(x>>8), shift) - SHRQ $8, R14 - MOVL R14, R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // candidate = int(table[currHash]) - // XXX: MOVWQZX table-32768(SP)(R11*2), R15 - // XXX: 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15 - BYTE $0x4e - BYTE $0x0f - BYTE $0xb7 - BYTE $0x7c - BYTE $0x5c - BYTE $0x78 - - // table[currHash] = uint16(s) - ADDQ $1, AX - - // XXX: MOVW AX, table-32768(SP)(R11*2) - // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2) - BYTE $0x66 - BYTE $0x42 - BYTE $0x89 - BYTE $0x44 - BYTE $0x5c - BYTE $0x78 - - // if uint32(x>>8) == load32(src, candidate) { continue } - MOVL (DX)(R15*1), BX - CMPL R14, BX - JEQ inner1 - - // nextHash = hash(uint32(x>>16), shift) - SHRQ $8, R14 - MOVL R14, R11 - IMULL $0x1e35a7bd, R11 - SHRL CX, R11 - - // s++ - ADDQ $1, SI - - // break out of the inner1 for loop, i.e. continue the outer loop. - JMP outer - -emitRemainder: - // if nextEmit < len(src) { etc } - MOVQ src_len+32(FP), AX - ADDQ DX, AX - CMPQ R10, AX - JEQ encodeBlockEnd - - // d += emitLiteral(dst[d:], src[nextEmit:]) - // - // Push args. - MOVQ DI, 0(SP) - MOVQ $0, 8(SP) // Unnecessary, as the callee ignores it, but conservative. - MOVQ $0, 16(SP) // Unnecessary, as the callee ignores it, but conservative. - MOVQ R10, 24(SP) - SUBQ R10, AX - MOVQ AX, 32(SP) - MOVQ AX, 40(SP) // Unnecessary, as the callee ignores it, but conservative. - - // Spill local variables (registers) onto the stack; call; unspill. - MOVQ DI, 80(SP) - CALL ·emitLiteral(SB) - MOVQ 80(SP), DI - - // Finish the "d +=" part of "d += emitLiteral(etc)". - ADDQ 48(SP), DI - -encodeBlockEnd: - MOVQ dst_base+0(FP), AX - SUBQ AX, DI - MOVQ DI, d+48(FP) - RET diff --git a/vendor/github.com/golang/snappy/encode_other.go b/vendor/github.com/golang/snappy/encode_other.go deleted file mode 100644 index dbcae905e6e..00000000000 --- a/vendor/github.com/golang/snappy/encode_other.go +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright 2016 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !amd64 appengine !gc noasm - -package snappy - -func load32(b []byte, i int) uint32 { - b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line. - return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 -} - -func load64(b []byte, i int) uint64 { - b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line. - return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | - uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 -} - -// emitLiteral writes a literal chunk and returns the number of bytes written. -// -// It assumes that: -// dst is long enough to hold the encoded bytes -// 1 <= len(lit) && len(lit) <= 65536 -func emitLiteral(dst, lit []byte) int { - i, n := 0, uint(len(lit)-1) - switch { - case n < 60: - dst[0] = uint8(n)<<2 | tagLiteral - i = 1 - case n < 1<<8: - dst[0] = 60<<2 | tagLiteral - dst[1] = uint8(n) - i = 2 - default: - dst[0] = 61<<2 | tagLiteral - dst[1] = uint8(n) - dst[2] = uint8(n >> 8) - i = 3 - } - return i + copy(dst[i:], lit) -} - -// emitCopy writes a copy chunk and returns the number of bytes written. -// -// It assumes that: -// dst is long enough to hold the encoded bytes -// 1 <= offset && offset <= 65535 -// 4 <= length && length <= 65535 -func emitCopy(dst []byte, offset, length int) int { - i := 0 - // The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The - // threshold for this loop is a little higher (at 68 = 64 + 4), and the - // length emitted down below is is a little lower (at 60 = 64 - 4), because - // it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed - // by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as - // a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as - // 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a - // tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an - // encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1. - for length >= 68 { - // Emit a length 64 copy, encoded as 3 bytes. - dst[i+0] = 63<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - i += 3 - length -= 64 - } - if length > 64 { - // Emit a length 60 copy, encoded as 3 bytes. - dst[i+0] = 59<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - i += 3 - length -= 60 - } - if length >= 12 || offset >= 2048 { - // Emit the remaining copy, encoded as 3 bytes. - dst[i+0] = uint8(length-1)<<2 | tagCopy2 - dst[i+1] = uint8(offset) - dst[i+2] = uint8(offset >> 8) - return i + 3 - } - // Emit the remaining copy, encoded as 2 bytes. - dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1 - dst[i+1] = uint8(offset) - return i + 2 -} - -// extendMatch returns the largest k such that k <= len(src) and that -// src[i:i+k-j] and src[j:k] have the same contents. -// -// It assumes that: -// 0 <= i && i < j && j <= len(src) -func extendMatch(src []byte, i, j int) int { - for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 { - } - return j -} - -func hash(u, shift uint32) uint32 { - return (u * 0x1e35a7bd) >> shift -} - -// encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It -// assumes that the varint-encoded length of the decompressed bytes has already -// been written. -// -// It also assumes that: -// len(dst) >= MaxEncodedLen(len(src)) && -// minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize -func encodeBlock(dst, src []byte) (d int) { - // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive. - // The table element type is uint16, as s < sLimit and sLimit < len(src) - // and len(src) <= maxBlockSize and maxBlockSize == 65536. - const ( - maxTableSize = 1 << 14 - // tableMask is redundant, but helps the compiler eliminate bounds - // checks. - tableMask = maxTableSize - 1 - ) - shift := uint32(32 - 8) - for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 { - shift-- - } - // In Go, all array elements are zero-initialized, so there is no advantage - // to a smaller tableSize per se. However, it matches the C++ algorithm, - // and in the asm versions of this code, we can get away with zeroing only - // the first tableSize elements. - var table [maxTableSize]uint16 - - // sLimit is when to stop looking for offset/length copies. The inputMargin - // lets us use a fast path for emitLiteral in the main loop, while we are - // looking for copies. - sLimit := len(src) - inputMargin - - // nextEmit is where in src the next emitLiteral should start from. - nextEmit := 0 - - // The encoded form must start with a literal, as there are no previous - // bytes to copy, so we start looking for hash matches at s == 1. - s := 1 - nextHash := hash(load32(src, s), shift) - - for { - // Copied from the C++ snappy implementation: - // - // Heuristic match skipping: If 32 bytes are scanned with no matches - // found, start looking only at every other byte. If 32 more bytes are - // scanned (or skipped), look at every third byte, etc.. When a match - // is found, immediately go back to looking at every byte. This is a - // small loss (~5% performance, ~0.1% density) for compressible data - // due to more bookkeeping, but for non-compressible data (such as - // JPEG) it's a huge win since the compressor quickly "realizes" the - // data is incompressible and doesn't bother looking for matches - // everywhere. - // - // The "skip" variable keeps track of how many bytes there are since - // the last match; dividing it by 32 (ie. right-shifting by five) gives - // the number of bytes to move ahead for each iteration. - skip := 32 - - nextS := s - candidate := 0 - for { - s = nextS - bytesBetweenHashLookups := skip >> 5 - nextS = s + bytesBetweenHashLookups - skip += bytesBetweenHashLookups - if nextS > sLimit { - goto emitRemainder - } - candidate = int(table[nextHash&tableMask]) - table[nextHash&tableMask] = uint16(s) - nextHash = hash(load32(src, nextS), shift) - if load32(src, s) == load32(src, candidate) { - break - } - } - - // A 4-byte match has been found. We'll later see if more than 4 bytes - // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit - // them as literal bytes. - d += emitLiteral(dst[d:], src[nextEmit:s]) - - // Call emitCopy, and then see if another emitCopy could be our next - // move. Repeat until we find no match for the input immediately after - // what was consumed by the last emitCopy call. - // - // If we exit this loop normally then we need to call emitLiteral next, - // though we don't yet know how big the literal will be. We handle that - // by proceeding to the next iteration of the main loop. We also can - // exit this loop via goto if we get close to exhausting the input. - for { - // Invariant: we have a 4-byte match at s, and no need to emit any - // literal bytes prior to s. - base := s - - // Extend the 4-byte match as long as possible. - // - // This is an inlined version of: - // s = extendMatch(src, candidate+4, s+4) - s += 4 - for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 { - } - - d += emitCopy(dst[d:], base-candidate, s-base) - nextEmit = s - if s >= sLimit { - goto emitRemainder - } - - // We could immediately start working at s now, but to improve - // compression we first update the hash table at s-1 and at s. If - // another emitCopy is not our next move, also calculate nextHash - // at s+1. At least on GOARCH=amd64, these three hash calculations - // are faster as one load64 call (with some shifts) instead of - // three load32 calls. - x := load64(src, s-1) - prevHash := hash(uint32(x>>0), shift) - table[prevHash&tableMask] = uint16(s - 1) - currHash := hash(uint32(x>>8), shift) - candidate = int(table[currHash&tableMask]) - table[currHash&tableMask] = uint16(s) - if uint32(x>>8) != load32(src, candidate) { - nextHash = hash(uint32(x>>16), shift) - s++ - break - } - } - } - -emitRemainder: - if nextEmit < len(src) { - d += emitLiteral(dst[d:], src[nextEmit:]) - } - return d -} diff --git a/vendor/github.com/golang/snappy/go.mod b/vendor/github.com/golang/snappy/go.mod deleted file mode 100644 index f6406bb2c76..00000000000 --- a/vendor/github.com/golang/snappy/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/golang/snappy diff --git a/vendor/github.com/golang/snappy/snappy.go b/vendor/github.com/golang/snappy/snappy.go deleted file mode 100644 index ece692ea461..00000000000 --- a/vendor/github.com/golang/snappy/snappy.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2011 The Snappy-Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package snappy implements the Snappy compression format. It aims for very -// high speeds and reasonable compression. -// -// There are actually two Snappy formats: block and stream. They are related, -// but different: trying to decompress block-compressed data as a Snappy stream -// will fail, and vice versa. The block format is the Decode and Encode -// functions and the stream format is the Reader and Writer types. -// -// The block format, the more common case, is used when the complete size (the -// number of bytes) of the original data is known upfront, at the time -// compression starts. The stream format, also known as the framing format, is -// for when that isn't always true. -// -// The canonical, C++ implementation is at https://github.com/google/snappy and -// it only implements the block format. -package snappy // import "github.com/golang/snappy" - -import ( - "hash/crc32" -) - -/* -Each encoded block begins with the varint-encoded length of the decoded data, -followed by a sequence of chunks. Chunks begin and end on byte boundaries. The -first byte of each chunk is broken into its 2 least and 6 most significant bits -called l and m: l ranges in [0, 4) and m ranges in [0, 64). l is the chunk tag. -Zero means a literal tag. All other values mean a copy tag. - -For literal tags: - - If m < 60, the next 1 + m bytes are literal bytes. - - Otherwise, let n be the little-endian unsigned integer denoted by the next - m - 59 bytes. The next 1 + n bytes after that are literal bytes. - -For copy tags, length bytes are copied from offset bytes ago, in the style of -Lempel-Ziv compression algorithms. In particular: - - For l == 1, the offset ranges in [0, 1<<11) and the length in [4, 12). - The length is 4 + the low 3 bits of m. The high 3 bits of m form bits 8-10 - of the offset. The next byte is bits 0-7 of the offset. - - For l == 2, the offset ranges in [0, 1<<16) and the length in [1, 65). - The length is 1 + m. The offset is the little-endian unsigned integer - denoted by the next 2 bytes. - - For l == 3, this tag is a legacy format that is no longer issued by most - encoders. Nonetheless, the offset ranges in [0, 1<<32) and the length in - [1, 65). The length is 1 + m. The offset is the little-endian unsigned - integer denoted by the next 4 bytes. -*/ -const ( - tagLiteral = 0x00 - tagCopy1 = 0x01 - tagCopy2 = 0x02 - tagCopy4 = 0x03 -) - -const ( - checksumSize = 4 - chunkHeaderSize = 4 - magicChunk = "\xff\x06\x00\x00" + magicBody - magicBody = "sNaPpY" - - // maxBlockSize is the maximum size of the input to encodeBlock. It is not - // part of the wire format per se, but some parts of the encoder assume - // that an offset fits into a uint16. - // - // Also, for the framing format (Writer type instead of Encode function), - // https://github.com/google/snappy/blob/master/framing_format.txt says - // that "the uncompressed data in a chunk must be no longer than 65536 - // bytes". - maxBlockSize = 65536 - - // maxEncodedLenOfMaxBlockSize equals MaxEncodedLen(maxBlockSize), but is - // hard coded to be a const instead of a variable, so that obufLen can also - // be a const. Their equivalence is confirmed by - // TestMaxEncodedLenOfMaxBlockSize. - maxEncodedLenOfMaxBlockSize = 76490 - - obufHeaderLen = len(magicChunk) + checksumSize + chunkHeaderSize - obufLen = obufHeaderLen + maxEncodedLenOfMaxBlockSize -) - -const ( - chunkTypeCompressedData = 0x00 - chunkTypeUncompressedData = 0x01 - chunkTypePadding = 0xfe - chunkTypeStreamIdentifier = 0xff -) - -var crcTable = crc32.MakeTable(crc32.Castagnoli) - -// crc implements the checksum specified in section 3 of -// https://github.com/google/snappy/blob/master/framing_format.txt -func crc(b []byte) uint32 { - c := crc32.Update(0, crcTable, b) - return uint32(c>>15|c<<17) + 0xa282ead8 -} diff --git a/vendor/github.com/golangci/golangci-lint/internal/cache/cache.go b/vendor/github.com/golangci/golangci-lint/internal/cache/cache.go index 9ac140c50ea..51c75a77d2d 100644 --- a/vendor/github.com/golangci/golangci-lint/internal/cache/cache.go +++ b/vendor/github.com/golangci/golangci-lint/internal/cache/cache.go @@ -14,7 +14,6 @@ import ( "encoding/hex" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strconv" @@ -24,6 +23,7 @@ import ( "github.com/pkg/errors" "github.com/golangci/golangci-lint/internal/renameio" + "github.com/golangci/golangci-lint/internal/robustio" ) // An ActionID is a cache action key, the hash of a complete description of a @@ -81,7 +81,7 @@ func (c *Cache) fileName(id [HashSize]byte, key string) string { var errMissing = errors.New("cache entry not found") func IsErrMissing(err error) bool { - return err == errMissing + return errors.Cause(err) == errMissing } const ( @@ -199,26 +199,6 @@ func (c *Cache) get(id ActionID) (Entry, error) { return Entry{buf, size, time.Unix(0, tm)}, nil } -// GetFile looks up the action ID in the cache and returns -// the name of the corresponding data file. -func (c *Cache) GetFile(id ActionID) (file string, entry Entry, err error) { - entry, err = c.Get(id) - if err != nil { - return "", Entry{}, err - } - - file, err = c.OutputFile(entry.OutputID) - if err != nil { - return "", Entry{}, err - } - - info, err := os.Stat(file) - if err != nil || info.Size() != entry.Size { - return "", Entry{}, errMissing - } - return file, entry, nil -} - // GetBytes looks up the action ID in the cache and returns // the corresponding output bytes. // GetBytes should only be used for data that can be expected to fit in memory. @@ -232,7 +212,7 @@ func (c *Cache) GetBytes(id ActionID) ([]byte, Entry, error) { return nil, entry, err } - data, err := ioutil.ReadFile(outputFile) + data, err := robustio.ReadFile(outputFile) if err != nil { return nil, entry, err } @@ -282,6 +262,9 @@ const ( func (c *Cache) used(file string) error { info, err := os.Stat(file) if err != nil { + if os.IsNotExist(err) { + return errMissing + } return errors.Wrapf(err, "failed to stat file %s", file) } diff --git a/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_darwin.go b/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_darwin.go new file mode 100644 index 00000000000..1ac0d10d7f1 --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_darwin.go @@ -0,0 +1,29 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package robustio + +import ( + "os" + "syscall" +) + +const errFileNotFound = syscall.ENOENT + +// isEphemeralError returns true if err may be resolved by waiting. +func isEphemeralError(err error) bool { + switch werr := err.(type) { + case *os.PathError: + err = werr.Err + case *os.LinkError: + err = werr.Err + case *os.SyscallError: + err = werr.Err + + } + if errno, ok := err.(syscall.Errno); ok { + return errno == errFileNotFound + } + return false +} diff --git a/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_flaky.go b/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_flaky.go new file mode 100644 index 00000000000..e0bf5b9b3b9 --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_flaky.go @@ -0,0 +1,93 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build windows darwin + +package robustio + +import ( + "io/ioutil" + "math/rand" + "os" + "syscall" + "time" +) + +const arbitraryTimeout = 500 * time.Millisecond + +const ERROR_SHARING_VIOLATION = 32 + +// retry retries ephemeral errors from f up to an arbitrary timeout +// to work around filesystem flakiness on Windows and Darwin. +func retry(f func() (err error, mayRetry bool)) error { + var ( + bestErr error + lowestErrno syscall.Errno + start time.Time + nextSleep time.Duration = 1 * time.Millisecond + ) + for { + err, mayRetry := f() + if err == nil || !mayRetry { + return err + } + + if errno, ok := err.(syscall.Errno); ok && (lowestErrno == 0 || errno < lowestErrno) { + bestErr = err + lowestErrno = errno + } else if bestErr == nil { + bestErr = err + } + + if start.IsZero() { + start = time.Now() + } else if d := time.Since(start) + nextSleep; d >= arbitraryTimeout { + break + } + time.Sleep(nextSleep) + nextSleep += time.Duration(rand.Int63n(int64(nextSleep))) + } + + return bestErr +} + +// rename is like os.Rename, but retries ephemeral errors. +// +// On windows it wraps os.Rename, which (as of 2019-06-04) uses MoveFileEx with +// MOVEFILE_REPLACE_EXISTING. +// +// Windows also provides a different system call, ReplaceFile, +// that provides similar semantics, but perhaps preserves more metadata. (The +// documentation on the differences between the two is very sparse.) +// +// Empirical error rates with MoveFileEx are lower under modest concurrency, so +// for now we're sticking with what the os package already provides. +func rename(oldpath, newpath string) (err error) { + return retry(func() (err error, mayRetry bool) { + err = os.Rename(oldpath, newpath) + return err, isEphemeralError(err) + }) +} + +// readFile is like ioutil.ReadFile, but retries ephemeral errors. +func readFile(filename string) ([]byte, error) { + var b []byte + err := retry(func() (err error, mayRetry bool) { + b, err = ioutil.ReadFile(filename) + + // Unlike in rename, we do not retry errFileNotFound here: it can occur + // as a spurious error, but the file may also genuinely not exist, so the + // increase in robustness is probably not worth the extra latency. + + return err, isEphemeralError(err) && err != errFileNotFound + }) + return b, err +} + +func removeAll(path string) error { + return retry(func() (err error, mayRetry bool) { + err = os.RemoveAll(path) + return err, isEphemeralError(err) + }) +} diff --git a/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_other.go b/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_other.go index 91ca56cb82c..a2428856f2e 100644 --- a/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_other.go +++ b/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_other.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//+build !windows +//+build !windows,!darwin package robustio diff --git a/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_windows.go b/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_windows.go index 02f1e8c1ce6..a35237d44ae 100644 --- a/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_windows.go +++ b/vendor/github.com/golangci/golangci-lint/internal/robustio/robustio_windows.go @@ -5,93 +5,22 @@ package robustio import ( - "io/ioutil" - "math/rand" "os" "syscall" - "time" ) -const arbitraryTimeout = 500 * time.Millisecond - -const ERROR_SHARING_VIOLATION = 32 - -// retry retries ephemeral errors from f up to an arbitrary timeout -// to work around spurious filesystem errors on Windows -func retry(f func() (err error, mayRetry bool)) error { - var ( - bestErr error - lowestErrno syscall.Errno - start time.Time - nextSleep time.Duration = 1 * time.Millisecond - ) - for { - err, mayRetry := f() - if err == nil || !mayRetry { - return err - } - - if errno, ok := err.(syscall.Errno); ok && (lowestErrno == 0 || errno < lowestErrno) { - bestErr = err - lowestErrno = errno - } else if bestErr == nil { - bestErr = err - } - - if start.IsZero() { - start = time.Now() - } else if d := time.Since(start) + nextSleep; d >= arbitraryTimeout { - break - } - time.Sleep(nextSleep) - nextSleep += time.Duration(rand.Int63n(int64(nextSleep))) - } - - return bestErr -} - -// rename is like os.Rename, but retries ephemeral errors. -// -// It wraps os.Rename, which (as of 2019-06-04) uses MoveFileEx with -// MOVEFILE_REPLACE_EXISTING. -// -// Windows also provides a different system call, ReplaceFile, -// that provides similar semantics, but perhaps preserves more metadata. (The -// documentation on the differences between the two is very sparse.) -// -// Empirical error rates with MoveFileEx are lower under modest concurrency, so -// for now we're sticking with what the os package already provides. -func rename(oldpath, newpath string) (err error) { - return retry(func() (err error, mayRetry bool) { - err = os.Rename(oldpath, newpath) - return err, isEphemeralError(err) - }) -} - -// readFile is like ioutil.ReadFile, but retries ephemeral errors. -func readFile(filename string) ([]byte, error) { - var b []byte - err := retry(func() (err error, mayRetry bool) { - b, err = ioutil.ReadFile(filename) - - // Unlike in rename, we do not retry ERROR_FILE_NOT_FOUND here: it can occur - // as a spurious error, but the file may also genuinely not exist, so the - // increase in robustness is probably not worth the extra latency. - - return err, isEphemeralError(err) && err != syscall.ERROR_FILE_NOT_FOUND - }) - return b, err -} - -func removeAll(path string) error { - return retry(func() (err error, mayRetry bool) { - err = os.RemoveAll(path) - return err, isEphemeralError(err) - }) -} +const errFileNotFound = syscall.ERROR_FILE_NOT_FOUND // isEphemeralError returns true if err may be resolved by waiting. func isEphemeralError(err error) bool { + switch werr := err.(type) { + case *os.PathError: + err = werr.Err + case *os.LinkError: + err = werr.Err + case *os.SyscallError: + err = werr.Err + } if errno, ok := err.(syscall.Errno); ok { switch errno { case syscall.ERROR_ACCESS_DENIED, diff --git a/vendor/github.com/golangci/golangci-lint/pkg/commands/config.go b/vendor/github.com/golangci/golangci-lint/pkg/commands/config.go index 807f1ca492a..4b63e2e5239 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/commands/config.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/commands/config.go @@ -35,22 +35,32 @@ func (e *Executor) initConfig() { cmd.AddCommand(pathCmd) } +func (e *Executor) getUsedConfig() string { + usedConfigFile := viper.ConfigFileUsed() + if usedConfigFile == "" { + return "" + } + + prettyUsedConfigFile, err := fsutils.ShortestRelPath(usedConfigFile, "") + if err != nil { + e.log.Warnf("Can't pretty print config file path: %s", err) + return usedConfigFile + } + + return prettyUsedConfigFile +} + func (e *Executor) executePathCmd(_ *cobra.Command, args []string) { if len(args) != 0 { e.log.Fatalf("Usage: golangci-lint config path") } - usedConfigFile := viper.ConfigFileUsed() + usedConfigFile := e.getUsedConfig() if usedConfigFile == "" { e.log.Warnf("No config file detected") os.Exit(exitcodes.NoConfigFileDetected) } - usedConfigFile, err := fsutils.ShortestRelPath(usedConfigFile, "") - if err != nil { - e.log.Warnf("Can't pretty print config file path: %s", err) - } - fmt.Println(usedConfigFile) os.Exit(0) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/commands/executor.go b/vendor/github.com/golangci/golangci-lint/pkg/commands/executor.go index ffef5b0a5bd..9581acab21f 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/commands/executor.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/commands/executor.go @@ -5,10 +5,10 @@ import ( "context" "crypto/sha256" "encoding/json" - "fmt" "io" "os" "path/filepath" + "strings" "time" "github.com/fatih/color" @@ -31,8 +31,9 @@ import ( ) type Executor struct { - rootCmd *cobra.Command - runCmd *cobra.Command + rootCmd *cobra.Command + runCmd *cobra.Command + lintersCmd *cobra.Command exitCode int version, commit, date string @@ -55,6 +56,7 @@ type Executor struct { } func NewExecutor(version, commit, date string) *Executor { + startedAt := time.Now() e := &Executor{ cfg: config.NewDefault(), version: version, @@ -66,9 +68,6 @@ func NewExecutor(version, commit, date string) *Executor { e.debugf("Starting execution...") e.log = report.NewLogWrapper(logutils.NewStderrLog(""), &e.reportData) - if ok := e.acquireFileLock(); !ok { - e.log.Fatalf("Parallel golangci-lint is running") - } // to setup log level early we need to parse config from command line extra time to // find `-v` option @@ -121,6 +120,7 @@ func NewExecutor(version, commit, date string) *Executor { // Slice options must be explicitly set for proper merging of config and command-line options. fixSlicesFlags(e.runCmd.Flags()) + fixSlicesFlags(e.lintersCmd.Flags()) e.EnabledLintersSet = lintersdb.NewEnabledSet(e.DBManager, lintersdb.NewValidator(e.DBManager), e.log.Child("lintersdb"), e.cfg) @@ -139,7 +139,7 @@ func NewExecutor(version, commit, date string) *Executor { if err = e.initHashSalt(version); err != nil { e.log.Fatalf("Failed to init hash salt: %s", err) } - e.debugf("Initialized executor") + e.debugf("Initialized executor in %s", time.Since(startedAt)) return e } @@ -191,27 +191,39 @@ func computeBinarySalt(version string) ([]byte, error) { } func computeConfigSalt(cfg *config.Config) ([]byte, error) { - configBytes, err := json.Marshal(cfg) + // We don't hash all config fields to reduce meaningless cache + // invalidations. At least, it has a huge impact on tests speed. + + lintersSettingsBytes, err := json.Marshal(cfg.LintersSettings) if err != nil { - return nil, errors.Wrap(err, "failed to json marshal config") + return nil, errors.Wrap(err, "failed to json marshal config linter settings") } + var configData bytes.Buffer + configData.WriteString("linters-settings=") + configData.Write(lintersSettingsBytes) + configData.WriteString("\nbuild-tags=%s" + strings.Join(cfg.Run.BuildTags, ",")) + h := sha256.New() - if n, err := h.Write(configBytes); n != len(configBytes) { - return nil, fmt.Errorf("failed to hash config bytes: wrote %d/%d bytes, error: %s", n, len(configBytes), err) - } + h.Write(configData.Bytes()) //nolint:errcheck return h.Sum(nil), nil } func (e *Executor) acquireFileLock() bool { + if e.cfg.Run.AllowParallelRunners { + e.debugf("Parallel runners are allowed, no locking") + return true + } + lockFile := filepath.Join(os.TempDir(), "golangci-lint.lock") e.debugf("Locking on file %s...", lockFile) f := flock.New(lockFile) - ctx, finish := context.WithTimeout(context.Background(), time.Minute) + const totalTimeout = 5 * time.Second + const retryDelay = time.Second + ctx, finish := context.WithTimeout(context.Background(), totalTimeout) defer finish() - timeout := time.Second * 3 - if ok, _ := f.TryLockContext(ctx, timeout); !ok { + if ok, _ := f.TryLockContext(ctx, retryDelay); !ok { return false } @@ -220,6 +232,10 @@ func (e *Executor) acquireFileLock() bool { } func (e *Executor) releaseFileLock() { + if e.cfg.Run.AllowParallelRunners { + return + } + if err := e.flock.Unlock(); err != nil { e.debugf("Failed to unlock on file: %s", err) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/commands/linters.go b/vendor/github.com/golangci/golangci-lint/pkg/commands/linters.go index 84452201945..873dab81770 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/commands/linters.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/commands/linters.go @@ -11,23 +11,13 @@ import ( ) func (e *Executor) initLinters() { - lintersCmd := &cobra.Command{ + e.lintersCmd = &cobra.Command{ Use: "linters", Short: "List current linters configuration", Run: e.executeLinters, } - e.rootCmd.AddCommand(lintersCmd) - e.initRunConfiguration(lintersCmd) -} - -func IsLinterInConfigsList(name string, linters []*linter.Config) bool { - for _, lc := range linters { - if lc.Name() == name { - return true - } - } - - return false + e.rootCmd.AddCommand(e.lintersCmd) + e.initRunConfiguration(e.lintersCmd) } func (e *Executor) executeLinters(_ *cobra.Command, args []string) { @@ -35,17 +25,21 @@ func (e *Executor) executeLinters(_ *cobra.Command, args []string) { e.log.Fatalf("Usage: golangci-lint linters") } - enabledLCs, err := e.EnabledLintersSet.Get(false) + enabledLintersMap, err := e.EnabledLintersSet.GetEnabledLintersMap() if err != nil { log.Fatalf("Can't get enabled linters: %s", err) } color.Green("Enabled by your configuration linters:\n") - printLinterConfigs(enabledLCs) + enabledLinters := make([]*linter.Config, 0, len(enabledLintersMap)) + for _, linter := range enabledLintersMap { + enabledLinters = append(enabledLinters, linter) + } + printLinterConfigs(enabledLinters) var disabledLCs []*linter.Config for _, lc := range e.DBManager.GetAllSupportedLinterConfigs() { - if !IsLinterInConfigsList(lc.Name(), enabledLCs) { + if enabledLintersMap[lc.Name()] == nil { disabledLCs = append(disabledLCs, lc) } } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/commands/root.go b/vendor/github.com/golangci/golangci-lint/pkg/commands/root.go index c8548cd7340..f90df9901ff 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/commands/root.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/commands/root.go @@ -73,7 +73,6 @@ func (e *Executor) persistentPostRun(_ *cobra.Command, _ []string) { trace.Stop() } - e.releaseFileLock() os.Exit(e.exitCode) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/commands/run.go b/vendor/github.com/golangci/golangci-lint/pkg/commands/run.go index 4149a00c4b0..92f0b175f0d 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/commands/run.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/commands/run.go @@ -80,7 +80,9 @@ func initFlagSet(fs *pflag.FlagSet, cfg *config.Config, m *lintersdb.Manager, is fs.BoolVar(&oc.PrintIssuedLine, "print-issued-lines", true, wh("Print lines of code with issue")) fs.BoolVar(&oc.PrintLinterName, "print-linter-name", true, wh("Print linter name in issue line")) fs.BoolVar(&oc.UniqByLine, "uniq-by-line", true, wh("Make issues output unique by line")) + fs.BoolVar(&oc.SortResults, "sort-results", false, wh("Sort linter results")) fs.BoolVar(&oc.PrintWelcomeMessage, "print-welcome", false, wh("Print welcome message")) + fs.StringVar(&oc.PathPrefix, "path-prefix", "", wh("Path prefix to add to output")) hideFlag("print-welcome") // no longer used // Run config @@ -106,6 +108,10 @@ func initFlagSet(fs *pflag.FlagSet, cfg *config.Config, m *lintersdb.Manager, is fs.BoolVar(&rc.UseDefaultSkipDirs, "skip-dirs-use-default", true, getDefaultDirectoryExcludeHelp()) fs.StringSliceVar(&rc.SkipFiles, "skip-files", nil, wh("Regexps of files to skip")) + const allowParallelDesc = "Allow multiple parallel golangci-lint instances running. " + + "If false (default) - golangci-lint acquires file lock on start." + fs.BoolVar(&rc.AllowParallelRunners, "allow-parallel-runners", false, wh(allowParallelDesc)) + // Linters settings config lsc := &cfg.LintersSettings @@ -251,6 +257,14 @@ func (e *Executor) initRun() { Use: "run", Short: welcomeMessage, Run: e.executeRun, + PreRun: func(_ *cobra.Command, _ []string) { + if ok := e.acquireFileLock(); !ok { + e.log.Fatalf("Parallel golangci-lint is running") + } + }, + PostRun: func(_ *cobra.Command, _ []string) { + e.releaseFileLock() + }, } e.rootCmd.AddCommand(e.runCmd) @@ -285,40 +299,34 @@ func fixSlicesFlags(fs *pflag.FlagSet) { func (e *Executor) runAnalysis(ctx context.Context, args []string) ([]result.Issue, error) { e.cfg.Run.Args = args - enabledLinters, err := e.EnabledLintersSet.Get(true) + lintersToRun, err := e.EnabledLintersSet.GetOptimizedLinters() if err != nil { return nil, err } - enabledOriginalLinters, err := e.EnabledLintersSet.Get(false) + enabledLintersMap, err := e.EnabledLintersSet.GetEnabledLintersMap() if err != nil { return nil, err } for _, lc := range e.DBManager.GetAllSupportedLinterConfigs() { - isEnabled := false - for _, enabledLC := range enabledOriginalLinters { - if enabledLC.Name() == lc.Name() { - isEnabled = true - break - } - } + isEnabled := enabledLintersMap[lc.Name()] != nil e.reportData.AddLinter(lc.Name(), isEnabled, lc.EnabledByDefault) } - lintCtx, err := e.contextLoader.Load(ctx, enabledLinters) + lintCtx, err := e.contextLoader.Load(ctx, lintersToRun) if err != nil { return nil, errors.Wrap(err, "context loading failed") } lintCtx.Log = e.log.Child("linters context") runner, err := lint.NewRunner(e.cfg, e.log.Child("runner"), - e.goenv, e.lineCache, e.DBManager, lintCtx.Packages) + e.goenv, e.EnabledLintersSet, e.lineCache, e.DBManager, lintCtx.Packages) if err != nil { return nil, err } - issues, err := runner.Run(ctx, enabledLinters, lintCtx) + issues, err := runner.Run(ctx, lintersToRun, lintCtx) if err != nil { return nil, err } @@ -440,8 +448,8 @@ func (e *Executor) executeRun(_ *cobra.Command, args []string) { // to be removed when deadline is finally decommissioned func (e *Executor) setTimeoutToDeadlineIfOnlyDeadlineIsSet() { - //lint:ignore SA1019 We want to promoted the deprecated config value when needed - deadlineValue := e.cfg.Run.Deadline // nolint:staticcheck + // nolint:staticcheck + deadlineValue := e.cfg.Run.Deadline if deadlineValue != 0 && e.cfg.Run.Timeout == defaultTimeout { e.cfg.Run.Timeout = deadlineValue } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/config/config.go b/vendor/github.com/golangci/golangci-lint/pkg/config/config.go index 2315f308c1c..69178580d2b 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/config/config.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/config/config.go @@ -40,7 +40,7 @@ var DefaultExcludePatterns = []ExcludePattern{ { ID: "EXC0001", Pattern: "Error return value of .((os\\.)?std(out|err)\\..*|.*Close" + - "|.*Flush|os\\.Remove(All)?|.*printf?|os\\.(Un)?Setenv). is not checked", + "|.*Flush|os\\.Remove(All)?|.*print(f|ln)?|os\\.(Un)?Setenv). is not checked", Linter: "errcheck", Why: "Almost all programs ignore errors on these functions and in most cases it's ok", }, @@ -150,6 +150,8 @@ type Run struct { SkipFiles []string `mapstructure:"skip-files"` SkipDirs []string `mapstructure:"skip-dirs"` UseDefaultSkipDirs bool `mapstructure:"skip-dirs-use-default"` + + AllowParallelRunners bool `mapstructure:"allow-parallel-runners"` } type LintersSettings struct { @@ -219,6 +221,10 @@ type LintersSettings struct { Recommendations []string `mapstructure:"recommendations"` Reason string `mapstructure:"reason"` } `mapstructure:"modules"` + Versions []map[string]struct { + Version string `mapstructure:"version"` + Reason string `mapstructure:"reason"` + } `mapstructure:"versions"` } `mapstructure:"blocked"` } @@ -233,13 +239,22 @@ type LintersSettings struct { Dogsled DogsledSettings Gocognit GocognitSettings Godot GodotSettings + Goheader GoHeaderSettings Testpackage TestpackageSettings Nestif NestifSettings NoLintLint NoLintLintSettings + Exhaustive ExhaustiveSettings + Gofumpt GofumptSettings Custom map[string]CustomLinterSettings } +type GoHeaderSettings struct { + Values map[string]map[string]string `mapstructure:"values"` + Template string `mapstructure:"template"` + TemplatePath string `mapstructure:"template-path"` +} + type GovetSettings struct { CheckShadowing bool `mapstructure:"check-shadowing"` Settings map[string]map[string]interface{} @@ -333,6 +348,14 @@ type NestifSettings struct { MinComplexity int `mapstructure:"min-complexity"` } +type ExhaustiveSettings struct { + DefaultSignifiesExhaustive bool `mapstructure:"default-signifies-exhaustive"` +} + +type GofumptSettings struct { + ExtraRules bool `mapstructure:"extra-rules"` +} + var defaultLintersSettings = LintersSettings{ Lll: LllSettings{ LineLength: 120, @@ -383,6 +406,12 @@ var defaultLintersSettings = LintersSettings{ Nestif: NestifSettings{ MinComplexity: 5, }, + Exhaustive: ExhaustiveSettings{ + DefaultSignifiesExhaustive: false, + }, + Gofumpt: GofumptSettings{ + ExtraRules: false, + }, } type CustomLinterSettings struct { @@ -401,51 +430,71 @@ type Linters struct { Presets []string } -type ExcludeRule struct { +type BaseRule struct { Linters []string Path string Text string Source string } -func validateOptionalRegex(value string) error { - if value == "" { - return nil - } - _, err := regexp.Compile(value) - return err -} - -func (e ExcludeRule) Validate() error { - if err := validateOptionalRegex(e.Path); err != nil { +func (b BaseRule) Validate(minConditionsCount int) error { + if err := validateOptionalRegex(b.Path); err != nil { return fmt.Errorf("invalid path regex: %v", err) } - if err := validateOptionalRegex(e.Text); err != nil { + if err := validateOptionalRegex(b.Text); err != nil { return fmt.Errorf("invalid text regex: %v", err) } - if err := validateOptionalRegex(e.Source); err != nil { + if err := validateOptionalRegex(b.Source); err != nil { return fmt.Errorf("invalid source regex: %v", err) } nonBlank := 0 - if len(e.Linters) > 0 { + if len(b.Linters) > 0 { nonBlank++ } - if e.Path != "" { + if b.Path != "" { nonBlank++ } - if e.Text != "" { + if b.Text != "" { nonBlank++ } - if e.Source != "" { + if b.Source != "" { nonBlank++ } - const minConditionsCount = 2 if nonBlank < minConditionsCount { - return errors.New("at least 2 of (text, source, path, linters) should be set") + return fmt.Errorf("at least %d of (text, source, path, linters) should be set", minConditionsCount) } return nil } +const excludeRuleMinConditionsCount = 2 + +type ExcludeRule struct { + BaseRule `mapstructure:",squash"` +} + +func validateOptionalRegex(value string) error { + if value == "" { + return nil + } + _, err := regexp.Compile(value) + return err +} + +func (e ExcludeRule) Validate() error { + return e.BaseRule.Validate(excludeRuleMinConditionsCount) +} + +const severityRuleMinConditionsCount = 1 + +type SeverityRule struct { + BaseRule `mapstructure:",squash"` + Severity string +} + +func (s *SeverityRule) Validate() error { + return s.BaseRule.Validate(severityRuleMinConditionsCount) +} + type Issues struct { IncludeDefaultExcludes []string `mapstructure:"include"` ExcludeCaseSensitive bool `mapstructure:"exclude-case-sensitive"` @@ -463,21 +512,30 @@ type Issues struct { NeedFix bool `mapstructure:"fix"` } +type Severity struct { + Default string `mapstructure:"default-severity"` + CaseSensitive bool `mapstructure:"case-sensitive"` + Rules []SeverityRule `mapstructure:"rules"` +} + type Config struct { Run Run Output struct { Format string Color string - PrintIssuedLine bool `mapstructure:"print-issued-lines"` - PrintLinterName bool `mapstructure:"print-linter-name"` - UniqByLine bool `mapstructure:"uniq-by-line"` - PrintWelcomeMessage bool `mapstructure:"print-welcome"` + PrintIssuedLine bool `mapstructure:"print-issued-lines"` + PrintLinterName bool `mapstructure:"print-linter-name"` + UniqByLine bool `mapstructure:"uniq-by-line"` + SortResults bool `mapstructure:"sort-results"` + PrintWelcomeMessage bool `mapstructure:"print-welcome"` + PathPrefix string `mapstructure:"path-prefix"` } LintersSettings LintersSettings `mapstructure:"linters-settings"` Linters Linters Issues Issues + Severity Severity InternalTest bool // Option is used only for testing golangci-lint code, don't use it } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/config/config_gocritic.go b/vendor/github.com/golangci/golangci-lint/pkg/config/config_gocritic.go index bbfd7bb1338..26317a678b5 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/config/config_gocritic.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/config/config_gocritic.go @@ -5,7 +5,7 @@ import ( "sort" "strings" - "github.com/go-lintpack/lintpack" + "github.com/go-critic/go-critic/framework/linter" "github.com/pkg/errors" _ "github.com/go-critic/go-critic/checkers" // this import register checkers @@ -18,9 +18,9 @@ const gocriticDebugKey = "gocritic" var ( gocriticDebugf = logutils.Debug(gocriticDebugKey) isGocriticDebug = logutils.HaveDebugTag(gocriticDebugKey) - allGocriticCheckers = lintpack.GetCheckersInfo() - allGocriticCheckerMap = func() map[string]*lintpack.CheckerInfo { - checkInfoMap := make(map[string]*lintpack.CheckerInfo) + allGocriticCheckers = linter.GetCheckersInfo() + allGocriticCheckerMap = func() map[string]*linter.CheckerInfo { + checkInfoMap := make(map[string]*linter.CheckerInfo) for _, checkInfo := range allGocriticCheckers { checkInfoMap[checkInfo.Name] = checkInfo } @@ -281,7 +281,7 @@ func getAllCheckerNames() map[string]bool { return allCheckerNames } -func isEnabledByDefaultGocriticCheck(info *lintpack.CheckerInfo) bool { +func isEnabledByDefaultGocriticCheck(info *linter.CheckerInfo) bool { return !info.HasTag("experimental") && !info.HasTag("opinionated") && !info.HasTag("performance") @@ -290,9 +290,6 @@ func isEnabledByDefaultGocriticCheck(info *lintpack.CheckerInfo) bool { func getDefaultEnabledGocriticCheckersNames() []string { var enabled []string for _, info := range allGocriticCheckers { - // get in sync with lintpack behavior in bindDefaultEnabledList - // in https://github.com/go-lintpack/lintpack/blob/master/linter/lintmain/internal/check/check.go#L317 - enable := isEnabledByDefaultGocriticCheck(info) if enable { enabled = append(enabled, info.Name) @@ -305,9 +302,6 @@ func getDefaultEnabledGocriticCheckersNames() []string { func getDefaultDisabledGocriticCheckersNames() []string { var disabled []string for _, info := range allGocriticCheckers { - // get in sync with lintpack behavior in bindDefaultEnabledList - // in https://github.com/go-lintpack/lintpack/blob/master/linter/lintmain/internal/check/check.go#L317 - enable := isEnabledByDefaultGocriticCheck(info) if !enable { disabled = append(disabled, info.Name) diff --git a/vendor/github.com/golangci/golangci-lint/pkg/config/reader.go b/vendor/github.com/golangci/golangci-lint/pkg/config/reader.go index 1e355e72213..e6b18a7a690 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/config/reader.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/config/reader.go @@ -113,6 +113,14 @@ func (r *FileReader) validateConfig() error { return fmt.Errorf("error in exclude rule #%d: %v", i, err) } } + if len(c.Severity.Rules) > 0 && c.Severity.Default == "" { + return errors.New("can't set severity rule option: no default severity defined") + } + for i, rule := range c.Severity.Rules { + if err := rule.Validate(); err != nil { + return fmt.Errorf("error in severity rule #%d: %v", i, err) + } + } if err := c.LintersSettings.Govet.Validate(); err != nil { return fmt.Errorf("error in govet config: %v", err) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl.go index eaac928e0aa..ed1c4fcbdc5 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/dupl.go @@ -34,7 +34,7 @@ func NewDupl() *goanalysis.Linter { analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { var fileNames []string for _, f := range pass.Files { - pos := pass.Fset.Position(f.Pos()) + pos := pass.Fset.PositionFor(f.Pos(), false) fileNames = append(fileNames, pos.Filename) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustive.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustive.go new file mode 100644 index 00000000000..cae37ecc61d --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/exhaustive.go @@ -0,0 +1,25 @@ +package golinters + +import ( + "github.com/nishanths/exhaustive" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" +) + +func NewExhaustive(settings *config.ExhaustiveSettings) *goanalysis.Linter { + a := exhaustive.Analyzer + + var cfg map[string]map[string]interface{} + if settings != nil { + cfg = map[string]map[string]interface{}{ + a.Name: { + exhaustive.DefaultSignifiesExhaustiveFlag: settings.DefaultSignifiesExhaustive, + }, + } + } + + return goanalysis.NewLinter(a.Name, a.Doc, []*analysis.Analyzer{a}, cfg). + WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/exportloopref.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/exportloopref.go new file mode 100644 index 00000000000..1131c575b95 --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/exportloopref.go @@ -0,0 +1,19 @@ +package golinters + +import ( + "github.com/kyoh86/exportloopref" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" +) + +func NewExportLoopRef() *goanalysis.Linter { + a := exportloopref.Analyzer + + return goanalysis.NewLinter( + a.Name, + a.Doc, + []*analysis.Analyzer{a}, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load/guard.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load/guard.go index 5695f717eb9..ab7775cc806 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load/guard.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/load/guard.go @@ -7,9 +7,8 @@ import ( ) type Guard struct { - loadMutexes map[*packages.Package]*sync.Mutex - mutexForExportData sync.Mutex - mutex sync.Mutex + loadMutexes map[*packages.Package]*sync.Mutex + mutex sync.Mutex } func NewGuard() *Guard { @@ -26,10 +25,6 @@ func (g *Guard) MutexForPkg(pkg *packages.Package) *sync.Mutex { return g.loadMutexes[pkg] } -func (g *Guard) MutexForExportData() *sync.Mutex { - return &g.mutexForExportData -} - func (g *Guard) Mutex() *sync.Mutex { return &g.mutex } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner.go index 64087c2833e..db193f37bb2 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/goanalysis/runner.go @@ -384,26 +384,6 @@ func extractDiagnostics(roots []*action) (retDiags []Diagnostic, retErrors []err return } -// NeedFacts reports whether any analysis required by the specified set -// needs facts. If so, we must load the entire program from source. -func NeedFacts(analyzers []*analysis.Analyzer) bool { - seen := make(map[*analysis.Analyzer]bool) - var q []*analysis.Analyzer // for BFS - q = append(q, analyzers...) - for len(q) > 0 { - a := q[0] - q = q[1:] - if !seen[a] { - seen[a] = true - if len(a.FactTypes) > 0 { - return true - } - q = append(q, a.Requires...) - } - } - return false -} - // An action represents one unit of analysis work: the application of // one analysis to one package. Actions form a DAG, both within a // package (as different analyzers are applied, either in sequence or @@ -955,7 +935,8 @@ func sizeOfReflectValueTreeBytes(rv reflect.Value, visitedPtrs map[uintptr]struc return rv.Len() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Uintptr, reflect.Bool, reflect.Float32, reflect.Float64, reflect.UnsafePointer: + reflect.Uintptr, reflect.Bool, reflect.Float32, reflect.Float64, + reflect.Complex64, reflect.Complex128, reflect.Func, reflect.UnsafePointer: return int(rv.Type().Size()) case reflect.Invalid: return 0 @@ -964,7 +945,7 @@ func sizeOfReflectValueTreeBytes(rv reflect.Value, visitedPtrs map[uintptr]struc } } -func (lp *loadingPackage) decUse() { +func (lp *loadingPackage) decUse(canClearTypes bool) { lp.decUseMutex.Lock() defer lp.decUseMutex.Unlock() @@ -1007,11 +988,17 @@ func (lp *loadingPackage) decUse() { return } - lp.pkg.Types = nil + if canClearTypes { + // canClearTypes is set to true if we can discard type + // information after the package and its dependents have been + // processed. This is the case when no whole program checkers (unused) are + // being run. + lp.pkg.Types = nil + } lp.pkg = nil for _, imp := range lp.imports { - imp.decUse() + imp.decUse(canClearTypes) } lp.imports = nil @@ -1047,12 +1034,8 @@ func (lp *loadingPackage) analyze(loadMode LoadMode, loadSem chan struct{}) { <-loadSem }() - defer func() { - if loadMode < LoadModeWholeProgram { - // Save memory on unused more fields. - lp.decUse() - } - }() + // Save memory on unused more fields. + defer lp.decUse(loadMode < LoadModeWholeProgram) if err := lp.loadWithFacts(loadMode); err != nil { werr := errors.Wrapf(err, "failed to load package %s", lp.pkg.Name) @@ -1168,22 +1151,6 @@ func (lp *loadingPackage) loadFromSource(loadMode LoadMode) error { } func (lp *loadingPackage) loadFromExportData() error { - // Because gcexportdata.Read has the potential to create or - // modify the types.Package for each node in the transitive - // closure of dependencies of lpkg, all exportdata operations - // must be sequential. (Finer-grained locking would require - // changes to the gcexportdata API.) - // - // The exportMu lock guards the Package.Pkg field and the - // types.Package it points to, for each Package in the graph. - // - // Not all accesses to Package.Pkg need to be protected by this mutex: - // graph ordering ensures that direct dependencies of source - // packages are fully loaded before the importer reads their Pkg field. - mu := lp.loadGuard.MutexForExportData() - mu.Lock() - defer mu.Unlock() - pkg := lp.pkg // Call NewPackage directly with explicit name. diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit.go index 8044e3e51d0..78afff86c59 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocognit.go @@ -39,7 +39,7 @@ func NewGocognit() *goanalysis.Linter { return nil, nil } - sort.Slice(stats, func(i, j int) bool { + sort.SliceStable(stats, func(i, j int) bool { return stats[i].Complexity > stats[j].Complexity }) diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic.go index fb29252096b..7181c48637d 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocritic.go @@ -10,7 +10,7 @@ import ( "strings" "sync" - "github.com/go-lintpack/lintpack" + gocriticlinter "github.com/go-critic/go-critic/framework/linter" "golang.org/x/tools/go/analysis" "github.com/golangci/golangci-lint/pkg/config" @@ -38,15 +38,15 @@ func NewGocritic() *goanalysis.Linter { nil, ).WithContextSetter(func(lintCtx *linter.Context) { analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - lintpackCtx := lintpack.NewContext(pass.Fset, sizes) - enabledCheckers, err := buildEnabledCheckers(lintCtx, lintpackCtx) + linterCtx := gocriticlinter.NewContext(pass.Fset, sizes) + enabledCheckers, err := buildEnabledCheckers(lintCtx, linterCtx) if err != nil { return nil, err } - lintpackCtx.SetPackageInfo(pass.TypesInfo, pass.Pkg) + linterCtx.SetPackageInfo(pass.TypesInfo, pass.Pkg) var res []goanalysis.Issue - pkgIssues := runGocriticOnPackage(lintpackCtx, enabledCheckers, pass.Files) + pkgIssues := runGocriticOnPackage(linterCtx, enabledCheckers, pass.Files) for i := range pkgIssues { res = append(res, goanalysis.NewIssue(&pkgIssues[i], pass)) } @@ -65,9 +65,9 @@ func NewGocritic() *goanalysis.Linter { }).WithLoadMode(goanalysis.LoadModeTypesInfo) } -func normalizeCheckerInfoParams(info *lintpack.CheckerInfo) lintpack.CheckerParams { +func normalizeCheckerInfoParams(info *gocriticlinter.CheckerInfo) gocriticlinter.CheckerParams { // lowercase info param keys here because golangci-lint's config parser lowercases all strings - ret := lintpack.CheckerParams{} + ret := gocriticlinter.CheckerParams{} for k, v := range info.Params { ret[strings.ToLower(k)] = v } @@ -75,7 +75,7 @@ func normalizeCheckerInfoParams(info *lintpack.CheckerInfo) lintpack.CheckerPara return ret } -func configureCheckerInfo(info *lintpack.CheckerInfo, allParams map[string]config.GocriticCheckSettings) error { +func configureCheckerInfo(info *gocriticlinter.CheckerInfo, allParams map[string]config.GocriticCheckSettings) error { params := allParams[strings.ToLower(info.Name)] if params == nil { // no config for this checker return nil @@ -108,12 +108,12 @@ func configureCheckerInfo(info *lintpack.CheckerInfo, allParams map[string]confi return nil } -func buildEnabledCheckers(lintCtx *linter.Context, lintpackCtx *lintpack.Context) ([]*lintpack.Checker, error) { +func buildEnabledCheckers(lintCtx *linter.Context, linterCtx *gocriticlinter.Context) ([]*gocriticlinter.Checker, error) { s := lintCtx.Settings().Gocritic allParams := s.GetLowercasedParams() - var enabledCheckers []*lintpack.Checker - for _, info := range lintpack.GetCheckersInfo() { + var enabledCheckers []*gocriticlinter.Checker + for _, info := range gocriticlinter.GetCheckersInfo() { if !s.IsCheckEnabled(info.Name) { continue } @@ -122,27 +122,27 @@ func buildEnabledCheckers(lintCtx *linter.Context, lintpackCtx *lintpack.Context return nil, err } - c := lintpack.NewChecker(lintpackCtx, info) + c := gocriticlinter.NewChecker(linterCtx, info) enabledCheckers = append(enabledCheckers, c) } return enabledCheckers, nil } -func runGocriticOnPackage(lintpackCtx *lintpack.Context, checkers []*lintpack.Checker, +func runGocriticOnPackage(linterCtx *gocriticlinter.Context, checkers []*gocriticlinter.Checker, files []*ast.File) []result.Issue { var res []result.Issue for _, f := range files { - filename := filepath.Base(lintpackCtx.FileSet.Position(f.Pos()).Filename) - lintpackCtx.SetFileInfo(filename, f) + filename := filepath.Base(linterCtx.FileSet.Position(f.Pos()).Filename) + linterCtx.SetFileInfo(filename, f) - issues := runGocriticOnFile(lintpackCtx, f, checkers) + issues := runGocriticOnFile(linterCtx, f, checkers) res = append(res, issues...) } return res } -func runGocriticOnFile(ctx *lintpack.Context, f *ast.File, checkers []*lintpack.Checker) []result.Issue { +func runGocriticOnFile(ctx *gocriticlinter.Context, f *ast.File, checkers []*gocriticlinter.Checker) []result.Issue { var res []result.Issue for _, c := range checkers { diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo.go index f9c0a799348..55f13fcfed2 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gocyclo.go @@ -39,7 +39,7 @@ func NewGocyclo() *goanalysis.Linter { return nil, nil } - sort.Slice(stats, func(i, j int) bool { + sort.SliceStable(stats, func(i, j int) bool { return stats[i].Complexity > stats[j].Complexity }) diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot.go index 842ec97d26e..5139713c4af 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/godot.go @@ -31,7 +31,7 @@ func NewGodot() *goanalysis.Linter { settings := godot.Settings{CheckAll: cfg.CheckAll} analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { - var issues []godot.Message + var issues []godot.Issue for _, file := range pass.Files { issues = append(issues, godot.Run(file, pass.Fset, settings)...) } @@ -43,10 +43,12 @@ func NewGodot() *goanalysis.Linter { res := make([]goanalysis.Issue, len(issues)) for k, i := range issues { issue := result.Issue{ - Pos: i.Pos, - Text: i.Message, - FromLinter: godotName, - Replacement: &result.Replacement{}, + Pos: i.Pos, + Text: i.Message, + FromLinter: godotName, + Replacement: &result.Replacement{ + NewLines: []string{i.Replacement}, + }, } res[k] = goanalysis.NewIssue(&issue, pass) diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt.go index e71f27bb171..aa340dcf3c4 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt.go @@ -31,7 +31,7 @@ func NewGofmt() *goanalysis.Linter { analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { var fileNames []string for _, f := range pass.Files { - pos := pass.Fset.Position(f.Pos()) + pos := pass.Fset.PositionFor(f.Pos(), false) fileNames = append(fileNames, pos.Filename) } @@ -46,7 +46,7 @@ func NewGofmt() *goanalysis.Linter { continue } - is, err := extractIssuesFromPatch(string(diff), lintCtx.Log, lintCtx, false) + is, err := extractIssuesFromPatch(string(diff), lintCtx.Log, lintCtx, gofmtName) if err != nil { return nil, errors.Wrapf(err, "can't extract issues from gofmt diff output %q", string(diff)) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt_common.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt_common.go index fb1e3f6623f..afb0d0c1bcc 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt_common.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofmt_common.go @@ -207,7 +207,29 @@ func (p *hunkChangesParser) parse(h *diffpkg.Hunk) []Change { return p.ret } -func extractIssuesFromPatch(patch string, log logutils.Log, lintCtx *linter.Context, isGoimports bool) ([]result.Issue, error) { +func getErrorTextForLinter(lintCtx *linter.Context, linterName string) string { + text := "File is not formatted" + switch linterName { + case gofumptName: + text = "File is not `gofumpt`-ed" + if lintCtx.Settings().Gofumpt.ExtraRules { + text += " with `-extra`" + } + case gofmtName: + text = "File is not `gofmt`-ed" + if lintCtx.Settings().Gofmt.Simplify { + text += " with `-s`" + } + case goimportsName: + text = "File is not `goimports`-ed" + if lintCtx.Settings().Goimports.LocalPrefixes != "" { + text += " with -local " + lintCtx.Settings().Goimports.LocalPrefixes + } + } + return text +} + +func extractIssuesFromPatch(patch string, log logutils.Log, lintCtx *linter.Context, linterName string) ([]result.Issue, error) { diffs, err := diffpkg.ParseMultiFileDiff([]byte(patch)) if err != nil { return nil, errors.Wrap(err, "can't parse patch") @@ -225,35 +247,19 @@ func extractIssuesFromPatch(patch string, log logutils.Log, lintCtx *linter.Cont } for _, hunk := range d.Hunks { - var text string - if isGoimports { - text = "File is not `goimports`-ed" - if lintCtx.Settings().Goimports.LocalPrefixes != "" { - text += " with -local " + lintCtx.Settings().Goimports.LocalPrefixes - } - } else { - text = "File is not `gofmt`-ed" - if lintCtx.Settings().Gofmt.Simplify { - text += " with `-s`" - } - } p := hunkChangesParser{ log: log, } changes := p.parse(hunk) for _, change := range changes { change := change // fix scope - linterName := gofmtName - if isGoimports { - linterName = goimportsName - } i := result.Issue{ FromLinter: linterName, Pos: token.Position{ Filename: d.NewName, Line: change.LineRange.From, }, - Text: text, + Text: getErrorTextForLinter(lintCtx, linterName), Replacement: &change.Replacement, } if change.LineRange.From != change.LineRange.To { diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofumpt.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofumpt.go new file mode 100644 index 00000000000..e91e54eeafc --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gofumpt.go @@ -0,0 +1,92 @@ +package golinters + +import ( + "bytes" + "fmt" + "io/ioutil" + "sync" + + "github.com/pkg/errors" + "github.com/shazow/go-diff/difflib" + "golang.org/x/tools/go/analysis" + "mvdan.cc/gofumpt/format" + + "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/lint/linter" +) + +const gofumptName = "gofumpt" + +func NewGofumpt() *goanalysis.Linter { + var mu sync.Mutex + var resIssues []goanalysis.Issue + differ := difflib.New() + + analyzer := &analysis.Analyzer{ + Name: gofumptName, + Doc: goanalysis.TheOnlyanalyzerDoc, + } + return goanalysis.NewLinter( + gofumptName, + "Gofumpt checks whether code was gofumpt-ed.", + []*analysis.Analyzer{analyzer}, + nil, + ).WithContextSetter(func(lintCtx *linter.Context) { + analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { + var fileNames []string + for _, f := range pass.Files { + pos := pass.Fset.PositionFor(f.Pos(), false) + fileNames = append(fileNames, pos.Filename) + } + + var issues []goanalysis.Issue + + for _, f := range fileNames { + input, err := ioutil.ReadFile(f) + if err != nil { + return nil, fmt.Errorf("unable to open file %s: %w", f, err) + } + output, err := format.Source(input, format.Options{ + ExtraRules: lintCtx.Settings().Gofumpt.ExtraRules, + }) + if err != nil { + return nil, fmt.Errorf("error while running gofumpt: %w", err) + } + if !bytes.Equal(input, output) { + out := bytes.Buffer{} + _, err = out.WriteString(fmt.Sprintf("--- %[1]s\n+++ %[1]s\n", f)) + if err != nil { + return nil, fmt.Errorf("error while running gofumpt: %w", err) + } + + err = differ.Diff(&out, bytes.NewReader(input), bytes.NewReader(output)) + if err != nil { + return nil, fmt.Errorf("error while running gofumpt: %w", err) + } + + diff := out.String() + is, err := extractIssuesFromPatch(diff, lintCtx.Log, lintCtx, gofumptName) + if err != nil { + return nil, errors.Wrapf(err, "can't extract issues from gofumpt diff output %q", diff) + } + + for i := range is { + issues = append(issues, goanalysis.NewIssue(&is[i], pass)) + } + } + } + + if len(issues) == 0 { + return nil, nil + } + + mu.Lock() + resIssues = append(resIssues, issues...) + mu.Unlock() + + return nil, nil + } + }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return resIssues + }).WithLoadMode(goanalysis.LoadModeSyntax) +} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/goheader.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/goheader.go new file mode 100644 index 00000000000..8517e173d3f --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/goheader.go @@ -0,0 +1,81 @@ +package golinters + +import ( + "go/token" + "sync" + + goheader "github.com/denis-tingajkin/go-header" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" + "github.com/golangci/golangci-lint/pkg/lint/linter" + "github.com/golangci/golangci-lint/pkg/result" +) + +const goHeaderName = "goheader" + +func NewGoHeader() *goanalysis.Linter { + var mu sync.Mutex + var issues []goanalysis.Issue + + analyzer := &analysis.Analyzer{ + Name: goHeaderName, + Doc: goanalysis.TheOnlyanalyzerDoc, + } + return goanalysis.NewLinter( + goHeaderName, + "Checks is file header matches to pattern", + []*analysis.Analyzer{analyzer}, + nil, + ).WithContextSetter(func(lintCtx *linter.Context) { + cfg := lintCtx.Cfg.LintersSettings.Goheader + c := &goheader.Configuration{ + Values: cfg.Values, + Template: cfg.Template, + TemplatePath: cfg.TemplatePath, + } + analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { + if c.TemplatePath == "" && c.Template == "" { + // User did not pass template, so then do not run go-header linter + return nil, nil + } + template, err := c.GetTemplate() + if err != nil { + return nil, err + } + values, err := c.GetValues() + if err != nil { + return nil, err + } + a := goheader.New(goheader.WithTemplate(template), goheader.WithValues(values)) + var res []goanalysis.Issue + for _, file := range pass.Files { + i := a.Analyze(file) + if i == nil { + continue + } + issue := result.Issue{ + Pos: token.Position{ + Line: i.Location().Line + 1, + Column: i.Location().Position, + Filename: pass.Fset.Position(file.Pos()).Filename, + }, + Text: i.Message(), + FromLinter: goHeaderName, + } + res = append(res, goanalysis.NewIssue(&issue, pass)) + } + if len(res) == 0 { + return nil, nil + } + + mu.Lock() + issues = append(issues, res...) + mu.Unlock() + + return nil, nil + } + }).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue { + return issues + }).WithLoadMode(goanalysis.LoadModeSyntax) +} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports.go index 90e19b0e85d..9ea4558f40c 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/goimports.go @@ -32,7 +32,7 @@ func NewGoimports() *goanalysis.Linter { analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { var fileNames []string for _, f := range pass.Files { - pos := pass.Fset.Position(f.Pos()) + pos := pass.Fset.PositionFor(f.Pos(), false) fileNames = append(fileNames, pos.Filename) } @@ -47,7 +47,7 @@ func NewGoimports() *goanalysis.Linter { continue } - is, err := extractIssuesFromPatch(string(diff), lintCtx.Log, lintCtx, true) + is, err := extractIssuesFromPatch(string(diff), lintCtx.Log, lintCtx, goimportsName) if err != nil { return nil, errors.Wrapf(err, "can't extract issues from gofmt diff output %q", string(diff)) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard.go index 29cc3c303ab..1376ad1572b 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gomodguard.go @@ -30,7 +30,9 @@ func NewGomodguard() *goanalysis.Linter { return goanalysis.NewLinter( gomodguardName, - "Allow and block list linter for direct Go module dependencies.", + "Allow and block list linter for direct Go module dependencies. "+ + "This is different from depguard where there are different block "+ + "types for example version constraints and module recommendations.", []*analysis.Analyzer{analyzer}, nil, ).WithContextSetter(func(lintCtx *linter.Context) { @@ -44,7 +46,7 @@ func NewGomodguard() *goanalysis.Linter { processorCfg.Allowed.Domains = linterCfg.Allowed.Domains for n := range linterCfg.Blocked.Modules { for k, v := range linterCfg.Blocked.Modules[n] { - m := gomodguard.BlockedModule{k: gomodguard.Recommendations{ + m := map[string]gomodguard.BlockedModule{k: { Recommendations: v.Recommendations, Reason: v.Reason, }} @@ -53,8 +55,19 @@ func NewGomodguard() *goanalysis.Linter { } } + for n := range linterCfg.Blocked.Versions { + for k, v := range linterCfg.Blocked.Versions[n] { + m := map[string]gomodguard.BlockedVersion{k: { + Version: v.Version, + Reason: v.Reason, + }} + processorCfg.Blocked.Versions = append(processorCfg.Blocked.Versions, m) + break + } + } + for _, file := range pass.Files { - files = append(files, pass.Fset.Position(file.Pos()).Filename) + files = append(files, pass.Fset.PositionFor(file.Pos(), false).Filename) } processor, err := gomodguard.NewProcessor(processorCfg, log.New(os.Stderr, "", 0)) diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec.go index 974429583b9..08b3e660f8c 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/gosec.go @@ -8,8 +8,8 @@ import ( "strconv" "sync" - "github.com/securego/gosec" - "github.com/securego/gosec/rules" + "github.com/securego/gosec/v2" + "github.com/securego/gosec/v2/rules" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/packages" diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/ineffassign.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/ineffassign.go index 601252f729a..93c1fb11bbb 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/ineffassign.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/ineffassign.go @@ -31,7 +31,7 @@ func NewIneffassign() *goanalysis.Linter { analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { var fileNames []string for _, f := range pass.Files { - pos := pass.Fset.Position(f.Pos()) + pos := pass.Fset.PositionFor(f.Pos(), false) fileNames = append(fileNames, pos.Filename) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll.go index c24b4d14814..5f26e91ddbf 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/lll.go @@ -92,7 +92,7 @@ func NewLLL() *goanalysis.Linter { analyzer.Run = func(pass *analysis.Pass) (interface{}, error) { var fileNames []string for _, f := range pass.Files { - pos := pass.Fset.Position(f.Pos()) + pos := pass.Fset.PositionFor(f.Pos(), false) fileNames = append(fileNames, pos.Filename) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell.go index 6cd421e5e93..80ecf9bb668 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/misspell.go @@ -102,7 +102,7 @@ func NewMisspell() *goanalysis.Linter { var fileNames []string for _, f := range pass.Files { - pos := pass.Fset.Position(f.Pos()) + pos := pass.Fset.PositionFor(f.Pos(), false) fileNames = append(fileNames, pos.Filename) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx.go new file mode 100644 index 00000000000..b5c4a4be240 --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/noctx.go @@ -0,0 +1,21 @@ +package golinters + +import ( + "github.com/sonatard/noctx" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" +) + +func NewNoctx() *goanalysis.Linter { + analyzers := []*analysis.Analyzer{ + noctx.Analyzer, + } + + return goanalysis.NewLinter( + "noctx", + "noctx finds sending http request without context.Context", + analyzers, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck.go new file mode 100644 index 00000000000..48ca246e70a --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/sqlclosecheck.go @@ -0,0 +1,21 @@ +package golinters + +import ( + "github.com/ryanrolds/sqlclosecheck/pkg/analyzer" + "golang.org/x/tools/go/analysis" + + "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" +) + +func NewSQLCloseCheck() *goanalysis.Linter { + analyzers := []*analysis.Analyzer{ + analyzer.NewAnalyzer(), + } + + return goanalysis.NewLinter( + "sqlclosecheck", + "Checks that sql.Rows and sql.Stmt are closed.", + analyzers, + nil, + ).WithLoadMode(goanalysis.LoadModeTypesInfo) +} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused.go index ac5a90d4185..bbe1e4b6903 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/unused.go @@ -55,7 +55,10 @@ func NewUnused() *goanalysis.Linter { } return issues }).WithContextSetter(func(lintCtx *linter.Context) { - u.WholeProgram = lintCtx.Settings().Unused.CheckExported + if lintCtx.Settings().Unused.CheckExported { + lintCtx.Log.Infof("Using whole program analysis for unused, it can be memory-heavy") + u.WholeProgram = true + } }).WithLoadMode(goanalysis.LoadModeWholeProgram) lnt.UseOriginalPackages() return lnt diff --git a/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl.go b/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl.go index f44d09f245c..ca659ac4e0e 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/golinters/wsl.go @@ -52,7 +52,7 @@ func NewWSL() *goanalysis.Linter { ) for _, file := range pass.Files { - files = append(files, pass.Fset.Position(file.Pos()).Filename) + files = append(files, pass.Fset.PositionFor(file.Pos(), false).Filename) } wslErrors, _ := wsl.NewProcessorWithConfig(processorCfg). diff --git a/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/config.go b/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/config.go index 52ff9b90d43..4ec835254f7 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/config.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/lint/linter/config.go @@ -22,9 +22,10 @@ type Config struct { InPresets []string AlternativeNames []string - OriginalURL string // URL of original (not forked) repo, needed for autogenerated README - CanAutoFix bool - IsSlow bool + OriginalURL string // URL of original (not forked) repo, needed for autogenerated README + CanAutoFix bool + IsSlow bool + DoesChangeTypes bool } func (lc *Config) ConsiderSlow() *Config { @@ -67,6 +68,11 @@ func (lc *Config) WithAutoFix() *Config { return lc } +func (lc *Config) WithChangeTypes() *Config { + lc.DoesChangeTypes = true + return lc +} + func (lc *Config) AllNames() []string { return append([]string{lc.Name()}, lc.AlternativeNames...) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/enabled_set.go b/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/enabled_set.go index 73e3bcfed29..eced95f6552 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/enabled_set.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/enabled_set.go @@ -1,7 +1,9 @@ package lintersdb import ( + "os" "sort" + "strings" "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/golinters/goanalysis" @@ -28,6 +30,7 @@ func NewEnabledSet(m *Manager, v *Validator, log logutils.Log, cfg *config.Confi } func (es EnabledSet) build(lcfg *config.Linters, enabledByDefaultLinters []*linter.Config) map[string]*linter.Config { + es.debugf("Linters config: %#v", lcfg) resultLintersSet := map[string]*linter.Config{} switch { case len(lcfg.Presets) != 0: @@ -76,22 +79,44 @@ func (es EnabledSet) build(lcfg *config.Linters, enabledByDefaultLinters []*lint return resultLintersSet } -func (es EnabledSet) Get(optimize bool) ([]*linter.Config, error) { +func (es EnabledSet) GetEnabledLintersMap() (map[string]*linter.Config, error) { + if err := es.v.validateEnabledDisabledLintersConfig(&es.cfg.Linters); err != nil { + return nil, err + } + + enabledLinters := es.build(&es.cfg.Linters, es.m.GetAllEnabledByDefaultLinters()) + if os.Getenv("GL_TEST_RUN") == "1" { + es.verbosePrintLintersStatus(enabledLinters) + } + return enabledLinters, nil +} + +// GetOptimizedLinters returns enabled linters after optimization (merging) of multiple linters +// into a fewer number of linters. E.g. some go/analysis linters can be optimized into +// one metalinter for data reuse and speed up. +func (es EnabledSet) GetOptimizedLinters() ([]*linter.Config, error) { if err := es.v.validateEnabledDisabledLintersConfig(&es.cfg.Linters); err != nil { return nil, err } resultLintersSet := es.build(&es.cfg.Linters, es.m.GetAllEnabledByDefaultLinters()) es.verbosePrintLintersStatus(resultLintersSet) - if optimize { - es.combineGoAnalysisLinters(resultLintersSet) - } + es.combineGoAnalysisLinters(resultLintersSet) var resultLinters []*linter.Config for _, lc := range resultLintersSet { resultLinters = append(resultLinters, lc) } + // Make order of execution of linters (go/analysis metalinter and unused) stable. + sort.Slice(resultLinters, func(i, j int) bool { + a, b := resultLinters[i], resultLinters[j] + if a.DoesChangeTypes != b.DoesChangeTypes { + return b.DoesChangeTypes // move type-changing linters to the end to optimize speed + } + return strings.Compare(a.Name(), b.Name()) < 0 + }) + return resultLinters, nil } @@ -122,6 +147,10 @@ func (es EnabledSet) combineGoAnalysisLinters(linters map[string]*linter.Config) delete(linters, lnt.Name()) } + // Make order of execution of go/analysis analyzers stable. + sort.Slice(goanalysisLinters, func(i, j int) bool { + return strings.Compare(goanalysisLinters[i].Name(), goanalysisLinters[j].Name()) <= 0 + }) ml := goanalysis.NewMetaLinter(goanalysisLinters) var presets []string diff --git a/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/manager.go b/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/manager.go index 492b92256f6..d988fb067c9 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/manager.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/manager.go @@ -87,9 +87,11 @@ func enableLinterConfigs(lcs []*linter.Config, isEnabled func(lc *linter.Config) func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { var govetCfg *config.GovetSettings var testpackageCfg *config.TestpackageSettings + var exhaustiveCfg *config.ExhaustiveSettings if m.cfg != nil { govetCfg = &m.cfg.LintersSettings.Govet testpackageCfg = &m.cfg.LintersSettings.Testpackage + exhaustiveCfg = &m.cfg.LintersSettings.Exhaustive } const megacheckName = "megacheck" lcs := []*linter.Config{ @@ -102,6 +104,10 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithLoadForGoAnalysis(). WithPresets(linter.PresetPerformance, linter.PresetBugs). WithURL("https://github.com/timakin/bodyclose"), + linter.NewConfig(golinters.NewNoctx()). + WithLoadForGoAnalysis(). + WithPresets(linter.PresetPerformance, linter.PresetBugs). + WithURL("https://github.com/sonatard/noctx"), linter.NewConfig(golinters.NewErrcheck()). WithLoadForGoAnalysis(). WithPresets(linter.PresetBugs). @@ -125,6 +131,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithPresets(linter.PresetUnused). WithAlternativeNames(megacheckName). ConsiderSlow(). + WithChangeTypes(). WithURL("https://github.com/dominikh/go-tools/tree/master/unused"), linter.NewConfig(golinters.NewGosimple()). WithLoadForGoAnalysis(). @@ -188,10 +195,17 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithPresets(linter.PresetFormatting). WithAutoFix(). WithURL("https://golang.org/cmd/gofmt/"), + linter.NewConfig(golinters.NewGofumpt()). + WithPresets(linter.PresetFormatting). + WithURL("https://github.com/mvdan/gofumpt"), linter.NewConfig(golinters.NewGoimports()). WithPresets(linter.PresetFormatting). WithAutoFix(). WithURL("https://godoc.org/golang.org/x/tools/cmd/goimports"), + linter.NewConfig(golinters.NewGoHeader()). + WithPresets(linter.PresetStyle). + WithLoadForGoAnalysis(). + WithURL("https://github.com/denis-tingajkin/go-header"), linter.NewConfig(golinters.NewMaligned()). WithLoadForGoAnalysis(). WithPresets(linter.PresetPerformance). @@ -254,6 +268,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithURL("https://github.com/tommy-muehle/go-mnd"), linter.NewConfig(golinters.NewGoerr113()). WithPresets(linter.PresetStyle). + WithLoadForGoAnalysis(). WithURL("https://github.com/Djarvur/go-err113"), linter.NewConfig(golinters.NewGomodguard()). WithPresets(linter.PresetStyle). @@ -261,6 +276,7 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { WithURL("https://github.com/ryancurrah/gomodguard"), linter.NewConfig(golinters.NewGodot()). WithPresets(linter.PresetStyle). + WithAutoFix(). WithURL("https://github.com/tetafro/godot"), linter.NewConfig(golinters.NewTestpackage(testpackageCfg)). WithPresets(linter.PresetStyle). @@ -269,10 +285,21 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config { linter.NewConfig(golinters.NewNestif()). WithPresets(linter.PresetComplexity). WithURL("https://github.com/nakabonne/nestif"), + linter.NewConfig(golinters.NewExportLoopRef()). + WithPresets(linter.PresetBugs). + WithURL("https://github.com/kyoh86/exportloopref"), + linter.NewConfig(golinters.NewExhaustive(exhaustiveCfg)). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/nishanths/exhaustive"), + linter.NewConfig(golinters.NewSQLCloseCheck()). + WithPresets(linter.PresetBugs). + WithLoadForGoAnalysis(). + WithURL("https://github.com/ryanrolds/sqlclosecheck"), // nolintlint must be last because it looks at the results of all the previous linters for unused nolint directives linter.NewConfig(golinters.NewNoLintLint()). WithPresets(linter.PresetStyle). - WithURL("https://github.com/golangci-lint/pkg/golinters/nolintlint"), + WithURL("https://github.com/golangci/golangci-lint/blob/master/pkg/golinters/nolintlint/README.md"), } isLocalRun := os.Getenv("GOLANGCI_COM_RUN") == "" diff --git a/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/validator.go b/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/validator.go index d7e3699c851..dead59657ab 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/validator.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/lint/lintersdb/validator.go @@ -22,7 +22,7 @@ func (v Validator) validateLintersNames(cfg *config.Linters) error { allNames = append(allNames, cfg.Disable...) for _, name := range allNames { if v.m.GetLinterConfigs(name) == nil { - return fmt.Errorf("no such linter %q", name) + return fmt.Errorf("no such linter %v, run 'golangci-lint linters' to see the list of supported linters", name) } } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/lint/load.go b/vendor/github.com/golangci/golangci-lint/pkg/lint/load.go index de0ab4117c3..3525396bc56 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/lint/load.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/lint/load.go @@ -98,6 +98,7 @@ func (cl *ContextLoader) makeBuildFlags() ([]string, error) { if len(cl.cfg.Run.BuildTags) != 0 { // go help build buildFlags = append(buildFlags, "-tags", strings.Join(cl.cfg.Run.BuildTags, " ")) + cl.log.Infof("Using build tags: %v", cl.cfg.Run.BuildTags) } mod := cl.cfg.Run.ModulesDownloadMode @@ -198,7 +199,14 @@ func (cl *ContextLoader) loadPackages(ctx context.Context, loadMode packages.Loa cl.debugf("Built loader args are %s", args) pkgs, err := packages.Load(conf, args...) if err != nil { - return nil, errors.Wrap(err, "failed to load program with go/packages") + return nil, errors.Wrap(err, "failed to load with go/packages") + } + + // Currently, go/packages doesn't guarantee that error will be returned + // if context was canceled. See + // https://github.com/golang/tools/commit/c5cec6710e927457c3c29d6c156415e8539a5111#r39261855 + if ctx.Err() != nil { + return nil, errors.Wrap(ctx.Err(), "timed out to load packages") } if loadMode&packages.NeedSyntax == 0 { @@ -279,7 +287,7 @@ func (cl *ContextLoader) Load(ctx context.Context, linters []*linter.Config) (*l loadMode := cl.findLoadMode(linters) pkgs, err := cl.loadPackages(ctx, loadMode) if err != nil { - return nil, err + return nil, errors.Wrap(err, "failed to load packages") } deduplicatedPkgs := cl.filterDuplicatePackages(pkgs) diff --git a/vendor/github.com/golangci/golangci-lint/pkg/lint/runner.go b/vendor/github.com/golangci/golangci-lint/pkg/lint/runner.go index e8f427e0214..084912226b6 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/lint/runner.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/lint/runner.go @@ -7,6 +7,8 @@ import ( "runtime/debug" "strings" + "github.com/pkg/errors" + "github.com/golangci/golangci-lint/internal/errorutil" "github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/fsutils" @@ -27,26 +29,8 @@ type Runner struct { Log logutils.Log } -func NewRunner(cfg *config.Config, log logutils.Log, goenv *goutil.Env, +func NewRunner(cfg *config.Config, log logutils.Log, goenv *goutil.Env, es *lintersdb.EnabledSet, lineCache *fsutils.LineCache, dbManager *lintersdb.Manager, pkgs []*gopackages.Package) (*Runner, error) { - icfg := cfg.Issues - excludePatterns := icfg.ExcludePatterns - if icfg.UseDefaultExcludes { - excludePatterns = append(excludePatterns, config.GetExcludePatternsStrings(icfg.IncludeDefaultExcludes)...) - } - - var excludeTotalPattern string - if len(excludePatterns) != 0 { - excludeTotalPattern = fmt.Sprintf("(%s)", strings.Join(excludePatterns, "|")) - } - - var excludeProcessor processors.Processor - if cfg.Issues.ExcludeCaseSensitive { - excludeProcessor = processors.NewExcludeCaseSensitive(excludeTotalPattern) - } else { - excludeProcessor = processors.NewExclude(excludeTotalPattern) - } - skipFilesProcessor, err := processors.NewSkipFiles(cfg.Run.SkipFiles) if err != nil { return nil, err @@ -61,27 +45,9 @@ func NewRunner(cfg *config.Config, log logutils.Log, goenv *goutil.Env, return nil, err } - var excludeRules []processors.ExcludeRule - for _, r := range icfg.ExcludeRules { - excludeRules = append(excludeRules, processors.ExcludeRule{ - Text: r.Text, - Source: r.Source, - Path: r.Path, - Linters: r.Linters, - }) - } - var excludeRulesProcessor processors.Processor - if cfg.Issues.ExcludeCaseSensitive { - excludeRulesProcessor = processors.NewExcludeRulesCaseSensitive(excludeRules, lineCache, log.Child("exclude_rules")) - } else { - excludeRulesProcessor = processors.NewExcludeRules(excludeRules, lineCache, log.Child("exclude_rules")) - } - - enabledLintersSet := lintersdb.NewEnabledSet(dbManager, - lintersdb.NewValidator(dbManager), log.Child("enabledLinters"), cfg) - lcs, err := enabledLintersSet.Get(false) + enabledLinters, err := es.GetEnabledLintersMap() if err != nil { - return nil, err + return nil, errors.Wrap(err, "failed to get enabled linters") } return &Runner{ @@ -101,17 +67,20 @@ func NewRunner(cfg *config.Config, log logutils.Log, goenv *goutil.Env, // Must be before exclude because users see already marked output and configure excluding by it. processors.NewIdentifierMarker(), - excludeProcessor, - excludeRulesProcessor, - processors.NewNolint(log.Child("nolint"), dbManager, lcs), + getExcludeProcessor(&cfg.Issues), + getExcludeRulesProcessor(&cfg.Issues, log, lineCache), + processors.NewNolint(log.Child("nolint"), dbManager, enabledLinters), processors.NewUniqByLine(cfg), - processors.NewDiff(icfg.Diff, icfg.DiffFromRevision, icfg.DiffPatchFilePath), + processors.NewDiff(cfg.Issues.Diff, cfg.Issues.DiffFromRevision, cfg.Issues.DiffPatchFilePath), processors.NewMaxPerFileFromLinter(cfg), - processors.NewMaxSameIssues(icfg.MaxSameIssues, log.Child("max_same_issues"), cfg), - processors.NewMaxFromLinter(icfg.MaxIssuesPerLinter, log.Child("max_from_linter"), cfg), + processors.NewMaxSameIssues(cfg.Issues.MaxSameIssues, log.Child("max_same_issues"), cfg), + processors.NewMaxFromLinter(cfg.Issues.MaxIssuesPerLinter, log.Child("max_from_linter"), cfg), processors.NewSourceCode(lineCache, log.Child("source_code")), processors.NewPathShortener(), + getSeverityRulesProcessor(&cfg.Severity, log, lineCache), + processors.NewPathPrefixer(cfg.Output.PathPrefix), + processors.NewSortResults(cfg), }, Log: log, }, nil @@ -131,14 +100,17 @@ func (r *Runner) runLinterSafe(ctx context.Context, lintCtx *linter.Context, } }() - specificLintCtx := *lintCtx - specificLintCtx.Log = r.Log.Child(lc.Name()) + issues, err := lc.Linter.Run(ctx, lintCtx) + + if lc.DoesChangeTypes { + // Packages in lintCtx might be dirty due to the last analysis, + // which affects to the next analysis. + // To avoid this issue, we clear type information from the packages. + // See https://github.com/golangci/golangci-lint/pull/944. + // Currently DoesChangeTypes is true only for `unused`. + lintCtx.ClearTypesInPackages() + } - // Packages in lintCtx might be dirty due to the last analysis, - // which affects to the next analysis. - // To avoid this issue, we clear type information from the packages. - specificLintCtx.ClearTypesInPackages() - issues, err := lc.Linter.Run(ctx, &specificLintCtx) if err != nil { return nil, err } @@ -251,3 +223,89 @@ func (r *Runner) processIssues(issues []result.Issue, sw *timeutils.Stopwatch, s return issues } + +func getExcludeProcessor(cfg *config.Issues) processors.Processor { + excludePatterns := cfg.ExcludePatterns + if cfg.UseDefaultExcludes { + excludePatterns = append(excludePatterns, config.GetExcludePatternsStrings(cfg.IncludeDefaultExcludes)...) + } + + var excludeTotalPattern string + if len(excludePatterns) != 0 { + excludeTotalPattern = fmt.Sprintf("(%s)", strings.Join(excludePatterns, "|")) + } + + var excludeProcessor processors.Processor + if cfg.ExcludeCaseSensitive { + excludeProcessor = processors.NewExcludeCaseSensitive(excludeTotalPattern) + } else { + excludeProcessor = processors.NewExclude(excludeTotalPattern) + } + + return excludeProcessor +} + +func getExcludeRulesProcessor(cfg *config.Issues, log logutils.Log, lineCache *fsutils.LineCache) processors.Processor { + var excludeRules []processors.ExcludeRule + for _, r := range cfg.ExcludeRules { + excludeRules = append(excludeRules, processors.ExcludeRule{ + BaseRule: processors.BaseRule{ + Text: r.Text, + Source: r.Source, + Path: r.Path, + Linters: r.Linters, + }, + }) + } + + var excludeRulesProcessor processors.Processor + if cfg.ExcludeCaseSensitive { + excludeRulesProcessor = processors.NewExcludeRulesCaseSensitive( + excludeRules, + lineCache, + log.Child("exclude_rules"), + ) + } else { + excludeRulesProcessor = processors.NewExcludeRules( + excludeRules, + lineCache, + log.Child("exclude_rules"), + ) + } + + return excludeRulesProcessor +} + +func getSeverityRulesProcessor(cfg *config.Severity, log logutils.Log, lineCache *fsutils.LineCache) processors.Processor { + var severityRules []processors.SeverityRule + for _, r := range cfg.Rules { + severityRules = append(severityRules, processors.SeverityRule{ + Severity: r.Severity, + BaseRule: processors.BaseRule{ + Text: r.Text, + Source: r.Source, + Path: r.Path, + Linters: r.Linters, + }, + }) + } + + var severityRulesProcessor processors.Processor + if cfg.CaseSensitive { + severityRulesProcessor = processors.NewSeverityRulesCaseSensitive( + cfg.Default, + severityRules, + lineCache, + log.Child("severity_rules"), + ) + } else { + severityRulesProcessor = processors.NewSeverityRules( + cfg.Default, + severityRules, + lineCache, + log.Child("severity_rules"), + ) + } + + return severityRulesProcessor +} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/printers/checkstyle.go b/vendor/github.com/golangci/golangci-lint/pkg/printers/checkstyle.go index f36bc108adc..c5b948a98d2 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/printers/checkstyle.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/printers/checkstyle.go @@ -5,6 +5,8 @@ import ( "encoding/xml" "fmt" + "github.com/go-xmlfmt/xmlfmt" + "github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/result" ) @@ -28,7 +30,7 @@ type checkstyleError struct { Source string `xml:"source,attr"` } -const defaultSeverity = "error" +const defaultCheckstyleSeverity = "error" type Checkstyle struct{} @@ -54,12 +56,17 @@ func (Checkstyle) Print(ctx context.Context, issues []result.Issue) error { files[issue.FilePath()] = file } + severity := defaultCheckstyleSeverity + if issue.Severity != "" { + severity = issue.Severity + } + newError := &checkstyleError{ Column: issue.Column(), Line: issue.Line(), Message: issue.Text, Source: issue.FromLinter, - Severity: defaultSeverity, + Severity: severity, } file.Errors = append(file.Errors, newError) @@ -75,6 +82,6 @@ func (Checkstyle) Print(ctx context.Context, issues []result.Issue) error { return err } - fmt.Fprintf(logutils.StdOut, "%s%s\n", xml.Header, data) + fmt.Fprintf(logutils.StdOut, "%s%s\n", xml.Header, xmlfmt.FormatXML(string(data), "", " ")) return nil } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/printers/codeclimate.go b/vendor/github.com/golangci/golangci-lint/pkg/printers/codeclimate.go index 26878056884..35a22ce99a7 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/printers/codeclimate.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/printers/codeclimate.go @@ -2,7 +2,6 @@ package printers import ( "context" - "crypto/md5" //nolint:gosec "encoding/json" "fmt" @@ -14,6 +13,7 @@ import ( // It is just enough to support GitLab CI Code Quality - https://docs.gitlab.com/ee/user/project/merge_requests/code_quality.html type CodeClimateIssue struct { Description string `json:"description"` + Severity string `json:"severity,omitempty"` Fingerprint string `json:"fingerprint"` Location struct { Path string `json:"path"` @@ -31,23 +31,23 @@ func NewCodeClimate() *CodeClimate { } func (p CodeClimate) Print(ctx context.Context, issues []result.Issue) error { - allIssues := []CodeClimateIssue{} - for ind := range issues { - i := &issues[ind] - var issue CodeClimateIssue - issue.Description = i.FromLinter + ": " + i.Text - issue.Location.Path = i.Pos.Filename - issue.Location.Lines.Begin = i.Pos.Line - - // Need a checksum of the issue, so we use MD5 of the filename, text, and first line of source - hash := md5.New() //nolint:gosec - _, _ = hash.Write([]byte(i.Pos.Filename + i.Text + i.SourceLines[0])) - issue.Fingerprint = fmt.Sprintf("%X", hash.Sum(nil)) - - allIssues = append(allIssues, issue) + codeClimateIssues := []CodeClimateIssue{} + for i := range issues { + issue := &issues[i] + codeClimateIssue := CodeClimateIssue{} + codeClimateIssue.Description = issue.Description() + codeClimateIssue.Location.Path = issue.Pos.Filename + codeClimateIssue.Location.Lines.Begin = issue.Pos.Line + codeClimateIssue.Fingerprint = issue.Fingerprint() + + if issue.Severity != "" { + codeClimateIssue.Severity = issue.Severity + } + + codeClimateIssues = append(codeClimateIssues, codeClimateIssue) } - outputJSON, err := json.Marshal(allIssues) + outputJSON, err := json.Marshal(codeClimateIssues) if err != nil { return err } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/printers/github.go b/vendor/github.com/golangci/golangci-lint/pkg/printers/github.go index fa11a2839a3..b8d70140a80 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/printers/github.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/printers/github.go @@ -11,6 +11,8 @@ import ( type github struct { } +const defaultGithubSeverity = "error" + // Github output format outputs issues according to Github actions format: // https://help.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-error-message func NewGithub() Printer { @@ -19,7 +21,12 @@ func NewGithub() Printer { // print each line as: ::error file=app.js,line=10,col=15::Something went wrong func formatIssueAsGithub(issue *result.Issue) string { - ret := fmt.Sprintf("::error file=%s,line=%d", issue.FilePath(), issue.Line()) + severity := defaultGithubSeverity + if issue.Severity != "" { + severity = issue.Severity + } + + ret := fmt.Sprintf("::%s file=%s,line=%d", severity, issue.FilePath(), issue.Line()) if issue.Pos.Column != 0 { ret += fmt.Sprintf(",col=%d", issue.Pos.Column) } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/printers/junitxml.go b/vendor/github.com/golangci/golangci-lint/pkg/printers/junitxml.go index b3d4280961c..9277cd66f2f 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/printers/junitxml.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/printers/junitxml.go @@ -17,6 +17,9 @@ type testSuitesXML struct { type testSuiteXML struct { XMLName xml.Name `xml:"testsuite"` Suite string `xml:"name,attr"` + Tests int `xml:"tests,attr"` + Errors int `xml:"errors,attr"` + Failures int `xml:"failures,attr"` TestCases []testCaseXML `xml:"testcase"` } @@ -46,6 +49,8 @@ func (JunitXML) Print(ctx context.Context, issues []result.Issue) error { suiteName := i.FilePath() testSuite := suites[suiteName] testSuite.Suite = i.FilePath() + testSuite.Tests++ + testSuite.Failures++ tc := testCaseXML{ Name: i.FromLinter, diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/issue.go b/vendor/github.com/golangci/golangci-lint/pkg/result/issue.go index 16d9a8a8c19..eafdbc4a958 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/result/issue.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/issue.go @@ -1,6 +1,8 @@ package result import ( + "crypto/md5" //nolint:gosec + "fmt" "go/token" "golang.org/x/tools/go/packages" @@ -26,6 +28,8 @@ type Issue struct { FromLinter string Text string + Severity string + // Source lines of a code with the issue to show SourceLines []string @@ -76,3 +80,19 @@ func (i *Issue) GetLineRange() Range { return *i.LineRange } + +func (i *Issue) Description() string { + return fmt.Sprintf("%s: %s", i.FromLinter, i.Text) +} + +func (i *Issue) Fingerprint() string { + firstLine := "" + if len(i.SourceLines) > 0 { + firstLine = i.SourceLines[0] + } + + hash := md5.New() //nolint:gosec + _, _ = hash.Write([]byte(fmt.Sprintf("%s%s%s", i.Pos.Filename, i.Text, firstLine))) + + return fmt.Sprintf("%X", hash.Sum(nil)) +} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/autogenerated_exclude.go b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/autogenerated_exclude.go index 249ba9d4437..112217952e7 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/autogenerated_exclude.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/autogenerated_exclude.go @@ -1,9 +1,9 @@ package processors import ( - "bufio" "fmt" - "os" + "go/parser" + "go/token" "path/filepath" "strings" @@ -113,37 +113,15 @@ func (p *AutogeneratedExclude) getOrCreateFileSummary(i *result.Issue) (*ageFile } func getDoc(filePath string) (string, error) { - file, err := os.Open(filePath) + fset := token.NewFileSet() + syntax, err := parser.ParseFile(fset, filePath, nil, parser.PackageClauseOnly|parser.ParseComments) if err != nil { - return "", errors.Wrap(err, "failed to open file") + return "", errors.Wrap(err, "failed to parse file") } - defer file.Close() - - scanner := bufio.NewScanner(file) - - // Issue 954: Some lines can be very long, e.g. auto-generated - // embedded resources. Reported on file of 86.2KB. - const ( - maxSize = 10 * 1024 * 1024 // 10MB should be enough - initialSize = 4096 // same as startBufSize in bufio - ) - scanner.Buffer(make([]byte, initialSize), maxSize) var docLines []string - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - if strings.HasPrefix(line, "//") { - text := strings.TrimSpace(strings.TrimPrefix(line, "//")) - docLines = append(docLines, text) - } else if line == "" || strings.HasPrefix(line, "package") { - // go to next line - } else { - break - } - } - - if err := scanner.Err(); err != nil { - return "", errors.Wrap(err, "failed to scan file") + for _, c := range syntax.Comments { + docLines = append(docLines, strings.TrimSpace(c.Text())) } return strings.Join(docLines, "\n"), nil diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/base_rule.go b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/base_rule.go new file mode 100644 index 00000000000..b6ce4f2159e --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/base_rule.go @@ -0,0 +1,69 @@ +package processors + +import ( + "regexp" + + "github.com/golangci/golangci-lint/pkg/fsutils" + "github.com/golangci/golangci-lint/pkg/logutils" + "github.com/golangci/golangci-lint/pkg/result" +) + +type BaseRule struct { + Text string + Source string + Path string + Linters []string +} + +type baseRule struct { + text *regexp.Regexp + source *regexp.Regexp + path *regexp.Regexp + linters []string +} + +func (r *baseRule) isEmpty() bool { + return r.text == nil && r.source == nil && r.path == nil && len(r.linters) == 0 +} + +func (r *baseRule) match(issue *result.Issue, lineCache *fsutils.LineCache, log logutils.Log) bool { + if r.isEmpty() { + return false + } + if r.text != nil && !r.text.MatchString(issue.Text) { + return false + } + if r.path != nil && !r.path.MatchString(issue.FilePath()) { + return false + } + if len(r.linters) != 0 && !r.matchLinter(issue) { + return false + } + + // the most heavyweight checking last + if r.source != nil && !r.matchSource(issue, lineCache, log) { + return false + } + + return true +} + +func (r *baseRule) matchLinter(issue *result.Issue) bool { + for _, linter := range r.linters { + if linter == issue.FromLinter { + return true + } + } + + return false +} + +func (r *baseRule) matchSource(issue *result.Issue, lineCache *fsutils.LineCache, log logutils.Log) bool { // nolint:interfacer + sourceLine, errSourceLine := lineCache.GetLine(issue.FilePath(), issue.Line()) + if errSourceLine != nil { + log.Warnf("Failed to get line %s:%d from line cache: %s", issue.FilePath(), issue.Line(), errSourceLine) + return false // can't properly match + } + + return r.source.MatchString(sourceLine) +} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude_rules.go b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude_rules.go index b926af5b1d4..d4d6569f4ce 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude_rules.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/exclude_rules.go @@ -9,21 +9,11 @@ import ( ) type excludeRule struct { - text *regexp.Regexp - source *regexp.Regexp - path *regexp.Regexp - linters []string -} - -func (r *excludeRule) isEmpty() bool { - return r.text == nil && r.path == nil && len(r.linters) == 0 + baseRule } type ExcludeRule struct { - Text string - Source string - Path string - Linters []string + BaseRule } type ExcludeRules struct { @@ -45,9 +35,8 @@ func NewExcludeRules(rules []ExcludeRule, lineCache *fsutils.LineCache, log logu func createRules(rules []ExcludeRule, prefix string) []excludeRule { parsedRules := make([]excludeRule, 0, len(rules)) for _, rule := range rules { - parsedRule := excludeRule{ - linters: rule.Linters, - } + parsedRule := excludeRule{} + parsedRule.linters = rule.Linters if rule.Text != "" { parsedRule.text = regexp.MustCompile(prefix + rule.Text) } @@ -69,7 +58,7 @@ func (p ExcludeRules) Process(issues []result.Issue) ([]result.Issue, error) { return filterIssues(issues, func(i *result.Issue) bool { for _, rule := range p.rules { rule := rule - if p.match(i, &rule) { + if rule.match(i, p.lineCache, p.log) { return false } } @@ -77,48 +66,6 @@ func (p ExcludeRules) Process(issues []result.Issue) ([]result.Issue, error) { }), nil } -func (p ExcludeRules) matchLinter(i *result.Issue, r *excludeRule) bool { - for _, linter := range r.linters { - if linter == i.FromLinter { - return true - } - } - - return false -} - -func (p ExcludeRules) matchSource(i *result.Issue, r *excludeRule) bool { //nolint:interfacer - sourceLine, err := p.lineCache.GetLine(i.FilePath(), i.Line()) - if err != nil { - p.log.Warnf("Failed to get line %s:%d from line cache: %s", i.FilePath(), i.Line(), err) - return false // can't properly match - } - - return r.source.MatchString(sourceLine) -} - -func (p ExcludeRules) match(i *result.Issue, r *excludeRule) bool { - if r.isEmpty() { - return false - } - if r.text != nil && !r.text.MatchString(i.Text) { - return false - } - if r.path != nil && !r.path.MatchString(i.FilePath()) { - return false - } - if len(r.linters) != 0 && !p.matchLinter(i, r) { - return false - } - - // the most heavyweight checking last - if r.source != nil && !p.matchSource(i, r) { - return false - } - - return true -} - func (ExcludeRules) Name() string { return "exclude-rules" } func (ExcludeRules) Finish() {} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/filename_unadjuster.go b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/filename_unadjuster.go index 5e692ceba2e..96540245b36 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/filename_unadjuster.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/filename_unadjuster.go @@ -16,6 +16,11 @@ import ( type posMapper func(pos token.Position) token.Position +type adjustMap struct { + sync.Mutex + m map[string]posMapper +} + // FilenameUnadjuster is needed because a lot of linters use fset.Position(f.Pos()) // to get filename. And they return adjusted filename (e.g. *.qtpl) for an issue. We need // restore real .go filename to properly output it, parse it, etc. @@ -27,7 +32,7 @@ type FilenameUnadjuster struct { var _ Processor = &FilenameUnadjuster{} -func processUnadjusterPkg(m map[string]posMapper, pkg *packages.Package, log logutils.Log) { +func processUnadjusterPkg(m *adjustMap, pkg *packages.Package, log logutils.Log) { fset := token.NewFileSet() // it's more memory efficient to not store all in one fset for _, filename := range pkg.CompiledGoFiles { @@ -36,7 +41,7 @@ func processUnadjusterPkg(m map[string]posMapper, pkg *packages.Package, log log } } -func processUnadjusterFile(filename string, m map[string]posMapper, log logutils.Log, fset *token.FileSet) { +func processUnadjusterFile(filename string, m *adjustMap, log logutils.Log, fset *token.FileSet) { syntax, err := parser.ParseFile(fset, filename, nil, parser.ParseComments) if err != nil { // Error will be reported by typecheck @@ -57,7 +62,9 @@ func processUnadjusterFile(filename string, m map[string]posMapper, log logutils return // file.go -> /caches/cgo-xxx } - m[adjustedFilename] = func(adjustedPos token.Position) token.Position { + m.Lock() + defer m.Unlock() + m.m[adjustedFilename] = func(adjustedPos token.Position) token.Position { tokenFile := fset.File(syntax.Pos()) if tokenFile == nil { log.Warnf("Failed to get token file for %s", adjustedFilename) @@ -68,22 +75,23 @@ func processUnadjusterFile(filename string, m map[string]posMapper, log logutils } func NewFilenameUnadjuster(pkgs []*packages.Package, log logutils.Log) *FilenameUnadjuster { - m := map[string]posMapper{} + m := adjustMap{m: map[string]posMapper{}} + startedAt := time.Now() var wg sync.WaitGroup wg.Add(len(pkgs)) for _, pkg := range pkgs { go func(pkg *packages.Package) { // It's important to call func here to run GC - processUnadjusterPkg(m, pkg, log) + processUnadjusterPkg(&m, pkg, log) wg.Done() }(pkg) } wg.Wait() - log.Infof("Pre-built %d adjustments in %s", len(m), time.Since(startedAt)) + log.Infof("Pre-built %d adjustments in %s", len(m.m), time.Since(startedAt)) return &FilenameUnadjuster{ - m: m, + m: m.m, log: log, loggedUnadjustments: map[string]bool{}, } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/nolint.go b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/nolint.go index 2f1e48db4e9..cda1017849d 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/nolint.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/nolint.go @@ -60,18 +60,13 @@ type filesCache map[string]*fileData type Nolint struct { cache filesCache dbManager *lintersdb.Manager - enabledLinters map[string]bool + enabledLinters map[string]*linter.Config log logutils.Log unknownLintersSet map[string]bool } -func NewNolint(log logutils.Log, dbManager *lintersdb.Manager, enabledLCs []*linter.Config) *Nolint { - enabledLinters := make(map[string]bool, len(enabledLCs)) - for _, lc := range enabledLCs { - enabledLinters[lc.Name()] = true - } - +func NewNolint(log logutils.Log, dbManager *lintersdb.Manager, enabledLinters map[string]*linter.Config) *Nolint { return &Nolint{ cache: filesCache{}, dbManager: dbManager, @@ -154,7 +149,7 @@ func (p *Nolint) shouldPassIssue(i *result.Issue) (bool, error) { if i.ExpectedNoLintLinter != "" { // don't expect disabled linters to cover their nolint statements nolintDebugf("enabled linters: %v", p.enabledLinters) - if !p.enabledLinters[i.ExpectedNoLintLinter] { + if p.enabledLinters[i.ExpectedNoLintLinter] == nil { return false, nil } nolintDebugf("checking that lint issue was used for %s: %v", i.ExpectedNoLintLinter, i) diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_prefixer.go b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_prefixer.go new file mode 100644 index 00000000000..5ce940b39bf --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/path_prefixer.go @@ -0,0 +1,37 @@ +package processors + +import ( + "path" + + "github.com/golangci/golangci-lint/pkg/result" +) + +// PathPrefixer adds a customizable prefix to every output path +type PathPrefixer struct { + prefix string +} + +var _ Processor = new(PathPrefixer) + +// NewPathPrefixer returns a new path prefixer for the provided string +func NewPathPrefixer(prefix string) *PathPrefixer { + return &PathPrefixer{prefix: prefix} +} + +// Name returns the name of this processor +func (*PathPrefixer) Name() string { + return "path_prefixer" +} + +// Process adds the prefix to each path +func (p *PathPrefixer) Process(issues []result.Issue) ([]result.Issue, error) { + if p.prefix != "" { + for i := range issues { + issues[i].Pos.Filename = path.Join(p.prefix, issues[i].Pos.Filename) + } + } + return issues, nil +} + +// Finish is implemented to satisfy the Processor interface +func (*PathPrefixer) Finish() {} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/severity_rules.go b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/severity_rules.go new file mode 100644 index 00000000000..5f11b54101c --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/severity_rules.go @@ -0,0 +1,103 @@ +package processors + +import ( + "regexp" + + "github.com/golangci/golangci-lint/pkg/fsutils" + "github.com/golangci/golangci-lint/pkg/logutils" + "github.com/golangci/golangci-lint/pkg/result" +) + +type severityRule struct { + baseRule + severity string +} + +type SeverityRule struct { + BaseRule + Severity string +} + +type SeverityRules struct { + defaultSeverity string + rules []severityRule + lineCache *fsutils.LineCache + log logutils.Log +} + +func NewSeverityRules(defaultSeverity string, rules []SeverityRule, lineCache *fsutils.LineCache, log logutils.Log) *SeverityRules { + r := &SeverityRules{ + lineCache: lineCache, + log: log, + defaultSeverity: defaultSeverity, + } + r.rules = createSeverityRules(rules, "(?i)") + + return r +} + +func createSeverityRules(rules []SeverityRule, prefix string) []severityRule { + parsedRules := make([]severityRule, 0, len(rules)) + for _, rule := range rules { + parsedRule := severityRule{} + parsedRule.linters = rule.Linters + parsedRule.severity = rule.Severity + if rule.Text != "" { + parsedRule.text = regexp.MustCompile(prefix + rule.Text) + } + if rule.Source != "" { + parsedRule.source = regexp.MustCompile(prefix + rule.Source) + } + if rule.Path != "" { + parsedRule.path = regexp.MustCompile(rule.Path) + } + parsedRules = append(parsedRules, parsedRule) + } + return parsedRules +} + +func (p SeverityRules) Process(issues []result.Issue) ([]result.Issue, error) { + if len(p.rules) == 0 { + return issues, nil + } + return transformIssues(issues, func(i *result.Issue) *result.Issue { + for _, rule := range p.rules { + rule := rule + + ruleSeverity := p.defaultSeverity + if rule.severity != "" { + ruleSeverity = rule.severity + } + + if rule.match(i, p.lineCache, p.log) { + i.Severity = ruleSeverity + return i + } + } + i.Severity = p.defaultSeverity + return i + }), nil +} + +func (SeverityRules) Name() string { return "severity-rules" } +func (SeverityRules) Finish() {} + +var _ Processor = SeverityRules{} + +type SeverityRulesCaseSensitive struct { + *SeverityRules +} + +func NewSeverityRulesCaseSensitive(defaultSeverity string, rules []SeverityRule, + lineCache *fsutils.LineCache, log logutils.Log) *SeverityRulesCaseSensitive { + r := &SeverityRules{ + lineCache: lineCache, + log: log, + defaultSeverity: defaultSeverity, + } + r.rules = createSeverityRules(rules, "") + + return &SeverityRulesCaseSensitive{r} +} + +func (SeverityRulesCaseSensitive) Name() string { return "severity-rules-case-sensitive" } diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_dirs.go b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_dirs.go index 5107814f0db..6488c109ecf 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_dirs.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_dirs.go @@ -31,6 +31,7 @@ const goFileSuffix = ".go" func NewSkipDirs(patterns []string, log logutils.Log, runArgs []string) (*SkipDirs, error) { var patternsRe []*regexp.Regexp for _, p := range patterns { + p = normalizePathInRegex(p) patternRe, err := regexp.Compile(p) if err != nil { return nil, errors.Wrapf(err, "can't compile regexp %q", p) diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_files.go b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_files.go index 92fd1a29be3..522b07e4f25 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_files.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/skip_files.go @@ -16,6 +16,7 @@ var _ Processor = SkipFiles{} func NewSkipFiles(patterns []string) (*SkipFiles, error) { var patternsRe []*regexp.Regexp for _, p := range patterns { + p = normalizePathInRegex(p) patternRe, err := regexp.Compile(p) if err != nil { return nil, fmt.Errorf("can't compile regexp %q: %s", p, err) diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/sort_results.go b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/sort_results.go new file mode 100644 index 00000000000..e726c3adfe0 --- /dev/null +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/sort_results.go @@ -0,0 +1,173 @@ +package processors + +import ( + "sort" + "strings" + + "github.com/golangci/golangci-lint/pkg/config" + "github.com/golangci/golangci-lint/pkg/result" +) + +// Base propose of this functionality to sort results (issues) +// produced by various linters by analyzing code. We achieving this +// by sorting results.Issues using processor step, and chain based +// rules that can compare different properties of the Issues struct. + +var _ Processor = (*SortResults)(nil) + +type SortResults struct { + cmp comparator + cfg *config.Config +} + +func NewSortResults(cfg *config.Config) *SortResults { + // For sorting we are comparing (in next order): file names, line numbers, + // position, and finally - giving up. + return &SortResults{ + cmp: ByName{ + next: ByLine{ + next: ByColumn{}, + }, + }, + cfg: cfg, + } +} + +// Process is performing sorting of the result issues. +func (sr SortResults) Process(issues []result.Issue) ([]result.Issue, error) { + if !sr.cfg.Output.SortResults { + return issues, nil + } + + sort.Slice(issues, func(i, j int) bool { + return sr.cmp.Compare(&issues[i], &issues[j]) == Less + }) + + return issues, nil +} + +func (sr SortResults) Name() string { return "sort_results" } +func (sr SortResults) Finish() {} + +type compareResult int + +const ( + Less compareResult = iota - 1 + Equal + Greater + None +) + +func (c compareResult) isNeutral() bool { + // return true if compare result is incomparable or equal. + return c == None || c == Equal +} + +//nolint:exhaustive +func (c compareResult) String() string { + switch c { + case Less: + return "Less" + case Equal: + return "Equal" + case Greater: + return "Greater" + } + + return "None" +} + +// comparator describe how to implement compare for two "issues" lexicographically +type comparator interface { + Compare(a, b *result.Issue) compareResult + Next() comparator +} + +var ( + _ comparator = (*ByName)(nil) + _ comparator = (*ByLine)(nil) + _ comparator = (*ByColumn)(nil) +) + +type ByName struct{ next comparator } + +//nolint:golint +func (cmp ByName) Next() comparator { return cmp.next } + +//nolint:golint +func (cmp ByName) Compare(a, b *result.Issue) compareResult { + var res compareResult + + if res = compareResult(strings.Compare(a.FilePath(), b.FilePath())); !res.isNeutral() { + return res + } + + if next := cmp.Next(); next != nil { + return next.Compare(a, b) + } + + return res +} + +type ByLine struct{ next comparator } + +//nolint:golint +func (cmp ByLine) Next() comparator { return cmp.next } + +//nolint:golint +func (cmp ByLine) Compare(a, b *result.Issue) compareResult { + var res compareResult + + if res = numericCompare(a.Line(), b.Line()); !res.isNeutral() { + return res + } + + if next := cmp.Next(); next != nil { + return next.Compare(a, b) + } + + return res +} + +type ByColumn struct{ next comparator } + +//nolint:golint +func (cmp ByColumn) Next() comparator { return cmp.next } + +//nolint:golint +func (cmp ByColumn) Compare(a, b *result.Issue) compareResult { + var res compareResult + + if res = numericCompare(a.Column(), b.Column()); !res.isNeutral() { + return res + } + + if next := cmp.Next(); next != nil { + return next.Compare(a, b) + } + + return res +} + +func numericCompare(a, b int) compareResult { + var ( + isValuesInvalid = a < 0 || b < 0 + isZeroValuesBoth = a == 0 && b == 0 + isEqual = a == b + isZeroValueInA = b > 0 && a == 0 + isZeroValueInB = a > 0 && b == 0 + ) + + switch { + case isZeroValuesBoth || isEqual: + return Equal + case isValuesInvalid || isZeroValueInA || isZeroValueInB: + return None + case a > b: + return Greater + case a < b: + return Less + } + + return Equal +} diff --git a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/utils.go b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/utils.go index 8bc3d847d65..7108fd3b3c2 100644 --- a/vendor/github.com/golangci/golangci-lint/pkg/result/processors/utils.go +++ b/vendor/github.com/golangci/golangci-lint/pkg/result/processors/utils.go @@ -1,6 +1,10 @@ package processors import ( + "path/filepath" + "regexp" + "strings" + "github.com/pkg/errors" "github.com/golangci/golangci-lint/pkg/result" @@ -44,3 +48,15 @@ func transformIssues(issues []result.Issue, transform func(i *result.Issue) *res return retIssues } + +var separatorToReplace = regexp.QuoteMeta(string(filepath.Separator)) + +func normalizePathInRegex(path string) string { + if filepath.Separator == '/' { + return path + } + + // This replacing should be safe because "/" are disallowed in Windows + // https://docs.microsoft.com/ru-ru/windows/win32/fileio/naming-a-file + return strings.ReplaceAll(path, "/", separatorToReplace) +} diff --git a/vendor/github.com/google/go-cmp/cmp/compare.go b/vendor/github.com/google/go-cmp/cmp/compare.go index 2133562b01c..580ae209782 100644 --- a/vendor/github.com/google/go-cmp/cmp/compare.go +++ b/vendor/github.com/google/go-cmp/cmp/compare.go @@ -6,6 +6,10 @@ // // This package is intended to be a more powerful and safer alternative to // reflect.DeepEqual for comparing whether two values are semantically equal. +// It is intended to only be used in tests, as performance is not a goal and +// it may panic if it cannot compare the values. Its propensity towards +// panicking means that its unsuitable for production environments where a +// spurious panic may be fatal. // // The primary features of cmp are: // @@ -22,8 +26,8 @@ // equality is determined by recursively comparing the primitive kinds on both // values, much like reflect.DeepEqual. Unlike reflect.DeepEqual, unexported // fields are not compared by default; they result in panics unless suppressed -// by using an Ignore option (see cmpopts.IgnoreUnexported) or explicitly compared -// using the AllowUnexported option. +// by using an Ignore option (see cmpopts.IgnoreUnexported) or explicitly +// compared using the Exporter option. package cmp import ( @@ -62,8 +66,8 @@ import ( // // Structs are equal if recursively calling Equal on all fields report equal. // If a struct contains unexported fields, Equal panics unless an Ignore option -// (e.g., cmpopts.IgnoreUnexported) ignores that field or the AllowUnexported -// option explicitly permits comparing the unexported field. +// (e.g., cmpopts.IgnoreUnexported) ignores that field or the Exporter option +// explicitly permits comparing the unexported field. // // Slices are equal if they are both nil or both non-nil, where recursively // calling Equal on all non-ignored slice or array elements report equal. @@ -80,31 +84,14 @@ import ( // Pointers and interfaces are equal if they are both nil or both non-nil, // where they have the same underlying concrete type and recursively // calling Equal on the underlying values reports equal. +// +// Before recursing into a pointer, slice element, or map, the current path +// is checked to detect whether the address has already been visited. +// If there is a cycle, then the pointed at values are considered equal +// only if both addresses were previously visited in the same path step. func Equal(x, y interface{}, opts ...Option) bool { - vx := reflect.ValueOf(x) - vy := reflect.ValueOf(y) - - // If the inputs are different types, auto-wrap them in an empty interface - // so that they have the same parent type. - var t reflect.Type - if !vx.IsValid() || !vy.IsValid() || vx.Type() != vy.Type() { - t = reflect.TypeOf((*interface{})(nil)).Elem() - if vx.IsValid() { - vvx := reflect.New(t).Elem() - vvx.Set(vx) - vx = vvx - } - if vy.IsValid() { - vvy := reflect.New(t).Elem() - vvy.Set(vy) - vy = vvy - } - } else { - t = vx.Type() - } - s := newState(opts) - s.compareAny(&pathStep{t, vx, vy}) + s.compareAny(rootStep(x, y)) return s.result.Equal() } @@ -123,20 +110,63 @@ func Equal(x, y interface{}, opts ...Option) bool { // Do not depend on this output being stable. If you need the ability to // programmatically interpret the difference, consider using a custom Reporter. func Diff(x, y interface{}, opts ...Option) string { + s := newState(opts) + + // Optimization: If there are no other reporters, we can optimize for the + // common case where the result is equal (and thus no reported difference). + // This avoids the expensive construction of a difference tree. + if len(s.reporters) == 0 { + s.compareAny(rootStep(x, y)) + if s.result.Equal() { + return "" + } + s.result = diff.Result{} // Reset results + } + r := new(defaultReporter) - eq := Equal(x, y, Options(opts), Reporter(r)) + s.reporters = append(s.reporters, reporter{r}) + s.compareAny(rootStep(x, y)) d := r.String() - if (d == "") != eq { + if (d == "") != s.result.Equal() { panic("inconsistent difference and equality results") } return d } +// rootStep constructs the first path step. If x and y have differing types, +// then they are stored within an empty interface type. +func rootStep(x, y interface{}) PathStep { + vx := reflect.ValueOf(x) + vy := reflect.ValueOf(y) + + // If the inputs are different types, auto-wrap them in an empty interface + // so that they have the same parent type. + var t reflect.Type + if !vx.IsValid() || !vy.IsValid() || vx.Type() != vy.Type() { + t = reflect.TypeOf((*interface{})(nil)).Elem() + if vx.IsValid() { + vvx := reflect.New(t).Elem() + vvx.Set(vx) + vx = vvx + } + if vy.IsValid() { + vvy := reflect.New(t).Elem() + vvy.Set(vy) + vy = vvy + } + } else { + t = vx.Type() + } + + return &pathStep{t, vx, vy} +} + type state struct { // These fields represent the "comparison state". // Calling statelessCompare must not result in observable changes to these. result diff.Result // The current result of comparison curPath Path // The current path in the value tree + curPtrs pointerPath // The current set of visited pointers reporters []reporter // Optional reporters // recChecker checks for infinite cycles applying the same set of @@ -148,13 +178,14 @@ type state struct { dynChecker dynChecker // These fields, once set by processOption, will not change. - exporters map[reflect.Type]bool // Set of structs with unexported field visibility - opts Options // List of all fundamental and filter options + exporters []exporter // List of exporters for structs with unexported fields + opts Options // List of all fundamental and filter options } func newState(opts []Option) *state { // Always ensure a validator option exists to validate the inputs. s := &state{opts: Options{validator{}}} + s.curPtrs.Init() s.processOption(Options(opts)) return s } @@ -174,13 +205,8 @@ func (s *state) processOption(opt Option) { panic(fmt.Sprintf("cannot use an unfiltered option: %v", opt)) } s.opts = append(s.opts, opt) - case visibleStructs: - if s.exporters == nil { - s.exporters = make(map[reflect.Type]bool) - } - for t := range opt { - s.exporters[t] = true - } + case exporter: + s.exporters = append(s.exporters, opt) case reporter: s.reporters = append(s.reporters, opt) default: @@ -192,9 +218,9 @@ func (s *state) processOption(opt Option) { // This function is stateless in that it does not alter the current result, // or output to any registered reporters. func (s *state) statelessCompare(step PathStep) diff.Result { - // We do not save and restore the curPath because all of the compareX - // methods should properly push and pop from the path. - // It is an implementation bug if the contents of curPath differs from + // We do not save and restore curPath and curPtrs because all of the + // compareX methods should properly push and pop from them. + // It is an implementation bug if the contents of the paths differ from // when calling this function to when returning from it. oldResult, oldReporters := s.result, s.reporters @@ -216,9 +242,17 @@ func (s *state) compareAny(step PathStep) { } s.recChecker.Check(s.curPath) - // Obtain the current type and values. + // Cycle-detection for slice elements (see NOTE in compareSlice). t := step.Type() vx, vy := step.Values() + if si, ok := step.(SliceIndex); ok && si.isSlice && vx.IsValid() && vy.IsValid() { + px, py := vx.Addr(), vy.Addr() + if eq, visited := s.curPtrs.Push(px, py); visited { + s.report(eq, reportByCycle) + return + } + defer s.curPtrs.Pop(px, py) + } // Rule 1: Check whether an option applies on this node in the value tree. if s.tryOptions(t, vx, vy) { @@ -342,7 +376,7 @@ func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) { // assuming that T is assignable to R. // Otherwise, it returns the input value as is. func sanitizeValue(v reflect.Value, t reflect.Type) reflect.Value { - // TODO(dsnet): Workaround for reflect bug (https://golang.org/issue/22143). + // TODO(≥go1.10): Workaround for reflect bug (https://golang.org/issue/22143). if !flags.AtLeastGo110 { if v.Kind() == reflect.Interface && v.IsNil() && v.Type() != t { return reflect.New(t).Elem() @@ -352,8 +386,10 @@ func sanitizeValue(v reflect.Value, t reflect.Type) reflect.Value { } func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) { + var addr bool var vax, vay reflect.Value // Addressable versions of vx and vy + var mayForce, mayForceInit bool step := StructField{&structField{}} for i := 0; i < t.NumField(); i++ { step.typ = t.Field(i).Type @@ -372,10 +408,18 @@ func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) { // For retrieveUnexportedField to work, the parent struct must // be addressable. Create a new copy of the values if // necessary to make them addressable. + addr = vx.CanAddr() || vy.CanAddr() vax = makeAddressable(vx) vay = makeAddressable(vy) } - step.mayForce = s.exporters[t] + if !mayForceInit { + for _, xf := range s.exporters { + mayForce = mayForce || xf(t) + } + mayForceInit = true + } + step.mayForce = mayForce + step.paddr = addr step.pvx = vax step.pvy = vay step.field = t.Field(i) @@ -391,9 +435,21 @@ func (s *state) compareSlice(t reflect.Type, vx, vy reflect.Value) { return } - // TODO: Support cyclic data structures. + // NOTE: It is incorrect to call curPtrs.Push on the slice header pointer + // since slices represents a list of pointers, rather than a single pointer. + // The pointer checking logic must be handled on a per-element basis + // in compareAny. + // + // A slice header (see reflect.SliceHeader) in Go is a tuple of a starting + // pointer P, a length N, and a capacity C. Supposing each slice element has + // a memory size of M, then the slice is equivalent to the list of pointers: + // [P+i*M for i in range(N)] + // + // For example, v[:0] and v[:1] are slices with the same starting pointer, + // but they are clearly different values. Using the slice pointer alone + // violates the assumption that equal pointers implies equal values. - step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}}} + step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}, isSlice: isSlice}} withIndexes := func(ix, iy int) SliceIndex { if ix >= 0 { step.vx, step.xkey = vx.Index(ix), ix @@ -470,7 +526,12 @@ func (s *state) compareMap(t reflect.Type, vx, vy reflect.Value) { return } - // TODO: Support cyclic data structures. + // Cycle-detection for maps. + if eq, visited := s.curPtrs.Push(vx, vy); visited { + s.report(eq, reportByCycle) + return + } + defer s.curPtrs.Pop(vx, vy) // We combine and sort the two map keys so that we can perform the // comparisons in a deterministic order. @@ -507,7 +568,12 @@ func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) { return } - // TODO: Support cyclic data structures. + // Cycle-detection for pointers. + if eq, visited := s.curPtrs.Push(vx, vy); visited { + s.report(eq, reportByCycle) + return + } + defer s.curPtrs.Pop(vx, vy) vx, vy = vx.Elem(), vy.Elem() s.compareAny(Indirect{&indirect{pathStep{t.Elem(), vx, vy}}}) diff --git a/vendor/github.com/google/go-cmp/cmp/export_panic.go b/vendor/github.com/google/go-cmp/cmp/export_panic.go index abc3a1c3e76..dfa5d213769 100644 --- a/vendor/github.com/google/go-cmp/cmp/export_panic.go +++ b/vendor/github.com/google/go-cmp/cmp/export_panic.go @@ -8,8 +8,8 @@ package cmp import "reflect" -const supportAllowUnexported = false +const supportExporters = false -func retrieveUnexportedField(reflect.Value, reflect.StructField) reflect.Value { - panic("retrieveUnexportedField is not implemented") +func retrieveUnexportedField(reflect.Value, reflect.StructField, bool) reflect.Value { + panic("no support for forcibly accessing unexported fields") } diff --git a/vendor/github.com/google/go-cmp/cmp/export_unsafe.go b/vendor/github.com/google/go-cmp/cmp/export_unsafe.go index 59d4ee91b47..351f1a34b46 100644 --- a/vendor/github.com/google/go-cmp/cmp/export_unsafe.go +++ b/vendor/github.com/google/go-cmp/cmp/export_unsafe.go @@ -11,13 +11,25 @@ import ( "unsafe" ) -const supportAllowUnexported = true +const supportExporters = true // retrieveUnexportedField uses unsafe to forcibly retrieve any field from // a struct such that the value has read-write permissions. // // The parent struct, v, must be addressable, while f must be a StructField -// describing the field to retrieve. -func retrieveUnexportedField(v reflect.Value, f reflect.StructField) reflect.Value { - return reflect.NewAt(f.Type, unsafe.Pointer(v.UnsafeAddr()+f.Offset)).Elem() +// describing the field to retrieve. If addr is false, +// then the returned value will be shallowed copied to be non-addressable. +func retrieveUnexportedField(v reflect.Value, f reflect.StructField, addr bool) reflect.Value { + ve := reflect.NewAt(f.Type, unsafe.Pointer(uintptr(unsafe.Pointer(v.UnsafeAddr()))+f.Offset)).Elem() + if !addr { + // A field is addressable if and only if the struct is addressable. + // If the original parent value was not addressable, shallow copy the + // value to make it non-addressable to avoid leaking an implementation + // detail of how forcibly exporting a field works. + if ve.Kind() == reflect.Interface && ve.IsNil() { + return reflect.Zero(f.Type) + } + return reflect.ValueOf(ve.Interface()).Convert(f.Type) + } + return ve } diff --git a/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go b/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go index 3d2e42662ca..730e223ee7b 100644 --- a/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go +++ b/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go @@ -12,6 +12,13 @@ // is more important than obtaining a minimal Levenshtein distance. package diff +import ( + "math/rand" + "time" + + "github.com/google/go-cmp/cmp/internal/flags" +) + // EditType represents a single operation within an edit-script. type EditType uint8 @@ -112,6 +119,8 @@ func (r Result) Similar() bool { return r.NumSame+1 >= r.NumDiff } +var randInt = rand.New(rand.NewSource(time.Now().Unix())).Intn(2) + // Difference reports whether two lists of lengths nx and ny are equal // given the definition of equality provided as f. // @@ -159,6 +168,17 @@ func Difference(nx, ny int, f EqualFunc) (es EditScript) { // A vertical edge is equivalent to inserting a symbol from list Y. // A diagonal edge is equivalent to a matching symbol between both X and Y. + // To ensure flexibility in changing the algorithm in the future, + // introduce some degree of deliberate instability. + // This is achieved by fiddling the zigzag iterator to start searching + // the graph starting from the bottom-right versus than the top-left. + // The result may differ depending on the starting search location, + // but still produces a valid edit script. + zigzagInit := randInt // either 0 or 1 + if flags.Deterministic { + zigzagInit = 0 + } + // Invariants: // • 0 ≤ fwdPath.X ≤ (fwdFrontier.X, revFrontier.X) ≤ revPath.X ≤ nx // • 0 ≤ fwdPath.Y ≤ (fwdFrontier.Y, revFrontier.Y) ≤ revPath.Y ≤ ny @@ -209,7 +229,7 @@ func Difference(nx, ny int, f EqualFunc) (es EditScript) { if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 { break } - for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ { + for stop1, stop2, i := false, false, zigzagInit; !(stop1 && stop2) && searchBudget > 0; i++ { // Search in a diagonal pattern for a match. z := zigzag(i) p := point{fwdFrontier.X + z, fwdFrontier.Y - z} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/name.go b/vendor/github.com/google/go-cmp/cmp/internal/value/name.go new file mode 100644 index 00000000000..8228e7d512a --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/internal/value/name.go @@ -0,0 +1,157 @@ +// Copyright 2020, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE.md file. + +package value + +import ( + "reflect" + "strconv" +) + +// TypeString is nearly identical to reflect.Type.String, +// but has an additional option to specify that full type names be used. +func TypeString(t reflect.Type, qualified bool) string { + return string(appendTypeName(nil, t, qualified, false)) +} + +func appendTypeName(b []byte, t reflect.Type, qualified, elideFunc bool) []byte { + // BUG: Go reflection provides no way to disambiguate two named types + // of the same name and within the same package, + // but declared within the namespace of different functions. + + // Named type. + if t.Name() != "" { + if qualified && t.PkgPath() != "" { + b = append(b, '"') + b = append(b, t.PkgPath()...) + b = append(b, '"') + b = append(b, '.') + b = append(b, t.Name()...) + } else { + b = append(b, t.String()...) + } + return b + } + + // Unnamed type. + switch k := t.Kind(); k { + case reflect.Bool, reflect.String, reflect.UnsafePointer, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, + reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: + b = append(b, k.String()...) + case reflect.Chan: + if t.ChanDir() == reflect.RecvDir { + b = append(b, "<-"...) + } + b = append(b, "chan"...) + if t.ChanDir() == reflect.SendDir { + b = append(b, "<-"...) + } + b = append(b, ' ') + b = appendTypeName(b, t.Elem(), qualified, false) + case reflect.Func: + if !elideFunc { + b = append(b, "func"...) + } + b = append(b, '(') + for i := 0; i < t.NumIn(); i++ { + if i > 0 { + b = append(b, ", "...) + } + if i == t.NumIn()-1 && t.IsVariadic() { + b = append(b, "..."...) + b = appendTypeName(b, t.In(i).Elem(), qualified, false) + } else { + b = appendTypeName(b, t.In(i), qualified, false) + } + } + b = append(b, ')') + switch t.NumOut() { + case 0: + // Do nothing + case 1: + b = append(b, ' ') + b = appendTypeName(b, t.Out(0), qualified, false) + default: + b = append(b, " ("...) + for i := 0; i < t.NumOut(); i++ { + if i > 0 { + b = append(b, ", "...) + } + b = appendTypeName(b, t.Out(i), qualified, false) + } + b = append(b, ')') + } + case reflect.Struct: + b = append(b, "struct{ "...) + for i := 0; i < t.NumField(); i++ { + if i > 0 { + b = append(b, "; "...) + } + sf := t.Field(i) + if !sf.Anonymous { + if qualified && sf.PkgPath != "" { + b = append(b, '"') + b = append(b, sf.PkgPath...) + b = append(b, '"') + b = append(b, '.') + } + b = append(b, sf.Name...) + b = append(b, ' ') + } + b = appendTypeName(b, sf.Type, qualified, false) + if sf.Tag != "" { + b = append(b, ' ') + b = strconv.AppendQuote(b, string(sf.Tag)) + } + } + if b[len(b)-1] == ' ' { + b = b[:len(b)-1] + } else { + b = append(b, ' ') + } + b = append(b, '}') + case reflect.Slice, reflect.Array: + b = append(b, '[') + if k == reflect.Array { + b = strconv.AppendUint(b, uint64(t.Len()), 10) + } + b = append(b, ']') + b = appendTypeName(b, t.Elem(), qualified, false) + case reflect.Map: + b = append(b, "map["...) + b = appendTypeName(b, t.Key(), qualified, false) + b = append(b, ']') + b = appendTypeName(b, t.Elem(), qualified, false) + case reflect.Ptr: + b = append(b, '*') + b = appendTypeName(b, t.Elem(), qualified, false) + case reflect.Interface: + b = append(b, "interface{ "...) + for i := 0; i < t.NumMethod(); i++ { + if i > 0 { + b = append(b, "; "...) + } + m := t.Method(i) + if qualified && m.PkgPath != "" { + b = append(b, '"') + b = append(b, m.PkgPath...) + b = append(b, '"') + b = append(b, '.') + } + b = append(b, m.Name...) + b = appendTypeName(b, m.Type, qualified, true) + } + if b[len(b)-1] == ' ' { + b = b[:len(b)-1] + } else { + b = append(b, ' ') + } + b = append(b, '}') + default: + panic("invalid kind: " + k.String()) + } + return b +} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go index 0a01c4796f1..e9e384a1c89 100644 --- a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go +++ b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_purego.go @@ -21,3 +21,13 @@ func PointerOf(v reflect.Value) Pointer { // assumes that the GC implementation does not use a moving collector. return Pointer{v.Pointer(), v.Type()} } + +// IsNil reports whether the pointer is nil. +func (p Pointer) IsNil() bool { + return p.p == 0 +} + +// Uintptr returns the pointer as a uintptr. +func (p Pointer) Uintptr() uintptr { + return p.p +} diff --git a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go index da134ae2a80..b50c17ec725 100644 --- a/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go +++ b/vendor/github.com/google/go-cmp/cmp/internal/value/pointer_unsafe.go @@ -24,3 +24,13 @@ func PointerOf(v reflect.Value) Pointer { // which is necessary if the GC ever uses a moving collector. return Pointer{unsafe.Pointer(v.Pointer()), v.Type()} } + +// IsNil reports whether the pointer is nil. +func (p Pointer) IsNil() bool { + return p.p == nil +} + +// Uintptr returns the pointer as a uintptr. +func (p Pointer) Uintptr() uintptr { + return uintptr(p.p) +} diff --git a/vendor/github.com/google/go-cmp/cmp/options.go b/vendor/github.com/google/go-cmp/cmp/options.go index 793448160ee..abbd2a63b69 100644 --- a/vendor/github.com/google/go-cmp/cmp/options.go +++ b/vendor/github.com/google/go-cmp/cmp/options.go @@ -225,8 +225,20 @@ func (validator) apply(s *state, vx, vy reflect.Value) { // Unable to Interface implies unexported field without visibility access. if !vx.CanInterface() || !vy.CanInterface() { - const help = "consider using a custom Comparer; if you control the implementation of type, you can also consider AllowUnexported or cmpopts.IgnoreUnexported" - panic(fmt.Sprintf("cannot handle unexported field: %#v\n%s", s.curPath, help)) + const help = "consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported" + var name string + if t := s.curPath.Index(-2).Type(); t.Name() != "" { + // Named type with unexported fields. + name = fmt.Sprintf("%q.%v", t.PkgPath(), t.Name()) // e.g., "path/to/package".MyType + } else { + // Unnamed type with unexported fields. Derive PkgPath from field. + var pkgPath string + for i := 0; i < t.NumField() && pkgPath == ""; i++ { + pkgPath = t.Field(i).PkgPath + } + name = fmt.Sprintf("%q.(%v)", pkgPath, t.String()) // e.g., "path/to/package".(struct { a int }) + } + panic(fmt.Sprintf("cannot handle unexported field at %#v:\n\t%v\n%s", s.curPath, name, help)) } panic("not reachable") @@ -360,9 +372,8 @@ func (cm comparer) String() string { return fmt.Sprintf("Comparer(%s)", function.NameOf(cm.fnc)) } -// AllowUnexported returns an Option that forcibly allows operations on -// unexported fields in certain structs, which are specified by passing in a -// value of each struct type. +// Exporter returns an Option that specifies whether Equal is allowed to +// introspect into the unexported fields of certain struct types. // // Users of this option must understand that comparing on unexported fields // from external packages is not safe since changes in the internal @@ -386,10 +397,24 @@ func (cm comparer) String() string { // // In other cases, the cmpopts.IgnoreUnexported option can be used to ignore // all unexported fields on specified struct types. -func AllowUnexported(types ...interface{}) Option { - if !supportAllowUnexported { - panic("AllowUnexported is not supported on purego builds, Google App Engine Standard, or GopherJS") +func Exporter(f func(reflect.Type) bool) Option { + if !supportExporters { + panic("Exporter is not supported on purego builds") } + return exporter(f) +} + +type exporter func(reflect.Type) bool + +func (exporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { + panic("not implemented") +} + +// AllowUnexported returns an Options that allows Equal to forcibly introspect +// unexported fields of the specified struct types. +// +// See Exporter for the proper use of this option. +func AllowUnexported(types ...interface{}) Option { m := make(map[reflect.Type]bool) for _, typ := range types { t := reflect.TypeOf(typ) @@ -398,13 +423,7 @@ func AllowUnexported(types ...interface{}) Option { } m[t] = true } - return visibleStructs(m) -} - -type visibleStructs map[reflect.Type]bool - -func (visibleStructs) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { - panic("not implemented") + return exporter(func(t reflect.Type) bool { return m[t] }) } // Result represents the comparison result for a single node and @@ -436,6 +455,11 @@ func (r Result) ByFunc() bool { return r.flags&reportByFunc != 0 } +// ByCycle reports whether a reference cycle was detected. +func (r Result) ByCycle() bool { + return r.flags&reportByCycle != 0 +} + type resultFlags uint const ( @@ -446,6 +470,7 @@ const ( reportByIgnore reportByMethod reportByFunc + reportByCycle ) // Reporter is an Option that can be passed to Equal. When Equal traverses diff --git a/vendor/github.com/google/go-cmp/cmp/path.go b/vendor/github.com/google/go-cmp/cmp/path.go index 96fffd291f7..603dbb0026e 100644 --- a/vendor/github.com/google/go-cmp/cmp/path.go +++ b/vendor/github.com/google/go-cmp/cmp/path.go @@ -10,6 +10,8 @@ import ( "strings" "unicode" "unicode/utf8" + + "github.com/google/go-cmp/cmp/internal/value" ) // Path is a list of PathSteps describing the sequence of operations to get @@ -41,7 +43,7 @@ type PathStep interface { // In some cases, one or both may be invalid or have restrictions: // • For StructField, both are not interface-able if the current field // is unexported and the struct type is not explicitly permitted by - // AllowUnexported to traverse unexported fields. + // an Exporter to traverse unexported fields. // • For SliceIndex, one may be invalid if an element is missing from // either the x or y slice. // • For MapIndex, one may be invalid if an entry is missing from @@ -175,7 +177,8 @@ type structField struct { // pvx, pvy, and field are only valid if unexported is true. unexported bool mayForce bool // Forcibly allow visibility - pvx, pvy reflect.Value // Parent values + paddr bool // Was parent addressable? + pvx, pvy reflect.Value // Parent values (always addressible) field reflect.StructField // Field information } @@ -187,8 +190,8 @@ func (sf StructField) Values() (vx, vy reflect.Value) { // Forcibly obtain read-write access to an unexported struct field. if sf.mayForce { - vx = retrieveUnexportedField(sf.pvx, sf.field) - vy = retrieveUnexportedField(sf.pvy, sf.field) + vx = retrieveUnexportedField(sf.pvx, sf.field, sf.paddr) + vy = retrieveUnexportedField(sf.pvy, sf.field, sf.paddr) return vx, vy // CanInterface reports true } return sf.vx, sf.vy // CanInterface reports false @@ -207,6 +210,7 @@ type SliceIndex struct{ *sliceIndex } type sliceIndex struct { pathStep xkey, ykey int + isSlice bool // False for reflect.Array } func (si SliceIndex) Type() reflect.Type { return si.typ } @@ -301,6 +305,72 @@ func (tf Transform) Func() reflect.Value { return tf.trans.fnc } // The == operator can be used to detect the exact option used. func (tf Transform) Option() Option { return tf.trans } +// pointerPath represents a dual-stack of pointers encountered when +// recursively traversing the x and y values. This data structure supports +// detection of cycles and determining whether the cycles are equal. +// In Go, cycles can occur via pointers, slices, and maps. +// +// The pointerPath uses a map to represent a stack; where descension into a +// pointer pushes the address onto the stack, and ascension from a pointer +// pops the address from the stack. Thus, when traversing into a pointer from +// reflect.Ptr, reflect.Slice element, or reflect.Map, we can detect cycles +// by checking whether the pointer has already been visited. The cycle detection +// uses a seperate stack for the x and y values. +// +// If a cycle is detected we need to determine whether the two pointers +// should be considered equal. The definition of equality chosen by Equal +// requires two graphs to have the same structure. To determine this, both the +// x and y values must have a cycle where the previous pointers were also +// encountered together as a pair. +// +// Semantically, this is equivalent to augmenting Indirect, SliceIndex, and +// MapIndex with pointer information for the x and y values. +// Suppose px and py are two pointers to compare, we then search the +// Path for whether px was ever encountered in the Path history of x, and +// similarly so with py. If either side has a cycle, the comparison is only +// equal if both px and py have a cycle resulting from the same PathStep. +// +// Using a map as a stack is more performant as we can perform cycle detection +// in O(1) instead of O(N) where N is len(Path). +type pointerPath struct { + // mx is keyed by x pointers, where the value is the associated y pointer. + mx map[value.Pointer]value.Pointer + // my is keyed by y pointers, where the value is the associated x pointer. + my map[value.Pointer]value.Pointer +} + +func (p *pointerPath) Init() { + p.mx = make(map[value.Pointer]value.Pointer) + p.my = make(map[value.Pointer]value.Pointer) +} + +// Push indicates intent to descend into pointers vx and vy where +// visited reports whether either has been seen before. If visited before, +// equal reports whether both pointers were encountered together. +// Pop must be called if and only if the pointers were never visited. +// +// The pointers vx and vy must be a reflect.Ptr, reflect.Slice, or reflect.Map +// and be non-nil. +func (p pointerPath) Push(vx, vy reflect.Value) (equal, visited bool) { + px := value.PointerOf(vx) + py := value.PointerOf(vy) + _, ok1 := p.mx[px] + _, ok2 := p.my[py] + if ok1 || ok2 { + equal = p.mx[px] == py && p.my[py] == px // Pointers paired together + return equal, true + } + p.mx[px] = py + p.my[py] = px + return false, false +} + +// Pop ascends from pointers vx and vy. +func (p pointerPath) Pop(vx, vy reflect.Value) { + delete(p.mx, value.PointerOf(vx)) + delete(p.my, value.PointerOf(vy)) +} + // isExported reports whether the identifier is exported. func isExported(id string) bool { r, _ := utf8.DecodeRuneInString(id) diff --git a/vendor/github.com/google/go-cmp/cmp/report.go b/vendor/github.com/google/go-cmp/cmp/report.go index 6ddf29993e5..aafcb363545 100644 --- a/vendor/github.com/google/go-cmp/cmp/report.go +++ b/vendor/github.com/google/go-cmp/cmp/report.go @@ -41,7 +41,10 @@ func (r *defaultReporter) String() string { if r.root.NumDiff == 0 { return "" } - return formatOptions{}.FormatDiff(r.root).String() + ptrs := new(pointerReferences) + text := formatOptions{}.FormatDiff(r.root, ptrs) + resolveReferences(text) + return text.String() } func assert(ok bool) { diff --git a/vendor/github.com/google/go-cmp/cmp/report_compare.go b/vendor/github.com/google/go-cmp/cmp/report_compare.go index 17a05eede48..9e2180964f1 100644 --- a/vendor/github.com/google/go-cmp/cmp/report_compare.go +++ b/vendor/github.com/google/go-cmp/cmp/report_compare.go @@ -11,14 +11,6 @@ import ( "github.com/google/go-cmp/cmp/internal/value" ) -// TODO: Enforce limits? -// * Enforce maximum number of records to print per node? -// * Enforce maximum size in bytes allowed? -// * As a heuristic, use less verbosity for equal nodes than unequal nodes. -// TODO: Enforce unique outputs? -// * Avoid Stringer methods if it results in same output? -// * Print pointer address if outputs still equal? - // numContextRecords is the number of surrounding equal records to print. const numContextRecords = 2 @@ -71,24 +63,66 @@ func (opts formatOptions) WithTypeMode(t typeMode) formatOptions { opts.TypeMode = t return opts } +func (opts formatOptions) WithVerbosity(level int) formatOptions { + opts.VerbosityLevel = level + opts.LimitVerbosity = true + return opts +} +func (opts formatOptions) verbosity() uint { + switch { + case opts.VerbosityLevel < 0: + return 0 + case opts.VerbosityLevel > 16: + return 16 // some reasonable maximum to avoid shift overflow + default: + return uint(opts.VerbosityLevel) + } +} + +const maxVerbosityPreset = 3 + +// verbosityPreset modifies the verbosity settings given an index +// between 0 and maxVerbosityPreset, inclusive. +func verbosityPreset(opts formatOptions, i int) formatOptions { + opts.VerbosityLevel = int(opts.verbosity()) + 2*i + if i > 0 { + opts.AvoidStringer = true + } + if i >= maxVerbosityPreset { + opts.PrintAddresses = true + opts.QualifiedNames = true + } + return opts +} // FormatDiff converts a valueNode tree into a textNode tree, where the later // is a textual representation of the differences detected in the former. -func (opts formatOptions) FormatDiff(v *valueNode) textNode { +func (opts formatOptions) FormatDiff(v *valueNode, ptrs *pointerReferences) (out textNode) { + if opts.DiffMode == diffIdentical { + opts = opts.WithVerbosity(1) + } else { + opts = opts.WithVerbosity(3) + } + // Check whether we have specialized formatting for this node. // This is not necessary, but helpful for producing more readable outputs. if opts.CanFormatDiffSlice(v) { return opts.FormatDiffSlice(v) } + var parentKind reflect.Kind + if v.parent != nil && v.parent.TransformerName == "" { + parentKind = v.parent.Type.Kind() + } + // For leaf nodes, format the value based on the reflect.Values alone. if v.MaxDepth == 0 { switch opts.DiffMode { case diffUnknown, diffIdentical: // Format Equal. if v.NumDiff == 0 { - outx := opts.FormatValue(v.ValueX, visitedPointers{}) - outy := opts.FormatValue(v.ValueY, visitedPointers{}) + outx := opts.FormatValue(v.ValueX, parentKind, ptrs) + outy := opts.FormatValue(v.ValueY, parentKind, ptrs) if v.NumIgnored > 0 && v.NumSame == 0 { return textEllipsis } else if outx.Len() < outy.Len() { @@ -101,8 +135,13 @@ func (opts formatOptions) FormatDiff(v *valueNode) textNode { // Format unequal. assert(opts.DiffMode == diffUnknown) var list textList - outx := opts.WithTypeMode(elideType).FormatValue(v.ValueX, visitedPointers{}) - outy := opts.WithTypeMode(elideType).FormatValue(v.ValueY, visitedPointers{}) + outx := opts.WithTypeMode(elideType).FormatValue(v.ValueX, parentKind, ptrs) + outy := opts.WithTypeMode(elideType).FormatValue(v.ValueY, parentKind, ptrs) + for i := 0; i <= maxVerbosityPreset && outx != nil && outy != nil && outx.Equal(outy); i++ { + opts2 := verbosityPreset(opts, i).WithTypeMode(elideType) + outx = opts2.FormatValue(v.ValueX, parentKind, ptrs) + outy = opts2.FormatValue(v.ValueY, parentKind, ptrs) + } if outx != nil { list = append(list, textRecord{Diff: '-', Value: outx}) } @@ -111,34 +150,57 @@ func (opts formatOptions) FormatDiff(v *valueNode) textNode { } return opts.WithTypeMode(emitType).FormatType(v.Type, list) case diffRemoved: - return opts.FormatValue(v.ValueX, visitedPointers{}) + return opts.FormatValue(v.ValueX, parentKind, ptrs) case diffInserted: - return opts.FormatValue(v.ValueY, visitedPointers{}) + return opts.FormatValue(v.ValueY, parentKind, ptrs) default: panic("invalid diff mode") } } + // Register slice element to support cycle detection. + if parentKind == reflect.Slice { + ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, true) + defer ptrs.Pop() + defer func() { out = wrapTrunkReferences(ptrRefs, out) }() + } + // Descend into the child value node. if v.TransformerName != "" { - out := opts.WithTypeMode(emitType).FormatDiff(v.Value) - out = textWrap{"Inverse(" + v.TransformerName + ", ", out, ")"} + out := opts.WithTypeMode(emitType).FormatDiff(v.Value, ptrs) + out = &textWrap{Prefix: "Inverse(" + v.TransformerName + ", ", Value: out, Suffix: ")"} return opts.FormatType(v.Type, out) } else { switch k := v.Type.Kind(); k { - case reflect.Struct, reflect.Array, reflect.Slice, reflect.Map: - return opts.FormatType(v.Type, opts.formatDiffList(v.Records, k)) + case reflect.Struct, reflect.Array, reflect.Slice: + out = opts.formatDiffList(v.Records, k, ptrs) + out = opts.FormatType(v.Type, out) + case reflect.Map: + // Register map to support cycle detection. + ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, false) + defer ptrs.Pop() + + out = opts.formatDiffList(v.Records, k, ptrs) + out = wrapTrunkReferences(ptrRefs, out) + out = opts.FormatType(v.Type, out) case reflect.Ptr: - return textWrap{"&", opts.FormatDiff(v.Value), ""} + // Register pointer to support cycle detection. + ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, false) + defer ptrs.Pop() + + out = opts.FormatDiff(v.Value, ptrs) + out = wrapTrunkReferences(ptrRefs, out) + out = &textWrap{Prefix: "&", Value: out} case reflect.Interface: - return opts.WithTypeMode(emitType).FormatDiff(v.Value) + out = opts.WithTypeMode(emitType).FormatDiff(v.Value, ptrs) default: panic(fmt.Sprintf("%v cannot have children", k)) } + return out } } -func (opts formatOptions) formatDiffList(recs []reportRecord, k reflect.Kind) textNode { +func (opts formatOptions) formatDiffList(recs []reportRecord, k reflect.Kind, ptrs *pointerReferences) textNode { // Derive record name based on the data structure kind. var name string var formatKey func(reflect.Value) string @@ -154,7 +216,17 @@ func (opts formatOptions) formatDiffList(recs []reportRecord, k reflect.Kind) te case reflect.Map: name = "entry" opts = opts.WithTypeMode(elideType) - formatKey = formatMapKey + formatKey = func(v reflect.Value) string { return formatMapKey(v, false, ptrs) } + } + + maxLen := -1 + if opts.LimitVerbosity { + if opts.DiffMode == diffIdentical { + maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... + } else { + maxLen = (1 << opts.verbosity()) << 1 // 2, 4, 8, 16, 32, 64, etc... + } + opts.VerbosityLevel-- } // Handle unification. @@ -163,6 +235,11 @@ func (opts formatOptions) formatDiffList(recs []reportRecord, k reflect.Kind) te var list textList var deferredEllipsis bool // Add final "..." to indicate records were dropped for _, r := range recs { + if len(list) == maxLen { + deferredEllipsis = true + break + } + // Elide struct fields that are zero value. if k == reflect.Struct { var isZero bool @@ -186,23 +263,31 @@ func (opts formatOptions) formatDiffList(recs []reportRecord, k reflect.Kind) te } continue } - if out := opts.FormatDiff(r.Value); out != nil { + if out := opts.FormatDiff(r.Value, ptrs); out != nil { list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) } } if deferredEllipsis { list.AppendEllipsis(diffStats{}) } - return textWrap{"{", list, "}"} + return &textWrap{Prefix: "{", Value: list, Suffix: "}"} case diffUnknown: default: panic("invalid diff mode") } // Handle differencing. + var numDiffs int var list textList + var keys []reflect.Value // invariant: len(list) == len(keys) groups := coalesceAdjacentRecords(name, recs) + maxGroup := diffStats{Name: name} for i, ds := range groups { + if maxLen >= 0 && numDiffs >= maxLen { + maxGroup = maxGroup.Append(ds) + continue + } + // Handle equal records. if ds.NumDiff() == 0 { // Compute the number of leading and trailing records to print. @@ -226,16 +311,21 @@ func (opts formatOptions) formatDiffList(recs []reportRecord, k reflect.Kind) te // Format the equal values. for _, r := range recs[:numLo] { - out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value) + out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value, ptrs) list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) + keys = append(keys, r.Key) } if numEqual > numLo+numHi { ds.NumIdentical -= numLo + numHi list.AppendEllipsis(ds) + for len(keys) < len(list) { + keys = append(keys, reflect.Value{}) + } } for _, r := range recs[numEqual-numHi : numEqual] { - out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value) + out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value, ptrs) list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) + keys = append(keys, r.Key) } recs = recs[numEqual:] continue @@ -247,24 +337,70 @@ func (opts formatOptions) formatDiffList(recs []reportRecord, k reflect.Kind) te case opts.CanFormatDiffSlice(r.Value): out := opts.FormatDiffSlice(r.Value) list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) + keys = append(keys, r.Key) case r.Value.NumChildren == r.Value.MaxDepth: - outx := opts.WithDiffMode(diffRemoved).FormatDiff(r.Value) - outy := opts.WithDiffMode(diffInserted).FormatDiff(r.Value) + outx := opts.WithDiffMode(diffRemoved).FormatDiff(r.Value, ptrs) + outy := opts.WithDiffMode(diffInserted).FormatDiff(r.Value, ptrs) + for i := 0; i <= maxVerbosityPreset && outx != nil && outy != nil && outx.Equal(outy); i++ { + opts2 := verbosityPreset(opts, i) + outx = opts2.WithDiffMode(diffRemoved).FormatDiff(r.Value, ptrs) + outy = opts2.WithDiffMode(diffInserted).FormatDiff(r.Value, ptrs) + } if outx != nil { list = append(list, textRecord{Diff: diffRemoved, Key: formatKey(r.Key), Value: outx}) + keys = append(keys, r.Key) } if outy != nil { list = append(list, textRecord{Diff: diffInserted, Key: formatKey(r.Key), Value: outy}) + keys = append(keys, r.Key) } default: - out := opts.FormatDiff(r.Value) + out := opts.FormatDiff(r.Value, ptrs) list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) + keys = append(keys, r.Key) } } recs = recs[ds.NumDiff():] + numDiffs += ds.NumDiff() + } + if maxGroup.IsZero() { + assert(len(recs) == 0) + } else { + list.AppendEllipsis(maxGroup) + for len(keys) < len(list) { + keys = append(keys, reflect.Value{}) + } } - assert(len(recs) == 0) - return textWrap{"{", list, "}"} + assert(len(list) == len(keys)) + + // For maps, the default formatting logic uses fmt.Stringer which may + // produce ambiguous output. Avoid calling String to disambiguate. + if k == reflect.Map { + var ambiguous bool + seenKeys := map[string]reflect.Value{} + for i, currKey := range keys { + if currKey.IsValid() { + strKey := list[i].Key + prevKey, seen := seenKeys[strKey] + if seen && prevKey.CanInterface() && currKey.CanInterface() { + ambiguous = prevKey.Interface() != currKey.Interface() + if ambiguous { + break + } + } + seenKeys[strKey] = currKey + } + } + if ambiguous { + for i, k := range keys { + if k.IsValid() { + list[i].Key = formatMapKey(k, true, ptrs) + } + } + } + } + + return &textWrap{Prefix: "{", Value: list, Suffix: "}"} } // coalesceAdjacentRecords coalesces the list of records into groups of diff --git a/vendor/github.com/google/go-cmp/cmp/report_references.go b/vendor/github.com/google/go-cmp/cmp/report_references.go new file mode 100644 index 00000000000..d620c2c20e7 --- /dev/null +++ b/vendor/github.com/google/go-cmp/cmp/report_references.go @@ -0,0 +1,264 @@ +// Copyright 2020, The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE.md file. + +package cmp + +import ( + "fmt" + "reflect" + "strings" + + "github.com/google/go-cmp/cmp/internal/flags" + "github.com/google/go-cmp/cmp/internal/value" +) + +const ( + pointerDelimPrefix = "⟪" + pointerDelimSuffix = "⟫" +) + +// formatPointer prints the address of the pointer. +func formatPointer(p value.Pointer, withDelims bool) string { + v := p.Uintptr() + if flags.Deterministic { + v = 0xdeadf00f // Only used for stable testing purposes + } + if withDelims { + return pointerDelimPrefix + formatHex(uint64(v)) + pointerDelimSuffix + } + return formatHex(uint64(v)) +} + +// pointerReferences is a stack of pointers visited so far. +type pointerReferences [][2]value.Pointer + +func (ps *pointerReferences) PushPair(vx, vy reflect.Value, d diffMode, deref bool) (pp [2]value.Pointer) { + if deref && vx.IsValid() { + vx = vx.Addr() + } + if deref && vy.IsValid() { + vy = vy.Addr() + } + switch d { + case diffUnknown, diffIdentical: + pp = [2]value.Pointer{value.PointerOf(vx), value.PointerOf(vy)} + case diffRemoved: + pp = [2]value.Pointer{value.PointerOf(vx), value.Pointer{}} + case diffInserted: + pp = [2]value.Pointer{value.Pointer{}, value.PointerOf(vy)} + } + *ps = append(*ps, pp) + return pp +} + +func (ps *pointerReferences) Push(v reflect.Value) (p value.Pointer, seen bool) { + p = value.PointerOf(v) + for _, pp := range *ps { + if p == pp[0] || p == pp[1] { + return p, true + } + } + *ps = append(*ps, [2]value.Pointer{p, p}) + return p, false +} + +func (ps *pointerReferences) Pop() { + *ps = (*ps)[:len(*ps)-1] +} + +// trunkReferences is metadata for a textNode indicating that the sub-tree +// represents the value for either pointer in a pair of references. +type trunkReferences struct{ pp [2]value.Pointer } + +// trunkReference is metadata for a textNode indicating that the sub-tree +// represents the value for the given pointer reference. +type trunkReference struct{ p value.Pointer } + +// leafReference is metadata for a textNode indicating that the value is +// truncated as it refers to another part of the tree (i.e., a trunk). +type leafReference struct{ p value.Pointer } + +func wrapTrunkReferences(pp [2]value.Pointer, s textNode) textNode { + switch { + case pp[0].IsNil(): + return &textWrap{Value: s, Metadata: trunkReference{pp[1]}} + case pp[1].IsNil(): + return &textWrap{Value: s, Metadata: trunkReference{pp[0]}} + case pp[0] == pp[1]: + return &textWrap{Value: s, Metadata: trunkReference{pp[0]}} + default: + return &textWrap{Value: s, Metadata: trunkReferences{pp}} + } +} +func wrapTrunkReference(p value.Pointer, printAddress bool, s textNode) textNode { + var prefix string + if printAddress { + prefix = formatPointer(p, true) + } + return &textWrap{Prefix: prefix, Value: s, Metadata: trunkReference{p}} +} +func makeLeafReference(p value.Pointer, printAddress bool) textNode { + out := &textWrap{Prefix: "(", Value: textEllipsis, Suffix: ")"} + var prefix string + if printAddress { + prefix = formatPointer(p, true) + } + return &textWrap{Prefix: prefix, Value: out, Metadata: leafReference{p}} +} + +// resolveReferences walks the textNode tree searching for any leaf reference +// metadata and resolves each against the corresponding trunk references. +// Since pointer addresses in memory are not particularly readable to the user, +// it replaces each pointer value with an arbitrary and unique reference ID. +func resolveReferences(s textNode) { + var walkNodes func(textNode, func(textNode)) + walkNodes = func(s textNode, f func(textNode)) { + f(s) + switch s := s.(type) { + case *textWrap: + walkNodes(s.Value, f) + case textList: + for _, r := range s { + walkNodes(r.Value, f) + } + } + } + + // Collect all trunks and leaves with reference metadata. + var trunks, leaves []*textWrap + walkNodes(s, func(s textNode) { + if s, ok := s.(*textWrap); ok { + switch s.Metadata.(type) { + case leafReference: + leaves = append(leaves, s) + case trunkReference, trunkReferences: + trunks = append(trunks, s) + } + } + }) + + // No leaf references to resolve. + if len(leaves) == 0 { + return + } + + // Collect the set of all leaf references to resolve. + leafPtrs := make(map[value.Pointer]bool) + for _, leaf := range leaves { + leafPtrs[leaf.Metadata.(leafReference).p] = true + } + + // Collect the set of trunk pointers that are always paired together. + // This allows us to assign a single ID to both pointers for brevity. + // If a pointer in a pair ever occurs by itself or as a different pair, + // then the pair is broken. + pairedTrunkPtrs := make(map[value.Pointer]value.Pointer) + unpair := func(p value.Pointer) { + if !pairedTrunkPtrs[p].IsNil() { + pairedTrunkPtrs[pairedTrunkPtrs[p]] = value.Pointer{} // invalidate other half + } + pairedTrunkPtrs[p] = value.Pointer{} // invalidate this half + } + for _, trunk := range trunks { + switch p := trunk.Metadata.(type) { + case trunkReference: + unpair(p.p) // standalone pointer cannot be part of a pair + case trunkReferences: + p0, ok0 := pairedTrunkPtrs[p.pp[0]] + p1, ok1 := pairedTrunkPtrs[p.pp[1]] + switch { + case !ok0 && !ok1: + // Register the newly seen pair. + pairedTrunkPtrs[p.pp[0]] = p.pp[1] + pairedTrunkPtrs[p.pp[1]] = p.pp[0] + case ok0 && ok1 && p0 == p.pp[1] && p1 == p.pp[0]: + // Exact pair already seen; do nothing. + default: + // Pair conflicts with some other pair; break all pairs. + unpair(p.pp[0]) + unpair(p.pp[1]) + } + } + } + + // Correlate each pointer referenced by leaves to a unique identifier, + // and print the IDs for each trunk that matches those pointers. + var nextID uint + ptrIDs := make(map[value.Pointer]uint) + newID := func() uint { + id := nextID + nextID++ + return id + } + for _, trunk := range trunks { + switch p := trunk.Metadata.(type) { + case trunkReference: + if print := leafPtrs[p.p]; print { + id, ok := ptrIDs[p.p] + if !ok { + id = newID() + ptrIDs[p.p] = id + } + trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id)) + } + case trunkReferences: + print0 := leafPtrs[p.pp[0]] + print1 := leafPtrs[p.pp[1]] + if print0 || print1 { + id0, ok0 := ptrIDs[p.pp[0]] + id1, ok1 := ptrIDs[p.pp[1]] + isPair := pairedTrunkPtrs[p.pp[0]] == p.pp[1] && pairedTrunkPtrs[p.pp[1]] == p.pp[0] + if isPair { + var id uint + assert(ok0 == ok1) // must be seen together or not at all + if ok0 { + assert(id0 == id1) // must have the same ID + id = id0 + } else { + id = newID() + ptrIDs[p.pp[0]] = id + ptrIDs[p.pp[1]] = id + } + trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id)) + } else { + if print0 && !ok0 { + id0 = newID() + ptrIDs[p.pp[0]] = id0 + } + if print1 && !ok1 { + id1 = newID() + ptrIDs[p.pp[1]] = id1 + } + switch { + case print0 && print1: + trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id0)+","+formatReference(id1)) + case print0: + trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id0)) + case print1: + trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id1)) + } + } + } + } + } + + // Update all leaf references with the unique identifier. + for _, leaf := range leaves { + if id, ok := ptrIDs[leaf.Metadata.(leafReference).p]; ok { + leaf.Prefix = updateReferencePrefix(leaf.Prefix, formatReference(id)) + } + } +} + +func formatReference(id uint) string { + return fmt.Sprintf("ref#%d", id) +} + +func updateReferencePrefix(prefix, ref string) string { + if prefix == "" { + return pointerDelimPrefix + ref + pointerDelimSuffix + } + suffix := strings.TrimPrefix(prefix, pointerDelimPrefix) + return pointerDelimPrefix + ref + ": " + suffix +} diff --git a/vendor/github.com/google/go-cmp/cmp/report_reflect.go b/vendor/github.com/google/go-cmp/cmp/report_reflect.go index 2761b628921..2d722ea51dc 100644 --- a/vendor/github.com/google/go-cmp/cmp/report_reflect.go +++ b/vendor/github.com/google/go-cmp/cmp/report_reflect.go @@ -10,8 +10,8 @@ import ( "strconv" "strings" "unicode" + "unicode/utf8" - "github.com/google/go-cmp/cmp/internal/flags" "github.com/google/go-cmp/cmp/internal/value" ) @@ -20,14 +20,22 @@ type formatValueOptions struct { // methods like error.Error or fmt.Stringer.String. AvoidStringer bool - // ShallowPointers controls whether to avoid descending into pointers. - // Useful when printing map keys, where pointer comparison is performed - // on the pointer address rather than the pointed-at value. - ShallowPointers bool - // PrintAddresses controls whether to print the address of all pointers, // slice elements, and maps. PrintAddresses bool + + // QualifiedNames controls whether FormatType uses the fully qualified name + // (including the full package path as opposed to just the package name). + QualifiedNames bool + + // VerbosityLevel controls the amount of output to produce. + // A higher value produces more output. A value of zero or lower produces + // no output (represented using an ellipsis). + // If LimitVerbosity is false, then the level is treated as infinite. + VerbosityLevel int + + // LimitVerbosity specifies that formatting should respect VerbosityLevel. + LimitVerbosity bool } // FormatType prints the type as if it were wrapping s. @@ -44,12 +52,15 @@ func (opts formatOptions) FormatType(t reflect.Type, s textNode) textNode { default: return s } + if opts.DiffMode == diffIdentical { + return s // elide type for identical nodes + } case elideType: return s } // Determine the type label, applying special handling for unnamed types. - typeName := t.String() + typeName := value.TypeString(t, opts.QualifiedNames) if t.Name() == "" { // According to Go grammar, certain type literals contain symbols that // do not strongly bind to the next lexicographical token (e.g., *T). @@ -57,39 +68,78 @@ func (opts formatOptions) FormatType(t reflect.Type, s textNode) textNode { case reflect.Chan, reflect.Func, reflect.Ptr: typeName = "(" + typeName + ")" } - typeName = strings.Replace(typeName, "struct {", "struct{", -1) - typeName = strings.Replace(typeName, "interface {", "interface{", -1) } + return &textWrap{Prefix: typeName, Value: wrapParens(s)} +} - // Avoid wrap the value in parenthesis if unnecessary. - if s, ok := s.(textWrap); ok { - hasParens := strings.HasPrefix(s.Prefix, "(") && strings.HasSuffix(s.Suffix, ")") - hasBraces := strings.HasPrefix(s.Prefix, "{") && strings.HasSuffix(s.Suffix, "}") +// wrapParens wraps s with a set of parenthesis, but avoids it if the +// wrapped node itself is already surrounded by a pair of parenthesis or braces. +// It handles unwrapping one level of pointer-reference nodes. +func wrapParens(s textNode) textNode { + var refNode *textWrap + if s2, ok := s.(*textWrap); ok { + // Unwrap a single pointer reference node. + switch s2.Metadata.(type) { + case leafReference, trunkReference, trunkReferences: + refNode = s2 + if s3, ok := refNode.Value.(*textWrap); ok { + s2 = s3 + } + } + + // Already has delimiters that make parenthesis unnecessary. + hasParens := strings.HasPrefix(s2.Prefix, "(") && strings.HasSuffix(s2.Suffix, ")") + hasBraces := strings.HasPrefix(s2.Prefix, "{") && strings.HasSuffix(s2.Suffix, "}") if hasParens || hasBraces { - return textWrap{typeName, s, ""} + return s } } - return textWrap{typeName + "(", s, ")"} + if refNode != nil { + refNode.Value = &textWrap{Prefix: "(", Value: refNode.Value, Suffix: ")"} + return s + } + return &textWrap{Prefix: "(", Value: s, Suffix: ")"} } // FormatValue prints the reflect.Value, taking extra care to avoid descending -// into pointers already in m. As pointers are visited, m is also updated. -func (opts formatOptions) FormatValue(v reflect.Value, m visitedPointers) (out textNode) { +// into pointers already in ptrs. As pointers are visited, ptrs is also updated. +func (opts formatOptions) FormatValue(v reflect.Value, parentKind reflect.Kind, ptrs *pointerReferences) (out textNode) { if !v.IsValid() { return nil } t := v.Type() + // Check slice element for cycles. + if parentKind == reflect.Slice { + ptrRef, visited := ptrs.Push(v.Addr()) + if visited { + return makeLeafReference(ptrRef, false) + } + defer ptrs.Pop() + defer func() { out = wrapTrunkReference(ptrRef, false, out) }() + } + // Check whether there is an Error or String method to call. if !opts.AvoidStringer && v.CanInterface() { // Avoid calling Error or String methods on nil receivers since many // implementations crash when doing so. if (t.Kind() != reflect.Ptr && t.Kind() != reflect.Interface) || !v.IsNil() { + var prefix, strVal string switch v := v.Interface().(type) { case error: - return textLine("e" + formatString(v.Error())) + prefix, strVal = "e", v.Error() case fmt.Stringer: - return textLine("s" + formatString(v.String())) + prefix, strVal = "s", v.String() + } + if prefix != "" { + maxLen := len(strVal) + if opts.LimitVerbosity { + maxLen = (1 << opts.verbosity()) << 5 // 32, 64, 128, 256, etc... + } + if len(strVal) > maxLen+len(textEllipsis) { + return textLine(prefix + formatString(strVal[:maxLen]) + string(textEllipsis)) + } + return textLine(prefix + formatString(strVal)) } } } @@ -102,94 +152,136 @@ func (opts formatOptions) FormatValue(v reflect.Value, m visitedPointers) (out t } }() - var ptr string switch t.Kind() { case reflect.Bool: return textLine(fmt.Sprint(v.Bool())) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return textLine(fmt.Sprint(v.Int())) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - // Unnamed uints are usually bytes or words, so use hexadecimal. - if t.PkgPath() == "" || t.Kind() == reflect.Uintptr { + case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return textLine(fmt.Sprint(v.Uint())) + case reflect.Uint8: + if parentKind == reflect.Slice || parentKind == reflect.Array { return textLine(formatHex(v.Uint())) } return textLine(fmt.Sprint(v.Uint())) + case reflect.Uintptr: + return textLine(formatHex(v.Uint())) case reflect.Float32, reflect.Float64: return textLine(fmt.Sprint(v.Float())) case reflect.Complex64, reflect.Complex128: return textLine(fmt.Sprint(v.Complex())) case reflect.String: + maxLen := v.Len() + if opts.LimitVerbosity { + maxLen = (1 << opts.verbosity()) << 5 // 32, 64, 128, 256, etc... + } + if v.Len() > maxLen+len(textEllipsis) { + return textLine(formatString(v.String()[:maxLen]) + string(textEllipsis)) + } return textLine(formatString(v.String())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: - return textLine(formatPointer(v)) + return textLine(formatPointer(value.PointerOf(v), true)) case reflect.Struct: var list textList + v := makeAddressable(v) // needed for retrieveUnexportedField + maxLen := v.NumField() + if opts.LimitVerbosity { + maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... + opts.VerbosityLevel-- + } for i := 0; i < v.NumField(); i++ { vv := v.Field(i) if value.IsZero(vv) { continue // Elide fields with zero values } - s := opts.WithTypeMode(autoType).FormatValue(vv, m) - list = append(list, textRecord{Key: t.Field(i).Name, Value: s}) + if len(list) == maxLen { + list.AppendEllipsis(diffStats{}) + break + } + sf := t.Field(i) + if supportExporters && !isExported(sf.Name) { + vv = retrieveUnexportedField(v, sf, true) + } + s := opts.WithTypeMode(autoType).FormatValue(vv, t.Kind(), ptrs) + list = append(list, textRecord{Key: sf.Name, Value: s}) } - return textWrap{"{", list, "}"} + return &textWrap{Prefix: "{", Value: list, Suffix: "}"} case reflect.Slice: if v.IsNil() { return textNil } - if opts.PrintAddresses { - ptr = formatPointer(v) - } fallthrough case reflect.Array: + maxLen := v.Len() + if opts.LimitVerbosity { + maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... + opts.VerbosityLevel-- + } var list textList for i := 0; i < v.Len(); i++ { - vi := v.Index(i) - if vi.CanAddr() { // Check for cyclic elements - p := vi.Addr() - if m.Visit(p) { - var out textNode - out = textLine(formatPointer(p)) - out = opts.WithTypeMode(emitType).FormatType(p.Type(), out) - out = textWrap{"*", out, ""} - list = append(list, textRecord{Value: out}) - continue - } + if len(list) == maxLen { + list.AppendEllipsis(diffStats{}) + break } - s := opts.WithTypeMode(elideType).FormatValue(vi, m) + s := opts.WithTypeMode(elideType).FormatValue(v.Index(i), t.Kind(), ptrs) list = append(list, textRecord{Value: s}) } - return textWrap{ptr + "{", list, "}"} + + out = &textWrap{Prefix: "{", Value: list, Suffix: "}"} + if t.Kind() == reflect.Slice && opts.PrintAddresses { + header := fmt.Sprintf("ptr:%v, len:%d, cap:%d", formatPointer(value.PointerOf(v), false), v.Len(), v.Cap()) + out = &textWrap{Prefix: pointerDelimPrefix + header + pointerDelimSuffix, Value: out} + } + return out case reflect.Map: if v.IsNil() { return textNil } - if m.Visit(v) { - return textLine(formatPointer(v)) + + // Check pointer for cycles. + ptrRef, visited := ptrs.Push(v) + if visited { + return makeLeafReference(ptrRef, opts.PrintAddresses) } + defer ptrs.Pop() + maxLen := v.Len() + if opts.LimitVerbosity { + maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... + opts.VerbosityLevel-- + } var list textList for _, k := range value.SortKeys(v.MapKeys()) { - sk := formatMapKey(k) - sv := opts.WithTypeMode(elideType).FormatValue(v.MapIndex(k), m) + if len(list) == maxLen { + list.AppendEllipsis(diffStats{}) + break + } + sk := formatMapKey(k, false, ptrs) + sv := opts.WithTypeMode(elideType).FormatValue(v.MapIndex(k), t.Kind(), ptrs) list = append(list, textRecord{Key: sk, Value: sv}) } - if opts.PrintAddresses { - ptr = formatPointer(v) - } - return textWrap{ptr + "{", list, "}"} + + out = &textWrap{Prefix: "{", Value: list, Suffix: "}"} + out = wrapTrunkReference(ptrRef, opts.PrintAddresses, out) + return out case reflect.Ptr: if v.IsNil() { return textNil } - if m.Visit(v) || opts.ShallowPointers { - return textLine(formatPointer(v)) - } - if opts.PrintAddresses { - ptr = formatPointer(v) + + // Check pointer for cycles. + ptrRef, visited := ptrs.Push(v) + if visited { + out = makeLeafReference(ptrRef, opts.PrintAddresses) + return &textWrap{Prefix: "&", Value: out} } + defer ptrs.Pop() + skipType = true // Let the underlying value print the type instead - return textWrap{"&" + ptr, opts.FormatValue(v.Elem(), m), ""} + out = opts.FormatValue(v.Elem(), t.Kind(), ptrs) + out = wrapTrunkReference(ptrRef, opts.PrintAddresses, out) + out = &textWrap{Prefix: "&", Value: out} + return out case reflect.Interface: if v.IsNil() { return textNil @@ -197,7 +289,7 @@ func (opts formatOptions) FormatValue(v reflect.Value, m visitedPointers) (out t // Interfaces accept different concrete types, // so configure the underlying value to explicitly print the type. skipType = true // Print the concrete type instead - return opts.WithTypeMode(emitType).FormatValue(v.Elem(), m) + return opts.WithTypeMode(emitType).FormatValue(v.Elem(), t.Kind(), ptrs) default: panic(fmt.Sprintf("%v kind not handled", v.Kind())) } @@ -205,11 +297,14 @@ func (opts formatOptions) FormatValue(v reflect.Value, m visitedPointers) (out t // formatMapKey formats v as if it were a map key. // The result is guaranteed to be a single line. -func formatMapKey(v reflect.Value) string { +func formatMapKey(v reflect.Value, disambiguate bool, ptrs *pointerReferences) string { var opts formatOptions + opts.DiffMode = diffIdentical opts.TypeMode = elideType - opts.ShallowPointers = true - s := opts.FormatValue(v, visitedPointers{}).String() + opts.PrintAddresses = disambiguate + opts.AvoidStringer = disambiguate + opts.QualifiedNames = disambiguate + s := opts.FormatValue(v, reflect.Map, ptrs).String() return strings.TrimSpace(s) } @@ -227,7 +322,7 @@ func formatString(s string) string { rawInvalid := func(r rune) bool { return r == '`' || r == '\n' || !(unicode.IsPrint(r) || r == '\t') } - if strings.IndexFunc(s, rawInvalid) < 0 { + if utf8.ValidString(s) && strings.IndexFunc(s, rawInvalid) < 0 { return "`" + s + "`" } return qs @@ -256,23 +351,3 @@ func formatHex(u uint64) string { } return fmt.Sprintf(f, u) } - -// formatPointer prints the address of the pointer. -func formatPointer(v reflect.Value) string { - p := v.Pointer() - if flags.Deterministic { - p = 0xdeadf00f // Only used for stable testing purposes - } - return fmt.Sprintf("⟪0x%x⟫", p) -} - -type visitedPointers map[value.Pointer]struct{} - -// Visit inserts pointer v into the visited map and reports whether it had -// already been visited before. -func (m visitedPointers) Visit(v reflect.Value) bool { - p := value.PointerOf(v) - _, visited := m[p] - m[p] = struct{}{} - return visited -} diff --git a/vendor/github.com/google/go-cmp/cmp/report_slices.go b/vendor/github.com/google/go-cmp/cmp/report_slices.go index eafcf2e4c0b..35315dad355 100644 --- a/vendor/github.com/google/go-cmp/cmp/report_slices.go +++ b/vendor/github.com/google/go-cmp/cmp/report_slices.go @@ -8,6 +8,7 @@ import ( "bytes" "fmt" "reflect" + "strconv" "strings" "unicode" "unicode/utf8" @@ -23,11 +24,25 @@ func (opts formatOptions) CanFormatDiffSlice(v *valueNode) bool { return false // Must be formatting in diff mode case v.NumDiff == 0: return false // No differences detected - case v.NumIgnored+v.NumCompared+v.NumTransformed > 0: - // TODO: Handle the case where someone uses bytes.Equal on a large slice. - return false // Some custom option was used to determined equality case !v.ValueX.IsValid() || !v.ValueY.IsValid(): return false // Both values must be valid + case v.Type.Kind() == reflect.Slice && (v.ValueX.Len() == 0 || v.ValueY.Len() == 0): + return false // Both slice values have to be non-empty + case v.NumIgnored > 0: + return false // Some ignore option was used + case v.NumTransformed > 0: + return false // Some transform option was used + case v.NumCompared > 1: + return false // More than one comparison was used + case v.NumCompared == 1 && v.Type.Name() != "": + // The need for cmp to check applicability of options on every element + // in a slice is a significant performance detriment for large []byte. + // The workaround is to specify Comparer(bytes.Equal), + // which enables cmp to compare []byte more efficiently. + // If they differ, we still want to provide batched diffing. + // The logic disallows named types since they tend to have their own + // String method, with nicer formatting than what this provides. + return false } switch t := v.Type; t.Kind() { @@ -82,7 +97,7 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { } if isText || isBinary { var numLines, lastLineIdx, maxLineLen int - isBinary = false + isBinary = !utf8.ValidString(sx) || !utf8.ValidString(sy) for i, r := range sx + sy { if !(unicode.IsPrint(r) || unicode.IsSpace(r)) || r == utf8.RuneError { isBinary = true @@ -97,7 +112,7 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { } } isText = !isBinary - isLinedText = isText && numLines >= 4 && maxLineLen <= 256 + isLinedText = isText && numLines >= 4 && maxLineLen <= 1024 } // Format the string into printable records. @@ -117,6 +132,83 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { }, ) delim = "\n" + + // If possible, use a custom triple-quote (""") syntax for printing + // differences in a string literal. This format is more readable, + // but has edge-cases where differences are visually indistinguishable. + // This format is avoided under the following conditions: + // • A line starts with `"""` + // • A line starts with "..." + // • A line contains non-printable characters + // • Adjacent different lines differ only by whitespace + // + // For example: + // """ + // ... // 3 identical lines + // foo + // bar + // - baz + // + BAZ + // """ + isTripleQuoted := true + prevRemoveLines := map[string]bool{} + prevInsertLines := map[string]bool{} + var list2 textList + list2 = append(list2, textRecord{Value: textLine(`"""`), ElideComma: true}) + for _, r := range list { + if !r.Value.Equal(textEllipsis) { + line, _ := strconv.Unquote(string(r.Value.(textLine))) + line = strings.TrimPrefix(strings.TrimSuffix(line, "\r"), "\r") // trim leading/trailing carriage returns for legacy Windows endline support + normLine := strings.Map(func(r rune) rune { + if unicode.IsSpace(r) { + return -1 // drop whitespace to avoid visually indistinguishable output + } + return r + }, line) + isPrintable := func(r rune) bool { + return unicode.IsPrint(r) || r == '\t' // specially treat tab as printable + } + isTripleQuoted = !strings.HasPrefix(line, `"""`) && !strings.HasPrefix(line, "...") && strings.TrimFunc(line, isPrintable) == "" + switch r.Diff { + case diffRemoved: + isTripleQuoted = isTripleQuoted && !prevInsertLines[normLine] + prevRemoveLines[normLine] = true + case diffInserted: + isTripleQuoted = isTripleQuoted && !prevRemoveLines[normLine] + prevInsertLines[normLine] = true + } + if !isTripleQuoted { + break + } + r.Value = textLine(line) + r.ElideComma = true + } + if !(r.Diff == diffRemoved || r.Diff == diffInserted) { // start a new non-adjacent difference group + prevRemoveLines = map[string]bool{} + prevInsertLines = map[string]bool{} + } + list2 = append(list2, r) + } + if r := list2[len(list2)-1]; r.Diff == diffIdentical && len(r.Value.(textLine)) == 0 { + list2 = list2[:len(list2)-1] // elide single empty line at the end + } + list2 = append(list2, textRecord{Value: textLine(`"""`), ElideComma: true}) + if isTripleQuoted { + var out textNode = &textWrap{Prefix: "(", Value: list2, Suffix: ")"} + switch t.Kind() { + case reflect.String: + if t != reflect.TypeOf(string("")) { + out = opts.FormatType(t, out) + } + case reflect.Slice: + // Always emit type for slices since the triple-quote syntax + // looks like a string (not a slice). + opts = opts.WithTypeMode(emitType) + out = opts.FormatType(t, out) + } + return out + } + // If the text appears to be single-lined text, // then perform differencing in approximately fixed-sized chunks. // The output is printed as quoted strings. @@ -129,6 +221,7 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { }, ) delim = "" + // If the text appears to be binary data, // then perform differencing in approximately fixed-sized chunks. // The output is inspired by hexdump. @@ -145,6 +238,7 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { return textRecord{Diff: d, Value: textLine(s), Comment: comment} }, ) + // For all other slices of primitive types, // then perform differencing in approximately fixed-sized chunks. // The size of each chunk depends on the width of the element kind. @@ -172,7 +266,9 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { switch t.Elem().Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: ss = append(ss, fmt.Sprint(v.Index(i).Int())) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: + ss = append(ss, fmt.Sprint(v.Index(i).Uint())) + case reflect.Uint8, reflect.Uintptr: ss = append(ss, formatHex(v.Index(i).Uint())) case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: ss = append(ss, fmt.Sprint(v.Index(i).Interface())) @@ -185,7 +281,7 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { } // Wrap the output with appropriate type information. - var out textNode = textWrap{"{", list, "}"} + var out textNode = &textWrap{Prefix: "{", Value: list, Suffix: "}"} if !isText { // The "{...}" byte-sequence literal is not valid Go syntax for strings. // Emit the type for extra clarity (e.g. "string{...}"). @@ -196,12 +292,12 @@ func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { } switch t.Kind() { case reflect.String: - out = textWrap{"strings.Join(", out, fmt.Sprintf(", %q)", delim)} + out = &textWrap{Prefix: "strings.Join(", Value: out, Suffix: fmt.Sprintf(", %q)", delim)} if t != reflect.TypeOf(string("")) { out = opts.FormatType(t, out) } case reflect.Slice: - out = textWrap{"bytes.Join(", out, fmt.Sprintf(", %q)", delim)} + out = &textWrap{Prefix: "bytes.Join(", Value: out, Suffix: fmt.Sprintf(", %q)", delim)} if t != reflect.TypeOf([]byte(nil)) { out = opts.FormatType(t, out) } @@ -242,9 +338,22 @@ func (opts formatOptions) formatDiffSlice( return n0 - v.Len() } + var numDiffs int + maxLen := -1 + if opts.LimitVerbosity { + maxLen = (1 << opts.verbosity()) << 2 // 4, 8, 16, 32, 64, etc... + opts.VerbosityLevel-- + } + groups := coalesceAdjacentEdits(name, es) groups = coalesceInterveningIdentical(groups, chunkSize/4) + maxGroup := diffStats{Name: name} for i, ds := range groups { + if maxLen >= 0 && numDiffs >= maxLen { + maxGroup = maxGroup.Append(ds) + continue + } + // Print equal. if ds.NumDiff() == 0 { // Compute the number of leading and trailing equal bytes to print. @@ -273,12 +382,18 @@ func (opts formatOptions) formatDiffSlice( } // Print unequal. + len0 := len(list) nx := appendChunks(vx.Slice(0, ds.NumIdentical+ds.NumRemoved+ds.NumModified), diffRemoved) vx = vx.Slice(nx, vx.Len()) ny := appendChunks(vy.Slice(0, ds.NumIdentical+ds.NumInserted+ds.NumModified), diffInserted) vy = vy.Slice(ny, vy.Len()) + numDiffs += len(list) - len0 + } + if maxGroup.IsZero() { + assert(vx.Len() == 0 && vy.Len() == 0) + } else { + list.AppendEllipsis(maxGroup) } - assert(vx.Len() == 0 && vy.Len() == 0) return list } diff --git a/vendor/github.com/google/go-cmp/cmp/report_text.go b/vendor/github.com/google/go-cmp/cmp/report_text.go index 8b8fcab7bdf..8b12c05cd4f 100644 --- a/vendor/github.com/google/go-cmp/cmp/report_text.go +++ b/vendor/github.com/google/go-cmp/cmp/report_text.go @@ -10,12 +10,15 @@ import ( "math/rand" "strings" "time" + "unicode/utf8" "github.com/google/go-cmp/cmp/internal/flags" ) var randBool = rand.New(rand.NewSource(time.Now().Unix())).Intn(2) == 0 +const maxColumnLength = 80 + type indentMode int func (n indentMode) appendIndent(b []byte, d diffMode) []byte { @@ -91,21 +94,22 @@ type textNode interface { // textWrap is a wrapper that concatenates a prefix and/or a suffix // to the underlying node. type textWrap struct { - Prefix string // e.g., "bytes.Buffer{" - Value textNode // textWrap | textList | textLine - Suffix string // e.g., "}" + Prefix string // e.g., "bytes.Buffer{" + Value textNode // textWrap | textList | textLine + Suffix string // e.g., "}" + Metadata interface{} // arbitrary metadata; has no effect on formatting } -func (s textWrap) Len() int { +func (s *textWrap) Len() int { return len(s.Prefix) + s.Value.Len() + len(s.Suffix) } -func (s1 textWrap) Equal(s2 textNode) bool { - if s2, ok := s2.(textWrap); ok { +func (s1 *textWrap) Equal(s2 textNode) bool { + if s2, ok := s2.(*textWrap); ok { return s1.Prefix == s2.Prefix && s1.Value.Equal(s2.Value) && s1.Suffix == s2.Suffix } return false } -func (s textWrap) String() string { +func (s *textWrap) String() string { var d diffMode var n indentMode _, s2 := s.formatCompactTo(nil, d) @@ -114,7 +118,7 @@ func (s textWrap) String() string { b = append(b, '\n') // Trailing newline return string(b) } -func (s textWrap) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { +func (s *textWrap) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { n0 := len(b) // Original buffer length b = append(b, s.Prefix...) b, s.Value = s.Value.formatCompactTo(b, d) @@ -124,7 +128,7 @@ func (s textWrap) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { } return b, s } -func (s textWrap) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte { +func (s *textWrap) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte { b = append(b, s.Prefix...) b = s.Value.formatExpandedTo(b, d, n) b = append(b, s.Suffix...) @@ -136,22 +140,23 @@ func (s textWrap) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte { // of the textList.formatCompactTo method. type textList []textRecord type textRecord struct { - Diff diffMode // e.g., 0 or '-' or '+' - Key string // e.g., "MyField" - Value textNode // textWrap | textLine - Comment fmt.Stringer // e.g., "6 identical fields" + Diff diffMode // e.g., 0 or '-' or '+' + Key string // e.g., "MyField" + Value textNode // textWrap | textLine + ElideComma bool // avoid trailing comma + Comment fmt.Stringer // e.g., "6 identical fields" } // AppendEllipsis appends a new ellipsis node to the list if none already // exists at the end. If cs is non-zero it coalesces the statistics with the // previous diffStats. func (s *textList) AppendEllipsis(ds diffStats) { - hasStats := ds != diffStats{} + hasStats := !ds.IsZero() if len(*s) == 0 || !(*s)[len(*s)-1].Value.Equal(textEllipsis) { if hasStats { - *s = append(*s, textRecord{Value: textEllipsis, Comment: ds}) + *s = append(*s, textRecord{Value: textEllipsis, ElideComma: true, Comment: ds}) } else { - *s = append(*s, textRecord{Value: textEllipsis}) + *s = append(*s, textRecord{Value: textEllipsis, ElideComma: true}) } return } @@ -191,7 +196,7 @@ func (s1 textList) Equal(s2 textNode) bool { } func (s textList) String() string { - return textWrap{"{", s, "}"}.String() + return (&textWrap{Prefix: "{", Value: s, Suffix: "}"}).String() } func (s textList) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { @@ -221,7 +226,7 @@ func (s textList) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { } // Force multi-lined output when printing a removed/inserted node that // is sufficiently long. - if (d == diffInserted || d == diffRemoved) && len(b[n0:]) > 80 { + if (d == diffInserted || d == diffRemoved) && len(b[n0:]) > maxColumnLength { multiLine = true } if !multiLine { @@ -236,16 +241,50 @@ func (s textList) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte { _, isLine := r.Value.(textLine) return r.Key == "" || !isLine }, - func(r textRecord) int { return len(r.Key) }, + func(r textRecord) int { return utf8.RuneCountInString(r.Key) }, ) alignValueLens := s.alignLens( func(r textRecord) bool { _, isLine := r.Value.(textLine) return !isLine || r.Value.Equal(textEllipsis) || r.Comment == nil }, - func(r textRecord) int { return len(r.Value.(textLine)) }, + func(r textRecord) int { return utf8.RuneCount(r.Value.(textLine)) }, ) + // Format lists of simple lists in a batched form. + // If the list is sequence of only textLine values, + // then batch multiple values on a single line. + var isSimple bool + for _, r := range s { + _, isLine := r.Value.(textLine) + isSimple = r.Diff == 0 && r.Key == "" && isLine && r.Comment == nil + if !isSimple { + break + } + } + if isSimple { + n++ + var batch []byte + emitBatch := func() { + if len(batch) > 0 { + b = n.appendIndent(append(b, '\n'), d) + b = append(b, bytes.TrimRight(batch, " ")...) + batch = batch[:0] + } + } + for _, r := range s { + line := r.Value.(textLine) + if len(batch)+len(line)+len(", ") > maxColumnLength { + emitBatch() + } + batch = append(batch, line...) + batch = append(batch, ", "...) + } + emitBatch() + n-- + return n.appendIndent(append(b, '\n'), d) + } + // Format the list as a multi-lined output. n++ for i, r := range s { @@ -256,7 +295,7 @@ func (s textList) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte { b = alignKeyLens[i].appendChar(b, ' ') b = r.Value.formatExpandedTo(b, d|r.Diff, n) - if !r.Value.Equal(textEllipsis) { + if !r.ElideComma { b = append(b, ',') } b = alignValueLens[i].appendChar(b, ' ') @@ -332,6 +371,11 @@ type diffStats struct { NumModified int } +func (s diffStats) IsZero() bool { + s.Name = "" + return s == diffStats{} +} + func (s diffStats) NumDiff() int { return s.NumRemoved + s.NumInserted + s.NumModified } diff --git a/vendor/github.com/google/uuid/.travis.yml b/vendor/github.com/google/uuid/.travis.yml deleted file mode 100644 index d8156a60ba9..00000000000 --- a/vendor/github.com/google/uuid/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: go - -go: - - 1.4.3 - - 1.5.3 - - tip - -script: - - go test -v ./... diff --git a/vendor/github.com/google/uuid/CONTRIBUTING.md b/vendor/github.com/google/uuid/CONTRIBUTING.md deleted file mode 100644 index 04fdf09f136..00000000000 --- a/vendor/github.com/google/uuid/CONTRIBUTING.md +++ /dev/null @@ -1,10 +0,0 @@ -# How to contribute - -We definitely welcome patches and contribution to this project! - -### Legal requirements - -In order to protect both you and ourselves, you will need to sign the -[Contributor License Agreement](https://cla.developers.google.com/clas). - -You may have already signed it for other Google projects. diff --git a/vendor/github.com/google/uuid/CONTRIBUTORS b/vendor/github.com/google/uuid/CONTRIBUTORS deleted file mode 100644 index b4bb97f6bcd..00000000000 --- a/vendor/github.com/google/uuid/CONTRIBUTORS +++ /dev/null @@ -1,9 +0,0 @@ -Paul Borman -bmatsuo -shawnps -theory -jboverfelt -dsymonds -cd1 -wallclockbuilder -dansouza diff --git a/vendor/github.com/google/uuid/LICENSE b/vendor/github.com/google/uuid/LICENSE deleted file mode 100644 index 5dc68268d90..00000000000 --- a/vendor/github.com/google/uuid/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009,2014 Google Inc. 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/google/uuid/README.md b/vendor/github.com/google/uuid/README.md deleted file mode 100644 index 9d92c11f16f..00000000000 --- a/vendor/github.com/google/uuid/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# uuid ![build status](https://travis-ci.org/google/uuid.svg?branch=master) -The uuid package generates and inspects UUIDs based on -[RFC 4122](http://tools.ietf.org/html/rfc4122) -and DCE 1.1: Authentication and Security Services. - -This package is based on the github.com/pborman/uuid package (previously named -code.google.com/p/go-uuid). It differs from these earlier packages in that -a UUID is a 16 byte array rather than a byte slice. One loss due to this -change is the ability to represent an invalid UUID (vs a NIL UUID). - -###### Install -`go get github.com/google/uuid` - -###### Documentation -[![GoDoc](https://godoc.org/github.com/google/uuid?status.svg)](http://godoc.org/github.com/google/uuid) - -Full `go doc` style documentation for the package can be viewed online without -installing this package by using the GoDoc site here: -http://godoc.org/github.com/google/uuid diff --git a/vendor/github.com/google/uuid/dce.go b/vendor/github.com/google/uuid/dce.go deleted file mode 100644 index fa820b9d309..00000000000 --- a/vendor/github.com/google/uuid/dce.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/binary" - "fmt" - "os" -) - -// A Domain represents a Version 2 domain -type Domain byte - -// Domain constants for DCE Security (Version 2) UUIDs. -const ( - Person = Domain(0) - Group = Domain(1) - Org = Domain(2) -) - -// NewDCESecurity returns a DCE Security (Version 2) UUID. -// -// The domain should be one of Person, Group or Org. -// On a POSIX system the id should be the users UID for the Person -// domain and the users GID for the Group. The meaning of id for -// the domain Org or on non-POSIX systems is site defined. -// -// For a given domain/id pair the same token may be returned for up to -// 7 minutes and 10 seconds. -func NewDCESecurity(domain Domain, id uint32) (UUID, error) { - uuid, err := NewUUID() - if err == nil { - uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 - uuid[9] = byte(domain) - binary.BigEndian.PutUint32(uuid[0:], id) - } - return uuid, err -} - -// NewDCEPerson returns a DCE Security (Version 2) UUID in the person -// domain with the id returned by os.Getuid. -// -// NewDCESecurity(Person, uint32(os.Getuid())) -func NewDCEPerson() (UUID, error) { - return NewDCESecurity(Person, uint32(os.Getuid())) -} - -// NewDCEGroup returns a DCE Security (Version 2) UUID in the group -// domain with the id returned by os.Getgid. -// -// NewDCESecurity(Group, uint32(os.Getgid())) -func NewDCEGroup() (UUID, error) { - return NewDCESecurity(Group, uint32(os.Getgid())) -} - -// Domain returns the domain for a Version 2 UUID. Domains are only defined -// for Version 2 UUIDs. -func (uuid UUID) Domain() Domain { - return Domain(uuid[9]) -} - -// ID returns the id for a Version 2 UUID. IDs are only defined for Version 2 -// UUIDs. -func (uuid UUID) ID() uint32 { - return binary.BigEndian.Uint32(uuid[0:4]) -} - -func (d Domain) String() string { - switch d { - case Person: - return "Person" - case Group: - return "Group" - case Org: - return "Org" - } - return fmt.Sprintf("Domain%d", int(d)) -} diff --git a/vendor/github.com/google/uuid/doc.go b/vendor/github.com/google/uuid/doc.go deleted file mode 100644 index 5b8a4b9af8c..00000000000 --- a/vendor/github.com/google/uuid/doc.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package uuid generates and inspects UUIDs. -// -// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security -// Services. -// -// A UUID is a 16 byte (128 bit) array. UUIDs may be used as keys to -// maps or compared directly. -package uuid diff --git a/vendor/github.com/google/uuid/go.mod b/vendor/github.com/google/uuid/go.mod deleted file mode 100644 index fc84cd79d4c..00000000000 --- a/vendor/github.com/google/uuid/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/google/uuid diff --git a/vendor/github.com/google/uuid/hash.go b/vendor/github.com/google/uuid/hash.go deleted file mode 100644 index b1746163151..00000000000 --- a/vendor/github.com/google/uuid/hash.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "crypto/md5" - "crypto/sha1" - "hash" -) - -// Well known namespace IDs and UUIDs -var ( - NameSpaceDNS = Must(Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceURL = Must(Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceOID = Must(Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceX500 = Must(Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) - Nil UUID // empty UUID, all zeros -) - -// NewHash returns a new UUID derived from the hash of space concatenated with -// data generated by h. The hash should be at least 16 byte in length. The -// first 16 bytes of the hash are used to form the UUID. The version of the -// UUID will be the lower 4 bits of version. NewHash is used to implement -// NewMD5 and NewSHA1. -func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { - h.Reset() - h.Write(space[:]) - h.Write(data) - s := h.Sum(nil) - var uuid UUID - copy(uuid[:], s) - uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4) - uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant - return uuid -} - -// NewMD5 returns a new MD5 (Version 3) UUID based on the -// supplied name space and data. It is the same as calling: -// -// NewHash(md5.New(), space, data, 3) -func NewMD5(space UUID, data []byte) UUID { - return NewHash(md5.New(), space, data, 3) -} - -// NewSHA1 returns a new SHA1 (Version 5) UUID based on the -// supplied name space and data. It is the same as calling: -// -// NewHash(sha1.New(), space, data, 5) -func NewSHA1(space UUID, data []byte) UUID { - return NewHash(sha1.New(), space, data, 5) -} diff --git a/vendor/github.com/google/uuid/marshal.go b/vendor/github.com/google/uuid/marshal.go deleted file mode 100644 index 7f9e0c6c0e3..00000000000 --- a/vendor/github.com/google/uuid/marshal.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import "fmt" - -// MarshalText implements encoding.TextMarshaler. -func (uuid UUID) MarshalText() ([]byte, error) { - var js [36]byte - encodeHex(js[:], uuid) - return js[:], nil -} - -// UnmarshalText implements encoding.TextUnmarshaler. -func (uuid *UUID) UnmarshalText(data []byte) error { - id, err := ParseBytes(data) - if err == nil { - *uuid = id - } - return err -} - -// MarshalBinary implements encoding.BinaryMarshaler. -func (uuid UUID) MarshalBinary() ([]byte, error) { - return uuid[:], nil -} - -// UnmarshalBinary implements encoding.BinaryUnmarshaler. -func (uuid *UUID) UnmarshalBinary(data []byte) error { - if len(data) != 16 { - return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) - } - copy(uuid[:], data) - return nil -} diff --git a/vendor/github.com/google/uuid/node.go b/vendor/github.com/google/uuid/node.go deleted file mode 100644 index d651a2b0619..00000000000 --- a/vendor/github.com/google/uuid/node.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "sync" -) - -var ( - nodeMu sync.Mutex - ifname string // name of interface being used - nodeID [6]byte // hardware for version 1 UUIDs - zeroID [6]byte // nodeID with only 0's -) - -// NodeInterface returns the name of the interface from which the NodeID was -// derived. The interface "user" is returned if the NodeID was set by -// SetNodeID. -func NodeInterface() string { - defer nodeMu.Unlock() - nodeMu.Lock() - return ifname -} - -// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. -// If name is "" then the first usable interface found will be used or a random -// Node ID will be generated. If a named interface cannot be found then false -// is returned. -// -// SetNodeInterface never fails when name is "". -func SetNodeInterface(name string) bool { - defer nodeMu.Unlock() - nodeMu.Lock() - return setNodeInterface(name) -} - -func setNodeInterface(name string) bool { - iname, addr := getHardwareInterface(name) // null implementation for js - if iname != "" && addr != nil { - ifname = iname - copy(nodeID[:], addr) - return true - } - - // We found no interfaces with a valid hardware address. If name - // does not specify a specific interface generate a random Node ID - // (section 4.1.6) - if name == "" { - ifname = "random" - randomBits(nodeID[:]) - return true - } - return false -} - -// NodeID returns a slice of a copy of the current Node ID, setting the Node ID -// if not already set. -func NodeID() []byte { - defer nodeMu.Unlock() - nodeMu.Lock() - if nodeID == zeroID { - setNodeInterface("") - } - nid := nodeID - return nid[:] -} - -// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes -// of id are used. If id is less than 6 bytes then false is returned and the -// Node ID is not set. -func SetNodeID(id []byte) bool { - if len(id) < 6 { - return false - } - defer nodeMu.Unlock() - nodeMu.Lock() - copy(nodeID[:], id) - ifname = "user" - return true -} - -// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is -// not valid. The NodeID is only well defined for version 1 and 2 UUIDs. -func (uuid UUID) NodeID() []byte { - var node [6]byte - copy(node[:], uuid[10:]) - return node[:] -} diff --git a/vendor/github.com/google/uuid/node_js.go b/vendor/github.com/google/uuid/node_js.go deleted file mode 100644 index 24b78edc907..00000000000 --- a/vendor/github.com/google/uuid/node_js.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build js - -package uuid - -// getHardwareInterface returns nil values for the JS version of the code. -// This remvoves the "net" dependency, because it is not used in the browser. -// Using the "net" library inflates the size of the transpiled JS code by 673k bytes. -func getHardwareInterface(name string) (string, []byte) { return "", nil } diff --git a/vendor/github.com/google/uuid/node_net.go b/vendor/github.com/google/uuid/node_net.go deleted file mode 100644 index 0cbbcddbd6e..00000000000 --- a/vendor/github.com/google/uuid/node_net.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !js - -package uuid - -import "net" - -var interfaces []net.Interface // cached list of interfaces - -// getHardwareInterface returns the name and hardware address of interface name. -// If name is "" then the name and hardware address of one of the system's -// interfaces is returned. If no interfaces are found (name does not exist or -// there are no interfaces) then "", nil is returned. -// -// Only addresses of at least 6 bytes are returned. -func getHardwareInterface(name string) (string, []byte) { - if interfaces == nil { - var err error - interfaces, err = net.Interfaces() - if err != nil { - return "", nil - } - } - for _, ifs := range interfaces { - if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { - return ifs.Name, ifs.HardwareAddr - } - } - return "", nil -} diff --git a/vendor/github.com/google/uuid/sql.go b/vendor/github.com/google/uuid/sql.go deleted file mode 100644 index f326b54db37..00000000000 --- a/vendor/github.com/google/uuid/sql.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "database/sql/driver" - "fmt" -) - -// Scan implements sql.Scanner so UUIDs can be read from databases transparently -// Currently, database types that map to string and []byte are supported. Please -// consult database-specific driver documentation for matching types. -func (uuid *UUID) Scan(src interface{}) error { - switch src := src.(type) { - case nil: - return nil - - case string: - // if an empty UUID comes from a table, we return a null UUID - if src == "" { - return nil - } - - // see Parse for required string format - u, err := Parse(src) - if err != nil { - return fmt.Errorf("Scan: %v", err) - } - - *uuid = u - - case []byte: - // if an empty UUID comes from a table, we return a null UUID - if len(src) == 0 { - return nil - } - - // assumes a simple slice of bytes if 16 bytes - // otherwise attempts to parse - if len(src) != 16 { - return uuid.Scan(string(src)) - } - copy((*uuid)[:], src) - - default: - return fmt.Errorf("Scan: unable to scan type %T into UUID", src) - } - - return nil -} - -// Value implements sql.Valuer so that UUIDs can be written to databases -// transparently. Currently, UUIDs map to strings. Please consult -// database-specific driver documentation for matching types. -func (uuid UUID) Value() (driver.Value, error) { - return uuid.String(), nil -} diff --git a/vendor/github.com/google/uuid/time.go b/vendor/github.com/google/uuid/time.go deleted file mode 100644 index e6ef06cdc87..00000000000 --- a/vendor/github.com/google/uuid/time.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/binary" - "sync" - "time" -) - -// A Time represents a time as the number of 100's of nanoseconds since 15 Oct -// 1582. -type Time int64 - -const ( - lillian = 2299160 // Julian day of 15 Oct 1582 - unix = 2440587 // Julian day of 1 Jan 1970 - epoch = unix - lillian // Days between epochs - g1582 = epoch * 86400 // seconds between epochs - g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs -) - -var ( - timeMu sync.Mutex - lasttime uint64 // last time we returned - clockSeq uint16 // clock sequence for this run - - timeNow = time.Now // for testing -) - -// UnixTime converts t the number of seconds and nanoseconds using the Unix -// epoch of 1 Jan 1970. -func (t Time) UnixTime() (sec, nsec int64) { - sec = int64(t - g1582ns100) - nsec = (sec % 10000000) * 100 - sec /= 10000000 - return sec, nsec -} - -// GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and -// clock sequence as well as adjusting the clock sequence as needed. An error -// is returned if the current time cannot be determined. -func GetTime() (Time, uint16, error) { - defer timeMu.Unlock() - timeMu.Lock() - return getTime() -} - -func getTime() (Time, uint16, error) { - t := timeNow() - - // If we don't have a clock sequence already, set one. - if clockSeq == 0 { - setClockSequence(-1) - } - now := uint64(t.UnixNano()/100) + g1582ns100 - - // If time has gone backwards with this clock sequence then we - // increment the clock sequence - if now <= lasttime { - clockSeq = ((clockSeq + 1) & 0x3fff) | 0x8000 - } - lasttime = now - return Time(now), clockSeq, nil -} - -// ClockSequence returns the current clock sequence, generating one if not -// already set. The clock sequence is only used for Version 1 UUIDs. -// -// The uuid package does not use global static storage for the clock sequence or -// the last time a UUID was generated. Unless SetClockSequence is used, a new -// random clock sequence is generated the first time a clock sequence is -// requested by ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) -func ClockSequence() int { - defer timeMu.Unlock() - timeMu.Lock() - return clockSequence() -} - -func clockSequence() int { - if clockSeq == 0 { - setClockSequence(-1) - } - return int(clockSeq & 0x3fff) -} - -// SetClockSequence sets the clock sequence to the lower 14 bits of seq. Setting to -// -1 causes a new sequence to be generated. -func SetClockSequence(seq int) { - defer timeMu.Unlock() - timeMu.Lock() - setClockSequence(seq) -} - -func setClockSequence(seq int) { - if seq == -1 { - var b [2]byte - randomBits(b[:]) // clock sequence - seq = int(b[0])<<8 | int(b[1]) - } - oldSeq := clockSeq - clockSeq = uint16(seq&0x3fff) | 0x8000 // Set our variant - if oldSeq != clockSeq { - lasttime = 0 - } -} - -// Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in -// uuid. The time is only defined for version 1 and 2 UUIDs. -func (uuid UUID) Time() Time { - time := int64(binary.BigEndian.Uint32(uuid[0:4])) - time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 - time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 - return Time(time) -} - -// ClockSequence returns the clock sequence encoded in uuid. -// The clock sequence is only well defined for version 1 and 2 UUIDs. -func (uuid UUID) ClockSequence() int { - return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff -} diff --git a/vendor/github.com/google/uuid/util.go b/vendor/github.com/google/uuid/util.go deleted file mode 100644 index 5ea6c737806..00000000000 --- a/vendor/github.com/google/uuid/util.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "io" -) - -// randomBits completely fills slice b with random data. -func randomBits(b []byte) { - if _, err := io.ReadFull(rander, b); err != nil { - panic(err.Error()) // rand should never fail - } -} - -// xvalues returns the value of a byte as a hexadecimal digit or 255. -var xvalues = [256]byte{ - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, - 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, -} - -// xtob converts hex characters x1 and x2 into a byte. -func xtob(x1, x2 byte) (byte, bool) { - b1 := xvalues[x1] - b2 := xvalues[x2] - return (b1 << 4) | b2, b1 != 255 && b2 != 255 -} diff --git a/vendor/github.com/google/uuid/uuid.go b/vendor/github.com/google/uuid/uuid.go deleted file mode 100644 index 524404cc522..00000000000 --- a/vendor/github.com/google/uuid/uuid.go +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "bytes" - "crypto/rand" - "encoding/hex" - "errors" - "fmt" - "io" - "strings" -) - -// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC -// 4122. -type UUID [16]byte - -// A Version represents a UUID's version. -type Version byte - -// A Variant represents a UUID's variant. -type Variant byte - -// Constants returned by Variant. -const ( - Invalid = Variant(iota) // Invalid UUID - RFC4122 // The variant specified in RFC4122 - Reserved // Reserved, NCS backward compatibility. - Microsoft // Reserved, Microsoft Corporation backward compatibility. - Future // Reserved for future definition. -) - -var rander = rand.Reader // random function - -// Parse decodes s into a UUID or returns an error. Both the standard UUID -// forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the -// Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex -// encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx. -func Parse(s string) (UUID, error) { - var uuid UUID - switch len(s) { - // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - case 36: - - // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - case 36 + 9: - if strings.ToLower(s[:9]) != "urn:uuid:" { - return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9]) - } - s = s[9:] - - // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - case 36 + 2: - s = s[1:] - - // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - case 32: - var ok bool - for i := range uuid { - uuid[i], ok = xtob(s[i*2], s[i*2+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - } - return uuid, nil - default: - return uuid, fmt.Errorf("invalid UUID length: %d", len(s)) - } - // s is now at least 36 bytes long - // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { - return uuid, errors.New("invalid UUID format") - } - for i, x := range [16]int{ - 0, 2, 4, 6, - 9, 11, - 14, 16, - 19, 21, - 24, 26, 28, 30, 32, 34} { - v, ok := xtob(s[x], s[x+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - uuid[i] = v - } - return uuid, nil -} - -// ParseBytes is like Parse, except it parses a byte slice instead of a string. -func ParseBytes(b []byte) (UUID, error) { - var uuid UUID - switch len(b) { - case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - if !bytes.Equal(bytes.ToLower(b[:9]), []byte("urn:uuid:")) { - return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9]) - } - b = b[9:] - case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - b = b[1:] - case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - var ok bool - for i := 0; i < 32; i += 2 { - uuid[i/2], ok = xtob(b[i], b[i+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - } - return uuid, nil - default: - return uuid, fmt.Errorf("invalid UUID length: %d", len(b)) - } - // s is now at least 36 bytes long - // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' { - return uuid, errors.New("invalid UUID format") - } - for i, x := range [16]int{ - 0, 2, 4, 6, - 9, 11, - 14, 16, - 19, 21, - 24, 26, 28, 30, 32, 34} { - v, ok := xtob(b[x], b[x+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - uuid[i] = v - } - return uuid, nil -} - -// MustParse is like Parse but panics if the string cannot be parsed. -// It simplifies safe initialization of global variables holding compiled UUIDs. -func MustParse(s string) UUID { - uuid, err := Parse(s) - if err != nil { - panic(`uuid: Parse(` + s + `): ` + err.Error()) - } - return uuid -} - -// FromBytes creates a new UUID from a byte slice. Returns an error if the slice -// does not have a length of 16. The bytes are copied from the slice. -func FromBytes(b []byte) (uuid UUID, err error) { - err = uuid.UnmarshalBinary(b) - return uuid, err -} - -// Must returns uuid if err is nil and panics otherwise. -func Must(uuid UUID, err error) UUID { - if err != nil { - panic(err) - } - return uuid -} - -// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -// , or "" if uuid is invalid. -func (uuid UUID) String() string { - var buf [36]byte - encodeHex(buf[:], uuid) - return string(buf[:]) -} - -// URN returns the RFC 2141 URN form of uuid, -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid. -func (uuid UUID) URN() string { - var buf [36 + 9]byte - copy(buf[:], "urn:uuid:") - encodeHex(buf[9:], uuid) - return string(buf[:]) -} - -func encodeHex(dst []byte, uuid UUID) { - hex.Encode(dst, uuid[:4]) - dst[8] = '-' - hex.Encode(dst[9:13], uuid[4:6]) - dst[13] = '-' - hex.Encode(dst[14:18], uuid[6:8]) - dst[18] = '-' - hex.Encode(dst[19:23], uuid[8:10]) - dst[23] = '-' - hex.Encode(dst[24:], uuid[10:]) -} - -// Variant returns the variant encoded in uuid. -func (uuid UUID) Variant() Variant { - switch { - case (uuid[8] & 0xc0) == 0x80: - return RFC4122 - case (uuid[8] & 0xe0) == 0xc0: - return Microsoft - case (uuid[8] & 0xe0) == 0xe0: - return Future - default: - return Reserved - } -} - -// Version returns the version of uuid. -func (uuid UUID) Version() Version { - return Version(uuid[6] >> 4) -} - -func (v Version) String() string { - if v > 15 { - return fmt.Sprintf("BAD_VERSION_%d", v) - } - return fmt.Sprintf("VERSION_%d", v) -} - -func (v Variant) String() string { - switch v { - case RFC4122: - return "RFC4122" - case Reserved: - return "Reserved" - case Microsoft: - return "Microsoft" - case Future: - return "Future" - case Invalid: - return "Invalid" - } - return fmt.Sprintf("BadVariant%d", int(v)) -} - -// SetRand sets the random number generator to r, which implements io.Reader. -// If r.Read returns an error when the package requests random data then -// a panic will be issued. -// -// Calling SetRand with nil sets the random number generator to the default -// generator. -func SetRand(r io.Reader) { - if r == nil { - rander = rand.Reader - return - } - rander = r -} diff --git a/vendor/github.com/google/uuid/version1.go b/vendor/github.com/google/uuid/version1.go deleted file mode 100644 index 199a1ac6540..00000000000 --- a/vendor/github.com/google/uuid/version1.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/binary" -) - -// NewUUID returns a Version 1 UUID based on the current NodeID and clock -// sequence, and the current time. If the NodeID has not been set by SetNodeID -// or SetNodeInterface then it will be set automatically. If the NodeID cannot -// be set NewUUID returns nil. If clock sequence has not been set by -// SetClockSequence then it will be set automatically. If GetTime fails to -// return the current NewUUID returns nil and an error. -// -// In most cases, New should be used. -func NewUUID() (UUID, error) { - nodeMu.Lock() - if nodeID == zeroID { - setNodeInterface("") - } - nodeMu.Unlock() - - var uuid UUID - now, seq, err := GetTime() - if err != nil { - return uuid, err - } - - timeLow := uint32(now & 0xffffffff) - timeMid := uint16((now >> 32) & 0xffff) - timeHi := uint16((now >> 48) & 0x0fff) - timeHi |= 0x1000 // Version 1 - - binary.BigEndian.PutUint32(uuid[0:], timeLow) - binary.BigEndian.PutUint16(uuid[4:], timeMid) - binary.BigEndian.PutUint16(uuid[6:], timeHi) - binary.BigEndian.PutUint16(uuid[8:], seq) - copy(uuid[10:], nodeID[:]) - - return uuid, nil -} diff --git a/vendor/github.com/google/uuid/version4.go b/vendor/github.com/google/uuid/version4.go deleted file mode 100644 index 84af91c9f54..00000000000 --- a/vendor/github.com/google/uuid/version4.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import "io" - -// New creates a new random UUID or panics. New is equivalent to -// the expression -// -// uuid.Must(uuid.NewRandom()) -func New() UUID { - return Must(NewRandom()) -} - -// NewRandom returns a Random (Version 4) UUID. -// -// The strength of the UUIDs is based on the strength of the crypto/rand -// package. -// -// A note about uniqueness derived from the UUID Wikipedia entry: -// -// Randomly generated UUIDs have 122 random bits. One's annual risk of being -// hit by a meteorite is estimated to be one chance in 17 billion, that -// means the probability is about 0.00000000006 (6 × 10−11), -// equivalent to the odds of creating a few tens of trillions of UUIDs in a -// year and having one duplicate. -func NewRandom() (UUID, error) { - var uuid UUID - _, err := io.ReadFull(rander, uuid[:]) - if err != nil { - return Nil, err - } - uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 - uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 - return uuid, nil -} diff --git a/vendor/github.com/gookit/color/.travis.yml b/vendor/github.com/gookit/color/.travis.yml index b2df0025643..4589f20d849 100644 --- a/vendor/github.com/gookit/color/.travis.yml +++ b/vendor/github.com/gookit/color/.travis.yml @@ -4,6 +4,7 @@ go: - '1.10' - '1.11' - '1.12' + - '1.13' before_install: - go get github.com/mattn/goveralls diff --git a/vendor/github.com/gookit/color/README.md b/vendor/github.com/gookit/color/README.md index 643de3a27a0..7e85f8084f4 100644 --- a/vendor/github.com/gookit/color/README.md +++ b/vendor/github.com/gookit/color/README.md @@ -1,33 +1,40 @@ # CLI Color -[![GoDoc](https://godoc.org/github.com/gookit/color?status.svg)](https://godoc.org/github.com/gookit/color) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/51b28c5f7ffe4cc2b0f12ecf25ed247f)](https://app.codacy.com/app/inhere/color) +[![GoDoc](https://godoc.org/github.com/gookit/color?status.svg)](https://pkg.go.dev/github.com/gookit/color?tab=overview) +[![GitHub tag (latest SemVer)](https://img.shields.io/github/tag/gookit/color)](https://github.com/gookit/color) [![Build Status](https://travis-ci.org/gookit/color.svg?branch=master)](https://travis-ci.org/gookit/color) [![Coverage Status](https://coveralls.io/repos/github/gookit/color/badge.svg?branch=master)](https://coveralls.io/github/gookit/color?branch=master) [![Go Report Card](https://goreportcard.com/badge/github.com/gookit/color)](https://goreportcard.com/report/github.com/gookit/color) A command-line color library with true color support, universal API methods and Windows support. -> **[中文说明](README_cn.md)** +> **[中文说明](README.zh-CN.md)** Basic color preview: ![basic-color](_examples/images/basic-color.png) +Now, it's works on windows CMD and PowerShell: + +![color-on-cmd-pwsh](_examples/images/color-on-cmd-pwsh.jpg) + ## Features -- Simple to use, zero dependencies -- Supports rich color output: 16-color, 256-color, true color (24-bit) - - 16-color output is the most commonly used and most widely supported, working on any Windows version - - See [this gist](https://gist.github.com/XVilka/8346728) for information on true color support -- Generic API methods: `Print`, `Printf`, `Println`, `Sprint`, `Sprintf` -- Supports HTML tag-style color rendering, such as `message` -- Basic colors: `Bold`, `Black`, `White`, `Gray`, `Red`, `Green`, `Yellow`, `Blue`, `Magenta`, `Cyan` -- Additional styles: `Info`, `Note`, `Light`, `Error`, `Danger`, `Notice`, `Success`, `Comment`, `Primary`, `Warning`, `Question`, `Secondary` + - Simple to use, zero dependencies + - Supports rich color output: 16-color, 256-color, true color (24-bit, RGB) + - 16-color output is the most commonly used and most widely supported, working on any Windows version + - ~~See [this gist](https://gist.github.com/XVilka/8346728) for information on true color support~~ + - Since `v1.2.4` **the 256-color, true color (24-bit) support windows CMD and PowerShell** + - Generic API methods: `Print`, `Printf`, `Println`, `Sprint`, `Sprintf` + - Supports HTML tag-style color rendering, such as `message`. Support working on windows `cmd` `powerShell` + - Basic colors: `Bold`, `Black`, `White`, `Gray`, `Red`, `Green`, `Yellow`, `Blue`, `Magenta`, `Cyan` + - Additional styles: `Info`, `Note`, `Light`, `Error`, `Danger`, `Notice`, `Success`, `Comment`, `Primary`, `Warning`, `Question`, `Secondary` ## GoDoc -- [godoc for gopkg](https://godoc.org/gopkg.in/gookit/color.v1) -- [godoc for github](https://godoc.org/github.com/gookit/color) + - [godoc for gopkg](https://pkg.go.dev/gopkg.in/gookit/color.v1) + - [godoc for github](https://pkg.go.dev/github.com/gookit/color) ## Quick start @@ -42,12 +49,16 @@ package main import ( "fmt" + "github.com/gookit/color" ) func main() { - // simple usage + // quick use like fmt.Print* + color.Red.Println("Simple to use color") + color.Green.Print("Simple to use color\n") color.Cyan.Printf("Simple to use %s\n", "color") + color.Yellow.Printf("Simple to use %s\n", "color") // use like func red := color.FgRed.Render @@ -87,22 +98,49 @@ Run demo: `go run ./_examples/demo.go` ![colored-out](_examples/images/color-demo.jpg) -## Detailed usage +## Custom Build Color + +```go +// Only use foreground color +color.FgCyan.Printf("Simple to use %s\n", "color") +// Only use background color +color.BgRed.Printf("Simple to use %s\n", "color") + +// Full custom: foreground, background, option +myStyle := color.New(color.FgWhite, color.BgBlack, color.OpBold) +myStyle.Println("custom color style") -### Basic color +// can also: +color.Style{color.FgCyan, color.OpBold}.Println("custom color style") +``` + +custom set console settings: + +```go +// set console color +color.Set(color.FgCyan) + +// print message +fmt.Print("message") + +// reset console settings +color.Reset() +``` + +## Basic Color Supported on any Windows version. -- `color.Bold` -- `color.Black` -- `color.White` -- `color.Gray` -- `color.Red` -- `color.Green` -- `color.Yellow` -- `color.Blue` -- `color.Magenta` -- `color.Cyan` + - `color.Bold` + - `color.Black` + - `color.White` + - `color.Gray` + - `color.Red` + - `color.Green` + - `color.Yellow` + - `color.Blue` + - `color.Magenta` + - `color.Cyan` ```go color.Bold.Println("bold message") @@ -113,44 +151,72 @@ Run demo: `go run ./_examples/basiccolor.go` ![basic-color](_examples/images/basic-color.png) -### Additional styles +## Additional styles Supported on any Windows version. -- `color.Info` -- `color.Note` -- `color.Light` -- `color.Error` -- `color.Danger` -- `color.Notice` -- `color.Success` -- `color.Comment` -- `color.Primary` -- `color.Warning` -- `color.Question` -- `color.Secondary` + - `color.Info` + - `color.Note` + - `color.Light` + - `color.Error` + - `color.Danger` + - `color.Debug` + - `color.Notice` + - `color.Success` + - `color.Comment` + - `color.Primary` + - `color.Warning` + - `color.Question` + - `color.Secondary` + +### Basic Style ```go // print message -color.Info.Print("Info message") -color.Success.Print("Success message") +color.Info.Println("Info message") +color.Success.Println("Success message") +``` -// prompt message -color.Info.Prompt("prompt style message") -color.Warn.Prompt("prompt style message") +Run demo: `go run ./_examples/theme_basic.go` + +![theme-basic](_examples/images/theme-basic.jpg) + +### Tips Style -// tips message +```go color.Info.Tips("tips style message") color.Warn.Tips("tips style message") ``` -Run demo: `go run ./_examples/theme_style.go` +Run demo: `go run ./_examples/theme_tips.go` + +![theme-tips](_examples/images/theme-tips.jpg) + +### Prompt Style + +```go +color.Info.Prompt("prompt style message") +color.Warn.Prompt("prompt style message") +``` + +Run demo: `go run ./_examples/theme_prompt.go` + +![theme-prompt](_examples/images/theme-prompt.jpg) + +### Block Style -![theme-style](_examples/images/theme-style.jpg) +```go +color.Info.Block("block style message") +color.Warn.Block("block style message") +``` -### HTML-like tag usage +Run demo: `go run ./_examples/theme_block.go` -Not supported on Windows (tags will be stripped). +![theme-block](_examples/images/theme-block.jpg) + +## HTML-like tag usage + +**Supported** on Windows `cmd.exe` `PowerShell` . ```go // use style tag @@ -178,6 +244,8 @@ Run demo: `go run ./_examples/colortag.go` ## 256-color usage +> 256 colors support Windows CMD, PowerShell environment after `v1.2.4` + ### Set the foreground or background color - `color.C256(val uint8, isBg ...bool) Color256` @@ -210,9 +278,23 @@ Run demo: `go run ./_examples/color256.go` ## Use RGB color +> RGB colors support Windows CMD, PowerShell environment after `v1.2.4` + +example: + +```go +color.RGB(30, 144, 255).Println("message. use RGB number") + +color.HEX("#1976D2").Println("blue-darken") +color.HEX("#D50000", true).Println("red-accent. use HEX style") + +color.RGBStyleFromString("213,0,0").Println("red-accent. use RGB number") +color.HEXStyle("eee", "D50000").Println("deep-purple color") +``` + ### Set the foreground or background color -- `color.RGB(r, g, b uint8, isBg ...bool) RGBColor` + - `color.RGB(r, g, b uint8, isBg ...bool) RGBColor` ```go c := color.RGB(30,144,255) // fg color @@ -226,7 +308,7 @@ c.Printf("format %s", "message") Create a style from an hexadecimal color string: -- `color.HEX(hex string, isBg ...bool) RGBColor` + - `color.HEX(hex string, isBg ...bool) RGBColor` ```go c := HEX("ccc") // can also: "cccccc" "#cccccc" @@ -242,7 +324,7 @@ c.Printf("format %s", "message") Can be used to set the foreground and background colors at the same time. -- `color.NewRGBStyle(fg RGBColor, bg ...RGBColor) *RGBStyle` + - `color.NewRGBStyle(fg RGBColor, bg ...RGBColor) *RGBStyle` ```go s := NewRGBStyle(RGB(20, 144, 234), RGB(234, 78, 23)) @@ -252,7 +334,7 @@ s.Printf("format %s", "message") Create a style from an hexadecimal color string: -- `color.HEXStyle(fg string, bg ...string) *RGBStyle` + - `color.HEXStyle(fg string, bg ...string) *RGBStyle` ```go s := HEXStyle("11aa23", "eee") @@ -262,24 +344,24 @@ s.Printf("format %s", "message") ## Gookit packages -- [gookit/ini](https://github.com/gookit/ini) Go config management, use INI files -- [gookit/rux](https://github.com/gookit/rux) Simple and fast request router for golang HTTP -- [gookit/gcli](https://github.com/gookit/gcli) build CLI application, tool library, running CLI commands -- [gookit/event](https://github.com/gookit/event) Lightweight event manager and dispatcher implements by Go -- [gookit/cache](https://github.com/gookit/cache) Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached. -- [gookit/config](https://github.com/gookit/config) Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags -- [gookit/color](https://github.com/gookit/color) A command-line color library with true color support, universal API methods and Windows support -- [gookit/filter](https://github.com/gookit/filter) Provide filtering, sanitizing, and conversion of golang data -- [gookit/validate](https://github.com/gookit/validate) Use for data validation and filtering. support Map, Struct, Form data -- [gookit/goutil](https://github.com/gookit/goutil) Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more -- More please see https://github.com/gookit + - [gookit/ini](https://github.com/gookit/ini) Go config management, use INI files + - [gookit/rux](https://github.com/gookit/rux) Simple and fast request router for golang HTTP + - [gookit/gcli](https://github.com/gookit/gcli) build CLI application, tool library, running CLI commands + - [gookit/event](https://github.com/gookit/event) Lightweight event manager and dispatcher implements by Go + - [gookit/cache](https://github.com/gookit/cache) Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached. + - [gookit/config](https://github.com/gookit/config) Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags + - [gookit/color](https://github.com/gookit/color) A command-line color library with true color support, universal API methods and Windows support + - [gookit/filter](https://github.com/gookit/filter) Provide filtering, sanitizing, and conversion of golang data + - [gookit/validate](https://github.com/gookit/validate) Use for data validation and filtering. support Map, Struct, Form data + - [gookit/goutil](https://github.com/gookit/goutil) Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more + - More please see https://github.com/gookit ## See also -- [`issue9/term`](https://github.com/issue9/term) -- [`beego/bee`](https://github.com/beego/bee) -- [`inhere/console`](https://github.com/inhere/php-console) -- [ANSI escape code](https://en.wikipedia.org/wiki/ANSI_escape_code) + - [`issue9/term`](https://github.com/issue9/term) + - [`beego/bee`](https://github.com/beego/bee) + - [`inhere/console`](https://github.com/inhere/php-console) + - [ANSI escape code](https://en.wikipedia.org/wiki/ANSI_escape_code) ## License diff --git a/vendor/github.com/gookit/color/README.zh-CN.md b/vendor/github.com/gookit/color/README.zh-CN.md new file mode 100644 index 00000000000..009e01f8c5f --- /dev/null +++ b/vendor/github.com/gookit/color/README.zh-CN.md @@ -0,0 +1,373 @@ +# CLI Color + +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/51b28c5f7ffe4cc2b0f12ecf25ed247f)](https://app.codacy.com/app/inhere/color) +[![GoDoc](https://godoc.org/github.com/gookit/color?status.svg)](https://pkg.go.dev/github.com/gookit/color?tab=overview) +[![GitHub tag (latest SemVer)](https://img.shields.io/github/tag/gookit/color)](https://github.com/gookit/color) +[![Build Status](https://travis-ci.org/gookit/color.svg?branch=master)](https://travis-ci.org/gookit/color) +[![Coverage Status](https://coveralls.io/repos/github/gookit/color/badge.svg?branch=master)](https://coveralls.io/github/gookit/color?branch=master) +[![Go Report Card](https://goreportcard.com/badge/github.com/gookit/color)](https://goreportcard.com/report/github.com/gookit/color) + +Golang下的命令行色彩使用库, 拥有丰富的色彩渲染输出,通用的API方法,兼容Windows系统 + +> **[EN README](README.md)** + +基本颜色预览: + +![basic-color](_examples/images/basic-color.png) + +现在,支持windows CMD和PowerShell中工作: + +![color-on-cmd-pwsh](_examples/images/color-on-cmd-pwsh.jpg) + +## 功能特色 + + - 使用简单方便,无其他依赖 + - 支持丰富的颜色输出, 16色(4bit),256色(8bit),RGB色彩(24bit, RGB) + - 16色(4bit)是最常用和支持最广的,支持Windows `cmd.exe` + - ~~另外两种支持 `linux` `mac` 和 Windows下的 `ConEmu` `git-bash` `mintty` 等部分终端~~ + - 自 `v1.2.4` 起 **256色(8bit),RGB色彩(24bit)均支持windows CMD和PowerShell终端** + - 通用的API方法:`Print` `Printf` `Println` `Sprint` `Sprintf` + - 同时支持html标签式的颜色渲染. eg: `message` + - 基础色彩: `Bold` `Black` `White` `Gray` `Red` `Green` `Yellow` `Blue` `Magenta` `Cyan` + - 扩展风格: `Info` `Note` `Light` `Error` `Danger` `Notice` `Success` `Comment` `Primary` `Warning` `Question` `Secondary` + - 支持Linux、Mac同时兼容Windows系统环境 + +## GoDoc + + - [godoc for gopkg](https://pkg.go.dev/gopkg.in/gookit/color.v1) + - [godoc for github](https://pkg.go.dev/github.com/gookit/color) + +## 快速开始 + +如下,引入当前包就可以快速的使用 + +```bash +import "gopkg.in/gookit/color.v1" // 推荐 +// or +import "github.com/gookit/color" +``` + +### 如何使用 + +```go +package main + +import ( + "fmt" + + "github.com/gookit/color" +) + +func main() { + // 简单快速的使用,跟 fmt.Print* 类似 + color.Red.Println("Simple to use color") + color.Green.Print("Simple to use color\n") + color.Cyan.Printf("Simple to use %s\n", "color") + color.Yellow.Printf("Simple to use %s\n", "color") + + // use like func + red := color.FgRed.Render + green := color.FgGreen.Render + fmt.Printf("%s line %s library\n", red("Command"), green("color")) + + // 自定义颜色 + color.New(color.FgWhite, color.BgBlack).Println("custom color style") + + // 也可以: + color.Style{color.FgCyan, color.OpBold}.Println("custom color style") + + // internal style: + color.Info.Println("message") + color.Warn.Println("message") + color.Error.Println("message") + + // 使用颜色标签 + color.Print("hello, welcome\n") + + // apply a style tag + color.Tag("info").Println("info style text") + + // prompt message + color.Info.Prompt("prompt style message") + color.Warn.Prompt("prompt style message") + + // tips message + color.Info.Tips("tips style message") + color.Warn.Tips("tips style message") +} +``` + +> 运行 demo: `go run ./_examples/demo.go` + +![colored-out](_examples/images/color-demo.jpg) + +## 构建风格 + +```go +// 仅设置前景色 +color.FgCyan.Printf("Simple to use %s\n", "color") +// 仅设置背景色 +color.BgRed.Printf("Simple to use %s\n", "color") + +// 完全自定义: 前景色 背景色 选项 +style := color.New(color.FgWhite, color.BgBlack, color.OpBold) +style.Println("custom color style") + +// 也可以: +color.Style{color.FgCyan, color.OpBold}.Println("custom color style") +``` + +直接设置控制台属性: + +```go +// 设置console颜色 +color.Set(color.FgCyan) + +// 输出信息 +fmt.Print("message") + +// 重置console颜色 +color.Reset() +``` + +> 当然,color已经内置丰富的色彩风格支持 + +## 基础颜色方法 + +> 支持在windows `cmd.exe` 使用 + + - `color.Bold` + - `color.Black` + - `color.White` + - `color.Gray` + - `color.Red` + - `color.Green` + - `color.Yellow` + - `color.Blue` + - `color.Magenta` + - `color.Cyan` + +```go +color.Bold.Println("bold message") +color.Yellow.Println("yellow message") +``` + +> 运行demo: `go run ./_examples/basiccolor.go` + +![basic-color](_examples/images/basic-color.png) + +## 扩展风格方法 + +> 支持在windows `cmd.exe` 使用 + + - `color.Info` + - `color.Note` + - `color.Light` + - `color.Error` + - `color.Danger` + - `color.Notice` + - `color.Success` + - `color.Comment` + - `color.Primary` + - `color.Warning` + - `color.Question` + - `color.Secondary` + +### 基础风格 + +```go +// print message +color.Info.Println("Info message") +color.Success.Println("Success message") +``` + +Run demo: `go run ./_examples/theme_basic.go` + +![theme-basic](_examples/images/theme-basic.jpg) + +### 简约提示风格 + +```go +color.Info.Tips("tips style message") +color.Warn.Tips("tips style message") +``` + +Run demo: `go run ./_examples/theme_tips.go` + +![theme-tips](_examples/images/theme-tips.jpg) + +### 着重提示风格 + +```go +color.Info.Prompt("prompt style message") +color.Warn.Prompt("prompt style message") +``` + +Run demo: `go run ./_examples/theme_prompt.go` + +![theme-prompt](_examples/images/theme-prompt.jpg) + +### 强调提示风格 + +```go +color.Info.Block("prompt style message") +color.Warn.Block("prompt style message") +``` + +Run demo: `go run ./_examples/theme_block.go` + +![theme-block](_examples/images/theme-block.jpg) + +### 使用颜色标签 + +> **支持** 在windows `cmd.exe` `PowerShell` 使用 + +使用内置的颜色标签,可以非常方便简单的构建自己需要的任何格式 + +```go +// 使用内置的 color tag +color.Print("hello, welcome") +color.Println("hello") +color.Println("hello") +color.Println("hello") + +// 自定义颜色属性 +color.Print("hello, welcome\n") +``` + + - 使用 `color.Tag` + +给后面输出的文本信息加上给定的颜色风格标签 + +```go +// set a style tag +color.Tag("info").Print("info style text") +color.Tag("info").Printf("%s style text", "info") +color.Tag("info").Println("info style text") +``` + +> 运行 demo: `go run ./_examples/colortag.go` + +![color-tags](_examples/images/color-tags.jpg) + +## 256色使用 + +> 256色彩在 `v1.2.4` 后支持Windows CMD,PowerShell 环境 + +### 使用前景或后景色 + + - `color.C256(val uint8, isBg ...bool) Color256` + +```go +c := color.C256(132) // fg color +c.Println("message") +c.Printf("format %s", "message") + +c := color.C256(132, true) // bg color +c.Println("message") +c.Printf("format %s", "message") +``` + +### 使用风格 + +> 可同时设置前景和背景色 + + - `color.S256(fgAndBg ...uint8) *Style256` + +```go +s := color.S256(32, 203) +s.Println("message") +s.Printf("format %s", "message") +``` + +> 运行 demo: `go run ./_examples/color256.go` + +![color-tags](_examples/images/256-color.jpg) + +## RGB色彩使用 + +> RGB色彩在 `v1.2.4` 后支持Windows CMD,PowerShell 环境 + +代码示例: + +```go +color.RGB(30, 144, 255).Println("message. use RGB number") + +color.HEX("#1976D2").Println("blue-darken") +color.HEX("#D50000", true).Println("red-accent. use HEX style") + +color.RGBStyleFromString("213,0,0").Println("red-accent. use RGB number") +color.HEXStyle("eee", "D50000").Println("deep-purple color") +``` + +### 使用前景或后景色 + + - `color.RGB(r, g, b uint8, isBg ...bool) RGBColor` + +```go +c := color.RGB(30,144,255) // fg color +c.Println("message") +c.Printf("format %s", "message") + +c := color.RGB(30,144,255, true) // bg color +c.Println("message") +c.Printf("format %s", "message") +``` + + - `color.HEX(hex string, isBg ...bool) RGBColor` 从16进制颜色创建 + +```go +c := HEX("ccc") // 也可以写为: "cccccc" "#cccccc" +c.Println("message") +c.Printf("format %s", "message") + +c = HEX("aabbcc", true) // as bg color +c.Println("message") +c.Printf("format %s", "message") +``` + +### 使用风格 + +> 可同时设置前景和背景色 + + - `color.NewRGBStyle(fg RGBColor, bg ...RGBColor) *RGBStyle` + +```go +s := NewRGBStyle(RGB(20, 144, 234), RGB(234, 78, 23)) +s.Println("message") +s.Printf("format %s", "message") +``` + + - `color.HEXStyle(fg string, bg ...string) *RGBStyle` 从16进制颜色创建 + +```go +s := HEXStyle("11aa23", "eee") +s.Println("message") +s.Printf("format %s", "message") +``` + +## Gookit 工具包 + + - [gookit/ini](https://github.com/gookit/ini) INI配置读取管理,支持多文件加载,数据覆盖合并, 解析ENV变量, 解析变量引用 + - [gookit/rux](https://github.com/gookit/rux) Simple and fast request router for golang HTTP + - [gookit/gcli](https://github.com/gookit/gcli) Go的命令行应用,工具库,运行CLI命令,支持命令行色彩,用户交互,进度显示,数据格式化显示 + - [gookit/event](https://github.com/gookit/event) Go实现的轻量级的事件管理、调度程序库, 支持设置监听器的优先级, 支持对一组事件进行监听 + - [gookit/cache](https://github.com/gookit/cache) 通用的缓存使用包装库,通过包装各种常用的驱动,来提供统一的使用API + - [gookit/config](https://github.com/gookit/config) Go应用配置管理,支持多种格式(JSON, YAML, TOML, INI, HCL, ENV, Flags),多文件加载,远程文件加载,数据合并 + - [gookit/color](https://github.com/gookit/color) CLI 控制台颜色渲染工具库, 拥有简洁的使用API,支持16色,256色,RGB色彩渲染输出 + - [gookit/filter](https://github.com/gookit/filter) 提供对Golang数据的过滤,净化,转换 + - [gookit/validate](https://github.com/gookit/validate) Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器 + - [gookit/goutil](https://github.com/gookit/goutil) Go 的一些工具函数,格式化,特殊处理,常用信息获取等 + - 更多请查看 https://github.com/gookit + +## 参考项目 + + - `issue9/term` https://github.com/issue9/term + - `beego/bee` https://github.com/beego/bee + - `inhere/console` https://github/inhere/php-console + - [ANSI转义序列](https://zh.wikipedia.org/wiki/ANSI转义序列) + - [Standard ANSI color map](https://conemu.github.io/en/AnsiEscapeCodes.html#Standard_ANSI_color_map) + +## License + +MIT diff --git a/vendor/github.com/gookit/color/README_cn.md b/vendor/github.com/gookit/color/README_cn.md deleted file mode 100644 index b8159b3472d..00000000000 --- a/vendor/github.com/gookit/color/README_cn.md +++ /dev/null @@ -1,312 +0,0 @@ -# CLI Color - -[![GoDoc](https://godoc.org/github.com/gookit/color?status.svg)](https://godoc.org/github.com/gookit/color) -[![Build Status](https://travis-ci.org/gookit/color.svg?branch=master)](https://travis-ci.org/gookit/color) -[![Coverage Status](https://coveralls.io/repos/github/gookit/color/badge.svg?branch=master)](https://coveralls.io/github/gookit/color?branch=master) -[![Go Report Card](https://goreportcard.com/badge/github.com/gookit/color)](https://goreportcard.com/report/github.com/gookit/color) - -Golang下的命令行色彩使用库, 拥有丰富的色彩渲染输出,通用的API方法,兼容Windows系统 - -> **[EN README](README.md)** - -基本颜色预览: - -![basic-color](_examples/images/basic-color.png) - -## 功能特色 - -- 使用简单方便,无其他依赖 -- 支持丰富的颜色输出, 16色(4bit),256色(8bit),RGB色彩(24bit) - - 16色(4bit)是最常用和支持最广的,支持Windows `cmd.exe` - - 另外两种支持 `linux` `mac` 和 Windows下的 `ConEmu` `git-bash` `mintty` 等部分终端 -- 通用的API方法:`Print` `Printf` `Println` `Sprint` `Sprintf` -- 同时支持html标签式的颜色渲染. eg: `message` -- 基础色彩: `Bold` `Black` `White` `Gray` `Red` `Green` `Yellow` `Blue` `Magenta` `Cyan` -- 扩展风格: `Info` `Note` `Light` `Error` `Danger` `Notice` `Success` `Comment` `Primary` `Warning` `Question` `Secondary` -- 兼容Windows系统环境 - -## GoDoc - -- [godoc for gopkg](https://godoc.org/gopkg.in/gookit/color.v1) -- [godoc for github](https://godoc.org/github.com/gookit/color) - -## 快速开始 - -如下,引入当前包就可以快速的使用 - -```bash -import "gopkg.in/gookit/color.v1" // 推荐 -// or -import "github.com/gookit/color" -``` - -### 如何使用 - -```go -package main - -import ( - "fmt" - "github.com/gookit/color" -) - -func main() { - // simple usage - color.Cyan.Printf("Simple to use %s\n", "color") - - // use like func - red := color.FgRed.Render - green := color.FgGreen.Render - fmt.Printf("%s line %s library\n", red("Command"), green("color")) - - // 自定义颜色 - color.New(color.FgWhite, color.BgBlack).Println("custom color style") - - // 也可以: - color.Style{color.FgCyan, color.OpBold}.Println("custom color style") - - // internal style: - color.Info.Println("message") - color.Warn.Println("message") - color.Error.Println("message") - - // 使用颜色标签 - color.Print("hello, welcome\n") - - // apply a style tag - color.Tag("info").Println("info style text") - - // prompt message - color.Info.Prompt("prompt style message") - color.Warn.Prompt("prompt style message") - - // tips message - color.Info.Tips("tips style message") - color.Warn.Tips("tips style message") -} -``` - -> 运行 demo: `go run ./_examples/app.go` - -![colored-out](_examples/images/color-demo.jpg) - -## 构建风格 - -```go -// 仅设置前景色 -color.FgCyan.Printf("Simple to use %s\n", "color") -// 仅设置背景色 -color.BgRed.Printf("Simple to use %s\n", "color") - -// 完全自定义 前景色 背景色 选项 -style := color.New(color.FgWhite, color.BgBlack, color.OpBold) -style.Println("custom color style") - -// 也可以: -color.Style{color.FgCyan, color.OpBold}.Println("custom color style") -``` - -```go -// 设置console颜色 -color.Set(color.FgCyan) - -// 输出信息 -fmt.Print("message") - -// 重置console颜色 -color.Reset() -``` - -## 使用内置风格 - -### 基础颜色方法 - -> 支持在windows `cmd.exe` 使用 - -- `color.Bold` -- `color.Black` -- `color.White` -- `color.Gray` -- `color.Red` -- `color.Green` -- `color.Yellow` -- `color.Blue` -- `color.Magenta` -- `color.Cyan` - -```go -color.Bold.Println("bold message") -color.Yellow.Println("yellow message") -``` - -> 运行 demo: `go run ./_examples/basiccolor.go` - -![basic-color](_examples/images/basic-color.png) - -### 扩展风格方法 - -> 支持在windows `cmd.exe` 使用 - -- `color.Info` -- `color.Note` -- `color.Light` -- `color.Error` -- `color.Danger` -- `color.Notice` -- `color.Success` -- `color.Comment` -- `color.Primary` -- `color.Warning` -- `color.Question` -- `color.Secondary` - -```go -color.Info.Println("Info message") -color.Success.Println("Success message") -``` - -> 运行 demo: `go run ./_examples/theme_style.go` - -![theme-style](_examples/images/theme-style.jpg) - -### 使用颜色标签 - -> **不** 支持在windows `cmd.exe` 使用,但不影响使用,会自动去除颜色标签 - -使用内置的颜色标签,可以非常方便简单的构建自己需要的任何格式 - -```go -// 使用内置的 color tag -color.Print("hello, welcome") -color.Println("hello") -color.Println("hello") -color.Println("hello") - -// 自定义颜色属性 -color.Print("hello, welcome\n") -``` - -- 使用 `color.Tag` - -给后面输出的文本信息加上给定的颜色风格标签 - -```go -// set a style tag -color.Tag("info").Print("info style text") -color.Tag("info").Printf("%s style text", "info") -color.Tag("info").Println("info style text") -``` - -> 运行 demo: `go run ./_examples/colortag.go` - -![color-tags](_examples/images/color-tags.jpg) - -## 256色使用 - -### 使用前景或后景色 - -- `color.C256(val uint8, isBg ...bool) Color256` - -```go -c := color.C256(132) // fg color -c.Println("message") -c.Printf("format %s", "message") - -c := color.C256(132, true) // bg color -c.Println("message") -c.Printf("format %s", "message") -``` - -### 使用风格 - -> 可同时设置前景和背景色 - -- `color.S256(fgAndBg ...uint8) *Style256` - -```go -s := color.S256(32, 203) -s.Println("message") -s.Printf("format %s", "message") -``` - -> 运行 demo: `go run ./_examples/color256.go` - -![color-tags](_examples/images/256-color.jpg) - -## RGB色彩使用 - -### 使用前景或后景色 - -- `color.RGB(r, g, b uint8, isBg ...bool) RGBColor` - -```go -c := color.RGB(30,144,255) // fg color -c.Println("message") -c.Printf("format %s", "message") - -c := color.RGB(30,144,255, true) // bg color -c.Println("message") -c.Printf("format %s", "message") -``` - -- `color.HEX(hex string, isBg ...bool) RGBColor` 从16进制颜色创建 - -```go -c := HEX("ccc") // 也可以写为: "cccccc" "#cccccc" -c.Println("message") -c.Printf("format %s", "message") - -c = HEX("aabbcc", true) // as bg color -c.Println("message") -c.Printf("format %s", "message") -``` - -### 使用风格 - -> 可同时设置前景和背景色 - -- `color.NewRGBStyle(fg RGBColor, bg ...RGBColor) *RGBStyle` - -```go -s := NewRGBStyle(RGB(20, 144, 234), RGB(234, 78, 23)) -s.Println("message") -s.Printf("format %s", "message") -``` - -- `color.HEXStyle(fg string, bg ...string) *RGBStyle` 从16进制颜色创建 - -```go -s := HEXStyle("11aa23", "eee") -s.Println("message") -s.Printf("format %s", "message") -``` - -## CLI 应用包 - -**[gookit/gcli](https://github.com/gookit/gcli)** 快速的构建CLI命令应用 - -## Gookit 工具包 - -- [gookit/ini](https://github.com/gookit/ini) INI配置读取管理,支持多文件加载,数据覆盖合并, 解析ENV变量, 解析变量引用 -- [gookit/rux](https://github.com/gookit/rux) Simple and fast request router for golang HTTP -- [gookit/gcli](https://github.com/gookit/gcli) Go的命令行应用,工具库,运行CLI命令,支持命令行色彩,用户交互,进度显示,数据格式化显示 -- [gookit/event](https://github.com/gookit/event) Go实现的轻量级的事件管理、调度程序库, 支持设置监听器的优先级, 支持对一组事件进行监听 -- [gookit/cache](https://github.com/gookit/cache) 通用的缓存使用包装库,通过包装各种常用的驱动,来提供统一的使用API -- [gookit/config](https://github.com/gookit/config) Go应用配置管理,支持多种格式(JSON, YAML, TOML, INI, HCL, ENV, Flags),多文件加载,远程文件加载,数据合并 -- [gookit/color](https://github.com/gookit/color) CLI 控制台颜色渲染工具库, 拥有简洁的使用API,支持16色,256色,RGB色彩渲染输出 -- [gookit/filter](https://github.com/gookit/filter) 提供对Golang数据的过滤,净化,转换 -- [gookit/validate](https://github.com/gookit/validate) Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器 -- [gookit/goutil](https://github.com/gookit/goutil) Go 的一些工具函数,格式化,特殊处理,常用信息获取等 -- 更多请查看 https://github.com/gookit - -## 参考项目 - -- `issue9/term` https://github.com/issue9/term -- `beego/bee` https://github.com/beego/bee -- `inhere/console` https://github/inhere/php-console -- [ANSI转义序列](https://zh.wikipedia.org/wiki/ANSI转义序列) -- [Standard ANSI color map](https://conemu.github.io/en/AnsiEscapeCodes.html#Standard_ANSI_color_map) - -## License - -MIT diff --git a/vendor/github.com/gookit/color/color.go b/vendor/github.com/gookit/color/color.go index 192305ffb03..f287a4d854e 100644 --- a/vendor/github.com/gookit/color/color.go +++ b/vendor/github.com/gookit/color/color.go @@ -12,6 +12,8 @@ package color import ( "fmt" + "io" + "os" "regexp" ) @@ -37,10 +39,11 @@ const ResetSet = "\x1b[0m" // CodeExpr regex to clear color codes eg "\033[1;36mText\x1b[0m" const CodeExpr = `\033\[[\d;?]+m` -// Enable switch color display -var Enable = true - var ( + // Enable switch color display + Enable = true + // output the default io.Writer message print + output io.Writer = os.Stdout // mark current env, It's like in `cmd.exe` // if not in windows, is's always is False. isLikeInCmd bool @@ -88,6 +91,24 @@ func Disable() { Enable = false } +// SetOutput set default colored text output +func SetOutput(w io.Writer) { + output = w +} + +// ResetOutput reset output +func ResetOutput() { + output = os.Stdout +} + +// ForceOpenColor force open color render +func ForceOpenColor() bool { + oldVal := isSupportColor + isSupportColor = true + + return oldVal +} + /************************************************************* * render color code *************************************************************/ @@ -96,7 +117,28 @@ func Disable() { // Usage: // msg := RenderCode("3;32;45", "some", "message") func RenderCode(code string, args ...interface{}) string { - message := fmt.Sprint(args...) + var message string + if ln := len(args); ln == 0 { + return "" + } + + message = fmt.Sprint(args...) + if len(code) == 0 { + return message + } + + // disabled OR not support color + if !Enable || !isSupportColor { + return ClearCode(message) + } + + return fmt.Sprintf(FullColorTpl, code, message) +} + +// RenderWithSpaces Render code with spaces. +// If the number of args is > 1, a space will be added between the args +func RenderWithSpaces(code string, args ...interface{}) string { + message := formatArgsForPrintln(args) if len(code) == 0 { return message } @@ -113,7 +155,6 @@ func RenderCode(code string, args ...interface{}) string { // Usage: // msg := RenderString("3;32;45", "a message") func RenderString(code string, str string) string { - // some check if len(code) == 0 || str == "" { return str } @@ -179,17 +220,17 @@ func (p *Printer) Sprintf(format string, a ...interface{}) string { // Print rendering colored messages func (p *Printer) Print(a ...interface{}) { - fmt.Print(RenderCode(p.String(), a...)) + doPrintV2(p.String(), fmt.Sprint(a...)) } // Printf format and rendering colored messages func (p *Printer) Printf(format string, a ...interface{}) { - fmt.Print(RenderString(p.String(), fmt.Sprintf(format, a...))) + doPrintV2(p.String(), fmt.Sprintf(format, a...)) } // Println rendering colored messages with newline func (p *Printer) Println(a ...interface{}) { - fmt.Println(RenderCode(p.String(), a...)) + doPrintlnV2(p.ColorCode, a) } // IsEmpty color code diff --git a/vendor/github.com/gookit/color/color_16.go b/vendor/github.com/gookit/color/color_16.go index 0c621a67481..6a54ee18c9e 100644 --- a/vendor/github.com/gookit/color/color_16.go +++ b/vendor/github.com/gookit/color/color_16.go @@ -20,8 +20,8 @@ const ( FgGreen FgYellow FgBlue - FgMagenta // 品红 - FgCyan // 青色 + FgMagenta // 品红 + FgCyan // 青色 FgWhite // FgDefault revert default FG FgDefault Color = 39 @@ -46,7 +46,7 @@ const ( BgBlack Color = iota + 40 BgRed BgGreen - BgYellow // BgBrown like yellow + BgYellow // BgBrown like yellow BgBlue BgMagenta BgCyan @@ -94,10 +94,14 @@ const ( White = FgWhite Yellow = FgYellow Magenta = FgMagenta + // special + Bold = OpBold Normal = FgDefault + // extra light + LightRed = FgLightRed LightCyan = FgLightCyan LightBlue = FgLightBlue @@ -124,6 +128,15 @@ func (c Color) Render(a ...interface{}) string { return RenderCode(c.String(), a...) } +// Renderln messages by color setting. +// like Println, will add spaces for each argument +// Usage: +// green := color.FgGreen.Renderln +// fmt.Println(green("message")) +func (c Color) Renderln(a ...interface{}) string { + return RenderWithSpaces(c.String(), a...) +} + // Sprint render messages by color setting. is alias of the Render() func (c Color) Sprint(a ...interface{}) string { return RenderCode(c.String(), a...) @@ -144,24 +157,19 @@ func (c Color) Sprintf(format string, args ...interface{}) string { // green := color.FgGreen.Print // green("message") func (c Color) Print(args ...interface{}) { - message := fmt.Sprint(args...) - if isLikeInCmd { - winPrint(message, c) - } else { - fmt.Print(RenderString(c.String(), message)) - } + doPrint(c.Code(), []Color{c}, fmt.Sprint(args...)) } // Printf format and print messages. // Usage: // color.Cyan.Printf("string %s", "arg0") func (c Color) Printf(format string, a ...interface{}) { - msg := fmt.Sprintf(format, a...) - if isLikeInCmd { - winPrint(msg, c) - } else { - fmt.Print(RenderString(c.String(), msg)) - } + doPrint(c.Code(), []Color{c}, fmt.Sprintf(format, a...)) +} + +// Println messages with new line +func (c Color) Println(a ...interface{}) { + doPrintln(c.String(), []Color{c}, a) } // Light current color. eg: 36(FgCyan) -> 96(FgLightCyan). @@ -192,7 +200,12 @@ func (c Color) Darken() Color { return c } -// String to code string. eg "35" +// Code convert to code string. eg "35" +func (c Color) Code() string { + return fmt.Sprintf("%d", c) +} + +// String convert to code string. eg "35" func (c Color) String() string { return fmt.Sprintf("%d", c) } @@ -285,12 +298,3 @@ func colors2code(colors ...Color) string { return strings.Join(codes, ";") } - -// Println messages with new line -func (c Color) Println(a ...interface{}) { - if isLikeInCmd { - winPrintln(fmt.Sprint(a...), c) - } else { - fmt.Println(RenderCode(c.String(), a...)) - } -} diff --git a/vendor/github.com/gookit/color/color_256.go b/vendor/github.com/gookit/color/color_256.go index 720cce57d1e..f0ca2097eb8 100644 --- a/vendor/github.com/gookit/color/color_256.go +++ b/vendor/github.com/gookit/color/color_256.go @@ -41,12 +41,15 @@ const ( // // 颜色值使用10进制和16进制都可 0x98 = 152 // -// 颜色有两位uint8组成, +// 颜色有两位uint8组成: // 0: color value // 1: color type, Fg=0 Bg=1 // >1: unset value +// example: // fg color: [152, 0] // bg color: [152, 1] +// +// NOTICE: now support 256 color on windows CMD, PowerShell type Color256 [2]uint8 // Bit8 create a color256 @@ -68,17 +71,17 @@ func C256(val uint8, isBg ...bool) Color256 { // Print print message func (c Color256) Print(a ...interface{}) { - fmt.Print(RenderCode(c.String(), a...)) + doPrintV2(c.String(), fmt.Sprint(a...)) } // Printf format and print message func (c Color256) Printf(format string, a ...interface{}) { - fmt.Print(RenderString(c.String(), fmt.Sprintf(format, a...))) + doPrintV2(c.String(), fmt.Sprintf(format, a...)) } // Println print message with newline func (c Color256) Println(a ...interface{}) { - fmt.Println(RenderCode(c.String(), a...)) + doPrintlnV2(c.String(), a) } // Sprint returns rendered message @@ -172,27 +175,32 @@ func (s *Style256) SetFg(fgVal uint8) *Style256 { // Print print message func (s *Style256) Print(a ...interface{}) { - fmt.Print(RenderCode(s.String(), a...)) + doPrintV2(s.String(), fmt.Sprint(a...)) } // Printf format and print message func (s *Style256) Printf(format string, a ...interface{}) { - fmt.Print(RenderString(s.String(), fmt.Sprintf(format, a...))) + doPrintV2(s.String(), fmt.Sprintf(format, a...)) } // Println print message with newline func (s *Style256) Println(a ...interface{}) { - fmt.Println(RenderCode(s.String(), a...)) + doPrintlnV2(s.String(), a) } // Sprint returns rendered message func (s *Style256) Sprint(a ...interface{}) string { - return RenderCode(s.String(), a...) + return RenderCode(s.Code(), a...) } // Sprintf returns format and rendered message func (s *Style256) Sprintf(format string, a ...interface{}) string { - return RenderString(s.String(), fmt.Sprintf(format, a...)) + return RenderString(s.Code(), fmt.Sprintf(format, a...)) +} + +// Code convert to color code string +func (s *Style256) Code() string { + return s.String() } // String convert to color code string diff --git a/vendor/github.com/gookit/color/color_nonwin.go b/vendor/github.com/gookit/color/color_nonwin.go new file mode 100644 index 00000000000..c254393341a --- /dev/null +++ b/vendor/github.com/gookit/color/color_nonwin.go @@ -0,0 +1,23 @@ +// +build !windows + +// The method in the file has no effect +// Only for compatibility with non-Windows systems + +package color + +func winSet(_ ...Color) (n int, err error) { + return +} + +func winReset() (n int, err error) { + return +} + +func winPrint(_ string, _ ...Color) {} +func winPrintln(_ string, _ ...Color) {} +func renderColorCodeOnCmd(_ func()) {} + +// IsTerminal check currently is terminal +func IsTerminal(_ int) bool { + return true +} diff --git a/vendor/github.com/gookit/color/color_not_win.go b/vendor/github.com/gookit/color/color_not_win.go deleted file mode 100644 index 7a34fd9885d..00000000000 --- a/vendor/github.com/gookit/color/color_not_win.go +++ /dev/null @@ -1,17 +0,0 @@ -// The method in the file has no effect -// Only for compatibility with non-Windows systems - -// +build !windows - -package color - -func winSet(_ ...Color) (n int, err error) { - return -} - -func winReset() (n int, err error) { - return -} - -func winPrint(_ string, _ ...Color) {} -func winPrintln(_ string, _ ...Color) {} diff --git a/vendor/github.com/gookit/color/color_rgb.go b/vendor/github.com/gookit/color/color_rgb.go index 3773821ffe7..3246b63a16a 100644 --- a/vendor/github.com/gookit/color/color_rgb.go +++ b/vendor/github.com/gookit/color/color_rgb.go @@ -47,6 +47,8 @@ const ( // // 3th: Fg=0, Bg=1, >1: unset value // RGBColor{30,144,255, 0} // RGBColor{30,144,255, 1} +// +// NOTICE: now support RGB color on windows CMD, PowerShell type RGBColor [4]uint8 // create a empty RGBColor @@ -107,17 +109,17 @@ func RGBFromString(rgb string, isBg ...bool) RGBColor { // Print print message func (c RGBColor) Print(a ...interface{}) { - fmt.Print(RenderCode(c.String(), a...)) + doPrintV2(c.String(), fmt.Sprint(a...)) } // Printf format and print message func (c RGBColor) Printf(format string, a ...interface{}) { - fmt.Print(RenderString(c.String(), fmt.Sprintf(format, a...))) + doPrintV2(c.String(), fmt.Sprintf(format, a...)) } // Println print message with newline func (c RGBColor) Println(a ...interface{}) { - fmt.Println(RenderCode(c.String(), a...)) + doPrintlnV2(c.String(), a) } // Sprint returns rendered message @@ -127,7 +129,7 @@ func (c RGBColor) Sprint(a ...interface{}) string { // Sprintf returns format and rendered message func (c RGBColor) Sprintf(format string, a ...interface{}) string { - return RenderString(c.String(), fmt.Sprintf(format, a...)) + return RenderString(c.Code(), fmt.Sprintf(format, a...)) } // Values to RGB values @@ -135,6 +137,11 @@ func (c RGBColor) Values() []int { return []int{int(c[0]), int(c[1]), int(c[2])} } +// Code to color code string +func (c RGBColor) Code() string { + return c.String() +} + // String to color code string func (c RGBColor) String() string { if c[3] == AsFg { // 0 is Fg @@ -234,7 +241,11 @@ func HEXStyle(fg string, bg ...string) *RGBStyle { s.SetBg(HEX(bg[0])) } - return s.SetFg(HEX(fg)) + if len(fg) > 0 { + s.SetFg(HEX(fg)) + } + + return s } // RGBStyleFromString create a RGBStyle from color value string. @@ -271,17 +282,17 @@ func (s *RGBStyle) SetBg(bg RGBColor) *RGBStyle { // Print print message func (s *RGBStyle) Print(a ...interface{}) { - fmt.Print(RenderCode(s.String(), a...)) + doPrintV2(s.String(), fmt.Sprint(a...)) } // Printf format and print message func (s *RGBStyle) Printf(format string, a ...interface{}) { - fmt.Print(RenderString(s.String(), fmt.Sprintf(format, a...))) + doPrintV2(s.String(), fmt.Sprintf(format, a...)) } // Println print message with newline func (s *RGBStyle) Println(a ...interface{}) { - fmt.Println(RenderCode(s.String(), a...)) + doPrintlnV2(s.String(), a) } // Sprint returns rendered message @@ -291,7 +302,12 @@ func (s *RGBStyle) Sprint(a ...interface{}) string { // Sprintf returns format and rendered message func (s *RGBStyle) Sprintf(format string, a ...interface{}) string { - return RenderString(s.String(), fmt.Sprintf(format, a...)) + return RenderString(s.Code(), fmt.Sprintf(format, a...)) +} + +// Code convert to color code string +func (s *RGBStyle) Code() string { + return s.String() } // String convert to color code string diff --git a/vendor/github.com/gookit/color/color_windows.go b/vendor/github.com/gookit/color/color_windows.go index 3d652f1d4a1..eea94301d90 100644 --- a/vendor/github.com/gookit/color/color_windows.go +++ b/vendor/github.com/gookit/color/color_windows.go @@ -80,15 +80,15 @@ const ( // color on windows var winColorsMap map[Color]uint16 +// related docs +// https://docs.microsoft.com/zh-cn/windows/console/console-virtual-terminal-sequences +// https://docs.microsoft.com/zh-cn/windows/console/console-virtual-terminal-sequences#samples var ( - // for cmd.exe - // echo %ESC%[1;33;40m Yellow on black %ESC%[0m - escChar = "" // isMSys bool kernel32 *syscall.LazyDLL procGetConsoleMode *syscall.LazyProc - // procSetConsoleMode *syscall.LazyProc + procSetConsoleMode *syscall.LazyProc procSetTextAttribute *syscall.LazyProc procGetConsoleScreenBufferInfo *syscall.LazyProc @@ -104,16 +104,17 @@ func init() { return } - // init some info + // init simple color code info isLikeInCmd = true initWinColorsMap() + // load related windows dll // isMSys = utils.IsMSys() kernel32 = syscall.NewLazyDLL("kernel32.dll") // https://docs.microsoft.com/en-us/windows/console/setconsolemode procGetConsoleMode = kernel32.NewProc("GetConsoleMode") - // procSetConsoleMode = kernel32.NewProc("SetConsoleMode") + procSetConsoleMode = kernel32.NewProc("SetConsoleMode") procSetTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") // https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo @@ -123,6 +124,73 @@ func init() { // err := getConsoleScreenBufferInfo(uintptr(syscall.Stdout), &defScreenInfo) } +/************************************************************* + * render full color code on windows(8,16,24bit color) + *************************************************************/ + +// docs https://docs.microsoft.com/zh-cn/windows/console/getconsolemode#parameters +const ( + // equals to docs page's ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004 + EnableVirtualTerminalProcessingMode uint32 = 0x4 +) + +// EnableVirtualTerminalProcessing Enable virtual terminal processing +// +// ref from github.com/konsorten/go-windows-terminal-sequences +// doc https://docs.microsoft.com/zh-cn/windows/console/console-virtual-terminal-sequences#samples +// +// Usage: +// err := EnableVirtualTerminalProcessing(syscall.Stdout, true) +// // support print color text +// err = EnableVirtualTerminalProcessing(syscall.Stdout, false) +func EnableVirtualTerminalProcessing(stream syscall.Handle, enable bool) error { + var mode uint32 + // Check if it is currently in the terminal + err := syscall.GetConsoleMode(syscall.Stdout, &mode) + if err != nil { + return err + } + + if enable { + mode |= EnableVirtualTerminalProcessingMode + } else { + mode &^= EnableVirtualTerminalProcessingMode + } + + ret, _, err := procSetConsoleMode.Call(uintptr(unsafe.Pointer(stream)), uintptr(mode)) + if ret == 0 { + return err + } + + return nil +} + +// renderColorCodeOnCmd enable cmd color render. +func renderColorCodeOnCmd(fn func()) { + err := EnableVirtualTerminalProcessing(syscall.Stdout, true) + // if is not in terminal, will clear color tag. + if err != nil { + // panic(err) + fn() + return + } + + // force open color render + old := ForceOpenColor() + fn() + // revert color setting + isSupportColor = old + + err = EnableVirtualTerminalProcessing(syscall.Stdout, false) + if err != nil { + panic(err) + } +} + +/************************************************************* + * render simple color code on windows + *************************************************************/ + // initWinColorsMap init colors to win-colors mapping func initWinColorsMap() { // init map @@ -185,12 +253,12 @@ func initWinColorsMap() { // winPrint func winPrint(str string, colors ...Color) { - _, _ = winInternalPrint(str, convertColorsToWinAttr(colors), false) + _, _ = winInternalPrint(str, colorsToWinAttr(colors), false) } // winPrintln func winPrintln(str string, colors ...Color) { - _, _ = winInternalPrint(str, convertColorsToWinAttr(colors), true) + _, _ = winInternalPrint(str, colorsToWinAttr(colors), true) } // winInternalPrint @@ -198,19 +266,17 @@ func winPrintln(str string, colors ...Color) { func winInternalPrint(str string, attribute uint16, newline bool) (int, error) { if !Enable { // not enable if newline { - return fmt.Println(str) + return fmt.Fprintln(output, str) } - - return fmt.Print(str) + return fmt.Fprint(output, str) } // fmt.Print("attribute val: ", attribute, "\n") _, _ = setConsoleTextAttr(uintptr(syscall.Stdout), attribute) - if newline { - fmt.Println(str) + _, _ = fmt.Fprintln(output, str) } else { - fmt.Print(str) + _, _ = fmt.Fprint(output, str) } // handle, _, _ = procSetTextAttribute.Call(uintptr(syscall.Stdout), winDefSetting) @@ -220,19 +286,14 @@ func winInternalPrint(str string, attribute uint16, newline bool) (int, error) { return winReset() } -// func winRender(str string, colors ...Color) string { -// setConsoleTextAttr(uintptr(syscall.Stdout), convertColorsToWinAttr(colors)) -// -// return str -// } - // winSet set console color attributes func winSet(colors ...Color) (int, error) { - if !Enable { // not enable + // not enable + if !Enable { return 0, nil } - return setConsoleTextAttr(uintptr(syscall.Stdout), convertColorsToWinAttr(colors)) + return setConsoleTextAttr(uintptr(syscall.Stdout), colorsToWinAttr(colors)) } // winReset reset color settings to default @@ -245,8 +306,8 @@ func winReset() (int, error) { return setConsoleTextAttr(uintptr(syscall.Stdout), winDefSetting) } -// convertColorsToWinAttr convert generic colors to win-colors attribute -func convertColorsToWinAttr(colors []Color) uint16 { +// colorsToWinAttr convert generic colors to win-colors attribute +func colorsToWinAttr(colors []Color) uint16 { var setting uint16 for _, c := range colors { // check exists @@ -299,10 +360,14 @@ func IsTerminal(fd int) bool { return r != 0 && e == 0 } +/************************************************************* + * some extra utils for windows + *************************************************************/ + // from package: golang.org/x/sys/windows type ( short int16 - word uint16 + word uint16 // coord cursor position coordinates coord struct { diff --git a/vendor/github.com/gookit/color/go.mod b/vendor/github.com/gookit/color/go.mod index f81dabde958..fd738c79921 100644 --- a/vendor/github.com/gookit/color/go.mod +++ b/vendor/github.com/gookit/color/go.mod @@ -1,5 +1,5 @@ module github.com/gookit/color -go 1.12 +go 1.11 require github.com/stretchr/testify v1.3.0 diff --git a/vendor/github.com/gookit/color/style.go b/vendor/github.com/gookit/color/style.go index 0d194d66514..412efb3b5b2 100644 --- a/vendor/github.com/gookit/color/style.go +++ b/vendor/github.com/gookit/color/style.go @@ -9,15 +9,20 @@ import ( * 16 color Style *************************************************************/ -// Style a 16 color style -// can add: fg color, bg color, color options +// Style a 16 color style. can add: fg color, bg color, color options +// // Example: -// color.Style(color.FgGreen).Print("message") +// color.Style{color.FgGreen}.Print("message") type Style []Color // New create a custom style +// +// Usage: +// color.New(color.FgGreen).Print("message") +// equals to: +// color.Style{color.FgGreen}.Print("message") func New(colors ...Color) Style { - return Style(colors) + return colors } // Save to styles map @@ -33,42 +38,43 @@ func (s Style) Render(a ...interface{}) string { return RenderCode(s.String(), a...) } +// Renderln render text line. +// like Println, will add spaces for each argument +// Usage: +// color.New(color.FgGreen).Renderln("text", "more") +// color.New(color.FgGreen, color.BgBlack, color.OpBold).Render("text", "more") +func (s Style) Renderln(a ...interface{}) string { + return RenderWithSpaces(s.String(), a...) +} + // Sprint is alias of the 'Render' func (s Style) Sprint(a ...interface{}) string { return RenderCode(s.String(), a...) } -// Sprintf is alias of the 'Render' +// Sprintf format and render message. func (s Style) Sprintf(format string, a ...interface{}) string { return RenderString(s.String(), fmt.Sprintf(format, a...)) } // Print render and Print text func (s Style) Print(a ...interface{}) { - if isLikeInCmd { - winPrint(fmt.Sprint(a...), s...) - } else { - fmt.Print(RenderCode(s.String(), a...)) - } + doPrint(s.String(), s, fmt.Sprint(a...)) } // Printf render and print text func (s Style) Printf(format string, a ...interface{}) { - message := fmt.Sprintf(format, a...) - if isLikeInCmd { - winPrint(message, s...) - } else { - fmt.Print(RenderString(s.String(), message)) - } + doPrint(s.Code(), s, fmt.Sprintf(format, a...)) } // Println render and print text line func (s Style) Println(a ...interface{}) { - if isLikeInCmd { - winPrintln(fmt.Sprint(a...), s...) - } else { - fmt.Println(RenderCode(s.String(), a...)) - } + doPrintln(s.String(), s, a) +} + +// Code convert to code string. returns like "32;45;3" +func (s Style) Code() string { + return s.String() } // String convert to code string. returns like "32;45;3" @@ -105,19 +111,20 @@ func (t *Theme) Save() { // Tips use name as title, only apply style for name func (t *Theme) Tips(format string, a ...interface{}) { - t.Print(strings.ToUpper(t.Name) + ": ") // only apply style for name + // only apply style for name + t.Print(strings.ToUpper(t.Name) + ": ") Printf(format+"\n", a...) } // Prompt use name as title, and apply style for message func (t *Theme) Prompt(format string, a ...interface{}) { - title := strings.ToUpper(t.Name) + ": " + title := strings.ToUpper(t.Name) + ":" t.Println(title, fmt.Sprintf(format, a...)) } // Block like Prompt, but will wrap a empty line func (t *Theme) Block(format string, a ...interface{}) { - title := strings.ToUpper(t.Name) + ":\n " + title := strings.ToUpper(t.Name) + ":\n" t.Println(title, fmt.Sprintf(format, a...)) } @@ -145,6 +152,8 @@ var ( Error = &Theme{"error", Style{FgLightWhite, BgRed}} // Danger color style Danger = &Theme{"danger", Style{OpBold, FgRed}} + // Debug color style + Debug = &Theme{"debug", Style{OpReset, FgCyan}} // Notice color style Notice = &Theme{"notice", Style{OpBold, FgCyan}} // Comment color style @@ -168,6 +177,7 @@ var Themes = map[string]*Theme{ "light": Light, "error": Error, + "debug": Debug, "danger": Danger, "notice": Notice, "success": Success, diff --git a/vendor/github.com/gookit/color/tag.go b/vendor/github.com/gookit/color/tag.go index 7c503e64c53..50daa40425a 100644 --- a/vendor/github.com/gookit/color/tag.go +++ b/vendor/github.com/gookit/color/tag.go @@ -3,24 +3,25 @@ package color import ( "fmt" "io" + "log" "regexp" "strings" ) // output colored text like use html tag. (not support windows cmd) const ( - // Regex to match color tags - // golang 不支持反向引用. 即不支持使用 \1 引用第一个匹配 ([a-z=;]+) + // MatchExpr regex to match color tags + // Notice: golang 不支持反向引用. 即不支持使用 \1 引用第一个匹配 ([a-z=;]+) // MatchExpr = `<([a-z=;]+)>(.*?)<\/\1>` // 所以调整一下 统一使用 `` 来结束标签,例如 "some text" // 支持自定义颜色属性的tag "content" // (?s:...) s - 让 "." 匹配换行 MatchExpr = `<([a-zA-Z_=,;]+)>(?s:(.*?))<\/>` - // Regex to match color attributes + // AttrExpr regex to match color attributes AttrExpr = `(fg|bg|op)[\s]*=[\s]*([a-zA-Z,]+);?` - // Regex used for removing color tags + // StripExpr regex used for removing color tags // StripExpr = `<[\/]?[a-zA-Z=;]+>` // 随着上面的做一些调整 StripExpr = `<[\/]?[a-zA-Z_=,;]*>` @@ -111,42 +112,84 @@ var colorTags = map[string]string{ * print methods(will auto parse color tags) *************************************************************/ -// Print messages +// Print render color tag and print messages func Print(a ...interface{}) { - fmt.Print(Render(a...)) + Fprint(output, a...) } // Printf format and print messages func Printf(format string, a ...interface{}) { - fmt.Print(ReplaceTag(fmt.Sprintf(format, a...))) + Fprintf(output, format, a...) } // Println messages with new line func Println(a ...interface{}) { - fmt.Println(Render(a...)) + Fprintln(output, a...) } // Fprint print rendered messages to writer +// Notice: will ignore print error func Fprint(w io.Writer, a ...interface{}) { - fmt.Fprint(w, Render(a...)) + if isLikeInCmd { + renderColorCodeOnCmd(func() { + _, _ = fmt.Fprint(w, Render(a...)) + }) + } else { + _, _ = fmt.Fprint(w, Render(a...)) + } } -// Fprintf print format and rendered messages to writer -func Fprintf(w io.Writer, format string, a ...interface{}) (int, error) { - return fmt.Fprint(w, ReplaceTag(fmt.Sprintf(format, a...))) +// Fprintf print format and rendered messages to writer. +// Notice: will ignore print error +func Fprintf(w io.Writer, format string, a ...interface{}) { + str := fmt.Sprintf(format, a...) + if isLikeInCmd { + renderColorCodeOnCmd(func() { + _, _ = fmt.Fprint(w, ReplaceTag(str)) + }) + } else { + _, _ = fmt.Fprint(w, ReplaceTag(str)) + } } // Fprintln print rendered messages line to writer -func Fprintln(w io.Writer, a ...interface{}) (int, error) { - return fmt.Fprintln(w, Render(a...)) +// Notice: will ignore print error +func Fprintln(w io.Writer, a ...interface{}) { + str := formatArgsForPrintln(a) + if isLikeInCmd { + renderColorCodeOnCmd(func() { + _, _ = fmt.Fprintln(w, ReplaceTag(str)) + }) + } else { + _, _ = fmt.Fprintln(w, ReplaceTag(str)) + } +} + +// Lprint passes colored messages to a log.Logger for printing. +// Notice: should be goroutine safe +func Lprint(l *log.Logger, a ...interface{}) { + if isLikeInCmd { + renderColorCodeOnCmd(func() { + l.Print(Render(a...)) + }) + } else { + l.Print(Render(a...)) + } } -// Render return rendered string +// Render parse color tags, return rendered string. +// Usage: +// text := Render("hello world!") +// fmt.Println(text) func Render(a ...interface{}) string { + if len(a) == 0 { + return "" + } + return ReplaceTag(fmt.Sprint(a...)) } -// Sprint return rendered string +// Sprint parse color tags, return rendered string func Sprint(args ...interface{}) string { return Render(args...) } @@ -191,14 +234,14 @@ func ReplaceTag(str string) string { // custom color in tag: "content" if code := ParseCodeFromAttr(tag); len(code) > 0 { - now := RenderCode(code, content) + now := RenderString(code, content) str = strings.Replace(str, full, now, 1) continue } // use defined tag: "content" if code := GetTagCode(tag); len(code) > 0 { - now := RenderCode(code, content) + now := RenderString(code, content) // old := WrapTag(content, tag) is equals to var 'full' str = strings.Replace(str, full, now, 1) } @@ -313,27 +356,31 @@ func IsDefinedTag(name string) bool { *************************************************************/ // Tag value is a defined style name +// Usage: +// Tag("info").Println("message") type Tag string // Print messages func (tg Tag) Print(a ...interface{}) { name := string(tg) + str := fmt.Sprint(a...) + if stl := GetStyle(name); !stl.IsEmpty() { - stl.Print(a...) - return + stl.Print(str) + } else { + doPrintV2(GetTagCode(name), str) } - - fmt.Print(RenderCode(GetTagCode(name), a...)) } // Printf format and print messages -func (tg Tag) Printf(format string, args ...interface{}) { +func (tg Tag) Printf(format string, a ...interface{}) { name := string(tg) - msg := fmt.Sprintf(format, args...) + str := fmt.Sprintf(format, a...) + if stl := GetStyle(name); !stl.IsEmpty() { - stl.Print(msg) + stl.Print(str) } else { - fmt.Print(RenderString(GetTagCode(name), msg)) + doPrintV2(GetTagCode(name), str) } } @@ -343,7 +390,7 @@ func (tg Tag) Println(a ...interface{}) { if stl := GetStyle(name); !stl.IsEmpty() { stl.Println(a...) } else { - fmt.Println(RenderCode(GetTagCode(name), a...)) + doPrintlnV2(GetTagCode(name), a) } } @@ -359,6 +406,8 @@ func (tg Tag) Sprint(a ...interface{}) string { // Sprintf format and render messages func (tg Tag) Sprintf(format string, a ...interface{}) string { - name := string(tg) - return RenderString(GetTagCode(name), fmt.Sprintf(format, a...)) + tag := string(tg) + str := fmt.Sprintf(format, a...) + + return RenderString(GetTagCode(tag), str) } diff --git a/vendor/github.com/gookit/color/utils.go b/vendor/github.com/gookit/color/utils.go index e2b0f2d662a..1a28bea2e80 100644 --- a/vendor/github.com/gookit/color/utils.go +++ b/vendor/github.com/gookit/color/utils.go @@ -1,11 +1,27 @@ package color import ( + "fmt" "io" "os" "strings" ) +// Support color: +// "TERM=xterm" +// "TERM=xterm-vt220" +// "TERM=xterm-256color" +// "TERM=screen-256color" +// "TERM=tmux-256color" +// "TERM=rxvt-unicode-256color" +// Don't support color: +// "TERM=cygwin" +var specialColorTerms = map[string]bool{ + "screen-256color": true, + "tmux-256color": true, + "rxvt-unicode-256color": true, +} + // IsConsole 判断 w 是否为 stderr、stdout、stdin 三者之一 func IsConsole(out io.Writer) bool { o, ok := out.(*os.File) @@ -33,11 +49,13 @@ func IsMSys() bool { // Not support: // windows cmd.exe, powerShell.exe func IsSupportColor() bool { - // "TERM=xterm" support color - // "TERM=xterm-vt220" support color - // "TERM=xterm-256color" support color - // "TERM=cygwin" don't support color - if strings.Contains(os.Getenv("TERM"), "xterm") { + envTerm := os.Getenv("TERM") + if strings.Contains(envTerm, "xterm") { + return true + } + + // it's special color term + if _, ok := specialColorTerms[envTerm]; ok { return true } @@ -57,14 +75,61 @@ func IsSupportColor() bool { // IsSupport256Color render func IsSupport256Color() bool { // "TERM=xterm-256color" + // "TERM=screen-256color" + // "TERM=tmux-256color" + // "TERM=rxvt-unicode-256color" return strings.Contains(os.Getenv("TERM"), "256color") } +// IsSupportTrueColor render. IsSupportRGBColor +func IsSupportTrueColor() bool { + // "COLORTERM=truecolor" + return strings.Contains(os.Getenv("COLORTERM"), "truecolor") +} + // its Win system. linux windows darwin // func isWindows() bool { // return runtime.GOOS == "windows" // } +func doPrint(code string, colors []Color, str string) { + if isLikeInCmd { + winPrint(str, colors...) + } else { + _, _ = fmt.Fprint(output, RenderString(code, str)) + } +} + +func doPrintln(code string, colors []Color, args []interface{}) { + str := formatArgsForPrintln(args) + if isLikeInCmd { + winPrintln(str, colors...) + } else { + _, _ = fmt.Fprintln(output, RenderString(code, str)) + } +} + +func doPrintV2(code, str string) { + if isLikeInCmd { + renderColorCodeOnCmd(func() { + _, _ = fmt.Fprint(output, RenderString(code, str)) + }) + } else { + _, _ = fmt.Fprint(output, RenderString(code, str)) + } +} + +func doPrintlnV2(code string, args []interface{}) { + str := formatArgsForPrintln(args) + if isLikeInCmd { + renderColorCodeOnCmd(func() { + _, _ = fmt.Fprintln(output, RenderString(code, str)) + }) + } else { + _, _ = fmt.Fprintln(output, RenderString(code, str)) + } +} + func stringToArr(str, sep string) (arr []string) { str = strings.TrimSpace(str) if str == "" { @@ -80,3 +145,17 @@ func stringToArr(str, sep string) (arr []string) { return } + +// if use Println, will add spaces for each arg +func formatArgsForPrintln(args []interface{}) (message string) { + if ln := len(args); ln == 0 { + message = "" + } else if ln == 1 { + message = fmt.Sprint(args[0]) + } else { + message = fmt.Sprintln(args...) + // clear last "\n" + message = message[:len(message)-1] + } + return +} diff --git a/vendor/github.com/gostaticanalysis/analysisutil/call.go b/vendor/github.com/gostaticanalysis/analysisutil/call.go new file mode 100644 index 00000000000..c2a6200f332 --- /dev/null +++ b/vendor/github.com/gostaticanalysis/analysisutil/call.go @@ -0,0 +1,206 @@ +package analysisutil + +import ( + "go/types" + + "golang.org/x/tools/go/ssa" +) + +// CalledChecker checks a function is called. +// See From and Func. +type CalledChecker struct { + Ignore func(instr ssa.Instruction) bool +} + +// Func returns true when f is called in the instr. +// If recv is not nil, Called also checks the receiver. +func (c *CalledChecker) Func(instr ssa.Instruction, recv ssa.Value, f *types.Func) bool { + + if c.Ignore != nil && c.Ignore(instr) { + return false + } + + call, ok := instr.(ssa.CallInstruction) + if !ok { + return false + } + + common := call.Common() + if common == nil { + return false + } + + callee := common.StaticCallee() + if callee == nil { + return false + } + + fn, ok := callee.Object().(*types.Func) + if !ok { + return false + } + + if recv != nil && + common.Signature().Recv() != nil && + (len(common.Args) == 0 || common.Args[0] != recv) { + return false + } + + return fn == f +} + +// From checks whether receiver's method is called in an instruction +// which belogns to after i-th instructions, or in succsor blocks of b. +// The first result is above value. +// The second result is whether type of i-th instruction does not much receiver +// or matches with ignore cases. +func (c *CalledChecker) From(b *ssa.BasicBlock, i int, receiver types.Type, methods ...*types.Func) (called, ok bool) { + if b == nil || i < 0 || i >= len(b.Instrs) || + receiver == nil || len(methods) == 0 { + return false, false + } + + v, ok := b.Instrs[i].(ssa.Value) + if !ok { + return false, false + } + + if !identical(v.Type(), receiver) { + return false, false + } + + from := &calledFrom{recv: v, fs: methods, ignore: c.Ignore} + if from.ignored() { + return false, false + } + + if from.instrs(b.Instrs[i:]) || + from.succs(b) { + return true, true + } + + return false, true +} + +type calledFrom struct { + recv ssa.Value + fs []*types.Func + done map[*ssa.BasicBlock]bool + ignore func(ssa.Instruction) bool +} + +func (c *calledFrom) ignored() bool { + refs := c.recv.Referrers() + if refs == nil { + return false + } + + for _, ref := range *refs { + if !c.isOwn(ref) && + ((c.ignore != nil && c.ignore(ref)) || + c.isRet(ref) || c.isArg(ref)) { + return true + } + } + + return false +} + +func (c *calledFrom) isOwn(instr ssa.Instruction) bool { + v, ok := instr.(ssa.Value) + if !ok { + return false + } + return v == c.recv +} + +func (c *calledFrom) isRet(instr ssa.Instruction) bool { + + ret, ok := instr.(*ssa.Return) + if !ok { + return false + } + + for _, r := range ret.Results { + if r == c.recv { + return true + } + } + + return false +} + +func (c *calledFrom) isArg(instr ssa.Instruction) bool { + + call, ok := instr.(ssa.CallInstruction) + if !ok { + return false + } + + common := call.Common() + if common == nil { + return false + } + + args := common.Args + if common.Signature().Recv() != nil { + args = args[1:] + } + + for i := range args { + if args[i] == c.recv { + return true + } + } + + return false +} + +func (c *calledFrom) instrs(instrs []ssa.Instruction) bool { + for _, instr := range instrs { + for _, f := range c.fs { + if Called(instr, c.recv, f) { + return true + } + } + } + return false +} + +func (c *calledFrom) succs(b *ssa.BasicBlock) bool { + if c.done == nil { + c.done = map[*ssa.BasicBlock]bool{} + } + + if c.done[b] { + return false + } + c.done[b] = true + + if len(b.Succs) == 0 { + return false + } + + for _, s := range b.Succs { + if !c.instrs(s.Instrs) && !c.succs(s) { + return false + } + } + + return true +} + +// CalledFrom checks whether receiver's method is called in an instruction +// which belogns to after i-th instructions, or in succsor blocks of b. +// The first result is above value. +// The second result is whether type of i-th instruction does not much receiver +// or matches with ignore cases. +func CalledFrom(b *ssa.BasicBlock, i int, receiver types.Type, methods ...*types.Func) (called, ok bool) { + return new(CalledChecker).From(b, i, receiver, methods...) +} + +// Called returns true when f is called in the instr. +// If recv is not nil, Called also checks the receiver. +func Called(instr ssa.Instruction, recv ssa.Value, f *types.Func) bool { + return new(CalledChecker).Func(instr, recv, f) +} diff --git a/vendor/github.com/gostaticanalysis/analysisutil/ssa.go b/vendor/github.com/gostaticanalysis/analysisutil/ssa.go index 3791586675b..67ccb41a32b 100644 --- a/vendor/github.com/gostaticanalysis/analysisutil/ssa.go +++ b/vendor/github.com/gostaticanalysis/analysisutil/ssa.go @@ -1,6 +1,8 @@ package analysisutil -import "golang.org/x/tools/go/ssa" +import ( + "golang.org/x/tools/go/ssa" +) // IfInstr returns *ssa.If which is contained in the block b. // If the block b has not any if instruction, IfInstr returns nil. @@ -29,3 +31,42 @@ func Phi(b *ssa.BasicBlock) (phis []*ssa.Phi) { } return } + +// Returns returns a slice of *ssa.Return in the function. +func Returns(v ssa.Value) []*ssa.Return { + var fn *ssa.Function + switch v := v.(type) { + case *ssa.Function: + fn = v + case *ssa.MakeClosure: + return Returns(v.Fn) + default: + return nil + } + + var rets []*ssa.Return + done := map[*ssa.BasicBlock]bool{} + for _, b := range fn.Blocks { + rets = append(rets, returnsInBlock(b, done)...) + } + return rets +} + +func returnsInBlock(b *ssa.BasicBlock, done map[*ssa.BasicBlock]bool) (rets []*ssa.Return) { + if done[b] { + return + } + done[b] = true + + if len(b.Instrs) != 0 { + switch instr := b.Instrs[len(b.Instrs)-1].(type) { + case *ssa.Return: + rets = append(rets, instr) + } + } + + for _, s := range b.Succs { + rets = append(rets, returnsInBlock(s, done)...) + } + return +} diff --git a/vendor/github.com/gostaticanalysis/analysisutil/types.go b/vendor/github.com/gostaticanalysis/analysisutil/types.go new file mode 100644 index 00000000000..383ce98561e --- /dev/null +++ b/vendor/github.com/gostaticanalysis/analysisutil/types.go @@ -0,0 +1,187 @@ +package analysisutil + +import ( + "go/ast" + "go/types" + + "golang.org/x/tools/go/analysis" +) + +var errType = types.Universe.Lookup("error").Type().Underlying().(*types.Interface) + +// ImplementsError return whether t implements error interface. +func ImplementsError(t types.Type) bool { + return types.Implements(t, errType) +} + +// ObjectOf returns types.Object by given name in the package. +func ObjectOf(pass *analysis.Pass, pkg, name string) types.Object { + return LookupFromImports(pass.Pkg.Imports(), pkg, name) +} + +// TypeOf returns types.Type by given name in the package. +// TypeOf accepts pointer types such as *T. +func TypeOf(pass *analysis.Pass, pkg, name string) types.Type { + if name == "" { + return nil + } + + if name[0] == '*' { + return types.NewPointer(TypeOf(pass, pkg, name[1:])) + } + + obj := ObjectOf(pass, pkg, name) + if obj == nil { + return nil + } + + return obj.Type() +} + +// MethodOf returns a method which has given name in the type. +func MethodOf(typ types.Type, name string) *types.Func { + switch typ := typ.(type) { + case *types.Named: + for i := 0; i < typ.NumMethods(); i++ { + if f := typ.Method(i); f.Id() == name { + return f + } + } + case *types.Pointer: + return MethodOf(typ.Elem(), name) + } + return nil +} + +// see: https://github.com/golang/go/issues/19670 +func identical(x, y types.Type) (ret bool) { + defer func() { + r := recover() + switch r := r.(type) { + case string: + if r == "unreachable" { + ret = false + return + } + case nil: + return + } + panic(r) + }() + return types.Identical(x, y) +} + +// Interfaces returns a map of interfaces which are declared in the package. +func Interfaces(pkg *types.Package) map[string]*types.Interface { + ifs := map[string]*types.Interface{} + + for _, n := range pkg.Scope().Names() { + o := pkg.Scope().Lookup(n) + if o != nil { + i, ok := o.Type().Underlying().(*types.Interface) + if ok { + ifs[n] = i + } + } + } + + return ifs +} + +// Structs returns a map of structs which are declared in the package. +func Structs(pkg *types.Package) map[string]*types.Struct { + structs := map[string]*types.Struct{} + + for _, n := range pkg.Scope().Names() { + o := pkg.Scope().Lookup(n) + if o != nil { + s, ok := o.Type().Underlying().(*types.Struct) + if ok { + structs[n] = s + } + } + } + + return structs +} + +// HasField returns whether the struct has the field. +func HasField(s *types.Struct, f *types.Var) bool { + if s == nil || f == nil { + return false + } + + for i := 0; i < s.NumFields(); i++ { + if s.Field(i) == f { + return true + } + } + + return false +} + +func TypesInfo(info ...*types.Info) *types.Info { + if len(info) == 0 { + return nil + } + + var merged types.Info + for i := range info { + mergeTypesInfo(&merged, info[i]) + } + + return &merged +} + +func mergeTypesInfo(i1, i2 *types.Info) { + // Types + if i1.Types == nil && i2.Types != nil { + i1.Types = map[ast.Expr]types.TypeAndValue{} + } + for expr, tv := range i2.Types { + i1.Types[expr] = tv + } + + // Defs + if i1.Defs == nil && i2.Defs != nil { + i1.Defs = map[*ast.Ident]types.Object{} + } + for ident, obj := range i2.Defs { + i1.Defs[ident] = obj + } + + // Uses + if i1.Uses == nil && i2.Uses != nil { + i1.Uses = map[*ast.Ident]types.Object{} + } + for ident, obj := range i2.Uses { + i1.Uses[ident] = obj + } + + // Implicits + if i1.Implicits == nil && i2.Implicits != nil { + i1.Implicits = map[ast.Node]types.Object{} + } + for n, obj := range i2.Implicits { + i1.Implicits[n] = obj + } + + // Selections + if i1.Selections == nil && i2.Selections != nil { + i1.Selections = map[*ast.SelectorExpr]*types.Selection{} + } + for expr, sel := range i2.Selections { + i1.Selections[expr] = sel + } + + // Scopes + if i1.Scopes == nil && i2.Scopes != nil { + i1.Scopes = map[ast.Node]*types.Scope{} + } + for n, s := range i2.Scopes { + i1.Scopes[n] = s + } + + // InitOrder + i1.InitOrder = append(i1.InitOrder, i2.InitOrder...) +} diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/.golangci.yml b/vendor/github.com/hashicorp/aws-sdk-go-base/.golangci.yml index 59ef674ca41..687b0c780dc 100644 --- a/vendor/github.com/hashicorp/aws-sdk-go-base/.golangci.yml +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/.golangci.yml @@ -6,14 +6,21 @@ linters: disable-all: true enable: - deadcode + - dogsled - errcheck + - goconst - gofmt + - gomnd - gosimple - ineffassign + - interfacer - misspell + - scopelint - staticcheck - structcheck - unconvert + - unparam - unused + - typecheck - varcheck - vet diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/.travis.yml b/vendor/github.com/hashicorp/aws-sdk-go-base/.travis.yml deleted file mode 100644 index f1aaa658b82..00000000000 --- a/vendor/github.com/hashicorp/aws-sdk-go-base/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -dist: xenial -language: go -go: -- "1.13.x" - -matrix: - fast_finish: true - allow_failures: - - go: tip - -install: -- make tools - -script: -- make lint -- go test -timeout=30s -parallel=4 -v ./... - -branches: - only: - - master diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/CHANGELOG.md b/vendor/github.com/hashicorp/aws-sdk-go-base/CHANGELOG.md index 558e7e39322..fd1b523fa7b 100644 --- a/vendor/github.com/hashicorp/aws-sdk-go-base/CHANGELOG.md +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/CHANGELOG.md @@ -1,3 +1,25 @@ +# v0.5.0 (June 4, 2020) + +BREAKING CHANGES + +* Credential ordering has changed from static, environment, shared credentials, EC2 metadata, default AWS Go SDK (shared configuration, web identity, ECS, EC2 Metadata) to static, environment, shared credentials, default AWS Go SDK (shared configuration, web identity, ECS, EC2 Metadata). #20 +* The `AWS_METADATA_TIMEOUT` environment variable no longer has any effect as we now depend on the default AWS Go SDK EC2 Metadata client timeout of one second with two retries. #20 / #44 + +ENHANCEMENTS + +* Always enable AWS shared configuration file support (no longer require `AWS_SDK_LOAD_CONFIG` environment variable) #38 +* Automatically expand `~` prefix for home directories in shared credentials filename handling #40 +* Support assume role duration, policy ARNs, tags, and transitive tag keys via configuration #39 +* Add `CannotAssumeRoleError` and `NoValidCredentialSourcesError` error types with helpers #42 + +BUG FIXES + +* Properly use custom STS endpoint during AssumeRole API calls triggered by Terraform AWS Provider and S3 Backend configurations #32 +* Properly use custom EC2 metadata endpoint during API calls triggered by fallback credentials lookup #32 +* Prefer shared configuration handling over EC2 metadata #20 +* Prefer ECS credentials over EC2 metadata #20 +* Remove hardcoded AWS Provider messaging in error messages #31 / #42 + # v0.4.0 (October 3, 2019) BUG FIXES diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/awsauth.go b/vendor/github.com/hashicorp/aws-sdk-go-base/awsauth.go index 5311620386a..3363b1d5be0 100644 --- a/vendor/github.com/hashicorp/aws-sdk-go-base/awsauth.go +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/awsauth.go @@ -13,29 +13,21 @@ import ( awsCredentials "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" "github.com/aws/aws-sdk-go/aws/credentials/stscreds" - "github.com/aws/aws-sdk-go/aws/defaults" "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/iam" "github.com/aws/aws-sdk-go/service/sts" "github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/go-multierror" + homedir "github.com/mitchellh/go-homedir" ) const ( - // errMsgNoValidCredentialSources error getting credentials - errMsgNoValidCredentialSources = `No valid credential sources found for AWS Provider. - Please see https://terraform.io/docs/providers/aws/index.html for more information on - providing credentials for the AWS Provider` + // Default amount of time for EC2/ECS metadata client operations. + // Keep this value low to prevent long delays in non-EC2/ECS environments. + DefaultMetadataClientTimeout = 100 * time.Millisecond ) -var ( - // ErrNoValidCredentialSources indicates that no credentials source could be found - ErrNoValidCredentialSources = errNoValidCredentialSources() -) - -func errNoValidCredentialSources() error { return errors.New(errMsgNoValidCredentialSources) } - // GetAccountIDAndPartition gets the account ID and associated partition. func GetAccountIDAndPartition(iamconn *iam.IAM, stsconn *sts.STS, authProviderName string) (string, string, error) { var accountID, partition string @@ -75,7 +67,7 @@ func GetAccountIDAndPartitionFromEC2Metadata() (string, string, error) { setOptionalEndpoint(cfg) sess, err := session.NewSession(cfg) if err != nil { - return "", "", fmt.Errorf("error creating EC2 Metadata session: %s", err) + return "", "", fmt.Errorf("error creating EC2 Metadata session: %w", err) } metadataClient := ec2metadata.New(sess) @@ -84,7 +76,7 @@ func GetAccountIDAndPartitionFromEC2Metadata() (string, string, error) { // We can end up here if there's an issue with the instance metadata service // or if we're getting credentials from AdRoll's Hologram (in which case IAMInfo will // error out). - err = fmt.Errorf("failed getting account information via EC2 Metadata IAM information: %s", err) + err = fmt.Errorf("failed getting account information via EC2 Metadata IAM information: %w", err) log.Printf("[DEBUG] %s", err) return "", "", err } @@ -107,7 +99,7 @@ func GetAccountIDAndPartitionFromIAMGetUser(iamconn *iam.IAM) (string, string, e return "", "", nil } } - err = fmt.Errorf("failed getting account information via iam:GetUser: %s", err) + err = fmt.Errorf("failed getting account information via iam:GetUser: %w", err) log.Printf("[DEBUG] %s", err) return "", "", err } @@ -130,7 +122,7 @@ func GetAccountIDAndPartitionFromIAMListRoles(iamconn *iam.IAM) (string, string, MaxItems: aws.Int64(int64(1)), }) if err != nil { - err = fmt.Errorf("failed getting account information via iam:ListRoles: %s", err) + err = fmt.Errorf("failed getting account information via iam:ListRoles: %w", err) log.Printf("[DEBUG] %s", err) return "", "", err } @@ -151,7 +143,7 @@ func GetAccountIDAndPartitionFromSTSGetCallerIdentity(stsconn *sts.STS) (string, output, err := stsconn.GetCallerIdentity(&sts.GetCallerIdentityInput{}) if err != nil { - return "", "", fmt.Errorf("error calling sts:GetCallerIdentity: %s", err) + return "", "", fmt.Errorf("error calling sts:GetCallerIdentity: %w", err) } if output == nil || output.Arn == nil { @@ -177,37 +169,30 @@ func parseAccountIDAndPartitionFromARN(inputARN string) (string, string, error) func GetCredentialsFromSession(c *Config) (*awsCredentials.Credentials, error) { log.Printf("[INFO] Attempting to use session-derived credentials") - var sess *session.Session - var err error - if c.Profile == "" { - sess, err = session.NewSession() - if err != nil { - return nil, ErrNoValidCredentialSources - } - } else { - options := &session.Options{ - Config: aws.Config{ - HTTPClient: cleanhttp.DefaultClient(), - MaxRetries: aws.Int(0), - Region: aws.String(c.Region), - }, - } - options.Profile = c.Profile - options.SharedConfigState = session.SharedConfigEnable + // Avoid setting HTTPClient here as it will prevent the ec2metadata + // client from automatically lowering the timeout to 1 second. + options := &session.Options{ + Config: aws.Config{ + EndpointResolver: c.EndpointResolver(), + MaxRetries: aws.Int(0), + Region: aws.String(c.Region), + }, + Profile: c.Profile, + SharedConfigState: session.SharedConfigEnable, + } - sess, err = session.NewSessionWithOptions(*options) - if err != nil { - if IsAWSErr(err, "NoCredentialProviders", "") { - return nil, ErrNoValidCredentialSources - } - return nil, fmt.Errorf("Error creating AWS session: %s", err) + sess, err := session.NewSessionWithOptions(*options) + if err != nil { + if IsAWSErr(err, "NoCredentialProviders", "") { + return nil, c.NewNoValidCredentialSourcesError(err) } + return nil, fmt.Errorf("Error creating AWS session: %w", err) } creds := sess.Config.Credentials cp, err := sess.Config.Credentials.Get() if err != nil { - return nil, ErrNoValidCredentialSources + return nil, c.NewNoValidCredentialSourcesError(err) } log.Printf("[INFO] Successfully derived credentials from session") @@ -216,10 +201,16 @@ func GetCredentialsFromSession(c *Config) (*awsCredentials.Credentials, error) { } // GetCredentials gets credentials from the environment, shared credentials, -// or the session (which may include a credential process). GetCredentials also -// validates the credentials and the ability to assume a role or will return an -// error if unsuccessful. +// the session (which may include a credential process), or ECS/EC2 metadata endpoints. +// GetCredentials also validates the credentials and the ability to assume a role +// or will return an error if unsuccessful. func GetCredentials(c *Config) (*awsCredentials.Credentials, error) { + sharedCredentialsFilename, err := homedir.Expand(c.CredsFilename) + + if err != nil { + return nil, fmt.Errorf("error expanding shared credentials filename: %w", err) + } + // build a chain provider, lazy-evaluated by aws-sdk providers := []awsCredentials.Provider{ &awsCredentials.StaticProvider{Value: awsCredentials.Value{ @@ -229,70 +220,11 @@ func GetCredentials(c *Config) (*awsCredentials.Credentials, error) { }}, &awsCredentials.EnvProvider{}, &awsCredentials.SharedCredentialsProvider{ - Filename: c.CredsFilename, + Filename: sharedCredentialsFilename, Profile: c.Profile, }, } - // Build isolated HTTP client to avoid issues with globally-shared settings - client := cleanhttp.DefaultClient() - - // Keep the default timeout (100ms) low as we don't want to wait in non-EC2 environments - client.Timeout = 100 * time.Millisecond - - const userTimeoutEnvVar = "AWS_METADATA_TIMEOUT" - userTimeout := os.Getenv(userTimeoutEnvVar) - if userTimeout != "" { - newTimeout, err := time.ParseDuration(userTimeout) - if err == nil { - if newTimeout.Nanoseconds() > 0 { - client.Timeout = newTimeout - } else { - log.Printf("[WARN] Non-positive value of %s (%s) is meaningless, ignoring", userTimeoutEnvVar, newTimeout.String()) - } - } else { - log.Printf("[WARN] Error converting %s to time.Duration: %s", userTimeoutEnvVar, err) - } - } - - log.Printf("[INFO] Setting AWS metadata API timeout to %s", client.Timeout.String()) - cfg := &aws.Config{ - HTTPClient: client, - } - usedEndpoint := setOptionalEndpoint(cfg) - - // Add the default AWS provider for ECS Task Roles if the relevant env variable is set - if uri := os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"); len(uri) > 0 { - providers = append(providers, defaults.RemoteCredProvider(*cfg, defaults.Handlers())) - log.Print("[INFO] ECS container credentials detected, RemoteCredProvider added to auth chain") - } - - if !c.SkipMetadataApiCheck { - // Real AWS should reply to a simple metadata request. - // We check it actually does to ensure something else didn't just - // happen to be listening on the same IP:Port - ec2Session, err := session.NewSession(cfg) - - if err != nil { - return nil, fmt.Errorf("error creating EC2 Metadata session: %s", err) - } - - metadataClient := ec2metadata.New(ec2Session) - if metadataClient.Available() { - providers = append(providers, &ec2rolecreds.EC2RoleProvider{ - Client: metadataClient, - }) - log.Print("[INFO] AWS EC2 instance detected via default metadata" + - " API endpoint, EC2RoleProvider added to the auth chain") - } else { - if usedEndpoint == "" { - usedEndpoint = "default location" - } - log.Printf("[INFO] Ignoring AWS metadata API endpoint at %s "+ - "as it doesn't return any instance-id", usedEndpoint) - } - } - // Validate the credentials before returning them creds := awsCredentials.NewChainCredentials(providers) cp, err := creds.Get() @@ -303,7 +235,7 @@ func GetCredentials(c *Config) (*awsCredentials.Credentials, error) { return nil, err } } else { - return nil, fmt.Errorf("Error loading credentials for AWS Provider: %s", err) + return nil, fmt.Errorf("Error loading credentials for AWS Provider: %w", err) } } else { log.Printf("[INFO] AWS Auth provider used: %q", cp.ProviderName) @@ -316,20 +248,21 @@ func GetCredentials(c *Config) (*awsCredentials.Credentials, error) { // Otherwise we need to construct an STS client with the main credentials, and verify // that we can assume the defined role. - log.Printf("[INFO] Attempting to AssumeRole %s (SessionName: %q, ExternalId: %q, Policy: %q)", - c.AssumeRoleARN, c.AssumeRoleSessionName, c.AssumeRoleExternalID, c.AssumeRolePolicy) + log.Printf("[INFO] Attempting to AssumeRole %s (SessionName: %q, ExternalId: %q)", + c.AssumeRoleARN, c.AssumeRoleSessionName, c.AssumeRoleExternalID) awsConfig := &aws.Config{ - Credentials: creds, - Region: aws.String(c.Region), - MaxRetries: aws.Int(c.MaxRetries), - HTTPClient: cleanhttp.DefaultClient(), + Credentials: creds, + EndpointResolver: c.EndpointResolver(), + Region: aws.String(c.Region), + MaxRetries: aws.Int(c.MaxRetries), + HTTPClient: cleanhttp.DefaultClient(), } assumeRoleSession, err := session.NewSession(awsConfig) if err != nil { - return nil, fmt.Errorf("error creating assume role session: %s", err) + return nil, fmt.Errorf("error creating assume role session: %w", err) } stsclient := sts.New(assumeRoleSession) @@ -337,31 +270,60 @@ func GetCredentials(c *Config) (*awsCredentials.Credentials, error) { Client: stsclient, RoleARN: c.AssumeRoleARN, } - if c.AssumeRoleSessionName != "" { - assumeRoleProvider.RoleSessionName = c.AssumeRoleSessionName + + if c.AssumeRoleDurationSeconds > 0 { + assumeRoleProvider.Duration = time.Duration(c.AssumeRoleDurationSeconds) * time.Second } + if c.AssumeRoleExternalID != "" { assumeRoleProvider.ExternalID = aws.String(c.AssumeRoleExternalID) } + if c.AssumeRolePolicy != "" { assumeRoleProvider.Policy = aws.String(c.AssumeRolePolicy) } + if len(c.AssumeRolePolicyARNs) > 0 { + var policyDescriptorTypes []*sts.PolicyDescriptorType + + for _, policyARN := range c.AssumeRolePolicyARNs { + policyDescriptorType := &sts.PolicyDescriptorType{ + Arn: aws.String(policyARN), + } + policyDescriptorTypes = append(policyDescriptorTypes, policyDescriptorType) + } + + assumeRoleProvider.PolicyArns = policyDescriptorTypes + } + + if c.AssumeRoleSessionName != "" { + assumeRoleProvider.RoleSessionName = c.AssumeRoleSessionName + } + + if len(c.AssumeRoleTags) > 0 { + var tags []*sts.Tag + + for k, v := range c.AssumeRoleTags { + tag := &sts.Tag{ + Key: aws.String(k), + Value: aws.String(v), + } + tags = append(tags, tag) + } + + assumeRoleProvider.Tags = tags + } + + if len(c.AssumeRoleTransitiveTagKeys) > 0 { + assumeRoleProvider.TransitiveTagKeys = aws.StringSlice(c.AssumeRoleTransitiveTagKeys) + } + providers = []awsCredentials.Provider{assumeRoleProvider} assumeRoleCreds := awsCredentials.NewChainCredentials(providers) _, err = assumeRoleCreds.Get() if err != nil { - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" { - return nil, fmt.Errorf("The role %q cannot be assumed.\n\n"+ - " There are a number of possible causes of this - the most common are:\n"+ - " * The credentials used in order to assume the role are invalid\n"+ - " * The credentials do not have appropriate permission to assume the role\n"+ - " * The role ARN is not valid", - c.AssumeRoleARN) - } - - return nil, fmt.Errorf("Error loading credentials for AWS Provider: %s", err) + return nil, c.NewCannotAssumeRoleError(err) } return assumeRoleCreds, nil diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/awserr.go b/vendor/github.com/hashicorp/aws-sdk-go-base/awserr.go index 28295483518..ce657679ae5 100644 --- a/vendor/github.com/hashicorp/aws-sdk-go-base/awserr.go +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/awserr.go @@ -1,6 +1,7 @@ package awsbase import ( + "errors" "strings" "github.com/aws/aws-sdk-go/aws/awserr" @@ -11,17 +12,13 @@ import ( // * Error.Code() matches code // * Error.Message() contains message func IsAWSErr(err error, code string, message string) bool { - awsErr, ok := err.(awserr.Error) + var awsErr awserr.Error - if !ok { - return false + if errors.As(err, &awsErr) { + return awsErr.Code() == code && strings.Contains(awsErr.Message(), message) } - if awsErr.Code() != code { - return false - } - - return strings.Contains(awsErr.Message(), message) + return false } // IsAWSErrExtended returns true if the error matches all these conditions: @@ -33,5 +30,15 @@ func IsAWSErrExtended(err error, code string, message string, origErrMessage str if !IsAWSErr(err, code, message) { return false } - return strings.Contains(err.(awserr.Error).OrigErr().Error(), origErrMessage) + + if origErrMessage == "" { + return true + } + + // Ensure OrigErr() is non-nil, to prevent panics + if origErr := err.(awserr.Error).OrigErr(); origErr != nil { + return strings.Contains(origErr.Error(), origErrMessage) + } + + return false } diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/config.go b/vendor/github.com/hashicorp/aws-sdk-go-base/config.go index fb57e44e41d..c5f9daafbdf 100644 --- a/vendor/github.com/hashicorp/aws-sdk-go-base/config.go +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/config.go @@ -1,25 +1,31 @@ package awsbase type Config struct { - AccessKey string - AssumeRoleARN string - AssumeRoleExternalID string - AssumeRolePolicy string - AssumeRoleSessionName string - CredsFilename string - DebugLogging bool - IamEndpoint string - Insecure bool - MaxRetries int - Profile string - Region string - SecretKey string - SkipCredsValidation bool - SkipMetadataApiCheck bool - SkipRequestingAccountId bool - StsEndpoint string - Token string - UserAgentProducts []*UserAgentProduct + AccessKey string + AssumeRoleARN string + AssumeRoleDurationSeconds int + AssumeRoleExternalID string + AssumeRolePolicy string + AssumeRolePolicyARNs []string + AssumeRoleSessionName string + AssumeRoleTags map[string]string + AssumeRoleTransitiveTagKeys []string + CallerDocumentationURL string + CallerName string + CredsFilename string + DebugLogging bool + IamEndpoint string + Insecure bool + MaxRetries int + Profile string + Region string + SecretKey string + SkipCredsValidation bool + SkipMetadataApiCheck bool + SkipRequestingAccountId bool + StsEndpoint string + Token string + UserAgentProducts []*UserAgentProduct } type UserAgentProduct struct { diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/endpoints.go b/vendor/github.com/hashicorp/aws-sdk-go-base/endpoints.go new file mode 100644 index 00000000000..c3f64d1cd37 --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/endpoints.go @@ -0,0 +1,46 @@ +package awsbase + +import ( + "log" + "os" + + "github.com/aws/aws-sdk-go/aws/ec2metadata" + "github.com/aws/aws-sdk-go/aws/endpoints" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/sts" +) + +func (c *Config) EndpointResolver() endpoints.Resolver { + resolver := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { + // Ensure we pass all existing information (e.g. SigningRegion) and + // only override the URL, otherwise a MissingRegion error can occur + // when aws.Config.Region is not defined. + resolvedEndpoint, err := endpoints.DefaultResolver().EndpointFor(service, region, optFns...) + + if err != nil { + return resolvedEndpoint, err + } + + switch service { + case ec2metadata.ServiceName: + if endpoint := os.Getenv("AWS_METADATA_URL"); endpoint != "" { + log.Printf("[INFO] Setting custom EC2 metadata endpoint: %s", endpoint) + resolvedEndpoint.URL = endpoint + } + case iam.ServiceName: + if endpoint := c.IamEndpoint; endpoint != "" { + log.Printf("[INFO] Setting custom IAM endpoint: %s", endpoint) + resolvedEndpoint.URL = endpoint + } + case sts.ServiceName: + if endpoint := c.StsEndpoint; endpoint != "" { + log.Printf("[INFO] Setting custom STS endpoint: %s", endpoint) + resolvedEndpoint.URL = endpoint + } + } + + return resolvedEndpoint, nil + } + + return endpoints.ResolverFunc(resolver) +} diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/errors.go b/vendor/github.com/hashicorp/aws-sdk-go-base/errors.go new file mode 100644 index 00000000000..2d5f1677cc5 --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/errors.go @@ -0,0 +1,76 @@ +package awsbase + +import ( + "errors" + "fmt" +) + +// CannotAssumeRoleError occurs when AssumeRole cannot complete. +type CannotAssumeRoleError struct { + Config *Config + Err error +} + +func (e CannotAssumeRoleError) Error() string { + if e.Config == nil { + return fmt.Sprintf("cannot assume role: %s", e.Err) + } + + return fmt.Sprintf(`IAM Role (%s) cannot be assumed. + +There are a number of possible causes of this - the most common are: + * The credentials used in order to assume the role are invalid + * The credentials do not have appropriate permission to assume the role + * The role ARN is not valid + +Error: %s +`, e.Config.AssumeRoleARN, e.Err) +} + +func (e CannotAssumeRoleError) Unwrap() error { + return e.Err +} + +// IsCannotAssumeRoleError returns true if the error contains the CannotAssumeRoleError type. +func IsCannotAssumeRoleError(err error) bool { + var e CannotAssumeRoleError + return errors.As(err, &e) +} + +func (c *Config) NewCannotAssumeRoleError(err error) CannotAssumeRoleError { + return CannotAssumeRoleError{Config: c, Err: err} +} + +// NoValidCredentialSourcesError occurs when all credential lookup methods have been exhausted without results. +type NoValidCredentialSourcesError struct { + Config *Config + Err error +} + +func (e NoValidCredentialSourcesError) Error() string { + if e.Config == nil { + return fmt.Sprintf("no valid credential sources found: %s", e.Err) + } + + return fmt.Sprintf(`no valid credential sources for %s found. + +Please see %s +for more information about providing credentials. + +Error: %s +`, e.Config.CallerName, e.Config.CallerDocumentationURL, e.Err) +} + +func (e NoValidCredentialSourcesError) Unwrap() error { + return e.Err +} + +// IsNoValidCredentialSourcesError returns true if the error contains the NoValidCredentialSourcesError type. +func IsNoValidCredentialSourcesError(err error) bool { + var e NoValidCredentialSourcesError + return errors.As(err, &e) +} + +func (c *Config) NewNoValidCredentialSourcesError(err error) NoValidCredentialSourcesError { + return NoValidCredentialSourcesError{Config: c, Err: err} +} diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/go.mod b/vendor/github.com/hashicorp/aws-sdk-go-base/go.mod index 1af445d2b17..d4cba362aec 100644 --- a/vendor/github.com/hashicorp/aws-sdk-go-base/go.mod +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/go.mod @@ -1,12 +1,10 @@ module github.com/hashicorp/aws-sdk-go-base require ( - github.com/aws/aws-sdk-go v1.25.3 + github.com/aws/aws-sdk-go v1.31.9 github.com/hashicorp/go-cleanhttp v0.5.0 github.com/hashicorp/go-multierror v1.0.0 - github.com/stretchr/testify v1.3.0 // indirect - golang.org/x/net v0.0.0-20190213061140-3a22650c66bd // indirect - golang.org/x/text v0.3.0 // indirect + github.com/mitchellh/go-homedir v1.1.0 ) go 1.13 diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/go.sum b/vendor/github.com/hashicorp/aws-sdk-go-base/go.sum index f06c2e9105d..eabfab4b54f 100644 --- a/vendor/github.com/hashicorp/aws-sdk-go-base/go.sum +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/go.sum @@ -1,23 +1,31 @@ -github.com/aws/aws-sdk-go v1.16.36 h1:POeH34ZME++pr7GBGh+ZO6Y5kOwSMQpqp5BGUgooJ6k= -github.com/aws/aws-sdk-go v1.16.36/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= -github.com/aws/aws-sdk-go v1.25.3 h1:uM16hIw9BotjZKMZlX05SN2EFtaWfi/NonPKIARiBLQ= -github.com/aws/aws-sdk-go v1.25.3/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/aws/aws-sdk-go v1.31.9 h1:n+b34ydVfgC30j0Qm69yaapmjejQPW2BoDBX7Uy/tLI= +github.com/aws/aws-sdk-go v1.31.9/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmespath/go-jmespath v0.3.0 h1:OS12ieG61fsCg5+qLJ+SsW9NicxNkg3b25OyT2yCeUc= +github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd h1:HuTn7WObtcDo9uEEU7rEqL0jYthdXAmZ6PP+meazmaU= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2 h1:CCH4IOTTfewWjGOlSp+zGcjutRKlBEZQ6wTn8ozI/nI= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/mock.go b/vendor/github.com/hashicorp/aws-sdk-go-base/mock.go index e3c80266020..06ecd082bc4 100644 --- a/vendor/github.com/hashicorp/aws-sdk-go-base/mock.go +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/mock.go @@ -2,6 +2,7 @@ package awsbase import ( "bytes" + "encoding/json" "fmt" "log" "net/http" @@ -19,7 +20,7 @@ func MockAwsApiServer(svcName string, endpoints []*MockEndpoint) *httptest.Serve ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { buf := new(bytes.Buffer) if _, err := buf.ReadFrom(r.Body); err != nil { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Error reading from HTTP Request Body: %s", err) return } @@ -43,7 +44,7 @@ func MockAwsApiServer(svcName string, endpoints []*MockEndpoint) *httptest.Serve } } - w.WriteHeader(400) + w.WriteHeader(http.StatusBadRequest) })) return ts @@ -73,20 +74,43 @@ func awsMetadataApiMock(responses []*MetadataResponse) func() { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") w.Header().Add("Server", "MockEC2") - log.Printf("[DEBUG] Mocker server received request to %q", r.RequestURI) + log.Printf("[DEBUG] Mock EC2 metadata server received request: %s", r.RequestURI) for _, e := range responses { if r.RequestURI == e.Uri { fmt.Fprintln(w, e.Body) return } } - w.WriteHeader(400) + w.WriteHeader(http.StatusBadRequest) })) os.Setenv("AWS_METADATA_URL", ts.URL+"/latest") return ts.Close } +// ecsCredentialsApiMock establishes a httptest server to mock out the ECS credentials API. +func ecsCredentialsApiMock() func() { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Header().Add("Server", "MockECS") + log.Printf("[DEBUG] Mock ECS credentials server received request: %s", r.RequestURI) + if r.RequestURI == "/creds" { + _ = json.NewEncoder(w).Encode(map[string]string{ + "AccessKeyId": "EcsCredentialsAccessKey", + "Expiration": time.Now().UTC().Format(time.RFC3339), + "RoleArn": "arn:aws:iam::000000000000:role/EcsCredentials", + "SecretAccessKey": "EcsCredentialsSecretKey", + "Token": "EcsCredentialsSessionToken", + }) + return + } + w.WriteHeader(http.StatusBadRequest) + })) + + os.Setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", ts.URL+"/creds") + return ts.Close +} + // MockEndpoint represents a basic request and response that can be used for creating simple httptest server routes. type MockEndpoint struct { Request *MockRequest @@ -119,13 +143,17 @@ var ec2metadata_instanceIdEndpoint = &MetadataResponse{ } var ec2metadata_securityCredentialsEndpoints = []*MetadataResponse{ + { + Uri: "/latest/api/token", + Body: "Ec2MetadataApiToken", + }, { Uri: "/latest/meta-data/iam/security-credentials/", Body: "test_role", }, { Uri: "/latest/meta-data/iam/security-credentials/test_role", - Body: "{\"Code\":\"Success\",\"LastUpdated\":\"2015-12-11T17:17:25Z\",\"Type\":\"AWS-HMAC\",\"AccessKeyId\":\"somekey\",\"SecretAccessKey\":\"somesecret\",\"Token\":\"sometoken\"}", + Body: "{\"Code\":\"Success\",\"LastUpdated\":\"2015-12-11T17:17:25Z\",\"Type\":\"AWS-HMAC\",\"AccessKeyId\":\"Ec2MetadataAccessKey\",\"SecretAccessKey\":\"Ec2MetadataSecretKey\",\"Token\":\"Ec2MetadataSessionToken\"}", }, } @@ -165,6 +193,54 @@ const iamResponse_GetUser_unauthorized = ` + + + arn:aws:sts::555555555555:assumed-role/role/AssumeRoleSessionName + ARO123EXAMPLE123:AssumeRoleSessionName + + + AssumeRoleAccessKey + AssumeRoleSecretKey + AssumeRoleSessionToken + %s + + + + 01234567-89ab-cdef-0123-456789abcdef + +`, time.Now().UTC().Format(time.RFC3339)) + +const stsResponse_AssumeRole_InvalidClientTokenId = ` + + Sender + InvalidClientTokenId + The security token included in the request is invalid. + +4d0cf5ec-892a-4d3f-84e4-30e9987d9bdd +` + +var stsResponse_AssumeRoleWithWebIdentity_valid = fmt.Sprintf(` + + amzn1.account.AF6RHO7KZU5XRVQJGXK6HB56KR2A + client.6666666666666666666.6666@apps.example.com + + arn:aws:sts::666666666666:assumed-role/FederatedWebIdentityRole/AssumeRoleWithWebIdentitySessionName + ARO123EXAMPLE123:AssumeRoleWithWebIdentitySessionName + + + AssumeRoleWithWebIdentitySessionToken + AssumeRoleWithWebIdentitySecretKey + %s + AssumeRoleWithWebIdentityAccessKey + + www.amazon.com + + + 01234567-89ab-cdef-0123-456789abcdef + +`, time.Now().UTC().Format(time.RFC3339)) + const stsResponse_GetCallerIdentity_valid = ` arn:aws:iam::222222222222:user/Alice @@ -228,3 +304,5 @@ const iamResponse_ListRoles_unauthorized = ` 0 { @@ -82,9 +99,7 @@ func GetSession(c *Config) (*session.Session, error) { // NOTE: This logic can be fooled by other request errors raising the retry count // before any networking error occurs sess.Handlers.Retry.PushBack(func(r *request.Request) { - // We currently depend on the DefaultRetryer exponential backoff here. - // ~10 retries gives a fair backoff of a few seconds. - if r.RetryCount < 9 { + if r.RetryCount < MaxNetworkRetryCount { return } // RequestError: send request failed @@ -102,9 +117,8 @@ func GetSession(c *Config) (*session.Session, error) { }) if !c.SkipCredsValidation { - stsClient := sts.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.StsEndpoint)})) - if _, _, err := GetAccountIDAndPartitionFromSTSGetCallerIdentity(stsClient); err != nil { - return nil, fmt.Errorf("error using credentials to get account ID: %s", err) + if _, _, err := GetAccountIDAndPartitionFromSTSGetCallerIdentity(sts.New(sess)); err != nil { + return nil, fmt.Errorf("error validating provider credentials: %w", err) } } @@ -125,14 +139,14 @@ func GetSessionWithAccountIDAndPartition(c *Config) (*session.Session, string, s return sess, accountID, partition, nil } - iamClient := iam.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.IamEndpoint)})) - stsClient := sts.New(sess.Copy(&aws.Config{Endpoint: aws.String(c.StsEndpoint)})) + iamClient := iam.New(sess) + stsClient := sts.New(sess) if !c.SkipCredsValidation { accountID, partition, err := GetAccountIDAndPartitionFromSTSGetCallerIdentity(stsClient) if err != nil { - return nil, "", "", fmt.Errorf("error validating provider credentials: %s", err) + return nil, "", "", fmt.Errorf("error validating provider credentials: %w", err) } return sess, accountID, partition, nil @@ -154,7 +168,7 @@ func GetSessionWithAccountIDAndPartition(c *Config) (*session.Session, string, s return nil, "", "", fmt.Errorf( "AWS account ID not previously found and failed retrieving via all available methods. "+ "See https://www.terraform.io/docs/providers/aws/index.html#skip_requesting_account_id for workaround and implications. "+ - "Errors: %s", err) + "Errors: %w", err) } var partition string diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/LICENSE b/vendor/github.com/hashicorp/go-checkpoint/LICENSE similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/LICENSE rename to vendor/github.com/hashicorp/go-checkpoint/LICENSE diff --git a/vendor/github.com/hashicorp/go-checkpoint/README.md b/vendor/github.com/hashicorp/go-checkpoint/README.md new file mode 100644 index 00000000000..e717b6ad339 --- /dev/null +++ b/vendor/github.com/hashicorp/go-checkpoint/README.md @@ -0,0 +1,22 @@ +# Go Checkpoint Client + +[Checkpoint](http://checkpoint.hashicorp.com) is an internal service at +Hashicorp that we use to check version information, broadcast security +bulletins, etc. + +We understand that software making remote calls over the internet +for any reason can be undesirable. Because of this, Checkpoint can be +disabled in all of our software that includes it. You can view the source +of this client to see that we're not sending any private information. + +Each Hashicorp application has it's specific configuration option +to disable checkpoint calls, but the `CHECKPOINT_DISABLE` makes +the underlying checkpoint component itself disabled. For example +in the case of packer: +``` +CHECKPOINT_DISABLE=1 packer build +``` + +**Note:** This repository is probably useless outside of internal HashiCorp +use. It is open source for disclosure and because our open source projects +must be able to link to it. diff --git a/vendor/github.com/hashicorp/go-checkpoint/check.go b/vendor/github.com/hashicorp/go-checkpoint/check.go new file mode 100644 index 00000000000..109d0d35286 --- /dev/null +++ b/vendor/github.com/hashicorp/go-checkpoint/check.go @@ -0,0 +1,368 @@ +package checkpoint + +import ( + crand "crypto/rand" + "encoding/binary" + "encoding/json" + "fmt" + "io" + "io/ioutil" + mrand "math/rand" + "net/http" + "net/url" + "os" + "path/filepath" + "reflect" + "runtime" + "strconv" + "strings" + "time" + + "github.com/hashicorp/go-cleanhttp" +) + +var magicBytes = [4]byte{0x35, 0x77, 0x69, 0xFB} + +// CheckParams are the parameters for configuring a check request. +type CheckParams struct { + // Product and version are used to lookup the correct product and + // alerts for the proper version. The version is also used to perform + // a version check. + Product string + Version string + + // Arch and OS are used to filter alerts potentially only to things + // affecting a specific os/arch combination. If these aren't specified, + // they'll be automatically filled in. + Arch string + OS string + + // Signature is some random signature that should be stored and used + // as a cookie-like value. This ensures that alerts aren't repeated. + // If the signature is changed, repeat alerts may be sent down. The + // signature should NOT be anything identifiable to a user (such as + // a MAC address). It should be random. + // + // If SignatureFile is given, then the signature will be read from this + // file. If the file doesn't exist, then a random signature will + // automatically be generated and stored here. SignatureFile will be + // ignored if Signature is given. + Signature string + SignatureFile string + + // CacheFile, if specified, will cache the result of a check. The + // duration of the cache is specified by CacheDuration, and defaults + // to 48 hours if not specified. If the CacheFile is newer than the + // CacheDuration, than the Check will short-circuit and use those + // results. + // + // If the CacheFile directory doesn't exist, it will be created with + // permissions 0755. + CacheFile string + CacheDuration time.Duration + + // Force, if true, will force the check even if CHECKPOINT_DISABLE + // is set. Within HashiCorp products, this is ONLY USED when the user + // specifically requests it. This is never automatically done without + // the user's consent. + Force bool +} + +// CheckResponse is the response for a check request. +type CheckResponse struct { + Product string `json:"product"` + CurrentVersion string `json:"current_version"` + CurrentReleaseDate int `json:"current_release_date"` + CurrentDownloadURL string `json:"current_download_url"` + CurrentChangelogURL string `json:"current_changelog_url"` + ProjectWebsite string `json:"project_website"` + Outdated bool `json:"outdated"` + Alerts []*CheckAlert `json:"alerts"` +} + +// CheckAlert is a single alert message from a check request. +// +// These never have to be manually constructed, and are typically populated +// into a CheckResponse as a result of the Check request. +type CheckAlert struct { + ID int `json:"id"` + Date int `json:"date"` + Message string `json:"message"` + URL string `json:"url"` + Level string `json:"level"` +} + +// Check checks for alerts and new version information. +func Check(p *CheckParams) (*CheckResponse, error) { + if disabled := os.Getenv("CHECKPOINT_DISABLE"); disabled != "" && !p.Force { + return &CheckResponse{}, nil + } + + // Set a default timeout of 3 sec for the check request (in milliseconds) + timeout := 3000 + if _, err := strconv.Atoi(os.Getenv("CHECKPOINT_TIMEOUT")); err == nil { + timeout, _ = strconv.Atoi(os.Getenv("CHECKPOINT_TIMEOUT")) + } + + // If we have a cached result, then use that + if r, err := checkCache(p.Version, p.CacheFile, p.CacheDuration); err != nil { + return nil, err + } else if r != nil { + defer r.Close() + return checkResult(r) + } + + var u url.URL + + if p.Arch == "" { + p.Arch = runtime.GOARCH + } + if p.OS == "" { + p.OS = runtime.GOOS + } + + // If we're given a SignatureFile, then attempt to read that. + signature := p.Signature + if p.Signature == "" && p.SignatureFile != "" { + var err error + signature, err = checkSignature(p.SignatureFile) + if err != nil { + return nil, err + } + } + + v := u.Query() + v.Set("version", p.Version) + v.Set("arch", p.Arch) + v.Set("os", p.OS) + v.Set("signature", signature) + + u.Scheme = "https" + u.Host = "checkpoint-api.hashicorp.com" + u.Path = fmt.Sprintf("/v1/check/%s", p.Product) + u.RawQuery = v.Encode() + + req, err := http.NewRequest("GET", u.String(), nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", "HashiCorp/go-checkpoint") + + client := cleanhttp.DefaultClient() + + // We use a short timeout since checking for new versions is not critical + // enough to block on if checkpoint is broken/slow. + client.Timeout = time.Duration(timeout) * time.Millisecond + + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode != 200 { + return nil, fmt.Errorf("Unknown status: %d", resp.StatusCode) + } + + var r io.Reader = resp.Body + if p.CacheFile != "" { + // Make sure the directory holding our cache exists. + if err := os.MkdirAll(filepath.Dir(p.CacheFile), 0755); err != nil { + return nil, err + } + + // We have to cache the result, so write the response to the + // file as we read it. + f, err := os.Create(p.CacheFile) + if err != nil { + return nil, err + } + + // Write the cache header + if err := writeCacheHeader(f, p.Version); err != nil { + f.Close() + os.Remove(p.CacheFile) + return nil, err + } + + defer f.Close() + r = io.TeeReader(r, f) + } + + return checkResult(r) +} + +// CheckInterval is used to check for a response on a given interval duration. +// The interval is not exact, and checks are randomized to prevent a thundering +// herd. However, it is expected that on average one check is performed per +// interval. The returned channel may be closed to stop background checks. +func CheckInterval(p *CheckParams, interval time.Duration, cb func(*CheckResponse, error)) chan struct{} { + doneCh := make(chan struct{}) + + if disabled := os.Getenv("CHECKPOINT_DISABLE"); disabled != "" { + return doneCh + } + + go func() { + for { + select { + case <-time.After(randomStagger(interval)): + resp, err := Check(p) + cb(resp, err) + case <-doneCh: + return + } + } + }() + + return doneCh +} + +// randomStagger returns an interval that is between 3/4 and 5/4 of +// the given interval. The expected value is the interval. +func randomStagger(interval time.Duration) time.Duration { + stagger := time.Duration(mrand.Int63()) % (interval / 2) + return 3*(interval/4) + stagger +} + +func checkCache(current string, path string, d time.Duration) (io.ReadCloser, error) { + fi, err := os.Stat(path) + if err != nil { + if os.IsNotExist(err) { + // File doesn't exist, not a problem + return nil, nil + } + + return nil, err + } + + if d == 0 { + d = 48 * time.Hour + } + + if fi.ModTime().Add(d).Before(time.Now()) { + // Cache is busted, delete the old file and re-request. We ignore + // errors here because re-creating the file is fine too. + os.Remove(path) + return nil, nil + } + + // File looks good so far, open it up so we can inspect the contents. + f, err := os.Open(path) + if err != nil { + return nil, err + } + + // Check the signature of the file + var sig [4]byte + if err := binary.Read(f, binary.LittleEndian, sig[:]); err != nil { + f.Close() + return nil, err + } + if !reflect.DeepEqual(sig, magicBytes) { + // Signatures don't match. Reset. + f.Close() + return nil, nil + } + + // Check the version. If it changed, then rewrite + var length uint32 + if err := binary.Read(f, binary.LittleEndian, &length); err != nil { + f.Close() + return nil, err + } + data := make([]byte, length) + if _, err := io.ReadFull(f, data); err != nil { + f.Close() + return nil, err + } + if string(data) != current { + // Version changed, reset + f.Close() + return nil, nil + } + + return f, nil +} +func checkResult(r io.Reader) (*CheckResponse, error) { + var result CheckResponse + if err := json.NewDecoder(r).Decode(&result); err != nil { + return nil, err + } + return &result, nil +} + +func checkSignature(path string) (string, error) { + _, err := os.Stat(path) + if err == nil { + // The file exists, read it out + sigBytes, err := ioutil.ReadFile(path) + if err != nil { + return "", err + } + + // Split the file into lines + lines := strings.SplitN(string(sigBytes), "\n", 2) + if len(lines) > 0 { + return strings.TrimSpace(lines[0]), nil + } + } + + // If this isn't a non-exist error, then return that. + if !os.IsNotExist(err) { + return "", err + } + + // The file doesn't exist, so create a signature. + var b [16]byte + n := 0 + for n < 16 { + n2, err := crand.Read(b[n:]) + if err != nil { + return "", err + } + + n += n2 + } + signature := fmt.Sprintf( + "%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) + + // Make sure the directory holding our signature exists. + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + return "", err + } + + // Write the signature + if err := ioutil.WriteFile(path, []byte(signature+"\n\n"+userMessage+"\n"), 0644); err != nil { + return "", err + } + + return signature, nil +} + +func writeCacheHeader(f io.Writer, v string) error { + // Write our signature first + if err := binary.Write(f, binary.LittleEndian, magicBytes); err != nil { + return err + } + + // Write out our current version length + length := uint32(len(v)) + if err := binary.Write(f, binary.LittleEndian, length); err != nil { + return err + } + + _, err := f.Write([]byte(v)) + return err +} + +// userMessage is suffixed to the signature file to provide feedback. +var userMessage = ` +This signature is a randomly generated UUID used to de-duplicate +alerts and version information. This signature is random, it is +not based on any personally identifiable information. To create +a new signature, you can simply delete this file at any time. +See the documentation for the software using Checkpoint for more +information on how to disable it. +` diff --git a/vendor/github.com/hashicorp/go-checkpoint/go.mod b/vendor/github.com/hashicorp/go-checkpoint/go.mod new file mode 100644 index 00000000000..be0c793e719 --- /dev/null +++ b/vendor/github.com/hashicorp/go-checkpoint/go.mod @@ -0,0 +1,6 @@ +module github.com/hashicorp/go-checkpoint + +require ( + github.com/hashicorp/go-cleanhttp v0.5.0 + github.com/hashicorp/go-uuid v1.0.0 +) diff --git a/vendor/github.com/hashicorp/go-checkpoint/go.sum b/vendor/github.com/hashicorp/go-checkpoint/go.sum new file mode 100644 index 00000000000..2128a0c8ded --- /dev/null +++ b/vendor/github.com/hashicorp/go-checkpoint/go.sum @@ -0,0 +1,4 @@ +github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-uuid v1.0.0 h1:RS8zrF7PhGwyNPOtxSClXXj9HA8feRnJzgnI1RJCSnM= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= diff --git a/vendor/github.com/hashicorp/go-checkpoint/telemetry.go b/vendor/github.com/hashicorp/go-checkpoint/telemetry.go new file mode 100644 index 00000000000..b9ee62983c2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-checkpoint/telemetry.go @@ -0,0 +1,118 @@ +package checkpoint + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "os" + "runtime" + "time" + + "github.com/hashicorp/go-cleanhttp" + uuid "github.com/hashicorp/go-uuid" +) + +// ReportParams are the parameters for configuring a telemetry report. +type ReportParams struct { + // Signature is some random signature that should be stored and used + // as a cookie-like value. This ensures that alerts aren't repeated. + // If the signature is changed, repeat alerts may be sent down. The + // signature should NOT be anything identifiable to a user (such as + // a MAC address). It should be random. + // + // If SignatureFile is given, then the signature will be read from this + // file. If the file doesn't exist, then a random signature will + // automatically be generated and stored here. SignatureFile will be + // ignored if Signature is given. + Signature string `json:"signature"` + SignatureFile string `json:"-"` + + StartTime time.Time `json:"start_time"` + EndTime time.Time `json:"end_time"` + Arch string `json:"arch"` + OS string `json:"os"` + Payload interface{} `json:"payload,omitempty"` + Product string `json:"product"` + RunID string `json:"run_id"` + SchemaVersion string `json:"schema_version"` + Version string `json:"version"` +} + +func (i *ReportParams) signature() string { + signature := i.Signature + if i.Signature == "" && i.SignatureFile != "" { + var err error + signature, err = checkSignature(i.SignatureFile) + if err != nil { + return "" + } + } + return signature +} + +// Report sends telemetry information to checkpoint +func Report(ctx context.Context, r *ReportParams) error { + if disabled := os.Getenv("CHECKPOINT_DISABLE"); disabled != "" { + return nil + } + + req, err := ReportRequest(r) + if err != nil { + return err + } + + client := cleanhttp.DefaultClient() + resp, err := client.Do(req.WithContext(ctx)) + if err != nil { + return err + } + if resp.StatusCode != 201 { + return fmt.Errorf("Unknown status: %d", resp.StatusCode) + } + + return nil +} + +// ReportRequest creates a request object for making a report +func ReportRequest(r *ReportParams) (*http.Request, error) { + // Populate some fields automatically if we can + if r.RunID == "" { + uuid, err := uuid.GenerateUUID() + if err != nil { + return nil, err + } + r.RunID = uuid + } + if r.Arch == "" { + r.Arch = runtime.GOARCH + } + if r.OS == "" { + r.OS = runtime.GOOS + } + if r.Signature == "" { + r.Signature = r.signature() + } + + b, err := json.Marshal(r) + if err != nil { + return nil, err + } + + u := &url.URL{ + Scheme: "https", + Host: "checkpoint-api.hashicorp.com", + Path: fmt.Sprintf("/v1/telemetry/%s", r.Product), + } + + req, err := http.NewRequest("POST", u.String(), bytes.NewReader(b)) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", "HashiCorp/go-checkpoint") + + return req, nil +} diff --git a/vendor/github.com/hashicorp/go-checkpoint/versions.go b/vendor/github.com/hashicorp/go-checkpoint/versions.go new file mode 100644 index 00000000000..a5b0d3b3231 --- /dev/null +++ b/vendor/github.com/hashicorp/go-checkpoint/versions.go @@ -0,0 +1,90 @@ +package checkpoint + +import ( + "encoding/json" + "fmt" + "net/http" + "net/url" + "os" + "strconv" + "time" + + "github.com/hashicorp/go-cleanhttp" +) + +// VersionsParams are the parameters for a versions request. +type VersionsParams struct { + // Service is used to lookup the correct service. + Service string + + // Product is used to filter the version contraints. + Product string + + // Force, if true, will force the check even if CHECKPOINT_DISABLE + // is set. Within HashiCorp products, this is ONLY USED when the user + // specifically requests it. This is never automatically done without + // the user's consent. + Force bool +} + +// VersionsResponse is the response for a versions request. +type VersionsResponse struct { + Service string `json:"service"` + Product string `json:"product"` + Minimum string `json:"minimum"` + Maximum string `json:"maximum"` + Excluding []string `json:"excluding"` +} + +// Versions returns the version constrains for a given service and product. +func Versions(p *VersionsParams) (*VersionsResponse, error) { + if disabled := os.Getenv("CHECKPOINT_DISABLE"); disabled != "" && !p.Force { + return &VersionsResponse{}, nil + } + + // Set a default timeout of 1 sec for the versions request (in milliseconds) + timeout := 1000 + if _, err := strconv.Atoi(os.Getenv("CHECKPOINT_TIMEOUT")); err == nil { + timeout, _ = strconv.Atoi(os.Getenv("CHECKPOINT_TIMEOUT")) + } + + v := url.Values{} + v.Set("product", p.Product) + + u := &url.URL{ + Scheme: "https", + Host: "checkpoint-api.hashicorp.com", + Path: fmt.Sprintf("/v1/versions/%s", p.Service), + RawQuery: v.Encode(), + } + + req, err := http.NewRequest("GET", u.String(), nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", "HashiCorp/go-checkpoint") + + client := cleanhttp.DefaultClient() + + // We use a short timeout since checking for new versions is not critical + // enough to block on if checkpoint is broken/slow. + client.Timeout = time.Duration(timeout) * time.Millisecond + + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode != 200 { + return nil, fmt.Errorf("Unknown status: %d", resp.StatusCode) + } + + result := &VersionsResponse{} + if err := json.NewDecoder(resp.Body).Decode(result); err != nil { + return nil, err + } + + return result, nil +} diff --git a/vendor/github.com/hashicorp/go-cty/LICENSE b/vendor/github.com/hashicorp/go-cty/LICENSE new file mode 100644 index 00000000000..d6503b55522 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017-2018 Martin Atkins + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/hashicorp/go-cty/cty/capsule.go b/vendor/github.com/hashicorp/go-cty/cty/capsule.go new file mode 100644 index 00000000000..2fdc15eaec1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/capsule.go @@ -0,0 +1,128 @@ +package cty + +import ( + "fmt" + "reflect" +) + +type capsuleType struct { + typeImplSigil + Name string + GoType reflect.Type + Ops *CapsuleOps +} + +func (t *capsuleType) Equals(other Type) bool { + if otherP, ok := other.typeImpl.(*capsuleType); ok { + // capsule types compare by pointer identity + return otherP == t + } + return false +} + +func (t *capsuleType) FriendlyName(mode friendlyTypeNameMode) string { + return t.Name +} + +func (t *capsuleType) GoString() string { + impl := t.Ops.TypeGoString + if impl == nil { + // To get a useful representation of our native type requires some + // shenanigans. + victimVal := reflect.Zero(t.GoType) + if t.Ops == noCapsuleOps { + return fmt.Sprintf("cty.Capsule(%q, reflect.TypeOf(%#v))", t.Name, victimVal.Interface()) + } else { + // Including the operations in the output will make this _very_ long, + // so in practice any capsule type with ops ought to provide a + // TypeGoString function to override this with something more + // reasonable. + return fmt.Sprintf("cty.CapsuleWithOps(%q, reflect.TypeOf(%#v), %#v)", t.Name, victimVal.Interface(), t.Ops) + } + } + return impl(t.GoType) +} + +// Capsule creates a new Capsule type. +// +// A Capsule type is a special type that can be used to transport arbitrary +// Go native values of a given type through the cty type system. A language +// that uses cty as its type system might, for example, provide functions +// that return capsule-typed values and then other functions that operate +// on those values. +// +// From cty's perspective, Capsule types have a few interesting characteristics, +// described in the following paragraphs. +// +// Each capsule type has an associated Go native type that it is able to +// transport. Capsule types compare by identity, so each call to the +// Capsule function creates an entirely-distinct cty Type, even if two calls +// use the same native type. +// +// Each capsule-typed value contains a pointer to a value of the given native +// type. A capsule-typed value by default supports no operations except +// equality, and equality is implemented by pointer identity of the +// encapsulated pointer. A capsule type can optionally have its own +// implementations of certain operations if it is created with CapsuleWithOps +// instead of Capsule. +// +// The given name is used as the new type's "friendly name". This can be any +// string in principle, but will usually be a short, all-lowercase name aimed +// at users of the embedding language (i.e. not mention Go-specific details) +// and will ideally not create ambiguity with any predefined cty type. +// +// Capsule types are never introduced by any standard cty operation, so a +// calling application opts in to including them within its own type system +// by creating them and introducing them via its own functions. At that point, +// the application is responsible for dealing with any capsule-typed values +// that might be returned. +func Capsule(name string, nativeType reflect.Type) Type { + return Type{ + &capsuleType{ + Name: name, + GoType: nativeType, + Ops: noCapsuleOps, + }, + } +} + +// CapsuleWithOps is like Capsule except the caller may provide an object +// representing some overloaded operation implementations to associate with +// the given capsule type. +// +// All of the other caveats and restrictions for capsule types still apply, but +// overloaded operations can potentially help a capsule type participate better +// in cty operations. +func CapsuleWithOps(name string, nativeType reflect.Type, ops *CapsuleOps) Type { + // Copy the operations to make sure the caller can't modify them after + // we're constructed. + ourOps := *ops + ourOps.assertValid() + + return Type{ + &capsuleType{ + Name: name, + GoType: nativeType, + Ops: &ourOps, + }, + } +} + +// IsCapsuleType returns true if this type is a capsule type, as created +// by cty.Capsule . +func (t Type) IsCapsuleType() bool { + _, ok := t.typeImpl.(*capsuleType) + return ok +} + +// EncapsulatedType returns the encapsulated native type of a capsule type, +// or panics if the receiver is not a Capsule type. +// +// Is IsCapsuleType to determine if this method is safe to call. +func (t Type) EncapsulatedType() reflect.Type { + impl, ok := t.typeImpl.(*capsuleType) + if !ok { + panic("not a capsule type") + } + return impl.GoType +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/capsule_ops.go b/vendor/github.com/hashicorp/go-cty/cty/capsule_ops.go new file mode 100644 index 00000000000..3ff6855ecdb --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/capsule_ops.go @@ -0,0 +1,132 @@ +package cty + +import ( + "reflect" +) + +// CapsuleOps represents a set of overloaded operations for a capsule type. +// +// Each field is a reference to a function that can either be nil or can be +// set to an implementation of the corresponding operation. If an operation +// function is nil then it isn't supported for the given capsule type. +type CapsuleOps struct { + // GoString provides the GoString implementation for values of the + // corresponding type. Conventionally this should return a string + // representation of an expression that would produce an equivalent + // value. + GoString func(val interface{}) string + + // TypeGoString provides the GoString implementation for the corresponding + // capsule type itself. + TypeGoString func(goTy reflect.Type) string + + // Equals provides the implementation of the Equals operation. This is + // called only with known, non-null values of the corresponding type, + // but if the corresponding type is a compound type then it must be + // ready to detect and handle nested unknown or null values, usually + // by recursively calling Value.Equals on those nested values. + // + // The result value must always be of type cty.Bool, or the Equals + // operation will panic. + // + // If RawEquals is set without also setting Equals, the RawEquals + // implementation will be used as a fallback implementation. That fallback + // is appropriate only for leaf types that do not contain any nested + // cty.Value that would need to distinguish Equals vs. RawEquals for their + // own equality. + // + // If RawEquals is nil then Equals must also be nil, selecting the default + // pointer-identity comparison instead. + Equals func(a, b interface{}) Value + + // RawEquals provides the implementation of the RawEquals operation. + // This is called only with known, non-null values of the corresponding + // type, but if the corresponding type is a compound type then it must be + // ready to detect and handle nested unknown or null values, usually + // by recursively calling Value.RawEquals on those nested values. + // + // If RawEquals is nil, values of the corresponding type are compared by + // pointer identity of the encapsulated value. + RawEquals func(a, b interface{}) bool + + // ConversionFrom can provide conversions from the corresponding type to + // some other type when values of the corresponding type are used with + // the "convert" package. (The main cty package does not use this operation.) + // + // This function itself returns a function, allowing it to switch its + // behavior depending on the given source type. Return nil to indicate + // that no such conversion is available. + ConversionFrom func(src Type) func(interface{}, Path) (Value, error) + + // ConversionTo can provide conversions to the corresponding type from + // some other type when values of the corresponding type are used with + // the "convert" package. (The main cty package does not use this operation.) + // + // This function itself returns a function, allowing it to switch its + // behavior depending on the given destination type. Return nil to indicate + // that no such conversion is available. + ConversionTo func(dst Type) func(Value, Path) (interface{}, error) + + // ExtensionData is an extension point for applications that wish to + // create their own extension features using capsule types. + // + // The key argument is any value that can be compared with Go's == + // operator, but should be of a named type in a package belonging to the + // application defining the key. An ExtensionData implementation must + // check to see if the given key is familar to it, and if so return a + // suitable value for the key. + // + // If the given key is unrecognized, the ExtensionData function must + // return a nil interface. (Importantly, not an interface containing a nil + // pointer of some other type.) + // The common implementation of ExtensionData is a single switch statement + // over "key" which has a default case returning nil. + // + // The meaning of any given key is entirely up to the application that + // defines it. Applications consuming ExtensionData from capsule types + // should do so defensively: if the result of ExtensionData is not valid, + // prefer to ignore it or gracefully produce an error rather than causing + // a panic. + ExtensionData func(key interface{}) interface{} +} + +// noCapsuleOps is a pointer to a CapsuleOps with no functions set, which +// is used as the default operations value when a type is created using +// the Capsule function. +var noCapsuleOps = &CapsuleOps{} + +func (ops *CapsuleOps) assertValid() { + if ops.RawEquals == nil && ops.Equals != nil { + panic("Equals cannot be set without RawEquals") + } +} + +// CapsuleOps returns a pointer to the CapsuleOps value for a capsule type, +// or panics if the receiver is not a capsule type. +// +// The caller must not modify the CapsuleOps. +func (ty Type) CapsuleOps() *CapsuleOps { + if !ty.IsCapsuleType() { + panic("not a capsule-typed value") + } + + return ty.typeImpl.(*capsuleType).Ops +} + +// CapsuleExtensionData is a convenience interface to the ExtensionData +// function that can be optionally implemented for a capsule type. It will +// check to see if the underlying type implements ExtensionData and call it +// if so. If not, it will return nil to indicate that the given key is not +// supported. +// +// See the documentation for CapsuleOps.ExtensionData for more information +// on the purpose of and usage of this mechanism. +// +// If CapsuleExtensionData is called on a non-capsule type then it will panic. +func (ty Type) CapsuleExtensionData(key interface{}) interface{} { + ops := ty.CapsuleOps() + if ops.ExtensionData == nil { + return nil + } + return ops.ExtensionData(key) +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/collection.go b/vendor/github.com/hashicorp/go-cty/cty/collection.go new file mode 100644 index 00000000000..ab3919b14b7 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/collection.go @@ -0,0 +1,34 @@ +package cty + +import ( + "errors" +) + +type collectionTypeImpl interface { + ElementType() Type +} + +// IsCollectionType returns true if the given type supports the operations +// that are defined for all collection types. +func (t Type) IsCollectionType() bool { + _, ok := t.typeImpl.(collectionTypeImpl) + return ok +} + +// ElementType returns the element type of the receiver if it is a collection +// type, or panics if it is not. Use IsCollectionType first to test whether +// this method will succeed. +func (t Type) ElementType() Type { + if ct, ok := t.typeImpl.(collectionTypeImpl); ok { + return ct.ElementType() + } + panic(errors.New("not a collection type")) +} + +// ElementCallback is a callback type used for iterating over elements of +// collections and attributes of objects. +// +// The types of key and value depend on what type is being iterated over. +// Return true to stop iterating after the current element, or false to +// continue iterating. +type ElementCallback func(key Value, val Value) (stop bool) diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/compare_types.go b/vendor/github.com/hashicorp/go-cty/cty/convert/compare_types.go new file mode 100644 index 00000000000..6ad3bff4542 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/compare_types.go @@ -0,0 +1,165 @@ +package convert + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// compareTypes implements a preference order for unification. +// +// The result of this method is not useful for anything other than unification +// preferences, since it assumes that the caller will verify that any suggested +// conversion is actually possible and it is thus able to to make certain +// optimistic assumptions. +func compareTypes(a cty.Type, b cty.Type) int { + + // DynamicPseudoType always has lowest preference, because anything can + // convert to it (it acts as a placeholder for "any type") and we want + // to optimistically assume that any dynamics will converge on matching + // their neighbors. + if a == cty.DynamicPseudoType || b == cty.DynamicPseudoType { + if a != cty.DynamicPseudoType { + return -1 + } + if b != cty.DynamicPseudoType { + return 1 + } + return 0 + } + + if a.IsPrimitiveType() && b.IsPrimitiveType() { + // String is a supertype of all primitive types, because we can + // represent all primitive values as specially-formatted strings. + if a == cty.String || b == cty.String { + if a != cty.String { + return 1 + } + if b != cty.String { + return -1 + } + return 0 + } + } + + if a.IsListType() && b.IsListType() { + return compareTypes(a.ElementType(), b.ElementType()) + } + if a.IsSetType() && b.IsSetType() { + return compareTypes(a.ElementType(), b.ElementType()) + } + if a.IsMapType() && b.IsMapType() { + return compareTypes(a.ElementType(), b.ElementType()) + } + + // From this point on we may have swapped the two items in order to + // simplify our cases. Therefore any non-zero return after this point + // must be multiplied by "swap" to potentially invert the return value + // if needed. + swap := 1 + switch { + case a.IsTupleType() && b.IsListType(): + fallthrough + case a.IsObjectType() && b.IsMapType(): + fallthrough + case a.IsSetType() && b.IsTupleType(): + fallthrough + case a.IsSetType() && b.IsListType(): + a, b = b, a + swap = -1 + } + + if b.IsSetType() && (a.IsTupleType() || a.IsListType()) { + // We'll just optimistically assume that the element types are + // unifyable/convertible, and let a second recursive pass + // figure out how to make that so. + return -1 * swap + } + + if a.IsListType() && b.IsTupleType() { + // We'll just optimistically assume that the tuple's element types + // can be unified into something compatible with the list's element + // type. + return -1 * swap + } + + if a.IsMapType() && b.IsObjectType() { + // We'll just optimistically assume that the object's attribute types + // can be unified into something compatible with the map's element + // type. + return -1 * swap + } + + // For object and tuple types, comparing two types doesn't really tell + // the whole story because it may be possible to construct a new type C + // that is the supertype of both A and B by unifying each attribute/element + // separately. That possibility is handled by Unify as a follow-up if + // type sorting is insufficient to produce a valid result. + // + // Here we will take care of the simple possibilities where no new type + // is needed. + if a.IsObjectType() && b.IsObjectType() { + atysA := a.AttributeTypes() + atysB := b.AttributeTypes() + + if len(atysA) != len(atysB) { + return 0 + } + + hasASuper := false + hasBSuper := false + for k := range atysA { + if _, has := atysB[k]; !has { + return 0 + } + + cmp := compareTypes(atysA[k], atysB[k]) + if cmp < 0 { + hasASuper = true + } else if cmp > 0 { + hasBSuper = true + } + } + + switch { + case hasASuper && hasBSuper: + return 0 + case hasASuper: + return -1 * swap + case hasBSuper: + return 1 * swap + default: + return 0 + } + } + if a.IsTupleType() && b.IsTupleType() { + etysA := a.TupleElementTypes() + etysB := b.TupleElementTypes() + + if len(etysA) != len(etysB) { + return 0 + } + + hasASuper := false + hasBSuper := false + for i := range etysA { + cmp := compareTypes(etysA[i], etysB[i]) + if cmp < 0 { + hasASuper = true + } else if cmp > 0 { + hasBSuper = true + } + } + + switch { + case hasASuper && hasBSuper: + return 0 + case hasASuper: + return -1 * swap + case hasBSuper: + return 1 * swap + default: + return 0 + } + } + + return 0 +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/conversion.go b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion.go new file mode 100644 index 00000000000..9c59c8f74d0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion.go @@ -0,0 +1,190 @@ +package convert + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// conversion is an internal variant of Conversion that carries around +// a cty.Path to be used in error responses. +type conversion func(cty.Value, cty.Path) (cty.Value, error) + +func getConversion(in cty.Type, out cty.Type, unsafe bool) conversion { + conv := getConversionKnown(in, out, unsafe) + if conv == nil { + return nil + } + + // Wrap the conversion in some standard checks that we don't want to + // have to repeat in every conversion function. + var ret conversion + ret = func(in cty.Value, path cty.Path) (cty.Value, error) { + if in.IsMarked() { + // We must unmark during the conversion and then re-apply the + // same marks to the result. + in, inMarks := in.Unmark() + v, err := ret(in, path) + if v != cty.NilVal { + v = v.WithMarks(inMarks) + } + return v, err + } + + if out == cty.DynamicPseudoType { + // Conversion to DynamicPseudoType always just passes through verbatim. + return in, nil + } + if !in.IsKnown() { + return cty.UnknownVal(out), nil + } + if in.IsNull() { + // We'll pass through nulls, albeit type converted, and let + // the caller deal with whatever handling they want to do in + // case null values are considered valid in some applications. + return cty.NullVal(out), nil + } + + return conv(in, path) + } + + return ret +} + +func getConversionKnown(in cty.Type, out cty.Type, unsafe bool) conversion { + switch { + + case out == cty.DynamicPseudoType: + // Conversion *to* DynamicPseudoType means that the caller wishes + // to allow any type in this position, so we'll produce a do-nothing + // conversion that just passes through the value as-is. + return dynamicPassthrough + + case unsafe && in == cty.DynamicPseudoType: + // Conversion *from* DynamicPseudoType means that we have a value + // whose type isn't yet known during type checking. For these we will + // assume that conversion will succeed and deal with any errors that + // result (which is why we can only do this when "unsafe" is set). + return dynamicFixup(out) + + case in.IsPrimitiveType() && out.IsPrimitiveType(): + conv := primitiveConversionsSafe[in][out] + if conv != nil { + return conv + } + if unsafe { + return primitiveConversionsUnsafe[in][out] + } + return nil + + case out.IsObjectType() && in.IsObjectType(): + return conversionObjectToObject(in, out, unsafe) + + case out.IsTupleType() && in.IsTupleType(): + return conversionTupleToTuple(in, out, unsafe) + + case out.IsListType() && (in.IsListType() || in.IsSetType()): + inEty := in.ElementType() + outEty := out.ElementType() + if inEty.Equals(outEty) { + // This indicates that we're converting from list to set with + // the same element type, so we don't need an element converter. + return conversionCollectionToList(outEty, nil) + } + + convEty := getConversion(inEty, outEty, unsafe) + if convEty == nil { + return nil + } + return conversionCollectionToList(outEty, convEty) + + case out.IsSetType() && (in.IsListType() || in.IsSetType()): + if in.IsListType() && !unsafe { + // Conversion from list to map is unsafe because it will lose + // information: the ordering will not be preserved, and any + // duplicate elements will be conflated. + return nil + } + inEty := in.ElementType() + outEty := out.ElementType() + convEty := getConversion(inEty, outEty, unsafe) + if inEty.Equals(outEty) { + // This indicates that we're converting from set to list with + // the same element type, so we don't need an element converter. + return conversionCollectionToSet(outEty, nil) + } + + if convEty == nil { + return nil + } + return conversionCollectionToSet(outEty, convEty) + + case out.IsMapType() && in.IsMapType(): + inEty := in.ElementType() + outEty := out.ElementType() + convEty := getConversion(inEty, outEty, unsafe) + if convEty == nil { + return nil + } + return conversionCollectionToMap(outEty, convEty) + + case out.IsListType() && in.IsTupleType(): + outEty := out.ElementType() + return conversionTupleToList(in, outEty, unsafe) + + case out.IsSetType() && in.IsTupleType(): + outEty := out.ElementType() + return conversionTupleToSet(in, outEty, unsafe) + + case out.IsMapType() && in.IsObjectType(): + outEty := out.ElementType() + return conversionObjectToMap(in, outEty, unsafe) + + case out.IsObjectType() && in.IsMapType(): + if !unsafe { + // Converting a map to an object is an "unsafe" conversion, + // because we don't know if all the map keys will correspond to + // object attributes. + return nil + } + return conversionMapToObject(in, out, unsafe) + + case in.IsCapsuleType() || out.IsCapsuleType(): + if !unsafe { + // Capsule types can only participate in "unsafe" conversions, + // because we don't know enough about their conversion behaviors + // to be sure that they will always be safe. + return nil + } + if in.Equals(out) { + // conversion to self is never allowed + return nil + } + if out.IsCapsuleType() { + if fn := out.CapsuleOps().ConversionTo; fn != nil { + return conversionToCapsule(in, out, fn) + } + } + if in.IsCapsuleType() { + if fn := in.CapsuleOps().ConversionFrom; fn != nil { + return conversionFromCapsule(in, out, fn) + } + } + // No conversion operation is available, then. + return nil + + default: + return nil + + } +} + +// retConversion wraps a conversion (internal type) so it can be returned +// as a Conversion (public type). +func retConversion(conv conversion) Conversion { + if conv == nil { + return nil + } + + return func(in cty.Value) (cty.Value, error) { + return conv(in, cty.Path(nil)) + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_capsule.go b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_capsule.go new file mode 100644 index 00000000000..6a6006af9e3 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_capsule.go @@ -0,0 +1,31 @@ +package convert + +import ( + "github.com/hashicorp/go-cty/cty" +) + +func conversionToCapsule(inTy, outTy cty.Type, fn func(inTy cty.Type) func(cty.Value, cty.Path) (interface{}, error)) conversion { + rawConv := fn(inTy) + if rawConv == nil { + return nil + } + + return func(in cty.Value, path cty.Path) (cty.Value, error) { + rawV, err := rawConv(in, path) + if err != nil { + return cty.NilVal, err + } + return cty.CapsuleVal(outTy, rawV), nil + } +} + +func conversionFromCapsule(inTy, outTy cty.Type, fn func(outTy cty.Type) func(interface{}, cty.Path) (cty.Value, error)) conversion { + rawConv := fn(outTy) + if rawConv == nil { + return nil + } + + return func(in cty.Value, path cty.Path) (cty.Value, error) { + return rawConv(in.EncapsulatedValue(), path) + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_collection.go b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_collection.go new file mode 100644 index 00000000000..575973d3c33 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_collection.go @@ -0,0 +1,488 @@ +package convert + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// conversionCollectionToList returns a conversion that will apply the given +// conversion to all of the elements of a collection (something that supports +// ForEachElement and LengthInt) and then returns the result as a list. +// +// "conv" can be nil if the elements are expected to already be of the +// correct type and just need to be re-wrapped into a list. (For example, +// if we're converting from a set into a list of the same element type.) +func conversionCollectionToList(ety cty.Type, conv conversion) conversion { + return func(val cty.Value, path cty.Path) (cty.Value, error) { + elems := make([]cty.Value, 0, val.LengthInt()) + i := int64(0) + elemPath := append(path.Copy(), nil) + it := val.ElementIterator() + for it.Next() { + _, val := it.Element() + var err error + + elemPath[len(elemPath)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(i), + } + + if conv != nil { + val, err = conv(val, elemPath) + if err != nil { + return cty.NilVal, err + } + } + elems = append(elems, val) + + i++ + } + + if len(elems) == 0 { + if ety == cty.DynamicPseudoType { + ety = val.Type().ElementType() + } + return cty.ListValEmpty(ety), nil + } + + return cty.ListVal(elems), nil + } +} + +// conversionCollectionToSet returns a conversion that will apply the given +// conversion to all of the elements of a collection (something that supports +// ForEachElement and LengthInt) and then returns the result as a set. +// +// "conv" can be nil if the elements are expected to already be of the +// correct type and just need to be re-wrapped into a set. (For example, +// if we're converting from a list into a set of the same element type.) +func conversionCollectionToSet(ety cty.Type, conv conversion) conversion { + return func(val cty.Value, path cty.Path) (cty.Value, error) { + elems := make([]cty.Value, 0, val.LengthInt()) + i := int64(0) + elemPath := append(path.Copy(), nil) + it := val.ElementIterator() + for it.Next() { + _, val := it.Element() + var err error + + elemPath[len(elemPath)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(i), + } + + if conv != nil { + val, err = conv(val, elemPath) + if err != nil { + return cty.NilVal, err + } + } + elems = append(elems, val) + + i++ + } + + if len(elems) == 0 { + // Prefer a concrete type over a dynamic type when returning an + // empty set + if ety == cty.DynamicPseudoType { + ety = val.Type().ElementType() + } + return cty.SetValEmpty(ety), nil + } + + return cty.SetVal(elems), nil + } +} + +// conversionCollectionToMap returns a conversion that will apply the given +// conversion to all of the elements of a collection (something that supports +// ForEachElement and LengthInt) and then returns the result as a map. +// +// "conv" can be nil if the elements are expected to already be of the +// correct type and just need to be re-wrapped into a map. +func conversionCollectionToMap(ety cty.Type, conv conversion) conversion { + return func(val cty.Value, path cty.Path) (cty.Value, error) { + elems := make(map[string]cty.Value, 0) + elemPath := append(path.Copy(), nil) + it := val.ElementIterator() + for it.Next() { + key, val := it.Element() + var err error + + elemPath[len(elemPath)-1] = cty.IndexStep{ + Key: key, + } + + keyStr, err := Convert(key, cty.String) + if err != nil { + // Should never happen, because keys can only be numbers or + // strings and both can convert to string. + return cty.DynamicVal, elemPath.NewErrorf("cannot convert key type %s to string for map", key.Type().FriendlyName()) + } + + if conv != nil { + val, err = conv(val, elemPath) + if err != nil { + return cty.NilVal, err + } + } + + elems[keyStr.AsString()] = val + } + + if len(elems) == 0 { + // Prefer a concrete type over a dynamic type when returning an + // empty map + if ety == cty.DynamicPseudoType { + ety = val.Type().ElementType() + } + return cty.MapValEmpty(ety), nil + } + + if ety.IsCollectionType() || ety.IsObjectType() { + var err error + if elems, err = conversionUnifyCollectionElements(elems, path, false); err != nil { + return cty.NilVal, err + } + } + + if err := conversionCheckMapElementTypes(elems, path); err != nil { + return cty.NilVal, err + } + + return cty.MapVal(elems), nil + } +} + +// conversionTupleToSet returns a conversion that will take a value of the +// given tuple type and return a set of the given element type. +// +// Will panic if the given tupleType isn't actually a tuple type. +func conversionTupleToSet(tupleType cty.Type, listEty cty.Type, unsafe bool) conversion { + tupleEtys := tupleType.TupleElementTypes() + + if len(tupleEtys) == 0 { + // Empty tuple short-circuit + return func(val cty.Value, path cty.Path) (cty.Value, error) { + return cty.SetValEmpty(listEty), nil + } + } + + if listEty == cty.DynamicPseudoType { + // This is a special case where the caller wants us to find + // a suitable single type that all elements can convert to, if + // possible. + listEty, _ = unify(tupleEtys, unsafe) + if listEty == cty.NilType { + return nil + } + } + + elemConvs := make([]conversion, len(tupleEtys)) + for i, tupleEty := range tupleEtys { + if tupleEty.Equals(listEty) { + // no conversion required + continue + } + + elemConvs[i] = getConversion(tupleEty, listEty, unsafe) + if elemConvs[i] == nil { + // If any of our element conversions are impossible, then the our + // whole conversion is impossible. + return nil + } + } + + // If we fall out here then a conversion is possible, using the + // element conversions in elemConvs + return func(val cty.Value, path cty.Path) (cty.Value, error) { + elems := make([]cty.Value, 0, len(elemConvs)) + elemPath := append(path.Copy(), nil) + i := int64(0) + it := val.ElementIterator() + for it.Next() { + _, val := it.Element() + var err error + + elemPath[len(elemPath)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(i), + } + + conv := elemConvs[i] + if conv != nil { + val, err = conv(val, elemPath) + if err != nil { + return cty.NilVal, err + } + } + elems = append(elems, val) + + i++ + } + + return cty.SetVal(elems), nil + } +} + +// conversionTupleToList returns a conversion that will take a value of the +// given tuple type and return a list of the given element type. +// +// Will panic if the given tupleType isn't actually a tuple type. +func conversionTupleToList(tupleType cty.Type, listEty cty.Type, unsafe bool) conversion { + tupleEtys := tupleType.TupleElementTypes() + + if len(tupleEtys) == 0 { + // Empty tuple short-circuit + return func(val cty.Value, path cty.Path) (cty.Value, error) { + return cty.ListValEmpty(listEty), nil + } + } + + if listEty == cty.DynamicPseudoType { + // This is a special case where the caller wants us to find + // a suitable single type that all elements can convert to, if + // possible. + listEty, _ = unify(tupleEtys, unsafe) + if listEty == cty.NilType { + return nil + } + } + + elemConvs := make([]conversion, len(tupleEtys)) + for i, tupleEty := range tupleEtys { + if tupleEty.Equals(listEty) { + // no conversion required + continue + } + + elemConvs[i] = getConversion(tupleEty, listEty, unsafe) + if elemConvs[i] == nil { + // If any of our element conversions are impossible, then the our + // whole conversion is impossible. + return nil + } + } + + // If we fall out here then a conversion is possible, using the + // element conversions in elemConvs + return func(val cty.Value, path cty.Path) (cty.Value, error) { + elems := make([]cty.Value, 0, len(elemConvs)) + elemPath := append(path.Copy(), nil) + i := int64(0) + it := val.ElementIterator() + for it.Next() { + _, val := it.Element() + var err error + + elemPath[len(elemPath)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(i), + } + + conv := elemConvs[i] + if conv != nil { + val, err = conv(val, elemPath) + if err != nil { + return cty.NilVal, err + } + } + elems = append(elems, val) + + i++ + } + + return cty.ListVal(elems), nil + } +} + +// conversionObjectToMap returns a conversion that will take a value of the +// given object type and return a map of the given element type. +// +// Will panic if the given objectType isn't actually an object type. +func conversionObjectToMap(objectType cty.Type, mapEty cty.Type, unsafe bool) conversion { + objectAtys := objectType.AttributeTypes() + + if len(objectAtys) == 0 { + // Empty object short-circuit + return func(val cty.Value, path cty.Path) (cty.Value, error) { + return cty.MapValEmpty(mapEty), nil + } + } + + if mapEty == cty.DynamicPseudoType { + // This is a special case where the caller wants us to find + // a suitable single type that all elements can convert to, if + // possible. + objectAtysList := make([]cty.Type, 0, len(objectAtys)) + for _, aty := range objectAtys { + objectAtysList = append(objectAtysList, aty) + } + mapEty, _ = unify(objectAtysList, unsafe) + if mapEty == cty.NilType { + return nil + } + } + + elemConvs := make(map[string]conversion, len(objectAtys)) + for name, objectAty := range objectAtys { + if objectAty.Equals(mapEty) { + // no conversion required + continue + } + + elemConvs[name] = getConversion(objectAty, mapEty, unsafe) + if elemConvs[name] == nil { + // If any of our element conversions are impossible, then the our + // whole conversion is impossible. + return nil + } + } + + // If we fall out here then a conversion is possible, using the + // element conversions in elemConvs + return func(val cty.Value, path cty.Path) (cty.Value, error) { + elems := make(map[string]cty.Value, len(elemConvs)) + elemPath := append(path.Copy(), nil) + it := val.ElementIterator() + for it.Next() { + name, val := it.Element() + var err error + + elemPath[len(elemPath)-1] = cty.IndexStep{ + Key: name, + } + + conv := elemConvs[name.AsString()] + if conv != nil { + val, err = conv(val, elemPath) + if err != nil { + return cty.NilVal, err + } + } + elems[name.AsString()] = val + } + + if mapEty.IsCollectionType() || mapEty.IsObjectType() { + var err error + if elems, err = conversionUnifyCollectionElements(elems, path, unsafe); err != nil { + return cty.NilVal, err + } + } + + if err := conversionCheckMapElementTypes(elems, path); err != nil { + return cty.NilVal, err + } + + return cty.MapVal(elems), nil + } +} + +// conversionMapToObject returns a conversion that will take a value of the +// given map type and return an object of the given type. The object attribute +// types must all be compatible with the map element type. +// +// Will panic if the given mapType and objType are not maps and objects +// respectively. +func conversionMapToObject(mapType cty.Type, objType cty.Type, unsafe bool) conversion { + objectAtys := objType.AttributeTypes() + mapEty := mapType.ElementType() + + elemConvs := make(map[string]conversion, len(objectAtys)) + for name, objectAty := range objectAtys { + if objectAty.Equals(mapEty) { + // no conversion required + continue + } + + elemConvs[name] = getConversion(mapEty, objectAty, unsafe) + if elemConvs[name] == nil { + // If any of our element conversions are impossible, then the our + // whole conversion is impossible. + return nil + } + } + + // If we fall out here then a conversion is possible, using the + // element conversions in elemConvs + return func(val cty.Value, path cty.Path) (cty.Value, error) { + elems := make(map[string]cty.Value, len(elemConvs)) + elemPath := append(path.Copy(), nil) + it := val.ElementIterator() + for it.Next() { + name, val := it.Element() + + // if there is no corresponding attribute, we skip this key + if _, ok := objectAtys[name.AsString()]; !ok { + continue + } + + var err error + + elemPath[len(elemPath)-1] = cty.IndexStep{ + Key: name, + } + + conv := elemConvs[name.AsString()] + if conv != nil { + val, err = conv(val, elemPath) + if err != nil { + return cty.NilVal, err + } + } + + elems[name.AsString()] = val + } + + return cty.ObjectVal(elems), nil + } +} + +func conversionUnifyCollectionElements(elems map[string]cty.Value, path cty.Path, unsafe bool) (map[string]cty.Value, error) { + elemTypes := make([]cty.Type, 0, len(elems)) + for _, elem := range elems { + elemTypes = append(elemTypes, elem.Type()) + } + unifiedType, _ := unify(elemTypes, unsafe) + if unifiedType == cty.NilType { + } + + unifiedElems := make(map[string]cty.Value) + elemPath := append(path.Copy(), nil) + + for name, elem := range elems { + if elem.Type().Equals(unifiedType) { + unifiedElems[name] = elem + continue + } + conv := getConversion(elem.Type(), unifiedType, unsafe) + if conv == nil { + } + elemPath[len(elemPath)-1] = cty.IndexStep{ + Key: cty.StringVal(name), + } + val, err := conv(elem, elemPath) + if err != nil { + return nil, err + } + unifiedElems[name] = val + } + + return unifiedElems, nil +} + +func conversionCheckMapElementTypes(elems map[string]cty.Value, path cty.Path) error { + elementType := cty.NilType + elemPath := append(path.Copy(), nil) + + for name, elem := range elems { + if elementType == cty.NilType { + elementType = elem.Type() + continue + } + if !elementType.Equals(elem.Type()) { + elemPath[len(elemPath)-1] = cty.IndexStep{ + Key: cty.StringVal(name), + } + return elemPath.NewErrorf("%s is required", elementType.FriendlyName()) + } + } + + return nil +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_dynamic.go b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_dynamic.go new file mode 100644 index 00000000000..5f571da13c4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_dynamic.go @@ -0,0 +1,33 @@ +package convert + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// dynamicFixup deals with just-in-time conversions of values that were +// input-typed as cty.DynamicPseudoType during analysis, ensuring that +// we end up with the desired output type once the value is known, or +// failing with an error if that is not possible. +// +// This is in the spirit of the cty philosophy of optimistically assuming that +// DynamicPseudoType values will become the intended value eventually, and +// dealing with any inconsistencies during final evaluation. +func dynamicFixup(wantType cty.Type) conversion { + return func(in cty.Value, path cty.Path) (cty.Value, error) { + ret, err := Convert(in, wantType) + if err != nil { + // Re-wrap this error so that the returned path is relative + // to the caller's original value, rather than relative to our + // conversion value here. + return cty.NilVal, path.NewError(err) + } + return ret, nil + } +} + +// dynamicPassthrough is an identity conversion that is used when the +// target type is DynamicPseudoType, indicating that the caller doesn't care +// which type is returned. +func dynamicPassthrough(in cty.Value, path cty.Path) (cty.Value, error) { + return in, nil +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_object.go b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_object.go new file mode 100644 index 00000000000..93743ca82f0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_object.go @@ -0,0 +1,76 @@ +package convert + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// conversionObjectToObject returns a conversion that will make the input +// object type conform to the output object type, if possible. +// +// Conversion is possible only if the output type is a subset of the input +// type, meaning that each attribute of the output type has a corresponding +// attribute in the input type where a recursive conversion is available. +// +// Shallow object conversions work the same for both safe and unsafe modes, +// but the safety flag is passed on to recursive conversions and may thus +// limit the above definition of "subset". +func conversionObjectToObject(in, out cty.Type, unsafe bool) conversion { + inAtys := in.AttributeTypes() + outAtys := out.AttributeTypes() + attrConvs := make(map[string]conversion) + + for name, outAty := range outAtys { + inAty, exists := inAtys[name] + if !exists { + // No conversion is available, then. + return nil + } + + if inAty.Equals(outAty) { + // No conversion needed, but we'll still record the attribute + // in our map for later reference. + attrConvs[name] = nil + continue + } + + attrConvs[name] = getConversion(inAty, outAty, unsafe) + if attrConvs[name] == nil { + // If a recursive conversion isn't available, then our top-level + // configuration is impossible too. + return nil + } + } + + // If we get here then a conversion is possible, using the attribute + // conversions given in attrConvs. + return func(val cty.Value, path cty.Path) (cty.Value, error) { + attrVals := make(map[string]cty.Value, len(attrConvs)) + path = append(path, nil) + pathStep := &path[len(path)-1] + + for it := val.ElementIterator(); it.Next(); { + nameVal, val := it.Element() + var err error + + name := nameVal.AsString() + *pathStep = cty.GetAttrStep{ + Name: name, + } + + conv, exists := attrConvs[name] + if !exists { + continue + } + if conv != nil { + val, err = conv(val, path) + if err != nil { + return cty.NilVal, err + } + } + + attrVals[name] = val + } + + return cty.ObjectVal(attrVals), nil + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_primitive.go b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_primitive.go new file mode 100644 index 00000000000..a55344413e2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_primitive.go @@ -0,0 +1,57 @@ +package convert + +import ( + "strings" + + "github.com/hashicorp/go-cty/cty" +) + +var stringTrue = cty.StringVal("true") +var stringFalse = cty.StringVal("false") + +var primitiveConversionsSafe = map[cty.Type]map[cty.Type]conversion{ + cty.Number: { + cty.String: func(val cty.Value, path cty.Path) (cty.Value, error) { + f := val.AsBigFloat() + return cty.StringVal(f.Text('f', -1)), nil + }, + }, + cty.Bool: { + cty.String: func(val cty.Value, path cty.Path) (cty.Value, error) { + if val.True() { + return stringTrue, nil + } else { + return stringFalse, nil + } + }, + }, +} + +var primitiveConversionsUnsafe = map[cty.Type]map[cty.Type]conversion{ + cty.String: { + cty.Number: func(val cty.Value, path cty.Path) (cty.Value, error) { + v, err := cty.ParseNumberVal(val.AsString()) + if err != nil { + return cty.NilVal, path.NewErrorf("a number is required") + } + return v, nil + }, + cty.Bool: func(val cty.Value, path cty.Path) (cty.Value, error) { + switch val.AsString() { + case "true", "1": + return cty.True, nil + case "false", "0": + return cty.False, nil + default: + switch strings.ToLower(val.AsString()) { + case "true": + return cty.NilVal, path.NewErrorf("a bool is required; to convert from string, use lowercase \"true\"") + case "false": + return cty.NilVal, path.NewErrorf("a bool is required; to convert from string, use lowercase \"false\"") + default: + return cty.NilVal, path.NewErrorf("a bool is required") + } + } + }, + }, +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_tuple.go b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_tuple.go new file mode 100644 index 00000000000..d89ec3808b9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/conversion_tuple.go @@ -0,0 +1,71 @@ +package convert + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// conversionTupleToTuple returns a conversion that will make the input +// tuple type conform to the output tuple type, if possible. +// +// Conversion is possible only if the two tuple types have the same number +// of elements and the corresponding elements by index can be converted. +// +// Shallow tuple conversions work the same for both safe and unsafe modes, +// but the safety flag is passed on to recursive conversions and may thus +// limit which element type conversions are possible. +func conversionTupleToTuple(in, out cty.Type, unsafe bool) conversion { + inEtys := in.TupleElementTypes() + outEtys := out.TupleElementTypes() + + if len(inEtys) != len(outEtys) { + return nil // no conversion is possible + } + + elemConvs := make([]conversion, len(inEtys)) + + for i, outEty := range outEtys { + inEty := inEtys[i] + + if inEty.Equals(outEty) { + // No conversion needed, so we can leave this one nil. + continue + } + + elemConvs[i] = getConversion(inEty, outEty, unsafe) + if elemConvs[i] == nil { + // If a recursive conversion isn't available, then our top-level + // configuration is impossible too. + return nil + } + } + + // If we get here then a conversion is possible, using the element + // conversions given in elemConvs. + return func(val cty.Value, path cty.Path) (cty.Value, error) { + elemVals := make([]cty.Value, len(elemConvs)) + path = append(path, nil) + pathStep := &path[len(path)-1] + + i := 0 + for it := val.ElementIterator(); it.Next(); i++ { + _, val := it.Element() + var err error + + *pathStep = cty.IndexStep{ + Key: cty.NumberIntVal(int64(i)), + } + + conv := elemConvs[i] + if conv != nil { + val, err = conv(val, path) + if err != nil { + return cty.NilVal, err + } + } + + elemVals[i] = val + } + + return cty.TupleVal(elemVals), nil + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/doc.go b/vendor/github.com/hashicorp/go-cty/cty/convert/doc.go new file mode 100644 index 00000000000..2037299bab4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/doc.go @@ -0,0 +1,15 @@ +// Package convert contains some routines for converting between cty types. +// The intent of providing this package is to encourage applications using +// cty to have consistent type conversion behavior for maximal interoperability +// when Values pass from one application to another. +// +// The conversions are categorized into two categories. "Safe" conversions are +// ones that are guaranteed to succeed if given a non-null value of the +// appropriate source type. "Unsafe" conversions, on the other hand, are valid +// for only a subset of input values, and thus may fail with an error when +// called for values outside of that valid subset. +// +// The functions whose names end in Unsafe support all of the conversions that +// are supported by the corresponding functions whose names do not have that +// suffix, and then additional unsafe conversions as well. +package convert diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/mismatch_msg.go b/vendor/github.com/hashicorp/go-cty/cty/convert/mismatch_msg.go new file mode 100644 index 00000000000..72f307f2078 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/mismatch_msg.go @@ -0,0 +1,220 @@ +package convert + +import ( + "bytes" + "fmt" + "sort" + + "github.com/hashicorp/go-cty/cty" +) + +// MismatchMessage is a helper to return an English-language description of +// the differences between got and want, phrased as a reason why got does +// not conform to want. +// +// This function does not itself attempt conversion, and so it should generally +// be used only after a conversion has failed, to report the conversion failure +// to an English-speaking user. The result will be confusing got is actually +// conforming to or convertable to want. +// +// The shorthand helper function Convert uses this function internally to +// produce its error messages, so callers of that function do not need to +// also use MismatchMessage. +// +// This function is similar to Type.TestConformance, but it is tailored to +// describing conversion failures and so the messages it generates relate +// specifically to the conversion rules implemented in this package. +func MismatchMessage(got, want cty.Type) string { + switch { + + case got.IsObjectType() && want.IsObjectType(): + // If both types are object types then we may be able to say something + // about their respective attributes. + return mismatchMessageObjects(got, want) + + case got.IsTupleType() && want.IsListType() && want.ElementType() == cty.DynamicPseudoType: + // If conversion from tuple to list failed then it's because we couldn't + // find a common type to convert all of the tuple elements to. + return "all list elements must have the same type" + + case got.IsTupleType() && want.IsSetType() && want.ElementType() == cty.DynamicPseudoType: + // If conversion from tuple to set failed then it's because we couldn't + // find a common type to convert all of the tuple elements to. + return "all set elements must have the same type" + + case got.IsObjectType() && want.IsMapType() && want.ElementType() == cty.DynamicPseudoType: + // If conversion from object to map failed then it's because we couldn't + // find a common type to convert all of the object attributes to. + return "all map elements must have the same type" + + case (got.IsTupleType() || got.IsObjectType()) && want.IsCollectionType(): + return mismatchMessageCollectionsFromStructural(got, want) + + case got.IsCollectionType() && want.IsCollectionType(): + return mismatchMessageCollectionsFromCollections(got, want) + + default: + // If we have nothing better to say, we'll just state what was required. + return want.FriendlyNameForConstraint() + " required" + } +} + +func mismatchMessageObjects(got, want cty.Type) string { + // Per our conversion rules, "got" is allowed to be a superset of "want", + // and so we'll produce error messages here under that assumption. + gotAtys := got.AttributeTypes() + wantAtys := want.AttributeTypes() + + // If we find missing attributes then we'll report those in preference, + // but if not then we will report a maximum of one non-conforming + // attribute, just to keep our messages relatively terse. + // We'll also prefer to report a recursive type error from an _unsafe_ + // conversion over a safe one, because these are subjectively more + // "serious". + var missingAttrs []string + var unsafeMismatchAttr string + var safeMismatchAttr string + + for name, wantAty := range wantAtys { + gotAty, exists := gotAtys[name] + if !exists { + missingAttrs = append(missingAttrs, name) + continue + } + + // We'll now try to convert these attributes in isolation and + // see if we have a nested conversion error to report. + // We'll try an unsafe conversion first, and then fall back on + // safe if unsafe is possible. + + // If we already have an unsafe mismatch attr error then we won't bother + // hunting for another one. + if unsafeMismatchAttr != "" { + continue + } + if conv := GetConversionUnsafe(gotAty, wantAty); conv == nil { + unsafeMismatchAttr = fmt.Sprintf("attribute %q: %s", name, MismatchMessage(gotAty, wantAty)) + } + + // If we already have a safe mismatch attr error then we won't bother + // hunting for another one. + if safeMismatchAttr != "" { + continue + } + if conv := GetConversion(gotAty, wantAty); conv == nil { + safeMismatchAttr = fmt.Sprintf("attribute %q: %s", name, MismatchMessage(gotAty, wantAty)) + } + } + + // We should now have collected at least one problem. If we have more than + // one then we'll use our preference order to decide what is most important + // to report. + switch { + + case len(missingAttrs) != 0: + sort.Strings(missingAttrs) + switch len(missingAttrs) { + case 1: + return fmt.Sprintf("attribute %q is required", missingAttrs[0]) + case 2: + return fmt.Sprintf("attributes %q and %q are required", missingAttrs[0], missingAttrs[1]) + default: + sort.Strings(missingAttrs) + var buf bytes.Buffer + for _, name := range missingAttrs[:len(missingAttrs)-1] { + fmt.Fprintf(&buf, "%q, ", name) + } + fmt.Fprintf(&buf, "and %q", missingAttrs[len(missingAttrs)-1]) + return fmt.Sprintf("attributes %s are required", buf.Bytes()) + } + + case unsafeMismatchAttr != "": + return unsafeMismatchAttr + + case safeMismatchAttr != "": + return safeMismatchAttr + + default: + // We should never get here, but if we do then we'll return + // just a generic message. + return "incorrect object attributes" + } +} + +func mismatchMessageCollectionsFromStructural(got, want cty.Type) string { + // First some straightforward cases where the kind is just altogether wrong. + switch { + case want.IsListType() && !got.IsTupleType(): + return want.FriendlyNameForConstraint() + " required" + case want.IsSetType() && !got.IsTupleType(): + return want.FriendlyNameForConstraint() + " required" + case want.IsMapType() && !got.IsObjectType(): + return want.FriendlyNameForConstraint() + " required" + } + + // If the kinds are matched well enough then we'll move on to checking + // individual elements. + wantEty := want.ElementType() + switch { + case got.IsTupleType(): + for i, gotEty := range got.TupleElementTypes() { + if gotEty.Equals(wantEty) { + continue // exact match, so no problem + } + if conv := getConversion(gotEty, wantEty, true); conv != nil { + continue // conversion is available, so no problem + } + return fmt.Sprintf("element %d: %s", i, MismatchMessage(gotEty, wantEty)) + } + + // If we get down here then something weird is going on but we'll + // return a reasonable fallback message anyway. + return fmt.Sprintf("all elements must be %s", wantEty.FriendlyNameForConstraint()) + + case got.IsObjectType(): + for name, gotAty := range got.AttributeTypes() { + if gotAty.Equals(wantEty) { + continue // exact match, so no problem + } + if conv := getConversion(gotAty, wantEty, true); conv != nil { + continue // conversion is available, so no problem + } + return fmt.Sprintf("element %q: %s", name, MismatchMessage(gotAty, wantEty)) + } + + // If we get down here then something weird is going on but we'll + // return a reasonable fallback message anyway. + return fmt.Sprintf("all elements must be %s", wantEty.FriendlyNameForConstraint()) + + default: + // Should not be possible to get here since we only call this function + // with got as structural types, but... + return want.FriendlyNameForConstraint() + " required" + } +} + +func mismatchMessageCollectionsFromCollections(got, want cty.Type) string { + // First some straightforward cases where the kind is just altogether wrong. + switch { + case want.IsListType() && !(got.IsListType() || got.IsSetType()): + return want.FriendlyNameForConstraint() + " required" + case want.IsSetType() && !(got.IsListType() || got.IsSetType()): + return want.FriendlyNameForConstraint() + " required" + case want.IsMapType() && !got.IsMapType(): + return want.FriendlyNameForConstraint() + " required" + } + + // If the kinds are matched well enough then we'll check the element types. + gotEty := got.ElementType() + wantEty := want.ElementType() + noun := "element type" + switch { + case want.IsListType(): + noun = "list element type" + case want.IsSetType(): + noun = "set element type" + case want.IsMapType(): + noun = "map element type" + } + return fmt.Sprintf("incorrect %s: %s", noun, MismatchMessage(gotEty, wantEty)) +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/public.go b/vendor/github.com/hashicorp/go-cty/cty/convert/public.go new file mode 100644 index 00000000000..3b50a692641 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/public.go @@ -0,0 +1,83 @@ +package convert + +import ( + "errors" + + "github.com/hashicorp/go-cty/cty" +) + +// This file contains the public interface of this package, which is intended +// to be a small, convenient interface designed for easy integration into +// a hypothetical language type checker and interpreter. + +// Conversion is a named function type representing a conversion from a +// value of one type to a value of another type. +// +// The source type for a conversion is always the source type given to +// the function that returned the Conversion, but there is no way to recover +// that from a Conversion value itself. If a Conversion is given a value +// that is not of its expected type (with the exception of DynamicPseudoType, +// which is always supported) then the function may panic or produce undefined +// results. +type Conversion func(in cty.Value) (out cty.Value, err error) + +// GetConversion returns a Conversion between the given in and out Types if +// a safe one is available, or returns nil otherwise. +func GetConversion(in cty.Type, out cty.Type) Conversion { + return retConversion(getConversion(in, out, false)) +} + +// GetConversionUnsafe returns a Conversion between the given in and out Types +// if either a safe or unsafe one is available, or returns nil otherwise. +func GetConversionUnsafe(in cty.Type, out cty.Type) Conversion { + return retConversion(getConversion(in, out, true)) +} + +// Convert returns the result of converting the given value to the given type +// if an safe or unsafe conversion is available, or returns an error if such a +// conversion is impossible. +// +// This is a convenience wrapper around calling GetConversionUnsafe and then +// immediately passing the given value to the resulting function. +func Convert(in cty.Value, want cty.Type) (cty.Value, error) { + if in.Type().Equals(want) { + return in, nil + } + + conv := GetConversionUnsafe(in.Type(), want) + if conv == nil { + return cty.NilVal, errors.New(MismatchMessage(in.Type(), want)) + } + return conv(in) +} + +// Unify attempts to find the most general type that can be converted from +// all of the given types. If this is possible, that type is returned along +// with a slice of necessary conversions for some of the given types. +// +// If no common supertype can be found, this function returns cty.NilType and +// a nil slice. +// +// If a common supertype *can* be found, the returned slice will always be +// non-nil and will contain a non-nil conversion for each given type that +// needs to be converted, with indices corresponding to the input slice. +// Any given type that does *not* need conversion (because it is already of +// the appropriate type) will have a nil Conversion. +// +// cty.DynamicPseudoType is, as usual, a special case. If the given type list +// contains a mixture of dynamic and non-dynamic types, the dynamic types are +// disregarded for type selection and a conversion is returned for them that +// will attempt a late conversion of the given value to the target type, +// failing with a conversion error if the eventual concrete type is not +// compatible. If *all* given types are DynamicPseudoType, or in the +// degenerate case of an empty slice of types, the returned type is itself +// cty.DynamicPseudoType and no conversions are attempted. +func Unify(types []cty.Type) (cty.Type, []Conversion) { + return unify(types, false) +} + +// UnifyUnsafe is the same as Unify except that it may return unsafe +// conversions in situations where a safe conversion isn't also available. +func UnifyUnsafe(types []cty.Type) (cty.Type, []Conversion) { + return unify(types, true) +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/sort_types.go b/vendor/github.com/hashicorp/go-cty/cty/convert/sort_types.go new file mode 100644 index 00000000000..8a9c327668a --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/sort_types.go @@ -0,0 +1,69 @@ +package convert + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// sortTypes produces an ordering of the given types that serves as a +// preference order for the result of unification of the given types. +// The return value is a slice of indices into the given slice, and will +// thus always be the same length as the given slice. +// +// The goal is that the most general of the given types will appear first +// in the ordering. If there are uncomparable pairs of types in the list +// then they will appear in an undefined order, and the unification pass +// will presumably then fail. +func sortTypes(tys []cty.Type) []int { + l := len(tys) + + // First we build a graph whose edges represent "more general than", + // which we will then do a topological sort of. + edges := make([][]int, l) + for i := 0; i < (l - 1); i++ { + for j := i + 1; j < l; j++ { + cmp := compareTypes(tys[i], tys[j]) + switch { + case cmp < 0: + edges[i] = append(edges[i], j) + case cmp > 0: + edges[j] = append(edges[j], i) + } + } + } + + // Compute the in-degree of each node + inDegree := make([]int, l) + for _, outs := range edges { + for _, j := range outs { + inDegree[j]++ + } + } + + // The array backing our result will double as our queue for visiting + // the nodes, with the queue slice moving along this array until it + // is empty and positioned at the end of the array. Thus our visiting + // order is also our result order. + result := make([]int, l) + queue := result[0:0] + + // Initialize the queue with any item of in-degree 0, preserving + // their relative order. + for i, n := range inDegree { + if n == 0 { + queue = append(queue, i) + } + } + + for len(queue) != 0 { + i := queue[0] + queue = queue[1:] + for _, j := range edges[i] { + inDegree[j]-- + if inDegree[j] == 0 { + queue = append(queue, j) + } + } + } + + return result +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/convert/unify.go b/vendor/github.com/hashicorp/go-cty/cty/convert/unify.go new file mode 100644 index 00000000000..b2a3bbe54e4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/convert/unify.go @@ -0,0 +1,357 @@ +package convert + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// The current unify implementation is somewhat inefficient, but we accept this +// under the assumption that it will generally be used with small numbers of +// types and with types of reasonable complexity. However, it does have a +// "happy path" where all of the given types are equal. +// +// This function is likely to have poor performance in cases where any given +// types are very complex (lots of deeply-nested structures) or if the list +// of types itself is very large. In particular, it will walk the nested type +// structure under the given types several times, especially when given a +// list of types for which unification is not possible, since each permutation +// will be tried to determine that result. +func unify(types []cty.Type, unsafe bool) (cty.Type, []Conversion) { + if len(types) == 0 { + // Degenerate case + return cty.NilType, nil + } + + // If all of the given types are of the same structural kind, we may be + // able to construct a new type that they can all be unified to, even if + // that is not one of the given types. We must try this before the general + // behavior below because in unsafe mode we can convert an object type to + // a subset of that type, which would be a much less useful conversion for + // unification purposes. + { + mapCt := 0 + objectCt := 0 + tupleCt := 0 + dynamicCt := 0 + for _, ty := range types { + switch { + case ty.IsMapType(): + mapCt++ + case ty.IsObjectType(): + objectCt++ + case ty.IsTupleType(): + tupleCt++ + case ty == cty.DynamicPseudoType: + dynamicCt++ + default: + break + } + } + switch { + case mapCt > 0 && (mapCt+dynamicCt) == len(types): + return unifyMapTypes(types, unsafe, dynamicCt > 0) + case objectCt > 0 && (objectCt+dynamicCt) == len(types): + return unifyObjectTypes(types, unsafe, dynamicCt > 0) + case tupleCt > 0 && (tupleCt+dynamicCt) == len(types): + return unifyTupleTypes(types, unsafe, dynamicCt > 0) + case objectCt > 0 && tupleCt > 0: + // Can never unify object and tuple types since they have incompatible kinds + return cty.NilType, nil + } + } + + prefOrder := sortTypes(types) + + // sortTypes gives us an order where earlier items are preferable as + // our result type. We'll now walk through these and choose the first + // one we encounter for which conversions exist for all source types. + conversions := make([]Conversion, len(types)) +Preferences: + for _, wantTypeIdx := range prefOrder { + wantType := types[wantTypeIdx] + for i, tryType := range types { + if i == wantTypeIdx { + // Don't need to convert our wanted type to itself + conversions[i] = nil + continue + } + + if tryType.Equals(wantType) { + conversions[i] = nil + continue + } + + if unsafe { + conversions[i] = GetConversionUnsafe(tryType, wantType) + } else { + conversions[i] = GetConversion(tryType, wantType) + } + + if conversions[i] == nil { + // wantType is not a suitable unification type, so we'll + // try the next one in our preference order. + continue Preferences + } + } + + return wantType, conversions + } + + // If we fall out here, no unification is possible + return cty.NilType, nil +} + +func unifyMapTypes(types []cty.Type, unsafe bool, hasDynamic bool) (cty.Type, []Conversion) { + // If we had any dynamic types in the input here then we can't predict + // what path we'll take through here once these become known types, so + // we'll conservatively produce DynamicVal for these. + if hasDynamic { + return unifyAllAsDynamic(types) + } + + elemTypes := make([]cty.Type, 0, len(types)) + for _, ty := range types { + elemTypes = append(elemTypes, ty.ElementType()) + } + retElemType, _ := unify(elemTypes, unsafe) + if retElemType == cty.NilType { + return cty.NilType, nil + } + + retTy := cty.Map(retElemType) + + conversions := make([]Conversion, len(types)) + for i, ty := range types { + if ty.Equals(retTy) { + continue + } + if unsafe { + conversions[i] = GetConversionUnsafe(ty, retTy) + } else { + conversions[i] = GetConversion(ty, retTy) + } + if conversions[i] == nil { + // Shouldn't be reachable, since we were able to unify + return cty.NilType, nil + } + } + + return retTy, conversions +} + +func unifyObjectTypes(types []cty.Type, unsafe bool, hasDynamic bool) (cty.Type, []Conversion) { + // If we had any dynamic types in the input here then we can't predict + // what path we'll take through here once these become known types, so + // we'll conservatively produce DynamicVal for these. + if hasDynamic { + return unifyAllAsDynamic(types) + } + + // There are two different ways we can succeed here: + // - If all of the given object types have the same set of attribute names + // and the corresponding types are all unifyable, then we construct that + // type. + // - If the given object types have different attribute names or their + // corresponding types are not unifyable, we'll instead try to unify + // all of the attribute types together to produce a map type. + // + // Our unification behavior is intentionally stricter than our conversion + // behavior for subset object types because user intent is different with + // unification use-cases: it makes sense to allow {"foo":true} to convert + // to emptyobjectval, but unifying an object with an attribute with the + // empty object type should be an error because unifying to the empty + // object type would be suprising and useless. + + firstAttrs := types[0].AttributeTypes() + for _, ty := range types[1:] { + thisAttrs := ty.AttributeTypes() + if len(thisAttrs) != len(firstAttrs) { + // If number of attributes is different then there can be no + // object type in common. + return unifyObjectTypesToMap(types, unsafe) + } + for name := range thisAttrs { + if _, ok := firstAttrs[name]; !ok { + // If attribute names don't exactly match then there can be + // no object type in common. + return unifyObjectTypesToMap(types, unsafe) + } + } + } + + // If we get here then we've proven that all of the given object types + // have exactly the same set of attribute names, though the types may + // differ. + retAtys := make(map[string]cty.Type) + atysAcross := make([]cty.Type, len(types)) + for name := range firstAttrs { + for i, ty := range types { + atysAcross[i] = ty.AttributeType(name) + } + retAtys[name], _ = unify(atysAcross, unsafe) + if retAtys[name] == cty.NilType { + // Cannot unify this attribute alone, which means that unification + // of everything down to a map type can't be possible either. + return cty.NilType, nil + } + } + retTy := cty.Object(retAtys) + + conversions := make([]Conversion, len(types)) + for i, ty := range types { + if ty.Equals(retTy) { + continue + } + if unsafe { + conversions[i] = GetConversionUnsafe(ty, retTy) + } else { + conversions[i] = GetConversion(ty, retTy) + } + if conversions[i] == nil { + // Shouldn't be reachable, since we were able to unify + return unifyObjectTypesToMap(types, unsafe) + } + } + + return retTy, conversions +} + +func unifyObjectTypesToMap(types []cty.Type, unsafe bool) (cty.Type, []Conversion) { + // This is our fallback case for unifyObjectTypes, where we see if we can + // construct a map type that can accept all of the attribute types. + + var atys []cty.Type + for _, ty := range types { + for _, aty := range ty.AttributeTypes() { + atys = append(atys, aty) + } + } + + ety, _ := unify(atys, unsafe) + if ety == cty.NilType { + return cty.NilType, nil + } + + retTy := cty.Map(ety) + conversions := make([]Conversion, len(types)) + for i, ty := range types { + if ty.Equals(retTy) { + continue + } + if unsafe { + conversions[i] = GetConversionUnsafe(ty, retTy) + } else { + conversions[i] = GetConversion(ty, retTy) + } + if conversions[i] == nil { + return cty.NilType, nil + } + } + return retTy, conversions +} + +func unifyTupleTypes(types []cty.Type, unsafe bool, hasDynamic bool) (cty.Type, []Conversion) { + // If we had any dynamic types in the input here then we can't predict + // what path we'll take through here once these become known types, so + // we'll conservatively produce DynamicVal for these. + if hasDynamic { + return unifyAllAsDynamic(types) + } + + // There are two different ways we can succeed here: + // - If all of the given tuple types have the same sequence of element types + // and the corresponding types are all unifyable, then we construct that + // type. + // - If the given tuple types have different element types or their + // corresponding types are not unifyable, we'll instead try to unify + // all of the elements types together to produce a list type. + + firstEtys := types[0].TupleElementTypes() + for _, ty := range types[1:] { + thisEtys := ty.TupleElementTypes() + if len(thisEtys) != len(firstEtys) { + // If number of elements is different then there can be no + // tuple type in common. + return unifyTupleTypesToList(types, unsafe) + } + } + + // If we get here then we've proven that all of the given tuple types + // have the same number of elements, though the types may differ. + retEtys := make([]cty.Type, len(firstEtys)) + atysAcross := make([]cty.Type, len(types)) + for idx := range firstEtys { + for tyI, ty := range types { + atysAcross[tyI] = ty.TupleElementTypes()[idx] + } + retEtys[idx], _ = unify(atysAcross, unsafe) + if retEtys[idx] == cty.NilType { + // Cannot unify this element alone, which means that unification + // of everything down to a map type can't be possible either. + return cty.NilType, nil + } + } + retTy := cty.Tuple(retEtys) + + conversions := make([]Conversion, len(types)) + for i, ty := range types { + if ty.Equals(retTy) { + continue + } + if unsafe { + conversions[i] = GetConversionUnsafe(ty, retTy) + } else { + conversions[i] = GetConversion(ty, retTy) + } + if conversions[i] == nil { + // Shouldn't be reachable, since we were able to unify + return unifyTupleTypesToList(types, unsafe) + } + } + + return retTy, conversions +} + +func unifyTupleTypesToList(types []cty.Type, unsafe bool) (cty.Type, []Conversion) { + // This is our fallback case for unifyTupleTypes, where we see if we can + // construct a list type that can accept all of the element types. + + var etys []cty.Type + for _, ty := range types { + for _, ety := range ty.TupleElementTypes() { + etys = append(etys, ety) + } + } + + ety, _ := unify(etys, unsafe) + if ety == cty.NilType { + return cty.NilType, nil + } + + retTy := cty.List(ety) + conversions := make([]Conversion, len(types)) + for i, ty := range types { + if ty.Equals(retTy) { + continue + } + if unsafe { + conversions[i] = GetConversionUnsafe(ty, retTy) + } else { + conversions[i] = GetConversion(ty, retTy) + } + if conversions[i] == nil { + // Shouldn't be reachable, since we were able to unify + return unifyObjectTypesToMap(types, unsafe) + } + } + return retTy, conversions +} + +func unifyAllAsDynamic(types []cty.Type) (cty.Type, []Conversion) { + conversions := make([]Conversion, len(types)) + for i := range conversions { + conversions[i] = func(cty.Value) (cty.Value, error) { + return cty.DynamicVal, nil + } + } + return cty.DynamicPseudoType, conversions +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/doc.go b/vendor/github.com/hashicorp/go-cty/cty/doc.go new file mode 100644 index 00000000000..d31f0547bf4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/doc.go @@ -0,0 +1,18 @@ +// Package cty (pronounced see-tie) provides some infrastructure for a type +// system that might be useful for applications that need to represent +// configuration values provided by the user whose types are not known +// at compile time, particularly if the calling application also allows +// such values to be used in expressions. +// +// The type system consists of primitive types Number, String and Bool, as +// well as List and Map collection types and Object types that can have +// arbitrarily-typed sets of attributes. +// +// A set of operations is defined on these types, which is accessible via +// the wrapper struct Value, which annotates the raw, internal representation +// of a value with its corresponding type. +// +// This package is oriented towards being a building block for configuration +// languages used to bootstrap an application. It is not optimized for use +// in tight loops where CPU time or memory pressure are a concern. +package cty diff --git a/vendor/github.com/hashicorp/go-cty/cty/element_iterator.go b/vendor/github.com/hashicorp/go-cty/cty/element_iterator.go new file mode 100644 index 00000000000..31567e766a8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/element_iterator.go @@ -0,0 +1,194 @@ +package cty + +import ( + "sort" + + "github.com/hashicorp/go-cty/cty/set" +) + +// ElementIterator is the interface type returned by Value.ElementIterator to +// allow the caller to iterate over elements of a collection-typed value. +// +// Its usage pattern is as follows: +// +// it := val.ElementIterator() +// for it.Next() { +// key, val := it.Element() +// // ... +// } +type ElementIterator interface { + Next() bool + Element() (key Value, value Value) +} + +func canElementIterator(val Value) bool { + switch { + case val.IsMarked(): + return false + case val.ty.IsListType(): + return true + case val.ty.IsMapType(): + return true + case val.ty.IsSetType(): + return true + case val.ty.IsTupleType(): + return true + case val.ty.IsObjectType(): + return true + default: + return false + } +} + +func elementIterator(val Value) ElementIterator { + val.assertUnmarked() + switch { + case val.ty.IsListType(): + return &listElementIterator{ + ety: val.ty.ElementType(), + vals: val.v.([]interface{}), + idx: -1, + } + case val.ty.IsMapType(): + // We iterate the keys in a predictable lexicographical order so + // that results will always be stable given the same input map. + rawMap := val.v.(map[string]interface{}) + keys := make([]string, 0, len(rawMap)) + for key := range rawMap { + keys = append(keys, key) + } + sort.Strings(keys) + + return &mapElementIterator{ + ety: val.ty.ElementType(), + vals: rawMap, + keys: keys, + idx: -1, + } + case val.ty.IsSetType(): + rawSet := val.v.(set.Set) + return &setElementIterator{ + ety: val.ty.ElementType(), + setIt: rawSet.Iterator(), + } + case val.ty.IsTupleType(): + return &tupleElementIterator{ + etys: val.ty.TupleElementTypes(), + vals: val.v.([]interface{}), + idx: -1, + } + case val.ty.IsObjectType(): + // We iterate the keys in a predictable lexicographical order so + // that results will always be stable given the same object type. + atys := val.ty.AttributeTypes() + keys := make([]string, 0, len(atys)) + for key := range atys { + keys = append(keys, key) + } + sort.Strings(keys) + + return &objectElementIterator{ + atys: atys, + vals: val.v.(map[string]interface{}), + attrNames: keys, + idx: -1, + } + default: + panic("attempt to iterate on non-collection, non-tuple type") + } +} + +type listElementIterator struct { + ety Type + vals []interface{} + idx int +} + +func (it *listElementIterator) Element() (Value, Value) { + i := it.idx + return NumberIntVal(int64(i)), Value{ + ty: it.ety, + v: it.vals[i], + } +} + +func (it *listElementIterator) Next() bool { + it.idx++ + return it.idx < len(it.vals) +} + +type mapElementIterator struct { + ety Type + vals map[string]interface{} + keys []string + idx int +} + +func (it *mapElementIterator) Element() (Value, Value) { + key := it.keys[it.idx] + return StringVal(key), Value{ + ty: it.ety, + v: it.vals[key], + } +} + +func (it *mapElementIterator) Next() bool { + it.idx++ + return it.idx < len(it.keys) +} + +type setElementIterator struct { + ety Type + setIt *set.Iterator +} + +func (it *setElementIterator) Element() (Value, Value) { + val := Value{ + ty: it.ety, + v: it.setIt.Value(), + } + return val, val +} + +func (it *setElementIterator) Next() bool { + return it.setIt.Next() +} + +type tupleElementIterator struct { + etys []Type + vals []interface{} + idx int +} + +func (it *tupleElementIterator) Element() (Value, Value) { + i := it.idx + return NumberIntVal(int64(i)), Value{ + ty: it.etys[i], + v: it.vals[i], + } +} + +func (it *tupleElementIterator) Next() bool { + it.idx++ + return it.idx < len(it.vals) +} + +type objectElementIterator struct { + atys map[string]Type + vals map[string]interface{} + attrNames []string + idx int +} + +func (it *objectElementIterator) Element() (Value, Value) { + key := it.attrNames[it.idx] + return StringVal(key), Value{ + ty: it.atys[key], + v: it.vals[key], + } +} + +func (it *objectElementIterator) Next() bool { + it.idx++ + return it.idx < len(it.attrNames) +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/error.go b/vendor/github.com/hashicorp/go-cty/cty/error.go new file mode 100644 index 00000000000..dd139f72499 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/error.go @@ -0,0 +1,55 @@ +package cty + +import ( + "fmt" +) + +// PathError is a specialization of error that represents where in a +// potentially-deep data structure an error occured, using a Path. +type PathError struct { + error + Path Path +} + +func errorf(path Path, f string, args ...interface{}) error { + // We need to copy the Path because often our caller builds it by + // continually mutating the same underlying buffer. + sPath := make(Path, len(path)) + copy(sPath, path) + return PathError{ + error: fmt.Errorf(f, args...), + Path: sPath, + } +} + +// NewErrorf creates a new PathError for the current path by passing the +// given format and arguments to fmt.Errorf and then wrapping the result +// similarly to NewError. +func (p Path) NewErrorf(f string, args ...interface{}) error { + return errorf(p, f, args...) +} + +// NewError creates a new PathError for the current path, wrapping the given +// error. +func (p Path) NewError(err error) error { + // if we're being asked to wrap an existing PathError then our new + // PathError will be the concatenation of the two paths, ensuring + // that we still get a single flat PathError that's thus easier for + // callers to deal with. + perr, wrappingPath := err.(PathError) + pathLen := len(p) + if wrappingPath { + pathLen = pathLen + len(perr.Path) + } + + sPath := make(Path, pathLen) + copy(sPath, p) + if wrappingPath { + copy(sPath[len(p):], perr.Path) + } + + return PathError{ + error: err, + Path: sPath, + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/gob.go b/vendor/github.com/hashicorp/go-cty/cty/gob.go new file mode 100644 index 00000000000..80929aa5440 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/gob.go @@ -0,0 +1,204 @@ +package cty + +import ( + "bytes" + "encoding/gob" + "errors" + "fmt" + "math/big" + + "github.com/hashicorp/go-cty/cty/set" +) + +// GobEncode is an implementation of the gob.GobEncoder interface, which +// allows Values to be included in structures encoded with encoding/gob. +// +// Currently it is not possible to represent values of capsule types in gob, +// because the types themselves cannot be represented. +func (val Value) GobEncode() ([]byte, error) { + if val.IsMarked() { + return nil, errors.New("value is marked") + } + + buf := &bytes.Buffer{} + enc := gob.NewEncoder(buf) + + gv := gobValue{ + Version: 0, + Ty: val.ty, + V: val.v, + } + + err := enc.Encode(gv) + if err != nil { + return nil, fmt.Errorf("error encoding cty.Value: %s", err) + } + + return buf.Bytes(), nil +} + +// GobDecode is an implementation of the gob.GobDecoder interface, which +// inverts the operation performed by GobEncode. See the documentation of +// GobEncode for considerations when using cty.Value instances with gob. +func (val *Value) GobDecode(buf []byte) error { + r := bytes.NewReader(buf) + dec := gob.NewDecoder(r) + + var gv gobValue + err := dec.Decode(&gv) + if err != nil { + return fmt.Errorf("error decoding cty.Value: %s", err) + } + if gv.Version != 0 { + return fmt.Errorf("unsupported cty.Value encoding version %d; only 0 is supported", gv.Version) + } + + // Because big.Float.GobEncode is implemented with a pointer reciever, + // gob encoding of an interface{} containing a *big.Float value does not + // round-trip correctly, emerging instead as a non-pointer big.Float. + // The rest of cty expects all number values to be represented by + // *big.Float, so we'll fix that up here. + gv.V = gobDecodeFixNumberPtr(gv.V, gv.Ty) + + val.ty = gv.Ty + val.v = gv.V + + return nil +} + +// GobEncode is an implementation of the gob.GobEncoder interface, which +// allows Types to be included in structures encoded with encoding/gob. +// +// Currently it is not possible to represent capsule types in gob. +func (t Type) GobEncode() ([]byte, error) { + buf := &bytes.Buffer{} + enc := gob.NewEncoder(buf) + + gt := gobType{ + Version: 0, + Impl: t.typeImpl, + } + + err := enc.Encode(gt) + if err != nil { + return nil, fmt.Errorf("error encoding cty.Type: %s", err) + } + + return buf.Bytes(), nil +} + +// GobDecode is an implementatino of the gob.GobDecoder interface, which +// reverses the encoding performed by GobEncode to allow types to be recovered +// from gob buffers. +func (t *Type) GobDecode(buf []byte) error { + r := bytes.NewReader(buf) + dec := gob.NewDecoder(r) + + var gt gobType + err := dec.Decode(>) + if err != nil { + return fmt.Errorf("error decoding cty.Type: %s", err) + } + if gt.Version != 0 { + return fmt.Errorf("unsupported cty.Type encoding version %d; only 0 is supported", gt.Version) + } + + t.typeImpl = gt.Impl + + return nil +} + +// Capsule types cannot currently be gob-encoded, because they rely on pointer +// equality and we have no way to recover the original pointer on decode. +func (t *capsuleType) GobEncode() ([]byte, error) { + return nil, fmt.Errorf("cannot gob-encode capsule type %q", t.FriendlyName(friendlyTypeName)) +} + +func (t *capsuleType) GobDecode() ([]byte, error) { + return nil, fmt.Errorf("cannot gob-decode capsule type %q", t.FriendlyName(friendlyTypeName)) +} + +type gobValue struct { + Version int + Ty Type + V interface{} +} + +type gobType struct { + Version int + Impl typeImpl +} + +type gobCapsuleTypeImpl struct { +} + +// goDecodeFixNumberPtr fixes an unfortunate quirk of round-tripping cty.Number +// values through gob: the big.Float.GobEncode method is implemented on a +// pointer receiver, and so it loses the "pointer-ness" of the value on +// encode, causing the values to emerge the other end as big.Float rather than +// *big.Float as we expect elsewhere in cty. +// +// The implementation of gobDecodeFixNumberPtr mutates the given raw value +// during its work, and may either return the same value mutated or a new +// value. Callers must no longer use whatever value they pass as "raw" after +// this function is called. +func gobDecodeFixNumberPtr(raw interface{}, ty Type) interface{} { + // Unfortunately we need to work recursively here because number values + // might be embedded in structural or collection type values. + + switch { + case ty.Equals(Number): + if bf, ok := raw.(big.Float); ok { + return &bf // wrap in pointer + } + case ty.IsMapType() && ty.ElementType().Equals(Number): + if m, ok := raw.(map[string]interface{}); ok { + for k, v := range m { + m[k] = gobDecodeFixNumberPtr(v, ty.ElementType()) + } + } + case ty.IsListType() && ty.ElementType().Equals(Number): + if s, ok := raw.([]interface{}); ok { + for i, v := range s { + s[i] = gobDecodeFixNumberPtr(v, ty.ElementType()) + } + } + case ty.IsSetType() && ty.ElementType().Equals(Number): + if s, ok := raw.(set.Set); ok { + newS := set.NewSet(s.Rules()) + for it := s.Iterator(); it.Next(); { + newV := gobDecodeFixNumberPtr(it.Value(), ty.ElementType()) + newS.Add(newV) + } + return newS + } + case ty.IsObjectType(): + if m, ok := raw.(map[string]interface{}); ok { + for k, v := range m { + aty := ty.AttributeType(k) + m[k] = gobDecodeFixNumberPtr(v, aty) + } + } + case ty.IsTupleType(): + if s, ok := raw.([]interface{}); ok { + for i, v := range s { + ety := ty.TupleElementType(i) + s[i] = gobDecodeFixNumberPtr(v, ety) + } + } + } + + return raw +} + +// gobDecodeFixNumberPtrVal is a helper wrapper around gobDecodeFixNumberPtr +// that works with already-constructed values. This is primarily for testing, +// to fix up intentionally-invalid number values for the parts of the test +// code that need them to be valid, such as calling GoString on them. +func gobDecodeFixNumberPtrVal(v Value) Value { + raw := gobDecodeFixNumberPtr(v.v, v.ty) + return Value{ + v: raw, + ty: v.ty, + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/gocty/doc.go b/vendor/github.com/hashicorp/go-cty/cty/gocty/doc.go new file mode 100644 index 00000000000..a5177d22b27 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/gocty/doc.go @@ -0,0 +1,7 @@ +// Package gocty deals with converting between cty Values and native go +// values. +// +// It operates under a similar principle to the encoding/json and +// encoding/xml packages in the standard library, using reflection to +// populate native Go data structures from cty values and vice-versa. +package gocty diff --git a/vendor/github.com/hashicorp/go-cty/cty/gocty/helpers.go b/vendor/github.com/hashicorp/go-cty/cty/gocty/helpers.go new file mode 100644 index 00000000000..0677a07947d --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/gocty/helpers.go @@ -0,0 +1,43 @@ +package gocty + +import ( + "math/big" + "reflect" + + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/go-cty/cty/set" +) + +var valueType = reflect.TypeOf(cty.Value{}) +var typeType = reflect.TypeOf(cty.Type{}) + +var setType = reflect.TypeOf(set.Set{}) + +var bigFloatType = reflect.TypeOf(big.Float{}) +var bigIntType = reflect.TypeOf(big.Int{}) + +var emptyInterfaceType = reflect.TypeOf(interface{}(nil)) + +var stringType = reflect.TypeOf("") + +// structTagIndices interrogates the fields of the given type (which must +// be a struct type, or we'll panic) and returns a map from the cty +// attribute names declared via struct tags to the indices of the +// fields holding those tags. +// +// This function will panic if two fields within the struct are tagged with +// the same cty attribute name. +func structTagIndices(st reflect.Type) map[string]int { + ct := st.NumField() + ret := make(map[string]int, ct) + + for i := 0; i < ct; i++ { + field := st.Field(i) + attrName := field.Tag.Get("cty") + if attrName != "" { + ret[attrName] = i + } + } + + return ret +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/gocty/in.go b/vendor/github.com/hashicorp/go-cty/cty/gocty/in.go new file mode 100644 index 00000000000..fc35c169204 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/gocty/in.go @@ -0,0 +1,548 @@ +package gocty + +import ( + "math/big" + "reflect" + + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/go-cty/cty/convert" + "github.com/hashicorp/go-cty/cty/set" +) + +// ToCtyValue produces a cty.Value from a Go value. The result will conform +// to the given type, or an error will be returned if this is not possible. +// +// The target type serves as a hint to resolve ambiguities in the mapping. +// For example, the Go type set.Set tells us that the value is a set but +// does not describe the set's element type. This also allows for convenient +// conversions, such as populating a set from a slice rather than having to +// first explicitly instantiate a set.Set. +// +// The audience of this function is assumed to be the developers of Go code +// that is integrating with cty, and thus the error messages it returns are +// presented from Go's perspective. These messages are thus not appropriate +// for display to end-users. An error returned from ToCtyValue represents a +// bug in the calling program, not user error. +func ToCtyValue(val interface{}, ty cty.Type) (cty.Value, error) { + // 'path' starts off as empty but will grow for each level of recursive + // call we make, so by the time toCtyValue returns it is likely to have + // unused capacity on the end of it, depending on how deeply-recursive + // the given Type is. + path := make(cty.Path, 0) + return toCtyValue(reflect.ValueOf(val), ty, path) +} + +func toCtyValue(val reflect.Value, ty cty.Type, path cty.Path) (cty.Value, error) { + if val != (reflect.Value{}) && val.Type().AssignableTo(valueType) { + // If the source value is a cty.Value then we'll try to just pass + // through to the target type directly. + return toCtyPassthrough(val, ty, path) + } + + switch ty { + case cty.Bool: + return toCtyBool(val, path) + case cty.Number: + return toCtyNumber(val, path) + case cty.String: + return toCtyString(val, path) + case cty.DynamicPseudoType: + return toCtyDynamic(val, path) + } + + switch { + case ty.IsListType(): + return toCtyList(val, ty.ElementType(), path) + case ty.IsMapType(): + return toCtyMap(val, ty.ElementType(), path) + case ty.IsSetType(): + return toCtySet(val, ty.ElementType(), path) + case ty.IsObjectType(): + return toCtyObject(val, ty.AttributeTypes(), path) + case ty.IsTupleType(): + return toCtyTuple(val, ty.TupleElementTypes(), path) + case ty.IsCapsuleType(): + return toCtyCapsule(val, ty, path) + } + + // We should never fall out here + return cty.NilVal, path.NewErrorf("unsupported target type %#v", ty) +} + +func toCtyBool(val reflect.Value, path cty.Path) (cty.Value, error) { + if val = toCtyUnwrapPointer(val); !val.IsValid() { + return cty.NullVal(cty.Bool), nil + } + + switch val.Kind() { + + case reflect.Bool: + return cty.BoolVal(val.Bool()), nil + + default: + return cty.NilVal, path.NewErrorf("can't convert Go %s to bool", val.Kind()) + + } + +} + +func toCtyNumber(val reflect.Value, path cty.Path) (cty.Value, error) { + if val = toCtyUnwrapPointer(val); !val.IsValid() { + return cty.NullVal(cty.Number), nil + } + + switch val.Kind() { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return cty.NumberIntVal(val.Int()), nil + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return cty.NumberUIntVal(val.Uint()), nil + + case reflect.Float32, reflect.Float64: + return cty.NumberFloatVal(val.Float()), nil + + case reflect.Struct: + if val.Type().AssignableTo(bigIntType) { + bigInt := val.Interface().(big.Int) + bigFloat := (&big.Float{}).SetInt(&bigInt) + val = reflect.ValueOf(*bigFloat) + } + + if val.Type().AssignableTo(bigFloatType) { + bigFloat := val.Interface().(big.Float) + return cty.NumberVal(&bigFloat), nil + } + + fallthrough + default: + return cty.NilVal, path.NewErrorf("can't convert Go %s to number", val.Kind()) + + } + +} + +func toCtyString(val reflect.Value, path cty.Path) (cty.Value, error) { + if val = toCtyUnwrapPointer(val); !val.IsValid() { + return cty.NullVal(cty.String), nil + } + + switch val.Kind() { + + case reflect.String: + return cty.StringVal(val.String()), nil + + default: + return cty.NilVal, path.NewErrorf("can't convert Go %s to string", val.Kind()) + + } + +} + +func toCtyList(val reflect.Value, ety cty.Type, path cty.Path) (cty.Value, error) { + if val = toCtyUnwrapPointer(val); !val.IsValid() { + return cty.NullVal(cty.List(ety)), nil + } + + switch val.Kind() { + + case reflect.Slice: + if val.IsNil() { + return cty.NullVal(cty.List(ety)), nil + } + fallthrough + case reflect.Array: + if val.Len() == 0 { + return cty.ListValEmpty(ety), nil + } + + // While we work on our elements we'll temporarily grow + // path to give us a place to put our index step. + path = append(path, cty.PathStep(nil)) + + vals := make([]cty.Value, val.Len()) + for i := range vals { + var err error + path[len(path)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(int64(i)), + } + vals[i], err = toCtyValue(val.Index(i), ety, path) + if err != nil { + return cty.NilVal, err + } + } + + // Discard our extra path segment, retaining it as extra capacity + // for future appending to the path. + path = path[:len(path)-1] + + return cty.ListVal(vals), nil + + default: + return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Kind(), cty.List(ety)) + + } +} + +func toCtyMap(val reflect.Value, ety cty.Type, path cty.Path) (cty.Value, error) { + if val = toCtyUnwrapPointer(val); !val.IsValid() { + return cty.NullVal(cty.Map(ety)), nil + } + + switch val.Kind() { + + case reflect.Map: + if val.IsNil() { + return cty.NullVal(cty.Map(ety)), nil + } + + if val.Len() == 0 { + return cty.MapValEmpty(ety), nil + } + + keyType := val.Type().Key() + if keyType.Kind() != reflect.String { + return cty.NilVal, path.NewErrorf("can't convert Go map with key type %s; key type must be string", keyType) + } + + // While we work on our elements we'll temporarily grow + // path to give us a place to put our index step. + path = append(path, cty.PathStep(nil)) + + vals := make(map[string]cty.Value, val.Len()) + for _, kv := range val.MapKeys() { + k := kv.String() + var err error + path[len(path)-1] = cty.IndexStep{ + Key: cty.StringVal(k), + } + vals[k], err = toCtyValue(val.MapIndex(reflect.ValueOf(k)), ety, path) + if err != nil { + return cty.NilVal, err + } + } + + // Discard our extra path segment, retaining it as extra capacity + // for future appending to the path. + path = path[:len(path)-1] + + return cty.MapVal(vals), nil + + default: + return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Kind(), cty.Map(ety)) + + } +} + +func toCtySet(val reflect.Value, ety cty.Type, path cty.Path) (cty.Value, error) { + if val = toCtyUnwrapPointer(val); !val.IsValid() { + return cty.NullVal(cty.Set(ety)), nil + } + + var vals []cty.Value + + switch val.Kind() { + + case reflect.Slice: + if val.IsNil() { + return cty.NullVal(cty.Set(ety)), nil + } + fallthrough + case reflect.Array: + if val.Len() == 0 { + return cty.SetValEmpty(ety), nil + } + + vals = make([]cty.Value, val.Len()) + for i := range vals { + var err error + vals[i], err = toCtyValue(val.Index(i), ety, path) + if err != nil { + return cty.NilVal, err + } + } + + case reflect.Struct: + + if !val.Type().AssignableTo(setType) { + return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Type(), cty.Set(ety)) + } + + rawSet := val.Interface().(set.Set) + inVals := rawSet.Values() + + if len(inVals) == 0 { + return cty.SetValEmpty(ety), nil + } + + vals = make([]cty.Value, len(inVals)) + for i := range inVals { + var err error + vals[i], err = toCtyValue(reflect.ValueOf(inVals[i]), ety, path) + if err != nil { + return cty.NilVal, err + } + } + + default: + return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Kind(), cty.Set(ety)) + + } + + return cty.SetVal(vals), nil +} + +func toCtyObject(val reflect.Value, attrTypes map[string]cty.Type, path cty.Path) (cty.Value, error) { + if val = toCtyUnwrapPointer(val); !val.IsValid() { + return cty.NullVal(cty.Object(attrTypes)), nil + } + + switch val.Kind() { + + case reflect.Map: + if val.IsNil() { + return cty.NullVal(cty.Object(attrTypes)), nil + } + + keyType := val.Type().Key() + if keyType.Kind() != reflect.String { + return cty.NilVal, path.NewErrorf("can't convert Go map with key type %s; key type must be string", keyType) + } + + if len(attrTypes) == 0 { + return cty.EmptyObjectVal, nil + } + + // While we work on our elements we'll temporarily grow + // path to give us a place to put our GetAttr step. + path = append(path, cty.PathStep(nil)) + + haveKeys := make(map[string]struct{}, val.Len()) + for _, kv := range val.MapKeys() { + haveKeys[kv.String()] = struct{}{} + } + + vals := make(map[string]cty.Value, len(attrTypes)) + for k, at := range attrTypes { + var err error + path[len(path)-1] = cty.GetAttrStep{ + Name: k, + } + + if _, have := haveKeys[k]; !have { + vals[k] = cty.NullVal(at) + continue + } + + vals[k], err = toCtyValue(val.MapIndex(reflect.ValueOf(k)), at, path) + if err != nil { + return cty.NilVal, err + } + } + + // Discard our extra path segment, retaining it as extra capacity + // for future appending to the path. + path = path[:len(path)-1] + + return cty.ObjectVal(vals), nil + + case reflect.Struct: + if len(attrTypes) == 0 { + return cty.EmptyObjectVal, nil + } + + // While we work on our elements we'll temporarily grow + // path to give us a place to put our GetAttr step. + path = append(path, cty.PathStep(nil)) + + attrFields := structTagIndices(val.Type()) + + vals := make(map[string]cty.Value, len(attrTypes)) + for k, at := range attrTypes { + path[len(path)-1] = cty.GetAttrStep{ + Name: k, + } + + if fieldIdx, have := attrFields[k]; have { + var err error + vals[k], err = toCtyValue(val.Field(fieldIdx), at, path) + if err != nil { + return cty.NilVal, err + } + } else { + vals[k] = cty.NullVal(at) + } + } + + // Discard our extra path segment, retaining it as extra capacity + // for future appending to the path. + path = path[:len(path)-1] + + return cty.ObjectVal(vals), nil + + default: + return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Kind(), cty.Object(attrTypes)) + + } +} + +func toCtyTuple(val reflect.Value, elemTypes []cty.Type, path cty.Path) (cty.Value, error) { + if val = toCtyUnwrapPointer(val); !val.IsValid() { + return cty.NullVal(cty.Tuple(elemTypes)), nil + } + + switch val.Kind() { + + case reflect.Slice: + if val.IsNil() { + return cty.NullVal(cty.Tuple(elemTypes)), nil + } + + if val.Len() != len(elemTypes) { + return cty.NilVal, path.NewErrorf("wrong number of elements %d; need %d", val.Len(), len(elemTypes)) + } + + if len(elemTypes) == 0 { + return cty.EmptyTupleVal, nil + } + + // While we work on our elements we'll temporarily grow + // path to give us a place to put our Index step. + path = append(path, cty.PathStep(nil)) + + vals := make([]cty.Value, len(elemTypes)) + for i, ety := range elemTypes { + var err error + + path[len(path)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(int64(i)), + } + + vals[i], err = toCtyValue(val.Index(i), ety, path) + if err != nil { + return cty.NilVal, err + } + } + + // Discard our extra path segment, retaining it as extra capacity + // for future appending to the path. + path = path[:len(path)-1] + + return cty.TupleVal(vals), nil + + case reflect.Struct: + fieldCount := val.Type().NumField() + if fieldCount != len(elemTypes) { + return cty.NilVal, path.NewErrorf("wrong number of struct fields %d; need %d", fieldCount, len(elemTypes)) + } + + if len(elemTypes) == 0 { + return cty.EmptyTupleVal, nil + } + + // While we work on our elements we'll temporarily grow + // path to give us a place to put our Index step. + path = append(path, cty.PathStep(nil)) + + vals := make([]cty.Value, len(elemTypes)) + for i, ety := range elemTypes { + var err error + + path[len(path)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(int64(i)), + } + + vals[i], err = toCtyValue(val.Field(i), ety, path) + if err != nil { + return cty.NilVal, err + } + } + + // Discard our extra path segment, retaining it as extra capacity + // for future appending to the path. + path = path[:len(path)-1] + + return cty.TupleVal(vals), nil + + default: + return cty.NilVal, path.NewErrorf("can't convert Go %s to %#v", val.Kind(), cty.Tuple(elemTypes)) + + } +} + +func toCtyCapsule(val reflect.Value, capsuleType cty.Type, path cty.Path) (cty.Value, error) { + if val = toCtyUnwrapPointer(val); !val.IsValid() { + return cty.NullVal(capsuleType), nil + } + + if val.Kind() != reflect.Ptr { + if !val.CanAddr() { + return cty.NilVal, path.NewErrorf("source value for capsule %#v must be addressable", capsuleType) + } + + val = val.Addr() + } + + if !val.Type().Elem().AssignableTo(capsuleType.EncapsulatedType()) { + return cty.NilVal, path.NewErrorf("value of type %T not compatible with capsule %#v", val.Interface(), capsuleType) + } + + return cty.CapsuleVal(capsuleType, val.Interface()), nil +} + +func toCtyDynamic(val reflect.Value, path cty.Path) (cty.Value, error) { + if val = toCtyUnwrapPointer(val); !val.IsValid() { + return cty.NullVal(cty.DynamicPseudoType), nil + } + + switch val.Kind() { + + case reflect.Struct: + if !val.Type().AssignableTo(valueType) { + return cty.NilVal, path.NewErrorf("can't convert Go %s dynamically; only cty.Value allowed", val.Type()) + } + + return val.Interface().(cty.Value), nil + + default: + return cty.NilVal, path.NewErrorf("can't convert Go %s dynamically; only cty.Value allowed", val.Kind()) + + } + +} + +func toCtyPassthrough(wrappedVal reflect.Value, wantTy cty.Type, path cty.Path) (cty.Value, error) { + if wrappedVal = toCtyUnwrapPointer(wrappedVal); !wrappedVal.IsValid() { + return cty.NullVal(wantTy), nil + } + + givenVal := wrappedVal.Interface().(cty.Value) + + val, err := convert.Convert(givenVal, wantTy) + if err != nil { + return cty.NilVal, path.NewErrorf("unsuitable value: %s", err) + } + return val, nil +} + +// toCtyUnwrapPointer is a helper for dealing with Go pointers. It has three +// possible outcomes: +// +// - Given value isn't a pointer, so it's just returned as-is. +// - Given value is a non-nil pointer, in which case it is dereferenced +// and the result returned. +// - Given value is a nil pointer, in which case an invalid value is returned. +// +// For nested pointer types, like **int, they are all dereferenced in turn +// until a non-pointer value is found, or until a nil pointer is encountered. +func toCtyUnwrapPointer(val reflect.Value) reflect.Value { + for val.Kind() == reflect.Ptr || val.Kind() == reflect.Interface { + if val.IsNil() { + return reflect.Value{} + } + + val = val.Elem() + } + + return val +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/gocty/out.go b/vendor/github.com/hashicorp/go-cty/cty/gocty/out.go new file mode 100644 index 00000000000..404faba18fa --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/gocty/out.go @@ -0,0 +1,686 @@ +package gocty + +import ( + "math" + "math/big" + "reflect" + + "github.com/hashicorp/go-cty/cty" +) + +// FromCtyValue assigns a cty.Value to a reflect.Value, which must be a pointer, +// using a fixed set of conversion rules. +// +// This function considers its audience to be the creator of the cty Value +// given, and thus the error messages it generates are (unlike with ToCtyValue) +// presented in cty terminology that is generally appropriate to return to +// end-users in applications where cty data structures are built from +// user-provided configuration. In particular this means that if incorrect +// target types are provided by the calling application the resulting error +// messages are likely to be confusing, since we assume that the given target +// type is correct and the cty.Value is where the error lies. +// +// If an error is returned, the target data structure may have been partially +// populated, but the degree to which this is true is an implementation +// detail that the calling application should not rely on. +// +// The function will panic if given a non-pointer as the Go value target, +// since that is considered to be a bug in the calling program. +func FromCtyValue(val cty.Value, target interface{}) error { + tVal := reflect.ValueOf(target) + if tVal.Kind() != reflect.Ptr { + panic("target value is not a pointer") + } + if tVal.IsNil() { + panic("target value is nil pointer") + } + + // 'path' starts off as empty but will grow for each level of recursive + // call we make, so by the time fromCtyValue returns it is likely to have + // unused capacity on the end of it, depending on how deeply-recursive + // the given cty.Value is. + path := make(cty.Path, 0) + return fromCtyValue(val, tVal, path) +} + +func fromCtyValue(val cty.Value, target reflect.Value, path cty.Path) error { + ty := val.Type() + + deepTarget := fromCtyPopulatePtr(target, false) + + // If we're decoding into a cty.Value then we just pass through the + // value as-is, to enable partial decoding. This is the only situation + // where unknown values are permitted. + if deepTarget.Kind() == reflect.Struct && deepTarget.Type().AssignableTo(valueType) { + deepTarget.Set(reflect.ValueOf(val)) + return nil + } + + // Lists and maps can be nil without indirection, but everything else + // requires a pointer and we set it immediately to nil. + // We also make an exception for capsule types because we want to handle + // pointers specially for these. + // (fromCtyList and fromCtyMap must therefore deal with val.IsNull, while + // other types can assume no nulls after this point.) + if val.IsNull() && !val.Type().IsListType() && !val.Type().IsMapType() && !val.Type().IsCapsuleType() { + target = fromCtyPopulatePtr(target, true) + if target.Kind() != reflect.Ptr { + return path.NewErrorf("null value is not allowed") + } + + target.Set(reflect.Zero(target.Type())) + return nil + } + + target = deepTarget + + if !val.IsKnown() { + return path.NewErrorf("value must be known") + } + + switch ty { + case cty.Bool: + return fromCtyBool(val, target, path) + case cty.Number: + return fromCtyNumber(val, target, path) + case cty.String: + return fromCtyString(val, target, path) + } + + switch { + case ty.IsListType(): + return fromCtyList(val, target, path) + case ty.IsMapType(): + return fromCtyMap(val, target, path) + case ty.IsSetType(): + return fromCtySet(val, target, path) + case ty.IsObjectType(): + return fromCtyObject(val, target, path) + case ty.IsTupleType(): + return fromCtyTuple(val, target, path) + case ty.IsCapsuleType(): + return fromCtyCapsule(val, target, path) + } + + // We should never fall out here; reaching here indicates a bug in this + // function. + return path.NewErrorf("unsupported source type %#v", ty) +} + +func fromCtyBool(val cty.Value, target reflect.Value, path cty.Path) error { + switch target.Kind() { + + case reflect.Bool: + target.SetBool(val.True()) + return nil + + default: + return likelyRequiredTypesError(path, target) + + } +} + +func fromCtyNumber(val cty.Value, target reflect.Value, path cty.Path) error { + bf := val.AsBigFloat() + + switch target.Kind() { + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return fromCtyNumberInt(bf, target, path) + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return fromCtyNumberUInt(bf, target, path) + + case reflect.Float32, reflect.Float64: + return fromCtyNumberFloat(bf, target, path) + + case reflect.Struct: + return fromCtyNumberBig(bf, target, path) + + default: + return likelyRequiredTypesError(path, target) + + } +} + +func fromCtyNumberInt(bf *big.Float, target reflect.Value, path cty.Path) error { + // Doing this with switch rather than << arithmetic because << with + // result >32-bits is not portable to 32-bit systems. + var min int64 + var max int64 + switch target.Type().Bits() { + case 8: + min = math.MinInt8 + max = math.MaxInt8 + case 16: + min = math.MinInt16 + max = math.MaxInt16 + case 32: + min = math.MinInt32 + max = math.MaxInt32 + case 64: + min = math.MinInt64 + max = math.MaxInt64 + default: + panic("weird number of bits in target int") + } + + iv, accuracy := bf.Int64() + if accuracy != big.Exact || iv < min || iv > max { + return path.NewErrorf("value must be a whole number, between %d and %d", min, max) + } + + target.SetInt(iv) + return nil +} + +func fromCtyNumberUInt(bf *big.Float, target reflect.Value, path cty.Path) error { + // Doing this with switch rather than << arithmetic because << with + // result >32-bits is not portable to 32-bit systems. + var max uint64 + switch target.Type().Bits() { + case 8: + max = math.MaxUint8 + case 16: + max = math.MaxUint16 + case 32: + max = math.MaxUint32 + case 64: + max = math.MaxUint64 + default: + panic("weird number of bits in target uint") + } + + iv, accuracy := bf.Uint64() + if accuracy != big.Exact || iv > max { + return path.NewErrorf("value must be a whole number, between 0 and %d inclusive", max) + } + + target.SetUint(iv) + return nil +} + +func fromCtyNumberFloat(bf *big.Float, target reflect.Value, path cty.Path) error { + switch target.Kind() { + case reflect.Float32, reflect.Float64: + fv, accuracy := bf.Float64() + if accuracy != big.Exact { + // We allow the precision to be truncated as part of our conversion, + // but we don't want to silently introduce infinities. + if math.IsInf(fv, 0) { + return path.NewErrorf("value must be between %f and %f inclusive", -math.MaxFloat64, math.MaxFloat64) + } + } + target.SetFloat(fv) + return nil + default: + panic("unsupported kind of float") + } +} + +func fromCtyNumberBig(bf *big.Float, target reflect.Value, path cty.Path) error { + switch { + + case bigFloatType.ConvertibleTo(target.Type()): + // Easy! + target.Set(reflect.ValueOf(bf).Elem().Convert(target.Type())) + return nil + + case bigIntType.ConvertibleTo(target.Type()): + bi, accuracy := bf.Int(nil) + if accuracy != big.Exact { + return path.NewErrorf("value must be a whole number") + } + target.Set(reflect.ValueOf(bi).Elem().Convert(target.Type())) + return nil + + default: + return likelyRequiredTypesError(path, target) + } +} + +func fromCtyString(val cty.Value, target reflect.Value, path cty.Path) error { + switch target.Kind() { + case reflect.String: + target.SetString(val.AsString()) + return nil + + default: + return likelyRequiredTypesError(path, target) + + } +} + +func fromCtyList(val cty.Value, target reflect.Value, path cty.Path) error { + switch target.Kind() { + + case reflect.Slice: + if val.IsNull() { + target.Set(reflect.Zero(target.Type())) + return nil + } + + length := val.LengthInt() + tv := reflect.MakeSlice(target.Type(), length, length) + + path = append(path, nil) + + i := 0 + var err error + val.ForEachElement(func(key cty.Value, val cty.Value) bool { + path[len(path)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(int64(i)), + } + + targetElem := tv.Index(i) + err = fromCtyValue(val, targetElem, path) + if err != nil { + return true + } + + i++ + return false + }) + if err != nil { + return err + } + + path = path[:len(path)-1] + + target.Set(tv) + return nil + + case reflect.Array: + if val.IsNull() { + return path.NewErrorf("null value is not allowed") + } + + length := val.LengthInt() + if length != target.Len() { + return path.NewErrorf("must be a list of length %d", target.Len()) + } + + path = append(path, nil) + + i := 0 + var err error + val.ForEachElement(func(key cty.Value, val cty.Value) bool { + path[len(path)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(int64(i)), + } + + targetElem := target.Index(i) + err = fromCtyValue(val, targetElem, path) + if err != nil { + return true + } + + i++ + return false + }) + if err != nil { + return err + } + + path = path[:len(path)-1] + + return nil + + default: + return likelyRequiredTypesError(path, target) + + } +} + +func fromCtyMap(val cty.Value, target reflect.Value, path cty.Path) error { + + switch target.Kind() { + + case reflect.Map: + if val.IsNull() { + target.Set(reflect.Zero(target.Type())) + return nil + } + + tv := reflect.MakeMap(target.Type()) + et := target.Type().Elem() + + path = append(path, nil) + + var err error + val.ForEachElement(func(key cty.Value, val cty.Value) bool { + path[len(path)-1] = cty.IndexStep{ + Key: key, + } + + ks := key.AsString() + + targetElem := reflect.New(et) + err = fromCtyValue(val, targetElem, path) + + tv.SetMapIndex(reflect.ValueOf(ks), targetElem.Elem()) + + return err != nil + }) + if err != nil { + return err + } + + path = path[:len(path)-1] + + target.Set(tv) + return nil + + default: + return likelyRequiredTypesError(path, target) + + } +} + +func fromCtySet(val cty.Value, target reflect.Value, path cty.Path) error { + switch target.Kind() { + + case reflect.Slice: + if val.IsNull() { + target.Set(reflect.Zero(target.Type())) + return nil + } + + length := val.LengthInt() + tv := reflect.MakeSlice(target.Type(), length, length) + + i := 0 + var err error + val.ForEachElement(func(key cty.Value, val cty.Value) bool { + targetElem := tv.Index(i) + err = fromCtyValue(val, targetElem, path) + if err != nil { + return true + } + + i++ + return false + }) + if err != nil { + return err + } + + target.Set(tv) + return nil + + case reflect.Array: + if val.IsNull() { + return path.NewErrorf("null value is not allowed") + } + + length := val.LengthInt() + if length != target.Len() { + return path.NewErrorf("must be a set of length %d", target.Len()) + } + + i := 0 + var err error + val.ForEachElement(func(key cty.Value, val cty.Value) bool { + targetElem := target.Index(i) + err = fromCtyValue(val, targetElem, path) + if err != nil { + return true + } + + i++ + return false + }) + if err != nil { + return err + } + + return nil + + // TODO: decode into set.Set instance + + default: + return likelyRequiredTypesError(path, target) + + } +} + +func fromCtyObject(val cty.Value, target reflect.Value, path cty.Path) error { + + switch target.Kind() { + + case reflect.Struct: + + attrTypes := val.Type().AttributeTypes() + targetFields := structTagIndices(target.Type()) + + path = append(path, nil) + + for k, i := range targetFields { + if _, exists := attrTypes[k]; !exists { + // If the field in question isn't able to represent nil, + // that's an error. + fk := target.Field(i).Kind() + switch fk { + case reflect.Ptr, reflect.Slice, reflect.Map, reflect.Interface: + // okay + default: + return path.NewErrorf("missing required attribute %q", k) + } + } + } + + for k := range attrTypes { + path[len(path)-1] = cty.GetAttrStep{ + Name: k, + } + + fieldIdx, exists := targetFields[k] + if !exists { + return path.NewErrorf("unsupported attribute %q", k) + } + + ev := val.GetAttr(k) + + targetField := target.Field(fieldIdx) + err := fromCtyValue(ev, targetField, path) + if err != nil { + return err + } + } + + path = path[:len(path)-1] + + return nil + + default: + return likelyRequiredTypesError(path, target) + + } +} + +func fromCtyTuple(val cty.Value, target reflect.Value, path cty.Path) error { + + switch target.Kind() { + + case reflect.Struct: + + elemTypes := val.Type().TupleElementTypes() + fieldCount := target.Type().NumField() + + if fieldCount != len(elemTypes) { + return path.NewErrorf("a tuple of %d elements is required", fieldCount) + } + + path = append(path, nil) + + for i := range elemTypes { + path[len(path)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(int64(i)), + } + + ev := val.Index(cty.NumberIntVal(int64(i))) + + targetField := target.Field(i) + err := fromCtyValue(ev, targetField, path) + if err != nil { + return err + } + } + + path = path[:len(path)-1] + + return nil + + default: + return likelyRequiredTypesError(path, target) + + } +} + +func fromCtyCapsule(val cty.Value, target reflect.Value, path cty.Path) error { + + if target.Kind() == reflect.Ptr { + // Walk through indirection until we get to the last pointer, + // which we might set to null below. + target = fromCtyPopulatePtr(target, true) + + if val.IsNull() { + target.Set(reflect.Zero(target.Type())) + return nil + } + + // Since a capsule contains a pointer to an object, we'll preserve + // that pointer on the way out and thus allow the caller to recover + // the original object, rather than a copy of it. + + eType := val.Type().EncapsulatedType() + + if !eType.AssignableTo(target.Elem().Type()) { + // Our interface contract promises that we won't expose Go + // implementation details in error messages, so we need to keep + // this vague. This can only arise if a calling application has + // more than one capsule type in play and a user mixes them up. + return path.NewErrorf("incorrect type %s", val.Type().FriendlyName()) + } + + target.Set(reflect.ValueOf(val.EncapsulatedValue())) + + return nil + } else { + if val.IsNull() { + return path.NewErrorf("null value is not allowed") + } + + // If our target isn't a pointer then we will attempt to copy + // the encapsulated value into it. + + eType := val.Type().EncapsulatedType() + + if !eType.AssignableTo(target.Type()) { + // Our interface contract promises that we won't expose Go + // implementation details in error messages, so we need to keep + // this vague. This can only arise if a calling application has + // more than one capsule type in play and a user mixes them up. + return path.NewErrorf("incorrect type %s", val.Type().FriendlyName()) + } + + // We know that EncapsulatedValue is always a pointer, so we + // can safely call .Elem on its reflect.Value. + target.Set(reflect.ValueOf(val.EncapsulatedValue()).Elem()) + + return nil + } + +} + +// fromCtyPopulatePtr recognizes when target is a pointer type and allocates +// a value to assign to that pointer, which it returns. +// +// If the given value has multiple levels of indirection, like **int, these +// will be processed in turn so that the return value is guaranteed to be +// a non-pointer. +// +// As an exception, if decodingNull is true then the returned value will be +// the final level of pointer, if any, so that the caller can assign it +// as nil to represent a null value. If the given target value is not a pointer +// at all then the returned value will be just the given target, so the caller +// must test if the returned value is a pointer before trying to assign nil +// to it. +func fromCtyPopulatePtr(target reflect.Value, decodingNull bool) reflect.Value { + for { + if target.Kind() == reflect.Interface && !target.IsNil() { + e := target.Elem() + if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { + target = e + } + } + + if target.Kind() != reflect.Ptr { + break + } + + // Stop early if we're decodingNull and we've found our last indirection + if target.Elem().Kind() != reflect.Ptr && decodingNull && target.CanSet() { + break + } + + if target.IsNil() { + target.Set(reflect.New(target.Type().Elem())) + } + + target = target.Elem() + } + return target +} + +// likelyRequiredTypesError returns an error that states which types are +// acceptable by making some assumptions about what types we support for +// each target Go kind. It's not a precise science but it allows us to return +// an error message that is cty-user-oriented rather than Go-oriented. +// +// Generally these error messages should be a matter of last resort, since +// the calling application should be validating user-provided value types +// before decoding anyway. +func likelyRequiredTypesError(path cty.Path, target reflect.Value) error { + switch target.Kind() { + + case reflect.Bool: + return path.NewErrorf("bool value is required") + + case reflect.String: + return path.NewErrorf("string value is required") + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + fallthrough + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + fallthrough + case reflect.Float32, reflect.Float64: + return path.NewErrorf("number value is required") + + case reflect.Slice, reflect.Array: + return path.NewErrorf("list or set value is required") + + case reflect.Map: + return path.NewErrorf("map or object value is required") + + case reflect.Struct: + switch { + + case target.Type().AssignableTo(bigFloatType) || target.Type().AssignableTo(bigIntType): + return path.NewErrorf("number value is required") + + case target.Type().AssignableTo(setType): + return path.NewErrorf("set or list value is required") + + default: + return path.NewErrorf("object or tuple value is required") + + } + + default: + // We should avoid getting into this path, since this error + // message is rather useless. + return path.NewErrorf("incorrect type") + + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/gocty/type_implied.go b/vendor/github.com/hashicorp/go-cty/cty/gocty/type_implied.go new file mode 100644 index 00000000000..b4134253585 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/gocty/type_implied.go @@ -0,0 +1,108 @@ +package gocty + +import ( + "reflect" + + "github.com/hashicorp/go-cty/cty" +) + +// ImpliedType takes an arbitrary Go value (as an interface{}) and attempts +// to find a suitable cty.Type instance that could be used for a conversion +// with ToCtyValue. +// +// This allows -- for simple situations at least -- types to be defined just +// once in Go and the cty types derived from the Go types, but in the process +// it makes some assumptions that may be undesirable so applications are +// encouraged to build their cty types directly if exacting control is +// required. +// +// Not all Go types can be represented as cty types, so an error may be +// returned which is usually considered to be a bug in the calling program. +// In particular, ImpliedType will never use capsule types in its returned +// type, because it cannot know the capsule types supported by the calling +// program. +func ImpliedType(gv interface{}) (cty.Type, error) { + rt := reflect.TypeOf(gv) + var path cty.Path + return impliedType(rt, path) +} + +func impliedType(rt reflect.Type, path cty.Path) (cty.Type, error) { + switch rt.Kind() { + + case reflect.Ptr: + return impliedType(rt.Elem(), path) + + // Primitive types + case reflect.Bool: + return cty.Bool, nil + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return cty.Number, nil + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return cty.Number, nil + case reflect.Float32, reflect.Float64: + return cty.Number, nil + case reflect.String: + return cty.String, nil + + // Collection types + case reflect.Slice: + path := append(path, cty.IndexStep{Key: cty.UnknownVal(cty.Number)}) + ety, err := impliedType(rt.Elem(), path) + if err != nil { + return cty.NilType, err + } + return cty.List(ety), nil + case reflect.Map: + if !stringType.AssignableTo(rt.Key()) { + return cty.NilType, path.NewErrorf("no cty.Type for %s (must have string keys)", rt) + } + path := append(path, cty.IndexStep{Key: cty.UnknownVal(cty.String)}) + ety, err := impliedType(rt.Elem(), path) + if err != nil { + return cty.NilType, err + } + return cty.Map(ety), nil + + // Structural types + case reflect.Struct: + return impliedStructType(rt, path) + + default: + return cty.NilType, path.NewErrorf("no cty.Type for %s", rt) + } +} + +func impliedStructType(rt reflect.Type, path cty.Path) (cty.Type, error) { + if valueType.AssignableTo(rt) { + // Special case: cty.Value represents cty.DynamicPseudoType, for + // type conformance checking. + return cty.DynamicPseudoType, nil + } + + fieldIdxs := structTagIndices(rt) + if len(fieldIdxs) == 0 { + return cty.NilType, path.NewErrorf("no cty.Type for %s (no cty field tags)", rt) + } + + atys := make(map[string]cty.Type, len(fieldIdxs)) + + { + // Temporary extension of path for attributes + path := append(path, nil) + + for k, fi := range fieldIdxs { + path[len(path)-1] = cty.GetAttrStep{Name: k} + + ft := rt.Field(fi).Type + aty, err := impliedType(ft, path) + if err != nil { + return cty.NilType, err + } + + atys[k] = aty + } + } + + return cty.Object(atys), nil +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/helper.go b/vendor/github.com/hashicorp/go-cty/cty/helper.go new file mode 100644 index 00000000000..1b88e9fa082 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/helper.go @@ -0,0 +1,99 @@ +package cty + +import ( + "fmt" +) + +// anyUnknown is a helper to easily check if a set of values contains any +// unknowns, for operations that short-circuit to return unknown in that case. +func anyUnknown(values ...Value) bool { + for _, val := range values { + if val.v == unknown { + return true + } + } + return false +} + +// typeCheck tests whether all of the given values belong to the given type. +// If the given types are a mixture of the given type and the dynamic +// pseudo-type then a short-circuit dynamic value is returned. If the given +// values are all of the correct type but at least one is unknown then +// a short-circuit unknown value is returned. If any other types appear then +// an error is returned. Otherwise (finally!) the result is nil, nil. +func typeCheck(required Type, ret Type, values ...Value) (shortCircuit *Value, err error) { + hasDynamic := false + hasUnknown := false + + for i, val := range values { + if val.ty == DynamicPseudoType { + hasDynamic = true + continue + } + + if !val.Type().Equals(required) { + return nil, fmt.Errorf( + "type mismatch: want %s but value %d is %s", + required.FriendlyName(), + i, val.ty.FriendlyName(), + ) + } + + if val.v == unknown { + hasUnknown = true + } + } + + if hasDynamic { + return &DynamicVal, nil + } + + if hasUnknown { + ret := UnknownVal(ret) + return &ret, nil + } + + return nil, nil +} + +// mustTypeCheck is a wrapper around typeCheck that immediately panics if +// any error is returned. +func mustTypeCheck(required Type, ret Type, values ...Value) *Value { + shortCircuit, err := typeCheck(required, ret, values...) + if err != nil { + panic(err) + } + return shortCircuit +} + +// shortCircuitForceType takes the return value from mustTypeCheck and +// replaces it with an unknown of the given type if the original value was +// DynamicVal. +// +// This is useful for operations that are specified to always return a +// particular type, since then a dynamic result can safely be "upgrade" to +// a strongly-typed unknown, which then allows subsequent operations to +// be actually type-checked. +// +// It is safe to use this only if the operation in question is defined as +// returning either a value of the given type or panicking, since we know +// then that subsequent operations won't run if the operation panics. +// +// If the given short-circuit value is *not* DynamicVal then it must be +// of the given type, or this function will panic. +func forceShortCircuitType(shortCircuit *Value, ty Type) *Value { + if shortCircuit == nil { + return nil + } + + if shortCircuit.ty == DynamicPseudoType { + ret := UnknownVal(ty) + return &ret + } + + if !shortCircuit.ty.Equals(ty) { + panic("forceShortCircuitType got value of wrong type") + } + + return shortCircuit +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/json.go b/vendor/github.com/hashicorp/go-cty/cty/json.go new file mode 100644 index 00000000000..c421a62ed94 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/json.go @@ -0,0 +1,176 @@ +package cty + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// MarshalJSON is an implementation of json.Marshaler that allows Type +// instances to be serialized as JSON. +// +// All standard types can be serialized, but capsule types cannot since there +// is no way to automatically recover the original pointer and capsule types +// compare by equality. +func (t Type) MarshalJSON() ([]byte, error) { + switch impl := t.typeImpl.(type) { + case primitiveType: + switch impl.Kind { + case primitiveTypeBool: + return []byte{'"', 'b', 'o', 'o', 'l', '"'}, nil + case primitiveTypeNumber: + return []byte{'"', 'n', 'u', 'm', 'b', 'e', 'r', '"'}, nil + case primitiveTypeString: + return []byte{'"', 's', 't', 'r', 'i', 'n', 'g', '"'}, nil + default: + panic("unknown primitive type kind") + } + case typeList, typeMap, typeSet: + buf := &bytes.Buffer{} + etyJSON, err := t.ElementType().MarshalJSON() + if err != nil { + return nil, err + } + buf.WriteRune('[') + switch impl.(type) { + case typeList: + buf.WriteString(`"list"`) + case typeMap: + buf.WriteString(`"map"`) + case typeSet: + buf.WriteString(`"set"`) + } + buf.WriteRune(',') + buf.Write(etyJSON) + buf.WriteRune(']') + return buf.Bytes(), nil + case typeObject: + buf := &bytes.Buffer{} + atysJSON, err := json.Marshal(t.AttributeTypes()) + if err != nil { + return nil, err + } + buf.WriteString(`["object",`) + buf.Write(atysJSON) + buf.WriteRune(']') + return buf.Bytes(), nil + case typeTuple: + buf := &bytes.Buffer{} + etysJSON, err := json.Marshal(t.TupleElementTypes()) + if err != nil { + return nil, err + } + buf.WriteString(`["tuple",`) + buf.Write(etysJSON) + buf.WriteRune(']') + return buf.Bytes(), nil + case pseudoTypeDynamic: + return []byte{'"', 'd', 'y', 'n', 'a', 'm', 'i', 'c', '"'}, nil + case *capsuleType: + return nil, fmt.Errorf("type not allowed: %s", t.FriendlyName()) + default: + // should never happen + panic("unknown type implementation") + } +} + +// UnmarshalJSON is the opposite of MarshalJSON. See the documentation of +// MarshalJSON for information on the limitations of JSON serialization of +// types. +func (t *Type) UnmarshalJSON(buf []byte) error { + r := bytes.NewReader(buf) + dec := json.NewDecoder(r) + + tok, err := dec.Token() + if err != nil { + return err + } + + switch v := tok.(type) { + case string: + switch v { + case "bool": + *t = Bool + case "number": + *t = Number + case "string": + *t = String + case "dynamic": + *t = DynamicPseudoType + default: + return fmt.Errorf("invalid primitive type name %q", v) + } + + if dec.More() { + return fmt.Errorf("extraneous data after type description") + } + return nil + case json.Delim: + if rune(v) != '[' { + return fmt.Errorf("invalid complex type description") + } + + tok, err = dec.Token() + if err != nil { + return err + } + + kind, ok := tok.(string) + if !ok { + return fmt.Errorf("invalid complex type kind name") + } + + switch kind { + case "list": + var ety Type + err = dec.Decode(&ety) + if err != nil { + return err + } + *t = List(ety) + case "map": + var ety Type + err = dec.Decode(&ety) + if err != nil { + return err + } + *t = Map(ety) + case "set": + var ety Type + err = dec.Decode(&ety) + if err != nil { + return err + } + *t = Set(ety) + case "object": + var atys map[string]Type + err = dec.Decode(&atys) + if err != nil { + return err + } + *t = Object(atys) + case "tuple": + var etys []Type + err = dec.Decode(&etys) + if err != nil { + return err + } + *t = Tuple(etys) + default: + return fmt.Errorf("invalid complex type kind name") + } + + tok, err = dec.Token() + if err != nil { + return err + } + if delim, ok := tok.(json.Delim); !ok || rune(delim) != ']' || dec.More() { + return fmt.Errorf("unexpected extra data in type description") + } + + return nil + + default: + return fmt.Errorf("invalid type description") + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/json/doc.go b/vendor/github.com/hashicorp/go-cty/cty/json/doc.go new file mode 100644 index 00000000000..8916513d673 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/json/doc.go @@ -0,0 +1,11 @@ +// Package json provides functions for serializing cty types and values in +// JSON format, and for decoding them again. +// +// Since the cty type system is a superset of the JSON type system, +// round-tripping through JSON is lossy unless type information is provided +// both at encoding time and decoding time. Callers of this package are +// therefore suggested to define their expected structure as a cty.Type +// and pass it in consistently both when encoding and when decoding, though +// default (type-lossy) behavior is provided for situations where the precise +// representation of the data is not significant. +package json diff --git a/vendor/github.com/hashicorp/go-cty/cty/json/marshal.go b/vendor/github.com/hashicorp/go-cty/cty/json/marshal.go new file mode 100644 index 00000000000..728ab0100f8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/json/marshal.go @@ -0,0 +1,193 @@ +package json + +import ( + "bytes" + "encoding/json" + "sort" + + "github.com/hashicorp/go-cty/cty" +) + +func marshal(val cty.Value, t cty.Type, path cty.Path, b *bytes.Buffer) error { + if val.IsMarked() { + return path.NewErrorf("value has marks, so it cannot be seralized") + } + + // If we're going to decode as DynamicPseudoType then we need to save + // dynamic type information to recover the real type. + if t == cty.DynamicPseudoType && val.Type() != cty.DynamicPseudoType { + return marshalDynamic(val, path, b) + } + + if val.IsNull() { + b.WriteString("null") + return nil + } + + if !val.IsKnown() { + return path.NewErrorf("value is not known") + } + + // The caller should've guaranteed that the given val is conformant with + // the given type t, so we'll proceed under that assumption here. + + switch { + case t.IsPrimitiveType(): + switch t { + case cty.String: + json, err := json.Marshal(val.AsString()) + if err != nil { + return path.NewErrorf("failed to serialize value: %s", err) + } + b.Write(json) + return nil + case cty.Number: + if val.RawEquals(cty.PositiveInfinity) || val.RawEquals(cty.NegativeInfinity) { + return path.NewErrorf("cannot serialize infinity as JSON") + } + b.WriteString(val.AsBigFloat().Text('f', -1)) + return nil + case cty.Bool: + if val.True() { + b.WriteString("true") + } else { + b.WriteString("false") + } + return nil + default: + panic("unsupported primitive type") + } + case t.IsListType(), t.IsSetType(): + b.WriteRune('[') + first := true + ety := t.ElementType() + it := val.ElementIterator() + path := append(path, nil) // local override of 'path' with extra element + for it.Next() { + if !first { + b.WriteRune(',') + } + ek, ev := it.Element() + path[len(path)-1] = cty.IndexStep{ + Key: ek, + } + err := marshal(ev, ety, path, b) + if err != nil { + return err + } + first = false + } + b.WriteRune(']') + return nil + case t.IsMapType(): + b.WriteRune('{') + first := true + ety := t.ElementType() + it := val.ElementIterator() + path := append(path, nil) // local override of 'path' with extra element + for it.Next() { + if !first { + b.WriteRune(',') + } + ek, ev := it.Element() + path[len(path)-1] = cty.IndexStep{ + Key: ek, + } + var err error + err = marshal(ek, ek.Type(), path, b) + if err != nil { + return err + } + b.WriteRune(':') + err = marshal(ev, ety, path, b) + if err != nil { + return err + } + first = false + } + b.WriteRune('}') + return nil + case t.IsTupleType(): + b.WriteRune('[') + etys := t.TupleElementTypes() + it := val.ElementIterator() + path := append(path, nil) // local override of 'path' with extra element + i := 0 + for it.Next() { + if i > 0 { + b.WriteRune(',') + } + ety := etys[i] + ek, ev := it.Element() + path[len(path)-1] = cty.IndexStep{ + Key: ek, + } + err := marshal(ev, ety, path, b) + if err != nil { + return err + } + i++ + } + b.WriteRune(']') + return nil + case t.IsObjectType(): + b.WriteRune('{') + atys := t.AttributeTypes() + path := append(path, nil) // local override of 'path' with extra element + + names := make([]string, 0, len(atys)) + for k := range atys { + names = append(names, k) + } + sort.Strings(names) + + for i, k := range names { + aty := atys[k] + if i > 0 { + b.WriteRune(',') + } + av := val.GetAttr(k) + path[len(path)-1] = cty.GetAttrStep{ + Name: k, + } + var err error + err = marshal(cty.StringVal(k), cty.String, path, b) + if err != nil { + return err + } + b.WriteRune(':') + err = marshal(av, aty, path, b) + if err != nil { + return err + } + } + b.WriteRune('}') + return nil + case t.IsCapsuleType(): + rawVal := val.EncapsulatedValue() + jsonVal, err := json.Marshal(rawVal) + if err != nil { + return path.NewError(err) + } + b.Write(jsonVal) + return nil + default: + // should never happen + return path.NewErrorf("cannot JSON-serialize %s", t.FriendlyName()) + } +} + +// marshalDynamic adds an extra wrapping object containing dynamic type +// information for the given value. +func marshalDynamic(val cty.Value, path cty.Path, b *bytes.Buffer) error { + typeJSON, err := MarshalType(val.Type()) + if err != nil { + return path.NewErrorf("failed to serialize type: %s", err) + } + b.WriteString(`{"value":`) + marshal(val, val.Type(), path, b) + b.WriteString(`,"type":`) + b.Write(typeJSON) + b.WriteRune('}') + return nil +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/json/simple.go b/vendor/github.com/hashicorp/go-cty/cty/json/simple.go new file mode 100644 index 00000000000..aaba8c3bdec --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/json/simple.go @@ -0,0 +1,41 @@ +package json + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// SimpleJSONValue is a wrapper around cty.Value that adds implementations of +// json.Marshaler and json.Unmarshaler for simple-but-type-lossy automatic +// encoding and decoding of values. +// +// The couplet Marshal and Unmarshal both take extra type information to +// inform the encoding and decoding process so that all of the cty types +// can be represented even though JSON's type system is a subset. +// +// SimpleJSONValue instead takes the approach of discarding the value's type +// information and then deriving a new type from the stored structure when +// decoding. This results in the same data being returned but not necessarily +// with exactly the same type. +// +// For information on how types are inferred when decoding, see the +// documentation of the function ImpliedType. +type SimpleJSONValue struct { + cty.Value +} + +// MarshalJSON is an implementation of json.Marshaler. See the documentation +// of SimpleJSONValue for more information. +func (v SimpleJSONValue) MarshalJSON() ([]byte, error) { + return Marshal(v.Value, v.Type()) +} + +// UnmarshalJSON is an implementation of json.Unmarshaler. See the +// documentation of SimpleJSONValue for more information. +func (v *SimpleJSONValue) UnmarshalJSON(buf []byte) error { + t, err := ImpliedType(buf) + if err != nil { + return err + } + v.Value, err = Unmarshal(buf, t) + return err +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/json/type.go b/vendor/github.com/hashicorp/go-cty/cty/json/type.go new file mode 100644 index 00000000000..59d7f2e17f2 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/json/type.go @@ -0,0 +1,23 @@ +package json + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// MarshalType returns a JSON serialization of the given type. +// +// This is just a thin wrapper around t.MarshalJSON, for symmetry with +// UnmarshalType. +func MarshalType(t cty.Type) ([]byte, error) { + return t.MarshalJSON() +} + +// UnmarshalType decodes a JSON serialization of the given type as produced +// by either Type.MarshalJSON or MarshalType. +// +// This is a convenience wrapper around Type.UnmarshalJSON. +func UnmarshalType(buf []byte) (cty.Type, error) { + var t cty.Type + err := t.UnmarshalJSON(buf) + return t, err +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/json/type_implied.go b/vendor/github.com/hashicorp/go-cty/cty/json/type_implied.go new file mode 100644 index 00000000000..8adf22bbe99 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/json/type_implied.go @@ -0,0 +1,170 @@ +package json + +import ( + "bytes" + "encoding/json" + "fmt" + + "github.com/hashicorp/go-cty/cty" +) + +// ImpliedType returns the cty Type implied by the structure of the given +// JSON-compliant buffer. This function implements the default type mapping +// behavior used when decoding arbitrary JSON without explicit cty Type +// information. +// +// The rules are as follows: +// +// JSON strings, numbers and bools map to their equivalent primitive type in +// cty. +// +// JSON objects map to cty object types, with the attributes defined by the +// object keys and the types of their values. +// +// JSON arrays map to cty tuple types, with the elements defined by the +// types of the array members. +// +// Any nulls are typed as DynamicPseudoType, so callers of this function +// must be prepared to deal with this. Callers that do not wish to deal with +// dynamic typing should not use this function and should instead describe +// their required types explicitly with a cty.Type instance when decoding. +// +// Any JSON syntax errors will be returned as an error, and the type will +// be the invalid value cty.NilType. +func ImpliedType(buf []byte) (cty.Type, error) { + r := bytes.NewReader(buf) + dec := json.NewDecoder(r) + dec.UseNumber() + + ty, err := impliedType(dec) + if err != nil { + return cty.NilType, err + } + + if dec.More() { + return cty.NilType, fmt.Errorf("extraneous data after JSON object") + } + + return ty, nil +} + +func impliedType(dec *json.Decoder) (cty.Type, error) { + tok, err := dec.Token() + if err != nil { + return cty.NilType, err + } + + return impliedTypeForTok(tok, dec) +} + +func impliedTypeForTok(tok json.Token, dec *json.Decoder) (cty.Type, error) { + if tok == nil { + return cty.DynamicPseudoType, nil + } + + switch ttok := tok.(type) { + case bool: + return cty.Bool, nil + + case json.Number: + return cty.Number, nil + + case string: + return cty.String, nil + + case json.Delim: + + switch rune(ttok) { + case '{': + return impliedObjectType(dec) + case '[': + return impliedTupleType(dec) + default: + return cty.NilType, fmt.Errorf("unexpected token %q", ttok) + } + + default: + return cty.NilType, fmt.Errorf("unsupported JSON token %#v", tok) + } +} + +func impliedObjectType(dec *json.Decoder) (cty.Type, error) { + // By the time we get in here, we've already consumed the { delimiter + // and so our next token should be the first object key. + + var atys map[string]cty.Type + + for { + // Read the object key first + tok, err := dec.Token() + if err != nil { + return cty.NilType, err + } + + if ttok, ok := tok.(json.Delim); ok { + if rune(ttok) != '}' { + return cty.NilType, fmt.Errorf("unexpected delimiter %q", ttok) + } + break + } + + key, ok := tok.(string) + if !ok { + return cty.NilType, fmt.Errorf("expected string but found %T", tok) + } + + // Now read the value + tok, err = dec.Token() + if err != nil { + return cty.NilType, err + } + + aty, err := impliedTypeForTok(tok, dec) + if err != nil { + return cty.NilType, err + } + + if atys == nil { + atys = make(map[string]cty.Type) + } + atys[key] = aty + } + + if len(atys) == 0 { + return cty.EmptyObject, nil + } + + return cty.Object(atys), nil +} + +func impliedTupleType(dec *json.Decoder) (cty.Type, error) { + // By the time we get in here, we've already consumed the [ delimiter + // and so our next token should be the first value. + + var etys []cty.Type + + for { + tok, err := dec.Token() + if err != nil { + return cty.NilType, err + } + + if ttok, ok := tok.(json.Delim); ok { + if rune(ttok) == ']' { + break + } + } + + ety, err := impliedTypeForTok(tok, dec) + if err != nil { + return cty.NilType, err + } + etys = append(etys, ety) + } + + if len(etys) == 0 { + return cty.EmptyTuple, nil + } + + return cty.Tuple(etys), nil +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/json/unmarshal.go b/vendor/github.com/hashicorp/go-cty/cty/json/unmarshal.go new file mode 100644 index 00000000000..5ad190d33b5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/json/unmarshal.go @@ -0,0 +1,459 @@ +package json + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" + + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/go-cty/cty/convert" +) + +func unmarshal(buf []byte, t cty.Type, path cty.Path) (cty.Value, error) { + dec := bufDecoder(buf) + + tok, err := dec.Token() + if err != nil { + return cty.NilVal, path.NewError(err) + } + + if tok == nil { + return cty.NullVal(t), nil + } + + if t == cty.DynamicPseudoType { + return unmarshalDynamic(buf, path) + } + + switch { + case t.IsPrimitiveType(): + val, err := unmarshalPrimitive(tok, t, path) + if err != nil { + return cty.NilVal, err + } + return val, nil + case t.IsListType(): + return unmarshalList(buf, t.ElementType(), path) + case t.IsSetType(): + return unmarshalSet(buf, t.ElementType(), path) + case t.IsMapType(): + return unmarshalMap(buf, t.ElementType(), path) + case t.IsTupleType(): + return unmarshalTuple(buf, t.TupleElementTypes(), path) + case t.IsObjectType(): + return unmarshalObject(buf, t.AttributeTypes(), path) + case t.IsCapsuleType(): + return unmarshalCapsule(buf, t, path) + default: + return cty.NilVal, path.NewErrorf("unsupported type %s", t.FriendlyName()) + } +} + +func unmarshalPrimitive(tok json.Token, t cty.Type, path cty.Path) (cty.Value, error) { + + switch t { + case cty.Bool: + switch v := tok.(type) { + case bool: + return cty.BoolVal(v), nil + case string: + val, err := convert.Convert(cty.StringVal(v), t) + if err != nil { + return cty.NilVal, path.NewError(err) + } + return val, nil + default: + return cty.NilVal, path.NewErrorf("bool is required") + } + case cty.Number: + if v, ok := tok.(json.Number); ok { + tok = string(v) + } + switch v := tok.(type) { + case string: + val, err := cty.ParseNumberVal(v) + if err != nil { + return cty.NilVal, path.NewError(err) + } + return val, nil + default: + return cty.NilVal, path.NewErrorf("number is required") + } + case cty.String: + switch v := tok.(type) { + case string: + return cty.StringVal(v), nil + case json.Number: + return cty.StringVal(string(v)), nil + case bool: + val, err := convert.Convert(cty.BoolVal(v), t) + if err != nil { + return cty.NilVal, path.NewError(err) + } + return val, nil + default: + return cty.NilVal, path.NewErrorf("string is required") + } + default: + // should never happen + panic("unsupported primitive type") + } +} + +func unmarshalList(buf []byte, ety cty.Type, path cty.Path) (cty.Value, error) { + dec := bufDecoder(buf) + if err := requireDelim(dec, '['); err != nil { + return cty.NilVal, path.NewError(err) + } + + var vals []cty.Value + + { + path := append(path, nil) + var idx int64 + + for dec.More() { + path[len(path)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(idx), + } + idx++ + + rawVal, err := readRawValue(dec) + if err != nil { + return cty.NilVal, path.NewErrorf("failed to read list value: %s", err) + } + + el, err := unmarshal(rawVal, ety, path) + if err != nil { + return cty.NilVal, err + } + + vals = append(vals, el) + } + } + + if err := requireDelim(dec, ']'); err != nil { + return cty.NilVal, path.NewError(err) + } + + if len(vals) == 0 { + return cty.ListValEmpty(ety), nil + } + + return cty.ListVal(vals), nil +} + +func unmarshalSet(buf []byte, ety cty.Type, path cty.Path) (cty.Value, error) { + dec := bufDecoder(buf) + if err := requireDelim(dec, '['); err != nil { + return cty.NilVal, path.NewError(err) + } + + var vals []cty.Value + + { + path := append(path, nil) + + for dec.More() { + path[len(path)-1] = cty.IndexStep{ + Key: cty.UnknownVal(ety), + } + + rawVal, err := readRawValue(dec) + if err != nil { + return cty.NilVal, path.NewErrorf("failed to read set value: %s", err) + } + + el, err := unmarshal(rawVal, ety, path) + if err != nil { + return cty.NilVal, err + } + + vals = append(vals, el) + } + } + + if err := requireDelim(dec, ']'); err != nil { + return cty.NilVal, path.NewError(err) + } + + if len(vals) == 0 { + return cty.SetValEmpty(ety), nil + } + + return cty.SetVal(vals), nil +} + +func unmarshalMap(buf []byte, ety cty.Type, path cty.Path) (cty.Value, error) { + dec := bufDecoder(buf) + if err := requireDelim(dec, '{'); err != nil { + return cty.NilVal, path.NewError(err) + } + + vals := make(map[string]cty.Value) + + { + path := append(path, nil) + + for dec.More() { + path[len(path)-1] = cty.IndexStep{ + Key: cty.UnknownVal(cty.String), + } + + var err error + + k, err := requireObjectKey(dec) + if err != nil { + return cty.NilVal, path.NewErrorf("failed to read map key: %s", err) + } + + path[len(path)-1] = cty.IndexStep{ + Key: cty.StringVal(k), + } + + rawVal, err := readRawValue(dec) + if err != nil { + return cty.NilVal, path.NewErrorf("failed to read map value: %s", err) + } + + el, err := unmarshal(rawVal, ety, path) + if err != nil { + return cty.NilVal, err + } + + vals[k] = el + } + } + + if err := requireDelim(dec, '}'); err != nil { + return cty.NilVal, path.NewError(err) + } + + if len(vals) == 0 { + return cty.MapValEmpty(ety), nil + } + + return cty.MapVal(vals), nil +} + +func unmarshalTuple(buf []byte, etys []cty.Type, path cty.Path) (cty.Value, error) { + dec := bufDecoder(buf) + if err := requireDelim(dec, '['); err != nil { + return cty.NilVal, path.NewError(err) + } + + var vals []cty.Value + + { + path := append(path, nil) + var idx int + + for dec.More() { + if idx >= len(etys) { + return cty.NilVal, path[:len(path)-1].NewErrorf("too many tuple elements (need %d)", len(etys)) + } + + path[len(path)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(int64(idx)), + } + ety := etys[idx] + idx++ + + rawVal, err := readRawValue(dec) + if err != nil { + return cty.NilVal, path.NewErrorf("failed to read tuple value: %s", err) + } + + el, err := unmarshal(rawVal, ety, path) + if err != nil { + return cty.NilVal, err + } + + vals = append(vals, el) + } + } + + if err := requireDelim(dec, ']'); err != nil { + return cty.NilVal, path.NewError(err) + } + + if len(vals) != len(etys) { + return cty.NilVal, path[:len(path)-1].NewErrorf("not enough tuple elements (need %d)", len(etys)) + } + + if len(vals) == 0 { + return cty.EmptyTupleVal, nil + } + + return cty.TupleVal(vals), nil +} + +func unmarshalObject(buf []byte, atys map[string]cty.Type, path cty.Path) (cty.Value, error) { + dec := bufDecoder(buf) + if err := requireDelim(dec, '{'); err != nil { + return cty.NilVal, path.NewError(err) + } + + vals := make(map[string]cty.Value) + + { + objPath := path // some errors report from the object's perspective + path := append(path, nil) // path to a specific attribute + + for dec.More() { + + var err error + + k, err := requireObjectKey(dec) + if err != nil { + return cty.NilVal, path.NewErrorf("failed to read object key: %s", err) + } + + aty, ok := atys[k] + if !ok { + return cty.NilVal, objPath.NewErrorf("unsupported attribute %q", k) + } + + path[len(path)-1] = cty.GetAttrStep{ + Name: k, + } + + rawVal, err := readRawValue(dec) + if err != nil { + return cty.NilVal, path.NewErrorf("failed to read object value: %s", err) + } + + el, err := unmarshal(rawVal, aty, path) + if err != nil { + return cty.NilVal, err + } + + vals[k] = el + } + } + + if err := requireDelim(dec, '}'); err != nil { + return cty.NilVal, path.NewError(err) + } + + // Make sure we have a value for every attribute + for k, aty := range atys { + if _, exists := vals[k]; !exists { + vals[k] = cty.NullVal(aty) + } + } + + if len(vals) == 0 { + return cty.EmptyObjectVal, nil + } + + return cty.ObjectVal(vals), nil +} + +func unmarshalCapsule(buf []byte, t cty.Type, path cty.Path) (cty.Value, error) { + rawType := t.EncapsulatedType() + ptrPtr := reflect.New(reflect.PtrTo(rawType)) + ptrPtr.Elem().Set(reflect.New(rawType)) + ptr := ptrPtr.Elem().Interface() + err := json.Unmarshal(buf, ptr) + if err != nil { + return cty.NilVal, path.NewError(err) + } + + return cty.CapsuleVal(t, ptr), nil +} + +func unmarshalDynamic(buf []byte, path cty.Path) (cty.Value, error) { + dec := bufDecoder(buf) + if err := requireDelim(dec, '{'); err != nil { + return cty.NilVal, path.NewError(err) + } + + var t cty.Type + var valBody []byte // defer actual decoding until we know the type + + for dec.More() { + var err error + + key, err := requireObjectKey(dec) + if err != nil { + return cty.NilVal, path.NewErrorf("failed to read dynamic type descriptor key: %s", err) + } + + rawVal, err := readRawValue(dec) + if err != nil { + return cty.NilVal, path.NewErrorf("failed to read dynamic type descriptor value: %s", err) + } + + switch key { + case "type": + err := json.Unmarshal(rawVal, &t) + if err != nil { + return cty.NilVal, path.NewErrorf("failed to decode type for dynamic value: %s", err) + } + case "value": + valBody = rawVal + default: + return cty.NilVal, path.NewErrorf("invalid key %q in dynamically-typed value", key) + } + + } + + if err := requireDelim(dec, '}'); err != nil { + return cty.NilVal, path.NewError(err) + } + + if t == cty.NilType { + return cty.NilVal, path.NewErrorf("missing type in dynamically-typed value") + } + if valBody == nil { + return cty.NilVal, path.NewErrorf("missing value in dynamically-typed value") + } + + val, err := Unmarshal([]byte(valBody), t) + if err != nil { + return cty.NilVal, path.NewError(err) + } + return val, nil +} + +func requireDelim(dec *json.Decoder, d rune) error { + tok, err := dec.Token() + if err != nil { + return err + } + + if tok != json.Delim(d) { + return fmt.Errorf("missing expected %c", d) + } + + return nil +} + +func requireObjectKey(dec *json.Decoder) (string, error) { + tok, err := dec.Token() + if err != nil { + return "", err + } + if s, ok := tok.(string); ok { + return s, nil + } + return "", fmt.Errorf("missing expected object key") +} + +func readRawValue(dec *json.Decoder) ([]byte, error) { + var rawVal json.RawMessage + err := dec.Decode(&rawVal) + if err != nil { + return nil, err + } + return []byte(rawVal), nil +} + +func bufDecoder(buf []byte) *json.Decoder { + r := bytes.NewReader(buf) + dec := json.NewDecoder(r) + dec.UseNumber() + return dec +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/json/value.go b/vendor/github.com/hashicorp/go-cty/cty/json/value.go new file mode 100644 index 00000000000..50748f70903 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/json/value.go @@ -0,0 +1,65 @@ +package json + +import ( + "bytes" + + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/go-cty/cty/convert" +) + +// Marshal produces a JSON representation of the given value that can later +// be decoded into a value of the given type. +// +// A type is specified separately to allow for the given type to include +// cty.DynamicPseudoType to represent situations where any type is permitted +// and so type information must be included to allow recovery of the stored +// structure when decoding. +// +// The given type will also be used to attempt automatic conversions of any +// non-conformant types in the given value, although this will not always +// be possible. If the value cannot be made to be conformant then an error is +// returned, which may be a cty.PathError. +// +// Capsule-typed values can be marshalled, but with some caveats. Since +// capsule values are compared by pointer equality, it is impossible to recover +// a value that will compare equal to the original value. Additionally, +// it's not possible to JSON-serialize the capsule type itself, so it's not +// valid to use capsule types within parts of the value that are conformed to +// cty.DynamicPseudoType. Otherwise, a capsule value can be used as long as +// the encapsulated type itself is serializable with the Marshal function +// in encoding/json. +func Marshal(val cty.Value, t cty.Type) ([]byte, error) { + errs := val.Type().TestConformance(t) + if errs != nil { + // Attempt a conversion + var err error + val, err = convert.Convert(val, t) + if err != nil { + return nil, err + } + } + + // From this point onward, val can be assumed to be conforming to t. + + buf := &bytes.Buffer{} + var path cty.Path + err := marshal(val, t, path, buf) + + if err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +// Unmarshal decodes a JSON representation of the given value into a cty Value +// conforming to the given type. +// +// While decoding, type conversions will be done where possible to make +// the result conformant even if the types given in JSON are not exactly +// correct. If conversion isn't possible then an error is returned, which +// may be a cty.PathError. +func Unmarshal(buf []byte, t cty.Type) (cty.Value, error) { + var path cty.Path + return unmarshal(buf, t, path) +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/list_type.go b/vendor/github.com/hashicorp/go-cty/cty/list_type.go new file mode 100644 index 00000000000..2ef02a12f3e --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/list_type.go @@ -0,0 +1,74 @@ +package cty + +import ( + "fmt" +) + +// TypeList instances represent specific list types. Each distinct ElementType +// creates a distinct, non-equal list type. +type typeList struct { + typeImplSigil + ElementTypeT Type +} + +// List creates a map type with the given element Type. +// +// List types are CollectionType implementations. +func List(elem Type) Type { + return Type{ + typeList{ + ElementTypeT: elem, + }, + } +} + +// Equals returns true if the other Type is a list whose element type is +// equal to that of the receiver. +func (t typeList) Equals(other Type) bool { + ot, isList := other.typeImpl.(typeList) + if !isList { + return false + } + + return t.ElementTypeT.Equals(ot.ElementTypeT) +} + +func (t typeList) FriendlyName(mode friendlyTypeNameMode) string { + elemName := t.ElementTypeT.friendlyNameMode(mode) + if mode == friendlyTypeConstraintName { + if t.ElementTypeT == DynamicPseudoType { + elemName = "any single type" + } + } + return "list of " + elemName +} + +func (t typeList) ElementType() Type { + return t.ElementTypeT +} + +func (t typeList) GoString() string { + return fmt.Sprintf("cty.List(%#v)", t.ElementTypeT) +} + +// IsListType returns true if the given type is a list type, regardless of its +// element type. +func (t Type) IsListType() bool { + _, ok := t.typeImpl.(typeList) + return ok +} + +// ListElementType is a convenience method that checks if the given type is +// a list type, returning a pointer to its element type if so and nil +// otherwise. This is intended to allow convenient conditional branches, +// like so: +// +// if et := t.ListElementType(); et != nil { +// // Do something with *et +// } +func (t Type) ListElementType() *Type { + if lt, ok := t.typeImpl.(typeList); ok { + return <.ElementTypeT + } + return nil +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/map_type.go b/vendor/github.com/hashicorp/go-cty/cty/map_type.go new file mode 100644 index 00000000000..82d36c6282a --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/map_type.go @@ -0,0 +1,74 @@ +package cty + +import ( + "fmt" +) + +// TypeList instances represent specific list types. Each distinct ElementType +// creates a distinct, non-equal list type. +type typeMap struct { + typeImplSigil + ElementTypeT Type +} + +// Map creates a map type with the given element Type. +// +// Map types are CollectionType implementations. +func Map(elem Type) Type { + return Type{ + typeMap{ + ElementTypeT: elem, + }, + } +} + +// Equals returns true if the other Type is a map whose element type is +// equal to that of the receiver. +func (t typeMap) Equals(other Type) bool { + ot, isMap := other.typeImpl.(typeMap) + if !isMap { + return false + } + + return t.ElementTypeT.Equals(ot.ElementTypeT) +} + +func (t typeMap) FriendlyName(mode friendlyTypeNameMode) string { + elemName := t.ElementTypeT.friendlyNameMode(mode) + if mode == friendlyTypeConstraintName { + if t.ElementTypeT == DynamicPseudoType { + elemName = "any single type" + } + } + return "map of " + elemName +} + +func (t typeMap) ElementType() Type { + return t.ElementTypeT +} + +func (t typeMap) GoString() string { + return fmt.Sprintf("cty.Map(%#v)", t.ElementTypeT) +} + +// IsMapType returns true if the given type is a list type, regardless of its +// element type. +func (t Type) IsMapType() bool { + _, ok := t.typeImpl.(typeMap) + return ok +} + +// MapElementType is a convenience method that checks if the given type is +// a map type, returning a pointer to its element type if so and nil +// otherwise. This is intended to allow convenient conditional branches, +// like so: +// +// if et := t.MapElementType(); et != nil { +// // Do something with *et +// } +func (t Type) MapElementType() *Type { + if lt, ok := t.typeImpl.(typeMap); ok { + return <.ElementTypeT + } + return nil +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/marks.go b/vendor/github.com/hashicorp/go-cty/cty/marks.go new file mode 100644 index 00000000000..3898e455335 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/marks.go @@ -0,0 +1,296 @@ +package cty + +import ( + "fmt" + "strings" +) + +// marker is an internal wrapper type used to add special "marks" to values. +// +// A "mark" is an annotation that can be used to represent additional +// characteristics of values that propagate through operation methods to +// result values. However, a marked value cannot be used with integration +// methods normally associated with its type, in order to ensure that +// calling applications don't inadvertently drop marks as they round-trip +// values out of cty and back in again. +// +// Marked values are created only explicitly by the calling application, so +// an application that never marks a value does not need to worry about +// encountering marked values. +type marker struct { + realV interface{} + marks ValueMarks +} + +// ValueMarks is a map, representing a set, of "mark" values associated with +// a Value. See Value.Mark for more information on the usage of mark values. +type ValueMarks map[interface{}]struct{} + +// NewValueMarks constructs a new ValueMarks set with the given mark values. +func NewValueMarks(marks ...interface{}) ValueMarks { + if len(marks) == 0 { + return nil + } + ret := make(ValueMarks, len(marks)) + for _, v := range marks { + ret[v] = struct{}{} + } + return ret +} + +// Equal returns true if the receiver and the given ValueMarks both contain +// the same marks. +func (m ValueMarks) Equal(o ValueMarks) bool { + if len(m) != len(o) { + return false + } + for v := range m { + if _, ok := o[v]; !ok { + return false + } + } + return true +} + +func (m ValueMarks) GoString() string { + var s strings.Builder + s.WriteString("cty.NewValueMarks(") + i := 0 + for mv := range m { + if i != 0 { + s.WriteString(", ") + } + s.WriteString(fmt.Sprintf("%#v", mv)) + i++ + } + s.WriteString(")") + return s.String() +} + +// IsMarked returns true if and only if the receiving value carries at least +// one mark. A marked value cannot be used directly with integration methods +// without explicitly unmarking it (and retrieving the markings) first. +func (val Value) IsMarked() bool { + _, ok := val.v.(marker) + return ok +} + +// HasMark returns true if and only if the receiving value has the given mark. +func (val Value) HasMark(mark interface{}) bool { + if mr, ok := val.v.(marker); ok { + _, ok := mr.marks[mark] + return ok + } + return false +} + +// ContainsMarked returns true if the receiving value or any value within it +// is marked. +// +// This operation is relatively expensive. If you only need a shallow result, +// use IsMarked instead. +func (val Value) ContainsMarked() bool { + ret := false + Walk(val, func(_ Path, v Value) (bool, error) { + if v.IsMarked() { + ret = true + return false, nil + } + return true, nil + }) + return ret +} + +func (val Value) assertUnmarked() { + if val.IsMarked() { + panic("value is marked, so must be unmarked first") + } +} + +// Marks returns a map (representing a set) of all of the mark values +// associated with the receiving value, without changing the marks. Returns nil +// if the value is not marked at all. +func (val Value) Marks() ValueMarks { + if mr, ok := val.v.(marker); ok { + // copy so that the caller can't mutate our internals + ret := make(ValueMarks, len(mr.marks)) + for k, v := range mr.marks { + ret[k] = v + } + return ret + } + return nil +} + +// HasSameMarks returns true if an only if the receiver and the given other +// value have identical marks. +func (val Value) HasSameMarks(other Value) bool { + vm, vmOK := val.v.(marker) + om, omOK := other.v.(marker) + if vmOK != omOK { + return false + } + if vmOK { + return vm.marks.Equal(om.marks) + } + return true +} + +// Mark returns a new value that as the same type and underlying value as +// the receiver but that also carries the given value as a "mark". +// +// Marks are used to carry additional application-specific characteristics +// associated with values. A marked value can be used with operation methods, +// in which case the marks are propagated to the operation results. A marked +// value _cannot_ be used with integration methods, so callers of those +// must derive an unmarked value using Unmark (and thus explicitly handle +// the markings) before calling the integration methods. +// +// The mark value can be any value that would be valid to use as a map key. +// The mark value should be of a named type in order to use the type itself +// as a namespace for markings. That type can be unexported if desired, in +// order to ensure that the mark can only be handled through the defining +// package's own functions. +// +// An application that never calls this method does not need to worry about +// handling marked values. +func (val Value) Mark(mark interface{}) Value { + var newMarker marker + newMarker.realV = val.v + if mr, ok := val.v.(marker); ok { + // It's already a marker, so we'll retain existing marks. + newMarker.marks = make(ValueMarks, len(mr.marks)+1) + for k, v := range mr.marks { + newMarker.marks[k] = v + } + } else { + // It's not a marker yet, so we're creating the first mark. + newMarker.marks = make(ValueMarks, 1) + } + newMarker.marks[mark] = struct{}{} + return Value{ + ty: val.ty, + v: newMarker, + } +} + +// Unmark separates the marks of the receiving value from the value itself, +// removing a new unmarked value and a map (representing a set) of the marks. +// +// If the receiver isn't marked, Unmark returns it verbatim along with a nil +// map of marks. +func (val Value) Unmark() (Value, ValueMarks) { + if !val.IsMarked() { + return val, nil + } + mr := val.v.(marker) + marks := val.Marks() // copy so that the caller can't mutate our internals + return Value{ + ty: val.ty, + v: mr.realV, + }, marks +} + +// UnmarkDeep is similar to Unmark, but it works with an entire nested structure +// rather than just the given value directly. +// +// The result is guaranteed to contain no nested values that are marked, and +// the returned marks set includes the superset of all of the marks encountered +// during the operation. +func (val Value) UnmarkDeep() (Value, ValueMarks) { + marks := make(ValueMarks) + ret, _ := Transform(val, func(_ Path, v Value) (Value, error) { + unmarkedV, valueMarks := v.Unmark() + for m, s := range valueMarks { + marks[m] = s + } + return unmarkedV, nil + }) + return ret, marks +} + +func (val Value) unmarkForce() Value { + unw, _ := val.Unmark() + return unw +} + +// WithMarks returns a new value that has the same type and underlying value +// as the receiver and also has the marks from the given maps (representing +// sets). +func (val Value) WithMarks(marks ...ValueMarks) Value { + if len(marks) == 0 { + return val + } + ownMarks := val.Marks() + markCount := len(ownMarks) + for _, s := range marks { + markCount += len(s) + } + if markCount == 0 { + return val + } + newMarks := make(ValueMarks, markCount) + for m := range ownMarks { + newMarks[m] = struct{}{} + } + for _, s := range marks { + for m := range s { + newMarks[m] = struct{}{} + } + } + v := val.v + if mr, ok := v.(marker); ok { + v = mr.realV + } + return Value{ + ty: val.ty, + v: marker{ + realV: v, + marks: newMarks, + }, + } +} + +// WithSameMarks returns a new value that has the same type and underlying +// value as the receiver and also has the marks from the given source values. +// +// Use this if you are implementing your own higher-level operations against +// cty using the integration methods, to re-introduce the marks from the +// source values of the operation. +func (val Value) WithSameMarks(srcs ...Value) Value { + if len(srcs) == 0 { + return val + } + ownMarks := val.Marks() + markCount := len(ownMarks) + for _, sv := range srcs { + if mr, ok := sv.v.(marker); ok { + markCount += len(mr.marks) + } + } + if markCount == 0 { + return val + } + newMarks := make(ValueMarks, markCount) + for m := range ownMarks { + newMarks[m] = struct{}{} + } + for _, sv := range srcs { + if mr, ok := sv.v.(marker); ok { + for m := range mr.marks { + newMarks[m] = struct{}{} + } + } + } + v := val.v + if mr, ok := v.(marker); ok { + v = mr.realV + } + return Value{ + ty: val.ty, + v: marker{ + realV: v, + marks: newMarks, + }, + } +} diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/doc.go b/vendor/github.com/hashicorp/go-cty/cty/msgpack/doc.go similarity index 100% rename from vendor/github.com/zclconf/go-cty/cty/msgpack/doc.go rename to vendor/github.com/hashicorp/go-cty/cty/msgpack/doc.go diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/dynamic.go b/vendor/github.com/hashicorp/go-cty/cty/msgpack/dynamic.go similarity index 95% rename from vendor/github.com/zclconf/go-cty/cty/msgpack/dynamic.go rename to vendor/github.com/hashicorp/go-cty/cty/msgpack/dynamic.go index 1b631d0a177..ce59d9ff424 100644 --- a/vendor/github.com/zclconf/go-cty/cty/msgpack/dynamic.go +++ b/vendor/github.com/hashicorp/go-cty/cty/msgpack/dynamic.go @@ -3,8 +3,8 @@ package msgpack import ( "bytes" + "github.com/hashicorp/go-cty/cty" "github.com/vmihailenco/msgpack" - "github.com/zclconf/go-cty/cty" ) type dynamicVal struct { diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/infinity.go b/vendor/github.com/hashicorp/go-cty/cty/msgpack/infinity.go similarity index 100% rename from vendor/github.com/zclconf/go-cty/cty/msgpack/infinity.go rename to vendor/github.com/hashicorp/go-cty/cty/msgpack/infinity.go diff --git a/vendor/github.com/hashicorp/go-cty/cty/msgpack/marshal.go b/vendor/github.com/hashicorp/go-cty/cty/msgpack/marshal.go new file mode 100644 index 00000000000..8a43c16ac92 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/msgpack/marshal.go @@ -0,0 +1,211 @@ +package msgpack + +import ( + "bytes" + "math/big" + "sort" + + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/go-cty/cty/convert" + "github.com/vmihailenco/msgpack" +) + +// Marshal produces a msgpack serialization of the given value that +// can be decoded into the given type later using Unmarshal. +// +// The given value must conform to the given type, or an error will +// be returned. +func Marshal(val cty.Value, ty cty.Type) ([]byte, error) { + errs := val.Type().TestConformance(ty) + if errs != nil { + // Attempt a conversion + var err error + val, err = convert.Convert(val, ty) + if err != nil { + return nil, err + } + } + + // From this point onward, val can be assumed to be conforming to t. + + var path cty.Path + var buf bytes.Buffer + enc := msgpack.NewEncoder(&buf) + + err := marshal(val, ty, path, enc) + if err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +func marshal(val cty.Value, ty cty.Type, path cty.Path, enc *msgpack.Encoder) error { + if val.IsMarked() { + return path.NewErrorf("value has marks, so it cannot be seralized") + } + + // If we're going to decode as DynamicPseudoType then we need to save + // dynamic type information to recover the real type. + if ty == cty.DynamicPseudoType && val.Type() != cty.DynamicPseudoType { + return marshalDynamic(val, path, enc) + } + + if !val.IsKnown() { + err := enc.Encode(unknownVal) + if err != nil { + return path.NewError(err) + } + return nil + } + if val.IsNull() { + err := enc.EncodeNil() + if err != nil { + return path.NewError(err) + } + return nil + } + + // The caller should've guaranteed that the given val is conformant with + // the given type ty, so we'll proceed under that assumption here. + switch { + case ty.IsPrimitiveType(): + switch ty { + case cty.String: + err := enc.EncodeString(val.AsString()) + if err != nil { + return path.NewError(err) + } + return nil + case cty.Number: + var err error + switch { + case val.RawEquals(cty.PositiveInfinity): + err = enc.EncodeFloat64(positiveInfinity) + case val.RawEquals(cty.NegativeInfinity): + err = enc.EncodeFloat64(negativeInfinity) + default: + bf := val.AsBigFloat() + if iv, acc := bf.Int64(); acc == big.Exact { + err = enc.EncodeInt(iv) + } else if fv, acc := bf.Float64(); acc == big.Exact { + err = enc.EncodeFloat64(fv) + } else { + err = enc.EncodeString(bf.Text('f', -1)) + } + } + if err != nil { + return path.NewError(err) + } + return nil + case cty.Bool: + err := enc.EncodeBool(val.True()) + if err != nil { + return path.NewError(err) + } + return nil + default: + panic("unsupported primitive type") + } + case ty.IsListType(), ty.IsSetType(): + enc.EncodeArrayLen(val.LengthInt()) + ety := ty.ElementType() + it := val.ElementIterator() + path := append(path, nil) // local override of 'path' with extra element + for it.Next() { + ek, ev := it.Element() + path[len(path)-1] = cty.IndexStep{ + Key: ek, + } + err := marshal(ev, ety, path, enc) + if err != nil { + return err + } + } + return nil + case ty.IsMapType(): + enc.EncodeMapLen(val.LengthInt()) + ety := ty.ElementType() + it := val.ElementIterator() + path := append(path, nil) // local override of 'path' with extra element + for it.Next() { + ek, ev := it.Element() + path[len(path)-1] = cty.IndexStep{ + Key: ek, + } + var err error + err = marshal(ek, ek.Type(), path, enc) + if err != nil { + return err + } + err = marshal(ev, ety, path, enc) + if err != nil { + return err + } + } + return nil + case ty.IsTupleType(): + etys := ty.TupleElementTypes() + it := val.ElementIterator() + path := append(path, nil) // local override of 'path' with extra element + i := 0 + enc.EncodeArrayLen(len(etys)) + for it.Next() { + ety := etys[i] + ek, ev := it.Element() + path[len(path)-1] = cty.IndexStep{ + Key: ek, + } + err := marshal(ev, ety, path, enc) + if err != nil { + return err + } + i++ + } + return nil + case ty.IsObjectType(): + atys := ty.AttributeTypes() + path := append(path, nil) // local override of 'path' with extra element + + names := make([]string, 0, len(atys)) + for k := range atys { + names = append(names, k) + } + sort.Strings(names) + + enc.EncodeMapLen(len(names)) + + for _, k := range names { + aty := atys[k] + av := val.GetAttr(k) + path[len(path)-1] = cty.GetAttrStep{ + Name: k, + } + var err error + err = marshal(cty.StringVal(k), cty.String, path, enc) + if err != nil { + return err + } + err = marshal(av, aty, path, enc) + if err != nil { + return err + } + } + return nil + case ty.IsCapsuleType(): + return path.NewErrorf("capsule types not supported for msgpack encoding") + default: + // should never happen + return path.NewErrorf("cannot msgpack-serialize %s", ty.FriendlyName()) + } +} + +// marshalDynamic adds an extra wrapping object containing dynamic type +// information for the given value. +func marshalDynamic(val cty.Value, path cty.Path, enc *msgpack.Encoder) error { + dv := dynamicVal{ + Value: val, + Path: path, + } + return enc.Encode(&dv) +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/msgpack/type_implied.go b/vendor/github.com/hashicorp/go-cty/cty/msgpack/type_implied.go new file mode 100644 index 00000000000..86664bac57e --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/msgpack/type_implied.go @@ -0,0 +1,167 @@ +package msgpack + +import ( + "bytes" + "fmt" + "io" + + "github.com/hashicorp/go-cty/cty" + "github.com/vmihailenco/msgpack" + msgpackcodes "github.com/vmihailenco/msgpack/codes" +) + +// ImpliedType returns the cty Type implied by the structure of the given +// msgpack-compliant buffer. This function implements the default type mapping +// behavior used when decoding arbitrary msgpack without explicit cty Type +// information. +// +// The rules are as follows: +// +// msgpack strings, numbers and bools map to their equivalent primitive type in +// cty. +// +// msgpack maps become cty object types, with the attributes defined by the +// map keys and the types of their values. +// +// msgpack arrays become cty tuple types, with the elements defined by the +// types of the array members. +// +// Any nulls are typed as DynamicPseudoType, so callers of this function +// must be prepared to deal with this. Callers that do not wish to deal with +// dynamic typing should not use this function and should instead describe +// their required types explicitly with a cty.Type instance when decoding. +// +// Any unknown values are similarly typed as DynamicPseudoType, because these +// do not carry type information on the wire. +// +// Any parse errors will be returned as an error, and the type will be the +// invalid value cty.NilType. +func ImpliedType(buf []byte) (cty.Type, error) { + r := bytes.NewReader(buf) + dec := msgpack.NewDecoder(r) + + ty, err := impliedType(dec) + if err != nil { + return cty.NilType, err + } + + // We must now be at the end of the buffer + err = dec.Skip() + if err != io.EOF { + return ty, fmt.Errorf("extra bytes after msgpack value") + } + + return ty, nil +} + +func impliedType(dec *msgpack.Decoder) (cty.Type, error) { + // If this function returns with a nil error then it must have already + // consumed the next value from the decoder, since when called recursively + // the caller will be expecting to find a following value here. + + code, err := dec.PeekCode() + if err != nil { + return cty.NilType, err + } + + switch { + + case code == msgpackcodes.Nil || msgpackcodes.IsExt(code): + err := dec.Skip() + return cty.DynamicPseudoType, err + + case code == msgpackcodes.True || code == msgpackcodes.False: + _, err := dec.DecodeBool() + return cty.Bool, err + + case msgpackcodes.IsFixedNum(code): + _, err := dec.DecodeInt64() + return cty.Number, err + + case code == msgpackcodes.Int8 || code == msgpackcodes.Int16 || code == msgpackcodes.Int32 || code == msgpackcodes.Int64: + _, err := dec.DecodeInt64() + return cty.Number, err + + case code == msgpackcodes.Uint8 || code == msgpackcodes.Uint16 || code == msgpackcodes.Uint32 || code == msgpackcodes.Uint64: + _, err := dec.DecodeUint64() + return cty.Number, err + + case code == msgpackcodes.Float || code == msgpackcodes.Double: + _, err := dec.DecodeFloat64() + return cty.Number, err + + case msgpackcodes.IsString(code): + _, err := dec.DecodeString() + return cty.String, err + + case msgpackcodes.IsFixedMap(code) || code == msgpackcodes.Map16 || code == msgpackcodes.Map32: + return impliedObjectType(dec) + + case msgpackcodes.IsFixedArray(code) || code == msgpackcodes.Array16 || code == msgpackcodes.Array32: + return impliedTupleType(dec) + + default: + return cty.NilType, fmt.Errorf("unsupported msgpack code %#v", code) + } +} + +func impliedObjectType(dec *msgpack.Decoder) (cty.Type, error) { + // If we get in here then we've already peeked the next code and know + // it's some sort of map. + l, err := dec.DecodeMapLen() + if err != nil { + return cty.DynamicPseudoType, nil + } + + var atys map[string]cty.Type + + for i := 0; i < l; i++ { + // Read the map key first. We require maps to be strings, but msgpack + // doesn't so we're prepared to error here if not. + k, err := dec.DecodeString() + if err != nil { + return cty.DynamicPseudoType, err + } + + aty, err := impliedType(dec) + if err != nil { + return cty.DynamicPseudoType, err + } + + if atys == nil { + atys = make(map[string]cty.Type) + } + atys[k] = aty + } + + if len(atys) == 0 { + return cty.EmptyObject, nil + } + + return cty.Object(atys), nil +} + +func impliedTupleType(dec *msgpack.Decoder) (cty.Type, error) { + // If we get in here then we've already peeked the next code and know + // it's some sort of array. + l, err := dec.DecodeArrayLen() + if err != nil { + return cty.DynamicPseudoType, nil + } + + if l == 0 { + return cty.EmptyTuple, nil + } + + etys := make([]cty.Type, l) + + for i := 0; i < l; i++ { + ety, err := impliedType(dec) + if err != nil { + return cty.DynamicPseudoType, err + } + etys[i] = ety + } + + return cty.Tuple(etys), nil +} diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/unknown.go b/vendor/github.com/hashicorp/go-cty/cty/msgpack/unknown.go similarity index 100% rename from vendor/github.com/zclconf/go-cty/cty/msgpack/unknown.go rename to vendor/github.com/hashicorp/go-cty/cty/msgpack/unknown.go diff --git a/vendor/github.com/hashicorp/go-cty/cty/msgpack/unmarshal.go b/vendor/github.com/hashicorp/go-cty/cty/msgpack/unmarshal.go new file mode 100644 index 00000000000..67f4c9a4cd6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/msgpack/unmarshal.go @@ -0,0 +1,334 @@ +package msgpack + +import ( + "bytes" + + "github.com/hashicorp/go-cty/cty" + "github.com/vmihailenco/msgpack" + msgpackCodes "github.com/vmihailenco/msgpack/codes" +) + +// Unmarshal interprets the given bytes as a msgpack-encoded cty Value of +// the given type, returning the result. +// +// If an error is returned, the error is written with a hypothetical +// end-user that wrote the msgpack file as its audience, using cty type +// system concepts rather than Go type system concepts. +func Unmarshal(b []byte, ty cty.Type) (cty.Value, error) { + r := bytes.NewReader(b) + dec := msgpack.NewDecoder(r) + + var path cty.Path + return unmarshal(dec, ty, path) +} + +func unmarshal(dec *msgpack.Decoder, ty cty.Type, path cty.Path) (cty.Value, error) { + peek, err := dec.PeekCode() + if err != nil { + return cty.DynamicVal, path.NewError(err) + } + if msgpackCodes.IsExt(peek) { + // We just assume _all_ extensions are unknown values, + // since we don't have any other extensions. + dec.Skip() // skip what we've peeked + return cty.UnknownVal(ty), nil + } + if ty == cty.DynamicPseudoType { + return unmarshalDynamic(dec, path) + } + if peek == msgpackCodes.Nil { + dec.Skip() // skip what we've peeked + return cty.NullVal(ty), nil + } + + switch { + case ty.IsPrimitiveType(): + val, err := unmarshalPrimitive(dec, ty, path) + if err != nil { + return cty.NilVal, err + } + return val, nil + case ty.IsListType(): + return unmarshalList(dec, ty.ElementType(), path) + case ty.IsSetType(): + return unmarshalSet(dec, ty.ElementType(), path) + case ty.IsMapType(): + return unmarshalMap(dec, ty.ElementType(), path) + case ty.IsTupleType(): + return unmarshalTuple(dec, ty.TupleElementTypes(), path) + case ty.IsObjectType(): + return unmarshalObject(dec, ty.AttributeTypes(), path) + default: + return cty.NilVal, path.NewErrorf("unsupported type %s", ty.FriendlyName()) + } +} + +func unmarshalPrimitive(dec *msgpack.Decoder, ty cty.Type, path cty.Path) (cty.Value, error) { + switch ty { + case cty.Bool: + rv, err := dec.DecodeBool() + if err != nil { + return cty.DynamicVal, path.NewErrorf("bool is required") + } + return cty.BoolVal(rv), nil + case cty.Number: + // Marshal will try int and float first, if the value can be + // losslessly represented in these encodings, and then fall + // back on a string if the number is too large or too precise. + peek, err := dec.PeekCode() + if err != nil { + return cty.DynamicVal, path.NewErrorf("number is required") + } + + if msgpackCodes.IsFixedNum(peek) { + rv, err := dec.DecodeInt64() + if err != nil { + return cty.DynamicVal, path.NewErrorf("number is required") + } + return cty.NumberIntVal(rv), nil + } + + switch peek { + case msgpackCodes.Int8, msgpackCodes.Int16, msgpackCodes.Int32, msgpackCodes.Int64: + rv, err := dec.DecodeInt64() + if err != nil { + return cty.DynamicVal, path.NewErrorf("number is required") + } + return cty.NumberIntVal(rv), nil + case msgpackCodes.Uint8, msgpackCodes.Uint16, msgpackCodes.Uint32, msgpackCodes.Uint64: + rv, err := dec.DecodeUint64() + if err != nil { + return cty.DynamicVal, path.NewErrorf("number is required") + } + return cty.NumberUIntVal(rv), nil + case msgpackCodes.Float, msgpackCodes.Double: + rv, err := dec.DecodeFloat64() + if err != nil { + return cty.DynamicVal, path.NewErrorf("number is required") + } + return cty.NumberFloatVal(rv), nil + default: + rv, err := dec.DecodeString() + if err != nil { + return cty.DynamicVal, path.NewErrorf("number is required") + } + v, err := cty.ParseNumberVal(rv) + if err != nil { + return cty.DynamicVal, path.NewErrorf("number is required") + } + return v, nil + } + case cty.String: + rv, err := dec.DecodeString() + if err != nil { + return cty.DynamicVal, path.NewErrorf("string is required") + } + return cty.StringVal(rv), nil + default: + // should never happen + panic("unsupported primitive type") + } +} + +func unmarshalList(dec *msgpack.Decoder, ety cty.Type, path cty.Path) (cty.Value, error) { + length, err := dec.DecodeArrayLen() + if err != nil { + return cty.DynamicVal, path.NewErrorf("a list is required") + } + + switch { + case length < 0: + return cty.NullVal(cty.List(ety)), nil + case length == 0: + return cty.ListValEmpty(ety), nil + } + + vals := make([]cty.Value, 0, length) + path = append(path, nil) + for i := 0; i < length; i++ { + path[len(path)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(int64(i)), + } + + val, err := unmarshal(dec, ety, path) + if err != nil { + return cty.DynamicVal, err + } + + vals = append(vals, val) + } + + return cty.ListVal(vals), nil +} + +func unmarshalSet(dec *msgpack.Decoder, ety cty.Type, path cty.Path) (cty.Value, error) { + length, err := dec.DecodeArrayLen() + if err != nil { + return cty.DynamicVal, path.NewErrorf("a set is required") + } + + switch { + case length < 0: + return cty.NullVal(cty.Set(ety)), nil + case length == 0: + return cty.SetValEmpty(ety), nil + } + + vals := make([]cty.Value, 0, length) + path = append(path, nil) + for i := 0; i < length; i++ { + path[len(path)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(int64(i)), + } + + val, err := unmarshal(dec, ety, path) + if err != nil { + return cty.DynamicVal, err + } + + vals = append(vals, val) + } + + return cty.SetVal(vals), nil +} + +func unmarshalMap(dec *msgpack.Decoder, ety cty.Type, path cty.Path) (cty.Value, error) { + length, err := dec.DecodeMapLen() + if err != nil { + return cty.DynamicVal, path.NewErrorf("a map is required") + } + + switch { + case length < 0: + return cty.NullVal(cty.Map(ety)), nil + case length == 0: + return cty.MapValEmpty(ety), nil + } + + vals := make(map[string]cty.Value, length) + path = append(path, nil) + for i := 0; i < length; i++ { + key, err := dec.DecodeString() + if err != nil { + path[:len(path)-1].NewErrorf("non-string key in map") + } + + path[len(path)-1] = cty.IndexStep{ + Key: cty.StringVal(key), + } + + val, err := unmarshal(dec, ety, path) + if err != nil { + return cty.DynamicVal, err + } + + vals[key] = val + } + + return cty.MapVal(vals), nil +} + +func unmarshalTuple(dec *msgpack.Decoder, etys []cty.Type, path cty.Path) (cty.Value, error) { + length, err := dec.DecodeArrayLen() + if err != nil { + return cty.DynamicVal, path.NewErrorf("a tuple is required") + } + + switch { + case length < 0: + return cty.NullVal(cty.Tuple(etys)), nil + case length == 0: + return cty.TupleVal(nil), nil + case length != len(etys): + return cty.DynamicVal, path.NewErrorf("a tuple of length %d is required", len(etys)) + } + + vals := make([]cty.Value, 0, length) + path = append(path, nil) + for i := 0; i < length; i++ { + path[len(path)-1] = cty.IndexStep{ + Key: cty.NumberIntVal(int64(i)), + } + ety := etys[i] + + val, err := unmarshal(dec, ety, path) + if err != nil { + return cty.DynamicVal, err + } + + vals = append(vals, val) + } + + return cty.TupleVal(vals), nil +} + +func unmarshalObject(dec *msgpack.Decoder, atys map[string]cty.Type, path cty.Path) (cty.Value, error) { + length, err := dec.DecodeMapLen() + if err != nil { + return cty.DynamicVal, path.NewErrorf("an object is required") + } + + switch { + case length < 0: + return cty.NullVal(cty.Object(atys)), nil + case length == 0: + return cty.ObjectVal(nil), nil + case length != len(atys): + return cty.DynamicVal, path.NewErrorf("an object with %d attributes is required (%d given)", + len(atys), length) + } + + vals := make(map[string]cty.Value, length) + path = append(path, nil) + for i := 0; i < length; i++ { + key, err := dec.DecodeString() + if err != nil { + return cty.DynamicVal, path[:len(path)-1].NewErrorf("all keys must be strings") + } + + path[len(path)-1] = cty.IndexStep{ + Key: cty.StringVal(key), + } + aty, exists := atys[key] + if !exists { + return cty.DynamicVal, path.NewErrorf("unsupported attribute") + } + + val, err := unmarshal(dec, aty, path) + if err != nil { + return cty.DynamicVal, err + } + + vals[key] = val + } + + return cty.ObjectVal(vals), nil +} + +func unmarshalDynamic(dec *msgpack.Decoder, path cty.Path) (cty.Value, error) { + length, err := dec.DecodeArrayLen() + if err != nil { + return cty.DynamicVal, path.NewError(err) + } + + switch { + case length == -1: + return cty.NullVal(cty.DynamicPseudoType), nil + case length != 2: + return cty.DynamicVal, path.NewErrorf( + "dynamic value array must have exactly two elements", + ) + } + + typeJSON, err := dec.DecodeBytes() + if err != nil { + return cty.DynamicVal, path.NewError(err) + } + var ty cty.Type + err = (&ty).UnmarshalJSON(typeJSON) + if err != nil { + return cty.DynamicVal, path.NewError(err) + } + + return unmarshal(dec, ty, path) +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/null.go b/vendor/github.com/hashicorp/go-cty/cty/null.go new file mode 100644 index 00000000000..d58d0287b64 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/null.go @@ -0,0 +1,14 @@ +package cty + +// NullVal returns a null value of the given type. A null can be created of any +// type, but operations on such values will always panic. Calling applications +// are encouraged to use nulls only sparingly, particularly when user-provided +// expressions are to be evaluated, since the precence of nulls creates a +// much higher chance of evaluation errors that can't be caught by a type +// checker. +func NullVal(t Type) Value { + return Value{ + ty: t, + v: nil, + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/object_type.go b/vendor/github.com/hashicorp/go-cty/cty/object_type.go new file mode 100644 index 00000000000..187d38751b8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/object_type.go @@ -0,0 +1,135 @@ +package cty + +import ( + "fmt" +) + +type typeObject struct { + typeImplSigil + AttrTypes map[string]Type +} + +// Object creates an object type with the given attribute types. +// +// After a map is passed to this function the caller must no longer access it, +// since ownership is transferred to this library. +func Object(attrTypes map[string]Type) Type { + attrTypesNorm := make(map[string]Type, len(attrTypes)) + for k, v := range attrTypes { + attrTypesNorm[NormalizeString(k)] = v + } + + return Type{ + typeObject{ + AttrTypes: attrTypesNorm, + }, + } +} + +func (t typeObject) Equals(other Type) bool { + if ot, ok := other.typeImpl.(typeObject); ok { + if len(t.AttrTypes) != len(ot.AttrTypes) { + // Fast path: if we don't have the same number of attributes + // then we can't possibly be equal. This also avoids the need + // to test attributes in both directions below, since we know + // there can't be extras in "other". + return false + } + + for attr, ty := range t.AttrTypes { + oty, ok := ot.AttrTypes[attr] + if !ok { + return false + } + if !oty.Equals(ty) { + return false + } + } + + return true + } + return false +} + +func (t typeObject) FriendlyName(mode friendlyTypeNameMode) string { + // There isn't really a friendly way to write an object type due to its + // complexity, so we'll just do something English-ish. Callers will + // probably want to make some extra effort to avoid ever printing out + // an object type FriendlyName in its entirety. For example, could + // produce an error message by diffing two object types and saying + // something like "Expected attribute foo to be string, but got number". + // TODO: Finish this + return "object" +} + +func (t typeObject) GoString() string { + if len(t.AttrTypes) == 0 { + return "cty.EmptyObject" + } + return fmt.Sprintf("cty.Object(%#v)", t.AttrTypes) +} + +// EmptyObject is a shorthand for Object(map[string]Type{}), to more +// easily talk about the empty object type. +var EmptyObject Type + +// EmptyObjectVal is the only possible non-null, non-unknown value of type +// EmptyObject. +var EmptyObjectVal Value + +func init() { + EmptyObject = Object(map[string]Type{}) + EmptyObjectVal = Value{ + ty: EmptyObject, + v: map[string]interface{}{}, + } +} + +// IsObjectType returns true if the given type is an object type, regardless +// of its element type. +func (t Type) IsObjectType() bool { + _, ok := t.typeImpl.(typeObject) + return ok +} + +// HasAttribute returns true if the receiver has an attribute with the given +// name, regardless of its type. Will panic if the reciever isn't an object +// type; use IsObjectType to determine whether this operation will succeed. +func (t Type) HasAttribute(name string) bool { + name = NormalizeString(name) + if ot, ok := t.typeImpl.(typeObject); ok { + _, hasAttr := ot.AttrTypes[name] + return hasAttr + } + panic("HasAttribute on non-object Type") +} + +// AttributeType returns the type of the attribute with the given name. Will +// panic if the receiver is not an object type (use IsObjectType to confirm) +// or if the object type has no such attribute (use HasAttribute to confirm). +func (t Type) AttributeType(name string) Type { + name = NormalizeString(name) + if ot, ok := t.typeImpl.(typeObject); ok { + aty, hasAttr := ot.AttrTypes[name] + if !hasAttr { + panic("no such attribute") + } + return aty + } + panic("AttributeType on non-object Type") +} + +// AttributeTypes returns a map from attribute names to their associated +// types. Will panic if the receiver is not an object type (use IsObjectType +// to confirm). +// +// The returned map is part of the internal state of the type, and is provided +// for read access only. It is forbidden for any caller to modify the returned +// map. For many purposes the attribute-related methods of Value are more +// appropriate and more convenient to use. +func (t Type) AttributeTypes() map[string]Type { + if ot, ok := t.typeImpl.(typeObject); ok { + return ot.AttrTypes + } + panic("AttributeTypes on non-object Type") +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/path.go b/vendor/github.com/hashicorp/go-cty/cty/path.go new file mode 100644 index 00000000000..636e68c63dd --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/path.go @@ -0,0 +1,270 @@ +package cty + +import ( + "errors" + "fmt" +) + +// A Path is a sequence of operations to locate a nested value within a +// data structure. +// +// The empty Path represents the given item. Any PathSteps within represent +// taking a single step down into a data structure. +// +// Path has some convenience methods for gradually constructing a path, +// but callers can also feel free to just produce a slice of PathStep manually +// and convert to this type, which may be more appropriate in environments +// where memory pressure is a concern. +// +// Although a Path is technically mutable, by convention callers should not +// mutate a path once it has been built and passed to some other subsystem. +// Instead, use Copy and then mutate the copy before using it. +type Path []PathStep + +// PathStep represents a single step down into a data structure, as part +// of a Path. PathStep is a closed interface, meaning that the only +// permitted implementations are those within this package. +type PathStep interface { + pathStepSigil() pathStepImpl + Apply(Value) (Value, error) +} + +// embed pathImpl into a struct to declare it a PathStep implementation +type pathStepImpl struct{} + +func (p pathStepImpl) pathStepSigil() pathStepImpl { + return p +} + +// Index returns a new Path that is the reciever with an IndexStep appended +// to the end. +// +// This is provided as a convenient way to construct paths, but each call +// will create garbage so it should not be used where memory pressure is a +// concern. +func (p Path) Index(v Value) Path { + ret := make(Path, len(p)+1) + copy(ret, p) + ret[len(p)] = IndexStep{ + Key: v, + } + return ret +} + +// IndexInt is a typed convenience method for Index. +func (p Path) IndexInt(v int) Path { + return p.Index(NumberIntVal(int64(v))) +} + +// IndexString is a typed convenience method for Index. +func (p Path) IndexString(v string) Path { + return p.Index(StringVal(v)) +} + +// IndexPath is a convenience method to start a new Path with an IndexStep. +func IndexPath(v Value) Path { + return Path{}.Index(v) +} + +// IndexIntPath is a typed convenience method for IndexPath. +func IndexIntPath(v int) Path { + return IndexPath(NumberIntVal(int64(v))) +} + +// IndexStringPath is a typed convenience method for IndexPath. +func IndexStringPath(v string) Path { + return IndexPath(StringVal(v)) +} + +// GetAttr returns a new Path that is the reciever with a GetAttrStep appended +// to the end. +// +// This is provided as a convenient way to construct paths, but each call +// will create garbage so it should not be used where memory pressure is a +// concern. +func (p Path) GetAttr(name string) Path { + ret := make(Path, len(p)+1) + copy(ret, p) + ret[len(p)] = GetAttrStep{ + Name: name, + } + return ret +} + +// Equals compares 2 Paths for exact equality. +func (p Path) Equals(other Path) bool { + if len(p) != len(other) { + return false + } + + for i := range p { + pv := p[i] + switch pv := pv.(type) { + case GetAttrStep: + ov, ok := other[i].(GetAttrStep) + if !ok || pv != ov { + return false + } + case IndexStep: + ov, ok := other[i].(IndexStep) + if !ok { + return false + } + + if !pv.Key.RawEquals(ov.Key) { + return false + } + default: + // Any invalid steps default to evaluating false. + return false + } + } + + return true + +} + +// HasPrefix determines if the path p contains the provided prefix. +func (p Path) HasPrefix(prefix Path) bool { + if len(prefix) > len(p) { + return false + } + + return p[:len(prefix)].Equals(prefix) +} + +// GetAttrPath is a convenience method to start a new Path with a GetAttrStep. +func GetAttrPath(name string) Path { + return Path{}.GetAttr(name) +} + +// Apply applies each of the steps in turn to successive values starting with +// the given value, and returns the result. If any step returns an error, +// the whole operation returns an error. +func (p Path) Apply(val Value) (Value, error) { + var err error + for i, step := range p { + val, err = step.Apply(val) + if err != nil { + return NilVal, fmt.Errorf("at step %d: %s", i, err) + } + } + return val, nil +} + +// LastStep applies the given path up to the last step and then returns +// the resulting value and the final step. +// +// This is useful when dealing with assignment operations, since in that +// case the *value* of the last step is not important (and may not, in fact, +// present at all) and we care only about its location. +// +// Since LastStep applies all steps except the last, it will return errors +// for those steps in the same way as Apply does. +// +// If the path has *no* steps then the returned PathStep will be nil, +// representing that any operation should be applied directly to the +// given value. +func (p Path) LastStep(val Value) (Value, PathStep, error) { + var err error + + if len(p) == 0 { + return val, nil, nil + } + + journey := p[:len(p)-1] + val, err = journey.Apply(val) + if err != nil { + return NilVal, nil, err + } + return val, p[len(p)-1], nil +} + +// Copy makes a shallow copy of the receiver. Often when paths are passed to +// caller code they come with the constraint that they are valid only until +// the caller returns, due to how they are constructed internally. Callers +// can use Copy to conveniently produce a copy of the value that _they_ control +// the validity of. +func (p Path) Copy() Path { + ret := make(Path, len(p)) + copy(ret, p) + return ret +} + +// IndexStep is a Step implementation representing applying the index operation +// to a value, which must be of either a list, map, or set type. +// +// When describing a path through a *type* rather than a concrete value, +// the Key may be an unknown value, indicating that the step applies to +// *any* key of the given type. +// +// When indexing into a set, the Key is actually the element being accessed +// itself, since in sets elements are their own identity. +type IndexStep struct { + pathStepImpl + Key Value +} + +// Apply returns the value resulting from indexing the given value with +// our key value. +func (s IndexStep) Apply(val Value) (Value, error) { + if val == NilVal || val.IsNull() { + return NilVal, errors.New("cannot index a null value") + } + + switch s.Key.Type() { + case Number: + if !(val.Type().IsListType() || val.Type().IsTupleType()) { + return NilVal, errors.New("not a list type") + } + case String: + if !val.Type().IsMapType() { + return NilVal, errors.New("not a map type") + } + default: + return NilVal, errors.New("key value not number or string") + } + + has := val.HasIndex(s.Key) + if !has.IsKnown() { + return UnknownVal(val.Type().ElementType()), nil + } + if !has.True() { + return NilVal, errors.New("value does not have given index key") + } + + return val.Index(s.Key), nil +} + +func (s IndexStep) GoString() string { + return fmt.Sprintf("cty.IndexStep{Key:%#v}", s.Key) +} + +// GetAttrStep is a Step implementation representing retrieving an attribute +// from a value, which must be of an object type. +type GetAttrStep struct { + pathStepImpl + Name string +} + +// Apply returns the value of our named attribute from the given value, which +// must be of an object type that has a value of that name. +func (s GetAttrStep) Apply(val Value) (Value, error) { + if val == NilVal || val.IsNull() { + return NilVal, errors.New("cannot access attributes on a null value") + } + + if !val.Type().IsObjectType() { + return NilVal, errors.New("not an object type") + } + + if !val.Type().HasAttribute(s.Name) { + return NilVal, fmt.Errorf("object has no attribute %q", s.Name) + } + + return val.GetAttr(s.Name), nil +} + +func (s GetAttrStep) GoString() string { + return fmt.Sprintf("cty.GetAttrStep{Name:%q}", s.Name) +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/path_set.go b/vendor/github.com/hashicorp/go-cty/cty/path_set.go new file mode 100644 index 00000000000..977523de577 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/path_set.go @@ -0,0 +1,198 @@ +package cty + +import ( + "fmt" + "hash/crc64" + + "github.com/hashicorp/go-cty/cty/set" +) + +// PathSet represents a set of Path objects. This can be used, for example, +// to talk about a subset of paths within a value that meet some criteria, +// without directly modifying the values at those paths. +type PathSet struct { + set set.Set +} + +// NewPathSet creates and returns a PathSet, with initial contents optionally +// set by the given arguments. +func NewPathSet(paths ...Path) PathSet { + ret := PathSet{ + set: set.NewSet(pathSetRules{}), + } + + for _, path := range paths { + ret.Add(path) + } + + return ret +} + +// Add inserts a single given path into the set. +// +// Paths are immutable after construction by convention. It is particularly +// important not to mutate a path after it has been placed into a PathSet. +// If a Path is mutated while in a set, behavior is undefined. +func (s PathSet) Add(path Path) { + s.set.Add(path) +} + +// AddAllSteps is like Add but it also adds all of the steps leading to +// the given path. +// +// For example, if given a path representing "foo.bar", it will add both +// "foo" and "bar". +func (s PathSet) AddAllSteps(path Path) { + for i := 1; i <= len(path); i++ { + s.Add(path[:i]) + } +} + +// Has returns true if the given path is in the receiving set. +func (s PathSet) Has(path Path) bool { + return s.set.Has(path) +} + +// List makes and returns a slice of all of the paths in the receiving set, +// in an undefined but consistent order. +func (s PathSet) List() []Path { + if s.Empty() { + return nil + } + ret := make([]Path, 0, s.set.Length()) + for it := s.set.Iterator(); it.Next(); { + ret = append(ret, it.Value().(Path)) + } + return ret +} + +// Remove modifies the receving set to no longer include the given path. +// If the given path was already absent, this is a no-op. +func (s PathSet) Remove(path Path) { + s.set.Remove(path) +} + +// Empty returns true if the length of the receiving set is zero. +func (s PathSet) Empty() bool { + return s.set.Length() == 0 +} + +// Union returns a new set whose contents are the union of the receiver and +// the given other set. +func (s PathSet) Union(other PathSet) PathSet { + return PathSet{ + set: s.set.Union(other.set), + } +} + +// Intersection returns a new set whose contents are the intersection of the +// receiver and the given other set. +func (s PathSet) Intersection(other PathSet) PathSet { + return PathSet{ + set: s.set.Intersection(other.set), + } +} + +// Subtract returns a new set whose contents are those from the receiver with +// any elements of the other given set subtracted. +func (s PathSet) Subtract(other PathSet) PathSet { + return PathSet{ + set: s.set.Subtract(other.set), + } +} + +// SymmetricDifference returns a new set whose contents are the symmetric +// difference of the receiver and the given other set. +func (s PathSet) SymmetricDifference(other PathSet) PathSet { + return PathSet{ + set: s.set.SymmetricDifference(other.set), + } +} + +// Equal returns true if and only if both the receiver and the given other +// set contain exactly the same paths. +func (s PathSet) Equal(other PathSet) bool { + if s.set.Length() != other.set.Length() { + return false + } + // Now we know the lengths are the same we only need to test in one + // direction whether everything in one is in the other. + for it := s.set.Iterator(); it.Next(); { + if !other.set.Has(it.Value()) { + return false + } + } + return true +} + +var crc64Table = crc64.MakeTable(crc64.ISO) + +var indexStepPlaceholder = []byte("#") + +// pathSetRules is an implementation of set.Rules from the set package, +// used internally within PathSet. +type pathSetRules struct { +} + +func (r pathSetRules) Hash(v interface{}) int { + path := v.(Path) + hash := crc64.New(crc64Table) + + for _, rawStep := range path { + switch step := rawStep.(type) { + case GetAttrStep: + // (this creates some garbage converting the string name to a + // []byte, but that's okay since cty is not designed to be + // used in tight loops under memory pressure.) + hash.Write([]byte(step.Name)) + default: + // For any other step type we just append a predefined value, + // which means that e.g. all indexes into a given collection will + // hash to the same value but we assume that collections are + // small and thus this won't hurt too much. + hash.Write(indexStepPlaceholder) + } + } + + // We discard half of the hash on 32-bit platforms; collisions just make + // our lookups take marginally longer, so not a big deal. + return int(hash.Sum64()) +} + +func (r pathSetRules) Equivalent(a, b interface{}) bool { + aPath := a.(Path) + bPath := b.(Path) + + if len(aPath) != len(bPath) { + return false + } + + for i := range aPath { + switch aStep := aPath[i].(type) { + case GetAttrStep: + bStep, ok := bPath[i].(GetAttrStep) + if !ok { + return false + } + + if aStep.Name != bStep.Name { + return false + } + case IndexStep: + bStep, ok := bPath[i].(IndexStep) + if !ok { + return false + } + + eq := aStep.Key.Equals(bStep.Key) + if !eq.IsKnown() || eq.False() { + return false + } + default: + // Should never happen, since we document PathStep as a closed type. + panic(fmt.Errorf("unsupported step type %T", aStep)) + } + } + + return true +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/primitive_type.go b/vendor/github.com/hashicorp/go-cty/cty/primitive_type.go new file mode 100644 index 00000000000..7b3d1196cd0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/primitive_type.go @@ -0,0 +1,122 @@ +package cty + +import "math/big" + +// primitiveType is the hidden implementation of the various primitive types +// that are exposed as variables in this package. +type primitiveType struct { + typeImplSigil + Kind primitiveTypeKind +} + +type primitiveTypeKind byte + +const ( + primitiveTypeBool primitiveTypeKind = 'B' + primitiveTypeNumber primitiveTypeKind = 'N' + primitiveTypeString primitiveTypeKind = 'S' +) + +func (t primitiveType) Equals(other Type) bool { + if otherP, ok := other.typeImpl.(primitiveType); ok { + return otherP.Kind == t.Kind + } + return false +} + +func (t primitiveType) FriendlyName(mode friendlyTypeNameMode) string { + switch t.Kind { + case primitiveTypeBool: + return "bool" + case primitiveTypeNumber: + return "number" + case primitiveTypeString: + return "string" + default: + // should never happen + panic("invalid primitive type") + } +} + +func (t primitiveType) GoString() string { + switch t.Kind { + case primitiveTypeBool: + return "cty.Bool" + case primitiveTypeNumber: + return "cty.Number" + case primitiveTypeString: + return "cty.String" + default: + // should never happen + panic("invalid primitive type") + } +} + +// Number is the numeric type. Number values are arbitrary-precision +// decimal numbers, which can then be converted into Go's various numeric +// types only if they are in the appropriate range. +var Number Type + +// String is the string type. String values are sequences of unicode codepoints +// encoded internally as UTF-8. +var String Type + +// Bool is the boolean type. The two values of this type are True and False. +var Bool Type + +// True is the truthy value of type Bool +var True Value + +// False is the falsey value of type Bool +var False Value + +// Zero is a number value representing exactly zero. +var Zero Value + +// PositiveInfinity is a Number value representing positive infinity +var PositiveInfinity Value + +// NegativeInfinity is a Number value representing negative infinity +var NegativeInfinity Value + +func init() { + Number = Type{ + primitiveType{Kind: primitiveTypeNumber}, + } + String = Type{ + primitiveType{Kind: primitiveTypeString}, + } + Bool = Type{ + primitiveType{Kind: primitiveTypeBool}, + } + True = Value{ + ty: Bool, + v: true, + } + False = Value{ + ty: Bool, + v: false, + } + Zero = Value{ + ty: Number, + v: big.NewFloat(0), + } + PositiveInfinity = Value{ + ty: Number, + v: (&big.Float{}).SetInf(false), + } + NegativeInfinity = Value{ + ty: Number, + v: (&big.Float{}).SetInf(true), + } +} + +// IsPrimitiveType returns true if and only if the reciever is a primitive +// type, which means it's either number, string, or bool. Any two primitive +// types can be safely compared for equality using the standard == operator +// without panic, which is not a guarantee that holds for all types. Primitive +// types can therefore also be used in switch statements. +func (t Type) IsPrimitiveType() bool { + _, ok := t.typeImpl.(primitiveType) + return ok +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/set/gob.go b/vendor/github.com/hashicorp/go-cty/cty/set/gob.go new file mode 100644 index 00000000000..da2978f655d --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/set/gob.go @@ -0,0 +1,76 @@ +package set + +import ( + "bytes" + "encoding/gob" + "fmt" +) + +// GobEncode is an implementation of the interface gob.GobEncoder, allowing +// sets to be included in structures encoded via gob. +// +// The set rules are included in the serialized value, so the caller must +// register its concrete rules type with gob.Register before using a +// set in a gob, and possibly also implement GobEncode/GobDecode to customize +// how any parameters are persisted. +// +// The set elements are also included, so if they are of non-primitive types +// they too must be registered with gob. +// +// If the produced gob values will persist for a long time, the caller must +// ensure compatibility of the rules implementation. In particular, if the +// definition of element equivalence changes between encoding and decoding +// then two distinct stored elements may be considered equivalent on decoding, +// causing the recovered set to have fewer elements than when it was stored. +func (s Set) GobEncode() ([]byte, error) { + gs := gobSet{ + Version: 0, + Rules: s.rules, + Values: s.Values(), + } + + buf := &bytes.Buffer{} + enc := gob.NewEncoder(buf) + err := enc.Encode(gs) + if err != nil { + return nil, fmt.Errorf("error encoding set.Set: %s", err) + } + + return buf.Bytes(), nil +} + +// GobDecode is the opposite of GobEncode. See GobEncode for information +// on the requirements for and caveats of including set values in gobs. +func (s *Set) GobDecode(buf []byte) error { + r := bytes.NewReader(buf) + dec := gob.NewDecoder(r) + + var gs gobSet + err := dec.Decode(&gs) + if err != nil { + return fmt.Errorf("error decoding set.Set: %s", err) + } + if gs.Version != 0 { + return fmt.Errorf("unsupported set.Set encoding version %d; need 0", gs.Version) + } + + victim := NewSetFromSlice(gs.Rules, gs.Values) + s.vals = victim.vals + s.rules = victim.rules + return nil +} + +type gobSet struct { + Version int + Rules Rules + + // The bucket-based representation is for efficient in-memory access, but + // for serialization it's enough to just retain the values themselves, + // which we can re-bucket using the rules (which may have changed!) when + // we re-inflate. + Values []interface{} +} + +func init() { + gob.Register([]interface{}(nil)) +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/set/iterator.go b/vendor/github.com/hashicorp/go-cty/cty/set/iterator.go new file mode 100644 index 00000000000..4a60494f9d6 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/set/iterator.go @@ -0,0 +1,15 @@ +package set + +type Iterator struct { + vals []interface{} + idx int +} + +func (it *Iterator) Value() interface{} { + return it.vals[it.idx] +} + +func (it *Iterator) Next() bool { + it.idx++ + return it.idx < len(it.vals) +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/set/ops.go b/vendor/github.com/hashicorp/go-cty/cty/set/ops.go new file mode 100644 index 00000000000..fd1555f2189 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/set/ops.go @@ -0,0 +1,210 @@ +package set + +import ( + "sort" +) + +// Add inserts the given value into the receiving Set. +// +// This mutates the set in-place. This operation is not thread-safe. +func (s Set) Add(val interface{}) { + hv := s.rules.Hash(val) + if _, ok := s.vals[hv]; !ok { + s.vals[hv] = make([]interface{}, 0, 1) + } + bucket := s.vals[hv] + + // See if an equivalent value is already present + for _, ev := range bucket { + if s.rules.Equivalent(val, ev) { + return + } + } + + s.vals[hv] = append(bucket, val) +} + +// Remove deletes the given value from the receiving set, if indeed it was +// there in the first place. If the value is not present, this is a no-op. +func (s Set) Remove(val interface{}) { + hv := s.rules.Hash(val) + bucket, ok := s.vals[hv] + if !ok { + return + } + + for i, ev := range bucket { + if s.rules.Equivalent(val, ev) { + newBucket := make([]interface{}, 0, len(bucket)-1) + newBucket = append(newBucket, bucket[:i]...) + newBucket = append(newBucket, bucket[i+1:]...) + if len(newBucket) > 0 { + s.vals[hv] = newBucket + } else { + delete(s.vals, hv) + } + return + } + } +} + +// Has returns true if the given value is in the receiving set, or false if +// it is not. +func (s Set) Has(val interface{}) bool { + hv := s.rules.Hash(val) + bucket, ok := s.vals[hv] + if !ok { + return false + } + + for _, ev := range bucket { + if s.rules.Equivalent(val, ev) { + return true + } + } + return false +} + +// Copy performs a shallow copy of the receiving set, returning a new set +// with the same rules and elements. +func (s Set) Copy() Set { + ret := NewSet(s.rules) + for k, v := range s.vals { + ret.vals[k] = v + } + return ret +} + +// Iterator returns an iterator over values in the set. If the set's rules +// implement OrderedRules then the result is ordered per those rules. If +// no order is provided, or if it is not a total order, then the iteration +// order is undefined but consistent for a particular version of cty. Do not +// rely on specific ordering between cty releases unless the rules order is a +// total order. +// +// The pattern for using the returned iterator is: +// +// it := set.Iterator() +// for it.Next() { +// val := it.Value() +// // ... +// } +// +// Once an iterator has been created for a set, the set *must not* be mutated +// until the iterator is no longer in use. +func (s Set) Iterator() *Iterator { + vals := s.Values() + + return &Iterator{ + vals: vals, + idx: -1, + } +} + +// EachValue calls the given callback once for each value in the set, in an +// undefined order that callers should not depend on. +func (s Set) EachValue(cb func(interface{})) { + it := s.Iterator() + for it.Next() { + cb(it.Value()) + } +} + +// Values returns a slice of all the values in the set. If the set rules have +// an order then the result is in that order. If no order is provided or if +// it is not a total order then the result order is undefined, but consistent +// for a particular set value within a specific release of cty. +func (s Set) Values() []interface{} { + var ret []interface{} + // Sort the bucketIds to ensure that we always traverse in a + // consistent order. + bucketIDs := make([]int, 0, len(s.vals)) + for id := range s.vals { + bucketIDs = append(bucketIDs, id) + } + sort.Ints(bucketIDs) + + for _, bucketID := range bucketIDs { + ret = append(ret, s.vals[bucketID]...) + } + + if orderRules, ok := s.rules.(OrderedRules); ok { + sort.SliceStable(ret, func(i, j int) bool { + return orderRules.Less(ret[i], ret[j]) + }) + } + + return ret +} + +// Length returns the number of values in the set. +func (s Set) Length() int { + var count int + for _, bucket := range s.vals { + count = count + len(bucket) + } + return count +} + +// Union returns a new set that contains all of the members of both the +// receiving set and the given set. Both sets must have the same rules, or +// else this function will panic. +func (s1 Set) Union(s2 Set) Set { + mustHaveSameRules(s1, s2) + rs := NewSet(s1.rules) + s1.EachValue(func(v interface{}) { + rs.Add(v) + }) + s2.EachValue(func(v interface{}) { + rs.Add(v) + }) + return rs +} + +// Intersection returns a new set that contains the values that both the +// receiver and given sets have in common. Both sets must have the same rules, +// or else this function will panic. +func (s1 Set) Intersection(s2 Set) Set { + mustHaveSameRules(s1, s2) + rs := NewSet(s1.rules) + s1.EachValue(func(v interface{}) { + if s2.Has(v) { + rs.Add(v) + } + }) + return rs +} + +// Subtract returns a new set that contains all of the values from the receiver +// that are not also in the given set. Both sets must have the same rules, +// or else this function will panic. +func (s1 Set) Subtract(s2 Set) Set { + mustHaveSameRules(s1, s2) + rs := NewSet(s1.rules) + s1.EachValue(func(v interface{}) { + if !s2.Has(v) { + rs.Add(v) + } + }) + return rs +} + +// SymmetricDifference returns a new set that contains all of the values from +// both the receiver and given sets, except those that both sets have in +// common. Both sets must have the same rules, or else this function will +// panic. +func (s1 Set) SymmetricDifference(s2 Set) Set { + mustHaveSameRules(s1, s2) + rs := NewSet(s1.rules) + s1.EachValue(func(v interface{}) { + if !s2.Has(v) { + rs.Add(v) + } + }) + s2.EachValue(func(v interface{}) { + if !s1.Has(v) { + rs.Add(v) + } + }) + return rs +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/set/rules.go b/vendor/github.com/hashicorp/go-cty/cty/set/rules.go new file mode 100644 index 00000000000..51f744b5e9a --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/set/rules.go @@ -0,0 +1,43 @@ +package set + +// Rules represents the operations that define membership for a Set. +// +// Each Set has a Rules instance, whose methods must satisfy the interface +// contracts given below for any value that will be added to the set. +type Rules interface { + // Hash returns an int that somewhat-uniquely identifies the given value. + // + // A good hash function will minimize collisions for values that will be + // added to the set, though collisions *are* permitted. Collisions will + // simply reduce the efficiency of operations on the set. + Hash(interface{}) int + + // Equivalent returns true if and only if the two values are considered + // equivalent for the sake of set membership. Two values that are + // equivalent cannot exist in the set at the same time, and if two + // equivalent values are added it is undefined which one will be + // returned when enumerating all of the set members. + // + // Two values that are equivalent *must* result in the same hash value, + // though it is *not* required that two values with the same hash value + // be equivalent. + Equivalent(interface{}, interface{}) bool +} + +// OrderedRules is an extension of Rules that can apply a partial order to +// element values. When a set's Rules implements OrderedRules an iterator +// over the set will return items in the order described by the rules. +// +// If the given order is not a total order (that is, some pairs of non-equivalent +// elements do not have a defined order) then the resulting iteration order +// is undefined but consistent for a particular version of cty. The exact +// order in that case is not part of the contract and is subject to change +// between versions. +type OrderedRules interface { + Rules + + // Less returns true if and only if the first argument should sort before + // the second argument. If the second argument should sort before the first + // or if there is no defined order for the values, return false. + Less(interface{}, interface{}) bool +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/set/set.go b/vendor/github.com/hashicorp/go-cty/cty/set/set.go new file mode 100644 index 00000000000..b4fb316f1cc --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/set/set.go @@ -0,0 +1,62 @@ +package set + +import ( + "fmt" +) + +// Set is an implementation of the concept of a set: a collection where all +// values are conceptually either in or out of the set, but the members are +// not ordered. +// +// This type primarily exists to be the internal type of sets in cty, but +// it is considered to be at the same level of abstraction as Go's built in +// slice and map collection types, and so should make no cty-specific +// assumptions. +// +// Set operations are not thread safe. It is the caller's responsibility to +// provide mutex guarantees where necessary. +// +// Set operations are not optimized to minimize memory pressure. Mutating +// a set will generally create garbage and so should perhaps be avoided in +// tight loops where memory pressure is a concern. +type Set struct { + vals map[int][]interface{} + rules Rules +} + +// NewSet returns an empty set with the membership rules given. +func NewSet(rules Rules) Set { + return Set{ + vals: map[int][]interface{}{}, + rules: rules, + } +} + +func NewSetFromSlice(rules Rules, vals []interface{}) Set { + s := NewSet(rules) + for _, v := range vals { + s.Add(v) + } + return s +} + +func sameRules(s1 Set, s2 Set) bool { + return s1.rules == s2.rules +} + +func mustHaveSameRules(s1 Set, s2 Set) { + if !sameRules(s1, s2) { + panic(fmt.Errorf("incompatible set rules: %#v, %#v", s1.rules, s2.rules)) + } +} + +// HasRules returns true if and only if the receiving set has the given rules +// instance as its rules. +func (s Set) HasRules(rules Rules) bool { + return s.rules == rules +} + +// Rules returns the receiving set's rules instance. +func (s Set) Rules() Rules { + return s.rules +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/set_helper.go b/vendor/github.com/hashicorp/go-cty/cty/set_helper.go new file mode 100644 index 00000000000..31622842621 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/set_helper.go @@ -0,0 +1,132 @@ +package cty + +import ( + "fmt" + + "github.com/hashicorp/go-cty/cty/set" +) + +// ValueSet is to cty.Set what []cty.Value is to cty.List and +// map[string]cty.Value is to cty.Map. It's provided to allow callers a +// convenient interface for manipulating sets before wrapping them in cty.Set +// values using cty.SetValFromValueSet. +// +// Unlike value slices and value maps, ValueSet instances have a single +// homogenous element type because that is a requirement of the underlying +// set implementation, which uses the element type to select a suitable +// hashing function. +// +// Set mutations are not concurrency-safe. +type ValueSet struct { + // ValueSet is just a thin wrapper around a set.Set with our value-oriented + // "rules" applied. We do this so that the caller can work in terms of + // cty.Value objects even though the set internals use the raw values. + s set.Set +} + +// NewValueSet creates and returns a new ValueSet with the given element type. +func NewValueSet(ety Type) ValueSet { + return newValueSet(set.NewSet(setRules{Type: ety})) +} + +func newValueSet(s set.Set) ValueSet { + return ValueSet{ + s: s, + } +} + +// ElementType returns the element type for the receiving ValueSet. +func (s ValueSet) ElementType() Type { + return s.s.Rules().(setRules).Type +} + +// Add inserts the given value into the receiving set. +func (s ValueSet) Add(v Value) { + s.requireElementType(v) + s.s.Add(v.v) +} + +// Remove deletes the given value from the receiving set, if indeed it was +// there in the first place. If the value is not present, this is a no-op. +func (s ValueSet) Remove(v Value) { + s.requireElementType(v) + s.s.Remove(v.v) +} + +// Has returns true if the given value is in the receiving set, or false if +// it is not. +func (s ValueSet) Has(v Value) bool { + s.requireElementType(v) + return s.s.Has(v.v) +} + +// Copy performs a shallow copy of the receiving set, returning a new set +// with the same rules and elements. +func (s ValueSet) Copy() ValueSet { + return newValueSet(s.s.Copy()) +} + +// Length returns the number of values in the set. +func (s ValueSet) Length() int { + return s.s.Length() +} + +// Values returns a slice of all of the values in the set in no particular +// order. +func (s ValueSet) Values() []Value { + l := s.s.Length() + if l == 0 { + return nil + } + ret := make([]Value, 0, l) + ety := s.ElementType() + for it := s.s.Iterator(); it.Next(); { + ret = append(ret, Value{ + ty: ety, + v: it.Value(), + }) + } + return ret +} + +// Union returns a new set that contains all of the members of both the +// receiving set and the given set. Both sets must have the same element type, +// or else this function will panic. +func (s ValueSet) Union(other ValueSet) ValueSet { + return newValueSet(s.s.Union(other.s)) +} + +// Intersection returns a new set that contains the values that both the +// receiver and given sets have in common. Both sets must have the same element +// type, or else this function will panic. +func (s ValueSet) Intersection(other ValueSet) ValueSet { + return newValueSet(s.s.Intersection(other.s)) +} + +// Subtract returns a new set that contains all of the values from the receiver +// that are not also in the given set. Both sets must have the same element +// type, or else this function will panic. +func (s ValueSet) Subtract(other ValueSet) ValueSet { + return newValueSet(s.s.Subtract(other.s)) +} + +// SymmetricDifference returns a new set that contains all of the values from +// both the receiver and given sets, except those that both sets have in +// common. Both sets must have the same element type, or else this function +// will panic. +func (s ValueSet) SymmetricDifference(other ValueSet) ValueSet { + return newValueSet(s.s.SymmetricDifference(other.s)) +} + +// requireElementType panics if the given value is not of the set's element type. +// +// It also panics if the given value is marked, because marked values cannot +// be stored in sets. +func (s ValueSet) requireElementType(v Value) { + if v.IsMarked() { + panic("cannot store marked value directly in a set (make the set itself unknown instead)") + } + if !v.Type().Equals(s.ElementType()) { + panic(fmt.Errorf("attempt to use %#v value with set of %#v", v.Type(), s.ElementType())) + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/set_internals.go b/vendor/github.com/hashicorp/go-cty/cty/set_internals.go new file mode 100644 index 00000000000..4080198097e --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/set_internals.go @@ -0,0 +1,244 @@ +package cty + +import ( + "bytes" + "fmt" + "hash/crc32" + "math/big" + "sort" + + "github.com/hashicorp/go-cty/cty/set" +) + +// setRules provides a Rules implementation for the ./set package that +// respects the equality rules for cty values of the given type. +// +// This implementation expects that values added to the set will be +// valid internal values for the given Type, which is to say that wrapping +// the given value in a Value struct along with the ruleset's type should +// produce a valid, working Value. +type setRules struct { + Type Type +} + +var _ set.OrderedRules = setRules{} + +// Hash returns a hash value for the receiver that can be used for equality +// checks where some inaccuracy is tolerable. +// +// The hash function is value-type-specific, so it is not meaningful to compare +// hash results for values of different types. +// +// This function is not safe to use for security-related applications, since +// the hash used is not strong enough. +func (val Value) Hash() int { + hashBytes, marks := makeSetHashBytes(val) + if len(marks) > 0 { + panic("can't take hash of value that has marks or has embedded values that have marks") + } + return int(crc32.ChecksumIEEE(hashBytes)) +} + +func (r setRules) Hash(v interface{}) int { + return Value{ + ty: r.Type, + v: v, + }.Hash() +} + +func (r setRules) Equivalent(v1 interface{}, v2 interface{}) bool { + v1v := Value{ + ty: r.Type, + v: v1, + } + v2v := Value{ + ty: r.Type, + v: v2, + } + + eqv := v1v.Equals(v2v) + + // By comparing the result to true we ensure that an Unknown result, + // which will result if either value is unknown, will be considered + // as non-equivalent. Two unknown values are not equivalent for the + // sake of set membership. + return eqv.v == true +} + +// Less is an implementation of set.OrderedRules so that we can iterate over +// set elements in a consistent order, where such an order is possible. +func (r setRules) Less(v1, v2 interface{}) bool { + v1v := Value{ + ty: r.Type, + v: v1, + } + v2v := Value{ + ty: r.Type, + v: v2, + } + + if v1v.RawEquals(v2v) { // Easy case: if they are equal then v1 can't be less + return false + } + + // Null values always sort after non-null values + if v2v.IsNull() && !v1v.IsNull() { + return true + } else if v1v.IsNull() { + return false + } + // Unknown values always sort after known values + if v1v.IsKnown() && !v2v.IsKnown() { + return true + } else if !v1v.IsKnown() { + return false + } + + switch r.Type { + case String: + // String values sort lexicographically + return v1v.AsString() < v2v.AsString() + case Bool: + // Weird to have a set of bools, but if we do then false sorts before true. + if v2v.True() || !v1v.True() { + return true + } + return false + case Number: + v1f := v1v.AsBigFloat() + v2f := v2v.AsBigFloat() + return v1f.Cmp(v2f) < 0 + default: + // No other types have a well-defined ordering, so we just produce a + // default consistent-but-undefined ordering then. This situation is + // not considered a compatibility constraint; callers should rely only + // on the ordering rules for primitive values. + v1h, _ := makeSetHashBytes(v1v) + v2h, _ := makeSetHashBytes(v2v) + return bytes.Compare(v1h, v2h) < 0 + } +} + +func makeSetHashBytes(val Value) ([]byte, ValueMarks) { + var buf bytes.Buffer + marks := make(ValueMarks) + appendSetHashBytes(val, &buf, marks) + return buf.Bytes(), marks +} + +func appendSetHashBytes(val Value, buf *bytes.Buffer, marks ValueMarks) { + // Exactly what bytes we generate here don't matter as long as the following + // constraints hold: + // - Unknown and null values all generate distinct strings from + // each other and from any normal value of the given type. + // - The delimiter used to separate items in a compound structure can + // never appear literally in any of its elements. + // Since we don't support hetrogenous lists we don't need to worry about + // collisions between values of different types, apart from + // PseudoTypeDynamic. + // If in practice we *do* get a collision then it's not a big deal because + // the Equivalent function will still distinguish values, but set + // performance will be best if we are able to produce a distinct string + // for each distinct value, unknown values notwithstanding. + + // Marks aren't considered part of a value for equality-testing purposes, + // so we'll unmark our value before we work with it but we'll remember + // the marks in case the caller needs to re-apply them to a derived + // value. + if val.IsMarked() { + unmarkedVal, valMarks := val.Unmark() + for m := range valMarks { + marks[m] = struct{}{} + } + val = unmarkedVal + } + + if !val.IsKnown() { + buf.WriteRune('?') + return + } + if val.IsNull() { + buf.WriteRune('~') + return + } + + switch val.ty { + case Number: + // Due to an unfortunate quirk of gob encoding for big.Float, we end up + // with non-pointer values immediately after a gob round-trip, and + // we end up in here before we've had a chance to run + // gobDecodeFixNumberPtr on the inner values of a gob-encoded set, + // and so sadly we must make a special effort to handle that situation + // here just so that we can get far enough along to fix it up for + // everything else in this package. + if bf, ok := val.v.(big.Float); ok { + buf.WriteString(bf.String()) + return + } + buf.WriteString(val.v.(*big.Float).String()) + return + case Bool: + if val.v.(bool) { + buf.WriteRune('T') + } else { + buf.WriteRune('F') + } + return + case String: + buf.WriteString(fmt.Sprintf("%q", val.v.(string))) + return + } + + if val.ty.IsMapType() { + buf.WriteRune('{') + val.ForEachElement(func(keyVal, elementVal Value) bool { + appendSetHashBytes(keyVal, buf, marks) + buf.WriteRune(':') + appendSetHashBytes(elementVal, buf, marks) + buf.WriteRune(';') + return false + }) + buf.WriteRune('}') + return + } + + if val.ty.IsListType() || val.ty.IsSetType() { + buf.WriteRune('[') + val.ForEachElement(func(keyVal, elementVal Value) bool { + appendSetHashBytes(elementVal, buf, marks) + buf.WriteRune(';') + return false + }) + buf.WriteRune(']') + return + } + + if val.ty.IsObjectType() { + buf.WriteRune('<') + attrNames := make([]string, 0, len(val.ty.AttributeTypes())) + for attrName := range val.ty.AttributeTypes() { + attrNames = append(attrNames, attrName) + } + sort.Strings(attrNames) + for _, attrName := range attrNames { + appendSetHashBytes(val.GetAttr(attrName), buf, marks) + buf.WriteRune(';') + } + buf.WriteRune('>') + return + } + + if val.ty.IsTupleType() { + buf.WriteRune('<') + val.ForEachElement(func(keyVal, elementVal Value) bool { + appendSetHashBytes(elementVal, buf, marks) + buf.WriteRune(';') + return false + }) + buf.WriteRune('>') + return + } + + // should never get down here + panic("unsupported type in set hash") +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/set_type.go b/vendor/github.com/hashicorp/go-cty/cty/set_type.go new file mode 100644 index 00000000000..cbc3706f2c4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/set_type.go @@ -0,0 +1,72 @@ +package cty + +import ( + "fmt" +) + +type typeSet struct { + typeImplSigil + ElementTypeT Type +} + +// Set creates a set type with the given element Type. +// +// Set types are CollectionType implementations. +func Set(elem Type) Type { + return Type{ + typeSet{ + ElementTypeT: elem, + }, + } +} + +// Equals returns true if the other Type is a set whose element type is +// equal to that of the receiver. +func (t typeSet) Equals(other Type) bool { + ot, isSet := other.typeImpl.(typeSet) + if !isSet { + return false + } + + return t.ElementTypeT.Equals(ot.ElementTypeT) +} + +func (t typeSet) FriendlyName(mode friendlyTypeNameMode) string { + elemName := t.ElementTypeT.friendlyNameMode(mode) + if mode == friendlyTypeConstraintName { + if t.ElementTypeT == DynamicPseudoType { + elemName = "any single type" + } + } + return "set of " + elemName +} + +func (t typeSet) ElementType() Type { + return t.ElementTypeT +} + +func (t typeSet) GoString() string { + return fmt.Sprintf("cty.Set(%#v)", t.ElementTypeT) +} + +// IsSetType returns true if the given type is a list type, regardless of its +// element type. +func (t Type) IsSetType() bool { + _, ok := t.typeImpl.(typeSet) + return ok +} + +// SetElementType is a convenience method that checks if the given type is +// a set type, returning a pointer to its element type if so and nil +// otherwise. This is intended to allow convenient conditional branches, +// like so: +// +// if et := t.SetElementType(); et != nil { +// // Do something with *et +// } +func (t Type) SetElementType() *Type { + if lt, ok := t.typeImpl.(typeSet); ok { + return <.ElementTypeT + } + return nil +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/tuple_type.go b/vendor/github.com/hashicorp/go-cty/cty/tuple_type.go new file mode 100644 index 00000000000..798cacd63a1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/tuple_type.go @@ -0,0 +1,121 @@ +package cty + +import ( + "fmt" +) + +type typeTuple struct { + typeImplSigil + ElemTypes []Type +} + +// Tuple creates a tuple type with the given element types. +// +// After a slice is passed to this function the caller must no longer access +// the underlying array, since ownership is transferred to this library. +func Tuple(elemTypes []Type) Type { + return Type{ + typeTuple{ + ElemTypes: elemTypes, + }, + } +} + +func (t typeTuple) Equals(other Type) bool { + if ot, ok := other.typeImpl.(typeTuple); ok { + if len(t.ElemTypes) != len(ot.ElemTypes) { + // Fast path: if we don't have the same number of elements + // then we can't possibly be equal. + return false + } + + for i, ty := range t.ElemTypes { + oty := ot.ElemTypes[i] + if !ok { + return false + } + if !oty.Equals(ty) { + return false + } + } + + return true + } + return false +} + +func (t typeTuple) FriendlyName(mode friendlyTypeNameMode) string { + // There isn't really a friendly way to write a tuple type due to its + // complexity, so we'll just do something English-ish. Callers will + // probably want to make some extra effort to avoid ever printing out + // a tuple type FriendlyName in its entirety. For example, could + // produce an error message by diffing two object types and saying + // something like "Expected attribute foo to be string, but got number". + // TODO: Finish this + return "tuple" +} + +func (t typeTuple) GoString() string { + if len(t.ElemTypes) == 0 { + return "cty.EmptyTuple" + } + return fmt.Sprintf("cty.Tuple(%#v)", t.ElemTypes) +} + +// EmptyTuple is a shorthand for Tuple([]Type{}), to more easily talk about +// the empty tuple type. +var EmptyTuple Type + +// EmptyTupleVal is the only possible non-null, non-unknown value of type +// EmptyTuple. +var EmptyTupleVal Value + +func init() { + EmptyTuple = Tuple([]Type{}) + EmptyTupleVal = Value{ + ty: EmptyTuple, + v: []interface{}{}, + } +} + +// IsTupleType returns true if the given type is an object type, regardless +// of its element type. +func (t Type) IsTupleType() bool { + _, ok := t.typeImpl.(typeTuple) + return ok +} + +// Length returns the number of elements of the receiving tuple type. +// Will panic if the reciever isn't a tuple type; use IsTupleType to determine +// whether this operation will succeed. +func (t Type) Length() int { + if ot, ok := t.typeImpl.(typeTuple); ok { + return len(ot.ElemTypes) + } + panic("Length on non-tuple Type") +} + +// TupleElementType returns the type of the element with the given index. Will +// panic if the receiver is not a tuple type (use IsTupleType to confirm) +// or if the index is out of range (use Length to confirm). +func (t Type) TupleElementType(idx int) Type { + if ot, ok := t.typeImpl.(typeTuple); ok { + return ot.ElemTypes[idx] + } + panic("TupleElementType on non-tuple Type") +} + +// TupleElementTypes returns a slice of the recieving tuple type's element +// types. Will panic if the receiver is not a tuple type (use IsTupleType +// to confirm). +// +// The returned slice is part of the internal state of the type, and is provided +// for read access only. It is forbidden for any caller to modify the +// underlying array. For many purposes the element-related methods of Value +// are more appropriate and more convenient to use. +func (t Type) TupleElementTypes() []Type { + if ot, ok := t.typeImpl.(typeTuple); ok { + return ot.ElemTypes + } + panic("TupleElementTypes on non-tuple Type") +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/type.go b/vendor/github.com/hashicorp/go-cty/cty/type.go new file mode 100644 index 00000000000..730cb9862ef --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/type.go @@ -0,0 +1,120 @@ +package cty + +// Type represents value types within the type system. +// +// This is a closed interface type, meaning that only the concrete +// implementations provided within this package are considered valid. +type Type struct { + typeImpl +} + +type typeImpl interface { + // isTypeImpl is a do-nothing method that exists only to express + // that a type is an implementation of typeImpl. + isTypeImpl() typeImplSigil + + // Equals returns true if the other given Type exactly equals the + // receiver Type. + Equals(other Type) bool + + // FriendlyName returns a human-friendly *English* name for the given + // type. + FriendlyName(mode friendlyTypeNameMode) string + + // GoString implements the GoStringer interface from package fmt. + GoString() string +} + +// Base implementation of Type to embed into concrete implementations +// to signal that they are implementations of Type. +type typeImplSigil struct{} + +func (t typeImplSigil) isTypeImpl() typeImplSigil { + return typeImplSigil{} +} + +// Equals returns true if the other given Type exactly equals the receiver +// type. +func (t Type) Equals(other Type) bool { + return t.typeImpl.Equals(other) +} + +// FriendlyName returns a human-friendly *English* name for the given type. +func (t Type) FriendlyName() string { + return t.typeImpl.FriendlyName(friendlyTypeName) +} + +// FriendlyNameForConstraint is similar to FriendlyName except that the +// result is specialized for describing type _constraints_ rather than types +// themselves. This is more appropriate when reporting that a particular value +// does not conform to an expected type constraint. +// +// In particular, this function uses the term "any type" to refer to +// cty.DynamicPseudoType, rather than "dynamic" as returned by FriendlyName. +func (t Type) FriendlyNameForConstraint() string { + return t.typeImpl.FriendlyName(friendlyTypeConstraintName) +} + +// friendlyNameMode is an internal combination of the various FriendlyName* +// variants that just directly takes a mode, for easy passthrough for +// recursive name construction. +func (t Type) friendlyNameMode(mode friendlyTypeNameMode) string { + return t.typeImpl.FriendlyName(mode) +} + +// GoString returns a string approximating how the receiver type would be +// expressed in Go source code. +func (t Type) GoString() string { + if t.typeImpl == nil { + return "cty.NilType" + } + + return t.typeImpl.GoString() +} + +// NilType is an invalid type used when a function is returning an error +// and has no useful type to return. It should not be used and any methods +// called on it will panic. +var NilType = Type{} + +// HasDynamicTypes returns true either if the receiver is itself +// DynamicPseudoType or if it is a compound type whose descendent elements +// are DynamicPseudoType. +func (t Type) HasDynamicTypes() bool { + switch { + case t == DynamicPseudoType: + return true + case t.IsPrimitiveType(): + return false + case t.IsCollectionType(): + return false + case t.IsObjectType(): + attrTypes := t.AttributeTypes() + for _, at := range attrTypes { + if at.HasDynamicTypes() { + return true + } + } + return false + case t.IsTupleType(): + elemTypes := t.TupleElementTypes() + for _, et := range elemTypes { + if et.HasDynamicTypes() { + return true + } + } + return false + case t.IsCapsuleType(): + return false + default: + // Should never happen, since above should be exhaustive + panic("HasDynamicTypes does not support the given type") + } +} + +type friendlyTypeNameMode rune + +const ( + friendlyTypeName friendlyTypeNameMode = 'N' + friendlyTypeConstraintName friendlyTypeNameMode = 'C' +) diff --git a/vendor/github.com/hashicorp/go-cty/cty/type_conform.go b/vendor/github.com/hashicorp/go-cty/cty/type_conform.go new file mode 100644 index 00000000000..476eeea87fc --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/type_conform.go @@ -0,0 +1,139 @@ +package cty + +// TestConformance recursively walks the receiver and the given other type and +// returns nil if the receiver *conforms* to the given type. +// +// Type conformance is similar to type equality but has one crucial difference: +// PseudoTypeDynamic can be used within the given type to represent that +// *any* type is allowed. +// +// If any non-conformities are found, the returned slice will be non-nil and +// contain at least one error value. It will be nil if the type is entirely +// conformant. +// +// Note that the special behavior of PseudoTypeDynamic is the *only* exception +// to normal type equality. Calling applications may wish to apply their own +// automatic conversion logic to the given data structure to create a more +// liberal notion of conformance to a type. +// +// Returned errors are usually (but not always) PathError instances that +// indicate where in the structure the error was found. If a returned error +// is of that type then the error message is written for (English-speaking) +// end-users working within the cty type system, not mentioning any Go-oriented +// implementation details. +func (t Type) TestConformance(other Type) []error { + path := make(Path, 0) + var errs []error + testConformance(t, other, path, &errs) + return errs +} + +func testConformance(given Type, want Type, path Path, errs *[]error) { + if want.Equals(DynamicPseudoType) { + // anything goes! + return + } + + if given.Equals(want) { + // Any equal types are always conformant + return + } + + // The remainder of this function is concerned with detecting + // and reporting the specific non-conformance, since we wouldn't + // have got here if the types were not divergent. + // We treat compound structures as special so that we can report + // specifically what is non-conforming, rather than simply returning + // the entire type names and letting the user puzzle it out. + + if given.IsObjectType() && want.IsObjectType() { + givenAttrs := given.AttributeTypes() + wantAttrs := want.AttributeTypes() + + for k := range givenAttrs { + if _, exists := wantAttrs[k]; !exists { + *errs = append( + *errs, + errorf(path, "unsupported attribute %q", k), + ) + } + } + for k := range wantAttrs { + if _, exists := givenAttrs[k]; !exists { + *errs = append( + *errs, + errorf(path, "missing required attribute %q", k), + ) + } + } + + path = append(path, nil) + pathIdx := len(path) - 1 + + for k, wantAttrType := range wantAttrs { + if givenAttrType, exists := givenAttrs[k]; exists { + path[pathIdx] = GetAttrStep{Name: k} + testConformance(givenAttrType, wantAttrType, path, errs) + } + } + + path = path[0:pathIdx] + + return + } + + if given.IsTupleType() && want.IsTupleType() { + givenElems := given.TupleElementTypes() + wantElems := want.TupleElementTypes() + + if len(givenElems) != len(wantElems) { + *errs = append( + *errs, + errorf(path, "%d elements are required, but got %d", len(wantElems), len(givenElems)), + ) + return + } + + path = append(path, nil) + pathIdx := len(path) - 1 + + for i, wantElemType := range wantElems { + givenElemType := givenElems[i] + path[pathIdx] = IndexStep{Key: NumberIntVal(int64(i))} + testConformance(givenElemType, wantElemType, path, errs) + } + + path = path[0:pathIdx] + + return + } + + if given.IsListType() && want.IsListType() { + path = append(path, IndexStep{Key: UnknownVal(Number)}) + pathIdx := len(path) - 1 + testConformance(given.ElementType(), want.ElementType(), path, errs) + path = path[0:pathIdx] + return + } + + if given.IsMapType() && want.IsMapType() { + path = append(path, IndexStep{Key: UnknownVal(String)}) + pathIdx := len(path) - 1 + testConformance(given.ElementType(), want.ElementType(), path, errs) + path = path[0:pathIdx] + return + } + + if given.IsSetType() && want.IsSetType() { + path = append(path, IndexStep{Key: UnknownVal(given.ElementType())}) + pathIdx := len(path) - 1 + testConformance(given.ElementType(), want.ElementType(), path, errs) + path = path[0:pathIdx] + return + } + + *errs = append( + *errs, + errorf(path, "%s required, but received %s", want.FriendlyName(), given.FriendlyName()), + ) +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/types_to_register.go b/vendor/github.com/hashicorp/go-cty/cty/types_to_register.go new file mode 100644 index 00000000000..ec05bb18aa0 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/types_to_register.go @@ -0,0 +1,57 @@ +package cty + +import ( + "encoding/gob" + "fmt" + "math/big" + "strings" + + "github.com/hashicorp/go-cty/cty/set" +) + +// InternalTypesToRegister is a slice of values that covers all of the +// internal types used in the representation of cty.Type and cty.Value +// across all cty Types. +// +// This is intended to be used to register these types with encoding +// packages that require registration of types used in interfaces, such as +// encoding/gob, thus allowing cty types and values to be included in streams +// created from those packages. However, registering with gob is not necessary +// since that is done automatically as a side-effect of importing this package. +// +// Callers should not do anything with the values here except pass them on +// verbatim to a registration function. +// +// If the calling application uses Capsule types that wrap local structs either +// directly or indirectly, these structs may also need to be registered in +// order to support encoding and decoding of values of these types. That is the +// responsibility of the calling application. +var InternalTypesToRegister []interface{} + +func init() { + InternalTypesToRegister = []interface{}{ + primitiveType{}, + typeList{}, + typeMap{}, + typeObject{}, + typeSet{}, + setRules{}, + set.Set{}, + typeTuple{}, + big.Float{}, + capsuleType{}, + []interface{}(nil), + map[string]interface{}(nil), + } + + // Register these with gob here, rather than in gob.go, to ensure + // that this will always happen after we build the above. + for _, tv := range InternalTypesToRegister { + typeName := fmt.Sprintf("%T", tv) + if strings.HasPrefix(typeName, "cty.") { + gob.RegisterName(fmt.Sprintf("github.com/hashicorp/go-cty/%s", typeName), tv) + } else { + gob.Register(tv) + } + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/unknown.go b/vendor/github.com/hashicorp/go-cty/cty/unknown.go new file mode 100644 index 00000000000..e54179eb144 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/unknown.go @@ -0,0 +1,84 @@ +package cty + +// unknownType is the placeholder type used for the sigil value representing +// "Unknown", to make it unambigiously distinct from any other possible value. +type unknownType struct { +} + +// Unknown is a special value that can be +var unknown interface{} = &unknownType{} + +// UnknownVal returns an Value that represents an unknown value of the given +// type. Unknown values can be used to represent a value that is +// not yet known. Its meaning is undefined in cty, but it could be used by +// an calling application to allow partial evaluation. +// +// Unknown values of any type can be created of any type. All operations on +// Unknown values themselves return Unknown. +func UnknownVal(t Type) Value { + return Value{ + ty: t, + v: unknown, + } +} + +func (t unknownType) GoString() string { + // This is the stringification of our internal unknown marker. The + // stringification of the public representation of unknowns is in + // Value.GoString. + return "cty.unknown" +} + +type pseudoTypeDynamic struct { + typeImplSigil +} + +// DynamicPseudoType represents the dynamic pseudo-type. +// +// This type can represent situations where a type is not yet known. Its +// meaning is undefined in cty, but it could be used by a calling +// application to allow expression type checking with some types not yet known. +// For example, the application might optimistically permit any operation on +// values of this type in type checking, allowing a partial type-check result, +// and then repeat the check when more information is known to get the +// final, concrete type. +// +// It is a pseudo-type because it is used only as a sigil to the calling +// application. "Unknown" is the only valid value of this pseudo-type, so +// operations on values of this type will always short-circuit as per +// the rules for that special value. +var DynamicPseudoType Type + +func (t pseudoTypeDynamic) Equals(other Type) bool { + _, ok := other.typeImpl.(pseudoTypeDynamic) + return ok +} + +func (t pseudoTypeDynamic) FriendlyName(mode friendlyTypeNameMode) string { + switch mode { + case friendlyTypeConstraintName: + return "any type" + default: + return "dynamic" + } +} + +func (t pseudoTypeDynamic) GoString() string { + return "cty.DynamicPseudoType" +} + +// DynamicVal is the only valid value of the pseudo-type dynamic. +// This value can be used as a placeholder where a value or expression's +// type and value are both unknown, thus allowing partial evaluation. See +// the docs for DynamicPseudoType for more information. +var DynamicVal Value + +func init() { + DynamicPseudoType = Type{ + pseudoTypeDynamic{}, + } + DynamicVal = Value{ + ty: DynamicPseudoType, + v: unknown, + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/unknown_as_null.go b/vendor/github.com/hashicorp/go-cty/cty/unknown_as_null.go new file mode 100644 index 00000000000..ba926475ce5 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/unknown_as_null.go @@ -0,0 +1,64 @@ +package cty + +// UnknownAsNull returns a value of the same type as the given value but +// with any unknown values (including nested values) replaced with null +// values of the same type. +// +// This can be useful if a result is to be serialized in a format that can't +// represent unknowns, such as JSON, as long as the caller does not need to +// retain the unknown value information. +func UnknownAsNull(val Value) Value { + ty := val.Type() + switch { + case val.IsNull(): + return val + case !val.IsKnown(): + return NullVal(ty) + case ty.IsListType() || ty.IsTupleType() || ty.IsSetType(): + length := val.LengthInt() + if length == 0 { + // If there are no elements then we can't have unknowns + return val + } + vals := make([]Value, 0, length) + it := val.ElementIterator() + for it.Next() { + _, v := it.Element() + vals = append(vals, UnknownAsNull(v)) + } + switch { + case ty.IsListType(): + return ListVal(vals) + case ty.IsTupleType(): + return TupleVal(vals) + default: + return SetVal(vals) + } + case ty.IsMapType() || ty.IsObjectType(): + var length int + switch { + case ty.IsMapType(): + length = val.LengthInt() + default: + length = len(val.Type().AttributeTypes()) + } + if length == 0 { + // If there are no elements then we can't have unknowns + return val + } + vals := make(map[string]Value, length) + it := val.ElementIterator() + for it.Next() { + k, v := it.Element() + vals[k.AsString()] = UnknownAsNull(v) + } + switch { + case ty.IsMapType(): + return MapVal(vals) + default: + return ObjectVal(vals) + } + } + + return val +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/value.go b/vendor/github.com/hashicorp/go-cty/cty/value.go new file mode 100644 index 00000000000..1025ba82eba --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/value.go @@ -0,0 +1,108 @@ +package cty + +// Value represents a value of a particular type, and is the interface by +// which operations are executed on typed values. +// +// Value has two different classes of method. Operation methods stay entirely +// within the type system (methods accept and return Value instances) and +// are intended for use in implementing a language in terms of cty, while +// integration methods either enter or leave the type system, working with +// native Go values. Operation methods are guaranteed to support all of the +// expected short-circuit behavior for unknown and dynamic values, while +// integration methods may not. +// +// The philosophy for the operations API is that it's the caller's +// responsibility to ensure that the given types and values satisfy the +// specified invariants during a separate type check, so that the caller is +// able to return errors to its user from the application's own perspective. +// +// Consequently the design of these methods assumes such checks have already +// been done and panics if any invariants turn out not to be satisfied. These +// panic errors are not intended to be handled, but rather indicate a bug in +// the calling application that should be fixed with more checks prior to +// executing operations. +// +// A related consequence of this philosophy is that no automatic type +// conversions are done. If a method specifies that its argument must be +// number then it's the caller's responsibility to do that conversion before +// the call, thus allowing the application to have more constrained conversion +// rules than are offered by the built-in converter where necessary. +type Value struct { + ty Type + v interface{} +} + +// Type returns the type of the value. +func (val Value) Type() Type { + return val.ty +} + +// IsKnown returns true if the value is known. That is, if it is not +// the result of the unknown value constructor Unknown(...), and is not +// the result of an operation on another unknown value. +// +// Unknown values are only produced either directly or as a result of +// operating on other unknown values, and so an application that never +// introduces Unknown values can be guaranteed to never receive any either. +func (val Value) IsKnown() bool { + if val.IsMarked() { + return val.unmarkForce().IsKnown() + } + return val.v != unknown +} + +// IsNull returns true if the value is null. Values of any type can be +// null, but any operations on a null value will panic. No operation ever +// produces null, so an application that never introduces Null values can +// be guaranteed to never receive any either. +func (val Value) IsNull() bool { + if val.IsMarked() { + return val.unmarkForce().IsNull() + } + return val.v == nil +} + +// NilVal is an invalid Value that can be used as a placeholder when returning +// with an error from a function that returns (Value, error). +// +// NilVal is *not* a valid error and so no operations may be performed on it. +// Any attempt to use it will result in a panic. +// +// This should not be confused with the idea of a Null value, as returned by +// NullVal. NilVal is a nil within the *Go* type system, and is invalid in +// the cty type system. Null values *do* exist in the cty type system. +var NilVal = Value{ + ty: Type{typeImpl: nil}, + v: nil, +} + +// IsWhollyKnown is an extension of IsKnown that also recursively checks +// inside collections and structures to see if there are any nested unknown +// values. +func (val Value) IsWhollyKnown() bool { + if val.IsMarked() { + return val.unmarkForce().IsWhollyKnown() + } + + if !val.IsKnown() { + return false + } + + if val.IsNull() { + // Can't recurse into a null, so we're done + return true + } + + switch { + case val.CanIterateElements(): + for it := val.ElementIterator(); it.Next(); { + _, ev := it.Element() + if !ev.IsWhollyKnown() { + return false + } + } + return true + default: + return true + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/value_init.go b/vendor/github.com/hashicorp/go-cty/cty/value_init.go new file mode 100644 index 00000000000..853a5a7dba1 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/value_init.go @@ -0,0 +1,324 @@ +package cty + +import ( + "fmt" + "math/big" + "reflect" + + "golang.org/x/text/unicode/norm" + + "github.com/hashicorp/go-cty/cty/set" +) + +// BoolVal returns a Value of type Number whose internal value is the given +// bool. +func BoolVal(v bool) Value { + return Value{ + ty: Bool, + v: v, + } +} + +// NumberVal returns a Value of type Number whose internal value is the given +// big.Float. The returned value becomes the owner of the big.Float object, +// and so it's forbidden for the caller to mutate the object after it's +// wrapped in this way. +func NumberVal(v *big.Float) Value { + return Value{ + ty: Number, + v: v, + } +} + +// ParseNumberVal returns a Value of type number produced by parsing the given +// string as a decimal real number. To ensure that two identical strings will +// always produce an equal number, always use this function to derive a number +// from a string; it will ensure that the precision and rounding mode for the +// internal big decimal is configured in a consistent way. +// +// If the given string cannot be parsed as a number, the returned error has +// the message "a number is required", making it suitable to return to an +// end-user to signal a type conversion error. +// +// If the given string contains a number that becomes a recurring fraction +// when expressed in binary then it will be truncated to have a 512-bit +// mantissa. Note that this is a higher precision than that of a float64, +// so coverting the same decimal number first to float64 and then calling +// NumberFloatVal will not produce an equal result; the conversion first +// to float64 will round the mantissa to fewer than 512 bits. +func ParseNumberVal(s string) (Value, error) { + // Base 10, precision 512, and rounding to nearest even is the standard + // way to handle numbers arriving as strings. + f, _, err := big.ParseFloat(s, 10, 512, big.ToNearestEven) + if err != nil { + return NilVal, fmt.Errorf("a number is required") + } + return NumberVal(f), nil +} + +// MustParseNumberVal is like ParseNumberVal but it will panic in case of any +// error. It can be used during initialization or any other situation where +// the given string is a constant or otherwise known to be correct by the +// caller. +func MustParseNumberVal(s string) Value { + ret, err := ParseNumberVal(s) + if err != nil { + panic(err) + } + return ret +} + +// NumberIntVal returns a Value of type Number whose internal value is equal +// to the given integer. +func NumberIntVal(v int64) Value { + return NumberVal(new(big.Float).SetInt64(v)) +} + +// NumberUIntVal returns a Value of type Number whose internal value is equal +// to the given unsigned integer. +func NumberUIntVal(v uint64) Value { + return NumberVal(new(big.Float).SetUint64(v)) +} + +// NumberFloatVal returns a Value of type Number whose internal value is +// equal to the given float. +func NumberFloatVal(v float64) Value { + return NumberVal(new(big.Float).SetFloat64(v)) +} + +// StringVal returns a Value of type String whose internal value is the +// given string. +// +// Strings must be UTF-8 encoded sequences of valid unicode codepoints, and +// they are NFC-normalized on entry into the world of cty values. +// +// If the given string is not valid UTF-8 then behavior of string operations +// is undefined. +func StringVal(v string) Value { + return Value{ + ty: String, + v: NormalizeString(v), + } +} + +// NormalizeString applies the same normalization that cty applies when +// constructing string values. +// +// A return value from this function can be meaningfully compared byte-for-byte +// with a Value.AsString result. +func NormalizeString(s string) string { + return norm.NFC.String(s) +} + +// ObjectVal returns a Value of an object type whose structure is defined +// by the key names and value types in the given map. +func ObjectVal(attrs map[string]Value) Value { + attrTypes := make(map[string]Type, len(attrs)) + attrVals := make(map[string]interface{}, len(attrs)) + + for attr, val := range attrs { + attr = NormalizeString(attr) + attrTypes[attr] = val.ty + attrVals[attr] = val.v + } + + return Value{ + ty: Object(attrTypes), + v: attrVals, + } +} + +// TupleVal returns a Value of a tuple type whose element types are +// defined by the value types in the given slice. +func TupleVal(elems []Value) Value { + elemTypes := make([]Type, len(elems)) + elemVals := make([]interface{}, len(elems)) + + for i, val := range elems { + elemTypes[i] = val.ty + elemVals[i] = val.v + } + + return Value{ + ty: Tuple(elemTypes), + v: elemVals, + } +} + +// ListVal returns a Value of list type whose element type is defined by +// the types of the given values, which must be homogenous. +// +// If the types are not all consistent (aside from elements that are of the +// dynamic pseudo-type) then this function will panic. It will panic also +// if the given list is empty, since then the element type cannot be inferred. +// (See also ListValEmpty.) +func ListVal(vals []Value) Value { + if len(vals) == 0 { + panic("must not call ListVal with empty slice") + } + elementType := DynamicPseudoType + rawList := make([]interface{}, len(vals)) + + for i, val := range vals { + if elementType == DynamicPseudoType { + elementType = val.ty + } else if val.ty != DynamicPseudoType && !elementType.Equals(val.ty) { + panic(fmt.Errorf( + "inconsistent list element types (%#v then %#v)", + elementType, val.ty, + )) + } + + rawList[i] = val.v + } + + return Value{ + ty: List(elementType), + v: rawList, + } +} + +// ListValEmpty returns an empty list of the given element type. +func ListValEmpty(element Type) Value { + return Value{ + ty: List(element), + v: []interface{}{}, + } +} + +// MapVal returns a Value of a map type whose element type is defined by +// the types of the given values, which must be homogenous. +// +// If the types are not all consistent (aside from elements that are of the +// dynamic pseudo-type) then this function will panic. It will panic also +// if the given map is empty, since then the element type cannot be inferred. +// (See also MapValEmpty.) +func MapVal(vals map[string]Value) Value { + if len(vals) == 0 { + panic("must not call MapVal with empty map") + } + elementType := DynamicPseudoType + rawMap := make(map[string]interface{}, len(vals)) + + for key, val := range vals { + if elementType == DynamicPseudoType { + elementType = val.ty + } else if val.ty != DynamicPseudoType && !elementType.Equals(val.ty) { + panic(fmt.Errorf( + "inconsistent map element types (%#v then %#v)", + elementType, val.ty, + )) + } + + rawMap[NormalizeString(key)] = val.v + } + + return Value{ + ty: Map(elementType), + v: rawMap, + } +} + +// MapValEmpty returns an empty map of the given element type. +func MapValEmpty(element Type) Value { + return Value{ + ty: Map(element), + v: map[string]interface{}{}, + } +} + +// SetVal returns a Value of set type whose element type is defined by +// the types of the given values, which must be homogenous. +// +// If the types are not all consistent (aside from elements that are of the +// dynamic pseudo-type) then this function will panic. It will panic also +// if the given list is empty, since then the element type cannot be inferred. +// (See also SetValEmpty.) +func SetVal(vals []Value) Value { + if len(vals) == 0 { + panic("must not call SetVal with empty slice") + } + elementType := DynamicPseudoType + rawList := make([]interface{}, len(vals)) + var markSets []ValueMarks + + for i, val := range vals { + if unmarkedVal, marks := val.UnmarkDeep(); len(marks) > 0 { + val = unmarkedVal + markSets = append(markSets, marks) + } + if val.ContainsMarked() { + // FIXME: Allow this, but unmark the values and apply the + // marking to the set itself instead. + panic("set cannot contain marked values") + } + if elementType == DynamicPseudoType { + elementType = val.ty + } else if val.ty != DynamicPseudoType && !elementType.Equals(val.ty) { + panic(fmt.Errorf( + "inconsistent set element types (%#v then %#v)", + elementType, val.ty, + )) + } + + rawList[i] = val.v + } + + rawVal := set.NewSetFromSlice(setRules{elementType}, rawList) + + return Value{ + ty: Set(elementType), + v: rawVal, + }.WithMarks(markSets...) +} + +// SetValFromValueSet returns a Value of set type based on an already-constructed +// ValueSet. +// +// The element type of the returned value is the element type of the given +// set. +func SetValFromValueSet(s ValueSet) Value { + ety := s.ElementType() + rawVal := s.s.Copy() // copy so caller can't mutate what we wrap + + return Value{ + ty: Set(ety), + v: rawVal, + } +} + +// SetValEmpty returns an empty set of the given element type. +func SetValEmpty(element Type) Value { + return Value{ + ty: Set(element), + v: set.NewSet(setRules{element}), + } +} + +// CapsuleVal creates a value of the given capsule type using the given +// wrapVal, which must be a pointer to a value of the capsule type's native +// type. +// +// This function will panic if the given type is not a capsule type, if +// the given wrapVal is not compatible with the given capsule type, or if +// wrapVal is not a pointer. +func CapsuleVal(ty Type, wrapVal interface{}) Value { + if !ty.IsCapsuleType() { + panic("not a capsule type") + } + + wv := reflect.ValueOf(wrapVal) + if wv.Kind() != reflect.Ptr { + panic("wrapVal is not a pointer") + } + + it := ty.typeImpl.(*capsuleType).GoType + if !wv.Type().Elem().AssignableTo(it) { + panic("wrapVal target is not compatible with the given capsule type") + } + + return Value{ + ty: ty, + v: wrapVal, + } +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/value_ops.go b/vendor/github.com/hashicorp/go-cty/cty/value_ops.go new file mode 100644 index 00000000000..69e5a8abbf4 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/value_ops.go @@ -0,0 +1,1290 @@ +package cty + +import ( + "fmt" + "math/big" + "reflect" + + "github.com/hashicorp/go-cty/cty/set" +) + +// GoString is an implementation of fmt.GoStringer that produces concise +// source-like representations of values suitable for use in debug messages. +func (val Value) GoString() string { + if val.IsMarked() { + unVal, marks := val.Unmark() + if len(marks) == 1 { + var mark interface{} + for m := range marks { + mark = m + } + return fmt.Sprintf("%#v.Mark(%#v)", unVal, mark) + } + return fmt.Sprintf("%#v.WithMarks(%#v)", unVal, marks) + } + + if val == NilVal { + return "cty.NilVal" + } + + if val.IsNull() { + return fmt.Sprintf("cty.NullVal(%#v)", val.ty) + } + if val == DynamicVal { // is unknown, so must be before the IsKnown check below + return "cty.DynamicVal" + } + if !val.IsKnown() { + return fmt.Sprintf("cty.UnknownVal(%#v)", val.ty) + } + + // By the time we reach here we've dealt with all of the exceptions around + // unknowns and nulls, so we're guaranteed that the values are the + // canonical internal representation of the given type. + + switch val.ty { + case Bool: + if val.v.(bool) { + return "cty.True" + } + return "cty.False" + case Number: + fv := val.v.(*big.Float) + // We'll try to use NumberIntVal or NumberFloatVal if we can, since + // the fully-general initializer call is pretty ugly-looking. + if fv.IsInt() { + return fmt.Sprintf("cty.NumberIntVal(%#v)", fv) + } + if rfv, accuracy := fv.Float64(); accuracy == big.Exact { + return fmt.Sprintf("cty.NumberFloatVal(%#v)", rfv) + } + return fmt.Sprintf("cty.MustParseNumberVal(%q)", fv.Text('f', -1)) + case String: + return fmt.Sprintf("cty.StringVal(%#v)", val.v) + } + + switch { + case val.ty.IsSetType(): + vals := val.AsValueSlice() + if len(vals) == 0 { + return fmt.Sprintf("cty.SetValEmpty(%#v)", val.ty.ElementType()) + } + return fmt.Sprintf("cty.SetVal(%#v)", vals) + case val.ty.IsListType(): + vals := val.AsValueSlice() + if len(vals) == 0 { + return fmt.Sprintf("cty.ListValEmpty(%#v)", val.ty.ElementType()) + } + return fmt.Sprintf("cty.ListVal(%#v)", vals) + case val.ty.IsMapType(): + vals := val.AsValueMap() + if len(vals) == 0 { + return fmt.Sprintf("cty.MapValEmpty(%#v)", val.ty.ElementType()) + } + return fmt.Sprintf("cty.MapVal(%#v)", vals) + case val.ty.IsTupleType(): + if val.ty.Equals(EmptyTuple) { + return "cty.EmptyTupleVal" + } + vals := val.AsValueSlice() + return fmt.Sprintf("cty.TupleVal(%#v)", vals) + case val.ty.IsObjectType(): + if val.ty.Equals(EmptyObject) { + return "cty.EmptyObjectVal" + } + vals := val.AsValueMap() + return fmt.Sprintf("cty.ObjectVal(%#v)", vals) + case val.ty.IsCapsuleType(): + impl := val.ty.CapsuleOps().GoString + if impl == nil { + return fmt.Sprintf("cty.CapsuleVal(%#v, %#v)", val.ty, val.v) + } + return impl(val.EncapsulatedValue()) + } + + // Default exposes implementation details, so should actually cover + // all of the cases above for good caller UX. + return fmt.Sprintf("cty.Value{ty: %#v, v: %#v}", val.ty, val.v) +} + +// Equals returns True if the receiver and the given other value have the +// same type and are exactly equal in value. +// +// As a special case, two null values are always equal regardless of type. +// +// The usual short-circuit rules apply, so the result will be unknown if +// either of the given values are. +// +// Use RawEquals to compare if two values are equal *ignoring* the +// short-circuit rules and the exception for null values. +func (val Value) Equals(other Value) Value { + if val.IsMarked() || other.IsMarked() { + val, valMarks := val.Unmark() + other, otherMarks := other.Unmark() + return val.Equals(other).WithMarks(valMarks, otherMarks) + } + + // Start by handling Unknown values before considering types. + // This needs to be done since Null values are always equal regardless of + // type. + switch { + case !val.IsKnown() && !other.IsKnown(): + // both unknown + return UnknownVal(Bool) + case val.IsKnown() && !other.IsKnown(): + switch { + case val.IsNull(), other.ty.HasDynamicTypes(): + // If known is Null, we need to wait for the unkown value since + // nulls of any type are equal. + // An unkown with a dynamic type compares as unknown, which we need + // to check before the type comparison below. + return UnknownVal(Bool) + case !val.ty.Equals(other.ty): + // There is no null comparison or dynamic types, so unequal types + // will never be equal. + return False + default: + return UnknownVal(Bool) + } + case other.IsKnown() && !val.IsKnown(): + switch { + case other.IsNull(), val.ty.HasDynamicTypes(): + // If known is Null, we need to wait for the unkown value since + // nulls of any type are equal. + // An unkown with a dynamic type compares as unknown, which we need + // to check before the type comparison below. + return UnknownVal(Bool) + case !other.ty.Equals(val.ty): + // There's no null comparison or dynamic types, so unequal types + // will never be equal. + return False + default: + return UnknownVal(Bool) + } + } + + switch { + case val.IsNull() && other.IsNull(): + // Nulls are always equal, regardless of type + return BoolVal(true) + case val.IsNull() || other.IsNull(): + // If only one is null then the result must be false + return BoolVal(false) + } + + if val.ty.HasDynamicTypes() || other.ty.HasDynamicTypes() { + return UnknownVal(Bool) + } + + if !val.ty.Equals(other.ty) { + return BoolVal(false) + } + + ty := val.ty + result := false + + switch { + case ty == Number: + result = val.v.(*big.Float).Cmp(other.v.(*big.Float)) == 0 + case ty == Bool: + result = val.v.(bool) == other.v.(bool) + case ty == String: + // Simple equality is safe because we NFC-normalize strings as they + // enter our world from StringVal, and so we can assume strings are + // always in normal form. + result = val.v.(string) == other.v.(string) + case ty.IsObjectType(): + oty := ty.typeImpl.(typeObject) + result = true + for attr, aty := range oty.AttrTypes { + lhs := Value{ + ty: aty, + v: val.v.(map[string]interface{})[attr], + } + rhs := Value{ + ty: aty, + v: other.v.(map[string]interface{})[attr], + } + eq := lhs.Equals(rhs) + if !eq.IsKnown() { + return UnknownVal(Bool) + } + if eq.False() { + result = false + break + } + } + case ty.IsTupleType(): + tty := ty.typeImpl.(typeTuple) + result = true + for i, ety := range tty.ElemTypes { + lhs := Value{ + ty: ety, + v: val.v.([]interface{})[i], + } + rhs := Value{ + ty: ety, + v: other.v.([]interface{})[i], + } + eq := lhs.Equals(rhs) + if !eq.IsKnown() { + return UnknownVal(Bool) + } + if eq.False() { + result = false + break + } + } + case ty.IsListType(): + ety := ty.typeImpl.(typeList).ElementTypeT + if len(val.v.([]interface{})) == len(other.v.([]interface{})) { + result = true + for i := range val.v.([]interface{}) { + lhs := Value{ + ty: ety, + v: val.v.([]interface{})[i], + } + rhs := Value{ + ty: ety, + v: other.v.([]interface{})[i], + } + eq := lhs.Equals(rhs) + if !eq.IsKnown() { + return UnknownVal(Bool) + } + if eq.False() { + result = false + break + } + } + } + case ty.IsSetType(): + s1 := val.v.(set.Set) + s2 := other.v.(set.Set) + equal := true + + // Note that by our definition of sets it's never possible for two + // sets that contain unknown values (directly or indicrectly) to + // ever be equal, even if they are otherwise identical. + + // FIXME: iterating both lists and checking each item is not the + // ideal implementation here, but it works with the primitives we + // have in the set implementation. Perhaps the set implementation + // can provide its own equality test later. + s1.EachValue(func(v interface{}) { + if !s2.Has(v) { + equal = false + } + }) + s2.EachValue(func(v interface{}) { + if !s1.Has(v) { + equal = false + } + }) + + result = equal + case ty.IsMapType(): + ety := ty.typeImpl.(typeMap).ElementTypeT + if len(val.v.(map[string]interface{})) == len(other.v.(map[string]interface{})) { + result = true + for k := range val.v.(map[string]interface{}) { + if _, ok := other.v.(map[string]interface{})[k]; !ok { + result = false + break + } + lhs := Value{ + ty: ety, + v: val.v.(map[string]interface{})[k], + } + rhs := Value{ + ty: ety, + v: other.v.(map[string]interface{})[k], + } + eq := lhs.Equals(rhs) + if !eq.IsKnown() { + return UnknownVal(Bool) + } + if eq.False() { + result = false + break + } + } + } + case ty.IsCapsuleType(): + impl := val.ty.CapsuleOps().Equals + if impl == nil { + impl := val.ty.CapsuleOps().RawEquals + if impl == nil { + // A capsule type's encapsulated value is a pointer to a value of its + // native type, so we can just compare these to get the identity test + // we need. + return BoolVal(val.v == other.v) + } + return BoolVal(impl(val.v, other.v)) + } + ret := impl(val.v, other.v) + if !ret.Type().Equals(Bool) { + panic(fmt.Sprintf("Equals for %#v returned %#v, not cty.Bool", ty, ret.Type())) + } + return ret + + default: + // should never happen + panic(fmt.Errorf("unsupported value type %#v in Equals", ty)) + } + + return BoolVal(result) +} + +// NotEqual is a shorthand for Equals followed by Not. +func (val Value) NotEqual(other Value) Value { + return val.Equals(other).Not() +} + +// True returns true if the receiver is True, false if False, and panics if +// the receiver is not of type Bool. +// +// This is a helper function to help write application logic that works with +// values, rather than a first-class operation. It does not work with unknown +// or null values. For more robust handling with unknown value +// short-circuiting, use val.Equals(cty.True). +func (val Value) True() bool { + val.assertUnmarked() + if val.ty != Bool { + panic("not bool") + } + return val.Equals(True).v.(bool) +} + +// False is the opposite of True. +func (val Value) False() bool { + return !val.True() +} + +// RawEquals returns true if and only if the two given values have the same +// type and equal value, ignoring the usual short-circuit rules about +// unknowns and dynamic types. +// +// This method is more appropriate for testing than for real use, since it +// skips over usual semantics around unknowns but as a consequence allows +// testing the result of another operation that is expected to return unknown. +// It returns a primitive Go bool rather than a Value to remind us that it +// is not a first-class value operation. +func (val Value) RawEquals(other Value) bool { + if !val.ty.Equals(other.ty) { + return false + } + if !val.HasSameMarks(other) { + return false + } + // Since we've now checked the marks, we'll unmark for the rest of this... + val = val.unmarkForce() + other = other.unmarkForce() + + if (!val.IsKnown()) && (!other.IsKnown()) { + return true + } + if (val.IsKnown() && !other.IsKnown()) || (other.IsKnown() && !val.IsKnown()) { + return false + } + if val.IsNull() && other.IsNull() { + return true + } + if (val.IsNull() && !other.IsNull()) || (other.IsNull() && !val.IsNull()) { + return false + } + if val.ty == DynamicPseudoType && other.ty == DynamicPseudoType { + return true + } + + ty := val.ty + switch { + case ty == Number || ty == Bool || ty == String || ty == DynamicPseudoType: + return val.Equals(other).True() + case ty.IsObjectType(): + oty := ty.typeImpl.(typeObject) + for attr, aty := range oty.AttrTypes { + lhs := Value{ + ty: aty, + v: val.v.(map[string]interface{})[attr], + } + rhs := Value{ + ty: aty, + v: other.v.(map[string]interface{})[attr], + } + eq := lhs.RawEquals(rhs) + if !eq { + return false + } + } + return true + case ty.IsTupleType(): + tty := ty.typeImpl.(typeTuple) + for i, ety := range tty.ElemTypes { + lhs := Value{ + ty: ety, + v: val.v.([]interface{})[i], + } + rhs := Value{ + ty: ety, + v: other.v.([]interface{})[i], + } + eq := lhs.RawEquals(rhs) + if !eq { + return false + } + } + return true + case ty.IsListType(): + ety := ty.typeImpl.(typeList).ElementTypeT + if len(val.v.([]interface{})) == len(other.v.([]interface{})) { + for i := range val.v.([]interface{}) { + lhs := Value{ + ty: ety, + v: val.v.([]interface{})[i], + } + rhs := Value{ + ty: ety, + v: other.v.([]interface{})[i], + } + eq := lhs.RawEquals(rhs) + if !eq { + return false + } + } + return true + } + return false + case ty.IsSetType(): + s1 := val.v.(set.Set) + s2 := other.v.(set.Set) + + // Since we're intentionally ignoring our rule that two unknowns + // are never equal, we can cheat here. + // (This isn't 100% right since e.g. it will fail if the set contains + // numbers that are infinite, which DeepEqual can't compare properly. + // We're accepting that limitation for simplicity here, since this + // function is here primarily for testing.) + return reflect.DeepEqual(s1, s2) + + case ty.IsMapType(): + ety := ty.typeImpl.(typeMap).ElementTypeT + if len(val.v.(map[string]interface{})) == len(other.v.(map[string]interface{})) { + for k := range val.v.(map[string]interface{}) { + if _, ok := other.v.(map[string]interface{})[k]; !ok { + return false + } + lhs := Value{ + ty: ety, + v: val.v.(map[string]interface{})[k], + } + rhs := Value{ + ty: ety, + v: other.v.(map[string]interface{})[k], + } + eq := lhs.RawEquals(rhs) + if !eq { + return false + } + } + return true + } + return false + case ty.IsCapsuleType(): + impl := val.ty.CapsuleOps().RawEquals + if impl == nil { + // A capsule type's encapsulated value is a pointer to a value of its + // native type, so we can just compare these to get the identity test + // we need. + return val.v == other.v + } + return impl(val.v, other.v) + + default: + // should never happen + panic(fmt.Errorf("unsupported value type %#v in RawEquals", ty)) + } +} + +// Add returns the sum of the receiver and the given other value. Both values +// must be numbers; this method will panic if not. +func (val Value) Add(other Value) Value { + if val.IsMarked() || other.IsMarked() { + val, valMarks := val.Unmark() + other, otherMarks := other.Unmark() + return val.Add(other).WithMarks(valMarks, otherMarks) + } + + if shortCircuit := mustTypeCheck(Number, Number, val, other); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Number) + return *shortCircuit + } + + ret := new(big.Float) + ret.Add(val.v.(*big.Float), other.v.(*big.Float)) + return NumberVal(ret) +} + +// Subtract returns receiver minus the given other value. Both values must be +// numbers; this method will panic if not. +func (val Value) Subtract(other Value) Value { + if val.IsMarked() || other.IsMarked() { + val, valMarks := val.Unmark() + other, otherMarks := other.Unmark() + return val.Subtract(other).WithMarks(valMarks, otherMarks) + } + + if shortCircuit := mustTypeCheck(Number, Number, val, other); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Number) + return *shortCircuit + } + + return val.Add(other.Negate()) +} + +// Negate returns the numeric negative of the receiver, which must be a number. +// This method will panic when given a value of any other type. +func (val Value) Negate() Value { + if val.IsMarked() { + val, valMarks := val.Unmark() + return val.Negate().WithMarks(valMarks) + } + + if shortCircuit := mustTypeCheck(Number, Number, val); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Number) + return *shortCircuit + } + + ret := new(big.Float).Neg(val.v.(*big.Float)) + return NumberVal(ret) +} + +// Multiply returns the product of the receiver and the given other value. +// Both values must be numbers; this method will panic if not. +func (val Value) Multiply(other Value) Value { + if val.IsMarked() || other.IsMarked() { + val, valMarks := val.Unmark() + other, otherMarks := other.Unmark() + return val.Multiply(other).WithMarks(valMarks, otherMarks) + } + + if shortCircuit := mustTypeCheck(Number, Number, val, other); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Number) + return *shortCircuit + } + + ret := new(big.Float) + ret.Mul(val.v.(*big.Float), other.v.(*big.Float)) + return NumberVal(ret) +} + +// Divide returns the quotient of the receiver and the given other value. +// Both values must be numbers; this method will panic if not. +// +// If the "other" value is exactly zero, this operation will return either +// PositiveInfinity or NegativeInfinity, depending on the sign of the +// receiver value. For some use-cases the presence of infinities may be +// undesirable, in which case the caller should check whether the +// other value equals zero before calling and raise an error instead. +// +// If both values are zero or infinity, this function will panic with +// an instance of big.ErrNaN. +func (val Value) Divide(other Value) Value { + if val.IsMarked() || other.IsMarked() { + val, valMarks := val.Unmark() + other, otherMarks := other.Unmark() + return val.Divide(other).WithMarks(valMarks, otherMarks) + } + + if shortCircuit := mustTypeCheck(Number, Number, val, other); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Number) + return *shortCircuit + } + + ret := new(big.Float) + ret.Quo(val.v.(*big.Float), other.v.(*big.Float)) + return NumberVal(ret) +} + +// Modulo returns the remainder of an integer division of the receiver and +// the given other value. Both values must be numbers; this method will panic +// if not. +// +// If the "other" value is exactly zero, this operation will return either +// PositiveInfinity or NegativeInfinity, depending on the sign of the +// receiver value. For some use-cases the presence of infinities may be +// undesirable, in which case the caller should check whether the +// other value equals zero before calling and raise an error instead. +// +// This operation is primarily here for use with nonzero natural numbers. +// Modulo with "other" as a non-natural number gets somewhat philosophical, +// and this function takes a position on what that should mean, but callers +// may wish to disallow such things outright or implement their own modulo +// if they disagree with the interpretation used here. +func (val Value) Modulo(other Value) Value { + if val.IsMarked() || other.IsMarked() { + val, valMarks := val.Unmark() + other, otherMarks := other.Unmark() + return val.Modulo(other).WithMarks(valMarks, otherMarks) + } + + if shortCircuit := mustTypeCheck(Number, Number, val, other); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Number) + return *shortCircuit + } + + // We cheat a bit here with infinities, just abusing the Multiply operation + // to get an infinite result of the correct sign. + if val == PositiveInfinity || val == NegativeInfinity || other == PositiveInfinity || other == NegativeInfinity { + return val.Multiply(other) + } + + if other.RawEquals(Zero) { + return val + } + + // FIXME: This is a bit clumsy. Should come back later and see if there's a + // more straightforward way to do this. + rat := val.Divide(other) + ratFloorInt := &big.Int{} + rat.v.(*big.Float).Int(ratFloorInt) + work := (&big.Float{}).SetInt(ratFloorInt) + work.Mul(other.v.(*big.Float), work) + work.Sub(val.v.(*big.Float), work) + + return NumberVal(work) +} + +// Absolute returns the absolute (signless) value of the receiver, which must +// be a number or this method will panic. +func (val Value) Absolute() Value { + if val.IsMarked() { + val, valMarks := val.Unmark() + return val.Absolute().WithMarks(valMarks) + } + + if shortCircuit := mustTypeCheck(Number, Number, val); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Number) + return *shortCircuit + } + + ret := (&big.Float{}).Abs(val.v.(*big.Float)) + return NumberVal(ret) +} + +// GetAttr returns the value of the given attribute of the receiver, which +// must be of an object type that has an attribute of the given name. +// This method will panic if the receiver type is not compatible. +// +// The method will also panic if the given attribute name is not defined +// for the value's type. Use the attribute-related methods on Type to +// check for the validity of an attribute before trying to use it. +// +// This method may be called on a value whose type is DynamicPseudoType, +// in which case the result will also be DynamicVal. +func (val Value) GetAttr(name string) Value { + if val.IsMarked() { + val, valMarks := val.Unmark() + return val.GetAttr(name).WithMarks(valMarks) + } + + if val.ty == DynamicPseudoType { + return DynamicVal + } + + if !val.ty.IsObjectType() { + panic("value is not an object") + } + + name = NormalizeString(name) + if !val.ty.HasAttribute(name) { + panic("value has no attribute of that name") + } + + attrType := val.ty.AttributeType(name) + + if !val.IsKnown() { + return UnknownVal(attrType) + } + + return Value{ + ty: attrType, + v: val.v.(map[string]interface{})[name], + } +} + +// Index returns the value of an element of the receiver, which must have +// either a list, map or tuple type. This method will panic if the receiver +// type is not compatible. +// +// The key value must be the correct type for the receving collection: a +// number if the collection is a list or tuple, or a string if it is a map. +// In the case of a list or tuple, the given number must be convertable to int +// or this method will panic. The key may alternatively be of +// DynamicPseudoType, in which case the result itself is an unknown of the +// collection's element type. +// +// The result is of the receiver collection's element type, or in the case +// of a tuple the type of the specific element index requested. +// +// This method may be called on a value whose type is DynamicPseudoType, +// in which case the result will also be the DynamicValue. +func (val Value) Index(key Value) Value { + if val.IsMarked() || key.IsMarked() { + val, valMarks := val.Unmark() + key, keyMarks := key.Unmark() + return val.Index(key).WithMarks(valMarks, keyMarks) + } + + if val.ty == DynamicPseudoType { + return DynamicVal + } + + switch { + case val.Type().IsListType(): + elty := val.Type().ElementType() + if key.Type() == DynamicPseudoType { + return UnknownVal(elty) + } + + if key.Type() != Number { + panic("element key for list must be number") + } + if !key.IsKnown() { + return UnknownVal(elty) + } + + if !val.IsKnown() { + return UnknownVal(elty) + } + + index, accuracy := key.v.(*big.Float).Int64() + if accuracy != big.Exact || index < 0 { + panic("element key for list must be non-negative integer") + } + + return Value{ + ty: elty, + v: val.v.([]interface{})[index], + } + case val.Type().IsMapType(): + elty := val.Type().ElementType() + if key.Type() == DynamicPseudoType { + return UnknownVal(elty) + } + + if key.Type() != String { + panic("element key for map must be string") + } + if !key.IsKnown() { + return UnknownVal(elty) + } + + if !val.IsKnown() { + return UnknownVal(elty) + } + + keyStr := key.v.(string) + + return Value{ + ty: elty, + v: val.v.(map[string]interface{})[keyStr], + } + case val.Type().IsTupleType(): + if key.Type() == DynamicPseudoType { + return DynamicVal + } + + if key.Type() != Number { + panic("element key for tuple must be number") + } + if !key.IsKnown() { + return DynamicVal + } + + index, accuracy := key.v.(*big.Float).Int64() + if accuracy != big.Exact || index < 0 { + panic("element key for list must be non-negative integer") + } + + eltys := val.Type().TupleElementTypes() + + if !val.IsKnown() { + return UnknownVal(eltys[index]) + } + + return Value{ + ty: eltys[index], + v: val.v.([]interface{})[index], + } + default: + panic("not a list, map, or tuple type") + } +} + +// HasIndex returns True if the receiver (which must be supported for Index) +// has an element with the given index key, or False if it does not. +// +// The result will be UnknownVal(Bool) if either the collection or the +// key value are unknown. +// +// This method will panic if the receiver is not indexable, but does not +// impose any panic-causing type constraints on the key. +func (val Value) HasIndex(key Value) Value { + if val.IsMarked() || key.IsMarked() { + val, valMarks := val.Unmark() + key, keyMarks := key.Unmark() + return val.HasIndex(key).WithMarks(valMarks, keyMarks) + } + + if val.ty == DynamicPseudoType { + return UnknownVal(Bool) + } + + switch { + case val.Type().IsListType(): + if key.Type() == DynamicPseudoType { + return UnknownVal(Bool) + } + + if key.Type() != Number { + return False + } + if !key.IsKnown() { + return UnknownVal(Bool) + } + if !val.IsKnown() { + return UnknownVal(Bool) + } + + index, accuracy := key.v.(*big.Float).Int64() + if accuracy != big.Exact || index < 0 { + return False + } + + return BoolVal(int(index) < len(val.v.([]interface{})) && index >= 0) + case val.Type().IsMapType(): + if key.Type() == DynamicPseudoType { + return UnknownVal(Bool) + } + + if key.Type() != String { + return False + } + if !key.IsKnown() { + return UnknownVal(Bool) + } + if !val.IsKnown() { + return UnknownVal(Bool) + } + + keyStr := key.v.(string) + _, exists := val.v.(map[string]interface{})[keyStr] + + return BoolVal(exists) + case val.Type().IsTupleType(): + if key.Type() == DynamicPseudoType { + return UnknownVal(Bool) + } + + if key.Type() != Number { + return False + } + if !key.IsKnown() { + return UnknownVal(Bool) + } + + index, accuracy := key.v.(*big.Float).Int64() + if accuracy != big.Exact || index < 0 { + return False + } + + length := val.Type().Length() + return BoolVal(int(index) < length && index >= 0) + default: + panic("not a list, map, or tuple type") + } +} + +// HasElement returns True if the receiver (which must be of a set type) +// has the given value as an element, or False if it does not. +// +// The result will be UnknownVal(Bool) if either the set or the +// given value are unknown. +// +// This method will panic if the receiver is not a set, or if it is a null set. +func (val Value) HasElement(elem Value) Value { + if val.IsMarked() || elem.IsMarked() { + val, valMarks := val.Unmark() + elem, elemMarks := elem.Unmark() + return val.HasElement(elem).WithMarks(valMarks, elemMarks) + } + + ty := val.Type() + + if !ty.IsSetType() { + panic("not a set type") + } + if !val.IsKnown() || !elem.IsKnown() { + return UnknownVal(Bool) + } + if val.IsNull() { + panic("can't call HasElement on a nil value") + } + if !ty.ElementType().Equals(elem.Type()) { + return False + } + + s := val.v.(set.Set) + return BoolVal(s.Has(elem.v)) +} + +// Length returns the length of the receiver, which must be a collection type +// or tuple type, as a number value. If the receiver is not a compatible type +// then this method will panic. +// +// If the receiver is unknown then the result is also unknown. +// +// If the receiver is null then this function will panic. +// +// Note that Length is not supported for strings. To determine the length +// of a string, call AsString and take the length of the native Go string +// that is returned. +func (val Value) Length() Value { + if val.IsMarked() { + val, valMarks := val.Unmark() + return val.Length().WithMarks(valMarks) + } + + if val.Type().IsTupleType() { + // For tuples, we can return the length even if the value is not known. + return NumberIntVal(int64(val.Type().Length())) + } + + if !val.IsKnown() { + return UnknownVal(Number) + } + + return NumberIntVal(int64(val.LengthInt())) +} + +// LengthInt is like Length except it returns an int. It has the same behavior +// as Length except that it will panic if the receiver is unknown. +// +// This is an integration method provided for the convenience of code bridging +// into Go's type system. +func (val Value) LengthInt() int { + val.assertUnmarked() + if val.Type().IsTupleType() { + // For tuples, we can return the length even if the value is not known. + return val.Type().Length() + } + if val.Type().IsObjectType() { + // For objects, the length is the number of attributes associated with the type. + return len(val.Type().AttributeTypes()) + } + if !val.IsKnown() { + panic("value is not known") + } + if val.IsNull() { + panic("value is null") + } + + switch { + + case val.ty.IsListType(): + return len(val.v.([]interface{})) + + case val.ty.IsSetType(): + return val.v.(set.Set).Length() + + case val.ty.IsMapType(): + return len(val.v.(map[string]interface{})) + + default: + panic("value is not a collection") + } +} + +// ElementIterator returns an ElementIterator for iterating the elements +// of the receiver, which must be a collection type, a tuple type, or an object +// type. If called on a method of any other type, this method will panic. +// +// The value must be Known and non-Null, or this method will panic. +// +// If the receiver is of a list type, the returned keys will be of type Number +// and the values will be of the list's element type. +// +// If the receiver is of a map type, the returned keys will be of type String +// and the value will be of the map's element type. Elements are passed in +// ascending lexicographical order by key. +// +// If the receiver is of a set type, each element is returned as both the +// key and the value, since set members are their own identity. +// +// If the receiver is of a tuple type, the returned keys will be of type Number +// and the value will be of the corresponding element's type. +// +// If the receiver is of an object type, the returned keys will be of type +// String and the value will be of the corresponding attributes's type. +// +// ElementIterator is an integration method, so it cannot handle Unknown +// values. This method will panic if the receiver is Unknown. +func (val Value) ElementIterator() ElementIterator { + val.assertUnmarked() + if !val.IsKnown() { + panic("can't use ElementIterator on unknown value") + } + if val.IsNull() { + panic("can't use ElementIterator on null value") + } + return elementIterator(val) +} + +// CanIterateElements returns true if the receiver can support the +// ElementIterator method (and by extension, ForEachElement) without panic. +func (val Value) CanIterateElements() bool { + return canElementIterator(val) +} + +// ForEachElement executes a given callback function for each element of +// the receiver, which must be a collection type or tuple type, or this method +// will panic. +// +// ForEachElement uses ElementIterator internally, and so the values passed +// to the callback are as described for ElementIterator. +// +// Returns true if the iteration exited early due to the callback function +// returning true, or false if the loop ran to completion. +// +// ForEachElement is an integration method, so it cannot handle Unknown +// values. This method will panic if the receiver is Unknown. +func (val Value) ForEachElement(cb ElementCallback) bool { + val.assertUnmarked() + it := val.ElementIterator() + for it.Next() { + key, val := it.Element() + stop := cb(key, val) + if stop { + return true + } + } + return false +} + +// Not returns the logical inverse of the receiver, which must be of type +// Bool or this method will panic. +func (val Value) Not() Value { + if val.IsMarked() { + val, valMarks := val.Unmark() + return val.Not().WithMarks(valMarks) + } + + if shortCircuit := mustTypeCheck(Bool, Bool, val); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Bool) + return *shortCircuit + } + + return BoolVal(!val.v.(bool)) +} + +// And returns the result of logical AND with the receiver and the other given +// value, which must both be of type Bool or this method will panic. +func (val Value) And(other Value) Value { + if val.IsMarked() || other.IsMarked() { + val, valMarks := val.Unmark() + other, otherMarks := other.Unmark() + return val.And(other).WithMarks(valMarks, otherMarks) + } + + if shortCircuit := mustTypeCheck(Bool, Bool, val, other); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Bool) + return *shortCircuit + } + + return BoolVal(val.v.(bool) && other.v.(bool)) +} + +// Or returns the result of logical OR with the receiver and the other given +// value, which must both be of type Bool or this method will panic. +func (val Value) Or(other Value) Value { + if val.IsMarked() || other.IsMarked() { + val, valMarks := val.Unmark() + other, otherMarks := other.Unmark() + return val.Or(other).WithMarks(valMarks, otherMarks) + } + + if shortCircuit := mustTypeCheck(Bool, Bool, val, other); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Bool) + return *shortCircuit + } + + return BoolVal(val.v.(bool) || other.v.(bool)) +} + +// LessThan returns True if the receiver is less than the other given value, +// which must both be numbers or this method will panic. +func (val Value) LessThan(other Value) Value { + if val.IsMarked() || other.IsMarked() { + val, valMarks := val.Unmark() + other, otherMarks := other.Unmark() + return val.LessThan(other).WithMarks(valMarks, otherMarks) + } + + if shortCircuit := mustTypeCheck(Number, Bool, val, other); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Bool) + return *shortCircuit + } + + return BoolVal(val.v.(*big.Float).Cmp(other.v.(*big.Float)) < 0) +} + +// GreaterThan returns True if the receiver is greater than the other given +// value, which must both be numbers or this method will panic. +func (val Value) GreaterThan(other Value) Value { + if val.IsMarked() || other.IsMarked() { + val, valMarks := val.Unmark() + other, otherMarks := other.Unmark() + return val.GreaterThan(other).WithMarks(valMarks, otherMarks) + } + + if shortCircuit := mustTypeCheck(Number, Bool, val, other); shortCircuit != nil { + shortCircuit = forceShortCircuitType(shortCircuit, Bool) + return *shortCircuit + } + + return BoolVal(val.v.(*big.Float).Cmp(other.v.(*big.Float)) > 0) +} + +// LessThanOrEqualTo is equivalent to LessThan and Equal combined with Or. +func (val Value) LessThanOrEqualTo(other Value) Value { + return val.LessThan(other).Or(val.Equals(other)) +} + +// GreaterThanOrEqualTo is equivalent to GreaterThan and Equal combined with Or. +func (val Value) GreaterThanOrEqualTo(other Value) Value { + return val.GreaterThan(other).Or(val.Equals(other)) +} + +// AsString returns the native string from a non-null, non-unknown cty.String +// value, or panics if called on any other value. +func (val Value) AsString() string { + val.assertUnmarked() + if val.ty != String { + panic("not a string") + } + if val.IsNull() { + panic("value is null") + } + if !val.IsKnown() { + panic("value is unknown") + } + + return val.v.(string) +} + +// AsBigFloat returns a big.Float representation of a non-null, non-unknown +// cty.Number value, or panics if called on any other value. +// +// For more convenient conversions to other native numeric types, use the +// "gocty" package. +func (val Value) AsBigFloat() *big.Float { + val.assertUnmarked() + if val.ty != Number { + panic("not a number") + } + if val.IsNull() { + panic("value is null") + } + if !val.IsKnown() { + panic("value is unknown") + } + + // Copy the float so that callers can't mutate our internal state + ret := *(val.v.(*big.Float)) + + return &ret +} + +// AsValueSlice returns a []cty.Value representation of a non-null, non-unknown +// value of any type that CanIterateElements, or panics if called on +// any other value. +// +// For more convenient conversions to slices of more specific types, use +// the "gocty" package. +func (val Value) AsValueSlice() []Value { + val.assertUnmarked() + l := val.LengthInt() + if l == 0 { + return nil + } + + ret := make([]Value, 0, l) + for it := val.ElementIterator(); it.Next(); { + _, v := it.Element() + ret = append(ret, v) + } + return ret +} + +// AsValueMap returns a map[string]cty.Value representation of a non-null, +// non-unknown value of any type that CanIterateElements, or panics if called +// on any other value. +// +// For more convenient conversions to maps of more specific types, use +// the "gocty" package. +func (val Value) AsValueMap() map[string]Value { + val.assertUnmarked() + l := val.LengthInt() + if l == 0 { + return nil + } + + ret := make(map[string]Value, l) + for it := val.ElementIterator(); it.Next(); { + k, v := it.Element() + ret[k.AsString()] = v + } + return ret +} + +// AsValueSet returns a ValueSet representation of a non-null, +// non-unknown value of any collection type, or panics if called +// on any other value. +// +// Unlike AsValueSlice and AsValueMap, this method requires specifically a +// collection type (list, set or map) and does not allow structural types +// (tuple or object), because the ValueSet type requires homogenous +// element types. +// +// The returned ValueSet can store only values of the receiver's element type. +func (val Value) AsValueSet() ValueSet { + val.assertUnmarked() + if !val.Type().IsCollectionType() { + panic("not a collection type") + } + + // We don't give the caller our own set.Set (assuming we're a cty.Set value) + // because then the caller could mutate our internals, which is forbidden. + // Instead, we will construct a new set and append our elements into it. + ret := NewValueSet(val.Type().ElementType()) + for it := val.ElementIterator(); it.Next(); { + _, v := it.Element() + ret.Add(v) + } + return ret +} + +// EncapsulatedValue returns the native value encapsulated in a non-null, +// non-unknown capsule-typed value, or panics if called on any other value. +// +// The result is the same pointer that was passed to CapsuleVal to create +// the value. Since cty considers values to be immutable, it is strongly +// recommended to treat the encapsulated value itself as immutable too. +func (val Value) EncapsulatedValue() interface{} { + val.assertUnmarked() + if !val.Type().IsCapsuleType() { + panic("not a capsule-typed value") + } + + return val.v +} diff --git a/vendor/github.com/hashicorp/go-cty/cty/walk.go b/vendor/github.com/hashicorp/go-cty/cty/walk.go new file mode 100644 index 00000000000..a6943babef8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty/cty/walk.go @@ -0,0 +1,182 @@ +package cty + +// Walk visits all of the values in a possibly-complex structure, calling +// a given function for each value. +// +// For example, given a list of strings the callback would first be called +// with the whole list and then called once for each element of the list. +// +// The callback function may prevent recursive visits to child values by +// returning false. The callback function my halt the walk altogether by +// returning a non-nil error. If the returned error is about the element +// currently being visited, it is recommended to use the provided path +// value to produce a PathError describing that context. +// +// The path passed to the given function may not be used after that function +// returns, since its backing array is re-used for other calls. +func Walk(val Value, cb func(Path, Value) (bool, error)) error { + var path Path + return walk(path, val, cb) +} + +func walk(path Path, val Value, cb func(Path, Value) (bool, error)) error { + deeper, err := cb(path, val) + if err != nil { + return err + } + if !deeper { + return nil + } + + if val.IsNull() || !val.IsKnown() { + // Can't recurse into null or unknown values, regardless of type + return nil + } + + ty := val.Type() + switch { + case ty.IsObjectType(): + for it := val.ElementIterator(); it.Next(); { + nameVal, av := it.Element() + path := append(path, GetAttrStep{ + Name: nameVal.AsString(), + }) + err := walk(path, av, cb) + if err != nil { + return err + } + } + case val.CanIterateElements(): + for it := val.ElementIterator(); it.Next(); { + kv, ev := it.Element() + path := append(path, IndexStep{ + Key: kv, + }) + err := walk(path, ev, cb) + if err != nil { + return err + } + } + } + return nil +} + +// Transform visits all of the values in a possibly-complex structure, +// calling a given function for each value which has an opportunity to +// replace that value. +// +// Unlike Walk, Transform visits child nodes first, so for a list of strings +// it would first visit the strings and then the _new_ list constructed +// from the transformed values of the list items. +// +// This is useful for creating the effect of being able to make deep mutations +// to a value even though values are immutable. However, it's the responsibility +// of the given function to preserve expected invariants, such as homogenity of +// element types in collections; this function can panic if such invariants +// are violated, just as if new values were constructed directly using the +// value constructor functions. An easy way to preserve invariants is to +// ensure that the transform function never changes the value type. +// +// The callback function my halt the walk altogether by +// returning a non-nil error. If the returned error is about the element +// currently being visited, it is recommended to use the provided path +// value to produce a PathError describing that context. +// +// The path passed to the given function may not be used after that function +// returns, since its backing array is re-used for other calls. +func Transform(val Value, cb func(Path, Value) (Value, error)) (Value, error) { + var path Path + return transform(path, val, cb) +} + +func transform(path Path, val Value, cb func(Path, Value) (Value, error)) (Value, error) { + ty := val.Type() + var newVal Value + + switch { + + case val.IsNull() || !val.IsKnown(): + // Can't recurse into null or unknown values, regardless of type + newVal = val + + case ty.IsListType() || ty.IsSetType() || ty.IsTupleType(): + l := val.LengthInt() + switch l { + case 0: + // No deep transform for an empty sequence + newVal = val + default: + elems := make([]Value, 0, l) + for it := val.ElementIterator(); it.Next(); { + kv, ev := it.Element() + path := append(path, IndexStep{ + Key: kv, + }) + newEv, err := transform(path, ev, cb) + if err != nil { + return DynamicVal, err + } + elems = append(elems, newEv) + } + switch { + case ty.IsListType(): + newVal = ListVal(elems) + case ty.IsSetType(): + newVal = SetVal(elems) + case ty.IsTupleType(): + newVal = TupleVal(elems) + default: + panic("unknown sequence type") // should never happen because of the case we are in + } + } + + case ty.IsMapType(): + l := val.LengthInt() + switch l { + case 0: + // No deep transform for an empty map + newVal = val + default: + elems := make(map[string]Value) + for it := val.ElementIterator(); it.Next(); { + kv, ev := it.Element() + path := append(path, IndexStep{ + Key: kv, + }) + newEv, err := transform(path, ev, cb) + if err != nil { + return DynamicVal, err + } + elems[kv.AsString()] = newEv + } + newVal = MapVal(elems) + } + + case ty.IsObjectType(): + switch { + case ty.Equals(EmptyObject): + // No deep transform for an empty object + newVal = val + default: + atys := ty.AttributeTypes() + newAVs := make(map[string]Value) + for name := range atys { + av := val.GetAttr(name) + path := append(path, GetAttrStep{ + Name: name, + }) + newAV, err := transform(path, av, cb) + if err != nil { + return DynamicVal, err + } + newAVs[name] = newAV + } + newVal = ObjectVal(newAVs) + } + + default: + newVal = val + } + + return cb(path, newVal) +} diff --git a/vendor/github.com/hashicorp/go-getter/.travis.yml b/vendor/github.com/hashicorp/go-getter/.travis.yml deleted file mode 100644 index 4fe9176aab8..00000000000 --- a/vendor/github.com/hashicorp/go-getter/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -sudo: false - -addons: - apt: - sources: - - sourceline: 'ppa:git-core/ppa' - packages: - - git - -language: go - -os: - - linux - - osx - -go: - - "1.11.x" - -before_script: - - go build ./cmd/go-getter - -branches: - only: - - master diff --git a/vendor/github.com/hashicorp/go-getter/README.md b/vendor/github.com/hashicorp/go-getter/README.md index 3de23c70943..bbcd15de968 100644 --- a/vendor/github.com/hashicorp/go-getter/README.md +++ b/vendor/github.com/hashicorp/go-getter/README.md @@ -1,10 +1,10 @@ # go-getter -[![Build Status](http://img.shields.io/travis/hashicorp/go-getter.svg?style=flat-square)][travis] +[![CircleCI](https://circleci.com/gh/hashicorp/go-getter/tree/master.svg?style=svg)][circleci] [![Build status](https://ci.appveyor.com/api/projects/status/ulq3qr43n62croyq/branch/master?svg=true)][appveyor] [![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] -[travis]: http://travis-ci.org/hashicorp/go-getter +[circleci]: https://circleci.com/gh/hashicorp/go-getter/tree/master [godocs]: http://godoc.org/github.com/hashicorp/go-getter [appveyor]: https://ci.appveyor.com/project/hashicorp/go-getter/branch/master @@ -356,3 +356,7 @@ In order to access to GCS, authentication credentials should be provided. More i - gcs::https://www.googleapis.com/storage/v1/bucket - gcs::https://www.googleapis.com/storage/v1/bucket/foo.zip - www.googleapis.com/storage/v1/bucket/foo + +#### GCS Testing + +The tests for `get_gcs.go` require you to have GCP credentials set in your environment. These credentials can have any level of permissions to any project, they just need to exist. This means setting `GOOGLE_APPLICATION_CREDENTIALS="~/path/to/credentials.json"` or `GOOGLE_CREDENTIALS="{stringified-credentials-json}"`. Due to this configuration, `get_gcs_test.go` will fail for external contributors in CircleCI. diff --git a/vendor/github.com/hashicorp/go-getter/client.go b/vendor/github.com/hashicorp/go-getter/client.go index 007a78ba7c8..38fb43b8f54 100644 --- a/vendor/github.com/hashicorp/go-getter/client.go +++ b/vendor/github.com/hashicorp/go-getter/client.go @@ -19,7 +19,7 @@ import ( // Using a client directly allows more fine-grained control over how downloading // is done, as well as customizing the protocols supported. type Client struct { - // Ctx for cancellation + // Ctx for cancellation Ctx context.Context // Src is the source URL to get. diff --git a/vendor/github.com/hashicorp/go-getter/get_git.go b/vendor/github.com/hashicorp/go-getter/get_git.go index bb1ec316d3e..1b9f4be8195 100644 --- a/vendor/github.com/hashicorp/go-getter/get_git.go +++ b/vendor/github.com/hashicorp/go-getter/get_git.go @@ -1,6 +1,7 @@ package getter import ( + "bytes" "context" "encoding/base64" "fmt" @@ -9,6 +10,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "runtime" "strconv" "strings" @@ -24,6 +26,8 @@ type GitGetter struct { getter } +var defaultBranchRegexp = regexp.MustCompile(`\s->\sorigin/(.*)`) + func (g *GitGetter) ClientMode(_ *url.URL) (ClientMode, error) { return ClientModeDir, nil } @@ -182,10 +186,10 @@ func (g *GitGetter) update(ctx context.Context, dst, sshKeyFile, ref string, dep cmd.Dir = dst if getRunCommand(cmd) != nil { - // Not a branch, switch to master. This will also catch non-existent - // branches, in which case we want to switch to master and then - // checkout the proper branch later. - ref = "master" + // Not a branch, switch to default branch. This will also catch + // non-existent branches, in which case we want to switch to default + // and then checkout the proper branch later. + ref = findDefaultBranch(dst) } // We have to be on a branch to pull @@ -216,6 +220,22 @@ func (g *GitGetter) fetchSubmodules(ctx context.Context, dst, sshKeyFile string, return getRunCommand(cmd) } +// findDefaultBranch checks the repo's origin remote for its default branch +// (generally "master"). "master" is returned if an origin default branch +// can't be determined. +func findDefaultBranch(dst string) string { + var stdoutbuf bytes.Buffer + cmd := exec.Command("git", "branch", "-r", "--points-at", "refs/remotes/origin/HEAD") + cmd.Dir = dst + cmd.Stdout = &stdoutbuf + err := cmd.Run() + matches := defaultBranchRegexp.FindStringSubmatch(stdoutbuf.String()) + if err != nil || matches == nil { + return "master" + } + return matches[len(matches)-1] +} + // setupGitEnv sets up the environment for the given command. This is used to // pass configuration data to git and ssh and enables advanced cloning methods. func setupGitEnv(cmd *exec.Cmd, sshKeyFile string) { diff --git a/vendor/github.com/hashicorp/go-getter/get_http.go b/vendor/github.com/hashicorp/go-getter/get_http.go index 7c4541c6e95..9ffdba78a5f 100644 --- a/vendor/github.com/hashicorp/go-getter/get_http.go +++ b/vendor/github.com/hashicorp/go-getter/get_http.go @@ -9,7 +9,6 @@ import ( "net/url" "os" "path/filepath" - "strconv" "strings" safetemp "github.com/hashicorp/go-safetemp" @@ -88,7 +87,10 @@ func (g *HttpGetter) Get(dst string, u *url.URL) error { return err } - req.Header = g.Header + if g.Header != nil { + req.Header = g.Header + } + resp, err := g.Client.Do(req) if err != nil { return err @@ -128,6 +130,12 @@ func (g *HttpGetter) Get(dst string, u *url.URL) error { return g.getSubdir(ctx, dst, source, subDir) } +// GetFile fetches the file from src and stores it at dst. +// If the server supports Accept-Range, HttpGetter will attempt a range +// request. This means it is the caller's responsibility to ensure that an +// older version of the destination file does not exist, else it will be either +// falsely identified as being replaced, or corrupted with extra bytes +// appended. func (g *HttpGetter) GetFile(dst string, src *url.URL) error { ctx := g.Context() if g.Netrc { @@ -136,7 +144,6 @@ func (g *HttpGetter) GetFile(dst string, src *url.URL) error { return err } } - // Create all the parent directories if needed if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil { return err @@ -165,18 +172,17 @@ func (g *HttpGetter) GetFile(dst string, src *url.URL) error { req.Header = g.Header } headResp, err := g.Client.Do(req) - if err == nil && headResp != nil { + if err == nil { headResp.Body.Close() if headResp.StatusCode == 200 { // If the HEAD request succeeded, then attempt to set the range // query if we can. - if headResp.Header.Get("Accept-Ranges") == "bytes" { + if headResp.Header.Get("Accept-Ranges") == "bytes" && headResp.ContentLength >= 0 { if fi, err := f.Stat(); err == nil { - if _, err = f.Seek(0, os.SEEK_END); err == nil { - req.Header.Set("Range", fmt.Sprintf("bytes=%d-", fi.Size())) + if _, err = f.Seek(0, io.SeekEnd); err == nil { currentFileSize = fi.Size() - totalFileSize, _ := strconv.ParseInt(headResp.Header.Get("Content-Length"), 10, 64) - if currentFileSize >= totalFileSize { + req.Header.Set("Range", fmt.Sprintf("bytes=%d-", currentFileSize)) + if currentFileSize >= headResp.ContentLength { // file already present return nil } diff --git a/vendor/github.com/hashicorp/go-multierror/.travis.yml b/vendor/github.com/hashicorp/go-multierror/.travis.yml index 304a8359558..24b80388f72 100644 --- a/vendor/github.com/hashicorp/go-multierror/.travis.yml +++ b/vendor/github.com/hashicorp/go-multierror/.travis.yml @@ -9,4 +9,4 @@ branches: only: - master -script: make test testrace +script: env GO111MODULE=on make test testrace diff --git a/vendor/github.com/hashicorp/go-multierror/README.md b/vendor/github.com/hashicorp/go-multierror/README.md index ead5830f7b7..e92fa614cd6 100644 --- a/vendor/github.com/hashicorp/go-multierror/README.md +++ b/vendor/github.com/hashicorp/go-multierror/README.md @@ -14,9 +14,10 @@ be a list of errors. If the caller knows this, they can unwrap the list and access the errors. If the caller doesn't know, the error formats to a nice human-readable format. -`go-multierror` implements the -[errwrap](https://github.com/hashicorp/errwrap) interface so that it can -be used with that library, as well. +`go-multierror` is fully compatible with the Go standard library +[errors](https://golang.org/pkg/errors/) package, including the +functions `As`, `Is`, and `Unwrap`. This provides a standardized approach +for introspecting on error values. ## Installation and Docs @@ -81,6 +82,39 @@ if err := something(); err != nil { } ``` +You can also use the standard [`errors.Unwrap`](https://golang.org/pkg/errors/#Unwrap) +function. This will continue to unwrap into subsequent errors until none exist. + +**Extracting an error** + +The standard library [`errors.As`](https://golang.org/pkg/errors/#As) +function can be used directly with a multierror to extract a specific error: + +```go +// Assume err is a multierror value +err := somefunc() + +// We want to know if "err" has a "RichErrorType" in it and extract it. +var errRich RichErrorType +if errors.As(err, &errRich) { + // It has it, and now errRich is populated. +} +``` + +**Checking for an exact error value** + +Some errors are returned as exact errors such as the [`ErrNotExist`](https://golang.org/pkg/os/#pkg-variables) +error in the `os` package. You can check if this error is present by using +the standard [`errors.Is`](https://golang.org/pkg/errors/#Is) function. + +```go +// Assume err is a multierror value +err := somefunc() +if errors.Is(err, os.ErrNotExist) { + // err contains os.ErrNotExist +} +``` + **Returning a multierror only if there are errors** If you build a `multierror.Error`, you can use the `ErrorOrNil` function diff --git a/vendor/github.com/hashicorp/go-multierror/go.mod b/vendor/github.com/hashicorp/go-multierror/go.mod index 2534331d5f9..0afe8e6f9d6 100644 --- a/vendor/github.com/hashicorp/go-multierror/go.mod +++ b/vendor/github.com/hashicorp/go-multierror/go.mod @@ -1,3 +1,5 @@ module github.com/hashicorp/go-multierror +go 1.14 + require github.com/hashicorp/errwrap v1.0.0 diff --git a/vendor/github.com/hashicorp/go-multierror/go.sum b/vendor/github.com/hashicorp/go-multierror/go.sum index 85b1f8ff333..e8238e9ec91 100644 --- a/vendor/github.com/hashicorp/go-multierror/go.sum +++ b/vendor/github.com/hashicorp/go-multierror/go.sum @@ -1,4 +1,2 @@ -github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce h1:prjrVgOk2Yg6w+PflHoszQNLTUh4kaByUcEWM/9uin4= -github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= diff --git a/vendor/github.com/hashicorp/go-multierror/group.go b/vendor/github.com/hashicorp/go-multierror/group.go new file mode 100644 index 00000000000..9c29efb7f87 --- /dev/null +++ b/vendor/github.com/hashicorp/go-multierror/group.go @@ -0,0 +1,38 @@ +package multierror + +import "sync" + +// Group is a collection of goroutines which return errors that need to be +// coalesced. +type Group struct { + mutex sync.Mutex + err *Error + wg sync.WaitGroup +} + +// Go calls the given function in a new goroutine. +// +// If the function returns an error it is added to the group multierror which +// is returned by Wait. +func (g *Group) Go(f func() error) { + g.wg.Add(1) + + go func() { + defer g.wg.Done() + + if err := f(); err != nil { + g.mutex.Lock() + g.err = Append(g.err, err) + g.mutex.Unlock() + } + }() +} + +// Wait blocks until all function calls from the Go method have returned, then +// returns the multierror. +func (g *Group) Wait() *Error { + g.wg.Wait() + g.mutex.Lock() + defer g.mutex.Unlock() + return g.err +} diff --git a/vendor/github.com/hashicorp/go-multierror/multierror.go b/vendor/github.com/hashicorp/go-multierror/multierror.go index 89b1422d1d1..d05dd926987 100644 --- a/vendor/github.com/hashicorp/go-multierror/multierror.go +++ b/vendor/github.com/hashicorp/go-multierror/multierror.go @@ -1,6 +1,7 @@ package multierror import ( + "errors" "fmt" ) @@ -49,3 +50,69 @@ func (e *Error) GoString() string { func (e *Error) WrappedErrors() []error { return e.Errors } + +// Unwrap returns an error from Error (or nil if there are no errors). +// This error returned will further support Unwrap to get the next error, +// etc. The order will match the order of Errors in the multierror.Error +// at the time of calling. +// +// The resulting error supports errors.As/Is/Unwrap so you can continue +// to use the stdlib errors package to introspect further. +// +// This will perform a shallow copy of the errors slice. Any errors appended +// to this error after calling Unwrap will not be available until a new +// Unwrap is called on the multierror.Error. +func (e *Error) Unwrap() error { + // If we have no errors then we do nothing + if e == nil || len(e.Errors) == 0 { + return nil + } + + // If we have exactly one error, we can just return that directly. + if len(e.Errors) == 1 { + return e.Errors[0] + } + + // Shallow copy the slice + errs := make([]error, len(e.Errors)) + copy(errs, e.Errors) + return chain(errs) +} + +// chain implements the interfaces necessary for errors.Is/As/Unwrap to +// work in a deterministic way with multierror. A chain tracks a list of +// errors while accounting for the current represented error. This lets +// Is/As be meaningful. +// +// Unwrap returns the next error. In the cleanest form, Unwrap would return +// the wrapped error here but we can't do that if we want to properly +// get access to all the errors. Instead, users are recommended to use +// Is/As to get the correct error type out. +// +// Precondition: []error is non-empty (len > 0) +type chain []error + +// Error implements the error interface +func (e chain) Error() string { + return e[0].Error() +} + +// Unwrap implements errors.Unwrap by returning the next error in the +// chain or nil if there are no more errors. +func (e chain) Unwrap() error { + if len(e) == 1 { + return nil + } + + return e[1:] +} + +// As implements errors.As by attempting to map to the current value. +func (e chain) As(target interface{}) bool { + return errors.As(e[0], target) +} + +// Is implements errors.Is by comparing the current value directly. +func (e chain) Is(target error) bool { + return errors.Is(e[0], target) +} diff --git a/vendor/github.com/hashicorp/go-plugin/README.md b/vendor/github.com/hashicorp/go-plugin/README.md index fe305ad5989..46ee09fc0ca 100644 --- a/vendor/github.com/hashicorp/go-plugin/README.md +++ b/vendor/github.com/hashicorp/go-plugin/README.md @@ -141,11 +141,6 @@ This plugin system will give host processes a system for constraining versions. This is in addition to the protocol versioning already present which is more for larger underlying changes. -**Plugin fetching.** We will integrate with [go-getter](https://github.com/hashicorp/go-getter) -to support automatic download + install of plugins. Paired with cryptographically -secure plugins (above), we can make this a safe operation for an amazing -user experience. - ## What About Shared Libraries? When we started using plugins (late 2012, early 2013), plugins over RPC diff --git a/vendor/github.com/hashicorp/go-plugin/client.go b/vendor/github.com/hashicorp/go-plugin/client.go index bc56559c632..780a3121da3 100644 --- a/vendor/github.com/hashicorp/go-plugin/client.go +++ b/vendor/github.com/hashicorp/go-plugin/client.go @@ -159,11 +159,8 @@ type ClientConfig struct { // SyncStdout, SyncStderr can be set to override the // respective os.Std* values in the plugin. Care should be taken to - // avoid races here. If these are nil, then this will automatically be - // hooked up to os.Stdin, Stdout, and Stderr, respectively. - // - // If the default values (nil) are used, then this package will not - // sync any of these streams. + // avoid races here. If these are nil, then this will be set to + // ioutil.Discard. SyncStdout io.Writer SyncStderr io.Writer @@ -215,6 +212,12 @@ type ReattachConfig struct { Protocol Protocol Addr net.Addr Pid int + + // Test is set to true if this is reattaching to to a plugin in "test mode" + // (see ServeConfig.Test). In this mode, client.Kill will NOT kill the + // process and instead will rely on the plugin to terminate itself. This + // should not be used in non-test environments. + Test bool } // SecureConfig is used to configure a client to verify the integrity of an @@ -690,14 +693,14 @@ func (c *Client) Start() (addr net.Addr, err error) { // Check the core protocol. Wrapped in a {} for scoping. { - var coreProtocol int64 - coreProtocol, err = strconv.ParseInt(parts[0], 10, 0) + var coreProtocol int + coreProtocol, err = strconv.Atoi(parts[0]) if err != nil { err = fmt.Errorf("Error parsing core protocol version: %s", err) return } - if int(coreProtocol) != CoreProtocolVersion { + if coreProtocol != CoreProtocolVersion { err = fmt.Errorf("Incompatible core API version with plugin. "+ "Plugin version: %s, Core version: %d\n\n"+ "To fix this, the plugin usually only needs to be recompiled.\n"+ @@ -788,7 +791,10 @@ func (c *Client) reattach() (net.Addr, error) { // Verify the process still exists. If not, then it is an error p, err := os.FindProcess(c.config.Reattach.Pid) if err != nil { - return nil, err + // On Unix systems, FindProcess never returns an error. + // On Windows, for non-existent pids it returns: + // os.SyscallError - 'OpenProcess: the paremter is incorrect' + return nil, ErrProcessNotFound } // Attempt to connect to the addr since on Unix systems FindProcess @@ -825,15 +831,21 @@ func (c *Client) reattach() (net.Addr, error) { c.exited = true }(p.Pid) - // Set the address and process + // Set the address and protocol c.address = c.config.Reattach.Addr - c.process = p c.protocol = c.config.Reattach.Protocol if c.protocol == "" { // Default the protocol to net/rpc for backwards compatibility c.protocol = ProtocolNetRPC } + // If we're in test mode, we do NOT set the process. This avoids the + // process being killed (the only purpose we have for c.process), since + // in test mode the process is responsible for exiting on its own. + if !c.config.Reattach.Test { + c.process = p + } + return c.address, nil } diff --git a/vendor/github.com/hashicorp/go-plugin/go.mod b/vendor/github.com/hashicorp/go-plugin/go.mod index f3ddf44e4cc..f0115b782a1 100644 --- a/vendor/github.com/hashicorp/go-plugin/go.mod +++ b/vendor/github.com/hashicorp/go-plugin/go.mod @@ -1,17 +1,15 @@ module github.com/hashicorp/go-plugin +go 1.13 + require ( - github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect - github.com/golang/protobuf v1.2.0 + github.com/golang/protobuf v1.3.4 github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb + github.com/jhump/protoreflect v1.6.0 github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77 github.com/oklog/run v1.0.0 github.com/stretchr/testify v1.3.0 // indirect - golang.org/x/net v0.0.0-20180826012351-8a410e7b638d - golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 // indirect - golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc // indirect - golang.org/x/text v0.3.0 // indirect - google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 // indirect - google.golang.org/grpc v1.14.0 + golang.org/x/net v0.0.0-20190311183353-d8887717615a + google.golang.org/grpc v1.27.1 ) diff --git a/vendor/github.com/hashicorp/go-plugin/go.sum b/vendor/github.com/hashicorp/go-plugin/go.sum index 21b14e998da..5d497615f5d 100644 --- a/vendor/github.com/hashicorp/go-plugin/go.sum +++ b/vendor/github.com/hashicorp/go-plugin/go.sum @@ -1,31 +1,74 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.4 h1:87PNWwrRvUSnqS4dlcBU/ftvOIBep4sYuBLlh6rX2wk= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd h1:rNuUHR+CvK1IS89MMtcF0EpcVMZtjKfPRp4MEmt/aTs= github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb h1:b5rjCoWHc7eqmAS4/qyk21ZsHyb6Mxv/jykxvNTkU4M= github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= +github.com/jhump/protoreflect v1.6.0 h1:h5jfMVslIg6l29nsMs0D8Wj17RDVdNYti0vDN/PZZoE= +github.com/jhump/protoreflect v1.6.0/go.mod h1:eaTn3RZAmMBcV0fifFvlm6VHNz3wSkYyXYWUh7ymB74= github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77 h1:7GoSOOW2jpsfkntVKaS2rAr1TJqfcxotyaUcuxoZSzg= github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20180530234432-1e491301e022/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d h1:g9qWBGx4puODJTMVyoPrpoxPFgVGd+z1DZwjfRu4d0I= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc h1:WiYx1rIFmx8c0mXAFtv5D/mHyKe1+jmuP7PViuwqwuQ= -golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20170818010345-ee236bd376b0/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/grpc v1.14.0 h1:ArxJuB1NWfPY6r9Gp9gqwplT0Ge7nqv9msgu03lHLmo= -google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.8.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.27.1 h1:zvIju4sqAGvwKspUQOhwnpcqSbzi7/H6QomNNjTL4sk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_client.go b/vendor/github.com/hashicorp/go-plugin/grpc_client.go index d0d0d8e20b0..97812191329 100644 --- a/vendor/github.com/hashicorp/go-plugin/grpc_client.go +++ b/vendor/github.com/hashicorp/go-plugin/grpc_client.go @@ -37,7 +37,6 @@ func dialGRPCConn(tls *tls.Config, dialer func(string, time.Duration) (net.Conn, grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(math.MaxInt32)), grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(math.MaxInt32))) - // Connect. Note the first parameter is unused because we use a custom // dialer that has the state to see the address. conn, err := grpc.Dial("unused", opts...) @@ -62,6 +61,13 @@ func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error) { go broker.Run() go brokerGRPCClient.StartStream() + // Start the stdio client + stdioClient, err := newGRPCStdioClient(doneCtx, c.logger.Named("stdio"), conn) + if err != nil { + return nil, err + } + go stdioClient.Run(c.config.SyncStdout, c.config.SyncStderr) + cl := &GRPCClient{ Conn: conn, Plugins: c.config.Plugins, diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_server.go b/vendor/github.com/hashicorp/go-plugin/grpc_server.go index d3dbf1cedcb..387628bf48f 100644 --- a/vendor/github.com/hashicorp/go-plugin/grpc_server.go +++ b/vendor/github.com/hashicorp/go-plugin/grpc_server.go @@ -14,6 +14,7 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/health" "google.golang.org/grpc/health/grpc_health_v1" + "google.golang.org/grpc/reflection" ) // GRPCServiceName is the name of the service that the health check should @@ -51,9 +52,10 @@ type GRPCServer struct { Stdout io.Reader Stderr io.Reader - config GRPCServerConfig - server *grpc.Server - broker *GRPCBroker + config GRPCServerConfig + server *grpc.Server + broker *GRPCBroker + stdioServer *grpcStdioServer logger hclog.Logger } @@ -73,6 +75,9 @@ func (s *GRPCServer) Init() error { GRPCServiceName, grpc_health_v1.HealthCheckResponse_SERVING) grpc_health_v1.RegisterHealthServer(s.server, healthCheck) + // Register the reflection service + reflection.Register(s.server) + // Register the broker service brokerServer := newGRPCBrokerServer() plugin.RegisterGRPCBrokerServer(s.server, brokerServer) @@ -80,11 +85,13 @@ func (s *GRPCServer) Init() error { go s.broker.Run() // Register the controller - controllerServer := &grpcControllerServer{ - server: s, - } + controllerServer := &grpcControllerServer{server: s} plugin.RegisterGRPCControllerServer(s.server, controllerServer) + // Register the stdio service + s.stdioServer = newGRPCStdioServer(s.logger, s.Stdout, s.Stderr) + plugin.RegisterGRPCStdioServer(s.server, s.stdioServer) + // Register all our plugins onto the gRPC server. for k, raw := range s.Plugins { p, ok := raw.(GRPCPlugin) diff --git a/vendor/github.com/hashicorp/go-plugin/grpc_stdio.go b/vendor/github.com/hashicorp/go-plugin/grpc_stdio.go new file mode 100644 index 00000000000..6231a9fd625 --- /dev/null +++ b/vendor/github.com/hashicorp/go-plugin/grpc_stdio.go @@ -0,0 +1,207 @@ +package plugin + +import ( + "bufio" + "bytes" + "context" + "io" + + empty "github.com/golang/protobuf/ptypes/empty" + hclog "github.com/hashicorp/go-hclog" + "github.com/hashicorp/go-plugin/internal/plugin" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// grpcStdioBuffer is the buffer size we try to fill when sending a chunk of +// stdio data. This is currently 1 KB for no reason other than that seems like +// enough (stdio data isn't that common) and is fairly low. +const grpcStdioBuffer = 1 * 1024 + +// grpcStdioServer implements the Stdio service and streams stdiout/stderr. +type grpcStdioServer struct { + stdoutCh <-chan []byte + stderrCh <-chan []byte +} + +// newGRPCStdioServer creates a new grpcStdioServer and starts the stream +// copying for the given out and err readers. +// +// This must only be called ONCE per srcOut, srcErr. +func newGRPCStdioServer(log hclog.Logger, srcOut, srcErr io.Reader) *grpcStdioServer { + stdoutCh := make(chan []byte) + stderrCh := make(chan []byte) + + // Begin copying the streams + go copyChan(log, stdoutCh, srcOut) + go copyChan(log, stderrCh, srcErr) + + // Construct our server + return &grpcStdioServer{ + stdoutCh: stdoutCh, + stderrCh: stderrCh, + } +} + +// StreamStdio streams our stdout/err as the response. +func (s *grpcStdioServer) StreamStdio( + _ *empty.Empty, + srv plugin.GRPCStdio_StreamStdioServer, +) error { + // Share the same data value between runs. Sending this over the wire + // marshals it so we can reuse this. + var data plugin.StdioData + + for { + // Read our data + select { + case data.Data = <-s.stdoutCh: + data.Channel = plugin.StdioData_STDOUT + + case data.Data = <-s.stderrCh: + data.Channel = plugin.StdioData_STDERR + + case <-srv.Context().Done(): + return nil + } + + // Not sure if this is possible, but if we somehow got here and + // we didn't populate any data at all, then just continue. + if len(data.Data) == 0 { + continue + } + + // Send our data to the client. + if err := srv.Send(&data); err != nil { + return err + } + } +} + +// grpcStdioClient wraps the stdio service as a client to copy +// the stdio data to output writers. +type grpcStdioClient struct { + log hclog.Logger + stdioClient plugin.GRPCStdio_StreamStdioClient +} + +// newGRPCStdioClient creates a grpcStdioClient. This will perform the +// initial connection to the stdio service. If the stdio service is unavailable +// then this will be a no-op. This allows this to work without error for +// plugins that don't support this. +func newGRPCStdioClient( + ctx context.Context, + log hclog.Logger, + conn *grpc.ClientConn, +) (*grpcStdioClient, error) { + client := plugin.NewGRPCStdioClient(conn) + + // Connect immediately to the endpoint + stdioClient, err := client.StreamStdio(ctx, &empty.Empty{}) + + // If we get an Unavailable or Unimplemented error, this means that the plugin isn't + // updated and linking to the latest version of go-plugin that supports + // this. We fall back to the previous behavior of just not syncing anything. + if status.Code(err) == codes.Unavailable || status.Code(err) == codes.Unimplemented { + log.Warn("stdio service not available, stdout/stderr syncing unavailable") + stdioClient = nil + err = nil + } + if err != nil { + return nil, err + } + + return &grpcStdioClient{ + log: log, + stdioClient: stdioClient, + }, nil +} + +// Run starts the loop that receives stdio data and writes it to the given +// writers. This blocks and should be run in a goroutine. +func (c *grpcStdioClient) Run(stdout, stderr io.Writer) { + // This will be nil if stdio is not supported by the plugin + if c.stdioClient == nil { + c.log.Warn("stdio service unavailable, run will do nothing") + return + } + + for { + c.log.Trace("waiting for stdio data") + data, err := c.stdioClient.Recv() + if err != nil { + if err == io.EOF || + status.Code(err) == codes.Unavailable || + status.Code(err) == codes.Canceled || + status.Code(err) == codes.Unimplemented || + err == context.Canceled { + c.log.Warn("received EOF, stopping recv loop", "err", err) + return + } + + c.log.Error("error receiving data", "err", err) + continue + } + + // Determine our output writer based on channel + var w io.Writer + switch data.Channel { + case plugin.StdioData_STDOUT: + w = stdout + + case plugin.StdioData_STDERR: + w = stderr + + default: + c.log.Warn("unknown channel, dropping", "channel", data.Channel) + continue + } + + // Write! In the event of an error we just continue. + if c.log.IsTrace() { + c.log.Trace("received data", "channel", data.Channel.String(), "len", len(data.Data)) + } + if _, err := io.Copy(w, bytes.NewReader(data.Data)); err != nil { + c.log.Error("failed to copy all bytes", "err", err) + } + } +} + +// copyChan copies an io.Reader into a channel. +func copyChan(log hclog.Logger, dst chan<- []byte, src io.Reader) { + bufsrc := bufio.NewReader(src) + + for { + // Make our data buffer. We allocate a new one per loop iteration + // so that we can send it over the channel. + var data [1024]byte + + // Read the data, this will block until data is available + n, err := bufsrc.Read(data[:]) + + // We have to check if we have data BEFORE err != nil. The bufio + // docs guarantee n == 0 on EOF but its better to be safe here. + if n > 0 { + // We have data! Send it on the channel. This will block if there + // is no reader on the other side. We expect that go-plugin will + // connect immediately to the stdio server to drain this so we want + // this block to happen for backpressure. + dst <- data[:n] + } + + // If we hit EOF we're done copying + if err == io.EOF { + log.Debug("stdio EOF, exiting copy loop") + return + } + + // Any other error we just exit the loop. We don't expect there to + // be errors since our use case for this is reading/writing from + // a in-process pipe (os.Pipe). + if err != nil { + log.Warn("error copying stdio data, stopping copy", "err", err) + return + } + } +} diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/gen.go b/vendor/github.com/hashicorp/go-plugin/internal/plugin/gen.go index aa2fdc81387..fb9d415254f 100644 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/gen.go +++ b/vendor/github.com/hashicorp/go-plugin/internal/plugin/gen.go @@ -1,3 +1,3 @@ -//go:generate protoc -I ./ ./grpc_broker.proto ./grpc_controller.proto --go_out=plugins=grpc:. +//go:generate protoc -I ./ ./grpc_broker.proto ./grpc_controller.proto ./grpc_stdio.proto --go_out=plugins=grpc:. package plugin diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.pb.go b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.pb.go index b6850aa59ea..6bf103859f8 100644 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.pb.go +++ b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.pb.go @@ -3,12 +3,13 @@ package plugin +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" + import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" context "golang.org/x/net/context" grpc "google.golang.org/grpc" - math "math" ) // Reference imports to suppress errors if they are not otherwise used. @@ -35,17 +36,16 @@ func (m *ConnInfo) Reset() { *m = ConnInfo{} } func (m *ConnInfo) String() string { return proto.CompactTextString(m) } func (*ConnInfo) ProtoMessage() {} func (*ConnInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_802e9beed3ec3b28, []int{0} + return fileDescriptor_grpc_broker_3322b07398605250, []int{0} } - func (m *ConnInfo) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ConnInfo.Unmarshal(m, b) } func (m *ConnInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ConnInfo.Marshal(b, m, deterministic) } -func (m *ConnInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_ConnInfo.Merge(m, src) +func (dst *ConnInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConnInfo.Merge(dst, src) } func (m *ConnInfo) XXX_Size() int { return xxx_messageInfo_ConnInfo.Size(m) @@ -81,23 +81,6 @@ func init() { proto.RegisterType((*ConnInfo)(nil), "plugin.ConnInfo") } -func init() { proto.RegisterFile("grpc_broker.proto", fileDescriptor_802e9beed3ec3b28) } - -var fileDescriptor_802e9beed3ec3b28 = []byte{ - // 175 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4c, 0x2f, 0x2a, 0x48, - 0x8e, 0x4f, 0x2a, 0xca, 0xcf, 0x4e, 0x2d, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2b, - 0xc8, 0x29, 0x4d, 0xcf, 0xcc, 0x53, 0x8a, 0xe5, 0xe2, 0x70, 0xce, 0xcf, 0xcb, 0xf3, 0xcc, 0x4b, - 0xcb, 0x17, 0x92, 0xe5, 0xe2, 0x2a, 0x4e, 0x2d, 0x2a, 0xcb, 0x4c, 0x4e, 0x8d, 0xcf, 0x4c, 0x91, - 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0d, 0xe2, 0x84, 0x8a, 0x78, 0xa6, 0x08, 0x49, 0x70, 0xb1, 0xe7, - 0xa5, 0x96, 0x94, 0xe7, 0x17, 0x65, 0x4b, 0x30, 0x29, 0x30, 0x6a, 0x70, 0x06, 0xc1, 0xb8, 0x20, - 0x99, 0xc4, 0x94, 0x94, 0xa2, 0xd4, 0xe2, 0x62, 0x09, 0x66, 0x88, 0x0c, 0x94, 0x6b, 0xe4, 0xcc, - 0xc5, 0xe5, 0x1e, 0x14, 0xe0, 0xec, 0x04, 0xb6, 0x5a, 0xc8, 0x94, 0x8b, 0x3b, 0xb8, 0x24, 0xb1, - 0xa8, 0x24, 0xb8, 0xa4, 0x28, 0x35, 0x31, 0x57, 0x48, 0x40, 0x0f, 0xe2, 0x08, 0x3d, 0x98, 0x0b, - 0xa4, 0x30, 0x44, 0x34, 0x18, 0x0d, 0x18, 0x9d, 0x38, 0xa2, 0xa0, 0xae, 0x4d, 0x62, 0x03, 0x3b, - 0xde, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x10, 0x15, 0x39, 0x47, 0xd1, 0x00, 0x00, 0x00, -} - // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn @@ -201,3 +184,20 @@ var _GRPCBroker_serviceDesc = grpc.ServiceDesc{ }, Metadata: "grpc_broker.proto", } + +func init() { proto.RegisterFile("grpc_broker.proto", fileDescriptor_grpc_broker_3322b07398605250) } + +var fileDescriptor_grpc_broker_3322b07398605250 = []byte{ + // 175 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4c, 0x2f, 0x2a, 0x48, + 0x8e, 0x4f, 0x2a, 0xca, 0xcf, 0x4e, 0x2d, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2b, + 0xc8, 0x29, 0x4d, 0xcf, 0xcc, 0x53, 0x8a, 0xe5, 0xe2, 0x70, 0xce, 0xcf, 0xcb, 0xf3, 0xcc, 0x4b, + 0xcb, 0x17, 0x92, 0xe5, 0xe2, 0x2a, 0x4e, 0x2d, 0x2a, 0xcb, 0x4c, 0x4e, 0x8d, 0xcf, 0x4c, 0x91, + 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0d, 0xe2, 0x84, 0x8a, 0x78, 0xa6, 0x08, 0x49, 0x70, 0xb1, 0xe7, + 0xa5, 0x96, 0x94, 0xe7, 0x17, 0x65, 0x4b, 0x30, 0x29, 0x30, 0x6a, 0x70, 0x06, 0xc1, 0xb8, 0x20, + 0x99, 0xc4, 0x94, 0x94, 0xa2, 0xd4, 0xe2, 0x62, 0x09, 0x66, 0x88, 0x0c, 0x94, 0x6b, 0xe4, 0xcc, + 0xc5, 0xe5, 0x1e, 0x14, 0xe0, 0xec, 0x04, 0xb6, 0x5a, 0xc8, 0x94, 0x8b, 0x3b, 0xb8, 0x24, 0xb1, + 0xa8, 0x24, 0xb8, 0xa4, 0x28, 0x35, 0x31, 0x57, 0x48, 0x40, 0x0f, 0xe2, 0x08, 0x3d, 0x98, 0x0b, + 0xa4, 0x30, 0x44, 0x34, 0x18, 0x0d, 0x18, 0x9d, 0x38, 0xa2, 0xa0, 0xae, 0x4d, 0x62, 0x03, 0x3b, + 0xde, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x10, 0x15, 0x39, 0x47, 0xd1, 0x00, 0x00, 0x00, +} diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.proto b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.proto index 3fa79e8ac0a..aa3df4630a7 100644 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.proto +++ b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_broker.proto @@ -11,5 +11,3 @@ message ConnInfo { service GRPCBroker { rpc StartStream(stream ConnInfo) returns (stream ConnInfo); } - - diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.pb.go b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.pb.go index 38b4204326e..3e39da95a89 100644 --- a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.pb.go +++ b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_controller.pb.go @@ -3,12 +3,13 @@ package plugin +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" + import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" context "golang.org/x/net/context" grpc "google.golang.org/grpc" - math "math" ) // Reference imports to suppress errors if they are not otherwise used. @@ -32,17 +33,16 @@ func (m *Empty) Reset() { *m = Empty{} } func (m *Empty) String() string { return proto.CompactTextString(m) } func (*Empty) ProtoMessage() {} func (*Empty) Descriptor() ([]byte, []int) { - return fileDescriptor_23c2c7e42feab570, []int{0} + return fileDescriptor_grpc_controller_08f8296ef6d80436, []int{0} } - func (m *Empty) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Empty.Unmarshal(m, b) } func (m *Empty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Empty.Marshal(b, m, deterministic) } -func (m *Empty) XXX_Merge(src proto.Message) { - xxx_messageInfo_Empty.Merge(m, src) +func (dst *Empty) XXX_Merge(src proto.Message) { + xxx_messageInfo_Empty.Merge(dst, src) } func (m *Empty) XXX_Size() int { return xxx_messageInfo_Empty.Size(m) @@ -57,19 +57,6 @@ func init() { proto.RegisterType((*Empty)(nil), "plugin.Empty") } -func init() { proto.RegisterFile("grpc_controller.proto", fileDescriptor_23c2c7e42feab570) } - -var fileDescriptor_23c2c7e42feab570 = []byte{ - // 108 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4d, 0x2f, 0x2a, 0x48, - 0x8e, 0x4f, 0xce, 0xcf, 0x2b, 0x29, 0xca, 0xcf, 0xc9, 0x49, 0x2d, 0xd2, 0x2b, 0x28, 0xca, 0x2f, - 0xc9, 0x17, 0x62, 0x2b, 0xc8, 0x29, 0x4d, 0xcf, 0xcc, 0x53, 0x62, 0xe7, 0x62, 0x75, 0xcd, 0x2d, - 0x28, 0xa9, 0x34, 0xb2, 0xe2, 0xe2, 0x73, 0x0f, 0x0a, 0x70, 0x76, 0x86, 0x2b, 0x14, 0xd2, 0xe0, - 0xe2, 0x08, 0xce, 0x28, 0x2d, 0x49, 0xc9, 0x2f, 0xcf, 0x13, 0xe2, 0xd5, 0x83, 0xa8, 0xd7, 0x03, - 0x2b, 0x96, 0x42, 0xe5, 0x3a, 0x71, 0x44, 0x41, 0x8d, 0x4b, 0x62, 0x03, 0x9b, 0x6e, 0x0c, 0x08, - 0x00, 0x00, 0xff, 0xff, 0xab, 0x7c, 0x27, 0xe5, 0x76, 0x00, 0x00, 0x00, -} - // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn @@ -141,3 +128,18 @@ var _GRPCController_serviceDesc = grpc.ServiceDesc{ Streams: []grpc.StreamDesc{}, Metadata: "grpc_controller.proto", } + +func init() { + proto.RegisterFile("grpc_controller.proto", fileDescriptor_grpc_controller_08f8296ef6d80436) +} + +var fileDescriptor_grpc_controller_08f8296ef6d80436 = []byte{ + // 108 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4d, 0x2f, 0x2a, 0x48, + 0x8e, 0x4f, 0xce, 0xcf, 0x2b, 0x29, 0xca, 0xcf, 0xc9, 0x49, 0x2d, 0xd2, 0x2b, 0x28, 0xca, 0x2f, + 0xc9, 0x17, 0x62, 0x2b, 0xc8, 0x29, 0x4d, 0xcf, 0xcc, 0x53, 0x62, 0xe7, 0x62, 0x75, 0xcd, 0x2d, + 0x28, 0xa9, 0x34, 0xb2, 0xe2, 0xe2, 0x73, 0x0f, 0x0a, 0x70, 0x76, 0x86, 0x2b, 0x14, 0xd2, 0xe0, + 0xe2, 0x08, 0xce, 0x28, 0x2d, 0x49, 0xc9, 0x2f, 0xcf, 0x13, 0xe2, 0xd5, 0x83, 0xa8, 0xd7, 0x03, + 0x2b, 0x96, 0x42, 0xe5, 0x3a, 0x71, 0x44, 0x41, 0x8d, 0x4b, 0x62, 0x03, 0x9b, 0x6e, 0x0c, 0x08, + 0x00, 0x00, 0xff, 0xff, 0xab, 0x7c, 0x27, 0xe5, 0x76, 0x00, 0x00, 0x00, +} diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.pb.go b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.pb.go new file mode 100644 index 00000000000..c8f94921b46 --- /dev/null +++ b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.pb.go @@ -0,0 +1,233 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: grpc_stdio.proto + +package plugin + +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import empty "github.com/golang/protobuf/ptypes/empty" + +import ( + context "golang.org/x/net/context" + grpc "google.golang.org/grpc" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package + +type StdioData_Channel int32 + +const ( + StdioData_INVALID StdioData_Channel = 0 + StdioData_STDOUT StdioData_Channel = 1 + StdioData_STDERR StdioData_Channel = 2 +) + +var StdioData_Channel_name = map[int32]string{ + 0: "INVALID", + 1: "STDOUT", + 2: "STDERR", +} +var StdioData_Channel_value = map[string]int32{ + "INVALID": 0, + "STDOUT": 1, + "STDERR": 2, +} + +func (x StdioData_Channel) String() string { + return proto.EnumName(StdioData_Channel_name, int32(x)) +} +func (StdioData_Channel) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_grpc_stdio_db2934322ca63bd5, []int{0, 0} +} + +// StdioData is a single chunk of stdout or stderr data that is streamed +// from GRPCStdio. +type StdioData struct { + Channel StdioData_Channel `protobuf:"varint,1,opt,name=channel,proto3,enum=plugin.StdioData_Channel" json:"channel,omitempty"` + Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *StdioData) Reset() { *m = StdioData{} } +func (m *StdioData) String() string { return proto.CompactTextString(m) } +func (*StdioData) ProtoMessage() {} +func (*StdioData) Descriptor() ([]byte, []int) { + return fileDescriptor_grpc_stdio_db2934322ca63bd5, []int{0} +} +func (m *StdioData) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StdioData.Unmarshal(m, b) +} +func (m *StdioData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StdioData.Marshal(b, m, deterministic) +} +func (dst *StdioData) XXX_Merge(src proto.Message) { + xxx_messageInfo_StdioData.Merge(dst, src) +} +func (m *StdioData) XXX_Size() int { + return xxx_messageInfo_StdioData.Size(m) +} +func (m *StdioData) XXX_DiscardUnknown() { + xxx_messageInfo_StdioData.DiscardUnknown(m) +} + +var xxx_messageInfo_StdioData proto.InternalMessageInfo + +func (m *StdioData) GetChannel() StdioData_Channel { + if m != nil { + return m.Channel + } + return StdioData_INVALID +} + +func (m *StdioData) GetData() []byte { + if m != nil { + return m.Data + } + return nil +} + +func init() { + proto.RegisterType((*StdioData)(nil), "plugin.StdioData") + proto.RegisterEnum("plugin.StdioData_Channel", StdioData_Channel_name, StdioData_Channel_value) +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// GRPCStdioClient is the client API for GRPCStdio service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type GRPCStdioClient interface { + // StreamStdio returns a stream that contains all the stdout/stderr. + // This RPC endpoint must only be called ONCE. Once stdio data is consumed + // it is not sent again. + // + // Callers should connect early to prevent blocking on the plugin process. + StreamStdio(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (GRPCStdio_StreamStdioClient, error) +} + +type gRPCStdioClient struct { + cc *grpc.ClientConn +} + +func NewGRPCStdioClient(cc *grpc.ClientConn) GRPCStdioClient { + return &gRPCStdioClient{cc} +} + +func (c *gRPCStdioClient) StreamStdio(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (GRPCStdio_StreamStdioClient, error) { + stream, err := c.cc.NewStream(ctx, &_GRPCStdio_serviceDesc.Streams[0], "/plugin.GRPCStdio/StreamStdio", opts...) + if err != nil { + return nil, err + } + x := &gRPCStdioStreamStdioClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type GRPCStdio_StreamStdioClient interface { + Recv() (*StdioData, error) + grpc.ClientStream +} + +type gRPCStdioStreamStdioClient struct { + grpc.ClientStream +} + +func (x *gRPCStdioStreamStdioClient) Recv() (*StdioData, error) { + m := new(StdioData) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// GRPCStdioServer is the server API for GRPCStdio service. +type GRPCStdioServer interface { + // StreamStdio returns a stream that contains all the stdout/stderr. + // This RPC endpoint must only be called ONCE. Once stdio data is consumed + // it is not sent again. + // + // Callers should connect early to prevent blocking on the plugin process. + StreamStdio(*empty.Empty, GRPCStdio_StreamStdioServer) error +} + +func RegisterGRPCStdioServer(s *grpc.Server, srv GRPCStdioServer) { + s.RegisterService(&_GRPCStdio_serviceDesc, srv) +} + +func _GRPCStdio_StreamStdio_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(empty.Empty) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(GRPCStdioServer).StreamStdio(m, &gRPCStdioStreamStdioServer{stream}) +} + +type GRPCStdio_StreamStdioServer interface { + Send(*StdioData) error + grpc.ServerStream +} + +type gRPCStdioStreamStdioServer struct { + grpc.ServerStream +} + +func (x *gRPCStdioStreamStdioServer) Send(m *StdioData) error { + return x.ServerStream.SendMsg(m) +} + +var _GRPCStdio_serviceDesc = grpc.ServiceDesc{ + ServiceName: "plugin.GRPCStdio", + HandlerType: (*GRPCStdioServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{ + { + StreamName: "StreamStdio", + Handler: _GRPCStdio_StreamStdio_Handler, + ServerStreams: true, + }, + }, + Metadata: "grpc_stdio.proto", +} + +func init() { proto.RegisterFile("grpc_stdio.proto", fileDescriptor_grpc_stdio_db2934322ca63bd5) } + +var fileDescriptor_grpc_stdio_db2934322ca63bd5 = []byte{ + // 221 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x48, 0x2f, 0x2a, 0x48, + 0x8e, 0x2f, 0x2e, 0x49, 0xc9, 0xcc, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2b, 0xc8, + 0x29, 0x4d, 0xcf, 0xcc, 0x93, 0x92, 0x4e, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x07, 0x8b, 0x26, + 0x95, 0xa6, 0xe9, 0xa7, 0xe6, 0x16, 0x94, 0x54, 0x42, 0x14, 0x29, 0xb5, 0x30, 0x72, 0x71, 0x06, + 0x83, 0x34, 0xb9, 0x24, 0x96, 0x24, 0x0a, 0x19, 0x73, 0xb1, 0x27, 0x67, 0x24, 0xe6, 0xe5, 0xa5, + 0xe6, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x19, 0x49, 0xea, 0x41, 0x0c, 0xd1, 0x83, 0xab, 0xd1, + 0x73, 0x86, 0x28, 0x08, 0x82, 0xa9, 0x14, 0x12, 0xe2, 0x62, 0x49, 0x49, 0x2c, 0x49, 0x94, 0x60, + 0x52, 0x60, 0xd4, 0xe0, 0x09, 0x02, 0xb3, 0x95, 0xf4, 0xb8, 0xd8, 0xa1, 0xea, 0x84, 0xb8, 0xb9, + 0xd8, 0x3d, 0xfd, 0xc2, 0x1c, 0x7d, 0x3c, 0x5d, 0x04, 0x18, 0x84, 0xb8, 0xb8, 0xd8, 0x82, 0x43, + 0x5c, 0xfc, 0x43, 0x43, 0x04, 0x18, 0xa1, 0x6c, 0xd7, 0xa0, 0x20, 0x01, 0x26, 0x23, 0x77, 0x2e, + 0x4e, 0xf7, 0xa0, 0x00, 0x67, 0xb0, 0x2d, 0x42, 0x56, 0x5c, 0xdc, 0xc1, 0x25, 0x45, 0xa9, 0x89, + 0xb9, 0x10, 0xae, 0x98, 0x1e, 0xc4, 0x03, 0x7a, 0x30, 0x0f, 0xe8, 0xb9, 0x82, 0x3c, 0x20, 0x25, + 0x88, 0xe1, 0x36, 0x03, 0x46, 0x27, 0x8e, 0x28, 0xa8, 0xb7, 0x93, 0xd8, 0xc0, 0xca, 0x8d, 0x01, + 0x01, 0x00, 0x00, 0xff, 0xff, 0x5d, 0xbb, 0xe0, 0x69, 0x19, 0x01, 0x00, 0x00, +} diff --git a/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.proto b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.proto new file mode 100644 index 00000000000..ce1a1223035 --- /dev/null +++ b/vendor/github.com/hashicorp/go-plugin/internal/plugin/grpc_stdio.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; +package plugin; +option go_package = "plugin"; + +import "google/protobuf/empty.proto"; + +// GRPCStdio is a service that is automatically run by the plugin process +// to stream any stdout/err data so that it can be mirrored on the plugin +// host side. +service GRPCStdio { + // StreamStdio returns a stream that contains all the stdout/stderr. + // This RPC endpoint must only be called ONCE. Once stdio data is consumed + // it is not sent again. + // + // Callers should connect early to prevent blocking on the plugin process. + rpc StreamStdio(google.protobuf.Empty) returns (stream StdioData); +} + +// StdioData is a single chunk of stdout or stderr data that is streamed +// from GRPCStdio. +message StdioData { + enum Channel { + INVALID = 0; + STDOUT = 1; + STDERR = 2; + } + + Channel channel = 1; + bytes data = 2; +} diff --git a/vendor/github.com/hashicorp/go-plugin/server.go b/vendor/github.com/hashicorp/go-plugin/server.go index 4c230e3ab4c..002d6080d4f 100644 --- a/vendor/github.com/hashicorp/go-plugin/server.go +++ b/vendor/github.com/hashicorp/go-plugin/server.go @@ -1,11 +1,13 @@ package plugin import ( + "context" "crypto/tls" "crypto/x509" "encoding/base64" "errors" "fmt" + "io" "io/ioutil" "log" "net" @@ -15,10 +17,8 @@ import ( "sort" "strconv" "strings" - "sync/atomic" - - "github.com/hashicorp/go-hclog" + hclog "github.com/hashicorp/go-hclog" "google.golang.org/grpc" ) @@ -85,6 +85,51 @@ type ServeConfig struct { // Logger is used to pass a logger into the server. If none is provided the // server will create a default logger. Logger hclog.Logger + + // Test, if non-nil, will put plugin serving into "test mode". This is + // meant to be used as part of `go test` within a plugin's codebase to + // launch the plugin in-process and output a ReattachConfig. + // + // This changes the behavior of the server in a number of ways to + // accomodate the expectation of running in-process: + // + // * The handshake cookie is not validated. + // * Stdout/stderr will receive plugin reads and writes + // * Connection information will not be sent to stdout + // + Test *ServeTestConfig +} + +// ServeTestConfig configures plugin serving for test mode. See ServeConfig.Test. +type ServeTestConfig struct { + // Context, if set, will force the plugin serving to end when cancelled. + // This is only a test configuration because the non-test configuration + // expects to take over the process and therefore end on an interrupt or + // kill signal. For tests, we need to kill the plugin serving routinely + // and this provides a way to do so. + // + // If you want to wait for the plugin process to close before moving on, + // you can wait on CloseCh. + Context context.Context + + // If this channel is non-nil, we will send the ReattachConfig via + // this channel. This can be encoded (via JSON recommended) to the + // plugin client to attach to this plugin. + ReattachConfigCh chan<- *ReattachConfig + + // CloseCh, if non-nil, will be closed when serving exits. This can be + // used along with Context to determine when the server is fully shut down. + // If this is not set, you can still use Context on its own, but note there + // may be a period of time between canceling the context and the plugin + // server being shut down. + CloseCh chan<- struct{} + + // SyncStdio, if true, will enable the client side "SyncStdout/Stderr" + // functionality to work. This defaults to false because the implementation + // of making this work within test environments is particularly messy + // and SyncStdio functionality is fairly rare, so we default to the simple + // scenario. + SyncStdio bool } // protocolVersion determines the protocol version and plugin set to be used by @@ -169,26 +214,46 @@ func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet) { // Serve serves the plugins given by ServeConfig. // // Serve doesn't return until the plugin is done being executed. Any -// errors will be outputted to os.Stderr. +// fixable errors will be output to os.Stderr and the process will +// exit with a status code of 1. Serve will panic for unexpected +// conditions where a user's fix is unknown. // // This is the method that plugins should call in their main() functions. func Serve(opts *ServeConfig) { - // Validate the handshake config - if opts.MagicCookieKey == "" || opts.MagicCookieValue == "" { - fmt.Fprintf(os.Stderr, - "Misconfigured ServeConfig given to serve this plugin: no magic cookie\n"+ - "key or value was set. Please notify the plugin author and report\n"+ - "this as a bug.\n") - os.Exit(1) - } + exitCode := -1 + // We use this to trigger an `os.Exit` so that we can execute our other + // deferred functions. In test mode, we just output the err to stderr + // and return. + defer func() { + if opts.Test == nil && exitCode >= 0 { + os.Exit(exitCode) + } - // First check the cookie - if os.Getenv(opts.MagicCookieKey) != opts.MagicCookieValue { - fmt.Fprintf(os.Stderr, - "This binary is a plugin. These are not meant to be executed directly.\n"+ - "Please execute the program that consumes these plugins, which will\n"+ - "load any plugins automatically\n") - os.Exit(1) + if opts.Test != nil && opts.Test.CloseCh != nil { + close(opts.Test.CloseCh) + } + }() + + if opts.Test == nil { + // Validate the handshake config + if opts.MagicCookieKey == "" || opts.MagicCookieValue == "" { + fmt.Fprintf(os.Stderr, + "Misconfigured ServeConfig given to serve this plugin: no magic cookie\n"+ + "key or value was set. Please notify the plugin author and report\n"+ + "this as a bug.\n") + exitCode = 1 + return + } + + // First check the cookie + if os.Getenv(opts.MagicCookieKey) != opts.MagicCookieValue { + fmt.Fprintf(os.Stderr, + "This binary is a plugin. These are not meant to be executed directly.\n"+ + "Please execute the program that consumes these plugins, which will\n"+ + "load any plugins automatically\n") + exitCode = 1 + return + } } // negotiate the version and plugins @@ -208,19 +273,6 @@ func Serve(opts *ServeConfig) { }) } - // Create our new stdout, stderr files. These will override our built-in - // stdout/stderr so that it works across the stream boundary. - stdout_r, stdout_w, err := os.Pipe() - if err != nil { - fmt.Fprintf(os.Stderr, "Error preparing plugin: %s\n", err) - os.Exit(1) - } - stderr_r, stderr_w, err := os.Pipe() - if err != nil { - fmt.Fprintf(os.Stderr, "Error preparing plugin: %s\n", err) - os.Exit(1) - } - // Register a listener so we can accept a connection listener, err := serverListener() if err != nil { @@ -281,6 +333,33 @@ func Serve(opts *ServeConfig) { // Create the channel to tell us when we're done doneCh := make(chan struct{}) + // Create our new stdout, stderr files. These will override our built-in + // stdout/stderr so that it works across the stream boundary. + var stdout_r, stderr_r io.Reader + stdout_r, stdout_w, err := os.Pipe() + if err != nil { + fmt.Fprintf(os.Stderr, "Error preparing plugin: %s\n", err) + os.Exit(1) + } + stderr_r, stderr_w, err := os.Pipe() + if err != nil { + fmt.Fprintf(os.Stderr, "Error preparing plugin: %s\n", err) + os.Exit(1) + } + + // If we're in test mode, we tee off the reader and write the data + // as-is to our normal Stdout and Stderr so that they continue working + // while stdio works. This is because in test mode, we assume we're running + // in `go test` or some equivalent and we want output to go to standard + // locations. + if opts.Test != nil { + // TODO(mitchellh): This isn't super ideal because a TeeReader + // only works if the reader side is actively read. If we never + // connect via a plugin client, the output still gets swallowed. + stdout_r = io.TeeReader(stdout_r, os.Stdout) + stderr_r = io.TeeReader(stderr_r, os.Stderr) + } + // Build the server type var server ServerProtocol switch protoType { @@ -323,35 +402,96 @@ func Serve(opts *ServeConfig) { logger.Debug("plugin address", "network", listener.Addr().Network(), "address", listener.Addr().String()) - // Output the address and service name to stdout so that the client can bring it up. - fmt.Printf("%d|%d|%s|%s|%s|%s\n", - CoreProtocolVersion, - protoVersion, - listener.Addr().Network(), - listener.Addr().String(), - protoType, - serverCert) - os.Stdout.Sync() - - // Eat the interrupts - ch := make(chan os.Signal, 1) - signal.Notify(ch, os.Interrupt) - go func() { - var count int32 = 0 - for { - <-ch - newCount := atomic.AddInt32(&count, 1) - logger.Debug("plugin received interrupt signal, ignoring", "count", newCount) + // Output the address and service name to stdout so that the client can + // bring it up. In test mode, we don't do this because clients will + // attach via a reattach config. + if opts.Test == nil { + fmt.Printf("%d|%d|%s|%s|%s|%s\n", + CoreProtocolVersion, + protoVersion, + listener.Addr().Network(), + listener.Addr().String(), + protoType, + serverCert) + os.Stdout.Sync() + } else if ch := opts.Test.ReattachConfigCh; ch != nil { + // Send back the reattach config that can be used. This isn't + // quite ready if they connect immediately but the client should + // retry a few times. + ch <- &ReattachConfig{ + Protocol: protoType, + Addr: listener.Addr(), + Pid: os.Getpid(), + Test: true, } - }() + } + + // Eat the interrupts. In test mode we disable this so that go test + // can be cancelled properly. + if opts.Test == nil { + ch := make(chan os.Signal, 1) + signal.Notify(ch, os.Interrupt) + go func() { + count := 0 + for { + <-ch + count++ + logger.Trace("plugin received interrupt signal, ignoring", "count", count) + } + }() + } - // Set our new out, err - os.Stdout = stdout_w - os.Stderr = stderr_w + // Set our stdout, stderr to the stdio stream that clients can retrieve + // using ClientConfig.SyncStdout/err. We only do this for non-test mode + // or if the test mode explicitly requests it. + // + // In test mode, we use a multiwriter so that the data continues going + // to the normal stdout/stderr so output can show up in test logs. We + // also send to the stdio stream so that clients can continue working + // if they depend on that. + if opts.Test == nil || opts.Test.SyncStdio { + if opts.Test != nil { + // In test mode we need to maintain the original values so we can + // reset it. + defer func(out, err *os.File) { + os.Stdout = out + os.Stderr = err + }(os.Stdout, os.Stderr) + } + os.Stdout = stdout_w + os.Stderr = stderr_w + } // Accept connections and wait for completion go server.Serve(listener) - <-doneCh + + ctx := context.Background() + if opts.Test != nil && opts.Test.Context != nil { + ctx = opts.Test.Context + } + select { + case <-ctx.Done(): + // Cancellation. We can stop the server by closing the listener. + // This isn't graceful at all but this is currently only used by + // tests and its our only way to stop. + listener.Close() + + // If this is a grpc server, then we also ask the server itself to + // end which will kill all connections. There isn't an easy way to do + // this for net/rpc currently but net/rpc is more and more unused. + if s, ok := server.(*GRPCServer); ok { + s.Stop() + } + + // Wait for the server itself to shut down + <-doneCh + + case <-doneCh: + // Note that given the documentation of Serve we should probably be + // setting exitCode = 0 and using os.Exit here. That's how it used to + // work before extracting this library. However, for years we've done + // this so we'll keep this functionality. + } } func serverListener() (net.Listener, error) { @@ -390,7 +530,7 @@ func serverListener_tcp() (net.Listener, error) { } if minPort > maxPort { - return nil, fmt.Errorf("ENV_MIN_PORT value of %d is greater than PLUGIN_MAX_PORT value of %d", minPort, maxPort) + return nil, fmt.Errorf("PLUGIN_MIN_PORT value of %d is greater than PLUGIN_MAX_PORT value of %d", minPort, maxPort) } for port := minPort; port <= maxPort; port++ { diff --git a/vendor/github.com/hashicorp/go-plugin/testing.go b/vendor/github.com/hashicorp/go-plugin/testing.go index 2cf2c26cc5c..e36f2eb2b7c 100644 --- a/vendor/github.com/hashicorp/go-plugin/testing.go +++ b/vendor/github.com/hashicorp/go-plugin/testing.go @@ -7,9 +7,9 @@ import ( "net" "net/rpc" - "github.com/mitchellh/go-testing-interface" hclog "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-plugin/internal/plugin" + "github.com/mitchellh/go-testing-interface" "google.golang.org/grpc" ) diff --git a/vendor/github.com/hashicorp/go-version/.travis.yml b/vendor/github.com/hashicorp/go-version/.travis.yml deleted file mode 100644 index 01c5dc219af..00000000000 --- a/vendor/github.com/hashicorp/go-version/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: go - -go: - - 1.2 - - 1.3 - - 1.4 - - 1.9 - - "1.10" - - 1.11 - - 1.12 - -script: - - go test diff --git a/vendor/github.com/hashicorp/go-version/README.md b/vendor/github.com/hashicorp/go-version/README.md index 6f3a15ce772..851a337beb4 100644 --- a/vendor/github.com/hashicorp/go-version/README.md +++ b/vendor/github.com/hashicorp/go-version/README.md @@ -1,5 +1,6 @@ # Versioning Library for Go -[![Build Status](https://travis-ci.org/hashicorp/go-version.svg?branch=master)](https://travis-ci.org/hashicorp/go-version) +[![Build Status](https://circleci.com/gh/hashicorp/go-version/tree/master.svg?style=svg)](https://circleci.com/gh/hashicorp/go-version/tree/master) +[![GoDoc](https://godoc.org/github.com/hashicorp/go-version?status.svg)](https://godoc.org/github.com/hashicorp/go-version) go-version is a library for parsing versions and version constraints, and verifying versions against a set of constraints. go-version diff --git a/vendor/github.com/hashicorp/go-version/version.go b/vendor/github.com/hashicorp/go-version/version.go index 1032c5606c3..09703e8e6ff 100644 --- a/vendor/github.com/hashicorp/go-version/version.go +++ b/vendor/github.com/hashicorp/go-version/version.go @@ -280,6 +280,10 @@ func comparePrereleases(v string, other string) int { // Equal tests if two versions are equal. func (v *Version) Equal(o *Version) bool { + if v == nil || o == nil { + return v == o + } + return v.Compare(o) == 0 } @@ -288,7 +292,7 @@ func (v *Version) GreaterThan(o *Version) bool { return v.Compare(o) > 0 } -// GreaterThanOrEqualTo tests if this version is greater than or equal to another version. +// GreaterThanOrEqual tests if this version is greater than or equal to another version. func (v *Version) GreaterThanOrEqual(o *Version) bool { return v.Compare(o) >= 0 } @@ -298,7 +302,7 @@ func (v *Version) LessThan(o *Version) bool { return v.Compare(o) < 0 } -// LessThanOrEqualTo tests if this version is less than or equal to another version. +// LessThanOrEqual tests if this version is less than or equal to another version. func (v *Version) LessThanOrEqual(o *Version) bool { return v.Compare(o) <= 0 } diff --git a/vendor/github.com/hashicorp/golang-lru/LICENSE b/vendor/github.com/hashicorp/golang-lru/LICENSE deleted file mode 100644 index be2cc4dfb60..00000000000 --- a/vendor/github.com/hashicorp/golang-lru/LICENSE +++ /dev/null @@ -1,362 +0,0 @@ -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/golang-lru/simplelru/lru.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go deleted file mode 100644 index 5673773b22b..00000000000 --- a/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go +++ /dev/null @@ -1,161 +0,0 @@ -package simplelru - -import ( - "container/list" - "errors" -) - -// EvictCallback is used to get a callback when a cache entry is evicted -type EvictCallback func(key interface{}, value interface{}) - -// LRU implements a non-thread safe fixed size LRU cache -type LRU struct { - size int - evictList *list.List - items map[interface{}]*list.Element - onEvict EvictCallback -} - -// entry is used to hold a value in the evictList -type entry struct { - key interface{} - value interface{} -} - -// NewLRU constructs an LRU of the given size -func NewLRU(size int, onEvict EvictCallback) (*LRU, error) { - if size <= 0 { - return nil, errors.New("Must provide a positive size") - } - c := &LRU{ - size: size, - evictList: list.New(), - items: make(map[interface{}]*list.Element), - onEvict: onEvict, - } - return c, nil -} - -// Purge is used to completely clear the cache. -func (c *LRU) Purge() { - for k, v := range c.items { - if c.onEvict != nil { - c.onEvict(k, v.Value.(*entry).value) - } - delete(c.items, k) - } - c.evictList.Init() -} - -// Add adds a value to the cache. Returns true if an eviction occurred. -func (c *LRU) Add(key, value interface{}) (evicted bool) { - // Check for existing item - if ent, ok := c.items[key]; ok { - c.evictList.MoveToFront(ent) - ent.Value.(*entry).value = value - return false - } - - // Add new item - ent := &entry{key, value} - entry := c.evictList.PushFront(ent) - c.items[key] = entry - - evict := c.evictList.Len() > c.size - // Verify size not exceeded - if evict { - c.removeOldest() - } - return evict -} - -// Get looks up a key's value from the cache. -func (c *LRU) Get(key interface{}) (value interface{}, ok bool) { - if ent, ok := c.items[key]; ok { - c.evictList.MoveToFront(ent) - return ent.Value.(*entry).value, true - } - return -} - -// Contains checks if a key is in the cache, without updating the recent-ness -// or deleting it for being stale. -func (c *LRU) Contains(key interface{}) (ok bool) { - _, ok = c.items[key] - return ok -} - -// Peek returns the key value (or undefined if not found) without updating -// the "recently used"-ness of the key. -func (c *LRU) Peek(key interface{}) (value interface{}, ok bool) { - var ent *list.Element - if ent, ok = c.items[key]; ok { - return ent.Value.(*entry).value, true - } - return nil, ok -} - -// Remove removes the provided key from the cache, returning if the -// key was contained. -func (c *LRU) Remove(key interface{}) (present bool) { - if ent, ok := c.items[key]; ok { - c.removeElement(ent) - return true - } - return false -} - -// RemoveOldest removes the oldest item from the cache. -func (c *LRU) RemoveOldest() (key interface{}, value interface{}, ok bool) { - ent := c.evictList.Back() - if ent != nil { - c.removeElement(ent) - kv := ent.Value.(*entry) - return kv.key, kv.value, true - } - return nil, nil, false -} - -// GetOldest returns the oldest entry -func (c *LRU) GetOldest() (key interface{}, value interface{}, ok bool) { - ent := c.evictList.Back() - if ent != nil { - kv := ent.Value.(*entry) - return kv.key, kv.value, true - } - return nil, nil, false -} - -// Keys returns a slice of the keys in the cache, from oldest to newest. -func (c *LRU) Keys() []interface{} { - keys := make([]interface{}, len(c.items)) - i := 0 - for ent := c.evictList.Back(); ent != nil; ent = ent.Prev() { - keys[i] = ent.Value.(*entry).key - i++ - } - return keys -} - -// Len returns the number of items in the cache. -func (c *LRU) Len() int { - return c.evictList.Len() -} - -// removeOldest removes the oldest item from the cache. -func (c *LRU) removeOldest() { - ent := c.evictList.Back() - if ent != nil { - c.removeElement(ent) - } -} - -// removeElement is used to remove a given list element from the cache -func (c *LRU) removeElement(e *list.Element) { - c.evictList.Remove(e) - kv := e.Value.(*entry) - delete(c.items, kv.key) - if c.onEvict != nil { - c.onEvict(kv.key, kv.value) - } -} diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go deleted file mode 100644 index 74c7077440c..00000000000 --- a/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go +++ /dev/null @@ -1,36 +0,0 @@ -package simplelru - -// LRUCache is the interface for simple LRU cache. -type LRUCache interface { - // Adds a value to the cache, returns true if an eviction occurred and - // updates the "recently used"-ness of the key. - Add(key, value interface{}) bool - - // Returns key's value from the cache and - // updates the "recently used"-ness of the key. #value, isFound - Get(key interface{}) (value interface{}, ok bool) - - // Check if a key exsists in cache without updating the recent-ness. - Contains(key interface{}) (ok bool) - - // Returns key's value without updating the "recently used"-ness of the key. - Peek(key interface{}) (value interface{}, ok bool) - - // Removes a key from the cache. - Remove(key interface{}) bool - - // Removes the oldest entry from cache. - RemoveOldest() (interface{}, interface{}, bool) - - // Returns the oldest entry from the cache. #key, value, isFound - GetOldest() (interface{}, interface{}, bool) - - // Returns a slice of the keys in the cache, from oldest to newest. - Keys() []interface{} - - // Returns the number of items in the cache. - Len() int - - // Clear all cache entries - Purge() -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/README.md b/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/README.md deleted file mode 100644 index f59ce92e94e..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/README.md +++ /dev/null @@ -1,184 +0,0 @@ -# HCL Dynamic Blocks Extension - -This HCL extension implements a special block type named "dynamic" that can -be used to dynamically generate blocks of other types by iterating over -collection values. - -Normally the block structure in an HCL configuration file is rigid, even -though dynamic expressions can be used within attribute values. This is -convenient for most applications since it allows the overall structure of -the document to be decoded easily, but in some applications it is desirable -to allow dynamic block generation within certain portions of the configuration. - -Dynamic block generation is performed using the `dynamic` block type: - -```hcl -toplevel { - nested { - foo = "static block 1" - } - - dynamic "nested" { - for_each = ["a", "b", "c"] - iterator = nested - content { - foo = "dynamic block ${nested.value}" - } - } - - nested { - foo = "static block 2" - } -} -``` - -The above is interpreted as if it were written as follows: - -```hcl -toplevel { - nested { - foo = "static block 1" - } - - nested { - foo = "dynamic block a" - } - - nested { - foo = "dynamic block b" - } - - nested { - foo = "dynamic block c" - } - - nested { - foo = "static block 2" - } -} -``` - -Since HCL block syntax is not normally exposed to the possibility of unknown -values, this extension must make some compromises when asked to iterate over -an unknown collection. If the length of the collection cannot be statically -recognized (because it is an unknown value of list, map, or set type) then -the `dynamic` construct will generate a _single_ dynamic block whose iterator -key and value are both unknown values of the dynamic pseudo-type, thus causing -any attribute values derived from iteration to appear as unknown values. There -is no explicit representation of the fact that the length of the collection may -eventually be different than one. - -## Usage - -Pass a body to function `Expand` to obtain a new body that will, on access -to its content, evaluate and expand any nested `dynamic` blocks. -Dynamic block processing is also automatically propagated into any nested -blocks that are returned, allowing users to nest dynamic blocks inside -one another and to nest dynamic blocks inside other static blocks. - -HCL structural decoding does not normally have access to an `EvalContext`, so -any variables and functions that should be available to the `for_each` -and `labels` expressions must be passed in when calling `Expand`. Expressions -within the `content` block are evaluated separately and so can be passed a -separate `EvalContext` if desired, during normal attribute expression -evaluation. - -## Detecting Variables - -Some applications dynamically generate an `EvalContext` by analyzing which -variables are referenced by an expression before evaluating it. - -This unfortunately requires some extra effort when this analysis is required -for the context passed to `Expand`: the HCL API requires a schema to be -provided in order to do any analysis of the blocks in a body, but the low-level -schema model provides a description of only one level of nested blocks at -a time, and thus a new schema must be provided for each additional level of -nesting. - -To make this arduous process as convenient as possible, this package provides -a helper function `WalkForEachVariables`, which returns a `WalkVariablesNode` -instance that can be used to find variables directly in a given body and also -determine which nested blocks require recursive calls. Using this mechanism -requires that the caller be able to look up a schema given a nested block type. -For _simple_ formats where a specific block type name always has the same schema -regardless of context, a walk can be implemented as follows: - -```go -func walkVariables(node dynblock.WalkVariablesNode, schema *hcl.BodySchema) []hcl.Traversal { - vars, children := node.Visit(schema) - - for _, child := range children { - var childSchema *hcl.BodySchema - switch child.BlockTypeName { - case "a": - childSchema = &hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "b", - LabelNames: []string{"key"}, - }, - }, - } - case "b": - childSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "val", - Required: true, - }, - }, - } - default: - // Should never happen, because the above cases should be exhaustive - // for the application's configuration format. - panic(fmt.Errorf("can't find schema for unknown block type %q", child.BlockTypeName)) - } - - vars = append(vars, testWalkAndAccumVars(child.Node, childSchema)...) - } -} -``` - -### Detecting Variables with `hcldec` Specifications - -For applications that use the higher-level `hcldec` package to decode nested -configuration structures into `cty` values, the same specification can be used -to automatically drive the recursive variable-detection walk described above. - -The helper function `ForEachVariablesHCLDec` allows an entire recursive -configuration structure to be analyzed in a single call given a `hcldec.Spec` -that describes the nested block structure. This means a `hcldec`-based -application can support dynamic blocks with only a little additional effort: - -```go -func decodeBody(body hcl.Body, spec hcldec.Spec) (cty.Value, hcl.Diagnostics) { - // Determine which variables are needed to expand dynamic blocks - neededForDynamic := dynblock.ForEachVariablesHCLDec(body, spec) - - // Build a suitable EvalContext and expand dynamic blocks - dynCtx := buildEvalContext(neededForDynamic) - dynBody := dynblock.Expand(body, dynCtx) - - // Determine which variables are needed to fully decode the expanded body - // This will analyze expressions that came both from static blocks in the - // original body and from blocks that were dynamically added by Expand. - neededForDecode := hcldec.Variables(dynBody, spec) - - // Build a suitable EvalContext and then fully decode the body as per the - // hcldec specification. - decCtx := buildEvalContext(neededForDecode) - return hcldec.Decode(dynBody, spec, decCtx) -} - -func buildEvalContext(needed []hcl.Traversal) *hcl.EvalContext { - // (to be implemented by your application) -} -``` - -# Performance - -This extension is going quite harshly against the grain of the HCL API, and -so it uses lots of wrapping objects and temporary data structures to get its -work done. HCL in general is not suitable for use in high-performance situations -or situations sensitive to memory pressure, but that is _especially_ true for -this extension. diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/expand_body.go b/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/expand_body.go deleted file mode 100644 index 65a9eab2df4..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/expand_body.go +++ /dev/null @@ -1,262 +0,0 @@ -package dynblock - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -// expandBody wraps another hcl.Body and expands any "dynamic" blocks found -// inside whenever Content or PartialContent is called. -type expandBody struct { - original hcl.Body - forEachCtx *hcl.EvalContext - iteration *iteration // non-nil if we're nested inside another "dynamic" block - - // These are used with PartialContent to produce a "remaining items" - // body to return. They are nil on all bodies fresh out of the transformer. - // - // Note that this is re-implemented here rather than delegating to the - // existing support required by the underlying body because we need to - // retain access to the entire original body on subsequent decode operations - // so we can retain any "dynamic" blocks for types we didn't take consume - // on the first pass. - hiddenAttrs map[string]struct{} - hiddenBlocks map[string]hcl.BlockHeaderSchema -} - -func (b *expandBody) Content(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Diagnostics) { - extSchema := b.extendSchema(schema) - rawContent, diags := b.original.Content(extSchema) - - blocks, blockDiags := b.expandBlocks(schema, rawContent.Blocks, false) - diags = append(diags, blockDiags...) - attrs := b.prepareAttributes(rawContent.Attributes) - - content := &hcl.BodyContent{ - Attributes: attrs, - Blocks: blocks, - MissingItemRange: b.original.MissingItemRange(), - } - - return content, diags -} - -func (b *expandBody) PartialContent(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Body, hcl.Diagnostics) { - extSchema := b.extendSchema(schema) - rawContent, _, diags := b.original.PartialContent(extSchema) - // We discard the "remain" argument above because we're going to construct - // our own remain that also takes into account remaining "dynamic" blocks. - - blocks, blockDiags := b.expandBlocks(schema, rawContent.Blocks, true) - diags = append(diags, blockDiags...) - attrs := b.prepareAttributes(rawContent.Attributes) - - content := &hcl.BodyContent{ - Attributes: attrs, - Blocks: blocks, - MissingItemRange: b.original.MissingItemRange(), - } - - remain := &expandBody{ - original: b.original, - forEachCtx: b.forEachCtx, - iteration: b.iteration, - hiddenAttrs: make(map[string]struct{}), - hiddenBlocks: make(map[string]hcl.BlockHeaderSchema), - } - for name := range b.hiddenAttrs { - remain.hiddenAttrs[name] = struct{}{} - } - for typeName, blockS := range b.hiddenBlocks { - remain.hiddenBlocks[typeName] = blockS - } - for _, attrS := range schema.Attributes { - remain.hiddenAttrs[attrS.Name] = struct{}{} - } - for _, blockS := range schema.Blocks { - remain.hiddenBlocks[blockS.Type] = blockS - } - - return content, remain, diags -} - -func (b *expandBody) extendSchema(schema *hcl.BodySchema) *hcl.BodySchema { - // We augment the requested schema to also include our special "dynamic" - // block type, since then we'll get instances of it interleaved with - // all of the literal child blocks we must also include. - extSchema := &hcl.BodySchema{ - Attributes: schema.Attributes, - Blocks: make([]hcl.BlockHeaderSchema, len(schema.Blocks), len(schema.Blocks)+len(b.hiddenBlocks)+1), - } - copy(extSchema.Blocks, schema.Blocks) - extSchema.Blocks = append(extSchema.Blocks, dynamicBlockHeaderSchema) - - // If we have any hiddenBlocks then we also need to register those here - // so that a call to "Content" on the underlying body won't fail. - // (We'll filter these out again once we process the result of either - // Content or PartialContent.) - for _, blockS := range b.hiddenBlocks { - extSchema.Blocks = append(extSchema.Blocks, blockS) - } - - // If we have any hiddenAttrs then we also need to register these, for - // the same reason as we deal with hiddenBlocks above. - if len(b.hiddenAttrs) != 0 { - newAttrs := make([]hcl.AttributeSchema, len(schema.Attributes), len(schema.Attributes)+len(b.hiddenAttrs)) - copy(newAttrs, extSchema.Attributes) - for name := range b.hiddenAttrs { - newAttrs = append(newAttrs, hcl.AttributeSchema{ - Name: name, - Required: false, - }) - } - extSchema.Attributes = newAttrs - } - - return extSchema -} - -func (b *expandBody) prepareAttributes(rawAttrs hcl.Attributes) hcl.Attributes { - if len(b.hiddenAttrs) == 0 && b.iteration == nil { - // Easy path: just pass through the attrs from the original body verbatim - return rawAttrs - } - - // Otherwise we have some work to do: we must filter out any attributes - // that are hidden (since a previous PartialContent call already saw these) - // and wrap the expressions of the inner attributes so that they will - // have access to our iteration variables. - attrs := make(hcl.Attributes, len(rawAttrs)) - for name, rawAttr := range rawAttrs { - if _, hidden := b.hiddenAttrs[name]; hidden { - continue - } - if b.iteration != nil { - attr := *rawAttr // shallow copy so we can mutate it - attr.Expr = exprWrap{ - Expression: attr.Expr, - i: b.iteration, - } - attrs[name] = &attr - } else { - // If we have no active iteration then no wrapping is required. - attrs[name] = rawAttr - } - } - return attrs -} - -func (b *expandBody) expandBlocks(schema *hcl.BodySchema, rawBlocks hcl.Blocks, partial bool) (hcl.Blocks, hcl.Diagnostics) { - var blocks hcl.Blocks - var diags hcl.Diagnostics - - for _, rawBlock := range rawBlocks { - switch rawBlock.Type { - case "dynamic": - realBlockType := rawBlock.Labels[0] - if _, hidden := b.hiddenBlocks[realBlockType]; hidden { - continue - } - - var blockS *hcl.BlockHeaderSchema - for _, candidate := range schema.Blocks { - if candidate.Type == realBlockType { - blockS = &candidate - break - } - } - if blockS == nil { - // Not a block type that the caller requested. - if !partial { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported block type", - Detail: fmt.Sprintf("Blocks of type %q are not expected here.", realBlockType), - Subject: &rawBlock.LabelRanges[0], - }) - } - continue - } - - spec, specDiags := b.decodeSpec(blockS, rawBlock) - diags = append(diags, specDiags...) - if specDiags.HasErrors() { - continue - } - - if spec.forEachVal.IsKnown() { - for it := spec.forEachVal.ElementIterator(); it.Next(); { - key, value := it.Element() - i := b.iteration.MakeChild(spec.iteratorName, key, value) - - block, blockDiags := spec.newBlock(i, b.forEachCtx) - diags = append(diags, blockDiags...) - if block != nil { - // Attach our new iteration context so that attributes - // and other nested blocks can refer to our iterator. - block.Body = b.expandChild(block.Body, i) - blocks = append(blocks, block) - } - } - } else { - // If our top-level iteration value isn't known then we're forced - // to compromise since HCL doesn't have any concept of an - // "unknown block". In this case then, we'll produce a single - // dynamic block with the iterator values set to DynamicVal, - // which at least makes the potential for a block visible - // in our result, even though it's not represented in a fully-accurate - // way. - i := b.iteration.MakeChild(spec.iteratorName, cty.DynamicVal, cty.DynamicVal) - block, blockDiags := spec.newBlock(i, b.forEachCtx) - diags = append(diags, blockDiags...) - if block != nil { - block.Body = b.expandChild(block.Body, i) - - // We additionally force all of the leaf attribute values - // in the result to be unknown so the calling application - // can, if necessary, use that as a heuristic to detect - // when a single nested block might be standing in for - // multiple blocks yet to be expanded. This retains the - // structure of the generated body but forces all of its - // leaf attribute values to be unknown. - block.Body = unknownBody{block.Body} - - blocks = append(blocks, block) - } - } - - default: - if _, hidden := b.hiddenBlocks[rawBlock.Type]; !hidden { - // A static block doesn't create a new iteration context, but - // it does need to inherit _our own_ iteration context in - // case it contains expressions that refer to our inherited - // iterators, or nested "dynamic" blocks. - expandedBlock := *rawBlock // shallow copy - expandedBlock.Body = b.expandChild(rawBlock.Body, b.iteration) - blocks = append(blocks, &expandedBlock) - } - } - } - - return blocks, diags -} - -func (b *expandBody) expandChild(child hcl.Body, i *iteration) hcl.Body { - chiCtx := i.EvalContext(b.forEachCtx) - ret := Expand(child, chiCtx) - ret.(*expandBody).iteration = i - return ret -} - -func (b *expandBody) JustAttributes() (hcl.Attributes, hcl.Diagnostics) { - // blocks aren't allowed in JustAttributes mode and this body can - // only produce blocks, so we'll just pass straight through to our - // underlying body here. - return b.original.JustAttributes() -} - -func (b *expandBody) MissingItemRange() hcl.Range { - return b.original.MissingItemRange() -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/expand_spec.go b/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/expand_spec.go deleted file mode 100644 index 98a51eadd89..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/expand_spec.go +++ /dev/null @@ -1,215 +0,0 @@ -package dynblock - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -type expandSpec struct { - blockType string - blockTypeRange hcl.Range - defRange hcl.Range - forEachVal cty.Value - iteratorName string - labelExprs []hcl.Expression - contentBody hcl.Body - inherited map[string]*iteration -} - -func (b *expandBody) decodeSpec(blockS *hcl.BlockHeaderSchema, rawSpec *hcl.Block) (*expandSpec, hcl.Diagnostics) { - var diags hcl.Diagnostics - - var schema *hcl.BodySchema - if len(blockS.LabelNames) != 0 { - schema = dynamicBlockBodySchemaLabels - } else { - schema = dynamicBlockBodySchemaNoLabels - } - - specContent, specDiags := rawSpec.Body.Content(schema) - diags = append(diags, specDiags...) - if specDiags.HasErrors() { - return nil, diags - } - - //// for_each attribute - - eachAttr := specContent.Attributes["for_each"] - eachVal, eachDiags := eachAttr.Expr.Value(b.forEachCtx) - diags = append(diags, eachDiags...) - - if !eachVal.CanIterateElements() && eachVal.Type() != cty.DynamicPseudoType { - // We skip this error for DynamicPseudoType because that means we either - // have a null (which is checked immediately below) or an unknown - // (which is handled in the expandBody Content methods). - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic for_each value", - Detail: fmt.Sprintf("Cannot use a %s value in for_each. An iterable collection is required.", eachVal.Type().FriendlyName()), - Subject: eachAttr.Expr.Range().Ptr(), - Expression: eachAttr.Expr, - EvalContext: b.forEachCtx, - }) - return nil, diags - } - if eachVal.IsNull() { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic for_each value", - Detail: "Cannot use a null value in for_each.", - Subject: eachAttr.Expr.Range().Ptr(), - Expression: eachAttr.Expr, - EvalContext: b.forEachCtx, - }) - return nil, diags - } - - //// iterator attribute - - iteratorName := blockS.Type - if iteratorAttr := specContent.Attributes["iterator"]; iteratorAttr != nil { - itTraversal, itDiags := hcl.AbsTraversalForExpr(iteratorAttr.Expr) - diags = append(diags, itDiags...) - if itDiags.HasErrors() { - return nil, diags - } - - if len(itTraversal) != 1 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic iterator name", - Detail: "Dynamic iterator must be a single variable name.", - Subject: itTraversal.SourceRange().Ptr(), - }) - return nil, diags - } - - iteratorName = itTraversal.RootName() - } - - var labelExprs []hcl.Expression - if labelsAttr := specContent.Attributes["labels"]; labelsAttr != nil { - var labelDiags hcl.Diagnostics - labelExprs, labelDiags = hcl.ExprList(labelsAttr.Expr) - diags = append(diags, labelDiags...) - if labelDiags.HasErrors() { - return nil, diags - } - - if len(labelExprs) > len(blockS.LabelNames) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Extraneous dynamic block label", - Detail: fmt.Sprintf("Blocks of type %q require %d label(s).", blockS.Type, len(blockS.LabelNames)), - Subject: labelExprs[len(blockS.LabelNames)].Range().Ptr(), - }) - return nil, diags - } else if len(labelExprs) < len(blockS.LabelNames) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Insufficient dynamic block labels", - Detail: fmt.Sprintf("Blocks of type %q require %d label(s).", blockS.Type, len(blockS.LabelNames)), - Subject: labelsAttr.Expr.Range().Ptr(), - }) - return nil, diags - } - } - - // Since our schema requests only blocks of type "content", we can assume - // that all entries in specContent.Blocks are content blocks. - if len(specContent.Blocks) == 0 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing dynamic content block", - Detail: "A dynamic block must have a nested block of type \"content\" to describe the body of each generated block.", - Subject: &specContent.MissingItemRange, - }) - return nil, diags - } - if len(specContent.Blocks) > 1 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Extraneous dynamic content block", - Detail: "Only one nested content block is allowed for each dynamic block.", - Subject: &specContent.Blocks[1].DefRange, - }) - return nil, diags - } - - return &expandSpec{ - blockType: blockS.Type, - blockTypeRange: rawSpec.LabelRanges[0], - defRange: rawSpec.DefRange, - forEachVal: eachVal, - iteratorName: iteratorName, - labelExprs: labelExprs, - contentBody: specContent.Blocks[0].Body, - }, diags -} - -func (s *expandSpec) newBlock(i *iteration, ctx *hcl.EvalContext) (*hcl.Block, hcl.Diagnostics) { - var diags hcl.Diagnostics - var labels []string - var labelRanges []hcl.Range - lCtx := i.EvalContext(ctx) - for _, labelExpr := range s.labelExprs { - labelVal, labelDiags := labelExpr.Value(lCtx) - diags = append(diags, labelDiags...) - if labelDiags.HasErrors() { - return nil, diags - } - - var convErr error - labelVal, convErr = convert.Convert(labelVal, cty.String) - if convErr != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic block label", - Detail: fmt.Sprintf("Cannot use this value as a dynamic block label: %s.", convErr), - Subject: labelExpr.Range().Ptr(), - Expression: labelExpr, - EvalContext: lCtx, - }) - return nil, diags - } - if labelVal.IsNull() { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic block label", - Detail: "Cannot use a null value as a dynamic block label.", - Subject: labelExpr.Range().Ptr(), - Expression: labelExpr, - EvalContext: lCtx, - }) - return nil, diags - } - if !labelVal.IsKnown() { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid dynamic block label", - Detail: "This value is not yet known. Dynamic block labels must be immediately-known values.", - Subject: labelExpr.Range().Ptr(), - Expression: labelExpr, - EvalContext: lCtx, - }) - return nil, diags - } - - labels = append(labels, labelVal.AsString()) - labelRanges = append(labelRanges, labelExpr.Range()) - } - - block := &hcl.Block{ - Type: s.blockType, - TypeRange: s.blockTypeRange, - Labels: labels, - LabelRanges: labelRanges, - DefRange: s.defRange, - Body: s.contentBody, - } - - return block, diags -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/expr_wrap.go b/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/expr_wrap.go deleted file mode 100644 index 460a1d2a318..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/expr_wrap.go +++ /dev/null @@ -1,42 +0,0 @@ -package dynblock - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -type exprWrap struct { - hcl.Expression - i *iteration -} - -func (e exprWrap) Variables() []hcl.Traversal { - raw := e.Expression.Variables() - ret := make([]hcl.Traversal, 0, len(raw)) - - // Filter out traversals that refer to our iterator name or any - // iterator we've inherited; we're going to provide those in - // our Value wrapper, so the caller doesn't need to know about them. - for _, traversal := range raw { - rootName := traversal.RootName() - if rootName == e.i.IteratorName { - continue - } - if _, inherited := e.i.Inherited[rootName]; inherited { - continue - } - ret = append(ret, traversal) - } - return ret -} - -func (e exprWrap) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - extCtx := e.i.EvalContext(ctx) - return e.Expression.Value(extCtx) -} - -// UnwrapExpression returns the expression being wrapped by this instance. -// This allows the original expression to be recovered by hcl.UnwrapExpression. -func (e exprWrap) UnwrapExpression() hcl.Expression { - return e.Expression -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/iteration.go b/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/iteration.go deleted file mode 100644 index c566388689b..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/iteration.go +++ /dev/null @@ -1,66 +0,0 @@ -package dynblock - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -type iteration struct { - IteratorName string - Key cty.Value - Value cty.Value - Inherited map[string]*iteration -} - -func (s *expandSpec) MakeIteration(key, value cty.Value) *iteration { - return &iteration{ - IteratorName: s.iteratorName, - Key: key, - Value: value, - Inherited: s.inherited, - } -} - -func (i *iteration) Object() cty.Value { - return cty.ObjectVal(map[string]cty.Value{ - "key": i.Key, - "value": i.Value, - }) -} - -func (i *iteration) EvalContext(base *hcl.EvalContext) *hcl.EvalContext { - new := base.NewChild() - - if i != nil { - new.Variables = map[string]cty.Value{} - for name, otherIt := range i.Inherited { - new.Variables[name] = otherIt.Object() - } - new.Variables[i.IteratorName] = i.Object() - } - - return new -} - -func (i *iteration) MakeChild(iteratorName string, key, value cty.Value) *iteration { - if i == nil { - // Create entirely new root iteration, then - return &iteration{ - IteratorName: iteratorName, - Key: key, - Value: value, - } - } - - inherited := map[string]*iteration{} - for name, otherIt := range i.Inherited { - inherited[name] = otherIt - } - inherited[i.IteratorName] = i - return &iteration{ - IteratorName: iteratorName, - Key: key, - Value: value, - Inherited: inherited, - } -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/public.go b/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/public.go deleted file mode 100644 index a5bfd94ec72..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/public.go +++ /dev/null @@ -1,47 +0,0 @@ -// Package dynblock provides an extension to HCL that allows dynamic -// declaration of nested blocks in certain contexts via a special block type -// named "dynamic". -package dynblock - -import ( - "github.com/hashicorp/hcl/v2" -) - -// Expand "dynamic" blocks in the given body, returning a new body that -// has those blocks expanded. -// -// The given EvalContext is used when evaluating "for_each" and "labels" -// attributes within dynamic blocks, allowing those expressions access to -// variables and functions beyond the iterator variable created by the -// iteration. -// -// Expand returns no diagnostics because no blocks are actually expanded -// until a call to Content or PartialContent on the returned body, which -// will then expand only the blocks selected by the schema. -// -// "dynamic" blocks are also expanded automatically within nested blocks -// in the given body, including within other dynamic blocks, thus allowing -// multi-dimensional iteration. However, it is not possible to -// dynamically-generate the "dynamic" blocks themselves except through nesting. -// -// parent { -// dynamic "child" { -// for_each = child_objs -// content { -// dynamic "grandchild" { -// for_each = child.value.children -// labels = [grandchild.key] -// content { -// parent_key = child.key -// value = grandchild.value -// } -// } -// } -// } -// } -func Expand(body hcl.Body, ctx *hcl.EvalContext) hcl.Body { - return &expandBody{ - original: body, - forEachCtx: ctx, - } -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/schema.go b/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/schema.go deleted file mode 100644 index b3907d6eae9..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/schema.go +++ /dev/null @@ -1,50 +0,0 @@ -package dynblock - -import "github.com/hashicorp/hcl/v2" - -var dynamicBlockHeaderSchema = hcl.BlockHeaderSchema{ - Type: "dynamic", - LabelNames: []string{"type"}, -} - -var dynamicBlockBodySchemaLabels = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "for_each", - Required: true, - }, - { - Name: "iterator", - Required: false, - }, - { - Name: "labels", - Required: true, - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "content", - LabelNames: nil, - }, - }, -} - -var dynamicBlockBodySchemaNoLabels = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "for_each", - Required: true, - }, - { - Name: "iterator", - Required: false, - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "content", - LabelNames: nil, - }, - }, -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/unknown_body.go b/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/unknown_body.go deleted file mode 100644 index ce98259a58c..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/unknown_body.go +++ /dev/null @@ -1,84 +0,0 @@ -package dynblock - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -// unknownBody is a funny body that just reports everything inside it as -// unknown. It uses a given other body as a sort of template for what attributes -// and blocks are inside -- including source location information -- but -// subsitutes unknown values of unknown type for all attributes. -// -// This rather odd process is used to handle expansion of dynamic blocks whose -// for_each expression is unknown. Since a block cannot itself be unknown, -// we instead arrange for everything _inside_ the block to be unknown instead, -// to give the best possible approximation. -type unknownBody struct { - template hcl.Body -} - -var _ hcl.Body = unknownBody{} - -func (b unknownBody) Content(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Diagnostics) { - content, diags := b.template.Content(schema) - content = b.fixupContent(content) - - // We're intentionally preserving the diagnostics reported from the - // inner body so that we can still report where the template body doesn't - // match the requested schema. - return content, diags -} - -func (b unknownBody) PartialContent(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Body, hcl.Diagnostics) { - content, remain, diags := b.template.PartialContent(schema) - content = b.fixupContent(content) - remain = unknownBody{remain} // remaining content must also be wrapped - - // We're intentionally preserving the diagnostics reported from the - // inner body so that we can still report where the template body doesn't - // match the requested schema. - return content, remain, diags -} - -func (b unknownBody) JustAttributes() (hcl.Attributes, hcl.Diagnostics) { - attrs, diags := b.template.JustAttributes() - attrs = b.fixupAttrs(attrs) - - // We're intentionally preserving the diagnostics reported from the - // inner body so that we can still report where the template body doesn't - // match the requested schema. - return attrs, diags -} - -func (b unknownBody) MissingItemRange() hcl.Range { - return b.template.MissingItemRange() -} - -func (b unknownBody) fixupContent(got *hcl.BodyContent) *hcl.BodyContent { - ret := &hcl.BodyContent{} - ret.Attributes = b.fixupAttrs(got.Attributes) - if len(got.Blocks) > 0 { - ret.Blocks = make(hcl.Blocks, 0, len(got.Blocks)) - for _, gotBlock := range got.Blocks { - new := *gotBlock // shallow copy - new.Body = unknownBody{gotBlock.Body} // nested content must also be marked unknown - ret.Blocks = append(ret.Blocks, &new) - } - } - - return ret -} - -func (b unknownBody) fixupAttrs(got hcl.Attributes) hcl.Attributes { - if len(got) == 0 { - return nil - } - ret := make(hcl.Attributes, len(got)) - for name, gotAttr := range got { - new := *gotAttr // shallow copy - new.Expr = hcl.StaticExpr(cty.DynamicVal, gotAttr.Expr.Range()) - ret[name] = &new - } - return ret -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/variables.go b/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/variables.go deleted file mode 100644 index 192339295e8..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/variables.go +++ /dev/null @@ -1,209 +0,0 @@ -package dynblock - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -// WalkVariables begins the recursive process of walking all expressions and -// nested blocks in the given body and its child bodies while taking into -// account any "dynamic" blocks. -// -// This function requires that the caller walk through the nested block -// structure in the given body level-by-level so that an appropriate schema -// can be provided at each level to inform further processing. This workflow -// is thus easiest to use for calling applications that have some higher-level -// schema representation available with which to drive this multi-step -// process. If your application uses the hcldec package, you may be able to -// use VariablesHCLDec instead for a more automatic approach. -func WalkVariables(body hcl.Body) WalkVariablesNode { - return WalkVariablesNode{ - body: body, - includeContent: true, - } -} - -// WalkExpandVariables is like Variables but it includes only the variables -// required for successful block expansion, ignoring any variables referenced -// inside block contents. The result is the minimal set of all variables -// required for a call to Expand, excluding variables that would only be -// needed to subsequently call Content or PartialContent on the expanded -// body. -func WalkExpandVariables(body hcl.Body) WalkVariablesNode { - return WalkVariablesNode{ - body: body, - } -} - -type WalkVariablesNode struct { - body hcl.Body - it *iteration - - includeContent bool -} - -type WalkVariablesChild struct { - BlockTypeName string - Node WalkVariablesNode -} - -// Body returns the HCL Body associated with the child node, in case the caller -// wants to do some sort of inspection of it in order to decide what schema -// to pass to Visit. -// -// Most implementations should just fetch a fixed schema based on the -// BlockTypeName field and not access this. Deciding on a schema dynamically -// based on the body is a strange thing to do and generally necessary only if -// your caller is already doing other bizarre things with HCL bodies. -func (c WalkVariablesChild) Body() hcl.Body { - return c.Node.body -} - -// Visit returns the variable traversals required for any "dynamic" blocks -// directly in the body associated with this node, and also returns any child -// nodes that must be visited in order to continue the walk. -// -// Each child node has its associated block type name given in its BlockTypeName -// field, which the calling application should use to determine the appropriate -// schema for the content of each child node and pass it to the child node's -// own Visit method to continue the walk recursively. -func (n WalkVariablesNode) Visit(schema *hcl.BodySchema) (vars []hcl.Traversal, children []WalkVariablesChild) { - extSchema := n.extendSchema(schema) - container, _, _ := n.body.PartialContent(extSchema) - if container == nil { - return vars, children - } - - children = make([]WalkVariablesChild, 0, len(container.Blocks)) - - if n.includeContent { - for _, attr := range container.Attributes { - for _, traversal := range attr.Expr.Variables() { - var ours, inherited bool - if n.it != nil { - ours = traversal.RootName() == n.it.IteratorName - _, inherited = n.it.Inherited[traversal.RootName()] - } - - if !(ours || inherited) { - vars = append(vars, traversal) - } - } - } - } - - for _, block := range container.Blocks { - switch block.Type { - - case "dynamic": - blockTypeName := block.Labels[0] - inner, _, _ := block.Body.PartialContent(variableDetectionInnerSchema) - if inner == nil { - continue - } - - iteratorName := blockTypeName - if attr, exists := inner.Attributes["iterator"]; exists { - iterTraversal, _ := hcl.AbsTraversalForExpr(attr.Expr) - if len(iterTraversal) == 0 { - // Ignore this invalid dynamic block, since it'll produce - // an error if someone tries to extract content from it - // later anyway. - continue - } - iteratorName = iterTraversal.RootName() - } - blockIt := n.it.MakeChild(iteratorName, cty.DynamicVal, cty.DynamicVal) - - if attr, exists := inner.Attributes["for_each"]; exists { - // Filter out iterator names inherited from parent blocks - for _, traversal := range attr.Expr.Variables() { - if _, inherited := blockIt.Inherited[traversal.RootName()]; !inherited { - vars = append(vars, traversal) - } - } - } - if attr, exists := inner.Attributes["labels"]; exists { - // Filter out both our own iterator name _and_ those inherited - // from parent blocks, since we provide _both_ of these to the - // label expressions. - for _, traversal := range attr.Expr.Variables() { - ours := traversal.RootName() == iteratorName - _, inherited := blockIt.Inherited[traversal.RootName()] - - if !(ours || inherited) { - vars = append(vars, traversal) - } - } - } - - for _, contentBlock := range inner.Blocks { - // We only request "content" blocks in our schema, so we know - // any blocks we find here will be content blocks. We require - // exactly one content block for actual expansion, but we'll - // be more liberal here so that callers can still collect - // variables from erroneous "dynamic" blocks. - children = append(children, WalkVariablesChild{ - BlockTypeName: blockTypeName, - Node: WalkVariablesNode{ - body: contentBlock.Body, - it: blockIt, - includeContent: n.includeContent, - }, - }) - } - - default: - children = append(children, WalkVariablesChild{ - BlockTypeName: block.Type, - Node: WalkVariablesNode{ - body: block.Body, - it: n.it, - includeContent: n.includeContent, - }, - }) - - } - } - - return vars, children -} - -func (n WalkVariablesNode) extendSchema(schema *hcl.BodySchema) *hcl.BodySchema { - // We augment the requested schema to also include our special "dynamic" - // block type, since then we'll get instances of it interleaved with - // all of the literal child blocks we must also include. - extSchema := &hcl.BodySchema{ - Attributes: schema.Attributes, - Blocks: make([]hcl.BlockHeaderSchema, len(schema.Blocks), len(schema.Blocks)+1), - } - copy(extSchema.Blocks, schema.Blocks) - extSchema.Blocks = append(extSchema.Blocks, dynamicBlockHeaderSchema) - - return extSchema -} - -// This is a more relaxed schema than what's in schema.go, since we -// want to maximize the amount of variables we can find even if there -// are erroneous blocks. -var variableDetectionInnerSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "for_each", - Required: false, - }, - { - Name: "labels", - Required: false, - }, - { - Name: "iterator", - Required: false, - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "content", - }, - }, -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/variables_hcldec.go b/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/variables_hcldec.go deleted file mode 100644 index 907ef3eba72..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/dynblock/variables_hcldec.go +++ /dev/null @@ -1,43 +0,0 @@ -package dynblock - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hcldec" -) - -// VariablesHCLDec is a wrapper around WalkVariables that uses the given hcldec -// specification to automatically drive the recursive walk through nested -// blocks in the given body. -// -// This is a drop-in replacement for hcldec.Variables which is able to treat -// blocks of type "dynamic" in the same special way that dynblock.Expand would, -// exposing both the variables referenced in the "for_each" and "labels" -// arguments and variables used in the nested "content" block. -func VariablesHCLDec(body hcl.Body, spec hcldec.Spec) []hcl.Traversal { - rootNode := WalkVariables(body) - return walkVariablesWithHCLDec(rootNode, spec) -} - -// ExpandVariablesHCLDec is like VariablesHCLDec but it includes only the -// minimal set of variables required to call Expand, ignoring variables that -// are referenced only inside normal block contents. See WalkExpandVariables -// for more information. -func ExpandVariablesHCLDec(body hcl.Body, spec hcldec.Spec) []hcl.Traversal { - rootNode := WalkExpandVariables(body) - return walkVariablesWithHCLDec(rootNode, spec) -} - -func walkVariablesWithHCLDec(node WalkVariablesNode, spec hcldec.Spec) []hcl.Traversal { - vars, children := node.Visit(hcldec.ImpliedSchema(spec)) - - if len(children) > 0 { - childSpecs := hcldec.ChildBlockTypes(spec) - for _, child := range children { - if childSpec, exists := childSpecs[child.BlockTypeName]; exists { - vars = append(vars, walkVariablesWithHCLDec(child.Node, childSpec)...) - } - } - } - - return vars -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/README.md b/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/README.md deleted file mode 100644 index 058f1e3d840..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/README.md +++ /dev/null @@ -1,135 +0,0 @@ -# HCL Type Expressions Extension - -This HCL extension defines a convention for describing HCL types using function -call and variable reference syntax, allowing configuration formats to include -type information provided by users. - -The type syntax is processed statically from a hcl.Expression, so it cannot -use any of the usual language operators. This is similar to type expressions -in statically-typed programming languages. - -```hcl -variable "example" { - type = list(string) -} -``` - -The extension is built using the `hcl.ExprAsKeyword` and `hcl.ExprCall` -functions, and so it relies on the underlying syntax to define how "keyword" -and "call" are interpreted. The above shows how they are interpreted in -the HCL native syntax, while the following shows the same information -expressed in JSON: - -```json -{ - "variable": { - "example": { - "type": "list(string)" - } - } -} -``` - -Notice that since we have additional contextual information that we intend -to allow only calls and keywords the JSON syntax is able to parse the given -string directly as an expression, rather than as a template as would be -the case for normal expression evaluation. - -For more information, see [the godoc reference](http://godoc.org/github.com/hashicorp/hcl/v2/ext/typeexpr). - -## Type Expression Syntax - -When expressed in the native syntax, the following expressions are permitted -in a type expression: - -* `string` - string -* `bool` - boolean -* `number` - number -* `any` - `cty.DynamicPseudoType` (in function `TypeConstraint` only) -* `list()` - list of the type given as an argument -* `set()` - set of the type given as an argument -* `map()` - map of the type given as an argument -* `tuple([])` - tuple with the element types given in the single list argument -* `object({=, ...}` - object with the attributes and corresponding types given in the single map argument - -For example: - -* `list(string)` -* `object({name=string,age=number})` -* `map(object({name=string,age=number}))` - -Note that the object constructor syntax is not fully-general for all possible -object types because it requires the attribute names to be valid identifiers. -In practice it is expected that any time an object type is being fixed for -type checking it will be one that has identifiers as its attributes; object -types with weird attributes generally show up only from arbitrary object -constructors in configuration files, which are usually treated either as maps -or as the dynamic pseudo-type. - -## Type Constraints as Values - -Along with defining a convention for writing down types using HCL expression -constructs, this package also includes a mechanism for representing types as -values that can be used as data within an HCL-based language. - -`typeexpr.TypeConstraintType` is a -[`cty` capsule type](https://github.com/zclconf/go-cty/blob/master/docs/types.md#capsule-types) -that encapsulates `cty.Type` values. You can construct such a value directly -using the `TypeConstraintVal` function: - -```go -tyVal := typeexpr.TypeConstraintVal(cty.String) - -// We can unpack the type from a value using TypeConstraintFromVal -ty := typeExpr.TypeConstraintFromVal(tyVal) -``` - -However, the primary purpose of `typeexpr.TypeConstraintType` is to be -specified as the type constraint for an argument, in which case it serves -as a signal for HCL to treat the argument expression as a type constraint -expression as defined above, rather than as a normal value expression. - -"An argument" in the above in practice means the following two locations: - -* As the type constraint for a parameter of a cty function that will be - used in an `hcl.EvalContext`. In that case, function calls in the HCL - native expression syntax will require the argument to be valid type constraint - expression syntax and the function implementation will receive a - `TypeConstraintType` value as the argument value for that parameter. - -* As the type constraint for a `hcldec.AttrSpec` or `hcldec.BlockAttrsSpec` - when decoding an HCL body using `hcldec`. In that case, the attributes - with that type constraint will be required to be valid type constraint - expression syntax and the result will be a `TypeConstraintType` value. - -Note that the special handling of these arguments means that an argument -marked in this way must use the type constraint syntax directly. It is not -valid to pass in a value of `TypeConstraintType` that has been obtained -dynamically via some other expression result. - -`TypeConstraintType` is provided with the intent of using it internally within -application code when incorporating type constraint expression syntax into -an HCL-based language, not to be used for dynamic "programming with types". A -calling application could support programming with types by defining its _own_ -capsule type, but that is not the purpose of `TypeConstraintType`. - -## The "convert" `cty` Function - -Building on the `TypeConstraintType` described in the previous section, this -package also provides `typeexpr.ConvertFunc` which is a cty function that -can be placed into a `cty.EvalContext` (conventionally named "convert") in -order to provide a general type conversion function in an HCL-based language: - -```hcl - foo = convert("true", bool) -``` - -The second parameter uses the mechanism described in the previous section to -require its argument to be a type constraint expression rather than a value -expression. In doing so, it allows converting with any type constraint that -can be expressed in this package's type constraint syntax. In the above example, -the `foo` argument would receive a boolean true, or `cty.True` in `cty` terms. - -The target type constraint must always be provided statically using inline -type constraint syntax. There is no way to _dynamically_ select a type -constraint using this function. diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/doc.go b/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/doc.go deleted file mode 100644 index c4b379579d4..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/doc.go +++ /dev/null @@ -1,11 +0,0 @@ -// Package typeexpr extends HCL with a convention for describing HCL types -// within configuration files. -// -// The type syntax is processed statically from a hcl.Expression, so it cannot -// use any of the usual language operators. This is similar to type expressions -// in statically-typed programming languages. -// -// variable "example" { -// type = list(string) -// } -package typeexpr diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/get_type.go b/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/get_type.go deleted file mode 100644 index 11b06897986..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/get_type.go +++ /dev/null @@ -1,196 +0,0 @@ -package typeexpr - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -const invalidTypeSummary = "Invalid type specification" - -// getType is the internal implementation of both Type and TypeConstraint, -// using the passed flag to distinguish. When constraint is false, the "any" -// keyword will produce an error. -func getType(expr hcl.Expression, constraint bool) (cty.Type, hcl.Diagnostics) { - // First we'll try for one of our keywords - kw := hcl.ExprAsKeyword(expr) - switch kw { - case "bool": - return cty.Bool, nil - case "string": - return cty.String, nil - case "number": - return cty.Number, nil - case "any": - if constraint { - return cty.DynamicPseudoType, nil - } - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("The keyword %q cannot be used in this type specification: an exact type is required.", kw), - Subject: expr.Range().Ptr(), - }} - case "list", "map", "set": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("The %s type constructor requires one argument specifying the element type.", kw), - Subject: expr.Range().Ptr(), - }} - case "object": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "The object type constructor requires one argument specifying the attribute types and values as a map.", - Subject: expr.Range().Ptr(), - }} - case "tuple": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "The tuple type constructor requires one argument specifying the element types as a list.", - Subject: expr.Range().Ptr(), - }} - case "": - // okay! we'll fall through and try processing as a call, then. - default: - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("The keyword %q is not a valid type specification.", kw), - Subject: expr.Range().Ptr(), - }} - } - - // If we get down here then our expression isn't just a keyword, so we'll - // try to process it as a call instead. - call, diags := hcl.ExprCall(expr) - if diags.HasErrors() { - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "A type specification is either a primitive type keyword (bool, number, string) or a complex type constructor call, like list(string).", - Subject: expr.Range().Ptr(), - }} - } - - switch call.Name { - case "bool", "string", "number", "any": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("Primitive type keyword %q does not expect arguments.", call.Name), - Subject: &call.ArgsRange, - }} - } - - if len(call.Arguments) != 1 { - contextRange := call.ArgsRange - subjectRange := call.ArgsRange - if len(call.Arguments) > 1 { - // If we have too many arguments (as opposed to too _few_) then - // we'll highlight the extraneous arguments as the diagnostic - // subject. - subjectRange = hcl.RangeBetween(call.Arguments[1].Range(), call.Arguments[len(call.Arguments)-1].Range()) - } - - switch call.Name { - case "list", "set", "map": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("The %s type constructor requires one argument specifying the element type.", call.Name), - Subject: &subjectRange, - Context: &contextRange, - }} - case "object": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "The object type constructor requires one argument specifying the attribute types and values as a map.", - Subject: &subjectRange, - Context: &contextRange, - }} - case "tuple": - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "The tuple type constructor requires one argument specifying the element types as a list.", - Subject: &subjectRange, - Context: &contextRange, - }} - } - } - - switch call.Name { - - case "list": - ety, diags := getType(call.Arguments[0], constraint) - return cty.List(ety), diags - case "set": - ety, diags := getType(call.Arguments[0], constraint) - return cty.Set(ety), diags - case "map": - ety, diags := getType(call.Arguments[0], constraint) - return cty.Map(ety), diags - case "object": - attrDefs, diags := hcl.ExprMap(call.Arguments[0]) - if diags.HasErrors() { - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "Object type constructor requires a map whose keys are attribute names and whose values are the corresponding attribute types.", - Subject: call.Arguments[0].Range().Ptr(), - Context: expr.Range().Ptr(), - }} - } - - atys := make(map[string]cty.Type) - for _, attrDef := range attrDefs { - attrName := hcl.ExprAsKeyword(attrDef.Key) - if attrName == "" { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "Object constructor map keys must be attribute names.", - Subject: attrDef.Key.Range().Ptr(), - Context: expr.Range().Ptr(), - }) - continue - } - aty, attrDiags := getType(attrDef.Value, constraint) - diags = append(diags, attrDiags...) - atys[attrName] = aty - } - return cty.Object(atys), diags - case "tuple": - elemDefs, diags := hcl.ExprList(call.Arguments[0]) - if diags.HasErrors() { - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: "Tuple type constructor requires a list of element types.", - Subject: call.Arguments[0].Range().Ptr(), - Context: expr.Range().Ptr(), - }} - } - etys := make([]cty.Type, len(elemDefs)) - for i, defExpr := range elemDefs { - ety, elemDiags := getType(defExpr, constraint) - diags = append(diags, elemDiags...) - etys[i] = ety - } - return cty.Tuple(etys), diags - default: - // Can't access call.Arguments in this path because we've not validated - // that it contains exactly one expression here. - return cty.DynamicPseudoType, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: invalidTypeSummary, - Detail: fmt.Sprintf("Keyword %q is not a valid type constructor.", call.Name), - Subject: expr.Range().Ptr(), - }} - } -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/public.go b/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/public.go deleted file mode 100644 index 3b8f618fbcd..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/public.go +++ /dev/null @@ -1,129 +0,0 @@ -package typeexpr - -import ( - "bytes" - "fmt" - "sort" - - "github.com/hashicorp/hcl/v2/hclsyntax" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -// Type attempts to process the given expression as a type expression and, if -// successful, returns the resulting type. If unsuccessful, error diagnostics -// are returned. -func Type(expr hcl.Expression) (cty.Type, hcl.Diagnostics) { - return getType(expr, false) -} - -// TypeConstraint attempts to parse the given expression as a type constraint -// and, if successful, returns the resulting type. If unsuccessful, error -// diagnostics are returned. -// -// A type constraint has the same structure as a type, but it additionally -// allows the keyword "any" to represent cty.DynamicPseudoType, which is often -// used as a wildcard in type checking and type conversion operations. -func TypeConstraint(expr hcl.Expression) (cty.Type, hcl.Diagnostics) { - return getType(expr, true) -} - -// TypeString returns a string rendering of the given type as it would be -// expected to appear in the HCL native syntax. -// -// This is primarily intended for showing types to the user in an application -// that uses typexpr, where the user can be assumed to be familiar with the -// type expression syntax. In applications that do not use typeexpr these -// results may be confusing to the user and so type.FriendlyName may be -// preferable, even though it's less precise. -// -// TypeString produces reasonable results only for types like what would be -// produced by the Type and TypeConstraint functions. In particular, it cannot -// support capsule types. -func TypeString(ty cty.Type) string { - // Easy cases first - switch ty { - case cty.String: - return "string" - case cty.Bool: - return "bool" - case cty.Number: - return "number" - case cty.DynamicPseudoType: - return "any" - } - - if ty.IsCapsuleType() { - panic("TypeString does not support capsule types") - } - - if ty.IsCollectionType() { - ety := ty.ElementType() - etyString := TypeString(ety) - switch { - case ty.IsListType(): - return fmt.Sprintf("list(%s)", etyString) - case ty.IsSetType(): - return fmt.Sprintf("set(%s)", etyString) - case ty.IsMapType(): - return fmt.Sprintf("map(%s)", etyString) - default: - // Should never happen because the above is exhaustive - panic("unsupported collection type") - } - } - - if ty.IsObjectType() { - var buf bytes.Buffer - buf.WriteString("object({") - atys := ty.AttributeTypes() - names := make([]string, 0, len(atys)) - for name := range atys { - names = append(names, name) - } - sort.Strings(names) - first := true - for _, name := range names { - aty := atys[name] - if !first { - buf.WriteByte(',') - } - if !hclsyntax.ValidIdentifier(name) { - // Should never happen for any type produced by this package, - // but we'll do something reasonable here just so we don't - // produce garbage if someone gives us a hand-assembled object - // type that has weird attribute names. - // Using Go-style quoting here isn't perfect, since it doesn't - // exactly match HCL syntax, but it's fine for an edge-case. - buf.WriteString(fmt.Sprintf("%q", name)) - } else { - buf.WriteString(name) - } - buf.WriteByte('=') - buf.WriteString(TypeString(aty)) - first = false - } - buf.WriteString("})") - return buf.String() - } - - if ty.IsTupleType() { - var buf bytes.Buffer - buf.WriteString("tuple([") - etys := ty.TupleElementTypes() - first := true - for _, ety := range etys { - if !first { - buf.WriteByte(',') - } - buf.WriteString(TypeString(ety)) - first = false - } - buf.WriteString("])") - return buf.String() - } - - // Should never happen because we covered all cases above. - panic(fmt.Errorf("unsupported type %#v", ty)) -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/type_type.go b/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/type_type.go deleted file mode 100644 index 5462d82c3c7..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/type_type.go +++ /dev/null @@ -1,118 +0,0 @@ -package typeexpr - -import ( - "fmt" - "reflect" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/ext/customdecode" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/function" -) - -// TypeConstraintType is a cty capsule type that allows cty type constraints to -// be used as values. -// -// If TypeConstraintType is used in a context supporting the -// customdecode.CustomExpressionDecoder extension then it will implement -// expression decoding using the TypeConstraint function, thus allowing -// type expressions to be used in contexts where value expressions might -// normally be expected, such as in arguments to function calls. -var TypeConstraintType cty.Type - -// TypeConstraintVal constructs a cty.Value whose type is -// TypeConstraintType. -func TypeConstraintVal(ty cty.Type) cty.Value { - return cty.CapsuleVal(TypeConstraintType, &ty) -} - -// TypeConstraintFromVal extracts the type from a cty.Value of -// TypeConstraintType that was previously constructed using TypeConstraintVal. -// -// If the given value isn't a known, non-null value of TypeConstraintType -// then this function will panic. -func TypeConstraintFromVal(v cty.Value) cty.Type { - if !v.Type().Equals(TypeConstraintType) { - panic("value is not of TypeConstraintType") - } - ptr := v.EncapsulatedValue().(*cty.Type) - return *ptr -} - -// ConvertFunc is a cty function that implements type conversions. -// -// Its signature is as follows: -// convert(value, type_constraint) -// -// ...where type_constraint is a type constraint expression as defined by -// typeexpr.TypeConstraint. -// -// It relies on HCL's customdecode extension and so it's not suitable for use -// in non-HCL contexts or if you are using a HCL syntax implementation that -// does not support customdecode for function arguments. However, it _is_ -// supported for function calls in the HCL native expression syntax. -var ConvertFunc function.Function - -func init() { - TypeConstraintType = cty.CapsuleWithOps("type constraint", reflect.TypeOf(cty.Type{}), &cty.CapsuleOps{ - ExtensionData: func(key interface{}) interface{} { - switch key { - case customdecode.CustomExpressionDecoder: - return customdecode.CustomExpressionDecoderFunc( - func(expr hcl.Expression, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - ty, diags := TypeConstraint(expr) - if diags.HasErrors() { - return cty.NilVal, diags - } - return TypeConstraintVal(ty), nil - }, - ) - default: - return nil - } - }, - TypeGoString: func(_ reflect.Type) string { - return "typeexpr.TypeConstraintType" - }, - GoString: func(raw interface{}) string { - tyPtr := raw.(*cty.Type) - return fmt.Sprintf("typeexpr.TypeConstraintVal(%#v)", *tyPtr) - }, - RawEquals: func(a, b interface{}) bool { - aPtr := a.(*cty.Type) - bPtr := b.(*cty.Type) - return (*aPtr).Equals(*bPtr) - }, - }) - - ConvertFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "value", - Type: cty.DynamicPseudoType, - AllowNull: true, - AllowDynamicType: true, - }, - { - Name: "type", - Type: TypeConstraintType, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - wantTypePtr := args[1].EncapsulatedValue().(*cty.Type) - got, err := convert.Convert(args[0], *wantTypePtr) - if err != nil { - return cty.NilType, function.NewArgError(0, err) - } - return got.Type(), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - v, err := convert.Convert(args[0], retType) - if err != nil { - return cty.NilVal, function.NewArgError(0, err) - } - return v, nil - }, - }) -} diff --git a/vendor/github.com/hashicorp/hcl/v2/gohcl/decode.go b/vendor/github.com/hashicorp/hcl/v2/gohcl/decode.go deleted file mode 100644 index f0d589d7774..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/gohcl/decode.go +++ /dev/null @@ -1,322 +0,0 @@ -package gohcl - -import ( - "fmt" - "reflect" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/gocty" -) - -// DecodeBody extracts the configuration within the given body into the given -// value. This value must be a non-nil pointer to either a struct or -// a map, where in the former case the configuration will be decoded using -// struct tags and in the latter case only attributes are allowed and their -// values are decoded into the map. -// -// The given EvalContext is used to resolve any variables or functions in -// expressions encountered while decoding. This may be nil to require only -// constant values, for simple applications that do not support variables or -// functions. -// -// The returned diagnostics should be inspected with its HasErrors method to -// determine if the populated value is valid and complete. If error diagnostics -// are returned then the given value may have been partially-populated but -// may still be accessed by a careful caller for static analysis and editor -// integration use-cases. -func DecodeBody(body hcl.Body, ctx *hcl.EvalContext, val interface{}) hcl.Diagnostics { - rv := reflect.ValueOf(val) - if rv.Kind() != reflect.Ptr { - panic(fmt.Sprintf("target value must be a pointer, not %s", rv.Type().String())) - } - - return decodeBodyToValue(body, ctx, rv.Elem()) -} - -func decodeBodyToValue(body hcl.Body, ctx *hcl.EvalContext, val reflect.Value) hcl.Diagnostics { - et := val.Type() - switch et.Kind() { - case reflect.Struct: - return decodeBodyToStruct(body, ctx, val) - case reflect.Map: - return decodeBodyToMap(body, ctx, val) - default: - panic(fmt.Sprintf("target value must be pointer to struct or map, not %s", et.String())) - } -} - -func decodeBodyToStruct(body hcl.Body, ctx *hcl.EvalContext, val reflect.Value) hcl.Diagnostics { - schema, partial := ImpliedBodySchema(val.Interface()) - - var content *hcl.BodyContent - var leftovers hcl.Body - var diags hcl.Diagnostics - if partial { - content, leftovers, diags = body.PartialContent(schema) - } else { - content, diags = body.Content(schema) - } - if content == nil { - return diags - } - - tags := getFieldTags(val.Type()) - - if tags.Remain != nil { - fieldIdx := *tags.Remain - field := val.Type().Field(fieldIdx) - fieldV := val.Field(fieldIdx) - switch { - case bodyType.AssignableTo(field.Type): - fieldV.Set(reflect.ValueOf(leftovers)) - case attrsType.AssignableTo(field.Type): - attrs, attrsDiags := leftovers.JustAttributes() - if len(attrsDiags) > 0 { - diags = append(diags, attrsDiags...) - } - fieldV.Set(reflect.ValueOf(attrs)) - default: - diags = append(diags, decodeBodyToValue(leftovers, ctx, fieldV)...) - } - } - - for name, fieldIdx := range tags.Attributes { - attr := content.Attributes[name] - field := val.Type().Field(fieldIdx) - fieldV := val.Field(fieldIdx) - - if attr == nil { - if !exprType.AssignableTo(field.Type) { - continue - } - - // As a special case, if the target is of type hcl.Expression then - // we'll assign an actual expression that evalues to a cty null, - // so the caller can deal with it within the cty realm rather - // than within the Go realm. - synthExpr := hcl.StaticExpr(cty.NullVal(cty.DynamicPseudoType), body.MissingItemRange()) - fieldV.Set(reflect.ValueOf(synthExpr)) - continue - } - - switch { - case attrType.AssignableTo(field.Type): - fieldV.Set(reflect.ValueOf(attr)) - case exprType.AssignableTo(field.Type): - fieldV.Set(reflect.ValueOf(attr.Expr)) - default: - diags = append(diags, DecodeExpression( - attr.Expr, ctx, fieldV.Addr().Interface(), - )...) - } - } - - blocksByType := content.Blocks.ByType() - - for typeName, fieldIdx := range tags.Blocks { - blocks := blocksByType[typeName] - field := val.Type().Field(fieldIdx) - - ty := field.Type - isSlice := false - isPtr := false - if ty.Kind() == reflect.Slice { - isSlice = true - ty = ty.Elem() - } - if ty.Kind() == reflect.Ptr { - isPtr = true - ty = ty.Elem() - } - - if len(blocks) > 1 && !isSlice { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Duplicate %s block", typeName), - Detail: fmt.Sprintf( - "Only one %s block is allowed. Another was defined at %s.", - typeName, blocks[0].DefRange.String(), - ), - Subject: &blocks[1].DefRange, - }) - continue - } - - if len(blocks) == 0 { - if isSlice || isPtr { - if val.Field(fieldIdx).IsNil() { - val.Field(fieldIdx).Set(reflect.Zero(field.Type)) - } - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Missing %s block", typeName), - Detail: fmt.Sprintf("A %s block is required.", typeName), - Subject: body.MissingItemRange().Ptr(), - }) - } - continue - } - - switch { - - case isSlice: - elemType := ty - if isPtr { - elemType = reflect.PtrTo(ty) - } - sli := val.Field(fieldIdx) - if sli.IsNil() { - sli = reflect.MakeSlice(reflect.SliceOf(elemType), len(blocks), len(blocks)) - } - - for i, block := range blocks { - if isPtr { - if i >= sli.Len() { - sli = reflect.Append(sli, reflect.New(ty)) - } - v := sli.Index(i) - if v.IsNil() { - v = reflect.New(ty) - } - diags = append(diags, decodeBlockToValue(block, ctx, v.Elem())...) - sli.Index(i).Set(v) - } else { - diags = append(diags, decodeBlockToValue(block, ctx, sli.Index(i))...) - } - } - - if sli.Len() > len(blocks) { - sli.SetLen(len(blocks)) - } - - val.Field(fieldIdx).Set(sli) - - default: - block := blocks[0] - if isPtr { - v := val.Field(fieldIdx) - if v.IsNil() { - v = reflect.New(ty) - } - diags = append(diags, decodeBlockToValue(block, ctx, v.Elem())...) - val.Field(fieldIdx).Set(v) - } else { - diags = append(diags, decodeBlockToValue(block, ctx, val.Field(fieldIdx))...) - } - - } - - } - - return diags -} - -func decodeBodyToMap(body hcl.Body, ctx *hcl.EvalContext, v reflect.Value) hcl.Diagnostics { - attrs, diags := body.JustAttributes() - if attrs == nil { - return diags - } - - mv := reflect.MakeMap(v.Type()) - - for k, attr := range attrs { - switch { - case attrType.AssignableTo(v.Type().Elem()): - mv.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(attr)) - case exprType.AssignableTo(v.Type().Elem()): - mv.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(attr.Expr)) - default: - ev := reflect.New(v.Type().Elem()) - diags = append(diags, DecodeExpression(attr.Expr, ctx, ev.Interface())...) - mv.SetMapIndex(reflect.ValueOf(k), ev.Elem()) - } - } - - v.Set(mv) - - return diags -} - -func decodeBlockToValue(block *hcl.Block, ctx *hcl.EvalContext, v reflect.Value) hcl.Diagnostics { - var diags hcl.Diagnostics - - ty := v.Type() - - switch { - case blockType.AssignableTo(ty): - v.Elem().Set(reflect.ValueOf(block)) - case bodyType.AssignableTo(ty): - v.Elem().Set(reflect.ValueOf(block.Body)) - case attrsType.AssignableTo(ty): - attrs, attrsDiags := block.Body.JustAttributes() - if len(attrsDiags) > 0 { - diags = append(diags, attrsDiags...) - } - v.Elem().Set(reflect.ValueOf(attrs)) - default: - diags = append(diags, decodeBodyToValue(block.Body, ctx, v)...) - - if len(block.Labels) > 0 { - blockTags := getFieldTags(ty) - for li, lv := range block.Labels { - lfieldIdx := blockTags.Labels[li].FieldIndex - v.Field(lfieldIdx).Set(reflect.ValueOf(lv)) - } - } - - } - - return diags -} - -// DecodeExpression extracts the value of the given expression into the given -// value. This value must be something that gocty is able to decode into, -// since the final decoding is delegated to that package. -// -// The given EvalContext is used to resolve any variables or functions in -// expressions encountered while decoding. This may be nil to require only -// constant values, for simple applications that do not support variables or -// functions. -// -// The returned diagnostics should be inspected with its HasErrors method to -// determine if the populated value is valid and complete. If error diagnostics -// are returned then the given value may have been partially-populated but -// may still be accessed by a careful caller for static analysis and editor -// integration use-cases. -func DecodeExpression(expr hcl.Expression, ctx *hcl.EvalContext, val interface{}) hcl.Diagnostics { - srcVal, diags := expr.Value(ctx) - - convTy, err := gocty.ImpliedType(val) - if err != nil { - panic(fmt.Sprintf("unsuitable DecodeExpression target: %s", err)) - } - - srcVal, err = convert.Convert(srcVal, convTy) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsuitable value type", - Detail: fmt.Sprintf("Unsuitable value: %s", err.Error()), - Subject: expr.StartRange().Ptr(), - Context: expr.Range().Ptr(), - }) - return diags - } - - err = gocty.FromCtyValue(srcVal, val) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsuitable value type", - Detail: fmt.Sprintf("Unsuitable value: %s", err.Error()), - Subject: expr.StartRange().Ptr(), - Context: expr.Range().Ptr(), - }) - } - - return diags -} diff --git a/vendor/github.com/hashicorp/hcl/v2/gohcl/doc.go b/vendor/github.com/hashicorp/hcl/v2/gohcl/doc.go deleted file mode 100644 index aa3c6ea9ef3..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/gohcl/doc.go +++ /dev/null @@ -1,53 +0,0 @@ -// Package gohcl allows decoding HCL configurations into Go data structures. -// -// It provides a convenient and concise way of describing the schema for -// configuration and then accessing the resulting data via native Go -// types. -// -// A struct field tag scheme is used, similar to other decoding and -// unmarshalling libraries. The tags are formatted as in the following example: -// -// ThingType string `hcl:"thing_type,attr"` -// -// Within each tag there are two comma-separated tokens. The first is the -// name of the corresponding construct in configuration, while the second -// is a keyword giving the kind of construct expected. The following -// kind keywords are supported: -// -// attr (the default) indicates that the value is to be populated from an attribute -// block indicates that the value is to populated from a block -// label indicates that the value is to populated from a block label -// remain indicates that the value is to be populated from the remaining body after populating other fields -// -// "attr" fields may either be of type *hcl.Expression, in which case the raw -// expression is assigned, or of any type accepted by gocty, in which case -// gocty will be used to assign the value to a native Go type. -// -// "block" fields may be of type *hcl.Block or hcl.Body, in which case the -// corresponding raw value is assigned, or may be a struct that recursively -// uses the same tags. Block fields may also be slices of any of these types, -// in which case multiple blocks of the corresponding type are decoded into -// the slice. -// -// "label" fields are considered only in a struct used as the type of a field -// marked as "block", and are used sequentially to capture the labels of -// the blocks being decoded. In this case, the name token is used only as -// an identifier for the label in diagnostic messages. -// -// "remain" can be placed on a single field that may be either of type -// hcl.Body or hcl.Attributes, in which case any remaining body content is -// placed into this field for delayed processing. If no "remain" field is -// present then any attributes or blocks not matched by another valid tag -// will cause an error diagnostic. -// -// Only a subset of this tagging/typing vocabulary is supported for the -// "Encode" family of functions. See the EncodeIntoBody docs for full details -// on the constraints there. -// -// Broadly-speaking this package deals with two types of error. The first is -// errors in the configuration itself, which are returned as diagnostics -// written with the configuration author as the target audience. The second -// is bugs in the calling program, such as invalid struct tags, which are -// surfaced via panics since there can be no useful runtime handling of such -// errors and they should certainly not be returned to the user as diagnostics. -package gohcl diff --git a/vendor/github.com/hashicorp/hcl/v2/gohcl/encode.go b/vendor/github.com/hashicorp/hcl/v2/gohcl/encode.go deleted file mode 100644 index d612e09c9f1..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/gohcl/encode.go +++ /dev/null @@ -1,191 +0,0 @@ -package gohcl - -import ( - "fmt" - "reflect" - "sort" - - "github.com/hashicorp/hcl/v2/hclwrite" - "github.com/zclconf/go-cty/cty/gocty" -) - -// EncodeIntoBody replaces the contents of the given hclwrite Body with -// attributes and blocks derived from the given value, which must be a -// struct value or a pointer to a struct value with the struct tags defined -// in this package. -// -// This function can work only with fully-decoded data. It will ignore any -// fields tagged as "remain", any fields that decode attributes into either -// hcl.Attribute or hcl.Expression values, and any fields that decode blocks -// into hcl.Attributes values. This function does not have enough information -// to complete the decoding of these types. -// -// Any fields tagged as "label" are ignored by this function. Use EncodeAsBlock -// to produce a whole hclwrite.Block including block labels. -// -// As long as a suitable value is given to encode and the destination body -// is non-nil, this function will always complete. It will panic in case of -// any errors in the calling program, such as passing an inappropriate type -// or a nil body. -// -// The layout of the resulting HCL source is derived from the ordering of -// the struct fields, with blank lines around nested blocks of different types. -// Fields representing attributes should usually precede those representing -// blocks so that the attributes can group togather in the result. For more -// control, use the hclwrite API directly. -func EncodeIntoBody(val interface{}, dst *hclwrite.Body) { - rv := reflect.ValueOf(val) - ty := rv.Type() - if ty.Kind() == reflect.Ptr { - rv = rv.Elem() - ty = rv.Type() - } - if ty.Kind() != reflect.Struct { - panic(fmt.Sprintf("value is %s, not struct", ty.Kind())) - } - - tags := getFieldTags(ty) - populateBody(rv, ty, tags, dst) -} - -// EncodeAsBlock creates a new hclwrite.Block populated with the data from -// the given value, which must be a struct or pointer to struct with the -// struct tags defined in this package. -// -// If the given struct type has fields tagged with "label" tags then they -// will be used in order to annotate the created block with labels. -// -// This function has the same constraints as EncodeIntoBody and will panic -// if they are violated. -func EncodeAsBlock(val interface{}, blockType string) *hclwrite.Block { - rv := reflect.ValueOf(val) - ty := rv.Type() - if ty.Kind() == reflect.Ptr { - rv = rv.Elem() - ty = rv.Type() - } - if ty.Kind() != reflect.Struct { - panic(fmt.Sprintf("value is %s, not struct", ty.Kind())) - } - - tags := getFieldTags(ty) - labels := make([]string, len(tags.Labels)) - for i, lf := range tags.Labels { - lv := rv.Field(lf.FieldIndex) - // We just stringify whatever we find. It should always be a string - // but if not then we'll still do something reasonable. - labels[i] = fmt.Sprintf("%s", lv.Interface()) - } - - block := hclwrite.NewBlock(blockType, labels) - populateBody(rv, ty, tags, block.Body()) - return block -} - -func populateBody(rv reflect.Value, ty reflect.Type, tags *fieldTags, dst *hclwrite.Body) { - nameIdxs := make(map[string]int, len(tags.Attributes)+len(tags.Blocks)) - namesOrder := make([]string, 0, len(tags.Attributes)+len(tags.Blocks)) - for n, i := range tags.Attributes { - nameIdxs[n] = i - namesOrder = append(namesOrder, n) - } - for n, i := range tags.Blocks { - nameIdxs[n] = i - namesOrder = append(namesOrder, n) - } - sort.SliceStable(namesOrder, func(i, j int) bool { - ni, nj := namesOrder[i], namesOrder[j] - return nameIdxs[ni] < nameIdxs[nj] - }) - - dst.Clear() - - prevWasBlock := false - for _, name := range namesOrder { - fieldIdx := nameIdxs[name] - field := ty.Field(fieldIdx) - fieldTy := field.Type - fieldVal := rv.Field(fieldIdx) - - if fieldTy.Kind() == reflect.Ptr { - fieldTy = fieldTy.Elem() - fieldVal = fieldVal.Elem() - } - - if _, isAttr := tags.Attributes[name]; isAttr { - - if exprType.AssignableTo(fieldTy) || attrType.AssignableTo(fieldTy) { - continue // ignore undecoded fields - } - if !fieldVal.IsValid() { - continue // ignore (field value is nil pointer) - } - if fieldTy.Kind() == reflect.Ptr && fieldVal.IsNil() { - continue // ignore - } - if prevWasBlock { - dst.AppendNewline() - prevWasBlock = false - } - - valTy, err := gocty.ImpliedType(fieldVal.Interface()) - if err != nil { - panic(fmt.Sprintf("cannot encode %T as HCL expression: %s", fieldVal.Interface(), err)) - } - - val, err := gocty.ToCtyValue(fieldVal.Interface(), valTy) - if err != nil { - // This should never happen, since we should always be able - // to decode into the implied type. - panic(fmt.Sprintf("failed to encode %T as %#v: %s", fieldVal.Interface(), valTy, err)) - } - - dst.SetAttributeValue(name, val) - - } else { // must be a block, then - elemTy := fieldTy - isSeq := false - if elemTy.Kind() == reflect.Slice || elemTy.Kind() == reflect.Array { - isSeq = true - elemTy = elemTy.Elem() - } - - if bodyType.AssignableTo(elemTy) || attrsType.AssignableTo(elemTy) { - continue // ignore undecoded fields - } - prevWasBlock = false - - if isSeq { - l := fieldVal.Len() - for i := 0; i < l; i++ { - elemVal := fieldVal.Index(i) - if !elemVal.IsValid() { - continue // ignore (elem value is nil pointer) - } - if elemTy.Kind() == reflect.Ptr && elemVal.IsNil() { - continue // ignore - } - block := EncodeAsBlock(elemVal.Interface(), name) - if !prevWasBlock { - dst.AppendNewline() - prevWasBlock = true - } - dst.AppendBlock(block) - } - } else { - if !fieldVal.IsValid() { - continue // ignore (field value is nil pointer) - } - if elemTy.Kind() == reflect.Ptr && fieldVal.IsNil() { - continue // ignore - } - block := EncodeAsBlock(fieldVal.Interface(), name) - if !prevWasBlock { - dst.AppendNewline() - prevWasBlock = true - } - dst.AppendBlock(block) - } - } - } -} diff --git a/vendor/github.com/hashicorp/hcl/v2/gohcl/schema.go b/vendor/github.com/hashicorp/hcl/v2/gohcl/schema.go deleted file mode 100644 index ecf6ddbac62..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/gohcl/schema.go +++ /dev/null @@ -1,174 +0,0 @@ -package gohcl - -import ( - "fmt" - "reflect" - "sort" - "strings" - - "github.com/hashicorp/hcl/v2" -) - -// ImpliedBodySchema produces a hcl.BodySchema derived from the type of the -// given value, which must be a struct value or a pointer to one. If an -// inappropriate value is passed, this function will panic. -// -// The second return argument indicates whether the given struct includes -// a "remain" field, and thus the returned schema is non-exhaustive. -// -// This uses the tags on the fields of the struct to discover how each -// field's value should be expressed within configuration. If an invalid -// mapping is attempted, this function will panic. -func ImpliedBodySchema(val interface{}) (schema *hcl.BodySchema, partial bool) { - ty := reflect.TypeOf(val) - - if ty.Kind() == reflect.Ptr { - ty = ty.Elem() - } - - if ty.Kind() != reflect.Struct { - panic(fmt.Sprintf("given value must be struct, not %T", val)) - } - - var attrSchemas []hcl.AttributeSchema - var blockSchemas []hcl.BlockHeaderSchema - - tags := getFieldTags(ty) - - attrNames := make([]string, 0, len(tags.Attributes)) - for n := range tags.Attributes { - attrNames = append(attrNames, n) - } - sort.Strings(attrNames) - for _, n := range attrNames { - idx := tags.Attributes[n] - optional := tags.Optional[n] - field := ty.Field(idx) - - var required bool - - switch { - case field.Type.AssignableTo(exprType): - // If we're decoding to hcl.Expression then absense can be - // indicated via a null value, so we don't specify that - // the field is required during decoding. - required = false - case field.Type.Kind() != reflect.Ptr && !optional: - required = true - default: - required = false - } - - attrSchemas = append(attrSchemas, hcl.AttributeSchema{ - Name: n, - Required: required, - }) - } - - blockNames := make([]string, 0, len(tags.Blocks)) - for n := range tags.Blocks { - blockNames = append(blockNames, n) - } - sort.Strings(blockNames) - for _, n := range blockNames { - idx := tags.Blocks[n] - field := ty.Field(idx) - fty := field.Type - if fty.Kind() == reflect.Slice { - fty = fty.Elem() - } - if fty.Kind() == reflect.Ptr { - fty = fty.Elem() - } - if fty.Kind() != reflect.Struct { - panic(fmt.Sprintf( - "hcl 'block' tag kind cannot be applied to %s field %s: struct required", field.Type.String(), field.Name, - )) - } - ftags := getFieldTags(fty) - var labelNames []string - if len(ftags.Labels) > 0 { - labelNames = make([]string, len(ftags.Labels)) - for i, l := range ftags.Labels { - labelNames[i] = l.Name - } - } - - blockSchemas = append(blockSchemas, hcl.BlockHeaderSchema{ - Type: n, - LabelNames: labelNames, - }) - } - - partial = tags.Remain != nil - schema = &hcl.BodySchema{ - Attributes: attrSchemas, - Blocks: blockSchemas, - } - return schema, partial -} - -type fieldTags struct { - Attributes map[string]int - Blocks map[string]int - Labels []labelField - Remain *int - Optional map[string]bool -} - -type labelField struct { - FieldIndex int - Name string -} - -func getFieldTags(ty reflect.Type) *fieldTags { - ret := &fieldTags{ - Attributes: map[string]int{}, - Blocks: map[string]int{}, - Optional: map[string]bool{}, - } - - ct := ty.NumField() - for i := 0; i < ct; i++ { - field := ty.Field(i) - tag := field.Tag.Get("hcl") - if tag == "" { - continue - } - - comma := strings.Index(tag, ",") - var name, kind string - if comma != -1 { - name = tag[:comma] - kind = tag[comma+1:] - } else { - name = tag - kind = "attr" - } - - switch kind { - case "attr": - ret.Attributes[name] = i - case "block": - ret.Blocks[name] = i - case "label": - ret.Labels = append(ret.Labels, labelField{ - FieldIndex: i, - Name: name, - }) - case "remain": - if ret.Remain != nil { - panic("only one 'remain' tag is permitted") - } - idx := i // copy, because this loop will continue assigning to i - ret.Remain = &idx - case "optional": - ret.Attributes[name] = i - ret.Optional[name] = true - default: - panic(fmt.Sprintf("invalid hcl field tag kind %q on %s %q", kind, field.Type.String(), field.Name)) - } - } - - return ret -} diff --git a/vendor/github.com/hashicorp/hcl/v2/gohcl/types.go b/vendor/github.com/hashicorp/hcl/v2/gohcl/types.go deleted file mode 100644 index a8d00f8ff2e..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/gohcl/types.go +++ /dev/null @@ -1,16 +0,0 @@ -package gohcl - -import ( - "reflect" - - "github.com/hashicorp/hcl/v2" -) - -var victimExpr hcl.Expression -var victimBody hcl.Body - -var exprType = reflect.TypeOf(&victimExpr).Elem() -var bodyType = reflect.TypeOf(&victimBody).Elem() -var blockType = reflect.TypeOf((*hcl.Block)(nil)) -var attrType = reflect.TypeOf((*hcl.Attribute)(nil)) -var attrsType = reflect.TypeOf(hcl.Attributes(nil)) diff --git a/vendor/github.com/hashicorp/hcl/v2/hcldec/block_labels.go b/vendor/github.com/hashicorp/hcl/v2/hcldec/block_labels.go deleted file mode 100644 index 71de451934a..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/hcldec/block_labels.go +++ /dev/null @@ -1,21 +0,0 @@ -package hcldec - -import ( - "github.com/hashicorp/hcl/v2" -) - -type blockLabel struct { - Value string - Range hcl.Range -} - -func labelsForBlock(block *hcl.Block) []blockLabel { - ret := make([]blockLabel, len(block.Labels)) - for i := range block.Labels { - ret[i] = blockLabel{ - Value: block.Labels[i], - Range: block.LabelRanges[i], - } - } - return ret -} diff --git a/vendor/github.com/hashicorp/hcl/v2/hcldec/decode.go b/vendor/github.com/hashicorp/hcl/v2/hcldec/decode.go deleted file mode 100644 index c6e42236d8f..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/hcldec/decode.go +++ /dev/null @@ -1,36 +0,0 @@ -package hcldec - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -func decode(body hcl.Body, blockLabels []blockLabel, ctx *hcl.EvalContext, spec Spec, partial bool) (cty.Value, hcl.Body, hcl.Diagnostics) { - schema := ImpliedSchema(spec) - - var content *hcl.BodyContent - var diags hcl.Diagnostics - var leftovers hcl.Body - - if partial { - content, leftovers, diags = body.PartialContent(schema) - } else { - content, diags = body.Content(schema) - } - - val, valDiags := spec.decode(content, blockLabels, ctx) - diags = append(diags, valDiags...) - - return val, leftovers, diags -} - -func impliedType(spec Spec) cty.Type { - return spec.impliedType() -} - -func sourceRange(body hcl.Body, blockLabels []blockLabel, spec Spec) hcl.Range { - schema := ImpliedSchema(spec) - content, _, _ := body.PartialContent(schema) - - return spec.sourceRange(content, blockLabels) -} diff --git a/vendor/github.com/hashicorp/hcl/v2/hcldec/doc.go b/vendor/github.com/hashicorp/hcl/v2/hcldec/doc.go deleted file mode 100644 index 23bfe542b2f..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/hcldec/doc.go +++ /dev/null @@ -1,12 +0,0 @@ -// Package hcldec provides a higher-level API for unpacking the content of -// HCL bodies, implemented in terms of the low-level "Content" API exposed -// by the bodies themselves. -// -// It allows decoding an entire nested configuration in a single operation -// by providing a description of the intended structure. -// -// For some applications it may be more convenient to use the "gohcl" -// package, which has a similar purpose but decodes directly into native -// Go data types. hcldec instead targets the cty type system, and thus allows -// a cty-driven application to remain within that type system. -package hcldec diff --git a/vendor/github.com/hashicorp/hcl/v2/hcldec/gob.go b/vendor/github.com/hashicorp/hcl/v2/hcldec/gob.go deleted file mode 100644 index e2027cfd2d2..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/hcldec/gob.go +++ /dev/null @@ -1,23 +0,0 @@ -package hcldec - -import ( - "encoding/gob" -) - -func init() { - // Every Spec implementation should be registered with gob, so that - // specs can be sent over gob channels, such as using - // github.com/hashicorp/go-plugin with plugins that need to describe - // what shape of configuration they are expecting. - gob.Register(ObjectSpec(nil)) - gob.Register(TupleSpec(nil)) - gob.Register((*AttrSpec)(nil)) - gob.Register((*LiteralSpec)(nil)) - gob.Register((*ExprSpec)(nil)) - gob.Register((*BlockSpec)(nil)) - gob.Register((*BlockListSpec)(nil)) - gob.Register((*BlockSetSpec)(nil)) - gob.Register((*BlockMapSpec)(nil)) - gob.Register((*BlockLabelSpec)(nil)) - gob.Register((*DefaultSpec)(nil)) -} diff --git a/vendor/github.com/hashicorp/hcl/v2/hcldec/public.go b/vendor/github.com/hashicorp/hcl/v2/hcldec/public.go deleted file mode 100644 index 1fa548d0c39..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/hcldec/public.go +++ /dev/null @@ -1,81 +0,0 @@ -package hcldec - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -// Decode interprets the given body using the given specification and returns -// the resulting value. If the given body is not valid per the spec, error -// diagnostics are returned and the returned value is likely to be incomplete. -// -// The ctx argument may be nil, in which case any references to variables or -// functions will produce error diagnostics. -func Decode(body hcl.Body, spec Spec, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - val, _, diags := decode(body, nil, ctx, spec, false) - return val, diags -} - -// PartialDecode is like Decode except that it permits "leftover" items in -// the top-level body, which are returned as a new body to allow for -// further processing. -// -// Any descendent block bodies are _not_ decoded partially and thus must -// be fully described by the given specification. -func PartialDecode(body hcl.Body, spec Spec, ctx *hcl.EvalContext) (cty.Value, hcl.Body, hcl.Diagnostics) { - return decode(body, nil, ctx, spec, true) -} - -// ImpliedType returns the value type that should result from decoding the -// given spec. -func ImpliedType(spec Spec) cty.Type { - return impliedType(spec) -} - -// SourceRange interprets the given body using the given specification and -// then returns the source range of the value that would be used to -// fulfill the spec. -// -// This can be used if application-level validation detects value errors, to -// obtain a reasonable SourceRange to use for generated diagnostics. It works -// best when applied to specific body items (e.g. using AttrSpec, BlockSpec, ...) -// as opposed to entire bodies using ObjectSpec, TupleSpec. The result will -// be less useful the broader the specification, so e.g. a spec that returns -// the entirety of all of the blocks of a given type is likely to be -// _particularly_ arbitrary and useless. -// -// If the given body is not valid per the given spec, the result is best-effort -// and may not actually be something ideal. It's expected that an application -// will already have used Decode or PartialDecode earlier and thus had an -// opportunity to detect and report spec violations. -func SourceRange(body hcl.Body, spec Spec) hcl.Range { - return sourceRange(body, nil, spec) -} - -// ChildBlockTypes returns a map of all of the child block types declared -// by the given spec, with block type names as keys and the associated -// nested body specs as values. -func ChildBlockTypes(spec Spec) map[string]Spec { - ret := map[string]Spec{} - - // visitSameBodyChildren walks through the spec structure, calling - // the given callback for each descendent spec encountered. We are - // interested in the specs that reference attributes and blocks. - var visit visitFunc - visit = func(s Spec) { - if bs, ok := s.(blockSpec); ok { - for _, blockS := range bs.blockHeaderSchemata() { - nested := bs.nestedSpec() - if nested != nil { // nil can be returned to dynamically opt out of this interface - ret[blockS.Type] = nested - } - } - } - - s.visitSameBodyChildren(visit) - } - - visit(spec) - - return ret -} diff --git a/vendor/github.com/hashicorp/hcl/v2/hcldec/schema.go b/vendor/github.com/hashicorp/hcl/v2/hcldec/schema.go deleted file mode 100644 index ddbe7fa4ab5..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/hcldec/schema.go +++ /dev/null @@ -1,36 +0,0 @@ -package hcldec - -import ( - "github.com/hashicorp/hcl/v2" -) - -// ImpliedSchema returns the *hcl.BodySchema implied by the given specification. -// This is the schema that the Decode function will use internally to -// access the content of a given body. -func ImpliedSchema(spec Spec) *hcl.BodySchema { - var attrs []hcl.AttributeSchema - var blocks []hcl.BlockHeaderSchema - - // visitSameBodyChildren walks through the spec structure, calling - // the given callback for each descendent spec encountered. We are - // interested in the specs that reference attributes and blocks. - var visit visitFunc - visit = func(s Spec) { - if as, ok := s.(attrSpec); ok { - attrs = append(attrs, as.attrSchemata()...) - } - - if bs, ok := s.(blockSpec); ok { - blocks = append(blocks, bs.blockHeaderSchemata()...) - } - - s.visitSameBodyChildren(visit) - } - - visit(spec) - - return &hcl.BodySchema{ - Attributes: attrs, - Blocks: blocks, - } -} diff --git a/vendor/github.com/hashicorp/hcl/v2/hcldec/spec.go b/vendor/github.com/hashicorp/hcl/v2/hcldec/spec.go deleted file mode 100644 index a70818e1b5b..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/hcldec/spec.go +++ /dev/null @@ -1,1591 +0,0 @@ -package hcldec - -import ( - "bytes" - "fmt" - "sort" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/ext/customdecode" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/function" -) - -// A Spec is a description of how to decode a hcl.Body to a cty.Value. -// -// The various other types in this package whose names end in "Spec" are -// the spec implementations. The most common top-level spec is ObjectSpec, -// which decodes body content into a cty.Value of an object type. -type Spec interface { - // Perform the decode operation on the given body, in the context of - // the given block (which might be null), using the given eval context. - // - // "block" is provided only by the nested calls performed by the spec - // types that work on block bodies. - decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) - - // Return the cty.Type that should be returned when decoding a body with - // this spec. - impliedType() cty.Type - - // Call the given callback once for each of the nested specs that would - // get decoded with the same body and block as the receiver. This should - // not descend into the nested specs used when decoding blocks. - visitSameBodyChildren(cb visitFunc) - - // Determine the source range of the value that would be returned for the - // spec in the given content, in the context of the given block - // (which might be null). If the corresponding item is missing, return - // a place where it might be inserted. - sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range -} - -type visitFunc func(spec Spec) - -// An ObjectSpec is a Spec that produces a cty.Value of an object type whose -// attributes correspond to the keys of the spec map. -type ObjectSpec map[string]Spec - -// attrSpec is implemented by specs that require attributes from the body. -type attrSpec interface { - attrSchemata() []hcl.AttributeSchema -} - -// blockSpec is implemented by specs that require blocks from the body. -type blockSpec interface { - blockHeaderSchemata() []hcl.BlockHeaderSchema - nestedSpec() Spec -} - -// specNeedingVariables is implemented by specs that can use variables -// from the EvalContext, to declare which variables they need. -type specNeedingVariables interface { - variablesNeeded(content *hcl.BodyContent) []hcl.Traversal -} - -func (s ObjectSpec) visitSameBodyChildren(cb visitFunc) { - for _, c := range s { - cb(c) - } -} - -func (s ObjectSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - vals := make(map[string]cty.Value, len(s)) - var diags hcl.Diagnostics - - for k, spec := range s { - var kd hcl.Diagnostics - vals[k], kd = spec.decode(content, blockLabels, ctx) - diags = append(diags, kd...) - } - - return cty.ObjectVal(vals), diags -} - -func (s ObjectSpec) impliedType() cty.Type { - if len(s) == 0 { - return cty.EmptyObject - } - - attrTypes := make(map[string]cty.Type) - for k, childSpec := range s { - attrTypes[k] = childSpec.impliedType() - } - return cty.Object(attrTypes) -} - -func (s ObjectSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // This is not great, but the best we can do. In practice, it's rather - // strange to ask for the source range of an entire top-level body, since - // that's already readily available to the caller. - return content.MissingItemRange -} - -// A TupleSpec is a Spec that produces a cty.Value of a tuple type whose -// elements correspond to the elements of the spec slice. -type TupleSpec []Spec - -func (s TupleSpec) visitSameBodyChildren(cb visitFunc) { - for _, c := range s { - cb(c) - } -} - -func (s TupleSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - vals := make([]cty.Value, len(s)) - var diags hcl.Diagnostics - - for i, spec := range s { - var ed hcl.Diagnostics - vals[i], ed = spec.decode(content, blockLabels, ctx) - diags = append(diags, ed...) - } - - return cty.TupleVal(vals), diags -} - -func (s TupleSpec) impliedType() cty.Type { - if len(s) == 0 { - return cty.EmptyTuple - } - - attrTypes := make([]cty.Type, len(s)) - for i, childSpec := range s { - attrTypes[i] = childSpec.impliedType() - } - return cty.Tuple(attrTypes) -} - -func (s TupleSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // This is not great, but the best we can do. In practice, it's rather - // strange to ask for the source range of an entire top-level body, since - // that's already readily available to the caller. - return content.MissingItemRange -} - -// An AttrSpec is a Spec that evaluates a particular attribute expression in -// the body and returns its resulting value converted to the requested type, -// or produces a diagnostic if the type is incorrect. -type AttrSpec struct { - Name string - Type cty.Type - Required bool -} - -func (s *AttrSpec) visitSameBodyChildren(cb visitFunc) { - // leaf node -} - -// specNeedingVariables implementation -func (s *AttrSpec) variablesNeeded(content *hcl.BodyContent) []hcl.Traversal { - attr, exists := content.Attributes[s.Name] - if !exists { - return nil - } - - return attr.Expr.Variables() -} - -// attrSpec implementation -func (s *AttrSpec) attrSchemata() []hcl.AttributeSchema { - return []hcl.AttributeSchema{ - { - Name: s.Name, - Required: s.Required, - }, - } -} - -func (s *AttrSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - attr, exists := content.Attributes[s.Name] - if !exists { - return content.MissingItemRange - } - - return attr.Expr.Range() -} - -func (s *AttrSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - attr, exists := content.Attributes[s.Name] - if !exists { - // We don't need to check required and emit a diagnostic here, because - // that would already have happened when building "content". - return cty.NullVal(s.Type), nil - } - - if decodeFn := customdecode.CustomExpressionDecoderForType(s.Type); decodeFn != nil { - v, diags := decodeFn(attr.Expr, ctx) - if v == cty.NilVal { - v = cty.UnknownVal(s.Type) - } - return v, diags - } - - val, diags := attr.Expr.Value(ctx) - - convVal, err := convert.Convert(val, s.Type) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Incorrect attribute value type", - Detail: fmt.Sprintf( - "Inappropriate value for attribute %q: %s.", - s.Name, err.Error(), - ), - Subject: attr.Expr.Range().Ptr(), - Context: hcl.RangeBetween(attr.NameRange, attr.Expr.Range()).Ptr(), - Expression: attr.Expr, - EvalContext: ctx, - }) - // We'll return an unknown value of the _correct_ type so that the - // incomplete result can still be used for some analysis use-cases. - val = cty.UnknownVal(s.Type) - } else { - val = convVal - } - - return val, diags -} - -func (s *AttrSpec) impliedType() cty.Type { - return s.Type -} - -// A LiteralSpec is a Spec that produces the given literal value, ignoring -// the given body. -type LiteralSpec struct { - Value cty.Value -} - -func (s *LiteralSpec) visitSameBodyChildren(cb visitFunc) { - // leaf node -} - -func (s *LiteralSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - return s.Value, nil -} - -func (s *LiteralSpec) impliedType() cty.Type { - return s.Value.Type() -} - -func (s *LiteralSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // No sensible range to return for a literal, so the caller had better - // ensure it doesn't cause any diagnostics. - return hcl.Range{ - Filename: "", - } -} - -// An ExprSpec is a Spec that evaluates the given expression, ignoring the -// given body. -type ExprSpec struct { - Expr hcl.Expression -} - -func (s *ExprSpec) visitSameBodyChildren(cb visitFunc) { - // leaf node -} - -// specNeedingVariables implementation -func (s *ExprSpec) variablesNeeded(content *hcl.BodyContent) []hcl.Traversal { - return s.Expr.Variables() -} - -func (s *ExprSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - return s.Expr.Value(ctx) -} - -func (s *ExprSpec) impliedType() cty.Type { - // We can't know the type of our expression until we evaluate it - return cty.DynamicPseudoType -} - -func (s *ExprSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - return s.Expr.Range() -} - -// A BlockSpec is a Spec that produces a cty.Value by decoding the contents -// of a single nested block of a given type, using a nested spec. -// -// If the Required flag is not set, the nested block may be omitted, in which -// case a null value is produced. If it _is_ set, an error diagnostic is -// produced if there are no nested blocks of the given type. -type BlockSpec struct { - TypeName string - Nested Spec - Required bool -} - -func (s *BlockSpec) visitSameBodyChildren(cb visitFunc) { - // leaf node ("Nested" does not use the same body) -} - -// blockSpec implementation -func (s *BlockSpec) blockHeaderSchemata() []hcl.BlockHeaderSchema { - return []hcl.BlockHeaderSchema{ - { - Type: s.TypeName, - LabelNames: findLabelSpecs(s.Nested), - }, - } -} - -// blockSpec implementation -func (s *BlockSpec) nestedSpec() Spec { - return s.Nested -} - -// specNeedingVariables implementation -func (s *BlockSpec) variablesNeeded(content *hcl.BodyContent) []hcl.Traversal { - var childBlock *hcl.Block - for _, candidate := range content.Blocks { - if candidate.Type != s.TypeName { - continue - } - - childBlock = candidate - break - } - - if childBlock == nil { - return nil - } - - return Variables(childBlock.Body, s.Nested) -} - -func (s *BlockSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - var diags hcl.Diagnostics - - var childBlock *hcl.Block - for _, candidate := range content.Blocks { - if candidate.Type != s.TypeName { - continue - } - - if childBlock != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Duplicate %s block", s.TypeName), - Detail: fmt.Sprintf( - "Only one block of type %q is allowed. Previous definition was at %s.", - s.TypeName, childBlock.DefRange.String(), - ), - Subject: &candidate.DefRange, - }) - break - } - - childBlock = candidate - } - - if childBlock == nil { - if s.Required { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Missing %s block", s.TypeName), - Detail: fmt.Sprintf( - "A block of type %q is required here.", s.TypeName, - ), - Subject: &content.MissingItemRange, - }) - } - return cty.NullVal(s.Nested.impliedType()), diags - } - - if s.Nested == nil { - panic("BlockSpec with no Nested Spec") - } - val, _, childDiags := decode(childBlock.Body, labelsForBlock(childBlock), ctx, s.Nested, false) - diags = append(diags, childDiags...) - return val, diags -} - -func (s *BlockSpec) impliedType() cty.Type { - return s.Nested.impliedType() -} - -func (s *BlockSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - var childBlock *hcl.Block - for _, candidate := range content.Blocks { - if candidate.Type != s.TypeName { - continue - } - - childBlock = candidate - break - } - - if childBlock == nil { - return content.MissingItemRange - } - - return sourceRange(childBlock.Body, labelsForBlock(childBlock), s.Nested) -} - -// A BlockListSpec is a Spec that produces a cty list of the results of -// decoding all of the nested blocks of a given type, using a nested spec. -type BlockListSpec struct { - TypeName string - Nested Spec - MinItems int - MaxItems int -} - -func (s *BlockListSpec) visitSameBodyChildren(cb visitFunc) { - // leaf node ("Nested" does not use the same body) -} - -// blockSpec implementation -func (s *BlockListSpec) blockHeaderSchemata() []hcl.BlockHeaderSchema { - return []hcl.BlockHeaderSchema{ - { - Type: s.TypeName, - LabelNames: findLabelSpecs(s.Nested), - }, - } -} - -// blockSpec implementation -func (s *BlockListSpec) nestedSpec() Spec { - return s.Nested -} - -// specNeedingVariables implementation -func (s *BlockListSpec) variablesNeeded(content *hcl.BodyContent) []hcl.Traversal { - var ret []hcl.Traversal - - for _, childBlock := range content.Blocks { - if childBlock.Type != s.TypeName { - continue - } - - ret = append(ret, Variables(childBlock.Body, s.Nested)...) - } - - return ret -} - -func (s *BlockListSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - var diags hcl.Diagnostics - - if s.Nested == nil { - panic("BlockListSpec with no Nested Spec") - } - - var elems []cty.Value - var sourceRanges []hcl.Range - for _, childBlock := range content.Blocks { - if childBlock.Type != s.TypeName { - continue - } - - val, _, childDiags := decode(childBlock.Body, labelsForBlock(childBlock), ctx, s.Nested, false) - diags = append(diags, childDiags...) - elems = append(elems, val) - sourceRanges = append(sourceRanges, sourceRange(childBlock.Body, labelsForBlock(childBlock), s.Nested)) - } - - if len(elems) < s.MinItems { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Insufficient %s blocks", s.TypeName), - Detail: fmt.Sprintf("At least %d %q blocks are required.", s.MinItems, s.TypeName), - Subject: &content.MissingItemRange, - }) - } else if s.MaxItems > 0 && len(elems) > s.MaxItems { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Too many %s blocks", s.TypeName), - Detail: fmt.Sprintf("No more than %d %q blocks are allowed", s.MaxItems, s.TypeName), - Subject: &sourceRanges[s.MaxItems], - }) - } - - var ret cty.Value - - if len(elems) == 0 { - ret = cty.ListValEmpty(s.Nested.impliedType()) - } else { - // Since our target is a list, all of the decoded elements must have the - // same type or cty.ListVal will panic below. Different types can arise - // if there is an attribute spec of type cty.DynamicPseudoType in the - // nested spec; all given values must be convertable to a single type - // in order for the result to be considered valid. - etys := make([]cty.Type, len(elems)) - for i, v := range elems { - etys[i] = v.Type() - } - ety, convs := convert.UnifyUnsafe(etys) - if ety == cty.NilType { - // FIXME: This is a pretty terrible error message. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Unconsistent argument types in %s blocks", s.TypeName), - Detail: "Corresponding attributes in all blocks of this type must be the same.", - Subject: &sourceRanges[0], - }) - return cty.DynamicVal, diags - } - for i, v := range elems { - if convs[i] != nil { - newV, err := convs[i](v) - if err != nil { - // FIXME: This is a pretty terrible error message. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Unconsistent argument types in %s blocks", s.TypeName), - Detail: fmt.Sprintf("Block with index %d has inconsistent argument types: %s.", i, err), - Subject: &sourceRanges[i], - }) - // Bail early here so we won't panic below in cty.ListVal - return cty.DynamicVal, diags - } - elems[i] = newV - } - } - - ret = cty.ListVal(elems) - } - - return ret, diags -} - -func (s *BlockListSpec) impliedType() cty.Type { - return cty.List(s.Nested.impliedType()) -} - -func (s *BlockListSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // We return the source range of the _first_ block of the given type, - // since they are not guaranteed to form a contiguous range. - - var childBlock *hcl.Block - for _, candidate := range content.Blocks { - if candidate.Type != s.TypeName { - continue - } - - childBlock = candidate - break - } - - if childBlock == nil { - return content.MissingItemRange - } - - return sourceRange(childBlock.Body, labelsForBlock(childBlock), s.Nested) -} - -// A BlockTupleSpec is a Spec that produces a cty tuple of the results of -// decoding all of the nested blocks of a given type, using a nested spec. -// -// This is similar to BlockListSpec, but it permits the nested blocks to have -// different result types in situations where cty.DynamicPseudoType attributes -// are present. -type BlockTupleSpec struct { - TypeName string - Nested Spec - MinItems int - MaxItems int -} - -func (s *BlockTupleSpec) visitSameBodyChildren(cb visitFunc) { - // leaf node ("Nested" does not use the same body) -} - -// blockSpec implementation -func (s *BlockTupleSpec) blockHeaderSchemata() []hcl.BlockHeaderSchema { - return []hcl.BlockHeaderSchema{ - { - Type: s.TypeName, - LabelNames: findLabelSpecs(s.Nested), - }, - } -} - -// blockSpec implementation -func (s *BlockTupleSpec) nestedSpec() Spec { - return s.Nested -} - -// specNeedingVariables implementation -func (s *BlockTupleSpec) variablesNeeded(content *hcl.BodyContent) []hcl.Traversal { - var ret []hcl.Traversal - - for _, childBlock := range content.Blocks { - if childBlock.Type != s.TypeName { - continue - } - - ret = append(ret, Variables(childBlock.Body, s.Nested)...) - } - - return ret -} - -func (s *BlockTupleSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - var diags hcl.Diagnostics - - if s.Nested == nil { - panic("BlockListSpec with no Nested Spec") - } - - var elems []cty.Value - var sourceRanges []hcl.Range - for _, childBlock := range content.Blocks { - if childBlock.Type != s.TypeName { - continue - } - - val, _, childDiags := decode(childBlock.Body, labelsForBlock(childBlock), ctx, s.Nested, false) - diags = append(diags, childDiags...) - elems = append(elems, val) - sourceRanges = append(sourceRanges, sourceRange(childBlock.Body, labelsForBlock(childBlock), s.Nested)) - } - - if len(elems) < s.MinItems { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Insufficient %s blocks", s.TypeName), - Detail: fmt.Sprintf("At least %d %q blocks are required.", s.MinItems, s.TypeName), - Subject: &content.MissingItemRange, - }) - } else if s.MaxItems > 0 && len(elems) > s.MaxItems { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Too many %s blocks", s.TypeName), - Detail: fmt.Sprintf("No more than %d %q blocks are allowed", s.MaxItems, s.TypeName), - Subject: &sourceRanges[s.MaxItems], - }) - } - - var ret cty.Value - - if len(elems) == 0 { - ret = cty.EmptyTupleVal - } else { - ret = cty.TupleVal(elems) - } - - return ret, diags -} - -func (s *BlockTupleSpec) impliedType() cty.Type { - // We can't predict our type, because we don't know how many blocks - // there will be until we decode. - return cty.DynamicPseudoType -} - -func (s *BlockTupleSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // We return the source range of the _first_ block of the given type, - // since they are not guaranteed to form a contiguous range. - - var childBlock *hcl.Block - for _, candidate := range content.Blocks { - if candidate.Type != s.TypeName { - continue - } - - childBlock = candidate - break - } - - if childBlock == nil { - return content.MissingItemRange - } - - return sourceRange(childBlock.Body, labelsForBlock(childBlock), s.Nested) -} - -// A BlockSetSpec is a Spec that produces a cty set of the results of -// decoding all of the nested blocks of a given type, using a nested spec. -type BlockSetSpec struct { - TypeName string - Nested Spec - MinItems int - MaxItems int -} - -func (s *BlockSetSpec) visitSameBodyChildren(cb visitFunc) { - // leaf node ("Nested" does not use the same body) -} - -// blockSpec implementation -func (s *BlockSetSpec) blockHeaderSchemata() []hcl.BlockHeaderSchema { - return []hcl.BlockHeaderSchema{ - { - Type: s.TypeName, - LabelNames: findLabelSpecs(s.Nested), - }, - } -} - -// blockSpec implementation -func (s *BlockSetSpec) nestedSpec() Spec { - return s.Nested -} - -// specNeedingVariables implementation -func (s *BlockSetSpec) variablesNeeded(content *hcl.BodyContent) []hcl.Traversal { - var ret []hcl.Traversal - - for _, childBlock := range content.Blocks { - if childBlock.Type != s.TypeName { - continue - } - - ret = append(ret, Variables(childBlock.Body, s.Nested)...) - } - - return ret -} - -func (s *BlockSetSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - var diags hcl.Diagnostics - - if s.Nested == nil { - panic("BlockSetSpec with no Nested Spec") - } - - var elems []cty.Value - var sourceRanges []hcl.Range - for _, childBlock := range content.Blocks { - if childBlock.Type != s.TypeName { - continue - } - - val, _, childDiags := decode(childBlock.Body, labelsForBlock(childBlock), ctx, s.Nested, false) - diags = append(diags, childDiags...) - elems = append(elems, val) - sourceRanges = append(sourceRanges, sourceRange(childBlock.Body, labelsForBlock(childBlock), s.Nested)) - } - - if len(elems) < s.MinItems { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Insufficient %s blocks", s.TypeName), - Detail: fmt.Sprintf("At least %d %q blocks are required.", s.MinItems, s.TypeName), - Subject: &content.MissingItemRange, - }) - } else if s.MaxItems > 0 && len(elems) > s.MaxItems { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Too many %s blocks", s.TypeName), - Detail: fmt.Sprintf("No more than %d %q blocks are allowed", s.MaxItems, s.TypeName), - Subject: &sourceRanges[s.MaxItems], - }) - } - - var ret cty.Value - - if len(elems) == 0 { - ret = cty.SetValEmpty(s.Nested.impliedType()) - } else { - // Since our target is a set, all of the decoded elements must have the - // same type or cty.SetVal will panic below. Different types can arise - // if there is an attribute spec of type cty.DynamicPseudoType in the - // nested spec; all given values must be convertable to a single type - // in order for the result to be considered valid. - etys := make([]cty.Type, len(elems)) - for i, v := range elems { - etys[i] = v.Type() - } - ety, convs := convert.UnifyUnsafe(etys) - if ety == cty.NilType { - // FIXME: This is a pretty terrible error message. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Unconsistent argument types in %s blocks", s.TypeName), - Detail: "Corresponding attributes in all blocks of this type must be the same.", - Subject: &sourceRanges[0], - }) - return cty.DynamicVal, diags - } - for i, v := range elems { - if convs[i] != nil { - newV, err := convs[i](v) - if err != nil { - // FIXME: This is a pretty terrible error message. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Unconsistent argument types in %s blocks", s.TypeName), - Detail: fmt.Sprintf("Block with index %d has inconsistent argument types: %s.", i, err), - Subject: &sourceRanges[i], - }) - // Bail early here so we won't panic below in cty.ListVal - return cty.DynamicVal, diags - } - elems[i] = newV - } - } - - ret = cty.SetVal(elems) - } - - return ret, diags -} - -func (s *BlockSetSpec) impliedType() cty.Type { - return cty.Set(s.Nested.impliedType()) -} - -func (s *BlockSetSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // We return the source range of the _first_ block of the given type, - // since they are not guaranteed to form a contiguous range. - - var childBlock *hcl.Block - for _, candidate := range content.Blocks { - if candidate.Type != s.TypeName { - continue - } - - childBlock = candidate - break - } - - if childBlock == nil { - return content.MissingItemRange - } - - return sourceRange(childBlock.Body, labelsForBlock(childBlock), s.Nested) -} - -// A BlockMapSpec is a Spec that produces a cty map of the results of -// decoding all of the nested blocks of a given type, using a nested spec. -// -// One level of map structure is created for each of the given label names. -// There must be at least one given label name. -type BlockMapSpec struct { - TypeName string - LabelNames []string - Nested Spec -} - -func (s *BlockMapSpec) visitSameBodyChildren(cb visitFunc) { - // leaf node ("Nested" does not use the same body) -} - -// blockSpec implementation -func (s *BlockMapSpec) blockHeaderSchemata() []hcl.BlockHeaderSchema { - return []hcl.BlockHeaderSchema{ - { - Type: s.TypeName, - LabelNames: append(s.LabelNames, findLabelSpecs(s.Nested)...), - }, - } -} - -// blockSpec implementation -func (s *BlockMapSpec) nestedSpec() Spec { - return s.Nested -} - -// specNeedingVariables implementation -func (s *BlockMapSpec) variablesNeeded(content *hcl.BodyContent) []hcl.Traversal { - var ret []hcl.Traversal - - for _, childBlock := range content.Blocks { - if childBlock.Type != s.TypeName { - continue - } - - ret = append(ret, Variables(childBlock.Body, s.Nested)...) - } - - return ret -} - -func (s *BlockMapSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - var diags hcl.Diagnostics - - if s.Nested == nil { - panic("BlockMapSpec with no Nested Spec") - } - if ImpliedType(s).HasDynamicTypes() { - panic("cty.DynamicPseudoType attributes may not be used inside a BlockMapSpec") - } - - elems := map[string]interface{}{} - for _, childBlock := range content.Blocks { - if childBlock.Type != s.TypeName { - continue - } - - childLabels := labelsForBlock(childBlock) - val, _, childDiags := decode(childBlock.Body, childLabels[len(s.LabelNames):], ctx, s.Nested, false) - targetMap := elems - for _, key := range childBlock.Labels[:len(s.LabelNames)-1] { - if _, exists := targetMap[key]; !exists { - targetMap[key] = make(map[string]interface{}) - } - targetMap = targetMap[key].(map[string]interface{}) - } - - diags = append(diags, childDiags...) - - key := childBlock.Labels[len(s.LabelNames)-1] - if _, exists := targetMap[key]; exists { - labelsBuf := bytes.Buffer{} - for _, label := range childBlock.Labels { - fmt.Fprintf(&labelsBuf, " %q", label) - } - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Duplicate %s block", s.TypeName), - Detail: fmt.Sprintf( - "A block for %s%s was already defined. The %s labels must be unique.", - s.TypeName, labelsBuf.String(), s.TypeName, - ), - Subject: &childBlock.DefRange, - }) - continue - } - - targetMap[key] = val - } - - if len(elems) == 0 { - return cty.MapValEmpty(s.Nested.impliedType()), diags - } - - var ctyMap func(map[string]interface{}, int) cty.Value - ctyMap = func(raw map[string]interface{}, depth int) cty.Value { - vals := make(map[string]cty.Value, len(raw)) - if depth == 1 { - for k, v := range raw { - vals[k] = v.(cty.Value) - } - } else { - for k, v := range raw { - vals[k] = ctyMap(v.(map[string]interface{}), depth-1) - } - } - return cty.MapVal(vals) - } - - return ctyMap(elems, len(s.LabelNames)), diags -} - -func (s *BlockMapSpec) impliedType() cty.Type { - ret := s.Nested.impliedType() - for _ = range s.LabelNames { - ret = cty.Map(ret) - } - return ret -} - -func (s *BlockMapSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // We return the source range of the _first_ block of the given type, - // since they are not guaranteed to form a contiguous range. - - var childBlock *hcl.Block - for _, candidate := range content.Blocks { - if candidate.Type != s.TypeName { - continue - } - - childBlock = candidate - break - } - - if childBlock == nil { - return content.MissingItemRange - } - - return sourceRange(childBlock.Body, labelsForBlock(childBlock), s.Nested) -} - -// A BlockObjectSpec is a Spec that produces a cty object of the results of -// decoding all of the nested blocks of a given type, using a nested spec. -// -// One level of object structure is created for each of the given label names. -// There must be at least one given label name. -// -// This is similar to BlockMapSpec, but it permits the nested blocks to have -// different result types in situations where cty.DynamicPseudoType attributes -// are present. -type BlockObjectSpec struct { - TypeName string - LabelNames []string - Nested Spec -} - -func (s *BlockObjectSpec) visitSameBodyChildren(cb visitFunc) { - // leaf node ("Nested" does not use the same body) -} - -// blockSpec implementation -func (s *BlockObjectSpec) blockHeaderSchemata() []hcl.BlockHeaderSchema { - return []hcl.BlockHeaderSchema{ - { - Type: s.TypeName, - LabelNames: append(s.LabelNames, findLabelSpecs(s.Nested)...), - }, - } -} - -// blockSpec implementation -func (s *BlockObjectSpec) nestedSpec() Spec { - return s.Nested -} - -// specNeedingVariables implementation -func (s *BlockObjectSpec) variablesNeeded(content *hcl.BodyContent) []hcl.Traversal { - var ret []hcl.Traversal - - for _, childBlock := range content.Blocks { - if childBlock.Type != s.TypeName { - continue - } - - ret = append(ret, Variables(childBlock.Body, s.Nested)...) - } - - return ret -} - -func (s *BlockObjectSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - var diags hcl.Diagnostics - - if s.Nested == nil { - panic("BlockObjectSpec with no Nested Spec") - } - - elems := map[string]interface{}{} - for _, childBlock := range content.Blocks { - if childBlock.Type != s.TypeName { - continue - } - - childLabels := labelsForBlock(childBlock) - val, _, childDiags := decode(childBlock.Body, childLabels[len(s.LabelNames):], ctx, s.Nested, false) - targetMap := elems - for _, key := range childBlock.Labels[:len(s.LabelNames)-1] { - if _, exists := targetMap[key]; !exists { - targetMap[key] = make(map[string]interface{}) - } - targetMap = targetMap[key].(map[string]interface{}) - } - - diags = append(diags, childDiags...) - - key := childBlock.Labels[len(s.LabelNames)-1] - if _, exists := targetMap[key]; exists { - labelsBuf := bytes.Buffer{} - for _, label := range childBlock.Labels { - fmt.Fprintf(&labelsBuf, " %q", label) - } - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Duplicate %s block", s.TypeName), - Detail: fmt.Sprintf( - "A block for %s%s was already defined. The %s labels must be unique.", - s.TypeName, labelsBuf.String(), s.TypeName, - ), - Subject: &childBlock.DefRange, - }) - continue - } - - targetMap[key] = val - } - - if len(elems) == 0 { - return cty.EmptyObjectVal, diags - } - - var ctyObj func(map[string]interface{}, int) cty.Value - ctyObj = func(raw map[string]interface{}, depth int) cty.Value { - vals := make(map[string]cty.Value, len(raw)) - if depth == 1 { - for k, v := range raw { - vals[k] = v.(cty.Value) - } - } else { - for k, v := range raw { - vals[k] = ctyObj(v.(map[string]interface{}), depth-1) - } - } - return cty.ObjectVal(vals) - } - - return ctyObj(elems, len(s.LabelNames)), diags -} - -func (s *BlockObjectSpec) impliedType() cty.Type { - // We can't predict our type, since we don't know how many blocks are - // present and what labels they have until we decode. - return cty.DynamicPseudoType -} - -func (s *BlockObjectSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // We return the source range of the _first_ block of the given type, - // since they are not guaranteed to form a contiguous range. - - var childBlock *hcl.Block - for _, candidate := range content.Blocks { - if candidate.Type != s.TypeName { - continue - } - - childBlock = candidate - break - } - - if childBlock == nil { - return content.MissingItemRange - } - - return sourceRange(childBlock.Body, labelsForBlock(childBlock), s.Nested) -} - -// A BlockAttrsSpec is a Spec that interprets a single block as if it were -// a map of some element type. That is, each attribute within the block -// becomes a key in the resulting map and the attribute's value becomes the -// element value, after conversion to the given element type. The resulting -// value is a cty.Map of the given element type. -// -// This spec imposes a validation constraint that there be exactly one block -// of the given type name and that this block may contain only attributes. The -// block does not accept any labels. -// -// This is an alternative to an AttrSpec of a map type for situations where -// block syntax is desired. Note that block syntax does not permit dynamic -// keys, construction of the result via a "for" expression, etc. In most cases -// an AttrSpec is preferred if the desired result is a map whose keys are -// chosen by the user rather than by schema. -type BlockAttrsSpec struct { - TypeName string - ElementType cty.Type - Required bool -} - -func (s *BlockAttrsSpec) visitSameBodyChildren(cb visitFunc) { - // leaf node -} - -// blockSpec implementation -func (s *BlockAttrsSpec) blockHeaderSchemata() []hcl.BlockHeaderSchema { - return []hcl.BlockHeaderSchema{ - { - Type: s.TypeName, - LabelNames: nil, - }, - } -} - -// blockSpec implementation -func (s *BlockAttrsSpec) nestedSpec() Spec { - // This is an odd case: we aren't actually going to apply a nested spec - // in this case, since we're going to interpret the body directly as - // attributes, but we need to return something non-nil so that the - // decoder will recognize this as a block spec. We won't actually be - // using this for anything at decode time. - return noopSpec{} -} - -// specNeedingVariables implementation -func (s *BlockAttrsSpec) variablesNeeded(content *hcl.BodyContent) []hcl.Traversal { - - block, _ := s.findBlock(content) - if block == nil { - return nil - } - - var vars []hcl.Traversal - - attrs, diags := block.Body.JustAttributes() - if diags.HasErrors() { - return nil - } - - for _, attr := range attrs { - vars = append(vars, attr.Expr.Variables()...) - } - - // We'll return the variables references in source order so that any - // error messages that result are also in source order. - sort.Slice(vars, func(i, j int) bool { - return vars[i].SourceRange().Start.Byte < vars[j].SourceRange().Start.Byte - }) - - return vars -} - -func (s *BlockAttrsSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - var diags hcl.Diagnostics - - block, other := s.findBlock(content) - if block == nil { - if s.Required { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Missing %s block", s.TypeName), - Detail: fmt.Sprintf( - "A block of type %q is required here.", s.TypeName, - ), - Subject: &content.MissingItemRange, - }) - } - return cty.NullVal(cty.Map(s.ElementType)), diags - } - if other != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Duplicate %s block", s.TypeName), - Detail: fmt.Sprintf( - "Only one block of type %q is allowed. Previous definition was at %s.", - s.TypeName, block.DefRange.String(), - ), - Subject: &other.DefRange, - }) - } - - attrs, attrDiags := block.Body.JustAttributes() - diags = append(diags, attrDiags...) - - if len(attrs) == 0 { - return cty.MapValEmpty(s.ElementType), diags - } - - vals := make(map[string]cty.Value, len(attrs)) - for name, attr := range attrs { - if decodeFn := customdecode.CustomExpressionDecoderForType(s.ElementType); decodeFn != nil { - attrVal, attrDiags := decodeFn(attr.Expr, ctx) - diags = append(diags, attrDiags...) - if attrVal == cty.NilVal { - attrVal = cty.UnknownVal(s.ElementType) - } - vals[name] = attrVal - continue - } - - attrVal, attrDiags := attr.Expr.Value(ctx) - diags = append(diags, attrDiags...) - - attrVal, err := convert.Convert(attrVal, s.ElementType) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid attribute value", - Detail: fmt.Sprintf("Invalid value for attribute of %q block: %s.", s.TypeName, err), - Subject: attr.Expr.Range().Ptr(), - Context: hcl.RangeBetween(attr.NameRange, attr.Expr.Range()).Ptr(), - Expression: attr.Expr, - EvalContext: ctx, - }) - attrVal = cty.UnknownVal(s.ElementType) - } - - vals[name] = attrVal - } - - return cty.MapVal(vals), diags -} - -func (s *BlockAttrsSpec) impliedType() cty.Type { - return cty.Map(s.ElementType) -} - -func (s *BlockAttrsSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - block, _ := s.findBlock(content) - if block == nil { - return content.MissingItemRange - } - return block.DefRange -} - -func (s *BlockAttrsSpec) findBlock(content *hcl.BodyContent) (block *hcl.Block, other *hcl.Block) { - for _, candidate := range content.Blocks { - if candidate.Type != s.TypeName { - continue - } - if block != nil { - return block, candidate - } - block = candidate - } - - return block, nil -} - -// A BlockLabelSpec is a Spec that returns a cty.String representing the -// label of the block its given body belongs to, if indeed its given body -// belongs to a block. It is a programming error to use this in a non-block -// context, so this spec will panic in that case. -// -// This spec only works in the nested spec within a BlockSpec, BlockListSpec, -// BlockSetSpec or BlockMapSpec. -// -// The full set of label specs used against a particular block must have a -// consecutive set of indices starting at zero. The maximum index found -// defines how many labels the corresponding blocks must have in cty source. -type BlockLabelSpec struct { - Index int - Name string -} - -func (s *BlockLabelSpec) visitSameBodyChildren(cb visitFunc) { - // leaf node -} - -func (s *BlockLabelSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - if s.Index >= len(blockLabels) { - panic("BlockListSpec used in non-block context") - } - - return cty.StringVal(blockLabels[s.Index].Value), nil -} - -func (s *BlockLabelSpec) impliedType() cty.Type { - return cty.String // labels are always strings -} - -func (s *BlockLabelSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - if s.Index >= len(blockLabels) { - panic("BlockListSpec used in non-block context") - } - - return blockLabels[s.Index].Range -} - -func findLabelSpecs(spec Spec) []string { - maxIdx := -1 - var names map[int]string - - var visit visitFunc - visit = func(s Spec) { - if ls, ok := s.(*BlockLabelSpec); ok { - if maxIdx < ls.Index { - maxIdx = ls.Index - } - if names == nil { - names = make(map[int]string) - } - names[ls.Index] = ls.Name - } - s.visitSameBodyChildren(visit) - } - - visit(spec) - - if maxIdx < 0 { - return nil // no labels at all - } - - ret := make([]string, maxIdx+1) - for i := range ret { - name := names[i] - if name == "" { - // Should never happen if the spec is conformant, since we require - // consecutive indices starting at zero. - name = fmt.Sprintf("missing%02d", i) - } - ret[i] = name - } - - return ret -} - -// DefaultSpec is a spec that wraps two specs, evaluating the primary first -// and then evaluating the default if the primary returns a null value. -// -// The two specifications must have the same implied result type for correct -// operation. If not, the result is undefined. -// -// Any requirements imposed by the "Default" spec apply even if "Primary" does -// not return null. For example, if the "Default" spec is for a required -// attribute then that attribute is always required, regardless of the result -// of the "Primary" spec. -// -// The "Default" spec must not describe a nested block, since otherwise the -// result of ChildBlockTypes would not be decidable without evaluation. If -// the default spec _does_ describe a nested block then the result is -// undefined. -type DefaultSpec struct { - Primary Spec - Default Spec -} - -func (s *DefaultSpec) visitSameBodyChildren(cb visitFunc) { - cb(s.Primary) - cb(s.Default) -} - -func (s *DefaultSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - val, diags := s.Primary.decode(content, blockLabels, ctx) - if val.IsNull() { - var moreDiags hcl.Diagnostics - val, moreDiags = s.Default.decode(content, blockLabels, ctx) - diags = append(diags, moreDiags...) - } - return val, diags -} - -func (s *DefaultSpec) impliedType() cty.Type { - return s.Primary.impliedType() -} - -// attrSpec implementation -func (s *DefaultSpec) attrSchemata() []hcl.AttributeSchema { - // We must pass through the union of both of our nested specs so that - // we'll have both values available in the result. - var ret []hcl.AttributeSchema - if as, ok := s.Primary.(attrSpec); ok { - ret = append(ret, as.attrSchemata()...) - } - if as, ok := s.Default.(attrSpec); ok { - ret = append(ret, as.attrSchemata()...) - } - return ret -} - -// blockSpec implementation -func (s *DefaultSpec) blockHeaderSchemata() []hcl.BlockHeaderSchema { - // Only the primary spec may describe a block, since otherwise - // our nestedSpec method below can't know which to return. - if bs, ok := s.Primary.(blockSpec); ok { - return bs.blockHeaderSchemata() - } - return nil -} - -// blockSpec implementation -func (s *DefaultSpec) nestedSpec() Spec { - if bs, ok := s.Primary.(blockSpec); ok { - return bs.nestedSpec() - } - return nil -} - -func (s *DefaultSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // We can't tell from here which of the two specs will ultimately be used - // in our result, so we'll just assume the first. This is usually the right - // choice because the default is often a literal spec that doesn't have a - // reasonable source range to return anyway. - return s.Primary.sourceRange(content, blockLabels) -} - -// TransformExprSpec is a spec that wraps another and then evaluates a given -// hcl.Expression on the result. -// -// The implied type of this spec is determined by evaluating the expression -// with an unknown value of the nested spec's implied type, which may cause -// the result to be imprecise. This spec should not be used in situations where -// precise result type information is needed. -type TransformExprSpec struct { - Wrapped Spec - Expr hcl.Expression - TransformCtx *hcl.EvalContext - VarName string -} - -func (s *TransformExprSpec) visitSameBodyChildren(cb visitFunc) { - cb(s.Wrapped) -} - -func (s *TransformExprSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - wrappedVal, diags := s.Wrapped.decode(content, blockLabels, ctx) - if diags.HasErrors() { - // We won't try to run our function in this case, because it'll probably - // generate confusing additional errors that will distract from the - // root cause. - return cty.UnknownVal(s.impliedType()), diags - } - - chiCtx := s.TransformCtx.NewChild() - chiCtx.Variables = map[string]cty.Value{ - s.VarName: wrappedVal, - } - resultVal, resultDiags := s.Expr.Value(chiCtx) - diags = append(diags, resultDiags...) - return resultVal, diags -} - -func (s *TransformExprSpec) impliedType() cty.Type { - wrappedTy := s.Wrapped.impliedType() - chiCtx := s.TransformCtx.NewChild() - chiCtx.Variables = map[string]cty.Value{ - s.VarName: cty.UnknownVal(wrappedTy), - } - resultVal, _ := s.Expr.Value(chiCtx) - return resultVal.Type() -} - -func (s *TransformExprSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // We'll just pass through our wrapped range here, even though that's - // not super-accurate, because there's nothing better to return. - return s.Wrapped.sourceRange(content, blockLabels) -} - -// TransformFuncSpec is a spec that wraps another and then evaluates a given -// cty function with the result. The given function must expect exactly one -// argument, where the result of the wrapped spec will be passed. -// -// The implied type of this spec is determined by type-checking the function -// with an unknown value of the nested spec's implied type, which may cause -// the result to be imprecise. This spec should not be used in situations where -// precise result type information is needed. -// -// If the given function produces an error when run, this spec will produce -// a non-user-actionable diagnostic message. It's the caller's responsibility -// to ensure that the given function cannot fail for any non-error result -// of the wrapped spec. -type TransformFuncSpec struct { - Wrapped Spec - Func function.Function -} - -func (s *TransformFuncSpec) visitSameBodyChildren(cb visitFunc) { - cb(s.Wrapped) -} - -func (s *TransformFuncSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - wrappedVal, diags := s.Wrapped.decode(content, blockLabels, ctx) - if diags.HasErrors() { - // We won't try to run our function in this case, because it'll probably - // generate confusing additional errors that will distract from the - // root cause. - return cty.UnknownVal(s.impliedType()), diags - } - - resultVal, err := s.Func.Call([]cty.Value{wrappedVal}) - if err != nil { - // This is not a good example of a diagnostic because it is reporting - // a programming error in the calling application, rather than something - // an end-user could act on. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Transform function failed", - Detail: fmt.Sprintf("Decoder transform returned an error: %s", err), - Subject: s.sourceRange(content, blockLabels).Ptr(), - }) - return cty.UnknownVal(s.impliedType()), diags - } - - return resultVal, diags -} - -func (s *TransformFuncSpec) impliedType() cty.Type { - wrappedTy := s.Wrapped.impliedType() - resultTy, err := s.Func.ReturnType([]cty.Type{wrappedTy}) - if err != nil { - // Should never happen with a correctly-configured spec - return cty.DynamicPseudoType - } - - return resultTy -} - -func (s *TransformFuncSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // We'll just pass through our wrapped range here, even though that's - // not super-accurate, because there's nothing better to return. - return s.Wrapped.sourceRange(content, blockLabels) -} - -// noopSpec is a placeholder spec that does nothing, used in situations where -// a non-nil placeholder spec is required. It is not exported because there is -// no reason to use it directly; it is always an implementation detail only. -type noopSpec struct { -} - -func (s noopSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - return cty.NullVal(cty.DynamicPseudoType), nil -} - -func (s noopSpec) impliedType() cty.Type { - return cty.DynamicPseudoType -} - -func (s noopSpec) visitSameBodyChildren(cb visitFunc) { - // nothing to do -} - -func (s noopSpec) sourceRange(content *hcl.BodyContent, blockLabels []blockLabel) hcl.Range { - // No useful range for a noopSpec, and nobody should be calling this anyway. - return hcl.Range{ - Filename: "noopSpec", - } -} diff --git a/vendor/github.com/hashicorp/hcl/v2/hcldec/variables.go b/vendor/github.com/hashicorp/hcl/v2/hcldec/variables.go deleted file mode 100644 index f8440eb6022..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/hcldec/variables.go +++ /dev/null @@ -1,36 +0,0 @@ -package hcldec - -import ( - "github.com/hashicorp/hcl/v2" -) - -// Variables processes the given body with the given spec and returns a -// list of the variable traversals that would be required to decode -// the same pairing of body and spec. -// -// This can be used to conditionally populate the variables in the EvalContext -// passed to Decode, for applications where a static scope is insufficient. -// -// If the given body is not compliant with the given schema, the result may -// be incomplete, but that's assumed to be okay because the eventual call -// to Decode will produce error diagnostics anyway. -func Variables(body hcl.Body, spec Spec) []hcl.Traversal { - var vars []hcl.Traversal - schema := ImpliedSchema(spec) - content, _, _ := body.PartialContent(schema) - - if vs, ok := spec.(specNeedingVariables); ok { - vars = append(vars, vs.variablesNeeded(content)...) - } - - var visitFn visitFunc - visitFn = func(s Spec) { - if vs, ok := s.(specNeedingVariables); ok { - vars = append(vars, vs.variablesNeeded(content)...) - } - s.visitSameBodyChildren(visitFn) - } - spec.visitSameBodyChildren(visitFn) - - return vars -} diff --git a/vendor/github.com/hashicorp/hcl/v2/hcled/doc.go b/vendor/github.com/hashicorp/hcl/v2/hcled/doc.go deleted file mode 100644 index 1a8014480cf..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/hcled/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package hcled provides functionality intended to help an application -// that embeds HCL to deliver relevant information to a text editor or IDE -// for navigating around and analyzing configuration files. -package hcled diff --git a/vendor/github.com/hashicorp/hcl/v2/hcled/navigation.go b/vendor/github.com/hashicorp/hcl/v2/hcled/navigation.go deleted file mode 100644 index 050ad758f6f..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/hcled/navigation.go +++ /dev/null @@ -1,34 +0,0 @@ -package hcled - -import ( - "github.com/hashicorp/hcl/v2" -) - -type contextStringer interface { - ContextString(offset int) string -} - -// ContextString returns a string describing the context of the given byte -// offset, if available. An empty string is returned if no such information -// is available, or otherwise the returned string is in a form that depends -// on the language used to write the referenced file. -func ContextString(file *hcl.File, offset int) string { - if cser, ok := file.Nav.(contextStringer); ok { - return cser.ContextString(offset) - } - return "" -} - -type contextDefRanger interface { - ContextDefRange(offset int) hcl.Range -} - -func ContextDefRange(file *hcl.File, offset int) hcl.Range { - if cser, ok := file.Nav.(contextDefRanger); ok { - defRange := cser.ContextDefRange(offset) - if !defRange.Empty() { - return defRange - } - } - return file.Body.MissingItemRange() -} diff --git a/vendor/github.com/hashicorp/hcl/v2/hclparse/parser.go b/vendor/github.com/hashicorp/hcl/v2/hclparse/parser.go deleted file mode 100644 index 1dc2eccd87f..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/hclparse/parser.go +++ /dev/null @@ -1,135 +0,0 @@ -// Package hclparse has the main API entry point for parsing both HCL native -// syntax and HCL JSON. -// -// The main HCL package also includes SimpleParse and SimpleParseFile which -// can be a simpler interface for the common case where an application just -// needs to parse a single file. The gohcl package simplifies that further -// in its SimpleDecode function, which combines hcl.SimpleParse with decoding -// into Go struct values -// -// Package hclparse, then, is useful for applications that require more fine -// control over parsing or which need to load many separate files and keep -// track of them for possible error reporting or other analysis. -package hclparse - -import ( - "fmt" - "io/ioutil" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" - "github.com/hashicorp/hcl/v2/json" -) - -// NOTE: This is the public interface for parsing. The actual parsers are -// in other packages alongside this one, with this package just wrapping them -// to provide a unified interface for the caller across all supported formats. - -// Parser is the main interface for parsing configuration files. As well as -// parsing files, a parser also retains a registry of all of the files it -// has parsed so that multiple attempts to parse the same file will return -// the same object and so the collected files can be used when printing -// diagnostics. -// -// Any diagnostics for parsing a file are only returned once on the first -// call to parse that file. Callers are expected to collect up diagnostics -// and present them together, so returning diagnostics for the same file -// multiple times would create a confusing result. -type Parser struct { - files map[string]*hcl.File -} - -// NewParser creates a new parser, ready to parse configuration files. -func NewParser() *Parser { - return &Parser{ - files: map[string]*hcl.File{}, - } -} - -// ParseHCL parses the given buffer (which is assumed to have been loaded from -// the given filename) as a native-syntax configuration file and returns the -// hcl.File object representing it. -func (p *Parser) ParseHCL(src []byte, filename string) (*hcl.File, hcl.Diagnostics) { - if existing := p.files[filename]; existing != nil { - return existing, nil - } - - file, diags := hclsyntax.ParseConfig(src, filename, hcl.Pos{Byte: 0, Line: 1, Column: 1}) - p.files[filename] = file - return file, diags -} - -// ParseHCLFile reads the given filename and parses it as a native-syntax HCL -// configuration file. An error diagnostic is returned if the given file -// cannot be read. -func (p *Parser) ParseHCLFile(filename string) (*hcl.File, hcl.Diagnostics) { - if existing := p.files[filename]; existing != nil { - return existing, nil - } - - src, err := ioutil.ReadFile(filename) - if err != nil { - return nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Failed to read file", - Detail: fmt.Sprintf("The configuration file %q could not be read.", filename), - }, - } - } - - return p.ParseHCL(src, filename) -} - -// ParseJSON parses the given JSON buffer (which is assumed to have been loaded -// from the given filename) and returns the hcl.File object representing it. -func (p *Parser) ParseJSON(src []byte, filename string) (*hcl.File, hcl.Diagnostics) { - if existing := p.files[filename]; existing != nil { - return existing, nil - } - - file, diags := json.Parse(src, filename) - p.files[filename] = file - return file, diags -} - -// ParseJSONFile reads the given filename and parses it as JSON, similarly to -// ParseJSON. An error diagnostic is returned if the given file cannot be read. -func (p *Parser) ParseJSONFile(filename string) (*hcl.File, hcl.Diagnostics) { - if existing := p.files[filename]; existing != nil { - return existing, nil - } - - file, diags := json.ParseFile(filename) - p.files[filename] = file - return file, diags -} - -// AddFile allows a caller to record in a parser a file that was parsed some -// other way, thus allowing it to be included in the registry of sources. -func (p *Parser) AddFile(filename string, file *hcl.File) { - p.files[filename] = file -} - -// Sources returns a map from filenames to the raw source code that was -// read from them. This is intended to be used, for example, to print -// diagnostics with contextual information. -// -// The arrays underlying the returned slices should not be modified. -func (p *Parser) Sources() map[string][]byte { - ret := make(map[string][]byte) - for fn, f := range p.files { - ret[fn] = f.Bytes - } - return ret -} - -// Files returns a map from filenames to the File objects produced from them. -// This is intended to be used, for example, to print diagnostics with -// contextual information. -// -// The returned map and all of the objects it refers to directly or indirectly -// must not be modified. -func (p *Parser) Files() map[string]*hcl.File { - return p.files -} diff --git a/vendor/github.com/hashicorp/hcl/v2/json/ast.go b/vendor/github.com/hashicorp/hcl/v2/json/ast.go deleted file mode 100644 index 9c580ca3471..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/json/ast.go +++ /dev/null @@ -1,121 +0,0 @@ -package json - -import ( - "math/big" - - "github.com/hashicorp/hcl/v2" -) - -type node interface { - Range() hcl.Range - StartRange() hcl.Range -} - -type objectVal struct { - Attrs []*objectAttr - SrcRange hcl.Range // range of the entire object, brace-to-brace - OpenRange hcl.Range // range of the opening brace - CloseRange hcl.Range // range of the closing brace -} - -func (n *objectVal) Range() hcl.Range { - return n.SrcRange -} - -func (n *objectVal) StartRange() hcl.Range { - return n.OpenRange -} - -type objectAttr struct { - Name string - Value node - NameRange hcl.Range // range of the name string -} - -func (n *objectAttr) Range() hcl.Range { - return n.NameRange -} - -func (n *objectAttr) StartRange() hcl.Range { - return n.NameRange -} - -type arrayVal struct { - Values []node - SrcRange hcl.Range // range of the entire object, bracket-to-bracket - OpenRange hcl.Range // range of the opening bracket -} - -func (n *arrayVal) Range() hcl.Range { - return n.SrcRange -} - -func (n *arrayVal) StartRange() hcl.Range { - return n.OpenRange -} - -type booleanVal struct { - Value bool - SrcRange hcl.Range -} - -func (n *booleanVal) Range() hcl.Range { - return n.SrcRange -} - -func (n *booleanVal) StartRange() hcl.Range { - return n.SrcRange -} - -type numberVal struct { - Value *big.Float - SrcRange hcl.Range -} - -func (n *numberVal) Range() hcl.Range { - return n.SrcRange -} - -func (n *numberVal) StartRange() hcl.Range { - return n.SrcRange -} - -type stringVal struct { - Value string - SrcRange hcl.Range -} - -func (n *stringVal) Range() hcl.Range { - return n.SrcRange -} - -func (n *stringVal) StartRange() hcl.Range { - return n.SrcRange -} - -type nullVal struct { - SrcRange hcl.Range -} - -func (n *nullVal) Range() hcl.Range { - return n.SrcRange -} - -func (n *nullVal) StartRange() hcl.Range { - return n.SrcRange -} - -// invalidVal is used as a placeholder where a value is needed for a valid -// parse tree but the input was invalid enough to prevent one from being -// created. -type invalidVal struct { - SrcRange hcl.Range -} - -func (n invalidVal) Range() hcl.Range { - return n.SrcRange -} - -func (n invalidVal) StartRange() hcl.Range { - return n.SrcRange -} diff --git a/vendor/github.com/hashicorp/hcl/v2/json/didyoumean.go b/vendor/github.com/hashicorp/hcl/v2/json/didyoumean.go deleted file mode 100644 index fbdd8bff509..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/json/didyoumean.go +++ /dev/null @@ -1,33 +0,0 @@ -package json - -import ( - "github.com/agext/levenshtein" -) - -var keywords = []string{"false", "true", "null"} - -// keywordSuggestion tries to find a valid JSON keyword that is close to the -// given string and returns it if found. If no keyword is close enough, returns -// the empty string. -func keywordSuggestion(given string) string { - return nameSuggestion(given, keywords) -} - -// nameSuggestion tries to find a name from the given slice of suggested names -// that is close to the given name and returns it if found. If no suggestion -// is close enough, returns the empty string. -// -// The suggestions are tried in order, so earlier suggestions take precedence -// if the given string is similar to two or more suggestions. -// -// This function is intended to be used with a relatively-small number of -// suggestions. It's not optimized for hundreds or thousands of them. -func nameSuggestion(given string, suggestions []string) string { - for _, suggestion := range suggestions { - dist := levenshtein.Distance(given, suggestion, nil) - if dist < 3 { // threshold determined experimentally - return suggestion - } - } - return "" -} diff --git a/vendor/github.com/hashicorp/hcl/v2/json/doc.go b/vendor/github.com/hashicorp/hcl/v2/json/doc.go deleted file mode 100644 index 84d731939fc..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/json/doc.go +++ /dev/null @@ -1,12 +0,0 @@ -// Package json is the JSON parser for HCL. It parses JSON files and returns -// implementations of the core HCL structural interfaces in terms of the -// JSON data inside. -// -// This is not a generic JSON parser. Instead, it deals with the mapping from -// the JSON information model to the HCL information model, using a number -// of hard-coded structural conventions. -// -// In most cases applications will not import this package directly, but will -// instead access its functionality indirectly through functions in the main -// "hcl" package and in the "hclparse" package. -package json diff --git a/vendor/github.com/hashicorp/hcl/v2/json/navigation.go b/vendor/github.com/hashicorp/hcl/v2/json/navigation.go deleted file mode 100644 index bc8a97f749d..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/json/navigation.go +++ /dev/null @@ -1,70 +0,0 @@ -package json - -import ( - "fmt" - "strings" -) - -type navigation struct { - root node -} - -// Implementation of hcled.ContextString -func (n navigation) ContextString(offset int) string { - steps := navigationStepsRev(n.root, offset) - if steps == nil { - return "" - } - - // We built our slice backwards, so we'll reverse it in-place now. - half := len(steps) / 2 // integer division - for i := 0; i < half; i++ { - steps[i], steps[len(steps)-1-i] = steps[len(steps)-1-i], steps[i] - } - - ret := strings.Join(steps, "") - if len(ret) > 0 && ret[0] == '.' { - ret = ret[1:] - } - return ret -} - -func navigationStepsRev(v node, offset int) []string { - switch tv := v.(type) { - case *objectVal: - // Do any of our properties have an object that contains the target - // offset? - for _, attr := range tv.Attrs { - k := attr.Name - av := attr.Value - - switch av.(type) { - case *objectVal, *arrayVal: - // okay - default: - continue - } - - if av.Range().ContainsOffset(offset) { - return append(navigationStepsRev(av, offset), "."+k) - } - } - case *arrayVal: - // Do any of our elements contain the target offset? - for i, elem := range tv.Values { - - switch elem.(type) { - case *objectVal, *arrayVal: - // okay - default: - continue - } - - if elem.Range().ContainsOffset(offset) { - return append(navigationStepsRev(elem, offset), fmt.Sprintf("[%d]", i)) - } - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/hcl/v2/json/parser.go b/vendor/github.com/hashicorp/hcl/v2/json/parser.go deleted file mode 100644 index 7a54c51b6e1..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/json/parser.go +++ /dev/null @@ -1,496 +0,0 @@ -package json - -import ( - "encoding/json" - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -func parseFileContent(buf []byte, filename string) (node, hcl.Diagnostics) { - tokens := scan(buf, pos{ - Filename: filename, - Pos: hcl.Pos{ - Byte: 0, - Line: 1, - Column: 1, - }, - }) - p := newPeeker(tokens) - node, diags := parseValue(p) - if len(diags) == 0 && p.Peek().Type != tokenEOF { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Extraneous data after value", - Detail: "Extra characters appear after the JSON value.", - Subject: p.Peek().Range.Ptr(), - }) - } - return node, diags -} - -func parseValue(p *peeker) (node, hcl.Diagnostics) { - tok := p.Peek() - - wrapInvalid := func(n node, diags hcl.Diagnostics) (node, hcl.Diagnostics) { - if n != nil { - return n, diags - } - return invalidVal{tok.Range}, diags - } - - switch tok.Type { - case tokenBraceO: - return wrapInvalid(parseObject(p)) - case tokenBrackO: - return wrapInvalid(parseArray(p)) - case tokenNumber: - return wrapInvalid(parseNumber(p)) - case tokenString: - return wrapInvalid(parseString(p)) - case tokenKeyword: - return wrapInvalid(parseKeyword(p)) - case tokenBraceC: - return wrapInvalid(nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Missing JSON value", - Detail: "A JSON value must start with a brace, a bracket, a number, a string, or a keyword.", - Subject: &tok.Range, - }, - }) - case tokenBrackC: - return wrapInvalid(nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Missing array element value", - Detail: "A JSON value must start with a brace, a bracket, a number, a string, or a keyword.", - Subject: &tok.Range, - }, - }) - case tokenEOF: - return wrapInvalid(nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Missing value", - Detail: "The JSON data ends prematurely.", - Subject: &tok.Range, - }, - }) - default: - return wrapInvalid(nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Invalid start of value", - Detail: "A JSON value must start with a brace, a bracket, a number, a string, or a keyword.", - Subject: &tok.Range, - }, - }) - } -} - -func tokenCanStartValue(tok token) bool { - switch tok.Type { - case tokenBraceO, tokenBrackO, tokenNumber, tokenString, tokenKeyword: - return true - default: - return false - } -} - -func parseObject(p *peeker) (node, hcl.Diagnostics) { - var diags hcl.Diagnostics - - open := p.Read() - attrs := []*objectAttr{} - - // recover is used to shift the peeker to what seems to be the end of - // our object, so that when we encounter an error we leave the peeker - // at a reasonable point in the token stream to continue parsing. - recover := func(tok token) { - open := 1 - for { - switch tok.Type { - case tokenBraceO: - open++ - case tokenBraceC: - open-- - if open <= 1 { - return - } - case tokenEOF: - // Ran out of source before we were able to recover, - // so we'll bail here and let the caller deal with it. - return - } - tok = p.Read() - } - } - -Token: - for { - if p.Peek().Type == tokenBraceC { - break Token - } - - keyNode, keyDiags := parseValue(p) - diags = diags.Extend(keyDiags) - if keyNode == nil { - return nil, diags - } - - keyStrNode, ok := keyNode.(*stringVal) - if !ok { - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid object property name", - Detail: "A JSON object property name must be a string", - Subject: keyNode.StartRange().Ptr(), - }) - } - - key := keyStrNode.Value - - colon := p.Read() - if colon.Type != tokenColon { - recover(colon) - - if colon.Type == tokenBraceC || colon.Type == tokenComma { - // Catch common mistake of using braces instead of brackets - // for an object. - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing object value", - Detail: "A JSON object attribute must have a value, introduced by a colon.", - Subject: &colon.Range, - }) - } - - if colon.Type == tokenEquals { - // Possible confusion with native HCL syntax. - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing property value colon", - Detail: "JSON uses a colon as its name/value delimiter, not an equals sign.", - Subject: &colon.Range, - }) - } - - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing property value colon", - Detail: "A colon must appear between an object property's name and its value.", - Subject: &colon.Range, - }) - } - - valNode, valDiags := parseValue(p) - diags = diags.Extend(valDiags) - if valNode == nil { - return nil, diags - } - - attrs = append(attrs, &objectAttr{ - Name: key, - Value: valNode, - NameRange: keyStrNode.SrcRange, - }) - - switch p.Peek().Type { - case tokenComma: - comma := p.Read() - if p.Peek().Type == tokenBraceC { - // Special error message for this common mistake - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Trailing comma in object", - Detail: "JSON does not permit a trailing comma after the final property in an object.", - Subject: &comma.Range, - }) - } - continue Token - case tokenEOF: - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unclosed object", - Detail: "No closing brace was found for this JSON object.", - Subject: &open.Range, - }) - case tokenBrackC: - // Consume the bracket anyway, so that we don't return with the peeker - // at a strange place. - p.Read() - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Mismatched braces", - Detail: "A JSON object must be closed with a brace, not a bracket.", - Subject: p.Peek().Range.Ptr(), - }) - case tokenBraceC: - break Token - default: - recover(p.Read()) - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing attribute seperator comma", - Detail: "A comma must appear between each property definition in an object.", - Subject: p.Peek().Range.Ptr(), - }) - } - - } - - close := p.Read() - return &objectVal{ - Attrs: attrs, - SrcRange: hcl.RangeBetween(open.Range, close.Range), - OpenRange: open.Range, - CloseRange: close.Range, - }, diags -} - -func parseArray(p *peeker) (node, hcl.Diagnostics) { - var diags hcl.Diagnostics - - open := p.Read() - vals := []node{} - - // recover is used to shift the peeker to what seems to be the end of - // our array, so that when we encounter an error we leave the peeker - // at a reasonable point in the token stream to continue parsing. - recover := func(tok token) { - open := 1 - for { - switch tok.Type { - case tokenBrackO: - open++ - case tokenBrackC: - open-- - if open <= 1 { - return - } - case tokenEOF: - // Ran out of source before we were able to recover, - // so we'll bail here and let the caller deal with it. - return - } - tok = p.Read() - } - } - -Token: - for { - if p.Peek().Type == tokenBrackC { - break Token - } - - valNode, valDiags := parseValue(p) - diags = diags.Extend(valDiags) - if valNode == nil { - return nil, diags - } - - vals = append(vals, valNode) - - switch p.Peek().Type { - case tokenComma: - comma := p.Read() - if p.Peek().Type == tokenBrackC { - // Special error message for this common mistake - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Trailing comma in array", - Detail: "JSON does not permit a trailing comma after the final value in an array.", - Subject: &comma.Range, - }) - } - continue Token - case tokenColon: - recover(p.Read()) - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid array value", - Detail: "A colon is not used to introduce values in a JSON array.", - Subject: p.Peek().Range.Ptr(), - }) - case tokenEOF: - recover(p.Read()) - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unclosed object", - Detail: "No closing bracket was found for this JSON array.", - Subject: &open.Range, - }) - case tokenBraceC: - recover(p.Read()) - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Mismatched brackets", - Detail: "A JSON array must be closed with a bracket, not a brace.", - Subject: p.Peek().Range.Ptr(), - }) - case tokenBrackC: - break Token - default: - recover(p.Read()) - return nil, diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing attribute seperator comma", - Detail: "A comma must appear between each value in an array.", - Subject: p.Peek().Range.Ptr(), - }) - } - - } - - close := p.Read() - return &arrayVal{ - Values: vals, - SrcRange: hcl.RangeBetween(open.Range, close.Range), - OpenRange: open.Range, - }, diags -} - -func parseNumber(p *peeker) (node, hcl.Diagnostics) { - tok := p.Read() - - // Use encoding/json to validate the number syntax. - // TODO: Do this more directly to produce better diagnostics. - var num json.Number - err := json.Unmarshal(tok.Bytes, &num) - if err != nil { - return nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Invalid JSON number", - Detail: fmt.Sprintf("There is a syntax error in the given JSON number."), - Subject: &tok.Range, - }, - } - } - - // We want to guarantee that we parse numbers the same way as cty (and thus - // native syntax HCL) would here, so we'll use the cty parser even though - // in most other cases we don't actually introduce cty concepts until - // decoding time. We'll unwrap the parsed float immediately afterwards, so - // the cty value is just a temporary helper. - nv, err := cty.ParseNumberVal(string(num)) - if err != nil { - // Should never happen if above passed, since JSON numbers are a subset - // of what cty can parse... - return nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Invalid JSON number", - Detail: fmt.Sprintf("There is a syntax error in the given JSON number."), - Subject: &tok.Range, - }, - } - } - - return &numberVal{ - Value: nv.AsBigFloat(), - SrcRange: tok.Range, - }, nil -} - -func parseString(p *peeker) (node, hcl.Diagnostics) { - tok := p.Read() - var str string - err := json.Unmarshal(tok.Bytes, &str) - - if err != nil { - var errRange hcl.Range - if serr, ok := err.(*json.SyntaxError); ok { - errOfs := serr.Offset - errPos := tok.Range.Start - errPos.Byte += int(errOfs) - - // TODO: Use the byte offset to properly count unicode - // characters for the column, and mark the whole of the - // character that was wrong as part of our range. - errPos.Column += int(errOfs) - - errEndPos := errPos - errEndPos.Byte++ - errEndPos.Column++ - - errRange = hcl.Range{ - Filename: tok.Range.Filename, - Start: errPos, - End: errEndPos, - } - } else { - errRange = tok.Range - } - - var contextRange *hcl.Range - if errRange != tok.Range { - contextRange = &tok.Range - } - - // FIXME: Eventually we should parse strings directly here so - // we can produce a more useful error message in the face fo things - // such as invalid escapes, etc. - return nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Invalid JSON string", - Detail: fmt.Sprintf("There is a syntax error in the given JSON string."), - Subject: &errRange, - Context: contextRange, - }, - } - } - - return &stringVal{ - Value: str, - SrcRange: tok.Range, - }, nil -} - -func parseKeyword(p *peeker) (node, hcl.Diagnostics) { - tok := p.Read() - s := string(tok.Bytes) - - switch s { - case "true": - return &booleanVal{ - Value: true, - SrcRange: tok.Range, - }, nil - case "false": - return &booleanVal{ - Value: false, - SrcRange: tok.Range, - }, nil - case "null": - return &nullVal{ - SrcRange: tok.Range, - }, nil - case "undefined", "NaN", "Infinity": - return nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Invalid JSON keyword", - Detail: fmt.Sprintf("The JavaScript identifier %q cannot be used in JSON.", s), - Subject: &tok.Range, - }, - } - default: - var dym string - if suggest := keywordSuggestion(s); suggest != "" { - dym = fmt.Sprintf(" Did you mean %q?", suggest) - } - - return nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Invalid JSON keyword", - Detail: fmt.Sprintf("%q is not a valid JSON keyword.%s", s, dym), - Subject: &tok.Range, - }, - } - } -} diff --git a/vendor/github.com/hashicorp/hcl/v2/json/peeker.go b/vendor/github.com/hashicorp/hcl/v2/json/peeker.go deleted file mode 100644 index fc7bbf58274..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/json/peeker.go +++ /dev/null @@ -1,25 +0,0 @@ -package json - -type peeker struct { - tokens []token - pos int -} - -func newPeeker(tokens []token) *peeker { - return &peeker{ - tokens: tokens, - pos: 0, - } -} - -func (p *peeker) Peek() token { - return p.tokens[p.pos] -} - -func (p *peeker) Read() token { - ret := p.tokens[p.pos] - if ret.Type != tokenEOF { - p.pos++ - } - return ret -} diff --git a/vendor/github.com/hashicorp/hcl/v2/json/public.go b/vendor/github.com/hashicorp/hcl/v2/json/public.go deleted file mode 100644 index 8dc4a36afe6..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/json/public.go +++ /dev/null @@ -1,94 +0,0 @@ -package json - -import ( - "fmt" - "io/ioutil" - "os" - - "github.com/hashicorp/hcl/v2" -) - -// Parse attempts to parse the given buffer as JSON and, if successful, returns -// a hcl.File for the HCL configuration represented by it. -// -// This is not a generic JSON parser. Instead, it deals only with the profile -// of JSON used to express HCL configuration. -// -// The returned file is valid only if the returned diagnostics returns false -// from its HasErrors method. If HasErrors returns true, the file represents -// the subset of data that was able to be parsed, which may be none. -func Parse(src []byte, filename string) (*hcl.File, hcl.Diagnostics) { - rootNode, diags := parseFileContent(src, filename) - - switch rootNode.(type) { - case *objectVal, *arrayVal: - // okay - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Root value must be object", - Detail: "The root value in a JSON-based configuration must be either a JSON object or a JSON array of objects.", - Subject: rootNode.StartRange().Ptr(), - }) - - // Since we've already produced an error message for this being - // invalid, we'll return an empty placeholder here so that trying to - // extract content from our root body won't produce a redundant - // error saying the same thing again in more general terms. - fakePos := hcl.Pos{ - Byte: 0, - Line: 1, - Column: 1, - } - fakeRange := hcl.Range{ - Filename: filename, - Start: fakePos, - End: fakePos, - } - rootNode = &objectVal{ - Attrs: []*objectAttr{}, - SrcRange: fakeRange, - OpenRange: fakeRange, - } - } - - file := &hcl.File{ - Body: &body{ - val: rootNode, - }, - Bytes: src, - Nav: navigation{rootNode}, - } - return file, diags -} - -// ParseFile is a convenience wrapper around Parse that first attempts to load -// data from the given filename, passing the result to Parse if successful. -// -// If the file cannot be read, an error diagnostic with nil context is returned. -func ParseFile(filename string) (*hcl.File, hcl.Diagnostics) { - f, err := os.Open(filename) - if err != nil { - return nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Failed to open file", - Detail: fmt.Sprintf("The file %q could not be opened.", filename), - }, - } - } - defer f.Close() - - src, err := ioutil.ReadAll(f) - if err != nil { - return nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Failed to read file", - Detail: fmt.Sprintf("The file %q was opened, but an error occured while reading it.", filename), - }, - } - } - - return Parse(src, filename) -} diff --git a/vendor/github.com/hashicorp/hcl/v2/json/scanner.go b/vendor/github.com/hashicorp/hcl/v2/json/scanner.go deleted file mode 100644 index 912eabce23f..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/json/scanner.go +++ /dev/null @@ -1,297 +0,0 @@ -package json - -import ( - "fmt" - - "github.com/apparentlymart/go-textseg/textseg" - "github.com/hashicorp/hcl/v2" -) - -//go:generate stringer -type tokenType scanner.go -type tokenType rune - -const ( - tokenBraceO tokenType = '{' - tokenBraceC tokenType = '}' - tokenBrackO tokenType = '[' - tokenBrackC tokenType = ']' - tokenComma tokenType = ',' - tokenColon tokenType = ':' - tokenKeyword tokenType = 'K' - tokenString tokenType = 'S' - tokenNumber tokenType = 'N' - tokenEOF tokenType = '␄' - tokenInvalid tokenType = 0 - tokenEquals tokenType = '=' // used only for reminding the user of JSON syntax -) - -type token struct { - Type tokenType - Bytes []byte - Range hcl.Range -} - -// scan returns the primary tokens for the given JSON buffer in sequence. -// -// The responsibility of this pass is to just mark the slices of the buffer -// as being of various types. It is lax in how it interprets the multi-byte -// token types keyword, string and number, preferring to capture erroneous -// extra bytes that we presume the user intended to be part of the token -// so that we can generate more helpful diagnostics in the parser. -func scan(buf []byte, start pos) []token { - var tokens []token - p := start - for { - if len(buf) == 0 { - tokens = append(tokens, token{ - Type: tokenEOF, - Bytes: nil, - Range: posRange(p, p), - }) - return tokens - } - - buf, p = skipWhitespace(buf, p) - - if len(buf) == 0 { - tokens = append(tokens, token{ - Type: tokenEOF, - Bytes: nil, - Range: posRange(p, p), - }) - return tokens - } - - start = p - - first := buf[0] - switch { - case first == '{' || first == '}' || first == '[' || first == ']' || first == ',' || first == ':' || first == '=': - p.Pos.Column++ - p.Pos.Byte++ - tokens = append(tokens, token{ - Type: tokenType(first), - Bytes: buf[0:1], - Range: posRange(start, p), - }) - buf = buf[1:] - case first == '"': - var tokBuf []byte - tokBuf, buf, p = scanString(buf, p) - tokens = append(tokens, token{ - Type: tokenString, - Bytes: tokBuf, - Range: posRange(start, p), - }) - case byteCanStartNumber(first): - var tokBuf []byte - tokBuf, buf, p = scanNumber(buf, p) - tokens = append(tokens, token{ - Type: tokenNumber, - Bytes: tokBuf, - Range: posRange(start, p), - }) - case byteCanStartKeyword(first): - var tokBuf []byte - tokBuf, buf, p = scanKeyword(buf, p) - tokens = append(tokens, token{ - Type: tokenKeyword, - Bytes: tokBuf, - Range: posRange(start, p), - }) - default: - tokens = append(tokens, token{ - Type: tokenInvalid, - Bytes: buf[:1], - Range: start.Range(1, 1), - }) - // If we've encountered an invalid then we might as well stop - // scanning since the parser won't proceed beyond this point. - return tokens - } - } -} - -func byteCanStartNumber(b byte) bool { - switch b { - // We are slightly more tolerant than JSON requires here since we - // expect the parser will make a stricter interpretation of the - // number bytes, but we specifically don't allow 'e' or 'E' here - // since we want the scanner to treat that as the start of an - // invalid keyword instead, to produce more intelligible error messages. - case '-', '+', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - return true - default: - return false - } -} - -func scanNumber(buf []byte, start pos) ([]byte, []byte, pos) { - // The scanner doesn't check that the sequence of digit-ish bytes is - // in a valid order. The parser must do this when decoding a number - // token. - var i int - p := start -Byte: - for i = 0; i < len(buf); i++ { - switch buf[i] { - case '-', '+', '.', 'e', 'E', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - p.Pos.Byte++ - p.Pos.Column++ - default: - break Byte - } - } - return buf[:i], buf[i:], p -} - -func byteCanStartKeyword(b byte) bool { - switch { - // We allow any sequence of alphabetical characters here, even though - // JSON is more constrained, so that we can collect what we presume - // the user intended to be a single keyword and then check its validity - // in the parser, where we can generate better diagnostics. - // So e.g. we want to be able to say: - // unrecognized keyword "True". Did you mean "true"? - case isAlphabetical(b): - return true - default: - return false - } -} - -func scanKeyword(buf []byte, start pos) ([]byte, []byte, pos) { - var i int - p := start -Byte: - for i = 0; i < len(buf); i++ { - b := buf[i] - switch { - case isAlphabetical(b) || b == '_': - p.Pos.Byte++ - p.Pos.Column++ - default: - break Byte - } - } - return buf[:i], buf[i:], p -} - -func scanString(buf []byte, start pos) ([]byte, []byte, pos) { - // The scanner doesn't validate correct use of escapes, etc. It pays - // attention to escapes only for the purpose of identifying the closing - // quote character. It's the parser's responsibility to do proper - // validation. - // - // The scanner also doesn't specifically detect unterminated string - // literals, though they can be identified in the parser by checking if - // the final byte in a string token is the double-quote character. - - // Skip the opening quote symbol - i := 1 - p := start - p.Pos.Byte++ - p.Pos.Column++ - escaping := false -Byte: - for i < len(buf) { - b := buf[i] - - switch { - case b == '\\': - escaping = !escaping - p.Pos.Byte++ - p.Pos.Column++ - i++ - case b == '"': - p.Pos.Byte++ - p.Pos.Column++ - i++ - if !escaping { - break Byte - } - escaping = false - case b < 32: - break Byte - default: - // Advance by one grapheme cluster, so that we consider each - // grapheme to be a "column". - // Ignoring error because this scanner cannot produce errors. - advance, _, _ := textseg.ScanGraphemeClusters(buf[i:], true) - - p.Pos.Byte += advance - p.Pos.Column++ - i += advance - - escaping = false - } - } - return buf[:i], buf[i:], p -} - -func skipWhitespace(buf []byte, start pos) ([]byte, pos) { - var i int - p := start -Byte: - for i = 0; i < len(buf); i++ { - switch buf[i] { - case ' ': - p.Pos.Byte++ - p.Pos.Column++ - case '\n': - p.Pos.Byte++ - p.Pos.Column = 1 - p.Pos.Line++ - case '\r': - // For the purpose of line/column counting we consider a - // carriage return to take up no space, assuming that it will - // be paired up with a newline (on Windows, for example) that - // will account for both of them. - p.Pos.Byte++ - case '\t': - // We arbitrarily count a tab as if it were two spaces, because - // we need to choose _some_ number here. This means any system - // that renders code on-screen with markers must itself treat - // tabs as a pair of spaces for rendering purposes, or instead - // use the byte offset and back into its own column position. - p.Pos.Byte++ - p.Pos.Column += 2 - default: - break Byte - } - } - return buf[i:], p -} - -type pos struct { - Filename string - Pos hcl.Pos -} - -func (p *pos) Range(byteLen, charLen int) hcl.Range { - start := p.Pos - end := p.Pos - end.Byte += byteLen - end.Column += charLen - return hcl.Range{ - Filename: p.Filename, - Start: start, - End: end, - } -} - -func posRange(start, end pos) hcl.Range { - return hcl.Range{ - Filename: start.Filename, - Start: start.Pos, - End: end.Pos, - } -} - -func (t token) GoString() string { - return fmt.Sprintf("json.token{json.%s, []byte(%q), %#v}", t.Type, t.Bytes, t.Range) -} - -func isAlphabetical(b byte) bool { - return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') -} diff --git a/vendor/github.com/hashicorp/hcl/v2/json/spec.md b/vendor/github.com/hashicorp/hcl/v2/json/spec.md deleted file mode 100644 index dac5729d48f..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/json/spec.md +++ /dev/null @@ -1,405 +0,0 @@ -# HCL JSON Syntax Specification - -This is the specification for the JSON serialization for hcl. HCL is a system -for defining configuration languages for applications. The HCL information -model is designed to support multiple concrete syntaxes for configuration, -and this JSON-based format complements [the native syntax](../hclsyntax/spec.md) -by being easy to machine-generate, whereas the native syntax is oriented -towards human authoring and maintenance - -This syntax is defined in terms of JSON as defined in -[RFC7159](https://tools.ietf.org/html/rfc7159). As such it inherits the JSON -grammar as-is, and merely defines a specific methodology for interpreting -JSON constructs into HCL structural elements and expressions. - -This mapping is defined such that valid JSON-serialized HCL input can be -_produced_ using standard JSON implementations in various programming languages. -_Parsing_ such JSON has some additional constraints not beyond what is normally -supported by JSON parsers, so a specialized parser may be required that -is able to: - -- Preserve the relative ordering of properties defined in an object. -- Preserve multiple definitions of the same property name. -- Preserve numeric values to the precision required by the number type - in [the HCL syntax-agnostic information model](../spec.md). -- Retain source location information for parsed tokens/constructs in order - to produce good error messages. - -## Structural Elements - -[The HCL syntax-agnostic information model](../spec.md) defines a _body_ as an -abstract container for attribute definitions and child blocks. A body is -represented in JSON as either a single JSON object or a JSON array of objects. - -Body processing is in terms of JSON object properties, visited in the order -they appear in the input. Where a body is represented by a single JSON object, -the properties of that object are visited in order. Where a body is -represented by a JSON array, each of its elements are visited in order and -each element has its properties visited in order. If any element of the array -is not a JSON object then the input is erroneous. - -When a body is being processed in the _dynamic attributes_ mode, the allowance -of a JSON array in the previous paragraph does not apply and instead a single -JSON object is always required. - -As defined in the language-agnostic model, body processing is in terms -of a schema which provides context for interpreting the body's content. For -JSON bodies, the schema is crucial to allow differentiation of attribute -definitions and block definitions, both of which are represented via object -properties. - -The special property name `"//"`, when used in an object representing a HCL -body, is parsed and ignored. A property with this name can be used to -include human-readable comments. (This special property name is _not_ -processed in this way for any _other_ HCL constructs that are represented as -JSON objects.) - -### Attributes - -Where the given schema describes an attribute with a given name, the object -property with the matching name — if present — serves as the attribute's -definition. - -When a body is being processed in the _dynamic attributes_ mode, each object -property serves as an attribute definition for the attribute whose name -matches the property name. - -The value of an attribute definition property is interpreted as an _expression_, -as described in a later section. - -Given a schema that calls for an attribute named "foo", a JSON object like -the following provides a definition for that attribute: - -```json -{ - "foo": "bar baz" -} -``` - -### Blocks - -Where the given schema describes a block with a given type name, each object -property with the matching name serves as a definition of zero or more blocks -of that type. - -Processing of child blocks is in terms of nested JSON objects and arrays. -If the schema defines one or more _labels_ for the block type, a nested JSON -object or JSON array of objects is required for each labelling level. These -are flattened to a single ordered sequence of object properties using the -same algorithm as for body content as defined above. Each object property -serves as a label value at the corresponding level. - -After any labelling levels, the next nested value is either a JSON object -representing a single block body, or a JSON array of JSON objects that each -represent a single block body. Use of an array accommodates the definition -of multiple blocks that have identical type and labels. - -Given a schema that calls for a block type named "foo" with no labels, the -following JSON objects are all valid definitions of zero or more blocks of this -type: - -```json -{ - "foo": { - "child_attr": "baz" - } -} -``` - -```json -{ - "foo": [ - { - "child_attr": "baz" - }, - { - "child_attr": "boz" - } - ] -} -``` - -```json -{ - "foo": [] -} -``` - -The first of these defines a single child block of type "foo". The second -defines _two_ such blocks. The final example shows a degenerate definition -of zero blocks, though generators should prefer to omit the property entirely -in this scenario. - -Given a schema that calls for a block type named "foo" with _two_ labels, the -extra label levels must be represented as objects or arrays of objects as in -the following examples: - -```json -{ - "foo": { - "bar": { - "baz": { - "child_attr": "baz" - }, - "boz": { - "child_attr": "baz" - } - }, - "boz": { - "baz": { - "child_attr": "baz" - } - } - } -} -``` - -```json -{ - "foo": { - "bar": { - "baz": { - "child_attr": "baz" - }, - "boz": { - "child_attr": "baz" - } - }, - "boz": { - "baz": [ - { - "child_attr": "baz" - }, - { - "child_attr": "boz" - } - ] - } - } -} -``` - -```json -{ - "foo": [ - { - "bar": { - "baz": { - "child_attr": "baz" - }, - "boz": { - "child_attr": "baz" - } - } - }, - { - "bar": { - "baz": [ - { - "child_attr": "baz" - }, - { - "child_attr": "boz" - } - ] - } - } - ] -} -``` - -```json -{ - "foo": { - "bar": { - "baz": { - "child_attr": "baz" - }, - "boz": { - "child_attr": "baz" - } - }, - "bar": { - "baz": [ - { - "child_attr": "baz" - }, - { - "child_attr": "boz" - } - ] - } - } -} -``` - -Arrays can be introduced at either the label definition or block body -definition levels to define multiple definitions of the same block type -or labels while preserving order. - -A JSON HCL parser _must_ support duplicate definitions of the same property -name within a single object, preserving all of them and the relative ordering -between them. The array-based forms are also required so that JSON HCL -configurations can be produced with JSON producing libraries that are not -able to preserve property definition order and multiple definitions of -the same property. - -## Expressions - -JSON lacks a native expression syntax, so the HCL JSON syntax instead defines -a mapping for each of the JSON value types, including a special mapping for -strings that allows optional use of arbitrary expressions. - -### Objects - -When interpreted as an expression, a JSON object represents a value of a HCL -object type. - -Each property of the JSON object represents an attribute of the HCL object type. -The property name string given in the JSON input is interpreted as a string -expression as described below, and its result is converted to string as defined -by the syntax-agnostic information model. If such a conversion is not possible, -an error is produced and evaluation fails. - -An instance of the constructed object type is then created, whose values -are interpreted by again recursively applying the mapping rules defined in -this section to each of the property values. - -If any evaluated property name strings produce null values, an error is -produced and evaluation fails. If any produce _unknown_ values, the _entire -object's_ result is an unknown value of the dynamic pseudo-type, signalling -that the type of the object cannot be determined. - -It is an error to define the same property name multiple times within a single -JSON object interpreted as an expression. In full expression mode, this -constraint applies to the name expression results after conversion to string, -rather than the raw string that may contain interpolation expressions. - -### Arrays - -When interpreted as an expression, a JSON array represents a value of a HCL -tuple type. - -Each element of the JSON array represents an element of the HCL tuple type. -The tuple type is constructed by enumerating the JSON array elements, creating -for each an element whose type is the result of recursively applying the -expression mapping rules. Correspondence is preserved between the array element -indices and the tuple element indices. - -An instance of the constructed tuple type is then created, whose values are -interpreted by again recursively applying the mapping rules defined in this -section. - -### Numbers - -When interpreted as an expression, a JSON number represents a HCL number value. - -HCL numbers are arbitrary-precision decimal values, so a JSON HCL parser must -be able to translate exactly the value given to a number of corresponding -precision, within the constraints set by the HCL syntax-agnostic information -model. - -In practice, off-the-shelf JSON serializers often do not support customizing the -processing of numbers, and instead force processing as 32-bit or 64-bit -floating point values. - -A _producer_ of JSON HCL that uses such a serializer can provide numeric values -as JSON strings where they have precision too great for representation in the -serializer's chosen numeric type in situations where the result will be -converted to number (using the standard conversion rules) by a calling -application. - -Alternatively, for expressions that are evaluated in full expression mode an -embedded template interpolation can be used to faithfully represent a number, -such as `"${1e150}"`, which will then be evaluated by the underlying HCL native -syntax expression evaluator. - -### Boolean Values - -The JSON boolean values `true` and `false`, when interpreted as expressions, -represent the corresponding HCL boolean values. - -### The Null Value - -The JSON value `null`, when interpreted as an expression, represents a -HCL null value of the dynamic pseudo-type. - -### Strings - -When interpreted as an expression, a JSON string may be interpreted in one of -two ways depending on the evaluation mode. - -If evaluating in literal-only mode (as defined by the syntax-agnostic -information model) the literal string is intepreted directly as a HCL string -value, by directly using the exact sequence of unicode characters represented. -Template interpolations and directives MUST NOT be processed in this mode, -allowing any characters that appear as introduction sequences to pass through -literally: - -```json -"Hello world! Template sequences like ${ are not intepreted here." -``` - -When evaluating in full expression mode (again, as defined by the syntax- -agnostic information model) the literal string is instead interpreted as a -_standalone template_ in the HCL Native Syntax. The expression evaluation -result is then the direct result of evaluating that template with the current -variable scope and function table. - -```json -"Hello, ${name}! Template sequences are interpreted in full expression mode." -``` - -In particular the _Template Interpolation Unwrapping_ requirement from the -HCL native syntax specification must be implemented, allowing the use of -single-interpolation templates to represent expressions that would not -otherwise be representable in JSON, such as the following example where -the result must be a number, rather than a string representation of a number: - -```json -"${ a + b }" -``` - -## Static Analysis - -The HCL static analysis operations are implemented for JSON values that -represent expressions, as described in the following sections. - -Due to the limited expressive power of the JSON syntax alone, use of these -static analyses functions rather than normal expression evaluation is used -as additional context for how a JSON value is to be interpreted, which means -that static analyses can result in a different interpretation of a given -expression than normal evaluation. - -### Static List - -An expression interpreted as a static list must be a JSON array. Each of the -values in the array is interpreted as an expression and returned. - -### Static Map - -An expression interpreted as a static map must be a JSON object. Each of the -key/value pairs in the object is presented as a pair of expressions. Since -object property names are always strings, evaluating the key expression with -a non-`nil` evaluation context will evaluate any template sequences given -in the property name. - -### Static Call - -An expression interpreted as a static call must be a string. The content of -the string is interpreted as a native syntax expression (not a _template_, -unlike normal evaluation) and then the static call analysis is delegated to -that expression. - -If the original expression is not a string or its contents cannot be parsed -as a native syntax expression then static call analysis is not supported. - -### Static Traversal - -An expression interpreted as a static traversal must be a string. The content -of the string is interpreted as a native syntax expression (not a _template_, -unlike normal evaluation) and then static traversal analysis is delegated -to that expression. - -If the original expression is not a string or its contents cannot be parsed -as a native syntax expression then static call analysis is not supported. diff --git a/vendor/github.com/hashicorp/hcl/v2/json/structure.go b/vendor/github.com/hashicorp/hcl/v2/json/structure.go deleted file mode 100644 index 76c9d739996..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/json/structure.go +++ /dev/null @@ -1,637 +0,0 @@ -package json - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// body is the implementation of "Body" used for files processed with the JSON -// parser. -type body struct { - val node - - // If non-nil, the keys of this map cause the corresponding attributes to - // be treated as non-existing. This is used when Body.PartialContent is - // called, to produce the "remaining content" Body. - hiddenAttrs map[string]struct{} -} - -// expression is the implementation of "Expression" used for files processed -// with the JSON parser. -type expression struct { - src node -} - -func (b *body) Content(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Diagnostics) { - content, newBody, diags := b.PartialContent(schema) - - hiddenAttrs := newBody.(*body).hiddenAttrs - - var nameSuggestions []string - for _, attrS := range schema.Attributes { - if _, ok := hiddenAttrs[attrS.Name]; !ok { - // Only suggest an attribute name if we didn't use it already. - nameSuggestions = append(nameSuggestions, attrS.Name) - } - } - for _, blockS := range schema.Blocks { - // Blocks can appear multiple times, so we'll suggest their type - // names regardless of whether they've already been used. - nameSuggestions = append(nameSuggestions, blockS.Type) - } - - jsonAttrs, attrDiags := b.collectDeepAttrs(b.val, nil) - diags = append(diags, attrDiags...) - - for _, attr := range jsonAttrs { - k := attr.Name - if k == "//" { - // Ignore "//" keys in objects representing bodies, to allow - // their use as comments. - continue - } - - if _, ok := hiddenAttrs[k]; !ok { - suggestion := nameSuggestion(k, nameSuggestions) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } - - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Extraneous JSON object property", - Detail: fmt.Sprintf("No argument or block type is named %q.%s", k, suggestion), - Subject: &attr.NameRange, - Context: attr.Range().Ptr(), - }) - } - } - - return content, diags -} - -func (b *body) PartialContent(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Body, hcl.Diagnostics) { - var diags hcl.Diagnostics - - jsonAttrs, attrDiags := b.collectDeepAttrs(b.val, nil) - diags = append(diags, attrDiags...) - - usedNames := map[string]struct{}{} - if b.hiddenAttrs != nil { - for k := range b.hiddenAttrs { - usedNames[k] = struct{}{} - } - } - - content := &hcl.BodyContent{ - Attributes: map[string]*hcl.Attribute{}, - Blocks: nil, - - MissingItemRange: b.MissingItemRange(), - } - - // Create some more convenient data structures for our work below. - attrSchemas := map[string]hcl.AttributeSchema{} - blockSchemas := map[string]hcl.BlockHeaderSchema{} - for _, attrS := range schema.Attributes { - attrSchemas[attrS.Name] = attrS - } - for _, blockS := range schema.Blocks { - blockSchemas[blockS.Type] = blockS - } - - for _, jsonAttr := range jsonAttrs { - attrName := jsonAttr.Name - if _, used := b.hiddenAttrs[attrName]; used { - continue - } - - if attrS, defined := attrSchemas[attrName]; defined { - if existing, exists := content.Attributes[attrName]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate argument", - Detail: fmt.Sprintf("The argument %q was already set at %s.", attrName, existing.Range), - Subject: &jsonAttr.NameRange, - Context: jsonAttr.Range().Ptr(), - }) - continue - } - - content.Attributes[attrS.Name] = &hcl.Attribute{ - Name: attrS.Name, - Expr: &expression{src: jsonAttr.Value}, - Range: hcl.RangeBetween(jsonAttr.NameRange, jsonAttr.Value.Range()), - NameRange: jsonAttr.NameRange, - } - usedNames[attrName] = struct{}{} - - } else if blockS, defined := blockSchemas[attrName]; defined { - bv := jsonAttr.Value - blockDiags := b.unpackBlock(bv, blockS.Type, &jsonAttr.NameRange, blockS.LabelNames, nil, nil, &content.Blocks) - diags = append(diags, blockDiags...) - usedNames[attrName] = struct{}{} - } - - // We ignore anything that isn't defined because that's the - // PartialContent contract. The Content method will catch leftovers. - } - - // Make sure we got all the required attributes. - for _, attrS := range schema.Attributes { - if !attrS.Required { - continue - } - if _, defined := content.Attributes[attrS.Name]; !defined { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing required argument", - Detail: fmt.Sprintf("The argument %q is required, but no definition was found.", attrS.Name), - Subject: b.MissingItemRange().Ptr(), - }) - } - } - - unusedBody := &body{ - val: b.val, - hiddenAttrs: usedNames, - } - - return content, unusedBody, diags -} - -// JustAttributes for JSON bodies interprets all properties of the wrapped -// JSON object as attributes and returns them. -func (b *body) JustAttributes() (hcl.Attributes, hcl.Diagnostics) { - var diags hcl.Diagnostics - attrs := make(map[string]*hcl.Attribute) - - obj, ok := b.val.(*objectVal) - if !ok { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Incorrect JSON value type", - Detail: "A JSON object is required here, setting the arguments for this block.", - Subject: b.val.StartRange().Ptr(), - }) - return attrs, diags - } - - for _, jsonAttr := range obj.Attrs { - name := jsonAttr.Name - if name == "//" { - // Ignore "//" keys in objects representing bodies, to allow - // their use as comments. - continue - } - - if _, hidden := b.hiddenAttrs[name]; hidden { - continue - } - - if existing, exists := attrs[name]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate attribute definition", - Detail: fmt.Sprintf("The argument %q was already set at %s.", name, existing.Range), - Subject: &jsonAttr.NameRange, - }) - continue - } - - attrs[name] = &hcl.Attribute{ - Name: name, - Expr: &expression{src: jsonAttr.Value}, - Range: hcl.RangeBetween(jsonAttr.NameRange, jsonAttr.Value.Range()), - NameRange: jsonAttr.NameRange, - } - } - - // No diagnostics possible here, since the parser already took care of - // finding duplicates and every JSON value can be a valid attribute value. - return attrs, diags -} - -func (b *body) MissingItemRange() hcl.Range { - switch tv := b.val.(type) { - case *objectVal: - return tv.CloseRange - case *arrayVal: - return tv.OpenRange - default: - // Should not happen in correct operation, but might show up if the - // input is invalid and we are producing partial results. - return tv.StartRange() - } -} - -func (b *body) unpackBlock(v node, typeName string, typeRange *hcl.Range, labelsLeft []string, labelsUsed []string, labelRanges []hcl.Range, blocks *hcl.Blocks) (diags hcl.Diagnostics) { - if len(labelsLeft) > 0 { - labelName := labelsLeft[0] - jsonAttrs, attrDiags := b.collectDeepAttrs(v, &labelName) - diags = append(diags, attrDiags...) - - if len(jsonAttrs) == 0 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing block label", - Detail: fmt.Sprintf("At least one object property is required, whose name represents the %s block's %s.", typeName, labelName), - Subject: v.StartRange().Ptr(), - }) - return - } - labelsUsed := append(labelsUsed, "") - labelRanges := append(labelRanges, hcl.Range{}) - for _, p := range jsonAttrs { - pk := p.Name - labelsUsed[len(labelsUsed)-1] = pk - labelRanges[len(labelRanges)-1] = p.NameRange - diags = append(diags, b.unpackBlock(p.Value, typeName, typeRange, labelsLeft[1:], labelsUsed, labelRanges, blocks)...) - } - return - } - - // By the time we get here, we've peeled off all the labels and we're ready - // to deal with the block's actual content. - - // need to copy the label slices because their underlying arrays will - // continue to be mutated after we return. - labels := make([]string, len(labelsUsed)) - copy(labels, labelsUsed) - labelR := make([]hcl.Range, len(labelRanges)) - copy(labelR, labelRanges) - - switch tv := v.(type) { - case *nullVal: - // There is no block content, e.g the value is null. - return - case *objectVal: - // Single instance of the block - *blocks = append(*blocks, &hcl.Block{ - Type: typeName, - Labels: labels, - Body: &body{ - val: tv, - }, - - DefRange: tv.OpenRange, - TypeRange: *typeRange, - LabelRanges: labelR, - }) - case *arrayVal: - // Multiple instances of the block - for _, av := range tv.Values { - *blocks = append(*blocks, &hcl.Block{ - Type: typeName, - Labels: labels, - Body: &body{ - val: av, // might be mistyped; we'll find out when content is requested for this body - }, - - DefRange: tv.OpenRange, - TypeRange: *typeRange, - LabelRanges: labelR, - }) - } - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Incorrect JSON value type", - Detail: fmt.Sprintf("Either a JSON object or a JSON array is required, representing the contents of one or more %q blocks.", typeName), - Subject: v.StartRange().Ptr(), - }) - } - return -} - -// collectDeepAttrs takes either a single object or an array of objects and -// flattens it into a list of object attributes, collecting attributes from -// all of the objects in a given array. -// -// Ordering is preserved, so a list of objects that each have one property -// will result in those properties being returned in the same order as the -// objects appeared in the array. -// -// This is appropriate for use only for objects representing bodies or labels -// within a block. -// -// The labelName argument, if non-null, is used to tailor returned error -// messages to refer to block labels rather than attributes and child blocks. -// It has no other effect. -func (b *body) collectDeepAttrs(v node, labelName *string) ([]*objectAttr, hcl.Diagnostics) { - var diags hcl.Diagnostics - var attrs []*objectAttr - - switch tv := v.(type) { - case *nullVal: - // If a value is null, then we don't return any attributes or return an error. - - case *objectVal: - attrs = append(attrs, tv.Attrs...) - - case *arrayVal: - for _, ev := range tv.Values { - switch tev := ev.(type) { - case *objectVal: - attrs = append(attrs, tev.Attrs...) - default: - if labelName != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Incorrect JSON value type", - Detail: fmt.Sprintf("A JSON object is required here, to specify %s labels for this block.", *labelName), - Subject: ev.StartRange().Ptr(), - }) - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Incorrect JSON value type", - Detail: "A JSON object is required here, to define arguments and child blocks.", - Subject: ev.StartRange().Ptr(), - }) - } - } - } - - default: - if labelName != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Incorrect JSON value type", - Detail: fmt.Sprintf("Either a JSON object or JSON array of objects is required here, to specify %s labels for this block.", *labelName), - Subject: v.StartRange().Ptr(), - }) - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Incorrect JSON value type", - Detail: "Either a JSON object or JSON array of objects is required here, to define arguments and child blocks.", - Subject: v.StartRange().Ptr(), - }) - } - } - - return attrs, diags -} - -func (e *expression) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - switch v := e.src.(type) { - case *stringVal: - if ctx != nil { - // Parse string contents as a HCL native language expression. - // We only do this if we have a context, so passing a nil context - // is how the caller specifies that interpolations are not allowed - // and that the string should just be returned verbatim. - templateSrc := v.Value - expr, diags := hclsyntax.ParseTemplate( - []byte(templateSrc), - v.SrcRange.Filename, - - // This won't produce _exactly_ the right result, since - // the hclsyntax parser can't "see" any escapes we removed - // while parsing JSON, but it's better than nothing. - hcl.Pos{ - Line: v.SrcRange.Start.Line, - - // skip over the opening quote mark - Byte: v.SrcRange.Start.Byte + 1, - Column: v.SrcRange.Start.Column + 1, - }, - ) - if diags.HasErrors() { - return cty.DynamicVal, diags - } - val, evalDiags := expr.Value(ctx) - diags = append(diags, evalDiags...) - return val, diags - } - - return cty.StringVal(v.Value), nil - case *numberVal: - return cty.NumberVal(v.Value), nil - case *booleanVal: - return cty.BoolVal(v.Value), nil - case *arrayVal: - var diags hcl.Diagnostics - vals := []cty.Value{} - for _, jsonVal := range v.Values { - val, valDiags := (&expression{src: jsonVal}).Value(ctx) - vals = append(vals, val) - diags = append(diags, valDiags...) - } - return cty.TupleVal(vals), diags - case *objectVal: - var diags hcl.Diagnostics - attrs := map[string]cty.Value{} - attrRanges := map[string]hcl.Range{} - known := true - for _, jsonAttr := range v.Attrs { - // In this one context we allow keys to contain interpolation - // expressions too, assuming we're evaluating in interpolation - // mode. This achieves parity with the native syntax where - // object expressions can have dynamic keys, while block contents - // may not. - name, nameDiags := (&expression{src: &stringVal{ - Value: jsonAttr.Name, - SrcRange: jsonAttr.NameRange, - }}).Value(ctx) - valExpr := &expression{src: jsonAttr.Value} - val, valDiags := valExpr.Value(ctx) - diags = append(diags, nameDiags...) - diags = append(diags, valDiags...) - - var err error - name, err = convert.Convert(name, cty.String) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid object key expression", - Detail: fmt.Sprintf("Cannot use this expression as an object key: %s.", err), - Subject: &jsonAttr.NameRange, - Expression: valExpr, - EvalContext: ctx, - }) - continue - } - if name.IsNull() { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid object key expression", - Detail: "Cannot use null value as an object key.", - Subject: &jsonAttr.NameRange, - Expression: valExpr, - EvalContext: ctx, - }) - continue - } - if !name.IsKnown() { - // This is a bit of a weird case, since our usual rules require - // us to tolerate unknowns and just represent the result as - // best we can but if we don't know the key then we can't - // know the type of our object at all, and thus we must turn - // the whole thing into cty.DynamicVal. This is consistent with - // how this situation is handled in the native syntax. - // We'll keep iterating so we can collect other errors in - // subsequent attributes. - known = false - continue - } - nameStr := name.AsString() - if _, defined := attrs[nameStr]; defined { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate object attribute", - Detail: fmt.Sprintf("An attribute named %q was already defined at %s.", nameStr, attrRanges[nameStr]), - Subject: &jsonAttr.NameRange, - Expression: e, - EvalContext: ctx, - }) - continue - } - attrs[nameStr] = val - attrRanges[nameStr] = jsonAttr.NameRange - } - if !known { - // We encountered an unknown key somewhere along the way, so - // we can't know what our type will eventually be. - return cty.DynamicVal, diags - } - return cty.ObjectVal(attrs), diags - case *nullVal: - return cty.NullVal(cty.DynamicPseudoType), nil - default: - // Default to DynamicVal so that ASTs containing invalid nodes can - // still be partially-evaluated. - return cty.DynamicVal, nil - } -} - -func (e *expression) Variables() []hcl.Traversal { - var vars []hcl.Traversal - - switch v := e.src.(type) { - case *stringVal: - templateSrc := v.Value - expr, diags := hclsyntax.ParseTemplate( - []byte(templateSrc), - v.SrcRange.Filename, - - // This won't produce _exactly_ the right result, since - // the hclsyntax parser can't "see" any escapes we removed - // while parsing JSON, but it's better than nothing. - hcl.Pos{ - Line: v.SrcRange.Start.Line, - - // skip over the opening quote mark - Byte: v.SrcRange.Start.Byte + 1, - Column: v.SrcRange.Start.Column + 1, - }, - ) - if diags.HasErrors() { - return vars - } - return expr.Variables() - - case *arrayVal: - for _, jsonVal := range v.Values { - vars = append(vars, (&expression{src: jsonVal}).Variables()...) - } - case *objectVal: - for _, jsonAttr := range v.Attrs { - keyExpr := &stringVal{ // we're going to treat key as an expression in this context - Value: jsonAttr.Name, - SrcRange: jsonAttr.NameRange, - } - vars = append(vars, (&expression{src: keyExpr}).Variables()...) - vars = append(vars, (&expression{src: jsonAttr.Value}).Variables()...) - } - } - - return vars -} - -func (e *expression) Range() hcl.Range { - return e.src.Range() -} - -func (e *expression) StartRange() hcl.Range { - return e.src.StartRange() -} - -// Implementation for hcl.AbsTraversalForExpr. -func (e *expression) AsTraversal() hcl.Traversal { - // In JSON-based syntax a traversal is given as a string containing - // traversal syntax as defined by hclsyntax.ParseTraversalAbs. - - switch v := e.src.(type) { - case *stringVal: - traversal, diags := hclsyntax.ParseTraversalAbs([]byte(v.Value), v.SrcRange.Filename, v.SrcRange.Start) - if diags.HasErrors() { - return nil - } - return traversal - default: - return nil - } -} - -// Implementation for hcl.ExprCall. -func (e *expression) ExprCall() *hcl.StaticCall { - // In JSON-based syntax a static call is given as a string containing - // an expression in the native syntax that also supports ExprCall. - - switch v := e.src.(type) { - case *stringVal: - expr, diags := hclsyntax.ParseExpression([]byte(v.Value), v.SrcRange.Filename, v.SrcRange.Start) - if diags.HasErrors() { - return nil - } - - call, diags := hcl.ExprCall(expr) - if diags.HasErrors() { - return nil - } - - return call - default: - return nil - } -} - -// Implementation for hcl.ExprList. -func (e *expression) ExprList() []hcl.Expression { - switch v := e.src.(type) { - case *arrayVal: - ret := make([]hcl.Expression, len(v.Values)) - for i, node := range v.Values { - ret[i] = &expression{src: node} - } - return ret - default: - return nil - } -} - -// Implementation for hcl.ExprMap. -func (e *expression) ExprMap() []hcl.KeyValuePair { - switch v := e.src.(type) { - case *objectVal: - ret := make([]hcl.KeyValuePair, len(v.Attrs)) - for i, jsonAttr := range v.Attrs { - ret[i] = hcl.KeyValuePair{ - Key: &expression{src: &stringVal{ - Value: jsonAttr.Name, - SrcRange: jsonAttr.NameRange, - }}, - Value: &expression{src: jsonAttr.Value}, - } - } - return ret - default: - return nil - } -} diff --git a/vendor/github.com/hashicorp/hcl/v2/json/tokentype_string.go b/vendor/github.com/hashicorp/hcl/v2/json/tokentype_string.go deleted file mode 100644 index bbcce5b306f..00000000000 --- a/vendor/github.com/hashicorp/hcl/v2/json/tokentype_string.go +++ /dev/null @@ -1,29 +0,0 @@ -// Code generated by "stringer -type tokenType scanner.go"; DO NOT EDIT. - -package json - -import "strconv" - -const _tokenType_name = "tokenInvalidtokenCommatokenColontokenEqualstokenKeywordtokenNumbertokenStringtokenBrackOtokenBrackCtokenBraceOtokenBraceCtokenEOF" - -var _tokenType_map = map[tokenType]string{ - 0: _tokenType_name[0:12], - 44: _tokenType_name[12:22], - 58: _tokenType_name[22:32], - 61: _tokenType_name[32:43], - 75: _tokenType_name[43:55], - 78: _tokenType_name[55:66], - 83: _tokenType_name[66:77], - 91: _tokenType_name[77:88], - 93: _tokenType_name[88:99], - 123: _tokenType_name[99:110], - 125: _tokenType_name[110:121], - 9220: _tokenType_name[121:129], -} - -func (i tokenType) String() string { - if str, ok := _tokenType_map[i]; ok { - return str - } - return "tokenType(" + strconv.FormatInt(int64(i), 10) + ")" -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/diagnostic.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/diagnostic.go deleted file mode 100644 index d9d27625837..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/diagnostic.go +++ /dev/null @@ -1,138 +0,0 @@ -package tfconfig - -import ( - "fmt" - - legacyhclparser "github.com/hashicorp/hcl/hcl/parser" - "github.com/hashicorp/hcl/v2" -) - -// Diagnostic describes a problem (error or warning) encountered during -// configuration loading. -type Diagnostic struct { - Severity DiagSeverity `json:"severity"` - Summary string `json:"summary"` - Detail string `json:"detail,omitempty"` - - // Pos is not populated for all diagnostics, but when populated should - // indicate a particular line that the described problem relates to. - Pos *SourcePos `json:"pos,omitempty"` -} - -// Diagnostics represents a sequence of diagnostics. This is the type that -// should be returned from a function that might generate diagnostics. -type Diagnostics []Diagnostic - -// HasErrors returns true if there is at least one Diagnostic of severity -// DiagError in the receiever. -// -// If a function returns a Diagnostics without errors then the result can -// be assumed to be complete within the "best effort" constraints of this -// library. If errors are present then the caller may wish to employ more -// caution in relying on the result. -func (diags Diagnostics) HasErrors() bool { - for _, diag := range diags { - if diag.Severity == DiagError { - return true - } - } - return false -} - -func (diags Diagnostics) Error() string { - switch len(diags) { - case 0: - return "no problems" - case 1: - return fmt.Sprintf("%s: %s", diags[0].Summary, diags[0].Detail) - default: - return fmt.Sprintf("%s: %s (and %d other messages)", diags[0].Summary, diags[0].Detail, len(diags)-1) - } -} - -// Err returns an error representing the receiver if the receiver HasErrors, or -// nil otherwise. -// -// The returned error can be type-asserted back to a Diagnostics if needed. -func (diags Diagnostics) Err() error { - if diags.HasErrors() { - return diags - } - return nil -} - -// DiagSeverity describes the severity of a Diagnostic. -type DiagSeverity rune - -// DiagError indicates a problem that prevented proper processing of the -// configuration. In the precense of DiagError diagnostics the result is -// likely to be incomplete. -const DiagError DiagSeverity = 'E' - -// DiagWarning indicates a problem that the user may wish to consider but -// that did not prevent proper processing of the configuration. -const DiagWarning DiagSeverity = 'W' - -// MarshalJSON is an implementation of encoding/json.Marshaler -func (s DiagSeverity) MarshalJSON() ([]byte, error) { - switch s { - case DiagError: - return []byte(`"error"`), nil - case DiagWarning: - return []byte(`"warning"`), nil - default: - return []byte(`"invalid"`), nil - } -} - -func diagnosticsHCL(diags hcl.Diagnostics) Diagnostics { - if len(diags) == 0 { - return nil - } - ret := make(Diagnostics, len(diags)) - for i, diag := range diags { - ret[i] = Diagnostic{ - Summary: diag.Summary, - Detail: diag.Detail, - } - switch diag.Severity { - case hcl.DiagError: - ret[i].Severity = DiagError - case hcl.DiagWarning: - ret[i].Severity = DiagWarning - } - if diag.Subject != nil { - pos := sourcePosHCL(*diag.Subject) - ret[i].Pos = &pos - } - } - return ret -} - -func diagnosticsError(err error) Diagnostics { - if err == nil { - return nil - } - - if posErr, ok := err.(*legacyhclparser.PosError); ok { - pos := sourcePosLegacyHCL(posErr.Pos, "") - return Diagnostics{ - Diagnostic{ - Severity: DiagError, - Summary: posErr.Err.Error(), - Pos: &pos, - }, - } - } - - return Diagnostics{ - Diagnostic{ - Severity: DiagError, - Summary: err.Error(), - }, - } -} - -func diagnosticsErrorf(format string, args ...interface{}) Diagnostics { - return diagnosticsError(fmt.Errorf(format, args...)) -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/doc.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/doc.go deleted file mode 100644 index 1604a6e08a3..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/doc.go +++ /dev/null @@ -1,21 +0,0 @@ -// Package tfconfig is a helper library that does careful, shallow parsing of -// Terraform modules to provide access to high-level metadata while -// remaining broadly compatible with configurations targeting various -// different Terraform versions. -// -// This packge focuses on describing top-level objects only, and in particular -// does not attempt any sort of processing that would require access to plugins. -// Currently it allows callers to extract high-level information about -// variables, outputs, resource blocks, provider dependencies, and Terraform -// Core dependencies. -// -// This package only works at the level of single modules. A full configuration -// is a tree of potentially several modules, some of which may be references -// to remote packages. There are some basic helpers for traversing calls to -// modules at relative local paths, however. -// -// This package employs a "best effort" parsing strategy, producing as complete -// a result as possible even though the input may not be entirely valid. The -// intended use-case is high-level analysis and indexing of externally-facing -// module characteristics, as opposed to validating or even applying the module. -package tfconfig diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go deleted file mode 100644 index faa93ed6fb0..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go +++ /dev/null @@ -1,130 +0,0 @@ -package tfconfig - -import ( - "fmt" - "io/ioutil" - "path/filepath" - "strings" - - "github.com/hashicorp/hcl/v2" -) - -// LoadModule reads the directory at the given path and attempts to interpret -// it as a Terraform module. -func LoadModule(dir string) (*Module, Diagnostics) { - - // For broad compatibility here we actually have two separate loader - // codepaths. The main one uses the new HCL parser and API and is intended - // for configurations from Terraform 0.12 onwards (though will work for - // many older configurations too), but we'll also fall back on one that - // uses the _old_ HCL implementation so we can deal with some edge-cases - // that are not valid in new HCL. - - module, diags := loadModule(dir) - if diags.HasErrors() { - // Try using the legacy HCL parser and see if we fare better. - legacyModule, legacyDiags := loadModuleLegacyHCL(dir) - if !legacyDiags.HasErrors() { - legacyModule.init(legacyDiags) - return legacyModule, legacyDiags - } - } - - module.init(diags) - return module, diags -} - -// IsModuleDir checks if the given path contains terraform configuration files. -// This allows the caller to decide how to handle directories that do not have tf files. -func IsModuleDir(dir string) bool { - primaryPaths, _ := dirFiles(dir) - if len(primaryPaths) == 0 { - return false - } - return true -} - -func (m *Module) init(diags Diagnostics) { - // Fill in any additional provider requirements that are implied by - // resource configurations, to avoid the caller from needing to apply - // this logic itself. Implied requirements don't have version constraints, - // but we'll make sure the requirement value is still non-nil in this - // case so callers can easily recognize it. - for _, r := range m.ManagedResources { - if _, exists := m.RequiredProviders[r.Provider.Name]; !exists { - m.RequiredProviders[r.Provider.Name] = []string{} - } - } - for _, r := range m.DataResources { - if _, exists := m.RequiredProviders[r.Provider.Name]; !exists { - m.RequiredProviders[r.Provider.Name] = []string{} - } - } - - // We redundantly also reference the diagnostics from inside the module - // object, primarily so that we can easily included in JSON-serialized - // versions of the module object. - m.Diagnostics = diags -} - -func dirFiles(dir string) (primary []string, diags hcl.Diagnostics) { - infos, err := ioutil.ReadDir(dir) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Failed to read module directory", - Detail: fmt.Sprintf("Module directory %s does not exist or cannot be read.", dir), - }) - return - } - - var override []string - for _, info := range infos { - if info.IsDir() { - // We only care about files - continue - } - - name := info.Name() - ext := fileExt(name) - if ext == "" || isIgnoredFile(name) { - continue - } - - baseName := name[:len(name)-len(ext)] // strip extension - isOverride := baseName == "override" || strings.HasSuffix(baseName, "_override") - - fullPath := filepath.Join(dir, name) - if isOverride { - override = append(override, fullPath) - } else { - primary = append(primary, fullPath) - } - } - - // We are assuming that any _override files will be logically named, - // and processing the files in alphabetical order. Primaries first, then overrides. - primary = append(primary, override...) - - return -} - -// fileExt returns the Terraform configuration extension of the given -// path, or a blank string if it is not a recognized extension. -func fileExt(path string) string { - if strings.HasSuffix(path, ".tf") { - return ".tf" - } else if strings.HasSuffix(path, ".tf.json") { - return ".tf.json" - } else { - return "" - } -} - -// isIgnoredFile returns true if the given filename (which must not have a -// directory path ahead of it) should be ignored as e.g. an editor swap file. -func isIgnoredFile(name string) bool { - return strings.HasPrefix(name, ".") || // Unix-like hidden files - strings.HasSuffix(name, "~") || // vim - strings.HasPrefix(name, "#") && strings.HasSuffix(name, "#") // emacs -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_hcl.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_hcl.go deleted file mode 100644 index 9cb3aeef1bf..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_hcl.go +++ /dev/null @@ -1,322 +0,0 @@ -package tfconfig - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/hashicorp/hcl/v2/hclsyntax" - - "github.com/hashicorp/hcl/v2/gohcl" - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclparse" - ctyjson "github.com/zclconf/go-cty/cty/json" -) - -func loadModule(dir string) (*Module, Diagnostics) { - mod := newModule(dir) - primaryPaths, diags := dirFiles(dir) - - parser := hclparse.NewParser() - - for _, filename := range primaryPaths { - var file *hcl.File - var fileDiags hcl.Diagnostics - if strings.HasSuffix(filename, ".json") { - file, fileDiags = parser.ParseJSONFile(filename) - } else { - file, fileDiags = parser.ParseHCLFile(filename) - } - diags = append(diags, fileDiags...) - if file == nil { - continue - } - - content, _, contentDiags := file.Body.PartialContent(rootSchema) - diags = append(diags, contentDiags...) - - for _, block := range content.Blocks { - switch block.Type { - - case "terraform": - content, _, contentDiags := block.Body.PartialContent(terraformBlockSchema) - diags = append(diags, contentDiags...) - - if attr, defined := content.Attributes["required_version"]; defined { - var version string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version) - diags = append(diags, valDiags...) - if !valDiags.HasErrors() { - mod.RequiredCore = append(mod.RequiredCore, version) - } - } - - for _, block := range content.Blocks { - // Our schema only allows required_providers here, so we - // assume that we'll only get that block type. - attrs, attrDiags := block.Body.JustAttributes() - diags = append(diags, attrDiags...) - - for name, attr := range attrs { - var version string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version) - diags = append(diags, valDiags...) - if !valDiags.HasErrors() { - mod.RequiredProviders[name] = append(mod.RequiredProviders[name], version) - } - } - } - - case "variable": - content, _, contentDiags := block.Body.PartialContent(variableSchema) - diags = append(diags, contentDiags...) - - name := block.Labels[0] - v := &Variable{ - Name: name, - Pos: sourcePosHCL(block.DefRange), - } - - mod.Variables[name] = v - - if attr, defined := content.Attributes["type"]; defined { - // We handle this particular attribute in a somewhat-tricky way: - // since Terraform may evolve its type expression syntax in - // future versions, we don't want to be overly-strict in how - // we handle it here, and so we'll instead just take the raw - // source provided by the user, using the source location - // information in the expression object. - // - // However, older versions of Terraform expected the type - // to be a string containing a keyword, so we'll need to - // handle that as a special case first for backward compatibility. - - var typeExpr string - - var typeExprAsStr string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &typeExprAsStr) - if !valDiags.HasErrors() { - typeExpr = typeExprAsStr - } else { - - rng := attr.Expr.Range() - sourceFilename := rng.Filename - source, exists := parser.Sources()[sourceFilename] - if exists { - typeExpr = string(rng.SliceBytes(source)) - } else { - // This should never happen, so we'll just warn about it and leave the type unspecified. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Source code not available", - Detail: fmt.Sprintf("Source code is not available for the file %q, which declares the variable %q.", sourceFilename, name), - Subject: &block.DefRange, - }) - typeExpr = "" - } - - } - - v.Type = typeExpr - } - - if attr, defined := content.Attributes["description"]; defined { - var description string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &description) - diags = append(diags, valDiags...) - v.Description = description - } - - if attr, defined := content.Attributes["default"]; defined { - // To avoid the caller needing to deal with cty here, we'll - // use its JSON encoding to convert into an - // approximately-equivalent plain Go interface{} value - // to return. - val, valDiags := attr.Expr.Value(nil) - diags = append(diags, valDiags...) - if val.IsWhollyKnown() { // should only be false if there are errors in the input - valJSON, err := ctyjson.Marshal(val, val.Type()) - if err != nil { - // Should never happen, since all possible known - // values have a JSON mapping. - panic(fmt.Errorf("failed to serialize default value as JSON: %s", err)) - } - var def interface{} - err = json.Unmarshal(valJSON, &def) - if err != nil { - // Again should never happen, because valJSON is - // guaranteed valid by ctyjson.Marshal. - panic(fmt.Errorf("failed to re-parse default value from JSON: %s", err)) - } - v.Default = def - } - } - - case "output": - - content, _, contentDiags := block.Body.PartialContent(outputSchema) - diags = append(diags, contentDiags...) - - name := block.Labels[0] - o := &Output{ - Name: name, - Pos: sourcePosHCL(block.DefRange), - } - - mod.Outputs[name] = o - - if attr, defined := content.Attributes["description"]; defined { - var description string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &description) - diags = append(diags, valDiags...) - o.Description = description - } - - case "provider": - - content, _, contentDiags := block.Body.PartialContent(providerConfigSchema) - diags = append(diags, contentDiags...) - - name := block.Labels[0] - - if attr, defined := content.Attributes["version"]; defined { - var version string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version) - diags = append(diags, valDiags...) - if !valDiags.HasErrors() { - mod.RequiredProviders[name] = append(mod.RequiredProviders[name], version) - } - } - - // Even if there wasn't an explicit version required, we still - // need an entry in our map to signal the unversioned dependency. - if _, exists := mod.RequiredProviders[name]; !exists { - mod.RequiredProviders[name] = []string{} - } - - case "resource", "data": - - content, _, contentDiags := block.Body.PartialContent(resourceSchema) - diags = append(diags, contentDiags...) - - typeName := block.Labels[0] - name := block.Labels[1] - - r := &Resource{ - Type: typeName, - Name: name, - Pos: sourcePosHCL(block.DefRange), - } - - var resourcesMap map[string]*Resource - - switch block.Type { - case "resource": - r.Mode = ManagedResourceMode - resourcesMap = mod.ManagedResources - case "data": - r.Mode = DataResourceMode - resourcesMap = mod.DataResources - } - - key := r.MapKey() - - resourcesMap[key] = r - - if attr, defined := content.Attributes["provider"]; defined { - // New style here is to provide this as a naked traversal - // expression, but we also support quoted references for - // older configurations that predated this convention. - traversal, travDiags := hcl.AbsTraversalForExpr(attr.Expr) - if travDiags.HasErrors() { - traversal = nil // in case we got any partial results - - // Fall back on trying to parse as a string - var travStr string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &travStr) - if !valDiags.HasErrors() { - var strDiags hcl.Diagnostics - traversal, strDiags = hclsyntax.ParseTraversalAbs([]byte(travStr), "", hcl.Pos{}) - if strDiags.HasErrors() { - traversal = nil - } - } - } - - // If we get out here with a nil traversal then we didn't - // succeed in processing the input. - if len(traversal) > 0 { - providerName := traversal.RootName() - alias := "" - if len(traversal) > 1 { - if getAttr, ok := traversal[1].(hcl.TraverseAttr); ok { - alias = getAttr.Name - } - } - r.Provider = ProviderRef{ - Name: providerName, - Alias: alias, - } - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider reference", - Detail: "Provider argument requires a provider name followed by an optional alias, like \"aws.foo\".", - Subject: attr.Expr.Range().Ptr(), - }) - } - } else { - // If provider _isn't_ set then we'll infer it from the - // resource type. - r.Provider = ProviderRef{ - Name: resourceTypeDefaultProviderName(r.Type), - } - } - - case "module": - - content, _, contentDiags := block.Body.PartialContent(moduleCallSchema) - diags = append(diags, contentDiags...) - - name := block.Labels[0] - mc := &ModuleCall{ - Name: block.Labels[0], - Pos: sourcePosHCL(block.DefRange), - } - - // check if this is overriding an existing module - var origSource string - if origMod, exists := mod.ModuleCalls[name]; exists { - origSource = origMod.Source - } - - mod.ModuleCalls[name] = mc - - if attr, defined := content.Attributes["source"]; defined { - var source string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &source) - diags = append(diags, valDiags...) - mc.Source = source - } - - if mc.Source == "" { - mc.Source = origSource - } - - if attr, defined := content.Attributes["version"]; defined { - var version string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version) - diags = append(diags, valDiags...) - mc.Version = version - } - - default: - // Should never happen because our cases above should be - // exhaustive for our schema. - panic(fmt.Errorf("unhandled block type %q", block.Type)) - } - } - } - - return mod, diagnosticsHCL(diags) -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go deleted file mode 100644 index 86ffdf11dd3..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go +++ /dev/null @@ -1,325 +0,0 @@ -package tfconfig - -import ( - "io/ioutil" - "strings" - - legacyhcl "github.com/hashicorp/hcl" - legacyast "github.com/hashicorp/hcl/hcl/ast" -) - -func loadModuleLegacyHCL(dir string) (*Module, Diagnostics) { - // This implementation is intentionally more quick-and-dirty than the - // main loader. In particular, it doesn't bother to keep careful track - // of multiple error messages because we always fall back on returning - // the main parser's error message if our fallback parsing produces - // an error, and thus the errors here are not seen by the end-caller. - mod := newModule(dir) - - primaryPaths, diags := dirFiles(dir) - if diags.HasErrors() { - return mod, diagnosticsHCL(diags) - } - - for _, filename := range primaryPaths { - src, err := ioutil.ReadFile(filename) - if err != nil { - return mod, diagnosticsErrorf("Error reading %s: %s", filename, err) - } - - hclRoot, err := legacyhcl.Parse(string(src)) - if err != nil { - return mod, diagnosticsErrorf("Error parsing %s: %s", filename, err) - } - - list, ok := hclRoot.Node.(*legacyast.ObjectList) - if !ok { - return mod, diagnosticsErrorf("Error parsing %s: no root object", filename) - } - - for _, item := range list.Filter("terraform").Items { - if len(item.Keys) > 0 { - item = &legacyast.ObjectItem{ - Val: &legacyast.ObjectType{ - List: &legacyast.ObjectList{ - Items: []*legacyast.ObjectItem{item}, - }, - }, - } - } - - type TerraformBlock struct { - RequiredVersion string `hcl:"required_version"` - } - var block TerraformBlock - err = legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("terraform block: %s", err) - } - - if block.RequiredVersion != "" { - mod.RequiredCore = append(mod.RequiredCore, block.RequiredVersion) - } - } - - if vars := list.Filter("variable"); len(vars.Items) > 0 { - vars = vars.Children() - type VariableBlock struct { - Type string `hcl:"type"` - Default interface{} - Description string - Fields []string `hcl:",decodedFields"` - } - - for _, item := range vars.Items { - unwrapLegacyHCLObjectKeysFromJSON(item, 1) - - if len(item.Keys) != 1 { - return nil, diagnosticsErrorf("variable block at %s has no label", item.Pos()) - } - - name := item.Keys[0].Token.Value().(string) - - var block VariableBlock - err := legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("invalid variable block at %s: %s", item.Pos(), err) - } - - // Clean up legacy HCL decoding ambiguity by unwrapping list of maps - if ms, ok := block.Default.([]map[string]interface{}); ok { - def := make(map[string]interface{}) - for _, m := range ms { - for k, v := range m { - def[k] = v - } - } - block.Default = def - } - - v := &Variable{ - Name: name, - Type: block.Type, - Description: block.Description, - Default: block.Default, - Pos: sourcePosLegacyHCL(item.Pos(), filename), - } - if _, exists := mod.Variables[name]; exists { - return nil, diagnosticsErrorf("duplicate variable block for %q", name) - } - mod.Variables[name] = v - - } - } - - if outputs := list.Filter("output"); len(outputs.Items) > 0 { - outputs = outputs.Children() - type OutputBlock struct { - Description string - } - - for _, item := range outputs.Items { - unwrapLegacyHCLObjectKeysFromJSON(item, 1) - - if len(item.Keys) != 1 { - return nil, diagnosticsErrorf("output block at %s has no label", item.Pos()) - } - - name := item.Keys[0].Token.Value().(string) - - var block OutputBlock - err := legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("invalid output block at %s: %s", item.Pos(), err) - } - - o := &Output{ - Name: name, - Description: block.Description, - Pos: sourcePosLegacyHCL(item.Pos(), filename), - } - if _, exists := mod.Outputs[name]; exists { - return nil, diagnosticsErrorf("duplicate output block for %q", name) - } - mod.Outputs[name] = o - } - } - - for _, blockType := range []string{"resource", "data"} { - if resources := list.Filter(blockType); len(resources.Items) > 0 { - resources = resources.Children() - type ResourceBlock struct { - Provider string - } - - for _, item := range resources.Items { - unwrapLegacyHCLObjectKeysFromJSON(item, 2) - - if len(item.Keys) != 2 { - return nil, diagnosticsErrorf("resource block at %s has wrong label count", item.Pos()) - } - - typeName := item.Keys[0].Token.Value().(string) - name := item.Keys[1].Token.Value().(string) - var mode ResourceMode - var rMap map[string]*Resource - switch blockType { - case "resource": - mode = ManagedResourceMode - rMap = mod.ManagedResources - case "data": - mode = DataResourceMode - rMap = mod.DataResources - } - - var block ResourceBlock - err := legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("invalid resource block at %s: %s", item.Pos(), err) - } - - var providerName, providerAlias string - if dotPos := strings.IndexByte(block.Provider, '.'); dotPos != -1 { - providerName = block.Provider[:dotPos] - providerAlias = block.Provider[dotPos+1:] - } else { - providerName = block.Provider - } - if providerName == "" { - providerName = resourceTypeDefaultProviderName(typeName) - } - - r := &Resource{ - Mode: mode, - Type: typeName, - Name: name, - Provider: ProviderRef{ - Name: providerName, - Alias: providerAlias, - }, - Pos: sourcePosLegacyHCL(item.Pos(), filename), - } - key := r.MapKey() - if _, exists := rMap[key]; exists { - return nil, diagnosticsErrorf("duplicate resource block for %q", key) - } - rMap[key] = r - } - } - - } - - if moduleCalls := list.Filter("module"); len(moduleCalls.Items) > 0 { - moduleCalls = moduleCalls.Children() - type ModuleBlock struct { - Source string - Version string - } - - for _, item := range moduleCalls.Items { - unwrapLegacyHCLObjectKeysFromJSON(item, 1) - - if len(item.Keys) != 1 { - return nil, diagnosticsErrorf("module block at %s has no label", item.Pos()) - } - - name := item.Keys[0].Token.Value().(string) - - var block ModuleBlock - err := legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("module block at %s: %s", item.Pos(), err) - } - - mc := &ModuleCall{ - Name: name, - Source: block.Source, - Version: block.Version, - Pos: sourcePosLegacyHCL(item.Pos(), filename), - } - // it's possible this module call is from an override file - if origMod, exists := mod.ModuleCalls[name]; exists { - if mc.Source == "" { - mc.Source = origMod.Source - } - } - mod.ModuleCalls[name] = mc - } - } - - if providerConfigs := list.Filter("provider"); len(providerConfigs.Items) > 0 { - providerConfigs = providerConfigs.Children() - type ProviderBlock struct { - Version string - } - - for _, item := range providerConfigs.Items { - unwrapLegacyHCLObjectKeysFromJSON(item, 1) - - if len(item.Keys) != 1 { - return nil, diagnosticsErrorf("provider block at %s has no label", item.Pos()) - } - - name := item.Keys[0].Token.Value().(string) - - var block ProviderBlock - err := legacyhcl.DecodeObject(&block, item.Val) - if err != nil { - return nil, diagnosticsErrorf("invalid provider block at %s: %s", item.Pos(), err) - } - - if block.Version != "" { - mod.RequiredProviders[name] = append(mod.RequiredProviders[name], block.Version) - } - - // Even if there wasn't an explicit version required, we still - // need an entry in our map to signal the unversioned dependency. - if _, exists := mod.RequiredProviders[name]; !exists { - mod.RequiredProviders[name] = []string{} - } - - } - } - } - - return mod, nil -} - -// unwrapLegacyHCLObjectKeysFromJSON cleans up an edge case that can occur when -// parsing JSON as input: if we're parsing JSON then directly nested -// items will show up as additional "keys". -// -// For objects that expect a fixed number of keys, this breaks the -// decoding process. This function unwraps the object into what it would've -// looked like if it came directly from HCL by specifying the number of keys -// you expect. -// -// Example: -// -// { "foo": { "baz": {} } } -// -// Will show up with Keys being: []string{"foo", "baz"} -// when we really just want the first two. This function will fix this. -func unwrapLegacyHCLObjectKeysFromJSON(item *legacyast.ObjectItem, depth int) { - if len(item.Keys) > depth && item.Keys[0].Token.JSON { - for len(item.Keys) > depth { - // Pop off the last key - n := len(item.Keys) - key := item.Keys[n-1] - item.Keys[n-1] = nil - item.Keys = item.Keys[:n-1] - - // Wrap our value in a list - item.Val = &legacyast.ObjectType{ - List: &legacyast.ObjectList{ - Items: []*legacyast.ObjectItem{ - &legacyast.ObjectItem{ - Keys: []*legacyast.ObjectKey{key}, - Val: item.Val, - }, - }, - }, - } - } - } -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go deleted file mode 100644 index 65ddb230735..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go +++ /dev/null @@ -1,35 +0,0 @@ -package tfconfig - -// Module is the top-level type representing a parsed and processed Terraform -// module. -type Module struct { - // Path is the local filesystem directory where the module was loaded from. - Path string `json:"path"` - - Variables map[string]*Variable `json:"variables"` - Outputs map[string]*Output `json:"outputs"` - - RequiredCore []string `json:"required_core,omitempty"` - RequiredProviders map[string][]string `json:"required_providers"` - - ManagedResources map[string]*Resource `json:"managed_resources"` - DataResources map[string]*Resource `json:"data_resources"` - ModuleCalls map[string]*ModuleCall `json:"module_calls"` - - // Diagnostics records any errors and warnings that were detected during - // loading, primarily for inclusion in serialized forms of the module - // since this slice is also returned as a second argument from LoadModule. - Diagnostics Diagnostics `json:"diagnostics,omitempty"` -} - -func newModule(path string) *Module { - return &Module{ - Path: path, - Variables: make(map[string]*Variable), - Outputs: make(map[string]*Output), - RequiredProviders: make(map[string][]string), - ManagedResources: make(map[string]*Resource), - DataResources: make(map[string]*Resource), - ModuleCalls: make(map[string]*ModuleCall), - } -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module_call.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module_call.go deleted file mode 100644 index 5e1e05a7268..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module_call.go +++ /dev/null @@ -1,11 +0,0 @@ -package tfconfig - -// ModuleCall represents a "module" block within a module. That is, a -// declaration of a child module from inside its parent. -type ModuleCall struct { - Name string `json:"name"` - Source string `json:"source"` - Version string `json:"version,omitempty"` - - Pos SourcePos `json:"pos"` -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/output.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/output.go deleted file mode 100644 index 890b25e694c..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/output.go +++ /dev/null @@ -1,9 +0,0 @@ -package tfconfig - -// Output represents a single output from a Terraform module. -type Output struct { - Name string `json:"name"` - Description string `json:"description,omitempty"` - - Pos SourcePos `json:"pos"` -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go deleted file mode 100644 index d924837785f..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go +++ /dev/null @@ -1,9 +0,0 @@ -package tfconfig - -// ProviderRef is a reference to a provider configuration within a module. -// It represents the contents of a "provider" argument in a resource, or -// a value in the "providers" map for a module call. -type ProviderRef struct { - Name string `json:"name"` - Alias string `json:"alias,omitempty"` // Empty if the default provider configuration is referenced -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/resource.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/resource.go deleted file mode 100644 index 401c8fce97e..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/resource.go +++ /dev/null @@ -1,64 +0,0 @@ -package tfconfig - -import ( - "fmt" - "strconv" - "strings" -) - -// Resource represents a single "resource" or "data" block within a module. -type Resource struct { - Mode ResourceMode `json:"mode"` - Type string `json:"type"` - Name string `json:"name"` - - Provider ProviderRef `json:"provider"` - - Pos SourcePos `json:"pos"` -} - -// MapKey returns a string that can be used to uniquely identify the receiver -// in a map[string]*Resource. -func (r *Resource) MapKey() string { - switch r.Mode { - case ManagedResourceMode: - return fmt.Sprintf("%s.%s", r.Type, r.Name) - case DataResourceMode: - return fmt.Sprintf("data.%s.%s", r.Type, r.Name) - default: - // should never happen - return fmt.Sprintf("[invalid_mode!].%s.%s", r.Type, r.Name) - } -} - -// ResourceMode represents the "mode" of a resource, which is used to -// distinguish between managed resources ("resource" blocks in config) and -// data resources ("data" blocks in config). -type ResourceMode rune - -const InvalidResourceMode ResourceMode = 0 -const ManagedResourceMode ResourceMode = 'M' -const DataResourceMode ResourceMode = 'D' - -func (m ResourceMode) String() string { - switch m { - case ManagedResourceMode: - return "managed" - case DataResourceMode: - return "data" - default: - return "" - } -} - -// MarshalJSON implements encoding/json.Marshaler. -func (m ResourceMode) MarshalJSON() ([]byte, error) { - return []byte(strconv.Quote(m.String())), nil -} - -func resourceTypeDefaultProviderName(typeName string) string { - if underPos := strings.IndexByte(typeName, '_'); underPos != -1 { - return typeName[:underPos] - } - return typeName -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/schema.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/schema.go deleted file mode 100644 index fd6ca9e70d5..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/schema.go +++ /dev/null @@ -1,106 +0,0 @@ -package tfconfig - -import ( - "github.com/hashicorp/hcl/v2" -) - -var rootSchema = &hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "terraform", - LabelNames: nil, - }, - { - Type: "variable", - LabelNames: []string{"name"}, - }, - { - Type: "output", - LabelNames: []string{"name"}, - }, - { - Type: "provider", - LabelNames: []string{"name"}, - }, - { - Type: "resource", - LabelNames: []string{"type", "name"}, - }, - { - Type: "data", - LabelNames: []string{"type", "name"}, - }, - { - Type: "module", - LabelNames: []string{"name"}, - }, - }, -} - -var terraformBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "required_version", - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "required_providers", - }, - }, -} - -var providerConfigSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "version", - }, - { - Name: "alias", - }, - }, -} - -var variableSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "type", - }, - { - Name: "description", - }, - { - Name: "default", - }, - }, -} - -var outputSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "description", - }, - }, -} - -var moduleCallSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "source", - }, - { - Name: "version", - }, - { - Name: "providers", - }, - }, -} - -var resourceSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "provider", - }, - }, -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/source_pos.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/source_pos.go deleted file mode 100644 index 548c9f9a391..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/source_pos.go +++ /dev/null @@ -1,50 +0,0 @@ -package tfconfig - -import ( - legacyhcltoken "github.com/hashicorp/hcl/hcl/token" - "github.com/hashicorp/hcl/v2" -) - -// SourcePos is a pointer to a particular location in a source file. -// -// This type is embedded into other structs to allow callers to locate the -// definition of each described module element. The SourcePos of an element -// is usually the first line of its definition, although the definition can -// be a little "fuzzy" with JSON-based config files. -type SourcePos struct { - Filename string `json:"filename"` - Line int `json:"line"` -} - -func sourcePos(filename string, line int) SourcePos { - return SourcePos{ - Filename: filename, - Line: line, - } -} - -func sourcePosHCL(rng hcl.Range) SourcePos { - // We intentionally throw away the column information here because - // current and legacy HCL both disagree on the definition of a column - // and so a line-only reference is the best granularity we can do - // such that the result is consistent between both parsers. - return SourcePos{ - Filename: rng.Filename, - Line: rng.Start.Line, - } -} - -func sourcePosLegacyHCL(pos legacyhcltoken.Pos, filename string) SourcePos { - useFilename := pos.Filename - // We'll try to use the filename given in legacy HCL position, but - // in practice there's no way to actually get this populated via - // the HCL API so it's usually empty except in some specialized - // situations, such as positions in error objects. - if useFilename == "" { - useFilename = filename - } - return SourcePos{ - Filename: useFilename, - Line: pos.Line, - } -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/variable.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/variable.go deleted file mode 100644 index 0f73fc995a8..00000000000 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/variable.go +++ /dev/null @@ -1,16 +0,0 @@ -package tfconfig - -// Variable represents a single variable from a Terraform module. -type Variable struct { - Name string `json:"name"` - Type string `json:"type,omitempty"` - Description string `json:"description,omitempty"` - - // Default is an approximate representation of the default value in - // the native Go type system. The conversion from the value given in - // configuration may be slightly lossy. Only values that can be - // serialized by json.Marshal will be included here. - Default interface{} `json:"default,omitempty"` - - Pos SourcePos `json:"pos"` -} diff --git a/vendor/github.com/hashicorp/terraform-exec/LICENSE b/vendor/github.com/hashicorp/terraform-exec/LICENSE new file mode 100644 index 00000000000..a612ad9813b --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/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-exec/tfinstall/pubkey.go b/vendor/github.com/hashicorp/terraform-exec/tfinstall/pubkey.go new file mode 100644 index 00000000000..a14f88c917f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/tfinstall/pubkey.go @@ -0,0 +1,32 @@ +package tfinstall + +const hashicorpPublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQENBFMORM0BCADBRyKO1MhCirazOSVwcfTr1xUxjPvfxD3hjUwHtjsOy/bT6p9f +W2mRPfwnq2JB5As+paL3UGDsSRDnK9KAxQb0NNF4+eVhr/EJ18s3wwXXDMjpIifq +fIm2WyH3G+aRLTLPIpscUNKDyxFOUbsmgXAmJ46Re1fn8uKxKRHbfa39aeuEYWFA +3drdL1WoUngvED7f+RnKBK2G6ZEpO+LDovQk19xGjiMTtPJrjMjZJ3QXqPvx5wca +KSZLr4lMTuoTI/ZXyZy5bD4tShiZz6KcyX27cD70q2iRcEZ0poLKHyEIDAi3TM5k +SwbbWBFd5RNPOR0qzrb/0p9ksKK48IIfH2FvABEBAAG0K0hhc2hpQ29ycCBTZWN1 +cml0eSA8c2VjdXJpdHlAaGFzaGljb3JwLmNvbT6JAU4EEwEKADgWIQSRpuf4XQXG +VjC+8YlRhS2HNI/8TAUCXn0BIQIbAwULCQgHAgYVCgkICwIEFgIDAQIeAQIXgAAK +CRBRhS2HNI/8TJITCACT2Zu2l8Jo/YLQMs+iYsC3gn5qJE/qf60VWpOnP0LG24rj +k3j4ET5P2ow/o9lQNCM/fJrEB2CwhnlvbrLbNBbt2e35QVWvvxwFZwVcoBQXTXdT ++G2cKS2Snc0bhNF7jcPX1zau8gxLurxQBaRdoL38XQ41aKfdOjEico4ZxQYSrOoC +RbF6FODXj+ZL8CzJFa2Sd0rHAROHoF7WhKOvTrg1u8JvHrSgvLYGBHQZUV23cmXH +yvzITl5jFzORf9TUdSv8tnuAnNsOV4vOA6lj61Z3/0Vgor+ZByfiznonPHQtKYtY +kac1M/Dq2xZYiSf0tDFywgUDIF/IyS348wKmnDGjuQENBFMORM0BCADWj1GNOP4O +wJmJDjI2gmeok6fYQeUbI/+Hnv5Z/cAK80Tvft3noy1oedxaDdazvrLu7YlyQOWA +M1curbqJa6ozPAwc7T8XSwWxIuFfo9rStHQE3QUARxIdziQKTtlAbXI2mQU99c6x +vSueQ/gq3ICFRBwCmPAm+JCwZG+cDLJJ/g6wEilNATSFdakbMX4lHUB2X0qradNO +J66pdZWxTCxRLomPBWa5JEPanbosaJk0+n9+P6ImPiWpt8wiu0Qzfzo7loXiDxo/ +0G8fSbjYsIF+skY+zhNbY1MenfIPctB9X5iyW291mWW7rhhZyuqqxN2xnmPPgFmi +QGd+8KVodadHABEBAAGJATwEGAECACYCGwwWIQSRpuf4XQXGVjC+8YlRhS2HNI/8 +TAUCXn0BRAUJEvOKdwAKCRBRhS2HNI/8TEzUB/9pEHVwtTxL8+VRq559Q0tPOIOb +h3b+GroZRQGq/tcQDVbYOO6cyRMR9IohVJk0b9wnnUHoZpoA4H79UUfIB4sZngma +enL/9magP1uAHxPxEa5i/yYqR0MYfz4+PGdvqyj91NrkZm3WIpwzqW/KZp8YnD77 +VzGVodT8xqAoHW+bHiza9Jmm9Rkf5/0i0JY7GXoJgk4QBG/Fcp0OR5NUWxN3PEM0 +dpeiU4GI5wOz5RAIOvSv7u1h0ZxMnJG4B4MKniIAr4yD7WYYZh/VxEPeiS/E1CVx +qHV5VVCoEIoYVHIuFIyFu1lIcei53VD6V690rmn0bp4A5hs+kErhThvkok3c +=+mCN +-----END PGP PUBLIC KEY BLOCK-----` diff --git a/vendor/github.com/hashicorp/terraform-exec/tfinstall/tfinstall.go b/vendor/github.com/hashicorp/terraform-exec/tfinstall/tfinstall.go new file mode 100644 index 00000000000..0330f03b650 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/tfinstall/tfinstall.go @@ -0,0 +1,287 @@ +package tfinstall + +import ( + "fmt" + "io/ioutil" + "log" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + + "github.com/hashicorp/go-checkpoint" + "github.com/hashicorp/go-getter" + "github.com/hashicorp/go-version" + "golang.org/x/crypto/openpgp" +) + +const baseUrl = "https://releases.hashicorp.com/terraform" + +type ExecPathFinder interface { + ExecPath() (string, error) +} + +type ExactPathOption struct { + execPath string +} + +func ExactPath(execPath string) *ExactPathOption { + opt := &ExactPathOption{ + execPath: execPath, + } + return opt +} + +func (opt *ExactPathOption) ExecPath() (string, error) { + if _, err := os.Stat(opt.execPath); err != nil { + // fall through to the next strategy if the local path does not exist + return "", nil + } + return opt.execPath, nil +} + +type LookPathOption struct { +} + +func LookPath() *LookPathOption { + opt := &LookPathOption{} + + return opt +} + +func (opt *LookPathOption) ExecPath() (string, error) { + p, err := exec.LookPath("terraform") + if err != nil { + if notFoundErr, ok := err.(*exec.Error); ok && notFoundErr.Err == exec.ErrNotFound { + log.Printf("[WARN] could not locate a terraform executable on system path; continuing") + return "", nil + } + return "", err + } + return p, nil +} + +type LatestVersionOption struct { + forceCheckpoint bool + installDir string +} + +func LatestVersion(installDir string, forceCheckpoint bool) *LatestVersionOption { + opt := &LatestVersionOption{ + forceCheckpoint: forceCheckpoint, + installDir: installDir, + } + + return opt +} + +func (opt *LatestVersionOption) ExecPath() (string, error) { + v, err := latestVersion(opt.forceCheckpoint) + if err != nil { + return "", err + } + + return downloadWithVerification(v, opt.installDir) +} + +type ExactVersionOption struct { + tfVersion string + installDir string +} + +func ExactVersion(tfVersion string, installDir string) *ExactVersionOption { + opt := &ExactVersionOption{ + tfVersion: tfVersion, + installDir: installDir, + } + + return opt +} + +func (opt *ExactVersionOption) ExecPath() (string, error) { + // validate version + _, err := version.NewVersion(opt.tfVersion) + if err != nil { + return "", err + } + + return downloadWithVerification(opt.tfVersion, opt.installDir) +} + +func Find(opts ...ExecPathFinder) (string, error) { + var terraformPath string + + // go through the options in order + // until a valid terraform executable is found + for _, opt := range opts { + p, err := opt.ExecPath() + if err != nil { + return "", fmt.Errorf("unexpected error: %s", err) + } + + if p == "" { + // strategy did not locate an executable - fall through to next + continue + } else { + terraformPath = p + break + } + } + + err := runTerraformVersion(terraformPath) + if err != nil { + return "", fmt.Errorf("executable found at path %s is not terraform: %s", terraformPath, err) + } + + if terraformPath == "" { + return "", fmt.Errorf("could not find terraform executable") + } + + return terraformPath, nil +} + +func downloadWithVerification(tfVersion string, installDir string) (string, error) { + osName := runtime.GOOS + archName := runtime.GOARCH + + // setup: ensure we have a place to put our downloaded terraform binary + var tfDir string + var err error + if installDir == "" { + tfDir, err = ioutil.TempDir("", "tfexec") + if err != nil { + return "", fmt.Errorf("failed to create temp dir: %s", err) + } + } else { + if _, err := os.Stat(installDir); err != nil { + return "", fmt.Errorf("could not access directory %s for installing Terraform: %s", installDir, err) + } + tfDir = installDir + + } + + // setup: getter client + httpHeader := make(http.Header) + httpHeader.Set("User-Agent", "HashiCorp-tfinstall/"+Version) + httpGetter := &getter.HttpGetter{ + Netrc: true, + } + client := getter.Client{ + Getters: map[string]getter.Getter{ + "https": httpGetter, + }, + } + client.Mode = getter.ClientModeAny + + // firstly, download and verify the signature of the checksum file + + sumsTmpDir, err := ioutil.TempDir("", "tfinstall") + if err != nil { + return "", err + } + defer os.RemoveAll(sumsTmpDir) + + sumsFilename := "terraform_" + tfVersion + "_SHA256SUMS" + sumsSigFilename := sumsFilename + ".sig" + + sumsUrl := fmt.Sprintf("%s/%s/%s", + baseUrl, tfVersion, sumsFilename) + sumsSigUrl := fmt.Sprintf("%s/%s/%s", + baseUrl, tfVersion, sumsSigFilename) + + client.Src = sumsUrl + client.Dst = sumsTmpDir + err = client.Get() + if err != nil { + return "", fmt.Errorf("error fetching checksums: %s", err) + } + + client.Src = sumsSigUrl + err = client.Get() + if err != nil { + return "", fmt.Errorf("error fetching checksums signature: %s", err) + } + + sumsPath := filepath.Join(sumsTmpDir, sumsFilename) + sumsSigPath := filepath.Join(sumsTmpDir, sumsSigFilename) + + err = verifySumsSignature(sumsPath, sumsSigPath) + if err != nil { + return "", err + } + + // secondly, download Terraform itself, verifying the checksum + url := tfUrl(tfVersion, osName, archName) + client.Src = url + client.Dst = tfDir + client.Mode = getter.ClientModeDir + err = client.Get() + if err != nil { + return "", err + } + + return filepath.Join(tfDir, "terraform"), nil +} + +func tfUrl(tfVersion, osName, archName string) string { + sumsFilename := "terraform_" + tfVersion + "_SHA256SUMS" + sumsUrl := fmt.Sprintf("%s/%s/%s", + baseUrl, tfVersion, sumsFilename) + return fmt.Sprintf( + "%s/%s/terraform_%s_%s_%s.zip?checksum=file:%s", + baseUrl, tfVersion, tfVersion, osName, archName, sumsUrl, + ) +} + +func latestVersion(forceCheckpoint bool) (string, error) { + resp, err := checkpoint.Check(&checkpoint.CheckParams{ + Product: "terraform", + Force: forceCheckpoint, + }) + if err != nil { + return "", err + } + + if resp.CurrentVersion == "" { + return "", fmt.Errorf("could not determine latest version of terraform using checkpoint: CHECKPOINT_DISABLE may be set") + } + + return resp.CurrentVersion, nil +} + +// verifySumsSignature downloads SHA256SUMS and SHA256SUMS.sig and verifies +// the signature using the HashiCorp public key. +func verifySumsSignature(sumsPath, sumsSigPath string) error { + el, err := openpgp.ReadArmoredKeyRing(strings.NewReader(hashicorpPublicKey)) + if err != nil { + return err + } + data, err := os.Open(sumsPath) + if err != nil { + return err + } + sig, err := os.Open(sumsSigPath) + if err != nil { + return err + } + _, err = openpgp.CheckDetachedSignature(el, data, sig) + + return err +} + +func runTerraformVersion(execPath string) error { + cmd := exec.Command(execPath, "version") + + out, err := cmd.Output() + if err != nil { + return err + } + + if !strings.HasPrefix(string(out), "Terraform v") { + return fmt.Errorf("located executable at %s, but output of `terraform version` was:\n%s", execPath, out) + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-exec/tfinstall/version.go b/vendor/github.com/hashicorp/terraform-exec/tfinstall/version.go new file mode 100644 index 00000000000..d13844aa07c --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-exec/tfinstall/version.go @@ -0,0 +1,4 @@ +package tfinstall + +// Version is the tfinstall package version, used in user agent headers +const Version = "0.3.0" diff --git a/vendor/github.com/hashicorp/terraform-json/schemas.go b/vendor/github.com/hashicorp/terraform-json/schemas.go index e025fbe0410..5dd430a5553 100644 --- a/vendor/github.com/hashicorp/terraform-json/schemas.go +++ b/vendor/github.com/hashicorp/terraform-json/schemas.go @@ -83,6 +83,18 @@ type Schema struct { Block *SchemaBlock `json:"block,omitempty"` } +// SchemaDescriptionKind describes the format type for a particular description's field. +type SchemaDescriptionKind string + +const ( + // SchemaDescriptionKindPlain indicates a string in plain text format. + SchemaDescriptionKindPlain SchemaDescriptionKind = "plaintext" + + // SchemaDescriptionKindMarkdown indicates a Markdown string and may need to be + // processed prior to presentation. + SchemaDescriptionKindMarkdown SchemaDescriptionKind = "markdown" +) + // SchemaBlock represents a nested block within a particular schema. type SchemaBlock struct { // The attributes defined at the particular level of this block. @@ -90,6 +102,14 @@ type SchemaBlock struct { // Any nested blocks within this particular block. NestedBlocks map[string]*SchemaBlockType `json:"block_types,omitempty"` + + // The description for this block and format of the description. If + // no kind is provided, it can be assumed to be plain text. + Description string `json:"description,omitempty"` + DescriptionKind SchemaDescriptionKind `json:"description_kind,omitempty"` + + // If true, this block is deprecated. + Deprecated bool `json:"deprecated,omitempty"` } // SchemaNestingMode is the nesting mode for a particular nested @@ -145,8 +165,13 @@ type SchemaAttribute struct { // The attribute type. AttributeType cty.Type `json:"type,omitempty"` - // The description field for this attribute. - Description string `json:"description,omitempty"` + // The description field for this attribute. If no kind is + // provided, it can be assumed to be plain text. + Description string `json:"description,omitempty"` + DescriptionKind SchemaDescriptionKind `json:"description_kind,omitempty"` + + // If true, this attribute is deprecated. + Deprecated bool `json:"deprecated,omitempty"` // If true, this attribute is required - it has to be entered in // configuration. diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/acctest/helper.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/acctest/helper.go deleted file mode 100644 index 050b9741d07..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/acctest/helper.go +++ /dev/null @@ -1,26 +0,0 @@ -package acctest - -import ( - "os" - - "github.com/hashicorp/terraform-plugin-sdk/plugin" - tftest "github.com/hashicorp/terraform-plugin-test" -) - -var TestHelper *tftest.Helper - -func UseBinaryDriver(name string, providerFunc plugin.ProviderFunc) { - sourceDir, err := os.Getwd() - if err != nil { - panic(err) - } - - if tftest.RunningAsPlugin() { - plugin.Serve(&plugin.ServeOpts{ - ProviderFunc: providerFunc, - }) - os.Exit(0) - } else { - TestHelper = tftest.AutoInitProviderHelper(name, sourceDir) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/acctest/acctest.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/acctest/acctest.go deleted file mode 100644 index 9d31031a470..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/acctest/acctest.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package acctest contains for Terraform Acceptance Tests -package acctest diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/acctest/remotetests.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/acctest/remotetests.go deleted file mode 100644 index 87c60b8be46..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/acctest/remotetests.go +++ /dev/null @@ -1,27 +0,0 @@ -package acctest - -import ( - "net/http" - "os" - "testing" -) - -// SkipRemoteTestsEnvVar is an environment variable that can be set by a user -// running the tests in an environment with limited network connectivity. By -// default, tests requiring internet connectivity make an effort to skip if no -// internet is available, but in some cases the smoke test will pass even -// though the test should still be skipped. -const SkipRemoteTestsEnvVar = "TF_SKIP_REMOTE_TESTS" - -// RemoteTestPrecheck is meant to be run by any unit test that requires -// outbound internet connectivity. The test will be skipped if it's -// unavailable. -func RemoteTestPrecheck(t *testing.T) { - if os.Getenv(SkipRemoteTestsEnvVar) != "" { - t.Skipf("skipping test, %s was set", SkipRemoteTestsEnvVar) - } - - if _, err := http.Get("http://google.com"); err != nil { - t.Skipf("skipping, internet seems to not be available: %s", err) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/computed.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/computed.go deleted file mode 100644 index 54ea5c40206..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/computed.go +++ /dev/null @@ -1,16 +0,0 @@ -package customdiff - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -// ComputedIf returns a CustomizeDiffFunc that sets the given key's new value -// as computed if the given condition function returns true. -func ComputedIf(key string, f ResourceConditionFunc) schema.CustomizeDiffFunc { - return func(d *schema.ResourceDiff, meta interface{}) error { - if f(d, meta) { - d.SetNewComputed(key) - } - return nil - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/condition.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/condition.go deleted file mode 100644 index 1d8e2bfd655..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/condition.go +++ /dev/null @@ -1,60 +0,0 @@ -package customdiff - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -// ResourceConditionFunc is a function type that makes a boolean decision based -// on an entire resource diff. -type ResourceConditionFunc func(d *schema.ResourceDiff, meta interface{}) bool - -// ValueChangeConditionFunc is a function type that makes a boolean decision -// by comparing two values. -type ValueChangeConditionFunc func(old, new, meta interface{}) bool - -// ValueConditionFunc is a function type that makes a boolean decision based -// on a given value. -type ValueConditionFunc func(value, meta interface{}) bool - -// If returns a CustomizeDiffFunc that calls the given condition -// function and then calls the given CustomizeDiffFunc only if the condition -// function returns true. -// -// This can be used to include conditional customizations when composing -// customizations using All and Sequence, but should generally be used only in -// simple scenarios. Prefer directly writing a CustomizeDiffFunc containing -// a conditional branch if the given CustomizeDiffFunc is already a -// locally-defined function, since this avoids obscuring the control flow. -func If(cond ResourceConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { - return func(d *schema.ResourceDiff, meta interface{}) error { - if cond(d, meta) { - return f(d, meta) - } - return nil - } -} - -// IfValueChange returns a CustomizeDiffFunc that calls the given condition -// function with the old and new values of the given key and then calls the -// given CustomizeDiffFunc only if the condition function returns true. -func IfValueChange(key string, cond ValueChangeConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { - return func(d *schema.ResourceDiff, meta interface{}) error { - old, new := d.GetChange(key) - if cond(old, new, meta) { - return f(d, meta) - } - return nil - } -} - -// IfValue returns a CustomizeDiffFunc that calls the given condition -// function with the new values of the given key and then calls the -// given CustomizeDiffFunc only if the condition function returns true. -func IfValue(key string, cond ValueConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { - return func(d *schema.ResourceDiff, meta interface{}) error { - if cond(d.Get(key), meta) { - return f(d, meta) - } - return nil - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/validate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/validate.go deleted file mode 100644 index 0bc2c69505b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/validate.go +++ /dev/null @@ -1,38 +0,0 @@ -package customdiff - -import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -// ValueChangeValidationFunc is a function type that validates the difference -// (or lack thereof) between two values, returning an error if the change -// is invalid. -type ValueChangeValidationFunc func(old, new, meta interface{}) error - -// ValueValidationFunc is a function type that validates a particular value, -// returning an error if the value is invalid. -type ValueValidationFunc func(value, meta interface{}) error - -// ValidateChange returns a CustomizeDiffFunc that applies the given validation -// function to the change for the given key, returning any error produced. -func ValidateChange(key string, f ValueChangeValidationFunc) schema.CustomizeDiffFunc { - return func(d *schema.ResourceDiff, meta interface{}) error { - old, new := d.GetChange(key) - return f(old, new, meta) - } -} - -// ValidateValue returns a CustomizeDiffFunc that applies the given validation -// function to value of the given key, returning any error produced. -// -// This should generally not be used since it is functionally equivalent to -// a validation function applied directly to the schema attribute in question, -// but is provided for situations where composing multiple CustomizeDiffFuncs -// together makes intent clearer than spreading that validation across the -// schema. -func ValidateValue(key string, f ValueValidationFunc) schema.CustomizeDiffFunc { - return func(d *schema.ResourceDiff, meta interface{}) error { - val := d.Get(key) - return f(val, meta) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/logging.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/logging.go deleted file mode 100644 index 6bd92f77784..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/logging.go +++ /dev/null @@ -1,100 +0,0 @@ -package logging - -import ( - "io" - "io/ioutil" - "log" - "os" - "strings" - "syscall" - - "github.com/hashicorp/logutils" -) - -// These are the environmental variables that determine if we log, and if -// we log whether or not the log should go to a file. -const ( - EnvLog = "TF_LOG" // Set to True - EnvLogFile = "TF_LOG_PATH" // Set to a file -) - -var ValidLevels = []logutils.LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"} - -// LogOutput determines where we should send logs (if anywhere) and the log level. -func LogOutput() (logOutput io.Writer, err error) { - logOutput = ioutil.Discard - - logLevel := LogLevel() - if logLevel == "" { - return - } - - logOutput = os.Stderr - if logPath := os.Getenv(EnvLogFile); logPath != "" { - var err error - logOutput, err = os.OpenFile(logPath, syscall.O_CREAT|syscall.O_RDWR|syscall.O_APPEND, 0666) - if err != nil { - return nil, err - } - } - - // This was the default since the beginning - logOutput = &logutils.LevelFilter{ - Levels: ValidLevels, - MinLevel: logutils.LogLevel(logLevel), - Writer: logOutput, - } - - return -} - -// SetOutput checks for a log destination with LogOutput, and calls -// log.SetOutput with the result. If LogOutput returns nil, SetOutput uses -// ioutil.Discard. Any error from LogOutout is fatal. -func SetOutput() { - out, err := LogOutput() - if err != nil { - log.Fatal(err) - } - - if out == nil { - out = ioutil.Discard - } - - log.SetOutput(out) -} - -// LogLevel returns the current log level string based the environment vars -func LogLevel() string { - envLevel := os.Getenv(EnvLog) - if envLevel == "" { - return "" - } - - logLevel := "TRACE" - if isValidLogLevel(envLevel) { - // allow following for better ux: info, Info or INFO - logLevel = strings.ToUpper(envLevel) - } else { - log.Printf("[WARN] Invalid log level: %q. Defaulting to level: TRACE. Valid levels are: %+v", - envLevel, ValidLevels) - } - - return logLevel -} - -// IsDebugOrHigher returns whether or not the current log level is debug or trace -func IsDebugOrHigher() bool { - level := string(LogLevel()) - return level == "DEBUG" || level == "TRACE" -} - -func isValidLogLevel(level string) bool { - for _, l := range ValidLevels { - if strings.ToUpper(level) == string(l) { - return true - } - } - - return false -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/grpc_test_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/grpc_test_provider.go deleted file mode 100644 index db12cee2021..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/grpc_test_provider.go +++ /dev/null @@ -1,43 +0,0 @@ -package resource - -import ( - "context" - "net" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/internal/helper/plugin" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - proto "github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5" - tfplugin "github.com/hashicorp/terraform-plugin-sdk/plugin" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "google.golang.org/grpc" - "google.golang.org/grpc/test/bufconn" -) - -// GRPCTestProvider takes a legacy ResourceProvider, wraps it in the new GRPC -// shim and starts it in a grpc server using an inmem connection. It returns a -// GRPCClient for this new server to test the shimmed resource provider. -func GRPCTestProvider(rp terraform.ResourceProvider) providers.Interface { - listener := bufconn.Listen(256 * 1024) - grpcServer := grpc.NewServer() - - p := plugin.NewGRPCProviderServerShim(rp) - proto.RegisterProviderServer(grpcServer, p) - - go grpcServer.Serve(listener) - - conn, err := grpc.Dial("", grpc.WithDialer(func(string, time.Duration) (net.Conn, error) { - return listener.Dial() - }), grpc.WithInsecure()) - if err != nil { - panic(err) - } - - var pp tfplugin.GRPCProviderPlugin - client, _ := pp.GRPCClient(context.Background(), nil, conn) - - grpcClient := client.(*tfplugin.GRPCProvider) - grpcClient.TestServer = grpcServer - - return grpcClient -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/map.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/map.go deleted file mode 100644 index 4befdb353f0..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/map.go +++ /dev/null @@ -1,140 +0,0 @@ -package resource - -import ( - "fmt" - "sort" - - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -// Map is a map of resources that are supported, and provides helpers for -// more easily implementing a ResourceProvider. -type Map struct { - Mapping map[string]Resource -} - -func (m *Map) Validate( - t string, c *terraform.ResourceConfig) ([]string, []error) { - r, ok := m.Mapping[t] - if !ok { - return nil, []error{fmt.Errorf("Unknown resource type: %s", t)} - } - - // If there is no validator set, then it is valid - if r.ConfigValidator == nil { - return nil, nil - } - - return r.ConfigValidator.Validate(c) -} - -// Apply performs a create or update depending on the diff, and calls -// the proper function on the matching Resource. -func (m *Map) Apply( - info *terraform.InstanceInfo, - s *terraform.InstanceState, - d *terraform.InstanceDiff, - meta interface{}) (*terraform.InstanceState, error) { - r, ok := m.Mapping[info.Type] - if !ok { - return nil, fmt.Errorf("Unknown resource type: %s", info.Type) - } - - if d.Destroy || d.RequiresNew() { - if s.ID != "" { - // Destroy the resource if it is created - err := r.Destroy(s, meta) - if err != nil { - return s, err - } - - s.ID = "" - } - - // If we're only destroying, and not creating, then return now. - // Otherwise, we continue so that we can create a new resource. - if !d.RequiresNew() { - return nil, nil - } - } - - var result *terraform.InstanceState - var err error - if s.ID == "" { - result, err = r.Create(s, d, meta) - } else { - if r.Update == nil { - return s, fmt.Errorf( - "Resource type '%s' doesn't support update", - info.Type) - } - - result, err = r.Update(s, d, meta) - } - if result != nil { - if result.Attributes == nil { - result.Attributes = make(map[string]string) - } - - result.Attributes["id"] = result.ID - } - - return result, err -} - -// Diff performs a diff on the proper resource type. -func (m *Map) Diff( - info *terraform.InstanceInfo, - s *terraform.InstanceState, - c *terraform.ResourceConfig, - meta interface{}) (*terraform.InstanceDiff, error) { - r, ok := m.Mapping[info.Type] - if !ok { - return nil, fmt.Errorf("Unknown resource type: %s", info.Type) - } - - return r.Diff(s, c, meta) -} - -// Refresh performs a Refresh on the proper resource type. -// -// Refresh on the Resource won't be called if the state represents a -// non-created resource (ID is blank). -// -// An error is returned if the resource isn't registered. -func (m *Map) Refresh( - info *terraform.InstanceInfo, - s *terraform.InstanceState, - meta interface{}) (*terraform.InstanceState, error) { - // If the resource isn't created, don't refresh. - if s.ID == "" { - return s, nil - } - - r, ok := m.Mapping[info.Type] - if !ok { - return nil, fmt.Errorf("Unknown resource type: %s", info.Type) - } - - return r.Refresh(s, meta) -} - -// Resources returns all the resources that are supported by this -// resource map and can be used to satisfy the Resources method of -// a ResourceProvider. -func (m *Map) Resources() []terraform.ResourceType { - ks := make([]string, 0, len(m.Mapping)) - for k := range m.Mapping { - ks = append(ks, k) - } - sort.Strings(ks) - - rs := make([]terraform.ResourceType, 0, len(m.Mapping)) - for _, k := range ks { - rs = append(rs, terraform.ResourceType{ - Name: k, - }) - } - - return rs -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/resource.go deleted file mode 100644 index 80782413b43..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/resource.go +++ /dev/null @@ -1,49 +0,0 @@ -package resource - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/helper/config" - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -type Resource struct { - ConfigValidator *config.Validator - Create CreateFunc - Destroy DestroyFunc - Diff DiffFunc - Refresh RefreshFunc - Update UpdateFunc -} - -// CreateFunc is a function that creates a resource that didn't previously -// exist. -type CreateFunc func( - *terraform.InstanceState, - *terraform.InstanceDiff, - interface{}) (*terraform.InstanceState, error) - -// DestroyFunc is a function that destroys a resource that previously -// exists using the state. -type DestroyFunc func( - *terraform.InstanceState, - interface{}) error - -// DiffFunc is a function that performs a diff of a resource. -type DiffFunc func( - *terraform.InstanceState, - *terraform.ResourceConfig, - interface{}) (*terraform.InstanceDiff, error) - -// RefreshFunc is a function that performs a refresh of a specific type -// of resource. -type RefreshFunc func( - *terraform.InstanceState, - interface{}) (*terraform.InstanceState, error) - -// UpdateFunc is a function that is called to update a resource that -// previously existed. The difference between this and CreateFunc is that -// the diff is guaranteed to only contain attributes that don't require -// a new resource. -type UpdateFunc func( - *terraform.InstanceState, - *terraform.InstanceDiff, - interface{}) (*terraform.InstanceState, error) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/state.go deleted file mode 100644 index 88a839664c1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/state.go +++ /dev/null @@ -1,259 +0,0 @@ -package resource - -import ( - "log" - "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. -// -// It returns three results. `result` is any object that will be returned -// as the final object after waiting for state change. This allows you to -// return the final updated object, for example an EC2 instance after refreshing -// it. -// -// `state` is the latest state of that object. And `err` is any error that -// may have happened while refreshing the state. -type StateRefreshFunc func() (result interface{}, state string, err error) - -// StateChangeConf is the configuration struct used for `WaitForState`. -type StateChangeConf struct { - Delay time.Duration // Wait this time before starting checks - Pending []string // States that are "allowed" and will continue trying - Refresh StateRefreshFunc // Refreshes the current state - Target []string // Target state - Timeout time.Duration // The amount of time to wait before timeout - MinTimeout time.Duration // Smallest time to wait before refreshes - PollInterval time.Duration // Override MinTimeout/backoff and only poll this often - NotFoundChecks int // Number of times to allow not found - - // This is to work around inconsistent APIs - ContinuousTargetOccurence int // Number of times the Target state has to occur continuously -} - -// WaitForState watches an object and waits for it to achieve the state -// specified in the configuration using the specified Refresh() func, -// waiting the number of seconds specified in the timeout configuration. -// -// If the Refresh function returns an error, exit immediately with that error. -// -// If the Refresh function returns a state other than the Target state or one -// listed in Pending, return immediately with an error. -// -// If the Timeout is exceeded before reaching the Target state, return an -// error. -// -// Otherwise, the result is the result of the first call to the Refresh function to -// reach the target state. -func (conf *StateChangeConf) WaitForState() (interface{}, error) { - log.Printf("[DEBUG] Waiting for state to become: %s", conf.Target) - - notfoundTick := 0 - targetOccurence := 0 - - // Set a default for times to check for not found - if conf.NotFoundChecks == 0 { - conf.NotFoundChecks = 20 - } - - if conf.ContinuousTargetOccurence == 0 { - conf.ContinuousTargetOccurence = 1 - } - - type Result struct { - Result interface{} - State string - Error error - Done bool - } - - // 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(resCh) - - time.Sleep(conf.Delay) - - // 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: res, - State: currentState, - Error: err, - } - - 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++ - if conf.ContinuousTargetOccurence == targetOccurence { - result.Done = true - resCh <- result - return - } - 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++ - if notfoundTick > conf.NotFoundChecks { - result.Error = &NotFoundError{ - LastError: err, - Retries: notfoundTick, - } - resCh <- result - return - } - } else { - // Reset the counter for when a resource isn't found - notfoundTick = 0 - found := false - - for _, allowed := range conf.Target { - if currentState == allowed { - found = true - targetOccurence++ - if conf.ContinuousTargetOccurence == targetOccurence { - result.Done = true - resCh <- result - return - } - continue - } - } - - for _, allowed := range conf.Pending { - if currentState == allowed { - found = true - targetOccurence = 0 - break - } - } - - if !found && len(conf.Pending) > 0 { - result.Error = &UnexpectedStateError{ - LastError: err, - State: result.State, - ExpectedState: conf.Target, - } - 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 { - wait = conf.PollInterval - } else { - if wait < conf.MinTimeout { - wait = conf.MinTimeout - } else if wait > 10*time.Second { - wait = 10 * time.Second - } - } - - log.Printf("[TRACE] Waiting %s before next try", wait) - } - }() - - // 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/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/state_shim.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/state_shim.go deleted file mode 100644 index 768b48470b0..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/state_shim.go +++ /dev/null @@ -1,465 +0,0 @@ -package resource - -import ( - "encoding/json" - "fmt" - "strconv" - - tfjson "github.com/hashicorp/terraform-json" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/zclconf/go-cty/cty" -) - -// shimState takes a new *states.State and reverts it to a legacy state for the provider ACC tests -func shimNewState(newState *states.State, providers map[string]terraform.ResourceProvider) (*terraform.State, error) { - state := terraform.NewState() - - // in the odd case of a nil state, let the helper packages handle it - if newState == nil { - return nil, nil - } - - for _, newMod := range newState.Modules { - mod := state.AddModule(newMod.Addr) - - for name, out := range newMod.OutputValues { - outputType := "" - val := hcl2shim.ConfigValueFromHCL2(out.Value) - ty := out.Value.Type() - switch { - case ty == cty.String: - outputType = "string" - case ty.IsTupleType() || ty.IsListType(): - outputType = "list" - case ty.IsMapType(): - outputType = "map" - } - - mod.Outputs[name] = &terraform.OutputState{ - Type: outputType, - Value: val, - Sensitive: out.Sensitive, - } - } - - for _, res := range newMod.Resources { - resType := res.Addr.Type - providerType := res.ProviderConfig.ProviderConfig.Type - - resource := getResource(providers, providerType, res.Addr) - - for key, i := range res.Instances { - resState := &terraform.ResourceState{ - Type: resType, - Provider: res.ProviderConfig.String(), - } - - // We should always have a Current instance here, but be safe about checking. - if i.Current != nil { - flatmap, err := shimmedAttributes(i.Current, resource) - if err != nil { - return nil, fmt.Errorf("error decoding state for %q: %s", resType, err) - } - - var meta map[string]interface{} - if i.Current.Private != nil { - err := json.Unmarshal(i.Current.Private, &meta) - if err != nil { - return nil, err - } - } - - resState.Primary = &terraform.InstanceState{ - ID: flatmap["id"], - Attributes: flatmap, - Tainted: i.Current.Status == states.ObjectTainted, - Meta: meta, - } - - if i.Current.SchemaVersion != 0 { - if resState.Primary.Meta == nil { - resState.Primary.Meta = map[string]interface{}{} - } - resState.Primary.Meta["schema_version"] = i.Current.SchemaVersion - } - - for _, dep := range i.Current.Dependencies { - resState.Dependencies = append(resState.Dependencies, dep.String()) - } - - // convert the indexes to the old style flapmap indexes - idx := "" - switch key.(type) { - case addrs.IntKey: - // don't add numeric index values to resources with a count of 0 - if len(res.Instances) > 1 { - idx = fmt.Sprintf(".%d", key) - } - case addrs.StringKey: - idx = "." + key.String() - } - - mod.Resources[res.Addr.String()+idx] = resState - } - - // add any deposed instances - for _, dep := range i.Deposed { - flatmap, err := shimmedAttributes(dep, resource) - if err != nil { - return nil, fmt.Errorf("error decoding deposed state for %q: %s", resType, err) - } - - var meta map[string]interface{} - if dep.Private != nil { - err := json.Unmarshal(dep.Private, &meta) - if err != nil { - return nil, err - } - } - - deposed := &terraform.InstanceState{ - ID: flatmap["id"], - Attributes: flatmap, - Tainted: dep.Status == states.ObjectTainted, - Meta: meta, - } - if dep.SchemaVersion != 0 { - deposed.Meta = map[string]interface{}{ - "schema_version": dep.SchemaVersion, - } - } - - resState.Deposed = append(resState.Deposed, deposed) - } - } - } - } - - return state, nil -} - -func getResource(providers map[string]terraform.ResourceProvider, providerName string, addr addrs.Resource) *schema.Resource { - p := providers[providerName] - if p == nil { - panic(fmt.Sprintf("provider %q not found in test step", providerName)) - } - - // this is only for tests, so should only see schema.Providers - provider := p.(*schema.Provider) - - switch addr.Mode { - case addrs.ManagedResourceMode: - resource := provider.ResourcesMap[addr.Type] - if resource != nil { - return resource - } - case addrs.DataResourceMode: - resource := provider.DataSourcesMap[addr.Type] - if resource != nil { - return resource - } - } - - panic(fmt.Sprintf("resource %s not found in test step", addr.Type)) -} - -func shimmedAttributes(instance *states.ResourceInstanceObjectSrc, res *schema.Resource) (map[string]string, error) { - flatmap := instance.AttrsFlat - if flatmap != nil { - return flatmap, nil - } - - // if we have json attrs, they need to be decoded - rio, err := instance.Decode(res.CoreConfigSchema().ImpliedType()) - if err != nil { - return nil, err - } - - instanceState, err := res.ShimInstanceStateFromValue(rio.Value) - if err != nil { - return nil, err - } - - return instanceState.Attributes, nil -} - -type shimmedState struct { - state *terraform.State -} - -func shimStateFromJson(jsonState *tfjson.State) (*terraform.State, error) { - state := terraform.NewState() - state.TFVersion = jsonState.TerraformVersion - - if jsonState.Values == nil { - // the state is empty - return state, nil - } - - for key, output := range jsonState.Values.Outputs { - os, err := shimOutputState(output) - if err != nil { - return nil, err - } - state.RootModule().Outputs[key] = os - } - - ss := &shimmedState{state} - err := ss.shimStateModule(jsonState.Values.RootModule) - if err != nil { - return nil, err - } - - return state, nil -} - -func shimOutputState(so *tfjson.StateOutput) (*terraform.OutputState, error) { - os := &terraform.OutputState{ - Sensitive: so.Sensitive, - } - - switch v := so.Value.(type) { - case string: - os.Type = "string" - os.Value = v - return os, nil - case []interface{}: - os.Type = "list" - if len(v) == 0 { - os.Value = v - return os, nil - } - switch firstElem := v[0].(type) { - case string: - elements := make([]interface{}, len(v)) - for i, el := range v { - elements[i] = el.(string) - } - os.Value = elements - case bool: - elements := make([]interface{}, len(v)) - for i, el := range v { - elements[i] = el.(bool) - } - os.Value = elements - // unmarshalled number from JSON will always be float64 - case float64: - elements := make([]interface{}, len(v)) - for i, el := range v { - elements[i] = el.(float64) - } - os.Value = elements - case []interface{}: - os.Value = v - case map[string]interface{}: - os.Value = v - default: - return nil, fmt.Errorf("unexpected output list element type: %T", firstElem) - } - return os, nil - case map[string]interface{}: - os.Type = "map" - os.Value = v - return os, nil - case bool: - os.Type = "string" - os.Value = strconv.FormatBool(v) - return os, nil - // unmarshalled number from JSON will always be float64 - case float64: - os.Type = "string" - os.Value = strconv.FormatFloat(v, 'f', -1, 64) - return os, nil - } - - return nil, fmt.Errorf("unexpected output type: %T", so.Value) -} - -func (ss *shimmedState) shimStateModule(sm *tfjson.StateModule) error { - var path addrs.ModuleInstance - - if sm.Address == "" { - path = addrs.RootModuleInstance - } else { - var diags tfdiags.Diagnostics - path, diags = addrs.ParseModuleInstanceStr(sm.Address) - if diags.HasErrors() { - return diags.Err() - } - } - - mod := ss.state.AddModule(path) - for _, res := range sm.Resources { - resourceState, err := shimResourceState(res) - if err != nil { - return err - } - - key, err := shimResourceStateKey(res) - if err != nil { - return err - } - - mod.Resources[key] = resourceState - } - - if len(sm.ChildModules) > 0 { - return fmt.Errorf("Modules are not supported. Found %d modules.", - len(sm.ChildModules)) - } - return nil -} - -func shimResourceStateKey(res *tfjson.StateResource) (string, error) { - if res.Index == nil { - return res.Address, nil - } - - var mode terraform.ResourceMode - switch res.Mode { - case tfjson.DataResourceMode: - mode = terraform.DataResourceMode - case tfjson.ManagedResourceMode: - mode = terraform.ManagedResourceMode - default: - return "", fmt.Errorf("unexpected resource mode for %q", res.Address) - } - - var index int - switch idx := res.Index.(type) { - case float64: - index = int(idx) - default: - return "", fmt.Errorf("unexpected index type (%T) for %q, "+ - "for_each is not supported", res.Index, res.Address) - } - - rsk := &terraform.ResourceStateKey{ - Mode: mode, - Type: res.Type, - Name: res.Name, - Index: index, - } - - return rsk.String(), nil -} - -func shimResourceState(res *tfjson.StateResource) (*terraform.ResourceState, error) { - sf := &shimmedFlatmap{} - err := sf.FromMap(res.AttributeValues) - if err != nil { - return nil, err - } - attributes := sf.Flatmap() - - if _, ok := attributes["id"]; !ok { - return nil, fmt.Errorf("no %q found in attributes", "id") - } - - return &terraform.ResourceState{ - Provider: res.ProviderName, - Type: res.Type, - Primary: &terraform.InstanceState{ - ID: attributes["id"], - Attributes: attributes, - Meta: map[string]interface{}{ - "schema_version": int(res.SchemaVersion), - }, - Tainted: res.Tainted, - }, - Dependencies: res.DependsOn, - }, nil -} - -type shimmedFlatmap struct { - m map[string]string -} - -func (sf *shimmedFlatmap) FromMap(attributes map[string]interface{}) error { - if sf.m == nil { - sf.m = make(map[string]string, len(attributes)) - } - - return sf.AddMap("", attributes) -} - -func (sf *shimmedFlatmap) AddMap(prefix string, m map[string]interface{}) error { - for key, value := range m { - k := key - if prefix != "" { - k = fmt.Sprintf("%s.%s", prefix, key) - } - - err := sf.AddEntry(k, value) - if err != nil { - return err - } - } - - mapLength := "%" - if prefix != "" { - mapLength = fmt.Sprintf("%s.%s", prefix, "%") - } - - sf.AddEntry(mapLength, strconv.Itoa(len(m))) - - return nil -} - -func (sf *shimmedFlatmap) AddSlice(name string, elements []interface{}) error { - for i, elem := range elements { - key := fmt.Sprintf("%s.%d", name, i) - err := sf.AddEntry(key, elem) - if err != nil { - return err - } - } - - sliceLength := fmt.Sprintf("%s.#", name) - sf.AddEntry(sliceLength, strconv.Itoa(len(elements))) - - return nil -} - -func (sf *shimmedFlatmap) AddEntry(key string, value interface{}) error { - switch el := value.(type) { - case nil: - // omit the entry - return nil - case bool: - sf.m[key] = strconv.FormatBool(el) - case float64: - sf.m[key] = strconv.FormatFloat(el, 'f', -1, 64) - case string: - sf.m[key] = el - case map[string]interface{}: - err := sf.AddMap(key, el) - if err != nil { - return err - } - case []interface{}: - err := sf.AddSlice(key, el) - if err != nil { - return err - } - default: - // This should never happen unless terraform-json - // changes how attributes (types) are represented. - // - // We handle all types which the JSON unmarshaler - // can possibly produce - // https://golang.org/pkg/encoding/json/#Unmarshal - - return fmt.Errorf("%q: unexpected type (%T)", key, el) - } - return nil -} - -func (sf *shimmedFlatmap) Flatmap() map[string]string { - return sf.m -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing.go deleted file mode 100644 index 7b331d80d13..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing.go +++ /dev/null @@ -1,1421 +0,0 @@ -package resource - -import ( - "bytes" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "log" - "os" - "path/filepath" - "reflect" - "regexp" - "strings" - "syscall" - "testing" - - "github.com/davecgh/go-spew/spew" - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/logutils" - "github.com/hashicorp/terraform-plugin-sdk/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/logging" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/command/format" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload" - "github.com/hashicorp/terraform-plugin-sdk/internal/initwd" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/mitchellh/colorstring" -) - -// flagSweep is a flag available when running tests on the command line. It -// contains a comma seperated list of regions to for the sweeper functions to -// run in. This flag bypasses the normal Test path and instead runs functions designed to -// clean up any leaked resources a testing environment could have created. It is -// a best effort attempt, and relies on Provider authors to implement "Sweeper" -// methods for resources. - -// Adding Sweeper methods with AddTestSweepers will -// construct a list of sweeper funcs to be called here. We iterate through -// regions provided by the sweep flag, and for each region we iterate through the -// tests, and exit on any errors. At time of writing, sweepers are ran -// sequentially, however they can list dependencies to be ran first. We track -// the sweepers that have been ran, so as to not run a sweeper twice for a given -// region. -// -// WARNING: -// Sweepers are designed to be destructive. You should not use the -sweep flag -// in any environment that is not strictly a test environment. Resources will be -// destroyed. - -var flagSweep = flag.String("sweep", "", "List of Regions to run available Sweepers") -var flagSweepAllowFailures = flag.Bool("sweep-allow-failures", false, "Enable to allow Sweeper Tests to continue after failures") -var flagSweepRun = flag.String("sweep-run", "", "Comma seperated list of Sweeper Tests to run") -var sweeperFuncs map[string]*Sweeper - -// type SweeperFunc is a signature for a function that acts as a sweeper. It -// accepts a string for the region that the sweeper is to be ran in. This -// function must be able to construct a valid client for that region. -type SweeperFunc func(r string) error - -type Sweeper struct { - // Name for sweeper. Must be unique to be ran by the Sweeper Runner - Name string - - // Dependencies list the const names of other Sweeper functions that must be ran - // prior to running this Sweeper. This is an ordered list that will be invoked - // recursively at the helper/resource level - Dependencies []string - - // Sweeper function that when invoked sweeps the Provider of specific - // resources - F SweeperFunc -} - -func init() { - sweeperFuncs = make(map[string]*Sweeper) -} - -// AddTestSweepers function adds a given name and Sweeper configuration -// pair to the internal sweeperFuncs map. Invoke this function to register a -// resource sweeper to be available for running when the -sweep flag is used -// with `go test`. Sweeper names must be unique to help ensure a given sweeper -// is only ran once per run. -func AddTestSweepers(name string, s *Sweeper) { - if _, ok := sweeperFuncs[name]; ok { - log.Fatalf("[ERR] Error adding (%s) to sweeperFuncs: function already exists in map", name) - } - - sweeperFuncs[name] = s -} - -func TestMain(m *testing.M) { - flag.Parse() - if *flagSweep != "" { - // parse flagSweep contents for regions to run - regions := strings.Split(*flagSweep, ",") - - // get filtered list of sweepers to run based on sweep-run flag - sweepers := filterSweepers(*flagSweepRun, sweeperFuncs) - - if _, err := runSweepers(regions, sweepers, *flagSweepAllowFailures); err != nil { - os.Exit(1) - } - } else { - if acctest.TestHelper != nil { - defer acctest.TestHelper.Close() - } - os.Exit(m.Run()) - } -} - -func runSweepers(regions []string, sweepers map[string]*Sweeper, allowFailures bool) (map[string]map[string]error, error) { - var sweeperErrorFound bool - sweeperRunList := make(map[string]map[string]error) - - for _, region := range regions { - region = strings.TrimSpace(region) - - var regionSweeperErrorFound bool - regionSweeperRunList := make(map[string]error) - - log.Printf("[DEBUG] Running Sweepers for region (%s):\n", region) - for _, sweeper := range sweepers { - if err := runSweeperWithRegion(region, sweeper, sweepers, regionSweeperRunList, allowFailures); err != nil { - if allowFailures { - continue - } - - sweeperRunList[region] = regionSweeperRunList - return sweeperRunList, fmt.Errorf("sweeper (%s) for region (%s) failed: %s", sweeper.Name, region, err) - } - } - - log.Printf("Sweeper Tests ran successfully:\n") - for sweeper, sweeperErr := range regionSweeperRunList { - if sweeperErr == nil { - fmt.Printf("\t- %s\n", sweeper) - } else { - regionSweeperErrorFound = true - } - } - - if regionSweeperErrorFound { - sweeperErrorFound = true - log.Printf("Sweeper Tests ran unsuccessfully:\n") - for sweeper, sweeperErr := range regionSweeperRunList { - if sweeperErr != nil { - fmt.Printf("\t- %s: %s\n", sweeper, sweeperErr) - } - } - } - - sweeperRunList[region] = regionSweeperRunList - } - - if sweeperErrorFound { - return sweeperRunList, errors.New("at least one sweeper failed") - } - - return sweeperRunList, nil -} - -// filterSweepers takes a comma seperated string listing the names of sweepers -// to be ran, and returns a filtered set from the list of all of sweepers to -// run based on the names given. -func filterSweepers(f string, source map[string]*Sweeper) map[string]*Sweeper { - filterSlice := strings.Split(strings.ToLower(f), ",") - if len(filterSlice) == 1 && filterSlice[0] == "" { - // if the filter slice is a single element of "" then no sweeper list was - // given, so just return the full list - return source - } - - sweepers := make(map[string]*Sweeper) - for name := range source { - for _, s := range filterSlice { - if strings.Contains(strings.ToLower(name), s) { - for foundName, foundSweeper := range filterSweeperWithDependencies(name, source) { - sweepers[foundName] = foundSweeper - } - } - } - } - return sweepers -} - -// filterSweeperWithDependencies recursively returns sweeper and all dependencies. -// Since filterSweepers performs fuzzy matching, this function is used -// to perform exact sweeper and dependency lookup. -func filterSweeperWithDependencies(name string, source map[string]*Sweeper) map[string]*Sweeper { - result := make(map[string]*Sweeper) - - currentSweeper, ok := source[name] - if !ok { - log.Printf("[WARN] Sweeper has dependency (%s), but that sweeper was not found", name) - return result - } - - result[name] = currentSweeper - - for _, dependency := range currentSweeper.Dependencies { - for foundName, foundSweeper := range filterSweeperWithDependencies(dependency, source) { - result[foundName] = foundSweeper - } - } - - return result -} - -// runSweeperWithRegion recieves a sweeper and a region, and recursively calls -// itself with that region for every dependency found for that sweeper. If there -// are no dependencies, invoke the contained sweeper fun with the region, and -// add the success/fail status to the sweeperRunList. -func runSweeperWithRegion(region string, s *Sweeper, sweepers map[string]*Sweeper, sweeperRunList map[string]error, allowFailures bool) error { - for _, dep := range s.Dependencies { - if depSweeper, ok := sweepers[dep]; ok { - log.Printf("[DEBUG] Sweeper (%s) has dependency (%s), running..", s.Name, dep) - err := runSweeperWithRegion(region, depSweeper, sweepers, sweeperRunList, allowFailures) - - if err != nil { - if allowFailures { - log.Printf("[ERROR] Error running Sweeper (%s) in region (%s): %s", depSweeper.Name, region, err) - continue - } - - return err - } - } else { - log.Printf("[WARN] Sweeper (%s) has dependency (%s), but that sweeper was not found", s.Name, dep) - } - } - - if _, ok := sweeperRunList[s.Name]; ok { - log.Printf("[DEBUG] Sweeper (%s) already ran in region (%s)", s.Name, region) - return nil - } - - log.Printf("[DEBUG] Running Sweeper (%s) in region (%s)", s.Name, region) - - runE := s.F(region) - - sweeperRunList[s.Name] = runE - - if runE != nil { - log.Printf("[ERROR] Error running Sweeper (%s) in region (%s): %s", s.Name, region, runE) - } - - return runE -} - -const TestEnvVar = "TF_ACC" - -// TestProvider can be implemented by any ResourceProvider to provide custom -// reset functionality at the start of an acceptance test. -// The helper/schema Provider implements this interface. -type TestProvider interface { - TestReset() error -} - -// TestCheckFunc is the callback type used with acceptance tests to check -// the state of a resource. The state passed in is the latest state known, -// or in the case of being after a destroy, it is the last known state when -// it was created. -type TestCheckFunc func(*terraform.State) error - -// ImportStateCheckFunc is the check function for ImportState tests -type ImportStateCheckFunc func([]*terraform.InstanceState) error - -// ImportStateIdFunc is an ID generation function to help with complex ID -// generation for ImportState tests. -type ImportStateIdFunc func(*terraform.State) (string, error) - -// TestCase is a single acceptance test case used to test the apply/destroy -// lifecycle of a resource in a specific configuration. -// -// When the destroy plan is executed, the config from the last TestStep -// is used to plan it. -type TestCase struct { - // IsUnitTest allows a test to run regardless of the TF_ACC - // environment variable. This should be used with care - only for - // fast tests on local resources (e.g. remote state with a local - // backend) but can be used to increase confidence in correct - // operation of Terraform without waiting for a full acctest run. - IsUnitTest bool - - // PreCheck, if non-nil, will be called before any test steps are - // executed. It will only be executed in the case that the steps - // would run, so it can be used for some validation before running - // acceptance tests, such as verifying that keys are setup. - PreCheck func() - - // Providers is the ResourceProvider that will be under test. - // - // Alternately, ProviderFactories can be specified for the providers - // that are valid. This takes priority over Providers. - // - // The end effect of each is the same: specifying the providers that - // are used within the tests. - Providers map[string]terraform.ResourceProvider - ProviderFactories map[string]terraform.ResourceProviderFactory - - // PreventPostDestroyRefresh can be set to true for cases where data sources - // are tested alongside real resources - PreventPostDestroyRefresh bool - - // CheckDestroy is called after the resource is finally destroyed - // to allow the tester to test that the resource is truly gone. - CheckDestroy TestCheckFunc - - // Steps are the apply sequences done within the context of the - // same state. Each step can have its own check to verify correctness. - Steps []TestStep - - // The settings below control the "ID-only refresh test." This is - // an enabled-by-default test that tests that a refresh can be - // refreshed with only an ID to result in the same attributes. - // This validates completeness of Refresh. - // - // IDRefreshName is the name of the resource to check. This will - // default to the first non-nil primary resource in the state. - // - // IDRefreshIgnore is a list of configuration keys that will be ignored. - IDRefreshName string - IDRefreshIgnore []string - - // DisableBinaryDriver forces this test case to run using the legacy test - // driver, even if the binary test driver has been enabled. - // This property will be removed in version 2.0.0 of the SDK. - DisableBinaryDriver bool -} - -// TestStep is a single apply sequence of a test, done within the -// context of a state. -// -// Multiple TestSteps can be sequenced in a Test to allow testing -// potentially complex update logic. In general, simply create/destroy -// tests will only need one step. -type TestStep struct { - // ResourceName should be set to the name of the resource - // that is being tested. Example: "aws_instance.foo". Various test - // modes use this to auto-detect state information. - // - // This is only required if the test mode settings below say it is - // for the mode you're using. - ResourceName string - - // PreConfig is called before the Config is applied to perform any per-step - // setup that needs to happen. This is called regardless of "test mode" - // below. - PreConfig func() - - // Taint is a list of resource addresses to taint prior to the execution of - // the step. Be sure to only include this at a step where the referenced - // address will be present in state, as it will fail the test if the resource - // is missing. - // - // This option is ignored on ImportState tests, and currently only works for - // resources in the root module path. - Taint []string - - //--------------------------------------------------------------- - // Test modes. One of the following groups of settings must be - // set to determine what the test step will do. Ideally we would've - // used Go interfaces here but there are now hundreds of tests we don't - // want to re-type so instead we just determine which step logic - // to run based on what settings below are set. - //--------------------------------------------------------------- - - //--------------------------------------------------------------- - // Plan, Apply testing - //--------------------------------------------------------------- - - // Config a string of the configuration to give to Terraform. If this - // is set, then the TestCase will execute this step with the same logic - // as a `terraform apply`. - Config string - - // Check is called after the Config is applied. Use this step to - // make your own API calls to check the status of things, and to - // inspect the format of the ResourceState itself. - // - // If an error is returned, the test will fail. In this case, a - // destroy plan will still be attempted. - // - // If this is nil, no check is done on this step. - Check TestCheckFunc - - // Destroy will create a destroy plan if set to true. - Destroy bool - - // ExpectNonEmptyPlan can be set to true for specific types of tests that are - // looking to verify that a diff occurs - ExpectNonEmptyPlan bool - - // ExpectError allows the construction of test cases that we expect to fail - // with an error. The specified regexp must match against the error for the - // test to pass. - ExpectError *regexp.Regexp - - // PlanOnly can be set to only run `plan` with this configuration, and not - // actually apply it. This is useful for ensuring config changes result in - // no-op plans - PlanOnly bool - - // PreventDiskCleanup can be set to true for testing terraform modules which - // require access to disk at runtime. Note that this will leave files in the - // temp folder - PreventDiskCleanup bool - - // PreventPostDestroyRefresh can be set to true for cases where data sources - // are tested alongside real resources - PreventPostDestroyRefresh bool - - // SkipFunc is called before applying config, but after PreConfig - // This is useful for defining test steps with platform-dependent checks - SkipFunc func() (bool, error) - - //--------------------------------------------------------------- - // ImportState testing - //--------------------------------------------------------------- - - // ImportState, if true, will test the functionality of ImportState - // by importing the resource with ResourceName (must be set) and the - // ID of that resource. - ImportState bool - - // ImportStateId is the ID to perform an ImportState operation with. - // This is optional. If it isn't set, then the resource ID is automatically - // 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 - - // ImportStateIdFunc is a function that can be used to dynamically generate - // the ID for the ImportState tests. It is sent the state, which can be - // checked to derive the attributes necessary and generate the string in the - // desired format. - ImportStateIdFunc ImportStateIdFunc - - // 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. - ImportStateCheck ImportStateCheckFunc - - // ImportStateVerify, if true, will also check that the state values - // that are finally put into the state after import match for all the - // IDs returned by the Import. Note that this checks for strict equality - // and does not respect DiffSuppressFunc or CustomizeDiff. - // - // ImportStateVerifyIgnore is a list of prefixes of fields that should - // not be verified to be equal. These can be set to ephemeral fields or - // fields that can't be refreshed and don't matter. - ImportStateVerify bool - ImportStateVerifyIgnore []string - - // provider s is used internally to maintain a reference to the - // underlying providers during the tests - providers map[string]terraform.ResourceProvider -} - -// Set to a file mask in sprintf format where %s is test name -const EnvLogPathMask = "TF_LOG_PATH_MASK" - -func LogOutput(t TestT) (logOutput io.Writer, err error) { - logOutput = ioutil.Discard - - logLevel := logging.LogLevel() - if logLevel == "" { - return - } - - logOutput = os.Stderr - - if logPath := os.Getenv(logging.EnvLogFile); logPath != "" { - var err error - logOutput, err = os.OpenFile(logPath, syscall.O_CREAT|syscall.O_RDWR|syscall.O_APPEND, 0666) - if err != nil { - return nil, err - } - } - - if logPathMask := os.Getenv(EnvLogPathMask); logPathMask != "" { - // Escape special characters which may appear if we have subtests - testName := strings.Replace(t.Name(), "/", "__", -1) - - logPath := fmt.Sprintf(logPathMask, testName) - var err error - logOutput, err = os.OpenFile(logPath, syscall.O_CREAT|syscall.O_RDWR|syscall.O_APPEND, 0666) - if err != nil { - return nil, err - } - } - - // This was the default since the beginning - logOutput = &logutils.LevelFilter{ - Levels: logging.ValidLevels, - MinLevel: logutils.LogLevel(logLevel), - Writer: logOutput, - } - - return -} - -// ParallelTest performs an acceptance test on a resource, allowing concurrency -// with other ParallelTest. -// -// Tests will fail if they do not properly handle conditions to allow multiple -// tests to occur against the same resource or service (e.g. random naming). -// All other requirements of the Test function also apply to this function. -func ParallelTest(t TestT, c TestCase) { - t.Parallel() - Test(t, c) -} - -// Test performs an acceptance test on a resource. -// -// Tests are not run unless an environmental variable "TF_ACC" is -// set to some non-empty value. This is to avoid test cases surprising -// a user by creating real resources. -// -// Tests will fail unless the verbose flag (`go test -v`, or explicitly -// the "-test.v" flag) is set. Because some acceptance tests take quite -// long, we require the verbose flag so users are able to see progress -// output. -func Test(t TestT, c TestCase) { - // We only run acceptance tests if an env var is set because they're - // slow and generally require some outside configuration. You can opt out - // of this with OverrideEnvVar on individual TestCases. - if os.Getenv(TestEnvVar) == "" && !c.IsUnitTest { - t.Skip(fmt.Sprintf( - "Acceptance tests skipped unless env '%s' set", - TestEnvVar)) - return - } - - logWriter, err := LogOutput(t) - if err != nil { - t.Error(fmt.Errorf("error setting up logging: %s", err)) - } - log.SetOutput(logWriter) - - // We require verbose mode so that the user knows what is going on. - if !testTesting && !testing.Verbose() && !c.IsUnitTest { - t.Fatal("Acceptance tests must be run with the -v flag on tests") - return - } - - // get instances of all providers, so we can use the individual - // resources to shim the state during the tests. - providers := make(map[string]terraform.ResourceProvider) - for name, pf := range testProviderFactories(c) { - p, err := pf() - if err != nil { - t.Fatal(err) - } - providers[name] = p - } - - if acctest.TestHelper != nil && c.DisableBinaryDriver == false { - // auto-configure all providers - for _, p := range providers { - err = p.Configure(terraform.NewResourceConfigRaw(nil)) - if err != nil { - t.Fatal(err) - } - } - - // Run the PreCheck if we have it. - // This is done after the auto-configure to allow providers - // to override the default auto-configure parameters. - if c.PreCheck != nil { - c.PreCheck() - } - - // inject providers for ImportStateVerify - RunNewTest(t.(*testing.T), c, providers) - return - } else { - // run the PreCheck if we have it - if c.PreCheck != nil { - c.PreCheck() - } - } - - providerResolver, err := testProviderResolver(c) - if err != nil { - t.Fatal(err) - } - - opts := terraform.ContextOpts{ProviderResolver: providerResolver} - - // A single state variable to track the lifecycle, starting with no state - var state *terraform.State - - // Go through each step and run it - var idRefreshCheck *terraform.ResourceState - idRefresh := c.IDRefreshName != "" - errored := false - for i, step := range c.Steps { - // insert the providers into the step so we can get the resources for - // shimming the state - step.providers = providers - - var err error - log.Printf("[DEBUG] Test: Executing step %d", i) - - if step.SkipFunc != nil { - skip, err := step.SkipFunc() - if err != nil { - t.Fatal(err) - } - if skip { - log.Printf("[WARN] Skipping step %d", i) - continue - } - } - - if step.Config == "" && !step.ImportState { - err = fmt.Errorf( - "unknown test mode for step. Please see TestStep docs\n\n%#v", - step) - } else { - if step.ImportState { - if step.Config == "" { - step.Config = testProviderConfig(c) - } - - // Can optionally set step.Config in addition to - // step.ImportState, to provide config for the import. - state, err = testStepImportState(opts, state, step) - } else { - state, err = testStepConfig(opts, state, step) - } - } - - // If we expected an error, but did not get one, fail - if err == nil && step.ExpectError != nil { - errored = true - t.Error(fmt.Sprintf( - "Step %d, no error received, but expected a match to:\n\n%s\n\n", - i, step.ExpectError)) - break - } - - // If there was an error, exit - if err != nil { - // Perhaps we expected an error? Check if it matches - if step.ExpectError != nil { - if !step.ExpectError.MatchString(err.Error()) { - errored = true - t.Error(fmt.Sprintf( - "Step %d, expected error:\n\n%s\n\nTo match:\n\n%s\n\n", - i, err, step.ExpectError)) - break - } - } else { - errored = true - t.Error(fmt.Sprintf("Step %d error: %s", i, detailedErrorMessage(err))) - break - } - } - - // If we've never checked an id-only refresh and our state isn't - // empty, find the first resource and test it. - if idRefresh && idRefreshCheck == nil && !state.Empty() { - // Find the first non-nil resource in the state - for _, m := range state.Modules { - if len(m.Resources) > 0 { - if v, ok := m.Resources[c.IDRefreshName]; ok { - idRefreshCheck = v - } - - break - } - } - - // If we have an instance to check for refreshes, do it - // immediately. We do it in the middle of another test - // because it shouldn't affect the overall state (refresh - // is read-only semantically) and we want to fail early if - // this fails. If refresh isn't read-only, then this will have - // caught a different bug. - if idRefreshCheck != nil { - log.Printf( - "[WARN] Test: Running ID-only refresh check on %s", - idRefreshCheck.Primary.ID) - if err := testIDOnlyRefresh(c, opts, step, idRefreshCheck); err != nil { - log.Printf("[ERROR] Test: ID-only test failed: %s", err) - t.Error(fmt.Sprintf( - "[ERROR] Test: ID-only test failed: %s", err)) - break - } - } - } - } - - // If we never checked an id-only refresh, it is a failure. - if idRefresh { - if !errored && len(c.Steps) > 0 && idRefreshCheck == nil { - t.Error("ID-only refresh check never ran.") - } - } - - // If we have a state, then run the destroy - if state != nil { - lastStep := c.Steps[len(c.Steps)-1] - destroyStep := TestStep{ - Config: lastStep.Config, - Check: c.CheckDestroy, - Destroy: true, - PreventDiskCleanup: lastStep.PreventDiskCleanup, - PreventPostDestroyRefresh: c.PreventPostDestroyRefresh, - providers: providers, - } - - log.Printf("[WARN] Test: Executing destroy step") - state, err := testStep(opts, state, destroyStep) - if err != nil { - t.Error(fmt.Sprintf( - "Error destroying resource! WARNING: Dangling resources\n"+ - "may exist. The full state and error is shown below.\n\n"+ - "Error: %s\n\nState: %s", - err, - state)) - } - } else { - log.Printf("[WARN] Skipping destroy test since there is no state.") - } -} - -// testProviderConfig takes the list of Providers in a TestCase and returns a -// config with only empty provider blocks. This is useful for Import, where no -// config is provided, but the providers must be defined. -func testProviderConfig(c TestCase) string { - var lines []string - for p := range c.Providers { - lines = append(lines, fmt.Sprintf("provider %q {}\n", p)) - } - - return strings.Join(lines, "") -} - -// testProviderFactories combines the fixed Providers and -// ResourceProviderFactory functions into a single map of -// ResourceProviderFactory functions. -func testProviderFactories(c TestCase) map[string]terraform.ResourceProviderFactory { - ctxProviders := make(map[string]terraform.ResourceProviderFactory) - for k, pf := range c.ProviderFactories { - ctxProviders[k] = pf - } - - // add any fixed providers - for k, p := range c.Providers { - ctxProviders[k] = terraform.ResourceProviderFactoryFixed(p) - } - return ctxProviders -} - -// testProviderResolver is a helper to build a ResourceProviderResolver -// with pre instantiated ResourceProviders, so that we can reset them for the -// test, while only calling the factory function once. -// Any errors are stored so that they can be returned by the factory in -// terraform to match non-test behavior. -func testProviderResolver(c TestCase) (providers.Resolver, error) { - ctxProviders := testProviderFactories(c) - - // wrap the old provider factories in the test grpc server so they can be - // called from terraform. - newProviders := make(map[string]providers.Factory) - - for k, pf := range ctxProviders { - factory := pf // must copy to ensure each closure sees its own value - newProviders[k] = func() (providers.Interface, error) { - p, err := factory() - if err != nil { - return nil, err - } - - // The provider is wrapped in a GRPCTestProvider so that it can be - // passed back to terraform core as a providers.Interface, rather - // than the legacy ResourceProvider. - return GRPCTestProvider(p), nil - } - } - - return providers.ResolverFixed(newProviders), nil -} - -// UnitTest is a helper to force the acceptance testing harness to run in the -// normal unit test suite. This should only be used for resource that don't -// have any external dependencies. -func UnitTest(t TestT, c TestCase) { - c.IsUnitTest = true - Test(t, c) -} - -func testIDOnlyRefresh(c TestCase, opts terraform.ContextOpts, step TestStep, r *terraform.ResourceState) error { - // TODO: We guard by this right now so master doesn't explode. We - // need to remove this eventually to make this part of the normal tests. - if os.Getenv("TF_ACC_IDONLY") == "" { - return nil - } - - addr := addrs.Resource{ - Mode: addrs.ManagedResourceMode, - Type: r.Type, - Name: "foo", - }.Instance(addrs.NoKey) - absAddr := addr.Absolute(addrs.RootModuleInstance) - - // Build the state. The state is just the resource with an ID. There - // are no attributes. We only set what is needed to perform a refresh. - state := states.NewState() - state.RootModule().SetResourceInstanceCurrent( - addr, - &states.ResourceInstanceObjectSrc{ - AttrsFlat: r.Primary.Attributes, - Status: states.ObjectReady, - }, - addrs.ProviderConfig{Type: "placeholder"}.Absolute(addrs.RootModuleInstance), - ) - - // Create the config module. We use the full config because Refresh - // doesn't have access to it and we may need things like provider - // configurations. The initial implementation of id-only checks used - // an empty config module, but that caused the aforementioned problems. - cfg, err := testConfig(opts, step) - if err != nil { - return err - } - - // Initialize the context - opts.Config = cfg - opts.State = state - ctx, ctxDiags := terraform.NewContext(&opts) - if ctxDiags.HasErrors() { - return ctxDiags.Err() - } - if diags := ctx.Validate(); len(diags) > 0 { - if diags.HasErrors() { - return errwrap.Wrapf("config is invalid: {{err}}", diags.Err()) - } - - log.Printf("[WARN] Config warnings:\n%s", diags.Err().Error()) - } - - // Refresh! - state, refreshDiags := ctx.Refresh() - if refreshDiags.HasErrors() { - return refreshDiags.Err() - } - - // Verify attribute equivalence. - actualR := state.ResourceInstance(absAddr) - if actualR == nil { - return fmt.Errorf("Resource gone!") - } - if actualR.Current == nil { - return fmt.Errorf("Resource has no primary instance") - } - actual := actualR.Current.AttrsFlat - expected := r.Primary.Attributes - // Remove fields we're ignoring - for _, v := range c.IDRefreshIgnore { - for k := range actual { - if strings.HasPrefix(k, v) { - delete(actual, k) - } - } - for k := range expected { - if strings.HasPrefix(k, v) { - delete(expected, k) - } - } - } - - if !reflect.DeepEqual(actual, expected) { - // Determine only the different attributes - for k, v := range expected { - if av, ok := actual[k]; ok && v == av { - delete(expected, k) - delete(actual, k) - } - } - - spewConf := spew.NewDefaultConfig() - spewConf.SortKeys = true - return fmt.Errorf( - "Attributes not equivalent. Difference is shown below. Top is actual, bottom is expected."+ - "\n\n%s\n\n%s", - spewConf.Sdump(actual), spewConf.Sdump(expected)) - } - - return nil -} - -func testConfig(opts terraform.ContextOpts, step TestStep) (*configs.Config, error) { - if step.PreConfig != nil { - step.PreConfig() - } - - cfgPath, err := ioutil.TempDir("", "tf-test") - if err != nil { - return nil, fmt.Errorf("Error creating temporary directory for config: %s", err) - } - - if step.PreventDiskCleanup { - log.Printf("[INFO] Skipping defer os.RemoveAll call") - } else { - defer os.RemoveAll(cfgPath) - } - - // Write the main configuration file - err = ioutil.WriteFile(filepath.Join(cfgPath, "main.tf"), []byte(step.Config), os.ModePerm) - if err != nil { - return nil, fmt.Errorf("Error creating temporary file for config: %s", err) - } - - // Create directory for our child modules, if any. - modulesDir := filepath.Join(cfgPath, ".modules") - err = os.Mkdir(modulesDir, os.ModePerm) - if err != nil { - return nil, fmt.Errorf("Error creating child modules directory: %s", err) - } - - inst := initwd.NewModuleInstaller(modulesDir, nil) - _, installDiags := inst.InstallModules(cfgPath, true, initwd.ModuleInstallHooksImpl{}) - if installDiags.HasErrors() { - return nil, installDiags.Err() - } - - loader, err := configload.NewLoader(&configload.Config{ - ModulesDir: modulesDir, - }) - if err != nil { - return nil, fmt.Errorf("failed to create config loader: %s", err) - } - - config, configDiags := loader.LoadConfig(cfgPath) - if configDiags.HasErrors() { - return nil, configDiags - } - - return config, nil -} - -func testResource(c TestStep, state *terraform.State) (*terraform.ResourceState, error) { - if c.ResourceName == "" { - return nil, fmt.Errorf("ResourceName must be set in TestStep") - } - - for _, m := range state.Modules { - if len(m.Resources) > 0 { - if v, ok := m.Resources[c.ResourceName]; ok { - return v, nil - } - } - } - - return nil, fmt.Errorf( - "Resource specified by ResourceName couldn't be found: %s", c.ResourceName) -} - -// ComposeTestCheckFunc lets you compose multiple TestCheckFuncs into -// a single TestCheckFunc. -// -// As a user testing their provider, this lets you decompose your checks -// into smaller pieces more easily. -func ComposeTestCheckFunc(fs ...TestCheckFunc) TestCheckFunc { - return func(s *terraform.State) error { - for i, f := range fs { - if err := f(s); err != nil { - return fmt.Errorf("Check %d/%d error: %s", i+1, len(fs), err) - } - } - - return nil - } -} - -// ComposeAggregateTestCheckFunc lets you compose multiple TestCheckFuncs into -// a single TestCheckFunc. -// -// As a user testing their provider, this lets you decompose your checks -// into smaller pieces more easily. -// -// Unlike ComposeTestCheckFunc, ComposeAggergateTestCheckFunc runs _all_ of the -// TestCheckFuncs and aggregates failures. -func ComposeAggregateTestCheckFunc(fs ...TestCheckFunc) TestCheckFunc { - return func(s *terraform.State) error { - var result *multierror.Error - - for i, f := range fs { - if err := f(s); err != nil { - result = multierror.Append(result, fmt.Errorf("Check %d/%d error: %s", i+1, len(fs), err)) - } - } - - return result.ErrorOrNil() - } -} - -// TestCheckResourceAttrSet is a TestCheckFunc which ensures a value -// exists in state for the given name/key combination. It is useful when -// testing that computed values were set, when it is not possible to -// know ahead of time what the values will be. -func TestCheckResourceAttrSet(name, key string) TestCheckFunc { - return func(s *terraform.State) error { - is, err := primaryInstanceState(s, name) - if err != nil { - return err - } - - return testCheckResourceAttrSet(is, name, key) - } -} - -// TestCheckModuleResourceAttrSet - as per TestCheckResourceAttrSet but with -// support for non-root modules -func TestCheckModuleResourceAttrSet(mp []string, name string, key string) TestCheckFunc { - mpt := addrs.Module(mp).UnkeyedInstanceShim() - return func(s *terraform.State) error { - is, err := modulePathPrimaryInstanceState(s, mpt, name) - if err != nil { - return err - } - - return testCheckResourceAttrSet(is, name, key) - } -} - -func testCheckResourceAttrSet(is *terraform.InstanceState, name string, key string) error { - if val, ok := is.Attributes[key]; !ok || val == "" { - return fmt.Errorf("%s: Attribute '%s' expected to be set", name, key) - } - - return nil -} - -// TestCheckResourceAttr is a TestCheckFunc which validates -// the value in state for the given name/key combination. -func TestCheckResourceAttr(name, key, value string) TestCheckFunc { - return func(s *terraform.State) error { - is, err := primaryInstanceState(s, name) - if err != nil { - return err - } - - return testCheckResourceAttr(is, name, key, value) - } -} - -// TestCheckModuleResourceAttr - as per TestCheckResourceAttr but with -// support for non-root modules -func TestCheckModuleResourceAttr(mp []string, name string, key string, value string) TestCheckFunc { - mpt := addrs.Module(mp).UnkeyedInstanceShim() - return func(s *terraform.State) error { - is, err := modulePathPrimaryInstanceState(s, mpt, name) - if err != nil { - return err - } - - return testCheckResourceAttr(is, name, key, value) - } -} - -func testCheckResourceAttr(is *terraform.InstanceState, name string, key string, value string) error { - // Empty containers may be elided from the state. - // If the intent here is to check for an empty container, allow the key to - // also be non-existent. - emptyCheck := false - if value == "0" && (strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%")) { - emptyCheck = true - } - - if v, ok := is.Attributes[key]; !ok || v != value { - if emptyCheck && !ok { - return nil - } - - if !ok { - return fmt.Errorf("%s: Attribute '%s' not found", name, key) - } - - return fmt.Errorf( - "%s: Attribute '%s' expected %#v, got %#v", - name, - key, - value, - v) - } - return nil -} - -// TestCheckNoResourceAttr is a TestCheckFunc which ensures that -// NO value exists in state for the given name/key combination. -func TestCheckNoResourceAttr(name, key string) TestCheckFunc { - return func(s *terraform.State) error { - is, err := primaryInstanceState(s, name) - if err != nil { - return err - } - - return testCheckNoResourceAttr(is, name, key) - } -} - -// TestCheckModuleNoResourceAttr - as per TestCheckNoResourceAttr but with -// support for non-root modules -func TestCheckModuleNoResourceAttr(mp []string, name string, key string) TestCheckFunc { - mpt := addrs.Module(mp).UnkeyedInstanceShim() - return func(s *terraform.State) error { - is, err := modulePathPrimaryInstanceState(s, mpt, name) - if err != nil { - return err - } - - return testCheckNoResourceAttr(is, name, key) - } -} - -func testCheckNoResourceAttr(is *terraform.InstanceState, name string, key string) error { - // Empty containers may sometimes be included in the state. - // If the intent here is to check for an empty container, allow the value to - // also be "0". - emptyCheck := false - if strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%") { - emptyCheck = true - } - - val, exists := is.Attributes[key] - if emptyCheck && val == "0" { - return nil - } - - if exists { - return fmt.Errorf("%s: Attribute '%s' found when not expected", name, key) - } - - return nil -} - -// TestMatchResourceAttr is a TestCheckFunc which checks that the value -// in state for the given name/key combination matches the given regex. -func TestMatchResourceAttr(name, key string, r *regexp.Regexp) TestCheckFunc { - return func(s *terraform.State) error { - is, err := primaryInstanceState(s, name) - if err != nil { - return err - } - - return testMatchResourceAttr(is, name, key, r) - } -} - -// TestModuleMatchResourceAttr - as per TestMatchResourceAttr but with -// support for non-root modules -func TestModuleMatchResourceAttr(mp []string, name string, key string, r *regexp.Regexp) TestCheckFunc { - mpt := addrs.Module(mp).UnkeyedInstanceShim() - return func(s *terraform.State) error { - is, err := modulePathPrimaryInstanceState(s, mpt, name) - if err != nil { - return err - } - - return testMatchResourceAttr(is, name, key, r) - } -} - -func testMatchResourceAttr(is *terraform.InstanceState, name string, key string, r *regexp.Regexp) error { - if !r.MatchString(is.Attributes[key]) { - return fmt.Errorf( - "%s: Attribute '%s' didn't match %q, got %#v", - name, - key, - r.String(), - is.Attributes[key]) - } - - return nil -} - -// TestCheckResourceAttrPtr is like TestCheckResourceAttr except the -// value is a pointer so that it can be updated while the test is running. -// It will only be dereferenced at the point this step is run. -func TestCheckResourceAttrPtr(name string, key string, value *string) TestCheckFunc { - return func(s *terraform.State) error { - return TestCheckResourceAttr(name, key, *value)(s) - } -} - -// TestCheckModuleResourceAttrPtr - as per TestCheckResourceAttrPtr but with -// support for non-root modules -func TestCheckModuleResourceAttrPtr(mp []string, name string, key string, value *string) TestCheckFunc { - return func(s *terraform.State) error { - return TestCheckModuleResourceAttr(mp, name, key, *value)(s) - } -} - -// TestCheckResourceAttrPair is a TestCheckFunc which validates that the values -// in state for a pair of name/key combinations are equal. -func TestCheckResourceAttrPair(nameFirst, keyFirst, nameSecond, keySecond string) TestCheckFunc { - return func(s *terraform.State) error { - isFirst, err := primaryInstanceState(s, nameFirst) - if err != nil { - return err - } - - isSecond, err := primaryInstanceState(s, nameSecond) - if err != nil { - return err - } - - return testCheckResourceAttrPair(isFirst, nameFirst, keyFirst, isSecond, nameSecond, keySecond) - } -} - -// TestCheckModuleResourceAttrPair - as per TestCheckResourceAttrPair but with -// support for non-root modules -func TestCheckModuleResourceAttrPair(mpFirst []string, nameFirst string, keyFirst string, mpSecond []string, nameSecond string, keySecond string) TestCheckFunc { - mptFirst := addrs.Module(mpFirst).UnkeyedInstanceShim() - mptSecond := addrs.Module(mpSecond).UnkeyedInstanceShim() - return func(s *terraform.State) error { - isFirst, err := modulePathPrimaryInstanceState(s, mptFirst, nameFirst) - if err != nil { - return err - } - - isSecond, err := modulePathPrimaryInstanceState(s, mptSecond, nameSecond) - if err != nil { - return err - } - - return testCheckResourceAttrPair(isFirst, nameFirst, keyFirst, isSecond, nameSecond, keySecond) - } -} - -func testCheckResourceAttrPair(isFirst *terraform.InstanceState, nameFirst string, keyFirst string, isSecond *terraform.InstanceState, nameSecond string, keySecond string) error { - vFirst, okFirst := isFirst.Attributes[keyFirst] - vSecond, okSecond := isSecond.Attributes[keySecond] - - // Container count values of 0 should not be relied upon, and not reliably - // maintained by helper/schema. For the purpose of tests, consider unset and - // 0 to be equal. - if len(keyFirst) > 2 && len(keySecond) > 2 && keyFirst[len(keyFirst)-2:] == keySecond[len(keySecond)-2:] && - (strings.HasSuffix(keyFirst, ".#") || strings.HasSuffix(keyFirst, ".%")) { - // they have the same suffix, and it is a collection count key. - if vFirst == "0" || vFirst == "" { - okFirst = false - } - if vSecond == "0" || vSecond == "" { - okSecond = false - } - } - - if okFirst != okSecond { - if !okFirst { - return fmt.Errorf("%s: Attribute %q not set, but %q is set in %s as %q", nameFirst, keyFirst, keySecond, nameSecond, vSecond) - } - return fmt.Errorf("%s: Attribute %q is %q, but %q is not set in %s", nameFirst, keyFirst, vFirst, keySecond, nameSecond) - } - if !(okFirst || okSecond) { - // If they both don't exist then they are equally unset, so that's okay. - return nil - } - - if vFirst != vSecond { - return fmt.Errorf( - "%s: Attribute '%s' expected %#v, got %#v", - nameFirst, - keyFirst, - vSecond, - vFirst) - } - - return nil -} - -// TestCheckOutput checks an output in the Terraform configuration -func TestCheckOutput(name, value string) TestCheckFunc { - return func(s *terraform.State) error { - ms := s.RootModule() - rs, ok := ms.Outputs[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - if rs.Value != value { - return fmt.Errorf( - "Output '%s': expected %#v, got %#v", - name, - value, - rs) - } - - return nil - } -} - -func TestMatchOutput(name string, r *regexp.Regexp) TestCheckFunc { - return func(s *terraform.State) error { - ms := s.RootModule() - rs, ok := ms.Outputs[name] - if !ok { - return fmt.Errorf("Not found: %s", name) - } - - if !r.MatchString(rs.Value.(string)) { - return fmt.Errorf( - "Output '%s': %#v didn't match %q", - name, - rs, - r.String()) - } - - return nil - } -} - -// TestT is the interface used to handle the test lifecycle of a test. -// -// Users should just use a *testing.T object, which implements this. -type TestT interface { - Error(args ...interface{}) - Fatal(args ...interface{}) - Skip(args ...interface{}) - Name() string - Parallel() -} - -// This is set to true by unit tests to alter some behavior -var testTesting = false - -// modulePrimaryInstanceState returns the instance state for the given resource -// name in a ModuleState -func modulePrimaryInstanceState(s *terraform.State, ms *terraform.ModuleState, name string) (*terraform.InstanceState, error) { - rs, ok := ms.Resources[name] - if !ok { - return nil, fmt.Errorf("Not found: %s in %s", name, ms.Path) - } - - is := rs.Primary - if is == nil { - return nil, fmt.Errorf("No primary instance: %s in %s", name, ms.Path) - } - - return is, nil -} - -// modulePathPrimaryInstanceState returns the primary instance state for the -// given resource name in a given module path. -func modulePathPrimaryInstanceState(s *terraform.State, mp addrs.ModuleInstance, name string) (*terraform.InstanceState, error) { - ms := s.ModuleByPath(mp) - if ms == nil { - return nil, fmt.Errorf("No module found at: %s", mp) - } - - return modulePrimaryInstanceState(s, ms, name) -} - -// primaryInstanceState returns the primary instance state for the given -// resource name in the root module. -func primaryInstanceState(s *terraform.State, name string) (*terraform.InstanceState, error) { - ms := s.RootModule() - return modulePrimaryInstanceState(s, ms, name) -} - -// operationError is a specialized implementation of error used to describe -// failures during one of the several operations performed for a particular -// test case. -type operationError struct { - OpName string - Diags tfdiags.Diagnostics -} - -func newOperationError(opName string, diags tfdiags.Diagnostics) error { - return operationError{opName, diags} -} - -// Error returns a terse error string containing just the basic diagnostic -// messages, for situations where normal Go error behavior is appropriate. -func (err operationError) Error() string { - return fmt.Sprintf("errors during %s: %s", err.OpName, err.Diags.Err().Error()) -} - -// ErrorDetail is like Error except it includes verbosely-rendered diagnostics -// similar to what would come from a normal Terraform run, which include -// additional context not included in Error(). -func (err operationError) ErrorDetail() string { - var buf bytes.Buffer - fmt.Fprintf(&buf, "errors during %s:", err.OpName) - clr := &colorstring.Colorize{Disable: true, Colors: colorstring.DefaultColors} - for _, diag := range err.Diags { - diagStr := format.Diagnostic(diag, nil, clr, 78) - buf.WriteByte('\n') - buf.WriteString(diagStr) - } - return buf.String() -} - -// detailedErrorMessage is a helper for calling ErrorDetail on an error if -// it is an operationError or just taking Error otherwise. -func detailedErrorMessage(err error) string { - switch tErr := err.(type) { - case operationError: - return tErr.ErrorDetail() - default: - return err.Error() - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_config.go deleted file mode 100644 index e21525de869..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_config.go +++ /dev/null @@ -1,404 +0,0 @@ -package resource - -import ( - "bufio" - "bytes" - "errors" - "fmt" - "log" - "sort" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -// testStepConfig runs a config-mode test step -func testStepConfig( - opts terraform.ContextOpts, - state *terraform.State, - step TestStep) (*terraform.State, error) { - return testStep(opts, state, step) -} - -func testStep(opts terraform.ContextOpts, state *terraform.State, step TestStep) (*terraform.State, error) { - if !step.Destroy { - if err := testStepTaint(state, step); err != nil { - return state, err - } - } - - cfg, err := testConfig(opts, step) - if err != nil { - return state, err - } - - var stepDiags tfdiags.Diagnostics - - // Build the context - opts.Config = cfg - opts.State, err = terraform.ShimLegacyState(state) - if err != nil { - return nil, err - } - - opts.Destroy = step.Destroy - ctx, stepDiags := terraform.NewContext(&opts) - if stepDiags.HasErrors() { - return state, fmt.Errorf("Error initializing context: %s", stepDiags.Err()) - } - if stepDiags := ctx.Validate(); len(stepDiags) > 0 { - if stepDiags.HasErrors() { - return state, errwrap.Wrapf("config is invalid: {{err}}", stepDiags.Err()) - } - - log.Printf("[WARN] Config warnings:\n%s", stepDiags) - } - - // Refresh! - newState, stepDiags := ctx.Refresh() - // shim the state first so the test can check the state on errors - - state, err = shimNewState(newState, step.providers) - if err != nil { - return nil, err - } - if stepDiags.HasErrors() { - return state, newOperationError("refresh", stepDiags) - } - - // If this step is a PlanOnly step, skip over this first Plan and subsequent - // Apply, and use the follow up Plan that checks for perpetual diffs - if !step.PlanOnly { - // Plan! - if p, stepDiags := ctx.Plan(); stepDiags.HasErrors() { - return state, newOperationError("plan", stepDiags) - } else { - log.Printf("[WARN] Test: Step plan: %s", legacyPlanComparisonString(newState, p.Changes)) - } - - // We need to keep a copy of the state prior to destroying - // such that destroy steps can verify their behavior in the check - // function - stateBeforeApplication := state.DeepCopy() - - // Apply the diff, creating real resources. - newState, stepDiags = ctx.Apply() - // shim the state first so the test can check the state on errors - state, err = shimNewState(newState, step.providers) - if err != nil { - return nil, err - } - if stepDiags.HasErrors() { - return state, newOperationError("apply", stepDiags) - } - - // Run any configured checks - if step.Check != nil { - if step.Destroy { - if err := step.Check(stateBeforeApplication); err != nil { - return state, fmt.Errorf("Check failed: %s", err) - } - } else { - if err := step.Check(state); err != nil { - return state, fmt.Errorf("Check failed: %s", err) - } - } - } - } - - // Now, verify that Plan is now empty and we don't have a perpetual diff issue - // We do this with TWO plans. One without a refresh. - var p *plans.Plan - if p, stepDiags = ctx.Plan(); stepDiags.HasErrors() { - return state, newOperationError("follow-up plan", stepDiags) - } - if !p.Changes.Empty() { - if step.ExpectNonEmptyPlan { - log.Printf("[INFO] Got non-empty plan, as expected:\n\n%s", legacyPlanComparisonString(newState, p.Changes)) - } else { - return state, fmt.Errorf( - "After applying this step, the plan was not empty:\n\n%s", legacyPlanComparisonString(newState, p.Changes)) - } - } - - // And another after a Refresh. - if !step.Destroy || (step.Destroy && !step.PreventPostDestroyRefresh) { - newState, stepDiags = ctx.Refresh() - if stepDiags.HasErrors() { - return state, newOperationError("follow-up refresh", stepDiags) - } - - state, err = shimNewState(newState, step.providers) - if err != nil { - return nil, err - } - } - if p, stepDiags = ctx.Plan(); stepDiags.HasErrors() { - return state, newOperationError("second follow-up refresh", stepDiags) - } - empty := p.Changes.Empty() - - // Data resources are tricky because they legitimately get instantiated - // during refresh so that they will be already populated during the - // plan walk. Because of this, if we have any data resources in the - // config we'll end up wanting to destroy them again here. This is - // acceptable and expected, and we'll treat it as "empty" for the - // sake of this testing. - if step.Destroy && !empty { - empty = true - for _, change := range p.Changes.Resources { - if change.Addr.Resource.Resource.Mode != addrs.DataResourceMode { - empty = false - break - } - } - } - - if !empty { - if step.ExpectNonEmptyPlan { - log.Printf("[INFO] Got non-empty plan, as expected:\n\n%s", legacyPlanComparisonString(newState, p.Changes)) - } else { - return state, fmt.Errorf( - "After applying this step and refreshing, "+ - "the plan was not empty:\n\n%s", legacyPlanComparisonString(newState, p.Changes)) - } - } - - // Made it here, but expected a non-empty plan, fail! - if step.ExpectNonEmptyPlan && empty { - return state, fmt.Errorf("Expected a non-empty plan, but got an empty plan!") - } - - // Made it here? Good job test step! - return state, nil -} - -// legacyPlanComparisonString produces a string representation of the changes -// from a plan and a given state togther, as was formerly produced by the -// String method of terraform.Plan. -// -// This is here only for compatibility with existing tests that predate our -// new plan and state types, and should not be used in new tests. Instead, use -// a library like "cmp" to do a deep equality and diff on the two -// data structures. -func legacyPlanComparisonString(state *states.State, changes *plans.Changes) string { - return fmt.Sprintf( - "DIFF:\n\n%s\n\nSTATE:\n\n%s", - legacyDiffComparisonString(changes), - state.String(), - ) -} - -// legacyDiffComparisonString produces a string representation of the changes -// from a planned changes object, as was formerly produced by the String method -// of terraform.Diff. -// -// This is here only for compatibility with existing tests that predate our -// new plan types, and should not be used in new tests. Instead, use a library -// like "cmp" to do a deep equality check and diff on the two data structures. -func legacyDiffComparisonString(changes *plans.Changes) string { - // The old string representation of a plan was grouped by module, but - // our new plan structure is not grouped in that way and so we'll need - // to preprocess it in order to produce that grouping. - type ResourceChanges struct { - Current *plans.ResourceInstanceChangeSrc - Deposed map[states.DeposedKey]*plans.ResourceInstanceChangeSrc - } - byModule := map[string]map[string]*ResourceChanges{} - resourceKeys := map[string][]string{} - requiresReplace := map[string][]string{} - var moduleKeys []string - for _, rc := range changes.Resources { - if rc.Action == plans.NoOp { - // We won't mention no-op changes here at all, since the old plan - // model we are emulating here didn't have such a concept. - continue - } - moduleKey := rc.Addr.Module.String() - if _, exists := byModule[moduleKey]; !exists { - moduleKeys = append(moduleKeys, moduleKey) - byModule[moduleKey] = make(map[string]*ResourceChanges) - } - resourceKey := rc.Addr.Resource.String() - if _, exists := byModule[moduleKey][resourceKey]; !exists { - resourceKeys[moduleKey] = append(resourceKeys[moduleKey], resourceKey) - byModule[moduleKey][resourceKey] = &ResourceChanges{ - Deposed: make(map[states.DeposedKey]*plans.ResourceInstanceChangeSrc), - } - } - - if rc.DeposedKey == states.NotDeposed { - byModule[moduleKey][resourceKey].Current = rc - } else { - byModule[moduleKey][resourceKey].Deposed[rc.DeposedKey] = rc - } - - rr := []string{} - for _, p := range rc.RequiredReplace.List() { - rr = append(rr, hcl2shim.FlatmapKeyFromPath(p)) - } - requiresReplace[resourceKey] = rr - } - sort.Strings(moduleKeys) - for _, ks := range resourceKeys { - sort.Strings(ks) - } - - var buf bytes.Buffer - - for _, moduleKey := range moduleKeys { - rcs := byModule[moduleKey] - var mBuf bytes.Buffer - - for _, resourceKey := range resourceKeys[moduleKey] { - rc := rcs[resourceKey] - - forceNewAttrs := requiresReplace[resourceKey] - - crud := "UPDATE" - if rc.Current != nil { - switch rc.Current.Action { - case plans.DeleteThenCreate: - crud = "DESTROY/CREATE" - case plans.CreateThenDelete: - crud = "CREATE/DESTROY" - case plans.Delete: - crud = "DESTROY" - case plans.Create: - crud = "CREATE" - } - } else { - // We must be working on a deposed object then, in which - // case destroying is the only possible action. - crud = "DESTROY" - } - - extra := "" - if rc.Current == nil && len(rc.Deposed) > 0 { - extra = " (deposed only)" - } - - fmt.Fprintf( - &mBuf, "%s: %s%s\n", - crud, resourceKey, extra, - ) - - attrNames := map[string]bool{} - var oldAttrs map[string]string - var newAttrs map[string]string - if rc.Current != nil { - if before := rc.Current.Before; before != nil { - ty, err := before.ImpliedType() - if err == nil { - val, err := before.Decode(ty) - if err == nil { - oldAttrs = hcl2shim.FlatmapValueFromHCL2(val) - for k := range oldAttrs { - attrNames[k] = true - } - } - } - } - if after := rc.Current.After; after != nil { - ty, err := after.ImpliedType() - if err == nil { - val, err := after.Decode(ty) - if err == nil { - newAttrs = hcl2shim.FlatmapValueFromHCL2(val) - for k := range newAttrs { - attrNames[k] = true - } - } - } - } - } - if oldAttrs == nil { - oldAttrs = make(map[string]string) - } - if newAttrs == nil { - newAttrs = make(map[string]string) - } - - attrNamesOrder := make([]string, 0, len(attrNames)) - keyLen := 0 - for n := range attrNames { - attrNamesOrder = append(attrNamesOrder, n) - if len(n) > keyLen { - keyLen = len(n) - } - } - sort.Strings(attrNamesOrder) - - for _, attrK := range attrNamesOrder { - v := newAttrs[attrK] - u := oldAttrs[attrK] - - if v == hcl2shim.UnknownVariableValue { - v = "" - } - // NOTE: we don't support here because we would - // need schema to do that. Excluding sensitive values - // is now done at the UI layer, and so should not be tested - // at the core layer. - - updateMsg := "" - - // This may not be as precise as in the old diff, as it matches - // everything under the attribute that was originally marked as - // ForceNew, but should help make it easier to determine what - // caused replacement here. - for _, k := range forceNewAttrs { - if strings.HasPrefix(attrK, k) { - updateMsg = " (forces new resource)" - break - } - } - - fmt.Fprintf( - &mBuf, " %s:%s %#v => %#v%s\n", - attrK, - strings.Repeat(" ", keyLen-len(attrK)), - u, v, - updateMsg, - ) - } - } - - if moduleKey == "" { // root module - buf.Write(mBuf.Bytes()) - buf.WriteByte('\n') - continue - } - - fmt.Fprintf(&buf, "%s:\n", moduleKey) - s := bufio.NewScanner(&mBuf) - for s.Scan() { - buf.WriteString(fmt.Sprintf(" %s\n", s.Text())) - } - } - - return buf.String() -} - -func testStepTaint(state *terraform.State, step TestStep) error { - for _, p := range step.Taint { - m := state.RootModule() - if m == nil { - return errors.New("no state") - } - rs, ok := m.Resources[p] - if !ok { - return fmt.Errorf("resource %q not found in state", p) - } - log.Printf("[WARN] Test: Explicitly tainting resource %q", p) - rs.Taint() - } - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_import_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_import_state.go deleted file mode 100644 index 7b7c30a7a2b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_import_state.go +++ /dev/null @@ -1,233 +0,0 @@ -package resource - -import ( - "fmt" - "log" - "reflect" - "strings" - - "github.com/davecgh/go-spew/spew" - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -// testStepImportState runs an imort state test step -func testStepImportState( - opts terraform.ContextOpts, - state *terraform.State, - step TestStep) (*terraform.State, error) { - - // Determine the ID to import - var importId string - switch { - case step.ImportStateIdFunc != nil: - var err error - importId, err = step.ImportStateIdFunc(state) - if err != nil { - return state, err - } - case step.ImportStateId != "": - importId = step.ImportStateId - default: - resource, err := testResource(step, state) - if err != nil { - return state, err - } - 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. - cfg, err := testConfig(opts, step) - if err != nil { - return state, err - } - - opts.Config = cfg - - // import tests start with empty state - opts.State = states.NewState() - - ctx, stepDiags := terraform.NewContext(&opts) - if stepDiags.HasErrors() { - return state, stepDiags.Err() - } - - // The test step provides the resource address as a string, so we need - // to parse it to get an addrs.AbsResourceAddress to pass in to the - // import method. - traversal, hclDiags := hclsyntax.ParseTraversalAbs([]byte(step.ResourceName), "", hcl.Pos{}) - if hclDiags.HasErrors() { - return nil, hclDiags - } - importAddr, stepDiags := addrs.ParseAbsResourceInstance(traversal) - if stepDiags.HasErrors() { - return nil, stepDiags.Err() - } - - // Do the import - importedState, stepDiags := ctx.Import(&terraform.ImportOpts{ - // Set the module so that any provider config is loaded - Config: cfg, - - Targets: []*terraform.ImportTarget{ - { - Addr: importAddr, - ID: importId, - }, - }, - }) - if stepDiags.HasErrors() { - log.Printf("[ERROR] Test: ImportState failure: %s", stepDiags.Err()) - return state, stepDiags.Err() - } - - newState, err := shimNewState(importedState, step.providers) - if err != nil { - return nil, err - } - - // Go through the new state and verify - if step.ImportStateCheck != nil { - var states []*terraform.InstanceState - for _, r := range newState.RootModule().Resources { - if r.Primary != nil { - is := r.Primary.DeepCopy() - is.Ephemeral.Type = r.Type // otherwise the check function cannot see the type - states = append(states, is) - } - } - if err := step.ImportStateCheck(states); err != nil { - return state, err - } - } - - // Verify that all the states match - if step.ImportStateVerify { - new := newState.RootModule().Resources - old := state.RootModule().Resources - for _, r := range new { - // Find the existing resource - var oldR *terraform.ResourceState - for _, r2 := range old { - if r2.Primary != nil && r2.Primary.ID == r.Primary.ID && r2.Type == r.Type { - oldR = r2 - break - } - } - if oldR == nil { - return state, fmt.Errorf( - "Failed state verification, resource with ID %s not found", - r.Primary.ID) - } - - // We'll try our best to find the schema for this resource type - // so we can ignore Removed fields during validation. If we fail - // to find the schema then we won't ignore them and so the test - // will need to rely on explicit ImportStateVerifyIgnore, though - // this shouldn't happen in any reasonable case. - var rsrcSchema *schema.Resource - if providerAddr, diags := addrs.ParseAbsProviderConfigStr(r.Provider); !diags.HasErrors() { - providerType := providerAddr.ProviderConfig.Type - if provider, ok := step.providers[providerType]; ok { - if provider, ok := provider.(*schema.Provider); ok { - rsrcSchema = provider.ResourcesMap[r.Type] - } - } - } - - // don't add empty flatmapped containers, so we can more easily - // compare the attributes - skipEmpty := func(k, v string) bool { - if strings.HasSuffix(k, ".#") || strings.HasSuffix(k, ".%") { - if v == "0" { - return true - } - } - return false - } - - // Compare their attributes - actual := make(map[string]string) - for k, v := range r.Primary.Attributes { - if skipEmpty(k, v) { - continue - } - actual[k] = v - } - - expected := make(map[string]string) - for k, v := range oldR.Primary.Attributes { - if skipEmpty(k, v) { - continue - } - expected[k] = v - } - - // Remove fields we're ignoring - for _, v := range step.ImportStateVerifyIgnore { - for k := range actual { - if strings.HasPrefix(k, v) { - delete(actual, k) - } - } - for k := range expected { - if strings.HasPrefix(k, v) { - delete(expected, k) - } - } - } - - // Also remove any attributes that are marked as "Removed" in the - // schema, if we have a schema to check that against. - if rsrcSchema != nil { - for k := range actual { - for _, schema := range rsrcSchema.SchemasForFlatmapPath(k) { - if schema.Removed != "" { - delete(actual, k) - break - } - } - } - for k := range expected { - for _, schema := range rsrcSchema.SchemasForFlatmapPath(k) { - if schema.Removed != "" { - delete(expected, k) - break - } - } - } - } - - if !reflect.DeepEqual(actual, expected) { - // Determine only the different attributes - for k, v := range expected { - if av, ok := actual[k]; ok && v == av { - delete(expected, k) - delete(actual, k) - } - } - - spewConf := spew.NewDefaultConfig() - spewConf.SortKeys = true - return state, fmt.Errorf( - "ImportStateVerify attributes not equivalent. Difference is shown below. Top is actual, bottom is expected."+ - "\n\n%s\n\n%s", - spewConf.Sdump(actual), spewConf.Sdump(expected)) - } - } - } - - // Return the old state (non-imported) so we don't change anything. - return state, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_new.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_new.go deleted file mode 100644 index 8ba9c85d31b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_new.go +++ /dev/null @@ -1,179 +0,0 @@ -package resource - -import ( - "fmt" - "log" - "reflect" - "strings" - "testing" - - "github.com/davecgh/go-spew/spew" - tfjson "github.com/hashicorp/terraform-json" - "github.com/hashicorp/terraform-plugin-sdk/acctest" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - tftest "github.com/hashicorp/terraform-plugin-test" -) - -func getState(t *testing.T, wd *tftest.WorkingDir) *terraform.State { - jsonState := wd.RequireState(t) - state, err := shimStateFromJson(jsonState) - if err != nil { - t.Fatal(err) - } - return state -} - -func RunNewTest(t *testing.T, c TestCase, providers map[string]terraform.ResourceProvider) { - spewConf := spew.NewDefaultConfig() - spewConf.SortKeys = true - wd := acctest.TestHelper.RequireNewWorkingDir(t) - - defer func() { - wd.RequireDestroy(t) - - if c.CheckDestroy != nil { - statePostDestroy := getState(t, wd) - - if err := c.CheckDestroy(statePostDestroy); err != nil { - t.Fatal(err) - } - } - wd.Close() - }() - - providerCfg := testProviderConfig(c) - - wd.RequireSetConfig(t, providerCfg) - wd.RequireInit(t) - - // use this to track last step succesfully applied - // acts as default for import tests - var appliedCfg string - - for i, step := range c.Steps { - - if step.PreConfig != nil { - step.PreConfig() - } - - if step.SkipFunc != nil { - skip, err := step.SkipFunc() - if err != nil { - t.Fatal(err) - } - if skip { - log.Printf("[WARN] Skipping step %d", i) - continue - } - } - - if step.ImportState { - step.providers = providers - err := testStepNewImportState(t, c, wd, step, appliedCfg) - if err != nil { - t.Fatal(err) - } - continue - } - - if step.Config != "" { - err := testStepNewConfig(t, c, wd, step) - if step.ExpectError != nil { - if err == nil { - t.Fatal("Expected an error but got none") - } - if !step.ExpectError.MatchString(err.Error()) { - t.Fatalf("Expected an error with pattern, no match on: %s", err) - } - } else { - if err != nil { - t.Fatal(err) - } - } - appliedCfg = step.Config - continue - } - - t.Fatal("Unsupported test mode") - } -} - -func planIsEmpty(plan *tfjson.Plan) bool { - for _, rc := range plan.ResourceChanges { - if rc.Mode == tfjson.DataResourceMode { - // Skip data sources as the current implementation ignores - // existing state and they are all re-read every time - continue - } - - for _, a := range rc.Change.Actions { - if a != tfjson.ActionNoop { - return false - } - } - } - return true -} -func testIDRefresh(c TestCase, t *testing.T, wd *tftest.WorkingDir, step TestStep, r *terraform.ResourceState) error { - spewConf := spew.NewDefaultConfig() - spewConf.SortKeys = true - - // Build the state. The state is just the resource with an ID. There - // are no attributes. We only set what is needed to perform a refresh. - state := terraform.NewState() - state.RootModule().Resources = make(map[string]*terraform.ResourceState) - state.RootModule().Resources[c.IDRefreshName] = &terraform.ResourceState{} - - // Temporarily set the config to a minimal provider config for the refresh - // test. After the refresh we can reset it. - cfg := testProviderConfig(c) - wd.RequireSetConfig(t, cfg) - defer wd.RequireSetConfig(t, step.Config) - - // Refresh! - wd.RequireRefresh(t) - state = getState(t, wd) - - // Verify attribute equivalence. - actualR := state.RootModule().Resources[c.IDRefreshName] - if actualR == nil { - return fmt.Errorf("Resource gone!") - } - if actualR.Primary == nil { - return fmt.Errorf("Resource has no primary instance") - } - actual := actualR.Primary.Attributes - expected := r.Primary.Attributes - // Remove fields we're ignoring - for _, v := range c.IDRefreshIgnore { - for k := range actual { - if strings.HasPrefix(k, v) { - delete(actual, k) - } - } - for k := range expected { - if strings.HasPrefix(k, v) { - delete(expected, k) - } - } - } - - if !reflect.DeepEqual(actual, expected) { - // Determine only the different attributes - for k, v := range expected { - if av, ok := actual[k]; ok && v == av { - delete(expected, k) - delete(actual, k) - } - } - - spewConf := spew.NewDefaultConfig() - spewConf.SortKeys = true - return fmt.Errorf( - "Attributes not equivalent. Difference is shown below. Top is actual, bottom is expected."+ - "\n\n%s\n\n%s", - spewConf.Sdump(actual), spewConf.Sdump(expected)) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_new_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_new_config.go deleted file mode 100644 index d2fbf29d783..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_new_config.go +++ /dev/null @@ -1,106 +0,0 @@ -package resource - -import ( - "testing" - - "github.com/davecgh/go-spew/spew" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - tftest "github.com/hashicorp/terraform-plugin-test" -) - -func testStepNewConfig(t *testing.T, c TestCase, wd *tftest.WorkingDir, step TestStep) error { - spewConf := spew.NewDefaultConfig() - spewConf.SortKeys = true - - var idRefreshCheck *terraform.ResourceState - idRefresh := c.IDRefreshName != "" - - if !step.Destroy { - state := getState(t, wd) - if err := testStepTaint(state, step); err != nil { - t.Fatalf("Error when tainting resources: %s", err) - } - } - - wd.RequireSetConfig(t, step.Config) - - if !step.PlanOnly { - err := wd.Apply() - if err != nil { - return err - } - - state := getState(t, wd) - if step.Check != nil { - if err := step.Check(state); err != nil { - t.Fatal(err) - } - } - } - - // Test for perpetual diffs by performing a plan, a refresh, and another plan - - // do a plan - wd.RequireCreatePlan(t) - plan := wd.RequireSavedPlan(t) - - if !planIsEmpty(plan) { - if step.ExpectNonEmptyPlan { - t.Log("[INFO] Got non-empty plan, as expected") - } else { - - t.Fatalf("After applying this test step, the plan was not empty. %s", spewConf.Sdump(plan)) - } - } - - // do a refresh - if !c.PreventPostDestroyRefresh { - wd.RequireRefresh(t) - } - - // do another plan - wd.RequireCreatePlan(t) - plan = wd.RequireSavedPlan(t) - - // check if plan is empty - if !planIsEmpty(plan) { - if step.ExpectNonEmptyPlan { - t.Log("[INFO] Got non-empty plan, as expected") - } else { - - t.Fatalf("After applying this test step and performing a `terraform refresh`, the plan was not empty. %s", spewConf.Sdump(plan)) - } - } - - // ID-ONLY REFRESH - // If we've never checked an id-only refresh and our state isn't - // empty, find the first resource and test it. - state := getState(t, wd) - if idRefresh && idRefreshCheck == nil && !state.Empty() { - // Find the first non-nil resource in the state - for _, m := range state.Modules { - if len(m.Resources) > 0 { - if v, ok := m.Resources[c.IDRefreshName]; ok { - idRefreshCheck = v - } - - break - } - } - - // If we have an instance to check for refreshes, do it - // immediately. We do it in the middle of another test - // because it shouldn't affect the overall state (refresh - // is read-only semantically) and we want to fail early if - // this fails. If refresh isn't read-only, then this will have - // caught a different bug. - if idRefreshCheck != nil { - if err := testIDRefresh(c, t, wd, step, idRefreshCheck); err != nil { - t.Fatalf( - "[ERROR] Test: ID-only test failed: %s", err) - } - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_new_import_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_new_import_state.go deleted file mode 100644 index ec2f9916827..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_new_import_state.go +++ /dev/null @@ -1,196 +0,0 @@ -package resource - -import ( - "reflect" - "strings" - "testing" - - "github.com/davecgh/go-spew/spew" - "github.com/hashicorp/terraform-plugin-sdk/acctest" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - tftest "github.com/hashicorp/terraform-plugin-test" -) - -func testStepNewImportState(t *testing.T, c TestCase, wd *tftest.WorkingDir, step TestStep, cfg string) error { - spewConf := spew.NewDefaultConfig() - spewConf.SortKeys = true - - if step.ResourceName == "" { - t.Fatal("ResourceName is required for an import state test") - } - - // get state from check sequence - state := getState(t, wd) - - // Determine the ID to import - var importId string - switch { - case step.ImportStateIdFunc != nil: - var err error - importId, err = step.ImportStateIdFunc(state) - if err != nil { - t.Fatal(err) - } - case step.ImportStateId != "": - importId = step.ImportStateId - default: - resource, err := testResource(step, state) - if err != nil { - t.Fatal(err) - } - importId = resource.Primary.ID - } - importId = step.ImportStateIdPrefix + importId - - // Create working directory for import tests - if step.Config == "" { - step.Config = cfg - if step.Config == "" { - t.Fatal("Cannot import state with no specified config") - } - } - importWd := acctest.TestHelper.RequireNewWorkingDir(t) - defer importWd.Close() - importWd.RequireSetConfig(t, step.Config) - importWd.RequireInit(t) - importWd.RequireImport(t, step.ResourceName, importId) - importState := getState(t, wd) - - // Go through the imported state and verify - if step.ImportStateCheck != nil { - var states []*terraform.InstanceState - for _, r := range importState.RootModule().Resources { - if r.Primary != nil { - is := r.Primary.DeepCopy() - is.Ephemeral.Type = r.Type // otherwise the check function cannot see the type - states = append(states, is) - } - } - if err := step.ImportStateCheck(states); err != nil { - t.Fatal(err) - } - } - - // Verify that all the states match - if step.ImportStateVerify { - new := importState.RootModule().Resources - old := state.RootModule().Resources - - for _, r := range new { - // Find the existing resource - var oldR *terraform.ResourceState - for _, r2 := range old { - if r2.Primary != nil && r2.Primary.ID == r.Primary.ID && r2.Type == r.Type { - oldR = r2 - break - } - } - if oldR == nil { - t.Fatalf( - "Failed state verification, resource with ID %s not found", - r.Primary.ID) - } - - // We'll try our best to find the schema for this resource type - // so we can ignore Removed fields during validation. If we fail - // to find the schema then we won't ignore them and so the test - // will need to rely on explicit ImportStateVerifyIgnore, though - // this shouldn't happen in any reasonable case. - // KEM CHANGE FROM OLD FRAMEWORK: Fail test if this happens. - var rsrcSchema *schema.Resource - providerAddr, diags := addrs.ParseAbsProviderConfigStr("provider." + r.Provider + "." + r.Type) - if diags.HasErrors() { - t.Fatalf("Failed to find schema for resource with ID %s", r.Primary) - } - - providerType := providerAddr.ProviderConfig.Type - if provider, ok := step.providers[providerType]; ok { - if provider, ok := provider.(*schema.Provider); ok { - rsrcSchema = provider.ResourcesMap[r.Type] - } - } - - // don't add empty flatmapped containers, so we can more easily - // compare the attributes - skipEmpty := func(k, v string) bool { - if strings.HasSuffix(k, ".#") || strings.HasSuffix(k, ".%") { - if v == "0" { - return true - } - } - return false - } - - // Compare their attributes - actual := make(map[string]string) - for k, v := range r.Primary.Attributes { - if skipEmpty(k, v) { - continue - } - actual[k] = v - } - - expected := make(map[string]string) - for k, v := range oldR.Primary.Attributes { - if skipEmpty(k, v) { - continue - } - expected[k] = v - } - - // Remove fields we're ignoring - for _, v := range step.ImportStateVerifyIgnore { - for k := range actual { - if strings.HasPrefix(k, v) { - delete(actual, k) - } - } - for k := range expected { - if strings.HasPrefix(k, v) { - delete(expected, k) - } - } - } - - // Also remove any attributes that are marked as "Removed" in the - // schema, if we have a schema to check that against. - if rsrcSchema != nil { - for k := range actual { - for _, schema := range rsrcSchema.SchemasForFlatmapPath(k) { - if schema.Removed != "" { - delete(actual, k) - break - } - } - } - for k := range expected { - for _, schema := range rsrcSchema.SchemasForFlatmapPath(k) { - if schema.Removed != "" { - delete(expected, k) - break - } - } - } - } - - if !reflect.DeepEqual(actual, expected) { - // Determine only the different attributes - for k, v := range expected { - if av, ok := actual[k]; ok && v == av { - delete(expected, k) - delete(actual, k) - } - } - - t.Fatalf( - "ImportStateVerify attributes not equivalent. Difference is shown below. Top is actual, bottom is expected."+ - "\n\n%s\n\n%s", - spewConf.Sdump(actual), spewConf.Sdump(expected)) - } - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/wait.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/wait.go deleted file mode 100644 index e56a5155d10..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/wait.go +++ /dev/null @@ -1,84 +0,0 @@ -package resource - -import ( - "sync" - "time" -) - -// Retry is a basic wrapper around StateChangeConf that will just retry -// a function until it no longer returns an error. -func Retry(timeout time.Duration, f RetryFunc) error { - // These are used to pull the error out of the function; need a mutex to - // avoid a data race. - var resultErr error - var resultErrMu sync.Mutex - - c := &StateChangeConf{ - Pending: []string{"retryableerror"}, - Target: []string{"success"}, - Timeout: timeout, - MinTimeout: 500 * time.Millisecond, - Refresh: func() (interface{}, string, error) { - rerr := f() - - resultErrMu.Lock() - defer resultErrMu.Unlock() - - if rerr == nil { - resultErr = nil - return 42, "success", nil - } - - resultErr = rerr.Err - - if rerr.Retryable { - return 42, "retryableerror", nil - } - return nil, "quit", rerr.Err - }, - } - - _, waitErr := c.WaitForState() - - // Need to acquire the lock here to be able to avoid race using resultErr as - // the return value - resultErrMu.Lock() - defer resultErrMu.Unlock() - - // resultErr may be nil because the wait timed out and resultErr was never - // set; this is still an error - if resultErr == nil { - return waitErr - } - // resultErr takes precedence over waitErr if both are set because it is - // more likely to be useful - return resultErr -} - -// RetryFunc is the function retried until it succeeds. -type RetryFunc func() *RetryError - -// RetryError is the required return type of RetryFunc. It forces client code -// to choose whether or not a given error is retryable. -type RetryError struct { - Err error - Retryable bool -} - -// RetryableError is a helper to create a RetryError that's retryable from a -// given error. -func RetryableError(err error) *RetryError { - if err == nil { - return nil - } - return &RetryError{Err: err, Retryable: true} -} - -// NonRetryableError is a helper to create a RetryError that's _not_ retryable -// from a given error. -func NonRetryableError(err error) *RetryError { - if err == nil { - return nil - } - return &RetryError{Err: err, Retryable: false} -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/backend.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/backend.go deleted file mode 100644 index 609c208b368..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/backend.go +++ /dev/null @@ -1,200 +0,0 @@ -package schema - -import ( - "context" - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - ctyconvert "github.com/zclconf/go-cty/cty/convert" -) - -// Backend represents a partial backend.Backend implementation and simplifies -// the creation of configuration loading and validation. -// -// Unlike other schema structs such as Provider, this struct is meant to be -// embedded within your actual implementation. It provides implementations -// only for Input and Configure and gives you a method for accessing the -// configuration in the form of a ResourceData that you're expected to call -// from the other implementation funcs. -type Backend struct { - // Schema is the schema for the configuration of this backend. If this - // Backend has no configuration this can be omitted. - Schema map[string]*Schema - - // ConfigureFunc is called to configure the backend. Use the - // FromContext* methods to extract information from the context. - // This can be nil, in which case nothing will be called but the - // config will still be stored. - ConfigureFunc func(context.Context) error - - config *ResourceData -} - -var ( - backendConfigKey = contextKey("backend config") -) - -// FromContextBackendConfig extracts a ResourceData with the configuration -// from the context. This should only be called by Backend functions. -func FromContextBackendConfig(ctx context.Context) *ResourceData { - return ctx.Value(backendConfigKey).(*ResourceData) -} - -func (b *Backend) ConfigSchema() *configschema.Block { - // This is an alias of CoreConfigSchema just to implement the - // backend.Backend interface. - return b.CoreConfigSchema() -} - -func (b *Backend) PrepareConfig(configVal cty.Value) (cty.Value, tfdiags.Diagnostics) { - if b == nil { - return configVal, nil - } - var diags tfdiags.Diagnostics - var err error - - // In order to use Transform below, this needs to be filled out completely - // according the schema. - configVal, err = b.CoreConfigSchema().CoerceValue(configVal) - if err != nil { - return configVal, diags.Append(err) - } - - // lookup any required, top-level attributes that are Null, and see if we - // have a Default value available. - configVal, err = cty.Transform(configVal, func(path cty.Path, val cty.Value) (cty.Value, error) { - // we're only looking for top-level attributes - if len(path) != 1 { - return val, nil - } - - // nothing to do if we already have a value - if !val.IsNull() { - return val, nil - } - - // get the Schema definition for this attribute - getAttr, ok := path[0].(cty.GetAttrStep) - // these should all exist, but just ignore anything strange - if !ok { - return val, nil - } - - attrSchema := b.Schema[getAttr.Name] - // continue to ignore anything that doesn't match - if attrSchema == nil { - return val, nil - } - - // this is deprecated, so don't set it - if attrSchema.Deprecated != "" || attrSchema.Removed != "" { - return val, nil - } - - // find a default value if it exists - def, err := attrSchema.DefaultValue() - if err != nil { - diags = diags.Append(fmt.Errorf("error getting default for %q: %s", getAttr.Name, err)) - return val, err - } - - // no default - if def == nil { - return val, nil - } - - // create a cty.Value and make sure it's the correct type - tmpVal := hcl2shim.HCL2ValueFromConfigValue(def) - - // helper/schema used to allow setting "" to a bool - if val.Type() == cty.Bool && tmpVal.RawEquals(cty.StringVal("")) { - // return a warning about the conversion - diags = diags.Append("provider set empty string as default value for bool " + getAttr.Name) - tmpVal = cty.False - } - - val, err = ctyconvert.Convert(tmpVal, val.Type()) - if err != nil { - diags = diags.Append(fmt.Errorf("error setting default for %q: %s", getAttr.Name, err)) - } - - return val, err - }) - if err != nil { - // any error here was already added to the diagnostics - return configVal, diags - } - - shimRC := b.shimConfig(configVal) - warns, errs := schemaMap(b.Schema).Validate(shimRC) - for _, warn := range warns { - diags = diags.Append(tfdiags.SimpleWarning(warn)) - } - for _, err := range errs { - diags = diags.Append(err) - } - return configVal, diags -} - -func (b *Backend) Configure(obj cty.Value) tfdiags.Diagnostics { - if b == nil { - return nil - } - - var diags tfdiags.Diagnostics - sm := schemaMap(b.Schema) - shimRC := b.shimConfig(obj) - - // Get a ResourceData for this configuration. To do this, we actually - // generate an intermediary "diff" although that is never exposed. - diff, err := sm.Diff(nil, shimRC, nil, nil, true) - if err != nil { - diags = diags.Append(err) - return diags - } - - data, err := sm.Data(nil, diff) - if err != nil { - diags = diags.Append(err) - return diags - } - b.config = data - - if b.ConfigureFunc != nil { - err = b.ConfigureFunc(context.WithValue( - context.Background(), backendConfigKey, data)) - if err != nil { - diags = diags.Append(err) - return diags - } - } - - return diags -} - -// shimConfig turns a new-style cty.Value configuration (which must be of -// an object type) into a minimal old-style *terraform.ResourceConfig object -// that should be populated enough to appease the not-yet-updated functionality -// in this package. This should be removed once everything is updated. -func (b *Backend) shimConfig(obj cty.Value) *terraform.ResourceConfig { - shimMap, ok := hcl2shim.ConfigValueFromHCL2(obj).(map[string]interface{}) - if !ok { - // If the configVal was nil, we still want a non-nil map here. - shimMap = map[string]interface{}{} - } - return &terraform.ResourceConfig{ - Config: shimMap, - Raw: shimMap, - } -} - -// Config returns the configuration. This is available after Configure is -// called. -func (b *Backend) Config() *ResourceData { - return b.config -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/provider.go deleted file mode 100644 index 2f88f1eab91..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/provider.go +++ /dev/null @@ -1,474 +0,0 @@ -package schema - -import ( - "context" - "errors" - "fmt" - "sort" - "sync" - - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -var ReservedProviderFields = []string{ - "alias", - "version", -} - -// Provider represents a resource provider in Terraform, and properly -// implements all of the ResourceProvider API. -// -// By defining a schema for the configuration of the provider, the -// map of supporting resources, and a configuration function, the schema -// framework takes over and handles all the provider operations for you. -// -// After defining the provider structure, it is unlikely that you'll require any -// of the methods on Provider itself. -type Provider struct { - // Schema is the schema for the configuration of this provider. If this - // provider has no configuration, this can be omitted. - // - // The keys of this map are the configuration keys, and the value is - // the schema describing the value of the configuration. - Schema map[string]*Schema - - // ResourcesMap is the list of available resources that this provider - // can manage, along with their Resource structure defining their - // own schemas and CRUD operations. - // - // Provider automatically handles routing operations such as Apply, - // Diff, etc. to the proper resource. - ResourcesMap map[string]*Resource - - // DataSourcesMap is the collection of available data sources that - // this provider implements, with a Resource instance defining - // the schema and Read operation of each. - // - // Resource instances for data sources must have a Read function - // and must *not* implement Create, Update or Delete. - DataSourcesMap map[string]*Resource - - // ConfigureFunc is a function for configuring the provider. If the - // provider doesn't need to be configured, this can be omitted. - // - // See the ConfigureFunc documentation for more information. - ConfigureFunc ConfigureFunc - - // MetaReset is called by TestReset to reset any state stored in the meta - // interface. This is especially important if the StopContext is stored by - // the provider. - MetaReset func() error - - meta interface{} - - // a mutex is required because TestReset can directly replace the stopCtx - stopMu sync.Mutex - stopCtx context.Context - stopCtxCancel context.CancelFunc - stopOnce sync.Once - - TerraformVersion string -} - -// ConfigureFunc is the function used to configure a Provider. -// -// The interface{} value returned by this function is stored and passed into -// the subsequent resources as the meta parameter. This return value is -// usually used to pass along a configured API client, a configuration -// structure, etc. -type ConfigureFunc func(*ResourceData) (interface{}, error) - -// InternalValidate should be called to validate the structure -// of the provider. -// -// This should be called in a unit test for any provider to verify -// before release that a provider is properly configured for use with -// this library. -func (p *Provider) InternalValidate() error { - if p == nil { - return errors.New("provider is nil") - } - - var validationErrors error - sm := schemaMap(p.Schema) - if err := sm.InternalValidate(sm); err != nil { - validationErrors = multierror.Append(validationErrors, err) - } - - // Provider-specific checks - for k := range sm { - if isReservedProviderFieldName(k) { - return fmt.Errorf("%s is a reserved field name for a provider", k) - } - } - - for k, r := range p.ResourcesMap { - if err := r.InternalValidate(nil, true); err != nil { - validationErrors = multierror.Append(validationErrors, fmt.Errorf("resource %s: %s", k, err)) - } - } - - for k, r := range p.DataSourcesMap { - if err := r.InternalValidate(nil, false); err != nil { - validationErrors = multierror.Append(validationErrors, fmt.Errorf("data source %s: %s", k, err)) - } - } - - return validationErrors -} - -func isReservedProviderFieldName(name string) bool { - for _, reservedName := range ReservedProviderFields { - if name == reservedName { - return true - } - } - return false -} - -// Meta returns the metadata associated with this provider that was -// returned by the Configure call. It will be nil until Configure is called. -func (p *Provider) Meta() interface{} { - return p.meta -} - -// SetMeta can be used to forcefully set the Meta object of the provider. -// Note that if Configure is called the return value will override anything -// set here. -func (p *Provider) SetMeta(v interface{}) { - p.meta = v -} - -// Stopped reports whether the provider has been stopped or not. -func (p *Provider) Stopped() bool { - ctx := p.StopContext() - select { - case <-ctx.Done(): - return true - default: - return false - } -} - -// StopCh returns a channel that is closed once the provider is stopped. -func (p *Provider) StopContext() context.Context { - p.stopOnce.Do(p.stopInit) - - p.stopMu.Lock() - defer p.stopMu.Unlock() - - return p.stopCtx -} - -func (p *Provider) stopInit() { - p.stopMu.Lock() - defer p.stopMu.Unlock() - - p.stopCtx, p.stopCtxCancel = context.WithCancel(context.Background()) -} - -// Stop implementation of terraform.ResourceProvider interface. -func (p *Provider) Stop() error { - p.stopOnce.Do(p.stopInit) - - p.stopMu.Lock() - defer p.stopMu.Unlock() - - p.stopCtxCancel() - return nil -} - -// TestReset resets any state stored in the Provider, and will call TestReset -// on Meta if it implements the TestProvider interface. -// This may be used to reset the schema.Provider at the start of a test, and is -// automatically called by resource.Test. -func (p *Provider) TestReset() error { - p.stopInit() - if p.MetaReset != nil { - return p.MetaReset() - } - return nil -} - -// GetSchema implementation of terraform.ResourceProvider interface -func (p *Provider) GetSchema(req *terraform.ProviderSchemaRequest) (*terraform.ProviderSchema, error) { - resourceTypes := map[string]*configschema.Block{} - dataSources := map[string]*configschema.Block{} - - for _, name := range req.ResourceTypes { - if r, exists := p.ResourcesMap[name]; exists { - resourceTypes[name] = r.CoreConfigSchema() - } - } - for _, name := range req.DataSources { - if r, exists := p.DataSourcesMap[name]; exists { - dataSources[name] = r.CoreConfigSchema() - } - } - - return &terraform.ProviderSchema{ - Provider: schemaMap(p.Schema).CoreConfigSchema(), - ResourceTypes: resourceTypes, - DataSources: dataSources, - }, nil -} - -// Input implementation of terraform.ResourceProvider interface. -func (p *Provider) Input( - input terraform.UIInput, - c *terraform.ResourceConfig) (*terraform.ResourceConfig, error) { - return schemaMap(p.Schema).Input(input, c) -} - -// Validate implementation of terraform.ResourceProvider interface. -func (p *Provider) Validate(c *terraform.ResourceConfig) ([]string, []error) { - if err := p.InternalValidate(); err != nil { - return nil, []error{fmt.Errorf( - "Internal validation of the provider failed! This is always a bug\n"+ - "with the provider itself, and not a user issue. Please report\n"+ - "this bug:\n\n%s", err)} - } - - return schemaMap(p.Schema).Validate(c) -} - -// ValidateResource implementation of terraform.ResourceProvider interface. -func (p *Provider) ValidateResource( - t string, c *terraform.ResourceConfig) ([]string, []error) { - r, ok := p.ResourcesMap[t] - if !ok { - return nil, []error{fmt.Errorf( - "Provider doesn't support resource: %s", t)} - } - - return r.Validate(c) -} - -// Configure implementation of terraform.ResourceProvider interface. -func (p *Provider) Configure(c *terraform.ResourceConfig) error { - // No configuration - if p.ConfigureFunc == nil { - return nil - } - - sm := schemaMap(p.Schema) - - // Get a ResourceData for this configuration. To do this, we actually - // generate an intermediary "diff" although that is never exposed. - diff, err := sm.Diff(nil, c, nil, p.meta, true) - if err != nil { - return err - } - - data, err := sm.Data(nil, diff) - if err != nil { - return err - } - - if p.TerraformVersion == "" { - // Terraform 0.12 introduced this field to the protocol - // We can therefore assume that if it's unconfigured at this point, it's 0.10 or 0.11 - p.TerraformVersion = "0.11+compatible" - } - meta, err := p.ConfigureFunc(data) - if err != nil { - return err - } - - p.meta = meta - return nil -} - -// Apply implementation of terraform.ResourceProvider interface. -func (p *Provider) Apply( - info *terraform.InstanceInfo, - s *terraform.InstanceState, - d *terraform.InstanceDiff) (*terraform.InstanceState, error) { - r, ok := p.ResourcesMap[info.Type] - if !ok { - return nil, fmt.Errorf("unknown resource type: %s", info.Type) - } - - return r.Apply(s, d, p.meta) -} - -// Diff implementation of terraform.ResourceProvider interface. -func (p *Provider) Diff( - info *terraform.InstanceInfo, - s *terraform.InstanceState, - c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) { - r, ok := p.ResourcesMap[info.Type] - if !ok { - return nil, fmt.Errorf("unknown resource type: %s", info.Type) - } - - return r.Diff(s, c, p.meta) -} - -// SimpleDiff is used by the new protocol wrappers to get a diff that doesn't -// attempt to calculate ignore_changes. -func (p *Provider) SimpleDiff( - info *terraform.InstanceInfo, - s *terraform.InstanceState, - c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) { - r, ok := p.ResourcesMap[info.Type] - if !ok { - return nil, fmt.Errorf("unknown resource type: %s", info.Type) - } - - return r.simpleDiff(s, c, p.meta) -} - -// Refresh implementation of terraform.ResourceProvider interface. -func (p *Provider) Refresh( - info *terraform.InstanceInfo, - s *terraform.InstanceState) (*terraform.InstanceState, error) { - r, ok := p.ResourcesMap[info.Type] - if !ok { - return nil, fmt.Errorf("unknown resource type: %s", info.Type) - } - - return r.Refresh(s, p.meta) -} - -// Resources implementation of terraform.ResourceProvider interface. -func (p *Provider) Resources() []terraform.ResourceType { - keys := make([]string, 0, len(p.ResourcesMap)) - for k := range p.ResourcesMap { - keys = append(keys, k) - } - sort.Strings(keys) - - result := make([]terraform.ResourceType, 0, len(keys)) - for _, k := range keys { - resource := p.ResourcesMap[k] - - // This isn't really possible (it'd fail InternalValidate), but - // we do it anyways to avoid a panic. - if resource == nil { - resource = &Resource{} - } - - result = append(result, terraform.ResourceType{ - Name: k, - Importable: resource.Importer != nil, - - // Indicates that a provider is compiled against a new enough - // version of core to support the GetSchema method. - SchemaAvailable: true, - }) - } - - return result -} - -func (p *Provider) ImportState( - info *terraform.InstanceInfo, - id string) ([]*terraform.InstanceState, error) { - // Find the resource - r, ok := p.ResourcesMap[info.Type] - if !ok { - return nil, fmt.Errorf("unknown resource type: %s", info.Type) - } - - // If it doesn't support import, error - if r.Importer == nil { - return nil, fmt.Errorf("resource %s doesn't support import", info.Type) - } - - // Create the data - data := r.Data(nil) - data.SetId(id) - data.SetType(info.Type) - - // Call the import function - results := []*ResourceData{data} - if r.Importer.State != nil { - var err error - results, err = r.Importer.State(data, p.meta) - if err != nil { - return nil, err - } - } - - // Convert the results to InstanceState values and return it - states := make([]*terraform.InstanceState, len(results)) - for i, r := range results { - states[i] = r.State() - } - - // Verify that all are non-nil. If there are any nil the error - // isn't obvious so we circumvent that with a friendlier error. - for _, s := range states { - if s == nil { - return nil, fmt.Errorf( - "nil entry in ImportState results. This is always a bug with\n" + - "the resource that is being imported. Please report this as\n" + - "a bug to Terraform.") - } - } - - return states, nil -} - -// ValidateDataSource implementation of terraform.ResourceProvider interface. -func (p *Provider) ValidateDataSource( - t string, c *terraform.ResourceConfig) ([]string, []error) { - r, ok := p.DataSourcesMap[t] - if !ok { - return nil, []error{fmt.Errorf( - "Provider doesn't support data source: %s", t)} - } - - return r.Validate(c) -} - -// ReadDataDiff implementation of terraform.ResourceProvider interface. -func (p *Provider) ReadDataDiff( - info *terraform.InstanceInfo, - c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) { - - r, ok := p.DataSourcesMap[info.Type] - if !ok { - return nil, fmt.Errorf("unknown data source: %s", info.Type) - } - - return r.Diff(nil, c, p.meta) -} - -// RefreshData implementation of terraform.ResourceProvider interface. -func (p *Provider) ReadDataApply( - info *terraform.InstanceInfo, - d *terraform.InstanceDiff) (*terraform.InstanceState, error) { - - r, ok := p.DataSourcesMap[info.Type] - if !ok { - return nil, fmt.Errorf("unknown data source: %s", info.Type) - } - - return r.ReadDataApply(d, p.meta) -} - -// DataSources implementation of terraform.ResourceProvider interface. -func (p *Provider) DataSources() []terraform.DataSource { - keys := make([]string, 0, len(p.DataSourcesMap)) - for k := range p.DataSourcesMap { - keys = append(keys, k) - } - sort.Strings(keys) - - result := make([]terraform.DataSource, 0, len(keys)) - for _, k := range keys { - result = append(result, terraform.DataSource{ - Name: k, - - // Indicates that a provider is compiled against a new enough - // version of core to support the GetSchema method. - SchemaAvailable: true, - }) - } - - return result -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource.go deleted file mode 100644 index 75cfe8857a3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource.go +++ /dev/null @@ -1,836 +0,0 @@ -package schema - -import ( - "errors" - "fmt" - "log" - "strconv" - - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/zclconf/go-cty/cty" -) - -var ReservedDataSourceFields = []string{ - "connection", - "count", - "depends_on", - "lifecycle", - "provider", - "provisioner", -} - -var ReservedResourceFields = []string{ - "connection", - "count", - "depends_on", - "id", - "lifecycle", - "provider", - "provisioner", -} - -// Resource represents a thing in Terraform that has a set of configurable -// attributes and a lifecycle (create, read, update, delete). -// -// The Resource schema is an abstraction that allows provider writers to -// worry only about CRUD operations while off-loading validation, diff -// generation, etc. to this higher level library. -// -// In spite of the name, this struct is not used only for terraform resources, -// but also for data sources. In the case of data sources, the Create, -// Update and Delete functions must not be provided. -type Resource struct { - // Schema is the schema for the configuration of this resource. - // - // The keys of this map are the configuration keys, and the values - // describe the schema of the configuration value. - // - // The schema is used to represent both configurable data as well - // as data that might be computed in the process of creating this - // resource. - Schema map[string]*Schema - - // SchemaVersion is the version number for this resource's Schema - // definition. The current SchemaVersion stored in the state for each - // resource. Provider authors can increment this version number - // when Schema semantics change. If the State's SchemaVersion is less than - // the current SchemaVersion, the InstanceState is yielded to the - // MigrateState callback, where the provider can make whatever changes it - // needs to update the state to be compatible to the latest version of the - // Schema. - // - // When unset, SchemaVersion defaults to 0, so provider authors can start - // their Versioning at any integer >= 1 - SchemaVersion int - - // MigrateState is deprecated and any new changes to a resource's schema - // should be handled by StateUpgraders. Existing MigrateState implementations - // should remain for compatibility with existing state. MigrateState will - // still be called if the stored SchemaVersion is less than the - // first version of the StateUpgraders. - // - // MigrateState is responsible for updating an InstanceState with an old - // version to the format expected by the current version of the Schema. - // - // It is called during Refresh if the State's stored SchemaVersion is less - // than the current SchemaVersion of the Resource. - // - // The function is yielded the state's stored SchemaVersion and a pointer to - // the InstanceState that needs updating, as well as the configured - // provider's configured meta interface{}, in case the migration process - // needs to make any remote API calls. - MigrateState StateMigrateFunc - - // StateUpgraders contains the functions responsible for upgrading an - // existing state with an old schema version to a newer schema. It is - // called specifically by Terraform when the stored schema version is less - // than the current SchemaVersion of the Resource. - // - // StateUpgraders map specific schema versions to a StateUpgrader - // function. The registered versions are expected to be ordered, - // consecutive values. The initial value may be greater than 0 to account - // for legacy schemas that weren't recorded and can be handled by - // MigrateState. - StateUpgraders []StateUpgrader - - // The functions below are the CRUD operations for this resource. - // - // The only optional operation is Update. If Update is not implemented, - // then updates will not be supported for this resource. - // - // The ResourceData parameter in the functions below are used to - // query configuration and changes for the resource as well as to set - // the ID, computed data, etc. - // - // The interface{} parameter is the result of the ConfigureFunc in - // the provider for this resource. If the provider does not define - // a ConfigureFunc, this will be nil. This parameter should be used - // to store API clients, configuration structures, etc. - // - // If any errors occur during each of the operation, an error should be - // returned. If a resource was partially updated, be careful to enable - // partial state mode for ResourceData and use it accordingly. - // - // Exists is a function that is called to check if a resource still - // exists. If this returns false, then this will affect the diff - // accordingly. If this function isn't set, it will not be called. You - // can also signal existence in the Read method by calling d.SetId("") - // if the Resource is no longer present and should be removed from state. - // The *ResourceData passed to Exists should _not_ be modified. - Create CreateFunc - Read ReadFunc - Update UpdateFunc - Delete DeleteFunc - Exists ExistsFunc - - // CustomizeDiff is a custom function for working with the diff that - // Terraform has created for this resource - it can be used to customize the - // diff that has been created, diff values not controlled by configuration, - // or even veto the diff altogether and abort the plan. It is passed a - // *ResourceDiff, a structure similar to ResourceData but lacking most write - // functions like Set, while introducing new functions that work with the - // diff such as SetNew, SetNewComputed, and ForceNew. - // - // The phases Terraform runs this in, and the state available via functions - // like Get and GetChange, are as follows: - // - // * New resource: One run with no state - // * Existing resource: One run with state - // * Existing resource, forced new: One run with state (before ForceNew), - // then one run without state (as if new resource) - // * Tainted resource: No runs (custom diff logic is skipped) - // * Destroy: No runs (standard diff logic is skipped on destroy diffs) - // - // This function needs to be resilient to support all scenarios. - // - // If this function needs to access external API resources, remember to flag - // the RequiresRefresh attribute mentioned below to ensure that - // -refresh=false is blocked when running plan or apply, as this means that - // this resource requires refresh-like behaviour to work effectively. - // - // For the most part, only computed fields can be customized by this - // function. - // - // This function is only allowed on regular resources (not data sources). - CustomizeDiff CustomizeDiffFunc - - // Importer is the ResourceImporter implementation for this resource. - // If this is nil, then this resource does not support importing. If - // this is non-nil, then it supports importing and ResourceImporter - // must be validated. The validity of ResourceImporter is verified - // by InternalValidate on Resource. - Importer *ResourceImporter - - // If non-empty, this string is emitted as a warning during Validate. - DeprecationMessage string - - // Timeouts allow users to specify specific time durations in which an - // operation should time out, to allow them to extend an action to suit their - // usage. For example, a user may specify a large Creation timeout for their - // AWS RDS Instance due to it's size, or restoring from a snapshot. - // Resource implementors must enable Timeout support by adding the allowed - // actions (Create, Read, Update, Delete, Default) to the Resource struct, and - // accessing them in the matching methods. - Timeouts *ResourceTimeout - - // Description is used as the description for docs, the language server and - // other user facing usage. It can be plain-text or markdown depending on the - // global DescriptionKind setting. - Description string -} - -// ShimInstanceStateFromValue converts a cty.Value to a -// terraform.InstanceState. -func (r *Resource) ShimInstanceStateFromValue(state cty.Value) (*terraform.InstanceState, error) { - // Get the raw shimmed value. While this is correct, the set hashes don't - // match those from the Schema. - s := terraform.NewInstanceStateShimmedFromValue(state, r.SchemaVersion) - - // We now rebuild the state through the ResourceData, so that the set indexes - // match what helper/schema expects. - data, err := schemaMap(r.Schema).Data(s, nil) - if err != nil { - return nil, err - } - - s = data.State() - if s == nil { - s = &terraform.InstanceState{} - } - return s, nil -} - -// See Resource documentation. -type CreateFunc func(*ResourceData, interface{}) error - -// See Resource documentation. -type ReadFunc func(*ResourceData, interface{}) error - -// See Resource documentation. -type UpdateFunc func(*ResourceData, interface{}) error - -// See Resource documentation. -type DeleteFunc func(*ResourceData, interface{}) error - -// See Resource documentation. -type ExistsFunc func(*ResourceData, interface{}) (bool, error) - -// See Resource documentation. -type StateMigrateFunc func( - int, *terraform.InstanceState, interface{}) (*terraform.InstanceState, error) - -type StateUpgrader struct { - // Version is the version schema that this Upgrader will handle, converting - // it to Version+1. - Version int - - // Type describes the schema that this function can upgrade. Type is - // required to decode the schema if the state was stored in a legacy - // flatmap format. - Type cty.Type - - // Upgrade takes the JSON encoded state and the provider meta value, and - // upgrades the state one single schema version. The provided state is - // deocded into the default json types using a map[string]interface{}. It - // is up to the StateUpgradeFunc to ensure that the returned value can be - // encoded using the new schema. - Upgrade StateUpgradeFunc -} - -// See StateUpgrader -type StateUpgradeFunc func(rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) - -// See Resource documentation. -type CustomizeDiffFunc func(*ResourceDiff, interface{}) error - -// Apply creates, updates, and/or deletes a resource. -func (r *Resource) Apply( - s *terraform.InstanceState, - d *terraform.InstanceDiff, - meta interface{}) (*terraform.InstanceState, error) { - data, err := schemaMap(r.Schema).Data(s, d) - if err != nil { - return s, err - } - - // Instance Diff shoould have the timeout info, need to copy it over to the - // ResourceData meta - rt := ResourceTimeout{} - if _, ok := d.Meta[TimeoutKey]; ok { - if err := rt.DiffDecode(d); err != nil { - log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) - } - } else if s != nil { - if _, ok := s.Meta[TimeoutKey]; ok { - if err := rt.StateDecode(s); err != nil { - log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) - } - } - } else { - log.Printf("[DEBUG] No meta timeoutkey found in Apply()") - } - data.timeouts = &rt - - if s == nil { - // The Terraform API dictates that this should never happen, but - // it doesn't hurt to be safe in this case. - s = new(terraform.InstanceState) - } - - if d.Destroy || d.RequiresNew() { - if s.ID != "" { - // Destroy the resource since it is created - if err := r.Delete(data, meta); err != nil { - return r.recordCurrentSchemaVersion(data.State()), err - } - - // Make sure the ID is gone. - data.SetId("") - } - - // If we're only destroying, and not creating, then return - // now since we're done! - if !d.RequiresNew() { - return nil, nil - } - - // Reset the data to be stateless since we just destroyed - data, err = schemaMap(r.Schema).Data(nil, d) - // data was reset, need to re-apply the parsed timeouts - data.timeouts = &rt - if err != nil { - return nil, err - } - } - - err = nil - if data.Id() == "" { - // We're creating, it is a new resource. - data.MarkNewResource() - err = r.Create(data, meta) - } else { - if r.Update == nil { - return s, fmt.Errorf("doesn't support update") - } - - err = r.Update(data, meta) - } - - return r.recordCurrentSchemaVersion(data.State()), err -} - -// Diff returns a diff of this resource. -func (r *Resource) Diff( - s *terraform.InstanceState, - c *terraform.ResourceConfig, - meta interface{}) (*terraform.InstanceDiff, error) { - - t := &ResourceTimeout{} - err := t.ConfigDecode(r, c) - - if err != nil { - return nil, fmt.Errorf("[ERR] Error decoding timeout: %s", err) - } - - instanceDiff, err := schemaMap(r.Schema).Diff(s, c, r.CustomizeDiff, meta, true) - if err != nil { - return instanceDiff, err - } - - if instanceDiff != nil { - if err := t.DiffEncode(instanceDiff); err != nil { - log.Printf("[ERR] Error encoding timeout to instance diff: %s", err) - } - } else { - log.Printf("[DEBUG] Instance Diff is nil in Diff()") - } - - return instanceDiff, err -} - -func (r *Resource) simpleDiff( - s *terraform.InstanceState, - c *terraform.ResourceConfig, - meta interface{}) (*terraform.InstanceDiff, error) { - - instanceDiff, err := schemaMap(r.Schema).Diff(s, c, r.CustomizeDiff, meta, false) - if err != nil { - return instanceDiff, err - } - - if instanceDiff == nil { - instanceDiff = terraform.NewInstanceDiff() - } - - // Make sure the old value is set in each of the instance diffs. - // This was done by the RequiresNew logic in the full legacy Diff. - for k, attr := range instanceDiff.Attributes { - if attr == nil { - continue - } - if s != nil { - attr.Old = s.Attributes[k] - } - } - - return instanceDiff, nil -} - -// Validate validates the resource configuration against the schema. -func (r *Resource) Validate(c *terraform.ResourceConfig) ([]string, []error) { - warns, errs := schemaMap(r.Schema).Validate(c) - - if r.DeprecationMessage != "" { - warns = append(warns, r.DeprecationMessage) - } - - return warns, errs -} - -// ReadDataApply loads the data for a data source, given a diff that -// describes the configuration arguments and desired computed attributes. -func (r *Resource) ReadDataApply( - d *terraform.InstanceDiff, - meta interface{}, -) (*terraform.InstanceState, error) { - // Data sources are always built completely from scratch - // on each read, so the source state is always nil. - data, err := schemaMap(r.Schema).Data(nil, d) - if err != nil { - return nil, err - } - - err = r.Read(data, meta) - state := data.State() - if state != nil && state.ID == "" { - // Data sources can set an ID if they want, but they aren't - // required to; we'll provide a placeholder if they don't, - // to preserve the invariant that all resources have non-empty - // ids. - state.ID = "-" - } - - return r.recordCurrentSchemaVersion(state), err -} - -// RefreshWithoutUpgrade reads the instance state, but does not call -// MigrateState or the StateUpgraders, since those are now invoked in a -// separate API call. -// RefreshWithoutUpgrade is part of the new plugin shims. -func (r *Resource) RefreshWithoutUpgrade( - s *terraform.InstanceState, - meta interface{}) (*terraform.InstanceState, error) { - // If the ID is already somehow blank, it doesn't exist - if s.ID == "" { - return nil, nil - } - - rt := ResourceTimeout{} - if _, ok := s.Meta[TimeoutKey]; ok { - if err := rt.StateDecode(s); err != nil { - log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) - } - } - - if r.Exists != nil { - // Make a copy of data so that if it is modified it doesn't - // affect our Read later. - data, err := schemaMap(r.Schema).Data(s, nil) - data.timeouts = &rt - - if err != nil { - return s, err - } - - exists, err := r.Exists(data, meta) - if err != nil { - return s, err - } - if !exists { - return nil, nil - } - } - - data, err := schemaMap(r.Schema).Data(s, nil) - data.timeouts = &rt - if err != nil { - return s, err - } - - err = r.Read(data, meta) - state := data.State() - if state != nil && state.ID == "" { - state = nil - } - - return r.recordCurrentSchemaVersion(state), err -} - -// Refresh refreshes the state of the resource. -func (r *Resource) Refresh( - s *terraform.InstanceState, - meta interface{}) (*terraform.InstanceState, error) { - // If the ID is already somehow blank, it doesn't exist - if s.ID == "" { - return nil, nil - } - - rt := ResourceTimeout{} - if _, ok := s.Meta[TimeoutKey]; ok { - if err := rt.StateDecode(s); err != nil { - log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) - } - } - - if r.Exists != nil { - // Make a copy of data so that if it is modified it doesn't - // affect our Read later. - data, err := schemaMap(r.Schema).Data(s, nil) - data.timeouts = &rt - - if err != nil { - return s, err - } - - exists, err := r.Exists(data, meta) - if err != nil { - return s, err - } - if !exists { - return nil, nil - } - } - - // there may be new StateUpgraders that need to be run - s, err := r.upgradeState(s, meta) - if err != nil { - return s, err - } - - data, err := schemaMap(r.Schema).Data(s, nil) - data.timeouts = &rt - if err != nil { - return s, err - } - - err = r.Read(data, meta) - state := data.State() - if state != nil && state.ID == "" { - state = nil - } - - return r.recordCurrentSchemaVersion(state), err -} - -func (r *Resource) upgradeState(s *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { - var err error - - needsMigration, stateSchemaVersion := r.checkSchemaVersion(s) - migrate := needsMigration && r.MigrateState != nil - - if migrate { - s, err = r.MigrateState(stateSchemaVersion, s, meta) - if err != nil { - return s, err - } - } - - if len(r.StateUpgraders) == 0 { - return s, nil - } - - // If we ran MigrateState, then the stateSchemaVersion value is no longer - // correct. We can expect the first upgrade function to be the correct - // schema type version. - if migrate { - stateSchemaVersion = r.StateUpgraders[0].Version - } - - schemaType := r.CoreConfigSchema().ImpliedType() - // find the expected type to convert the state - for _, upgrader := range r.StateUpgraders { - if stateSchemaVersion == upgrader.Version { - schemaType = upgrader.Type - } - } - - // StateUpgraders only operate on the new JSON format state, so the state - // need to be converted. - stateVal, err := StateValueFromInstanceState(s, schemaType) - if err != nil { - return nil, err - } - - jsonState, err := StateValueToJSONMap(stateVal, schemaType) - if err != nil { - return nil, err - } - - for _, upgrader := range r.StateUpgraders { - if stateSchemaVersion != upgrader.Version { - continue - } - - jsonState, err = upgrader.Upgrade(jsonState, meta) - if err != nil { - return nil, err - } - stateSchemaVersion++ - } - - // now we need to re-flatmap the new state - stateVal, err = JSONMapToStateValue(jsonState, r.CoreConfigSchema()) - if err != nil { - return nil, err - } - - return r.ShimInstanceStateFromValue(stateVal) -} - -// InternalValidate should be called to validate the structure -// of the resource. -// -// This should be called in a unit test for any resource to verify -// before release that a resource is properly configured for use with -// this library. -// -// Provider.InternalValidate() will automatically call this for all of -// the resources it manages, so you don't need to call this manually if it -// is part of a Provider. -func (r *Resource) InternalValidate(topSchemaMap schemaMap, writable bool) error { - if r == nil { - return errors.New("resource is nil") - } - - if !writable { - if r.Create != nil || r.Update != nil || r.Delete != nil { - return fmt.Errorf("must not implement Create, Update or Delete") - } - - // CustomizeDiff cannot be defined for read-only resources - if r.CustomizeDiff != nil { - return fmt.Errorf("cannot implement CustomizeDiff") - } - } - - tsm := topSchemaMap - - if r.isTopLevel() && writable { - // All non-Computed attributes must be ForceNew if Update is not defined - if r.Update == nil { - nonForceNewAttrs := make([]string, 0) - for k, v := range r.Schema { - if !v.ForceNew && !v.Computed { - nonForceNewAttrs = append(nonForceNewAttrs, k) - } - } - if len(nonForceNewAttrs) > 0 { - return fmt.Errorf( - "No Update defined, must set ForceNew on: %#v", nonForceNewAttrs) - } - } else { - nonUpdateableAttrs := make([]string, 0) - for k, v := range r.Schema { - if v.ForceNew || v.Computed && !v.Optional { - nonUpdateableAttrs = append(nonUpdateableAttrs, k) - } - } - updateableAttrs := len(r.Schema) - len(nonUpdateableAttrs) - if updateableAttrs == 0 { - return fmt.Errorf( - "All fields are ForceNew or Computed w/out Optional, Update is superfluous") - } - } - - tsm = schemaMap(r.Schema) - - // Destroy, and Read are required - if r.Read == nil { - return fmt.Errorf("Read must be implemented") - } - if r.Delete == nil { - return fmt.Errorf("Delete must be implemented") - } - - // If we have an importer, we need to verify the importer. - if r.Importer != nil { - if err := r.Importer.InternalValidate(); err != nil { - return err - } - } - - for k, f := range tsm { - if isReservedResourceFieldName(k, f) { - return fmt.Errorf("%s is a reserved field name", k) - } - } - } - - lastVersion := -1 - for _, u := range r.StateUpgraders { - if lastVersion >= 0 && u.Version-lastVersion > 1 { - return fmt.Errorf("missing schema version between %d and %d", lastVersion, u.Version) - } - - if u.Version >= r.SchemaVersion { - return fmt.Errorf("StateUpgrader version %d is >= current version %d", u.Version, r.SchemaVersion) - } - - if !u.Type.IsObjectType() { - return fmt.Errorf("StateUpgrader %d type is not cty.Object", u.Version) - } - - if u.Upgrade == nil { - return fmt.Errorf("StateUpgrader %d missing StateUpgradeFunc", u.Version) - } - - lastVersion = u.Version - } - - if lastVersion >= 0 && lastVersion != r.SchemaVersion-1 { - return fmt.Errorf("missing StateUpgrader between %d and %d", lastVersion, r.SchemaVersion) - } - - // Data source - if r.isTopLevel() && !writable { - tsm = schemaMap(r.Schema) - for k := range tsm { - if isReservedDataSourceFieldName(k) { - return fmt.Errorf("%s is a reserved field name", k) - } - } - } - - return schemaMap(r.Schema).InternalValidate(tsm) -} - -func isReservedDataSourceFieldName(name string) bool { - for _, reservedName := range ReservedDataSourceFields { - if name == reservedName { - return true - } - } - return false -} - -func isReservedResourceFieldName(name string, s *Schema) bool { - // Allow phasing out "id" - // See https://github.com/terraform-providers/terraform-provider-aws/pull/1626#issuecomment-328881415 - if name == "id" && (s.Deprecated != "" || s.Removed != "") { - return false - } - - for _, reservedName := range ReservedResourceFields { - if name == reservedName { - return true - } - } - return false -} - -// Data returns a ResourceData struct for this Resource. Each return value -// is a separate copy and can be safely modified differently. -// -// The data returned from this function has no actual affect on the Resource -// itself (including the state given to this function). -// -// This function is useful for unit tests and ResourceImporter functions. -func (r *Resource) Data(s *terraform.InstanceState) *ResourceData { - result, err := schemaMap(r.Schema).Data(s, nil) - if err != nil { - // At the time of writing, this isn't possible (Data never returns - // non-nil errors). We panic to find this in the future if we have to. - // I don't see a reason for Data to ever return an error. - panic(err) - } - - // load the Resource timeouts - result.timeouts = r.Timeouts - if result.timeouts == nil { - result.timeouts = &ResourceTimeout{} - } - - // Set the schema version to latest by default - result.meta = map[string]interface{}{ - "schema_version": strconv.Itoa(r.SchemaVersion), - } - - return result -} - -// TestResourceData Yields a ResourceData filled with this resource's schema for use in unit testing -// -// TODO: May be able to be removed with the above ResourceData function. -func (r *Resource) TestResourceData() *ResourceData { - return &ResourceData{ - schema: r.Schema, - } -} - -// SchemasForFlatmapPath tries its best to find a sequence of schemas that -// the given dot-delimited attribute path traverses through in the schema -// of the receiving Resource. -func (r *Resource) SchemasForFlatmapPath(path string) []*Schema { - return SchemasForFlatmapPath(path, r.Schema) -} - -// Returns true if the resource is "top level" i.e. not a sub-resource. -func (r *Resource) isTopLevel() bool { - // TODO: This is a heuristic; replace with a definitive attribute? - return (r.Create != nil || r.Read != nil) -} - -// Determines if a given InstanceState needs to be migrated by checking the -// stored version number with the current SchemaVersion -func (r *Resource) checkSchemaVersion(is *terraform.InstanceState) (bool, int) { - // Get the raw interface{} value for the schema version. If it doesn't - // exist or is nil then set it to zero. - raw := is.Meta["schema_version"] - if raw == nil { - raw = "0" - } - - // Try to convert it to a string. If it isn't a string then we pretend - // that it isn't set at all. It should never not be a string unless it - // was manually tampered with. - rawString, ok := raw.(string) - if !ok { - rawString = "0" - } - - stateSchemaVersion, _ := strconv.Atoi(rawString) - - // Don't run MigrateState if the version is handled by a StateUpgrader, - // since StateMigrateFuncs are not required to handle unknown versions - maxVersion := r.SchemaVersion - if len(r.StateUpgraders) > 0 { - maxVersion = r.StateUpgraders[0].Version - } - - return stateSchemaVersion < maxVersion, stateSchemaVersion -} - -func (r *Resource) recordCurrentSchemaVersion( - state *terraform.InstanceState) *terraform.InstanceState { - if state != nil && r.SchemaVersion > 0 { - if state.Meta == nil { - state.Meta = make(map[string]interface{}) - } - state.Meta["schema_version"] = strconv.Itoa(r.SchemaVersion) - } - return state -} - -// Noop is a convenience implementation of resource function which takes -// no action and returns no error. -func Noop(*ResourceData, interface{}) error { - return nil -} - -// RemoveFromState is a convenience implementation of a resource function -// which sets the resource ID to empty string (to remove it from state) -// and returns no error. -func RemoveFromState(d *ResourceData, _ interface{}) error { - d.SetId("") - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_importer.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_importer.go deleted file mode 100644 index 5dada3caf32..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_importer.go +++ /dev/null @@ -1,52 +0,0 @@ -package schema - -// ResourceImporter defines how a resource is imported in Terraform. This -// can be set onto a Resource struct to make it Importable. Not all resources -// have to be importable; if a Resource doesn't have a ResourceImporter then -// it won't be importable. -// -// "Importing" in Terraform is the process of taking an already-created -// resource and bringing it under Terraform management. This can include -// updating Terraform state, generating Terraform configuration, etc. -type ResourceImporter struct { - // The functions below must all be implemented for importing to work. - - // State is called to convert an ID to one or more InstanceState to - // insert into the Terraform state. If this isn't specified, then - // the ID is passed straight through. - State StateFunc -} - -// StateFunc is the function called to import a resource into the -// Terraform state. It is given a ResourceData with only ID set. This -// ID is going to be an arbitrary value given by the user and may not map -// directly to the ID format that the resource expects, so that should -// be validated. -// -// This should return a slice of ResourceData that turn into the state -// that was imported. This might be as simple as returning only the argument -// that was given to the function. In other cases (such as AWS security groups), -// an import may fan out to multiple resources and this will have to return -// multiple. -// -// To create the ResourceData structures for other resource types (if -// you have to), instantiate your resource and call the Data function. -type StateFunc func(*ResourceData, interface{}) ([]*ResourceData, error) - -// InternalValidate should be called to validate the structure of this -// importer. This should be called in a unit test. -// -// Resource.InternalValidate() will automatically call this, so this doesn't -// need to be called manually. Further, Resource.InternalValidate() is -// automatically called by Provider.InternalValidate(), so you only need -// to internal validate the provider. -func (r *ResourceImporter) InternalValidate() error { - return nil -} - -// ImportStatePassthrough is an implementation of StateFunc that can be -// used to simply pass the ID directly through. This should be used only -// in the case that an ID-only refresh is possible. -func ImportStatePassthrough(d *ResourceData, m interface{}) ([]*ResourceData, error) { - return []*ResourceData{d}, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/schema.go deleted file mode 100644 index 69ab09b7c5a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/schema.go +++ /dev/null @@ -1,1976 +0,0 @@ -// schema is a high-level framework for easily writing new providers -// for Terraform. Usage of schema is recommended over attempting to write -// to the low-level plugin interfaces manually. -// -// schema breaks down provider creation into simple CRUD operations for -// resources. The logic of diffing, destroying before creating, updating -// or creating, etc. is all handled by the framework. The plugin author -// only needs to implement a configuration schema and the CRUD operations and -// everything else is meant to just work. -// -// A good starting point is to view the Provider structure. -package schema - -import ( - "context" - "fmt" - "os" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "sync" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/mitchellh/copystructure" - "github.com/mitchellh/mapstructure" -) - -// Name of ENV variable which (if not empty) prefers panic over error -const PanicOnErr = "TF_SCHEMA_PANIC_ON_ERROR" - -// type used for schema package context keys -type contextKey string - -var ( - protoVersionMu sync.Mutex - protoVersion5 = false -) - -func isProto5() bool { - protoVersionMu.Lock() - defer protoVersionMu.Unlock() - return protoVersion5 - -} - -// SetProto5 enables a feature flag for any internal changes required required -// to work with the new plugin protocol. This should not be called by -// provider. -func SetProto5() { - protoVersionMu.Lock() - defer protoVersionMu.Unlock() - protoVersion5 = true -} - -// Schema is used to describe the structure of a value. -// -// Read the documentation of the struct elements for important details. -type Schema struct { - // Type is the type of the value and must be one of the ValueType values. - // - // This type not only determines what type is expected/valid in configuring - // this value, but also what type is returned when ResourceData.Get is - // called. The types returned by Get are: - // - // TypeBool - bool - // TypeInt - int - // TypeFloat - float64 - // TypeString - string - // TypeList - []interface{} - // TypeMap - map[string]interface{} - // TypeSet - *schema.Set - // - Type ValueType - - // ConfigMode allows for overriding the default behaviors for mapping - // schema entries onto configuration constructs. - // - // By default, the Elem field is used to choose whether a particular - // schema is represented in configuration as an attribute or as a nested - // block; if Elem is a *schema.Resource then it's a block and it's an - // attribute otherwise. - // - // If Elem is *schema.Resource then setting ConfigMode to - // SchemaConfigModeAttr will force it to be represented in configuration - // as an attribute, which means that the Computed flag can be used to - // provide default elements when the argument isn't set at all, while still - // allowing the user to force zero elements by explicitly assigning an - // empty list. - // - // When Computed is set without Optional, the attribute is not settable - // in configuration at all and so SchemaConfigModeAttr is the automatic - // behavior, and SchemaConfigModeBlock is not permitted. - ConfigMode SchemaConfigMode - - // If one of these is set, then this item can come from the configuration. - // Both cannot be set. If Optional is set, the value is optional. If - // Required is set, the value is required. - // - // One of these must be set if the value is not computed. That is: - // value either comes from the config, is computed, or is both. - Optional bool - Required bool - - // If this is non-nil, the provided function will be used during diff - // of this field. If this is nil, a default diff for the type of the - // schema will be used. - // - // This allows comparison based on something other than primitive, list - // or map equality - for example SSH public keys may be considered - // equivalent regardless of trailing whitespace. - 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. - // - // 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 - // will be no default and the user will be asked to fill it in. - // - // If either of these is set, then the user won't be asked for input - // for this key if the default is not nil. - Default interface{} - DefaultFunc SchemaDefaultFunc - - // Description is used as the description for docs, the language server and - // other user facing usage. It can be plain-text or markdown depending on the - // global DescriptionKind setting. - Description string - - // InputDefault is the default value to use for when inputs are requested. - // This differs from Default in that if Default is set, no input is - // asked for. If Input is asked, this will be the default value offered. - InputDefault string - - // The fields below relate to diffs. - // - // If Computed is true, then the result of this value is computed - // (unless specified by config) on creation. - // - // If ForceNew is true, then a change in this resource necessitates - // the creation of a new resource. - // - // StateFunc is a function called to change the value of this before - // storing it in the state (and likewise before comparing for diffs). - // The use for this is for example with large strings, you may want - // to simply store the hash of it. - Computed bool - ForceNew bool - StateFunc SchemaStateFunc - - // The following fields are only set for a TypeList, TypeSet, or TypeMap. - // - // Elem represents the element type. For a TypeMap, it must be a *Schema - // with a Type that is one of the primitives: TypeString, TypeBool, - // TypeInt, or TypeFloat. Otherwise it may be either a *Schema or a - // *Resource. If it is *Schema, the element type is just a simple value. - // If it is *Resource, the element type is a complex structure, - // potentially managed via its own CRUD actions on the API. - Elem interface{} - - // The following fields are only set for a TypeList or TypeSet. - // - // MaxItems defines a maximum amount of items that can exist within a - // TypeSet or TypeList. Specific use cases would be if a TypeSet is being - // used to wrap a complex structure, however more than one instance would - // cause instability. - // - // MinItems defines a minimum amount of items that can exist within a - // TypeSet or TypeList. Specific use cases would be if a TypeSet is being - // used to wrap a complex structure, however less than one instance would - // cause instability. - // - // If the field Optional is set to true then MinItems is ignored and thus - // effectively zero. - MaxItems int - MinItems int - - // PromoteSingle originally allowed for a single element to be assigned - // where a primitive list was expected, but this no longer works from - // Terraform v0.12 onwards (Terraform Core will require a list to be set - // regardless of what this is set to) and so only applies to Terraform v0.11 - // and earlier, and so should be used only to retain this functionality - // for those still using v0.11 with a provider that formerly used this. - PromoteSingle bool - - // The following fields are only valid for a TypeSet type. - // - // Set defines a function to determine the unique ID of an item so that - // a proper set can be built. - Set SchemaSetFunc - - // ComputedWhen is a set of queries on the configuration. Whenever any - // of these things is changed, it will require a recompute (this requires - // that Computed is set to true). - // - // NOTE: This currently does not work. - ComputedWhen []string - - // ConflictsWith is a set of schema keys that conflict with this schema. - // This will only check that they're set in the _config_. This will not - // raise an error for a malfunctioning resource that sets a conflicting - // key. - // - // ExactlyOneOf is a set of schema keys that, when set, only one of the - // keys in that list can be specified. It will error if none are - // specified as well. - // - // AtLeastOneOf is a set of schema keys that, when set, at least one of - // the keys in that list must be specified. - ConflictsWith []string - ExactlyOneOf []string - AtLeastOneOf []string - - // When Deprecated is set, this attribute is deprecated. - // - // A deprecated field still works, but will probably stop working in near - // future. This string is the message shown to the user with instructions on - // how to address the deprecation. - Deprecated string - - // When Removed is set, this attribute has been removed from the schema - // - // Removed attributes can be left in the Schema to generate informative error - // messages for the user when they show up in resource configurations. - // This string is the message shown to the user with instructions on - // what do to about the removed attribute. - Removed string - - // ValidateFunc allows individual fields to define arbitrary validation - // logic. It is yielded the provided config value as an interface{} that is - // guaranteed to be of the proper Schema type, and it can yield warnings or - // errors based on inspection of that value. - // - // ValidateFunc is honored only when the schema's Type is set to TypeInt, - // TypeFloat, TypeString, TypeBool, or TypeMap. It is ignored for all other types. - ValidateFunc SchemaValidateFunc - - // Sensitive ensures that the attribute's value does not get displayed in - // logs or regular output. It should be used for passwords or other - // secret fields. Future versions of Terraform may encrypt these - // values. - Sensitive bool -} - -// SchemaConfigMode is used to influence how a schema item is mapped into a -// corresponding configuration construct, using the ConfigMode field of -// Schema. -type SchemaConfigMode int - -const ( - SchemaConfigModeAuto SchemaConfigMode = iota - SchemaConfigModeAttr - SchemaConfigModeBlock -) - -// SchemaDiffSuppressFunc is a function which can be used to determine -// whether a detected diff on a schema element is "valid" or not, and -// suppress it from the plan if necessary. -// -// Return true if the diff should be suppressed, false to retain it. -type SchemaDiffSuppressFunc func(k, old, new string, d *ResourceData) bool - -// SchemaDefaultFunc is a function called to return a default value for -// a field. -type SchemaDefaultFunc func() (interface{}, error) - -// EnvDefaultFunc is a helper function that returns the value of the -// given environment variable, if one exists, or the default value -// otherwise. -func EnvDefaultFunc(k string, dv interface{}) SchemaDefaultFunc { - return func() (interface{}, error) { - if v := os.Getenv(k); v != "" { - return v, nil - } - - return dv, nil - } -} - -// MultiEnvDefaultFunc is a helper function that returns the value of the first -// environment variable in the given list that returns a non-empty value. If -// none of the environment variables return a value, the default value is -// returned. -func MultiEnvDefaultFunc(ks []string, dv interface{}) SchemaDefaultFunc { - return func() (interface{}, error) { - for _, k := range ks { - if v := os.Getenv(k); v != "" { - return v, nil - } - } - return dv, nil - } -} - -// SchemaSetFunc is a function that must return a unique ID for the given -// element. This unique ID is used to store the element in a hash. -type SchemaSetFunc func(interface{}) int - -// SchemaStateFunc is a function used to convert some type to a string -// to be stored in the state. -type SchemaStateFunc func(interface{}) string - -// SchemaValidateFunc is a function used to validate a single field in the -// schema. -type SchemaValidateFunc func(interface{}, string) ([]string, []error) - -func (s *Schema) GoString() string { - return fmt.Sprintf("*%#v", *s) -} - -// Returns a default value for this schema by either reading Default or -// evaluating DefaultFunc. If neither of these are defined, returns nil. -func (s *Schema) DefaultValue() (interface{}, error) { - if s.Default != nil { - return s.Default, nil - } - - if s.DefaultFunc != nil { - defaultValue, err := s.DefaultFunc() - if err != nil { - return nil, fmt.Errorf("error loading default: %s", err) - } - return defaultValue, nil - } - - return nil, nil -} - -// Returns a zero value for the schema. -func (s *Schema) ZeroValue() interface{} { - // If it's a set then we'll do a bit of extra work to provide the - // right hashing function in our empty value. - if s.Type == TypeSet { - setFunc := s.Set - if setFunc == nil { - // Default set function uses the schema to hash the whole value - elem := s.Elem - switch t := elem.(type) { - case *Schema: - setFunc = HashSchema(t) - case *Resource: - setFunc = HashResource(t) - default: - panic("invalid set element type") - } - } - return &Set{F: setFunc} - } else { - return s.Type.Zero() - } -} - -func (s *Schema) finalizeDiff(d *terraform.ResourceAttrDiff, customized bool) *terraform.ResourceAttrDiff { - if d == nil { - return d - } - - if s.Type == TypeBool { - normalizeBoolString := func(s string) string { - switch s { - case "0": - return "false" - case "1": - return "true" - } - return s - } - d.Old = normalizeBoolString(d.Old) - d.New = normalizeBoolString(d.New) - } - - if s.Computed && !d.NewRemoved && d.New == "" { - // Computed attribute without a new value set - d.NewComputed = true - } - - if s.ForceNew { - // ForceNew, mark that this field is requiring new under the - // following conditions, explained below: - // - // * Old != New - There is a change in value. This field - // is therefore causing a new resource. - // - // * NewComputed - This field is being computed, hence a - // potential change in value, mark as causing a new resource. - d.RequiresNew = d.Old != d.New || d.NewComputed - } - - if d.NewRemoved { - return d - } - - if s.Computed { - // FIXME: This is where the customized bool from getChange finally - // comes into play. It allows the previously incorrect behavior - // of an empty string being used as "unset" when the value is - // computed. This should be removed once we can properly - // represent an unset/nil value from the configuration. - if !customized { - if d.Old != "" && d.New == "" { - // This is a computed value with an old value set already, - // just let it go. - return nil - } - } - - if d.New == "" && !d.NewComputed { - // Computed attribute without a new value set - d.NewComputed = true - } - } - - if s.Sensitive { - // Set the Sensitive flag so output is hidden in the UI - d.Sensitive = true - } - - return d -} - -// InternalMap is used to aid in the transition to the new schema types and -// protocol. The name is not meant to convey any usefulness, as this is not to -// be used directly by any providers. -type InternalMap = schemaMap - -// schemaMap is a wrapper that adds nice functions on top of schemas. -type schemaMap map[string]*Schema - -func (m schemaMap) panicOnError() bool { - if os.Getenv(PanicOnErr) != "" { - return true - } - return false -} - -// Data returns a ResourceData for the given schema, state, and diff. -// -// The diff is optional. -func (m schemaMap) Data( - s *terraform.InstanceState, - d *terraform.InstanceDiff) (*ResourceData, error) { - return &ResourceData{ - schema: m, - state: s, - diff: d, - panicOnError: m.panicOnError(), - }, nil -} - -// DeepCopy returns a copy of this schemaMap. The copy can be safely modified -// without affecting the original. -func (m *schemaMap) DeepCopy() schemaMap { - copy, err := copystructure.Config{Lock: true}.Copy(m) - if err != nil { - panic(err) - } - return *copy.(*schemaMap) -} - -// Diff returns the diff for a resource given the schema map, -// state, and configuration. -func (m schemaMap) Diff( - s *terraform.InstanceState, - c *terraform.ResourceConfig, - customizeDiff CustomizeDiffFunc, - meta interface{}, - handleRequiresNew bool) (*terraform.InstanceDiff, error) { - result := new(terraform.InstanceDiff) - result.Attributes = make(map[string]*terraform.ResourceAttrDiff) - - // Make sure to mark if the resource is tainted - if s != nil { - result.DestroyTainted = s.Tainted - } - - d := &ResourceData{ - schema: m, - state: s, - config: c, - panicOnError: m.panicOnError(), - } - - for k, schema := range m { - err := m.diff(k, schema, result, d, false) - if err != nil { - return nil, err - } - } - - // Remove any nil diffs just to keep things clean - for k, v := range result.Attributes { - if v == nil { - delete(result.Attributes, k) - } - } - - // If this is a non-destroy diff, call any custom diff logic that has been - // defined. - if !result.DestroyTainted && customizeDiff != nil { - mc := m.DeepCopy() - rd := newResourceDiff(mc, c, s, result) - if err := customizeDiff(rd, meta); err != nil { - return nil, err - } - for _, k := range rd.UpdatedKeys() { - err := m.diff(k, mc[k], result, rd, false) - if err != nil { - return nil, err - } - } - } - - if handleRequiresNew { - // If the diff requires a new resource, then we recompute the diff - // so we have the complete new resource diff, and preserve the - // RequiresNew fields where necessary so the user knows exactly what - // caused that. - if result.RequiresNew() { - // Create the new diff - result2 := new(terraform.InstanceDiff) - result2.Attributes = make(map[string]*terraform.ResourceAttrDiff) - - // Preserve the DestroyTainted flag - result2.DestroyTainted = result.DestroyTainted - - // Reset the data to not contain state. We have to call init() - // again in order to reset the FieldReaders. - d.state = nil - d.init() - - // Perform the diff again - for k, schema := range m { - err := m.diff(k, schema, result2, d, false) - if err != nil { - return nil, err - } - } - - // Re-run customization - if !result2.DestroyTainted && customizeDiff != nil { - mc := m.DeepCopy() - rd := newResourceDiff(mc, c, d.state, result2) - if err := customizeDiff(rd, meta); err != nil { - return nil, err - } - for _, k := range rd.UpdatedKeys() { - err := m.diff(k, mc[k], result2, rd, false) - if err != nil { - return nil, err - } - } - } - - // Force all the fields to not force a new since we know what we - // want to force new. - for k, attr := range result2.Attributes { - if attr == nil { - continue - } - - if attr.RequiresNew { - attr.RequiresNew = false - } - - if s != nil { - attr.Old = s.Attributes[k] - } - } - - // Now copy in all the requires new diffs... - for k, attr := range result.Attributes { - if attr == nil { - continue - } - - newAttr, ok := result2.Attributes[k] - if !ok { - newAttr = attr - } - - if attr.RequiresNew { - newAttr.RequiresNew = true - } - - result2.Attributes[k] = newAttr - } - - // And set the diff! - result = result2 - } - - } - - // Go through and detect all of the ComputedWhens now that we've - // finished the diff. - // TODO - - if result.Empty() { - // If we don't have any diff elements, just return nil - return nil, nil - } - - return result, nil -} - -// Input implements the terraform.ResourceProvider method by asking -// for input for required configuration keys that don't have a value. -func (m schemaMap) Input( - input terraform.UIInput, - c *terraform.ResourceConfig) (*terraform.ResourceConfig, error) { - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) - - for _, k := range keys { - v := m[k] - - // Skip things that don't require config, if that is even valid - // for a provider schema. - // Required XOR Optional must always be true to validate, so we only - // need to check one. - if v.Optional { - continue - } - - // Deprecated fields should never prompt - if v.Deprecated != "" { - continue - } - - // Skip things that have a value of some sort already - if _, ok := c.Raw[k]; ok { - continue - } - - // Skip if it has a default value - defaultValue, err := v.DefaultValue() - if err != nil { - return nil, fmt.Errorf("%s: error loading default: %s", k, err) - } - if defaultValue != nil { - continue - } - - var value interface{} - switch v.Type { - case TypeBool, TypeInt, TypeFloat, TypeSet, TypeList: - continue - case TypeString: - value, err = m.inputString(input, k, v) - default: - panic(fmt.Sprintf("Unknown type for input: %#v", v.Type)) - } - - if err != nil { - return nil, fmt.Errorf( - "%s: %s", k, err) - } - - c.Config[k] = value - } - - return c, nil -} - -// Validate validates the configuration against this schema mapping. -func (m schemaMap) Validate(c *terraform.ResourceConfig) ([]string, []error) { - return m.validateObject("", m, c) -} - -// InternalValidate validates the format of this schema. This should be called -// from a unit test (and not in user-path code) to verify that a schema -// is properly built. -func (m schemaMap) InternalValidate(topSchemaMap schemaMap) error { - return m.internalValidate(topSchemaMap, false) -} - -func (m schemaMap) internalValidate(topSchemaMap schemaMap, attrsOnly bool) error { - if topSchemaMap == nil { - topSchemaMap = m - } - for k, v := range m { - if v.Type == TypeInvalid { - return fmt.Errorf("%s: Type must be specified", k) - } - - if v.Optional && v.Required { - return fmt.Errorf("%s: Optional or Required must be set, not both", k) - } - - if v.Required && v.Computed { - return fmt.Errorf("%s: Cannot be both Required and Computed", k) - } - - if !v.Required && !v.Optional && !v.Computed { - return fmt.Errorf("%s: One of optional, required, or computed must be set", k) - } - - computedOnly := v.Computed && !v.Optional - - switch v.ConfigMode { - case SchemaConfigModeBlock: - if _, ok := v.Elem.(*Resource); !ok { - return fmt.Errorf("%s: ConfigMode of block is allowed only when Elem is *schema.Resource", k) - } - if attrsOnly { - return fmt.Errorf("%s: ConfigMode of block cannot be used in child of schema with ConfigMode of attribute", k) - } - if computedOnly { - return fmt.Errorf("%s: ConfigMode of block cannot be used for computed schema", k) - } - case SchemaConfigModeAttr: - // anything goes - case SchemaConfigModeAuto: - // Since "Auto" for Elem: *Resource would create a nested block, - // and that's impossible inside an attribute, we require it to be - // explicitly overridden as mode "Attr" for clarity. - if _, ok := v.Elem.(*Resource); ok { - if attrsOnly { - return fmt.Errorf("%s: in *schema.Resource with ConfigMode of attribute, so must also have ConfigMode of attribute", k) - } - } - default: - return fmt.Errorf("%s: invalid ConfigMode value", k) - } - - if v.Computed && v.Default != nil { - return fmt.Errorf("%s: Default must be nil if computed", k) - } - - if v.Required && v.Default != nil { - return fmt.Errorf("%s: Default cannot be set with Required", k) - } - - if len(v.ComputedWhen) > 0 && !v.Computed { - return fmt.Errorf("%s: ComputedWhen can only be set with Computed", k) - } - - if len(v.ConflictsWith) > 0 && v.Required { - return fmt.Errorf("%s: ConflictsWith cannot be set with Required", k) - } - - if len(v.ExactlyOneOf) > 0 && v.Required { - return fmt.Errorf("%s: ExactlyOneOf cannot be set with Required", k) - } - - if len(v.AtLeastOneOf) > 0 && v.Required { - return fmt.Errorf("%s: AtLeastOneOf cannot be set with Required", k) - } - - if len(v.ConflictsWith) > 0 { - err := checkKeysAgainstSchemaFlags(k, v.ConflictsWith, topSchemaMap) - if err != nil { - return fmt.Errorf("ConflictsWith: %+v", err) - } - } - - if len(v.ExactlyOneOf) > 0 { - err := checkKeysAgainstSchemaFlags(k, v.ExactlyOneOf, topSchemaMap) - if err != nil { - return fmt.Errorf("ExactlyOneOf: %+v", err) - } - } - - if len(v.AtLeastOneOf) > 0 { - err := checkKeysAgainstSchemaFlags(k, v.AtLeastOneOf, topSchemaMap) - if err != nil { - return fmt.Errorf("AtLeastOneOf: %+v", err) - } - } - - if v.Type == TypeList || v.Type == TypeSet { - if v.Elem == nil { - return fmt.Errorf("%s: Elem must be set for lists", k) - } - - if v.Default != nil { - return fmt.Errorf("%s: Default is not valid for lists or sets", k) - } - - if v.Type != TypeSet && v.Set != nil { - return fmt.Errorf("%s: Set can only be set for TypeSet", k) - } - - switch t := v.Elem.(type) { - case *Resource: - attrsOnly := attrsOnly || v.ConfigMode == SchemaConfigModeAttr - - if err := schemaMap(t.Schema).internalValidate(topSchemaMap, attrsOnly); err != nil { - return err - } - case *Schema: - bad := t.Computed || t.Optional || t.Required - if bad { - return fmt.Errorf( - "%s: Elem must have only Type set", k) - } - } - } else { - if v.MaxItems > 0 || v.MinItems > 0 { - return fmt.Errorf("%s: MaxItems and MinItems are only supported on lists or sets", k) - } - } - - // 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: - return fmt.Errorf("%s: ValidateFunc is not yet supported on lists or sets.", k) - } - } - - if v.Deprecated == "" && v.Removed == "" { - if !isValidFieldName(k) { - return fmt.Errorf("%s: Field name may only contain lowercase alphanumeric characters & underscores.", k) - } - } - } - - return nil -} - -func checkKeysAgainstSchemaFlags(k string, keys []string, topSchemaMap schemaMap) error { - for _, key := range keys { - parts := strings.Split(key, ".") - sm := topSchemaMap - var target *Schema - for _, part := range parts { - // Skip index fields - if _, err := strconv.Atoi(part); err == nil { - continue - } - - var ok bool - if target, ok = sm[part]; !ok { - return fmt.Errorf("%s references unknown attribute (%s) at part (%s)", k, key, part) - } - - if subResource, ok := target.Elem.(*Resource); ok { - sm = schemaMap(subResource.Schema) - } - } - if target == nil { - return fmt.Errorf("%s cannot find target attribute (%s), sm: %#v", k, key, sm) - } - if target.Required { - return fmt.Errorf("%s cannot contain Required attribute (%s)", k, key) - } - - if len(target.ComputedWhen) > 0 { - return fmt.Errorf("%s cannot contain Computed(When) attribute (%s)", k, key) - } - } - return nil -} - -func isValidFieldName(name string) bool { - re := regexp.MustCompile("^[a-z0-9_]+$") - return re.MatchString(name) -} - -// resourceDiffer is an interface that is used by the private diff functions. -// This helps facilitate diff logic for both ResourceData and ResoureDiff with -// minimal divergence in code. -type resourceDiffer interface { - diffChange(string) (interface{}, interface{}, bool, bool, bool) - Get(string) interface{} - GetChange(string) (interface{}, interface{}) - GetOk(string) (interface{}, bool) - HasChange(string) bool - Id() string -} - -func (m schemaMap) diff( - k string, - schema *Schema, - diff *terraform.InstanceDiff, - d resourceDiffer, - all bool) error { - - unsupressedDiff := new(terraform.InstanceDiff) - unsupressedDiff.Attributes = make(map[string]*terraform.ResourceAttrDiff) - - var err error - switch schema.Type { - case TypeBool, TypeInt, TypeFloat, TypeString: - err = m.diffString(k, schema, unsupressedDiff, d, all) - case TypeList: - err = m.diffList(k, schema, unsupressedDiff, d, all) - case TypeMap: - err = m.diffMap(k, schema, unsupressedDiff, d, all) - case TypeSet: - err = m.diffSet(k, schema, unsupressedDiff, d, all) - default: - err = fmt.Errorf("%s: unknown type %#v", k, schema.Type) - } - - for attrK, attrV := range unsupressedDiff.Attributes { - switch rd := d.(type) { - case *ResourceData: - if schema.DiffSuppressFunc != nil && attrV != nil && - schema.DiffSuppressFunc(attrK, attrV.Old, attrV.New, rd) { - // If this attr diff is suppressed, we may still need it in the - // overall diff if it's contained within a set. Rather than - // dropping the diff, make it a NOOP. - if !all { - continue - } - - attrV = &terraform.ResourceAttrDiff{ - Old: attrV.Old, - New: attrV.Old, - } - } - } - diff.Attributes[attrK] = attrV - } - - return err -} - -func (m schemaMap) diffList( - k string, - schema *Schema, - diff *terraform.InstanceDiff, - d resourceDiffer, - all bool) error { - o, n, _, computedList, customized := d.diffChange(k) - if computedList { - n = nil - } - nSet := n != nil - - // If we have an old value and no new value is set or will be - // computed once all variables can be interpolated and we're - // computed, then nothing has changed. - if o != nil && n == nil && !computedList && schema.Computed { - return nil - } - - if o == nil { - o = []interface{}{} - } - if n == nil { - n = []interface{}{} - } - if s, ok := o.(*Set); ok { - o = s.List() - } - if s, ok := n.(*Set); ok { - n = s.List() - } - os := o.([]interface{}) - vs := n.([]interface{}) - - // If the new value was set, and the two are equal, then we're done. - // We have to do this check here because sets might be NOT - // reflect.DeepEqual so we need to wait until we get the []interface{} - if !all && nSet && reflect.DeepEqual(os, vs) { - return nil - } - - // Get the counts - oldLen := len(os) - newLen := len(vs) - oldStr := strconv.FormatInt(int64(oldLen), 10) - - // If the whole list is computed, then say that the # is computed - if computedList { - diff.Attributes[k+".#"] = &terraform.ResourceAttrDiff{ - Old: oldStr, - NewComputed: true, - RequiresNew: schema.ForceNew, - } - return nil - } - - // If the counts are not the same, then record that diff - changed := oldLen != newLen - computed := oldLen == 0 && newLen == 0 && schema.Computed - if changed || computed || all { - countSchema := &Schema{ - Type: TypeInt, - Computed: schema.Computed, - ForceNew: schema.ForceNew, - } - - newStr := "" - if !computed { - newStr = strconv.FormatInt(int64(newLen), 10) - } else { - oldStr = "" - } - - diff.Attributes[k+".#"] = countSchema.finalizeDiff( - &terraform.ResourceAttrDiff{ - Old: oldStr, - New: newStr, - }, - customized, - ) - } - - // Figure out the maximum - maxLen := oldLen - if newLen > maxLen { - maxLen = newLen - } - - switch t := schema.Elem.(type) { - case *Resource: - // This is a complex resource - for i := 0; i < maxLen; i++ { - for k2, schema := range t.Schema { - subK := fmt.Sprintf("%s.%d.%s", k, i, k2) - err := m.diff(subK, schema, diff, d, all) - if err != nil { - return err - } - } - } - case *Schema: - // Copy the schema so that we can set Computed/ForceNew from - // the parent schema (the TypeList). - t2 := *t - t2.ForceNew = schema.ForceNew - - // This is just a primitive element, so go through each and - // just diff each. - for i := 0; i < maxLen; i++ { - subK := fmt.Sprintf("%s.%d", k, i) - err := m.diff(subK, &t2, diff, d, all) - if err != nil { - return err - } - } - default: - return fmt.Errorf("%s: unknown element type (internal)", k) - } - - return nil -} - -func (m schemaMap) diffMap( - k string, - schema *Schema, - diff *terraform.InstanceDiff, - d resourceDiffer, - all bool) error { - prefix := k + "." - - // First get all the values from the state - var stateMap, configMap map[string]string - o, n, _, nComputed, customized := d.diffChange(k) - if err := mapstructure.WeakDecode(o, &stateMap); err != nil { - return fmt.Errorf("%s: %s", k, err) - } - if err := mapstructure.WeakDecode(n, &configMap); err != nil { - return fmt.Errorf("%s: %s", k, err) - } - - // Keep track of whether the state _exists_ at all prior to clearing it - stateExists := o != nil - - // Delete any count values, since we don't use those - delete(configMap, "%") - delete(stateMap, "%") - - // Check if the number of elements has changed. - oldLen, newLen := len(stateMap), len(configMap) - changed := oldLen != newLen - if oldLen != 0 && newLen == 0 && schema.Computed { - changed = false - } - - // It is computed if we have no old value, no new value, the schema - // says it is computed, and it didn't exist in the state before. The - // last point means: if it existed in the state, even empty, then it - // has already been computed. - computed := oldLen == 0 && newLen == 0 && schema.Computed && !stateExists - - // If the count has changed or we're computed, then add a diff for the - // count. "nComputed" means that the new value _contains_ a value that - // is computed. We don't do granular diffs for this yet, so we mark the - // whole map as computed. - if changed || computed || nComputed { - countSchema := &Schema{ - Type: TypeInt, - Computed: schema.Computed || nComputed, - ForceNew: schema.ForceNew, - } - - oldStr := strconv.FormatInt(int64(oldLen), 10) - newStr := "" - if !computed && !nComputed { - newStr = strconv.FormatInt(int64(newLen), 10) - } else { - oldStr = "" - } - - diff.Attributes[k+".%"] = countSchema.finalizeDiff( - &terraform.ResourceAttrDiff{ - Old: oldStr, - New: newStr, - }, - customized, - ) - } - - // If the new map is nil and we're computed, then ignore it. - if n == nil && schema.Computed { - return nil - } - - // Now we compare, preferring values from the config map - for k, v := range configMap { - old, ok := stateMap[k] - delete(stateMap, k) - - if old == v && ok && !all { - continue - } - - diff.Attributes[prefix+k] = schema.finalizeDiff( - &terraform.ResourceAttrDiff{ - Old: old, - New: v, - }, - customized, - ) - } - for k, v := range stateMap { - diff.Attributes[prefix+k] = schema.finalizeDiff( - &terraform.ResourceAttrDiff{ - Old: v, - NewRemoved: true, - }, - customized, - ) - } - - return nil -} - -func (m schemaMap) diffSet( - k string, - schema *Schema, - diff *terraform.InstanceDiff, - d resourceDiffer, - all bool) error { - - o, n, _, computedSet, customized := d.diffChange(k) - if computedSet { - n = nil - } - nSet := n != nil - - // If we have an old value and no new value is set or will be - // computed once all variables can be interpolated and we're - // computed, then nothing has changed. - if o != nil && n == nil && !computedSet && schema.Computed { - return nil - } - - if o == nil { - o = schema.ZeroValue().(*Set) - } - if n == nil { - n = schema.ZeroValue().(*Set) - } - os := o.(*Set) - ns := n.(*Set) - - // If the new value was set, compare the listCode's to determine if - // the two are equal. Comparing listCode's instead of the actual values - // is needed because there could be computed values in the set which - // would result in false positives while comparing. - if !all && nSet && reflect.DeepEqual(os.listCode(), ns.listCode()) { - return nil - } - - // Get the counts - oldLen := os.Len() - newLen := ns.Len() - oldStr := strconv.Itoa(oldLen) - newStr := strconv.Itoa(newLen) - - // Build a schema for our count - countSchema := &Schema{ - Type: TypeInt, - Computed: schema.Computed, - ForceNew: schema.ForceNew, - } - - // If the set computed then say that the # is computed - if computedSet || schema.Computed && !nSet { - // If # already exists, equals 0 and no new set is supplied, there - // is nothing to record in the diff - count, ok := d.GetOk(k + ".#") - if ok && count.(int) == 0 && !nSet && !computedSet { - return nil - } - - // Set the count but make sure that if # does not exist, we don't - // use the zeroed value - countStr := strconv.Itoa(count.(int)) - if !ok { - countStr = "" - } - - diff.Attributes[k+".#"] = countSchema.finalizeDiff( - &terraform.ResourceAttrDiff{ - Old: countStr, - NewComputed: true, - }, - customized, - ) - return nil - } - - // If the counts are not the same, then record that diff - changed := oldLen != newLen - if changed || all { - diff.Attributes[k+".#"] = countSchema.finalizeDiff( - &terraform.ResourceAttrDiff{ - Old: oldStr, - New: newStr, - }, - customized, - ) - } - - // Build the list of codes that will make up our set. This is the - // removed codes as well as all the codes in the new codes. - codes := make([][]string, 2) - codes[0] = os.Difference(ns).listCode() - codes[1] = ns.listCode() - for _, list := range codes { - for _, code := range list { - switch t := schema.Elem.(type) { - case *Resource: - // This is a complex resource - for k2, schema := range t.Schema { - subK := fmt.Sprintf("%s.%s.%s", k, code, k2) - err := m.diff(subK, schema, diff, d, true) - if err != nil { - return err - } - } - case *Schema: - // Copy the schema so that we can set Computed/ForceNew from - // the parent schema (the TypeSet). - t2 := *t - t2.ForceNew = schema.ForceNew - - // This is just a primitive element, so go through each and - // just diff each. - subK := fmt.Sprintf("%s.%s", k, code) - err := m.diff(subK, &t2, diff, d, true) - if err != nil { - return err - } - default: - return fmt.Errorf("%s: unknown element type (internal)", k) - } - } - } - - return nil -} - -func (m schemaMap) diffString( - k string, - schema *Schema, - diff *terraform.InstanceDiff, - d resourceDiffer, - all bool) error { - var originalN interface{} - var os, ns string - o, n, _, computed, customized := d.diffChange(k) - if schema.StateFunc != nil && n != nil { - originalN = n - n = schema.StateFunc(n) - } - nraw := n - if nraw == nil && o != nil { - nraw = schema.Type.Zero() - } - if err := mapstructure.WeakDecode(o, &os); err != nil { - return fmt.Errorf("%s: %s", k, err) - } - if err := mapstructure.WeakDecode(nraw, &ns); err != nil { - return fmt.Errorf("%s: %s", k, err) - } - - if os == ns && !all && !computed { - // They're the same value. If there old value is not blank or we - // have an ID, then return right away since we're already setup. - if os != "" || d.Id() != "" { - return nil - } - - // Otherwise, only continue if we're computed - if !schema.Computed { - return nil - } - } - - removed := false - if o != nil && n == nil && !computed { - removed = true - } - if removed && schema.Computed { - return nil - } - - diff.Attributes[k] = schema.finalizeDiff( - &terraform.ResourceAttrDiff{ - Old: os, - New: ns, - NewExtra: originalN, - NewRemoved: removed, - NewComputed: computed, - }, - customized, - ) - - return nil -} - -func (m schemaMap) inputString( - input terraform.UIInput, - k string, - schema *Schema) (interface{}, error) { - result, err := input.Input(context.Background(), &terraform.InputOpts{ - Id: k, - Query: k, - Description: schema.Description, - Default: schema.InputDefault, - }) - - return result, err -} - -func (m schemaMap) validate( - k string, - schema *Schema, - c *terraform.ResourceConfig) ([]string, []error) { - raw, ok := c.Get(k) - if !ok && schema.DefaultFunc != nil { - // We have a dynamic default. Check if we have a value. - var err error - raw, err = schema.DefaultFunc() - if err != nil { - return nil, []error{fmt.Errorf( - "%q, error loading default: %s", k, err)} - } - - // We're okay as long as we had a value set - ok = raw != nil - } - - err := validateExactlyOneAttribute(k, schema, c) - if err != nil { - return nil, []error{err} - } - - err = validateAtLeastOneAttribute(k, schema, c) - if err != nil { - return nil, []error{err} - } - - if !ok { - if schema.Required { - return nil, []error{fmt.Errorf( - "%q: required field is not set", k)} - } - return nil, nil - } - - if !schema.Required && !schema.Optional { - // This is a computed-only field - return nil, []error{fmt.Errorf( - "%q: this field cannot be set", k)} - } - - // If the value is unknown then we can't validate it yet. - // In particular, this avoids spurious type errors where downstream - // validation code sees UnknownVariableValue as being just a string. - // The SDK has to allow the unknown value through initially, so that - // Required fields set via an interpolated value are accepted. - if !isWhollyKnown(raw) { - if schema.Deprecated != "" { - return []string{fmt.Sprintf("%q: [DEPRECATED] %s", k, schema.Deprecated)}, nil - } - return nil, nil - } - - err = validateConflictingAttributes(k, schema, c) - if err != nil { - return nil, []error{err} - } - - return m.validateType(k, raw, schema, c) -} - -// isWhollyKnown returns false if the argument contains an UnknownVariableValue -func isWhollyKnown(raw interface{}) bool { - switch raw := raw.(type) { - case string: - if raw == hcl2shim.UnknownVariableValue { - return false - } - case []interface{}: - for _, v := range raw { - if !isWhollyKnown(v) { - return false - } - } - case map[string]interface{}: - for _, v := range raw { - if !isWhollyKnown(v) { - return false - } - } - } - return true -} -func validateConflictingAttributes( - k string, - schema *Schema, - c *terraform.ResourceConfig) error { - - if len(schema.ConflictsWith) == 0 { - return nil - } - - for _, conflictingKey := range schema.ConflictsWith { - if raw, ok := c.Get(conflictingKey); ok { - if raw == hcl2shim.UnknownVariableValue { - // An unknown value might become unset (null) once known, so - // we must defer validation until it's known. - continue - } - return fmt.Errorf( - "%q: conflicts with %s", k, conflictingKey) - } - } - - return nil -} - -func removeDuplicates(elements []string) []string { - encountered := make(map[string]struct{}, 0) - result := []string{} - - for v := range elements { - if _, ok := encountered[elements[v]]; !ok { - encountered[elements[v]] = struct{}{} - result = append(result, elements[v]) - } - } - - return result -} - -func validateExactlyOneAttribute( - k string, - schema *Schema, - c *terraform.ResourceConfig) error { - - if len(schema.ExactlyOneOf) == 0 { - return nil - } - - allKeys := removeDuplicates(append(schema.ExactlyOneOf, k)) - sort.Strings(allKeys) - specified := make([]string, 0) - unknownVariableValueCount := 0 - for _, exactlyOneOfKey := range allKeys { - if c.IsComputed(exactlyOneOfKey) { - unknownVariableValueCount++ - continue - } - - _, ok := c.Get(exactlyOneOfKey) - if ok { - specified = append(specified, exactlyOneOfKey) - } - } - - if len(specified) == 0 && unknownVariableValueCount == 0 { - return fmt.Errorf("%q: one of `%s` must be specified", k, strings.Join(allKeys, ",")) - } - - if len(specified) > 1 { - return fmt.Errorf("%q: only one of `%s` can be specified, but `%s` were specified.", k, strings.Join(allKeys, ","), strings.Join(specified, ",")) - } - - return nil -} - -func validateAtLeastOneAttribute( - k string, - schema *Schema, - c *terraform.ResourceConfig) error { - - if len(schema.AtLeastOneOf) == 0 { - return nil - } - - allKeys := removeDuplicates(append(schema.AtLeastOneOf, k)) - sort.Strings(allKeys) - - for _, atLeastOneOfKey := range allKeys { - if _, ok := c.Get(atLeastOneOfKey); ok { - // We can ignore hcl2shim.UnknownVariable by assuming it's been set and additional validation elsewhere - // will uncover this if it is in fact null. - return nil - } - } - - return fmt.Errorf("%q: one of `%s` must be specified", k, strings.Join(allKeys, ",")) -} - -func (m schemaMap) validateList( - k string, - raw interface{}, - schema *Schema, - c *terraform.ResourceConfig) ([]string, []error) { - // first check if the list is wholly unknown - if s, ok := raw.(string); ok { - if s == hcl2shim.UnknownVariableValue { - return nil, nil - } - } - - // schemaMap can't validate nil - if raw == nil { - return nil, nil - } - - // We use reflection to verify the slice because you can't - // case to []interface{} unless the slice is exactly that type. - rawV := reflect.ValueOf(raw) - - // If we support promotion and the raw value isn't a slice, wrap - // it in []interface{} and check again. - if schema.PromoteSingle && rawV.Kind() != reflect.Slice { - raw = []interface{}{raw} - rawV = reflect.ValueOf(raw) - } - - if rawV.Kind() != reflect.Slice { - return nil, []error{fmt.Errorf( - "%s: should be a list", k)} - } - - // We can't validate list length if this came from a dynamic block. - // Since there's no way to determine if something was from a dynamic block - // at this point, we're going to skip validation in the new protocol if - // there are any unknowns. Validate will eventually be called again once - // all values are known. - if isProto5() && !isWhollyKnown(raw) { - return nil, nil - } - - // Validate length - if schema.MaxItems > 0 && rawV.Len() > schema.MaxItems { - return nil, []error{fmt.Errorf( - "%s: attribute supports %d item maximum, config has %d declared", k, schema.MaxItems, rawV.Len())} - } - - if schema.MinItems > 0 && rawV.Len() < schema.MinItems { - return nil, []error{fmt.Errorf( - "%s: attribute supports %d item as a minimum, config has %d declared", k, schema.MinItems, rawV.Len())} - } - - // Now build the []interface{} - raws := make([]interface{}, rawV.Len()) - for i := range raws { - raws[i] = rawV.Index(i).Interface() - } - - var ws []string - var es []error - for i, raw := range raws { - key := fmt.Sprintf("%s.%d", k, i) - - // Reify the key value from the ResourceConfig. - // If the list was computed we have all raw values, but some of these - // may be known in the config, and aren't individually marked as Computed. - if r, ok := c.Get(key); ok { - raw = r - } - - var ws2 []string - var es2 []error - switch t := schema.Elem.(type) { - case *Resource: - // This is a sub-resource - ws2, es2 = m.validateObject(key, t.Schema, c) - case *Schema: - ws2, es2 = m.validateType(key, raw, t, c) - } - - if len(ws2) > 0 { - ws = append(ws, ws2...) - } - if len(es2) > 0 { - es = append(es, es2...) - } - } - - return ws, es -} - -func (m schemaMap) validateMap( - k string, - raw interface{}, - schema *Schema, - c *terraform.ResourceConfig) ([]string, []error) { - // first check if the list is wholly unknown - if s, ok := raw.(string); ok { - if s == hcl2shim.UnknownVariableValue { - return nil, nil - } - } - - // schemaMap can't validate nil - if raw == nil { - return nil, nil - } - // We use reflection to verify the slice because you can't - // case to []interface{} unless the slice is exactly that type. - rawV := reflect.ValueOf(raw) - switch rawV.Kind() { - case reflect.String: - // If raw and reified are equal, this is a string and should - // be rejected. - reified, reifiedOk := c.Get(k) - if reifiedOk && raw == reified && !c.IsComputed(k) { - return nil, []error{fmt.Errorf("%s: should be a map", k)} - } - // Otherwise it's likely raw is an interpolation. - return nil, nil - case reflect.Map: - case reflect.Slice: - default: - return nil, []error{fmt.Errorf("%s: should be a map", k)} - } - - // If it is not a slice, validate directly - if rawV.Kind() != reflect.Slice { - mapIface := rawV.Interface() - if _, errs := validateMapValues(k, mapIface.(map[string]interface{}), schema); len(errs) > 0 { - return nil, errs - } - if schema.ValidateFunc != nil { - return schema.ValidateFunc(mapIface, k) - } - return nil, nil - } - - // It is a slice, verify that all the elements are maps - raws := make([]interface{}, rawV.Len()) - for i := range raws { - raws[i] = rawV.Index(i).Interface() - } - - for _, raw := range raws { - v := reflect.ValueOf(raw) - if v.Kind() != reflect.Map { - return nil, []error{fmt.Errorf( - "%s: should be a map", k)} - } - mapIface := v.Interface() - if _, errs := validateMapValues(k, mapIface.(map[string]interface{}), schema); len(errs) > 0 { - return nil, errs - } - } - - if schema.ValidateFunc != nil { - validatableMap := make(map[string]interface{}) - for _, raw := range raws { - for k, v := range raw.(map[string]interface{}) { - validatableMap[k] = v - } - } - - return schema.ValidateFunc(validatableMap, k) - } - - return nil, nil -} - -func validateMapValues(k string, m map[string]interface{}, schema *Schema) ([]string, []error) { - for key, raw := range m { - valueType, err := getValueType(k, schema) - if err != nil { - return nil, []error{err} - } - - switch valueType { - case TypeBool: - var n bool - if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)} - } - case TypeInt: - var n int - if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)} - } - case TypeFloat: - var n float64 - if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)} - } - case TypeString: - var n string - if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)} - } - default: - panic(fmt.Sprintf("Unknown validation type: %#v", schema.Type)) - } - } - return nil, nil -} - -func getValueType(k string, schema *Schema) (ValueType, error) { - if schema.Elem == nil { - return TypeString, nil - } - if vt, ok := schema.Elem.(ValueType); ok { - return vt, nil - } - - // If a Schema is provided to a Map, we use the Type of that schema - // as the type for each element in the Map. - if s, ok := schema.Elem.(*Schema); ok { - return s.Type, nil - } - - if _, ok := schema.Elem.(*Resource); ok { - // TODO: We don't actually support this (yet) - // but silently pass the validation, until we decide - // how to handle nested structures in maps - return TypeString, nil - } - return 0, fmt.Errorf("%s: unexpected map value type: %#v", k, schema.Elem) -} - -func (m schemaMap) validateObject( - k string, - schema map[string]*Schema, - c *terraform.ResourceConfig) ([]string, []error) { - raw, _ := c.Get(k) - - // schemaMap can't validate nil - if raw == nil { - return nil, nil - } - - if _, ok := raw.(map[string]interface{}); !ok && !c.IsComputed(k) { - return nil, []error{fmt.Errorf( - "%s: expected object, got %s", - k, reflect.ValueOf(raw).Kind())} - } - - var ws []string - var es []error - for subK, s := range schema { - key := subK - if k != "" { - key = fmt.Sprintf("%s.%s", k, subK) - } - - ws2, es2 := m.validate(key, s, c) - if len(ws2) > 0 { - ws = append(ws, ws2...) - } - if len(es2) > 0 { - es = append(es, es2...) - } - } - - // Detect any extra/unknown keys and report those as errors. - if m, ok := raw.(map[string]interface{}); ok { - for subk := range m { - if _, ok := schema[subk]; !ok { - if subk == TimeoutsConfigKey { - continue - } - es = append(es, fmt.Errorf( - "%s: invalid or unknown key: %s", k, subk)) - } - } - } - - return ws, es -} - -func (m schemaMap) validatePrimitive( - k string, - raw interface{}, - schema *Schema, - c *terraform.ResourceConfig) ([]string, []error) { - - // a nil value shouldn't happen in the old protocol, and in the new - // protocol the types have already been validated. Either way, we can't - // reflect on nil, so don't panic. - if raw == nil { - return nil, nil - } - - // Catch if the user gave a complex type where a primitive was - // expected, so we can return a friendly error message that - // doesn't contain Go type system terminology. - switch reflect.ValueOf(raw).Type().Kind() { - case reflect.Slice: - return nil, []error{ - fmt.Errorf("%s must be a single value, not a list", k), - } - case reflect.Map: - return nil, []error{ - fmt.Errorf("%s must be a single value, not a map", k), - } - default: // ok - } - - if c.IsComputed(k) { - // If the key is being computed, then it is not an error as - // long as it's not a slice or map. - return nil, nil - } - - var decoded interface{} - switch schema.Type { - case TypeBool: - // Verify that we can parse this as the correct type - var n bool - if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{fmt.Errorf("%s: %s", k, err)} - } - decoded = n - case TypeInt: - switch { - case isProto5(): - // We need to verify the type precisely, because WeakDecode will - // decode a float as an integer. - - // the config shims only use int for integral number values - if v, ok := raw.(int); ok { - decoded = v - } else { - return nil, []error{fmt.Errorf("%s: must be a whole number, got %v", k, raw)} - } - default: - // Verify that we can parse this as an int - var n int - if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{fmt.Errorf("%s: %s", k, err)} - } - decoded = n - } - case TypeFloat: - // Verify that we can parse this as an int - var n float64 - if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{fmt.Errorf("%s: %s", k, err)} - } - decoded = n - case TypeString: - // Verify that we can parse this as a string - var n string - if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{fmt.Errorf("%s: %s", k, err)} - } - decoded = n - default: - panic(fmt.Sprintf("Unknown validation type: %#v", schema.Type)) - } - - if schema.ValidateFunc != nil { - return schema.ValidateFunc(decoded, k) - } - - return nil, nil -} - -func (m schemaMap) validateType( - k string, - raw interface{}, - schema *Schema, - c *terraform.ResourceConfig) ([]string, []error) { - var ws []string - var es []error - switch schema.Type { - case TypeSet, TypeList: - ws, es = m.validateList(k, raw, schema, c) - case TypeMap: - ws, es = m.validateMap(k, raw, schema, c) - default: - ws, es = m.validatePrimitive(k, raw, schema, c) - } - - if schema.Deprecated != "" { - ws = append(ws, fmt.Sprintf( - "%q: [DEPRECATED] %s", k, schema.Deprecated)) - } - - if schema.Removed != "" { - es = append(es, fmt.Errorf( - "%q: [REMOVED] %s", k, schema.Removed)) - } - - return ws, es -} - -// Zero returns the zero value for a type. -func (t ValueType) Zero() interface{} { - switch t { - case TypeInvalid: - return nil - case TypeBool: - return false - case TypeInt: - return 0 - case TypeFloat: - return 0.0 - case TypeString: - return "" - case TypeList: - return []interface{}{} - case TypeMap: - return map[string]interface{}{} - case TypeSet: - return new(Set) - case typeObject: - return map[string]interface{}{} - default: - panic(fmt.Sprintf("unknown type %s", t)) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/set.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/set.go deleted file mode 100644 index daa431ddb1c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/set.go +++ /dev/null @@ -1,246 +0,0 @@ -package schema - -import ( - "bytes" - "fmt" - "reflect" - "sort" - "strconv" - "sync" - - "github.com/hashicorp/terraform-plugin-sdk/helper/hashcode" -) - -// HashString hashes strings. If you want a Set of strings, this is the -// SchemaSetFunc you want. -func HashString(v interface{}) int { - return hashcode.String(v.(string)) -} - -// HashInt hashes integers. If you want a Set of integers, this is the -// SchemaSetFunc you want. -func HashInt(v interface{}) int { - return hashcode.String(strconv.Itoa(v.(int))) -} - -// HashResource hashes complex structures that are described using -// a *Resource. This is the default set implementation used when a set's -// element type is a full resource. -func HashResource(resource *Resource) SchemaSetFunc { - return func(v interface{}) int { - var buf bytes.Buffer - SerializeResourceForHash(&buf, v, resource) - return hashcode.String(buf.String()) - } -} - -// HashSchema hashes values that are described using a *Schema. This is the -// default set implementation used when a set's element type is a single -// schema. -func HashSchema(schema *Schema) SchemaSetFunc { - return func(v interface{}) int { - var buf bytes.Buffer - SerializeValueForHash(&buf, v, schema) - return hashcode.String(buf.String()) - } -} - -// Set is a set data structure that is returned for elements of type -// TypeSet. -type Set struct { - F SchemaSetFunc - - m map[string]interface{} - once sync.Once -} - -// NewSet is a convenience method for creating a new set with the given -// items. -func NewSet(f SchemaSetFunc, items []interface{}) *Set { - s := &Set{F: f} - for _, i := range items { - s.Add(i) - } - - return s -} - -// CopySet returns a copy of another set. -func CopySet(otherSet *Set) *Set { - return NewSet(otherSet.F, otherSet.List()) -} - -// Add adds an item to the set if it isn't already in the set. -func (s *Set) Add(item interface{}) { - s.add(item, false) -} - -// Remove removes an item if it's already in the set. Idempotent. -func (s *Set) Remove(item interface{}) { - s.remove(item) -} - -// Contains checks if the set has the given item. -func (s *Set) Contains(item interface{}) bool { - _, ok := s.m[s.hash(item)] - return ok -} - -// Len returns the amount of items in the set. -func (s *Set) Len() int { - return len(s.m) -} - -// List returns the elements of this set in slice format. -// -// The order of the returned elements is deterministic. Given the same -// set, the order of this will always be the same. -func (s *Set) List() []interface{} { - result := make([]interface{}, len(s.m)) - for i, k := range s.listCode() { - result[i] = s.m[k] - } - - return result -} - -// Difference performs a set difference of the two sets, returning -// a new third set that has only the elements unique to this set. -func (s *Set) Difference(other *Set) *Set { - result := &Set{F: s.F} - result.once.Do(result.init) - - for k, v := range s.m { - if _, ok := other.m[k]; !ok { - result.m[k] = v - } - } - - return result -} - -// Intersection performs the set intersection of the two sets -// and returns a new third set. -func (s *Set) Intersection(other *Set) *Set { - result := &Set{F: s.F} - result.once.Do(result.init) - - for k, v := range s.m { - if _, ok := other.m[k]; ok { - result.m[k] = v - } - } - - return result -} - -// Union performs the set union of the two sets and returns a new third -// set. -func (s *Set) Union(other *Set) *Set { - result := &Set{F: s.F} - result.once.Do(result.init) - - for k, v := range s.m { - result.m[k] = v - } - for k, v := range other.m { - result.m[k] = v - } - - return result -} - -func (s *Set) Equal(raw interface{}) bool { - other, ok := raw.(*Set) - if !ok { - return false - } - - return reflect.DeepEqual(s.m, other.m) -} - -// HashEqual simply checks to the keys the top-level map to the keys in the -// other set's top-level map to see if they are equal. This obviously assumes -// you have a properly working hash function - use HashResource if in doubt. -func (s *Set) HashEqual(raw interface{}) bool { - other, ok := raw.(*Set) - if !ok { - return false - } - - ks1 := make([]string, 0) - ks2 := make([]string, 0) - - for k := range s.m { - ks1 = append(ks1, k) - } - for k := range other.m { - ks2 = append(ks2, k) - } - - sort.Strings(ks1) - sort.Strings(ks2) - - return reflect.DeepEqual(ks1, ks2) -} - -func (s *Set) GoString() string { - return fmt.Sprintf("*Set(%#v)", s.m) -} - -func (s *Set) init() { - s.m = make(map[string]interface{}) -} - -func (s *Set) add(item interface{}, computed bool) string { - s.once.Do(s.init) - - code := s.hash(item) - if computed { - code = "~" + code - - if isProto5() { - tmpCode := code - count := 0 - for _, exists := s.m[tmpCode]; exists; _, exists = s.m[tmpCode] { - count++ - tmpCode = fmt.Sprintf("%s%d", code, count) - } - code = tmpCode - } - } - - if _, ok := s.m[code]; !ok { - s.m[code] = item - } - - return code -} - -func (s *Set) hash(item interface{}) string { - code := s.F(item) - // Always return a nonnegative hashcode. - if code < 0 { - code = -code - } - return strconv.Itoa(code) -} - -func (s *Set) remove(item interface{}) string { - s.once.Do(s.init) - - code := s.hash(item) - delete(s.m, code) - - return code -} - -func (s *Set) listCode() []string { - // Sort the hash codes so the order of the list is deterministic - keys := make([]string, 0, len(s.m)) - for k := range s.m { - keys = append(keys, k) - } - sort.Sort(sort.StringSlice(keys)) - return keys -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/testing.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/testing.go deleted file mode 100644 index 4d0fd7365de..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/testing.go +++ /dev/null @@ -1,28 +0,0 @@ -package schema - -import ( - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -// TestResourceDataRaw creates a ResourceData from a raw configuration map. -func TestResourceDataRaw( - t *testing.T, schema map[string]*Schema, raw map[string]interface{}) *ResourceData { - t.Helper() - - c := terraform.NewResourceConfigRaw(raw) - - sm := schemaMap(schema) - diff, err := sm.Diff(nil, c, nil, nil, true) - if err != nil { - t.Fatalf("err: %s", err) - } - - result, err := sm.Data(nil, diff) - if err != nil { - t.Fatalf("err: %s", err) - } - - return result -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/int.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/int.go deleted file mode 100644 index 8ade5b1e689..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/int.go +++ /dev/null @@ -1,125 +0,0 @@ -package validation - -import ( - "fmt" - "math" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -// IntBetween returns a SchemaValidateFunc which tests if the provided value -// is of type int and is between min and max (inclusive) -func IntBetween(min, max int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(int) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) - return warnings, errors - } - - if v < min || v > max { - errors = append(errors, fmt.Errorf("expected %s to be in the range (%d - %d), got %d", k, min, max, v)) - return warnings, errors - } - - return warnings, errors - } -} - -// IntAtLeast returns a SchemaValidateFunc which tests if the provided value -// is of type int and is at least min (inclusive) -func IntAtLeast(min int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(int) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) - return warnings, errors - } - - if v < min { - errors = append(errors, fmt.Errorf("expected %s to be at least (%d), got %d", k, min, v)) - return warnings, errors - } - - return warnings, errors - } -} - -// IntAtMost returns a SchemaValidateFunc which tests if the provided value -// is of type int and is at most max (inclusive) -func IntAtMost(max int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(int) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) - return warnings, errors - } - - if v > max { - errors = append(errors, fmt.Errorf("expected %s to be at most (%d), got %d", k, max, v)) - return warnings, errors - } - - return warnings, errors - } -} - -// IntDivisibleBy returns a SchemaValidateFunc which tests if the provided value -// is of type int and is divisible by a given number -func IntDivisibleBy(divisor int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(int) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) - return warnings, errors - } - - if math.Mod(float64(v), float64(divisor)) != 0 { - errors = append(errors, fmt.Errorf("expected %s to be divisible by %d, got: %v", k, divisor, i)) - return warnings, errors - } - - return warnings, errors - } -} - -// IntInSlice returns a SchemaValidateFunc which tests if the provided value -// is of type int and matches the value of an element in the valid slice -func IntInSlice(valid []int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(int) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) - return warnings, errors - } - - for _, validInt := range valid { - if v == validInt { - return warnings, errors - } - } - - errors = append(errors, fmt.Errorf("expected %s to be one of %v, got %d", k, valid, v)) - return warnings, errors - } -} - -// IntNotInSlice returns a SchemaValidateFunc which tests if the provided value -// is of type int and matches the value of an element in the valid slice -func IntNotInSlice(valid []int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(int) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) - return warnings, errors - } - - for _, validInt := range valid { - if v == validInt { - errors = append(errors, fmt.Errorf("expected %s to not be one of %v, got %d", k, valid, v)) - } - } - - return warnings, errors - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/list.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/list.go deleted file mode 100644 index d60a4882f2d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/list.go +++ /dev/null @@ -1,41 +0,0 @@ -package validation - -import "fmt" - -// ValidateListUniqueStrings is a ValidateFunc that ensures a list has no -// duplicate items in it. It's useful for when a list is needed over a set -// because order matters, yet the items still need to be unique. -// -// Deprecated: use ListOfUniqueStrings -func ValidateListUniqueStrings(i interface{}, k string) (warnings []string, errors []error) { - return ListOfUniqueStrings(i, k) -} - -// ListOfUniqueStrings is a ValidateFunc that ensures a list has no -// duplicate items in it. It's useful for when a list is needed over a set -// because order matters, yet the items still need to be unique. -func ListOfUniqueStrings(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.([]interface{}) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %q to be List", k)) - return warnings, errors - } - - for _, e := range v { - if _, eok := e.(string); !eok { - errors = append(errors, fmt.Errorf("expected %q to only contain string elements, found :%v", k, e)) - return warnings, errors - } - } - - for n1, i1 := range v { - for n2, i2 := range v { - if i1.(string) == i2.(string) && n1 != n2 { - errors = append(errors, fmt.Errorf("expected %q to not have duplicates: found 2 or more of %v", k, i1)) - return warnings, errors - } - } - } - - return warnings, errors -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/meta.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/meta.go deleted file mode 100644 index b05557ac2a6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/meta.go +++ /dev/null @@ -1,59 +0,0 @@ -package validation - -import ( - "fmt" - "reflect" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -// NoZeroValues is a SchemaValidateFunc which tests if the provided value is -// not a zero value. It's useful in situations where you want to catch -// explicit zero values on things like required fields during validation. -func NoZeroValues(i interface{}, k string) (s []string, es []error) { - if reflect.ValueOf(i).Interface() == reflect.Zero(reflect.TypeOf(i)).Interface() { - switch reflect.TypeOf(i).Kind() { - case reflect.String: - es = append(es, fmt.Errorf("%s must not be empty, got %v", k, i)) - case reflect.Int, reflect.Float64: - es = append(es, fmt.Errorf("%s must not be zero, got %v", k, i)) - default: - // this validator should only ever be applied to TypeString, TypeInt and TypeFloat - panic(fmt.Errorf("can't use NoZeroValues with %T attribute %s", i, k)) - } - } - return -} - -// All returns a SchemaValidateFunc which tests if the provided value -// passes all provided SchemaValidateFunc -func All(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc { - return func(i interface{}, k string) ([]string, []error) { - var allErrors []error - var allWarnings []string - for _, validator := range validators { - validatorWarnings, validatorErrors := validator(i, k) - allWarnings = append(allWarnings, validatorWarnings...) - allErrors = append(allErrors, validatorErrors...) - } - return allWarnings, allErrors - } -} - -// Any returns a SchemaValidateFunc which tests if the provided value -// passes any of the provided SchemaValidateFunc -func Any(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc { - return func(i interface{}, k string) ([]string, []error) { - var allErrors []error - var allWarnings []string - for _, validator := range validators { - validatorWarnings, validatorErrors := validator(i, k) - if len(validatorWarnings) == 0 && len(validatorErrors) == 0 { - return []string{}, []error{} - } - allWarnings = append(allWarnings, validatorWarnings...) - allErrors = append(allErrors, validatorErrors...) - } - return allWarnings, allErrors - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/strings.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/strings.go deleted file mode 100644 index c4e53b5126f..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/strings.go +++ /dev/null @@ -1,253 +0,0 @@ -package validation - -import ( - "encoding/base64" - "fmt" - "regexp" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/helper/structure" -) - -// StringIsNotEmpty is a ValidateFunc that ensures a string is not empty -func StringIsNotEmpty(i interface{}, k string) ([]string, []error) { - v, ok := i.(string) - if !ok { - return nil, []error{fmt.Errorf("expected type of %q to be string", k)} - } - - if v == "" { - return nil, []error{fmt.Errorf("expected %q to not be an empty string, got %v", k, i)} - } - - return nil, nil -} - -// StringIsNotWhiteSpace is a ValidateFunc that ensures a string is not empty or consisting entirely of whitespace characters -func StringIsNotWhiteSpace(i interface{}, k string) ([]string, []error) { - v, ok := i.(string) - if !ok { - return nil, []error{fmt.Errorf("expected type of %q to be string", k)} - } - - if strings.TrimSpace(v) == "" { - return nil, []error{fmt.Errorf("expected %q to not be an empty string or whitespace", k)} - } - - return nil, nil -} - -// StringIsEmpty is a ValidateFunc that ensures a string has no characters -func StringIsEmpty(i interface{}, k string) ([]string, []error) { - v, ok := i.(string) - if !ok { - return nil, []error{fmt.Errorf("expected type of %q to be string", k)} - } - - if v != "" { - return nil, []error{fmt.Errorf("expected %q to be an empty string: got %v", k, v)} - } - - return nil, nil -} - -// StringIsWhiteSpace is a ValidateFunc that ensures a string is composed of entirely whitespace -func StringIsWhiteSpace(i interface{}, k string) ([]string, []error) { - v, ok := i.(string) - if !ok { - return nil, []error{fmt.Errorf("expected type of %q to be string", k)} - } - - if strings.TrimSpace(v) != "" { - return nil, []error{fmt.Errorf("expected %q to be an empty string or whitespace: got %v", k, v)} - } - - return nil, nil -} - -// StringLenBetween returns a SchemaValidateFunc which tests if the provided value -// is of type string and has length between min and max (inclusive) -func StringLenBetween(min, max int) schema.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return warnings, errors - } - - if len(v) < min || len(v) > max { - errors = append(errors, fmt.Errorf("expected length of %s to be in the range (%d - %d), got %s", k, min, max, v)) - } - - return warnings, errors - } -} - -// StringMatch returns a SchemaValidateFunc which tests if the provided value -// matches a given regexp. Optionally an error message can be provided to -// return something friendlier than "must match some globby regexp". -func StringMatch(r *regexp.Regexp, message string) schema.SchemaValidateFunc { - return func(i interface{}, k string) ([]string, []error) { - v, ok := i.(string) - if !ok { - return nil, []error{fmt.Errorf("expected type of %s to be string", k)} - } - - if ok := r.MatchString(v); !ok { - if message != "" { - return nil, []error{fmt.Errorf("invalid value for %s (%s)", k, message)} - - } - return nil, []error{fmt.Errorf("expected value of %s to match regular expression %q, got %v", k, r, i)} - } - return nil, nil - } -} - -// StringDoesNotMatch returns a SchemaValidateFunc which tests if the provided value -// does not match a given regexp. Optionally an error message can be provided to -// return something friendlier than "must not match some globby regexp". -func StringDoesNotMatch(r *regexp.Regexp, message string) schema.SchemaValidateFunc { - return func(i interface{}, k string) ([]string, []error) { - v, ok := i.(string) - if !ok { - return nil, []error{fmt.Errorf("expected type of %s to be string", k)} - } - - if ok := r.MatchString(v); ok { - if message != "" { - return nil, []error{fmt.Errorf("invalid value for %s (%s)", k, message)} - - } - return nil, []error{fmt.Errorf("expected value of %s to not match regular expression %q, got %v", k, r, i)} - } - return nil, nil - } -} - -// StringInSlice returns a SchemaValidateFunc which tests if the provided value -// is of type string and matches the value of an element in the valid slice -// will test with in lower case if ignoreCase is true -func StringInSlice(valid []string, ignoreCase bool) schema.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return warnings, errors - } - - for _, str := range valid { - if v == str || (ignoreCase && strings.ToLower(v) == strings.ToLower(str)) { - return warnings, errors - } - } - - errors = append(errors, fmt.Errorf("expected %s to be one of %v, got %s", k, valid, v)) - return warnings, errors - } -} - -// StringNotInSlice returns a SchemaValidateFunc which tests if the provided value -// is of type string and does not match the value of any element in the invalid slice -// will test with in lower case if ignoreCase is true -func StringNotInSlice(invalid []string, ignoreCase bool) schema.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return warnings, errors - } - - for _, str := range invalid { - if v == str || (ignoreCase && strings.ToLower(v) == strings.ToLower(str)) { - errors = append(errors, fmt.Errorf("expected %s to not be any of %v, got %s", k, invalid, v)) - return warnings, errors - } - } - - return warnings, errors - } -} - -// StringDoesNotContainAny returns a SchemaValidateFunc which validates that the -// provided value does not contain any of the specified Unicode code points in chars. -func StringDoesNotContainAny(chars string) schema.SchemaValidateFunc { - return func(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return warnings, errors - } - - if strings.ContainsAny(v, chars) { - errors = append(errors, fmt.Errorf("expected value of %s to not contain any of %q, got %v", k, chars, i)) - return warnings, errors - } - - return warnings, errors - } -} - -// StringIsBase64 is a ValidateFunc that ensures a string can be parsed as Base64 -func StringIsBase64(i interface{}, k string) (warnings []string, errors []error) { - // Empty string is not allowed - if warnings, errors = StringIsNotEmpty(i, k); len(errors) > 0 { - return - } - - // NoEmptyStrings checks it is a string - v, _ := i.(string) - - if _, err := base64.StdEncoding.DecodeString(v); err != nil { - errors = append(errors, fmt.Errorf("expected %q to be a base64 string, got %v", k, v)) - } - - return warnings, errors -} - -// ValidateJsonString is a SchemaValidateFunc which tests to make sure the -// supplied string is valid JSON. -// -// Deprecated: use StringIsJSON instead -func ValidateJsonString(i interface{}, k string) (warnings []string, errors []error) { - return StringIsJSON(i, k) -} - -// StringIsJSON is a SchemaValidateFunc which tests to make sure the supplied string is valid JSON. -func StringIsJSON(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return warnings, errors - } - - if _, err := structure.NormalizeJsonString(v); err != nil { - errors = append(errors, fmt.Errorf("%q contains an invalid JSON: %s", k, err)) - } - - return warnings, errors -} - -// ValidateRegexp returns a SchemaValidateFunc which tests to make sure the -// supplied string is a valid regular expression. -// -// Deprecated: use StringIsValidRegExp instead -func ValidateRegexp(i interface{}, k string) (warnings []string, errors []error) { - return StringIsValidRegExp(i, k) -} - -// StringIsValidRegExp returns a SchemaValidateFunc which tests to make sure the supplied string is a valid regular expression. -func StringIsValidRegExp(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) - return warnings, errors - } - - if _, err := regexp.Compile(v); err != nil { - errors = append(errors, fmt.Errorf("%q: %s", k, err)) - } - - return warnings, errors -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/testing.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/testing.go deleted file mode 100644 index 8a2da7f892b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/testing.go +++ /dev/null @@ -1,43 +0,0 @@ -package validation - -import ( - "regexp" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -type testCase struct { - val interface{} - f schema.SchemaValidateFunc - expectedErr *regexp.Regexp -} - -func runTestCases(t *testing.T, cases []testCase) { - matchErr := func(errs []error, r *regexp.Regexp) bool { - // err must match one provided - for _, err := range errs { - if r.MatchString(err.Error()) { - return true - } - } - - return false - } - - for i, tc := range cases { - _, errs := tc.f(tc.val, "test_property") - - if len(errs) == 0 && tc.expectedErr == nil { - continue - } - - if len(errs) != 0 && tc.expectedErr == nil { - t.Fatalf("expected test case %d to produce no errors, got %v", i, errs) - } - - if !matchErr(errs, tc.expectedErr) { - t.Fatalf("expected test case %d to produce error matching \"%s\", got %v", i, tc.expectedErr, errs) - } - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/time.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/time.go deleted file mode 100644 index 1c6788c68fe..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/time.go +++ /dev/null @@ -1,61 +0,0 @@ -package validation - -import ( - "fmt" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" -) - -// IsDayOfTheWeek id a SchemaValidateFunc which tests if the provided value is of type string and a valid english day of the week -func IsDayOfTheWeek(ignoreCase bool) schema.SchemaValidateFunc { - return StringInSlice([]string{ - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - "Sunday", - }, ignoreCase) -} - -// IsMonth id a SchemaValidateFunc which tests if the provided value is of type string and a valid english month -func IsMonth(ignoreCase bool) schema.SchemaValidateFunc { - return StringInSlice([]string{ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December", - }, ignoreCase) -} - -// IsRFC3339Time is a SchemaValidateFunc which tests if the provided value is of type string and a valid RFC33349Time -func IsRFC3339Time(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) - return warnings, errors - } - - if _, err := time.Parse(time.RFC3339, v); err != nil { - errors = append(errors, fmt.Errorf("expected %q to be a valid RFC3339 date, got %q: %+v", k, i, err)) - } - - return warnings, errors -} - -// ValidateRFC3339TimeString is a ValidateFunc that ensures a string parses as time.RFC3339 format -// -// Deprecated: use IsRFC3339Time() instead -func ValidateRFC3339TimeString(i interface{}, k string) (warnings []string, errors []error) { - return IsRFC3339Time(i, k) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/httpclient/useragent.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/httpclient/useragent.go deleted file mode 100644 index 36b494c0149..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/httpclient/useragent.go +++ /dev/null @@ -1,26 +0,0 @@ -package httpclient - -import ( - "fmt" - "log" - "os" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/meta" -) - -const uaEnvVar = "TF_APPEND_USER_AGENT" - -func TerraformUserAgent(version string) string { - ua := fmt.Sprintf("HashiCorp Terraform/%s (+https://www.terraform.io) Terraform Plugin SDK/%s", version, meta.SDKVersionString()) - - if add := os.Getenv(uaEnvVar); add != "" { - add = strings.TrimSpace(add) - if len(add) > 0 { - ua += " " + add - log.Printf("[DEBUG] Using modified User-Agent: %s", ua) - } - } - - return ua -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/count_attr.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/count_attr.go deleted file mode 100644 index 90a5faf0edf..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/count_attr.go +++ /dev/null @@ -1,12 +0,0 @@ -package addrs - -// CountAttr is the address of an attribute of the "count" object in -// the interpolation scope, like "count.index". -type CountAttr struct { - referenceable - Name string -} - -func (ca CountAttr) String() string { - return "count." + ca.Name -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/for_each_attr.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/for_each_attr.go deleted file mode 100644 index 7a6385035df..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/for_each_attr.go +++ /dev/null @@ -1,12 +0,0 @@ -package addrs - -// ForEachAttr is the address of an attribute referencing the current "for_each" object in -// the interpolation scope, addressed using the "each" keyword, ex. "each.key" and "each.value" -type ForEachAttr struct { - referenceable - Name string -} - -func (f ForEachAttr) String() string { - return "each." + f.Name -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/input_variable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/input_variable.go deleted file mode 100644 index d2c046c111b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/input_variable.go +++ /dev/null @@ -1,41 +0,0 @@ -package addrs - -import ( - "fmt" -) - -// InputVariable is the address of an input variable. -type InputVariable struct { - referenceable - Name string -} - -func (v InputVariable) String() string { - return "var." + v.Name -} - -// AbsInputVariableInstance is the address of an input variable within a -// particular module instance. -type AbsInputVariableInstance struct { - Module ModuleInstance - Variable InputVariable -} - -// InputVariable returns the absolute address of the input variable of the -// given name inside the receiving module instance. -func (m ModuleInstance) InputVariable(name string) AbsInputVariableInstance { - return AbsInputVariableInstance{ - Module: m, - Variable: InputVariable{ - Name: name, - }, - } -} - -func (v AbsInputVariableInstance) String() string { - if len(v.Module) == 0 { - return v.String() - } - - return fmt.Sprintf("%s.%s", v.Module.String(), v.Variable.String()) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/instance_key.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/instance_key.go deleted file mode 100644 index cef8b279640..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/instance_key.go +++ /dev/null @@ -1,123 +0,0 @@ -package addrs - -import ( - "fmt" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/gocty" -) - -// InstanceKey represents the key of an instance within an object that -// contains multiple instances due to using "count" or "for_each" arguments -// in configuration. -// -// IntKey and StringKey are the two implementations of this type. No other -// implementations are allowed. The single instance of an object that _isn't_ -// using "count" or "for_each" is represented by NoKey, which is a nil -// InstanceKey. -type InstanceKey interface { - instanceKeySigil() - String() string -} - -// ParseInstanceKey returns the instance key corresponding to the given value, -// which must be known and non-null. -// -// If an unknown or null value is provided then this function will panic. This -// function is intended to deal with the values that would naturally be found -// in a hcl.TraverseIndex, which (when parsed from source, at least) can never -// contain unknown or null values. -func ParseInstanceKey(key cty.Value) (InstanceKey, error) { - switch key.Type() { - case cty.String: - return StringKey(key.AsString()), nil - case cty.Number: - var idx int - err := gocty.FromCtyValue(key, &idx) - return IntKey(idx), err - default: - return NoKey, fmt.Errorf("either a string or an integer is required") - } -} - -// NoKey represents the absense of an InstanceKey, for the single instance -// of a configuration object that does not use "count" or "for_each" at all. -var NoKey InstanceKey - -// IntKey is the InstanceKey representation representing integer indices, as -// used when the "count" argument is specified or if for_each is used with -// a sequence type. -type IntKey int - -func (k IntKey) instanceKeySigil() { -} - -func (k IntKey) String() string { - return fmt.Sprintf("[%d]", int(k)) -} - -// StringKey is the InstanceKey representation representing string indices, as -// used when the "for_each" argument is specified with a map or object type. -type StringKey string - -func (k StringKey) instanceKeySigil() { -} - -func (k StringKey) String() string { - // FIXME: This isn't _quite_ right because Go's quoted string syntax is - // slightly different than HCL's, but we'll accept it for now. - return fmt.Sprintf("[%q]", string(k)) -} - -// InstanceKeyLess returns true if the first given instance key i should sort -// before the second key j, and false otherwise. -func InstanceKeyLess(i, j InstanceKey) bool { - iTy := instanceKeyType(i) - jTy := instanceKeyType(j) - - switch { - case i == j: - return false - case i == NoKey: - return true - case j == NoKey: - return false - case iTy != jTy: - // The ordering here is arbitrary except that we want NoKeyType - // to sort before the others, so we'll just use the enum values - // of InstanceKeyType here (where NoKey is zero, sorting before - // any other). - return uint32(iTy) < uint32(jTy) - case iTy == IntKeyType: - return int(i.(IntKey)) < int(j.(IntKey)) - case iTy == StringKeyType: - return string(i.(StringKey)) < string(j.(StringKey)) - default: - // Shouldn't be possible to get down here in practice, since the - // above is exhaustive. - return false - } -} - -func instanceKeyType(k InstanceKey) InstanceKeyType { - if _, ok := k.(StringKey); ok { - return StringKeyType - } - if _, ok := k.(IntKey); ok { - return IntKeyType - } - return NoKeyType -} - -// InstanceKeyType represents the different types of instance key that are -// supported. Usually it is sufficient to simply type-assert an InstanceKey -// value to either IntKey or StringKey, but this type and its values can be -// used to represent the types themselves, rather than specific values -// of those types. -type InstanceKeyType rune - -const ( - NoKeyType InstanceKeyType = 0 - IntKeyType InstanceKeyType = 'I' - StringKeyType InstanceKeyType = 'S' -) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/local_value.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/local_value.go deleted file mode 100644 index 61a07b9c75b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/local_value.go +++ /dev/null @@ -1,48 +0,0 @@ -package addrs - -import ( - "fmt" -) - -// LocalValue is the address of a local value. -type LocalValue struct { - referenceable - Name string -} - -func (v LocalValue) String() string { - return "local." + v.Name -} - -// Absolute converts the receiver into an absolute address within the given -// module instance. -func (v LocalValue) Absolute(m ModuleInstance) AbsLocalValue { - return AbsLocalValue{ - Module: m, - LocalValue: v, - } -} - -// AbsLocalValue is the absolute address of a local value within a module instance. -type AbsLocalValue struct { - Module ModuleInstance - LocalValue LocalValue -} - -// LocalValue returns the absolute address of a local value of the given -// name within the receiving module instance. -func (m ModuleInstance) LocalValue(name string) AbsLocalValue { - return AbsLocalValue{ - Module: m, - LocalValue: LocalValue{ - Name: name, - }, - } -} - -func (v AbsLocalValue) String() string { - if len(v.Module) == 0 { - return v.LocalValue.String() - } - return fmt.Sprintf("%s.%s", v.Module.String(), v.LocalValue.String()) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module.go deleted file mode 100644 index 1533f853c5a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module.go +++ /dev/null @@ -1,51 +0,0 @@ -package addrs - -import ( - "strings" -) - -// Module is an address for a module call within configuration. This is -// the static counterpart of ModuleInstance, representing a traversal through -// the static module call tree in configuration and does not take into account -// the potentially-multiple instances of a module that might be created by -// "count" and "for_each" arguments within those calls. -// -// This type should be used only in very specialized cases when working with -// the static module call tree. Type ModuleInstance is appropriate in more cases. -// -// Although Module is a slice, it should be treated as immutable after creation. -type Module []string - -// IsRoot returns true if the receiver is the address of the root module, -// or false otherwise. -func (m Module) IsRoot() bool { - return len(m) == 0 -} - -func (m Module) String() string { - if len(m) == 0 { - return "" - } - return strings.Join([]string(m), ".") -} - -// Call returns the module call address that corresponds to the given module -// instance, along with the address of the module that contains it. -// -// There is no call for the root module, so this method will panic if called -// on the root module address. -// -// In practice, this just turns the last element of the receiver into a -// ModuleCall and then returns a slice of the receiever that excludes that -// last part. This is just a convenience for situations where a call address -// is required, such as when dealing with *Reference and Referencable values. -func (m Module) Call() (Module, ModuleCall) { - if len(m) == 0 { - panic("cannot produce ModuleCall for root module") - } - - caller, callName := m[:len(m)-1], m[len(m)-1] - return caller, ModuleCall{ - Name: callName, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_call.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_call.go deleted file mode 100644 index d138fade76b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_call.go +++ /dev/null @@ -1,63 +0,0 @@ -package addrs - -import ( - "fmt" -) - -// ModuleCall is the address of a call from the current module to a child -// module. -// -// There is no "Abs" version of ModuleCall because an absolute module path -// is represented by ModuleInstance. -type ModuleCall struct { - referenceable - Name string -} - -func (c ModuleCall) String() string { - return "module." + c.Name -} - -// ModuleCallInstance is the address of one instance of a module created from -// a module call, which might create multiple instances using "count" or -// "for_each" arguments. -type ModuleCallInstance struct { - referenceable - Call ModuleCall - Key InstanceKey -} - -func (c ModuleCallInstance) String() string { - if c.Key == NoKey { - return c.Call.String() - } - return fmt.Sprintf("module.%s%s", c.Call.Name, c.Key) -} - -// ModuleInstance returns the address of the module instance that corresponds -// to the receiving call instance when resolved in the given calling module. -// In other words, it returns the child module instance that the receving -// call instance creates. -func (c ModuleCallInstance) ModuleInstance(caller ModuleInstance) ModuleInstance { - return caller.Child(c.Call.Name, c.Key) -} - -// ModuleCallOutput is the address of a particular named output produced by -// an instance of a module call. -type ModuleCallOutput struct { - referenceable - Call ModuleCallInstance - Name string -} - -func (co ModuleCallOutput) String() string { - return fmt.Sprintf("%s.%s", co.Call.String(), co.Name) -} - -// AbsOutputValue returns the absolute output value address that corresponds -// to the receving module call output address, once resolved in the given -// calling module. -func (co ModuleCallOutput) AbsOutputValue(caller ModuleInstance) AbsOutputValue { - moduleAddr := co.Call.ModuleInstance(caller) - return moduleAddr.OutputValue(co.Name) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_instance.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_instance.go deleted file mode 100644 index bb0901a26c1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_instance.go +++ /dev/null @@ -1,388 +0,0 @@ -package addrs - -import ( - "bytes" - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/gocty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// ModuleInstance is an address for a particular module instance within the -// dynamic module tree. This is an extension of the static traversals -// represented by type Module that deals with the possibility of a single -// module call producing multiple instances via the "count" and "for_each" -// arguments. -// -// Although ModuleInstance is a slice, it should be treated as immutable after -// creation. -type ModuleInstance []ModuleInstanceStep - -var ( - _ Targetable = ModuleInstance(nil) -) - -func ParseModuleInstance(traversal hcl.Traversal) (ModuleInstance, tfdiags.Diagnostics) { - mi, remain, diags := parseModuleInstancePrefix(traversal) - if len(remain) != 0 { - if len(remain) == len(traversal) { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid module instance address", - Detail: "A module instance address must begin with \"module.\".", - Subject: remain.SourceRange().Ptr(), - }) - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid module instance address", - Detail: "The module instance address is followed by additional invalid content.", - Subject: remain.SourceRange().Ptr(), - }) - } - } - return mi, diags -} - -// ParseModuleInstanceStr is a helper wrapper around ParseModuleInstance -// that takes a string and parses it with the HCL native syntax traversal parser -// before interpreting it. -// -// This should be used only in specialized situations since it will cause the -// created references to not have any meaningful source location information. -// If a reference string is coming from a source that should be identified in -// error messages then the caller should instead parse it directly using a -// suitable function from the HCL API and pass the traversal itself to -// ParseProviderConfigCompact. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// then the returned address is invalid. -func ParseModuleInstanceStr(str string) (ModuleInstance, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return nil, diags - } - - addr, addrDiags := ParseModuleInstance(traversal) - diags = diags.Append(addrDiags) - return addr, diags -} - -func parseModuleInstancePrefix(traversal hcl.Traversal) (ModuleInstance, hcl.Traversal, tfdiags.Diagnostics) { - remain := traversal - var mi ModuleInstance - var diags tfdiags.Diagnostics - - for len(remain) > 0 { - var next string - switch tt := remain[0].(type) { - case hcl.TraverseRoot: - next = tt.Name - case hcl.TraverseAttr: - next = tt.Name - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address operator", - Detail: "Module address prefix must be followed by dot and then a name.", - Subject: remain[0].SourceRange().Ptr(), - }) - break - } - - if next != "module" { - break - } - - kwRange := remain[0].SourceRange() - remain = remain[1:] - // If we have the prefix "module" then we should be followed by an - // module call name, as an attribute, and then optionally an index step - // giving the instance key. - if len(remain) == 0 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address operator", - Detail: "Prefix \"module.\" must be followed by a module name.", - Subject: &kwRange, - }) - break - } - - var moduleName string - switch tt := remain[0].(type) { - case hcl.TraverseAttr: - moduleName = tt.Name - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address operator", - Detail: "Prefix \"module.\" must be followed by a module name.", - Subject: remain[0].SourceRange().Ptr(), - }) - break - } - remain = remain[1:] - step := ModuleInstanceStep{ - Name: moduleName, - } - - if len(remain) > 0 { - if idx, ok := remain[0].(hcl.TraverseIndex); ok { - remain = remain[1:] - - switch idx.Key.Type() { - case cty.String: - step.InstanceKey = StringKey(idx.Key.AsString()) - case cty.Number: - var idxInt int - err := gocty.FromCtyValue(idx.Key, &idxInt) - if err == nil { - step.InstanceKey = IntKey(idxInt) - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address operator", - Detail: fmt.Sprintf("Invalid module index: %s.", err), - Subject: idx.SourceRange().Ptr(), - }) - } - default: - // Should never happen, because no other types are allowed in traversal indices. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address operator", - Detail: "Invalid module key: must be either a string or an integer.", - Subject: idx.SourceRange().Ptr(), - }) - } - } - } - - mi = append(mi, step) - } - - var retRemain hcl.Traversal - if len(remain) > 0 { - retRemain = make(hcl.Traversal, len(remain)) - copy(retRemain, remain) - // The first element here might be either a TraverseRoot or a - // TraverseAttr, depending on whether we had a module address on the - // front. To make life easier for callers, we'll normalize to always - // start with a TraverseRoot. - if tt, ok := retRemain[0].(hcl.TraverseAttr); ok { - retRemain[0] = hcl.TraverseRoot{ - Name: tt.Name, - SrcRange: tt.SrcRange, - } - } - } - - return mi, retRemain, diags -} - -// UnkeyedInstanceShim is a shim method for converting a Module address to the -// equivalent ModuleInstance address that assumes that no modules have -// keyed instances. -// -// This is a temporary allowance for the fact that Terraform does not presently -// support "count" and "for_each" on modules, and thus graph building code that -// derives graph nodes from configuration must just assume unkeyed modules -// in order to construct the graph. At a later time when "count" and "for_each" -// support is added for modules, all callers of this method will need to be -// reworked to allow for keyed module instances. -func (m Module) UnkeyedInstanceShim() ModuleInstance { - path := make(ModuleInstance, len(m)) - for i, name := range m { - path[i] = ModuleInstanceStep{Name: name} - } - return path -} - -// ModuleInstanceStep is a single traversal step through the dynamic module -// tree. It is used only as part of ModuleInstance. -type ModuleInstanceStep struct { - Name string - InstanceKey InstanceKey -} - -// RootModuleInstance is the module instance address representing the root -// module, which is also the zero value of ModuleInstance. -var RootModuleInstance ModuleInstance - -// IsRoot returns true if the receiver is the address of the root module instance, -// or false otherwise. -func (m ModuleInstance) IsRoot() bool { - return len(m) == 0 -} - -// Child returns the address of a child module instance of the receiver, -// identified by the given name and key. -func (m ModuleInstance) Child(name string, key InstanceKey) ModuleInstance { - ret := make(ModuleInstance, 0, len(m)+1) - ret = append(ret, m...) - return append(ret, ModuleInstanceStep{ - Name: name, - InstanceKey: key, - }) -} - -// Parent returns the address of the parent module instance of the receiver, or -// the receiver itself if there is no parent (if it's the root module address). -func (m ModuleInstance) Parent() ModuleInstance { - if len(m) == 0 { - return m - } - return m[:len(m)-1] -} - -// String returns a string representation of the receiver, in the format used -// within e.g. user-provided resource addresses. -// -// The address of the root module has the empty string as its representation. -func (m ModuleInstance) String() string { - var buf bytes.Buffer - sep := "" - for _, step := range m { - buf.WriteString(sep) - buf.WriteString("module.") - buf.WriteString(step.Name) - if step.InstanceKey != NoKey { - buf.WriteString(step.InstanceKey.String()) - } - sep = "." - } - return buf.String() -} - -// Less returns true if the receiver should sort before the given other value -// in a sorted list of addresses. -func (m ModuleInstance) Less(o ModuleInstance) bool { - if len(m) != len(o) { - // Shorter path sorts first. - return len(m) < len(o) - } - - for i := range m { - mS, oS := m[i], o[i] - switch { - case mS.Name != oS.Name: - return mS.Name < oS.Name - case mS.InstanceKey != oS.InstanceKey: - return InstanceKeyLess(mS.InstanceKey, oS.InstanceKey) - } - } - - return false -} - -// Ancestors returns a slice containing the receiver and all of its ancestor -// module instances, all the way up to (and including) the root module. -// The result is ordered by depth, with the root module always first. -// -// Since the result always includes the root module, a caller may choose to -// ignore it by slicing the result with [1:]. -func (m ModuleInstance) Ancestors() []ModuleInstance { - ret := make([]ModuleInstance, 0, len(m)+1) - for i := 0; i <= len(m); i++ { - ret = append(ret, m[:i]) - } - return ret -} - -// Call returns the module call address that corresponds to the given module -// instance, along with the address of the module instance that contains it. -// -// There is no call for the root module, so this method will panic if called -// on the root module address. -// -// A single module call can produce potentially many module instances, so the -// result discards any instance key that might be present on the last step -// of the instance. To retain this, use CallInstance instead. -// -// In practice, this just turns the last element of the receiver into a -// ModuleCall and then returns a slice of the receiever that excludes that -// last part. This is just a convenience for situations where a call address -// is required, such as when dealing with *Reference and Referencable values. -func (m ModuleInstance) Call() (ModuleInstance, ModuleCall) { - if len(m) == 0 { - panic("cannot produce ModuleCall for root module") - } - - inst, lastStep := m[:len(m)-1], m[len(m)-1] - return inst, ModuleCall{ - Name: lastStep.Name, - } -} - -// CallInstance returns the module call instance address that corresponds to -// the given module instance, along with the address of the module instance -// that contains it. -// -// There is no call for the root module, so this method will panic if called -// on the root module address. -// -// In practice, this just turns the last element of the receiver into a -// ModuleCallInstance and then returns a slice of the receiever that excludes -// that last part. This is just a convenience for situations where a call\ -// address is required, such as when dealing with *Reference and Referencable -// values. -func (m ModuleInstance) CallInstance() (ModuleInstance, ModuleCallInstance) { - if len(m) == 0 { - panic("cannot produce ModuleCallInstance for root module") - } - - inst, lastStep := m[:len(m)-1], m[len(m)-1] - return inst, ModuleCallInstance{ - Call: ModuleCall{ - Name: lastStep.Name, - }, - Key: lastStep.InstanceKey, - } -} - -// TargetContains implements Targetable by returning true if the given other -// address either matches the receiver, is a sub-module-instance of the -// receiver, or is a targetable absolute address within a module that -// is contained within the reciever. -func (m ModuleInstance) TargetContains(other Targetable) bool { - switch to := other.(type) { - - case ModuleInstance: - if len(to) < len(m) { - // Can't be contained if the path is shorter - return false - } - // Other is contained if its steps match for the length of our own path. - for i, ourStep := range m { - otherStep := to[i] - if ourStep != otherStep { - return false - } - } - // If we fall out here then the prefixed matched, so it's contained. - return true - - case AbsResource: - return m.TargetContains(to.Module) - - case AbsResourceInstance: - return m.TargetContains(to.Module) - - default: - return false - } -} - -func (m ModuleInstance) targetableSigil() { - // ModuleInstance is targetable -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/output_value.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/output_value.go deleted file mode 100644 index bcd923acb76..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/output_value.go +++ /dev/null @@ -1,75 +0,0 @@ -package addrs - -import ( - "fmt" -) - -// OutputValue is the address of an output value, in the context of the module -// that is defining it. -// -// This is related to but separate from ModuleCallOutput, which represents -// a module output from the perspective of its parent module. Since output -// values cannot be represented from the module where they are defined, -// OutputValue is not Referenceable, while ModuleCallOutput is. -type OutputValue struct { - Name string -} - -func (v OutputValue) String() string { - return "output." + v.Name -} - -// Absolute converts the receiver into an absolute address within the given -// module instance. -func (v OutputValue) Absolute(m ModuleInstance) AbsOutputValue { - return AbsOutputValue{ - Module: m, - OutputValue: v, - } -} - -// AbsOutputValue is the absolute address of an output value within a module instance. -// -// This represents an output globally within the namespace of a particular -// configuration. It is related to but separate from ModuleCallOutput, which -// represents a module output from the perspective of its parent module. -type AbsOutputValue struct { - Module ModuleInstance - OutputValue OutputValue -} - -// OutputValue returns the absolute address of an output value of the given -// name within the receiving module instance. -func (m ModuleInstance) OutputValue(name string) AbsOutputValue { - return AbsOutputValue{ - Module: m, - OutputValue: OutputValue{ - Name: name, - }, - } -} - -func (v AbsOutputValue) String() string { - if v.Module.IsRoot() { - return v.OutputValue.String() - } - return fmt.Sprintf("%s.%s", v.Module.String(), v.OutputValue.String()) -} - -// ModuleCallOutput converts an AbsModuleOutput into a ModuleCallOutput, -// returning also the module instance that the ModuleCallOutput is relative -// to. -// -// The root module does not have a call, and so this method cannot be used -// with outputs in the root module, and will panic in that case. -func (v AbsOutputValue) ModuleCallOutput() (ModuleInstance, ModuleCallOutput) { - if v.Module.IsRoot() { - panic("ReferenceFromCall used with root module output") - } - - caller, call := v.Module.CallInstance() - return caller, ModuleCallOutput{ - Call: call, - Name: v.OutputValue.Name, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/parse_ref.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/parse_ref.go deleted file mode 100644 index a2ee16441e5..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/parse_ref.go +++ /dev/null @@ -1,346 +0,0 @@ -package addrs - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// Reference describes a reference to an address with source location -// information. -type Reference struct { - Subject Referenceable - SourceRange tfdiags.SourceRange - Remaining hcl.Traversal -} - -// ParseRef attempts to extract a referencable address from the prefix of the -// given traversal, which must be an absolute traversal or this function -// will panic. -// -// If no error diagnostics are returned, the returned reference includes the -// address that was extracted, the source range it was extracted from, and any -// remaining relative traversal that was not consumed as part of the -// reference. -// -// If error diagnostics are returned then the Reference value is invalid and -// must not be used. -func ParseRef(traversal hcl.Traversal) (*Reference, tfdiags.Diagnostics) { - ref, diags := parseRef(traversal) - - // Normalize a little to make life easier for callers. - if ref != nil { - if len(ref.Remaining) == 0 { - ref.Remaining = nil - } - } - - return ref, diags -} - -// ParseRefStr is a helper wrapper around ParseRef that takes a string -// and parses it with the HCL native syntax traversal parser before -// interpreting it. -// -// This should be used only in specialized situations since it will cause the -// created references to not have any meaningful source location information. -// If a reference string is coming from a source that should be identified in -// error messages then the caller should instead parse it directly using a -// suitable function from the HCL API and pass the traversal itself to -// ParseRef. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// the returned reference may be nil or incomplete. -func ParseRefStr(str string) (*Reference, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return nil, diags - } - - ref, targetDiags := ParseRef(traversal) - diags = diags.Append(targetDiags) - return ref, diags -} - -func parseRef(traversal hcl.Traversal) (*Reference, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - root := traversal.RootName() - rootRange := traversal[0].SourceRange() - - switch root { - - case "count": - name, rng, remain, diags := parseSingleAttrRef(traversal) - return &Reference{ - Subject: CountAttr{Name: name}, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags - - case "each": - name, rng, remain, diags := parseSingleAttrRef(traversal) - return &Reference{ - Subject: ForEachAttr{Name: name}, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags - - case "data": - if len(traversal) < 3 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: `The "data" object must be followed by two attribute names: the data source type and the resource name.`, - Subject: traversal.SourceRange().Ptr(), - }) - return nil, diags - } - remain := traversal[1:] // trim off "data" so we can use our shared resource reference parser - return parseResourceRef(DataResourceMode, rootRange, remain) - - case "local": - name, rng, remain, diags := parseSingleAttrRef(traversal) - return &Reference{ - Subject: LocalValue{Name: name}, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags - - case "module": - callName, callRange, remain, diags := parseSingleAttrRef(traversal) - if diags.HasErrors() { - return nil, diags - } - - // A traversal starting with "module" can either be a reference to - // an entire module instance or to a single output from a module - // instance, depending on what we find after this introducer. - - callInstance := ModuleCallInstance{ - Call: ModuleCall{ - Name: callName, - }, - Key: NoKey, - } - - if len(remain) == 0 { - // Reference to an entire module instance. Might alternatively - // be a reference to a collection of instances of a particular - // module, but the caller will need to deal with that ambiguity - // since we don't have enough context here. - return &Reference{ - Subject: callInstance, - SourceRange: tfdiags.SourceRangeFromHCL(callRange), - Remaining: remain, - }, diags - } - - if idxTrav, ok := remain[0].(hcl.TraverseIndex); ok { - var err error - callInstance.Key, err = ParseInstanceKey(idxTrav.Key) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid index key", - Detail: fmt.Sprintf("Invalid index for module instance: %s.", err), - Subject: &idxTrav.SrcRange, - }) - return nil, diags - } - remain = remain[1:] - - if len(remain) == 0 { - // Also a reference to an entire module instance, but we have a key - // now. - return &Reference{ - Subject: callInstance, - SourceRange: tfdiags.SourceRangeFromHCL(hcl.RangeBetween(callRange, idxTrav.SrcRange)), - Remaining: remain, - }, diags - } - } - - if attrTrav, ok := remain[0].(hcl.TraverseAttr); ok { - remain = remain[1:] - return &Reference{ - Subject: ModuleCallOutput{ - Name: attrTrav.Name, - Call: callInstance, - }, - SourceRange: tfdiags.SourceRangeFromHCL(hcl.RangeBetween(callRange, attrTrav.SrcRange)), - Remaining: remain, - }, diags - } - - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: "Module instance objects do not support this operation.", - Subject: remain[0].SourceRange().Ptr(), - }) - return nil, diags - - case "path": - name, rng, remain, diags := parseSingleAttrRef(traversal) - return &Reference{ - Subject: PathAttr{Name: name}, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags - - case "self": - return &Reference{ - Subject: Self, - SourceRange: tfdiags.SourceRangeFromHCL(rootRange), - Remaining: traversal[1:], - }, diags - - case "terraform": - name, rng, remain, diags := parseSingleAttrRef(traversal) - return &Reference{ - Subject: TerraformAttr{Name: name}, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags - - case "var": - name, rng, remain, diags := parseSingleAttrRef(traversal) - return &Reference{ - Subject: InputVariable{Name: name}, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags - - default: - return parseResourceRef(ManagedResourceMode, rootRange, traversal) - } -} - -func parseResourceRef(mode ResourceMode, startRange hcl.Range, traversal hcl.Traversal) (*Reference, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - if len(traversal) < 2 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: `A reference to a resource type must be followed by at least one attribute access, specifying the resource name.`, - Subject: hcl.RangeBetween(traversal[0].SourceRange(), traversal[len(traversal)-1].SourceRange()).Ptr(), - }) - return nil, diags - } - - var typeName, name string - switch tt := traversal[0].(type) { // Could be either root or attr, depending on our resource mode - case hcl.TraverseRoot: - typeName = tt.Name - case hcl.TraverseAttr: - typeName = tt.Name - default: - // If it isn't a TraverseRoot then it must be a "data" reference. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: `The "data" object does not support this operation.`, - Subject: traversal[0].SourceRange().Ptr(), - }) - return nil, diags - } - - attrTrav, ok := traversal[1].(hcl.TraverseAttr) - if !ok { - var what string - switch mode { - case DataResourceMode: - what = "data source" - default: - what = "resource type" - } - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: fmt.Sprintf(`A reference to a %s must be followed by at least one attribute access, specifying the resource name.`, what), - Subject: traversal[1].SourceRange().Ptr(), - }) - return nil, diags - } - name = attrTrav.Name - rng := hcl.RangeBetween(startRange, attrTrav.SrcRange) - remain := traversal[2:] - - resourceAddr := Resource{ - Mode: mode, - Type: typeName, - Name: name, - } - resourceInstAddr := ResourceInstance{ - Resource: resourceAddr, - Key: NoKey, - } - - if len(remain) == 0 { - // This might actually be a reference to the collection of all instances - // of the resource, but we don't have enough context here to decide - // so we'll let the caller resolve that ambiguity. - return &Reference{ - Subject: resourceAddr, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - }, diags - } - - if idxTrav, ok := remain[0].(hcl.TraverseIndex); ok { - var err error - resourceInstAddr.Key, err = ParseInstanceKey(idxTrav.Key) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid index key", - Detail: fmt.Sprintf("Invalid index for resource instance: %s.", err), - Subject: &idxTrav.SrcRange, - }) - return nil, diags - } - remain = remain[1:] - rng = hcl.RangeBetween(rng, idxTrav.SrcRange) - } - - return &Reference{ - Subject: resourceInstAddr, - SourceRange: tfdiags.SourceRangeFromHCL(rng), - Remaining: remain, - }, diags -} - -func parseSingleAttrRef(traversal hcl.Traversal) (string, hcl.Range, hcl.Traversal, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - root := traversal.RootName() - rootRange := traversal[0].SourceRange() - - if len(traversal) < 2 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: fmt.Sprintf("The %q object cannot be accessed directly. Instead, access one of its attributes.", root), - Subject: &rootRange, - }) - return "", hcl.Range{}, nil, diags - } - if attrTrav, ok := traversal[1].(hcl.TraverseAttr); ok { - return attrTrav.Name, hcl.RangeBetween(rootRange, attrTrav.SrcRange), traversal[2:], diags - } - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference", - Detail: fmt.Sprintf("The %q object does not support this operation.", root), - Subject: traversal[1].SourceRange().Ptr(), - }) - return "", hcl.Range{}, nil, diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/parse_target.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/parse_target.go deleted file mode 100644 index 5b922e8b664..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/parse_target.go +++ /dev/null @@ -1,240 +0,0 @@ -package addrs - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2/hclsyntax" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// Target describes a targeted address with source location information. -type Target struct { - Subject Targetable - SourceRange tfdiags.SourceRange -} - -// ParseTarget attempts to interpret the given traversal as a targetable -// address. The given traversal must be absolute, or this function will -// panic. -// -// If no error diagnostics are returned, the returned target includes the -// address that was extracted and the source range it was extracted from. -// -// If error diagnostics are returned then the Target value is invalid and -// must not be used. -func ParseTarget(traversal hcl.Traversal) (*Target, tfdiags.Diagnostics) { - path, remain, diags := parseModuleInstancePrefix(traversal) - if diags.HasErrors() { - return nil, diags - } - - rng := tfdiags.SourceRangeFromHCL(traversal.SourceRange()) - - if len(remain) == 0 { - return &Target{ - Subject: path, - SourceRange: rng, - }, diags - } - - mode := ManagedResourceMode - if remain.RootName() == "data" { - mode = DataResourceMode - remain = remain[1:] - } - - if len(remain) < 2 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "Resource specification must include a resource type and name.", - Subject: remain.SourceRange().Ptr(), - }) - return nil, diags - } - - var typeName, name string - switch tt := remain[0].(type) { - case hcl.TraverseRoot: - typeName = tt.Name - case hcl.TraverseAttr: - typeName = tt.Name - default: - switch mode { - case ManagedResourceMode: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A resource type name is required.", - Subject: remain[0].SourceRange().Ptr(), - }) - case DataResourceMode: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A data source name is required.", - Subject: remain[0].SourceRange().Ptr(), - }) - default: - panic("unknown mode") - } - return nil, diags - } - - switch tt := remain[1].(type) { - case hcl.TraverseAttr: - name = tt.Name - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A resource name is required.", - Subject: remain[1].SourceRange().Ptr(), - }) - return nil, diags - } - - var subject Targetable - remain = remain[2:] - switch len(remain) { - case 0: - subject = path.Resource(mode, typeName, name) - case 1: - if tt, ok := remain[0].(hcl.TraverseIndex); ok { - key, err := ParseInstanceKey(tt.Key) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: fmt.Sprintf("Invalid resource instance key: %s.", err), - Subject: remain[0].SourceRange().Ptr(), - }) - return nil, diags - } - - subject = path.ResourceInstance(mode, typeName, name, key) - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "Resource instance key must be given in square brackets.", - Subject: remain[0].SourceRange().Ptr(), - }) - return nil, diags - } - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "Unexpected extra operators after address.", - Subject: remain[1].SourceRange().Ptr(), - }) - return nil, diags - } - - return &Target{ - Subject: subject, - SourceRange: rng, - }, diags -} - -// ParseTargetStr is a helper wrapper around ParseTarget that takes a string -// and parses it with the HCL native syntax traversal parser before -// interpreting it. -// -// This should be used only in specialized situations since it will cause the -// created references to not have any meaningful source location information. -// If a target string is coming from a source that should be identified in -// error messages then the caller should instead parse it directly using a -// suitable function from the HCL API and pass the traversal itself to -// ParseTarget. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// the returned target may be nil or incomplete. -func ParseTargetStr(str string) (*Target, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return nil, diags - } - - target, targetDiags := ParseTarget(traversal) - diags = diags.Append(targetDiags) - return target, diags -} - -// ParseAbsResourceInstance attempts to interpret the given traversal as an -// absolute resource instance address, using the same syntax as expected by -// ParseTarget. -// -// If no error diagnostics are returned, the returned target includes the -// address that was extracted and the source range it was extracted from. -// -// If error diagnostics are returned then the AbsResource value is invalid and -// must not be used. -func ParseAbsResourceInstance(traversal hcl.Traversal) (AbsResourceInstance, tfdiags.Diagnostics) { - addr, diags := ParseTarget(traversal) - if diags.HasErrors() { - return AbsResourceInstance{}, diags - } - - switch tt := addr.Subject.(type) { - - case AbsResource: - return tt.Instance(NoKey), diags - - case AbsResourceInstance: - return tt, diags - - case ModuleInstance: // Catch likely user error with specialized message - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A resource instance address is required here. The module path must be followed by a resource instance specification.", - Subject: traversal.SourceRange().Ptr(), - }) - return AbsResourceInstance{}, diags - - default: // Generic message for other address types - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid address", - Detail: "A resource address is required here.", - Subject: traversal.SourceRange().Ptr(), - }) - return AbsResourceInstance{}, diags - - } -} - -// ParseAbsResourceInstanceStr is a helper wrapper around -// ParseAbsResourceInstance that takes a string and parses it with the HCL -// native syntax traversal parser before interpreting it. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// the returned address may be incomplete. -// -// Since this function has no context about the source of the given string, -// any returned diagnostics will not have meaningful source location -// information. -func ParseAbsResourceInstanceStr(str string) (AbsResourceInstance, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return AbsResourceInstance{}, diags - } - - addr, addrDiags := ParseAbsResourceInstance(traversal) - diags = diags.Append(addrDiags) - return addr, diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/path_attr.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/path_attr.go deleted file mode 100644 index cfc13f4bcd8..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/path_attr.go +++ /dev/null @@ -1,12 +0,0 @@ -package addrs - -// PathAttr is the address of an attribute of the "path" object in -// the interpolation scope, like "path.module". -type PathAttr struct { - referenceable - Name string -} - -func (pa PathAttr) String() string { - return "path." + pa.Name -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/provider_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/provider_config.go deleted file mode 100644 index c6fce1a5045..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/provider_config.go +++ /dev/null @@ -1,289 +0,0 @@ -package addrs - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" -) - -// ProviderConfig is the address of a provider configuration. -type ProviderConfig struct { - Type string - - // If not empty, Alias identifies which non-default (aliased) provider - // configuration this address refers to. - Alias string -} - -// ParseProviderConfigCompact parses the given absolute traversal as a relative -// provider address in compact form. The following are examples of traversals -// that can be successfully parsed as compact relative provider configuration -// addresses: -// -// aws -// aws.foo -// -// This function will panic if given a relative traversal. -// -// If the returned diagnostics contains errors then the result value is invalid -// and must not be used. -func ParseProviderConfigCompact(traversal hcl.Traversal) (ProviderConfig, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - ret := ProviderConfig{ - Type: traversal.RootName(), - } - - if len(traversal) < 2 { - // Just a type name, then. - return ret, diags - } - - aliasStep := traversal[1] - switch ts := aliasStep.(type) { - case hcl.TraverseAttr: - ret.Alias = ts.Name - return ret, diags - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "The provider type name must either stand alone or be followed by an alias name separated with a dot.", - Subject: aliasStep.SourceRange().Ptr(), - }) - } - - if len(traversal) > 2 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "Extraneous extra operators after provider configuration address.", - Subject: traversal[2:].SourceRange().Ptr(), - }) - } - - return ret, diags -} - -// ParseProviderConfigCompactStr is a helper wrapper around ParseProviderConfigCompact -// that takes a string and parses it with the HCL native syntax traversal parser -// before interpreting it. -// -// This should be used only in specialized situations since it will cause the -// created references to not have any meaningful source location information. -// If a reference string is coming from a source that should be identified in -// error messages then the caller should instead parse it directly using a -// suitable function from the HCL API and pass the traversal itself to -// ParseProviderConfigCompact. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// then the returned address is invalid. -func ParseProviderConfigCompactStr(str string) (ProviderConfig, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return ProviderConfig{}, diags - } - - addr, addrDiags := ParseProviderConfigCompact(traversal) - diags = diags.Append(addrDiags) - return addr, diags -} - -// Absolute returns an AbsProviderConfig from the receiver and the given module -// instance address. -func (pc ProviderConfig) Absolute(module ModuleInstance) AbsProviderConfig { - return AbsProviderConfig{ - Module: module, - ProviderConfig: pc, - } -} - -func (pc ProviderConfig) String() string { - if pc.Type == "" { - // Should never happen; always indicates a bug - return "provider." - } - - if pc.Alias != "" { - return fmt.Sprintf("provider.%s.%s", pc.Type, pc.Alias) - } - - return "provider." + pc.Type -} - -// StringCompact is an alternative to String that returns the form that can -// be parsed by ParseProviderConfigCompact, without the "provider." prefix. -func (pc ProviderConfig) StringCompact() string { - if pc.Alias != "" { - return fmt.Sprintf("%s.%s", pc.Type, pc.Alias) - } - return pc.Type -} - -// AbsProviderConfig is the absolute address of a provider configuration -// within a particular module instance. -type AbsProviderConfig struct { - Module ModuleInstance - ProviderConfig ProviderConfig -} - -// ParseAbsProviderConfig parses the given traversal as an absolute provider -// address. The following are examples of traversals that can be successfully -// parsed as absolute provider configuration addresses: -// -// provider.aws -// provider.aws.foo -// module.bar.provider.aws -// module.bar.module.baz.provider.aws.foo -// module.foo[1].provider.aws.foo -// -// This type of address is used, for example, to record the relationships -// between resources and provider configurations in the state structure. -// This type of address is not generally used in the UI, except in error -// messages that refer to provider configurations. -func ParseAbsProviderConfig(traversal hcl.Traversal) (AbsProviderConfig, tfdiags.Diagnostics) { - modInst, remain, diags := parseModuleInstancePrefix(traversal) - ret := AbsProviderConfig{ - Module: modInst, - } - if len(remain) < 2 || remain.RootName() != "provider" { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "Provider address must begin with \"provider.\", followed by a provider type name.", - Subject: remain.SourceRange().Ptr(), - }) - return ret, diags - } - if len(remain) > 3 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "Extraneous operators after provider configuration alias.", - Subject: hcl.Traversal(remain[3:]).SourceRange().Ptr(), - }) - return ret, diags - } - - if tt, ok := remain[1].(hcl.TraverseAttr); ok { - ret.ProviderConfig.Type = tt.Name - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "The prefix \"provider.\" must be followed by a provider type name.", - Subject: remain[1].SourceRange().Ptr(), - }) - return ret, diags - } - - if len(remain) == 3 { - if tt, ok := remain[2].(hcl.TraverseAttr); ok { - ret.ProviderConfig.Alias = tt.Name - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration address", - Detail: "Provider type name must be followed by a configuration alias name.", - Subject: remain[2].SourceRange().Ptr(), - }) - return ret, diags - } - } - - return ret, diags -} - -// ParseAbsProviderConfigStr is a helper wrapper around ParseAbsProviderConfig -// that takes a string and parses it with the HCL native syntax traversal parser -// before interpreting it. -// -// This should be used only in specialized situations since it will cause the -// created references to not have any meaningful source location information. -// If a reference string is coming from a source that should be identified in -// error messages then the caller should instead parse it directly using a -// suitable function from the HCL API and pass the traversal itself to -// ParseAbsProviderConfig. -// -// Error diagnostics are returned if either the parsing fails or the analysis -// of the traversal fails. There is no way for the caller to distinguish the -// two kinds of diagnostics programmatically. If error diagnostics are returned -// the returned address is invalid. -func ParseAbsProviderConfigStr(str string) (AbsProviderConfig, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(parseDiags) - if parseDiags.HasErrors() { - return AbsProviderConfig{}, diags - } - - addr, addrDiags := ParseAbsProviderConfig(traversal) - diags = diags.Append(addrDiags) - return addr, diags -} - -// ProviderConfigDefault returns the address of the default provider config -// of the given type inside the recieving module instance. -func (m ModuleInstance) ProviderConfigDefault(name string) AbsProviderConfig { - return AbsProviderConfig{ - Module: m, - ProviderConfig: ProviderConfig{ - Type: name, - }, - } -} - -// ProviderConfigAliased returns the address of an aliased provider config -// of with given type and alias inside the recieving module instance. -func (m ModuleInstance) ProviderConfigAliased(name, alias string) AbsProviderConfig { - return AbsProviderConfig{ - Module: m, - ProviderConfig: ProviderConfig{ - Type: name, - Alias: alias, - }, - } -} - -// Inherited returns an address that the receiving configuration address might -// inherit from in a parent module. The second bool return value indicates if -// such inheritance is possible, and thus whether the returned address is valid. -// -// Inheritance is possible only for default (un-aliased) providers in modules -// other than the root module. Even if a valid address is returned, inheritence -// may not be performed for other reasons, such as if the calling module -// provided explicit provider configurations within the call for this module. -// The ProviderTransformer graph transform in the main terraform module has -// the authoritative logic for provider inheritance, and this method is here -// mainly just for its benefit. -func (pc AbsProviderConfig) Inherited() (AbsProviderConfig, bool) { - // Can't inherit if we're already in the root. - if len(pc.Module) == 0 { - return AbsProviderConfig{}, false - } - - // Can't inherit if we have an alias. - if pc.ProviderConfig.Alias != "" { - return AbsProviderConfig{}, false - } - - // Otherwise, we might inherit from a configuration with the same - // provider name in the parent module instance. - parentMod := pc.Module.Parent() - return pc.ProviderConfig.Absolute(parentMod), true -} - -func (pc AbsProviderConfig) String() string { - if len(pc.Module) == 0 { - return pc.ProviderConfig.String() - } - return fmt.Sprintf("%s.%s", pc.Module.String(), pc.ProviderConfig.String()) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/provider_type.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/provider_type.go deleted file mode 100644 index 64b8ac869c9..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/provider_type.go +++ /dev/null @@ -1,7 +0,0 @@ -package addrs - -// ProviderType encapsulates a single provider type. In the future this will be -// extended to include additional fields including Namespace and SourceHost -type ProviderType struct { - Name string -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/referenceable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/referenceable.go deleted file mode 100644 index 211083a5f45..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/referenceable.go +++ /dev/null @@ -1,20 +0,0 @@ -package addrs - -// Referenceable is an interface implemented by all address types that can -// appear as references in configuration language expressions. -type Referenceable interface { - // All implementations of this interface must be covered by the type switch - // in lang.Scope.buildEvalContext. - referenceableSigil() - - // String produces a string representation of the address that could be - // parsed as a HCL traversal and passed to ParseRef to produce an identical - // result. - String() string -} - -type referenceable struct { -} - -func (r referenceable) referenceableSigil() { -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource.go deleted file mode 100644 index 103f8a28c3a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource.go +++ /dev/null @@ -1,254 +0,0 @@ -package addrs - -import ( - "fmt" - "strings" -) - -// Resource is an address for a resource block within configuration, which -// contains potentially-multiple resource instances if that configuration -// block uses "count" or "for_each". -type Resource struct { - referenceable - Mode ResourceMode - Type string - Name string -} - -func (r Resource) String() string { - switch r.Mode { - case ManagedResourceMode: - return fmt.Sprintf("%s.%s", r.Type, r.Name) - case DataResourceMode: - return fmt.Sprintf("data.%s.%s", r.Type, r.Name) - default: - // Should never happen, but we'll return a string here rather than - // crashing just in case it does. - return fmt.Sprintf(".%s.%s", r.Type, r.Name) - } -} - -// Instance produces the address for a specific instance of the receiver -// that is idenfied by the given key. -func (r Resource) Instance(key InstanceKey) ResourceInstance { - return ResourceInstance{ - Resource: r, - Key: key, - } -} - -// Absolute returns an AbsResource from the receiver and the given module -// instance address. -func (r Resource) Absolute(module ModuleInstance) AbsResource { - return AbsResource{ - Module: module, - Resource: r, - } -} - -// DefaultProviderConfig returns the address of the provider configuration -// that should be used for the resource identified by the reciever if it -// does not have a provider configuration address explicitly set in -// configuration. -// -// This method is not able to verify that such a configuration exists, nor -// represent the behavior of automatically inheriting certain provider -// configurations from parent modules. It just does a static analysis of the -// receiving address and returns an address to start from, relative to the -// same module that contains the resource. -func (r Resource) DefaultProviderConfig() ProviderConfig { - typeName := r.Type - if under := strings.Index(typeName, "_"); under != -1 { - typeName = typeName[:under] - } - return ProviderConfig{ - Type: typeName, - } -} - -// ResourceInstance is an address for a specific instance of a resource. -// When a resource is defined in configuration with "count" or "for_each" it -// produces zero or more instances, which can be addressed using this type. -type ResourceInstance struct { - referenceable - Resource Resource - Key InstanceKey -} - -func (r ResourceInstance) ContainingResource() Resource { - return r.Resource -} - -func (r ResourceInstance) String() string { - if r.Key == NoKey { - return r.Resource.String() - } - return r.Resource.String() + r.Key.String() -} - -// Absolute returns an AbsResourceInstance from the receiver and the given module -// instance address. -func (r ResourceInstance) Absolute(module ModuleInstance) AbsResourceInstance { - return AbsResourceInstance{ - Module: module, - Resource: r, - } -} - -// AbsResource is an absolute address for a resource under a given module path. -type AbsResource struct { - targetable - Module ModuleInstance - Resource Resource -} - -// Resource returns the address of a particular resource within the receiver. -func (m ModuleInstance) Resource(mode ResourceMode, typeName string, name string) AbsResource { - return AbsResource{ - Module: m, - Resource: Resource{ - Mode: mode, - Type: typeName, - Name: name, - }, - } -} - -// Instance produces the address for a specific instance of the receiver -// that is idenfied by the given key. -func (r AbsResource) Instance(key InstanceKey) AbsResourceInstance { - return AbsResourceInstance{ - Module: r.Module, - Resource: r.Resource.Instance(key), - } -} - -// TargetContains implements Targetable by returning true if the given other -// address is either equal to the receiver or is an instance of the -// receiver. -func (r AbsResource) TargetContains(other Targetable) bool { - switch to := other.(type) { - - case AbsResource: - // We'll use our stringification as a cheat-ish way to test for equality. - return to.String() == r.String() - - case AbsResourceInstance: - return r.TargetContains(to.ContainingResource()) - - default: - return false - - } -} - -func (r AbsResource) String() string { - if len(r.Module) == 0 { - return r.Resource.String() - } - return fmt.Sprintf("%s.%s", r.Module.String(), r.Resource.String()) -} - -// AbsResourceInstance is an absolute address for a resource instance under a -// given module path. -type AbsResourceInstance struct { - targetable - Module ModuleInstance - Resource ResourceInstance -} - -// ResourceInstance returns the address of a particular resource instance within the receiver. -func (m ModuleInstance) ResourceInstance(mode ResourceMode, typeName string, name string, key InstanceKey) AbsResourceInstance { - return AbsResourceInstance{ - Module: m, - Resource: ResourceInstance{ - Resource: Resource{ - Mode: mode, - Type: typeName, - Name: name, - }, - Key: key, - }, - } -} - -// ContainingResource returns the address of the resource that contains the -// receving resource instance. In other words, it discards the key portion -// of the address to produce an AbsResource value. -func (r AbsResourceInstance) ContainingResource() AbsResource { - return AbsResource{ - Module: r.Module, - Resource: r.Resource.ContainingResource(), - } -} - -// TargetContains implements Targetable by returning true if the given other -// address is equal to the receiver. -func (r AbsResourceInstance) TargetContains(other Targetable) bool { - switch to := other.(type) { - - case AbsResourceInstance: - // We'll use our stringification as a cheat-ish way to test for equality. - return to.String() == r.String() - - default: - return false - - } -} - -func (r AbsResourceInstance) String() string { - if len(r.Module) == 0 { - return r.Resource.String() - } - return fmt.Sprintf("%s.%s", r.Module.String(), r.Resource.String()) -} - -// Less returns true if the receiver should sort before the given other value -// in a sorted list of addresses. -func (r AbsResourceInstance) Less(o AbsResourceInstance) bool { - switch { - - case len(r.Module) != len(o.Module): - return len(r.Module) < len(o.Module) - - case r.Module.String() != o.Module.String(): - return r.Module.Less(o.Module) - - case r.Resource.Resource.Mode != o.Resource.Resource.Mode: - return r.Resource.Resource.Mode == DataResourceMode - - case r.Resource.Resource.Type != o.Resource.Resource.Type: - return r.Resource.Resource.Type < o.Resource.Resource.Type - - case r.Resource.Resource.Name != o.Resource.Resource.Name: - return r.Resource.Resource.Name < o.Resource.Resource.Name - - case r.Resource.Key != o.Resource.Key: - return InstanceKeyLess(r.Resource.Key, o.Resource.Key) - - default: - return false - - } -} - -// ResourceMode defines which lifecycle applies to a given resource. Each -// resource lifecycle has a slightly different address format. -type ResourceMode rune - -//go:generate go run golang.org/x/tools/cmd/stringer -type ResourceMode - -const ( - // InvalidResourceMode is the zero value of ResourceMode and is not - // a valid resource mode. - InvalidResourceMode ResourceMode = 0 - - // ManagedResourceMode indicates a managed resource, as defined by - // "resource" blocks in configuration. - ManagedResourceMode ResourceMode = 'M' - - // DataResourceMode indicates a data resource, as defined by - // "data" blocks in configuration. - DataResourceMode ResourceMode = 'D' -) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource_phase.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource_phase.go deleted file mode 100644 index 9bdbdc421a7..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource_phase.go +++ /dev/null @@ -1,105 +0,0 @@ -package addrs - -import "fmt" - -// ResourceInstancePhase is a special kind of reference used only internally -// during graph building to represent resource instances that are in a -// non-primary state. -// -// Graph nodes can declare themselves referenceable via an instance phase -// or can declare that they reference an instance phase in order to accomodate -// secondary graph nodes dealing with, for example, destroy actions. -// -// This special reference type cannot be accessed directly by end-users, and -// should never be shown in the UI. -type ResourceInstancePhase struct { - referenceable - ResourceInstance ResourceInstance - Phase ResourceInstancePhaseType -} - -var _ Referenceable = ResourceInstancePhase{} - -// Phase returns a special "phase address" for the receving instance. See the -// documentation of ResourceInstancePhase for the limited situations where this -// is intended to be used. -func (r ResourceInstance) Phase(rpt ResourceInstancePhaseType) ResourceInstancePhase { - return ResourceInstancePhase{ - ResourceInstance: r, - Phase: rpt, - } -} - -// ContainingResource returns an address for the same phase of the resource -// that this instance belongs to. -func (rp ResourceInstancePhase) ContainingResource() ResourcePhase { - return rp.ResourceInstance.Resource.Phase(rp.Phase) -} - -func (rp ResourceInstancePhase) String() string { - // We use a different separator here than usual to ensure that we'll - // never conflict with any non-phased resource instance string. This - // is intentionally something that would fail parsing with ParseRef, - // because this special address type should never be exposed in the UI. - return fmt.Sprintf("%s#%s", rp.ResourceInstance, rp.Phase) -} - -// ResourceInstancePhaseType is an enumeration used with ResourceInstancePhase. -type ResourceInstancePhaseType string - -const ( - // ResourceInstancePhaseDestroy represents the "destroy" phase of a - // resource instance. - ResourceInstancePhaseDestroy ResourceInstancePhaseType = "destroy" - - // ResourceInstancePhaseDestroyCBD is similar to ResourceInstancePhaseDestroy - // but is used for resources that have "create_before_destroy" set, thus - // requiring a different dependency ordering. - ResourceInstancePhaseDestroyCBD ResourceInstancePhaseType = "destroy-cbd" -) - -func (rpt ResourceInstancePhaseType) String() string { - return string(rpt) -} - -// ResourcePhase is a special kind of reference used only internally -// during graph building to represent resources that are in a -// non-primary state. -// -// Graph nodes can declare themselves referenceable via a resource phase -// or can declare that they reference a resource phase in order to accomodate -// secondary graph nodes dealing with, for example, destroy actions. -// -// Since resources (as opposed to instances) aren't actually phased, this -// address type is used only as an approximation during initial construction -// of the resource-oriented plan graph, under the assumption that resource -// instances with ResourceInstancePhase addresses will be created in dynamic -// subgraphs during the graph walk. -// -// This special reference type cannot be accessed directly by end-users, and -// should never be shown in the UI. -type ResourcePhase struct { - referenceable - Resource Resource - Phase ResourceInstancePhaseType -} - -var _ Referenceable = ResourcePhase{} - -// Phase returns a special "phase address" for the receving instance. See the -// documentation of ResourceInstancePhase for the limited situations where this -// is intended to be used. -func (r Resource) Phase(rpt ResourceInstancePhaseType) ResourcePhase { - return ResourcePhase{ - Resource: r, - Phase: rpt, - } -} - -func (rp ResourcePhase) String() string { - // We use a different separator here than usual to ensure that we'll - // never conflict with any non-phased resource instance string. This - // is intentionally something that would fail parsing with ParseRef, - // because this special address type should never be exposed in the UI. - return fmt.Sprintf("%s#%s", rp.Resource, rp.Phase) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resourcemode_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resourcemode_string.go deleted file mode 100644 index 0b5c33f8ee2..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resourcemode_string.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by "stringer -type ResourceMode"; DO NOT EDIT. - -package addrs - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[InvalidResourceMode-0] - _ = x[ManagedResourceMode-77] - _ = x[DataResourceMode-68] -} - -const ( - _ResourceMode_name_0 = "InvalidResourceMode" - _ResourceMode_name_1 = "DataResourceMode" - _ResourceMode_name_2 = "ManagedResourceMode" -) - -func (i ResourceMode) String() string { - switch { - case i == 0: - return _ResourceMode_name_0 - case i == 68: - return _ResourceMode_name_1 - case i == 77: - return _ResourceMode_name_2 - default: - return "ResourceMode(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/self.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/self.go deleted file mode 100644 index 7f24eaf085b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/self.go +++ /dev/null @@ -1,14 +0,0 @@ -package addrs - -// Self is the address of the special object "self" that behaves as an alias -// for a containing object currently in scope. -const Self selfT = 0 - -type selfT int - -func (s selfT) referenceableSigil() { -} - -func (s selfT) String() string { - return "self" -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/targetable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/targetable.go deleted file mode 100644 index 16819a5afbb..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/targetable.go +++ /dev/null @@ -1,26 +0,0 @@ -package addrs - -// Targetable is an interface implemented by all address types that can be -// used as "targets" for selecting sub-graphs of a graph. -type Targetable interface { - targetableSigil() - - // TargetContains returns true if the receiver is considered to contain - // the given other address. Containment, for the purpose of targeting, - // means that if a container address is targeted then all of the - // addresses within it are also implicitly targeted. - // - // A targetable address always contains at least itself. - TargetContains(other Targetable) bool - - // String produces a string representation of the address that could be - // parsed as a HCL traversal and passed to ParseTarget to produce an - // identical result. - String() string -} - -type targetable struct { -} - -func (r targetable) targetableSigil() { -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/terraform_attr.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/terraform_attr.go deleted file mode 100644 index a880182ae2a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/terraform_attr.go +++ /dev/null @@ -1,12 +0,0 @@ -package addrs - -// TerraformAttr is the address of an attribute of the "terraform" object in -// the interpolation scope, like "terraform.workspace". -type TerraformAttr struct { - referenceable - Name string -} - -func (ta TerraformAttr) String() string { - return "terraform." + ta.Name -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diagnostic.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diagnostic.go deleted file mode 100644 index c054acf0acd..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diagnostic.go +++ /dev/null @@ -1,295 +0,0 @@ -package format - -import ( - "bufio" - "bytes" - "fmt" - "sort" - "strings" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hcled" - "github.com/hashicorp/hcl/v2/hclparse" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/mitchellh/colorstring" - wordwrap "github.com/mitchellh/go-wordwrap" - "github.com/zclconf/go-cty/cty" -) - -// Diagnostic formats a single diagnostic message. -// -// The width argument specifies at what column the diagnostic messages will -// be wrapped. If set to zero, messages will not be wrapped by this function -// at all. Although the long-form text parts of the message are wrapped, -// not all aspects of the message are guaranteed to fit within the specified -// terminal width. -func Diagnostic(diag tfdiags.Diagnostic, sources map[string][]byte, color *colorstring.Colorize, width int) string { - if diag == nil { - // No good reason to pass a nil diagnostic in here... - return "" - } - - var buf bytes.Buffer - - switch diag.Severity() { - case tfdiags.Error: - buf.WriteString(color.Color("\n[bold][red]Error: [reset]")) - case tfdiags.Warning: - buf.WriteString(color.Color("\n[bold][yellow]Warning: [reset]")) - default: - // Clear out any coloring that might be applied by Terraform's UI helper, - // so our result is not context-sensitive. - buf.WriteString(color.Color("\n[reset]")) - } - - desc := diag.Description() - sourceRefs := diag.Source() - - // We don't wrap the summary, since we expect it to be terse, and since - // this is where we put the text of a native Go error it may not always - // be pure text that lends itself well to word-wrapping. - fmt.Fprintf(&buf, color.Color("[bold]%s[reset]\n\n"), desc.Summary) - - if sourceRefs.Subject != nil { - // We'll borrow HCL's range implementation here, because it has some - // handy features to help us produce a nice source code snippet. - highlightRange := sourceRefs.Subject.ToHCL() - snippetRange := highlightRange - if sourceRefs.Context != nil { - snippetRange = sourceRefs.Context.ToHCL() - } - - // Make sure the snippet includes the highlight. This should be true - // for any reasonable diagnostic, but we'll make sure. - snippetRange = hcl.RangeOver(snippetRange, highlightRange) - if snippetRange.Empty() { - snippetRange.End.Byte++ - snippetRange.End.Column++ - } - if highlightRange.Empty() { - highlightRange.End.Byte++ - highlightRange.End.Column++ - } - - var src []byte - if sources != nil { - src = sources[snippetRange.Filename] - } - if src == nil { - // This should generally not happen, as long as sources are always - // loaded through the main loader. We may load things in other - // ways in weird cases, so we'll tolerate it at the expense of - // a not-so-helpful error message. - fmt.Fprintf(&buf, " on %s line %d:\n (source code not available)\n", highlightRange.Filename, highlightRange.Start.Line) - } else { - file, offset := parseRange(src, highlightRange) - - headerRange := highlightRange - - contextStr := hcled.ContextString(file, offset-1) - if contextStr != "" { - contextStr = ", in " + contextStr - } - - fmt.Fprintf(&buf, " on %s line %d%s:\n", headerRange.Filename, headerRange.Start.Line, contextStr) - - // Config snippet rendering - sc := hcl.NewRangeScanner(src, highlightRange.Filename, bufio.ScanLines) - for sc.Scan() { - lineRange := sc.Range() - if !lineRange.Overlaps(snippetRange) { - continue - } - beforeRange, highlightedRange, afterRange := lineRange.PartitionAround(highlightRange) - before := beforeRange.SliceBytes(src) - highlighted := highlightedRange.SliceBytes(src) - after := afterRange.SliceBytes(src) - fmt.Fprintf( - &buf, color.Color("%4d: %s[underline]%s[reset]%s\n"), - lineRange.Start.Line, - before, highlighted, after, - ) - } - - } - - if fromExpr := diag.FromExpr(); fromExpr != nil { - // We may also be able to generate information about the dynamic - // values of relevant variables at the point of evaluation, then. - // This is particularly useful for expressions that get evaluated - // multiple times with different values, such as blocks using - // "count" and "for_each", or within "for" expressions. - expr := fromExpr.Expression - ctx := fromExpr.EvalContext - vars := expr.Variables() - stmts := make([]string, 0, len(vars)) - seen := make(map[string]struct{}, len(vars)) - Traversals: - for _, traversal := range vars { - for len(traversal) > 1 { - val, diags := traversal.TraverseAbs(ctx) - if diags.HasErrors() { - // Skip anything that generates errors, since we probably - // already have the same error in our diagnostics set - // already. - traversal = traversal[:len(traversal)-1] - continue - } - - traversalStr := traversalStr(traversal) - if _, exists := seen[traversalStr]; exists { - continue Traversals // don't show duplicates when the same variable is referenced multiple times - } - switch { - case !val.IsKnown(): - // Can't say anything about this yet, then. - continue Traversals - case val.IsNull(): - stmts = append(stmts, fmt.Sprintf(color.Color("[bold]%s[reset] is null"), traversalStr)) - default: - stmts = append(stmts, fmt.Sprintf(color.Color("[bold]%s[reset] is %s"), traversalStr, compactValueStr(val))) - } - seen[traversalStr] = struct{}{} - } - } - - sort.Strings(stmts) // FIXME: Should maybe use a traversal-aware sort that can sort numeric indexes properly? - - if len(stmts) > 0 { - fmt.Fprint(&buf, color.Color(" [dark_gray]|----------------[reset]\n")) - } - for _, stmt := range stmts { - fmt.Fprintf(&buf, color.Color(" [dark_gray]|[reset] %s\n"), stmt) - } - } - - buf.WriteByte('\n') - } - - if desc.Detail != "" { - detail := desc.Detail - if width != 0 { - detail = wordwrap.WrapString(detail, uint(width)) - } - fmt.Fprintf(&buf, "%s\n", detail) - } - - return buf.String() -} - -func parseRange(src []byte, rng hcl.Range) (*hcl.File, int) { - filename := rng.Filename - offset := rng.Start.Byte - - // We need to re-parse here to get a *hcl.File we can interrogate. This - // is not awesome since we presumably already parsed the file earlier too, - // but this re-parsing is architecturally simpler than retaining all of - // the hcl.File objects and we only do this in the case of an error anyway - // so the overhead here is not a big problem. - parser := hclparse.NewParser() - var file *hcl.File - var diags hcl.Diagnostics - if strings.HasSuffix(filename, ".json") { - file, diags = parser.ParseJSON(src, filename) - } else { - file, diags = parser.ParseHCL(src, filename) - } - if diags.HasErrors() { - return file, offset - } - - return file, offset -} - -// traversalStr produces a representation of an HCL traversal that is compact, -// resembles HCL native syntax, and is suitable for display in the UI. -func traversalStr(traversal hcl.Traversal) string { - // This is a specialized subset of traversal rendering tailored to - // producing helpful contextual messages in diagnostics. It is not - // comprehensive nor intended to be used for other purposes. - - var buf bytes.Buffer - for _, step := range traversal { - switch tStep := step.(type) { - case hcl.TraverseRoot: - buf.WriteString(tStep.Name) - case hcl.TraverseAttr: - buf.WriteByte('.') - buf.WriteString(tStep.Name) - case hcl.TraverseIndex: - buf.WriteByte('[') - if keyTy := tStep.Key.Type(); keyTy.IsPrimitiveType() { - buf.WriteString(compactValueStr(tStep.Key)) - } else { - // We'll just use a placeholder for more complex values, - // since otherwise our result could grow ridiculously long. - buf.WriteString("...") - } - buf.WriteByte(']') - } - } - return buf.String() -} - -// compactValueStr produces a compact, single-line summary of a given value -// that is suitable for display in the UI. -// -// For primitives it returns a full representation, while for more complex -// types it instead summarizes the type, size, etc to produce something -// that is hopefully still somewhat useful but not as verbose as a rendering -// of the entire data structure. -func compactValueStr(val cty.Value) string { - // This is a specialized subset of value rendering tailored to producing - // helpful but concise messages in diagnostics. It is not comprehensive - // nor intended to be used for other purposes. - - ty := val.Type() - switch { - case val.IsNull(): - return "null" - case !val.IsKnown(): - // Should never happen here because we should filter before we get - // in here, but we'll do something reasonable rather than panic. - return "(not yet known)" - case ty == cty.Bool: - if val.True() { - return "true" - } - return "false" - case ty == cty.Number: - bf := val.AsBigFloat() - return bf.Text('g', 10) - case ty == cty.String: - // Go string syntax is not exactly the same as HCL native string syntax, - // but we'll accept the minor edge-cases where this is different here - // for now, just to get something reasonable here. - return fmt.Sprintf("%q", val.AsString()) - case ty.IsCollectionType() || ty.IsTupleType(): - l := val.LengthInt() - switch l { - case 0: - return "empty " + ty.FriendlyName() - case 1: - return ty.FriendlyName() + " with 1 element" - default: - return fmt.Sprintf("%s with %d elements", ty.FriendlyName(), l) - } - case ty.IsObjectType(): - atys := ty.AttributeTypes() - l := len(atys) - switch l { - case 0: - return "object with no attributes" - case 1: - var name string - for k := range atys { - name = k - } - return fmt.Sprintf("object with 1 attribute %q", name) - default: - return fmt.Sprintf("object with %d attributes", l) - } - default: - return ty.FriendlyName() - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diff.go deleted file mode 100644 index 0a2aa7d02e6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diff.go +++ /dev/null @@ -1,1192 +0,0 @@ -package format - -import ( - "bufio" - "bytes" - "fmt" - "sort" - "strings" - - "github.com/mitchellh/colorstring" - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// ResourceChange returns a string representation of a change to a particular -// resource, for inclusion in user-facing plan output. -// -// The resource schema must be provided along with the change so that the -// formatted change can reflect the configuration structure for the associated -// resource. -// -// If "color" is non-nil, it will be used to color the result. Otherwise, -// no color codes will be included. -func ResourceChange( - change *plans.ResourceInstanceChangeSrc, - tainted bool, - schema *configschema.Block, - color *colorstring.Colorize, -) string { - addr := change.Addr - var buf bytes.Buffer - - if color == nil { - color = &colorstring.Colorize{ - Colors: colorstring.DefaultColors, - Disable: true, - Reset: false, - } - } - - dispAddr := addr.String() - if change.DeposedKey != states.NotDeposed { - dispAddr = fmt.Sprintf("%s (deposed object %s)", dispAddr, change.DeposedKey) - } - - switch change.Action { - case plans.Create: - buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be created", dispAddr))) - case plans.Read: - buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be read during apply\n # (config refers to values not yet known)", dispAddr))) - case plans.Update: - buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be updated in-place", dispAddr))) - case plans.CreateThenDelete, plans.DeleteThenCreate: - if tainted { - buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] is tainted, so must be [bold][red]replaced", dispAddr))) - } else { - buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] must be [bold][red]replaced", dispAddr))) - } - case plans.Delete: - buf.WriteString(color.Color(fmt.Sprintf("[bold] # %s[reset] will be [bold][red]destroyed", dispAddr))) - default: - // should never happen, since the above is exhaustive - buf.WriteString(fmt.Sprintf("%s has an action the plan renderer doesn't support (this is a bug)", dispAddr)) - } - buf.WriteString(color.Color("[reset]\n")) - - switch change.Action { - case plans.Create: - buf.WriteString(color.Color("[green] +[reset] ")) - case plans.Read: - buf.WriteString(color.Color("[cyan] <=[reset] ")) - case plans.Update: - buf.WriteString(color.Color("[yellow] ~[reset] ")) - case plans.DeleteThenCreate: - buf.WriteString(color.Color("[red]-[reset]/[green]+[reset] ")) - case plans.CreateThenDelete: - buf.WriteString(color.Color("[green]+[reset]/[red]-[reset] ")) - case plans.Delete: - buf.WriteString(color.Color("[red] -[reset] ")) - default: - buf.WriteString(color.Color("??? ")) - } - - switch addr.Resource.Resource.Mode { - case addrs.ManagedResourceMode: - buf.WriteString(fmt.Sprintf( - "resource %q %q", - addr.Resource.Resource.Type, - addr.Resource.Resource.Name, - )) - case addrs.DataResourceMode: - buf.WriteString(fmt.Sprintf( - "data %q %q ", - addr.Resource.Resource.Type, - addr.Resource.Resource.Name, - )) - default: - // should never happen, since the above is exhaustive - buf.WriteString(addr.String()) - } - - buf.WriteString(" {") - - p := blockBodyDiffPrinter{ - buf: &buf, - color: color, - action: change.Action, - requiredReplace: change.RequiredReplace, - } - - // Most commonly-used resources have nested blocks that result in us - // going at least three traversals deep while we recurse here, so we'll - // start with that much capacity and then grow as needed for deeper - // structures. - path := make(cty.Path, 0, 3) - - changeV, err := change.Decode(schema.ImpliedType()) - if err != nil { - // Should never happen in here, since we've already been through - // loads of layers of encode/decode of the planned changes before now. - panic(fmt.Sprintf("failed to decode plan for %s while rendering diff: %s", addr, err)) - } - - // We currently have an opt-out that permits the legacy SDK to return values - // that defy our usual conventions around handling of nesting blocks. To - // avoid the rendering code from needing to handle all of these, we'll - // normalize first. - // (Ideally we'd do this as part of the SDK opt-out implementation in core, - // but we've added it here for now to reduce risk of unexpected impacts - // on other code in core.) - changeV.Change.Before = objchange.NormalizeObjectFromLegacySDK(changeV.Change.Before, schema) - changeV.Change.After = objchange.NormalizeObjectFromLegacySDK(changeV.Change.After, schema) - - bodyWritten := p.writeBlockBodyDiff(schema, changeV.Before, changeV.After, 6, path) - if bodyWritten { - buf.WriteString("\n") - buf.WriteString(strings.Repeat(" ", 4)) - } - buf.WriteString("}\n") - - return buf.String() -} - -type blockBodyDiffPrinter struct { - buf *bytes.Buffer - color *colorstring.Colorize - action plans.Action - requiredReplace cty.PathSet -} - -const forcesNewResourceCaption = " [red]# forces replacement[reset]" - -// writeBlockBodyDiff writes attribute or block differences -// and returns true if any differences were found and written -func (p *blockBodyDiffPrinter) writeBlockBodyDiff(schema *configschema.Block, old, new cty.Value, indent int, path cty.Path) bool { - path = ctyEnsurePathCapacity(path, 1) - - bodyWritten := false - blankBeforeBlocks := false - { - attrNames := make([]string, 0, len(schema.Attributes)) - attrNameLen := 0 - for name := range schema.Attributes { - oldVal := ctyGetAttrMaybeNull(old, name) - newVal := ctyGetAttrMaybeNull(new, name) - if oldVal.IsNull() && newVal.IsNull() { - // Skip attributes where both old and new values are null - // (we do this early here so that we'll do our value alignment - // based on the longest attribute name that has a change, rather - // than the longest attribute name in the full set.) - continue - } - - attrNames = append(attrNames, name) - if len(name) > attrNameLen { - attrNameLen = len(name) - } - } - sort.Strings(attrNames) - if len(attrNames) > 0 { - blankBeforeBlocks = true - } - - for _, name := range attrNames { - attrS := schema.Attributes[name] - oldVal := ctyGetAttrMaybeNull(old, name) - newVal := ctyGetAttrMaybeNull(new, name) - - bodyWritten = true - p.writeAttrDiff(name, attrS, oldVal, newVal, attrNameLen, indent, path) - } - } - - { - blockTypeNames := make([]string, 0, len(schema.BlockTypes)) - for name := range schema.BlockTypes { - blockTypeNames = append(blockTypeNames, name) - } - sort.Strings(blockTypeNames) - - for _, name := range blockTypeNames { - blockS := schema.BlockTypes[name] - oldVal := ctyGetAttrMaybeNull(old, name) - newVal := ctyGetAttrMaybeNull(new, name) - - bodyWritten = true - p.writeNestedBlockDiffs(name, blockS, oldVal, newVal, blankBeforeBlocks, indent, path) - - // Always include a blank for any subsequent block types. - blankBeforeBlocks = true - } - } - - return bodyWritten -} - -func (p *blockBodyDiffPrinter) writeAttrDiff(name string, attrS *configschema.Attribute, old, new cty.Value, nameLen, indent int, path cty.Path) { - path = append(path, cty.GetAttrStep{Name: name}) - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent)) - showJustNew := false - var action plans.Action - switch { - case old.IsNull(): - action = plans.Create - showJustNew = true - case new.IsNull(): - action = plans.Delete - case ctyEqualWithUnknown(old, new): - action = plans.NoOp - showJustNew = true - default: - action = plans.Update - } - - p.writeActionSymbol(action) - - p.buf.WriteString(p.color.Color("[bold]")) - p.buf.WriteString(name) - p.buf.WriteString(p.color.Color("[reset]")) - p.buf.WriteString(strings.Repeat(" ", nameLen-len(name))) - p.buf.WriteString(" = ") - - if attrS.Sensitive { - p.buf.WriteString("(sensitive value)") - } else { - switch { - case showJustNew: - p.writeValue(new, action, indent+2) - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - default: - // We show new even if it is null to emphasize the fact - // that it is being unset, since otherwise it is easy to - // misunderstand that the value is still set to the old value. - p.writeValueDiff(old, new, indent+2, path) - } - } -} - -func (p *blockBodyDiffPrinter) writeNestedBlockDiffs(name string, blockS *configschema.NestedBlock, old, new cty.Value, blankBefore bool, indent int, path cty.Path) { - path = append(path, cty.GetAttrStep{Name: name}) - if old.IsNull() && new.IsNull() { - // Nothing to do if both old and new is null - return - } - - // Where old/new are collections representing a nesting mode other than - // NestingSingle, we assume the collection value can never be unknown - // since we always produce the container for the nested objects, even if - // the objects within are computed. - - switch blockS.Nesting { - case configschema.NestingSingle, configschema.NestingGroup: - var action plans.Action - eqV := new.Equals(old) - switch { - case old.IsNull(): - action = plans.Create - case new.IsNull(): - action = plans.Delete - case !new.IsWhollyKnown() || !old.IsWhollyKnown(): - // "old" should actually always be known due to our contract - // that old values must never be unknown, but we'll allow it - // anyway to be robust. - action = plans.Update - case !eqV.IsKnown() || !eqV.True(): - action = plans.Update - } - - if blankBefore { - p.buf.WriteRune('\n') - } - p.writeNestedBlockDiff(name, nil, &blockS.Block, action, old, new, indent, path) - case configschema.NestingList: - // For the sake of handling nested blocks, we'll treat a null list - // the same as an empty list since the config language doesn't - // distinguish these anyway. - old = ctyNullBlockListAsEmpty(old) - new = ctyNullBlockListAsEmpty(new) - - oldItems := ctyCollectionValues(old) - newItems := ctyCollectionValues(new) - - // Here we intentionally preserve the index-based correspondance - // between old and new, rather than trying to detect insertions - // and removals in the list, because this more accurately reflects - // how Terraform Core and providers will understand the change, - // particularly when the nested block contains computed attributes - // that will themselves maintain correspondance by index. - - // commonLen is number of elements that exist in both lists, which - // will be presented as updates (~). Any additional items in one - // of the lists will be presented as either creates (+) or deletes (-) - // depending on which list they belong to. - var commonLen int - switch { - case len(oldItems) < len(newItems): - commonLen = len(oldItems) - default: - commonLen = len(newItems) - } - - if blankBefore && (len(oldItems) > 0 || len(newItems) > 0) { - p.buf.WriteRune('\n') - } - - for i := 0; i < commonLen; i++ { - path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))}) - oldItem := oldItems[i] - newItem := newItems[i] - action := plans.Update - if oldItem.RawEquals(newItem) { - action = plans.NoOp - } - p.writeNestedBlockDiff(name, nil, &blockS.Block, action, oldItem, newItem, indent, path) - } - for i := commonLen; i < len(oldItems); i++ { - path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))}) - oldItem := oldItems[i] - newItem := cty.NullVal(oldItem.Type()) - p.writeNestedBlockDiff(name, nil, &blockS.Block, plans.Delete, oldItem, newItem, indent, path) - } - for i := commonLen; i < len(newItems); i++ { - path := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))}) - newItem := newItems[i] - oldItem := cty.NullVal(newItem.Type()) - p.writeNestedBlockDiff(name, nil, &blockS.Block, plans.Create, oldItem, newItem, indent, path) - } - case configschema.NestingSet: - // For the sake of handling nested blocks, we'll treat a null set - // the same as an empty set since the config language doesn't - // distinguish these anyway. - old = ctyNullBlockSetAsEmpty(old) - new = ctyNullBlockSetAsEmpty(new) - - oldItems := ctyCollectionValues(old) - newItems := ctyCollectionValues(new) - - if (len(oldItems) + len(newItems)) == 0 { - // Nothing to do if both sets are empty - return - } - - allItems := make([]cty.Value, 0, len(oldItems)+len(newItems)) - allItems = append(allItems, oldItems...) - allItems = append(allItems, newItems...) - all := cty.SetVal(allItems) - - if blankBefore { - p.buf.WriteRune('\n') - } - - for it := all.ElementIterator(); it.Next(); { - _, val := it.Element() - var action plans.Action - var oldValue, newValue cty.Value - switch { - case !val.IsKnown(): - action = plans.Update - newValue = val - case !old.HasElement(val).True(): - action = plans.Create - oldValue = cty.NullVal(val.Type()) - newValue = val - case !new.HasElement(val).True(): - action = plans.Delete - oldValue = val - newValue = cty.NullVal(val.Type()) - default: - action = plans.NoOp - oldValue = val - newValue = val - } - path := append(path, cty.IndexStep{Key: val}) - p.writeNestedBlockDiff(name, nil, &blockS.Block, action, oldValue, newValue, indent, path) - } - - case configschema.NestingMap: - // For the sake of handling nested blocks, we'll treat a null map - // the same as an empty map since the config language doesn't - // distinguish these anyway. - old = ctyNullBlockMapAsEmpty(old) - new = ctyNullBlockMapAsEmpty(new) - - oldItems := old.AsValueMap() - newItems := new.AsValueMap() - if (len(oldItems) + len(newItems)) == 0 { - // Nothing to do if both maps are empty - return - } - - allKeys := make(map[string]bool) - for k := range oldItems { - allKeys[k] = true - } - for k := range newItems { - allKeys[k] = true - } - allKeysOrder := make([]string, 0, len(allKeys)) - for k := range allKeys { - allKeysOrder = append(allKeysOrder, k) - } - sort.Strings(allKeysOrder) - - if blankBefore { - p.buf.WriteRune('\n') - } - - for _, k := range allKeysOrder { - var action plans.Action - oldValue := oldItems[k] - newValue := newItems[k] - switch { - case oldValue == cty.NilVal: - oldValue = cty.NullVal(newValue.Type()) - action = plans.Create - case newValue == cty.NilVal: - newValue = cty.NullVal(oldValue.Type()) - action = plans.Delete - case !newValue.RawEquals(oldValue): - action = plans.Update - default: - action = plans.NoOp - } - - path := append(path, cty.IndexStep{Key: cty.StringVal(k)}) - p.writeNestedBlockDiff(name, &k, &blockS.Block, action, oldValue, newValue, indent, path) - } - } -} - -func (p *blockBodyDiffPrinter) writeNestedBlockDiff(name string, label *string, blockS *configschema.Block, action plans.Action, old, new cty.Value, indent int, path cty.Path) { - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent)) - p.writeActionSymbol(action) - - if label != nil { - fmt.Fprintf(p.buf, "%s %q {", name, *label) - } else { - fmt.Fprintf(p.buf, "%s {", name) - } - - if action != plans.NoOp && (p.pathForcesNewResource(path) || p.pathForcesNewResource(path[:len(path)-1])) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - - bodyWritten := p.writeBlockBodyDiff(blockS, old, new, indent+4, path) - if bodyWritten { - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent+2)) - } - p.buf.WriteString("}") -} - -func (p *blockBodyDiffPrinter) writeValue(val cty.Value, action plans.Action, indent int) { - if !val.IsKnown() { - p.buf.WriteString("(known after apply)") - return - } - if val.IsNull() { - p.buf.WriteString(p.color.Color("[dark_gray]null[reset]")) - return - } - - ty := val.Type() - - switch { - case ty.IsPrimitiveType(): - switch ty { - case cty.String: - { - // Special behavior for JSON strings containing array or object - src := []byte(val.AsString()) - ty, err := ctyjson.ImpliedType(src) - // check for the special case of "null", which decodes to nil, - // and just allow it to be printed out directly - if err == nil && !ty.IsPrimitiveType() && val.AsString() != "null" { - jv, err := ctyjson.Unmarshal(src, ty) - if err == nil { - p.buf.WriteString("jsonencode(") - if jv.LengthInt() == 0 { - p.writeValue(jv, action, 0) - } else { - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent+4)) - p.writeValue(jv, action, indent+4) - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent)) - } - p.buf.WriteByte(')') - break // don't *also* do the normal behavior below - } - } - } - fmt.Fprintf(p.buf, "%q", val.AsString()) - case cty.Bool: - if val.True() { - p.buf.WriteString("true") - } else { - p.buf.WriteString("false") - } - case cty.Number: - bf := val.AsBigFloat() - p.buf.WriteString(bf.Text('f', -1)) - default: - // should never happen, since the above is exhaustive - fmt.Fprintf(p.buf, "%#v", val) - } - case ty.IsListType() || ty.IsSetType() || ty.IsTupleType(): - p.buf.WriteString("[") - - it := val.ElementIterator() - for it.Next() { - _, val := it.Element() - - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(action) - p.writeValue(val, action, indent+4) - p.buf.WriteString(",") - } - - if val.LengthInt() > 0 { - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent)) - } - p.buf.WriteString("]") - case ty.IsMapType(): - p.buf.WriteString("{") - - keyLen := 0 - for it := val.ElementIterator(); it.Next(); { - key, _ := it.Element() - if keyStr := key.AsString(); len(keyStr) > keyLen { - keyLen = len(keyStr) - } - } - - for it := val.ElementIterator(); it.Next(); { - key, val := it.Element() - - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(action) - p.writeValue(key, action, indent+4) - p.buf.WriteString(strings.Repeat(" ", keyLen-len(key.AsString()))) - p.buf.WriteString(" = ") - p.writeValue(val, action, indent+4) - } - - if val.LengthInt() > 0 { - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent)) - } - p.buf.WriteString("}") - case ty.IsObjectType(): - p.buf.WriteString("{") - - atys := ty.AttributeTypes() - attrNames := make([]string, 0, len(atys)) - nameLen := 0 - for attrName := range atys { - attrNames = append(attrNames, attrName) - if len(attrName) > nameLen { - nameLen = len(attrName) - } - } - sort.Strings(attrNames) - - for _, attrName := range attrNames { - val := val.GetAttr(attrName) - - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(action) - p.buf.WriteString(attrName) - p.buf.WriteString(strings.Repeat(" ", nameLen-len(attrName))) - p.buf.WriteString(" = ") - p.writeValue(val, action, indent+4) - } - - if len(attrNames) > 0 { - p.buf.WriteString("\n") - p.buf.WriteString(strings.Repeat(" ", indent)) - } - p.buf.WriteString("}") - } -} - -func (p *blockBodyDiffPrinter) writeValueDiff(old, new cty.Value, indent int, path cty.Path) { - ty := old.Type() - typesEqual := ctyTypesEqual(ty, new.Type()) - - // We have some specialized diff implementations for certain complex - // values where it's useful to see a visualization of the diff of - // the nested elements rather than just showing the entire old and - // new values verbatim. - // However, these specialized implementations can apply only if both - // values are known and non-null. - if old.IsKnown() && new.IsKnown() && !old.IsNull() && !new.IsNull() && typesEqual { - switch { - case ty == cty.String: - // We have special behavior for both multi-line strings in general - // and for strings that can parse as JSON. For the JSON handling - // to apply, both old and new must be valid JSON. - // For single-line strings that don't parse as JSON we just fall - // out of this switch block and do the default old -> new rendering. - oldS := old.AsString() - newS := new.AsString() - - { - // Special behavior for JSON strings containing object or - // list values. - oldBytes := []byte(oldS) - newBytes := []byte(newS) - oldType, oldErr := ctyjson.ImpliedType(oldBytes) - newType, newErr := ctyjson.ImpliedType(newBytes) - if oldErr == nil && newErr == nil && !(oldType.IsPrimitiveType() && newType.IsPrimitiveType()) { - oldJV, oldErr := ctyjson.Unmarshal(oldBytes, oldType) - newJV, newErr := ctyjson.Unmarshal(newBytes, newType) - if oldErr == nil && newErr == nil { - if !oldJV.RawEquals(newJV) { // two JSON values may differ only in insignificant whitespace - p.buf.WriteString("jsonencode(") - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(plans.Update) - p.writeValueDiff(oldJV, newJV, indent+4, path) - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteByte(')') - } else { - // if they differ only in insigificant whitespace - // then we'll note that but still expand out the - // effective value. - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color("jsonencode( [red]# whitespace changes force replacement[reset]")) - } else { - p.buf.WriteString(p.color.Color("jsonencode( [dim]# whitespace changes[reset]")) - } - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent+4)) - p.writeValue(oldJV, plans.NoOp, indent+4) - p.buf.WriteByte('\n') - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteByte(')') - } - return - } - } - } - - if strings.Index(oldS, "\n") < 0 && strings.Index(newS, "\n") < 0 { - break - } - - p.buf.WriteString("<<~EOT") - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - p.buf.WriteString("\n") - - var oldLines, newLines []cty.Value - { - r := strings.NewReader(oldS) - sc := bufio.NewScanner(r) - for sc.Scan() { - oldLines = append(oldLines, cty.StringVal(sc.Text())) - } - } - { - r := strings.NewReader(newS) - sc := bufio.NewScanner(r) - for sc.Scan() { - newLines = append(newLines, cty.StringVal(sc.Text())) - } - } - - diffLines := ctySequenceDiff(oldLines, newLines) - for _, diffLine := range diffLines { - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(diffLine.Action) - - switch diffLine.Action { - case plans.NoOp, plans.Delete: - p.buf.WriteString(diffLine.Before.AsString()) - case plans.Create: - p.buf.WriteString(diffLine.After.AsString()) - default: - // Should never happen since the above covers all - // actions that ctySequenceDiff can return for strings - p.buf.WriteString(diffLine.After.AsString()) - - } - p.buf.WriteString("\n") - } - - p.buf.WriteString(strings.Repeat(" ", indent)) // +4 here because there's no symbol - p.buf.WriteString("EOT") - - return - - case ty.IsSetType(): - p.buf.WriteString("[") - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - p.buf.WriteString("\n") - - var addedVals, removedVals, allVals []cty.Value - for it := old.ElementIterator(); it.Next(); { - _, val := it.Element() - allVals = append(allVals, val) - if new.HasElement(val).False() { - removedVals = append(removedVals, val) - } - } - for it := new.ElementIterator(); it.Next(); { - _, val := it.Element() - allVals = append(allVals, val) - if val.IsKnown() && old.HasElement(val).False() { - addedVals = append(addedVals, val) - } - } - - var all, added, removed cty.Value - if len(allVals) > 0 { - all = cty.SetVal(allVals) - } else { - all = cty.SetValEmpty(ty.ElementType()) - } - if len(addedVals) > 0 { - added = cty.SetVal(addedVals) - } else { - added = cty.SetValEmpty(ty.ElementType()) - } - if len(removedVals) > 0 { - removed = cty.SetVal(removedVals) - } else { - removed = cty.SetValEmpty(ty.ElementType()) - } - - for it := all.ElementIterator(); it.Next(); { - _, val := it.Element() - - p.buf.WriteString(strings.Repeat(" ", indent+2)) - - var action plans.Action - switch { - case !val.IsKnown(): - action = plans.Update - case added.HasElement(val).True(): - action = plans.Create - case removed.HasElement(val).True(): - action = plans.Delete - default: - action = plans.NoOp - } - - p.writeActionSymbol(action) - p.writeValue(val, action, indent+4) - p.buf.WriteString(",\n") - } - - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteString("]") - return - case ty.IsListType() || ty.IsTupleType(): - p.buf.WriteString("[") - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - p.buf.WriteString("\n") - - elemDiffs := ctySequenceDiff(old.AsValueSlice(), new.AsValueSlice()) - for _, elemDiff := range elemDiffs { - p.buf.WriteString(strings.Repeat(" ", indent+2)) - p.writeActionSymbol(elemDiff.Action) - switch elemDiff.Action { - case plans.NoOp, plans.Delete: - p.writeValue(elemDiff.Before, elemDiff.Action, indent+4) - case plans.Update: - p.writeValueDiff(elemDiff.Before, elemDiff.After, indent+4, path) - case plans.Create: - p.writeValue(elemDiff.After, elemDiff.Action, indent+4) - default: - // Should never happen since the above covers all - // actions that ctySequenceDiff can return. - p.writeValue(elemDiff.After, elemDiff.Action, indent+4) - } - - p.buf.WriteString(",\n") - } - - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteString("]") - return - - case ty.IsMapType(): - p.buf.WriteString("{") - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - p.buf.WriteString("\n") - - var allKeys []string - keyLen := 0 - for it := old.ElementIterator(); it.Next(); { - k, _ := it.Element() - keyStr := k.AsString() - allKeys = append(allKeys, keyStr) - if len(keyStr) > keyLen { - keyLen = len(keyStr) - } - } - for it := new.ElementIterator(); it.Next(); { - k, _ := it.Element() - keyStr := k.AsString() - allKeys = append(allKeys, keyStr) - if len(keyStr) > keyLen { - keyLen = len(keyStr) - } - } - - sort.Strings(allKeys) - - lastK := "" - for i, k := range allKeys { - if i > 0 && lastK == k { - continue // skip duplicates (list is sorted) - } - lastK = k - - p.buf.WriteString(strings.Repeat(" ", indent+2)) - kV := cty.StringVal(k) - var action plans.Action - if old.HasIndex(kV).False() { - action = plans.Create - } else if new.HasIndex(kV).False() { - action = plans.Delete - } else if eqV := old.Index(kV).Equals(new.Index(kV)); eqV.IsKnown() && eqV.True() { - action = plans.NoOp - } else { - action = plans.Update - } - - path := append(path, cty.IndexStep{Key: kV}) - - p.writeActionSymbol(action) - p.writeValue(kV, action, indent+4) - p.buf.WriteString(strings.Repeat(" ", keyLen-len(k))) - p.buf.WriteString(" = ") - switch action { - case plans.Create, plans.NoOp: - v := new.Index(kV) - p.writeValue(v, action, indent+4) - case plans.Delete: - oldV := old.Index(kV) - newV := cty.NullVal(oldV.Type()) - p.writeValueDiff(oldV, newV, indent+4, path) - default: - oldV := old.Index(kV) - newV := new.Index(kV) - p.writeValueDiff(oldV, newV, indent+4, path) - } - - p.buf.WriteByte('\n') - } - - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteString("}") - return - case ty.IsObjectType(): - p.buf.WriteString("{") - p.buf.WriteString("\n") - - forcesNewResource := p.pathForcesNewResource(path) - - var allKeys []string - keyLen := 0 - for it := old.ElementIterator(); it.Next(); { - k, _ := it.Element() - keyStr := k.AsString() - allKeys = append(allKeys, keyStr) - if len(keyStr) > keyLen { - keyLen = len(keyStr) - } - } - for it := new.ElementIterator(); it.Next(); { - k, _ := it.Element() - keyStr := k.AsString() - allKeys = append(allKeys, keyStr) - if len(keyStr) > keyLen { - keyLen = len(keyStr) - } - } - - sort.Strings(allKeys) - - lastK := "" - for i, k := range allKeys { - if i > 0 && lastK == k { - continue // skip duplicates (list is sorted) - } - lastK = k - - p.buf.WriteString(strings.Repeat(" ", indent+2)) - kV := k - var action plans.Action - if !old.Type().HasAttribute(kV) { - action = plans.Create - } else if !new.Type().HasAttribute(kV) { - action = plans.Delete - } else if eqV := old.GetAttr(kV).Equals(new.GetAttr(kV)); eqV.IsKnown() && eqV.True() { - action = plans.NoOp - } else { - action = plans.Update - } - - path := append(path, cty.GetAttrStep{Name: kV}) - - p.writeActionSymbol(action) - p.buf.WriteString(k) - p.buf.WriteString(strings.Repeat(" ", keyLen-len(k))) - p.buf.WriteString(" = ") - - switch action { - case plans.Create, plans.NoOp: - v := new.GetAttr(kV) - p.writeValue(v, action, indent+4) - case plans.Delete: - oldV := old.GetAttr(kV) - newV := cty.NullVal(oldV.Type()) - p.writeValueDiff(oldV, newV, indent+4, path) - default: - oldV := old.GetAttr(kV) - newV := new.GetAttr(kV) - p.writeValueDiff(oldV, newV, indent+4, path) - } - - p.buf.WriteString("\n") - } - - p.buf.WriteString(strings.Repeat(" ", indent)) - p.buf.WriteString("}") - - if forcesNewResource { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } - return - } - } - - // In all other cases, we just show the new and old values as-is - p.writeValue(old, plans.Delete, indent) - if new.IsNull() { - p.buf.WriteString(p.color.Color(" [dark_gray]->[reset] ")) - } else { - p.buf.WriteString(p.color.Color(" [yellow]->[reset] ")) - } - - p.writeValue(new, plans.Create, indent) - if p.pathForcesNewResource(path) { - p.buf.WriteString(p.color.Color(forcesNewResourceCaption)) - } -} - -// writeActionSymbol writes a symbol to represent the given action, followed -// by a space. -// -// It only supports the actions that can be represented with a single character: -// Create, Delete, Update and NoAction. -func (p *blockBodyDiffPrinter) writeActionSymbol(action plans.Action) { - switch action { - case plans.Create: - p.buf.WriteString(p.color.Color("[green]+[reset] ")) - case plans.Delete: - p.buf.WriteString(p.color.Color("[red]-[reset] ")) - case plans.Update: - p.buf.WriteString(p.color.Color("[yellow]~[reset] ")) - case plans.NoOp: - p.buf.WriteString(" ") - default: - // Should never happen - p.buf.WriteString(p.color.Color("? ")) - } -} - -func (p *blockBodyDiffPrinter) pathForcesNewResource(path cty.Path) bool { - if !p.action.IsReplace() { - // "requiredReplace" only applies when the instance is being replaced - return false - } - return p.requiredReplace.Has(path) -} - -func ctyEmptyString(value cty.Value) bool { - if !value.IsNull() && value.IsKnown() { - valueType := value.Type() - if valueType == cty.String && value.AsString() == "" { - return true - } - } - return false -} - -func ctyGetAttrMaybeNull(val cty.Value, name string) cty.Value { - attrType := val.Type().AttributeType(name) - - if val.IsNull() { - return cty.NullVal(attrType) - } - - // We treat "" as null here - // as existing SDK doesn't support null yet. - // This allows us to avoid spurious diffs - // until we introduce null to the SDK. - attrValue := val.GetAttr(name) - if ctyEmptyString(attrValue) { - return cty.NullVal(attrType) - } - - return attrValue -} - -func ctyCollectionValues(val cty.Value) []cty.Value { - if !val.IsKnown() || val.IsNull() { - return nil - } - - ret := make([]cty.Value, 0, val.LengthInt()) - for it := val.ElementIterator(); it.Next(); { - _, value := it.Element() - ret = append(ret, value) - } - return ret -} - -// ctySequenceDiff returns differences between given sequences of cty.Value(s) -// in the form of Create, Delete, or Update actions (for objects). -func ctySequenceDiff(old, new []cty.Value) []*plans.Change { - var ret []*plans.Change - lcs := objchange.LongestCommonSubsequence(old, new) - var oldI, newI, lcsI int - for oldI < len(old) || newI < len(new) || lcsI < len(lcs) { - for oldI < len(old) && (lcsI >= len(lcs) || !old[oldI].RawEquals(lcs[lcsI])) { - isObjectDiff := old[oldI].Type().IsObjectType() && (newI >= len(new) || new[newI].Type().IsObjectType()) - if isObjectDiff && newI < len(new) { - ret = append(ret, &plans.Change{ - Action: plans.Update, - Before: old[oldI], - After: new[newI], - }) - oldI++ - newI++ // we also consume the next "new" in this case - continue - } - - ret = append(ret, &plans.Change{ - Action: plans.Delete, - Before: old[oldI], - After: cty.NullVal(old[oldI].Type()), - }) - oldI++ - } - for newI < len(new) && (lcsI >= len(lcs) || !new[newI].RawEquals(lcs[lcsI])) { - ret = append(ret, &plans.Change{ - Action: plans.Create, - Before: cty.NullVal(new[newI].Type()), - After: new[newI], - }) - newI++ - } - if lcsI < len(lcs) { - ret = append(ret, &plans.Change{ - Action: plans.NoOp, - Before: lcs[lcsI], - After: lcs[lcsI], - }) - - // All of our indexes advance together now, since the line - // is common to all three sequences. - lcsI++ - oldI++ - newI++ - } - } - return ret -} - -func ctyEqualWithUnknown(old, new cty.Value) bool { - if !old.IsWhollyKnown() || !new.IsWhollyKnown() { - return false - } - return old.Equals(new).True() -} - -// ctyTypesEqual checks equality of two types more loosely -// by avoiding checks of object/tuple elements -// as we render differences on element-by-element basis anyway -func ctyTypesEqual(oldT, newT cty.Type) bool { - if oldT.IsObjectType() && newT.IsObjectType() { - return true - } - if oldT.IsTupleType() && newT.IsTupleType() { - return true - } - return oldT.Equals(newT) -} - -func ctyEnsurePathCapacity(path cty.Path, minExtra int) cty.Path { - if cap(path)-len(path) >= minExtra { - return path - } - newCap := cap(path) * 2 - if newCap < (len(path) + minExtra) { - newCap = len(path) + minExtra - } - newPath := make(cty.Path, len(path), newCap) - copy(newPath, path) - return newPath -} - -// ctyNullBlockListAsEmpty either returns the given value verbatim if it is non-nil -// or returns an empty value of a suitable type to serve as a placeholder for it. -// -// In particular, this function handles the special situation where a "list" is -// actually represented as a tuple type where nested blocks contain -// dynamically-typed values. -func ctyNullBlockListAsEmpty(in cty.Value) cty.Value { - if !in.IsNull() { - return in - } - if ty := in.Type(); ty.IsListType() { - return cty.ListValEmpty(ty.ElementType()) - } - return cty.EmptyTupleVal // must need a tuple, then -} - -// ctyNullBlockMapAsEmpty either returns the given value verbatim if it is non-nil -// or returns an empty value of a suitable type to serve as a placeholder for it. -// -// In particular, this function handles the special situation where a "map" is -// actually represented as an object type where nested blocks contain -// dynamically-typed values. -func ctyNullBlockMapAsEmpty(in cty.Value) cty.Value { - if !in.IsNull() { - return in - } - if ty := in.Type(); ty.IsMapType() { - return cty.MapValEmpty(ty.ElementType()) - } - return cty.EmptyObjectVal // must need an object, then -} - -// ctyNullBlockSetAsEmpty either returns the given value verbatim if it is non-nil -// or returns an empty value of a suitable type to serve as a placeholder for it. -func ctyNullBlockSetAsEmpty(in cty.Value) cty.Value { - if !in.IsNull() { - return in - } - // Dynamically-typed attributes are not supported inside blocks backed by - // sets, so our result here is always a set. - return cty.SetValEmpty(in.Type().ElementType()) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/format.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/format.go deleted file mode 100644 index aa8d7deb2a2..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/format.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package format contains helpers for formatting various Terraform -// structures for human-readabout output. -// -// This package is used by the official Terraform CLI in formatting any -// output and is exported to encourage non-official frontends to mimic the -// output formatting as much as possible so that text formats of Terraform -// structures have a consistent look and feel. -package format diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/object_id.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/object_id.go deleted file mode 100644 index 85ebbfec5ea..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/object_id.go +++ /dev/null @@ -1,123 +0,0 @@ -package format - -import ( - "github.com/zclconf/go-cty/cty" -) - -// ObjectValueID takes a value that is assumed to be an object representation -// of some resource instance object and attempts to heuristically find an -// attribute of it that is likely to be a unique identifier in the remote -// system that it belongs to which will be useful to the user. -// -// If such an attribute is found, its name and string value intended for -// display are returned. Both returned strings are empty if no such attribute -// exists, in which case the caller should assume that the resource instance -// address within the Terraform configuration is the best available identifier. -// -// This is only a best-effort sort of thing, relying on naming conventions in -// our resource type schemas. The result is not guaranteed to be unique, but -// should generally be suitable for display to an end-user anyway. -// -// This function will panic if the given value is not of an object type. -func ObjectValueID(obj cty.Value) (k, v string) { - if obj.IsNull() || !obj.IsKnown() { - return "", "" - } - - atys := obj.Type().AttributeTypes() - - switch { - - case atys["id"] == cty.String: - v := obj.GetAttr("id") - if v.IsKnown() && !v.IsNull() { - return "id", v.AsString() - } - - case atys["name"] == cty.String: - // "name" isn't always globally unique, but if there isn't also an - // "id" then it _often_ is, in practice. - v := obj.GetAttr("name") - if v.IsKnown() && !v.IsNull() { - return "name", v.AsString() - } - } - - return "", "" -} - -// ObjectValueName takes a value that is assumed to be an object representation -// of some resource instance object and attempts to heuristically find an -// attribute of it that is likely to be a human-friendly name in the remote -// system that it belongs to which will be useful to the user. -// -// If such an attribute is found, its name and string value intended for -// display are returned. Both returned strings are empty if no such attribute -// exists, in which case the caller should assume that the resource instance -// address within the Terraform configuration is the best available identifier. -// -// This is only a best-effort sort of thing, relying on naming conventions in -// our resource type schemas. The result is not guaranteed to be unique, but -// should generally be suitable for display to an end-user anyway. -// -// Callers that use both ObjectValueName and ObjectValueID at the same time -// should be prepared to get the same attribute key and value from both in -// some cases, since there is overlap betweek the id-extraction and -// name-extraction heuristics. -// -// This function will panic if the given value is not of an object type. -func ObjectValueName(obj cty.Value) (k, v string) { - if obj.IsNull() || !obj.IsKnown() { - return "", "" - } - - atys := obj.Type().AttributeTypes() - - switch { - - case atys["name"] == cty.String: - v := obj.GetAttr("name") - if v.IsKnown() && !v.IsNull() { - return "name", v.AsString() - } - - case atys["tags"].IsMapType() && atys["tags"].ElementType() == cty.String: - tags := obj.GetAttr("tags") - if tags.IsNull() || !tags.IsWhollyKnown() { - break - } - - switch { - case tags.HasIndex(cty.StringVal("name")).RawEquals(cty.True): - v := tags.Index(cty.StringVal("name")) - if v.IsKnown() && !v.IsNull() { - return "tags.name", v.AsString() - } - case tags.HasIndex(cty.StringVal("Name")).RawEquals(cty.True): - // AWS-style naming convention - v := tags.Index(cty.StringVal("Name")) - if v.IsKnown() && !v.IsNull() { - return "tags.Name", v.AsString() - } - } - } - - return "", "" -} - -// ObjectValueIDOrName is a convenience wrapper around both ObjectValueID -// and ObjectValueName (in that preference order) to try to extract some sort -// of human-friendly descriptive string value for an object as additional -// context about an object when it is being displayed in a compact way (where -// not all of the attributes are visible.) -// -// Just as with the two functions it wraps, it is a best-effort and may return -// two empty strings if no suitable attribute can be found for a given object. -func ObjectValueIDOrName(obj cty.Value) (k, v string) { - k, v = ObjectValueID(obj) - if k != "" { - return - } - k, v = ObjectValueName(obj) - return -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/state.go deleted file mode 100644 index 14869ad3ca3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/state.go +++ /dev/null @@ -1,208 +0,0 @@ -package format - -import ( - "bytes" - "fmt" - "sort" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/terraform" - "github.com/mitchellh/colorstring" - "github.com/zclconf/go-cty/cty" -) - -// StateOpts are the options for formatting a state. -type StateOpts struct { - // State is the state to format. This is required. - State *states.State - - // Schemas are used to decode attributes. This is required. - Schemas *terraform.Schemas - - // Color is the colorizer. This is optional. - Color *colorstring.Colorize -} - -// State takes a state and returns a string -func State(opts *StateOpts) string { - if opts.Color == nil { - panic("colorize not given") - } - - if opts.Schemas == nil { - panic("schemas not given") - } - - s := opts.State - if len(s.Modules) == 0 { - return "The state file is empty. No resources are represented." - } - - buf := bytes.NewBufferString("[reset]") - p := blockBodyDiffPrinter{ - buf: buf, - color: opts.Color, - action: plans.NoOp, - } - - // Format all the modules - for _, m := range s.Modules { - formatStateModule(p, m, opts.Schemas) - } - - // Write the outputs for the root module - m := s.RootModule() - - if m.OutputValues != nil { - if len(m.OutputValues) > 0 { - p.buf.WriteString("Outputs:\n\n") - } - - // Sort the outputs - ks := make([]string, 0, len(m.OutputValues)) - for k := range m.OutputValues { - ks = append(ks, k) - } - sort.Strings(ks) - - // Output each output k/v pair - for _, k := range ks { - v := m.OutputValues[k] - p.buf.WriteString(fmt.Sprintf("%s = ", k)) - p.writeValue(v.Value, plans.NoOp, 0) - p.buf.WriteString("\n") - } - } - - trimmedOutput := strings.TrimSpace(p.buf.String()) - trimmedOutput += "[reset]" - - return opts.Color.Color(trimmedOutput) - -} - -func formatStateModule(p blockBodyDiffPrinter, m *states.Module, schemas *terraform.Schemas) { - // First get the names of all the resources so we can show them - // in alphabetical order. - names := make([]string, 0, len(m.Resources)) - for name := range m.Resources { - names = append(names, name) - } - sort.Strings(names) - - // Go through each resource and begin building up the output. - for _, key := range names { - for k, v := range m.Resources[key].Instances { - // keep these in order to keep the current object first, and - // provide deterministic output for the deposed objects - type obj struct { - header string - instance *states.ResourceInstanceObjectSrc - } - instances := []obj{} - - addr := m.Resources[key].Addr - - taintStr := "" - if v.Current != nil && v.Current.Status == 'T' { - taintStr = " (tainted)" - } - - instances = append(instances, - obj{fmt.Sprintf("# %s:%s\n", addr.Absolute(m.Addr).Instance(k), taintStr), v.Current}) - - for dk, v := range v.Deposed { - instances = append(instances, - obj{fmt.Sprintf("# %s: (deposed object %s)\n", addr.Absolute(m.Addr).Instance(k), dk), v}) - } - - // Sort the instances for consistent output. - // Starting the sort from the second index, so the current instance - // is always first. - sort.Slice(instances[1:], func(i, j int) bool { - return instances[i+1].header < instances[j+1].header - }) - - for _, obj := range instances { - header := obj.header - instance := obj.instance - p.buf.WriteString(header) - if instance == nil { - // this shouldn't happen, but there's nothing to do here so - // don't panic below. - continue - } - - var schema *configschema.Block - provider := m.Resources[key].ProviderConfig.ProviderConfig.StringCompact() - if _, exists := schemas.Providers[provider]; !exists { - // This should never happen in normal use because we should've - // loaded all of the schemas and checked things prior to this - // point. We can't return errors here, but since this is UI code - // we will try to do _something_ reasonable. - p.buf.WriteString(fmt.Sprintf("# missing schema for provider %q\n\n", provider)) - continue - } - - switch addr.Mode { - case addrs.ManagedResourceMode: - schema, _ = schemas.ResourceTypeConfig( - provider, - addr.Mode, - addr.Type, - ) - if schema == nil { - p.buf.WriteString(fmt.Sprintf( - "# missing schema for provider %q resource type %s\n\n", provider, addr.Type)) - continue - } - - p.buf.WriteString(fmt.Sprintf( - "resource %q %q {", - addr.Type, - addr.Name, - )) - case addrs.DataResourceMode: - schema, _ = schemas.ResourceTypeConfig( - provider, - addr.Mode, - addr.Type, - ) - if schema == nil { - p.buf.WriteString(fmt.Sprintf( - "# missing schema for provider %q data source %s\n\n", provider, addr.Type)) - continue - } - - p.buf.WriteString(fmt.Sprintf( - "data %q %q {", - addr.Type, - addr.Name, - )) - default: - // should never happen, since the above is exhaustive - p.buf.WriteString(addr.String()) - } - - val, err := instance.Decode(schema.ImpliedType()) - if err != nil { - fmt.Println(err.Error()) - break - } - - path := make(cty.Path, 0, 3) - bodyWritten := p.writeBlockBodyDiff(schema, val.Value, val.Value, 2, path) - if bodyWritten { - p.buf.WriteString("\n") - } - - p.buf.WriteString("}\n\n") - } - } - } - p.buf.WriteString("\n") -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/backend.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/backend.go deleted file mode 100644 index 76d161d7237..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/backend.go +++ /dev/null @@ -1,24 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl/v2" -) - -// Backend represents a "backend" block inside a "terraform" block in a module -// or file. -type Backend struct { - Type string - Config hcl.Body - - TypeRange hcl.Range - DeclRange hcl.Range -} - -func decodeBackendBlock(block *hcl.Block) (*Backend, hcl.Diagnostics) { - return &Backend{ - Type: block.Labels[0], - TypeRange: block.LabelRanges[0], - Config: block.Body, - DeclRange: block.DefRange, - }, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/compat_shim.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/compat_shim.go deleted file mode 100644 index e594ebd40ff..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/compat_shim.go +++ /dev/null @@ -1,116 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" - "github.com/zclconf/go-cty/cty" -) - -// ------------------------------------------------------------------------- -// Functions in this file are compatibility shims intended to ease conversion -// from the old configuration loader. Any use of these functions that makes -// a change should generate a deprecation warning explaining to the user how -// to update their code for new patterns. -// -// Shims are particularly important for any patterns that have been widely -// documented in books, tutorials, etc. Users will still be starting from -// these examples and we want to help them adopt the latest patterns rather -// than leave them stranded. -// ------------------------------------------------------------------------- - -// shimTraversalInString takes any arbitrary expression and checks if it is -// a quoted string in the native syntax. If it _is_, then it is parsed as a -// traversal and re-wrapped into a synthetic traversal expression and a -// warning is generated. Otherwise, the given expression is just returned -// verbatim. -// -// This function has no effect on expressions from the JSON syntax, since -// traversals in strings are the required pattern in that syntax. -// -// If wantKeyword is set, the generated warning diagnostic will talk about -// keywords rather than references. The behavior is otherwise unchanged, and -// the caller remains responsible for checking that the result is indeed -// a keyword, e.g. using hcl.ExprAsKeyword. -func shimTraversalInString(expr hcl.Expression, wantKeyword bool) (hcl.Expression, hcl.Diagnostics) { - // ObjectConsKeyExpr is a special wrapper type used for keys on object - // constructors to deal with the fact that naked identifiers are normally - // handled as "bareword" strings rather than as variable references. Since - // we know we're interpreting as a traversal anyway (and thus it won't - // matter whether it's a string or an identifier) we can safely just unwrap - // here and then process whatever we find inside as normal. - if ocke, ok := expr.(*hclsyntax.ObjectConsKeyExpr); ok { - expr = ocke.Wrapped - } - - if !exprIsNativeQuotedString(expr) { - return expr, nil - } - - strVal, diags := expr.Value(nil) - if diags.HasErrors() || strVal.IsNull() || !strVal.IsKnown() { - // Since we're not even able to attempt a shim here, we'll discard - // the diagnostics we saw so far and let the caller's own error - // handling take care of reporting the invalid expression. - return expr, nil - } - - // The position handling here isn't _quite_ right because it won't - // take into account any escape sequences in the literal string, but - // it should be close enough for any error reporting to make sense. - srcRange := expr.Range() - startPos := srcRange.Start // copy - startPos.Column++ // skip initial quote - startPos.Byte++ // skip initial quote - - traversal, tDiags := hclsyntax.ParseTraversalAbs( - []byte(strVal.AsString()), - srcRange.Filename, - startPos, - ) - diags = append(diags, tDiags...) - - // For initial release our deprecation warnings are disabled to allow - // a period where modules can be compatible with both old and new - // conventions. - // FIXME: Re-enable these deprecation warnings in a release prior to - // Terraform 0.13 and then remove the shims altogether for 0.13. - /* - if wantKeyword { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Quoted keywords are deprecated", - Detail: "In this context, keywords are expected literally rather than in quotes. Previous versions of Terraform required quotes, but that usage is now deprecated. Remove the quotes surrounding this keyword to silence this warning.", - Subject: &srcRange, - }) - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Quoted references are deprecated", - Detail: "In this context, references are expected literally rather than in quotes. Previous versions of Terraform required quotes, but that usage is now deprecated. Remove the quotes surrounding this reference to silence this warning.", - Subject: &srcRange, - }) - } - */ - - return &hclsyntax.ScopeTraversalExpr{ - Traversal: traversal, - SrcRange: srcRange, - }, diags -} - -// shimIsIgnoreChangesStar returns true if the given expression seems to be -// a string literal whose value is "*". This is used to support a legacy -// form of ignore_changes = all . -// -// This function does not itself emit any diagnostics, so it's the caller's -// responsibility to emit a warning diagnostic when this function returns true. -func shimIsIgnoreChangesStar(expr hcl.Expression) bool { - val, valDiags := expr.Value(nil) - if valDiags.HasErrors() { - return false - } - if val.Type() != cty.String || val.IsNull() || !val.IsKnown() { - return false - } - return val.AsString() == "*" -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/config.go deleted file mode 100644 index 82c88a10f26..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/config.go +++ /dev/null @@ -1,164 +0,0 @@ -package configs - -import ( - "sort" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// A Config is a node in the tree of modules within a configuration. -// -// The module tree is constructed by following ModuleCall instances recursively -// through the root module transitively into descendent modules. -// -// A module tree described in *this* package represents the static tree -// represented by configuration. During evaluation a static ModuleNode may -// expand into zero or more module instances depending on the use of count and -// for_each configuration attributes within each call. -type Config struct { - // RootModule points to the Config for the root module within the same - // module tree as this module. If this module _is_ the root module then - // this is self-referential. - Root *Config - - // ParentModule points to the Config for the module that directly calls - // this module. If this is the root module then this field is nil. - Parent *Config - - // Path is a sequence of module logical names that traverse from the root - // module to this config. Path is empty for the root module. - // - // This should only be used to display paths to the end-user in rare cases - // where we are talking about the static module tree, before module calls - // have been resolved. In most cases, an addrs.ModuleInstance describing - // a node in the dynamic module tree is better, since it will then include - // any keys resulting from evaluating "count" and "for_each" arguments. - Path addrs.Module - - // ChildModules points to the Config for each of the direct child modules - // called from this module. The keys in this map match the keys in - // Module.ModuleCalls. - Children map[string]*Config - - // Module points to the object describing the configuration for the - // various elements (variables, resources, etc) defined by this module. - Module *Module - - // CallRange is the source range for the header of the module block that - // requested this module. - // - // This field is meaningless for the root module, where its contents are undefined. - CallRange hcl.Range - - // SourceAddr is the source address that the referenced module was requested - // from, as specified in configuration. - // - // This field is meaningless for the root module, where its contents are undefined. - SourceAddr string - - // SourceAddrRange is the location in the configuration source where the - // SourceAddr value was set, for use in diagnostic messages. - // - // This field is meaningless for the root module, where its contents are undefined. - SourceAddrRange hcl.Range - - // Version is the specific version that was selected for this module, - // based on version constraints given in configuration. - // - // This field is nil if the module was loaded from a non-registry source, - // since versions are not supported for other sources. - // - // This field is meaningless for the root module, where it will always - // be nil. - Version *version.Version -} - -// NewEmptyConfig constructs a single-node configuration tree with an empty -// root module. This is generally a pretty useless thing to do, so most callers -// should instead use BuildConfig. -func NewEmptyConfig() *Config { - ret := &Config{} - ret.Root = ret - ret.Children = make(map[string]*Config) - ret.Module = &Module{} - return ret -} - -// DeepEach calls the given function once for each module in the tree, starting -// with the receiver. -// -// A parent is always called before its children and children of a particular -// node are visited in lexicographic order by their names. -func (c *Config) DeepEach(cb func(c *Config)) { - cb(c) - - names := make([]string, 0, len(c.Children)) - for name := range c.Children { - names = append(names, name) - } - - for _, name := range names { - c.Children[name].DeepEach(cb) - } -} - -// DescendentForInstance is like Descendent except that it accepts a path -// to a particular module instance in the dynamic module graph, returning -// the node from the static module graph that corresponds to it. -// -// All instances created by a particular module call share the same -// configuration, so the keys within the given path are disregarded. -func (c *Config) DescendentForInstance(path addrs.ModuleInstance) *Config { - current := c - for _, step := range path { - current = current.Children[step.Name] - if current == nil { - return nil - } - } - return current -} - -// ProviderTypes returns the names of each distinct provider type referenced -// in the receiving configuration. -// -// This is a helper for easily determining which provider types are required -// to fully interpret the configuration, though it does not include version -// information and so callers are expected to have already dealt with -// provider version selection in an earlier step and have identified suitable -// versions for each provider. -func (c *Config) ProviderTypes() []string { - m := make(map[string]struct{}) - c.gatherProviderTypes(m) - - ret := make([]string, 0, len(m)) - for k := range m { - ret = append(ret, k) - } - sort.Strings(ret) - return ret -} -func (c *Config) gatherProviderTypes(m map[string]struct{}) { - if c == nil { - return - } - - for _, pc := range c.Module.ProviderConfigs { - m[pc.Name] = struct{}{} - } - for _, rc := range c.Module.ManagedResources { - providerAddr := rc.ProviderConfigAddr() - m[providerAddr.Type] = struct{}{} - } - for _, rc := range c.Module.DataResources { - providerAddr := rc.ProviderConfigAddr() - m[providerAddr.Type] = struct{}{} - } - - // Must also visit our child modules, recursively. - for _, cc := range c.Children { - cc.gatherProviderTypes(m) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/config_build.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/config_build.go deleted file mode 100644 index cb46b65aaaa..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/config_build.go +++ /dev/null @@ -1,160 +0,0 @@ -package configs - -import ( - "sort" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// BuildConfig constructs a Config from a root module by loading all of its -// descendent modules via the given ModuleWalker. -// -// The result is a module tree that has so far only had basic module- and -// file-level invariants validated. If the returned diagnostics contains errors, -// the returned module tree may be incomplete but can still be used carefully -// for static analysis. -func BuildConfig(root *Module, walker ModuleWalker) (*Config, hcl.Diagnostics) { - var diags hcl.Diagnostics - cfg := &Config{ - Module: root, - } - cfg.Root = cfg // Root module is self-referential. - cfg.Children, diags = buildChildModules(cfg, walker) - return cfg, diags -} - -func buildChildModules(parent *Config, walker ModuleWalker) (map[string]*Config, hcl.Diagnostics) { - var diags hcl.Diagnostics - ret := map[string]*Config{} - - calls := parent.Module.ModuleCalls - - // We'll sort the calls by their local names so that they'll appear in a - // predictable order in any logging that's produced during the walk. - callNames := make([]string, 0, len(calls)) - for k := range calls { - callNames = append(callNames, k) - } - sort.Strings(callNames) - - for _, callName := range callNames { - call := calls[callName] - path := make([]string, len(parent.Path)+1) - copy(path, parent.Path) - path[len(path)-1] = call.Name - - req := ModuleRequest{ - Name: call.Name, - Path: path, - SourceAddr: call.SourceAddr, - SourceAddrRange: call.SourceAddrRange, - VersionConstraint: call.Version, - Parent: parent, - CallRange: call.DeclRange, - } - - mod, ver, modDiags := walker.LoadModule(&req) - diags = append(diags, modDiags...) - if mod == nil { - // nil can be returned if the source address was invalid and so - // nothing could be loaded whatsoever. LoadModule should've - // returned at least one error diagnostic in that case. - continue - } - - child := &Config{ - Parent: parent, - Root: parent.Root, - Path: path, - Module: mod, - CallRange: call.DeclRange, - SourceAddr: call.SourceAddr, - SourceAddrRange: call.SourceAddrRange, - Version: ver, - } - - child.Children, modDiags = buildChildModules(child, walker) - diags = append(diags, modDiags...) - - ret[call.Name] = child - } - - return ret, diags -} - -// A ModuleWalker knows how to find and load a child module given details about -// the module to be loaded and a reference to its partially-loaded parent -// Config. -type ModuleWalker interface { - // LoadModule finds and loads a requested child module. - // - // If errors are detected during loading, implementations should return them - // in the diagnostics object. If the diagnostics object contains any errors - // then the caller will tolerate the returned module being nil or incomplete. - // If no errors are returned, it should be non-nil and complete. - // - // Full validation need not have been performed but an implementation should - // ensure that the basic file- and module-validations performed by the - // LoadConfigDir function (valid syntax, no namespace collisions, etc) have - // been performed before returning a module. - LoadModule(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics) -} - -// ModuleWalkerFunc is an implementation of ModuleWalker that directly wraps -// a callback function, for more convenient use of that interface. -type ModuleWalkerFunc func(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics) - -// LoadModule implements ModuleWalker. -func (f ModuleWalkerFunc) LoadModule(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics) { - return f(req) -} - -// ModuleRequest is used with the ModuleWalker interface to describe a child -// module that must be loaded. -type ModuleRequest struct { - // Name is the "logical name" of the module call within configuration. - // This is provided in case the name is used as part of a storage key - // for the module, but implementations must otherwise treat it as an - // opaque string. It is guaranteed to have already been validated as an - // HCL identifier and UTF-8 encoded. - Name string - - // Path is a list of logical names that traverse from the root module to - // this module. This can be used, for example, to form a lookup key for - // each distinct module call in a configuration, allowing for multiple - // calls with the same name at different points in the tree. - Path addrs.Module - - // SourceAddr is the source address string provided by the user in - // configuration. - SourceAddr string - - // SourceAddrRange is the source range for the SourceAddr value as it - // was provided in configuration. This can and should be used to generate - // diagnostics about the source address having invalid syntax, referring - // to a non-existent object, etc. - SourceAddrRange hcl.Range - - // VersionConstraint is the version constraint applied to the module in - // configuration. This data structure includes the source range for - // the constraint, which can and should be used to generate diagnostics - // about constraint-related issues, such as constraints that eliminate all - // available versions of a module whose source is otherwise valid. - VersionConstraint VersionConstraint - - // Parent is the partially-constructed module tree node that the loaded - // module will be added to. Callers may refer to any field of this - // structure except Children, which is still under construction when - // ModuleRequest objects are created and thus has undefined content. - // The main reason this is provided is so that full module paths can - // be constructed for uniqueness. - Parent *Config - - // CallRange is the source range for the header of the "module" block - // in configuration that prompted this request. This can be used as the - // subject of an error diagnostic that relates to the module call itself, - // rather than to either its source address or its version number. - CallRange hcl.Range -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/copy_dir.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/copy_dir.go deleted file mode 100644 index ebbeb3b629f..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/copy_dir.go +++ /dev/null @@ -1,125 +0,0 @@ -package configload - -import ( - "io" - "os" - "path/filepath" - "strings" -) - -// copyDir copies the src directory contents into dst. Both directories -// should already exist. -func copyDir(dst, src string) error { - src, err := filepath.EvalSymlinks(src) - if err != nil { - return err - } - - walkFn := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - if path == src { - return nil - } - - if strings.HasPrefix(filepath.Base(path), ".") { - // Skip any dot files - if info.IsDir() { - return filepath.SkipDir - } else { - return nil - } - } - - // The "path" has the src prefixed to it. We need to join our - // destination with the path without the src on it. - dstPath := filepath.Join(dst, path[len(src):]) - - // we don't want to try and copy the same file over itself. - if eq, err := sameFile(path, dstPath); eq { - return nil - } else if err != nil { - return err - } - - // If we have a directory, make that subdirectory, then continue - // the walk. - if info.IsDir() { - if path == filepath.Join(src, dst) { - // dst is in src; don't walk it. - return nil - } - - if err := os.MkdirAll(dstPath, 0755); err != nil { - return err - } - - return nil - } - - // If the current path is a symlink, recreate the symlink relative to - // the dst directory - if info.Mode()&os.ModeSymlink == os.ModeSymlink { - target, err := os.Readlink(path) - if err != nil { - return err - } - - return os.Symlink(target, dstPath) - } - - // If we have a file, copy the contents. - srcF, err := os.Open(path) - if err != nil { - return err - } - defer srcF.Close() - - dstF, err := os.Create(dstPath) - if err != nil { - return err - } - defer dstF.Close() - - if _, err := io.Copy(dstF, srcF); err != nil { - return err - } - - // Chmod it - return os.Chmod(dstPath, info.Mode()) - } - - return filepath.Walk(src, walkFn) -} - -// sameFile tried to determine if to paths are the same file. -// If the paths don't match, we lookup the inode on supported systems. -func sameFile(a, b string) (bool, error) { - if a == b { - return true, nil - } - - aIno, err := inode(a) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - - bIno, err := inode(b) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - - if aIno > 0 && aIno == bIno { - return true, nil - } - - return false, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/doc.go deleted file mode 100644 index 8b615f90260..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package configload knows how to install modules into the .terraform/modules -// directory and to load modules from those installed locations. It is used -// in conjunction with the LoadConfig function in the parent package. -package configload diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/inode.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/inode.go deleted file mode 100644 index 57df04145a0..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/inode.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build linux darwin openbsd netbsd solaris dragonfly - -package configload - -import ( - "fmt" - "os" - "syscall" -) - -// lookup the inode of a file on posix systems -func inode(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - if st, ok := stat.Sys().(*syscall.Stat_t); ok { - return st.Ino, nil - } - return 0, fmt.Errorf("could not determine file inode") -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/inode_freebsd.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/inode_freebsd.go deleted file mode 100644 index 4dc28eaa897..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/inode_freebsd.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build freebsd - -package configload - -import ( - "fmt" - "os" - "syscall" -) - -// lookup the inode of a file on posix systems -func inode(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - if st, ok := stat.Sys().(*syscall.Stat_t); ok { - return uint64(st.Ino), nil - } - return 0, fmt.Errorf("could not determine file inode") -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/inode_windows.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/inode_windows.go deleted file mode 100644 index 0d22e672642..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/inode_windows.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build windows - -package configload - -// no syscall.Stat_t on windows, return 0 for inodes -func inode(path string) (uint64, error) { - return 0, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/loader.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/loader.go deleted file mode 100644 index 0d12d7d2aa6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/loader.go +++ /dev/null @@ -1,101 +0,0 @@ -package configload - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/registry" - "github.com/hashicorp/terraform-svchost/disco" - "github.com/spf13/afero" -) - -// A Loader instance is the main entry-point for loading configurations via -// this package. -// -// It extends the general config-loading functionality in the parent package -// "configs" to support installation of modules from remote sources and -// loading full configurations using modules that were previously installed. -type Loader struct { - // parser is used to read configuration - parser *configs.Parser - - // modules is used to install and locate descendent modules that are - // referenced (directly or indirectly) from the root module. - modules moduleMgr -} - -// Config is used with NewLoader to specify configuration arguments for the -// loader. -type Config struct { - // ModulesDir is a path to a directory where descendent modules are - // (or should be) installed. (This is usually the - // .terraform/modules directory, in the common case where this package - // is being loaded from the main Terraform CLI package.) - ModulesDir string - - // Services is the service discovery client to use when locating remote - // module registry endpoints. If this is nil then registry sources are - // not supported, which should be true only in specialized circumstances - // such as in tests. - Services *disco.Disco -} - -// NewLoader creates and returns a loader that reads configuration from the -// real OS filesystem. -// -// The loader has some internal state about the modules that are currently -// installed, which is read from disk as part of this function. If that -// manifest cannot be read then an error will be returned. -func NewLoader(config *Config) (*Loader, error) { - fs := afero.NewOsFs() - parser := configs.NewParser(fs) - reg := registry.NewClient(config.Services, nil) - - ret := &Loader{ - parser: parser, - modules: moduleMgr{ - FS: afero.Afero{Fs: fs}, - CanInstall: true, - Dir: config.ModulesDir, - Services: config.Services, - Registry: reg, - }, - } - - err := ret.modules.readModuleManifestSnapshot() - if err != nil { - return nil, fmt.Errorf("failed to read module manifest: %s", err) - } - - return ret, nil -} - -// ModulesDir returns the path to the directory where the loader will look for -// the local cache of remote module packages. -func (l *Loader) ModulesDir() string { - return l.modules.Dir -} - -// RefreshModules updates the in-memory cache of the module manifest from the -// module manifest file on disk. This is not necessary in normal use because -// module installation and configuration loading are separate steps, but it -// can be useful in tests where module installation is done as a part of -// configuration loading by a helper function. -// -// Call this function after any module installation where an existing loader -// is already alive and may be used again later. -// -// An error is returned if the manifest file cannot be read. -func (l *Loader) RefreshModules() error { - if l == nil { - // Nothing to do, then. - return nil - } - return l.modules.readModuleManifestSnapshot() -} - -// Sources returns the source code cache for the underlying parser of this -// loader. This is a shorthand for l.Parser().Sources(). -func (l *Loader) Sources() map[string][]byte { - return l.parser.Sources() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/loader_load.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/loader_load.go deleted file mode 100644 index bcfa733e60d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/loader_load.go +++ /dev/null @@ -1,105 +0,0 @@ -package configload - -import ( - "fmt" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" -) - -// LoadConfig reads the Terraform module in the given directory and uses it as the -// root module to build the static module tree that represents a configuration, -// assuming that all required descendent modules have already been installed. -// -// If error diagnostics are returned, the returned configuration may be either -// nil or incomplete. In the latter case, cautious static analysis is possible -// in spite of the errors. -// -// LoadConfig performs the basic syntax and uniqueness validations that are -// required to process the individual modules, and also detects -func (l *Loader) LoadConfig(rootDir string) (*configs.Config, hcl.Diagnostics) { - rootMod, diags := l.parser.LoadConfigDir(rootDir) - if rootMod == nil { - return nil, diags - } - - cfg, cDiags := configs.BuildConfig(rootMod, configs.ModuleWalkerFunc(l.moduleWalkerLoad)) - diags = append(diags, cDiags...) - - return cfg, diags -} - -// moduleWalkerLoad is a configs.ModuleWalkerFunc for loading modules that -// are presumed to have already been installed. A different function -// (moduleWalkerInstall) is used for installation. -func (l *Loader) moduleWalkerLoad(req *configs.ModuleRequest) (*configs.Module, *version.Version, hcl.Diagnostics) { - // Since we're just loading here, we expect that all referenced modules - // will be already installed and described in our manifest. However, we - // do verify that the manifest and the configuration are in agreement - // so that we can prompt the user to run "terraform init" if not. - - key := l.modules.manifest.ModuleKey(req.Path) - record, exists := l.modules.manifest[key] - - if !exists { - return nil, nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Module not installed", - Detail: "This module is not yet installed. Run \"terraform init\" to install all modules required by this configuration.", - Subject: &req.CallRange, - }, - } - } - - var diags hcl.Diagnostics - - // Check for inconsistencies between manifest and config - if req.SourceAddr != record.SourceAddr { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Module source has changed", - Detail: "The source address was changed since this module was installed. Run \"terraform init\" to install all modules required by this configuration.", - Subject: &req.SourceAddrRange, - }) - } - if len(req.VersionConstraint.Required) > 0 && record.Version == nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Module version requirements have changed", - Detail: "The version requirements have changed since this module was installed and the installed version is no longer acceptable. Run \"terraform init\" to install all modules required by this configuration.", - Subject: &req.SourceAddrRange, - }) - } - if record.Version != nil && !req.VersionConstraint.Required.Check(record.Version) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Module version requirements have changed", - Detail: fmt.Sprintf( - "The version requirements have changed since this module was installed and the installed version (%s) is no longer acceptable. Run \"terraform init\" to install all modules required by this configuration.", - record.Version, - ), - Subject: &req.SourceAddrRange, - }) - } - - mod, mDiags := l.parser.LoadConfigDir(record.Dir) - diags = append(diags, mDiags...) - if mod == nil { - // nil specifically indicates that the directory does not exist or - // cannot be read, so in this case we'll discard any generic diagnostics - // returned from LoadConfigDir and produce our own context-sensitive - // error message. - return nil, nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Module not installed", - Detail: fmt.Sprintf("This module's local cache directory %s could not be read. Run \"terraform init\" to install all modules required by this configuration.", record.Dir), - Subject: &req.CallRange, - }, - } - } - - return mod, record.Version, diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/loader_snapshot.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/loader_snapshot.go deleted file mode 100644 index 0772edc71fb..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/loader_snapshot.go +++ /dev/null @@ -1,492 +0,0 @@ -package configload - -import ( - "fmt" - "io" - "os" - "path/filepath" - "sort" - "time" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/modsdir" - "github.com/spf13/afero" -) - -// LoadConfigWithSnapshot is a variant of LoadConfig that also simultaneously -// creates an in-memory snapshot of the configuration files used, which can -// be later used to create a loader that may read only from this snapshot. -func (l *Loader) LoadConfigWithSnapshot(rootDir string) (*configs.Config, *Snapshot, hcl.Diagnostics) { - rootMod, diags := l.parser.LoadConfigDir(rootDir) - if rootMod == nil { - return nil, nil, diags - } - - snap := &Snapshot{ - Modules: map[string]*SnapshotModule{}, - } - walker := l.makeModuleWalkerSnapshot(snap) - cfg, cDiags := configs.BuildConfig(rootMod, walker) - diags = append(diags, cDiags...) - - addDiags := l.addModuleToSnapshot(snap, "", rootDir, "", nil) - diags = append(diags, addDiags...) - - return cfg, snap, diags -} - -// NewLoaderFromSnapshot creates a Loader that reads files only from the -// given snapshot. -// -// A snapshot-based loader cannot install modules, so calling InstallModules -// on the return value will cause a panic. -// -// A snapshot-based loader also has access only to configuration files. Its -// underlying parser does not have access to other files in the native -// filesystem, such as values files. For those, either use a normal loader -// (created by NewLoader) or use the configs.Parser API directly. -func NewLoaderFromSnapshot(snap *Snapshot) *Loader { - fs := snapshotFS{snap} - parser := configs.NewParser(fs) - - ret := &Loader{ - parser: parser, - modules: moduleMgr{ - FS: afero.Afero{Fs: fs}, - CanInstall: false, - manifest: snap.moduleManifest(), - }, - } - - return ret -} - -// Snapshot is an in-memory representation of the source files from a -// configuration, which can be used as an alternative configurations source -// for a loader with NewLoaderFromSnapshot. -// -// The primary purpose of a Snapshot is to build the configuration portion -// of a plan file (see ../../plans/planfile) so that it can later be reloaded -// and used to recover the exact configuration that the plan was built from. -type Snapshot struct { - // Modules is a map from opaque module keys (suitable for use as directory - // names on all supported operating systems) to the snapshot information - // about each module. - Modules map[string]*SnapshotModule -} - -// SnapshotModule represents a single module within a Snapshot. -type SnapshotModule struct { - // Dir is the path, relative to the root directory given when the - // snapshot was created, where the module appears in the snapshot's - // virtual filesystem. - Dir string - - // Files is a map from each configuration file filename for the - // module to a raw byte representation of the source file contents. - Files map[string][]byte - - // SourceAddr is the source address given for this module in configuration. - SourceAddr string `json:"Source"` - - // Version is the version of the module that is installed, or nil if - // the module is installed from a source that does not support versions. - Version *version.Version `json:"-"` -} - -// moduleManifest constructs a module manifest based on the contents of -// the receiving snapshot. -func (s *Snapshot) moduleManifest() modsdir.Manifest { - ret := make(modsdir.Manifest) - - for k, modSnap := range s.Modules { - ret[k] = modsdir.Record{ - Key: k, - Dir: modSnap.Dir, - SourceAddr: modSnap.SourceAddr, - Version: modSnap.Version, - } - } - - return ret -} - -// makeModuleWalkerSnapshot creates a configs.ModuleWalker that will exhibit -// the same lookup behaviors as l.moduleWalkerLoad but will additionally write -// source files from the referenced modules into the given snapshot. -func (l *Loader) makeModuleWalkerSnapshot(snap *Snapshot) configs.ModuleWalker { - return configs.ModuleWalkerFunc( - func(req *configs.ModuleRequest) (*configs.Module, *version.Version, hcl.Diagnostics) { - mod, v, diags := l.moduleWalkerLoad(req) - if diags.HasErrors() { - return mod, v, diags - } - - key := l.modules.manifest.ModuleKey(req.Path) - record, exists := l.modules.manifest[key] - - if !exists { - // Should never happen, since otherwise moduleWalkerLoader would've - // returned an error and we would've returned already. - panic(fmt.Sprintf("module %s is not present in manifest", key)) - } - - addDiags := l.addModuleToSnapshot(snap, key, record.Dir, record.SourceAddr, record.Version) - diags = append(diags, addDiags...) - - return mod, v, diags - }, - ) -} - -func (l *Loader) addModuleToSnapshot(snap *Snapshot, key string, dir string, sourceAddr string, v *version.Version) hcl.Diagnostics { - var diags hcl.Diagnostics - - primaryFiles, overrideFiles, moreDiags := l.parser.ConfigDirFiles(dir) - if moreDiags.HasErrors() { - // Any diagnostics we get here should be already present - // in diags, so it's weird if we get here but we'll allow it - // and return a general error message in that case. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Failed to read directory for module", - Detail: fmt.Sprintf("The source directory %s could not be read", dir), - }) - return diags - } - - snapMod := &SnapshotModule{ - Dir: dir, - Files: map[string][]byte{}, - SourceAddr: sourceAddr, - Version: v, - } - - files := make([]string, 0, len(primaryFiles)+len(overrideFiles)) - files = append(files, primaryFiles...) - files = append(files, overrideFiles...) - sources := l.Sources() // should be populated with all the files we need by now - for _, filePath := range files { - filename := filepath.Base(filePath) - src, exists := sources[filePath] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing source file for snapshot", - Detail: fmt.Sprintf("The source code for file %s could not be found to produce a configuration snapshot.", filePath), - }) - continue - } - snapMod.Files[filepath.Clean(filename)] = src - } - - snap.Modules[key] = snapMod - - return diags -} - -// snapshotFS is an implementation of afero.Fs that reads from a snapshot. -// -// This is not intended as a general-purpose filesystem implementation. Instead, -// it just supports the minimal functionality required to support the -// configuration loader and parser as an implementation detail of creating -// a loader from a snapshot. -type snapshotFS struct { - snap *Snapshot -} - -var _ afero.Fs = snapshotFS{} - -func (fs snapshotFS) Create(name string) (afero.File, error) { - return nil, fmt.Errorf("cannot create file inside configuration snapshot") -} - -func (fs snapshotFS) Mkdir(name string, perm os.FileMode) error { - return fmt.Errorf("cannot create directory inside configuration snapshot") -} - -func (fs snapshotFS) MkdirAll(name string, perm os.FileMode) error { - return fmt.Errorf("cannot create directories inside configuration snapshot") -} - -func (fs snapshotFS) Open(name string) (afero.File, error) { - - // Our "filesystem" is sparsely populated only with the directories - // mentioned by modules in our snapshot, so the high-level process - // for opening a file is: - // - Find the module snapshot corresponding to the containing directory - // - Find the file within that snapshot - // - Wrap the resulting byte slice in a snapshotFile to return - // - // The other possibility handled here is if the given name is for the - // module directory itself, in which case we'll return a snapshotDir - // instead. - // - // This function doesn't try to be incredibly robust in supporting - // different permutations of paths, etc because in practice we only - // need to support the path forms that our own loader and parser will - // generate. - - dir := filepath.Dir(name) - fn := filepath.Base(name) - directDir := filepath.Clean(name) - - // First we'll check to see if this is an exact path for a module directory. - // We need to do this first (rather than as part of the next loop below) - // because a module in a child directory of another module can otherwise - // appear to be a file in that parent directory. - for _, candidate := range fs.snap.Modules { - modDir := filepath.Clean(candidate.Dir) - if modDir == directDir { - // We've matched the module directory itself - filenames := make([]string, 0, len(candidate.Files)) - for n := range candidate.Files { - filenames = append(filenames, n) - } - sort.Strings(filenames) - return snapshotDir{ - filenames: filenames, - }, nil - } - } - - // If we get here then the given path isn't a module directory exactly, so - // we'll treat it as a file path and try to find a module directory it - // could be located in. - var modSnap *SnapshotModule - for _, candidate := range fs.snap.Modules { - modDir := filepath.Clean(candidate.Dir) - if modDir == dir { - modSnap = candidate - break - } - } - if modSnap == nil { - return nil, os.ErrNotExist - } - - src, exists := modSnap.Files[fn] - if !exists { - return nil, os.ErrNotExist - } - - return &snapshotFile{ - src: src, - }, nil -} - -func (fs snapshotFS) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { - return fs.Open(name) -} - -func (fs snapshotFS) Remove(name string) error { - return fmt.Errorf("cannot remove file inside configuration snapshot") -} - -func (fs snapshotFS) RemoveAll(path string) error { - return fmt.Errorf("cannot remove files inside configuration snapshot") -} - -func (fs snapshotFS) Rename(old, new string) error { - return fmt.Errorf("cannot rename file inside configuration snapshot") -} - -func (fs snapshotFS) Stat(name string) (os.FileInfo, error) { - f, err := fs.Open(name) - if err != nil { - return nil, err - } - _, isDir := f.(snapshotDir) - return snapshotFileInfo{ - name: filepath.Base(name), - isDir: isDir, - }, nil -} - -func (fs snapshotFS) Name() string { - return "ConfigSnapshotFS" -} - -func (fs snapshotFS) Chmod(name string, mode os.FileMode) error { - return fmt.Errorf("cannot set file mode inside configuration snapshot") -} - -func (fs snapshotFS) Chtimes(name string, atime, mtime time.Time) error { - return fmt.Errorf("cannot set file times inside configuration snapshot") -} - -type snapshotFile struct { - snapshotFileStub - src []byte - at int64 -} - -var _ afero.File = (*snapshotFile)(nil) - -func (f *snapshotFile) Read(p []byte) (n int, err error) { - if len(p) > 0 && f.at == int64(len(f.src)) { - return 0, io.EOF - } - if f.at > int64(len(f.src)) { - return 0, io.ErrUnexpectedEOF - } - if int64(len(f.src))-f.at >= int64(len(p)) { - n = len(p) - } else { - n = int(int64(len(f.src)) - f.at) - } - copy(p, f.src[f.at:f.at+int64(n)]) - f.at += int64(n) - return -} - -func (f *snapshotFile) ReadAt(p []byte, off int64) (n int, err error) { - f.at = off - return f.Read(p) -} - -func (f *snapshotFile) Seek(offset int64, whence int) (int64, error) { - switch whence { - case 0: - f.at = offset - case 1: - f.at += offset - case 2: - f.at = int64(len(f.src)) + offset - } - return f.at, nil -} - -type snapshotDir struct { - snapshotFileStub - filenames []string - at int -} - -var _ afero.File = snapshotDir{} - -func (f snapshotDir) Readdir(count int) ([]os.FileInfo, error) { - names, err := f.Readdirnames(count) - if err != nil { - return nil, err - } - ret := make([]os.FileInfo, len(names)) - for i, name := range names { - ret[i] = snapshotFileInfo{ - name: name, - isDir: false, - } - } - return ret, nil -} - -func (f snapshotDir) Readdirnames(count int) ([]string, error) { - var outLen int - names := f.filenames[f.at:] - if count > 0 { - if len(names) < count { - outLen = len(names) - } else { - outLen = count - } - if len(names) == 0 { - return nil, io.EOF - } - } else { - outLen = len(names) - } - f.at += outLen - - return names[:outLen], nil -} - -// snapshotFileInfo is a minimal implementation of os.FileInfo to support our -// virtual filesystem from snapshots. -type snapshotFileInfo struct { - name string - isDir bool -} - -var _ os.FileInfo = snapshotFileInfo{} - -func (fi snapshotFileInfo) Name() string { - return fi.name -} - -func (fi snapshotFileInfo) Size() int64 { - // In practice, our parser and loader never call Size - return -1 -} - -func (fi snapshotFileInfo) Mode() os.FileMode { - return os.ModePerm -} - -func (fi snapshotFileInfo) ModTime() time.Time { - return time.Now() -} - -func (fi snapshotFileInfo) IsDir() bool { - return fi.isDir -} - -func (fi snapshotFileInfo) Sys() interface{} { - return nil -} - -type snapshotFileStub struct{} - -func (f snapshotFileStub) Close() error { - return nil -} - -func (f snapshotFileStub) Read(p []byte) (n int, err error) { - return 0, fmt.Errorf("cannot read") -} - -func (f snapshotFileStub) ReadAt(p []byte, off int64) (n int, err error) { - return 0, fmt.Errorf("cannot read") -} - -func (f snapshotFileStub) Seek(offset int64, whence int) (int64, error) { - return 0, fmt.Errorf("cannot seek") -} - -func (f snapshotFileStub) Write(p []byte) (n int, err error) { - return f.WriteAt(p, 0) -} - -func (f snapshotFileStub) WriteAt(p []byte, off int64) (n int, err error) { - return 0, fmt.Errorf("cannot write to file in snapshot") -} - -func (f snapshotFileStub) WriteString(s string) (n int, err error) { - return 0, fmt.Errorf("cannot write to file in snapshot") -} - -func (f snapshotFileStub) Name() string { - // in practice, the loader and parser never use this - return "" -} - -func (f snapshotFileStub) Readdir(count int) ([]os.FileInfo, error) { - return nil, fmt.Errorf("cannot use Readdir on a file") -} - -func (f snapshotFileStub) Readdirnames(count int) ([]string, error) { - return nil, fmt.Errorf("cannot use Readdir on a file") -} - -func (f snapshotFileStub) Stat() (os.FileInfo, error) { - return nil, fmt.Errorf("cannot stat") -} - -func (f snapshotFileStub) Sync() error { - return nil -} - -func (f snapshotFileStub) Truncate(size int64) error { - return fmt.Errorf("cannot write to file in snapshot") -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/module_mgr.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/module_mgr.go deleted file mode 100644 index 797f50d2423..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/module_mgr.go +++ /dev/null @@ -1,62 +0,0 @@ -package configload - -import ( - "os" - "path/filepath" - - "github.com/hashicorp/terraform-plugin-sdk/internal/modsdir" - "github.com/hashicorp/terraform-plugin-sdk/internal/registry" - "github.com/hashicorp/terraform-svchost/disco" - "github.com/spf13/afero" -) - -type moduleMgr struct { - FS afero.Afero - - // CanInstall is true for a module manager that can support installation. - // - // This must be set only if FS is an afero.OsFs, because the installer - // (which uses go-getter) is not aware of the virtual filesystem - // abstraction and will always write into the "real" filesystem. - CanInstall bool - - // Dir is the path where descendent modules are (or will be) installed. - Dir string - - // Services is a service discovery client that will be used to find - // remote module registry endpoints. This object may be pre-loaded with - // cached discovery information. - Services *disco.Disco - - // Registry is a client for the module registry protocol, which is used - // when a module is requested from a registry source. - Registry *registry.Client - - // manifest tracks the currently-installed modules for this manager. - // - // The loader may read this. Only the installer may write to it, and - // after a set of updates are completed the installer must call - // writeModuleManifestSnapshot to persist a snapshot of the manifest - // to disk for use on subsequent runs. - manifest modsdir.Manifest -} - -func (m *moduleMgr) manifestSnapshotPath() string { - return filepath.Join(m.Dir, modsdir.ManifestSnapshotFilename) -} - -// readModuleManifestSnapshot loads a manifest snapshot from the filesystem. -func (m *moduleMgr) readModuleManifestSnapshot() error { - r, err := m.FS.Open(m.manifestSnapshotPath()) - if err != nil { - if os.IsNotExist(err) { - // We'll treat a missing file as an empty manifest - m.manifest = make(modsdir.Manifest) - return nil - } - return err - } - - m.manifest, err = modsdir.ReadManifestSnapshot(r) - return err -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/testing.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/testing.go deleted file mode 100644 index 86ca9d10b77..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/testing.go +++ /dev/null @@ -1,43 +0,0 @@ -package configload - -import ( - "io/ioutil" - "os" - "testing" -) - -// NewLoaderForTests is a variant of NewLoader that is intended to be more -// convenient for unit tests. -// -// The loader's modules directory is a separate temporary directory created -// for each call. Along with the created loader, this function returns a -// cleanup function that should be called before the test completes in order -// to remove that temporary directory. -// -// In the case of any errors, t.Fatal (or similar) will be called to halt -// execution of the test, so the calling test does not need to handle errors -// itself. -func NewLoaderForTests(t *testing.T) (*Loader, func()) { - t.Helper() - - modulesDir, err := ioutil.TempDir("", "tf-configs") - if err != nil { - t.Fatalf("failed to create temporary modules dir: %s", err) - return nil, func() {} - } - - cleanup := func() { - os.RemoveAll(modulesDir) - } - - loader, err := NewLoader(&Config{ - ModulesDir: modulesDir, - }) - if err != nil { - cleanup() - t.Fatalf("failed to create config loader: %s", err) - return nil, func() {} - } - - return loader, cleanup -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/decoder_spec.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/decoder_spec.go deleted file mode 100644 index 2c21ca5e57a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/decoder_spec.go +++ /dev/null @@ -1,123 +0,0 @@ -package configschema - -import ( - "github.com/hashicorp/hcl/v2/hcldec" -) - -var mapLabelNames = []string{"key"} - -// DecoderSpec returns a hcldec.Spec that can be used to decode a HCL Body -// using the facilities in the hcldec package. -// -// The returned specification is guaranteed to return a value of the same type -// returned by method ImpliedType, but it may contain null values if any of the -// block attributes are defined as optional and/or computed respectively. -func (b *Block) DecoderSpec() hcldec.Spec { - ret := hcldec.ObjectSpec{} - if b == nil { - return ret - } - - for name, attrS := range b.Attributes { - ret[name] = attrS.decoderSpec(name) - } - - for name, blockS := range b.BlockTypes { - if _, exists := ret[name]; exists { - // This indicates an invalid schema, since it's not valid to - // define both an attribute and a block type of the same name. - // However, we don't raise this here since it's checked by - // InternalValidate. - continue - } - - childSpec := blockS.Block.DecoderSpec() - - // We can only validate 0 or 1 for MinItems, because a dynamic block - // may satisfy any number of min items while only having a single - // block in the config. We cannot validate MaxItems because a - // configuration may have any number of dynamic blocks - minItems := 0 - if blockS.MinItems > 1 { - minItems = 1 - } - - switch blockS.Nesting { - case NestingSingle, NestingGroup: - ret[name] = &hcldec.BlockSpec{ - TypeName: name, - Nested: childSpec, - Required: blockS.MinItems == 1, - } - if blockS.Nesting == NestingGroup { - ret[name] = &hcldec.DefaultSpec{ - Primary: ret[name], - Default: &hcldec.LiteralSpec{ - Value: blockS.EmptyValue(), - }, - } - } - case NestingList: - // We prefer to use a list where possible, since it makes our - // implied type more complete, but if there are any - // dynamically-typed attributes inside we must use a tuple - // instead, at the expense of our type then not being predictable. - if blockS.Block.ImpliedType().HasDynamicTypes() { - ret[name] = &hcldec.BlockTupleSpec{ - TypeName: name, - Nested: childSpec, - MinItems: minItems, - } - } else { - ret[name] = &hcldec.BlockListSpec{ - TypeName: name, - Nested: childSpec, - MinItems: minItems, - } - } - case NestingSet: - // We forbid dynamically-typed attributes inside NestingSet in - // InternalValidate, so we don't do anything special to handle - // that here. (There is no set analog to tuple and object types, - // because cty's set implementation depends on knowing the static - // type in order to properly compute its internal hashes.) - ret[name] = &hcldec.BlockSetSpec{ - TypeName: name, - Nested: childSpec, - MinItems: minItems, - } - case NestingMap: - // We prefer to use a list where possible, since it makes our - // implied type more complete, but if there are any - // dynamically-typed attributes inside we must use a tuple - // instead, at the expense of our type then not being predictable. - if blockS.Block.ImpliedType().HasDynamicTypes() { - ret[name] = &hcldec.BlockObjectSpec{ - TypeName: name, - Nested: childSpec, - LabelNames: mapLabelNames, - } - } else { - ret[name] = &hcldec.BlockMapSpec{ - TypeName: name, - Nested: childSpec, - LabelNames: mapLabelNames, - } - } - default: - // Invalid nesting type is just ignored. It's checked by - // InternalValidate. - continue - } - } - - return ret -} - -func (a *Attribute) decoderSpec(name string) hcldec.Spec { - return &hcldec.AttrSpec{ - Name: name, - Type: a.Type, - Required: a.Required, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/implied_type.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/implied_type.go deleted file mode 100644 index 51f51cebcc8..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/implied_type.go +++ /dev/null @@ -1,21 +0,0 @@ -package configschema - -import ( - "github.com/hashicorp/hcl/v2/hcldec" - "github.com/zclconf/go-cty/cty" -) - -// ImpliedType returns the cty.Type that would result from decoding a -// configuration block using the receiving block schema. -// -// ImpliedType always returns a result, even if the given schema is -// inconsistent. Code that creates configschema.Block objects should be -// tested using the InternalValidate method to detect any inconsistencies -// that would cause this method to fall back on defaults and assumptions. -func (b *Block) ImpliedType() cty.Type { - if b == nil { - return cty.EmptyObject - } - - return hcldec.ImpliedType(b.DecoderSpec()) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/internal_validate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/internal_validate.go deleted file mode 100644 index ebf1abbab16..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/internal_validate.go +++ /dev/null @@ -1,105 +0,0 @@ -package configschema - -import ( - "fmt" - "regexp" - - "github.com/zclconf/go-cty/cty" - - multierror "github.com/hashicorp/go-multierror" -) - -var validName = regexp.MustCompile(`^[a-z0-9_]+$`) - -// InternalValidate returns an error if the receiving block and its child -// schema definitions have any consistencies with the documented rules for -// valid schema. -// -// This is intended to be used within unit tests to detect when a given -// schema is invalid. -func (b *Block) InternalValidate() error { - if b == nil { - return fmt.Errorf("top-level block schema is nil") - } - return b.internalValidate("", nil) - -} - -func (b *Block) internalValidate(prefix string, err error) error { - for name, attrS := range b.Attributes { - if attrS == nil { - err = multierror.Append(err, fmt.Errorf("%s%s: attribute schema is nil", prefix, name)) - continue - } - if !validName.MatchString(name) { - err = multierror.Append(err, fmt.Errorf("%s%s: name may contain only lowercase letters, digits and underscores", prefix, name)) - } - if attrS.Optional == false && attrS.Required == false && attrS.Computed == false { - err = multierror.Append(err, fmt.Errorf("%s%s: must set Optional, Required or Computed", prefix, name)) - } - if attrS.Optional && attrS.Required { - err = multierror.Append(err, fmt.Errorf("%s%s: cannot set both Optional and Required", prefix, name)) - } - if attrS.Computed && attrS.Required { - err = multierror.Append(err, fmt.Errorf("%s%s: cannot set both Computed and Required", prefix, name)) - } - if attrS.Type == cty.NilType { - err = multierror.Append(err, fmt.Errorf("%s%s: Type must be set to something other than cty.NilType", prefix, name)) - } - } - - for name, blockS := range b.BlockTypes { - if blockS == nil { - err = multierror.Append(err, fmt.Errorf("%s%s: block schema is nil", prefix, name)) - continue - } - - if _, isAttr := b.Attributes[name]; isAttr { - err = multierror.Append(err, fmt.Errorf("%s%s: name defined as both attribute and child block type", prefix, name)) - } else if !validName.MatchString(name) { - err = multierror.Append(err, fmt.Errorf("%s%s: name may contain only lowercase letters, digits and underscores", prefix, name)) - } - - if blockS.MinItems < 0 || blockS.MaxItems < 0 { - err = multierror.Append(err, fmt.Errorf("%s%s: MinItems and MaxItems must both be greater than zero", prefix, name)) - } - - switch blockS.Nesting { - case NestingSingle: - switch { - case blockS.MinItems != blockS.MaxItems: - err = multierror.Append(err, fmt.Errorf("%s%s: MinItems and MaxItems must match in NestingSingle mode", prefix, name)) - case blockS.MinItems < 0 || blockS.MinItems > 1: - err = multierror.Append(err, fmt.Errorf("%s%s: MinItems and MaxItems must be set to either 0 or 1 in NestingSingle mode", prefix, name)) - } - case NestingGroup: - if blockS.MinItems != 0 || blockS.MaxItems != 0 { - err = multierror.Append(err, fmt.Errorf("%s%s: MinItems and MaxItems cannot be used in NestingGroup mode", prefix, name)) - } - case NestingList, NestingSet: - if blockS.MinItems > blockS.MaxItems && blockS.MaxItems != 0 { - err = multierror.Append(err, fmt.Errorf("%s%s: MinItems must be less than or equal to MaxItems in %s mode", prefix, name, blockS.Nesting)) - } - if blockS.Nesting == NestingSet { - ety := blockS.Block.ImpliedType() - if ety.HasDynamicTypes() { - // This is not permitted because the HCL (cty) set implementation - // needs to know the exact type of set elements in order to - // properly hash them, and so can't support mixed types. - err = multierror.Append(err, fmt.Errorf("%s%s: NestingSet blocks may not contain attributes of cty.DynamicPseudoType", prefix, name)) - } - } - case NestingMap: - if blockS.MinItems != 0 || blockS.MaxItems != 0 { - err = multierror.Append(err, fmt.Errorf("%s%s: MinItems and MaxItems must both be 0 in NestingMap mode", prefix, name)) - } - default: - err = multierror.Append(err, fmt.Errorf("%s%s: invalid nesting mode %s", prefix, name, blockS.Nesting)) - } - - subPrefix := prefix + name + "." - err = blockS.Block.internalValidate(subPrefix, err) - } - - return err -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/none_required.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/none_required.go deleted file mode 100644 index 0be3b8fa357..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/none_required.go +++ /dev/null @@ -1,38 +0,0 @@ -package configschema - -// NoneRequired returns a deep copy of the receiver with any required -// attributes translated to optional. -func (b *Block) NoneRequired() *Block { - ret := &Block{} - - if b.Attributes != nil { - ret.Attributes = make(map[string]*Attribute, len(b.Attributes)) - } - for name, attrS := range b.Attributes { - ret.Attributes[name] = attrS.forceOptional() - } - - if b.BlockTypes != nil { - ret.BlockTypes = make(map[string]*NestedBlock, len(b.BlockTypes)) - } - for name, blockS := range b.BlockTypes { - ret.BlockTypes[name] = blockS.noneRequired() - } - - return ret -} - -func (b *NestedBlock) noneRequired() *NestedBlock { - ret := *b - ret.Block = *(ret.Block.NoneRequired()) - ret.MinItems = 0 - ret.MaxItems = 0 - return &ret -} - -func (a *Attribute) forceOptional() *Attribute { - ret := *a - ret.Optional = true - ret.Required = false - return &ret -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/schema.go deleted file mode 100644 index b41a3096889..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/schema.go +++ /dev/null @@ -1,155 +0,0 @@ -package configschema - -import ( - "github.com/zclconf/go-cty/cty" -) - -// StringKind represents the format a string is in. -type StringKind int - -const ( - // StringPlain indicates a string is plain-text and requires no processing for display. - StringPlain StringKind = iota - // StringMarkdown indicates a string is in markdown format and may - // require additional processing to display. - StringMarkdown -) - -// Block represents a configuration block. -// -// "Block" here is a logical grouping construct, though it happens to map -// directly onto the physical block syntax of Terraform's native configuration -// syntax. It may be a more a matter of convention in other syntaxes, such as -// JSON. -// -// When converted to a value, a Block always becomes an instance of an object -// type derived from its defined attributes and nested blocks -type Block struct { - // Attributes describes any attributes that may appear directly inside - // the block. - Attributes map[string]*Attribute - - // BlockTypes describes any nested block types that may appear directly - // inside the block. - BlockTypes map[string]*NestedBlock - - // Description and DescriptionKind contain a user facing description of the block - // and the format of that string. - Description string - DescriptionKind StringKind - - // Deprecated indicates whether the block has been marked as deprecated in the - // provider and usage should be discouraged. - Deprecated bool -} - -// Attribute represents a configuration attribute, within a block. -type Attribute struct { - // Type is a type specification that the attribute's value must conform to. - Type cty.Type - - // Description is an English-language description of the purpose and - // usage of the attribute. A description should be concise and use only - // one or two sentences, leaving full definition to longer-form - // documentation defined elsewhere. - Description string - DescriptionKind StringKind - - // Required, if set to true, specifies that an omitted or null value is - // not permitted. - Required bool - - // Optional, if set to true, specifies that an omitted or null value is - // permitted. This field conflicts with Required. - Optional bool - - // Computed, if set to true, specifies that the value comes from the - // provider rather than from configuration. If combined with Optional, - // then the config may optionally provide an overridden value. - Computed bool - - // Sensitive, if set to true, indicates that an attribute may contain - // sensitive information. - // - // At present nothing is done with this information, but callers are - // encouraged to set it where appropriate so that it may be used in the - // future to help Terraform mask sensitive information. (Terraform - // currently achieves this in a limited sense via other mechanisms.) - Sensitive bool - - // Deprecated indicates whether the attribute has been marked as deprecated in the - // provider and usage should be discouraged. - Deprecated bool -} - -// NestedBlock represents the embedding of one block within another. -type NestedBlock struct { - // Block is the description of the block that's nested. - Block - - // Nesting provides the nesting mode for the child block, which determines - // how many instances of the block are allowed, how many labels it expects, - // and how the resulting data will be converted into a data structure. - Nesting NestingMode - - // MinItems and MaxItems set, for the NestingList and NestingSet nesting - // modes, lower and upper limits on the number of child blocks allowed - // of the given type. If both are left at zero, no limit is applied. - // - // As a special case, both values can be set to 1 for NestingSingle in - // order to indicate that a particular single block is required. - // - // These fields are ignored for other nesting modes and must both be left - // at zero. - MinItems, MaxItems int -} - -// NestingMode is an enumeration of modes for nesting blocks inside other -// blocks. -type NestingMode int - -//go:generate go run golang.org/x/tools/cmd/stringer -type=NestingMode - -const ( - nestingModeInvalid NestingMode = iota - - // NestingSingle indicates that only a single instance of a given - // block type is permitted, with no labels, and its content should be - // provided directly as an object value. - NestingSingle - - // NestingGroup is similar to NestingSingle in that it calls for only a - // single instance of a given block type with no labels, but it additonally - // guarantees that its result will never be null, even if the block is - // absent, and instead the nested attributes and blocks will be treated - // as absent in that case. (Any required attributes or blocks within the - // nested block are not enforced unless the block is explicitly present - // in the configuration, so they are all effectively optional when the - // block is not present.) - // - // This is useful for the situation where a remote API has a feature that - // is always enabled but has a group of settings related to that feature - // that themselves have default values. By using NestingGroup instead of - // NestingSingle in that case, generated plans will show the block as - // present even when not present in configuration, thus allowing any - // default values within to be displayed to the user. - NestingGroup - - // NestingList indicates that multiple blocks of the given type are - // permitted, with no labels, and that their corresponding objects should - // be provided in a list. - NestingList - - // NestingSet indicates that multiple blocks of the given type are - // permitted, with no labels, and that their corresponding objects should - // be provided in a set. - NestingSet - - // NestingMap indicates that multiple blocks of the given type are - // permitted, each with a single label, and that their corresponding - // objects should be provided in a map whose keys are the labels. - // - // It's an error, therefore, to use the same label value on multiple - // blocks. - NestingMap -) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/validate_traversal.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/validate_traversal.go deleted file mode 100644 index 446705bafbe..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/validate_traversal.go +++ /dev/null @@ -1,173 +0,0 @@ -package configschema - -import ( - "fmt" - "sort" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/helper/didyoumean" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// StaticValidateTraversal checks whether the given traversal (which must be -// relative) refers to a construct in the receiving schema, returning error -// diagnostics if any problems are found. -// -// This method is "optimistic" in that it will not return errors for possible -// problems that cannot be detected statically. It is possible that an -// traversal which passed static validation will still fail when evaluated. -func (b *Block) StaticValidateTraversal(traversal hcl.Traversal) tfdiags.Diagnostics { - if !traversal.IsRelative() { - panic("StaticValidateTraversal on absolute traversal") - } - if len(traversal) == 0 { - return nil - } - - var diags tfdiags.Diagnostics - - next := traversal[0] - after := traversal[1:] - - var name string - switch step := next.(type) { - case hcl.TraverseAttr: - name = step.Name - case hcl.TraverseIndex: - // No other traversal step types are allowed directly at a block. - // If it looks like the user was trying to use index syntax to - // access an attribute then we'll produce a specialized message. - key := step.Key - if key.Type() == cty.String && key.IsKnown() && !key.IsNull() { - maybeName := key.AsString() - if hclsyntax.ValidIdentifier(maybeName) { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid index operation`, - Detail: fmt.Sprintf(`Only attribute access is allowed here. Did you mean to access attribute %q using the dot operator?`, maybeName), - Subject: &step.SrcRange, - }) - return diags - } - } - // If it looks like some other kind of index then we'll use a generic error. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid index operation`, - Detail: `Only attribute access is allowed here, using the dot operator.`, - Subject: &step.SrcRange, - }) - return diags - default: - // No other traversal types should appear in a normal valid traversal, - // but we'll handle this with a generic error anyway to be robust. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid operation`, - Detail: `Only attribute access is allowed here, using the dot operator.`, - Subject: next.SourceRange().Ptr(), - }) - return diags - } - - if attrS, exists := b.Attributes[name]; exists { - // For attribute validation we will just apply the rest of the - // traversal to an unknown value of the attribute type and pass - // through HCL's own errors, since we don't want to replicate all of - // HCL's type checking rules here. - val := cty.UnknownVal(attrS.Type) - _, hclDiags := after.TraverseRel(val) - diags = diags.Append(hclDiags) - return diags - } - - if blockS, exists := b.BlockTypes[name]; exists { - moreDiags := blockS.staticValidateTraversal(name, after) - diags = diags.Append(moreDiags) - return diags - } - - // If we get here then the name isn't valid at all. We'll collect up - // all of the names that _are_ valid to use as suggestions. - var suggestions []string - for name := range b.Attributes { - suggestions = append(suggestions, name) - } - for name := range b.BlockTypes { - suggestions = append(suggestions, name) - } - sort.Strings(suggestions) - suggestion := didyoumean.NameSuggestion(name, suggestions) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Unsupported attribute`, - Detail: fmt.Sprintf(`This object has no argument, nested block, or exported attribute named %q.%s`, name, suggestion), - Subject: next.SourceRange().Ptr(), - }) - - return diags -} - -func (b *NestedBlock) staticValidateTraversal(typeName string, traversal hcl.Traversal) tfdiags.Diagnostics { - if b.Nesting == NestingSingle || b.Nesting == NestingGroup { - // Single blocks are easy: just pass right through. - return b.Block.StaticValidateTraversal(traversal) - } - - if len(traversal) == 0 { - // It's always valid to access a nested block's attribute directly. - return nil - } - - var diags tfdiags.Diagnostics - next := traversal[0] - after := traversal[1:] - - switch b.Nesting { - - case NestingSet: - // Can't traverse into a set at all, since it does not have any keys - // to index with. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Cannot index a set value`, - Detail: fmt.Sprintf(`Block type %q is represented by a set of objects, and set elements do not have addressable keys. To find elements matching specific criteria, use a "for" expression with an "if" clause.`, typeName), - Subject: next.SourceRange().Ptr(), - }) - return diags - - case NestingList: - if _, ok := next.(hcl.TraverseIndex); ok { - moreDiags := b.Block.StaticValidateTraversal(after) - diags = diags.Append(moreDiags) - } else { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid operation`, - Detail: fmt.Sprintf(`Block type %q is represented by a list of objects, so it must be indexed using a numeric key, like .%s[0].`, typeName, typeName), - Subject: next.SourceRange().Ptr(), - }) - } - return diags - - case NestingMap: - // Both attribute and index steps are valid for maps, so we'll just - // pass through here and let normal evaluation catch an - // incorrectly-typed index key later, if present. - moreDiags := b.Block.StaticValidateTraversal(after) - diags = diags.Append(moreDiags) - return diags - - default: - // Invalid nesting type is just ignored. It's checked by - // InternalValidate. (Note that we handled NestingSingle separately - // back at the start of this function.) - return nil - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/depends_on.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/depends_on.go deleted file mode 100644 index 036c2d6c305..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/depends_on.go +++ /dev/null @@ -1,23 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl/v2" -) - -func decodeDependsOn(attr *hcl.Attribute) ([]hcl.Traversal, hcl.Diagnostics) { - var ret []hcl.Traversal - exprs, diags := hcl.ExprList(attr.Expr) - - for _, expr := range exprs { - expr, shimDiags := shimTraversalInString(expr, false) - diags = append(diags, shimDiags...) - - traversal, travDiags := hcl.AbsTraversalForExpr(expr) - diags = append(diags, travDiags...) - if len(traversal) != 0 { - ret = append(ret, traversal) - } - } - - return ret, diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/doc.go deleted file mode 100644 index f01eb79f400..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -// Package configs contains types that represent Terraform configurations and -// the different elements thereof. -// -// The functionality in this package can be used for some static analyses of -// Terraform configurations, but this package generally exposes representations -// of the configuration source code rather than the result of evaluating these -// objects. The sibling package "lang" deals with evaluation of structures -// and expressions in the configuration. -// -// Due to its close relationship with HCL, this package makes frequent use -// of types from the HCL API, including raw HCL diagnostic messages. Such -// diagnostics can be converted into Terraform-flavored diagnostics, if needed, -// using functions in the sibling package tfdiags. -// -// The Parser type is the main entry-point into this package. The LoadConfigDir -// method can be used to load a single module directory, and then a full -// configuration (including any descendent modules) can be produced using -// the top-level BuildConfig method. -package configs diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/paths.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/paths.go deleted file mode 100644 index 3403c026bf8..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/paths.go +++ /dev/null @@ -1,276 +0,0 @@ -package hcl2shim - -import ( - "fmt" - "reflect" - "strconv" - "strings" - - "github.com/zclconf/go-cty/cty" -) - -// RequiresReplace takes a list of flatmapped paths from a -// InstanceDiff.Attributes along with the corresponding cty.Type, and returns -// the list of the cty.Paths that are flagged as causing the resource -// replacement (RequiresNew). -// This will filter out redundant paths, paths that refer to flatmapped indexes -// (e.g. "#", "%"), and will return any changes within a set as the path to the -// set itself. -func RequiresReplace(attrs []string, ty cty.Type) ([]cty.Path, error) { - var paths []cty.Path - - for _, attr := range attrs { - p, err := requiresReplacePath(attr, ty) - if err != nil { - return nil, err - } - - paths = append(paths, p) - } - - // now trim off any trailing paths that aren't GetAttrSteps, since only an - // attribute itself can require replacement - paths = trimPaths(paths) - - // There may be redundant paths due to set elements or index attributes - // Do some ugly n^2 filtering, but these are always fairly small sets. - for i := 0; i < len(paths)-1; i++ { - for j := i + 1; j < len(paths); j++ { - if reflect.DeepEqual(paths[i], paths[j]) { - // swap the tail and slice it off - paths[j], paths[len(paths)-1] = paths[len(paths)-1], paths[j] - paths = paths[:len(paths)-1] - j-- - } - } - } - - return paths, nil -} - -// trimPaths removes any trailing steps that aren't of type GetAttrSet, since -// only an attribute itself can require replacement -func trimPaths(paths []cty.Path) []cty.Path { - var trimmed []cty.Path - for _, path := range paths { - path = trimPath(path) - if len(path) > 0 { - trimmed = append(trimmed, path) - } - } - return trimmed -} - -func trimPath(path cty.Path) cty.Path { - for len(path) > 0 { - _, isGetAttr := path[len(path)-1].(cty.GetAttrStep) - if isGetAttr { - break - } - path = path[:len(path)-1] - } - return path -} - -// requiresReplacePath takes a key from a flatmap along with the cty.Type -// describing the structure, and returns the cty.Path that would be used to -// reference the nested value in the data structure. -// This is used specifically to record the RequiresReplace attributes from a -// ResourceInstanceDiff. -func requiresReplacePath(k string, ty cty.Type) (cty.Path, error) { - if k == "" { - return nil, nil - } - if !ty.IsObjectType() { - panic(fmt.Sprintf("requires replace path on non-object type: %#v", ty)) - } - - path, err := pathFromFlatmapKeyObject(k, ty.AttributeTypes()) - if err != nil { - return path, fmt.Errorf("[%s] %s", k, err) - } - return path, nil -} - -func pathSplit(p string) (string, string) { - parts := strings.SplitN(p, ".", 2) - head := parts[0] - rest := "" - if len(parts) > 1 { - rest = parts[1] - } - return head, rest -} - -func pathFromFlatmapKeyObject(key string, atys map[string]cty.Type) (cty.Path, error) { - k, rest := pathSplit(key) - - path := cty.Path{cty.GetAttrStep{Name: k}} - - ty, ok := atys[k] - if !ok { - return path, fmt.Errorf("attribute %q not found", k) - } - - if rest == "" { - return path, nil - } - - p, err := pathFromFlatmapKeyValue(rest, ty) - if err != nil { - return path, err - } - - return append(path, p...), nil -} - -func pathFromFlatmapKeyValue(key string, ty cty.Type) (cty.Path, error) { - var path cty.Path - var err error - - switch { - case ty.IsPrimitiveType(): - err = fmt.Errorf("invalid step %q with type %#v", key, ty) - case ty.IsObjectType(): - path, err = pathFromFlatmapKeyObject(key, ty.AttributeTypes()) - case ty.IsTupleType(): - path, err = pathFromFlatmapKeyTuple(key, ty.TupleElementTypes()) - case ty.IsMapType(): - path, err = pathFromFlatmapKeyMap(key, ty) - case ty.IsListType(): - path, err = pathFromFlatmapKeyList(key, ty) - case ty.IsSetType(): - path, err = pathFromFlatmapKeySet(key, ty) - default: - err = fmt.Errorf("unrecognized type: %s", ty.FriendlyName()) - } - - if err != nil { - return path, err - } - - return path, nil -} - -func pathFromFlatmapKeyTuple(key string, etys []cty.Type) (cty.Path, error) { - var path cty.Path - var err error - - k, rest := pathSplit(key) - - // we don't need to convert the index keys to paths - if k == "#" { - return path, nil - } - - idx, err := strconv.Atoi(k) - if err != nil { - return path, err - } - - path = cty.Path{cty.IndexStep{Key: cty.NumberIntVal(int64(idx))}} - - if idx >= len(etys) { - return path, fmt.Errorf("index %s out of range in %#v", key, etys) - } - - if rest == "" { - return path, nil - } - - ty := etys[idx] - - p, err := pathFromFlatmapKeyValue(rest, ty.ElementType()) - if err != nil { - return path, err - } - - return append(path, p...), nil -} - -func pathFromFlatmapKeyMap(key string, ty cty.Type) (cty.Path, error) { - var path cty.Path - var err error - - k, rest := key, "" - if !ty.ElementType().IsPrimitiveType() { - k, rest = pathSplit(key) - } - - // we don't need to convert the index keys to paths - if k == "%" { - return path, nil - } - - path = cty.Path{cty.IndexStep{Key: cty.StringVal(k)}} - - if rest == "" { - return path, nil - } - - p, err := pathFromFlatmapKeyValue(rest, ty.ElementType()) - if err != nil { - return path, err - } - - return append(path, p...), nil -} - -func pathFromFlatmapKeyList(key string, ty cty.Type) (cty.Path, error) { - var path cty.Path - var err error - - k, rest := pathSplit(key) - - // we don't need to convert the index keys to paths - if key == "#" { - return path, nil - } - - idx, err := strconv.Atoi(k) - if err != nil { - return path, err - } - - path = cty.Path{cty.IndexStep{Key: cty.NumberIntVal(int64(idx))}} - - if rest == "" { - return path, nil - } - - p, err := pathFromFlatmapKeyValue(rest, ty.ElementType()) - if err != nil { - return path, err - } - - return append(path, p...), nil -} - -func pathFromFlatmapKeySet(key string, ty cty.Type) (cty.Path, error) { - // once we hit a set, we can't return consistent paths, so just mark the - // set as a whole changed. - return nil, nil -} - -// FlatmapKeyFromPath returns the flatmap equivalent of the given cty.Path for -// use in generating legacy style diffs. -func FlatmapKeyFromPath(path cty.Path) string { - var parts []string - - for _, step := range path { - switch step := step.(type) { - case cty.GetAttrStep: - parts = append(parts, step.Name) - case cty.IndexStep: - switch ty := step.Key.Type(); { - case ty == cty.String: - parts = append(parts, step.Key.AsString()) - case ty == cty.Number: - i, _ := step.Key.AsBigFloat().Int64() - parts = append(parts, strconv.Itoa(int(i))) - } - } - } - - return strings.Join(parts, ".") -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module.go deleted file mode 100644 index 78223c3b867..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module.go +++ /dev/null @@ -1,404 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// Module is a container for a set of configuration constructs that are -// evaluated within a common namespace. -type Module struct { - // SourceDir is the filesystem directory that the module was loaded from. - // - // This is populated automatically only for configurations loaded with - // LoadConfigDir. If the parser is using a virtual filesystem then the - // path here will be in terms of that virtual filesystem. - - // Any other caller that constructs a module directly with NewModule may - // assign a suitable value to this attribute before using it for other - // purposes. It should be treated as immutable by all consumers of Module - // values. - SourceDir string - - CoreVersionConstraints []VersionConstraint - - Backend *Backend - ProviderConfigs map[string]*Provider - ProviderRequirements map[string][]VersionConstraint - - Variables map[string]*Variable - Locals map[string]*Local - Outputs map[string]*Output - - ModuleCalls map[string]*ModuleCall - - ManagedResources map[string]*Resource - DataResources map[string]*Resource -} - -// File describes the contents of a single configuration file. -// -// Individual files are not usually used alone, but rather combined together -// with other files (conventionally, those in the same directory) to produce -// a *Module, using NewModule. -// -// At the level of an individual file we represent directly the structural -// elements present in the file, without any attempt to detect conflicting -// declarations. A File object can therefore be used for some basic static -// analysis of individual elements, but must be built into a Module to detect -// duplicate declarations. -type File struct { - CoreVersionConstraints []VersionConstraint - - Backends []*Backend - ProviderConfigs []*Provider - ProviderRequirements []*ProviderRequirement - - Variables []*Variable - Locals []*Local - Outputs []*Output - - ModuleCalls []*ModuleCall - - ManagedResources []*Resource - DataResources []*Resource -} - -// NewModule takes a list of primary files and a list of override files and -// produces a *Module by combining the files together. -// -// If there are any conflicting declarations in the given files -- for example, -// if the same variable name is defined twice -- then the resulting module -// will be incomplete and error diagnostics will be returned. Careful static -// analysis of the returned Module is still possible in this case, but the -// module will probably not be semantically valid. -func NewModule(primaryFiles, overrideFiles []*File) (*Module, hcl.Diagnostics) { - var diags hcl.Diagnostics - mod := &Module{ - ProviderConfigs: map[string]*Provider{}, - ProviderRequirements: map[string][]VersionConstraint{}, - Variables: map[string]*Variable{}, - Locals: map[string]*Local{}, - Outputs: map[string]*Output{}, - ModuleCalls: map[string]*ModuleCall{}, - ManagedResources: map[string]*Resource{}, - DataResources: map[string]*Resource{}, - } - - for _, file := range primaryFiles { - fileDiags := mod.appendFile(file) - diags = append(diags, fileDiags...) - } - - for _, file := range overrideFiles { - fileDiags := mod.mergeFile(file) - diags = append(diags, fileDiags...) - } - - return mod, diags -} - -// ResourceByAddr returns the configuration for the resource with the given -// address, or nil if there is no such resource. -func (m *Module) ResourceByAddr(addr addrs.Resource) *Resource { - key := addr.String() - switch addr.Mode { - case addrs.ManagedResourceMode: - return m.ManagedResources[key] - case addrs.DataResourceMode: - return m.DataResources[key] - default: - return nil - } -} - -func (m *Module) appendFile(file *File) hcl.Diagnostics { - var diags hcl.Diagnostics - - for _, constraint := range file.CoreVersionConstraints { - // If there are any conflicting requirements then we'll catch them - // when we actually check these constraints. - m.CoreVersionConstraints = append(m.CoreVersionConstraints, constraint) - } - - for _, b := range file.Backends { - if m.Backend != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate backend configuration", - Detail: fmt.Sprintf("A module may have only one backend configuration. The backend was previously configured at %s.", m.Backend.DeclRange), - Subject: &b.DeclRange, - }) - continue - } - m.Backend = b - } - - for _, pc := range file.ProviderConfigs { - key := pc.moduleUniqueKey() - if existing, exists := m.ProviderConfigs[key]; exists { - if existing.Alias == "" { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate provider configuration", - Detail: fmt.Sprintf("A default (non-aliased) provider configuration for %q was already given at %s. If multiple configurations are required, set the \"alias\" argument for alternative configurations.", existing.Name, existing.DeclRange), - Subject: &pc.DeclRange, - }) - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate provider configuration", - Detail: fmt.Sprintf("A provider configuration for %q with alias %q was already given at %s. Each configuration for the same provider must have a distinct alias.", existing.Name, existing.Alias, existing.DeclRange), - Subject: &pc.DeclRange, - }) - } - continue - } - m.ProviderConfigs[key] = pc - } - - for _, reqd := range file.ProviderRequirements { - m.ProviderRequirements[reqd.Name] = append(m.ProviderRequirements[reqd.Name], reqd.Requirement) - } - - for _, v := range file.Variables { - if existing, exists := m.Variables[v.Name]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate variable declaration", - Detail: fmt.Sprintf("A variable named %q was already declared at %s. Variable names must be unique within a module.", existing.Name, existing.DeclRange), - Subject: &v.DeclRange, - }) - } - m.Variables[v.Name] = v - } - - for _, l := range file.Locals { - if existing, exists := m.Locals[l.Name]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate local value definition", - Detail: fmt.Sprintf("A local value named %q was already defined at %s. Local value names must be unique within a module.", existing.Name, existing.DeclRange), - Subject: &l.DeclRange, - }) - } - m.Locals[l.Name] = l - } - - for _, o := range file.Outputs { - if existing, exists := m.Outputs[o.Name]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate output definition", - Detail: fmt.Sprintf("An output named %q was already defined at %s. Output names must be unique within a module.", existing.Name, existing.DeclRange), - Subject: &o.DeclRange, - }) - } - m.Outputs[o.Name] = o - } - - for _, mc := range file.ModuleCalls { - if existing, exists := m.ModuleCalls[mc.Name]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate module call", - Detail: fmt.Sprintf("An module call named %q was already defined at %s. Module calls must have unique names within a module.", existing.Name, existing.DeclRange), - Subject: &mc.DeclRange, - }) - } - m.ModuleCalls[mc.Name] = mc - } - - for _, r := range file.ManagedResources { - key := r.moduleUniqueKey() - if existing, exists := m.ManagedResources[key]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Duplicate resource %q configuration", existing.Type), - Detail: fmt.Sprintf("A %s resource named %q was already declared at %s. Resource names must be unique per type in each module.", existing.Type, existing.Name, existing.DeclRange), - Subject: &r.DeclRange, - }) - continue - } - m.ManagedResources[key] = r - } - - for _, r := range file.DataResources { - key := r.moduleUniqueKey() - if existing, exists := m.DataResources[key]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: fmt.Sprintf("Duplicate data %q configuration", existing.Type), - Detail: fmt.Sprintf("A %s data resource named %q was already declared at %s. Resource names must be unique per type in each module.", existing.Type, existing.Name, existing.DeclRange), - Subject: &r.DeclRange, - }) - continue - } - m.DataResources[key] = r - } - - return diags -} - -func (m *Module) mergeFile(file *File) hcl.Diagnostics { - var diags hcl.Diagnostics - - if len(file.CoreVersionConstraints) != 0 { - // This is a bit of a strange case for overriding since we normally - // would union together across multiple files anyway, but we'll - // allow it and have each override file clobber any existing list. - m.CoreVersionConstraints = nil - for _, constraint := range file.CoreVersionConstraints { - m.CoreVersionConstraints = append(m.CoreVersionConstraints, constraint) - } - } - - if len(file.Backends) != 0 { - switch len(file.Backends) { - case 1: - m.Backend = file.Backends[0] - default: - // An override file with multiple backends is still invalid, even - // though it can override backends from _other_ files. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate backend configuration", - Detail: fmt.Sprintf("Each override file may have only one backend configuration. A backend was previously configured at %s.", file.Backends[0].DeclRange), - Subject: &file.Backends[1].DeclRange, - }) - } - } - - for _, pc := range file.ProviderConfigs { - key := pc.moduleUniqueKey() - existing, exists := m.ProviderConfigs[key] - if pc.Alias == "" { - // We allow overriding a non-existing _default_ provider configuration - // because the user model is that an absent provider configuration - // implies an empty provider configuration, which is what the user - // is therefore overriding here. - if exists { - mergeDiags := existing.merge(pc) - diags = append(diags, mergeDiags...) - } else { - m.ProviderConfigs[key] = pc - } - } else { - // For aliased providers, there must be a base configuration to - // override. This allows us to detect and report alias typos - // that might otherwise cause the override to not apply. - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing base provider configuration for override", - Detail: fmt.Sprintf("There is no %s provider configuration with the alias %q. An override file can only override an aliased provider configuration that was already defined in a primary configuration file.", pc.Name, pc.Alias), - Subject: &pc.DeclRange, - }) - continue - } - mergeDiags := existing.merge(pc) - diags = append(diags, mergeDiags...) - } - } - - if len(file.ProviderRequirements) != 0 { - mergeProviderVersionConstraints(m.ProviderRequirements, file.ProviderRequirements) - } - - for _, v := range file.Variables { - existing, exists := m.Variables[v.Name] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing base variable declaration to override", - Detail: fmt.Sprintf("There is no variable named %q. An override file can only override a variable that was already declared in a primary configuration file.", v.Name), - Subject: &v.DeclRange, - }) - continue - } - mergeDiags := existing.merge(v) - diags = append(diags, mergeDiags...) - } - - for _, l := range file.Locals { - existing, exists := m.Locals[l.Name] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing base local value definition to override", - Detail: fmt.Sprintf("There is no local value named %q. An override file can only override a local value that was already defined in a primary configuration file.", l.Name), - Subject: &l.DeclRange, - }) - continue - } - mergeDiags := existing.merge(l) - diags = append(diags, mergeDiags...) - } - - for _, o := range file.Outputs { - existing, exists := m.Outputs[o.Name] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing base output definition to override", - Detail: fmt.Sprintf("There is no output named %q. An override file can only override an output that was already defined in a primary configuration file.", o.Name), - Subject: &o.DeclRange, - }) - continue - } - mergeDiags := existing.merge(o) - diags = append(diags, mergeDiags...) - } - - for _, mc := range file.ModuleCalls { - existing, exists := m.ModuleCalls[mc.Name] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing module call to override", - Detail: fmt.Sprintf("There is no module call named %q. An override file can only override a module call that was defined in a primary configuration file.", mc.Name), - Subject: &mc.DeclRange, - }) - continue - } - mergeDiags := existing.merge(mc) - diags = append(diags, mergeDiags...) - } - - for _, r := range file.ManagedResources { - key := r.moduleUniqueKey() - existing, exists := m.ManagedResources[key] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing resource to override", - Detail: fmt.Sprintf("There is no %s resource named %q. An override file can only override a resource block defined in a primary configuration file.", r.Type, r.Name), - Subject: &r.DeclRange, - }) - continue - } - mergeDiags := existing.merge(r) - diags = append(diags, mergeDiags...) - } - - for _, r := range file.DataResources { - key := r.moduleUniqueKey() - existing, exists := m.DataResources[key] - if !exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing data resource to override", - Detail: fmt.Sprintf("There is no %s data resource named %q. An override file can only override a data block defined in a primary configuration file.", r.Type, r.Name), - Subject: &r.DeclRange, - }) - continue - } - mergeDiags := existing.merge(r) - diags = append(diags, mergeDiags...) - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_call.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_call.go deleted file mode 100644 index a484ffef9c0..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_call.go +++ /dev/null @@ -1,188 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/gohcl" - "github.com/hashicorp/hcl/v2/hclsyntax" -) - -// ModuleCall represents a "module" block in a module or file. -type ModuleCall struct { - Name string - - SourceAddr string - SourceAddrRange hcl.Range - SourceSet bool - - Config hcl.Body - - Version VersionConstraint - - Count hcl.Expression - ForEach hcl.Expression - - Providers []PassedProviderConfig - - DependsOn []hcl.Traversal - - DeclRange hcl.Range -} - -func decodeModuleBlock(block *hcl.Block, override bool) (*ModuleCall, hcl.Diagnostics) { - mc := &ModuleCall{ - Name: block.Labels[0], - DeclRange: block.DefRange, - } - - schema := moduleBlockSchema - if override { - schema = schemaForOverrides(schema) - } - - content, remain, diags := block.Body.PartialContent(schema) - mc.Config = remain - - if !hclsyntax.ValidIdentifier(mc.Name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid module instance name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[0], - }) - } - - if attr, exists := content.Attributes["source"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &mc.SourceAddr) - diags = append(diags, valDiags...) - mc.SourceAddrRange = attr.Expr.Range() - mc.SourceSet = true - } - - if attr, exists := content.Attributes["version"]; exists { - var versionDiags hcl.Diagnostics - mc.Version, versionDiags = decodeVersionConstraint(attr) - diags = append(diags, versionDiags...) - } - - if attr, exists := content.Attributes["count"]; exists { - mc.Count = attr.Expr - - // We currently parse this, but don't yet do anything with it. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved argument name in module block", - Detail: fmt.Sprintf("The name %q is reserved for use in a future version of Terraform.", attr.Name), - Subject: &attr.NameRange, - }) - } - - if attr, exists := content.Attributes["for_each"]; exists { - mc.ForEach = attr.Expr - - // We currently parse this, but don't yet do anything with it. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved argument name in module block", - Detail: fmt.Sprintf("The name %q is reserved for use in a future version of Terraform.", attr.Name), - Subject: &attr.NameRange, - }) - } - - if attr, exists := content.Attributes["depends_on"]; exists { - deps, depsDiags := decodeDependsOn(attr) - diags = append(diags, depsDiags...) - mc.DependsOn = append(mc.DependsOn, deps...) - - // We currently parse this, but don't yet do anything with it. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved argument name in module block", - Detail: fmt.Sprintf("The name %q is reserved for use in a future version of Terraform.", attr.Name), - Subject: &attr.NameRange, - }) - } - - if attr, exists := content.Attributes["providers"]; exists { - seen := make(map[string]hcl.Range) - pairs, pDiags := hcl.ExprMap(attr.Expr) - diags = append(diags, pDiags...) - for _, pair := range pairs { - key, keyDiags := decodeProviderConfigRef(pair.Key, "providers") - diags = append(diags, keyDiags...) - value, valueDiags := decodeProviderConfigRef(pair.Value, "providers") - diags = append(diags, valueDiags...) - if keyDiags.HasErrors() || valueDiags.HasErrors() { - continue - } - - matchKey := key.String() - if prev, exists := seen[matchKey]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate provider address", - Detail: fmt.Sprintf("A provider configuration was already passed to %s at %s. Each child provider configuration can be assigned only once.", matchKey, prev), - Subject: pair.Value.Range().Ptr(), - }) - continue - } - - rng := hcl.RangeBetween(pair.Key.Range(), pair.Value.Range()) - seen[matchKey] = rng - mc.Providers = append(mc.Providers, PassedProviderConfig{ - InChild: key, - InParent: value, - }) - } - } - - // Reserved block types (all of them) - for _, block := range content.Blocks { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved block type name in module block", - Detail: fmt.Sprintf("The block type name %q is reserved for use by Terraform in a future version.", block.Type), - Subject: &block.TypeRange, - }) - } - - return mc, diags -} - -// PassedProviderConfig represents a provider config explicitly passed down to -// a child module, possibly giving it a new local address in the process. -type PassedProviderConfig struct { - InChild *ProviderConfigRef - InParent *ProviderConfigRef -} - -var moduleBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "source", - Required: true, - }, - { - Name: "version", - }, - { - Name: "count", - }, - { - Name: "for_each", - }, - { - Name: "depends_on", - }, - { - Name: "providers", - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - // These are all reserved for future use. - {Type: "lifecycle"}, - {Type: "locals"}, - {Type: "provider", LabelNames: []string{"type"}}, - }, -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge.go deleted file mode 100644 index 6fb82acfbd2..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge.go +++ /dev/null @@ -1,247 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// The methods in this file are used by Module.mergeFile to apply overrides -// to our different configuration elements. These methods all follow the -// pattern of mutating the receiver to incorporate settings from the parameter, -// returning error diagnostics if any aspect of the parameter cannot be merged -// into the receiver for some reason. -// -// User expectation is that anything _explicitly_ set in the given object -// should take precedence over the corresponding settings in the receiver, -// but that anything omitted in the given object should be left unchanged. -// In some cases it may be reasonable to do a "deep merge" of certain nested -// features, if it is possible to unambiguously correlate the nested elements -// and their behaviors are orthogonal to each other. - -func (p *Provider) merge(op *Provider) hcl.Diagnostics { - var diags hcl.Diagnostics - - if op.Version.Required != nil { - p.Version = op.Version - } - - p.Config = MergeBodies(p.Config, op.Config) - - return diags -} - -func mergeProviderVersionConstraints(recv map[string][]VersionConstraint, ovrd []*ProviderRequirement) { - // Any provider name that's mentioned in the override gets nilled out in - // our map so that we'll rebuild it below. Any provider not mentioned is - // left unchanged. - for _, reqd := range ovrd { - delete(recv, reqd.Name) - } - for _, reqd := range ovrd { - recv[reqd.Name] = append(recv[reqd.Name], reqd.Requirement) - } -} - -func (v *Variable) merge(ov *Variable) hcl.Diagnostics { - var diags hcl.Diagnostics - - if ov.DescriptionSet { - v.Description = ov.Description - v.DescriptionSet = ov.DescriptionSet - } - if ov.Default != cty.NilVal { - v.Default = ov.Default - } - if ov.Type != cty.NilType { - v.Type = ov.Type - } - if ov.ParsingMode != 0 { - v.ParsingMode = ov.ParsingMode - } - - // If the override file overrode type without default or vice-versa then - // it may have created an invalid situation, which we'll catch now by - // attempting to re-convert the value. - // - // Note that here we may be re-converting an already-converted base value - // from the base config. This will be a no-op if the type was not changed, - // but in particular might be user-observable in the edge case where the - // literal value in config could've been converted to the overridden type - // constraint but the converted value cannot. In practice, this situation - // should be rare since most of our conversions are interchangable. - if v.Default != cty.NilVal { - val, err := convert.Convert(v.Default, v.Type) - if err != nil { - // What exactly we'll say in the error message here depends on whether - // it was Default or Type that was overridden here. - switch { - case ov.Type != cty.NilType && ov.Default == cty.NilVal: - // If only the type was overridden - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid default value for variable", - Detail: fmt.Sprintf("Overriding this variable's type constraint has made its default value invalid: %s.", err), - Subject: &ov.DeclRange, - }) - case ov.Type == cty.NilType && ov.Default != cty.NilVal: - // Only the default was overridden - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid default value for variable", - Detail: fmt.Sprintf("The overridden default value for this variable is not compatible with the variable's type constraint: %s.", err), - Subject: &ov.DeclRange, - }) - default: - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid default value for variable", - Detail: fmt.Sprintf("This variable's default value is not compatible with its type constraint: %s.", err), - Subject: &ov.DeclRange, - }) - } - } else { - v.Default = val - } - } - - return diags -} - -func (l *Local) merge(ol *Local) hcl.Diagnostics { - var diags hcl.Diagnostics - - // Since a local is just a single expression in configuration, the - // override definition entirely replaces the base definition, including - // the source range so that we'll send the user to the right place if - // there is an error. - l.Expr = ol.Expr - l.DeclRange = ol.DeclRange - - return diags -} - -func (o *Output) merge(oo *Output) hcl.Diagnostics { - var diags hcl.Diagnostics - - if oo.Description != "" { - o.Description = oo.Description - } - if oo.Expr != nil { - o.Expr = oo.Expr - } - if oo.SensitiveSet { - o.Sensitive = oo.Sensitive - o.SensitiveSet = oo.SensitiveSet - } - - // We don't allow depends_on to be overridden because that is likely to - // cause confusing misbehavior. - if len(oo.DependsOn) != 0 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported override", - Detail: "The depends_on argument may not be overridden.", - Subject: oo.DependsOn[0].SourceRange().Ptr(), // the first item is the closest range we have - }) - } - - return diags -} - -func (mc *ModuleCall) merge(omc *ModuleCall) hcl.Diagnostics { - var diags hcl.Diagnostics - - if omc.SourceSet { - mc.SourceAddr = omc.SourceAddr - mc.SourceAddrRange = omc.SourceAddrRange - mc.SourceSet = omc.SourceSet - } - - if omc.Count != nil { - mc.Count = omc.Count - } - - if omc.ForEach != nil { - mc.ForEach = omc.ForEach - } - - if len(omc.Version.Required) != 0 { - mc.Version = omc.Version - } - - mc.Config = MergeBodies(mc.Config, omc.Config) - - // We don't allow depends_on to be overridden because that is likely to - // cause confusing misbehavior. - if len(mc.DependsOn) != 0 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported override", - Detail: "The depends_on argument may not be overridden.", - Subject: mc.DependsOn[0].SourceRange().Ptr(), // the first item is the closest range we have - }) - } - - return diags -} - -func (r *Resource) merge(or *Resource) hcl.Diagnostics { - var diags hcl.Diagnostics - - if r.Mode != or.Mode { - // This is always a programming error, since managed and data resources - // are kept in separate maps in the configuration structures. - panic(fmt.Errorf("can't merge %s into %s", or.Mode, r.Mode)) - } - - if or.Count != nil { - r.Count = or.Count - } - if or.ForEach != nil { - r.ForEach = or.ForEach - } - if or.ProviderConfigRef != nil { - r.ProviderConfigRef = or.ProviderConfigRef - } - if r.Mode == addrs.ManagedResourceMode { - // or.Managed is always non-nil for managed resource mode - - if or.Managed.Connection != nil { - r.Managed.Connection = or.Managed.Connection - } - if or.Managed.CreateBeforeDestroySet { - r.Managed.CreateBeforeDestroy = or.Managed.CreateBeforeDestroy - r.Managed.CreateBeforeDestroySet = or.Managed.CreateBeforeDestroySet - } - if len(or.Managed.IgnoreChanges) != 0 { - r.Managed.IgnoreChanges = or.Managed.IgnoreChanges - } - if or.Managed.PreventDestroySet { - r.Managed.PreventDestroy = or.Managed.PreventDestroy - r.Managed.PreventDestroySet = or.Managed.PreventDestroySet - } - if len(or.Managed.Provisioners) != 0 { - r.Managed.Provisioners = or.Managed.Provisioners - } - } - - r.Config = MergeBodies(r.Config, or.Config) - - // We don't allow depends_on to be overridden because that is likely to - // cause confusing misbehavior. - if len(or.DependsOn) != 0 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported override", - Detail: "The depends_on argument may not be overridden.", - Subject: or.DependsOn[0].SourceRange().Ptr(), // the first item is the closest range we have - }) - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge_body.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge_body.go deleted file mode 100644 index 7b51eae85e3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge_body.go +++ /dev/null @@ -1,143 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl/v2" -) - -// MergeBodies creates a new HCL body that contains a combination of the -// given base and override bodies. Attributes and blocks defined in the -// override body take precedence over those of the same name defined in -// the base body. -// -// If any block of a particular type appears in "override" then it will -// replace _all_ of the blocks of the same type in "base" in the new -// body. -func MergeBodies(base, override hcl.Body) hcl.Body { - return mergeBody{ - Base: base, - Override: override, - } -} - -// mergeBody is a hcl.Body implementation that wraps a pair of other bodies -// and allows attributes and blocks within the override to take precedence -// over those defined in the base body. -// -// This is used to deal with dynamically-processed bodies in Module.mergeFile. -// It uses a shallow-only merging strategy where direct attributes defined -// in Override will override attributes of the same name in Base, while any -// blocks defined in Override will hide all blocks of the same type in Base. -// -// This cannot possibly "do the right thing" in all cases, because we don't -// have enough information about user intent. However, this behavior is intended -// to be reasonable for simple overriding use-cases. -type mergeBody struct { - Base hcl.Body - Override hcl.Body -} - -var _ hcl.Body = mergeBody{} - -func (b mergeBody) Content(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Diagnostics) { - var diags hcl.Diagnostics - baseSchema := schemaWithDynamic(schema) - overrideSchema := schemaWithDynamic(schemaForOverrides(schema)) - - baseContent, _, cDiags := b.Base.PartialContent(baseSchema) - diags = append(diags, cDiags...) - overrideContent, _, cDiags := b.Override.PartialContent(overrideSchema) - diags = append(diags, cDiags...) - - content := b.prepareContent(baseContent, overrideContent) - - return content, diags -} - -func (b mergeBody) PartialContent(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Body, hcl.Diagnostics) { - var diags hcl.Diagnostics - baseSchema := schemaWithDynamic(schema) - overrideSchema := schemaWithDynamic(schemaForOverrides(schema)) - - baseContent, baseRemain, cDiags := b.Base.PartialContent(baseSchema) - diags = append(diags, cDiags...) - overrideContent, overrideRemain, cDiags := b.Override.PartialContent(overrideSchema) - diags = append(diags, cDiags...) - - content := b.prepareContent(baseContent, overrideContent) - - remain := MergeBodies(baseRemain, overrideRemain) - - return content, remain, diags -} - -func (b mergeBody) prepareContent(base *hcl.BodyContent, override *hcl.BodyContent) *hcl.BodyContent { - content := &hcl.BodyContent{ - Attributes: make(hcl.Attributes), - } - - // For attributes we just assign from each map in turn and let the override - // map clobber any matching entries from base. - for k, a := range base.Attributes { - content.Attributes[k] = a - } - for k, a := range override.Attributes { - content.Attributes[k] = a - } - - // Things are a little more interesting for blocks because they arrive - // as a flat list. Our merging semantics call for us to suppress blocks - // from base if at least one block of the same type appears in override. - // We explicitly do not try to correlate and deeply merge nested blocks, - // since we don't have enough context here to infer user intent. - - overriddenBlockTypes := make(map[string]bool) - for _, block := range override.Blocks { - if block.Type == "dynamic" { - overriddenBlockTypes[block.Labels[0]] = true - continue - } - overriddenBlockTypes[block.Type] = true - } - for _, block := range base.Blocks { - // We skip over dynamic blocks whose type label is an overridden type - // but note that below we do still leave them as dynamic blocks in - // the result because expanding the dynamic blocks that are left is - // done much later during the core graph walks, where we can safely - // evaluate the expressions. - if block.Type == "dynamic" && overriddenBlockTypes[block.Labels[0]] { - continue - } - if overriddenBlockTypes[block.Type] { - continue - } - content.Blocks = append(content.Blocks, block) - } - for _, block := range override.Blocks { - content.Blocks = append(content.Blocks, block) - } - - return content -} - -func (b mergeBody) JustAttributes() (hcl.Attributes, hcl.Diagnostics) { - var diags hcl.Diagnostics - ret := make(hcl.Attributes) - - baseAttrs, aDiags := b.Base.JustAttributes() - diags = append(diags, aDiags...) - overrideAttrs, aDiags := b.Override.JustAttributes() - diags = append(diags, aDiags...) - - for k, a := range baseAttrs { - ret[k] = a - } - for k, a := range overrideAttrs { - ret[k] = a - } - - return ret, diags -} - -func (b mergeBody) MissingItemRange() hcl.Range { - return b.Base.MissingItemRange() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/named_values.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/named_values.go deleted file mode 100644 index 8c8398e0b72..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/named_values.go +++ /dev/null @@ -1,354 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/ext/typeexpr" - "github.com/hashicorp/hcl/v2/gohcl" - "github.com/hashicorp/hcl/v2/hclsyntax" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// A consistent detail message for all "not a valid identifier" diagnostics. -const badIdentifierDetail = "A name must start with a letter and may contain only letters, digits, underscores, and dashes." - -// Variable represents a "variable" block in a module or file. -type Variable struct { - Name string - Description string - Default cty.Value - Type cty.Type - ParsingMode VariableParsingMode - - DescriptionSet bool - - DeclRange hcl.Range -} - -func decodeVariableBlock(block *hcl.Block, override bool) (*Variable, hcl.Diagnostics) { - v := &Variable{ - Name: block.Labels[0], - DeclRange: block.DefRange, - } - - // Unless we're building an override, we'll set some defaults - // which we might override with attributes below. We leave these - // as zero-value in the override case so we can recognize whether - // or not they are set when we merge. - if !override { - v.Type = cty.DynamicPseudoType - v.ParsingMode = VariableParseLiteral - } - - content, diags := block.Body.Content(variableBlockSchema) - - if !hclsyntax.ValidIdentifier(v.Name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid variable name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[0], - }) - } - - // Don't allow declaration of variables that would conflict with the - // reserved attribute and block type names in a "module" block, since - // these won't be usable for child modules. - for _, attr := range moduleBlockSchema.Attributes { - if attr.Name == v.Name { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid variable name", - Detail: fmt.Sprintf("The variable name %q is reserved due to its special meaning inside module blocks.", attr.Name), - Subject: &block.LabelRanges[0], - }) - } - } - for _, blockS := range moduleBlockSchema.Blocks { - if blockS.Type == v.Name { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid variable name", - Detail: fmt.Sprintf("The variable name %q is reserved due to its special meaning inside module blocks.", blockS.Type), - Subject: &block.LabelRanges[0], - }) - } - } - - if attr, exists := content.Attributes["description"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &v.Description) - diags = append(diags, valDiags...) - v.DescriptionSet = true - } - - if attr, exists := content.Attributes["type"]; exists { - ty, parseMode, tyDiags := decodeVariableType(attr.Expr) - diags = append(diags, tyDiags...) - v.Type = ty - v.ParsingMode = parseMode - } - - if attr, exists := content.Attributes["default"]; exists { - val, valDiags := attr.Expr.Value(nil) - diags = append(diags, valDiags...) - - // Convert the default to the expected type so we can catch invalid - // defaults early and allow later code to assume validity. - // Note that this depends on us having already processed any "type" - // attribute above. - // However, we can't do this if we're in an override file where - // the type might not be set; we'll catch that during merge. - if v.Type != cty.NilType { - var err error - val, err = convert.Convert(val, v.Type) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid default value for variable", - Detail: fmt.Sprintf("This default value is not compatible with the variable's type constraint: %s.", err), - Subject: attr.Expr.Range().Ptr(), - }) - val = cty.DynamicVal - } - } - - v.Default = val - } - - return v, diags -} - -func decodeVariableType(expr hcl.Expression) (cty.Type, VariableParsingMode, hcl.Diagnostics) { - if exprIsNativeQuotedString(expr) { - // Here we're accepting the pre-0.12 form of variable type argument where - // the string values "string", "list" and "map" are accepted has a hint - // about the type used primarily for deciding how to parse values - // given on the command line and in environment variables. - // Only the native syntax ends up in this codepath; we handle the - // JSON syntax (which is, of course, quoted even in the new format) - // in the normal codepath below. - val, diags := expr.Value(nil) - if diags.HasErrors() { - return cty.DynamicPseudoType, VariableParseHCL, diags - } - str := val.AsString() - switch str { - case "string": - return cty.String, VariableParseLiteral, diags - case "list": - return cty.List(cty.DynamicPseudoType), VariableParseHCL, diags - case "map": - return cty.Map(cty.DynamicPseudoType), VariableParseHCL, diags - default: - return cty.DynamicPseudoType, VariableParseHCL, hcl.Diagnostics{{ - Severity: hcl.DiagError, - Summary: "Invalid legacy variable type hint", - Detail: `The legacy variable type hint form, using a quoted string, allows only the values "string", "list", and "map". To provide a full type expression, remove the surrounding quotes and give the type expression directly.`, - Subject: expr.Range().Ptr(), - }} - } - } - - // First we'll deal with some shorthand forms that the HCL-level type - // expression parser doesn't include. These both emulate pre-0.12 behavior - // of allowing a list or map of any element type as long as all of the - // elements are consistent. This is the same as list(any) or map(any). - switch hcl.ExprAsKeyword(expr) { - case "list": - return cty.List(cty.DynamicPseudoType), VariableParseHCL, nil - case "map": - return cty.Map(cty.DynamicPseudoType), VariableParseHCL, nil - } - - ty, diags := typeexpr.TypeConstraint(expr) - if diags.HasErrors() { - return cty.DynamicPseudoType, VariableParseHCL, diags - } - - switch { - case ty.IsPrimitiveType(): - // Primitive types use literal parsing. - return ty, VariableParseLiteral, diags - default: - // Everything else uses HCL parsing - return ty, VariableParseHCL, diags - } -} - -// VariableParsingMode defines how values of a particular variable given by -// text-only mechanisms (command line arguments and environment variables) -// should be parsed to produce the final value. -type VariableParsingMode rune - -// VariableParseLiteral is a variable parsing mode that just takes the given -// string directly as a cty.String value. -const VariableParseLiteral VariableParsingMode = 'L' - -// VariableParseHCL is a variable parsing mode that attempts to parse the given -// string as an HCL expression and returns the result. -const VariableParseHCL VariableParsingMode = 'H' - -// Parse uses the receiving parsing mode to process the given variable value -// string, returning the result along with any diagnostics. -// -// A VariableParsingMode does not know the expected type of the corresponding -// variable, so it's the caller's responsibility to attempt to convert the -// result to the appropriate type and return to the user any diagnostics that -// conversion may produce. -// -// The given name is used to create a synthetic filename in case any diagnostics -// must be generated about the given string value. This should be the name -// of the root module variable whose value will be populated from the given -// string. -// -// If the returned diagnostics has errors, the returned value may not be -// valid. -func (m VariableParsingMode) Parse(name, value string) (cty.Value, hcl.Diagnostics) { - switch m { - case VariableParseLiteral: - return cty.StringVal(value), nil - case VariableParseHCL: - fakeFilename := fmt.Sprintf("", name) - expr, diags := hclsyntax.ParseExpression([]byte(value), fakeFilename, hcl.Pos{Line: 1, Column: 1}) - if diags.HasErrors() { - return cty.DynamicVal, diags - } - val, valDiags := expr.Value(nil) - diags = append(diags, valDiags...) - return val, diags - default: - // Should never happen - panic(fmt.Errorf("Parse called on invalid VariableParsingMode %#v", m)) - } -} - -// Output represents an "output" block in a module or file. -type Output struct { - Name string - Description string - Expr hcl.Expression - DependsOn []hcl.Traversal - Sensitive bool - - DescriptionSet bool - SensitiveSet bool - - DeclRange hcl.Range -} - -func decodeOutputBlock(block *hcl.Block, override bool) (*Output, hcl.Diagnostics) { - o := &Output{ - Name: block.Labels[0], - DeclRange: block.DefRange, - } - - schema := outputBlockSchema - if override { - schema = schemaForOverrides(schema) - } - - content, diags := block.Body.Content(schema) - - if !hclsyntax.ValidIdentifier(o.Name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid output name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[0], - }) - } - - if attr, exists := content.Attributes["description"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &o.Description) - diags = append(diags, valDiags...) - o.DescriptionSet = true - } - - if attr, exists := content.Attributes["value"]; exists { - o.Expr = attr.Expr - } - - if attr, exists := content.Attributes["sensitive"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &o.Sensitive) - diags = append(diags, valDiags...) - o.SensitiveSet = true - } - - if attr, exists := content.Attributes["depends_on"]; exists { - deps, depsDiags := decodeDependsOn(attr) - diags = append(diags, depsDiags...) - o.DependsOn = append(o.DependsOn, deps...) - } - - return o, diags -} - -// Local represents a single entry from a "locals" block in a module or file. -// The "locals" block itself is not represented, because it serves only to -// provide context for us to interpret its contents. -type Local struct { - Name string - Expr hcl.Expression - - DeclRange hcl.Range -} - -func decodeLocalsBlock(block *hcl.Block) ([]*Local, hcl.Diagnostics) { - attrs, diags := block.Body.JustAttributes() - if len(attrs) == 0 { - return nil, diags - } - - locals := make([]*Local, 0, len(attrs)) - for name, attr := range attrs { - if !hclsyntax.ValidIdentifier(name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid local value name", - Detail: badIdentifierDetail, - Subject: &attr.NameRange, - }) - } - - locals = append(locals, &Local{ - Name: name, - Expr: attr.Expr, - DeclRange: attr.Range, - }) - } - return locals, diags -} - -var variableBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "description", - }, - { - Name: "default", - }, - { - Name: "type", - }, - }, -} - -var outputBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "description", - }, - { - Name: "value", - Required: true, - }, - { - Name: "depends_on", - }, - { - Name: "sensitive", - }, - }, -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser.go deleted file mode 100644 index 2a621b57721..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser.go +++ /dev/null @@ -1,100 +0,0 @@ -package configs - -import ( - "fmt" - "strings" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclparse" - "github.com/spf13/afero" -) - -// Parser is the main interface to read configuration files and other related -// files from disk. -// -// It retains a cache of all files that are loaded so that they can be used -// to create source code snippets in diagnostics, etc. -type Parser struct { - fs afero.Afero - p *hclparse.Parser -} - -// NewParser creates and returns a new Parser that reads files from the given -// filesystem. If a nil filesystem is passed then the system's "real" filesystem -// will be used, via afero.OsFs. -func NewParser(fs afero.Fs) *Parser { - if fs == nil { - fs = afero.OsFs{} - } - - return &Parser{ - fs: afero.Afero{Fs: fs}, - p: hclparse.NewParser(), - } -} - -// LoadHCLFile is a low-level method that reads the file at the given path, -// parses it, and returns the hcl.Body representing its root. In many cases -// it is better to use one of the other Load*File methods on this type, -// which additionally decode the root body in some way and return a higher-level -// construct. -// -// If the file cannot be read at all -- e.g. because it does not exist -- then -// this method will return a nil body and error diagnostics. In this case -// callers may wish to ignore the provided error diagnostics and produce -// a more context-sensitive error instead. -// -// The file will be parsed using the HCL native syntax unless the filename -// ends with ".json", in which case the HCL JSON syntax will be used. -func (p *Parser) LoadHCLFile(path string) (hcl.Body, hcl.Diagnostics) { - src, err := p.fs.ReadFile(path) - - if err != nil { - return nil, hcl.Diagnostics{ - { - Severity: hcl.DiagError, - Summary: "Failed to read file", - Detail: fmt.Sprintf("The file %q could not be read.", path), - }, - } - } - - var file *hcl.File - var diags hcl.Diagnostics - switch { - case strings.HasSuffix(path, ".json"): - file, diags = p.p.ParseJSON(src, path) - default: - file, diags = p.p.ParseHCL(src, path) - } - - // If the returned file or body is nil, then we'll return a non-nil empty - // body so we'll meet our contract that nil means an error reading the file. - if file == nil || file.Body == nil { - return hcl.EmptyBody(), diags - } - - return file.Body, diags -} - -// Sources returns a map of the cached source buffers for all files that -// have been loaded through this parser, with source filenames (as requested -// when each file was opened) as the keys. -func (p *Parser) Sources() map[string][]byte { - return p.p.Sources() -} - -// ForceFileSource artificially adds source code to the cache of file sources, -// as if it had been loaded from the given filename. -// -// This should be used only in special situations where configuration is loaded -// some other way. Most callers should load configuration via methods of -// Parser, which will update the sources cache automatically. -func (p *Parser) ForceFileSource(filename string, src []byte) { - // We'll make a synthetic hcl.File here just so we can reuse the - // existing cache. - p.p.AddFile(filename, &hcl.File{ - Body: hcl.EmptyBody(), - Bytes: src, - }) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config.go deleted file mode 100644 index d4cbc945c33..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config.go +++ /dev/null @@ -1,247 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl/v2" -) - -// LoadConfigFile reads the file at the given path and parses it as a config -// file. -// -// If the file cannot be read -- for example, if it does not exist -- then -// a nil *File will be returned along with error diagnostics. Callers may wish -// to disregard the returned diagnostics in this case and instead generate -// their own error message(s) with additional context. -// -// If the returned diagnostics has errors when a non-nil map is returned -// then the map may be incomplete but should be valid enough for careful -// static analysis. -// -// This method wraps LoadHCLFile, and so it inherits the syntax selection -// behaviors documented for that method. -func (p *Parser) LoadConfigFile(path string) (*File, hcl.Diagnostics) { - return p.loadConfigFile(path, false) -} - -// LoadConfigFileOverride is the same as LoadConfigFile except that it relaxes -// certain required attribute constraints in order to interpret the given -// file as an overrides file. -func (p *Parser) LoadConfigFileOverride(path string) (*File, hcl.Diagnostics) { - return p.loadConfigFile(path, true) -} - -func (p *Parser) loadConfigFile(path string, override bool) (*File, hcl.Diagnostics) { - - body, diags := p.LoadHCLFile(path) - if body == nil { - return nil, diags - } - - file := &File{} - - var reqDiags hcl.Diagnostics - file.CoreVersionConstraints, reqDiags = sniffCoreVersionRequirements(body) - diags = append(diags, reqDiags...) - - content, contentDiags := body.Content(configFileSchema) - diags = append(diags, contentDiags...) - - for _, block := range content.Blocks { - switch block.Type { - - case "terraform": - content, contentDiags := block.Body.Content(terraformBlockSchema) - diags = append(diags, contentDiags...) - - // We ignore the "terraform_version" attribute here because - // sniffCoreVersionRequirements already dealt with that above. - - for _, innerBlock := range content.Blocks { - switch innerBlock.Type { - - case "backend": - backendCfg, cfgDiags := decodeBackendBlock(innerBlock) - diags = append(diags, cfgDiags...) - if backendCfg != nil { - file.Backends = append(file.Backends, backendCfg) - } - - case "required_providers": - reqs, reqsDiags := decodeRequiredProvidersBlock(innerBlock) - diags = append(diags, reqsDiags...) - file.ProviderRequirements = append(file.ProviderRequirements, reqs...) - - default: - // Should never happen because the above cases should be exhaustive - // for all block type names in our schema. - continue - - } - } - - case "provider": - cfg, cfgDiags := decodeProviderBlock(block) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.ProviderConfigs = append(file.ProviderConfigs, cfg) - } - - case "variable": - cfg, cfgDiags := decodeVariableBlock(block, override) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.Variables = append(file.Variables, cfg) - } - - case "locals": - defs, defsDiags := decodeLocalsBlock(block) - diags = append(diags, defsDiags...) - file.Locals = append(file.Locals, defs...) - - case "output": - cfg, cfgDiags := decodeOutputBlock(block, override) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.Outputs = append(file.Outputs, cfg) - } - - case "module": - cfg, cfgDiags := decodeModuleBlock(block, override) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.ModuleCalls = append(file.ModuleCalls, cfg) - } - - case "resource": - cfg, cfgDiags := decodeResourceBlock(block) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.ManagedResources = append(file.ManagedResources, cfg) - } - - case "data": - cfg, cfgDiags := decodeDataBlock(block) - diags = append(diags, cfgDiags...) - if cfg != nil { - file.DataResources = append(file.DataResources, cfg) - } - - default: - // Should never happen because the above cases should be exhaustive - // for all block type names in our schema. - continue - - } - } - - return file, diags -} - -// sniffCoreVersionRequirements does minimal parsing of the given body for -// "terraform" blocks with "required_version" attributes, returning the -// requirements found. -// -// This is intended to maximize the chance that we'll be able to read the -// requirements (syntax errors notwithstanding) even if the config file contains -// constructs that might've been added in future Terraform versions -// -// This is a "best effort" sort of method which will return constraints it is -// able to find, but may return no constraints at all if the given body is -// so invalid that it cannot be decoded at all. -func sniffCoreVersionRequirements(body hcl.Body) ([]VersionConstraint, hcl.Diagnostics) { - rootContent, _, diags := body.PartialContent(configFileVersionSniffRootSchema) - - var constraints []VersionConstraint - - for _, block := range rootContent.Blocks { - content, _, blockDiags := block.Body.PartialContent(configFileVersionSniffBlockSchema) - diags = append(diags, blockDiags...) - - attr, exists := content.Attributes["required_version"] - if !exists { - continue - } - - constraint, constraintDiags := decodeVersionConstraint(attr) - diags = append(diags, constraintDiags...) - if !constraintDiags.HasErrors() { - constraints = append(constraints, constraint) - } - } - - return constraints, diags -} - -// configFileSchema is the schema for the top-level of a config file. We use -// the low-level HCL API for this level so we can easily deal with each -// block type separately with its own decoding logic. -var configFileSchema = &hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "terraform", - }, - { - Type: "provider", - LabelNames: []string{"name"}, - }, - { - Type: "variable", - LabelNames: []string{"name"}, - }, - { - Type: "locals", - }, - { - Type: "output", - LabelNames: []string{"name"}, - }, - { - Type: "module", - LabelNames: []string{"name"}, - }, - { - Type: "resource", - LabelNames: []string{"type", "name"}, - }, - { - Type: "data", - LabelNames: []string{"type", "name"}, - }, - }, -} - -// terraformBlockSchema is the schema for a top-level "terraform" block in -// a configuration file. -var terraformBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "required_version", - }, - }, - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "backend", - LabelNames: []string{"type"}, - }, - { - Type: "required_providers", - }, - }, -} - -// configFileVersionSniffRootSchema is a schema for sniffCoreVersionRequirements -var configFileVersionSniffRootSchema = &hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "terraform", - }, - }, -} - -// configFileVersionSniffBlockSchema is a schema for sniffCoreVersionRequirements -var configFileVersionSniffBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "required_version", - }, - }, -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config_dir.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config_dir.go deleted file mode 100644 index afdd69833f8..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config_dir.go +++ /dev/null @@ -1,163 +0,0 @@ -package configs - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/hashicorp/hcl/v2" -) - -// LoadConfigDir reads the .tf and .tf.json files in the given directory -// as config files (using LoadConfigFile) and then combines these files into -// a single Module. -// -// If this method returns nil, that indicates that the given directory does not -// exist at all or could not be opened for some reason. Callers may wish to -// detect this case and ignore the returned diagnostics so that they can -// produce a more context-aware error message in that case. -// -// If this method returns a non-nil module while error diagnostics are returned -// then the module may be incomplete but can be used carefully for static -// analysis. -// -// This file does not consider a directory with no files to be an error, and -// will simply return an empty module in that case. Callers should first call -// Parser.IsConfigDir if they wish to recognize that situation. -// -// .tf files are parsed using the HCL native syntax while .tf.json files are -// parsed using the HCL JSON syntax. -func (p *Parser) LoadConfigDir(path string) (*Module, hcl.Diagnostics) { - primaryPaths, overridePaths, diags := p.dirFiles(path) - if diags.HasErrors() { - return nil, diags - } - - primary, fDiags := p.loadFiles(primaryPaths, false) - diags = append(diags, fDiags...) - override, fDiags := p.loadFiles(overridePaths, true) - diags = append(diags, fDiags...) - - mod, modDiags := NewModule(primary, override) - diags = append(diags, modDiags...) - - mod.SourceDir = path - - return mod, diags -} - -// ConfigDirFiles returns lists of the primary and override files configuration -// files in the given directory. -// -// If the given directory does not exist or cannot be read, error diagnostics -// are returned. If errors are returned, the resulting lists may be incomplete. -func (p Parser) ConfigDirFiles(dir string) (primary, override []string, diags hcl.Diagnostics) { - return p.dirFiles(dir) -} - -// IsConfigDir determines whether the given path refers to a directory that -// exists and contains at least one Terraform config file (with a .tf or -// .tf.json extension.) -func (p *Parser) IsConfigDir(path string) bool { - primaryPaths, overridePaths, _ := p.dirFiles(path) - return (len(primaryPaths) + len(overridePaths)) > 0 -} - -func (p *Parser) loadFiles(paths []string, override bool) ([]*File, hcl.Diagnostics) { - var files []*File - var diags hcl.Diagnostics - - for _, path := range paths { - var f *File - var fDiags hcl.Diagnostics - if override { - f, fDiags = p.LoadConfigFileOverride(path) - } else { - f, fDiags = p.LoadConfigFile(path) - } - diags = append(diags, fDiags...) - if f != nil { - files = append(files, f) - } - } - - return files, diags -} - -func (p *Parser) dirFiles(dir string) (primary, override []string, diags hcl.Diagnostics) { - infos, err := p.fs.ReadDir(dir) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Failed to read module directory", - Detail: fmt.Sprintf("Module directory %s does not exist or cannot be read.", dir), - }) - return - } - - for _, info := range infos { - if info.IsDir() { - // We only care about files - continue - } - - name := info.Name() - ext := fileExt(name) - if ext == "" || IsIgnoredFile(name) { - continue - } - - baseName := name[:len(name)-len(ext)] // strip extension - isOverride := baseName == "override" || strings.HasSuffix(baseName, "_override") - - fullPath := filepath.Join(dir, name) - if isOverride { - override = append(override, fullPath) - } else { - primary = append(primary, fullPath) - } - } - - return -} - -// fileExt returns the Terraform configuration extension of the given -// path, or a blank string if it is not a recognized extension. -func fileExt(path string) string { - if strings.HasSuffix(path, ".tf") { - return ".tf" - } else if strings.HasSuffix(path, ".tf.json") { - return ".tf.json" - } else { - return "" - } -} - -// IsIgnoredFile returns true if the given filename (which must not have a -// directory path ahead of it) should be ignored as e.g. an editor swap file. -func IsIgnoredFile(name string) bool { - return strings.HasPrefix(name, ".") || // Unix-like hidden files - strings.HasSuffix(name, "~") || // vim - strings.HasPrefix(name, "#") && strings.HasSuffix(name, "#") // emacs -} - -// IsEmptyDir returns true if the given filesystem path contains no Terraform -// configuration files. -// -// Unlike the methods of the Parser type, this function always consults the -// real filesystem, and thus it isn't appropriate to use when working with -// configuration loaded from a plan file. -func IsEmptyDir(path string) (bool, error) { - if _, err := os.Stat(path); err != nil && os.IsNotExist(err) { - return true, nil - } - - p := NewParser(nil) - fs, os, err := p.dirFiles(path) - if err != nil { - return false, err - } - - return len(fs) == 0 && len(os) == 0, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_values.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_values.go deleted file mode 100644 index 10d98e5b091..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_values.go +++ /dev/null @@ -1,43 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -// LoadValuesFile reads the file at the given path and parses it as a "values -// file", which is an HCL config file whose top-level attributes are treated -// as arbitrary key.value pairs. -// -// If the file cannot be read -- for example, if it does not exist -- then -// a nil map will be returned along with error diagnostics. Callers may wish -// to disregard the returned diagnostics in this case and instead generate -// their own error message(s) with additional context. -// -// If the returned diagnostics has errors when a non-nil map is returned -// then the map may be incomplete but should be valid enough for careful -// static analysis. -// -// This method wraps LoadHCLFile, and so it inherits the syntax selection -// behaviors documented for that method. -func (p *Parser) LoadValuesFile(path string) (map[string]cty.Value, hcl.Diagnostics) { - body, diags := p.LoadHCLFile(path) - if body == nil { - return nil, diags - } - - vals := make(map[string]cty.Value) - attrs, attrDiags := body.JustAttributes() - diags = append(diags, attrDiags...) - if attrs == nil { - return vals, diags - } - - for name, attr := range attrs { - val, valDiags := attr.Expr.Value(nil) - diags = append(diags, valDiags...) - vals[name] = val - } - - return vals, diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provider.go deleted file mode 100644 index cb9ba1f3f6f..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provider.go +++ /dev/null @@ -1,144 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/gohcl" - "github.com/hashicorp/hcl/v2/hclsyntax" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// Provider represents a "provider" block in a module or file. A provider -// block is a provider configuration, and there can be zero or more -// configurations for each actual provider. -type Provider struct { - Name string - NameRange hcl.Range - Alias string - AliasRange *hcl.Range // nil if no alias set - - Version VersionConstraint - - Config hcl.Body - - DeclRange hcl.Range -} - -func decodeProviderBlock(block *hcl.Block) (*Provider, hcl.Diagnostics) { - content, config, diags := block.Body.PartialContent(providerBlockSchema) - - provider := &Provider{ - Name: block.Labels[0], - NameRange: block.LabelRanges[0], - Config: config, - DeclRange: block.DefRange, - } - - if attr, exists := content.Attributes["alias"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &provider.Alias) - diags = append(diags, valDiags...) - provider.AliasRange = attr.Expr.Range().Ptr() - - if !hclsyntax.ValidIdentifier(provider.Alias) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration alias", - Detail: fmt.Sprintf("An alias must be a valid name. %s", badIdentifierDetail), - }) - } - } - - if attr, exists := content.Attributes["version"]; exists { - var versionDiags hcl.Diagnostics - provider.Version, versionDiags = decodeVersionConstraint(attr) - diags = append(diags, versionDiags...) - } - - // Reserved attribute names - for _, name := range []string{"count", "depends_on", "for_each", "source"} { - if attr, exists := content.Attributes[name]; exists { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved argument name in provider block", - Detail: fmt.Sprintf("The provider argument name %q is reserved for use by Terraform in a future version.", name), - Subject: &attr.NameRange, - }) - } - } - - // Reserved block types (all of them) - for _, block := range content.Blocks { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved block type name in provider block", - Detail: fmt.Sprintf("The block type name %q is reserved for use by Terraform in a future version.", block.Type), - Subject: &block.TypeRange, - }) - } - - return provider, diags -} - -// Addr returns the address of the receiving provider configuration, relative -// to its containing module. -func (p *Provider) Addr() addrs.ProviderConfig { - return addrs.ProviderConfig{ - Type: p.Name, - Alias: p.Alias, - } -} - -func (p *Provider) moduleUniqueKey() string { - if p.Alias != "" { - return fmt.Sprintf("%s.%s", p.Name, p.Alias) - } - return p.Name -} - -// ProviderRequirement represents a declaration of a dependency on a particular -// provider version without actually configuring that provider. This is used in -// child modules that expect a provider to be passed in from their parent. -type ProviderRequirement struct { - Name string - Requirement VersionConstraint -} - -func decodeRequiredProvidersBlock(block *hcl.Block) ([]*ProviderRequirement, hcl.Diagnostics) { - attrs, diags := block.Body.JustAttributes() - var reqs []*ProviderRequirement - for name, attr := range attrs { - req, reqDiags := decodeVersionConstraint(attr) - diags = append(diags, reqDiags...) - if !diags.HasErrors() { - reqs = append(reqs, &ProviderRequirement{ - Name: name, - Requirement: req, - }) - } - } - return reqs, diags -} - -var providerBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "alias", - }, - { - Name: "version", - }, - - // Attribute names reserved for future expansion. - {Name: "count"}, - {Name: "depends_on"}, - {Name: "for_each"}, - {Name: "source"}, - }, - Blocks: []hcl.BlockHeaderSchema{ - // _All_ of these are reserved for future expansion. - {Type: "lifecycle"}, - {Type: "locals"}, - }, -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioner.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioner.go deleted file mode 100644 index 47b65679180..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioner.go +++ /dev/null @@ -1,150 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" -) - -// Provisioner represents a "provisioner" block when used within a -// "resource" block in a module or file. -type Provisioner struct { - Type string - Config hcl.Body - Connection *Connection - When ProvisionerWhen - OnFailure ProvisionerOnFailure - - DeclRange hcl.Range - TypeRange hcl.Range -} - -func decodeProvisionerBlock(block *hcl.Block) (*Provisioner, hcl.Diagnostics) { - pv := &Provisioner{ - Type: block.Labels[0], - TypeRange: block.LabelRanges[0], - DeclRange: block.DefRange, - When: ProvisionerWhenCreate, - OnFailure: ProvisionerOnFailureFail, - } - - content, config, diags := block.Body.PartialContent(provisionerBlockSchema) - pv.Config = config - - if attr, exists := content.Attributes["when"]; exists { - expr, shimDiags := shimTraversalInString(attr.Expr, true) - diags = append(diags, shimDiags...) - - switch hcl.ExprAsKeyword(expr) { - case "create": - pv.When = ProvisionerWhenCreate - case "destroy": - pv.When = ProvisionerWhenDestroy - default: - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid \"when\" keyword", - Detail: "The \"when\" argument requires one of the following keywords: create or destroy.", - Subject: expr.Range().Ptr(), - }) - } - } - - if attr, exists := content.Attributes["on_failure"]; exists { - expr, shimDiags := shimTraversalInString(attr.Expr, true) - diags = append(diags, shimDiags...) - - switch hcl.ExprAsKeyword(expr) { - case "continue": - pv.OnFailure = ProvisionerOnFailureContinue - case "fail": - pv.OnFailure = ProvisionerOnFailureFail - default: - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid \"on_failure\" keyword", - Detail: "The \"on_failure\" argument requires one of the following keywords: continue or fail.", - Subject: attr.Expr.Range().Ptr(), - }) - } - } - - var seenConnection *hcl.Block - for _, block := range content.Blocks { - switch block.Type { - - case "connection": - if seenConnection != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate connection block", - Detail: fmt.Sprintf("This provisioner already has a connection block at %s.", seenConnection.DefRange), - Subject: &block.DefRange, - }) - continue - } - seenConnection = block - - //conn, connDiags := decodeConnectionBlock(block) - //diags = append(diags, connDiags...) - pv.Connection = &Connection{ - Config: block.Body, - DeclRange: block.DefRange, - } - - default: - // Any other block types are ones we've reserved for future use, - // so they get a generic message. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved block type name in provisioner block", - Detail: fmt.Sprintf("The block type name %q is reserved for use by Terraform in a future version.", block.Type), - Subject: &block.TypeRange, - }) - } - } - - return pv, diags -} - -// Connection represents a "connection" block when used within either a -// "resource" or "provisioner" block in a module or file. -type Connection struct { - Config hcl.Body - - DeclRange hcl.Range -} - -// ProvisionerWhen is an enum for valid values for when to run provisioners. -type ProvisionerWhen int - -//go:generate go run golang.org/x/tools/cmd/stringer -type ProvisionerWhen - -const ( - ProvisionerWhenInvalid ProvisionerWhen = iota - ProvisionerWhenCreate - ProvisionerWhenDestroy -) - -// ProvisionerOnFailure is an enum for valid values for on_failure options -// for provisioners. -type ProvisionerOnFailure int - -//go:generate go run golang.org/x/tools/cmd/stringer -type ProvisionerOnFailure - -const ( - ProvisionerOnFailureInvalid ProvisionerOnFailure = iota - ProvisionerOnFailureContinue - ProvisionerOnFailureFail -) - -var provisionerBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - {Name: "when"}, - {Name: "on_failure"}, - }, - Blocks: []hcl.BlockHeaderSchema{ - {Type: "connection"}, - {Type: "lifecycle"}, // reserved for future use - }, -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioneronfailure_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioneronfailure_string.go deleted file mode 100644 index 7ff5a6e00b5..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioneronfailure_string.go +++ /dev/null @@ -1,25 +0,0 @@ -// Code generated by "stringer -type ProvisionerOnFailure"; DO NOT EDIT. - -package configs - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[ProvisionerOnFailureInvalid-0] - _ = x[ProvisionerOnFailureContinue-1] - _ = x[ProvisionerOnFailureFail-2] -} - -const _ProvisionerOnFailure_name = "ProvisionerOnFailureInvalidProvisionerOnFailureContinueProvisionerOnFailureFail" - -var _ProvisionerOnFailure_index = [...]uint8{0, 27, 55, 79} - -func (i ProvisionerOnFailure) String() string { - if i < 0 || i >= ProvisionerOnFailure(len(_ProvisionerOnFailure_index)-1) { - return "ProvisionerOnFailure(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _ProvisionerOnFailure_name[_ProvisionerOnFailure_index[i]:_ProvisionerOnFailure_index[i+1]] -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisionerwhen_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisionerwhen_string.go deleted file mode 100644 index 9f21b3ac636..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisionerwhen_string.go +++ /dev/null @@ -1,25 +0,0 @@ -// Code generated by "stringer -type ProvisionerWhen"; DO NOT EDIT. - -package configs - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[ProvisionerWhenInvalid-0] - _ = x[ProvisionerWhenCreate-1] - _ = x[ProvisionerWhenDestroy-2] -} - -const _ProvisionerWhen_name = "ProvisionerWhenInvalidProvisionerWhenCreateProvisionerWhenDestroy" - -var _ProvisionerWhen_index = [...]uint8{0, 22, 43, 65} - -func (i ProvisionerWhen) String() string { - if i < 0 || i >= ProvisionerWhen(len(_ProvisionerWhen_index)-1) { - return "ProvisionerWhen(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _ProvisionerWhen_name[_ProvisionerWhen_index[i]:_ProvisionerWhen_index[i+1]] -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/resource.go deleted file mode 100644 index cd9991a3898..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/resource.go +++ /dev/null @@ -1,490 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/gohcl" - "github.com/hashicorp/hcl/v2/hclsyntax" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// Resource represents a "resource" or "data" block in a module or file. -type Resource struct { - Mode addrs.ResourceMode - Name string - Type string - Config hcl.Body - Count hcl.Expression - ForEach hcl.Expression - - ProviderConfigRef *ProviderConfigRef - - DependsOn []hcl.Traversal - - // Managed is populated only for Mode = addrs.ManagedResourceMode, - // containing the additional fields that apply to managed resources. - // For all other resource modes, this field is nil. - Managed *ManagedResource - - DeclRange hcl.Range - TypeRange hcl.Range -} - -// ManagedResource represents a "resource" block in a module or file. -type ManagedResource struct { - Connection *Connection - Provisioners []*Provisioner - - CreateBeforeDestroy bool - PreventDestroy bool - IgnoreChanges []hcl.Traversal - IgnoreAllChanges bool - - CreateBeforeDestroySet bool - PreventDestroySet bool -} - -func (r *Resource) moduleUniqueKey() string { - return r.Addr().String() -} - -// Addr returns a resource address for the receiver that is relative to the -// resource's containing module. -func (r *Resource) Addr() addrs.Resource { - return addrs.Resource{ - Mode: r.Mode, - Type: r.Type, - Name: r.Name, - } -} - -// ProviderConfigAddr returns the address for the provider configuration -// that should be used for this resource. This function implements the -// default behavior of extracting the type from the resource type name if -// an explicit "provider" argument was not provided. -func (r *Resource) ProviderConfigAddr() addrs.ProviderConfig { - if r.ProviderConfigRef == nil { - return r.Addr().DefaultProviderConfig() - } - - return addrs.ProviderConfig{ - Type: r.ProviderConfigRef.Name, - Alias: r.ProviderConfigRef.Alias, - } -} - -func decodeResourceBlock(block *hcl.Block) (*Resource, hcl.Diagnostics) { - r := &Resource{ - Mode: addrs.ManagedResourceMode, - Type: block.Labels[0], - Name: block.Labels[1], - DeclRange: block.DefRange, - TypeRange: block.LabelRanges[0], - Managed: &ManagedResource{}, - } - - content, remain, diags := block.Body.PartialContent(resourceBlockSchema) - r.Config = remain - - if !hclsyntax.ValidIdentifier(r.Type) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource type name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[0], - }) - } - if !hclsyntax.ValidIdentifier(r.Name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[1], - }) - } - - if attr, exists := content.Attributes["count"]; exists { - r.Count = attr.Expr - } - - if attr, exists := content.Attributes["for_each"]; exists { - r.ForEach = attr.Expr - // Cannot have count and for_each on the same resource block - if r.Count != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid combination of "count" and "for_each"`, - Detail: `The "count" and "for_each" meta-arguments are mutually-exclusive, only one should be used to be explicit about the number of resources to be created.`, - Subject: &attr.NameRange, - }) - } - } - - if attr, exists := content.Attributes["provider"]; exists { - var providerDiags hcl.Diagnostics - r.ProviderConfigRef, providerDiags = decodeProviderConfigRef(attr.Expr, "provider") - diags = append(diags, providerDiags...) - } - - if attr, exists := content.Attributes["depends_on"]; exists { - deps, depsDiags := decodeDependsOn(attr) - diags = append(diags, depsDiags...) - r.DependsOn = append(r.DependsOn, deps...) - } - - var seenLifecycle *hcl.Block - var seenConnection *hcl.Block - for _, block := range content.Blocks { - switch block.Type { - case "lifecycle": - if seenLifecycle != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate lifecycle block", - Detail: fmt.Sprintf("This resource already has a lifecycle block at %s.", seenLifecycle.DefRange), - Subject: &block.DefRange, - }) - continue - } - seenLifecycle = block - - lcContent, lcDiags := block.Body.Content(resourceLifecycleBlockSchema) - diags = append(diags, lcDiags...) - - if attr, exists := lcContent.Attributes["create_before_destroy"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &r.Managed.CreateBeforeDestroy) - diags = append(diags, valDiags...) - r.Managed.CreateBeforeDestroySet = true - } - - if attr, exists := lcContent.Attributes["prevent_destroy"]; exists { - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &r.Managed.PreventDestroy) - diags = append(diags, valDiags...) - r.Managed.PreventDestroySet = true - } - - if attr, exists := lcContent.Attributes["ignore_changes"]; exists { - - // ignore_changes can either be a list of relative traversals - // or it can be just the keyword "all" to ignore changes to this - // resource entirely. - // ignore_changes = [ami, instance_type] - // ignore_changes = all - // We also allow two legacy forms for compatibility with earlier - // versions: - // ignore_changes = ["ami", "instance_type"] - // ignore_changes = ["*"] - - kw := hcl.ExprAsKeyword(attr.Expr) - - switch { - case kw == "all": - r.Managed.IgnoreAllChanges = true - default: - exprs, listDiags := hcl.ExprList(attr.Expr) - diags = append(diags, listDiags...) - - var ignoreAllRange hcl.Range - - for _, expr := range exprs { - - // our expr might be the literal string "*", which - // we accept as a deprecated way of saying "all". - if shimIsIgnoreChangesStar(expr) { - r.Managed.IgnoreAllChanges = true - ignoreAllRange = expr.Range() - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Deprecated ignore_changes wildcard", - Detail: "The [\"*\"] form of ignore_changes wildcard is deprecated. Use \"ignore_changes = all\" to ignore changes to all attributes.", - Subject: attr.Expr.Range().Ptr(), - }) - continue - } - - expr, shimDiags := shimTraversalInString(expr, false) - diags = append(diags, shimDiags...) - - traversal, travDiags := hcl.RelTraversalForExpr(expr) - diags = append(diags, travDiags...) - if len(traversal) != 0 { - r.Managed.IgnoreChanges = append(r.Managed.IgnoreChanges, traversal) - } - } - - if r.Managed.IgnoreAllChanges && len(r.Managed.IgnoreChanges) != 0 { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid ignore_changes ruleset", - Detail: "Cannot mix wildcard string \"*\" with non-wildcard references.", - Subject: &ignoreAllRange, - Context: attr.Expr.Range().Ptr(), - }) - } - - } - - } - - case "connection": - if seenConnection != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Duplicate connection block", - Detail: fmt.Sprintf("This resource already has a connection block at %s.", seenConnection.DefRange), - Subject: &block.DefRange, - }) - continue - } - seenConnection = block - - r.Managed.Connection = &Connection{ - Config: block.Body, - DeclRange: block.DefRange, - } - - case "provisioner": - pv, pvDiags := decodeProvisionerBlock(block) - diags = append(diags, pvDiags...) - if pv != nil { - r.Managed.Provisioners = append(r.Managed.Provisioners, pv) - } - - default: - // Any other block types are ones we've reserved for future use, - // so they get a generic message. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved block type name in resource block", - Detail: fmt.Sprintf("The block type name %q is reserved for use by Terraform in a future version.", block.Type), - Subject: &block.TypeRange, - }) - } - } - - return r, diags -} - -func decodeDataBlock(block *hcl.Block) (*Resource, hcl.Diagnostics) { - r := &Resource{ - Mode: addrs.DataResourceMode, - Type: block.Labels[0], - Name: block.Labels[1], - DeclRange: block.DefRange, - TypeRange: block.LabelRanges[0], - } - - content, remain, diags := block.Body.PartialContent(dataBlockSchema) - r.Config = remain - - if !hclsyntax.ValidIdentifier(r.Type) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid data source name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[0], - }) - } - if !hclsyntax.ValidIdentifier(r.Name) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid data resource name", - Detail: badIdentifierDetail, - Subject: &block.LabelRanges[1], - }) - } - - if attr, exists := content.Attributes["count"]; exists { - r.Count = attr.Expr - } - - if attr, exists := content.Attributes["for_each"]; exists { - r.ForEach = attr.Expr - // Cannot have count and for_each on the same data block - if r.Count != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid combination of "count" and "for_each"`, - Detail: `The "count" and "for_each" meta-arguments are mutually-exclusive, only one should be used to be explicit about the number of resources to be created.`, - Subject: &attr.NameRange, - }) - } - } - - if attr, exists := content.Attributes["provider"]; exists { - var providerDiags hcl.Diagnostics - r.ProviderConfigRef, providerDiags = decodeProviderConfigRef(attr.Expr, "provider") - diags = append(diags, providerDiags...) - } - - if attr, exists := content.Attributes["depends_on"]; exists { - deps, depsDiags := decodeDependsOn(attr) - diags = append(diags, depsDiags...) - r.DependsOn = append(r.DependsOn, deps...) - } - - for _, block := range content.Blocks { - // All of the block types we accept are just reserved for future use, but some get a specialized error message. - switch block.Type { - case "lifecycle": - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported lifecycle block", - Detail: "Data resources do not have lifecycle settings, so a lifecycle block is not allowed.", - Subject: &block.DefRange, - }) - default: - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Reserved block type name in data block", - Detail: fmt.Sprintf("The block type name %q is reserved for use by Terraform in a future version.", block.Type), - Subject: &block.TypeRange, - }) - } - } - - return r, diags -} - -type ProviderConfigRef struct { - Name string - NameRange hcl.Range - Alias string - AliasRange *hcl.Range // nil if alias not set -} - -func decodeProviderConfigRef(expr hcl.Expression, argName string) (*ProviderConfigRef, hcl.Diagnostics) { - var diags hcl.Diagnostics - - var shimDiags hcl.Diagnostics - expr, shimDiags = shimTraversalInString(expr, false) - diags = append(diags, shimDiags...) - - traversal, travDiags := hcl.AbsTraversalForExpr(expr) - - // AbsTraversalForExpr produces only generic errors, so we'll discard - // the errors given and produce our own with extra context. If we didn't - // get any errors then we might still have warnings, though. - if !travDiags.HasErrors() { - diags = append(diags, travDiags...) - } - - if len(traversal) < 1 || len(traversal) > 2 { - // A provider reference was given as a string literal in the legacy - // configuration language and there are lots of examples out there - // showing that usage, so we'll sniff for that situation here and - // produce a specialized error message for it to help users find - // the new correct form. - if exprIsNativeQuotedString(expr) { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration reference", - Detail: "A provider configuration reference must not be given in quotes.", - Subject: expr.Range().Ptr(), - }) - return nil, diags - } - - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration reference", - Detail: fmt.Sprintf("The %s argument requires a provider type name, optionally followed by a period and then a configuration alias.", argName), - Subject: expr.Range().Ptr(), - }) - return nil, diags - } - - ret := &ProviderConfigRef{ - Name: traversal.RootName(), - NameRange: traversal[0].SourceRange(), - } - - if len(traversal) > 1 { - aliasStep, ok := traversal[1].(hcl.TraverseAttr) - if !ok { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider configuration reference", - Detail: "Provider name must either stand alone or be followed by a period and then a configuration alias.", - Subject: traversal[1].SourceRange().Ptr(), - }) - return ret, diags - } - - ret.Alias = aliasStep.Name - ret.AliasRange = aliasStep.SourceRange().Ptr() - } - - return ret, diags -} - -// Addr returns the provider config address corresponding to the receiving -// config reference. -// -// This is a trivial conversion, essentially just discarding the source -// location information and keeping just the addressing information. -func (r *ProviderConfigRef) Addr() addrs.ProviderConfig { - return addrs.ProviderConfig{ - Type: r.Name, - Alias: r.Alias, - } -} - -func (r *ProviderConfigRef) String() string { - if r == nil { - return "" - } - if r.Alias != "" { - return fmt.Sprintf("%s.%s", r.Name, r.Alias) - } - return r.Name -} - -var commonResourceAttributes = []hcl.AttributeSchema{ - { - Name: "count", - }, - { - Name: "for_each", - }, - { - Name: "provider", - }, - { - Name: "depends_on", - }, -} - -var resourceBlockSchema = &hcl.BodySchema{ - Attributes: commonResourceAttributes, - Blocks: []hcl.BlockHeaderSchema{ - {Type: "locals"}, // reserved for future use - {Type: "lifecycle"}, - {Type: "connection"}, - {Type: "provisioner", LabelNames: []string{"type"}}, - }, -} - -var dataBlockSchema = &hcl.BodySchema{ - Attributes: commonResourceAttributes, - Blocks: []hcl.BlockHeaderSchema{ - {Type: "lifecycle"}, // reserved for future use - {Type: "locals"}, // reserved for future use - }, -} - -var resourceLifecycleBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "create_before_destroy", - }, - { - Name: "prevent_destroy", - }, - { - Name: "ignore_changes", - }, - }, -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/synth_body.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/synth_body.go deleted file mode 100644 index cd914e5dbc4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/synth_body.go +++ /dev/null @@ -1,118 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" - "github.com/zclconf/go-cty/cty" -) - -// SynthBody produces a synthetic hcl.Body that behaves as if it had attributes -// corresponding to the elements given in the values map. -// -// This is useful in situations where, for example, values provided on the -// command line can override values given in configuration, using MergeBodies. -// -// The given filename is used in case any diagnostics are returned. Since -// the created body is synthetic, it is likely that this will not be a "real" -// filename. For example, if from a command line argument it could be -// a representation of that argument's name, such as "-var=...". -func SynthBody(filename string, values map[string]cty.Value) hcl.Body { - return synthBody{ - Filename: filename, - Values: values, - } -} - -type synthBody struct { - Filename string - Values map[string]cty.Value -} - -func (b synthBody) Content(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Diagnostics) { - content, remain, diags := b.PartialContent(schema) - remainS := remain.(synthBody) - for name := range remainS.Values { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported attribute", - Detail: fmt.Sprintf("An attribute named %q is not expected here.", name), - Subject: b.synthRange().Ptr(), - }) - } - return content, diags -} - -func (b synthBody) PartialContent(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Body, hcl.Diagnostics) { - var diags hcl.Diagnostics - content := &hcl.BodyContent{ - Attributes: make(hcl.Attributes), - MissingItemRange: b.synthRange(), - } - - remainValues := make(map[string]cty.Value) - for attrName, val := range b.Values { - remainValues[attrName] = val - } - - for _, attrS := range schema.Attributes { - delete(remainValues, attrS.Name) - val, defined := b.Values[attrS.Name] - if !defined { - if attrS.Required { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing required attribute", - Detail: fmt.Sprintf("The attribute %q is required, but no definition was found.", attrS.Name), - Subject: b.synthRange().Ptr(), - }) - } - continue - } - content.Attributes[attrS.Name] = b.synthAttribute(attrS.Name, val) - } - - // We just ignore blocks altogether, because this body type never has - // nested blocks. - - remain := synthBody{ - Filename: b.Filename, - Values: remainValues, - } - - return content, remain, diags -} - -func (b synthBody) JustAttributes() (hcl.Attributes, hcl.Diagnostics) { - ret := make(hcl.Attributes) - for name, val := range b.Values { - ret[name] = b.synthAttribute(name, val) - } - return ret, nil -} - -func (b synthBody) MissingItemRange() hcl.Range { - return b.synthRange() -} - -func (b synthBody) synthAttribute(name string, val cty.Value) *hcl.Attribute { - rng := b.synthRange() - return &hcl.Attribute{ - Name: name, - Expr: &hclsyntax.LiteralValueExpr{ - Val: val, - SrcRange: rng, - }, - NameRange: rng, - Range: rng, - } -} - -func (b synthBody) synthRange() hcl.Range { - return hcl.Range{ - Filename: b.Filename, - Start: hcl.Pos{Line: 1, Column: 1}, - End: hcl.Pos{Line: 1, Column: 1}, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/util.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/util.go deleted file mode 100644 index e135546fb78..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/util.go +++ /dev/null @@ -1,63 +0,0 @@ -package configs - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" -) - -// exprIsNativeQuotedString determines whether the given expression looks like -// it's a quoted string in the HCL native syntax. -// -// This should be used sparingly only for situations where our legacy HCL -// decoding would've expected a keyword or reference in quotes but our new -// decoding expects the keyword or reference to be provided directly as -// an identifier-based expression. -func exprIsNativeQuotedString(expr hcl.Expression) bool { - _, ok := expr.(*hclsyntax.TemplateExpr) - return ok -} - -// schemaForOverrides takes a *hcl.BodySchema and produces a new one that is -// equivalent except that any required attributes are forced to not be required. -// -// This is useful for dealing with "override" config files, which are allowed -// to omit things that they don't wish to override from the main configuration. -// -// The returned schema may have some pointers in common with the given schema, -// so neither the given schema nor the returned schema should be modified after -// using this function in order to avoid confusion. -// -// Overrides are rarely used, so it's recommended to just create the override -// schema on the fly only when it's needed, rather than storing it in a global -// variable as we tend to do for a primary schema. -func schemaForOverrides(schema *hcl.BodySchema) *hcl.BodySchema { - ret := &hcl.BodySchema{ - Attributes: make([]hcl.AttributeSchema, len(schema.Attributes)), - Blocks: schema.Blocks, - } - - for i, attrS := range schema.Attributes { - ret.Attributes[i] = attrS - ret.Attributes[i].Required = false - } - - return ret -} - -// schemaWithDynamic takes a *hcl.BodySchema and produces a new one that -// is equivalent except that it accepts an additional block type "dynamic" with -// a single label, used to recognize usage of the HCL dynamic block extension. -func schemaWithDynamic(schema *hcl.BodySchema) *hcl.BodySchema { - ret := &hcl.BodySchema{ - Attributes: schema.Attributes, - Blocks: make([]hcl.BlockHeaderSchema, len(schema.Blocks), len(schema.Blocks)+1), - } - - copy(ret.Blocks, schema.Blocks) - ret.Blocks = append(ret.Blocks, hcl.BlockHeaderSchema{ - Type: "dynamic", - LabelNames: []string{"type"}, - }) - - return ret -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/variable_type_hint.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/variable_type_hint.go deleted file mode 100644 index c02ad4b5526..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/variable_type_hint.go +++ /dev/null @@ -1,45 +0,0 @@ -package configs - -// VariableTypeHint is an enumeration used for the Variable.TypeHint field, -// which is an incompletely-specified type for the variable which is used -// as a hint for whether a value provided in an ambiguous context (on the -// command line or in an environment variable) should be taken literally as a -// string or parsed as an HCL expression to produce a data structure. -// -// The type hint is applied to runtime values as well, but since it does not -// accurately describe a precise type it is not fully-sufficient to infer -// the dynamic type of a value passed through a variable. -// -// These hints use inaccurate terminology for historical reasons. Full details -// are in the documentation for each constant in this enumeration, but in -// summary: -// -// TypeHintString requires a primitive type -// TypeHintList requires a type that could be converted to a tuple -// TypeHintMap requires a type that could be converted to an object -type VariableTypeHint rune - -//go:generate go run golang.org/x/tools/cmd/stringer -type VariableTypeHint - -// TypeHintNone indicates the absence of a type hint. Values specified in -// ambiguous contexts will be treated as literal strings, as if TypeHintString -// were selected, but no runtime value checks will be applied. This is reasonable -// type hint for a module that is never intended to be used at the top-level -// of a configuration, since descendent modules never receive values from -// ambiguous contexts. -const TypeHintNone VariableTypeHint = 0 - -// TypeHintString spec indicates that a value provided in an ambiguous context -// should be treated as a literal string, and additionally requires that the -// runtime value for the variable is of a primitive type (string, number, bool). -const TypeHintString VariableTypeHint = 'S' - -// TypeHintList indicates that a value provided in an ambiguous context should -// be treated as an HCL expression, and additionally requires that the -// runtime value for the variable is of an tuple, list, or set type. -const TypeHintList VariableTypeHint = 'L' - -// TypeHintMap indicates that a value provided in an ambiguous context should -// be treated as an HCL expression, and additionally requires that the -// runtime value for the variable is of an object or map type. -const TypeHintMap VariableTypeHint = 'M' diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/variabletypehint_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/variabletypehint_string.go deleted file mode 100644 index 2b50428ce12..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/variabletypehint_string.go +++ /dev/null @@ -1,39 +0,0 @@ -// Code generated by "stringer -type VariableTypeHint"; DO NOT EDIT. - -package configs - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[TypeHintNone-0] - _ = x[TypeHintString-83] - _ = x[TypeHintList-76] - _ = x[TypeHintMap-77] -} - -const ( - _VariableTypeHint_name_0 = "TypeHintNone" - _VariableTypeHint_name_1 = "TypeHintListTypeHintMap" - _VariableTypeHint_name_2 = "TypeHintString" -) - -var ( - _VariableTypeHint_index_1 = [...]uint8{0, 12, 23} -) - -func (i VariableTypeHint) String() string { - switch { - case i == 0: - return _VariableTypeHint_name_0 - case 76 <= i && i <= 77: - i -= 76 - return _VariableTypeHint_name_1[_VariableTypeHint_index_1[i]:_VariableTypeHint_index_1[i+1]] - case i == 83: - return _VariableTypeHint_name_2 - default: - return "VariableTypeHint(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/version_constraint.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/version_constraint.go deleted file mode 100644 index 0f541dc711d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/version_constraint.go +++ /dev/null @@ -1,71 +0,0 @@ -package configs - -import ( - "fmt" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// VersionConstraint represents a version constraint on some resource -// (e.g. Terraform Core, a provider, a module, ...) that carries with it -// a source range so that a helpful diagnostic can be printed in the event -// that a particular constraint does not match. -type VersionConstraint struct { - Required version.Constraints - DeclRange hcl.Range -} - -func decodeVersionConstraint(attr *hcl.Attribute) (VersionConstraint, hcl.Diagnostics) { - ret := VersionConstraint{ - DeclRange: attr.Range, - } - - val, diags := attr.Expr.Value(nil) - if diags.HasErrors() { - return ret, diags - } - var err error - val, err = convert.Convert(val, cty.String) - if err != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid version constraint", - Detail: fmt.Sprintf("A string value is required for %s.", attr.Name), - Subject: attr.Expr.Range().Ptr(), - }) - return ret, diags - } - - if val.IsNull() { - // A null version constraint is strange, but we'll just treat it - // like an empty constraint set. - return ret, diags - } - - if !val.IsWhollyKnown() { - // If there is a syntax error, HCL sets the value of the given attribute - // to cty.DynamicVal. A diagnostic for the syntax error will already - // bubble up, so we will move forward gracefully here. - return ret, diags - } - - constraintStr := val.AsString() - constraints, err := version.NewConstraint(constraintStr) - if err != nil { - // NewConstraint doesn't return user-friendly errors, so we'll just - // ignore the provided error and produce our own generic one. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid version constraint", - Detail: "This string does not use correct version constraint syntax.", // Not very actionable :( - Subject: attr.Expr.Range().Ptr(), - }) - return ret, diags - } - - ret.Required = constraints - return ret, diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/dag.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/dag.go deleted file mode 100644 index a150af96190..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/dag.go +++ /dev/null @@ -1,301 +0,0 @@ -package dag - -import ( - "fmt" - "sort" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - - "github.com/hashicorp/go-multierror" -) - -// AcyclicGraph is a specialization of Graph that cannot have cycles. With -// this property, we get the property of sane graph traversal. -type AcyclicGraph struct { - Graph -} - -// WalkFunc is the callback used for walking the graph. -type WalkFunc func(Vertex) tfdiags.Diagnostics - -// DepthWalkFunc is a walk function that also receives the current depth of the -// walk as an argument -type DepthWalkFunc func(Vertex, int) error - -func (g *AcyclicGraph) DirectedGraph() Grapher { - return g -} - -// Returns a Set that includes every Vertex yielded by walking down from the -// provided starting Vertex v. -func (g *AcyclicGraph) Ancestors(v Vertex) (*Set, error) { - s := new(Set) - start := AsVertexList(g.DownEdges(v)) - memoFunc := func(v Vertex, d int) error { - s.Add(v) - return nil - } - - if err := g.DepthFirstWalk(start, memoFunc); err != nil { - return nil, err - } - - return s, nil -} - -// Returns a Set that includes every Vertex yielded by walking up from the -// provided starting Vertex v. -func (g *AcyclicGraph) Descendents(v Vertex) (*Set, error) { - s := new(Set) - start := AsVertexList(g.UpEdges(v)) - memoFunc := func(v Vertex, d int) error { - s.Add(v) - return nil - } - - if err := g.ReverseDepthFirstWalk(start, memoFunc); err != nil { - return nil, err - } - - return s, nil -} - -// Root returns the root of the DAG, or an error. -// -// Complexity: O(V) -func (g *AcyclicGraph) Root() (Vertex, error) { - roots := make([]Vertex, 0, 1) - for _, v := range g.Vertices() { - if g.UpEdges(v).Len() == 0 { - roots = append(roots, v) - } - } - - if len(roots) > 1 { - // TODO(mitchellh): make this error message a lot better - return nil, fmt.Errorf("multiple roots: %#v", roots) - } - - if len(roots) == 0 { - return nil, fmt.Errorf("no roots found") - } - - return roots[0], nil -} - -// TransitiveReduction performs the transitive reduction of graph g in place. -// The transitive reduction of a graph is a graph with as few edges as -// possible with the same reachability as the original graph. This means -// that if there are three nodes A => B => C, and A connects to both -// B and C, and B connects to C, then the transitive reduction is the -// same graph with only a single edge between A and B, and a single edge -// between B and C. -// -// The graph must be valid for this operation to behave properly. If -// Validate() returns an error, the behavior is undefined and the results -// will likely be unexpected. -// -// Complexity: O(V(V+E)), or asymptotically O(VE) -func (g *AcyclicGraph) TransitiveReduction() { - // For each vertex u in graph g, do a DFS starting from each vertex - // v such that the edge (u,v) exists (v is a direct descendant of u). - // - // For each v-prime reachable from v, remove the edge (u, v-prime). - defer g.debug.BeginOperation("TransitiveReduction", "").End("") - - for _, u := range g.Vertices() { - uTargets := g.DownEdges(u) - vs := AsVertexList(g.DownEdges(u)) - - g.depthFirstWalk(vs, false, func(v Vertex, d int) error { - shared := uTargets.Intersection(g.DownEdges(v)) - for _, vPrime := range AsVertexList(shared) { - g.RemoveEdge(BasicEdge(u, vPrime)) - } - - return nil - }) - } -} - -// Validate validates the DAG. A DAG is valid if it has a single root -// with no cycles. -func (g *AcyclicGraph) Validate() error { - if _, err := g.Root(); err != nil { - return err - } - - // Look for cycles of more than 1 component - var err error - cycles := g.Cycles() - if len(cycles) > 0 { - for _, cycle := range cycles { - cycleStr := make([]string, len(cycle)) - for j, vertex := range cycle { - cycleStr[j] = VertexName(vertex) - } - - err = multierror.Append(err, fmt.Errorf( - "Cycle: %s", strings.Join(cycleStr, ", "))) - } - } - - // Look for cycles to self - for _, e := range g.Edges() { - if e.Source() == e.Target() { - err = multierror.Append(err, fmt.Errorf( - "Self reference: %s", VertexName(e.Source()))) - } - } - - return err -} - -func (g *AcyclicGraph) Cycles() [][]Vertex { - var cycles [][]Vertex - for _, cycle := range StronglyConnected(&g.Graph) { - if len(cycle) > 1 { - cycles = append(cycles, cycle) - } - } - return cycles -} - -// Walk walks the graph, calling your callback as each node is visited. -// This will walk nodes in parallel if it can. The resulting diagnostics -// contains problems from all graphs visited, in no particular order. -func (g *AcyclicGraph) Walk(cb WalkFunc) tfdiags.Diagnostics { - defer g.debug.BeginOperation(typeWalk, "").End("") - - w := &Walker{Callback: cb, Reverse: true} - w.Update(g) - return w.Wait() -} - -// simple convenience helper for converting a dag.Set to a []Vertex -func AsVertexList(s *Set) []Vertex { - rawList := s.List() - vertexList := make([]Vertex, len(rawList)) - for i, raw := range rawList { - vertexList[i] = raw.(Vertex) - } - return vertexList -} - -type vertexAtDepth struct { - Vertex Vertex - Depth int -} - -// depthFirstWalk does a depth-first walk of the graph starting from -// the vertices in start. -func (g *AcyclicGraph) DepthFirstWalk(start []Vertex, f DepthWalkFunc) error { - return g.depthFirstWalk(start, true, f) -} - -// This internal method provides the option of not sorting the vertices during -// the walk, which we use for the Transitive reduction. -// Some configurations can lead to fully-connected subgraphs, which makes our -// transitive reduction algorithm O(n^3). This is still passable for the size -// of our graphs, but the additional n^2 sort operations would make this -// uncomputable in a reasonable amount of time. -func (g *AcyclicGraph) depthFirstWalk(start []Vertex, sorted bool, f DepthWalkFunc) error { - defer g.debug.BeginOperation(typeDepthFirstWalk, "").End("") - - seen := make(map[Vertex]struct{}) - frontier := make([]*vertexAtDepth, len(start)) - for i, v := range start { - frontier[i] = &vertexAtDepth{ - Vertex: v, - Depth: 0, - } - } - for len(frontier) > 0 { - // Pop the current vertex - n := len(frontier) - current := frontier[n-1] - frontier = frontier[:n-1] - - // Check if we've seen this already and return... - if _, ok := seen[current.Vertex]; ok { - continue - } - seen[current.Vertex] = struct{}{} - - // Visit the current node - if err := f(current.Vertex, current.Depth); err != nil { - return err - } - - // Visit targets of this in a consistent order. - targets := AsVertexList(g.DownEdges(current.Vertex)) - - if sorted { - sort.Sort(byVertexName(targets)) - } - - for _, t := range targets { - frontier = append(frontier, &vertexAtDepth{ - Vertex: t, - Depth: current.Depth + 1, - }) - } - } - - return nil -} - -// reverseDepthFirstWalk does a depth-first walk _up_ the graph starting from -// the vertices in start. -func (g *AcyclicGraph) ReverseDepthFirstWalk(start []Vertex, f DepthWalkFunc) error { - defer g.debug.BeginOperation(typeReverseDepthFirstWalk, "").End("") - - seen := make(map[Vertex]struct{}) - frontier := make([]*vertexAtDepth, len(start)) - for i, v := range start { - frontier[i] = &vertexAtDepth{ - Vertex: v, - Depth: 0, - } - } - for len(frontier) > 0 { - // Pop the current vertex - n := len(frontier) - current := frontier[n-1] - frontier = frontier[:n-1] - - // Check if we've seen this already and return... - if _, ok := seen[current.Vertex]; ok { - continue - } - seen[current.Vertex] = struct{}{} - - // Add next set of targets in a consistent order. - targets := AsVertexList(g.UpEdges(current.Vertex)) - sort.Sort(byVertexName(targets)) - for _, t := range targets { - frontier = append(frontier, &vertexAtDepth{ - Vertex: t, - Depth: current.Depth + 1, - }) - } - - // Visit the current node - if err := f(current.Vertex, current.Depth); err != nil { - return err - } - } - - return nil -} - -// byVertexName implements sort.Interface so a list of Vertices can be sorted -// consistently by their VertexName -type byVertexName []Vertex - -func (b byVertexName) Len() int { return len(b) } -func (b byVertexName) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b byVertexName) Less(i, j int) bool { - return VertexName(b[i]) < VertexName(b[j]) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/dot.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/dot.go deleted file mode 100644 index 65a351b6fbd..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/dot.go +++ /dev/null @@ -1,278 +0,0 @@ -package dag - -import ( - "bytes" - "fmt" - "sort" - "strings" -) - -// DotOpts are the options for generating a dot formatted Graph. -type DotOpts struct { - // Allows some nodes to decide to only show themselves when the user has - // requested the "verbose" graph. - Verbose bool - - // Highlight Cycles - DrawCycles bool - - // How many levels to expand modules as we draw - MaxDepth int - - // use this to keep the cluster_ naming convention from the previous dot writer - cluster bool -} - -// GraphNodeDotter can be implemented by a node to cause it to be included -// in the dot graph. The Dot method will be called which is expected to -// return a representation of this node. -type GraphNodeDotter interface { - // Dot is called to return the dot formatting for the node. - // The first parameter is the title of the node. - // The second parameter includes user-specified options that affect the dot - // graph. See GraphDotOpts below for details. - DotNode(string, *DotOpts) *DotNode -} - -// DotNode provides a structure for Vertices to return in order to specify their -// dot format. -type DotNode struct { - Name string - Attrs map[string]string -} - -// Returns the DOT representation of this Graph. -func (g *marshalGraph) Dot(opts *DotOpts) []byte { - if opts == nil { - opts = &DotOpts{ - DrawCycles: true, - MaxDepth: -1, - Verbose: true, - } - } - - var w indentWriter - w.WriteString("digraph {\n") - w.Indent() - - // some dot defaults - w.WriteString(`compound = "true"` + "\n") - w.WriteString(`newrank = "true"` + "\n") - - // the top level graph is written as the first subgraph - w.WriteString(`subgraph "root" {` + "\n") - g.writeBody(opts, &w) - - // cluster isn't really used other than for naming purposes in some graphs - opts.cluster = opts.MaxDepth != 0 - maxDepth := opts.MaxDepth - if maxDepth == 0 { - maxDepth = -1 - } - - for _, s := range g.Subgraphs { - g.writeSubgraph(s, opts, maxDepth, &w) - } - - w.Unindent() - w.WriteString("}\n") - return w.Bytes() -} - -func (v *marshalVertex) dot(g *marshalGraph, opts *DotOpts) []byte { - var buf bytes.Buffer - graphName := g.Name - if graphName == "" { - graphName = "root" - } - - name := v.Name - attrs := v.Attrs - if v.graphNodeDotter != nil { - node := v.graphNodeDotter.DotNode(name, opts) - if node == nil { - return []byte{} - } - - newAttrs := make(map[string]string) - for k, v := range attrs { - newAttrs[k] = v - } - for k, v := range node.Attrs { - newAttrs[k] = v - } - - name = node.Name - attrs = newAttrs - } - - buf.WriteString(fmt.Sprintf(`"[%s] %s"`, graphName, name)) - writeAttrs(&buf, attrs) - buf.WriteByte('\n') - - return buf.Bytes() -} - -func (e *marshalEdge) dot(g *marshalGraph) string { - var buf bytes.Buffer - graphName := g.Name - if graphName == "" { - graphName = "root" - } - - sourceName := g.vertexByID(e.Source).Name - targetName := g.vertexByID(e.Target).Name - s := fmt.Sprintf(`"[%s] %s" -> "[%s] %s"`, graphName, sourceName, graphName, targetName) - buf.WriteString(s) - writeAttrs(&buf, e.Attrs) - - return buf.String() -} - -func cycleDot(e *marshalEdge, g *marshalGraph) string { - return e.dot(g) + ` [color = "red", penwidth = "2.0"]` -} - -// Write the subgraph body. The is recursive, and the depth argument is used to -// record the current depth of iteration. -func (g *marshalGraph) writeSubgraph(sg *marshalGraph, opts *DotOpts, depth int, w *indentWriter) { - if depth == 0 { - return - } - depth-- - - name := sg.Name - if opts.cluster { - // we prefix with cluster_ to match the old dot output - name = "cluster_" + name - sg.Attrs["label"] = sg.Name - } - w.WriteString(fmt.Sprintf("subgraph %q {\n", name)) - sg.writeBody(opts, w) - - for _, sg := range sg.Subgraphs { - g.writeSubgraph(sg, opts, depth, w) - } -} - -func (g *marshalGraph) writeBody(opts *DotOpts, w *indentWriter) { - w.Indent() - - for _, as := range attrStrings(g.Attrs) { - w.WriteString(as + "\n") - } - - // list of Vertices that aren't to be included in the dot output - skip := map[string]bool{} - - for _, v := range g.Vertices { - if v.graphNodeDotter == nil { - skip[v.ID] = true - continue - } - - w.Write(v.dot(g, opts)) - } - - var dotEdges []string - - if opts.DrawCycles { - for _, c := range g.Cycles { - if len(c) < 2 { - continue - } - - for i, j := 0, 1; i < len(c); i, j = i+1, j+1 { - if j >= len(c) { - j = 0 - } - src := c[i] - tgt := c[j] - - if skip[src.ID] || skip[tgt.ID] { - continue - } - - e := &marshalEdge{ - Name: fmt.Sprintf("%s|%s", src.Name, tgt.Name), - Source: src.ID, - Target: tgt.ID, - Attrs: make(map[string]string), - } - - dotEdges = append(dotEdges, cycleDot(e, g)) - src = tgt - } - } - } - - for _, e := range g.Edges { - dotEdges = append(dotEdges, e.dot(g)) - } - - // srot these again to match the old output - sort.Strings(dotEdges) - - for _, e := range dotEdges { - w.WriteString(e + "\n") - } - - w.Unindent() - w.WriteString("}\n") -} - -func writeAttrs(buf *bytes.Buffer, attrs map[string]string) { - if len(attrs) > 0 { - buf.WriteString(" [") - buf.WriteString(strings.Join(attrStrings(attrs), ", ")) - buf.WriteString("]") - } -} - -func attrStrings(attrs map[string]string) []string { - strings := make([]string, 0, len(attrs)) - for k, v := range attrs { - strings = append(strings, fmt.Sprintf("%s = %q", k, v)) - } - sort.Strings(strings) - return strings -} - -// Provide a bytes.Buffer like structure, which will indent when starting a -// newline. -type indentWriter struct { - bytes.Buffer - level int -} - -func (w *indentWriter) indent() { - newline := []byte("\n") - if !bytes.HasSuffix(w.Bytes(), newline) { - return - } - for i := 0; i < w.level; i++ { - w.Buffer.WriteString("\t") - } -} - -// Indent increases indentation by 1 -func (w *indentWriter) Indent() { w.level++ } - -// Unindent decreases indentation by 1 -func (w *indentWriter) Unindent() { w.level-- } - -// the following methods intercecpt the byte.Buffer writes and insert the -// indentation when starting a new line. -func (w *indentWriter) Write(b []byte) (int, error) { - w.indent() - return w.Buffer.Write(b) -} - -func (w *indentWriter) WriteString(s string) (int, error) { - w.indent() - return w.Buffer.WriteString(s) -} -func (w *indentWriter) WriteByte(b byte) error { - w.indent() - return w.Buffer.WriteByte(b) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/edge.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/edge.go deleted file mode 100644 index f0d99ee3a61..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/edge.go +++ /dev/null @@ -1,37 +0,0 @@ -package dag - -import ( - "fmt" -) - -// Edge represents an edge in the graph, with a source and target vertex. -type Edge interface { - Source() Vertex - Target() Vertex - - Hashable -} - -// BasicEdge returns an Edge implementation that simply tracks the source -// and target given as-is. -func BasicEdge(source, target Vertex) Edge { - return &basicEdge{S: source, T: target} -} - -// basicEdge is a basic implementation of Edge that has the source and -// target vertex. -type basicEdge struct { - S, T Vertex -} - -func (e *basicEdge) Hashcode() interface{} { - return fmt.Sprintf("%p-%p", e.S, e.T) -} - -func (e *basicEdge) Source() Vertex { - return e.S -} - -func (e *basicEdge) Target() Vertex { - return e.T -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/graph.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/graph.go deleted file mode 100644 index e7517a2062b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/graph.go +++ /dev/null @@ -1,391 +0,0 @@ -package dag - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "sort" -) - -// Graph is used to represent a dependency graph. -type Graph struct { - vertices *Set - edges *Set - downEdges map[interface{}]*Set - upEdges map[interface{}]*Set - - // JSON encoder for recording debug information - debug *encoder -} - -// Subgrapher allows a Vertex to be a Graph itself, by returning a Grapher. -type Subgrapher interface { - Subgraph() Grapher -} - -// A Grapher is any type that returns a Grapher, mainly used to identify -// dag.Graph and dag.AcyclicGraph. In the case of Graph and AcyclicGraph, they -// return themselves. -type Grapher interface { - DirectedGraph() Grapher -} - -// Vertex of the graph. -type Vertex interface{} - -// NamedVertex is an optional interface that can be implemented by Vertex -// to give it a human-friendly name that is used for outputting the graph. -type NamedVertex interface { - Vertex - Name() string -} - -func (g *Graph) DirectedGraph() Grapher { - return g -} - -// Vertices returns the list of all the vertices in the graph. -func (g *Graph) Vertices() []Vertex { - list := g.vertices.List() - result := make([]Vertex, len(list)) - for i, v := range list { - result[i] = v.(Vertex) - } - - return result -} - -// Edges returns the list of all the edges in the graph. -func (g *Graph) Edges() []Edge { - list := g.edges.List() - result := make([]Edge, len(list)) - for i, v := range list { - result[i] = v.(Edge) - } - - return result -} - -// EdgesFrom returns the list of edges from the given source. -func (g *Graph) EdgesFrom(v Vertex) []Edge { - var result []Edge - from := hashcode(v) - for _, e := range g.Edges() { - if hashcode(e.Source()) == from { - result = append(result, e) - } - } - - return result -} - -// EdgesTo returns the list of edges to the given target. -func (g *Graph) EdgesTo(v Vertex) []Edge { - var result []Edge - search := hashcode(v) - for _, e := range g.Edges() { - if hashcode(e.Target()) == search { - result = append(result, e) - } - } - - return result -} - -// HasVertex checks if the given Vertex is present in the graph. -func (g *Graph) HasVertex(v Vertex) bool { - return g.vertices.Include(v) -} - -// HasEdge checks if the given Edge is present in the graph. -func (g *Graph) HasEdge(e Edge) bool { - return g.edges.Include(e) -} - -// Add adds a vertex to the graph. This is safe to call multiple time with -// the same Vertex. -func (g *Graph) Add(v Vertex) Vertex { - g.init() - g.vertices.Add(v) - g.debug.Add(v) - return v -} - -// Remove removes a vertex from the graph. This will also remove any -// edges with this vertex as a source or target. -func (g *Graph) Remove(v Vertex) Vertex { - // Delete the vertex itself - g.vertices.Delete(v) - g.debug.Remove(v) - - // Delete the edges to non-existent things - for _, target := range g.DownEdges(v).List() { - g.RemoveEdge(BasicEdge(v, target)) - } - for _, source := range g.UpEdges(v).List() { - g.RemoveEdge(BasicEdge(source, v)) - } - - return nil -} - -// Replace replaces the original Vertex with replacement. If the original -// does not exist within the graph, then false is returned. Otherwise, true -// is returned. -func (g *Graph) Replace(original, replacement Vertex) bool { - // If we don't have the original, we can't do anything - if !g.vertices.Include(original) { - return false - } - - defer g.debug.BeginOperation("Replace", "").End("") - - // If they're the same, then don't do anything - if original == replacement { - return true - } - - // Add our new vertex, then copy all the edges - g.Add(replacement) - for _, target := range g.DownEdges(original).List() { - g.Connect(BasicEdge(replacement, target)) - } - for _, source := range g.UpEdges(original).List() { - g.Connect(BasicEdge(source, replacement)) - } - - // Remove our old vertex, which will also remove all the edges - g.Remove(original) - - return true -} - -// RemoveEdge removes an edge from the graph. -func (g *Graph) RemoveEdge(edge Edge) { - g.init() - g.debug.RemoveEdge(edge) - - // Delete the edge from the set - g.edges.Delete(edge) - - // Delete the up/down edges - if s, ok := g.downEdges[hashcode(edge.Source())]; ok { - s.Delete(edge.Target()) - } - if s, ok := g.upEdges[hashcode(edge.Target())]; ok { - s.Delete(edge.Source()) - } -} - -// DownEdges returns the outward edges from the source Vertex v. -func (g *Graph) DownEdges(v Vertex) *Set { - g.init() - return g.downEdges[hashcode(v)] -} - -// UpEdges returns the inward edges to the destination Vertex v. -func (g *Graph) UpEdges(v Vertex) *Set { - g.init() - return g.upEdges[hashcode(v)] -} - -// Connect adds an edge with the given source and target. This is safe to -// call multiple times with the same value. Note that the same value is -// verified through pointer equality of the vertices, not through the -// value of the edge itself. -func (g *Graph) Connect(edge Edge) { - g.init() - g.debug.Connect(edge) - - source := edge.Source() - target := edge.Target() - sourceCode := hashcode(source) - targetCode := hashcode(target) - - // Do we have this already? If so, don't add it again. - if s, ok := g.downEdges[sourceCode]; ok && s.Include(target) { - return - } - - // Add the edge to the set - g.edges.Add(edge) - - // Add the down edge - s, ok := g.downEdges[sourceCode] - if !ok { - s = new(Set) - g.downEdges[sourceCode] = s - } - s.Add(target) - - // Add the up edge - s, ok = g.upEdges[targetCode] - if !ok { - s = new(Set) - g.upEdges[targetCode] = s - } - s.Add(source) -} - -// String outputs some human-friendly output for the graph structure. -func (g *Graph) StringWithNodeTypes() string { - var buf bytes.Buffer - - // Build the list of node names and a mapping so that we can more - // easily alphabetize the output to remain deterministic. - vertices := g.Vertices() - names := make([]string, 0, len(vertices)) - mapping := make(map[string]Vertex, len(vertices)) - for _, v := range vertices { - name := VertexName(v) - names = append(names, name) - mapping[name] = v - } - sort.Strings(names) - - // Write each node in order... - for _, name := range names { - v := mapping[name] - targets := g.downEdges[hashcode(v)] - - buf.WriteString(fmt.Sprintf("%s - %T\n", name, v)) - - // Alphabetize dependencies - deps := make([]string, 0, targets.Len()) - targetNodes := make(map[string]Vertex) - for _, target := range targets.List() { - dep := VertexName(target) - deps = append(deps, dep) - targetNodes[dep] = target - } - sort.Strings(deps) - - // Write dependencies - for _, d := range deps { - buf.WriteString(fmt.Sprintf(" %s - %T\n", d, targetNodes[d])) - } - } - - return buf.String() -} - -// String outputs some human-friendly output for the graph structure. -func (g *Graph) String() string { - var buf bytes.Buffer - - // Build the list of node names and a mapping so that we can more - // easily alphabetize the output to remain deterministic. - vertices := g.Vertices() - names := make([]string, 0, len(vertices)) - mapping := make(map[string]Vertex, len(vertices)) - for _, v := range vertices { - name := VertexName(v) - names = append(names, name) - mapping[name] = v - } - sort.Strings(names) - - // Write each node in order... - for _, name := range names { - v := mapping[name] - targets := g.downEdges[hashcode(v)] - - buf.WriteString(fmt.Sprintf("%s\n", name)) - - // Alphabetize dependencies - deps := make([]string, 0, targets.Len()) - for _, target := range targets.List() { - deps = append(deps, VertexName(target)) - } - sort.Strings(deps) - - // Write dependencies - for _, d := range deps { - buf.WriteString(fmt.Sprintf(" %s\n", d)) - } - } - - return buf.String() -} - -func (g *Graph) init() { - if g.vertices == nil { - g.vertices = new(Set) - } - if g.edges == nil { - g.edges = new(Set) - } - if g.downEdges == nil { - g.downEdges = make(map[interface{}]*Set) - } - if g.upEdges == nil { - g.upEdges = make(map[interface{}]*Set) - } -} - -// Dot returns a dot-formatted representation of the Graph. -func (g *Graph) Dot(opts *DotOpts) []byte { - return newMarshalGraph("", g).Dot(opts) -} - -// MarshalJSON returns a JSON representation of the entire Graph. -func (g *Graph) MarshalJSON() ([]byte, error) { - dg := newMarshalGraph("root", g) - return json.MarshalIndent(dg, "", " ") -} - -// SetDebugWriter sets the io.Writer where the Graph will record debug -// information. After this is set, the graph will immediately encode itself to -// the stream, and continue to record all subsequent operations. -func (g *Graph) SetDebugWriter(w io.Writer) { - g.debug = &encoder{w: w} - g.debug.Encode(newMarshalGraph("root", g)) -} - -// DebugVertexInfo encodes arbitrary information about a vertex in the graph -// debug logs. -func (g *Graph) DebugVertexInfo(v Vertex, info string) { - va := newVertexInfo(typeVertexInfo, v, info) - g.debug.Encode(va) -} - -// DebugEdgeInfo encodes arbitrary information about an edge in the graph debug -// logs. -func (g *Graph) DebugEdgeInfo(e Edge, info string) { - ea := newEdgeInfo(typeEdgeInfo, e, info) - g.debug.Encode(ea) -} - -// DebugVisitInfo records a visit to a Vertex during a walk operation. -func (g *Graph) DebugVisitInfo(v Vertex, info string) { - vi := newVertexInfo(typeVisitInfo, v, info) - g.debug.Encode(vi) -} - -// DebugOperation marks the start of a set of graph transformations in -// the debug log, and returns a DebugOperationEnd func, which marks the end of -// the operation in the log. Additional information can be added to the log via -// the info parameter. -// -// The returned func's End method allows this method to be called from a single -// defer statement: -// defer g.DebugOperationBegin("OpName", "operating").End("") -// -// The returned function must be called to properly close the logical operation -// in the logs. -func (g *Graph) DebugOperation(operation string, info string) DebugOperationEnd { - return g.debug.BeginOperation(operation, info) -} - -// VertexName returns the name of a vertex. -func VertexName(raw Vertex) string { - switch v := raw.(type) { - case NamedVertex: - return v.Name() - case fmt.Stringer: - return fmt.Sprintf("%s", v) - default: - return fmt.Sprintf("%v", v) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/marshal.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/marshal.go deleted file mode 100644 index 7b23ea9c120..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/marshal.go +++ /dev/null @@ -1,460 +0,0 @@ -package dag - -import ( - "encoding/json" - "fmt" - "io" - "log" - "reflect" - "sort" - "strconv" - "sync" -) - -const ( - typeOperation = "Operation" - typeTransform = "Transform" - typeWalk = "Walk" - typeDepthFirstWalk = "DepthFirstWalk" - typeReverseDepthFirstWalk = "ReverseDepthFirstWalk" - typeTransitiveReduction = "TransitiveReduction" - typeEdgeInfo = "EdgeInfo" - typeVertexInfo = "VertexInfo" - typeVisitInfo = "VisitInfo" -) - -// the marshal* structs are for serialization of the graph data. -type marshalGraph struct { - // Type is always "Graph", for identification as a top level object in the - // JSON stream. - Type string - - // Each marshal structure requires a unique ID so that it can be referenced - // by other structures. - ID string `json:",omitempty"` - - // Human readable name for this graph. - Name string `json:",omitempty"` - - // Arbitrary attributes that can be added to the output. - Attrs map[string]string `json:",omitempty"` - - // List of graph vertices, sorted by ID. - Vertices []*marshalVertex `json:",omitempty"` - - // List of edges, sorted by Source ID. - Edges []*marshalEdge `json:",omitempty"` - - // Any number of subgraphs. A subgraph itself is considered a vertex, and - // may be referenced by either end of an edge. - Subgraphs []*marshalGraph `json:",omitempty"` - - // Any lists of vertices that are included in cycles. - Cycles [][]*marshalVertex `json:",omitempty"` -} - -// The add, remove, connect, removeEdge methods mirror the basic Graph -// manipulations to reconstruct a marshalGraph from a debug log. -func (g *marshalGraph) add(v *marshalVertex) { - g.Vertices = append(g.Vertices, v) - sort.Sort(vertices(g.Vertices)) -} - -func (g *marshalGraph) remove(v *marshalVertex) { - for i, existing := range g.Vertices { - if v.ID == existing.ID { - g.Vertices = append(g.Vertices[:i], g.Vertices[i+1:]...) - return - } - } -} - -func (g *marshalGraph) connect(e *marshalEdge) { - g.Edges = append(g.Edges, e) - sort.Sort(edges(g.Edges)) -} - -func (g *marshalGraph) removeEdge(e *marshalEdge) { - for i, existing := range g.Edges { - if e.Source == existing.Source && e.Target == existing.Target { - g.Edges = append(g.Edges[:i], g.Edges[i+1:]...) - return - } - } -} - -func (g *marshalGraph) vertexByID(id string) *marshalVertex { - for _, v := range g.Vertices { - if id == v.ID { - return v - } - } - return nil -} - -type marshalVertex struct { - // Unique ID, used to reference this vertex from other structures. - ID string - - // Human readable name - Name string `json:",omitempty"` - - Attrs map[string]string `json:",omitempty"` - - // This is to help transition from the old Dot interfaces. We record if the - // node was a GraphNodeDotter here, so we can call it to get attributes. - graphNodeDotter GraphNodeDotter -} - -func newMarshalVertex(v Vertex) *marshalVertex { - dn, ok := v.(GraphNodeDotter) - if !ok { - dn = nil - } - - return &marshalVertex{ - ID: marshalVertexID(v), - Name: VertexName(v), - Attrs: make(map[string]string), - graphNodeDotter: dn, - } -} - -// vertices is a sort.Interface implementation for sorting vertices by ID -type vertices []*marshalVertex - -func (v vertices) Less(i, j int) bool { return v[i].Name < v[j].Name } -func (v vertices) Len() int { return len(v) } -func (v vertices) Swap(i, j int) { v[i], v[j] = v[j], v[i] } - -type marshalEdge struct { - // Human readable name - Name string - - // Source and Target Vertices by ID - Source string - Target string - - Attrs map[string]string `json:",omitempty"` -} - -func newMarshalEdge(e Edge) *marshalEdge { - return &marshalEdge{ - Name: fmt.Sprintf("%s|%s", VertexName(e.Source()), VertexName(e.Target())), - Source: marshalVertexID(e.Source()), - Target: marshalVertexID(e.Target()), - Attrs: make(map[string]string), - } -} - -// edges is a sort.Interface implementation for sorting edges by Source ID -type edges []*marshalEdge - -func (e edges) Less(i, j int) bool { return e[i].Name < e[j].Name } -func (e edges) Len() int { return len(e) } -func (e edges) Swap(i, j int) { e[i], e[j] = e[j], e[i] } - -// build a marshalGraph structure from a *Graph -func newMarshalGraph(name string, g *Graph) *marshalGraph { - mg := &marshalGraph{ - Type: "Graph", - Name: name, - Attrs: make(map[string]string), - } - - for _, v := range g.Vertices() { - id := marshalVertexID(v) - if sg, ok := marshalSubgrapher(v); ok { - smg := newMarshalGraph(VertexName(v), sg) - smg.ID = id - mg.Subgraphs = append(mg.Subgraphs, smg) - } - - mv := newMarshalVertex(v) - mg.Vertices = append(mg.Vertices, mv) - } - - sort.Sort(vertices(mg.Vertices)) - - for _, e := range g.Edges() { - mg.Edges = append(mg.Edges, newMarshalEdge(e)) - } - - sort.Sort(edges(mg.Edges)) - - for _, c := range (&AcyclicGraph{*g}).Cycles() { - var cycle []*marshalVertex - for _, v := range c { - mv := newMarshalVertex(v) - cycle = append(cycle, mv) - } - mg.Cycles = append(mg.Cycles, cycle) - } - - return mg -} - -// Attempt to return a unique ID for any vertex. -func marshalVertexID(v Vertex) string { - val := reflect.ValueOf(v) - switch val.Kind() { - case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: - return strconv.Itoa(int(val.Pointer())) - case reflect.Interface: - return strconv.Itoa(int(val.InterfaceData()[1])) - } - - if v, ok := v.(Hashable); ok { - h := v.Hashcode() - if h, ok := h.(string); ok { - return h - } - } - - // fallback to a name, which we hope is unique. - return VertexName(v) - - // we could try harder by attempting to read the arbitrary value from the - // interface, but we shouldn't get here from terraform right now. -} - -// check for a Subgrapher, and return the underlying *Graph. -func marshalSubgrapher(v Vertex) (*Graph, bool) { - sg, ok := v.(Subgrapher) - if !ok { - return nil, false - } - - switch g := sg.Subgraph().DirectedGraph().(type) { - case *Graph: - return g, true - case *AcyclicGraph: - return &g.Graph, true - } - - return nil, false -} - -// The DebugOperationEnd func type provides a way to call an End function via a -// method call, allowing for the chaining of methods in a defer statement. -type DebugOperationEnd func(string) - -// End calls function e with the info parameter, marking the end of this -// operation in the logs. -func (e DebugOperationEnd) End(info string) { e(info) } - -// encoder provides methods to write debug data to an io.Writer, and is a noop -// when no writer is present -type encoder struct { - sync.Mutex - w io.Writer -} - -// Encode is analogous to json.Encoder.Encode -func (e *encoder) Encode(i interface{}) { - if e == nil || e.w == nil { - return - } - e.Lock() - defer e.Unlock() - - js, err := json.Marshal(i) - if err != nil { - log.Println("[ERROR] dag:", err) - return - } - js = append(js, '\n') - - _, err = e.w.Write(js) - if err != nil { - log.Println("[ERROR] dag:", err) - return - } -} - -func (e *encoder) Add(v Vertex) { - if e == nil { - return - } - e.Encode(marshalTransform{ - Type: typeTransform, - AddVertex: newMarshalVertex(v), - }) -} - -// Remove records the removal of Vertex v. -func (e *encoder) Remove(v Vertex) { - if e == nil { - return - } - e.Encode(marshalTransform{ - Type: typeTransform, - RemoveVertex: newMarshalVertex(v), - }) -} - -func (e *encoder) Connect(edge Edge) { - if e == nil { - return - } - e.Encode(marshalTransform{ - Type: typeTransform, - AddEdge: newMarshalEdge(edge), - }) -} - -func (e *encoder) RemoveEdge(edge Edge) { - if e == nil { - return - } - e.Encode(marshalTransform{ - Type: typeTransform, - RemoveEdge: newMarshalEdge(edge), - }) -} - -// BeginOperation marks the start of set of graph transformations, and returns -// an EndDebugOperation func to be called once the opration is complete. -func (e *encoder) BeginOperation(op string, info string) DebugOperationEnd { - if e == nil { - return func(string) {} - } - - e.Encode(marshalOperation{ - Type: typeOperation, - Begin: op, - Info: info, - }) - - return func(info string) { - e.Encode(marshalOperation{ - Type: typeOperation, - End: op, - Info: info, - }) - } -} - -// structure for recording graph transformations -type marshalTransform struct { - // Type: "Transform" - Type string - AddEdge *marshalEdge `json:",omitempty"` - RemoveEdge *marshalEdge `json:",omitempty"` - AddVertex *marshalVertex `json:",omitempty"` - RemoveVertex *marshalVertex `json:",omitempty"` -} - -func (t marshalTransform) Transform(g *marshalGraph) { - switch { - case t.AddEdge != nil: - g.connect(t.AddEdge) - case t.RemoveEdge != nil: - g.removeEdge(t.RemoveEdge) - case t.AddVertex != nil: - g.add(t.AddVertex) - case t.RemoveVertex != nil: - g.remove(t.RemoveVertex) - } -} - -// this structure allows us to decode any object in the json stream for -// inspection, then re-decode it into a proper struct if needed. -type streamDecode struct { - Type string - Map map[string]interface{} - JSON []byte -} - -func (s *streamDecode) UnmarshalJSON(d []byte) error { - s.JSON = d - err := json.Unmarshal(d, &s.Map) - if err != nil { - return err - } - - if t, ok := s.Map["Type"]; ok { - s.Type, _ = t.(string) - } - return nil -} - -// structure for recording the beginning and end of any multi-step -// transformations. These are informational, and not required to reproduce the -// graph state. -type marshalOperation struct { - Type string - Begin string `json:",omitempty"` - End string `json:",omitempty"` - Info string `json:",omitempty"` -} - -// decodeGraph decodes a marshalGraph from an encoded graph stream. -func decodeGraph(r io.Reader) (*marshalGraph, error) { - dec := json.NewDecoder(r) - - // a stream should always start with a graph - g := &marshalGraph{} - - err := dec.Decode(g) - if err != nil { - return nil, err - } - - // now replay any operations that occurred on the original graph - for dec.More() { - s := &streamDecode{} - err := dec.Decode(s) - if err != nil { - return g, err - } - - // the only Type we're concerned with here is Transform to complete the - // Graph - if s.Type != typeTransform { - continue - } - - t := &marshalTransform{} - err = json.Unmarshal(s.JSON, t) - if err != nil { - return g, err - } - t.Transform(g) - } - return g, nil -} - -// marshalVertexInfo allows encoding arbitrary information about the a single -// Vertex in the logs. These are accumulated for informational display while -// rebuilding the graph. -type marshalVertexInfo struct { - Type string - Vertex *marshalVertex - Info string -} - -func newVertexInfo(infoType string, v Vertex, info string) *marshalVertexInfo { - return &marshalVertexInfo{ - Type: infoType, - Vertex: newMarshalVertex(v), - Info: info, - } -} - -// marshalEdgeInfo allows encoding arbitrary information about the a single -// Edge in the logs. These are accumulated for informational display while -// rebuilding the graph. -type marshalEdgeInfo struct { - Type string - Edge *marshalEdge - Info string -} - -func newEdgeInfo(infoType string, e Edge, info string) *marshalEdgeInfo { - return &marshalEdgeInfo{ - Type: infoType, - Edge: newMarshalEdge(e), - Info: info, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/set.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/set.go deleted file mode 100644 index 92b42151d75..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/set.go +++ /dev/null @@ -1,123 +0,0 @@ -package dag - -import ( - "sync" -) - -// Set is a set data structure. -type Set struct { - m map[interface{}]interface{} - once sync.Once -} - -// Hashable is the interface used by set to get the hash code of a value. -// If this isn't given, then the value of the item being added to the set -// itself is used as the comparison value. -type Hashable interface { - Hashcode() interface{} -} - -// hashcode returns the hashcode used for set elements. -func hashcode(v interface{}) interface{} { - if h, ok := v.(Hashable); ok { - return h.Hashcode() - } - - return v -} - -// Add adds an item to the set -func (s *Set) Add(v interface{}) { - s.once.Do(s.init) - s.m[hashcode(v)] = v -} - -// Delete removes an item from the set. -func (s *Set) Delete(v interface{}) { - s.once.Do(s.init) - delete(s.m, hashcode(v)) -} - -// Include returns true/false of whether a value is in the set. -func (s *Set) Include(v interface{}) bool { - s.once.Do(s.init) - _, ok := s.m[hashcode(v)] - return ok -} - -// Intersection computes the set intersection with other. -func (s *Set) Intersection(other *Set) *Set { - result := new(Set) - if s == nil { - return result - } - if other != nil { - for _, v := range s.m { - if other.Include(v) { - result.Add(v) - } - } - } - - return result -} - -// Difference returns a set with the elements that s has but -// other doesn't. -func (s *Set) Difference(other *Set) *Set { - result := new(Set) - if s != nil { - for k, v := range s.m { - var ok bool - if other != nil { - _, ok = other.m[k] - } - if !ok { - result.Add(v) - } - } - } - - return result -} - -// 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 { - return 0 - } - - return len(s.m) -} - -// List returns the list of set elements. -func (s *Set) List() []interface{} { - if s == nil { - return nil - } - - r := make([]interface{}, 0, len(s.m)) - for _, v := range s.m { - r = append(r, v) - } - - return r -} - -func (s *Set) init() { - s.m = make(map[interface{}]interface{}) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/tarjan.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/tarjan.go deleted file mode 100644 index 9d8b25ce2ca..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/tarjan.go +++ /dev/null @@ -1,107 +0,0 @@ -package dag - -// StronglyConnected returns the list of strongly connected components -// within the Graph g. This information is primarily used by this package -// for cycle detection, but strongly connected components have widespread -// use. -func StronglyConnected(g *Graph) [][]Vertex { - vs := g.Vertices() - acct := sccAcct{ - NextIndex: 1, - VertexIndex: make(map[Vertex]int, len(vs)), - } - for _, v := range vs { - // Recurse on any non-visited nodes - if acct.VertexIndex[v] == 0 { - stronglyConnected(&acct, g, v) - } - } - return acct.SCC -} - -func stronglyConnected(acct *sccAcct, g *Graph, v Vertex) int { - // Initial vertex visit - index := acct.visit(v) - minIdx := index - - for _, raw := range g.DownEdges(v).List() { - target := raw.(Vertex) - targetIdx := acct.VertexIndex[target] - - // Recurse on successor if not yet visited - if targetIdx == 0 { - minIdx = min(minIdx, stronglyConnected(acct, g, target)) - } else if acct.inStack(target) { - // Check if the vertex is in the stack - minIdx = min(minIdx, targetIdx) - } - } - - // Pop the strongly connected components off the stack if - // this is a root vertex - if index == minIdx { - var scc []Vertex - for { - v2 := acct.pop() - scc = append(scc, v2) - if v2 == v { - break - } - } - - acct.SCC = append(acct.SCC, scc) - } - - return minIdx -} - -func min(a, b int) int { - if a <= b { - return a - } - return b -} - -// sccAcct is used ot pass around accounting information for -// the StronglyConnectedComponents algorithm -type sccAcct struct { - NextIndex int - VertexIndex map[Vertex]int - Stack []Vertex - SCC [][]Vertex -} - -// visit assigns an index and pushes a vertex onto the stack -func (s *sccAcct) visit(v Vertex) int { - idx := s.NextIndex - s.VertexIndex[v] = idx - s.NextIndex++ - s.push(v) - return idx -} - -// push adds a vertex to the stack -func (s *sccAcct) push(n Vertex) { - s.Stack = append(s.Stack, n) -} - -// pop removes a vertex from the stack -func (s *sccAcct) pop() Vertex { - n := len(s.Stack) - if n == 0 { - return nil - } - vertex := s.Stack[n-1] - s.Stack = s.Stack[:n-1] - return vertex -} - -// inStack checks if a vertex is in the stack -func (s *sccAcct) inStack(needle Vertex) bool { - for _, n := range s.Stack { - if n == needle { - return true - } - } - return false -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/walk.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/walk.go deleted file mode 100644 index 5ddf8ef34c1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/walk.go +++ /dev/null @@ -1,454 +0,0 @@ -package dag - -import ( - "errors" - "log" - "sync" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// Walker is used to walk every vertex of a graph in parallel. -// -// A vertex will only be walked when the dependencies of that vertex have -// been walked. If two vertices can be walked at the same time, they will be. -// -// Update can be called to update the graph. This can be called even during -// a walk, cahnging vertices/edges mid-walk. This should be done carefully. -// If a vertex is removed but has already been executed, the result of that -// execution (any error) is still returned by Wait. Changing or re-adding -// a vertex that has already executed has no effect. Changing edges of -// a vertex that has already executed has no effect. -// -// Non-parallelism can be enforced by introducing a lock in your callback -// function. However, the goroutine overhead of a walk will remain. -// Walker will create V*2 goroutines (one for each vertex, and dependency -// waiter for each vertex). In general this should be of no concern unless -// there are a huge number of vertices. -// -// The walk is depth first by default. This can be changed with the Reverse -// option. -// -// A single walker is only valid for one graph walk. After the walk is complete -// you must construct a new walker to walk again. State for the walk is never -// deleted in case vertices or edges are changed. -type Walker struct { - // Callback is what is called for each vertex - Callback WalkFunc - - // Reverse, if true, causes the source of an edge to depend on a target. - // When false (default), the target depends on the source. - Reverse bool - - // changeLock must be held to modify any of the fields below. Only Update - // should modify these fields. Modifying them outside of Update can cause - // serious problems. - changeLock sync.Mutex - vertices Set - edges Set - vertexMap map[Vertex]*walkerVertex - - // wait is done when all vertices have executed. It may become "undone" - // if new vertices are added. - wait sync.WaitGroup - - // diagsMap contains the diagnostics recorded so far for execution, - // and upstreamFailed contains all the vertices whose problems were - // caused by upstream failures, and thus whose diagnostics should be - // excluded from the final set. - // - // Readers and writers of either map must hold diagsLock. - diagsMap map[Vertex]tfdiags.Diagnostics - upstreamFailed map[Vertex]struct{} - diagsLock sync.Mutex -} - -type walkerVertex struct { - // These should only be set once on initialization and never written again. - // They are not protected by a lock since they don't need to be since - // they are write-once. - - // DoneCh is closed when this vertex has completed execution, regardless - // of success. - // - // CancelCh is closed when the vertex should cancel execution. If execution - // is already complete (DoneCh is closed), this has no effect. Otherwise, - // execution is cancelled as quickly as possible. - DoneCh chan struct{} - CancelCh chan struct{} - - // Dependency information. Any changes to any of these fields requires - // holding DepsLock. - // - // DepsCh is sent a single value that denotes whether the upstream deps - // were successful (no errors). Any value sent means that the upstream - // dependencies are complete. No other values will ever be sent again. - // - // DepsUpdateCh is closed when there is a new DepsCh set. - DepsCh chan bool - DepsUpdateCh chan struct{} - DepsLock sync.Mutex - - // Below is not safe to read/write in parallel. This behavior is - // enforced by changes only happening in Update. Nothing else should - // ever modify these. - deps map[Vertex]chan struct{} - depsCancelCh chan struct{} -} - -// Wait waits for the completion of the walk and returns diagnostics describing -// any problems that arose. Update should be called to populate the walk with -// vertices and edges prior to calling this. -// -// Wait will return as soon as all currently known vertices are complete. -// If you plan on calling Update with more vertices in the future, you -// should not call Wait until after this is done. -func (w *Walker) Wait() tfdiags.Diagnostics { - // Wait for completion - w.wait.Wait() - - var diags tfdiags.Diagnostics - w.diagsLock.Lock() - for v, vDiags := range w.diagsMap { - if _, upstream := w.upstreamFailed[v]; upstream { - // Ignore diagnostics for nodes that had failed upstreams, since - // the downstream diagnostics are likely to be redundant. - continue - } - diags = diags.Append(vDiags) - } - w.diagsLock.Unlock() - - return diags -} - -// Update updates the currently executing walk with the given graph. -// This will perform a diff of the vertices and edges and update the walker. -// Already completed vertices remain completed (including any errors during -// their execution). -// -// This returns immediately once the walker is updated; it does not wait -// for completion of the walk. -// -// Multiple Updates can be called in parallel. Update can be called at any -// time during a walk. -func (w *Walker) Update(g *AcyclicGraph) { - log.Print("[TRACE] dag/walk: updating graph") - var v, e *Set - if g != nil { - v, e = g.vertices, g.edges - } - - // Grab the change lock so no more updates happen but also so that - // no new vertices are executed during this time since we may be - // removing them. - w.changeLock.Lock() - defer w.changeLock.Unlock() - - // Initialize fields - if w.vertexMap == nil { - w.vertexMap = make(map[Vertex]*walkerVertex) - } - - // Calculate all our sets - newEdges := e.Difference(&w.edges) - oldEdges := w.edges.Difference(e) - newVerts := v.Difference(&w.vertices) - oldVerts := w.vertices.Difference(v) - - // Add the new vertices - for _, raw := range newVerts.List() { - v := raw.(Vertex) - - // Add to the waitgroup so our walk is not done until everything finishes - w.wait.Add(1) - - // Add to our own set so we know about it already - log.Printf("[TRACE] dag/walk: added new vertex: %q", VertexName(v)) - w.vertices.Add(raw) - - // Initialize the vertex info - info := &walkerVertex{ - DoneCh: make(chan struct{}), - CancelCh: make(chan struct{}), - deps: make(map[Vertex]chan struct{}), - } - - // Add it to the map and kick off the walk - w.vertexMap[v] = info - } - - // Remove the old vertices - for _, raw := range oldVerts.List() { - v := raw.(Vertex) - - // Get the vertex info so we can cancel it - info, ok := w.vertexMap[v] - if !ok { - // This vertex for some reason was never in our map. This - // shouldn't be possible. - continue - } - - // Cancel the vertex - close(info.CancelCh) - - // Delete it out of the map - delete(w.vertexMap, v) - - log.Printf("[TRACE] dag/walk: removed vertex: %q", VertexName(v)) - w.vertices.Delete(raw) - } - - // Add the new edges - var changedDeps Set - for _, raw := range newEdges.List() { - edge := raw.(Edge) - waiter, dep := w.edgeParts(edge) - - // Get the info for the waiter - waiterInfo, ok := w.vertexMap[waiter] - if !ok { - // Vertex doesn't exist... shouldn't be possible but ignore. - continue - } - - // Get the info for the dep - depInfo, ok := w.vertexMap[dep] - if !ok { - // Vertex doesn't exist... shouldn't be possible but ignore. - continue - } - - // Add the dependency to our waiter - waiterInfo.deps[dep] = depInfo.DoneCh - - // Record that the deps changed for this waiter - changedDeps.Add(waiter) - - log.Printf( - "[TRACE] dag/walk: added edge: %q waiting on %q", - VertexName(waiter), VertexName(dep)) - w.edges.Add(raw) - } - - // Process reoved edges - for _, raw := range oldEdges.List() { - edge := raw.(Edge) - waiter, dep := w.edgeParts(edge) - - // Get the info for the waiter - waiterInfo, ok := w.vertexMap[waiter] - if !ok { - // Vertex doesn't exist... shouldn't be possible but ignore. - continue - } - - // Delete the dependency from the waiter - delete(waiterInfo.deps, dep) - - // Record that the deps changed for this waiter - changedDeps.Add(waiter) - - log.Printf( - "[TRACE] dag/walk: removed edge: %q waiting on %q", - VertexName(waiter), VertexName(dep)) - w.edges.Delete(raw) - } - - // For each vertex with changed dependencies, we need to kick off - // a new waiter and notify the vertex of the changes. - for _, raw := range changedDeps.List() { - v := raw.(Vertex) - info, ok := w.vertexMap[v] - if !ok { - // Vertex doesn't exist... shouldn't be possible but ignore. - continue - } - - // Create a new done channel - doneCh := make(chan bool, 1) - - // Create the channel we close for cancellation - cancelCh := make(chan struct{}) - - // Build a new deps copy - deps := make(map[Vertex]<-chan struct{}) - for k, v := range info.deps { - deps[k] = v - } - - // Update the update channel - info.DepsLock.Lock() - if info.DepsUpdateCh != nil { - close(info.DepsUpdateCh) - } - info.DepsCh = doneCh - info.DepsUpdateCh = make(chan struct{}) - info.DepsLock.Unlock() - - // Cancel the older waiter - if info.depsCancelCh != nil { - close(info.depsCancelCh) - } - info.depsCancelCh = cancelCh - - log.Printf( - "[TRACE] dag/walk: dependencies changed for %q, sending new deps", - VertexName(v)) - - // Start the waiter - go w.waitDeps(v, deps, doneCh, cancelCh) - } - - // Start all the new vertices. We do this at the end so that all - // the edge waiters and changes are setup above. - for _, raw := range newVerts.List() { - v := raw.(Vertex) - go w.walkVertex(v, w.vertexMap[v]) - } -} - -// edgeParts returns the waiter and the dependency, in that order. -// The waiter is waiting on the dependency. -func (w *Walker) edgeParts(e Edge) (Vertex, Vertex) { - if w.Reverse { - return e.Source(), e.Target() - } - - return e.Target(), e.Source() -} - -// walkVertex walks a single vertex, waiting for any dependencies before -// executing the callback. -func (w *Walker) walkVertex(v Vertex, info *walkerVertex) { - // When we're done executing, lower the waitgroup count - defer w.wait.Done() - - // When we're done, always close our done channel - defer close(info.DoneCh) - - // Wait for our dependencies. We create a [closed] deps channel so - // that we can immediately fall through to load our actual DepsCh. - var depsSuccess bool - var depsUpdateCh chan struct{} - depsCh := make(chan bool, 1) - depsCh <- true - close(depsCh) - for { - select { - case <-info.CancelCh: - // Cancel - return - - case depsSuccess = <-depsCh: - // Deps complete! Mark as nil to trigger completion handling. - depsCh = nil - - case <-depsUpdateCh: - // New deps, reloop - } - - // Check if we have updated dependencies. This can happen if the - // dependencies were satisfied exactly prior to an Update occurring. - // In that case, we'd like to take into account new dependencies - // if possible. - info.DepsLock.Lock() - if info.DepsCh != nil { - depsCh = info.DepsCh - info.DepsCh = nil - } - if info.DepsUpdateCh != nil { - depsUpdateCh = info.DepsUpdateCh - } - info.DepsLock.Unlock() - - // If we still have no deps channel set, then we're done! - if depsCh == nil { - break - } - } - - // If we passed dependencies, we just want to check once more that - // we're not cancelled, since this can happen just as dependencies pass. - select { - case <-info.CancelCh: - // Cancelled during an update while dependencies completed. - return - default: - } - - // Run our callback or note that our upstream failed - var diags tfdiags.Diagnostics - var upstreamFailed bool - if depsSuccess { - log.Printf("[TRACE] dag/walk: visiting %q", VertexName(v)) - diags = w.Callback(v) - } else { - log.Printf("[TRACE] dag/walk: upstream of %q errored, so skipping", VertexName(v)) - // This won't be displayed to the user because we'll set upstreamFailed, - // but we need to ensure there's at least one error in here so that - // the failures will cascade downstream. - diags = diags.Append(errors.New("upstream dependencies failed")) - upstreamFailed = true - } - - // Record the result (we must do this after execution because we mustn't - // hold diagsLock while visiting a vertex.) - w.diagsLock.Lock() - if w.diagsMap == nil { - w.diagsMap = make(map[Vertex]tfdiags.Diagnostics) - } - w.diagsMap[v] = diags - if w.upstreamFailed == nil { - w.upstreamFailed = make(map[Vertex]struct{}) - } - if upstreamFailed { - w.upstreamFailed[v] = struct{}{} - } - w.diagsLock.Unlock() -} - -func (w *Walker) waitDeps( - v Vertex, - deps map[Vertex]<-chan struct{}, - doneCh chan<- bool, - cancelCh <-chan struct{}) { - - // For each dependency given to us, wait for it to complete - for dep, depCh := range deps { - DepSatisfied: - for { - select { - case <-depCh: - // Dependency satisfied! - break DepSatisfied - - case <-cancelCh: - // Wait cancelled. Note that we didn't satisfy dependencies - // so that anything waiting on us also doesn't run. - doneCh <- false - return - - case <-time.After(time.Second * 5): - log.Printf("[TRACE] dag/walk: vertex %q is waiting for %q", - VertexName(v), VertexName(dep)) - } - } - } - - // Dependencies satisfied! We need to check if any errored - w.diagsLock.Lock() - defer w.diagsLock.Unlock() - for dep := range deps { - if w.diagsMap[dep].HasErrors() { - // One of our dependencies failed, so return false - doneCh <- false - return - } - } - - // All dependencies satisfied and successful - doneCh <- true -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/config.go deleted file mode 100644 index b86bd7923aa..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/config.go +++ /dev/null @@ -1,63 +0,0 @@ -package earlyconfig - -import ( - version "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// A Config is a node in the tree of modules within a configuration. -// -// The module tree is constructed by following ModuleCall instances recursively -// through the root module transitively into descendent modules. -type Config struct { - // RootModule points to the Config for the root module within the same - // module tree as this module. If this module _is_ the root module then - // this is self-referential. - Root *Config - - // ParentModule points to the Config for the module that directly calls - // this module. If this is the root module then this field is nil. - Parent *Config - - // Path is a sequence of module logical names that traverse from the root - // module to this config. Path is empty for the root module. - // - // This should only be used to display paths to the end-user in rare cases - // where we are talking about the static module tree, before module calls - // have been resolved. In most cases, an addrs.ModuleInstance describing - // a node in the dynamic module tree is better, since it will then include - // any keys resulting from evaluating "count" and "for_each" arguments. - Path addrs.Module - - // ChildModules points to the Config for each of the direct child modules - // called from this module. The keys in this map match the keys in - // Module.ModuleCalls. - Children map[string]*Config - - // Module points to the object describing the configuration for the - // various elements (variables, resources, etc) defined by this module. - Module *tfconfig.Module - - // CallPos is the source position for the header of the module block that - // requested this module. - // - // This field is meaningless for the root module, where its contents are undefined. - CallPos tfconfig.SourcePos - - // SourceAddr is the source address that the referenced module was requested - // from, as specified in configuration. - // - // This field is meaningless for the root module, where its contents are undefined. - SourceAddr string - - // Version is the specific version that was selected for this module, - // based on version constraints given in configuration. - // - // This field is nil if the module was loaded from a non-registry source, - // since versions are not supported for other sources. - // - // This field is meaningless for the root module, where it will always - // be nil. - Version *version.Version -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/config_build.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/config_build.go deleted file mode 100644 index 3707f2738df..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/config_build.go +++ /dev/null @@ -1,144 +0,0 @@ -package earlyconfig - -import ( - "fmt" - "sort" - "strings" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// BuildConfig constructs a Config from a root module by loading all of its -// descendent modules via the given ModuleWalker. -func BuildConfig(root *tfconfig.Module, walker ModuleWalker) (*Config, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - cfg := &Config{ - Module: root, - } - cfg.Root = cfg // Root module is self-referential. - cfg.Children, diags = buildChildModules(cfg, walker) - return cfg, diags -} - -func buildChildModules(parent *Config, walker ModuleWalker) (map[string]*Config, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - ret := map[string]*Config{} - calls := parent.Module.ModuleCalls - - // We'll sort the calls by their local names so that they'll appear in a - // predictable order in any logging that's produced during the walk. - callNames := make([]string, 0, len(calls)) - for k := range calls { - callNames = append(callNames, k) - } - sort.Strings(callNames) - - for _, callName := range callNames { - call := calls[callName] - path := make([]string, len(parent.Path)+1) - copy(path, parent.Path) - path[len(path)-1] = call.Name - - var vc version.Constraints - if strings.TrimSpace(call.Version) != "" { - var err error - vc, err = version.NewConstraint(call.Version) - if err != nil { - diags = diags.Append(wrapDiagnostic(tfconfig.Diagnostic{ - Severity: tfconfig.DiagError, - Summary: "Invalid version constraint", - Detail: fmt.Sprintf("Module %q (declared at %s line %d) has invalid version constraint %q: %s.", callName, call.Pos.Filename, call.Pos.Line, call.Version, err), - })) - continue - } - } - - req := ModuleRequest{ - Name: call.Name, - Path: path, - SourceAddr: call.Source, - VersionConstraints: vc, - Parent: parent, - CallPos: call.Pos, - } - - mod, ver, modDiags := walker.LoadModule(&req) - diags = append(diags, modDiags...) - if mod == nil { - // nil can be returned if the source address was invalid and so - // nothing could be loaded whatsoever. LoadModule should've - // returned at least one error diagnostic in that case. - continue - } - - child := &Config{ - Parent: parent, - Root: parent.Root, - Path: path, - Module: mod, - CallPos: call.Pos, - SourceAddr: call.Source, - Version: ver, - } - - child.Children, modDiags = buildChildModules(child, walker) - diags = diags.Append(modDiags) - - ret[call.Name] = child - } - - return ret, diags -} - -// ModuleRequest is used as part of the ModuleWalker interface used with -// function BuildConfig. -type ModuleRequest struct { - // Name is the "logical name" of the module call within configuration. - // This is provided in case the name is used as part of a storage key - // for the module, but implementations must otherwise treat it as an - // opaque string. It is guaranteed to have already been validated as an - // HCL identifier and UTF-8 encoded. - Name string - - // Path is a list of logical names that traverse from the root module to - // this module. This can be used, for example, to form a lookup key for - // each distinct module call in a configuration, allowing for multiple - // calls with the same name at different points in the tree. - Path addrs.Module - - // SourceAddr is the source address string provided by the user in - // configuration. - SourceAddr string - - // VersionConstraint is the version constraint applied to the module in - // configuration. - VersionConstraints version.Constraints - - // Parent is the partially-constructed module tree node that the loaded - // module will be added to. Callers may refer to any field of this - // structure except Children, which is still under construction when - // ModuleRequest objects are created and thus has undefined content. - // The main reason this is provided is so that full module paths can - // be constructed for uniqueness. - Parent *Config - - // CallRange is the source position for the header of the "module" block - // in configuration that prompted this request. - CallPos tfconfig.SourcePos -} - -// ModuleWalker is an interface used with BuildConfig. -type ModuleWalker interface { - LoadModule(req *ModuleRequest) (*tfconfig.Module, *version.Version, tfdiags.Diagnostics) -} - -// ModuleWalkerFunc is an implementation of ModuleWalker that directly wraps -// a callback function, for more convenient use of that interface. -type ModuleWalkerFunc func(req *ModuleRequest) (*tfconfig.Module, *version.Version, tfdiags.Diagnostics) - -func (f ModuleWalkerFunc) LoadModule(req *ModuleRequest) (*tfconfig.Module, *version.Version, tfdiags.Diagnostics) { - return f(req) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/diagnostics.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/diagnostics.go deleted file mode 100644 index b2e1807eb7a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/diagnostics.go +++ /dev/null @@ -1,78 +0,0 @@ -package earlyconfig - -import ( - "fmt" - - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -func wrapDiagnostics(diags tfconfig.Diagnostics) tfdiags.Diagnostics { - ret := make(tfdiags.Diagnostics, len(diags)) - for i, diag := range diags { - ret[i] = wrapDiagnostic(diag) - } - return ret -} - -func wrapDiagnostic(diag tfconfig.Diagnostic) tfdiags.Diagnostic { - return wrappedDiagnostic{ - d: diag, - } -} - -type wrappedDiagnostic struct { - d tfconfig.Diagnostic -} - -func (d wrappedDiagnostic) Severity() tfdiags.Severity { - switch d.d.Severity { - case tfconfig.DiagError: - return tfdiags.Error - case tfconfig.DiagWarning: - return tfdiags.Warning - default: - // Should never happen since there are no other severities - return 0 - } -} - -func (d wrappedDiagnostic) Description() tfdiags.Description { - // Since the inspect library doesn't produce precise source locations, - // we include the position information as part of the error message text. - // See the comment inside method "Source" for more information. - switch { - case d.d.Pos == nil: - return tfdiags.Description{ - Summary: d.d.Summary, - Detail: d.d.Detail, - } - case d.d.Detail != "": - return tfdiags.Description{ - Summary: d.d.Summary, - Detail: fmt.Sprintf("On %s line %d: %s", d.d.Pos.Filename, d.d.Pos.Line, d.d.Detail), - } - default: - return tfdiags.Description{ - Summary: fmt.Sprintf("%s (on %s line %d)", d.d.Summary, d.d.Pos.Filename, d.d.Pos.Line), - } - } -} - -func (d wrappedDiagnostic) Source() tfdiags.Source { - // Since the inspect library is constrained by the lowest common denominator - // between legacy HCL and modern HCL, it only returns ranges at whole-line - // granularity, and that isn't sufficient to populate a tfdiags.Source - // and so we'll just omit ranges altogether and include the line number in - // the Description text. - // - // Callers that want to return nicer errors should consider reacting to - // earlyconfig errors by attempting a follow-up parse with the normal - // config loader, which can produce more precise source location - // information. - return tfdiags.Source{} -} - -func (d wrappedDiagnostic) FromExpr() *tfdiags.FromExpr { - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/doc.go deleted file mode 100644 index a9cf10f37c2..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -// Package earlyconfig is a specialized alternative to the top-level "configs" -// package that does only shallow processing of configuration and is therefore -// able to be much more liberal than the full config loader in what it accepts. -// -// In particular, it can accept both current and legacy HCL syntax, and it -// ignores top-level blocks that it doesn't recognize. These two characteristics -// make this package ideal for dependency-checking use-cases so that we are -// more likely to be able to return an error message about an explicit -// incompatibility than to return a less-actionable message about a construct -// not being supported. -// -// However, its liberal approach also means it should be used sparingly. It -// exists primarily for "terraform init", so that it is able to detect -// incompatibilities more robustly when installing dependencies. For most -// other use-cases, use the "configs" and "configs/configload" packages. -// -// Package earlyconfig is a wrapper around the terraform-config-inspect -// codebase, adding to it just some helper functionality for Terraform's own -// use-cases. -package earlyconfig diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/module.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/module.go deleted file mode 100644 index 11eff2eb692..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig/module.go +++ /dev/null @@ -1,13 +0,0 @@ -package earlyconfig - -import ( - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// LoadModule loads some top-level metadata for the module in the given -// directory. -func LoadModule(dir string) (*tfconfig.Module, tfdiags.Diagnostics) { - mod, diags := tfconfig.LoadModule(dir) - return mod, wrapDiagnostics(diags) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/flatmap/expand.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/flatmap/expand.go deleted file mode 100644 index 1bb7b9f2f96..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/flatmap/expand.go +++ /dev/null @@ -1,152 +0,0 @@ -package flatmap - -import ( - "fmt" - "sort" - "strconv" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" -) - -// Expand takes a map and a key (prefix) and expands that value into -// a more complex structure. This is the reverse of the Flatten operation. -func Expand(m map[string]string, key string) interface{} { - // If the key is exactly a key in the map, just return it - if v, ok := m[key]; ok { - if v == "true" { - return true - } else if v == "false" { - return false - } - - return v - } - - // Check if the key is an array, and if so, expand the array - if v, ok := m[key+".#"]; ok { - // If the count of the key is unknown, then just put the unknown - // value in the value itself. This will be detected by Terraform - // core later. - if v == hcl2shim.UnknownVariableValue { - return v - } - - return expandArray(m, key) - } - - // Check if this is a prefix in the map - prefix := key + "." - for k := range m { - if strings.HasPrefix(k, prefix) { - return expandMap(m, prefix) - } - } - - return nil -} - -func expandArray(m map[string]string, prefix string) []interface{} { - num, err := strconv.ParseInt(m[prefix+".#"], 0, 0) - if err != nil { - panic(err) - } - - // 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{}{} - } - - // NOTE: "num" is not necessarily accurate, e.g. if a user tampers - // with state, so the following code should not crash when given a - // number of items more or less than what's given in num. The - // num key is mainly just a hint that this is a list or set. - - // The Schema "Set" type stores its values in an array format, but - // using numeric hash values instead of ordinal keys. Take the set - // of keys regardless of value, and expand them in numeric order. - // See GH-11042 for more details. - keySet := map[int]bool{} - computed := map[string]bool{} - for k := range m { - if !strings.HasPrefix(k, prefix+".") { - continue - } - - key := k[len(prefix)+1:] - idx := strings.Index(key, ".") - if idx != -1 { - key = key[:idx] - } - - // skip the count value - if key == "#" { - continue - } - - // strip the computed flag if there is one - if strings.HasPrefix(key, "~") { - key = key[1:] - computed[key] = true - } - - k, err := strconv.Atoi(key) - if err != nil { - panic(err) - } - keySet[int(k)] = true - } - - keysList := make([]int, 0, num) - for key := range keySet { - keysList = append(keysList, key) - } - sort.Ints(keysList) - - result := make([]interface{}, len(keysList)) - for i, key := range keysList { - keyString := strconv.Itoa(key) - if computed[keyString] { - keyString = "~" + keyString - } - result[i] = Expand(m, fmt.Sprintf("%s.%s", prefix, keyString)) - } - - return result -} - -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 { - if !strings.HasPrefix(k, prefix) { - continue - } - - key := k[len(prefix):] - idx := strings.Index(key, ".") - if idx != -1 { - key = key[:idx] - } - if _, ok := result[key]; ok { - continue - } - - // skip the map count value - if key == "%" { - continue - } - - result[key] = Expand(m, k[:len(prefix)+len(key)]) - } - - return result -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/flatmap/flatten.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/flatmap/flatten.go deleted file mode 100644 index 9ff6e426526..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/flatmap/flatten.go +++ /dev/null @@ -1,71 +0,0 @@ -package flatmap - -import ( - "fmt" - "reflect" -) - -// Flatten takes a structure and turns into a flat map[string]string. -// -// Within the "thing" parameter, only primitive values are allowed. Structs are -// not supported. Therefore, it can only be slices, maps, primitives, and -// any combination of those together. -// -// See the tests for examples of what inputs are turned into. -func Flatten(thing map[string]interface{}) Map { - result := make(map[string]string) - - for k, raw := range thing { - flatten(result, k, reflect.ValueOf(raw)) - } - - return Map(result) -} - -func flatten(result map[string]string, prefix string, v reflect.Value) { - if v.Kind() == reflect.Interface { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Bool: - if v.Bool() { - result[prefix] = "true" - } else { - result[prefix] = "false" - } - case reflect.Int: - result[prefix] = fmt.Sprintf("%d", v.Int()) - case reflect.Map: - flattenMap(result, prefix, v) - case reflect.Slice: - flattenSlice(result, prefix, v) - case reflect.String: - result[prefix] = v.String() - default: - panic(fmt.Sprintf("Unknown: %s", v)) - } -} - -func flattenMap(result map[string]string, prefix string, v reflect.Value) { - for _, k := range v.MapKeys() { - if k.Kind() == reflect.Interface { - k = k.Elem() - } - - if k.Kind() != reflect.String { - panic(fmt.Sprintf("%s: map key is not string: %s", prefix, k)) - } - - flatten(result, fmt.Sprintf("%s.%s", prefix, k.String()), v.MapIndex(k)) - } -} - -func flattenSlice(result map[string]string, prefix string, v reflect.Value) { - prefix = prefix + "." - - result[prefix+"#"] = fmt.Sprintf("%d", v.Len()) - for i := 0; i < v.Len(); i++ { - flatten(result, fmt.Sprintf("%s%d", prefix, i), v.Index(i)) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/flatmap/map.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/flatmap/map.go deleted file mode 100644 index 435e04a39db..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/flatmap/map.go +++ /dev/null @@ -1,82 +0,0 @@ -package flatmap - -import ( - "strings" -) - -// Map is a wrapper around map[string]string that provides some helpers -// above it that assume the map is in the format that flatmap expects -// (the result of Flatten). -// -// All modifying functions such as Delete are done in-place unless -// otherwise noted. -type Map map[string]string - -// Contains returns true if the map contains the given key. -func (m Map) Contains(key string) bool { - for _, k := range m.Keys() { - if k == key { - return true - } - } - - return false -} - -// Delete deletes a key out of the map with the given prefix. -func (m Map) Delete(prefix string) { - for k := range m { - match := k == prefix - if !match { - if !strings.HasPrefix(k, prefix) { - continue - } - - if k[len(prefix):len(prefix)+1] != "." { - continue - } - } - - delete(m, k) - } -} - -// Keys returns all of the top-level keys in this map -func (m Map) Keys() []string { - ks := make(map[string]struct{}) - for k := range m { - idx := strings.Index(k, ".") - if idx == -1 { - idx = len(k) - } - - ks[k[:idx]] = struct{}{} - } - - result := make([]string, 0, len(ks)) - for k := range ks { - result = append(result, k) - } - - return result -} - -// Merge merges the contents of the other Map into this one. -// -// This merge is smarter than a simple map iteration because it -// will fully replace arrays and other complex structures that -// are present in this map with the other map's. For example, if -// this map has a 3 element "foo" list, and m2 has a 2 element "foo" -// list, then the result will be that m has a 2 element "foo" -// list. -func (m Map) Merge(m2 Map) { - for _, prefix := range m2.Keys() { - m.Delete(prefix) - - for k, v := range m2 { - if strings.HasPrefix(k, prefix) { - m[k] = v - } - } - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/config/validator.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/config/validator.go deleted file mode 100644 index be5db8b982d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/config/validator.go +++ /dev/null @@ -1,214 +0,0 @@ -package config - -import ( - "fmt" - "strconv" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/internal/flatmap" - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -// Validator is a helper that helps you validate the configuration -// of your resource, resource provider, etc. -// -// At the most basic level, set the Required and Optional lists to be -// specifiers of keys that are required or optional. If a key shows up -// that isn't in one of these two lists, then an error is generated. -// -// The "specifiers" allowed in this is a fairly rich syntax to help -// describe the format of your configuration: -// -// * Basic keys are just strings. For example: "foo" will match the -// "foo" key. -// -// * Nested structure keys can be matched by doing -// "listener.*.foo". This will verify that there is at least one -// listener element that has the "foo" key set. -// -// * The existence of a nested structure can be checked by simply -// doing "listener.*" which will verify that there is at least -// one element in the "listener" structure. This is NOT -// validating that "listener" is an array. It is validating -// that it is a nested structure in the configuration. -// -type Validator struct { - Required []string - Optional []string -} - -func (v *Validator) Validate( - c *terraform.ResourceConfig) (ws []string, es []error) { - // Flatten the configuration so it is easier to reason about - flat := flatmap.Flatten(c.Raw) - - keySet := make(map[string]validatorKey) - for i, vs := range [][]string{v.Required, v.Optional} { - req := i == 0 - for _, k := range vs { - vk, err := newValidatorKey(k, req) - if err != nil { - es = append(es, err) - continue - } - - keySet[k] = vk - } - } - - purged := make([]string, 0) - for _, kv := range keySet { - p, w, e := kv.Validate(flat) - if len(w) > 0 { - ws = append(ws, w...) - } - if len(e) > 0 { - es = append(es, e...) - } - - purged = append(purged, p...) - } - - // Delete all the keys we processed in order to find - // the unknown keys. - for _, p := range purged { - delete(flat, p) - } - - // The rest are unknown - for k := range flat { - es = append(es, fmt.Errorf("Unknown configuration: %s", k)) - } - - return -} - -type validatorKey interface { - // Validate validates the given configuration and returns viewed keys, - // warnings, and errors. - Validate(map[string]string) ([]string, []string, []error) -} - -func newValidatorKey(k string, req bool) (validatorKey, error) { - var result validatorKey - - parts := strings.Split(k, ".") - if len(parts) > 1 && parts[1] == "*" { - result = &nestedValidatorKey{ - Parts: parts, - Required: req, - } - } else { - result = &basicValidatorKey{ - Key: k, - Required: req, - } - } - - return result, nil -} - -// basicValidatorKey validates keys that are basic such as "foo" -type basicValidatorKey struct { - Key string - Required bool -} - -func (v *basicValidatorKey) Validate( - m map[string]string) ([]string, []string, []error) { - for k := range m { - // If we have the exact key its a match - if k == v.Key { - return []string{k}, nil, nil - } - } - - if !v.Required { - return nil, nil, nil - } - - return nil, nil, []error{fmt.Errorf( - "Key not found: %s", v.Key)} -} - -type nestedValidatorKey struct { - Parts []string - Required bool -} - -func (v *nestedValidatorKey) validate( - m map[string]string, - prefix string, - offset int) ([]string, []string, []error) { - if offset >= len(v.Parts) { - // We're at the end. Look for a specific key. - v2 := &basicValidatorKey{Key: prefix, Required: v.Required} - return v2.Validate(m) - } - - current := v.Parts[offset] - - // If we're at offset 0, special case to start at the next one. - if offset == 0 { - return v.validate(m, current, offset+1) - } - - // Determine if we're doing a "for all" or a specific key - if current != "*" { - // We're looking at a specific key, continue on. - return v.validate(m, prefix+"."+current, offset+1) - } - - // We're doing a "for all", so we loop over. - countStr, ok := m[prefix+".#"] - if !ok { - if !v.Required { - // It wasn't required, so its no problem. - return nil, nil, nil - } - - return nil, nil, []error{fmt.Errorf( - "Key not found: %s", prefix)} - } - - count, err := strconv.ParseInt(countStr, 0, 0) - if err != nil { - // This shouldn't happen if flatmap works properly - panic("invalid flatmap array") - } - - var e []error - var w []string - u := make([]string, 1, count+1) - u[0] = prefix + ".#" - for i := 0; i < int(count); i++ { - prefix := fmt.Sprintf("%s.%d", prefix, i) - - // Mark that we saw this specific key - u = append(u, prefix) - - // Mark all prefixes of this - for k := range m { - if !strings.HasPrefix(k, prefix+".") { - continue - } - u = append(u, k) - } - - // If we have more parts, then validate deeper - if offset+1 < len(v.Parts) { - u2, w2, e2 := v.validate(m, prefix, offset+1) - - u = append(u, u2...) - w = append(w, w2...) - e = append(e, e2...) - } - } - - return u, w, e -} - -func (v *nestedValidatorKey) Validate( - m map[string]string) ([]string, []string, []error) { - return v.validate(m, "", 0) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/didyoumean/name_suggestion.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/didyoumean/name_suggestion.go deleted file mode 100644 index 54899bc6522..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/didyoumean/name_suggestion.go +++ /dev/null @@ -1,24 +0,0 @@ -package didyoumean - -import ( - "github.com/agext/levenshtein" -) - -// NameSuggestion tries to find a name from the given slice of suggested names -// that is close to the given name and returns it if found. If no suggestion -// is close enough, returns the empty string. -// -// The suggestions are tried in order, so earlier suggestions take precedence -// if the given string is similar to two or more suggestions. -// -// This function is intended to be used with a relatively-small number of -// suggestions. It's not optimized for hundreds or thousands of them. -func NameSuggestion(given string, suggestions []string) string { - for _, suggestion := range suggestions { - dist := levenshtein.Distance(given, suggestion, nil) - if dist < 3 { // threshold determined experimentally - return suggestion - } - } - return "" -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/plugin/grpc_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/plugin/grpc_provider.go deleted file mode 100644 index 388f1ed59d9..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/plugin/grpc_provider.go +++ /dev/null @@ -1,1398 +0,0 @@ -package plugin - -import ( - "encoding/json" - "fmt" - "log" - "strconv" - - "github.com/zclconf/go-cty/cty" - ctyconvert "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/msgpack" - context "golang.org/x/net/context" - - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange" - "github.com/hashicorp/terraform-plugin-sdk/internal/plugin/convert" - proto "github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5" - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -const newExtraKey = "_new_extra_shim" - -// NewGRPCProviderServerShim wraps a terraform.ResourceProvider in a -// proto.ProviderServer implementation. If the provided provider is not a -// *schema.Provider, this will return nil, -func NewGRPCProviderServerShim(p terraform.ResourceProvider) *GRPCProviderServer { - sp, ok := p.(*schema.Provider) - if !ok { - return nil - } - - return &GRPCProviderServer{ - provider: sp, - } -} - -// GRPCProviderServer handles the server, or plugin side of the rpc connection. -type GRPCProviderServer struct { - provider *schema.Provider -} - -func (s *GRPCProviderServer) GetSchema(_ context.Context, req *proto.GetProviderSchema_Request) (*proto.GetProviderSchema_Response, error) { - // Here we are certain that the provider is being called through grpc, so - // make sure the feature flag for helper/schema is set - schema.SetProto5() - - resp := &proto.GetProviderSchema_Response{ - ResourceSchemas: make(map[string]*proto.Schema), - DataSourceSchemas: make(map[string]*proto.Schema), - } - - resp.Provider = &proto.Schema{ - Block: convert.ConfigSchemaToProto(s.getProviderSchemaBlock()), - } - - for typ, res := range s.provider.ResourcesMap { - resp.ResourceSchemas[typ] = &proto.Schema{ - Version: int64(res.SchemaVersion), - Block: convert.ConfigSchemaToProto(res.CoreConfigSchema()), - } - } - - for typ, dat := range s.provider.DataSourcesMap { - resp.DataSourceSchemas[typ] = &proto.Schema{ - Version: int64(dat.SchemaVersion), - Block: convert.ConfigSchemaToProto(dat.CoreConfigSchema()), - } - } - - return resp, nil -} - -func (s *GRPCProviderServer) getProviderSchemaBlock() *configschema.Block { - return schema.InternalMap(s.provider.Schema).CoreConfigSchema() -} - -func (s *GRPCProviderServer) getResourceSchemaBlock(name string) *configschema.Block { - res := s.provider.ResourcesMap[name] - return res.CoreConfigSchema() -} - -func (s *GRPCProviderServer) getDatasourceSchemaBlock(name string) *configschema.Block { - dat := s.provider.DataSourcesMap[name] - return dat.CoreConfigSchema() -} - -func (s *GRPCProviderServer) PrepareProviderConfig(_ context.Context, req *proto.PrepareProviderConfig_Request) (*proto.PrepareProviderConfig_Response, error) { - resp := &proto.PrepareProviderConfig_Response{} - - schemaBlock := s.getProviderSchemaBlock() - - configVal, err := msgpack.Unmarshal(req.Config.Msgpack, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // lookup any required, top-level attributes that are Null, and see if we - // have a Default value available. - configVal, err = cty.Transform(configVal, func(path cty.Path, val cty.Value) (cty.Value, error) { - // we're only looking for top-level attributes - if len(path) != 1 { - return val, nil - } - - // nothing to do if we already have a value - if !val.IsNull() { - return val, nil - } - - // get the Schema definition for this attribute - getAttr, ok := path[0].(cty.GetAttrStep) - // these should all exist, but just ignore anything strange - if !ok { - return val, nil - } - - attrSchema := s.provider.Schema[getAttr.Name] - // continue to ignore anything that doesn't match - if attrSchema == nil { - return val, nil - } - - // this is deprecated, so don't set it - if attrSchema.Deprecated != "" || attrSchema.Removed != "" { - return val, nil - } - - // find a default value if it exists - def, err := attrSchema.DefaultValue() - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("error getting default for %q: %s", getAttr.Name, err)) - return val, err - } - - // no default - if def == nil { - return val, nil - } - - // create a cty.Value and make sure it's the correct type - tmpVal := hcl2shim.HCL2ValueFromConfigValue(def) - - // helper/schema used to allow setting "" to a bool - if val.Type() == cty.Bool && tmpVal.RawEquals(cty.StringVal("")) { - // return a warning about the conversion - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, "provider set empty string as default value for bool "+getAttr.Name) - tmpVal = cty.False - } - - val, err = ctyconvert.Convert(tmpVal, val.Type()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("error setting default for %q: %s", getAttr.Name, err)) - } - - return val, err - }) - if err != nil { - // any error here was already added to the diagnostics - return resp, nil - } - - configVal, err = schemaBlock.CoerceValue(configVal) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // Ensure there are no nulls that will cause helper/schema to panic. - if err := validateConfigNulls(configVal, nil); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) - - warns, errs := s.provider.Validate(config) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, convert.WarnsAndErrsToProto(warns, errs)) - - preparedConfigMP, err := msgpack.Marshal(configVal, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - resp.PreparedConfig = &proto.DynamicValue{Msgpack: preparedConfigMP} - - return resp, nil -} - -func (s *GRPCProviderServer) ValidateResourceTypeConfig(_ context.Context, req *proto.ValidateResourceTypeConfig_Request) (*proto.ValidateResourceTypeConfig_Response, error) { - resp := &proto.ValidateResourceTypeConfig_Response{} - - schemaBlock := s.getResourceSchemaBlock(req.TypeName) - - configVal, err := msgpack.Unmarshal(req.Config.Msgpack, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) - - warns, errs := s.provider.ValidateResource(req.TypeName, config) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, convert.WarnsAndErrsToProto(warns, errs)) - - return resp, nil -} - -func (s *GRPCProviderServer) ValidateDataSourceConfig(_ context.Context, req *proto.ValidateDataSourceConfig_Request) (*proto.ValidateDataSourceConfig_Response, error) { - resp := &proto.ValidateDataSourceConfig_Response{} - - schemaBlock := s.getDatasourceSchemaBlock(req.TypeName) - - configVal, err := msgpack.Unmarshal(req.Config.Msgpack, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // Ensure there are no nulls that will cause helper/schema to panic. - if err := validateConfigNulls(configVal, nil); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) - - warns, errs := s.provider.ValidateDataSource(req.TypeName, config) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, convert.WarnsAndErrsToProto(warns, errs)) - - return resp, nil -} - -func (s *GRPCProviderServer) UpgradeResourceState(_ context.Context, req *proto.UpgradeResourceState_Request) (*proto.UpgradeResourceState_Response, error) { - resp := &proto.UpgradeResourceState_Response{} - - res := s.provider.ResourcesMap[req.TypeName] - schemaBlock := s.getResourceSchemaBlock(req.TypeName) - - version := int(req.Version) - - jsonMap := map[string]interface{}{} - var err error - - switch { - // We first need to upgrade a flatmap state if it exists. - // There should never be both a JSON and Flatmap state in the request. - case len(req.RawState.Flatmap) > 0: - jsonMap, version, err = s.upgradeFlatmapState(version, req.RawState.Flatmap, res) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - // if there's a JSON state, we need to decode it. - case len(req.RawState.Json) > 0: - err = json.Unmarshal(req.RawState.Json, &jsonMap) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - default: - log.Println("[DEBUG] no state provided to upgrade") - return resp, nil - } - - // complete the upgrade of the JSON states - jsonMap, err = s.upgradeJSONState(version, jsonMap, res) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // The provider isn't required to clean out removed fields - s.removeAttributes(jsonMap, schemaBlock.ImpliedType()) - - // now we need to turn the state into the default json representation, so - // that it can be re-decoded using the actual schema. - val, err := schema.JSONMapToStateValue(jsonMap, schemaBlock) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // Now we need to make sure blocks are represented correctly, which means - // that missing blocks are empty collections, rather than null. - // First we need to CoerceValue to ensure that all object types match. - val, err = schemaBlock.CoerceValue(val) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - // Normalize the value and fill in any missing blocks. - val = objchange.NormalizeObjectFromLegacySDK(val, schemaBlock) - - // encode the final state to the expected msgpack format - newStateMP, err := msgpack.Marshal(val, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - resp.UpgradedState = &proto.DynamicValue{Msgpack: newStateMP} - return resp, nil -} - -// upgradeFlatmapState takes a legacy flatmap state, upgrades it using Migrate -// state if necessary, and converts it to the new JSON state format decoded as a -// map[string]interface{}. -// upgradeFlatmapState returns the json map along with the corresponding schema -// version. -func (s *GRPCProviderServer) upgradeFlatmapState(version int, m map[string]string, res *schema.Resource) (map[string]interface{}, int, error) { - // this will be the version we've upgraded so, defaulting to the given - // version in case no migration was called. - upgradedVersion := version - - // first determine if we need to call the legacy MigrateState func - requiresMigrate := version < res.SchemaVersion - - schemaType := res.CoreConfigSchema().ImpliedType() - - // if there are any StateUpgraders, then we need to only compare - // against the first version there - if len(res.StateUpgraders) > 0 { - requiresMigrate = version < res.StateUpgraders[0].Version - } - - if requiresMigrate && res.MigrateState == nil { - // Providers were previously allowed to bump the version - // without declaring MigrateState. - // If there are further upgraders, then we've only updated that far. - if len(res.StateUpgraders) > 0 { - schemaType = res.StateUpgraders[0].Type - upgradedVersion = res.StateUpgraders[0].Version - } - } else if requiresMigrate { - is := &terraform.InstanceState{ - ID: m["id"], - Attributes: m, - Meta: map[string]interface{}{ - "schema_version": strconv.Itoa(version), - }, - } - - is, err := res.MigrateState(version, is, s.provider.Meta()) - if err != nil { - return nil, 0, err - } - - // re-assign the map in case there was a copy made, making sure to keep - // the ID - m := is.Attributes - m["id"] = is.ID - - // if there are further upgraders, then we've only updated that far - if len(res.StateUpgraders) > 0 { - schemaType = res.StateUpgraders[0].Type - upgradedVersion = res.StateUpgraders[0].Version - } - } else { - // the schema version may be newer than the MigrateState functions - // handled and older than the current, but still stored in the flatmap - // form. If that's the case, we need to find the correct schema type to - // convert the state. - for _, upgrader := range res.StateUpgraders { - if upgrader.Version == version { - schemaType = upgrader.Type - break - } - } - } - - // now we know the state is up to the latest version that handled the - // flatmap format state. Now we can upgrade the format and continue from - // there. - newConfigVal, err := hcl2shim.HCL2ValueFromFlatmap(m, schemaType) - if err != nil { - return nil, 0, err - } - - jsonMap, err := schema.StateValueToJSONMap(newConfigVal, schemaType) - return jsonMap, upgradedVersion, err -} - -func (s *GRPCProviderServer) upgradeJSONState(version int, m map[string]interface{}, res *schema.Resource) (map[string]interface{}, error) { - var err error - - for _, upgrader := range res.StateUpgraders { - if version != upgrader.Version { - continue - } - - m, err = upgrader.Upgrade(m, s.provider.Meta()) - if err != nil { - return nil, err - } - version++ - } - - return m, nil -} - -// Remove any attributes no longer present in the schema, so that the json can -// be correctly decoded. -func (s *GRPCProviderServer) removeAttributes(v interface{}, ty cty.Type) { - // we're only concerned with finding maps that corespond to object - // attributes - switch v := v.(type) { - case []interface{}: - // If these aren't blocks the next call will be a noop - if ty.IsListType() || ty.IsSetType() { - eTy := ty.ElementType() - for _, eV := range v { - s.removeAttributes(eV, eTy) - } - } - return - case map[string]interface{}: - // map blocks aren't yet supported, but handle this just in case - if ty.IsMapType() { - eTy := ty.ElementType() - for _, eV := range v { - s.removeAttributes(eV, eTy) - } - return - } - - if ty == cty.DynamicPseudoType { - log.Printf("[DEBUG] ignoring dynamic block: %#v\n", v) - return - } - - if !ty.IsObjectType() { - // This shouldn't happen, and will fail to decode further on, so - // there's no need to handle it here. - log.Printf("[WARN] unexpected type %#v for map in json state", ty) - return - } - - attrTypes := ty.AttributeTypes() - for attr, attrV := range v { - attrTy, ok := attrTypes[attr] - if !ok { - log.Printf("[DEBUG] attribute %q no longer present in schema", attr) - delete(v, attr) - continue - } - - s.removeAttributes(attrV, attrTy) - } - } -} - -func (s *GRPCProviderServer) Stop(_ context.Context, _ *proto.Stop_Request) (*proto.Stop_Response, error) { - resp := &proto.Stop_Response{} - - err := s.provider.Stop() - if err != nil { - resp.Error = err.Error() - } - - return resp, nil -} - -func (s *GRPCProviderServer) Configure(_ context.Context, req *proto.Configure_Request) (*proto.Configure_Response, error) { - resp := &proto.Configure_Response{} - - schemaBlock := s.getProviderSchemaBlock() - - configVal, err := msgpack.Unmarshal(req.Config.Msgpack, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - s.provider.TerraformVersion = req.TerraformVersion - - // Ensure there are no nulls that will cause helper/schema to panic. - if err := validateConfigNulls(configVal, nil); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) - err = s.provider.Configure(config) - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - - return resp, nil -} - -func (s *GRPCProviderServer) ReadResource(_ context.Context, req *proto.ReadResource_Request) (*proto.ReadResource_Response, error) { - resp := &proto.ReadResource_Response{ - // helper/schema did previously handle private data during refresh, but - // core is now going to expect this to be maintained in order to - // persist it in the state. - Private: req.Private, - } - - res := s.provider.ResourcesMap[req.TypeName] - schemaBlock := s.getResourceSchemaBlock(req.TypeName) - - stateVal, err := msgpack.Unmarshal(req.CurrentState.Msgpack, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - instanceState, err := res.ShimInstanceStateFromValue(stateVal) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - private := make(map[string]interface{}) - if len(req.Private) > 0 { - if err := json.Unmarshal(req.Private, &private); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - } - instanceState.Meta = private - - newInstanceState, err := res.RefreshWithoutUpgrade(instanceState, s.provider.Meta()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - if newInstanceState == nil || newInstanceState.ID == "" { - // The old provider API used an empty id to signal that the remote - // object appears to have been deleted, but our new protocol expects - // to see a null value (in the cty sense) in that case. - newStateMP, err := msgpack.Marshal(cty.NullVal(schemaBlock.ImpliedType()), schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - } - resp.NewState = &proto.DynamicValue{ - Msgpack: newStateMP, - } - return resp, nil - } - - // helper/schema should always copy the ID over, but do it again just to be safe - newInstanceState.Attributes["id"] = newInstanceState.ID - - newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(newInstanceState.Attributes, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - newStateVal = normalizeNullValues(newStateVal, stateVal, false) - newStateVal = copyTimeoutValues(newStateVal, stateVal) - - newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - resp.NewState = &proto.DynamicValue{ - Msgpack: newStateMP, - } - - return resp, nil -} - -func (s *GRPCProviderServer) PlanResourceChange(_ context.Context, req *proto.PlanResourceChange_Request) (*proto.PlanResourceChange_Response, error) { - resp := &proto.PlanResourceChange_Response{} - - // This is a signal to Terraform Core that we're doing the best we can to - // shim the legacy type system of the SDK onto the Terraform type system - // but we need it to cut us some slack. This setting should not be taken - // forward to any new SDK implementations, since setting it prevents us - // from catching certain classes of provider bug that can lead to - // confusing downstream errors. - resp.LegacyTypeSystem = true - - res := s.provider.ResourcesMap[req.TypeName] - schemaBlock := s.getResourceSchemaBlock(req.TypeName) - - priorStateVal, err := msgpack.Unmarshal(req.PriorState.Msgpack, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - create := priorStateVal.IsNull() - - proposedNewStateVal, err := msgpack.Unmarshal(req.ProposedNewState.Msgpack, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // We don't usually plan destroys, but this can return early in any case. - if proposedNewStateVal.IsNull() { - resp.PlannedState = req.ProposedNewState - resp.PlannedPrivate = req.PriorPrivate - return resp, nil - } - - info := &terraform.InstanceInfo{ - Type: req.TypeName, - } - - priorState, err := res.ShimInstanceStateFromValue(priorStateVal) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - priorPrivate := make(map[string]interface{}) - if len(req.PriorPrivate) > 0 { - if err := json.Unmarshal(req.PriorPrivate, &priorPrivate); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - } - - priorState.Meta = priorPrivate - - // Ensure there are no nulls that will cause helper/schema to panic. - if err := validateConfigNulls(proposedNewStateVal, nil); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // turn the proposed state into a legacy configuration - cfg := terraform.NewResourceConfigShimmed(proposedNewStateVal, schemaBlock) - - diff, err := s.provider.SimpleDiff(info, priorState, cfg) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // if this is a new instance, we need to make sure ID is going to be computed - if create { - if diff == nil { - diff = terraform.NewInstanceDiff() - } - - diff.Attributes["id"] = &terraform.ResourceAttrDiff{ - NewComputed: true, - } - } - - if diff == nil || len(diff.Attributes) == 0 { - // schema.Provider.Diff returns nil if it ends up making a diff with no - // changes, but our new interface wants us to return an actual change - // description that _shows_ there are no changes. This is always the - // prior state, because we force a diff above if this is a new instance. - resp.PlannedState = req.PriorState - resp.PlannedPrivate = req.PriorPrivate - return resp, nil - } - - if priorState == nil { - priorState = &terraform.InstanceState{} - } - - // now we need to apply the diff to the prior state, so get the planned state - plannedAttrs, err := diff.Apply(priorState.Attributes, schemaBlock) - - plannedStateVal, err := hcl2shim.HCL2ValueFromFlatmap(plannedAttrs, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - plannedStateVal, err = schemaBlock.CoerceValue(plannedStateVal) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - plannedStateVal = normalizeNullValues(plannedStateVal, proposedNewStateVal, false) - - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - plannedStateVal = copyTimeoutValues(plannedStateVal, proposedNewStateVal) - - // The old SDK code has some imprecisions that cause it to sometimes - // generate differences that the SDK itself does not consider significant - // but Terraform Core would. To avoid producing weird do-nothing diffs - // in that case, we'll check if the provider as produced something we - // think is "equivalent" to the prior state and just return the prior state - // itself if so, thus ensuring that Terraform Core will treat this as - // a no-op. See the docs for ValuesSDKEquivalent for some caveats on its - // accuracy. - forceNoChanges := false - if hcl2shim.ValuesSDKEquivalent(priorStateVal, plannedStateVal) { - plannedStateVal = priorStateVal - forceNoChanges = true - } - - // if this was creating the resource, we need to set any remaining computed - // fields - if create { - plannedStateVal = SetUnknowns(plannedStateVal, schemaBlock) - } - - plannedMP, err := msgpack.Marshal(plannedStateVal, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.PlannedState = &proto.DynamicValue{ - Msgpack: plannedMP, - } - - // encode any timeouts into the diff Meta - t := &schema.ResourceTimeout{} - if err := t.ConfigDecode(res, cfg); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - if err := t.DiffEncode(diff); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // Now we need to store any NewExtra values, which are where any actual - // StateFunc modified config fields are hidden. - privateMap := diff.Meta - if privateMap == nil { - privateMap = map[string]interface{}{} - } - - newExtra := map[string]interface{}{} - - for k, v := range diff.Attributes { - if v.NewExtra != nil { - newExtra[k] = v.NewExtra - } - } - privateMap[newExtraKey] = newExtra - - // the Meta field gets encoded into PlannedPrivate - plannedPrivate, err := json.Marshal(privateMap) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.PlannedPrivate = plannedPrivate - - // collect the attributes that require instance replacement, and convert - // them to cty.Paths. - var requiresNew []string - if !forceNoChanges { - for attr, d := range diff.Attributes { - if d.RequiresNew { - requiresNew = append(requiresNew, attr) - } - } - } - - // If anything requires a new resource already, or the "id" field indicates - // that we will be creating a new resource, then we need to add that to - // RequiresReplace so that core can tell if the instance is being replaced - // even if changes are being suppressed via "ignore_changes". - id := plannedStateVal.GetAttr("id") - if len(requiresNew) > 0 || id.IsNull() || !id.IsKnown() { - requiresNew = append(requiresNew, "id") - } - - requiresReplace, err := hcl2shim.RequiresReplace(requiresNew, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // convert these to the protocol structures - for _, p := range requiresReplace { - resp.RequiresReplace = append(resp.RequiresReplace, pathToAttributePath(p)) - } - - return resp, nil -} - -func (s *GRPCProviderServer) ApplyResourceChange(_ context.Context, req *proto.ApplyResourceChange_Request) (*proto.ApplyResourceChange_Response, error) { - resp := &proto.ApplyResourceChange_Response{ - // Start with the existing state as a fallback - NewState: req.PriorState, - } - - res := s.provider.ResourcesMap[req.TypeName] - schemaBlock := s.getResourceSchemaBlock(req.TypeName) - - priorStateVal, err := msgpack.Unmarshal(req.PriorState.Msgpack, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - plannedStateVal, err := msgpack.Unmarshal(req.PlannedState.Msgpack, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - info := &terraform.InstanceInfo{ - Type: req.TypeName, - } - - priorState, err := res.ShimInstanceStateFromValue(priorStateVal) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - private := make(map[string]interface{}) - if len(req.PlannedPrivate) > 0 { - if err := json.Unmarshal(req.PlannedPrivate, &private); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - } - - var diff *terraform.InstanceDiff - destroy := false - - // a null state means we are destroying the instance - if plannedStateVal.IsNull() { - destroy = true - diff = &terraform.InstanceDiff{ - Attributes: make(map[string]*terraform.ResourceAttrDiff), - Meta: make(map[string]interface{}), - Destroy: true, - } - } else { - diff, err = schema.DiffFromValues(priorStateVal, plannedStateVal, stripResourceModifiers(res)) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - } - - if diff == nil { - diff = &terraform.InstanceDiff{ - Attributes: make(map[string]*terraform.ResourceAttrDiff), - Meta: make(map[string]interface{}), - } - } - - // add NewExtra Fields that may have been stored in the private data - if newExtra := private[newExtraKey]; newExtra != nil { - for k, v := range newExtra.(map[string]interface{}) { - d := diff.Attributes[k] - - if d == nil { - d = &terraform.ResourceAttrDiff{} - } - - d.NewExtra = v - diff.Attributes[k] = d - } - } - - if private != nil { - diff.Meta = private - } - - for k, d := range diff.Attributes { - // We need to turn off any RequiresNew. There could be attributes - // without changes in here inserted by helper/schema, but if they have - // RequiresNew then the state will be dropped from the ResourceData. - d.RequiresNew = false - - // Check that any "removed" attributes that don't actually exist in the - // prior state, or helper/schema will confuse itself - if d.NewRemoved { - if _, ok := priorState.Attributes[k]; !ok { - delete(diff.Attributes, k) - } - } - } - - newInstanceState, err := s.provider.Apply(info, priorState, diff) - // we record the error here, but continue processing any returned state. - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - } - newStateVal := cty.NullVal(schemaBlock.ImpliedType()) - - // Always return a null value for destroy. - // While this is usually indicated by a nil state, check for missing ID or - // attributes in the case of a provider failure. - if destroy || newInstanceState == nil || newInstanceState.Attributes == nil || newInstanceState.ID == "" { - newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.NewState = &proto.DynamicValue{ - Msgpack: newStateMP, - } - return resp, nil - } - - // We keep the null val if we destroyed the resource, otherwise build the - // entire object, even if the new state was nil. - newStateVal, err = schema.StateValueFromInstanceState(newInstanceState, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - newStateVal = normalizeNullValues(newStateVal, plannedStateVal, true) - - newStateVal = copyTimeoutValues(newStateVal, plannedStateVal) - - newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.NewState = &proto.DynamicValue{ - Msgpack: newStateMP, - } - - meta, err := json.Marshal(newInstanceState.Meta) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.Private = meta - - // This is a signal to Terraform Core that we're doing the best we can to - // shim the legacy type system of the SDK onto the Terraform type system - // but we need it to cut us some slack. This setting should not be taken - // forward to any new SDK implementations, since setting it prevents us - // from catching certain classes of provider bug that can lead to - // confusing downstream errors. - resp.LegacyTypeSystem = true - - return resp, nil -} - -func (s *GRPCProviderServer) ImportResourceState(_ context.Context, req *proto.ImportResourceState_Request) (*proto.ImportResourceState_Response, error) { - resp := &proto.ImportResourceState_Response{} - - info := &terraform.InstanceInfo{ - Type: req.TypeName, - } - - newInstanceStates, err := s.provider.ImportState(info, req.Id) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - for _, is := range newInstanceStates { - // copy the ID again just to be sure it wasn't missed - is.Attributes["id"] = is.ID - - resourceType := is.Ephemeral.Type - if resourceType == "" { - resourceType = req.TypeName - } - - schemaBlock := s.getResourceSchemaBlock(resourceType) - newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(is.Attributes, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // Normalize the value and fill in any missing blocks. - newStateVal = objchange.NormalizeObjectFromLegacySDK(newStateVal, schemaBlock) - - newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - meta, err := json.Marshal(is.Meta) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - importedResource := &proto.ImportResourceState_ImportedResource{ - TypeName: resourceType, - State: &proto.DynamicValue{ - Msgpack: newStateMP, - }, - Private: meta, - } - - resp.ImportedResources = append(resp.ImportedResources, importedResource) - } - - return resp, nil -} - -func (s *GRPCProviderServer) ReadDataSource(_ context.Context, req *proto.ReadDataSource_Request) (*proto.ReadDataSource_Response, error) { - resp := &proto.ReadDataSource_Response{} - - schemaBlock := s.getDatasourceSchemaBlock(req.TypeName) - - configVal, err := msgpack.Unmarshal(req.Config.Msgpack, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - info := &terraform.InstanceInfo{ - Type: req.TypeName, - } - - // Ensure there are no nulls that will cause helper/schema to panic. - if err := validateConfigNulls(configVal, nil); err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) - - // we need to still build the diff separately with the Read method to match - // the old behavior - diff, err := s.provider.ReadDataDiff(info, config) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - // now we can get the new complete data source - newInstanceState, err := s.provider.ReadDataApply(info, diff) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - newStateVal, err := schema.StateValueFromInstanceState(newInstanceState, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - - newStateVal = copyTimeoutValues(newStateVal, configVal) - - newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) - if err != nil { - resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) - return resp, nil - } - resp.State = &proto.DynamicValue{ - Msgpack: newStateMP, - } - return resp, nil -} - -func pathToAttributePath(path cty.Path) *proto.AttributePath { - var steps []*proto.AttributePath_Step - - for _, step := range path { - switch s := step.(type) { - case cty.GetAttrStep: - steps = append(steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_AttributeName{ - AttributeName: s.Name, - }, - }) - case cty.IndexStep: - ty := s.Key.Type() - switch ty { - case cty.Number: - i, _ := s.Key.AsBigFloat().Int64() - steps = append(steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_ElementKeyInt{ - ElementKeyInt: i, - }, - }) - case cty.String: - steps = append(steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_ElementKeyString{ - ElementKeyString: s.Key.AsString(), - }, - }) - } - } - } - - return &proto.AttributePath{Steps: steps} -} - -// helper/schema throws away timeout values from the config and stores them in -// the Private/Meta fields. we need to copy those values into the planned state -// so that core doesn't see a perpetual diff with the timeout block. -func copyTimeoutValues(to cty.Value, from cty.Value) cty.Value { - // if `to` is null we are planning to remove it altogether. - if to.IsNull() { - return to - } - toAttrs := to.AsValueMap() - // We need to remove the key since the hcl2shims will add a non-null block - // because we can't determine if a single block was null from the flatmapped - // values. This needs to conform to the correct schema for marshaling, so - // change the value to null rather than deleting it from the object map. - timeouts, ok := toAttrs[schema.TimeoutsConfigKey] - if ok { - toAttrs[schema.TimeoutsConfigKey] = cty.NullVal(timeouts.Type()) - } - - // if from is null then there are no timeouts to copy - if from.IsNull() { - return cty.ObjectVal(toAttrs) - } - - fromAttrs := from.AsValueMap() - timeouts, ok = fromAttrs[schema.TimeoutsConfigKey] - - // timeouts shouldn't be unknown, but don't copy possibly invalid values either - if !ok || timeouts.IsNull() || !timeouts.IsWhollyKnown() { - // no timeouts block to copy - return cty.ObjectVal(toAttrs) - } - - toAttrs[schema.TimeoutsConfigKey] = timeouts - - return cty.ObjectVal(toAttrs) -} - -// stripResourceModifiers takes a *schema.Resource and returns a deep copy with all -// StateFuncs and CustomizeDiffs removed. This will be used during apply to -// create a diff from a planned state where the diff modifications have already -// been applied. -func stripResourceModifiers(r *schema.Resource) *schema.Resource { - if r == nil { - return nil - } - // start with a shallow copy - newResource := new(schema.Resource) - *newResource = *r - - newResource.CustomizeDiff = nil - newResource.Schema = map[string]*schema.Schema{} - - for k, s := range r.Schema { - newResource.Schema[k] = stripSchema(s) - } - - return newResource -} - -func stripSchema(s *schema.Schema) *schema.Schema { - if s == nil { - return nil - } - // start with a shallow copy - newSchema := new(schema.Schema) - *newSchema = *s - - newSchema.StateFunc = nil - - switch e := newSchema.Elem.(type) { - case *schema.Schema: - newSchema.Elem = stripSchema(e) - case *schema.Resource: - newSchema.Elem = stripResourceModifiers(e) - } - - return newSchema -} - -// Zero values and empty containers may be interchanged by the apply process. -// When there is a discrepency between src and dst value being null or empty, -// prefer the src value. This takes a little more liberty with set types, since -// we can't correlate modified set values. In the case of sets, if the src set -// was wholly known we assume the value was correctly applied and copy that -// entirely to the new value. -// While apply prefers the src value, during plan we prefer dst whenever there -// is an unknown or a set is involved, since the plan can alter the value -// however it sees fit. This however means that a CustomizeDiffFunction may not -// be able to change a null to an empty value or vice versa, but that should be -// very uncommon nor was it reliable before 0.12 either. -func normalizeNullValues(dst, src cty.Value, apply bool) cty.Value { - ty := dst.Type() - if !src.IsNull() && !src.IsKnown() { - // Return src during plan to retain unknown interpolated placeholders, - // which could be lost if we're only updating a resource. If this is a - // read scenario, then there shouldn't be any unknowns at all. - if dst.IsNull() && !apply { - return src - } - return dst - } - - // Handle null/empty changes for collections during apply. - // A change between null and empty values prefers src to make sure the state - // is consistent between plan and apply. - if ty.IsCollectionType() && apply { - dstEmpty := !dst.IsNull() && dst.IsKnown() && dst.LengthInt() == 0 - srcEmpty := !src.IsNull() && src.IsKnown() && src.LengthInt() == 0 - - if (src.IsNull() && dstEmpty) || (srcEmpty && dst.IsNull()) { - return src - } - } - - // check the invariants that we need below, to ensure we are working with - // non-null and known values. - if src.IsNull() || !src.IsKnown() || !dst.IsKnown() { - return dst - } - - switch { - case ty.IsMapType(), ty.IsObjectType(): - var dstMap map[string]cty.Value - if !dst.IsNull() { - dstMap = dst.AsValueMap() - } - if dstMap == nil { - dstMap = map[string]cty.Value{} - } - - srcMap := src.AsValueMap() - for key, v := range srcMap { - dstVal, ok := dstMap[key] - if !ok && apply && ty.IsMapType() { - // don't transfer old map values to dst during apply - continue - } - - if dstVal == cty.NilVal { - if !apply && ty.IsMapType() { - // let plan shape this map however it wants - continue - } - dstVal = cty.NullVal(v.Type()) - } - - dstMap[key] = normalizeNullValues(dstVal, v, apply) - } - - // you can't call MapVal/ObjectVal with empty maps, but nothing was - // copied in anyway. If the dst is nil, and the src is known, assume the - // src is correct. - if len(dstMap) == 0 { - if dst.IsNull() && src.IsWhollyKnown() && apply { - return src - } - return dst - } - - if ty.IsMapType() { - // helper/schema will populate an optional+computed map with - // unknowns which we have to fixup here. - // It would be preferable to simply prevent any known value from - // becoming unknown, but concessions have to be made to retain the - // broken legacy behavior when possible. - for k, srcVal := range srcMap { - if !srcVal.IsNull() && srcVal.IsKnown() { - dstVal, ok := dstMap[k] - if !ok { - continue - } - - if !dstVal.IsNull() && !dstVal.IsKnown() { - dstMap[k] = srcVal - } - } - } - - return cty.MapVal(dstMap) - } - - return cty.ObjectVal(dstMap) - - case ty.IsSetType(): - // If the original was wholly known, then we expect that is what the - // provider applied. The apply process loses too much information to - // reliably re-create the set. - if src.IsWhollyKnown() && apply { - return src - } - - case ty.IsListType(), ty.IsTupleType(): - // If the dst is null, and the src is known, then we lost an empty value - // so take the original. - if dst.IsNull() { - if src.IsWhollyKnown() && src.LengthInt() == 0 && apply { - return src - } - - // if dst is null and src only contains unknown values, then we lost - // those during a read or plan. - if !apply && !src.IsNull() { - allUnknown := true - for _, v := range src.AsValueSlice() { - if v.IsKnown() { - allUnknown = false - break - } - } - if allUnknown { - return src - } - } - - return dst - } - - // if the lengths are identical, then iterate over each element in succession. - srcLen := src.LengthInt() - dstLen := dst.LengthInt() - if srcLen == dstLen && srcLen > 0 { - srcs := src.AsValueSlice() - dsts := dst.AsValueSlice() - - for i := 0; i < srcLen; i++ { - dsts[i] = normalizeNullValues(dsts[i], srcs[i], apply) - } - - if ty.IsTupleType() { - return cty.TupleVal(dsts) - } - return cty.ListVal(dsts) - } - - case ty == cty.String: - // The legacy SDK should not be able to remove a value during plan or - // apply, however we are only going to overwrite this if the source was - // an empty string, since that is what is often equated with unset and - // lost in the diff process. - if dst.IsNull() && src.AsString() == "" { - return src - } - } - - return dst -} - -// validateConfigNulls checks a config value for unsupported nulls before -// attempting to shim the value. While null values can mostly be ignored in the -// configuration, since they're not supported in HCL1, the case where a null -// appears in a list-like attribute (list, set, tuple) will present a nil value -// to helper/schema which can panic. Return an error to the user in this case, -// indicating the attribute with the null value. -func validateConfigNulls(v cty.Value, path cty.Path) []*proto.Diagnostic { - var diags []*proto.Diagnostic - if v.IsNull() || !v.IsKnown() { - return diags - } - - switch { - case v.Type().IsListType() || v.Type().IsSetType() || v.Type().IsTupleType(): - it := v.ElementIterator() - for it.Next() { - kv, ev := it.Element() - if ev.IsNull() { - // if this is a set, the kv is also going to be null which - // isn't a valid path element, so we can't append it to the - // diagnostic. - p := path - if !kv.IsNull() { - p = append(p, cty.IndexStep{Key: kv}) - } - - diags = append(diags, &proto.Diagnostic{ - Severity: proto.Diagnostic_ERROR, - Summary: "Null value found in list", - Detail: "Null values are not allowed for this attribute value.", - Attribute: convert.PathToAttributePath(p), - }) - continue - } - - d := validateConfigNulls(ev, append(path, cty.IndexStep{Key: kv})) - diags = convert.AppendProtoDiag(diags, d) - } - - case v.Type().IsMapType() || v.Type().IsObjectType(): - it := v.ElementIterator() - for it.Next() { - kv, ev := it.Element() - var step cty.PathStep - switch { - case v.Type().IsMapType(): - step = cty.IndexStep{Key: kv} - case v.Type().IsObjectType(): - step = cty.GetAttrStep{Name: kv.AsString()} - } - d := validateConfigNulls(ev, append(path, step)) - diags = convert.AppendProtoDiag(diags, d) - } - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/plugin/unknown.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/plugin/unknown.go deleted file mode 100644 index a22a264fa0a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/plugin/unknown.go +++ /dev/null @@ -1,131 +0,0 @@ -package plugin - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/zclconf/go-cty/cty" -) - -// SetUnknowns takes a cty.Value, and compares it to the schema setting any null -// values which are computed to unknown. -func SetUnknowns(val cty.Value, schema *configschema.Block) cty.Value { - if !val.IsKnown() { - return val - } - - // If the object was null, we still need to handle the top level attributes - // which might be computed, but we don't need to expand the blocks. - if val.IsNull() { - objMap := map[string]cty.Value{} - allNull := true - for name, attr := range schema.Attributes { - switch { - case attr.Computed: - objMap[name] = cty.UnknownVal(attr.Type) - allNull = false - default: - objMap[name] = cty.NullVal(attr.Type) - } - } - - // If this object has no unknown attributes, then we can leave it null. - if allNull { - return val - } - - return cty.ObjectVal(objMap) - } - - valMap := val.AsValueMap() - newVals := make(map[string]cty.Value) - - for name, attr := range schema.Attributes { - v := valMap[name] - - if attr.Computed && v.IsNull() { - newVals[name] = cty.UnknownVal(attr.Type) - continue - } - - newVals[name] = v - } - - for name, blockS := range schema.BlockTypes { - blockVal := valMap[name] - if blockVal.IsNull() || !blockVal.IsKnown() { - newVals[name] = blockVal - continue - } - - blockValType := blockVal.Type() - blockElementType := blockS.Block.ImpliedType() - - // This switches on the value type here, so we can correctly switch - // between Tuples/Lists and Maps/Objects. - switch { - case blockS.Nesting == configschema.NestingSingle || blockS.Nesting == configschema.NestingGroup: - // NestingSingle is the only exception here, where we treat the - // block directly as an object - newVals[name] = SetUnknowns(blockVal, &blockS.Block) - - case blockValType.IsSetType(), blockValType.IsListType(), blockValType.IsTupleType(): - listVals := blockVal.AsValueSlice() - newListVals := make([]cty.Value, 0, len(listVals)) - - for _, v := range listVals { - newListVals = append(newListVals, SetUnknowns(v, &blockS.Block)) - } - - switch { - case blockValType.IsSetType(): - switch len(newListVals) { - case 0: - newVals[name] = cty.SetValEmpty(blockElementType) - default: - newVals[name] = cty.SetVal(newListVals) - } - case blockValType.IsListType(): - switch len(newListVals) { - case 0: - newVals[name] = cty.ListValEmpty(blockElementType) - default: - newVals[name] = cty.ListVal(newListVals) - } - case blockValType.IsTupleType(): - newVals[name] = cty.TupleVal(newListVals) - } - - case blockValType.IsMapType(), blockValType.IsObjectType(): - mapVals := blockVal.AsValueMap() - newMapVals := make(map[string]cty.Value) - - for k, v := range mapVals { - newMapVals[k] = SetUnknowns(v, &blockS.Block) - } - - switch { - case blockValType.IsMapType(): - switch len(newMapVals) { - case 0: - newVals[name] = cty.MapValEmpty(blockElementType) - default: - newVals[name] = cty.MapVal(newMapVals) - } - case blockValType.IsObjectType(): - if len(newMapVals) == 0 { - // We need to populate empty values to make a valid object. - for attr, ty := range blockElementType.AttributeTypes() { - newMapVals[attr] = cty.NullVal(ty) - } - } - newVals[name] = cty.ObjectVal(newMapVals) - } - - default: - panic(fmt.Sprintf("failed to set unknown values for nested block %q:%#v", name, blockValType)) - } - } - - return cty.ObjectVal(newVals) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/httpclient/client.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/httpclient/client.go deleted file mode 100644 index ad8d626c66d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/httpclient/client.go +++ /dev/null @@ -1,53 +0,0 @@ -package httpclient - -import ( - "fmt" - "log" - "net/http" - "os" - "strings" - - cleanhttp "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/terraform-plugin-sdk/internal/version" -) - -const uaEnvVar = "TF_APPEND_USER_AGENT" -const userAgentFormat = "Terraform/%s" - -// New returns the DefaultPooledClient from the cleanhttp -// package that will also send a Terraform User-Agent string. -func New() *http.Client { - cli := cleanhttp.DefaultPooledClient() - cli.Transport = &userAgentRoundTripper{ - userAgent: UserAgentString(), - inner: cli.Transport, - } - return cli -} - -type userAgentRoundTripper struct { - inner http.RoundTripper - userAgent string -} - -func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - if _, ok := req.Header["User-Agent"]; !ok { - req.Header.Set("User-Agent", rt.userAgent) - } - log.Printf("[TRACE] HTTP client %s request to %s", req.Method, req.URL.String()) - return rt.inner.RoundTrip(req) -} - -func UserAgentString() string { - ua := fmt.Sprintf(userAgentFormat, version.Version) - - if add := os.Getenv(uaEnvVar); add != "" { - add = strings.TrimSpace(add) - if len(add) > 0 { - ua += " " + add - log.Printf("[DEBUG] Using modified User-Agent: %s", ua) - } - } - - return ua -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/copy_dir.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/copy_dir.go deleted file mode 100644 index 7096ff74f82..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/copy_dir.go +++ /dev/null @@ -1,125 +0,0 @@ -package initwd - -import ( - "io" - "os" - "path/filepath" - "strings" -) - -// copyDir copies the src directory contents into dst. Both directories -// should already exist. -func copyDir(dst, src string) error { - src, err := filepath.EvalSymlinks(src) - if err != nil { - return err - } - - walkFn := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - if path == src { - return nil - } - - if strings.HasPrefix(filepath.Base(path), ".") { - // Skip any dot files - if info.IsDir() { - return filepath.SkipDir - } else { - return nil - } - } - - // The "path" has the src prefixed to it. We need to join our - // destination with the path without the src on it. - dstPath := filepath.Join(dst, path[len(src):]) - - // we don't want to try and copy the same file over itself. - if eq, err := sameFile(path, dstPath); eq { - return nil - } else if err != nil { - return err - } - - // If we have a directory, make that subdirectory, then continue - // the walk. - if info.IsDir() { - if path == filepath.Join(src, dst) { - // dst is in src; don't walk it. - return nil - } - - if err := os.MkdirAll(dstPath, 0755); err != nil { - return err - } - - return nil - } - - // If the current path is a symlink, recreate the symlink relative to - // the dst directory - if info.Mode()&os.ModeSymlink == os.ModeSymlink { - target, err := os.Readlink(path) - if err != nil { - return err - } - - return os.Symlink(target, dstPath) - } - - // If we have a file, copy the contents. - srcF, err := os.Open(path) - if err != nil { - return err - } - defer srcF.Close() - - dstF, err := os.Create(dstPath) - if err != nil { - return err - } - defer dstF.Close() - - if _, err := io.Copy(dstF, srcF); err != nil { - return err - } - - // Chmod it - return os.Chmod(dstPath, info.Mode()) - } - - return filepath.Walk(src, walkFn) -} - -// sameFile tried to determine if to paths are the same file. -// If the paths don't match, we lookup the inode on supported systems. -func sameFile(a, b string) (bool, error) { - if a == b { - return true, nil - } - - aIno, err := inode(a) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - - bIno, err := inode(b) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - - if aIno > 0 && aIno == bIno { - return true, nil - } - - return false, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/doc.go deleted file mode 100644 index b9d938dbb09..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/doc.go +++ /dev/null @@ -1,7 +0,0 @@ -// Package initwd contains various helper functions used by the "terraform init" -// command to initialize a working directory. -// -// These functions may also be used from testing code to simulate the behaviors -// of "terraform init" against test fixtures, but should not be used elsewhere -// in the main code. -package initwd diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/from_module.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/from_module.go deleted file mode 100644 index 641e71dec8a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/from_module.go +++ /dev/null @@ -1,363 +0,0 @@ -package initwd - -import ( - "fmt" - "github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig" - "io/ioutil" - "log" - "os" - "path/filepath" - "sort" - "strings" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform-plugin-sdk/internal/modsdir" - "github.com/hashicorp/terraform-plugin-sdk/internal/registry" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -const initFromModuleRootCallName = "root" -const initFromModuleRootKeyPrefix = initFromModuleRootCallName + "." - -// DirFromModule populates the given directory (which must exist and be -// empty) with the contents of the module at the given source address. -// -// It does this by installing the given module and all of its descendent -// modules in a temporary root directory and then copying the installed -// files into suitable locations. As a consequence, any diagnostics it -// generates will reveal the location of this temporary directory to the -// user. -// -// This rather roundabout installation approach is taken to ensure that -// installation proceeds in a manner identical to normal module installation. -// -// If the given source address specifies a sub-directory of the given -// package then only the sub-directory and its descendents will be copied -// into the given root directory, which will cause any relative module -// references using ../ from that module to be unresolvable. Error diagnostics -// are produced in that case, to prompt the user to rewrite the source strings -// to be absolute references to the original remote module. -func DirFromModule(rootDir, modulesDir, sourceAddr string, reg *registry.Client, hooks ModuleInstallHooks) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - // The way this function works is pretty ugly, but we accept it because - // -from-module is a less important case than normal module installation - // and so it's better to keep this ugly complexity out here rather than - // adding even more complexity to the normal module installer. - - // The target directory must exist but be empty. - { - entries, err := ioutil.ReadDir(rootDir) - if err != nil { - if os.IsNotExist(err) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Target directory does not exist", - fmt.Sprintf("Cannot initialize non-existent directory %s.", rootDir), - )) - } else { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to read target directory", - fmt.Sprintf("Error reading %s to ensure it is empty: %s.", rootDir, err), - )) - } - return diags - } - haveEntries := false - for _, entry := range entries { - if entry.Name() == "." || entry.Name() == ".." || entry.Name() == ".terraform" { - continue - } - haveEntries = true - } - if haveEntries { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Can't populate non-empty directory", - fmt.Sprintf("The target directory %s is not empty, so it cannot be initialized with the -from-module=... option.", rootDir), - )) - return diags - } - } - - instDir := filepath.Join(rootDir, ".terraform/init-from-module") - inst := NewModuleInstaller(instDir, reg) - log.Printf("[DEBUG] installing modules in %s to initialize working directory from %q", instDir, sourceAddr) - os.RemoveAll(instDir) // if this fails then we'll fail on MkdirAll below too - err := os.MkdirAll(instDir, os.ModePerm) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to create temporary directory", - fmt.Sprintf("Failed to create temporary directory %s: %s.", instDir, err), - )) - return diags - } - - instManifest := make(modsdir.Manifest) - retManifest := make(modsdir.Manifest) - - fakeFilename := fmt.Sprintf("-from-module=%q", sourceAddr) - fakePos := tfconfig.SourcePos{ - Filename: fakeFilename, - Line: 1, - } - - // -from-module allows relative paths but it's different than a normal - // module address where it'd be resolved relative to the module call - // (which is synthetic, here.) To address this, we'll just patch up any - // relative paths to be absolute paths before we run, ensuring we'll - // get the right result. This also, as an important side-effect, ensures - // that the result will be "downloaded" with go-getter (copied from the - // source location), rather than just recorded as a relative path. - { - maybePath := filepath.ToSlash(sourceAddr) - if maybePath == "." || strings.HasPrefix(maybePath, "./") || strings.HasPrefix(maybePath, "../") { - if wd, err := os.Getwd(); err == nil { - sourceAddr = filepath.Join(wd, sourceAddr) - log.Printf("[TRACE] -from-module relative path rewritten to absolute path %s", sourceAddr) - } - } - } - - // Now we need to create an artificial root module that will seed our - // installation process. - fakeRootModule := &tfconfig.Module{ - ModuleCalls: map[string]*tfconfig.ModuleCall{ - initFromModuleRootCallName: { - Name: initFromModuleRootCallName, - Source: sourceAddr, - Pos: fakePos, - }, - }, - } - - // wrapHooks filters hook notifications to only include Download calls - // and to trim off the initFromModuleRootCallName prefix. We'll produce - // our own Install notifications directly below. - wrapHooks := installHooksInitDir{ - Wrapped: hooks, - } - getter := reusingGetter{} - _, instDiags := inst.installDescendentModules(fakeRootModule, rootDir, instManifest, true, wrapHooks, getter) - diags = append(diags, instDiags...) - if instDiags.HasErrors() { - return diags - } - - // If all of that succeeded then we'll now migrate what was installed - // into the final directory structure. - err = os.MkdirAll(modulesDir, os.ModePerm) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to create local modules directory", - fmt.Sprintf("Failed to create modules directory %s: %s.", modulesDir, err), - )) - return diags - } - - recordKeys := make([]string, 0, len(instManifest)) - for k := range instManifest { - recordKeys = append(recordKeys, k) - } - sort.Strings(recordKeys) - - for _, recordKey := range recordKeys { - record := instManifest[recordKey] - - if record.Key == initFromModuleRootCallName { - // We've found the module the user requested, which we must - // now copy into rootDir so it can be used directly. - log.Printf("[TRACE] copying new root module from %s to %s", record.Dir, rootDir) - err := copyDir(rootDir, record.Dir) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to copy root module", - fmt.Sprintf("Error copying root module %q from %s to %s: %s.", sourceAddr, record.Dir, rootDir, err), - )) - continue - } - - // We'll try to load the newly-copied module here just so we can - // sniff for any module calls that ../ out of the root directory - // and must thus be rewritten to be absolute addresses again. - // For now we can't do this rewriting automatically, but we'll - // generate an error to help the user do it manually. - mod, _ := earlyconfig.LoadModule(rootDir) // ignore diagnostics since we're just doing value-add here anyway - if mod != nil { - for _, mc := range mod.ModuleCalls { - if pathTraversesUp(mc.Source) { - packageAddr, givenSubdir := splitAddrSubdir(sourceAddr) - newSubdir := filepath.Join(givenSubdir, mc.Source) - if pathTraversesUp(newSubdir) { - // This should never happen in any reasonable - // configuration since this suggests a path that - // traverses up out of the package root. We'll just - // ignore this, since we'll fail soon enough anyway - // trying to resolve this path when this module is - // loaded. - continue - } - - var newAddr = packageAddr - if newSubdir != "" { - newAddr = fmt.Sprintf("%s//%s", newAddr, filepath.ToSlash(newSubdir)) - } - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Root module references parent directory", - fmt.Sprintf("The requested module %q refers to a module via its parent directory. To use this as a new root module this source string must be rewritten as a remote source address, such as %q.", sourceAddr, newAddr), - )) - continue - } - } - } - - retManifest[""] = modsdir.Record{ - Key: "", - Dir: rootDir, - } - continue - } - - if !strings.HasPrefix(record.Key, initFromModuleRootKeyPrefix) { - // Ignore the *real* root module, whose key is empty, since - // we're only interested in the module named "root" and its - // descendents. - continue - } - - newKey := record.Key[len(initFromModuleRootKeyPrefix):] - instPath := filepath.Join(modulesDir, newKey) - tempPath := filepath.Join(instDir, record.Key) - - // tempPath won't be present for a module that was installed from - // a relative path, so in that case we just record the installation - // directory and assume it was already copied into place as part - // of its parent. - if _, err := os.Stat(tempPath); err != nil { - if !os.IsNotExist(err) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to stat temporary module install directory", - fmt.Sprintf("Error from stat %s for module %s: %s.", instPath, newKey, err), - )) - continue - } - - var parentKey string - if lastDot := strings.LastIndexByte(newKey, '.'); lastDot != -1 { - parentKey = newKey[:lastDot] - } else { - parentKey = "" // parent is the root module - } - - parentOld := instManifest[initFromModuleRootKeyPrefix+parentKey] - parentNew := retManifest[parentKey] - - // We need to figure out which portion of our directory is the - // parent package path and which portion is the subdirectory - // under that. - baseDirRel, err := filepath.Rel(parentOld.Dir, record.Dir) - if err != nil { - // Should never happen, because we constructed both directories - // from the same base and so they must have a common prefix. - panic(err) - } - - newDir := filepath.Join(parentNew.Dir, baseDirRel) - log.Printf("[TRACE] relative reference for %s rewritten from %s to %s", newKey, record.Dir, newDir) - newRecord := record // shallow copy - newRecord.Dir = newDir - newRecord.Key = newKey - retManifest[newKey] = newRecord - hooks.Install(newRecord.Key, newRecord.Version, newRecord.Dir) - continue - } - - err = os.MkdirAll(instPath, os.ModePerm) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to create module install directory", - fmt.Sprintf("Error creating directory %s for module %s: %s.", instPath, newKey, err), - )) - continue - } - - // We copy rather than "rename" here because renaming between directories - // can be tricky in edge-cases like network filesystems, etc. - log.Printf("[TRACE] copying new module %s from %s to %s", newKey, record.Dir, instPath) - err := copyDir(instPath, tempPath) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to copy descendent module", - fmt.Sprintf("Error copying module %q from %s to %s: %s.", newKey, tempPath, rootDir, err), - )) - continue - } - - subDir, err := filepath.Rel(tempPath, record.Dir) - if err != nil { - // Should never happen, because we constructed both directories - // from the same base and so they must have a common prefix. - panic(err) - } - - newRecord := record // shallow copy - newRecord.Dir = filepath.Join(instPath, subDir) - newRecord.Key = newKey - retManifest[newKey] = newRecord - hooks.Install(newRecord.Key, newRecord.Version, newRecord.Dir) - } - - retManifest.WriteSnapshotToDir(modulesDir) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to write module manifest", - fmt.Sprintf("Error writing module manifest: %s.", err), - )) - } - - if !diags.HasErrors() { - // Try to clean up our temporary directory, but don't worry if we don't - // succeed since it shouldn't hurt anything. - os.RemoveAll(instDir) - } - - return diags -} - -func pathTraversesUp(path string) bool { - return strings.HasPrefix(filepath.ToSlash(path), "../") -} - -// installHooksInitDir is an adapter wrapper for an InstallHooks that -// does some fakery to make downloads look like they are happening in their -// final locations, rather than in the temporary loader we use. -// -// It also suppresses "Install" calls entirely, since InitDirFromModule -// does its own installation steps after the initial installation pass -// has completed. -type installHooksInitDir struct { - Wrapped ModuleInstallHooks - ModuleInstallHooksImpl -} - -func (h installHooksInitDir) Download(moduleAddr, packageAddr string, version *version.Version) { - if !strings.HasPrefix(moduleAddr, initFromModuleRootKeyPrefix) { - // We won't announce the root module, since hook implementations - // don't expect to see that and the caller will usually have produced - // its own user-facing notification about what it's doing anyway. - return - } - - trimAddr := moduleAddr[len(initFromModuleRootKeyPrefix):] - h.Wrapped.Download(trimAddr, packageAddr, version) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/getter.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/getter.go deleted file mode 100644 index 8dc0374b1e8..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/getter.go +++ /dev/null @@ -1,204 +0,0 @@ -package initwd - -import ( - "fmt" - "log" - "os" - "path/filepath" - "strings" - - cleanhttp "github.com/hashicorp/go-cleanhttp" - getter "github.com/hashicorp/go-getter" - "github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc" -) - -// We configure our own go-getter detector and getter sets here, because -// the set of sources we support is part of Terraform's documentation and -// so we don't want any new sources introduced in go-getter to sneak in here -// and work even though they aren't documented. This also insulates us from -// any meddling that might be done by other go-getter callers linked into our -// executable. - -var goGetterNoDetectors = []getter.Detector{} - -var goGetterDecompressors = map[string]getter.Decompressor{ - "bz2": new(getter.Bzip2Decompressor), - "gz": new(getter.GzipDecompressor), - "xz": new(getter.XzDecompressor), - "zip": new(getter.ZipDecompressor), - - "tar.bz2": new(getter.TarBzip2Decompressor), - "tar.tbz2": new(getter.TarBzip2Decompressor), - - "tar.gz": new(getter.TarGzipDecompressor), - "tgz": new(getter.TarGzipDecompressor), - - "tar.xz": new(getter.TarXzDecompressor), - "txz": new(getter.TarXzDecompressor), -} - -var goGetterGetters = map[string]getter.Getter{ - "file": new(getter.FileGetter), - "gcs": new(getter.GCSGetter), - "git": new(getter.GitGetter), - "hg": new(getter.HgGetter), - "s3": new(getter.S3Getter), - "http": getterHTTPGetter, - "https": getterHTTPGetter, -} - -var getterHTTPClient = cleanhttp.DefaultClient() - -var getterHTTPGetter = &getter.HttpGetter{ - Client: getterHTTPClient, - Netrc: true, -} - -// A reusingGetter is a helper for the module installer that remembers -// the final resolved addresses of all of the sources it has already been -// asked to install, and will copy from a prior installation directory if -// it has the same resolved source address. -// -// The keys in a reusingGetter are resolved and trimmed source addresses -// (with a scheme always present, and without any "subdir" component), -// and the values are the paths where each source was previously installed. -type reusingGetter map[string]string - -// getWithGoGetter retrieves the package referenced in the given address -// into the installation path and then returns the full path to any subdir -// indicated in the address. -// -// The errors returned by this function are those surfaced by the underlying -// go-getter library, which have very inconsistent quality as -// end-user-actionable error messages. At this time we do not have any -// reasonable way to improve these error messages at this layer because -// the underlying errors are not separately recognizable. -func (g reusingGetter) getWithGoGetter(instPath, addr string) (string, error) { - packageAddr, subDir := splitAddrSubdir(addr) - - log.Printf("[DEBUG] will download %q to %s", packageAddr, instPath) - - realAddr, err := getter.Detect(packageAddr, instPath, getter.Detectors) - if err != nil { - return "", err - } - - if isMaybeRelativeLocalPath(realAddr) { - return "", &MaybeRelativePathErr{addr} - } - - var realSubDir string - realAddr, realSubDir = splitAddrSubdir(realAddr) - if realSubDir != "" { - subDir = filepath.Join(realSubDir, subDir) - } - - if realAddr != packageAddr { - log.Printf("[TRACE] go-getter detectors rewrote %q to %q", packageAddr, realAddr) - } - - if prevDir, exists := g[realAddr]; exists { - log.Printf("[TRACE] copying previous install %s to %s", prevDir, instPath) - err := os.Mkdir(instPath, os.ModePerm) - if err != nil { - return "", fmt.Errorf("failed to create directory %s: %s", instPath, err) - } - err = copyDir(instPath, prevDir) - if err != nil { - return "", fmt.Errorf("failed to copy from %s to %s: %s", prevDir, instPath, err) - } - } else { - log.Printf("[TRACE] fetching %q to %q", realAddr, instPath) - client := getter.Client{ - Src: realAddr, - Dst: instPath, - Pwd: instPath, - - Mode: getter.ClientModeDir, - - Detectors: goGetterNoDetectors, // we already did detection above - Decompressors: goGetterDecompressors, - Getters: goGetterGetters, - } - err = client.Get() - if err != nil { - return "", err - } - // Remember where we installed this so we might reuse this directory - // on subsequent calls to avoid re-downloading. - g[realAddr] = instPath - } - - // Our subDir string can contain wildcards until this point, so that - // e.g. a subDir of * can expand to one top-level directory in a .tar.gz - // archive. Now that we've expanded the archive successfully we must - // resolve that into a concrete path. - var finalDir string - if subDir != "" { - finalDir, err = getter.SubdirGlob(instPath, subDir) - log.Printf("[TRACE] expanded %q to %q", subDir, finalDir) - if err != nil { - return "", err - } - } else { - finalDir = instPath - } - - // If we got this far then we have apparently succeeded in downloading - // the requested object! - return filepath.Clean(finalDir), nil -} - -// splitAddrSubdir splits the given address (which is assumed to be a -// registry address or go-getter-style address) into a package portion -// and a sub-directory portion. -// -// The package portion defines what should be downloaded and then the -// sub-directory portion, if present, specifies a sub-directory within -// the downloaded object (an archive, VCS repository, etc) that contains -// the module's configuration files. -// -// The subDir portion will be returned as empty if no subdir separator -// ("//") is present in the address. -func splitAddrSubdir(addr string) (packageAddr, subDir string) { - return getter.SourceDirSubdir(addr) -} - -var localSourcePrefixes = []string{ - "./", - "../", - ".\\", - "..\\", -} - -func isLocalSourceAddr(addr string) bool { - for _, prefix := range localSourcePrefixes { - if strings.HasPrefix(addr, prefix) { - return true - } - } - return false -} - -func isRegistrySourceAddr(addr string) bool { - _, err := regsrc.ParseModuleSource(addr) - return err == nil -} - -type MaybeRelativePathErr struct { - Addr string -} - -func (e *MaybeRelativePathErr) Error() string { - return fmt.Sprintf("Terraform cannot determine the module source for %s", e.Addr) -} - -func isMaybeRelativeLocalPath(addr string) bool { - if strings.HasPrefix(addr, "file://") { - _, err := os.Stat(addr[7:]) - if err != nil { - return true - } - } - return false -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/inode.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/inode.go deleted file mode 100644 index 1150b093ccb..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/inode.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build linux darwin openbsd netbsd solaris dragonfly - -package initwd - -import ( - "fmt" - "os" - "syscall" -) - -// lookup the inode of a file on posix systems -func inode(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - if st, ok := stat.Sys().(*syscall.Stat_t); ok { - return st.Ino, nil - } - return 0, fmt.Errorf("could not determine file inode") -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/inode_freebsd.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/inode_freebsd.go deleted file mode 100644 index 30532f54ace..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/inode_freebsd.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build freebsd - -package initwd - -import ( - "fmt" - "os" - "syscall" -) - -// lookup the inode of a file on posix systems -func inode(path string) (uint64, error) { - stat, err := os.Stat(path) - if err != nil { - return 0, err - } - if st, ok := stat.Sys().(*syscall.Stat_t); ok { - return uint64(st.Ino), nil - } - return 0, fmt.Errorf("could not determine file inode") -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/inode_windows.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/inode_windows.go deleted file mode 100644 index 3ed58e4bf96..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/inode_windows.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build windows - -package initwd - -// no syscall.Stat_t on windows, return 0 for inodes -func inode(path string) (uint64, error) { - return 0, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/module_install.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/module_install.go deleted file mode 100644 index 8e055756734..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/module_install.go +++ /dev/null @@ -1,558 +0,0 @@ -package initwd - -import ( - "fmt" - "log" - "os" - "path/filepath" - "strings" - - version "github.com/hashicorp/go-version" - "github.com/hashicorp/terraform-config-inspect/tfconfig" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/earlyconfig" - "github.com/hashicorp/terraform-plugin-sdk/internal/modsdir" - "github.com/hashicorp/terraform-plugin-sdk/internal/registry" - "github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -type ModuleInstaller struct { - modsDir string - reg *registry.Client -} - -func NewModuleInstaller(modsDir string, reg *registry.Client) *ModuleInstaller { - return &ModuleInstaller{ - modsDir: modsDir, - reg: reg, - } -} - -// InstallModules analyses the root module in the given directory and installs -// all of its direct and transitive dependencies into the given modules -// directory, which must already exist. -// -// Since InstallModules makes possibly-time-consuming calls to remote services, -// a hook interface is supported to allow the caller to be notified when -// each module is installed and, for remote modules, when downloading begins. -// LoadConfig guarantees that two hook calls will not happen concurrently but -// it does not guarantee any particular ordering of hook calls. This mechanism -// is for UI feedback only and does not give the caller any control over the -// process. -// -// If modules are already installed in the target directory, they will be -// skipped unless their source address or version have changed or unless -// the upgrade flag is set. -// -// InstallModules never deletes any directory, except in the case where it -// needs to replace a directory that is already present with a newly-extracted -// package. -// -// If the returned diagnostics contains errors then the module installation -// may have wholly or partially completed. Modules must be loaded in order -// to find their dependencies, so this function does many of the same checks -// as LoadConfig as a side-effect. -// -// If successful (the returned diagnostics contains no errors) then the -// first return value is the early configuration tree that was constructed by -// the installation process. -func (i *ModuleInstaller) InstallModules(rootDir string, upgrade bool, hooks ModuleInstallHooks) (*earlyconfig.Config, tfdiags.Diagnostics) { - log.Printf("[TRACE] ModuleInstaller: installing child modules for %s into %s", rootDir, i.modsDir) - - rootMod, diags := earlyconfig.LoadModule(rootDir) - if rootMod == nil { - return nil, diags - } - - manifest, err := modsdir.ReadManifestSnapshotForDir(i.modsDir) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to read modules manifest file", - fmt.Sprintf("Error reading manifest for %s: %s.", i.modsDir, err), - )) - return nil, diags - } - - getter := reusingGetter{} - cfg, instDiags := i.installDescendentModules(rootMod, rootDir, manifest, upgrade, hooks, getter) - diags = append(diags, instDiags...) - - return cfg, diags -} - -func (i *ModuleInstaller) installDescendentModules(rootMod *tfconfig.Module, rootDir string, manifest modsdir.Manifest, upgrade bool, hooks ModuleInstallHooks, getter reusingGetter) (*earlyconfig.Config, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - if hooks == nil { - // Use our no-op implementation as a placeholder - hooks = ModuleInstallHooksImpl{} - } - - // Create a manifest record for the root module. This will be used if - // there are any relative-pathed modules in the root. - manifest[""] = modsdir.Record{ - Key: "", - Dir: rootDir, - } - - cfg, cDiags := earlyconfig.BuildConfig(rootMod, earlyconfig.ModuleWalkerFunc( - func(req *earlyconfig.ModuleRequest) (*tfconfig.Module, *version.Version, tfdiags.Diagnostics) { - - key := manifest.ModuleKey(req.Path) - instPath := i.packageInstallPath(req.Path) - - log.Printf("[DEBUG] Module installer: begin %s", key) - - // First we'll check if we need to upgrade/replace an existing - // installed module, and delete it out of the way if so. - replace := upgrade - if !replace { - record, recorded := manifest[key] - switch { - case !recorded: - log.Printf("[TRACE] ModuleInstaller: %s is not yet installed", key) - replace = true - case record.SourceAddr != req.SourceAddr: - log.Printf("[TRACE] ModuleInstaller: %s source address has changed from %q to %q", key, record.SourceAddr, req.SourceAddr) - replace = true - case record.Version != nil && !req.VersionConstraints.Check(record.Version): - log.Printf("[TRACE] ModuleInstaller: %s version %s no longer compatible with constraints %s", key, record.Version, req.VersionConstraints) - replace = true - } - } - - // If we _are_ planning to replace this module, then we'll remove - // it now so our installation code below won't conflict with any - // existing remnants. - if replace { - if _, recorded := manifest[key]; recorded { - log.Printf("[TRACE] ModuleInstaller: discarding previous record of %s prior to reinstall", key) - } - delete(manifest, key) - // Deleting a module invalidates all of its descendent modules too. - keyPrefix := key + "." - for subKey := range manifest { - if strings.HasPrefix(subKey, keyPrefix) { - if _, recorded := manifest[subKey]; recorded { - log.Printf("[TRACE] ModuleInstaller: also discarding downstream %s", subKey) - } - delete(manifest, subKey) - } - } - } - - record, recorded := manifest[key] - if !recorded { - // Clean up any stale cache directory that might be present. - // If this is a local (relative) source then the dir will - // not exist, but we'll ignore that. - log.Printf("[TRACE] ModuleInstaller: cleaning directory %s prior to install of %s", instPath, key) - err := os.RemoveAll(instPath) - if err != nil && !os.IsNotExist(err) { - log.Printf("[TRACE] ModuleInstaller: failed to remove %s: %s", key, err) - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to remove local module cache", - fmt.Sprintf( - "Terraform tried to remove %s in order to reinstall this module, but encountered an error: %s", - instPath, err, - ), - )) - return nil, nil, diags - } - } else { - // If this module is already recorded and its root directory - // exists then we will just load what's already there and - // keep our existing record. - info, err := os.Stat(record.Dir) - if err == nil && info.IsDir() { - mod, mDiags := earlyconfig.LoadModule(record.Dir) - diags = diags.Append(mDiags) - - log.Printf("[TRACE] ModuleInstaller: Module installer: %s %s already installed in %s", key, record.Version, record.Dir) - return mod, record.Version, diags - } - } - - // If we get down here then it's finally time to actually install - // the module. There are some variants to this process depending - // on what type of module source address we have. - switch { - - case isLocalSourceAddr(req.SourceAddr): - log.Printf("[TRACE] ModuleInstaller: %s has local path %q", key, req.SourceAddr) - mod, mDiags := i.installLocalModule(req, key, manifest, hooks) - diags = append(diags, mDiags...) - return mod, nil, diags - - case isRegistrySourceAddr(req.SourceAddr): - addr, err := regsrc.ParseModuleSource(req.SourceAddr) - if err != nil { - // Should never happen because isRegistrySourceAddr already validated - panic(err) - } - log.Printf("[TRACE] ModuleInstaller: %s is a registry module at %s", key, addr) - - mod, v, mDiags := i.installRegistryModule(req, key, instPath, addr, manifest, hooks, getter) - diags = append(diags, mDiags...) - return mod, v, diags - - default: - log.Printf("[TRACE] ModuleInstaller: %s address %q will be handled by go-getter", key, req.SourceAddr) - - mod, mDiags := i.installGoGetterModule(req, key, instPath, manifest, hooks, getter) - diags = append(diags, mDiags...) - return mod, nil, diags - } - - }, - )) - diags = append(diags, cDiags...) - - err := manifest.WriteSnapshotToDir(i.modsDir) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to update module manifest", - fmt.Sprintf("Unable to write the module manifest file: %s", err), - )) - } - - return cfg, diags -} - -func (i *ModuleInstaller) installLocalModule(req *earlyconfig.ModuleRequest, key string, manifest modsdir.Manifest, hooks ModuleInstallHooks) (*tfconfig.Module, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - parentKey := manifest.ModuleKey(req.Parent.Path) - parentRecord, recorded := manifest[parentKey] - if !recorded { - // This is indicative of a bug rather than a user-actionable error - panic(fmt.Errorf("missing manifest record for parent module %s", parentKey)) - } - - if len(req.VersionConstraints) != 0 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid version constraint", - fmt.Sprintf("Cannot apply a version constraint to module %q (at %s:%d) because it has a relative local path.", req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - } - - // For local sources we don't actually need to modify the - // filesystem at all because the parent already wrote - // the files we need, and so we just load up what's already here. - newDir := filepath.Join(parentRecord.Dir, req.SourceAddr) - - log.Printf("[TRACE] ModuleInstaller: %s uses directory from parent: %s", key, newDir) - // it is possible that the local directory is a symlink - newDir, err := filepath.EvalSymlinks(newDir) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unreadable module directory", - fmt.Sprintf("Unable to evaluate directory symlink: %s", err.Error()), - )) - } - - mod, mDiags := earlyconfig.LoadModule(newDir) - if mod == nil { - // nil indicates missing or unreadable directory, so we'll - // discard the returned diags and return a more specific - // error message here. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unreadable module directory", - fmt.Sprintf("The directory %s could not be read for module %q at %s:%d.", newDir, req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - } else { - diags = diags.Append(mDiags) - } - - // Note the local location in our manifest. - manifest[key] = modsdir.Record{ - Key: key, - Dir: newDir, - SourceAddr: req.SourceAddr, - } - log.Printf("[DEBUG] Module installer: %s installed at %s", key, newDir) - hooks.Install(key, nil, newDir) - - return mod, diags -} - -func (i *ModuleInstaller) installRegistryModule(req *earlyconfig.ModuleRequest, key string, instPath string, addr *regsrc.Module, manifest modsdir.Manifest, hooks ModuleInstallHooks, getter reusingGetter) (*tfconfig.Module, *version.Version, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - hostname, err := addr.SvcHost() - if err != nil { - // If it looks like the user was trying to use punycode then we'll generate - // a specialized error for that case. We require the unicode form of - // hostname so that hostnames are always human-readable in configuration - // and punycode can't be used to hide a malicious module hostname. - if strings.HasPrefix(addr.RawHost.Raw, "xn--") { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid module registry hostname", - fmt.Sprintf("The hostname portion of the module %q source address (at %s:%d) is not an acceptable hostname. Internationalized domain names must be given in unicode form rather than ASCII (\"punycode\") form.", req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - } else { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid module registry hostname", - fmt.Sprintf("The hostname portion of the module %q source address (at %s:%d) is not a valid hostname.", req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - } - return nil, nil, diags - } - - reg := i.reg - - log.Printf("[DEBUG] %s listing available versions of %s at %s", key, addr, hostname) - resp, err := reg.ModuleVersions(addr) - if err != nil { - if registry.IsModuleNotFound(err) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Module not found", - fmt.Sprintf("Module %q (from %s:%d) cannot be found in the module registry at %s.", req.Name, req.CallPos.Filename, req.CallPos.Line, hostname), - )) - } else { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Error accessing remote module registry", - fmt.Sprintf("Failed to retrieve available versions for module %q (%s:%d) from %s: %s.", req.Name, req.CallPos.Filename, req.CallPos.Line, hostname, err), - )) - } - return nil, nil, diags - } - - // The response might contain information about dependencies to allow us - // to potentially optimize future requests, but we don't currently do that - // and so for now we'll just take the first item which is guaranteed to - // be the address we requested. - if len(resp.Modules) < 1 { - // Should never happen, but since this is a remote service that may - // be implemented by third-parties we will handle it gracefully. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid response from remote module registry", - fmt.Sprintf("The registry at %s returned an invalid response when Terraform requested available versions for module %q (%s:%d).", hostname, req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - return nil, nil, diags - } - - modMeta := resp.Modules[0] - - var latestMatch *version.Version - var latestVersion *version.Version - for _, mv := range modMeta.Versions { - v, err := version.NewVersion(mv.Version) - if err != nil { - // Should never happen if the registry server is compliant with - // the protocol, but we'll warn if not to assist someone who - // might be developing a module registry server. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Warning, - "Invalid response from remote module registry", - fmt.Sprintf("The registry at %s returned an invalid version string %q for module %q (%s:%d), which Terraform ignored.", hostname, mv.Version, req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - continue - } - - // If we've found a pre-release version then we'll ignore it unless - // it was exactly requested. - if v.Prerelease() != "" && req.VersionConstraints.String() != v.String() { - log.Printf("[TRACE] ModuleInstaller: %s ignoring %s because it is a pre-release and was not requested exactly", key, v) - continue - } - - if latestVersion == nil || v.GreaterThan(latestVersion) { - latestVersion = v - } - - if req.VersionConstraints.Check(v) { - if latestMatch == nil || v.GreaterThan(latestMatch) { - latestMatch = v - } - } - } - - if latestVersion == nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Module has no versions", - fmt.Sprintf("Module %q (%s:%d) has no versions available on %s.", addr, req.CallPos.Filename, req.CallPos.Line, hostname), - )) - return nil, nil, diags - } - - if latestMatch == nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unresolvable module version constraint", - fmt.Sprintf("There is no available version of module %q (%s:%d) which matches the given version constraint. The newest available version is %s.", addr, req.CallPos.Filename, req.CallPos.Line, latestVersion), - )) - return nil, nil, diags - } - - // Report up to the caller that we're about to start downloading. - packageAddr, _ := splitAddrSubdir(req.SourceAddr) - hooks.Download(key, packageAddr, latestMatch) - - // If we manage to get down here then we've found a suitable version to - // install, so we need to ask the registry where we should download it from. - // The response to this is a go-getter-style address string. - dlAddr, err := reg.ModuleLocation(addr, latestMatch.String()) - if err != nil { - log.Printf("[ERROR] %s from %s %s: %s", key, addr, latestMatch, err) - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid response from remote module registry", - fmt.Sprintf("The remote registry at %s failed to return a download URL for %s %s.", hostname, addr, latestMatch), - )) - return nil, nil, diags - } - - log.Printf("[TRACE] ModuleInstaller: %s %s %s is available at %q", key, addr, latestMatch, dlAddr) - - modDir, err := getter.getWithGoGetter(instPath, dlAddr) - if err != nil { - // Errors returned by go-getter have very inconsistent quality as - // end-user error messages, but for now we're accepting that because - // we have no way to recognize any specific errors to improve them - // and masking the error entirely would hide valuable diagnostic - // information from the user. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to download module", - fmt.Sprintf("Could not download module %q (%s:%d) source code from %q: %s.", req.Name, req.CallPos.Filename, req.CallPos.Line, dlAddr, err), - )) - return nil, nil, diags - } - - log.Printf("[TRACE] ModuleInstaller: %s %q was downloaded to %s", key, dlAddr, modDir) - - if addr.RawSubmodule != "" { - // Append the user's requested subdirectory to any subdirectory that - // was implied by any of the nested layers we expanded within go-getter. - modDir = filepath.Join(modDir, addr.RawSubmodule) - } - - log.Printf("[TRACE] ModuleInstaller: %s should now be at %s", key, modDir) - - // Finally we are ready to try actually loading the module. - mod, mDiags := earlyconfig.LoadModule(modDir) - if mod == nil { - // nil indicates missing or unreadable directory, so we'll - // discard the returned diags and return a more specific - // error message here. For registry modules this actually - // indicates a bug in the code above, since it's not the - // user's responsibility to create the directory in this case. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unreadable module directory", - fmt.Sprintf("The directory %s could not be read. This is a bug in Terraform and should be reported.", modDir), - )) - } else { - diags = append(diags, mDiags...) - } - - // Note the local location in our manifest. - manifest[key] = modsdir.Record{ - Key: key, - Version: latestMatch, - Dir: modDir, - SourceAddr: req.SourceAddr, - } - log.Printf("[DEBUG] Module installer: %s installed at %s", key, modDir) - hooks.Install(key, latestMatch, modDir) - - return mod, latestMatch, diags -} - -func (i *ModuleInstaller) installGoGetterModule(req *earlyconfig.ModuleRequest, key string, instPath string, manifest modsdir.Manifest, hooks ModuleInstallHooks, getter reusingGetter) (*tfconfig.Module, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // Report up to the caller that we're about to start downloading. - packageAddr, _ := splitAddrSubdir(req.SourceAddr) - hooks.Download(key, packageAddr, nil) - - if len(req.VersionConstraints) != 0 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid version constraint", - fmt.Sprintf("Cannot apply a version constraint to module %q (at %s:%d) because it has a non Registry URL.", req.Name, req.CallPos.Filename, req.CallPos.Line), - )) - return nil, diags - } - - modDir, err := getter.getWithGoGetter(instPath, req.SourceAddr) - if err != nil { - if _, ok := err.(*MaybeRelativePathErr); ok { - log.Printf( - "[TRACE] ModuleInstaller: %s looks like a local path but is missing ./ or ../", - req.SourceAddr, - ) - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Module not found", - fmt.Sprintf( - "The module address %q could not be resolved.\n\n"+ - "If you intended this as a path relative to the current "+ - "module, use \"./%s\" instead. The \"./\" prefix "+ - "indicates that the address is a relative filesystem path.", - req.SourceAddr, req.SourceAddr, - ), - )) - } else { - // Errors returned by go-getter have very inconsistent quality as - // end-user error messages, but for now we're accepting that because - // we have no way to recognize any specific errors to improve them - // and masking the error entirely would hide valuable diagnostic - // information from the user. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to download module", - fmt.Sprintf("Could not download module %q (%s:%d) source code from %q: %s", req.Name, req.CallPos.Filename, req.CallPos.Line, packageAddr, err), - )) - } - return nil, diags - - } - - log.Printf("[TRACE] ModuleInstaller: %s %q was downloaded to %s", key, req.SourceAddr, modDir) - - mod, mDiags := earlyconfig.LoadModule(modDir) - if mod == nil { - // nil indicates missing or unreadable directory, so we'll - // discard the returned diags and return a more specific - // error message here. For go-getter modules this actually - // indicates a bug in the code above, since it's not the - // user's responsibility to create the directory in this case. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unreadable module directory", - fmt.Sprintf("The directory %s could not be read. This is a bug in Terraform and should be reported.", modDir), - )) - } else { - diags = append(diags, mDiags...) - } - - // Note the local location in our manifest. - manifest[key] = modsdir.Record{ - Key: key, - Dir: modDir, - SourceAddr: req.SourceAddr, - } - log.Printf("[DEBUG] Module installer: %s installed at %s", key, modDir) - hooks.Install(key, nil, modDir) - - return mod, diags -} - -func (i *ModuleInstaller) packageInstallPath(modulePath addrs.Module) string { - return filepath.Join(i.modsDir, strings.Join(modulePath, ".")) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/module_install_hooks.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/module_install_hooks.go deleted file mode 100644 index 817a6dc832a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/initwd/module_install_hooks.go +++ /dev/null @@ -1,36 +0,0 @@ -package initwd - -import ( - version "github.com/hashicorp/go-version" -) - -// ModuleInstallHooks is an interface used to provide notifications about the -// installation process being orchestrated by InstallModules. -// -// This interface may have new methods added in future, so implementers should -// embed InstallHooksImpl to get no-op implementations of any unimplemented -// methods. -type ModuleInstallHooks interface { - // Download is called for modules that are retrieved from a remote source - // before that download begins, to allow a caller to give feedback - // on progress through a possibly-long sequence of downloads. - Download(moduleAddr, packageAddr string, version *version.Version) - - // Install is called for each module that is installed, even if it did - // not need to be downloaded from a remote source. - Install(moduleAddr string, version *version.Version, localPath string) -} - -// ModuleInstallHooksImpl is a do-nothing implementation of InstallHooks that -// can be embedded in another implementation struct to allow only partial -// implementation of the interface. -type ModuleInstallHooksImpl struct { -} - -func (h ModuleInstallHooksImpl) Download(moduleAddr, packageAddr string, version *version.Version) { -} - -func (h ModuleInstallHooksImpl) Install(moduleAddr string, version *version.Version, localPath string) { -} - -var _ ModuleInstallHooks = ModuleInstallHooksImpl{} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/doc.go deleted file mode 100644 index 8f89909c6fc..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package blocktoattr includes some helper functions that can perform -// preprocessing on a HCL body where a configschema.Block schema is available -// in order to allow list and set attributes defined in the schema to be -// optionally written by the user as block syntax. -package blocktoattr diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/fixup.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/fixup.go deleted file mode 100644 index f782f6b754d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/fixup.go +++ /dev/null @@ -1,187 +0,0 @@ -package blocktoattr - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hcldec" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/zclconf/go-cty/cty" -) - -// FixUpBlockAttrs takes a raw HCL body and adds some additional normalization -// functionality to allow attributes that are specified as having list or set -// type in the schema to be written with HCL block syntax as multiple nested -// blocks with the attribute name as the block type. -// -// This partially restores some of the block/attribute confusion from HCL 1 -// so that existing patterns that depended on that confusion can continue to -// be used in the short term while we settle on a longer-term strategy. -// -// Most of the fixup work is actually done when the returned body is -// subsequently decoded, so while FixUpBlockAttrs always succeeds, the eventual -// decode of the body might not, if the content of the body is so ambiguous -// that there's no safe way to map it to the schema. -func FixUpBlockAttrs(body hcl.Body, schema *configschema.Block) hcl.Body { - // The schema should never be nil, but in practice it seems to be sometimes - // in the presence of poorly-configured test mocks, so we'll be robust - // by synthesizing an empty one. - if schema == nil { - schema = &configschema.Block{} - } - - return &fixupBody{ - original: body, - schema: schema, - names: ambiguousNames(schema), - } -} - -type fixupBody struct { - original hcl.Body - schema *configschema.Block - names map[string]struct{} -} - -// Content decodes content from the body. The given schema must be the lower-level -// representation of the same schema that was previously passed to FixUpBlockAttrs, -// or else the result is undefined. -func (b *fixupBody) Content(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Diagnostics) { - schema = b.effectiveSchema(schema) - content, diags := b.original.Content(schema) - return b.fixupContent(content), diags -} - -func (b *fixupBody) PartialContent(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Body, hcl.Diagnostics) { - schema = b.effectiveSchema(schema) - content, remain, diags := b.original.PartialContent(schema) - remain = &fixupBody{ - original: remain, - schema: b.schema, - names: b.names, - } - return b.fixupContent(content), remain, diags -} - -func (b *fixupBody) JustAttributes() (hcl.Attributes, hcl.Diagnostics) { - // FixUpBlockAttrs is not intended to be used in situations where we'd use - // JustAttributes, so we just pass this through verbatim to complete our - // implementation of hcl.Body. - return b.original.JustAttributes() -} - -func (b *fixupBody) MissingItemRange() hcl.Range { - return b.original.MissingItemRange() -} - -// effectiveSchema produces a derived *hcl.BodySchema by sniffing the body's -// content to determine whether the author has used attribute or block syntax -// for each of the ambigious attributes where both are permitted. -// -// The resulting schema will always contain all of the same names that are -// in the given schema, but some attribute schemas may instead be replaced by -// block header schemas. -func (b *fixupBody) effectiveSchema(given *hcl.BodySchema) *hcl.BodySchema { - return effectiveSchema(given, b.original, b.names, true) -} - -func (b *fixupBody) fixupContent(content *hcl.BodyContent) *hcl.BodyContent { - var ret hcl.BodyContent - ret.Attributes = make(hcl.Attributes) - for name, attr := range content.Attributes { - ret.Attributes[name] = attr - } - blockAttrVals := make(map[string][]*hcl.Block) - for _, block := range content.Blocks { - if _, exists := b.names[block.Type]; exists { - // If we get here then we've found a block type whose instances need - // to be re-interpreted as a list-of-objects attribute. We'll gather - // those up and fix them up below. - blockAttrVals[block.Type] = append(blockAttrVals[block.Type], block) - continue - } - - // We need to now re-wrap our inner body so it will be subject to the - // same attribute-as-block fixup when recursively decoded. - retBlock := *block // shallow copy - if blockS, ok := b.schema.BlockTypes[block.Type]; ok { - // Would be weird if not ok, but we'll allow it for robustness; body just won't be fixed up, then - retBlock.Body = FixUpBlockAttrs(retBlock.Body, &blockS.Block) - } - - ret.Blocks = append(ret.Blocks, &retBlock) - } - // No we'll install synthetic attributes for each of our fixups. We can't - // do this exactly because HCL's information model expects an attribute - // to be a single decl but we have multiple separate blocks. We'll - // approximate things, then, by using only our first block for the source - // location information. (We are guaranteed at least one by the above logic.) - for name, blocks := range blockAttrVals { - ret.Attributes[name] = &hcl.Attribute{ - Name: name, - Expr: &fixupBlocksExpr{ - blocks: blocks, - ety: b.schema.Attributes[name].Type.ElementType(), - }, - - Range: blocks[0].DefRange, - NameRange: blocks[0].TypeRange, - } - } - return &ret -} - -type fixupBlocksExpr struct { - blocks hcl.Blocks - ety cty.Type -} - -func (e *fixupBlocksExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - // In order to produce a suitable value for our expression we need to - // now decode the whole descendent block structure under each of our block - // bodies. - // - // That requires us to do something rather strange: we must construct a - // synthetic block type schema derived from the element type of the - // attribute, thus inverting our usual direction of lowering a schema - // into an implied type. Because a type is less detailed than a schema, - // the result is imprecise and in particular will just consider all - // the attributes to be optional and let the provider eventually decide - // whether to return errors if they turn out to be null when required. - schema := SchemaForCtyElementType(e.ety) // this schema's ImpliedType will match e.ety - spec := schema.DecoderSpec() - - vals := make([]cty.Value, len(e.blocks)) - var diags hcl.Diagnostics - for i, block := range e.blocks { - body := FixUpBlockAttrs(block.Body, schema) - val, blockDiags := hcldec.Decode(body, spec, ctx) - diags = append(diags, blockDiags...) - if val == cty.NilVal { - val = cty.UnknownVal(e.ety) - } - vals[i] = val - } - if len(vals) == 0 { - return cty.ListValEmpty(e.ety), diags - } - return cty.ListVal(vals), diags -} - -func (e *fixupBlocksExpr) Variables() []hcl.Traversal { - var ret []hcl.Traversal - schema := SchemaForCtyElementType(e.ety) - spec := schema.DecoderSpec() - for _, block := range e.blocks { - ret = append(ret, hcldec.Variables(block.Body, spec)...) - } - return ret -} - -func (e *fixupBlocksExpr) Range() hcl.Range { - // This is not really an appropriate range for the expression but it's - // the best we can do from here. - return e.blocks[0].DefRange -} - -func (e *fixupBlocksExpr) StartRange() hcl.Range { - return e.blocks[0].DefRange -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/schema.go deleted file mode 100644 index 129ee0e82fa..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/schema.go +++ /dev/null @@ -1,119 +0,0 @@ -package blocktoattr - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/zclconf/go-cty/cty" -) - -func ambiguousNames(schema *configschema.Block) map[string]struct{} { - if schema == nil { - return nil - } - ambiguousNames := make(map[string]struct{}) - for name, attrS := range schema.Attributes { - aty := attrS.Type - if (aty.IsListType() || aty.IsSetType()) && aty.ElementType().IsObjectType() { - ambiguousNames[name] = struct{}{} - } - } - return ambiguousNames -} - -func effectiveSchema(given *hcl.BodySchema, body hcl.Body, ambiguousNames map[string]struct{}, dynamicExpanded bool) *hcl.BodySchema { - ret := &hcl.BodySchema{} - - appearsAsBlock := make(map[string]struct{}) - { - // We'll construct some throwaway schemas here just to probe for - // whether each of our ambiguous names seems to be being used as - // an attribute or a block. We need to check both because in JSON - // syntax we rely on the schema to decide between attribute or block - // interpretation and so JSON will always answer yes to both of - // these questions and we want to prefer the attribute interpretation - // in that case. - var probeSchema hcl.BodySchema - - for name := range ambiguousNames { - probeSchema = hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: name, - }, - }, - } - content, _, _ := body.PartialContent(&probeSchema) - if _, exists := content.Attributes[name]; exists { - // Can decode as an attribute, so we'll go with that. - continue - } - probeSchema = hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: name, - }, - }, - } - content, _, _ = body.PartialContent(&probeSchema) - if len(content.Blocks) > 0 || dynamicExpanded { - // A dynamic block with an empty iterator returns nothing. - // If there's no attribute and we have either a block or a - // dynamic expansion, we need to rewrite this one as a - // block for a successful result. - appearsAsBlock[name] = struct{}{} - } - } - if !dynamicExpanded { - // If we're deciding for a context where dynamic blocks haven't - // been expanded yet then we need to probe for those too. - probeSchema = hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "dynamic", - LabelNames: []string{"type"}, - }, - }, - } - content, _, _ := body.PartialContent(&probeSchema) - for _, block := range content.Blocks { - if _, exists := ambiguousNames[block.Labels[0]]; exists { - appearsAsBlock[block.Labels[0]] = struct{}{} - } - } - } - } - - for _, attrS := range given.Attributes { - if _, exists := appearsAsBlock[attrS.Name]; exists { - ret.Blocks = append(ret.Blocks, hcl.BlockHeaderSchema{ - Type: attrS.Name, - }) - } else { - ret.Attributes = append(ret.Attributes, attrS) - } - } - - // Anything that is specified as a block type in the input schema remains - // that way by just passing through verbatim. - ret.Blocks = append(ret.Blocks, given.Blocks...) - - return ret -} - -// SchemaForCtyElementType converts a cty object type into an -// approximately-equivalent configschema.Block representing the element of -// a list or set. If the given type is not an object type then this -// function will panic. -func SchemaForCtyElementType(ty cty.Type) *configschema.Block { - atys := ty.AttributeTypes() - ret := &configschema.Block{ - Attributes: make(map[string]*configschema.Attribute, len(atys)), - } - for name, aty := range atys { - ret.Attributes[name] = &configschema.Attribute{ - Type: aty, - Optional: true, - } - } - return ret -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/variables.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/variables.go deleted file mode 100644 index f5ed1c539b7..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr/variables.go +++ /dev/null @@ -1,45 +0,0 @@ -package blocktoattr - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/ext/dynblock" - "github.com/hashicorp/hcl/v2/hcldec" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" -) - -// ExpandedVariables finds all of the global variables referenced in the -// given body with the given schema while taking into account the possibilities -// both of "dynamic" blocks being expanded and the possibility of certain -// attributes being written instead as nested blocks as allowed by the -// FixUpBlockAttrs function. -// -// This function exists to allow variables to be analyzed prior to dynamic -// block expansion while also dealing with the fact that dynamic block expansion -// might in turn produce nested blocks that are subject to FixUpBlockAttrs. -// -// This is intended as a drop-in replacement for dynblock.VariablesHCLDec, -// which is itself a drop-in replacement for hcldec.Variables. -func ExpandedVariables(body hcl.Body, schema *configschema.Block) []hcl.Traversal { - rootNode := dynblock.WalkVariables(body) - return walkVariables(rootNode, body, schema) -} - -func walkVariables(node dynblock.WalkVariablesNode, body hcl.Body, schema *configschema.Block) []hcl.Traversal { - givenRawSchema := hcldec.ImpliedSchema(schema.DecoderSpec()) - ambiguousNames := ambiguousNames(schema) - effectiveRawSchema := effectiveSchema(givenRawSchema, body, ambiguousNames, false) - vars, children := node.Visit(effectiveRawSchema) - - for _, child := range children { - if blockS, exists := schema.BlockTypes[child.BlockTypeName]; exists { - vars = append(vars, walkVariables(child.Node, child.Body(), &blockS.Block)...) - } else if attrS, exists := schema.Attributes[child.BlockTypeName]; exists && attrS.Type.IsCollectionType() && attrS.Type.ElementType().IsObjectType() { - // ☝️Check for collection type before element type, because if this is a mis-placed reference, - // a panic here will prevent other useful diags from being elevated to show the user what to fix - synthSchema := SchemaForCtyElementType(attrS.Type.ElementType()) - vars = append(vars, walkVariables(child.Node, child.Body(), synthSchema)...) - } - } - - return vars -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/data.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/data.go deleted file mode 100644 index 13f7ed935e8..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/data.go +++ /dev/null @@ -1,34 +0,0 @@ -package lang - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" -) - -// Data is an interface whose implementations can provide cty.Value -// representations of objects identified by referenceable addresses from -// the addrs package. -// -// This interface will grow each time a new type of reference is added, and so -// implementations outside of the Terraform codebases are not advised. -// -// Each method returns a suitable value and optionally some diagnostics. If the -// returned diagnostics contains errors then the type of the returned value is -// used to construct an unknown value of the same type which is then used in -// place of the requested object so that type checking can still proceed. In -// cases where it's not possible to even determine a suitable result type, -// cty.DynamicVal is returned along with errors describing the problem. -type Data interface { - StaticValidateReferences(refs []*addrs.Reference, self addrs.Referenceable) tfdiags.Diagnostics - - GetCountAttr(addrs.CountAttr, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetForEachAttr(addrs.ForEachAttr, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetResource(addrs.Resource, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetLocalValue(addrs.LocalValue, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetModuleInstance(addrs.ModuleCallInstance, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetModuleInstanceOutput(addrs.ModuleCallOutput, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetPathAttr(addrs.PathAttr, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetTerraformAttr(addrs.TerraformAttr, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) - GetInputVariable(addrs.InputVariable, tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/doc.go deleted file mode 100644 index af5c5cac0d2..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package lang deals with the runtime aspects of Terraform's configuration -// language, with concerns such as expression evaluation. It is closely related -// to sibling package "configs", which is responsible for configuration -// parsing and static validation. -package lang diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/eval.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/eval.go deleted file mode 100644 index ec48a873f04..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/eval.go +++ /dev/null @@ -1,473 +0,0 @@ -package lang - -import ( - "fmt" - "log" - "strconv" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/ext/dynblock" - "github.com/hashicorp/hcl/v2/hcldec" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// ExpandBlock expands any "dynamic" blocks present in the given body. The -// result is a body with those blocks expanded, ready to be evaluated with -// EvalBlock. -// -// If the returned diagnostics contains errors then the result may be -// incomplete or invalid. -func (s *Scope) ExpandBlock(body hcl.Body, schema *configschema.Block) (hcl.Body, tfdiags.Diagnostics) { - spec := schema.DecoderSpec() - - traversals := dynblock.ExpandVariablesHCLDec(body, spec) - refs, diags := References(traversals) - - ctx, ctxDiags := s.EvalContext(refs) - diags = diags.Append(ctxDiags) - - return dynblock.Expand(body, ctx), diags -} - -// EvalBlock evaluates the given body using the given block schema and returns -// a cty object value representing its contents. The type of the result conforms -// to the implied type of the given schema. -// -// This function does not automatically expand "dynamic" blocks within the -// body. If that is desired, first call the ExpandBlock method to obtain -// an expanded body to pass to this method. -// -// If the returned diagnostics contains errors then the result may be -// incomplete or invalid. -func (s *Scope) EvalBlock(body hcl.Body, schema *configschema.Block) (cty.Value, tfdiags.Diagnostics) { - spec := schema.DecoderSpec() - - refs, diags := ReferencesInBlock(body, schema) - - ctx, ctxDiags := s.EvalContext(refs) - diags = diags.Append(ctxDiags) - if diags.HasErrors() { - // We'll stop early if we found problems in the references, because - // it's likely evaluation will produce redundant copies of the same errors. - return cty.UnknownVal(schema.ImpliedType()), diags - } - - // HACK: In order to remain compatible with some assumptions made in - // Terraform v0.11 and earlier about the approximate equivalence of - // attribute vs. block syntax, we do a just-in-time fixup here to allow - // any attribute in the schema that has a list-of-objects or set-of-objects - // kind to potentially be populated instead by one or more nested blocks - // whose type is the attribute name. - body = blocktoattr.FixUpBlockAttrs(body, schema) - - val, evalDiags := hcldec.Decode(body, spec, ctx) - diags = diags.Append(evalDiags) - - return val, diags -} - -// EvalExpr evaluates a single expression in the receiving context and returns -// the resulting value. The value will be converted to the given type before -// it is returned if possible, or else an error diagnostic will be produced -// describing the conversion error. -// -// Pass an expected type of cty.DynamicPseudoType to skip automatic conversion -// and just obtain the returned value directly. -// -// If the returned diagnostics contains errors then the result may be -// incomplete, but will always be of the requested type. -func (s *Scope) EvalExpr(expr hcl.Expression, wantType cty.Type) (cty.Value, tfdiags.Diagnostics) { - refs, diags := ReferencesInExpr(expr) - - ctx, ctxDiags := s.EvalContext(refs) - diags = diags.Append(ctxDiags) - if diags.HasErrors() { - // We'll stop early if we found problems in the references, because - // it's likely evaluation will produce redundant copies of the same errors. - return cty.UnknownVal(wantType), diags - } - - val, evalDiags := expr.Value(ctx) - diags = diags.Append(evalDiags) - - if wantType != cty.DynamicPseudoType { - var convErr error - val, convErr = convert.Convert(val, wantType) - if convErr != nil { - val = cty.UnknownVal(wantType) - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Incorrect value type", - Detail: fmt.Sprintf("Invalid expression value: %s.", tfdiags.FormatError(convErr)), - Subject: expr.Range().Ptr(), - }) - } - } - - return val, diags -} - -// EvalReference evaluates the given reference in the receiving scope and -// returns the resulting value. The value will be converted to the given type before -// it is returned if possible, or else an error diagnostic will be produced -// describing the conversion error. -// -// Pass an expected type of cty.DynamicPseudoType to skip automatic conversion -// and just obtain the returned value directly. -// -// If the returned diagnostics contains errors then the result may be -// incomplete, but will always be of the requested type. -func (s *Scope) EvalReference(ref *addrs.Reference, wantType cty.Type) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // We cheat a bit here and just build an EvalContext for our requested - // reference with the "self" address overridden, and then pull the "self" - // result out of it to return. - ctx, ctxDiags := s.evalContext([]*addrs.Reference{ref}, ref.Subject) - diags = diags.Append(ctxDiags) - val := ctx.Variables["self"] - if val == cty.NilVal { - val = cty.DynamicVal - } - - var convErr error - val, convErr = convert.Convert(val, wantType) - if convErr != nil { - val = cty.UnknownVal(wantType) - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Incorrect value type", - Detail: fmt.Sprintf("Invalid expression value: %s.", tfdiags.FormatError(convErr)), - Subject: ref.SourceRange.ToHCL().Ptr(), - }) - } - - return val, diags -} - -// EvalContext constructs a HCL expression evaluation context whose variable -// scope contains sufficient values to satisfy the given set of references. -// -// Most callers should prefer to use the evaluation helper methods that -// this type offers, but this is here for less common situations where the -// caller will handle the evaluation calls itself. -func (s *Scope) EvalContext(refs []*addrs.Reference) (*hcl.EvalContext, tfdiags.Diagnostics) { - return s.evalContext(refs, s.SelfAddr) -} - -func (s *Scope) evalContext(refs []*addrs.Reference, selfAddr addrs.Referenceable) (*hcl.EvalContext, tfdiags.Diagnostics) { - if s == nil { - panic("attempt to construct EvalContext for nil Scope") - } - - var diags tfdiags.Diagnostics - vals := make(map[string]cty.Value) - funcs := s.Functions() - ctx := &hcl.EvalContext{ - Variables: vals, - Functions: funcs, - } - - if len(refs) == 0 { - // Easy path for common case where there are no references at all. - return ctx, diags - } - - // First we'll do static validation of the references. This catches things - // early that might otherwise not get caught due to unknown values being - // present in the scope during planning. - if staticDiags := s.Data.StaticValidateReferences(refs, selfAddr); staticDiags.HasErrors() { - diags = diags.Append(staticDiags) - return ctx, diags - } - - // The reference set we are given has not been de-duped, and so there can - // be redundant requests in it for two reasons: - // - The same item is referenced multiple times - // - Both an item and that item's container are separately referenced. - // We will still visit every reference here and ask our data source for - // it, since that allows us to gather a full set of any errors and - // warnings, but once we've gathered all the data we'll then skip anything - // that's redundant in the process of populating our values map. - dataResources := map[string]map[string]cty.Value{} - managedResources := map[string]map[string]cty.Value{} - wholeModules := map[string]map[addrs.InstanceKey]cty.Value{} - moduleOutputs := map[string]map[addrs.InstanceKey]map[string]cty.Value{} - inputVariables := map[string]cty.Value{} - localValues := map[string]cty.Value{} - pathAttrs := map[string]cty.Value{} - terraformAttrs := map[string]cty.Value{} - countAttrs := map[string]cty.Value{} - forEachAttrs := map[string]cty.Value{} - var self cty.Value - - for _, ref := range refs { - rng := ref.SourceRange - - rawSubj := ref.Subject - if rawSubj == addrs.Self { - if selfAddr == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "self" reference`, - // This detail message mentions some current practice that - // this codepath doesn't really "know about". If the "self" - // object starts being supported in more contexts later then - // we'll need to adjust this message. - Detail: `The "self" object is not available in this context. This object can be used only in resource provisioner and connection blocks.`, - Subject: ref.SourceRange.ToHCL().Ptr(), - }) - continue - } - - if selfAddr == addrs.Self { - // Programming error: the self address cannot alias itself. - panic("scope SelfAddr attempting to alias itself") - } - - // self can only be used within a resource instance - subj := selfAddr.(addrs.ResourceInstance) - - val, valDiags := normalizeRefValue(s.Data.GetResource(subj.ContainingResource(), rng)) - - diags = diags.Append(valDiags) - - // Self is an exception in that it must always resolve to a - // particular instance. We will still insert the full resource into - // the context below. - switch k := subj.Key.(type) { - case addrs.IntKey: - self = val.Index(cty.NumberIntVal(int64(k))) - case addrs.StringKey: - self = val.Index(cty.StringVal(string(k))) - default: - self = val - } - - continue - } - - // This type switch must cover all of the "Referenceable" implementations - // in package addrs, however we are removing the possibility of - // ResourceInstance beforehand. - if addr, ok := rawSubj.(addrs.ResourceInstance); ok { - rawSubj = addr.ContainingResource() - } - - switch subj := rawSubj.(type) { - case addrs.Resource: - var into map[string]map[string]cty.Value - switch subj.Mode { - case addrs.ManagedResourceMode: - into = managedResources - case addrs.DataResourceMode: - into = dataResources - default: - panic(fmt.Errorf("unsupported ResourceMode %s", subj.Mode)) - } - - val, valDiags := normalizeRefValue(s.Data.GetResource(subj, rng)) - diags = diags.Append(valDiags) - - r := subj - if into[r.Type] == nil { - into[r.Type] = make(map[string]cty.Value) - } - into[r.Type][r.Name] = val - - case addrs.ModuleCallInstance: - val, valDiags := normalizeRefValue(s.Data.GetModuleInstance(subj, rng)) - diags = diags.Append(valDiags) - - if wholeModules[subj.Call.Name] == nil { - wholeModules[subj.Call.Name] = make(map[addrs.InstanceKey]cty.Value) - } - wholeModules[subj.Call.Name][subj.Key] = val - - case addrs.ModuleCallOutput: - val, valDiags := normalizeRefValue(s.Data.GetModuleInstanceOutput(subj, rng)) - diags = diags.Append(valDiags) - - callName := subj.Call.Call.Name - callKey := subj.Call.Key - if moduleOutputs[callName] == nil { - moduleOutputs[callName] = make(map[addrs.InstanceKey]map[string]cty.Value) - } - if moduleOutputs[callName][callKey] == nil { - moduleOutputs[callName][callKey] = make(map[string]cty.Value) - } - moduleOutputs[callName][callKey][subj.Name] = val - - case addrs.InputVariable: - val, valDiags := normalizeRefValue(s.Data.GetInputVariable(subj, rng)) - diags = diags.Append(valDiags) - inputVariables[subj.Name] = val - - case addrs.LocalValue: - val, valDiags := normalizeRefValue(s.Data.GetLocalValue(subj, rng)) - diags = diags.Append(valDiags) - localValues[subj.Name] = val - - case addrs.PathAttr: - val, valDiags := normalizeRefValue(s.Data.GetPathAttr(subj, rng)) - diags = diags.Append(valDiags) - pathAttrs[subj.Name] = val - - case addrs.TerraformAttr: - val, valDiags := normalizeRefValue(s.Data.GetTerraformAttr(subj, rng)) - diags = diags.Append(valDiags) - terraformAttrs[subj.Name] = val - - case addrs.CountAttr: - val, valDiags := normalizeRefValue(s.Data.GetCountAttr(subj, rng)) - diags = diags.Append(valDiags) - countAttrs[subj.Name] = val - - case addrs.ForEachAttr: - val, valDiags := normalizeRefValue(s.Data.GetForEachAttr(subj, rng)) - diags = diags.Append(valDiags) - forEachAttrs[subj.Name] = val - - default: - // Should never happen - panic(fmt.Errorf("Scope.buildEvalContext cannot handle address type %T", rawSubj)) - } - } - - for k, v := range buildResourceObjects(managedResources) { - vals[k] = v - } - vals["data"] = cty.ObjectVal(buildResourceObjects(dataResources)) - vals["module"] = cty.ObjectVal(buildModuleObjects(wholeModules, moduleOutputs)) - vals["var"] = cty.ObjectVal(inputVariables) - vals["local"] = cty.ObjectVal(localValues) - vals["path"] = cty.ObjectVal(pathAttrs) - vals["terraform"] = cty.ObjectVal(terraformAttrs) - vals["count"] = cty.ObjectVal(countAttrs) - vals["each"] = cty.ObjectVal(forEachAttrs) - if self != cty.NilVal { - vals["self"] = self - } - - return ctx, diags -} - -func buildResourceObjects(resources map[string]map[string]cty.Value) map[string]cty.Value { - vals := make(map[string]cty.Value) - for typeName, nameVals := range resources { - vals[typeName] = cty.ObjectVal(nameVals) - } - return vals -} - -func buildModuleObjects(wholeModules map[string]map[addrs.InstanceKey]cty.Value, moduleOutputs map[string]map[addrs.InstanceKey]map[string]cty.Value) map[string]cty.Value { - vals := make(map[string]cty.Value) - - for name, keys := range wholeModules { - vals[name] = buildInstanceObjects(keys) - } - - for name, keys := range moduleOutputs { - if _, exists := wholeModules[name]; exists { - // If we also have a whole module value for this name then we'll - // skip this since the individual outputs are embedded in that result. - continue - } - - // The shape of this collection isn't compatible with buildInstanceObjects, - // but rather than replicating most of the buildInstanceObjects logic - // here we'll instead first transform the structure to be what that - // function expects and then use it. This is a little wasteful, but - // we do not expect this these maps to be large and so the extra work - // here should not hurt too much. - flattened := make(map[addrs.InstanceKey]cty.Value, len(keys)) - for k, vals := range keys { - flattened[k] = cty.ObjectVal(vals) - } - vals[name] = buildInstanceObjects(flattened) - } - - return vals -} - -func buildInstanceObjects(keys map[addrs.InstanceKey]cty.Value) cty.Value { - if val, exists := keys[addrs.NoKey]; exists { - // If present, a "no key" value supersedes all other values, - // since they should be embedded inside it. - return val - } - - // If we only have individual values then we need to construct - // either a list or a map, depending on what sort of keys we - // have. - haveInt := false - haveString := false - maxInt := 0 - - for k := range keys { - switch tk := k.(type) { - case addrs.IntKey: - haveInt = true - if int(tk) > maxInt { - maxInt = int(tk) - } - case addrs.StringKey: - haveString = true - } - } - - // We should either have ints or strings and not both, but - // if we have both then we'll prefer strings and let the - // language interpreter try to convert the int keys into - // strings in a map. - switch { - case haveString: - vals := make(map[string]cty.Value) - for k, v := range keys { - switch tk := k.(type) { - case addrs.StringKey: - vals[string(tk)] = v - case addrs.IntKey: - sk := strconv.Itoa(int(tk)) - vals[sk] = v - } - } - return cty.ObjectVal(vals) - case haveInt: - // We'll make a tuple that is long enough for our maximum - // index value. It doesn't matter if we end up shorter than - // the number of instances because if length(...) were - // being evaluated we would've got a NoKey reference and - // thus not ended up in this codepath at all. - vals := make([]cty.Value, maxInt+1) - for i := range vals { - if v, exists := keys[addrs.IntKey(i)]; exists { - vals[i] = v - } else { - // Just a placeholder, since nothing will access this anyway - vals[i] = cty.DynamicVal - } - } - return cty.TupleVal(vals) - default: - // Should never happen because there are no other key types. - log.Printf("[ERROR] strange makeInstanceObjects call with no supported key types") - return cty.EmptyObjectVal - } -} - -func normalizeRefValue(val cty.Value, diags tfdiags.Diagnostics) (cty.Value, tfdiags.Diagnostics) { - if diags.HasErrors() { - // If there are errors then we will force an unknown result so that - // we can still evaluate and catch type errors but we'll avoid - // producing redundant re-statements of the same errors we've already - // dealt with here. - return cty.UnknownVal(val.Type()), diags - } - return val, diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/cidr.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/cidr.go deleted file mode 100644 index 8c075148964..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/cidr.go +++ /dev/null @@ -1,218 +0,0 @@ -package funcs - -import ( - "fmt" - "net" - - "github.com/apparentlymart/go-cidr/cidr" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/gocty" -) - -// CidrHostFunc contructs a function that calculates a full host IP address -// within a given IP network address prefix. -var CidrHostFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "prefix", - Type: cty.String, - }, - { - Name: "hostnum", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var hostNum int - if err := gocty.FromCtyValue(args[1], &hostNum); err != nil { - return cty.UnknownVal(cty.String), err - } - _, network, err := net.ParseCIDR(args[0].AsString()) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) - } - - ip, err := cidr.Host(network, hostNum) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.StringVal(ip.String()), nil - }, -}) - -// CidrNetmaskFunc contructs a function that converts an IPv4 address prefix given -// in CIDR notation into a subnet mask address. -var CidrNetmaskFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "prefix", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - _, network, err := net.ParseCIDR(args[0].AsString()) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) - } - - return cty.StringVal(net.IP(network.Mask).String()), nil - }, -}) - -// CidrSubnetFunc contructs a function that calculates a subnet address within -// a given IP network address prefix. -var CidrSubnetFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "prefix", - Type: cty.String, - }, - { - Name: "newbits", - Type: cty.Number, - }, - { - Name: "netnum", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var newbits int - if err := gocty.FromCtyValue(args[1], &newbits); err != nil { - return cty.UnknownVal(cty.String), err - } - var netnum int - if err := gocty.FromCtyValue(args[2], &netnum); err != nil { - return cty.UnknownVal(cty.String), err - } - - _, network, err := net.ParseCIDR(args[0].AsString()) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) - } - - // For portability with 32-bit systems where the subnet number - // will be a 32-bit int, we only allow extension of 32 bits in - // one call even if we're running on a 64-bit machine. - // (Of course, this is significant only for IPv6.) - if newbits > 32 { - return cty.UnknownVal(cty.String), fmt.Errorf("may not extend prefix by more than 32 bits") - } - - newNetwork, err := cidr.Subnet(network, newbits, netnum) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.StringVal(newNetwork.String()), nil - }, -}) - -// CidrSubnetsFunc is similar to CidrSubnetFunc but calculates many consecutive -// subnet addresses at once, rather than just a single subnet extension. -var CidrSubnetsFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "prefix", - Type: cty.String, - }, - }, - VarParam: &function.Parameter{ - Name: "newbits", - Type: cty.Number, - }, - Type: function.StaticReturnType(cty.List(cty.String)), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - _, network, err := net.ParseCIDR(args[0].AsString()) - if err != nil { - return cty.UnknownVal(cty.String), function.NewArgErrorf(0, "invalid CIDR expression: %s", err) - } - startPrefixLen, _ := network.Mask.Size() - - prefixLengthArgs := args[1:] - if len(prefixLengthArgs) == 0 { - return cty.ListValEmpty(cty.String), nil - } - - var firstLength int - if err := gocty.FromCtyValue(prefixLengthArgs[0], &firstLength); err != nil { - return cty.UnknownVal(cty.String), function.NewArgError(1, err) - } - firstLength += startPrefixLen - - retVals := make([]cty.Value, len(prefixLengthArgs)) - - current, _ := cidr.PreviousSubnet(network, firstLength) - for i, lengthArg := range prefixLengthArgs { - var length int - if err := gocty.FromCtyValue(lengthArg, &length); err != nil { - return cty.UnknownVal(cty.String), function.NewArgError(i+1, err) - } - - if length < 1 { - return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "must extend prefix by at least one bit") - } - // For portability with 32-bit systems where the subnet number - // will be a 32-bit int, we only allow extension of 32 bits in - // one call even if we're running on a 64-bit machine. - // (Of course, this is significant only for IPv6.) - if length > 32 { - return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "may not extend prefix by more than 32 bits") - } - length += startPrefixLen - if length > (len(network.IP) * 8) { - protocol := "IP" - switch len(network.IP) * 8 { - case 32: - protocol = "IPv4" - case 128: - protocol = "IPv6" - } - return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "would extend prefix to %d bits, which is too long for an %s address", length, protocol) - } - - next, rollover := cidr.NextSubnet(current, length) - if rollover || !network.Contains(next.IP) { - // If we run out of suffix bits in the base CIDR prefix then - // NextSubnet will start incrementing the prefix bits, which - // we don't allow because it would then allocate addresses - // outside of the caller's given prefix. - return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "not enough remaining address space for a subnet with a prefix of %d bits after %s", length, current.String()) - } - - current = next - retVals[i] = cty.StringVal(current.String()) - } - - return cty.ListVal(retVals), nil - }, -}) - -// CidrHost calculates a full host IP address within a given IP network address prefix. -func CidrHost(prefix, hostnum cty.Value) (cty.Value, error) { - return CidrHostFunc.Call([]cty.Value{prefix, hostnum}) -} - -// CidrNetmask converts an IPv4 address prefix given in CIDR notation into a subnet mask address. -func CidrNetmask(prefix cty.Value) (cty.Value, error) { - return CidrNetmaskFunc.Call([]cty.Value{prefix}) -} - -// CidrSubnet calculates a subnet address within a given IP network address prefix. -func CidrSubnet(prefix, newbits, netnum cty.Value) (cty.Value, error) { - return CidrSubnetFunc.Call([]cty.Value{prefix, newbits, netnum}) -} - -// CidrSubnets calculates a sequence of consecutive subnet prefixes that may -// be of different prefix lengths under a common base prefix. -func CidrSubnets(prefix cty.Value, newbits ...cty.Value) (cty.Value, error) { - args := make([]cty.Value, len(newbits)+1) - args[0] = prefix - copy(args[1:], newbits) - return CidrSubnetsFunc.Call(args) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/collection.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/collection.go deleted file mode 100644 index e6898457b9d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/collection.go +++ /dev/null @@ -1,1519 +0,0 @@ -package funcs - -import ( - "errors" - "fmt" - "sort" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/function/stdlib" - "github.com/zclconf/go-cty/cty/gocty" -) - -var ElementFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.DynamicPseudoType, - }, - { - Name: "index", - Type: cty.Number, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - list := args[0] - listTy := list.Type() - switch { - case listTy.IsListType(): - return listTy.ElementType(), nil - case listTy.IsTupleType(): - if !args[1].IsKnown() { - // If the index isn't known yet then we can't predict the - // result type since each tuple element can have its own type. - return cty.DynamicPseudoType, nil - } - - etys := listTy.TupleElementTypes() - var index int - err := gocty.FromCtyValue(args[1], &index) - if err != nil { - // e.g. fractional number where whole number is required - return cty.DynamicPseudoType, fmt.Errorf("invalid index: %s", err) - } - if len(etys) == 0 { - return cty.DynamicPseudoType, errors.New("cannot use element function with an empty list") - } - index = index % len(etys) - return etys[index], nil - default: - return cty.DynamicPseudoType, fmt.Errorf("cannot read elements from %s", listTy.FriendlyName()) - } - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - var index int - err := gocty.FromCtyValue(args[1], &index) - if err != nil { - // can't happen because we checked this in the Type function above - return cty.DynamicVal, fmt.Errorf("invalid index: %s", err) - } - - if !args[0].IsKnown() { - return cty.UnknownVal(retType), nil - } - - l := args[0].LengthInt() - if l == 0 { - return cty.DynamicVal, errors.New("cannot use element function with an empty list") - } - index = index % l - - // We did all the necessary type checks in the type function above, - // so this is guaranteed not to fail. - return args[0].Index(cty.NumberIntVal(int64(index))), nil - }, -}) - -var LengthFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "value", - Type: cty.DynamicPseudoType, - AllowDynamicType: true, - AllowUnknown: true, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - collTy := args[0].Type() - switch { - case collTy == cty.String || collTy.IsTupleType() || collTy.IsObjectType() || collTy.IsListType() || collTy.IsMapType() || collTy.IsSetType() || collTy == cty.DynamicPseudoType: - return cty.Number, nil - default: - return cty.Number, errors.New("argument must be a string, a collection type, or a structural type") - } - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - coll := args[0] - collTy := args[0].Type() - switch { - case collTy == cty.DynamicPseudoType: - return cty.UnknownVal(cty.Number), nil - case collTy.IsTupleType(): - l := len(collTy.TupleElementTypes()) - return cty.NumberIntVal(int64(l)), nil - case collTy.IsObjectType(): - l := len(collTy.AttributeTypes()) - return cty.NumberIntVal(int64(l)), nil - case collTy == cty.String: - // We'll delegate to the cty stdlib strlen function here, because - // it deals with all of the complexities of tokenizing unicode - // grapheme clusters. - return stdlib.Strlen(coll) - case collTy.IsListType() || collTy.IsSetType() || collTy.IsMapType(): - return coll.Length(), nil - default: - // Should never happen, because of the checks in our Type func above - return cty.UnknownVal(cty.Number), errors.New("impossible value type for length(...)") - } - }, -}) - -// CoalesceFunc constructs a function that takes any number of arguments and -// returns the first one that isn't empty. This function was copied from go-cty -// stdlib and modified so that it returns the first *non-empty* non-null element -// from a sequence, instead of merely the first non-null. -var CoalesceFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - VarParam: &function.Parameter{ - Name: "vals", - Type: cty.DynamicPseudoType, - AllowUnknown: true, - AllowDynamicType: true, - AllowNull: true, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - argTypes := make([]cty.Type, len(args)) - for i, val := range args { - argTypes[i] = val.Type() - } - retType, _ := convert.UnifyUnsafe(argTypes) - if retType == cty.NilType { - return cty.NilType, errors.New("all arguments must have the same type") - } - return retType, nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - for _, argVal := range args { - // We already know this will succeed because of the checks in our Type func above - argVal, _ = convert.Convert(argVal, retType) - if !argVal.IsKnown() { - return cty.UnknownVal(retType), nil - } - if argVal.IsNull() { - continue - } - if retType == cty.String && argVal.RawEquals(cty.StringVal("")) { - continue - } - - return argVal, nil - } - return cty.NilVal, errors.New("no non-null, non-empty-string arguments") - }, -}) - -// CoalesceListFunc constructs a function that takes any number of list arguments -// and returns the first one that isn't empty. -var CoalesceListFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - VarParam: &function.Parameter{ - Name: "vals", - Type: cty.DynamicPseudoType, - AllowUnknown: true, - AllowDynamicType: true, - AllowNull: true, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - if len(args) == 0 { - return cty.NilType, errors.New("at least one argument is required") - } - - argTypes := make([]cty.Type, len(args)) - - for i, arg := range args { - // if any argument is unknown, we can't be certain know which type we will return - if !arg.IsKnown() { - return cty.DynamicPseudoType, nil - } - ty := arg.Type() - - if !ty.IsListType() && !ty.IsTupleType() { - return cty.NilType, errors.New("coalescelist arguments must be lists or tuples") - } - - argTypes[i] = arg.Type() - } - - last := argTypes[0] - // If there are mixed types, we have to return a dynamic type. - for _, next := range argTypes[1:] { - if !next.Equals(last) { - return cty.DynamicPseudoType, nil - } - } - - return last, nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - for _, arg := range args { - if !arg.IsKnown() { - // If we run into an unknown list at some point, we can't - // predict the final result yet. (If there's a known, non-empty - // arg before this then we won't get here.) - return cty.UnknownVal(retType), nil - } - - if arg.LengthInt() > 0 { - return arg, nil - } - } - - return cty.NilVal, errors.New("no non-null arguments") - }, -}) - -// CompactFunc constructs a function that takes a list of strings and returns a new list -// with any empty string elements removed. -var CompactFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.List(cty.String), - }, - }, - Type: function.StaticReturnType(cty.List(cty.String)), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - listVal := args[0] - if !listVal.IsWhollyKnown() { - // If some of the element values aren't known yet then we - // can't yet return a compacted list - return cty.UnknownVal(retType), nil - } - - var outputList []cty.Value - - for it := listVal.ElementIterator(); it.Next(); { - _, v := it.Element() - if v.IsNull() || v.AsString() == "" { - continue - } - outputList = append(outputList, v) - } - - if len(outputList) == 0 { - return cty.ListValEmpty(cty.String), nil - } - - return cty.ListVal(outputList), nil - }, -}) - -// ContainsFunc constructs a function that determines whether a given list or -// set contains a given single value as one of its elements. -var ContainsFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.DynamicPseudoType, - }, - { - Name: "value", - Type: cty.DynamicPseudoType, - }, - }, - Type: function.StaticReturnType(cty.Bool), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - arg := args[0] - ty := arg.Type() - - if !ty.IsListType() && !ty.IsTupleType() && !ty.IsSetType() { - return cty.NilVal, errors.New("argument must be list, tuple, or set") - } - - _, err = Index(cty.TupleVal(arg.AsValueSlice()), args[1]) - if err != nil { - return cty.False, nil - } - - return cty.True, nil - }, -}) - -// IndexFunc constructs a function that finds the element index for a given value in a list. -var IndexFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.DynamicPseudoType, - }, - { - Name: "value", - Type: cty.DynamicPseudoType, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - if !(args[0].Type().IsListType() || args[0].Type().IsTupleType()) { - return cty.NilVal, errors.New("argument must be a list or tuple") - } - - if !args[0].IsKnown() { - return cty.UnknownVal(cty.Number), nil - } - - if args[0].LengthInt() == 0 { // Easy path - return cty.NilVal, errors.New("cannot search an empty list") - } - - for it := args[0].ElementIterator(); it.Next(); { - i, v := it.Element() - eq, err := stdlib.Equal(v, args[1]) - if err != nil { - return cty.NilVal, err - } - if !eq.IsKnown() { - return cty.UnknownVal(cty.Number), nil - } - if eq.True() { - return i, nil - } - } - return cty.NilVal, errors.New("item not found") - - }, -}) - -// DistinctFunc constructs a function that takes a list and returns a new list -// with any duplicate elements removed. -var DistinctFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.List(cty.DynamicPseudoType), - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - return args[0].Type(), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - listVal := args[0] - - if !listVal.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - var list []cty.Value - - for it := listVal.ElementIterator(); it.Next(); { - _, v := it.Element() - list, err = appendIfMissing(list, v) - if err != nil { - return cty.NilVal, err - } - } - - if len(list) == 0 { - return cty.ListValEmpty(retType.ElementType()), nil - } - return cty.ListVal(list), nil - }, -}) - -// ChunklistFunc constructs a function that splits a single list into fixed-size chunks, -// returning a list of lists. -var ChunklistFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.List(cty.DynamicPseudoType), - }, - { - Name: "size", - Type: cty.Number, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - return cty.List(args[0].Type()), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - listVal := args[0] - if !listVal.IsKnown() { - return cty.UnknownVal(retType), nil - } - - if listVal.LengthInt() == 0 { - return cty.ListValEmpty(listVal.Type()), nil - } - - var size int - err = gocty.FromCtyValue(args[1], &size) - if err != nil { - return cty.NilVal, fmt.Errorf("invalid index: %s", err) - } - - if size < 0 { - return cty.NilVal, errors.New("the size argument must be positive") - } - - output := make([]cty.Value, 0) - - // if size is 0, returns a list made of the initial list - if size == 0 { - output = append(output, listVal) - return cty.ListVal(output), nil - } - - chunk := make([]cty.Value, 0) - - l := args[0].LengthInt() - i := 0 - - for it := listVal.ElementIterator(); it.Next(); { - _, v := it.Element() - chunk = append(chunk, v) - - // Chunk when index isn't 0, or when reaching the values's length - if (i+1)%size == 0 || (i+1) == l { - output = append(output, cty.ListVal(chunk)) - chunk = make([]cty.Value, 0) - } - i++ - } - - return cty.ListVal(output), nil - }, -}) - -// FlattenFunc constructs a function that takes a list and replaces any elements -// that are lists with a flattened sequence of the list contents. -var FlattenFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.DynamicPseudoType, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - if !args[0].IsWhollyKnown() { - return cty.DynamicPseudoType, nil - } - - argTy := args[0].Type() - if !argTy.IsListType() && !argTy.IsSetType() && !argTy.IsTupleType() { - return cty.NilType, errors.New("can only flatten lists, sets and tuples") - } - - retVal, known := flattener(args[0]) - if !known { - return cty.DynamicPseudoType, nil - } - - tys := make([]cty.Type, len(retVal)) - for i, ty := range retVal { - tys[i] = ty.Type() - } - return cty.Tuple(tys), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - inputList := args[0] - if inputList.LengthInt() == 0 { - return cty.EmptyTupleVal, nil - } - - out, known := flattener(inputList) - if !known { - return cty.UnknownVal(retType), nil - } - - return cty.TupleVal(out), nil - }, -}) - -// Flatten until it's not a cty.List, and return whether the value is known. -// We can flatten lists with unknown values, as long as they are not -// lists themselves. -func flattener(flattenList cty.Value) ([]cty.Value, bool) { - out := make([]cty.Value, 0) - for it := flattenList.ElementIterator(); it.Next(); { - _, val := it.Element() - if val.Type().IsListType() || val.Type().IsSetType() || val.Type().IsTupleType() { - if !val.IsKnown() { - return out, false - } - - res, known := flattener(val) - if !known { - return res, known - } - out = append(out, res...) - } else { - out = append(out, val) - } - } - return out, true -} - -// KeysFunc constructs a function that takes a map and returns a sorted list of the map keys. -var KeysFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "inputMap", - Type: cty.DynamicPseudoType, - AllowUnknown: true, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - ty := args[0].Type() - switch { - case ty.IsMapType(): - return cty.List(cty.String), nil - case ty.IsObjectType(): - atys := ty.AttributeTypes() - if len(atys) == 0 { - return cty.EmptyTuple, nil - } - // All of our result elements will be strings, and atys just - // decides how many there are. - etys := make([]cty.Type, len(atys)) - for i := range etys { - etys[i] = cty.String - } - return cty.Tuple(etys), nil - default: - return cty.DynamicPseudoType, function.NewArgErrorf(0, "must have map or object type") - } - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - m := args[0] - var keys []cty.Value - - switch { - case m.Type().IsObjectType(): - // In this case we allow unknown values so we must work only with - // the attribute _types_, not with the value itself. - var names []string - for name := range m.Type().AttributeTypes() { - names = append(names, name) - } - sort.Strings(names) // same ordering guaranteed by cty's ElementIterator - if len(names) == 0 { - return cty.EmptyTupleVal, nil - } - keys = make([]cty.Value, len(names)) - for i, name := range names { - keys[i] = cty.StringVal(name) - } - return cty.TupleVal(keys), nil - default: - if !m.IsKnown() { - return cty.UnknownVal(retType), nil - } - - // cty guarantees that ElementIterator will iterate in lexicographical - // order by key. - for it := args[0].ElementIterator(); it.Next(); { - k, _ := it.Element() - keys = append(keys, k) - } - if len(keys) == 0 { - return cty.ListValEmpty(cty.String), nil - } - return cty.ListVal(keys), nil - } - }, -}) - -// ListFunc constructs a function that takes an arbitrary number of arguments -// and returns a list containing those values in the same order. -// -// This function is deprecated in Terraform v0.12 -var ListFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - VarParam: &function.Parameter{ - Name: "vals", - Type: cty.DynamicPseudoType, - AllowUnknown: true, - AllowDynamicType: true, - AllowNull: true, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - if len(args) == 0 { - return cty.NilType, errors.New("at least one argument is required") - } - - argTypes := make([]cty.Type, len(args)) - - for i, arg := range args { - argTypes[i] = arg.Type() - } - - retType, _ := convert.UnifyUnsafe(argTypes) - if retType == cty.NilType { - return cty.NilType, errors.New("all arguments must have the same type") - } - - return cty.List(retType), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - newList := make([]cty.Value, 0, len(args)) - - for _, arg := range args { - // We already know this will succeed because of the checks in our Type func above - arg, _ = convert.Convert(arg, retType.ElementType()) - newList = append(newList, arg) - } - - return cty.ListVal(newList), nil - }, -}) - -// LookupFunc constructs a function that performs dynamic lookups of map types. -var LookupFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "inputMap", - Type: cty.DynamicPseudoType, - }, - { - Name: "key", - Type: cty.String, - }, - }, - VarParam: &function.Parameter{ - Name: "default", - Type: cty.DynamicPseudoType, - AllowUnknown: true, - AllowDynamicType: true, - AllowNull: true, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - if len(args) < 1 || len(args) > 3 { - return cty.NilType, fmt.Errorf("lookup() takes two or three arguments, got %d", len(args)) - } - - ty := args[0].Type() - - switch { - case ty.IsObjectType(): - if !args[1].IsKnown() { - return cty.DynamicPseudoType, nil - } - - key := args[1].AsString() - if ty.HasAttribute(key) { - return args[0].GetAttr(key).Type(), nil - } else if len(args) == 3 { - // if the key isn't found but a default is provided, - // return the default type - return args[2].Type(), nil - } - return cty.DynamicPseudoType, function.NewArgErrorf(0, "the given object has no attribute %q", key) - case ty.IsMapType(): - if len(args) == 3 { - _, err = convert.Convert(args[2], ty.ElementType()) - if err != nil { - return cty.NilType, function.NewArgErrorf(2, "the default value must have the same type as the map elements") - } - } - return ty.ElementType(), nil - default: - return cty.NilType, function.NewArgErrorf(0, "lookup() requires a map as the first argument") - } - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var defaultVal cty.Value - defaultValueSet := false - - if len(args) == 3 { - defaultVal = args[2] - defaultValueSet = true - } - - mapVar := args[0] - lookupKey := args[1].AsString() - - if !mapVar.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - - if mapVar.Type().IsObjectType() { - if mapVar.Type().HasAttribute(lookupKey) { - return mapVar.GetAttr(lookupKey), nil - } - } else if mapVar.HasIndex(cty.StringVal(lookupKey)) == cty.True { - return mapVar.Index(cty.StringVal(lookupKey)), nil - } - - if defaultValueSet { - defaultVal, err = convert.Convert(defaultVal, retType) - if err != nil { - return cty.NilVal, err - } - return defaultVal, nil - } - - return cty.UnknownVal(cty.DynamicPseudoType), fmt.Errorf( - "lookup failed to find '%s'", lookupKey) - }, -}) - -// MapFunc constructs a function that takes an even number of arguments and -// returns a map whose elements are constructed from consecutive pairs of arguments. -// -// This function is deprecated in Terraform v0.12 -var MapFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - VarParam: &function.Parameter{ - Name: "vals", - Type: cty.DynamicPseudoType, - AllowUnknown: true, - AllowDynamicType: true, - AllowNull: true, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - if len(args) < 2 || len(args)%2 != 0 { - return cty.NilType, fmt.Errorf("map requires an even number of two or more arguments, got %d", len(args)) - } - - argTypes := make([]cty.Type, len(args)/2) - index := 0 - - for i := 0; i < len(args); i += 2 { - argTypes[index] = args[i+1].Type() - index++ - } - - valType, _ := convert.UnifyUnsafe(argTypes) - if valType == cty.NilType { - return cty.NilType, errors.New("all arguments must have the same type") - } - - return cty.Map(valType), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - for _, arg := range args { - if !arg.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - } - - outputMap := make(map[string]cty.Value) - - for i := 0; i < len(args); i += 2 { - - key := args[i].AsString() - - err := gocty.FromCtyValue(args[i], &key) - if err != nil { - return cty.NilVal, err - } - - val := args[i+1] - - var variable cty.Value - err = gocty.FromCtyValue(val, &variable) - if err != nil { - return cty.NilVal, err - } - - // We already know this will succeed because of the checks in our Type func above - variable, _ = convert.Convert(variable, retType.ElementType()) - - // Check for duplicate keys - if _, ok := outputMap[key]; ok { - return cty.NilVal, fmt.Errorf("argument %d is a duplicate key: %q", i+1, key) - } - outputMap[key] = variable - } - - return cty.MapVal(outputMap), nil - }, -}) - -// MatchkeysFunc constructs a function that constructs a new list by taking a -// subset of elements from one list whose indexes match the corresponding -// indexes of values in another list. -var MatchkeysFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "values", - Type: cty.List(cty.DynamicPseudoType), - }, - { - Name: "keys", - Type: cty.List(cty.DynamicPseudoType), - }, - { - Name: "searchset", - Type: cty.List(cty.DynamicPseudoType), - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - ty, _ := convert.UnifyUnsafe([]cty.Type{args[1].Type(), args[2].Type()}) - if ty == cty.NilType { - return cty.NilType, errors.New("keys and searchset must be of the same type") - } - - // the return type is based on args[0] (values) - return args[0].Type(), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - if !args[0].IsKnown() { - return cty.UnknownVal(cty.List(retType.ElementType())), nil - } - - if args[0].LengthInt() != args[1].LengthInt() { - return cty.ListValEmpty(retType.ElementType()), errors.New("length of keys and values should be equal") - } - - output := make([]cty.Value, 0) - values := args[0] - - // Keys and searchset must be the same type. - // We can skip error checking here because we've already verified that - // they can be unified in the Type function - ty, _ := convert.UnifyUnsafe([]cty.Type{args[1].Type(), args[2].Type()}) - keys, _ := convert.Convert(args[1], ty) - searchset, _ := convert.Convert(args[2], ty) - - // if searchset is empty, return an empty list. - if searchset.LengthInt() == 0 { - return cty.ListValEmpty(retType.ElementType()), nil - } - - if !values.IsWhollyKnown() || !keys.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - - i := 0 - for it := keys.ElementIterator(); it.Next(); { - _, key := it.Element() - for iter := searchset.ElementIterator(); iter.Next(); { - _, search := iter.Element() - eq, err := stdlib.Equal(key, search) - if err != nil { - return cty.NilVal, err - } - if !eq.IsKnown() { - return cty.ListValEmpty(retType.ElementType()), nil - } - if eq.True() { - v := values.Index(cty.NumberIntVal(int64(i))) - output = append(output, v) - break - } - } - i++ - } - - // if we haven't matched any key, then output is an empty list. - if len(output) == 0 { - return cty.ListValEmpty(retType.ElementType()), nil - } - return cty.ListVal(output), nil - }, -}) - -// MergeFunc constructs a function that takes an arbitrary number of maps and -// returns a single map that contains a merged set of elements from all of the maps. -// -// If more than one given map defines the same key then the one that is later in -// the argument sequence takes precedence. -var MergeFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - VarParam: &function.Parameter{ - Name: "maps", - Type: cty.DynamicPseudoType, - AllowDynamicType: true, - }, - Type: function.StaticReturnType(cty.DynamicPseudoType), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - outputMap := make(map[string]cty.Value) - - for _, arg := range args { - if !arg.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - if !arg.Type().IsObjectType() && !arg.Type().IsMapType() { - return cty.NilVal, fmt.Errorf("arguments must be maps or objects, got %#v", arg.Type().FriendlyName()) - } - for it := arg.ElementIterator(); it.Next(); { - k, v := it.Element() - outputMap[k.AsString()] = v - } - } - return cty.ObjectVal(outputMap), nil - }, -}) - -// ReverseFunc takes a sequence and produces a new sequence of the same length -// with all of the same elements as the given sequence but in reverse order. -var ReverseFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.DynamicPseudoType, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - argTy := args[0].Type() - switch { - case argTy.IsTupleType(): - argTys := argTy.TupleElementTypes() - retTys := make([]cty.Type, len(argTys)) - for i, ty := range argTys { - retTys[len(retTys)-i-1] = ty - } - return cty.Tuple(retTys), nil - case argTy.IsListType(), argTy.IsSetType(): // We accept sets here to mimic the usual behavior of auto-converting to list - return cty.List(argTy.ElementType()), nil - default: - return cty.NilType, function.NewArgErrorf(0, "can only reverse list or tuple values, not %s", argTy.FriendlyName()) - } - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - in := args[0].AsValueSlice() - outVals := make([]cty.Value, len(in)) - for i, v := range in { - outVals[len(outVals)-i-1] = v - } - switch { - case retType.IsTupleType(): - return cty.TupleVal(outVals), nil - default: - if len(outVals) == 0 { - return cty.ListValEmpty(retType.ElementType()), nil - } - return cty.ListVal(outVals), nil - } - }, -}) - -// SetProductFunc calculates the cartesian product of two or more sets or -// sequences. If the arguments are all lists then the result is a list of tuples, -// preserving the ordering of all of the input lists. Otherwise the result is a -// set of tuples. -var SetProductFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - VarParam: &function.Parameter{ - Name: "sets", - Type: cty.DynamicPseudoType, - }, - Type: func(args []cty.Value) (retType cty.Type, err error) { - if len(args) < 2 { - return cty.NilType, errors.New("at least two arguments are required") - } - - listCount := 0 - elemTys := make([]cty.Type, len(args)) - for i, arg := range args { - aty := arg.Type() - switch { - case aty.IsSetType(): - elemTys[i] = aty.ElementType() - case aty.IsListType(): - elemTys[i] = aty.ElementType() - listCount++ - case aty.IsTupleType(): - // We can accept a tuple type only if there's some common type - // that all of its elements can be converted to. - allEtys := aty.TupleElementTypes() - if len(allEtys) == 0 { - elemTys[i] = cty.DynamicPseudoType - listCount++ - break - } - ety, _ := convert.UnifyUnsafe(allEtys) - if ety == cty.NilType { - return cty.NilType, function.NewArgErrorf(i, "all elements must be of the same type") - } - elemTys[i] = ety - listCount++ - default: - return cty.NilType, function.NewArgErrorf(i, "a set or a list is required") - } - } - - if listCount == len(args) { - return cty.List(cty.Tuple(elemTys)), nil - } - return cty.Set(cty.Tuple(elemTys)), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - ety := retType.ElementType() - - total := 1 - for _, arg := range args { - // Because of our type checking function, we are guaranteed that - // all of the arguments are known, non-null values of types that - // support LengthInt. - total *= arg.LengthInt() - } - - if total == 0 { - // If any of the arguments was an empty collection then our result - // is also an empty collection, which we'll short-circuit here. - if retType.IsListType() { - return cty.ListValEmpty(ety), nil - } - return cty.SetValEmpty(ety), nil - } - - subEtys := ety.TupleElementTypes() - product := make([][]cty.Value, total) - - b := make([]cty.Value, total*len(args)) - n := make([]int, len(args)) - s := 0 - argVals := make([][]cty.Value, len(args)) - for i, arg := range args { - argVals[i] = arg.AsValueSlice() - } - - for i := range product { - e := s + len(args) - pi := b[s:e] - product[i] = pi - s = e - - for j, n := range n { - val := argVals[j][n] - ty := subEtys[j] - if !val.Type().Equals(ty) { - var err error - val, err = convert.Convert(val, ty) - if err != nil { - // Should never happen since we checked this in our - // type-checking function. - return cty.NilVal, fmt.Errorf("failed to convert argVals[%d][%d] to %s; this is a bug in Terraform", j, n, ty.FriendlyName()) - } - } - pi[j] = val - } - - for j := len(n) - 1; j >= 0; j-- { - n[j]++ - if n[j] < len(argVals[j]) { - break - } - n[j] = 0 - } - } - - productVals := make([]cty.Value, total) - for i, vals := range product { - productVals[i] = cty.TupleVal(vals) - } - - if retType.IsListType() { - return cty.ListVal(productVals), nil - } - return cty.SetVal(productVals), nil - }, -}) - -// SliceFunc constructs a function that extracts some consecutive elements -// from within a list. -var SliceFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.DynamicPseudoType, - }, - { - Name: "start_index", - Type: cty.Number, - }, - { - Name: "end_index", - Type: cty.Number, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - arg := args[0] - argTy := arg.Type() - - if argTy.IsSetType() { - return cty.NilType, function.NewArgErrorf(0, "cannot slice a set, because its elements do not have indices; use the tolist function to force conversion to list if the ordering of the result is not important") - } - if !argTy.IsListType() && !argTy.IsTupleType() { - return cty.NilType, function.NewArgErrorf(0, "must be a list or tuple value") - } - - startIndex, endIndex, idxsKnown, err := sliceIndexes(args) - if err != nil { - return cty.NilType, err - } - - if argTy.IsListType() { - return argTy, nil - } - - if !idxsKnown { - // If we don't know our start/end indices then we can't predict - // the result type if we're planning to return a tuple. - return cty.DynamicPseudoType, nil - } - return cty.Tuple(argTy.TupleElementTypes()[startIndex:endIndex]), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - inputList := args[0] - - if retType == cty.DynamicPseudoType { - return cty.DynamicVal, nil - } - - // we ignore idxsKnown return value here because the indices are always - // known here, or else the call would've short-circuited. - startIndex, endIndex, _, err := sliceIndexes(args) - if err != nil { - return cty.NilVal, err - } - - if endIndex-startIndex == 0 { - if retType.IsTupleType() { - return cty.EmptyTupleVal, nil - } - return cty.ListValEmpty(retType.ElementType()), nil - } - - outputList := inputList.AsValueSlice()[startIndex:endIndex] - - if retType.IsTupleType() { - return cty.TupleVal(outputList), nil - } - - return cty.ListVal(outputList), nil - }, -}) - -func sliceIndexes(args []cty.Value) (int, int, bool, error) { - var startIndex, endIndex, length int - var startKnown, endKnown, lengthKnown bool - - if args[0].Type().IsTupleType() || args[0].IsKnown() { // if it's a tuple then we always know the length by the type, but lists must be known - length = args[0].LengthInt() - lengthKnown = true - } - - if args[1].IsKnown() { - if err := gocty.FromCtyValue(args[1], &startIndex); err != nil { - return 0, 0, false, function.NewArgErrorf(1, "invalid start index: %s", err) - } - if startIndex < 0 { - return 0, 0, false, function.NewArgErrorf(1, "start index must not be less than zero") - } - if lengthKnown && startIndex > length { - return 0, 0, false, function.NewArgErrorf(1, "start index must not be greater than the length of the list") - } - startKnown = true - } - if args[2].IsKnown() { - if err := gocty.FromCtyValue(args[2], &endIndex); err != nil { - return 0, 0, false, function.NewArgErrorf(2, "invalid end index: %s", err) - } - if endIndex < 0 { - return 0, 0, false, function.NewArgErrorf(2, "end index must not be less than zero") - } - if lengthKnown && endIndex > length { - return 0, 0, false, function.NewArgErrorf(2, "end index must not be greater than the length of the list") - } - endKnown = true - } - if startKnown && endKnown { - if startIndex > endIndex { - return 0, 0, false, function.NewArgErrorf(1, "start index must not be greater than end index") - } - } - return startIndex, endIndex, startKnown && endKnown, nil -} - -// TransposeFunc contructs a function that takes a map of lists of strings and -// TransposeFunc constructs a function that takes a map of lists of strings and -// swaps the keys and values to produce a new map of lists of strings. -var TransposeFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "values", - Type: cty.Map(cty.List(cty.String)), - }, - }, - Type: function.StaticReturnType(cty.Map(cty.List(cty.String))), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - inputMap := args[0] - if !inputMap.IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - - outputMap := make(map[string]cty.Value) - tmpMap := make(map[string][]string) - - for it := inputMap.ElementIterator(); it.Next(); { - inKey, inVal := it.Element() - for iter := inVal.ElementIterator(); iter.Next(); { - _, val := iter.Element() - if !val.Type().Equals(cty.String) { - return cty.MapValEmpty(cty.List(cty.String)), errors.New("input must be a map of lists of strings") - } - - outKey := val.AsString() - if _, ok := tmpMap[outKey]; !ok { - tmpMap[outKey] = make([]string, 0) - } - outVal := tmpMap[outKey] - outVal = append(outVal, inKey.AsString()) - sort.Strings(outVal) - tmpMap[outKey] = outVal - } - } - - for outKey, outVal := range tmpMap { - values := make([]cty.Value, 0) - for _, v := range outVal { - values = append(values, cty.StringVal(v)) - } - outputMap[outKey] = cty.ListVal(values) - } - - return cty.MapVal(outputMap), nil - }, -}) - -// ValuesFunc constructs a function that returns a list of the map values, -// in the order of the sorted keys. -var ValuesFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "values", - Type: cty.DynamicPseudoType, - }, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - ty := args[0].Type() - if ty.IsMapType() { - return cty.List(ty.ElementType()), nil - } else if ty.IsObjectType() { - // The result is a tuple type with all of the same types as our - // object type's attributes, sorted in lexicographical order by the - // keys. (This matches the sort order guaranteed by ElementIterator - // on a cty object value.) - atys := ty.AttributeTypes() - if len(atys) == 0 { - return cty.EmptyTuple, nil - } - attrNames := make([]string, 0, len(atys)) - for name := range atys { - attrNames = append(attrNames, name) - } - sort.Strings(attrNames) - - tys := make([]cty.Type, len(attrNames)) - for i, name := range attrNames { - tys[i] = atys[name] - } - return cty.Tuple(tys), nil - } - return cty.NilType, errors.New("values() requires a map as the first argument") - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - mapVar := args[0] - - // We can just iterate the map/object value here because cty guarantees - // that these types always iterate in key lexicographical order. - var values []cty.Value - for it := mapVar.ElementIterator(); it.Next(); { - _, val := it.Element() - values = append(values, val) - } - - if retType.IsTupleType() { - return cty.TupleVal(values), nil - } - if len(values) == 0 { - return cty.ListValEmpty(retType.ElementType()), nil - } - return cty.ListVal(values), nil - }, -}) - -// ZipmapFunc constructs a function that constructs a map from a list of keys -// and a corresponding list of values. -var ZipmapFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "keys", - Type: cty.List(cty.String), - }, - { - Name: "values", - Type: cty.DynamicPseudoType, - }, - }, - Type: func(args []cty.Value) (ret cty.Type, err error) { - keys := args[0] - values := args[1] - valuesTy := values.Type() - - switch { - case valuesTy.IsListType(): - return cty.Map(values.Type().ElementType()), nil - case valuesTy.IsTupleType(): - if !keys.IsWhollyKnown() { - // Since zipmap with a tuple produces an object, we need to know - // all of the key names before we can predict our result type. - return cty.DynamicPseudoType, nil - } - - keysRaw := keys.AsValueSlice() - valueTypesRaw := valuesTy.TupleElementTypes() - if len(keysRaw) != len(valueTypesRaw) { - return cty.NilType, fmt.Errorf("number of keys (%d) does not match number of values (%d)", len(keysRaw), len(valueTypesRaw)) - } - atys := make(map[string]cty.Type, len(valueTypesRaw)) - for i, keyVal := range keysRaw { - if keyVal.IsNull() { - return cty.NilType, fmt.Errorf("keys list has null value at index %d", i) - } - key := keyVal.AsString() - atys[key] = valueTypesRaw[i] - } - return cty.Object(atys), nil - - default: - return cty.NilType, errors.New("values argument must be a list or tuple value") - } - }, - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - keys := args[0] - values := args[1] - - if !keys.IsWhollyKnown() { - // Unknown map keys and object attributes are not supported, so - // our entire result must be unknown in this case. - return cty.UnknownVal(retType), nil - } - - // both keys and values are guaranteed to be shallowly-known here, - // because our declared params above don't allow unknown or null values. - if keys.LengthInt() != values.LengthInt() { - return cty.NilVal, fmt.Errorf("number of keys (%d) does not match number of values (%d)", keys.LengthInt(), values.LengthInt()) - } - - output := make(map[string]cty.Value) - - i := 0 - for it := keys.ElementIterator(); it.Next(); { - _, v := it.Element() - val := values.Index(cty.NumberIntVal(int64(i))) - output[v.AsString()] = val - i++ - } - - switch { - case retType.IsMapType(): - if len(output) == 0 { - return cty.MapValEmpty(retType.ElementType()), nil - } - return cty.MapVal(output), nil - case retType.IsObjectType(): - return cty.ObjectVal(output), nil - default: - // Should never happen because the type-check function should've - // caught any other case. - return cty.NilVal, fmt.Errorf("internally selected incorrect result type %s (this is a bug)", retType.FriendlyName()) - } - }, -}) - -// helper function to add an element to a list, if it does not already exist -func appendIfMissing(slice []cty.Value, element cty.Value) ([]cty.Value, error) { - for _, ele := range slice { - eq, err := stdlib.Equal(ele, element) - if err != nil { - return slice, err - } - if eq.True() { - return slice, nil - } - } - return append(slice, element), nil -} - -// Element returns a single element from a given list at the given index. If -// index is greater than the length of the list then it is wrapped modulo -// the list length. -func Element(list, index cty.Value) (cty.Value, error) { - return ElementFunc.Call([]cty.Value{list, index}) -} - -// Length returns the number of elements in the given collection or number of -// Unicode characters in the given string. -func Length(collection cty.Value) (cty.Value, error) { - return LengthFunc.Call([]cty.Value{collection}) -} - -// Coalesce takes any number of arguments and returns the first one that isn't empty. -func Coalesce(args ...cty.Value) (cty.Value, error) { - return CoalesceFunc.Call(args) -} - -// CoalesceList takes any number of list arguments and returns the first one that isn't empty. -func CoalesceList(args ...cty.Value) (cty.Value, error) { - return CoalesceListFunc.Call(args) -} - -// Compact takes a list of strings and returns a new list -// with any empty string elements removed. -func Compact(list cty.Value) (cty.Value, error) { - return CompactFunc.Call([]cty.Value{list}) -} - -// Contains determines whether a given list contains a given single value -// as one of its elements. -func Contains(list, value cty.Value) (cty.Value, error) { - return ContainsFunc.Call([]cty.Value{list, value}) -} - -// Index finds the element index for a given value in a list. -func Index(list, value cty.Value) (cty.Value, error) { - return IndexFunc.Call([]cty.Value{list, value}) -} - -// Distinct takes a list and returns a new list with any duplicate elements removed. -func Distinct(list cty.Value) (cty.Value, error) { - return DistinctFunc.Call([]cty.Value{list}) -} - -// Chunklist splits a single list into fixed-size chunks, returning a list of lists. -func Chunklist(list, size cty.Value) (cty.Value, error) { - return ChunklistFunc.Call([]cty.Value{list, size}) -} - -// Flatten takes a list and replaces any elements that are lists with a flattened -// sequence of the list contents. -func Flatten(list cty.Value) (cty.Value, error) { - return FlattenFunc.Call([]cty.Value{list}) -} - -// Keys takes a map and returns a sorted list of the map keys. -func Keys(inputMap cty.Value) (cty.Value, error) { - return KeysFunc.Call([]cty.Value{inputMap}) -} - -// List takes any number of list arguments and returns a list containing those -// values in the same order. -func List(args ...cty.Value) (cty.Value, error) { - return ListFunc.Call(args) -} - -// Lookup performs a dynamic lookup into a map. -// There are two required arguments, map and key, plus an optional default, -// which is a value to return if no key is found in map. -func Lookup(args ...cty.Value) (cty.Value, error) { - return LookupFunc.Call(args) -} - -// Map takes an even number of arguments and returns a map whose elements are constructed -// from consecutive pairs of arguments. -func Map(args ...cty.Value) (cty.Value, error) { - return MapFunc.Call(args) -} - -// Matchkeys constructs a new list by taking a subset of elements from one list -// whose indexes match the corresponding indexes of values in another list. -func Matchkeys(values, keys, searchset cty.Value) (cty.Value, error) { - return MatchkeysFunc.Call([]cty.Value{values, keys, searchset}) -} - -// Merge takes an arbitrary number of maps and returns a single map that contains -// a merged set of elements from all of the maps. -// -// If more than one given map defines the same key then the one that is later in -// the argument sequence takes precedence. -func Merge(maps ...cty.Value) (cty.Value, error) { - return MergeFunc.Call(maps) -} - -// Reverse takes a sequence and produces a new sequence of the same length -// with all of the same elements as the given sequence but in reverse order. -func Reverse(list cty.Value) (cty.Value, error) { - return ReverseFunc.Call([]cty.Value{list}) -} - -// SetProduct computes the cartesian product of sets or sequences. -func SetProduct(sets ...cty.Value) (cty.Value, error) { - return SetProductFunc.Call(sets) -} - -// Slice extracts some consecutive elements from within a list. -func Slice(list, start, end cty.Value) (cty.Value, error) { - return SliceFunc.Call([]cty.Value{list, start, end}) -} - -// Transpose takes a map of lists of strings and swaps the keys and values to -// produce a new map of lists of strings. -func Transpose(values cty.Value) (cty.Value, error) { - return TransposeFunc.Call([]cty.Value{values}) -} - -// Values returns a list of the map values, in the order of the sorted keys. -// This function only works on flat maps. -func Values(values cty.Value) (cty.Value, error) { - return ValuesFunc.Call([]cty.Value{values}) -} - -// Zipmap constructs a map from a list of keys and a corresponding list of values. -func Zipmap(keys, values cty.Value) (cty.Value, error) { - return ZipmapFunc.Call([]cty.Value{keys, values}) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/conversion.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/conversion.go deleted file mode 100644 index 83f85979722..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/conversion.go +++ /dev/null @@ -1,87 +0,0 @@ -package funcs - -import ( - "strconv" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/function" -) - -// MakeToFunc constructs a "to..." function, like "tostring", which converts -// its argument to a specific type or type kind. -// -// The given type wantTy can be any type constraint that cty's "convert" package -// would accept. In particular, this means that you can pass -// cty.List(cty.DynamicPseudoType) to mean "list of any single type", which -// will then cause cty to attempt to unify all of the element types when given -// a tuple. -func MakeToFunc(wantTy cty.Type) function.Function { - return function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "v", - // We use DynamicPseudoType rather than wantTy here so that - // all values will pass through the function API verbatim and - // we can handle the conversion logic within the Type and - // Impl functions. This allows us to customize the error - // messages to be more appropriate for an explicit type - // conversion, whereas the cty function system produces - // messages aimed at _implicit_ type conversions. - Type: cty.DynamicPseudoType, - AllowNull: true, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - gotTy := args[0].Type() - if gotTy.Equals(wantTy) { - return wantTy, nil - } - conv := convert.GetConversionUnsafe(args[0].Type(), wantTy) - if conv == nil { - // We'll use some specialized errors for some trickier cases, - // but most we can handle in a simple way. - switch { - case gotTy.IsTupleType() && wantTy.IsTupleType(): - return cty.NilType, function.NewArgErrorf(0, "incompatible tuple type for conversion: %s", convert.MismatchMessage(gotTy, wantTy)) - case gotTy.IsObjectType() && wantTy.IsObjectType(): - return cty.NilType, function.NewArgErrorf(0, "incompatible object type for conversion: %s", convert.MismatchMessage(gotTy, wantTy)) - default: - return cty.NilType, function.NewArgErrorf(0, "cannot convert %s to %s", gotTy.FriendlyName(), wantTy.FriendlyNameForConstraint()) - } - } - // If a conversion is available then everything is fine. - return wantTy, nil - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - // We didn't set "AllowUnknown" on our argument, so it is guaranteed - // to be known here but may still be null. - ret, err := convert.Convert(args[0], retType) - if err != nil { - // Because we used GetConversionUnsafe above, conversion can - // still potentially fail in here. For example, if the user - // asks to convert the string "a" to bool then we'll - // optimistically permit it during type checking but fail here - // once we note that the value isn't either "true" or "false". - gotTy := args[0].Type() - switch { - case gotTy == cty.String && wantTy == cty.Bool: - what := "string" - if !args[0].IsNull() { - what = strconv.Quote(args[0].AsString()) - } - return cty.NilVal, function.NewArgErrorf(0, `cannot convert %s to bool; only the strings "true" or "false" are allowed`, what) - case gotTy == cty.String && wantTy == cty.Number: - what := "string" - if !args[0].IsNull() { - what = strconv.Quote(args[0].AsString()) - } - return cty.NilVal, function.NewArgErrorf(0, `cannot convert %s to number; given string must be a decimal representation of a number`, what) - default: - return cty.NilVal, function.NewArgErrorf(0, "cannot convert %s to %s", gotTy.FriendlyName(), wantTy.FriendlyNameForConstraint()) - } - } - return ret, nil - }, - }) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/crypto.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/crypto.go deleted file mode 100644 index 28074fb13eb..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/crypto.go +++ /dev/null @@ -1,325 +0,0 @@ -package funcs - -import ( - "crypto/md5" - "crypto/rsa" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "crypto/x509" - "encoding/base64" - "encoding/hex" - "encoding/pem" - "fmt" - "hash" - - uuidv5 "github.com/google/uuid" - uuid "github.com/hashicorp/go-uuid" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/gocty" - "golang.org/x/crypto/bcrypt" -) - -var UUIDFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - result, err := uuid.GenerateUUID() - if err != nil { - return cty.UnknownVal(cty.String), err - } - return cty.StringVal(result), nil - }, -}) - -var UUIDV5Func = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "namespace", - Type: cty.String, - }, - { - Name: "name", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var namespace uuidv5.UUID - switch { - case args[0].AsString() == "dns": - namespace = uuidv5.NameSpaceDNS - case args[0].AsString() == "url": - namespace = uuidv5.NameSpaceURL - case args[0].AsString() == "oid": - namespace = uuidv5.NameSpaceOID - case args[0].AsString() == "x500": - namespace = uuidv5.NameSpaceX500 - default: - if namespace, err = uuidv5.Parse(args[0].AsString()); err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("uuidv5() doesn't support namespace %s (%v)", args[0].AsString(), err) - } - } - val := args[1].AsString() - return cty.StringVal(uuidv5.NewSHA1(namespace, []byte(val)).String()), nil - }, -}) - -// Base64Sha256Func constructs a function that computes the SHA256 hash of a given string -// and encodes it with Base64. -var Base64Sha256Func = makeStringHashFunction(sha256.New, base64.StdEncoding.EncodeToString) - -// MakeFileBase64Sha256Func constructs a function that is like Base64Sha256Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileBase64Sha256Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, sha256.New, base64.StdEncoding.EncodeToString) -} - -// Base64Sha512Func constructs a function that computes the SHA256 hash of a given string -// and encodes it with Base64. -var Base64Sha512Func = makeStringHashFunction(sha512.New, base64.StdEncoding.EncodeToString) - -// MakeFileBase64Sha512Func constructs a function that is like Base64Sha512Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileBase64Sha512Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, sha512.New, base64.StdEncoding.EncodeToString) -} - -// BcryptFunc constructs a function that computes a hash of the given string using the Blowfish cipher. -var BcryptFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - VarParam: &function.Parameter{ - Name: "cost", - Type: cty.Number, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - defaultCost := 10 - - if len(args) > 1 { - var val int - if err := gocty.FromCtyValue(args[1], &val); err != nil { - return cty.UnknownVal(cty.String), err - } - defaultCost = val - } - - if len(args) > 2 { - return cty.UnknownVal(cty.String), fmt.Errorf("bcrypt() takes no more than two arguments") - } - - input := args[0].AsString() - out, err := bcrypt.GenerateFromPassword([]byte(input), defaultCost) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("error occured generating password %s", err.Error()) - } - - return cty.StringVal(string(out)), nil - }, -}) - -// Md5Func constructs a function that computes the MD5 hash of a given string and encodes it with hexadecimal digits. -var Md5Func = makeStringHashFunction(md5.New, hex.EncodeToString) - -// MakeFileMd5Func constructs a function that is like Md5Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileMd5Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, md5.New, hex.EncodeToString) -} - -// RsaDecryptFunc constructs a function that decrypts an RSA-encrypted ciphertext. -var RsaDecryptFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "ciphertext", - Type: cty.String, - }, - { - Name: "privatekey", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - s := args[0].AsString() - key := args[1].AsString() - - b, err := base64.StdEncoding.DecodeString(s) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to decode input %q: cipher text must be base64-encoded", s) - } - - block, _ := pem.Decode([]byte(key)) - if block == nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to parse key: no key found") - } - if block.Headers["Proc-Type"] == "4,ENCRYPTED" { - return cty.UnknownVal(cty.String), fmt.Errorf( - "failed to parse key: password protected keys are not supported. Please decrypt the key prior to use", - ) - } - - x509Key, err := x509.ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - out, err := rsa.DecryptPKCS1v15(nil, x509Key, b) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.StringVal(string(out)), nil - }, -}) - -// Sha1Func contructs a function that computes the SHA1 hash of a given string -// and encodes it with hexadecimal digits. -var Sha1Func = makeStringHashFunction(sha1.New, hex.EncodeToString) - -// MakeFileSha1Func constructs a function that is like Sha1Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileSha1Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, sha1.New, hex.EncodeToString) -} - -// Sha256Func contructs a function that computes the SHA256 hash of a given string -// and encodes it with hexadecimal digits. -var Sha256Func = makeStringHashFunction(sha256.New, hex.EncodeToString) - -// MakeFileSha256Func constructs a function that is like Sha256Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileSha256Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, sha256.New, hex.EncodeToString) -} - -// Sha512Func contructs a function that computes the SHA512 hash of a given string -// and encodes it with hexadecimal digits. -var Sha512Func = makeStringHashFunction(sha512.New, hex.EncodeToString) - -// MakeFileSha512Func constructs a function that is like Sha512Func but reads the -// contents of a file rather than hashing a given literal string. -func MakeFileSha512Func(baseDir string) function.Function { - return makeFileHashFunction(baseDir, sha512.New, hex.EncodeToString) -} - -func makeStringHashFunction(hf func() hash.Hash, enc func([]byte) string) function.Function { - return function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - s := args[0].AsString() - h := hf() - h.Write([]byte(s)) - rv := enc(h.Sum(nil)) - return cty.StringVal(rv), nil - }, - }) -} - -func makeFileHashFunction(baseDir string, hf func() hash.Hash, enc func([]byte) string) function.Function { - return function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - path := args[0].AsString() - src, err := readFileBytes(baseDir, path) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - h := hf() - h.Write(src) - rv := enc(h.Sum(nil)) - return cty.StringVal(rv), nil - }, - }) -} - -// UUID generates and returns a Type-4 UUID in the standard hexadecimal string -// format. -// -// This is not a pure function: it will generate a different result for each -// call. It must therefore be registered as an impure function in the function -// table in the "lang" package. -func UUID() (cty.Value, error) { - return UUIDFunc.Call(nil) -} - -// UUIDV5 generates and returns a Type-5 UUID in the standard hexadecimal string -// format. -func UUIDV5(namespace cty.Value, name cty.Value) (cty.Value, error) { - return UUIDV5Func.Call([]cty.Value{namespace, name}) -} - -// Base64Sha256 computes the SHA256 hash of a given string and encodes it with -// Base64. -// -// The given string is first encoded as UTF-8 and then the SHA256 algorithm is applied -// as defined in RFC 4634. The raw hash is then encoded with Base64 before returning. -// Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4. -func Base64Sha256(str cty.Value) (cty.Value, error) { - return Base64Sha256Func.Call([]cty.Value{str}) -} - -// Base64Sha512 computes the SHA512 hash of a given string and encodes it with -// Base64. -// -// The given string is first encoded as UTF-8 and then the SHA256 algorithm is applied -// as defined in RFC 4634. The raw hash is then encoded with Base64 before returning. -// Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4 -func Base64Sha512(str cty.Value) (cty.Value, error) { - return Base64Sha512Func.Call([]cty.Value{str}) -} - -// Bcrypt computes a hash of the given string using the Blowfish cipher, -// returning a string in the Modular Crypt Format -// usually expected in the shadow password file on many Unix systems. -func Bcrypt(str cty.Value, cost ...cty.Value) (cty.Value, error) { - args := make([]cty.Value, len(cost)+1) - args[0] = str - copy(args[1:], cost) - return BcryptFunc.Call(args) -} - -// Md5 computes the MD5 hash of a given string and encodes it with hexadecimal digits. -func Md5(str cty.Value) (cty.Value, error) { - return Md5Func.Call([]cty.Value{str}) -} - -// RsaDecrypt decrypts an RSA-encrypted ciphertext, returning the corresponding -// cleartext. -func RsaDecrypt(ciphertext, privatekey cty.Value) (cty.Value, error) { - return RsaDecryptFunc.Call([]cty.Value{ciphertext, privatekey}) -} - -// Sha1 computes the SHA1 hash of a given string and encodes it with hexadecimal digits. -func Sha1(str cty.Value) (cty.Value, error) { - return Sha1Func.Call([]cty.Value{str}) -} - -// Sha256 computes the SHA256 hash of a given string and encodes it with hexadecimal digits. -func Sha256(str cty.Value) (cty.Value, error) { - return Sha256Func.Call([]cty.Value{str}) -} - -// Sha512 computes the SHA512 hash of a given string and encodes it with hexadecimal digits. -func Sha512(str cty.Value) (cty.Value, error) { - return Sha512Func.Call([]cty.Value{str}) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/datetime.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/datetime.go deleted file mode 100644 index 5dae198774a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/datetime.go +++ /dev/null @@ -1,70 +0,0 @@ -package funcs - -import ( - "time" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" -) - -// TimestampFunc constructs a function that returns a string representation of the current date and time. -var TimestampFunc = function.New(&function.Spec{ - Params: []function.Parameter{}, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return cty.StringVal(time.Now().UTC().Format(time.RFC3339)), nil - }, -}) - -// TimeAddFunc constructs a function that adds a duration to a timestamp, returning a new timestamp. -var TimeAddFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "timestamp", - Type: cty.String, - }, - { - Name: "duration", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - ts, err := time.Parse(time.RFC3339, args[0].AsString()) - if err != nil { - return cty.UnknownVal(cty.String), err - } - duration, err := time.ParseDuration(args[1].AsString()) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.StringVal(ts.Add(duration).Format(time.RFC3339)), nil - }, -}) - -// Timestamp returns a string representation of the current date and time. -// -// In the Terraform language, timestamps are conventionally represented as -// strings using RFC 3339 "Date and Time format" syntax, and so timestamp -// returns a string in this format. -func Timestamp() (cty.Value, error) { - return TimestampFunc.Call([]cty.Value{}) -} - -// TimeAdd adds a duration to a timestamp, returning a new timestamp. -// -// In the Terraform language, timestamps are conventionally represented as -// strings using RFC 3339 "Date and Time format" syntax. Timeadd requires -// the timestamp argument to be a string conforming to this syntax. -// -// `duration` is a string representation of a time difference, consisting of -// sequences of number and unit pairs, like `"1.5h"` or `1h30m`. The accepted -// units are `ns`, `us` (or `µs`), `"ms"`, `"s"`, `"m"`, and `"h"`. The first -// number may be negative to indicate a negative duration, like `"-2h5m"`. -// -// The result is a string, also in RFC 3339 format, representing the result -// of adding the given direction to the given timestamp. -func TimeAdd(timestamp cty.Value, duration cty.Value) (cty.Value, error) { - return TimeAddFunc.Call([]cty.Value{timestamp, duration}) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/encoding.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/encoding.go deleted file mode 100644 index af93f08dc1b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/encoding.go +++ /dev/null @@ -1,140 +0,0 @@ -package funcs - -import ( - "bytes" - "compress/gzip" - "encoding/base64" - "fmt" - "log" - "net/url" - "unicode/utf8" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" -) - -// Base64DecodeFunc constructs a function that decodes a string containing a base64 sequence. -var Base64DecodeFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - s := args[0].AsString() - sDec, err := base64.StdEncoding.DecodeString(s) - if err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to decode base64 data '%s'", s) - } - if !utf8.Valid([]byte(sDec)) { - log.Printf("[DEBUG] the result of decoding the the provided string is not valid UTF-8: %s", sDec) - return cty.UnknownVal(cty.String), fmt.Errorf("the result of decoding the the provided string is not valid UTF-8") - } - return cty.StringVal(string(sDec)), nil - }, -}) - -// Base64EncodeFunc constructs a function that encodes a string to a base64 sequence. -var Base64EncodeFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return cty.StringVal(base64.StdEncoding.EncodeToString([]byte(args[0].AsString()))), nil - }, -}) - -// Base64GzipFunc constructs a function that compresses a string with gzip and then encodes the result in -// Base64 encoding. -var Base64GzipFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - s := args[0].AsString() - - var b bytes.Buffer - gz := gzip.NewWriter(&b) - if _, err := gz.Write([]byte(s)); err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to write gzip raw data: '%s'", s) - } - if err := gz.Flush(); err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to flush gzip writer: '%s'", s) - } - if err := gz.Close(); err != nil { - return cty.UnknownVal(cty.String), fmt.Errorf("failed to close gzip writer: '%s'", s) - } - return cty.StringVal(base64.StdEncoding.EncodeToString(b.Bytes())), nil - }, -}) - -// URLEncodeFunc constructs a function that applies URL encoding to a given string. -var URLEncodeFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return cty.StringVal(url.QueryEscape(args[0].AsString())), nil - }, -}) - -// Base64Decode decodes a string containing a base64 sequence. -// -// Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4. -// -// Strings in the Terraform language are sequences of unicode characters rather -// than bytes, so this function will also interpret the resulting bytes as -// UTF-8. If the bytes after Base64 decoding are _not_ valid UTF-8, this function -// produces an error. -func Base64Decode(str cty.Value) (cty.Value, error) { - return Base64DecodeFunc.Call([]cty.Value{str}) -} - -// Base64Encode applies Base64 encoding to a string. -// -// Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4. -// -// Strings in the Terraform language are sequences of unicode characters rather -// than bytes, so this function will first encode the characters from the string -// as UTF-8, and then apply Base64 encoding to the result. -func Base64Encode(str cty.Value) (cty.Value, error) { - return Base64EncodeFunc.Call([]cty.Value{str}) -} - -// Base64Gzip compresses a string with gzip and then encodes the result in -// Base64 encoding. -// -// Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4. -// -// Strings in the Terraform language are sequences of unicode characters rather -// than bytes, so this function will first encode the characters from the string -// as UTF-8, then apply gzip compression, and then finally apply Base64 encoding. -func Base64Gzip(str cty.Value) (cty.Value, error) { - return Base64GzipFunc.Call([]cty.Value{str}) -} - -// URLEncode applies URL encoding to a given string. -// -// This function identifies characters in the given string that would have a -// special meaning when included as a query string argument in a URL and -// escapes them using RFC 3986 "percent encoding". -// -// If the given string contains non-ASCII characters, these are first encoded as -// UTF-8 and then percent encoding is applied separately to each UTF-8 byte. -func URLEncode(str cty.Value) (cty.Value, error) { - return URLEncodeFunc.Call([]cty.Value{str}) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/filesystem.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/filesystem.go deleted file mode 100644 index 786d3e74bc6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/filesystem.go +++ /dev/null @@ -1,360 +0,0 @@ -package funcs - -import ( - "encoding/base64" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "unicode/utf8" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" - homedir "github.com/mitchellh/go-homedir" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" -) - -// MakeFileFunc constructs a function that takes a file path and returns the -// contents of that file, either directly as a string (where valid UTF-8 is -// required) or as a string containing base64 bytes. -func MakeFileFunc(baseDir string, encBase64 bool) function.Function { - return function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - path := args[0].AsString() - src, err := readFileBytes(baseDir, path) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - switch { - case encBase64: - enc := base64.StdEncoding.EncodeToString(src) - return cty.StringVal(enc), nil - default: - if !utf8.Valid(src) { - return cty.UnknownVal(cty.String), fmt.Errorf("contents of %s are not valid UTF-8; use the filebase64 function to obtain the Base64 encoded contents or the other file functions (e.g. filemd5, filesha256) to obtain file hashing results instead", path) - } - return cty.StringVal(string(src)), nil - } - }, - }) -} - -// MakeTemplateFileFunc constructs a function that takes a file path and -// an arbitrary object of named values and attempts to render the referenced -// file as a template using HCL template syntax. -// -// The template itself may recursively call other functions so a callback -// must be provided to get access to those functions. The template cannot, -// however, access any variables defined in the scope: it is restricted only to -// those variables provided in the second function argument, to ensure that all -// dependencies on other graph nodes can be seen before executing this function. -// -// As a special exception, a referenced template file may not recursively call -// the templatefile function, since that would risk the same file being -// included into itself indefinitely. -func MakeTemplateFileFunc(baseDir string, funcsCb func() map[string]function.Function) function.Function { - - params := []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - { - Name: "vars", - Type: cty.DynamicPseudoType, - }, - } - - loadTmpl := func(fn string) (hcl.Expression, error) { - // We re-use File here to ensure the same filename interpretation - // as it does, along with its other safety checks. - tmplVal, err := File(baseDir, cty.StringVal(fn)) - if err != nil { - return nil, err - } - - expr, diags := hclsyntax.ParseTemplate([]byte(tmplVal.AsString()), fn, hcl.Pos{Line: 1, Column: 1}) - if diags.HasErrors() { - return nil, diags - } - - return expr, nil - } - - renderTmpl := func(expr hcl.Expression, varsVal cty.Value) (cty.Value, error) { - if varsTy := varsVal.Type(); !(varsTy.IsMapType() || varsTy.IsObjectType()) { - return cty.DynamicVal, function.NewArgErrorf(1, "invalid vars value: must be a map") // or an object, but we don't strongly distinguish these most of the time - } - - ctx := &hcl.EvalContext{ - Variables: varsVal.AsValueMap(), - } - - // We'll pre-check references in the template here so we can give a - // more specialized error message than HCL would by default, so it's - // clearer that this problem is coming from a templatefile call. - for _, traversal := range expr.Variables() { - root := traversal.RootName() - if _, ok := ctx.Variables[root]; !ok { - return cty.DynamicVal, function.NewArgErrorf(1, "vars map does not contain key %q, referenced at %s", root, traversal[0].SourceRange()) - } - } - - givenFuncs := funcsCb() // this callback indirection is to avoid chicken/egg problems - funcs := make(map[string]function.Function, len(givenFuncs)) - for name, fn := range givenFuncs { - if name == "templatefile" { - // We stub this one out to prevent recursive calls. - funcs[name] = function.New(&function.Spec{ - Params: params, - Type: func(args []cty.Value) (cty.Type, error) { - return cty.NilType, fmt.Errorf("cannot recursively call templatefile from inside templatefile call") - }, - }) - continue - } - funcs[name] = fn - } - ctx.Functions = funcs - - val, diags := expr.Value(ctx) - if diags.HasErrors() { - return cty.DynamicVal, diags - } - return val, nil - } - - return function.New(&function.Spec{ - Params: params, - Type: func(args []cty.Value) (cty.Type, error) { - if !(args[0].IsKnown() && args[1].IsKnown()) { - return cty.DynamicPseudoType, nil - } - - // We'll render our template now to see what result type it produces. - // A template consisting only of a single interpolation an potentially - // return any type. - expr, err := loadTmpl(args[0].AsString()) - if err != nil { - return cty.DynamicPseudoType, err - } - - // This is safe even if args[1] contains unknowns because the HCL - // template renderer itself knows how to short-circuit those. - val, err := renderTmpl(expr, args[1]) - return val.Type(), err - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - expr, err := loadTmpl(args[0].AsString()) - if err != nil { - return cty.DynamicVal, err - } - return renderTmpl(expr, args[1]) - }, - }) - -} - -// MakeFileExistsFunc constructs a function that takes a path -// and determines whether a file exists at that path -func MakeFileExistsFunc(baseDir string) function.Function { - return function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.Bool), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - path := args[0].AsString() - path, err := homedir.Expand(path) - if err != nil { - return cty.UnknownVal(cty.Bool), fmt.Errorf("failed to expand ~: %s", err) - } - - if !filepath.IsAbs(path) { - path = filepath.Join(baseDir, path) - } - - // Ensure that the path is canonical for the host OS - path = filepath.Clean(path) - - fi, err := os.Stat(path) - if err != nil { - if os.IsNotExist(err) { - return cty.False, nil - } - return cty.UnknownVal(cty.Bool), fmt.Errorf("failed to stat %s", path) - } - - if fi.Mode().IsRegular() { - return cty.True, nil - } - - return cty.False, fmt.Errorf("%s is not a regular file, but %q", - path, fi.Mode().String()) - }, - }) -} - -// BasenameFunc constructs a function that takes a string containing a filesystem path -// and removes all except the last portion from it. -var BasenameFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return cty.StringVal(filepath.Base(args[0].AsString())), nil - }, -}) - -// DirnameFunc constructs a function that takes a string containing a filesystem path -// and removes the last portion from it. -var DirnameFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return cty.StringVal(filepath.Dir(args[0].AsString())), nil - }, -}) - -// AbsPathFunc constructs a function that converts a filesystem path to an absolute path -var AbsPathFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - absPath, err := filepath.Abs(args[0].AsString()) - return cty.StringVal(filepath.ToSlash(absPath)), err - }, -}) - -// PathExpandFunc constructs a function that expands a leading ~ character to the current user's home directory. -var PathExpandFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "path", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - - homePath, err := homedir.Expand(args[0].AsString()) - return cty.StringVal(homePath), err - }, -}) - -func readFileBytes(baseDir, path string) ([]byte, error) { - path, err := homedir.Expand(path) - if err != nil { - return nil, fmt.Errorf("failed to expand ~: %s", err) - } - - if !filepath.IsAbs(path) { - path = filepath.Join(baseDir, path) - } - - // Ensure that the path is canonical for the host OS - path = filepath.Clean(path) - - src, err := ioutil.ReadFile(path) - if err != nil { - // ReadFile does not return Terraform-user-friendly error - // messages, so we'll provide our own. - if os.IsNotExist(err) { - return nil, fmt.Errorf("no file exists at %s", path) - } - return nil, fmt.Errorf("failed to read %s", path) - } - - return src, nil -} - -// File reads the contents of the file at the given path. -// -// The file must contain valid UTF-8 bytes, or this function will return an error. -// -// The underlying function implementation works relative to a particular base -// directory, so this wrapper takes a base directory string and uses it to -// construct the underlying function before calling it. -func File(baseDir string, path cty.Value) (cty.Value, error) { - fn := MakeFileFunc(baseDir, false) - return fn.Call([]cty.Value{path}) -} - -// FileExists determines whether a file exists at the given path. -// -// The underlying function implementation works relative to a particular base -// directory, so this wrapper takes a base directory string and uses it to -// construct the underlying function before calling it. -func FileExists(baseDir string, path cty.Value) (cty.Value, error) { - fn := MakeFileExistsFunc(baseDir) - return fn.Call([]cty.Value{path}) -} - -// FileBase64 reads the contents of the file at the given path. -// -// The bytes from the file are encoded as base64 before returning. -// -// The underlying function implementation works relative to a particular base -// directory, so this wrapper takes a base directory string and uses it to -// construct the underlying function before calling it. -func FileBase64(baseDir string, path cty.Value) (cty.Value, error) { - fn := MakeFileFunc(baseDir, true) - return fn.Call([]cty.Value{path}) -} - -// Basename takes a string containing a filesystem path and removes all except the last portion from it. -// -// The underlying function implementation works only with the path string and does not access the filesystem itself. -// It is therefore unable to take into account filesystem features such as symlinks. -// -// If the path is empty then the result is ".", representing the current working directory. -func Basename(path cty.Value) (cty.Value, error) { - return BasenameFunc.Call([]cty.Value{path}) -} - -// Dirname takes a string containing a filesystem path and removes the last portion from it. -// -// The underlying function implementation works only with the path string and does not access the filesystem itself. -// It is therefore unable to take into account filesystem features such as symlinks. -// -// If the path is empty then the result is ".", representing the current working directory. -func Dirname(path cty.Value) (cty.Value, error) { - return DirnameFunc.Call([]cty.Value{path}) -} - -// Pathexpand takes a string that might begin with a `~` segment, and if so it replaces that segment with -// the current user's home directory path. -// -// The underlying function implementation works only with the path string and does not access the filesystem itself. -// It is therefore unable to take into account filesystem features such as symlinks. -// -// If the leading segment in the path is not `~` then the given path is returned unmodified. -func Pathexpand(path cty.Value) (cty.Value, error) { - return PathExpandFunc.Call([]cty.Value{path}) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/number.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/number.go deleted file mode 100644 index c813f47bf67..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/number.go +++ /dev/null @@ -1,217 +0,0 @@ -package funcs - -import ( - "math" - "math/big" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/gocty" -) - -// CeilFunc contructs a function that returns the closest whole number greater -// than or equal to the given value. -var CeilFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "num", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var val float64 - if err := gocty.FromCtyValue(args[0], &val); err != nil { - return cty.UnknownVal(cty.String), err - } - return cty.NumberIntVal(int64(math.Ceil(val))), nil - }, -}) - -// FloorFunc contructs a function that returns the closest whole number lesser -// than or equal to the given value. -var FloorFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "num", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var val float64 - if err := gocty.FromCtyValue(args[0], &val); err != nil { - return cty.UnknownVal(cty.String), err - } - return cty.NumberIntVal(int64(math.Floor(val))), nil - }, -}) - -// LogFunc contructs a function that returns the logarithm of a given number in a given base. -var LogFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "num", - Type: cty.Number, - }, - { - Name: "base", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var num float64 - if err := gocty.FromCtyValue(args[0], &num); err != nil { - return cty.UnknownVal(cty.String), err - } - - var base float64 - if err := gocty.FromCtyValue(args[1], &base); err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.NumberFloatVal(math.Log(num) / math.Log(base)), nil - }, -}) - -// PowFunc contructs a function that returns the logarithm of a given number in a given base. -var PowFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "num", - Type: cty.Number, - }, - { - Name: "power", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var num float64 - if err := gocty.FromCtyValue(args[0], &num); err != nil { - return cty.UnknownVal(cty.String), err - } - - var power float64 - if err := gocty.FromCtyValue(args[1], &power); err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.NumberFloatVal(math.Pow(num, power)), nil - }, -}) - -// SignumFunc contructs a function that returns the closest whole number greater -// than or equal to the given value. -var SignumFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "num", - Type: cty.Number, - }, - }, - Type: function.StaticReturnType(cty.Number), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var num int - if err := gocty.FromCtyValue(args[0], &num); err != nil { - return cty.UnknownVal(cty.String), err - } - switch { - case num < 0: - return cty.NumberIntVal(-1), nil - case num > 0: - return cty.NumberIntVal(+1), nil - default: - return cty.NumberIntVal(0), nil - } - }, -}) - -// ParseIntFunc contructs a function that parses a string argument and returns an integer of the specified base. -var ParseIntFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "number", - Type: cty.DynamicPseudoType, - }, - { - Name: "base", - Type: cty.Number, - }, - }, - - Type: func(args []cty.Value) (cty.Type, error) { - if !args[0].Type().Equals(cty.String) { - return cty.Number, function.NewArgErrorf(0, "first argument must be a string, not %s", args[0].Type().FriendlyName()) - } - return cty.Number, nil - }, - - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - var numstr string - var base int - var err error - - if err = gocty.FromCtyValue(args[0], &numstr); err != nil { - return cty.UnknownVal(cty.String), function.NewArgError(0, err) - } - - if err = gocty.FromCtyValue(args[1], &base); err != nil { - return cty.UnknownVal(cty.Number), function.NewArgError(1, err) - } - - if base < 2 || base > 62 { - return cty.UnknownVal(cty.Number), function.NewArgErrorf( - 1, - "base must be a whole number between 2 and 62 inclusive", - ) - } - - num, ok := (&big.Int{}).SetString(numstr, base) - if !ok { - return cty.UnknownVal(cty.Number), function.NewArgErrorf( - 0, - "cannot parse %q as a base %d integer", - numstr, - base, - ) - } - - parsedNum := cty.NumberVal((&big.Float{}).SetInt(num)) - - return parsedNum, nil - }, -}) - -// Ceil returns the closest whole number greater than or equal to the given value. -func Ceil(num cty.Value) (cty.Value, error) { - return CeilFunc.Call([]cty.Value{num}) -} - -// Floor returns the closest whole number lesser than or equal to the given value. -func Floor(num cty.Value) (cty.Value, error) { - return FloorFunc.Call([]cty.Value{num}) -} - -// Log returns returns the logarithm of a given number in a given base. -func Log(num, base cty.Value) (cty.Value, error) { - return LogFunc.Call([]cty.Value{num, base}) -} - -// Pow returns the logarithm of a given number in a given base. -func Pow(num, power cty.Value) (cty.Value, error) { - return PowFunc.Call([]cty.Value{num, power}) -} - -// Signum determines the sign of a number, returning a number between -1 and -// 1 to represent the sign. -func Signum(num cty.Value) (cty.Value, error) { - return SignumFunc.Call([]cty.Value{num}) -} - -// ParseInt parses a string argument and returns an integer of the specified base. -func ParseInt(num cty.Value, base cty.Value) (cty.Value, error) { - return ParseIntFunc.Call([]cty.Value{num, base}) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/string.go deleted file mode 100644 index c9ddf19e368..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/string.go +++ /dev/null @@ -1,280 +0,0 @@ -package funcs - -import ( - "fmt" - "regexp" - "sort" - "strings" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/gocty" -) - -var JoinFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "separator", - Type: cty.String, - }, - }, - VarParam: &function.Parameter{ - Name: "lists", - Type: cty.List(cty.String), - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - sep := args[0].AsString() - listVals := args[1:] - if len(listVals) < 1 { - return cty.UnknownVal(cty.String), fmt.Errorf("at least one list is required") - } - - l := 0 - for _, list := range listVals { - if !list.IsWhollyKnown() { - return cty.UnknownVal(cty.String), nil - } - l += list.LengthInt() - } - - items := make([]string, 0, l) - for ai, list := range listVals { - ei := 0 - for it := list.ElementIterator(); it.Next(); { - _, val := it.Element() - if val.IsNull() { - if len(listVals) > 1 { - return cty.UnknownVal(cty.String), function.NewArgErrorf(ai+1, "element %d of list %d is null; cannot concatenate null values", ei, ai+1) - } - return cty.UnknownVal(cty.String), function.NewArgErrorf(ai+1, "element %d is null; cannot concatenate null values", ei) - } - items = append(items, val.AsString()) - ei++ - } - } - - return cty.StringVal(strings.Join(items, sep)), nil - }, -}) - -var SortFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "list", - Type: cty.List(cty.String), - }, - }, - Type: function.StaticReturnType(cty.List(cty.String)), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - listVal := args[0] - - if !listVal.IsWhollyKnown() { - // If some of the element values aren't known yet then we - // can't yet preduct the order of the result. - return cty.UnknownVal(retType), nil - } - if listVal.LengthInt() == 0 { // Easy path - return listVal, nil - } - - list := make([]string, 0, listVal.LengthInt()) - for it := listVal.ElementIterator(); it.Next(); { - iv, v := it.Element() - if v.IsNull() { - return cty.UnknownVal(retType), fmt.Errorf("given list element %s is null; a null string cannot be sorted", iv.AsBigFloat().String()) - } - list = append(list, v.AsString()) - } - - sort.Strings(list) - retVals := make([]cty.Value, len(list)) - for i, s := range list { - retVals[i] = cty.StringVal(s) - } - return cty.ListVal(retVals), nil - }, -}) - -var SplitFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "separator", - Type: cty.String, - }, - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.List(cty.String)), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - sep := args[0].AsString() - str := args[1].AsString() - elems := strings.Split(str, sep) - elemVals := make([]cty.Value, len(elems)) - for i, s := range elems { - elemVals[i] = cty.StringVal(s) - } - if len(elemVals) == 0 { - return cty.ListValEmpty(cty.String), nil - } - return cty.ListVal(elemVals), nil - }, -}) - -// ChompFunc constructions a function that removes newline characters at the end of a string. -var ChompFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - newlines := regexp.MustCompile(`(?:\r\n?|\n)*\z`) - return cty.StringVal(newlines.ReplaceAllString(args[0].AsString(), "")), nil - }, -}) - -// IndentFunc constructions a function that adds a given number of spaces to the -// beginnings of all but the first line in a given multi-line string. -var IndentFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "spaces", - Type: cty.Number, - }, - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - var spaces int - if err := gocty.FromCtyValue(args[0], &spaces); err != nil { - return cty.UnknownVal(cty.String), err - } - data := args[1].AsString() - pad := strings.Repeat(" ", spaces) - return cty.StringVal(strings.Replace(data, "\n", "\n"+pad, -1)), nil - }, -}) - -// ReplaceFunc constructions a function that searches a given string for another -// given substring, and replaces each occurence with a given replacement string. -var ReplaceFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - { - Name: "substr", - Type: cty.String, - }, - { - Name: "replace", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - str := args[0].AsString() - substr := args[1].AsString() - replace := args[2].AsString() - - // We search/replace using a regexp if the string is surrounded - // in forward slashes. - if len(substr) > 1 && substr[0] == '/' && substr[len(substr)-1] == '/' { - re, err := regexp.Compile(substr[1 : len(substr)-1]) - if err != nil { - return cty.UnknownVal(cty.String), err - } - - return cty.StringVal(re.ReplaceAllString(str, replace)), nil - } - - return cty.StringVal(strings.Replace(str, substr, replace, -1)), nil - }, -}) - -// TitleFunc constructions a function that converts the first letter of each word -// in the given string to uppercase. -var TitleFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - return cty.StringVal(strings.Title(args[0].AsString())), nil - }, -}) - -// TrimSpaceFunc constructions a function that removes any space characters from -// the start and end of the given string. -var TrimSpaceFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { - return cty.StringVal(strings.TrimSpace(args[0].AsString())), nil - }, -}) - -// Join concatenates together the string elements of one or more lists with a -// given separator. -func Join(sep cty.Value, lists ...cty.Value) (cty.Value, error) { - args := make([]cty.Value, len(lists)+1) - args[0] = sep - copy(args[1:], lists) - return JoinFunc.Call(args) -} - -// Sort re-orders the elements of a given list of strings so that they are -// in ascending lexicographical order. -func Sort(list cty.Value) (cty.Value, error) { - return SortFunc.Call([]cty.Value{list}) -} - -// Split divides a given string by a given separator, returning a list of -// strings containing the characters between the separator sequences. -func Split(sep, str cty.Value) (cty.Value, error) { - return SplitFunc.Call([]cty.Value{sep, str}) -} - -// Chomp removes newline characters at the end of a string. -func Chomp(str cty.Value) (cty.Value, error) { - return ChompFunc.Call([]cty.Value{str}) -} - -// Indent adds a given number of spaces to the beginnings of all but the first -// line in a given multi-line string. -func Indent(spaces, str cty.Value) (cty.Value, error) { - return IndentFunc.Call([]cty.Value{spaces, str}) -} - -// Replace searches a given string for another given substring, -// and replaces all occurences with a given replacement string. -func Replace(str, substr, replace cty.Value) (cty.Value, error) { - return ReplaceFunc.Call([]cty.Value{str, substr, replace}) -} - -// Title converts the first letter of each word in the given string to uppercase. -func Title(str cty.Value) (cty.Value, error) { - return TitleFunc.Call([]cty.Value{str}) -} - -// TrimSpace removes any space characters from the start and end of the given string. -func TrimSpace(str cty.Value) (cty.Value, error) { - return TrimSpaceFunc.Call([]cty.Value{str}) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/functions.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/functions.go deleted file mode 100644 index a3c4906646d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/functions.go +++ /dev/null @@ -1,146 +0,0 @@ -package lang - -import ( - ctyyaml "github.com/zclconf/go-cty-yaml" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" - "github.com/zclconf/go-cty/cty/function/stdlib" - - "github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs" -) - -var impureFunctions = []string{ - "bcrypt", - "timestamp", - "uuid", -} - -// Functions returns the set of functions that should be used to when evaluating -// expressions in the receiving scope. -func (s *Scope) Functions() map[string]function.Function { - s.funcsLock.Lock() - if s.funcs == nil { - // Some of our functions are just directly the cty stdlib functions. - // Others are implemented in the subdirectory "funcs" here in this - // repository. New functions should generally start out their lives - // in the "funcs" directory and potentially graduate to cty stdlib - // later if the functionality seems to be something domain-agnostic - // that would be useful to all applications using cty functions. - - s.funcs = map[string]function.Function{ - "abs": stdlib.AbsoluteFunc, - "abspath": funcs.AbsPathFunc, - "basename": funcs.BasenameFunc, - "base64decode": funcs.Base64DecodeFunc, - "base64encode": funcs.Base64EncodeFunc, - "base64gzip": funcs.Base64GzipFunc, - "base64sha256": funcs.Base64Sha256Func, - "base64sha512": funcs.Base64Sha512Func, - "bcrypt": funcs.BcryptFunc, - "ceil": funcs.CeilFunc, - "chomp": funcs.ChompFunc, - "cidrhost": funcs.CidrHostFunc, - "cidrnetmask": funcs.CidrNetmaskFunc, - "cidrsubnet": funcs.CidrSubnetFunc, - "cidrsubnets": funcs.CidrSubnetsFunc, - "coalesce": funcs.CoalesceFunc, - "coalescelist": funcs.CoalesceListFunc, - "compact": funcs.CompactFunc, - "concat": stdlib.ConcatFunc, - "contains": funcs.ContainsFunc, - "csvdecode": stdlib.CSVDecodeFunc, - "dirname": funcs.DirnameFunc, - "distinct": funcs.DistinctFunc, - "element": funcs.ElementFunc, - "chunklist": funcs.ChunklistFunc, - "file": funcs.MakeFileFunc(s.BaseDir, false), - "fileexists": funcs.MakeFileExistsFunc(s.BaseDir), - "filebase64": funcs.MakeFileFunc(s.BaseDir, true), - "filebase64sha256": funcs.MakeFileBase64Sha256Func(s.BaseDir), - "filebase64sha512": funcs.MakeFileBase64Sha512Func(s.BaseDir), - "filemd5": funcs.MakeFileMd5Func(s.BaseDir), - "filesha1": funcs.MakeFileSha1Func(s.BaseDir), - "filesha256": funcs.MakeFileSha256Func(s.BaseDir), - "filesha512": funcs.MakeFileSha512Func(s.BaseDir), - "flatten": funcs.FlattenFunc, - "floor": funcs.FloorFunc, - "format": stdlib.FormatFunc, - "formatdate": stdlib.FormatDateFunc, - "formatlist": stdlib.FormatListFunc, - "indent": funcs.IndentFunc, - "index": funcs.IndexFunc, - "join": funcs.JoinFunc, - "jsondecode": stdlib.JSONDecodeFunc, - "jsonencode": stdlib.JSONEncodeFunc, - "keys": funcs.KeysFunc, - "length": funcs.LengthFunc, - "list": funcs.ListFunc, - "log": funcs.LogFunc, - "lookup": funcs.LookupFunc, - "lower": stdlib.LowerFunc, - "map": funcs.MapFunc, - "matchkeys": funcs.MatchkeysFunc, - "max": stdlib.MaxFunc, - "md5": funcs.Md5Func, - "merge": funcs.MergeFunc, - "min": stdlib.MinFunc, - "parseint": funcs.ParseIntFunc, - "pathexpand": funcs.PathExpandFunc, - "pow": funcs.PowFunc, - "range": stdlib.RangeFunc, - "regex": stdlib.RegexFunc, - "regexall": stdlib.RegexAllFunc, - "replace": funcs.ReplaceFunc, - "reverse": funcs.ReverseFunc, - "rsadecrypt": funcs.RsaDecryptFunc, - "setintersection": stdlib.SetIntersectionFunc, - "setproduct": funcs.SetProductFunc, - "setunion": stdlib.SetUnionFunc, - "sha1": funcs.Sha1Func, - "sha256": funcs.Sha256Func, - "sha512": funcs.Sha512Func, - "signum": funcs.SignumFunc, - "slice": funcs.SliceFunc, - "sort": funcs.SortFunc, - "split": funcs.SplitFunc, - "strrev": stdlib.ReverseFunc, - "substr": stdlib.SubstrFunc, - "timestamp": funcs.TimestampFunc, - "timeadd": funcs.TimeAddFunc, - "title": funcs.TitleFunc, - "tostring": funcs.MakeToFunc(cty.String), - "tonumber": funcs.MakeToFunc(cty.Number), - "tobool": funcs.MakeToFunc(cty.Bool), - "toset": funcs.MakeToFunc(cty.Set(cty.DynamicPseudoType)), - "tolist": funcs.MakeToFunc(cty.List(cty.DynamicPseudoType)), - "tomap": funcs.MakeToFunc(cty.Map(cty.DynamicPseudoType)), - "transpose": funcs.TransposeFunc, - "trimspace": funcs.TrimSpaceFunc, - "upper": stdlib.UpperFunc, - "urlencode": funcs.URLEncodeFunc, - "uuid": funcs.UUIDFunc, - "uuidv5": funcs.UUIDV5Func, - "values": funcs.ValuesFunc, - "yamldecode": ctyyaml.YAMLDecodeFunc, - "yamlencode": ctyyaml.YAMLEncodeFunc, - "zipmap": funcs.ZipmapFunc, - } - - s.funcs["templatefile"] = funcs.MakeTemplateFileFunc(s.BaseDir, func() map[string]function.Function { - // The templatefile function prevents recursive calls to itself - // by copying this map and overwriting the "templatefile" entry. - return s.funcs - }) - - if s.PureOnly { - // Force our few impure functions to return unknown so that we - // can defer evaluating them until a later pass. - for _, name := range impureFunctions { - s.funcs[name] = function.Unpredictable(s.funcs[name]) - } - } - } - s.funcsLock.Unlock() - - return s.funcs -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/references.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/references.go deleted file mode 100644 index 7923d51135f..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/references.go +++ /dev/null @@ -1,81 +0,0 @@ -package lang - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang/blocktoattr" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// References finds all of the references in the given set of traversals, -// returning diagnostics if any of the traversals cannot be interpreted as a -// reference. -// -// This function does not do any de-duplication of references, since references -// have source location information embedded in them and so any invalid -// references that are duplicated should have errors reported for each -// occurence. -// -// If the returned diagnostics contains errors then the result may be -// incomplete or invalid. Otherwise, the returned slice has one reference per -// given traversal, though it is not guaranteed that the references will -// appear in the same order as the given traversals. -func References(traversals []hcl.Traversal) ([]*addrs.Reference, tfdiags.Diagnostics) { - if len(traversals) == 0 { - return nil, nil - } - - var diags tfdiags.Diagnostics - refs := make([]*addrs.Reference, 0, len(traversals)) - - for _, traversal := range traversals { - ref, refDiags := addrs.ParseRef(traversal) - diags = diags.Append(refDiags) - if ref == nil { - continue - } - refs = append(refs, ref) - } - - return refs, diags -} - -// ReferencesInBlock is a helper wrapper around References that first searches -// the given body for traversals, before converting those traversals to -// references. -// -// A block schema must be provided so that this function can determine where in -// the body variables are expected. -func ReferencesInBlock(body hcl.Body, schema *configschema.Block) ([]*addrs.Reference, tfdiags.Diagnostics) { - if body == nil { - return nil, nil - } - - // We use blocktoattr.ExpandedVariables instead of hcldec.Variables or - // dynblock.VariablesHCLDec here because when we evaluate a block we'll - // first apply the dynamic block extension and _then_ the blocktoattr - // transform, and so blocktoattr.ExpandedVariables takes into account - // both of those transforms when it analyzes the body to ensure we find - // all of the references as if they'd already moved into their final - // locations, even though we can't expand dynamic blocks yet until we - // already know which variables are required. - // - // The set of cases we want to detect here is covered by the tests for - // the plan graph builder in the main 'terraform' package, since it's - // in a better position to test this due to having mock providers etc - // available. - traversals := blocktoattr.ExpandedVariables(body, schema) - return References(traversals) -} - -// ReferencesInExpr is a helper wrapper around References that first searches -// the given expression for traversals, before converting those traversals -// to references. -func ReferencesInExpr(expr hcl.Expression) ([]*addrs.Reference, tfdiags.Diagnostics) { - if expr == nil { - return nil, nil - } - traversals := expr.Variables() - return References(traversals) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/scope.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/scope.go deleted file mode 100644 index a720cca6820..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/scope.go +++ /dev/null @@ -1,34 +0,0 @@ -package lang - -import ( - "sync" - - "github.com/zclconf/go-cty/cty/function" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// Scope is the main type in this package, allowing dynamic evaluation of -// blocks and expressions based on some contextual information that informs -// which variables and functions will be available. -type Scope struct { - // Data is used to resolve references in expressions. - Data Data - - // SelfAddr is the address that the "self" object should be an alias of, - // or nil if the "self" object should not be available at all. - SelfAddr addrs.Referenceable - - // BaseDir is the base directory used by any interpolation functions that - // accept filesystem paths as arguments. - BaseDir string - - // PureOnly can be set to true to request that any non-pure functions - // produce unknown value results rather than actually executing. This is - // important during a plan phase to avoid generating results that could - // then differ during apply. - PureOnly bool - - funcs map[string]function.Function - funcsLock sync.Mutex -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/doc.go deleted file mode 100644 index 0d7d664fc1f..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package modsdir is an internal package containing the model types used to -// represent the manifest of modules in a local modules cache directory. -package modsdir diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/manifest.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/manifest.go deleted file mode 100644 index 2d45c8520ee..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/manifest.go +++ /dev/null @@ -1,138 +0,0 @@ -package modsdir - -import ( - "encoding/json" - "fmt" - "io" - "io/ioutil" - "log" - "os" - "path/filepath" - - version "github.com/hashicorp/go-version" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// Record represents some metadata about an installed module, as part -// of a ModuleManifest. -type Record struct { - // Key is a unique identifier for this particular module, based on its - // position within the static module tree. - Key string `json:"Key"` - - // SourceAddr is the source address given for this module in configuration. - // This is used only to detect if the source was changed in configuration - // since the module was last installed, which means that the installer - // must re-install it. - SourceAddr string `json:"Source"` - - // Version is the exact version of the module, which results from parsing - // VersionStr. nil for un-versioned modules. - Version *version.Version `json:"-"` - - // VersionStr is the version specifier string. This is used only for - // serialization in snapshots and should not be accessed or updated - // by any other codepaths; use "Version" instead. - VersionStr string `json:"Version,omitempty"` - - // Dir is the path to the local directory where the module is installed. - Dir string `json:"Dir"` -} - -// Manifest is a map used to keep track of the filesystem locations -// and other metadata about installed modules. -// -// The configuration loader refers to this, while the module installer updates -// it to reflect any changes to the installed modules. -type Manifest map[string]Record - -func (m Manifest) ModuleKey(path addrs.Module) string { - return path.String() -} - -// manifestSnapshotFile is an internal struct used only to assist in our JSON -// serialization of manifest snapshots. It should not be used for any other -// purpose. -type manifestSnapshotFile struct { - Records []Record `json:"Modules"` -} - -func ReadManifestSnapshot(r io.Reader) (Manifest, error) { - src, err := ioutil.ReadAll(r) - if err != nil { - return nil, err - } - - if len(src) == 0 { - // This should never happen, but we'll tolerate it as if it were - // a valid empty JSON object. - return make(Manifest), nil - } - - var read manifestSnapshotFile - err = json.Unmarshal(src, &read) - - new := make(Manifest) - for _, record := range read.Records { - if record.VersionStr != "" { - record.Version, err = version.NewVersion(record.VersionStr) - if err != nil { - return nil, fmt.Errorf("invalid version %q for %s: %s", record.VersionStr, record.Key, err) - } - } - if _, exists := new[record.Key]; exists { - // This should never happen in any valid file, so we'll catch it - // and report it to avoid confusing/undefined behavior if the - // snapshot file was edited incorrectly outside of Terraform. - return nil, fmt.Errorf("snapshot file contains two records for path %s", record.Key) - } - new[record.Key] = record - } - return new, nil -} - -func ReadManifestSnapshotForDir(dir string) (Manifest, error) { - fn := filepath.Join(dir, ManifestSnapshotFilename) - r, err := os.Open(fn) - if err != nil { - if os.IsNotExist(err) { - return make(Manifest), nil // missing file is okay and treated as empty - } - return nil, err - } - return ReadManifestSnapshot(r) -} - -func (m Manifest) WriteSnapshot(w io.Writer) error { - var write manifestSnapshotFile - - for _, record := range m { - // Make sure VersionStr is in sync with Version, since we encourage - // callers to manipulate Version and ignore VersionStr. - if record.Version != nil { - record.VersionStr = record.Version.String() - } else { - record.VersionStr = "" - } - write.Records = append(write.Records, record) - } - - src, err := json.Marshal(write) - if err != nil { - return err - } - - _, err = w.Write(src) - return err -} - -func (m Manifest) WriteSnapshotToDir(dir string) error { - fn := filepath.Join(dir, ManifestSnapshotFilename) - log.Printf("[TRACE] modsdir: writing modules manifest to %s", fn) - w, err := os.Create(fn) - if err != nil { - return err - } - return m.WriteSnapshot(w) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/paths.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/paths.go deleted file mode 100644 index 9ebb52431ba..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/paths.go +++ /dev/null @@ -1,3 +0,0 @@ -package modsdir - -const ManifestSnapshotFilename = "modules.json" diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/dependencies.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/dependencies.go deleted file mode 100644 index c8058871845..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/dependencies.go +++ /dev/null @@ -1,43 +0,0 @@ -package moduledeps - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery" -) - -// Providers describes a set of provider dependencies for a given module. -// -// Each named provider instance can have one version constraint. -type Providers map[ProviderInstance]ProviderDependency - -// ProviderDependency describes the dependency for a particular provider -// instance, including both the set of allowed versions and the reason for -// the dependency. -type ProviderDependency struct { - Constraints discovery.Constraints - Reason ProviderDependencyReason -} - -// ProviderDependencyReason is an enumeration of reasons why a dependency might be -// present. -type ProviderDependencyReason int - -const ( - // ProviderDependencyExplicit means that there is an explicit "provider" - // block in the configuration for this module. - ProviderDependencyExplicit ProviderDependencyReason = iota - - // ProviderDependencyImplicit means that there is no explicit "provider" - // block but there is at least one resource that uses this provider. - ProviderDependencyImplicit - - // ProviderDependencyInherited is a special case of - // ProviderDependencyImplicit where a parent module has defined a - // configuration for the provider that has been inherited by at least one - // resource in this module. - ProviderDependencyInherited - - // ProviderDependencyFromState means that this provider is not currently - // referenced by configuration at all, but some existing instances in - // the state still depend on it. - ProviderDependencyFromState -) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/doc.go deleted file mode 100644 index 7eff083157d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/doc.go +++ /dev/null @@ -1,7 +0,0 @@ -// Package moduledeps contains types that can be used to describe the -// providers required for all of the modules in a module tree. -// -// It does not itself contain the functionality for populating such -// data structures; that's in Terraform core, since this package intentionally -// does not depend on terraform core to avoid package dependency cycles. -package moduledeps diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/module.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/module.go deleted file mode 100644 index 5189acfc1c4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/module.go +++ /dev/null @@ -1,134 +0,0 @@ -package moduledeps - -import ( - "sort" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery" -) - -// Module represents the dependencies of a single module, as well being -// a node in a tree of such structures representing the dependencies of -// an entire configuration. -type Module struct { - Name string - Providers Providers - Children []*Module -} - -// WalkFunc is a callback type for use with Module.WalkTree -type WalkFunc func(path []string, parent *Module, current *Module) error - -// WalkTree calls the given callback once for the receiver and then -// once for each descendent, in an order such that parents are called -// before their children and siblings are called in the order they -// appear in the Children slice. -// -// When calling the callback, parent will be nil for the first call -// for the receiving module, and then set to the direct parent of -// each module for the subsequent calls. -// -// The path given to the callback is valid only until the callback -// returns, after which it will be mutated and reused. Callbacks must -// therefore copy the path slice if they wish to retain it. -// -// If the given callback returns an error, the walk will be aborted at -// that point and that error returned to the caller. -// -// This function is not thread-safe for concurrent modifications of the -// data structure, so it's the caller's responsibility to arrange for that -// should it be needed. -// -// It is safe for a callback to modify the descendents of the "current" -// module, including the ordering of the Children slice itself, but the -// callback MUST NOT modify the parent module. -func (m *Module) WalkTree(cb WalkFunc) error { - return walkModuleTree(make([]string, 0, 1), nil, m, cb) -} - -func walkModuleTree(path []string, parent *Module, current *Module, cb WalkFunc) error { - path = append(path, current.Name) - err := cb(path, parent, current) - if err != nil { - return err - } - - for _, child := range current.Children { - err := walkModuleTree(path, current, child, cb) - if err != nil { - return err - } - } - return nil -} - -// SortChildren sorts the Children slice into lexicographic order by -// name, in-place. -// -// This is primarily useful prior to calling WalkTree so that the walk -// will proceed in a consistent order. -func (m *Module) SortChildren() { - sort.Sort(sortModules{m.Children}) -} - -type sortModules struct { - modules []*Module -} - -func (s sortModules) Len() int { - return len(s.modules) -} - -func (s sortModules) Less(i, j int) bool { - cmp := strings.Compare(s.modules[i].Name, s.modules[j].Name) - return cmp < 0 -} - -func (s sortModules) Swap(i, j int) { - s.modules[i], s.modules[j] = s.modules[j], s.modules[i] -} - -// PluginRequirements produces a PluginRequirements structure that can -// be used with discovery.PluginMetaSet.ConstrainVersions to identify -// suitable plugins to satisfy the module's provider dependencies. -// -// This method only considers the direct requirements of the receiver. -// Use AllPluginRequirements to flatten the dependencies for the -// entire tree of modules. -// -// Requirements returned by this method include only version constraints, -// and apply no particular SHA256 hash constraint. -func (m *Module) PluginRequirements() discovery.PluginRequirements { - ret := make(discovery.PluginRequirements) - for inst, dep := range m.Providers { - // m.Providers is keyed on provider names, such as "aws.foo". - // a PluginRequirements wants keys to be provider *types*, such - // as "aws". If there are multiple aliases for the same - // provider then we will flatten them into a single requirement - // by combining their constraint sets. - pty := inst.Type() - if existing, exists := ret[pty]; exists { - ret[pty].Versions = existing.Versions.Append(dep.Constraints) - } else { - ret[pty] = &discovery.PluginConstraints{ - Versions: dep.Constraints, - } - } - } - return ret -} - -// AllPluginRequirements calls PluginRequirements for the receiver and all -// of its descendents, and merges the result into a single PluginRequirements -// structure that would satisfy all of the modules together. -// -// Requirements returned by this method include only version constraints, -// and apply no particular SHA256 hash constraint. -func (m *Module) AllPluginRequirements() discovery.PluginRequirements { - var ret discovery.PluginRequirements - m.WalkTree(func(path []string, parent *Module, current *Module) error { - ret = ret.Merge(current.PluginRequirements()) - return nil - }) - return ret -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/provider.go deleted file mode 100644 index 89ceefb2cf0..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps/provider.go +++ /dev/null @@ -1,30 +0,0 @@ -package moduledeps - -import ( - "strings" -) - -// ProviderInstance describes a particular provider instance by its full name, -// like "null" or "aws.foo". -type ProviderInstance string - -// Type returns the provider type of this instance. For example, for an instance -// named "aws.foo" the type is "aws". -func (p ProviderInstance) Type() string { - t := string(p) - if dotPos := strings.Index(t, "."); dotPos != -1 { - t = t[:dotPos] - } - return t -} - -// Alias returns the alias of this provider, if any. An instance named "aws.foo" -// has the alias "foo", while an instance named just "docker" has no alias, -// so the empty string would be returned. -func (p ProviderInstance) Alias() string { - t := string(p) - if dotPos := strings.Index(t, "."); dotPos != -1 { - return t[dotPos+1:] - } - return "" -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/action.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/action.go deleted file mode 100644 index c653b106b3a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/action.go +++ /dev/null @@ -1,22 +0,0 @@ -package plans - -type Action rune - -const ( - NoOp Action = 0 - Create Action = '+' - Read Action = '←' - Update Action = '~' - DeleteThenCreate Action = '∓' - CreateThenDelete Action = '±' - Delete Action = '-' -) - -//go:generate go run golang.org/x/tools/cmd/stringer -type Action - -// IsReplace returns true if the action is one of the two actions that -// represents replacing an existing object with a new object: -// DeleteThenCreate or CreateThenDelete. -func (a Action) IsReplace() bool { - return a == DeleteThenCreate || a == CreateThenDelete -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/action_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/action_string.go deleted file mode 100644 index be43ab1757b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/action_string.go +++ /dev/null @@ -1,49 +0,0 @@ -// Code generated by "stringer -type Action"; DO NOT EDIT. - -package plans - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[NoOp-0] - _ = x[Create-43] - _ = x[Read-8592] - _ = x[Update-126] - _ = x[DeleteThenCreate-8723] - _ = x[CreateThenDelete-177] - _ = x[Delete-45] -} - -const ( - _Action_name_0 = "NoOp" - _Action_name_1 = "Create" - _Action_name_2 = "Delete" - _Action_name_3 = "Update" - _Action_name_4 = "CreateThenDelete" - _Action_name_5 = "Read" - _Action_name_6 = "DeleteThenCreate" -) - -func (i Action) String() string { - switch { - case i == 0: - return _Action_name_0 - case i == 43: - return _Action_name_1 - case i == 45: - return _Action_name_2 - case i == 126: - return _Action_name_3 - case i == 177: - return _Action_name_4 - case i == 8592: - return _Action_name_5 - case i == 8723: - return _Action_name_6 - default: - return "Action(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/changes.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/changes.go deleted file mode 100644 index 5c2028c832a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/changes.go +++ /dev/null @@ -1,308 +0,0 @@ -package plans - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/zclconf/go-cty/cty" -) - -// Changes describes various actions that Terraform will attempt to take if -// the corresponding plan is applied. -// -// A Changes object can be rendered into a visual diff (by the caller, using -// code in another package) for display to the user. -type Changes struct { - // Resources tracks planned changes to resource instance objects. - Resources []*ResourceInstanceChangeSrc - - // Outputs tracks planned changes output values. - // - // Note that although an in-memory plan contains planned changes for - // outputs throughout the configuration, a plan serialized - // to disk retains only the root outputs because they are - // externally-visible, while other outputs are implementation details and - // can be easily re-calculated during the apply phase. Therefore only root - // module outputs will survive a round-trip through a plan file. - Outputs []*OutputChangeSrc -} - -// NewChanges returns a valid Changes object that describes no changes. -func NewChanges() *Changes { - return &Changes{} -} - -func (c *Changes) Empty() bool { - for _, res := range c.Resources { - if res.Action != NoOp { - return false - } - } - return true -} - -// ResourceInstance returns the planned change for the current object of the -// resource instance of the given address, if any. Returns nil if no change is -// planned. -func (c *Changes) ResourceInstance(addr addrs.AbsResourceInstance) *ResourceInstanceChangeSrc { - addrStr := addr.String() - for _, rc := range c.Resources { - if rc.Addr.String() == addrStr && rc.DeposedKey == states.NotDeposed { - return rc - } - } - - return nil -} - -// ResourceInstanceDeposed returns the plan change of a deposed object of -// the resource instance of the given address, if any. Returns nil if no change -// is planned. -func (c *Changes) ResourceInstanceDeposed(addr addrs.AbsResourceInstance, key states.DeposedKey) *ResourceInstanceChangeSrc { - addrStr := addr.String() - for _, rc := range c.Resources { - if rc.Addr.String() == addrStr && rc.DeposedKey == key { - return rc - } - } - - return nil -} - -// OutputValue returns the planned change for the output value with the -// given address, if any. Returns nil if no change is planned. -func (c *Changes) OutputValue(addr addrs.AbsOutputValue) *OutputChangeSrc { - addrStr := addr.String() - for _, oc := range c.Outputs { - if oc.Addr.String() == addrStr { - return oc - } - } - - return nil -} - -// SyncWrapper returns a wrapper object around the receiver that can be used -// to make certain changes to the receiver in a concurrency-safe way, as long -// as all callers share the same wrapper object. -func (c *Changes) SyncWrapper() *ChangesSync { - return &ChangesSync{ - changes: c, - } -} - -// ResourceInstanceChange describes a change to a particular resource instance -// object. -type ResourceInstanceChange struct { - // Addr is the absolute address of the resource instance that the change - // will apply to. - Addr addrs.AbsResourceInstance - - // DeposedKey is the identifier for a deposed object associated with the - // given instance, or states.NotDeposed if this change applies to the - // current object. - // - // A Replace change for a resource with create_before_destroy set will - // create a new DeposedKey temporarily during replacement. In that case, - // DeposedKey in the plan is always states.NotDeposed, representing that - // the current object is being replaced with the deposed. - DeposedKey states.DeposedKey - - // Provider is the address of the provider configuration that was used - // to plan this change, and thus the configuration that must also be - // used to apply it. - ProviderAddr addrs.AbsProviderConfig - - // Change is an embedded description of the change. - Change - - // RequiredReplace is a set of paths that caused the change action to be - // Replace rather than Update. Always nil if the change action is not - // Replace. - // - // This is retained only for UI-plan-rendering purposes and so it does not - // currently survive a round-trip through a saved plan file. - RequiredReplace cty.PathSet - - // Private allows a provider to stash any extra data that is opaque to - // Terraform that relates to this change. Terraform will save this - // byte-for-byte and return it to the provider in the apply call. - Private []byte -} - -// Encode produces a variant of the reciever that has its change values -// serialized so it can be written to a plan file. Pass the implied type of the -// corresponding resource type schema for correct operation. -func (rc *ResourceInstanceChange) Encode(ty cty.Type) (*ResourceInstanceChangeSrc, error) { - cs, err := rc.Change.Encode(ty) - if err != nil { - return nil, err - } - return &ResourceInstanceChangeSrc{ - Addr: rc.Addr, - DeposedKey: rc.DeposedKey, - ProviderAddr: rc.ProviderAddr, - ChangeSrc: *cs, - RequiredReplace: rc.RequiredReplace, - Private: rc.Private, - }, err -} - -// Simplify will, where possible, produce a change with a simpler action than -// the receiever given a flag indicating whether the caller is dealing with -// a normal apply or a destroy. This flag deals with the fact that Terraform -// Core uses a specialized graph node type for destroying; only that -// specialized node should set "destroying" to true. -// -// The following table shows the simplification behavior: -// -// Action Destroying? New Action -// --------+-------------+----------- -// Create true NoOp -// Delete false NoOp -// Replace true Delete -// Replace false Create -// -// For any combination not in the above table, the Simplify just returns the -// receiver as-is. -func (rc *ResourceInstanceChange) Simplify(destroying bool) *ResourceInstanceChange { - if destroying { - switch rc.Action { - case Delete: - // We'll fall out and just return rc verbatim, then. - case CreateThenDelete, DeleteThenCreate: - return &ResourceInstanceChange{ - Addr: rc.Addr, - DeposedKey: rc.DeposedKey, - Private: rc.Private, - ProviderAddr: rc.ProviderAddr, - Change: Change{ - Action: Delete, - Before: rc.Before, - After: cty.NullVal(rc.Before.Type()), - }, - } - default: - return &ResourceInstanceChange{ - Addr: rc.Addr, - DeposedKey: rc.DeposedKey, - Private: rc.Private, - ProviderAddr: rc.ProviderAddr, - Change: Change{ - Action: NoOp, - Before: rc.Before, - After: rc.Before, - }, - } - } - } else { - switch rc.Action { - case Delete: - return &ResourceInstanceChange{ - Addr: rc.Addr, - DeposedKey: rc.DeposedKey, - Private: rc.Private, - ProviderAddr: rc.ProviderAddr, - Change: Change{ - Action: NoOp, - Before: rc.Before, - After: rc.Before, - }, - } - case CreateThenDelete, DeleteThenCreate: - return &ResourceInstanceChange{ - Addr: rc.Addr, - DeposedKey: rc.DeposedKey, - Private: rc.Private, - ProviderAddr: rc.ProviderAddr, - Change: Change{ - Action: Create, - Before: cty.NullVal(rc.After.Type()), - After: rc.After, - }, - } - } - } - - // If we fall out here then our change is already simple enough. - return rc -} - -// OutputChange describes a change to an output value. -type OutputChange struct { - // Addr is the absolute address of the output value that the change - // will apply to. - Addr addrs.AbsOutputValue - - // Change is an embedded description of the change. - // - // For output value changes, the type constraint for the DynamicValue - // instances is always cty.DynamicPseudoType. - Change - - // Sensitive, if true, indicates that either the old or new value in the - // change is sensitive and so a rendered version of the plan in the UI - // should elide the actual values while still indicating the action of the - // change. - Sensitive bool -} - -// Encode produces a variant of the reciever that has its change values -// serialized so it can be written to a plan file. -func (oc *OutputChange) Encode() (*OutputChangeSrc, error) { - cs, err := oc.Change.Encode(cty.DynamicPseudoType) - if err != nil { - return nil, err - } - return &OutputChangeSrc{ - Addr: oc.Addr, - ChangeSrc: *cs, - Sensitive: oc.Sensitive, - }, err -} - -// Change describes a single change with a given action. -type Change struct { - // Action defines what kind of change is being made. - Action Action - - // Interpretation of Before and After depend on Action: - // - // NoOp Before and After are the same, unchanged value - // Create Before is nil, and After is the expected value after create. - // Read Before is any prior value (nil if no prior), and After is the - // value that was or will be read. - // Update Before is the value prior to update, and After is the expected - // value after update. - // Replace As with Update. - // Delete Before is the value prior to delete, and After is always nil. - // - // Unknown values may appear anywhere within the Before and After values, - // either as the values themselves or as nested elements within known - // collections/structures. - Before, After cty.Value -} - -// Encode produces a variant of the reciever that has its change values -// serialized so it can be written to a plan file. Pass the type constraint -// that the values are expected to conform to; to properly decode the values -// later an identical type constraint must be provided at that time. -// -// Where a Change is embedded in some other struct, it's generally better -// to call the corresponding Encode method of that struct rather than working -// directly with its embedded Change. -func (c *Change) Encode(ty cty.Type) (*ChangeSrc, error) { - beforeDV, err := NewDynamicValue(c.Before, ty) - if err != nil { - return nil, err - } - afterDV, err := NewDynamicValue(c.After, ty) - if err != nil { - return nil, err - } - - return &ChangeSrc{ - Action: c.Action, - Before: beforeDV, - After: afterDV, - }, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/changes_src.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/changes_src.go deleted file mode 100644 index 97bc8da7c48..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/changes_src.go +++ /dev/null @@ -1,190 +0,0 @@ -package plans - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/zclconf/go-cty/cty" -) - -// ResourceInstanceChangeSrc is a not-yet-decoded ResourceInstanceChange. -// Pass the associated resource type's schema type to method Decode to -// obtain a ResourceInstancChange. -type ResourceInstanceChangeSrc struct { - // Addr is the absolute address of the resource instance that the change - // will apply to. - Addr addrs.AbsResourceInstance - - // DeposedKey is the identifier for a deposed object associated with the - // given instance, or states.NotDeposed if this change applies to the - // current object. - // - // A Replace change for a resource with create_before_destroy set will - // create a new DeposedKey temporarily during replacement. In that case, - // DeposedKey in the plan is always states.NotDeposed, representing that - // the current object is being replaced with the deposed. - DeposedKey states.DeposedKey - - // Provider is the address of the provider configuration that was used - // to plan this change, and thus the configuration that must also be - // used to apply it. - ProviderAddr addrs.AbsProviderConfig - - // ChangeSrc is an embedded description of the not-yet-decoded change. - ChangeSrc - - // RequiredReplace is a set of paths that caused the change action to be - // Replace rather than Update. Always nil if the change action is not - // Replace. - // - // This is retained only for UI-plan-rendering purposes and so it does not - // currently survive a round-trip through a saved plan file. - RequiredReplace cty.PathSet - - // Private allows a provider to stash any extra data that is opaque to - // Terraform that relates to this change. Terraform will save this - // byte-for-byte and return it to the provider in the apply call. - Private []byte -} - -// Decode unmarshals the raw representation of the instance object being -// changed. Pass the implied type of the corresponding resource type schema -// for correct operation. -func (rcs *ResourceInstanceChangeSrc) Decode(ty cty.Type) (*ResourceInstanceChange, error) { - change, err := rcs.ChangeSrc.Decode(ty) - if err != nil { - return nil, err - } - return &ResourceInstanceChange{ - Addr: rcs.Addr, - DeposedKey: rcs.DeposedKey, - ProviderAddr: rcs.ProviderAddr, - Change: *change, - RequiredReplace: rcs.RequiredReplace, - Private: rcs.Private, - }, nil -} - -// DeepCopy creates a copy of the receiver where any pointers to nested mutable -// values are also copied, thus ensuring that future mutations of the receiver -// will not affect the copy. -// -// Some types used within a resource change are immutable by convention even -// though the Go language allows them to be mutated, such as the types from -// the addrs package. These are _not_ copied by this method, under the -// assumption that callers will behave themselves. -func (rcs *ResourceInstanceChangeSrc) DeepCopy() *ResourceInstanceChangeSrc { - if rcs == nil { - return nil - } - ret := *rcs - - ret.RequiredReplace = cty.NewPathSet(ret.RequiredReplace.List()...) - - if len(ret.Private) != 0 { - private := make([]byte, len(ret.Private)) - copy(private, ret.Private) - ret.Private = private - } - - ret.ChangeSrc.Before = ret.ChangeSrc.Before.Copy() - ret.ChangeSrc.After = ret.ChangeSrc.After.Copy() - - return &ret -} - -// OutputChangeSrc describes a change to an output value. -type OutputChangeSrc struct { - // Addr is the absolute address of the output value that the change - // will apply to. - Addr addrs.AbsOutputValue - - // ChangeSrc is an embedded description of the not-yet-decoded change. - // - // For output value changes, the type constraint for the DynamicValue - // instances is always cty.DynamicPseudoType. - ChangeSrc - - // Sensitive, if true, indicates that either the old or new value in the - // change is sensitive and so a rendered version of the plan in the UI - // should elide the actual values while still indicating the action of the - // change. - Sensitive bool -} - -// Decode unmarshals the raw representation of the output value being -// changed. -func (ocs *OutputChangeSrc) Decode() (*OutputChange, error) { - change, err := ocs.ChangeSrc.Decode(cty.DynamicPseudoType) - if err != nil { - return nil, err - } - return &OutputChange{ - Addr: ocs.Addr, - Change: *change, - Sensitive: ocs.Sensitive, - }, nil -} - -// DeepCopy creates a copy of the receiver where any pointers to nested mutable -// values are also copied, thus ensuring that future mutations of the receiver -// will not affect the copy. -// -// Some types used within a resource change are immutable by convention even -// though the Go language allows them to be mutated, such as the types from -// the addrs package. These are _not_ copied by this method, under the -// assumption that callers will behave themselves. -func (ocs *OutputChangeSrc) DeepCopy() *OutputChangeSrc { - if ocs == nil { - return nil - } - ret := *ocs - - ret.ChangeSrc.Before = ret.ChangeSrc.Before.Copy() - ret.ChangeSrc.After = ret.ChangeSrc.After.Copy() - - return &ret -} - -// ChangeSrc is a not-yet-decoded Change. -type ChangeSrc struct { - // Action defines what kind of change is being made. - Action Action - - // Before and After correspond to the fields of the same name in Change, - // but have not yet been decoded from the serialized value used for - // storage. - Before, After DynamicValue -} - -// Decode unmarshals the raw representations of the before and after values -// to produce a Change object. Pass the type constraint that the result must -// conform to. -// -// Where a ChangeSrc is embedded in some other struct, it's generally better -// to call the corresponding Decode method of that struct rather than working -// directly with its embedded Change. -func (cs *ChangeSrc) Decode(ty cty.Type) (*Change, error) { - var err error - before := cty.NullVal(ty) - after := cty.NullVal(ty) - - if len(cs.Before) > 0 { - before, err = cs.Before.Decode(ty) - if err != nil { - return nil, fmt.Errorf("error decoding 'before' value: %s", err) - } - } - if len(cs.After) > 0 { - after, err = cs.After.Decode(ty) - if err != nil { - return nil, fmt.Errorf("error decoding 'after' value: %s", err) - } - } - return &Change{ - Action: cs.Action, - Before: before, - After: after, - }, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/changes_sync.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/changes_sync.go deleted file mode 100644 index 89cc1ab2254..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/changes_sync.go +++ /dev/null @@ -1,144 +0,0 @@ -package plans - -import ( - "fmt" - "sync" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// ChangesSync is a wrapper around a Changes that provides a concurrency-safe -// interface to insert new changes and retrieve copies of existing changes. -// -// Each ChangesSync is independent of all others, so all concurrent writers -// to a particular Changes must share a single ChangesSync. Behavior is -// undefined if any other caller makes changes to the underlying Changes -// object or its nested objects concurrently with any of the methods of a -// particular ChangesSync. -type ChangesSync struct { - lock sync.Mutex - changes *Changes -} - -// AppendResourceInstanceChange records the given resource instance change in -// the set of planned resource changes. -// -// The caller must ensure that there are no concurrent writes to the given -// change while this method is running, but it is safe to resume mutating -// it after this method returns without affecting the saved change. -func (cs *ChangesSync) AppendResourceInstanceChange(changeSrc *ResourceInstanceChangeSrc) { - if cs == nil { - panic("AppendResourceInstanceChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - s := changeSrc.DeepCopy() - cs.changes.Resources = append(cs.changes.Resources, s) -} - -// GetResourceInstanceChange searches the set of resource instance changes for -// one matching the given address and generation, returning it if it exists. -// -// If no such change exists, nil is returned. -// -// The returned object is a deep copy of the change recorded in the plan, so -// callers may mutate it although it's generally better (less confusing) to -// treat planned changes as immutable after they've been initially constructed. -func (cs *ChangesSync) GetResourceInstanceChange(addr addrs.AbsResourceInstance, gen states.Generation) *ResourceInstanceChangeSrc { - if cs == nil { - panic("GetResourceInstanceChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - if gen == states.CurrentGen { - return cs.changes.ResourceInstance(addr).DeepCopy() - } - if dk, ok := gen.(states.DeposedKey); ok { - return cs.changes.ResourceInstanceDeposed(addr, dk).DeepCopy() - } - panic(fmt.Sprintf("unsupported generation value %#v", gen)) -} - -// RemoveResourceInstanceChange searches the set of resource instance changes -// for one matching the given address and generation, and removes it from the -// set if it exists. -func (cs *ChangesSync) RemoveResourceInstanceChange(addr addrs.AbsResourceInstance, gen states.Generation) { - if cs == nil { - panic("RemoveResourceInstanceChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - dk := states.NotDeposed - if realDK, ok := gen.(states.DeposedKey); ok { - dk = realDK - } - - addrStr := addr.String() - for i, r := range cs.changes.Resources { - if r.Addr.String() != addrStr || r.DeposedKey != dk { - continue - } - copy(cs.changes.Resources[i:], cs.changes.Resources[i+1:]) - cs.changes.Resources = cs.changes.Resources[:len(cs.changes.Resources)-1] - return - } -} - -// AppendOutputChange records the given output value change in the set of -// planned value changes. -// -// The caller must ensure that there are no concurrent writes to the given -// change while this method is running, but it is safe to resume mutating -// it after this method returns without affecting the saved change. -func (cs *ChangesSync) AppendOutputChange(changeSrc *OutputChangeSrc) { - if cs == nil { - panic("AppendOutputChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - s := changeSrc.DeepCopy() - cs.changes.Outputs = append(cs.changes.Outputs, s) -} - -// GetOutputChange searches the set of output value changes for one matching -// the given address, returning it if it exists. -// -// If no such change exists, nil is returned. -// -// The returned object is a deep copy of the change recorded in the plan, so -// callers may mutate it although it's generally better (less confusing) to -// treat planned changes as immutable after they've been initially constructed. -func (cs *ChangesSync) GetOutputChange(addr addrs.AbsOutputValue) *OutputChangeSrc { - if cs == nil { - panic("GetOutputChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - return cs.changes.OutputValue(addr) -} - -// RemoveOutputChange searches the set of output value changes for one matching -// the given address, and removes it from the set if it exists. -func (cs *ChangesSync) RemoveOutputChange(addr addrs.AbsOutputValue) { - if cs == nil { - panic("RemoveOutputChange on nil ChangesSync") - } - cs.lock.Lock() - defer cs.lock.Unlock() - - addrStr := addr.String() - for i, o := range cs.changes.Outputs { - if o.Addr.String() != addrStr { - continue - } - copy(cs.changes.Outputs[i:], cs.changes.Outputs[i+1:]) - cs.changes.Outputs = cs.changes.Outputs[:len(cs.changes.Outputs)-1] - return - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/doc.go deleted file mode 100644 index 01ca3892389..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package plans contains the types that are used to represent Terraform plans. -// -// A plan describes a set of changes that Terraform will make to update remote -// objects to match with changes to the configuration. -package plans diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/dynamic_value.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/dynamic_value.go deleted file mode 100644 index 51fbb24cfb3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/dynamic_value.go +++ /dev/null @@ -1,96 +0,0 @@ -package plans - -import ( - "github.com/zclconf/go-cty/cty" - ctymsgpack "github.com/zclconf/go-cty/cty/msgpack" -) - -// DynamicValue is the representation in the plan of a value whose type cannot -// be determined at compile time, such as because it comes from a schema -// defined in a plugin. -// -// This type is used as an indirection so that the overall plan structure can -// be decoded without schema available, and then the dynamic values accessed -// at a later time once the appropriate schema has been determined. -// -// Internally, DynamicValue is a serialized version of a cty.Value created -// against a particular type constraint. Callers should not access directly -// the serialized form, whose format may change in future. Values of this -// type must always be created by calling NewDynamicValue. -// -// The zero value of DynamicValue is nil, and represents the absense of a -// value within the Go type system. This is distinct from a cty.NullVal -// result, which represents the absense of a value within the cty type system. -type DynamicValue []byte - -// NewDynamicValue creates a DynamicValue by serializing the given value -// against the given type constraint. The value must conform to the type -// constraint, or the result is undefined. -// -// If the value to be encoded has no predefined schema (for example, for -// module output values and input variables), set the type constraint to -// cty.DynamicPseudoType in order to save type information as part of the -// value, and then also pass cty.DynamicPseudoType to method Decode to recover -// the original value. -// -// cty.NilVal can be used to represent the absense of a value, but callers -// must be careful to distinguish values that are absent at the Go layer -// (cty.NilVal) vs. values that are absent at the cty layer (cty.NullVal -// results). -func NewDynamicValue(val cty.Value, ty cty.Type) (DynamicValue, error) { - // If we're given cty.NilVal (the zero value of cty.Value, which is - // distinct from a typed null value created by cty.NullVal) then we'll - // assume the caller is trying to represent the _absense_ of a value, - // and so we'll return a nil DynamicValue. - if val == cty.NilVal { - return DynamicValue(nil), nil - } - - // Currently our internal encoding is msgpack, via ctymsgpack. - buf, err := ctymsgpack.Marshal(val, ty) - if err != nil { - return nil, err - } - - return DynamicValue(buf), nil -} - -// Decode retrieves the effective value from the receiever by interpreting the -// serialized form against the given type constraint. For correct results, -// the type constraint must match (or be consistent with) the one that was -// used to create the receiver. -// -// A nil DynamicValue decodes to cty.NilVal, which is not a valid value and -// instead represents the absense of a value. -func (v DynamicValue) Decode(ty cty.Type) (cty.Value, error) { - if v == nil { - return cty.NilVal, nil - } - - return ctymsgpack.Unmarshal([]byte(v), ty) -} - -// ImpliedType returns the type implied by the serialized structure of the -// receiving value. -// -// This will not necessarily be exactly the type that was given when the -// value was encoded, and in particular must not be used for values that -// were encoded with their static type given as cty.DynamicPseudoType. -// It is however safe to use this method for values that were encoded using -// their runtime type as the conforming type, with the result being -// semantically equivalent but with all lists and sets represented as tuples, -// and maps as objects, due to ambiguities of the serialization. -func (v DynamicValue) ImpliedType() (cty.Type, error) { - return ctymsgpack.ImpliedType([]byte(v)) -} - -// Copy produces a copy of the receiver with a distinct backing array. -func (v DynamicValue) Copy() DynamicValue { - if v == nil { - return nil - } - - ret := make(DynamicValue, len(v)) - copy(ret, v) - return ret -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/all_null.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/all_null.go deleted file mode 100644 index ba9cc9611ac..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/all_null.go +++ /dev/null @@ -1,18 +0,0 @@ -package objchange - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/zclconf/go-cty/cty" -) - -// AllAttributesNull constructs a non-null cty.Value of the object type implied -// by the given schema that has all of its leaf attributes set to null and all -// of its nested block collections set to zero-length. -// -// This simulates what would result from decoding an empty configuration block -// with the given schema, except that it does not produce errors -func AllAttributesNull(schema *configschema.Block) cty.Value { - // "All attributes null" happens to be the definition of EmptyValue for - // a Block, so we can just delegate to that. - return schema.EmptyValue() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/compatible.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/compatible.go deleted file mode 100644 index 36a7d496c2a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/compatible.go +++ /dev/null @@ -1,447 +0,0 @@ -package objchange - -import ( - "fmt" - "strconv" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" -) - -// AssertObjectCompatible checks whether the given "actual" value is a valid -// completion of the possibly-partially-unknown "planned" value. -// -// This means that any known leaf value in "planned" must be equal to the -// corresponding value in "actual", and various other similar constraints. -// -// Any inconsistencies are reported by returning a non-zero number of errors. -// These errors are usually (but not necessarily) cty.PathError values -// referring to a particular nested value within the "actual" value. -// -// The two values must have types that conform to the given schema's implied -// type, or this function will panic. -func AssertObjectCompatible(schema *configschema.Block, planned, actual cty.Value) []error { - return assertObjectCompatible(schema, planned, actual, nil) -} - -func assertObjectCompatible(schema *configschema.Block, planned, actual cty.Value, path cty.Path) []error { - var errs []error - if planned.IsNull() && !actual.IsNull() { - errs = append(errs, path.NewErrorf("was absent, but now present")) - return errs - } - if actual.IsNull() && !planned.IsNull() { - errs = append(errs, path.NewErrorf("was present, but now absent")) - return errs - } - if planned.IsNull() { - // No further checks possible if both values are null - return errs - } - - for name, attrS := range schema.Attributes { - plannedV := planned.GetAttr(name) - actualV := actual.GetAttr(name) - - path := append(path, cty.GetAttrStep{Name: name}) - moreErrs := assertValueCompatible(plannedV, actualV, path) - if attrS.Sensitive { - if len(moreErrs) > 0 { - // Use a vague placeholder message instead, to avoid disclosing - // sensitive information. - errs = append(errs, path.NewErrorf("inconsistent values for sensitive attribute")) - } - } else { - errs = append(errs, moreErrs...) - } - } - for name, blockS := range schema.BlockTypes { - plannedV := planned.GetAttr(name) - actualV := actual.GetAttr(name) - - // As a special case, if there were any blocks whose leaf attributes - // are all unknown then we assume (possibly incorrectly) that the - // HCL dynamic block extension is in use with an unknown for_each - // argument, and so we will do looser validation here that allows - // for those blocks to have expanded into a different number of blocks - // if the for_each value is now known. - maybeUnknownBlocks := couldHaveUnknownBlockPlaceholder(plannedV, blockS, false) - - path := append(path, cty.GetAttrStep{Name: name}) - switch blockS.Nesting { - case configschema.NestingSingle, configschema.NestingGroup: - // If an unknown block placeholder was present then the placeholder - // may have expanded out into zero blocks, which is okay. - if maybeUnknownBlocks && actualV.IsNull() { - continue - } - moreErrs := assertObjectCompatible(&blockS.Block, plannedV, actualV, path) - errs = append(errs, moreErrs...) - case configschema.NestingList: - // A NestingList might either be a list or a tuple, depending on - // whether there are dynamically-typed attributes inside. However, - // both support a similar-enough API that we can treat them the - // same for our purposes here. - if !plannedV.IsKnown() || !actualV.IsKnown() || plannedV.IsNull() || actualV.IsNull() { - continue - } - - if maybeUnknownBlocks { - // When unknown blocks are present the final blocks may be - // at different indices than the planned blocks, so unfortunately - // we can't do our usual checks in this case without generating - // false negatives. - continue - } - - plannedL := plannedV.LengthInt() - actualL := actualV.LengthInt() - if plannedL != actualL { - errs = append(errs, path.NewErrorf("block count changed from %d to %d", plannedL, actualL)) - continue - } - for it := plannedV.ElementIterator(); it.Next(); { - idx, plannedEV := it.Element() - if !actualV.HasIndex(idx).True() { - continue - } - actualEV := actualV.Index(idx) - moreErrs := assertObjectCompatible(&blockS.Block, plannedEV, actualEV, append(path, cty.IndexStep{Key: idx})) - errs = append(errs, moreErrs...) - } - case configschema.NestingMap: - // A NestingMap might either be a map or an object, depending on - // whether there are dynamically-typed attributes inside, but - // that's decided statically and so both values will have the same - // kind. - if plannedV.Type().IsObjectType() { - plannedAtys := plannedV.Type().AttributeTypes() - actualAtys := actualV.Type().AttributeTypes() - for k := range plannedAtys { - if _, ok := actualAtys[k]; !ok { - errs = append(errs, path.NewErrorf("block key %q has vanished", k)) - continue - } - - plannedEV := plannedV.GetAttr(k) - actualEV := actualV.GetAttr(k) - moreErrs := assertObjectCompatible(&blockS.Block, plannedEV, actualEV, append(path, cty.GetAttrStep{Name: k})) - errs = append(errs, moreErrs...) - } - if !maybeUnknownBlocks { // new blocks may appear if unknown blocks were present in the plan - for k := range actualAtys { - if _, ok := plannedAtys[k]; !ok { - errs = append(errs, path.NewErrorf("new block key %q has appeared", k)) - continue - } - } - } - } else { - if !plannedV.IsKnown() || plannedV.IsNull() || actualV.IsNull() { - continue - } - plannedL := plannedV.LengthInt() - actualL := actualV.LengthInt() - if plannedL != actualL && !maybeUnknownBlocks { // new blocks may appear if unknown blocks were persent in the plan - errs = append(errs, path.NewErrorf("block count changed from %d to %d", plannedL, actualL)) - continue - } - for it := plannedV.ElementIterator(); it.Next(); { - idx, plannedEV := it.Element() - if !actualV.HasIndex(idx).True() { - continue - } - actualEV := actualV.Index(idx) - moreErrs := assertObjectCompatible(&blockS.Block, plannedEV, actualEV, append(path, cty.IndexStep{Key: idx})) - errs = append(errs, moreErrs...) - } - } - case configschema.NestingSet: - if !plannedV.IsKnown() || !actualV.IsKnown() || plannedV.IsNull() || actualV.IsNull() { - continue - } - - setErrs := assertSetValuesCompatible(plannedV, actualV, path, func(plannedEV, actualEV cty.Value) bool { - errs := assertObjectCompatible(&blockS.Block, plannedEV, actualEV, append(path, cty.IndexStep{Key: actualEV})) - return len(errs) == 0 - }) - errs = append(errs, setErrs...) - - if maybeUnknownBlocks { - // When unknown blocks are present the final number of blocks - // may be different, either because the unknown set values - // become equal and are collapsed, or the count is unknown due - // a dynamic block. Unfortunately this means we can't do our - // usual checks in this case without generating false - // negatives. - continue - } - - // There can be fewer elements in a set after its elements are all - // known (values that turn out to be equal will coalesce) but the - // number of elements must never get larger. - plannedL := plannedV.LengthInt() - actualL := actualV.LengthInt() - if plannedL < actualL { - errs = append(errs, path.NewErrorf("block set length changed from %d to %d", plannedL, actualL)) - } - default: - panic(fmt.Sprintf("unsupported nesting mode %s", blockS.Nesting)) - } - } - return errs -} - -func assertValueCompatible(planned, actual cty.Value, path cty.Path) []error { - // NOTE: We don't normally use the GoString rendering of cty.Value in - // user-facing error messages as a rule, but we make an exception - // for this function because we expect the user to pass this message on - // verbatim to the provider development team and so more detail is better. - - var errs []error - if planned.Type() == cty.DynamicPseudoType { - // Anything goes, then - return errs - } - if problems := planned.Type().TestConformance(actual.Type()); len(problems) > 0 { - errs = append(errs, path.NewErrorf("wrong final value type: %s", convert.MismatchMessage(actual.Type(), planned.Type()))) - // If the types don't match then we can't do any other comparisons, - // so we bail early. - return errs - } - - if !planned.IsKnown() { - // We didn't know what were going to end up with during plan, so - // anything goes during apply. - return errs - } - - if actual.IsNull() { - if planned.IsNull() { - return nil - } - errs = append(errs, path.NewErrorf("was %#v, but now null", planned)) - return errs - } - if planned.IsNull() { - errs = append(errs, path.NewErrorf("was null, but now %#v", actual)) - return errs - } - - ty := planned.Type() - switch { - - case !actual.IsKnown(): - errs = append(errs, path.NewErrorf("was known, but now unknown")) - - case ty.IsPrimitiveType(): - if !actual.Equals(planned).True() { - errs = append(errs, path.NewErrorf("was %#v, but now %#v", planned, actual)) - } - - case ty.IsListType() || ty.IsMapType() || ty.IsTupleType(): - for it := planned.ElementIterator(); it.Next(); { - k, plannedV := it.Element() - if !actual.HasIndex(k).True() { - errs = append(errs, path.NewErrorf("element %s has vanished", indexStrForErrors(k))) - continue - } - - actualV := actual.Index(k) - moreErrs := assertValueCompatible(plannedV, actualV, append(path, cty.IndexStep{Key: k})) - errs = append(errs, moreErrs...) - } - - for it := actual.ElementIterator(); it.Next(); { - k, _ := it.Element() - if !planned.HasIndex(k).True() { - errs = append(errs, path.NewErrorf("new element %s has appeared", indexStrForErrors(k))) - } - } - - case ty.IsObjectType(): - atys := ty.AttributeTypes() - for name := range atys { - // Because we already tested that the two values have the same type, - // we can assume that the same attributes are present in both and - // focus just on testing their values. - plannedV := planned.GetAttr(name) - actualV := actual.GetAttr(name) - moreErrs := assertValueCompatible(plannedV, actualV, append(path, cty.GetAttrStep{Name: name})) - errs = append(errs, moreErrs...) - } - - case ty.IsSetType(): - // We can't really do anything useful for sets here because changing - // an unknown element to known changes the identity of the element, and - // so we can't correlate them properly. However, we will at least check - // to ensure that the number of elements is consistent, along with - // the general type-match checks we ran earlier in this function. - if planned.IsKnown() && !planned.IsNull() && !actual.IsNull() { - - setErrs := assertSetValuesCompatible(planned, actual, path, func(plannedV, actualV cty.Value) bool { - errs := assertValueCompatible(plannedV, actualV, append(path, cty.IndexStep{Key: actualV})) - return len(errs) == 0 - }) - errs = append(errs, setErrs...) - - // There can be fewer elements in a set after its elements are all - // known (values that turn out to be equal will coalesce) but the - // number of elements must never get larger. - - plannedL := planned.LengthInt() - actualL := actual.LengthInt() - if plannedL < actualL { - errs = append(errs, path.NewErrorf("length changed from %d to %d", plannedL, actualL)) - } - } - } - - return errs -} - -func indexStrForErrors(v cty.Value) string { - switch v.Type() { - case cty.Number: - return v.AsBigFloat().Text('f', -1) - case cty.String: - return strconv.Quote(v.AsString()) - default: - // Should be impossible, since no other index types are allowed! - return fmt.Sprintf("%#v", v) - } -} - -// couldHaveUnknownBlockPlaceholder is a heuristic that recognizes how the -// HCL dynamic block extension behaves when it's asked to expand a block whose -// for_each argument is unknown. In such cases, it generates a single placeholder -// block with all leaf attribute values unknown, and once the for_each -// expression becomes known the placeholder may be replaced with any number -// of blocks, so object compatibility checks would need to be more liberal. -// -// Set "nested" if testing a block that is nested inside a candidate block -// placeholder; this changes the interpretation of there being no blocks of -// a type to allow for there being zero nested blocks. -func couldHaveUnknownBlockPlaceholder(v cty.Value, blockS *configschema.NestedBlock, nested bool) bool { - switch blockS.Nesting { - case configschema.NestingSingle, configschema.NestingGroup: - if nested && v.IsNull() { - return true // for nested blocks, a single block being unset doesn't disqualify from being an unknown block placeholder - } - return couldBeUnknownBlockPlaceholderElement(v, &blockS.Block) - default: - // These situations should be impossible for correct providers, but - // we permit the legacy SDK to produce some incorrect outcomes - // for compatibility with its existing logic, and so we must be - // tolerant here. - if !v.IsKnown() { - return true - } - if v.IsNull() { - return false // treated as if the list were empty, so we would see zero iterations below - } - - // For all other nesting modes, our value should be something iterable. - for it := v.ElementIterator(); it.Next(); { - _, ev := it.Element() - if couldBeUnknownBlockPlaceholderElement(ev, &blockS.Block) { - return true - } - } - - // Our default changes depending on whether we're testing the candidate - // block itself or something nested inside of it: zero blocks of a type - // can never contain a dynamic block placeholder, but a dynamic block - // placeholder might contain zero blocks of one of its own nested block - // types, if none were set in the config at all. - return nested - } -} - -func couldBeUnknownBlockPlaceholderElement(v cty.Value, schema *configschema.Block) bool { - if v.IsNull() { - return false // null value can never be a placeholder element - } - if !v.IsKnown() { - return true // this should never happen for well-behaved providers, but can happen with the legacy SDK opt-outs - } - for name := range schema.Attributes { - av := v.GetAttr(name) - - // Unknown block placeholders contain only unknown or null attribute - // values, depending on whether or not a particular attribute was set - // explicitly inside the content block. Note that this is imprecise: - // non-placeholders can also match this, so this function can generate - // false positives. - if av.IsKnown() && !av.IsNull() { - return false - } - } - for name, blockS := range schema.BlockTypes { - if !couldHaveUnknownBlockPlaceholder(v.GetAttr(name), blockS, true) { - return false - } - } - return true -} - -// assertSetValuesCompatible checks that each of the elements in a can -// be correlated with at least one equivalent element in b and vice-versa, -// using the given correlation function. -// -// This allows the number of elements in the sets to change as long as all -// elements in both sets can be correlated, making this function safe to use -// with sets that may contain unknown values as long as the unknown case is -// addressed in some reasonable way in the callback function. -// -// The callback always recieves values from set a as its first argument and -// values from set b in its second argument, so it is safe to use with -// non-commutative functions. -// -// As with assertValueCompatible, we assume that the target audience of error -// messages here is a provider developer (via a bug report from a user) and so -// we intentionally violate our usual rule of keeping cty implementation -// details out of error messages. -func assertSetValuesCompatible(planned, actual cty.Value, path cty.Path, f func(aVal, bVal cty.Value) bool) []error { - a := planned - b := actual - - // Our methodology here is a little tricky, to deal with the fact that - // it's impossible to directly correlate two non-equal set elements because - // they don't have identities separate from their values. - // The approach is to count the number of equivalent elements each element - // of a has in b and vice-versa, and then return true only if each element - // in both sets has at least one equivalent. - as := a.AsValueSlice() - bs := b.AsValueSlice() - aeqs := make([]bool, len(as)) - beqs := make([]bool, len(bs)) - for ai, av := range as { - for bi, bv := range bs { - if f(av, bv) { - aeqs[ai] = true - beqs[bi] = true - } - } - } - - var errs []error - for i, eq := range aeqs { - if !eq { - errs = append(errs, path.NewErrorf("planned set element %#v does not correlate with any element in actual", as[i])) - } - } - if len(errs) > 0 { - // Exit early since otherwise we're likely to generate duplicate - // error messages from the other perspective in the subsequent loop. - return errs - } - for i, eq := range beqs { - if !eq { - errs = append(errs, path.NewErrorf("actual set element %#v does not correlate with any element in plan", bs[i])) - } - } - return errs -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/doc.go deleted file mode 100644 index 2c18a0108f9..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package objchange deals with the business logic of taking a prior state -// value and a config value and producing a proposed new merged value, along -// with other related rules in this domain. -package objchange diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/lcs.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/lcs.go deleted file mode 100644 index cbfefddddb9..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/lcs.go +++ /dev/null @@ -1,104 +0,0 @@ -package objchange - -import ( - "github.com/zclconf/go-cty/cty" -) - -// LongestCommonSubsequence finds a sequence of values that are common to both -// x and y, with the same relative ordering as in both collections. This result -// is useful as a first step towards computing a diff showing added/removed -// elements in a sequence. -// -// The approached used here is a "naive" one, assuming that both xs and ys will -// generally be small in most reasonable Terraform configurations. For larger -// lists the time/space usage may be sub-optimal. -// -// A pair of lists may have multiple longest common subsequences. In that -// case, the one selected by this function is undefined. -func LongestCommonSubsequence(xs, ys []cty.Value) []cty.Value { - if len(xs) == 0 || len(ys) == 0 { - return make([]cty.Value, 0) - } - - c := make([]int, len(xs)*len(ys)) - eqs := make([]bool, len(xs)*len(ys)) - w := len(xs) - - for y := 0; y < len(ys); y++ { - for x := 0; x < len(xs); x++ { - eqV := xs[x].Equals(ys[y]) - eq := false - if eqV.IsKnown() && eqV.True() { - eq = true - eqs[(w*y)+x] = true // equality tests can be expensive, so cache it - } - if eq { - // Sequence gets one longer than for the cell at top left, - // since we'd append a new item to the sequence here. - if x == 0 || y == 0 { - c[(w*y)+x] = 1 - } else { - c[(w*y)+x] = c[(w*(y-1))+(x-1)] + 1 - } - } else { - // We follow the longest of the sequence above and the sequence - // to the left of us in the matrix. - l := 0 - u := 0 - if x > 0 { - l = c[(w*y)+(x-1)] - } - if y > 0 { - u = c[(w*(y-1))+x] - } - if l > u { - c[(w*y)+x] = l - } else { - c[(w*y)+x] = u - } - } - } - } - - // The bottom right cell tells us how long our longest sequence will be - seq := make([]cty.Value, c[len(c)-1]) - - // Now we will walk back from the bottom right cell, finding again all - // of the equal pairs to construct our sequence. - x := len(xs) - 1 - y := len(ys) - 1 - i := len(seq) - 1 - - for x > -1 && y > -1 { - if eqs[(w*y)+x] { - // Add the value to our result list and then walk diagonally - // up and to the left. - seq[i] = xs[x] - x-- - y-- - i-- - } else { - // Take the path with the greatest sequence length in the matrix. - l := 0 - u := 0 - if x > 0 { - l = c[(w*y)+(x-1)] - } - if y > 0 { - u = c[(w*(y-1))+x] - } - if l > u { - x-- - } else { - y-- - } - } - } - - if i > -1 { - // should never happen if the matrix was constructed properly - panic("not enough elements in sequence") - } - - return seq -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/objchange.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/objchange.go deleted file mode 100644 index 879fc93a1e6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/objchange.go +++ /dev/null @@ -1,390 +0,0 @@ -package objchange - -import ( - "fmt" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" -) - -// ProposedNewObject constructs a proposed new object value by combining the -// computed attribute values from "prior" with the configured attribute values -// from "config". -// -// Both value must conform to the given schema's implied type, or this function -// will panic. -// -// The prior value must be wholly known, but the config value may be unknown -// or have nested unknown values. -// -// The merging of the two objects includes the attributes of any nested blocks, -// which will be correlated in a manner appropriate for their nesting mode. -// Note in particular that the correlation for blocks backed by sets is a -// heuristic based on matching non-computed attribute values and so it may -// produce strange results with more "extreme" cases, such as a nested set -// block where _all_ attributes are computed. -func ProposedNewObject(schema *configschema.Block, prior, config cty.Value) cty.Value { - // If the config and prior are both null, return early here before - // populating the prior block. The prevents non-null blocks from appearing - // the proposed state value. - if config.IsNull() && prior.IsNull() { - return prior - } - - if prior.IsNull() { - // In this case, we will construct a synthetic prior value that is - // similar to the result of decoding an empty configuration block, - // which simplifies our handling of the top-level attributes/blocks - // below by giving us one non-null level of object to pull values from. - prior = AllAttributesNull(schema) - } - return proposedNewObject(schema, prior, config) -} - -// PlannedDataResourceObject is similar to ProposedNewObject but tailored for -// planning data resources in particular. Specifically, it replaces the values -// of any Computed attributes not set in the configuration with an unknown -// value, which serves as a placeholder for a value to be filled in by the -// provider when the data resource is finally read. -// -// Data resources are different because the planning of them is handled -// entirely within Terraform Core and not subject to customization by the -// provider. This function is, in effect, producing an equivalent result to -// passing the ProposedNewObject result into a provider's PlanResourceChange -// function, assuming a fixed implementation of PlanResourceChange that just -// fills in unknown values as needed. -func PlannedDataResourceObject(schema *configschema.Block, config cty.Value) cty.Value { - // Our trick here is to run the ProposedNewObject logic with an - // entirely-unknown prior value. Because of cty's unknown short-circuit - // behavior, any operation on prior returns another unknown, and so - // unknown values propagate into all of the parts of the resulting value - // that would normally be filled in by preserving the prior state. - prior := cty.UnknownVal(schema.ImpliedType()) - return proposedNewObject(schema, prior, config) -} - -func proposedNewObject(schema *configschema.Block, prior, config cty.Value) cty.Value { - if config.IsNull() || !config.IsKnown() { - // This is a weird situation, but we'll allow it anyway to free - // callers from needing to specifically check for these cases. - return prior - } - if (!prior.Type().IsObjectType()) || (!config.Type().IsObjectType()) { - panic("ProposedNewObject only supports object-typed values") - } - - // From this point onwards, we can assume that both values are non-null - // object types, and that the config value itself is known (though it - // may contain nested values that are unknown.) - - newAttrs := map[string]cty.Value{} - for name, attr := range schema.Attributes { - priorV := prior.GetAttr(name) - configV := config.GetAttr(name) - var newV cty.Value - switch { - case attr.Computed && attr.Optional: - // This is the trickiest scenario: we want to keep the prior value - // if the config isn't overriding it. Note that due to some - // ambiguity here, setting an optional+computed attribute from - // config and then later switching the config to null in a - // subsequent change causes the initial config value to be "sticky" - // unless the provider specifically overrides it during its own - // plan customization step. - if configV.IsNull() { - newV = priorV - } else { - newV = configV - } - case attr.Computed: - // configV will always be null in this case, by definition. - // priorV may also be null, but that's okay. - newV = priorV - default: - // For non-computed attributes, we always take the config value, - // even if it is null. If it's _required_ then null values - // should've been caught during an earlier validation step, and - // so we don't really care about that here. - newV = configV - } - newAttrs[name] = newV - } - - // Merging nested blocks is a little more complex, since we need to - // correlate blocks between both objects and then recursively propose - // a new object for each. The correlation logic depends on the nesting - // mode for each block type. - for name, blockType := range schema.BlockTypes { - priorV := prior.GetAttr(name) - configV := config.GetAttr(name) - var newV cty.Value - switch blockType.Nesting { - - case configschema.NestingSingle, configschema.NestingGroup: - newV = ProposedNewObject(&blockType.Block, priorV, configV) - - case configschema.NestingList: - // Nested blocks are correlated by index. - configVLen := 0 - if configV.IsKnown() && !configV.IsNull() { - configVLen = configV.LengthInt() - } - if configVLen > 0 { - newVals := make([]cty.Value, 0, configVLen) - for it := configV.ElementIterator(); it.Next(); { - idx, configEV := it.Element() - if priorV.IsKnown() && (priorV.IsNull() || !priorV.HasIndex(idx).True()) { - // If there is no corresponding prior element then - // we just take the config value as-is. - newVals = append(newVals, configEV) - continue - } - priorEV := priorV.Index(idx) - - newEV := ProposedNewObject(&blockType.Block, priorEV, configEV) - newVals = append(newVals, newEV) - } - // Despite the name, a NestingList might also be a tuple, if - // its nested schema contains dynamically-typed attributes. - if configV.Type().IsTupleType() { - newV = cty.TupleVal(newVals) - } else { - newV = cty.ListVal(newVals) - } - } else { - // Despite the name, a NestingList might also be a tuple, if - // its nested schema contains dynamically-typed attributes. - if configV.Type().IsTupleType() { - newV = cty.EmptyTupleVal - } else { - newV = cty.ListValEmpty(blockType.ImpliedType()) - } - } - - case configschema.NestingMap: - // Despite the name, a NestingMap may produce either a map or - // object value, depending on whether the nested schema contains - // dynamically-typed attributes. - if configV.Type().IsObjectType() { - // Nested blocks are correlated by key. - configVLen := 0 - if configV.IsKnown() && !configV.IsNull() { - configVLen = configV.LengthInt() - } - if configVLen > 0 { - newVals := make(map[string]cty.Value, configVLen) - atys := configV.Type().AttributeTypes() - for name := range atys { - configEV := configV.GetAttr(name) - if !priorV.IsKnown() || priorV.IsNull() || !priorV.Type().HasAttribute(name) { - // If there is no corresponding prior element then - // we just take the config value as-is. - newVals[name] = configEV - continue - } - priorEV := priorV.GetAttr(name) - - newEV := ProposedNewObject(&blockType.Block, priorEV, configEV) - newVals[name] = newEV - } - // Although we call the nesting mode "map", we actually use - // object values so that elements might have different types - // in case of dynamically-typed attributes. - newV = cty.ObjectVal(newVals) - } else { - newV = cty.EmptyObjectVal - } - } else { - configVLen := 0 - if configV.IsKnown() && !configV.IsNull() { - configVLen = configV.LengthInt() - } - if configVLen > 0 { - newVals := make(map[string]cty.Value, configVLen) - for it := configV.ElementIterator(); it.Next(); { - idx, configEV := it.Element() - k := idx.AsString() - if priorV.IsKnown() && (priorV.IsNull() || !priorV.HasIndex(idx).True()) { - // If there is no corresponding prior element then - // we just take the config value as-is. - newVals[k] = configEV - continue - } - priorEV := priorV.Index(idx) - - newEV := ProposedNewObject(&blockType.Block, priorEV, configEV) - newVals[k] = newEV - } - newV = cty.MapVal(newVals) - } else { - newV = cty.MapValEmpty(blockType.ImpliedType()) - } - } - - case configschema.NestingSet: - if !configV.Type().IsSetType() { - panic("configschema.NestingSet value is not a set as expected") - } - - // Nested blocks are correlated by comparing the element values - // after eliminating all of the computed attributes. In practice, - // this means that any config change produces an entirely new - // nested object, and we only propagate prior computed values - // if the non-computed attribute values are identical. - var cmpVals [][2]cty.Value - if priorV.IsKnown() && !priorV.IsNull() { - cmpVals = setElementCompareValues(&blockType.Block, priorV, false) - } - configVLen := 0 - if configV.IsKnown() && !configV.IsNull() { - configVLen = configV.LengthInt() - } - if configVLen > 0 { - used := make([]bool, len(cmpVals)) // track used elements in case multiple have the same compare value - newVals := make([]cty.Value, 0, configVLen) - for it := configV.ElementIterator(); it.Next(); { - _, configEV := it.Element() - var priorEV cty.Value - for i, cmp := range cmpVals { - if used[i] { - continue - } - if cmp[1].RawEquals(configEV) { - priorEV = cmp[0] - used[i] = true // we can't use this value on a future iteration - break - } - } - if priorEV == cty.NilVal { - priorEV = cty.NullVal(blockType.ImpliedType()) - } - - newEV := ProposedNewObject(&blockType.Block, priorEV, configEV) - newVals = append(newVals, newEV) - } - newV = cty.SetVal(newVals) - } else { - newV = cty.SetValEmpty(blockType.Block.ImpliedType()) - } - - default: - // Should never happen, since the above cases are comprehensive. - panic(fmt.Sprintf("unsupported block nesting mode %s", blockType.Nesting)) - } - - newAttrs[name] = newV - } - - return cty.ObjectVal(newAttrs) -} - -// setElementCompareValues takes a known, non-null value of a cty.Set type and -// returns a table -- constructed of two-element arrays -- that maps original -// set element values to corresponding values that have all of the computed -// values removed, making them suitable for comparison with values obtained -// from configuration. The element type of the set must conform to the implied -// type of the given schema, or this function will panic. -// -// In the resulting slice, the zeroth element of each array is the original -// value and the one-indexed element is the corresponding "compare value". -// -// This is intended to help correlate prior elements with configured elements -// in ProposedNewObject. The result is a heuristic rather than an exact science, -// since e.g. two separate elements may reduce to the same value through this -// process. The caller must therefore be ready to deal with duplicates. -func setElementCompareValues(schema *configschema.Block, set cty.Value, isConfig bool) [][2]cty.Value { - ret := make([][2]cty.Value, 0, set.LengthInt()) - for it := set.ElementIterator(); it.Next(); { - _, ev := it.Element() - ret = append(ret, [2]cty.Value{ev, setElementCompareValue(schema, ev, isConfig)}) - } - return ret -} - -// setElementCompareValue creates a new value that has all of the same -// non-computed attribute values as the one given but has all computed -// attribute values forced to null. -// -// If isConfig is true then non-null Optional+Computed attribute values will -// be preserved. Otherwise, they will also be set to null. -// -// The input value must conform to the schema's implied type, and the return -// value is guaranteed to conform to it. -func setElementCompareValue(schema *configschema.Block, v cty.Value, isConfig bool) cty.Value { - if v.IsNull() || !v.IsKnown() { - return v - } - - attrs := map[string]cty.Value{} - for name, attr := range schema.Attributes { - switch { - case attr.Computed && attr.Optional: - if isConfig { - attrs[name] = v.GetAttr(name) - } else { - attrs[name] = cty.NullVal(attr.Type) - } - case attr.Computed: - attrs[name] = cty.NullVal(attr.Type) - default: - attrs[name] = v.GetAttr(name) - } - } - - for name, blockType := range schema.BlockTypes { - switch blockType.Nesting { - - case configschema.NestingSingle, configschema.NestingGroup: - attrs[name] = setElementCompareValue(&blockType.Block, v.GetAttr(name), isConfig) - - case configschema.NestingList, configschema.NestingSet: - cv := v.GetAttr(name) - if cv.IsNull() || !cv.IsKnown() { - attrs[name] = cv - continue - } - if l := cv.LengthInt(); l > 0 { - elems := make([]cty.Value, 0, l) - for it := cv.ElementIterator(); it.Next(); { - _, ev := it.Element() - elems = append(elems, setElementCompareValue(&blockType.Block, ev, isConfig)) - } - if blockType.Nesting == configschema.NestingSet { - // SetValEmpty would panic if given elements that are not - // all of the same type, but that's guaranteed not to - // happen here because our input value was _already_ a - // set and we've not changed the types of any elements here. - attrs[name] = cty.SetVal(elems) - } else { - attrs[name] = cty.TupleVal(elems) - } - } else { - if blockType.Nesting == configschema.NestingSet { - attrs[name] = cty.SetValEmpty(blockType.Block.ImpliedType()) - } else { - attrs[name] = cty.EmptyTupleVal - } - } - - case configschema.NestingMap: - cv := v.GetAttr(name) - if cv.IsNull() || !cv.IsKnown() { - attrs[name] = cv - continue - } - elems := make(map[string]cty.Value) - for it := cv.ElementIterator(); it.Next(); { - kv, ev := it.Element() - elems[kv.AsString()] = setElementCompareValue(&blockType.Block, ev, isConfig) - } - attrs[name] = cty.ObjectVal(elems) - - default: - // Should never happen, since the above cases are comprehensive. - panic(fmt.Sprintf("unsupported block nesting mode %s", blockType.Nesting)) - } - } - - return cty.ObjectVal(attrs) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/plan_valid.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/plan_valid.go deleted file mode 100644 index 905a91142a1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/plan_valid.go +++ /dev/null @@ -1,267 +0,0 @@ -package objchange - -import ( - "fmt" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" -) - -// AssertPlanValid checks checks whether a planned new state returned by a -// provider's PlanResourceChange method is suitable to achieve a change -// from priorState to config. It returns a slice with nonzero length if -// any problems are detected. Because problems here indicate bugs in the -// provider that generated the plannedState, they are written with provider -// developers as an audience, rather than end-users. -// -// All of the given values must have the same type and must conform to the -// implied type of the given schema, or this function may panic or produce -// garbage results. -// -// During planning, a provider may only make changes to attributes that are -// null (unset) in the configuration and are marked as "computed" in the -// resource type schema, in order to insert any default values the provider -// may know about. If the default value cannot be determined until apply time, -// the provider can return an unknown value. Providers are forbidden from -// planning a change that disagrees with any non-null argument in the -// configuration. -// -// As a special exception, providers _are_ allowed to provide attribute values -// conflicting with configuration if and only if the planned value exactly -// matches the corresponding attribute value in the prior state. The provider -// can use this to signal that the new value is functionally equivalent to -// the old and thus no change is required. -func AssertPlanValid(schema *configschema.Block, priorState, config, plannedState cty.Value) []error { - return assertPlanValid(schema, priorState, config, plannedState, nil) -} - -func assertPlanValid(schema *configschema.Block, priorState, config, plannedState cty.Value, path cty.Path) []error { - var errs []error - if plannedState.IsNull() && !config.IsNull() { - errs = append(errs, path.NewErrorf("planned for absense but config wants existence")) - return errs - } - if config.IsNull() && !plannedState.IsNull() { - errs = append(errs, path.NewErrorf("planned for existence but config wants absense")) - return errs - } - if plannedState.IsNull() { - // No further checks possible if the planned value is null - return errs - } - - impTy := schema.ImpliedType() - - for name, attrS := range schema.Attributes { - plannedV := plannedState.GetAttr(name) - configV := config.GetAttr(name) - priorV := cty.NullVal(attrS.Type) - if !priorState.IsNull() { - priorV = priorState.GetAttr(name) - } - - path := append(path, cty.GetAttrStep{Name: name}) - moreErrs := assertPlannedValueValid(attrS, priorV, configV, plannedV, path) - errs = append(errs, moreErrs...) - } - for name, blockS := range schema.BlockTypes { - path := append(path, cty.GetAttrStep{Name: name}) - plannedV := plannedState.GetAttr(name) - configV := config.GetAttr(name) - priorV := cty.NullVal(impTy.AttributeType(name)) - if !priorState.IsNull() { - priorV = priorState.GetAttr(name) - } - if plannedV.RawEquals(configV) { - // Easy path: nothing has changed at all - continue - } - if !plannedV.IsKnown() { - errs = append(errs, path.NewErrorf("attribute representing nested block must not be unknown itself; set nested attribute values to unknown instead")) - continue - } - - switch blockS.Nesting { - case configschema.NestingSingle, configschema.NestingGroup: - moreErrs := assertPlanValid(&blockS.Block, priorV, configV, plannedV, path) - errs = append(errs, moreErrs...) - case configschema.NestingList: - // A NestingList might either be a list or a tuple, depending on - // whether there are dynamically-typed attributes inside. However, - // both support a similar-enough API that we can treat them the - // same for our purposes here. - if plannedV.IsNull() { - errs = append(errs, path.NewErrorf("attribute representing a list of nested blocks must be empty to indicate no blocks, not null")) - continue - } - - plannedL := plannedV.LengthInt() - configL := configV.LengthInt() - if plannedL != configL { - errs = append(errs, path.NewErrorf("block count in plan (%d) disagrees with count in config (%d)", plannedL, configL)) - continue - } - for it := plannedV.ElementIterator(); it.Next(); { - idx, plannedEV := it.Element() - path := append(path, cty.IndexStep{Key: idx}) - if !plannedEV.IsKnown() { - errs = append(errs, path.NewErrorf("element representing nested block must not be unknown itself; set nested attribute values to unknown instead")) - continue - } - if !configV.HasIndex(idx).True() { - continue // should never happen since we checked the lengths above - } - configEV := configV.Index(idx) - priorEV := cty.NullVal(blockS.ImpliedType()) - if !priorV.IsNull() && priorV.HasIndex(idx).True() { - priorEV = priorV.Index(idx) - } - - moreErrs := assertPlanValid(&blockS.Block, priorEV, configEV, plannedEV, path) - errs = append(errs, moreErrs...) - } - case configschema.NestingMap: - if plannedV.IsNull() { - errs = append(errs, path.NewErrorf("attribute representing a map of nested blocks must be empty to indicate no blocks, not null")) - continue - } - - // A NestingMap might either be a map or an object, depending on - // whether there are dynamically-typed attributes inside, but - // that's decided statically and so all values will have the same - // kind. - if plannedV.Type().IsObjectType() { - plannedAtys := plannedV.Type().AttributeTypes() - configAtys := configV.Type().AttributeTypes() - for k := range plannedAtys { - if _, ok := configAtys[k]; !ok { - errs = append(errs, path.NewErrorf("block key %q from plan is not present in config", k)) - continue - } - path := append(path, cty.GetAttrStep{Name: k}) - - plannedEV := plannedV.GetAttr(k) - if !plannedEV.IsKnown() { - errs = append(errs, path.NewErrorf("element representing nested block must not be unknown itself; set nested attribute values to unknown instead")) - continue - } - configEV := configV.GetAttr(k) - priorEV := cty.NullVal(blockS.ImpliedType()) - if !priorV.IsNull() && priorV.Type().HasAttribute(k) { - priorEV = priorV.GetAttr(k) - } - moreErrs := assertPlanValid(&blockS.Block, priorEV, configEV, plannedEV, path) - errs = append(errs, moreErrs...) - } - for k := range configAtys { - if _, ok := plannedAtys[k]; !ok { - errs = append(errs, path.NewErrorf("block key %q from config is not present in plan", k)) - continue - } - } - } else { - plannedL := plannedV.LengthInt() - configL := configV.LengthInt() - if plannedL != configL { - errs = append(errs, path.NewErrorf("block count in plan (%d) disagrees with count in config (%d)", plannedL, configL)) - continue - } - for it := plannedV.ElementIterator(); it.Next(); { - idx, plannedEV := it.Element() - path := append(path, cty.IndexStep{Key: idx}) - if !plannedEV.IsKnown() { - errs = append(errs, path.NewErrorf("element representing nested block must not be unknown itself; set nested attribute values to unknown instead")) - continue - } - k := idx.AsString() - if !configV.HasIndex(idx).True() { - errs = append(errs, path.NewErrorf("block key %q from plan is not present in config", k)) - continue - } - configEV := configV.Index(idx) - priorEV := cty.NullVal(blockS.ImpliedType()) - if !priorV.IsNull() && priorV.HasIndex(idx).True() { - priorEV = priorV.Index(idx) - } - moreErrs := assertPlanValid(&blockS.Block, priorEV, configEV, plannedEV, path) - errs = append(errs, moreErrs...) - } - for it := configV.ElementIterator(); it.Next(); { - idx, _ := it.Element() - if !plannedV.HasIndex(idx).True() { - errs = append(errs, path.NewErrorf("block key %q from config is not present in plan", idx.AsString())) - continue - } - } - } - case configschema.NestingSet: - if plannedV.IsNull() { - errs = append(errs, path.NewErrorf("attribute representing a set of nested blocks must be empty to indicate no blocks, not null")) - continue - } - - // Because set elements have no identifier with which to correlate - // them, we can't robustly validate the plan for a nested block - // backed by a set, and so unfortunately we need to just trust the - // provider to do the right thing. :( - // - // (In principle we could correlate elements by matching the - // subset of attributes explicitly set in config, except for the - // special diff suppression rule which allows for there to be a - // planned value that is constructed by mixing part of a prior - // value with part of a config value, creating an entirely new - // element that is not present in either prior nor config.) - for it := plannedV.ElementIterator(); it.Next(); { - idx, plannedEV := it.Element() - path := append(path, cty.IndexStep{Key: idx}) - if !plannedEV.IsKnown() { - errs = append(errs, path.NewErrorf("element representing nested block must not be unknown itself; set nested attribute values to unknown instead")) - continue - } - } - - default: - panic(fmt.Sprintf("unsupported nesting mode %s", blockS.Nesting)) - } - } - - return errs -} - -func assertPlannedValueValid(attrS *configschema.Attribute, priorV, configV, plannedV cty.Value, path cty.Path) []error { - var errs []error - if plannedV.RawEquals(configV) { - // This is the easy path: provider didn't change anything at all. - return errs - } - if plannedV.RawEquals(priorV) && !priorV.IsNull() { - // Also pretty easy: there is a prior value and the provider has - // returned it unchanged. This indicates that configV and plannedV - // are functionally equivalent and so the provider wishes to disregard - // the configuration value in favor of the prior. - return errs - } - if attrS.Computed && configV.IsNull() { - // The provider is allowed to change the value of any computed - // attribute that isn't explicitly set in the config. - return errs - } - - // If none of the above conditions match, the provider has made an invalid - // change to this attribute. - if priorV.IsNull() { - if attrS.Sensitive { - errs = append(errs, path.NewErrorf("sensitive planned value does not match config value")) - } else { - errs = append(errs, path.NewErrorf("planned value %#v does not match config value %#v", plannedV, configV)) - } - return errs - } - if attrS.Sensitive { - errs = append(errs, path.NewErrorf("sensitive planned value does not match config value nor prior value")) - } else { - errs = append(errs, path.NewErrorf("planned value %#v does not match config value %#v nor prior value %#v", plannedV, configV, priorV)) - } - return errs -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/plan.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/plan.go deleted file mode 100644 index 0abed56a0ff..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/plan.go +++ /dev/null @@ -1,92 +0,0 @@ -package plans - -import ( - "sort" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/zclconf/go-cty/cty" -) - -// Plan is the top-level type representing a planned set of changes. -// -// A plan is a summary of the set of changes required to move from a current -// state to a goal state derived from configuration. The described changes -// are not applied directly, but contain an approximation of the final -// result that will be completed during apply by resolving any values that -// cannot be predicted. -// -// A plan must always be accompanied by the state and configuration it was -// built from, since the plan does not itself include all of the information -// required to make the changes indicated. -type Plan struct { - VariableValues map[string]DynamicValue - Changes *Changes - TargetAddrs []addrs.Targetable - ProviderSHA256s map[string][]byte - Backend Backend -} - -// Backend represents the backend-related configuration and other data as it -// existed when a plan was created. -type Backend struct { - // Type is the type of backend that the plan will apply against. - Type string - - // Config is the configuration of the backend, whose schema is decided by - // the backend Type. - Config DynamicValue - - // Workspace is the name of the workspace that was active when the plan - // was created. It is illegal to apply a plan created for one workspace - // to the state of another workspace. - // (This constraint is already enforced by the statefile lineage mechanism, - // but storing this explicitly allows us to return a better error message - // in the situation where the user has the wrong workspace selected.) - Workspace string -} - -func NewBackend(typeName string, config cty.Value, configSchema *configschema.Block, workspaceName string) (*Backend, error) { - dv, err := NewDynamicValue(config, configSchema.ImpliedType()) - if err != nil { - return nil, err - } - - return &Backend{ - Type: typeName, - Config: dv, - Workspace: workspaceName, - }, nil -} - -// ProviderAddrs returns a list of all of the provider configuration addresses -// referenced throughout the receiving plan. -// -// The result is de-duplicated so that each distinct address appears only once. -func (p *Plan) ProviderAddrs() []addrs.AbsProviderConfig { - if p == nil || p.Changes == nil { - return nil - } - - m := map[string]addrs.AbsProviderConfig{} - for _, rc := range p.Changes.Resources { - m[rc.ProviderAddr.String()] = rc.ProviderAddr - } - if len(m) == 0 { - return nil - } - - // This is mainly just so we'll get stable results for testing purposes. - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) - - ret := make([]addrs.AbsProviderConfig, len(keys)) - for i, key := range keys { - ret[i] = m[key] - } - - return ret -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/convert/diagnostics.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/convert/diagnostics.go deleted file mode 100644 index f20f0507e96..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/convert/diagnostics.go +++ /dev/null @@ -1,132 +0,0 @@ -package convert - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - proto "github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5" - "github.com/zclconf/go-cty/cty" -) - -// WarnsAndErrorsToProto converts the warnings and errors return by the legacy -// provider to protobuf diagnostics. -func WarnsAndErrsToProto(warns []string, errs []error) (diags []*proto.Diagnostic) { - for _, w := range warns { - diags = AppendProtoDiag(diags, w) - } - - for _, e := range errs { - diags = AppendProtoDiag(diags, e) - } - - return diags -} - -// AppendProtoDiag appends a new diagnostic from a warning string or an error. -// This panics if d is not a string or error. -func AppendProtoDiag(diags []*proto.Diagnostic, d interface{}) []*proto.Diagnostic { - switch d := d.(type) { - case cty.PathError: - ap := PathToAttributePath(d.Path) - diags = append(diags, &proto.Diagnostic{ - Severity: proto.Diagnostic_ERROR, - Summary: d.Error(), - Attribute: ap, - }) - case error: - diags = append(diags, &proto.Diagnostic{ - Severity: proto.Diagnostic_ERROR, - Summary: d.Error(), - }) - case string: - diags = append(diags, &proto.Diagnostic{ - Severity: proto.Diagnostic_WARNING, - Summary: d, - }) - case *proto.Diagnostic: - diags = append(diags, d) - case []*proto.Diagnostic: - diags = append(diags, d...) - } - return diags -} - -// ProtoToDiagnostics converts a list of proto.Diagnostics to a tf.Diagnostics. -func ProtoToDiagnostics(ds []*proto.Diagnostic) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - for _, d := range ds { - var severity tfdiags.Severity - - switch d.Severity { - case proto.Diagnostic_ERROR: - severity = tfdiags.Error - case proto.Diagnostic_WARNING: - severity = tfdiags.Warning - } - - var newDiag tfdiags.Diagnostic - - // if there's an attribute path, we need to create a AttributeValue diagnostic - if d.Attribute != nil { - path := AttributePathToPath(d.Attribute) - newDiag = tfdiags.AttributeValue(severity, d.Summary, d.Detail, path) - } else { - newDiag = tfdiags.WholeContainingBody(severity, d.Summary, d.Detail) - } - - diags = diags.Append(newDiag) - } - - return diags -} - -// AttributePathToPath takes the proto encoded path and converts it to a cty.Path -func AttributePathToPath(ap *proto.AttributePath) cty.Path { - var p cty.Path - for _, step := range ap.Steps { - switch selector := step.Selector.(type) { - case *proto.AttributePath_Step_AttributeName: - p = p.GetAttr(selector.AttributeName) - case *proto.AttributePath_Step_ElementKeyString: - p = p.Index(cty.StringVal(selector.ElementKeyString)) - case *proto.AttributePath_Step_ElementKeyInt: - p = p.Index(cty.NumberIntVal(selector.ElementKeyInt)) - } - } - return p -} - -// AttributePathToPath takes a cty.Path and converts it to a proto-encoded path. -func PathToAttributePath(p cty.Path) *proto.AttributePath { - ap := &proto.AttributePath{} - for _, step := range p { - switch selector := step.(type) { - case cty.GetAttrStep: - ap.Steps = append(ap.Steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_AttributeName{ - AttributeName: selector.Name, - }, - }) - case cty.IndexStep: - key := selector.Key - switch key.Type() { - case cty.String: - ap.Steps = append(ap.Steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_ElementKeyString{ - ElementKeyString: key.AsString(), - }, - }) - case cty.Number: - v, _ := key.AsBigFloat().Int64() - ap.Steps = append(ap.Steps, &proto.AttributePath_Step{ - Selector: &proto.AttributePath_Step_ElementKeyInt{ - ElementKeyInt: v, - }, - }) - default: - // We'll bail early if we encounter anything else, and just - // return the valid prefix. - return ap - } - } - } - return ap -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/convert/schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/convert/schema.go deleted file mode 100644 index 88b8a9a6992..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/convert/schema.go +++ /dev/null @@ -1,192 +0,0 @@ -package convert - -import ( - "encoding/json" - "log" - "reflect" - "sort" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - proto "github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5" -) - -// ConfigSchemaToProto takes a *configschema.Block and converts it to a -// proto.Schema_Block for a grpc response. -func ConfigSchemaToProto(b *configschema.Block) *proto.Schema_Block { - block := &proto.Schema_Block{ - Description: b.Description, - DescriptionKind: protoStringKind(b.DescriptionKind), - Deprecated: b.Deprecated, - } - - for _, name := range sortedKeys(b.Attributes) { - a := b.Attributes[name] - - attr := &proto.Schema_Attribute{ - Name: name, - Description: a.Description, - DescriptionKind: protoStringKind(a.DescriptionKind), - Optional: a.Optional, - Computed: a.Computed, - Required: a.Required, - Sensitive: a.Sensitive, - Deprecated: a.Deprecated, - } - - ty, err := json.Marshal(a.Type) - if err != nil { - panic(err) - } - - attr.Type = ty - - block.Attributes = append(block.Attributes, attr) - } - - for _, name := range sortedKeys(b.BlockTypes) { - b := b.BlockTypes[name] - block.BlockTypes = append(block.BlockTypes, protoSchemaNestedBlock(name, b)) - } - - return block -} - -func protoStringKind(k configschema.StringKind) proto.StringKind { - switch k { - default: - log.Printf("[TRACE] unexpected configschema.StringKind: %d", k) - return proto.StringKind_PLAIN - case configschema.StringPlain: - return proto.StringKind_PLAIN - case configschema.StringMarkdown: - return proto.StringKind_MARKDOWN - } -} - -func protoSchemaNestedBlock(name string, b *configschema.NestedBlock) *proto.Schema_NestedBlock { - var nesting proto.Schema_NestedBlock_NestingMode - switch b.Nesting { - case configschema.NestingSingle: - nesting = proto.Schema_NestedBlock_SINGLE - case configschema.NestingGroup: - nesting = proto.Schema_NestedBlock_GROUP - case configschema.NestingList: - nesting = proto.Schema_NestedBlock_LIST - case configschema.NestingSet: - nesting = proto.Schema_NestedBlock_SET - case configschema.NestingMap: - nesting = proto.Schema_NestedBlock_MAP - default: - nesting = proto.Schema_NestedBlock_INVALID - } - return &proto.Schema_NestedBlock{ - TypeName: name, - Block: ConfigSchemaToProto(&b.Block), - Nesting: nesting, - MinItems: int64(b.MinItems), - MaxItems: int64(b.MaxItems), - } -} - -// ProtoToProviderSchema takes a proto.Schema and converts it to a providers.Schema. -func ProtoToProviderSchema(s *proto.Schema) providers.Schema { - return providers.Schema{ - Version: s.Version, - Block: ProtoToConfigSchema(s.Block), - } -} - -// ProtoToConfigSchema takes the GetSchcema_Block from a grpc response and converts it -// to a terraform *configschema.Block. -func ProtoToConfigSchema(b *proto.Schema_Block) *configschema.Block { - block := &configschema.Block{ - Attributes: make(map[string]*configschema.Attribute), - BlockTypes: make(map[string]*configschema.NestedBlock), - - Description: b.Description, - DescriptionKind: schemaStringKind(b.DescriptionKind), - Deprecated: b.Deprecated, - } - - for _, a := range b.Attributes { - attr := &configschema.Attribute{ - Description: a.Description, - DescriptionKind: schemaStringKind(a.DescriptionKind), - Required: a.Required, - Optional: a.Optional, - Computed: a.Computed, - Sensitive: a.Sensitive, - Deprecated: a.Deprecated, - } - - if err := json.Unmarshal(a.Type, &attr.Type); err != nil { - panic(err) - } - - block.Attributes[a.Name] = attr - } - - for _, b := range b.BlockTypes { - block.BlockTypes[b.TypeName] = schemaNestedBlock(b) - } - - return block -} - -func schemaStringKind(k proto.StringKind) configschema.StringKind { - switch k { - default: - log.Printf("[TRACE] unexpected proto.StringKind: %d", k) - return configschema.StringPlain - case proto.StringKind_PLAIN: - return configschema.StringPlain - case proto.StringKind_MARKDOWN: - return configschema.StringMarkdown - } -} - -func schemaNestedBlock(b *proto.Schema_NestedBlock) *configschema.NestedBlock { - var nesting configschema.NestingMode - switch b.Nesting { - case proto.Schema_NestedBlock_SINGLE: - nesting = configschema.NestingSingle - case proto.Schema_NestedBlock_GROUP: - nesting = configschema.NestingGroup - case proto.Schema_NestedBlock_LIST: - nesting = configschema.NestingList - case proto.Schema_NestedBlock_MAP: - nesting = configschema.NestingMap - case proto.Schema_NestedBlock_SET: - nesting = configschema.NestingSet - default: - // In all other cases we'll leave it as the zero value (invalid) and - // let the caller validate it and deal with this. - } - - nb := &configschema.NestedBlock{ - Nesting: nesting, - MinItems: int(b.MinItems), - MaxItems: int(b.MaxItems), - } - - nested := ProtoToConfigSchema(b.Block) - nb.Block = *nested - return nb -} - -// sortedKeys returns the lexically sorted keys from the given map. This is -// used to make schema conversions are deterministic. This panics if map keys -// are not a string. -func sortedKeys(m interface{}) []string { - v := reflect.ValueOf(m) - keys := make([]string, v.Len()) - - mapKeys := v.MapKeys() - for i, k := range mapKeys { - keys[i] = k.Interface().(string) - } - - sort.Strings(keys) - return keys -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/error.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/error.go deleted file mode 100644 index 729e97099e3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/error.go +++ /dev/null @@ -1,64 +0,0 @@ -package discovery - -// Error is a type used to describe situations that the caller must handle -// since they indicate some form of user error. -// -// The functions and methods that return these specialized errors indicate so -// in their documentation. The Error type should not itself be used directly, -// but rather errors should be compared using the == operator with the -// error constants in this package. -// -// Values of this type are _not_ used when the error being reported is an -// operational error (server unavailable, etc) or indicative of a bug in -// this package or its caller. -type Error string - -// ErrorNoSuitableVersion indicates that a suitable version (meeting given -// constraints) is not available. -const ErrorNoSuitableVersion = Error("no suitable version is available") - -// ErrorNoVersionCompatible indicates that all of the available versions -// that otherwise met constraints are not compatible with the current -// version of Terraform. -const ErrorNoVersionCompatible = Error("no available version is compatible with this version of Terraform") - -// ErrorVersionIncompatible indicates that all of the versions within the -// constraints are not compatible with the current version of Terrafrom, though -// there does exist a version outside of the constaints that is compatible. -const ErrorVersionIncompatible = Error("incompatible provider version") - -// ErrorNoSuchProvider indicates that no provider exists with a name given -const ErrorNoSuchProvider = Error("no provider exists with the given name") - -// ErrorNoVersionCompatibleWithPlatform indicates that all of the available -// versions that otherwise met constraints are not compatible with the -// requested platform -const ErrorNoVersionCompatibleWithPlatform = Error("no available version is compatible for the requested platform") - -// ErrorMissingChecksumVerification indicates that either the provider -// distribution is missing the SHA256SUMS file or the checksum file does -// not contain a checksum for the binary plugin -const ErrorMissingChecksumVerification = Error("unable to verify checksum") - -// ErrorChecksumVerification indicates that the current checksum of the -// provider plugin has changed since the initial release and is not trusted -// to download -const ErrorChecksumVerification = Error("unexpected plugin checksum") - -// ErrorSignatureVerification indicates that the digital signature for a -// provider distribution could not be verified for one of the following -// reasons: missing signature file, missing public key, or the signature -// was not signed by any known key for the publisher -const ErrorSignatureVerification = Error("unable to verify signature") - -// ErrorServiceUnreachable indicates that the network was unable to connect -// to the registry service -const ErrorServiceUnreachable = Error("registry service is unreachable") - -// ErrorPublicRegistryUnreachable indicates that the network was unable to connect -// to the public registry in particular, so we can show a link to the statuspage -const ErrorPublicRegistryUnreachable = Error("registry service is unreachable, check https://status.hashicorp.com/ for status updates") - -func (err Error) Error() string { - return string(err) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/find.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/find.go deleted file mode 100644 index f053312b00d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/find.go +++ /dev/null @@ -1,191 +0,0 @@ -package discovery - -import ( - "io/ioutil" - "log" - "os" - "path/filepath" - "strings" -) - -// FindPlugins looks in the given directories for files whose filenames -// suggest that they are plugins of the given kind (e.g. "provider") and -// returns a PluginMetaSet representing the discovered potential-plugins. -// -// Currently this supports two different naming schemes. The current -// standard naming scheme is a subdirectory called $GOOS-$GOARCH containing -// files named terraform-$KIND-$NAME-V$VERSION. The legacy naming scheme is -// files directly in the given directory whose names are like -// terraform-$KIND-$NAME. -// -// Only one plugin will be returned for each unique plugin (name, version) -// pair, with preference given to files found in earlier directories. -// -// This is a convenience wrapper around FindPluginPaths and ResolvePluginsPaths. -func FindPlugins(kind string, dirs []string) PluginMetaSet { - return ResolvePluginPaths(FindPluginPaths(kind, dirs)) -} - -// FindPluginPaths looks in the given directories for files whose filenames -// suggest that they are plugins of the given kind (e.g. "provider"). -// -// The return value is a list of absolute paths that appear to refer to -// plugins in the given directories, based only on what can be inferred -// from the naming scheme. The paths returned are ordered such that files -// in later dirs appear after files in earlier dirs in the given directory -// list. Within the same directory plugins are returned in a consistent but -// undefined order. -func FindPluginPaths(kind string, dirs []string) []string { - // This is just a thin wrapper around findPluginPaths so that we can - // use the latter in tests with a fake machineName so we can use our - // test fixtures. - return findPluginPaths(kind, dirs) -} - -func findPluginPaths(kind string, dirs []string) []string { - prefix := "terraform-" + kind + "-" - - ret := make([]string, 0, len(dirs)) - - for _, dir := range dirs { - items, err := ioutil.ReadDir(dir) - if err != nil { - // Ignore missing dirs, non-dirs, etc - continue - } - - log.Printf("[DEBUG] checking for %s in %q", kind, dir) - - for _, item := range items { - fullName := item.Name() - - if !strings.HasPrefix(fullName, prefix) { - continue - } - - // New-style paths must have a version segment in filename - if strings.Contains(strings.ToLower(fullName), "_v") { - absPath, err := filepath.Abs(filepath.Join(dir, fullName)) - if err != nil { - log.Printf("[ERROR] plugin filepath error: %s", err) - continue - } - - // Check that the file we found is usable - if !pathIsFile(absPath) { - log.Printf("[ERROR] ignoring non-file %s", absPath) - continue - } - - log.Printf("[DEBUG] found %s %q", kind, fullName) - ret = append(ret, filepath.Clean(absPath)) - continue - } - - // Legacy style with files directly in the base directory - absPath, err := filepath.Abs(filepath.Join(dir, fullName)) - if err != nil { - log.Printf("[ERROR] plugin filepath error: %s", err) - continue - } - - // Check that the file we found is usable - if !pathIsFile(absPath) { - log.Printf("[ERROR] ignoring non-file %s", absPath) - continue - } - - log.Printf("[WARN] found legacy %s %q", kind, fullName) - - ret = append(ret, filepath.Clean(absPath)) - } - } - - return ret -} - -// Returns true if and only if the given path refers to a file or a symlink -// to a file. -func pathIsFile(path string) bool { - info, err := os.Stat(path) - if err != nil { - return false - } - - return !info.IsDir() -} - -// ResolvePluginPaths takes a list of paths to plugin executables (as returned -// by e.g. FindPluginPaths) and produces a PluginMetaSet describing the -// referenced plugins. -// -// If the same combination of plugin name and version appears multiple times, -// the earlier reference will be preferred. Several different versions of -// the same plugin name may be returned, in which case the methods of -// PluginMetaSet can be used to filter down. -func ResolvePluginPaths(paths []string) PluginMetaSet { - s := make(PluginMetaSet) - - type nameVersion struct { - Name string - Version string - } - found := make(map[nameVersion]struct{}) - - for _, path := range paths { - baseName := strings.ToLower(filepath.Base(path)) - if !strings.HasPrefix(baseName, "terraform-") { - // Should never happen with reasonable input - continue - } - - baseName = baseName[10:] - firstDash := strings.Index(baseName, "-") - if firstDash == -1 { - // Should never happen with reasonable input - continue - } - - baseName = baseName[firstDash+1:] - if baseName == "" { - // Should never happen with reasonable input - continue - } - - // Trim the .exe suffix used on Windows before we start wrangling - // the remainder of the path. - if strings.HasSuffix(baseName, ".exe") { - baseName = baseName[:len(baseName)-4] - } - - parts := strings.SplitN(baseName, "_v", 2) - name := parts[0] - version := VersionZero - if len(parts) == 2 { - version = parts[1] - } - - // Auto-installed plugins contain an extra name portion representing - // the expected plugin version, which we must trim off. - if underX := strings.Index(version, "_x"); underX != -1 { - version = version[:underX] - } - - if _, ok := found[nameVersion{name, version}]; ok { - // Skip duplicate versions of the same plugin - // (We do this during this step because after this we will be - // dealing with sets and thus lose our ordering with which to - // decide preference.) - continue - } - - s.Add(PluginMeta{ - Name: name, - Version: VersionStr(version), - Path: path, - }) - found[nameVersion{name, version}] = struct{}{} - } - - return s -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/get.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/get.go deleted file mode 100644 index 722bb28a2c4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/get.go +++ /dev/null @@ -1,669 +0,0 @@ -package discovery - -import ( - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "os" - "path/filepath" - "runtime" - "strconv" - "strings" - - "github.com/hashicorp/errwrap" - getter "github.com/hashicorp/go-getter" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/httpclient" - "github.com/hashicorp/terraform-plugin-sdk/internal/registry" - "github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc" - "github.com/hashicorp/terraform-plugin-sdk/internal/registry/response" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - tfversion "github.com/hashicorp/terraform-plugin-sdk/internal/version" - "github.com/hashicorp/terraform-svchost/disco" - "github.com/mitchellh/cli" -) - -// Releases are located by querying the terraform registry. - -var httpClient *http.Client - -func init() { - httpClient = httpclient.New() - - httpGetter := &getter.HttpGetter{ - Client: httpClient, - Netrc: true, - } - - getter.Getters["http"] = httpGetter - getter.Getters["https"] = httpGetter -} - -// ProviderInstaller is an Installer implementation that knows how to -// download Terraform providers from the official HashiCorp releases service -// into a local directory. The files downloaded are compliant with the -// naming scheme expected by FindPlugins, so the target directory of a -// provider installer can be used as one of several plugin discovery sources. -type ProviderInstaller struct { - Dir string - - // Cache is used to access and update a local cache of plugins if non-nil. - // Can be nil to disable caching. - Cache PluginCache - - PluginProtocolVersion uint - - // OS and Arch specify the OS and architecture that should be used when - // installing plugins. These use the same labels as the runtime.GOOS and - // runtime.GOARCH variables respectively, and indeed the values of these - // are used as defaults if either of these is the empty string. - OS string - Arch string - - // Skip checksum and signature verification - SkipVerify bool - - Ui cli.Ui // Ui for output - - // Services is a required *disco.Disco, which may have services and - // credentials pre-loaded. - Services *disco.Disco - - // registry client - registry *registry.Client -} - -// Get is part of an implementation of type Installer, and attempts to download -// and install a Terraform provider matching the given constraints. -// -// This method may return one of a number of sentinel errors from this -// package to indicate issues that are likely to be resolvable via user action: -// -// ErrorNoSuchProvider: no provider with the given name exists in the repository. -// ErrorNoSuitableVersion: the provider exists but no available version matches constraints. -// ErrorNoVersionCompatible: a plugin was found within the constraints but it is -// incompatible with the current Terraform version. -// -// These errors should be recognized and handled as special cases by the caller -// to present a suitable user-oriented error message. -// -// All other errors indicate an internal problem that is likely _not_ solvable -// through user action, or at least not within Terraform's scope. Error messages -// are produced under the assumption that if presented to the user they will -// be presented alongside context about what is being installed, and thus the -// error messages do not redundantly include such information. -func (i *ProviderInstaller) Get(provider addrs.ProviderType, req Constraints) (PluginMeta, tfdiags.Diagnostics, error) { - var diags tfdiags.Diagnostics - - // a little bit of initialization. - if i.OS == "" { - i.OS = runtime.GOOS - } - if i.Arch == "" { - i.Arch = runtime.GOARCH - } - if i.registry == nil { - i.registry = registry.NewClient(i.Services, nil) - } - - // get a full listing of versions for the requested provider - allVersions, err := i.listProviderVersions(provider) - - // TODO: return multiple errors - if err != nil { - log.Printf("[DEBUG] %s", err) - if registry.IsServiceUnreachable(err) { - registryHost, err := i.hostname() - if err == nil && registryHost == regsrc.PublicRegistryHost.Raw { - return PluginMeta{}, diags, ErrorPublicRegistryUnreachable - } - return PluginMeta{}, diags, ErrorServiceUnreachable - } - if registry.IsServiceNotProvided(err) { - return PluginMeta{}, diags, err - } - return PluginMeta{}, diags, ErrorNoSuchProvider - } - - // Add any warnings from the response to diags - for _, warning := range allVersions.Warnings { - hostname, err := i.hostname() - if err != nil { - return PluginMeta{}, diags, err - } - diag := tfdiags.SimpleWarning(fmt.Sprintf("%s: %s", hostname, warning)) - diags = diags.Append(diag) - } - - if len(allVersions.Versions) == 0 { - return PluginMeta{}, diags, ErrorNoSuitableVersion - } - providerSource := allVersions.ID - - // Filter the list of plugin versions to those which meet the version constraints - versions := allowedVersions(allVersions, req) - if len(versions) == 0 { - return PluginMeta{}, diags, ErrorNoSuitableVersion - } - - // sort them newest to oldest. The newest version wins! - response.ProviderVersionCollection(versions).Sort() - - // if the chosen provider version does not support the requested platform, - // filter the list of acceptable versions to those that support that platform - if err := i.checkPlatformCompatibility(versions[0]); err != nil { - versions = i.platformCompatibleVersions(versions) - if len(versions) == 0 { - return PluginMeta{}, diags, ErrorNoVersionCompatibleWithPlatform - } - } - - // we now have a winning platform-compatible version - versionMeta := versions[0] - v := VersionStr(versionMeta.Version).MustParse() - - // check protocol compatibility - if err := i.checkPluginProtocol(versionMeta); err != nil { - closestMatch, err := i.findClosestProtocolCompatibleVersion(allVersions.Versions) - if err != nil { - // No operation here if we can't find a version with compatible protocol - return PluginMeta{}, diags, err - } - - // Prompt version suggestion to UI based on closest protocol match - var errMsg string - closestVersion := VersionStr(closestMatch.Version).MustParse() - if v.NewerThan(closestVersion) { - errMsg = providerProtocolTooNew - } else { - errMsg = providerProtocolTooOld - } - - constraintStr := req.String() - if constraintStr == "" { - constraintStr = "(any version)" - } - - return PluginMeta{}, diags, errwrap.Wrap(ErrorVersionIncompatible, fmt.Errorf(fmt.Sprintf( - errMsg, provider, v.String(), tfversion.String(), - closestVersion.String(), closestVersion.MinorUpgradeConstraintStr(), constraintStr))) - } - - downloadURLs, err := i.listProviderDownloadURLs(providerSource, versionMeta.Version) - if err != nil { - return PluginMeta{}, diags, err - } - providerURL := downloadURLs.DownloadURL - - if !i.SkipVerify { - // Terraform verifies the integrity of a provider release before downloading - // the plugin binary. The digital signature (SHA256SUMS.sig) on the - // release distribution (SHA256SUMS) is verified with the public key of the - // publisher provided in the Terraform Registry response, ensuring that - // everything is as intended by the publisher. The checksum of the provider - // plugin is expected in the SHA256SUMS file and is double checked to match - // the checksum of the original published release to the Registry. This - // enforces immutability of releases between the Registry and the plugin's - // host location. Lastly, the integrity of the binary is verified upon - // download matches the Registry and signed checksum. - sha256, err := i.getProviderChecksum(downloadURLs) - if err != nil { - return PluginMeta{}, diags, err - } - - // add the checksum parameter for go-getter to verify the download for us. - if sha256 != "" { - providerURL = providerURL + "?checksum=sha256:" + sha256 - } - } - - printedProviderName := fmt.Sprintf("%q (%s)", provider.Name, providerSource) - i.Ui.Info(fmt.Sprintf("- Downloading plugin for provider %s %s...", printedProviderName, versionMeta.Version)) - log.Printf("[DEBUG] getting provider %s version %q", printedProviderName, versionMeta.Version) - err = i.install(provider, v, providerURL) - if err != nil { - return PluginMeta{}, diags, err - } - - // Find what we just installed - // (This is weird, because go-getter doesn't directly return - // information about what was extracted, and we just extracted - // the archive directly into a shared dir here.) - log.Printf("[DEBUG] looking for the %s %s plugin we just installed", provider.Name, versionMeta.Version) - metas := FindPlugins("provider", []string{i.Dir}) - log.Printf("[DEBUG] all plugins found %#v", metas) - metas, _ = metas.ValidateVersions() - metas = metas.WithName(provider.Name).WithVersion(v) - log.Printf("[DEBUG] filtered plugins %#v", metas) - if metas.Count() == 0 { - // This should never happen. Suggests that the release archive - // contains an executable file whose name doesn't match the - // expected convention. - return PluginMeta{}, diags, fmt.Errorf( - "failed to find installed plugin version %s; this is a bug in Terraform and should be reported", - versionMeta.Version, - ) - } - - if metas.Count() > 1 { - // This should also never happen, and suggests that a - // particular version was re-released with a different - // executable filename. We consider releases as immutable, so - // this is an error. - return PluginMeta{}, diags, fmt.Errorf( - "multiple plugins installed for version %s; this is a bug in Terraform and should be reported", - versionMeta.Version, - ) - } - - // By now we know we have exactly one meta, and so "Newest" will - // return that one. - return metas.Newest(), diags, nil -} - -func (i *ProviderInstaller) install(provider addrs.ProviderType, version Version, url string) error { - if i.Cache != nil { - log.Printf("[DEBUG] looking for provider %s %s in plugin cache", provider.Name, version) - cached := i.Cache.CachedPluginPath("provider", provider.Name, version) - if cached == "" { - log.Printf("[DEBUG] %s %s not yet in cache, so downloading %s", provider.Name, version, url) - err := getter.Get(i.Cache.InstallDir(), url) - if err != nil { - return err - } - // should now be in cache - cached = i.Cache.CachedPluginPath("provider", provider.Name, version) - if cached == "" { - // should never happen if the getter is behaving properly - // and the plugins are packaged properly. - return fmt.Errorf("failed to find downloaded plugin in cache %s", i.Cache.InstallDir()) - } - } - - // Link or copy the cached binary into our install dir so the - // normal resolution machinery can find it. - filename := filepath.Base(cached) - targetPath := filepath.Join(i.Dir, filename) - // check if the target dir exists, and create it if not - var err error - if _, StatErr := os.Stat(i.Dir); os.IsNotExist(StatErr) { - err = os.MkdirAll(i.Dir, 0700) - } - if err != nil { - return err - } - - log.Printf("[DEBUG] installing %s %s to %s from local cache %s", provider.Name, version, targetPath, cached) - - // Delete if we can. If there's nothing there already then no harm done. - // This is important because we can't create a link if there's - // already a file of the same name present. - // (any other error here we'll catch below when we try to write here) - os.Remove(targetPath) - - // We don't attempt linking on Windows because links are not - // comprehensively supported by all tools/apps in Windows and - // so we choose to be conservative to avoid creating any - // weird issues for Windows users. - linkErr := errors.New("link not supported for Windows") // placeholder error, never actually returned - if runtime.GOOS != "windows" { - // Try hard linking first. Hard links are preferable because this - // creates a self-contained directory that doesn't depend on the - // cache after install. - linkErr = os.Link(cached, targetPath) - - // If that failed, try a symlink. This _does_ depend on the cache - // after install, so the user must manage the cache more carefully - // in this case, but avoids creating redundant copies of the - // plugins on disk. - if linkErr != nil { - linkErr = os.Symlink(cached, targetPath) - } - } - - // If we still have an error then we'll try a copy as a fallback. - // In this case either the OS is Windows or the target filesystem - // can't support symlinks. - if linkErr != nil { - srcFile, err := os.Open(cached) - if err != nil { - return fmt.Errorf("failed to open cached plugin %s: %s", cached, err) - } - defer srcFile.Close() - - destFile, err := os.OpenFile(targetPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, os.ModePerm) - if err != nil { - return fmt.Errorf("failed to create %s: %s", targetPath, err) - } - - _, err = io.Copy(destFile, srcFile) - if err != nil { - destFile.Close() - return fmt.Errorf("failed to copy cached plugin from %s to %s: %s", cached, targetPath, err) - } - - err = destFile.Close() - if err != nil { - return fmt.Errorf("error creating %s: %s", targetPath, err) - } - } - - // One way or another, by the time we get here we should have either - // a link or a copy of the cached plugin within i.Dir, as expected. - } else { - log.Printf("[DEBUG] plugin cache is disabled, so downloading %s %s from %s", provider.Name, version, url) - err := getter.Get(i.Dir, url) - if err != nil { - return err - } - } - return nil -} - -func (i *ProviderInstaller) PurgeUnused(used map[string]PluginMeta) (PluginMetaSet, error) { - purge := make(PluginMetaSet) - - present := FindPlugins("provider", []string{i.Dir}) - for meta := range present { - chosen, ok := used[meta.Name] - if !ok { - purge.Add(meta) - } - if chosen.Path != meta.Path { - purge.Add(meta) - } - } - - removed := make(PluginMetaSet) - var errs error - for meta := range purge { - path := meta.Path - err := os.Remove(path) - if err != nil { - errs = multierror.Append(errs, fmt.Errorf( - "failed to remove unused provider plugin %s: %s", - path, err, - )) - } else { - removed.Add(meta) - } - } - - return removed, errs -} - -func (i *ProviderInstaller) getProviderChecksum(resp *response.TerraformProviderPlatformLocation) (string, error) { - // Get SHA256SUMS file. - shasums, err := getFile(resp.ShasumsURL) - if err != nil { - log.Printf("[ERROR] error fetching checksums from %q: %s", resp.ShasumsURL, err) - return "", ErrorMissingChecksumVerification - } - - // Get SHA256SUMS.sig file. - signature, err := getFile(resp.ShasumsSignatureURL) - if err != nil { - log.Printf("[ERROR] error fetching checksums signature from %q: %s", resp.ShasumsSignatureURL, err) - return "", ErrorSignatureVerification - } - - // Verify the GPG signature returned from the Registry. - asciiArmor := resp.SigningKeys.GPGASCIIArmor() - signer, err := verifySig(shasums, signature, asciiArmor) - if err != nil { - log.Printf("[ERROR] error verifying signature: %s", err) - return "", ErrorSignatureVerification - } - - // Also verify the GPG signature against the HashiCorp public key. This is - // a temporary additional check until a more robust key verification - // process is added in a future release. - _, err = verifySig(shasums, signature, HashicorpPublicKey) - if err != nil { - log.Printf("[ERROR] error verifying signature against HashiCorp public key: %s", err) - return "", ErrorSignatureVerification - } - - // Display identity for GPG key which succeeded verifying the signature. - // This could also be used to display to the user with i.Ui.Info(). - identities := []string{} - for k := range signer.Identities { - identities = append(identities, k) - } - identity := strings.Join(identities, ", ") - log.Printf("[DEBUG] verified GPG signature with key from %s", identity) - - // Extract checksum for this os/arch platform binary and verify against Registry - checksum := checksumForFile(shasums, resp.Filename) - if checksum == "" { - log.Printf("[ERROR] missing checksum for %s from source %s", resp.Filename, resp.ShasumsURL) - return "", ErrorMissingChecksumVerification - } else if checksum != resp.Shasum { - log.Printf("[ERROR] unexpected checksum for %s from source %q", resp.Filename, resp.ShasumsURL) - return "", ErrorChecksumVerification - } - - return checksum, nil -} - -func (i *ProviderInstaller) hostname() (string, error) { - provider := regsrc.NewTerraformProvider("", i.OS, i.Arch) - svchost, err := provider.SvcHost() - if err != nil { - return "", err - } - - return svchost.ForDisplay(), nil -} - -// list all versions available for the named provider -func (i *ProviderInstaller) listProviderVersions(provider addrs.ProviderType) (*response.TerraformProviderVersions, error) { - req := regsrc.NewTerraformProvider(provider.Name, i.OS, i.Arch) - versions, err := i.registry.TerraformProviderVersions(req) - return versions, err -} - -func (i *ProviderInstaller) listProviderDownloadURLs(name, version string) (*response.TerraformProviderPlatformLocation, error) { - urls, err := i.registry.TerraformProviderLocation(regsrc.NewTerraformProvider(name, i.OS, i.Arch), version) - if urls == nil { - return nil, fmt.Errorf("No download urls found for provider %s", name) - } - return urls, err -} - -// findClosestProtocolCompatibleVersion searches for the provider version with the closest protocol match. -// Prerelease versions are filtered. -func (i *ProviderInstaller) findClosestProtocolCompatibleVersion(versions []*response.TerraformProviderVersion) (*response.TerraformProviderVersion, error) { - // Loop through all the provider versions to find the earliest and latest - // versions that match the installer protocol to then select the closest of the two - var latest, earliest *response.TerraformProviderVersion - for _, version := range versions { - // Prereleases are filtered and will not be suggested - v, err := VersionStr(version.Version).Parse() - if err != nil || v.IsPrerelease() { - continue - } - - if err := i.checkPluginProtocol(version); err == nil { - if earliest == nil { - // Found the first provider version with compatible protocol - earliest = version - } - // Update the latest protocol compatible version - latest = version - } - } - if earliest == nil { - // No compatible protocol was found for any version - return nil, ErrorNoVersionCompatible - } - - // Convert protocols to comparable types - protoString := strconv.Itoa(int(i.PluginProtocolVersion)) - protocolVersion, err := VersionStr(protoString).Parse() - if err != nil { - return nil, fmt.Errorf("invalid plugin protocol version: %q", i.PluginProtocolVersion) - } - - earliestVersionProtocol, err := VersionStr(earliest.Protocols[0]).Parse() - if err != nil { - return nil, err - } - - // Compare installer protocol version with the first protocol listed of the earliest match - // [A, B] where A is assumed the earliest compatible major version of the protocol pair - if protocolVersion.NewerThan(earliestVersionProtocol) { - // Provider protocols are too old, the closest version is the earliest compatible version - return earliest, nil - } - - // Provider protocols are too new, the closest version is the latest compatible version - return latest, nil -} - -func (i *ProviderInstaller) checkPluginProtocol(versionMeta *response.TerraformProviderVersion) error { - // TODO: should this be a different error? We should probably differentiate between - // no compatible versions and no protocol versions listed at all - if len(versionMeta.Protocols) == 0 { - return fmt.Errorf("no plugin protocol versions listed") - } - - protoString := strconv.Itoa(int(i.PluginProtocolVersion)) - protocolVersion, err := VersionStr(protoString).Parse() - if err != nil { - return fmt.Errorf("invalid plugin protocol version: %q", i.PluginProtocolVersion) - } - protocolConstraint, err := protocolVersion.MinorUpgradeConstraintStr().Parse() - if err != nil { - // This should not fail if the preceding function succeeded. - return fmt.Errorf("invalid plugin protocol version: %q", protocolVersion.String()) - } - - for _, p := range versionMeta.Protocols { - proPro, err := VersionStr(p).Parse() - if err != nil { - // invalid protocol reported by the registry. Move along. - log.Printf("[WARN] invalid provider protocol version %q found in the registry", versionMeta.Version) - continue - } - // success! - if protocolConstraint.Allows(proPro) { - return nil - } - } - - return ErrorNoVersionCompatible -} - -// platformCompatibleVersions returns a list of provider versions that are -// compatible with the requested platform. -func (i *ProviderInstaller) platformCompatibleVersions(versions []*response.TerraformProviderVersion) []*response.TerraformProviderVersion { - var v []*response.TerraformProviderVersion - for _, version := range versions { - if err := i.checkPlatformCompatibility(version); err == nil { - v = append(v, version) - } - } - return v -} - -func (i *ProviderInstaller) checkPlatformCompatibility(versionMeta *response.TerraformProviderVersion) error { - if len(versionMeta.Platforms) == 0 { - return fmt.Errorf("no supported provider platforms listed") - } - for _, p := range versionMeta.Platforms { - if p.Arch == i.Arch && p.OS == i.OS { - return nil - } - } - return fmt.Errorf("version %s does not support the requested platform %s_%s", versionMeta.Version, i.OS, i.Arch) -} - -// take the list of available versions for a plugin, and filter out those that -// don't fit the constraints. -func allowedVersions(available *response.TerraformProviderVersions, required Constraints) []*response.TerraformProviderVersion { - var allowed []*response.TerraformProviderVersion - - for _, v := range available.Versions { - version, err := VersionStr(v.Version).Parse() - if err != nil { - log.Printf("[WARN] invalid version found for %q: %s", available.ID, err) - continue - } - if required.Allows(version) { - allowed = append(allowed, v) - } - } - return allowed -} - -func checksumForFile(sums []byte, name string) string { - for _, line := range strings.Split(string(sums), "\n") { - parts := strings.Fields(line) - if len(parts) > 1 && parts[1] == name { - return parts[0] - } - } - return "" -} - -func getFile(url string) ([]byte, error) { - resp, err := httpClient.Get(url) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("%s", resp.Status) - } - - data, err := ioutil.ReadAll(resp.Body) - if err != nil { - return data, err - } - return data, nil -} - -// providerProtocolTooOld is a message sent to the CLI UI if the provider's -// supported protocol versions are too old for the user's version of terraform, -// but an older version of the provider is compatible. -const providerProtocolTooOld = ` -[reset][bold][red]Provider %q v%s is not compatible with Terraform %s.[reset][red] - -Provider version %s is the earliest compatible version. Select it with -the following version constraint: - - version = %q - -Terraform checked all of the plugin versions matching the given constraint: - %s - -Consult the documentation for this provider for more information on -compatibility between provider and Terraform versions. -` - -// providerProtocolTooNew is a message sent to the CLI UI if the provider's -// supported protocol versions are too new for the user's version of terraform, -// and the user could either upgrade terraform or choose an older version of the -// provider -const providerProtocolTooNew = ` -[reset][bold][red]Provider %q v%s is not compatible with Terraform %s.[reset][red] - -Provider version %s is the latest compatible version. Select it with -the following constraint: - - version = %q - -Terraform checked all of the plugin versions matching the given constraint: - %s - -Consult the documentation for this provider for more information on -compatibility between provider and Terraform versions. - -Alternatively, upgrade to the latest version of Terraform for compatibility with newer provider releases. -` diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/get_cache.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/get_cache.go deleted file mode 100644 index 1a100426482..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/get_cache.go +++ /dev/null @@ -1,48 +0,0 @@ -package discovery - -// PluginCache is an interface implemented by objects that are able to maintain -// a cache of plugins. -type PluginCache interface { - // CachedPluginPath returns a path where the requested plugin is already - // cached, or an empty string if the requested plugin is not yet cached. - CachedPluginPath(kind string, name string, version Version) string - - // InstallDir returns the directory that new plugins should be installed into - // in order to populate the cache. This directory should be used as the - // first argument to getter.Get when downloading plugins with go-getter. - // - // After installing into this directory, use CachedPluginPath to obtain the - // path where the plugin was installed. - InstallDir() string -} - -// NewLocalPluginCache returns a PluginCache that caches plugins in a -// given local directory. -func NewLocalPluginCache(dir string) PluginCache { - return &pluginCache{ - Dir: dir, - } -} - -type pluginCache struct { - Dir string -} - -func (c *pluginCache) CachedPluginPath(kind string, name string, version Version) string { - allPlugins := FindPlugins(kind, []string{c.Dir}) - plugins := allPlugins.WithName(name).WithVersion(version) - - if plugins.Count() == 0 { - // nothing cached - return "" - } - - // There should generally be only one plugin here; if there's more than - // one match for some reason then we'll just choose one arbitrarily. - plugin := plugins.Newest() - return plugin.Path -} - -func (c *pluginCache) InstallDir() string { - return c.Dir -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/hashicorp.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/hashicorp.go deleted file mode 100644 index 4622ca0545c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/hashicorp.go +++ /dev/null @@ -1,34 +0,0 @@ -package discovery - -// HashicorpPublicKey is the HashiCorp public key, also available at -// https://www.hashicorp.com/security -const HashicorpPublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1 - -mQENBFMORM0BCADBRyKO1MhCirazOSVwcfTr1xUxjPvfxD3hjUwHtjsOy/bT6p9f -W2mRPfwnq2JB5As+paL3UGDsSRDnK9KAxQb0NNF4+eVhr/EJ18s3wwXXDMjpIifq -fIm2WyH3G+aRLTLPIpscUNKDyxFOUbsmgXAmJ46Re1fn8uKxKRHbfa39aeuEYWFA -3drdL1WoUngvED7f+RnKBK2G6ZEpO+LDovQk19xGjiMTtPJrjMjZJ3QXqPvx5wca -KSZLr4lMTuoTI/ZXyZy5bD4tShiZz6KcyX27cD70q2iRcEZ0poLKHyEIDAi3TM5k -SwbbWBFd5RNPOR0qzrb/0p9ksKK48IIfH2FvABEBAAG0K0hhc2hpQ29ycCBTZWN1 -cml0eSA8c2VjdXJpdHlAaGFzaGljb3JwLmNvbT6JATgEEwECACIFAlMORM0CGwMG -CwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEFGFLYc0j/xMyWIIAIPhcVqiQ59n -Jc07gjUX0SWBJAxEG1lKxfzS4Xp+57h2xxTpdotGQ1fZwsihaIqow337YHQI3q0i -SqV534Ms+j/tU7X8sq11xFJIeEVG8PASRCwmryUwghFKPlHETQ8jJ+Y8+1asRydi -psP3B/5Mjhqv/uOK+Vy3zAyIpyDOMtIpOVfjSpCplVRdtSTFWBu9Em7j5I2HMn1w -sJZnJgXKpybpibGiiTtmnFLOwibmprSu04rsnP4ncdC2XRD4wIjoyA+4PKgX3sCO -klEzKryWYBmLkJOMDdo52LttP3279s7XrkLEE7ia0fXa2c12EQ0f0DQ1tGUvyVEW -WmJVccm5bq25AQ0EUw5EzQEIANaPUY04/g7AmYkOMjaCZ6iTp9hB5Rsj/4ee/ln9 -wArzRO9+3eejLWh53FoN1rO+su7tiXJA5YAzVy6tuolrqjM8DBztPxdLBbEi4V+j -2tK0dATdBQBHEh3OJApO2UBtcjaZBT31zrG9K55D+CrcgIVEHAKY8Cb4kLBkb5wM -skn+DrASKU0BNIV1qRsxfiUdQHZfSqtp004nrql1lbFMLFEuiY8FZrkkQ9qduixo -mTT6f34/oiY+Jam3zCK7RDN/OjuWheIPGj/Qbx9JuNiwgX6yRj7OE1tjUx6d8g9y -0H1fmLJbb3WZZbuuGFnK6qrE3bGeY8+AWaJAZ37wpWh1p0cAEQEAAYkBHwQYAQIA -CQUCUw5EzQIbDAAKCRBRhS2HNI/8TJntCAClU7TOO/X053eKF1jqNW4A1qpxctVc -z8eTcY8Om5O4f6a/rfxfNFKn9Qyja/OG1xWNobETy7MiMXYjaa8uUx5iFy6kMVaP -0BXJ59NLZjMARGw6lVTYDTIvzqqqwLxgliSDfSnqUhubGwvykANPO+93BBx89MRG -unNoYGXtPlhNFrAsB1VR8+EyKLv2HQtGCPSFBhrjuzH3gxGibNDDdFQLxxuJWepJ -EK1UbTS4ms0NgZ2Uknqn1WRU1Ki7rE4sTy68iZtWpKQXZEJa0IGnuI2sSINGcXCJ -oEIgXTMyCILo34Fa/C6VCm2WBgz9zZO8/rHIiQm1J5zqz0DrDwKBUM9C -=LYpS ------END PGP PUBLIC KEY BLOCK-----` diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/meta.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/meta.go deleted file mode 100644 index bdcebcb9dc4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/meta.go +++ /dev/null @@ -1,41 +0,0 @@ -package discovery - -import ( - "crypto/sha256" - "io" - "os" -) - -// PluginMeta is metadata about a plugin, useful for launching the plugin -// and for understanding which plugins are available. -type PluginMeta struct { - // Name is the name of the plugin, e.g. as inferred from the plugin - // binary's filename, or by explicit configuration. - Name string - - // Version is the semver version of the plugin, expressed as a string - // that might not be semver-valid. - Version VersionStr - - // Path is the absolute path of the executable that can be launched - // to provide the RPC server for this plugin. - Path string -} - -// SHA256 returns a SHA256 hash of the content of the referenced executable -// file, or an error if the file's contents cannot be read. -func (m PluginMeta) SHA256() ([]byte, error) { - f, err := os.Open(m.Path) - if err != nil { - return nil, err - } - defer f.Close() - - h := sha256.New() - _, err = io.Copy(h, f) - if err != nil { - return nil, err - } - - return h.Sum(nil), nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/meta_set.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/meta_set.go deleted file mode 100644 index 3a992892df6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/meta_set.go +++ /dev/null @@ -1,195 +0,0 @@ -package discovery - -// A PluginMetaSet is a set of PluginMeta objects meeting a certain criteria. -// -// Methods on this type allow filtering of the set to produce subsets that -// meet more restrictive criteria. -type PluginMetaSet map[PluginMeta]struct{} - -// Add inserts the given PluginMeta into the receiving set. This is a no-op -// if the given meta is already present. -func (s PluginMetaSet) Add(p PluginMeta) { - s[p] = struct{}{} -} - -// Remove removes the given PluginMeta from the receiving set. This is a no-op -// if the given meta is not already present. -func (s PluginMetaSet) Remove(p PluginMeta) { - delete(s, p) -} - -// Has returns true if the given meta is in the receiving set, or false -// otherwise. -func (s PluginMetaSet) Has(p PluginMeta) bool { - _, ok := s[p] - return ok -} - -// Count returns the number of metas in the set -func (s PluginMetaSet) Count() int { - return len(s) -} - -// ValidateVersions returns two new PluginMetaSets, separating those with -// versions that have syntax-valid semver versions from those that don't. -// -// Eliminating invalid versions from consideration (and possibly warning about -// them) is usually the first step of working with a meta set after discovery -// has completed. -func (s PluginMetaSet) ValidateVersions() (valid, invalid PluginMetaSet) { - valid = make(PluginMetaSet) - invalid = make(PluginMetaSet) - for p := range s { - if _, err := p.Version.Parse(); err == nil { - valid.Add(p) - } else { - invalid.Add(p) - } - } - return -} - -// WithName returns the subset of metas that have the given name. -func (s PluginMetaSet) WithName(name string) PluginMetaSet { - ns := make(PluginMetaSet) - for p := range s { - if p.Name == name { - ns.Add(p) - } - } - return ns -} - -// WithVersion returns the subset of metas that have the given version. -// -// This should be used only with the "valid" result from ValidateVersions; -// it will ignore any plugin metas that have invalid version strings. -func (s PluginMetaSet) WithVersion(version Version) PluginMetaSet { - ns := make(PluginMetaSet) - for p := range s { - gotVersion, err := p.Version.Parse() - if err != nil { - continue - } - if gotVersion.Equal(version) { - ns.Add(p) - } - } - return ns -} - -// ByName groups the metas in the set by their Names, returning a map. -func (s PluginMetaSet) ByName() map[string]PluginMetaSet { - ret := make(map[string]PluginMetaSet) - for p := range s { - if _, ok := ret[p.Name]; !ok { - ret[p.Name] = make(PluginMetaSet) - } - ret[p.Name].Add(p) - } - return ret -} - -// Newest returns the one item from the set that has the newest Version value. -// -// The result is meaningful only if the set is already filtered such that -// all of the metas have the same Name. -// -// If there isn't at least one meta in the set then this function will panic. -// Use Count() to ensure that there is at least one value before calling. -// -// If any of the metas have invalid version strings then this function will -// panic. Use ValidateVersions() first to filter out metas with invalid -// versions. -// -// If two metas have the same Version then one is arbitrarily chosen. This -// situation should be avoided by pre-filtering the set. -func (s PluginMetaSet) Newest() PluginMeta { - if len(s) == 0 { - panic("can't call NewestStable on empty PluginMetaSet") - } - - var first = true - var winner PluginMeta - var winnerVersion Version - for p := range s { - version, err := p.Version.Parse() - if err != nil { - panic(err) - } - - if first == true || version.NewerThan(winnerVersion) { - winner = p - winnerVersion = version - first = false - } - } - - return winner -} - -// ConstrainVersions takes a set of requirements and attempts to -// return a map from name to a set of metas that have the matching -// name and an appropriate version. -// -// If any of the given requirements match *no* plugins then its PluginMetaSet -// in the returned map will be empty. -// -// All viable metas are returned, so the caller can apply any desired filtering -// to reduce down to a single option. For example, calling Newest() to obtain -// the highest available version. -// -// If any of the metas in the set have invalid version strings then this -// function will panic. Use ValidateVersions() first to filter out metas with -// invalid versions. -func (s PluginMetaSet) ConstrainVersions(reqd PluginRequirements) map[string]PluginMetaSet { - ret := make(map[string]PluginMetaSet) - for p := range s { - name := p.Name - allowedVersions, ok := reqd[name] - if !ok { - continue - } - if _, ok := ret[p.Name]; !ok { - ret[p.Name] = make(PluginMetaSet) - } - version, err := p.Version.Parse() - if err != nil { - panic(err) - } - if allowedVersions.Allows(version) { - ret[p.Name].Add(p) - } - } - return ret -} - -// OverridePaths returns a new set where any existing plugins with the given -// names are removed and replaced with the single path given in the map. -// -// This is here only to continue to support the legacy way of overriding -// plugin binaries in the .terraformrc file. It treats all given plugins -// as pre-versioning (version 0.0.0). This mechanism will eventually be -// phased out, with vendor directories being the intended replacement. -func (s PluginMetaSet) OverridePaths(paths map[string]string) PluginMetaSet { - ret := make(PluginMetaSet) - for p := range s { - if _, ok := paths[p.Name]; ok { - // Skip plugins that we're overridding - continue - } - - ret.Add(p) - } - - // Now add the metadata for overriding plugins - for name, path := range paths { - ret.Add(PluginMeta{ - Name: name, - Version: VersionZero, - Path: path, - }) - } - - return ret -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/requirements.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/requirements.go deleted file mode 100644 index 75430fdd609..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/requirements.go +++ /dev/null @@ -1,105 +0,0 @@ -package discovery - -import ( - "bytes" -) - -// PluginRequirements describes a set of plugins (assumed to be of a consistent -// kind) that are required to exist and have versions within the given -// corresponding sets. -type PluginRequirements map[string]*PluginConstraints - -// PluginConstraints represents an element of PluginRequirements describing -// the constraints for a single plugin. -type PluginConstraints struct { - // Specifies that the plugin's version must be within the given - // constraints. - Versions Constraints - - // If non-nil, the hash of the on-disk plugin executable must exactly - // match the SHA256 hash given here. - SHA256 []byte -} - -// Allows returns true if the given version is within the receiver's version -// constraints. -func (s *PluginConstraints) Allows(v Version) bool { - return s.Versions.Allows(v) -} - -// AcceptsSHA256 returns true if the given executable SHA256 hash is acceptable, -// either because it matches the constraint or because there is no such -// constraint. -func (s *PluginConstraints) AcceptsSHA256(digest []byte) bool { - if s.SHA256 == nil { - return true - } - return bytes.Equal(s.SHA256, digest) -} - -// Merge takes the contents of the receiver and the other given requirements -// object and merges them together into a single requirements structure -// that satisfies both sets of requirements. -// -// Note that it doesn't make sense to merge two PluginRequirements with -// differing required plugin SHA256 hashes, since the result will never -// match any plugin. -func (r PluginRequirements) Merge(other PluginRequirements) PluginRequirements { - ret := make(PluginRequirements) - for n, c := range r { - ret[n] = &PluginConstraints{ - Versions: Constraints{}.Append(c.Versions), - SHA256: c.SHA256, - } - } - for n, c := range other { - if existing, exists := ret[n]; exists { - ret[n].Versions = ret[n].Versions.Append(c.Versions) - - if existing.SHA256 != nil { - if c.SHA256 != nil && !bytes.Equal(c.SHA256, existing.SHA256) { - // If we've been asked to merge two constraints with - // different SHA256 hashes then we'll produce a dummy value - // that can never match anything. This is a silly edge case - // that no reasonable caller should hit. - ret[n].SHA256 = []byte(invalidProviderHash) - } - } else { - ret[n].SHA256 = c.SHA256 // might still be nil - } - } else { - ret[n] = &PluginConstraints{ - Versions: Constraints{}.Append(c.Versions), - SHA256: c.SHA256, - } - } - } - return ret -} - -// LockExecutables applies additional constraints to the receiver that -// require plugin executables with specific SHA256 digests. This modifies -// the receiver in-place, since it's intended to be applied after -// version constraints have been resolved. -// -// The given map must include a key for every plugin that is already -// required. If not, any missing keys will cause the corresponding plugin -// to never match, though the direct caller doesn't necessarily need to -// guarantee this as long as the downstream code _applying_ these constraints -// is able to deal with the non-match in some way. -func (r PluginRequirements) LockExecutables(sha256s map[string][]byte) { - for name, cons := range r { - digest := sha256s[name] - - if digest == nil { - // Prevent any match, which will then presumably cause the - // downstream consumer of this requirements to report an error. - cons.SHA256 = []byte(invalidProviderHash) - continue - } - - cons.SHA256 = digest - } -} - -const invalidProviderHash = "" diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/signature.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/signature.go deleted file mode 100644 index 7bbae50c384..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/signature.go +++ /dev/null @@ -1,19 +0,0 @@ -package discovery - -import ( - "bytes" - "strings" - - "golang.org/x/crypto/openpgp" -) - -// Verify the data using the provided openpgp detached signature and the -// embedded hashicorp public key. -func verifySig(data, sig []byte, armor string) (*openpgp.Entity, error) { - el, err := openpgp.ReadArmoredKeyRing(strings.NewReader(armor)) - if err != nil { - return nil, err - } - - return openpgp.CheckDetachedSignature(el, bytes.NewReader(data), bytes.NewReader(sig)) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/version.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/version.go deleted file mode 100644 index 4311d510765..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/version.go +++ /dev/null @@ -1,77 +0,0 @@ -package discovery - -import ( - "fmt" - "sort" - - version "github.com/hashicorp/go-version" -) - -const VersionZero = "0.0.0" - -// A VersionStr is a string containing a possibly-invalid representation -// of a semver version number. Call Parse on it to obtain a real Version -// object, or discover that it is invalid. -type VersionStr string - -// Parse transforms a VersionStr into a Version if it is -// syntactically valid. If it isn't then an error is returned instead. -func (s VersionStr) Parse() (Version, error) { - raw, err := version.NewVersion(string(s)) - if err != nil { - return Version{}, err - } - return Version{raw}, nil -} - -// MustParse transforms a VersionStr into a Version if it is -// syntactically valid. If it isn't then it panics. -func (s VersionStr) MustParse() Version { - ret, err := s.Parse() - if err != nil { - panic(err) - } - return ret -} - -// Version represents a version number that has been parsed from -// a semver string and known to be valid. -type Version struct { - // We wrap this here just because it avoids a proliferation of - // direct go-version imports all over the place, and keeps the - // version-processing details within this package. - raw *version.Version -} - -func (v Version) String() string { - return v.raw.String() -} - -func (v Version) NewerThan(other Version) bool { - return v.raw.GreaterThan(other.raw) -} - -func (v Version) Equal(other Version) bool { - return v.raw.Equal(other.raw) -} - -// IsPrerelease determines if version is a prerelease -func (v Version) IsPrerelease() bool { - return v.raw.Prerelease() != "" -} - -// MinorUpgradeConstraintStr returns a ConstraintStr that would permit -// minor upgrades relative to the receiving version. -func (v Version) MinorUpgradeConstraintStr() ConstraintStr { - segments := v.raw.Segments() - return ConstraintStr(fmt.Sprintf("~> %d.%d", segments[0], segments[1])) -} - -type Versions []Version - -// Sort sorts version from newest to oldest. -func (v Versions) Sort() { - sort.Slice(v, func(i, j int) bool { - return v[i].NewerThan(v[j]) - }) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/version_set.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/version_set.go deleted file mode 100644 index fc8b6f8bd2a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery/version_set.go +++ /dev/null @@ -1,83 +0,0 @@ -package discovery - -import ( - "sort" - - version "github.com/hashicorp/go-version" -) - -// A ConstraintStr is a string containing a possibly-invalid representation -// of a version constraint provided in configuration. Call Parse on it to -// obtain a real Constraint object, or discover that it is invalid. -type ConstraintStr string - -// Parse transforms a ConstraintStr into a Constraints if it is -// syntactically valid. If it isn't then an error is returned instead. -func (s ConstraintStr) Parse() (Constraints, error) { - raw, err := version.NewConstraint(string(s)) - if err != nil { - return Constraints{}, err - } - return Constraints{raw}, nil -} - -// MustParse is like Parse but it panics if the constraint string is invalid. -func (s ConstraintStr) MustParse() Constraints { - ret, err := s.Parse() - if err != nil { - panic(err) - } - return ret -} - -// Constraints represents a set of versions which any given Version is either -// a member of or not. -type Constraints struct { - raw version.Constraints -} - -// NewConstraints creates a Constraints based on a version.Constraints. -func NewConstraints(c version.Constraints) Constraints { - return Constraints{c} -} - -// AllVersions is a Constraints containing all versions -var AllVersions Constraints - -func init() { - AllVersions = Constraints{ - raw: make(version.Constraints, 0), - } -} - -// Allows returns true if the given version permitted by the receiving -// constraints set. -func (s Constraints) Allows(v Version) bool { - return s.raw.Check(v.raw) -} - -// Append combines the receiving set with the given other set to produce -// a set that is the intersection of both sets, which is to say that resulting -// constraints contain only the versions that are members of both. -func (s Constraints) Append(other Constraints) Constraints { - raw := make(version.Constraints, 0, len(s.raw)+len(other.raw)) - - // Since "raw" is a list of constraints that remove versions from the set, - // "Intersection" is implemented by concatenating together those lists, - // thus leaving behind only the versions not removed by either list. - raw = append(raw, s.raw...) - raw = append(raw, other.raw...) - - // while the set is unordered, we sort these lexically for consistent output - sort.Slice(raw, func(i, j int) bool { - return raw[i].String() < raw[j].String() - }) - - return Constraints{raw} -} - -// String returns a string representation of the set members as a set -// of range constraints. -func (s Constraints) String() string { - return s.raw.String() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/addressed_types.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/addressed_types.go deleted file mode 100644 index 0f48f2447d4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/addressed_types.go +++ /dev/null @@ -1,47 +0,0 @@ -package providers - -import ( - "sort" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// AddressedTypes is a helper that extracts all of the distinct provider -// types from the given list of relative provider configuration addresses. -func AddressedTypes(providerAddrs []addrs.ProviderConfig) []string { - if len(providerAddrs) == 0 { - return nil - } - m := map[string]struct{}{} - for _, addr := range providerAddrs { - m[addr.Type] = struct{}{} - } - - names := make([]string, 0, len(m)) - for typeName := range m { - names = append(names, typeName) - } - - sort.Strings(names) // Stable result for tests - return names -} - -// AddressedTypesAbs is a helper that extracts all of the distinct provider -// types from the given list of absolute provider configuration addresses. -func AddressedTypesAbs(providerAddrs []addrs.AbsProviderConfig) []string { - if len(providerAddrs) == 0 { - return nil - } - m := map[string]struct{}{} - for _, addr := range providerAddrs { - m[addr.ProviderConfig.Type] = struct{}{} - } - - names := make([]string, 0, len(m)) - for typeName := range m { - names = append(names, typeName) - } - - sort.Strings(names) // Stable result for tests - return names -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/doc.go deleted file mode 100644 index 39aa1de60f7..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package providers contains the interface and primary types required to -// implement a Terraform resource provider. -package providers diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/provider.go deleted file mode 100644 index 3d0aa8ec9eb..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/provider.go +++ /dev/null @@ -1,359 +0,0 @@ -package providers - -import ( - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// Interface represents the set of methods required for a complete resource -// provider plugin. -type Interface interface { - // GetSchema returns the complete schema for the provider. - GetSchema() GetSchemaResponse - - // PrepareProviderConfig allows the provider to validate the configuration - // values, and set or override any values with defaults. - PrepareProviderConfig(PrepareProviderConfigRequest) PrepareProviderConfigResponse - - // ValidateResourceTypeConfig allows the provider to validate the resource - // configuration values. - ValidateResourceTypeConfig(ValidateResourceTypeConfigRequest) ValidateResourceTypeConfigResponse - - // ValidateDataSource allows the provider to validate the data source - // configuration values. - ValidateDataSourceConfig(ValidateDataSourceConfigRequest) ValidateDataSourceConfigResponse - - // UpgradeResourceState is called when the state loader encounters an - // instance state whose schema version is less than the one reported by the - // currently-used version of the corresponding provider, and the upgraded - // result is used for any further processing. - UpgradeResourceState(UpgradeResourceStateRequest) UpgradeResourceStateResponse - - // Configure configures and initialized the provider. - Configure(ConfigureRequest) ConfigureResponse - - // Stop is called when the provider should halt any in-flight actions. - // - // Stop should not block waiting for in-flight actions to complete. It - // should take any action it wants and return immediately acknowledging it - // has received the stop request. Terraform will not make any further API - // calls to the provider after Stop is called. - // - // The error returned, if non-nil, is assumed to mean that signaling the - // stop somehow failed and that the user should expect potentially waiting - // a longer period of time. - Stop() error - - // ReadResource refreshes a resource and returns its current state. - ReadResource(ReadResourceRequest) ReadResourceResponse - - // PlanResourceChange takes the current state and proposed state of a - // resource, and returns the planned final state. - PlanResourceChange(PlanResourceChangeRequest) PlanResourceChangeResponse - - // ApplyResourceChange takes the planned state for a resource, which may - // yet contain unknown computed values, and applies the changes returning - // the final state. - ApplyResourceChange(ApplyResourceChangeRequest) ApplyResourceChangeResponse - - // ImportResourceState requests that the given resource be imported. - ImportResourceState(ImportResourceStateRequest) ImportResourceStateResponse - - // ReadDataSource returns the data source's current state. - ReadDataSource(ReadDataSourceRequest) ReadDataSourceResponse - - // Close shuts down the plugin process if applicable. - Close() error -} - -type GetSchemaResponse struct { - // Provider is the schema for the provider itself. - Provider Schema - - // ResourceTypes map the resource type name to that type's schema. - ResourceTypes map[string]Schema - - // DataSources maps the data source name to that data source's schema. - DataSources map[string]Schema - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -// Schema pairs a provider or resource schema with that schema's version. -// This is used to be able to upgrade the schema in UpgradeResourceState. -type Schema struct { - Version int64 - Block *configschema.Block -} - -type PrepareProviderConfigRequest struct { - // Config is the raw configuration value for the provider. - Config cty.Value -} - -type PrepareProviderConfigResponse struct { - // PreparedConfig is the configuration as prepared by the provider. - PreparedConfig cty.Value - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type ValidateResourceTypeConfigRequest struct { - // TypeName is the name of the resource type to validate. - TypeName string - - // Config is the configuration value to validate, which may contain unknown - // values. - Config cty.Value -} - -type ValidateResourceTypeConfigResponse struct { - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type ValidateDataSourceConfigRequest struct { - // TypeName is the name of the data source type to validate. - TypeName string - - // Config is the configuration value to validate, which may contain unknown - // values. - Config cty.Value -} - -type ValidateDataSourceConfigResponse struct { - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type UpgradeResourceStateRequest struct { - // TypeName is the name of the resource type being upgraded - TypeName string - - // Version is version of the schema that created the current state. - Version int64 - - // RawStateJSON and RawStateFlatmap contiain the state that needs to be - // upgraded to match the current schema version. Because the schema is - // unknown, this contains only the raw data as stored in the state. - // RawStateJSON is the current json state encoding. - // RawStateFlatmap is the legacy flatmap encoding. - // Only on of these fields may be set for the upgrade request. - RawStateJSON []byte - RawStateFlatmap map[string]string -} - -type UpgradeResourceStateResponse struct { - // UpgradedState is the newly upgraded resource state. - UpgradedState cty.Value - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type ConfigureRequest struct { - // Terraform version is the version string from the running instance of - // terraform. Providers can use TerraformVersion to verify compatibility, - // and to store for informational purposes. - TerraformVersion string - - // Config is the complete configuration value for the provider. - Config cty.Value -} - -type ConfigureResponse struct { - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type ReadResourceRequest struct { - // TypeName is the name of the resource type being read. - TypeName string - - // PriorState contains the previously saved state value for this resource. - PriorState cty.Value - - // Private is an opaque blob that will be stored in state along with the - // resource. It is intended only for interpretation by the provider itself. - Private []byte -} - -type ReadResourceResponse struct { - // NewState contains the current state of the resource. - NewState cty.Value - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics - - // Private is an opaque blob that will be stored in state along with the - // resource. It is intended only for interpretation by the provider itself. - Private []byte -} - -type PlanResourceChangeRequest struct { - // TypeName is the name of the resource type to plan. - TypeName string - - // PriorState is the previously saved state value for this resource. - PriorState cty.Value - - // ProposedNewState is the expected state after the new configuration is - // applied. This is created by directly applying the configuration to the - // PriorState. The provider is then responsible for applying any further - // changes required to create the proposed final state. - ProposedNewState cty.Value - - // Config is the resource configuration, before being merged with the - // PriorState. Any value not explicitly set in the configuration will be - // null. Config is supplied for reference, but Provider implementations - // should prefer the ProposedNewState in most circumstances. - Config cty.Value - - // PriorPrivate is the previously saved private data returned from the - // provider during the last apply. - PriorPrivate []byte -} - -type PlanResourceChangeResponse struct { - // PlannedState is the expected state of the resource once the current - // configuration is applied. - PlannedState cty.Value - - // RequiresReplace is the list of thee attributes that are requiring - // resource replacement. - RequiresReplace []cty.Path - - // PlannedPrivate is an opaque blob that is not interpreted by terraform - // core. This will be saved and relayed back to the provider during - // ApplyResourceChange. - PlannedPrivate []byte - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics - - // LegacyTypeSystem is set only if the provider is using the legacy SDK - // whose type system cannot be precisely mapped into the Terraform type - // system. We use this to bypass certain consistency checks that would - // otherwise fail due to this imprecise mapping. No other provider or SDK - // implementation is permitted to set this. - LegacyTypeSystem bool -} - -type ApplyResourceChangeRequest struct { - // TypeName is the name of the resource type being applied. - TypeName string - - // PriorState is the current state of resource. - PriorState cty.Value - - // Planned state is the state returned from PlanResourceChange, and should - // represent the new state, minus any remaining computed attributes. - PlannedState cty.Value - - // Config is the resource configuration, before being merged with the - // PriorState. Any value not explicitly set in the configuration will be - // null. Config is supplied for reference, but Provider implementations - // should prefer the PlannedState in most circumstances. - Config cty.Value - - // PlannedPrivate is the same value as returned by PlanResourceChange. - PlannedPrivate []byte -} - -type ApplyResourceChangeResponse struct { - // NewState is the new complete state after applying the planned change. - // In the event of an error, NewState should represent the most recent - // known state of the resource, if it exists. - NewState cty.Value - - // Private is an opaque blob that will be stored in state along with the - // resource. It is intended only for interpretation by the provider itself. - Private []byte - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics - - // LegacyTypeSystem is set only if the provider is using the legacy SDK - // whose type system cannot be precisely mapped into the Terraform type - // system. We use this to bypass certain consistency checks that would - // otherwise fail due to this imprecise mapping. No other provider or SDK - // implementation is permitted to set this. - LegacyTypeSystem bool -} - -type ImportResourceStateRequest struct { - // TypeName is the name of the resource type to be imported. - TypeName string - - // ID is a string with which the provider can identify the resource to be - // imported. - ID string -} - -type ImportResourceStateResponse struct { - // ImportedResources contains one or more state values related to the - // imported resource. It is not required that these be complete, only that - // there is enough identifying information for the provider to successfully - // update the states in ReadResource. - ImportedResources []ImportedResource - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -// ImportedResource represents an object being imported into Terraform with the -// help of a provider. An ImportedObject is a RemoteObject that has been read -// by the provider's import handler but hasn't yet been committed to state. -type ImportedResource struct { - // TypeName is the name of the resource type associated with the - // returned state. It's possible for providers to import multiple related - // types with a single import request. - TypeName string - - // State is the state of the remote object being imported. This may not be - // complete, but must contain enough information to uniquely identify the - // resource. - State cty.Value - - // Private is an opaque blob that will be stored in state along with the - // resource. It is intended only for interpretation by the provider itself. - Private []byte -} - -// AsInstanceObject converts the receiving ImportedObject into a -// ResourceInstanceObject that has status ObjectReady. -// -// The returned object does not know its own resource type, so the caller must -// retain the ResourceType value from the source object if this information is -// needed. -// -// The returned object also has no dependency addresses, but the caller may -// freely modify the direct fields of the returned object without affecting -// the receiver. -func (ir ImportedResource) AsInstanceObject() *states.ResourceInstanceObject { - return &states.ResourceInstanceObject{ - Status: states.ObjectReady, - Value: ir.State, - Private: ir.Private, - } -} - -type ReadDataSourceRequest struct { - // TypeName is the name of the data source type to Read. - TypeName string - - // Config is the complete configuration for the requested data source. - Config cty.Value -} - -type ReadDataSourceResponse struct { - // State is the current state of the requested data source. - State cty.Value - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/resolver.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/resolver.go deleted file mode 100644 index b42e4920272..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/resolver.go +++ /dev/null @@ -1,68 +0,0 @@ -package providers - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery" -) - -// Resolver is an interface implemented by objects that are able to resolve -// a given set of resource provider version constraints into Factory -// callbacks. -type Resolver interface { - // Given a constraint map, return a Factory for each requested provider. - // If some or all of the constraints cannot be satisfied, return a non-nil - // slice of errors describing the problems. - ResolveProviders(reqd discovery.PluginRequirements) (map[string]Factory, []error) -} - -// ResolverFunc wraps a callback function and turns it into a Resolver -// implementation, for convenience in situations where a function and its -// associated closure are sufficient as a resolver implementation. -type ResolverFunc func(reqd discovery.PluginRequirements) (map[string]Factory, []error) - -// ResolveProviders implements Resolver by calling the -// wrapped function. -func (f ResolverFunc) ResolveProviders(reqd discovery.PluginRequirements) (map[string]Factory, []error) { - return f(reqd) -} - -// ResolverFixed returns a Resolver that has a fixed set of provider factories -// provided by the caller. The returned resolver ignores version constraints -// entirely and just returns the given factory for each requested provider -// name. -// -// This function is primarily used in tests, to provide mock providers or -// in-process providers under test. -func ResolverFixed(factories map[string]Factory) Resolver { - return ResolverFunc(func(reqd discovery.PluginRequirements) (map[string]Factory, []error) { - ret := make(map[string]Factory, len(reqd)) - var errs []error - for name := range reqd { - if factory, exists := factories[name]; exists { - ret[name] = factory - } else { - errs = append(errs, fmt.Errorf("provider %q is not available", name)) - } - } - return ret, errs - }) -} - -// Factory is a function type that creates a new instance of a resource -// provider, or returns an error if that is impossible. -type Factory func() (Interface, error) - -// FactoryFixed is a helper that creates a Factory that just returns some given -// single provider. -// -// Unlike usual factories, the exact same instance is returned for each call -// to the factory and so this must be used in only specialized situations where -// the caller can take care to either not mutate the given provider at all -// or to mutate it in ways that will not cause unexpected behavior for others -// holding the same reference. -func FactoryFixed(p Interface) Factory { - return func() (Interface, error) { - return p, nil - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/provisioners/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/provisioners/doc.go deleted file mode 100644 index b03ba9a1bbd..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/provisioners/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package provisioners contains the interface and primary types to implement a -// Terraform resource provisioner. -package provisioners diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/provisioners/factory.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/provisioners/factory.go deleted file mode 100644 index 7a9dca0a087..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/provisioners/factory.go +++ /dev/null @@ -1,5 +0,0 @@ -package provisioners - -// Factory is a function type that creates a new instance of a resource -// provisioner, or returns an error if that is impossible. -type Factory func() (Interface, error) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/provisioners/provisioner.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/provisioners/provisioner.go deleted file mode 100644 index 7d8f4076ba4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/provisioners/provisioner.go +++ /dev/null @@ -1,82 +0,0 @@ -package provisioners - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" -) - -// Interface is the set of methods required for a resource provisioner plugin. -type Interface interface { - // GetSchema returns the schema for the provisioner configuration. - GetSchema() GetSchemaResponse - - // ValidateProvisionerConfig allows the provisioner to validate the - // configuration values. - ValidateProvisionerConfig(ValidateProvisionerConfigRequest) ValidateProvisionerConfigResponse - - // ProvisionResource runs the provisioner with provided configuration. - // ProvisionResource blocks until the execution is complete. - // If the returned diagnostics contain any errors, the resource will be - // left in a tainted state. - ProvisionResource(ProvisionResourceRequest) ProvisionResourceResponse - - // Stop is called to interrupt the provisioner. - // - // Stop should not block waiting for in-flight actions to complete. It - // should take any action it wants and return immediately acknowledging it - // has received the stop request. Terraform will not make any further API - // calls to the provisioner after Stop is called. - // - // The error returned, if non-nil, is assumed to mean that signaling the - // stop somehow failed and that the user should expect potentially waiting - // a longer period of time. - Stop() error - - // Close shuts down the plugin process if applicable. - Close() error -} - -type GetSchemaResponse struct { - // Provisioner contains the schema for this provisioner. - Provisioner *configschema.Block - - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -// UIOutput provides the Output method for resource provisioner -// plugins to write any output to the UI. -// -// Provisioners may call the Output method multiple times while Apply is in -// progress. It is invalid to call Output after Apply returns. -type UIOutput interface { - Output(string) -} - -type ValidateProvisionerConfigRequest struct { - // Config is the complete configuration to be used for the provisioner. - Config cty.Value -} - -type ValidateProvisionerConfigResponse struct { - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} - -type ProvisionResourceRequest struct { - // Config is the complete provisioner configuration. - Config cty.Value - - // Connection contains any information required to access the resource - // instance. - Connection cty.Value - - // UIOutput is used to return output during the Apply operation. - UIOutput UIOutput -} - -type ProvisionResourceResponse struct { - // Diagnostics contains any warnings or errors from the method call. - Diagnostics tfdiags.Diagnostics -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/client.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/client.go deleted file mode 100644 index 4ef22052c3d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/client.go +++ /dev/null @@ -1,346 +0,0 @@ -package registry - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "log" - "net/http" - "net/url" - "path" - "strings" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/httpclient" - internalhttpclient "github.com/hashicorp/terraform-plugin-sdk/internal/httpclient" - "github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc" - "github.com/hashicorp/terraform-plugin-sdk/internal/registry/response" - "github.com/hashicorp/terraform-plugin-sdk/internal/version" - "github.com/hashicorp/terraform-svchost" - "github.com/hashicorp/terraform-svchost/disco" -) - -const ( - xTerraformGet = "X-Terraform-Get" - xTerraformVersion = "X-Terraform-Version" - requestTimeout = 10 * time.Second - modulesServiceID = "modules.v1" - providersServiceID = "providers.v1" -) - -var tfVersion = version.String() - -// Client provides methods to query Terraform Registries. -type Client struct { - // this is the client to be used for all requests. - client *http.Client - - // services is a required *disco.Disco, which may have services and - // credentials pre-loaded. - services *disco.Disco -} - -// NewClient returns a new initialized registry client. -func NewClient(services *disco.Disco, client *http.Client) *Client { - if services == nil { - services = disco.New() - } - - if client == nil { - client = internalhttpclient.New() - client.Timeout = requestTimeout - } - - services.Transport = client.Transport - - services.SetUserAgent(httpclient.TerraformUserAgent(version.String())) - - return &Client{ - client: client, - services: services, - } -} - -// Discover queries the host, and returns the url for the registry. -func (c *Client) Discover(host svchost.Hostname, serviceID string) (*url.URL, error) { - service, err := c.services.DiscoverServiceURL(host, serviceID) - if err != nil { - return nil, &ServiceUnreachableError{err} - } - if !strings.HasSuffix(service.Path, "/") { - service.Path += "/" - } - return service, nil -} - -// ModuleVersions queries the registry for a module, and returns the available versions. -func (c *Client) ModuleVersions(module *regsrc.Module) (*response.ModuleVersions, error) { - host, err := module.SvcHost() - if err != nil { - return nil, err - } - - service, err := c.Discover(host, modulesServiceID) - if err != nil { - return nil, err - } - - p, err := url.Parse(path.Join(module.Module(), "versions")) - if err != nil { - return nil, err - } - - service = service.ResolveReference(p) - - log.Printf("[DEBUG] fetching module versions from %q", service) - - req, err := http.NewRequest("GET", service.String(), nil) - if err != nil { - return nil, err - } - - c.addRequestCreds(host, req) - req.Header.Set(xTerraformVersion, tfVersion) - - resp, err := c.client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - switch resp.StatusCode { - case http.StatusOK: - // OK - case http.StatusNotFound: - return nil, &errModuleNotFound{addr: module} - default: - return nil, fmt.Errorf("error looking up module versions: %s", resp.Status) - } - - var versions response.ModuleVersions - - dec := json.NewDecoder(resp.Body) - if err := dec.Decode(&versions); err != nil { - return nil, err - } - - for _, mod := range versions.Modules { - for _, v := range mod.Versions { - log.Printf("[DEBUG] found available version %q for %s", v.Version, mod.Source) - } - } - - return &versions, nil -} - -func (c *Client) addRequestCreds(host svchost.Hostname, req *http.Request) { - creds, err := c.services.CredentialsForHost(host) - if err != nil { - log.Printf("[WARN] Failed to get credentials for %s: %s (ignoring)", host, err) - return - } - - if creds != nil { - creds.PrepareRequest(req) - } -} - -// ModuleLocation find the download location for a specific version module. -// This returns a string, because the final location may contain special go-getter syntax. -func (c *Client) ModuleLocation(module *regsrc.Module, version string) (string, error) { - host, err := module.SvcHost() - if err != nil { - return "", err - } - - service, err := c.Discover(host, modulesServiceID) - if err != nil { - return "", err - } - - var p *url.URL - if version == "" { - p, err = url.Parse(path.Join(module.Module(), "download")) - } else { - p, err = url.Parse(path.Join(module.Module(), version, "download")) - } - if err != nil { - return "", err - } - download := service.ResolveReference(p) - - log.Printf("[DEBUG] looking up module location from %q", download) - - req, err := http.NewRequest("GET", download.String(), nil) - if err != nil { - return "", err - } - - c.addRequestCreds(host, req) - req.Header.Set(xTerraformVersion, tfVersion) - - resp, err := c.client.Do(req) - if err != nil { - return "", err - } - defer resp.Body.Close() - - // there should be no body, but save it for logging - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return "", fmt.Errorf("error reading response body from registry: %s", err) - } - - switch resp.StatusCode { - case http.StatusOK, http.StatusNoContent: - // OK - case http.StatusNotFound: - return "", fmt.Errorf("module %q version %q not found", module, version) - default: - // anything else is an error: - return "", fmt.Errorf("error getting download location for %q: %s resp:%s", module, resp.Status, body) - } - - // the download location is in the X-Terraform-Get header - location := resp.Header.Get(xTerraformGet) - if location == "" { - return "", fmt.Errorf("failed to get download URL for %q: %s resp:%s", module, resp.Status, body) - } - - // If location looks like it's trying to be a relative URL, treat it as - // one. - // - // We don't do this for just _any_ location, since the X-Terraform-Get - // header is a go-getter location rather than a URL, and so not all - // possible values will parse reasonably as URLs.) - // - // When used in conjunction with go-getter we normally require this header - // to be an absolute URL, but we are more liberal here because third-party - // registry implementations may not "know" their own absolute URLs if - // e.g. they are running behind a reverse proxy frontend, or such. - if strings.HasPrefix(location, "/") || strings.HasPrefix(location, "./") || strings.HasPrefix(location, "../") { - locationURL, err := url.Parse(location) - if err != nil { - return "", fmt.Errorf("invalid relative URL for %q: %s", module, err) - } - locationURL = download.ResolveReference(locationURL) - location = locationURL.String() - } - - return location, nil -} - -// TerraformProviderVersions queries the registry for a provider, and returns the available versions. -func (c *Client) TerraformProviderVersions(provider *regsrc.TerraformProvider) (*response.TerraformProviderVersions, error) { - host, err := provider.SvcHost() - if err != nil { - return nil, err - } - - service, err := c.Discover(host, providersServiceID) - if err != nil { - return nil, err - } - - p, err := url.Parse(path.Join(provider.TerraformProvider(), "versions")) - if err != nil { - return nil, err - } - - service = service.ResolveReference(p) - - log.Printf("[DEBUG] fetching provider versions from %q", service) - - req, err := http.NewRequest("GET", service.String(), nil) - if err != nil { - return nil, err - } - - c.addRequestCreds(host, req) - req.Header.Set(xTerraformVersion, tfVersion) - - resp, err := c.client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - switch resp.StatusCode { - case http.StatusOK: - // OK - case http.StatusNotFound: - return nil, &errProviderNotFound{addr: provider} - default: - return nil, fmt.Errorf("error looking up provider versions: %s", resp.Status) - } - - var versions response.TerraformProviderVersions - - dec := json.NewDecoder(resp.Body) - if err := dec.Decode(&versions); err != nil { - return nil, err - } - - return &versions, nil -} - -// TerraformProviderLocation queries the registry for a provider download metadata -func (c *Client) TerraformProviderLocation(provider *regsrc.TerraformProvider, version string) (*response.TerraformProviderPlatformLocation, error) { - host, err := provider.SvcHost() - if err != nil { - return nil, err - } - - service, err := c.Discover(host, providersServiceID) - if err != nil { - return nil, err - } - - p, err := url.Parse(path.Join( - provider.TerraformProvider(), - version, - "download", - provider.OS, - provider.Arch, - )) - if err != nil { - return nil, err - } - - service = service.ResolveReference(p) - - log.Printf("[DEBUG] fetching provider location from %q", service) - - req, err := http.NewRequest("GET", service.String(), nil) - if err != nil { - return nil, err - } - - c.addRequestCreds(host, req) - req.Header.Set(xTerraformVersion, tfVersion) - - resp, err := c.client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - var loc response.TerraformProviderPlatformLocation - - dec := json.NewDecoder(resp.Body) - if err := dec.Decode(&loc); err != nil { - return nil, err - } - - switch resp.StatusCode { - case http.StatusOK, http.StatusNoContent: - // OK - case http.StatusNotFound: - return nil, fmt.Errorf("provider %q version %q not found", provider.TerraformProvider(), version) - default: - // anything else is an error: - return nil, fmt.Errorf("error getting download location for %q: %s", provider.TerraformProvider(), resp.Status) - } - - return &loc, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/errors.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/errors.go deleted file mode 100644 index b05438c4db2..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/errors.go +++ /dev/null @@ -1,55 +0,0 @@ -package registry - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc" - "github.com/hashicorp/terraform-svchost/disco" -) - -type errModuleNotFound struct { - addr *regsrc.Module -} - -func (e *errModuleNotFound) Error() string { - return fmt.Sprintf("module %s not found", e.addr) -} - -// IsModuleNotFound returns true only if the given error is a "module not found" -// error. This allows callers to recognize this particular error condition -// as distinct from operational errors such as poor network connectivity. -func IsModuleNotFound(err error) bool { - _, ok := err.(*errModuleNotFound) - return ok -} - -type errProviderNotFound struct { - addr *regsrc.TerraformProvider -} - -func (e *errProviderNotFound) Error() string { - return fmt.Sprintf("provider %s not found", e.addr) -} - -// IsServiceNotProvided returns true only if the given error is a "service not provided" -// error. This allows callers to recognize this particular error condition -// as distinct from operational errors such as poor network connectivity. -func IsServiceNotProvided(err error) bool { - _, ok := err.(*disco.ErrServiceNotProvided) - return ok -} - -// ServiceUnreachableError Registry service is unreachable -type ServiceUnreachableError struct { - err error -} - -func (e *ServiceUnreachableError) Error() string { - return e.err.Error() -} - -// IsServiceUnreachable returns true if the registry/discovery service was unreachable -func IsServiceUnreachable(err error) bool { - _, ok := err.(*ServiceUnreachableError) - return ok -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/friendly_host.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/friendly_host.go deleted file mode 100644 index c9bc40bee8f..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/friendly_host.go +++ /dev/null @@ -1,140 +0,0 @@ -package regsrc - -import ( - "regexp" - "strings" - - "github.com/hashicorp/terraform-svchost" -) - -var ( - // InvalidHostString is a placeholder returned when a raw host can't be - // converted by IDNA spec. It will never be returned for any host for which - // Valid() is true. - InvalidHostString = "" - - // urlLabelEndSubRe is a sub-expression that matches any character that's - // allowed at the start or end of a URL label according to RFC1123. - urlLabelEndSubRe = "[0-9A-Za-z]" - - // urlLabelEndSubRe is a sub-expression that matches any character that's - // allowed at in a non-start or end of a URL label according to RFC1123. - urlLabelMidSubRe = "[0-9A-Za-z-]" - - // urlLabelUnicodeSubRe is a sub-expression that matches any non-ascii char - // in an IDN (Unicode) display URL. It's not strict - there are only ~15k - // valid Unicode points in IDN RFC (some with conditions). We are just going - // with being liberal with matching and then erroring if we fail to convert - // to punycode later (which validates chars fully). This at least ensures - // ascii chars dissalowed by the RC1123 parts above don't become legal - // again. - urlLabelUnicodeSubRe = "[^[:ascii:]]" - - // hostLabelSubRe is the sub-expression that matches a valid hostname label. - // It does not anchor the start or end so it can be composed into more - // complex RegExps below. Note that for sanity we don't handle disallowing - // raw punycode in this regexp (esp. since re2 doesn't support negative - // lookbehind, but we can capture it's presence here to check later). - hostLabelSubRe = "" + - // Match valid initial char, or unicode char - "(?:" + urlLabelEndSubRe + "|" + urlLabelUnicodeSubRe + ")" + - // Optionally, match 0 to 61 valid URL or Unicode chars, - // followed by one valid end char or unicode char - "(?:" + - "(?:" + urlLabelMidSubRe + "|" + urlLabelUnicodeSubRe + "){0,61}" + - "(?:" + urlLabelEndSubRe + "|" + urlLabelUnicodeSubRe + ")" + - ")?" - - // hostSubRe is the sub-expression that matches a valid host prefix. - // Allows custom port. - hostSubRe = hostLabelSubRe + "(?:\\." + hostLabelSubRe + ")+(?::\\d+)?" - - // hostRe is a regexp that matches a valid host prefix. Additional - // validation of unicode strings is needed for matches. - hostRe = regexp.MustCompile("^" + hostSubRe + "$") -) - -// FriendlyHost describes a registry instance identified in source strings by a -// simple bare hostname like registry.terraform.io. -type FriendlyHost struct { - Raw string -} - -func NewFriendlyHost(host string) *FriendlyHost { - return &FriendlyHost{Raw: host} -} - -// ParseFriendlyHost attempts to parse a valid "friendly host" prefix from the -// given string. If no valid prefix is found, host will be nil and rest will -// contain the full source string. The host prefix must terminate at the end of -// the input or at the first / character. If one or more characters exist after -// the first /, they will be returned as rest (without the / delimiter). -// Hostnames containing punycode WILL be parsed successfully since they may have -// come from an internal normalized source string, however should be considered -// invalid if the string came from a user directly. This must be checked -// explicitly for user-input strings by calling Valid() on the -// returned host. -func ParseFriendlyHost(source string) (host *FriendlyHost, rest string) { - parts := strings.SplitN(source, "/", 2) - - if hostRe.MatchString(parts[0]) { - host = &FriendlyHost{Raw: parts[0]} - if len(parts) == 2 { - rest = parts[1] - } - return - } - - // No match, return whole string as rest along with nil host - rest = source - return -} - -// Valid returns whether the host prefix is considered valid in any case. -// Example of invalid prefixes might include ones that don't conform to the host -// name specifications. Not that IDN prefixes containing punycode are not valid -// input which we expect to always be in user-input or normalised display form. -func (h *FriendlyHost) Valid() bool { - return svchost.IsValid(h.Raw) -} - -// Display returns the host formatted for display to the user in CLI or web -// output. -func (h *FriendlyHost) Display() string { - return svchost.ForDisplay(h.Raw) -} - -// Normalized returns the host formatted for internal reference or comparison. -func (h *FriendlyHost) Normalized() string { - host, err := svchost.ForComparison(h.Raw) - if err != nil { - return InvalidHostString - } - return string(host) -} - -// String returns the host formatted as the user originally typed it assuming it -// was parsed from user input. -func (h *FriendlyHost) String() string { - return h.Raw -} - -// Equal compares the FriendlyHost against another instance taking normalization -// into account. Invalid hosts cannot be compared and will always return false. -func (h *FriendlyHost) Equal(other *FriendlyHost) bool { - if other == nil { - return false - } - - otherHost, err := svchost.ForComparison(other.Raw) - if err != nil { - return false - } - - host, err := svchost.ForComparison(h.Raw) - if err != nil { - return false - } - - return otherHost == host -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/module.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/module.go deleted file mode 100644 index eb37481ff36..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/module.go +++ /dev/null @@ -1,175 +0,0 @@ -package regsrc - -import ( - "errors" - "fmt" - "regexp" - "strings" - - svchost "github.com/hashicorp/terraform-svchost" -) - -var ( - ErrInvalidModuleSource = errors.New("not a valid registry module source") - - // nameSubRe is the sub-expression that matches a valid module namespace or - // name. It's strictly a super-set of what GitHub allows for user/org and - // repo names respectively, but more restrictive than our original repo-name - // regex which allowed periods but could cause ambiguity with hostname - // prefixes. It does not anchor the start or end so it can be composed into - // more complex RegExps below. Alphanumeric with - and _ allowed in non - // leading or trailing positions. Max length 64 chars. (GitHub username is - // 38 max.) - nameSubRe = "[0-9A-Za-z](?:[0-9A-Za-z-_]{0,62}[0-9A-Za-z])?" - - // providerSubRe is the sub-expression that matches a valid provider. It - // does not anchor the start or end so it can be composed into more complex - // RegExps below. Only lowercase chars and digits are supported in practice. - // Max length 64 chars. - providerSubRe = "[0-9a-z]{1,64}" - - // moduleSourceRe is a regular expression that matches the basic - // namespace/name/provider[//...] format for registry sources. It assumes - // any FriendlyHost prefix has already been removed if present. - moduleSourceRe = regexp.MustCompile( - fmt.Sprintf("^(%s)\\/(%s)\\/(%s)(?:\\/\\/(.*))?$", - nameSubRe, nameSubRe, providerSubRe)) - - // these hostnames are not allowed as registry sources, because they are - // already special case module sources in terraform. - disallowed = map[string]bool{ - "github.com": true, - "bitbucket.org": true, - } -) - -// Module describes a Terraform Registry Module source. -type Module struct { - // RawHost is the friendly host prefix if one was present. It might be nil - // if the original source had no host prefix which implies - // PublicRegistryHost but is distinct from having an actual pointer to - // PublicRegistryHost since it encodes the fact the original string didn't - // include a host prefix at all which is significant for recovering actual - // input not just normalized form. Most callers should access it with Host() - // which will return public registry host instance if it's nil. - RawHost *FriendlyHost - RawNamespace string - RawName string - RawProvider string - RawSubmodule string -} - -// ParseModuleSource attempts to parse source as a Terraform registry module -// source. If the string is not found to be in a valid format, -// ErrInvalidModuleSource is returned. Note that this can only be used on -// "input" strings, e.g. either ones supplied by the user or potentially -// normalised but in Display form (unicode). It will fail to parse a source with -// a punycoded domain since this is not permitted input from a user. If you have -// an already normalized string internally, you can compare it without parsing -// by comparing with the normalized version of the subject with the normal -// string equality operator. -func ParseModuleSource(source string) (*Module, error) { - // See if there is a friendly host prefix. - host, rest := ParseFriendlyHost(source) - if host != nil { - if !host.Valid() || disallowed[host.Display()] { - return nil, ErrInvalidModuleSource - } - } - - matches := moduleSourceRe.FindStringSubmatch(rest) - if len(matches) < 4 { - return nil, ErrInvalidModuleSource - } - - m := &Module{ - RawHost: host, - RawNamespace: matches[1], - RawName: matches[2], - RawProvider: matches[3], - } - - if len(matches) == 5 { - m.RawSubmodule = matches[4] - } - - return m, nil -} - -// Display returns the source formatted for display to the user in CLI or web -// output. -func (m *Module) Display() string { - return m.formatWithPrefix(m.normalizedHostPrefix(m.Host().Display()), false) -} - -// Normalized returns the source formatted for internal reference or comparison. -func (m *Module) Normalized() string { - return m.formatWithPrefix(m.normalizedHostPrefix(m.Host().Normalized()), false) -} - -// String returns the source formatted as the user originally typed it assuming -// it was parsed from user input. -func (m *Module) String() string { - // Don't normalize public registry hostname - leave it exactly like the user - // input it. - hostPrefix := "" - if m.RawHost != nil { - hostPrefix = m.RawHost.String() + "/" - } - return m.formatWithPrefix(hostPrefix, true) -} - -// Equal compares the module source against another instance taking -// normalization into account. -func (m *Module) Equal(other *Module) bool { - return m.Normalized() == other.Normalized() -} - -// Host returns the FriendlyHost object describing which registry this module is -// in. If the original source string had not host component this will return the -// PublicRegistryHost. -func (m *Module) Host() *FriendlyHost { - if m.RawHost == nil { - return PublicRegistryHost - } - return m.RawHost -} - -func (m *Module) normalizedHostPrefix(host string) string { - if m.Host().Equal(PublicRegistryHost) { - return "" - } - return host + "/" -} - -func (m *Module) formatWithPrefix(hostPrefix string, preserveCase bool) string { - suffix := "" - if m.RawSubmodule != "" { - suffix = "//" + m.RawSubmodule - } - str := fmt.Sprintf("%s%s/%s/%s%s", hostPrefix, m.RawNamespace, m.RawName, - m.RawProvider, suffix) - - // lower case by default - if !preserveCase { - return strings.ToLower(str) - } - return str -} - -// Module returns just the registry ID of the module, without a hostname or -// suffix. -func (m *Module) Module() string { - return fmt.Sprintf("%s/%s/%s", m.RawNamespace, m.RawName, m.RawProvider) -} - -// SvcHost returns the svchost.Hostname for this module. Since FriendlyHost may -// contain an invalid hostname, this also returns an error indicating if it -// could be converted to a svchost.Hostname. If no host is specified, the -// default PublicRegistryHost is returned. -func (m *Module) SvcHost() (svchost.Hostname, error) { - if m.RawHost == nil { - return svchost.ForComparison(PublicRegistryHost.Raw) - } - return svchost.ForComparison(m.RawHost.Raw) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/regsrc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/regsrc.go deleted file mode 100644 index c430bf14133..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/regsrc.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package regsrc provides helpers for working with source strings that identify -// resources within a Terraform registry. -package regsrc - -var ( - // PublicRegistryHost is a FriendlyHost that represents the public registry. - PublicRegistryHost = NewFriendlyHost("registry.terraform.io") -) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/terraform_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/terraform_provider.go deleted file mode 100644 index 7205d03b8c7..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/regsrc/terraform_provider.go +++ /dev/null @@ -1,60 +0,0 @@ -package regsrc - -import ( - "fmt" - "runtime" - "strings" - - "github.com/hashicorp/terraform-svchost" -) - -var ( - // DefaultProviderNamespace represents the namespace for canonical - // HashiCorp-controlled providers. - DefaultProviderNamespace = "-" -) - -// TerraformProvider describes a Terraform Registry Provider source. -type TerraformProvider struct { - RawHost *FriendlyHost - RawNamespace string - RawName string - OS string - Arch string -} - -// NewTerraformProvider constructs a new provider source. -func NewTerraformProvider(name, os, arch string) *TerraformProvider { - if os == "" { - os = runtime.GOOS - } - if arch == "" { - arch = runtime.GOARCH - } - - // separate namespace if included - namespace := DefaultProviderNamespace - if names := strings.SplitN(name, "/", 2); len(names) == 2 { - namespace, name = names[0], names[1] - } - p := &TerraformProvider{ - RawHost: PublicRegistryHost, - RawNamespace: namespace, - RawName: name, - OS: os, - Arch: arch, - } - - return p -} - -// Provider returns just the registry ID of the provider -func (p *TerraformProvider) TerraformProvider() string { - return fmt.Sprintf("%s/%s", p.RawNamespace, p.RawName) -} - -// SvcHost returns the svchost.Hostname for this provider. The -// default PublicRegistryHost is returned. -func (p *TerraformProvider) SvcHost() (svchost.Hostname, error) { - return svchost.ForComparison(PublicRegistryHost.Raw) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/module.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/module.go deleted file mode 100644 index 06163963efe..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/module.go +++ /dev/null @@ -1,46 +0,0 @@ -package response - -// ModuleSubmodule is the metadata about a specific submodule within -// a module. This includes the root module as a special case. -type ModuleSubmodule struct { - Path string `json:"path"` - Readme string `json:"readme"` - Empty bool `json:"empty"` - - Inputs []*ModuleInput `json:"inputs"` - Outputs []*ModuleOutput `json:"outputs"` - Dependencies []*ModuleDep `json:"dependencies"` - Resources []*ModuleResource `json:"resources"` -} - -// ModuleInput is an input for a module. -type ModuleInput struct { - Name string `json:"name"` - Description string `json:"description"` - Default string `json:"default"` -} - -// ModuleOutput is an output for a module. -type ModuleOutput struct { - Name string `json:"name"` - Description string `json:"description"` -} - -// ModuleDep is an output for a module. -type ModuleDep struct { - Name string `json:"name"` - Source string `json:"source"` - Version string `json:"version"` -} - -// ModuleProviderDep is the output for a provider dependency -type ModuleProviderDep struct { - Name string `json:"name"` - Version string `json:"version"` -} - -// ModuleResource is an output for a module. -type ModuleResource struct { - Name string `json:"name"` - Type string `json:"type"` -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/module_versions.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/module_versions.go deleted file mode 100644 index f69e9750c23..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/module_versions.go +++ /dev/null @@ -1,32 +0,0 @@ -package response - -// ModuleVersions is the response format that contains all metadata about module -// versions needed for terraform CLI to resolve version constraints. See RFC -// TF-042 for details on this format. -type ModuleVersions struct { - Modules []*ModuleProviderVersions `json:"modules"` -} - -// ModuleProviderVersions is the response format for a single module instance, -// containing metadata about all versions and their dependencies. -type ModuleProviderVersions struct { - Source string `json:"source"` - Versions []*ModuleVersion `json:"versions"` -} - -// ModuleVersion is the output metadata for a given version needed by CLI to -// resolve candidate versions to satisfy requirements. -type ModuleVersion struct { - Version string `json:"version"` - Root VersionSubmodule `json:"root"` - Submodules []*VersionSubmodule `json:"submodules"` -} - -// VersionSubmodule is the output metadata for a submodule within a given -// version needed by CLI to resolve candidate versions to satisfy requirements. -// When representing the Root in JSON the path is omitted. -type VersionSubmodule struct { - Path string `json:"path,omitempty"` - Providers []*ModuleProviderDep `json:"providers"` - Dependencies []*ModuleDep `json:"dependencies"` -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/pagination.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/pagination.go deleted file mode 100644 index 75a925490a2..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/pagination.go +++ /dev/null @@ -1,65 +0,0 @@ -package response - -import ( - "net/url" - "strconv" -) - -// PaginationMeta is a structure included in responses for pagination. -type PaginationMeta struct { - Limit int `json:"limit"` - CurrentOffset int `json:"current_offset"` - NextOffset *int `json:"next_offset,omitempty"` - PrevOffset *int `json:"prev_offset,omitempty"` - NextURL string `json:"next_url,omitempty"` - PrevURL string `json:"prev_url,omitempty"` -} - -// NewPaginationMeta populates pagination meta data from result parameters -func NewPaginationMeta(offset, limit int, hasMore bool, currentURL string) PaginationMeta { - pm := PaginationMeta{ - Limit: limit, - CurrentOffset: offset, - } - - // Calculate next/prev offsets, leave nil if not valid pages - nextOffset := offset + limit - if hasMore { - pm.NextOffset = &nextOffset - } - - prevOffset := offset - limit - if prevOffset < 0 { - prevOffset = 0 - } - if prevOffset < offset { - pm.PrevOffset = &prevOffset - } - - // If URL format provided, populate URLs. Intentionally swallow URL errors for now, API should - // catch missing URLs if we call with bad URL arg (and we care about them being present). - if currentURL != "" && pm.NextOffset != nil { - pm.NextURL, _ = setQueryParam(currentURL, "offset", *pm.NextOffset, 0) - } - if currentURL != "" && pm.PrevOffset != nil { - pm.PrevURL, _ = setQueryParam(currentURL, "offset", *pm.PrevOffset, 0) - } - - return pm -} - -func setQueryParam(baseURL, key string, val, defaultVal int) (string, error) { - u, err := url.Parse(baseURL) - if err != nil { - return "", err - } - q := u.Query() - if val == defaultVal { - // elide param if it's the default value - q.Del(key) - } else { - q.Set(key, strconv.Itoa(val)) - } - u.RawQuery = q.Encode() - return u.String(), nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/terraform_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/terraform_provider.go deleted file mode 100644 index c2c333b0dca..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/registry/response/terraform_provider.go +++ /dev/null @@ -1,95 +0,0 @@ -package response - -import ( - "sort" - "strings" - - version "github.com/hashicorp/go-version" -) - -// TerraformProvider is the response structure for all required information for -// Terraform to choose a download URL. It must include all versions and all -// platforms for Terraform to perform version and os/arch constraint matching -// locally. -type TerraformProvider struct { - ID string `json:"id"` - - Versions []*TerraformProviderVersion `json:"versions"` -} - -// TerraformProviderVersion is the Terraform-specific response structure for a -// provider version. -type TerraformProviderVersion struct { - Version string `json:"version"` - Protocols []string `json:"protocols"` - - Platforms []*TerraformProviderPlatform `json:"platforms"` -} - -// TerraformProviderVersions is the Terraform-specific response structure for an -// array of provider versions -type TerraformProviderVersions struct { - ID string `json:"id"` - Versions []*TerraformProviderVersion `json:"versions"` - Warnings []string `json:"warnings"` -} - -// TerraformProviderPlatform is the Terraform-specific response structure for a -// provider platform. -type TerraformProviderPlatform struct { - OS string `json:"os"` - Arch string `json:"arch"` -} - -// TerraformProviderPlatformLocation is the Terraform-specific response -// structure for a provider platform with all details required to perform a -// download. -type TerraformProviderPlatformLocation struct { - Protocols []string `json:"protocols"` - OS string `json:"os"` - Arch string `json:"arch"` - Filename string `json:"filename"` - DownloadURL string `json:"download_url"` - ShasumsURL string `json:"shasums_url"` - ShasumsSignatureURL string `json:"shasums_signature_url"` - Shasum string `json:"shasum"` - - SigningKeys SigningKeyList `json:"signing_keys"` -} - -// SigningKeyList is the response structure for a list of signing keys. -type SigningKeyList struct { - GPGKeys []*GPGKey `json:"gpg_public_keys"` -} - -// GPGKey is the response structure for a GPG key. -type GPGKey struct { - ASCIIArmor string `json:"ascii_armor"` - Source string `json:"source"` - SourceURL *string `json:"source_url"` -} - -// Collection type for TerraformProviderVersion -type ProviderVersionCollection []*TerraformProviderVersion - -// GPGASCIIArmor returns an ASCII-armor-formatted string for all of the gpg -// keys in the response. -func (signingKeys *SigningKeyList) GPGASCIIArmor() string { - keys := []string{} - - for _, gpgKey := range signingKeys.GPGKeys { - keys = append(keys, gpgKey.ASCIIArmor) - } - - return strings.Join(keys, "\n") -} - -// Sort sorts versions from newest to oldest. -func (v ProviderVersionCollection) Sort() { - sort.Slice(v, func(i, j int) bool { - versionA, _ := version.NewVersion(v[i].Version) - versionB, _ := version.NewVersion(v[j].Version) - - return versionA.GreaterThan(versionB) - }) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/doc.go deleted file mode 100644 index 7dd74ac7852..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package states contains the types that are used to represent Terraform -// states. -package states diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/eachmode_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/eachmode_string.go deleted file mode 100644 index 0dc73499a33..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/eachmode_string.go +++ /dev/null @@ -1,35 +0,0 @@ -// Code generated by "stringer -type EachMode"; DO NOT EDIT. - -package states - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[NoEach-0] - _ = x[EachList-76] - _ = x[EachMap-77] -} - -const ( - _EachMode_name_0 = "NoEach" - _EachMode_name_1 = "EachListEachMap" -) - -var ( - _EachMode_index_1 = [...]uint8{0, 8, 15} -) - -func (i EachMode) String() string { - switch { - case i == 0: - return _EachMode_name_0 - case 76 <= i && i <= 77: - i -= 76 - return _EachMode_name_1[_EachMode_index_1[i]:_EachMode_index_1[i+1]] - default: - return "EachMode(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_generation.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_generation.go deleted file mode 100644 index 891adc003ce..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_generation.go +++ /dev/null @@ -1,20 +0,0 @@ -package states - -// Generation is used to represent multiple objects in a succession of objects -// represented by a single resource instance address. A resource instance can -// have multiple generations over its lifetime due to object replacement -// (when a change can't be applied without destroying and re-creating), and -// multiple generations can exist at the same time when create_before_destroy -// is used. -// -// A Generation value can either be the value of the variable "CurrentGen" or -// a value of type DeposedKey. Generation values can be compared for equality -// using "==" and used as map keys. The zero value of Generation (nil) is not -// a valid generation and must not be used. -type Generation interface { - generation() -} - -// CurrentGen is the Generation representing the currently-active object for -// a resource instance. -var CurrentGen Generation diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object.go deleted file mode 100644 index 3bb717d332e..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object.go +++ /dev/null @@ -1,120 +0,0 @@ -package states - -import ( - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// ResourceInstanceObject is the local representation of a specific remote -// object associated with a resource instance. In practice not all remote -// objects are actually remote in the sense of being accessed over the network, -// but this is the most common case. -// -// It is not valid to mutate a ResourceInstanceObject once it has been created. -// Instead, create a new object and replace the existing one. -type ResourceInstanceObject struct { - // Value is the object-typed value representing the remote object within - // Terraform. - Value cty.Value - - // Private is an opaque value set by the provider when this object was - // last created or updated. Terraform Core does not use this value in - // any way and it is not exposed anywhere in the user interface, so - // a provider can use it for retaining any necessary private state. - Private []byte - - // Status represents the "readiness" of the object as of the last time - // it was updated. - Status ObjectStatus - - // Dependencies is a set of other addresses in the same module which - // this instance depended on when the given attributes were evaluated. - // This is used to construct the dependency relationships for an object - // whose configuration is no longer available, such as if it has been - // removed from configuration altogether, or is now deposed. - Dependencies []addrs.Referenceable -} - -// ObjectStatus represents the status of a RemoteObject. -type ObjectStatus rune - -//go:generate go run golang.org/x/tools/cmd/stringer -type ObjectStatus - -const ( - // ObjectReady is an object status for an object that is ready to use. - ObjectReady ObjectStatus = 'R' - - // ObjectTainted is an object status representing an object that is in - // an unrecoverable bad state due to a partial failure during a create, - // update, or delete operation. Since it cannot be moved into the - // ObjectRead state, a tainted object must be replaced. - ObjectTainted ObjectStatus = 'T' - - // ObjectPlanned is a special object status used only for the transient - // placeholder objects we place into state during the refresh and plan - // walks to stand in for objects that will be created during apply. - // - // Any object of this status must have a corresponding change recorded - // in the current plan, whose value must then be used in preference to - // the value stored in state when evaluating expressions. A planned - // object stored in state will be incomplete if any of its attributes are - // not yet known, and the plan must be consulted in order to "see" those - // unknown values, because the state is not able to represent them. - ObjectPlanned ObjectStatus = 'P' -) - -// Encode marshals the value within the receiver to produce a -// ResourceInstanceObjectSrc ready to be written to a state file. -// -// The given type must be the implied type of the resource type schema, and -// the given value must conform to it. It is important to pass the schema -// type and not the object's own type so that dynamically-typed attributes -// will be stored correctly. The caller must also provide the version number -// of the schema that the given type was derived from, which will be recorded -// in the source object so it can be used to detect when schema migration is -// required on read. -// -// The returned object may share internal references with the receiver and -// so the caller must not mutate the receiver any further once once this -// method is called. -func (o *ResourceInstanceObject) Encode(ty cty.Type, schemaVersion uint64) (*ResourceInstanceObjectSrc, error) { - // Our state serialization can't represent unknown values, so we convert - // them to nulls here. This is lossy, but nobody should be writing unknown - // values here and expecting to get them out again later. - // - // We get unknown values here while we're building out a "planned state" - // during the plan phase, but the value stored in the plan takes precedence - // for expression evaluation. The apply step should never produce unknown - // values, but if it does it's the responsibility of the caller to detect - // and raise an error about that. - val := cty.UnknownAsNull(o.Value) - - src, err := ctyjson.Marshal(val, ty) - if err != nil { - return nil, err - } - - return &ResourceInstanceObjectSrc{ - SchemaVersion: schemaVersion, - AttrsJSON: src, - Private: o.Private, - Status: o.Status, - Dependencies: o.Dependencies, - }, nil -} - -// AsTainted returns a deep copy of the receiver with the status updated to -// ObjectTainted. -func (o *ResourceInstanceObject) AsTainted() *ResourceInstanceObject { - if o == nil { - // A nil object can't be tainted, but we'll allow this anyway to - // avoid a crash, since we presumably intend to eventually record - // the object has having been deleted anyway. - return nil - } - ret := o.DeepCopy() - ret.Status = ObjectTainted - return ret -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object_src.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object_src.go deleted file mode 100644 index 728ad80d12e..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object_src.go +++ /dev/null @@ -1,113 +0,0 @@ -package states - -import ( - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" -) - -// ResourceInstanceObjectSrc is a not-fully-decoded version of -// ResourceInstanceObject. Decoding of it can be completed by first handling -// any schema migration steps to get to the latest schema version and then -// calling method Decode with the implied type of the latest schema. -type ResourceInstanceObjectSrc struct { - // SchemaVersion is the resource-type-specific schema version number that - // was current when either AttrsJSON or AttrsFlat was encoded. Migration - // steps are required if this is less than the current version number - // reported by the corresponding provider. - SchemaVersion uint64 - - // AttrsJSON is a JSON-encoded representation of the object attributes, - // encoding the value (of the object type implied by the associated resource - // type schema) that represents this remote object in Terraform Language - // expressions, and is compared with configuration when producing a diff. - // - // This is retained in JSON format here because it may require preprocessing - // before decoding if, for example, the stored attributes are for an older - // schema version which the provider must upgrade before use. If the - // version is current, it is valid to simply decode this using the - // type implied by the current schema, without the need for the provider - // to perform an upgrade first. - // - // When writing a ResourceInstanceObject into the state, AttrsJSON should - // always be conformant to the current schema version and the current - // schema version should be recorded in the SchemaVersion field. - AttrsJSON []byte - - // AttrsFlat is a legacy form of attributes used in older state file - // formats, and in the new state format for objects that haven't yet been - // upgraded. This attribute is mutually exclusive with Attrs: for any - // ResourceInstanceObject, only one of these attributes may be populated - // and the other must be nil. - // - // An instance object with this field populated should be upgraded to use - // Attrs at the earliest opportunity, since this legacy flatmap-based - // format will be phased out over time. AttrsFlat should not be used when - // writing new or updated objects to state; instead, callers must follow - // the recommendations in the AttrsJSON documentation above. - AttrsFlat map[string]string - - // These fields all correspond to the fields of the same name on - // ResourceInstanceObject. - Private []byte - Status ObjectStatus - Dependencies []addrs.Referenceable -} - -// Decode unmarshals the raw representation of the object attributes. Pass the -// implied type of the corresponding resource type schema for correct operation. -// -// Before calling Decode, the caller must check that the SchemaVersion field -// exactly equals the version number of the schema whose implied type is being -// passed, or else the result is undefined. -// -// The returned object may share internal references with the receiver and -// so the caller must not mutate the receiver any further once once this -// method is called. -func (os *ResourceInstanceObjectSrc) Decode(ty cty.Type) (*ResourceInstanceObject, error) { - var val cty.Value - var err error - if os.AttrsFlat != nil { - // Legacy mode. We'll do our best to unpick this from the flatmap. - val, err = hcl2shim.HCL2ValueFromFlatmap(os.AttrsFlat, ty) - if err != nil { - return nil, err - } - } else { - val, err = ctyjson.Unmarshal(os.AttrsJSON, ty) - if err != nil { - return nil, err - } - } - - return &ResourceInstanceObject{ - Value: val, - Status: os.Status, - Dependencies: os.Dependencies, - Private: os.Private, - }, nil -} - -// CompleteUpgrade creates a new ResourceInstanceObjectSrc by copying the -// metadata from the receiver and writing in the given new schema version -// and attribute value that are presumed to have resulted from upgrading -// from an older schema version. -func (os *ResourceInstanceObjectSrc) CompleteUpgrade(newAttrs cty.Value, newType cty.Type, newSchemaVersion uint64) (*ResourceInstanceObjectSrc, error) { - new := os.DeepCopy() - new.AttrsFlat = nil // We always use JSON after an upgrade, even if the source used flatmap - - // This is the same principle as ResourceInstanceObject.Encode, but - // avoiding a decode/re-encode cycle because we don't have type info - // available for the "old" attributes. - newAttrs = cty.UnknownAsNull(newAttrs) - src, err := ctyjson.Marshal(newAttrs, newType) - if err != nil { - return nil, err - } - - new.AttrsJSON = src - new.SchemaVersion = newSchemaVersion - return new, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/module.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/module.go deleted file mode 100644 index 6b74cbfa6bd..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/module.go +++ /dev/null @@ -1,268 +0,0 @@ -package states - -import ( - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// Module is a container for the states of objects within a particular module. -type Module struct { - Addr addrs.ModuleInstance - - // Resources contains the state for each resource. The keys in this map are - // an implementation detail and must not be used by outside callers. - Resources map[string]*Resource - - // OutputValues contains the state for each output value. The keys in this - // map are output value names. - OutputValues map[string]*OutputValue - - // LocalValues contains the value for each named output value. The keys - // in this map are local value names. - LocalValues map[string]cty.Value -} - -// NewModule constructs an empty module state for the given module address. -func NewModule(addr addrs.ModuleInstance) *Module { - return &Module{ - Addr: addr, - Resources: map[string]*Resource{}, - OutputValues: map[string]*OutputValue{}, - LocalValues: map[string]cty.Value{}, - } -} - -// Resource returns the state for the resource with the given address within -// the receiving module state, or nil if the requested resource is not tracked -// in the state. -func (ms *Module) Resource(addr addrs.Resource) *Resource { - return ms.Resources[addr.String()] -} - -// ResourceInstance returns the state for the resource instance with the given -// address within the receiving module state, or nil if the requested instance -// is not tracked in the state. -func (ms *Module) ResourceInstance(addr addrs.ResourceInstance) *ResourceInstance { - rs := ms.Resource(addr.Resource) - if rs == nil { - return nil - } - return rs.Instance(addr.Key) -} - -// SetResourceMeta updates the resource-level metadata for the resource -// with the given address, creating the resource state for it if it doesn't -// already exist. -func (ms *Module) SetResourceMeta(addr addrs.Resource, eachMode EachMode, provider addrs.AbsProviderConfig) { - rs := ms.Resource(addr) - if rs == nil { - rs = &Resource{ - Addr: addr, - Instances: map[addrs.InstanceKey]*ResourceInstance{}, - } - ms.Resources[addr.String()] = rs - } - - rs.EachMode = eachMode - rs.ProviderConfig = provider -} - -// RemoveResource removes the entire state for the given resource, taking with -// it any instances associated with the resource. This should generally be -// called only for resource objects whose instances have all been destroyed. -func (ms *Module) RemoveResource(addr addrs.Resource) { - delete(ms.Resources, addr.String()) -} - -// SetResourceInstanceCurrent saves the given instance object as the current -// generation of the resource instance with the given address, simulataneously -// updating the recorded provider configuration address, dependencies, and -// resource EachMode. -// -// Any existing current instance object for the given resource is overwritten. -// Set obj to nil to remove the primary generation object altogether. If there -// are no deposed objects then the instance will be removed altogether. -// -// The provider address and "each mode" are resource-wide settings and so they -// are updated for all other instances of the same resource as a side-effect of -// this call. -func (ms *Module) SetResourceInstanceCurrent(addr addrs.ResourceInstance, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig) { - ms.SetResourceMeta(addr.Resource, eachModeForInstanceKey(addr.Key), provider) - - rs := ms.Resource(addr.Resource) - is := rs.EnsureInstance(addr.Key) - - is.Current = obj - - if !is.HasObjects() { - // If we have no objects at all then we'll clean up. - delete(rs.Instances, addr.Key) - } - if rs.EachMode == NoEach && len(rs.Instances) == 0 { - // Also clean up if we only expect to have one instance anyway - // and there are none. We leave the resource behind if an each mode - // is active because an empty list or map of instances is a valid state. - delete(ms.Resources, addr.Resource.String()) - } -} - -// SetResourceInstanceDeposed saves the given instance object as a deposed -// generation of the resource instance with the given address and deposed key. -// -// Call this method only for pre-existing deposed objects that already have -// a known DeposedKey. For example, this method is useful if reloading objects -// that were persisted to a state file. To mark the current object as deposed, -// use DeposeResourceInstanceObject instead. -// -// The resource that contains the given instance must already exist in the -// state, or this method will panic. Use Resource to check first if its -// presence is not already guaranteed. -// -// Any existing current instance object for the given resource and deposed key -// is overwritten. Set obj to nil to remove the deposed object altogether. If -// the instance is left with no objects after this operation then it will -// be removed from its containing resource altogether. -func (ms *Module) SetResourceInstanceDeposed(addr addrs.ResourceInstance, key DeposedKey, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig) { - ms.SetResourceMeta(addr.Resource, eachModeForInstanceKey(addr.Key), provider) - - rs := ms.Resource(addr.Resource) - is := rs.EnsureInstance(addr.Key) - if obj != nil { - is.Deposed[key] = obj - } else { - delete(is.Deposed, key) - } - - if !is.HasObjects() { - // If we have no objects at all then we'll clean up. - delete(rs.Instances, addr.Key) - } - if rs.EachMode == NoEach && len(rs.Instances) == 0 { - // Also clean up if we only expect to have one instance anyway - // and there are none. We leave the resource behind if an each mode - // is active because an empty list or map of instances is a valid state. - delete(ms.Resources, addr.Resource.String()) - } -} - -// ForgetResourceInstanceDeposed removes the record of the deposed object with -// the given address and key, if present. If not present, this is a no-op. -func (ms *Module) ForgetResourceInstanceDeposed(addr addrs.ResourceInstance, key DeposedKey) { - rs := ms.Resource(addr.Resource) - if rs == nil { - return - } - is := rs.Instance(addr.Key) - if is == nil { - return - } - delete(is.Deposed, key) - - if !is.HasObjects() { - // If we have no objects at all then we'll clean up. - delete(rs.Instances, addr.Key) - } - if rs.EachMode == NoEach && len(rs.Instances) == 0 { - // Also clean up if we only expect to have one instance anyway - // and there are none. We leave the resource behind if an each mode - // is active because an empty list or map of instances is a valid state. - delete(ms.Resources, addr.Resource.String()) - } -} - -// deposeResourceInstanceObject is the real implementation of -// SyncState.DeposeResourceInstanceObject. -func (ms *Module) deposeResourceInstanceObject(addr addrs.ResourceInstance, forceKey DeposedKey) DeposedKey { - is := ms.ResourceInstance(addr) - if is == nil { - return NotDeposed - } - return is.deposeCurrentObject(forceKey) -} - -// maybeRestoreResourceInstanceDeposed is the real implementation of -// SyncState.MaybeRestoreResourceInstanceDeposed. -func (ms *Module) maybeRestoreResourceInstanceDeposed(addr addrs.ResourceInstance, key DeposedKey) bool { - rs := ms.Resource(addr.Resource) - if rs == nil { - return false - } - is := rs.Instance(addr.Key) - if is == nil { - return false - } - if is.Current != nil { - return false - } - if len(is.Deposed) == 0 { - return false - } - is.Current = is.Deposed[key] - delete(is.Deposed, key) - return true -} - -// SetOutputValue writes an output value into the state, overwriting any -// existing value of the same name. -func (ms *Module) SetOutputValue(name string, value cty.Value, sensitive bool) *OutputValue { - os := &OutputValue{ - Value: value, - Sensitive: sensitive, - } - ms.OutputValues[name] = os - return os -} - -// RemoveOutputValue removes the output value of the given name from the state, -// if it exists. This method is a no-op if there is no value of the given -// name. -func (ms *Module) RemoveOutputValue(name string) { - delete(ms.OutputValues, name) -} - -// SetLocalValue writes a local value into the state, overwriting any -// existing value of the same name. -func (ms *Module) SetLocalValue(name string, value cty.Value) { - ms.LocalValues[name] = value -} - -// RemoveLocalValue removes the local value of the given name from the state, -// if it exists. This method is a no-op if there is no value of the given -// name. -func (ms *Module) RemoveLocalValue(name string) { - delete(ms.LocalValues, name) -} - -// PruneResourceHusks is a specialized method that will remove any Resource -// objects that do not contain any instances, even if they have an EachMode. -// -// You probably shouldn't call this! See the method of the same name on -// type State for more information on what this is for and the rare situations -// where it is safe to use. -func (ms *Module) PruneResourceHusks() { - for _, rs := range ms.Resources { - if len(rs.Instances) == 0 { - ms.RemoveResource(rs.Addr) - } - } -} - -// empty returns true if the receving module state is contributing nothing -// to the state. In other words, it returns true if the module could be -// removed from the state altogether without changing the meaning of the state. -// -// In practice a module containing no objects is the same as a non-existent -// module, and so we can opportunistically clean up once a module becomes -// empty on the assumption that it will be re-added if needed later. -func (ms *Module) empty() bool { - if ms == nil { - return true - } - - // This must be updated to cover any new collections added to Module - // in future. - return (len(ms.Resources) == 0 && - len(ms.OutputValues) == 0 && - len(ms.LocalValues) == 0) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/objectstatus_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/objectstatus_string.go deleted file mode 100644 index 96a6db2f4c4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/objectstatus_string.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by "stringer -type ObjectStatus"; DO NOT EDIT. - -package states - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[ObjectReady-82] - _ = x[ObjectTainted-84] - _ = x[ObjectPlanned-80] -} - -const ( - _ObjectStatus_name_0 = "ObjectPlanned" - _ObjectStatus_name_1 = "ObjectReady" - _ObjectStatus_name_2 = "ObjectTainted" -) - -func (i ObjectStatus) String() string { - switch { - case i == 80: - return _ObjectStatus_name_0 - case i == 82: - return _ObjectStatus_name_1 - case i == 84: - return _ObjectStatus_name_2 - default: - return "ObjectStatus(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/output_value.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/output_value.go deleted file mode 100644 index d232b76d404..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/output_value.go +++ /dev/null @@ -1,14 +0,0 @@ -package states - -import ( - "github.com/zclconf/go-cty/cty" -) - -// OutputValue represents the state of a particular output value. -// -// It is not valid to mutate an OutputValue object once it has been created. -// Instead, create an entirely new OutputValue to replace the previous one. -type OutputValue struct { - Value cty.Value - Sensitive bool -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/resource.go deleted file mode 100644 index 32ea638acd8..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/resource.go +++ /dev/null @@ -1,233 +0,0 @@ -package states - -import ( - "fmt" - "math/rand" - "time" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// Resource represents the state of a resource. -type Resource struct { - // Addr is the module-relative address for the resource this state object - // belongs to. - Addr addrs.Resource - - // EachMode is the multi-instance mode currently in use for this resource, - // or NoEach if this is a single-instance resource. This dictates what - // type of value is returned when accessing this resource via expressions - // in the Terraform language. - EachMode EachMode - - // Instances contains the potentially-multiple instances associated with - // this resource. This map can contain a mixture of different key types, - // but only the ones of InstanceKeyType are considered current. - Instances map[addrs.InstanceKey]*ResourceInstance - - // ProviderConfig is the absolute address for the provider configuration that - // most recently managed this resource. This is used to connect a resource - // with a provider configuration when the resource configuration block is - // not available, such as if it has been removed from configuration - // altogether. - ProviderConfig addrs.AbsProviderConfig -} - -// Instance returns the state for the instance with the given key, or nil -// if no such instance is tracked within the state. -func (rs *Resource) Instance(key addrs.InstanceKey) *ResourceInstance { - return rs.Instances[key] -} - -// EnsureInstance returns the state for the instance with the given key, -// creating a new empty state for it if one doesn't already exist. -// -// Because this may create and save a new state, it is considered to be -// a write operation. -func (rs *Resource) EnsureInstance(key addrs.InstanceKey) *ResourceInstance { - ret := rs.Instance(key) - if ret == nil { - ret = NewResourceInstance() - rs.Instances[key] = ret - } - return ret -} - -// ResourceInstance represents the state of a particular instance of a resource. -type ResourceInstance struct { - // Current, if non-nil, is the remote object that is currently represented - // by the corresponding resource instance. - Current *ResourceInstanceObjectSrc - - // Deposed, if len > 0, contains any remote objects that were previously - // represented by the corresponding resource instance but have been - // replaced and are pending destruction due to the create_before_destroy - // lifecycle mode. - Deposed map[DeposedKey]*ResourceInstanceObjectSrc -} - -// NewResourceInstance constructs and returns a new ResourceInstance, ready to -// use. -func NewResourceInstance() *ResourceInstance { - return &ResourceInstance{ - Deposed: map[DeposedKey]*ResourceInstanceObjectSrc{}, - } -} - -// HasCurrent returns true if this resource instance has a "current"-generation -// object. Most instances do, but this can briefly be false during a -// create-before-destroy replace operation when the current has been deposed -// but its replacement has not yet been created. -func (i *ResourceInstance) HasCurrent() bool { - return i != nil && i.Current != nil -} - -// HasDeposed returns true if this resource instance has a deposed object -// with the given key. -func (i *ResourceInstance) HasDeposed(key DeposedKey) bool { - return i != nil && i.Deposed[key] != nil -} - -// HasObjects returns true if this resource has any objects at all, whether -// current or deposed. -func (i *ResourceInstance) HasObjects() bool { - return i.Current != nil || len(i.Deposed) != 0 -} - -// deposeCurrentObject is part of the real implementation of -// SyncState.DeposeResourceInstanceObject. The exported method uses a lock -// to ensure that we can safely allocate an unused deposed key without -// collision. -func (i *ResourceInstance) deposeCurrentObject(forceKey DeposedKey) DeposedKey { - if !i.HasCurrent() { - return NotDeposed - } - - key := forceKey - if key == NotDeposed { - key = i.findUnusedDeposedKey() - } else { - if _, exists := i.Deposed[key]; exists { - panic(fmt.Sprintf("forced key %s is already in use", forceKey)) - } - } - i.Deposed[key] = i.Current - i.Current = nil - return key -} - -// GetGeneration retrieves the object of the given generation from the -// ResourceInstance, or returns nil if there is no such object. -// -// If the given generation is nil or invalid, this method will panic. -func (i *ResourceInstance) GetGeneration(gen Generation) *ResourceInstanceObjectSrc { - if gen == CurrentGen { - return i.Current - } - if dk, ok := gen.(DeposedKey); ok { - return i.Deposed[dk] - } - if gen == nil { - panic(fmt.Sprintf("get with nil Generation")) - } - // Should never fall out here, since the above covers all possible - // Generation values. - panic(fmt.Sprintf("get invalid Generation %#v", gen)) -} - -// FindUnusedDeposedKey generates a unique DeposedKey that is guaranteed not to -// already be in use for this instance at the time of the call. -// -// Note that the validity of this result may change if new deposed keys are -// allocated before it is used. To avoid this risk, instead use the -// DeposeResourceInstanceObject method on the SyncState wrapper type, which -// allocates a key and uses it atomically. -func (i *ResourceInstance) FindUnusedDeposedKey() DeposedKey { - return i.findUnusedDeposedKey() -} - -// findUnusedDeposedKey generates a unique DeposedKey that is guaranteed not to -// already be in use for this instance. -func (i *ResourceInstance) findUnusedDeposedKey() DeposedKey { - for { - key := NewDeposedKey() - if _, exists := i.Deposed[key]; !exists { - return key - } - // Spin until we find a unique one. This shouldn't take long, because - // we have a 32-bit keyspace and there's rarely more than one deposed - // instance. - } -} - -// EachMode specifies the multi-instance mode for a resource. -type EachMode rune - -const ( - NoEach EachMode = 0 - EachList EachMode = 'L' - EachMap EachMode = 'M' -) - -//go:generate go run golang.org/x/tools/cmd/stringer -type EachMode - -func eachModeForInstanceKey(key addrs.InstanceKey) EachMode { - switch key.(type) { - case addrs.IntKey: - return EachList - case addrs.StringKey: - return EachMap - default: - if key == addrs.NoKey { - return NoEach - } - panic(fmt.Sprintf("don't know an each mode for instance key %#v", key)) - } -} - -// DeposedKey is a 8-character hex string used to uniquely identify deposed -// instance objects in the state. -type DeposedKey string - -// NotDeposed is a special invalid value of DeposedKey that is used to represent -// the absense of a deposed key. It must not be used as an actual deposed key. -const NotDeposed = DeposedKey("") - -var deposedKeyRand = rand.New(rand.NewSource(time.Now().UnixNano())) - -// NewDeposedKey generates a pseudo-random deposed key. Because of the short -// length of these keys, uniqueness is not a natural consequence and so the -// caller should test to see if the generated key is already in use and generate -// another if so, until a unique key is found. -func NewDeposedKey() DeposedKey { - v := deposedKeyRand.Uint32() - return DeposedKey(fmt.Sprintf("%08x", v)) -} - -func (k DeposedKey) String() string { - return string(k) -} - -func (k DeposedKey) GoString() string { - ks := string(k) - switch { - case ks == "": - return "states.NotDeposed" - default: - return fmt.Sprintf("states.DeposedKey(%s)", ks) - } -} - -// Generation is a helper method to convert a DeposedKey into a Generation. -// If the reciever is anything other than NotDeposed then the result is -// just the same value as a Generation. If the receiver is NotDeposed then -// the result is CurrentGen. -func (k DeposedKey) Generation() Generation { - if k == NotDeposed { - return CurrentGen - } - return k -} - -// generation is an implementation of Generation. -func (k DeposedKey) generation() {} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state.go deleted file mode 100644 index 328dd53d5c6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state.go +++ /dev/null @@ -1,229 +0,0 @@ -package states - -import ( - "sort" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// State is the top-level type of a Terraform state. -// -// A state should be mutated only via its accessor methods, to ensure that -// invariants are preserved. -// -// Access to State and the nested values within it is not concurrency-safe, -// so when accessing a State object concurrently it is the caller's -// responsibility to ensure that only one write is in progress at a time -// and that reads only occur when no write is in progress. The most common -// way to acheive this is to wrap the State in a SyncState and use the -// higher-level atomic operations supported by that type. -type State struct { - // Modules contains the state for each module. The keys in this map are - // an implementation detail and must not be used by outside callers. - Modules map[string]*Module -} - -// NewState constructs a minimal empty state, containing an empty root module. -func NewState() *State { - modules := map[string]*Module{} - modules[addrs.RootModuleInstance.String()] = NewModule(addrs.RootModuleInstance) - return &State{ - Modules: modules, - } -} - -// BuildState is a helper -- primarily intended for tests -- to build a state -// using imperative code against the StateSync type while still acting as -// an expression of type *State to assign into a containing struct. -func BuildState(cb func(*SyncState)) *State { - s := NewState() - cb(s.SyncWrapper()) - return s -} - -// Empty returns true if there are no resources or populated output values -// in the receiver. In other words, if this state could be safely replaced -// with the return value of NewState and be functionally equivalent. -func (s *State) Empty() bool { - if s == nil { - return true - } - for _, ms := range s.Modules { - if len(ms.Resources) != 0 { - return false - } - if len(ms.OutputValues) != 0 { - return false - } - } - return true -} - -// Module returns the state for the module with the given address, or nil if -// the requested module is not tracked in the state. -func (s *State) Module(addr addrs.ModuleInstance) *Module { - if s == nil { - panic("State.Module on nil *State") - } - return s.Modules[addr.String()] -} - -// RemoveModule removes the module with the given address from the state, -// unless it is the root module. The root module cannot be deleted, and so -// this method will panic if that is attempted. -// -// Removing a module implicitly discards all of the resources, outputs and -// local values within it, and so this should usually be done only for empty -// modules. For callers accessing the state through a SyncState wrapper, modules -// are automatically pruned if they are empty after one of their contained -// elements is removed. -func (s *State) RemoveModule(addr addrs.ModuleInstance) { - if addr.IsRoot() { - panic("attempted to remove root module") - } - - delete(s.Modules, addr.String()) -} - -// RootModule is a convenient alias for Module(addrs.RootModuleInstance). -func (s *State) RootModule() *Module { - if s == nil { - panic("RootModule called on nil State") - } - return s.Modules[addrs.RootModuleInstance.String()] -} - -// EnsureModule returns the state for the module with the given address, -// creating and adding a new one if necessary. -// -// Since this might modify the state to add a new instance, it is considered -// to be a write operation. -func (s *State) EnsureModule(addr addrs.ModuleInstance) *Module { - ms := s.Module(addr) - if ms == nil { - ms = NewModule(addr) - s.Modules[addr.String()] = ms - } - return ms -} - -// HasResources returns true if there is at least one resource (of any mode) -// present in the receiving state. -func (s *State) HasResources() bool { - if s == nil { - return false - } - for _, ms := range s.Modules { - if len(ms.Resources) > 0 { - return true - } - } - return false -} - -// Resource returns the state for the resource with the given address, or nil -// if no such resource is tracked in the state. -func (s *State) Resource(addr addrs.AbsResource) *Resource { - ms := s.Module(addr.Module) - if ms == nil { - return nil - } - return ms.Resource(addr.Resource) -} - -// ResourceInstance returns the state for the resource instance with the given -// address, or nil if no such resource is tracked in the state. -func (s *State) ResourceInstance(addr addrs.AbsResourceInstance) *ResourceInstance { - if s == nil { - panic("State.ResourceInstance on nil *State") - } - ms := s.Module(addr.Module) - if ms == nil { - return nil - } - return ms.ResourceInstance(addr.Resource) -} - -// OutputValue returns the state for the output value with the given address, -// or nil if no such output value is tracked in the state. -func (s *State) OutputValue(addr addrs.AbsOutputValue) *OutputValue { - ms := s.Module(addr.Module) - if ms == nil { - return nil - } - return ms.OutputValues[addr.OutputValue.Name] -} - -// LocalValue returns the value of the named local value with the given address, -// or cty.NilVal if no such value is tracked in the state. -func (s *State) LocalValue(addr addrs.AbsLocalValue) cty.Value { - ms := s.Module(addr.Module) - if ms == nil { - return cty.NilVal - } - return ms.LocalValues[addr.LocalValue.Name] -} - -// ProviderAddrs returns a list of all of the provider configuration addresses -// referenced throughout the receiving state. -// -// The result is de-duplicated so that each distinct address appears only once. -func (s *State) ProviderAddrs() []addrs.AbsProviderConfig { - if s == nil { - return nil - } - - m := map[string]addrs.AbsProviderConfig{} - for _, ms := range s.Modules { - for _, rc := range ms.Resources { - m[rc.ProviderConfig.String()] = rc.ProviderConfig - } - } - if len(m) == 0 { - return nil - } - - // This is mainly just so we'll get stable results for testing purposes. - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - sort.Strings(keys) - - ret := make([]addrs.AbsProviderConfig, len(keys)) - for i, key := range keys { - ret[i] = m[key] - } - - return ret -} - -// PruneResourceHusks is a specialized method that will remove any Resource -// objects that do not contain any instances, even if they have an EachMode. -// -// This should generally be used only after a "terraform destroy" operation, -// to finalize the cleanup of the state. It is not correct to use this after -// other operations because if a resource has "count = 0" or "for_each" over -// an empty collection then we want to retain it in the state so that references -// to it, particularly in "strange" contexts like "terraform console", can be -// properly resolved. -// -// This method MUST NOT be called concurrently with other readers and writers -// of the receiving state. -func (s *State) PruneResourceHusks() { - for _, m := range s.Modules { - m.PruneResourceHusks() - if len(m.Resources) == 0 && !m.Addr.IsRoot() { - s.RemoveModule(m.Addr) - } - } -} - -// SyncWrapper returns a SyncState object wrapping the receiver. -func (s *State) SyncWrapper() *SyncState { - return &SyncState{ - state: s, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_deepcopy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_deepcopy.go deleted file mode 100644 index 6266aca79dc..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_deepcopy.go +++ /dev/null @@ -1,221 +0,0 @@ -package states - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/zclconf/go-cty/cty" -) - -// Taking deep copies of states is an important operation because state is -// otherwise a mutable data structure that is challenging to share across -// many separate callers. It is important that the DeepCopy implementations -// in this file comprehensively copy all parts of the state data structure -// that could be mutated via pointers. - -// DeepCopy returns a new state that contains equivalent data to the reciever -// but shares no backing memory in common. -// -// As with all methods on State, this method is not safe to use concurrently -// with writing to any portion of the recieving data structure. It is the -// caller's responsibility to ensure mutual exclusion for the duration of the -// operation, but may then freely modify the receiver and the returned copy -// independently once this method returns. -func (s *State) DeepCopy() *State { - if s == nil { - return nil - } - - modules := make(map[string]*Module, len(s.Modules)) - for k, m := range s.Modules { - modules[k] = m.DeepCopy() - } - return &State{ - Modules: modules, - } -} - -// DeepCopy returns a new module state that contains equivalent data to the -// receiver but shares no backing memory in common. -// -// As with all methods on Module, this method is not safe to use concurrently -// with writing to any portion of the recieving data structure. It is the -// caller's responsibility to ensure mutual exclusion for the duration of the -// operation, but may then freely modify the receiver and the returned copy -// independently once this method returns. -func (ms *Module) DeepCopy() *Module { - if ms == nil { - return nil - } - - resources := make(map[string]*Resource, len(ms.Resources)) - for k, r := range ms.Resources { - resources[k] = r.DeepCopy() - } - outputValues := make(map[string]*OutputValue, len(ms.OutputValues)) - for k, v := range ms.OutputValues { - outputValues[k] = v.DeepCopy() - } - localValues := make(map[string]cty.Value, len(ms.LocalValues)) - for k, v := range ms.LocalValues { - // cty.Value is immutable, so we don't need to copy these. - localValues[k] = v - } - - return &Module{ - Addr: ms.Addr, // technically mutable, but immutable by convention - Resources: resources, - OutputValues: outputValues, - LocalValues: localValues, - } -} - -// DeepCopy returns a new resource state that contains equivalent data to the -// receiver but shares no backing memory in common. -// -// As with all methods on Resource, this method is not safe to use concurrently -// with writing to any portion of the recieving data structure. It is the -// caller's responsibility to ensure mutual exclusion for the duration of the -// operation, but may then freely modify the receiver and the returned copy -// independently once this method returns. -func (rs *Resource) DeepCopy() *Resource { - if rs == nil { - return nil - } - - instances := make(map[addrs.InstanceKey]*ResourceInstance, len(rs.Instances)) - for k, i := range rs.Instances { - instances[k] = i.DeepCopy() - } - - return &Resource{ - Addr: rs.Addr, - EachMode: rs.EachMode, - Instances: instances, - ProviderConfig: rs.ProviderConfig, // technically mutable, but immutable by convention - } -} - -// DeepCopy returns a new resource instance state that contains equivalent data -// to the receiver but shares no backing memory in common. -// -// As with all methods on ResourceInstance, this method is not safe to use -// concurrently with writing to any portion of the recieving data structure. It -// is the caller's responsibility to ensure mutual exclusion for the duration -// of the operation, but may then freely modify the receiver and the returned -// copy independently once this method returns. -func (is *ResourceInstance) DeepCopy() *ResourceInstance { - if is == nil { - return nil - } - - deposed := make(map[DeposedKey]*ResourceInstanceObjectSrc, len(is.Deposed)) - for k, obj := range is.Deposed { - deposed[k] = obj.DeepCopy() - } - - return &ResourceInstance{ - Current: is.Current.DeepCopy(), - Deposed: deposed, - } -} - -// DeepCopy returns a new resource instance object that contains equivalent data -// to the receiver but shares no backing memory in common. -// -// As with all methods on ResourceInstanceObjectSrc, this method is not safe to -// use concurrently with writing to any portion of the recieving data structure. -// It is the caller's responsibility to ensure mutual exclusion for the duration -// of the operation, but may then freely modify the receiver and the returned -// copy independently once this method returns. -func (obj *ResourceInstanceObjectSrc) DeepCopy() *ResourceInstanceObjectSrc { - if obj == nil { - return nil - } - - var attrsFlat map[string]string - if obj.AttrsFlat != nil { - attrsFlat = make(map[string]string, len(obj.AttrsFlat)) - for k, v := range obj.AttrsFlat { - attrsFlat[k] = v - } - } - - var attrsJSON []byte - if obj.AttrsJSON != nil { - attrsJSON = make([]byte, len(obj.AttrsJSON)) - copy(attrsJSON, obj.AttrsJSON) - } - - var private []byte - if obj.Private != nil { - private = make([]byte, len(obj.Private)) - copy(private, obj.Private) - } - - // Some addrs.Referencable implementations are technically mutable, but - // we treat them as immutable by convention and so we don't deep-copy here. - dependencies := make([]addrs.Referenceable, len(obj.Dependencies)) - copy(dependencies, obj.Dependencies) - - return &ResourceInstanceObjectSrc{ - Status: obj.Status, - SchemaVersion: obj.SchemaVersion, - Private: private, - AttrsFlat: attrsFlat, - AttrsJSON: attrsJSON, - Dependencies: dependencies, - } -} - -// DeepCopy returns a new resource instance object that contains equivalent data -// to the receiver but shares no backing memory in common. -// -// As with all methods on ResourceInstanceObject, this method is not safe to use -// concurrently with writing to any portion of the recieving data structure. It -// is the caller's responsibility to ensure mutual exclusion for the duration -// of the operation, but may then freely modify the receiver and the returned -// copy independently once this method returns. -func (obj *ResourceInstanceObject) DeepCopy() *ResourceInstanceObject { - if obj == nil { - return nil - } - - var private []byte - if obj.Private != nil { - private = make([]byte, len(obj.Private)) - copy(private, obj.Private) - } - - // Some addrs.Referenceable implementations are technically mutable, but - // we treat them as immutable by convention and so we don't deep-copy here. - var dependencies []addrs.Referenceable - if obj.Dependencies != nil { - dependencies = make([]addrs.Referenceable, len(obj.Dependencies)) - copy(dependencies, obj.Dependencies) - } - - return &ResourceInstanceObject{ - Value: obj.Value, - Status: obj.Status, - Private: private, - Dependencies: dependencies, - } -} - -// DeepCopy returns a new output value state that contains equivalent data -// to the receiver but shares no backing memory in common. -// -// As with all methods on OutputValue, this method is not safe to use -// concurrently with writing to any portion of the recieving data structure. It -// is the caller's responsibility to ensure mutual exclusion for the duration -// of the operation, but may then freely modify the receiver and the returned -// copy independently once this method returns. -func (os *OutputValue) DeepCopy() *OutputValue { - if os == nil { - return nil - } - - return &OutputValue{ - Value: os.Value, - Sensitive: os.Sensitive, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_equal.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_equal.go deleted file mode 100644 index ea20967e5b9..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_equal.go +++ /dev/null @@ -1,18 +0,0 @@ -package states - -import ( - "reflect" -) - -// Equal returns true if the receiver is functionally equivalent to other, -// including any ephemeral portions of the state that would not be included -// if the state were saved to files. -// -// To test only the persistent portions of two states for equality, instead -// use statefile.StatesMarshalEqual. -func (s *State) Equal(other *State) bool { - // For the moment this is sufficient, but we may need to do something - // more elaborate in future if we have any portions of state that require - // more sophisticated comparisons. - return reflect.DeepEqual(s, other) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_string.go deleted file mode 100644 index dffd650d6b0..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_string.go +++ /dev/null @@ -1,279 +0,0 @@ -package states - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "sort" - "strings" - - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" -) - -// String returns a rather-odd string representation of the entire state. -// -// This is intended to match the behavior of the older terraform.State.String -// method that is used in lots of existing tests. It should not be used in -// new tests: instead, use "cmp" to directly compare the state data structures -// and print out a diff if they do not match. -// -// This method should never be used in non-test code, whether directly by call -// or indirectly via a %s or %q verb in package fmt. -func (s *State) String() string { - if s == nil { - return "" - } - - // sort the modules by name for consistent output - modules := make([]string, 0, len(s.Modules)) - for m := range s.Modules { - modules = append(modules, m) - } - sort.Strings(modules) - - var buf bytes.Buffer - for _, name := range modules { - m := s.Modules[name] - mStr := m.testString() - - // If we're the root module, we just write the output directly. - if m.Addr.IsRoot() { - buf.WriteString(mStr + "\n") - continue - } - - // We need to build out a string that resembles the not-quite-standard - // format that terraform.State.String used to use, where there's a - // "module." prefix but then just a chain of all of the module names - // without any further "module." portions. - buf.WriteString("module") - for _, step := range m.Addr { - buf.WriteByte('.') - buf.WriteString(step.Name) - if step.InstanceKey != addrs.NoKey { - buf.WriteByte('[') - buf.WriteString(step.InstanceKey.String()) - buf.WriteByte(']') - } - } - buf.WriteString(":\n") - - s := bufio.NewScanner(strings.NewReader(mStr)) - for s.Scan() { - text := s.Text() - if text != "" { - text = " " + text - } - - buf.WriteString(fmt.Sprintf("%s\n", text)) - } - } - - return strings.TrimSpace(buf.String()) -} - -// testString is used to produce part of the output of State.String. It should -// never be used directly. -func (m *Module) testString() string { - var buf bytes.Buffer - - if len(m.Resources) == 0 { - buf.WriteString("") - } - - // We use AbsResourceInstance here, even though everything belongs to - // the same module, just because we have a sorting behavior defined - // for those but not for just ResourceInstance. - addrsOrder := make([]addrs.AbsResourceInstance, 0, len(m.Resources)) - for _, rs := range m.Resources { - for ik := range rs.Instances { - addrsOrder = append(addrsOrder, rs.Addr.Instance(ik).Absolute(addrs.RootModuleInstance)) - } - } - - sort.Slice(addrsOrder, func(i, j int) bool { - return addrsOrder[i].Less(addrsOrder[j]) - }) - - for _, fakeAbsAddr := range addrsOrder { - addr := fakeAbsAddr.Resource - rs := m.Resource(addr.ContainingResource()) - is := m.ResourceInstance(addr) - - // Here we need to fake up a legacy-style address as the old state - // types would've used, since that's what our tests against those - // old types expect. The significant difference is that instancekey - // is dot-separated rather than using index brackets. - k := addr.ContainingResource().String() - if addr.Key != addrs.NoKey { - switch tk := addr.Key.(type) { - case addrs.IntKey: - k = fmt.Sprintf("%s.%d", k, tk) - default: - // No other key types existed for the legacy types, so we - // can do whatever we want here. We'll just use our standard - // syntax for these. - k = k + tk.String() - } - } - - id := LegacyInstanceObjectID(is.Current) - - taintStr := "" - if is.Current != nil && is.Current.Status == ObjectTainted { - taintStr = " (tainted)" - } - - deposedStr := "" - if len(is.Deposed) > 0 { - deposedStr = fmt.Sprintf(" (%d deposed)", len(is.Deposed)) - } - - buf.WriteString(fmt.Sprintf("%s:%s%s\n", k, taintStr, deposedStr)) - buf.WriteString(fmt.Sprintf(" ID = %s\n", id)) - buf.WriteString(fmt.Sprintf(" provider = %s\n", rs.ProviderConfig.String())) - - // Attributes were a flatmap before, but are not anymore. To preserve - // our old output as closely as possible we need to do a conversion - // to flatmap. Normally we'd want to do this with schema for - // accuracy, but for our purposes here it only needs to be approximate. - // This should produce an identical result for most cases, though - // in particular will differ in a few cases: - // - The keys used for elements in a set will be different - // - Values for attributes of type cty.DynamicPseudoType will be - // misinterpreted (but these weren't possible in old world anyway) - var attributes map[string]string - if obj := is.Current; obj != nil { - switch { - case obj.AttrsFlat != nil: - // Easy (but increasingly unlikely) case: the state hasn't - // actually been upgraded to the new form yet. - attributes = obj.AttrsFlat - case obj.AttrsJSON != nil: - ty, err := ctyjson.ImpliedType(obj.AttrsJSON) - if err == nil { - val, err := ctyjson.Unmarshal(obj.AttrsJSON, ty) - if err == nil { - attributes = hcl2shim.FlatmapValueFromHCL2(val) - } - } - } - } - attrKeys := make([]string, 0, len(attributes)) - for ak, val := range attributes { - if ak == "id" { - continue - } - - // don't show empty containers in the output - if val == "0" && (strings.HasSuffix(ak, ".#") || strings.HasSuffix(ak, ".%")) { - continue - } - - attrKeys = append(attrKeys, ak) - } - - sort.Strings(attrKeys) - - for _, ak := range attrKeys { - av := attributes[ak] - buf.WriteString(fmt.Sprintf(" %s = %s\n", ak, av)) - } - - // CAUTION: Since deposed keys are now random strings instead of - // incrementing integers, this result will not be deterministic - // if there is more than one deposed object. - i := 1 - for _, t := range is.Deposed { - id := LegacyInstanceObjectID(t) - taintStr := "" - if t.Status == ObjectTainted { - taintStr = " (tainted)" - } - buf.WriteString(fmt.Sprintf(" Deposed ID %d = %s%s\n", i, id, taintStr)) - i++ - } - - if obj := is.Current; obj != nil && len(obj.Dependencies) > 0 { - buf.WriteString(fmt.Sprintf("\n Dependencies:\n")) - for _, dep := range obj.Dependencies { - buf.WriteString(fmt.Sprintf(" %s\n", dep.String())) - } - } - } - - if len(m.OutputValues) > 0 { - buf.WriteString("\nOutputs:\n\n") - - ks := make([]string, 0, len(m.OutputValues)) - for k := range m.OutputValues { - ks = append(ks, k) - } - sort.Strings(ks) - - for _, k := range ks { - v := m.OutputValues[k] - lv := hcl2shim.ConfigValueFromHCL2(v.Value) - switch vTyped := lv.(type) { - case string: - buf.WriteString(fmt.Sprintf("%s = %s\n", k, vTyped)) - case []interface{}: - buf.WriteString(fmt.Sprintf("%s = %s\n", k, vTyped)) - case map[string]interface{}: - var mapKeys []string - for key := range vTyped { - mapKeys = append(mapKeys, key) - } - sort.Strings(mapKeys) - - var mapBuf bytes.Buffer - mapBuf.WriteString("{") - for _, key := range mapKeys { - mapBuf.WriteString(fmt.Sprintf("%s:%s ", key, vTyped[key])) - } - mapBuf.WriteString("}") - - buf.WriteString(fmt.Sprintf("%s = %s\n", k, mapBuf.String())) - default: - buf.WriteString(fmt.Sprintf("%s = %#v\n", k, lv)) - } - } - } - - return buf.String() -} - -// LegacyInstanceObjectID is a helper for extracting an object id value from -// an instance object in a way that approximates how we used to do this -// for the old state types. ID is no longer first-class, so this is preserved -// only for compatibility with old tests that include the id as part of their -// expected value. -func LegacyInstanceObjectID(obj *ResourceInstanceObjectSrc) string { - if obj == nil { - return "" - } - - if obj.AttrsJSON != nil { - type WithID struct { - ID string `json:"id"` - } - var withID WithID - err := json.Unmarshal(obj.AttrsJSON, &withID) - if err == nil { - return withID.ID - } - } else if obj.AttrsFlat != nil { - if flatID, exists := obj.AttrsFlat["id"]; exists { - return flatID - } - } - - // For resource types created after we removed id as special there may - // not actually be one at all. This is okay because older tests won't - // encounter this, and new tests shouldn't be using ids. - return "" -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/diagnostics.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/diagnostics.go deleted file mode 100644 index 042ce51c144..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/diagnostics.go +++ /dev/null @@ -1,62 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -const invalidFormat = "Invalid state file format" - -// jsonUnmarshalDiags is a helper that translates errors returned from -// json.Unmarshal into hopefully-more-helpful diagnostics messages. -func jsonUnmarshalDiags(err error) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - if err == nil { - return diags - } - - switch tErr := err.(type) { - case *json.SyntaxError: - // We've usually already successfully parsed a source file as JSON at - // least once before we'd use jsonUnmarshalDiags with it (to sniff - // the version number) so this particular error should not appear much - // in practice. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - invalidFormat, - fmt.Sprintf("The state file could not be parsed as JSON: syntax error at byte offset %d.", tErr.Offset), - )) - case *json.UnmarshalTypeError: - // This is likely to be the most common area, describing a - // non-conformance between the file and the expected file format - // at a semantic level. - if tErr.Field != "" { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - invalidFormat, - fmt.Sprintf("The state file field %q has invalid value %s", tErr.Field, tErr.Value), - )) - break - } else { - // Without a field name, we can't really say anything helpful. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - invalidFormat, - "The state file does not conform to the expected JSON data structure.", - )) - } - default: - // Fallback for all other types of errors. This can happen only for - // custom UnmarshalJSON implementations, so should be encountered - // only rarely. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - invalidFormat, - fmt.Sprintf("The state file does not conform to the expected JSON data structure: %s.", err.Error()), - )) - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/doc.go deleted file mode 100644 index 625d0cf429a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package statefile deals with the file format used to serialize states for -// persistent storage and then deserialize them into memory again later. -package statefile diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/file.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/file.go deleted file mode 100644 index 70c8ba6cec2..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/file.go +++ /dev/null @@ -1,31 +0,0 @@ -package statefile - -import ( - version "github.com/hashicorp/go-version" - - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// File is the in-memory representation of a state file. It includes the state -// itself along with various metadata used to track changing state files for -// the same configuration over time. -type File struct { - // TerraformVersion is the version of Terraform that wrote this state file. - TerraformVersion *version.Version - - // Serial is incremented on any operation that modifies - // the State file. It is used to detect potentially conflicting - // updates. - Serial uint64 - - // Lineage is set when a new, blank state file is created and then - // never updated. This allows us to determine whether the serials - // of two states can be meaningfully compared. - // Apart from the guarantee that collisions between two lineages - // are very unlikely, this value is opaque and external callers - // should only compare lineage strings byte-for-byte for equality. - Lineage string - - // State is the actual state represented by this file. - State *states.State -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/read.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/read.go deleted file mode 100644 index f1899cd228e..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/read.go +++ /dev/null @@ -1,209 +0,0 @@ -package statefile - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - - version "github.com/hashicorp/go-version" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - tfversion "github.com/hashicorp/terraform-plugin-sdk/internal/version" -) - -// ErrNoState is returned by ReadState when the state file is empty. -var ErrNoState = errors.New("no state") - -// Read reads a state from the given reader. -// -// Legacy state format versions 1 through 3 are supported, but the result will -// contain object attributes in the deprecated "flatmap" format and so must -// be upgraded by the caller before use. -// -// If the state file is empty, the special error value ErrNoState is returned. -// Otherwise, the returned error might be a wrapper around tfdiags.Diagnostics -// potentially describing multiple errors. -func Read(r io.Reader) (*File, error) { - // Some callers provide us a "typed nil" *os.File here, which would - // cause us to panic below if we tried to use it. - if f, ok := r.(*os.File); ok && f == nil { - return nil, ErrNoState - } - - var diags tfdiags.Diagnostics - - // We actually just buffer the whole thing in memory, because states are - // generally not huge and we need to do be able to sniff for a version - // number before full parsing. - src, err := ioutil.ReadAll(r) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to read state file", - fmt.Sprintf("The state file could not be read: %s", err), - )) - return nil, diags.Err() - } - - if len(src) == 0 { - return nil, ErrNoState - } - - state, diags := readState(src) - if diags.HasErrors() { - return nil, diags.Err() - } - - if state == nil { - // Should never happen - panic("readState returned nil state with no errors") - } - - if state.TerraformVersion != nil && state.TerraformVersion.GreaterThan(tfversion.SemVer) { - return state, fmt.Errorf( - "state snapshot was created by Terraform v%s, which is newer than current v%s; upgrade to Terraform v%s or greater to work with this state", - state.TerraformVersion, - tfversion.SemVer, - state.TerraformVersion, - ) - } - - return state, diags.Err() -} - -func readState(src []byte) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - if looksLikeVersion0(src) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - "The state is stored in a legacy binary format that is not supported since Terraform v0.7. To continue, first upgrade the state using Terraform 0.6.16 or earlier.", - )) - return nil, diags - } - - version, versionDiags := sniffJSONStateVersion(src) - diags = diags.Append(versionDiags) - if versionDiags.HasErrors() { - return nil, diags - } - - switch version { - case 0: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - "The state file uses JSON syntax but has a version number of zero. There was never a JSON-based state format zero, so this state file is invalid and cannot be processed.", - )) - return nil, diags - case 1: - return readStateV1(src) - case 2: - return readStateV2(src) - case 3: - return readStateV3(src) - case 4: - return readStateV4(src) - default: - thisVersion := tfversion.SemVer.String() - creatingVersion := sniffJSONStateTerraformVersion(src) - switch { - case creatingVersion != "": - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - fmt.Sprintf("The state file uses format version %d, which is not supported by Terraform %s. This state file was created by Terraform %s.", version, thisVersion, creatingVersion), - )) - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - fmt.Sprintf("The state file uses format version %d, which is not supported by Terraform %s. This state file may have been created by a newer version of Terraform.", version, thisVersion), - )) - } - return nil, diags - } -} - -func sniffJSONStateVersion(src []byte) (uint64, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - type VersionSniff struct { - Version *uint64 `json:"version"` - } - var sniff VersionSniff - err := json.Unmarshal(src, &sniff) - if err != nil { - switch tErr := err.(type) { - case *json.SyntaxError: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - fmt.Sprintf("The state file could not be parsed as JSON: syntax error at byte offset %d.", tErr.Offset), - )) - case *json.UnmarshalTypeError: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - fmt.Sprintf("The version in the state file is %s. A positive whole number is required.", tErr.Value), - )) - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - "The state file could not be parsed as JSON.", - )) - } - } - - if sniff.Version == nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - unsupportedFormat, - "The state file does not have a \"version\" attribute, which is required to identify the format version.", - )) - return 0, diags - } - - return *sniff.Version, diags -} - -// sniffJSONStateTerraformVersion attempts to sniff the Terraform version -// specification from the given state file source code. The result is either -// a version string or an empty string if no version number could be extracted. -// -// This is a best-effort function intended to produce nicer error messages. It -// should not be used for any real processing. -func sniffJSONStateTerraformVersion(src []byte) string { - type VersionSniff struct { - Version string `json:"terraform_version"` - } - var sniff VersionSniff - - err := json.Unmarshal(src, &sniff) - if err != nil { - return "" - } - - // Attempt to parse the string as a version so we won't report garbage - // as a version number. - _, err = version.NewVersion(sniff.Version) - if err != nil { - return "" - } - - return sniff.Version -} - -// unsupportedFormat is a diagnostic summary message for when the state file -// seems to not be a state file at all, or is not a supported version. -// -// Use invalidFormat instead for the subtly-different case of "this looks like -// it's intended to be a state file but it's not structured correctly". -const unsupportedFormat = "Unsupported state file format" - -const upgradeFailed = "State format upgrade failed" diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version0.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version0.go deleted file mode 100644 index 9b533317bd2..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version0.go +++ /dev/null @@ -1,23 +0,0 @@ -package statefile - -// looksLikeVersion0 sniffs for the signature indicating a version 0 state -// file. -// -// Version 0 was the number retroactively assigned to Terraform's initial -// (unversioned) binary state file format, which was later superseded by the -// version 1 format in JSON. -// -// Version 0 is no longer supported, so this is used only to detect it and -// return a nice error to the user. -func looksLikeVersion0(src []byte) bool { - // Version 0 files begin with the magic prefix "tfstate". - const magic = "tfstate" - if len(src) < len(magic) { - // Not even long enough to have the magic prefix - return false - } - if string(src[0:len(magic)]) == magic { - return true - } - return false -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version1.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version1.go deleted file mode 100644 index 85b422ad22b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version1.go +++ /dev/null @@ -1,167 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -func readStateV1(src []byte) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV1 := &stateV1{} - err := json.Unmarshal(src, sV1) - if err != nil { - diags = diags.Append(jsonUnmarshalDiags(err)) - return nil, diags - } - - file, prepDiags := prepareStateV1(sV1) - diags = diags.Append(prepDiags) - return file, diags -} - -func prepareStateV1(sV1 *stateV1) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV2, err := upgradeStateV1ToV2(sV1) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - upgradeFailed, - fmt.Sprintf("Error upgrading state file format from version 1 to version 2: %s.", err), - )) - return nil, diags - } - - file, prepDiags := prepareStateV2(sV2) - diags = diags.Append(prepDiags) - return file, diags -} - -// stateV1 is a representation of the legacy JSON state format version 1. -// -// It is only used to read version 1 JSON files prior to upgrading them to -// the current format. -type stateV1 struct { - // Version is the protocol version. "1" for a StateV1. - Version int `json:"version"` - - // Serial is incremented on any operation that modifies - // the State file. It is used to detect potentially conflicting - // updates. - Serial int64 `json:"serial"` - - // Remote is used to track the metadata required to - // pull and push state files from a remote storage endpoint. - Remote *remoteStateV1 `json:"remote,omitempty"` - - // Modules contains all the modules in a breadth-first order - Modules []*moduleStateV1 `json:"modules"` -} - -type remoteStateV1 struct { - // Type controls the client we use for the remote state - Type string `json:"type"` - - // Config is used to store arbitrary configuration that - // is type specific - Config map[string]string `json:"config"` -} - -type moduleStateV1 struct { - // Path is the import path from the root module. Modules imports are - // always disjoint, so the path represents amodule tree - Path []string `json:"path"` - - // Outputs declared by the module and maintained for each module - // even though only the root module technically needs to be kept. - // This allows operators to inspect values at the boundaries. - Outputs map[string]string `json:"outputs"` - - // Resources is a mapping of the logically named resource to - // the state of the resource. Each resource may actually have - // N instances underneath, although a user only needs to think - // about the 1:1 case. - Resources map[string]*resourceStateV1 `json:"resources"` - - // Dependencies are a list of things that this module relies on - // existing to remain intact. For example: an module may depend - // on a VPC ID given by an aws_vpc resource. - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a module that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on,omitempty"` -} - -type resourceStateV1 struct { - // This is filled in and managed by Terraform, and is the resource - // type itself such as "mycloud_instance". If a resource provider sets - // this value, it won't be persisted. - Type string `json:"type"` - - // Dependencies are a list of things that this resource relies on - // existing to remain intact. For example: an AWS instance might - // depend on a subnet (which itself might depend on a VPC, and so - // on). - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a resource that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on,omitempty"` - - // Primary is the current active instance for this resource. - // It can be replaced but only after a successful creation. - // This is the instances on which providers will act. - Primary *instanceStateV1 `json:"primary"` - - // Tainted is used to track any underlying instances that - // have been created but are in a bad or unknown state and - // need to be cleaned up subsequently. In the - // standard case, there is only at most a single instance. - // However, in pathological cases, it is possible for the number - // of instances to accumulate. - Tainted []*instanceStateV1 `json:"tainted,omitempty"` - - // Deposed is used in the mechanics of CreateBeforeDestroy: the existing - // Primary is Deposed to get it out of the way for the replacement Primary to - // be created by Apply. If the replacement Primary creates successfully, the - // Deposed instance is cleaned up. If there were problems creating the - // replacement, the instance remains in the Deposed list so it can be - // destroyed in a future run. Functionally, Deposed instances are very - // similar to Tainted instances in that Terraform is only tracking them in - // order to remember to destroy them. - Deposed []*instanceStateV1 `json:"deposed,omitempty"` - - // Provider is used when a resource is connected to a provider with an alias. - // If this string is empty, the resource is connected to the default provider, - // e.g. "aws_instance" goes with the "aws" provider. - // If the resource block contained a "provider" key, that value will be set here. - Provider string `json:"provider,omitempty"` -} - -type instanceStateV1 struct { - // A unique ID for this resource. This is opaque to Terraform - // and is only meant as a lookup mechanism for the providers. - ID string `json:"id"` - - // Attributes are basic information about the resource. Any keys here - // are accessible in variable format within Terraform configurations: - // ${resourcetype.name.attribute}. - Attributes map[string]string `json:"attributes,omitempty"` - - // Meta is a simple K/V map that is persisted to the State but otherwise - // ignored by Terraform core. It's meant to be used for accounting by - // external client code. - Meta map[string]string `json:"meta,omitempty"` -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version1_upgrade.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version1_upgrade.go deleted file mode 100644 index 0b417e1c401..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version1_upgrade.go +++ /dev/null @@ -1,172 +0,0 @@ -package statefile - -import ( - "fmt" - "log" - - "github.com/mitchellh/copystructure" -) - -// upgradeStateV1ToV2 is used to upgrade a V1 state representation -// into a V2 state representation -func upgradeStateV1ToV2(old *stateV1) (*stateV2, error) { - log.Printf("[TRACE] statefile.Read: upgrading format from v1 to v2") - if old == nil { - return nil, nil - } - - remote, err := old.Remote.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading State V1: %v", err) - } - - modules := make([]*moduleStateV2, len(old.Modules)) - for i, module := range old.Modules { - upgraded, err := module.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading State V1: %v", err) - } - modules[i] = upgraded - } - if len(modules) == 0 { - modules = nil - } - - newState := &stateV2{ - Version: 2, - Serial: old.Serial, - Remote: remote, - Modules: modules, - } - - return newState, nil -} - -func (old *remoteStateV1) upgradeToV2() (*remoteStateV2, error) { - if old == nil { - return nil, nil - } - - config, err := copystructure.Copy(old.Config) - if err != nil { - return nil, fmt.Errorf("Error upgrading RemoteState V1: %v", err) - } - - return &remoteStateV2{ - Type: old.Type, - Config: config.(map[string]string), - }, nil -} - -func (old *moduleStateV1) upgradeToV2() (*moduleStateV2, error) { - if old == nil { - return nil, nil - } - - pathRaw, err := copystructure.Copy(old.Path) - if err != nil { - return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err) - } - path, ok := pathRaw.([]string) - if !ok { - return nil, fmt.Errorf("Error upgrading ModuleState V1: path is not a list of strings") - } - if len(path) == 0 { - // We found some V1 states with a nil path. Assume root. - path = []string{"root"} - } - - // Outputs needs upgrading to use the new structure - outputs := make(map[string]*outputStateV2) - for key, output := range old.Outputs { - outputs[key] = &outputStateV2{ - Type: "string", - Value: output, - Sensitive: false, - } - } - - resources := make(map[string]*resourceStateV2) - for key, oldResource := range old.Resources { - upgraded, err := oldResource.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err) - } - resources[key] = upgraded - } - - dependencies, err := copystructure.Copy(old.Dependencies) - if err != nil { - return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err) - } - - return &moduleStateV2{ - Path: path, - Outputs: outputs, - Resources: resources, - Dependencies: dependencies.([]string), - }, nil -} - -func (old *resourceStateV1) upgradeToV2() (*resourceStateV2, error) { - if old == nil { - return nil, nil - } - - dependencies, err := copystructure.Copy(old.Dependencies) - if err != nil { - return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err) - } - - primary, err := old.Primary.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err) - } - - deposed := make([]*instanceStateV2, len(old.Deposed)) - for i, v := range old.Deposed { - upgraded, err := v.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err) - } - deposed[i] = upgraded - } - if len(deposed) == 0 { - deposed = nil - } - - return &resourceStateV2{ - Type: old.Type, - Dependencies: dependencies.([]string), - Primary: primary, - Deposed: deposed, - Provider: old.Provider, - }, nil -} - -func (old *instanceStateV1) upgradeToV2() (*instanceStateV2, error) { - if old == nil { - return nil, nil - } - - attributes, err := copystructure.Copy(old.Attributes) - if err != nil { - return nil, fmt.Errorf("Error upgrading InstanceState V1: %v", err) - } - - meta, err := copystructure.Copy(old.Meta) - if err != nil { - return nil, fmt.Errorf("Error upgrading InstanceState V1: %v", err) - } - - newMeta := make(map[string]interface{}) - for k, v := range meta.(map[string]string) { - newMeta[k] = v - } - - return &instanceStateV2{ - ID: old.ID, - Attributes: attributes.(map[string]string), - Meta: newMeta, - }, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version2.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version2.go deleted file mode 100644 index 6d10166b2e6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version2.go +++ /dev/null @@ -1,204 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -func readStateV2(src []byte) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV2 := &stateV2{} - err := json.Unmarshal(src, sV2) - if err != nil { - diags = diags.Append(jsonUnmarshalDiags(err)) - return nil, diags - } - - file, prepDiags := prepareStateV2(sV2) - diags = diags.Append(prepDiags) - return file, diags -} - -func prepareStateV2(sV2 *stateV2) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV3, err := upgradeStateV2ToV3(sV2) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - upgradeFailed, - fmt.Sprintf("Error upgrading state file format from version 2 to version 3: %s.", err), - )) - return nil, diags - } - - file, prepDiags := prepareStateV3(sV3) - diags = diags.Append(prepDiags) - return file, diags -} - -// stateV2 is a representation of the legacy JSON state format version 2. -// -// It is only used to read version 2 JSON files prior to upgrading them to -// the current format. -type stateV2 struct { - // Version is the state file protocol version. - Version int `json:"version"` - - // TFVersion is the version of Terraform that wrote this state. - TFVersion string `json:"terraform_version,omitempty"` - - // Serial is incremented on any operation that modifies - // the State file. It is used to detect potentially conflicting - // updates. - Serial int64 `json:"serial"` - - // Lineage is set when a new, blank state is created and then - // never updated. This allows us to determine whether the serials - // of two states can be meaningfully compared. - // Apart from the guarantee that collisions between two lineages - // are very unlikely, this value is opaque and external callers - // should only compare lineage strings byte-for-byte for equality. - Lineage string `json:"lineage"` - - // Remote is used to track the metadata required to - // pull and push state files from a remote storage endpoint. - Remote *remoteStateV2 `json:"remote,omitempty"` - - // Backend tracks the configuration for the backend in use with - // this state. This is used to track any changes in the backend - // configuration. - Backend *backendStateV2 `json:"backend,omitempty"` - - // Modules contains all the modules in a breadth-first order - Modules []*moduleStateV2 `json:"modules"` -} - -type remoteStateV2 struct { - // Type controls the client we use for the remote state - Type string `json:"type"` - - // Config is used to store arbitrary configuration that - // is type specific - Config map[string]string `json:"config"` -} - -type outputStateV2 struct { - // Sensitive describes whether the output is considered sensitive, - // which may lead to masking the value on screen in some cases. - Sensitive bool `json:"sensitive"` - // Type describes the structure of Value. Valid values are "string", - // "map" and "list" - Type string `json:"type"` - // Value contains the value of the output, in the structure described - // by the Type field. - Value interface{} `json:"value"` -} - -type moduleStateV2 struct { - // Path is the import path from the root module. Modules imports are - // always disjoint, so the path represents amodule tree - Path []string `json:"path"` - - // Locals are kept only transiently in-memory, because we can always - // re-compute them. - Locals map[string]interface{} `json:"-"` - - // Outputs declared by the module and maintained for each module - // even though only the root module technically needs to be kept. - // This allows operators to inspect values at the boundaries. - Outputs map[string]*outputStateV2 `json:"outputs"` - - // Resources is a mapping of the logically named resource to - // the state of the resource. Each resource may actually have - // N instances underneath, although a user only needs to think - // about the 1:1 case. - Resources map[string]*resourceStateV2 `json:"resources"` - - // Dependencies are a list of things that this module relies on - // existing to remain intact. For example: an module may depend - // on a VPC ID given by an aws_vpc resource. - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a module that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on"` -} - -type resourceStateV2 struct { - // This is filled in and managed by Terraform, and is the resource - // type itself such as "mycloud_instance". If a resource provider sets - // this value, it won't be persisted. - Type string `json:"type"` - - // Dependencies are a list of things that this resource relies on - // existing to remain intact. For example: an AWS instance might - // depend on a subnet (which itself might depend on a VPC, and so - // on). - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a resource that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on"` - - // Primary is the current active instance for this resource. - // It can be replaced but only after a successful creation. - // This is the instances on which providers will act. - Primary *instanceStateV2 `json:"primary"` - - // Deposed is used in the mechanics of CreateBeforeDestroy: the existing - // Primary is Deposed to get it out of the way for the replacement Primary to - // be created by Apply. If the replacement Primary creates successfully, the - // Deposed instance is cleaned up. - // - // If there were problems creating the replacement Primary, the Deposed - // instance and the (now tainted) replacement Primary will be swapped so the - // tainted replacement will be cleaned up instead. - // - // An instance will remain in the Deposed list until it is successfully - // destroyed and purged. - Deposed []*instanceStateV2 `json:"deposed"` - - // Provider is used when a resource is connected to a provider with an alias. - // If this string is empty, the resource is connected to the default provider, - // e.g. "aws_instance" goes with the "aws" provider. - // If the resource block contained a "provider" key, that value will be set here. - Provider string `json:"provider"` -} - -type instanceStateV2 struct { - // A unique ID for this resource. This is opaque to Terraform - // and is only meant as a lookup mechanism for the providers. - ID string `json:"id"` - - // Attributes are basic information about the resource. Any keys here - // are accessible in variable format within Terraform configurations: - // ${resourcetype.name.attribute}. - Attributes map[string]string `json:"attributes"` - - // Meta is a simple K/V map that is persisted to the State but otherwise - // ignored by Terraform core. It's meant to be used for accounting by - // external client code. The value here must only contain Go primitives - // and collections. - Meta map[string]interface{} `json:"meta"` - - // Tainted is used to mark a resource for recreation. - Tainted bool `json:"tainted"` -} - -type backendStateV2 struct { - Type string `json:"type"` // Backend type - ConfigRaw json.RawMessage `json:"config"` // Backend raw config - Hash uint64 `json:"hash"` // Hash of portion of configuration from config files -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version2_upgrade.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version2_upgrade.go deleted file mode 100644 index 2d03c07c9dc..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version2_upgrade.go +++ /dev/null @@ -1,145 +0,0 @@ -package statefile - -import ( - "fmt" - "log" - "regexp" - "sort" - "strconv" - "strings" - - "github.com/mitchellh/copystructure" -) - -func upgradeStateV2ToV3(old *stateV2) (*stateV3, error) { - if old == nil { - return (*stateV3)(nil), nil - } - - var new *stateV3 - { - copy, err := copystructure.Config{Lock: true}.Copy(old) - if err != nil { - panic(err) - } - newWrongType := copy.(*stateV2) - newRightType := (stateV3)(*newWrongType) - new = &newRightType - } - - // Set the new version number - new.Version = 3 - - // Change the counts for things which look like maps to use the % - // syntax. Remove counts for empty collections - they will be added - // back in later. - for _, module := range new.Modules { - for _, resource := range module.Resources { - // Upgrade Primary - if resource.Primary != nil { - upgradeAttributesV2ToV3(resource.Primary) - } - - // Upgrade Deposed - for _, deposed := range resource.Deposed { - upgradeAttributesV2ToV3(deposed) - } - } - } - - return new, nil -} - -func upgradeAttributesV2ToV3(instanceState *instanceStateV2) error { - collectionKeyRegexp := regexp.MustCompile(`^(.*\.)#$`) - collectionSubkeyRegexp := regexp.MustCompile(`^([^\.]+)\..*`) - - // Identify the key prefix of anything which is a collection - var collectionKeyPrefixes []string - for key := range instanceState.Attributes { - if submatches := collectionKeyRegexp.FindAllStringSubmatch(key, -1); len(submatches) > 0 { - collectionKeyPrefixes = append(collectionKeyPrefixes, submatches[0][1]) - } - } - sort.Strings(collectionKeyPrefixes) - - log.Printf("[STATE UPGRADE] Detected the following collections in state: %v", collectionKeyPrefixes) - - // This could be rolled into fewer loops, but it is somewhat clearer this way, and will not - // run very often. - for _, prefix := range collectionKeyPrefixes { - // First get the actual keys that belong to this prefix - var potentialKeysMatching []string - for key := range instanceState.Attributes { - if strings.HasPrefix(key, prefix) { - potentialKeysMatching = append(potentialKeysMatching, strings.TrimPrefix(key, prefix)) - } - } - sort.Strings(potentialKeysMatching) - - var actualKeysMatching []string - for _, key := range potentialKeysMatching { - if submatches := collectionSubkeyRegexp.FindAllStringSubmatch(key, -1); len(submatches) > 0 { - actualKeysMatching = append(actualKeysMatching, submatches[0][1]) - } else { - if key != "#" { - actualKeysMatching = append(actualKeysMatching, key) - } - } - } - actualKeysMatching = uniqueSortedStrings(actualKeysMatching) - - // Now inspect the keys in order to determine whether this is most likely to be - // a map, list or set. There is room for error here, so we log in each case. If - // there is no method of telling, we remove the key from the InstanceState in - // order that it will be recreated. Again, this could be rolled into fewer loops - // but we prefer clarity. - - oldCountKey := fmt.Sprintf("%s#", prefix) - - // First, detect "obvious" maps - which have non-numeric keys (mostly). - hasNonNumericKeys := false - for _, key := range actualKeysMatching { - if _, err := strconv.Atoi(key); err != nil { - hasNonNumericKeys = true - } - } - if hasNonNumericKeys { - newCountKey := fmt.Sprintf("%s%%", prefix) - - instanceState.Attributes[newCountKey] = instanceState.Attributes[oldCountKey] - delete(instanceState.Attributes, oldCountKey) - log.Printf("[STATE UPGRADE] Detected %s as a map. Replaced count = %s", - strings.TrimSuffix(prefix, "."), instanceState.Attributes[newCountKey]) - } - - // Now detect empty collections and remove them from state. - if len(actualKeysMatching) == 0 { - delete(instanceState.Attributes, oldCountKey) - log.Printf("[STATE UPGRADE] Detected %s as an empty collection. Removed from state.", - strings.TrimSuffix(prefix, ".")) - } - } - - return nil -} - -// uniqueSortedStrings removes duplicates from a slice of strings and returns -// a sorted slice of the unique strings. -func uniqueSortedStrings(input []string) []string { - uniquemap := make(map[string]struct{}) - for _, str := range input { - uniquemap[str] = struct{}{} - } - - output := make([]string, len(uniquemap)) - - i := 0 - for key := range uniquemap { - output[i] = key - i = i + 1 - } - - sort.Strings(output) - return output -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version3.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version3.go deleted file mode 100644 index 1c81e7169e5..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version3.go +++ /dev/null @@ -1,50 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -func readStateV3(src []byte) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV3 := &stateV3{} - err := json.Unmarshal(src, sV3) - if err != nil { - diags = diags.Append(jsonUnmarshalDiags(err)) - return nil, diags - } - - file, prepDiags := prepareStateV3(sV3) - diags = diags.Append(prepDiags) - return file, diags -} - -func prepareStateV3(sV3 *stateV3) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV4, err := upgradeStateV3ToV4(sV3) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - upgradeFailed, - fmt.Sprintf("Error upgrading state file format from version 3 to version 4: %s.", err), - )) - return nil, diags - } - - file, prepDiags := prepareStateV4(sV4) - diags = diags.Append(prepDiags) - return file, diags -} - -// stateV2 is a representation of the legacy JSON state format version 3. -// -// It is only used to read version 3 JSON files prior to upgrading them to -// the current format. -// -// The differences between version 2 and version 3 are only in the data and -// not in the structure, so stateV3 actually shares the same structs as -// stateV2. Type stateV3 represents that the data within is formatted as -// expected by the V3 format, rather than the V2 format. -type stateV3 stateV2 diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version3_upgrade.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version3_upgrade.go deleted file mode 100644 index f08a62b2d59..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version3_upgrade.go +++ /dev/null @@ -1,444 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - "strconv" - "strings" - - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -func upgradeStateV3ToV4(old *stateV3) (*stateV4, error) { - - if old.Serial < 0 { - // The new format is using uint64 here, which should be fine for any - // real state (we only used positive integers in practice) but we'll - // catch this explicitly here to avoid weird behavior if a state file - // has been tampered with in some way. - return nil, fmt.Errorf("state has serial less than zero, which is invalid") - } - - new := &stateV4{ - TerraformVersion: old.TFVersion, - Serial: uint64(old.Serial), - Lineage: old.Lineage, - RootOutputs: map[string]outputStateV4{}, - Resources: []resourceStateV4{}, - } - - if new.TerraformVersion == "" { - // Older formats considered this to be optional, but now it's required - // and so we'll stub it out with something that's definitely older - // than the version that really created this state. - new.TerraformVersion = "0.0.0" - } - - for _, msOld := range old.Modules { - if len(msOld.Path) < 1 || msOld.Path[0] != "root" { - return nil, fmt.Errorf("state contains invalid module path %#v", msOld.Path) - } - - // Convert legacy-style module address into our newer address type. - // Since these old formats are only generated by versions of Terraform - // that don't support count and for_each on modules, we can just assume - // all of the modules are unkeyed. - moduleAddr := make(addrs.ModuleInstance, len(msOld.Path)-1) - for i, name := range msOld.Path[1:] { - moduleAddr[i] = addrs.ModuleInstanceStep{ - Name: name, - InstanceKey: addrs.NoKey, - } - } - - // In a v3 state file, a "resource state" is actually an instance - // state, so we need to fill in a missing level of heirarchy here - // by lazily creating resource states as we encounter them. - // We'll track them in here, keyed on the string representation of - // the resource address. - resourceStates := map[string]*resourceStateV4{} - - for legacyAddr, rsOld := range msOld.Resources { - instAddr, err := parseLegacyResourceAddress(legacyAddr) - if err != nil { - return nil, err - } - - resAddr := instAddr.Resource - rs, exists := resourceStates[resAddr.String()] - if !exists { - var modeStr string - switch resAddr.Mode { - case addrs.ManagedResourceMode: - modeStr = "managed" - case addrs.DataResourceMode: - modeStr = "data" - default: - return nil, fmt.Errorf("state contains resource %s with an unsupported resource mode %#v", resAddr, resAddr.Mode) - } - - // In state versions prior to 4 we allowed each instance of a - // resource to have its own provider configuration address, - // which makes no real sense in practice because providers - // are associated with resources in the configuration. We - // elevate that to the resource level during this upgrade, - // implicitly taking the provider address of the first instance - // we encounter for each resource. While this is lossy in - // theory, in practice there is no reason for these values to - // differ between instances. - var providerAddr addrs.AbsProviderConfig - oldProviderAddr := rsOld.Provider - if strings.Contains(oldProviderAddr, "provider.") { - // Smells like a new-style provider address, but we'll test it. - var diags tfdiags.Diagnostics - providerAddr, diags = addrs.ParseAbsProviderConfigStr(oldProviderAddr) - if diags.HasErrors() { - return nil, fmt.Errorf("invalid provider config reference %q for %s: %s", oldProviderAddr, instAddr, diags.Err()) - } - } else { - // Smells like an old-style module-local provider address, - // which we'll need to migrate. We'll assume it's referring - // to the same module the resource is in, which might be - // incorrect but it'll get fixed up next time any updates - // are made to an instance. - if oldProviderAddr != "" { - localAddr, diags := addrs.ParseProviderConfigCompactStr(oldProviderAddr) - if diags.HasErrors() { - return nil, fmt.Errorf("invalid legacy provider config reference %q for %s: %s", oldProviderAddr, instAddr, diags.Err()) - } - providerAddr = localAddr.Absolute(moduleAddr) - } else { - providerAddr = resAddr.DefaultProviderConfig().Absolute(moduleAddr) - } - } - - rs = &resourceStateV4{ - Module: moduleAddr.String(), - Mode: modeStr, - Type: resAddr.Type, - Name: resAddr.Name, - Instances: []instanceObjectStateV4{}, - ProviderConfig: providerAddr.String(), - } - resourceStates[resAddr.String()] = rs - } - - // Now we'll deal with the instance itself, which may either be - // the first instance in a resource we just created or an additional - // instance for a resource added on a prior loop. - instKey := instAddr.Key - if isOld := rsOld.Primary; isOld != nil { - isNew, err := upgradeInstanceObjectV3ToV4(rsOld, isOld, instKey, states.NotDeposed) - if err != nil { - return nil, fmt.Errorf("failed to migrate primary generation of %s: %s", instAddr, err) - } - rs.Instances = append(rs.Instances, *isNew) - } - for i, isOld := range rsOld.Deposed { - // When we migrate old instances we'll use sequential deposed - // keys just so that the upgrade result is deterministic. New - // deposed keys allocated moving forward will be pseudorandomly - // selected, but we check for collisions and so these - // non-random ones won't hurt. - deposedKey := states.DeposedKey(fmt.Sprintf("%08x", i+1)) - isNew, err := upgradeInstanceObjectV3ToV4(rsOld, isOld, instKey, deposedKey) - if err != nil { - return nil, fmt.Errorf("failed to migrate deposed generation index %d of %s: %s", i, instAddr, err) - } - rs.Instances = append(rs.Instances, *isNew) - } - - if instKey != addrs.NoKey && rs.EachMode == "" { - rs.EachMode = "list" - } - } - - for _, rs := range resourceStates { - new.Resources = append(new.Resources, *rs) - } - - if len(msOld.Path) == 1 && msOld.Path[0] == "root" { - // We'll migrate the outputs for this module too, then. - for name, oldOS := range msOld.Outputs { - newOS := outputStateV4{ - Sensitive: oldOS.Sensitive, - } - - valRaw := oldOS.Value - valSrc, err := json.Marshal(valRaw) - if err != nil { - // Should never happen, because this value came from JSON - // in the first place and so we're just round-tripping here. - return nil, fmt.Errorf("failed to serialize output %q value as JSON: %s", name, err) - } - - // The "type" field in state V2 wasn't really that useful - // since it was only able to capture string vs. list vs. map. - // For this reason, during upgrade we'll just discard it - // altogether and use cty's idea of the implied type of - // turning our old value into JSON. - ty, err := ctyjson.ImpliedType(valSrc) - if err != nil { - // REALLY should never happen, because we literally just - // encoded this as JSON above! - return nil, fmt.Errorf("failed to parse output %q value from JSON: %s", name, err) - } - - // ImpliedType tends to produce structural types, but since older - // version of Terraform didn't support those a collection type - // is probably what was intended, so we'll see if we can - // interpret our value as one. - ty = simplifyImpliedValueType(ty) - - tySrc, err := ctyjson.MarshalType(ty) - if err != nil { - return nil, fmt.Errorf("failed to serialize output %q type as JSON: %s", name, err) - } - - newOS.ValueRaw = json.RawMessage(valSrc) - newOS.ValueTypeRaw = json.RawMessage(tySrc) - - new.RootOutputs[name] = newOS - } - } - } - - new.normalize() - - return new, nil -} - -func upgradeInstanceObjectV3ToV4(rsOld *resourceStateV2, isOld *instanceStateV2, instKey addrs.InstanceKey, deposedKey states.DeposedKey) (*instanceObjectStateV4, error) { - - // Schema versions were, in prior formats, a private concern of the provider - // SDK, and not a first-class concept in the state format. Here we're - // sniffing for the pre-0.12 SDK's way of representing schema versions - // and promoting it to our first-class field if we find it. We'll ignore - // it if it doesn't look like what the SDK would've written. If this - // sniffing fails then we'll assume schema version 0. - var schemaVersion uint64 - migratedSchemaVersion := false - if raw, exists := isOld.Meta["schema_version"]; exists { - switch tv := raw.(type) { - case string: - v, err := strconv.ParseUint(tv, 10, 64) - if err == nil { - schemaVersion = v - migratedSchemaVersion = true - } - case int: - schemaVersion = uint64(tv) - migratedSchemaVersion = true - case float64: - schemaVersion = uint64(tv) - migratedSchemaVersion = true - } - } - - private := map[string]interface{}{} - for k, v := range isOld.Meta { - if k == "schema_version" && migratedSchemaVersion { - // We're gonna promote this into our first-class schema version field - continue - } - private[k] = v - } - var privateJSON []byte - if len(private) != 0 { - var err error - privateJSON, err = json.Marshal(private) - if err != nil { - // This shouldn't happen, because the Meta values all came from JSON - // originally anyway. - return nil, fmt.Errorf("cannot serialize private instance object data: %s", err) - } - } - - var status string - if isOld.Tainted { - status = "tainted" - } - - var instKeyRaw interface{} - switch tk := instKey.(type) { - case addrs.IntKey: - instKeyRaw = int(tk) - case addrs.StringKey: - instKeyRaw = string(tk) - default: - if instKeyRaw != nil { - return nil, fmt.Errorf("unsupported instance key: %#v", instKey) - } - } - - var attributes map[string]string - if isOld.Attributes != nil { - attributes = make(map[string]string, len(isOld.Attributes)) - for k, v := range isOld.Attributes { - attributes[k] = v - } - } - if isOld.ID != "" { - // As a special case, if we don't already have an "id" attribute and - // yet there's a non-empty first-class ID on the old object then we'll - // create a synthetic id attribute to avoid losing that first-class id. - // In practice this generally arises only in tests where state literals - // are hand-written in a non-standard way; real code prior to 0.12 - // would always force the first-class ID to be copied into the - // id attribute before storing. - if attributes == nil { - attributes = make(map[string]string, len(isOld.Attributes)) - } - if idVal := attributes["id"]; idVal == "" { - attributes["id"] = isOld.ID - } - } - - dependencies := make([]string, len(rsOld.Dependencies)) - for i, v := range rsOld.Dependencies { - depStr, err := parseLegacyDependency(v) - if err != nil { - return nil, fmt.Errorf("invalid dependency reference %q: %s", v, err) - } - dependencies[i] = depStr - } - - return &instanceObjectStateV4{ - IndexKey: instKeyRaw, - Status: status, - Deposed: string(deposedKey), - AttributesFlat: attributes, - Dependencies: dependencies, - SchemaVersion: schemaVersion, - PrivateRaw: privateJSON, - }, nil -} - -// parseLegacyResourceAddress parses the different identifier format used -// state formats before version 4, like "instance.name.0". -func parseLegacyResourceAddress(s string) (addrs.ResourceInstance, error) { - var ret addrs.ResourceInstance - - // Split based on ".". Every resource address should have at least two - // elements (type and name). - parts := strings.Split(s, ".") - if len(parts) < 2 || len(parts) > 4 { - return ret, fmt.Errorf("invalid internal resource address format: %s", s) - } - - // Data resource if we have at least 3 parts and the first one is data - ret.Resource.Mode = addrs.ManagedResourceMode - if len(parts) > 2 && parts[0] == "data" { - ret.Resource.Mode = addrs.DataResourceMode - parts = parts[1:] - } - - // If we're not a data resource and we have more than 3, then it is an error - if len(parts) > 3 && ret.Resource.Mode != addrs.DataResourceMode { - return ret, fmt.Errorf("invalid internal resource address format: %s", s) - } - - // Build the parts of the resource address that are guaranteed to exist - ret.Resource.Type = parts[0] - ret.Resource.Name = parts[1] - ret.Key = addrs.NoKey - - // If we have more parts, then we have an index. Parse that. - if len(parts) > 2 { - idx, err := strconv.ParseInt(parts[2], 0, 0) - if err != nil { - return ret, fmt.Errorf("error parsing resource address %q: %s", s, err) - } - - ret.Key = addrs.IntKey(idx) - } - - return ret, nil -} - -// simplifyImpliedValueType attempts to heuristically simplify a value type -// derived from a legacy stored output value into something simpler that -// is closer to what would've fitted into the pre-v0.12 value type system. -func simplifyImpliedValueType(ty cty.Type) cty.Type { - switch { - case ty.IsTupleType(): - // If all of the element types are the same then we'll make this - // a list instead. This is very likely to be true, since prior versions - // of Terraform did not officially support mixed-type collections. - - if ty.Equals(cty.EmptyTuple) { - // Don't know what the element type would be, then. - return ty - } - - etys := ty.TupleElementTypes() - ety := etys[0] - for _, other := range etys[1:] { - if !other.Equals(ety) { - // inconsistent types - return ty - } - } - ety = simplifyImpliedValueType(ety) - return cty.List(ety) - - case ty.IsObjectType(): - // If all of the attribute types are the same then we'll make this - // a map instead. This is very likely to be true, since prior versions - // of Terraform did not officially support mixed-type collections. - - if ty.Equals(cty.EmptyObject) { - // Don't know what the element type would be, then. - return ty - } - - atys := ty.AttributeTypes() - var ety cty.Type - for _, other := range atys { - if ety == cty.NilType { - ety = other - continue - } - if !other.Equals(ety) { - // inconsistent types - return ty - } - } - ety = simplifyImpliedValueType(ety) - return cty.Map(ety) - - default: - // No other normalizations are possible - return ty - } -} - -func parseLegacyDependency(s string) (string, error) { - parts := strings.Split(s, ".") - ret := parts[0] - for _, part := range parts[1:] { - if part == "*" { - break - } - if i, err := strconv.Atoi(part); err == nil { - ret = ret + fmt.Sprintf("[%d]", i) - break - } - ret = ret + "." + part - } - - // The result must parse as a reference, or else we'll create an invalid - // state file. - var diags tfdiags.Diagnostics - _, diags = addrs.ParseRefStr(ret) - if diags.HasErrors() { - return "", diags.Err() - } - - return ret, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version4.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version4.go deleted file mode 100644 index 164b57f827f..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version4.go +++ /dev/null @@ -1,604 +0,0 @@ -package statefile - -import ( - "encoding/json" - "fmt" - "io" - "sort" - - version "github.com/hashicorp/go-version" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -func readStateV4(src []byte) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - sV4 := &stateV4{} - err := json.Unmarshal(src, sV4) - if err != nil { - diags = diags.Append(jsonUnmarshalDiags(err)) - return nil, diags - } - - file, prepDiags := prepareStateV4(sV4) - diags = diags.Append(prepDiags) - return file, diags -} - -func prepareStateV4(sV4 *stateV4) (*File, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - var tfVersion *version.Version - if sV4.TerraformVersion != "" { - var err error - tfVersion, err = version.NewVersion(sV4.TerraformVersion) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid Terraform version string", - fmt.Sprintf("State file claims to have been written by Terraform version %q, which is not a valid version string.", sV4.TerraformVersion), - )) - } - } - - file := &File{ - TerraformVersion: tfVersion, - Serial: sV4.Serial, - Lineage: sV4.Lineage, - } - - state := states.NewState() - - for _, rsV4 := range sV4.Resources { - rAddr := addrs.Resource{ - Type: rsV4.Type, - Name: rsV4.Name, - } - switch rsV4.Mode { - case "managed": - rAddr.Mode = addrs.ManagedResourceMode - case "data": - rAddr.Mode = addrs.DataResourceMode - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource mode in state", - fmt.Sprintf("State contains a resource with mode %q (%q %q) which is not supported.", rsV4.Mode, rAddr.Type, rAddr.Name), - )) - continue - } - - moduleAddr := addrs.RootModuleInstance - if rsV4.Module != "" { - var addrDiags tfdiags.Diagnostics - moduleAddr, addrDiags = addrs.ParseModuleInstanceStr(rsV4.Module) - diags = diags.Append(addrDiags) - if addrDiags.HasErrors() { - continue - } - } - - providerAddr, addrDiags := addrs.ParseAbsProviderConfigStr(rsV4.ProviderConfig) - diags.Append(addrDiags) - if addrDiags.HasErrors() { - continue - } - - var eachMode states.EachMode - switch rsV4.EachMode { - case "": - eachMode = states.NoEach - case "list": - eachMode = states.EachList - case "map": - eachMode = states.EachMap - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource metadata in state", - fmt.Sprintf("Resource %s has invalid \"each\" value %q in state.", rAddr.Absolute(moduleAddr), eachMode), - )) - continue - } - - ms := state.EnsureModule(moduleAddr) - - // Ensure the resource container object is present in the state. - ms.SetResourceMeta(rAddr, eachMode, providerAddr) - - for _, isV4 := range rsV4.Instances { - keyRaw := isV4.IndexKey - var key addrs.InstanceKey - switch tk := keyRaw.(type) { - case int: - key = addrs.IntKey(tk) - case float64: - // Since JSON only has one number type, reading from encoding/json - // gives us a float64 here even if the number is whole. - // float64 has a smaller integer range than int, but in practice - // we rarely have more than a few tens of instances and so - // it's unlikely that we'll exhaust the 52 bits in a float64. - key = addrs.IntKey(int(tk)) - case string: - key = addrs.StringKey(tk) - default: - if keyRaw != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource instance metadata in state", - fmt.Sprintf("Resource %s has an instance with the invalid instance key %#v.", rAddr.Absolute(moduleAddr), keyRaw), - )) - continue - } - key = addrs.NoKey - } - - instAddr := rAddr.Instance(key) - - obj := &states.ResourceInstanceObjectSrc{ - SchemaVersion: isV4.SchemaVersion, - } - - { - // Instance attributes - switch { - case isV4.AttributesRaw != nil: - obj.AttrsJSON = isV4.AttributesRaw - case isV4.AttributesFlat != nil: - obj.AttrsFlat = isV4.AttributesFlat - default: - // This is odd, but we'll accept it and just treat the - // object has being empty. In practice this should arise - // only from the contrived sort of state objects we tend - // to hand-write inline in tests. - obj.AttrsJSON = []byte{'{', '}'} - } - } - - { - // Status - raw := isV4.Status - switch raw { - case "": - obj.Status = states.ObjectReady - case "tainted": - obj.Status = states.ObjectTainted - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource instance metadata in state", - fmt.Sprintf("Instance %s has invalid status %q.", instAddr.Absolute(moduleAddr), raw), - )) - continue - } - } - - if raw := isV4.PrivateRaw; len(raw) > 0 { - obj.Private = raw - } - - { - depsRaw := isV4.Dependencies - deps := make([]addrs.Referenceable, 0, len(depsRaw)) - for _, depRaw := range depsRaw { - ref, refDiags := addrs.ParseRefStr(depRaw) - diags = diags.Append(refDiags) - if refDiags.HasErrors() { - continue - } - if len(ref.Remaining) != 0 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource instance metadata in state", - fmt.Sprintf("Instance %s declares dependency on %q, which is not a reference to a dependable object.", instAddr.Absolute(moduleAddr), depRaw), - )) - } - if ref.Subject == nil { - // Should never happen - panic(fmt.Sprintf("parsing dependency %q for instance %s returned a nil address", depRaw, instAddr.Absolute(moduleAddr))) - } - deps = append(deps, ref.Subject) - } - obj.Dependencies = deps - } - - switch { - case isV4.Deposed != "": - dk := states.DeposedKey(isV4.Deposed) - if len(dk) != 8 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource instance metadata in state", - fmt.Sprintf("Instance %s has an object with deposed key %q, which is not correctly formatted.", instAddr.Absolute(moduleAddr), isV4.Deposed), - )) - continue - } - is := ms.ResourceInstance(instAddr) - if is.HasDeposed(dk) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Duplicate resource instance in state", - fmt.Sprintf("Instance %s deposed object %q appears multiple times in the state file.", instAddr.Absolute(moduleAddr), dk), - )) - continue - } - - ms.SetResourceInstanceDeposed(instAddr, dk, obj, providerAddr) - default: - is := ms.ResourceInstance(instAddr) - if is.HasCurrent() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Duplicate resource instance in state", - fmt.Sprintf("Instance %s appears multiple times in the state file.", instAddr.Absolute(moduleAddr)), - )) - continue - } - - ms.SetResourceInstanceCurrent(instAddr, obj, providerAddr) - } - } - - // We repeat this after creating the instances because - // SetResourceInstanceCurrent automatically resets this metadata based - // on the incoming objects. That behavior is useful when we're making - // piecemeal updates to the state during an apply, but when we're - // reading the state file we want to reflect its contents exactly. - ms.SetResourceMeta(rAddr, eachMode, providerAddr) - } - - // The root module is special in that we persist its attributes and thus - // need to reload them now. (For descendent modules we just re-calculate - // them based on the latest configuration on each run.) - { - rootModule := state.RootModule() - for name, fos := range sV4.RootOutputs { - os := &states.OutputValue{} - os.Sensitive = fos.Sensitive - - ty, err := ctyjson.UnmarshalType([]byte(fos.ValueTypeRaw)) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid output value type in state", - fmt.Sprintf("The state file has an invalid type specification for output %q: %s.", name, err), - )) - continue - } - - val, err := ctyjson.Unmarshal([]byte(fos.ValueRaw), ty) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid output value saved in state", - fmt.Sprintf("The state file has an invalid value for output %q: %s.", name, err), - )) - continue - } - - os.Value = val - rootModule.OutputValues[name] = os - } - } - - file.State = state - return file, diags -} - -func writeStateV4(file *File, w io.Writer) tfdiags.Diagnostics { - // Here we'll convert back from the "File" representation to our - // stateV4 struct representation and write that. - // - // While we support legacy state formats for reading, we only support the - // latest for writing and so if a V5 is added in future then this function - // should be deleted and replaced with a writeStateV5, even though the - // read/prepare V4 functions above would stick around. - - var diags tfdiags.Diagnostics - if file == nil || file.State == nil { - panic("attempt to write nil state to file") - } - - var terraformVersion string - if file.TerraformVersion != nil { - terraformVersion = file.TerraformVersion.String() - } - - sV4 := &stateV4{ - TerraformVersion: terraformVersion, - Serial: file.Serial, - Lineage: file.Lineage, - RootOutputs: map[string]outputStateV4{}, - Resources: []resourceStateV4{}, - } - - for name, os := range file.State.RootModule().OutputValues { - src, err := ctyjson.Marshal(os.Value, os.Value.Type()) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize output value in state", - fmt.Sprintf("An error occured while serializing output value %q: %s.", name, err), - )) - continue - } - - typeSrc, err := ctyjson.MarshalType(os.Value.Type()) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize output value in state", - fmt.Sprintf("An error occured while serializing the type of output value %q: %s.", name, err), - )) - continue - } - - sV4.RootOutputs[name] = outputStateV4{ - Sensitive: os.Sensitive, - ValueRaw: json.RawMessage(src), - ValueTypeRaw: json.RawMessage(typeSrc), - } - } - - for _, ms := range file.State.Modules { - moduleAddr := ms.Addr - for _, rs := range ms.Resources { - resourceAddr := rs.Addr - - var mode string - switch resourceAddr.Mode { - case addrs.ManagedResourceMode: - mode = "managed" - case addrs.DataResourceMode: - mode = "data" - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize resource in state", - fmt.Sprintf("Resource %s has mode %s, which cannot be serialized in state", resourceAddr.Absolute(moduleAddr), resourceAddr.Mode), - )) - continue - } - - var eachMode string - switch rs.EachMode { - case states.NoEach: - eachMode = "" - case states.EachList: - eachMode = "list" - case states.EachMap: - eachMode = "map" - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize resource in state", - fmt.Sprintf("Resource %s has \"each\" mode %s, which cannot be serialized in state", resourceAddr.Absolute(moduleAddr), rs.EachMode), - )) - continue - } - - sV4.Resources = append(sV4.Resources, resourceStateV4{ - Module: moduleAddr.String(), - Mode: mode, - Type: resourceAddr.Type, - Name: resourceAddr.Name, - EachMode: eachMode, - ProviderConfig: rs.ProviderConfig.String(), - Instances: []instanceObjectStateV4{}, - }) - rsV4 := &(sV4.Resources[len(sV4.Resources)-1]) - - for key, is := range rs.Instances { - if is.HasCurrent() { - var objDiags tfdiags.Diagnostics - rsV4.Instances, objDiags = appendInstanceObjectStateV4( - rs, is, key, is.Current, states.NotDeposed, - rsV4.Instances, - ) - diags = diags.Append(objDiags) - } - for dk, obj := range is.Deposed { - var objDiags tfdiags.Diagnostics - rsV4.Instances, objDiags = appendInstanceObjectStateV4( - rs, is, key, obj, dk, - rsV4.Instances, - ) - diags = diags.Append(objDiags) - } - } - } - } - - sV4.normalize() - - src, err := json.MarshalIndent(sV4, "", " ") - if err != nil { - // Shouldn't happen if we do our conversion to *stateV4 correctly above. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize state", - fmt.Sprintf("An error occured while serializing the state to save it. This is a bug in Terraform and should be reported: %s.", err), - )) - return diags - } - src = append(src, '\n') - - _, err = w.Write(src) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to write state", - fmt.Sprintf("An error occured while writing the serialized state: %s.", err), - )) - return diags - } - - return diags -} - -func appendInstanceObjectStateV4(rs *states.Resource, is *states.ResourceInstance, key addrs.InstanceKey, obj *states.ResourceInstanceObjectSrc, deposed states.DeposedKey, isV4s []instanceObjectStateV4) ([]instanceObjectStateV4, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - var status string - switch obj.Status { - case states.ObjectReady: - status = "" - case states.ObjectTainted: - status = "tainted" - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize resource instance in state", - fmt.Sprintf("Instance %s has status %s, which cannot be saved in state.", rs.Addr.Instance(key), obj.Status), - )) - } - - var privateRaw []byte - if len(obj.Private) > 0 { - privateRaw = obj.Private - } - - deps := make([]string, len(obj.Dependencies)) - for i, depAddr := range obj.Dependencies { - deps[i] = depAddr.String() - } - - var rawKey interface{} - switch tk := key.(type) { - case addrs.IntKey: - rawKey = int(tk) - case addrs.StringKey: - rawKey = string(tk) - default: - if key != addrs.NoKey { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to serialize resource instance in state", - fmt.Sprintf("Instance %s has an unsupported instance key: %#v.", rs.Addr.Instance(key), key), - )) - } - } - - return append(isV4s, instanceObjectStateV4{ - IndexKey: rawKey, - Deposed: string(deposed), - Status: status, - SchemaVersion: obj.SchemaVersion, - AttributesFlat: obj.AttrsFlat, - AttributesRaw: obj.AttrsJSON, - PrivateRaw: privateRaw, - Dependencies: deps, - }), diags -} - -type stateV4 struct { - Version stateVersionV4 `json:"version"` - TerraformVersion string `json:"terraform_version"` - Serial uint64 `json:"serial"` - Lineage string `json:"lineage"` - RootOutputs map[string]outputStateV4 `json:"outputs"` - Resources []resourceStateV4 `json:"resources"` -} - -// normalize makes some in-place changes to normalize the way items are -// stored to ensure that two functionally-equivalent states will be stored -// identically. -func (s *stateV4) normalize() { - sort.Stable(sortResourcesV4(s.Resources)) - for _, rs := range s.Resources { - sort.Stable(sortInstancesV4(rs.Instances)) - } -} - -type outputStateV4 struct { - ValueRaw json.RawMessage `json:"value"` - ValueTypeRaw json.RawMessage `json:"type"` - Sensitive bool `json:"sensitive,omitempty"` -} - -type resourceStateV4 struct { - Module string `json:"module,omitempty"` - Mode string `json:"mode"` - Type string `json:"type"` - Name string `json:"name"` - EachMode string `json:"each,omitempty"` - ProviderConfig string `json:"provider"` - Instances []instanceObjectStateV4 `json:"instances"` -} - -type instanceObjectStateV4 struct { - IndexKey interface{} `json:"index_key,omitempty"` - Status string `json:"status,omitempty"` - Deposed string `json:"deposed,omitempty"` - - SchemaVersion uint64 `json:"schema_version"` - AttributesRaw json.RawMessage `json:"attributes,omitempty"` - AttributesFlat map[string]string `json:"attributes_flat,omitempty"` - - PrivateRaw []byte `json:"private,omitempty"` - - Dependencies []string `json:"depends_on,omitempty"` -} - -// stateVersionV4 is a weird special type we use to produce our hard-coded -// "version": 4 in the JSON serialization. -type stateVersionV4 struct{} - -func (sv stateVersionV4) MarshalJSON() ([]byte, error) { - return []byte{'4'}, nil -} - -func (sv stateVersionV4) UnmarshalJSON([]byte) error { - // Nothing to do: we already know we're version 4 - return nil -} - -type sortResourcesV4 []resourceStateV4 - -func (sr sortResourcesV4) Len() int { return len(sr) } -func (sr sortResourcesV4) Swap(i, j int) { sr[i], sr[j] = sr[j], sr[i] } -func (sr sortResourcesV4) Less(i, j int) bool { - switch { - case sr[i].Mode != sr[j].Mode: - return sr[i].Mode < sr[j].Mode - case sr[i].Type != sr[j].Type: - return sr[i].Type < sr[j].Type - case sr[i].Name != sr[j].Name: - return sr[i].Name < sr[j].Name - default: - return false - } -} - -type sortInstancesV4 []instanceObjectStateV4 - -func (si sortInstancesV4) Len() int { return len(si) } -func (si sortInstancesV4) Swap(i, j int) { si[i], si[j] = si[j], si[i] } -func (si sortInstancesV4) Less(i, j int) bool { - ki := si[i].IndexKey - kj := si[j].IndexKey - if ki != kj { - if (ki == nil) != (kj == nil) { - return ki == nil - } - if kii, isInt := ki.(int); isInt { - if kji, isInt := kj.(int); isInt { - return kii < kji - } - return true - } - if kis, isStr := ki.(string); isStr { - if kjs, isStr := kj.(string); isStr { - return kis < kjs - } - return true - } - } - if si[i].Deposed != si[j].Deposed { - return si[i].Deposed < si[j].Deposed - } - return false -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/write.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/write.go deleted file mode 100644 index 8fdca45803a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/write.go +++ /dev/null @@ -1,17 +0,0 @@ -package statefile - -import ( - "io" - - tfversion "github.com/hashicorp/terraform-plugin-sdk/internal/version" -) - -// Write writes the given state to the given writer in the current state -// serialization format. -func Write(s *File, w io.Writer) error { - // Always record the current terraform version in the state. - s.TerraformVersion = tfversion.SemVer - - diags := writeStateV4(s, w) - return diags.Err() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/sync.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/sync.go deleted file mode 100644 index 6d236125407..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/sync.go +++ /dev/null @@ -1,484 +0,0 @@ -package states - -import ( - "log" - "sync" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/zclconf/go-cty/cty" -) - -// SyncState is a wrapper around State that provides concurrency-safe access to -// various common operations that occur during a Terraform graph walk, or other -// similar concurrent contexts. -// -// When a SyncState wrapper is in use, no concurrent direct access to the -// underlying objects is permitted unless the caller first acquires an explicit -// lock, using the Lock and Unlock methods. Most callers should _not_ -// explicitly lock, and should instead use the other methods of this type that -// handle locking automatically. -// -// Since SyncState is able to safely consolidate multiple updates into a single -// atomic operation, many of its methods are at a higher level than those -// of the underlying types, and operate on the state as a whole rather than -// on individual sub-structures of the state. -// -// SyncState can only protect against races within its own methods. It cannot -// provide any guarantees about the order in which concurrent operations will -// be processed, so callers may still need to employ higher-level techniques -// for ensuring correct operation sequencing, such as building and walking -// a dependency graph. -type SyncState struct { - state *State - lock sync.RWMutex -} - -// Module returns a snapshot of the state of the module instance with the given -// address, or nil if no such module is tracked. -// -// The return value is a pointer to a copy of the module state, which the -// caller may then freely access and mutate. However, since the module state -// tends to be a large data structure with many child objects, where possible -// callers should prefer to use a more granular accessor to access a child -// module directly, and thus reduce the amount of copying required. -func (s *SyncState) Module(addr addrs.ModuleInstance) *Module { - s.lock.RLock() - ret := s.state.Module(addr).DeepCopy() - s.lock.RUnlock() - return ret -} - -// OutputValue returns a snapshot of the state of the output value with the -// given address, or nil if no such output value is tracked. -// -// The return value is a pointer to a copy of the output value state, which the -// caller may then freely access and mutate. -func (s *SyncState) OutputValue(addr addrs.AbsOutputValue) *OutputValue { - s.lock.RLock() - ret := s.state.OutputValue(addr).DeepCopy() - s.lock.RUnlock() - return ret -} - -// SetOutputValue writes a given output value into the state, overwriting -// any existing value of the same name. -// -// If the module containing the output is not yet tracked in state then it -// be added as a side-effect. -func (s *SyncState) SetOutputValue(addr addrs.AbsOutputValue, value cty.Value, sensitive bool) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.EnsureModule(addr.Module) - ms.SetOutputValue(addr.OutputValue.Name, value, sensitive) -} - -// RemoveOutputValue removes the stored value for the output value with the -// given address. -// -// If this results in its containing module being empty, the module will be -// pruned from the state as a side-effect. -func (s *SyncState) RemoveOutputValue(addr addrs.AbsOutputValue) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return - } - ms.RemoveOutputValue(addr.OutputValue.Name) - s.maybePruneModule(addr.Module) -} - -// LocalValue returns the current value associated with the given local value -// address. -func (s *SyncState) LocalValue(addr addrs.AbsLocalValue) cty.Value { - s.lock.RLock() - // cty.Value is immutable, so we don't need any extra copying here. - ret := s.state.LocalValue(addr) - s.lock.RUnlock() - return ret -} - -// SetLocalValue writes a given output value into the state, overwriting -// any existing value of the same name. -// -// If the module containing the local value is not yet tracked in state then it -// will be added as a side-effect. -func (s *SyncState) SetLocalValue(addr addrs.AbsLocalValue, value cty.Value) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.EnsureModule(addr.Module) - ms.SetLocalValue(addr.LocalValue.Name, value) -} - -// RemoveLocalValue removes the stored value for the local value with the -// given address. -// -// If this results in its containing module being empty, the module will be -// pruned from the state as a side-effect. -func (s *SyncState) RemoveLocalValue(addr addrs.AbsLocalValue) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return - } - ms.RemoveLocalValue(addr.LocalValue.Name) - s.maybePruneModule(addr.Module) -} - -// Resource returns a snapshot of the state of the resource with the given -// address, or nil if no such resource is tracked. -// -// The return value is a pointer to a copy of the resource state, which the -// caller may then freely access and mutate. -func (s *SyncState) Resource(addr addrs.AbsResource) *Resource { - s.lock.RLock() - ret := s.state.Resource(addr).DeepCopy() - s.lock.RUnlock() - return ret -} - -// ResourceInstance returns a snapshot of the state the resource instance with -// the given address, or nil if no such instance is tracked. -// -// The return value is a pointer to a copy of the instance state, which the -// caller may then freely access and mutate. -func (s *SyncState) ResourceInstance(addr addrs.AbsResourceInstance) *ResourceInstance { - s.lock.RLock() - ret := s.state.ResourceInstance(addr).DeepCopy() - s.lock.RUnlock() - return ret -} - -// ResourceInstanceObject returns a snapshot of the current instance object -// of the given generation belonging to the instance with the given address, -// or nil if no such object is tracked.. -// -// The return value is a pointer to a copy of the object, which the caller may -// then freely access and mutate. -func (s *SyncState) ResourceInstanceObject(addr addrs.AbsResourceInstance, gen Generation) *ResourceInstanceObjectSrc { - s.lock.RLock() - defer s.lock.RUnlock() - - inst := s.state.ResourceInstance(addr) - if inst == nil { - return nil - } - return inst.GetGeneration(gen).DeepCopy() -} - -// SetResourceMeta updates the resource-level metadata for the resource at -// the given address, creating the containing module state and resource state -// as a side-effect if not already present. -func (s *SyncState) SetResourceMeta(addr addrs.AbsResource, eachMode EachMode, provider addrs.AbsProviderConfig) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.EnsureModule(addr.Module) - ms.SetResourceMeta(addr.Resource, eachMode, provider) -} - -// RemoveResourceIfEmpty is similar to RemoveResource but first checks to -// make sure there are no instances or objects left in the resource. -// -// Returns true if the resource was removed, or false if remaining child -// objects prevented its removal. Returns true also if the resource was -// already absent, and thus no action needed to be taken. -func (s *SyncState) RemoveResourceIfEmpty(addr addrs.AbsResource) bool { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return true // nothing to do - } - rs := ms.Resource(addr.Resource) - if rs == nil { - return true // nothing to do - } - if len(rs.Instances) != 0 { - // We don't check here for the possibility of instances that exist - // but don't have any objects because it's the responsibility of the - // instance-mutation methods to prune those away automatically. - return false - } - ms.RemoveResource(addr.Resource) - s.maybePruneModule(addr.Module) - return true -} - -// MaybeFixUpResourceInstanceAddressForCount deals with the situation where a -// resource has changed from having "count" set to not set, or vice-versa, and -// so we need to rename the zeroth instance key to no key at all, or vice-versa. -// -// Set countEnabled to true if the resource has count set in its new -// configuration, or false if it does not. -// -// The state is modified in-place if necessary, moving a resource instance -// between the two addresses. The return value is true if a change was made, -// and false otherwise. -func (s *SyncState) MaybeFixUpResourceInstanceAddressForCount(addr addrs.AbsResource, countEnabled bool) bool { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return false - } - - relAddr := addr.Resource - rs := ms.Resource(relAddr) - if rs == nil { - return false - } - huntKey := addrs.NoKey - replaceKey := addrs.InstanceKey(addrs.IntKey(0)) - if !countEnabled { - huntKey, replaceKey = replaceKey, huntKey - } - - is, exists := rs.Instances[huntKey] - if !exists { - return false - } - - if _, exists := rs.Instances[replaceKey]; exists { - // If the replacement key also exists then we'll do nothing and keep both. - return false - } - - // If we get here then we need to "rename" from hunt to replace - rs.Instances[replaceKey] = is - delete(rs.Instances, huntKey) - return true -} - -// SetResourceInstanceCurrent saves the given instance object as the current -// generation of the resource instance with the given address, simultaneously -// updating the recorded provider configuration address, dependencies, and -// resource EachMode. -// -// Any existing current instance object for the given resource is overwritten. -// Set obj to nil to remove the primary generation object altogether. If there -// are no deposed objects then the instance as a whole will be removed, which -// may in turn also remove the containing module if it becomes empty. -// -// The caller must ensure that the given ResourceInstanceObject is not -// concurrently mutated during this call, but may be freely used again once -// this function returns. -// -// The provider address and "each mode" are resource-wide settings and so they -// are updated for all other instances of the same resource as a side-effect of -// this call. -// -// If the containing module for this resource or the resource itself are not -// already tracked in state then they will be added as a side-effect. -func (s *SyncState) SetResourceInstanceCurrent(addr addrs.AbsResourceInstance, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.EnsureModule(addr.Module) - ms.SetResourceInstanceCurrent(addr.Resource, obj.DeepCopy(), provider) - s.maybePruneModule(addr.Module) -} - -// SetResourceInstanceDeposed saves the given instance object as a deposed -// generation of the resource instance with the given address and deposed key. -// -// Call this method only for pre-existing deposed objects that already have -// a known DeposedKey. For example, this method is useful if reloading objects -// that were persisted to a state file. To mark the current object as deposed, -// use DeposeResourceInstanceObject instead. -// -// The caller must ensure that the given ResourceInstanceObject is not -// concurrently mutated during this call, but may be freely used again once -// this function returns. -// -// The resource that contains the given instance must already exist in the -// state, or this method will panic. Use Resource to check first if its -// presence is not already guaranteed. -// -// Any existing current instance object for the given resource and deposed key -// is overwritten. Set obj to nil to remove the deposed object altogether. If -// the instance is left with no objects after this operation then it will -// be removed from its containing resource altogether. -// -// If the containing module for this resource or the resource itself are not -// already tracked in state then they will be added as a side-effect. -func (s *SyncState) SetResourceInstanceDeposed(addr addrs.AbsResourceInstance, key DeposedKey, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig) { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.EnsureModule(addr.Module) - ms.SetResourceInstanceDeposed(addr.Resource, key, obj.DeepCopy(), provider) - s.maybePruneModule(addr.Module) -} - -// DeposeResourceInstanceObject moves the current instance object for the -// given resource instance address into the deposed set, leaving the instance -// without a current object. -// -// The return value is the newly-allocated deposed key, or NotDeposed if the -// given instance is already lacking a current object. -// -// If the containing module for this resource or the resource itself are not -// already tracked in state then there cannot be a current object for the -// given instance, and so NotDeposed will be returned without modifying the -// state at all. -func (s *SyncState) DeposeResourceInstanceObject(addr addrs.AbsResourceInstance) DeposedKey { - s.lock.Lock() - defer s.lock.Unlock() - - ms := s.state.Module(addr.Module) - if ms == nil { - return NotDeposed - } - - return ms.deposeResourceInstanceObject(addr.Resource, NotDeposed) -} - -// DeposeResourceInstanceObjectForceKey is like DeposeResourceInstanceObject -// but uses a pre-allocated key. It's the caller's responsibility to ensure -// that there aren't any races to use a particular key; this method will panic -// if the given key is already in use. -func (s *SyncState) DeposeResourceInstanceObjectForceKey(addr addrs.AbsResourceInstance, forcedKey DeposedKey) { - s.lock.Lock() - defer s.lock.Unlock() - - if forcedKey == NotDeposed { - // Usage error: should use DeposeResourceInstanceObject in this case - panic("DeposeResourceInstanceObjectForceKey called without forced key") - } - - ms := s.state.Module(addr.Module) - if ms == nil { - return // Nothing to do, since there can't be any current object either. - } - - ms.deposeResourceInstanceObject(addr.Resource, forcedKey) -} - -// MaybeRestoreResourceInstanceDeposed will restore the deposed object with the -// given key on the specified resource as the current object for that instance -// if and only if that would not cause us to forget an existing current -// object for that instance. -// -// Returns true if the object was restored to current, or false if no change -// was made at all. -func (s *SyncState) MaybeRestoreResourceInstanceDeposed(addr addrs.AbsResourceInstance, key DeposedKey) bool { - s.lock.Lock() - defer s.lock.Unlock() - - if key == NotDeposed { - panic("MaybeRestoreResourceInstanceDeposed called without DeposedKey") - } - - ms := s.state.Module(addr.Module) - if ms == nil { - // Nothing to do, since the specified deposed object cannot exist. - return false - } - - return ms.maybeRestoreResourceInstanceDeposed(addr.Resource, key) -} - -// RemovePlannedResourceInstanceObjects removes from the state any resource -// instance objects that have the status ObjectPlanned, indiciating that they -// are just transient placeholders created during planning. -// -// Note that this does not restore any "ready" or "tainted" object that might -// have been present before the planned object was written. The only real use -// for this method is in preparing the state created during a refresh walk, -// where we run the planning step for certain instances just to create enough -// information to allow correct expression evaluation within provider and -// data resource blocks. Discarding planned instances in that case is okay -// because the refresh phase only creates planned objects to stand in for -// objects that don't exist yet, and thus the planned object must have been -// absent before by definition. -func (s *SyncState) RemovePlannedResourceInstanceObjects() { - // TODO: Merge together the refresh and plan phases into a single walk, - // so we can remove the need to create this "partial plan" during refresh - // that we then need to clean up before proceeding. - - s.lock.Lock() - defer s.lock.Unlock() - - for _, ms := range s.state.Modules { - moduleAddr := ms.Addr - - for _, rs := range ms.Resources { - resAddr := rs.Addr - - for ik, is := range rs.Instances { - instAddr := resAddr.Instance(ik) - - if is.Current != nil && is.Current.Status == ObjectPlanned { - // Setting the current instance to nil removes it from the - // state altogether if there are not also deposed instances. - ms.SetResourceInstanceCurrent(instAddr, nil, rs.ProviderConfig) - } - - for dk, obj := range is.Deposed { - // Deposed objects should never be "planned", but we'll - // do this anyway for the sake of completeness. - if obj.Status == ObjectPlanned { - ms.ForgetResourceInstanceDeposed(instAddr, dk) - } - } - } - } - - // We may have deleted some objects, which means that we may have - // left a module empty, and so we must prune to preserve the invariant - // that only the root module is allowed to be empty. - s.maybePruneModule(moduleAddr) - } -} - -// Lock acquires an explicit lock on the state, allowing direct read and write -// access to the returned state object. The caller must call Unlock once -// access is no longer needed, and then immediately discard the state pointer -// pointer. -// -// Most callers should not use this. Instead, use the concurrency-safe -// accessors and mutators provided directly on SyncState. -func (s *SyncState) Lock() *State { - s.lock.Lock() - return s.state -} - -// Unlock releases a lock previously acquired by Lock, at which point the -// caller must cease all use of the state pointer that was returned. -// -// Do not call this method except to end an explicit lock acquired by -// Lock. If a caller calls Unlock without first holding the lock, behavior -// is undefined. -func (s *SyncState) Unlock() { - s.lock.Unlock() -} - -// maybePruneModule will remove a module from the state altogether if it is -// empty, unless it's the root module which must always be present. -// -// This helper method is not concurrency-safe on its own, so must only be -// called while the caller is already holding the lock for writing. -func (s *SyncState) maybePruneModule(addr addrs.ModuleInstance) { - if addr.IsRoot() { - // We never prune the root. - return - } - - ms := s.state.Module(addr) - if ms == nil { - return - } - - if ms.empty() { - log.Printf("[TRACE] states.SyncState: pruning %s because it is empty", addr) - s.state.RemoveModule(addr) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/config_traversals.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/config_traversals.go deleted file mode 100644 index 8e41f46ed28..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/config_traversals.go +++ /dev/null @@ -1,68 +0,0 @@ -package tfdiags - -import ( - "bytes" - "fmt" - "strconv" - - "github.com/zclconf/go-cty/cty" -) - -// FormatCtyPath is a helper function to produce a user-friendly string -// representation of a cty.Path. The result uses a syntax similar to the -// HCL expression language in the hope of it being familiar to users. -func FormatCtyPath(path cty.Path) string { - var buf bytes.Buffer - for _, step := range path { - switch ts := step.(type) { - case cty.GetAttrStep: - fmt.Fprintf(&buf, ".%s", ts.Name) - case cty.IndexStep: - buf.WriteByte('[') - key := ts.Key - keyTy := key.Type() - switch { - case key.IsNull(): - buf.WriteString("null") - case !key.IsKnown(): - buf.WriteString("(not yet known)") - case keyTy == cty.Number: - bf := key.AsBigFloat() - buf.WriteString(bf.Text('g', -1)) - case keyTy == cty.String: - buf.WriteString(strconv.Quote(key.AsString())) - default: - buf.WriteString("...") - } - buf.WriteByte(']') - } - } - return buf.String() -} - -// FormatError is a helper function to produce a user-friendly string -// representation of certain special error types that we might want to -// include in diagnostic messages. -// -// This currently has special behavior only for cty.PathError, where a -// non-empty path is rendered in a HCL-like syntax as context. -func FormatError(err error) string { - perr, ok := err.(cty.PathError) - if !ok || len(perr.Path) == 0 { - return err.Error() - } - - return fmt.Sprintf("%s: %s", FormatCtyPath(perr.Path), perr.Error()) -} - -// FormatErrorPrefixed is like FormatError except that it presents any path -// information after the given prefix string, which is assumed to contain -// an HCL syntax representation of the value that errors are relative to. -func FormatErrorPrefixed(err error, prefix string) string { - perr, ok := err.(cty.PathError) - if !ok || len(perr.Path) == 0 { - return fmt.Sprintf("%s: %s", prefix, err.Error()) - } - - return fmt.Sprintf("%s%s: %s", prefix, FormatCtyPath(perr.Path), perr.Error()) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/contextual.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/contextual.go deleted file mode 100644 index 59c06b70b58..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/contextual.go +++ /dev/null @@ -1,372 +0,0 @@ -package tfdiags - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/gocty" -) - -// The "contextual" family of diagnostics are designed to allow separating -// the detection of a problem from placing that problem in context. For -// example, some code that is validating an object extracted from configuration -// may not have access to the configuration that generated it, but can still -// report problems within that object which the caller can then place in -// context by calling IsConfigBody on the returned diagnostics. -// -// When contextual diagnostics are used, the documentation for a method must -// be very explicit about what context is implied for any diagnostics returned, -// to help ensure the expected result. - -// contextualFromConfig is an interface type implemented by diagnostic types -// that can elaborate themselves when given information about the configuration -// body they are embedded in. -// -// Usually this entails extracting source location information in order to -// populate the "Subject" range. -type contextualFromConfigBody interface { - ElaborateFromConfigBody(hcl.Body) Diagnostic -} - -// InConfigBody returns a copy of the receiver with any config-contextual -// diagnostics elaborated in the context of the given body. -func (d Diagnostics) InConfigBody(body hcl.Body) Diagnostics { - if len(d) == 0 { - return nil - } - - ret := make(Diagnostics, len(d)) - for i, srcDiag := range d { - if cd, isCD := srcDiag.(contextualFromConfigBody); isCD { - ret[i] = cd.ElaborateFromConfigBody(body) - } else { - ret[i] = srcDiag - } - } - - return ret -} - -// AttributeValue returns a diagnostic about an attribute value in an implied current -// configuration context. This should be returned only from functions whose -// interface specifies a clear configuration context that this will be -// resolved in. -// -// The given path is relative to the implied configuration context. To describe -// a top-level attribute, it should be a single-element cty.Path with a -// cty.GetAttrStep. It's assumed that the path is returning into a structure -// that would be produced by our conventions in the configschema package; it -// may return unexpected results for structures that can't be represented by -// configschema. -// -// Since mapping attribute paths back onto configuration is an imprecise -// operation (e.g. dynamic block generation may cause the same block to be -// evaluated multiple times) the diagnostic detail should include the attribute -// name and other context required to help the user understand what is being -// referenced in case the identified source range is not unique. -// -// The returned attribute will not have source location information until -// context is applied to the containing diagnostics using diags.InConfigBody. -// After context is applied, the source location is the value assigned to the -// named attribute, or the containing body's "missing item range" if no -// value is present. -func AttributeValue(severity Severity, summary, detail string, attrPath cty.Path) Diagnostic { - return &attributeDiagnostic{ - diagnosticBase: diagnosticBase{ - severity: severity, - summary: summary, - detail: detail, - }, - attrPath: attrPath, - } -} - -// GetAttribute extracts an attribute cty.Path from a diagnostic if it contains -// one. Normally this is not accessed directly, and instead the config body is -// added to the Diagnostic to create a more complete message for the user. In -// some cases however, we may want to know just the name of the attribute that -// generated the Diagnostic message. -// This returns a nil cty.Path if it does not exist in the Diagnostic. -func GetAttribute(d Diagnostic) cty.Path { - if d, ok := d.(*attributeDiagnostic); ok { - return d.attrPath - } - return nil -} - -type attributeDiagnostic struct { - diagnosticBase - attrPath cty.Path - subject *SourceRange // populated only after ElaborateFromConfigBody -} - -// ElaborateFromConfigBody finds the most accurate possible source location -// for a diagnostic's attribute path within the given body. -// -// Backing out from a path back to a source location is not always entirely -// possible because we lose some information in the decoding process, so -// if an exact position cannot be found then the returned diagnostic will -// refer to a position somewhere within the containing body, which is assumed -// to be better than no location at all. -// -// If possible it is generally better to report an error at a layer where -// source location information is still available, for more accuracy. This -// is not always possible due to system architecture, so this serves as a -// "best effort" fallback behavior for such situations. -func (d *attributeDiagnostic) ElaborateFromConfigBody(body hcl.Body) Diagnostic { - if len(d.attrPath) < 1 { - // Should never happen, but we'll allow it rather than crashing. - return d - } - - if d.subject != nil { - // Don't modify an already-elaborated diagnostic. - return d - } - - ret := *d - - // This function will often end up re-decoding values that were already - // decoded by an earlier step. This is non-ideal but is architecturally - // more convenient than arranging for source location information to be - // propagated to every place in Terraform, and this happens only in the - // presence of errors where performance isn't a concern. - - traverse := d.attrPath[:] - final := d.attrPath[len(d.attrPath)-1] - - // Index should never be the first step - // as indexing of top blocks (such as resources & data sources) - // is handled elsewhere - if _, isIdxStep := traverse[0].(cty.IndexStep); isIdxStep { - subject := SourceRangeFromHCL(body.MissingItemRange()) - ret.subject = &subject - return &ret - } - - // Process index separately - idxStep, hasIdx := final.(cty.IndexStep) - if hasIdx { - final = d.attrPath[len(d.attrPath)-2] - traverse = d.attrPath[:len(d.attrPath)-1] - } - - // If we have more than one step after removing index - // then we'll first try to traverse to a child body - // corresponding to the requested path. - if len(traverse) > 1 { - body = traversePathSteps(traverse, body) - } - - // Default is to indicate a missing item in the deepest body we reached - // while traversing. - subject := SourceRangeFromHCL(body.MissingItemRange()) - ret.subject = &subject - - // Once we get here, "final" should be a GetAttr step that maps to an - // attribute in our current body. - finalStep, isAttr := final.(cty.GetAttrStep) - if !isAttr { - return &ret - } - - content, _, contentDiags := body.PartialContent(&hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: finalStep.Name, - Required: true, - }, - }, - }) - if contentDiags.HasErrors() { - return &ret - } - - if attr, ok := content.Attributes[finalStep.Name]; ok { - hclRange := attr.Expr.Range() - if hasIdx { - // Try to be more precise by finding index range - hclRange = hclRangeFromIndexStepAndAttribute(idxStep, attr) - } - subject = SourceRangeFromHCL(hclRange) - ret.subject = &subject - } - - return &ret -} - -func traversePathSteps(traverse []cty.PathStep, body hcl.Body) hcl.Body { - for i := 0; i < len(traverse); i++ { - step := traverse[i] - - switch tStep := step.(type) { - case cty.GetAttrStep: - - var next cty.PathStep - if i < (len(traverse) - 1) { - next = traverse[i+1] - } - - // Will be indexing into our result here? - var indexType cty.Type - var indexVal cty.Value - if nextIndex, ok := next.(cty.IndexStep); ok { - indexVal = nextIndex.Key - indexType = indexVal.Type() - i++ // skip over the index on subsequent iterations - } - - var blockLabelNames []string - if indexType == cty.String { - // Map traversal means we expect one label for the key. - blockLabelNames = []string{"key"} - } - - // For intermediate steps we expect to be referring to a child - // block, so we'll attempt decoding under that assumption. - content, _, contentDiags := body.PartialContent(&hcl.BodySchema{ - Blocks: []hcl.BlockHeaderSchema{ - { - Type: tStep.Name, - LabelNames: blockLabelNames, - }, - }, - }) - if contentDiags.HasErrors() { - return body - } - filtered := make([]*hcl.Block, 0, len(content.Blocks)) - for _, block := range content.Blocks { - if block.Type == tStep.Name { - filtered = append(filtered, block) - } - } - if len(filtered) == 0 { - // Step doesn't refer to a block - continue - } - - switch indexType { - case cty.NilType: // no index at all - if len(filtered) != 1 { - return body - } - body = filtered[0].Body - case cty.Number: - var idx int - err := gocty.FromCtyValue(indexVal, &idx) - if err != nil || idx >= len(filtered) { - return body - } - body = filtered[idx].Body - case cty.String: - key := indexVal.AsString() - var block *hcl.Block - for _, candidate := range filtered { - if candidate.Labels[0] == key { - block = candidate - break - } - } - if block == nil { - // No block with this key, so we'll just indicate a - // missing item in the containing block. - return body - } - body = block.Body - default: - // Should never happen, because only string and numeric indices - // are supported by cty collections. - return body - } - - default: - // For any other kind of step, we'll just return our current body - // as the subject and accept that this is a little inaccurate. - return body - } - } - return body -} - -func hclRangeFromIndexStepAndAttribute(idxStep cty.IndexStep, attr *hcl.Attribute) hcl.Range { - switch idxStep.Key.Type() { - case cty.Number: - var idx int - err := gocty.FromCtyValue(idxStep.Key, &idx) - items, diags := hcl.ExprList(attr.Expr) - if diags.HasErrors() { - return attr.Expr.Range() - } - if err != nil || idx >= len(items) { - return attr.NameRange - } - return items[idx].Range() - case cty.String: - pairs, diags := hcl.ExprMap(attr.Expr) - if diags.HasErrors() { - return attr.Expr.Range() - } - stepKey := idxStep.Key.AsString() - for _, kvPair := range pairs { - key, err := kvPair.Key.Value(nil) - if err != nil { - return attr.Expr.Range() - } - if key.AsString() == stepKey { - startRng := kvPair.Value.StartRange() - return startRng - } - } - return attr.NameRange - } - return attr.Expr.Range() -} - -func (d *attributeDiagnostic) Source() Source { - return Source{ - Subject: d.subject, - } -} - -// WholeContainingBody returns a diagnostic about the body that is an implied -// current configuration context. This should be returned only from -// functions whose interface specifies a clear configuration context that this -// will be resolved in. -// -// The returned attribute will not have source location information until -// context is applied to the containing diagnostics using diags.InConfigBody. -// After context is applied, the source location is currently the missing item -// range of the body. In future, this may change to some other suitable -// part of the containing body. -func WholeContainingBody(severity Severity, summary, detail string) Diagnostic { - return &wholeBodyDiagnostic{ - diagnosticBase: diagnosticBase{ - severity: severity, - summary: summary, - detail: detail, - }, - } -} - -type wholeBodyDiagnostic struct { - diagnosticBase - subject *SourceRange // populated only after ElaborateFromConfigBody -} - -func (d *wholeBodyDiagnostic) ElaborateFromConfigBody(body hcl.Body) Diagnostic { - if d.subject != nil { - // Don't modify an already-elaborated diagnostic. - return d - } - - ret := *d - rng := SourceRangeFromHCL(body.MissingItemRange()) - ret.subject = &rng - return &ret -} - -func (d *wholeBodyDiagnostic) Source() Source { - return Source{ - Subject: d.subject, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/diagnostic.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/diagnostic.go deleted file mode 100644 index a7699cf013c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/diagnostic.go +++ /dev/null @@ -1,40 +0,0 @@ -package tfdiags - -import ( - "github.com/hashicorp/hcl/v2" -) - -type Diagnostic interface { - Severity() Severity - Description() Description - Source() Source - - // FromExpr returns the expression-related context for the diagnostic, if - // available. Returns nil if the diagnostic is not related to an - // expression evaluation. - FromExpr() *FromExpr -} - -type Severity rune - -//go:generate go run golang.org/x/tools/cmd/stringer -type=Severity - -const ( - Error Severity = 'E' - Warning Severity = 'W' -) - -type Description struct { - Summary string - Detail string -} - -type Source struct { - Subject *SourceRange - Context *SourceRange -} - -type FromExpr struct { - Expression hcl.Expression - EvalContext *hcl.EvalContext -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/diagnostic_base.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/diagnostic_base.go deleted file mode 100644 index 50bf9d8eba5..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/diagnostic_base.go +++ /dev/null @@ -1,31 +0,0 @@ -package tfdiags - -// diagnosticBase can be embedded in other diagnostic structs to get -// default implementations of Severity and Description. This type also -// has default implementations of Source and FromExpr that return no source -// location or expression-related information, so embedders should generally -// override those method to return more useful results where possible. -type diagnosticBase struct { - severity Severity - summary string - detail string -} - -func (d diagnosticBase) Severity() Severity { - return d.severity -} - -func (d diagnosticBase) Description() Description { - return Description{ - Summary: d.summary, - Detail: d.detail, - } -} - -func (d diagnosticBase) Source() Source { - return Source{} -} - -func (d diagnosticBase) FromExpr() *FromExpr { - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/diagnostics.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/diagnostics.go deleted file mode 100644 index a19fa80c40d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/diagnostics.go +++ /dev/null @@ -1,318 +0,0 @@ -package tfdiags - -import ( - "bytes" - "fmt" - "path/filepath" - "sort" - "strings" - - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - "github.com/hashicorp/hcl/v2" -) - -// Diagnostics is a list of diagnostics. Diagnostics is intended to be used -// where a Go "error" might normally be used, allowing richer information -// to be conveyed (more context, support for warnings). -// -// A nil Diagnostics is a valid, empty diagnostics list, thus allowing -// heap allocation to be avoided in the common case where there are no -// diagnostics to report at all. -type Diagnostics []Diagnostic - -// Append is the main interface for constructing Diagnostics lists, taking -// an existing list (which may be nil) and appending the new objects to it -// after normalizing them to be implementations of Diagnostic. -// -// The usual pattern for a function that natively "speaks" diagnostics is: -// -// // Create a nil Diagnostics at the start of the function -// var diags diag.Diagnostics -// -// // At later points, build on it if errors / warnings occur: -// foo, err := DoSomethingRisky() -// if err != nil { -// diags = diags.Append(err) -// } -// -// // Eventually return the result and diagnostics in place of error -// return result, diags -// -// Append accepts a variety of different diagnostic-like types, including -// native Go errors and HCL diagnostics. It also knows how to unwrap -// a multierror.Error into separate error diagnostics. It can be passed -// another Diagnostics to concatenate the two lists. If given something -// it cannot handle, this function will panic. -func (diags Diagnostics) Append(new ...interface{}) Diagnostics { - for _, item := range new { - if item == nil { - continue - } - - switch ti := item.(type) { - case Diagnostic: - diags = append(diags, ti) - case Diagnostics: - diags = append(diags, ti...) // flatten - case diagnosticsAsError: - diags = diags.Append(ti.Diagnostics) // unwrap - case NonFatalError: - diags = diags.Append(ti.Diagnostics) // unwrap - case hcl.Diagnostics: - for _, hclDiag := range ti { - diags = append(diags, hclDiagnostic{hclDiag}) - } - case *hcl.Diagnostic: - diags = append(diags, hclDiagnostic{ti}) - case *multierror.Error: - for _, err := range ti.Errors { - diags = append(diags, nativeError{err}) - } - case error: - switch { - case errwrap.ContainsType(ti, Diagnostics(nil)): - // If we have an errwrap wrapper with a Diagnostics hiding - // inside then we'll unpick it here to get access to the - // individual diagnostics. - diags = diags.Append(errwrap.GetType(ti, Diagnostics(nil))) - case errwrap.ContainsType(ti, hcl.Diagnostics(nil)): - // Likewise, if we have HCL diagnostics we'll unpick that too. - diags = diags.Append(errwrap.GetType(ti, hcl.Diagnostics(nil))) - default: - diags = append(diags, nativeError{ti}) - } - default: - panic(fmt.Errorf("can't construct diagnostic(s) from %T", item)) - } - } - - // Given the above, we should never end up with a non-nil empty slice - // here, but we'll make sure of that so callers can rely on empty == nil - if len(diags) == 0 { - return nil - } - - return diags -} - -// HasErrors returns true if any of the diagnostics in the list have -// a severity of Error. -func (diags Diagnostics) HasErrors() bool { - for _, diag := range diags { - if diag.Severity() == Error { - return true - } - } - return false -} - -// ForRPC returns a version of the receiver that has been simplified so that -// it is friendly to RPC protocols. -// -// Currently this means that it can be serialized with encoding/gob and -// subsequently re-inflated. It may later grow to include other serialization -// formats. -// -// Note that this loses information about the original objects used to -// construct the diagnostics, so e.g. the errwrap API will not work as -// expected on an error-wrapped Diagnostics that came from ForRPC. -func (diags Diagnostics) ForRPC() Diagnostics { - ret := make(Diagnostics, len(diags)) - for i := range diags { - ret[i] = makeRPCFriendlyDiag(diags[i]) - } - return ret -} - -// Err flattens a diagnostics list into a single Go error, or to nil -// if the diagnostics list does not include any error-level diagnostics. -// -// This can be used to smuggle diagnostics through an API that deals in -// native errors, but unfortunately it will lose naked warnings (warnings -// that aren't accompanied by at least one error) since such APIs have no -// mechanism through which to report these. -// -// return result, diags.Error() -func (diags Diagnostics) Err() error { - if !diags.HasErrors() { - return nil - } - return diagnosticsAsError{diags} -} - -// ErrWithWarnings is similar to Err except that it will also return a non-nil -// error if the receiver contains only warnings. -// -// In the warnings-only situation, the result is guaranteed to be of dynamic -// type NonFatalError, allowing diagnostics-aware callers to type-assert -// and unwrap it, treating it as non-fatal. -// -// This should be used only in contexts where the caller is able to recognize -// and handle NonFatalError. For normal callers that expect a lack of errors -// to be signaled by nil, use just Diagnostics.Err. -func (diags Diagnostics) ErrWithWarnings() error { - if len(diags) == 0 { - return nil - } - if diags.HasErrors() { - return diags.Err() - } - return NonFatalError{diags} -} - -// NonFatalErr is similar to Err except that it always returns either nil -// (if there are no diagnostics at all) or NonFatalError. -// -// This allows diagnostics to be returned over an error return channel while -// being explicit that the diagnostics should not halt processing. -// -// This should be used only in contexts where the caller is able to recognize -// and handle NonFatalError. For normal callers that expect a lack of errors -// to be signaled by nil, use just Diagnostics.Err. -func (diags Diagnostics) NonFatalErr() error { - if len(diags) == 0 { - return nil - } - return NonFatalError{diags} -} - -type diagnosticsAsError struct { - Diagnostics -} - -func (dae diagnosticsAsError) Error() string { - diags := dae.Diagnostics - switch { - case len(diags) == 0: - // should never happen, since we don't create this wrapper if - // there are no diagnostics in the list. - return "no errors" - case len(diags) == 1: - desc := diags[0].Description() - if desc.Detail == "" { - return desc.Summary - } - return fmt.Sprintf("%s: %s", desc.Summary, desc.Detail) - default: - var ret bytes.Buffer - fmt.Fprintf(&ret, "%d problems:\n", len(diags)) - for _, diag := range dae.Diagnostics { - desc := diag.Description() - if desc.Detail == "" { - fmt.Fprintf(&ret, "\n- %s", desc.Summary) - } else { - fmt.Fprintf(&ret, "\n- %s: %s", desc.Summary, desc.Detail) - } - } - return ret.String() - } -} - -// WrappedErrors is an implementation of errwrap.Wrapper so that an error-wrapped -// diagnostics object can be picked apart by errwrap-aware code. -func (dae diagnosticsAsError) WrappedErrors() []error { - var errs []error - for _, diag := range dae.Diagnostics { - if wrapper, isErr := diag.(nativeError); isErr { - errs = append(errs, wrapper.err) - } - } - return errs -} - -// NonFatalError is a special error type, returned by -// Diagnostics.ErrWithWarnings and Diagnostics.NonFatalErr, -// that indicates that the wrapped diagnostics should be treated as non-fatal. -// Callers can conditionally type-assert an error to this type in order to -// detect the non-fatal scenario and handle it in a different way. -type NonFatalError struct { - Diagnostics -} - -func (woe NonFatalError) Error() string { - diags := woe.Diagnostics - switch { - case len(diags) == 0: - // should never happen, since we don't create this wrapper if - // there are no diagnostics in the list. - return "no errors or warnings" - case len(diags) == 1: - desc := diags[0].Description() - if desc.Detail == "" { - return desc.Summary - } - return fmt.Sprintf("%s: %s", desc.Summary, desc.Detail) - default: - var ret bytes.Buffer - if diags.HasErrors() { - fmt.Fprintf(&ret, "%d problems:\n", len(diags)) - } else { - fmt.Fprintf(&ret, "%d warnings:\n", len(diags)) - } - for _, diag := range woe.Diagnostics { - desc := diag.Description() - if desc.Detail == "" { - fmt.Fprintf(&ret, "\n- %s", desc.Summary) - } else { - fmt.Fprintf(&ret, "\n- %s: %s", desc.Summary, desc.Detail) - } - } - return ret.String() - } -} - -// sortDiagnostics is an implementation of sort.Interface -type sortDiagnostics []Diagnostic - -var _ sort.Interface = sortDiagnostics(nil) - -func (sd sortDiagnostics) Len() int { - return len(sd) -} - -func (sd sortDiagnostics) Less(i, j int) bool { - iD, jD := sd[i], sd[j] - iSev, jSev := iD.Severity(), jD.Severity() - iSrc, jSrc := iD.Source(), jD.Source() - - switch { - - case iSev != jSev: - return iSev == Warning - - case (iSrc.Subject == nil) != (jSrc.Subject == nil): - return iSrc.Subject == nil - - case iSrc.Subject != nil && *iSrc.Subject != *jSrc.Subject: - iSubj := iSrc.Subject - jSubj := jSrc.Subject - switch { - case iSubj.Filename != jSubj.Filename: - // Path with fewer segments goes first if they are different lengths - sep := string(filepath.Separator) - iCount := strings.Count(iSubj.Filename, sep) - jCount := strings.Count(jSubj.Filename, sep) - if iCount != jCount { - return iCount < jCount - } - return iSubj.Filename < jSubj.Filename - case iSubj.Start.Byte != jSubj.Start.Byte: - return iSubj.Start.Byte < jSubj.Start.Byte - case iSubj.End.Byte != jSubj.End.Byte: - return iSubj.End.Byte < jSubj.End.Byte - } - fallthrough - - default: - // The remaining properties do not have a defined ordering, so - // we'll leave it unspecified. Since we use sort.Stable in - // the caller of this, the ordering of remaining items will - // be preserved. - return false - } -} - -func (sd sortDiagnostics) Swap(i, j int) { - sd[i], sd[j] = sd[j], sd[i] -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/error.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/error.go deleted file mode 100644 index 13f7a714f42..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/error.go +++ /dev/null @@ -1,28 +0,0 @@ -package tfdiags - -// nativeError is a Diagnostic implementation that wraps a normal Go error -type nativeError struct { - err error -} - -var _ Diagnostic = nativeError{} - -func (e nativeError) Severity() Severity { - return Error -} - -func (e nativeError) Description() Description { - return Description{ - Summary: FormatError(e.err), - } -} - -func (e nativeError) Source() Source { - // No source information available for a native error - return Source{} -} - -func (e nativeError) FromExpr() *FromExpr { - // Native errors are not expression-related - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/hcl.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/hcl.go deleted file mode 100644 index 8c781611a5c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/hcl.go +++ /dev/null @@ -1,87 +0,0 @@ -package tfdiags - -import ( - "github.com/hashicorp/hcl/v2" -) - -// hclDiagnostic is a Diagnostic implementation that wraps a HCL Diagnostic -type hclDiagnostic struct { - diag *hcl.Diagnostic -} - -var _ Diagnostic = hclDiagnostic{} - -func (d hclDiagnostic) Severity() Severity { - switch d.diag.Severity { - case hcl.DiagWarning: - return Warning - default: - return Error - } -} - -func (d hclDiagnostic) Description() Description { - return Description{ - Summary: d.diag.Summary, - Detail: d.diag.Detail, - } -} - -func (d hclDiagnostic) Source() Source { - var ret Source - if d.diag.Subject != nil { - rng := SourceRangeFromHCL(*d.diag.Subject) - ret.Subject = &rng - } - if d.diag.Context != nil { - rng := SourceRangeFromHCL(*d.diag.Context) - ret.Context = &rng - } - return ret -} - -func (d hclDiagnostic) FromExpr() *FromExpr { - if d.diag.Expression == nil || d.diag.EvalContext == nil { - return nil - } - return &FromExpr{ - Expression: d.diag.Expression, - EvalContext: d.diag.EvalContext, - } -} - -// SourceRangeFromHCL constructs a SourceRange from the corresponding range -// type within the HCL package. -func SourceRangeFromHCL(hclRange hcl.Range) SourceRange { - return SourceRange{ - Filename: hclRange.Filename, - Start: SourcePos{ - Line: hclRange.Start.Line, - Column: hclRange.Start.Column, - Byte: hclRange.Start.Byte, - }, - End: SourcePos{ - Line: hclRange.End.Line, - Column: hclRange.End.Column, - Byte: hclRange.End.Byte, - }, - } -} - -// ToHCL constructs a HCL Range from the receiving SourceRange. This is the -// opposite of SourceRangeFromHCL. -func (r SourceRange) ToHCL() hcl.Range { - return hcl.Range{ - Filename: r.Filename, - Start: hcl.Pos{ - Line: r.Start.Line, - Column: r.Start.Column, - Byte: r.Start.Byte, - }, - End: hcl.Pos{ - Line: r.End.Line, - Column: r.End.Column, - Byte: r.End.Byte, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/rpc_friendly.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/rpc_friendly.go deleted file mode 100644 index 485063b0c0e..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/rpc_friendly.go +++ /dev/null @@ -1,59 +0,0 @@ -package tfdiags - -import ( - "encoding/gob" -) - -type rpcFriendlyDiag struct { - Severity_ Severity - Summary_ string - Detail_ string - Subject_ *SourceRange - Context_ *SourceRange -} - -// rpcFriendlyDiag transforms a given diagnostic so that is more friendly to -// RPC. -// -// In particular, it currently returns an object that can be serialized and -// later re-inflated using gob. This definition may grow to include other -// serializations later. -func makeRPCFriendlyDiag(diag Diagnostic) Diagnostic { - desc := diag.Description() - source := diag.Source() - return &rpcFriendlyDiag{ - Severity_: diag.Severity(), - Summary_: desc.Summary, - Detail_: desc.Detail, - Subject_: source.Subject, - Context_: source.Context, - } -} - -func (d *rpcFriendlyDiag) Severity() Severity { - return d.Severity_ -} - -func (d *rpcFriendlyDiag) Description() Description { - return Description{ - Summary: d.Summary_, - Detail: d.Detail_, - } -} - -func (d *rpcFriendlyDiag) Source() Source { - return Source{ - Subject: d.Subject_, - Context: d.Context_, - } -} - -func (d rpcFriendlyDiag) FromExpr() *FromExpr { - // RPC-friendly diagnostics cannot preserve expression information because - // expressions themselves are not RPC-friendly. - return nil -} - -func init() { - gob.Register((*rpcFriendlyDiag)(nil)) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/simple_warning.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/simple_warning.go deleted file mode 100644 index b0f1ecd46c6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/simple_warning.go +++ /dev/null @@ -1,30 +0,0 @@ -package tfdiags - -type simpleWarning string - -var _ Diagnostic = simpleWarning("") - -// SimpleWarning constructs a simple (summary-only) warning diagnostic. -func SimpleWarning(msg string) Diagnostic { - return simpleWarning(msg) -} - -func (e simpleWarning) Severity() Severity { - return Warning -} - -func (e simpleWarning) Description() Description { - return Description{ - Summary: string(e), - } -} - -func (e simpleWarning) Source() Source { - // No source information available for a simple warning - return Source{} -} - -func (e simpleWarning) FromExpr() *FromExpr { - // Simple warnings are not expression-related - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/source_range.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/source_range.go deleted file mode 100644 index 3031168d6a4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/source_range.go +++ /dev/null @@ -1,35 +0,0 @@ -package tfdiags - -import ( - "fmt" - "os" - "path/filepath" -) - -type SourceRange struct { - Filename string - Start, End SourcePos -} - -type SourcePos struct { - Line, Column, Byte int -} - -// StartString returns a string representation of the start of the range, -// including the filename and the line and column numbers. -func (r SourceRange) StartString() string { - filename := r.Filename - - // We'll try to relative-ize our filename here so it's less verbose - // in the common case of being in the current working directory. If not, - // we'll just show the full path. - wd, err := os.Getwd() - if err == nil { - relFn, err := filepath.Rel(wd, filename) - if err == nil { - filename = relFn - } - } - - return fmt.Sprintf("%s:%d,%d", filename, r.Start.Line, r.Start.Column) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/sourceless.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/sourceless.go deleted file mode 100644 index eaa27373db1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/sourceless.go +++ /dev/null @@ -1,13 +0,0 @@ -package tfdiags - -// Sourceless creates and returns a diagnostic with no source location -// information. This is generally used for operational-type errors that are -// caused by or relate to the environment where Terraform is running rather -// than to the provided configuration. -func Sourceless(severity Severity, summary, detail string) Diagnostic { - return diagnosticBase{ - severity: severity, - summary: summary, - detail: detail, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/helper/pgpkeys/encrypt_decrypt.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/helper/pgpkeys/encrypt_decrypt.go deleted file mode 100644 index 8f6be2bf0dc..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/helper/pgpkeys/encrypt_decrypt.go +++ /dev/null @@ -1,85 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/keybase/go-crypto/openpgp" - "github.com/keybase/go-crypto/openpgp/packet" -) - -// EncryptShares takes an ordered set of byte slices to encrypt and the -// corresponding base64-encoded public keys to encrypt them with, encrypts each -// byte slice with the corresponding public key. -// -// Note: There is no corresponding test function; this functionality is -// thoroughly tested in the init and rekey command unit tests -func EncryptShares(input [][]byte, pgpKeys []string) ([]string, [][]byte, error) { - if len(input) != len(pgpKeys) { - return nil, nil, fmt.Errorf("mismatch between number items to encrypt and number of PGP keys") - } - encryptedShares := make([][]byte, 0, len(pgpKeys)) - entities, err := GetEntities(pgpKeys) - if err != nil { - return nil, nil, err - } - for i, entity := range entities { - ctBuf := bytes.NewBuffer(nil) - pt, err := openpgp.Encrypt(ctBuf, []*openpgp.Entity{entity}, nil, nil, nil) - if err != nil { - return nil, nil, errwrap.Wrapf("error setting up encryption for PGP message: {{err}}", err) - } - _, err = pt.Write(input[i]) - if err != nil { - return nil, nil, errwrap.Wrapf("error encrypting PGP message: {{err}}", err) - } - pt.Close() - encryptedShares = append(encryptedShares, ctBuf.Bytes()) - } - - fingerprints, err := GetFingerprints(nil, entities) - if err != nil { - return nil, nil, err - } - - return fingerprints, encryptedShares, nil -} - -// GetFingerprints takes in a list of openpgp Entities and returns the -// fingerprints. If entities is nil, it will instead parse both entities and -// fingerprints from the pgpKeys string slice. -func GetFingerprints(pgpKeys []string, entities []*openpgp.Entity) ([]string, error) { - if entities == nil { - var err error - entities, err = GetEntities(pgpKeys) - - if err != nil { - return nil, err - } - } - ret := make([]string, 0, len(entities)) - for _, entity := range entities { - ret = append(ret, fmt.Sprintf("%x", entity.PrimaryKey.Fingerprint)) - } - return ret, nil -} - -// GetEntities takes in a string array of base64-encoded PGP keys and returns -// the openpgp Entities -func GetEntities(pgpKeys []string) ([]*openpgp.Entity, error) { - ret := make([]*openpgp.Entity, 0, len(pgpKeys)) - for _, keystring := range pgpKeys { - data, err := base64.StdEncoding.DecodeString(keystring) - if err != nil { - return nil, errwrap.Wrapf("error decoding given PGP key: {{err}}", err) - } - entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data))) - if err != nil { - return nil, errwrap.Wrapf("error parsing given PGP key: {{err}}", err) - } - ret = append(ret, entity) - } - return ret, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/helper/pgpkeys/flag.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/helper/pgpkeys/flag.go deleted file mode 100644 index e83dac99b54..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/helper/pgpkeys/flag.go +++ /dev/null @@ -1,112 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "errors" - "fmt" - "os" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/keybase/go-crypto/openpgp" -) - -// PGPPubKeyFiles implements the flag.Value interface and allows parsing and -// reading a list of PGP public key files. -type PubKeyFilesFlag []string - -func (p *PubKeyFilesFlag) String() string { - return fmt.Sprint(*p) -} - -func (p *PubKeyFilesFlag) Set(val string) error { - if len(*p) > 0 { - return errors.New("can only be specified once") - } - - keys, err := ParsePGPKeys(strings.Split(val, ",")) - if err != nil { - return err - } - - *p = PubKeyFilesFlag(keys) - return nil -} - -// ParsePGPKeys takes a list of PGP keys and parses them either using keybase -// or reading them from disk and returns the "expanded" list of pgp keys in -// the same order. -func ParsePGPKeys(keyfiles []string) ([]string, error) { - keys := make([]string, len(keyfiles)) - - keybaseMap, err := FetchKeybasePubkeys(keyfiles) - if err != nil { - return nil, err - } - - for i, keyfile := range keyfiles { - keyfile = strings.TrimSpace(keyfile) - - if strings.HasPrefix(keyfile, kbPrefix) { - key, ok := keybaseMap[keyfile] - if !ok || key == "" { - return nil, fmt.Errorf("keybase user %q not found", strings.TrimPrefix(keyfile, kbPrefix)) - } - keys[i] = key - continue - } - - pgpStr, err := ReadPGPFile(keyfile) - if err != nil { - return nil, err - } - keys[i] = pgpStr - } - - return keys, nil -} - -// ReadPGPFile reads the given PGP file from disk. -func ReadPGPFile(path string) (string, error) { - if path[0] == '@' { - path = path[1:] - } - f, err := os.Open(path) - if err != nil { - return "", err - } - defer f.Close() - buf := bytes.NewBuffer(nil) - _, err = buf.ReadFrom(f) - if err != nil { - return "", err - } - - // First parse as an armored keyring file, if that doesn't work, treat it as a straight binary/b64 string - keyReader := bytes.NewReader(buf.Bytes()) - entityList, err := openpgp.ReadArmoredKeyRing(keyReader) - if err == nil { - if len(entityList) != 1 { - return "", fmt.Errorf("more than one key found in file %q", path) - } - if entityList[0] == nil { - return "", fmt.Errorf("primary key was nil for file %q", path) - } - - serializedEntity := bytes.NewBuffer(nil) - err = entityList[0].Serialize(serializedEntity) - if err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("error serializing entity for file %q: {{err}}", path), err) - } - - return base64.StdEncoding.EncodeToString(serializedEntity.Bytes()), nil - } - - _, err = base64.StdEncoding.DecodeString(buf.String()) - if err == nil { - return buf.String(), nil - } - return base64.StdEncoding.EncodeToString(buf.Bytes()), nil - -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/helper/pgpkeys/keybase.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/helper/pgpkeys/keybase.go deleted file mode 100644 index 7d153346a5c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/helper/pgpkeys/keybase.go +++ /dev/null @@ -1,117 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - cleanhttp "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/terraform-plugin-sdk/internal/vault/sdk/helper/jsonutil" - "github.com/keybase/go-crypto/openpgp" -) - -const ( - kbPrefix = "keybase:" -) - -// FetchKeybasePubkeys fetches public keys from Keybase given a set of -// usernames, which are derived from correctly formatted input entries. It -// doesn't use their client code due to both the API and the fact that it is -// considered alpha and probably best not to rely on it. The keys are returned -// as base64-encoded strings. -func FetchKeybasePubkeys(input []string) (map[string]string, error) { - client := cleanhttp.DefaultClient() - if client == nil { - return nil, fmt.Errorf("unable to create an http client") - } - - if len(input) == 0 { - return nil, nil - } - - usernames := make([]string, 0, len(input)) - for _, v := range input { - if strings.HasPrefix(v, kbPrefix) { - usernames = append(usernames, strings.TrimPrefix(v, kbPrefix)) - } - } - - if len(usernames) == 0 { - return nil, nil - } - - ret := make(map[string]string, len(usernames)) - url := fmt.Sprintf("https://keybase.io/_/api/1.0/user/lookup.json?usernames=%s&fields=public_keys", strings.Join(usernames, ",")) - resp, err := client.Get(url) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - type PublicKeys struct { - Primary struct { - Bundle string - } - } - - type LThem struct { - PublicKeys `json:"public_keys"` - } - - type KbResp struct { - Status struct { - Name string - } - Them []LThem - } - - out := &KbResp{ - Them: []LThem{}, - } - - if err := jsonutil.DecodeJSONFromReader(resp.Body, out); err != nil { - return nil, err - } - - if out.Status.Name != "OK" { - return nil, fmt.Errorf("got non-OK response: %q", out.Status.Name) - } - - missingNames := make([]string, 0, len(usernames)) - var keyReader *bytes.Reader - serializedEntity := bytes.NewBuffer(nil) - for i, themVal := range out.Them { - if themVal.Primary.Bundle == "" { - missingNames = append(missingNames, usernames[i]) - continue - } - keyReader = bytes.NewReader([]byte(themVal.Primary.Bundle)) - entityList, err := openpgp.ReadArmoredKeyRing(keyReader) - if err != nil { - return nil, err - } - if len(entityList) != 1 { - return nil, fmt.Errorf("primary key could not be parsed for user %q", usernames[i]) - } - if entityList[0] == nil { - return nil, fmt.Errorf("primary key was nil for user %q", usernames[i]) - } - - serializedEntity.Reset() - err = entityList[0].Serialize(serializedEntity) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error serializing entity for user %q: {{err}}", usernames[i]), err) - } - - // The API returns values in the same ordering requested, so this should properly match - ret[kbPrefix+usernames[i]] = base64.StdEncoding.EncodeToString(serializedEntity.Bytes()) - } - - if len(missingNames) > 0 { - return nil, fmt.Errorf("unable to fetch keys for user(s) %q from keybase", strings.Join(missingNames, ",")) - } - - return ret, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/sdk/helper/compressutil/compress.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/sdk/helper/compressutil/compress.go deleted file mode 100644 index 356d4548fa4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/sdk/helper/compressutil/compress.go +++ /dev/null @@ -1,207 +0,0 @@ -package compressutil - -import ( - "bytes" - "compress/gzip" - "compress/lzw" - "fmt" - "io" - - "github.com/golang/snappy" - "github.com/hashicorp/errwrap" - "github.com/pierrec/lz4" -) - -const ( - // A byte value used as a canary prefix for the compressed information - // which is used to distinguish if a JSON input is compressed or not. - // The value of this constant should not be a first character of any - // valid JSON string. - - CompressionTypeGzip = "gzip" - CompressionCanaryGzip byte = 'G' - - CompressionTypeLZW = "lzw" - CompressionCanaryLZW byte = 'L' - - CompressionTypeSnappy = "snappy" - CompressionCanarySnappy byte = 'S' - - CompressionTypeLZ4 = "lz4" - CompressionCanaryLZ4 byte = '4' -) - -// SnappyReadCloser embeds the snappy reader which implements the io.Reader -// interface. The decompress procedure in this utility expects an -// io.ReadCloser. This type implements the io.Closer interface to retain the -// generic way of decompression. -type CompressUtilReadCloser struct { - io.Reader -} - -// Close is a noop method implemented only to satisfy the io.Closer interface -func (c *CompressUtilReadCloser) Close() error { - return nil -} - -// CompressionConfig is used to select a compression type to be performed by -// Compress and Decompress utilities. -// Supported types are: -// * CompressionTypeLZW -// * CompressionTypeGzip -// * CompressionTypeSnappy -// * CompressionTypeLZ4 -// -// When using CompressionTypeGzip, the compression levels can also be chosen: -// * gzip.DefaultCompression -// * gzip.BestSpeed -// * gzip.BestCompression -type CompressionConfig struct { - // Type of the compression algorithm to be used - Type string - - // When using Gzip format, the compression level to employ - GzipCompressionLevel int -} - -// Compress places the canary byte in a buffer and uses the same buffer to fill -// in the compressed information of the given input. The configuration supports -// two type of compression: LZW and Gzip. When using Gzip compression format, -// if GzipCompressionLevel is not specified, the 'gzip.DefaultCompression' will -// be assumed. -func Compress(data []byte, config *CompressionConfig) ([]byte, error) { - var buf bytes.Buffer - var writer io.WriteCloser - var err error - - if config == nil { - return nil, fmt.Errorf("config is nil") - } - - // Write the canary into the buffer and create writer to compress the - // input data based on the configured type - switch config.Type { - case CompressionTypeLZW: - buf.Write([]byte{CompressionCanaryLZW}) - writer = lzw.NewWriter(&buf, lzw.LSB, 8) - - case CompressionTypeGzip: - buf.Write([]byte{CompressionCanaryGzip}) - - switch { - case config.GzipCompressionLevel == gzip.BestCompression, - config.GzipCompressionLevel == gzip.BestSpeed, - config.GzipCompressionLevel == gzip.DefaultCompression: - // These are valid compression levels - default: - // If compression level is set to NoCompression or to - // any invalid value, fallback to Defaultcompression - config.GzipCompressionLevel = gzip.DefaultCompression - } - writer, err = gzip.NewWriterLevel(&buf, config.GzipCompressionLevel) - - case CompressionTypeSnappy: - buf.Write([]byte{CompressionCanarySnappy}) - writer = snappy.NewBufferedWriter(&buf) - - case CompressionTypeLZ4: - buf.Write([]byte{CompressionCanaryLZ4}) - writer = lz4.NewWriter(&buf) - - default: - return nil, fmt.Errorf("unsupported compression type") - } - - if err != nil { - return nil, errwrap.Wrapf("failed to create a compression writer: {{err}}", err) - } - - if writer == nil { - return nil, fmt.Errorf("failed to create a compression writer") - } - - // Compress the input and place it in the same buffer containing the - // canary byte. - if _, err = writer.Write(data); err != nil { - return nil, errwrap.Wrapf("failed to compress input data: err: {{err}}", err) - } - - // Close the io.WriteCloser - if err = writer.Close(); err != nil { - return nil, err - } - - // Return the compressed bytes with canary byte at the start - return buf.Bytes(), nil -} - -// Decompress checks if the first byte in the input matches the canary byte. -// If the first byte is a canary byte, then the input past the canary byte -// will be decompressed using the method specified in the given configuration. -// If the first byte isn't a canary byte, then the utility returns a boolean -// value indicating that the input was not compressed. -func Decompress(data []byte) ([]byte, bool, error) { - var err error - var reader io.ReadCloser - if data == nil || len(data) == 0 { - return nil, false, fmt.Errorf("'data' being decompressed is empty") - } - - canary := data[0] - cData := data[1:] - - switch canary { - // If the first byte matches the canary byte, remove the canary - // byte and try to decompress the data that is after the canary. - case CompressionCanaryGzip: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - reader, err = gzip.NewReader(bytes.NewReader(cData)) - - case CompressionCanaryLZW: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - reader = lzw.NewReader(bytes.NewReader(cData), lzw.LSB, 8) - - case CompressionCanarySnappy: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - reader = &CompressUtilReadCloser{ - Reader: snappy.NewReader(bytes.NewReader(cData)), - } - - case CompressionCanaryLZ4: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - reader = &CompressUtilReadCloser{ - Reader: lz4.NewReader(bytes.NewReader(cData)), - } - - default: - // If the first byte doesn't match the canary byte, it means - // that the content was not compressed at all. Indicate the - // caller that the input was not compressed. - return nil, true, nil - } - if err != nil { - return nil, false, errwrap.Wrapf("failed to create a compression reader: {{err}}", err) - } - if reader == nil { - return nil, false, fmt.Errorf("failed to create a compression reader") - } - - // Close the io.ReadCloser - defer reader.Close() - - // Read all the compressed data into a buffer - var buf bytes.Buffer - if _, err = io.Copy(&buf, reader); err != nil { - return nil, false, err - } - - return buf.Bytes(), false, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/sdk/helper/jsonutil/json.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/sdk/helper/jsonutil/json.go deleted file mode 100644 index b5dbca4f86f..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/vault/sdk/helper/jsonutil/json.go +++ /dev/null @@ -1,100 +0,0 @@ -package jsonutil - -import ( - "bytes" - "compress/gzip" - "encoding/json" - "fmt" - "io" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/terraform-plugin-sdk/internal/vault/sdk/helper/compressutil" -) - -// Encodes/Marshals the given object into JSON -func EncodeJSON(in interface{}) ([]byte, error) { - if in == nil { - return nil, fmt.Errorf("input for encoding is nil") - } - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - if err := enc.Encode(in); err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// EncodeJSONAndCompress encodes the given input into JSON and compresses the -// encoded value (using Gzip format BestCompression level, by default). A -// canary byte is placed at the beginning of the returned bytes for the logic -// in decompression method to identify compressed input. -func EncodeJSONAndCompress(in interface{}, config *compressutil.CompressionConfig) ([]byte, error) { - if in == nil { - return nil, fmt.Errorf("input for encoding is nil") - } - - // First JSON encode the given input - encodedBytes, err := EncodeJSON(in) - if err != nil { - return nil, err - } - - if config == nil { - config = &compressutil.CompressionConfig{ - Type: compressutil.CompressionTypeGzip, - GzipCompressionLevel: gzip.BestCompression, - } - } - - return compressutil.Compress(encodedBytes, config) -} - -// DecodeJSON tries to decompress the given data. The call to decompress, fails -// if the content was not compressed in the first place, which is identified by -// a canary byte before the compressed data. If the data is not compressed, it -// is JSON decoded directly. Otherwise the decompressed data will be JSON -// decoded. -func DecodeJSON(data []byte, out interface{}) error { - if data == nil || len(data) == 0 { - return fmt.Errorf("'data' being decoded is nil") - } - if out == nil { - return fmt.Errorf("output parameter 'out' is nil") - } - - // Decompress the data if it was compressed in the first place - decompressedBytes, uncompressed, err := compressutil.Decompress(data) - if err != nil { - return errwrap.Wrapf("failed to decompress JSON: {{err}}", err) - } - if !uncompressed && (decompressedBytes == nil || len(decompressedBytes) == 0) { - return fmt.Errorf("decompressed data being decoded is invalid") - } - - // If the input supplied failed to contain the compression canary, it - // will be notified by the compression utility. Decode the decompressed - // input. - if !uncompressed { - data = decompressedBytes - } - - return DecodeJSONFromReader(bytes.NewReader(data), out) -} - -// Decodes/Unmarshals the given io.Reader pointing to a JSON, into a desired object -func DecodeJSONFromReader(r io.Reader, out interface{}) error { - if r == nil { - return fmt.Errorf("'io.Reader' being decoded is nil") - } - if out == nil { - return fmt.Errorf("output parameter 'out' is nil") - } - - dec := json.NewDecoder(r) - - // While decoding JSON values, interpret the integer values as `json.Number`s instead of `float64`. - dec.UseNumber() - - // Since 'out' is an interface representing a pointer, pass it to the decoder without an '&' - return dec.Decode(out) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/version/version.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/version/version.go deleted file mode 100644 index 2d56dab6960..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/version/version.go +++ /dev/null @@ -1,36 +0,0 @@ -// The version package provides a location to set the release versions for all -// packages to consume, without creating import cycles. -// -// This package should not import any other terraform packages. -package version - -import ( - "fmt" - - version "github.com/hashicorp/go-version" -) - -// The main version number that is being run at the moment. -var Version = "0.12.7" - -// A pre-release marker for the version. If this is "" (empty string) -// then it means that it is a final release. Otherwise, this is a pre-release -// such as "dev" (in development), "beta", "rc1", etc. -var Prerelease = "sdk" - -// SemVer is an instance of version.Version. This has the secondary -// benefit of verifying during tests and init time that our version is a -// proper semantic version, which should always be the case. -var SemVer *version.Version - -func init() { - SemVer = version.Must(version.NewVersion(Version)) -} - -// String returns the complete version string, including prerelease -func String() string { - if Prerelease != "" { - return fmt.Sprintf("%s-%s", Version, Prerelease) - } - return Version -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/meta/meta.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/meta/meta.go deleted file mode 100644 index 0363c2d9371..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/meta/meta.go +++ /dev/null @@ -1,36 +0,0 @@ -// The meta package provides a location to set the release version -// and any other relevant metadata for the SDK. -// -// This package should not import any other SDK packages. -package meta - -import ( - "fmt" - - version "github.com/hashicorp/go-version" -) - -// The main version number that is being run at the moment. -var SDKVersion = "1.9.0" - -// A pre-release marker for the version. If this is "" (empty string) -// then it means that it is a final release. Otherwise, this is a pre-release -// such as "dev" (in development), "beta", "rc1", etc. -var SDKPrerelease = "" - -// SemVer is an instance of version.Version. This has the secondary -// benefit of verifying during tests and init time that our version is a -// proper semantic version, which should always be the case. -var SemVer *version.Version - -func init() { - SemVer = version.Must(version.NewVersion(SDKVersion)) -} - -// VersionString returns the complete version string, including prerelease -func SDKVersionString() string { - if SDKPrerelease != "" { - return fmt.Sprintf("%s-%s", SDKVersion, SDKPrerelease) - } - return SDKVersion -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/client.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/client.go deleted file mode 100644 index 5a99e90064a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/client.go +++ /dev/null @@ -1,35 +0,0 @@ -package plugin - -import ( - "os" - "os/exec" - - hclog "github.com/hashicorp/go-hclog" - plugin "github.com/hashicorp/go-plugin" - "github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery" -) - -// ClientConfig returns a configuration object that can be used to instantiate -// a client for the plugin described by the given metadata. -func ClientConfig(m discovery.PluginMeta) *plugin.ClientConfig { - logger := hclog.New(&hclog.LoggerOptions{ - Name: "plugin", - Level: hclog.Trace, - Output: os.Stderr, - }) - - return &plugin.ClientConfig{ - Cmd: exec.Command(m.Path), - HandshakeConfig: Handshake, - VersionedPlugins: VersionedPlugins, - Managed: true, - Logger: logger, - AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC}, - AutoMTLS: true, - } -} - -// Client returns a plugin client for the plugin described by the given metadata. -func Client(m discovery.PluginMeta) *plugin.Client { - return plugin.NewClient(ClientConfig(m)) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/grpc_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/grpc_provider.go deleted file mode 100644 index e4520975c1b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/grpc_provider.go +++ /dev/null @@ -1,563 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "log" - "sync" - - "github.com/zclconf/go-cty/cty" - - plugin "github.com/hashicorp/go-plugin" - "github.com/hashicorp/terraform-plugin-sdk/internal/plugin/convert" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - proto "github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5" - "github.com/zclconf/go-cty/cty/msgpack" - "google.golang.org/grpc" -) - -// GRPCProviderPlugin implements plugin.GRPCPlugin for the go-plugin package. -type GRPCProviderPlugin struct { - plugin.Plugin - GRPCProvider func() proto.ProviderServer -} - -func (p *GRPCProviderPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { - return &GRPCProvider{ - client: proto.NewProviderClient(c), - ctx: ctx, - }, nil -} - -func (p *GRPCProviderPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error { - proto.RegisterProviderServer(s, p.GRPCProvider()) - return nil -} - -// GRPCProvider handles the client, or core side of the plugin rpc connection. -// The GRPCProvider methods are mostly a translation layer between the -// terraform provioders types and the grpc proto types, directly converting -// between the two. -type GRPCProvider struct { - // PluginClient provides a reference to the plugin.Client which controls the plugin process. - // This allows the GRPCProvider a way to shutdown the plugin process. - PluginClient *plugin.Client - - // TestServer contains a grpc.Server to close when the GRPCProvider is being - // used in an end to end test of a provider. - TestServer *grpc.Server - - // Proto client use to make the grpc service calls. - client proto.ProviderClient - - // this context is created by the plugin package, and is canceled when the - // plugin process ends. - ctx context.Context - - // schema stores the schema for this provider. This is used to properly - // serialize the state for requests. - mu sync.Mutex - schemas providers.GetSchemaResponse -} - -// getSchema is used internally to get the saved provider schema. The schema -// should have already been fetched from the provider, but we have to -// synchronize access to avoid being called concurrently with GetSchema. -func (p *GRPCProvider) getSchema() providers.GetSchemaResponse { - p.mu.Lock() - // unlock inline in case GetSchema needs to be called - if p.schemas.Provider.Block != nil { - p.mu.Unlock() - return p.schemas - } - p.mu.Unlock() - - // the schema should have been fetched already, but give it another shot - // just in case things are being called out of order. This may happen for - // tests. - schemas := p.GetSchema() - if schemas.Diagnostics.HasErrors() { - panic(schemas.Diagnostics.Err()) - } - - return schemas -} - -// getResourceSchema is a helper to extract the schema for a resource, and -// panics if the schema is not available. -func (p *GRPCProvider) getResourceSchema(name string) providers.Schema { - schema := p.getSchema() - resSchema, ok := schema.ResourceTypes[name] - if !ok { - panic("unknown resource type " + name) - } - return resSchema -} - -// gettDatasourceSchema is a helper to extract the schema for a datasource, and -// panics if that schema is not available. -func (p *GRPCProvider) getDatasourceSchema(name string) providers.Schema { - schema := p.getSchema() - dataSchema, ok := schema.DataSources[name] - if !ok { - panic("unknown data source " + name) - } - return dataSchema -} - -func (p *GRPCProvider) GetSchema() (resp providers.GetSchemaResponse) { - log.Printf("[TRACE] GRPCProvider: GetSchema") - p.mu.Lock() - defer p.mu.Unlock() - - if p.schemas.Provider.Block != nil { - return p.schemas - } - - resp.ResourceTypes = make(map[string]providers.Schema) - resp.DataSources = make(map[string]providers.Schema) - - // Some providers may generate quite large schemas, and the internal default - // grpc response size limit is 4MB. 64MB should cover most any use case, and - // if we get providers nearing that we may want to consider a finer-grained - // API to fetch individual resource schemas. - // Note: this option is marked as EXPERIMENTAL in the grpc API. - const maxRecvSize = 64 << 20 - protoResp, err := p.client.GetSchema(p.ctx, new(proto.GetProviderSchema_Request), grpc.MaxRecvMsgSizeCallOption{MaxRecvMsgSize: maxRecvSize}) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - if protoResp.Provider == nil { - resp.Diagnostics = resp.Diagnostics.Append(errors.New("missing provider schema")) - return resp - } - - resp.Provider = convert.ProtoToProviderSchema(protoResp.Provider) - - for name, res := range protoResp.ResourceSchemas { - resp.ResourceTypes[name] = convert.ProtoToProviderSchema(res) - } - - for name, data := range protoResp.DataSourceSchemas { - resp.DataSources[name] = convert.ProtoToProviderSchema(data) - } - - p.schemas = resp - - return resp -} - -func (p *GRPCProvider) PrepareProviderConfig(r providers.PrepareProviderConfigRequest) (resp providers.PrepareProviderConfigResponse) { - log.Printf("[TRACE] GRPCProvider: PrepareProviderConfig") - - schema := p.getSchema() - ty := schema.Provider.Block.ImpliedType() - - mp, err := msgpack.Marshal(r.Config, ty) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.PrepareProviderConfig_Request{ - Config: &proto.DynamicValue{Msgpack: mp}, - } - - protoResp, err := p.client.PrepareProviderConfig(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - config := cty.NullVal(ty) - if protoResp.PreparedConfig != nil { - config, err = msgpack.Unmarshal(protoResp.PreparedConfig.Msgpack, ty) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resp.PreparedConfig = config - - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - return resp -} - -func (p *GRPCProvider) ValidateResourceTypeConfig(r providers.ValidateResourceTypeConfigRequest) (resp providers.ValidateResourceTypeConfigResponse) { - log.Printf("[TRACE] GRPCProvider: ValidateResourceTypeConfig") - resourceSchema := p.getResourceSchema(r.TypeName) - - mp, err := msgpack.Marshal(r.Config, resourceSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ValidateResourceTypeConfig_Request{ - TypeName: r.TypeName, - Config: &proto.DynamicValue{Msgpack: mp}, - } - - protoResp, err := p.client.ValidateResourceTypeConfig(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - return resp -} - -func (p *GRPCProvider) ValidateDataSourceConfig(r providers.ValidateDataSourceConfigRequest) (resp providers.ValidateDataSourceConfigResponse) { - log.Printf("[TRACE] GRPCProvider: ValidateDataSourceConfig") - - dataSchema := p.getDatasourceSchema(r.TypeName) - - mp, err := msgpack.Marshal(r.Config, dataSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ValidateDataSourceConfig_Request{ - TypeName: r.TypeName, - Config: &proto.DynamicValue{Msgpack: mp}, - } - - protoResp, err := p.client.ValidateDataSourceConfig(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - return resp -} - -func (p *GRPCProvider) UpgradeResourceState(r providers.UpgradeResourceStateRequest) (resp providers.UpgradeResourceStateResponse) { - log.Printf("[TRACE] GRPCProvider: UpgradeResourceState") - - resSchema := p.getResourceSchema(r.TypeName) - - protoReq := &proto.UpgradeResourceState_Request{ - TypeName: r.TypeName, - Version: int64(r.Version), - RawState: &proto.RawState{ - Json: r.RawStateJSON, - Flatmap: r.RawStateFlatmap, - }, - } - - protoResp, err := p.client.UpgradeResourceState(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - state := cty.NullVal(resSchema.Block.ImpliedType()) - if protoResp.UpgradedState != nil { - state, err = msgpack.Unmarshal(protoResp.UpgradedState.Msgpack, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - - resp.UpgradedState = state - return resp -} - -func (p *GRPCProvider) Configure(r providers.ConfigureRequest) (resp providers.ConfigureResponse) { - log.Printf("[TRACE] GRPCProvider: Configure") - - schema := p.getSchema() - - var mp []byte - - // we don't have anything to marshal if there's no config - mp, err := msgpack.Marshal(r.Config, schema.Provider.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.Configure_Request{ - TerraformVersion: r.TerraformVersion, - Config: &proto.DynamicValue{ - Msgpack: mp, - }, - } - - protoResp, err := p.client.Configure(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - return resp -} - -func (p *GRPCProvider) Stop() error { - log.Printf("[TRACE] GRPCProvider: Stop") - - resp, err := p.client.Stop(p.ctx, new(proto.Stop_Request)) - if err != nil { - return err - } - - if resp.Error != "" { - return errors.New(resp.Error) - } - return nil -} - -func (p *GRPCProvider) ReadResource(r providers.ReadResourceRequest) (resp providers.ReadResourceResponse) { - log.Printf("[TRACE] GRPCProvider: ReadResource") - - resSchema := p.getResourceSchema(r.TypeName) - - mp, err := msgpack.Marshal(r.PriorState, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ReadResource_Request{ - TypeName: r.TypeName, - CurrentState: &proto.DynamicValue{Msgpack: mp}, - Private: r.Private, - } - - protoResp, err := p.client.ReadResource(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - state := cty.NullVal(resSchema.Block.ImpliedType()) - if protoResp.NewState != nil { - state, err = msgpack.Unmarshal(protoResp.NewState.Msgpack, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resp.NewState = state - resp.Private = protoResp.Private - - return resp -} - -func (p *GRPCProvider) PlanResourceChange(r providers.PlanResourceChangeRequest) (resp providers.PlanResourceChangeResponse) { - log.Printf("[TRACE] GRPCProvider: PlanResourceChange") - - resSchema := p.getResourceSchema(r.TypeName) - - priorMP, err := msgpack.Marshal(r.PriorState, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - configMP, err := msgpack.Marshal(r.Config, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - propMP, err := msgpack.Marshal(r.ProposedNewState, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.PlanResourceChange_Request{ - TypeName: r.TypeName, - PriorState: &proto.DynamicValue{Msgpack: priorMP}, - Config: &proto.DynamicValue{Msgpack: configMP}, - ProposedNewState: &proto.DynamicValue{Msgpack: propMP}, - PriorPrivate: r.PriorPrivate, - } - - protoResp, err := p.client.PlanResourceChange(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - state := cty.NullVal(resSchema.Block.ImpliedType()) - if protoResp.PlannedState != nil { - state, err = msgpack.Unmarshal(protoResp.PlannedState.Msgpack, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resp.PlannedState = state - - for _, p := range protoResp.RequiresReplace { - resp.RequiresReplace = append(resp.RequiresReplace, convert.AttributePathToPath(p)) - } - - resp.PlannedPrivate = protoResp.PlannedPrivate - - resp.LegacyTypeSystem = protoResp.LegacyTypeSystem - - return resp -} - -func (p *GRPCProvider) ApplyResourceChange(r providers.ApplyResourceChangeRequest) (resp providers.ApplyResourceChangeResponse) { - log.Printf("[TRACE] GRPCProvider: ApplyResourceChange") - - resSchema := p.getResourceSchema(r.TypeName) - - priorMP, err := msgpack.Marshal(r.PriorState, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - plannedMP, err := msgpack.Marshal(r.PlannedState, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - configMP, err := msgpack.Marshal(r.Config, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ApplyResourceChange_Request{ - TypeName: r.TypeName, - PriorState: &proto.DynamicValue{Msgpack: priorMP}, - PlannedState: &proto.DynamicValue{Msgpack: plannedMP}, - Config: &proto.DynamicValue{Msgpack: configMP}, - PlannedPrivate: r.PlannedPrivate, - } - - protoResp, err := p.client.ApplyResourceChange(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - resp.Private = protoResp.Private - - state := cty.NullVal(resSchema.Block.ImpliedType()) - if protoResp.NewState != nil { - state, err = msgpack.Unmarshal(protoResp.NewState.Msgpack, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resp.NewState = state - - resp.LegacyTypeSystem = protoResp.LegacyTypeSystem - - return resp -} - -func (p *GRPCProvider) ImportResourceState(r providers.ImportResourceStateRequest) (resp providers.ImportResourceStateResponse) { - log.Printf("[TRACE] GRPCProvider: ImportResourceState") - - protoReq := &proto.ImportResourceState_Request{ - TypeName: r.TypeName, - Id: r.ID, - } - - protoResp, err := p.client.ImportResourceState(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - for _, imported := range protoResp.ImportedResources { - resource := providers.ImportedResource{ - TypeName: imported.TypeName, - Private: imported.Private, - } - - resSchema := p.getResourceSchema(resource.TypeName) - state := cty.NullVal(resSchema.Block.ImpliedType()) - if imported.State != nil { - state, err = msgpack.Unmarshal(imported.State.Msgpack, resSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resource.State = state - resp.ImportedResources = append(resp.ImportedResources, resource) - } - - return resp -} - -func (p *GRPCProvider) ReadDataSource(r providers.ReadDataSourceRequest) (resp providers.ReadDataSourceResponse) { - log.Printf("[TRACE] GRPCProvider: ReadDataSource") - - dataSchema := p.getDatasourceSchema(r.TypeName) - - config, err := msgpack.Marshal(r.Config, dataSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ReadDataSource_Request{ - TypeName: r.TypeName, - Config: &proto.DynamicValue{ - Msgpack: config, - }, - } - - protoResp, err := p.client.ReadDataSource(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - state := cty.NullVal(dataSchema.Block.ImpliedType()) - if protoResp.State != nil { - state, err = msgpack.Unmarshal(protoResp.State.Msgpack, dataSchema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - } - resp.State = state - - return resp -} - -// closing the grpc connection is final, and terraform will call it at the end of every phase. -func (p *GRPCProvider) Close() error { - log.Printf("[TRACE] GRPCProvider: Close") - - // Make sure to stop the server if we're not running within go-plugin. - if p.TestServer != nil { - p.TestServer.Stop() - } - - // Check this since it's not automatically inserted during plugin creation. - // It's currently only inserted by the command package, because that is - // where the factory is built and is the only point with access to the - // plugin.Client. - if p.PluginClient == nil { - log.Println("[DEBUG] provider has no plugin.Client") - return nil - } - - p.PluginClient.Kill() - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/grpc_provisioner.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/grpc_provisioner.go deleted file mode 100644 index c0e6f549abe..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/grpc_provisioner.go +++ /dev/null @@ -1,178 +0,0 @@ -package plugin - -import ( - "context" - "errors" - "io" - "log" - "sync" - - plugin "github.com/hashicorp/go-plugin" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/plugin/convert" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" - proto "github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/msgpack" - "google.golang.org/grpc" -) - -// GRPCProvisionerPlugin is the plugin.GRPCPlugin implementation. -type GRPCProvisionerPlugin struct { - plugin.Plugin - GRPCProvisioner func() proto.ProvisionerServer -} - -func (p *GRPCProvisionerPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { - return &GRPCProvisioner{ - client: proto.NewProvisionerClient(c), - ctx: ctx, - }, nil -} - -func (p *GRPCProvisionerPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error { - proto.RegisterProvisionerServer(s, p.GRPCProvisioner()) - return nil -} - -// provisioners.Interface grpc implementation -type GRPCProvisioner struct { - // PluginClient provides a reference to the plugin.Client which controls the plugin process. - // This allows the GRPCProvider a way to shutdown the plugin process. - PluginClient *plugin.Client - - client proto.ProvisionerClient - ctx context.Context - - // Cache the schema since we need it for serialization in each method call. - mu sync.Mutex - schema *configschema.Block -} - -func (p *GRPCProvisioner) GetSchema() (resp provisioners.GetSchemaResponse) { - p.mu.Lock() - defer p.mu.Unlock() - - if p.schema != nil { - return provisioners.GetSchemaResponse{ - Provisioner: p.schema, - } - } - - protoResp, err := p.client.GetSchema(p.ctx, new(proto.GetProvisionerSchema_Request)) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - - if protoResp.Provisioner == nil { - resp.Diagnostics = resp.Diagnostics.Append(errors.New("missing provisioner schema")) - return resp - } - - resp.Provisioner = convert.ProtoToConfigSchema(protoResp.Provisioner.Block) - - p.schema = resp.Provisioner - - return resp -} - -func (p *GRPCProvisioner) ValidateProvisionerConfig(r provisioners.ValidateProvisionerConfigRequest) (resp provisioners.ValidateProvisionerConfigResponse) { - schema := p.GetSchema() - if schema.Diagnostics.HasErrors() { - resp.Diagnostics = resp.Diagnostics.Append(schema.Diagnostics) - return resp - } - - mp, err := msgpack.Marshal(r.Config, schema.Provisioner.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ValidateProvisionerConfig_Request{ - Config: &proto.DynamicValue{Msgpack: mp}, - } - protoResp, err := p.client.ValidateProvisionerConfig(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(protoResp.Diagnostics)) - return resp -} - -func (p *GRPCProvisioner) ProvisionResource(r provisioners.ProvisionResourceRequest) (resp provisioners.ProvisionResourceResponse) { - schema := p.GetSchema() - if schema.Diagnostics.HasErrors() { - resp.Diagnostics = resp.Diagnostics.Append(schema.Diagnostics) - return resp - } - - mp, err := msgpack.Marshal(r.Config, schema.Provisioner.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - // connection is always assumed to be a simple string map - connMP, err := msgpack.Marshal(r.Connection, cty.Map(cty.String)) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - protoReq := &proto.ProvisionResource_Request{ - Config: &proto.DynamicValue{Msgpack: mp}, - Connection: &proto.DynamicValue{Msgpack: connMP}, - } - - outputClient, err := p.client.ProvisionResource(p.ctx, protoReq) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - - for { - rcv, err := outputClient.Recv() - if rcv != nil { - r.UIOutput.Output(rcv.Output) - } - if err != nil { - if err != io.EOF { - resp.Diagnostics = resp.Diagnostics.Append(err) - } - break - } - - if len(rcv.Diagnostics) > 0 { - resp.Diagnostics = resp.Diagnostics.Append(convert.ProtoToDiagnostics(rcv.Diagnostics)) - break - } - } - - return resp -} - -func (p *GRPCProvisioner) Stop() error { - protoResp, err := p.client.Stop(p.ctx, &proto.Stop_Request{}) - if err != nil { - return err - } - if protoResp.Error != "" { - return errors.New(protoResp.Error) - } - return nil -} - -func (p *GRPCProvisioner) Close() error { - // check this since it's not automatically inserted during plugin creation - if p.PluginClient == nil { - log.Println("[DEBUG] provider has no plugin.Client") - return nil - } - - p.PluginClient.Kill() - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/plugin.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/plugin.go deleted file mode 100644 index e4fb577619c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/plugin.go +++ /dev/null @@ -1,14 +0,0 @@ -package plugin - -import ( - "github.com/hashicorp/go-plugin" -) - -// See serve.go for serving plugins - -var VersionedPlugins = map[int]plugin.PluginSet{ - 5: { - "provider": &GRPCProviderPlugin{}, - "provisioner": &GRPCProvisionerPlugin{}, - }, -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/resource_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/resource_provider.go deleted file mode 100644 index bfd62e2e9ba..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/resource_provider.go +++ /dev/null @@ -1,620 +0,0 @@ -package plugin - -import ( - "net/rpc" - - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -// ResourceProviderPlugin is the plugin.Plugin implementation. -type ResourceProviderPlugin struct { - ResourceProvider func() terraform.ResourceProvider -} - -func (p *ResourceProviderPlugin) Server(b *plugin.MuxBroker) (interface{}, error) { - return &ResourceProviderServer{ - Broker: b, - Provider: p.ResourceProvider(), - }, nil -} - -func (p *ResourceProviderPlugin) Client( - b *plugin.MuxBroker, c *rpc.Client) (interface{}, error) { - return &ResourceProvider{Broker: b, Client: c}, nil -} - -// ResourceProvider is an implementation of terraform.ResourceProvider -// that communicates over RPC. -type ResourceProvider struct { - Broker *plugin.MuxBroker - Client *rpc.Client -} - -func (p *ResourceProvider) Stop() error { - var resp ResourceProviderStopResponse - err := p.Client.Call("Plugin.Stop", new(interface{}), &resp) - if err != nil { - return err - } - if resp.Error != nil { - err = resp.Error - } - - return err -} - -func (p *ResourceProvider) GetSchema(req *terraform.ProviderSchemaRequest) (*terraform.ProviderSchema, error) { - var result ResourceProviderGetSchemaResponse - args := &ResourceProviderGetSchemaArgs{ - Req: req, - } - - err := p.Client.Call("Plugin.GetSchema", args, &result) - if err != nil { - return nil, err - } - - if result.Error != nil { - err = result.Error - } - - return result.Schema, err -} - -func (p *ResourceProvider) Input( - input terraform.UIInput, - c *terraform.ResourceConfig) (*terraform.ResourceConfig, error) { - id := p.Broker.NextId() - go p.Broker.AcceptAndServe(id, &UIInputServer{ - UIInput: input, - }) - - var resp ResourceProviderInputResponse - args := ResourceProviderInputArgs{ - InputId: id, - Config: c, - } - - err := p.Client.Call("Plugin.Input", &args, &resp) - if err != nil { - return nil, err - } - if resp.Error != nil { - err = resp.Error - return nil, err - } - - return resp.Config, nil -} - -func (p *ResourceProvider) Validate(c *terraform.ResourceConfig) ([]string, []error) { - var resp ResourceProviderValidateResponse - args := ResourceProviderValidateArgs{ - Config: c, - } - - err := p.Client.Call("Plugin.Validate", &args, &resp) - if err != nil { - return nil, []error{err} - } - - var errs []error - if len(resp.Errors) > 0 { - errs = make([]error, len(resp.Errors)) - for i, err := range resp.Errors { - errs[i] = err - } - } - - return resp.Warnings, errs -} - -func (p *ResourceProvider) ValidateResource( - t string, c *terraform.ResourceConfig) ([]string, []error) { - var resp ResourceProviderValidateResourceResponse - args := ResourceProviderValidateResourceArgs{ - Config: c, - Type: t, - } - - err := p.Client.Call("Plugin.ValidateResource", &args, &resp) - if err != nil { - return nil, []error{err} - } - - var errs []error - if len(resp.Errors) > 0 { - errs = make([]error, len(resp.Errors)) - for i, err := range resp.Errors { - errs[i] = err - } - } - - return resp.Warnings, errs -} - -func (p *ResourceProvider) Configure(c *terraform.ResourceConfig) error { - var resp ResourceProviderConfigureResponse - err := p.Client.Call("Plugin.Configure", c, &resp) - if err != nil { - return err - } - if resp.Error != nil { - err = resp.Error - } - - return err -} - -func (p *ResourceProvider) Apply( - info *terraform.InstanceInfo, - s *terraform.InstanceState, - d *terraform.InstanceDiff) (*terraform.InstanceState, error) { - var resp ResourceProviderApplyResponse - args := &ResourceProviderApplyArgs{ - Info: info, - State: s, - Diff: d, - } - - err := p.Client.Call("Plugin.Apply", args, &resp) - if err != nil { - return nil, err - } - if resp.Error != nil { - err = resp.Error - } - - return resp.State, err -} - -func (p *ResourceProvider) Diff( - info *terraform.InstanceInfo, - s *terraform.InstanceState, - c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) { - var resp ResourceProviderDiffResponse - args := &ResourceProviderDiffArgs{ - Info: info, - State: s, - Config: c, - } - err := p.Client.Call("Plugin.Diff", args, &resp) - if err != nil { - return nil, err - } - if resp.Error != nil { - err = resp.Error - } - - return resp.Diff, err -} - -func (p *ResourceProvider) ValidateDataSource( - t string, c *terraform.ResourceConfig) ([]string, []error) { - var resp ResourceProviderValidateResourceResponse - args := ResourceProviderValidateResourceArgs{ - Config: c, - Type: t, - } - - err := p.Client.Call("Plugin.ValidateDataSource", &args, &resp) - if err != nil { - return nil, []error{err} - } - - var errs []error - if len(resp.Errors) > 0 { - errs = make([]error, len(resp.Errors)) - for i, err := range resp.Errors { - errs[i] = err - } - } - - return resp.Warnings, errs -} - -func (p *ResourceProvider) Refresh( - info *terraform.InstanceInfo, - s *terraform.InstanceState) (*terraform.InstanceState, error) { - var resp ResourceProviderRefreshResponse - args := &ResourceProviderRefreshArgs{ - Info: info, - State: s, - } - - err := p.Client.Call("Plugin.Refresh", args, &resp) - if err != nil { - return nil, err - } - if resp.Error != nil { - err = resp.Error - } - - return resp.State, err -} - -func (p *ResourceProvider) ImportState( - info *terraform.InstanceInfo, - id string) ([]*terraform.InstanceState, error) { - var resp ResourceProviderImportStateResponse - args := &ResourceProviderImportStateArgs{ - Info: info, - Id: id, - } - - err := p.Client.Call("Plugin.ImportState", args, &resp) - if err != nil { - return nil, err - } - if resp.Error != nil { - err = resp.Error - } - - return resp.State, err -} - -func (p *ResourceProvider) Resources() []terraform.ResourceType { - var result []terraform.ResourceType - - err := p.Client.Call("Plugin.Resources", new(interface{}), &result) - if err != nil { - // TODO: panic, log, what? - return nil - } - - return result -} - -func (p *ResourceProvider) ReadDataDiff( - info *terraform.InstanceInfo, - c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) { - var resp ResourceProviderReadDataDiffResponse - args := &ResourceProviderReadDataDiffArgs{ - Info: info, - Config: c, - } - - err := p.Client.Call("Plugin.ReadDataDiff", args, &resp) - if err != nil { - return nil, err - } - if resp.Error != nil { - err = resp.Error - } - - return resp.Diff, err -} - -func (p *ResourceProvider) ReadDataApply( - info *terraform.InstanceInfo, - d *terraform.InstanceDiff) (*terraform.InstanceState, error) { - var resp ResourceProviderReadDataApplyResponse - args := &ResourceProviderReadDataApplyArgs{ - Info: info, - Diff: d, - } - - err := p.Client.Call("Plugin.ReadDataApply", args, &resp) - if err != nil { - return nil, err - } - if resp.Error != nil { - err = resp.Error - } - - return resp.State, err -} - -func (p *ResourceProvider) DataSources() []terraform.DataSource { - var result []terraform.DataSource - - err := p.Client.Call("Plugin.DataSources", new(interface{}), &result) - if err != nil { - // TODO: panic, log, what? - return nil - } - - return result -} - -func (p *ResourceProvider) Close() error { - return p.Client.Close() -} - -// ResourceProviderServer is a net/rpc compatible structure for serving -// a ResourceProvider. This should not be used directly. -type ResourceProviderServer struct { - Broker *plugin.MuxBroker - Provider terraform.ResourceProvider -} - -type ResourceProviderStopResponse struct { - Error *plugin.BasicError -} - -type ResourceProviderGetSchemaArgs struct { - Req *terraform.ProviderSchemaRequest -} - -type ResourceProviderGetSchemaResponse struct { - Schema *terraform.ProviderSchema - Error *plugin.BasicError -} - -type ResourceProviderConfigureResponse struct { - Error *plugin.BasicError -} - -type ResourceProviderInputArgs struct { - InputId uint32 - Config *terraform.ResourceConfig -} - -type ResourceProviderInputResponse struct { - Config *terraform.ResourceConfig - Error *plugin.BasicError -} - -type ResourceProviderApplyArgs struct { - Info *terraform.InstanceInfo - State *terraform.InstanceState - Diff *terraform.InstanceDiff -} - -type ResourceProviderApplyResponse struct { - State *terraform.InstanceState - Error *plugin.BasicError -} - -type ResourceProviderDiffArgs struct { - Info *terraform.InstanceInfo - State *terraform.InstanceState - Config *terraform.ResourceConfig -} - -type ResourceProviderDiffResponse struct { - Diff *terraform.InstanceDiff - Error *plugin.BasicError -} - -type ResourceProviderRefreshArgs struct { - Info *terraform.InstanceInfo - State *terraform.InstanceState -} - -type ResourceProviderRefreshResponse struct { - State *terraform.InstanceState - Error *plugin.BasicError -} - -type ResourceProviderImportStateArgs struct { - Info *terraform.InstanceInfo - Id string -} - -type ResourceProviderImportStateResponse struct { - State []*terraform.InstanceState - Error *plugin.BasicError -} - -type ResourceProviderReadDataApplyArgs struct { - Info *terraform.InstanceInfo - Diff *terraform.InstanceDiff -} - -type ResourceProviderReadDataApplyResponse struct { - State *terraform.InstanceState - Error *plugin.BasicError -} - -type ResourceProviderReadDataDiffArgs struct { - Info *terraform.InstanceInfo - Config *terraform.ResourceConfig -} - -type ResourceProviderReadDataDiffResponse struct { - Diff *terraform.InstanceDiff - Error *plugin.BasicError -} - -type ResourceProviderValidateArgs struct { - Config *terraform.ResourceConfig -} - -type ResourceProviderValidateResponse struct { - Warnings []string - Errors []*plugin.BasicError -} - -type ResourceProviderValidateResourceArgs struct { - Config *terraform.ResourceConfig - Type string -} - -type ResourceProviderValidateResourceResponse struct { - Warnings []string - Errors []*plugin.BasicError -} - -func (s *ResourceProviderServer) Stop( - _ interface{}, - reply *ResourceProviderStopResponse) error { - err := s.Provider.Stop() - *reply = ResourceProviderStopResponse{ - Error: plugin.NewBasicError(err), - } - - return nil -} - -func (s *ResourceProviderServer) GetSchema( - args *ResourceProviderGetSchemaArgs, - result *ResourceProviderGetSchemaResponse, -) error { - schema, err := s.Provider.GetSchema(args.Req) - result.Schema = schema - if err != nil { - result.Error = plugin.NewBasicError(err) - } - return nil -} - -func (s *ResourceProviderServer) Input( - args *ResourceProviderInputArgs, - reply *ResourceProviderInputResponse) error { - conn, err := s.Broker.Dial(args.InputId) - if err != nil { - *reply = ResourceProviderInputResponse{ - Error: plugin.NewBasicError(err), - } - return nil - } - client := rpc.NewClient(conn) - defer client.Close() - - input := &UIInput{Client: client} - - config, err := s.Provider.Input(input, args.Config) - *reply = ResourceProviderInputResponse{ - Config: config, - Error: plugin.NewBasicError(err), - } - - return nil -} - -func (s *ResourceProviderServer) Validate( - args *ResourceProviderValidateArgs, - reply *ResourceProviderValidateResponse) error { - warns, errs := s.Provider.Validate(args.Config) - berrs := make([]*plugin.BasicError, len(errs)) - for i, err := range errs { - berrs[i] = plugin.NewBasicError(err) - } - *reply = ResourceProviderValidateResponse{ - Warnings: warns, - Errors: berrs, - } - return nil -} - -func (s *ResourceProviderServer) ValidateResource( - args *ResourceProviderValidateResourceArgs, - reply *ResourceProviderValidateResourceResponse) error { - warns, errs := s.Provider.ValidateResource(args.Type, args.Config) - berrs := make([]*plugin.BasicError, len(errs)) - for i, err := range errs { - berrs[i] = plugin.NewBasicError(err) - } - *reply = ResourceProviderValidateResourceResponse{ - Warnings: warns, - Errors: berrs, - } - return nil -} - -func (s *ResourceProviderServer) Configure( - config *terraform.ResourceConfig, - reply *ResourceProviderConfigureResponse) error { - err := s.Provider.Configure(config) - *reply = ResourceProviderConfigureResponse{ - Error: plugin.NewBasicError(err), - } - return nil -} - -func (s *ResourceProviderServer) Apply( - args *ResourceProviderApplyArgs, - result *ResourceProviderApplyResponse) error { - state, err := s.Provider.Apply(args.Info, args.State, args.Diff) - *result = ResourceProviderApplyResponse{ - State: state, - Error: plugin.NewBasicError(err), - } - return nil -} - -func (s *ResourceProviderServer) Diff( - args *ResourceProviderDiffArgs, - result *ResourceProviderDiffResponse) error { - diff, err := s.Provider.Diff(args.Info, args.State, args.Config) - *result = ResourceProviderDiffResponse{ - Diff: diff, - Error: plugin.NewBasicError(err), - } - return nil -} - -func (s *ResourceProviderServer) Refresh( - args *ResourceProviderRefreshArgs, - result *ResourceProviderRefreshResponse) error { - newState, err := s.Provider.Refresh(args.Info, args.State) - *result = ResourceProviderRefreshResponse{ - State: newState, - Error: plugin.NewBasicError(err), - } - return nil -} - -func (s *ResourceProviderServer) ImportState( - args *ResourceProviderImportStateArgs, - result *ResourceProviderImportStateResponse) error { - states, err := s.Provider.ImportState(args.Info, args.Id) - *result = ResourceProviderImportStateResponse{ - State: states, - Error: plugin.NewBasicError(err), - } - return nil -} - -func (s *ResourceProviderServer) Resources( - nothing interface{}, - result *[]terraform.ResourceType) error { - *result = s.Provider.Resources() - return nil -} - -func (s *ResourceProviderServer) ValidateDataSource( - args *ResourceProviderValidateResourceArgs, - reply *ResourceProviderValidateResourceResponse) error { - warns, errs := s.Provider.ValidateDataSource(args.Type, args.Config) - berrs := make([]*plugin.BasicError, len(errs)) - for i, err := range errs { - berrs[i] = plugin.NewBasicError(err) - } - *reply = ResourceProviderValidateResourceResponse{ - Warnings: warns, - Errors: berrs, - } - return nil -} - -func (s *ResourceProviderServer) ReadDataDiff( - args *ResourceProviderReadDataDiffArgs, - result *ResourceProviderReadDataDiffResponse) error { - diff, err := s.Provider.ReadDataDiff(args.Info, args.Config) - *result = ResourceProviderReadDataDiffResponse{ - Diff: diff, - Error: plugin.NewBasicError(err), - } - return nil -} - -func (s *ResourceProviderServer) ReadDataApply( - args *ResourceProviderReadDataApplyArgs, - result *ResourceProviderReadDataApplyResponse) error { - newState, err := s.Provider.ReadDataApply(args.Info, args.Diff) - *result = ResourceProviderReadDataApplyResponse{ - State: newState, - Error: plugin.NewBasicError(err), - } - return nil -} - -func (s *ResourceProviderServer) DataSources( - nothing interface{}, - result *[]terraform.DataSource) error { - *result = s.Provider.DataSources() - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/serve.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/serve.go deleted file mode 100644 index cbe9fc63693..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/serve.go +++ /dev/null @@ -1,100 +0,0 @@ -package plugin - -import ( - "github.com/hashicorp/go-plugin" - grpcplugin "github.com/hashicorp/terraform-plugin-sdk/internal/helper/plugin" - proto "github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5" - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -const ( - // The constants below are the names of the plugins that can be dispensed - // from the plugin server. - ProviderPluginName = "provider" - - // DefaultProtocolVersion is the protocol version assumed for legacy clients that don't specify - // a particular version during their handshake. This is the version used when Terraform 0.10 - // and 0.11 launch plugins that were built with support for both versions 4 and 5, and must - // stay unchanged at 4 until we intentionally build plugins that are not compatible with 0.10 and - // 0.11. - DefaultProtocolVersion = 4 -) - -// Handshake is the HandshakeConfig used to configure clients and servers. -var Handshake = plugin.HandshakeConfig{ - // The ProtocolVersion is the version that must match between TF core - // and TF plugins. This should be bumped whenever a change happens in - // one or the other that makes it so that they can't safely communicate. - // This could be adding a new interface value, it could be how - // helper/schema computes diffs, etc. - ProtocolVersion: DefaultProtocolVersion, - - // The magic cookie values should NEVER be changed. - MagicCookieKey: "TF_PLUGIN_MAGIC_COOKIE", - MagicCookieValue: "d602bf8f470bc67ca7faa0386276bbdd4330efaf76d1a219cb4d6991ca9872b2", -} - -type ProviderFunc func() terraform.ResourceProvider -type GRPCProviderFunc func() proto.ProviderServer - -// ServeOpts are the configurations to serve a plugin. -type ServeOpts struct { - ProviderFunc ProviderFunc - - // Wrapped versions of the above plugins will automatically shimmed and - // added to the GRPC functions when possible. - GRPCProviderFunc GRPCProviderFunc -} - -// Serve serves a plugin. This function never returns and should be the final -// function called in the main function of the plugin. -func Serve(opts *ServeOpts) { - // since the plugins may not yet be aware of the new protocol, we - // automatically wrap the plugins in the grpc shims. - if opts.GRPCProviderFunc == nil && opts.ProviderFunc != nil { - provider := grpcplugin.NewGRPCProviderServerShim(opts.ProviderFunc()) - // this is almost always going to be a *schema.Provider, but check that - // we got back a valid provider just in case. - if provider != nil { - opts.GRPCProviderFunc = func() proto.ProviderServer { - return provider - } - } - } - - plugin.Serve(&plugin.ServeConfig{ - HandshakeConfig: Handshake, - VersionedPlugins: pluginSet(opts), - GRPCServer: plugin.DefaultGRPCServer, - }) -} - -// pluginMap returns the legacy map[string]plugin.Plugin to use for configuring -// a plugin server or client. -func legacyPluginMap(opts *ServeOpts) map[string]plugin.Plugin { - return map[string]plugin.Plugin{ - "provider": &ResourceProviderPlugin{ - ResourceProvider: opts.ProviderFunc, - }, - } -} - -func pluginSet(opts *ServeOpts) map[int]plugin.PluginSet { - // Set the legacy netrpc plugins at version 4. - // The oldest version is returned in when executed by a legacy go-plugin - // client. - plugins := map[int]plugin.PluginSet{ - 4: legacyPluginMap(opts), - } - - // add the new protocol versions if they're configured - if opts.GRPCProviderFunc != nil { - plugins[5] = plugin.PluginSet{} - if opts.GRPCProviderFunc != nil { - plugins[5]["provider"] = &GRPCProviderPlugin{ - GRPCProvider: opts.GRPCProviderFunc, - } - } - } - return plugins -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/ui_input.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/ui_input.go deleted file mode 100644 index b24b03ebfe1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/ui_input.go +++ /dev/null @@ -1,52 +0,0 @@ -package plugin - -import ( - "context" - "net/rpc" - - "github.com/hashicorp/go-plugin" - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -// UIInput is an implementation of terraform.UIInput that communicates -// over RPC. -type UIInput struct { - Client *rpc.Client -} - -func (i *UIInput) Input(ctx context.Context, opts *terraform.InputOpts) (string, error) { - var resp UIInputInputResponse - err := i.Client.Call("Plugin.Input", opts, &resp) - if err != nil { - return "", err - } - if resp.Error != nil { - err = resp.Error - return "", err - } - - return resp.Value, nil -} - -type UIInputInputResponse struct { - Value string - Error *plugin.BasicError -} - -// UIInputServer is a net/rpc compatible structure for serving -// a UIInputServer. This should not be used directly. -type UIInputServer struct { - UIInput terraform.UIInput -} - -func (s *UIInputServer) Input( - opts *terraform.InputOpts, - reply *UIInputInputResponse) error { - value, err := s.UIInput.Input(context.Background(), opts) - *reply = UIInputInputResponse{ - Value: value, - Error: plugin.NewBasicError(err), - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/ui_output.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/ui_output.go deleted file mode 100644 index 07c13d03aa4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/ui_output.go +++ /dev/null @@ -1,29 +0,0 @@ -package plugin - -import ( - "net/rpc" - - "github.com/hashicorp/terraform-plugin-sdk/terraform" -) - -// UIOutput is an implementatin of terraform.UIOutput that communicates -// over RPC. -type UIOutput struct { - Client *rpc.Client -} - -func (o *UIOutput) Output(v string) { - o.Client.Call("Plugin.Output", v, new(interface{})) -} - -// UIOutputServer is the RPC server for serving UIOutput. -type UIOutputServer struct { - UIOutput terraform.UIOutput -} - -func (s *UIOutputServer) Output( - v string, - reply *interface{}) error { - s.UIOutput.Output(v) - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context.go deleted file mode 100644 index eb05c68ae30..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context.go +++ /dev/null @@ -1,882 +0,0 @@ -package terraform - -import ( - "bytes" - "context" - "fmt" - "log" - "sync" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" -) - -// InputMode defines what sort of input will be asked for when Input -// is called on Context. -type InputMode byte - -const ( - // InputModeVar asks for all variables - InputModeVar InputMode = 1 << iota - - // InputModeVarUnset asks for variables which are not set yet. - // InputModeVar must be set for this to have an effect. - InputModeVarUnset - - // InputModeProvider asks for provider variables - InputModeProvider - - // InputModeStd is the standard operating mode and asks for both variables - // and providers. - InputModeStd = InputModeVar | InputModeProvider -) - -// ContextOpts are the user-configurable options to create a context with -// NewContext. -type ContextOpts struct { - Config *configs.Config - Changes *plans.Changes - State *states.State - Targets []addrs.Targetable - Variables InputValues - Meta *ContextMeta - Destroy bool - - Hooks []Hook - Parallelism int - ProviderResolver providers.Resolver - Provisioners map[string]ProvisionerFactory - - // If non-nil, will apply as additional constraints on the provider - // plugins that will be requested from the provider resolver. - ProviderSHA256s map[string][]byte - SkipProviderVerify bool - - UIInput UIInput -} - -// ContextMeta is metadata about the running context. This is information -// that this package or structure cannot determine on its own but exposes -// into Terraform in various ways. This must be provided by the Context -// initializer. -type ContextMeta struct { - Env string // Env is the state environment -} - -// Context represents all the context that Terraform needs in order to -// perform operations on infrastructure. This structure is built using -// NewContext. -type Context struct { - config *configs.Config - changes *plans.Changes - state *states.State - targets []addrs.Targetable - variables InputValues - meta *ContextMeta - destroy bool - - hooks []Hook - components contextComponentFactory - schemas *Schemas - sh *stopHook - uiInput UIInput - - l sync.Mutex // Lock acquired during any task - parallelSem Semaphore - providerInputConfig map[string]map[string]cty.Value - providerSHA256s map[string][]byte - runCond *sync.Cond - runContext context.Context - runContextCancel context.CancelFunc - shadowErr error -} - -// (additional methods on Context can be found in context_*.go files.) - -// NewContext creates a new Context structure. -// -// Once a Context is created, the caller must not access or mutate any of -// the objects referenced (directly or indirectly) by the ContextOpts fields. -// -// If the returned diagnostics contains errors then the resulting context is -// invalid and must not be used. -func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { - log.Printf("[TRACE] terraform.NewContext: starting") - diags := CheckCoreVersionRequirements(opts.Config) - // If version constraints are not met then we'll bail early since otherwise - // we're likely to just see a bunch of other errors related to - // incompatibilities, which could be overwhelming for the user. - if diags.HasErrors() { - return nil, diags - } - - // Copy all the hooks and add our stop hook. We don't append directly - // to the Config so that we're not modifying that in-place. - sh := new(stopHook) - hooks := make([]Hook, len(opts.Hooks)+1) - copy(hooks, opts.Hooks) - hooks[len(opts.Hooks)] = sh - - state := opts.State - if state == nil { - state = states.NewState() - } - - // Determine parallelism, default to 10. We do this both to limit - // CPU pressure but also to have an extra guard against rate throttling - // from providers. - par := opts.Parallelism - if par == 0 { - par = 10 - } - - // Set up the variables in the following sequence: - // 0 - Take default values from the configuration - // 1 - Take values from TF_VAR_x environment variables - // 2 - Take values specified in -var flags, overriding values - // set by environment variables if necessary. This includes - // values taken from -var-file in addition. - var variables InputValues - if opts.Config != nil { - // Default variables from the configuration seed our map. - variables = DefaultVariableValues(opts.Config.Module.Variables) - } - // Variables provided by the caller (from CLI, environment, etc) can - // override the defaults. - variables = variables.Override(opts.Variables) - - // Bind available provider plugins to the constraints in config - var providerFactories map[string]providers.Factory - if opts.ProviderResolver != nil { - deps := ConfigTreeDependencies(opts.Config, state) - reqd := deps.AllPluginRequirements() - if opts.ProviderSHA256s != nil && !opts.SkipProviderVerify { - reqd.LockExecutables(opts.ProviderSHA256s) - } - log.Printf("[TRACE] terraform.NewContext: resolving provider version selections") - - var providerDiags tfdiags.Diagnostics - providerFactories, providerDiags = resourceProviderFactories(opts.ProviderResolver, reqd) - diags = diags.Append(providerDiags) - - if diags.HasErrors() { - return nil, diags - } - } else { - providerFactories = make(map[string]providers.Factory) - } - - components := &basicComponentFactory{ - providers: providerFactories, - provisioners: opts.Provisioners, - } - - log.Printf("[TRACE] terraform.NewContext: loading provider schemas") - schemas, err := LoadSchemas(opts.Config, opts.State, components) - if err != nil { - diags = diags.Append(err) - return nil, diags - } - - changes := opts.Changes - if changes == nil { - changes = plans.NewChanges() - } - - config := opts.Config - if config == nil { - config = configs.NewEmptyConfig() - } - - log.Printf("[TRACE] terraform.NewContext: complete") - - return &Context{ - components: components, - schemas: schemas, - destroy: opts.Destroy, - changes: changes, - hooks: hooks, - meta: opts.Meta, - config: config, - state: state, - targets: opts.Targets, - uiInput: opts.UIInput, - variables: variables, - - parallelSem: NewSemaphore(par), - providerInputConfig: make(map[string]map[string]cty.Value), - providerSHA256s: opts.ProviderSHA256s, - sh: sh, - }, nil -} - -func (c *Context) Schemas() *Schemas { - return c.schemas -} - -type ContextGraphOpts struct { - // If true, validates the graph structure (checks for cycles). - Validate bool - - // Legacy graphs only: won't prune the graph - Verbose bool -} - -// Graph returns the graph used for the given operation type. -// -// The most extensive or complex graph type is GraphTypePlan. -func (c *Context) Graph(typ GraphType, opts *ContextGraphOpts) (*Graph, tfdiags.Diagnostics) { - if opts == nil { - opts = &ContextGraphOpts{Validate: true} - } - - log.Printf("[INFO] terraform: building graph: %s", typ) - switch typ { - case GraphTypeApply: - return (&ApplyGraphBuilder{ - Config: c.config, - Changes: c.changes, - State: c.state, - Components: c.components, - Schemas: c.schemas, - Targets: c.targets, - Destroy: c.destroy, - Validate: opts.Validate, - }).Build(addrs.RootModuleInstance) - - case GraphTypeValidate: - // The validate graph is just a slightly modified plan graph - fallthrough - case GraphTypePlan: - // Create the plan graph builder - p := &PlanGraphBuilder{ - Config: c.config, - State: c.state, - Components: c.components, - Schemas: c.schemas, - Targets: c.targets, - Validate: opts.Validate, - } - - // Some special cases for other graph types shared with plan currently - var b GraphBuilder = p - switch typ { - case GraphTypeValidate: - b = ValidateGraphBuilder(p) - } - - return b.Build(addrs.RootModuleInstance) - - case GraphTypePlanDestroy: - return (&DestroyPlanGraphBuilder{ - Config: c.config, - State: c.state, - Components: c.components, - Schemas: c.schemas, - Targets: c.targets, - Validate: opts.Validate, - }).Build(addrs.RootModuleInstance) - - case GraphTypeRefresh: - return (&RefreshGraphBuilder{ - Config: c.config, - State: c.state, - Components: c.components, - Schemas: c.schemas, - Targets: c.targets, - Validate: opts.Validate, - }).Build(addrs.RootModuleInstance) - - case GraphTypeEval: - return (&EvalGraphBuilder{ - Config: c.config, - State: c.state, - Components: c.components, - Schemas: c.schemas, - }).Build(addrs.RootModuleInstance) - - default: - // Should never happen, because the above is exhaustive for all graph types. - panic(fmt.Errorf("unsupported graph type %s", typ)) - } -} - -// ShadowError returns any errors caught during a shadow operation. -// -// A shadow operation is an operation run in parallel to a real operation -// that performs the same tasks using new logic on copied state. The results -// are compared to ensure that the new logic works the same as the old logic. -// The shadow never affects the real operation or return values. -// -// The result of the shadow operation are only available through this function -// call after a real operation is complete. -// -// For API consumers of Context, you can safely ignore this function -// completely if you have no interest in helping report experimental feature -// errors to Terraform maintainers. Otherwise, please call this function -// after every operation and report this to the user. -// -// IMPORTANT: Shadow errors are _never_ critical: they _never_ affect -// the real state or result of a real operation. They are purely informational -// to assist in future Terraform versions being more stable. Please message -// this effectively to the end user. -// -// This must be called only when no other operation is running (refresh, -// plan, etc.). The result can be used in parallel to any other operation -// running. -func (c *Context) ShadowError() error { - return c.shadowErr -} - -// State returns a copy of the current state associated with this context. -// -// This cannot safely be called in parallel with any other Context function. -func (c *Context) State() *states.State { - return c.state.DeepCopy() -} - -// Eval produces a scope in which expressions can be evaluated for -// the given module path. -// -// This method must first evaluate any ephemeral values (input variables, local -// values, and output values) in the configuration. These ephemeral values are -// not included in the persisted state, so they must be re-computed using other -// values in the state before they can be properly evaluated. The updated -// values are retained in the main state associated with the receiving context. -// -// This function takes no action against remote APIs but it does need access -// to all provider and provisioner instances in order to obtain their schemas -// for type checking. -// -// The result is an evaluation scope that can be used to resolve references -// against the root module. If the returned diagnostics contains errors then -// the returned scope may be nil. If it is not nil then it may still be used -// to attempt expression evaluation or other analysis, but some expressions -// may not behave as expected. -func (c *Context) Eval(path addrs.ModuleInstance) (*lang.Scope, tfdiags.Diagnostics) { - // This is intended for external callers such as the "terraform console" - // command. Internally, we create an evaluator in c.walk before walking - // the graph, and create scopes in ContextGraphWalker. - - var diags tfdiags.Diagnostics - defer c.acquireRun("eval")() - - // Start with a copy of state so that we don't affect any instances - // that other methods may have already returned. - c.state = c.state.DeepCopy() - var walker *ContextGraphWalker - - graph, graphDiags := c.Graph(GraphTypeEval, nil) - diags = diags.Append(graphDiags) - if !diags.HasErrors() { - var walkDiags tfdiags.Diagnostics - walker, walkDiags = c.walk(graph, walkEval) - diags = diags.Append(walker.NonFatalDiagnostics) - diags = diags.Append(walkDiags) - } - - if walker == nil { - // If we skipped walking the graph (due to errors) then we'll just - // use a placeholder graph walker here, which'll refer to the - // unmodified state. - walker = c.graphWalker(walkEval) - } - - // This is a bit weird since we don't normally evaluate outside of - // the context of a walk, but we'll "re-enter" our desired path here - // just to get hold of an EvalContext for it. GraphContextBuiltin - // caches its contexts, so we should get hold of the context that was - // previously used for evaluation here, unless we skipped walking. - evalCtx := walker.EnterPath(path) - return evalCtx.EvaluationScope(nil, EvalDataForNoInstanceKey), diags -} - -// Apply applies the changes represented by this context and returns -// the resulting 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() (*states.State, tfdiags.Diagnostics) { - defer c.acquireRun("apply")() - - // Copy our own state - c.state = c.state.DeepCopy() - - // Build the graph. - graph, diags := c.Graph(GraphTypeApply, nil) - if diags.HasErrors() { - return nil, diags - } - - // Determine the operation - operation := walkApply - if c.destroy { - operation = walkDestroy - } - - // Walk the graph - walker, walkDiags := c.walk(graph, operation) - diags = diags.Append(walker.NonFatalDiagnostics) - diags = diags.Append(walkDiags) - - if c.destroy && !diags.HasErrors() { - // If we know we were trying to destroy objects anyway, and we - // completed without any errors, then we'll also prune out any - // leftover empty resource husks (left after all of the instances - // of a resource with "count" or "for_each" are destroyed) to - // help ensure we end up with an _actually_ empty state, assuming - // we weren't destroying with -target here. - // - // (This doesn't actually take into account -target, but that should - // be okay because it doesn't throw away anything we can't recompute - // on a subsequent "terraform plan" run, if the resources are still - // present in the configuration. However, this _will_ cause "count = 0" - // resources to read as unknown during the next refresh walk, which - // may cause some additional churn if used in a data resource or - // provider block, until we remove refreshing as a separate walk and - // just do it as part of the plan walk.) - c.state.PruneResourceHusks() - } - - if len(c.targets) > 0 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Warning, - "Applied changes may be incomplete", - `The plan was created with the -target option in effect, so some changes requested in the configuration may have been ignored and the output values may not be fully updated. Run the following command to verify that no other changes are pending: - terraform plan - -Note that the -target option is not suitable for routine use, and is provided only for exceptional situations such as recovering from errors or mistakes, or when Terraform specifically suggests to use it as part of an error message.`, - )) - } - - return c.state, diags -} - -// Plan generates an execution plan for the given context. -// -// The execution plan encapsulates the context and can be stored -// in order to reinstantiate a context later for Apply. -// -// Plan also updates the diff of this context to be the diff generated -// by the plan, so Apply can be called after. -func (c *Context) Plan() (*plans.Plan, tfdiags.Diagnostics) { - defer c.acquireRun("plan")() - c.changes = plans.NewChanges() - - var diags tfdiags.Diagnostics - - if len(c.targets) > 0 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Warning, - "Resource targeting is in effect", - `You are creating a plan with the -target option, which means that the result of this plan may not represent all of the changes requested by the current configuration. - -The -target option is not for routine use, and is provided only for exceptional situations such as recovering from errors or mistakes, or when Terraform specifically suggests to use it as part of an error message.`, - )) - } - - varVals := make(map[string]plans.DynamicValue, len(c.variables)) - for k, iv := range c.variables { - // We use cty.DynamicPseudoType here so that we'll save both the - // value _and_ its dynamic type in the plan, so we can recover - // exactly the same value later. - dv, err := plans.NewDynamicValue(iv.Value, cty.DynamicPseudoType) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to prepare variable value for plan", - fmt.Sprintf("The value for variable %q could not be serialized to store in the plan: %s.", k, err), - )) - continue - } - varVals[k] = dv - } - - p := &plans.Plan{ - VariableValues: varVals, - TargetAddrs: c.targets, - ProviderSHA256s: c.providerSHA256s, - } - - var operation walkOperation - if c.destroy { - operation = walkPlanDestroy - } else { - // Set our state to be something temporary. We do this so that - // the plan can update a fake state so that variables work, then - // we replace it back with our old state. - old := c.state - if old == nil { - c.state = states.NewState() - } else { - c.state = old.DeepCopy() - } - defer func() { - c.state = old - }() - - operation = walkPlan - } - - // Build the graph. - graphType := GraphTypePlan - if c.destroy { - graphType = GraphTypePlanDestroy - } - graph, graphDiags := c.Graph(graphType, nil) - diags = diags.Append(graphDiags) - if graphDiags.HasErrors() { - return nil, diags - } - - // Do the walk - walker, walkDiags := c.walk(graph, operation) - diags = diags.Append(walker.NonFatalDiagnostics) - diags = diags.Append(walkDiags) - if walkDiags.HasErrors() { - return nil, diags - } - p.Changes = c.changes - - return p, diags -} - -// Refresh goes through all the resources in the state and refreshes them -// 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 may be returned and -// will potentially be partially updated. -func (c *Context) Refresh() (*states.State, tfdiags.Diagnostics) { - defer c.acquireRun("refresh")() - - // Copy our own state - c.state = c.state.DeepCopy() - - // Refresh builds a partial changeset as part of its work because it must - // create placeholder stubs for any resource instances that'll be created - // in subsequent plan so that provider configurations and data resources - // can interpolate from them. This plan is always thrown away after - // the operation completes, restoring any existing changeset. - oldChanges := c.changes - defer func() { c.changes = oldChanges }() - c.changes = plans.NewChanges() - - // Build the graph. - graph, diags := c.Graph(GraphTypeRefresh, nil) - if diags.HasErrors() { - return nil, diags - } - - // Do the walk - _, walkDiags := c.walk(graph, walkRefresh) - diags = diags.Append(walkDiags) - if walkDiags.HasErrors() { - return nil, diags - } - - // During our walk we will have created planned object placeholders in - // state for resource instances that are in configuration but not yet - // created. These were created only to allow expression evaluation to - // work properly in provider and data blocks during the walk and must - // now be discarded, since a subsequent plan walk is responsible for - // creating these "for real". - // TODO: Consolidate refresh and plan into a single walk, so that the - // refresh walk doesn't need to emulate various aspects of the plan - // walk in order to properly evaluate provider and data blocks. - c.state.SyncWrapper().RemovePlannedResourceInstanceObjects() - - return c.state, diags -} - -// Stop stops the running task. -// -// Stop will block until the task completes. -func (c *Context) Stop() { - log.Printf("[WARN] terraform: Stop called, initiating interrupt sequence") - - c.l.Lock() - defer c.l.Unlock() - - // If we're running, then stop - if c.runContextCancel != nil { - log.Printf("[WARN] terraform: run context exists, stopping") - - // Tell the hook we want to stop - c.sh.Stop() - - // Stop the context - c.runContextCancel() - c.runContextCancel = nil - } - - // Grab the condition var before we exit - if cond := c.runCond; cond != nil { - log.Printf("[INFO] terraform: waiting for graceful stop to complete") - cond.Wait() - } - - log.Printf("[WARN] terraform: stop complete") -} - -// Validate performs semantic validation of the configuration, and returning -// any warnings or errors. -// -// Syntax and structural checks are performed by the configuration loader, -// and so are not repeated here. -func (c *Context) Validate() tfdiags.Diagnostics { - defer c.acquireRun("validate")() - - var diags tfdiags.Diagnostics - - // Validate input variables. We do this only for the values supplied - // by the root module, since child module calls are validated when we - // visit their graph nodes. - if c.config != nil { - varDiags := checkInputVariables(c.config.Module.Variables, c.variables) - diags = diags.Append(varDiags) - } - - // If we have errors at this point then we probably won't be able to - // construct a graph without producing redundant errors, so we'll halt early. - if diags.HasErrors() { - return diags - } - - // Build the graph so we can walk it and run Validate on nodes. - // We also validate the graph generated here, but this graph doesn't - // necessarily match the graph that Plan will generate, so we'll validate the - // graph again later after Planning. - graph, graphDiags := c.Graph(GraphTypeValidate, nil) - diags = diags.Append(graphDiags) - if graphDiags.HasErrors() { - return diags - } - - // Walk - walker, walkDiags := c.walk(graph, walkValidate) - diags = diags.Append(walker.NonFatalDiagnostics) - diags = diags.Append(walkDiags) - if walkDiags.HasErrors() { - return diags - } - - return diags -} - -// Config returns the configuration tree associated with this context. -func (c *Context) Config() *configs.Config { - return c.config -} - -// Variables will return the mapping of variables that were defined -// for this Context. If Input was called, this mapping may be different -// than what was given. -func (c *Context) Variables() InputValues { - return c.variables -} - -// SetVariable sets a variable after a context has already been built. -func (c *Context) SetVariable(k string, v cty.Value) { - c.variables[k] = &InputValue{ - Value: v, - SourceType: ValueFromCaller, - } -} - -func (c *Context) acquireRun(phase string) func() { - // With the run lock held, grab the context lock to make changes - // to the run context. - c.l.Lock() - defer c.l.Unlock() - - // Wait until we're no longer running - for c.runCond != nil { - c.runCond.Wait() - } - - // Build our lock - c.runCond = sync.NewCond(&c.l) - - // Create a new run context - c.runContext, c.runContextCancel = context.WithCancel(context.Background()) - - // Reset the stop hook so we're not stopped - c.sh.Reset() - - // Reset the shadow errors - c.shadowErr = nil - - return c.releaseRun -} - -func (c *Context) releaseRun() { - // Grab the context lock so that we can make modifications to fields - c.l.Lock() - defer c.l.Unlock() - - // End our run. We check if runContext is non-nil because it can be - // set to nil if it was cancelled via Stop() - if c.runContextCancel != nil { - c.runContextCancel() - } - - // Unlock all waiting our condition - cond := c.runCond - c.runCond = nil - cond.Broadcast() - - // Unset the context - c.runContext = nil -} - -func (c *Context) walk(graph *Graph, operation walkOperation) (*ContextGraphWalker, tfdiags.Diagnostics) { - log.Printf("[DEBUG] Starting graph walk: %s", operation.String()) - - walker := c.graphWalker(operation) - - // Watch for a stop so we can call the provider Stop() API. - watchStop, watchWait := c.watchStop(walker) - - // Walk the real graph, this will block until it completes - diags := graph.Walk(walker) - - // Close the channel so the watcher stops, and wait for it to return. - close(watchStop) - <-watchWait - - return walker, diags -} - -func (c *Context) graphWalker(operation walkOperation) *ContextGraphWalker { - return &ContextGraphWalker{ - Context: c, - State: c.state.SyncWrapper(), - Changes: c.changes.SyncWrapper(), - Operation: operation, - StopContext: c.runContext, - RootVariableValues: c.variables, - } -} - -// watchStop immediately returns a `stop` and a `wait` chan after dispatching -// the watchStop goroutine. This will watch the runContext for cancellation and -// stop the providers accordingly. When the watch is no longer needed, the -// `stop` chan should be closed before waiting on the `wait` chan. -// The `wait` chan is important, because without synchronizing with the end of -// the watchStop goroutine, the runContext may also be closed during the select -// incorrectly causing providers to be stopped. Even if the graph walk is done -// at that point, stopping a provider permanently cancels its StopContext which -// can cause later actions to fail. -func (c *Context) watchStop(walker *ContextGraphWalker) (chan struct{}, <-chan struct{}) { - stop := make(chan struct{}) - wait := make(chan struct{}) - - // get the runContext cancellation channel now, because releaseRun will - // write to the runContext field. - done := c.runContext.Done() - - go func() { - defer close(wait) - // Wait for a stop or completion - select { - case <-done: - // done means the context was canceled, so we need to try and stop - // providers. - case <-stop: - // our own stop channel was closed. - return - } - - // If we're here, we're stopped, trigger the call. - log.Printf("[TRACE] Context: requesting providers and provisioners to gracefully stop") - - { - // Copy the providers so that a misbehaved blocking Stop doesn't - // completely hang Terraform. - walker.providerLock.Lock() - ps := make([]providers.Interface, 0, len(walker.providerCache)) - for _, p := range walker.providerCache { - ps = append(ps, p) - } - defer walker.providerLock.Unlock() - - for _, p := range ps { - // We ignore the error for now since there isn't any reasonable - // action to take if there is an error here, since the stop is still - // advisory: Terraform will exit once the graph node completes. - p.Stop() - } - } - - { - // Call stop on all the provisioners - walker.provisionerLock.Lock() - ps := make([]provisioners.Interface, 0, len(walker.provisionerCache)) - for _, p := range walker.provisionerCache { - ps = append(ps, p) - } - defer walker.provisionerLock.Unlock() - - for _, p := range ps { - // We ignore the error for now since there isn't any reasonable - // action to take if there is an error here, since the stop is still - // advisory: Terraform will exit once the graph node completes. - p.Stop() - } - } - }() - - return stop, wait -} - -// ShimLegacyState is a helper that takes the legacy state type and -// converts it to the new state type. -// -// This is implemented as a state file upgrade, so it will not preserve -// parts of the state structure that are not included in a serialized state, -// such as the resolved results of any local values, outputs in non-root -// modules, etc. -func ShimLegacyState(legacy *State) (*states.State, error) { - if legacy == nil { - return nil, nil - } - var buf bytes.Buffer - err := WriteState(legacy, &buf) - if err != nil { - return nil, err - } - f, err := statefile.Read(&buf) - if err != nil { - return nil, err - } - return f.State, err -} - -// MustShimLegacyState is a wrapper around ShimLegacyState that panics if -// the conversion does not succeed. This is primarily intended for tests where -// the given legacy state is an object constructed within the test. -func MustShimLegacyState(legacy *State) *states.State { - ret, err := ShimLegacyState(legacy) - if err != nil { - panic(err) - } - return ret -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_components.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_components.go deleted file mode 100644 index a627996e39b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_components.go +++ /dev/null @@ -1,68 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" -) - -// contextComponentFactory is the interface that Context uses -// to initialize various components such as providers and provisioners. -// This factory gets more information than the raw maps using to initialize -// a Context. This information is used for debugging. -type contextComponentFactory interface { - // ResourceProvider creates a new ResourceProvider with the given - // type. The "uid" is a unique identifier for this provider being - // initialized that can be used for internal tracking. - ResourceProvider(typ, uid string) (providers.Interface, error) - ResourceProviders() []string - - // ResourceProvisioner creates a new ResourceProvisioner with the - // given type. The "uid" is a unique identifier for this provisioner - // being initialized that can be used for internal tracking. - ResourceProvisioner(typ, uid string) (provisioners.Interface, error) - ResourceProvisioners() []string -} - -// basicComponentFactory just calls a factory from a map directly. -type basicComponentFactory struct { - providers map[string]providers.Factory - provisioners map[string]ProvisionerFactory -} - -func (c *basicComponentFactory) ResourceProviders() []string { - result := make([]string, len(c.providers)) - for k := range c.providers { - result = append(result, k) - } - - return result -} - -func (c *basicComponentFactory) ResourceProvisioners() []string { - result := make([]string, len(c.provisioners)) - for k := range c.provisioners { - result = append(result, k) - } - - return result -} - -func (c *basicComponentFactory) ResourceProvider(typ, uid string) (providers.Interface, error) { - f, ok := c.providers[typ] - if !ok { - return nil, fmt.Errorf("unknown provider %q", typ) - } - - return f() -} - -func (c *basicComponentFactory) ResourceProvisioner(typ, uid string) (provisioners.Interface, error) { - f, ok := c.provisioners[typ] - if !ok { - return nil, fmt.Errorf("unknown provisioner %q", typ) - } - - return f() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_graph_type.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_graph_type.go deleted file mode 100644 index 4448d8706e1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_graph_type.go +++ /dev/null @@ -1,32 +0,0 @@ -package terraform - -//go:generate go run golang.org/x/tools/cmd/stringer -type=GraphType context_graph_type.go - -// GraphType is an enum of the type of graph to create with a Context. -// The values of the constants may change so they shouldn't be depended on; -// always use the constant name. -type GraphType byte - -const ( - GraphTypeInvalid GraphType = 0 - GraphTypeLegacy GraphType = iota - GraphTypeRefresh - GraphTypePlan - GraphTypePlanDestroy - GraphTypeApply - GraphTypeValidate - GraphTypeEval // only visits in-memory elements such as variables, locals, and outputs. -) - -// GraphTypeMap is a mapping of human-readable string to GraphType. This -// is useful to use as the mechanism for human input for configurable -// graph types. -var GraphTypeMap = map[string]GraphType{ - "apply": GraphTypeApply, - "plan": GraphTypePlan, - "plan-destroy": GraphTypePlanDestroy, - "refresh": GraphTypeRefresh, - "legacy": GraphTypeLegacy, - "validate": GraphTypeValidate, - "eval": GraphTypeEval, -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_import.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_import.go deleted file mode 100644 index 9a9cd9626b1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_import.go +++ /dev/null @@ -1,83 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// ImportOpts are used as the configuration for Import. -type ImportOpts struct { - // Targets are the targets to import - Targets []*ImportTarget - - // Config is optional, and specifies a config tree that will be loaded - // into the graph and evaluated. This is the source for provider - // configurations. - Config *configs.Config -} - -// ImportTarget is a single resource to import. -type ImportTarget struct { - // Addr is the address for the resource instance that the new object should - // be imported into. - Addr addrs.AbsResourceInstance - - // ID is the ID of the resource to import. This is resource-specific. - ID string - - // ProviderAddr is the address of the provider that should handle the import. - ProviderAddr addrs.AbsProviderConfig -} - -// Import takes already-created external resources and brings them -// under Terraform management. Import requires the exact type, name, and ID -// of the resources to import. -// -// This operation is idempotent. If the requested resource is already -// imported, no changes are made to the state. -// -// Further, this operation also gracefully handles partial state. If during -// an import there is a failure, all previously imported resources remain -// imported. -func (c *Context) Import(opts *ImportOpts) (*states.State, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // Hold a lock since we can modify our own state here - defer c.acquireRun("import")() - - // Copy our own state - c.state = c.state.DeepCopy() - - // If no module is given, default to the module configured with - // the Context. - config := opts.Config - if config == nil { - config = c.config - } - - // Initialize our graph builder - builder := &ImportGraphBuilder{ - ImportTargets: opts.Targets, - Config: config, - Components: c.components, - Schemas: c.schemas, - } - - // Build the graph! - graph, graphDiags := builder.Build(addrs.RootModuleInstance) - diags = diags.Append(graphDiags) - if graphDiags.HasErrors() { - return c.state, diags - } - - // Walk it - _, walkDiags := c.walk(graph, walkImport) - diags = diags.Append(walkDiags) - if walkDiags.HasErrors() { - return c.state, diags - } - - return c.state, diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_input.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_input.go deleted file mode 100644 index b99f1afacfc..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_input.go +++ /dev/null @@ -1,251 +0,0 @@ -package terraform - -import ( - "context" - "fmt" - "log" - "sort" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hcldec" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// Input asks for input to fill variables and provider configurations. -// This modifies the configuration in-place, so asking for Input twice -// may result in different UI output showing different current values. -func (c *Context) Input(mode InputMode) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - defer c.acquireRun("input")() - - if c.uiInput == nil { - log.Printf("[TRACE] Context.Input: uiInput is nil, so skipping") - return diags - } - - ctx := context.Background() - - if mode&InputModeVar != 0 { - log.Printf("[TRACE] Context.Input: Prompting for variables") - - // Walk the variables first for the root module. We walk them in - // alphabetical order for UX reasons. - configs := c.config.Module.Variables - names := make([]string, 0, len(configs)) - for name := range configs { - names = append(names, name) - } - sort.Strings(names) - Variables: - for _, n := range names { - v := configs[n] - - // If we only care about unset variables, then we should set any - // variable that is already set. - if mode&InputModeVarUnset != 0 { - if _, isSet := c.variables[n]; isSet { - continue - } - } - - // this should only happen during tests - if c.uiInput == nil { - log.Println("[WARN] Context.uiInput is nil during input walk") - continue - } - - // Ask the user for a value for this variable - var rawValue string - retry := 0 - for { - var err error - rawValue, err = c.uiInput.Input(ctx, &InputOpts{ - Id: fmt.Sprintf("var.%s", n), - Query: fmt.Sprintf("var.%s", n), - Description: v.Description, - }) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to request interactive input", - fmt.Sprintf("Terraform attempted to request a value for var.%s interactively, but encountered an error: %s.", n, err), - )) - return diags - } - - if rawValue == "" && v.Default == cty.NilVal { - // Redo if it is required, but abort if we keep getting - // blank entries - if retry > 2 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Required variable not assigned", - fmt.Sprintf("The variable %q is required, so Terraform cannot proceed without a defined value for it.", n), - )) - continue Variables - } - retry++ - continue - } - - break - } - - val, valDiags := v.ParsingMode.Parse(n, rawValue) - diags = diags.Append(valDiags) - if diags.HasErrors() { - continue - } - - c.variables[n] = &InputValue{ - Value: val, - SourceType: ValueFromInput, - } - } - } - - if mode&InputModeProvider != 0 { - log.Printf("[TRACE] Context.Input: Prompting for provider arguments") - - // We prompt for input only for provider configurations defined in - // the root module. At the time of writing that is an arbitrary - // restriction, but we have future plans to support "count" and - // "for_each" on modules that will then prevent us from supporting - // input for child module configurations anyway (since we'd need to - // dynamic-expand first), and provider configurations in child modules - // are not recommended since v0.11 anyway, so this restriction allows - // us to keep this relatively simple without significant hardship. - - pcs := make(map[string]*configs.Provider) - pas := make(map[string]addrs.ProviderConfig) - for _, pc := range c.config.Module.ProviderConfigs { - addr := pc.Addr() - pcs[addr.String()] = pc - pas[addr.String()] = addr - log.Printf("[TRACE] Context.Input: Provider %s declared at %s", addr, pc.DeclRange) - } - // We also need to detect _implied_ provider configs from resources. - // These won't have *configs.Provider objects, but they will still - // exist in the map and we'll just treat them as empty below. - for _, rc := range c.config.Module.ManagedResources { - pa := rc.ProviderConfigAddr() - if pa.Alias != "" { - continue // alias configurations cannot be implied - } - if _, exists := pcs[pa.String()]; !exists { - pcs[pa.String()] = nil - pas[pa.String()] = pa - log.Printf("[TRACE] Context.Input: Provider %s implied by resource block at %s", pa, rc.DeclRange) - } - } - for _, rc := range c.config.Module.DataResources { - pa := rc.ProviderConfigAddr() - if pa.Alias != "" { - continue // alias configurations cannot be implied - } - if _, exists := pcs[pa.String()]; !exists { - pcs[pa.String()] = nil - pas[pa.String()] = pa - log.Printf("[TRACE] Context.Input: Provider %s implied by data block at %s", pa, rc.DeclRange) - } - } - - for pk, pa := range pas { - pc := pcs[pk] // will be nil if this is an implied config - - // Wrap the input into a namespace - input := &PrefixUIInput{ - IdPrefix: pk, - QueryPrefix: pk + ".", - UIInput: c.uiInput, - } - - schema := c.schemas.ProviderConfig(pa.Type) - if schema == nil { - // Could either be an incorrect config or just an incomplete - // mock in tests. We'll let a later pass decide, and just - // ignore this for the purposes of gathering input. - log.Printf("[TRACE] Context.Input: No schema available for provider type %q", pa.Type) - continue - } - - // For our purposes here we just want to detect if attrbutes are - // set in config at all, so rather than doing a full decode - // (which would require us to prepare an evalcontext, etc) we'll - // use the low-level HCL API to process only the top-level - // structure. - var attrExprs hcl.Attributes // nil if there is no config - if pc != nil && pc.Config != nil { - lowLevelSchema := schemaForInputSniffing(hcldec.ImpliedSchema(schema.DecoderSpec())) - content, _, diags := pc.Config.PartialContent(lowLevelSchema) - if diags.HasErrors() { - log.Printf("[TRACE] Context.Input: %s has decode error, so ignoring: %s", pa, diags.Error()) - continue - } - attrExprs = content.Attributes - } - - keys := make([]string, 0, len(schema.Attributes)) - for key := range schema.Attributes { - keys = append(keys, key) - } - sort.Strings(keys) - - vals := map[string]cty.Value{} - for _, key := range keys { - attrS := schema.Attributes[key] - if attrS.Optional { - continue - } - if attrExprs != nil { - if _, exists := attrExprs[key]; exists { - continue - } - } - if !attrS.Type.Equals(cty.String) { - continue - } - - log.Printf("[TRACE] Context.Input: Prompting for %s argument %s", pa, key) - rawVal, err := input.Input(ctx, &InputOpts{ - Id: key, - Query: key, - Description: attrS.Description, - }) - if err != nil { - log.Printf("[TRACE] Context.Input: Failed to prompt for %s argument %s: %s", pa, key, err) - continue - } - - vals[key] = cty.StringVal(rawVal) - } - - c.providerInputConfig[pk] = vals - log.Printf("[TRACE] Context.Input: Input for %s: %#v", pk, vals) - } - } - - return diags -} - -// schemaForInputSniffing returns a transformed version of a given schema -// that marks all attributes as optional, which the Context.Input method can -// use to detect whether a required argument is set without missing arguments -// themselves generating errors. -func schemaForInputSniffing(schema *hcl.BodySchema) *hcl.BodySchema { - ret := &hcl.BodySchema{ - Attributes: make([]hcl.AttributeSchema, len(schema.Attributes)), - Blocks: schema.Blocks, - } - - for i, attrS := range schema.Attributes { - ret.Attributes[i] = attrS - ret.Attributes[i].Required = false - } - - return ret -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/diff.go deleted file mode 100644 index fd5b389b066..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/diff.go +++ /dev/null @@ -1,1441 +0,0 @@ -package terraform - -import ( - "bufio" - "bytes" - "fmt" - "log" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "sync" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" - "github.com/zclconf/go-cty/cty" - - "github.com/mitchellh/copystructure" -) - -// DiffChangeType is an enum with the kind of changes a diff has planned. -type DiffChangeType byte - -const ( - DiffInvalid DiffChangeType = iota - DiffNone - DiffCreate - DiffUpdate - DiffDestroy - DiffDestroyCreate - - // DiffRefresh is only used in the UI for displaying diffs. - // Managed resource reads never appear in plan, and when data source - // reads appear they are represented as DiffCreate in core before - // transforming to DiffRefresh in the UI layer. - DiffRefresh // TODO: Actually use DiffRefresh in core too, for less confusion -) - -// multiVal matches the index key to a flatmapped set, list or map -var multiVal = regexp.MustCompile(`\.(#|%)$`) - -// Diff tracks the changes that are necessary to apply a configuration -// to an existing infrastructure. -type Diff struct { - // Modules contains all the modules that have a diff - Modules []*ModuleDiff -} - -// Prune cleans out unused structures in the diff without affecting -// the behavior of the diff at all. -// -// This is not safe to call concurrently. This is safe to call on a -// nil Diff. -func (d *Diff) Prune() { - if d == nil { - return - } - - // Prune all empty modules - newModules := make([]*ModuleDiff, 0, len(d.Modules)) - for _, m := range d.Modules { - // If the module isn't empty, we keep it - if !m.Empty() { - newModules = append(newModules, m) - } - } - if len(newModules) == 0 { - newModules = nil - } - d.Modules = newModules -} - -// AddModule adds the module with the given path to the diff. -// -// This should be the preferred method to add module diffs since it -// allows us to optimize lookups later as well as control sorting. -func (d *Diff) AddModule(path addrs.ModuleInstance) *ModuleDiff { - // Lower the new-style address into a legacy-style address. - // This requires that none of the steps have instance keys, which is - // true for all addresses at the time of implementing this because - // "count" and "for_each" are not yet implemented for modules. - legacyPath := make([]string, len(path)) - for i, step := range path { - if step.InstanceKey != addrs.NoKey { - // FIXME: Once the rest of Terraform is ready to use count and - // for_each, remove all of this and just write the addrs.ModuleInstance - // value itself into the ModuleState. - panic("diff cannot represent modules with count or for_each keys") - } - - legacyPath[i] = step.Name - } - - m := &ModuleDiff{Path: legacyPath} - m.init() - d.Modules = append(d.Modules, m) - return m -} - -// ModuleByPath is used to lookup the module diff for the given path. -// This should be the preferred lookup mechanism as it allows for future -// lookup optimizations. -func (d *Diff) ModuleByPath(path addrs.ModuleInstance) *ModuleDiff { - if d == nil { - return nil - } - for _, mod := range d.Modules { - if mod.Path == nil { - panic("missing module path") - } - modPath := normalizeModulePath(mod.Path) - if modPath.String() == path.String() { - return mod - } - } - return nil -} - -// RootModule returns the ModuleState for the root module -func (d *Diff) RootModule() *ModuleDiff { - root := d.ModuleByPath(addrs.RootModuleInstance) - if root == nil { - panic("missing root module") - } - return root -} - -// Empty returns true if the diff has no changes. -func (d *Diff) Empty() bool { - if d == nil { - return true - } - - for _, m := range d.Modules { - if !m.Empty() { - return false - } - } - - return true -} - -// Equal compares two diffs for exact equality. -// -// This is different from the Same comparison that is supported which -// checks for operation equality taking into account computed values. Equal -// instead checks for exact equality. -func (d *Diff) Equal(d2 *Diff) bool { - // If one is nil, they must both be nil - if d == nil || d2 == nil { - return d == d2 - } - - // Sort the modules - sort.Sort(moduleDiffSort(d.Modules)) - sort.Sort(moduleDiffSort(d2.Modules)) - - // Copy since we have to modify the module destroy flag to false so - // we don't compare that. TODO: delete this when we get rid of the - // destroy flag on modules. - dCopy := d.DeepCopy() - d2Copy := d2.DeepCopy() - for _, m := range dCopy.Modules { - m.Destroy = false - } - for _, m := range d2Copy.Modules { - m.Destroy = false - } - - // Use DeepEqual - return reflect.DeepEqual(dCopy, d2Copy) -} - -// DeepCopy performs a deep copy of all parts of the Diff, making the -// resulting Diff safe to use without modifying this one. -func (d *Diff) DeepCopy() *Diff { - copy, err := copystructure.Config{Lock: true}.Copy(d) - if err != nil { - panic(err) - } - - return copy.(*Diff) -} - -func (d *Diff) String() string { - var buf bytes.Buffer - - keys := make([]string, 0, len(d.Modules)) - lookup := make(map[string]*ModuleDiff) - for _, m := range d.Modules { - addr := normalizeModulePath(m.Path) - key := addr.String() - keys = append(keys, key) - lookup[key] = m - } - sort.Strings(keys) - - for _, key := range keys { - m := lookup[key] - mStr := m.String() - - // If we're the root module, we just write the output directly. - if reflect.DeepEqual(m.Path, rootModulePath) { - buf.WriteString(mStr + "\n") - continue - } - - buf.WriteString(fmt.Sprintf("%s:\n", key)) - - s := bufio.NewScanner(strings.NewReader(mStr)) - for s.Scan() { - buf.WriteString(fmt.Sprintf(" %s\n", s.Text())) - } - } - - return strings.TrimSpace(buf.String()) -} - -// ModuleDiff tracks the differences between resources to apply within -// a single module. -type ModuleDiff struct { - Path []string - Resources map[string]*InstanceDiff - Destroy bool // Set only by the destroy plan -} - -func (d *ModuleDiff) init() { - if d.Resources == nil { - d.Resources = make(map[string]*InstanceDiff) - } - for _, r := range d.Resources { - r.init() - } -} - -// ChangeType returns the type of changes that the diff for this -// module includes. -// -// At a module level, this will only be DiffNone, DiffUpdate, DiffDestroy, or -// DiffCreate. If an instance within the module has a DiffDestroyCreate -// then this will register as a DiffCreate for a module. -func (d *ModuleDiff) ChangeType() DiffChangeType { - result := DiffNone - for _, r := range d.Resources { - change := r.ChangeType() - switch change { - case DiffCreate, DiffDestroy: - if result == DiffNone { - result = change - } - case DiffDestroyCreate, DiffUpdate: - result = DiffUpdate - } - } - - return result -} - -// Empty returns true if the diff has no changes within this module. -func (d *ModuleDiff) Empty() bool { - if d.Destroy { - return false - } - - if len(d.Resources) == 0 { - return true - } - - for _, rd := range d.Resources { - if !rd.Empty() { - return false - } - } - - return true -} - -// Instances returns the instance diffs for the id given. This can return -// multiple instance diffs if there are counts within the resource. -func (d *ModuleDiff) Instances(id string) []*InstanceDiff { - var result []*InstanceDiff - for k, diff := range d.Resources { - if k == id || strings.HasPrefix(k, id+".") { - if !diff.Empty() { - result = append(result, diff) - } - } - } - - return result -} - -// IsRoot says whether or not this module diff is for the root module. -func (d *ModuleDiff) IsRoot() bool { - return reflect.DeepEqual(d.Path, rootModulePath) -} - -// String outputs the diff in a long but command-line friendly output -// format that users can read to quickly inspect a diff. -func (d *ModuleDiff) String() string { - var buf bytes.Buffer - - names := make([]string, 0, len(d.Resources)) - for name := range d.Resources { - names = append(names, name) - } - sort.Strings(names) - - for _, name := range names { - rdiff := d.Resources[name] - - crud := "UPDATE" - switch { - case rdiff.RequiresNew() && (rdiff.GetDestroy() || rdiff.GetDestroyTainted()): - crud = "DESTROY/CREATE" - case rdiff.GetDestroy() || rdiff.GetDestroyDeposed(): - crud = "DESTROY" - case rdiff.RequiresNew(): - crud = "CREATE" - } - - extra := "" - if !rdiff.GetDestroy() && rdiff.GetDestroyDeposed() { - extra = " (deposed only)" - } - - buf.WriteString(fmt.Sprintf( - "%s: %s%s\n", - crud, - name, - extra)) - - keyLen := 0 - rdiffAttrs := rdiff.CopyAttributes() - keys := make([]string, 0, len(rdiffAttrs)) - for key := range rdiffAttrs { - if key == "id" { - continue - } - - keys = append(keys, key) - if len(key) > keyLen { - keyLen = len(key) - } - } - sort.Strings(keys) - - for _, attrK := range keys { - attrDiff, _ := rdiff.GetAttribute(attrK) - - v := attrDiff.New - u := attrDiff.Old - if attrDiff.NewComputed { - v = "" - } - - if attrDiff.Sensitive { - u = "" - v = "" - } - - updateMsg := "" - if attrDiff.RequiresNew { - updateMsg = " (forces new resource)" - } else if attrDiff.Sensitive { - updateMsg = " (attribute changed)" - } - - buf.WriteString(fmt.Sprintf( - " %s:%s %#v => %#v%s\n", - attrK, - strings.Repeat(" ", keyLen-len(attrK)), - u, - v, - updateMsg)) - } - } - - return buf.String() -} - -// InstanceDiff is the diff of a resource from some state to another. -type InstanceDiff struct { - mu sync.Mutex - Attributes map[string]*ResourceAttrDiff - Destroy bool - DestroyDeposed bool - DestroyTainted bool - - // Meta is a simple K/V map that is stored in a diff and persisted to - // plans but otherwise is completely ignored by Terraform core. It is - // meant to be used for additional data a resource may want to pass through. - // The value here must only contain Go primitives and collections. - Meta map[string]interface{} -} - -func (d *InstanceDiff) Lock() { d.mu.Lock() } -func (d *InstanceDiff) Unlock() { d.mu.Unlock() } - -// ApplyToValue merges the receiver into the given base value, returning a -// new value that incorporates the planned changes. The given value must -// conform to the given schema, or this method will panic. -// -// This method is intended for shimming old subsystems that still use this -// legacy diff type to work with the new-style types. -func (d *InstanceDiff) ApplyToValue(base cty.Value, schema *configschema.Block) (cty.Value, error) { - // Create an InstanceState attributes from our existing state. - // We can use this to more easily apply the diff changes. - attrs := hcl2shim.FlatmapValueFromHCL2(base) - applied, err := d.Apply(attrs, schema) - if err != nil { - return base, err - } - - val, err := hcl2shim.HCL2ValueFromFlatmap(applied, schema.ImpliedType()) - if err != nil { - return base, err - } - - return schema.CoerceValue(val) -} - -// Apply applies the diff to the provided flatmapped attributes, -// returning the new instance attributes. -// -// This method is intended for shimming old subsystems that still use this -// legacy diff type to work with the new-style types. -func (d *InstanceDiff) Apply(attrs map[string]string, schema *configschema.Block) (map[string]string, error) { - // We always build a new value here, even if the given diff is "empty", - // because we might be planning to create a new instance that happens - // to have no attributes set, and so we want to produce an empty object - // rather than just echoing back the null old value. - if attrs == nil { - attrs = map[string]string{} - } - - // Rather applying the diff to mutate the attrs, we'll copy new values into - // here to avoid the possibility of leaving stale values. - result := map[string]string{} - - if d.Destroy || d.DestroyDeposed || d.DestroyTainted { - return result, nil - } - - return d.applyBlockDiff(nil, attrs, schema) -} - -func (d *InstanceDiff) applyBlockDiff(path []string, attrs map[string]string, schema *configschema.Block) (map[string]string, error) { - result := map[string]string{} - name := "" - if len(path) > 0 { - name = path[len(path)-1] - } - - // localPrefix is used to build the local result map - localPrefix := "" - if name != "" { - localPrefix = name + "." - } - - // iterate over the schema rather than the attributes, so we can handle - // different block types separately from plain attributes - for n, attrSchema := range schema.Attributes { - var err error - newAttrs, err := d.applyAttrDiff(append(path, n), attrs, attrSchema) - - if err != nil { - return result, err - } - - for k, v := range newAttrs { - result[localPrefix+k] = v - } - } - - blockPrefix := strings.Join(path, ".") - if blockPrefix != "" { - blockPrefix += "." - } - for n, block := range schema.BlockTypes { - // we need to find the set of all keys that traverse this block - candidateKeys := map[string]bool{} - blockKey := blockPrefix + n + "." - localBlockPrefix := localPrefix + n + "." - - // we can only trust the diff for sets, since the path changes, so don't - // count existing values as candidate keys. If it turns out we're - // keeping the attributes, we will catch it down below with "keepBlock" - // after we check the set count. - if block.Nesting != configschema.NestingSet { - for k := range attrs { - if strings.HasPrefix(k, blockKey) { - nextDot := strings.Index(k[len(blockKey):], ".") - if nextDot < 0 { - continue - } - nextDot += len(blockKey) - candidateKeys[k[len(blockKey):nextDot]] = true - } - } - } - - for k, diff := range d.Attributes { - // helper/schema should not insert nil diff values, but don't panic - // if it does. - if diff == nil { - continue - } - - if strings.HasPrefix(k, blockKey) { - nextDot := strings.Index(k[len(blockKey):], ".") - if nextDot < 0 { - continue - } - - if diff.NewRemoved { - continue - } - - nextDot += len(blockKey) - candidateKeys[k[len(blockKey):nextDot]] = true - } - } - - // check each set candidate to see if it was removed. - // we need to do this, because when entire sets are removed, they may - // have the wrong key, and ony show diffs going to "" - if block.Nesting == configschema.NestingSet { - for k := range candidateKeys { - indexPrefix := strings.Join(append(path, n, k), ".") + "." - keep := false - // now check each set element to see if it's a new diff, or one - // that we're dropping. Since we're only applying the "New" - // portion of the set, we can ignore diffs that only contain "Old" - for attr, diff := range d.Attributes { - // helper/schema should not insert nil diff values, but don't panic - // if it does. - if diff == nil { - continue - } - - if !strings.HasPrefix(attr, indexPrefix) { - continue - } - - // check for empty "count" keys - if (strings.HasSuffix(attr, ".#") || strings.HasSuffix(attr, ".%")) && diff.New == "0" { - continue - } - - // removed items don't count either - if diff.NewRemoved { - continue - } - - // this must be a diff to keep - keep = true - break - } - if !keep { - delete(candidateKeys, k) - } - } - } - - for k := range candidateKeys { - newAttrs, err := d.applyBlockDiff(append(path, n, k), attrs, &block.Block) - if err != nil { - return result, err - } - - for attr, v := range newAttrs { - result[localBlockPrefix+attr] = v - } - } - - keepBlock := true - // check this block's count diff directly first, since we may not - // have candidates because it was removed and only set to "0" - if diff, ok := d.Attributes[blockKey+"#"]; ok { - if diff.New == "0" || diff.NewRemoved { - keepBlock = false - } - } - - // if there was no diff at all, then we need to keep the block attributes - if len(candidateKeys) == 0 && keepBlock { - for k, v := range attrs { - if strings.HasPrefix(k, blockKey) { - // we need the key relative to this block, so remove the - // entire prefix, then re-insert the block name. - localKey := localBlockPrefix + k[len(blockKey):] - result[localKey] = v - } - } - } - - countAddr := strings.Join(append(path, n, "#"), ".") - if countDiff, ok := d.Attributes[countAddr]; ok { - if countDiff.NewComputed { - result[localBlockPrefix+"#"] = hcl2shim.UnknownVariableValue - } else { - result[localBlockPrefix+"#"] = countDiff.New - - // While sets are complete, list are not, and we may not have all the - // information to track removals. If the list was truncated, we need to - // remove the extra items from the result. - if block.Nesting == configschema.NestingList && - countDiff.New != "" && countDiff.New != hcl2shim.UnknownVariableValue { - length, _ := strconv.Atoi(countDiff.New) - for k := range result { - if !strings.HasPrefix(k, localBlockPrefix) { - continue - } - - index := k[len(localBlockPrefix):] - nextDot := strings.Index(index, ".") - if nextDot < 1 { - continue - } - index = index[:nextDot] - i, err := strconv.Atoi(index) - if err != nil { - // this shouldn't happen since we added these - // ourself, but make note of it just in case. - log.Printf("[ERROR] bad list index in %q: %s", k, err) - continue - } - if i >= length { - delete(result, k) - } - } - } - } - } else if origCount, ok := attrs[countAddr]; ok && keepBlock { - result[localBlockPrefix+"#"] = origCount - } else { - result[localBlockPrefix+"#"] = countFlatmapContainerValues(localBlockPrefix+"#", result) - } - } - - return result, nil -} - -func (d *InstanceDiff) applyAttrDiff(path []string, attrs map[string]string, attrSchema *configschema.Attribute) (map[string]string, error) { - ty := attrSchema.Type - switch { - case ty.IsListType(), ty.IsTupleType(), ty.IsMapType(): - return d.applyCollectionDiff(path, attrs, attrSchema) - case ty.IsSetType(): - return d.applySetDiff(path, attrs, attrSchema) - default: - return d.applySingleAttrDiff(path, attrs, attrSchema) - } -} - -func (d *InstanceDiff) applySingleAttrDiff(path []string, attrs map[string]string, attrSchema *configschema.Attribute) (map[string]string, error) { - currentKey := strings.Join(path, ".") - - attr := path[len(path)-1] - - result := map[string]string{} - diff := d.Attributes[currentKey] - old, exists := attrs[currentKey] - - if diff != nil && diff.NewComputed { - result[attr] = hcl2shim.UnknownVariableValue - return result, nil - } - - // "id" must exist and not be an empty string, or it must be unknown. - // This only applied to top-level "id" fields. - if attr == "id" && len(path) == 1 { - if old == "" { - result[attr] = hcl2shim.UnknownVariableValue - } else { - result[attr] = old - } - return result, nil - } - - // attribute diffs are sometimes missed, so assume no diff means keep the - // old value - if diff == nil { - if exists { - result[attr] = old - } else { - // We need required values, so set those with an empty value. It - // must be set in the config, since if it were missing it would have - // failed validation. - if attrSchema.Required { - // we only set a missing string here, since bool or number types - // would have distinct zero value which shouldn't have been - // lost. - if attrSchema.Type == cty.String { - result[attr] = "" - } - } - } - return result, nil - } - - // check for missmatched diff values - if exists && - old != diff.Old && - old != hcl2shim.UnknownVariableValue && - diff.Old != hcl2shim.UnknownVariableValue { - return result, fmt.Errorf("diff apply conflict for %s: diff expects %q, but prior value has %q", attr, diff.Old, old) - } - - if diff.NewRemoved { - // don't set anything in the new value - return map[string]string{}, nil - } - - if diff.Old == diff.New && diff.New == "" { - // this can only be a valid empty string - if attrSchema.Type == cty.String { - result[attr] = "" - } - return result, nil - } - - if attrSchema.Computed && diff.NewComputed { - result[attr] = hcl2shim.UnknownVariableValue - return result, nil - } - - result[attr] = diff.New - - return result, nil -} - -func (d *InstanceDiff) applyCollectionDiff(path []string, attrs map[string]string, attrSchema *configschema.Attribute) (map[string]string, error) { - result := map[string]string{} - - prefix := "" - if len(path) > 1 { - prefix = strings.Join(path[:len(path)-1], ".") + "." - } - - name := "" - if len(path) > 0 { - name = path[len(path)-1] - } - - currentKey := prefix + name - - // check the index first for special handling - for k, diff := range d.Attributes { - // check the index value, which can be set, and 0 - if k == currentKey+".#" || k == currentKey+".%" || k == currentKey { - if diff.NewRemoved { - return result, nil - } - - if diff.NewComputed { - result[k[len(prefix):]] = hcl2shim.UnknownVariableValue - return result, nil - } - - // do what the diff tells us to here, so that it's consistent with applies - if diff.New == "0" { - result[k[len(prefix):]] = "0" - return result, nil - } - } - } - - // collect all the keys from the diff and the old state - noDiff := true - keys := map[string]bool{} - for k := range d.Attributes { - if !strings.HasPrefix(k, currentKey+".") { - continue - } - noDiff = false - keys[k] = true - } - - noAttrs := true - for k := range attrs { - if !strings.HasPrefix(k, currentKey+".") { - continue - } - noAttrs = false - keys[k] = true - } - - // If there's no diff and no attrs, then there's no value at all. - // This prevents an unexpected zero-count attribute in the attributes. - if noDiff && noAttrs { - return result, nil - } - - idx := "#" - if attrSchema.Type.IsMapType() { - idx = "%" - } - - for k := range keys { - // generate an schema placeholder for the values - elSchema := &configschema.Attribute{ - Type: attrSchema.Type.ElementType(), - } - - res, err := d.applySingleAttrDiff(append(path, k[len(currentKey)+1:]), attrs, elSchema) - if err != nil { - return result, err - } - - for k, v := range res { - result[name+"."+k] = v - } - } - - // Just like in nested list blocks, for simple lists we may need to fill in - // missing empty strings. - countKey := name + "." + idx - count := result[countKey] - length, _ := strconv.Atoi(count) - - if count != "" && count != hcl2shim.UnknownVariableValue && - attrSchema.Type.Equals(cty.List(cty.String)) { - // insert empty strings into missing indexes - for i := 0; i < length; i++ { - key := fmt.Sprintf("%s.%d", name, i) - if _, ok := result[key]; !ok { - result[key] = "" - } - } - } - - // now check for truncation in any type of list - if attrSchema.Type.IsListType() { - for key := range result { - if key == countKey { - continue - } - - if len(key) <= len(name)+1 { - // not sure what this is, but don't panic - continue - } - - index := key[len(name)+1:] - - // It is possible to have nested sets or maps, so look for another dot - dot := strings.Index(index, ".") - if dot > 0 { - index = index[:dot] - } - - // This shouldn't have any more dots, since the element type is only string. - num, err := strconv.Atoi(index) - if err != nil { - log.Printf("[ERROR] bad list index in %q: %s", currentKey, err) - continue - } - - if num >= length { - delete(result, key) - } - } - } - - // Fill in the count value if it wasn't present in the diff for some reason, - // or if there is no count at all. - _, countDiff := d.Attributes[countKey] - if result[countKey] == "" || (!countDiff && len(keys) != len(result)) { - result[countKey] = countFlatmapContainerValues(countKey, result) - } - - return result, nil -} - -func (d *InstanceDiff) applySetDiff(path []string, attrs map[string]string, attrSchema *configschema.Attribute) (map[string]string, error) { - // We only need this special behavior for sets of object. - if !attrSchema.Type.ElementType().IsObjectType() { - // The normal collection apply behavior will work okay for this one, then. - return d.applyCollectionDiff(path, attrs, attrSchema) - } - - // When we're dealing with a set of an object type we actually want to - // use our normal _block type_ apply behaviors, so we'll construct ourselves - // a synthetic schema that treats the object type as a block type and - // then delegate to our block apply method. - synthSchema := &configschema.Block{ - Attributes: make(map[string]*configschema.Attribute), - } - - for name, ty := range attrSchema.Type.ElementType().AttributeTypes() { - // We can safely make everything into an attribute here because in the - // event that there are nested set attributes we'll end up back in - // here again recursively and can then deal with the next level of - // expansion. - synthSchema.Attributes[name] = &configschema.Attribute{ - Type: ty, - Optional: true, - } - } - - parentPath := path[:len(path)-1] - childName := path[len(path)-1] - containerSchema := &configschema.Block{ - BlockTypes: map[string]*configschema.NestedBlock{ - childName: { - Nesting: configschema.NestingSet, - Block: *synthSchema, - }, - }, - } - - return d.applyBlockDiff(parentPath, attrs, containerSchema) -} - -// countFlatmapContainerValues returns the number of values in the flatmapped container -// (set, map, list) indexed by key. The key argument is expected to include the -// trailing ".#", or ".%". -func countFlatmapContainerValues(key string, attrs map[string]string) string { - if len(key) < 3 || !(strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%")) { - panic(fmt.Sprintf("invalid index value %q", key)) - } - - prefix := key[:len(key)-1] - items := map[string]int{} - - for k := range attrs { - if k == key { - continue - } - if !strings.HasPrefix(k, prefix) { - continue - } - - suffix := k[len(prefix):] - dot := strings.Index(suffix, ".") - if dot > 0 { - suffix = suffix[:dot] - } - - items[suffix]++ - } - return strconv.Itoa(len(items)) -} - -// ResourceAttrDiff is the diff of a single attribute of a resource. -type ResourceAttrDiff struct { - Old string // Old Value - New string // New Value - NewComputed bool // True if new value is computed (unknown currently) - NewRemoved bool // True if this attribute is being removed - NewExtra interface{} // Extra information for the provider - RequiresNew bool // True if change requires new resource - Sensitive bool // True if the data should not be displayed in UI output - Type DiffAttrType -} - -// Empty returns true if the diff for this attr is neutral -func (d *ResourceAttrDiff) Empty() bool { - return d.Old == d.New && !d.NewComputed && !d.NewRemoved -} - -func (d *ResourceAttrDiff) GoString() string { - return fmt.Sprintf("*%#v", *d) -} - -// DiffAttrType is an enum type that says whether a resource attribute -// diff is an input attribute (comes from the configuration) or an -// output attribute (comes as a result of applying the configuration). An -// example input would be "ami" for AWS and an example output would be -// "private_ip". -type DiffAttrType byte - -const ( - DiffAttrUnknown DiffAttrType = iota - DiffAttrInput - DiffAttrOutput -) - -func (d *InstanceDiff) init() { - if d.Attributes == nil { - d.Attributes = make(map[string]*ResourceAttrDiff) - } -} - -func NewInstanceDiff() *InstanceDiff { - return &InstanceDiff{Attributes: make(map[string]*ResourceAttrDiff)} -} - -func (d *InstanceDiff) Copy() (*InstanceDiff, error) { - if d == nil { - return nil, nil - } - - dCopy, err := copystructure.Config{Lock: true}.Copy(d) - if err != nil { - return nil, err - } - - return dCopy.(*InstanceDiff), nil -} - -// ChangeType returns the DiffChangeType represented by the diff -// for this single instance. -func (d *InstanceDiff) ChangeType() DiffChangeType { - if d.Empty() { - return DiffNone - } - - if d.RequiresNew() && (d.GetDestroy() || d.GetDestroyTainted()) { - return DiffDestroyCreate - } - - if d.GetDestroy() || d.GetDestroyDeposed() { - return DiffDestroy - } - - if d.RequiresNew() { - return DiffCreate - } - - return DiffUpdate -} - -// Empty returns true if this diff encapsulates no changes. -func (d *InstanceDiff) Empty() bool { - if d == nil { - return true - } - - d.mu.Lock() - defer d.mu.Unlock() - return !d.Destroy && - !d.DestroyTainted && - !d.DestroyDeposed && - len(d.Attributes) == 0 -} - -// Equal compares two diffs for exact equality. -// -// This is different from the Same comparison that is supported which -// checks for operation equality taking into account computed values. Equal -// instead checks for exact equality. -func (d *InstanceDiff) Equal(d2 *InstanceDiff) bool { - // If one is nil, they must both be nil - if d == nil || d2 == nil { - return d == d2 - } - - // Use DeepEqual - return reflect.DeepEqual(d, d2) -} - -// DeepCopy performs a deep copy of all parts of the InstanceDiff -func (d *InstanceDiff) DeepCopy() *InstanceDiff { - copy, err := copystructure.Config{Lock: true}.Copy(d) - if err != nil { - panic(err) - } - - return copy.(*InstanceDiff) -} - -func (d *InstanceDiff) GoString() string { - return fmt.Sprintf("*%#v", InstanceDiff{ - Attributes: d.Attributes, - Destroy: d.Destroy, - DestroyTainted: d.DestroyTainted, - DestroyDeposed: d.DestroyDeposed, - }) -} - -// RequiresNew returns true if the diff requires the creation of a new -// resource (implying the destruction of the old). -func (d *InstanceDiff) RequiresNew() bool { - if d == nil { - return false - } - - d.mu.Lock() - defer d.mu.Unlock() - - return d.requiresNew() -} - -func (d *InstanceDiff) requiresNew() bool { - if d == nil { - return false - } - - if d.DestroyTainted { - return true - } - - for _, rd := range d.Attributes { - if rd != nil && rd.RequiresNew { - return true - } - } - - return false -} - -func (d *InstanceDiff) GetDestroyDeposed() bool { - d.mu.Lock() - defer d.mu.Unlock() - - return d.DestroyDeposed -} - -func (d *InstanceDiff) SetDestroyDeposed(b bool) { - d.mu.Lock() - defer d.mu.Unlock() - - d.DestroyDeposed = b -} - -// These methods are properly locked, for use outside other InstanceDiff -// methods but everywhere else within the terraform package. -// TODO refactor the locking scheme -func (d *InstanceDiff) SetTainted(b bool) { - d.mu.Lock() - defer d.mu.Unlock() - - d.DestroyTainted = b -} - -func (d *InstanceDiff) GetDestroyTainted() bool { - d.mu.Lock() - defer d.mu.Unlock() - - return d.DestroyTainted -} - -func (d *InstanceDiff) SetDestroy(b bool) { - d.mu.Lock() - defer d.mu.Unlock() - - d.Destroy = b -} - -func (d *InstanceDiff) GetDestroy() bool { - d.mu.Lock() - defer d.mu.Unlock() - - return d.Destroy -} - -func (d *InstanceDiff) SetAttribute(key string, attr *ResourceAttrDiff) { - d.mu.Lock() - defer d.mu.Unlock() - - d.Attributes[key] = attr -} - -func (d *InstanceDiff) DelAttribute(key string) { - d.mu.Lock() - defer d.mu.Unlock() - - delete(d.Attributes, key) -} - -func (d *InstanceDiff) GetAttribute(key string) (*ResourceAttrDiff, bool) { - d.mu.Lock() - defer d.mu.Unlock() - - attr, ok := d.Attributes[key] - return attr, ok -} -func (d *InstanceDiff) GetAttributesLen() int { - d.mu.Lock() - defer d.mu.Unlock() - - return len(d.Attributes) -} - -// Safely copies the Attributes map -func (d *InstanceDiff) CopyAttributes() map[string]*ResourceAttrDiff { - d.mu.Lock() - defer d.mu.Unlock() - - attrs := make(map[string]*ResourceAttrDiff) - for k, v := range d.Attributes { - attrs[k] = v - } - - return attrs -} - -// Same checks whether or not two InstanceDiff's are the "same". When -// we say "same", it is not necessarily exactly equal. Instead, it is -// just checking that the same attributes are changing, a destroy -// isn't suddenly happening, etc. -func (d *InstanceDiff) Same(d2 *InstanceDiff) (bool, string) { - // we can safely compare the pointers without a lock - switch { - case d == nil && d2 == nil: - return true, "" - case d == nil || d2 == nil: - return false, "one nil" - case d == d2: - return true, "" - } - - d.mu.Lock() - defer d.mu.Unlock() - - // If we're going from requiring new to NOT requiring new, then we have - // to see if all required news were computed. If so, it is allowed since - // computed may also mean "same value and therefore not new". - oldNew := d.requiresNew() - newNew := d2.RequiresNew() - if oldNew && !newNew { - oldNew = false - - // This section builds a list of ignorable attributes for requiresNew - // by removing off any elements of collections going to zero elements. - // For collections going to zero, they may not exist at all in the - // new diff (and hence RequiresNew == false). - ignoreAttrs := make(map[string]struct{}) - for k, diffOld := range d.Attributes { - if !strings.HasSuffix(k, ".%") && !strings.HasSuffix(k, ".#") { - continue - } - - // This case is in here as a protection measure. The bug that this - // code originally fixed (GH-11349) didn't have to deal with computed - // so I'm not 100% sure what the correct behavior is. Best to leave - // the old behavior. - if diffOld.NewComputed { - continue - } - - // We're looking for the case a map goes to exactly 0. - if diffOld.New != "0" { - continue - } - - // Found it! Ignore all of these. The prefix here is stripping - // off the "%" so it is just "k." - prefix := k[:len(k)-1] - for k2 := range d.Attributes { - if strings.HasPrefix(k2, prefix) { - ignoreAttrs[k2] = struct{}{} - } - } - } - - for k, rd := range d.Attributes { - if _, ok := ignoreAttrs[k]; ok { - continue - } - - // If the field is requires new and NOT computed, then what - // we have is a diff mismatch for sure. We set that the old - // diff does REQUIRE a ForceNew. - if rd != nil && rd.RequiresNew && !rd.NewComputed { - oldNew = true - break - } - } - } - - if oldNew != newNew { - return false, fmt.Sprintf( - "diff RequiresNew; old: %t, new: %t", oldNew, newNew) - } - - // Verify that destroy matches. The second boolean here allows us to - // have mismatching Destroy if we're moving from RequiresNew true - // to false above. Therefore, the second boolean will only pass if - // we're moving from Destroy: true to false as well. - if d.Destroy != d2.GetDestroy() && d.requiresNew() == oldNew { - return false, fmt.Sprintf( - "diff: Destroy; old: %t, new: %t", d.Destroy, d2.GetDestroy()) - } - - // Go through the old diff and make sure the new diff has all the - // same attributes. To start, build up the check map to be all the keys. - checkOld := make(map[string]struct{}) - checkNew := make(map[string]struct{}) - for k := range d.Attributes { - checkOld[k] = struct{}{} - } - for k := range d2.CopyAttributes() { - checkNew[k] = struct{}{} - } - - // Make an ordered list so we are sure the approximated hashes are left - // to process at the end of the loop - keys := make([]string, 0, len(d.Attributes)) - for k := range d.Attributes { - keys = append(keys, k) - } - sort.StringSlice(keys).Sort() - - for _, k := range keys { - diffOld := d.Attributes[k] - - if _, ok := checkOld[k]; !ok { - // We're not checking this key for whatever reason (see where - // check is modified). - continue - } - - // Remove this key since we'll never hit it again - delete(checkOld, k) - delete(checkNew, k) - - _, ok := d2.GetAttribute(k) - if !ok { - // If there's no new attribute, and the old diff expected the attribute - // to be removed, that's just fine. - if diffOld.NewRemoved { - continue - } - - // If the last diff was a computed value then the absense of - // that value is allowed since it may mean the value ended up - // being the same. - if diffOld.NewComputed { - ok = true - } - - // No exact match, but maybe this is a set containing computed - // values. So check if there is an approximate hash in the key - // and if so, try to match the key. - if strings.Contains(k, "~") { - parts := strings.Split(k, ".") - parts2 := append([]string(nil), parts...) - - re := regexp.MustCompile(`^~\d+$`) - for i, part := range parts { - if re.MatchString(part) { - // we're going to consider this the base of a - // computed hash, and remove all longer matching fields - ok = true - - parts2[i] = `\d+` - parts2 = parts2[:i+1] - break - } - } - - re, err := regexp.Compile("^" + strings.Join(parts2, `\.`)) - if err != nil { - return false, fmt.Sprintf("regexp failed to compile; err: %#v", err) - } - - for k2 := range checkNew { - if re.MatchString(k2) { - delete(checkNew, k2) - } - } - } - - // This is a little tricky, but when a diff contains a computed - // list, set, or map that can only be interpolated after the apply - // command has created the dependent resources, it could turn out - // that the result is actually the same as the existing state which - // would remove the key from the diff. - if diffOld.NewComputed && (strings.HasSuffix(k, ".#") || strings.HasSuffix(k, ".%")) { - ok = true - } - - // Similarly, in a RequiresNew scenario, a list that shows up in the plan - // diff can disappear from the apply diff, which is calculated from an - // empty state. - if d.requiresNew() && (strings.HasSuffix(k, ".#") || strings.HasSuffix(k, ".%")) { - ok = true - } - - if !ok { - return false, fmt.Sprintf("attribute mismatch: %s", k) - } - } - - // search for the suffix of the base of a [computed] map, list or set. - match := multiVal.FindStringSubmatch(k) - - if diffOld.NewComputed && len(match) == 2 { - matchLen := len(match[1]) - - // This is a computed list, set, or map, so remove any keys with - // this prefix from the check list. - kprefix := k[:len(k)-matchLen] - for k2 := range checkOld { - if strings.HasPrefix(k2, kprefix) { - delete(checkOld, k2) - } - } - for k2 := range checkNew { - if strings.HasPrefix(k2, kprefix) { - delete(checkNew, k2) - } - } - } - - // We don't compare the values because we can't currently actually - // guarantee to generate the same value two two diffs created from - // the same state+config: we have some pesky interpolation functions - // that do not behave as pure functions (uuid, timestamp) and so they - // can be different each time a diff is produced. - // FIXME: Re-organize our config handling so that we don't re-evaluate - // expressions when we produce a second comparison diff during - // apply (for EvalCompareDiff). - } - - // Check for leftover attributes - if len(checkNew) > 0 { - extras := make([]string, 0, len(checkNew)) - for attr := range checkNew { - extras = append(extras, attr) - } - return false, - fmt.Sprintf("extra attributes: %s", strings.Join(extras, ", ")) - } - - return true, "" -} - -// moduleDiffSort implements sort.Interface to sort module diffs by path. -type moduleDiffSort []*ModuleDiff - -func (s moduleDiffSort) Len() int { return len(s) } -func (s moduleDiffSort) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s moduleDiffSort) Less(i, j int) bool { - a := s[i] - b := s[j] - - // If the lengths are different, then the shorter one always wins - if len(a.Path) != len(b.Path) { - return len(a.Path) < len(b.Path) - } - - // Otherwise, compare lexically - return strings.Join(a.Path, ".") < strings.Join(b.Path, ".") -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/edge_destroy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/edge_destroy.go deleted file mode 100644 index 17464bc0638..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/edge_destroy.go +++ /dev/null @@ -1,17 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// DestroyEdge is an edge that represents a standard "destroy" relationship: -// Target depends on Source because Source is destroying. -type DestroyEdge struct { - S, T dag.Vertex -} - -func (e *DestroyEdge) Hashcode() interface{} { return fmt.Sprintf("%p-%p", e.S, e.T) } -func (e *DestroyEdge) Source() dag.Vertex { return e.S } -func (e *DestroyEdge) Target() dag.Vertex { return e.T } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval.go deleted file mode 100644 index c490c3bcffb..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval.go +++ /dev/null @@ -1,70 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalNode is the interface that must be implemented by graph nodes to -// evaluate/execute. -type EvalNode interface { - // Eval evaluates this node with the given context. The second parameter - // are the argument values. These will match in order and 1-1 with the - // results of the Args() return value. - Eval(EvalContext) (interface{}, error) -} - -// GraphNodeEvalable is the interface that graph nodes must implement -// to enable valuation. -type GraphNodeEvalable interface { - EvalTree() EvalNode -} - -// EvalEarlyExitError is a special error return value that can be returned -// by eval nodes that does an early exit. -type EvalEarlyExitError struct{} - -func (EvalEarlyExitError) Error() string { return "early exit" } - -// Eval evaluates the given EvalNode with the given context, properly -// evaluating all args in the correct order. -func Eval(n EvalNode, ctx EvalContext) (interface{}, error) { - // Call the lower level eval which doesn't understand early exit, - // and if we early exit, it isn't an error. - result, err := EvalRaw(n, ctx) - if err != nil { - if _, ok := err.(EvalEarlyExitError); ok { - return nil, nil - } - } - - return result, err -} - -// EvalRaw is like Eval except that it returns all errors, even if they -// signal something normal such as EvalEarlyExitError. -func EvalRaw(n EvalNode, ctx EvalContext) (interface{}, error) { - path := "unknown" - if ctx != nil { - path = ctx.Path().String() - } - if path == "" { - path = "" - } - - log.Printf("[TRACE] %s: eval: %T", path, n) - output, err := n.Eval(ctx) - if err != nil { - switch err.(type) { - case EvalEarlyExitError: - log.Printf("[TRACE] %s: eval: %T, early exit err: %s", path, n, err) - case tfdiags.NonFatalError: - log.Printf("[WARN] %s: eval: %T, non-fatal err: %s", path, n, err) - default: - log.Printf("[ERROR] %s: eval: %T, err: %s", path, n, err) - } - } - - return output, err -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_apply.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_apply.go deleted file mode 100644 index 6beeaea984f..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_apply.go +++ /dev/null @@ -1,656 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - "strings" - - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalApply is an EvalNode implementation that writes the diff to -// the full diff. -type EvalApply struct { - Addr addrs.ResourceInstance - Config *configs.Resource - Dependencies []addrs.Referenceable - State **states.ResourceInstanceObject - Change **plans.ResourceInstanceChange - ProviderAddr addrs.AbsProviderConfig - Provider *providers.Interface - ProviderSchema **ProviderSchema - Output **states.ResourceInstanceObject - CreateNew *bool - Error *error -} - -// TODO: test -func (n *EvalApply) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - - change := *n.Change - provider := *n.Provider - state := *n.State - absAddr := n.Addr.Absolute(ctx.Path()) - - if state == nil { - state = &states.ResourceInstanceObject{} - } - - schema, _ := (*n.ProviderSchema).SchemaForResourceType(n.Addr.Resource.Mode, n.Addr.Resource.Type) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support resource type %q", n.Addr.Resource.Type) - } - - if n.CreateNew != nil { - *n.CreateNew = (change.Action == plans.Create || change.Action.IsReplace()) - } - - configVal := cty.NullVal(cty.DynamicPseudoType) - if n.Config != nil { - var configDiags tfdiags.Diagnostics - forEach, _ := evaluateResourceForEachExpression(n.Config.ForEach, ctx) - keyData := EvalDataForInstanceKey(n.Addr.Key, forEach) - configVal, _, configDiags = ctx.EvaluateBlock(n.Config.Config, schema, nil, keyData) - diags = diags.Append(configDiags) - if configDiags.HasErrors() { - return nil, diags.Err() - } - } - - if !configVal.IsWhollyKnown() { - return nil, fmt.Errorf( - "configuration for %s still contains unknown values during apply (this is a bug in Terraform; please report it!)", - absAddr, - ) - } - - log.Printf("[DEBUG] %s: applying the planned %s change", n.Addr.Absolute(ctx.Path()), change.Action) - resp := provider.ApplyResourceChange(providers.ApplyResourceChangeRequest{ - TypeName: n.Addr.Resource.Type, - PriorState: change.Before, - Config: configVal, - PlannedState: change.After, - PlannedPrivate: change.Private, - }) - applyDiags := resp.Diagnostics - if n.Config != nil { - applyDiags = applyDiags.InConfigBody(n.Config.Config) - } - diags = diags.Append(applyDiags) - - // Even if there are errors in the returned diagnostics, the provider may - // have returned a _partial_ state for an object that already exists but - // failed to fully configure, and so the remaining code must always run - // to completion but must be defensive against the new value being - // incomplete. - newVal := resp.NewState - - if newVal == cty.NilVal { - // Providers are supposed to return a partial new value even when errors - // occur, but sometimes they don't and so in that case we'll patch that up - // by just using the prior state, so we'll at least keep track of the - // object for the user to retry. - newVal = change.Before - - // As a special case, we'll set the new value to null if it looks like - // we were trying to execute a delete, because the provider in this case - // probably left the newVal unset intending it to be interpreted as "null". - if change.After.IsNull() { - newVal = cty.NullVal(schema.ImpliedType()) - } - - // Ideally we'd produce an error or warning here if newVal is nil and - // there are no errors in diags, because that indicates a buggy - // provider not properly reporting its result, but unfortunately many - // of our historical test mocks behave in this way and so producing - // a diagnostic here fails hundreds of tests. Instead, we must just - // silently retain the old value for now. Returning a nil value with - // no errors is still always considered a bug in the provider though, - // and should be fixed for any "real" providers that do it. - } - - var conformDiags tfdiags.Diagnostics - for _, err := range newVal.Type().TestConformance(schema.ImpliedType()) { - conformDiags = conformDiags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid object", - fmt.Sprintf( - "Provider %q produced an invalid value after apply for %s. The result cannot not be saved in the Terraform state.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatErrorPrefixed(err, absAddr.String()), - ), - )) - } - diags = diags.Append(conformDiags) - if conformDiags.HasErrors() { - // Bail early in this particular case, because an object that doesn't - // conform to the schema can't be saved in the state anyway -- the - // serializer will reject it. - return nil, diags.Err() - } - - // After this point we have a type-conforming result object and so we - // must always run to completion to ensure it can be saved. If n.Error - // is set then we must not return a non-nil error, in order to allow - // evaluation to continue to a later point where our state object will - // be saved. - - // By this point there must not be any unknown values remaining in our - // object, because we've applied the change and we can't save unknowns - // in our persistent state. If any are present then we will indicate an - // error (which is always a bug in the provider) but we will also replace - // them with nulls so that we can successfully save the portions of the - // returned value that are known. - if !newVal.IsWhollyKnown() { - // To generate better error messages, we'll go for a walk through the - // value and make a separate diagnostic for each unknown value we - // find. - cty.Walk(newVal, func(path cty.Path, val cty.Value) (bool, error) { - if !val.IsKnown() { - pathStr := tfdiags.FormatCtyPath(path) - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider returned invalid result object after apply", - fmt.Sprintf( - "After the apply operation, the provider still indicated an unknown value for %s%s. All values must be known after apply, so this is always a bug in the provider and should be reported in the provider's own repository. Terraform will still save the other known object values in the state.", - n.Addr.Absolute(ctx.Path()), pathStr, - ), - )) - } - return true, nil - }) - - // NOTE: This operation can potentially be lossy if there are multiple - // elements in a set that differ only by unknown values: after - // replacing with null these will be merged together into a single set - // element. Since we can only get here in the presence of a provider - // bug, we accept this because storing a result here is always a - // best-effort sort of thing. - newVal = cty.UnknownAsNull(newVal) - } - - if change.Action != plans.Delete && !diags.HasErrors() { - // Only values that were marked as unknown in the planned value are allowed - // to change during the apply operation. (We do this after the unknown-ness - // check above so that we also catch anything that became unknown after - // being known during plan.) - // - // If we are returning other errors anyway then we'll give this - // a pass since the other errors are usually the explanation for - // this one and so it's more helpful to let the user focus on the - // root cause rather than distract with this extra problem. - if errs := objchange.AssertObjectCompatible(schema, change.After, newVal); len(errs) > 0 { - if resp.LegacyTypeSystem { - // The shimming of the old type system in the legacy SDK is not precise - // enough to pass this consistency check, so we'll give it a pass here, - // but we will generate a warning about it so that we are more likely - // to notice in the logs if an inconsistency beyond the type system - // leads to a downstream provider failure. - var buf strings.Builder - fmt.Fprintf(&buf, "[WARN] Provider %q produced an unexpected new value for %s, but we are tolerating it because it is using the legacy plugin SDK.\n The following problems may be the cause of any confusing errors from downstream operations:", n.ProviderAddr.ProviderConfig.Type, absAddr) - for _, err := range errs { - fmt.Fprintf(&buf, "\n - %s", tfdiags.FormatError(err)) - } - log.Print(buf.String()) - - // The sort of inconsistency we won't catch here is if a known value - // in the plan is changed during apply. That can cause downstream - // problems because a dependent resource would make its own plan based - // on the planned value, and thus get a different result during the - // apply phase. This will usually lead to a "Provider produced invalid plan" - // error that incorrectly blames the downstream resource for the change. - - } else { - for _, err := range errs { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced inconsistent result after apply", - fmt.Sprintf( - "When applying changes to %s, provider %q produced an unexpected new value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - absAddr, n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatError(err), - ), - )) - } - } - } - } - - // If a provider returns a null or non-null object at the wrong time then - // we still want to save that but it often causes some confusing behaviors - // where it seems like Terraform is failing to take any action at all, - // so we'll generate some errors to draw attention to it. - if !diags.HasErrors() { - if change.Action == plans.Delete && !newVal.IsNull() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider returned invalid result object after apply", - fmt.Sprintf( - "After applying a %s plan, the provider returned a non-null object for %s. Destroying should always produce a null value, so this is always a bug in the provider and should be reported in the provider's own repository. Terraform will still save this errant object in the state for debugging and recovery.", - change.Action, n.Addr.Absolute(ctx.Path()), - ), - )) - } - if change.Action != plans.Delete && newVal.IsNull() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider returned invalid result object after apply", - fmt.Sprintf( - "After applying a %s plan, the provider returned a null object for %s. Only destroying should always produce a null value, so this is always a bug in the provider and should be reported in the provider's own repository.", - change.Action, n.Addr.Absolute(ctx.Path()), - ), - )) - } - } - - // Sometimes providers return a null value when an operation fails for some - // reason, but we'd rather keep the prior state so that the error can be - // corrected on a subsequent run. We must only do this for null new value - // though, or else we may discard partial updates the provider was able to - // complete. - if diags.HasErrors() && newVal.IsNull() { - // Otherwise, we'll continue but using the prior state as the new value, - // making this effectively a no-op. If the item really _has_ been - // deleted then our next refresh will detect that and fix it up. - // If change.Action is Create then change.Before will also be null, - // which is fine. - newVal = change.Before - } - - var newState *states.ResourceInstanceObject - if !newVal.IsNull() { // null value indicates that the object is deleted, so we won't set a new state in that case - newState = &states.ResourceInstanceObject{ - Status: states.ObjectReady, - Value: newVal, - Private: resp.Private, - Dependencies: n.Dependencies, // Should be populated by the caller from the StateDependencies method on the resource instance node - } - } - - // Write the final state - if n.Output != nil { - *n.Output = newState - } - - if diags.HasErrors() { - // If the caller provided an error pointer then they are expected to - // handle the error some other way and we treat our own result as - // success. - if n.Error != nil { - err := diags.Err() - *n.Error = err - log.Printf("[DEBUG] %s: apply errored, but we're indicating that via the Error pointer rather than returning it: %s", n.Addr.Absolute(ctx.Path()), err) - return nil, nil - } - } - - return nil, diags.ErrWithWarnings() -} - -// EvalApplyPre is an EvalNode implementation that does the pre-Apply work -type EvalApplyPre struct { - Addr addrs.ResourceInstance - Gen states.Generation - State **states.ResourceInstanceObject - Change **plans.ResourceInstanceChange -} - -// TODO: test -func (n *EvalApplyPre) Eval(ctx EvalContext) (interface{}, error) { - change := *n.Change - absAddr := n.Addr.Absolute(ctx.Path()) - - if change == nil { - panic(fmt.Sprintf("EvalApplyPre for %s called with nil Change", absAddr)) - } - - if resourceHasUserVisibleApply(n.Addr) { - priorState := change.Before - plannedNewState := change.After - - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreApply(absAddr, n.Gen, change.Action, priorState, plannedNewState) - }) - if err != nil { - return nil, err - } - } - - return nil, nil -} - -// EvalApplyPost is an EvalNode implementation that does the post-Apply work -type EvalApplyPost struct { - Addr addrs.ResourceInstance - Gen states.Generation - State **states.ResourceInstanceObject - Error *error -} - -// TODO: test -func (n *EvalApplyPost) Eval(ctx EvalContext) (interface{}, error) { - state := *n.State - - if resourceHasUserVisibleApply(n.Addr) { - absAddr := n.Addr.Absolute(ctx.Path()) - var newState cty.Value - if state != nil { - newState = state.Value - } else { - newState = cty.NullVal(cty.DynamicPseudoType) - } - var err error - if n.Error != nil { - err = *n.Error - } - - hookErr := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostApply(absAddr, n.Gen, newState, err) - }) - if hookErr != nil { - return nil, hookErr - } - } - - return nil, *n.Error -} - -// EvalMaybeTainted is an EvalNode that takes the planned change, new value, -// and possible error from an apply operation and produces a new instance -// object marked as tainted if it appears that a create operation has failed. -// -// This EvalNode never returns an error, to ensure that a subsequent EvalNode -// can still record the possibly-tainted object in the state. -type EvalMaybeTainted struct { - Addr addrs.ResourceInstance - Gen states.Generation - Change **plans.ResourceInstanceChange - State **states.ResourceInstanceObject - Error *error - - // If StateOutput is not nil, its referent will be assigned either the same - // pointer as State or a new object with its status set as Tainted, - // depending on whether an error is given and if this was a create action. - StateOutput **states.ResourceInstanceObject -} - -// TODO: test -func (n *EvalMaybeTainted) Eval(ctx EvalContext) (interface{}, error) { - state := *n.State - change := *n.Change - err := *n.Error - - if state != nil && state.Status == states.ObjectTainted { - log.Printf("[TRACE] EvalMaybeTainted: %s was already tainted, so nothing to do", n.Addr.Absolute(ctx.Path())) - return nil, nil - } - - if n.StateOutput != nil { - if err != nil && change.Action == plans.Create { - // If there are errors during a _create_ then the object is - // in an undefined state, and so we'll mark it as tainted so - // we can try again on the next run. - // - // We don't do this for other change actions because errors - // during updates will often not change the remote object at all. - // If there _were_ changes prior to the error, it's the provider's - // responsibility to record the effect of those changes in the - // object value it returned. - log.Printf("[TRACE] EvalMaybeTainted: %s encountered an error during creation, so it is now marked as tainted", n.Addr.Absolute(ctx.Path())) - *n.StateOutput = state.AsTainted() - } else { - *n.StateOutput = state - } - } - - return nil, nil -} - -// resourceHasUserVisibleApply returns true if the given resource is one where -// apply actions should be exposed to the user. -// -// Certain resources do apply actions only as an implementation detail, so -// these should not be advertised to code outside of this package. -func resourceHasUserVisibleApply(addr addrs.ResourceInstance) bool { - // Only managed resources have user-visible apply actions. - // In particular, this excludes data resources since we "apply" these - // only as an implementation detail of removing them from state when - // they are destroyed. (When reading, they don't get here at all because - // we present them as "Refresh" actions.) - return addr.ContainingResource().Mode == addrs.ManagedResourceMode -} - -// EvalApplyProvisioners is an EvalNode implementation that executes -// the provisioners for a resource. -// -// TODO(mitchellh): This should probably be split up into a more fine-grained -// ApplyProvisioner (single) that is looped over. -type EvalApplyProvisioners struct { - Addr addrs.ResourceInstance - State **states.ResourceInstanceObject - ResourceConfig *configs.Resource - CreateNew *bool - Error *error - - // When is the type of provisioner to run at this point - When configs.ProvisionerWhen -} - -// TODO: test -func (n *EvalApplyProvisioners) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - state := *n.State - if state == nil { - log.Printf("[TRACE] EvalApplyProvisioners: %s has no state, so skipping provisioners", n.Addr) - return nil, nil - } - if n.When == configs.ProvisionerWhenCreate && n.CreateNew != nil && !*n.CreateNew { - // If we're not creating a new resource, then don't run provisioners - log.Printf("[TRACE] EvalApplyProvisioners: %s is not freshly-created, so no provisioning is required", n.Addr) - return nil, nil - } - if state.Status == states.ObjectTainted { - // No point in provisioning an object that is already tainted, since - // it's going to get recreated on the next apply anyway. - log.Printf("[TRACE] EvalApplyProvisioners: %s is tainted, so skipping provisioning", n.Addr) - return nil, nil - } - - provs := n.filterProvisioners() - if len(provs) == 0 { - // We have no provisioners, so don't do anything - return nil, nil - } - - if n.Error != nil && *n.Error != nil { - // We're already tainted, so just return out - return nil, nil - } - - { - // Call pre hook - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreProvisionInstance(absAddr, state.Value) - }) - if err != nil { - return nil, err - } - } - - // If there are no errors, then we append it to our output error - // if we have one, otherwise we just output it. - err := n.apply(ctx, provs) - if err != nil { - *n.Error = multierror.Append(*n.Error, err) - if n.Error == nil { - return nil, err - } else { - log.Printf("[TRACE] EvalApplyProvisioners: %s provisioning failed, but we will continue anyway at the caller's request", absAddr) - return nil, nil - } - } - - { - // Call post hook - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostProvisionInstance(absAddr, state.Value) - }) - if err != nil { - return nil, err - } - } - - return nil, nil -} - -// filterProvisioners filters the provisioners on the resource to only -// the provisioners specified by the "when" option. -func (n *EvalApplyProvisioners) filterProvisioners() []*configs.Provisioner { - // Fast path the zero case - if n.ResourceConfig == nil || n.ResourceConfig.Managed == nil { - return nil - } - - if len(n.ResourceConfig.Managed.Provisioners) == 0 { - return nil - } - - result := make([]*configs.Provisioner, 0, len(n.ResourceConfig.Managed.Provisioners)) - for _, p := range n.ResourceConfig.Managed.Provisioners { - if p.When == n.When { - result = append(result, p) - } - } - - return result -} - -func (n *EvalApplyProvisioners) apply(ctx EvalContext, provs []*configs.Provisioner) error { - var diags tfdiags.Diagnostics - instanceAddr := n.Addr - absAddr := instanceAddr.Absolute(ctx.Path()) - - // If there's a connection block defined directly inside the resource block - // then it'll serve as a base connection configuration for all of the - // provisioners. - var baseConn hcl.Body - if n.ResourceConfig.Managed != nil && n.ResourceConfig.Managed.Connection != nil { - baseConn = n.ResourceConfig.Managed.Connection.Config - } - - for _, prov := range provs { - log.Printf("[TRACE] EvalApplyProvisioners: provisioning %s with %q", absAddr, prov.Type) - - // Get the provisioner - provisioner := ctx.Provisioner(prov.Type) - schema := ctx.ProvisionerSchema(prov.Type) - - forEach, forEachDiags := evaluateResourceForEachExpression(n.ResourceConfig.ForEach, ctx) - diags = diags.Append(forEachDiags) - keyData := EvalDataForInstanceKey(instanceAddr.Key, forEach) - - // Evaluate the main provisioner configuration. - config, _, configDiags := ctx.EvaluateBlock(prov.Config, schema, instanceAddr, keyData) - diags = diags.Append(configDiags) - - // If the provisioner block contains a connection block of its own then - // it can override the base connection configuration, if any. - var localConn hcl.Body - if prov.Connection != nil { - localConn = prov.Connection.Config - } - - var connBody hcl.Body - switch { - case baseConn != nil && localConn != nil: - // Our standard merging logic applies here, similar to what we do - // with _override.tf configuration files: arguments from the - // base connection block will be masked by any arguments of the - // same name in the local connection block. - connBody = configs.MergeBodies(baseConn, localConn) - case baseConn != nil: - connBody = baseConn - case localConn != nil: - connBody = localConn - } - - // start with an empty connInfo - connInfo := cty.NullVal(connectionBlockSupersetSchema.ImpliedType()) - - if connBody != nil { - var connInfoDiags tfdiags.Diagnostics - connInfo, _, connInfoDiags = ctx.EvaluateBlock(connBody, connectionBlockSupersetSchema, instanceAddr, keyData) - diags = diags.Append(connInfoDiags) - if diags.HasErrors() { - // "on failure continue" setting only applies to failures of the - // provisioner itself, not to invalid configuration. - return diags.Err() - } - } - - { - // Call pre hook - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreProvisionInstanceStep(absAddr, prov.Type) - }) - if err != nil { - return err - } - } - - // The output function - outputFn := func(msg string) { - ctx.Hook(func(h Hook) (HookAction, error) { - h.ProvisionOutput(absAddr, prov.Type, msg) - return HookActionContinue, nil - }) - } - - output := CallbackUIOutput{OutputFn: outputFn} - resp := provisioner.ProvisionResource(provisioners.ProvisionResourceRequest{ - Config: config, - Connection: connInfo, - UIOutput: &output, - }) - applyDiags := resp.Diagnostics.InConfigBody(prov.Config) - - // Call post hook - hookErr := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostProvisionInstanceStep(absAddr, prov.Type, applyDiags.Err()) - }) - - switch prov.OnFailure { - case configs.ProvisionerOnFailureContinue: - if applyDiags.HasErrors() { - log.Printf("[WARN] Errors while provisioning %s with %q, but continuing as requested in configuration", n.Addr, prov.Type) - } else { - // Maybe there are warnings that we still want to see - diags = diags.Append(applyDiags) - } - default: - diags = diags.Append(applyDiags) - if applyDiags.HasErrors() { - log.Printf("[WARN] Errors while provisioning %s with %q, so aborting", n.Addr, prov.Type) - return diags.Err() - } - } - - // Deal with the hook - if hookErr != nil { - return hookErr - } - } - - return diags.ErrWithWarnings() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_check_prevent_destroy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_check_prevent_destroy.go deleted file mode 100644 index d13a9652915..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_check_prevent_destroy.go +++ /dev/null @@ -1,47 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - - "github.com/hashicorp/hcl/v2" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalPreventDestroy is an EvalNode implementation that returns an -// error if a resource has PreventDestroy configured and the diff -// would destroy the resource. -type EvalCheckPreventDestroy struct { - Addr addrs.ResourceInstance - Config *configs.Resource - Change **plans.ResourceInstanceChange -} - -func (n *EvalCheckPreventDestroy) Eval(ctx EvalContext) (interface{}, error) { - if n.Change == nil || *n.Change == nil || n.Config == nil || n.Config.Managed == nil { - return nil, nil - } - - change := *n.Change - preventDestroy := n.Config.Managed.PreventDestroy - - if (change.Action == plans.Delete || change.Action.IsReplace()) && preventDestroy { - var diags tfdiags.Diagnostics - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Instance cannot be destroyed", - Detail: fmt.Sprintf( - "Resource %s has lifecycle.prevent_destroy set, but the plan calls for this resource to be destroyed. To avoid this error and continue with the plan, either disable lifecycle.prevent_destroy or reduce the scope of the plan using the -target flag.", - n.Addr.Absolute(ctx.Path()).String(), - ), - Subject: &n.Config.DeclRange, - }) - return nil, diags.Err() - } - - return nil, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_context.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_context.go deleted file mode 100644 index 4fa011e2b5c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_context.go +++ /dev/null @@ -1,133 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" -) - -// EvalContext is the interface that is given to eval nodes to execute. -type EvalContext interface { - // Stopped returns a channel that is closed when evaluation is stopped - // via Terraform.Context.Stop() - Stopped() <-chan struct{} - - // Path is the current module path. - Path() addrs.ModuleInstance - - // Hook is used to call hook methods. The callback is called for each - // hook and should return the hook action to take and the error. - Hook(func(Hook) (HookAction, error)) error - - // Input is the UIInput object for interacting with the UI. - Input() UIInput - - // InitProvider initializes the provider with the given type and address, and - // returns the implementation of the resource provider or an error. - // - // It is an error to initialize the same provider more than once. - InitProvider(typ string, addr addrs.ProviderConfig) (providers.Interface, error) - - // Provider gets the provider instance with the given address (already - // initialized) or returns nil if the provider isn't initialized. - // - // This method expects an _absolute_ provider configuration address, since - // resources in one module are able to use providers from other modules. - // InitProvider must've been called on the EvalContext of the module - // that owns the given provider before calling this method. - Provider(addrs.AbsProviderConfig) providers.Interface - - // ProviderSchema retrieves the schema for a particular provider, which - // must have already been initialized with InitProvider. - // - // This method expects an _absolute_ provider configuration address, since - // resources in one module are able to use providers from other modules. - ProviderSchema(addrs.AbsProviderConfig) *ProviderSchema - - // CloseProvider closes provider connections that aren't needed anymore. - CloseProvider(addrs.ProviderConfig) error - - // ConfigureProvider configures the provider with the given - // configuration. This is a separate context call because this call - // is used to store the provider configuration for inheritance lookups - // with ParentProviderConfig(). - ConfigureProvider(addrs.ProviderConfig, cty.Value) tfdiags.Diagnostics - - // ProviderInput and SetProviderInput are used to configure providers - // from user input. - ProviderInput(addrs.ProviderConfig) map[string]cty.Value - SetProviderInput(addrs.ProviderConfig, map[string]cty.Value) - - // InitProvisioner initializes the provisioner with the given name and - // returns the implementation of the resource provisioner or an error. - // - // It is an error to initialize the same provisioner more than once. - InitProvisioner(string) (provisioners.Interface, error) - - // Provisioner gets the provisioner instance with the given name (already - // initialized) or returns nil if the provisioner isn't initialized. - Provisioner(string) provisioners.Interface - - // ProvisionerSchema retrieves the main configuration schema for a - // particular provisioner, which must have already been initialized with - // InitProvisioner. - ProvisionerSchema(string) *configschema.Block - - // CloseProvisioner closes provisioner connections that aren't needed - // anymore. - CloseProvisioner(string) error - - // EvaluateBlock takes the given raw configuration block and associated - // schema and evaluates it to produce a value of an object type that - // conforms to the implied type of the schema. - // - // The "self" argument is optional. If given, it is the referenceable - // address that the name "self" should behave as an alias for when - // evaluating. Set this to nil if the "self" object should not be available. - // - // The "key" argument is also optional. If given, it is the instance key - // of the current object within the multi-instance container it belongs - // to. For example, on a resource block with "count" set this should be - // set to a different addrs.IntKey for each instance created from that - // block. Set this to addrs.NoKey if not appropriate. - // - // The returned body is an expanded version of the given body, with any - // "dynamic" blocks replaced with zero or more static blocks. This can be - // used to extract correct source location information about attributes of - // the returned object value. - EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) - - // EvaluateExpr takes the given HCL expression and evaluates it to produce - // a value. - // - // The "self" argument is optional. If given, it is the referenceable - // address that the name "self" should behave as an alias for when - // evaluating. Set this to nil if the "self" object should not be available. - EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) - - // EvaluationScope returns a scope that can be used to evaluate reference - // addresses in this context. - EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope - - // SetModuleCallArguments defines values for the variables of a particular - // child module call. - // - // Calling this function multiple times has merging behavior, keeping any - // previously-set keys that are not present in the new map. - SetModuleCallArguments(addrs.ModuleCallInstance, map[string]cty.Value) - - // Changes returns the writer object that can be used to write new proposed - // changes into the global changes set. - Changes() *plans.ChangesSync - - // State returns a wrapper object that provides safe concurrent access to - // the global state. - State() *states.SyncState -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_context_builtin.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_context_builtin.go deleted file mode 100644 index bd414a96089..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_context_builtin.go +++ /dev/null @@ -1,329 +0,0 @@ -package terraform - -import ( - "context" - "fmt" - "log" - "sync" - - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" - "github.com/hashicorp/terraform-plugin-sdk/internal/version" - - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/zclconf/go-cty/cty" -) - -// BuiltinEvalContext is an EvalContext implementation that is used by -// Terraform by default. -type BuiltinEvalContext struct { - // StopContext is the context used to track whether we're complete - StopContext context.Context - - // PathValue is the Path that this context is operating within. - PathValue addrs.ModuleInstance - - // Evaluator is used for evaluating expressions within the scope of this - // eval context. - Evaluator *Evaluator - - // Schemas is a repository of all of the schemas we should need to - // decode configuration blocks and expressions. This must be constructed by - // the caller to include schemas for all of the providers, resource types, - // data sources and provisioners used by the given configuration and - // state. - // - // This must not be mutated during evaluation. - Schemas *Schemas - - // VariableValues contains the variable values across all modules. This - // structure is shared across the entire containing context, and so it - // may be accessed only when holding VariableValuesLock. - // The keys of the first level of VariableValues are the string - // representations of addrs.ModuleInstance values. The second-level keys - // are variable names within each module instance. - VariableValues map[string]map[string]cty.Value - VariableValuesLock *sync.Mutex - - Components contextComponentFactory - Hooks []Hook - InputValue UIInput - ProviderCache map[string]providers.Interface - ProviderInputConfig map[string]map[string]cty.Value - ProviderLock *sync.Mutex - ProvisionerCache map[string]provisioners.Interface - ProvisionerLock *sync.Mutex - ChangesValue *plans.ChangesSync - StateValue *states.SyncState - - once sync.Once -} - -// BuiltinEvalContext implements EvalContext -var _ EvalContext = (*BuiltinEvalContext)(nil) - -func (ctx *BuiltinEvalContext) Stopped() <-chan struct{} { - // This can happen during tests. During tests, we just block forever. - if ctx.StopContext == nil { - return nil - } - - return ctx.StopContext.Done() -} - -func (ctx *BuiltinEvalContext) Hook(fn func(Hook) (HookAction, error)) error { - for _, h := range ctx.Hooks { - action, err := fn(h) - if err != nil { - return err - } - - switch action { - case HookActionContinue: - continue - case HookActionHalt: - // Return an early exit error to trigger an early exit - log.Printf("[WARN] Early exit triggered by hook: %T", h) - return EvalEarlyExitError{} - } - } - - return nil -} - -func (ctx *BuiltinEvalContext) Input() UIInput { - return ctx.InputValue -} - -func (ctx *BuiltinEvalContext) InitProvider(typeName string, addr addrs.ProviderConfig) (providers.Interface, error) { - ctx.once.Do(ctx.init) - absAddr := addr.Absolute(ctx.Path()) - - // If we already initialized, it is an error - if p := ctx.Provider(absAddr); p != nil { - return nil, fmt.Errorf("%s is already initialized", addr) - } - - // Warning: make sure to acquire these locks AFTER the call to Provider - // above, since it also acquires locks. - ctx.ProviderLock.Lock() - defer ctx.ProviderLock.Unlock() - - key := absAddr.String() - - p, err := ctx.Components.ResourceProvider(typeName, key) - if err != nil { - return nil, err - } - - log.Printf("[TRACE] BuiltinEvalContext: Initialized %q provider for %s", typeName, absAddr) - ctx.ProviderCache[key] = p - - return p, nil -} - -func (ctx *BuiltinEvalContext) Provider(addr addrs.AbsProviderConfig) providers.Interface { - ctx.once.Do(ctx.init) - - ctx.ProviderLock.Lock() - defer ctx.ProviderLock.Unlock() - - return ctx.ProviderCache[addr.String()] -} - -func (ctx *BuiltinEvalContext) ProviderSchema(addr addrs.AbsProviderConfig) *ProviderSchema { - ctx.once.Do(ctx.init) - - return ctx.Schemas.ProviderSchema(addr.ProviderConfig.Type) -} - -func (ctx *BuiltinEvalContext) CloseProvider(addr addrs.ProviderConfig) error { - ctx.once.Do(ctx.init) - - ctx.ProviderLock.Lock() - defer ctx.ProviderLock.Unlock() - - key := addr.Absolute(ctx.Path()).String() - provider := ctx.ProviderCache[key] - if provider != nil { - delete(ctx.ProviderCache, key) - return provider.Close() - } - - return nil -} - -func (ctx *BuiltinEvalContext) ConfigureProvider(addr addrs.ProviderConfig, cfg cty.Value) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - absAddr := addr.Absolute(ctx.Path()) - p := ctx.Provider(absAddr) - if p == nil { - diags = diags.Append(fmt.Errorf("%s not initialized", addr)) - return diags - } - - providerSchema := ctx.ProviderSchema(absAddr) - if providerSchema == nil { - diags = diags.Append(fmt.Errorf("schema for %s is not available", absAddr)) - return diags - } - - req := providers.ConfigureRequest{ - TerraformVersion: version.String(), - Config: cfg, - } - - resp := p.Configure(req) - return resp.Diagnostics -} - -func (ctx *BuiltinEvalContext) ProviderInput(pc addrs.ProviderConfig) map[string]cty.Value { - ctx.ProviderLock.Lock() - defer ctx.ProviderLock.Unlock() - - if !ctx.Path().IsRoot() { - // Only root module provider configurations can have input. - return nil - } - - return ctx.ProviderInputConfig[pc.String()] -} - -func (ctx *BuiltinEvalContext) SetProviderInput(pc addrs.ProviderConfig, c map[string]cty.Value) { - absProvider := pc.Absolute(ctx.Path()) - - if !ctx.Path().IsRoot() { - // Only root module provider configurations can have input. - log.Printf("[WARN] BuiltinEvalContext: attempt to SetProviderInput for non-root module") - return - } - - // Save the configuration - ctx.ProviderLock.Lock() - ctx.ProviderInputConfig[absProvider.String()] = c - ctx.ProviderLock.Unlock() -} - -func (ctx *BuiltinEvalContext) InitProvisioner(n string) (provisioners.Interface, error) { - ctx.once.Do(ctx.init) - - // If we already initialized, it is an error - if p := ctx.Provisioner(n); p != nil { - return nil, fmt.Errorf("Provisioner '%s' already initialized", n) - } - - // Warning: make sure to acquire these locks AFTER the call to Provisioner - // above, since it also acquires locks. - ctx.ProvisionerLock.Lock() - defer ctx.ProvisionerLock.Unlock() - - key := PathObjectCacheKey(ctx.Path(), n) - - p, err := ctx.Components.ResourceProvisioner(n, key) - if err != nil { - return nil, err - } - - ctx.ProvisionerCache[key] = p - - return p, nil -} - -func (ctx *BuiltinEvalContext) Provisioner(n string) provisioners.Interface { - ctx.once.Do(ctx.init) - - ctx.ProvisionerLock.Lock() - defer ctx.ProvisionerLock.Unlock() - - key := PathObjectCacheKey(ctx.Path(), n) - return ctx.ProvisionerCache[key] -} - -func (ctx *BuiltinEvalContext) ProvisionerSchema(n string) *configschema.Block { - ctx.once.Do(ctx.init) - - return ctx.Schemas.ProvisionerConfig(n) -} - -func (ctx *BuiltinEvalContext) CloseProvisioner(n string) error { - ctx.once.Do(ctx.init) - - ctx.ProvisionerLock.Lock() - defer ctx.ProvisionerLock.Unlock() - - key := PathObjectCacheKey(ctx.Path(), n) - - prov := ctx.ProvisionerCache[key] - if prov != nil { - return prov.Close() - } - - return nil -} - -func (ctx *BuiltinEvalContext) EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - scope := ctx.EvaluationScope(self, keyData) - body, evalDiags := scope.ExpandBlock(body, schema) - diags = diags.Append(evalDiags) - val, evalDiags := scope.EvalBlock(body, schema) - diags = diags.Append(evalDiags) - return val, body, diags -} - -func (ctx *BuiltinEvalContext) EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { - scope := ctx.EvaluationScope(self, EvalDataForNoInstanceKey) - return scope.EvalExpr(expr, wantType) -} - -func (ctx *BuiltinEvalContext) EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope { - data := &evaluationStateData{ - Evaluator: ctx.Evaluator, - ModulePath: ctx.PathValue, - InstanceKeyData: keyData, - Operation: ctx.Evaluator.Operation, - } - return ctx.Evaluator.Scope(data, self) -} - -func (ctx *BuiltinEvalContext) Path() addrs.ModuleInstance { - return ctx.PathValue -} - -func (ctx *BuiltinEvalContext) SetModuleCallArguments(n addrs.ModuleCallInstance, vals map[string]cty.Value) { - ctx.VariableValuesLock.Lock() - defer ctx.VariableValuesLock.Unlock() - - childPath := n.ModuleInstance(ctx.PathValue) - key := childPath.String() - - args := ctx.VariableValues[key] - if args == nil { - args = make(map[string]cty.Value) - ctx.VariableValues[key] = vals - return - } - - for k, v := range vals { - args[k] = v - } -} - -func (ctx *BuiltinEvalContext) Changes() *plans.ChangesSync { - return ctx.ChangesValue -} - -func (ctx *BuiltinEvalContext) State() *states.SyncState { - return ctx.StateValue -} - -func (ctx *BuiltinEvalContext) init() { -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_context_mock.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_context_mock.go deleted file mode 100644 index 786316fb354..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_context_mock.go +++ /dev/null @@ -1,319 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hcldec" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// MockEvalContext is a mock version of EvalContext that can be used -// for tests. -type MockEvalContext struct { - StoppedCalled bool - StoppedValue <-chan struct{} - - HookCalled bool - HookHook Hook - HookError error - - InputCalled bool - InputInput UIInput - - InitProviderCalled bool - InitProviderType string - InitProviderAddr addrs.ProviderConfig - InitProviderProvider providers.Interface - InitProviderError error - - ProviderCalled bool - ProviderAddr addrs.AbsProviderConfig - ProviderProvider providers.Interface - - ProviderSchemaCalled bool - ProviderSchemaAddr addrs.AbsProviderConfig - ProviderSchemaSchema *ProviderSchema - - CloseProviderCalled bool - CloseProviderAddr addrs.ProviderConfig - CloseProviderProvider providers.Interface - - ProviderInputCalled bool - ProviderInputAddr addrs.ProviderConfig - ProviderInputValues map[string]cty.Value - - SetProviderInputCalled bool - SetProviderInputAddr addrs.ProviderConfig - SetProviderInputValues map[string]cty.Value - - ConfigureProviderCalled bool - ConfigureProviderAddr addrs.ProviderConfig - ConfigureProviderConfig cty.Value - ConfigureProviderDiags tfdiags.Diagnostics - - InitProvisionerCalled bool - InitProvisionerName string - InitProvisionerProvisioner provisioners.Interface - InitProvisionerError error - - ProvisionerCalled bool - ProvisionerName string - ProvisionerProvisioner provisioners.Interface - - ProvisionerSchemaCalled bool - ProvisionerSchemaName string - ProvisionerSchemaSchema *configschema.Block - - CloseProvisionerCalled bool - CloseProvisionerName string - CloseProvisionerProvisioner provisioners.Interface - - EvaluateBlockCalled bool - EvaluateBlockBody hcl.Body - EvaluateBlockSchema *configschema.Block - EvaluateBlockSelf addrs.Referenceable - EvaluateBlockKeyData InstanceKeyEvalData - EvaluateBlockResultFunc func( - body hcl.Body, - schema *configschema.Block, - self addrs.Referenceable, - keyData InstanceKeyEvalData, - ) (cty.Value, hcl.Body, tfdiags.Diagnostics) // overrides the other values below, if set - EvaluateBlockResult cty.Value - EvaluateBlockExpandedBody hcl.Body - EvaluateBlockDiags tfdiags.Diagnostics - - EvaluateExprCalled bool - EvaluateExprExpr hcl.Expression - EvaluateExprWantType cty.Type - EvaluateExprSelf addrs.Referenceable - EvaluateExprResultFunc func( - expr hcl.Expression, - wantType cty.Type, - self addrs.Referenceable, - ) (cty.Value, tfdiags.Diagnostics) // overrides the other values below, if set - EvaluateExprResult cty.Value - EvaluateExprDiags tfdiags.Diagnostics - - EvaluationScopeCalled bool - EvaluationScopeSelf addrs.Referenceable - EvaluationScopeKeyData InstanceKeyEvalData - EvaluationScopeScope *lang.Scope - - PathCalled bool - PathPath addrs.ModuleInstance - - SetModuleCallArgumentsCalled bool - SetModuleCallArgumentsModule addrs.ModuleCallInstance - SetModuleCallArgumentsValues map[string]cty.Value - - ChangesCalled bool - ChangesChanges *plans.ChangesSync - - StateCalled bool - StateState *states.SyncState -} - -// MockEvalContext implements EvalContext -var _ EvalContext = (*MockEvalContext)(nil) - -func (c *MockEvalContext) Stopped() <-chan struct{} { - c.StoppedCalled = true - return c.StoppedValue -} - -func (c *MockEvalContext) Hook(fn func(Hook) (HookAction, error)) error { - c.HookCalled = true - if c.HookHook != nil { - if _, err := fn(c.HookHook); err != nil { - return err - } - } - - return c.HookError -} - -func (c *MockEvalContext) Input() UIInput { - c.InputCalled = true - return c.InputInput -} - -func (c *MockEvalContext) InitProvider(t string, addr addrs.ProviderConfig) (providers.Interface, error) { - c.InitProviderCalled = true - c.InitProviderType = t - c.InitProviderAddr = addr - return c.InitProviderProvider, c.InitProviderError -} - -func (c *MockEvalContext) Provider(addr addrs.AbsProviderConfig) providers.Interface { - c.ProviderCalled = true - c.ProviderAddr = addr - return c.ProviderProvider -} - -func (c *MockEvalContext) ProviderSchema(addr addrs.AbsProviderConfig) *ProviderSchema { - c.ProviderSchemaCalled = true - c.ProviderSchemaAddr = addr - return c.ProviderSchemaSchema -} - -func (c *MockEvalContext) CloseProvider(addr addrs.ProviderConfig) error { - c.CloseProviderCalled = true - c.CloseProviderAddr = addr - return nil -} - -func (c *MockEvalContext) ConfigureProvider(addr addrs.ProviderConfig, cfg cty.Value) tfdiags.Diagnostics { - c.ConfigureProviderCalled = true - c.ConfigureProviderAddr = addr - c.ConfigureProviderConfig = cfg - return c.ConfigureProviderDiags -} - -func (c *MockEvalContext) ProviderInput(addr addrs.ProviderConfig) map[string]cty.Value { - c.ProviderInputCalled = true - c.ProviderInputAddr = addr - return c.ProviderInputValues -} - -func (c *MockEvalContext) SetProviderInput(addr addrs.ProviderConfig, vals map[string]cty.Value) { - c.SetProviderInputCalled = true - c.SetProviderInputAddr = addr - c.SetProviderInputValues = vals -} - -func (c *MockEvalContext) InitProvisioner(n string) (provisioners.Interface, error) { - c.InitProvisionerCalled = true - c.InitProvisionerName = n - return c.InitProvisionerProvisioner, c.InitProvisionerError -} - -func (c *MockEvalContext) Provisioner(n string) provisioners.Interface { - c.ProvisionerCalled = true - c.ProvisionerName = n - return c.ProvisionerProvisioner -} - -func (c *MockEvalContext) ProvisionerSchema(n string) *configschema.Block { - c.ProvisionerSchemaCalled = true - c.ProvisionerSchemaName = n - return c.ProvisionerSchemaSchema -} - -func (c *MockEvalContext) CloseProvisioner(n string) error { - c.CloseProvisionerCalled = true - c.CloseProvisionerName = n - return nil -} - -func (c *MockEvalContext) EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { - c.EvaluateBlockCalled = true - c.EvaluateBlockBody = body - c.EvaluateBlockSchema = schema - c.EvaluateBlockSelf = self - c.EvaluateBlockKeyData = keyData - if c.EvaluateBlockResultFunc != nil { - return c.EvaluateBlockResultFunc(body, schema, self, keyData) - } - return c.EvaluateBlockResult, c.EvaluateBlockExpandedBody, c.EvaluateBlockDiags -} - -func (c *MockEvalContext) EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { - c.EvaluateExprCalled = true - c.EvaluateExprExpr = expr - c.EvaluateExprWantType = wantType - c.EvaluateExprSelf = self - if c.EvaluateExprResultFunc != nil { - return c.EvaluateExprResultFunc(expr, wantType, self) - } - return c.EvaluateExprResult, c.EvaluateExprDiags -} - -// installSimpleEval is a helper to install a simple mock implementation of -// both EvaluateBlock and EvaluateExpr into the receiver. -// -// These default implementations will either evaluate the given input against -// the scope in field EvaluationScopeScope or, if it is nil, with no eval -// context at all so that only constant values may be used. -// -// This function overwrites any existing functions installed in fields -// EvaluateBlockResultFunc and EvaluateExprResultFunc. -func (c *MockEvalContext) installSimpleEval() { - c.EvaluateBlockResultFunc = func(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { - if scope := c.EvaluationScopeScope; scope != nil { - // Fully-functional codepath. - var diags tfdiags.Diagnostics - body, diags = scope.ExpandBlock(body, schema) - if diags.HasErrors() { - return cty.DynamicVal, body, diags - } - val, evalDiags := c.EvaluationScopeScope.EvalBlock(body, schema) - diags = diags.Append(evalDiags) - if evalDiags.HasErrors() { - return cty.DynamicVal, body, diags - } - return val, body, diags - } - - // Fallback codepath supporting constant values only. - val, hclDiags := hcldec.Decode(body, schema.DecoderSpec(), nil) - return val, body, tfdiags.Diagnostics(nil).Append(hclDiags) - } - c.EvaluateExprResultFunc = func(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { - if scope := c.EvaluationScopeScope; scope != nil { - // Fully-functional codepath. - return scope.EvalExpr(expr, wantType) - } - - // Fallback codepath supporting constant values only. - var diags tfdiags.Diagnostics - val, hclDiags := expr.Value(nil) - diags = diags.Append(hclDiags) - if hclDiags.HasErrors() { - return cty.DynamicVal, diags - } - var err error - val, err = convert.Convert(val, wantType) - if err != nil { - diags = diags.Append(err) - return cty.DynamicVal, diags - } - return val, diags - } -} - -func (c *MockEvalContext) EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope { - c.EvaluationScopeCalled = true - c.EvaluationScopeSelf = self - c.EvaluationScopeKeyData = keyData - return c.EvaluationScopeScope -} - -func (c *MockEvalContext) Path() addrs.ModuleInstance { - c.PathCalled = true - return c.PathPath -} - -func (c *MockEvalContext) SetModuleCallArguments(n addrs.ModuleCallInstance, values map[string]cty.Value) { - c.SetModuleCallArgumentsCalled = true - c.SetModuleCallArgumentsModule = n - c.SetModuleCallArgumentsValues = values -} - -func (c *MockEvalContext) Changes() *plans.ChangesSync { - c.ChangesCalled = true - return c.ChangesChanges -} - -func (c *MockEvalContext) State() *states.SyncState { - c.StateCalled = true - return c.StateState -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_count.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_count.go deleted file mode 100644 index 7d6fa4919da..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_count.go +++ /dev/null @@ -1,120 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/gocty" -) - -// evaluateResourceCountExpression is our standard mechanism for interpreting an -// expression given for a "count" argument on a resource. This should be called -// from the DynamicExpand of a node representing a resource in order to -// determine the final count value. -// -// If the result is zero or positive and no error diagnostics are returned, then -// the result is the literal count value to use. -// -// If the result is -1, this indicates that the given expression is nil and so -// the "count" behavior should not be enabled for this resource at all. -// -// If error diagnostics are returned then the result is always the meaningless -// placeholder value -1. -func evaluateResourceCountExpression(expr hcl.Expression, ctx EvalContext) (int, tfdiags.Diagnostics) { - count, known, diags := evaluateResourceCountExpressionKnown(expr, ctx) - if !known { - // Currently this is a rather bad outcome from a UX standpoint, since we have - // no real mechanism to deal with this situation and all we can do is produce - // an error message. - // FIXME: In future, implement a built-in mechanism for deferring changes that - // can't yet be predicted, and use it to guide the user through several - // plan/apply steps until the desired configuration is eventually reached. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The "count" value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how many instances will be created. To work around this, use the -target argument to first apply only the resources that the count depends on.`, - Subject: expr.Range().Ptr(), - }) - } - return count, diags -} - -// evaluateResourceCountExpressionKnown is like evaluateResourceCountExpression -// except that it handles an unknown result by returning count = 0 and -// a known = false, rather than by reporting the unknown value as an error -// diagnostic. -func evaluateResourceCountExpressionKnown(expr hcl.Expression, ctx EvalContext) (count int, known bool, diags tfdiags.Diagnostics) { - if expr == nil { - return -1, true, nil - } - - countVal, countDiags := ctx.EvaluateExpr(expr, cty.Number, nil) - diags = diags.Append(countDiags) - if diags.HasErrors() { - return -1, true, diags - } - - switch { - case countVal.IsNull(): - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The given "count" argument value is null. An integer is required.`, - Subject: expr.Range().Ptr(), - }) - return -1, true, diags - case !countVal.IsKnown(): - return 0, false, diags - } - - err := gocty.FromCtyValue(countVal, &count) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: fmt.Sprintf(`The given "count" argument value is unsuitable: %s.`, err), - Subject: expr.Range().Ptr(), - }) - return -1, true, diags - } - if count < 0 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The given "count" argument value is unsuitable: negative numbers are not supported.`, - Subject: expr.Range().Ptr(), - }) - return -1, true, diags - } - - return count, true, diags -} - -// fixResourceCountSetTransition is a helper function to fix up the state when a -// resource transitions its "count" from being set to unset or vice-versa, -// treating a 0-key and a no-key instance as aliases for one another across -// the transition. -// -// The correct time to call this function is in the DynamicExpand method for -// a node representing a resource, just after evaluating the count with -// evaluateResourceCountExpression, and before any other analysis of the -// state such as orphan detection. -// -// This function calls methods on the given EvalContext to update the current -// state in-place, if necessary. It is a no-op if there is no count transition -// taking place. -// -// Since the state is modified in-place, this function must take a writer lock -// on the state. The caller must therefore not also be holding a state lock, -// or this function will block forever awaiting the lock. -func fixResourceCountSetTransition(ctx EvalContext, addr addrs.AbsResource, countEnabled bool) { - state := ctx.State() - changed := state.MaybeFixUpResourceInstanceAddressForCount(addr, countEnabled) - if changed { - log.Printf("[TRACE] renamed first %s instance in transient state due to count argument change", addr) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_count_boundary.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_count_boundary.go deleted file mode 100644 index aac380632ae..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_count_boundary.go +++ /dev/null @@ -1,77 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" -) - -// EvalCountFixZeroOneBoundaryGlobal is an EvalNode that fixes up the state -// when there is a resource count with zero/one boundary, i.e. fixing -// a resource named "aws_instance.foo" to "aws_instance.foo.0" and vice-versa. -// -// This works on the global state. -type EvalCountFixZeroOneBoundaryGlobal struct { - Config *configs.Config -} - -// TODO: test -func (n *EvalCountFixZeroOneBoundaryGlobal) Eval(ctx EvalContext) (interface{}, error) { - // We'll temporarily lock the state to grab the modules, then work on each - // one separately while taking a lock again for each separate resource. - // This means that if another caller concurrently adds a module here while - // we're working then we won't update it, but that's no worse than the - // concurrent writer blocking for our entire fixup process and _then_ - // adding a new module, and in practice the graph node associated with - // this eval depends on everything else in the graph anyway, so there - // should not be concurrent writers. - state := ctx.State().Lock() - moduleAddrs := make([]addrs.ModuleInstance, 0, len(state.Modules)) - for _, m := range state.Modules { - moduleAddrs = append(moduleAddrs, m.Addr) - } - ctx.State().Unlock() - - for _, addr := range moduleAddrs { - cfg := n.Config.DescendentForInstance(addr) - if cfg == nil { - log.Printf("[WARN] Not fixing up EachModes for %s because it has no config", addr) - continue - } - if err := n.fixModule(ctx, addr); err != nil { - return nil, err - } - } - - return nil, nil -} - -func (n *EvalCountFixZeroOneBoundaryGlobal) fixModule(ctx EvalContext, moduleAddr addrs.ModuleInstance) error { - ms := ctx.State().Module(moduleAddr) - cfg := n.Config.DescendentForInstance(moduleAddr) - if ms == nil { - // Theoretically possible for a concurrent writer to delete a module - // while we're running, but in practice the graph node that called us - // depends on everything else in the graph and so there can never - // be a concurrent writer. - return fmt.Errorf("[WARN] no state found for %s while trying to fix up EachModes", moduleAddr) - } - if cfg == nil { - return fmt.Errorf("[WARN] no config found for %s while trying to fix up EachModes", moduleAddr) - } - - for _, r := range ms.Resources { - addr := r.Addr.Absolute(moduleAddr) - rCfg := cfg.Module.ResourceByAddr(r.Addr) - if rCfg == nil { - log.Printf("[WARN] Not fixing up EachModes for %s because it has no config", addr) - continue - } - hasCount := rCfg.Count != nil - fixResourceCountSetTransition(ctx, addr, hasCount) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_diff.go deleted file mode 100644 index d6f51c95045..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_diff.go +++ /dev/null @@ -1,783 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - "strings" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalCheckPlannedChange is an EvalNode implementation that produces errors -// if the _actual_ expected value is not compatible with what was recorded -// in the plan. -// -// Errors here are most often indicative of a bug in the provider, so our -// error messages will report with that in mind. It's also possible that -// there's a bug in Terraform's Core's own "proposed new value" code in -// EvalDiff. -type EvalCheckPlannedChange struct { - Addr addrs.ResourceInstance - ProviderAddr addrs.AbsProviderConfig - ProviderSchema **ProviderSchema - - // We take ResourceInstanceChange objects here just because that's what's - // convenient to pass in from the evaltree implementation, but we really - // only look at the "After" value of each change. - Planned, Actual **plans.ResourceInstanceChange -} - -func (n *EvalCheckPlannedChange) Eval(ctx EvalContext) (interface{}, error) { - providerSchema := *n.ProviderSchema - plannedChange := *n.Planned - actualChange := *n.Actual - - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support %q", n.Addr.Resource.Type) - } - - var diags tfdiags.Diagnostics - absAddr := n.Addr.Absolute(ctx.Path()) - - log.Printf("[TRACE] EvalCheckPlannedChange: Verifying that actual change (action %s) matches planned change (action %s)", actualChange.Action, plannedChange.Action) - - if plannedChange.Action != actualChange.Action { - switch { - case plannedChange.Action == plans.Update && actualChange.Action == plans.NoOp: - // It's okay for an update to become a NoOp once we've filled in - // all of the unknown values, since the final values might actually - // match what was there before after all. - log.Printf("[DEBUG] After incorporating new values learned so far during apply, %s change has become NoOp", absAddr) - default: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced inconsistent final plan", - fmt.Sprintf( - "When expanding the plan for %s to include new values learned so far during apply, provider %q changed the planned action from %s to %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - absAddr, n.ProviderAddr.ProviderConfig.Type, - plannedChange.Action, actualChange.Action, - ), - )) - } - } - - errs := objchange.AssertObjectCompatible(schema, plannedChange.After, actualChange.After) - for _, err := range errs { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced inconsistent final plan", - fmt.Sprintf( - "When expanding the plan for %s to include new values learned so far during apply, provider %q produced an invalid new value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - absAddr, n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatError(err), - ), - )) - } - return nil, diags.Err() -} - -// EvalDiff is an EvalNode implementation that detects changes for a given -// resource instance. -type EvalDiff struct { - Addr addrs.ResourceInstance - Config *configs.Resource - Provider *providers.Interface - ProviderAddr addrs.AbsProviderConfig - ProviderSchema **ProviderSchema - State **states.ResourceInstanceObject - PreviousDiff **plans.ResourceInstanceChange - - // CreateBeforeDestroy is set if either the resource's own config sets - // create_before_destroy explicitly or if dependencies have forced the - // resource to be handled as create_before_destroy in order to avoid - // a dependency cycle. - CreateBeforeDestroy bool - - OutputChange **plans.ResourceInstanceChange - OutputValue *cty.Value - OutputState **states.ResourceInstanceObject - - Stub bool -} - -// TODO: test -func (n *EvalDiff) Eval(ctx EvalContext) (interface{}, error) { - state := *n.State - config := *n.Config - provider := *n.Provider - providerSchema := *n.ProviderSchema - - if providerSchema == nil { - return nil, fmt.Errorf("provider schema is unavailable for %s", n.Addr) - } - if n.ProviderAddr.ProviderConfig.Type == "" { - panic(fmt.Sprintf("EvalDiff for %s does not have ProviderAddr set", n.Addr.Absolute(ctx.Path()))) - } - - var diags tfdiags.Diagnostics - - // Evaluate the configuration - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support resource type %q", n.Addr.Resource.Type) - } - forEach, _ := evaluateResourceForEachExpression(n.Config.ForEach, ctx) - keyData := EvalDataForInstanceKey(n.Addr.Key, forEach) - configVal, _, configDiags := ctx.EvaluateBlock(config.Config, schema, nil, keyData) - diags = diags.Append(configDiags) - if configDiags.HasErrors() { - return nil, diags.Err() - } - - absAddr := n.Addr.Absolute(ctx.Path()) - var priorVal cty.Value - var priorValTainted cty.Value - var priorPrivate []byte - if state != nil { - if state.Status != states.ObjectTainted { - priorVal = state.Value - priorPrivate = state.Private - } else { - // If the prior state is tainted then we'll proceed below like - // we're creating an entirely new object, but then turn it into - // a synthetic "Replace" change at the end, creating the same - // result as if the provider had marked at least one argument - // change as "requires replacement". - priorValTainted = state.Value - priorVal = cty.NullVal(schema.ImpliedType()) - } - } else { - priorVal = cty.NullVal(schema.ImpliedType()) - } - - proposedNewVal := objchange.ProposedNewObject(schema, priorVal, configVal) - - // Call pre-diff hook - if !n.Stub { - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreDiff(absAddr, states.CurrentGen, priorVal, proposedNewVal) - }) - if err != nil { - return nil, err - } - } - - log.Printf("[TRACE] Re-validating config for %q", n.Addr.Absolute(ctx.Path())) - // Allow the provider to validate the final set of values. - // The config was statically validated early on, but there may have been - // unknown values which the provider could not validate at the time. - validateResp := provider.ValidateResourceTypeConfig( - providers.ValidateResourceTypeConfigRequest{ - TypeName: n.Addr.Resource.Type, - Config: configVal, - }, - ) - if validateResp.Diagnostics.HasErrors() { - return nil, validateResp.Diagnostics.InConfigBody(config.Config).Err() - } - - // The provider gets an opportunity to customize the proposed new value, - // which in turn produces the _planned_ new value. But before - // we send back this information, we need to process ignore_changes - // so that CustomizeDiff will not act on them - var ignoreChangeDiags tfdiags.Diagnostics - proposedNewVal, ignoreChangeDiags = n.processIgnoreChanges(priorVal, proposedNewVal) - diags = diags.Append(ignoreChangeDiags) - if ignoreChangeDiags.HasErrors() { - return nil, diags.Err() - } - - resp := provider.PlanResourceChange(providers.PlanResourceChangeRequest{ - TypeName: n.Addr.Resource.Type, - Config: configVal, - PriorState: priorVal, - ProposedNewState: proposedNewVal, - PriorPrivate: priorPrivate, - }) - diags = diags.Append(resp.Diagnostics.InConfigBody(config.Config)) - if diags.HasErrors() { - return nil, diags.Err() - } - - plannedNewVal := resp.PlannedState - plannedPrivate := resp.PlannedPrivate - - if plannedNewVal == cty.NilVal { - // Should never happen. Since real-world providers return via RPC a nil - // is always a bug in the client-side stub. This is more likely caused - // by an incompletely-configured mock provider in tests, though. - panic(fmt.Sprintf("PlanResourceChange of %s produced nil value", absAddr.String())) - } - - // We allow the planned new value to disagree with configuration _values_ - // here, since that allows the provider to do special logic like a - // DiffSuppressFunc, but we still require that the provider produces - // a value whose type conforms to the schema. - for _, err := range plannedNewVal.Type().TestConformance(schema.ImpliedType()) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid plan", - fmt.Sprintf( - "Provider %q planned an invalid value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatErrorPrefixed(err, absAddr.String()), - ), - )) - } - if diags.HasErrors() { - return nil, diags.Err() - } - - if errs := objchange.AssertPlanValid(schema, priorVal, configVal, plannedNewVal); len(errs) > 0 { - if resp.LegacyTypeSystem { - // The shimming of the old type system in the legacy SDK is not precise - // enough to pass this consistency check, so we'll give it a pass here, - // but we will generate a warning about it so that we are more likely - // to notice in the logs if an inconsistency beyond the type system - // leads to a downstream provider failure. - var buf strings.Builder - fmt.Fprintf(&buf, "[WARN] Provider %q produced an invalid plan for %s, but we are tolerating it because it is using the legacy plugin SDK.\n The following problems may be the cause of any confusing errors from downstream operations:", n.ProviderAddr.ProviderConfig.Type, absAddr) - for _, err := range errs { - fmt.Fprintf(&buf, "\n - %s", tfdiags.FormatError(err)) - } - log.Print(buf.String()) - } else { - for _, err := range errs { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid plan", - fmt.Sprintf( - "Provider %q planned an invalid value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatErrorPrefixed(err, absAddr.String()), - ), - )) - } - return nil, diags.Err() - } - } - - // TODO: We should be able to remove this repeat of processing ignored changes - // after the plan, which helps providers relying on old behavior "just work" - // in the next major version, such that we can be stricter about ignore_changes - // values - plannedNewVal, ignoreChangeDiags = n.processIgnoreChanges(priorVal, plannedNewVal) - diags = diags.Append(ignoreChangeDiags) - if ignoreChangeDiags.HasErrors() { - return nil, diags.Err() - } - - // The provider produces a list of paths to attributes whose changes mean - // that we must replace rather than update an existing remote object. - // However, we only need to do that if the identified attributes _have_ - // actually changed -- particularly after we may have undone some of the - // changes in processIgnoreChanges -- so now we'll filter that list to - // include only where changes are detected. - reqRep := cty.NewPathSet() - if len(resp.RequiresReplace) > 0 { - for _, path := range resp.RequiresReplace { - if priorVal.IsNull() { - // If prior is null then we don't expect any RequiresReplace at all, - // because this is a Create action. - continue - } - - priorChangedVal, priorPathDiags := hcl.ApplyPath(priorVal, path, nil) - plannedChangedVal, plannedPathDiags := hcl.ApplyPath(plannedNewVal, path, nil) - if plannedPathDiags.HasErrors() && priorPathDiags.HasErrors() { - // This means the path was invalid in both the prior and new - // values, which is an error with the provider itself. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid plan", - fmt.Sprintf( - "Provider %q has indicated \"requires replacement\" on %s for a non-existent attribute path %#v.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, absAddr, path, - ), - )) - continue - } - - // Make sure we have valid Values for both values. - // Note: if the opposing value was of the type - // cty.DynamicPseudoType, the type assigned here may not exactly - // match the schema. This is fine here, since we're only going to - // check for equality, but if the NullVal is to be used, we need to - // check the schema for th true type. - switch { - case priorChangedVal == cty.NilVal && plannedChangedVal == cty.NilVal: - // this should never happen without ApplyPath errors above - panic("requires replace path returned 2 nil values") - case priorChangedVal == cty.NilVal: - priorChangedVal = cty.NullVal(plannedChangedVal.Type()) - case plannedChangedVal == cty.NilVal: - plannedChangedVal = cty.NullVal(priorChangedVal.Type()) - } - - eqV := plannedChangedVal.Equals(priorChangedVal) - if !eqV.IsKnown() || eqV.False() { - reqRep.Add(path) - } - } - if diags.HasErrors() { - return nil, diags.Err() - } - } - - eqV := plannedNewVal.Equals(priorVal) - eq := eqV.IsKnown() && eqV.True() - - var action plans.Action - switch { - case priorVal.IsNull(): - action = plans.Create - case eq: - action = plans.NoOp - case !reqRep.Empty(): - // If there are any "requires replace" paths left _after our filtering - // above_ then this is a replace action. - if n.CreateBeforeDestroy { - action = plans.CreateThenDelete - } else { - action = plans.DeleteThenCreate - } - default: - action = plans.Update - // "Delete" is never chosen here, because deletion plans are always - // created more directly elsewhere, such as in "orphan" handling. - } - - if action.IsReplace() { - // In this strange situation we want to produce a change object that - // shows our real prior object but has a _new_ object that is built - // from a null prior object, since we're going to delete the one - // that has all the computed values on it. - // - // Therefore we'll ask the provider to plan again here, giving it - // a null object for the prior, and then we'll meld that with the - // _actual_ prior state to produce a correctly-shaped replace change. - // The resulting change should show any computed attributes changing - // from known prior values to unknown values, unless the provider is - // able to predict new values for any of these computed attributes. - nullPriorVal := cty.NullVal(schema.ImpliedType()) - - // create a new proposed value from the null state and the config - proposedNewVal = objchange.ProposedNewObject(schema, nullPriorVal, configVal) - - resp = provider.PlanResourceChange(providers.PlanResourceChangeRequest{ - TypeName: n.Addr.Resource.Type, - Config: configVal, - PriorState: nullPriorVal, - ProposedNewState: proposedNewVal, - PriorPrivate: plannedPrivate, - }) - // We need to tread carefully here, since if there are any warnings - // in here they probably also came out of our previous call to - // PlanResourceChange above, and so we don't want to repeat them. - // Consequently, we break from the usual pattern here and only - // append these new diagnostics if there's at least one error inside. - if resp.Diagnostics.HasErrors() { - diags = diags.Append(resp.Diagnostics.InConfigBody(config.Config)) - return nil, diags.Err() - } - plannedNewVal = resp.PlannedState - plannedPrivate = resp.PlannedPrivate - for _, err := range plannedNewVal.Type().TestConformance(schema.ImpliedType()) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid plan", - fmt.Sprintf( - "Provider %q planned an invalid value for %s%s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, absAddr, tfdiags.FormatError(err), - ), - )) - } - if diags.HasErrors() { - return nil, diags.Err() - } - } - - // If our prior value was tainted then we actually want this to appear - // as a replace change, even though so far we've been treating it as a - // create. - if action == plans.Create && priorValTainted != cty.NilVal { - if n.CreateBeforeDestroy { - action = plans.CreateThenDelete - } else { - action = plans.DeleteThenCreate - } - priorVal = priorValTainted - } - - // As a special case, if we have a previous diff (presumably from the plan - // phases, whereas we're now in the apply phase) and it was for a replace, - // we've already deleted the original object from state by the time we - // get here and so we would've ended up with a _create_ action this time, - // which we now need to paper over to get a result consistent with what - // we originally intended. - if n.PreviousDiff != nil { - prevChange := *n.PreviousDiff - if prevChange.Action.IsReplace() && action == plans.Create { - log.Printf("[TRACE] EvalDiff: %s treating Create change as %s change to match with earlier plan", absAddr, prevChange.Action) - action = prevChange.Action - priorVal = prevChange.Before - } - } - - // Call post-refresh hook - if !n.Stub { - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostDiff(absAddr, states.CurrentGen, action, priorVal, plannedNewVal) - }) - if err != nil { - return nil, err - } - } - - // Update our output if we care - if n.OutputChange != nil { - *n.OutputChange = &plans.ResourceInstanceChange{ - Addr: absAddr, - Private: plannedPrivate, - ProviderAddr: n.ProviderAddr, - Change: plans.Change{ - Action: action, - Before: priorVal, - After: plannedNewVal, - }, - RequiredReplace: reqRep, - } - } - - if n.OutputValue != nil { - *n.OutputValue = configVal - } - - // Update the state if we care - if n.OutputState != nil { - *n.OutputState = &states.ResourceInstanceObject{ - // We use the special "planned" status here to note that this - // object's value is not yet complete. Objects with this status - // cannot be used during expression evaluation, so the caller - // must _also_ record the returned change in the active plan, - // which the expression evaluator will use in preference to this - // incomplete value recorded in the state. - Status: states.ObjectPlanned, - Value: plannedNewVal, - Private: plannedPrivate, - } - } - - return nil, nil -} - -func (n *EvalDiff) processIgnoreChanges(prior, proposed cty.Value) (cty.Value, tfdiags.Diagnostics) { - // ignore_changes only applies when an object already exists, since we - // can't ignore changes to a thing we've not created yet. - if prior.IsNull() { - return proposed, nil - } - - ignoreChanges := n.Config.Managed.IgnoreChanges - ignoreAll := n.Config.Managed.IgnoreAllChanges - - if len(ignoreChanges) == 0 && !ignoreAll { - return proposed, nil - } - if ignoreAll { - return prior, nil - } - if prior.IsNull() || proposed.IsNull() { - // Ignore changes doesn't apply when we're creating for the first time. - // Proposed should never be null here, but if it is then we'll just let it be. - return proposed, nil - } - - return processIgnoreChangesIndividual(prior, proposed, ignoreChanges) -} - -func processIgnoreChangesIndividual(prior, proposed cty.Value, ignoreChanges []hcl.Traversal) (cty.Value, tfdiags.Diagnostics) { - // When we walk below we will be using cty.Path values for comparison, so - // we'll convert our traversals here so we can compare more easily. - ignoreChangesPath := make([]cty.Path, len(ignoreChanges)) - for i, traversal := range ignoreChanges { - path := make(cty.Path, len(traversal)) - for si, step := range traversal { - switch ts := step.(type) { - case hcl.TraverseRoot: - path[si] = cty.GetAttrStep{ - Name: ts.Name, - } - case hcl.TraverseAttr: - path[si] = cty.GetAttrStep{ - Name: ts.Name, - } - case hcl.TraverseIndex: - path[si] = cty.IndexStep{ - Key: ts.Key, - } - default: - panic(fmt.Sprintf("unsupported traversal step %#v", step)) - } - } - ignoreChangesPath[i] = path - } - - var diags tfdiags.Diagnostics - ret, _ := cty.Transform(proposed, func(path cty.Path, v cty.Value) (cty.Value, error) { - // First we must see if this is a path that's being ignored at all. - // We're looking for an exact match here because this walk will visit - // leaf values first and then their containers, and we want to do - // the "ignore" transform once we reach the point indicated, throwing - // away any deeper values we already produced at that point. - var ignoreTraversal hcl.Traversal - for i, candidate := range ignoreChangesPath { - if path.Equals(candidate) { - ignoreTraversal = ignoreChanges[i] - } - } - if ignoreTraversal == nil { - return v, nil - } - - // If we're able to follow the same path through the prior value, - // we'll take the value there instead, effectively undoing the - // change that was planned. - priorV, diags := hcl.ApplyPath(prior, path, nil) - if diags.HasErrors() { - // We just ignore the errors and move on here, since we assume it's - // just because the prior value was a slightly-different shape. - // It could potentially also be that the traversal doesn't match - // the schema, but we should've caught that during the validate - // walk if so. - return v, nil - } - return priorV, nil - }) - return ret, diags -} - -// EvalDiffDestroy is an EvalNode implementation that returns a plain -// destroy diff. -type EvalDiffDestroy struct { - Addr addrs.ResourceInstance - DeposedKey states.DeposedKey - State **states.ResourceInstanceObject - ProviderAddr addrs.AbsProviderConfig - - Output **plans.ResourceInstanceChange - OutputState **states.ResourceInstanceObject -} - -// TODO: test -func (n *EvalDiffDestroy) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - state := *n.State - - if n.ProviderAddr.ProviderConfig.Type == "" { - if n.DeposedKey == "" { - panic(fmt.Sprintf("EvalDiffDestroy for %s does not have ProviderAddr set", absAddr)) - } else { - panic(fmt.Sprintf("EvalDiffDestroy for %s (deposed %s) does not have ProviderAddr set", absAddr, n.DeposedKey)) - } - } - - // If there is no state or our attributes object is null then we're already - // destroyed. - if state == nil || state.Value.IsNull() { - return nil, nil - } - - // Call pre-diff hook - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreDiff( - absAddr, n.DeposedKey.Generation(), - state.Value, - cty.NullVal(cty.DynamicPseudoType), - ) - }) - if err != nil { - return nil, err - } - - // Change is always the same for a destroy. We don't need the provider's - // help for this one. - // TODO: Should we give the provider an opportunity to veto this? - change := &plans.ResourceInstanceChange{ - Addr: absAddr, - DeposedKey: n.DeposedKey, - Change: plans.Change{ - Action: plans.Delete, - Before: state.Value, - After: cty.NullVal(cty.DynamicPseudoType), - }, - Private: state.Private, - ProviderAddr: n.ProviderAddr, - } - - // Call post-diff hook - err = ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostDiff( - absAddr, - n.DeposedKey.Generation(), - change.Action, - change.Before, - change.After, - ) - }) - if err != nil { - return nil, err - } - - // Update our output - *n.Output = change - - if n.OutputState != nil { - // Record our proposed new state, which is nil because we're destroying. - *n.OutputState = nil - } - - return nil, nil -} - -// EvalReduceDiff is an EvalNode implementation that takes a planned resource -// instance change as might be produced by EvalDiff or EvalDiffDestroy and -// "simplifies" it to a single atomic action to be performed by a specific -// graph node. -// -// Callers must specify whether they are a destroy node or a regular apply -// node. If the result is NoOp then the given change requires no action for -// the specific graph node calling this and so evaluation of the that graph -// node should exit early and take no action. -// -// The object written to OutChange may either be identical to InChange or -// a new change object derived from InChange. Because of the former case, the -// caller must not mutate the object returned in OutChange. -type EvalReduceDiff struct { - Addr addrs.ResourceInstance - InChange **plans.ResourceInstanceChange - Destroy bool - OutChange **plans.ResourceInstanceChange -} - -// TODO: test -func (n *EvalReduceDiff) Eval(ctx EvalContext) (interface{}, error) { - in := *n.InChange - out := in.Simplify(n.Destroy) - if n.OutChange != nil { - *n.OutChange = out - } - if out.Action != in.Action { - if n.Destroy { - log.Printf("[TRACE] EvalReduceDiff: %s change simplified from %s to %s for destroy node", n.Addr, in.Action, out.Action) - } else { - log.Printf("[TRACE] EvalReduceDiff: %s change simplified from %s to %s for apply node", n.Addr, in.Action, out.Action) - } - } - return nil, nil -} - -// EvalReadDiff is an EvalNode implementation that retrieves the planned -// change for a particular resource instance object. -type EvalReadDiff struct { - Addr addrs.ResourceInstance - DeposedKey states.DeposedKey - ProviderSchema **ProviderSchema - Change **plans.ResourceInstanceChange -} - -func (n *EvalReadDiff) Eval(ctx EvalContext) (interface{}, error) { - providerSchema := *n.ProviderSchema - changes := ctx.Changes() - addr := n.Addr.Absolute(ctx.Path()) - - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support resource type %q", n.Addr.Resource.Type) - } - - gen := states.CurrentGen - if n.DeposedKey != states.NotDeposed { - gen = n.DeposedKey - } - csrc := changes.GetResourceInstanceChange(addr, gen) - if csrc == nil { - log.Printf("[TRACE] EvalReadDiff: No planned change recorded for %s", addr) - return nil, nil - } - - change, err := csrc.Decode(schema.ImpliedType()) - if err != nil { - return nil, fmt.Errorf("failed to decode planned changes for %s: %s", addr, err) - } - if n.Change != nil { - *n.Change = change - } - - log.Printf("[TRACE] EvalReadDiff: Read %s change from plan for %s", change.Action, addr) - - return nil, nil -} - -// EvalWriteDiff is an EvalNode implementation that saves a planned change -// for an instance object into the set of global planned changes. -type EvalWriteDiff struct { - Addr addrs.ResourceInstance - DeposedKey states.DeposedKey - ProviderSchema **ProviderSchema - Change **plans.ResourceInstanceChange -} - -// TODO: test -func (n *EvalWriteDiff) Eval(ctx EvalContext) (interface{}, error) { - changes := ctx.Changes() - addr := n.Addr.Absolute(ctx.Path()) - if n.Change == nil || *n.Change == nil { - // Caller sets nil to indicate that we need to remove a change from - // the set of changes. - gen := states.CurrentGen - if n.DeposedKey != states.NotDeposed { - gen = n.DeposedKey - } - changes.RemoveResourceInstanceChange(addr, gen) - return nil, nil - } - - providerSchema := *n.ProviderSchema - change := *n.Change - - if change.Addr.String() != addr.String() || change.DeposedKey != n.DeposedKey { - // Should never happen, and indicates a bug in the caller. - panic("inconsistent address and/or deposed key in EvalWriteDiff") - } - - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support resource type %q", n.Addr.Resource.Type) - } - - csrc, err := change.Encode(schema.ImpliedType()) - if err != nil { - return nil, fmt.Errorf("failed to encode planned changes for %s: %s", addr, err) - } - - changes.AppendResourceInstanceChange(csrc) - if n.DeposedKey == states.NotDeposed { - log.Printf("[TRACE] EvalWriteDiff: recorded %s change for %s", change.Action, addr) - } else { - log.Printf("[TRACE] EvalWriteDiff: recorded %s change for %s deposed object %s", change.Action, addr, n.DeposedKey) - } - - return nil, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_error.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_error.go deleted file mode 100644 index 470f798b7fc..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_error.go +++ /dev/null @@ -1,20 +0,0 @@ -package terraform - -// EvalReturnError is an EvalNode implementation that returns an -// error if it is present. -// -// This is useful for scenarios where an error has been captured by -// another EvalNode (like EvalApply) for special EvalTree-based error -// handling, and that handling has completed, so the error should be -// returned normally. -type EvalReturnError struct { - Error *error -} - -func (n *EvalReturnError) Eval(ctx EvalContext) (interface{}, error) { - if n.Error == nil { - return nil, nil - } - - return nil, *n.Error -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_filter.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_filter.go deleted file mode 100644 index 711c625c836..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_filter.go +++ /dev/null @@ -1,25 +0,0 @@ -package terraform - -// EvalNodeFilterFunc is the callback used to replace a node with -// another to node. To not do the replacement, just return the input node. -type EvalNodeFilterFunc func(EvalNode) EvalNode - -// EvalNodeFilterable is an interface that can be implemented by -// EvalNodes to allow filtering of sub-elements. Note that this isn't -// a common thing to implement and you probably don't need it. -type EvalNodeFilterable interface { - EvalNode - Filter(EvalNodeFilterFunc) -} - -// EvalFilter runs the filter on the given node and returns the -// final filtered value. This should be called rather than checking -// the EvalNode directly since this will properly handle EvalNodeFilterables. -func EvalFilter(node EvalNode, fn EvalNodeFilterFunc) EvalNode { - if f, ok := node.(EvalNodeFilterable); ok { - f.Filter(fn) - return node - } - - return fn(node) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_filter_operation.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_filter_operation.go deleted file mode 100644 index 1a55f024a81..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_filter_operation.go +++ /dev/null @@ -1,49 +0,0 @@ -package terraform - -// EvalNodeOpFilterable is an interface that EvalNodes can implement -// to be filterable by the operation that is being run on Terraform. -type EvalNodeOpFilterable interface { - IncludeInOp(walkOperation) bool -} - -// EvalNodeFilterOp returns a filter function that filters nodes that -// include themselves in specific operations. -func EvalNodeFilterOp(op walkOperation) EvalNodeFilterFunc { - return func(n EvalNode) EvalNode { - include := true - if of, ok := n.(EvalNodeOpFilterable); ok { - include = of.IncludeInOp(op) - } - if include { - return n - } - - return EvalNoop{} - } -} - -// EvalOpFilter is an EvalNode implementation that is a proxy to -// another node but filters based on the operation. -type EvalOpFilter struct { - // Ops is the list of operations to include this node in. - Ops []walkOperation - - // Node is the node to execute - Node EvalNode -} - -// TODO: test -func (n *EvalOpFilter) Eval(ctx EvalContext) (interface{}, error) { - return EvalRaw(n.Node, ctx) -} - -// EvalNodeOpFilterable impl. -func (n *EvalOpFilter) IncludeInOp(op walkOperation) bool { - for _, v := range n.Ops { - if v == op { - return true - } - } - - return false -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_for_each.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_for_each.go deleted file mode 100644 index a63389a9149..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_for_each.go +++ /dev/null @@ -1,95 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" -) - -// evaluateResourceForEachExpression interprets a "for_each" argument on a resource. -// -// Returns a cty.Value map, and diagnostics if necessary. It will return nil if -// the expression is nil, and is used to distinguish between an unset for_each and an -// empty map -func evaluateResourceForEachExpression(expr hcl.Expression, ctx EvalContext) (forEach map[string]cty.Value, diags tfdiags.Diagnostics) { - forEachMap, known, diags := evaluateResourceForEachExpressionKnown(expr, ctx) - if !known { - // Attach a diag as we do with count, with the same downsides - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid for_each argument", - Detail: `The "for_each" value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how many instances will be created. To work around this, use the -target argument to first apply only the resources that the for_each depends on.`, - Subject: expr.Range().Ptr(), - }) - } - return forEachMap, diags -} - -// evaluateResourceForEachExpressionKnown is like evaluateResourceForEachExpression -// except that it handles an unknown result by returning an empty map and -// a known = false, rather than by reporting the unknown value as an error -// diagnostic. -func evaluateResourceForEachExpressionKnown(expr hcl.Expression, ctx EvalContext) (forEach map[string]cty.Value, known bool, diags tfdiags.Diagnostics) { - if expr == nil { - return nil, true, nil - } - - forEachVal, forEachDiags := ctx.EvaluateExpr(expr, cty.DynamicPseudoType, nil) - diags = diags.Append(forEachDiags) - if diags.HasErrors() { - return nil, true, diags - } - - switch { - case forEachVal.IsNull(): - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid for_each argument", - Detail: `The given "for_each" argument value is unsuitable: the given "for_each" argument value is null. A map, or set of strings is allowed.`, - Subject: expr.Range().Ptr(), - }) - return nil, true, diags - case !forEachVal.IsKnown(): - return map[string]cty.Value{}, false, diags - } - - if !forEachVal.CanIterateElements() || forEachVal.Type().IsListType() || forEachVal.Type().IsTupleType() { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid for_each argument", - Detail: fmt.Sprintf(`The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type %s.`, forEachVal.Type().FriendlyName()), - Subject: expr.Range().Ptr(), - }) - return nil, true, diags - } - - // If the map is empty ({}), return an empty map, because cty will return nil when representing {} AsValueMap - // This also covers an empty set (toset([])) - if forEachVal.LengthInt() == 0 { - return map[string]cty.Value{}, true, diags - } - - if forEachVal.Type().IsSetType() { - if forEachVal.Type().ElementType() != cty.String { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid for_each set argument", - Detail: fmt.Sprintf(`The given "for_each" argument value is unsuitable: "for_each" supports maps and sets of strings, but you have provided a set containing type %s.`, forEachVal.Type().ElementType().FriendlyName()), - Subject: expr.Range().Ptr(), - }) - return nil, true, diags - } - - // A set may contain unknown values that must be - // discovered by checking with IsWhollyKnown (which iterates through the - // structure), while for maps in cty, keys can never be unknown or null, - // thus the earlier IsKnown check suffices for maps - if !forEachVal.IsWhollyKnown() { - return map[string]cty.Value{}, false, diags - } - } - - return forEachVal.AsValueMap(), true, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_if.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_if.go deleted file mode 100644 index d6b46a1f222..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_if.go +++ /dev/null @@ -1,26 +0,0 @@ -package terraform - -// EvalIf is an EvalNode that is a conditional. -type EvalIf struct { - If func(EvalContext) (bool, error) - Then EvalNode - Else EvalNode -} - -// TODO: test -func (n *EvalIf) Eval(ctx EvalContext) (interface{}, error) { - yes, err := n.If(ctx) - if err != nil { - return nil, err - } - - if yes { - return EvalRaw(n.Then, ctx) - } else { - if n.Else != nil { - return EvalRaw(n.Else, ctx) - } - } - - return nil, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_import_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_import_state.go deleted file mode 100644 index 25a2aae06b1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_import_state.go +++ /dev/null @@ -1,95 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalImportState is an EvalNode implementation that performs an -// ImportState operation on a provider. This will return the imported -// states but won't modify any actual state. -type EvalImportState struct { - Addr addrs.ResourceInstance - Provider *providers.Interface - ID string - Output *[]providers.ImportedResource -} - -// TODO: test -func (n *EvalImportState) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - provider := *n.Provider - var diags tfdiags.Diagnostics - - { - // Call pre-import hook - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreImportState(absAddr, n.ID) - }) - if err != nil { - return nil, err - } - } - - resp := provider.ImportResourceState(providers.ImportResourceStateRequest{ - TypeName: n.Addr.Resource.Type, - ID: n.ID, - }) - diags = diags.Append(resp.Diagnostics) - if diags.HasErrors() { - return nil, diags.Err() - } - - imported := resp.ImportedResources - - for _, obj := range imported { - log.Printf("[TRACE] EvalImportState: import %s %q produced instance object of type %s", absAddr.String(), n.ID, obj.TypeName) - } - - if n.Output != nil { - *n.Output = imported - } - - { - // Call post-import hook - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostImportState(absAddr, imported) - }) - if err != nil { - return nil, err - } - } - - return nil, nil -} - -// EvalImportStateVerify verifies the state after ImportState and -// after the refresh to make sure it is non-nil and valid. -type EvalImportStateVerify struct { - Addr addrs.ResourceInstance - State **states.ResourceInstanceObject -} - -// TODO: test -func (n *EvalImportStateVerify) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - - state := *n.State - if state.Value.IsNull() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Cannot import non-existent remote object", - fmt.Sprintf( - "While attempting to import an existing object to %s, the provider detected that no object exists with the given id. Only pre-existing objects can be imported; check that the id is correct and that it is associated with the provider's configured region or endpoint, or use \"terraform apply\" to create a new remote object for this resource.", - n.Addr.String(), - ), - )) - } - - return nil, diags.ErrWithWarnings() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_lang.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_lang.go deleted file mode 100644 index 5ab6b44f5ca..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_lang.go +++ /dev/null @@ -1,61 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/zclconf/go-cty/cty" -) - -// EvalConfigBlock is an EvalNode implementation that takes a raw -// configuration block and evaluates any expressions within it. -// -// ExpandedConfig is populated with the result of expanding any "dynamic" -// blocks in the given body, which can be useful for extracting correct source -// location information for specific attributes in the result. -type EvalConfigBlock struct { - Config *hcl.Body - Schema *configschema.Block - SelfAddr addrs.Referenceable - Output *cty.Value - ExpandedConfig *hcl.Body - ContinueOnErr bool -} - -func (n *EvalConfigBlock) Eval(ctx EvalContext) (interface{}, error) { - val, body, diags := ctx.EvaluateBlock(*n.Config, n.Schema, n.SelfAddr, EvalDataForNoInstanceKey) - if diags.HasErrors() && n.ContinueOnErr { - log.Printf("[WARN] Block evaluation failed: %s", diags.Err()) - return nil, EvalEarlyExitError{} - } - - if n.Output != nil { - *n.Output = val - } - if n.ExpandedConfig != nil { - *n.ExpandedConfig = body - } - - return nil, diags.ErrWithWarnings() -} - -// EvalConfigExpr is an EvalNode implementation that takes a raw configuration -// expression and evaluates it. -type EvalConfigExpr struct { - Expr hcl.Expression - SelfAddr addrs.Referenceable - Output *cty.Value -} - -func (n *EvalConfigExpr) Eval(ctx EvalContext) (interface{}, error) { - val, diags := ctx.EvaluateExpr(n.Expr, cty.DynamicPseudoType, n.SelfAddr) - - if n.Output != nil { - *n.Output = val - } - - return nil, diags.ErrWithWarnings() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_local.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_local.go deleted file mode 100644 index 03101938021..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_local.go +++ /dev/null @@ -1,74 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalLocal is an EvalNode implementation that evaluates the -// expression for a local value and writes it into a transient part of -// the state. -type EvalLocal struct { - Addr addrs.LocalValue - Expr hcl.Expression -} - -func (n *EvalLocal) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - - // We ignore diags here because any problems we might find will be found - // again in EvaluateExpr below. - refs, _ := lang.ReferencesInExpr(n.Expr) - for _, ref := range refs { - if ref.Subject == n.Addr { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Self-referencing local value", - Detail: fmt.Sprintf("Local value %s cannot use its own result as part of its expression.", n.Addr), - Subject: ref.SourceRange.ToHCL().Ptr(), - Context: n.Expr.Range().Ptr(), - }) - } - } - if diags.HasErrors() { - return nil, diags.Err() - } - - val, moreDiags := ctx.EvaluateExpr(n.Expr, cty.DynamicPseudoType, nil) - diags = diags.Append(moreDiags) - if moreDiags.HasErrors() { - return nil, diags.Err() - } - - state := ctx.State() - if state == nil { - return nil, fmt.Errorf("cannot write local value to nil state") - } - - state.SetLocalValue(n.Addr.Absolute(ctx.Path()), val) - - return nil, nil -} - -// EvalDeleteLocal is an EvalNode implementation that deletes a Local value -// from the state. Locals aren't persisted, but we don't need to evaluate them -// during destroy. -type EvalDeleteLocal struct { - Addr addrs.LocalValue -} - -func (n *EvalDeleteLocal) Eval(ctx EvalContext) (interface{}, error) { - state := ctx.State() - if state == nil { - return nil, nil - } - - state.RemoveLocalValue(n.Addr.Absolute(ctx.Path())) - return nil, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_noop.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_noop.go deleted file mode 100644 index f4bc8225c54..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_noop.go +++ /dev/null @@ -1,8 +0,0 @@ -package terraform - -// EvalNoop is an EvalNode that does nothing. -type EvalNoop struct{} - -func (EvalNoop) Eval(EvalContext) (interface{}, error) { - return nil, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_output.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_output.go deleted file mode 100644 index 9f71e92f651..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_output.go +++ /dev/null @@ -1,135 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// EvalDeleteOutput is an EvalNode implementation that deletes an output -// from the state. -type EvalDeleteOutput struct { - Addr addrs.OutputValue -} - -// TODO: test -func (n *EvalDeleteOutput) Eval(ctx EvalContext) (interface{}, error) { - state := ctx.State() - if state == nil { - return nil, nil - } - - state.RemoveOutputValue(n.Addr.Absolute(ctx.Path())) - return nil, nil -} - -// EvalWriteOutput is an EvalNode implementation that writes the output -// for the given name to the current state. -type EvalWriteOutput struct { - Addr addrs.OutputValue - Sensitive bool - Expr hcl.Expression - // ContinueOnErr allows interpolation to fail during Input - ContinueOnErr bool -} - -// TODO: test -func (n *EvalWriteOutput) Eval(ctx EvalContext) (interface{}, error) { - addr := n.Addr.Absolute(ctx.Path()) - - // This has to run before we have a state lock, since evaluation also - // reads the state - val, diags := ctx.EvaluateExpr(n.Expr, cty.DynamicPseudoType, nil) - // We'll handle errors below, after we have loaded the module. - - state := ctx.State() - if state == nil { - return nil, nil - } - - changes := ctx.Changes() // may be nil, if we're not working on a changeset - - // handling the interpolation error - if diags.HasErrors() { - if n.ContinueOnErr || flagWarnOutputErrors { - log.Printf("[ERROR] Output interpolation %q failed: %s", n.Addr.Name, diags.Err()) - // if we're continuing, make sure the output is included, and - // marked as unknown. If the evaluator was able to find a type - // for the value in spite of the error then we'll use it. - n.setValue(addr, state, changes, cty.UnknownVal(val.Type())) - return nil, EvalEarlyExitError{} - } - return nil, diags.Err() - } - - n.setValue(addr, state, changes, val) - - return nil, nil -} - -func (n *EvalWriteOutput) setValue(addr addrs.AbsOutputValue, state *states.SyncState, changes *plans.ChangesSync, val cty.Value) { - if val.IsKnown() && !val.IsNull() { - // The state itself doesn't represent unknown values, so we null them - // out here and then we'll save the real unknown value in the planned - // changeset below, if we have one on this graph walk. - log.Printf("[TRACE] EvalWriteOutput: Saving value for %s in state", addr) - stateVal := cty.UnknownAsNull(val) - state.SetOutputValue(addr, stateVal, n.Sensitive) - } else { - log.Printf("[TRACE] EvalWriteOutput: Removing %s from state (it is now null)", addr) - state.RemoveOutputValue(addr) - } - - // If we also have an active changeset then we'll replicate the value in - // there. This is used in preference to the state where present, since it - // *is* able to represent unknowns, while the state cannot. - if changes != nil { - // For the moment we are not properly tracking changes to output - // values, and just marking them always as "Create" or "Destroy" - // actions. A future release will rework the output lifecycle so we - // can track their changes properly, in a similar way to how we work - // with resource instances. - - var change *plans.OutputChange - if !val.IsNull() { - change = &plans.OutputChange{ - Addr: addr, - Sensitive: n.Sensitive, - Change: plans.Change{ - Action: plans.Create, - Before: cty.NullVal(cty.DynamicPseudoType), - After: val, - }, - } - } else { - change = &plans.OutputChange{ - Addr: addr, - Sensitive: n.Sensitive, - Change: plans.Change{ - // This is just a weird placeholder delete action since - // we don't have an actual prior value to indicate. - // FIXME: Generate real planned changes for output values - // that include the old values. - Action: plans.Delete, - Before: cty.NullVal(cty.DynamicPseudoType), - After: cty.NullVal(cty.DynamicPseudoType), - }, - } - } - - cs, err := change.Encode() - if err != nil { - // Should never happen, since we just constructed this right above - panic(fmt.Sprintf("planned change for %s could not be encoded: %s", addr, err)) - } - log.Printf("[TRACE] EvalWriteOutput: Saving %s change for %s in changeset", change.Action, addr) - changes.RemoveOutputChange(addr) // remove any existing planned change, if present - changes.AppendOutputChange(cs) // add the new planned change - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provider.go deleted file mode 100644 index 7440cff7adf..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provider.go +++ /dev/null @@ -1,147 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/hcl/v2" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -func buildProviderConfig(ctx EvalContext, addr addrs.ProviderConfig, config *configs.Provider) hcl.Body { - var configBody hcl.Body - if config != nil { - configBody = config.Config - } - - var inputBody hcl.Body - inputConfig := ctx.ProviderInput(addr) - if len(inputConfig) > 0 { - inputBody = configs.SynthBody("", inputConfig) - } - - switch { - case configBody != nil && inputBody != nil: - log.Printf("[TRACE] buildProviderConfig for %s: merging explicit config and input", addr) - // Note that the inputBody is the _base_ here, because configs.MergeBodies - // expects the base have all of the required fields, while these are - // forced to be optional for the override. The input process should - // guarantee that we have a value for each of the required arguments and - // that in practice the sets of attributes in each body will be - // disjoint. - return configs.MergeBodies(inputBody, configBody) - case configBody != nil: - log.Printf("[TRACE] buildProviderConfig for %s: using explicit config only", addr) - return configBody - case inputBody != nil: - log.Printf("[TRACE] buildProviderConfig for %s: using input only", addr) - return inputBody - default: - log.Printf("[TRACE] buildProviderConfig for %s: no configuration at all", addr) - return hcl.EmptyBody() - } -} - -// EvalConfigProvider is an EvalNode implementation that configures -// a provider that is already initialized and retrieved. -type EvalConfigProvider struct { - Addr addrs.ProviderConfig - Provider *providers.Interface - Config *configs.Provider -} - -func (n *EvalConfigProvider) Eval(ctx EvalContext) (interface{}, error) { - if n.Provider == nil { - return nil, fmt.Errorf("EvalConfigProvider Provider is nil") - } - - var diags tfdiags.Diagnostics - provider := *n.Provider - config := n.Config - - configBody := buildProviderConfig(ctx, n.Addr, config) - - resp := provider.GetSchema() - diags = diags.Append(resp.Diagnostics) - if diags.HasErrors() { - return nil, diags.NonFatalErr() - } - - configSchema := resp.Provider.Block - configVal, configBody, evalDiags := ctx.EvaluateBlock(configBody, configSchema, nil, EvalDataForNoInstanceKey) - diags = diags.Append(evalDiags) - if evalDiags.HasErrors() { - return nil, diags.NonFatalErr() - } - - configDiags := ctx.ConfigureProvider(n.Addr, configVal) - configDiags = configDiags.InConfigBody(configBody) - - return nil, configDiags.ErrWithWarnings() -} - -// EvalInitProvider is an EvalNode implementation that initializes a provider -// and returns nothing. The provider can be retrieved again with the -// EvalGetProvider node. -type EvalInitProvider struct { - TypeName string - Addr addrs.ProviderConfig -} - -func (n *EvalInitProvider) Eval(ctx EvalContext) (interface{}, error) { - return ctx.InitProvider(n.TypeName, n.Addr) -} - -// EvalCloseProvider is an EvalNode implementation that closes provider -// connections that aren't needed anymore. -type EvalCloseProvider struct { - Addr addrs.ProviderConfig -} - -func (n *EvalCloseProvider) Eval(ctx EvalContext) (interface{}, error) { - ctx.CloseProvider(n.Addr) - return nil, nil -} - -// EvalGetProvider is an EvalNode implementation that retrieves an already -// initialized provider instance for the given name. -// -// Unlike most eval nodes, this takes an _absolute_ provider configuration, -// because providers can be passed into and inherited between modules. -// Resource nodes must therefore know the absolute path of the provider they -// will use, which is usually accomplished by implementing -// interface GraphNodeProviderConsumer. -type EvalGetProvider struct { - Addr addrs.AbsProviderConfig - Output *providers.Interface - - // If non-nil, Schema will be updated after eval to refer to the - // schema of the provider. - Schema **ProviderSchema -} - -func (n *EvalGetProvider) Eval(ctx EvalContext) (interface{}, error) { - if n.Addr.ProviderConfig.Type == "" { - // Should never happen - panic("EvalGetProvider used with uninitialized provider configuration address") - } - - result := ctx.Provider(n.Addr) - if result == nil { - return nil, fmt.Errorf("provider %s not initialized", n.Addr) - } - - if n.Output != nil { - *n.Output = result - } - - if n.Schema != nil { - *n.Schema = ctx.ProviderSchema(n.Addr) - } - - return nil, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provisioner.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provisioner.go deleted file mode 100644 index 405ce9d0bd5..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provisioner.go +++ /dev/null @@ -1,55 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" -) - -// EvalInitProvisioner is an EvalNode implementation that initializes a provisioner -// and returns nothing. The provisioner can be retrieved again with the -// EvalGetProvisioner node. -type EvalInitProvisioner struct { - Name string -} - -func (n *EvalInitProvisioner) Eval(ctx EvalContext) (interface{}, error) { - return ctx.InitProvisioner(n.Name) -} - -// EvalCloseProvisioner is an EvalNode implementation that closes provisioner -// connections that aren't needed anymore. -type EvalCloseProvisioner struct { - Name string -} - -func (n *EvalCloseProvisioner) Eval(ctx EvalContext) (interface{}, error) { - ctx.CloseProvisioner(n.Name) - return nil, nil -} - -// EvalGetProvisioner is an EvalNode implementation that retrieves an already -// initialized provisioner instance for the given name. -type EvalGetProvisioner struct { - Name string - Output *provisioners.Interface - Schema **configschema.Block -} - -func (n *EvalGetProvisioner) Eval(ctx EvalContext) (interface{}, error) { - result := ctx.Provisioner(n.Name) - if result == nil { - return nil, fmt.Errorf("provisioner %s not initialized", n.Name) - } - - if n.Output != nil { - *n.Output = result - } - - if n.Schema != nil { - *n.Schema = ctx.ProvisionerSchema(n.Name) - } - - return result, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_read_data.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_read_data.go deleted file mode 100644 index 0b734b793f3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_read_data.go +++ /dev/null @@ -1,395 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalReadData is an EvalNode implementation that deals with the main part -// of the data resource lifecycle: either actually reading from the data source -// or generating a plan to do so. -type EvalReadData struct { - Addr addrs.ResourceInstance - Config *configs.Resource - Dependencies []addrs.Referenceable - Provider *providers.Interface - ProviderAddr addrs.AbsProviderConfig - ProviderSchema **ProviderSchema - - // Planned is set when dealing with data resources that were deferred to - // the apply walk, to let us see what was planned. If this is set, the - // evaluation of the config is required to produce a wholly-known - // configuration which is consistent with the partial object included - // in this planned change. - Planned **plans.ResourceInstanceChange - - // ForcePlanRead, if true, overrides the usual behavior of immediately - // reading from the data source where possible, instead forcing us to - // _always_ generate a plan. This is used during the plan walk, since we - // mustn't actually apply anything there. (The resulting state doesn't - // get persisted) - ForcePlanRead bool - - // The result from this EvalNode has a few different possibilities - // depending on the input: - // - If Planned is nil then we assume we're aiming to _produce_ the plan, - // and so the following two outcomes are possible: - // - OutputChange.Action is plans.NoOp and OutputState is the complete - // result of reading from the data source. This is the easy path. - // - OutputChange.Action is plans.Read and OutputState is a planned - // object placeholder (states.ObjectPlanned). In this case, the - // returned change must be recorded in the overral changeset and - // eventually passed to another instance of this struct during the - // apply walk. - // - If Planned is non-nil then we assume we're aiming to complete a - // planned read from an earlier plan walk. In this case the only possible - // non-error outcome is to set Output.Action (if non-nil) to a plans.NoOp - // change and put the complete resulting state in OutputState, ready to - // be saved in the overall state and used for expression evaluation. - OutputChange **plans.ResourceInstanceChange - OutputValue *cty.Value - OutputConfigValue *cty.Value - OutputState **states.ResourceInstanceObject -} - -func (n *EvalReadData) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - log.Printf("[TRACE] EvalReadData: working on %s", absAddr) - - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - return nil, fmt.Errorf("provider schema not available for %s", n.Addr) - } - - var diags tfdiags.Diagnostics - var change *plans.ResourceInstanceChange - var configVal cty.Value - - // TODO: Do we need to handle Delete changes here? EvalReadDataDiff and - // EvalReadDataApply did, but it seems like we should handle that via a - // separate mechanism since it boils down to just deleting the object from - // the state... and we do that on every plan anyway, forcing the data - // resource to re-read. - - config := *n.Config - provider := *n.Provider - providerSchema := *n.ProviderSchema - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider %q does not support data source %q", n.ProviderAddr.ProviderConfig.Type, n.Addr.Resource.Type) - } - - // We'll always start by evaluating the configuration. What we do after - // that will depend on the evaluation result along with what other inputs - // we were given. - objTy := schema.ImpliedType() - priorVal := cty.NullVal(objTy) // for data resources, prior is always null because we start fresh every time - - forEach, _ := evaluateResourceForEachExpression(n.Config.ForEach, ctx) - keyData := EvalDataForInstanceKey(n.Addr.Key, forEach) - - var configDiags tfdiags.Diagnostics - configVal, _, configDiags = ctx.EvaluateBlock(config.Config, schema, nil, keyData) - diags = diags.Append(configDiags) - if configDiags.HasErrors() { - return nil, diags.Err() - } - - proposedNewVal := objchange.PlannedDataResourceObject(schema, configVal) - - // If our configuration contains any unknown values then we must defer the - // read to the apply phase by producing a "Read" change for this resource, - // and a placeholder value for it in the state. - if n.ForcePlanRead || !configVal.IsWhollyKnown() { - // If the configuration is still unknown when we're applying a planned - // change then that indicates a bug in Terraform, since we should have - // everything resolved by now. - if n.Planned != nil && *n.Planned != nil { - return nil, fmt.Errorf( - "configuration for %s still contains unknown values during apply (this is a bug in Terraform; please report it!)", - absAddr, - ) - } - if n.ForcePlanRead { - log.Printf("[TRACE] EvalReadData: %s configuration is fully known, but we're forcing a read plan to be created", absAddr) - } else { - log.Printf("[TRACE] EvalReadData: %s configuration not fully known yet, so deferring to apply phase", absAddr) - } - - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreDiff(absAddr, states.CurrentGen, priorVal, proposedNewVal) - }) - if err != nil { - return nil, err - } - - change = &plans.ResourceInstanceChange{ - Addr: absAddr, - ProviderAddr: n.ProviderAddr, - Change: plans.Change{ - Action: plans.Read, - Before: priorVal, - After: proposedNewVal, - }, - } - - err = ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostDiff(absAddr, states.CurrentGen, change.Action, priorVal, proposedNewVal) - }) - if err != nil { - return nil, err - } - - if n.OutputChange != nil { - *n.OutputChange = change - } - if n.OutputValue != nil { - *n.OutputValue = change.After - } - if n.OutputConfigValue != nil { - *n.OutputConfigValue = configVal - } - if n.OutputState != nil { - state := &states.ResourceInstanceObject{ - Value: change.After, - Status: states.ObjectPlanned, // because the partial value in the plan must be used for now - Dependencies: n.Dependencies, - } - *n.OutputState = state - } - - return nil, diags.ErrWithWarnings() - } - - if n.Planned != nil && *n.Planned != nil && (*n.Planned).Action != plans.Read { - // If any other action gets in here then that's always a bug; this - // EvalNode only deals with reading. - return nil, fmt.Errorf( - "invalid action %s for %s: only Read is supported (this is a bug in Terraform; please report it!)", - (*n.Planned).Action, absAddr, - ) - } - - log.Printf("[TRACE] Re-validating config for %s", absAddr) - validateResp := provider.ValidateDataSourceConfig( - providers.ValidateDataSourceConfigRequest{ - TypeName: n.Addr.Resource.Type, - Config: configVal, - }, - ) - if validateResp.Diagnostics.HasErrors() { - return nil, validateResp.Diagnostics.InConfigBody(n.Config.Config).Err() - } - - // If we get down here then our configuration is complete and we're read - // to actually call the provider to read the data. - log.Printf("[TRACE] EvalReadData: %s configuration is complete, so reading from provider", absAddr) - - err := ctx.Hook(func(h Hook) (HookAction, error) { - // We don't have a state yet, so we'll just give the hook an - // empty one to work with. - return h.PreRefresh(absAddr, states.CurrentGen, cty.NullVal(cty.DynamicPseudoType)) - }) - if err != nil { - return nil, err - } - - resp := provider.ReadDataSource(providers.ReadDataSourceRequest{ - TypeName: n.Addr.Resource.Type, - Config: configVal, - }) - diags = diags.Append(resp.Diagnostics.InConfigBody(n.Config.Config)) - if diags.HasErrors() { - return nil, diags.Err() - } - newVal := resp.State - if newVal == cty.NilVal { - // This can happen with incompletely-configured mocks. We'll allow it - // and treat it as an alias for a properly-typed null value. - newVal = cty.NullVal(schema.ImpliedType()) - } - - for _, err := range newVal.Type().TestConformance(schema.ImpliedType()) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid object", - fmt.Sprintf( - "Provider %q produced an invalid value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatErrorPrefixed(err, absAddr.String()), - ), - )) - } - if diags.HasErrors() { - return nil, diags.Err() - } - - if newVal.IsNull() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced null object", - fmt.Sprintf( - "Provider %q produced a null value for %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, absAddr, - ), - )) - } - if !newVal.IsWhollyKnown() { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid object", - fmt.Sprintf( - "Provider %q produced a value for %s that is not wholly known.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, absAddr, - ), - )) - - // We'll still save the object, but we need to eliminate any unknown - // values first because we can't serialize them in the state file. - // Note that this may cause set elements to be coalesced if they - // differed only by having unknown values, but we don't worry about - // that here because we're saving the value only for inspection - // purposes; the error we added above will halt the graph walk. - newVal = cty.UnknownAsNull(newVal) - } - - // Since we've completed the read, we actually have no change to make, but - // we'll produce a NoOp one anyway to preserve the usual flow of the - // plan phase and allow it to produce a complete plan. - change = &plans.ResourceInstanceChange{ - Addr: absAddr, - ProviderAddr: n.ProviderAddr, - Change: plans.Change{ - Action: plans.NoOp, - Before: newVal, - After: newVal, - }, - } - state := &states.ResourceInstanceObject{ - Value: change.After, - Status: states.ObjectReady, // because we completed the read from the provider - Dependencies: n.Dependencies, - } - - err = ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostRefresh(absAddr, states.CurrentGen, change.Before, newVal) - }) - if err != nil { - return nil, err - } - - if n.OutputChange != nil { - *n.OutputChange = change - } - if n.OutputValue != nil { - *n.OutputValue = change.After - } - if n.OutputConfigValue != nil { - *n.OutputConfigValue = configVal - } - if n.OutputState != nil { - *n.OutputState = state - } - - return nil, diags.ErrWithWarnings() -} - -// EvalReadDataApply is an EvalNode implementation that executes a data -// resource's ReadDataApply method to read data from the data source. -type EvalReadDataApply struct { - Addr addrs.ResourceInstance - Provider *providers.Interface - ProviderAddr addrs.AbsProviderConfig - ProviderSchema **ProviderSchema - Output **states.ResourceInstanceObject - Config *configs.Resource - Change **plans.ResourceInstanceChange - StateReferences []addrs.Referenceable -} - -func (n *EvalReadDataApply) Eval(ctx EvalContext) (interface{}, error) { - provider := *n.Provider - change := *n.Change - providerSchema := *n.ProviderSchema - absAddr := n.Addr.Absolute(ctx.Path()) - - var diags tfdiags.Diagnostics - - // If the diff is for *destroying* this resource then we'll - // just drop its state and move on, since data resources don't - // support an actual "destroy" action. - if change != nil && change.Action == plans.Delete { - if n.Output != nil { - *n.Output = nil - } - return nil, nil - } - - // For the purpose of external hooks we present a data apply as a - // "Refresh" rather than an "Apply" because creating a data source - // is presented to users/callers as a "read" operation. - err := ctx.Hook(func(h Hook) (HookAction, error) { - // We don't have a state yet, so we'll just give the hook an - // empty one to work with. - return h.PreRefresh(absAddr, states.CurrentGen, cty.NullVal(cty.DynamicPseudoType)) - }) - if err != nil { - return nil, err - } - - resp := provider.ReadDataSource(providers.ReadDataSourceRequest{ - TypeName: n.Addr.Resource.Type, - Config: change.After, - }) - diags = diags.Append(resp.Diagnostics.InConfigBody(n.Config.Config)) - if diags.HasErrors() { - return nil, diags.Err() - } - - schema, _ := providerSchema.SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support data source %q", n.Addr.Resource.Type) - } - - newVal := resp.State - for _, err := range newVal.Type().TestConformance(schema.ImpliedType()) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid object", - fmt.Sprintf( - "Provider %q planned an invalid value for %s. The result could not be saved.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, tfdiags.FormatErrorPrefixed(err, absAddr.String()), - ), - )) - } - if diags.HasErrors() { - return nil, diags.Err() - } - - err = ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostRefresh(absAddr, states.CurrentGen, change.Before, newVal) - }) - if err != nil { - return nil, err - } - - if n.Output != nil { - *n.Output = &states.ResourceInstanceObject{ - Value: newVal, - Status: states.ObjectReady, - Dependencies: n.StateReferences, - } - } - - return nil, diags.ErrWithWarnings() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_refresh.go deleted file mode 100644 index 6a834445c31..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_refresh.go +++ /dev/null @@ -1,106 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalRefresh is an EvalNode implementation that does a refresh for -// a resource. -type EvalRefresh struct { - Addr addrs.ResourceInstance - ProviderAddr addrs.AbsProviderConfig - Provider *providers.Interface - ProviderSchema **ProviderSchema - State **states.ResourceInstanceObject - Output **states.ResourceInstanceObject -} - -// TODO: test -func (n *EvalRefresh) Eval(ctx EvalContext) (interface{}, error) { - state := *n.State - absAddr := n.Addr.Absolute(ctx.Path()) - - var diags tfdiags.Diagnostics - - // If we have no state, we don't do any refreshing - if state == nil { - log.Printf("[DEBUG] refresh: %s: no state, so not refreshing", n.Addr.Absolute(ctx.Path())) - return nil, diags.ErrWithWarnings() - } - - schema, _ := (*n.ProviderSchema).SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Should be caught during validation, so we don't bother with a pretty error here - return nil, fmt.Errorf("provider does not support resource type %q", n.Addr.Resource.Type) - } - - // Call pre-refresh hook - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreRefresh(absAddr, states.CurrentGen, state.Value) - }) - if err != nil { - return nil, diags.ErrWithWarnings() - } - - // Refresh! - priorVal := state.Value - req := providers.ReadResourceRequest{ - TypeName: n.Addr.Resource.Type, - PriorState: priorVal, - Private: state.Private, - } - - provider := *n.Provider - resp := provider.ReadResource(req) - diags = diags.Append(resp.Diagnostics) - if diags.HasErrors() { - return nil, diags.Err() - } - - if resp.NewState == cty.NilVal { - // This ought not to happen in real cases since it's not possible to - // send NilVal over the plugin RPC channel, but it can come up in - // tests due to sloppy mocking. - panic("new state is cty.NilVal") - } - - for _, err := range resp.NewState.Type().TestConformance(schema.ImpliedType()) { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider produced invalid object", - fmt.Sprintf( - "Provider %q planned an invalid value for %s during refresh: %s.\n\nThis is a bug in the provider, which should be reported in the provider's own issue tracker.", - n.ProviderAddr.ProviderConfig.Type, absAddr, tfdiags.FormatError(err), - ), - )) - } - if diags.HasErrors() { - return nil, diags.Err() - } - - newState := state.DeepCopy() - newState.Value = resp.NewState - newState.Private = resp.Private - - // Call post-refresh hook - err = ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostRefresh(absAddr, states.CurrentGen, priorVal, newState.Value) - }) - if err != nil { - return nil, err - } - - if n.Output != nil { - *n.Output = newState - } - - return nil, diags.ErrWithWarnings() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_sequence.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_sequence.go deleted file mode 100644 index 7d6bb6603bd..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_sequence.go +++ /dev/null @@ -1,42 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalSequence is an EvalNode that evaluates in sequence. -type EvalSequence struct { - Nodes []EvalNode -} - -func (n *EvalSequence) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - - for _, n := range n.Nodes { - if n == nil { - continue - } - - if _, err := EvalRaw(n, ctx); err != nil { - if _, isEarlyExit := err.(EvalEarlyExitError); isEarlyExit { - // In this path we abort early, losing any non-error - // diagnostics we saw earlier. - return nil, err - } - diags = diags.Append(err) - if diags.HasErrors() { - // Halt if we get some errors, but warnings are okay. - break - } - } - } - - return nil, diags.ErrWithWarnings() -} - -// EvalNodeFilterable impl. -func (n *EvalSequence) Filter(fn EvalNodeFilterFunc) { - for i, node := range n.Nodes { - n.Nodes[i] = fn(node) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_state.go deleted file mode 100644 index 70a72bbdbc1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_state.go +++ /dev/null @@ -1,475 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalReadState is an EvalNode implementation that reads the -// current object for a specific instance in the state. -type EvalReadState struct { - // Addr is the address of the instance to read state for. - Addr addrs.ResourceInstance - - // ProviderSchema is the schema for the provider given in Provider. - ProviderSchema **ProviderSchema - - // Provider is the provider that will subsequently perform actions on - // the the state object. This is used to perform any schema upgrades - // that might be required to prepare the stored data for use. - Provider *providers.Interface - - // Output will be written with a pointer to the retrieved object. - Output **states.ResourceInstanceObject -} - -func (n *EvalReadState) Eval(ctx EvalContext) (interface{}, error) { - if n.Provider == nil || *n.Provider == nil { - panic("EvalReadState used with no Provider object") - } - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - panic("EvalReadState used with no ProviderSchema object") - } - - absAddr := n.Addr.Absolute(ctx.Path()) - log.Printf("[TRACE] EvalReadState: reading state for %s", absAddr) - - src := ctx.State().ResourceInstanceObject(absAddr, states.CurrentGen) - if src == nil { - // Presumably we only have deposed objects, then. - log.Printf("[TRACE] EvalReadState: no state present for %s", absAddr) - return nil, nil - } - - schema, currentVersion := (*n.ProviderSchema).SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Shouldn't happen since we should've failed long ago if no schema is present - return nil, fmt.Errorf("no schema available for %s while reading state; this is a bug in Terraform and should be reported", absAddr) - } - var diags tfdiags.Diagnostics - src, diags = UpgradeResourceState(absAddr, *n.Provider, src, schema, currentVersion) - if diags.HasErrors() { - // Note that we don't have any channel to return warnings here. We'll - // accept that for now since warnings during a schema upgrade would - // be pretty weird anyway, since this operation is supposed to seem - // invisible to the user. - return nil, diags.Err() - } - - obj, err := src.Decode(schema.ImpliedType()) - if err != nil { - return nil, err - } - - if n.Output != nil { - *n.Output = obj - } - return obj, nil -} - -// EvalReadStateDeposed is an EvalNode implementation that reads the -// deposed InstanceState for a specific resource out of the state -type EvalReadStateDeposed struct { - // Addr is the address of the instance to read state for. - Addr addrs.ResourceInstance - - // Key identifies which deposed object we will read. - Key states.DeposedKey - - // ProviderSchema is the schema for the provider given in Provider. - ProviderSchema **ProviderSchema - - // Provider is the provider that will subsequently perform actions on - // the the state object. This is used to perform any schema upgrades - // that might be required to prepare the stored data for use. - Provider *providers.Interface - - // Output will be written with a pointer to the retrieved object. - Output **states.ResourceInstanceObject -} - -func (n *EvalReadStateDeposed) Eval(ctx EvalContext) (interface{}, error) { - if n.Provider == nil || *n.Provider == nil { - panic("EvalReadStateDeposed used with no Provider object") - } - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - panic("EvalReadStateDeposed used with no ProviderSchema object") - } - - key := n.Key - if key == states.NotDeposed { - return nil, fmt.Errorf("EvalReadStateDeposed used with no instance key; this is a bug in Terraform and should be reported") - } - absAddr := n.Addr.Absolute(ctx.Path()) - log.Printf("[TRACE] EvalReadStateDeposed: reading state for %s deposed object %s", absAddr, n.Key) - - src := ctx.State().ResourceInstanceObject(absAddr, key) - if src == nil { - // Presumably we only have deposed objects, then. - log.Printf("[TRACE] EvalReadStateDeposed: no state present for %s deposed object %s", absAddr, n.Key) - return nil, nil - } - - schema, currentVersion := (*n.ProviderSchema).SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // Shouldn't happen since we should've failed long ago if no schema is present - return nil, fmt.Errorf("no schema available for %s while reading state; this is a bug in Terraform and should be reported", absAddr) - } - var diags tfdiags.Diagnostics - src, diags = UpgradeResourceState(absAddr, *n.Provider, src, schema, currentVersion) - if diags.HasErrors() { - // Note that we don't have any channel to return warnings here. We'll - // accept that for now since warnings during a schema upgrade would - // be pretty weird anyway, since this operation is supposed to seem - // invisible to the user. - return nil, diags.Err() - } - - obj, err := src.Decode(schema.ImpliedType()) - if err != nil { - return nil, err - } - if n.Output != nil { - *n.Output = obj - } - return obj, nil -} - -// EvalRequireState is an EvalNode implementation that exits early if the given -// object is null. -type EvalRequireState struct { - State **states.ResourceInstanceObject -} - -func (n *EvalRequireState) Eval(ctx EvalContext) (interface{}, error) { - if n.State == nil { - return nil, EvalEarlyExitError{} - } - - state := *n.State - if state == nil || state.Value.IsNull() { - return nil, EvalEarlyExitError{} - } - - return nil, nil -} - -// EvalUpdateStateHook is an EvalNode implementation that calls the -// PostStateUpdate hook with the current state. -type EvalUpdateStateHook struct{} - -func (n *EvalUpdateStateHook) Eval(ctx EvalContext) (interface{}, error) { - // In principle we could grab the lock here just long enough to take a - // deep copy and then pass that to our hooks below, but we'll instead - // hold the hook for the duration to avoid the potential confusing - // situation of us racing to call PostStateUpdate concurrently with - // different state snapshots. - stateSync := ctx.State() - state := stateSync.Lock().DeepCopy() - defer stateSync.Unlock() - - // Call the hook - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostStateUpdate(state) - }) - if err != nil { - return nil, err - } - - return nil, nil -} - -// EvalWriteState is an EvalNode implementation that saves the given object -// as the current object for the selected resource instance. -type EvalWriteState struct { - // Addr is the address of the instance to read state for. - Addr addrs.ResourceInstance - - // State is the object state to save. - State **states.ResourceInstanceObject - - // ProviderSchema is the schema for the provider given in ProviderAddr. - ProviderSchema **ProviderSchema - - // ProviderAddr is the address of the provider configuration that - // produced the given object. - ProviderAddr addrs.AbsProviderConfig -} - -func (n *EvalWriteState) Eval(ctx EvalContext) (interface{}, error) { - if n.State == nil { - // Note that a pointer _to_ nil is valid here, indicating the total - // absense of an object as we'd see during destroy. - panic("EvalWriteState used with no ResourceInstanceObject") - } - - absAddr := n.Addr.Absolute(ctx.Path()) - state := ctx.State() - - if n.ProviderAddr.ProviderConfig.Type == "" { - return nil, fmt.Errorf("failed to write state for %s, missing provider type", absAddr) - } - - obj := *n.State - if obj == nil || obj.Value.IsNull() { - // No need to encode anything: we'll just write it directly. - state.SetResourceInstanceCurrent(absAddr, nil, n.ProviderAddr) - log.Printf("[TRACE] EvalWriteState: removing state object for %s", absAddr) - return nil, nil - } - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - // Should never happen, unless our state object is nil - panic("EvalWriteState used with pointer to nil ProviderSchema object") - } - - if obj != nil { - log.Printf("[TRACE] EvalWriteState: writing current state object for %s", absAddr) - } else { - log.Printf("[TRACE] EvalWriteState: removing current state object for %s", absAddr) - } - - schema, currentVersion := (*n.ProviderSchema).SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // It shouldn't be possible to get this far in any real scenario - // without a schema, but we might end up here in contrived tests that - // fail to set up their world properly. - return nil, fmt.Errorf("failed to encode %s in state: no resource type schema available", absAddr) - } - src, err := obj.Encode(schema.ImpliedType(), currentVersion) - if err != nil { - return nil, fmt.Errorf("failed to encode %s in state: %s", absAddr, err) - } - - state.SetResourceInstanceCurrent(absAddr, src, n.ProviderAddr) - return nil, nil -} - -// EvalWriteStateDeposed is an EvalNode implementation that writes -// an InstanceState out to the Deposed list of a resource in the state. -type EvalWriteStateDeposed struct { - // Addr is the address of the instance to read state for. - Addr addrs.ResourceInstance - - // Key indicates which deposed object to write to. - Key states.DeposedKey - - // State is the object state to save. - State **states.ResourceInstanceObject - - // ProviderSchema is the schema for the provider given in ProviderAddr. - ProviderSchema **ProviderSchema - - // ProviderAddr is the address of the provider configuration that - // produced the given object. - ProviderAddr addrs.AbsProviderConfig -} - -func (n *EvalWriteStateDeposed) Eval(ctx EvalContext) (interface{}, error) { - if n.State == nil { - // Note that a pointer _to_ nil is valid here, indicating the total - // absense of an object as we'd see during destroy. - panic("EvalWriteStateDeposed used with no ResourceInstanceObject") - } - - absAddr := n.Addr.Absolute(ctx.Path()) - key := n.Key - state := ctx.State() - - if key == states.NotDeposed { - // should never happen - return nil, fmt.Errorf("can't save deposed object for %s without a deposed key; this is a bug in Terraform that should be reported", absAddr) - } - - obj := *n.State - if obj == nil { - // No need to encode anything: we'll just write it directly. - state.SetResourceInstanceDeposed(absAddr, key, nil, n.ProviderAddr) - log.Printf("[TRACE] EvalWriteStateDeposed: removing state object for %s deposed %s", absAddr, key) - return nil, nil - } - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - // Should never happen, unless our state object is nil - panic("EvalWriteStateDeposed used with no ProviderSchema object") - } - - schema, currentVersion := (*n.ProviderSchema).SchemaForResourceAddr(n.Addr.ContainingResource()) - if schema == nil { - // It shouldn't be possible to get this far in any real scenario - // without a schema, but we might end up here in contrived tests that - // fail to set up their world properly. - return nil, fmt.Errorf("failed to encode %s in state: no resource type schema available", absAddr) - } - src, err := obj.Encode(schema.ImpliedType(), currentVersion) - if err != nil { - return nil, fmt.Errorf("failed to encode %s in state: %s", absAddr, err) - } - - log.Printf("[TRACE] EvalWriteStateDeposed: writing state object for %s deposed %s", absAddr, key) - state.SetResourceInstanceDeposed(absAddr, key, src, n.ProviderAddr) - return nil, nil -} - -// EvalDeposeState is an EvalNode implementation that moves the current object -// for the given instance to instead be a deposed object, leaving the instance -// with no current object. -// This is used at the beginning of a create-before-destroy replace action so -// that the create can create while preserving the old state of the -// to-be-destroyed object. -type EvalDeposeState struct { - Addr addrs.ResourceInstance - - // ForceKey, if a value other than states.NotDeposed, will be used as the - // key for the newly-created deposed object that results from this action. - // If set to states.NotDeposed (the zero value), a new unique key will be - // allocated. - ForceKey states.DeposedKey - - // OutputKey, if non-nil, will be written with the deposed object key that - // was generated for the object. This can then be passed to - // EvalUndeposeState.Key so it knows which deposed instance to forget. - OutputKey *states.DeposedKey -} - -// TODO: test -func (n *EvalDeposeState) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - state := ctx.State() - - var key states.DeposedKey - if n.ForceKey == states.NotDeposed { - key = state.DeposeResourceInstanceObject(absAddr) - } else { - key = n.ForceKey - state.DeposeResourceInstanceObjectForceKey(absAddr, key) - } - log.Printf("[TRACE] EvalDeposeState: prior object for %s now deposed with key %s", absAddr, key) - - if n.OutputKey != nil { - *n.OutputKey = key - } - - return nil, nil -} - -// EvalMaybeRestoreDeposedObject is an EvalNode implementation that will -// restore a particular deposed object of the specified resource instance -// to be the "current" object if and only if the instance doesn't currently -// have a current object. -// -// This is intended for use when the create leg of a create before destroy -// fails with no partial new object: if we didn't take any action, the user -// would be left in the unfortunate situation of having no current object -// and the previously-workign object now deposed. This EvalNode causes a -// better outcome by restoring things to how they were before the replace -// operation began. -// -// The create operation may have produced a partial result even though it -// failed and it's important that we don't "forget" that state, so in that -// situation the prior object remains deposed and the partial new object -// remains the current object, allowing the situation to hopefully be -// improved in a subsequent run. -type EvalMaybeRestoreDeposedObject struct { - Addr addrs.ResourceInstance - - // Key is a pointer to the deposed object key that should be forgotten - // from the state, which must be non-nil. - Key *states.DeposedKey -} - -// TODO: test -func (n *EvalMaybeRestoreDeposedObject) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - dk := *n.Key - state := ctx.State() - - restored := state.MaybeRestoreResourceInstanceDeposed(absAddr, dk) - if restored { - log.Printf("[TRACE] EvalMaybeRestoreDeposedObject: %s deposed object %s was restored as the current object", absAddr, dk) - } else { - log.Printf("[TRACE] EvalMaybeRestoreDeposedObject: %s deposed object %s remains deposed", absAddr, dk) - } - - return nil, nil -} - -// EvalWriteResourceState is an EvalNode implementation that ensures that -// a suitable resource-level state record is present in the state, if that's -// required for the "each mode" of that resource. -// -// This is important primarily for the situation where count = 0, since this -// eval is the only change we get to set the resource "each mode" to list -// in that case, allowing expression evaluation to see it as a zero-element -// list rather than as not set at all. -type EvalWriteResourceState struct { - Addr addrs.Resource - Config *configs.Resource - ProviderAddr addrs.AbsProviderConfig -} - -// TODO: test -func (n *EvalWriteResourceState) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - absAddr := n.Addr.Absolute(ctx.Path()) - state := ctx.State() - - count, countDiags := evaluateResourceCountExpression(n.Config.Count, ctx) - diags = diags.Append(countDiags) - if countDiags.HasErrors() { - return nil, diags.Err() - } - - eachMode := states.NoEach - if count >= 0 { // -1 signals "count not set" - eachMode = states.EachList - } - - forEach, forEachDiags := evaluateResourceForEachExpression(n.Config.ForEach, ctx) - diags = diags.Append(forEachDiags) - if forEachDiags.HasErrors() { - return nil, diags.Err() - } - - if forEach != nil { - eachMode = states.EachMap - } - - // This method takes care of all of the business logic of updating this - // while ensuring that any existing instances are preserved, etc. - state.SetResourceMeta(absAddr, eachMode, n.ProviderAddr) - - return nil, nil -} - -// EvalForgetResourceState is an EvalNode implementation that prunes out an -// empty resource-level state for a given resource address, or produces an -// error if it isn't empty after all. -// -// This should be the last action taken for a resource that has been removed -// from the configuration altogether, to clean up the leftover husk of the -// resource in the state after other EvalNodes have destroyed and removed -// all of the instances and instance objects beneath it. -type EvalForgetResourceState struct { - Addr addrs.Resource -} - -func (n *EvalForgetResourceState) Eval(ctx EvalContext) (interface{}, error) { - absAddr := n.Addr.Absolute(ctx.Path()) - state := ctx.State() - - pruned := state.RemoveResourceIfEmpty(absAddr) - if !pruned { - // If this produces an error, it indicates a bug elsewhere in Terraform - // -- probably missing graph nodes, graph edges, or - // incorrectly-implemented evaluation steps. - return nil, fmt.Errorf("orphan resource %s still has a non-empty state after apply; this is a bug in Terraform", absAddr) - } - log.Printf("[TRACE] EvalForgetResourceState: Pruned husk of %s from state", absAddr) - - return nil, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_state_upgrade.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_state_upgrade.go deleted file mode 100644 index 27d5f212eb2..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_state_upgrade.go +++ /dev/null @@ -1,106 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// UpgradeResourceState will, if necessary, run the provider-defined upgrade -// logic against the given state object to make it compliant with the -// current schema version. This is a no-op if the given state object is -// already at the latest version. -// -// If any errors occur during upgrade, error diagnostics are returned. In that -// case it is not safe to proceed with using the original state object. -func UpgradeResourceState(addr addrs.AbsResourceInstance, provider providers.Interface, src *states.ResourceInstanceObjectSrc, currentSchema *configschema.Block, currentVersion uint64) (*states.ResourceInstanceObjectSrc, tfdiags.Diagnostics) { - if addr.Resource.Resource.Mode != addrs.ManagedResourceMode { - // We only do state upgrading for managed resources. - return src, nil - } - - stateIsFlatmap := len(src.AttrsJSON) == 0 - - providerType := addr.Resource.Resource.DefaultProviderConfig().Type - if src.SchemaVersion > currentVersion { - log.Printf("[TRACE] UpgradeResourceState: can't downgrade state for %s from version %d to %d", addr, src.SchemaVersion, currentVersion) - var diags tfdiags.Diagnostics - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Resource instance managed by newer provider version", - // This is not a very good error message, but we don't retain enough - // information in state to give good feedback on what provider - // version might be required here. :( - fmt.Sprintf("The current state of %s was created by a newer provider version than is currently selected. Upgrade the %s provider to work with this state.", addr, providerType), - )) - return nil, diags - } - - // If we get down here then we need to upgrade the state, with the - // provider's help. - // If this state was originally created by a version of Terraform prior to - // v0.12, this also includes translating from legacy flatmap to new-style - // representation, since only the provider has enough information to - // understand a flatmap built against an older schema. - if src.SchemaVersion != currentVersion { - log.Printf("[TRACE] UpgradeResourceState: upgrading state for %s from version %d to %d using provider %q", addr, src.SchemaVersion, currentVersion, providerType) - } else { - log.Printf("[TRACE] UpgradeResourceState: schema version of %s is still %d; calling provider %q for any other minor fixups", addr, currentVersion, providerType) - } - - req := providers.UpgradeResourceStateRequest{ - TypeName: addr.Resource.Resource.Type, - - // TODO: The internal schema version representations are all using - // uint64 instead of int64, but unsigned integers aren't friendly - // to all protobuf target languages so in practice we use int64 - // on the wire. In future we will change all of our internal - // representations to int64 too. - Version: int64(src.SchemaVersion), - } - - if stateIsFlatmap { - req.RawStateFlatmap = src.AttrsFlat - } else { - req.RawStateJSON = src.AttrsJSON - } - - resp := provider.UpgradeResourceState(req) - diags := resp.Diagnostics - if diags.HasErrors() { - return nil, diags - } - - // After upgrading, the new value must conform to the current schema. When - // going over RPC this is actually already ensured by the - // marshaling/unmarshaling of the new value, but we'll check it here - // anyway for robustness, e.g. for in-process providers. - newValue := resp.UpgradedState - if errs := newValue.Type().TestConformance(currentSchema.ImpliedType()); len(errs) > 0 { - for _, err := range errs { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid resource state upgrade", - fmt.Sprintf("The %s provider upgraded the state for %s from a previous version, but produced an invalid result: %s.", providerType, addr, tfdiags.FormatError(err)), - )) - } - return nil, diags - } - - new, err := src.CompleteUpgrade(newValue, currentSchema.ImpliedType(), uint64(currentVersion)) - if err != nil { - // We already checked for type conformance above, so getting into this - // codepath should be rare and is probably a bug somewhere under CompleteUpgrade. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to encode result of resource state upgrade", - fmt.Sprintf("Failed to encode state for %s after resource schema upgrade: %s.", addr, tfdiags.FormatError(err)), - )) - } - return new, diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_validate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_validate.go deleted file mode 100644 index a4f28bd90f6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_validate.go +++ /dev/null @@ -1,588 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/gocty" -) - -// EvalValidateCount is an EvalNode implementation that validates -// the count of a resource. -type EvalValidateCount struct { - Resource *configs.Resource -} - -// TODO: test -func (n *EvalValidateCount) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - var count int - var err error - - val, valDiags := ctx.EvaluateExpr(n.Resource.Count, cty.Number, nil) - diags = diags.Append(valDiags) - if valDiags.HasErrors() { - goto RETURN - } - if val.IsNull() || !val.IsKnown() { - goto RETURN - } - - err = gocty.FromCtyValue(val, &count) - if err != nil { - // The EvaluateExpr call above already guaranteed us a number value, - // so if we end up here then we have something that is out of range - // for an int, and the error message will include a description of - // the valid range. - rawVal := val.AsBigFloat() - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count value", - Detail: fmt.Sprintf("The number %s is not a valid count value: %s.", rawVal, err), - Subject: n.Resource.Count.Range().Ptr(), - }) - } else if count < 0 { - rawVal := val.AsBigFloat() - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count value", - Detail: fmt.Sprintf("The number %s is not a valid count value: count must not be negative.", rawVal), - Subject: n.Resource.Count.Range().Ptr(), - }) - } - -RETURN: - return nil, diags.NonFatalErr() -} - -// EvalValidateProvider is an EvalNode implementation that validates -// a provider configuration. -type EvalValidateProvider struct { - Addr addrs.ProviderConfig - Provider *providers.Interface - Config *configs.Provider -} - -func (n *EvalValidateProvider) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - provider := *n.Provider - - configBody := buildProviderConfig(ctx, n.Addr, n.Config) - - resp := provider.GetSchema() - diags = diags.Append(resp.Diagnostics) - if diags.HasErrors() { - return nil, diags.NonFatalErr() - } - - configSchema := resp.Provider.Block - if configSchema == nil { - // Should never happen in real code, but often comes up in tests where - // mock schemas are being used that tend to be incomplete. - log.Printf("[WARN] EvalValidateProvider: no config schema is available for %s, so using empty schema", n.Addr) - configSchema = &configschema.Block{} - } - - configVal, configBody, evalDiags := ctx.EvaluateBlock(configBody, configSchema, nil, EvalDataForNoInstanceKey) - diags = diags.Append(evalDiags) - if evalDiags.HasErrors() { - return nil, diags.NonFatalErr() - } - - req := providers.PrepareProviderConfigRequest{ - Config: configVal, - } - - validateResp := provider.PrepareProviderConfig(req) - diags = diags.Append(validateResp.Diagnostics) - - return nil, diags.NonFatalErr() -} - -// EvalValidateProvisioner is an EvalNode implementation that validates -// the configuration of a provisioner belonging to a resource. The provisioner -// config is expected to contain the merged connection configurations. -type EvalValidateProvisioner struct { - ResourceAddr addrs.Resource - Provisioner *provisioners.Interface - Schema **configschema.Block - Config *configs.Provisioner - ResourceHasCount bool - ResourceHasForEach bool -} - -func (n *EvalValidateProvisioner) Eval(ctx EvalContext) (interface{}, error) { - provisioner := *n.Provisioner - config := *n.Config - schema := *n.Schema - - var diags tfdiags.Diagnostics - - { - // Validate the provisioner's own config first - - configVal, _, configDiags := n.evaluateBlock(ctx, config.Config, schema) - diags = diags.Append(configDiags) - if configDiags.HasErrors() { - return nil, diags.Err() - } - - if configVal == cty.NilVal { - // Should never happen for a well-behaved EvaluateBlock implementation - return nil, fmt.Errorf("EvaluateBlock returned nil value") - } - - req := provisioners.ValidateProvisionerConfigRequest{ - Config: configVal, - } - - resp := provisioner.ValidateProvisionerConfig(req) - diags = diags.Append(resp.Diagnostics) - } - - { - // Now validate the connection config, which contains the merged bodies - // of the resource and provisioner connection blocks. - connDiags := n.validateConnConfig(ctx, config.Connection, n.ResourceAddr) - diags = diags.Append(connDiags) - } - - return nil, diags.NonFatalErr() -} - -func (n *EvalValidateProvisioner) validateConnConfig(ctx EvalContext, config *configs.Connection, self addrs.Referenceable) tfdiags.Diagnostics { - // 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. - - var diags tfdiags.Diagnostics - - if config == nil || config.Config == nil { - // No block to validate - return diags - } - - // We evaluate here just by evaluating the block and returning any - // diagnostics we get, since evaluation alone is enough to check for - // extraneous arguments and incorrectly-typed arguments. - _, _, configDiags := n.evaluateBlock(ctx, config.Config, connectionBlockSupersetSchema) - diags = diags.Append(configDiags) - - return diags -} - -func (n *EvalValidateProvisioner) evaluateBlock(ctx EvalContext, body hcl.Body, schema *configschema.Block) (cty.Value, hcl.Body, tfdiags.Diagnostics) { - keyData := EvalDataForNoInstanceKey - selfAddr := n.ResourceAddr.Instance(addrs.NoKey) - - if n.ResourceHasCount { - // For a resource that has count, we allow count.index but don't - // know at this stage what it will return. - keyData = InstanceKeyEvalData{ - CountIndex: cty.UnknownVal(cty.Number), - } - - // "self" can't point to an unknown key, but we'll force it to be - // key 0 here, which should return an unknown value of the - // expected type since none of these elements are known at this - // point anyway. - selfAddr = n.ResourceAddr.Instance(addrs.IntKey(0)) - } else if n.ResourceHasForEach { - // For a resource that has for_each, we allow each.value and each.key - // but don't know at this stage what it will return. - keyData = InstanceKeyEvalData{ - EachKey: cty.UnknownVal(cty.String), - EachValue: cty.DynamicVal, - } - - // "self" can't point to an unknown key, but we'll force it to be - // key "" here, which should return an unknown value of the - // expected type since none of these elements are known at - // this point anyway. - selfAddr = n.ResourceAddr.Instance(addrs.StringKey("")) - } - - return ctx.EvaluateBlock(body, schema, selfAddr, keyData) -} - -// connectionBlockSupersetSchema is a schema representing the superset of all -// possible arguments for "connection" blocks across all supported connection -// types. -// -// This currently lives here because we've not yet updated our communicator -// subsystem to be aware of schema itself. Once that is done, we can remove -// this and use a type-specific schema from the communicator to validate -// exactly what is expected for a given connection type. -var connectionBlockSupersetSchema = &configschema.Block{ - Attributes: map[string]*configschema.Attribute{ - // NOTE: "type" is not included here because it's treated special - // by the config loader and stored away in a separate field. - - // Common attributes for both connection types - "host": { - Type: cty.String, - Required: true, - }, - "type": { - Type: cty.String, - Optional: true, - }, - "user": { - Type: cty.String, - Optional: true, - }, - "password": { - Type: cty.String, - Optional: true, - }, - "port": { - Type: cty.String, - Optional: true, - }, - "timeout": { - Type: cty.String, - Optional: true, - }, - "script_path": { - Type: cty.String, - Optional: true, - }, - - // For type=ssh only (enforced in ssh communicator) - "private_key": { - Type: cty.String, - Optional: true, - }, - "certificate": { - Type: cty.String, - Optional: true, - }, - "host_key": { - Type: cty.String, - Optional: true, - }, - "agent": { - Type: cty.Bool, - Optional: true, - }, - "agent_identity": { - Type: cty.String, - Optional: true, - }, - "bastion_host": { - Type: cty.String, - Optional: true, - }, - "bastion_host_key": { - Type: cty.String, - Optional: true, - }, - "bastion_port": { - Type: cty.Number, - Optional: true, - }, - "bastion_user": { - Type: cty.String, - Optional: true, - }, - "bastion_password": { - Type: cty.String, - Optional: true, - }, - "bastion_private_key": { - Type: cty.String, - Optional: true, - }, - "bastion_certificate": { - Type: cty.String, - Optional: true, - }, - - // For type=winrm only (enforced in winrm communicator) - "https": { - Type: cty.Bool, - Optional: true, - }, - "insecure": { - Type: cty.Bool, - Optional: true, - }, - "cacert": { - Type: cty.String, - Optional: true, - }, - "use_ntlm": { - Type: cty.Bool, - Optional: true, - }, - }, -} - -// connectionBlockSupersetSchema is a schema representing the superset of all -// possible arguments for "connection" blocks across all supported connection -// types. -// -// This currently lives here because we've not yet updated our communicator -// subsystem to be aware of schema itself. It's exported only for use in the -// configs/configupgrade package and should not be used from anywhere else. -// The caller may not modify any part of the returned schema data structure. -func ConnectionBlockSupersetSchema() *configschema.Block { - return connectionBlockSupersetSchema -} - -// EvalValidateResource is an EvalNode implementation that validates -// the configuration of a resource. -type EvalValidateResource struct { - Addr addrs.Resource - Provider *providers.Interface - ProviderSchema **ProviderSchema - Config *configs.Resource - - // IgnoreWarnings means that warnings will not be passed through. This allows - // "just-in-time" passes of validation to continue execution through warnings. - IgnoreWarnings bool - - // ConfigVal, if non-nil, will be updated with the value resulting from - // evaluating the given configuration body. Since validation is performed - // very early, this value is likely to contain lots of unknown values, - // but its type will conform to the schema of the resource type associated - // with the resource instance being validated. - ConfigVal *cty.Value -} - -func (n *EvalValidateResource) Eval(ctx EvalContext) (interface{}, error) { - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - return nil, fmt.Errorf("EvalValidateResource has nil schema for %s", n.Addr) - } - - var diags tfdiags.Diagnostics - provider := *n.Provider - cfg := *n.Config - schema := *n.ProviderSchema - mode := cfg.Mode - - keyData := EvalDataForNoInstanceKey - if n.Config.Count != nil { - // If the config block has count, we'll evaluate with an unknown - // number as count.index so we can still type check even though - // we won't expand count until the plan phase. - keyData = InstanceKeyEvalData{ - CountIndex: cty.UnknownVal(cty.Number), - } - - // Basic type-checking of the count argument. More complete validation - // of this will happen when we DynamicExpand during the plan walk. - countDiags := n.validateCount(ctx, n.Config.Count) - diags = diags.Append(countDiags) - } - - if n.Config.ForEach != nil { - keyData = InstanceKeyEvalData{ - EachKey: cty.UnknownVal(cty.String), - EachValue: cty.UnknownVal(cty.DynamicPseudoType), - } - - // Evaluate the for_each expression here so we can expose the diagnostics - forEachDiags := n.validateForEach(ctx, n.Config.ForEach) - diags = diags.Append(forEachDiags) - } - - for _, traversal := range n.Config.DependsOn { - ref, refDiags := addrs.ParseRef(traversal) - diags = diags.Append(refDiags) - if !refDiags.HasErrors() && len(ref.Remaining) != 0 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid depends_on reference", - Detail: "References in depends_on must be to a whole object (resource, etc), not to an attribute of an object.", - Subject: ref.Remaining.SourceRange().Ptr(), - }) - } - - // The ref must also refer to something that exists. To test that, - // we'll just eval it and count on the fact that our evaluator will - // detect references to non-existent objects. - if !diags.HasErrors() { - scope := ctx.EvaluationScope(nil, EvalDataForNoInstanceKey) - if scope != nil { // sometimes nil in tests, due to incomplete mocks - _, refDiags = scope.EvalReference(ref, cty.DynamicPseudoType) - diags = diags.Append(refDiags) - } - } - } - - // Provider entry point varies depending on resource mode, because - // managed resources and data resources are two distinct concepts - // in the provider abstraction. - switch mode { - case addrs.ManagedResourceMode: - schema, _ := schema.SchemaForResourceType(mode, cfg.Type) - if schema == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource type", - Detail: fmt.Sprintf("The provider %s does not support resource type %q.", cfg.ProviderConfigAddr(), cfg.Type), - Subject: &cfg.TypeRange, - }) - return nil, diags.Err() - } - - configVal, _, valDiags := ctx.EvaluateBlock(cfg.Config, schema, nil, keyData) - diags = diags.Append(valDiags) - if valDiags.HasErrors() { - return nil, diags.Err() - } - - if cfg.Managed != nil { // can be nil only in tests with poorly-configured mocks - for _, traversal := range cfg.Managed.IgnoreChanges { - moreDiags := schema.StaticValidateTraversal(traversal) - diags = diags.Append(moreDiags) - } - } - - req := providers.ValidateResourceTypeConfigRequest{ - TypeName: cfg.Type, - Config: configVal, - } - - resp := provider.ValidateResourceTypeConfig(req) - diags = diags.Append(resp.Diagnostics.InConfigBody(cfg.Config)) - - if n.ConfigVal != nil { - *n.ConfigVal = configVal - } - - case addrs.DataResourceMode: - schema, _ := schema.SchemaForResourceType(mode, cfg.Type) - if schema == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid data source", - Detail: fmt.Sprintf("The provider %s does not support data source %q.", cfg.ProviderConfigAddr(), cfg.Type), - Subject: &cfg.TypeRange, - }) - return nil, diags.Err() - } - - configVal, _, valDiags := ctx.EvaluateBlock(cfg.Config, schema, nil, keyData) - diags = diags.Append(valDiags) - if valDiags.HasErrors() { - return nil, diags.Err() - } - - req := providers.ValidateDataSourceConfigRequest{ - TypeName: cfg.Type, - Config: configVal, - } - - resp := provider.ValidateDataSourceConfig(req) - diags = diags.Append(resp.Diagnostics.InConfigBody(cfg.Config)) - } - - if n.IgnoreWarnings { - // If we _only_ have warnings then we'll return nil. - if diags.HasErrors() { - return nil, diags.NonFatalErr() - } - return nil, nil - } else { - // We'll return an error if there are any diagnostics at all, even if - // some of them are warnings. - return nil, diags.NonFatalErr() - } -} - -func (n *EvalValidateResource) validateCount(ctx EvalContext, expr hcl.Expression) tfdiags.Diagnostics { - if expr == nil { - return nil - } - - var diags tfdiags.Diagnostics - - countVal, countDiags := ctx.EvaluateExpr(expr, cty.Number, nil) - diags = diags.Append(countDiags) - if diags.HasErrors() { - return diags - } - - if countVal.IsNull() { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The given "count" argument value is null. An integer is required.`, - Subject: expr.Range().Ptr(), - }) - return diags - } - - var err error - countVal, err = convert.Convert(countVal, cty.Number) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: fmt.Sprintf(`The given "count" argument value is unsuitable: %s.`, err), - Subject: expr.Range().Ptr(), - }) - return diags - } - - // If the value isn't known then that's the best we can do for now, but - // we'll check more thoroughly during the plan walk. - if !countVal.IsKnown() { - return diags - } - - // If we _do_ know the value, then we can do a few more checks here. - var count int - err = gocty.FromCtyValue(countVal, &count) - if err != nil { - // Isn't a whole number, etc. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: fmt.Sprintf(`The given "count" argument value is unsuitable: %s.`, err), - Subject: expr.Range().Ptr(), - }) - return diags - } - - if count < 0 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The given "count" argument value is unsuitable: count cannot be negative.`, - Subject: expr.Range().Ptr(), - }) - return diags - } - - return diags -} - -func (n *EvalValidateResource) validateForEach(ctx EvalContext, expr hcl.Expression) (diags tfdiags.Diagnostics) { - _, known, forEachDiags := evaluateResourceForEachExpressionKnown(expr, ctx) - // If the value isn't known then that's the best we can do for now, but - // we'll check more thoroughly during the plan walk - if !known { - return diags - } - - if forEachDiags.HasErrors() { - diags = diags.Append(forEachDiags) - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_validate_selfref.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_validate_selfref.go deleted file mode 100644 index c9cc0e6daa8..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_validate_selfref.go +++ /dev/null @@ -1,67 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalValidateSelfRef is an EvalNode implementation that checks to ensure that -// expressions within a particular referencable block do not reference that -// same block. -type EvalValidateSelfRef struct { - Addr addrs.Referenceable - Config hcl.Body - ProviderSchema **ProviderSchema -} - -func (n *EvalValidateSelfRef) Eval(ctx EvalContext) (interface{}, error) { - var diags tfdiags.Diagnostics - addr := n.Addr - - addrStrs := make([]string, 0, 1) - addrStrs = append(addrStrs, addr.String()) - switch tAddr := addr.(type) { - case addrs.ResourceInstance: - // A resource instance may not refer to its containing resource either. - addrStrs = append(addrStrs, tAddr.ContainingResource().String()) - } - - if n.ProviderSchema == nil || *n.ProviderSchema == nil { - return nil, fmt.Errorf("provider schema unavailable while validating %s for self-references; this is a bug in Terraform and should be reported", addr) - } - - providerSchema := *n.ProviderSchema - var schema *configschema.Block - switch tAddr := addr.(type) { - case addrs.Resource: - schema, _ = providerSchema.SchemaForResourceAddr(tAddr) - case addrs.ResourceInstance: - schema, _ = providerSchema.SchemaForResourceAddr(tAddr.ContainingResource()) - } - - if schema == nil { - return nil, fmt.Errorf("no schema available for %s to validate for self-references; this is a bug in Terraform and should be reported", addr) - } - - refs, _ := lang.ReferencesInBlock(n.Config, schema) - for _, ref := range refs { - for _, addrStr := range addrStrs { - if ref.Subject.String() == addrStr { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Self-referential block", - Detail: fmt.Sprintf("Configuration for %s may not refer to itself.", addrStr), - Subject: ref.SourceRange.ToHCL().Ptr(), - }) - } - } - } - - return nil, diags.NonFatalErr() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_variable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_variable.go deleted file mode 100644 index 79f44b3fe92..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_variable.go +++ /dev/null @@ -1,96 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// EvalSetModuleCallArguments is an EvalNode implementation that sets values -// for arguments of a child module call, for later retrieval during -// expression evaluation. -type EvalSetModuleCallArguments struct { - Module addrs.ModuleCallInstance - Values map[string]cty.Value -} - -// TODO: test -func (n *EvalSetModuleCallArguments) Eval(ctx EvalContext) (interface{}, error) { - ctx.SetModuleCallArguments(n.Module, n.Values) - return nil, nil -} - -// EvalModuleCallArgument is an EvalNode implementation that produces the value -// for a particular variable as will be used by a child module instance. -// -// The result is written into the map given in Values, with its key -// set to the local name of the variable, disregarding the module instance -// address. Any existing values in that map are deleted first. This weird -// interface is a result of trying to be convenient for use with -// EvalContext.SetModuleCallArguments, which expects a map to merge in with -// any existing arguments. -type EvalModuleCallArgument struct { - Addr addrs.InputVariable - Config *configs.Variable - Expr hcl.Expression - - // If this flag is set, any diagnostics are discarded and this operation - // will always succeed, though may produce an unknown value in the - // event of an error. - IgnoreDiagnostics bool - - Values map[string]cty.Value -} - -func (n *EvalModuleCallArgument) Eval(ctx EvalContext) (interface{}, error) { - // Clear out the existing mapping - for k := range n.Values { - delete(n.Values, k) - } - - wantType := n.Config.Type - name := n.Addr.Name - expr := n.Expr - - if expr == nil { - // Should never happen, but we'll bail out early here rather than - // crash in case it does. We set no value at all in this case, - // making a subsequent call to EvalContext.SetModuleCallArguments - // a no-op. - log.Printf("[ERROR] attempt to evaluate %s with nil expression", n.Addr.String()) - return nil, nil - } - - val, diags := ctx.EvaluateExpr(expr, cty.DynamicPseudoType, nil) - - // We intentionally passed DynamicPseudoType to EvaluateExpr above because - // now we can do our own local type conversion and produce an error message - // with better context if it fails. - var convErr error - val, convErr = convert.Convert(val, wantType) - if convErr != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid value for module argument", - Detail: fmt.Sprintf( - "The given value is not suitable for child module variable %q defined at %s: %s.", - name, n.Config.DeclRange.String(), convErr, - ), - Subject: expr.Range().Ptr(), - }) - // We'll return a placeholder unknown value to avoid producing - // redundant downstream errors. - val = cty.UnknownVal(wantType) - } - - n.Values[name] = val - if n.IgnoreDiagnostics { - return nil, nil - } - return nil, diags.ErrWithWarnings() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaltree_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaltree_provider.go deleted file mode 100644 index d4a8d3cf749..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaltree_provider.go +++ /dev/null @@ -1,88 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" -) - -// ProviderEvalTree returns the evaluation tree for initializing and -// configuring providers. -func ProviderEvalTree(n *NodeApplyableProvider, config *configs.Provider) EvalNode { - var provider providers.Interface - - addr := n.Addr - relAddr := addr.ProviderConfig - - seq := make([]EvalNode, 0, 5) - seq = append(seq, &EvalInitProvider{ - TypeName: relAddr.Type, - Addr: addr.ProviderConfig, - }) - - // Input stuff - seq = append(seq, &EvalOpFilter{ - Ops: []walkOperation{walkImport}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: addr, - Output: &provider, - }, - }, - }, - }) - - seq = append(seq, &EvalOpFilter{ - Ops: []walkOperation{walkValidate}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: addr, - Output: &provider, - }, - &EvalValidateProvider{ - Addr: relAddr, - Provider: &provider, - Config: config, - }, - }, - }, - }) - - // Apply stuff - seq = append(seq, &EvalOpFilter{ - Ops: []walkOperation{walkRefresh, walkPlan, walkApply, walkDestroy, walkImport}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: addr, - Output: &provider, - }, - }, - }, - }) - - // We configure on everything but validate, since validate may - // not have access to all the variables. - seq = append(seq, &EvalOpFilter{ - Ops: []walkOperation{walkRefresh, walkPlan, walkApply, walkDestroy, walkImport}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalConfigProvider{ - Addr: relAddr, - Provider: &provider, - Config: config, - }, - }, - }, - }) - - return &EvalSequence{Nodes: seq} -} - -// CloseProviderEvalTree returns the evaluation tree for closing -// provider connections that aren't needed anymore. -func CloseProviderEvalTree(addr addrs.AbsProviderConfig) EvalNode { - return &EvalCloseProvider{Addr: addr.ProviderConfig} -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate.go deleted file mode 100644 index 2d3eabd4886..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate.go +++ /dev/null @@ -1,838 +0,0 @@ -package terraform - -import ( - "fmt" - "os" - "path/filepath" - "sync" - - "github.com/agext/levenshtein" - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// Evaluator provides the necessary contextual data for evaluating expressions -// for a particular walk operation. -type Evaluator struct { - // Operation defines what type of operation this evaluator is being used - // for. - Operation walkOperation - - // Meta is contextual metadata about the current operation. - Meta *ContextMeta - - // Config is the root node in the configuration tree. - Config *configs.Config - - // VariableValues is a map from variable names to their associated values, - // within the module indicated by ModulePath. VariableValues is modified - // concurrently, and so it must be accessed only while holding - // VariableValuesLock. - // - // The first map level is string representations of addr.ModuleInstance - // values, while the second level is variable names. - VariableValues map[string]map[string]cty.Value - VariableValuesLock *sync.Mutex - - // Schemas is a repository of all of the schemas we should need to - // evaluate expressions. This must be constructed by the caller to - // include schemas for all of the providers, resource types, data sources - // and provisioners used by the given configuration and state. - // - // This must not be mutated during evaluation. - Schemas *Schemas - - // State is the current state, embedded in a wrapper that ensures that - // it can be safely accessed and modified concurrently. - State *states.SyncState - - // Changes is the set of proposed changes, embedded in a wrapper that - // ensures they can be safely accessed and modified concurrently. - Changes *plans.ChangesSync -} - -// Scope creates an evaluation scope for the given module path and optional -// resource. -// -// If the "self" argument is nil then the "self" object is not available -// in evaluated expressions. Otherwise, it behaves as an alias for the given -// address. -func (e *Evaluator) Scope(data lang.Data, self addrs.Referenceable) *lang.Scope { - return &lang.Scope{ - Data: data, - SelfAddr: self, - PureOnly: e.Operation != walkApply && e.Operation != walkDestroy, - BaseDir: ".", // Always current working directory for now. - } -} - -// evaluationStateData is an implementation of lang.Data that resolves -// references primarily (but not exclusively) using information from a State. -type evaluationStateData struct { - Evaluator *Evaluator - - // ModulePath is the path through the dynamic module tree to the module - // that references will be resolved relative to. - ModulePath addrs.ModuleInstance - - // InstanceKeyData describes the values, if any, that are accessible due - // to repetition of a containing object using "count" or "for_each" - // arguments. (It is _not_ used for the for_each inside "dynamic" blocks, - // since the user specifies in that case which variable name to locally - // shadow.) - InstanceKeyData InstanceKeyEvalData - - // Operation records the type of walk the evaluationStateData is being used - // for. - Operation walkOperation -} - -// InstanceKeyEvalData is used during evaluation to specify which values, -// if any, should be produced for count.index, each.key, and each.value. -type InstanceKeyEvalData struct { - // CountIndex is the value for count.index, or cty.NilVal if evaluating - // in a context where the "count" argument is not active. - // - // For correct operation, this should always be of type cty.Number if not - // nil. - CountIndex cty.Value - - // EachKey and EachValue are the values for each.key and each.value - // respectively, or cty.NilVal if evaluating in a context where the - // "for_each" argument is not active. These must either both be set - // or neither set. - // - // For correct operation, EachKey must always be either of type cty.String - // or cty.Number if not nil. - EachKey, EachValue cty.Value -} - -// EvalDataForInstanceKey constructs a suitable InstanceKeyEvalData for -// evaluating in a context that has the given instance key. -func EvalDataForInstanceKey(key addrs.InstanceKey, forEachMap map[string]cty.Value) InstanceKeyEvalData { - var countIdx cty.Value - var eachKey cty.Value - var eachVal cty.Value - - if intKey, ok := key.(addrs.IntKey); ok { - countIdx = cty.NumberIntVal(int64(intKey)) - } - - if stringKey, ok := key.(addrs.StringKey); ok { - eachKey = cty.StringVal(string(stringKey)) - eachVal = forEachMap[string(stringKey)] - } - - return InstanceKeyEvalData{ - CountIndex: countIdx, - EachKey: eachKey, - EachValue: eachVal, - } -} - -// EvalDataForNoInstanceKey is a value of InstanceKeyData that sets no instance -// key values at all, suitable for use in contexts where no keyed instance -// is relevant. -var EvalDataForNoInstanceKey = InstanceKeyEvalData{} - -// evaluationStateData must implement lang.Data -var _ lang.Data = (*evaluationStateData)(nil) - -func (d *evaluationStateData) GetCountAttr(addr addrs.CountAttr, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - switch addr.Name { - - case "index": - idxVal := d.InstanceKeyData.CountIndex - if idxVal == cty.NilVal { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to "count" in non-counted context`, - Detail: fmt.Sprintf(`The "count" object can be used only in "resource" and "data" blocks, and only when the "count" argument is set.`), - Subject: rng.ToHCL().Ptr(), - }) - return cty.UnknownVal(cty.Number), diags - } - return idxVal, diags - - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "count" attribute`, - Detail: fmt.Sprintf(`The "count" object does not have an attribute named %q. The only supported attribute is count.index, which is the index of each instance of a resource block that has the "count" argument set.`, addr.Name), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } -} - -func (d *evaluationStateData) GetForEachAttr(addr addrs.ForEachAttr, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - var returnVal cty.Value - switch addr.Name { - - case "key": - returnVal = d.InstanceKeyData.EachKey - case "value": - returnVal = d.InstanceKeyData.EachValue - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "each" attribute`, - Detail: fmt.Sprintf(`The "each" object does not have an attribute named %q. The supported attributes are each.key and each.value, the current key and value pair of the "for_each" attribute set.`, addr.Name), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - if returnVal == cty.NilVal { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to "each" in context without for_each`, - Detail: fmt.Sprintf(`The "each" object can be used only in "resource" blocks, and only when the "for_each" argument is set.`), - Subject: rng.ToHCL().Ptr(), - }) - return cty.UnknownVal(cty.DynamicPseudoType), diags - } - return returnVal, diags -} - -func (d *evaluationStateData) GetInputVariable(addr addrs.InputVariable, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // First we'll make sure the requested value is declared in configuration, - // so we can produce a nice message if not. - moduleConfig := d.Evaluator.Config.DescendentForInstance(d.ModulePath) - if moduleConfig == nil { - // should never happen, since we can't be evaluating in a module - // that wasn't mentioned in configuration. - panic(fmt.Sprintf("input variable read from %s, which has no configuration", d.ModulePath)) - } - - config := moduleConfig.Module.Variables[addr.Name] - if config == nil { - var suggestions []string - for k := range moduleConfig.Module.Variables { - suggestions = append(suggestions, k) - } - suggestion := nameSuggestion(addr.Name, suggestions) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } else { - suggestion = fmt.Sprintf(" This variable can be declared with a variable %q {} block.", addr.Name) - } - - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared input variable`, - Detail: fmt.Sprintf(`An input variable with the name %q has not been declared.%s`, addr.Name, suggestion), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - wantType := cty.DynamicPseudoType - if config.Type != cty.NilType { - wantType = config.Type - } - - d.Evaluator.VariableValuesLock.Lock() - defer d.Evaluator.VariableValuesLock.Unlock() - - // During the validate walk, input variables are always unknown so - // that we are validating the configuration for all possible input values - // rather than for a specific set. Checking against a specific set of - // input values then happens during the plan walk. - // - // This is important because otherwise the validation walk will tend to be - // overly strict, requiring expressions throughout the configuration to - // be complicated to accommodate all possible inputs, whereas returning - // known here allows for simpler patterns like using input values as - // guards to broadly enable/disable resources, avoid processing things - // that are disabled, etc. Terraform's static validation leans towards - // being liberal in what it accepts because the subsequent plan walk has - // more information available and so can be more conservative. - if d.Operation == walkValidate { - return cty.UnknownVal(wantType), diags - } - - moduleAddrStr := d.ModulePath.String() - vals := d.Evaluator.VariableValues[moduleAddrStr] - if vals == nil { - return cty.UnknownVal(wantType), diags - } - - val, isSet := vals[addr.Name] - if !isSet { - if config.Default != cty.NilVal { - return config.Default, diags - } - return cty.UnknownVal(wantType), diags - } - - var err error - val, err = convert.Convert(val, wantType) - if err != nil { - // We should never get here because this problem should've been caught - // during earlier validation, but we'll do something reasonable anyway. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Incorrect variable type`, - Detail: fmt.Sprintf(`The resolved value of variable %q is not appropriate: %s.`, addr.Name, err), - Subject: &config.DeclRange, - }) - // Stub out our return value so that the semantic checker doesn't - // produce redundant downstream errors. - val = cty.UnknownVal(wantType) - } - - return val, diags -} - -func (d *evaluationStateData) GetLocalValue(addr addrs.LocalValue, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // First we'll make sure the requested value is declared in configuration, - // so we can produce a nice message if not. - moduleConfig := d.Evaluator.Config.DescendentForInstance(d.ModulePath) - if moduleConfig == nil { - // should never happen, since we can't be evaluating in a module - // that wasn't mentioned in configuration. - panic(fmt.Sprintf("local value read from %s, which has no configuration", d.ModulePath)) - } - - config := moduleConfig.Module.Locals[addr.Name] - if config == nil { - var suggestions []string - for k := range moduleConfig.Module.Locals { - suggestions = append(suggestions, k) - } - suggestion := nameSuggestion(addr.Name, suggestions) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } - - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared local value`, - Detail: fmt.Sprintf(`A local value with the name %q has not been declared.%s`, addr.Name, suggestion), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - val := d.Evaluator.State.LocalValue(addr.Absolute(d.ModulePath)) - if val == cty.NilVal { - // Not evaluated yet? - val = cty.DynamicVal - } - - return val, diags -} - -func (d *evaluationStateData) GetModuleInstance(addr addrs.ModuleCallInstance, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // Output results live in the module that declares them, which is one of - // the child module instances of our current module path. - moduleAddr := addr.ModuleInstance(d.ModulePath) - - // We'll consult the configuration to see what output names we are - // expecting, so we can ensure the resulting object is of the expected - // type even if our data is incomplete for some reason. - moduleConfig := d.Evaluator.Config.DescendentForInstance(moduleAddr) - if moduleConfig == nil { - // should never happen, since this should've been caught during - // static validation. - panic(fmt.Sprintf("output value read from %s, which has no configuration", moduleAddr)) - } - outputConfigs := moduleConfig.Module.Outputs - - vals := map[string]cty.Value{} - for n := range outputConfigs { - addr := addrs.OutputValue{Name: n}.Absolute(moduleAddr) - - // If a pending change is present in our current changeset then its value - // takes priority over what's in state. (It will usually be the same but - // will differ if the new value is unknown during planning.) - if changeSrc := d.Evaluator.Changes.GetOutputChange(addr); changeSrc != nil { - change, err := changeSrc.Decode() - if err != nil { - // This should happen only if someone has tampered with a plan - // file, so we won't bother with a pretty error for it. - diags = diags.Append(fmt.Errorf("planned change for %s could not be decoded: %s", addr, err)) - vals[n] = cty.DynamicVal - continue - } - // We care only about the "after" value, which is the value this output - // will take on after the plan is applied. - vals[n] = change.After - } else { - os := d.Evaluator.State.OutputValue(addr) - if os == nil { - // Not evaluated yet? - vals[n] = cty.DynamicVal - continue - } - vals[n] = os.Value - } - } - return cty.ObjectVal(vals), diags -} - -func (d *evaluationStateData) GetModuleInstanceOutput(addr addrs.ModuleCallOutput, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - // Output results live in the module that declares them, which is one of - // the child module instances of our current module path. - absAddr := addr.AbsOutputValue(d.ModulePath) - moduleAddr := absAddr.Module - - // First we'll consult the configuration to see if an output of this - // name is declared at all. - moduleConfig := d.Evaluator.Config.DescendentForInstance(moduleAddr) - if moduleConfig == nil { - // this doesn't happen in normal circumstances due to our validation - // pass, but it can turn up in some unusual situations, like in the - // "terraform console" repl where arbitrary expressions can be - // evaluated. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared module`, - Detail: fmt.Sprintf(`The configuration contains no %s.`, moduleAddr), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - config := moduleConfig.Module.Outputs[addr.Name] - if config == nil { - var suggestions []string - for k := range moduleConfig.Module.Outputs { - suggestions = append(suggestions, k) - } - suggestion := nameSuggestion(addr.Name, suggestions) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } - - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared output value`, - Detail: fmt.Sprintf(`An output value with the name %q has not been declared in %s.%s`, addr.Name, moduleDisplayAddr(moduleAddr), suggestion), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - // If a pending change is present in our current changeset then its value - // takes priority over what's in state. (It will usually be the same but - // will differ if the new value is unknown during planning.) - if changeSrc := d.Evaluator.Changes.GetOutputChange(absAddr); changeSrc != nil { - change, err := changeSrc.Decode() - if err != nil { - // This should happen only if someone has tampered with a plan - // file, so we won't bother with a pretty error for it. - diags = diags.Append(fmt.Errorf("planned change for %s could not be decoded: %s", absAddr, err)) - return cty.DynamicVal, diags - } - // We care only about the "after" value, which is the value this output - // will take on after the plan is applied. - return change.After, diags - } - - os := d.Evaluator.State.OutputValue(absAddr) - if os == nil { - // Not evaluated yet? - return cty.DynamicVal, diags - } - - return os.Value, diags -} - -func (d *evaluationStateData) GetPathAttr(addr addrs.PathAttr, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - switch addr.Name { - - case "cwd": - wd, err := os.Getwd() - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Failed to get working directory`, - Detail: fmt.Sprintf(`The value for path.cwd cannot be determined due to a system error: %s`, err), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - return cty.StringVal(filepath.ToSlash(wd)), diags - - case "module": - moduleConfig := d.Evaluator.Config.DescendentForInstance(d.ModulePath) - if moduleConfig == nil { - // should never happen, since we can't be evaluating in a module - // that wasn't mentioned in configuration. - panic(fmt.Sprintf("module.path read from module %s, which has no configuration", d.ModulePath)) - } - sourceDir := moduleConfig.Module.SourceDir - return cty.StringVal(filepath.ToSlash(sourceDir)), diags - - case "root": - sourceDir := d.Evaluator.Config.Module.SourceDir - return cty.StringVal(filepath.ToSlash(sourceDir)), diags - - default: - suggestion := nameSuggestion(addr.Name, []string{"cwd", "module", "root"}) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "path" attribute`, - Detail: fmt.Sprintf(`The "path" object does not have an attribute named %q.%s`, addr.Name, suggestion), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } -} - -func (d *evaluationStateData) GetResource(addr addrs.Resource, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - // First we'll consult the configuration to see if an resource of this - // name is declared at all. - moduleAddr := d.ModulePath - moduleConfig := d.Evaluator.Config.DescendentForInstance(moduleAddr) - if moduleConfig == nil { - // should never happen, since we can't be evaluating in a module - // that wasn't mentioned in configuration. - panic(fmt.Sprintf("resource value read from %s, which has no configuration", moduleAddr)) - } - - config := moduleConfig.Module.ResourceByAddr(addr) - if config == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared resource`, - Detail: fmt.Sprintf(`A resource %q %q has not been declared in %s`, addr.Type, addr.Name, moduleDisplayAddr(moduleAddr)), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - rs := d.Evaluator.State.Resource(addr.Absolute(d.ModulePath)) - - if rs == nil { - // we must return DynamicVal so that both interpretations - // can proceed without generating errors, and we'll deal with this - // in a later step where more information is gathered. - // (In practice we should only end up here during the validate walk, - // since later walks should have at least partial states populated - // for all resources in the configuration.) - return cty.DynamicVal, diags - } - - // Break out early during validation, because resource may not be expanded - // yet and indexed references may show up as invalid. - if d.Operation == walkValidate { - return cty.DynamicVal, diags - } - - return d.getResourceInstancesAll(addr, rng, config, rs, rs.ProviderConfig) -} - -func (d *evaluationStateData) getResourceInstancesAll(addr addrs.Resource, rng tfdiags.SourceRange, config *configs.Resource, rs *states.Resource, providerAddr addrs.AbsProviderConfig) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - - instAddr := addrs.ResourceInstance{Resource: addr, Key: addrs.NoKey} - - schema := d.getResourceSchema(addr, providerAddr) - if schema == nil { - // This shouldn't happen, since validation before we get here should've - // taken care of it, but we'll show a reasonable error message anyway. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Missing resource type schema`, - Detail: fmt.Sprintf("No schema is available for %s in %s. This is a bug in Terraform and should be reported.", addr, providerAddr), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } - - switch rs.EachMode { - case states.NoEach: - ty := schema.ImpliedType() - is := rs.Instances[addrs.NoKey] - if is == nil || is.Current == nil { - // Assume we're dealing with an instance that hasn't been created yet. - return cty.UnknownVal(ty), diags - } - - if is.Current.Status == states.ObjectPlanned { - // If there's a pending change for this instance in our plan, we'll prefer - // that. This is important because the state can't represent unknown values - // and so its data is inaccurate when changes are pending. - if change := d.Evaluator.Changes.GetResourceInstanceChange(instAddr.Absolute(d.ModulePath), states.CurrentGen); change != nil { - val, err := change.After.Decode(ty) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in plan", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the plan: %s.", addr.Absolute(d.ModulePath), err), - Subject: &config.DeclRange, - }) - return cty.UnknownVal(ty), diags - } - return val, diags - } else { - // If the object is in planned status then we should not - // get here, since we should've found a pending value - // in the plan above instead. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing pending object in plan", - Detail: fmt.Sprintf("Instance %s is marked as having a change pending but that change is not recorded in the plan. This is a bug in Terraform; please report it.", addr), - Subject: &config.DeclRange, - }) - return cty.UnknownVal(ty), diags - } - } - - ios, err := is.Current.Decode(ty) - if err != nil { - // This shouldn't happen, since by the time we get here - // we should've upgraded the state data already. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in state", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the state: %s.", addr.Absolute(d.ModulePath), err), - Subject: &config.DeclRange, - }) - return cty.UnknownVal(ty), diags - } - - return ios.Value, diags - - case states.EachList: - // We need to infer the length of our resulting tuple by searching - // for the max IntKey in our instances map. - length := 0 - for k := range rs.Instances { - if ik, ok := k.(addrs.IntKey); ok { - if int(ik) >= length { - length = int(ik) + 1 - } - } - } - - vals := make([]cty.Value, length) - for i := 0; i < length; i++ { - ty := schema.ImpliedType() - key := addrs.IntKey(i) - is, exists := rs.Instances[key] - if exists && is.Current != nil { - instAddr := addr.Instance(key).Absolute(d.ModulePath) - - // Prefer pending value in plan if present. See getResourceInstanceSingle - // comment for the rationale. - if is.Current.Status == states.ObjectPlanned { - if change := d.Evaluator.Changes.GetResourceInstanceChange(instAddr, states.CurrentGen); change != nil { - val, err := change.After.Decode(ty) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in plan", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the plan: %s.", instAddr, err), - Subject: &config.DeclRange, - }) - continue - } - vals[i] = val - continue - } else { - // If the object is in planned status then we should not - // get here, since we should've found a pending value - // in the plan above instead. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing pending object in plan", - Detail: fmt.Sprintf("Instance %s is marked as having a change pending but that change is not recorded in the plan. This is a bug in Terraform; please report it.", instAddr), - Subject: &config.DeclRange, - }) - continue - } - } - - ios, err := is.Current.Decode(ty) - if err != nil { - // This shouldn't happen, since by the time we get here - // we should've upgraded the state data already. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in state", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the state: %s.", instAddr, err), - Subject: &config.DeclRange, - }) - continue - } - vals[i] = ios.Value - } else { - // There shouldn't normally be "gaps" in our list but we'll - // allow it under the assumption that we're in a weird situation - // where e.g. someone has run "terraform state mv" to reorder - // a list and left a hole behind. - vals[i] = cty.UnknownVal(schema.ImpliedType()) - } - } - - // We use a tuple rather than a list here because resource schemas may - // include dynamically-typed attributes, which will then cause each - // instance to potentially have a different runtime type even though - // they all conform to the static schema. - return cty.TupleVal(vals), diags - - case states.EachMap: - ty := schema.ImpliedType() - vals := make(map[string]cty.Value, len(rs.Instances)) - for k, is := range rs.Instances { - if sk, ok := k.(addrs.StringKey); ok { - instAddr := addr.Instance(k).Absolute(d.ModulePath) - - // Prefer pending value in plan if present. See getResourceInstanceSingle - // comment for the rationale. - // Prefer pending value in plan if present. See getResourceInstanceSingle - // comment for the rationale. - if is.Current.Status == states.ObjectPlanned { - if change := d.Evaluator.Changes.GetResourceInstanceChange(instAddr, states.CurrentGen); change != nil { - val, err := change.After.Decode(ty) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in plan", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the plan: %s.", instAddr, err), - Subject: &config.DeclRange, - }) - continue - } - vals[string(sk)] = val - continue - } else { - // If the object is in planned status then we should not - // get here, since we should've found a pending value - // in the plan above instead. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Missing pending object in plan", - Detail: fmt.Sprintf("Instance %s is marked as having a change pending but that change is not recorded in the plan. This is a bug in Terraform; please report it.", instAddr), - Subject: &config.DeclRange, - }) - continue - } - } - - ios, err := is.Current.Decode(ty) - if err != nil { - // This shouldn't happen, since by the time we get here - // we should've upgraded the state data already. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in state", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the state: %s.", instAddr, err), - Subject: &config.DeclRange, - }) - continue - } - vals[string(sk)] = ios.Value - } - } - - // We use an object rather than a map here because resource schemas may - // include dynamically-typed attributes, which will then cause each - // instance to potentially have a different runtime type even though - // they all conform to the static schema. - return cty.ObjectVal(vals), diags - - default: - // Should never happen since caller should deal with other modes - panic(fmt.Sprintf("unsupported EachMode %s", rs.EachMode)) - } -} - -func (d *evaluationStateData) getResourceSchema(addr addrs.Resource, providerAddr addrs.AbsProviderConfig) *configschema.Block { - providerType := providerAddr.ProviderConfig.Type - schemas := d.Evaluator.Schemas - schema, _ := schemas.ResourceTypeConfig(providerType, addr.Mode, addr.Type) - return schema -} - -func (d *evaluationStateData) GetTerraformAttr(addr addrs.TerraformAttr, rng tfdiags.SourceRange) (cty.Value, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - switch addr.Name { - - case "workspace": - workspaceName := d.Evaluator.Meta.Env - return cty.StringVal(workspaceName), diags - - case "env": - // Prior to Terraform 0.12 there was an attribute "env", which was - // an alias name for "workspace". This was deprecated and is now - // removed. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "terraform" attribute`, - Detail: `The terraform.env attribute was deprecated in v0.10 and removed in v0.12. The "state environment" concept was rename to "workspace" in v0.12, and so the workspace name can now be accessed using the terraform.workspace attribute.`, - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "terraform" attribute`, - Detail: fmt.Sprintf(`The "terraform" object does not have an attribute named %q. The only supported attribute is terraform.workspace, the name of the currently-selected workspace.`, addr.Name), - Subject: rng.ToHCL().Ptr(), - }) - return cty.DynamicVal, diags - } -} - -// nameSuggestion tries to find a name from the given slice of suggested names -// that is close to the given name and returns it if found. If no suggestion -// is close enough, returns the empty string. -// -// The suggestions are tried in order, so earlier suggestions take precedence -// if the given string is similar to two or more suggestions. -// -// This function is intended to be used with a relatively-small number of -// suggestions. It's not optimized for hundreds or thousands of them. -func nameSuggestion(given string, suggestions []string) string { - for _, suggestion := range suggestions { - dist := levenshtein.Distance(given, suggestion, nil) - if dist < 3 { // threshold determined experimentally - return suggestion - } - } - return "" -} - -// moduleDisplayAddr returns a string describing the given module instance -// address that is appropriate for returning to users in situations where the -// root module is possible. Specifically, it returns "the root module" if the -// root module instance is given, or a string representation of the module -// address otherwise. -func moduleDisplayAddr(addr addrs.ModuleInstance) string { - switch { - case addr.IsRoot(): - return "the root module" - default: - return addr.String() - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate_valid.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate_valid.go deleted file mode 100644 index 35a8be0c960..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate_valid.go +++ /dev/null @@ -1,299 +0,0 @@ -package terraform - -import ( - "fmt" - "sort" - - "github.com/hashicorp/hcl/v2" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/helper/didyoumean" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// StaticValidateReferences checks the given references against schemas and -// other statically-checkable rules, producing error diagnostics if any -// problems are found. -// -// If this method returns errors for a particular reference then evaluating -// that reference is likely to generate a very similar error, so callers should -// not run this method and then also evaluate the source expression(s) and -// merge the two sets of diagnostics together, since this will result in -// confusing redundant errors. -// -// This method can find more errors than can be found by evaluating an -// expression with a partially-populated scope, since it checks the referenced -// names directly against the schema rather than relying on evaluation errors. -// -// The result may include warning diagnostics if, for example, deprecated -// features are referenced. -func (d *evaluationStateData) StaticValidateReferences(refs []*addrs.Reference, self addrs.Referenceable) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - for _, ref := range refs { - moreDiags := d.staticValidateReference(ref, self) - diags = diags.Append(moreDiags) - } - return diags -} - -func (d *evaluationStateData) staticValidateReference(ref *addrs.Reference, self addrs.Referenceable) tfdiags.Diagnostics { - modCfg := d.Evaluator.Config.DescendentForInstance(d.ModulePath) - if modCfg == nil { - // This is a bug in the caller rather than a problem with the - // reference, but rather than crashing out here in an unhelpful way - // we'll just ignore it and trust a different layer to catch it. - return nil - } - - if ref.Subject == addrs.Self { - // The "self" address is a special alias for the address given as - // our self parameter here, if present. - if self == nil { - var diags tfdiags.Diagnostics - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "self" reference`, - // This detail message mentions some current practice that - // this codepath doesn't really "know about". If the "self" - // object starts being supported in more contexts later then - // we'll need to adjust this message. - Detail: `The "self" object is not available in this context. This object can be used only in resource provisioner and connection blocks.`, - Subject: ref.SourceRange.ToHCL().Ptr(), - }) - return diags - } - - synthRef := *ref // shallow copy - synthRef.Subject = self - ref = &synthRef - } - - switch addr := ref.Subject.(type) { - - // For static validation we validate both resource and resource instance references the same way. - // We mostly disregard the index, though we do some simple validation of - // its _presence_ in staticValidateSingleResourceReference and - // staticValidateMultiResourceReference respectively. - case addrs.Resource: - var diags tfdiags.Diagnostics - diags = diags.Append(d.staticValidateSingleResourceReference(modCfg, addr, ref.Remaining, ref.SourceRange)) - diags = diags.Append(d.staticValidateResourceReference(modCfg, addr, ref.Remaining, ref.SourceRange)) - return diags - case addrs.ResourceInstance: - var diags tfdiags.Diagnostics - diags = diags.Append(d.staticValidateMultiResourceReference(modCfg, addr, ref.Remaining, ref.SourceRange)) - diags = diags.Append(d.staticValidateResourceReference(modCfg, addr.ContainingResource(), ref.Remaining, ref.SourceRange)) - return diags - - // We also handle all module call references the same way, disregarding index. - case addrs.ModuleCall: - return d.staticValidateModuleCallReference(modCfg, addr, ref.Remaining, ref.SourceRange) - case addrs.ModuleCallInstance: - return d.staticValidateModuleCallReference(modCfg, addr.Call, ref.Remaining, ref.SourceRange) - case addrs.ModuleCallOutput: - // This one is a funny one because we will take the output name referenced - // and use it to fake up a "remaining" that would make sense for the - // module call itself, rather than for the specific output, and then - // we can just re-use our static module call validation logic. - remain := make(hcl.Traversal, len(ref.Remaining)+1) - copy(remain[1:], ref.Remaining) - remain[0] = hcl.TraverseAttr{ - Name: addr.Name, - - // Using the whole reference as the source range here doesn't exactly - // match how HCL would normally generate an attribute traversal, - // but is close enough for our purposes. - SrcRange: ref.SourceRange.ToHCL(), - } - return d.staticValidateModuleCallReference(modCfg, addr.Call.Call, remain, ref.SourceRange) - - default: - // Anything else we'll just permit through without any static validation - // and let it be caught during dynamic evaluation, in evaluate.go . - return nil - } -} - -func (d *evaluationStateData) staticValidateSingleResourceReference(modCfg *configs.Config, addr addrs.Resource, remain hcl.Traversal, rng tfdiags.SourceRange) tfdiags.Diagnostics { - // If we have at least one step in "remain" and this resource has - // "count" set then we know for sure this in invalid because we have - // something like: - // aws_instance.foo.bar - // ...when we really need - // aws_instance.foo[count.index].bar - - // It is _not_ safe to do this check when remain is empty, because that - // would also match aws_instance.foo[count.index].bar due to `count.index` - // not being statically-resolvable as part of a reference, and match - // direct references to the whole aws_instance.foo tuple. - if len(remain) == 0 { - return nil - } - - var diags tfdiags.Diagnostics - - cfg := modCfg.Module.ResourceByAddr(addr) - if cfg == nil { - // We'll just bail out here and catch this in our subsequent call to - // staticValidateResourceReference, then. - return diags - } - - if cfg.Count != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Missing resource instance key`, - Detail: fmt.Sprintf("Because %s has \"count\" set, its attributes must be accessed on specific instances.\n\nFor example, to correlate with indices of a referring resource, use:\n %s[count.index]", addr, addr), - Subject: rng.ToHCL().Ptr(), - }) - } - if cfg.ForEach != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Missing resource instance key`, - Detail: fmt.Sprintf("Because %s has \"for_each\" set, its attributes must be accessed on specific instances.\n\nFor example, to correlate with indices of a referring resource, use:\n %s[each.key]", addr, addr), - Subject: rng.ToHCL().Ptr(), - }) - } - - return diags -} - -func (d *evaluationStateData) staticValidateMultiResourceReference(modCfg *configs.Config, addr addrs.ResourceInstance, remain hcl.Traversal, rng tfdiags.SourceRange) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - cfg := modCfg.Module.ResourceByAddr(addr.ContainingResource()) - if cfg == nil { - // We'll just bail out here and catch this in our subsequent call to - // staticValidateResourceReference, then. - return diags - } - - if addr.Key == addrs.NoKey { - // This is a different path into staticValidateSingleResourceReference - return d.staticValidateSingleResourceReference(modCfg, addr.ContainingResource(), remain, rng) - } else { - if cfg.Count == nil && cfg.ForEach == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Unexpected resource instance key`, - Detail: fmt.Sprintf(`Because %s does not have "count" or "for_each" set, references to it must not include an index key. Remove the bracketed index to refer to the single instance of this resource.`, addr.ContainingResource()), - Subject: rng.ToHCL().Ptr(), - }) - } - } - - return diags -} - -func (d *evaluationStateData) staticValidateResourceReference(modCfg *configs.Config, addr addrs.Resource, remain hcl.Traversal, rng tfdiags.SourceRange) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - var modeAdjective string - switch addr.Mode { - case addrs.ManagedResourceMode: - modeAdjective = "managed" - case addrs.DataResourceMode: - modeAdjective = "data" - default: - // should never happen - modeAdjective = "" - } - - cfg := modCfg.Module.ResourceByAddr(addr) - if cfg == nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared resource`, - Detail: fmt.Sprintf(`A %s resource %q %q has not been declared in %s.`, modeAdjective, addr.Type, addr.Name, moduleConfigDisplayAddr(modCfg.Path)), - Subject: rng.ToHCL().Ptr(), - }) - return diags - } - - // Normally accessing this directly is wrong because it doesn't take into - // account provider inheritance, etc but it's okay here because we're only - // paying attention to the type anyway. - providerType := cfg.ProviderConfigAddr().Type - schema, _ := d.Evaluator.Schemas.ResourceTypeConfig(providerType, addr.Mode, addr.Type) - - if schema == nil { - // Prior validation should've taken care of a resource block with an - // unsupported type, so we should never get here but we'll handle it - // here anyway for robustness. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid resource type`, - Detail: fmt.Sprintf(`A %s resource type %q is not supported by provider %q.`, modeAdjective, addr.Type, providerType), - Subject: rng.ToHCL().Ptr(), - }) - return diags - } - - // As a special case we'll detect attempts to access an attribute called - // "count" and produce a special error for it, since versions of Terraform - // prior to v0.12 offered this as a weird special case that we can no - // longer support. - if len(remain) > 0 { - if step, ok := remain[0].(hcl.TraverseAttr); ok && step.Name == "count" { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid resource count attribute`, - Detail: fmt.Sprintf(`The special "count" attribute is no longer supported after Terraform v0.12. Instead, use length(%s) to count resource instances.`, addr), - Subject: rng.ToHCL().Ptr(), - }) - return diags - } - } - - // If we got this far then we'll try to validate the remaining traversal - // steps against our schema. - moreDiags := schema.StaticValidateTraversal(remain) - diags = diags.Append(moreDiags) - - return diags -} - -func (d *evaluationStateData) staticValidateModuleCallReference(modCfg *configs.Config, addr addrs.ModuleCall, remain hcl.Traversal, rng tfdiags.SourceRange) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - // For now, our focus here is just in testing that the referenced module - // call exists. All other validation is deferred until evaluation time. - _, exists := modCfg.Module.ModuleCalls[addr.Name] - if !exists { - var suggestions []string - for name := range modCfg.Module.ModuleCalls { - suggestions = append(suggestions, name) - } - sort.Strings(suggestions) - suggestion := didyoumean.NameSuggestion(addr.Name, suggestions) - if suggestion != "" { - suggestion = fmt.Sprintf(" Did you mean %q?", suggestion) - } - - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to undeclared module`, - Detail: fmt.Sprintf(`No module call named %q is declared in %s.%s`, addr.Name, moduleConfigDisplayAddr(modCfg.Path), suggestion), - Subject: rng.ToHCL().Ptr(), - }) - return diags - } - - return diags -} - -// moduleConfigDisplayAddr returns a string describing the given module -// address that is appropriate for returning to users in situations where the -// root module is possible. Specifically, it returns "the root module" if the -// root module instance is given, or a string representation of the module -// address otherwise. -func moduleConfigDisplayAddr(addr addrs.Module) string { - switch { - case addr.IsRoot(): - return "the root module" - default: - return addr.String() - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/features.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/features.go deleted file mode 100644 index 97c77bdbd00..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/features.go +++ /dev/null @@ -1,7 +0,0 @@ -package terraform - -import "os" - -// This file holds feature flags for the next release - -var flagWarnOutputErrors = os.Getenv("TF_WARN_OUTPUT_ERRORS") != "" diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph.go deleted file mode 100644 index 36e295b6f20..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph.go +++ /dev/null @@ -1,141 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// Graph represents the graph that Terraform uses to represent resources -// and their dependencies. -type Graph struct { - // Graph is the actual DAG. This is embedded so you can call the DAG - // methods directly. - dag.AcyclicGraph - - // Path is the path in the module tree that this Graph represents. - Path addrs.ModuleInstance - - // debugName is a name for reference in the debug output. This is usually - // to indicate what topmost builder was, and if this graph is a shadow or - // not. - debugName string -} - -func (g *Graph) DirectedGraph() dag.Grapher { - return &g.AcyclicGraph -} - -// Walk walks the graph with the given walker for callbacks. The graph -// will be walked with full parallelism, so the walker should expect -// to be called in concurrently. -func (g *Graph) Walk(walker GraphWalker) tfdiags.Diagnostics { - return g.walk(walker) -} - -func (g *Graph) walk(walker GraphWalker) tfdiags.Diagnostics { - // The callbacks for enter/exiting a graph - ctx := walker.EnterPath(g.Path) - defer walker.ExitPath(g.Path) - - // Get the path for logs - path := ctx.Path().String() - - debugName := "walk-graph.json" - if g.debugName != "" { - debugName = g.debugName + "-" + debugName - } - - // Walk the graph. - var walkFn dag.WalkFunc - walkFn = func(v dag.Vertex) (diags tfdiags.Diagnostics) { - log.Printf("[TRACE] vertex %q: starting visit (%T)", dag.VertexName(v), v) - g.DebugVisitInfo(v, g.debugName) - - defer func() { - log.Printf("[TRACE] vertex %q: visit complete", dag.VertexName(v)) - }() - - walker.EnterVertex(v) - defer walker.ExitVertex(v, diags) - - // vertexCtx is the context that we use when evaluating. This - // is normally the context of our graph but can be overridden - // with a GraphNodeSubPath impl. - vertexCtx := ctx - if pn, ok := v.(GraphNodeSubPath); ok && len(pn.Path()) > 0 { - vertexCtx = walker.EnterPath(pn.Path()) - defer walker.ExitPath(pn.Path()) - } - - // If the node is eval-able, then evaluate it. - if ev, ok := v.(GraphNodeEvalable); ok { - tree := ev.EvalTree() - if tree == nil { - panic(fmt.Sprintf("%q (%T): nil eval tree", dag.VertexName(v), v)) - } - - // Allow the walker to change our tree if needed. Eval, - // then callback with the output. - log.Printf("[TRACE] vertex %q: evaluating", dag.VertexName(v)) - - g.DebugVertexInfo(v, fmt.Sprintf("evaluating %T(%s)", v, path)) - - tree = walker.EnterEvalTree(v, tree) - output, err := Eval(tree, vertexCtx) - diags = diags.Append(walker.ExitEvalTree(v, output, err)) - if diags.HasErrors() { - return - } - } - - // If the node is dynamically expanded, then expand it - if ev, ok := v.(GraphNodeDynamicExpandable); ok { - log.Printf("[TRACE] vertex %q: expanding dynamic subgraph", dag.VertexName(v)) - - g.DebugVertexInfo(v, fmt.Sprintf("expanding %T(%s)", v, path)) - - g, err := ev.DynamicExpand(vertexCtx) - if err != nil { - diags = diags.Append(err) - return - } - if g != nil { - // Walk the subgraph - log.Printf("[TRACE] vertex %q: entering dynamic subgraph", dag.VertexName(v)) - subDiags := g.walk(walker) - diags = diags.Append(subDiags) - if subDiags.HasErrors() { - log.Printf("[TRACE] vertex %q: dynamic subgraph encountered errors", dag.VertexName(v)) - return - } - log.Printf("[TRACE] vertex %q: dynamic subgraph completed successfully", dag.VertexName(v)) - } else { - log.Printf("[TRACE] vertex %q: produced no dynamic subgraph", dag.VertexName(v)) - } - } - - // If the node has a subgraph, then walk the subgraph - if sn, ok := v.(GraphNodeSubgraph); ok { - log.Printf("[TRACE] vertex %q: entering static subgraph", dag.VertexName(v)) - - g.DebugVertexInfo(v, fmt.Sprintf("subgraph: %T(%s)", v, path)) - - subDiags := sn.Subgraph().(*Graph).walk(walker) - if subDiags.HasErrors() { - log.Printf("[TRACE] vertex %q: static subgraph encountered errors", dag.VertexName(v)) - return - } - log.Printf("[TRACE] vertex %q: static subgraph completed successfully", dag.VertexName(v)) - } - - return - } - - return g.AcyclicGraph.Walk(walkFn) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder.go deleted file mode 100644 index ee2c5857afb..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder.go +++ /dev/null @@ -1,85 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// GraphBuilder is an interface that can be implemented and used with -// Terraform to build the graph that Terraform walks. -type GraphBuilder interface { - // Build builds the graph for the given module path. It is up to - // the interface implementation whether this build should expand - // the graph or not. - Build(addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) -} - -// BasicGraphBuilder is a GraphBuilder that builds a graph out of a -// series of transforms and (optionally) validates the graph is a valid -// structure. -type BasicGraphBuilder struct { - Steps []GraphTransformer - Validate bool - // Optional name to add to the graph debug log - Name string -} - -func (b *BasicGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - g := &Graph{Path: path} - - var lastStepStr string - for _, step := range b.Steps { - if step == nil { - continue - } - log.Printf("[TRACE] Executing graph transform %T", step) - - stepName := fmt.Sprintf("%T", step) - dot := strings.LastIndex(stepName, ".") - if dot >= 0 { - stepName = stepName[dot+1:] - } - - debugOp := g.DebugOperation(stepName, "") - err := step.Transform(g) - - errMsg := "" - if err != nil { - errMsg = err.Error() - } - debugOp.End(errMsg) - - if thisStepStr := g.StringWithNodeTypes(); thisStepStr != lastStepStr { - log.Printf("[TRACE] Completed graph transform %T with new graph:\n%s------", step, thisStepStr) - lastStepStr = thisStepStr - } else { - log.Printf("[TRACE] Completed graph transform %T (no changes)", step) - } - - if err != nil { - if nf, isNF := err.(tfdiags.NonFatalError); isNF { - diags = diags.Append(nf.Diagnostics) - } else { - diags = diags.Append(err) - return g, diags - } - } - } - - // Validate the graph structure - if b.Validate { - if err := g.Validate(); err != nil { - log.Printf("[ERROR] Graph validation failed. Graph:\n\n%s", g.String()) - diags = diags.Append(err) - return nil, diags - } - } - - return g, diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_apply.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_apply.go deleted file mode 100644 index 91898761065..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_apply.go +++ /dev/null @@ -1,211 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// ApplyGraphBuilder implements GraphBuilder and is responsible for building -// a graph for applying a Terraform diff. -// -// Because the graph is built from the diff (vs. the config or state), -// this helps ensure that the apply-time graph doesn't modify any resources -// that aren't explicitly in the diff. There are other scenarios where the -// diff can be deviated, so this is just one layer of protection. -type ApplyGraphBuilder struct { - // Config is the configuration tree that the diff was built from. - Config *configs.Config - - // Changes describes the changes that we need apply. - Changes *plans.Changes - - // State is the current state - State *states.State - - // Components is a factory for the plug-in components (providers and - // provisioners) available for use. - Components contextComponentFactory - - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas - - // Targets are resources to target. This is only required to make sure - // unnecessary outputs aren't included in the apply graph. The plan - // builder successfully handles targeting resources. In the future, - // outputs should go into the diff so that this is unnecessary. - Targets []addrs.Targetable - - // DisableReduce, if true, will not reduce the graph. Great for testing. - DisableReduce bool - - // Destroy, if true, represents a pure destroy operation - Destroy bool - - // Validate will do structural validation of the graph. - Validate bool -} - -// See GraphBuilder -func (b *ApplyGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { - return (&BasicGraphBuilder{ - Steps: b.Steps(), - Validate: b.Validate, - Name: "ApplyGraphBuilder", - }).Build(path) -} - -// See GraphBuilder -func (b *ApplyGraphBuilder) Steps() []GraphTransformer { - // Custom factory for creating providers. - concreteProvider := func(a *NodeAbstractProvider) dag.Vertex { - return &NodeApplyableProvider{ - NodeAbstractProvider: a, - } - } - - concreteResource := func(a *NodeAbstractResource) dag.Vertex { - return &NodeApplyableResource{ - NodeAbstractResource: a, - } - } - - concreteOrphanResource := func(a *NodeAbstractResource) dag.Vertex { - return &NodeDestroyResource{ - NodeAbstractResource: a, - } - } - - concreteResourceInstance := func(a *NodeAbstractResourceInstance) dag.Vertex { - return &NodeApplyableResourceInstance{ - NodeAbstractResourceInstance: a, - } - } - - steps := []GraphTransformer{ - // Creates all the resources represented in the config. During apply, - // we use this just to ensure that the whole-resource metadata is - // updated to reflect things such as whether the count argument is - // set in config, or which provider configuration manages each resource. - &ConfigTransformer{ - Concrete: concreteResource, - Config: b.Config, - }, - - // Creates all the resource instances represented in the diff, along - // with dependency edges against the whole-resource nodes added by - // ConfigTransformer above. - &DiffTransformer{ - Concrete: concreteResourceInstance, - State: b.State, - Changes: b.Changes, - }, - - // Creates extra cleanup nodes for any entire resources that are - // no longer present in config, so we can make sure we clean up the - // leftover empty resource states after the instances have been - // destroyed. - // (We don't track this particular type of change in the plan because - // it's just cleanup of our own state object, and so doesn't effect - // any real remote objects or consumable outputs.) - &OrphanResourceTransformer{ - Concrete: concreteOrphanResource, - Config: b.Config, - State: b.State, - }, - - // Create orphan output nodes - &OrphanOutputTransformer{Config: b.Config, State: b.State}, - - // Attach the configuration to any resources - &AttachResourceConfigTransformer{Config: b.Config}, - - // Attach the state - &AttachStateTransformer{State: b.State}, - - // Provisioner-related transformations - &MissingProvisionerTransformer{Provisioners: b.Components.ResourceProvisioners()}, - &ProvisionerTransformer{}, - - // Add root variables - &RootVariableTransformer{Config: b.Config}, - - // Add the local values - &LocalTransformer{Config: b.Config}, - - // Add the outputs - &OutputTransformer{Config: b.Config}, - - // Add module variables - &ModuleVariableTransformer{Config: b.Config}, - - // add providers - TransformProviders(b.Components.ResourceProviders(), concreteProvider, b.Config), - - // Remove modules no longer present in the config - &RemovedModuleTransformer{Config: b.Config, State: b.State}, - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: b.Schemas}, - - // Connect references so ordering is correct - &ReferenceTransformer{}, - - // Destruction ordering - &DestroyEdgeTransformer{ - Config: b.Config, - State: b.State, - Schemas: b.Schemas, - }, - - &CBDEdgeTransformer{ - Config: b.Config, - State: b.State, - Schemas: b.Schemas, - Destroy: b.Destroy, - }, - - // Handle destroy time transformations for output and local values. - // Reverse the edges from outputs and locals, so that - // interpolations don't fail during destroy. - // Create a destroy node for outputs to remove them from the state. - // Prune unreferenced values, which may have interpolations that can't - // be resolved. - GraphTransformIf( - func() bool { return b.Destroy }, - GraphTransformMulti( - &DestroyValueReferenceTransformer{}, - &DestroyOutputTransformer{}, - &PruneUnusedValuesTransformer{}, - ), - ), - - // Add the node to fix the state count boundaries - &CountBoundaryTransformer{ - Config: b.Config, - }, - - // Target - &TargetsTransformer{Targets: b.Targets}, - - // Close opened plugin connections - &CloseProviderTransformer{}, - &CloseProvisionerTransformer{}, - - // Single root - &RootTransformer{}, - } - - if !b.DisableReduce { - // Perform the transitive reduction to make our graph a bit - // more sane if possible (it usually is possible). - steps = append(steps, &TransitiveReductionTransformer{}) - } - - return steps -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_destroy_plan.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_destroy_plan.go deleted file mode 100644 index 32fe5f97359..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_destroy_plan.go +++ /dev/null @@ -1,97 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// DestroyPlanGraphBuilder implements GraphBuilder and is responsible for -// planning a pure-destroy. -// -// Planning a pure destroy operation is simple because we can ignore most -// ordering configuration and simply reverse the state. -type DestroyPlanGraphBuilder struct { - // Config is the configuration tree to build the plan from. - Config *configs.Config - - // State is the current state - State *states.State - - // Components is a factory for the plug-in components (providers and - // provisioners) available for use. - Components contextComponentFactory - - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas - - // Targets are resources to target - Targets []addrs.Targetable - - // Validate will do structural validation of the graph. - Validate bool -} - -// See GraphBuilder -func (b *DestroyPlanGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { - return (&BasicGraphBuilder{ - Steps: b.Steps(), - Validate: b.Validate, - Name: "DestroyPlanGraphBuilder", - }).Build(path) -} - -// See GraphBuilder -func (b *DestroyPlanGraphBuilder) Steps() []GraphTransformer { - concreteResourceInstance := func(a *NodeAbstractResourceInstance) dag.Vertex { - return &NodePlanDestroyableResourceInstance{ - NodeAbstractResourceInstance: a, - } - } - concreteResourceInstanceDeposed := func(a *NodeAbstractResourceInstance, key states.DeposedKey) dag.Vertex { - return &NodePlanDeposedResourceInstanceObject{ - NodeAbstractResourceInstance: a, - DeposedKey: key, - } - } - - concreteProvider := func(a *NodeAbstractProvider) dag.Vertex { - return &NodeApplyableProvider{ - NodeAbstractProvider: a, - } - } - - steps := []GraphTransformer{ - // Creates nodes for the resource instances tracked in the state. - &StateTransformer{ - ConcreteCurrent: concreteResourceInstance, - ConcreteDeposed: concreteResourceInstanceDeposed, - State: b.State, - }, - - // Attach the configuration to any resources - &AttachResourceConfigTransformer{Config: b.Config}, - - TransformProviders(b.Components.ResourceProviders(), concreteProvider, b.Config), - - // Destruction ordering. We require this only so that - // targeting below will prune the correct things. - &DestroyEdgeTransformer{ - Config: b.Config, - State: b.State, - Schemas: b.Schemas, - }, - - // Target. Note we don't set "Destroy: true" here since we already - // created proper destroy ordering. - &TargetsTransformer{Targets: b.Targets}, - - // Single root - &RootTransformer{}, - } - - return steps -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_eval.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_eval.go deleted file mode 100644 index 8a0bcf5ba9e..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_eval.go +++ /dev/null @@ -1,108 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// EvalGraphBuilder implements GraphBuilder and constructs a graph suitable -// for evaluating in-memory values (input variables, local values, output -// values) in the state without any other side-effects. -// -// This graph is used only in weird cases, such as the "terraform console" -// CLI command, where we need to evaluate expressions against the state -// without taking any other actions. -// -// The generated graph will include nodes for providers, resources, etc -// just to allow indirect dependencies to be resolved, but these nodes will -// not take any actions themselves since we assume that their parts of the -// state, if any, are already complete. -// -// Although the providers are never configured, they must still be available -// in order to obtain schema information used for type checking, etc. -type EvalGraphBuilder struct { - // Config is the configuration tree. - Config *configs.Config - - // State is the current state - State *states.State - - // Components is a factory for the plug-in components (providers and - // provisioners) available for use. - Components contextComponentFactory - - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas -} - -// See GraphBuilder -func (b *EvalGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { - return (&BasicGraphBuilder{ - Steps: b.Steps(), - Validate: true, - Name: "EvalGraphBuilder", - }).Build(path) -} - -// See GraphBuilder -func (b *EvalGraphBuilder) Steps() []GraphTransformer { - concreteProvider := func(a *NodeAbstractProvider) dag.Vertex { - return &NodeEvalableProvider{ - NodeAbstractProvider: a, - } - } - - steps := []GraphTransformer{ - // 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: nil, // just use the abstract type - Config: b.Config, - Unique: true, - }, - - // Attach the state - &AttachStateTransformer{State: b.State}, - - // Attach the configuration to any resources - &AttachResourceConfigTransformer{Config: b.Config}, - - // Add root variables - &RootVariableTransformer{Config: b.Config}, - - // Add the local values - &LocalTransformer{Config: b.Config}, - - // Add the outputs - &OutputTransformer{Config: b.Config}, - - // Add module variables - &ModuleVariableTransformer{Config: b.Config}, - - TransformProviders(b.Components.ResourceProviders(), concreteProvider, b.Config), - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: b.Schemas}, - - // Connect so that the references are ready for targeting. We'll - // have to connect again later for providers and so on. - &ReferenceTransformer{}, - - // Although we don't configure providers, we do still start them up - // to get their schemas, and so we must shut them down again here. - &CloseProviderTransformer{}, - - // Single root - &RootTransformer{}, - - // Remove redundant edges to simplify the graph. - &TransitiveReductionTransformer{}, - } - - return steps -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_import.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_import.go deleted file mode 100644 index dcbb10e6088..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_import.go +++ /dev/null @@ -1,100 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// ImportGraphBuilder implements GraphBuilder and is responsible for building -// a graph for importing resources into Terraform. This is a much, much -// simpler graph than a normal configuration graph. -type ImportGraphBuilder struct { - // ImportTargets are the list of resources to import. - ImportTargets []*ImportTarget - - // Module is a configuration to build the graph from. See ImportOpts.Config. - Config *configs.Config - - // Components is the factory for our available plugin components. - Components contextComponentFactory - - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas -} - -// Build builds the graph according to the steps returned by Steps. -func (b *ImportGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { - return (&BasicGraphBuilder{ - Steps: b.Steps(), - Validate: true, - Name: "ImportGraphBuilder", - }).Build(path) -} - -// Steps returns the ordered list of GraphTransformers that must be executed -// to build a complete graph. -func (b *ImportGraphBuilder) Steps() []GraphTransformer { - // Get the module. If we don't have one, we just use an empty tree - // so that the transform still works but does nothing. - config := b.Config - if config == nil { - config = configs.NewEmptyConfig() - } - - // Custom factory for creating providers. - concreteProvider := func(a *NodeAbstractProvider) dag.Vertex { - return &NodeApplyableProvider{ - NodeAbstractProvider: a, - } - } - - steps := []GraphTransformer{ - // Create all our resources from the configuration and state - &ConfigTransformer{Config: config}, - - // Attach the configuration to any resources - &AttachResourceConfigTransformer{Config: b.Config}, - - // Add the import steps - &ImportStateTransformer{Targets: b.ImportTargets}, - - // Add root variables - &RootVariableTransformer{Config: b.Config}, - - TransformProviders(b.Components.ResourceProviders(), concreteProvider, config), - - // This validates that the providers only depend on variables - &ImportProviderValidateTransformer{}, - - // Add the local values - &LocalTransformer{Config: b.Config}, - - // Add the outputs - &OutputTransformer{Config: b.Config}, - - // Add module variables - &ModuleVariableTransformer{Config: b.Config}, - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: b.Schemas}, - - // Connect so that the references are ready for targeting. We'll - // have to connect again later for providers and so on. - &ReferenceTransformer{}, - - // Close opened plugin connections - &CloseProviderTransformer{}, - - // Single root - &RootTransformer{}, - - // Optimize - &TransitiveReductionTransformer{}, - } - - return steps -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_plan.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_plan.go deleted file mode 100644 index bcd119b39d3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_plan.go +++ /dev/null @@ -1,204 +0,0 @@ -package terraform - -import ( - "sync" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// PlanGraphBuilder implements GraphBuilder and is responsible for building -// a graph for planning (creating a Terraform Diff). -// -// The primary difference between this graph and others: -// -// * Based on the config since it represents the target state -// -// * Ignores lifecycle options since no lifecycle events occur here. This -// simplifies the graph significantly since complex transforms such as -// create-before-destroy can be completely ignored. -// -type PlanGraphBuilder struct { - // Config is the configuration tree to build a plan from. - Config *configs.Config - - // State is the current state - State *states.State - - // Components is a factory for the plug-in components (providers and - // provisioners) available for use. - Components contextComponentFactory - - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas - - // Targets are resources to target - Targets []addrs.Targetable - - // DisableReduce, if true, will not reduce the graph. Great for testing. - DisableReduce bool - - // Validate will do structural validation of the graph. - Validate bool - - // CustomConcrete can be set to customize the node types created - // for various parts of the plan. This is useful in order to customize - // the plan behavior. - CustomConcrete bool - ConcreteProvider ConcreteProviderNodeFunc - ConcreteResource ConcreteResourceNodeFunc - ConcreteResourceOrphan ConcreteResourceInstanceNodeFunc - - once sync.Once -} - -// See GraphBuilder -func (b *PlanGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { - return (&BasicGraphBuilder{ - Steps: b.Steps(), - Validate: b.Validate, - Name: "PlanGraphBuilder", - }).Build(path) -} - -// See GraphBuilder -func (b *PlanGraphBuilder) Steps() []GraphTransformer { - b.once.Do(b.init) - - concreteResourceInstanceDeposed := func(a *NodeAbstractResourceInstance, key states.DeposedKey) dag.Vertex { - return &NodePlanDeposedResourceInstanceObject{ - NodeAbstractResourceInstance: a, - DeposedKey: key, - } - } - - steps := []GraphTransformer{ - // Creates all the resources represented in the config - &ConfigTransformer{ - Concrete: b.ConcreteResource, - Config: b.Config, - }, - - // Add the local values - &LocalTransformer{Config: b.Config}, - - // Add the outputs - &OutputTransformer{Config: b.Config}, - - // Add orphan resources - &OrphanResourceInstanceTransformer{ - Concrete: b.ConcreteResourceOrphan, - State: b.State, - Config: b.Config, - }, - - // We also need nodes for any deposed instance objects present in the - // state, so we can plan to destroy them. (This intentionally - // skips creating nodes for _current_ objects, since ConfigTransformer - // created nodes that will do that during DynamicExpand.) - &StateTransformer{ - ConcreteDeposed: concreteResourceInstanceDeposed, - State: b.State, - }, - - // Create orphan output nodes - &OrphanOutputTransformer{ - Config: b.Config, - State: b.State, - }, - - // Attach the configuration to any resources - &AttachResourceConfigTransformer{Config: b.Config}, - - // Attach the state - &AttachStateTransformer{State: b.State}, - - // Add root variables - &RootVariableTransformer{Config: b.Config}, - - &MissingProvisionerTransformer{Provisioners: b.Components.ResourceProvisioners()}, - &ProvisionerTransformer{}, - - // Add module variables - &ModuleVariableTransformer{ - Config: b.Config, - }, - - TransformProviders(b.Components.ResourceProviders(), b.ConcreteProvider, b.Config), - - // Remove modules no longer present in the config - &RemovedModuleTransformer{Config: b.Config, State: b.State}, - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: b.Schemas}, - - // Connect so that the references are ready for targeting. We'll - // have to connect again later for providers and so on. - &ReferenceTransformer{}, - - // Add the node to fix the state count boundaries - &CountBoundaryTransformer{ - Config: b.Config, - }, - - // Target - &TargetsTransformer{ - Targets: b.Targets, - - // Resource nodes from config have not yet been expanded for - // "count", so we must apply targeting without indices. Exact - // targeting will be dealt with later when these resources - // DynamicExpand. - IgnoreIndices: true, - }, - - // Detect when create_before_destroy must be forced on for a particular - // node due to dependency edges, to avoid graph cycles during apply. - &ForcedCBDTransformer{}, - - // Close opened plugin connections - &CloseProviderTransformer{}, - &CloseProvisionerTransformer{}, - - // Single root - &RootTransformer{}, - } - - if !b.DisableReduce { - // Perform the transitive reduction to make our graph a bit - // more sane if possible (it usually is possible). - steps = append(steps, &TransitiveReductionTransformer{}) - } - - return steps -} - -func (b *PlanGraphBuilder) init() { - // Do nothing if the user requests customizing the fields - if b.CustomConcrete { - return - } - - b.ConcreteProvider = func(a *NodeAbstractProvider) dag.Vertex { - return &NodeApplyableProvider{ - NodeAbstractProvider: a, - } - } - - b.ConcreteResource = func(a *NodeAbstractResource) dag.Vertex { - return &NodePlannableResource{ - NodeAbstractResource: a, - } - } - - b.ConcreteResourceOrphan = func(a *NodeAbstractResourceInstance) dag.Vertex { - return &NodePlannableResourceInstanceOrphan{ - NodeAbstractResourceInstance: a, - } - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_refresh.go deleted file mode 100644 index fad7bf161fc..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_refresh.go +++ /dev/null @@ -1,194 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// RefreshGraphBuilder implements GraphBuilder and is responsible for building -// a graph for refreshing (updating the Terraform state). -// -// The primary difference between this graph and others: -// -// * Based on the state since it represents the only resources that -// need to be refreshed. -// -// * Ignores lifecycle options since no lifecycle events occur here. This -// simplifies the graph significantly since complex transforms such as -// create-before-destroy can be completely ignored. -// -type RefreshGraphBuilder struct { - // Config is the configuration tree. - Config *configs.Config - - // State is the prior state - State *states.State - - // Components is a factory for the plug-in components (providers and - // provisioners) available for use. - Components contextComponentFactory - - // Schemas is the repository of schemas we will draw from to analyse - // the configuration. - Schemas *Schemas - - // Targets are resources to target - Targets []addrs.Targetable - - // DisableReduce, if true, will not reduce the graph. Great for testing. - DisableReduce bool - - // Validate will do structural validation of the graph. - Validate bool -} - -// See GraphBuilder -func (b *RefreshGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) { - return (&BasicGraphBuilder{ - Steps: b.Steps(), - Validate: b.Validate, - Name: "RefreshGraphBuilder", - }).Build(path) -} - -// See GraphBuilder -func (b *RefreshGraphBuilder) Steps() []GraphTransformer { - // Custom factory for creating providers. - concreteProvider := func(a *NodeAbstractProvider) dag.Vertex { - return &NodeApplyableProvider{ - NodeAbstractProvider: a, - } - } - - concreteManagedResource := func(a *NodeAbstractResource) dag.Vertex { - return &NodeRefreshableManagedResource{ - NodeAbstractResource: a, - } - } - - concreteManagedResourceInstance := func(a *NodeAbstractResourceInstance) dag.Vertex { - return &NodeRefreshableManagedResourceInstance{ - NodeAbstractResourceInstance: a, - } - } - - concreteResourceInstanceDeposed := func(a *NodeAbstractResourceInstance, key states.DeposedKey) dag.Vertex { - // The "Plan" node type also handles refreshing behavior. - return &NodePlanDeposedResourceInstanceObject{ - NodeAbstractResourceInstance: a, - DeposedKey: key, - } - } - - concreteDataResource := func(a *NodeAbstractResource) dag.Vertex { - return &NodeRefreshableDataResource{ - NodeAbstractResource: a, - } - } - - steps := []GraphTransformer{ - // 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, - Config: b.Config, - Unique: true, - ModeFilter: true, - Mode: addrs.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. This will also - // add any orphans from scaling in as destroy nodes. - &ConfigTransformer{ - Concrete: concreteDataResource, - Config: b.Config, - Unique: true, - ModeFilter: true, - Mode: addrs.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. - &OrphanResourceInstanceTransformer{ - Concrete: concreteManagedResourceInstance, - State: b.State, - Config: b.Config, - }, - - // We also need nodes for any deposed instance objects present in the - // state, so we can check if they still exist. (This intentionally - // skips creating nodes for _current_ objects, since ConfigTransformer - // created nodes that will do that during DynamicExpand.) - &StateTransformer{ - ConcreteDeposed: concreteResourceInstanceDeposed, - State: b.State, - }, - - // Attach the state - &AttachStateTransformer{State: b.State}, - - // Attach the configuration to any resources - &AttachResourceConfigTransformer{Config: b.Config}, - - // Add root variables - &RootVariableTransformer{Config: b.Config}, - - // Add the local values - &LocalTransformer{Config: b.Config}, - - // Add the outputs - &OutputTransformer{Config: b.Config}, - - // Add module variables - &ModuleVariableTransformer{Config: b.Config}, - - TransformProviders(b.Components.ResourceProviders(), concreteProvider, b.Config), - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: b.Schemas}, - - // Connect so that the references are ready for targeting. We'll - // have to connect again later for providers and so on. - &ReferenceTransformer{}, - - // Target - &TargetsTransformer{ - Targets: b.Targets, - - // Resource nodes from config have not yet been expanded for - // "count", so we must apply targeting without indices. Exact - // targeting will be dealt with later when these resources - // DynamicExpand. - IgnoreIndices: true, - }, - - // Close opened plugin connections - &CloseProviderTransformer{}, - - // Single root - &RootTransformer{}, - } - - if !b.DisableReduce { - // Perform the transitive reduction to make our graph a bit - // more sane if possible (it usually is possible). - steps = append(steps, &TransitiveReductionTransformer{}) - } - - return steps -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_validate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_validate.go deleted file mode 100644 index 0aa8b915a90..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_validate.go +++ /dev/null @@ -1,34 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// ValidateGraphBuilder creates the graph for the validate operation. -// -// ValidateGraphBuilder is based on the PlanGraphBuilder. We do this so that -// we only have to validate what we'd normally plan anyways. The -// PlanGraphBuilder given will be modified so it shouldn't be used for anything -// else after calling this function. -func ValidateGraphBuilder(p *PlanGraphBuilder) GraphBuilder { - // We're going to customize the concrete functions - p.CustomConcrete = true - - // Set the provider to the normal provider. This will ask for input. - p.ConcreteProvider = func(a *NodeAbstractProvider) dag.Vertex { - return &NodeApplyableProvider{ - NodeAbstractProvider: a, - } - } - - p.ConcreteResource = func(a *NodeAbstractResource) dag.Vertex { - return &NodeValidatableResource{ - NodeAbstractResource: a, - } - } - - // We purposely don't set any other concrete types since they don't - // require validation. - - return p -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_dot.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_dot.go deleted file mode 100644 index 5dbf415ffd4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_dot.go +++ /dev/null @@ -1,9 +0,0 @@ -package terraform - -import "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - -// GraphDot returns the dot formatting of a visual representation of -// the given Terraform graph. -func GraphDot(g *Graph, opts *dag.DotOpts) (string, error) { - return string(g.Dot(opts)), nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_interface_subgraph.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_interface_subgraph.go deleted file mode 100644 index a005ea5a0ae..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_interface_subgraph.go +++ /dev/null @@ -1,11 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// GraphNodeSubPath says that a node is part of a graph with a -// different path, and the context should be adjusted accordingly. -type GraphNodeSubPath interface { - Path() addrs.ModuleInstance -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_walk.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_walk.go deleted file mode 100644 index d699376f2f3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_walk.go +++ /dev/null @@ -1,32 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// GraphWalker is an interface that can be implemented that when used -// with Graph.Walk will invoke the given callbacks under certain events. -type GraphWalker interface { - EnterPath(addrs.ModuleInstance) EvalContext - ExitPath(addrs.ModuleInstance) - EnterVertex(dag.Vertex) - ExitVertex(dag.Vertex, tfdiags.Diagnostics) - EnterEvalTree(dag.Vertex, EvalNode) EvalNode - ExitEvalTree(dag.Vertex, interface{}, error) tfdiags.Diagnostics -} - -// NullGraphWalker is a GraphWalker implementation that does nothing. -// This can be embedded within other GraphWalker implementations for easily -// implementing all the required functions. -type NullGraphWalker struct{} - -func (NullGraphWalker) EnterPath(addrs.ModuleInstance) EvalContext { return new(MockEvalContext) } -func (NullGraphWalker) ExitPath(addrs.ModuleInstance) {} -func (NullGraphWalker) EnterVertex(dag.Vertex) {} -func (NullGraphWalker) ExitVertex(dag.Vertex, tfdiags.Diagnostics) {} -func (NullGraphWalker) EnterEvalTree(v dag.Vertex, n EvalNode) EvalNode { return n } -func (NullGraphWalker) ExitEvalTree(dag.Vertex, interface{}, error) tfdiags.Diagnostics { - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_walk_context.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_walk_context.go deleted file mode 100644 index 11fb2fd01e4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_walk_context.go +++ /dev/null @@ -1,157 +0,0 @@ -package terraform - -import ( - "context" - "log" - "sync" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// ContextGraphWalker is the GraphWalker implementation used with the -// Context struct to walk and evaluate the graph. -type ContextGraphWalker struct { - NullGraphWalker - - // Configurable values - Context *Context - State *states.SyncState // Used for safe concurrent access to state - Changes *plans.ChangesSync // Used for safe concurrent writes to changes - Operation walkOperation - StopContext context.Context - RootVariableValues InputValues - - // This is an output. Do not set this, nor read it while a graph walk - // is in progress. - NonFatalDiagnostics tfdiags.Diagnostics - - errorLock sync.Mutex - once sync.Once - contexts map[string]*BuiltinEvalContext - contextLock sync.Mutex - variableValues map[string]map[string]cty.Value - variableValuesLock sync.Mutex - providerCache map[string]providers.Interface - providerSchemas map[string]*ProviderSchema - providerLock sync.Mutex - provisionerCache map[string]provisioners.Interface - provisionerSchemas map[string]*configschema.Block - provisionerLock sync.Mutex -} - -func (w *ContextGraphWalker) EnterPath(path addrs.ModuleInstance) EvalContext { - w.once.Do(w.init) - - w.contextLock.Lock() - defer w.contextLock.Unlock() - - // If we already have a context for this path cached, use that - key := path.String() - if ctx, ok := w.contexts[key]; ok { - return ctx - } - - // Our evaluator shares some locks with the main context and the walker - // so that we can safely run multiple evaluations at once across - // different modules. - evaluator := &Evaluator{ - Meta: w.Context.meta, - Config: w.Context.config, - Operation: w.Operation, - State: w.State, - Changes: w.Changes, - Schemas: w.Context.schemas, - VariableValues: w.variableValues, - VariableValuesLock: &w.variableValuesLock, - } - - ctx := &BuiltinEvalContext{ - StopContext: w.StopContext, - PathValue: path, - Hooks: w.Context.hooks, - InputValue: w.Context.uiInput, - Components: w.Context.components, - Schemas: w.Context.schemas, - ProviderCache: w.providerCache, - ProviderInputConfig: w.Context.providerInputConfig, - ProviderLock: &w.providerLock, - ProvisionerCache: w.provisionerCache, - ProvisionerLock: &w.provisionerLock, - ChangesValue: w.Changes, - StateValue: w.State, - Evaluator: evaluator, - VariableValues: w.variableValues, - VariableValuesLock: &w.variableValuesLock, - } - - w.contexts[key] = ctx - return ctx -} - -func (w *ContextGraphWalker) EnterEvalTree(v dag.Vertex, n EvalNode) EvalNode { - log.Printf("[TRACE] [%s] Entering eval tree: %s", w.Operation, dag.VertexName(v)) - - // Acquire a lock on the semaphore - w.Context.parallelSem.Acquire() - - // We want to filter the evaluation tree to only include operations - // that belong in this operation. - return EvalFilter(n, EvalNodeFilterOp(w.Operation)) -} - -func (w *ContextGraphWalker) ExitEvalTree(v dag.Vertex, output interface{}, err error) tfdiags.Diagnostics { - log.Printf("[TRACE] [%s] Exiting eval tree: %s", w.Operation, dag.VertexName(v)) - - // Release the semaphore - w.Context.parallelSem.Release() - - if err == nil { - return nil - } - - // Acquire the lock because anything is going to require a lock. - w.errorLock.Lock() - defer w.errorLock.Unlock() - - // If the error is non-fatal then we'll accumulate its diagnostics in our - // non-fatal list, rather than returning it directly, so that the graph - // walk can continue. - if nferr, ok := err.(tfdiags.NonFatalError); ok { - log.Printf("[WARN] %s: %s", dag.VertexName(v), nferr) - w.NonFatalDiagnostics = w.NonFatalDiagnostics.Append(nferr.Diagnostics) - return nil - } - - // Otherwise, we'll let our usual diagnostics machinery figure out how to - // unpack this as one or more diagnostic messages and return that. If we - // get down here then the returned diagnostics will contain at least one - // error, causing the graph walk to halt. - var diags tfdiags.Diagnostics - diags = diags.Append(err) - return diags -} - -func (w *ContextGraphWalker) init() { - w.contexts = make(map[string]*BuiltinEvalContext) - w.providerCache = make(map[string]providers.Interface) - w.providerSchemas = make(map[string]*ProviderSchema) - w.provisionerCache = make(map[string]provisioners.Interface) - w.provisionerSchemas = make(map[string]*configschema.Block) - w.variableValues = make(map[string]map[string]cty.Value) - - // Populate root module variable values. Other modules will be populated - // during the graph walk. - w.variableValues[""] = make(map[string]cty.Value) - for k, iv := range w.RootVariableValues { - w.variableValues[""][k] = iv.Value - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_walk_operation.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_walk_operation.go deleted file mode 100644 index 859f6fb121c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_walk_operation.go +++ /dev/null @@ -1,18 +0,0 @@ -package terraform - -//go:generate go run golang.org/x/tools/cmd/stringer -type=walkOperation graph_walk_operation.go - -// walkOperation is an enum which tells the walkContext what to do. -type walkOperation byte - -const ( - walkInvalid walkOperation = iota - walkApply - walkPlan - walkPlanDestroy - walkRefresh - walkValidate - walkDestroy - walkImport - walkEval // used just to prepare EvalContext for expression evaluation, with no other actions -) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graphtype_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graphtype_string.go deleted file mode 100644 index b51e1a26617..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graphtype_string.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by "stringer -type=GraphType context_graph_type.go"; DO NOT EDIT. - -package terraform - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[GraphTypeInvalid-0] - _ = x[GraphTypeLegacy-1] - _ = x[GraphTypeRefresh-2] - _ = x[GraphTypePlan-3] - _ = x[GraphTypePlanDestroy-4] - _ = x[GraphTypeApply-5] - _ = x[GraphTypeValidate-6] - _ = x[GraphTypeEval-7] -} - -const _GraphType_name = "GraphTypeInvalidGraphTypeLegacyGraphTypeRefreshGraphTypePlanGraphTypePlanDestroyGraphTypeApplyGraphTypeValidateGraphTypeEval" - -var _GraphType_index = [...]uint8{0, 16, 31, 47, 60, 80, 94, 111, 124} - -func (i GraphType) String() string { - if i >= GraphType(len(_GraphType_index)-1) { - return "GraphType(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _GraphType_name[_GraphType_index[i]:_GraphType_index[i+1]] -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/hook.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/hook.go deleted file mode 100644 index b5be9482436..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/hook.go +++ /dev/null @@ -1,145 +0,0 @@ -package terraform - -import ( - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// HookAction is an enum of actions that can be taken as a result of a hook -// callback. This allows you to modify the behavior of Terraform at runtime. -type HookAction byte - -const ( - // HookActionContinue continues with processing as usual. - HookActionContinue HookAction = iota - - // HookActionHalt halts immediately: no more hooks are processed - // and the action that Terraform was about to take is cancelled. - HookActionHalt -) - -// Hook is the interface that must be implemented to hook into various -// parts of Terraform, allowing you to inspect or change behavior at runtime. -// -// There are MANY hook points into Terraform. If you only want to implement -// some hook points, but not all (which is the likely case), then embed the -// NilHook into your struct, which implements all of the interface but does -// nothing. Then, override only the functions you want to implement. -type Hook interface { - // PreApply and PostApply are called before and after an action for a - // single instance is applied. The error argument in PostApply is the - // error, if any, that was returned from the provider Apply call itself. - PreApply(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) - PostApply(addr addrs.AbsResourceInstance, gen states.Generation, newState cty.Value, err error) (HookAction, error) - - // PreDiff and PostDiff are called before and after a provider is given - // the opportunity to customize the proposed new state to produce the - // planned new state. - PreDiff(addr addrs.AbsResourceInstance, gen states.Generation, priorState, proposedNewState cty.Value) (HookAction, error) - PostDiff(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) - - // The provisioning hooks signal both the overall start end end of - // provisioning for a particular instance and of each of the individual - // configured provisioners for each instance. The sequence of these - // for a given instance might look something like this: - // - // PreProvisionInstance(aws_instance.foo[1], ...) - // PreProvisionInstanceStep(aws_instance.foo[1], "file") - // PostProvisionInstanceStep(aws_instance.foo[1], "file", nil) - // PreProvisionInstanceStep(aws_instance.foo[1], "remote-exec") - // ProvisionOutput(aws_instance.foo[1], "remote-exec", "Installing foo...") - // ProvisionOutput(aws_instance.foo[1], "remote-exec", "Configuring bar...") - // PostProvisionInstanceStep(aws_instance.foo[1], "remote-exec", nil) - // PostProvisionInstance(aws_instance.foo[1], ...) - // - // ProvisionOutput is called with output sent back by the provisioners. - // This will be called multiple times as output comes in, with each call - // representing one line of output. It cannot control whether the - // provisioner continues running. - PreProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) - PostProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) - PreProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string) (HookAction, error) - PostProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string, err error) (HookAction, error) - ProvisionOutput(addr addrs.AbsResourceInstance, typeName string, line string) - - // PreRefresh and PostRefresh are called before and after a single - // resource state is refreshed, respectively. - PreRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value) (HookAction, error) - PostRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value, newState cty.Value) (HookAction, error) - - // PreImportState and PostImportState are called before and after - // (respectively) each state import operation for a given resource address. - PreImportState(addr addrs.AbsResourceInstance, importID string) (HookAction, error) - PostImportState(addr addrs.AbsResourceInstance, imported []providers.ImportedResource) (HookAction, error) - - // PostStateUpdate is called each time the state is updated. It receives - // a deep copy of the state, which it may therefore access freely without - // any need for locks to protect from concurrent writes from the caller. - PostStateUpdate(new *states.State) (HookAction, error) -} - -// NilHook is a Hook implementation that does nothing. It exists only to -// simplify implementing hooks. You can embed this into your Hook implementation -// and only implement the functions you are interested in. -type NilHook struct{} - -var _ Hook = (*NilHook)(nil) - -func (*NilHook) PreApply(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) PostApply(addr addrs.AbsResourceInstance, gen states.Generation, newState cty.Value, err error) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) PreDiff(addr addrs.AbsResourceInstance, gen states.Generation, priorState, proposedNewState cty.Value) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) PostDiff(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) PreProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) PostProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) PreProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) PostProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string, err error) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) ProvisionOutput(addr addrs.AbsResourceInstance, typeName string, line string) { -} - -func (*NilHook) PreRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) PostRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value, newState cty.Value) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) PreImportState(addr addrs.AbsResourceInstance, importID string) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) PostImportState(addr addrs.AbsResourceInstance, imported []providers.ImportedResource) (HookAction, error) { - return HookActionContinue, nil -} - -func (*NilHook) PostStateUpdate(new *states.State) (HookAction, error) { - return HookActionContinue, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/hook_mock.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/hook_mock.go deleted file mode 100644 index 74a29bde0e6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/hook_mock.go +++ /dev/null @@ -1,274 +0,0 @@ -package terraform - -import ( - "sync" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// MockHook is an implementation of Hook that can be used for tests. -// It records all of its function calls. -type MockHook struct { - sync.Mutex - - PreApplyCalled bool - PreApplyAddr addrs.AbsResourceInstance - PreApplyGen states.Generation - PreApplyAction plans.Action - PreApplyPriorState cty.Value - PreApplyPlannedState cty.Value - PreApplyReturn HookAction - PreApplyError error - - PostApplyCalled bool - PostApplyAddr addrs.AbsResourceInstance - PostApplyGen states.Generation - PostApplyNewState cty.Value - PostApplyError error - PostApplyReturn HookAction - PostApplyReturnError error - PostApplyFn func(addrs.AbsResourceInstance, states.Generation, cty.Value, error) (HookAction, error) - - PreDiffCalled bool - PreDiffAddr addrs.AbsResourceInstance - PreDiffGen states.Generation - PreDiffPriorState cty.Value - PreDiffProposedState cty.Value - PreDiffReturn HookAction - PreDiffError error - - PostDiffCalled bool - PostDiffAddr addrs.AbsResourceInstance - PostDiffGen states.Generation - PostDiffAction plans.Action - PostDiffPriorState cty.Value - PostDiffPlannedState cty.Value - PostDiffReturn HookAction - PostDiffError error - - PreProvisionInstanceCalled bool - PreProvisionInstanceAddr addrs.AbsResourceInstance - PreProvisionInstanceState cty.Value - PreProvisionInstanceReturn HookAction - PreProvisionInstanceError error - - PostProvisionInstanceCalled bool - PostProvisionInstanceAddr addrs.AbsResourceInstance - PostProvisionInstanceState cty.Value - PostProvisionInstanceReturn HookAction - PostProvisionInstanceError error - - PreProvisionInstanceStepCalled bool - PreProvisionInstanceStepAddr addrs.AbsResourceInstance - PreProvisionInstanceStepProvisionerType string - PreProvisionInstanceStepReturn HookAction - PreProvisionInstanceStepError error - - PostProvisionInstanceStepCalled bool - PostProvisionInstanceStepAddr addrs.AbsResourceInstance - PostProvisionInstanceStepProvisionerType string - PostProvisionInstanceStepErrorArg error - PostProvisionInstanceStepReturn HookAction - PostProvisionInstanceStepError error - - ProvisionOutputCalled bool - ProvisionOutputAddr addrs.AbsResourceInstance - ProvisionOutputProvisionerType string - ProvisionOutputMessage string - - PreRefreshCalled bool - PreRefreshAddr addrs.AbsResourceInstance - PreRefreshGen states.Generation - PreRefreshPriorState cty.Value - PreRefreshReturn HookAction - PreRefreshError error - - PostRefreshCalled bool - PostRefreshAddr addrs.AbsResourceInstance - PostRefreshGen states.Generation - PostRefreshPriorState cty.Value - PostRefreshNewState cty.Value - PostRefreshReturn HookAction - PostRefreshError error - - PreImportStateCalled bool - PreImportStateAddr addrs.AbsResourceInstance - PreImportStateID string - PreImportStateReturn HookAction - PreImportStateError error - - PostImportStateCalled bool - PostImportStateAddr addrs.AbsResourceInstance - PostImportStateNewStates []providers.ImportedResource - PostImportStateReturn HookAction - PostImportStateError error - - PostStateUpdateCalled bool - PostStateUpdateState *states.State - PostStateUpdateReturn HookAction - PostStateUpdateError error -} - -var _ Hook = (*MockHook)(nil) - -func (h *MockHook) PreApply(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PreApplyCalled = true - h.PreApplyAddr = addr - h.PreApplyGen = gen - h.PreApplyAction = action - h.PreApplyPriorState = priorState - h.PreApplyPlannedState = plannedNewState - return h.PreApplyReturn, h.PreApplyError -} - -func (h *MockHook) PostApply(addr addrs.AbsResourceInstance, gen states.Generation, newState cty.Value, err error) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PostApplyCalled = true - h.PostApplyAddr = addr - h.PostApplyGen = gen - h.PostApplyNewState = newState - h.PostApplyError = err - - if h.PostApplyFn != nil { - return h.PostApplyFn(addr, gen, newState, err) - } - - return h.PostApplyReturn, h.PostApplyReturnError -} - -func (h *MockHook) PreDiff(addr addrs.AbsResourceInstance, gen states.Generation, priorState, proposedNewState cty.Value) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PreDiffCalled = true - h.PreDiffAddr = addr - h.PreDiffGen = gen - h.PreDiffPriorState = priorState - h.PreDiffProposedState = proposedNewState - return h.PreDiffReturn, h.PreDiffError -} - -func (h *MockHook) PostDiff(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PostDiffCalled = true - h.PostDiffAddr = addr - h.PostDiffGen = gen - h.PostDiffAction = action - h.PostDiffPriorState = priorState - h.PostDiffPlannedState = plannedNewState - return h.PostDiffReturn, h.PostDiffError -} - -func (h *MockHook) PreProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PreProvisionInstanceCalled = true - h.PreProvisionInstanceAddr = addr - h.PreProvisionInstanceState = state - return h.PreProvisionInstanceReturn, h.PreProvisionInstanceError -} - -func (h *MockHook) PostProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PostProvisionInstanceCalled = true - h.PostProvisionInstanceAddr = addr - h.PostProvisionInstanceState = state - return h.PostProvisionInstanceReturn, h.PostProvisionInstanceError -} - -func (h *MockHook) PreProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PreProvisionInstanceStepCalled = true - h.PreProvisionInstanceStepAddr = addr - h.PreProvisionInstanceStepProvisionerType = typeName - return h.PreProvisionInstanceStepReturn, h.PreProvisionInstanceStepError -} - -func (h *MockHook) PostProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string, err error) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PostProvisionInstanceStepCalled = true - h.PostProvisionInstanceStepAddr = addr - h.PostProvisionInstanceStepProvisionerType = typeName - h.PostProvisionInstanceStepErrorArg = err - return h.PostProvisionInstanceStepReturn, h.PostProvisionInstanceStepError -} - -func (h *MockHook) ProvisionOutput(addr addrs.AbsResourceInstance, typeName string, line string) { - h.Lock() - defer h.Unlock() - - h.ProvisionOutputCalled = true - h.ProvisionOutputAddr = addr - h.ProvisionOutputProvisionerType = typeName - h.ProvisionOutputMessage = line -} - -func (h *MockHook) PreRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PreRefreshCalled = true - h.PreRefreshAddr = addr - h.PreRefreshGen = gen - h.PreRefreshPriorState = priorState - return h.PreRefreshReturn, h.PreRefreshError -} - -func (h *MockHook) PostRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value, newState cty.Value) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PostRefreshCalled = true - h.PostRefreshAddr = addr - h.PostRefreshPriorState = priorState - h.PostRefreshNewState = newState - return h.PostRefreshReturn, h.PostRefreshError -} - -func (h *MockHook) PreImportState(addr addrs.AbsResourceInstance, importID string) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PreImportStateCalled = true - h.PreImportStateAddr = addr - h.PreImportStateID = importID - return h.PreImportStateReturn, h.PreImportStateError -} - -func (h *MockHook) PostImportState(addr addrs.AbsResourceInstance, imported []providers.ImportedResource) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PostImportStateCalled = true - h.PostImportStateAddr = addr - h.PostImportStateNewStates = imported - return h.PostImportStateReturn, h.PostImportStateError -} - -func (h *MockHook) PostStateUpdate(new *states.State) (HookAction, error) { - h.Lock() - defer h.Unlock() - - h.PostStateUpdateCalled = true - h.PostStateUpdateState = new - return h.PostStateUpdateReturn, h.PostStateUpdateError -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/hook_stop.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/hook_stop.go deleted file mode 100644 index 42c3d20cb94..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/hook_stop.go +++ /dev/null @@ -1,100 +0,0 @@ -package terraform - -import ( - "sync/atomic" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// stopHook is a private Hook implementation that Terraform uses to -// signal when to stop or cancel actions. -type stopHook struct { - stop uint32 -} - -var _ Hook = (*stopHook)(nil) - -func (h *stopHook) PreApply(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) PostApply(addr addrs.AbsResourceInstance, gen states.Generation, newState cty.Value, err error) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) PreDiff(addr addrs.AbsResourceInstance, gen states.Generation, priorState, proposedNewState cty.Value) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) PostDiff(addr addrs.AbsResourceInstance, gen states.Generation, action plans.Action, priorState, plannedNewState cty.Value) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) PreProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) PostProvisionInstance(addr addrs.AbsResourceInstance, state cty.Value) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) PreProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) PostProvisionInstanceStep(addr addrs.AbsResourceInstance, typeName string, err error) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) ProvisionOutput(addr addrs.AbsResourceInstance, typeName string, line string) { -} - -func (h *stopHook) PreRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) PostRefresh(addr addrs.AbsResourceInstance, gen states.Generation, priorState cty.Value, newState cty.Value) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) PreImportState(addr addrs.AbsResourceInstance, importID string) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) PostImportState(addr addrs.AbsResourceInstance, imported []providers.ImportedResource) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) PostStateUpdate(new *states.State) (HookAction, error) { - return h.hook() -} - -func (h *stopHook) hook() (HookAction, error) { - if h.Stopped() { - // FIXME: This should really return an error since stopping partway - // through is not a successful run-to-completion, but we'll need to - // introduce that cautiously since existing automation solutions may - // be depending on this behavior. - return HookActionHalt, nil - } - - return HookActionContinue, nil -} - -// reset should be called within the lock context -func (h *stopHook) Reset() { - atomic.StoreUint32(&h.stop, 0) -} - -func (h *stopHook) Stop() { - atomic.StoreUint32(&h.stop, 1) -} - -func (h *stopHook) Stopped() bool { - return atomic.LoadUint32(&h.stop) == 1 -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/instancetype.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/instancetype.go deleted file mode 100644 index 375a8638a88..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/instancetype.go +++ /dev/null @@ -1,13 +0,0 @@ -package terraform - -//go:generate go run golang.org/x/tools/cmd/stringer -type=InstanceType instancetype.go - -// InstanceType is an enum of the various types of instances store in the State -type InstanceType int - -const ( - TypeInvalid InstanceType = iota - TypePrimary - TypeTainted - TypeDeposed -) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/instancetype_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/instancetype_string.go deleted file mode 100644 index 95b7a9802e5..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/instancetype_string.go +++ /dev/null @@ -1,26 +0,0 @@ -// Code generated by "stringer -type=InstanceType instancetype.go"; DO NOT EDIT. - -package terraform - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[TypeInvalid-0] - _ = x[TypePrimary-1] - _ = x[TypeTainted-2] - _ = x[TypeDeposed-3] -} - -const _InstanceType_name = "TypeInvalidTypePrimaryTypeTaintedTypeDeposed" - -var _InstanceType_index = [...]uint8{0, 11, 22, 33, 44} - -func (i InstanceType) String() string { - if i < 0 || i >= InstanceType(len(_InstanceType_index)-1) { - return "InstanceType(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _InstanceType_name[_InstanceType_index[i]:_InstanceType_index[i+1]] -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/module_dependencies.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/module_dependencies.go deleted file mode 100644 index f1434e62520..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/module_dependencies.go +++ /dev/null @@ -1,202 +0,0 @@ -package terraform - -import ( - version "github.com/hashicorp/go-version" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/moduledeps" - "github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// ConfigTreeDependencies returns the dependencies of the tree of modules -// described by the given configuration and state. -// -// Both configuration and state are required because there can be resources -// implied by instances in the state that no longer exist in config. -func ConfigTreeDependencies(root *configs.Config, state *states.State) *moduledeps.Module { - // First we walk the configuration tree to build the overall structure - // and capture the explicit/implicit/inherited provider dependencies. - deps := configTreeConfigDependencies(root, nil) - - // Next we walk over the resources in the state to catch any additional - // dependencies created by existing resources that are no longer in config. - // Most things we find in state will already be present in 'deps', but - // we're interested in the rare thing that isn't. - configTreeMergeStateDependencies(deps, state) - - return deps -} - -func configTreeConfigDependencies(root *configs.Config, inheritProviders map[string]*configs.Provider) *moduledeps.Module { - if root == nil { - // If no config is provided, we'll make a synthetic root. - // This isn't necessarily correct if we're called with a nil that - // *isn't* at the root, but in practice that can never happen. - return &moduledeps.Module{ - Name: "root", - Providers: make(moduledeps.Providers), - } - } - - name := "root" - if len(root.Path) != 0 { - name = root.Path[len(root.Path)-1] - } - - ret := &moduledeps.Module{ - Name: name, - } - - module := root.Module - - // Provider dependencies - { - providers := make(moduledeps.Providers) - - // The main way to declare a provider dependency is explicitly inside - // the "terraform" block, which allows declaring a requirement without - // also creating a configuration. - for fullName, constraints := range module.ProviderRequirements { - inst := moduledeps.ProviderInstance(fullName) - - // The handling here is a bit fiddly because the moduledeps package - // was designed around the legacy (pre-0.12) configuration model - // and hasn't yet been revised to handle the new model. As a result, - // we need to do some translation here. - // FIXME: Eventually we should adjust the underlying model so we - // can also retain the source location of each constraint, for - // more informative output from the "terraform providers" command. - var rawConstraints version.Constraints - for _, constraint := range constraints { - rawConstraints = append(rawConstraints, constraint.Required...) - } - discoConstraints := discovery.NewConstraints(rawConstraints) - - providers[inst] = moduledeps.ProviderDependency{ - Constraints: discoConstraints, - Reason: moduledeps.ProviderDependencyExplicit, - } - } - - // Provider configurations can also include version constraints, - // allowing for more terse declaration in situations where both a - // configuration and a constraint are defined in the same module. - for fullName, pCfg := range module.ProviderConfigs { - inst := moduledeps.ProviderInstance(fullName) - discoConstraints := discovery.AllVersions - if pCfg.Version.Required != nil { - discoConstraints = discovery.NewConstraints(pCfg.Version.Required) - } - if existing, exists := providers[inst]; exists { - existing.Constraints = existing.Constraints.Append(discoConstraints) - } else { - providers[inst] = moduledeps.ProviderDependency{ - Constraints: discoConstraints, - Reason: moduledeps.ProviderDependencyExplicit, - } - } - } - - // Each resource in the configuration creates an *implicit* provider - // dependency, though we'll only record it if there isn't already - // an explicit dependency on the same provider. - for _, rc := range module.ManagedResources { - addr := rc.ProviderConfigAddr() - inst := moduledeps.ProviderInstance(addr.StringCompact()) - if _, exists := providers[inst]; exists { - // Explicit dependency already present - continue - } - - reason := moduledeps.ProviderDependencyImplicit - if _, inherited := inheritProviders[addr.StringCompact()]; inherited { - reason = moduledeps.ProviderDependencyInherited - } - - providers[inst] = moduledeps.ProviderDependency{ - Constraints: discovery.AllVersions, - Reason: reason, - } - } - for _, rc := range module.DataResources { - addr := rc.ProviderConfigAddr() - inst := moduledeps.ProviderInstance(addr.StringCompact()) - if _, exists := providers[inst]; exists { - // Explicit dependency already present - continue - } - - reason := moduledeps.ProviderDependencyImplicit - if _, inherited := inheritProviders[addr.String()]; inherited { - reason = moduledeps.ProviderDependencyInherited - } - - providers[inst] = moduledeps.ProviderDependency{ - Constraints: discovery.AllVersions, - Reason: reason, - } - } - - ret.Providers = providers - } - - childInherit := make(map[string]*configs.Provider) - for k, v := range inheritProviders { - childInherit[k] = v - } - for k, v := range module.ProviderConfigs { - childInherit[k] = v - } - for _, c := range root.Children { - ret.Children = append(ret.Children, configTreeConfigDependencies(c, childInherit)) - } - - return ret -} - -func configTreeMergeStateDependencies(root *moduledeps.Module, state *states.State) { - if state == nil { - return - } - - findModule := func(path addrs.ModuleInstance) *moduledeps.Module { - module := root - for _, step := range path { - var next *moduledeps.Module - for _, cm := range module.Children { - if cm.Name == step.Name { - next = cm - break - } - } - - if next == nil { - // If we didn't find a next node, we'll need to make one - next = &moduledeps.Module{ - Name: step.Name, - Providers: make(moduledeps.Providers), - } - module.Children = append(module.Children, next) - } - - module = next - } - return module - } - - for _, ms := range state.Modules { - module := findModule(ms.Addr) - - for _, rs := range ms.Resources { - inst := moduledeps.ProviderInstance(rs.ProviderConfig.ProviderConfig.StringCompact()) - if _, exists := module.Providers[inst]; !exists { - module.Providers[inst] = moduledeps.ProviderDependency{ - Constraints: discovery.AllVersions, - Reason: moduledeps.ProviderDependencyFromState, - } - } - } - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_count_boundary.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_count_boundary.go deleted file mode 100644 index acd8262b066..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_count_boundary.go +++ /dev/null @@ -1,22 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" -) - -// NodeCountBoundary fixes up any transitions between "each modes" in objects -// saved in state, such as switching from NoEach to EachInt. -type NodeCountBoundary struct { - Config *configs.Config -} - -func (n *NodeCountBoundary) Name() string { - return "meta.count-boundary (EachMode fixup)" -} - -// GraphNodeEvalable -func (n *NodeCountBoundary) EvalTree() EvalNode { - return &EvalCountFixZeroOneBoundaryGlobal{ - Config: n.Config, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_destroy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_destroy.go deleted file mode 100644 index 56a33bce2c6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_destroy.go +++ /dev/null @@ -1,40 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// NodeDestroyableDataResourceInstance represents a resource that is "destroyable": -// it is ready to be destroyed. -type NodeDestroyableDataResourceInstance struct { - *NodeAbstractResourceInstance -} - -// GraphNodeEvalable -func (n *NodeDestroyableDataResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - var providerSchema *ProviderSchema - // We don't need the provider, but we're calling EvalGetProvider to load the - // schema. - var provider providers.Interface - - // Just destroy it. - var state *states.ResourceInstanceObject - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalWriteState{ - Addr: addr.Resource, - State: &state, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_refresh.go deleted file mode 100644 index 56283c0ac39..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_refresh.go +++ /dev/null @@ -1,229 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" -) - -// NodeRefreshableDataResource represents a resource that is "refreshable". -type NodeRefreshableDataResource struct { - *NodeAbstractResource -} - -var ( - _ GraphNodeSubPath = (*NodeRefreshableDataResource)(nil) - _ GraphNodeDynamicExpandable = (*NodeRefreshableDataResource)(nil) - _ GraphNodeReferenceable = (*NodeRefreshableDataResource)(nil) - _ GraphNodeReferencer = (*NodeRefreshableDataResource)(nil) - _ GraphNodeResource = (*NodeRefreshableDataResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodeRefreshableDataResource)(nil) -) - -// GraphNodeDynamicExpandable -func (n *NodeRefreshableDataResource) DynamicExpand(ctx EvalContext) (*Graph, error) { - var diags tfdiags.Diagnostics - - count, countKnown, countDiags := evaluateResourceCountExpressionKnown(n.Config.Count, ctx) - diags = diags.Append(countDiags) - if countDiags.HasErrors() { - return nil, diags.Err() - } - if !countKnown { - // If the count isn't known yet, we'll skip refreshing and try expansion - // again during the plan walk. - return nil, nil - } - - forEachMap, forEachKnown, forEachDiags := evaluateResourceForEachExpressionKnown(n.Config.ForEach, ctx) - diags = diags.Append(forEachDiags) - if forEachDiags.HasErrors() { - return nil, diags.Err() - } - if !forEachKnown { - // If the for_each isn't known yet, we'll skip refreshing and try expansion - // again during the plan walk. - return nil, nil - } - - // Next we need to potentially rename an instance address in the state - // if we're transitioning whether "count" is set at all. - fixResourceCountSetTransition(ctx, n.ResourceAddr(), count != -1) - - // Our graph transformers require access to the full state, so we'll - // temporarily lock it while we work on this. - state := ctx.State().Lock() - defer ctx.State().Unlock() - - // The concrete resource factory we'll use - concreteResource := func(a *NodeAbstractResourceInstance) dag.Vertex { - // Add the config and state since we don't do that via transforms - a.Config = n.Config - a.ResolvedProvider = n.ResolvedProvider - - return &NodeRefreshableDataResourceInstance{ - NodeAbstractResourceInstance: a, - } - } - - // We also need a destroyable resource for orphans that are a result of a - // scaled-in count. - concreteResourceDestroyable := func(a *NodeAbstractResourceInstance) dag.Vertex { - // Add the config and provider since we don't do that via transforms - a.Config = n.Config - a.ResolvedProvider = n.ResolvedProvider - - return &NodeDestroyableDataResourceInstance{ - NodeAbstractResourceInstance: a, - } - } - - // Start creating the steps - steps := []GraphTransformer{ - // Expand the count. - &ResourceCountTransformer{ - Concrete: concreteResource, - Schema: n.Schema, - Count: count, - ForEach: forEachMap, - Addr: n.ResourceAddr(), - }, - - // Add the count orphans. As these are orphaned refresh nodes, we add them - // directly as NodeDestroyableDataResource. - &OrphanResourceCountTransformer{ - Concrete: concreteResourceDestroyable, - Count: count, - ForEach: forEachMap, - Addr: n.ResourceAddr(), - State: state, - }, - - // Attach the state - &AttachStateTransformer{State: state}, - - // Targeting - &TargetsTransformer{Targets: n.Targets}, - - // Connect references so ordering is correct - &ReferenceTransformer{}, - - // Make sure there is a single root - &RootTransformer{}, - } - - // Build the graph - b := &BasicGraphBuilder{ - Steps: steps, - Validate: true, - Name: "NodeRefreshableDataResource", - } - - graph, diags := b.Build(ctx.Path()) - return graph, diags.ErrWithWarnings() -} - -// NodeRefreshableDataResourceInstance represents a single resource instance -// that is refreshable. -type NodeRefreshableDataResourceInstance struct { - *NodeAbstractResourceInstance -} - -// GraphNodeEvalable -func (n *NodeRefreshableDataResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - // These variables are the state for the eval sequence below, and are - // updated through pointers. - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - var configVal cty.Value - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - - // Always destroy the existing state first, since we must - // make sure that values from a previous read will not - // get interpolated if we end up needing to defer our - // loading until apply time. - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, // a pointer to nil, here - ProviderSchema: &providerSchema, - }, - - // EvalReadData will _attempt_ to read the data source, but may - // generate an incomplete planned object if the configuration - // includes values that won't be known until apply. - &EvalReadData{ - Addr: addr.Resource, - Config: n.Config, - Dependencies: n.StateReferences(), - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - OutputChange: &change, - OutputConfigValue: &configVal, - OutputState: &state, - // If the config explicitly has a depends_on for this data - // source, assume the intention is to prevent refreshing ahead - // of that dependency, and therefore we need to deal with this - // resource during the apply phase. We do that by forcing this - // read to result in a plan. - ForcePlanRead: len(n.Config.DependsOn) > 0, - }, - - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - return (*state).Status != states.ObjectPlanned, nil - }, - Then: &EvalSequence{ - Nodes: []EvalNode{ - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, - ProviderSchema: &providerSchema, - }, - &EvalUpdateStateHook{}, - }, - }, - Else: &EvalSequence{ - // We can't deal with this yet, so we'll repeat this step - // during the plan walk to produce a planned change to read - // this during the apply walk. However, we do still need to - // save the generated change and partial state so that - // results from it can be included in other data resources - // or provider configurations during the refresh walk. - // (The planned object we save in the state here will be - // pruned out at the end of the refresh walk, returning - // it back to being unset again for subsequent walks.) - Nodes: []EvalNode{ - &EvalWriteDiff{ - Addr: addr.Resource, - Change: &change, - ProviderSchema: &providerSchema, - }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, - ProviderSchema: &providerSchema, - }, - }, - }, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_local.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_local.go deleted file mode 100644 index 38681d83dbb..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_local.go +++ /dev/null @@ -1,70 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" -) - -// NodeLocal represents a named local value in a particular module. -// -// Local value nodes only have one operation, common to all walk types: -// evaluate the result and place it in state. -type NodeLocal struct { - Addr addrs.AbsLocalValue - Config *configs.Local -} - -var ( - _ GraphNodeSubPath = (*NodeLocal)(nil) - _ RemovableIfNotTargeted = (*NodeLocal)(nil) - _ GraphNodeReferenceable = (*NodeLocal)(nil) - _ GraphNodeReferencer = (*NodeLocal)(nil) - _ GraphNodeEvalable = (*NodeLocal)(nil) - _ dag.GraphNodeDotter = (*NodeLocal)(nil) -) - -func (n *NodeLocal) Name() string { - return n.Addr.String() -} - -// GraphNodeSubPath -func (n *NodeLocal) Path() addrs.ModuleInstance { - return n.Addr.Module -} - -// RemovableIfNotTargeted -func (n *NodeLocal) RemoveIfNotTargeted() bool { - return true -} - -// GraphNodeReferenceable -func (n *NodeLocal) ReferenceableAddrs() []addrs.Referenceable { - return []addrs.Referenceable{n.Addr.LocalValue} -} - -// GraphNodeReferencer -func (n *NodeLocal) References() []*addrs.Reference { - refs, _ := lang.ReferencesInExpr(n.Config.Expr) - return appendResourceDestroyReferences(refs) -} - -// GraphNodeEvalable -func (n *NodeLocal) EvalTree() EvalNode { - return &EvalLocal{ - Addr: n.Addr.LocalValue, - Expr: n.Config.Expr, - } -} - -// dag.GraphNodeDotter impl. -func (n *NodeLocal) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "note", - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_module_removed.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_module_removed.go deleted file mode 100644 index 6e3cb41dc22..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_module_removed.go +++ /dev/null @@ -1,89 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// NodeModuleRemoved represents a module that is no longer in the -// config. -type NodeModuleRemoved struct { - Addr addrs.ModuleInstance -} - -var ( - _ GraphNodeSubPath = (*NodeModuleRemoved)(nil) - _ RemovableIfNotTargeted = (*NodeModuleRemoved)(nil) - _ GraphNodeEvalable = (*NodeModuleRemoved)(nil) - _ GraphNodeReferencer = (*NodeModuleRemoved)(nil) - _ GraphNodeReferenceOutside = (*NodeModuleRemoved)(nil) -) - -func (n *NodeModuleRemoved) Name() string { - return fmt.Sprintf("%s (removed)", n.Addr.String()) -} - -// GraphNodeSubPath -func (n *NodeModuleRemoved) Path() addrs.ModuleInstance { - return n.Addr -} - -// GraphNodeEvalable -func (n *NodeModuleRemoved) EvalTree() EvalNode { - return &EvalOpFilter{ - Ops: []walkOperation{walkRefresh, walkApply, walkDestroy}, - Node: &EvalCheckModuleRemoved{ - Addr: n.Addr, - }, - } -} - -func (n *NodeModuleRemoved) ReferenceOutside() (selfPath, referencePath addrs.ModuleInstance) { - // Our "References" implementation indicates that this node depends on - // the call to the module it represents, which implicitly depends on - // everything inside the module. That reference must therefore be - // interpreted in terms of our parent module. - return n.Addr, n.Addr.Parent() -} - -func (n *NodeModuleRemoved) References() []*addrs.Reference { - // We depend on the call to the module we represent, because that - // implicitly then depends on everything inside that module. - // Our ReferenceOutside implementation causes this to be interpreted - // within the parent module. - - _, call := n.Addr.CallInstance() - return []*addrs.Reference{ - { - Subject: call, - - // No source range here, because there's nothing reasonable for - // us to return. - }, - } -} - -// RemovableIfNotTargeted -func (n *NodeModuleRemoved) RemoveIfNotTargeted() bool { - // We need to add this so that this node will be removed if - // it isn't targeted or a dependency of a target. - return true -} - -// EvalCheckModuleRemoved is an EvalNode implementation that verifies that -// a module has been removed from the state as expected. -type EvalCheckModuleRemoved struct { - Addr addrs.ModuleInstance -} - -func (n *EvalCheckModuleRemoved) Eval(ctx EvalContext) (interface{}, error) { - mod := ctx.State().Module(n.Addr) - if mod != nil { - // If we get here then that indicates a bug either in the states - // module or in an earlier step of the graph walk, since we should've - // pruned out the module when the last resource was removed from it. - return nil, fmt.Errorf("leftover module %s in state that should have been removed; this is a bug in Terraform and should be reported", n.Addr) - } - return nil, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_module_variable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_module_variable.go deleted file mode 100644 index 76311a56d3d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_module_variable.go +++ /dev/null @@ -1,142 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" - "github.com/zclconf/go-cty/cty" -) - -// NodeApplyableModuleVariable represents a module variable input during -// the apply step. -type NodeApplyableModuleVariable struct { - Addr addrs.AbsInputVariableInstance - Config *configs.Variable // Config is the var in the config - Expr hcl.Expression // Expr is the value expression given in the call -} - -// Ensure that we are implementing all of the interfaces we think we are -// implementing. -var ( - _ GraphNodeSubPath = (*NodeApplyableModuleVariable)(nil) - _ RemovableIfNotTargeted = (*NodeApplyableModuleVariable)(nil) - _ GraphNodeReferenceOutside = (*NodeApplyableModuleVariable)(nil) - _ GraphNodeReferenceable = (*NodeApplyableModuleVariable)(nil) - _ GraphNodeReferencer = (*NodeApplyableModuleVariable)(nil) - _ GraphNodeEvalable = (*NodeApplyableModuleVariable)(nil) - _ dag.GraphNodeDotter = (*NodeApplyableModuleVariable)(nil) -) - -func (n *NodeApplyableModuleVariable) Name() string { - return n.Addr.String() -} - -// GraphNodeSubPath -func (n *NodeApplyableModuleVariable) Path() addrs.ModuleInstance { - // We execute in the parent scope (above our own module) because - // expressions in our value are resolved in that context. - return n.Addr.Module.Parent() -} - -// RemovableIfNotTargeted -func (n *NodeApplyableModuleVariable) RemoveIfNotTargeted() bool { - // We need to add this so that this node will be removed if - // it isn't targeted or a dependency of a target. - return true -} - -// GraphNodeReferenceOutside implementation -func (n *NodeApplyableModuleVariable) ReferenceOutside() (selfPath, referencePath addrs.ModuleInstance) { - - // Module input variables have their value expressions defined in the - // context of their calling (parent) module, and so references from - // a node of this type should be resolved in the parent module instance. - referencePath = n.Addr.Module.Parent() - - // Input variables are _referenced_ from their own module, though. - selfPath = n.Addr.Module - - return // uses named return values -} - -// GraphNodeReferenceable -func (n *NodeApplyableModuleVariable) ReferenceableAddrs() []addrs.Referenceable { - return []addrs.Referenceable{n.Addr.Variable} -} - -// GraphNodeReferencer -func (n *NodeApplyableModuleVariable) References() []*addrs.Reference { - - // If we have no value expression, we cannot depend on anything. - if n.Expr == nil { - return nil - } - - // Variables in the root don't depend on anything, because their values - // are gathered prior to the graph walk and recorded in the context. - if len(n.Addr.Module) == 0 { - return nil - } - - // Otherwise, we depend on anything referenced by our value expression. - // We ignore diagnostics here under the assumption that we'll re-eval - // all these things later and catch them then; for our purposes here, - // we only care about valid references. - // - // Due to our GraphNodeReferenceOutside implementation, the addresses - // returned by this function are interpreted in the _parent_ module from - // where our associated variable was declared, which is correct because - // our value expression is assigned within a "module" block in the parent - // module. - refs, _ := lang.ReferencesInExpr(n.Expr) - return refs -} - -// GraphNodeEvalable -func (n *NodeApplyableModuleVariable) EvalTree() EvalNode { - // If we have no value, do nothing - if n.Expr == nil { - return &EvalNoop{} - } - - // Otherwise, interpolate the value of this variable and set it - // within the variables mapping. - vals := make(map[string]cty.Value) - - _, call := n.Addr.Module.CallInstance() - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalOpFilter{ - Ops: []walkOperation{walkRefresh, walkPlan, walkApply, - walkDestroy, walkValidate}, - Node: &EvalModuleCallArgument{ - Addr: n.Addr.Variable, - Config: n.Config, - Expr: n.Expr, - Values: vals, - - IgnoreDiagnostics: false, - }, - }, - - &EvalSetModuleCallArguments{ - Module: call, - Values: vals, - }, - }, - } -} - -// dag.GraphNodeDotter impl. -func (n *NodeApplyableModuleVariable) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "note", - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_output.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_output.go deleted file mode 100644 index 7530571234d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_output.go +++ /dev/null @@ -1,200 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" -) - -// NodeApplyableOutput represents an output that is "applyable": -// it is ready to be applied. -type NodeApplyableOutput struct { - Addr addrs.AbsOutputValue - Config *configs.Output // Config is the output in the config -} - -var ( - _ GraphNodeSubPath = (*NodeApplyableOutput)(nil) - _ RemovableIfNotTargeted = (*NodeApplyableOutput)(nil) - _ GraphNodeTargetDownstream = (*NodeApplyableOutput)(nil) - _ GraphNodeReferenceable = (*NodeApplyableOutput)(nil) - _ GraphNodeReferencer = (*NodeApplyableOutput)(nil) - _ GraphNodeReferenceOutside = (*NodeApplyableOutput)(nil) - _ GraphNodeEvalable = (*NodeApplyableOutput)(nil) - _ dag.GraphNodeDotter = (*NodeApplyableOutput)(nil) -) - -func (n *NodeApplyableOutput) Name() string { - return n.Addr.String() -} - -// GraphNodeSubPath -func (n *NodeApplyableOutput) Path() addrs.ModuleInstance { - return n.Addr.Module -} - -// RemovableIfNotTargeted -func (n *NodeApplyableOutput) RemoveIfNotTargeted() bool { - // We need to add this so that this node will be removed if - // it isn't targeted or a dependency of a target. - return true -} - -// 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 -} - -func referenceOutsideForOutput(addr addrs.AbsOutputValue) (selfPath, referencePath addrs.ModuleInstance) { - - // Output values have their expressions resolved in the context of the - // module where they are defined. - referencePath = addr.Module - - // ...but they are referenced in the context of their calling module. - selfPath = addr.Module.Parent() - - return // uses named return values - -} - -// GraphNodeReferenceOutside implementation -func (n *NodeApplyableOutput) ReferenceOutside() (selfPath, referencePath addrs.ModuleInstance) { - return referenceOutsideForOutput(n.Addr) -} - -func referenceableAddrsForOutput(addr addrs.AbsOutputValue) []addrs.Referenceable { - // An output in the root module can't be referenced at all. - if addr.Module.IsRoot() { - return nil - } - - // Otherwise, we can be referenced via a reference to our output name - // on the parent module's call, or via a reference to the entire call. - // e.g. module.foo.bar or just module.foo . - // Note that our ReferenceOutside method causes these addresses to be - // relative to the calling module, not the module where the output - // was declared. - _, outp := addr.ModuleCallOutput() - _, call := addr.Module.CallInstance() - return []addrs.Referenceable{outp, call} - -} - -// GraphNodeReferenceable -func (n *NodeApplyableOutput) ReferenceableAddrs() []addrs.Referenceable { - return referenceableAddrsForOutput(n.Addr) -} - -func referencesForOutput(c *configs.Output) []*addrs.Reference { - impRefs, _ := lang.ReferencesInExpr(c.Expr) - expRefs, _ := lang.References(c.DependsOn) - l := len(impRefs) + len(expRefs) - if l == 0 { - return nil - } - refs := make([]*addrs.Reference, 0, l) - refs = append(refs, impRefs...) - refs = append(refs, expRefs...) - return refs - -} - -// GraphNodeReferencer -func (n *NodeApplyableOutput) References() []*addrs.Reference { - return appendResourceDestroyReferences(referencesForOutput(n.Config)) -} - -// GraphNodeEvalable -func (n *NodeApplyableOutput) EvalTree() EvalNode { - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalOpFilter{ - Ops: []walkOperation{walkRefresh, walkPlan, walkApply, walkValidate, walkDestroy, walkPlanDestroy}, - Node: &EvalWriteOutput{ - Addr: n.Addr.OutputValue, - Sensitive: n.Config.Sensitive, - Expr: n.Config.Expr, - }, - }, - }, - } -} - -// dag.GraphNodeDotter impl. -func (n *NodeApplyableOutput) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "note", - }, - } -} - -// NodeDestroyableOutput represents an output that is "destroybale": -// its application will remove the output from the state. -type NodeDestroyableOutput struct { - Addr addrs.AbsOutputValue - Config *configs.Output // Config is the output in the config -} - -var ( - _ GraphNodeSubPath = (*NodeDestroyableOutput)(nil) - _ RemovableIfNotTargeted = (*NodeDestroyableOutput)(nil) - _ GraphNodeTargetDownstream = (*NodeDestroyableOutput)(nil) - _ GraphNodeReferencer = (*NodeDestroyableOutput)(nil) - _ GraphNodeEvalable = (*NodeDestroyableOutput)(nil) - _ dag.GraphNodeDotter = (*NodeDestroyableOutput)(nil) -) - -func (n *NodeDestroyableOutput) Name() string { - return fmt.Sprintf("%s (destroy)", n.Addr.String()) -} - -// GraphNodeSubPath -func (n *NodeDestroyableOutput) Path() addrs.ModuleInstance { - return n.Addr.Module -} - -// RemovableIfNotTargeted -func (n *NodeDestroyableOutput) RemoveIfNotTargeted() bool { - // We need to add this so that this node will be removed if - // it isn't targeted or a dependency of a target. - return true -} - -// This will keep the destroy node in the graph if its corresponding output -// node is also in the destroy graph. -func (n *NodeDestroyableOutput) TargetDownstream(targetedDeps, untargetedDeps *dag.Set) bool { - return true -} - -// GraphNodeReferencer -func (n *NodeDestroyableOutput) References() []*addrs.Reference { - return referencesForOutput(n.Config) -} - -// GraphNodeEvalable -func (n *NodeDestroyableOutput) EvalTree() EvalNode { - return &EvalDeleteOutput{ - Addr: n.Addr.OutputValue, - } -} - -// dag.GraphNodeDotter impl. -func (n *NodeDestroyableOutput) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "note", - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_output_orphan.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_output_orphan.go deleted file mode 100644 index a76d1742ce9..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_output_orphan.go +++ /dev/null @@ -1,48 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// NodeOutputOrphan represents an output that is an orphan. -type NodeOutputOrphan struct { - Addr addrs.AbsOutputValue -} - -var ( - _ GraphNodeSubPath = (*NodeOutputOrphan)(nil) - _ GraphNodeReferenceable = (*NodeOutputOrphan)(nil) - _ GraphNodeReferenceOutside = (*NodeOutputOrphan)(nil) - _ GraphNodeEvalable = (*NodeOutputOrphan)(nil) -) - -func (n *NodeOutputOrphan) Name() string { - return fmt.Sprintf("%s (orphan)", n.Addr.String()) -} - -// GraphNodeReferenceOutside implementation -func (n *NodeOutputOrphan) ReferenceOutside() (selfPath, referencePath addrs.ModuleInstance) { - return referenceOutsideForOutput(n.Addr) -} - -// GraphNodeReferenceable -func (n *NodeOutputOrphan) ReferenceableAddrs() []addrs.Referenceable { - return referenceableAddrsForOutput(n.Addr) -} - -// GraphNodeSubPath -func (n *NodeOutputOrphan) Path() addrs.ModuleInstance { - return n.Addr.Module -} - -// GraphNodeEvalable -func (n *NodeOutputOrphan) EvalTree() EvalNode { - return &EvalOpFilter{ - Ops: []walkOperation{walkRefresh, walkApply, walkDestroy}, - Node: &EvalDeleteOutput{ - Addr: n.Addr.OutputValue, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider.go deleted file mode 100644 index 2071ab168f8..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider.go +++ /dev/null @@ -1,11 +0,0 @@ -package terraform - -// NodeApplyableProvider represents a provider during an apply. -type NodeApplyableProvider struct { - *NodeAbstractProvider -} - -// GraphNodeEvalable -func (n *NodeApplyableProvider) EvalTree() EvalNode { - return ProviderEvalTree(n, n.ProviderConfig()) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_abstract.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_abstract.go deleted file mode 100644 index afdd4741d2e..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_abstract.go +++ /dev/null @@ -1,96 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// ConcreteProviderNodeFunc is a callback type used to convert an -// abstract provider to a concrete one of some type. -type ConcreteProviderNodeFunc func(*NodeAbstractProvider) dag.Vertex - -// NodeAbstractProvider represents a provider that has no associated operations. -// It registers all the common interfaces across operations for providers. -type NodeAbstractProvider struct { - Addr addrs.AbsProviderConfig - - // The fields below will be automatically set using the Attach - // interfaces if you're running those transforms, but also be explicitly - // set if you already have that information. - - Config *configs.Provider - Schema *configschema.Block -} - -var ( - _ GraphNodeSubPath = (*NodeAbstractProvider)(nil) - _ RemovableIfNotTargeted = (*NodeAbstractProvider)(nil) - _ GraphNodeReferencer = (*NodeAbstractProvider)(nil) - _ GraphNodeProvider = (*NodeAbstractProvider)(nil) - _ GraphNodeAttachProvider = (*NodeAbstractProvider)(nil) - _ GraphNodeAttachProviderConfigSchema = (*NodeAbstractProvider)(nil) - _ dag.GraphNodeDotter = (*NodeAbstractProvider)(nil) -) - -func (n *NodeAbstractProvider) Name() string { - return n.Addr.String() -} - -// GraphNodeSubPath -func (n *NodeAbstractProvider) Path() addrs.ModuleInstance { - return n.Addr.Module -} - -// RemovableIfNotTargeted -func (n *NodeAbstractProvider) RemoveIfNotTargeted() bool { - // We need to add this so that this node will be removed if - // it isn't targeted or a dependency of a target. - return true -} - -// GraphNodeReferencer -func (n *NodeAbstractProvider) References() []*addrs.Reference { - if n.Config == nil || n.Schema == nil { - return nil - } - - return ReferencesFromConfig(n.Config.Config, n.Schema) -} - -// GraphNodeProvider -func (n *NodeAbstractProvider) ProviderAddr() addrs.AbsProviderConfig { - return n.Addr -} - -// GraphNodeProvider -func (n *NodeAbstractProvider) ProviderConfig() *configs.Provider { - if n.Config == nil { - return nil - } - - return n.Config -} - -// GraphNodeAttachProvider -func (n *NodeAbstractProvider) AttachProvider(c *configs.Provider) { - n.Config = c -} - -// GraphNodeAttachProviderConfigSchema impl. -func (n *NodeAbstractProvider) AttachProviderConfigSchema(schema *configschema.Block) { - n.Schema = schema -} - -// GraphNodeDotter impl. -func (n *NodeAbstractProvider) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "diamond", - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_disabled.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_disabled.go deleted file mode 100644 index 51335654bde..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_disabled.go +++ /dev/null @@ -1,27 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// NodeDisabledProvider represents a provider that is disabled. A disabled -// provider does nothing. It exists to properly set inheritance information -// for child providers. -type NodeDisabledProvider struct { - *NodeAbstractProvider -} - -var ( - _ GraphNodeSubPath = (*NodeDisabledProvider)(nil) - _ RemovableIfNotTargeted = (*NodeDisabledProvider)(nil) - _ GraphNodeReferencer = (*NodeDisabledProvider)(nil) - _ GraphNodeProvider = (*NodeDisabledProvider)(nil) - _ GraphNodeAttachProvider = (*NodeDisabledProvider)(nil) - _ dag.GraphNodeDotter = (*NodeDisabledProvider)(nil) -) - -func (n *NodeDisabledProvider) Name() string { - return fmt.Sprintf("%s (disabled)", n.NodeAbstractProvider.Name()) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_eval.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_eval.go deleted file mode 100644 index 580e60cb7e4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_eval.go +++ /dev/null @@ -1,20 +0,0 @@ -package terraform - -// NodeEvalableProvider represents a provider during an "eval" walk. -// This special provider node type just initializes a provider and -// fetches its schema, without configuring it or otherwise interacting -// with it. -type NodeEvalableProvider struct { - *NodeAbstractProvider -} - -// GraphNodeEvalable -func (n *NodeEvalableProvider) EvalTree() EvalNode { - addr := n.Addr - relAddr := addr.ProviderConfig - - return &EvalInitProvider{ - TypeName: relAddr.Type, - Addr: addr.ProviderConfig, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provisioner.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provisioner.go deleted file mode 100644 index 573f030d702..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provisioner.go +++ /dev/null @@ -1,44 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// NodeProvisioner represents a provider that has no associated operations. -// It registers all the common interfaces across operations for providers. -type NodeProvisioner struct { - NameValue string - PathValue addrs.ModuleInstance -} - -var ( - _ GraphNodeSubPath = (*NodeProvisioner)(nil) - _ GraphNodeProvisioner = (*NodeProvisioner)(nil) - _ GraphNodeEvalable = (*NodeProvisioner)(nil) -) - -func (n *NodeProvisioner) Name() string { - result := fmt.Sprintf("provisioner.%s", n.NameValue) - if len(n.PathValue) > 0 { - result = fmt.Sprintf("%s.%s", n.PathValue.String(), result) - } - - return result -} - -// GraphNodeSubPath -func (n *NodeProvisioner) Path() addrs.ModuleInstance { - return n.PathValue -} - -// GraphNodeProvisioner -func (n *NodeProvisioner) ProvisionerName() string { - return n.NameValue -} - -// GraphNodeEvalable impl. -func (n *NodeProvisioner) EvalTree() EvalNode { - return &EvalInitProvisioner{Name: n.NameValue} -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_abstract.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_abstract.go deleted file mode 100644 index c7b0e3c8e75..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_abstract.go +++ /dev/null @@ -1,446 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - "sort" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// ConcreteResourceNodeFunc is a callback type used to convert an -// abstract resource to a concrete one of some type. -type ConcreteResourceNodeFunc func(*NodeAbstractResource) dag.Vertex - -// GraphNodeResource is implemented by any nodes that represent a resource. -// The type of operation cannot be assumed, only that this node represents -// the given resource. -type GraphNodeResource interface { - ResourceAddr() addrs.AbsResource -} - -// ConcreteResourceInstanceNodeFunc is a callback type used to convert an -// abstract resource instance to a concrete one of some type. -type ConcreteResourceInstanceNodeFunc func(*NodeAbstractResourceInstance) dag.Vertex - -// GraphNodeResourceInstance is implemented by any nodes that represent -// a resource instance. A single resource may have multiple instances if, -// for example, the "count" or "for_each" argument is used for it in -// configuration. -type GraphNodeResourceInstance interface { - ResourceInstanceAddr() addrs.AbsResourceInstance -} - -// NodeAbstractResource represents a resource that has no associated -// operations. It registers all the interfaces for a resource that common -// across multiple operation types. -type NodeAbstractResource struct { - Addr addrs.AbsResource // Addr is the address for this resource - - // The fields below will be automatically set using the Attach - // interfaces if you're running those transforms, but also be explicitly - // set if you already have that information. - - Schema *configschema.Block // Schema for processing the configuration body - SchemaVersion uint64 // Schema version of "Schema", as decided by the provider - Config *configs.Resource // Config is the resource in the config - - ProvisionerSchemas map[string]*configschema.Block - - Targets []addrs.Targetable // Set from GraphNodeTargetable - - // The address of the provider this resource will use - ResolvedProvider addrs.AbsProviderConfig -} - -var ( - _ GraphNodeSubPath = (*NodeAbstractResource)(nil) - _ GraphNodeReferenceable = (*NodeAbstractResource)(nil) - _ GraphNodeReferencer = (*NodeAbstractResource)(nil) - _ GraphNodeProviderConsumer = (*NodeAbstractResource)(nil) - _ GraphNodeProvisionerConsumer = (*NodeAbstractResource)(nil) - _ GraphNodeResource = (*NodeAbstractResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodeAbstractResource)(nil) - _ GraphNodeAttachResourceSchema = (*NodeAbstractResource)(nil) - _ GraphNodeAttachProvisionerSchema = (*NodeAbstractResource)(nil) - _ GraphNodeTargetable = (*NodeAbstractResource)(nil) - _ dag.GraphNodeDotter = (*NodeAbstractResource)(nil) -) - -// NewNodeAbstractResource creates an abstract resource graph node for -// the given absolute resource address. -func NewNodeAbstractResource(addr addrs.AbsResource) *NodeAbstractResource { - return &NodeAbstractResource{ - Addr: addr, - } -} - -// NodeAbstractResourceInstance represents a resource instance with no -// associated operations. It embeds NodeAbstractResource but additionally -// contains an instance key, used to identify one of potentially many -// instances that were created from a resource in configuration, e.g. using -// the "count" or "for_each" arguments. -type NodeAbstractResourceInstance struct { - NodeAbstractResource - InstanceKey addrs.InstanceKey - - // The fields below will be automatically set using the Attach - // interfaces if you're running those transforms, but also be explicitly - // set if you already have that information. - - ResourceState *states.Resource -} - -var ( - _ GraphNodeSubPath = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeReferenceable = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeReferencer = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeProviderConsumer = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeProvisionerConsumer = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeResource = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeAttachResourceState = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeAttachResourceConfig = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeAttachResourceSchema = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeAttachProvisionerSchema = (*NodeAbstractResourceInstance)(nil) - _ GraphNodeTargetable = (*NodeAbstractResourceInstance)(nil) - _ dag.GraphNodeDotter = (*NodeAbstractResourceInstance)(nil) -) - -// NewNodeAbstractResourceInstance creates an abstract resource instance graph -// node for the given absolute resource instance address. -func NewNodeAbstractResourceInstance(addr addrs.AbsResourceInstance) *NodeAbstractResourceInstance { - // Due to the fact that we embed NodeAbstractResource, the given address - // actually ends up split between the resource address in the embedded - // object and the InstanceKey field in our own struct. The - // ResourceInstanceAddr method will stick these back together again on - // request. - return &NodeAbstractResourceInstance{ - NodeAbstractResource: NodeAbstractResource{ - Addr: addr.ContainingResource(), - }, - InstanceKey: addr.Resource.Key, - } -} - -func (n *NodeAbstractResource) Name() string { - return n.ResourceAddr().String() -} - -func (n *NodeAbstractResourceInstance) Name() string { - return n.ResourceInstanceAddr().String() -} - -// GraphNodeSubPath -func (n *NodeAbstractResource) Path() addrs.ModuleInstance { - return n.Addr.Module -} - -// GraphNodeReferenceable -func (n *NodeAbstractResource) ReferenceableAddrs() []addrs.Referenceable { - return []addrs.Referenceable{n.Addr.Resource} -} - -// GraphNodeReferenceable -func (n *NodeAbstractResourceInstance) ReferenceableAddrs() []addrs.Referenceable { - addr := n.ResourceInstanceAddr() - return []addrs.Referenceable{ - addr.Resource, - - // A resource instance can also be referenced by the address of its - // containing resource, so that e.g. a reference to aws_instance.foo - // would match both aws_instance.foo[0] and aws_instance.foo[1]. - addr.ContainingResource().Resource, - } -} - -// GraphNodeReferencer -func (n *NodeAbstractResource) References() []*addrs.Reference { - // If we have a config then we prefer to use that. - if c := n.Config; c != nil { - var result []*addrs.Reference - - for _, traversal := range c.DependsOn { - ref, err := addrs.ParseRef(traversal) - if err != nil { - // We ignore this here, because this isn't a suitable place to return - // errors. This situation should be caught and rejected during - // validation. - log.Printf("[ERROR] Can't parse %#v from depends_on as reference: %s", traversal, err) - continue - } - - result = append(result, ref) - } - - if n.Schema == nil { - // Should never happens, but we'll log if it does so that we can - // see this easily when debugging. - log.Printf("[WARN] no schema is attached to %s, so config references cannot be detected", n.Name()) - } - - refs, _ := lang.ReferencesInExpr(c.Count) - result = append(result, refs...) - refs, _ = lang.ReferencesInExpr(c.ForEach) - result = append(result, refs...) - refs, _ = lang.ReferencesInBlock(c.Config, n.Schema) - result = append(result, refs...) - if c.Managed != nil { - for _, p := range c.Managed.Provisioners { - if p.When != configs.ProvisionerWhenCreate { - continue - } - if p.Connection != nil { - refs, _ = lang.ReferencesInBlock(p.Connection.Config, connectionBlockSupersetSchema) - result = append(result, refs...) - } - - schema := n.ProvisionerSchemas[p.Type] - if schema == nil { - log.Printf("[WARN] no schema for provisioner %q is attached to %s, so provisioner block references cannot be detected", p.Type, n.Name()) - } - refs, _ = lang.ReferencesInBlock(p.Config, schema) - result = append(result, refs...) - } - } - return result - } - - // Otherwise, we have no references. - return nil -} - -// GraphNodeReferencer -func (n *NodeAbstractResourceInstance) References() []*addrs.Reference { - // If we have a configuration attached then we'll delegate to our - // embedded abstract resource, which knows how to extract dependencies - // from configuration. - if n.Config != nil { - if n.Schema == nil { - // We'll produce a log message about this out here so that - // we can include the full instance address, since the equivalent - // message in NodeAbstractResource.References cannot see it. - log.Printf("[WARN] no schema is attached to %s, so config references cannot be detected", n.Name()) - return nil - } - return n.NodeAbstractResource.References() - } - - // Otherwise, if we have state then we'll use the values stored in state - // as a fallback. - if rs := n.ResourceState; rs != nil { - if s := rs.Instance(n.InstanceKey); s != nil { - // State is still storing dependencies as old-style strings, so we'll - // need to do a little work here to massage this to the form we now - // want. - var result []*addrs.Reference - - // It is (apparently) possible for s.Current to be nil. This proved - // difficult to reproduce, so we will fix the symptom here and hope - // to find the root cause another time. - // - // https://github.com/hashicorp/terraform-plugin-sdk/issues/21407 - if s.Current == nil { - log.Printf("[WARN] no current state found for %s", n.Name()) - } else { - for _, addr := range s.Current.Dependencies { - if addr == nil { - // Should never happen; indicates a bug in the state loader - panic(fmt.Sprintf("dependencies for current object on %s contains nil address", n.ResourceInstanceAddr())) - } - - // This is a little weird: we need to manufacture an addrs.Reference - // with a fake range here because the state isn't something we can - // make source references into. - result = append(result, &addrs.Reference{ - Subject: addr, - SourceRange: tfdiags.SourceRange{ - Filename: "(state file)", - }, - }) - } - } - return result - } - } - - // If we have neither config nor state then we have no references. - return nil -} - -// StateReferences returns the dependencies to put into the state for -// this resource. -func (n *NodeAbstractResourceInstance) StateReferences() []addrs.Referenceable { - selfAddrs := n.ReferenceableAddrs() - - // Since we don't include the source location references in our - // results from this method, we'll also filter out duplicates: - // there's no point in listing the same object twice without - // that additional context. - seen := map[string]struct{}{} - - // Pretend that we've already "seen" all of our own addresses so that we - // won't record self-references in the state. This can arise if, for - // example, a provisioner for a resource refers to the resource itself, - // which is valid (since provisioners always run after apply) but should - // not create an explicit dependency edge. - for _, selfAddr := range selfAddrs { - seen[selfAddr.String()] = struct{}{} - if riAddr, ok := selfAddr.(addrs.ResourceInstance); ok { - seen[riAddr.ContainingResource().String()] = struct{}{} - } - } - - depsRaw := n.References() - deps := make([]addrs.Referenceable, 0, len(depsRaw)) - for _, d := range depsRaw { - subj := d.Subject - if mco, isOutput := subj.(addrs.ModuleCallOutput); isOutput { - // For state dependencies, we simplify outputs to just refer - // to the module as a whole. It's not really clear why we do this, - // but this logic is preserved from before the 0.12 rewrite of - // this function. - subj = mco.Call - } - - k := subj.String() - if _, exists := seen[k]; exists { - continue - } - seen[k] = struct{}{} - switch tr := subj.(type) { - case addrs.ResourceInstance: - deps = append(deps, tr) - case addrs.Resource: - deps = append(deps, tr) - case addrs.ModuleCallInstance: - deps = append(deps, tr) - default: - // No other reference types are recorded in the state. - } - } - - // We'll also sort them, since that'll avoid creating changes in the - // serialized state that make no semantic difference. - sort.Slice(deps, func(i, j int) bool { - // Simple string-based sort because we just care about consistency, - // not user-friendliness. - return deps[i].String() < deps[j].String() - }) - - return deps -} - -func (n *NodeAbstractResource) SetProvider(p addrs.AbsProviderConfig) { - n.ResolvedProvider = p -} - -// GraphNodeProviderConsumer -func (n *NodeAbstractResource) ProvidedBy() (addrs.AbsProviderConfig, bool) { - // If we have a config we prefer that above all else - if n.Config != nil { - relAddr := n.Config.ProviderConfigAddr() - return relAddr.Absolute(n.Path()), false - } - - // Use our type and containing module path to guess a provider configuration address - return n.Addr.Resource.DefaultProviderConfig().Absolute(n.Addr.Module), false -} - -// GraphNodeProviderConsumer -func (n *NodeAbstractResourceInstance) ProvidedBy() (addrs.AbsProviderConfig, bool) { - // If we have a config we prefer that above all else - if n.Config != nil { - relAddr := n.Config.ProviderConfigAddr() - return relAddr.Absolute(n.Path()), false - } - - // If we have state, then we will use the provider from there - if n.ResourceState != nil { - // An address from the state must match exactly, since we must ensure - // we refresh/destroy a resource with the same provider configuration - // that created it. - return n.ResourceState.ProviderConfig, true - } - - // Use our type and containing module path to guess a provider configuration address - return n.Addr.Resource.DefaultProviderConfig().Absolute(n.Path()), false -} - -// GraphNodeProvisionerConsumer -func (n *NodeAbstractResource) ProvisionedBy() []string { - // If we have no configuration, then we have no provisioners - if n.Config == nil || n.Config.Managed == nil { - return nil - } - - // Build the list of provisioners we need based on the configuration. - // It is okay to have duplicates here. - result := make([]string, len(n.Config.Managed.Provisioners)) - for i, p := range n.Config.Managed.Provisioners { - result[i] = p.Type - } - - return result -} - -// GraphNodeProvisionerConsumer -func (n *NodeAbstractResource) AttachProvisionerSchema(name string, schema *configschema.Block) { - if n.ProvisionerSchemas == nil { - n.ProvisionerSchemas = make(map[string]*configschema.Block) - } - n.ProvisionerSchemas[name] = schema -} - -// GraphNodeResource -func (n *NodeAbstractResource) ResourceAddr() addrs.AbsResource { - return n.Addr -} - -// GraphNodeResourceInstance -func (n *NodeAbstractResourceInstance) ResourceInstanceAddr() addrs.AbsResourceInstance { - return n.NodeAbstractResource.Addr.Instance(n.InstanceKey) -} - -// GraphNodeAddressable, TODO: remove, used by target, should unify -func (n *NodeAbstractResource) ResourceAddress() *ResourceAddress { - return NewLegacyResourceAddress(n.Addr) -} - -// GraphNodeTargetable -func (n *NodeAbstractResource) SetTargets(targets []addrs.Targetable) { - n.Targets = targets -} - -// GraphNodeAttachResourceState -func (n *NodeAbstractResourceInstance) AttachResourceState(s *states.Resource) { - n.ResourceState = s -} - -// GraphNodeAttachResourceConfig -func (n *NodeAbstractResource) AttachResourceConfig(c *configs.Resource) { - n.Config = c -} - -// GraphNodeAttachResourceSchema impl -func (n *NodeAbstractResource) AttachResourceSchema(schema *configschema.Block, version uint64) { - n.Schema = schema - n.SchemaVersion = version -} - -// GraphNodeDotter impl. -func (n *NodeAbstractResource) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "box", - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply.go deleted file mode 100644 index 68d438d7bc4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply.go +++ /dev/null @@ -1,71 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" -) - -// NodeApplyableResource represents a resource that is "applyable": -// it may need to have its record in the state adjusted to match configuration. -// -// Unlike in the plan walk, this resource node does not DynamicExpand. Instead, -// it should be inserted into the same graph as any instances of the nodes -// with dependency edges ensuring that the resource is evaluated before any -// of its instances, which will turn ensure that the whole-resource record -// in the state is suitably prepared to receive any updates to instances. -type NodeApplyableResource struct { - *NodeAbstractResource -} - -var ( - _ GraphNodeResource = (*NodeApplyableResource)(nil) - _ GraphNodeEvalable = (*NodeApplyableResource)(nil) - _ GraphNodeProviderConsumer = (*NodeApplyableResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodeApplyableResource)(nil) - _ GraphNodeReferencer = (*NodeApplyableResource)(nil) -) - -func (n *NodeApplyableResource) Name() string { - return n.NodeAbstractResource.Name() + " (prepare state)" -} - -func (n *NodeApplyableResource) References() []*addrs.Reference { - if n.Config == nil { - log.Printf("[WARN] NodeApplyableResource %q: no configuration, so can't determine References", dag.VertexName(n)) - return nil - } - - var result []*addrs.Reference - - // Since this node type only updates resource-level metadata, we only - // need to worry about the parts of the configuration that affect - // our "each mode": the count and for_each meta-arguments. - refs, _ := lang.ReferencesInExpr(n.Config.Count) - result = append(result, refs...) - refs, _ = lang.ReferencesInExpr(n.Config.ForEach) - result = append(result, refs...) - - return result -} - -// GraphNodeEvalable -func (n *NodeApplyableResource) EvalTree() EvalNode { - addr := n.ResourceAddr() - config := n.Config - providerAddr := n.ResolvedProvider - - if config == nil { - // Nothing to do, then. - log.Printf("[TRACE] NodeApplyableResource: no configuration present for %s", addr) - return &EvalNoop{} - } - - return &EvalWriteResourceState{ - Addr: addr.Resource, - Config: config, - ProviderAddr: providerAddr, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply_instance.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply_instance.go deleted file mode 100644 index acdda45e407..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply_instance.go +++ /dev/null @@ -1,426 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// NodeApplyableResourceInstance represents a resource instance that is -// "applyable": it is ready to be applied and is represented by a diff. -// -// This node is for a specific instance of a resource. It will usually be -// accompanied in the graph by a NodeApplyableResource representing its -// containing resource, and should depend on that node to ensure that the -// state is properly prepared to receive changes to instances. -type NodeApplyableResourceInstance struct { - *NodeAbstractResourceInstance - - destroyNode GraphNodeDestroyerCBD - graphNodeDeposer // implementation of GraphNodeDeposer -} - -var ( - _ GraphNodeResource = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeCreator = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeReferencer = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeDeposer = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeEvalable = (*NodeApplyableResourceInstance)(nil) -) - -// GraphNodeAttachDestroyer -func (n *NodeApplyableResourceInstance) AttachDestroyNode(d GraphNodeDestroyerCBD) { - n.destroyNode = d -} - -// createBeforeDestroy checks this nodes config status and the status af any -// companion destroy node for CreateBeforeDestroy. -func (n *NodeApplyableResourceInstance) createBeforeDestroy() bool { - cbd := false - - if n.Config != nil && n.Config.Managed != nil { - cbd = n.Config.Managed.CreateBeforeDestroy - } - - if n.destroyNode != nil { - cbd = cbd || n.destroyNode.CreateBeforeDestroy() - } - - return cbd -} - -// GraphNodeCreator -func (n *NodeApplyableResourceInstance) CreateAddr() *addrs.AbsResourceInstance { - addr := n.ResourceInstanceAddr() - return &addr -} - -// GraphNodeReferencer, overriding NodeAbstractResourceInstance -func (n *NodeApplyableResourceInstance) References() []*addrs.Reference { - // Start with the usual resource instance implementation - ret := n.NodeAbstractResourceInstance.References() - - // Applying a resource must also depend on the destruction of any of its - // dependencies, since this may for example affect the outcome of - // evaluating an entire list of resources with "count" set (by reducing - // the count). - // - // However, we can't do this in create_before_destroy mode because that - // would create a dependency cycle. We make a compromise here of requiring - // changes to be updated across two applies in this case, since the first - // plan will use the old values. - if !n.createBeforeDestroy() { - for _, ref := range ret { - switch tr := ref.Subject.(type) { - case addrs.ResourceInstance: - newRef := *ref // shallow copy so we can mutate - newRef.Subject = tr.Phase(addrs.ResourceInstancePhaseDestroy) - newRef.Remaining = nil // can't access attributes of something being destroyed - ret = append(ret, &newRef) - case addrs.Resource: - newRef := *ref // shallow copy so we can mutate - newRef.Subject = tr.Phase(addrs.ResourceInstancePhaseDestroy) - newRef.Remaining = nil // can't access attributes of something being destroyed - ret = append(ret, &newRef) - } - } - } - - return ret -} - -// GraphNodeEvalable -func (n *NodeApplyableResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - if n.Config == nil { - // This should not be possible, but we've got here in at least one - // case as discussed in the following issue: - // https://github.com/hashicorp/terraform-plugin-sdk/issues/21258 - // To avoid an outright crash here, we'll instead return an explicit - // error. - var diags tfdiags.Diagnostics - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Resource node has no configuration attached", - fmt.Sprintf( - "The graph node for %s has no configuration attached to it. This suggests a bug in Terraform's apply graph builder; please report it!", - addr, - ), - )) - err := diags.Err() - return &EvalReturnError{ - Error: &err, - } - } - - // Eval info is different depending on what kind of resource this is - switch n.Config.Mode { - case addrs.ManagedResourceMode: - return n.evalTreeManagedResource(addr) - case addrs.DataResourceMode: - return n.evalTreeDataResource(addr) - default: - panic(fmt.Errorf("unsupported resource mode %s", n.Config.Mode)) - } -} - -func (n *NodeApplyableResourceInstance) evalTreeDataResource(addr addrs.AbsResourceInstance) EvalNode { - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - - // Get the saved diff for apply - &EvalReadDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &change, - }, - - // Stop early if we don't actually have a diff - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if change == nil { - return true, EvalEarlyExitError{} - } - return true, nil - }, - Then: EvalNoop{}, - }, - - // In this particular call to EvalReadData we include our planned - // change, which signals that we expect this read to complete fully - // with no unknown values; it'll produce an error if not. - &EvalReadData{ - Addr: addr.Resource, - Config: n.Config, - Dependencies: n.StateReferences(), - Planned: &change, // setting this indicates that the result must be complete - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - OutputState: &state, - }, - - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - - // Clear the diff now that we've applied it, so - // later nodes won't see a diff that's now a no-op. - &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: nil, - }, - - &EvalUpdateStateHook{}, - }, - } -} - -func (n *NodeApplyableResourceInstance) evalTreeManagedResource(addr addrs.AbsResourceInstance) EvalNode { - // Declare a bunch of variables that are used for state during - // evaluation. Most of this are written to by-address below. - var provider providers.Interface - var providerSchema *ProviderSchema - var diff, diffApply *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - var err error - var createNew bool - var createBeforeDestroyEnabled bool - var configVal cty.Value - var deposedKey states.DeposedKey - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - - // Get the saved diff for apply - &EvalReadDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &diffApply, - }, - - // We don't want to do any destroys - // (these are handled by NodeDestroyResourceInstance instead) - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if diffApply == nil { - return true, EvalEarlyExitError{} - } - if diffApply.Action == plans.Delete { - return true, EvalEarlyExitError{} - } - return true, nil - }, - Then: EvalNoop{}, - }, - - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - destroy := false - if diffApply != nil { - destroy = (diffApply.Action == plans.Delete || diffApply.Action.IsReplace()) - } - if destroy && n.createBeforeDestroy() { - createBeforeDestroyEnabled = true - } - return createBeforeDestroyEnabled, nil - }, - Then: &EvalDeposeState{ - Addr: addr.Resource, - ForceKey: n.PreallocatedDeposedKey, - OutputKey: &deposedKey, - }, - }, - - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - - Output: &state, - }, - - // Get the saved diff - &EvalReadDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &diff, - }, - - // Make a new diff, in case we've learned new values in the state - // during apply which we can now incorporate. - &EvalDiff{ - Addr: addr.Resource, - Config: n.Config, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - PreviousDiff: &diff, - OutputChange: &diffApply, - OutputValue: &configVal, - OutputState: &state, - }, - - // Compare the diffs - &EvalCheckPlannedChange{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - Planned: &diff, - Actual: &diffApply, - }, - - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - - Output: &state, - }, - - &EvalReduceDiff{ - Addr: addr.Resource, - InChange: &diffApply, - Destroy: false, - OutChange: &diffApply, - }, - - // EvalReduceDiff may have simplified our planned change - // into a NoOp if it only requires destroying, since destroying - // is handled by NodeDestroyResourceInstance. - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if diffApply == nil || diffApply.Action == plans.NoOp { - return true, EvalEarlyExitError{} - } - return true, nil - }, - Then: EvalNoop{}, - }, - - // Call pre-apply hook - &EvalApplyPre{ - Addr: addr.Resource, - State: &state, - Change: &diffApply, - }, - &EvalApply{ - Addr: addr.Resource, - Config: n.Config, - Dependencies: n.StateReferences(), - State: &state, - Change: &diffApply, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - Output: &state, - Error: &err, - CreateNew: &createNew, - }, - &EvalMaybeTainted{ - Addr: addr.Resource, - State: &state, - Change: &diffApply, - Error: &err, - StateOutput: &state, - }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - &EvalApplyProvisioners{ - Addr: addr.Resource, - State: &state, // EvalApplyProvisioners will skip if already tainted - ResourceConfig: n.Config, - CreateNew: &createNew, - Error: &err, - When: configs.ProvisionerWhenCreate, - }, - &EvalMaybeTainted{ - Addr: addr.Resource, - State: &state, - Change: &diffApply, - Error: &err, - StateOutput: &state, - }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - return createBeforeDestroyEnabled && err != nil, nil - }, - Then: &EvalMaybeRestoreDeposedObject{ - Addr: addr.Resource, - Key: &deposedKey, - }, - }, - - // We clear the diff out here so that future nodes - // don't see a diff that is already complete. There - // is no longer a diff! - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if !diff.Action.IsReplace() { - return true, nil - } - if !n.createBeforeDestroy() { - return true, nil - } - return false, nil - }, - Then: &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: nil, - }, - }, - - &EvalApplyPost{ - Addr: addr.Resource, - State: &state, - Error: &err, - }, - &EvalUpdateStateHook{}, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy.go deleted file mode 100644 index 049e5e99078..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy.go +++ /dev/null @@ -1,321 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// NodeDestroyResourceInstance represents a resource instance that is to be -// destroyed. -type NodeDestroyResourceInstance struct { - *NodeAbstractResourceInstance - - // If DeposedKey is set to anything other than states.NotDeposed then - // this node destroys a deposed object of the associated instance - // rather than its current object. - DeposedKey states.DeposedKey - - CreateBeforeDestroyOverride *bool -} - -var ( - _ GraphNodeResource = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeDestroyer = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeDestroyerCBD = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeReferenceable = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeReferencer = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeEvalable = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeProviderConsumer = (*NodeDestroyResourceInstance)(nil) - _ GraphNodeProvisionerConsumer = (*NodeDestroyResourceInstance)(nil) -) - -func (n *NodeDestroyResourceInstance) Name() string { - if n.DeposedKey != states.NotDeposed { - return fmt.Sprintf("%s (destroy deposed %s)", n.ResourceInstanceAddr(), n.DeposedKey) - } - return n.ResourceInstanceAddr().String() + " (destroy)" -} - -// GraphNodeDestroyer -func (n *NodeDestroyResourceInstance) DestroyAddr() *addrs.AbsResourceInstance { - addr := n.ResourceInstanceAddr() - return &addr -} - -// GraphNodeDestroyerCBD -func (n *NodeDestroyResourceInstance) CreateBeforeDestroy() bool { - if n.CreateBeforeDestroyOverride != nil { - return *n.CreateBeforeDestroyOverride - } - - // If we have no config, we just assume no - if n.Config == nil || n.Config.Managed == nil { - return false - } - - return n.Config.Managed.CreateBeforeDestroy -} - -// GraphNodeDestroyerCBD -func (n *NodeDestroyResourceInstance) ModifyCreateBeforeDestroy(v bool) error { - n.CreateBeforeDestroyOverride = &v - return nil -} - -// GraphNodeReferenceable, overriding NodeAbstractResource -func (n *NodeDestroyResourceInstance) ReferenceableAddrs() []addrs.Referenceable { - normalAddrs := n.NodeAbstractResourceInstance.ReferenceableAddrs() - destroyAddrs := make([]addrs.Referenceable, len(normalAddrs)) - - phaseType := addrs.ResourceInstancePhaseDestroy - if n.CreateBeforeDestroy() { - phaseType = addrs.ResourceInstancePhaseDestroyCBD - } - - for i, normalAddr := range normalAddrs { - switch ta := normalAddr.(type) { - case addrs.Resource: - destroyAddrs[i] = ta.Phase(phaseType) - case addrs.ResourceInstance: - destroyAddrs[i] = ta.Phase(phaseType) - default: - destroyAddrs[i] = normalAddr - } - } - - return destroyAddrs -} - -// GraphNodeReferencer, overriding NodeAbstractResource -func (n *NodeDestroyResourceInstance) References() []*addrs.Reference { - // If we have a config, then we need to include destroy-time dependencies - if c := n.Config; c != nil && c.Managed != nil { - var result []*addrs.Reference - - // We include conn info and config for destroy time provisioners - // as dependencies that we have. - for _, p := range c.Managed.Provisioners { - schema := n.ProvisionerSchemas[p.Type] - - if p.When == configs.ProvisionerWhenDestroy { - if p.Connection != nil { - result = append(result, ReferencesFromConfig(p.Connection.Config, connectionBlockSupersetSchema)...) - } - result = append(result, ReferencesFromConfig(p.Config, schema)...) - } - } - - return result - } - - return nil -} - -// GraphNodeEvalable -func (n *NodeDestroyResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - // Get our state - rs := n.ResourceState - var is *states.ResourceInstance - if rs != nil { - is = rs.Instance(n.InstanceKey) - } - if is == nil { - log.Printf("[WARN] NodeDestroyResourceInstance for %s with no state", addr) - } - - var changeApply *plans.ResourceInstanceChange - var provider providers.Interface - var providerSchema *ProviderSchema - var state *states.ResourceInstanceObject - var err error - return &EvalOpFilter{ - Ops: []walkOperation{walkApply, walkDestroy}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - - // Get the saved diff for apply - &EvalReadDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &changeApply, - }, - - &EvalReduceDiff{ - Addr: addr.Resource, - InChange: &changeApply, - Destroy: true, - OutChange: &changeApply, - }, - - // EvalReduceDiff may have simplified our planned change - // into a NoOp if it does not require destroying. - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if changeApply == nil || changeApply.Action == plans.NoOp { - return true, EvalEarlyExitError{} - } - return true, nil - }, - Then: EvalNoop{}, - }, - - &EvalReadState{ - Addr: addr.Resource, - Output: &state, - Provider: &provider, - ProviderSchema: &providerSchema, - }, - &EvalRequireState{ - State: &state, - }, - - // Call pre-apply hook - &EvalApplyPre{ - Addr: addr.Resource, - State: &state, - Change: &changeApply, - }, - - // Run destroy provisioners if not tainted - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if state != nil && state.Status == states.ObjectTainted { - return false, nil - } - - return true, nil - }, - - Then: &EvalApplyProvisioners{ - Addr: addr.Resource, - State: &state, - ResourceConfig: n.Config, - Error: &err, - When: configs.ProvisionerWhenDestroy, - }, - }, - - // If we have a provisioning error, then we just call - // the post-apply hook now. - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - return err != nil, nil - }, - - Then: &EvalApplyPost{ - Addr: addr.Resource, - State: &state, - Error: &err, - }, - }, - - // Make sure we handle data sources properly. - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - return addr.Resource.Resource.Mode == addrs.DataResourceMode, nil - }, - - Then: &EvalReadDataApply{ - Addr: addr.Resource, - Config: n.Config, - Change: &changeApply, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - Output: &state, - }, - Else: &EvalApply{ - Addr: addr.Resource, - Config: nil, // No configuration because we are destroying - State: &state, - Change: &changeApply, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - Output: &state, - Error: &err, - }, - }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - &EvalApplyPost{ - Addr: addr.Resource, - State: &state, - Error: &err, - }, - &EvalUpdateStateHook{}, - }, - }, - } -} - -// NodeDestroyResourceInstance represents a resource that is to be destroyed. -// -// Destroying a resource is a state-only operation: it is the individual -// instances being destroyed that affects remote objects. During graph -// construction, NodeDestroyResource should always depend on any other node -// related to the given resource, since it's just a final cleanup to avoid -// leaving skeleton resource objects in state after their instances have -// all been destroyed. -type NodeDestroyResource struct { - *NodeAbstractResource -} - -var ( - _ GraphNodeResource = (*NodeDestroyResource)(nil) - _ GraphNodeReferenceable = (*NodeDestroyResource)(nil) - _ GraphNodeReferencer = (*NodeDestroyResource)(nil) - _ GraphNodeEvalable = (*NodeDestroyResource)(nil) -) - -func (n *NodeDestroyResource) Name() string { - return n.ResourceAddr().String() + " (clean up state)" -} - -// GraphNodeReferenceable, overriding NodeAbstractResource -func (n *NodeDestroyResource) ReferenceableAddrs() []addrs.Referenceable { - // NodeDestroyResource doesn't participate in references: the graph - // builder that created it should ensure directly that it already depends - // on every other node related to its resource, without relying on - // references. - return nil -} - -// GraphNodeReferencer, overriding NodeAbstractResource -func (n *NodeDestroyResource) References() []*addrs.Reference { - // NodeDestroyResource doesn't participate in references: the graph - // builder that created it should ensure directly that it already depends - // on every other node related to its resource, without relying on - // references. - return nil -} - -// GraphNodeEvalable -func (n *NodeDestroyResource) EvalTree() EvalNode { - // This EvalNode will produce an error if the resource isn't already - // empty by the time it is called, since it should just be pruning the - // leftover husk of a resource in state after all of the child instances - // and their objects were destroyed. - return &EvalForgetResourceState{ - Addr: n.ResourceAddr().Resource, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy_deposed.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy_deposed.go deleted file mode 100644 index 269c7980804..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy_deposed.go +++ /dev/null @@ -1,313 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// ConcreteResourceInstanceDeposedNodeFunc is a callback type used to convert -// an abstract resource instance to a concrete one of some type that has -// an associated deposed object key. -type ConcreteResourceInstanceDeposedNodeFunc func(*NodeAbstractResourceInstance, states.DeposedKey) dag.Vertex - -type GraphNodeDeposedResourceInstanceObject interface { - DeposedInstanceObjectKey() states.DeposedKey -} - -// NodePlanDeposedResourceInstanceObject represents deposed resource -// instance objects during plan. These are distinct from the primary object -// for each resource instance since the only valid operation to do with them -// is to destroy them. -// -// This node type is also used during the refresh walk to ensure that the -// record of a deposed object is up-to-date before we plan to destroy it. -type NodePlanDeposedResourceInstanceObject struct { - *NodeAbstractResourceInstance - DeposedKey states.DeposedKey -} - -var ( - _ GraphNodeDeposedResourceInstanceObject = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeResource = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeResourceInstance = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeReferenceable = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeReferencer = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeEvalable = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeProviderConsumer = (*NodePlanDeposedResourceInstanceObject)(nil) - _ GraphNodeProvisionerConsumer = (*NodePlanDeposedResourceInstanceObject)(nil) -) - -func (n *NodePlanDeposedResourceInstanceObject) Name() string { - return fmt.Sprintf("%s (deposed %s)", n.ResourceInstanceAddr().String(), n.DeposedKey) -} - -func (n *NodePlanDeposedResourceInstanceObject) DeposedInstanceObjectKey() states.DeposedKey { - return n.DeposedKey -} - -// GraphNodeReferenceable implementation, overriding the one from NodeAbstractResourceInstance -func (n *NodePlanDeposedResourceInstanceObject) ReferenceableAddrs() []addrs.Referenceable { - // Deposed objects don't participate in references. - return nil -} - -// GraphNodeReferencer implementation, overriding the one from NodeAbstractResourceInstance -func (n *NodePlanDeposedResourceInstanceObject) References() []*addrs.Reference { - // We don't evaluate configuration for deposed objects, so they effectively - // make no references. - return nil -} - -// GraphNodeEvalable impl. -func (n *NodePlanDeposedResourceInstanceObject) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - var provider providers.Interface - var providerSchema *ProviderSchema - var state *states.ResourceInstanceObject - - seq := &EvalSequence{Nodes: make([]EvalNode, 0, 5)} - - // During the refresh walk we will ensure that our record of the deposed - // object is up-to-date. If it was already deleted outside of Terraform - // then this will remove it from state and thus avoid us planning a - // destroy for it during the subsequent plan walk. - seq.Nodes = append(seq.Nodes, &EvalOpFilter{ - Ops: []walkOperation{walkRefresh}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalReadStateDeposed{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - Key: n.DeposedKey, - Output: &state, - }, - &EvalRefresh{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - Provider: &provider, - ProviderSchema: &providerSchema, - State: &state, - Output: &state, - }, - &EvalWriteStateDeposed{ - Addr: addr.Resource, - Key: n.DeposedKey, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - }, - }, - }) - - // During the plan walk we always produce a planned destroy change, because - // destroying is the only supported action for deposed objects. - var change *plans.ResourceInstanceChange - seq.Nodes = append(seq.Nodes, &EvalOpFilter{ - Ops: []walkOperation{walkPlan, walkPlanDestroy}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalReadStateDeposed{ - Addr: addr.Resource, - Output: &state, - Key: n.DeposedKey, - Provider: &provider, - ProviderSchema: &providerSchema, - }, - &EvalDiffDestroy{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - DeposedKey: n.DeposedKey, - State: &state, - Output: &change, - }, - &EvalWriteDiff{ - Addr: addr.Resource, - DeposedKey: n.DeposedKey, - ProviderSchema: &providerSchema, - Change: &change, - }, - // Since deposed objects cannot be referenced by expressions - // elsewhere, we don't need to also record the planned new - // state in this case. - }, - }, - }) - - return seq -} - -// NodeDestroyDeposedResourceInstanceObject represents deposed resource -// instance objects during apply. Nodes of this type are inserted by -// DiffTransformer when the planned changeset contains "delete" changes for -// deposed instance objects, and its only supported operation is to destroy -// and then forget the associated object. -type NodeDestroyDeposedResourceInstanceObject struct { - *NodeAbstractResourceInstance - DeposedKey states.DeposedKey -} - -var ( - _ GraphNodeDeposedResourceInstanceObject = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeResource = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeResourceInstance = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeDestroyer = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeDestroyerCBD = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeReferenceable = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeReferencer = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeEvalable = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeProviderConsumer = (*NodeDestroyDeposedResourceInstanceObject)(nil) - _ GraphNodeProvisionerConsumer = (*NodeDestroyDeposedResourceInstanceObject)(nil) -) - -func (n *NodeDestroyDeposedResourceInstanceObject) Name() string { - return fmt.Sprintf("%s (destroy deposed %s)", n.Addr.String(), n.DeposedKey) -} - -func (n *NodeDestroyDeposedResourceInstanceObject) DeposedInstanceObjectKey() states.DeposedKey { - return n.DeposedKey -} - -// GraphNodeReferenceable implementation, overriding the one from NodeAbstractResourceInstance -func (n *NodeDestroyDeposedResourceInstanceObject) ReferenceableAddrs() []addrs.Referenceable { - // Deposed objects don't participate in references. - return nil -} - -// GraphNodeReferencer implementation, overriding the one from NodeAbstractResourceInstance -func (n *NodeDestroyDeposedResourceInstanceObject) References() []*addrs.Reference { - // We don't evaluate configuration for deposed objects, so they effectively - // make no references. - return nil -} - -// GraphNodeDestroyer -func (n *NodeDestroyDeposedResourceInstanceObject) DestroyAddr() *addrs.AbsResourceInstance { - addr := n.ResourceInstanceAddr() - return &addr -} - -// GraphNodeDestroyerCBD -func (n *NodeDestroyDeposedResourceInstanceObject) CreateBeforeDestroy() bool { - // A deposed instance is always CreateBeforeDestroy by definition, since - // we use deposed only to handle create-before-destroy. - return true -} - -// GraphNodeDestroyerCBD -func (n *NodeDestroyDeposedResourceInstanceObject) ModifyCreateBeforeDestroy(v bool) error { - if !v { - // Should never happen: deposed instances are _always_ create_before_destroy. - return fmt.Errorf("can't deactivate create_before_destroy for a deposed instance") - } - return nil -} - -// GraphNodeEvalable impl. -func (n *NodeDestroyDeposedResourceInstanceObject) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - var provider providers.Interface - var providerSchema *ProviderSchema - var state *states.ResourceInstanceObject - var change *plans.ResourceInstanceChange - var err error - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalReadStateDeposed{ - Addr: addr.Resource, - Output: &state, - Key: n.DeposedKey, - Provider: &provider, - ProviderSchema: &providerSchema, - }, - &EvalDiffDestroy{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, - Output: &change, - }, - // Call pre-apply hook - &EvalApplyPre{ - Addr: addr.Resource, - State: &state, - Change: &change, - }, - &EvalApply{ - Addr: addr.Resource, - Config: nil, // No configuration because we are destroying - State: &state, - Change: &change, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - Output: &state, - Error: &err, - }, - // Always write the resource back to the state deposed... if it - // was successfully destroyed it will be pruned. If it was not, it will - // be caught on the next run. - &EvalWriteStateDeposed{ - Addr: addr.Resource, - Key: n.DeposedKey, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - &EvalApplyPost{ - Addr: addr.Resource, - State: &state, - Error: &err, - }, - &EvalReturnError{ - Error: &err, - }, - &EvalUpdateStateHook{}, - }, - } -} - -// GraphNodeDeposer is an optional interface implemented by graph nodes that -// might create a single new deposed object for a specific associated resource -// instance, allowing a caller to optionally pre-allocate a DeposedKey for -// it. -type GraphNodeDeposer interface { - // SetPreallocatedDeposedKey will be called during graph construction - // if a particular node must use a pre-allocated deposed key if/when it - // "deposes" the current object of its associated resource instance. - SetPreallocatedDeposedKey(key states.DeposedKey) -} - -// graphNodeDeposer is an embeddable implementation of GraphNodeDeposer. -// Embed it in a node type to get automatic support for it, and then access -// the field PreallocatedDeposedKey to access any pre-allocated key. -type graphNodeDeposer struct { - PreallocatedDeposedKey states.DeposedKey -} - -func (n *graphNodeDeposer) SetPreallocatedDeposedKey(key states.DeposedKey) { - n.PreallocatedDeposedKey = key -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan.go deleted file mode 100644 index 2dc0df908e1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan.go +++ /dev/null @@ -1,166 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// NodePlannableResource represents a resource that is "plannable": -// it is ready to be planned in order to create a diff. -type NodePlannableResource struct { - *NodeAbstractResource - - // ForceCreateBeforeDestroy might be set via our GraphNodeDestroyerCBD - // during graph construction, if dependencies require us to force this - // on regardless of what the configuration says. - ForceCreateBeforeDestroy *bool -} - -var ( - _ GraphNodeSubPath = (*NodePlannableResource)(nil) - _ GraphNodeDestroyerCBD = (*NodePlannableResource)(nil) - _ GraphNodeDynamicExpandable = (*NodePlannableResource)(nil) - _ GraphNodeReferenceable = (*NodePlannableResource)(nil) - _ GraphNodeReferencer = (*NodePlannableResource)(nil) - _ GraphNodeResource = (*NodePlannableResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodePlannableResource)(nil) -) - -// GraphNodeEvalable -func (n *NodePlannableResource) EvalTree() EvalNode { - addr := n.ResourceAddr() - config := n.Config - - if config == nil { - // Nothing to do, then. - log.Printf("[TRACE] NodeApplyableResource: no configuration present for %s", addr) - return &EvalNoop{} - } - - // this ensures we can reference the resource even if the count is 0 - return &EvalWriteResourceState{ - Addr: addr.Resource, - Config: config, - ProviderAddr: n.ResolvedProvider, - } -} - -// GraphNodeDestroyerCBD -func (n *NodePlannableResource) CreateBeforeDestroy() bool { - if n.ForceCreateBeforeDestroy != nil { - return *n.ForceCreateBeforeDestroy - } - - // If we have no config, we just assume no - if n.Config == nil || n.Config.Managed == nil { - return false - } - - return n.Config.Managed.CreateBeforeDestroy -} - -// GraphNodeDestroyerCBD -func (n *NodePlannableResource) ModifyCreateBeforeDestroy(v bool) error { - n.ForceCreateBeforeDestroy = &v - return nil -} - -// GraphNodeDynamicExpandable -func (n *NodePlannableResource) DynamicExpand(ctx EvalContext) (*Graph, error) { - var diags tfdiags.Diagnostics - - count, countDiags := evaluateResourceCountExpression(n.Config.Count, ctx) - diags = diags.Append(countDiags) - if countDiags.HasErrors() { - return nil, diags.Err() - } - - forEachMap, forEachDiags := evaluateResourceForEachExpression(n.Config.ForEach, ctx) - if forEachDiags.HasErrors() { - return nil, diags.Err() - } - - // Next we need to potentially rename an instance address in the state - // if we're transitioning whether "count" is set at all. - fixResourceCountSetTransition(ctx, n.ResourceAddr(), count != -1) - - // Our graph transformers require access to the full state, so we'll - // temporarily lock it while we work on this. - state := ctx.State().Lock() - defer ctx.State().Unlock() - - // The concrete resource factory we'll use - concreteResource := func(a *NodeAbstractResourceInstance) dag.Vertex { - // Add the config and state since we don't do that via transforms - a.Config = n.Config - a.ResolvedProvider = n.ResolvedProvider - a.Schema = n.Schema - a.ProvisionerSchemas = n.ProvisionerSchemas - - return &NodePlannableResourceInstance{ - NodeAbstractResourceInstance: a, - - // By the time we're walking, we've figured out whether we need - // to force on CreateBeforeDestroy due to dependencies on other - // nodes that have it. - ForceCreateBeforeDestroy: n.CreateBeforeDestroy(), - } - } - - // The concrete resource factory we'll use for orphans - concreteResourceOrphan := func(a *NodeAbstractResourceInstance) dag.Vertex { - // Add the config and state since we don't do that via transforms - a.Config = n.Config - a.ResolvedProvider = n.ResolvedProvider - a.Schema = n.Schema - a.ProvisionerSchemas = n.ProvisionerSchemas - - return &NodePlannableResourceInstanceOrphan{ - NodeAbstractResourceInstance: a, - } - } - - // Start creating the steps - steps := []GraphTransformer{ - // Expand the count or for_each (if present) - &ResourceCountTransformer{ - Concrete: concreteResource, - Schema: n.Schema, - Count: count, - ForEach: forEachMap, - Addr: n.ResourceAddr(), - }, - - // Add the count/for_each orphans - &OrphanResourceCountTransformer{ - Concrete: concreteResourceOrphan, - Count: count, - ForEach: forEachMap, - Addr: n.ResourceAddr(), - State: state, - }, - - // Attach the state - &AttachStateTransformer{State: state}, - - // Targeting - &TargetsTransformer{Targets: 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: "NodePlannableResource", - } - graph, diags := b.Build(ctx.Path()) - return graph, diags.ErrWithWarnings() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_destroy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_destroy.go deleted file mode 100644 index 2c3a7012b94..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_destroy.go +++ /dev/null @@ -1,88 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// NodePlanDestroyableResourceInstance represents a resource that is ready -// to be planned for destruction. -type NodePlanDestroyableResourceInstance struct { - *NodeAbstractResourceInstance -} - -var ( - _ GraphNodeSubPath = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeReferenceable = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeReferencer = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeDestroyer = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeResource = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeAttachResourceConfig = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeAttachResourceState = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeEvalable = (*NodePlanDestroyableResourceInstance)(nil) - _ GraphNodeProviderConsumer = (*NodePlanDestroyableResourceInstance)(nil) -) - -// GraphNodeDestroyer -func (n *NodePlanDestroyableResourceInstance) DestroyAddr() *addrs.AbsResourceInstance { - addr := n.ResourceInstanceAddr() - return &addr -} - -// GraphNodeEvalable -func (n *NodePlanDestroyableResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - // Declare a bunch of variables that are used for state during - // evaluation. These are written to by address in the EvalNodes we - // declare below. - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - - if n.ResolvedProvider.ProviderConfig.Type == "" { - // Should never happen; indicates that the graph was not constructed - // correctly since we didn't get our provider attached. - panic(fmt.Sprintf("%T %q was not assigned a resolved provider", n, dag.VertexName(n))) - } - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - - Output: &state, - }, - &EvalDiffDestroy{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, - Output: &change, - }, - &EvalCheckPreventDestroy{ - Addr: addr.Resource, - Config: n.Config, - Change: &change, - }, - &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &change, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_instance.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_instance.go deleted file mode 100644 index ac4b24cf220..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_instance.go +++ /dev/null @@ -1,201 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/zclconf/go-cty/cty" -) - -// NodePlannableResourceInstance represents a _single_ resource -// instance that is plannable. This means this represents a single -// count index, for example. -type NodePlannableResourceInstance struct { - *NodeAbstractResourceInstance - ForceCreateBeforeDestroy bool -} - -var ( - _ GraphNodeSubPath = (*NodePlannableResourceInstance)(nil) - _ GraphNodeReferenceable = (*NodePlannableResourceInstance)(nil) - _ GraphNodeReferencer = (*NodePlannableResourceInstance)(nil) - _ GraphNodeResource = (*NodePlannableResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodePlannableResourceInstance)(nil) - _ GraphNodeAttachResourceConfig = (*NodePlannableResourceInstance)(nil) - _ GraphNodeAttachResourceState = (*NodePlannableResourceInstance)(nil) - _ GraphNodeEvalable = (*NodePlannableResourceInstance)(nil) -) - -// GraphNodeEvalable -func (n *NodePlannableResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - // Eval info is different depending on what kind of resource this is - switch addr.Resource.Resource.Mode { - case addrs.ManagedResourceMode: - return n.evalTreeManagedResource(addr) - case addrs.DataResourceMode: - return n.evalTreeDataResource(addr) - default: - panic(fmt.Errorf("unsupported resource mode %s", n.Config.Mode)) - } -} - -func (n *NodePlannableResourceInstance) evalTreeDataResource(addr addrs.AbsResourceInstance) EvalNode { - config := n.Config - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - var configVal cty.Value - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - - Output: &state, - }, - - // If we already have a non-planned state then we already dealt - // with this during the refresh walk and so we have nothing to do - // here. - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - depChanges := false - - // Check and see if any of our dependencies have changes. - changes := ctx.Changes() - for _, d := range n.StateReferences() { - ri, ok := d.(addrs.ResourceInstance) - if !ok { - continue - } - change := changes.GetResourceInstanceChange(ri.Absolute(ctx.Path()), states.CurrentGen) - if change != nil && change.Action != plans.NoOp { - depChanges = true - break - } - } - - refreshed := state != nil && state.Status != states.ObjectPlanned - - // If there are no dependency changes, and it's not a forced - // read because we there was no Refresh, then we don't need - // to re-read. If any dependencies have changes, it means - // our config may also have changes and we need to Read the - // data source again. - if !depChanges && refreshed { - return false, EvalEarlyExitError{} - } - return true, nil - }, - Then: EvalNoop{}, - }, - - &EvalValidateSelfRef{ - Addr: addr.Resource, - Config: config.Config, - ProviderSchema: &providerSchema, - }, - - &EvalReadData{ - Addr: addr.Resource, - Config: n.Config, - Dependencies: n.StateReferences(), - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - ForcePlanRead: true, // _always_ produce a Read change, even if the config seems ready - OutputChange: &change, - OutputValue: &configVal, - OutputState: &state, - }, - - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - - &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &change, - }, - }, - } -} - -func (n *NodePlannableResourceInstance) evalTreeManagedResource(addr addrs.AbsResourceInstance) EvalNode { - config := n.Config - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - - Output: &state, - }, - - &EvalValidateSelfRef{ - Addr: addr.Resource, - Config: config.Config, - ProviderSchema: &providerSchema, - }, - - &EvalDiff{ - Addr: addr.Resource, - Config: n.Config, - CreateBeforeDestroy: n.ForceCreateBeforeDestroy, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - OutputChange: &change, - OutputState: &state, - }, - &EvalCheckPreventDestroy{ - Addr: addr.Resource, - Config: n.Config, - Change: &change, - }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - State: &state, - ProviderSchema: &providerSchema, - }, - &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &change, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_orphan.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_orphan.go deleted file mode 100644 index 8e4f7148ff9..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_orphan.go +++ /dev/null @@ -1,84 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// NodePlannableResourceInstanceOrphan represents a resource that is "applyable": -// it is ready to be applied and is represented by a diff. -type NodePlannableResourceInstanceOrphan struct { - *NodeAbstractResourceInstance -} - -var ( - _ GraphNodeSubPath = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeReferenceable = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeReferencer = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeResource = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeResourceInstance = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeAttachResourceConfig = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeAttachResourceState = (*NodePlannableResourceInstanceOrphan)(nil) - _ GraphNodeEvalable = (*NodePlannableResourceInstanceOrphan)(nil) -) - -var ( - _ GraphNodeEvalable = (*NodePlannableResourceInstanceOrphan)(nil) -) - -func (n *NodePlannableResourceInstanceOrphan) Name() string { - return n.ResourceInstanceAddr().String() + " (orphan)" -} - -// GraphNodeEvalable -func (n *NodePlannableResourceInstanceOrphan) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - // Declare a bunch of variables that are used for state during - // evaluation. Most of this are written to by-address below. - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - var provider providers.Interface - var providerSchema *ProviderSchema - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - - Output: &state, - }, - &EvalDiffDestroy{ - Addr: addr.Resource, - State: &state, - ProviderAddr: n.ResolvedProvider, - Output: &change, - OutputState: &state, // Will point to a nil state after this complete, signalling destroyed - }, - &EvalCheckPreventDestroy{ - Addr: addr.Resource, - Config: n.Config, - Change: &change, - }, - &EvalWriteDiff{ - Addr: addr.Resource, - ProviderSchema: &providerSchema, - Change: &change, - }, - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_refresh.go deleted file mode 100644 index dcab37270ca..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_refresh.go +++ /dev/null @@ -1,296 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// NodeRefreshableManagedResource represents a resource that is expanabled into -// NodeRefreshableManagedResourceInstance. Resource count orphans are also added. -type NodeRefreshableManagedResource struct { - *NodeAbstractResource -} - -var ( - _ GraphNodeSubPath = (*NodeRefreshableManagedResource)(nil) - _ GraphNodeDynamicExpandable = (*NodeRefreshableManagedResource)(nil) - _ GraphNodeReferenceable = (*NodeRefreshableManagedResource)(nil) - _ GraphNodeReferencer = (*NodeRefreshableManagedResource)(nil) - _ GraphNodeResource = (*NodeRefreshableManagedResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodeRefreshableManagedResource)(nil) -) - -// GraphNodeDynamicExpandable -func (n *NodeRefreshableManagedResource) DynamicExpand(ctx EvalContext) (*Graph, error) { - var diags tfdiags.Diagnostics - - count, countDiags := evaluateResourceCountExpression(n.Config.Count, ctx) - diags = diags.Append(countDiags) - if countDiags.HasErrors() { - return nil, diags.Err() - } - - forEachMap, forEachDiags := evaluateResourceForEachExpression(n.Config.ForEach, ctx) - if forEachDiags.HasErrors() { - return nil, diags.Err() - } - - // Next we need to potentially rename an instance address in the state - // if we're transitioning whether "count" is set at all. - fixResourceCountSetTransition(ctx, n.ResourceAddr(), count != -1) - - // Our graph transformers require access to the full state, so we'll - // temporarily lock it while we work on this. - state := ctx.State().Lock() - defer ctx.State().Unlock() - - // The concrete resource factory we'll use - concreteResource := func(a *NodeAbstractResourceInstance) dag.Vertex { - // Add the config and state since we don't do that via transforms - a.Config = n.Config - a.ResolvedProvider = n.ResolvedProvider - - return &NodeRefreshableManagedResourceInstance{ - NodeAbstractResourceInstance: a, - } - } - - // Start creating the steps - steps := []GraphTransformer{ - // Expand the count. - &ResourceCountTransformer{ - Concrete: concreteResource, - Schema: n.Schema, - Count: count, - ForEach: forEachMap, - Addr: n.ResourceAddr(), - }, - - // Add the count orphans to make sure these resources are accounted for - // during a scale in. - &OrphanResourceCountTransformer{ - Concrete: concreteResource, - Count: count, - ForEach: forEachMap, - Addr: n.ResourceAddr(), - State: state, - }, - - // Attach the state - &AttachStateTransformer{State: state}, - - // Targeting - &TargetsTransformer{Targets: 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", - } - - graph, diags := b.Build(ctx.Path()) - return graph, diags.ErrWithWarnings() -} - -// NodeRefreshableManagedResourceInstance represents a resource that is "applyable": -// it is ready to be applied and is represented by a diff. -type NodeRefreshableManagedResourceInstance struct { - *NodeAbstractResourceInstance -} - -var ( - _ GraphNodeSubPath = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeReferenceable = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeReferencer = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeDestroyer = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeResource = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeAttachResourceConfig = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeAttachResourceState = (*NodeRefreshableManagedResourceInstance)(nil) - _ GraphNodeEvalable = (*NodeRefreshableManagedResourceInstance)(nil) -) - -// GraphNodeDestroyer -func (n *NodeRefreshableManagedResourceInstance) DestroyAddr() *addrs.AbsResourceInstance { - addr := n.ResourceInstanceAddr() - return &addr -} - -// GraphNodeEvalable -func (n *NodeRefreshableManagedResourceInstance) EvalTree() EvalNode { - addr := n.ResourceInstanceAddr() - - // Eval info is different depending on what kind of resource this is - switch addr.Resource.Resource.Mode { - case addrs.ManagedResourceMode: - if n.ResourceState == nil { - log.Printf("[TRACE] NodeRefreshableManagedResourceInstance: %s has no existing state to refresh", addr) - return n.evalTreeManagedResourceNoState() - } - log.Printf("[TRACE] NodeRefreshableManagedResourceInstance: %s will be refreshed", addr) - return n.evalTreeManagedResource() - - case addrs.DataResourceMode: - // Get the data source node. If we don't have a configuration - // then it is an orphan so we destroy it (remove it from the state). - var dn GraphNodeEvalable - if n.Config != nil { - dn = &NodeRefreshableDataResourceInstance{ - NodeAbstractResourceInstance: n.NodeAbstractResourceInstance, - } - } else { - dn = &NodeDestroyableDataResourceInstance{ - NodeAbstractResourceInstance: n.NodeAbstractResourceInstance, - } - } - - return dn.EvalTree() - default: - panic(fmt.Errorf("unsupported resource mode %s", addr.Resource.Resource.Mode)) - } -} - -func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResource() EvalNode { - addr := n.ResourceInstanceAddr() - - // Declare a bunch of variables that are used for state during - // evaluation. Most of this are written to by-address below. - var provider providers.Interface - var providerSchema *ProviderSchema - var state *states.ResourceInstanceObject - - // This happened during initial development. All known cases were - // fixed and tested but as a sanity check let's assert here. - if n.ResourceState == nil { - err := fmt.Errorf( - "No resource state attached for addr: %s\n\n"+ - "This is a bug. Please report this to Terraform with your configuration\n"+ - "and state attached. Please be careful to scrub any sensitive information.", - addr) - return &EvalReturnError{Error: &err} - } - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - - Output: &state, - }, - - &EvalRefresh{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - Provider: &provider, - ProviderSchema: &providerSchema, - State: &state, - Output: &state, - }, - - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - }, - } -} - -// evalTreeManagedResourceNoState produces an EvalSequence for refresh resource -// nodes that don't have state attached. An example of where this functionality -// is useful is when a resource that already exists in state is being scaled -// out, ie: has its resource count increased. In this case, the scaled out node -// needs to be available to other nodes (namely data sources) that may depend -// on it for proper interpolation, or confusing "index out of range" errors can -// occur. -// -// The steps in this sequence are very similar to the steps carried out in -// plan, but nothing is done with the diff after it is created - it is dropped, -// and its changes are not counted in the UI. -func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResourceNoState() EvalNode { - addr := n.ResourceInstanceAddr() - - // Declare a bunch of variables that are used for state during - // evaluation. Most of this are written to by-address below. - var provider providers.Interface - var providerSchema *ProviderSchema - var change *plans.ResourceInstanceChange - var state *states.ResourceInstanceObject - - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - - &EvalReadState{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - - Output: &state, - }, - - &EvalDiff{ - Addr: addr.Resource, - Config: n.Config, - Provider: &provider, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - OutputChange: &change, - OutputState: &state, - Stub: true, - }, - - &EvalWriteState{ - Addr: addr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - - // We must also save the planned change, so that expressions in - // other nodes, such as provider configurations and data resources, - // can work with the planned new value. - // - // This depends on the fact that Context.Refresh creates a - // temporary new empty changeset for the duration of its graph - // walk, and so this recorded change will be discarded immediately - // after the refresh walk completes. - &EvalWriteDiff{ - Addr: addr.Resource, - Change: &change, - ProviderSchema: &providerSchema, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_validate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_validate.go deleted file mode 100644 index f0eb18a0655..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_validate.go +++ /dev/null @@ -1,90 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" - "github.com/zclconf/go-cty/cty" -) - -// NodeValidatableResource represents a resource that is used for validation -// only. -type NodeValidatableResource struct { - *NodeAbstractResource -} - -var ( - _ GraphNodeSubPath = (*NodeValidatableResource)(nil) - _ GraphNodeEvalable = (*NodeValidatableResource)(nil) - _ GraphNodeReferenceable = (*NodeValidatableResource)(nil) - _ GraphNodeReferencer = (*NodeValidatableResource)(nil) - _ GraphNodeResource = (*NodeValidatableResource)(nil) - _ GraphNodeAttachResourceConfig = (*NodeValidatableResource)(nil) -) - -// GraphNodeEvalable -func (n *NodeValidatableResource) EvalTree() EvalNode { - addr := n.ResourceAddr() - config := n.Config - - // Declare the variables will be used are used to pass values along - // the evaluation sequence below. These are written to via pointers - // passed to the EvalNodes. - var provider providers.Interface - var providerSchema *ProviderSchema - var configVal cty.Value - - seq := &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalValidateResource{ - Addr: addr.Resource, - Provider: &provider, - ProviderSchema: &providerSchema, - Config: config, - ConfigVal: &configVal, - }, - }, - } - - if managed := n.Config.Managed; managed != nil { - hasCount := n.Config.Count != nil - hasForEach := n.Config.ForEach != nil - - // Validate all the provisioners - for _, p := range managed.Provisioners { - var provisioner provisioners.Interface - var provisionerSchema *configschema.Block - - if p.Connection == nil { - p.Connection = config.Managed.Connection - } else if config.Managed.Connection != nil { - p.Connection.Config = configs.MergeBodies(config.Managed.Connection.Config, p.Connection.Config) - } - - seq.Nodes = append( - seq.Nodes, - &EvalGetProvisioner{ - Name: p.Type, - Output: &provisioner, - Schema: &provisionerSchema, - }, - &EvalValidateProvisioner{ - ResourceAddr: addr.Resource, - Provisioner: &provisioner, - Schema: &provisionerSchema, - Config: p, - ResourceHasCount: hasCount, - ResourceHasForEach: hasForEach, - }, - ) - } - } - - return seq -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_root_variable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_root_variable.go deleted file mode 100644 index 844d060c9f1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_root_variable.go +++ /dev/null @@ -1,44 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// NodeRootVariable represents a root variable input. -type NodeRootVariable struct { - Addr addrs.InputVariable - Config *configs.Variable -} - -var ( - _ GraphNodeSubPath = (*NodeRootVariable)(nil) - _ GraphNodeReferenceable = (*NodeRootVariable)(nil) - _ dag.GraphNodeDotter = (*NodeApplyableModuleVariable)(nil) -) - -func (n *NodeRootVariable) Name() string { - return n.Addr.String() -} - -// GraphNodeSubPath -func (n *NodeRootVariable) Path() addrs.ModuleInstance { - return addrs.RootModuleInstance -} - -// GraphNodeReferenceable -func (n *NodeRootVariable) ReferenceableAddrs() []addrs.Referenceable { - return []addrs.Referenceable{n.Addr} -} - -// dag.GraphNodeDotter impl. -func (n *NodeRootVariable) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "note", - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/path.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/path.go deleted file mode 100644 index 19e3469cb35..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/path.go +++ /dev/null @@ -1,17 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// PathObjectCacheKey is like PathCacheKey but includes an additional name -// to be included in the key, for module-namespaced objects. -// -// The result of this function is guaranteed unique for any distinct pair -// of path and name, but is not guaranteed to be in any particular format -// and in particular should never be shown to end-users. -func PathObjectCacheKey(path addrs.ModuleInstance, objectName string) string { - return fmt.Sprintf("%s|%s", path.String(), objectName) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/plan.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/plan.go deleted file mode 100644 index 5c19f6e7cf8..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/plan.go +++ /dev/null @@ -1,94 +0,0 @@ -package terraform - -import ( - "bytes" - "encoding/gob" - "fmt" - "io" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/zclconf/go-cty/cty" -) - -func init() { - gob.Register(make([]interface{}, 0)) - gob.Register(make([]map[string]interface{}, 0)) - gob.Register(make(map[string]interface{})) - gob.Register(make(map[string]string)) -} - -// Plan represents a single Terraform execution plan, which contains -// all the information necessary to make an infrastructure change. -// -// A plan has to contain basically the entire state of the world -// necessary to make a change: the state, diff, config, backend config, etc. -// This is so that it can run alone without any other data. -type Plan struct { - // Diff describes the resource actions that must be taken when this - // plan is applied. - Diff *Diff - - // Config represents the entire configuration that was present when this - // plan was created. - Config *configs.Config - - // State is the Terraform state that was current when this plan was - // created. - // - // It is not allowed to apply a plan that has a stale state, since its - // diff could be outdated. - State *State - - // Vars retains the variables that were set when creating the plan, so - // that the same variables can be applied during apply. - Vars map[string]cty.Value - - // Targets, if non-empty, contains a set of resource address strings that - // identify graph nodes that were selected as targets for plan. - // - // When targets are set, any graph node that is not directly targeted or - // indirectly targeted via dependencies is excluded from the graph. - Targets []string - - // TerraformVersion is the version of Terraform that was used to create - // this plan. - // - // It is not allowed to apply a plan created with a different version of - // Terraform, since the other fields of this structure may be interpreted - // in different ways between versions. - TerraformVersion string - - // ProviderSHA256s is a map giving the SHA256 hashes of the exact binaries - // used as plugins for each provider during plan. - // - // These must match between plan and apply to ensure that the diff is - // correctly interpreted, since different provider versions may have - // different attributes or attribute value constraints. - ProviderSHA256s map[string][]byte - - // Backend is the backend that this plan should use and store data with. - Backend *BackendState - - // Destroy indicates that this plan was created for a full destroy operation - Destroy bool -} - -func (p *Plan) String() string { - buf := new(bytes.Buffer) - buf.WriteString("DIFF:\n\n") - buf.WriteString(p.Diff.String()) - buf.WriteString("\n\nSTATE:\n\n") - buf.WriteString(p.State.String()) - return buf.String() -} - -// ReadPlan reads a plan structure out of a reader in the format that -// was written by WritePlan. -func ReadPlan(src io.Reader) (*Plan, error) { - return nil, fmt.Errorf("terraform.ReadPlan is no longer in use; use planfile.Open instead") -} - -// WritePlan writes a plan somewhere in a binary format. -func WritePlan(d *Plan, dst io.Writer) error { - return fmt.Errorf("terraform.WritePlan is no longer in use; use planfile.Create instead") -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provider_mock.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provider_mock.go deleted file mode 100644 index 7e401f33ebf..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provider_mock.go +++ /dev/null @@ -1,521 +0,0 @@ -package terraform - -import ( - "encoding/json" - "fmt" - "sync" - - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -var _ providers.Interface = (*MockProvider)(nil) - -// MockProvider implements providers.Interface but mocks out all the -// calls for testing purposes. -type MockProvider struct { - sync.Mutex - - // Anything you want, in case you need to store extra data with the mock. - Meta interface{} - - GetSchemaCalled bool - GetSchemaReturn *ProviderSchema // This is using ProviderSchema directly rather than providers.GetSchemaResponse for compatibility with old tests - - PrepareProviderConfigCalled bool - PrepareProviderConfigResponse providers.PrepareProviderConfigResponse - PrepareProviderConfigRequest providers.PrepareProviderConfigRequest - PrepareProviderConfigFn func(providers.PrepareProviderConfigRequest) providers.PrepareProviderConfigResponse - - ValidateResourceTypeConfigCalled bool - ValidateResourceTypeConfigTypeName string - ValidateResourceTypeConfigResponse providers.ValidateResourceTypeConfigResponse - ValidateResourceTypeConfigRequest providers.ValidateResourceTypeConfigRequest - ValidateResourceTypeConfigFn func(providers.ValidateResourceTypeConfigRequest) providers.ValidateResourceTypeConfigResponse - - ValidateDataSourceConfigCalled bool - ValidateDataSourceConfigTypeName string - ValidateDataSourceConfigResponse providers.ValidateDataSourceConfigResponse - ValidateDataSourceConfigRequest providers.ValidateDataSourceConfigRequest - ValidateDataSourceConfigFn func(providers.ValidateDataSourceConfigRequest) providers.ValidateDataSourceConfigResponse - - UpgradeResourceStateCalled bool - UpgradeResourceStateTypeName string - UpgradeResourceStateResponse providers.UpgradeResourceStateResponse - UpgradeResourceStateRequest providers.UpgradeResourceStateRequest - UpgradeResourceStateFn func(providers.UpgradeResourceStateRequest) providers.UpgradeResourceStateResponse - - ConfigureCalled bool - ConfigureResponse providers.ConfigureResponse - ConfigureRequest providers.ConfigureRequest - ConfigureNewFn func(providers.ConfigureRequest) providers.ConfigureResponse // Named ConfigureNewFn so we can still have the legacy ConfigureFn declared below - - StopCalled bool - StopFn func() error - StopResponse error - - ReadResourceCalled bool - ReadResourceResponse providers.ReadResourceResponse - ReadResourceRequest providers.ReadResourceRequest - ReadResourceFn func(providers.ReadResourceRequest) providers.ReadResourceResponse - - PlanResourceChangeCalled bool - PlanResourceChangeResponse providers.PlanResourceChangeResponse - PlanResourceChangeRequest providers.PlanResourceChangeRequest - PlanResourceChangeFn func(providers.PlanResourceChangeRequest) providers.PlanResourceChangeResponse - - ApplyResourceChangeCalled bool - ApplyResourceChangeResponse providers.ApplyResourceChangeResponse - ApplyResourceChangeRequest providers.ApplyResourceChangeRequest - ApplyResourceChangeFn func(providers.ApplyResourceChangeRequest) providers.ApplyResourceChangeResponse - - ImportResourceStateCalled bool - ImportResourceStateResponse providers.ImportResourceStateResponse - ImportResourceStateRequest providers.ImportResourceStateRequest - ImportResourceStateFn func(providers.ImportResourceStateRequest) providers.ImportResourceStateResponse - // Legacy return type for existing tests, which will be shimmed into an - // ImportResourceStateResponse if set - ImportStateReturn []*InstanceState - - ReadDataSourceCalled bool - ReadDataSourceResponse providers.ReadDataSourceResponse - ReadDataSourceRequest providers.ReadDataSourceRequest - ReadDataSourceFn func(providers.ReadDataSourceRequest) providers.ReadDataSourceResponse - - CloseCalled bool - CloseError error - - // Legacy callbacks: if these are set, we will shim incoming calls for - // new-style methods to these old-fashioned terraform.ResourceProvider - // mock callbacks, for the benefit of older tests that were written against - // the old mock API. - ValidateFn func(c *ResourceConfig) (ws []string, es []error) - ConfigureFn func(c *ResourceConfig) error - DiffFn func(info *InstanceInfo, s *InstanceState, c *ResourceConfig) (*InstanceDiff, error) - ApplyFn func(info *InstanceInfo, s *InstanceState, d *InstanceDiff) (*InstanceState, error) -} - -func (p *MockProvider) GetSchema() providers.GetSchemaResponse { - p.Lock() - defer p.Unlock() - p.GetSchemaCalled = true - return p.getSchema() -} - -func (p *MockProvider) getSchema() providers.GetSchemaResponse { - // This version of getSchema doesn't do any locking, so it's suitable to - // call from other methods of this mock as long as they are already - // holding the lock. - - ret := providers.GetSchemaResponse{ - Provider: providers.Schema{}, - DataSources: map[string]providers.Schema{}, - ResourceTypes: map[string]providers.Schema{}, - } - if p.GetSchemaReturn != nil { - ret.Provider.Block = p.GetSchemaReturn.Provider - for n, s := range p.GetSchemaReturn.DataSources { - ret.DataSources[n] = providers.Schema{ - Block: s, - } - } - for n, s := range p.GetSchemaReturn.ResourceTypes { - ret.ResourceTypes[n] = providers.Schema{ - Version: int64(p.GetSchemaReturn.ResourceTypeSchemaVersions[n]), - Block: s, - } - } - } - - return ret -} - -func (p *MockProvider) PrepareProviderConfig(r providers.PrepareProviderConfigRequest) providers.PrepareProviderConfigResponse { - p.Lock() - defer p.Unlock() - - p.PrepareProviderConfigCalled = true - p.PrepareProviderConfigRequest = r - if p.PrepareProviderConfigFn != nil { - return p.PrepareProviderConfigFn(r) - } - return p.PrepareProviderConfigResponse -} - -func (p *MockProvider) ValidateResourceTypeConfig(r providers.ValidateResourceTypeConfigRequest) providers.ValidateResourceTypeConfigResponse { - p.Lock() - defer p.Unlock() - - p.ValidateResourceTypeConfigCalled = true - p.ValidateResourceTypeConfigRequest = r - - if p.ValidateFn != nil { - resp := p.getSchema() - schema := resp.Provider.Block - rc := NewResourceConfigShimmed(r.Config, schema) - warns, errs := p.ValidateFn(rc) - ret := providers.ValidateResourceTypeConfigResponse{} - for _, warn := range warns { - ret.Diagnostics = ret.Diagnostics.Append(tfdiags.SimpleWarning(warn)) - } - for _, err := range errs { - ret.Diagnostics = ret.Diagnostics.Append(err) - } - } - if p.ValidateResourceTypeConfigFn != nil { - return p.ValidateResourceTypeConfigFn(r) - } - - return p.ValidateResourceTypeConfigResponse -} - -func (p *MockProvider) ValidateDataSourceConfig(r providers.ValidateDataSourceConfigRequest) providers.ValidateDataSourceConfigResponse { - p.Lock() - defer p.Unlock() - - p.ValidateDataSourceConfigCalled = true - p.ValidateDataSourceConfigRequest = r - - if p.ValidateDataSourceConfigFn != nil { - return p.ValidateDataSourceConfigFn(r) - } - - return p.ValidateDataSourceConfigResponse -} - -func (p *MockProvider) UpgradeResourceState(r providers.UpgradeResourceStateRequest) providers.UpgradeResourceStateResponse { - p.Lock() - defer p.Unlock() - - schemas := p.getSchema() - schema := schemas.ResourceTypes[r.TypeName] - schemaType := schema.Block.ImpliedType() - - p.UpgradeResourceStateCalled = true - p.UpgradeResourceStateRequest = r - - if p.UpgradeResourceStateFn != nil { - return p.UpgradeResourceStateFn(r) - } - - resp := p.UpgradeResourceStateResponse - - if resp.UpgradedState == cty.NilVal { - switch { - case r.RawStateFlatmap != nil: - v, err := hcl2shim.HCL2ValueFromFlatmap(r.RawStateFlatmap, schemaType) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.UpgradedState = v - case len(r.RawStateJSON) > 0: - v, err := ctyjson.Unmarshal(r.RawStateJSON, schemaType) - - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - return resp - } - resp.UpgradedState = v - } - } - return resp -} - -func (p *MockProvider) Configure(r providers.ConfigureRequest) providers.ConfigureResponse { - p.Lock() - defer p.Unlock() - - p.ConfigureCalled = true - p.ConfigureRequest = r - - if p.ConfigureFn != nil { - resp := p.getSchema() - schema := resp.Provider.Block - rc := NewResourceConfigShimmed(r.Config, schema) - ret := providers.ConfigureResponse{} - - err := p.ConfigureFn(rc) - if err != nil { - ret.Diagnostics = ret.Diagnostics.Append(err) - } - return ret - } - if p.ConfigureNewFn != nil { - return p.ConfigureNewFn(r) - } - - return p.ConfigureResponse -} - -func (p *MockProvider) Stop() error { - // We intentionally don't lock in this one because the whole point of this - // method is to be called concurrently with another operation that can - // be cancelled. The provider itself is responsible for handling - // any concurrency concerns in this case. - - p.StopCalled = true - if p.StopFn != nil { - return p.StopFn() - } - - return p.StopResponse -} - -func (p *MockProvider) ReadResource(r providers.ReadResourceRequest) providers.ReadResourceResponse { - p.Lock() - defer p.Unlock() - - p.ReadResourceCalled = true - p.ReadResourceRequest = r - - if p.ReadResourceFn != nil { - return p.ReadResourceFn(r) - } - - // make sure the NewState fits the schema - newState, err := p.GetSchemaReturn.ResourceTypes[r.TypeName].CoerceValue(p.ReadResourceResponse.NewState) - if err != nil { - panic(err) - } - resp := p.ReadResourceResponse - resp.NewState = newState - - return resp -} - -func (p *MockProvider) PlanResourceChange(r providers.PlanResourceChangeRequest) providers.PlanResourceChangeResponse { - p.Lock() - defer p.Unlock() - - p.PlanResourceChangeCalled = true - p.PlanResourceChangeRequest = r - - if p.DiffFn != nil { - ps := p.getSchema() - if ps.ResourceTypes == nil || ps.ResourceTypes[r.TypeName].Block == nil { - return providers.PlanResourceChangeResponse{ - Diagnostics: tfdiags.Diagnostics(nil).Append(fmt.Printf("mock provider has no schema for resource type %s", r.TypeName)), - } - } - schema := ps.ResourceTypes[r.TypeName].Block - info := &InstanceInfo{ - Type: r.TypeName, - } - priorState := NewInstanceStateShimmedFromValue(r.PriorState, 0) - cfg := NewResourceConfigShimmed(r.Config, schema) - - legacyDiff, err := p.DiffFn(info, priorState, cfg) - - var res providers.PlanResourceChangeResponse - res.PlannedState = r.ProposedNewState - if err != nil { - res.Diagnostics = res.Diagnostics.Append(err) - } - if legacyDiff != nil { - newVal, err := legacyDiff.ApplyToValue(r.PriorState, schema) - if err != nil { - res.Diagnostics = res.Diagnostics.Append(err) - } - - res.PlannedState = newVal - - var requiresNew []string - for attr, d := range legacyDiff.Attributes { - if d.RequiresNew { - requiresNew = append(requiresNew, attr) - } - } - requiresReplace, err := hcl2shim.RequiresReplace(requiresNew, schema.ImpliedType()) - if err != nil { - res.Diagnostics = res.Diagnostics.Append(err) - } - res.RequiresReplace = requiresReplace - } - return res - } - if p.PlanResourceChangeFn != nil { - return p.PlanResourceChangeFn(r) - } - - return p.PlanResourceChangeResponse -} - -func (p *MockProvider) ApplyResourceChange(r providers.ApplyResourceChangeRequest) providers.ApplyResourceChangeResponse { - p.Lock() - p.ApplyResourceChangeCalled = true - p.ApplyResourceChangeRequest = r - p.Unlock() - - if p.ApplyFn != nil { - // ApplyFn is a special callback fashioned after our old provider - // interface, which expected to be given an actual diff rather than - // separate old/new values to apply. Therefore we need to approximate - // a diff here well enough that _most_ of our legacy ApplyFns in old - // tests still see the behavior they are expecting. New tests should - // not use this, and should instead use ApplyResourceChangeFn directly. - providerSchema := p.getSchema() - schema, ok := providerSchema.ResourceTypes[r.TypeName] - if !ok { - return providers.ApplyResourceChangeResponse{ - Diagnostics: tfdiags.Diagnostics(nil).Append(fmt.Errorf("no mocked schema available for resource type %s", r.TypeName)), - } - } - - info := &InstanceInfo{ - Type: r.TypeName, - } - - priorVal := r.PriorState - plannedVal := r.PlannedState - priorMap := hcl2shim.FlatmapValueFromHCL2(priorVal) - plannedMap := hcl2shim.FlatmapValueFromHCL2(plannedVal) - s := NewInstanceStateShimmedFromValue(priorVal, 0) - d := &InstanceDiff{ - Attributes: make(map[string]*ResourceAttrDiff), - } - if plannedMap == nil { // destroying, then - d.Destroy = true - // Destroy diffs don't have any attribute diffs - } else { - if priorMap == nil { // creating, then - // We'll just make an empty prior map to make things easier below. - priorMap = make(map[string]string) - } - - for k, new := range plannedMap { - old := priorMap[k] - newComputed := false - if new == hcl2shim.UnknownVariableValue { - new = "" - newComputed = true - } - d.Attributes[k] = &ResourceAttrDiff{ - Old: old, - New: new, - NewComputed: newComputed, - Type: DiffAttrInput, // not generally used in tests, so just hard-coded - } - } - // Also need any attributes that were removed in "planned" - for k, old := range priorMap { - if _, ok := plannedMap[k]; ok { - continue - } - d.Attributes[k] = &ResourceAttrDiff{ - Old: old, - NewRemoved: true, - Type: DiffAttrInput, - } - } - } - newState, err := p.ApplyFn(info, s, d) - resp := providers.ApplyResourceChangeResponse{} - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - } - if newState != nil { - var newVal cty.Value - if newState != nil { - var err error - newVal, err = newState.AttrsAsObjectValue(schema.Block.ImpliedType()) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - } - } else { - // If apply returned a nil new state then that's the old way to - // indicate that the object was destroyed. Our new interface calls - // for that to be signalled as a null value. - newVal = cty.NullVal(schema.Block.ImpliedType()) - } - resp.NewState = newVal - } - - return resp - } - if p.ApplyResourceChangeFn != nil { - return p.ApplyResourceChangeFn(r) - } - - return p.ApplyResourceChangeResponse -} - -func (p *MockProvider) ImportResourceState(r providers.ImportResourceStateRequest) providers.ImportResourceStateResponse { - p.Lock() - defer p.Unlock() - - if p.ImportStateReturn != nil { - for _, is := range p.ImportStateReturn { - if is.Attributes == nil { - is.Attributes = make(map[string]string) - } - is.Attributes["id"] = is.ID - - typeName := is.Ephemeral.Type - // Use the requested type if the resource has no type of it's own. - // We still return the empty type, which will error, but this prevents a panic. - if typeName == "" { - typeName = r.TypeName - } - - schema := p.GetSchemaReturn.ResourceTypes[typeName] - if schema == nil { - panic("no schema found for " + typeName) - } - - private, err := json.Marshal(is.Meta) - if err != nil { - panic(err) - } - - state, err := hcl2shim.HCL2ValueFromFlatmap(is.Attributes, schema.ImpliedType()) - if err != nil { - panic(err) - } - - state, err = schema.CoerceValue(state) - if err != nil { - panic(err) - } - - p.ImportResourceStateResponse.ImportedResources = append( - p.ImportResourceStateResponse.ImportedResources, - providers.ImportedResource{ - TypeName: is.Ephemeral.Type, - State: state, - Private: private, - }) - } - } - - p.ImportResourceStateCalled = true - p.ImportResourceStateRequest = r - if p.ImportResourceStateFn != nil { - return p.ImportResourceStateFn(r) - } - - return p.ImportResourceStateResponse -} - -func (p *MockProvider) ReadDataSource(r providers.ReadDataSourceRequest) providers.ReadDataSourceResponse { - p.Lock() - defer p.Unlock() - - p.ReadDataSourceCalled = true - p.ReadDataSourceRequest = r - - if p.ReadDataSourceFn != nil { - return p.ReadDataSourceFn(r) - } - - return p.ReadDataSourceResponse -} - -func (p *MockProvider) Close() error { - p.CloseCalled = true - return p.CloseError -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provisioner_mock.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provisioner_mock.go deleted file mode 100644 index 93b19be57d4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provisioner_mock.go +++ /dev/null @@ -1,154 +0,0 @@ -package terraform - -import ( - "fmt" - "sync" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" -) - -var _ provisioners.Interface = (*MockProvisioner)(nil) - -// MockProvisioner implements provisioners.Interface but mocks out all the -// calls for testing purposes. -type MockProvisioner struct { - sync.Mutex - // Anything you want, in case you need to store extra data with the mock. - Meta interface{} - - GetSchemaCalled bool - GetSchemaResponse provisioners.GetSchemaResponse - - ValidateProvisionerConfigCalled bool - ValidateProvisionerConfigRequest provisioners.ValidateProvisionerConfigRequest - ValidateProvisionerConfigResponse provisioners.ValidateProvisionerConfigResponse - ValidateProvisionerConfigFn func(provisioners.ValidateProvisionerConfigRequest) provisioners.ValidateProvisionerConfigResponse - - ProvisionResourceCalled bool - ProvisionResourceRequest provisioners.ProvisionResourceRequest - ProvisionResourceResponse provisioners.ProvisionResourceResponse - ProvisionResourceFn func(provisioners.ProvisionResourceRequest) provisioners.ProvisionResourceResponse - - StopCalled bool - StopResponse error - StopFn func() error - - CloseCalled bool - CloseResponse error - CloseFn func() error - - // Legacy callbacks: if these are set, we will shim incoming calls for - // new-style methods to these old-fashioned terraform.ResourceProvider - // mock callbacks, for the benefit of older tests that were written against - // the old mock API. - ApplyFn func(rs *InstanceState, c *ResourceConfig) error -} - -func (p *MockProvisioner) GetSchema() provisioners.GetSchemaResponse { - p.Lock() - defer p.Unlock() - - p.GetSchemaCalled = true - return p.getSchema() -} - -// getSchema is the implementation of GetSchema, which can be called from other -// methods on MockProvisioner that may already be holding the lock. -func (p *MockProvisioner) getSchema() provisioners.GetSchemaResponse { - return p.GetSchemaResponse -} - -func (p *MockProvisioner) ValidateProvisionerConfig(r provisioners.ValidateProvisionerConfigRequest) provisioners.ValidateProvisionerConfigResponse { - p.Lock() - defer p.Unlock() - - p.ValidateProvisionerConfigCalled = true - p.ValidateProvisionerConfigRequest = r - if p.ValidateProvisionerConfigFn != nil { - return p.ValidateProvisionerConfigFn(r) - } - return p.ValidateProvisionerConfigResponse -} - -func (p *MockProvisioner) ProvisionResource(r provisioners.ProvisionResourceRequest) provisioners.ProvisionResourceResponse { - p.Lock() - defer p.Unlock() - - p.ProvisionResourceCalled = true - p.ProvisionResourceRequest = r - if p.ApplyFn != nil { - if !r.Config.IsKnown() { - panic(fmt.Sprintf("cannot provision with unknown value: %#v", r.Config)) - } - - schema := p.getSchema() - rc := NewResourceConfigShimmed(r.Config, schema.Provisioner) - connVal := r.Connection - connMap := map[string]string{} - - if !connVal.IsNull() && connVal.IsKnown() { - for it := connVal.ElementIterator(); it.Next(); { - ak, av := it.Element() - name := ak.AsString() - - if !av.IsKnown() || av.IsNull() { - continue - } - - av, _ = convert.Convert(av, cty.String) - connMap[name] = av.AsString() - } - } - - // We no longer pass the full instance state to a provisioner, so we'll - // construct a partial one that should be good enough for what existing - // test mocks need. - is := &InstanceState{ - Ephemeral: EphemeralState{ - ConnInfo: connMap, - }, - } - var resp provisioners.ProvisionResourceResponse - err := p.ApplyFn(is, rc) - if err != nil { - resp.Diagnostics = resp.Diagnostics.Append(err) - } - return resp - } - if p.ProvisionResourceFn != nil { - fn := p.ProvisionResourceFn - p.Unlock() - return fn(r) - } - - return p.ProvisionResourceResponse -} - -func (p *MockProvisioner) Stop() error { - // We intentionally don't lock in this one because the whole point of this - // method is to be called concurrently with another operation that can - // be cancelled. The provisioner itself is responsible for handling - // any concurrency concerns in this case. - - p.StopCalled = true - if p.StopFn != nil { - return p.StopFn() - } - - return p.StopResponse -} - -func (p *MockProvisioner) Close() error { - p.Lock() - defer p.Unlock() - - p.CloseCalled = true - if p.CloseFn != nil { - return p.CloseFn() - } - - return p.CloseResponse -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource.go deleted file mode 100644 index bd5774600ec..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource.go +++ /dev/null @@ -1,510 +0,0 @@ -package terraform - -import ( - "fmt" - "reflect" - "sort" - "strconv" - "strings" - - "github.com/mitchellh/copystructure" - "github.com/mitchellh/reflectwalk" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" -) - -// Resource is a legacy way to identify a particular resource instance. -// -// New code should use addrs.ResourceInstance instead. This is still here -// only for codepaths that haven't been updated yet. -type Resource struct { - // These are all used by the new EvalNode stuff. - Name string - Type string - CountIndex int - - // These aren't really used anymore anywhere, but we keep them around - // since we haven't done a proper cleanup yet. - Id string - Info *InstanceInfo - Config *ResourceConfig - Dependencies []string - Diff *InstanceDiff - Provider ResourceProvider - State *InstanceState - Flags ResourceFlag -} - -// NewResource constructs a legacy Resource object from an -// addrs.ResourceInstance value. -// -// This is provided to shim to old codepaths that haven't been updated away -// from this type yet. Since this old type is not able to represent instances -// that have string keys, this function will panic if given a resource address -// that has a string key. -func NewResource(addr addrs.ResourceInstance) *Resource { - ret := &Resource{ - Name: addr.Resource.Name, - Type: addr.Resource.Type, - } - - if addr.Key != addrs.NoKey { - switch tk := addr.Key.(type) { - case addrs.IntKey: - ret.CountIndex = int(tk) - default: - panic(fmt.Errorf("resource instance with key %#v is not supported", addr.Key)) - } - } - - return ret -} - -// ResourceKind specifies what kind of instance we're working with, whether -// its a primary instance, a tainted instance, or an orphan. -type ResourceFlag byte - -// InstanceInfo is used to hold information about the instance and/or -// resource being modified. -type InstanceInfo struct { - // Id is a unique name to represent this instance. This is not related - // to InstanceState.ID in any way. - Id string - - // ModulePath is the complete path of the module containing this - // instance. - ModulePath []string - - // Type is the resource type of this instance - Type string -} - -// NewInstanceInfo constructs an InstanceInfo from an addrs.AbsResourceInstance. -// -// InstanceInfo is a legacy type, and uses of it should be gradually replaced -// by direct use of addrs.AbsResource or addrs.AbsResourceInstance as -// appropriate. -// -// The legacy InstanceInfo type cannot represent module instances with instance -// keys, so this function will panic if given such a path. Uses of this type -// should all be removed or replaced before implementing "count" and "for_each" -// arguments on modules in order to avoid such panics. -// -// This legacy type also cannot represent resource instances with string -// instance keys. It will panic if the given key is not either NoKey or an -// IntKey. -func NewInstanceInfo(addr addrs.AbsResourceInstance) *InstanceInfo { - // We need an old-style []string module path for InstanceInfo. - path := make([]string, len(addr.Module)) - for i, step := range addr.Module { - if step.InstanceKey != addrs.NoKey { - panic("NewInstanceInfo cannot convert module instance with key") - } - path[i] = step.Name - } - - // This is a funny old meaning of "id" that is no longer current. It should - // not be used for anything users might see. Note that it does not include - // a representation of the resource mode, and so it's impossible to - // determine from an InstanceInfo alone whether it is a managed or data - // resource that is being referred to. - id := fmt.Sprintf("%s.%s", addr.Resource.Resource.Type, addr.Resource.Resource.Name) - if addr.Resource.Resource.Mode == addrs.DataResourceMode { - id = "data." + id - } - if addr.Resource.Key != addrs.NoKey { - switch k := addr.Resource.Key.(type) { - case addrs.IntKey: - id = id + fmt.Sprintf(".%d", int(k)) - default: - panic(fmt.Sprintf("NewInstanceInfo cannot convert resource instance with %T instance key", addr.Resource.Key)) - } - } - - return &InstanceInfo{ - Id: id, - ModulePath: path, - Type: addr.Resource.Resource.Type, - } -} - -// ResourceAddress returns the address of the resource that the receiver is describing. -func (i *InstanceInfo) ResourceAddress() *ResourceAddress { - // GROSS: for tainted and deposed instances, their status gets appended - // to i.Id to create a unique id for the graph node. Historically these - // ids were displayed to the user, so it's designed to be human-readable: - // "aws_instance.bar.0 (deposed #0)" - // - // So here we detect such suffixes and try to interpret them back to - // their original meaning so we can then produce a ResourceAddress - // with a suitable InstanceType. - id := i.Id - instanceType := TypeInvalid - if idx := strings.Index(id, " ("); idx != -1 { - remain := id[idx:] - id = id[:idx] - - switch { - case strings.Contains(remain, "tainted"): - instanceType = TypeTainted - case strings.Contains(remain, "deposed"): - instanceType = TypeDeposed - } - } - - addr, err := parseResourceAddressInternal(id) - if err != nil { - // should never happen, since that would indicate a bug in the - // code that constructed this InstanceInfo. - panic(fmt.Errorf("InstanceInfo has invalid Id %s", id)) - } - if len(i.ModulePath) > 1 { - addr.Path = i.ModulePath[1:] // trim off "root" prefix, which is implied - } - if instanceType != TypeInvalid { - addr.InstanceTypeSet = true - addr.InstanceType = instanceType - } - return addr -} - -// ResourceConfig is a legacy type that was formerly used to represent -// interpolatable configuration blocks. It is now only used to shim to old -// APIs that still use this type, via NewResourceConfigShimmed. -type ResourceConfig struct { - ComputedKeys []string - Raw map[string]interface{} - Config map[string]interface{} -} - -// NewResourceConfigRaw constructs a ResourceConfig whose content is exactly -// the given value. -// -// The given value may contain hcl2shim.UnknownVariableValue to signal that -// something is computed, but it must not contain unprocessed interpolation -// sequences as we might've seen in Terraform v0.11 and prior. -func NewResourceConfigRaw(raw map[string]interface{}) *ResourceConfig { - v := hcl2shim.HCL2ValueFromConfigValue(raw) - - // This is a little weird but we round-trip the value through the hcl2shim - // package here for two reasons: firstly, because that reduces the risk - // of it including something unlike what NewResourceConfigShimmed would - // produce, and secondly because it creates a copy of "raw" just in case - // something is relying on the fact that in the old world the raw and - // config maps were always distinct, and thus you could in principle mutate - // one without affecting the other. (I sure hope nobody was doing that, though!) - cfg := hcl2shim.ConfigValueFromHCL2(v).(map[string]interface{}) - - return &ResourceConfig{ - Raw: raw, - Config: cfg, - - ComputedKeys: newResourceConfigShimmedComputedKeys(v, ""), - } -} - -// NewResourceConfigShimmed wraps a cty.Value of object type in a legacy -// ResourceConfig object, so that it can be passed to older APIs that expect -// this wrapping. -// -// The returned ResourceConfig is already interpolated and cannot be -// re-interpolated. It is, therefore, useful only to functions that expect -// an already-populated ResourceConfig which they then treat as read-only. -// -// If the given value is not of an object type that conforms to the given -// schema then this function will panic. -func NewResourceConfigShimmed(val cty.Value, schema *configschema.Block) *ResourceConfig { - if !val.Type().IsObjectType() { - panic(fmt.Errorf("NewResourceConfigShimmed given %#v; an object type is required", val.Type())) - } - ret := &ResourceConfig{} - - legacyVal := hcl2shim.ConfigValueFromHCL2Block(val, schema) - if legacyVal != nil { - ret.Config = legacyVal - - // Now we need to walk through our structure and find any unknown values, - // producing the separate list ComputedKeys to represent these. We use the - // schema here so that we can preserve the expected invariant - // that an attribute is always either wholly known or wholly unknown, while - // a child block can be partially unknown. - ret.ComputedKeys = newResourceConfigShimmedComputedKeys(val, "") - } else { - ret.Config = make(map[string]interface{}) - } - ret.Raw = ret.Config - - return ret -} - -// Record the any config values in ComputedKeys. This field had been unused in -// helper/schema, but in the new protocol we're using this so that the SDK can -// now handle having an unknown collection. The legacy diff code doesn't -// properly handle the unknown, because it can't be expressed in the same way -// between the config and diff. -func newResourceConfigShimmedComputedKeys(val cty.Value, path string) []string { - var ret []string - ty := val.Type() - - if val.IsNull() { - return ret - } - - if !val.IsKnown() { - // we shouldn't have an entirely unknown resource, but prevent empty - // strings just in case - if len(path) > 0 { - ret = append(ret, path) - } - return ret - } - - if path != "" { - path += "." - } - switch { - case ty.IsListType(), ty.IsTupleType(), ty.IsSetType(): - i := 0 - for it := val.ElementIterator(); it.Next(); i++ { - _, subVal := it.Element() - keys := newResourceConfigShimmedComputedKeys(subVal, fmt.Sprintf("%s%d", path, i)) - ret = append(ret, keys...) - } - - case ty.IsMapType(), ty.IsObjectType(): - for it := val.ElementIterator(); it.Next(); { - subK, subVal := it.Element() - keys := newResourceConfigShimmedComputedKeys(subVal, fmt.Sprintf("%s%s", path, subK.AsString())) - ret = append(ret, keys...) - } - } - - return ret -} - -// DeepCopy performs a deep copy of the configuration. This makes it safe -// to modify any of the structures that are part of the resource config without -// affecting the original configuration. -func (c *ResourceConfig) DeepCopy() *ResourceConfig { - // DeepCopying a nil should return a nil to avoid panics - if c == nil { - return nil - } - - // Copy, this will copy all the exported attributes - copy, err := copystructure.Config{Lock: true}.Copy(c) - if err != nil { - panic(err) - } - - // Force the type - result := copy.(*ResourceConfig) - - return result -} - -// Equal checks the equality of two resource configs. -func (c *ResourceConfig) Equal(c2 *ResourceConfig) bool { - // If either are nil, then they're only equal if they're both nil - if c == nil || c2 == nil { - return c == c2 - } - - // Sort the computed keys so they're deterministic - sort.Strings(c.ComputedKeys) - sort.Strings(c2.ComputedKeys) - - // Two resource configs if their exported properties are equal. - // We don't compare "raw" because it is never used again after - // initialization and for all intents and purposes they are equal - // if the exported properties are equal. - check := [][2]interface{}{ - {c.ComputedKeys, c2.ComputedKeys}, - {c.Raw, c2.Raw}, - {c.Config, c2.Config}, - } - for _, pair := range check { - if !reflect.DeepEqual(pair[0], pair[1]) { - return false - } - } - - return true -} - -// CheckSet checks that the given list of configuration keys is -// properly set. If not, errors are returned for each unset key. -// -// This is useful to be called in the Validate method of a ResourceProvider. -func (c *ResourceConfig) CheckSet(keys []string) []error { - var errs []error - - for _, k := range keys { - if !c.IsSet(k) { - errs = append(errs, fmt.Errorf("%s must be set", k)) - } - } - - return errs -} - -// Get looks up a configuration value by key and returns the value. -// -// The second return value is true if the get was successful. Get will -// return the raw value if the key is computed, so you should pair this -// with IsComputed. -func (c *ResourceConfig) Get(k string) (interface{}, bool) { - // We aim to get a value from the configuration. If it is computed, - // then we return the pure raw value. - source := c.Config - if c.IsComputed(k) { - source = c.Raw - } - - return c.get(k, source) -} - -// GetRaw looks up a configuration value by key and returns the value, -// from the raw, uninterpolated config. -// -// The second return value is true if the get was successful. Get will -// not succeed if the value is being computed. -func (c *ResourceConfig) GetRaw(k string) (interface{}, bool) { - return c.get(k, c.Raw) -} - -// IsComputed returns whether the given key is computed or not. -func (c *ResourceConfig) IsComputed(k string) bool { - // The next thing we do is check the config if we get a computed - // value out of it. - v, ok := c.get(k, c.Config) - if !ok { - return false - } - - // If value is nil, then it isn't computed - if v == nil { - return false - } - - // Test if the value contains an unknown value - var w unknownCheckWalker - if err := reflectwalk.Walk(v, &w); err != nil { - panic(err) - } - - return w.Unknown -} - -// IsSet checks if the key in the configuration is set. A key is set if -// it has a value or the value is being computed (is unknown currently). -// -// This function should be used rather than checking the keys of the -// raw configuration itself, since a key may be omitted from the raw -// configuration if it is being computed. -func (c *ResourceConfig) IsSet(k string) bool { - if c == nil { - return false - } - - if c.IsComputed(k) { - return true - } - - if _, ok := c.Get(k); ok { - return true - } - - return false -} - -func (c *ResourceConfig) get( - k string, raw map[string]interface{}) (interface{}, bool) { - parts := strings.Split(k, ".") - if len(parts) == 1 && parts[0] == "" { - parts = nil - } - - var current interface{} = raw - var previous interface{} = nil - for i, part := range parts { - if current == nil { - return nil, false - } - - cv := reflect.ValueOf(current) - switch cv.Kind() { - case reflect.Map: - previous = current - v := cv.MapIndex(reflect.ValueOf(part)) - if !v.IsValid() { - if i > 0 && i != (len(parts)-1) { - tryKey := strings.Join(parts[i:], ".") - v := cv.MapIndex(reflect.ValueOf(tryKey)) - if !v.IsValid() { - return nil, false - } - - return v.Interface(), true - } - - return nil, false - } - - current = v.Interface() - case reflect.Slice: - previous = current - - if part == "#" { - // If any value in a list is computed, this whole thing - // is computed and we can't read any part of it. - for i := 0; i < cv.Len(); i++ { - if v := cv.Index(i).Interface(); v == hcl2shim.UnknownVariableValue { - return v, true - } - } - - current = cv.Len() - } else { - i, err := strconv.ParseInt(part, 0, 0) - if err != nil { - return nil, false - } - if int(i) < 0 || int(i) >= cv.Len() { - return nil, false - } - current = cv.Index(int(i)).Interface() - } - case reflect.String: - // This happens when map keys contain "." and have a common - // prefix so were split as path components above. - actualKey := strings.Join(parts[i-1:], ".") - if prevMap, ok := previous.(map[string]interface{}); ok { - v, ok := prevMap[actualKey] - return v, ok - } - - return nil, false - default: - panic(fmt.Sprintf("Unknown kind: %s", cv.Kind())) - } - } - - return current, true -} - -// unknownCheckWalker -type unknownCheckWalker struct { - Unknown bool -} - -func (w *unknownCheckWalker) Primitive(v reflect.Value) error { - if v.Interface() == hcl2shim.UnknownVariableValue { - w.Unknown = true - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_address.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_address.go deleted file mode 100644 index 8a683012d24..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_address.go +++ /dev/null @@ -1,618 +0,0 @@ -package terraform - -import ( - "fmt" - "reflect" - "regexp" - "strconv" - "strings" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" -) - -// ResourceAddress is a way of identifying an individual resource (or, -// eventually, a subset of resources) within the state. It is used for Targets. -type ResourceAddress struct { - // Addresses a resource falling somewhere in the module path - // When specified alone, addresses all resources within a module path - Path []string - - // Addresses a specific resource that occurs in a list - Index int - - InstanceType InstanceType - InstanceTypeSet bool - Name string - Type string - Mode ResourceMode // significant only if InstanceTypeSet -} - -// Copy returns a copy of this ResourceAddress -func (r *ResourceAddress) Copy() *ResourceAddress { - if r == nil { - return nil - } - - n := &ResourceAddress{ - Path: make([]string, 0, len(r.Path)), - Index: r.Index, - InstanceType: r.InstanceType, - Name: r.Name, - Type: r.Type, - Mode: r.Mode, - } - - n.Path = append(n.Path, r.Path...) - - return n -} - -// String outputs the address that parses into this address. -func (r *ResourceAddress) String() string { - var result []string - for _, p := range r.Path { - result = append(result, "module", p) - } - - switch r.Mode { - case ManagedResourceMode: - // nothing to do - case DataResourceMode: - result = append(result, "data") - default: - panic(fmt.Errorf("unsupported resource mode %s", r.Mode)) - } - - if r.Type != "" { - result = append(result, r.Type) - } - - if r.Name != "" { - name := r.Name - if r.InstanceTypeSet { - switch r.InstanceType { - case TypePrimary: - name += ".primary" - case TypeDeposed: - name += ".deposed" - case TypeTainted: - name += ".tainted" - } - } - - if r.Index >= 0 { - name += fmt.Sprintf("[%d]", r.Index) - } - result = append(result, name) - } - - return strings.Join(result, ".") -} - -// HasResourceSpec returns true if the address has a resource spec, as -// defined in the documentation: -// https://www.terraform.io/docs/internals/resource-addressing.html -// In particular, this returns false if the address contains only -// a module path, thus addressing the entire module. -func (r *ResourceAddress) HasResourceSpec() bool { - return r.Type != "" && r.Name != "" -} - -// WholeModuleAddress returns the resource address that refers to all -// resources in the same module as the receiver address. -func (r *ResourceAddress) WholeModuleAddress() *ResourceAddress { - return &ResourceAddress{ - Path: r.Path, - Index: -1, - InstanceTypeSet: false, - } -} - -// MatchesResourceConfig returns true if the receiver matches the given -// configuration resource within the given _static_ module path. Note that -// the module path in a resource address is a _dynamic_ module path, and -// multiple dynamic resource paths may map to a single static path if -// count and for_each are in use on module calls. -// -// Since resource configuration blocks represent all of the instances of -// a multi-instance resource, the index of the address (if any) is not -// considered. -func (r *ResourceAddress) MatchesResourceConfig(path addrs.Module, rc *configs.Resource) bool { - if r.HasResourceSpec() { - // FIXME: Some ugliness while we are between worlds. Functionality - // in "addrs" should eventually replace this ResourceAddress idea - // completely, but for now we'll need to translate to the old - // way of representing resource modes. - switch r.Mode { - case ManagedResourceMode: - if rc.Mode != addrs.ManagedResourceMode { - return false - } - case DataResourceMode: - if rc.Mode != addrs.DataResourceMode { - return false - } - } - if r.Type != rc.Type || r.Name != rc.Name { - return false - } - } - - addrPath := r.Path - - // normalize - if len(addrPath) == 0 { - addrPath = nil - } - if len(path) == 0 { - path = nil - } - rawPath := []string(path) - return reflect.DeepEqual(addrPath, rawPath) -} - -// stateId returns the ID that this resource should be entered with -// in the state. This is also used for diffs. In the future, we'd like to -// move away from this string field so I don't export this. -func (r *ResourceAddress) stateId() string { - result := fmt.Sprintf("%s.%s", r.Type, r.Name) - switch r.Mode { - case ManagedResourceMode: - // Done - case DataResourceMode: - result = fmt.Sprintf("data.%s", result) - default: - panic(fmt.Errorf("unknown resource mode: %s", r.Mode)) - } - if r.Index >= 0 { - result += fmt.Sprintf(".%d", r.Index) - } - - return result -} - -// parseResourceAddressInternal parses the somewhat bespoke resource -// identifier used in states and diffs, such as "instance.name.0". -func parseResourceAddressInternal(s string) (*ResourceAddress, error) { - // Split based on ".". Every resource address should have at least two - // elements (type and name). - parts := strings.Split(s, ".") - if len(parts) < 2 || len(parts) > 4 { - return nil, fmt.Errorf("Invalid internal resource address format: %s", s) - } - - // Data resource if we have at least 3 parts and the first one is data - mode := ManagedResourceMode - if len(parts) > 2 && parts[0] == "data" { - mode = DataResourceMode - parts = parts[1:] - } - - // If we're not a data resource and we have more than 3, then it is an error - if len(parts) > 3 && mode != DataResourceMode { - return nil, fmt.Errorf("Invalid internal resource address format: %s", s) - } - - // Build the parts of the resource address that are guaranteed to exist - addr := &ResourceAddress{ - Type: parts[0], - Name: parts[1], - Index: -1, - InstanceType: TypePrimary, - Mode: mode, - } - - // If we have more parts, then we have an index. Parse that. - if len(parts) > 2 { - idx, err := strconv.ParseInt(parts[2], 0, 0) - if err != nil { - return nil, fmt.Errorf("Error parsing resource address %q: %s", s, err) - } - - addr.Index = int(idx) - } - - return addr, nil -} - -func ParseResourceAddress(s string) (*ResourceAddress, error) { - matches, err := tokenizeResourceAddress(s) - if err != nil { - return nil, err - } - mode := ManagedResourceMode - if matches["data_prefix"] != "" { - mode = DataResourceMode - } - resourceIndex, err := ParseResourceIndex(matches["index"]) - if err != nil { - return nil, err - } - instanceType, err := ParseInstanceType(matches["instance_type"]) - if err != nil { - return nil, err - } - path := ParseResourcePath(matches["path"]) - - // not allowed to say "data." without a type following - if mode == DataResourceMode && matches["type"] == "" { - return nil, fmt.Errorf( - "invalid resource address %q: must target specific data instance", - s, - ) - } - - return &ResourceAddress{ - Path: path, - Index: resourceIndex, - InstanceType: instanceType, - InstanceTypeSet: matches["instance_type"] != "", - Name: matches["name"], - Type: matches["type"], - Mode: mode, - }, nil -} - -// ParseResourceAddressForInstanceDiff creates a ResourceAddress for a -// resource name as described in a module diff. -// -// For historical reasons a different addressing format is used in this -// context. The internal format should not be shown in the UI and instead -// this function should be used to translate to a ResourceAddress and -// then, where appropriate, use the String method to produce a canonical -// resource address string for display in the UI. -// -// The given path slice must be empty (or nil) for the root module, and -// otherwise consist of a sequence of module names traversing down into -// the module tree. If a non-nil path is provided, the caller must not -// modify its underlying array after passing it to this function. -func ParseResourceAddressForInstanceDiff(path []string, key string) (*ResourceAddress, error) { - addr, err := parseResourceAddressInternal(key) - if err != nil { - return nil, err - } - addr.Path = path - return addr, nil -} - -// NewLegacyResourceAddress creates a ResourceAddress from a new-style -// addrs.AbsResource value. -// -// This is provided for shimming purposes so that we can still easily call into -// older functions that expect the ResourceAddress type. -func NewLegacyResourceAddress(addr addrs.AbsResource) *ResourceAddress { - ret := &ResourceAddress{ - Type: addr.Resource.Type, - Name: addr.Resource.Name, - } - - switch addr.Resource.Mode { - case addrs.ManagedResourceMode: - ret.Mode = ManagedResourceMode - case addrs.DataResourceMode: - ret.Mode = DataResourceMode - default: - panic(fmt.Errorf("cannot shim %s to legacy ResourceMode value", addr.Resource.Mode)) - } - - path := make([]string, len(addr.Module)) - for i, step := range addr.Module { - if step.InstanceKey != addrs.NoKey { - // At the time of writing this can't happen because we don't - // ket generate keyed module instances. This legacy codepath must - // be removed before we can support "count" and "for_each" for - // modules. - panic(fmt.Errorf("cannot shim module instance step with key %#v to legacy ResourceAddress.Path", step.InstanceKey)) - } - - path[i] = step.Name - } - ret.Path = path - ret.Index = -1 - - return ret -} - -// NewLegacyResourceInstanceAddress creates a ResourceAddress from a new-style -// addrs.AbsResource value. -// -// This is provided for shimming purposes so that we can still easily call into -// older functions that expect the ResourceAddress type. -func NewLegacyResourceInstanceAddress(addr addrs.AbsResourceInstance) *ResourceAddress { - ret := &ResourceAddress{ - Type: addr.Resource.Resource.Type, - Name: addr.Resource.Resource.Name, - } - - switch addr.Resource.Resource.Mode { - case addrs.ManagedResourceMode: - ret.Mode = ManagedResourceMode - case addrs.DataResourceMode: - ret.Mode = DataResourceMode - default: - panic(fmt.Errorf("cannot shim %s to legacy ResourceMode value", addr.Resource.Resource.Mode)) - } - - path := make([]string, len(addr.Module)) - for i, step := range addr.Module { - if step.InstanceKey != addrs.NoKey { - // At the time of writing this can't happen because we don't - // ket generate keyed module instances. This legacy codepath must - // be removed before we can support "count" and "for_each" for - // modules. - panic(fmt.Errorf("cannot shim module instance step with key %#v to legacy ResourceAddress.Path", step.InstanceKey)) - } - - path[i] = step.Name - } - ret.Path = path - - if addr.Resource.Key == addrs.NoKey { - ret.Index = -1 - } else if ik, ok := addr.Resource.Key.(addrs.IntKey); ok { - ret.Index = int(ik) - } else if _, ok := addr.Resource.Key.(addrs.StringKey); ok { - ret.Index = -1 - } else { - panic(fmt.Errorf("cannot shim resource instance with key %#v to legacy ResourceAddress.Index", addr.Resource.Key)) - } - - return ret -} - -// AbsResourceInstanceAddr converts the receiver, a legacy resource address, to -// the new resource address type addrs.AbsResourceInstance. -// -// This method can be used only on an address that has a resource specification. -// It will panic if called on a module-path-only ResourceAddress. Use -// method HasResourceSpec to check before calling, in contexts where it is -// unclear. -// -// addrs.AbsResourceInstance does not represent the "tainted" and "deposed" -// states, and so if these are present on the receiver then they are discarded. -// -// This is provided for shimming purposes so that we can easily adapt functions -// that are returning the legacy ResourceAddress type, for situations where -// the new type is required. -func (addr *ResourceAddress) AbsResourceInstanceAddr() addrs.AbsResourceInstance { - if !addr.HasResourceSpec() { - panic("AbsResourceInstanceAddr called on ResourceAddress with no resource spec") - } - - ret := addrs.AbsResourceInstance{ - Module: addr.ModuleInstanceAddr(), - Resource: addrs.ResourceInstance{ - Resource: addrs.Resource{ - Type: addr.Type, - Name: addr.Name, - }, - }, - } - - switch addr.Mode { - case ManagedResourceMode: - ret.Resource.Resource.Mode = addrs.ManagedResourceMode - case DataResourceMode: - ret.Resource.Resource.Mode = addrs.DataResourceMode - default: - panic(fmt.Errorf("cannot shim %s to addrs.ResourceMode value", addr.Mode)) - } - - if addr.Index != -1 { - ret.Resource.Key = addrs.IntKey(addr.Index) - } - - return ret -} - -// ModuleInstanceAddr returns the module path portion of the receiver as a -// addrs.ModuleInstance value. -func (addr *ResourceAddress) ModuleInstanceAddr() addrs.ModuleInstance { - path := make(addrs.ModuleInstance, len(addr.Path)) - for i, name := range addr.Path { - path[i] = addrs.ModuleInstanceStep{Name: name} - } - return path -} - -// Contains returns true if and only if the given node is contained within -// the receiver. -// -// Containment is defined in terms of the module and resource heirarchy: -// a resource is contained within its module and any ancestor modules, -// an indexed resource instance is contained with the unindexed resource, etc. -func (addr *ResourceAddress) Contains(other *ResourceAddress) bool { - ourPath := addr.Path - givenPath := other.Path - if len(givenPath) < len(ourPath) { - return false - } - for i := range ourPath { - if ourPath[i] != givenPath[i] { - return false - } - } - - // If the receiver is a whole-module address then the path prefix - // matching is all we need. - if !addr.HasResourceSpec() { - return true - } - - if addr.Type != other.Type || addr.Name != other.Name || addr.Mode != other.Mode { - return false - } - - if addr.Index != -1 && addr.Index != other.Index { - return false - } - - if addr.InstanceTypeSet && (addr.InstanceTypeSet != other.InstanceTypeSet || addr.InstanceType != other.InstanceType) { - return false - } - - return true -} - -// Equals returns true if the receiver matches the given address. -// -// The name of this method is a misnomer, since it doesn't test for exact -// equality. Instead, it tests that the _specified_ parts of each -// address match, treating any unspecified parts as wildcards. -// -// See also Contains, which takes a more heirarchical approach to comparing -// addresses. -func (addr *ResourceAddress) Equals(raw interface{}) bool { - other, ok := raw.(*ResourceAddress) - if !ok { - return false - } - - pathMatch := len(addr.Path) == 0 && len(other.Path) == 0 || - reflect.DeepEqual(addr.Path, other.Path) - - indexMatch := addr.Index == -1 || - other.Index == -1 || - addr.Index == other.Index - - nameMatch := addr.Name == "" || - other.Name == "" || - addr.Name == other.Name - - typeMatch := addr.Type == "" || - other.Type == "" || - addr.Type == other.Type - - // mode is significant only when type is set - modeMatch := addr.Type == "" || - other.Type == "" || - addr.Mode == other.Mode - - return pathMatch && - indexMatch && - addr.InstanceType == other.InstanceType && - nameMatch && - typeMatch && - modeMatch -} - -// Less returns true if and only if the receiver should be sorted before -// the given address when presenting a list of resource addresses to -// an end-user. -// -// This sort uses lexicographic sorting for most components, but uses -// numeric sort for indices, thus causing index 10 to sort after -// index 9, rather than after index 1. -func (addr *ResourceAddress) Less(other *ResourceAddress) bool { - - switch { - - case len(addr.Path) != len(other.Path): - return len(addr.Path) < len(other.Path) - - case !reflect.DeepEqual(addr.Path, other.Path): - // If the two paths are the same length but don't match, we'll just - // cheat and compare the string forms since it's easier than - // comparing all of the path segments in turn, and lexicographic - // comparison is correct for the module path portion. - addrStr := addr.String() - otherStr := other.String() - return addrStr < otherStr - - case addr.Mode != other.Mode: - return addr.Mode == DataResourceMode - - case addr.Type != other.Type: - return addr.Type < other.Type - - case addr.Name != other.Name: - return addr.Name < other.Name - - case addr.Index != other.Index: - // Since "Index" is -1 for an un-indexed address, this also conveniently - // sorts unindexed addresses before indexed ones, should they both - // appear for some reason. - return addr.Index < other.Index - - case addr.InstanceTypeSet != other.InstanceTypeSet: - return !addr.InstanceTypeSet - - case addr.InstanceType != other.InstanceType: - // InstanceType is actually an enum, so this is just an arbitrary - // sort based on the enum numeric values, and thus not particularly - // meaningful. - return addr.InstanceType < other.InstanceType - - default: - return false - - } -} - -func ParseResourceIndex(s string) (int, error) { - if s == "" { - return -1, nil - } - return strconv.Atoi(s) -} - -func ParseResourcePath(s string) []string { - if s == "" { - return nil - } - parts := strings.Split(s, ".") - path := make([]string, 0, len(parts)) - for _, s := range parts { - // Due to the limitations of the regexp match below, the path match has - // some noise in it we have to filter out :| - if s == "" || s == "module" { - continue - } - path = append(path, s) - } - return path -} - -func ParseInstanceType(s string) (InstanceType, error) { - switch s { - case "", "primary": - return TypePrimary, nil - case "deposed": - return TypeDeposed, nil - case "tainted": - return TypeTainted, nil - default: - return TypeInvalid, fmt.Errorf("Unexpected value for InstanceType field: %q", s) - } -} - -func tokenizeResourceAddress(s string) (map[string]string, error) { - // Example of portions of the regexp below using the - // string "aws_instance.web.tainted[1]" - re := regexp.MustCompile(`\A` + - // "module.foo.module.bar" (optional) - `(?P(?:module\.(?P[^.]+)\.?)*)` + - // possibly "data.", if targeting is a data resource - `(?P(?:data\.)?)` + - // "aws_instance.web" (optional when module path specified) - `(?:(?P[^.]+)\.(?P[^.[]+))?` + - // "tainted" (optional, omission implies: "primary") - `(?:\.(?P\w+))?` + - // "1" (optional, omission implies: "0") - `(?:\[(?P\d+)\])?` + - `\z`) - - groupNames := re.SubexpNames() - rawMatches := re.FindAllStringSubmatch(s, -1) - if len(rawMatches) != 1 { - return nil, fmt.Errorf("invalid resource address %q", s) - } - - matches := make(map[string]string) - for i, m := range rawMatches[0] { - matches[groupNames[i]] = m - } - - return matches, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provider.go deleted file mode 100644 index fec45967fbd..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provider.go +++ /dev/null @@ -1,319 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - - "github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" -) - -// ResourceProvider is an interface that must be implemented by any -// resource provider: the thing that creates and manages the resources in -// a Terraform configuration. -// -// Important implementation note: All returned pointers, such as -// *ResourceConfig, *InstanceState, *InstanceDiff, etc. must not point to -// shared data. Terraform is highly parallel and assumes that this data is safe -// to read/write in parallel so it must be unique references. Note that it is -// safe to return arguments as results, however. -type ResourceProvider interface { - /********************************************************************* - * Functions related to the provider - *********************************************************************/ - - // GetSchema returns the config schema for the main provider - // configuration, as would appear in a "provider" block in the - // configuration files. - // - // Currently not all providers support schema. Callers must therefore - // first call Resources and DataSources and ensure that at least one - // resource or data source has the SchemaAvailable flag set. - GetSchema(*ProviderSchemaRequest) (*ProviderSchema, error) - - // Input was used prior to v0.12 to ask the provider to prompt the user - // for input to complete the configuration. - // - // From v0.12 onwards this method is never called because Terraform Core - // is able to handle the necessary input logic itself based on the - // schema returned from GetSchema. - Input(UIInput, *ResourceConfig) (*ResourceConfig, error) - - // Validate is called once at the beginning with the raw configuration - // (no interpolation done) and can return a list of warnings and/or - // errors. - // - // This is called once with the provider configuration only. It may not - // be called at all if no provider configuration is given. - // - // This should not assume that any values of the configurations are valid. - // The primary use case of this call is to check that required keys are - // set. - Validate(*ResourceConfig) ([]string, []error) - - // Configure configures the provider itself with the configuration - // given. This is useful for setting things like access keys. - // - // This won't be called at all if no provider configuration is given. - // - // Configure returns an error if it occurred. - Configure(*ResourceConfig) error - - // Resources returns all the available resource types that this provider - // knows how to manage. - Resources() []ResourceType - - // Stop is called when the provider should halt any in-flight actions. - // - // This can be used to make a nicer Ctrl-C experience for Terraform. - // Even if this isn't implemented to do anything (just returns nil), - // Terraform will still cleanly stop after the currently executing - // graph node is complete. However, this API can be used to make more - // efficient halts. - // - // Stop doesn't have to and shouldn't block waiting for in-flight actions - // to complete. It should take any action it wants and return immediately - // acknowledging it has received the stop request. Terraform core will - // automatically not make any further API calls to the provider soon - // after Stop is called (technically exactly once the currently executing - // graph nodes are complete). - // - // The error returned, if non-nil, is assumed to mean that signaling the - // stop somehow failed and that the user should expect potentially waiting - // a longer period of time. - Stop() error - - /********************************************************************* - * Functions related to individual resources - *********************************************************************/ - - // ValidateResource is called once at the beginning with the raw - // configuration (no interpolation done) and can return a list of warnings - // and/or errors. - // - // This is called once per resource. - // - // This should not assume any of the values in the resource configuration - // are valid since it is possible they have to be interpolated still. - // The primary use case of this call is to check that the required keys - // are set and that the general structure is correct. - ValidateResource(string, *ResourceConfig) ([]string, []error) - - // Apply applies a diff to a specific resource and returns the new - // resource state along with an error. - // - // If the resource state given has an empty ID, then a new resource - // is expected to be created. - Apply( - *InstanceInfo, - *InstanceState, - *InstanceDiff) (*InstanceState, error) - - // Diff diffs a resource versus a desired state and returns - // a diff. - Diff( - *InstanceInfo, - *InstanceState, - *ResourceConfig) (*InstanceDiff, error) - - // Refresh refreshes a resource and updates all of its attributes - // with the latest information. - Refresh(*InstanceInfo, *InstanceState) (*InstanceState, error) - - /********************************************************************* - * Functions related to importing - *********************************************************************/ - - // ImportState requests that the given resource be imported. - // - // The returned InstanceState only requires ID be set. Importing - // will always call Refresh after the state to complete it. - // - // IMPORTANT: InstanceState doesn't have the resource type attached - // to it. A type must be specified on the state via the Ephemeral - // field on the state. - // - // This function can return multiple states. Normally, an import - // will map 1:1 to a physical resource. However, some resources map - // to multiple. For example, an AWS security group may contain many rules. - // Each rule is represented by a separate resource in Terraform, - // therefore multiple states are returned. - ImportState(*InstanceInfo, string) ([]*InstanceState, error) - - /********************************************************************* - * Functions related to data resources - *********************************************************************/ - - // ValidateDataSource is called once at the beginning with the raw - // configuration (no interpolation done) and can return a list of warnings - // and/or errors. - // - // This is called once per data source instance. - // - // This should not assume any of the values in the resource configuration - // are valid since it is possible they have to be interpolated still. - // The primary use case of this call is to check that the required keys - // are set and that the general structure is correct. - ValidateDataSource(string, *ResourceConfig) ([]string, []error) - - // DataSources returns all of the available data sources that this - // provider implements. - DataSources() []DataSource - - // ReadDataDiff produces a diff that represents the state that will - // be produced when the given data source is read using a later call - // to ReadDataApply. - ReadDataDiff(*InstanceInfo, *ResourceConfig) (*InstanceDiff, error) - - // ReadDataApply initializes a data instance using the configuration - // in a diff produced by ReadDataDiff. - ReadDataApply(*InstanceInfo, *InstanceDiff) (*InstanceState, error) -} - -// ResourceProviderCloser is an interface that providers that can close -// connections that aren't needed anymore must implement. -type ResourceProviderCloser interface { - Close() error -} - -// ResourceType is a type of resource that a resource provider can manage. -type ResourceType struct { - Name string // Name of the resource, example "instance" (no provider prefix) - Importable bool // Whether this resource supports importing - - // SchemaAvailable is set if the provider supports the ProviderSchema, - // ResourceTypeSchema and DataSourceSchema methods. Although it is - // included on each resource type, it's actually a provider-wide setting - // that's smuggled here only because that avoids a breaking change to - // the plugin protocol. - SchemaAvailable bool -} - -// DataSource is a data source that a resource provider implements. -type DataSource struct { - Name string - - // SchemaAvailable is set if the provider supports the ProviderSchema, - // ResourceTypeSchema and DataSourceSchema methods. Although it is - // included on each resource type, it's actually a provider-wide setting - // that's smuggled here only because that avoids a breaking change to - // the plugin protocol. - SchemaAvailable bool -} - -// ResourceProviderResolver is an interface implemented by objects that are -// able to resolve a given set of resource provider version constraints -// into ResourceProviderFactory callbacks. -type ResourceProviderResolver interface { - // Given a constraint map, return a ResourceProviderFactory for each - // requested provider. If some or all of the constraints cannot be - // satisfied, return a non-nil slice of errors describing the problems. - ResolveProviders(reqd discovery.PluginRequirements) (map[string]ResourceProviderFactory, []error) -} - -// ResourceProviderResolverFunc wraps a callback function and turns it into -// a ResourceProviderResolver implementation, for convenience in situations -// where a function and its associated closure are sufficient as a resolver -// implementation. -type ResourceProviderResolverFunc func(reqd discovery.PluginRequirements) (map[string]ResourceProviderFactory, []error) - -// ResolveProviders implements ResourceProviderResolver by calling the -// wrapped function. -func (f ResourceProviderResolverFunc) ResolveProviders(reqd discovery.PluginRequirements) (map[string]ResourceProviderFactory, []error) { - return f(reqd) -} - -// ResourceProviderResolverFixed returns a ResourceProviderResolver that -// has a fixed set of provider factories provided by the caller. The returned -// resolver ignores version constraints entirely and just returns the given -// factory for each requested provider name. -// -// This function is primarily used in tests, to provide mock providers or -// in-process providers under test. -func ResourceProviderResolverFixed(factories map[string]ResourceProviderFactory) ResourceProviderResolver { - return ResourceProviderResolverFunc(func(reqd discovery.PluginRequirements) (map[string]ResourceProviderFactory, []error) { - ret := make(map[string]ResourceProviderFactory, len(reqd)) - var errs []error - for name := range reqd { - if factory, exists := factories[name]; exists { - ret[name] = factory - } else { - errs = append(errs, fmt.Errorf("provider %q is not available", name)) - } - } - return ret, errs - }) -} - -// ResourceProviderFactory is a function type that creates a new instance -// of a resource provider. -type ResourceProviderFactory func() (ResourceProvider, error) - -// ResourceProviderFactoryFixed is a helper that creates a -// ResourceProviderFactory that just returns some fixed provider. -func ResourceProviderFactoryFixed(p ResourceProvider) ResourceProviderFactory { - return func() (ResourceProvider, error) { - return p, nil - } -} - -func ProviderHasResource(p ResourceProvider, n string) bool { - for _, rt := range p.Resources() { - if rt.Name == n { - return true - } - } - - return false -} - -func ProviderHasDataSource(p ResourceProvider, n string) bool { - for _, rt := range p.DataSources() { - if rt.Name == n { - return true - } - } - - return false -} - -// resourceProviderFactories matches available plugins to the given version -// requirements to produce a map of compatible provider plugins if possible, -// or an error if the currently-available plugins are insufficient. -// -// This should be called only with configurations that have passed calls -// to config.Validate(), which ensures that all of the given version -// constraints are valid. It will panic if any invalid constraints are present. -func resourceProviderFactories(resolver providers.Resolver, reqd discovery.PluginRequirements) (map[string]providers.Factory, tfdiags.Diagnostics) { - var diags tfdiags.Diagnostics - ret, errs := resolver.ResolveProviders(reqd) - if errs != nil { - diags = diags.Append( - tfdiags.Sourceless(tfdiags.Error, - "Could not satisfy plugin requirements", - errPluginInit, - ), - ) - - for _, err := range errs { - diags = diags.Append(err) - } - - return nil, diags - } - - return ret, nil -} - -const errPluginInit = ` -Plugin reinitialization required. Please run "terraform init". - -Plugins are external binaries that Terraform uses to access and manipulate -resources. The configuration provided requires plugins which can't be located, -don't satisfy the version constraints, or are otherwise incompatible. - -Terraform automatically discovers provider requirements from your -configuration, including providers used in child modules. To see the -requirements and constraints from each module, run "terraform providers". -` diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provider_mock.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provider_mock.go deleted file mode 100644 index 4000e3d2149..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provider_mock.go +++ /dev/null @@ -1,315 +0,0 @@ -package terraform - -import ( - "sync" -) - -// MockResourceProvider implements ResourceProvider but mocks out all the -// calls for testing purposes. -type MockResourceProvider struct { - sync.Mutex - - // Anything you want, in case you need to store extra data with the mock. - Meta interface{} - - CloseCalled bool - CloseError error - GetSchemaCalled bool - GetSchemaRequest *ProviderSchemaRequest - GetSchemaReturn *ProviderSchema - GetSchemaReturnError error - InputCalled bool - InputInput UIInput - InputConfig *ResourceConfig - InputReturnConfig *ResourceConfig - InputReturnError error - InputFn func(UIInput, *ResourceConfig) (*ResourceConfig, error) - ApplyCalled bool - ApplyInfo *InstanceInfo - ApplyState *InstanceState - ApplyDiff *InstanceDiff - ApplyFn func(*InstanceInfo, *InstanceState, *InstanceDiff) (*InstanceState, error) - ApplyReturn *InstanceState - ApplyReturnError error - ConfigureCalled bool - ConfigureConfig *ResourceConfig - ConfigureFn func(*ResourceConfig) error - ConfigureReturnError error - DiffCalled bool - DiffInfo *InstanceInfo - DiffState *InstanceState - DiffDesired *ResourceConfig - DiffFn func(*InstanceInfo, *InstanceState, *ResourceConfig) (*InstanceDiff, error) - DiffReturn *InstanceDiff - DiffReturnError error - RefreshCalled bool - RefreshInfo *InstanceInfo - RefreshState *InstanceState - RefreshFn func(*InstanceInfo, *InstanceState) (*InstanceState, error) - RefreshReturn *InstanceState - RefreshReturnError error - ResourcesCalled bool - ResourcesReturn []ResourceType - ReadDataApplyCalled bool - ReadDataApplyInfo *InstanceInfo - ReadDataApplyDiff *InstanceDiff - ReadDataApplyFn func(*InstanceInfo, *InstanceDiff) (*InstanceState, error) - ReadDataApplyReturn *InstanceState - ReadDataApplyReturnError error - ReadDataDiffCalled bool - ReadDataDiffInfo *InstanceInfo - ReadDataDiffDesired *ResourceConfig - ReadDataDiffFn func(*InstanceInfo, *ResourceConfig) (*InstanceDiff, error) - ReadDataDiffReturn *InstanceDiff - ReadDataDiffReturnError error - StopCalled bool - StopFn func() error - StopReturnError error - DataSourcesCalled bool - DataSourcesReturn []DataSource - ValidateCalled bool - ValidateConfig *ResourceConfig - ValidateFn func(*ResourceConfig) ([]string, []error) - ValidateReturnWarns []string - ValidateReturnErrors []error - ValidateResourceFn func(string, *ResourceConfig) ([]string, []error) - ValidateResourceCalled bool - ValidateResourceType string - ValidateResourceConfig *ResourceConfig - ValidateResourceReturnWarns []string - ValidateResourceReturnErrors []error - ValidateDataSourceFn func(string, *ResourceConfig) ([]string, []error) - ValidateDataSourceCalled bool - ValidateDataSourceType string - ValidateDataSourceConfig *ResourceConfig - ValidateDataSourceReturnWarns []string - ValidateDataSourceReturnErrors []error - - ImportStateCalled bool - ImportStateInfo *InstanceInfo - ImportStateID string - ImportStateReturn []*InstanceState - ImportStateReturnError error - ImportStateFn func(*InstanceInfo, string) ([]*InstanceState, error) -} - -func (p *MockResourceProvider) Close() error { - p.CloseCalled = true - return p.CloseError -} - -func (p *MockResourceProvider) GetSchema(req *ProviderSchemaRequest) (*ProviderSchema, error) { - p.Lock() - defer p.Unlock() - - p.GetSchemaCalled = true - p.GetSchemaRequest = req - return p.GetSchemaReturn, p.GetSchemaReturnError -} - -func (p *MockResourceProvider) Input( - input UIInput, c *ResourceConfig) (*ResourceConfig, error) { - p.Lock() - defer p.Unlock() - p.InputCalled = true - p.InputInput = input - p.InputConfig = c - if p.InputFn != nil { - return p.InputFn(input, c) - } - return p.InputReturnConfig, p.InputReturnError -} - -func (p *MockResourceProvider) Validate(c *ResourceConfig) ([]string, []error) { - p.Lock() - defer p.Unlock() - - p.ValidateCalled = true - p.ValidateConfig = c - if p.ValidateFn != nil { - return p.ValidateFn(c) - } - return p.ValidateReturnWarns, p.ValidateReturnErrors -} - -func (p *MockResourceProvider) ValidateResource(t string, c *ResourceConfig) ([]string, []error) { - p.Lock() - defer p.Unlock() - - p.ValidateResourceCalled = true - p.ValidateResourceType = t - p.ValidateResourceConfig = c - - if p.ValidateResourceFn != nil { - return p.ValidateResourceFn(t, c) - } - - return p.ValidateResourceReturnWarns, p.ValidateResourceReturnErrors -} - -func (p *MockResourceProvider) Configure(c *ResourceConfig) error { - p.Lock() - defer p.Unlock() - - p.ConfigureCalled = true - p.ConfigureConfig = c - - if p.ConfigureFn != nil { - return p.ConfigureFn(c) - } - - return p.ConfigureReturnError -} - -func (p *MockResourceProvider) Stop() error { - p.Lock() - defer p.Unlock() - - p.StopCalled = true - if p.StopFn != nil { - return p.StopFn() - } - - return p.StopReturnError -} - -func (p *MockResourceProvider) Apply( - info *InstanceInfo, - state *InstanceState, - diff *InstanceDiff) (*InstanceState, error) { - // We only lock while writing data. Reading is fine - p.Lock() - p.ApplyCalled = true - p.ApplyInfo = info - p.ApplyState = state - p.ApplyDiff = diff - p.Unlock() - - if p.ApplyFn != nil { - return p.ApplyFn(info, state, diff) - } - - return p.ApplyReturn.DeepCopy(), p.ApplyReturnError -} - -func (p *MockResourceProvider) Diff( - info *InstanceInfo, - state *InstanceState, - desired *ResourceConfig) (*InstanceDiff, error) { - p.Lock() - defer p.Unlock() - - p.DiffCalled = true - p.DiffInfo = info - p.DiffState = state - p.DiffDesired = desired - - if p.DiffFn != nil { - return p.DiffFn(info, state, desired) - } - - return p.DiffReturn.DeepCopy(), p.DiffReturnError -} - -func (p *MockResourceProvider) Refresh( - info *InstanceInfo, - s *InstanceState) (*InstanceState, error) { - p.Lock() - defer p.Unlock() - - p.RefreshCalled = true - p.RefreshInfo = info - p.RefreshState = s - - if p.RefreshFn != nil { - return p.RefreshFn(info, s) - } - - return p.RefreshReturn.DeepCopy(), p.RefreshReturnError -} - -func (p *MockResourceProvider) Resources() []ResourceType { - p.Lock() - defer p.Unlock() - - p.ResourcesCalled = true - return p.ResourcesReturn -} - -func (p *MockResourceProvider) ImportState(info *InstanceInfo, id string) ([]*InstanceState, error) { - p.Lock() - defer p.Unlock() - - p.ImportStateCalled = true - p.ImportStateInfo = info - p.ImportStateID = id - if p.ImportStateFn != nil { - return p.ImportStateFn(info, id) - } - - var result []*InstanceState - if p.ImportStateReturn != nil { - result = make([]*InstanceState, len(p.ImportStateReturn)) - for i, v := range p.ImportStateReturn { - result[i] = v.DeepCopy() - } - } - - return result, p.ImportStateReturnError -} - -func (p *MockResourceProvider) ValidateDataSource(t string, c *ResourceConfig) ([]string, []error) { - p.Lock() - defer p.Unlock() - - p.ValidateDataSourceCalled = true - p.ValidateDataSourceType = t - p.ValidateDataSourceConfig = c - - if p.ValidateDataSourceFn != nil { - return p.ValidateDataSourceFn(t, c) - } - - return p.ValidateDataSourceReturnWarns, p.ValidateDataSourceReturnErrors -} - -func (p *MockResourceProvider) ReadDataDiff( - info *InstanceInfo, - desired *ResourceConfig) (*InstanceDiff, error) { - p.Lock() - defer p.Unlock() - - p.ReadDataDiffCalled = true - p.ReadDataDiffInfo = info - p.ReadDataDiffDesired = desired - if p.ReadDataDiffFn != nil { - return p.ReadDataDiffFn(info, desired) - } - - return p.ReadDataDiffReturn.DeepCopy(), p.ReadDataDiffReturnError -} - -func (p *MockResourceProvider) ReadDataApply( - info *InstanceInfo, - d *InstanceDiff) (*InstanceState, error) { - p.Lock() - defer p.Unlock() - - p.ReadDataApplyCalled = true - p.ReadDataApplyInfo = info - p.ReadDataApplyDiff = d - - if p.ReadDataApplyFn != nil { - return p.ReadDataApplyFn(info, d) - } - - return p.ReadDataApplyReturn.DeepCopy(), p.ReadDataApplyReturnError -} - -func (p *MockResourceProvider) DataSources() []DataSource { - p.Lock() - defer p.Unlock() - - p.DataSourcesCalled = true - return p.DataSourcesReturn -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provisioner.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provisioner.go deleted file mode 100644 index 74ee2a940d4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provisioner.go +++ /dev/null @@ -1,70 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/provisioners" -) - -// ResourceProvisioner is an interface that must be implemented by any -// resource provisioner: the thing that initializes resources in -// a Terraform configuration. -type ResourceProvisioner interface { - // GetConfigSchema returns the schema for the provisioner type's main - // configuration block. This is called prior to Validate to enable some - // basic structural validation to be performed automatically and to allow - // the configuration to be properly extracted from potentially-ambiguous - // configuration file formats. - GetConfigSchema() (*configschema.Block, error) - - // Validate is called once at the beginning with the raw - // configuration (no interpolation done) and can return a list of warnings - // and/or errors. - // - // This is called once per resource. - // - // This should not assume any of the values in the resource configuration - // are valid since it is possible they have to be interpolated still. - // The primary use case of this call is to check that the required keys - // are set and that the general structure is correct. - Validate(*ResourceConfig) ([]string, []error) - - // Apply runs the provisioner on a specific resource and returns the new - // resource state along with an error. Instead of a diff, the ResourceConfig - // is provided since provisioners only run after a resource has been - // newly created. - Apply(UIOutput, *InstanceState, *ResourceConfig) error - - // Stop is called when the provisioner should halt any in-flight actions. - // - // This can be used to make a nicer Ctrl-C experience for Terraform. - // Even if this isn't implemented to do anything (just returns nil), - // Terraform will still cleanly stop after the currently executing - // graph node is complete. However, this API can be used to make more - // efficient halts. - // - // Stop doesn't have to and shouldn't block waiting for in-flight actions - // to complete. It should take any action it wants and return immediately - // acknowledging it has received the stop request. Terraform core will - // automatically not make any further API calls to the provider soon - // after Stop is called (technically exactly once the currently executing - // graph nodes are complete). - // - // The error returned, if non-nil, is assumed to mean that signaling the - // stop somehow failed and that the user should expect potentially waiting - // a longer period of time. - Stop() error -} - -// ResourceProvisionerCloser is an interface that provisioners that can close -// connections that aren't needed anymore must implement. -type ResourceProvisionerCloser interface { - Close() error -} - -// ResourceProvisionerFactory is a function type that creates a new instance -// of a resource provisioner. -type ResourceProvisionerFactory func() (ResourceProvisioner, error) - -// ProvisionerFactory is a function type that creates a new instance -// of a provisioners.Interface. -type ProvisionerFactory = provisioners.Factory diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provisioner_mock.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provisioner_mock.go deleted file mode 100644 index ed6f241bc86..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_provisioner_mock.go +++ /dev/null @@ -1,87 +0,0 @@ -package terraform - -import ( - "sync" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" -) - -// MockResourceProvisioner implements ResourceProvisioner but mocks out all the -// calls for testing purposes. -type MockResourceProvisioner struct { - sync.Mutex - // Anything you want, in case you need to store extra data with the mock. - Meta interface{} - - GetConfigSchemaCalled bool - GetConfigSchemaReturnSchema *configschema.Block - GetConfigSchemaReturnError error - - ApplyCalled bool - ApplyOutput UIOutput - ApplyState *InstanceState - ApplyConfig *ResourceConfig - ApplyFn func(*InstanceState, *ResourceConfig) error - ApplyReturnError error - - ValidateCalled bool - ValidateConfig *ResourceConfig - ValidateFn func(c *ResourceConfig) ([]string, []error) - ValidateReturnWarns []string - ValidateReturnErrors []error - - StopCalled bool - StopFn func() error - StopReturnError error -} - -var _ ResourceProvisioner = (*MockResourceProvisioner)(nil) - -func (p *MockResourceProvisioner) GetConfigSchema() (*configschema.Block, error) { - p.GetConfigSchemaCalled = true - return p.GetConfigSchemaReturnSchema, p.GetConfigSchemaReturnError -} - -func (p *MockResourceProvisioner) Validate(c *ResourceConfig) ([]string, []error) { - p.Lock() - defer p.Unlock() - - p.ValidateCalled = true - p.ValidateConfig = c - if p.ValidateFn != nil { - return p.ValidateFn(c) - } - return p.ValidateReturnWarns, p.ValidateReturnErrors -} - -func (p *MockResourceProvisioner) Apply( - output UIOutput, - state *InstanceState, - c *ResourceConfig) error { - p.Lock() - - p.ApplyCalled = true - p.ApplyOutput = output - p.ApplyState = state - p.ApplyConfig = c - if p.ApplyFn != nil { - fn := p.ApplyFn - p.Unlock() - return fn(state, c) - } - - defer p.Unlock() - return p.ApplyReturnError -} - -func (p *MockResourceProvisioner) Stop() error { - p.Lock() - defer p.Unlock() - - p.StopCalled = true - if p.StopFn != nil { - return p.StopFn() - } - - return p.StopReturnError -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/schemas.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/schemas.go deleted file mode 100644 index 8bc3b017b1e..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/schemas.go +++ /dev/null @@ -1,278 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// Schemas is a container for various kinds of schema that Terraform needs -// during processing. -type Schemas struct { - Providers map[string]*ProviderSchema - Provisioners map[string]*configschema.Block -} - -// ProviderSchema returns the entire ProviderSchema object that was produced -// by the plugin for the given provider, or nil if no such schema is available. -// -// It's usually better to go use the more precise methods offered by type -// Schemas to handle this detail automatically. -func (ss *Schemas) ProviderSchema(typeName string) *ProviderSchema { - if ss.Providers == nil { - return nil - } - return ss.Providers[typeName] -} - -// ProviderConfig returns the schema for the provider configuration of the -// given provider type, or nil if no such schema is available. -func (ss *Schemas) ProviderConfig(typeName string) *configschema.Block { - ps := ss.ProviderSchema(typeName) - if ps == nil { - return nil - } - return ps.Provider -} - -// ResourceTypeConfig returns the schema for the configuration of a given -// resource type belonging to a given provider type, or nil of no such -// schema is available. -// -// In many cases the provider type is inferrable from the resource type name, -// but this is not always true because users can override the provider for -// a resource using the "provider" meta-argument. Therefore it's important to -// always pass the correct provider name, even though it many cases it feels -// redundant. -func (ss *Schemas) ResourceTypeConfig(providerType string, resourceMode addrs.ResourceMode, resourceType string) (block *configschema.Block, schemaVersion uint64) { - ps := ss.ProviderSchema(providerType) - if ps == nil || ps.ResourceTypes == nil { - return nil, 0 - } - return ps.SchemaForResourceType(resourceMode, resourceType) -} - -// ProvisionerConfig returns the schema for the configuration of a given -// provisioner, or nil of no such schema is available. -func (ss *Schemas) ProvisionerConfig(name string) *configschema.Block { - return ss.Provisioners[name] -} - -// LoadSchemas searches the given configuration, state and plan (any of which -// may be nil) for constructs that have an associated schema, requests the -// necessary schemas from the given component factory (which must _not_ be nil), -// and returns a single object representing all of the necessary schemas. -// -// If an error is returned, it may be a wrapped tfdiags.Diagnostics describing -// errors across multiple separate objects. Errors here will usually indicate -// either misbehavior on the part of one of the providers or of the provider -// protocol itself. When returned with errors, the returned schemas object is -// still valid but may be incomplete. -func LoadSchemas(config *configs.Config, state *states.State, components contextComponentFactory) (*Schemas, error) { - schemas := &Schemas{ - Providers: map[string]*ProviderSchema{}, - Provisioners: map[string]*configschema.Block{}, - } - var diags tfdiags.Diagnostics - - newDiags := loadProviderSchemas(schemas.Providers, config, state, components) - diags = diags.Append(newDiags) - newDiags = loadProvisionerSchemas(schemas.Provisioners, config, components) - diags = diags.Append(newDiags) - - return schemas, diags.Err() -} - -func loadProviderSchemas(schemas map[string]*ProviderSchema, config *configs.Config, state *states.State, components contextComponentFactory) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - ensure := func(typeName string) { - if _, exists := schemas[typeName]; exists { - return - } - - log.Printf("[TRACE] LoadSchemas: retrieving schema for provider type %q", typeName) - provider, err := components.ResourceProvider(typeName, "early/"+typeName) - if err != nil { - // We'll put a stub in the map so we won't re-attempt this on - // future calls. - schemas[typeName] = &ProviderSchema{} - diags = diags.Append( - fmt.Errorf("Failed to instantiate provider %q to obtain schema: %s", typeName, err), - ) - return - } - defer func() { - provider.Close() - }() - - resp := provider.GetSchema() - if resp.Diagnostics.HasErrors() { - // We'll put a stub in the map so we won't re-attempt this on - // future calls. - schemas[typeName] = &ProviderSchema{} - diags = diags.Append( - fmt.Errorf("Failed to retrieve schema from provider %q: %s", typeName, resp.Diagnostics.Err()), - ) - return - } - - s := &ProviderSchema{ - Provider: resp.Provider.Block, - ResourceTypes: make(map[string]*configschema.Block), - DataSources: make(map[string]*configschema.Block), - - ResourceTypeSchemaVersions: make(map[string]uint64), - } - - if resp.Provider.Version < 0 { - // We're not using the version numbers here yet, but we'll check - // for validity anyway in case we start using them in future. - diags = diags.Append( - fmt.Errorf("invalid negative schema version provider configuration for provider %q", typeName), - ) - } - - for t, r := range resp.ResourceTypes { - s.ResourceTypes[t] = r.Block - s.ResourceTypeSchemaVersions[t] = uint64(r.Version) - if r.Version < 0 { - diags = diags.Append( - fmt.Errorf("invalid negative schema version for resource type %s in provider %q", t, typeName), - ) - } - } - - for t, d := range resp.DataSources { - s.DataSources[t] = d.Block - if d.Version < 0 { - // We're not using the version numbers here yet, but we'll check - // for validity anyway in case we start using them in future. - diags = diags.Append( - fmt.Errorf("invalid negative schema version for data source %s in provider %q", t, typeName), - ) - } - } - - schemas[typeName] = s - } - - if config != nil { - for _, typeName := range config.ProviderTypes() { - ensure(typeName) - } - } - - if state != nil { - needed := providers.AddressedTypesAbs(state.ProviderAddrs()) - for _, typeName := range needed { - ensure(typeName) - } - } - - return diags -} - -func loadProvisionerSchemas(schemas map[string]*configschema.Block, config *configs.Config, components contextComponentFactory) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - ensure := func(name string) { - if _, exists := schemas[name]; exists { - return - } - - log.Printf("[TRACE] LoadSchemas: retrieving schema for provisioner %q", name) - provisioner, err := components.ResourceProvisioner(name, "early/"+name) - if err != nil { - // We'll put a stub in the map so we won't re-attempt this on - // future calls. - schemas[name] = &configschema.Block{} - diags = diags.Append( - fmt.Errorf("Failed to instantiate provisioner %q to obtain schema: %s", name, err), - ) - return - } - defer func() { - if closer, ok := provisioner.(ResourceProvisionerCloser); ok { - closer.Close() - } - }() - - resp := provisioner.GetSchema() - if resp.Diagnostics.HasErrors() { - // We'll put a stub in the map so we won't re-attempt this on - // future calls. - schemas[name] = &configschema.Block{} - diags = diags.Append( - fmt.Errorf("Failed to retrieve schema from provisioner %q: %s", name, resp.Diagnostics.Err()), - ) - return - } - - schemas[name] = resp.Provisioner - } - - if config != nil { - for _, rc := range config.Module.ManagedResources { - for _, pc := range rc.Managed.Provisioners { - ensure(pc.Type) - } - } - - // Must also visit our child modules, recursively. - for _, cc := range config.Children { - childDiags := loadProvisionerSchemas(schemas, cc, components) - diags = diags.Append(childDiags) - } - } - - return diags -} - -// ProviderSchema represents the schema for a provider's own configuration -// and the configuration for some or all of its resources and data sources. -// -// The completeness of this structure depends on how it was constructed. -// When constructed for a configuration, it will generally include only -// resource types and data sources used by that configuration. -type ProviderSchema struct { - Provider *configschema.Block - ResourceTypes map[string]*configschema.Block - DataSources map[string]*configschema.Block - - ResourceTypeSchemaVersions map[string]uint64 -} - -// SchemaForResourceType attempts to find a schema for the given mode and type. -// Returns nil if no such schema is available. -func (ps *ProviderSchema) SchemaForResourceType(mode addrs.ResourceMode, typeName string) (schema *configschema.Block, version uint64) { - switch mode { - case addrs.ManagedResourceMode: - return ps.ResourceTypes[typeName], ps.ResourceTypeSchemaVersions[typeName] - case addrs.DataResourceMode: - // Data resources don't have schema versions right now, since state is discarded for each refresh - return ps.DataSources[typeName], 0 - default: - // Shouldn't happen, because the above cases are comprehensive. - return nil, 0 - } -} - -// SchemaForResourceAddr attempts to find a schema for the mode and type from -// the given resource address. Returns nil if no such schema is available. -func (ps *ProviderSchema) SchemaForResourceAddr(addr addrs.Resource) (schema *configschema.Block, version uint64) { - return ps.SchemaForResourceType(addr.Mode, addr.Type) -} - -// ProviderSchemaRequest is used to describe to a ResourceProvider which -// aspects of schema are required, when calling the GetSchema method. -type ProviderSchemaRequest struct { - ResourceTypes []string - DataSources []string -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state.go deleted file mode 100644 index b2b308e7905..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state.go +++ /dev/null @@ -1,2217 +0,0 @@ -package terraform - -import ( - "bufio" - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "os" - "reflect" - "sort" - "strconv" - "strings" - "sync" - - "github.com/hashicorp/errwrap" - multierror "github.com/hashicorp/go-multierror" - uuid "github.com/hashicorp/go-uuid" - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/hclsyntax" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - tfversion "github.com/hashicorp/terraform-plugin-sdk/internal/version" - "github.com/mitchellh/copystructure" - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" -) - -const ( - // StateVersion is the current version for our state file - StateVersion = 3 -) - -// rootModulePath is the path of the root module -var rootModulePath = []string{"root"} - -// normalizeModulePath transforms a legacy module path (which may or may not -// have a redundant "root" label at the start of it) into an -// addrs.ModuleInstance representing the same module. -// -// For legacy reasons, different parts of Terraform disagree about whether the -// root module has the path []string{} or []string{"root"}, and so this -// function accepts both and trims off the "root". An implication of this is -// that it's not possible to actually have a module call in the root module -// that is itself named "root", since that would be ambiguous. -// -// normalizeModulePath takes a raw module path and returns a path that -// has the rootModulePath prepended to it. If I could go back in time I -// would've never had a rootModulePath (empty path would be root). We can -// still fix this but thats a big refactor that my branch doesn't make sense -// for. Instead, this function normalizes paths. -func normalizeModulePath(p []string) addrs.ModuleInstance { - // FIXME: Remove this once everyone is using addrs.ModuleInstance. - - if len(p) > 0 && p[0] == "root" { - p = p[1:] - } - - ret := make(addrs.ModuleInstance, len(p)) - for i, name := range p { - // For now we don't actually support modules with multiple instances - // identified by keys, so we just treat every path element as a - // step with no key. - ret[i] = addrs.ModuleInstanceStep{ - Name: name, - } - } - return ret -} - -// State keeps track of a snapshot state-of-the-world that Terraform -// can use to keep track of what real world resources it is actually -// managing. -type State struct { - // Version is the state file protocol version. - Version int `json:"version"` - - // TFVersion is the version of Terraform that wrote this state. - TFVersion string `json:"terraform_version,omitempty"` - - // Serial is incremented on any operation that modifies - // the State file. It is used to detect potentially conflicting - // updates. - Serial int64 `json:"serial"` - - // Lineage is set when a new, blank state is created and then - // never updated. This allows us to determine whether the serials - // of two states can be meaningfully compared. - // Apart from the guarantee that collisions between two lineages - // are very unlikely, this value is opaque and external callers - // should only compare lineage strings byte-for-byte for equality. - Lineage string `json:"lineage"` - - // Remote is used to track the metadata required to - // pull and push state files from a remote storage endpoint. - Remote *RemoteState `json:"remote,omitempty"` - - // Backend tracks the configuration for the backend in use with - // this state. This is used to track any changes in the backend - // configuration. - Backend *BackendState `json:"backend,omitempty"` - - // Modules contains all the modules in a breadth-first order - Modules []*ModuleState `json:"modules"` - - mu sync.Mutex -} - -func (s *State) Lock() { s.mu.Lock() } -func (s *State) Unlock() { s.mu.Unlock() } - -// NewState is used to initialize a blank state -func NewState() *State { - s := &State{} - s.init() - return s -} - -// Children returns the ModuleStates that are direct children of -// the given path. If the path is "root", for example, then children -// returned might be "root.child", but not "root.child.grandchild". -func (s *State) Children(path []string) []*ModuleState { - s.Lock() - defer s.Unlock() - // TODO: test - - return s.children(path) -} - -func (s *State) children(path []string) []*ModuleState { - result := make([]*ModuleState, 0) - for _, m := range s.Modules { - if m == nil { - continue - } - - if len(m.Path) != len(path)+1 { - continue - } - if !reflect.DeepEqual(path, m.Path[:len(path)]) { - continue - } - - result = append(result, m) - } - - return result -} - -// AddModule adds the module with the given path to the state. -// -// This should be the preferred method to add module states since it -// allows us to optimize lookups later as well as control sorting. -func (s *State) AddModule(path addrs.ModuleInstance) *ModuleState { - s.Lock() - defer s.Unlock() - - return s.addModule(path) -} - -func (s *State) addModule(path addrs.ModuleInstance) *ModuleState { - // check if the module exists first - m := s.moduleByPath(path) - if m != nil { - return m - } - - // Lower the new-style address into a legacy-style address. - // This requires that none of the steps have instance keys, which is - // true for all addresses at the time of implementing this because - // "count" and "for_each" are not yet implemented for modules. - // For the purposes of state, the legacy address format also includes - // a redundant extra prefix element "root". It is important to include - // this because the "prune" method will remove any module that has a - // path length less than one, and other parts of the state code will - // trim off the first element indiscriminately. - legacyPath := make([]string, len(path)+1) - legacyPath[0] = "root" - for i, step := range path { - if step.InstanceKey != addrs.NoKey { - // FIXME: Once the rest of Terraform is ready to use count and - // for_each, remove all of this and just write the addrs.ModuleInstance - // value itself into the ModuleState. - panic("state cannot represent modules with count or for_each keys") - } - - legacyPath[i+1] = step.Name - } - - m = &ModuleState{Path: legacyPath} - m.init() - s.Modules = append(s.Modules, m) - s.sort() - return m -} - -// ModuleByPath is used to lookup the module state for the given path. -// This should be the preferred lookup mechanism as it allows for future -// lookup optimizations. -func (s *State) ModuleByPath(path addrs.ModuleInstance) *ModuleState { - if s == nil { - return nil - } - s.Lock() - defer s.Unlock() - - return s.moduleByPath(path) -} - -func (s *State) moduleByPath(path addrs.ModuleInstance) *ModuleState { - for _, mod := range s.Modules { - if mod == nil { - continue - } - if mod.Path == nil { - panic("missing module path") - } - modPath := normalizeModulePath(mod.Path) - if modPath.String() == path.String() { - return mod - } - } - return nil -} - -// Empty returns true if the state is empty. -func (s *State) Empty() bool { - if s == nil { - return true - } - s.Lock() - defer s.Unlock() - - return len(s.Modules) == 0 -} - -// HasResources returns true if the state contains any resources. -// -// This is similar to !s.Empty, but returns true also in the case where the -// state has modules but all of them are devoid of resources. -func (s *State) HasResources() bool { - if s.Empty() { - return false - } - - for _, mod := range s.Modules { - if len(mod.Resources) > 0 { - return true - } - } - - return false -} - -// IsRemote returns true if State represents a state that exists and is -// remote. -func (s *State) IsRemote() bool { - if s == nil { - return false - } - s.Lock() - defer s.Unlock() - - if s.Remote == nil { - return false - } - if s.Remote.Type == "" { - return false - } - - return true -} - -// Validate validates the integrity of this state file. -// -// Certain properties of the statefile are expected by Terraform in order -// to behave properly. The core of Terraform will assume that once it -// receives a State structure that it has been validated. This validation -// check should be called to ensure that. -// -// If this returns an error, then the user should be notified. The error -// response will include detailed information on the nature of the error. -func (s *State) Validate() error { - s.Lock() - defer s.Unlock() - - var result error - - // !!!! FOR DEVELOPERS !!!! - // - // Any errors returned from this Validate function will BLOCK TERRAFORM - // from loading a state file. Therefore, this should only contain checks - // that are only resolvable through manual intervention. - // - // !!!! FOR DEVELOPERS !!!! - - // Make sure there are no duplicate module states. We open a new - // block here so we can use basic variable names and future validations - // can do the same. - { - found := make(map[string]struct{}) - for _, ms := range s.Modules { - if ms == nil { - continue - } - - key := strings.Join(ms.Path, ".") - if _, ok := found[key]; ok { - result = multierror.Append(result, fmt.Errorf( - strings.TrimSpace(stateValidateErrMultiModule), key)) - continue - } - - found[key] = struct{}{} - } - } - - return result -} - -// Remove removes the item in the state at the given address, returning -// any errors that may have occurred. -// -// If the address references a module state or resource, it will delete -// all children as well. To check what will be deleted, use a StateFilter -// first. -func (s *State) Remove(addr ...string) error { - s.Lock() - defer s.Unlock() - - // Filter out what we need to delete - filter := &StateFilter{State: s} - results, err := filter.Filter(addr...) - if err != nil { - return err - } - - // If we have no results, just exit early, we're not going to do anything. - // While what happens below is fairly fast, this is an important early - // exit since the prune below might modify the state more and we don't - // want to modify the state if we don't have to. - if len(results) == 0 { - return nil - } - - // Go through each result and grab what we need - removed := make(map[interface{}]struct{}) - for _, r := range results { - // Convert the path to our own type - path := append([]string{"root"}, r.Path...) - - // If we removed this already, then ignore - if _, ok := removed[r.Value]; ok { - continue - } - - // If we removed the parent already, then ignore - if r.Parent != nil { - if _, ok := removed[r.Parent.Value]; ok { - continue - } - } - - // Add this to the removed list - removed[r.Value] = struct{}{} - - switch v := r.Value.(type) { - case *ModuleState: - s.removeModule(path, v) - case *ResourceState: - s.removeResource(path, v) - case *InstanceState: - s.removeInstance(path, r.Parent.Value.(*ResourceState), v) - default: - return fmt.Errorf("unknown type to delete: %T", r.Value) - } - } - - // Prune since the removal functions often do the bare minimum to - // remove a thing and may leave around dangling empty modules, resources, - // etc. Prune will clean that all up. - s.prune() - - return nil -} - -func (s *State) removeModule(path []string, v *ModuleState) { - for i, m := range s.Modules { - if m == v { - s.Modules, s.Modules[len(s.Modules)-1] = append(s.Modules[:i], s.Modules[i+1:]...), nil - return - } - } -} - -func (s *State) removeResource(path []string, v *ResourceState) { - // Get the module this resource lives in. If it doesn't exist, we're done. - mod := s.moduleByPath(normalizeModulePath(path)) - if mod == nil { - return - } - - // Find this resource. This is a O(N) lookup when if we had the key - // it could be O(1) but even with thousands of resources this shouldn't - // matter right now. We can easily up performance here when the time comes. - for k, r := range mod.Resources { - if r == v { - // Found it - delete(mod.Resources, k) - return - } - } -} - -func (s *State) removeInstance(path []string, r *ResourceState, v *InstanceState) { - // Go through the resource and find the instance that matches this - // (if any) and remove it. - - // Check primary - if r.Primary == v { - r.Primary = nil - return - } - - // Check lists - lists := [][]*InstanceState{r.Deposed} - for _, is := range lists { - for i, instance := range is { - if instance == v { - // Found it, remove it - is, is[len(is)-1] = append(is[:i], is[i+1:]...), nil - - // Done - return - } - } - } -} - -// RootModule returns the ModuleState for the root module -func (s *State) RootModule() *ModuleState { - root := s.ModuleByPath(addrs.RootModuleInstance) - if root == nil { - panic("missing root module") - } - return root -} - -// Equal tests if one state is equal to another. -func (s *State) Equal(other *State) bool { - // If one is nil, we do a direct check - if s == nil || other == nil { - return s == other - } - - s.Lock() - defer s.Unlock() - return s.equal(other) -} - -func (s *State) equal(other *State) bool { - if s == nil || other == nil { - return s == other - } - - // If the versions are different, they're certainly not equal - if s.Version != other.Version { - return false - } - - // If any of the modules are not equal, then this state isn't equal - if len(s.Modules) != len(other.Modules) { - return false - } - for _, m := range s.Modules { - // This isn't very optimal currently but works. - otherM := other.moduleByPath(normalizeModulePath(m.Path)) - if otherM == nil { - return false - } - - // If they're not equal, then we're not equal! - if !m.Equal(otherM) { - return false - } - } - - return true -} - -// MarshalEqual is similar to Equal but provides a stronger definition of -// "equal", where two states are equal if and only if their serialized form -// is byte-for-byte identical. -// -// This is primarily useful for callers that are trying to save snapshots -// of state to persistent storage, allowing them to detect when a new -// snapshot must be taken. -// -// Note that the serial number and lineage are included in the serialized form, -// so it's the caller's responsibility to properly manage these attributes -// so that this method is only called on two states that have the same -// serial and lineage, unless detecting such differences is desired. -func (s *State) MarshalEqual(other *State) bool { - if s == nil && other == nil { - return true - } else if s == nil || other == nil { - return false - } - - recvBuf := &bytes.Buffer{} - otherBuf := &bytes.Buffer{} - - err := WriteState(s, recvBuf) - if err != nil { - // should never happen, since we're writing to a buffer - panic(err) - } - - err = WriteState(other, otherBuf) - if err != nil { - // should never happen, since we're writing to a buffer - panic(err) - } - - return bytes.Equal(recvBuf.Bytes(), otherBuf.Bytes()) -} - -type StateAgeComparison int - -const ( - StateAgeEqual StateAgeComparison = 0 - StateAgeReceiverNewer StateAgeComparison = 1 - StateAgeReceiverOlder StateAgeComparison = -1 -) - -// CompareAges compares one state with another for which is "older". -// -// This is a simple check using the state's serial, and is thus only as -// reliable as the serial itself. In the normal case, only one state -// exists for a given combination of lineage/serial, but Terraform -// does not guarantee this and so the result of this method should be -// used with care. -// -// Returns an integer that is negative if the receiver is older than -// the argument, positive if the converse, and zero if they are equal. -// An error is returned if the two states are not of the same lineage, -// in which case the integer returned has no meaning. -func (s *State) CompareAges(other *State) (StateAgeComparison, error) { - // nil states are "older" than actual states - switch { - case s != nil && other == nil: - return StateAgeReceiverNewer, nil - case s == nil && other != nil: - return StateAgeReceiverOlder, nil - case s == nil && other == nil: - return StateAgeEqual, nil - } - - if !s.SameLineage(other) { - return StateAgeEqual, fmt.Errorf( - "can't compare two states of differing lineage", - ) - } - - s.Lock() - defer s.Unlock() - - switch { - case s.Serial < other.Serial: - return StateAgeReceiverOlder, nil - case s.Serial > other.Serial: - return StateAgeReceiverNewer, nil - default: - return StateAgeEqual, nil - } -} - -// SameLineage returns true only if the state given in argument belongs -// to the same "lineage" of states as the receiver. -func (s *State) SameLineage(other *State) bool { - s.Lock() - defer s.Unlock() - - // If one of the states has no lineage then it is assumed to predate - // this concept, and so we'll accept it as belonging to any lineage - // so that a lineage string can be assigned to newer versions - // without breaking compatibility with older versions. - if s.Lineage == "" || other.Lineage == "" { - return true - } - - return s.Lineage == other.Lineage -} - -// DeepCopy performs a deep copy of the state structure and returns -// a new structure. -func (s *State) DeepCopy() *State { - if s == nil { - return nil - } - - copy, err := copystructure.Config{Lock: true}.Copy(s) - if err != nil { - panic(err) - } - - return copy.(*State) -} - -// FromFutureTerraform checks if this state was written by a Terraform -// version from the future. -func (s *State) FromFutureTerraform() bool { - s.Lock() - defer s.Unlock() - - // No TF version means it is certainly from the past - if s.TFVersion == "" { - return false - } - - v := version.Must(version.NewVersion(s.TFVersion)) - return tfversion.SemVer.LessThan(v) -} - -func (s *State) Init() { - s.Lock() - defer s.Unlock() - s.init() -} - -func (s *State) init() { - if s.Version == 0 { - s.Version = StateVersion - } - - if s.moduleByPath(addrs.RootModuleInstance) == nil { - s.addModule(addrs.RootModuleInstance) - } - s.ensureHasLineage() - - for _, mod := range s.Modules { - if mod != nil { - mod.init() - } - } - - if s.Remote != nil { - s.Remote.init() - } - -} - -func (s *State) EnsureHasLineage() { - s.Lock() - defer s.Unlock() - - s.ensureHasLineage() -} - -func (s *State) ensureHasLineage() { - if s.Lineage == "" { - lineage, err := uuid.GenerateUUID() - if err != nil { - panic(fmt.Errorf("Failed to generate lineage: %v", err)) - } - s.Lineage = lineage - log.Printf("[DEBUG] New state was assigned lineage %q\n", s.Lineage) - } else { - log.Printf("[TRACE] Preserving existing state lineage %q\n", s.Lineage) - } -} - -// AddModuleState insert this module state and override any existing ModuleState -func (s *State) AddModuleState(mod *ModuleState) { - mod.init() - s.Lock() - defer s.Unlock() - - s.addModuleState(mod) -} - -func (s *State) addModuleState(mod *ModuleState) { - for i, m := range s.Modules { - if reflect.DeepEqual(m.Path, mod.Path) { - s.Modules[i] = mod - return - } - } - - s.Modules = append(s.Modules, mod) - s.sort() -} - -// prune is used to remove any resources that are no longer required -func (s *State) prune() { - if s == nil { - return - } - - // Filter out empty modules. - // A module is always assumed to have a path, and it's length isn't always - // bounds checked later on. Modules may be "emptied" during destroy, but we - // never want to store those in the state. - for i := 0; i < len(s.Modules); i++ { - if s.Modules[i] == nil || len(s.Modules[i].Path) == 0 { - s.Modules = append(s.Modules[:i], s.Modules[i+1:]...) - i-- - } - } - - for _, mod := range s.Modules { - mod.prune() - } - if s.Remote != nil && s.Remote.Empty() { - s.Remote = nil - } -} - -// sort sorts the modules -func (s *State) sort() { - sort.Sort(moduleStateSort(s.Modules)) - - // Allow modules to be sorted - for _, m := range s.Modules { - if m != nil { - m.sort() - } - } -} - -func (s *State) String() string { - if s == nil { - return "" - } - s.Lock() - defer s.Unlock() - - var buf bytes.Buffer - for _, m := range s.Modules { - mStr := m.String() - - // If we're the root module, we just write the output directly. - if reflect.DeepEqual(m.Path, rootModulePath) { - buf.WriteString(mStr + "\n") - continue - } - - buf.WriteString(fmt.Sprintf("module.%s:\n", strings.Join(m.Path[1:], "."))) - - s := bufio.NewScanner(strings.NewReader(mStr)) - for s.Scan() { - text := s.Text() - if text != "" { - text = " " + text - } - - buf.WriteString(fmt.Sprintf("%s\n", text)) - } - } - - return strings.TrimSpace(buf.String()) -} - -// BackendState stores the configuration to connect to a remote backend. -type BackendState struct { - Type string `json:"type"` // Backend type - ConfigRaw json.RawMessage `json:"config"` // Backend raw config - Hash uint64 `json:"hash"` // Hash of portion of configuration from config files -} - -// Empty returns true if BackendState has no state. -func (s *BackendState) Empty() bool { - return s == nil || s.Type == "" -} - -// Config decodes the type-specific configuration object using the provided -// schema and returns the result as a cty.Value. -// -// An error is returned if the stored configuration does not conform to the -// given schema. -func (s *BackendState) Config(schema *configschema.Block) (cty.Value, error) { - ty := schema.ImpliedType() - if s == nil { - return cty.NullVal(ty), nil - } - return ctyjson.Unmarshal(s.ConfigRaw, ty) -} - -// SetConfig replaces (in-place) the type-specific configuration object using -// the provided value and associated schema. -// -// An error is returned if the given value does not conform to the implied -// type of the schema. -func (s *BackendState) SetConfig(val cty.Value, schema *configschema.Block) error { - ty := schema.ImpliedType() - buf, err := ctyjson.Marshal(val, ty) - if err != nil { - return err - } - s.ConfigRaw = buf - return nil -} - -// ForPlan produces an alternative representation of the reciever that is -// suitable for storing in a plan. The current workspace must additionally -// be provided, to be stored alongside the backend configuration. -// -// The backend configuration schema is required in order to properly -// encode the backend-specific configuration settings. -func (s *BackendState) ForPlan(schema *configschema.Block, workspaceName string) (*plans.Backend, error) { - if s == nil { - return nil, nil - } - - configVal, err := s.Config(schema) - if err != nil { - return nil, errwrap.Wrapf("failed to decode backend config: {{err}}", err) - } - return plans.NewBackend(s.Type, configVal, schema, workspaceName) -} - -// RemoteState is used to track the information about a remote -// state store that we push/pull state to. -type RemoteState struct { - // Type controls the client we use for the remote state - Type string `json:"type"` - - // Config is used to store arbitrary configuration that - // is type specific - Config map[string]string `json:"config"` - - mu sync.Mutex -} - -func (s *RemoteState) Lock() { s.mu.Lock() } -func (s *RemoteState) Unlock() { s.mu.Unlock() } - -func (r *RemoteState) init() { - r.Lock() - defer r.Unlock() - - if r.Config == nil { - r.Config = make(map[string]string) - } -} - -func (r *RemoteState) Empty() bool { - if r == nil { - return true - } - r.Lock() - defer r.Unlock() - - return r.Type == "" -} - -func (r *RemoteState) Equals(other *RemoteState) bool { - r.Lock() - defer r.Unlock() - - if r.Type != other.Type { - return false - } - if len(r.Config) != len(other.Config) { - return false - } - for k, v := range r.Config { - if other.Config[k] != v { - return false - } - } - return true -} - -// OutputState is used to track the state relevant to a single output. -type OutputState struct { - // Sensitive describes whether the output is considered sensitive, - // which may lead to masking the value on screen in some cases. - Sensitive bool `json:"sensitive"` - // Type describes the structure of Value. Valid values are "string", - // "map" and "list" - Type string `json:"type"` - // Value contains the value of the output, in the structure described - // by the Type field. - Value interface{} `json:"value"` - - mu sync.Mutex -} - -func (s *OutputState) Lock() { s.mu.Lock() } -func (s *OutputState) Unlock() { s.mu.Unlock() } - -func (s *OutputState) String() string { - return fmt.Sprintf("%#v", s.Value) -} - -// Equal compares two OutputState structures for equality. nil values are -// considered equal. -func (s *OutputState) Equal(other *OutputState) bool { - if s == nil && other == nil { - return true - } - - if s == nil || other == nil { - return false - } - s.Lock() - defer s.Unlock() - - if s.Type != other.Type { - return false - } - - if s.Sensitive != other.Sensitive { - return false - } - - if !reflect.DeepEqual(s.Value, other.Value) { - return false - } - - return true -} - -// ModuleState is used to track all the state relevant to a single -// module. Previous to Terraform 0.3, all state belonged to the "root" -// module. -type ModuleState struct { - // Path is the import path from the root module. Modules imports are - // always disjoint, so the path represents amodule tree - Path []string `json:"path"` - - // Locals are kept only transiently in-memory, because we can always - // re-compute them. - Locals map[string]interface{} `json:"-"` - - // Outputs declared by the module and maintained for each module - // even though only the root module technically needs to be kept. - // This allows operators to inspect values at the boundaries. - Outputs map[string]*OutputState `json:"outputs"` - - // Resources is a mapping of the logically named resource to - // the state of the resource. Each resource may actually have - // N instances underneath, although a user only needs to think - // about the 1:1 case. - Resources map[string]*ResourceState `json:"resources"` - - // Dependencies are a list of things that this module relies on - // existing to remain intact. For example: an module may depend - // on a VPC ID given by an aws_vpc resource. - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a module that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on"` - - mu sync.Mutex -} - -func (s *ModuleState) Lock() { s.mu.Lock() } -func (s *ModuleState) Unlock() { s.mu.Unlock() } - -// Equal tests whether one module state is equal to another. -func (m *ModuleState) Equal(other *ModuleState) bool { - m.Lock() - defer m.Unlock() - - // Paths must be equal - if !reflect.DeepEqual(m.Path, other.Path) { - return false - } - - // Outputs must be equal - if len(m.Outputs) != len(other.Outputs) { - return false - } - for k, v := range m.Outputs { - if !other.Outputs[k].Equal(v) { - return false - } - } - - // Dependencies must be equal. This sorts these in place but - // this shouldn't cause any problems. - sort.Strings(m.Dependencies) - sort.Strings(other.Dependencies) - if len(m.Dependencies) != len(other.Dependencies) { - return false - } - for i, d := range m.Dependencies { - if other.Dependencies[i] != d { - return false - } - } - - // Resources must be equal - if len(m.Resources) != len(other.Resources) { - return false - } - for k, r := range m.Resources { - otherR, ok := other.Resources[k] - if !ok { - return false - } - - if !r.Equal(otherR) { - return false - } - } - - return true -} - -// IsRoot says whether or not this module diff is for the root module. -func (m *ModuleState) IsRoot() bool { - m.Lock() - defer m.Unlock() - return reflect.DeepEqual(m.Path, rootModulePath) -} - -// IsDescendent returns true if other is a descendent of this module. -func (m *ModuleState) IsDescendent(other *ModuleState) bool { - m.Lock() - defer m.Unlock() - - i := len(m.Path) - return len(other.Path) > i && reflect.DeepEqual(other.Path[:i], m.Path) -} - -// Orphans returns a list of keys of resources that are in the State -// but aren't present in the configuration itself. Hence, these keys -// represent the state of resources that are orphans. -func (m *ModuleState) Orphans(c *configs.Module) []addrs.ResourceInstance { - m.Lock() - defer m.Unlock() - - inConfig := make(map[string]struct{}) - if c != nil { - for _, r := range c.ManagedResources { - inConfig[r.Addr().String()] = struct{}{} - } - for _, r := range c.DataResources { - inConfig[r.Addr().String()] = struct{}{} - } - } - - var result []addrs.ResourceInstance - for k := range m.Resources { - // Since we've not yet updated state to use our new address format, - // we need to do some shimming here. - legacyAddr, err := parseResourceAddressInternal(k) - if err != nil { - // Suggests that the user tampered with the state, since we always - // generate valid internal addresses. - log.Printf("ModuleState has invalid resource key %q. Ignoring.", k) - continue - } - - addr := legacyAddr.AbsResourceInstanceAddr().Resource - compareKey := addr.Resource.String() // compare by resource address, ignoring instance key - if _, exists := inConfig[compareKey]; !exists { - result = append(result, addr) - } - } - return result -} - -// RemovedOutputs returns a list of outputs that are in the State but aren't -// present in the configuration itself. -func (s *ModuleState) RemovedOutputs(outputs map[string]*configs.Output) []addrs.OutputValue { - if outputs == nil { - // If we got no output map at all then we'll just treat our set of - // configured outputs as empty, since that suggests that they've all - // been removed by removing their containing module. - outputs = make(map[string]*configs.Output) - } - - s.Lock() - defer s.Unlock() - - var ret []addrs.OutputValue - for n := range s.Outputs { - if _, declared := outputs[n]; !declared { - ret = append(ret, addrs.OutputValue{ - Name: n, - }) - } - } - - return ret -} - -// View returns a view with the given resource prefix. -func (m *ModuleState) View(id string) *ModuleState { - if m == nil { - return m - } - - r := m.deepcopy() - for k := range r.Resources { - if id == k || strings.HasPrefix(k, id+".") { - continue - } - - delete(r.Resources, k) - } - - return r -} - -func (m *ModuleState) init() { - m.Lock() - defer m.Unlock() - - if m.Path == nil { - m.Path = []string{} - } - if m.Outputs == nil { - m.Outputs = make(map[string]*OutputState) - } - if m.Resources == nil { - m.Resources = make(map[string]*ResourceState) - } - - if m.Dependencies == nil { - m.Dependencies = make([]string, 0) - } - - for _, rs := range m.Resources { - rs.init() - } -} - -func (m *ModuleState) deepcopy() *ModuleState { - if m == nil { - return nil - } - - stateCopy, err := copystructure.Config{Lock: true}.Copy(m) - if err != nil { - panic(err) - } - - return stateCopy.(*ModuleState) -} - -// prune is used to remove any resources that are no longer required -func (m *ModuleState) prune() { - m.Lock() - defer m.Unlock() - - for k, v := range m.Resources { - if v == nil || (v.Primary == nil || v.Primary.ID == "") && len(v.Deposed) == 0 { - delete(m.Resources, k) - continue - } - - v.prune() - } - - for k, v := range m.Outputs { - if v.Value == hcl2shim.UnknownVariableValue { - delete(m.Outputs, k) - } - } - - m.Dependencies = uniqueStrings(m.Dependencies) -} - -func (m *ModuleState) sort() { - for _, v := range m.Resources { - v.sort() - } -} - -func (m *ModuleState) String() string { - m.Lock() - defer m.Unlock() - - var buf bytes.Buffer - - if len(m.Resources) == 0 { - buf.WriteString("") - } - - names := make([]string, 0, len(m.Resources)) - for name := range m.Resources { - names = append(names, name) - } - - sort.Sort(resourceNameSort(names)) - - for _, k := range names { - rs := m.Resources[k] - var id string - if rs.Primary != nil { - id = rs.Primary.ID - } - if id == "" { - id = "" - } - - taintStr := "" - if rs.Primary.Tainted { - taintStr = " (tainted)" - } - - deposedStr := "" - if len(rs.Deposed) > 0 { - deposedStr = fmt.Sprintf(" (%d deposed)", len(rs.Deposed)) - } - - buf.WriteString(fmt.Sprintf("%s:%s%s\n", k, taintStr, deposedStr)) - buf.WriteString(fmt.Sprintf(" ID = %s\n", id)) - if rs.Provider != "" { - buf.WriteString(fmt.Sprintf(" provider = %s\n", rs.Provider)) - } - - var attributes map[string]string - if rs.Primary != nil { - attributes = rs.Primary.Attributes - } - attrKeys := make([]string, 0, len(attributes)) - for ak := range attributes { - if ak == "id" { - continue - } - - attrKeys = append(attrKeys, ak) - } - - sort.Strings(attrKeys) - - for _, ak := range attrKeys { - av := attributes[ak] - buf.WriteString(fmt.Sprintf(" %s = %s\n", ak, av)) - } - - for idx, t := range rs.Deposed { - taintStr := "" - if t.Tainted { - taintStr = " (tainted)" - } - buf.WriteString(fmt.Sprintf(" Deposed ID %d = %s%s\n", idx+1, t.ID, taintStr)) - } - - if len(rs.Dependencies) > 0 { - buf.WriteString(fmt.Sprintf("\n Dependencies:\n")) - for _, dep := range rs.Dependencies { - buf.WriteString(fmt.Sprintf(" %s\n", dep)) - } - } - } - - if len(m.Outputs) > 0 { - buf.WriteString("\nOutputs:\n\n") - - ks := make([]string, 0, len(m.Outputs)) - for k := range m.Outputs { - ks = append(ks, k) - } - - sort.Strings(ks) - - for _, k := range ks { - v := m.Outputs[k] - switch vTyped := v.Value.(type) { - case string: - buf.WriteString(fmt.Sprintf("%s = %s\n", k, vTyped)) - case []interface{}: - buf.WriteString(fmt.Sprintf("%s = %s\n", k, vTyped)) - case map[string]interface{}: - var mapKeys []string - for key := range vTyped { - mapKeys = append(mapKeys, key) - } - sort.Strings(mapKeys) - - var mapBuf bytes.Buffer - mapBuf.WriteString("{") - for _, key := range mapKeys { - mapBuf.WriteString(fmt.Sprintf("%s:%s ", key, vTyped[key])) - } - mapBuf.WriteString("}") - - buf.WriteString(fmt.Sprintf("%s = %s\n", k, mapBuf.String())) - } - } - } - - return buf.String() -} - -func (m *ModuleState) Empty() bool { - return len(m.Locals) == 0 && len(m.Outputs) == 0 && len(m.Resources) == 0 -} - -// ResourceStateKey is a structured representation of the key used for the -// ModuleState.Resources mapping -type ResourceStateKey struct { - Name string - Type string - Mode ResourceMode - Index int -} - -// Equal determines whether two ResourceStateKeys are the same -func (rsk *ResourceStateKey) Equal(other *ResourceStateKey) bool { - if rsk == nil || other == nil { - return false - } - if rsk.Mode != other.Mode { - return false - } - if rsk.Type != other.Type { - return false - } - if rsk.Name != other.Name { - return false - } - if rsk.Index != other.Index { - return false - } - return true -} - -func (rsk *ResourceStateKey) String() string { - if rsk == nil { - return "" - } - var prefix string - switch rsk.Mode { - case ManagedResourceMode: - prefix = "" - case DataResourceMode: - prefix = "data." - default: - panic(fmt.Errorf("unknown resource mode %s", rsk.Mode)) - } - if rsk.Index == -1 { - return fmt.Sprintf("%s%s.%s", prefix, rsk.Type, rsk.Name) - } - return fmt.Sprintf("%s%s.%s.%d", prefix, rsk.Type, rsk.Name, rsk.Index) -} - -// ParseResourceStateKey accepts a key in the format used by -// ModuleState.Resources and returns a resource name and resource index. In the -// state, a resource has the format "type.name.index" or "type.name". In the -// latter case, the index is returned as -1. -func ParseResourceStateKey(k string) (*ResourceStateKey, error) { - parts := strings.Split(k, ".") - mode := ManagedResourceMode - if len(parts) > 0 && parts[0] == "data" { - mode = DataResourceMode - // Don't need the constant "data" prefix for parsing - // now that we've figured out the mode. - parts = parts[1:] - } - if len(parts) < 2 || len(parts) > 3 { - return nil, fmt.Errorf("Malformed resource state key: %s", k) - } - rsk := &ResourceStateKey{ - Mode: mode, - Type: parts[0], - Name: parts[1], - Index: -1, - } - if len(parts) == 3 { - index, err := strconv.Atoi(parts[2]) - if err != nil { - return nil, fmt.Errorf("Malformed resource state key index: %s", k) - } - rsk.Index = index - } - return rsk, nil -} - -// ResourceState holds the state of a resource that is used so that -// a provider can find and manage an existing resource as well as for -// storing attributes that are used to populate variables of child -// resources. -// -// Attributes has attributes about the created resource that are -// queryable in interpolation: "${type.id.attr}" -// -// Extra is just extra data that a provider can return that we store -// for later, but is not exposed in any way to the user. -// -type ResourceState struct { - // This is filled in and managed by Terraform, and is the resource - // type itself such as "mycloud_instance". If a resource provider sets - // this value, it won't be persisted. - Type string `json:"type"` - - // Dependencies are a list of things that this resource relies on - // existing to remain intact. For example: an AWS instance might - // depend on a subnet (which itself might depend on a VPC, and so - // on). - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a resource that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on"` - - // Primary is the current active instance for this resource. - // It can be replaced but only after a successful creation. - // This is the instances on which providers will act. - Primary *InstanceState `json:"primary"` - - // Deposed is used in the mechanics of CreateBeforeDestroy: the existing - // Primary is Deposed to get it out of the way for the replacement Primary to - // be created by Apply. If the replacement Primary creates successfully, the - // Deposed instance is cleaned up. - // - // If there were problems creating the replacement Primary, the Deposed - // instance and the (now tainted) replacement Primary will be swapped so the - // tainted replacement will be cleaned up instead. - // - // An instance will remain in the Deposed list until it is successfully - // destroyed and purged. - Deposed []*InstanceState `json:"deposed"` - - // Provider is used when a resource is connected to a provider with an alias. - // If this string is empty, the resource is connected to the default provider, - // e.g. "aws_instance" goes with the "aws" provider. - // If the resource block contained a "provider" key, that value will be set here. - Provider string `json:"provider"` - - mu sync.Mutex -} - -func (s *ResourceState) Lock() { s.mu.Lock() } -func (s *ResourceState) Unlock() { s.mu.Unlock() } - -// Equal tests whether two ResourceStates are equal. -func (s *ResourceState) Equal(other *ResourceState) bool { - s.Lock() - defer s.Unlock() - - if s.Type != other.Type { - return false - } - - if s.Provider != other.Provider { - return false - } - - // Dependencies must be equal - sort.Strings(s.Dependencies) - sort.Strings(other.Dependencies) - if len(s.Dependencies) != len(other.Dependencies) { - return false - } - for i, d := range s.Dependencies { - if other.Dependencies[i] != d { - return false - } - } - - // States must be equal - if !s.Primary.Equal(other.Primary) { - return false - } - - return true -} - -// Taint marks a resource as tainted. -func (s *ResourceState) Taint() { - s.Lock() - defer s.Unlock() - - if s.Primary != nil { - s.Primary.Tainted = true - } -} - -// Untaint unmarks a resource as tainted. -func (s *ResourceState) Untaint() { - s.Lock() - defer s.Unlock() - - if s.Primary != nil { - s.Primary.Tainted = false - } -} - -// ProviderAddr returns the provider address for the receiver, by parsing the -// string representation saved in state. An error can be returned if the -// value in state is corrupt. -func (s *ResourceState) ProviderAddr() (addrs.AbsProviderConfig, error) { - var diags tfdiags.Diagnostics - - str := s.Provider - traversal, travDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) - diags = diags.Append(travDiags) - if travDiags.HasErrors() { - return addrs.AbsProviderConfig{}, diags.Err() - } - - addr, addrDiags := addrs.ParseAbsProviderConfig(traversal) - diags = diags.Append(addrDiags) - return addr, diags.Err() -} - -func (s *ResourceState) init() { - s.Lock() - defer s.Unlock() - - if s.Primary == nil { - s.Primary = &InstanceState{} - } - s.Primary.init() - - if s.Dependencies == nil { - s.Dependencies = []string{} - } - - if s.Deposed == nil { - s.Deposed = make([]*InstanceState, 0) - } -} - -// prune is used to remove any instances that are no longer required -func (s *ResourceState) prune() { - s.Lock() - defer s.Unlock() - - n := len(s.Deposed) - for i := 0; i < n; i++ { - inst := s.Deposed[i] - if inst == nil || inst.ID == "" { - copy(s.Deposed[i:], s.Deposed[i+1:]) - s.Deposed[n-1] = nil - n-- - i-- - } - } - s.Deposed = s.Deposed[:n] - - s.Dependencies = uniqueStrings(s.Dependencies) -} - -func (s *ResourceState) sort() { - s.Lock() - defer s.Unlock() - - sort.Strings(s.Dependencies) -} - -func (s *ResourceState) String() string { - s.Lock() - defer s.Unlock() - - var buf bytes.Buffer - buf.WriteString(fmt.Sprintf("Type = %s", s.Type)) - return buf.String() -} - -// InstanceState is used to track the unique state information belonging -// to a given instance. -type InstanceState struct { - // A unique ID for this resource. This is opaque to Terraform - // and is only meant as a lookup mechanism for the providers. - ID string `json:"id"` - - // Attributes are basic information about the resource. Any keys here - // are accessible in variable format within Terraform configurations: - // ${resourcetype.name.attribute}. - Attributes map[string]string `json:"attributes"` - - // Ephemeral is used to store any state associated with this instance - // that is necessary for the Terraform run to complete, but is not - // persisted to a state file. - Ephemeral EphemeralState `json:"-"` - - // Meta is a simple K/V map that is persisted to the State but otherwise - // ignored by Terraform core. It's meant to be used for accounting by - // external client code. The value here must only contain Go primitives - // and collections. - Meta map[string]interface{} `json:"meta"` - - // Tainted is used to mark a resource for recreation. - Tainted bool `json:"tainted"` - - mu sync.Mutex -} - -func (s *InstanceState) Lock() { s.mu.Lock() } -func (s *InstanceState) Unlock() { s.mu.Unlock() } - -func (s *InstanceState) init() { - s.Lock() - defer s.Unlock() - - if s.Attributes == nil { - s.Attributes = make(map[string]string) - } - if s.Meta == nil { - s.Meta = make(map[string]interface{}) - } - s.Ephemeral.init() -} - -// NewInstanceStateShimmedFromValue is a shim method to lower a new-style -// object value representing the attributes of an instance object into the -// legacy InstanceState representation. -// -// This is for shimming to old components only and should not be used in new code. -func NewInstanceStateShimmedFromValue(state cty.Value, schemaVersion int) *InstanceState { - attrs := hcl2shim.FlatmapValueFromHCL2(state) - return &InstanceState{ - ID: attrs["id"], - Attributes: attrs, - Meta: map[string]interface{}{ - "schema_version": schemaVersion, - }, - } -} - -// AttrsAsObjectValue shims from the legacy InstanceState representation to -// a new-style cty object value representation of the state attributes, using -// the given type for guidance. -// -// The given type must be the implied type of the schema of the resource type -// of the object whose state is being converted, or the result is undefined. -// -// This is for shimming from old components only and should not be used in -// new code. -func (s *InstanceState) AttrsAsObjectValue(ty cty.Type) (cty.Value, error) { - if s == nil { - // if the state is nil, we need to construct a complete cty.Value with - // null attributes, rather than a single cty.NullVal(ty) - s = &InstanceState{} - } - - if s.Attributes == nil { - s.Attributes = map[string]string{} - } - - // make sure ID is included in the attributes. The InstanceState.ID value - // takes precedence. - if s.ID != "" { - s.Attributes["id"] = s.ID - } - - return hcl2shim.HCL2ValueFromFlatmap(s.Attributes, ty) -} - -// Copy all the Fields from another InstanceState -func (s *InstanceState) Set(from *InstanceState) { - s.Lock() - defer s.Unlock() - - from.Lock() - defer from.Unlock() - - s.ID = from.ID - s.Attributes = from.Attributes - s.Ephemeral = from.Ephemeral - s.Meta = from.Meta - s.Tainted = from.Tainted -} - -func (s *InstanceState) DeepCopy() *InstanceState { - copy, err := copystructure.Config{Lock: true}.Copy(s) - if err != nil { - panic(err) - } - - return copy.(*InstanceState) -} - -func (s *InstanceState) Empty() bool { - if s == nil { - return true - } - s.Lock() - defer s.Unlock() - - return s.ID == "" -} - -func (s *InstanceState) Equal(other *InstanceState) bool { - // Short circuit some nil checks - if s == nil || other == nil { - return s == other - } - s.Lock() - defer s.Unlock() - - // IDs must be equal - if s.ID != other.ID { - return false - } - - // Attributes must be equal - if len(s.Attributes) != len(other.Attributes) { - return false - } - for k, v := range s.Attributes { - otherV, ok := other.Attributes[k] - if !ok { - return false - } - - if v != otherV { - return false - } - } - - // Meta must be equal - if len(s.Meta) != len(other.Meta) { - return false - } - if s.Meta != nil && other.Meta != nil { - // We only do the deep check if both are non-nil. If one is nil - // we treat it as equal since their lengths are both zero (check - // above). - // - // Since this can contain numeric values that may change types during - // serialization, let's compare the serialized values. - sMeta, err := json.Marshal(s.Meta) - if err != nil { - // marshaling primitives shouldn't ever error out - panic(err) - } - otherMeta, err := json.Marshal(other.Meta) - if err != nil { - panic(err) - } - - if !bytes.Equal(sMeta, otherMeta) { - return false - } - } - - if s.Tainted != other.Tainted { - return false - } - - return true -} - -// MergeDiff takes a ResourceDiff and merges the attributes into -// this resource state in order to generate a new state. This new -// state can be used to provide updated attribute lookups for -// variable interpolation. -// -// If the diff attribute requires computing the value, and hence -// won't be available until apply, the value is replaced with the -// computeID. -func (s *InstanceState) MergeDiff(d *InstanceDiff) *InstanceState { - result := s.DeepCopy() - if result == nil { - result = new(InstanceState) - } - result.init() - - if s != nil { - s.Lock() - defer s.Unlock() - for k, v := range s.Attributes { - result.Attributes[k] = v - } - } - if d != nil { - for k, diff := range d.CopyAttributes() { - if diff.NewRemoved { - delete(result.Attributes, k) - continue - } - if diff.NewComputed { - result.Attributes[k] = hcl2shim.UnknownVariableValue - continue - } - - result.Attributes[k] = diff.New - } - } - - return result -} - -func (s *InstanceState) String() string { - notCreated := "" - - if s == nil { - return notCreated - } - - s.Lock() - defer s.Unlock() - - var buf bytes.Buffer - - if s.ID == "" { - return notCreated - } - - buf.WriteString(fmt.Sprintf("ID = %s\n", s.ID)) - - attributes := s.Attributes - attrKeys := make([]string, 0, len(attributes)) - for ak := range attributes { - if ak == "id" { - continue - } - - attrKeys = append(attrKeys, ak) - } - sort.Strings(attrKeys) - - for _, ak := range attrKeys { - av := attributes[ak] - buf.WriteString(fmt.Sprintf("%s = %s\n", ak, av)) - } - - buf.WriteString(fmt.Sprintf("Tainted = %t\n", s.Tainted)) - - return buf.String() -} - -// EphemeralState is used for transient state that is only kept in-memory -type EphemeralState struct { - // ConnInfo is used for the providers to export information which is - // used to connect to the resource for provisioning. For example, - // this could contain SSH or WinRM credentials. - ConnInfo map[string]string `json:"-"` - - // Type is used to specify the resource type for this instance. This is only - // required for import operations (as documented). If the documentation - // doesn't state that you need to set this, then don't worry about - // setting it. - Type string `json:"-"` -} - -func (e *EphemeralState) init() { - if e.ConnInfo == nil { - e.ConnInfo = make(map[string]string) - } -} - -func (e *EphemeralState) DeepCopy() *EphemeralState { - copy, err := copystructure.Config{Lock: true}.Copy(e) - if err != nil { - panic(err) - } - - return copy.(*EphemeralState) -} - -type jsonStateVersionIdentifier struct { - Version int `json:"version"` -} - -// Check if this is a V0 format - the magic bytes at the start of the file -// should be "tfstate" if so. We no longer support upgrading this type of -// state but return an error message explaining to a user how they can -// upgrade via the 0.6.x series. -func testForV0State(buf *bufio.Reader) error { - start, err := buf.Peek(len("tfstate")) - if err != nil { - return fmt.Errorf("Failed to check for magic bytes: %v", err) - } - if string(start) == "tfstate" { - return fmt.Errorf("Terraform 0.7 no longer supports upgrading the binary state\n" + - "format which was used prior to Terraform 0.3. Please upgrade\n" + - "this state file using Terraform 0.6.16 prior to using it with\n" + - "Terraform 0.7.") - } - - return nil -} - -// ErrNoState is returned by ReadState when the io.Reader contains no data -var ErrNoState = errors.New("no state") - -// ReadState reads a state structure out of a reader in the format that -// was written by WriteState. -func ReadState(src io.Reader) (*State, error) { - // check for a nil file specifically, since that produces a platform - // specific error if we try to use it in a bufio.Reader. - if f, ok := src.(*os.File); ok && f == nil { - return nil, ErrNoState - } - - buf := bufio.NewReader(src) - - if _, err := buf.Peek(1); err != nil { - if err == io.EOF { - return nil, ErrNoState - } - return nil, err - } - - if err := testForV0State(buf); err != nil { - return nil, err - } - - // If we are JSON we buffer the whole thing in memory so we can read it twice. - // This is suboptimal, but will work for now. - jsonBytes, err := ioutil.ReadAll(buf) - if err != nil { - return nil, fmt.Errorf("Reading state file failed: %v", err) - } - - versionIdentifier := &jsonStateVersionIdentifier{} - if err := json.Unmarshal(jsonBytes, versionIdentifier); err != nil { - return nil, fmt.Errorf("Decoding state file version failed: %v", err) - } - - var result *State - switch versionIdentifier.Version { - case 0: - return nil, fmt.Errorf("State version 0 is not supported as JSON.") - case 1: - v1State, err := ReadStateV1(jsonBytes) - if err != nil { - return nil, err - } - - v2State, err := upgradeStateV1ToV2(v1State) - if err != nil { - return nil, err - } - - v3State, err := upgradeStateV2ToV3(v2State) - if err != nil { - return nil, err - } - - // increment the Serial whenever we upgrade state - v3State.Serial++ - result = v3State - case 2: - v2State, err := ReadStateV2(jsonBytes) - if err != nil { - return nil, err - } - v3State, err := upgradeStateV2ToV3(v2State) - if err != nil { - return nil, err - } - - v3State.Serial++ - result = v3State - case 3: - v3State, err := ReadStateV3(jsonBytes) - if err != nil { - return nil, err - } - - result = v3State - default: - return nil, fmt.Errorf("Terraform %s does not support state version %d, please update.", - tfversion.SemVer.String(), versionIdentifier.Version) - } - - // If we reached this place we must have a result set - if result == nil { - panic("resulting state in load not set, assertion failed") - } - - // Prune the state when read it. Its possible to write unpruned states or - // for a user to make a state unpruned (nil-ing a module state for example). - result.prune() - - // Validate the state file is valid - if err := result.Validate(); err != nil { - return nil, err - } - - return result, nil -} - -func ReadStateV1(jsonBytes []byte) (*stateV1, error) { - v1State := &stateV1{} - if err := json.Unmarshal(jsonBytes, v1State); err != nil { - return nil, fmt.Errorf("Decoding state file failed: %v", err) - } - - if v1State.Version != 1 { - return nil, fmt.Errorf("Decoded state version did not match the decoder selection: "+ - "read %d, expected 1", v1State.Version) - } - - return v1State, nil -} - -func ReadStateV2(jsonBytes []byte) (*State, error) { - state := &State{} - if err := json.Unmarshal(jsonBytes, state); err != nil { - return nil, fmt.Errorf("Decoding state file failed: %v", err) - } - - // Check the version, this to ensure we don't read a future - // version that we don't understand - if state.Version > StateVersion { - return nil, fmt.Errorf("Terraform %s does not support state version %d, please update.", - tfversion.SemVer.String(), state.Version) - } - - // Make sure the version is semantic - if state.TFVersion != "" { - if _, err := version.NewVersion(state.TFVersion); err != nil { - return nil, fmt.Errorf( - "State contains invalid version: %s\n\n"+ - "Terraform validates the version format prior to writing it. This\n"+ - "means that this is invalid of the state becoming corrupted through\n"+ - "some external means. Please manually modify the Terraform version\n"+ - "field to be a proper semantic version.", - state.TFVersion) - } - } - - // catch any unitialized fields in the state - state.init() - - // Sort it - state.sort() - - return state, nil -} - -func ReadStateV3(jsonBytes []byte) (*State, error) { - state := &State{} - if err := json.Unmarshal(jsonBytes, state); err != nil { - return nil, fmt.Errorf("Decoding state file failed: %v", err) - } - - // Check the version, this to ensure we don't read a future - // version that we don't understand - if state.Version > StateVersion { - return nil, fmt.Errorf("Terraform %s does not support state version %d, please update.", - tfversion.SemVer.String(), state.Version) - } - - // Make sure the version is semantic - if state.TFVersion != "" { - if _, err := version.NewVersion(state.TFVersion); err != nil { - return nil, fmt.Errorf( - "State contains invalid version: %s\n\n"+ - "Terraform validates the version format prior to writing it. This\n"+ - "means that this is invalid of the state becoming corrupted through\n"+ - "some external means. Please manually modify the Terraform version\n"+ - "field to be a proper semantic version.", - state.TFVersion) - } - } - - // 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. - var buf bytes.Buffer - err := WriteState(state, &buf) - if err != nil { - return nil, err - } - - if !bytes.Equal(jsonBytes, buf.Bytes()) { - log.Println("[INFO] state modified during read or write. incrementing serial number") - state.Serial++ - } - - return state, nil -} - -// WriteState writes a state somewhere in a binary format. -func WriteState(d *State, dst io.Writer) error { - // 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 - - // If the TFVersion is set, verify it. We used to just set the version - // here, but this isn't safe since it changes the MD5 sum on some remote - // state storage backends such as Atlas. We now leave it be if needed. - if d.TFVersion != "" { - if _, err := version.NewVersion(d.TFVersion); err != nil { - return fmt.Errorf( - "Error writing state, invalid version: %s\n\n"+ - "The Terraform version when writing the state must be a semantic\n"+ - "version.", - d.TFVersion) - } - } - - // Encode the data in a human-friendly way - data, err := json.MarshalIndent(d, "", " ") - if err != nil { - return fmt.Errorf("Failed to encode state: %s", err) - } - - // We append a newline to the data because MarshalIndent doesn't - data = append(data, '\n') - - // Write the data out to the dst - if _, err := io.Copy(dst, bytes.NewReader(data)); err != nil { - return fmt.Errorf("Failed to write state: %v", err) - } - - return nil -} - -// resourceNameSort implements the sort.Interface to sort name parts lexically for -// strings and numerically for integer indexes. -type resourceNameSort []string - -func (r resourceNameSort) Len() int { return len(r) } -func (r resourceNameSort) Swap(i, j int) { r[i], r[j] = r[j], r[i] } - -func (r resourceNameSort) Less(i, j int) bool { - iParts := strings.Split(r[i], ".") - jParts := strings.Split(r[j], ".") - - end := len(iParts) - if len(jParts) < end { - end = len(jParts) - } - - for idx := 0; idx < end; idx++ { - if iParts[idx] == jParts[idx] { - continue - } - - // sort on the first non-matching part - iInt, iIntErr := strconv.Atoi(iParts[idx]) - jInt, jIntErr := strconv.Atoi(jParts[idx]) - - switch { - case iIntErr == nil && jIntErr == nil: - // sort numerically if both parts are integers - return iInt < jInt - case iIntErr == nil: - // numbers sort before strings - return true - case jIntErr == nil: - return false - default: - return iParts[idx] < jParts[idx] - } - } - - return r[i] < r[j] -} - -// moduleStateSort implements sort.Interface to sort module states -type moduleStateSort []*ModuleState - -func (s moduleStateSort) Len() int { - return len(s) -} - -func (s moduleStateSort) Less(i, j int) bool { - a := s[i] - b := s[j] - - // If either is nil, then the nil one is "less" than - if a == nil || b == nil { - return a == nil - } - - // If the lengths are different, then the shorter one always wins - if len(a.Path) != len(b.Path) { - return len(a.Path) < len(b.Path) - } - - // Otherwise, compare lexically - return strings.Join(a.Path, ".") < strings.Join(b.Path, ".") -} - -func (s moduleStateSort) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -const stateValidateErrMultiModule = ` -Multiple modules with the same path: %s - -This means that there are multiple entries in the "modules" field -in your state file that point to the same module. This will cause Terraform -to behave in unexpected and error prone ways and is invalid. Please back up -and modify your state file manually to resolve this. -` diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_upgrade_v1_to_v2.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_upgrade_v1_to_v2.go deleted file mode 100644 index aa13cce8030..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_upgrade_v1_to_v2.go +++ /dev/null @@ -1,189 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/mitchellh/copystructure" -) - -// upgradeStateV1ToV2 is used to upgrade a V1 state representation -// into a V2 state representation -func upgradeStateV1ToV2(old *stateV1) (*State, error) { - if old == nil { - return nil, nil - } - - remote, err := old.Remote.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading State V1: %v", err) - } - - modules := make([]*ModuleState, len(old.Modules)) - for i, module := range old.Modules { - upgraded, err := module.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading State V1: %v", err) - } - modules[i] = upgraded - } - if len(modules) == 0 { - modules = nil - } - - newState := &State{ - Version: 2, - Serial: old.Serial, - Remote: remote, - Modules: modules, - } - - newState.sort() - newState.init() - - return newState, nil -} - -func (old *remoteStateV1) upgradeToV2() (*RemoteState, error) { - if old == nil { - return nil, nil - } - - config, err := copystructure.Copy(old.Config) - if err != nil { - return nil, fmt.Errorf("Error upgrading RemoteState V1: %v", err) - } - - return &RemoteState{ - Type: old.Type, - Config: config.(map[string]string), - }, nil -} - -func (old *moduleStateV1) upgradeToV2() (*ModuleState, error) { - if old == nil { - return nil, nil - } - - pathRaw, err := copystructure.Copy(old.Path) - if err != nil { - return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err) - } - path, ok := pathRaw.([]string) - if !ok { - return nil, fmt.Errorf("Error upgrading ModuleState V1: path is not a list of strings") - } - if len(path) == 0 { - // We found some V1 states with a nil path. Assume root and catch - // duplicate path errors later (as part of Validate). - path = rootModulePath - } - - // Outputs needs upgrading to use the new structure - outputs := make(map[string]*OutputState) - for key, output := range old.Outputs { - outputs[key] = &OutputState{ - Type: "string", - Value: output, - Sensitive: false, - } - } - - resources := make(map[string]*ResourceState) - for key, oldResource := range old.Resources { - upgraded, err := oldResource.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err) - } - resources[key] = upgraded - } - - dependencies, err := copystructure.Copy(old.Dependencies) - if err != nil { - return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err) - } - - return &ModuleState{ - Path: path, - Outputs: outputs, - Resources: resources, - Dependencies: dependencies.([]string), - }, nil -} - -func (old *resourceStateV1) upgradeToV2() (*ResourceState, error) { - if old == nil { - return nil, nil - } - - dependencies, err := copystructure.Copy(old.Dependencies) - if err != nil { - return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err) - } - - primary, err := old.Primary.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err) - } - - deposed := make([]*InstanceState, len(old.Deposed)) - for i, v := range old.Deposed { - upgraded, err := v.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading ResourceState V1: %v", err) - } - deposed[i] = upgraded - } - if len(deposed) == 0 { - deposed = nil - } - - return &ResourceState{ - Type: old.Type, - Dependencies: dependencies.([]string), - Primary: primary, - Deposed: deposed, - Provider: old.Provider, - }, nil -} - -func (old *instanceStateV1) upgradeToV2() (*InstanceState, error) { - if old == nil { - return nil, nil - } - - attributes, err := copystructure.Copy(old.Attributes) - if err != nil { - return nil, fmt.Errorf("Error upgrading InstanceState V1: %v", err) - } - ephemeral, err := old.Ephemeral.upgradeToV2() - if err != nil { - return nil, fmt.Errorf("Error upgrading InstanceState V1: %v", err) - } - - meta, err := copystructure.Copy(old.Meta) - if err != nil { - return nil, fmt.Errorf("Error upgrading InstanceState V1: %v", err) - } - - newMeta := make(map[string]interface{}) - for k, v := range meta.(map[string]string) { - newMeta[k] = v - } - - return &InstanceState{ - ID: old.ID, - Attributes: attributes.(map[string]string), - Ephemeral: *ephemeral, - Meta: newMeta, - }, nil -} - -func (old *ephemeralStateV1) upgradeToV2() (*EphemeralState, error) { - connInfo, err := copystructure.Copy(old.ConnInfo) - if err != nil { - return nil, fmt.Errorf("Error upgrading EphemeralState V1: %v", err) - } - return &EphemeralState{ - ConnInfo: connInfo.(map[string]string), - }, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_upgrade_v2_to_v3.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_upgrade_v2_to_v3.go deleted file mode 100644 index e52d35fcd14..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_upgrade_v2_to_v3.go +++ /dev/null @@ -1,142 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - "regexp" - "sort" - "strconv" - "strings" -) - -// The upgrade process from V2 to V3 state does not affect the structure, -// so we do not need to redeclare all of the structs involved - we just -// take a deep copy of the old structure and assert the version number is -// as we expect. -func upgradeStateV2ToV3(old *State) (*State, error) { - new := old.DeepCopy() - - // Ensure the copied version is v2 before attempting to upgrade - if new.Version != 2 { - return nil, fmt.Errorf("Cannot apply v2->v3 state upgrade to " + - "a state which is not version 2.") - } - - // Set the new version number - new.Version = 3 - - // Change the counts for things which look like maps to use the % - // syntax. Remove counts for empty collections - they will be added - // back in later. - for _, module := range new.Modules { - for _, resource := range module.Resources { - // Upgrade Primary - if resource.Primary != nil { - upgradeAttributesV2ToV3(resource.Primary) - } - - // Upgrade Deposed - if resource.Deposed != nil { - for _, deposed := range resource.Deposed { - upgradeAttributesV2ToV3(deposed) - } - } - } - } - - return new, nil -} - -func upgradeAttributesV2ToV3(instanceState *InstanceState) error { - collectionKeyRegexp := regexp.MustCompile(`^(.*\.)#$`) - collectionSubkeyRegexp := regexp.MustCompile(`^([^\.]+)\..*`) - - // Identify the key prefix of anything which is a collection - var collectionKeyPrefixes []string - for key := range instanceState.Attributes { - if submatches := collectionKeyRegexp.FindAllStringSubmatch(key, -1); len(submatches) > 0 { - collectionKeyPrefixes = append(collectionKeyPrefixes, submatches[0][1]) - } - } - sort.Strings(collectionKeyPrefixes) - - log.Printf("[STATE UPGRADE] Detected the following collections in state: %v", collectionKeyPrefixes) - - // This could be rolled into fewer loops, but it is somewhat clearer this way, and will not - // run very often. - for _, prefix := range collectionKeyPrefixes { - // First get the actual keys that belong to this prefix - var potentialKeysMatching []string - for key := range instanceState.Attributes { - if strings.HasPrefix(key, prefix) { - potentialKeysMatching = append(potentialKeysMatching, strings.TrimPrefix(key, prefix)) - } - } - sort.Strings(potentialKeysMatching) - - var actualKeysMatching []string - for _, key := range potentialKeysMatching { - if submatches := collectionSubkeyRegexp.FindAllStringSubmatch(key, -1); len(submatches) > 0 { - actualKeysMatching = append(actualKeysMatching, submatches[0][1]) - } else { - if key != "#" { - actualKeysMatching = append(actualKeysMatching, key) - } - } - } - actualKeysMatching = uniqueSortedStrings(actualKeysMatching) - - // Now inspect the keys in order to determine whether this is most likely to be - // a map, list or set. There is room for error here, so we log in each case. If - // there is no method of telling, we remove the key from the InstanceState in - // order that it will be recreated. Again, this could be rolled into fewer loops - // but we prefer clarity. - - oldCountKey := fmt.Sprintf("%s#", prefix) - - // First, detect "obvious" maps - which have non-numeric keys (mostly). - hasNonNumericKeys := false - for _, key := range actualKeysMatching { - if _, err := strconv.Atoi(key); err != nil { - hasNonNumericKeys = true - } - } - if hasNonNumericKeys { - newCountKey := fmt.Sprintf("%s%%", prefix) - - instanceState.Attributes[newCountKey] = instanceState.Attributes[oldCountKey] - delete(instanceState.Attributes, oldCountKey) - log.Printf("[STATE UPGRADE] Detected %s as a map. Replaced count = %s", - strings.TrimSuffix(prefix, "."), instanceState.Attributes[newCountKey]) - } - - // Now detect empty collections and remove them from state. - if len(actualKeysMatching) == 0 { - delete(instanceState.Attributes, oldCountKey) - log.Printf("[STATE UPGRADE] Detected %s as an empty collection. Removed from state.", - strings.TrimSuffix(prefix, ".")) - } - } - - return nil -} - -// uniqueSortedStrings removes duplicates from a slice of strings and returns -// a sorted slice of the unique strings. -func uniqueSortedStrings(input []string) []string { - uniquemap := make(map[string]struct{}) - for _, str := range input { - uniquemap[str] = struct{}{} - } - - output := make([]string, len(uniquemap)) - - i := 0 - for key := range uniquemap { - output[i] = key - i = i + 1 - } - - sort.Strings(output) - return output -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_v1.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_v1.go deleted file mode 100644 index 68cffb41b5c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_v1.go +++ /dev/null @@ -1,145 +0,0 @@ -package terraform - -// stateV1 keeps track of a snapshot state-of-the-world that Terraform -// can use to keep track of what real world resources it is actually -// managing. -// -// stateV1 is _only used for the purposes of backwards compatibility -// and is no longer used in Terraform. -// -// For the upgrade process, see state_upgrade_v1_to_v2.go -type stateV1 struct { - // Version is the protocol version. "1" for a StateV1. - Version int `json:"version"` - - // Serial is incremented on any operation that modifies - // the State file. It is used to detect potentially conflicting - // updates. - Serial int64 `json:"serial"` - - // Remote is used to track the metadata required to - // pull and push state files from a remote storage endpoint. - Remote *remoteStateV1 `json:"remote,omitempty"` - - // Modules contains all the modules in a breadth-first order - Modules []*moduleStateV1 `json:"modules"` -} - -type remoteStateV1 struct { - // Type controls the client we use for the remote state - Type string `json:"type"` - - // Config is used to store arbitrary configuration that - // is type specific - Config map[string]string `json:"config"` -} - -type moduleStateV1 struct { - // Path is the import path from the root module. Modules imports are - // always disjoint, so the path represents amodule tree - Path []string `json:"path"` - - // Outputs declared by the module and maintained for each module - // even though only the root module technically needs to be kept. - // This allows operators to inspect values at the boundaries. - Outputs map[string]string `json:"outputs"` - - // Resources is a mapping of the logically named resource to - // the state of the resource. Each resource may actually have - // N instances underneath, although a user only needs to think - // about the 1:1 case. - Resources map[string]*resourceStateV1 `json:"resources"` - - // Dependencies are a list of things that this module relies on - // existing to remain intact. For example: an module may depend - // on a VPC ID given by an aws_vpc resource. - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a module that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on,omitempty"` -} - -type resourceStateV1 struct { - // This is filled in and managed by Terraform, and is the resource - // type itself such as "mycloud_instance". If a resource provider sets - // this value, it won't be persisted. - Type string `json:"type"` - - // Dependencies are a list of things that this resource relies on - // existing to remain intact. For example: an AWS instance might - // depend on a subnet (which itself might depend on a VPC, and so - // on). - // - // Terraform uses this information to build valid destruction - // orders and to warn the user if they're destroying a resource that - // another resource depends on. - // - // Things can be put into this list that may not be managed by - // Terraform. If Terraform doesn't find a matching ID in the - // overall state, then it assumes it isn't managed and doesn't - // worry about it. - Dependencies []string `json:"depends_on,omitempty"` - - // Primary is the current active instance for this resource. - // It can be replaced but only after a successful creation. - // This is the instances on which providers will act. - Primary *instanceStateV1 `json:"primary"` - - // Tainted is used to track any underlying instances that - // have been created but are in a bad or unknown state and - // need to be cleaned up subsequently. In the - // standard case, there is only at most a single instance. - // However, in pathological cases, it is possible for the number - // of instances to accumulate. - Tainted []*instanceStateV1 `json:"tainted,omitempty"` - - // Deposed is used in the mechanics of CreateBeforeDestroy: the existing - // Primary is Deposed to get it out of the way for the replacement Primary to - // be created by Apply. If the replacement Primary creates successfully, the - // Deposed instance is cleaned up. If there were problems creating the - // replacement, the instance remains in the Deposed list so it can be - // destroyed in a future run. Functionally, Deposed instances are very - // similar to Tainted instances in that Terraform is only tracking them in - // order to remember to destroy them. - Deposed []*instanceStateV1 `json:"deposed,omitempty"` - - // Provider is used when a resource is connected to a provider with an alias. - // If this string is empty, the resource is connected to the default provider, - // e.g. "aws_instance" goes with the "aws" provider. - // If the resource block contained a "provider" key, that value will be set here. - Provider string `json:"provider,omitempty"` -} - -type instanceStateV1 struct { - // A unique ID for this resource. This is opaque to Terraform - // and is only meant as a lookup mechanism for the providers. - ID string `json:"id"` - - // Attributes are basic information about the resource. Any keys here - // are accessible in variable format within Terraform configurations: - // ${resourcetype.name.attribute}. - Attributes map[string]string `json:"attributes,omitempty"` - - // Ephemeral is used to store any state associated with this instance - // that is necessary for the Terraform run to complete, but is not - // persisted to a state file. - Ephemeral ephemeralStateV1 `json:"-"` - - // Meta is a simple K/V map that is persisted to the State but otherwise - // ignored by Terraform core. It's meant to be used for accounting by - // external client code. - Meta map[string]string `json:"meta,omitempty"` -} - -type ephemeralStateV1 struct { - // ConnInfo is used for the providers to export information which is - // used to connect to the resource for provisioning. For example, - // this could contain SSH or WinRM credentials. - ConnInfo map[string]string `json:"-"` -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/testing.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/testing.go deleted file mode 100644 index 3f0418d9273..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/testing.go +++ /dev/null @@ -1,19 +0,0 @@ -package terraform - -import ( - "os" - "testing" -) - -// TestStateFile writes the given state to the path. -func TestStateFile(t *testing.T, path string, state *State) { - f, err := os.Create(path) - if err != nil { - t.Fatalf("err: %s", err) - } - defer f.Close() - - if err := WriteState(state, f); err != nil { - t.Fatalf("err: %s", err) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform.go deleted file mode 100644 index f9559f41b6c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform.go +++ /dev/null @@ -1,62 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// GraphTransformer is the interface that transformers implement. This -// interface is only for transforms that need entire graph visibility. -type GraphTransformer interface { - Transform(*Graph) error -} - -// GraphVertexTransformer is an interface that transforms a single -// Vertex within with graph. This is a specialization of GraphTransformer -// that makes it easy to do vertex replacement. -// -// The GraphTransformer that runs through the GraphVertexTransformers is -// VertexTransformer. -type GraphVertexTransformer interface { - Transform(dag.Vertex) (dag.Vertex, error) -} - -// GraphTransformIf is a helper function that conditionally returns a -// GraphTransformer given. This is useful for calling inline a sequence -// of transforms without having to split it up into multiple append() calls. -func GraphTransformIf(f func() bool, then GraphTransformer) GraphTransformer { - if f() { - return then - } - - return nil -} - -type graphTransformerMulti struct { - Transforms []GraphTransformer -} - -func (t *graphTransformerMulti) Transform(g *Graph) error { - var lastStepStr string - for _, t := range t.Transforms { - log.Printf("[TRACE] (graphTransformerMulti) Executing graph transform %T", t) - if err := t.Transform(g); err != nil { - return err - } - if thisStepStr := g.StringWithNodeTypes(); thisStepStr != lastStepStr { - log.Printf("[TRACE] (graphTransformerMulti) Completed graph transform %T with new graph:\n%s------", t, thisStepStr) - lastStepStr = thisStepStr - } else { - log.Printf("[TRACE] (graphTransformerMulti) Completed graph transform %T (no changes)", t) - } - } - - return nil -} - -// GraphTransformMulti combines multiple graph transformers into a single -// GraphTransformer that runs all the individual graph transformers. -func GraphTransformMulti(ts ...GraphTransformer) GraphTransformer { - return &graphTransformerMulti{Transforms: ts} -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_config_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_config_provider.go deleted file mode 100644 index cbac13387b3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_config_provider.go +++ /dev/null @@ -1,19 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" -) - -// GraphNodeAttachProvider is an interface that must be implemented by nodes -// that want provider configurations attached. -type GraphNodeAttachProvider interface { - // Must be implemented to determine the path for the configuration - GraphNodeSubPath - - // ProviderName with no module prefix. Example: "aws". - ProviderAddr() addrs.AbsProviderConfig - - // Sets the configuration - AttachProvider(*configs.Provider) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_config_resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_config_resource.go deleted file mode 100644 index 23578c78467..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_config_resource.go +++ /dev/null @@ -1,74 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// GraphNodeAttachResourceConfig is an interface that must be implemented by nodes -// that want resource configurations attached. -type GraphNodeAttachResourceConfig interface { - GraphNodeResource - - // Sets the configuration - AttachResourceConfig(*configs.Resource) -} - -// AttachResourceConfigTransformer goes through the graph and attaches -// resource configuration structures to nodes that implement -// GraphNodeAttachManagedResourceConfig or GraphNodeAttachDataResourceConfig. -// -// The attached configuration structures are directly from the configuration. -// If they're going to be modified, a copy should be made. -type AttachResourceConfigTransformer struct { - Config *configs.Config // Config is the root node in the config tree -} - -func (t *AttachResourceConfigTransformer) Transform(g *Graph) error { - - // Go through and find GraphNodeAttachResource - for _, v := range g.Vertices() { - // Only care about GraphNodeAttachResource implementations - arn, ok := v.(GraphNodeAttachResourceConfig) - if !ok { - continue - } - - // Determine what we're looking for - addr := arn.ResourceAddr() - - // Get the configuration. - config := t.Config.DescendentForInstance(addr.Module) - if config == nil { - log.Printf("[TRACE] AttachResourceConfigTransformer: %q (%T) has no configuration available", dag.VertexName(v), v) - continue - } - - for _, r := range config.Module.ManagedResources { - rAddr := r.Addr() - - if rAddr != addr.Resource { - // Not the same resource - continue - } - - log.Printf("[TRACE] AttachResourceConfigTransformer: attaching to %q (%T) config from %s", dag.VertexName(v), v, r.DeclRange) - arn.AttachResourceConfig(r) - } - for _, r := range config.Module.DataResources { - rAddr := r.Addr() - - if rAddr != addr.Resource { - // Not the same resource - continue - } - - log.Printf("[TRACE] AttachResourceConfigTransformer: attaching to %q (%T) config from %#v", dag.VertexName(v), v, r.DeclRange) - arn.AttachResourceConfig(r) - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_schema.go deleted file mode 100644 index fee220b52bb..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_schema.go +++ /dev/null @@ -1,99 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// GraphNodeAttachResourceSchema is an interface implemented by node types -// that need a resource schema attached. -type GraphNodeAttachResourceSchema interface { - GraphNodeResource - GraphNodeProviderConsumer - - AttachResourceSchema(schema *configschema.Block, version uint64) -} - -// GraphNodeAttachProviderConfigSchema is an interface implemented by node types -// that need a provider configuration schema attached. -type GraphNodeAttachProviderConfigSchema interface { - GraphNodeProvider - - AttachProviderConfigSchema(*configschema.Block) -} - -// GraphNodeAttachProvisionerSchema is an interface implemented by node types -// that need one or more provisioner schemas attached. -type GraphNodeAttachProvisionerSchema interface { - ProvisionedBy() []string - - // SetProvisionerSchema is called during transform for each provisioner - // type returned from ProvisionedBy, providing the configuration schema - // for each provisioner in turn. The implementer should save these for - // later use in evaluating provisioner configuration blocks. - AttachProvisionerSchema(name string, schema *configschema.Block) -} - -// AttachSchemaTransformer finds nodes that implement -// GraphNodeAttachResourceSchema, GraphNodeAttachProviderConfigSchema, or -// GraphNodeAttachProvisionerSchema, looks up the needed schemas for each -// and then passes them to a method implemented by the node. -type AttachSchemaTransformer struct { - Schemas *Schemas -} - -func (t *AttachSchemaTransformer) Transform(g *Graph) error { - if t.Schemas == nil { - // Should never happen with a reasonable caller, but we'll return a - // proper error here anyway so that we'll fail gracefully. - return fmt.Errorf("AttachSchemaTransformer used with nil Schemas") - } - - for _, v := range g.Vertices() { - - if tv, ok := v.(GraphNodeAttachResourceSchema); ok { - addr := tv.ResourceAddr() - mode := addr.Resource.Mode - typeName := addr.Resource.Type - providerAddr, _ := tv.ProvidedBy() - providerType := providerAddr.ProviderConfig.Type - - schema, version := t.Schemas.ResourceTypeConfig(providerType, mode, typeName) - if schema == nil { - log.Printf("[ERROR] AttachSchemaTransformer: No resource schema available for %s", addr) - continue - } - log.Printf("[TRACE] AttachSchemaTransformer: attaching resource schema to %s", dag.VertexName(v)) - tv.AttachResourceSchema(schema, version) - } - - if tv, ok := v.(GraphNodeAttachProviderConfigSchema); ok { - providerAddr := tv.ProviderAddr() - schema := t.Schemas.ProviderConfig(providerAddr.ProviderConfig.Type) - if schema == nil { - log.Printf("[ERROR] AttachSchemaTransformer: No provider config schema available for %s", providerAddr) - continue - } - log.Printf("[TRACE] AttachSchemaTransformer: attaching provider config schema to %s", dag.VertexName(v)) - tv.AttachProviderConfigSchema(schema) - } - - if tv, ok := v.(GraphNodeAttachProvisionerSchema); ok { - names := tv.ProvisionedBy() - for _, name := range names { - schema := t.Schemas.ProvisionerConfig(name) - if schema == nil { - log.Printf("[ERROR] AttachSchemaTransformer: No schema available for provisioner %q on %q", name, dag.VertexName(v)) - continue - } - log.Printf("[TRACE] AttachSchemaTransformer: attaching provisioner %q config schema to %s", name, dag.VertexName(v)) - tv.AttachProvisionerSchema(name, schema) - } - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_state.go deleted file mode 100644 index f8749487985..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_state.go +++ /dev/null @@ -1,68 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// GraphNodeAttachResourceState is an interface that can be implemented -// to request that a ResourceState is attached to the node. -// -// Due to a historical naming inconsistency, the type ResourceState actually -// represents the state for a particular _instance_, while InstanceState -// represents the values for that instance during a particular phase -// (e.g. primary vs. deposed). Consequently, GraphNodeAttachResourceState -// is supported only for nodes that represent resource instances, even though -// the name might suggest it is for containing resources. -type GraphNodeAttachResourceState interface { - GraphNodeResourceInstance - - // Sets the state - AttachResourceState(*states.Resource) -} - -// AttachStateTransformer goes through the graph and attaches -// state to nodes that implement the interfaces above. -type AttachStateTransformer struct { - State *states.State // State is the root state -} - -func (t *AttachStateTransformer) Transform(g *Graph) error { - // If no state, then nothing to do - if t.State == nil { - log.Printf("[DEBUG] Not attaching any node states: overall state is nil") - return nil - } - - for _, v := range g.Vertices() { - // Nodes implement this interface to request state attachment. - an, ok := v.(GraphNodeAttachResourceState) - if !ok { - continue - } - addr := an.ResourceInstanceAddr() - - rs := t.State.Resource(addr.ContainingResource()) - if rs == nil { - log.Printf("[DEBUG] Resource state not found for node %q, instance %s", dag.VertexName(v), addr) - continue - } - - is := rs.Instance(addr.Resource.Key) - if is == nil { - // We don't actually need this here, since we'll attach the whole - // resource state, but we still check because it'd be weird - // for the specific instance we're attaching to not to exist. - log.Printf("[DEBUG] Resource instance state not found for node %q, instance %s", dag.VertexName(v), addr) - continue - } - - // make sure to attach a copy of the state, so instances can modify the - // same ResourceState. - an.AttachResourceState(rs.DeepCopy()) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_config.go deleted file mode 100644 index 8920761ea2d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_config.go +++ /dev/null @@ -1,133 +0,0 @@ -package terraform - -import ( - "log" - "sync" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// ConfigTransformer is a GraphTransformer that adds all the resources -// from the configuration to the graph. -// -// The module used to configure this transformer must be the root module. -// -// Only resources are added to the graph. Variables, outputs, and -// providers must be added via other transforms. -// -// Unlike ConfigTransformerOld, this transformer creates a graph with -// all resources including module resources, rather than creating module -// nodes that are then "flattened". -type ConfigTransformer struct { - Concrete ConcreteResourceNodeFunc - - // Module is the module to add resources from. - Config *configs.Config - - // Unique will only add resources that aren't already present in the graph. - Unique bool - - // Mode will only add resources that match the given mode - ModeFilter bool - Mode addrs.ResourceMode - - l sync.Mutex - uniqueMap map[string]struct{} -} - -func (t *ConfigTransformer) Transform(g *Graph) error { - // Lock since we use some internal state - t.l.Lock() - defer t.l.Unlock() - - // If no configuration is available, we don't do anything - if t.Config == nil { - return nil - } - - // Reset the uniqueness map. If we're tracking uniques, then populate - // it with addresses. - t.uniqueMap = make(map[string]struct{}) - defer func() { t.uniqueMap = nil }() - if t.Unique { - for _, v := range g.Vertices() { - if rn, ok := v.(GraphNodeResource); ok { - t.uniqueMap[rn.ResourceAddr().String()] = struct{}{} - } - } - } - - // Start the transformation process - return t.transform(g, t.Config) -} - -func (t *ConfigTransformer) transform(g *Graph, config *configs.Config) error { - // If no config, do nothing - if config == nil { - return nil - } - - // Add our resources - if err := t.transformSingle(g, config); err != nil { - return err - } - - // Transform all the children. - for _, c := range config.Children { - if err := t.transform(g, c); err != nil { - return err - } - } - - return nil -} - -func (t *ConfigTransformer) transformSingle(g *Graph, config *configs.Config) error { - path := config.Path - module := config.Module - log.Printf("[TRACE] ConfigTransformer: Starting for path: %v", path) - - // For now we assume that each module call produces only one module - // instance with no key, since we don't yet support "count" and "for_each" - // on modules. - // FIXME: As part of supporting "count" and "for_each" on modules, rework - // this so that we'll "expand" the module call first and then create graph - // nodes for each module instance separately. - instPath := path.UnkeyedInstanceShim() - - allResources := make([]*configs.Resource, 0, len(module.ManagedResources)+len(module.DataResources)) - for _, r := range module.ManagedResources { - allResources = append(allResources, r) - } - for _, r := range module.DataResources { - allResources = append(allResources, r) - } - - for _, r := range allResources { - relAddr := r.Addr() - - if t.ModeFilter && relAddr.Mode != t.Mode { - // Skip non-matching modes - continue - } - - addr := relAddr.Absolute(instPath) - if _, ok := t.uniqueMap[addr.String()]; ok { - // We've already seen a resource with this address. This should - // never happen, because we enforce uniqueness in the config loader. - continue - } - - abstract := &NodeAbstractResource{Addr: addr} - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - - g.Add(node) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_count_boundary.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_count_boundary.go deleted file mode 100644 index 892f75ec17b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_count_boundary.go +++ /dev/null @@ -1,33 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// CountBoundaryTransformer adds a node that depends on everything else -// so that it runs last in order to clean up the state for nodes that -// are on the "count boundary": "foo.0" when only one exists becomes "foo" -type CountBoundaryTransformer struct { - Config *configs.Config -} - -func (t *CountBoundaryTransformer) Transform(g *Graph) error { - node := &NodeCountBoundary{ - Config: t.Config, - } - g.Add(node) - - // Depends on everything - for _, v := range g.Vertices() { - // Don't connect to ourselves - if v == node { - continue - } - - // Connect! - g.Connect(dag.BasicEdge(node, v)) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_cbd.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_cbd.go deleted file mode 100644 index 98e088eee7e..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_cbd.go +++ /dev/null @@ -1,297 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// GraphNodeDestroyerCBD must be implemented by nodes that might be -// create-before-destroy destroyers, or might plan a create-before-destroy -// action. -type GraphNodeDestroyerCBD interface { - // CreateBeforeDestroy returns true if this node represents a node - // that is doing a CBD. - CreateBeforeDestroy() bool - - // ModifyCreateBeforeDestroy is called when the CBD state of a node - // is changed dynamically. This can return an error if this isn't - // allowed. - ModifyCreateBeforeDestroy(bool) error -} - -// GraphNodeAttachDestroyer is implemented by applyable nodes that have a -// companion destroy node. This allows the creation node to look up the status -// of the destroy node and determine if it needs to depose the existing state, -// or replace it. -// If a node is not marked as create-before-destroy in the configuration, but a -// dependency forces that status, only the destroy node will be aware of that -// status. -type GraphNodeAttachDestroyer interface { - // AttachDestroyNode takes a destroy node and saves a reference to that - // node in the receiver, so it can later check the status of - // CreateBeforeDestroy(). - AttachDestroyNode(n GraphNodeDestroyerCBD) -} - -// ForcedCBDTransformer detects when a particular CBD-able graph node has -// dependencies with another that has create_before_destroy set that require -// it to be forced on, and forces it on. -// -// This must be used in the plan graph builder to ensure that -// create_before_destroy settings are properly propagated before constructing -// the planned changes. This requires that the plannable resource nodes -// implement GraphNodeDestroyerCBD. -type ForcedCBDTransformer struct { -} - -func (t *ForcedCBDTransformer) Transform(g *Graph) error { - for _, v := range g.Vertices() { - dn, ok := v.(GraphNodeDestroyerCBD) - if !ok { - continue - } - - if !dn.CreateBeforeDestroy() { - // If there are no CBD decendent (dependent nodes), then we - // do nothing here. - if !t.hasCBDDescendent(g, v) { - log.Printf("[TRACE] ForcedCBDTransformer: %q (%T) has no CBD descendent, so skipping", dag.VertexName(v), v) - continue - } - - // If this isn't naturally a CBD node, this means that an descendent is - // and we need to auto-upgrade this node to CBD. We do this because - // a CBD node depending on non-CBD will result in cycles. To avoid this, - // we always attempt to upgrade it. - log.Printf("[TRACE] ForcedCBDTransformer: forcing create_before_destroy on for %q (%T)", dag.VertexName(v), v) - if err := dn.ModifyCreateBeforeDestroy(true); err != nil { - return fmt.Errorf( - "%s: must have create before destroy enabled because "+ - "a dependent resource has CBD enabled. However, when "+ - "attempting to automatically do this, an error occurred: %s", - dag.VertexName(v), err) - } - } else { - log.Printf("[TRACE] ForcedCBDTransformer: %q (%T) already has create_before_destroy set", dag.VertexName(v), v) - } - } - return nil -} - -// hasCBDDescendent returns true if any descendent (node that depends on this) -// has CBD set. -func (t *ForcedCBDTransformer) hasCBDDescendent(g *Graph, v dag.Vertex) bool { - s, _ := g.Descendents(v) - if s == nil { - return true - } - - for _, ov := range s.List() { - dn, ok := ov.(GraphNodeDestroyerCBD) - if !ok { - continue - } - - if dn.CreateBeforeDestroy() { - // some descendent is CreateBeforeDestroy, so we need to follow suit - log.Printf("[TRACE] ForcedCBDTransformer: %q has CBD descendent %q", dag.VertexName(v), dag.VertexName(ov)) - return true - } - } - - return false -} - -// CBDEdgeTransformer modifies the edges of CBD nodes that went through -// the DestroyEdgeTransformer to have the right dependencies. There are -// two real tasks here: -// -// 1. With CBD, the destroy edge is inverted: the destroy depends on -// the creation. -// -// 2. A_d must depend on resources that depend on A. This is to enable -// the destroy to only happen once nodes that depend on A successfully -// update to A. Example: adding a web server updates the load balancer -// before deleting the old web server. -// -// This transformer requires that a previous transformer has already forced -// create_before_destroy on for nodes that are depended on by explicit CBD -// nodes. This is the logic in ForcedCBDTransformer, though in practice we -// will get here by recording the CBD-ness of each change in the plan during -// the plan walk and then forcing the nodes into the appropriate setting during -// DiffTransformer when building the apply graph. -type CBDEdgeTransformer struct { - // Module and State are only needed to look up dependencies in - // any way possible. Either can be nil if not availabile. - Config *configs.Config - State *states.State - - // If configuration is present then Schemas is required in order to - // obtain schema information from providers and provisioners so we can - // properly resolve implicit dependencies. - Schemas *Schemas - - // If the operation is a simple destroy, no transformation is done. - Destroy bool -} - -func (t *CBDEdgeTransformer) Transform(g *Graph) error { - if t.Destroy { - return nil - } - - // Go through and reverse any destroy edges - destroyMap := make(map[string][]dag.Vertex) - for _, v := range g.Vertices() { - dn, ok := v.(GraphNodeDestroyerCBD) - if !ok { - continue - } - dern, ok := v.(GraphNodeDestroyer) - if !ok { - continue - } - - if !dn.CreateBeforeDestroy() { - continue - } - - // Find the destroy edge. There should only be one. - for _, e := range g.EdgesTo(v) { - // Not a destroy edge, ignore it - de, ok := e.(*DestroyEdge) - if !ok { - continue - } - - log.Printf("[TRACE] CBDEdgeTransformer: inverting edge: %s => %s", - dag.VertexName(de.Source()), dag.VertexName(de.Target())) - - // Found it! Invert. - g.RemoveEdge(de) - applyNode := de.Source() - destroyNode := de.Target() - g.Connect(&DestroyEdge{S: destroyNode, T: applyNode}) - break - } - - // If the address has an index, we strip that. Our depMap creation - // graph doesn't expand counts so we don't currently get _exact_ - // dependencies. One day when we limit dependencies more exactly - // this will have to change. We have a test case covering this - // (depNonCBDCountBoth) so it'll be caught. - addr := dern.DestroyAddr() - key := addr.ContainingResource().String() - - // Add this to the list of nodes that we need to fix up - // the edges for (step 2 above in the docs). - destroyMap[key] = append(destroyMap[key], v) - } - - // If we have no CBD nodes, then our work here is done - if len(destroyMap) == 0 { - return nil - } - - // We have CBD nodes. We now have to move on to the much more difficult - // task of connecting dependencies of the creation side of the destroy - // to the destruction node. The easiest way to explain this is an example: - // - // Given a pre-destroy dependence of: A => B - // And A has CBD set. - // - // The resulting graph should be: A => B => A_d - // - // They key here is that B happens before A is destroyed. This is to - // facilitate the primary purpose for CBD: making sure that downstreams - // are properly updated to avoid downtime before the resource is destroyed. - depMap, err := t.depMap(g, destroyMap) - if err != nil { - return err - } - - // We now have the mapping of resource addresses to the destroy - // nodes they need to depend on. We now go through our own vertices to - // find any matching these addresses and make the connection. - for _, v := range g.Vertices() { - // We're looking for creators - rn, ok := v.(GraphNodeCreator) - if !ok { - continue - } - - // Get the address - addr := rn.CreateAddr() - - // If the address has an index, we strip that. Our depMap creation - // graph doesn't expand counts so we don't currently get _exact_ - // dependencies. One day when we limit dependencies more exactly - // this will have to change. We have a test case covering this - // (depNonCBDCount) so it'll be caught. - key := addr.ContainingResource().String() - - // If there is nothing this resource should depend on, ignore it - dns, ok := depMap[key] - if !ok { - continue - } - - // We have nodes! Make the connection - for _, dn := range dns { - log.Printf("[TRACE] CBDEdgeTransformer: destroy depends on dependence: %s => %s", - dag.VertexName(dn), dag.VertexName(v)) - g.Connect(dag.BasicEdge(dn, v)) - } - } - - return nil -} - -func (t *CBDEdgeTransformer) depMap(g *Graph, destroyMap map[string][]dag.Vertex) (map[string][]dag.Vertex, error) { - // Build the list of destroy nodes that each resource address should depend - // on. For example, when we find B, we map the address of B to A_d in the - // "depMap" variable below. - depMap := make(map[string][]dag.Vertex) - for _, v := range g.Vertices() { - // We're looking for resources. - rn, ok := v.(GraphNodeResource) - if !ok { - continue - } - - // Get the address - addr := rn.ResourceAddr() - key := addr.String() - - // Get the destroy nodes that are destroying this resource. - // If there aren't any, then we don't need to worry about - // any connections. - dns, ok := destroyMap[key] - if !ok { - continue - } - - // Get the nodes that depend on this on. In the example above: - // finding B in A => B. Since dependencies can span modules, walk all - // descendents of the resource. - des, _ := g.Descendents(v) - for _, v := range des.List() { - // We're looking for resources. - rn, ok := v.(GraphNodeResource) - if !ok { - continue - } - - // Keep track of the destroy nodes that this address - // needs to depend on. - key := rn.ResourceAddr().String() - depMap[key] = append(depMap[key], dns...) - } - } - - return depMap, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_edge.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_edge.go deleted file mode 100644 index 1d211570fc1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_edge.go +++ /dev/null @@ -1,323 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// GraphNodeDestroyer must be implemented by nodes that destroy resources. -type GraphNodeDestroyer interface { - dag.Vertex - - // DestroyAddr is the address of the resource that is being - // destroyed by this node. If this returns nil, then this node - // is not destroying anything. - DestroyAddr() *addrs.AbsResourceInstance -} - -// GraphNodeCreator must be implemented by nodes that create OR update resources. -type GraphNodeCreator interface { - // CreateAddr is the address of the resource being created or updated - CreateAddr() *addrs.AbsResourceInstance -} - -// DestroyEdgeTransformer is a GraphTransformer that creates the proper -// references for destroy resources. Destroy resources are more complex -// in that they must be depend on the destruction of resources that -// in turn depend on the CREATION of the node being destroy. -// -// That is complicated. Visually: -// -// B_d -> A_d -> A -> B -// -// Notice that A destroy depends on B destroy, while B create depends on -// A create. They're inverted. This must be done for example because often -// dependent resources will block parent resources from deleting. Concrete -// example: VPC with subnets, the VPC can't be deleted while there are -// still subnets. -type DestroyEdgeTransformer struct { - // These are needed to properly build the graph of dependencies - // to determine what a destroy node depends on. Any of these can be nil. - Config *configs.Config - State *states.State - - // If configuration is present then Schemas is required in order to - // obtain schema information from providers and provisioners in order - // to properly resolve implicit dependencies. - Schemas *Schemas -} - -func (t *DestroyEdgeTransformer) Transform(g *Graph) error { - // Build a map of what is being destroyed (by address string) to - // the list of destroyers. Usually there will be at most one destroyer - // per node, but we allow multiple if present for completeness. - destroyers := make(map[string][]GraphNodeDestroyer) - destroyerAddrs := make(map[string]addrs.AbsResourceInstance) - for _, v := range g.Vertices() { - dn, ok := v.(GraphNodeDestroyer) - if !ok { - continue - } - - addrP := dn.DestroyAddr() - if addrP == nil { - continue - } - addr := *addrP - - key := addr.String() - log.Printf("[TRACE] DestroyEdgeTransformer: %q (%T) destroys %s", dag.VertexName(dn), v, key) - destroyers[key] = append(destroyers[key], dn) - destroyerAddrs[key] = addr - } - - // If we aren't destroying anything, there will be no edges to make - // so just exit early and avoid future work. - if len(destroyers) == 0 { - return nil - } - - // Go through and connect creators to destroyers. Going along with - // our example, this makes: A_d => A - for _, v := range g.Vertices() { - cn, ok := v.(GraphNodeCreator) - if !ok { - continue - } - - addr := cn.CreateAddr() - if addr == nil { - continue - } - - key := addr.String() - ds := destroyers[key] - if len(ds) == 0 { - continue - } - - for _, d := range ds { - // For illustrating our example - a_d := d.(dag.Vertex) - a := v - - log.Printf( - "[TRACE] DestroyEdgeTransformer: connecting creator %q with destroyer %q", - dag.VertexName(a), dag.VertexName(a_d)) - - g.Connect(&DestroyEdge{S: a, T: a_d}) - - // Attach the destroy node to the creator - // There really shouldn't be more than one destroyer, but even if - // there are, any of them will represent the correct - // CreateBeforeDestroy status. - if n, ok := cn.(GraphNodeAttachDestroyer); ok { - if d, ok := d.(GraphNodeDestroyerCBD); ok { - n.AttachDestroyNode(d) - } - } - } - } - - // This is strange but is the easiest way to get the dependencies - // of a node that is being destroyed. We use another graph to make sure - // the resource is in the graph and ask for references. We have to do this - // because the node that is being destroyed may NOT be in the graph. - // - // Example: resource A is force new, then destroy A AND create A are - // in the graph. BUT if resource A is just pure destroy, then only - // destroy A is in the graph, and create A is not. - providerFn := func(a *NodeAbstractProvider) dag.Vertex { - return &NodeApplyableProvider{NodeAbstractProvider: a} - } - steps := []GraphTransformer{ - // Add the local values - &LocalTransformer{Config: t.Config}, - - // Add outputs and metadata - &OutputTransformer{Config: t.Config}, - &AttachResourceConfigTransformer{Config: t.Config}, - &AttachStateTransformer{State: t.State}, - - // Add all the variables. We can depend on resources through - // variables due to module parameters, and we need to properly - // determine that. - &RootVariableTransformer{Config: t.Config}, - &ModuleVariableTransformer{Config: t.Config}, - - TransformProviders(nil, providerFn, t.Config), - - // Must attach schemas before ReferenceTransformer so that we can - // analyze the configuration to find references. - &AttachSchemaTransformer{Schemas: t.Schemas}, - - &ReferenceTransformer{}, - } - - // Go through all the nodes being destroyed and create a graph. - // The resulting graph is only of things being CREATED. For example, - // following our example, the resulting graph would be: - // - // A, B (with no edges) - // - var tempG Graph - var tempDestroyed []dag.Vertex - for d := range destroyers { - // d is the string key for the resource being destroyed. We actually - // want the address value, which we stashed earlier. - addr := destroyerAddrs[d] - - // This part is a little bit weird but is the best way to - // find the dependencies we need to: build a graph and use the - // attach config and state transformers then ask for references. - abstract := NewNodeAbstractResourceInstance(addr) - tempG.Add(abstract) - tempDestroyed = append(tempDestroyed, abstract) - - // We also add the destroy version here since the destroy can - // depend on things that the creation doesn't (destroy provisioners). - destroy := &NodeDestroyResourceInstance{NodeAbstractResourceInstance: abstract} - tempG.Add(destroy) - tempDestroyed = append(tempDestroyed, destroy) - } - - // Run the graph transforms so we have the information we need to - // build references. - log.Printf("[TRACE] DestroyEdgeTransformer: constructing temporary graph for analysis of references, starting from:\n%s", tempG.StringWithNodeTypes()) - for _, s := range steps { - log.Printf("[TRACE] DestroyEdgeTransformer: running %T on temporary graph", s) - if err := s.Transform(&tempG); err != nil { - log.Printf("[TRACE] DestroyEdgeTransformer: %T failed: %s", s, err) - return err - } - } - log.Printf("[TRACE] DestroyEdgeTransformer: temporary reference graph:\n%s", tempG.String()) - - // Go through all the nodes in the graph and determine what they - // depend on. - for _, v := range tempDestroyed { - // Find all ancestors of this to determine the edges we'll depend on - vs, err := tempG.Ancestors(v) - if err != nil { - return err - } - - refs := make([]dag.Vertex, 0, vs.Len()) - for _, raw := range vs.List() { - refs = append(refs, raw.(dag.Vertex)) - } - - refNames := make([]string, len(refs)) - for i, ref := range refs { - refNames[i] = dag.VertexName(ref) - } - log.Printf( - "[TRACE] DestroyEdgeTransformer: creation node %q references %s", - dag.VertexName(v), refNames) - - // If we have no references, then we won't need to do anything - if len(refs) == 0 { - continue - } - - // Get the destroy node for this. In the example of our struct, - // we are currently at B and we're looking for B_d. - rn, ok := v.(GraphNodeResourceInstance) - if !ok { - log.Printf("[TRACE] DestroyEdgeTransformer: skipping %s, since it's not a resource", dag.VertexName(v)) - continue - } - - addr := rn.ResourceInstanceAddr() - dns := destroyers[addr.String()] - - // We have dependencies, check if any are being destroyed - // to build the list of things that we must depend on! - // - // In the example of the struct, if we have: - // - // B_d => A_d => A => B - // - // Then at this point in the algorithm we started with B_d, - // we built B (to get dependencies), and we found A. We're now looking - // to see if A_d exists. - var depDestroyers []dag.Vertex - for _, v := range refs { - rn, ok := v.(GraphNodeResourceInstance) - if !ok { - continue - } - - addr := rn.ResourceInstanceAddr() - key := addr.String() - if ds, ok := destroyers[key]; ok { - for _, d := range ds { - depDestroyers = append(depDestroyers, d.(dag.Vertex)) - log.Printf( - "[TRACE] DestroyEdgeTransformer: destruction of %q depends on %s", - key, dag.VertexName(d)) - } - } - } - - // Go through and make the connections. Use the variable - // names "a_d" and "b_d" to reference our example. - for _, a_d := range dns { - for _, b_d := range depDestroyers { - if b_d != a_d { - log.Printf("[TRACE] DestroyEdgeTransformer: %q depends on %q", dag.VertexName(b_d), dag.VertexName(a_d)) - g.Connect(dag.BasicEdge(b_d, a_d)) - } - } - } - } - - return t.pruneResources(g) -} - -// If there are only destroy instances for a particular resource, there's no -// reason for the resource node to prepare the state. Remove Resource nodes so -// that they don't fail by trying to evaluate a resource that is only being -// destroyed along with its dependencies. -func (t *DestroyEdgeTransformer) pruneResources(g *Graph) error { - for _, v := range g.Vertices() { - n, ok := v.(*NodeApplyableResource) - if !ok { - continue - } - - // if there are only destroy dependencies, we don't need this node - des, err := g.Descendents(n) - if err != nil { - return err - } - - descendents := des.List() - nonDestroyInstanceFound := false - for _, v := range descendents { - if _, ok := v.(*NodeApplyableResourceInstance); ok { - nonDestroyInstanceFound = true - break - } - } - - if nonDestroyInstanceFound { - continue - } - - // connect all the through-edges, then delete the node - for _, d := range g.DownEdges(n).List() { - for _, u := range g.UpEdges(n).List() { - g.Connect(dag.BasicEdge(u, d)) - } - } - log.Printf("DestroyEdgeTransformer: pruning unused resource node %s", dag.VertexName(n)) - g.Remove(n) - } - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_diff.go deleted file mode 100644 index b7a237fce36..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_diff.go +++ /dev/null @@ -1,184 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/plans" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// DiffTransformer is a GraphTransformer that adds graph nodes representing -// each of the resource changes described in the given Changes object. -type DiffTransformer struct { - Concrete ConcreteResourceInstanceNodeFunc - State *states.State - Changes *plans.Changes -} - -func (t *DiffTransformer) Transform(g *Graph) error { - if t.Changes == nil || len(t.Changes.Resources) == 0 { - // Nothing to do! - return nil - } - - // Go through all the modules in the diff. - log.Printf("[TRACE] DiffTransformer starting") - - var diags tfdiags.Diagnostics - state := t.State - changes := t.Changes - - // DiffTransformer creates resource _instance_ nodes. If there are any - // whole-resource nodes already in the graph, we must ensure that they - // get evaluated before any of the corresponding instances by creating - // dependency edges, so we'll do some prep work here to ensure we'll only - // create connections to nodes that existed before we started here. - resourceNodes := map[string][]GraphNodeResource{} - for _, node := range g.Vertices() { - rn, ok := node.(GraphNodeResource) - if !ok { - continue - } - // We ignore any instances that _also_ implement - // GraphNodeResourceInstance, since in the unlikely event that they - // do exist we'd probably end up creating cycles by connecting them. - if _, ok := node.(GraphNodeResourceInstance); ok { - continue - } - - addr := rn.ResourceAddr().String() - resourceNodes[addr] = append(resourceNodes[addr], rn) - } - - for _, rc := range changes.Resources { - addr := rc.Addr - dk := rc.DeposedKey - - log.Printf("[TRACE] DiffTransformer: found %s change for %s %s", rc.Action, addr, dk) - - // Depending on the action we'll need some different combinations of - // nodes, because destroying uses a special node type separate from - // other actions. - var update, delete, createBeforeDestroy bool - switch rc.Action { - case plans.NoOp: - continue - case plans.Delete: - delete = true - case plans.DeleteThenCreate, plans.CreateThenDelete: - update = true - delete = true - createBeforeDestroy = (rc.Action == plans.CreateThenDelete) - default: - update = true - } - - if dk != states.NotDeposed && update { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid planned change for deposed object", - fmt.Sprintf("The plan contains a non-delete change for %s deposed object %s. The only valid action for a deposed object is to destroy it, so this is a bug in Terraform.", addr, dk), - )) - continue - } - - // If we're going to do a create_before_destroy Replace operation then - // we need to allocate a DeposedKey to use to retain the - // not-yet-destroyed prior object, so that the delete node can destroy - // _that_ rather than the newly-created node, which will be current - // by the time the delete node is visited. - if update && delete && createBeforeDestroy { - // In this case, variable dk will be the _pre-assigned_ DeposedKey - // that must be used if the update graph node deposes the current - // instance, which will then align with the same key we pass - // into the destroy node to ensure we destroy exactly the deposed - // object we expect. - if state != nil { - ris := state.ResourceInstance(addr) - if ris == nil { - // Should never happen, since we don't plan to replace an - // instance that doesn't exist yet. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid planned change", - fmt.Sprintf("The plan contains a replace change for %s, which doesn't exist yet. This is a bug in Terraform.", addr), - )) - continue - } - - // Allocating a deposed key separately from using it can be racy - // in general, but we assume here that nothing except the apply - // node we instantiate below will actually make new deposed objects - // in practice, and so the set of already-used keys will not change - // between now and then. - dk = ris.FindUnusedDeposedKey() - } else { - // If we have no state at all yet then we can use _any_ - // DeposedKey. - dk = states.NewDeposedKey() - } - } - - if update { - // All actions except destroying the node type chosen by t.Concrete - abstract := NewNodeAbstractResourceInstance(addr) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - - if createBeforeDestroy { - // We'll attach our pre-allocated DeposedKey to the node if - // it supports that. NodeApplyableResourceInstance is the - // specific concrete node type we are looking for here really, - // since that's the only node type that might depose objects. - if dn, ok := node.(GraphNodeDeposer); ok { - dn.SetPreallocatedDeposedKey(dk) - } - log.Printf("[TRACE] DiffTransformer: %s will be represented by %s, deposing prior object to %s", addr, dag.VertexName(node), dk) - } else { - log.Printf("[TRACE] DiffTransformer: %s will be represented by %s", addr, dag.VertexName(node)) - } - - g.Add(node) - rsrcAddr := addr.ContainingResource().String() - for _, rsrcNode := range resourceNodes[rsrcAddr] { - g.Connect(dag.BasicEdge(node, rsrcNode)) - } - } - - if delete { - // Destroying always uses a destroy-specific node type, though - // which one depends on whether we're destroying a current object - // or a deposed object. - var node GraphNodeResourceInstance - abstract := NewNodeAbstractResourceInstance(addr) - if dk == states.NotDeposed { - node = &NodeDestroyResourceInstance{ - NodeAbstractResourceInstance: abstract, - DeposedKey: dk, - } - node.(*NodeDestroyResourceInstance).ModifyCreateBeforeDestroy(createBeforeDestroy) - } else { - node = &NodeDestroyDeposedResourceInstanceObject{ - NodeAbstractResourceInstance: abstract, - DeposedKey: dk, - } - } - if dk == states.NotDeposed { - log.Printf("[TRACE] DiffTransformer: %s will be represented for destruction by %s", addr, dag.VertexName(node)) - } else { - log.Printf("[TRACE] DiffTransformer: %s deposed object %s will be represented for destruction by %s", addr, dk, dag.VertexName(node)) - } - g.Add(node) - } - - } - - log.Printf("[TRACE] DiffTransformer complete") - - return diags.Err() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_expand.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_expand.go deleted file mode 100644 index 03eac685eb4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_expand.go +++ /dev/null @@ -1,48 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// GraphNodeExapndable is an interface that nodes can implement to -// signal that they can be expanded. Expanded nodes turn into -// GraphNodeSubgraph nodes within the graph. -type GraphNodeExpandable interface { - Expand(GraphBuilder) (GraphNodeSubgraph, error) -} - -// GraphNodeDynamicExpandable is an interface that nodes can implement -// to signal that they can be expanded at eval-time (hence dynamic). -// These nodes are given the eval context and are expected to return -// a new subgraph. -type GraphNodeDynamicExpandable interface { - DynamicExpand(EvalContext) (*Graph, error) -} - -// GraphNodeSubgraph is an interface a node can implement if it has -// a larger subgraph that should be walked. -type GraphNodeSubgraph interface { - Subgraph() dag.Grapher -} - -// ExpandTransform is a transformer that does a subgraph expansion -// at graph transform time (vs. at eval time). The benefit of earlier -// subgraph expansion is that errors with the graph build can be detected -// at an earlier stage. -type ExpandTransform struct { - Builder GraphBuilder -} - -func (t *ExpandTransform) Transform(v dag.Vertex) (dag.Vertex, error) { - ev, ok := v.(GraphNodeExpandable) - if !ok { - // This isn't an expandable vertex, so just ignore it. - return v, nil - } - - // Expand the subgraph! - log.Printf("[DEBUG] vertex %q: static expanding", dag.VertexName(ev)) - return ev.Expand(t.Builder) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_provider.go deleted file mode 100644 index 2ce23ddbec2..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_provider.go +++ /dev/null @@ -1,44 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// ImportProviderValidateTransformer is a GraphTransformer that goes through -// the providers in the graph and validates that they only depend on variables. -type ImportProviderValidateTransformer struct{} - -func (t *ImportProviderValidateTransformer) Transform(g *Graph) error { - var diags tfdiags.Diagnostics - - for _, v := range g.Vertices() { - // We only care about providers - pv, ok := v.(GraphNodeProvider) - if !ok { - continue - } - - // We only care about providers that reference things - rn, ok := pv.(GraphNodeReferencer) - if !ok { - continue - } - - for _, ref := range rn.References() { - if _, ok := ref.Subject.(addrs.InputVariable); !ok { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider dependency for import", - Detail: fmt.Sprintf("The configuration for %s depends on %s. Providers used with import must either have literal configuration or refer only to input variables.", pv.ProviderAddr(), ref.Subject.String()), - Subject: ref.SourceRange.ToHCL().Ptr(), - }) - } - } - } - - return diags.Err() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_state.go deleted file mode 100644 index 7dd2c4876d3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_state.go +++ /dev/null @@ -1,239 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/providers" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// ImportStateTransformer is a GraphTransformer that adds nodes to the -// graph to represent the imports we want to do for resources. -type ImportStateTransformer struct { - Targets []*ImportTarget -} - -func (t *ImportStateTransformer) Transform(g *Graph) error { - for _, target := range t.Targets { - // The ProviderAddr may not be supplied for non-aliased providers. - // This will be populated if the targets come from the cli, but tests - // may not specify implied provider addresses. - providerAddr := target.ProviderAddr - if providerAddr.ProviderConfig.Type == "" { - providerAddr = target.Addr.Resource.Resource.DefaultProviderConfig().Absolute(target.Addr.Module) - } - - node := &graphNodeImportState{ - Addr: target.Addr, - ID: target.ID, - ProviderAddr: providerAddr, - } - g.Add(node) - } - return nil -} - -type graphNodeImportState struct { - Addr addrs.AbsResourceInstance // Addr is the resource address to import into - ID string // ID is the ID to import as - ProviderAddr addrs.AbsProviderConfig // Provider address given by the user, or implied by the resource type - ResolvedProvider addrs.AbsProviderConfig // provider node address after resolution - - states []providers.ImportedResource -} - -var ( - _ GraphNodeSubPath = (*graphNodeImportState)(nil) - _ GraphNodeEvalable = (*graphNodeImportState)(nil) - _ GraphNodeProviderConsumer = (*graphNodeImportState)(nil) - _ GraphNodeDynamicExpandable = (*graphNodeImportState)(nil) -) - -func (n *graphNodeImportState) Name() string { - return fmt.Sprintf("%s (import id %q)", n.Addr, n.ID) -} - -// GraphNodeProviderConsumer -func (n *graphNodeImportState) ProvidedBy() (addrs.AbsProviderConfig, bool) { - // We assume that n.ProviderAddr has been properly populated here. - // It's the responsibility of the code creating a graphNodeImportState - // to populate this, possibly by calling DefaultProviderConfig() on the - // resource address to infer an implied provider from the resource type - // name. - return n.ProviderAddr, false -} - -// GraphNodeProviderConsumer -func (n *graphNodeImportState) SetProvider(addr addrs.AbsProviderConfig) { - n.ResolvedProvider = addr -} - -// GraphNodeSubPath -func (n *graphNodeImportState) Path() addrs.ModuleInstance { - return n.Addr.Module -} - -// GraphNodeEvalable impl. -func (n *graphNodeImportState) EvalTree() EvalNode { - var provider providers.Interface - - // Reset our states - n.states = nil - - // Return our sequence - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - }, - &EvalImportState{ - Addr: n.Addr.Resource, - Provider: &provider, - ID: n.ID, - Output: &n.states, - }, - }, - } -} - -// GraphNodeDynamicExpandable impl. -// -// We use DynamicExpand as a way to generate the subgraph of refreshes -// and state inserts we need to do for our import state. Since they're new -// resources they don't depend on anything else and refreshes are isolated -// so this is nearly a perfect use case for dynamic expand. -func (n *graphNodeImportState) DynamicExpand(ctx EvalContext) (*Graph, error) { - var diags tfdiags.Diagnostics - - g := &Graph{Path: ctx.Path()} - - // nameCounter is used to de-dup names in the state. - nameCounter := make(map[string]int) - - // Compile the list of addresses that we'll be inserting into the state. - // We do this ahead of time so we can verify that we aren't importing - // something that already exists. - addrs := make([]addrs.AbsResourceInstance, len(n.states)) - for i, state := range n.states { - addr := n.Addr - if t := state.TypeName; t != "" { - addr.Resource.Resource.Type = t - } - - // Determine if we need to suffix the name to de-dup - key := addr.String() - count, ok := nameCounter[key] - if ok { - count++ - addr.Resource.Resource.Name += fmt.Sprintf("-%d", count) - } - nameCounter[key] = count - - // Add it to our list - addrs[i] = addr - } - - // Verify that all the addresses are clear - state := ctx.State() - for _, addr := range addrs { - existing := state.ResourceInstance(addr) - if existing != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Resource already managed by Terraform", - fmt.Sprintf("Terraform is already managing a remote object for %s. To import to this address you must first remove the existing object from the state.", addr), - )) - continue - } - } - if diags.HasErrors() { - // Bail out early, then. - return nil, diags.Err() - } - - // For each of the states, we add a node to handle the refresh/add to state. - // "n.states" is populated by our own EvalTree with the result of - // ImportState. Since DynamicExpand is always called after EvalTree, this - // is safe. - for i, state := range n.states { - g.Add(&graphNodeImportStateSub{ - TargetAddr: addrs[i], - State: state, - ResolvedProvider: n.ResolvedProvider, - }) - } - - // Root transform for a single root - t := &RootTransformer{} - if err := t.Transform(g); err != nil { - return nil, err - } - - // Done! - return g, diags.Err() -} - -// graphNodeImportStateSub is the sub-node of graphNodeImportState -// and is part of the subgraph. This node is responsible for refreshing -// and adding a resource to the state once it is imported. -type graphNodeImportStateSub struct { - TargetAddr addrs.AbsResourceInstance - State providers.ImportedResource - ResolvedProvider addrs.AbsProviderConfig -} - -var ( - _ GraphNodeSubPath = (*graphNodeImportStateSub)(nil) - _ GraphNodeEvalable = (*graphNodeImportStateSub)(nil) -) - -func (n *graphNodeImportStateSub) Name() string { - return fmt.Sprintf("import %s result", n.TargetAddr) -} - -func (n *graphNodeImportStateSub) Path() addrs.ModuleInstance { - return n.TargetAddr.Module -} - -// GraphNodeEvalable impl. -func (n *graphNodeImportStateSub) EvalTree() EvalNode { - // If the Ephemeral type isn't set, then it is an error - if n.State.TypeName == "" { - err := fmt.Errorf("import of %s didn't set type", n.TargetAddr.String()) - return &EvalReturnError{Error: &err} - } - - state := n.State.AsInstanceObject() - - var provider providers.Interface - var providerSchema *ProviderSchema - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Addr: n.ResolvedProvider, - Output: &provider, - Schema: &providerSchema, - }, - &EvalRefresh{ - Addr: n.TargetAddr.Resource, - ProviderAddr: n.ResolvedProvider, - Provider: &provider, - ProviderSchema: &providerSchema, - State: &state, - Output: &state, - }, - &EvalImportStateVerify{ - Addr: n.TargetAddr.Resource, - State: &state, - }, - &EvalWriteState{ - Addr: n.TargetAddr.Resource, - ProviderAddr: n.ResolvedProvider, - ProviderSchema: &providerSchema, - State: &state, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_local.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_local.go deleted file mode 100644 index b97dea2abd4..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_local.go +++ /dev/null @@ -1,48 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" -) - -// LocalTransformer is a GraphTransformer that adds all the local values -// from the configuration to the graph. -type LocalTransformer struct { - Config *configs.Config -} - -func (t *LocalTransformer) Transform(g *Graph) error { - return t.transformModule(g, t.Config) -} - -func (t *LocalTransformer) transformModule(g *Graph, c *configs.Config) error { - if c == nil { - // Can't have any locals if there's no config - return nil - } - - // Our addressing system distinguishes between modules and module instances, - // but we're not yet ready to make that distinction here (since we don't - // support "count"/"for_each" on modules) and so we just do a naive - // transform of the module path into a module instance path, assuming that - // no keys are in use. This should be removed when "count" and "for_each" - // are implemented for modules. - path := c.Path.UnkeyedInstanceShim() - - for _, local := range c.Module.Locals { - addr := path.LocalValue(local.Name) - node := &NodeLocal{ - Addr: addr, - Config: local, - } - g.Add(node) - } - - // Also populate locals for child modules - for _, cc := range c.Children { - if err := t.transformModule(g, cc); err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_module_variable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_module_variable.go deleted file mode 100644 index caa4b6a63c6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_module_variable.go +++ /dev/null @@ -1,126 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2/hclsyntax" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" -) - -// ModuleVariableTransformer is a GraphTransformer that adds all the variables -// in the configuration to the graph. -// -// Any "variable" block present in any non-root module is included here, even -// if a particular variable is not referenced from anywhere. -// -// The transform will produce errors if a call to a module does not conform -// to the expected set of arguments, but this transformer is not in a good -// position to return errors and so the validate walk should include specific -// steps for validating module blocks, separate from this transform. -type ModuleVariableTransformer struct { - Config *configs.Config -} - -func (t *ModuleVariableTransformer) Transform(g *Graph) error { - return t.transform(g, nil, t.Config) -} - -func (t *ModuleVariableTransformer) transform(g *Graph, parent, c *configs.Config) error { - // We can have no variables if we have no configuration. - if c == nil { - return nil - } - - // Transform all the children first. - for _, cc := range c.Children { - if err := t.transform(g, c, cc); err != nil { - return err - } - } - - // If we're processing anything other than the root module then we'll - // add graph nodes for variables defined inside. (Variables for the root - // module are dealt with in RootVariableTransformer). - // If we have a parent, we can determine if a module variable is being - // used, so we transform this. - if parent != nil { - if err := t.transformSingle(g, parent, c); err != nil { - return err - } - } - - return nil -} - -func (t *ModuleVariableTransformer) transformSingle(g *Graph, parent, c *configs.Config) error { - - // Our addressing system distinguishes between modules and module instances, - // but we're not yet ready to make that distinction here (since we don't - // support "count"/"for_each" on modules) and so we just do a naive - // transform of the module path into a module instance path, assuming that - // no keys are in use. This should be removed when "count" and "for_each" - // are implemented for modules. - path := c.Path.UnkeyedInstanceShim() - _, call := path.Call() - - // Find the call in the parent module configuration, so we can get the - // expressions given for each input variable at the call site. - callConfig, exists := parent.Module.ModuleCalls[call.Name] - if !exists { - // This should never happen, since it indicates an improperly-constructed - // configuration tree. - panic(fmt.Errorf("no module call block found for %s", path)) - } - - // We need to construct a schema for the expected call arguments based on - // the configured variables in our config, which we can then use to - // decode the content of the call block. - schema := &hcl.BodySchema{} - for _, v := range c.Module.Variables { - schema.Attributes = append(schema.Attributes, hcl.AttributeSchema{ - Name: v.Name, - Required: v.Default == cty.NilVal, - }) - } - - content, contentDiags := callConfig.Config.Content(schema) - if contentDiags.HasErrors() { - // Validation code elsewhere should deal with any errors before we - // get in here, but we'll report them out here just in case, to - // avoid crashes. - var diags tfdiags.Diagnostics - diags = diags.Append(contentDiags) - return diags.Err() - } - - for _, v := range c.Module.Variables { - var expr hcl.Expression - if attr := content.Attributes[v.Name]; attr != nil { - expr = attr.Expr - } else { - // No expression provided for this variable, so we'll make a - // synthetic one using the variable's default value. - expr = &hclsyntax.LiteralValueExpr{ - Val: v.Default, - SrcRange: v.DeclRange, // This is not exact, but close enough - } - } - - // For now we treat all module variables as "applyable", even though - // such nodes are valid to use on other walks too. We may specialize - // this in future if we find reasons to employ different behaviors - // in different scenarios. - node := &NodeApplyableModuleVariable{ - Addr: path.InputVariable(v.Name), - Config: v, - Expr: expr, - } - g.Add(node) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_orphan_count.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_orphan_count.go deleted file mode 100644 index 4d1323fb09a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_orphan_count.go +++ /dev/null @@ -1,175 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" - "github.com/zclconf/go-cty/cty" -) - -// OrphanResourceCountTransformer is a GraphTransformer that adds orphans -// for an expanded count to the graph. The determination of this depends -// on the count argument given. -// -// Orphans are found by comparing the count to what is found in the state. -// This transform assumes that if an element in the state is within the count -// bounds given, that it is not an orphan. -type OrphanResourceCountTransformer struct { - Concrete ConcreteResourceInstanceNodeFunc - - Count int // Actual count of the resource, or -1 if count is not set at all - ForEach map[string]cty.Value // The ForEach map on the resource - Addr addrs.AbsResource // Addr of the resource to look for orphans - State *states.State // Full global state -} - -func (t *OrphanResourceCountTransformer) Transform(g *Graph) error { - rs := t.State.Resource(t.Addr) - if rs == nil { - return nil // Resource doesn't exist in state, so nothing to do! - } - - haveKeys := make(map[addrs.InstanceKey]struct{}) - for key := range rs.Instances { - haveKeys[key] = struct{}{} - } - - // if for_each is set, use that transformer - if t.ForEach != nil { - return t.transformForEach(haveKeys, g) - } - if t.Count < 0 { - return t.transformNoCount(haveKeys, g) - } - if t.Count == 0 { - return t.transformZeroCount(haveKeys, g) - } - return t.transformCount(haveKeys, g) -} - -func (t *OrphanResourceCountTransformer) transformForEach(haveKeys map[addrs.InstanceKey]struct{}, g *Graph) error { - // If there is a NoKey node, add this to the graph first, - // so that we can create edges to it in subsequent (StringKey) nodes. - // This is because the last item determines the resource mode for the whole resource, - // (see SetResourceInstanceCurrent for more information) and we need to evaluate - // an orphaned (NoKey) resource before the in-memory state is updated - // to deal with a new for_each resource - _, hasNoKeyNode := haveKeys[addrs.NoKey] - var noKeyNode dag.Vertex - if hasNoKeyNode { - abstract := NewNodeAbstractResourceInstance(t.Addr.Instance(addrs.NoKey)) - noKeyNode = abstract - if f := t.Concrete; f != nil { - noKeyNode = f(abstract) - } - g.Add(noKeyNode) - } - - for key := range haveKeys { - // If the key is no-key, we have already added it, so skip - if key == addrs.NoKey { - continue - } - - s, _ := key.(addrs.StringKey) - // If the key is present in our current for_each, carry on - if _, ok := t.ForEach[string(s)]; ok { - continue - } - - abstract := NewNodeAbstractResourceInstance(t.Addr.Instance(key)) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - log.Printf("[TRACE] OrphanResourceCount(non-zero): adding %s as %T", t.Addr, node) - g.Add(node) - - // Add edge to noKeyNode if it exists - if hasNoKeyNode { - g.Connect(dag.BasicEdge(node, noKeyNode)) - } - } - return nil -} - -func (t *OrphanResourceCountTransformer) transformCount(haveKeys map[addrs.InstanceKey]struct{}, g *Graph) error { - // Due to the logic in Transform, we only get in here if our count is - // at least one. - - _, have0Key := haveKeys[addrs.IntKey(0)] - - for key := range haveKeys { - if key == addrs.NoKey && !have0Key { - // If we have no 0-key then we will accept a no-key instance - // as an alias for it. - continue - } - - i, isInt := key.(addrs.IntKey) - if isInt && int(i) < t.Count { - continue - } - - abstract := NewNodeAbstractResourceInstance(t.Addr.Instance(key)) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - log.Printf("[TRACE] OrphanResourceCount(non-zero): adding %s as %T", t.Addr, node) - g.Add(node) - } - - return nil -} - -func (t *OrphanResourceCountTransformer) transformZeroCount(haveKeys map[addrs.InstanceKey]struct{}, g *Graph) error { - // This case is easy: we need to orphan any keys we have at all. - - for key := range haveKeys { - abstract := NewNodeAbstractResourceInstance(t.Addr.Instance(key)) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - log.Printf("[TRACE] OrphanResourceCount(zero): adding %s as %T", t.Addr, node) - g.Add(node) - } - - return nil -} - -func (t *OrphanResourceCountTransformer) transformNoCount(haveKeys map[addrs.InstanceKey]struct{}, g *Graph) error { - // Negative count indicates that count is not set at all, in which - // case we expect to have a single instance with no key set at all. - // However, we'll also accept an instance with key 0 set as an alias - // for it, in case the user has just deleted the "count" argument and - // so wants to keep the first instance in the set. - - _, haveNoKey := haveKeys[addrs.NoKey] - _, have0Key := haveKeys[addrs.IntKey(0)] - keepKey := addrs.NoKey - if have0Key && !haveNoKey { - // If we don't have a no-key instance then we can use the 0-key instance - // instead. - keepKey = addrs.IntKey(0) - } - - for key := range haveKeys { - if key == keepKey { - continue - } - - abstract := NewNodeAbstractResourceInstance(t.Addr.Instance(key)) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - log.Printf("[TRACE] OrphanResourceCount(no-count): adding %s as %T", t.Addr, node) - g.Add(node) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_orphan_output.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_orphan_output.go deleted file mode 100644 index cab10da124b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_orphan_output.go +++ /dev/null @@ -1,60 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// OrphanOutputTransformer finds the outputs that aren't present -// in the given config that are in the state and adds them to the graph -// for deletion. -type OrphanOutputTransformer struct { - Config *configs.Config // Root of config tree - State *states.State // State is the root state -} - -func (t *OrphanOutputTransformer) Transform(g *Graph) error { - if t.State == nil { - log.Printf("[DEBUG] No state, no orphan outputs") - return nil - } - - for _, ms := range t.State.Modules { - if err := t.transform(g, ms); err != nil { - return err - } - } - return nil -} - -func (t *OrphanOutputTransformer) transform(g *Graph, ms *states.Module) error { - if ms == nil { - return nil - } - - moduleAddr := ms.Addr - - // Get the config for this path, which is nil if the entire module has been - // removed. - var outputs map[string]*configs.Output - if c := t.Config.DescendentForInstance(moduleAddr); c != nil { - outputs = c.Module.Outputs - } - - // An output is "orphaned" if it's present in the state but not declared - // in the configuration. - for name := range ms.OutputValues { - if _, exists := outputs[name]; exists { - continue - } - - g.Add(&NodeOutputOrphan{ - Addr: addrs.OutputValue{Name: name}.Absolute(moduleAddr), - }) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_orphan_resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_orphan_resource.go deleted file mode 100644 index f927b10864c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_orphan_resource.go +++ /dev/null @@ -1,179 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// OrphanResourceInstanceTransformer is a GraphTransformer that adds orphaned -// resource instances to the graph. An "orphan" is an instance that is present -// in the state but belongs to a resource that is no longer present in the -// configuration. -// -// This is not the transformer that deals with "count orphans" (instances that -// are no longer covered by a resource's "count" or "for_each" setting); that's -// handled instead by OrphanResourceCountTransformer. -type OrphanResourceInstanceTransformer struct { - Concrete ConcreteResourceInstanceNodeFunc - - // State is the global state. We require the global state to - // properly find module orphans at our path. - State *states.State - - // Config is the root node in the configuration tree. We'll look up - // the appropriate note in this tree using the path in each node. - Config *configs.Config -} - -func (t *OrphanResourceInstanceTransformer) Transform(g *Graph) error { - if t.State == nil { - // If the entire state is nil, there can't be any orphans - return nil - } - if t.Config == nil { - // Should never happen: we can't be doing any Terraform operations - // without at least an empty configuration. - panic("OrphanResourceInstanceTransformer used without setting Config") - } - - // Go through the modules and for each module transform in order - // to add the orphan. - for _, ms := range t.State.Modules { - if err := t.transform(g, ms); err != nil { - return err - } - } - - return nil -} - -func (t *OrphanResourceInstanceTransformer) transform(g *Graph, ms *states.Module) error { - if ms == nil { - return nil - } - - moduleAddr := ms.Addr - - // Get the configuration for this module. The configuration might be - // nil if the module was removed from the configuration. This is okay, - // this just means that every resource is an orphan. - var m *configs.Module - if c := t.Config.DescendentForInstance(moduleAddr); c != nil { - m = c.Module - } - - // An "orphan" is a resource that is in the state but not the configuration, - // so we'll walk the state resources and try to correlate each of them - // with a configuration block. Each orphan gets a node in the graph whose - // type is decided by t.Concrete. - // - // We don't handle orphans related to changes in the "count" and "for_each" - // pseudo-arguments here. They are handled by OrphanResourceCountTransformer. - for _, rs := range ms.Resources { - if m != nil { - if r := m.ResourceByAddr(rs.Addr); r != nil { - continue - } - } - - for key := range rs.Instances { - addr := rs.Addr.Instance(key).Absolute(moduleAddr) - abstract := NewNodeAbstractResourceInstance(addr) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - log.Printf("[TRACE] OrphanResourceInstanceTransformer: adding single-instance orphan node for %s", addr) - g.Add(node) - } - } - - return nil -} - -// OrphanResourceTransformer is a GraphTransformer that adds orphaned -// resources to the graph. An "orphan" is a resource that is present in -// the state but no longer present in the config. -// -// This is separate to OrphanResourceInstanceTransformer in that it deals with -// whole resources, rather than individual instances of resources. Orphan -// resource nodes are only used during apply to clean up leftover empty -// resource state skeletons, after all of the instances inside have been -// removed. -// -// This transformer will also create edges in the graph to any pre-existing -// node that creates or destroys the entire orphaned resource or any of its -// instances, to ensure that the "orphan-ness" of a resource is always dealt -// with after all other aspects of it. -type OrphanResourceTransformer struct { - Concrete ConcreteResourceNodeFunc - - // State is the global state. - State *states.State - - // Config is the root node in the configuration tree. - Config *configs.Config -} - -func (t *OrphanResourceTransformer) Transform(g *Graph) error { - if t.State == nil { - // If the entire state is nil, there can't be any orphans - return nil - } - if t.Config == nil { - // Should never happen: we can't be doing any Terraform operations - // without at least an empty configuration. - panic("OrphanResourceTransformer used without setting Config") - } - - // We'll first collect up the existing nodes for each resource so we can - // create dependency edges for any new nodes we create. - deps := map[string][]dag.Vertex{} - for _, v := range g.Vertices() { - switch tv := v.(type) { - case GraphNodeResourceInstance: - k := tv.ResourceInstanceAddr().ContainingResource().String() - deps[k] = append(deps[k], v) - case GraphNodeResource: - k := tv.ResourceAddr().String() - deps[k] = append(deps[k], v) - case GraphNodeDestroyer: - k := tv.DestroyAddr().ContainingResource().String() - deps[k] = append(deps[k], v) - } - } - - for _, ms := range t.State.Modules { - moduleAddr := ms.Addr - - mc := t.Config.DescendentForInstance(moduleAddr) // might be nil if whole module has been removed - - for _, rs := range ms.Resources { - if mc != nil { - if r := mc.Module.ResourceByAddr(rs.Addr); r != nil { - // It's in the config, so nothing to do for this one. - continue - } - } - - addr := rs.Addr.Absolute(moduleAddr) - abstract := NewNodeAbstractResource(addr) - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - log.Printf("[TRACE] OrphanResourceTransformer: adding whole-resource orphan node for %s", addr) - g.Add(node) - for _, dn := range deps[addr.String()] { - log.Printf("[TRACE] OrphanResourceTransformer: node %q depends on %q", dag.VertexName(node), dag.VertexName(dn)) - g.Connect(dag.BasicEdge(node, dn)) - } - } - } - - return nil - -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_output.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_output.go deleted file mode 100644 index e2979ac5c47..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_output.go +++ /dev/null @@ -1,95 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// OutputTransformer is a GraphTransformer that adds all the outputs -// in the configuration to the graph. -// -// This is done for the apply graph builder even if dependent nodes -// aren't changing since there is no downside: the state will be available -// even if the dependent items aren't changing. -type OutputTransformer struct { - Config *configs.Config -} - -func (t *OutputTransformer) Transform(g *Graph) error { - return t.transform(g, t.Config) -} - -func (t *OutputTransformer) transform(g *Graph, c *configs.Config) error { - // If we have no config then there can be no outputs. - if c == nil { - return nil - } - - // Transform all the children. We must do this first because - // we can reference module outputs and they must show up in the - // reference map. - for _, cc := range c.Children { - if err := t.transform(g, cc); err != nil { - return err - } - } - - // Our addressing system distinguishes between modules and module instances, - // but we're not yet ready to make that distinction here (since we don't - // support "count"/"for_each" on modules) and so we just do a naive - // transform of the module path into a module instance path, assuming that - // no keys are in use. This should be removed when "count" and "for_each" - // are implemented for modules. - path := c.Path.UnkeyedInstanceShim() - - for _, o := range c.Module.Outputs { - addr := path.OutputValue(o.Name) - node := &NodeApplyableOutput{ - Addr: addr, - Config: o, - } - g.Add(node) - } - - return nil -} - -// DestroyOutputTransformer is a GraphTransformer that adds nodes to delete -// outputs during destroy. We need to do this to ensure that no stale outputs -// are ever left in the state. -type DestroyOutputTransformer struct { -} - -func (t *DestroyOutputTransformer) Transform(g *Graph) error { - for _, v := range g.Vertices() { - output, ok := v.(*NodeApplyableOutput) - if !ok { - continue - } - - // create the destroy node for this output - node := &NodeDestroyableOutput{ - Addr: output.Addr, - Config: output.Config, - } - - log.Printf("[TRACE] creating %s", node.Name()) - g.Add(node) - - deps, err := g.Descendents(v) - if err != nil { - return err - } - - // the destroy node must depend on the eval node - deps.Add(v) - - for _, d := range deps.List() { - log.Printf("[TRACE] %s depends on %s", node.Name(), dag.VertexName(d)) - g.Connect(dag.BasicEdge(node, d)) - } - } - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_provider.go deleted file mode 100644 index 9c8966faceb..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_provider.go +++ /dev/null @@ -1,705 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -func TransformProviders(providers []string, concrete ConcreteProviderNodeFunc, config *configs.Config) GraphTransformer { - return GraphTransformMulti( - // Add providers from the config - &ProviderConfigTransformer{ - Config: config, - Providers: providers, - Concrete: concrete, - }, - // Add any remaining missing providers - &MissingProviderTransformer{ - Providers: providers, - Concrete: concrete, - }, - // Connect the providers - &ProviderTransformer{ - Config: config, - }, - // Remove unused providers and proxies - &PruneProviderTransformer{}, - // Connect provider to their parent provider nodes - &ParentProviderTransformer{}, - ) -} - -// GraphNodeProvider is an interface that nodes that can be a provider -// must implement. -// -// ProviderAddr returns the address of the provider configuration this -// satisfies, which is relative to the path returned by method Path(). -// -// Name returns the full name of the provider in the config. -type GraphNodeProvider interface { - GraphNodeSubPath - ProviderAddr() addrs.AbsProviderConfig - Name() string -} - -// GraphNodeCloseProvider is an interface that nodes that can be a close -// provider must implement. The CloseProviderName returned is the name of -// the provider they satisfy. -type GraphNodeCloseProvider interface { - GraphNodeSubPath - CloseProviderAddr() addrs.AbsProviderConfig -} - -// GraphNodeProviderConsumer is an interface that nodes that require -// a provider must implement. ProvidedBy must return the address of the provider -// to use, which will be resolved to a configuration either in the same module -// or in an ancestor module, with the resulting absolute address passed to -// SetProvider. -type GraphNodeProviderConsumer interface { - // ProvidedBy returns the address of the provider configuration the node - // refers to. If the returned "exact" value is true, this address will - // be taken exactly. If "exact" is false, a provider configuration from - // an ancestor module may be selected instead. - ProvidedBy() (addr addrs.AbsProviderConfig, exact bool) - // Set the resolved provider address for this resource. - SetProvider(addrs.AbsProviderConfig) -} - -// ProviderTransformer is a GraphTransformer that maps resources to -// providers within the graph. This will error if there are any resources -// that don't map to proper resources. -type ProviderTransformer struct { - Config *configs.Config -} - -func (t *ProviderTransformer) Transform(g *Graph) error { - // We need to find a provider configuration address for each resource - // either directly represented by a node or referenced by a node in - // the graph, and then create graph edges from provider to provider user - // so that the providers will get initialized first. - - var diags tfdiags.Diagnostics - - // To start, we'll collect the _requested_ provider addresses for each - // node, which we'll then resolve (handling provider inheritence, etc) in - // the next step. - // Our "requested" map is from graph vertices to string representations of - // provider config addresses (for deduping) to requests. - type ProviderRequest struct { - Addr addrs.AbsProviderConfig - Exact bool // If true, inheritence from parent modules is not attempted - } - requested := map[dag.Vertex]map[string]ProviderRequest{} - needConfigured := map[string]addrs.AbsProviderConfig{} - for _, v := range g.Vertices() { - - // Does the vertex _directly_ use a provider? - if pv, ok := v.(GraphNodeProviderConsumer); ok { - requested[v] = make(map[string]ProviderRequest) - - p, exact := pv.ProvidedBy() - if exact { - log.Printf("[TRACE] ProviderTransformer: %s is provided by %s exactly", dag.VertexName(v), p) - } else { - log.Printf("[TRACE] ProviderTransformer: %s is provided by %s or inherited equivalent", dag.VertexName(v), p) - } - - requested[v][p.String()] = ProviderRequest{ - Addr: p, - Exact: exact, - } - - // Direct references need the provider configured as well as initialized - needConfigured[p.String()] = p - } - } - - // Now we'll go through all the requested addresses we just collected and - // figure out which _actual_ config address each belongs to, after resolving - // for provider inheritance and passing. - m := providerVertexMap(g) - for v, reqs := range requested { - for key, req := range reqs { - p := req.Addr - target := m[key] - - _, ok := v.(GraphNodeSubPath) - if !ok && target == nil { - // No target and no path to traverse up from - diags = diags.Append(fmt.Errorf("%s: provider %s couldn't be found", dag.VertexName(v), p)) - continue - } - - if target != nil { - log.Printf("[TRACE] ProviderTransformer: exact match for %s serving %s", p, dag.VertexName(v)) - } - - // if we don't have a provider at this level, walk up the path looking for one, - // unless we were told to be exact. - if target == nil && !req.Exact { - for pp, ok := p.Inherited(); ok; pp, ok = pp.Inherited() { - key := pp.String() - target = m[key] - if target != nil { - log.Printf("[TRACE] ProviderTransformer: %s uses inherited configuration %s", dag.VertexName(v), pp) - break - } - log.Printf("[TRACE] ProviderTransformer: looking for %s to serve %s", pp, dag.VertexName(v)) - } - } - - // If this provider doesn't need to be configured then we can just - // stub it out with an init-only provider node, which will just - // start up the provider and fetch its schema. - if _, exists := needConfigured[key]; target == nil && !exists { - stubAddr := p.ProviderConfig.Absolute(addrs.RootModuleInstance) - stub := &NodeEvalableProvider{ - &NodeAbstractProvider{ - Addr: stubAddr, - }, - } - m[stubAddr.String()] = stub - log.Printf("[TRACE] ProviderTransformer: creating init-only node for %s", stubAddr) - target = stub - g.Add(target) - } - - if target == nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Provider configuration not present", - fmt.Sprintf( - "To work with %s its original provider configuration at %s is required, but it has been removed. This occurs when a provider configuration is removed while objects created by that provider still exist in the state. Re-add the provider configuration to destroy %s, after which you can remove the provider configuration again.", - dag.VertexName(v), p, dag.VertexName(v), - ), - )) - break - } - - // see if this in an inherited provider - if p, ok := target.(*graphNodeProxyProvider); ok { - g.Remove(p) - target = p.Target() - key = target.(GraphNodeProvider).ProviderAddr().String() - } - - log.Printf("[DEBUG] ProviderTransformer: %q (%T) needs %s", dag.VertexName(v), v, dag.VertexName(target)) - if pv, ok := v.(GraphNodeProviderConsumer); ok { - pv.SetProvider(target.ProviderAddr()) - } - g.Connect(dag.BasicEdge(v, target)) - } - } - - return diags.Err() -} - -// CloseProviderTransformer is a GraphTransformer that adds nodes to the -// graph that will close open provider connections that aren't needed anymore. -// A provider connection is not needed anymore once all depended resources -// in the graph are evaluated. -type CloseProviderTransformer struct{} - -func (t *CloseProviderTransformer) Transform(g *Graph) error { - pm := providerVertexMap(g) - cpm := make(map[string]*graphNodeCloseProvider) - var err error - - for _, v := range pm { - p := v.(GraphNodeProvider) - key := p.ProviderAddr().String() - - // get the close provider of this type if we alread created it - closer := cpm[key] - - if closer == nil { - // create a closer for this provider type - closer = &graphNodeCloseProvider{Addr: p.ProviderAddr()} - g.Add(closer) - cpm[key] = closer - } - - // Close node depends on the provider itself - // this is added unconditionally, so it will connect to all instances - // of the provider. Extra edges will be removed by transitive - // reduction. - g.Connect(dag.BasicEdge(closer, p)) - - // connect all the provider's resources to the close node - for _, s := range g.UpEdges(p).List() { - if _, ok := s.(GraphNodeProviderConsumer); ok { - g.Connect(dag.BasicEdge(closer, s)) - } - } - } - - return err -} - -// MissingProviderTransformer is a GraphTransformer that adds to the graph -// a node for each default provider configuration that is referenced by another -// node but not already present in the graph. -// -// These "default" nodes are always added to the root module, regardless of -// where they are requested. This is important because our inheritance -// resolution behavior in ProviderTransformer will then treat these as a -// last-ditch fallback after walking up the tree, rather than preferring them -// as it would if they were placed in the same module as the requester. -// -// This transformer may create extra nodes that are not needed in practice, -// due to overriding provider configurations in child modules. -// PruneProviderTransformer can then remove these once ProviderTransformer -// has resolved all of the inheritence, etc. -type MissingProviderTransformer struct { - // Providers is the list of providers we support. - Providers []string - - // Concrete, if set, overrides how the providers are made. - Concrete ConcreteProviderNodeFunc -} - -func (t *MissingProviderTransformer) Transform(g *Graph) error { - // Initialize factory - if t.Concrete == nil { - t.Concrete = func(a *NodeAbstractProvider) dag.Vertex { - return a - } - } - - var err error - m := providerVertexMap(g) - for _, v := range g.Vertices() { - pv, ok := v.(GraphNodeProviderConsumer) - if !ok { - continue - } - - // For our work here we actually care only about the provider type and - // we plan to place all default providers in the root module, and so - // it's safe for us to rely on ProvidedBy here rather than waiting for - // the later proper resolution of provider inheritance done by - // ProviderTransformer. - p, _ := pv.ProvidedBy() - if p.ProviderConfig.Alias != "" { - // We do not create default aliased configurations. - log.Println("[TRACE] MissingProviderTransformer: skipping implication of aliased config", p) - continue - } - - // We're going to create an implicit _default_ configuration for the - // referenced provider type in the _root_ module, ignoring all other - // aspects of the resource's declared provider address. - defaultAddr := addrs.RootModuleInstance.ProviderConfigDefault(p.ProviderConfig.Type) - key := defaultAddr.String() - provider := m[key] - - if provider != nil { - // There's already an explicit default configuration for this - // provider type in the root module, so we have nothing to do. - continue - } - - log.Printf("[DEBUG] adding implicit provider configuration %s, implied first by %s", defaultAddr, dag.VertexName(v)) - - // create the missing top-level provider - provider = t.Concrete(&NodeAbstractProvider{ - Addr: defaultAddr, - }).(GraphNodeProvider) - - g.Add(provider) - m[key] = provider - } - - return err -} - -// ParentProviderTransformer connects provider nodes to their parents. -// -// This works by finding nodes that are both GraphNodeProviders and -// GraphNodeSubPath. It then connects the providers to their parent -// path. The parent provider is always at the root level. -type ParentProviderTransformer struct{} - -func (t *ParentProviderTransformer) Transform(g *Graph) error { - pm := providerVertexMap(g) - for _, v := range g.Vertices() { - // Only care about providers - pn, ok := v.(GraphNodeProvider) - if !ok { - continue - } - - // Also require non-empty path, since otherwise we're in the root - // module and so cannot have a parent. - if len(pn.Path()) <= 1 { - continue - } - - // this provider may be disabled, but we can only get it's name from - // the ProviderName string - addr := pn.ProviderAddr() - parentAddr, ok := addr.Inherited() - if ok { - parent := pm[parentAddr.String()] - if parent != nil { - g.Connect(dag.BasicEdge(v, parent)) - } - } - } - return nil -} - -// PruneProviderTransformer removes any providers that are not actually used by -// anything, and provider proxies. This avoids the provider being initialized -// and configured. This both saves resources but also avoids errors since -// configuration may imply initialization which may require auth. -type PruneProviderTransformer struct{} - -func (t *PruneProviderTransformer) Transform(g *Graph) error { - for _, v := range g.Vertices() { - // We only care about providers - _, ok := v.(GraphNodeProvider) - if !ok { - continue - } - - // ProxyProviders will have up edges, but we're now done with them in the graph - if _, ok := v.(*graphNodeProxyProvider); ok { - log.Printf("[DEBUG] pruning proxy %s", dag.VertexName(v)) - g.Remove(v) - } - - // Remove providers with no dependencies. - if g.UpEdges(v).Len() == 0 { - log.Printf("[DEBUG] pruning unused %s", dag.VertexName(v)) - g.Remove(v) - } - } - - return nil -} - -func providerVertexMap(g *Graph) map[string]GraphNodeProvider { - m := make(map[string]GraphNodeProvider) - for _, v := range g.Vertices() { - if pv, ok := v.(GraphNodeProvider); ok { - addr := pv.ProviderAddr() - m[addr.String()] = pv - } - } - - return m -} - -type graphNodeCloseProvider struct { - Addr addrs.AbsProviderConfig -} - -var ( - _ GraphNodeCloseProvider = (*graphNodeCloseProvider)(nil) -) - -func (n *graphNodeCloseProvider) Name() string { - return n.Addr.String() + " (close)" -} - -// GraphNodeSubPath impl. -func (n *graphNodeCloseProvider) Path() addrs.ModuleInstance { - return n.Addr.Module -} - -// GraphNodeEvalable impl. -func (n *graphNodeCloseProvider) EvalTree() EvalNode { - return CloseProviderEvalTree(n.Addr) -} - -// GraphNodeDependable impl. -func (n *graphNodeCloseProvider) DependableName() []string { - return []string{n.Name()} -} - -func (n *graphNodeCloseProvider) CloseProviderAddr() addrs.AbsProviderConfig { - return n.Addr -} - -// GraphNodeDotter impl. -func (n *graphNodeCloseProvider) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - if !opts.Verbose { - return nil - } - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "diamond", - }, - } -} - -// RemovableIfNotTargeted -func (n *graphNodeCloseProvider) RemoveIfNotTargeted() bool { - // We need to add this so that this node will be removed if - // it isn't targeted or a dependency of a target. - return true -} - -// graphNodeProxyProvider is a GraphNodeProvider implementation that is used to -// store the name and value of a provider node for inheritance between modules. -// These nodes are only used to store the data while loading the provider -// configurations, and are removed after all the resources have been connected -// to their providers. -type graphNodeProxyProvider struct { - addr addrs.AbsProviderConfig - target GraphNodeProvider -} - -var ( - _ GraphNodeProvider = (*graphNodeProxyProvider)(nil) -) - -func (n *graphNodeProxyProvider) ProviderAddr() addrs.AbsProviderConfig { - return n.addr -} - -func (n *graphNodeProxyProvider) Path() addrs.ModuleInstance { - return n.addr.Module -} - -func (n *graphNodeProxyProvider) Name() string { - return n.addr.String() + " (proxy)" -} - -// find the concrete provider instance -func (n *graphNodeProxyProvider) Target() GraphNodeProvider { - switch t := n.target.(type) { - case *graphNodeProxyProvider: - return t.Target() - default: - return n.target - } -} - -// ProviderConfigTransformer adds all provider nodes from the configuration and -// attaches the configs. -type ProviderConfigTransformer struct { - Providers []string - Concrete ConcreteProviderNodeFunc - - // each provider node is stored here so that the proxy nodes can look up - // their targets by name. - providers map[string]GraphNodeProvider - // record providers that can be overriden with a proxy - proxiable map[string]bool - - // Config is the root node of the configuration tree to add providers from. - Config *configs.Config -} - -func (t *ProviderConfigTransformer) Transform(g *Graph) error { - // If no configuration is given, we don't do anything - if t.Config == nil { - return nil - } - - t.providers = make(map[string]GraphNodeProvider) - t.proxiable = make(map[string]bool) - - // Start the transformation process - if err := t.transform(g, t.Config); err != nil { - return err - } - - // finally attach the configs to the new nodes - return t.attachProviderConfigs(g) -} - -func (t *ProviderConfigTransformer) transform(g *Graph, c *configs.Config) error { - // If no config, do nothing - if c == nil { - return nil - } - - // Add our resources - if err := t.transformSingle(g, c); err != nil { - return err - } - - // Transform all the children. - for _, cc := range c.Children { - if err := t.transform(g, cc); err != nil { - return err - } - } - return nil -} - -func (t *ProviderConfigTransformer) transformSingle(g *Graph, c *configs.Config) error { - // Get the module associated with this configuration tree node - mod := c.Module - staticPath := c.Path - - // We actually need a dynamic module path here, but we've not yet updated - // our graph builders enough to support expansion of module calls with - // "count" and "for_each" set, so for now we'll shim this by converting to - // a dynamic path with no keys. At the time of writing this is the only - // possible kind of dynamic path anyway. - path := make(addrs.ModuleInstance, len(staticPath)) - for i, name := range staticPath { - path[i] = addrs.ModuleInstanceStep{ - Name: name, - } - } - - // add all providers from the configuration - for _, p := range mod.ProviderConfigs { - relAddr := p.Addr() - addr := relAddr.Absolute(path) - - abstract := &NodeAbstractProvider{ - Addr: addr, - } - var v dag.Vertex - if t.Concrete != nil { - v = t.Concrete(abstract) - } else { - v = abstract - } - - // Add it to the graph - g.Add(v) - key := addr.String() - t.providers[key] = v.(GraphNodeProvider) - - // A provider configuration is "proxyable" if its configuration is - // entirely empty. This means it's standing in for a provider - // configuration that must be passed in from the parent module. - // We decide this by evaluating the config with an empty schema; - // if this succeeds, then we know there's nothing in the body. - _, diags := p.Config.Content(&hcl.BodySchema{}) - t.proxiable[key] = !diags.HasErrors() - } - - // Now replace the provider nodes with proxy nodes if a provider was being - // passed in, and create implicit proxies if there was no config. Any extra - // proxies will be removed in the prune step. - return t.addProxyProviders(g, c) -} - -func (t *ProviderConfigTransformer) addProxyProviders(g *Graph, c *configs.Config) error { - path := c.Path - - // can't add proxies at the root - if len(path) == 0 { - return nil - } - - parentPath, callAddr := path.Call() - parent := c.Parent - if parent == nil { - return nil - } - - callName := callAddr.Name - var parentCfg *configs.ModuleCall - for name, mod := range parent.Module.ModuleCalls { - if name == callName { - parentCfg = mod - break - } - } - - // We currently don't support count/for_each for modules and so we must - // shim our path and parentPath into module instances here so that the - // rest of Terraform can behave as if we do. This shimming should be - // removed later as part of implementing count/for_each for modules. - instPath := make(addrs.ModuleInstance, len(path)) - for i, name := range path { - instPath[i] = addrs.ModuleInstanceStep{Name: name} - } - parentInstPath := make(addrs.ModuleInstance, len(parentPath)) - for i, name := range parentPath { - parentInstPath[i] = addrs.ModuleInstanceStep{Name: name} - } - - if parentCfg == nil { - // this can't really happen during normal execution. - return fmt.Errorf("parent module config not found for %s", c.Path.String()) - } - - // Go through all the providers the parent is passing in, and add proxies to - // the parent provider nodes. - for _, pair := range parentCfg.Providers { - fullAddr := pair.InChild.Addr().Absolute(instPath) - fullParentAddr := pair.InParent.Addr().Absolute(parentInstPath) - fullName := fullAddr.String() - fullParentName := fullParentAddr.String() - - parentProvider := t.providers[fullParentName] - - if parentProvider == nil { - return fmt.Errorf("missing provider %s", fullParentName) - } - - proxy := &graphNodeProxyProvider{ - addr: fullAddr, - target: parentProvider, - } - - concreteProvider := t.providers[fullName] - - // replace the concrete node with the provider passed in - if concreteProvider != nil && t.proxiable[fullName] { - g.Replace(concreteProvider, proxy) - t.providers[fullName] = proxy - continue - } - - // aliased configurations can't be implicitly passed in - if fullAddr.ProviderConfig.Alias != "" { - continue - } - - // There was no concrete provider, so add this as an implicit provider. - // The extra proxy will be pruned later if it's unused. - g.Add(proxy) - t.providers[fullName] = proxy - } - return nil -} - -func (t *ProviderConfigTransformer) attachProviderConfigs(g *Graph) error { - for _, v := range g.Vertices() { - // Only care about GraphNodeAttachProvider implementations - apn, ok := v.(GraphNodeAttachProvider) - if !ok { - continue - } - - // Determine what we're looking for - addr := apn.ProviderAddr() - - // Get the configuration. - mc := t.Config.DescendentForInstance(addr.Module) - if mc == nil { - log.Printf("[TRACE] ProviderConfigTransformer: no configuration available for %s", addr.String()) - continue - } - - // Go through the provider configs to find the matching config - for _, p := range mc.Module.ProviderConfigs { - if p.Name == addr.ProviderConfig.Type && p.Alias == addr.ProviderConfig.Alias { - log.Printf("[TRACE] ProviderConfigTransformer: attaching to %q provider configuration from %s", dag.VertexName(v), p.DeclRange) - apn.AttachProvider(p) - break - } - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_provisioner.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_provisioner.go deleted file mode 100644 index e6fe25dac00..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_provisioner.go +++ /dev/null @@ -1,205 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - - "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// GraphNodeProvisioner is an interface that nodes that can be a provisioner -// must implement. The ProvisionerName returned is the name of the provisioner -// they satisfy. -type GraphNodeProvisioner interface { - ProvisionerName() string -} - -// GraphNodeCloseProvisioner is an interface that nodes that can be a close -// provisioner must implement. The CloseProvisionerName returned is the name -// of the provisioner they satisfy. -type GraphNodeCloseProvisioner interface { - CloseProvisionerName() string -} - -// GraphNodeProvisionerConsumer is an interface that nodes that require -// a provisioner must implement. ProvisionedBy must return the names of the -// provisioners to use. -type GraphNodeProvisionerConsumer interface { - ProvisionedBy() []string -} - -// ProvisionerTransformer is a GraphTransformer that maps resources to -// provisioners within the graph. This will error if there are any resources -// that don't map to proper resources. -type ProvisionerTransformer struct{} - -func (t *ProvisionerTransformer) Transform(g *Graph) error { - // Go through the other nodes and match them to provisioners they need - var err error - m := provisionerVertexMap(g) - for _, v := range g.Vertices() { - if pv, ok := v.(GraphNodeProvisionerConsumer); ok { - for _, p := range pv.ProvisionedBy() { - key := provisionerMapKey(p, pv) - if m[key] == nil { - err = multierror.Append(err, fmt.Errorf( - "%s: provisioner %s couldn't be found", - dag.VertexName(v), p)) - continue - } - - log.Printf("[TRACE] ProvisionerTransformer: %s is provisioned by %s (%q)", dag.VertexName(v), key, dag.VertexName(m[key])) - g.Connect(dag.BasicEdge(v, m[key])) - } - } - } - - return err -} - -// MissingProvisionerTransformer is a GraphTransformer that adds nodes -// for missing provisioners into the graph. -type MissingProvisionerTransformer struct { - // Provisioners is the list of provisioners we support. - Provisioners []string -} - -func (t *MissingProvisionerTransformer) Transform(g *Graph) error { - // Create a set of our supported provisioners - supported := make(map[string]struct{}, len(t.Provisioners)) - for _, v := range t.Provisioners { - supported[v] = struct{}{} - } - - // Get the map of provisioners we already have in our graph - m := provisionerVertexMap(g) - - // Go through all the provisioner consumers and make sure we add - // that provisioner if it is missing. - for _, v := range g.Vertices() { - pv, ok := v.(GraphNodeProvisionerConsumer) - if !ok { - continue - } - - // If this node has a subpath, then we use that as a prefix - // into our map to check for an existing provider. - path := addrs.RootModuleInstance - if sp, ok := pv.(GraphNodeSubPath); ok { - path = sp.Path() - } - - for _, p := range pv.ProvisionedBy() { - // Build the key for storing in the map - key := provisionerMapKey(p, pv) - - if _, ok := m[key]; ok { - // This provisioner already exists as a configure node - continue - } - - if _, ok := supported[p]; !ok { - // If we don't support the provisioner type, we skip it. - // Validation later will catch this as an error. - continue - } - - // Build the vertex - var newV dag.Vertex = &NodeProvisioner{ - NameValue: p, - PathValue: path, - } - - // Add the missing provisioner node to the graph - m[key] = g.Add(newV) - log.Printf("[TRACE] MissingProviderTransformer: added implicit provisioner %s, first implied by %s", key, dag.VertexName(v)) - } - } - - return nil -} - -// CloseProvisionerTransformer is a GraphTransformer that adds nodes to the -// graph that will close open provisioner connections that aren't needed -// anymore. A provisioner connection is not needed anymore once all depended -// resources in the graph are evaluated. -type CloseProvisionerTransformer struct{} - -func (t *CloseProvisionerTransformer) Transform(g *Graph) error { - m := closeProvisionerVertexMap(g) - for _, v := range g.Vertices() { - if pv, ok := v.(GraphNodeProvisionerConsumer); ok { - for _, p := range pv.ProvisionedBy() { - source := m[p] - - if source == nil { - // Create a new graphNodeCloseProvisioner and add it to the graph - source = &graphNodeCloseProvisioner{ProvisionerNameValue: p} - g.Add(source) - - // Make sure we also add the new graphNodeCloseProvisioner to the map - // so we don't create and add any duplicate graphNodeCloseProvisioners. - m[p] = source - } - - g.Connect(dag.BasicEdge(source, v)) - } - } - } - - return nil -} - -// provisionerMapKey is a helper that gives us the key to use for the -// maps returned by things such as provisionerVertexMap. -func provisionerMapKey(k string, v dag.Vertex) string { - pathPrefix := "" - if sp, ok := v.(GraphNodeSubPath); ok { - pathPrefix = sp.Path().String() + "." - } - - return pathPrefix + k -} - -func provisionerVertexMap(g *Graph) map[string]dag.Vertex { - m := make(map[string]dag.Vertex) - for _, v := range g.Vertices() { - if pv, ok := v.(GraphNodeProvisioner); ok { - key := provisionerMapKey(pv.ProvisionerName(), v) - m[key] = v - } - } - - return m -} - -func closeProvisionerVertexMap(g *Graph) map[string]dag.Vertex { - m := make(map[string]dag.Vertex) - for _, v := range g.Vertices() { - if pv, ok := v.(GraphNodeCloseProvisioner); ok { - m[pv.CloseProvisionerName()] = v - } - } - - return m -} - -type graphNodeCloseProvisioner struct { - ProvisionerNameValue string -} - -func (n *graphNodeCloseProvisioner) Name() string { - return fmt.Sprintf("provisioner.%s (close)", n.ProvisionerNameValue) -} - -// GraphNodeEvalable impl. -func (n *graphNodeCloseProvisioner) EvalTree() EvalNode { - return &EvalCloseProvisioner{Name: n.ProvisionerNameValue} -} - -func (n *graphNodeCloseProvisioner) CloseProvisionerName() string { - return n.ProvisionerNameValue -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_reference.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_reference.go deleted file mode 100644 index 54f9829c754..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_reference.go +++ /dev/null @@ -1,446 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/hashicorp/terraform-plugin-sdk/internal/lang" -) - -// GraphNodeReferenceable must be implemented by any node that represents -// a Terraform thing that can be referenced (resource, module, etc.). -// -// Even if the thing has no name, this should return an empty list. By -// implementing this and returning a non-nil result, you say that this CAN -// be referenced and other methods of referencing may still be possible (such -// as by path!) -type GraphNodeReferenceable interface { - GraphNodeSubPath - - // ReferenceableAddrs returns a list of addresses through which this can be - // referenced. - ReferenceableAddrs() []addrs.Referenceable -} - -// GraphNodeReferencer must be implemented by nodes that reference other -// Terraform items and therefore depend on them. -type GraphNodeReferencer interface { - GraphNodeSubPath - - // References returns a list of references made by this node, which - // include both a referenced address and source location information for - // the reference. - References() []*addrs.Reference -} - -// GraphNodeReferenceOutside is an interface that can optionally be implemented. -// A node that implements it can specify that its own referenceable addresses -// and/or the addresses it references are in a different module than the -// node itself. -// -// Any referenceable addresses returned by ReferenceableAddrs are interpreted -// relative to the returned selfPath. -// -// Any references returned by References are interpreted relative to the -// returned referencePath. -// -// It is valid but not required for either of these paths to match what is -// returned by method Path, though if both match the main Path then there -// is no reason to implement this method. -// -// The primary use-case for this is the nodes representing module input -// variables, since their expressions are resolved in terms of their calling -// module, but they are still referenced from their own module. -type GraphNodeReferenceOutside interface { - // ReferenceOutside returns a path in which any references from this node - // are resolved. - ReferenceOutside() (selfPath, referencePath addrs.ModuleInstance) -} - -// ReferenceTransformer is a GraphTransformer that connects all the -// nodes that reference each other in order to form the proper ordering. -type ReferenceTransformer struct{} - -func (t *ReferenceTransformer) Transform(g *Graph) error { - // Build a reference map so we can efficiently look up the references - vs := g.Vertices() - m := NewReferenceMap(vs) - - // Find the things that reference things and connect them - for _, v := range vs { - parents, _ := m.References(v) - parentsDbg := make([]string, len(parents)) - for i, v := range parents { - parentsDbg[i] = dag.VertexName(v) - } - log.Printf( - "[DEBUG] ReferenceTransformer: %q references: %v", - dag.VertexName(v), parentsDbg) - - for _, parent := range parents { - g.Connect(dag.BasicEdge(v, parent)) - } - } - - return nil -} - -// DestroyReferenceTransformer is a GraphTransformer that reverses the edges -// for locals and outputs that depend on other nodes which will be -// removed during destroy. If a destroy node is evaluated before the local or -// output value, it will be removed from the state, and the later interpolation -// will fail. -type DestroyValueReferenceTransformer struct{} - -func (t *DestroyValueReferenceTransformer) Transform(g *Graph) error { - vs := g.Vertices() - for _, v := range vs { - switch v.(type) { - case *NodeApplyableOutput, *NodeLocal: - // OK - default: - continue - } - - // reverse any outgoing edges so that the value is evaluated first. - for _, e := range g.EdgesFrom(v) { - target := e.Target() - - // only destroy nodes will be evaluated in reverse - if _, ok := target.(GraphNodeDestroyer); !ok { - continue - } - - log.Printf("[TRACE] output dep: %s", dag.VertexName(target)) - - g.RemoveEdge(e) - g.Connect(&DestroyEdge{S: target, T: v}) - } - } - - return nil -} - -// PruneUnusedValuesTransformer is s GraphTransformer that removes local and -// output values which are not referenced in the graph. Since outputs and -// locals always need to be evaluated, if they reference a resource that is not -// available in the state the interpolation could fail. -type PruneUnusedValuesTransformer struct{} - -func (t *PruneUnusedValuesTransformer) Transform(g *Graph) error { - // this might need multiple runs in order to ensure that pruning a value - // doesn't effect a previously checked value. - for removed := 0; ; removed = 0 { - for _, v := range g.Vertices() { - switch v.(type) { - case *NodeApplyableOutput, *NodeLocal: - // OK - default: - continue - } - - dependants := g.UpEdges(v) - - switch dependants.Len() { - case 0: - // nothing at all depends on this - g.Remove(v) - removed++ - case 1: - // because an output's destroy node always depends on the output, - // we need to check for the case of a single destroy node. - d := dependants.List()[0] - if _, ok := d.(*NodeDestroyableOutput); ok { - g.Remove(v) - removed++ - } - } - } - if removed == 0 { - break - } - } - - return nil -} - -// ReferenceMap is a structure that can be used to efficiently check -// for references on a graph. -type ReferenceMap struct { - // vertices is a map from internal reference keys (as produced by the - // mapKey method) to one or more vertices that are identified by each key. - // - // A particular reference key might actually identify multiple vertices, - // e.g. in situations where one object is contained inside another. - vertices map[string][]dag.Vertex - - // edges is a map whose keys are a subset of the internal reference keys - // from "vertices", and whose values are the nodes that refer to each - // key. The values in this map are the referrers, while values in - // "verticies" are the referents. The keys in both cases are referents. - edges map[string][]dag.Vertex -} - -// References returns the set of vertices that the given vertex refers to, -// and any referenced addresses that do not have corresponding vertices. -func (m *ReferenceMap) References(v dag.Vertex) ([]dag.Vertex, []addrs.Referenceable) { - rn, ok := v.(GraphNodeReferencer) - if !ok { - return nil, nil - } - if _, ok := v.(GraphNodeSubPath); !ok { - return nil, nil - } - - var matches []dag.Vertex - var missing []addrs.Referenceable - - for _, ref := range rn.References() { - subject := ref.Subject - - key := m.referenceMapKey(v, subject) - if _, exists := m.vertices[key]; !exists { - // If what we were looking for was a ResourceInstance then we - // might be in a resource-oriented graph rather than an - // instance-oriented graph, and so we'll see if we have the - // resource itself instead. - switch ri := subject.(type) { - case addrs.ResourceInstance: - subject = ri.ContainingResource() - case addrs.ResourceInstancePhase: - subject = ri.ContainingResource() - } - key = m.referenceMapKey(v, subject) - } - - vertices := m.vertices[key] - for _, rv := range vertices { - // don't include self-references - if rv == v { - continue - } - matches = append(matches, rv) - } - if len(vertices) == 0 { - missing = append(missing, ref.Subject) - } - } - - return matches, missing -} - -// Referrers returns the set of vertices that refer to the given vertex. -func (m *ReferenceMap) Referrers(v dag.Vertex) []dag.Vertex { - rn, ok := v.(GraphNodeReferenceable) - if !ok { - return nil - } - sp, ok := v.(GraphNodeSubPath) - if !ok { - return nil - } - - var matches []dag.Vertex - for _, addr := range rn.ReferenceableAddrs() { - key := m.mapKey(sp.Path(), addr) - referrers, ok := m.edges[key] - if !ok { - continue - } - - // If the referrer set includes our own given vertex then we skip, - // since we don't want to return self-references. - selfRef := false - for _, p := range referrers { - if p == v { - selfRef = true - break - } - } - if selfRef { - continue - } - - matches = append(matches, referrers...) - } - - return matches -} - -func (m *ReferenceMap) mapKey(path addrs.ModuleInstance, addr addrs.Referenceable) string { - return fmt.Sprintf("%s|%s", path.String(), addr.String()) -} - -// vertexReferenceablePath returns the path in which the given vertex can be -// referenced. This is the path that its results from ReferenceableAddrs -// are considered to be relative to. -// -// Only GraphNodeSubPath implementations can be referenced, so this method will -// panic if the given vertex does not implement that interface. -func (m *ReferenceMap) vertexReferenceablePath(v dag.Vertex) addrs.ModuleInstance { - sp, ok := v.(GraphNodeSubPath) - if !ok { - // Only nodes with paths can participate in a reference map. - panic(fmt.Errorf("vertexMapKey on vertex type %T which doesn't implement GraphNodeSubPath", sp)) - } - - if outside, ok := v.(GraphNodeReferenceOutside); ok { - // Vertex is referenced from a different module than where it was - // declared. - path, _ := outside.ReferenceOutside() - return path - } - - // Vertex is referenced from the same module as where it was declared. - return sp.Path() -} - -// vertexReferencePath returns the path in which references _from_ the given -// vertex must be interpreted. -// -// Only GraphNodeSubPath implementations can have references, so this method -// will panic if the given vertex does not implement that interface. -func vertexReferencePath(referrer dag.Vertex) addrs.ModuleInstance { - sp, ok := referrer.(GraphNodeSubPath) - if !ok { - // Only nodes with paths can participate in a reference map. - panic(fmt.Errorf("vertexReferencePath on vertex type %T which doesn't implement GraphNodeSubPath", sp)) - } - - var path addrs.ModuleInstance - if outside, ok := referrer.(GraphNodeReferenceOutside); ok { - // Vertex makes references to objects in a different module than where - // it was declared. - _, path = outside.ReferenceOutside() - return path - } - - // Vertex makes references to objects in the same module as where it - // was declared. - return sp.Path() -} - -// referenceMapKey produces keys for the "edges" map. "referrer" is the vertex -// that the reference is from, and "addr" is the address of the object being -// referenced. -// -// The result is an opaque string that includes both the address of the given -// object and the address of the module instance that object belongs to. -// -// Only GraphNodeSubPath implementations can be referrers, so this method will -// panic if the given vertex does not implement that interface. -func (m *ReferenceMap) referenceMapKey(referrer dag.Vertex, addr addrs.Referenceable) string { - path := vertexReferencePath(referrer) - return m.mapKey(path, addr) -} - -// NewReferenceMap is used to create a new reference map for the -// given set of vertices. -func NewReferenceMap(vs []dag.Vertex) *ReferenceMap { - var m ReferenceMap - - // Build the lookup table - vertices := make(map[string][]dag.Vertex) - for _, v := range vs { - _, ok := v.(GraphNodeSubPath) - if !ok { - // Only nodes with paths can participate in a reference map. - continue - } - - // We're only looking for referenceable nodes - rn, ok := v.(GraphNodeReferenceable) - if !ok { - continue - } - - path := m.vertexReferenceablePath(v) - - // Go through and cache them - for _, addr := range rn.ReferenceableAddrs() { - key := m.mapKey(path, addr) - vertices[key] = append(vertices[key], v) - } - - // Any node can be referenced by the address of the module it belongs - // to or any of that module's ancestors. - for _, addr := range path.Ancestors()[1:] { - // Can be referenced either as the specific call instance (with - // an instance key) or as the bare module call itself (the "module" - // block in the parent module that created the instance). - callPath, call := addr.Call() - callInstPath, callInst := addr.CallInstance() - callKey := m.mapKey(callPath, call) - callInstKey := m.mapKey(callInstPath, callInst) - vertices[callKey] = append(vertices[callKey], v) - vertices[callInstKey] = append(vertices[callInstKey], v) - } - } - - // Build the lookup table for referenced by - edges := make(map[string][]dag.Vertex) - for _, v := range vs { - _, ok := v.(GraphNodeSubPath) - if !ok { - // Only nodes with paths can participate in a reference map. - continue - } - - rn, ok := v.(GraphNodeReferencer) - if !ok { - // We're only looking for referenceable nodes - continue - } - - // Go through and cache them - for _, ref := range rn.References() { - if ref.Subject == nil { - // Should never happen - panic(fmt.Sprintf("%T.References returned reference with nil subject", rn)) - } - key := m.referenceMapKey(v, ref.Subject) - edges[key] = append(edges[key], v) - } - } - - m.vertices = vertices - m.edges = edges - return &m -} - -// ReferencesFromConfig returns the references that a configuration has -// based on the interpolated variables in a configuration. -func ReferencesFromConfig(body hcl.Body, schema *configschema.Block) []*addrs.Reference { - if body == nil { - return nil - } - refs, _ := lang.ReferencesInBlock(body, schema) - return refs -} - -// appendResourceDestroyReferences identifies resource and resource instance -// references in the given slice and appends to it the "destroy-phase" -// equivalents of those references, returning the result. -// -// This can be used in the References implementation for a node which must also -// depend on the destruction of anything it references. -func appendResourceDestroyReferences(refs []*addrs.Reference) []*addrs.Reference { - given := refs - for _, ref := range given { - switch tr := ref.Subject.(type) { - case addrs.Resource: - newRef := *ref // shallow copy - newRef.Subject = tr.Phase(addrs.ResourceInstancePhaseDestroy) - refs = append(refs, &newRef) - case addrs.ResourceInstance: - newRef := *ref // shallow copy - newRef.Subject = tr.Phase(addrs.ResourceInstancePhaseDestroy) - refs = append(refs, &newRef) - } - } - return refs -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_removed_modules.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_removed_modules.go deleted file mode 100644 index 327950d885f..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_removed_modules.go +++ /dev/null @@ -1,33 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// RemovedModuleTransformer implements GraphTransformer to add nodes indicating -// when a module was removed from the configuration. -type RemovedModuleTransformer struct { - Config *configs.Config // root node in the config tree - State *states.State -} - -func (t *RemovedModuleTransformer) Transform(g *Graph) error { - // nothing to remove if there's no state! - if t.State == nil { - return nil - } - - for _, m := range t.State.Modules { - cc := t.Config.DescendentForInstance(m.Addr) - if cc != nil { - continue - } - - log.Printf("[DEBUG] %s is no longer in configuration\n", m.Addr) - g.Add(&NodeModuleRemoved{Addr: m.Addr}) - } - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_resource_count.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_resource_count.go deleted file mode 100644 index 51d9466a2c1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_resource_count.go +++ /dev/null @@ -1,71 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - "github.com/zclconf/go-cty/cty" -) - -// ResourceCountTransformer is a GraphTransformer that expands the count -// out for a specific resource. -// -// This assumes that the count is already interpolated. -type ResourceCountTransformer struct { - Concrete ConcreteResourceInstanceNodeFunc - Schema *configschema.Block - - // Count is either the number of indexed instances to create, or -1 to - // indicate that count is not set at all and thus a no-key instance should - // be created. - Count int - ForEach map[string]cty.Value - Addr addrs.AbsResource -} - -func (t *ResourceCountTransformer) Transform(g *Graph) error { - if t.Count < 0 && t.ForEach == nil { - // Negative count indicates that count is not set at all. - addr := t.Addr.Instance(addrs.NoKey) - - abstract := NewNodeAbstractResourceInstance(addr) - abstract.Schema = t.Schema - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - - g.Add(node) - return nil - } - - // Add nodes related to the for_each expression - for key := range t.ForEach { - addr := t.Addr.Instance(addrs.StringKey(key)) - abstract := NewNodeAbstractResourceInstance(addr) - abstract.Schema = t.Schema - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - - g.Add(node) - } - - // For each count, build and add the node - for i := 0; i < t.Count; i++ { - key := addrs.IntKey(i) - addr := t.Addr.Instance(key) - - abstract := NewNodeAbstractResourceInstance(addr) - abstract.Schema = t.Schema - var node dag.Vertex = abstract - if f := t.Concrete; f != nil { - node = f(abstract) - } - - g.Add(node) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_root.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_root.go deleted file mode 100644 index 485c1c8a04b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_root.go +++ /dev/null @@ -1,38 +0,0 @@ -package terraform - -import "github.com/hashicorp/terraform-plugin-sdk/internal/dag" - -const rootNodeName = "root" - -// RootTransformer is a GraphTransformer that adds a root to the graph. -type RootTransformer struct{} - -func (t *RootTransformer) Transform(g *Graph) error { - // If we already have a good root, we're done - if _, err := g.Root(); err == nil { - return nil - } - - // Add a root - var root graphNodeRoot - g.Add(root) - - // Connect the root to all the edges that need it - for _, v := range g.Vertices() { - if v == root { - continue - } - - if g.UpEdges(v).Len() == 0 { - g.Connect(dag.BasicEdge(root, v)) - } - } - - return nil -} - -type graphNodeRoot struct{} - -func (n graphNodeRoot) Name() string { - return rootNodeName -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_state.go deleted file mode 100644 index e7d95be9780..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_state.go +++ /dev/null @@ -1,74 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/states" -) - -// StateTransformer is a GraphTransformer that adds the elements of -// the state to the graph. -// -// This transform is used for example by the DestroyPlanGraphBuilder to ensure -// that only resources that are in the state are represented in the graph. -type StateTransformer struct { - // ConcreteCurrent and ConcreteDeposed are used to specialize the abstract - // resource instance nodes that this transformer will create. - // - // If either of these is nil, the objects of that type will be skipped and - // not added to the graph at all. It doesn't make sense to use this - // transformer without setting at least one of these, since that would - // skip everything and thus be a no-op. - ConcreteCurrent ConcreteResourceInstanceNodeFunc - ConcreteDeposed ConcreteResourceInstanceDeposedNodeFunc - - State *states.State -} - -func (t *StateTransformer) Transform(g *Graph) error { - if !t.State.HasResources() { - log.Printf("[TRACE] StateTransformer: state is empty, so nothing to do") - return nil - } - - switch { - case t.ConcreteCurrent != nil && t.ConcreteDeposed != nil: - log.Printf("[TRACE] StateTransformer: creating nodes for both current and deposed instance objects") - case t.ConcreteCurrent != nil: - log.Printf("[TRACE] StateTransformer: creating nodes for current instance objects only") - case t.ConcreteDeposed != nil: - log.Printf("[TRACE] StateTransformer: creating nodes for deposed instance objects only") - default: - log.Printf("[TRACE] StateTransformer: pointless no-op call, creating no nodes at all") - } - - for _, ms := range t.State.Modules { - moduleAddr := ms.Addr - - for _, rs := range ms.Resources { - resourceAddr := rs.Addr.Absolute(moduleAddr) - - for key, is := range rs.Instances { - addr := resourceAddr.Instance(key) - - if obj := is.Current; obj != nil && t.ConcreteCurrent != nil { - abstract := NewNodeAbstractResourceInstance(addr) - node := t.ConcreteCurrent(abstract) - g.Add(node) - log.Printf("[TRACE] StateTransformer: added %T for %s current object", node, addr) - } - - if t.ConcreteDeposed != nil { - for dk := range is.Deposed { - abstract := NewNodeAbstractResourceInstance(addr) - node := t.ConcreteDeposed(abstract, dk) - g.Add(node) - log.Printf("[TRACE] StateTransformer: added %T for %s deposed object %s", node, addr, dk) - } - } - } - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_targets.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_targets.go deleted file mode 100644 index beb1eed9e3b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_targets.go +++ /dev/null @@ -1,267 +0,0 @@ -package terraform - -import ( - "log" - - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// GraphNodeTargetable is an interface for graph nodes to implement when they -// need to be told about incoming targets. This is useful for nodes that need -// to respect targets as they dynamically expand. Note that the list of targets -// provided will contain every target provided, and each implementing graph -// node must filter this list to targets considered relevant. -type GraphNodeTargetable interface { - SetTargets([]addrs.Targetable) -} - -// 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. -type TargetsTransformer struct { - // List of targeted resource names specified by the user - Targets []addrs.Targetable - - // If set, the index portions of resource addresses will be ignored - // for comparison. This is used when transforming a graph where - // counted resources have not yet been expanded, since otherwise - // the unexpanded nodes (which never have indices) would not match. - IgnoreIndices bool - - // Set to true when we're in a `terraform destroy` or a - // `terraform plan -destroy` - Destroy bool -} - -func (t *TargetsTransformer) Transform(g *Graph) error { - if len(t.Targets) > 0 { - targetedNodes, err := t.selectTargetedNodes(g, t.Targets) - if err != nil { - return err - } - - for _, v := range g.Vertices() { - removable := false - if _, ok := v.(GraphNodeResource); ok { - removable = true - } - - if vr, ok := v.(RemovableIfNotTargeted); ok { - removable = vr.RemoveIfNotTargeted() - } - - if removable && !targetedNodes.Include(v) { - log.Printf("[DEBUG] Removing %q, filtered by targeting.", dag.VertexName(v)) - g.Remove(v) - } - } - } - - return nil -} - -// Returns a set of targeted nodes. A targeted node is either addressed -// directly, address indirectly via its container, or it's a dependency of a -// targeted node. Destroy mode keeps dependents instead of dependencies. -func (t *TargetsTransformer) selectTargetedNodes(g *Graph, addrs []addrs.Targetable) (*dag.Set, error) { - targetedNodes := new(dag.Set) - - vertices := g.Vertices() - - for _, v := range vertices { - if t.nodeIsTarget(v, addrs) { - targetedNodes.Add(v) - - // We inform nodes that ask about the list of targets - helps for nodes - // that need to dynamically expand. Note that this only occurs for nodes - // that are already directly targeted. - if tn, ok := v.(GraphNodeTargetable); ok { - tn.SetTargets(addrs) - } - - var deps *dag.Set - var err error - if t.Destroy { - deps, err = g.Descendents(v) - } else { - deps, err = g.Ancestors(v) - } - if err != nil { - return nil, err - } - - for _, d := range deps.List() { - targetedNodes.Add(d) - } - } - } - return t.addDependencies(targetedNodes, g) -} - -func (t *TargetsTransformer) addDependencies(targetedNodes *dag.Set, g *Graph) (*dag.Set, error) { - // 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 { - // providers don't cause transitive dependencies, so don't target - // downstream from them. - if _, ok := v.(GraphNodeProvider); ok { - continue - } - - 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 { - _, 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.Filter(func(dv interface{}) bool { - return filterPartialOutputs(dv, targetedNodes, g) - }), nil -} - -// Outputs may have been included transitively, but if any of their -// dependencies have been pruned they won't be resolvable. -// If nothing depends on the output, and the output is missing any -// dependencies, remove it from the graph. -// This essentially maintains the previous behavior where interpolation in -// outputs would fail silently, but can now surface errors where the output -// is required. -func filterPartialOutputs(v interface{}, targetedNodes *dag.Set, g *Graph) bool { - // should this just be done with TargetDownstream? - if _, ok := v.(*NodeApplyableOutput); !ok { - return true - } - - dependers := g.UpEdges(v) - for _, d := range dependers.List() { - if _, ok := d.(*NodeCountBoundary); ok { - continue - } - - if !targetedNodes.Include(d) { - // this one is going to be removed, so it doesn't count - continue - } - - // as soon as we see a real dependency, we mark this as - // non-removable - return true - } - - depends := g.DownEdges(v) - - for _, d := range depends.List() { - if !targetedNodes.Include(d) { - log.Printf("[WARN] %s missing targeted dependency %s, removing from the graph", - dag.VertexName(v), dag.VertexName(d)) - return false - } - } - return true -} - -func (t *TargetsTransformer) nodeIsTarget(v dag.Vertex, targets []addrs.Targetable) bool { - var vertexAddr addrs.Targetable - switch r := v.(type) { - case GraphNodeResourceInstance: - vertexAddr = r.ResourceInstanceAddr() - case GraphNodeResource: - vertexAddr = r.ResourceAddr() - default: - // Only resource and resource instance nodes can be targeted. - return false - } - _, ok := v.(GraphNodeResource) - if !ok { - return false - } - - for _, targetAddr := range targets { - if t.IgnoreIndices { - // If we're ignoring indices then we'll convert any resource instance - // addresses into resource addresses. We don't need to convert - // vertexAddr because instance addresses are contained within - // their associated resources, and so .TargetContains will take - // care of this for us. - if instance, isInstance := targetAddr.(addrs.AbsResourceInstance); isInstance { - targetAddr = instance.ContainingResource() - } - } - if targetAddr.TargetContains(vertexAddr) { - return true - } - } - - return false -} - -// RemovableIfNotTargeted is a special interface for graph nodes that -// aren't directly addressable, but need to be removed from the graph when they -// are not targeted. (Nodes that are not directly targeted end up in the set of -// targeted nodes because something that _is_ targeted depends on them.) The -// initial use case for this interface is GraphNodeConfigVariable, which was -// having trouble interpolating for module variables in targeted scenarios that -// filtered out the resource node being referenced. -type RemovableIfNotTargeted interface { - RemoveIfNotTargeted() bool -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_transitive_reduction.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_transitive_reduction.go deleted file mode 100644 index 21842789cf7..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_transitive_reduction.go +++ /dev/null @@ -1,20 +0,0 @@ -package terraform - -// TransitiveReductionTransformer is a GraphTransformer that performs -// finds the transitive reduction of the graph. For a definition of -// transitive reduction, see Wikipedia. -type TransitiveReductionTransformer struct{} - -func (t *TransitiveReductionTransformer) Transform(g *Graph) error { - // If the graph isn't valid, skip the transitive reduction. - // We don't error here because Terraform itself handles graph - // validation in a better way, or we assume it does. - if err := g.Validate(); err != nil { - return nil - } - - // Do it - g.TransitiveReduction() - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_variable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_variable.go deleted file mode 100644 index 3afce566086..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_variable.go +++ /dev/null @@ -1,40 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" -) - -// RootVariableTransformer is a GraphTransformer that adds all the root -// variables to the graph. -// -// Root variables are currently no-ops but they must be added to the -// graph since downstream things that depend on them must be able to -// reach them. -type RootVariableTransformer struct { - Config *configs.Config -} - -func (t *RootVariableTransformer) Transform(g *Graph) error { - // We can have no variables if we have no config. - if t.Config == nil { - return nil - } - - // We're only considering root module variables here, since child - // module variables are handled by ModuleVariableTransformer. - vars := t.Config.Module.Variables - - // Add all variables here - for _, v := range vars { - node := &NodeRootVariable{ - Addr: addrs.InputVariable{ - Name: v.Name, - }, - Config: v, - } - g.Add(node) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_vertex.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_vertex.go deleted file mode 100644 index 6b3c62d1f30..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_vertex.go +++ /dev/null @@ -1,44 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/internal/dag" -) - -// VertexTransformer is a GraphTransformer that transforms vertices -// using the GraphVertexTransformers. The Transforms are run in sequential -// order. If a transform replaces a vertex then the next transform will see -// the new vertex. -type VertexTransformer struct { - Transforms []GraphVertexTransformer -} - -func (t *VertexTransformer) Transform(g *Graph) error { - for _, v := range g.Vertices() { - for _, vt := range t.Transforms { - newV, err := vt.Transform(v) - if err != nil { - return err - } - - // If the vertex didn't change, then don't do anything more - if newV == v { - continue - } - - // Vertex changed, replace it within the graph - if ok := g.Replace(v, newV); !ok { - // This should never happen, big problem - return fmt.Errorf( - "Failed to replace %s with %s!\n\nSource: %#v\n\nTarget: %#v", - dag.VertexName(v), dag.VertexName(newV), v, newV) - } - - // Replace v so that future transforms use the proper vertex - v = newV - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_input.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_input.go deleted file mode 100644 index f6790d9e5f3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_input.go +++ /dev/null @@ -1,28 +0,0 @@ -package terraform - -import "context" - -// UIInput is the interface that must be implemented to ask for input -// from this user. This should forward the request to wherever the user -// inputs things to ask for values. -type UIInput interface { - Input(context.Context, *InputOpts) (string, error) -} - -// InputOpts are options for asking for input. -type InputOpts struct { - // Id is a unique ID for the question being asked that might be - // used for logging or to look up a prior answered question. - Id string - - // Query is a human-friendly question for inputting this value. - Query string - - // Description is a description about what this option is. Be wary - // that this will probably be in a terminal so split lines as you see - // necessary. - Description string - - // Default will be the value returned if no data is entered. - Default string -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_input_mock.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_input_mock.go deleted file mode 100644 index e2d9c384819..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_input_mock.go +++ /dev/null @@ -1,25 +0,0 @@ -package terraform - -import "context" - -// MockUIInput is an implementation of UIInput that can be used for tests. -type MockUIInput struct { - InputCalled bool - InputOpts *InputOpts - InputReturnMap map[string]string - InputReturnString string - InputReturnError error - InputFn func(*InputOpts) (string, error) -} - -func (i *MockUIInput) Input(ctx context.Context, opts *InputOpts) (string, error) { - i.InputCalled = true - i.InputOpts = opts - if i.InputFn != nil { - return i.InputFn(opts) - } - if i.InputReturnMap != nil { - return i.InputReturnMap[opts.Id], i.InputReturnError - } - return i.InputReturnString, i.InputReturnError -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_input_prefix.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_input_prefix.go deleted file mode 100644 index b5d32b1e85d..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_input_prefix.go +++ /dev/null @@ -1,20 +0,0 @@ -package terraform - -import ( - "context" - "fmt" -) - -// PrefixUIInput is an implementation of UIInput that prefixes the ID -// with a string, allowing queries to be namespaced. -type PrefixUIInput struct { - IdPrefix string - QueryPrefix string - UIInput UIInput -} - -func (i *PrefixUIInput) Input(ctx context.Context, opts *InputOpts) (string, error) { - opts.Id = fmt.Sprintf("%s.%s", i.IdPrefix, opts.Id) - opts.Query = fmt.Sprintf("%s%s", i.QueryPrefix, opts.Query) - return i.UIInput.Input(ctx, opts) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output.go deleted file mode 100644 index 84427c63de1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output.go +++ /dev/null @@ -1,7 +0,0 @@ -package terraform - -// UIOutput is the interface that must be implemented to output -// data to the end user. -type UIOutput interface { - Output(string) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output_callback.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output_callback.go deleted file mode 100644 index 135a91c5f0a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output_callback.go +++ /dev/null @@ -1,9 +0,0 @@ -package terraform - -type CallbackUIOutput struct { - OutputFn func(string) -} - -func (o *CallbackUIOutput) Output(v string) { - o.OutputFn(v) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output_mock.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output_mock.go deleted file mode 100644 index d828c921ca3..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output_mock.go +++ /dev/null @@ -1,21 +0,0 @@ -package terraform - -import "sync" - -// MockUIOutput is an implementation of UIOutput that can be used for tests. -type MockUIOutput struct { - sync.Mutex - OutputCalled bool - OutputMessage string - OutputFn func(string) -} - -func (o *MockUIOutput) Output(v string) { - o.Lock() - defer o.Unlock() - o.OutputCalled = true - o.OutputMessage = v - if o.OutputFn != nil { - o.OutputFn(v) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output_provisioner.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output_provisioner.go deleted file mode 100644 index 0d7d4ce032c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/ui_output_provisioner.go +++ /dev/null @@ -1,19 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" -) - -// ProvisionerUIOutput is an implementation of UIOutput that calls a hook -// for the output so that the hooks can handle it. -type ProvisionerUIOutput struct { - InstanceAddr addrs.AbsResourceInstance - ProvisionerType string - Hooks []Hook -} - -func (o *ProvisionerUIOutput) Output(msg string) { - for _, h := range o.Hooks { - h.ProvisionOutput(o.InstanceAddr, o.ProvisionerType, msg) - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/util.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/util.go deleted file mode 100644 index 5428cd5a0a1..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/util.go +++ /dev/null @@ -1,75 +0,0 @@ -package terraform - -import ( - "sort" -) - -// Semaphore is a wrapper around a channel to provide -// utility methods to clarify that we are treating the -// channel as a semaphore -type Semaphore chan struct{} - -// NewSemaphore creates a semaphore that allows up -// to a given limit of simultaneous acquisitions -func NewSemaphore(n int) Semaphore { - if n == 0 { - panic("semaphore with limit 0") - } - ch := make(chan struct{}, n) - return Semaphore(ch) -} - -// Acquire is used to acquire an available slot. -// Blocks until available. -func (s Semaphore) Acquire() { - s <- struct{}{} -} - -// TryAcquire is used to do a non-blocking acquire. -// Returns a bool indicating success -func (s Semaphore) TryAcquire() bool { - select { - case s <- struct{}{}: - return true - default: - return false - } -} - -// Release is used to return a slot. Acquire must -// be called as a pre-condition. -func (s Semaphore) Release() { - select { - case <-s: - default: - panic("release without an acquire") - } -} - -// strSliceContains checks if a given string is contained in a slice -// When anybody asks why Go needs generics, here you go. -func strSliceContains(haystack []string, needle string) bool { - for _, s := range haystack { - if s == needle { - return true - } - } - 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/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/valuesourcetype_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/valuesourcetype_string.go deleted file mode 100644 index 627593d762b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/valuesourcetype_string.go +++ /dev/null @@ -1,59 +0,0 @@ -// Code generated by "stringer -type ValueSourceType"; DO NOT EDIT. - -package terraform - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[ValueFromUnknown-0] - _ = x[ValueFromConfig-67] - _ = x[ValueFromAutoFile-70] - _ = x[ValueFromNamedFile-78] - _ = x[ValueFromCLIArg-65] - _ = x[ValueFromEnvVar-69] - _ = x[ValueFromInput-73] - _ = x[ValueFromPlan-80] - _ = x[ValueFromCaller-83] -} - -const ( - _ValueSourceType_name_0 = "ValueFromUnknown" - _ValueSourceType_name_1 = "ValueFromCLIArg" - _ValueSourceType_name_2 = "ValueFromConfig" - _ValueSourceType_name_3 = "ValueFromEnvVarValueFromAutoFile" - _ValueSourceType_name_4 = "ValueFromInput" - _ValueSourceType_name_5 = "ValueFromNamedFile" - _ValueSourceType_name_6 = "ValueFromPlan" - _ValueSourceType_name_7 = "ValueFromCaller" -) - -var ( - _ValueSourceType_index_3 = [...]uint8{0, 15, 32} -) - -func (i ValueSourceType) String() string { - switch { - case i == 0: - return _ValueSourceType_name_0 - case i == 65: - return _ValueSourceType_name_1 - case i == 67: - return _ValueSourceType_name_2 - case 69 <= i && i <= 70: - i -= 69 - return _ValueSourceType_name_3[_ValueSourceType_index_3[i]:_ValueSourceType_index_3[i+1]] - case i == 73: - return _ValueSourceType_name_4 - case i == 78: - return _ValueSourceType_name_5 - case i == 80: - return _ValueSourceType_name_6 - case i == 83: - return _ValueSourceType_name_7 - default: - return "ValueSourceType(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/variables.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/variables.go deleted file mode 100644 index 4ae9c92cfc5..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/variables.go +++ /dev/null @@ -1,313 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" -) - -// InputValue represents a value for a variable in the root module, provided -// as part of the definition of an operation. -type InputValue struct { - Value cty.Value - SourceType ValueSourceType - - // SourceRange provides source location information for values whose - // SourceType is either ValueFromConfig or ValueFromFile. It is not - // populated for other source types, and so should not be used. - SourceRange tfdiags.SourceRange -} - -// ValueSourceType describes what broad category of source location provided -// a particular value. -type ValueSourceType rune - -const ( - // ValueFromUnknown is the zero value of ValueSourceType and is not valid. - ValueFromUnknown ValueSourceType = 0 - - // ValueFromConfig indicates that a value came from a .tf or .tf.json file, - // e.g. the default value defined for a variable. - ValueFromConfig ValueSourceType = 'C' - - // ValueFromAutoFile indicates that a value came from a "values file", like - // a .tfvars file, that was implicitly loaded by naming convention. - ValueFromAutoFile ValueSourceType = 'F' - - // ValueFromNamedFile indicates that a value came from a named "values file", - // like a .tfvars file, that was passed explicitly on the command line (e.g. - // -var-file=foo.tfvars). - ValueFromNamedFile ValueSourceType = 'N' - - // ValueFromCLIArg indicates that the value was provided directly in - // a CLI argument. The name of this argument is not recorded and so it must - // be inferred from context. - ValueFromCLIArg ValueSourceType = 'A' - - // ValueFromEnvVar indicates that the value was provided via an environment - // variable. The name of the variable is not recorded and so it must be - // inferred from context. - ValueFromEnvVar ValueSourceType = 'E' - - // ValueFromInput indicates that the value was provided at an interactive - // input prompt. - ValueFromInput ValueSourceType = 'I' - - // ValueFromPlan indicates that the value was retrieved from a stored plan. - ValueFromPlan ValueSourceType = 'P' - - // ValueFromCaller indicates that the value was explicitly overridden by - // a caller to Context.SetVariable after the context was constructed. - ValueFromCaller ValueSourceType = 'S' -) - -func (v *InputValue) GoString() string { - if (v.SourceRange != tfdiags.SourceRange{}) { - return fmt.Sprintf("&terraform.InputValue{Value: %#v, SourceType: %#v, SourceRange: %#v}", v.Value, v.SourceType, v.SourceRange) - } else { - return fmt.Sprintf("&terraform.InputValue{Value: %#v, SourceType: %#v}", v.Value, v.SourceType) - } -} - -func (v ValueSourceType) GoString() string { - return fmt.Sprintf("terraform.%s", v) -} - -//go:generate go run golang.org/x/tools/cmd/stringer -type ValueSourceType - -// InputValues is a map of InputValue instances. -type InputValues map[string]*InputValue - -// InputValuesFromCaller turns the given map of naked values into an -// InputValues that attributes each value to "a caller", using the source -// type ValueFromCaller. This is primarily useful for testing purposes. -// -// This should not be used as a general way to convert map[string]cty.Value -// into InputValues, since in most real cases we want to set a suitable -// other SourceType and possibly SourceRange value. -func InputValuesFromCaller(vals map[string]cty.Value) InputValues { - ret := make(InputValues, len(vals)) - for k, v := range vals { - ret[k] = &InputValue{ - Value: v, - SourceType: ValueFromCaller, - } - } - return ret -} - -// Override merges the given value maps with the receiver, overriding any -// conflicting keys so that the latest definition wins. -func (vv InputValues) Override(others ...InputValues) InputValues { - // FIXME: This should check to see if any of the values are maps and - // merge them if so, in order to preserve the behavior from prior to - // Terraform 0.12. - ret := make(InputValues) - for k, v := range vv { - ret[k] = v - } - for _, other := range others { - for k, v := range other { - ret[k] = v - } - } - return ret -} - -// JustValues returns a map that just includes the values, discarding the -// source information. -func (vv InputValues) JustValues() map[string]cty.Value { - ret := make(map[string]cty.Value, len(vv)) - for k, v := range vv { - ret[k] = v.Value - } - return ret -} - -// DefaultVariableValues returns an InputValues map representing the default -// values specified for variables in the given configuration map. -func DefaultVariableValues(configs map[string]*configs.Variable) InputValues { - ret := make(InputValues) - for k, c := range configs { - if c.Default == cty.NilVal { - continue - } - ret[k] = &InputValue{ - Value: c.Default, - SourceType: ValueFromConfig, - SourceRange: tfdiags.SourceRangeFromHCL(c.DeclRange), - } - } - return ret -} - -// SameValues returns true if the given InputValues has the same values as -// the receiever, disregarding the source types and source ranges. -// -// Values are compared using the cty "RawEquals" method, which means that -// unknown values can be considered equal to one another if they are of the -// same type. -func (vv InputValues) SameValues(other InputValues) bool { - if len(vv) != len(other) { - return false - } - - for k, v := range vv { - ov, exists := other[k] - if !exists { - return false - } - if !v.Value.RawEquals(ov.Value) { - return false - } - } - - return true -} - -// HasValues returns true if the reciever has the same values as in the given -// map, disregarding the source types and source ranges. -// -// Values are compared using the cty "RawEquals" method, which means that -// unknown values can be considered equal to one another if they are of the -// same type. -func (vv InputValues) HasValues(vals map[string]cty.Value) bool { - if len(vv) != len(vals) { - return false - } - - for k, v := range vv { - oVal, exists := vals[k] - if !exists { - return false - } - if !v.Value.RawEquals(oVal) { - return false - } - } - - return true -} - -// Identical returns true if the given InputValues has the same values, -// source types, and source ranges as the receiver. -// -// Values are compared using the cty "RawEquals" method, which means that -// unknown values can be considered equal to one another if they are of the -// same type. -// -// This method is primarily for testing. For most practical purposes, it's -// better to use SameValues or HasValues. -func (vv InputValues) Identical(other InputValues) bool { - if len(vv) != len(other) { - return false - } - - for k, v := range vv { - ov, exists := other[k] - if !exists { - return false - } - if !v.Value.RawEquals(ov.Value) { - return false - } - if v.SourceType != ov.SourceType { - return false - } - if v.SourceRange != ov.SourceRange { - return false - } - } - - return true -} - -// checkInputVariables ensures that variable values supplied at the UI conform -// to their corresponding declarations in configuration. -// -// The set of values is considered valid only if the returned diagnostics -// does not contain errors. A valid set of values may still produce warnings, -// which should be returned to the user. -func checkInputVariables(vcs map[string]*configs.Variable, vs InputValues) tfdiags.Diagnostics { - var diags tfdiags.Diagnostics - - for name, vc := range vcs { - val, isSet := vs[name] - if !isSet { - // Always an error, since the caller should already have included - // default values from the configuration in the values map. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Unassigned variable", - fmt.Sprintf("The input variable %q has not been assigned a value. This is a bug in Terraform; please report it in a GitHub issue.", name), - )) - continue - } - - wantType := vc.Type - - // A given value is valid if it can convert to the desired type. - _, err := convert.Convert(val.Value, wantType) - if err != nil { - switch val.SourceType { - case ValueFromConfig, ValueFromAutoFile, ValueFromNamedFile: - // We have source location information for these. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid value for input variable", - Detail: fmt.Sprintf("The given value is not valid for variable %q: %s.", name, err), - Subject: val.SourceRange.ToHCL().Ptr(), - }) - case ValueFromEnvVar: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid value for input variable", - fmt.Sprintf("The environment variable TF_VAR_%s does not contain a valid value for variable %q: %s.", name, name, err), - )) - case ValueFromCLIArg: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid value for input variable", - fmt.Sprintf("The argument -var=\"%s=...\" does not contain a valid value for variable %q: %s.", name, name, err), - )) - case ValueFromInput: - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid value for input variable", - fmt.Sprintf("The value entered for variable %q is not valid: %s.", name, err), - )) - default: - // The above gets us good coverage for the situations users - // are likely to encounter with their own inputs. The other - // cases are generally implementation bugs, so we'll just - // use a generic error for these. - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Invalid value for input variable", - fmt.Sprintf("The value provided for variable %q is not valid: %s.", name, err), - )) - } - } - } - - // Check for any variables that are assigned without being configured. - // This is always an implementation error in the caller, because we - // expect undefined variables to be caught during context construction - // where there is better context to report it well. - for name := range vs { - if _, defined := vcs[name]; !defined { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Value assigned to undeclared variable", - fmt.Sprintf("A value was assigned to an undeclared input variable %q.", name), - )) - } - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/version_required.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/version_required.go deleted file mode 100644 index 4cc3bbba6a6..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/version_required.go +++ /dev/null @@ -1,62 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" - - "github.com/hashicorp/terraform-plugin-sdk/internal/configs" - - tfversion "github.com/hashicorp/terraform-plugin-sdk/internal/version" -) - -// CheckCoreVersionRequirements visits each of the modules in the given -// configuration tree and verifies that any given Core version constraints -// match with the version of Terraform Core that is being used. -// -// The returned diagnostics will contain errors if any constraints do not match. -// The returned diagnostics might also return warnings, which should be -// displayed to the user. -func CheckCoreVersionRequirements(config *configs.Config) tfdiags.Diagnostics { - if config == nil { - return nil - } - - var diags tfdiags.Diagnostics - module := config.Module - - for _, constraint := range module.CoreVersionConstraints { - if !constraint.Required.Check(tfversion.SemVer) { - switch { - case len(config.Path) == 0: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported Terraform Core version", - Detail: fmt.Sprintf( - "This configuration does not support Terraform version %s. To proceed, either choose another supported Terraform version or update this version constraint. Version constraints are normally set for good reason, so updating the constraint may lead to other errors or unexpected behavior.", - tfversion.String(), - ), - Subject: &constraint.DeclRange, - }) - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsupported Terraform Core version", - Detail: fmt.Sprintf( - "Module %s (from %s) does not support Terraform version %s. To proceed, either choose another supported Terraform version or update this version constraint. Version constraints are normally set for good reason, so updating the constraint may lead to other errors or unexpected behavior.", - config.Path, config.SourceAddr, tfversion.String(), - ), - Subject: &constraint.DeclRange, - }) - } - } - } - - for _, c := range config.Children { - childDiags := CheckCoreVersionRequirements(c) - diags = diags.Append(childDiags) - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/walkoperation_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/walkoperation_string.go deleted file mode 100644 index 0666aa5f3ff..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/walkoperation_string.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by "stringer -type=walkOperation graph_walk_operation.go"; DO NOT EDIT. - -package terraform - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[walkInvalid-0] - _ = x[walkApply-1] - _ = x[walkPlan-2] - _ = x[walkPlanDestroy-3] - _ = x[walkRefresh-4] - _ = x[walkValidate-5] - _ = x[walkDestroy-6] - _ = x[walkImport-7] - _ = x[walkEval-8] -} - -const _walkOperation_name = "walkInvalidwalkApplywalkPlanwalkPlanDestroywalkRefreshwalkValidatewalkDestroywalkImportwalkEval" - -var _walkOperation_index = [...]uint8{0, 11, 20, 28, 43, 54, 66, 77, 87, 95} - -func (i walkOperation) String() string { - if i >= walkOperation(len(_walkOperation_index)-1) { - return "walkOperation(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _walkOperation_name[_walkOperation_index[i]:_walkOperation_index[i+1]] -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/LICENSE b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/LICENSE new file mode 100644 index 00000000000..c33dcc7c928 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/LICENSE @@ -0,0 +1,354 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. “Contributor” + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. “Contributor Version” + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor’s Contribution. + +1.3. “Contribution” + + means Covered Software of a particular Contributor. + +1.4. “Covered Software” + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. “Incompatible With Secondary Licenses” + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of version + 1.1 or earlier of the License, but not also under the terms of a + Secondary License. + +1.6. “Executable Form” + + means any form of the work other than Source Code Form. + +1.7. “Larger Work” + + means a work that combines Covered Software with other material, in a separate + file or files, that is not Covered Software. + +1.8. “License” + + means this document. + +1.9. “Licensable” + + means having the right to grant, to the maximum extent possible, whether at the + time of the initial grant or subsequently, any and all of the rights conveyed by + this License. + +1.10. “Modifications” + + means any of the following: + + a. any file in Source Code Form that results from an addition to, deletion + from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. “Patent Claims” of a Contributor + + means any patent claim(s), including without limitation, method, process, + and apparatus claims, in any patent Licensable by such Contributor that + would be infringed, but for the grant of the License, by the making, + using, selling, offering for sale, having made, import, or transfer of + either its Contributions or its Contributor Version. + +1.12. “Secondary License” + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. “Source Code Form” + + means the form of the work preferred for making modifications. + +1.14. “You” (or “Your”) + + means an individual or a legal entity exercising rights under this + License. For legal entities, “You” includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, “control” means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or as + part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its Contributions + or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution become + effective for each Contribution on the date the Contributor first distributes + such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under this + License. No additional rights or licenses will be implied from the distribution + or licensing of Covered Software under this License. Notwithstanding Section + 2.1(b) above, no patent license is granted by a Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party’s + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of its + Contributions. + + This License does not grant any rights in the trademarks, service marks, or + logos of any Contributor (except as may be necessary to comply with the + notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this License + (see Section 10.2) or under the terms of a Secondary License (if permitted + under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its Contributions + are its original creation(s) or it has sufficient rights to grant the + rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under applicable + copyright doctrines of fair use, fair dealing, or other equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under the + terms of this License. You must inform recipients that the Source Code Form + of the Covered Software is governed by the terms of this License, and how + they can obtain a copy of this License. You may not attempt to alter or + restrict the recipients’ rights in the Source Code Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this License, + or sublicense it under different terms, provided that the license for + the Executable Form does not attempt to limit or alter the recipients’ + rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for the + Covered Software. If the Larger Work is a combination of Covered Software + with a work governed by one or more Secondary Licenses, and the Covered + Software is not Incompatible With Secondary Licenses, this License permits + You to additionally distribute such Covered Software under the terms of + such Secondary License(s), so that the recipient of the Larger Work may, at + their option, further distribute the Covered Software under the terms of + either this License or such Secondary License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices (including + copyright notices, patent notices, disclaimers of warranty, or limitations + of liability) contained within the Source Code Form of the Covered + Software, except that You may alter any license notices to the extent + required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on behalf + of any Contributor. You must make it absolutely clear that any such + warranty, support, indemnity, or liability obligation is offered by You + alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, judicial + order, or regulation then You must: (a) comply with the terms of this License + to the maximum extent possible; and (b) describe the limitations and the code + they affect. Such description must be placed in a text file included with all + distributions of the Covered Software under this License. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing basis, + if such Contributor fails to notify You of the non-compliance by some + reasonable means prior to 60 days after You have come back into compliance. + Moreover, Your grants from a particular Contributor are reinstated on an + ongoing basis if such Contributor notifies You of the non-compliance by + some reasonable means, this is the first time You have received notice of + non-compliance with this License from such Contributor, and You become + compliant prior to 30 days after Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, counter-claims, + and cross-claims) alleging that a Contributor Version directly or + indirectly infringes any patent, then the rights granted to You by any and + all Contributors for the Covered Software under Section 2.1 of this License + shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an “as is” basis, without + warranty of any kind, either expressed, implied, or statutory, including, + without limitation, warranties that the Covered Software is free of defects, + merchantable, fit for a particular purpose or non-infringing. The entire + risk as to the quality and performance of the Covered Software is with You. + Should any Covered Software prove defective in any respect, You (not any + Contributor) assume the cost of any necessary servicing, repair, or + correction. This disclaimer of warranty constitutes an essential part of this + License. No use of any Covered Software is authorized under this License + except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from such + party’s negligence to the extent applicable law prohibits such limitation. + Some jurisdictions do not allow the exclusion or limitation of incidental or + consequential damages, so this exclusion and limitation may not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts of + a jurisdiction where the defendant maintains its principal place of business + and such litigation shall be governed by laws of that jurisdiction, without + reference to its conflict-of-law provisions. Nothing in this Section shall + prevent a party’s ability to bring cross-claims or counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject matter + hereof. If any provision of this License is held to be unenforceable, such + provision shall be reformed only to the extent necessary to make it + enforceable. Any law or regulation which provides that the language of a + contract shall be construed against the drafter shall not be used to construe + this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version of + the License under which You originally received the Covered Software, or + under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a modified + version of this License if you rename the license and remove any + references to the name of the license steward (except to note that such + modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + If You choose to distribute Source Code Form that is Incompatible With + Secondary Licenses under the terms of this version of the License, the + notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then +You may include the notice in a location (such as a LICENSE file in a relevant +directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - “Incompatible With Secondary Licenses” Notice + + This Source Code Form is “Incompatible + With Secondary Licenses”, as defined by + the Mozilla Public License, v. 2.0. + diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/diag/diagnostic.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/diag/diagnostic.go new file mode 100644 index 00000000000..3b1ced344f5 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/diag/diagnostic.go @@ -0,0 +1,104 @@ +package diag + +import ( + "errors" + "fmt" + + "github.com/hashicorp/go-cty/cty" +) + +// Diagnostics is a collection of Diagnostic. +// +// Developers should append and build the list of diagnostics up until a fatal +// error is reached, at which point they should return the Diagnostics to the +// SDK. +type Diagnostics []Diagnostic + +// HasError returns true is Diagnostics contains an instance of +// Severity == Error. +// +// This helper aims to mimic the go error practices of if err != nil. After any +// operation that returns Diagnostics, check that it HasError and bubble up the +// stack. +func (diags Diagnostics) HasError() bool { + for i := range diags { + if diags[i].Severity == Error { + return true + } + } + return false +} + +// Diagnostic is a contextual message intended at outlining problems in user +// configuration. +// +// It supports multiple levels of severity (Error or Warning), a short Summary +// of the problem, an optional longer Detail message that can assist the user in +// fixing the problem, as well as an AttributePath representation which +// Terraform uses to indicate where the issue took place in the user's +// configuration. +// +// A Diagnostic will typically be used to pinpoint a problem with user +// configuration, however it can still be used to present warnings or errors +// to the user without any AttributePath set. +type Diagnostic struct { + // Severity indicates the level of the Diagnostic. Currently can be set to + // either Error or Warning + Severity Severity + + // Summary is a short description of the problem, rendered above location + // information + Summary string + + // Detail is an optional second message rendered below location information + // typically used to communicate a potential fix to the user. + Detail string + + // AttributePath is a representation of the path starting from the root of + // block (resource, datasource, provider) under evaluation by the SDK, to + // the attribute that the Diagnostic should be associated to. Terraform will + // use this information to render information on where the problem took + // place in the user's configuration. + // + // It is represented with cty.Path, which is a list of steps of either + // cty.GetAttrStep (an actual attribute) or cty.IndexStep (a step with Key + // of cty.StringVal for map indexes, and cty.NumberVal for list indexes). + // + // PLEASE NOTE: While cty can support indexing into sets, the SDK and + // protocol currently do not. For any Diagnostic related to a schema.TypeSet + // or a child of that type, please terminate the path at the schema.TypeSet + // and opt for more verbose Summary and Detail to help guide the user. + // + // Validity of the AttributePath is currently the responsibility of the + // developer, Terraform should render the root block (provider, resource, + // datasource) in cases where the attribute path is invalid. + AttributePath cty.Path +} + +// Validate ensures a valid Severity and a non-empty Summary are set. +func (d Diagnostic) Validate() error { + var validSev bool + for _, sev := range severities { + if d.Severity == sev { + validSev = true + break + } + } + if !validSev { + return fmt.Errorf("invalid severity: %v", d.Severity) + } + if d.Summary == "" { + return errors.New("empty summary") + } + return nil +} + +// Severity is an enum type marking the severity level of a Diagnostic +type Severity int + +const ( + Error Severity = iota + Warning +) + +var severities = []Severity{Error, Warning} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/diag/helpers.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/diag/helpers.go new file mode 100644 index 00000000000..8037b1301e5 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/diag/helpers.go @@ -0,0 +1,36 @@ +package diag + +import "fmt" + +// FromErr will convert an error into a Diagnostics. This returns Diagnostics +// as the most common use case in Go will be handling a single error +// returned from a function. +// +// if err != nil { +// return diag.FromErr(err) +// } +func FromErr(err error) Diagnostics { + return Diagnostics{ + Diagnostic{ + Severity: Error, + Summary: err.Error(), + }, + } +} + +// Errorf creates a Diagnostics with a single Error level Diagnostic entry. +// The summary is populated by performing a fmt.Sprintf with the supplied +// values. This returns a single error in a Diagnostics as errors typically +// do not occur in multiples as warnings may. +// +// if unexpectedCondition { +// return diag.Errorf("unexpected: %s", someValue) +// } +func Errorf(format string, a ...interface{}) Diagnostics { + return Diagnostics{ + Diagnostic{ + Severity: Error, + Summary: fmt.Sprintf(format, a...), + }, + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/acctest/random.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest/random.go similarity index 97% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/acctest/random.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest/random.go index 258e4db70fd..9742275624e 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/acctest/random.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest/random.go @@ -14,9 +14,8 @@ import ( "strings" "time" - "golang.org/x/crypto/ssh" - "github.com/apparentlymart/go-cidr/cidr" + "golang.org/x/crypto/ssh" ) func init() { @@ -37,11 +36,12 @@ func RandomWithPrefix(name string) string { return fmt.Sprintf("%s-%d", name, rand.New(rand.NewSource(time.Now().UnixNano())).Int()) } +// RandIntRange returns a random integer between min (inclusive) and max (exclusive) func RandIntRange(min int, max int) int { source := rand.New(rand.NewSource(time.Now().UnixNano())) rangeMax := max - min - return int(source.Int31n(int32(rangeMax))) + return int(source.Int31n(int32(rangeMax))) + min } // RandString generates a random alphanumeric string of the length specified diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/compose.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/compose.go similarity index 88% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/compose.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/compose.go index b09199953e8..9b1b929d0f9 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/compose.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/compose.go @@ -1,8 +1,11 @@ package customdiff import ( + "context" + "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // All returns a CustomizeDiffFunc that runs all of the given @@ -42,10 +45,10 @@ import ( // } // func All(funcs ...schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { - return func(d *schema.ResourceDiff, meta interface{}) error { + return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { var err error for _, f := range funcs { - thisErr := f(d, meta) + thisErr := f(ctx, d, meta) if thisErr != nil { err = multierror.Append(err, thisErr) } @@ -60,9 +63,9 @@ func All(funcs ...schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { // // If all functions succeed, the combined function also succeeds. func Sequence(funcs ...schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { - return func(d *schema.ResourceDiff, meta interface{}) error { + return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { for _, f := range funcs { - err := f(d, meta) + err := f(ctx, d, meta) if err != nil { return err } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/computed.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/computed.go new file mode 100644 index 00000000000..f47d11a4597 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/computed.go @@ -0,0 +1,18 @@ +package customdiff + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +// ComputedIf returns a CustomizeDiffFunc that sets the given key's new value +// as computed if the given condition function returns true. +func ComputedIf(key string, f ResourceConditionFunc) schema.CustomizeDiffFunc { + return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { + if f(ctx, d, meta) { + d.SetNewComputed(key) + } + return nil + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/condition.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/condition.go new file mode 100644 index 00000000000..e85cdc7aee6 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/condition.go @@ -0,0 +1,62 @@ +package customdiff + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +// ResourceConditionFunc is a function type that makes a boolean decision based +// on an entire resource diff. +type ResourceConditionFunc func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) bool + +// ValueChangeConditionFunc is a function type that makes a boolean decision +// by comparing two values. +type ValueChangeConditionFunc func(ctx context.Context, old, new, meta interface{}) bool + +// ValueConditionFunc is a function type that makes a boolean decision based +// on a given value. +type ValueConditionFunc func(ctx context.Context, value, meta interface{}) bool + +// If returns a CustomizeDiffFunc that calls the given condition +// function and then calls the given CustomizeDiffFunc only if the condition +// function returns true. +// +// This can be used to include conditional customizations when composing +// customizations using All and Sequence, but should generally be used only in +// simple scenarios. Prefer directly writing a CustomizeDiffFunc containing +// a conditional branch if the given CustomizeDiffFunc is already a +// locally-defined function, since this avoids obscuring the control flow. +func If(cond ResourceConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { + return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { + if cond(ctx, d, meta) { + return f(ctx, d, meta) + } + return nil + } +} + +// IfValueChange returns a CustomizeDiffFunc that calls the given condition +// function with the old and new values of the given key and then calls the +// given CustomizeDiffFunc only if the condition function returns true. +func IfValueChange(key string, cond ValueChangeConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { + return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { + old, new := d.GetChange(key) + if cond(ctx, old, new, meta) { + return f(ctx, d, meta) + } + return nil + } +} + +// IfValue returns a CustomizeDiffFunc that calls the given condition +// function with the new values of the given key and then calls the +// given CustomizeDiffFunc only if the condition function returns true. +func IfValue(key string, cond ValueConditionFunc, f schema.CustomizeDiffFunc) schema.CustomizeDiffFunc { + return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { + if cond(ctx, d.Get(key), meta) { + return f(ctx, d, meta) + } + return nil + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/doc.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/doc.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/doc.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/force_new.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/force_new.go similarity index 80% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/force_new.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/force_new.go index 26afa8cb697..0ffc0886f24 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/customdiff/force_new.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/force_new.go @@ -1,7 +1,9 @@ package customdiff import ( - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "context" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // ForceNewIf returns a CustomizeDiffFunc that flags the given key as @@ -11,8 +13,8 @@ import ( // values of the field compare equal, since no attribute diff is generated in // that case. func ForceNewIf(key string, f ResourceConditionFunc) schema.CustomizeDiffFunc { - return func(d *schema.ResourceDiff, meta interface{}) error { - if f(d, meta) { + return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { + if f(ctx, d, meta) { d.ForceNew(key) } return nil @@ -30,9 +32,9 @@ func ForceNewIf(key string, f ResourceConditionFunc) schema.CustomizeDiffFunc { // and explicit code in the common case where the decision can be made with // only the specific field value. func ForceNewIfChange(key string, f ValueChangeConditionFunc) schema.CustomizeDiffFunc { - return func(d *schema.ResourceDiff, meta interface{}) error { + return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { old, new := d.GetChange(key) - if f(old, new, meta) { + if f(ctx, old, new, meta) { d.ForceNew(key) } return nil diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/validate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/validate.go new file mode 100644 index 00000000000..5b88e5e0be8 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff/validate.go @@ -0,0 +1,40 @@ +package customdiff + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +// ValueChangeValidationFunc is a function type that validates the difference +// (or lack thereof) between two values, returning an error if the change +// is invalid. +type ValueChangeValidationFunc func(ctx context.Context, old, new, meta interface{}) error + +// ValueValidationFunc is a function type that validates a particular value, +// returning an error if the value is invalid. +type ValueValidationFunc func(ctx context.Context, value, meta interface{}) error + +// ValidateChange returns a CustomizeDiffFunc that applies the given validation +// function to the change for the given key, returning any error produced. +func ValidateChange(key string, f ValueChangeValidationFunc) schema.CustomizeDiffFunc { + return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { + old, new := d.GetChange(key) + return f(ctx, old, new, meta) + } +} + +// ValidateValue returns a CustomizeDiffFunc that applies the given validation +// function to value of the given key, returning any error produced. +// +// This should generally not be used since it is functionally equivalent to +// a validation function applied directly to the schema attribute in question, +// but is provided for situations where composing multiple CustomizeDiffFuncs +// together makes intent clearer than spreading that validation across the +// schema. +func ValidateValue(key string, f ValueValidationFunc) schema.CustomizeDiffFunc { + return func(ctx context.Context, d *schema.ResourceDiff, meta interface{}) error { + val := d.Get(key) + return f(ctx, val, meta) + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/logging.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/logging.go new file mode 100644 index 00000000000..546c5e1cfca --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/logging.go @@ -0,0 +1,116 @@ +package logging + +import ( + "fmt" + "io" + "io/ioutil" + "log" + "os" + "strings" + "syscall" + + "github.com/hashicorp/logutils" + testing "github.com/mitchellh/go-testing-interface" +) + +// These are the environmental variables that determine if we log, and if +// we log whether or not the log should go to a file. +const ( + EnvLog = "TF_LOG" // Set to True + EnvLogFile = "TF_LOG_PATH" // Set to a file + // EnvLogPathMask splits test log files by name. + EnvLogPathMask = "TF_LOG_PATH_MASK" +) + +var ValidLevels = []logutils.LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"} + +// LogOutput determines where we should send logs (if anywhere) and the log level. +func LogOutput(t testing.T) (logOutput io.Writer, err error) { + logOutput = ioutil.Discard + + logLevel := LogLevel() + if logLevel == "" { + return + } + + logOutput = os.Stderr + if logPath := os.Getenv(EnvLogFile); logPath != "" { + var err error + logOutput, err = os.OpenFile(logPath, syscall.O_CREAT|syscall.O_RDWR|syscall.O_APPEND, 0666) + if err != nil { + return nil, err + } + } + + if logPathMask := os.Getenv(EnvLogPathMask); logPathMask != "" { + // Escape special characters which may appear if we have subtests + testName := strings.Replace(t.Name(), "/", "__", -1) + + logPath := fmt.Sprintf(logPathMask, testName) + var err error + logOutput, err = os.OpenFile(logPath, syscall.O_CREAT|syscall.O_RDWR|syscall.O_APPEND, 0666) + if err != nil { + return nil, err + } + } + + // This was the default since the beginning + logOutput = &logutils.LevelFilter{ + Levels: ValidLevels, + MinLevel: logutils.LogLevel(logLevel), + Writer: logOutput, + } + + return +} + +// SetOutput checks for a log destination with LogOutput, and calls +// log.SetOutput with the result. If LogOutput returns nil, SetOutput uses +// ioutil.Discard. Any error from LogOutout is fatal. +func SetOutput(t testing.T) { + out, err := LogOutput(t) + if err != nil { + log.Fatal(err) + } + + if out == nil { + out = ioutil.Discard + } + + log.SetOutput(out) +} + +// LogLevel returns the current log level string based the environment vars +func LogLevel() string { + envLevel := os.Getenv(EnvLog) + if envLevel == "" { + return "" + } + + logLevel := "TRACE" + if isValidLogLevel(envLevel) { + // allow following for better ux: info, Info or INFO + logLevel = strings.ToUpper(envLevel) + } else { + log.Printf("[WARN] Invalid log level: %q. Defaulting to level: TRACE. Valid levels are: %+v", + envLevel, ValidLevels) + } + + return logLevel +} + +// IsDebugOrHigher returns whether or not the current log level is debug or trace +func IsDebugOrHigher() bool { + level := string(LogLevel()) + return level == "DEBUG" || level == "TRACE" +} + +func isValidLogLevel(level string) bool { + for _, l := range ValidLevels { + if strings.ToUpper(level) == string(l) { + return true + } + } + + return false +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/transport.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/transport.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/transport.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging/transport.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/error.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/error.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/error.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/error.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/id.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/id.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/id.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/id.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/plugin.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/plugin.go new file mode 100644 index 00000000000..6d25e4527b6 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/plugin.go @@ -0,0 +1,154 @@ +package resource + +import ( + "context" + "encoding/json" + "fmt" + "io/ioutil" + "log" + "os" + "strings" + "sync" + + "github.com/hashicorp/go-hclog" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + grpcplugin "github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin" + proto "github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5" + "github.com/hashicorp/terraform-plugin-sdk/v2/plugin" + tftest "github.com/hashicorp/terraform-plugin-test/v2" + testing "github.com/mitchellh/go-testing-interface" +) + +func runProviderCommand(t testing.T, f func() error, wd *tftest.WorkingDir, factories map[string]func() (*schema.Provider, error)) error { + // don't point to this as a test failure location + // point to whatever called it + t.Helper() + + // Run the providers in the same process as the test runner using the + // reattach behavior in Terraform. This ensures we get test coverage + // and enables the use of delve as a debugger. + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + // this is needed so Terraform doesn't default to expecting protocol 4; + // we're skipping the handshake because Terraform didn't launch the + // plugins. + os.Setenv("PLUGIN_PROTOCOL_VERSIONS", "5") + + // Terraform 0.12.X and 0.13.X+ treat namespaceless providers + // differently in terms of what namespace they default to. So we're + // going to set both variations, as we don't know which version of + // Terraform we're talking to. We're also going to allow overriding + // the host or namespace using environment variables. + var namespaces []string + host := "registry.terraform.io" + if v := os.Getenv("TF_ACC_PROVIDER_NAMESPACE"); v != "" { + namespaces = append(namespaces, v) + } else { + namespaces = append(namespaces, "-", "hashicorp") + } + if v := os.Getenv("TF_ACC_PROVIDER_HOST"); v != "" { + host = v + } + + // Spin up gRPC servers for every provider factory, start a + // WaitGroup to listen for all of the close channels. + var wg sync.WaitGroup + reattachInfo := map[string]plugin.ReattachConfig{} + for providerName, factory := range factories { + // providerName may be returned as terraform-provider-foo, and + // we need just foo. So let's fix that. + providerName = strings.TrimPrefix(providerName, "terraform-provider-") + + provider, err := factory() + if err != nil { + return fmt.Errorf("unable to create provider %q from factory: %w", providerName, err) + } + + // keep track of the running factory, so we can make sure it's + // shut down. + wg.Add(1) + + // configure the settings our plugin will be served with + // the GRPCProviderFunc wraps a non-gRPC provider server + // into a gRPC interface, and the logger just discards logs + // from go-plugin. + opts := &plugin.ServeOpts{ + GRPCProviderFunc: func() proto.ProviderServer { + return grpcplugin.NewGRPCProviderServer(provider) + }, + Logger: hclog.New(&hclog.LoggerOptions{ + Name: "plugintest", + Level: hclog.Trace, + Output: ioutil.Discard, + }), + } + + // let's actually start the provider server + config, closeCh, err := plugin.DebugServe(ctx, opts) + if err != nil { + return fmt.Errorf("unable to serve provider %q: %w", providerName, err) + } + + // plugin.DebugServe hijacks our log output location, so let's + // reset it + logging.SetOutput(t) + + // when the provider exits, remove one from the waitgroup + // so we can track when everything is done + go func(c <-chan struct{}) { + <-c + wg.Done() + }(closeCh) + + // set our provider's reattachinfo in our map, once + // for every namespace that different Terraform versions + // may expect. + for _, ns := range namespaces { + reattachInfo[strings.TrimSuffix(host, "/")+"/"+ + strings.TrimSuffix(ns, "/")+"/"+ + providerName] = config + } + } + + // set the environment variable that will tell Terraform how to + // connect to our various running servers. + reattachStr, err := json.Marshal(reattachInfo) + if err != nil { + return err + } + wd.Setenv("TF_REATTACH_PROVIDERS", string(reattachStr)) + + // ok, let's call whatever Terraform command the test was trying to + // call, now that we know it'll attach back to those servers we just + // started. + err = f() + if err != nil { + log.Printf("[WARN] Got error running Terraform: %s", err) + } + + // cancel the servers so they'll return. Otherwise, this closeCh won't + // get closed, and we'll hang here. + cancel() + + // wait for the servers to actually shut down; it may take a moment for + // them to clean up, or whatever. + // TODO: add a timeout here? + // PC: do we need one? The test will time out automatically... + wg.Wait() + + // once we've run the Terraform command, let's remove the reattach + // information from the WorkingDir's environment. The WorkingDir will + // persist until the next call, but the server in the reattach info + // doesn't exist anymore at this point, so the reattach info is no + // longer valid. In theory it should be overwritten in the next call, + // but just to avoid any confusing bug reports, let's just unset the + // environment variable altogether. + wd.Unsetenv("TF_REATTACH_PROVIDERS") + + // return any error returned from the orchestration code running + // Terraform commands + return err +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/state.go new file mode 100644 index 00000000000..6eda1993f1b --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/state.go @@ -0,0 +1,280 @@ +package resource + +import ( + "context" + "log" + "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. +// +// It returns three results. `result` is any object that will be returned +// as the final object after waiting for state change. This allows you to +// return the final updated object, for example an EC2 instance after refreshing +// it. A nil result represents not found. +// +// `state` is the latest state of that object. And `err` is any error that +// may have happened while refreshing the state. +type StateRefreshFunc func() (result interface{}, state string, err error) + +// StateChangeConf is the configuration struct used for `WaitForState`. +type StateChangeConf struct { + Delay time.Duration // Wait this time before starting checks + Pending []string // States that are "allowed" and will continue trying + Refresh StateRefreshFunc // Refreshes the current state + Target []string // Target state + Timeout time.Duration // The amount of time to wait before timeout + MinTimeout time.Duration // Smallest time to wait before refreshes + PollInterval time.Duration // Override MinTimeout/backoff and only poll this often + NotFoundChecks int // Number of times to allow not found (nil result from Refresh) + + // This is to work around inconsistent APIs + ContinuousTargetOccurence int // Number of times the Target state has to occur continuously +} + +// WaitForStateContext watches an object and waits for it to achieve the state +// specified in the configuration using the specified Refresh() func, +// waiting the number of seconds specified in the timeout configuration. +// +// If the Refresh function returns an error, exit immediately with that error. +// +// If the Refresh function returns a state other than the Target state or one +// listed in Pending, return immediately with an error. +// +// If the Timeout is exceeded before reaching the Target state, return an +// error. +// +// Otherwise, the result is the result of the first call to the Refresh function to +// reach the target state. +// +// Cancellation from the passed in context will cancel the refresh loop +func (conf *StateChangeConf) WaitForStateContext(ctx context.Context) (interface{}, error) { + log.Printf("[DEBUG] Waiting for state to become: %s", conf.Target) + + notfoundTick := 0 + targetOccurence := 0 + + // Set a default for times to check for not found + if conf.NotFoundChecks == 0 { + conf.NotFoundChecks = 20 + } + + if conf.ContinuousTargetOccurence == 0 { + conf.ContinuousTargetOccurence = 1 + } + + type Result struct { + Result interface{} + State string + Error error + Done bool + } + + // 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(resCh) + + select { + case <-time.After(conf.Delay): + case <-cancelCh: + return + } + + // 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: res, + State: currentState, + Error: err, + } + + 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++ + if conf.ContinuousTargetOccurence == targetOccurence { + result.Done = true + resCh <- result + return + } + 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++ + if notfoundTick > conf.NotFoundChecks { + result.Error = &NotFoundError{ + LastError: err, + Retries: notfoundTick, + } + resCh <- result + return + } + } else { + // Reset the counter for when a resource isn't found + notfoundTick = 0 + found := false + + for _, allowed := range conf.Target { + if currentState == allowed { + found = true + targetOccurence++ + if conf.ContinuousTargetOccurence == targetOccurence { + result.Done = true + resCh <- result + return + } + continue + } + } + + for _, allowed := range conf.Pending { + if currentState == allowed { + found = true + targetOccurence = 0 + break + } + } + + if !found && len(conf.Pending) > 0 { + result.Error = &UnexpectedStateError{ + LastError: err, + State: result.State, + ExpectedState: conf.Target, + } + 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 { + wait = conf.PollInterval + } else { + if wait < conf.MinTimeout { + wait = conf.MinTimeout + } else if wait > 10*time.Second { + wait = 10 * time.Second + } + } + + log.Printf("[TRACE] Waiting %s before next try", wait) + } + }() + + // 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 <-ctx.Done(): + close(cancelCh) + return nil, ctx.Err() + 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 <-ctx.Done(): + log.Println("[ERROR] Context cancelation detected, abandoning grace period") + break forSelect + 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, + } + } + } +} + +// WaitForState watches an object and waits for it to achieve the state +// specified in the configuration using the specified Refresh() func, +// waiting the number of seconds specified in the timeout configuration. +// +// Deprecated: Please use WaitForStateContext to ensure proper plugin shutdown +func (conf *StateChangeConf) WaitForState() (interface{}, error) { + return conf.WaitForStateContext(context.Background()) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/state_shim.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/state_shim.go new file mode 100644 index 00000000000..42c7b64081c --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/state_shim.go @@ -0,0 +1,288 @@ +package resource + +import ( + "fmt" + "strconv" + + tfjson "github.com/hashicorp/terraform-json" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +type shimmedState struct { + state *terraform.State +} + +func shimStateFromJson(jsonState *tfjson.State) (*terraform.State, error) { + state := terraform.NewState() + state.TFVersion = jsonState.TerraformVersion + + if jsonState.Values == nil { + // the state is empty + return state, nil + } + + for key, output := range jsonState.Values.Outputs { + os, err := shimOutputState(output) + if err != nil { + return nil, err + } + state.RootModule().Outputs[key] = os + } + + ss := &shimmedState{state} + err := ss.shimStateModule(jsonState.Values.RootModule) + if err != nil { + return nil, err + } + + return state, nil +} + +func shimOutputState(so *tfjson.StateOutput) (*terraform.OutputState, error) { + os := &terraform.OutputState{ + Sensitive: so.Sensitive, + } + + switch v := so.Value.(type) { + case string: + os.Type = "string" + os.Value = v + return os, nil + case []interface{}: + os.Type = "list" + if len(v) == 0 { + os.Value = v + return os, nil + } + switch firstElem := v[0].(type) { + case string: + elements := make([]interface{}, len(v)) + for i, el := range v { + elements[i] = el.(string) + } + os.Value = elements + case bool: + elements := make([]interface{}, len(v)) + for i, el := range v { + elements[i] = el.(bool) + } + os.Value = elements + // unmarshalled number from JSON will always be float64 + case float64: + elements := make([]interface{}, len(v)) + for i, el := range v { + elements[i] = el.(float64) + } + os.Value = elements + case []interface{}: + os.Value = v + case map[string]interface{}: + os.Value = v + default: + return nil, fmt.Errorf("unexpected output list element type: %T", firstElem) + } + return os, nil + case map[string]interface{}: + os.Type = "map" + os.Value = v + return os, nil + case bool: + os.Type = "string" + os.Value = strconv.FormatBool(v) + return os, nil + // unmarshalled number from JSON will always be float64 + case float64: + os.Type = "string" + os.Value = strconv.FormatFloat(v, 'f', -1, 64) + return os, nil + } + + return nil, fmt.Errorf("unexpected output type: %T", so.Value) +} + +func (ss *shimmedState) shimStateModule(sm *tfjson.StateModule) error { + var path addrs.ModuleInstance + + if sm.Address == "" { + path = addrs.RootModuleInstance + } else { + var diags tfdiags.Diagnostics + path, diags = addrs.ParseModuleInstanceStr(sm.Address) + if diags.HasErrors() { + return diags.Err() + } + } + + mod := ss.state.AddModule(path) + for _, res := range sm.Resources { + resourceState, err := shimResourceState(res) + if err != nil { + return err + } + + key, err := shimResourceStateKey(res) + if err != nil { + return err + } + + mod.Resources[key] = resourceState + } + + if len(sm.ChildModules) > 0 { + return fmt.Errorf("Modules are not supported. Found %d modules.", + len(sm.ChildModules)) + } + return nil +} + +func shimResourceStateKey(res *tfjson.StateResource) (string, error) { + if res.Index == nil { + return res.Address, nil + } + + var mode terraform.ResourceMode + switch res.Mode { + case tfjson.DataResourceMode: + mode = terraform.DataResourceMode + case tfjson.ManagedResourceMode: + mode = terraform.ManagedResourceMode + default: + return "", fmt.Errorf("unexpected resource mode for %q", res.Address) + } + + var index int + switch idx := res.Index.(type) { + case float64: + index = int(idx) + default: + return "", fmt.Errorf("unexpected index type (%T) for %q, "+ + "for_each is not supported", res.Index, res.Address) + } + + rsk := &terraform.ResourceStateKey{ + Mode: mode, + Type: res.Type, + Name: res.Name, + Index: index, + } + + return rsk.String(), nil +} + +func shimResourceState(res *tfjson.StateResource) (*terraform.ResourceState, error) { + sf := &shimmedFlatmap{} + err := sf.FromMap(res.AttributeValues) + if err != nil { + return nil, err + } + attributes := sf.Flatmap() + + if _, ok := attributes["id"]; !ok { + return nil, fmt.Errorf("no %q found in attributes", "id") + } + + return &terraform.ResourceState{ + Provider: res.ProviderName, + Type: res.Type, + Primary: &terraform.InstanceState{ + ID: attributes["id"], + Attributes: attributes, + Meta: map[string]interface{}{ + "schema_version": int(res.SchemaVersion), + }, + Tainted: res.Tainted, + }, + Dependencies: res.DependsOn, + }, nil +} + +type shimmedFlatmap struct { + m map[string]string +} + +func (sf *shimmedFlatmap) FromMap(attributes map[string]interface{}) error { + if sf.m == nil { + sf.m = make(map[string]string, len(attributes)) + } + + return sf.AddMap("", attributes) +} + +func (sf *shimmedFlatmap) AddMap(prefix string, m map[string]interface{}) error { + for key, value := range m { + k := key + if prefix != "" { + k = fmt.Sprintf("%s.%s", prefix, key) + } + + err := sf.AddEntry(k, value) + if err != nil { + return err + } + } + + mapLength := "%" + if prefix != "" { + mapLength = fmt.Sprintf("%s.%s", prefix, "%") + } + + sf.AddEntry(mapLength, strconv.Itoa(len(m))) + + return nil +} + +func (sf *shimmedFlatmap) AddSlice(name string, elements []interface{}) error { + for i, elem := range elements { + key := fmt.Sprintf("%s.%d", name, i) + err := sf.AddEntry(key, elem) + if err != nil { + return err + } + } + + sliceLength := fmt.Sprintf("%s.#", name) + sf.AddEntry(sliceLength, strconv.Itoa(len(elements))) + + return nil +} + +func (sf *shimmedFlatmap) AddEntry(key string, value interface{}) error { + switch el := value.(type) { + case nil: + // omit the entry + return nil + case bool: + sf.m[key] = strconv.FormatBool(el) + case float64: + sf.m[key] = strconv.FormatFloat(el, 'f', -1, 64) + case string: + sf.m[key] = el + case map[string]interface{}: + err := sf.AddMap(key, el) + if err != nil { + return err + } + case []interface{}: + err := sf.AddSlice(key, el) + if err != nil { + return err + } + default: + // This should never happen unless terraform-json + // changes how attributes (types) are represented. + // + // We handle all types which the JSON unmarshaler + // can possibly produce + // https://golang.org/pkg/encoding/json/#Unmarshal + + return fmt.Errorf("%q: unexpected type (%T)", key, el) + } + return nil +} + +func (sf *shimmedFlatmap) Flatmap() map[string]string { + return sf.m +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing.go new file mode 100644 index 00000000000..0787141bed3 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing.go @@ -0,0 +1,1040 @@ +package resource + +import ( + "errors" + "flag" + "fmt" + "log" + "os" + "regexp" + "strconv" + "strings" + + "github.com/hashicorp/go-multierror" + tftest "github.com/hashicorp/terraform-plugin-test/v2" + testing "github.com/mitchellh/go-testing-interface" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +// flagSweep is a flag available when running tests on the command line. It +// contains a comma seperated list of regions to for the sweeper functions to +// run in. This flag bypasses the normal Test path and instead runs functions designed to +// clean up any leaked resources a testing environment could have created. It is +// a best effort attempt, and relies on Provider authors to implement "Sweeper" +// methods for resources. + +// Adding Sweeper methods with AddTestSweepers will +// construct a list of sweeper funcs to be called here. We iterate through +// regions provided by the sweep flag, and for each region we iterate through the +// tests, and exit on any errors. At time of writing, sweepers are ran +// sequentially, however they can list dependencies to be ran first. We track +// the sweepers that have been ran, so as to not run a sweeper twice for a given +// region. +// +// WARNING: +// Sweepers are designed to be destructive. You should not use the -sweep flag +// in any environment that is not strictly a test environment. Resources will be +// destroyed. + +var flagSweep = flag.String("sweep", "", "List of Regions to run available Sweepers") +var flagSweepAllowFailures = flag.Bool("sweep-allow-failures", false, "Enable to allow Sweeper Tests to continue after failures") +var flagSweepRun = flag.String("sweep-run", "", "Comma seperated list of Sweeper Tests to run") +var sweeperFuncs map[string]*Sweeper + +// type SweeperFunc is a signature for a function that acts as a sweeper. It +// accepts a string for the region that the sweeper is to be ran in. This +// function must be able to construct a valid client for that region. +type SweeperFunc func(r string) error + +type Sweeper struct { + // Name for sweeper. Must be unique to be ran by the Sweeper Runner + Name string + + // Dependencies list the const names of other Sweeper functions that must be ran + // prior to running this Sweeper. This is an ordered list that will be invoked + // recursively at the helper/resource level + Dependencies []string + + // Sweeper function that when invoked sweeps the Provider of specific + // resources + F SweeperFunc +} + +func init() { + sweeperFuncs = make(map[string]*Sweeper) +} + +// AddTestSweepers function adds a given name and Sweeper configuration +// pair to the internal sweeperFuncs map. Invoke this function to register a +// resource sweeper to be available for running when the -sweep flag is used +// with `go test`. Sweeper names must be unique to help ensure a given sweeper +// is only ran once per run. +func AddTestSweepers(name string, s *Sweeper) { + if _, ok := sweeperFuncs[name]; ok { + log.Fatalf("[ERR] Error adding (%s) to sweeperFuncs: function already exists in map", name) + } + + sweeperFuncs[name] = s +} + +func TestMain(m interface { + Run() int +}) { + flag.Parse() + if *flagSweep != "" { + // parse flagSweep contents for regions to run + regions := strings.Split(*flagSweep, ",") + + // get filtered list of sweepers to run based on sweep-run flag + sweepers := filterSweepers(*flagSweepRun, sweeperFuncs) + + if _, err := runSweepers(regions, sweepers, *flagSweepAllowFailures); err != nil { + os.Exit(1) + } + } else { + exitCode := m.Run() + os.Exit(exitCode) + } +} + +func runSweepers(regions []string, sweepers map[string]*Sweeper, allowFailures bool) (map[string]map[string]error, error) { + var sweeperErrorFound bool + sweeperRunList := make(map[string]map[string]error) + + for _, region := range regions { + region = strings.TrimSpace(region) + + var regionSweeperErrorFound bool + regionSweeperRunList := make(map[string]error) + + log.Printf("[DEBUG] Running Sweepers for region (%s):\n", region) + for _, sweeper := range sweepers { + if err := runSweeperWithRegion(region, sweeper, sweepers, regionSweeperRunList, allowFailures); err != nil { + if allowFailures { + continue + } + + sweeperRunList[region] = regionSweeperRunList + return sweeperRunList, fmt.Errorf("sweeper (%s) for region (%s) failed: %s", sweeper.Name, region, err) + } + } + + log.Printf("Sweeper Tests ran successfully:\n") + for sweeper, sweeperErr := range regionSweeperRunList { + if sweeperErr == nil { + fmt.Printf("\t- %s\n", sweeper) + } else { + regionSweeperErrorFound = true + } + } + + if regionSweeperErrorFound { + sweeperErrorFound = true + log.Printf("Sweeper Tests ran unsuccessfully:\n") + for sweeper, sweeperErr := range regionSweeperRunList { + if sweeperErr != nil { + fmt.Printf("\t- %s: %s\n", sweeper, sweeperErr) + } + } + } + + sweeperRunList[region] = regionSweeperRunList + } + + if sweeperErrorFound { + return sweeperRunList, errors.New("at least one sweeper failed") + } + + return sweeperRunList, nil +} + +// filterSweepers takes a comma seperated string listing the names of sweepers +// to be ran, and returns a filtered set from the list of all of sweepers to +// run based on the names given. +func filterSweepers(f string, source map[string]*Sweeper) map[string]*Sweeper { + filterSlice := strings.Split(strings.ToLower(f), ",") + if len(filterSlice) == 1 && filterSlice[0] == "" { + // if the filter slice is a single element of "" then no sweeper list was + // given, so just return the full list + return source + } + + sweepers := make(map[string]*Sweeper) + for name := range source { + for _, s := range filterSlice { + if strings.Contains(strings.ToLower(name), s) { + for foundName, foundSweeper := range filterSweeperWithDependencies(name, source) { + sweepers[foundName] = foundSweeper + } + } + } + } + return sweepers +} + +// filterSweeperWithDependencies recursively returns sweeper and all dependencies. +// Since filterSweepers performs fuzzy matching, this function is used +// to perform exact sweeper and dependency lookup. +func filterSweeperWithDependencies(name string, source map[string]*Sweeper) map[string]*Sweeper { + result := make(map[string]*Sweeper) + + currentSweeper, ok := source[name] + if !ok { + log.Printf("[WARN] Sweeper has dependency (%s), but that sweeper was not found", name) + return result + } + + result[name] = currentSweeper + + for _, dependency := range currentSweeper.Dependencies { + for foundName, foundSweeper := range filterSweeperWithDependencies(dependency, source) { + result[foundName] = foundSweeper + } + } + + return result +} + +// runSweeperWithRegion recieves a sweeper and a region, and recursively calls +// itself with that region for every dependency found for that sweeper. If there +// are no dependencies, invoke the contained sweeper fun with the region, and +// add the success/fail status to the sweeperRunList. +func runSweeperWithRegion(region string, s *Sweeper, sweepers map[string]*Sweeper, sweeperRunList map[string]error, allowFailures bool) error { + for _, dep := range s.Dependencies { + depSweeper, ok := sweepers[dep] + + if !ok { + return fmt.Errorf("sweeper (%s) has dependency (%s), but that sweeper was not found", s.Name, dep) + } + + log.Printf("[DEBUG] Sweeper (%s) has dependency (%s), running..", s.Name, dep) + err := runSweeperWithRegion(region, depSweeper, sweepers, sweeperRunList, allowFailures) + + if err != nil { + if allowFailures { + log.Printf("[ERROR] Error running Sweeper (%s) in region (%s): %s", depSweeper.Name, region, err) + continue + } + + return err + } + } + + if _, ok := sweeperRunList[s.Name]; ok { + log.Printf("[DEBUG] Sweeper (%s) already ran in region (%s)", s.Name, region) + return nil + } + + log.Printf("[DEBUG] Running Sweeper (%s) in region (%s)", s.Name, region) + + runE := s.F(region) + + sweeperRunList[s.Name] = runE + + if runE != nil { + log.Printf("[ERROR] Error running Sweeper (%s) in region (%s): %s", s.Name, region, runE) + } + + return runE +} + +const TestEnvVar = "TF_ACC" + +// TestCheckFunc is the callback type used with acceptance tests to check +// the state of a resource. The state passed in is the latest state known, +// or in the case of being after a destroy, it is the last known state when +// it was created. +type TestCheckFunc func(*terraform.State) error + +// ImportStateCheckFunc is the check function for ImportState tests +type ImportStateCheckFunc func([]*terraform.InstanceState) error + +// ImportStateIdFunc is an ID generation function to help with complex ID +// generation for ImportState tests. +type ImportStateIdFunc func(*terraform.State) (string, error) + +// TestCase is a single acceptance test case used to test the apply/destroy +// lifecycle of a resource in a specific configuration. +// +// When the destroy plan is executed, the config from the last TestStep +// is used to plan it. +type TestCase struct { + // IsUnitTest allows a test to run regardless of the TF_ACC + // environment variable. This should be used with care - only for + // fast tests on local resources (e.g. remote state with a local + // backend) but can be used to increase confidence in correct + // operation of Terraform without waiting for a full acctest run. + IsUnitTest bool + + // PreCheck, if non-nil, will be called before any test steps are + // executed. It will only be executed in the case that the steps + // would run, so it can be used for some validation before running + // acceptance tests, such as verifying that keys are setup. + PreCheck func() + + // ProviderFactories can be specified for the providers that are valid. + // + // These are the providers that can be referenced within the test. Each key + // is an individually addressable provider. Typically you will only pass a + // single value here for the provider you are testing. Aliases are not + // supported by the test framework, so to use multiple provider instances, + // you should add additional copies to this map with unique names. To set + // their configuration, you would reference them similar to the following: + // + // provider "my_factory_key" { + // # ... + // } + // + // resource "my_resource" "mr" { + // provider = my_factory_key + // + // # ... + // } + ProviderFactories map[string]func() (*schema.Provider, error) + + // Providers is the ResourceProvider that will be under test. + // + // Deprecated: Providers is deprecated, please use ProviderFactories + Providers map[string]*schema.Provider + + // ExternalProviders are providers the TestCase relies on that should + // be downloaded from the registry during init. This is only really + // necessary to set if you're using import, as providers in your config + // will be automatically retrieved during init. Import doesn't use a + // config, however, so we allow manually specifying them here to be + // downloaded for import tests. + ExternalProviders map[string]ExternalProvider + + // PreventPostDestroyRefresh can be set to true for cases where data sources + // are tested alongside real resources + PreventPostDestroyRefresh bool + + // CheckDestroy is called after the resource is finally destroyed + // to allow the tester to test that the resource is truly gone. + CheckDestroy TestCheckFunc + + // Steps are the apply sequences done within the context of the + // same state. Each step can have its own check to verify correctness. + Steps []TestStep + + // The settings below control the "ID-only refresh test." This is + // an enabled-by-default test that tests that a refresh can be + // refreshed with only an ID to result in the same attributes. + // This validates completeness of Refresh. + // + // IDRefreshName is the name of the resource to check. This will + // default to the first non-nil primary resource in the state. + // + // IDRefreshIgnore is a list of configuration keys that will be ignored. + IDRefreshName string + IDRefreshIgnore []string +} + +// ExternalProvider holds information about third-party providers that should +// be downloaded by Terraform as part of running the test step. +type ExternalProvider struct { + VersionConstraint string // the version constraint for the provider + Source string // the provider source +} + +// TestStep is a single apply sequence of a test, done within the +// context of a state. +// +// Multiple TestSteps can be sequenced in a Test to allow testing +// potentially complex update logic. In general, simply create/destroy +// tests will only need one step. +type TestStep struct { + // ResourceName should be set to the name of the resource + // that is being tested. Example: "aws_instance.foo". Various test + // modes use this to auto-detect state information. + // + // This is only required if the test mode settings below say it is + // for the mode you're using. + ResourceName string + + // PreConfig is called before the Config is applied to perform any per-step + // setup that needs to happen. This is called regardless of "test mode" + // below. + PreConfig func() + + // Taint is a list of resource addresses to taint prior to the execution of + // the step. Be sure to only include this at a step where the referenced + // address will be present in state, as it will fail the test if the resource + // is missing. + // + // This option is ignored on ImportState tests, and currently only works for + // resources in the root module path. + Taint []string + + //--------------------------------------------------------------- + // Test modes. One of the following groups of settings must be + // set to determine what the test step will do. Ideally we would've + // used Go interfaces here but there are now hundreds of tests we don't + // want to re-type so instead we just determine which step logic + // to run based on what settings below are set. + //--------------------------------------------------------------- + + //--------------------------------------------------------------- + // Plan, Apply testing + //--------------------------------------------------------------- + + // Config a string of the configuration to give to Terraform. If this + // is set, then the TestCase will execute this step with the same logic + // as a `terraform apply`. + Config string + + // Check is called after the Config is applied. Use this step to + // make your own API calls to check the status of things, and to + // inspect the format of the ResourceState itself. + // + // If an error is returned, the test will fail. In this case, a + // destroy plan will still be attempted. + // + // If this is nil, no check is done on this step. + Check TestCheckFunc + + // Destroy will create a destroy plan if set to true. + Destroy bool + + // ExpectNonEmptyPlan can be set to true for specific types of tests that are + // looking to verify that a diff occurs + ExpectNonEmptyPlan bool + + // ExpectError allows the construction of test cases that we expect to fail + // with an error. The specified regexp must match against the error for the + // test to pass. + ExpectError *regexp.Regexp + + // PlanOnly can be set to only run `plan` with this configuration, and not + // actually apply it. This is useful for ensuring config changes result in + // no-op plans + PlanOnly bool + + // PreventDiskCleanup can be set to true for testing terraform modules which + // require access to disk at runtime. Note that this will leave files in the + // temp folder + PreventDiskCleanup bool + + // PreventPostDestroyRefresh can be set to true for cases where data sources + // are tested alongside real resources + PreventPostDestroyRefresh bool + + // SkipFunc is called before applying config, but after PreConfig + // This is useful for defining test steps with platform-dependent checks + SkipFunc func() (bool, error) + + //--------------------------------------------------------------- + // ImportState testing + //--------------------------------------------------------------- + + // ImportState, if true, will test the functionality of ImportState + // by importing the resource with ResourceName (must be set) and the + // ID of that resource. + ImportState bool + + // ImportStateId is the ID to perform an ImportState operation with. + // This is optional. If it isn't set, then the resource ID is automatically + // 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 + + // ImportStateIdFunc is a function that can be used to dynamically generate + // the ID for the ImportState tests. It is sent the state, which can be + // checked to derive the attributes necessary and generate the string in the + // desired format. + ImportStateIdFunc ImportStateIdFunc + + // 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. + ImportStateCheck ImportStateCheckFunc + + // ImportStateVerify, if true, will also check that the state values + // that are finally put into the state after import match for all the + // IDs returned by the Import. Note that this checks for strict equality + // and does not respect DiffSuppressFunc or CustomizeDiff. + // + // ImportStateVerifyIgnore is a list of prefixes of fields that should + // not be verified to be equal. These can be set to ephemeral fields or + // fields that can't be refreshed and don't matter. + ImportStateVerify bool + ImportStateVerifyIgnore []string +} + +// ParallelTest performs an acceptance test on a resource, allowing concurrency +// with other ParallelTest. +// +// Tests will fail if they do not properly handle conditions to allow multiple +// tests to occur against the same resource or service (e.g. random naming). +// All other requirements of the Test function also apply to this function. +func ParallelTest(t testing.T, c TestCase) { + t.Helper() + t.Parallel() + Test(t, c) +} + +// Test performs an acceptance test on a resource. +// +// Tests are not run unless an environmental variable "TF_ACC" is +// set to some non-empty value. This is to avoid test cases surprising +// a user by creating real resources. +// +// Tests will fail unless the verbose flag (`go test -v`, or explicitly +// the "-test.v" flag) is set. Because some acceptance tests take quite +// long, we require the verbose flag so users are able to see progress +// output. +func Test(t testing.T, c TestCase) { + t.Helper() + + // We only run acceptance tests if an env var is set because they're + // slow and generally require some outside configuration. You can opt out + // of this with OverrideEnvVar on individual TestCases. + if os.Getenv(TestEnvVar) == "" && !c.IsUnitTest { + t.Skip(fmt.Sprintf( + "Acceptance tests skipped unless env '%s' set", + TestEnvVar)) + return + } + + logging.SetOutput(t) + + // Copy any explicitly passed providers to factories, this is for backwards compatibility. + if len(c.Providers) > 0 { + c.ProviderFactories = map[string]func() (*schema.Provider, error){} + + for name, p := range c.Providers { + if _, ok := c.ProviderFactories[name]; ok { + t.Fatalf("ProviderFactory for %q already exists, cannot overwrite with Provider", name) + } + prov := p + c.ProviderFactories[name] = func() (*schema.Provider, error) { + return prov, nil + } + } + } + + // Run the PreCheck if we have it. + // This is done after the auto-configure to allow providers + // to override the default auto-configure parameters. + if c.PreCheck != nil { + c.PreCheck() + } + + sourceDir, err := os.Getwd() + if err != nil { + t.Fatalf("Error getting working dir: %s", err) + } + helper := tftest.AutoInitProviderHelper(sourceDir) + defer func(helper *tftest.Helper) { + err := helper.Close() + if err != nil { + log.Printf("Error cleaning up temporary test files: %s", err) + } + }(helper) + + runNewTest(t, c, helper) +} + +// testProviderConfig takes the list of Providers in a TestCase and returns a +// config with only empty provider blocks. This is useful for Import, where no +// config is provided, but the providers must be defined. +func testProviderConfig(c TestCase) (string, error) { + var lines []string + var requiredProviders []string + for p := range c.Providers { + lines = append(lines, fmt.Sprintf("provider %q {}\n", p)) + } + for p, v := range c.ExternalProviders { + if _, ok := c.Providers[p]; ok { + return "", fmt.Errorf("Provider %q set in both Providers and ExternalProviders for TestCase. Must be set in only one.", p) + } + if _, ok := c.ProviderFactories[p]; ok { + return "", fmt.Errorf("Provider %q set in both ProviderFactories and ExternalProviders for TestCase. Must be set in only one.", p) + } + lines = append(lines, fmt.Sprintf("provider %q {}\n", p)) + var providerBlock string + if v.VersionConstraint != "" { + providerBlock = fmt.Sprintf("%s\nversion = %q", providerBlock, v.VersionConstraint) + } + if v.Source != "" { + providerBlock = fmt.Sprintf("%s\nsource = %q", providerBlock, v.Source) + } + if providerBlock != "" { + providerBlock = fmt.Sprintf("%s = {%s\n}\n", p, providerBlock) + } + requiredProviders = append(requiredProviders, providerBlock) + } + + if len(requiredProviders) > 0 { + lines = append([]string{fmt.Sprintf("terraform {\nrequired_providers {\n%s}\n}\n\n", strings.Join(requiredProviders, ""))}, lines...) + } + + return strings.Join(lines, ""), nil +} + +// UnitTest is a helper to force the acceptance testing harness to run in the +// normal unit test suite. This should only be used for resource that don't +// have any external dependencies. +func UnitTest(t testing.T, c TestCase) { + t.Helper() + + c.IsUnitTest = true + Test(t, c) +} + +func testResource(c TestStep, state *terraform.State) (*terraform.ResourceState, error) { + if c.ResourceName == "" { + return nil, fmt.Errorf("ResourceName must be set in TestStep") + } + + for _, m := range state.Modules { + if len(m.Resources) > 0 { + if v, ok := m.Resources[c.ResourceName]; ok { + return v, nil + } + } + } + + return nil, fmt.Errorf( + "Resource specified by ResourceName couldn't be found: %s", c.ResourceName) +} + +// ComposeTestCheckFunc lets you compose multiple TestCheckFuncs into +// a single TestCheckFunc. +// +// As a user testing their provider, this lets you decompose your checks +// into smaller pieces more easily. +func ComposeTestCheckFunc(fs ...TestCheckFunc) TestCheckFunc { + return func(s *terraform.State) error { + for i, f := range fs { + if err := f(s); err != nil { + return fmt.Errorf("Check %d/%d error: %s", i+1, len(fs), err) + } + } + + return nil + } +} + +// ComposeAggregateTestCheckFunc lets you compose multiple TestCheckFuncs into +// a single TestCheckFunc. +// +// As a user testing their provider, this lets you decompose your checks +// into smaller pieces more easily. +// +// Unlike ComposeTestCheckFunc, ComposeAggergateTestCheckFunc runs _all_ of the +// TestCheckFuncs and aggregates failures. +func ComposeAggregateTestCheckFunc(fs ...TestCheckFunc) TestCheckFunc { + return func(s *terraform.State) error { + var result *multierror.Error + + for i, f := range fs { + if err := f(s); err != nil { + result = multierror.Append(result, fmt.Errorf("Check %d/%d error: %s", i+1, len(fs), err)) + } + } + + return result.ErrorOrNil() + } +} + +// TestCheckResourceAttrSet is a TestCheckFunc which ensures a value +// exists in state for the given name/key combination. It is useful when +// testing that computed values were set, when it is not possible to +// know ahead of time what the values will be. +func TestCheckResourceAttrSet(name, key string) TestCheckFunc { + return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { + is, err := primaryInstanceState(s, name) + if err != nil { + return err + } + + return testCheckResourceAttrSet(is, name, key) + }) +} + +// TestCheckModuleResourceAttrSet - as per TestCheckResourceAttrSet but with +// support for non-root modules +func TestCheckModuleResourceAttrSet(mp []string, name string, key string) TestCheckFunc { + mpt := addrs.Module(mp).UnkeyedInstanceShim() + return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { + is, err := modulePathPrimaryInstanceState(s, mpt, name) + if err != nil { + return err + } + + return testCheckResourceAttrSet(is, name, key) + }) +} + +func testCheckResourceAttrSet(is *terraform.InstanceState, name string, key string) error { + if val, ok := is.Attributes[key]; !ok || val == "" { + return fmt.Errorf("%s: Attribute '%s' expected to be set", name, key) + } + + return nil +} + +// TestCheckResourceAttr is a TestCheckFunc which validates +// the value in state for the given name/key combination. +func TestCheckResourceAttr(name, key, value string) TestCheckFunc { + return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { + is, err := primaryInstanceState(s, name) + if err != nil { + return err + } + + return testCheckResourceAttr(is, name, key, value) + }) +} + +// TestCheckModuleResourceAttr - as per TestCheckResourceAttr but with +// support for non-root modules +func TestCheckModuleResourceAttr(mp []string, name string, key string, value string) TestCheckFunc { + mpt := addrs.Module(mp).UnkeyedInstanceShim() + return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { + is, err := modulePathPrimaryInstanceState(s, mpt, name) + if err != nil { + return err + } + + return testCheckResourceAttr(is, name, key, value) + }) +} + +func testCheckResourceAttr(is *terraform.InstanceState, name string, key string, value string) error { + // Empty containers may be elided from the state. + // If the intent here is to check for an empty container, allow the key to + // also be non-existent. + emptyCheck := false + if value == "0" && (strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%")) { + emptyCheck = true + } + + if v, ok := is.Attributes[key]; !ok || v != value { + if emptyCheck && !ok { + return nil + } + + if !ok { + return fmt.Errorf("%s: Attribute '%s' not found", name, key) + } + + return fmt.Errorf( + "%s: Attribute '%s' expected %#v, got %#v", + name, + key, + value, + v) + } + return nil +} + +// TestCheckNoResourceAttr is a TestCheckFunc which ensures that +// NO value exists in state for the given name/key combination. +func TestCheckNoResourceAttr(name, key string) TestCheckFunc { + return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { + is, err := primaryInstanceState(s, name) + if err != nil { + return err + } + + return testCheckNoResourceAttr(is, name, key) + }) +} + +// TestCheckModuleNoResourceAttr - as per TestCheckNoResourceAttr but with +// support for non-root modules +func TestCheckModuleNoResourceAttr(mp []string, name string, key string) TestCheckFunc { + mpt := addrs.Module(mp).UnkeyedInstanceShim() + return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { + is, err := modulePathPrimaryInstanceState(s, mpt, name) + if err != nil { + return err + } + + return testCheckNoResourceAttr(is, name, key) + }) +} + +func testCheckNoResourceAttr(is *terraform.InstanceState, name string, key string) error { + // Empty containers may sometimes be included in the state. + // If the intent here is to check for an empty container, allow the value to + // also be "0". + emptyCheck := false + if strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%") { + emptyCheck = true + } + + val, exists := is.Attributes[key] + if emptyCheck && val == "0" { + return nil + } + + if exists { + return fmt.Errorf("%s: Attribute '%s' found when not expected", name, key) + } + + return nil +} + +// TestMatchResourceAttr is a TestCheckFunc which checks that the value +// in state for the given name/key combination matches the given regex. +func TestMatchResourceAttr(name, key string, r *regexp.Regexp) TestCheckFunc { + return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { + is, err := primaryInstanceState(s, name) + if err != nil { + return err + } + + return testMatchResourceAttr(is, name, key, r) + }) +} + +// TestModuleMatchResourceAttr - as per TestMatchResourceAttr but with +// support for non-root modules +func TestModuleMatchResourceAttr(mp []string, name string, key string, r *regexp.Regexp) TestCheckFunc { + mpt := addrs.Module(mp).UnkeyedInstanceShim() + return checkIfIndexesIntoTypeSet(key, func(s *terraform.State) error { + is, err := modulePathPrimaryInstanceState(s, mpt, name) + if err != nil { + return err + } + + return testMatchResourceAttr(is, name, key, r) + }) +} + +func testMatchResourceAttr(is *terraform.InstanceState, name string, key string, r *regexp.Regexp) error { + if !r.MatchString(is.Attributes[key]) { + return fmt.Errorf( + "%s: Attribute '%s' didn't match %q, got %#v", + name, + key, + r.String(), + is.Attributes[key]) + } + + return nil +} + +// TestCheckResourceAttrPtr is like TestCheckResourceAttr except the +// value is a pointer so that it can be updated while the test is running. +// It will only be dereferenced at the point this step is run. +func TestCheckResourceAttrPtr(name string, key string, value *string) TestCheckFunc { + return func(s *terraform.State) error { + return TestCheckResourceAttr(name, key, *value)(s) + } +} + +// TestCheckModuleResourceAttrPtr - as per TestCheckResourceAttrPtr but with +// support for non-root modules +func TestCheckModuleResourceAttrPtr(mp []string, name string, key string, value *string) TestCheckFunc { + return func(s *terraform.State) error { + return TestCheckModuleResourceAttr(mp, name, key, *value)(s) + } +} + +// TestCheckResourceAttrPair is a TestCheckFunc which validates that the values +// in state for a pair of name/key combinations are equal. +func TestCheckResourceAttrPair(nameFirst, keyFirst, nameSecond, keySecond string) TestCheckFunc { + return checkIfIndexesIntoTypeSetPair(keyFirst, keySecond, func(s *terraform.State) error { + isFirst, err := primaryInstanceState(s, nameFirst) + if err != nil { + return err + } + + isSecond, err := primaryInstanceState(s, nameSecond) + if err != nil { + return err + } + + return testCheckResourceAttrPair(isFirst, nameFirst, keyFirst, isSecond, nameSecond, keySecond) + }) +} + +// TestCheckModuleResourceAttrPair - as per TestCheckResourceAttrPair but with +// support for non-root modules +func TestCheckModuleResourceAttrPair(mpFirst []string, nameFirst string, keyFirst string, mpSecond []string, nameSecond string, keySecond string) TestCheckFunc { + mptFirst := addrs.Module(mpFirst).UnkeyedInstanceShim() + mptSecond := addrs.Module(mpSecond).UnkeyedInstanceShim() + return checkIfIndexesIntoTypeSetPair(keyFirst, keySecond, func(s *terraform.State) error { + isFirst, err := modulePathPrimaryInstanceState(s, mptFirst, nameFirst) + if err != nil { + return err + } + + isSecond, err := modulePathPrimaryInstanceState(s, mptSecond, nameSecond) + if err != nil { + return err + } + + return testCheckResourceAttrPair(isFirst, nameFirst, keyFirst, isSecond, nameSecond, keySecond) + }) +} + +func testCheckResourceAttrPair(isFirst *terraform.InstanceState, nameFirst string, keyFirst string, isSecond *terraform.InstanceState, nameSecond string, keySecond string) error { + if nameFirst == nameSecond && keyFirst == keySecond { + return fmt.Errorf( + "comparing self: resource %s attribute %s", + nameFirst, + keyFirst, + ) + } + + vFirst, okFirst := isFirst.Attributes[keyFirst] + vSecond, okSecond := isSecond.Attributes[keySecond] + + // Container count values of 0 should not be relied upon, and not reliably + // maintained by helper/schema. For the purpose of tests, consider unset and + // 0 to be equal. + if len(keyFirst) > 2 && len(keySecond) > 2 && keyFirst[len(keyFirst)-2:] == keySecond[len(keySecond)-2:] && + (strings.HasSuffix(keyFirst, ".#") || strings.HasSuffix(keyFirst, ".%")) { + // they have the same suffix, and it is a collection count key. + if vFirst == "0" || vFirst == "" { + okFirst = false + } + if vSecond == "0" || vSecond == "" { + okSecond = false + } + } + + if okFirst != okSecond { + if !okFirst { + return fmt.Errorf("%s: Attribute %q not set, but %q is set in %s as %q", nameFirst, keyFirst, keySecond, nameSecond, vSecond) + } + return fmt.Errorf("%s: Attribute %q is %q, but %q is not set in %s", nameFirst, keyFirst, vFirst, keySecond, nameSecond) + } + if !(okFirst || okSecond) { + // If they both don't exist then they are equally unset, so that's okay. + return nil + } + + if vFirst != vSecond { + return fmt.Errorf( + "%s: Attribute '%s' expected %#v, got %#v", + nameFirst, + keyFirst, + vSecond, + vFirst) + } + + return nil +} + +// TestCheckOutput checks an output in the Terraform configuration +func TestCheckOutput(name, value string) TestCheckFunc { + return func(s *terraform.State) error { + ms := s.RootModule() + rs, ok := ms.Outputs[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + if rs.Value != value { + return fmt.Errorf( + "Output '%s': expected %#v, got %#v", + name, + value, + rs) + } + + return nil + } +} + +func TestMatchOutput(name string, r *regexp.Regexp) TestCheckFunc { + return func(s *terraform.State) error { + ms := s.RootModule() + rs, ok := ms.Outputs[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + if !r.MatchString(rs.Value.(string)) { + return fmt.Errorf( + "Output '%s': %#v didn't match %q", + name, + rs, + r.String()) + } + + return nil + } +} + +// modulePrimaryInstanceState returns the instance state for the given resource +// name in a ModuleState +func modulePrimaryInstanceState(s *terraform.State, ms *terraform.ModuleState, name string) (*terraform.InstanceState, error) { + rs, ok := ms.Resources[name] + if !ok { + return nil, fmt.Errorf("Not found: %s in %s", name, ms.Path) + } + + is := rs.Primary + if is == nil { + return nil, fmt.Errorf("No primary instance: %s in %s", name, ms.Path) + } + + return is, nil +} + +// modulePathPrimaryInstanceState returns the primary instance state for the +// given resource name in a given module path. +func modulePathPrimaryInstanceState(s *terraform.State, mp addrs.ModuleInstance, name string) (*terraform.InstanceState, error) { + ms := s.ModuleByPath(mp) + if ms == nil { + return nil, fmt.Errorf("No module found at: %s", mp) + } + + return modulePrimaryInstanceState(s, ms, name) +} + +// primaryInstanceState returns the primary instance state for the given +// resource name in the root module. +func primaryInstanceState(s *terraform.State, name string) (*terraform.InstanceState, error) { + ms := s.RootModule() + return modulePrimaryInstanceState(s, ms, name) +} + +// indexesIntoTypeSet is a heuristic to try and identify if a flatmap style +// string address uses a precalculated TypeSet hash, which are integers and +// typically are large and obviously not a list index +func indexesIntoTypeSet(key string) bool { + for _, part := range strings.Split(key, ".") { + if i, err := strconv.Atoi(part); err == nil && i > 100 { + return true + } + } + return false +} + +func checkIfIndexesIntoTypeSet(key string, f TestCheckFunc) TestCheckFunc { + return func(s *terraform.State) error { + err := f(s) + if err != nil && s.IsBinaryDrivenTest && indexesIntoTypeSet(key) { + return fmt.Errorf("Error in test check: %s\nTest check address %q likely indexes into TypeSet\nThis is currently not possible in the SDK", err, key) + } + return err + } +} + +func checkIfIndexesIntoTypeSetPair(keyFirst, keySecond string, f TestCheckFunc) TestCheckFunc { + return func(s *terraform.State) error { + err := f(s) + if err != nil && s.IsBinaryDrivenTest && (indexesIntoTypeSet(keyFirst) || indexesIntoTypeSet(keySecond)) { + return fmt.Errorf("Error in test check: %s\nTest check address %q or %q likely indexes into TypeSet\nThis is currently not possible in the SDK", err, keyFirst, keySecond) + } + return err + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_config.go new file mode 100644 index 00000000000..1e39294fd7f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_config.go @@ -0,0 +1,25 @@ +package resource + +import ( + "errors" + "fmt" + "log" + + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func testStepTaint(state *terraform.State, step TestStep) error { + for _, p := range step.Taint { + m := state.RootModule() + if m == nil { + return errors.New("no state") + } + rs, ok := m.Resources[p] + if !ok { + return fmt.Errorf("resource %q not found in state", p) + } + log.Printf("[WARN] Test: Explicitly tainting resource %q", p) + rs.Taint() + } + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new.go new file mode 100644 index 00000000000..b4aff32f14f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new.go @@ -0,0 +1,242 @@ +package resource + +import ( + "fmt" + "log" + "reflect" + "strings" + + "github.com/davecgh/go-spew/spew" + tfjson "github.com/hashicorp/terraform-json" + tftest "github.com/hashicorp/terraform-plugin-test/v2" + testing "github.com/mitchellh/go-testing-interface" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func runPostTestDestroy(t testing.T, c TestCase, wd *tftest.WorkingDir, factories map[string]func() (*schema.Provider, error)) error { + t.Helper() + + err := runProviderCommand(t, func() error { + wd.RequireDestroy(t) + return nil + }, wd, factories) + if err != nil { + return err + } + + if c.CheckDestroy != nil { + var statePostDestroy *terraform.State + err := runProviderCommand(t, func() error { + statePostDestroy = getState(t, wd) + return nil + }, wd, factories) + if err != nil { + return err + } + + if err := c.CheckDestroy(statePostDestroy); err != nil { + return err + } + } + + return nil +} + +func runNewTest(t testing.T, c TestCase, helper *tftest.Helper) { + t.Helper() + + spewConf := spew.NewDefaultConfig() + spewConf.SortKeys = true + wd := helper.RequireNewWorkingDir(t) + + defer func() { + var statePreDestroy *terraform.State + err := runProviderCommand(t, func() error { + statePreDestroy = getState(t, wd) + return nil + }, wd, c.ProviderFactories) + if err != nil { + t.Fatalf("Error retrieving state, there may be dangling resources: %s", err.Error()) + return + } + + if !stateIsEmpty(statePreDestroy) { + runPostTestDestroy(t, c, wd, c.ProviderFactories) + } + + wd.Close() + }() + + providerCfg, err := testProviderConfig(c) + if err != nil { + t.Fatal(err) + } + + wd.RequireSetConfig(t, providerCfg) + err = runProviderCommand(t, func() error { + wd.RequireInit(t) + return nil + }, wd, c.ProviderFactories) + if err != nil { + t.Fatalf("Error running init: %s", err.Error()) + return + } + + // use this to track last step succesfully applied + // acts as default for import tests + var appliedCfg string + + for i, step := range c.Steps { + if step.PreConfig != nil { + step.PreConfig() + } + + if step.SkipFunc != nil { + skip, err := step.SkipFunc() + if err != nil { + t.Fatal(err) + } + if skip { + log.Printf("[WARN] Skipping step %d/%d", i+1, len(c.Steps)) + continue + } + } + + if step.ImportState { + err := testStepNewImportState(t, c, helper, wd, step, appliedCfg) + if err != nil { + t.Fatal(err) + } + continue + } + + if step.Config != "" { + err := testStepNewConfig(t, c, wd, step) + if step.ExpectError != nil { + if err == nil { + t.Fatalf("Step %d/%d, expected an error but got none", i+1, len(c.Steps)) + } + if !step.ExpectError.MatchString(err.Error()) { + t.Fatalf("Step %d/%d, expected an error with pattern, no match on: %s", i+1, len(c.Steps), err) + } + } else { + if err != nil { + t.Fatalf("Step %d/%d error: %s", i+1, len(c.Steps), err) + } + } + appliedCfg = step.Config + continue + } + + t.Fatal("Unsupported test mode") + } +} + +func getState(t testing.T, wd *tftest.WorkingDir) *terraform.State { + t.Helper() + + jsonState := wd.RequireState(t) + state, err := shimStateFromJson(jsonState) + if err != nil { + t.Fatal(err) + } + return state +} + +func stateIsEmpty(state *terraform.State) bool { + return state.Empty() || !state.HasResources() +} + +func planIsEmpty(plan *tfjson.Plan) bool { + for _, rc := range plan.ResourceChanges { + if rc.Mode == tfjson.DataResourceMode { + // Skip data sources as the current implementation ignores + // existing state and they are all re-read every time + continue + } + + for _, a := range rc.Change.Actions { + if a != tfjson.ActionNoop { + return false + } + } + } + return true +} + +func testIDRefresh(c TestCase, t testing.T, wd *tftest.WorkingDir, step TestStep, r *terraform.ResourceState) error { + t.Helper() + + spewConf := spew.NewDefaultConfig() + spewConf.SortKeys = true + + // Build the state. The state is just the resource with an ID. There + // are no attributes. We only set what is needed to perform a refresh. + state := terraform.NewState() + state.RootModule().Resources = make(map[string]*terraform.ResourceState) + state.RootModule().Resources[c.IDRefreshName] = &terraform.ResourceState{} + + // Temporarily set the config to a minimal provider config for the refresh + // test. After the refresh we can reset it. + cfg, err := testProviderConfig(c) + if err != nil { + return err + } + wd.RequireSetConfig(t, cfg) + defer wd.RequireSetConfig(t, step.Config) + + // Refresh! + err = runProviderCommand(t, func() error { + wd.RequireRefresh(t) + state = getState(t, wd) + return nil + }, wd, c.ProviderFactories) + if err != nil { + return err + } + + // Verify attribute equivalence. + actualR := state.RootModule().Resources[c.IDRefreshName] + if actualR == nil { + return fmt.Errorf("Resource gone!") + } + if actualR.Primary == nil { + return fmt.Errorf("Resource has no primary instance") + } + actual := actualR.Primary.Attributes + expected := r.Primary.Attributes + // Remove fields we're ignoring + for _, v := range c.IDRefreshIgnore { + for k := range actual { + if strings.HasPrefix(k, v) { + delete(actual, k) + } + } + for k := range expected { + if strings.HasPrefix(k, v) { + delete(expected, k) + } + } + } + + if !reflect.DeepEqual(actual, expected) { + // Determine only the different attributes + for k, v := range expected { + if av, ok := actual[k]; ok && v == av { + delete(expected, k) + delete(actual, k) + } + } + + spewConf := spew.NewDefaultConfig() + spewConf.SortKeys = true + return fmt.Errorf( + "Attributes not equivalent. Difference is shown below. Top is actual, bottom is expected."+ + "\n\n%s\n\n%s", + spewConf.Sdump(actual), spewConf.Sdump(expected)) + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_config.go new file mode 100644 index 00000000000..c847cf45516 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_config.go @@ -0,0 +1,182 @@ +package resource + +import ( + tfjson "github.com/hashicorp/terraform-json" + tftest "github.com/hashicorp/terraform-plugin-test/v2" + testing "github.com/mitchellh/go-testing-interface" + + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func testStepNewConfig(t testing.T, c TestCase, wd *tftest.WorkingDir, step TestStep) error { + t.Helper() + + var idRefreshCheck *terraform.ResourceState + idRefresh := c.IDRefreshName != "" + + if !step.Destroy { + var state *terraform.State + err := runProviderCommand(t, func() error { + state = getState(t, wd) + return nil + }, wd, c.ProviderFactories) + if err != nil { + return err + } + if err := testStepTaint(state, step); err != nil { + t.Fatalf("Error when tainting resources: %s", err) + } + } + + wd.RequireSetConfig(t, step.Config) + + // require a refresh before applying + // failing to do this will result in data sources not being updated + err := runProviderCommand(t, func() error { + return wd.Refresh() + }, wd, c.ProviderFactories) + if err != nil { + return err + } + + if !step.PlanOnly { + err := runProviderCommand(t, func() error { + return wd.Apply() + }, wd, c.ProviderFactories) + if err != nil { + return err + } + + var state *terraform.State + err = runProviderCommand(t, func() error { + state = getState(t, wd) + return nil + }, wd, c.ProviderFactories) + if err != nil { + return err + } + if step.Check != nil { + state.IsBinaryDrivenTest = true + if err := step.Check(state); err != nil { + t.Fatal(err) + } + } + } + + // Test for perpetual diffs by performing a plan, a refresh, and another plan + + // do a plan + err = runProviderCommand(t, func() error { + return wd.CreatePlan() + }, wd, c.ProviderFactories) + if err != nil { + return err + } + + var plan *tfjson.Plan + err = runProviderCommand(t, func() error { + plan = wd.RequireSavedPlan(t) + return nil + }, wd, c.ProviderFactories) + if err != nil { + return err + } + + if !planIsEmpty(plan) { + if step.ExpectNonEmptyPlan { + t.Log("[INFO] Got non-empty plan, as expected") + } else { + var stdout string + err = runProviderCommand(t, func() error { + stdout = wd.RequireSavedPlanStdout(t) + return nil + }, wd, c.ProviderFactories) + if err != nil { + return err + } + t.Fatalf("After applying this test step, the plan was not empty.\nstdout:\n\n%s", stdout) + } + } + + // do a refresh + if !c.PreventPostDestroyRefresh { + err := runProviderCommand(t, func() error { + return wd.Refresh() + }, wd, c.ProviderFactories) + if err != nil { + return err + } + } + + // do another plan + err = runProviderCommand(t, func() error { + return wd.CreatePlan() + }, wd, c.ProviderFactories) + if err != nil { + return err + } + + err = runProviderCommand(t, func() error { + plan = wd.RequireSavedPlan(t) + return nil + }, wd, c.ProviderFactories) + if err != nil { + return err + } + + // check if plan is empty + if !planIsEmpty(plan) { + if step.ExpectNonEmptyPlan { + t.Log("[INFO] Got non-empty plan, as expected") + } else { + var stdout string + err = runProviderCommand(t, func() error { + stdout = wd.RequireSavedPlanStdout(t) + return nil + }, wd, c.ProviderFactories) + if err != nil { + return err + } + t.Fatalf("After applying this test step and performing a `terraform refresh`, the plan was not empty.\nstdout\n\n%s", stdout) + } + } + + // ID-ONLY REFRESH + // If we've never checked an id-only refresh and our state isn't + // empty, find the first resource and test it. + var state *terraform.State + err = runProviderCommand(t, func() error { + state = getState(t, wd) + return nil + }, wd, c.ProviderFactories) + if err != nil { + return err + } + if idRefresh && idRefreshCheck == nil && !state.Empty() { + // Find the first non-nil resource in the state + for _, m := range state.Modules { + if len(m.Resources) > 0 { + if v, ok := m.Resources[c.IDRefreshName]; ok { + idRefreshCheck = v + } + + break + } + } + + // If we have an instance to check for refreshes, do it + // immediately. We do it in the middle of another test + // because it shouldn't affect the overall state (refresh + // is read-only semantically) and we want to fail early if + // this fails. If refresh isn't read-only, then this will have + // caught a different bug. + if idRefreshCheck != nil { + if err := testIDRefresh(c, t, wd, step, idRefreshCheck); err != nil { + t.Fatalf( + "[ERROR] Test: ID-only test failed: %s", err) + } + } + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_import_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_import_state.go new file mode 100644 index 00000000000..5ef8d722b1e --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/testing_new_import_state.go @@ -0,0 +1,185 @@ +package resource + +import ( + "reflect" + "strings" + + "github.com/davecgh/go-spew/spew" + tftest "github.com/hashicorp/terraform-plugin-test/v2" + testing "github.com/mitchellh/go-testing-interface" + + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func testStepNewImportState(t testing.T, c TestCase, helper *tftest.Helper, wd *tftest.WorkingDir, step TestStep, cfg string) error { + t.Helper() + + spewConf := spew.NewDefaultConfig() + spewConf.SortKeys = true + + if step.ResourceName == "" { + t.Fatal("ResourceName is required for an import state test") + } + + // get state from check sequence + var state *terraform.State + err := runProviderCommand(t, func() error { + state = getState(t, wd) + return nil + }, wd, c.ProviderFactories) + if err != nil { + t.Fatalf("Error getting state: %s", err) + } + + // Determine the ID to import + var importId string + switch { + case step.ImportStateIdFunc != nil: + var err error + importId, err = step.ImportStateIdFunc(state) + if err != nil { + t.Fatal(err) + } + case step.ImportStateId != "": + importId = step.ImportStateId + default: + resource, err := testResource(step, state) + if err != nil { + t.Fatal(err) + } + importId = resource.Primary.ID + } + importId = step.ImportStateIdPrefix + importId + + // Create working directory for import tests + if step.Config == "" { + step.Config = cfg + if step.Config == "" { + t.Fatal("Cannot import state with no specified config") + } + } + importWd := helper.RequireNewWorkingDir(t) + defer importWd.Close() + importWd.RequireSetConfig(t, step.Config) + + err = runProviderCommand(t, func() error { + importWd.RequireInit(t) + return nil + }, importWd, c.ProviderFactories) + if err != nil { + t.Fatalf("Error running init: %s", err) + } + + err = runProviderCommand(t, func() error { + importWd.RequireImport(t, step.ResourceName, importId) + return nil + }, importWd, c.ProviderFactories) + if err != nil { + t.Fatalf("Error running import: %s", err) + } + + var importState *terraform.State + err = runProviderCommand(t, func() error { + importState = getState(t, wd) + return nil + }, wd, c.ProviderFactories) + if err != nil { + t.Fatalf("Error getting state: %s", err) + } + + // Go through the imported state and verify + if step.ImportStateCheck != nil { + var states []*terraform.InstanceState + for _, r := range importState.RootModule().Resources { + if r.Primary != nil { + is := r.Primary.DeepCopy() + is.Ephemeral.Type = r.Type // otherwise the check function cannot see the type + states = append(states, is) + } + } + if err := step.ImportStateCheck(states); err != nil { + t.Fatal(err) + } + } + + // Verify that all the states match + if step.ImportStateVerify { + new := importState.RootModule().Resources + old := state.RootModule().Resources + + for _, r := range new { + // Find the existing resource + var oldR *terraform.ResourceState + for _, r2 := range old { + if r2.Primary != nil && r2.Primary.ID == r.Primary.ID && r2.Type == r.Type { + oldR = r2 + break + } + } + if oldR == nil { + t.Fatalf( + "Failed state verification, resource with ID %s not found", + r.Primary.ID) + } + + // don't add empty flatmapped containers, so we can more easily + // compare the attributes + skipEmpty := func(k, v string) bool { + if strings.HasSuffix(k, ".#") || strings.HasSuffix(k, ".%") { + if v == "0" { + return true + } + } + return false + } + + // Compare their attributes + actual := make(map[string]string) + for k, v := range r.Primary.Attributes { + if skipEmpty(k, v) { + continue + } + actual[k] = v + } + + expected := make(map[string]string) + for k, v := range oldR.Primary.Attributes { + if skipEmpty(k, v) { + continue + } + expected[k] = v + } + + // Remove fields we're ignoring + for _, v := range step.ImportStateVerifyIgnore { + for k := range actual { + if strings.HasPrefix(k, v) { + delete(actual, k) + } + } + for k := range expected { + if strings.HasPrefix(k, v) { + delete(expected, k) + } + } + } + + if !reflect.DeepEqual(actual, expected) { + // Determine only the different attributes + for k, v := range expected { + if av, ok := actual[k]; ok && v == av { + delete(expected, k) + delete(actual, k) + } + } + + t.Fatalf( + "ImportStateVerify attributes not equivalent. Difference is shown below. Top is actual, bottom is expected."+ + "\n\n%s\n\n%s", + spewConf.Sdump(actual), spewConf.Sdump(expected)) + } + } + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/wait.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/wait.go new file mode 100644 index 00000000000..b625feae0ea --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource/wait.go @@ -0,0 +1,109 @@ +package resource + +import ( + "context" + "errors" + "sync" + "time" +) + +// RetryContext is a basic wrapper around StateChangeConf that will just retry +// a function until it no longer returns an error. +// +// Cancellation from the passed in context will propagate through to the +// underlying StateChangeConf +func RetryContext(ctx context.Context, timeout time.Duration, f RetryFunc) error { + // These are used to pull the error out of the function; need a mutex to + // avoid a data race. + var resultErr error + var resultErrMu sync.Mutex + + c := &StateChangeConf{ + Pending: []string{"retryableerror"}, + Target: []string{"success"}, + Timeout: timeout, + MinTimeout: 500 * time.Millisecond, + Refresh: func() (interface{}, string, error) { + rerr := f() + + resultErrMu.Lock() + defer resultErrMu.Unlock() + + if rerr == nil { + resultErr = nil + return 42, "success", nil + } + + resultErr = rerr.Err + + if rerr.Retryable { + return 42, "retryableerror", nil + } + return nil, "quit", rerr.Err + }, + } + + _, waitErr := c.WaitForStateContext(ctx) + + // Need to acquire the lock here to be able to avoid race using resultErr as + // the return value + resultErrMu.Lock() + defer resultErrMu.Unlock() + + // resultErr may be nil because the wait timed out and resultErr was never + // set; this is still an error + if resultErr == nil { + return waitErr + } + // resultErr takes precedence over waitErr if both are set because it is + // more likely to be useful + return resultErr +} + +// Retry is a basic wrapper around StateChangeConf that will just retry +// a function until it no longer returns an error. +// +// Deprecated: Please use RetryContext to ensure proper plugin shutdown +func Retry(timeout time.Duration, f RetryFunc) error { + return RetryContext(context.Background(), timeout, f) +} + +// RetryFunc is the function retried until it succeeds. +type RetryFunc func() *RetryError + +// RetryError is the required return type of RetryFunc. It forces client code +// to choose whether or not a given error is retryable. +type RetryError struct { + Err error + Retryable bool +} + +// RetryableError is a helper to create a RetryError that's retryable from a +// given error. To prevent logic errors, will return an error when passed a +// nil error. +func RetryableError(err error) *RetryError { + if err == nil { + return &RetryError{ + Err: errors.New("empty retryable error received. " + + "This is a bug with the Terraform provider and should be " + + "reported as a GitHub issue in the provider repository."), + Retryable: false, + } + } + return &RetryError{Err: err, Retryable: true} +} + +// NonRetryableError is a helper to create a RetryError that's _not_ retryable +// from a given error. To prevent logic errors, will return an error when +// passed a nil error. +func NonRetryableError(err error) *RetryError { + if err == nil { + return &RetryError{ + Err: errors.New("empty non-retryable error received. " + + "This is a bug with the Terraform provider and should be " + + "reported as a GitHub issue in the provider repository."), + Retryable: false, + } + } + return &RetryError{Err: err, Retryable: false} +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/README.md b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/README.md similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/README.md rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/README.md diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/core_schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/core_schema.go similarity index 94% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/core_schema.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/core_schema.go index d16abef88f4..bb1fc1dbe54 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/core_schema.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/core_schema.go @@ -3,14 +3,27 @@ package schema import ( "fmt" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/zclconf/go-cty/cty" + "github.com/hashicorp/go-cty/cty" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" +) + +// StringKind represents the format a string is in. +type StringKind configschema.StringKind + +const ( + // StringPlain indicates a string is plain-text and requires no processing for display. + StringPlain = StringKind(configschema.StringPlain) + + // StringMarkdown indicates a string is in markdown format and may + // require additional processing to display. + StringMarkdown = StringKind(configschema.StringMarkdown) ) var ( // DescriptionKind is the default StringKind of descriptions in this provider. // It defaults to StringPlain but can be globally switched to StringMarkdown. - DescriptionKind = configschema.StringPlain + DescriptionKind = StringPlain // SchemaDescriptionBuilder converts helper/schema.Schema Descriptions to configschema.Attribute // and Block Descriptions. This method can be used to modify the description text prior to it @@ -136,7 +149,7 @@ func (s *Schema) coreConfigSchemaAttribute() *configschema.Attribute { } desc := SchemaDescriptionBuilder(s) - descKind := DescriptionKind + descKind := configschema.StringKind(DescriptionKind) if desc == "" { // fallback to plain text if empty descKind = configschema.StringPlain @@ -163,7 +176,7 @@ func (s *Schema) coreConfigSchemaBlock() *configschema.NestedBlock { ret.Block = *nested desc := SchemaDescriptionBuilder(s) - descKind := DescriptionKind + descKind := configschema.StringKind(DescriptionKind) if desc == "" { // fallback to plain text if empty descKind = configschema.StringPlain @@ -272,7 +285,7 @@ func (r *Resource) CoreConfigSchema() *configschema.Block { block := r.coreConfigSchema() desc := ResourceDescriptionBuilder(r) - descKind := DescriptionKind + descKind := configschema.StringKind(DescriptionKind) if desc == "" { // fallback to plain text if empty descKind = configschema.StringPlain @@ -353,9 +366,3 @@ func (r *Resource) CoreConfigSchema() *configschema.Block { func (r *Resource) coreConfigSchema() *configschema.Block { return schemaMap(r.Schema).CoreConfigSchema() } - -// CoreConfigSchema is a convenient shortcut for calling CoreConfigSchema -// on the backends's schema. -func (r *Backend) CoreConfigSchema() *configschema.Block { - return schemaMap(r.Schema).CoreConfigSchema() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/data_source_resource_shim.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/data_source_resource_shim.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/data_source_resource_shim.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/data_source_resource_shim.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/equal.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/equal.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/equal.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/equal.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader.go similarity index 96% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader.go index 622e9b13eb2..c7721bcd366 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader.go @@ -3,7 +3,6 @@ package schema import ( "fmt" "strconv" - "strings" ) // FieldReaders are responsible for decoding fields out of data into @@ -42,13 +41,6 @@ func (r *FieldReadResult) ValueOrZero(s *Schema) interface{} { return s.ZeroValue() } -// SchemasForFlatmapPath tries its best to find a sequence of schemas that -// the given dot-delimited attribute path traverses through. -func SchemasForFlatmapPath(path string, schemaMap map[string]*Schema) []*Schema { - parts := strings.Split(path, ".") - return addrToSchema(parts, schemaMap) -} - // addrToSchema finds the final element schema for the given address // and the given schema. It returns all the schemas that led to the final // schema. These are in order of the address (out to in). diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_config.go similarity index 85% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader_config.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_config.go index dc2ae1af5d4..3f1f5e8ab1b 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader_config.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_config.go @@ -7,8 +7,9 @@ import ( "strings" "sync" - "github.com/hashicorp/terraform-plugin-sdk/terraform" "github.com/mitchellh/mapstructure" + + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // ConfigFieldReader reads fields out of an untyped map[string]string to the @@ -81,31 +82,16 @@ func (r *ConfigFieldReader) readField( k := strings.Join(address, ".") schema := schemaList[len(schemaList)-1] - // If we're getting the single element of a promoted list, then - // check to see if we have a single element we need to promote. - if address[len(address)-1] == "0" && len(schemaList) > 1 { - lastSchema := schemaList[len(schemaList)-2] - if lastSchema.Type == TypeList && lastSchema.PromoteSingle { - k := strings.Join(address[:len(address)-1], ".") - result, err := r.readPrimitive(k, schema) - if err == nil { - return result, nil - } - } - } - - if protoVersion5 { - switch schema.Type { - case TypeList, TypeSet, TypeMap, typeObject: - // Check if the value itself is unknown. - // The new protocol shims will add unknown values to this list of - // ComputedKeys. This is the only way we have to indicate that a - // collection is unknown in the config - for _, unknown := range r.Config.ComputedKeys { - if k == unknown { - log.Printf("[DEBUG] setting computed for %q from ComputedKeys", k) - return FieldReadResult{Computed: true, Exists: true}, nil - } + switch schema.Type { + case TypeList, TypeSet, TypeMap, typeObject: + // Check if the value itself is unknown. + // The new protocol shims will add unknown values to this list of + // ComputedKeys. This is the only way we have to indicate that a + // collection is unknown in the config + for _, unknown := range r.Config.ComputedKeys { + if k == unknown { + log.Printf("[DEBUG] setting computed for %q from ComputedKeys", k) + return FieldReadResult{Computed: true, Exists: true}, nil } } } @@ -114,17 +100,6 @@ func (r *ConfigFieldReader) readField( case TypeBool, TypeFloat, TypeInt, TypeString: return r.readPrimitive(k, schema) case TypeList: - // If we support promotion then we first check if we have a lone - // value that we must promote. - // a value that is alone. - if schema.PromoteSingle { - result, err := r.readPrimitive(k, schema.Elem.(*Schema)) - if err == nil && result.Exists { - result.Value = []interface{}{result.Value} - return result, nil - } - } - return readListField(&nestedConfigFieldReader{r}, address, schema) case TypeMap: return r.readMap(k, schema) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader_diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_diff.go similarity index 99% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader_diff.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_diff.go index c099029afa7..642e7f32eb3 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader_diff.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_diff.go @@ -4,8 +4,9 @@ import ( "fmt" "strings" - "github.com/hashicorp/terraform-plugin-sdk/terraform" "github.com/mitchellh/mapstructure" + + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // DiffFieldReader reads fields out of a diff structures. diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader_map.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_map.go similarity index 88% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader_map.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_map.go index 53f73b71bb1..092dd7f6859 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader_map.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_map.go @@ -200,36 +200,3 @@ func (r BasicMapReader) Range(f func(string, string) bool) bool { return true } - -// MultiMapReader reads over multiple maps, preferring keys that are -// founder earlier (lower number index) vs. later (higher number index) -type MultiMapReader []map[string]string - -func (r MultiMapReader) Access(k string) (string, bool) { - for _, m := range r { - if v, ok := m[k]; ok { - return v, ok - } - } - - return "", false -} - -func (r MultiMapReader) Range(f func(string, string) bool) bool { - done := make(map[string]struct{}) - for _, m := range r { - for k, v := range m { - if _, ok := done[k]; ok { - continue - } - - if cont := f(k, v); !cont { - return false - } - - done[k] = struct{}{} - } - } - - return true -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader_multi.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_multi.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_reader_multi.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_reader_multi.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_writer.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_writer.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_writer.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_writer.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_writer_map.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_writer_map.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/field_writer_map.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/field_writer_map.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/getsource_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/getsource_string.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/getsource_string.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/getsource_string.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/provider.go new file mode 100644 index 00000000000..209f3691d63 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/provider.go @@ -0,0 +1,469 @@ +package schema + +import ( + "context" + "errors" + "fmt" + "log" + "os" + "sort" + "strings" + + "github.com/hashicorp/go-multierror" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" + grpcpluginctx "github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/context" + "github.com/hashicorp/terraform-plugin-sdk/v2/meta" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +const uaEnvVar = "TF_APPEND_USER_AGENT" + +var ReservedProviderFields = []string{ + "alias", + "version", +} + +// StopContext returns a context safe for global use that will cancel +// when Terraform requests a stop. This function should only be called +// within a ConfigureContextFunc, passing in the request scoped context +// received in that method. +// +// Deprecated: The use of a global context is discouraged. Please use the new +// context aware CRUD methods. +func StopContext(ctx context.Context) (context.Context, bool) { + stopContext, ok := ctx.Value(grpcpluginctx.StopContextKey).(context.Context) + return stopContext, ok +} + +// Provider represents a resource provider in Terraform, and properly +// implements all of the ResourceProvider API. +// +// By defining a schema for the configuration of the provider, the +// map of supporting resources, and a configuration function, the schema +// framework takes over and handles all the provider operations for you. +// +// After defining the provider structure, it is unlikely that you'll require any +// of the methods on Provider itself. +type Provider struct { + // Schema is the schema for the configuration of this provider. If this + // provider has no configuration, this can be omitted. + // + // The keys of this map are the configuration keys, and the value is + // the schema describing the value of the configuration. + Schema map[string]*Schema + + // ResourcesMap is the list of available resources that this provider + // can manage, along with their Resource structure defining their + // own schemas and CRUD operations. + // + // Provider automatically handles routing operations such as Apply, + // Diff, etc. to the proper resource. + ResourcesMap map[string]*Resource + + // DataSourcesMap is the collection of available data sources that + // this provider implements, with a Resource instance defining + // the schema and Read operation of each. + // + // Resource instances for data sources must have a Read function + // and must *not* implement Create, Update or Delete. + DataSourcesMap map[string]*Resource + + // ProviderMetaSchema is the schema for the configuration of the meta + // information for this provider. If this provider has no meta info, + // this can be omitted. This functionality is currently experimental + // and subject to change or break without warning; it should only be + // used by providers that are collaborating on its use with the + // Terraform team. + ProviderMetaSchema map[string]*Schema + + // ConfigureFunc is a function for configuring the provider. If the + // provider doesn't need to be configured, this can be omitted. + // + // Deprecated: Please use ConfigureContextFunc instead. + ConfigureFunc ConfigureFunc + + // ConfigureContextFunc is a function for configuring the provider. If the + // provider doesn't need to be configured, this can be omitted. This function + // receives a context.Context that will cancel when Terraform sends a + // cancellation signal. This function can yield Diagnostics. + ConfigureContextFunc ConfigureContextFunc + + meta interface{} + + TerraformVersion string +} + +// ConfigureFunc is the function used to configure a Provider. +// +// Deprecated: Please use ConfigureContextFunc +type ConfigureFunc func(*ResourceData) (interface{}, error) + +// ConfigureContextFunc is the function used to configure a Provider. +// +// The interface{} value returned by this function is stored and passed into +// the subsequent resources as the meta parameter. This return value is +// usually used to pass along a configured API client, a configuration +// structure, etc. +type ConfigureContextFunc func(context.Context, *ResourceData) (interface{}, diag.Diagnostics) + +// InternalValidate should be called to validate the structure +// of the provider. +// +// This should be called in a unit test for any provider to verify +// before release that a provider is properly configured for use with +// this library. +func (p *Provider) InternalValidate() error { + if p == nil { + return errors.New("provider is nil") + } + + if p.ConfigureFunc != nil && p.ConfigureContextFunc != nil { + return errors.New("ConfigureFunc and ConfigureContextFunc must not both be set") + } + + var validationErrors error + sm := schemaMap(p.Schema) + if err := sm.InternalValidate(sm); err != nil { + validationErrors = multierror.Append(validationErrors, err) + } + + // Provider-specific checks + for k := range sm { + if isReservedProviderFieldName(k) { + return fmt.Errorf("%s is a reserved field name for a provider", k) + } + } + + for k, r := range p.ResourcesMap { + if err := r.InternalValidate(nil, true); err != nil { + validationErrors = multierror.Append(validationErrors, fmt.Errorf("resource %s: %s", k, err)) + } + } + + for k, r := range p.DataSourcesMap { + if err := r.InternalValidate(nil, false); err != nil { + validationErrors = multierror.Append(validationErrors, fmt.Errorf("data source %s: %s", k, err)) + } + } + + return validationErrors +} + +func isReservedProviderFieldName(name string) bool { + for _, reservedName := range ReservedProviderFields { + if name == reservedName { + return true + } + } + return false +} + +// Meta returns the metadata associated with this provider that was +// returned by the Configure call. It will be nil until Configure is called. +func (p *Provider) Meta() interface{} { + return p.meta +} + +// SetMeta can be used to forcefully set the Meta object of the provider. +// Note that if Configure is called the return value will override anything +// set here. +func (p *Provider) SetMeta(v interface{}) { + p.meta = v +} + +// GetSchema returns the config schema for the main provider +// configuration, as would appear in a "provider" block in the +// configuration files. +// +// Currently not all providers support schema. Callers must therefore +// first call Resources and DataSources and ensure that at least one +// resource or data source has the SchemaAvailable flag set. +func (p *Provider) GetSchema(req *terraform.ProviderSchemaRequest) (*terraform.ProviderSchema, error) { + resourceTypes := map[string]*configschema.Block{} + dataSources := map[string]*configschema.Block{} + + for _, name := range req.ResourceTypes { + if r, exists := p.ResourcesMap[name]; exists { + resourceTypes[name] = r.CoreConfigSchema() + } + } + for _, name := range req.DataSources { + if r, exists := p.DataSourcesMap[name]; exists { + dataSources[name] = r.CoreConfigSchema() + } + } + + return &terraform.ProviderSchema{ + Provider: schemaMap(p.Schema).CoreConfigSchema(), + ResourceTypes: resourceTypes, + DataSources: dataSources, + }, nil +} + +// Validate is called once at the beginning with the raw configuration +// (no interpolation done) and can return diagnostics +// +// This is called once with the provider configuration only. It may not +// be called at all if no provider configuration is given. +// +// This should not assume that any values of the configurations are valid. +// The primary use case of this call is to check that required keys are +// set. +func (p *Provider) Validate(c *terraform.ResourceConfig) diag.Diagnostics { + if err := p.InternalValidate(); err != nil { + return []diag.Diagnostic{ + { + Severity: diag.Error, + Summary: "InternalValidate", + Detail: fmt.Sprintf("Internal validation of the provider failed! This is always a bug\n"+ + "with the provider itself, and not a user issue. Please report\n"+ + "this bug:\n\n%s", err), + }, + } + } + + return schemaMap(p.Schema).Validate(c) +} + +// ValidateResource is called once at the beginning with the raw +// configuration (no interpolation done) and can return diagnostics. +// +// This is called once per resource. +// +// This should not assume any of the values in the resource configuration +// are valid since it is possible they have to be interpolated still. +// The primary use case of this call is to check that the required keys +// are set and that the general structure is correct. +func (p *Provider) ValidateResource( + t string, c *terraform.ResourceConfig) diag.Diagnostics { + r, ok := p.ResourcesMap[t] + if !ok { + return []diag.Diagnostic{ + { + Severity: diag.Error, + Summary: fmt.Sprintf("Provider doesn't support resource: %s", t), + }, + } + } + + return r.Validate(c) +} + +// Configure configures the provider itself with the configuration +// given. This is useful for setting things like access keys. +// +// This won't be called at all if no provider configuration is given. +func (p *Provider) Configure(ctx context.Context, c *terraform.ResourceConfig) diag.Diagnostics { + // No configuration + if p.ConfigureFunc == nil && p.ConfigureContextFunc == nil { + return nil + } + + sm := schemaMap(p.Schema) + + // Get a ResourceData for this configuration. To do this, we actually + // generate an intermediary "diff" although that is never exposed. + diff, err := sm.Diff(ctx, nil, c, nil, p.meta, true) + if err != nil { + return diag.FromErr(err) + } + + data, err := sm.Data(nil, diff) + if err != nil { + return diag.FromErr(err) + } + + if p.ConfigureFunc != nil { + meta, err := p.ConfigureFunc(data) + if err != nil { + return diag.FromErr(err) + } + p.meta = meta + } + if p.ConfigureContextFunc != nil { + meta, diags := p.ConfigureContextFunc(ctx, data) + if diags.HasError() { + return diags + } + p.meta = meta + } + + return nil +} + +// Resources returns all the available resource types that this provider +// knows how to manage. +func (p *Provider) Resources() []terraform.ResourceType { + keys := make([]string, 0, len(p.ResourcesMap)) + for k := range p.ResourcesMap { + keys = append(keys, k) + } + sort.Strings(keys) + + result := make([]terraform.ResourceType, 0, len(keys)) + for _, k := range keys { + resource := p.ResourcesMap[k] + + // This isn't really possible (it'd fail InternalValidate), but + // we do it anyways to avoid a panic. + if resource == nil { + resource = &Resource{} + } + + result = append(result, terraform.ResourceType{ + Name: k, + Importable: resource.Importer != nil, + + // Indicates that a provider is compiled against a new enough + // version of core to support the GetSchema method. + SchemaAvailable: true, + }) + } + + return result +} + +// ImportState requests that the given resource be imported. +// +// The returned InstanceState only requires ID be set. Importing +// will always call Refresh after the state to complete it. +// +// IMPORTANT: InstanceState doesn't have the resource type attached +// to it. A type must be specified on the state via the Ephemeral +// field on the state. +// +// This function can return multiple states. Normally, an import +// will map 1:1 to a physical resource. However, some resources map +// to multiple. For example, an AWS security group may contain many rules. +// Each rule is represented by a separate resource in Terraform, +// therefore multiple states are returned. +func (p *Provider) ImportState( + ctx context.Context, + info *terraform.InstanceInfo, + id string) ([]*terraform.InstanceState, error) { + // Find the resource + r, ok := p.ResourcesMap[info.Type] + if !ok { + return nil, fmt.Errorf("unknown resource type: %s", info.Type) + } + + // If it doesn't support import, error + if r.Importer == nil { + return nil, fmt.Errorf("resource %s doesn't support import", info.Type) + } + + // Create the data + data := r.Data(nil) + data.SetId(id) + data.SetType(info.Type) + + // Call the import function + results := []*ResourceData{data} + if r.Importer.State != nil || r.Importer.StateContext != nil { + var err error + if r.Importer.StateContext != nil { + results, err = r.Importer.StateContext(ctx, data, p.meta) + } else { + results, err = r.Importer.State(data, p.meta) + } + if err != nil { + return nil, err + } + } + + // Convert the results to InstanceState values and return it + states := make([]*terraform.InstanceState, len(results)) + for i, r := range results { + states[i] = r.State() + } + + // Verify that all are non-nil. If there are any nil the error + // isn't obvious so we circumvent that with a friendlier error. + for _, s := range states { + if s == nil { + return nil, fmt.Errorf( + "nil entry in ImportState results. This is always a bug with\n" + + "the resource that is being imported. Please report this as\n" + + "a bug to Terraform.") + } + } + + return states, nil +} + +// ValidateDataSource is called once at the beginning with the raw +// configuration (no interpolation done) and can return diagnostics. +// +// This is called once per data source instance. +// +// This should not assume any of the values in the resource configuration +// are valid since it is possible they have to be interpolated still. +// The primary use case of this call is to check that the required keys +// are set and that the general structure is correct. +func (p *Provider) ValidateDataSource( + t string, c *terraform.ResourceConfig) diag.Diagnostics { + r, ok := p.DataSourcesMap[t] + if !ok { + return []diag.Diagnostic{ + { + Severity: diag.Error, + Summary: fmt.Sprintf("Provider doesn't support data source: %s", t), + }, + } + } + + return r.Validate(c) +} + +// DataSources returns all of the available data sources that this +// provider implements. +func (p *Provider) DataSources() []terraform.DataSource { + keys := make([]string, 0, len(p.DataSourcesMap)) + for k := range p.DataSourcesMap { + keys = append(keys, k) + } + sort.Strings(keys) + + result := make([]terraform.DataSource, 0, len(keys)) + for _, k := range keys { + result = append(result, terraform.DataSource{ + Name: k, + + // Indicates that a provider is compiled against a new enough + // version of core to support the GetSchema method. + SchemaAvailable: true, + }) + } + + return result +} + +// UserAgent returns a string suitable for use in the User-Agent header of +// requests generated by the provider. The generated string contains the +// version of Terraform, the Plugin SDK, and the provider used to generate the +// request. `name` should be the hyphen-separated reporting name of the +// provider, and `version` should be the version of the provider. +// +// If TF_APPEND_USER_AGENT is set, its value will be appended to the returned +// string. +func (p *Provider) UserAgent(name, version string) string { + ua := fmt.Sprintf("Terraform/%s (+https://www.terraform.io) Terraform-Plugin-SDK/%s", p.TerraformVersion, meta.SDKVersionString()) + if name != "" { + ua += " " + name + if version != "" { + ua += "/" + version + } + } + + if add := os.Getenv(uaEnvVar); add != "" { + add = strings.TrimSpace(add) + if len(add) > 0 { + ua += " " + add + log.Printf("[DEBUG] Using modified User-Agent: %s", ua) + } + } + + return ua +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource.go new file mode 100644 index 00000000000..f295cab7eef --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource.go @@ -0,0 +1,809 @@ +package schema + +import ( + "context" + "errors" + "fmt" + "log" + "strconv" + + "github.com/hashicorp/go-cty/cty" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +var ReservedDataSourceFields = []string{ + "connection", + "count", + "depends_on", + "lifecycle", + "provider", + "provisioner", +} + +var ReservedResourceFields = []string{ + "connection", + "count", + "depends_on", + "id", + "lifecycle", + "provider", + "provisioner", +} + +// Resource represents a thing in Terraform that has a set of configurable +// attributes and a lifecycle (create, read, update, delete). +// +// The Resource schema is an abstraction that allows provider writers to +// worry only about CRUD operations while off-loading validation, diff +// generation, etc. to this higher level library. +// +// In spite of the name, this struct is not used only for terraform resources, +// but also for data sources. In the case of data sources, the Create, +// Update and Delete functions must not be provided. +type Resource struct { + // Schema is the schema for the configuration of this resource. + // + // The keys of this map are the configuration keys, and the values + // describe the schema of the configuration value. + // + // The schema is used to represent both configurable data as well + // as data that might be computed in the process of creating this + // resource. + Schema map[string]*Schema + + // SchemaVersion is the version number for this resource's Schema + // definition. The current SchemaVersion stored in the state for each + // resource. Provider authors can increment this version number + // when Schema semantics change. If the State's SchemaVersion is less than + // the current SchemaVersion, the InstanceState is yielded to the + // MigrateState callback, where the provider can make whatever changes it + // needs to update the state to be compatible to the latest version of the + // Schema. + // + // When unset, SchemaVersion defaults to 0, so provider authors can start + // their Versioning at any integer >= 1 + SchemaVersion int + + // MigrateState is responsible for updating an InstanceState with an old + // version to the format expected by the current version of the Schema. + // + // It is called during Refresh if the State's stored SchemaVersion is less + // than the current SchemaVersion of the Resource. + // + // The function is yielded the state's stored SchemaVersion and a pointer to + // the InstanceState that needs updating, as well as the configured + // provider's configured meta interface{}, in case the migration process + // needs to make any remote API calls. + // + // Deprecated: MigrateState is deprecated and any new changes to a resource's schema + // should be handled by StateUpgraders. Existing MigrateState implementations + // should remain for compatibility with existing state. MigrateState will + // still be called if the stored SchemaVersion is less than the + // first version of the StateUpgraders. + MigrateState StateMigrateFunc + + // StateUpgraders contains the functions responsible for upgrading an + // existing state with an old schema version to a newer schema. It is + // called specifically by Terraform when the stored schema version is less + // than the current SchemaVersion of the Resource. + // + // StateUpgraders map specific schema versions to a StateUpgrader + // function. The registered versions are expected to be ordered, + // consecutive values. The initial value may be greater than 0 to account + // for legacy schemas that weren't recorded and can be handled by + // MigrateState. + StateUpgraders []StateUpgrader + + // The functions below are the CRUD operations for this resource. + // + // Deprecated: Please use the context aware equivalents instead. Only one of + // the operations or context aware equivalent can be set, not both. + Create CreateFunc + Read ReadFunc + Update UpdateFunc + Delete DeleteFunc + + // Exists is a function that is called to check if a resource still + // exists. If this returns false, then this will affect the diff + // accordingly. If this function isn't set, it will not be called. You + // can also signal existence in the Read method by calling d.SetId("") + // if the Resource is no longer present and should be removed from state. + // The *ResourceData passed to Exists should _not_ be modified. + // + // Deprecated: ReadContext should be able to encapsulate the logic of Exists + Exists ExistsFunc + + // The functions below are the CRUD operations for this resource. + // + // The only optional operation is Update. If Update is not + // implemented, then updates will not be supported for this resource. + // + // The ResourceData parameter in the functions below are used to + // query configuration and changes for the resource as well as to set + // the ID, computed data, etc. + // + // The interface{} parameter is the result of the ConfigureFunc in + // the provider for this resource. If the provider does not define + // a ConfigureFunc, this will be nil. This parameter should be used + // to store API clients, configuration structures, etc. + // + // These functions are passed a context configured to timeout with whatever + // was set as the timeout for this operation. Useful for forwarding on to + // backend SDK's that accept context. The context will also cancel if + // Terraform sends a cancellation signal. + // + // These functions return diagnostics, allowing developers to build + // a list of warnings and errors to be presented to the Terraform user. + // The AttributePath of those diagnostics should be built within these + // functions, please consult go-cty documentation for building a cty.Path + CreateContext CreateContextFunc + ReadContext ReadContextFunc + UpdateContext UpdateContextFunc + DeleteContext DeleteContextFunc + + // CustomizeDiff is a custom function for working with the diff that + // Terraform has created for this resource - it can be used to customize the + // diff that has been created, diff values not controlled by configuration, + // or even veto the diff altogether and abort the plan. It is passed a + // *ResourceDiff, a structure similar to ResourceData but lacking most write + // functions like Set, while introducing new functions that work with the + // diff such as SetNew, SetNewComputed, and ForceNew. + // + // The phases Terraform runs this in, and the state available via functions + // like Get and GetChange, are as follows: + // + // * New resource: One run with no state + // * Existing resource: One run with state + // * Existing resource, forced new: One run with state (before ForceNew), + // then one run without state (as if new resource) + // * Tainted resource: No runs (custom diff logic is skipped) + // * Destroy: No runs (standard diff logic is skipped on destroy diffs) + // + // This function needs to be resilient to support all scenarios. + // + // For the most part, only computed fields can be customized by this + // function. + // + // This function is only allowed on regular resources (not data sources). + CustomizeDiff CustomizeDiffFunc + + // Importer is the ResourceImporter implementation for this resource. + // If this is nil, then this resource does not support importing. If + // this is non-nil, then it supports importing and ResourceImporter + // must be validated. The validity of ResourceImporter is verified + // by InternalValidate on Resource. + Importer *ResourceImporter + + // If non-empty, this string is emitted as a warning during Validate. + DeprecationMessage string + + // Timeouts allow users to specify specific time durations in which an + // operation should time out, to allow them to extend an action to suit their + // usage. For example, a user may specify a large Creation timeout for their + // AWS RDS Instance due to it's size, or restoring from a snapshot. + // Resource implementors must enable Timeout support by adding the allowed + // actions (Create, Read, Update, Delete, Default) to the Resource struct, and + // accessing them in the matching methods. + Timeouts *ResourceTimeout + + // Description is used as the description for docs, the language server and + // other user facing usage. It can be plain-text or markdown depending on the + // global DescriptionKind setting. + Description string +} + +// ShimInstanceStateFromValue converts a cty.Value to a +// terraform.InstanceState. +func (r *Resource) ShimInstanceStateFromValue(state cty.Value) (*terraform.InstanceState, error) { + // Get the raw shimmed value. While this is correct, the set hashes don't + // match those from the Schema. + s := terraform.NewInstanceStateShimmedFromValue(state, r.SchemaVersion) + + // We now rebuild the state through the ResourceData, so that the set indexes + // match what helper/schema expects. + data, err := schemaMap(r.Schema).Data(s, nil) + if err != nil { + return nil, err + } + + s = data.State() + if s == nil { + s = &terraform.InstanceState{} + } + return s, nil +} + +// The following function types are of the legacy CRUD operations. +// +// Deprecated: Please use the context aware equivalents instead. +type CreateFunc func(*ResourceData, interface{}) error +type ReadFunc func(*ResourceData, interface{}) error +type UpdateFunc func(*ResourceData, interface{}) error +type DeleteFunc func(*ResourceData, interface{}) error +type ExistsFunc func(*ResourceData, interface{}) (bool, error) + +// See Resource documentation. +type CreateContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics + +// See Resource documentation. +type ReadContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics + +// See Resource documentation. +type UpdateContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics + +// See Resource documentation. +type DeleteContextFunc func(context.Context, *ResourceData, interface{}) diag.Diagnostics + +// See Resource documentation. +type StateMigrateFunc func( + int, *terraform.InstanceState, interface{}) (*terraform.InstanceState, error) + +type StateUpgrader struct { + // Version is the version schema that this Upgrader will handle, converting + // it to Version+1. + Version int + + // Type describes the schema that this function can upgrade. Type is + // required to decode the schema if the state was stored in a legacy + // flatmap format. + Type cty.Type + + // Upgrade takes the JSON encoded state and the provider meta value, and + // upgrades the state one single schema version. The provided state is + // deocded into the default json types using a map[string]interface{}. It + // is up to the StateUpgradeFunc to ensure that the returned value can be + // encoded using the new schema. + Upgrade StateUpgradeFunc +} + +// See StateUpgrader +type StateUpgradeFunc func(ctx context.Context, rawState map[string]interface{}, meta interface{}) (map[string]interface{}, error) + +// See Resource documentation. +type CustomizeDiffFunc func(context.Context, *ResourceDiff, interface{}) error + +func (r *Resource) create(ctx context.Context, d *ResourceData, meta interface{}) diag.Diagnostics { + if r.Create != nil { + if err := r.Create(d, meta); err != nil { + return diag.FromErr(err) + } + return nil + } + ctx, cancel := context.WithTimeout(ctx, d.Timeout(TimeoutCreate)) + defer cancel() + return r.CreateContext(ctx, d, meta) +} + +func (r *Resource) read(ctx context.Context, d *ResourceData, meta interface{}) diag.Diagnostics { + if r.Read != nil { + if err := r.Read(d, meta); err != nil { + return diag.FromErr(err) + } + return nil + } + ctx, cancel := context.WithTimeout(ctx, d.Timeout(TimeoutRead)) + defer cancel() + return r.ReadContext(ctx, d, meta) +} + +func (r *Resource) update(ctx context.Context, d *ResourceData, meta interface{}) diag.Diagnostics { + if r.Update != nil { + if err := r.Update(d, meta); err != nil { + return diag.FromErr(err) + } + return nil + } + ctx, cancel := context.WithTimeout(ctx, d.Timeout(TimeoutUpdate)) + defer cancel() + return r.UpdateContext(ctx, d, meta) +} + +func (r *Resource) delete(ctx context.Context, d *ResourceData, meta interface{}) diag.Diagnostics { + if r.Delete != nil { + if err := r.Delete(d, meta); err != nil { + return diag.FromErr(err) + } + return nil + } + ctx, cancel := context.WithTimeout(ctx, d.Timeout(TimeoutDelete)) + defer cancel() + return r.DeleteContext(ctx, d, meta) +} + +// Apply creates, updates, and/or deletes a resource. +func (r *Resource) Apply( + ctx context.Context, + s *terraform.InstanceState, + d *terraform.InstanceDiff, + meta interface{}) (*terraform.InstanceState, diag.Diagnostics) { + data, err := schemaMap(r.Schema).Data(s, d) + if err != nil { + return s, diag.FromErr(err) + } + + if s != nil && data != nil { + data.providerMeta = s.ProviderMeta + } + + // Instance Diff shoould have the timeout info, need to copy it over to the + // ResourceData meta + rt := ResourceTimeout{} + if _, ok := d.Meta[TimeoutKey]; ok { + if err := rt.DiffDecode(d); err != nil { + log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) + } + } else if s != nil { + if _, ok := s.Meta[TimeoutKey]; ok { + if err := rt.StateDecode(s); err != nil { + log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) + } + } + } else { + log.Printf("[DEBUG] No meta timeoutkey found in Apply()") + } + data.timeouts = &rt + + if s == nil { + // The Terraform API dictates that this should never happen, but + // it doesn't hurt to be safe in this case. + s = new(terraform.InstanceState) + } + + var diags diag.Diagnostics + + if d.Destroy || d.RequiresNew() { + if s.ID != "" { + // Destroy the resource since it is created + diags = append(diags, r.delete(ctx, data, meta)...) + if diags.HasError() { + return r.recordCurrentSchemaVersion(data.State()), diags + } + + // Make sure the ID is gone. + data.SetId("") + } + + // If we're only destroying, and not creating, then return + // now since we're done! + if !d.RequiresNew() { + return nil, diags + } + + // Reset the data to be stateless since we just destroyed + data, err = schemaMap(r.Schema).Data(nil, d) + if err != nil { + return nil, append(diags, diag.FromErr(err)...) + } + + // data was reset, need to re-apply the parsed timeouts + data.timeouts = &rt + } + + if data.Id() == "" { + // We're creating, it is a new resource. + data.MarkNewResource() + diags = append(diags, r.create(ctx, data, meta)...) + } else { + if !r.updateFuncSet() { + return s, append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "doesn't support update", + }) + } + diags = append(diags, r.update(ctx, data, meta)...) + } + + return r.recordCurrentSchemaVersion(data.State()), diags +} + +// Diff returns a diff of this resource. +func (r *Resource) Diff( + ctx context.Context, + s *terraform.InstanceState, + c *terraform.ResourceConfig, + meta interface{}) (*terraform.InstanceDiff, error) { + + t := &ResourceTimeout{} + err := t.ConfigDecode(r, c) + + if err != nil { + return nil, fmt.Errorf("[ERR] Error decoding timeout: %s", err) + } + + instanceDiff, err := schemaMap(r.Schema).Diff(ctx, s, c, r.CustomizeDiff, meta, true) + if err != nil { + return instanceDiff, err + } + + if instanceDiff != nil { + if err := t.DiffEncode(instanceDiff); err != nil { + log.Printf("[ERR] Error encoding timeout to instance diff: %s", err) + } + } else { + log.Printf("[DEBUG] Instance Diff is nil in Diff()") + } + + return instanceDiff, err +} + +func (r *Resource) SimpleDiff( + ctx context.Context, + s *terraform.InstanceState, + c *terraform.ResourceConfig, + meta interface{}) (*terraform.InstanceDiff, error) { + + instanceDiff, err := schemaMap(r.Schema).Diff(ctx, s, c, r.CustomizeDiff, meta, false) + if err != nil { + return instanceDiff, err + } + + if instanceDiff == nil { + instanceDiff = terraform.NewInstanceDiff() + } + + // Make sure the old value is set in each of the instance diffs. + // This was done by the RequiresNew logic in the full legacy Diff. + for k, attr := range instanceDiff.Attributes { + if attr == nil { + continue + } + if s != nil { + attr.Old = s.Attributes[k] + } + } + + return instanceDiff, nil +} + +// Validate validates the resource configuration against the schema. +func (r *Resource) Validate(c *terraform.ResourceConfig) diag.Diagnostics { + diags := schemaMap(r.Schema).Validate(c) + + if r.DeprecationMessage != "" { + diags = append(diags, diag.Diagnostic{ + Severity: diag.Warning, + Summary: "Deprecated Resource", + Detail: r.DeprecationMessage, + }) + } + + return diags +} + +// ReadDataApply loads the data for a data source, given a diff that +// describes the configuration arguments and desired computed attributes. +func (r *Resource) ReadDataApply( + ctx context.Context, + d *terraform.InstanceDiff, + meta interface{}, +) (*terraform.InstanceState, diag.Diagnostics) { + // Data sources are always built completely from scratch + // on each read, so the source state is always nil. + data, err := schemaMap(r.Schema).Data(nil, d) + if err != nil { + return nil, diag.FromErr(err) + } + + diags := r.read(ctx, data, meta) + state := data.State() + if state != nil && state.ID == "" { + // Data sources can set an ID if they want, but they aren't + // required to; we'll provide a placeholder if they don't, + // to preserve the invariant that all resources have non-empty + // ids. + state.ID = "-" + } + + return r.recordCurrentSchemaVersion(state), diags +} + +// RefreshWithoutUpgrade reads the instance state, but does not call +// MigrateState or the StateUpgraders, since those are now invoked in a +// separate API call. +// RefreshWithoutUpgrade is part of the new plugin shims. +func (r *Resource) RefreshWithoutUpgrade( + ctx context.Context, + s *terraform.InstanceState, + meta interface{}) (*terraform.InstanceState, diag.Diagnostics) { + // If the ID is already somehow blank, it doesn't exist + if s.ID == "" { + return nil, nil + } + + rt := ResourceTimeout{} + if _, ok := s.Meta[TimeoutKey]; ok { + if err := rt.StateDecode(s); err != nil { + log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) + } + } + + if r.Exists != nil { + // Make a copy of data so that if it is modified it doesn't + // affect our Read later. + data, err := schemaMap(r.Schema).Data(s, nil) + if err != nil { + return s, diag.FromErr(err) + } + data.timeouts = &rt + + if s != nil { + data.providerMeta = s.ProviderMeta + } + + exists, err := r.Exists(data, meta) + if err != nil { + return s, diag.FromErr(err) + } + + if !exists { + return nil, nil + } + } + + data, err := schemaMap(r.Schema).Data(s, nil) + if err != nil { + return s, diag.FromErr(err) + } + data.timeouts = &rt + + if s != nil { + data.providerMeta = s.ProviderMeta + } + + diags := r.read(ctx, data, meta) + state := data.State() + if state != nil && state.ID == "" { + state = nil + } + + return r.recordCurrentSchemaVersion(state), diags +} + +func (r *Resource) createFuncSet() bool { + return (r.Create != nil || r.CreateContext != nil) +} + +func (r *Resource) readFuncSet() bool { + return (r.Read != nil || r.ReadContext != nil) +} + +func (r *Resource) updateFuncSet() bool { + return (r.Update != nil || r.UpdateContext != nil) +} + +func (r *Resource) deleteFuncSet() bool { + return (r.Delete != nil || r.DeleteContext != nil) +} + +// InternalValidate should be called to validate the structure +// of the resource. +// +// This should be called in a unit test for any resource to verify +// before release that a resource is properly configured for use with +// this library. +// +// Provider.InternalValidate() will automatically call this for all of +// the resources it manages, so you don't need to call this manually if it +// is part of a Provider. +func (r *Resource) InternalValidate(topSchemaMap schemaMap, writable bool) error { + if r == nil { + return errors.New("resource is nil") + } + + if !writable { + if r.createFuncSet() || r.updateFuncSet() || r.deleteFuncSet() { + return fmt.Errorf("must not implement Create, Update or Delete") + } + + // CustomizeDiff cannot be defined for read-only resources + if r.CustomizeDiff != nil { + return fmt.Errorf("cannot implement CustomizeDiff") + } + } + + tsm := topSchemaMap + + if r.isTopLevel() && writable { + // All non-Computed attributes must be ForceNew if Update is not defined + if !r.updateFuncSet() { + nonForceNewAttrs := make([]string, 0) + for k, v := range r.Schema { + if !v.ForceNew && !v.Computed { + nonForceNewAttrs = append(nonForceNewAttrs, k) + } + } + if len(nonForceNewAttrs) > 0 { + return fmt.Errorf( + "No Update defined, must set ForceNew on: %#v", nonForceNewAttrs) + } + } else { + nonUpdateableAttrs := make([]string, 0) + for k, v := range r.Schema { + if v.ForceNew || v.Computed && !v.Optional { + nonUpdateableAttrs = append(nonUpdateableAttrs, k) + } + } + updateableAttrs := len(r.Schema) - len(nonUpdateableAttrs) + if updateableAttrs == 0 { + return fmt.Errorf( + "All fields are ForceNew or Computed w/out Optional, Update is superfluous") + } + } + + tsm = schemaMap(r.Schema) + + // Destroy, and Read are required + if !r.readFuncSet() { + return fmt.Errorf("Read must be implemented") + } + if !r.deleteFuncSet() { + return fmt.Errorf("Delete must be implemented") + } + + // If we have an importer, we need to verify the importer. + if r.Importer != nil { + if err := r.Importer.InternalValidate(); err != nil { + return err + } + } + + for k, f := range tsm { + if isReservedResourceFieldName(k, f) { + return fmt.Errorf("%s is a reserved field name", k) + } + } + } + + lastVersion := -1 + for _, u := range r.StateUpgraders { + if lastVersion >= 0 && u.Version-lastVersion > 1 { + return fmt.Errorf("missing schema version between %d and %d", lastVersion, u.Version) + } + + if u.Version >= r.SchemaVersion { + return fmt.Errorf("StateUpgrader version %d is >= current version %d", u.Version, r.SchemaVersion) + } + + if !u.Type.IsObjectType() { + return fmt.Errorf("StateUpgrader %d type is not cty.Object", u.Version) + } + + if u.Upgrade == nil { + return fmt.Errorf("StateUpgrader %d missing StateUpgradeFunc", u.Version) + } + + lastVersion = u.Version + } + + if lastVersion >= 0 && lastVersion != r.SchemaVersion-1 { + return fmt.Errorf("missing StateUpgrader between %d and %d", lastVersion, r.SchemaVersion) + } + + // Data source + if r.isTopLevel() && !writable { + tsm = schemaMap(r.Schema) + for k := range tsm { + if isReservedDataSourceFieldName(k) { + return fmt.Errorf("%s is a reserved field name", k) + } + } + } + + // check context funcs are not set alongside their nonctx counterparts + if r.CreateContext != nil && r.Create != nil { + return fmt.Errorf("CreateContext and Create should not both be set") + } + if r.ReadContext != nil && r.Read != nil { + return fmt.Errorf("ReadContext and Read should not both be set") + } + if r.UpdateContext != nil && r.Update != nil { + return fmt.Errorf("UpdateContext and Update should not both be set") + } + if r.DeleteContext != nil && r.Delete != nil { + return fmt.Errorf("DeleteContext and Delete should not both be set") + } + + return schemaMap(r.Schema).InternalValidate(tsm) +} + +func isReservedDataSourceFieldName(name string) bool { + for _, reservedName := range ReservedDataSourceFields { + if name == reservedName { + return true + } + } + return false +} + +func isReservedResourceFieldName(name string, s *Schema) bool { + // Allow phasing out "id" + // See https://github.com/terraform-providers/terraform-provider-aws/pull/1626#issuecomment-328881415 + if name == "id" && s.Deprecated != "" { + return false + } + + for _, reservedName := range ReservedResourceFields { + if name == reservedName { + return true + } + } + return false +} + +// Data returns a ResourceData struct for this Resource. Each return value +// is a separate copy and can be safely modified differently. +// +// The data returned from this function has no actual affect on the Resource +// itself (including the state given to this function). +// +// This function is useful for unit tests and ResourceImporter functions. +func (r *Resource) Data(s *terraform.InstanceState) *ResourceData { + result, err := schemaMap(r.Schema).Data(s, nil) + if err != nil { + // At the time of writing, this isn't possible (Data never returns + // non-nil errors). We panic to find this in the future if we have to. + // I don't see a reason for Data to ever return an error. + panic(err) + } + + // load the Resource timeouts + result.timeouts = r.Timeouts + if result.timeouts == nil { + result.timeouts = &ResourceTimeout{} + } + + // Set the schema version to latest by default + result.meta = map[string]interface{}{ + "schema_version": strconv.Itoa(r.SchemaVersion), + } + + return result +} + +// TestResourceData Yields a ResourceData filled with this resource's schema for use in unit testing +// +// TODO: May be able to be removed with the above ResourceData function. +func (r *Resource) TestResourceData() *ResourceData { + return &ResourceData{ + schema: r.Schema, + } +} + +// Returns true if the resource is "top level" i.e. not a sub-resource. +func (r *Resource) isTopLevel() bool { + // TODO: This is a heuristic; replace with a definitive attribute? + return (r.createFuncSet() || r.readFuncSet()) +} + +func (r *Resource) recordCurrentSchemaVersion( + state *terraform.InstanceState) *terraform.InstanceState { + if state != nil && r.SchemaVersion > 0 { + if state.Meta == nil { + state.Meta = make(map[string]interface{}) + } + state.Meta["schema_version"] = strconv.Itoa(r.SchemaVersion) + } + return state +} + +// Noop is a convenience implementation of resource function which takes +// no action and returns no error. +func Noop(*ResourceData, interface{}) error { + return nil +} + +// NoopContext is a convenience implementation of context aware resource function which takes +// no action and returns no error. +func NoopContext(context.Context, *ResourceData, interface{}) diag.Diagnostics { + return nil +} + +// RemoveFromState is a convenience implementation of a resource function +// which sets the resource ID to empty string (to remove it from state) +// and returns no error. +func RemoveFromState(d *ResourceData, _ interface{}) error { + d.SetId("") + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_data.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_data.go similarity index 86% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_data.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_data.go index a8a6e223602..1906343d763 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_data.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_data.go @@ -7,32 +7,33 @@ import ( "sync" "time" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/go-cty/cty/gocty" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // ResourceData is used to query and set the attributes of a resource. // // ResourceData is the primary argument received for CRUD operations on // a resource as well as configuration of a provider. It is a powerful -// structure that can be used to not only query data, but check for changes, -// define partial state updates, etc. +// structure that can be used to not only query data, but also check for changes // -// The most relevant methods to take a look at are Get, Set, and Partial. +// The most relevant methods to take a look at are Get and Set. type ResourceData struct { // Settable (internally) - schema map[string]*Schema - config *terraform.ResourceConfig - state *terraform.InstanceState - diff *terraform.InstanceDiff - meta map[string]interface{} - timeouts *ResourceTimeout + schema map[string]*Schema + config *terraform.ResourceConfig + state *terraform.InstanceState + diff *terraform.InstanceDiff + meta map[string]interface{} + timeouts *ResourceTimeout + providerMeta cty.Value // Don't set multiReader *MultiLevelFieldReader setWriter *MapFieldWriter newState *terraform.InstanceState partial bool - partialMap map[string]struct{} once sync.Once isNew bool @@ -49,17 +50,6 @@ type getResult struct { Schema *Schema } -// UnsafeSetFieldRaw allows setting arbitrary values in state to arbitrary -// values, bypassing schema. This MUST NOT be used in normal circumstances - -// it exists only to support the remote_state data source. -// -// Deprecated: Fully define schema attributes and use Set() instead. -func (d *ResourceData) UnsafeSetFieldRaw(key string, value string) { - d.once.Do(d.init) - - d.setWriter.unsafeWriteField(key, value) -} - // Get returns the data for the given key, or nil if the key doesn't exist // in the schema. // @@ -152,23 +142,19 @@ func (d *ResourceData) HasChange(key string) bool { return !reflect.DeepEqual(o, n) } -// Partial turns partial state mode on/off. -// -// When partial state mode is enabled, then only key prefixes specified -// by SetPartial will be in the final state. This allows providers to return -// partial states for partially applied resources (when errors occur). +// Partial is a legacy function that was used for capturing state of specific +// attributes if an update only partially worked. Enabling this flag without +// setting any specific keys with the now removed SetPartial has a useful side +// effect of preserving all of the resource's previous state. Although confusing, +// it has been discovered that during an update when an error is returned, the +// proposed config is set into state, even without any calls to d.Set. // -// Deprecated: Partial state has very limited benefit given Terraform refreshes -// before operations by default. +// In practice this default behavior goes mostly unnoticed since Terraform +// refreshes between operations by default. The state situation discussed is +// subject to further investigation and potential change. Until then, this +// function has been preserved for the specific usecase. func (d *ResourceData) Partial(on bool) { d.partial = on - if on { - if d.partialMap == nil { - d.partialMap = make(map[string]struct{}) - } - } else { - d.partialMap = nil - } } // Set sets the value for the given key. @@ -197,27 +183,16 @@ func (d *ResourceData) Set(key string, value interface{}) error { } err := d.setWriter.WriteField(strings.Split(key, "."), value) - if err != nil && d.panicOnError { - panic(err) + if err != nil { + if d.panicOnError { + panic(err) + } else { + log.Printf("[ERROR] setting state: %s", err) + } } return err } -// SetPartial adds the key to the final state output while -// in partial state mode. The key must be a root key in the schema (i.e. -// it cannot be "list.0"). -// -// If partial state mode is disabled, then this has no effect. Additionally, -// whenever partial state mode is toggled, the partial data is cleared. -// -// Deprecated: Partial state has very limited benefit given Terraform refreshes -// before operations by default. -func (d *ResourceData) SetPartial(k string) { - if d.partial { - d.partialMap[k] = struct{}{} - } -} - func (d *ResourceData) MarkNewResource() { d.isNew = true } @@ -330,11 +305,7 @@ func (d *ResourceData) State() *terraform.InstanceState { source := getSourceSet if d.partial { source = getSourceState - if _, ok := d.partialMap[k]; ok { - source = getSourceSet - } } - raw := d.get([]string{k}, source) if raw.Exists && !raw.Computed { rawMap[k] = raw.Value @@ -560,3 +531,10 @@ func (d *ResourceData) get(addr []string, source getSource) getResult { Schema: schema, } } + +func (d *ResourceData) GetProviderMeta(dst interface{}) error { + if d.providerMeta.IsNull() { + return nil + } + return gocty.FromCtyValue(d.providerMeta, &dst) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_data_get_source.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_data_get_source.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_data_get_source.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_data_get_source.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_diff.go similarity index 99% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_diff.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_diff.go index f55a66e14fd..984929df7b5 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_diff.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_diff.go @@ -7,7 +7,7 @@ import ( "strings" "sync" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // newValueWriter is a minor re-implementation of MapFieldWriter to include diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_importer.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_importer.go new file mode 100644 index 00000000000..3b17c8e96d4 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_importer.go @@ -0,0 +1,79 @@ +package schema + +import ( + "context" + "errors" +) + +// ResourceImporter defines how a resource is imported in Terraform. This +// can be set onto a Resource struct to make it Importable. Not all resources +// have to be importable; if a Resource doesn't have a ResourceImporter then +// it won't be importable. +// +// "Importing" in Terraform is the process of taking an already-created +// resource and bringing it under Terraform management. This can include +// updating Terraform state, generating Terraform configuration, etc. +type ResourceImporter struct { + // State is called to convert an ID to one or more InstanceState to + // insert into the Terraform state. + // + // Deprecated: State is deprecated in favor of StateContext. + // Only one of the two functions can bet set. + State StateFunc + + // StateContext is called to convert an ID to one or more InstanceState to + // insert into the Terraform state. If this isn't specified, then + // the ID is passed straight through. This function receives a context + // that will cancel if Terraform sends a cancellation signal. + StateContext StateContextFunc +} + +// StateFunc is the function called to import a resource into the Terraform state. +// +// Deprecated: Please use the context aware equivalent StateContextFunc. +type StateFunc func(*ResourceData, interface{}) ([]*ResourceData, error) + +// StateContextFunc is the function called to import a resource into the +// Terraform state. It is given a ResourceData with only ID set. This +// ID is going to be an arbitrary value given by the user and may not map +// directly to the ID format that the resource expects, so that should +// be validated. +// +// This should return a slice of ResourceData that turn into the state +// that was imported. This might be as simple as returning only the argument +// that was given to the function. In other cases (such as AWS security groups), +// an import may fan out to multiple resources and this will have to return +// multiple. +// +// To create the ResourceData structures for other resource types (if +// you have to), instantiate your resource and call the Data function. +type StateContextFunc func(context.Context, *ResourceData, interface{}) ([]*ResourceData, error) + +// InternalValidate should be called to validate the structure of this +// importer. This should be called in a unit test. +// +// Resource.InternalValidate() will automatically call this, so this doesn't +// need to be called manually. Further, Resource.InternalValidate() is +// automatically called by Provider.InternalValidate(), so you only need +// to internal validate the provider. +func (r *ResourceImporter) InternalValidate() error { + if r.State != nil && r.StateContext != nil { + return errors.New("Both State and StateContext cannot be set.") + } + return nil +} + +// ImportStatePassthrough is an implementation of StateFunc that can be +// used to simply pass the ID directly through. +// +// Deprecated: Please use the context aware ImportStatePassthroughContext instead +func ImportStatePassthrough(d *ResourceData, m interface{}) ([]*ResourceData, error) { + return []*ResourceData{d}, nil +} + +// ImportStatePassthroughContext is an implementation of StateContextFunc that can be +// used to simply pass the ID directly through. This should be used only +// in the case that an ID-only refresh is possible. +func ImportStatePassthroughContext(ctx context.Context, d *ResourceData, m interface{}) ([]*ResourceData, error) { + return []*ResourceData{d}, nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_timeout.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_timeout.go similarity index 98% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_timeout.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_timeout.go index f12bf725961..cee0b67811f 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/resource_timeout.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/resource_timeout.go @@ -5,9 +5,10 @@ import ( "log" "time" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" - "github.com/hashicorp/terraform-plugin-sdk/terraform" "github.com/mitchellh/copystructure" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) const TimeoutKey = "e2bfb730-ecaa-11e6-8f88-34363bc7c4c0" diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/schema.go new file mode 100644 index 00000000000..24befc9d7fa --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/schema.go @@ -0,0 +1,2121 @@ +// schema is a high-level framework for easily writing new providers +// for Terraform. Usage of schema is recommended over attempting to write +// to the low-level plugin interfaces manually. +// +// schema breaks down provider creation into simple CRUD operations for +// resources. The logic of diffing, destroying before creating, updating +// or creating, etc. is all handled by the framework. The plugin author +// only needs to implement a configuration schema and the CRUD operations and +// everything else is meant to just work. +// +// A good starting point is to view the Provider structure. +package schema + +import ( + "context" + "fmt" + "log" + "os" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + + "github.com/hashicorp/go-cty/cty" + "github.com/mitchellh/copystructure" + "github.com/mitchellh/mapstructure" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +// Schema is used to describe the structure of a value. +// +// Read the documentation of the struct elements for important details. +type Schema struct { + // Type is the type of the value and must be one of the ValueType values. + // + // This type not only determines what type is expected/valid in configuring + // this value, but also what type is returned when ResourceData.Get is + // called. The types returned by Get are: + // + // TypeBool - bool + // TypeInt - int + // TypeFloat - float64 + // TypeString - string + // TypeList - []interface{} + // TypeMap - map[string]interface{} + // TypeSet - *schema.Set + // + Type ValueType + + // ConfigMode allows for overriding the default behaviors for mapping + // schema entries onto configuration constructs. + // + // By default, the Elem field is used to choose whether a particular + // schema is represented in configuration as an attribute or as a nested + // block; if Elem is a *schema.Resource then it's a block and it's an + // attribute otherwise. + // + // If Elem is *schema.Resource then setting ConfigMode to + // SchemaConfigModeAttr will force it to be represented in configuration + // as an attribute, which means that the Computed flag can be used to + // provide default elements when the argument isn't set at all, while still + // allowing the user to force zero elements by explicitly assigning an + // empty list. + // + // When Computed is set without Optional, the attribute is not settable + // in configuration at all and so SchemaConfigModeAttr is the automatic + // behavior, and SchemaConfigModeBlock is not permitted. + ConfigMode SchemaConfigMode + + // If one of these is set, then this item can come from the configuration. + // Both cannot be set. If Optional is set, the value is optional. If + // Required is set, the value is required. + // + // One of these must be set if the value is not computed. That is: + // value either comes from the config, is computed, or is both. + Optional bool + Required bool + + // If this is non-nil, the provided function will be used during diff + // of this field. If this is nil, a default diff for the type of the + // schema will be used. + // + // This allows comparison based on something other than primitive, list + // or map equality - for example SSH public keys may be considered + // equivalent regardless of trailing whitespace. + 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. + // + // 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 + // will be no default and the user will be asked to fill it in. + // + // If either of these is set, then the user won't be asked for input + // for this key if the default is not nil. + Default interface{} + DefaultFunc SchemaDefaultFunc + + // Description is used as the description for docs, the language server and + // other user facing usage. It can be plain-text or markdown depending on the + // global DescriptionKind setting. + Description string + + // InputDefault is the default value to use for when inputs are requested. + // This differs from Default in that if Default is set, no input is + // asked for. If Input is asked, this will be the default value offered. + InputDefault string + + // The fields below relate to diffs. + // + // If Computed is true, then the result of this value is computed + // (unless specified by config) on creation. + // + // If ForceNew is true, then a change in this resource necessitates + // the creation of a new resource. + // + // StateFunc is a function called to change the value of this before + // storing it in the state (and likewise before comparing for diffs). + // The use for this is for example with large strings, you may want + // to simply store the hash of it. + Computed bool + ForceNew bool + StateFunc SchemaStateFunc + + // The following fields are only set for a TypeList, TypeSet, or TypeMap. + // + // Elem represents the element type. For a TypeMap, it must be a *Schema + // with a Type that is one of the primitives: TypeString, TypeBool, + // TypeInt, or TypeFloat. Otherwise it may be either a *Schema or a + // *Resource. If it is *Schema, the element type is just a simple value. + // If it is *Resource, the element type is a complex structure, + // potentially managed via its own CRUD actions on the API. + Elem interface{} + + // The following fields are only set for a TypeList or TypeSet. + // + // MaxItems defines a maximum amount of items that can exist within a + // TypeSet or TypeList. Specific use cases would be if a TypeSet is being + // used to wrap a complex structure, however more than one instance would + // cause instability. + // + // MinItems defines a minimum amount of items that can exist within a + // TypeSet or TypeList. Specific use cases would be if a TypeSet is being + // used to wrap a complex structure, however less than one instance would + // cause instability. + // + // If the field Optional is set to true then MinItems is ignored and thus + // effectively zero. + MaxItems int + MinItems int + + // The following fields are only valid for a TypeSet type. + // + // Set defines a function to determine the unique ID of an item so that + // a proper set can be built. + Set SchemaSetFunc + + // ComputedWhen is a set of queries on the configuration. Whenever any + // of these things is changed, it will require a recompute (this requires + // that Computed is set to true). + // + // NOTE: This currently does not work. + ComputedWhen []string + + // ConflictsWith is a set of schema keys that conflict with this schema. + // This will only check that they're set in the _config_. This will not + // raise an error for a malfunctioning resource that sets a conflicting + // key. + // + // ExactlyOneOf is a set of schema keys that, when set, only one of the + // keys in that list can be specified. It will error if none are + // specified as well. + // + // AtLeastOneOf is a set of schema keys that, when set, at least one of + // the keys in that list must be specified. + // + // RequiredWith is a set of schema keys that must be set simultaneously. + ConflictsWith []string + ExactlyOneOf []string + AtLeastOneOf []string + RequiredWith []string + + // When Deprecated is set, this attribute is deprecated. + // + // A deprecated field still works, but will probably stop working in near + // future. This string is the message shown to the user with instructions on + // how to address the deprecation. + Deprecated string + + // ValidateFunc allows individual fields to define arbitrary validation + // logic. It is yielded the provided config value as an interface{} that is + // guaranteed to be of the proper Schema type, and it can yield warnings or + // errors based on inspection of that value. + // + // ValidateFunc is honored only when the schema's Type is set to TypeInt, + // TypeFloat, TypeString, TypeBool, or TypeMap. It is ignored for all other types. + // + // Deprecated: please use ValidateDiagFunc + ValidateFunc SchemaValidateFunc + + // ValidateDiagFunc allows individual fields to define arbitrary validation + // logic. It is yielded the provided config value as an interface{} that is + // guaranteed to be of the proper Schema type, and it can yield diagnostics + // based on inspection of that value. + // + // ValidateDiagFunc is honored only when the schema's Type is set to TypeInt, + // TypeFloat, TypeString, TypeBool, or TypeMap. It is ignored for all other types. + // + // ValidateDiagFunc is also yielded the cty.Path the SDK has built up to this + // attribute. The SDK will automatically set the AttributePath of any returned + // Diagnostics to this path. Therefore the developer does not need to set + // the AttributePath for primitive types. + // + // In the case of TypeMap to provide the most precise information, please + // set an AttributePath with the additional cty.IndexStep: + // + // AttributePath: cty.IndexStringPath("key_name") + // + // Or alternatively use the passed in path to create the absolute path: + // + // AttributePath: append(path, cty.IndexStep{Key: cty.StringVal("key_name")}) + ValidateDiagFunc SchemaValidateDiagFunc + + // Sensitive ensures that the attribute's value does not get displayed in + // logs or regular output. It should be used for passwords or other + // secret fields. Future versions of Terraform may encrypt these + // values. + Sensitive bool +} + +// SchemaConfigMode is used to influence how a schema item is mapped into a +// corresponding configuration construct, using the ConfigMode field of +// Schema. +type SchemaConfigMode int + +const ( + SchemaConfigModeAuto SchemaConfigMode = iota + SchemaConfigModeAttr + SchemaConfigModeBlock +) + +// SchemaDiffSuppressFunc is a function which can be used to determine +// whether a detected diff on a schema element is "valid" or not, and +// suppress it from the plan if necessary. +// +// Return true if the diff should be suppressed, false to retain it. +type SchemaDiffSuppressFunc func(k, old, new string, d *ResourceData) bool + +// SchemaDefaultFunc is a function called to return a default value for +// a field. +type SchemaDefaultFunc func() (interface{}, error) + +// EnvDefaultFunc is a helper function that returns the value of the +// given environment variable, if one exists, or the default value +// otherwise. +func EnvDefaultFunc(k string, dv interface{}) SchemaDefaultFunc { + return func() (interface{}, error) { + if v := os.Getenv(k); v != "" { + return v, nil + } + + return dv, nil + } +} + +// MultiEnvDefaultFunc is a helper function that returns the value of the first +// environment variable in the given list that returns a non-empty value. If +// none of the environment variables return a value, the default value is +// returned. +func MultiEnvDefaultFunc(ks []string, dv interface{}) SchemaDefaultFunc { + return func() (interface{}, error) { + for _, k := range ks { + if v := os.Getenv(k); v != "" { + return v, nil + } + } + return dv, nil + } +} + +// SchemaSetFunc is a function that must return a unique ID for the given +// element. This unique ID is used to store the element in a hash. +type SchemaSetFunc func(interface{}) int + +// SchemaStateFunc is a function used to convert some type to a string +// to be stored in the state. +type SchemaStateFunc func(interface{}) string + +// SchemaValidateFunc is a function used to validate a single field in the +// schema. +// +// Deprecated: please use SchemaValidateDiagFunc +type SchemaValidateFunc func(interface{}, string) ([]string, []error) + +// SchemaValidateDiagFunc is a function used to validate a single field in the +// schema and has Diagnostic support. +type SchemaValidateDiagFunc func(interface{}, cty.Path) diag.Diagnostics + +func (s *Schema) GoString() string { + return fmt.Sprintf("*%#v", *s) +} + +// Returns a default value for this schema by either reading Default or +// evaluating DefaultFunc. If neither of these are defined, returns nil. +func (s *Schema) DefaultValue() (interface{}, error) { + if s.Default != nil { + return s.Default, nil + } + + if s.DefaultFunc != nil { + defaultValue, err := s.DefaultFunc() + if err != nil { + return nil, fmt.Errorf("error loading default: %s", err) + } + return defaultValue, nil + } + + return nil, nil +} + +// Returns a zero value for the schema. +func (s *Schema) ZeroValue() interface{} { + // If it's a set then we'll do a bit of extra work to provide the + // right hashing function in our empty value. + if s.Type == TypeSet { + setFunc := s.Set + if setFunc == nil { + // Default set function uses the schema to hash the whole value + elem := s.Elem + switch t := elem.(type) { + case *Schema: + setFunc = HashSchema(t) + case *Resource: + setFunc = HashResource(t) + default: + panic("invalid set element type") + } + } + return &Set{F: setFunc} + } else { + return s.Type.Zero() + } +} + +func (s *Schema) finalizeDiff(d *terraform.ResourceAttrDiff, customized bool) *terraform.ResourceAttrDiff { + if d == nil { + return d + } + + if s.Type == TypeBool { + normalizeBoolString := func(s string) string { + switch s { + case "0": + return "false" + case "1": + return "true" + } + return s + } + d.Old = normalizeBoolString(d.Old) + d.New = normalizeBoolString(d.New) + } + + if s.Computed && !d.NewRemoved && d.New == "" { + // Computed attribute without a new value set + d.NewComputed = true + } + + if s.ForceNew { + // ForceNew, mark that this field is requiring new under the + // following conditions, explained below: + // + // * Old != New - There is a change in value. This field + // is therefore causing a new resource. + // + // * NewComputed - This field is being computed, hence a + // potential change in value, mark as causing a new resource. + d.RequiresNew = d.Old != d.New || d.NewComputed + } + + if d.NewRemoved { + return d + } + + if s.Computed { + // FIXME: This is where the customized bool from getChange finally + // comes into play. It allows the previously incorrect behavior + // of an empty string being used as "unset" when the value is + // computed. This should be removed once we can properly + // represent an unset/nil value from the configuration. + if !customized { + if d.Old != "" && d.New == "" { + // This is a computed value with an old value set already, + // just let it go. + return nil + } + } + + if d.New == "" && !d.NewComputed { + // Computed attribute without a new value set + d.NewComputed = true + } + } + + if s.Sensitive { + // Set the Sensitive flag so output is hidden in the UI + d.Sensitive = true + } + + return d +} + +func (s *Schema) validateFunc(decoded interface{}, k string, path cty.Path) diag.Diagnostics { + var diags diag.Diagnostics + + if s.ValidateDiagFunc != nil { + diags = s.ValidateDiagFunc(decoded, path) + for i := range diags { + if !diags[i].AttributePath.HasPrefix(path) { + diags[i].AttributePath = append(path, diags[i].AttributePath...) + } + } + } else if s.ValidateFunc != nil { + ws, es := s.ValidateFunc(decoded, k) + for _, w := range ws { + diags = append(diags, diag.Diagnostic{ + Severity: diag.Warning, + Summary: w, + AttributePath: path, + }) + } + for _, e := range es { + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: e.Error(), + AttributePath: path, + }) + } + } + + return diags +} + +// InternalMap is used to aid in the transition to the new schema types and +// protocol. The name is not meant to convey any usefulness, as this is not to +// be used directly by any providers. +type InternalMap = schemaMap + +// schemaMap is a wrapper that adds nice functions on top of schemas. +type schemaMap map[string]*Schema + +func (m schemaMap) panicOnError() bool { + return os.Getenv("TF_ACC") != "" +} + +// Data returns a ResourceData for the given schema, state, and diff. +// +// The diff is optional. +func (m schemaMap) Data( + s *terraform.InstanceState, + d *terraform.InstanceDiff) (*ResourceData, error) { + return &ResourceData{ + schema: m, + state: s, + diff: d, + panicOnError: m.panicOnError(), + }, nil +} + +// DeepCopy returns a copy of this schemaMap. The copy can be safely modified +// without affecting the original. +func (m *schemaMap) DeepCopy() schemaMap { + copy, err := copystructure.Config{Lock: true}.Copy(m) + if err != nil { + panic(err) + } + return *copy.(*schemaMap) +} + +// Diff returns the diff for a resource given the schema map, +// state, and configuration. +func (m schemaMap) Diff( + ctx context.Context, + s *terraform.InstanceState, + c *terraform.ResourceConfig, + customizeDiff CustomizeDiffFunc, + meta interface{}, + handleRequiresNew bool) (*terraform.InstanceDiff, error) { + result := new(terraform.InstanceDiff) + result.Attributes = make(map[string]*terraform.ResourceAttrDiff) + + // Make sure to mark if the resource is tainted + if s != nil { + result.DestroyTainted = s.Tainted + } + + d := &ResourceData{ + schema: m, + state: s, + config: c, + panicOnError: m.panicOnError(), + } + + for k, schema := range m { + err := m.diff(k, schema, result, d, false) + if err != nil { + return nil, err + } + } + + // Remove any nil diffs just to keep things clean + for k, v := range result.Attributes { + if v == nil { + delete(result.Attributes, k) + } + } + + // If this is a non-destroy diff, call any custom diff logic that has been + // defined. + if !result.DestroyTainted && customizeDiff != nil { + mc := m.DeepCopy() + rd := newResourceDiff(mc, c, s, result) + if err := customizeDiff(ctx, rd, meta); err != nil { + return nil, err + } + for _, k := range rd.UpdatedKeys() { + err := m.diff(k, mc[k], result, rd, false) + if err != nil { + return nil, err + } + } + } + + if handleRequiresNew { + // If the diff requires a new resource, then we recompute the diff + // so we have the complete new resource diff, and preserve the + // RequiresNew fields where necessary so the user knows exactly what + // caused that. + if result.RequiresNew() { + // Create the new diff + result2 := new(terraform.InstanceDiff) + result2.Attributes = make(map[string]*terraform.ResourceAttrDiff) + + // Preserve the DestroyTainted flag + result2.DestroyTainted = result.DestroyTainted + + // Reset the data to not contain state. We have to call init() + // again in order to reset the FieldReaders. + d.state = nil + d.init() + + // Perform the diff again + for k, schema := range m { + err := m.diff(k, schema, result2, d, false) + if err != nil { + return nil, err + } + } + + // Re-run customization + if !result2.DestroyTainted && customizeDiff != nil { + mc := m.DeepCopy() + rd := newResourceDiff(mc, c, d.state, result2) + if err := customizeDiff(ctx, rd, meta); err != nil { + return nil, err + } + for _, k := range rd.UpdatedKeys() { + err := m.diff(k, mc[k], result2, rd, false) + if err != nil { + return nil, err + } + } + } + + // Force all the fields to not force a new since we know what we + // want to force new. + for k, attr := range result2.Attributes { + if attr == nil { + continue + } + + if attr.RequiresNew { + attr.RequiresNew = false + } + + if s != nil { + attr.Old = s.Attributes[k] + } + } + + // Now copy in all the requires new diffs... + for k, attr := range result.Attributes { + if attr == nil { + continue + } + + newAttr, ok := result2.Attributes[k] + if !ok { + newAttr = attr + } + + if attr.RequiresNew { + newAttr.RequiresNew = true + } + + result2.Attributes[k] = newAttr + } + + // And set the diff! + result = result2 + } + + } + + // Go through and detect all of the ComputedWhens now that we've + // finished the diff. + // TODO + + if result.Empty() { + // If we don't have any diff elements, just return nil + return nil, nil + } + + return result, nil +} + +// Validate validates the configuration against this schema mapping. +func (m schemaMap) Validate(c *terraform.ResourceConfig) diag.Diagnostics { + return m.validateObject("", m, c, cty.Path{}) +} + +// InternalValidate validates the format of this schema. This should be called +// from a unit test (and not in user-path code) to verify that a schema +// is properly built. +func (m schemaMap) InternalValidate(topSchemaMap schemaMap) error { + return m.internalValidate(topSchemaMap, false) +} + +func (m schemaMap) internalValidate(topSchemaMap schemaMap, attrsOnly bool) error { + if topSchemaMap == nil { + topSchemaMap = m + } + for k, v := range m { + if v.Type == TypeInvalid { + return fmt.Errorf("%s: Type must be specified", k) + } + + if v.Optional && v.Required { + return fmt.Errorf("%s: Optional or Required must be set, not both", k) + } + + if v.Required && v.Computed { + return fmt.Errorf("%s: Cannot be both Required and Computed", k) + } + + if !v.Required && !v.Optional && !v.Computed { + return fmt.Errorf("%s: One of optional, required, or computed must be set", k) + } + + computedOnly := v.Computed && !v.Optional + + switch v.ConfigMode { + case SchemaConfigModeBlock: + if _, ok := v.Elem.(*Resource); !ok { + return fmt.Errorf("%s: ConfigMode of block is allowed only when Elem is *schema.Resource", k) + } + if attrsOnly { + return fmt.Errorf("%s: ConfigMode of block cannot be used in child of schema with ConfigMode of attribute", k) + } + if computedOnly { + return fmt.Errorf("%s: ConfigMode of block cannot be used for computed schema", k) + } + case SchemaConfigModeAttr: + // anything goes + case SchemaConfigModeAuto: + // Since "Auto" for Elem: *Resource would create a nested block, + // and that's impossible inside an attribute, we require it to be + // explicitly overridden as mode "Attr" for clarity. + if _, ok := v.Elem.(*Resource); ok { + if attrsOnly { + return fmt.Errorf("%s: in *schema.Resource with ConfigMode of attribute, so must also have ConfigMode of attribute", k) + } + } + default: + return fmt.Errorf("%s: invalid ConfigMode value", k) + } + + if v.Computed && v.Default != nil { + return fmt.Errorf("%s: Default must be nil if computed", k) + } + + if v.Required && v.Default != nil { + return fmt.Errorf("%s: Default cannot be set with Required", k) + } + + if len(v.ComputedWhen) > 0 && !v.Computed { + return fmt.Errorf("%s: ComputedWhen can only be set with Computed", k) + } + + if len(v.ConflictsWith) > 0 && v.Required { + return fmt.Errorf("%s: ConflictsWith cannot be set with Required", k) + } + + if len(v.ExactlyOneOf) > 0 && v.Required { + return fmt.Errorf("%s: ExactlyOneOf cannot be set with Required", k) + } + + if len(v.AtLeastOneOf) > 0 && v.Required { + return fmt.Errorf("%s: AtLeastOneOf cannot be set with Required", k) + } + + if len(v.ConflictsWith) > 0 { + err := checkKeysAgainstSchemaFlags(k, v.ConflictsWith, topSchemaMap, v, false) + if err != nil { + return fmt.Errorf("ConflictsWith: %+v", err) + } + } + + if len(v.RequiredWith) > 0 { + err := checkKeysAgainstSchemaFlags(k, v.RequiredWith, topSchemaMap, v, true) + if err != nil { + return fmt.Errorf("RequiredWith: %+v", err) + } + } + + if len(v.ExactlyOneOf) > 0 { + err := checkKeysAgainstSchemaFlags(k, v.ExactlyOneOf, topSchemaMap, v, true) + if err != nil { + return fmt.Errorf("ExactlyOneOf: %+v", err) + } + } + + if len(v.AtLeastOneOf) > 0 { + err := checkKeysAgainstSchemaFlags(k, v.AtLeastOneOf, topSchemaMap, v, true) + if err != nil { + return fmt.Errorf("AtLeastOneOf: %+v", err) + } + } + + if v.Type == TypeList || v.Type == TypeSet { + if v.Elem == nil { + return fmt.Errorf("%s: Elem must be set for lists", k) + } + + if v.Default != nil { + return fmt.Errorf("%s: Default is not valid for lists or sets", k) + } + + if v.Type != TypeSet && v.Set != nil { + return fmt.Errorf("%s: Set can only be set for TypeSet", k) + } + + switch t := v.Elem.(type) { + case *Resource: + attrsOnly := attrsOnly || v.ConfigMode == SchemaConfigModeAttr + + if err := schemaMap(t.Schema).internalValidate(topSchemaMap, attrsOnly); err != nil { + return err + } + case *Schema: + bad := t.Computed || t.Optional || t.Required + if bad { + return fmt.Errorf( + "%s: Elem must have only Type set", k) + } + } + } else { + if v.MaxItems > 0 || v.MinItems > 0 { + return fmt.Errorf("%s: MaxItems and MinItems are only supported on lists or sets", k) + } + } + + if v.Type == TypeMap && v.Elem != nil { + switch v.Elem.(type) { + case *Resource: + return fmt.Errorf("%s: TypeMap with Elem *Resource not supported,"+ + "use TypeList/TypeSet with Elem *Resource or TypeMap with Elem *Schema", k) + } + } + + if computedOnly { + if len(v.AtLeastOneOf) > 0 { + return fmt.Errorf("%s: AtLeastOneOf is for configurable attributes,"+ + "there's nothing to configure on computed-only field", k) + } + if len(v.ConflictsWith) > 0 { + return fmt.Errorf("%s: ConflictsWith is for configurable attributes,"+ + "there's nothing to configure on computed-only field", k) + } + if v.Default != nil { + return fmt.Errorf("%s: Default is for configurable attributes,"+ + "there's nothing to configure on computed-only field", k) + } + if v.DefaultFunc != nil { + return fmt.Errorf("%s: DefaultFunc is for configurable attributes,"+ + "there's nothing to configure 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 len(v.ExactlyOneOf) > 0 { + return fmt.Errorf("%s: ExactlyOneOf is for configurable attributes,"+ + "there's nothing to configure on computed-only field", k) + } + if v.InputDefault != "" { + return fmt.Errorf("%s: InputDefault is for configurable attributes,"+ + "there's nothing to configure on computed-only field", k) + } + if v.MaxItems > 0 { + return fmt.Errorf("%s: MaxItems is for configurable attributes,"+ + "there's nothing to configure on computed-only field", k) + } + if v.MinItems > 0 { + return fmt.Errorf("%s: MinItems is for configurable attributes,"+ + "there's nothing to configure on computed-only field", k) + } + if v.StateFunc != nil { + return fmt.Errorf("%s: StateFunc is extraneous, "+ + "value should just be changed before setting on computed-only field", k) + } + 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.ValidateDiagFunc != nil { + return fmt.Errorf("%s: ValidateDiagFunc is for validating user input, "+ + "there's nothing to validate on computed-only field", k) + } + } + + if v.ValidateFunc != nil || v.ValidateDiagFunc != nil { + switch v.Type { + case TypeList, TypeSet: + return fmt.Errorf("%s: ValidateFunc and ValidateDiagFunc are not yet supported on lists or sets.", k) + } + } + + if v.ValidateFunc != nil && v.ValidateDiagFunc != nil { + return fmt.Errorf("%s: ValidateFunc and ValidateDiagFunc cannot both be set", k) + } + + if v.Deprecated == "" { + if !isValidFieldName(k) { + return fmt.Errorf("%s: Field name may only contain lowercase alphanumeric characters & underscores.", k) + } + } + } + + return nil +} + +func checkKeysAgainstSchemaFlags(k string, keys []string, topSchemaMap schemaMap, self *Schema, allowSelfReference bool) error { + for _, key := range keys { + parts := strings.Split(key, ".") + sm := topSchemaMap + var target *Schema + for idx, part := range parts { + // Skip index fields if 0 + partInt, err := strconv.Atoi(part) + + if err == nil { + if partInt != 0 { + return fmt.Errorf("%s configuration block reference (%s) can only use the .0. index for TypeList and MaxItems: 1 configuration blocks", k, key) + } + + continue + } + + var ok bool + if target, ok = sm[part]; !ok { + return fmt.Errorf("%s references unknown attribute (%s) at part (%s)", k, key, part) + } + + subResource, ok := target.Elem.(*Resource) + + if !ok { + continue + } + + // Skip Type/MaxItems check if not the last element + if (target.Type == TypeSet || target.MaxItems != 1) && idx+1 != len(parts) { + return fmt.Errorf("%s configuration block reference (%s) can only be used with TypeList and MaxItems: 1 configuration blocks", k, key) + } + + sm = schemaMap(subResource.Schema) + } + + if target == nil { + return fmt.Errorf("%s cannot find target attribute (%s), sm: %#v", k, key, sm) + } + + if target == self && !allowSelfReference { + return fmt.Errorf("%s cannot reference self (%s)", k, key) + } + + if target.Required { + return fmt.Errorf("%s cannot contain Required attribute (%s)", k, key) + } + + if len(target.ComputedWhen) > 0 { + return fmt.Errorf("%s cannot contain Computed(When) attribute (%s)", k, key) + } + } + + return nil +} + +func isValidFieldName(name string) bool { + re := regexp.MustCompile("^[a-z0-9_]+$") + return re.MatchString(name) +} + +// resourceDiffer is an interface that is used by the private diff functions. +// This helps facilitate diff logic for both ResourceData and ResoureDiff with +// minimal divergence in code. +type resourceDiffer interface { + diffChange(string) (interface{}, interface{}, bool, bool, bool) + Get(string) interface{} + GetChange(string) (interface{}, interface{}) + GetOk(string) (interface{}, bool) + HasChange(string) bool + Id() string +} + +func (m schemaMap) diff( + k string, + schema *Schema, + diff *terraform.InstanceDiff, + d resourceDiffer, + all bool) error { + + unsupressedDiff := new(terraform.InstanceDiff) + unsupressedDiff.Attributes = make(map[string]*terraform.ResourceAttrDiff) + + var err error + switch schema.Type { + case TypeBool, TypeInt, TypeFloat, TypeString: + err = m.diffString(k, schema, unsupressedDiff, d, all) + case TypeList: + err = m.diffList(k, schema, unsupressedDiff, d, all) + case TypeMap: + err = m.diffMap(k, schema, unsupressedDiff, d, all) + case TypeSet: + err = m.diffSet(k, schema, unsupressedDiff, d, all) + default: + err = fmt.Errorf("%s: unknown type %#v", k, schema.Type) + } + + for attrK, attrV := range unsupressedDiff.Attributes { + switch rd := d.(type) { + case *ResourceData: + if schema.DiffSuppressFunc != nil && attrV != nil && + schema.DiffSuppressFunc(attrK, attrV.Old, attrV.New, rd) { + // If this attr diff is suppressed, we may still need it in the + // overall diff if it's contained within a set. Rather than + // dropping the diff, make it a NOOP. + if !all { + continue + } + + attrV = &terraform.ResourceAttrDiff{ + Old: attrV.Old, + New: attrV.Old, + } + } + } + diff.Attributes[attrK] = attrV + } + + return err +} + +func (m schemaMap) diffList( + k string, + schema *Schema, + diff *terraform.InstanceDiff, + d resourceDiffer, + all bool) error { + o, n, _, computedList, customized := d.diffChange(k) + if computedList { + n = nil + } + nSet := n != nil + + // If we have an old value and no new value is set or will be + // computed once all variables can be interpolated and we're + // computed, then nothing has changed. + if o != nil && n == nil && !computedList && schema.Computed { + return nil + } + + if o == nil { + o = []interface{}{} + } + if n == nil { + n = []interface{}{} + } + if s, ok := o.(*Set); ok { + o = s.List() + } + if s, ok := n.(*Set); ok { + n = s.List() + } + os := o.([]interface{}) + vs := n.([]interface{}) + + // If the new value was set, and the two are equal, then we're done. + // We have to do this check here because sets might be NOT + // reflect.DeepEqual so we need to wait until we get the []interface{} + if !all && nSet && reflect.DeepEqual(os, vs) { + return nil + } + + // Get the counts + oldLen := len(os) + newLen := len(vs) + oldStr := strconv.FormatInt(int64(oldLen), 10) + + // If the whole list is computed, then say that the # is computed + if computedList { + diff.Attributes[k+".#"] = &terraform.ResourceAttrDiff{ + Old: oldStr, + NewComputed: true, + RequiresNew: schema.ForceNew, + } + return nil + } + + // If the counts are not the same, then record that diff + changed := oldLen != newLen + computed := oldLen == 0 && newLen == 0 && schema.Computed + if changed || computed || all { + countSchema := &Schema{ + Type: TypeInt, + Computed: schema.Computed, + ForceNew: schema.ForceNew, + } + + newStr := "" + if !computed { + newStr = strconv.FormatInt(int64(newLen), 10) + } else { + oldStr = "" + } + + diff.Attributes[k+".#"] = countSchema.finalizeDiff( + &terraform.ResourceAttrDiff{ + Old: oldStr, + New: newStr, + }, + customized, + ) + } + + // Figure out the maximum + maxLen := oldLen + if newLen > maxLen { + maxLen = newLen + } + + switch t := schema.Elem.(type) { + case *Resource: + // This is a complex resource + for i := 0; i < maxLen; i++ { + for k2, schema := range t.Schema { + subK := fmt.Sprintf("%s.%d.%s", k, i, k2) + err := m.diff(subK, schema, diff, d, all) + if err != nil { + return err + } + } + } + case *Schema: + // Copy the schema so that we can set Computed/ForceNew from + // the parent schema (the TypeList). + t2 := *t + t2.ForceNew = schema.ForceNew + + // This is just a primitive element, so go through each and + // just diff each. + for i := 0; i < maxLen; i++ { + subK := fmt.Sprintf("%s.%d", k, i) + err := m.diff(subK, &t2, diff, d, all) + if err != nil { + return err + } + } + default: + return fmt.Errorf("%s: unknown element type (internal)", k) + } + + return nil +} + +func (m schemaMap) diffMap( + k string, + schema *Schema, + diff *terraform.InstanceDiff, + d resourceDiffer, + all bool) error { + prefix := k + "." + + // First get all the values from the state + var stateMap, configMap map[string]string + o, n, _, nComputed, customized := d.diffChange(k) + if err := mapstructure.WeakDecode(o, &stateMap); err != nil { + return fmt.Errorf("%s: %s", k, err) + } + if err := mapstructure.WeakDecode(n, &configMap); err != nil { + return fmt.Errorf("%s: %s", k, err) + } + + // Keep track of whether the state _exists_ at all prior to clearing it + stateExists := o != nil + + // Delete any count values, since we don't use those + delete(configMap, "%") + delete(stateMap, "%") + + // Check if the number of elements has changed. + oldLen, newLen := len(stateMap), len(configMap) + changed := oldLen != newLen + if oldLen != 0 && newLen == 0 && schema.Computed { + changed = false + } + + // It is computed if we have no old value, no new value, the schema + // says it is computed, and it didn't exist in the state before. The + // last point means: if it existed in the state, even empty, then it + // has already been computed. + computed := oldLen == 0 && newLen == 0 && schema.Computed && !stateExists + + // If the count has changed or we're computed, then add a diff for the + // count. "nComputed" means that the new value _contains_ a value that + // is computed. We don't do granular diffs for this yet, so we mark the + // whole map as computed. + if changed || computed || nComputed { + countSchema := &Schema{ + Type: TypeInt, + Computed: schema.Computed || nComputed, + ForceNew: schema.ForceNew, + } + + oldStr := strconv.FormatInt(int64(oldLen), 10) + newStr := "" + if !computed && !nComputed { + newStr = strconv.FormatInt(int64(newLen), 10) + } else { + oldStr = "" + } + + diff.Attributes[k+".%"] = countSchema.finalizeDiff( + &terraform.ResourceAttrDiff{ + Old: oldStr, + New: newStr, + }, + customized, + ) + } + + // If the new map is nil and we're computed, then ignore it. + if n == nil && schema.Computed { + return nil + } + + // Now we compare, preferring values from the config map + for k, v := range configMap { + old, ok := stateMap[k] + delete(stateMap, k) + + if old == v && ok && !all { + continue + } + + diff.Attributes[prefix+k] = schema.finalizeDiff( + &terraform.ResourceAttrDiff{ + Old: old, + New: v, + }, + customized, + ) + } + for k, v := range stateMap { + diff.Attributes[prefix+k] = schema.finalizeDiff( + &terraform.ResourceAttrDiff{ + Old: v, + NewRemoved: true, + }, + customized, + ) + } + + return nil +} + +func (m schemaMap) diffSet( + k string, + schema *Schema, + diff *terraform.InstanceDiff, + d resourceDiffer, + all bool) error { + + o, n, _, computedSet, customized := d.diffChange(k) + if computedSet { + n = nil + } + nSet := n != nil + + // If we have an old value and no new value is set or will be + // computed once all variables can be interpolated and we're + // computed, then nothing has changed. + if o != nil && n == nil && !computedSet && schema.Computed { + return nil + } + + if o == nil { + o = schema.ZeroValue().(*Set) + } + if n == nil { + n = schema.ZeroValue().(*Set) + } + os := o.(*Set) + ns := n.(*Set) + + // If the new value was set, compare the listCode's to determine if + // the two are equal. Comparing listCode's instead of the actual values + // is needed because there could be computed values in the set which + // would result in false positives while comparing. + if !all && nSet && reflect.DeepEqual(os.listCode(), ns.listCode()) { + return nil + } + + // Get the counts + oldLen := os.Len() + newLen := ns.Len() + oldStr := strconv.Itoa(oldLen) + newStr := strconv.Itoa(newLen) + + // Build a schema for our count + countSchema := &Schema{ + Type: TypeInt, + Computed: schema.Computed, + ForceNew: schema.ForceNew, + } + + // If the set computed then say that the # is computed + if computedSet || schema.Computed && !nSet { + // If # already exists, equals 0 and no new set is supplied, there + // is nothing to record in the diff + count, ok := d.GetOk(k + ".#") + if ok && count.(int) == 0 && !nSet && !computedSet { + return nil + } + + // Set the count but make sure that if # does not exist, we don't + // use the zeroed value + countStr := strconv.Itoa(count.(int)) + if !ok { + countStr = "" + } + + diff.Attributes[k+".#"] = countSchema.finalizeDiff( + &terraform.ResourceAttrDiff{ + Old: countStr, + NewComputed: true, + }, + customized, + ) + return nil + } + + // If the counts are not the same, then record that diff + changed := oldLen != newLen + if changed || all { + diff.Attributes[k+".#"] = countSchema.finalizeDiff( + &terraform.ResourceAttrDiff{ + Old: oldStr, + New: newStr, + }, + customized, + ) + } + + // Build the list of codes that will make up our set. This is the + // removed codes as well as all the codes in the new codes. + codes := make([][]string, 2) + codes[0] = os.Difference(ns).listCode() + codes[1] = ns.listCode() + for _, list := range codes { + for _, code := range list { + switch t := schema.Elem.(type) { + case *Resource: + // This is a complex resource + for k2, schema := range t.Schema { + subK := fmt.Sprintf("%s.%s.%s", k, code, k2) + err := m.diff(subK, schema, diff, d, true) + if err != nil { + return err + } + } + case *Schema: + // Copy the schema so that we can set Computed/ForceNew from + // the parent schema (the TypeSet). + t2 := *t + t2.ForceNew = schema.ForceNew + + // This is just a primitive element, so go through each and + // just diff each. + subK := fmt.Sprintf("%s.%s", k, code) + err := m.diff(subK, &t2, diff, d, true) + if err != nil { + return err + } + default: + return fmt.Errorf("%s: unknown element type (internal)", k) + } + } + } + + return nil +} + +func (m schemaMap) diffString( + k string, + schema *Schema, + diff *terraform.InstanceDiff, + d resourceDiffer, + all bool) error { + var originalN interface{} + var os, ns string + o, n, _, computed, customized := d.diffChange(k) + if schema.StateFunc != nil && n != nil { + originalN = n + n = schema.StateFunc(n) + } + nraw := n + if nraw == nil && o != nil { + nraw = schema.Type.Zero() + } + if err := mapstructure.WeakDecode(o, &os); err != nil { + return fmt.Errorf("%s: %s", k, err) + } + if err := mapstructure.WeakDecode(nraw, &ns); err != nil { + return fmt.Errorf("%s: %s", k, err) + } + + if os == ns && !all && !computed { + // They're the same value. If there old value is not blank or we + // have an ID, then return right away since we're already setup. + if os != "" || d.Id() != "" { + return nil + } + + // Otherwise, only continue if we're computed + if !schema.Computed { + return nil + } + } + + removed := false + if o != nil && n == nil && !computed { + removed = true + } + if removed && schema.Computed { + return nil + } + + diff.Attributes[k] = schema.finalizeDiff( + &terraform.ResourceAttrDiff{ + Old: os, + New: ns, + NewExtra: originalN, + NewRemoved: removed, + NewComputed: computed, + }, + customized, + ) + + return nil +} + +func (m schemaMap) validate( + k string, + schema *Schema, + c *terraform.ResourceConfig, + path cty.Path) diag.Diagnostics { + + var diags diag.Diagnostics + + raw, ok := c.Get(k) + if !ok && schema.DefaultFunc != nil { + // We have a dynamic default. Check if we have a value. + var err error + raw, err = schema.DefaultFunc() + if err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Loading Default", + Detail: err.Error(), + AttributePath: path, + }) + } + + // We're okay as long as we had a value set + ok = raw != nil + } + + err := validateExactlyOneAttribute(k, schema, c) + if err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "ExactlyOne", + Detail: err.Error(), + AttributePath: path, + }) + } + + err = validateAtLeastOneAttribute(k, schema, c) + if err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "AtLeastOne", + Detail: err.Error(), + AttributePath: path, + }) + } + + if !ok { + if schema.Required { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Required attribute is not set", + AttributePath: path, + }) + } + return diags + } + + if !schema.Required && !schema.Optional { + // This is a computed-only field + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Computed attribute cannot be set", + AttributePath: path, + }) + } + + err = validateRequiredWithAttribute(k, schema, c) + if err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "RequiredWith", + Detail: err.Error(), + AttributePath: path, + }) + } + + // If the value is unknown then we can't validate it yet. + // In particular, this avoids spurious type errors where downstream + // validation code sees UnknownVariableValue as being just a string. + // The SDK has to allow the unknown value through initially, so that + // Required fields set via an interpolated value are accepted. + if !isWhollyKnown(raw) { + if schema.Deprecated != "" { + return append(diags, diag.Diagnostic{ + Severity: diag.Warning, + Summary: "Attribute is deprecated", + Detail: schema.Deprecated, + AttributePath: path, + }) + } + return diags + } + + err = validateConflictingAttributes(k, schema, c) + if err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "ConflictsWith", + Detail: err.Error(), + AttributePath: path, + }) + } + + return m.validateType(k, raw, schema, c, path) +} + +// isWhollyKnown returns false if the argument contains an UnknownVariableValue +func isWhollyKnown(raw interface{}) bool { + switch raw := raw.(type) { + case string: + if raw == hcl2shim.UnknownVariableValue { + return false + } + case []interface{}: + for _, v := range raw { + if !isWhollyKnown(v) { + return false + } + } + case map[string]interface{}: + for _, v := range raw { + if !isWhollyKnown(v) { + return false + } + } + } + return true +} +func validateConflictingAttributes( + k string, + schema *Schema, + c *terraform.ResourceConfig) error { + + if len(schema.ConflictsWith) == 0 { + return nil + } + + for _, conflictingKey := range schema.ConflictsWith { + if raw, ok := c.Get(conflictingKey); ok { + if raw == hcl2shim.UnknownVariableValue { + // An unknown value might become unset (null) once known, so + // we must defer validation until it's known. + continue + } + return fmt.Errorf( + "%q: conflicts with %s", k, conflictingKey) + } + } + + return nil +} + +func removeDuplicates(elements []string) []string { + encountered := make(map[string]struct{}, 0) + result := []string{} + + for v := range elements { + if _, ok := encountered[elements[v]]; !ok { + encountered[elements[v]] = struct{}{} + result = append(result, elements[v]) + } + } + + return result +} + +func validateRequiredWithAttribute( + k string, + schema *Schema, + c *terraform.ResourceConfig) error { + + if len(schema.RequiredWith) == 0 { + return nil + } + + allKeys := removeDuplicates(append(schema.RequiredWith, k)) + sort.Strings(allKeys) + + for _, key := range allKeys { + if _, ok := c.Get(key); !ok { + return fmt.Errorf("%q: all of `%s` must be specified", k, strings.Join(allKeys, ",")) + } + } + + return nil +} + +func validateExactlyOneAttribute( + k string, + schema *Schema, + c *terraform.ResourceConfig) error { + + if len(schema.ExactlyOneOf) == 0 { + return nil + } + + allKeys := removeDuplicates(append(schema.ExactlyOneOf, k)) + sort.Strings(allKeys) + specified := make([]string, 0) + unknownVariableValueCount := 0 + for _, exactlyOneOfKey := range allKeys { + if c.IsComputed(exactlyOneOfKey) { + unknownVariableValueCount++ + continue + } + + _, ok := c.Get(exactlyOneOfKey) + if ok { + specified = append(specified, exactlyOneOfKey) + } + } + + if len(specified) == 0 && unknownVariableValueCount == 0 { + return fmt.Errorf("%q: one of `%s` must be specified", k, strings.Join(allKeys, ",")) + } + + if len(specified) > 1 { + return fmt.Errorf("%q: only one of `%s` can be specified, but `%s` were specified.", k, strings.Join(allKeys, ","), strings.Join(specified, ",")) + } + + return nil +} + +func validateAtLeastOneAttribute( + k string, + schema *Schema, + c *terraform.ResourceConfig) error { + + if len(schema.AtLeastOneOf) == 0 { + return nil + } + + allKeys := removeDuplicates(append(schema.AtLeastOneOf, k)) + sort.Strings(allKeys) + + for _, atLeastOneOfKey := range allKeys { + if _, ok := c.Get(atLeastOneOfKey); ok { + // We can ignore hcl2shim.UnknownVariable by assuming it's been set and additional validation elsewhere + // will uncover this if it is in fact null. + return nil + } + } + + return fmt.Errorf("%q: one of `%s` must be specified", k, strings.Join(allKeys, ",")) +} + +func (m schemaMap) validateList( + k string, + raw interface{}, + schema *Schema, + c *terraform.ResourceConfig, + path cty.Path) diag.Diagnostics { + + var diags diag.Diagnostics + + // first check if the list is wholly unknown + if s, ok := raw.(string); ok { + if s == hcl2shim.UnknownVariableValue { + return diags + } + } + + // schemaMap can't validate nil + if raw == nil { + return diags + } + + // We use reflection to verify the slice because you can't + // case to []interface{} unless the slice is exactly that type. + rawV := reflect.ValueOf(raw) + + if rawV.Kind() != reflect.Slice { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Attribute should be a list", + AttributePath: path, + }) + } + + // We can't validate list length if this came from a dynamic block. + // Since there's no way to determine if something was from a dynamic block + // at this point, we're going to skip validation in the new protocol if + // there are any unknowns. Validate will eventually be called again once + // all values are known. + if !isWhollyKnown(raw) { + return diags + } + + // Validate length + if schema.MaxItems > 0 && rawV.Len() > schema.MaxItems { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "List longer than MaxItems", + Detail: fmt.Sprintf("Attribute supports %d item maximum, config has %d declared", schema.MaxItems, rawV.Len()), + AttributePath: path, + }) + } + + if schema.MinItems > 0 && rawV.Len() < schema.MinItems { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "List shorter than MinItems", + Detail: fmt.Sprintf("Attribute supports %d item minimum, config has %d declared", schema.MinItems, rawV.Len()), + AttributePath: path, + }) + } + + // Now build the []interface{} + raws := make([]interface{}, rawV.Len()) + for i := range raws { + raws[i] = rawV.Index(i).Interface() + } + + for i, raw := range raws { + key := fmt.Sprintf("%s.%d", k, i) + + // Reify the key value from the ResourceConfig. + // If the list was computed we have all raw values, but some of these + // may be known in the config, and aren't individually marked as Computed. + if r, ok := c.Get(key); ok { + raw = r + } + + p := append(path, cty.IndexStep{Key: cty.NumberIntVal(int64(i))}) + + switch t := schema.Elem.(type) { + case *Resource: + // This is a sub-resource + diags = append(diags, m.validateObject(key, t.Schema, c, p)...) + case *Schema: + diags = append(diags, m.validateType(key, raw, t, c, p)...) + } + + } + + return diags +} + +func (m schemaMap) validateMap( + k string, + raw interface{}, + schema *Schema, + c *terraform.ResourceConfig, + path cty.Path) diag.Diagnostics { + + var diags diag.Diagnostics + + // first check if the list is wholly unknown + if s, ok := raw.(string); ok { + if s == hcl2shim.UnknownVariableValue { + return diags + } + } + + // schemaMap can't validate nil + if raw == nil { + return diags + } + // We use reflection to verify the slice because you can't + // case to []interface{} unless the slice is exactly that type. + rawV := reflect.ValueOf(raw) + switch rawV.Kind() { + case reflect.String: + // If raw and reified are equal, this is a string and should + // be rejected. + reified, reifiedOk := c.Get(k) + if reifiedOk && raw == reified && !c.IsComputed(k) { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Attribute should be a map", + AttributePath: path, + }) + } + // Otherwise it's likely raw is an interpolation. + return diags + case reflect.Map: + case reflect.Slice: + default: + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Attribute should be a map", + AttributePath: path, + }) + } + + // If it is not a slice, validate directly + if rawV.Kind() != reflect.Slice { + mapIface := rawV.Interface() + diags = append(diags, validateMapValues(k, mapIface.(map[string]interface{}), schema, path)...) + if diags.HasError() { + return diags + } + + return schema.validateFunc(mapIface, k, path) + } + + // It is a slice, verify that all the elements are maps + raws := make([]interface{}, rawV.Len()) + for i := range raws { + raws[i] = rawV.Index(i).Interface() + } + + for _, raw := range raws { + v := reflect.ValueOf(raw) + if v.Kind() != reflect.Map { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Attribute should be a map", + AttributePath: path, + }) + } + mapIface := v.Interface() + diags = append(diags, validateMapValues(k, mapIface.(map[string]interface{}), schema, path)...) + if diags.HasError() { + return diags + } + } + + validatableMap := make(map[string]interface{}) + for _, raw := range raws { + for k, v := range raw.(map[string]interface{}) { + validatableMap[k] = v + } + } + + return schema.validateFunc(validatableMap, k, path) +} + +func validateMapValues(k string, m map[string]interface{}, schema *Schema, path cty.Path) diag.Diagnostics { + + var diags diag.Diagnostics + + for key, raw := range m { + valueType, err := getValueType(k, schema) + p := append(path, cty.IndexStep{Key: cty.StringVal(key)}) + if err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: err.Error(), + AttributePath: p, + }) + } + + switch valueType { + case TypeBool: + var n bool + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: err.Error(), + AttributePath: p, + }) + } + case TypeInt: + var n int + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: err.Error(), + AttributePath: p, + }) + } + case TypeFloat: + var n float64 + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: err.Error(), + AttributePath: p, + }) + } + case TypeString: + var n string + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: err.Error(), + AttributePath: p, + }) + } + default: + panic(fmt.Sprintf("Unknown validation type: %#v", schema.Type)) + } + } + return diags +} + +func getValueType(k string, schema *Schema) (ValueType, error) { + if schema.Elem == nil { + return TypeString, nil + } + if vt, ok := schema.Elem.(ValueType); ok { + return vt, nil + } + + // If a Schema is provided to a Map, we use the Type of that schema + // as the type for each element in the Map. + if s, ok := schema.Elem.(*Schema); ok { + return s.Type, nil + } + + if _, ok := schema.Elem.(*Resource); ok { + // TODO: We don't actually support this (yet) + // but silently pass the validation, until we decide + // how to handle nested structures in maps + return TypeString, nil + } + return 0, fmt.Errorf("%s: unexpected map value type: %#v", k, schema.Elem) +} + +func (m schemaMap) validateObject( + k string, + schema map[string]*Schema, + c *terraform.ResourceConfig, + path cty.Path) diag.Diagnostics { + + var diags diag.Diagnostics + + raw, _ := c.Get(k) + + // schemaMap can't validate nil + if raw == nil { + return diags + } + + if _, ok := raw.(map[string]interface{}); !ok && !c.IsComputed(k) { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Expected Object Type", + Detail: fmt.Sprintf("Expected object, got %s", reflect.ValueOf(raw).Kind()), + AttributePath: path, + }) + } + + for subK, s := range schema { + key := subK + if k != "" { + key = fmt.Sprintf("%s.%s", k, subK) + } + diags = append(diags, m.validate(key, s, c, append(path, cty.GetAttrStep{Name: subK}))...) + } + + // Detect any extra/unknown keys and report those as errors. + if m, ok := raw.(map[string]interface{}); ok { + for subk := range m { + if _, ok := schema[subk]; !ok { + if subk == TimeoutsConfigKey { + continue + } + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Invalid or unknown key", + AttributePath: append(path, cty.GetAttrStep{Name: subk}), + }) + } + } + } + + return diags +} + +func (m schemaMap) validatePrimitive( + k string, + raw interface{}, + schema *Schema, + c *terraform.ResourceConfig, + path cty.Path) diag.Diagnostics { + + var diags diag.Diagnostics + + // a nil value shouldn't happen in the old protocol, and in the new + // protocol the types have already been validated. Either way, we can't + // reflect on nil, so don't panic. + if raw == nil { + return diags + } + + // Catch if the user gave a complex type where a primitive was + // expected, so we can return a friendly error message that + // doesn't contain Go type system terminology. + switch reflect.ValueOf(raw).Type().Kind() { + case reflect.Slice: + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Attribute must be a single value, not a list", + AttributePath: path, + }) + case reflect.Map: + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Attribute must be a single value, not a map", + AttributePath: path, + }) + default: // ok + } + + if c.IsComputed(k) { + // If the key is being computed, then it is not an error as + // long as it's not a slice or map. + return diags + } + + var decoded interface{} + switch schema.Type { + case TypeBool: + // Verify that we can parse this as the correct type + var n bool + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: err.Error(), + AttributePath: path, + }) + } + decoded = n + case TypeInt: + // We need to verify the type precisely, because WeakDecode will + // decode a float as an integer. + + // the config shims only use int for integral number values + if v, ok := raw.(int); ok { + decoded = v + } else { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: fmt.Sprintf("Attribute must be a whole number, got %v", raw), + AttributePath: path, + }) + } + case TypeFloat: + // Verify that we can parse this as an int + var n float64 + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: err.Error(), + AttributePath: path, + }) + } + decoded = n + case TypeString: + // Verify that we can parse this as a string + var n string + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: err.Error(), + AttributePath: path, + }) + } + decoded = n + default: + panic(fmt.Sprintf("Unknown validation type: %#v", schema.Type)) + } + + return append(diags, schema.validateFunc(decoded, k, path)...) +} + +func (m schemaMap) validateType( + k string, + raw interface{}, + schema *Schema, + c *terraform.ResourceConfig, + path cty.Path) diag.Diagnostics { + + var diags diag.Diagnostics + switch schema.Type { + case TypeList: + diags = m.validateList(k, raw, schema, c, path) + case TypeSet: + // indexing into sets is not representable in the current protocol + // best we can do is associate the path up to this attribute. + diags = m.validateList(k, raw, schema, c, path) + log.Printf("[WARN] Truncating attribute path of %d diagnostics for TypeSet", len(diags)) + for i := range diags { + diags[i].AttributePath = path + } + case TypeMap: + diags = m.validateMap(k, raw, schema, c, path) + default: + diags = m.validatePrimitive(k, raw, schema, c, path) + } + + if schema.Deprecated != "" { + diags = append(diags, diag.Diagnostic{ + Severity: diag.Warning, + Summary: "Deprecated Attribute", + Detail: schema.Deprecated, + AttributePath: path, + }) + } + + return diags +} + +// Zero returns the zero value for a type. +func (t ValueType) Zero() interface{} { + switch t { + case TypeInvalid: + return nil + case TypeBool: + return false + case TypeInt: + return 0 + case TypeFloat: + return 0.0 + case TypeString: + return "" + case TypeList: + return []interface{}{} + case TypeMap: + return map[string]interface{}{} + case TypeSet: + return new(Set) + case typeObject: + return map[string]interface{}{} + default: + panic(fmt.Sprintf("unknown type %s", t)) + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/serialize.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/serialize.go similarity index 94% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/serialize.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/serialize.go index fe6d7504c74..0e0e3cca9e5 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/serialize.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/serialize.go @@ -91,7 +91,12 @@ func SerializeResourceForHash(buf *bytes.Buffer, val interface{}, resource *Reso sm := resource.Schema m := val.(map[string]interface{}) var keys []string - for k := range sm { + allComputed := true + for k, v := range sm { + if v.Optional || v.Required { + allComputed = false + } + keys = append(keys, k) } sort.Strings(keys) @@ -100,7 +105,7 @@ func SerializeResourceForHash(buf *bytes.Buffer, val interface{}, resource *Reso // Skip attributes that are not user-provided. Computed attributes // do not contribute to the hash since their ultimate value cannot // be known at plan/diff time. - if !(innerSchema.Required || innerSchema.Optional) { + if !allComputed && !(innerSchema.Required || innerSchema.Optional) { continue } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/set.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/set.go new file mode 100644 index 00000000000..a510e60ff05 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/set.go @@ -0,0 +1,276 @@ +package schema + +import ( + "bytes" + "fmt" + "reflect" + "sort" + "strconv" + "sync" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/hashcode" +) + +// HashString hashes strings. If you want a Set of strings, this is the +// SchemaSetFunc you want. +func HashString(v interface{}) int { + return hashcode.String(v.(string)) +} + +// HashInt hashes integers. If you want a Set of integers, this is the +// SchemaSetFunc you want. +func HashInt(v interface{}) int { + return hashcode.String(strconv.Itoa(v.(int))) +} + +// HashResource hashes complex structures that are described using +// a *Resource. This is the default set implementation used when a set's +// element type is a full resource. +func HashResource(resource *Resource) SchemaSetFunc { + return func(v interface{}) int { + var buf bytes.Buffer + SerializeResourceForHash(&buf, v, resource) + return hashcode.String(buf.String()) + } +} + +// HashSchema hashes values that are described using a *Schema. This is the +// default set implementation used when a set's element type is a single +// schema. +func HashSchema(schema *Schema) SchemaSetFunc { + return func(v interface{}) int { + var buf bytes.Buffer + SerializeValueForHash(&buf, v, schema) + return hashcode.String(buf.String()) + } +} + +// Set is a set data structure that is returned for elements of type +// TypeSet. +type Set struct { + F SchemaSetFunc + + m map[string]interface{} + once sync.Once +} + +// NewSet is a convenience method for creating a new set with the given +// items. +func NewSet(f SchemaSetFunc, items []interface{}) *Set { + s := &Set{F: f} + for _, i := range items { + s.Add(i) + } + + return s +} + +// CopySet returns a copy of another set. +func CopySet(otherSet *Set) *Set { + return NewSet(otherSet.F, otherSet.List()) +} + +// Add adds an item to the set if it isn't already in the set. +func (s *Set) Add(item interface{}) { + s.add(item, false) +} + +// Remove removes an item if it's already in the set. Idempotent. +func (s *Set) Remove(item interface{}) { + s.remove(item) +} + +// Contains checks if the set has the given item. +func (s *Set) Contains(item interface{}) bool { + _, ok := s.m[s.hash(item)] + return ok +} + +// Len returns the amount of items in the set. +func (s *Set) Len() int { + return len(s.m) +} + +// List returns the elements of this set in slice format. +// +// The order of the returned elements is deterministic. Given the same +// set, the order of this will always be the same. +func (s *Set) List() []interface{} { + result := make([]interface{}, len(s.m)) + for i, k := range s.listCode() { + result[i] = s.m[k] + } + + return result +} + +// Difference performs a set difference of the two sets, returning +// a new third set that has only the elements unique to this set. +func (s *Set) Difference(other *Set) *Set { + result := &Set{F: s.F} + result.once.Do(result.init) + + for k, v := range s.m { + if _, ok := other.m[k]; !ok { + result.m[k] = v + } + } + + return result +} + +// Intersection performs the set intersection of the two sets +// and returns a new third set. +func (s *Set) Intersection(other *Set) *Set { + result := &Set{F: s.F} + result.once.Do(result.init) + + for k, v := range s.m { + if _, ok := other.m[k]; ok { + result.m[k] = v + } + } + + return result +} + +// Union performs the set union of the two sets and returns a new third +// set. +func (s *Set) Union(other *Set) *Set { + result := &Set{F: s.F} + result.once.Do(result.init) + + for k, v := range s.m { + result.m[k] = v + } + for k, v := range other.m { + result.m[k] = v + } + + return result +} + +func checkSetMapEqual(m1, m2 map[string]interface{}) bool { + if (m1 == nil) != (m2 == nil) { + return false + } + if len(m1) != len(m2) { + return false + } + for k := range m1 { + v1 := m1[k] + v2, ok := m2[k] + if !ok { + return false + } + switch v1.(type) { + case map[string]interface{}: + same := checkSetMapEqual(v1.(map[string]interface{}), v2.(map[string]interface{})) + if !same { + return false + } + case *Set: + same := v1.(*Set).Equal(v2) + if !same { + return false + } + default: + same := reflect.DeepEqual(v1, v2) + if !same { + return false + } + } + } + return true +} + +func (s *Set) Equal(raw interface{}) bool { + other, ok := raw.(*Set) + if !ok { + return false + } + return checkSetMapEqual(s.m, other.m) +} + +// HashEqual simply checks to the keys the top-level map to the keys in the +// other set's top-level map to see if they are equal. This obviously assumes +// you have a properly working hash function - use HashResource if in doubt. +func (s *Set) HashEqual(raw interface{}) bool { + other, ok := raw.(*Set) + if !ok { + return false + } + + ks1 := make([]string, 0) + ks2 := make([]string, 0) + + for k := range s.m { + ks1 = append(ks1, k) + } + for k := range other.m { + ks2 = append(ks2, k) + } + + sort.Strings(ks1) + sort.Strings(ks2) + + return reflect.DeepEqual(ks1, ks2) +} + +func (s *Set) GoString() string { + return fmt.Sprintf("*Set(%#v)", s.m) +} + +func (s *Set) init() { + s.m = make(map[string]interface{}) +} + +func (s *Set) add(item interface{}, computed bool) string { + s.once.Do(s.init) + + code := s.hash(item) + if computed { + code = "~" + code + tmpCode := code + count := 0 + for _, exists := s.m[tmpCode]; exists; _, exists = s.m[tmpCode] { + count++ + tmpCode = fmt.Sprintf("%s%d", code, count) + } + code = tmpCode + } + + if _, ok := s.m[code]; !ok { + s.m[code] = item + } + + return code +} + +func (s *Set) hash(item interface{}) string { + code := s.F(item) + // Always return a nonnegative hashcode. + if code < 0 { + code = -code + } + return strconv.Itoa(code) +} + +func (s *Set) remove(item interface{}) string { + s.once.Do(s.init) + + code := s.hash(item) + delete(s.m, code) + + return code +} + +func (s *Set) listCode() []string { + // Sort the hash codes so the order of the list is deterministic + keys := make([]string, 0, len(s.m)) + for k := range s.m { + keys = append(keys, k) + } + sort.Sort(sort.StringSlice(keys)) + return keys +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/shims.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/shims.go similarity index 81% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/shims.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/shims.go index 93c601f80ab..40a5abc0db8 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/shims.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/shims.go @@ -1,29 +1,30 @@ package schema import ( + "context" "encoding/json" - "github.com/zclconf/go-cty/cty" - ctyjson "github.com/zclconf/go-cty/cty/json" + "github.com/hashicorp/go-cty/cty" + ctyjson "github.com/hashicorp/go-cty/cty/json" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" - "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) // DiffFromValues takes the current state and desired state as cty.Values and // derives a terraform.InstanceDiff to give to the legacy providers. This is // used to take the states provided by the new ApplyResourceChange method and // convert them to a state+diff required for the legacy Apply method. -func DiffFromValues(prior, planned cty.Value, res *Resource) (*terraform.InstanceDiff, error) { - return diffFromValues(prior, planned, res, nil) +func DiffFromValues(ctx context.Context, prior, planned cty.Value, res *Resource) (*terraform.InstanceDiff, error) { + return diffFromValues(ctx, prior, planned, res, nil) } // diffFromValues takes an additional CustomizeDiffFunc, so we can generate our // test fixtures from the legacy tests. In the new provider protocol the diff // only needs to be created for the apply operation, and any customizations // have already been done. -func diffFromValues(prior, planned cty.Value, res *Resource, cust CustomizeDiffFunc) (*terraform.InstanceDiff, error) { +func diffFromValues(ctx context.Context, prior, planned cty.Value, res *Resource, cust CustomizeDiffFunc) (*terraform.InstanceDiff, error) { instanceState, err := res.ShimInstanceStateFromValue(prior) if err != nil { return nil, err @@ -35,7 +36,7 @@ func diffFromValues(prior, planned cty.Value, res *Resource, cust CustomizeDiffF removeConfigUnknowns(cfg.Config) removeConfigUnknowns(cfg.Raw) - diff, err := schemaMap(res.Schema).Diff(instanceState, cfg, cust, nil, false) + diff, err := schemaMap(res.Schema).Diff(ctx, instanceState, cfg, cust, nil, false) if err != nil { return nil, err } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/testing.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/testing.go new file mode 100644 index 00000000000..f345f832631 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/testing.go @@ -0,0 +1,29 @@ +package schema + +import ( + "context" + + testing "github.com/mitchellh/go-testing-interface" + + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +// TestResourceDataRaw creates a ResourceData from a raw configuration map. +func TestResourceDataRaw(t testing.T, schema map[string]*Schema, raw map[string]interface{}) *ResourceData { + t.Helper() + + c := terraform.NewResourceConfigRaw(raw) + + sm := schemaMap(schema) + diff, err := sm.Diff(context.Background(), nil, c, nil, nil, true) + if err != nil { + t.Fatalf("err: %s", err) + } + + result, err := sm.Data(nil, diff) + if err != nil { + t.Fatalf("err: %s", err) + } + + return result +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/valuetype.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/valuetype.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/valuetype.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/valuetype.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/valuetype_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/valuetype_string.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/schema/valuetype_string.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema/valuetype_string.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/structure/expand_json.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/expand_json.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/structure/expand_json.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/expand_json.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/structure/flatten_json.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/flatten_json.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/structure/flatten_json.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/flatten_json.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/structure/normalize_json.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/normalize_json.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/structure/normalize_json.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/normalize_json.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/structure/suppress_json_diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/suppress_json_diff.go similarity index 83% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/structure/suppress_json_diff.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/suppress_json_diff.go index e23707f574c..741ca0ac2e9 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/structure/suppress_json_diff.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure/suppress_json_diff.go @@ -3,7 +3,7 @@ package structure import ( "reflect" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func SuppressJsonDiff(k, old, new string, d *schema.ResourceData) bool { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/float.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/float.go similarity index 96% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/float.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/float.go index f0bfbfa530d..05a30531e2d 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/float.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/float.go @@ -3,7 +3,7 @@ package validation import ( "fmt" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // FloatBetween returns a SchemaValidateFunc which tests if the provided value diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/int.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/int.go new file mode 100644 index 00000000000..f2738201cc0 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/int.go @@ -0,0 +1,125 @@ +package validation + +import ( + "fmt" + "math" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +// IntBetween returns a SchemaValidateFunc which tests if the provided value +// is of type int and is between min and max (inclusive) +func IntBetween(min, max int) schema.SchemaValidateFunc { + return func(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(int) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) + return warnings, errors + } + + if v < min || v > max { + errors = append(errors, fmt.Errorf("expected %s to be in the range (%d - %d), got %d", k, min, max, v)) + return warnings, errors + } + + return warnings, errors + } +} + +// IntAtLeast returns a SchemaValidateFunc which tests if the provided value +// is of type int and is at least min (inclusive) +func IntAtLeast(min int) schema.SchemaValidateFunc { + return func(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(int) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) + return warnings, errors + } + + if v < min { + errors = append(errors, fmt.Errorf("expected %s to be at least (%d), got %d", k, min, v)) + return warnings, errors + } + + return warnings, errors + } +} + +// IntAtMost returns a SchemaValidateFunc which tests if the provided value +// is of type int and is at most max (inclusive) +func IntAtMost(max int) schema.SchemaValidateFunc { + return func(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(int) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) + return warnings, errors + } + + if v > max { + errors = append(errors, fmt.Errorf("expected %s to be at most (%d), got %d", k, max, v)) + return warnings, errors + } + + return warnings, errors + } +} + +// IntDivisibleBy returns a SchemaValidateFunc which tests if the provided value +// is of type int and is divisible by a given number +func IntDivisibleBy(divisor int) schema.SchemaValidateFunc { + return func(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(int) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) + return warnings, errors + } + + if math.Mod(float64(v), float64(divisor)) != 0 { + errors = append(errors, fmt.Errorf("expected %s to be divisible by %d, got: %v", k, divisor, i)) + return warnings, errors + } + + return warnings, errors + } +} + +// IntInSlice returns a SchemaValidateFunc which tests if the provided value +// is of type int and matches the value of an element in the valid slice +func IntInSlice(valid []int) schema.SchemaValidateFunc { + return func(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(int) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) + return warnings, errors + } + + for _, validInt := range valid { + if v == validInt { + return warnings, errors + } + } + + errors = append(errors, fmt.Errorf("expected %s to be one of %v, got %d", k, valid, v)) + return warnings, errors + } +} + +// IntNotInSlice returns a SchemaValidateFunc which tests if the provided value +// is of type int and matches the value of an element in the valid slice +func IntNotInSlice(valid []int) schema.SchemaValidateFunc { + return func(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(int) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be integer", k)) + return warnings, errors + } + + for _, validInt := range valid { + if v == validInt { + errors = append(errors, fmt.Errorf("expected %s to not be one of %v, got %d", k, valid, v)) + } + } + + return warnings, errors + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/list.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/list.go new file mode 100644 index 00000000000..75702b5b8a3 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/list.go @@ -0,0 +1,32 @@ +package validation + +import "fmt" + +// ListOfUniqueStrings is a ValidateFunc that ensures a list has no +// duplicate items in it. It's useful for when a list is needed over a set +// because order matters, yet the items still need to be unique. +func ListOfUniqueStrings(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.([]interface{}) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %q to be List", k)) + return warnings, errors + } + + for _, e := range v { + if _, eok := e.(string); !eok { + errors = append(errors, fmt.Errorf("expected %q to only contain string elements, found :%v", k, e)) + return warnings, errors + } + } + + for n1, i1 := range v { + for n2, i2 := range v { + if i1.(string) == i2.(string) && n1 != n2 { + errors = append(errors, fmt.Errorf("expected %q to not have duplicates: found 2 or more of %v", k, i1)) + return warnings, errors + } + } + } + + return warnings, errors +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/map.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/map.go new file mode 100644 index 00000000000..3e8068a8c09 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/map.go @@ -0,0 +1,155 @@ +package validation + +import ( + "fmt" + "regexp" + "sort" + + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +// MapKeyLenBetween returns a SchemaValidateDiagFunc which tests if the provided value +// is of type map and the length of all keys are between min and max (inclusive) +func MapKeyLenBetween(min, max int) schema.SchemaValidateDiagFunc { + return func(v interface{}, path cty.Path) diag.Diagnostics { + var diags diag.Diagnostics + + for _, key := range sortedKeys(v.(map[string]interface{})) { + len := len(key) + if len < min || len > max { + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Bad map key length", + Detail: fmt.Sprintf("Map key lengths should be in the range (%d - %d): %s (length = %d)", min, max, key, len), + AttributePath: append(path, cty.IndexStep{Key: cty.StringVal(key)}), + }) + } + } + + return diags + } +} + +// MapValueLenBetween returns a SchemaValidateDiagFunc which tests if the provided value +// is of type map and the length of all values are between min and max (inclusive) +func MapValueLenBetween(min, max int) schema.SchemaValidateDiagFunc { + return func(v interface{}, path cty.Path) diag.Diagnostics { + var diags diag.Diagnostics + + m := v.(map[string]interface{}) + + for _, key := range sortedKeys(m) { + val := m[key] + + if _, ok := val.(string); !ok { + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Bad map value type", + Detail: fmt.Sprintf("Map values should be strings: %s => %v (type = %T)", key, val, val), + AttributePath: append(path, cty.IndexStep{Key: cty.StringVal(key)}), + }) + continue + } + + len := len(val.(string)) + if len < min || len > max { + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Bad map value length", + Detail: fmt.Sprintf("Map value lengths should be in the range (%d - %d): %s => %v (length = %d)", min, max, key, val, len), + AttributePath: append(path, cty.IndexStep{Key: cty.StringVal(key)}), + }) + } + } + + return diags + } +} + +// MapKeyMatch returns a SchemaValidateDiagFunc which tests if the provided value +// is of type map and all keys match a given regexp. Optionally an error message +// can be provided to return something friendlier than "expected to match some globby regexp". +func MapKeyMatch(r *regexp.Regexp, message string) schema.SchemaValidateDiagFunc { + return func(v interface{}, path cty.Path) diag.Diagnostics { + var diags diag.Diagnostics + + for _, key := range sortedKeys(v.(map[string]interface{})) { + if ok := r.MatchString(key); !ok { + var detail string + if message == "" { + detail = fmt.Sprintf("Map key expected to match regular expression %q: %s", r, key) + } else { + detail = fmt.Sprintf("%s: %s", message, key) + } + + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Invalid map key", + Detail: detail, + AttributePath: append(path, cty.IndexStep{Key: cty.StringVal(key)}), + }) + } + } + + return diags + } +} + +// MapValueMatch returns a SchemaValidateDiagFunc which tests if the provided value +// is of type map and all values match a given regexp. Optionally an error message +// can be provided to return something friendlier than "expected to match some globby regexp". +func MapValueMatch(r *regexp.Regexp, message string) schema.SchemaValidateDiagFunc { + return func(v interface{}, path cty.Path) diag.Diagnostics { + var diags diag.Diagnostics + + m := v.(map[string]interface{}) + + for _, key := range sortedKeys(m) { + val := m[key] + + if _, ok := val.(string); !ok { + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Bad map value type", + Detail: fmt.Sprintf("Map values should be strings: %s => %v (type = %T)", key, val, val), + AttributePath: append(path, cty.IndexStep{Key: cty.StringVal(key)}), + }) + continue + } + + if ok := r.MatchString(val.(string)); !ok { + var detail string + if message == "" { + detail = fmt.Sprintf("Map value expected to match regular expression %q: %s => %v", r, key, val) + } else { + detail = fmt.Sprintf("%s: %s => %v", message, key, val) + } + + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: "Invalid map value", + Detail: detail, + AttributePath: append(path, cty.IndexStep{Key: cty.StringVal(key)}), + }) + } + } + + return diags + } +} + +func sortedKeys(m map[string]interface{}) []string { + keys := make([]string, len(m)) + + i := 0 + for key := range m { + keys[i] = key + i++ + } + + sort.Strings(keys) + + return keys +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/meta.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/meta.go new file mode 100644 index 00000000000..344f8ba1fee --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/meta.go @@ -0,0 +1,59 @@ +package validation + +import ( + "fmt" + "reflect" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +// NoZeroValues is a SchemaValidateFunc which tests if the provided value is +// not a zero value. It's useful in situations where you want to catch +// explicit zero values on things like required fields during validation. +func NoZeroValues(i interface{}, k string) (s []string, es []error) { + if reflect.ValueOf(i).Interface() == reflect.Zero(reflect.TypeOf(i)).Interface() { + switch reflect.TypeOf(i).Kind() { + case reflect.String: + es = append(es, fmt.Errorf("%s must not be empty, got %v", k, i)) + case reflect.Int, reflect.Float64: + es = append(es, fmt.Errorf("%s must not be zero, got %v", k, i)) + default: + // this validator should only ever be applied to TypeString, TypeInt and TypeFloat + panic(fmt.Errorf("can't use NoZeroValues with %T attribute %s", i, k)) + } + } + return +} + +// All returns a SchemaValidateFunc which tests if the provided value +// passes all provided SchemaValidateFunc +func All(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc { + return func(i interface{}, k string) ([]string, []error) { + var allErrors []error + var allWarnings []string + for _, validator := range validators { + validatorWarnings, validatorErrors := validator(i, k) + allWarnings = append(allWarnings, validatorWarnings...) + allErrors = append(allErrors, validatorErrors...) + } + return allWarnings, allErrors + } +} + +// Any returns a SchemaValidateFunc which tests if the provided value +// passes any of the provided SchemaValidateFunc +func Any(validators ...schema.SchemaValidateFunc) schema.SchemaValidateFunc { + return func(i interface{}, k string) ([]string, []error) { + var allErrors []error + var allWarnings []string + for _, validator := range validators { + validatorWarnings, validatorErrors := validator(i, k) + if len(validatorWarnings) == 0 && len(validatorErrors) == 0 { + return []string{}, []error{} + } + allWarnings = append(allWarnings, validatorWarnings...) + allErrors = append(allErrors, validatorErrors...) + } + return allWarnings, allErrors + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/network.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/network.go similarity index 86% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/network.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/network.go index 4fea7179878..8aa7139a004 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/network.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/network.go @@ -6,17 +6,9 @@ import ( "net" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) -// SingleIP returns a SchemaValidateFunc which tests if the provided value -// is of type string, and in valid single Value notation -// -// Deprecated: use IsIPAddress instead -func SingleIP() schema.SchemaValidateFunc { - return IsIPAddress -} - // IsIPAddress is a SchemaValidateFunc which tests if the provided value is of type string and is a single IP (v4 or v6) func IsIPAddress(i interface{}, k string) (warnings []string, errors []error) { v, ok := i.(string) @@ -65,13 +57,6 @@ func IsIPv4Address(i interface{}, k string) (warnings []string, errors []error) return warnings, errors } -// IPRange returns a SchemaValidateFunc which tests if the provided value is of type string, and in valid IP range -// -// Deprecated: use IsIPv4Range instead -func IPRange() schema.SchemaValidateFunc { - return IsIPv4Range -} - // IsIPv4Range is a SchemaValidateFunc which tests if the provided value is of type string, and in valid IP range func IsIPv4Range(i interface{}, k string) (warnings []string, errors []error) { v, ok := i.(string) @@ -110,14 +95,6 @@ func IsCIDR(i interface{}, k string) (warnings []string, errors []error) { return warnings, errors } -// CIDRNetwork returns a SchemaValidateFunc which tests if the provided value -// is of type string, is in valid Value network notation, and has significant bits between min and max (inclusive) -// -// Deprecated: use IsCIDRNetwork instead -func CIDRNetwork(min, max int) schema.SchemaValidateFunc { - return IsCIDRNetwork(min, max) -} - // IsCIDRNetwork returns a SchemaValidateFunc which tests if the provided value // is of type string, is in valid Value network notation, and has significant bits between min and max (inclusive) func IsCIDRNetwork(min, max int) schema.SchemaValidateFunc { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/strings.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/strings.go new file mode 100644 index 00000000000..c0c17d01164 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/strings.go @@ -0,0 +1,237 @@ +package validation + +import ( + "encoding/base64" + "fmt" + "regexp" + "strings" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" +) + +// StringIsNotEmpty is a ValidateFunc that ensures a string is not empty +func StringIsNotEmpty(i interface{}, k string) ([]string, []error) { + v, ok := i.(string) + if !ok { + return nil, []error{fmt.Errorf("expected type of %q to be string", k)} + } + + if v == "" { + return nil, []error{fmt.Errorf("expected %q to not be an empty string, got %v", k, i)} + } + + return nil, nil +} + +// StringIsNotWhiteSpace is a ValidateFunc that ensures a string is not empty or consisting entirely of whitespace characters +func StringIsNotWhiteSpace(i interface{}, k string) ([]string, []error) { + v, ok := i.(string) + if !ok { + return nil, []error{fmt.Errorf("expected type of %q to be string", k)} + } + + if strings.TrimSpace(v) == "" { + return nil, []error{fmt.Errorf("expected %q to not be an empty string or whitespace", k)} + } + + return nil, nil +} + +// StringIsEmpty is a ValidateFunc that ensures a string has no characters +func StringIsEmpty(i interface{}, k string) ([]string, []error) { + v, ok := i.(string) + if !ok { + return nil, []error{fmt.Errorf("expected type of %q to be string", k)} + } + + if v != "" { + return nil, []error{fmt.Errorf("expected %q to be an empty string: got %v", k, v)} + } + + return nil, nil +} + +// StringIsWhiteSpace is a ValidateFunc that ensures a string is composed of entirely whitespace +func StringIsWhiteSpace(i interface{}, k string) ([]string, []error) { + v, ok := i.(string) + if !ok { + return nil, []error{fmt.Errorf("expected type of %q to be string", k)} + } + + if strings.TrimSpace(v) != "" { + return nil, []error{fmt.Errorf("expected %q to be an empty string or whitespace: got %v", k, v)} + } + + return nil, nil +} + +// StringLenBetween returns a SchemaValidateFunc which tests if the provided value +// is of type string and has length between min and max (inclusive) +func StringLenBetween(min, max int) schema.SchemaValidateFunc { + return func(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) + return warnings, errors + } + + if len(v) < min || len(v) > max { + errors = append(errors, fmt.Errorf("expected length of %s to be in the range (%d - %d), got %s", k, min, max, v)) + } + + return warnings, errors + } +} + +// StringMatch returns a SchemaValidateFunc which tests if the provided value +// matches a given regexp. Optionally an error message can be provided to +// return something friendlier than "must match some globby regexp". +func StringMatch(r *regexp.Regexp, message string) schema.SchemaValidateFunc { + return func(i interface{}, k string) ([]string, []error) { + v, ok := i.(string) + if !ok { + return nil, []error{fmt.Errorf("expected type of %s to be string", k)} + } + + if ok := r.MatchString(v); !ok { + if message != "" { + return nil, []error{fmt.Errorf("invalid value for %s (%s)", k, message)} + + } + return nil, []error{fmt.Errorf("expected value of %s to match regular expression %q, got %v", k, r, i)} + } + return nil, nil + } +} + +// StringDoesNotMatch returns a SchemaValidateFunc which tests if the provided value +// does not match a given regexp. Optionally an error message can be provided to +// return something friendlier than "must not match some globby regexp". +func StringDoesNotMatch(r *regexp.Regexp, message string) schema.SchemaValidateFunc { + return func(i interface{}, k string) ([]string, []error) { + v, ok := i.(string) + if !ok { + return nil, []error{fmt.Errorf("expected type of %s to be string", k)} + } + + if ok := r.MatchString(v); ok { + if message != "" { + return nil, []error{fmt.Errorf("invalid value for %s (%s)", k, message)} + + } + return nil, []error{fmt.Errorf("expected value of %s to not match regular expression %q, got %v", k, r, i)} + } + return nil, nil + } +} + +// StringInSlice returns a SchemaValidateFunc which tests if the provided value +// is of type string and matches the value of an element in the valid slice +// will test with in lower case if ignoreCase is true +func StringInSlice(valid []string, ignoreCase bool) schema.SchemaValidateFunc { + return func(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) + return warnings, errors + } + + for _, str := range valid { + if v == str || (ignoreCase && strings.ToLower(v) == strings.ToLower(str)) { + return warnings, errors + } + } + + errors = append(errors, fmt.Errorf("expected %s to be one of %v, got %s", k, valid, v)) + return warnings, errors + } +} + +// StringNotInSlice returns a SchemaValidateFunc which tests if the provided value +// is of type string and does not match the value of any element in the invalid slice +// will test with in lower case if ignoreCase is true +func StringNotInSlice(invalid []string, ignoreCase bool) schema.SchemaValidateFunc { + return func(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) + return warnings, errors + } + + for _, str := range invalid { + if v == str || (ignoreCase && strings.ToLower(v) == strings.ToLower(str)) { + errors = append(errors, fmt.Errorf("expected %s to not be any of %v, got %s", k, invalid, v)) + return warnings, errors + } + } + + return warnings, errors + } +} + +// StringDoesNotContainAny returns a SchemaValidateFunc which validates that the +// provided value does not contain any of the specified Unicode code points in chars. +func StringDoesNotContainAny(chars string) schema.SchemaValidateFunc { + return func(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) + return warnings, errors + } + + if strings.ContainsAny(v, chars) { + errors = append(errors, fmt.Errorf("expected value of %s to not contain any of %q, got %v", k, chars, i)) + return warnings, errors + } + + return warnings, errors + } +} + +// StringIsBase64 is a ValidateFunc that ensures a string can be parsed as Base64 +func StringIsBase64(i interface{}, k string) (warnings []string, errors []error) { + // Empty string is not allowed + if warnings, errors = StringIsNotEmpty(i, k); len(errors) > 0 { + return + } + + // NoEmptyStrings checks it is a string + v, _ := i.(string) + + if _, err := base64.StdEncoding.DecodeString(v); err != nil { + errors = append(errors, fmt.Errorf("expected %q to be a base64 string, got %v", k, v)) + } + + return warnings, errors +} + +// StringIsJSON is a SchemaValidateFunc which tests to make sure the supplied string is valid JSON. +func StringIsJSON(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) + return warnings, errors + } + + if _, err := structure.NormalizeJsonString(v); err != nil { + errors = append(errors, fmt.Errorf("%q contains an invalid JSON: %s", k, err)) + } + + return warnings, errors +} + +// StringIsValidRegExp returns a SchemaValidateFunc which tests to make sure the supplied string is a valid regular expression. +func StringIsValidRegExp(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %s to be string", k)) + return warnings, errors + } + + if _, err := regexp.Compile(v); err != nil { + errors = append(errors, fmt.Errorf("%q: %s", k, err)) + } + + return warnings, errors +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/testing.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/testing.go new file mode 100644 index 00000000000..c76a4ed999f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/testing.go @@ -0,0 +1,46 @@ +package validation + +import ( + "regexp" + + testing "github.com/mitchellh/go-testing-interface" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +type testCase struct { + val interface{} + f schema.SchemaValidateFunc + expectedErr *regexp.Regexp +} + +func runTestCases(t testing.T, cases []testCase) { + t.Helper() + + matchErr := func(errs []error, r *regexp.Regexp) bool { + // err must match one provided + for _, err := range errs { + if r.MatchString(err.Error()) { + return true + } + } + + return false + } + + for i, tc := range cases { + _, errs := tc.f(tc.val, "test_property") + + if len(errs) == 0 && tc.expectedErr == nil { + continue + } + + if len(errs) != 0 && tc.expectedErr == nil { + t.Fatalf("expected test case %d to produce no errors, got %v", i, errs) + } + + if !matchErr(errs, tc.expectedErr) { + t.Fatalf("expected test case %d to produce error matching \"%s\", got %v", i, tc.expectedErr, errs) + } + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/time.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/time.go new file mode 100644 index 00000000000..df3e2620c6f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/time.go @@ -0,0 +1,54 @@ +package validation + +import ( + "fmt" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +// IsDayOfTheWeek id a SchemaValidateFunc which tests if the provided value is of type string and a valid english day of the week +func IsDayOfTheWeek(ignoreCase bool) schema.SchemaValidateFunc { + return StringInSlice([]string{ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", + }, ignoreCase) +} + +// IsMonth id a SchemaValidateFunc which tests if the provided value is of type string and a valid english month +func IsMonth(ignoreCase bool) schema.SchemaValidateFunc { + return StringInSlice([]string{ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", + }, ignoreCase) +} + +// IsRFC3339Time is a SchemaValidateFunc which tests if the provided value is of type string and a valid RFC33349Time +func IsRFC3339Time(i interface{}, k string) (warnings []string, errors []error) { + v, ok := i.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) + return warnings, errors + } + + if _, err := time.Parse(time.RFC3339, v); err != nil { + errors = append(errors, fmt.Errorf("expected %q to be a valid RFC3339 date, got %q: %+v", k, i, err)) + } + + return warnings, errors +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/uuid.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/uuid.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/uuid.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/uuid.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/web.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/web.go similarity index 96% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/web.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/web.go index eb5437f14bf..615e0feb7c1 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/validation/web.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation/web.go @@ -5,7 +5,7 @@ import ( "net/url" "strings" - "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) // IsURLWithHTTPS is a SchemaValidateFunc which tests if the provided value is of type string and a valid HTTPS URL diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/doc.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/doc.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/doc.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/instance_key.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/instance_key.go new file mode 100644 index 00000000000..064aeda28c3 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/instance_key.go @@ -0,0 +1,47 @@ +package addrs + +import ( + "fmt" +) + +// instanceKey represents the key of an instance within an object that +// contains multiple instances due to using "count" or "for_each" arguments +// in configuration. +// +// intKey and stringKey are the two implementations of this type. No other +// implementations are allowed. The single instance of an object that _isn't_ +// using "count" or "for_each" is represented by NoKey, which is a nil +// InstanceKey. +type instanceKey interface { + instanceKeySigil() + String() string +} + +// NoKey represents the absense of an instanceKey, for the single instance +// of a configuration object that does not use "count" or "for_each" at all. +var NoKey instanceKey + +// intKey is the InstanceKey representation representing integer indices, as +// used when the "count" argument is specified or if for_each is used with +// a sequence type. +type intKey int + +func (k intKey) instanceKeySigil() { +} + +func (k intKey) String() string { + return fmt.Sprintf("[%d]", int(k)) +} + +// stringKey is the InstanceKey representation representing string indices, as +// used when the "for_each" argument is specified with a map or object type. +type stringKey string + +func (k stringKey) instanceKeySigil() { +} + +func (k stringKey) String() string { + // FIXME: This isn't _quite_ right because Go's quoted string syntax is + // slightly different than HCL's, but we'll accept it for now. + return fmt.Sprintf("[%q]", string(k)) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/module.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/module.go new file mode 100644 index 00000000000..98699f46e27 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/module.go @@ -0,0 +1,13 @@ +package addrs + +// Module is an address for a module call within configuration. This is +// the static counterpart of ModuleInstance, representing a traversal through +// the static module call tree in configuration and does not take into account +// the potentially-multiple instances of a module that might be created by +// "count" and "for_each" arguments within those calls. +// +// This type should be used only in very specialized cases when working with +// the static module call tree. Type ModuleInstance is appropriate in more cases. +// +// Although Module is a slice, it should be treated as immutable after creation. +type Module []string diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/module_instance.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/module_instance.go new file mode 100644 index 00000000000..f31d833d2a8 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/module_instance.go @@ -0,0 +1,241 @@ +package addrs + +import ( + "bytes" + "fmt" + + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/hclsyntax" + "github.com/zclconf/go-cty/cty" + "github.com/zclconf/go-cty/cty/gocty" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags" +) + +// ModuleInstance is an address for a particular module instance within the +// dynamic module tree. This is an extension of the static traversals +// represented by type Module that deals with the possibility of a single +// module call producing multiple instances via the "count" and "for_each" +// arguments. +// +// Although ModuleInstance is a slice, it should be treated as immutable after +// creation. +type ModuleInstance []ModuleInstanceStep + +func parseModuleInstance(traversal hcl.Traversal) (ModuleInstance, tfdiags.Diagnostics) { + mi, remain, diags := parseModuleInstancePrefix(traversal) + if len(remain) != 0 { + if len(remain) == len(traversal) { + diags = append(diags, tfdiags.Diag( + tfdiags.Error, + "Invalid module instance address", + "A module instance address must begin with \"module.\".", + )) + } else { + diags = append(diags, tfdiags.Diag( + tfdiags.Error, + "Invalid module instance address", + "The module instance address is followed by additional invalid content.", + )) + } + } + return mi, diags +} + +// ParseModuleInstanceStr is a helper wrapper around ParseModuleInstance +// that takes a string and parses it with the HCL native syntax traversal parser +// before interpreting it. +// +// This should be used only in specialized situations since it will cause the +// created references to not have any meaningful source location information. +// If a reference string is coming from a source that should be identified in +// error messages then the caller should instead parse it directly using a +// suitable function from the HCL API and pass the traversal itself to +// ParseProviderConfigCompact. +// +// Error diagnostics are returned if either the parsing fails or the analysis +// of the traversal fails. There is no way for the caller to distinguish the +// two kinds of diagnostics programmatically. If error diagnostics are returned +// then the returned address is invalid. +func ParseModuleInstanceStr(str string) (ModuleInstance, tfdiags.Diagnostics) { + var diags tfdiags.Diagnostics + + traversal, parseDiags := hclsyntax.ParseTraversalAbs([]byte(str), "", hcl.Pos{Line: 1, Column: 1}) + for _, err := range parseDiags.Errs() { + // ignore warnings, they don't matter in this case + diags = append(diags, tfdiags.FromError(err)) + } + if parseDiags.HasErrors() { + return nil, diags + } + + addr, addrDiags := parseModuleInstance(traversal) + diags = append(diags, addrDiags...) + return addr, diags +} + +func parseModuleInstancePrefix(traversal hcl.Traversal) (ModuleInstance, hcl.Traversal, tfdiags.Diagnostics) { + remain := traversal + var mi ModuleInstance + var diags tfdiags.Diagnostics + + for len(remain) > 0 { + var next string + switch tt := remain[0].(type) { + case hcl.TraverseRoot: + next = tt.Name + case hcl.TraverseAttr: + next = tt.Name + default: + diags = append(diags, tfdiags.Diag( + tfdiags.Error, + "Invalid address operator", + "Module address prefix must be followed by dot and then a name.", + )) + break + } + + if next != "module" { + break + } + + remain = remain[1:] + // If we have the prefix "module" then we should be followed by an + // module call name, as an attribute, and then optionally an index step + // giving the instance key. + if len(remain) == 0 { + diags = append(diags, tfdiags.Diag( + tfdiags.Error, + "Invalid address operator", + "Prefix \"module.\" must be followed by a module name.", + )) + break + } + + var moduleName string + switch tt := remain[0].(type) { + case hcl.TraverseAttr: + moduleName = tt.Name + default: + diags = append(diags, tfdiags.Diag( + tfdiags.Error, + "Invalid address operator", + "Prefix \"module.\" must be followed by a module name.", + )) + break + } + remain = remain[1:] + step := ModuleInstanceStep{ + Name: moduleName, + } + + if len(remain) > 0 { + if idx, ok := remain[0].(hcl.TraverseIndex); ok { + remain = remain[1:] + + switch idx.Key.Type() { + case cty.String: + step.InstanceKey = stringKey(idx.Key.AsString()) + case cty.Number: + var idxInt int + err := gocty.FromCtyValue(idx.Key, &idxInt) + if err == nil { + step.InstanceKey = intKey(idxInt) + } else { + diags = append(diags, tfdiags.Diag( + tfdiags.Error, + "Invalid address operator", + fmt.Sprintf("Invalid module index: %s.", err), + )) + } + default: + // Should never happen, because no other types are allowed in traversal indices. + diags = append(diags, tfdiags.Diag( + tfdiags.Error, + "Invalid address operator", + "Invalid module key: must be either a string or an integer.", + )) + } + } + } + + mi = append(mi, step) + } + + var retRemain hcl.Traversal + if len(remain) > 0 { + retRemain = make(hcl.Traversal, len(remain)) + copy(retRemain, remain) + // The first element here might be either a TraverseRoot or a + // TraverseAttr, depending on whether we had a module address on the + // front. To make life easier for callers, we'll normalize to always + // start with a TraverseRoot. + if tt, ok := retRemain[0].(hcl.TraverseAttr); ok { + retRemain[0] = hcl.TraverseRoot{ + Name: tt.Name, + SrcRange: tt.SrcRange, + } + } + } + + return mi, retRemain, diags +} + +// UnkeyedInstanceShim is a shim method for converting a Module address to the +// equivalent ModuleInstance address that assumes that no modules have +// keyed instances. +// +// This is a temporary allowance for the fact that Terraform does not presently +// support "count" and "for_each" on modules, and thus graph building code that +// derives graph nodes from configuration must just assume unkeyed modules +// in order to construct the graph. At a later time when "count" and "for_each" +// support is added for modules, all callers of this method will need to be +// reworked to allow for keyed module instances. +func (m Module) UnkeyedInstanceShim() ModuleInstance { + path := make(ModuleInstance, len(m)) + for i, name := range m { + path[i] = ModuleInstanceStep{Name: name} + } + return path +} + +// ModuleInstanceStep is a single traversal step through the dynamic module +// tree. It is used only as part of ModuleInstance. +type ModuleInstanceStep struct { + Name string + InstanceKey instanceKey +} + +// RootModuleInstance is the module instance address representing the root +// module, which is also the zero value of ModuleInstance. +var RootModuleInstance ModuleInstance + +// Child returns the address of a child module instance of the receiver, +// identified by the given name and key. +func (m ModuleInstance) Child(name string, key instanceKey) ModuleInstance { + ret := make(ModuleInstance, 0, len(m)+1) + ret = append(ret, m...) + return append(ret, ModuleInstanceStep{ + Name: name, + InstanceKey: key, + }) +} + +// String returns a string representation of the receiver, in the format used +// within e.g. user-provided resource addresses. +// +// The address of the root module has the empty string as its representation. +func (m ModuleInstance) String() string { + var buf bytes.Buffer + sep := "" + for _, step := range m { + buf.WriteString(sep) + buf.WriteString("module.") + buf.WriteString(step.Name) + if step.InstanceKey != NoKey { + buf.WriteString(step.InstanceKey.String()) + } + sep = "." + } + return buf.String() +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/resource.go new file mode 100644 index 00000000000..f56032b5d26 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/resource.go @@ -0,0 +1,130 @@ +package addrs + +import ( + "fmt" +) + +// resource is an address for a resource block within configuration, which +// contains potentially-multiple resource instances if that configuration +// block uses "count" or "for_each". +type resource struct { + Mode resourceMode + Type string + Name string +} + +func (r resource) String() string { + switch r.Mode { + case ManagedResourceMode: + return fmt.Sprintf("%s.%s", r.Type, r.Name) + case DataResourceMode: + return fmt.Sprintf("data.%s.%s", r.Type, r.Name) + default: + // Should never happen, but we'll return a string here rather than + // crashing just in case it does. + return fmt.Sprintf(".%s.%s", r.Type, r.Name) + } +} + +// resourceInstance is an address for a specific instance of a resource. +// When a resource is defined in configuration with "count" or "for_each" it +// produces zero or more instances, which can be addressed using this type. +type resourceInstance struct { + Resource resource + Key instanceKey +} + +func (r resourceInstance) ContainingResource() resource { + return r.Resource +} + +func (r resourceInstance) String() string { + if r.Key == NoKey { + return r.Resource.String() + } + return r.Resource.String() + r.Key.String() +} + +// absResource is an absolute address for a resource under a given module path. +type absResource struct { + Module ModuleInstance + Resource resource +} + +// Resource returns the address of a particular resource within the receiver. +func (m ModuleInstance) Resource(mode resourceMode, typeName string, name string) absResource { + return absResource{ + Module: m, + Resource: resource{ + Mode: mode, + Type: typeName, + Name: name, + }, + } +} + +func (r absResource) String() string { + if len(r.Module) == 0 { + return r.Resource.String() + } + return fmt.Sprintf("%s.%s", r.Module.String(), r.Resource.String()) +} + +// absResourceInstance is an absolute address for a resource instance under a +// given module path. +type absResourceInstance struct { + Module ModuleInstance + Resource resourceInstance +} + +// ResourceInstance returns the address of a particular resource instance within the receiver. +func (m ModuleInstance) ResourceInstance(mode resourceMode, typeName string, name string, key instanceKey) absResourceInstance { + return absResourceInstance{ + Module: m, + Resource: resourceInstance{ + Resource: resource{ + Mode: mode, + Type: typeName, + Name: name, + }, + Key: key, + }, + } +} + +// ContainingResource returns the address of the resource that contains the +// receving resource instance. In other words, it discards the key portion +// of the address to produce an absResource value. +func (r absResourceInstance) ContainingResource() absResource { + return absResource{ + Module: r.Module, + Resource: r.Resource.ContainingResource(), + } +} + +func (r absResourceInstance) String() string { + if len(r.Module) == 0 { + return r.Resource.String() + } + return fmt.Sprintf("%s.%s", r.Module.String(), r.Resource.String()) +} + +// resourceMode defines which lifecycle applies to a given resource. Each +// resource lifecycle has a slightly different address format. +type resourceMode rune + +//go:generate go run golang.org/x/tools/cmd/stringer -type resourceMode + +const ( + // InvalidResourceMode is the zero value of ResourceMode and is not + // a valid resource mode. + InvalidResourceMode resourceMode = 0 + + // ManagedResourceMode indicates a managed resource, as defined by + // "resource" blocks in configuration. + ManagedResourceMode resourceMode = 'M' + + // DataResourceMode indicates a data resource, as defined by + // "data" blocks in configuration. + DataResourceMode resourceMode = 'D' +) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/resourcemode_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/resourcemode_string.go new file mode 100644 index 00000000000..3b2e65c3ab6 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs/resourcemode_string.go @@ -0,0 +1,33 @@ +// Code generated by "stringer -type resourceMode"; DO NOT EDIT. + +package addrs + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[InvalidResourceMode-0] + _ = x[ManagedResourceMode-77] + _ = x[DataResourceMode-68] +} + +const ( + _resourceMode_name_0 = "InvalidResourceMode" + _resourceMode_name_1 = "DataResourceMode" + _resourceMode_name_2 = "ManagedResourceMode" +) + +func (i resourceMode) String() string { + switch { + case i == 0: + return _resourceMode_name_0 + case i == 68: + return _resourceMode_name_1 + case i == 77: + return _resourceMode_name_2 + default: + return "resourceMode(" + strconv.FormatInt(int64(i), 10) + ")" + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/coerce_value.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/coerce_value.go similarity index 98% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/coerce_value.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/coerce_value.go index 41a533745c3..48278abed25 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/coerce_value.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/coerce_value.go @@ -3,8 +3,8 @@ package configschema import ( "fmt" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/go-cty/cty/convert" ) // CoerceValue attempts to force the given value to conform to the type diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/doc.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/doc.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/doc.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/empty_value.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/empty_value.go similarity index 98% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/empty_value.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/empty_value.go index 005da56bf5e..51b8c5d24c0 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/empty_value.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/empty_value.go @@ -1,7 +1,7 @@ package configschema import ( - "github.com/zclconf/go-cty/cty" + "github.com/hashicorp/go-cty/cty" ) // EmptyValue returns the "empty value" for the recieving block, which for diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/implied_type.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/implied_type.go new file mode 100644 index 00000000000..edc9dadccee --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/implied_type.go @@ -0,0 +1,68 @@ +package configschema + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// ImpliedType returns the cty.Type that would result from decoding a +// configuration block using the receiving block schema. +// +// ImpliedType always returns a result, even if the given schema is +// inconsistent. +func (b *Block) ImpliedType() cty.Type { + if b == nil { + return cty.EmptyObject + } + + atys := make(map[string]cty.Type) + + for name, attrS := range b.Attributes { + atys[name] = attrS.Type + } + + for name, blockS := range b.BlockTypes { + if _, exists := atys[name]; exists { + panic("invalid schema, blocks and attributes cannot have the same name") + } + + childType := blockS.Block.ImpliedType() + + switch blockS.Nesting { + case NestingSingle, NestingGroup: + atys[name] = childType + case NestingList: + // We prefer to use a list where possible, since it makes our + // implied type more complete, but if there are any + // dynamically-typed attributes inside we must use a tuple + // instead, which means our type _constraint_ must be + // cty.DynamicPseudoType to allow the tuple type to be decided + // separately for each value. + if childType.HasDynamicTypes() { + atys[name] = cty.DynamicPseudoType + } else { + atys[name] = cty.List(childType) + } + case NestingSet: + if childType.HasDynamicTypes() { + panic("can't use cty.DynamicPseudoType inside a block type with NestingSet") + } + atys[name] = cty.Set(childType) + case NestingMap: + // We prefer to use a map where possible, since it makes our + // implied type more complete, but if there are any + // dynamically-typed attributes inside we must use an object + // instead, which means our type _constraint_ must be + // cty.DynamicPseudoType to allow the tuple type to be decided + // separately for each value. + if childType.HasDynamicTypes() { + atys[name] = cty.DynamicPseudoType + } else { + atys[name] = cty.Map(childType) + } + default: + panic("invalid nesting type") + } + } + + return cty.Object(atys) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/nestingmode_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/nestingmode_string.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema/nestingmode_string.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/nestingmode_string.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/schema.go new file mode 100644 index 00000000000..6cddb9c63b4 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema/schema.go @@ -0,0 +1,155 @@ +package configschema + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// StringKind represents the format a string is in. +type StringKind int + +const ( + // StringPlain indicates a string is plain-text and requires no processing for display. + StringPlain StringKind = iota + // StringMarkdown indicates a string is in markdown format and may + // require additional processing to display. + StringMarkdown +) + +// Block represents a configuration block. +// +// "Block" here is a logical grouping construct, though it happens to map +// directly onto the physical block syntax of Terraform's native configuration +// syntax. It may be a more a matter of convention in other syntaxes, such as +// JSON. +// +// When converted to a value, a Block always becomes an instance of an object +// type derived from its defined attributes and nested blocks +type Block struct { + // Attributes describes any attributes that may appear directly inside + // the block. + Attributes map[string]*Attribute + + // BlockTypes describes any nested block types that may appear directly + // inside the block. + BlockTypes map[string]*NestedBlock + + // Description and DescriptionKind contain a user facing description of the block + // and the format of that string. + Description string + DescriptionKind StringKind + + // Deprecated indicates whether the block has been marked as deprecated in the + // provider and usage should be discouraged. + Deprecated bool +} + +// Attribute represents a configuration attribute, within a block. +type Attribute struct { + // Type is a type specification that the attribute's value must conform to. + Type cty.Type + + // Description is an English-language description of the purpose and + // usage of the attribute. A description should be concise and use only + // one or two sentences, leaving full definition to longer-form + // documentation defined elsewhere. + Description string + DescriptionKind StringKind + + // Required, if set to true, specifies that an omitted or null value is + // not permitted. + Required bool + + // Optional, if set to true, specifies that an omitted or null value is + // permitted. This field conflicts with Required. + Optional bool + + // Computed, if set to true, specifies that the value comes from the + // provider rather than from configuration. If combined with Optional, + // then the config may optionally provide an overridden value. + Computed bool + + // Sensitive, if set to true, indicates that an attribute may contain + // sensitive information. + // + // At present nothing is done with this information, but callers are + // encouraged to set it where appropriate so that it may be used in the + // future to help Terraform mask sensitive information. (Terraform + // currently achieves this in a limited sense via other mechanisms.) + Sensitive bool + + // Deprecated indicates whether the attribute has been marked as deprecated in the + // provider and usage should be discouraged. + Deprecated bool +} + +// NestedBlock represents the embedding of one block within another. +type NestedBlock struct { + // Block is the description of the block that's nested. + Block + + // Nesting provides the nesting mode for the child block, which determines + // how many instances of the block are allowed, how many labels it expects, + // and how the resulting data will be converted into a data structure. + Nesting NestingMode + + // MinItems and MaxItems set, for the NestingList and NestingSet nesting + // modes, lower and upper limits on the number of child blocks allowed + // of the given type. If both are left at zero, no limit is applied. + // + // As a special case, both values can be set to 1 for NestingSingle in + // order to indicate that a particular single block is required. + // + // These fields are ignored for other nesting modes and must both be left + // at zero. + MinItems, MaxItems int +} + +// NestingMode is an enumeration of modes for nesting blocks inside other +// blocks. +type NestingMode int + +//go:generate go run golang.org/x/tools/cmd/stringer -type=NestingMode + +const ( + nestingModeInvalid NestingMode = iota + + // NestingSingle indicates that only a single instance of a given + // block type is permitted, with no labels, and its content should be + // provided directly as an object value. + NestingSingle + + // NestingGroup is similar to NestingSingle in that it calls for only a + // single instance of a given block type with no labels, but it additonally + // guarantees that its result will never be null, even if the block is + // absent, and instead the nested attributes and blocks will be treated + // as absent in that case. (Any required attributes or blocks within the + // nested block are not enforced unless the block is explicitly present + // in the configuration, so they are all effectively optional when the + // block is not present.) + // + // This is useful for the situation where a remote API has a feature that + // is always enabled but has a group of settings related to that feature + // that themselves have default values. By using NestingGroup instead of + // NestingSingle in that case, generated plans will show the block as + // present even when not present in configuration, thus allowing any + // default values within to be displayed to the user. + NestingGroup + + // NestingList indicates that multiple blocks of the given type are + // permitted, with no labels, and that their corresponding objects should + // be provided in a list. + NestingList + + // NestingSet indicates that multiple blocks of the given type are + // permitted, with no labels, and that their corresponding objects should + // be provided in a set. + NestingSet + + // NestingMap indicates that multiple blocks of the given type are + // permitted, each with a single label, and that their corresponding + // objects should be provided in a map whose keys are the labels. + // + // It's an error, therefore, to use the same label value on multiple + // blocks. + NestingMap +) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/flatmap.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/flatmap.go similarity index 99% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/flatmap.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/flatmap.go index bb4228d98c4..e620e76a90e 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/flatmap.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/flatmap.go @@ -5,9 +5,8 @@ import ( "strconv" "strings" - "github.com/zclconf/go-cty/cty/convert" - - "github.com/zclconf/go-cty/cty" + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/go-cty/cty/convert" ) // FlatmapValueFromHCL2 converts a value from HCL2 (really, from the cty dynamic diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/paths.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/paths.go new file mode 100644 index 00000000000..e557845a703 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/paths.go @@ -0,0 +1,276 @@ +package hcl2shim + +import ( + "fmt" + "reflect" + "strconv" + "strings" + + "github.com/hashicorp/go-cty/cty" +) + +// RequiresReplace takes a list of flatmapped paths from a +// InstanceDiff.Attributes along with the corresponding cty.Type, and returns +// the list of the cty.Paths that are flagged as causing the resource +// replacement (RequiresNew). +// This will filter out redundant paths, paths that refer to flatmapped indexes +// (e.g. "#", "%"), and will return any changes within a set as the path to the +// set itself. +func RequiresReplace(attrs []string, ty cty.Type) ([]cty.Path, error) { + var paths []cty.Path + + for _, attr := range attrs { + p, err := requiresReplacePath(attr, ty) + if err != nil { + return nil, err + } + + paths = append(paths, p) + } + + // now trim off any trailing paths that aren't GetAttrSteps, since only an + // attribute itself can require replacement + paths = trimPaths(paths) + + // There may be redundant paths due to set elements or index attributes + // Do some ugly n^2 filtering, but these are always fairly small sets. + for i := 0; i < len(paths)-1; i++ { + for j := i + 1; j < len(paths); j++ { + if reflect.DeepEqual(paths[i], paths[j]) { + // swap the tail and slice it off + paths[j], paths[len(paths)-1] = paths[len(paths)-1], paths[j] + paths = paths[:len(paths)-1] + j-- + } + } + } + + return paths, nil +} + +// trimPaths removes any trailing steps that aren't of type GetAttrSet, since +// only an attribute itself can require replacement +func trimPaths(paths []cty.Path) []cty.Path { + var trimmed []cty.Path + for _, path := range paths { + path = trimPath(path) + if len(path) > 0 { + trimmed = append(trimmed, path) + } + } + return trimmed +} + +func trimPath(path cty.Path) cty.Path { + for len(path) > 0 { + _, isGetAttr := path[len(path)-1].(cty.GetAttrStep) + if isGetAttr { + break + } + path = path[:len(path)-1] + } + return path +} + +// requiresReplacePath takes a key from a flatmap along with the cty.Type +// describing the structure, and returns the cty.Path that would be used to +// reference the nested value in the data structure. +// This is used specifically to record the RequiresReplace attributes from a +// ResourceInstanceDiff. +func requiresReplacePath(k string, ty cty.Type) (cty.Path, error) { + if k == "" { + return nil, nil + } + if !ty.IsObjectType() { + panic(fmt.Sprintf("requires replace path on non-object type: %#v", ty)) + } + + path, err := pathFromFlatmapKeyObject(k, ty.AttributeTypes()) + if err != nil { + return path, fmt.Errorf("[%s] %s", k, err) + } + return path, nil +} + +func pathSplit(p string) (string, string) { + parts := strings.SplitN(p, ".", 2) + head := parts[0] + rest := "" + if len(parts) > 1 { + rest = parts[1] + } + return head, rest +} + +func pathFromFlatmapKeyObject(key string, atys map[string]cty.Type) (cty.Path, error) { + k, rest := pathSplit(key) + + path := cty.Path{cty.GetAttrStep{Name: k}} + + ty, ok := atys[k] + if !ok { + return path, fmt.Errorf("attribute %q not found", k) + } + + if rest == "" { + return path, nil + } + + p, err := pathFromFlatmapKeyValue(rest, ty) + if err != nil { + return path, err + } + + return append(path, p...), nil +} + +func pathFromFlatmapKeyValue(key string, ty cty.Type) (cty.Path, error) { + var path cty.Path + var err error + + switch { + case ty.IsPrimitiveType(): + err = fmt.Errorf("invalid step %q with type %#v", key, ty) + case ty.IsObjectType(): + path, err = pathFromFlatmapKeyObject(key, ty.AttributeTypes()) + case ty.IsTupleType(): + path, err = pathFromFlatmapKeyTuple(key, ty.TupleElementTypes()) + case ty.IsMapType(): + path, err = pathFromFlatmapKeyMap(key, ty) + case ty.IsListType(): + path, err = pathFromFlatmapKeyList(key, ty) + case ty.IsSetType(): + path, err = pathFromFlatmapKeySet(key, ty) + default: + err = fmt.Errorf("unrecognized type: %s", ty.FriendlyName()) + } + + if err != nil { + return path, err + } + + return path, nil +} + +func pathFromFlatmapKeyTuple(key string, etys []cty.Type) (cty.Path, error) { + var path cty.Path + var err error + + k, rest := pathSplit(key) + + // we don't need to convert the index keys to paths + if k == "#" { + return path, nil + } + + idx, err := strconv.Atoi(k) + if err != nil { + return path, err + } + + path = cty.Path{cty.IndexStep{Key: cty.NumberIntVal(int64(idx))}} + + if idx >= len(etys) { + return path, fmt.Errorf("index %s out of range in %#v", key, etys) + } + + if rest == "" { + return path, nil + } + + ty := etys[idx] + + p, err := pathFromFlatmapKeyValue(rest, ty.ElementType()) + if err != nil { + return path, err + } + + return append(path, p...), nil +} + +func pathFromFlatmapKeyMap(key string, ty cty.Type) (cty.Path, error) { + var path cty.Path + var err error + + k, rest := key, "" + if !ty.ElementType().IsPrimitiveType() { + k, rest = pathSplit(key) + } + + // we don't need to convert the index keys to paths + if k == "%" { + return path, nil + } + + path = cty.Path{cty.IndexStep{Key: cty.StringVal(k)}} + + if rest == "" { + return path, nil + } + + p, err := pathFromFlatmapKeyValue(rest, ty.ElementType()) + if err != nil { + return path, err + } + + return append(path, p...), nil +} + +func pathFromFlatmapKeyList(key string, ty cty.Type) (cty.Path, error) { + var path cty.Path + var err error + + k, rest := pathSplit(key) + + // we don't need to convert the index keys to paths + if key == "#" { + return path, nil + } + + idx, err := strconv.Atoi(k) + if err != nil { + return path, err + } + + path = cty.Path{cty.IndexStep{Key: cty.NumberIntVal(int64(idx))}} + + if rest == "" { + return path, nil + } + + p, err := pathFromFlatmapKeyValue(rest, ty.ElementType()) + if err != nil { + return path, err + } + + return append(path, p...), nil +} + +func pathFromFlatmapKeySet(key string, ty cty.Type) (cty.Path, error) { + // once we hit a set, we can't return consistent paths, so just mark the + // set as a whole changed. + return nil, nil +} + +// FlatmapKeyFromPath returns the flatmap equivalent of the given cty.Path for +// use in generating legacy style diffs. +func FlatmapKeyFromPath(path cty.Path) string { + var parts []string + + for _, step := range path { + switch step := step.(type) { + case cty.GetAttrStep: + parts = append(parts, step.Name) + case cty.IndexStep: + switch ty := step.Key.Type(); { + case ty == cty.String: + parts = append(parts, step.Key.AsString()) + case ty == cty.Number: + i, _ := step.Key.AsBigFloat().Int64() + parts = append(parts, strconv.Itoa(int(i))) + } + } + } + + return strings.Join(parts, ".") +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/single_attr_body.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/single_attr_body.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/single_attr_body.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/single_attr_body.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/values.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/values.go similarity index 98% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/values.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/values.go index a074c749d52..91e91547a85 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/values.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/values.go @@ -4,9 +4,9 @@ import ( "fmt" "math/big" - "github.com/zclconf/go-cty/cty" + "github.com/hashicorp/go-cty/cty" - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" ) // UnknownVariableValue is a sentinel value that can be used diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/values_equiv.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/values_equiv.go similarity index 99% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/values_equiv.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/values_equiv.go index 92f0213d724..87638b4e499 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim/values_equiv.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim/values_equiv.go @@ -1,7 +1,7 @@ package hcl2shim import ( - "github.com/zclconf/go-cty/cty" + "github.com/hashicorp/go-cty/cty" ) // ValuesSDKEquivalent returns true if both of the given values seem equivalent diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/hashcode/hashcode.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/hashcode/hashcode.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/helper/hashcode/hashcode.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/hashcode/hashcode.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/context/context.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/context/context.go new file mode 100644 index 00000000000..0939edeff66 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/context/context.go @@ -0,0 +1,7 @@ +package context + +type Key string + +var ( + StopContextKey = Key("StopContext") +) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/plugin/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/doc.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/helper/plugin/doc.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/doc.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/grpc_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/grpc_provider.go new file mode 100644 index 00000000000..6eb20a06157 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/grpc_provider.go @@ -0,0 +1,1464 @@ +package plugin + +import ( + "context" + "encoding/json" + "fmt" + "log" + "strconv" + "sync" + + "github.com/hashicorp/go-cty/cty" + ctyconvert "github.com/hashicorp/go-cty/cty/convert" + "github.com/hashicorp/go-cty/cty/msgpack" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim" + c "github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/context" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/plans/objchange" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert" + proto "github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +const newExtraKey = "_new_extra_shim" + +func NewGRPCProviderServer(p *schema.Provider) *GRPCProviderServer { + return &GRPCProviderServer{ + provider: p, + stopCh: make(chan struct{}), + } +} + +// GRPCProviderServer handles the server, or plugin side of the rpc connection. +type GRPCProviderServer struct { + provider *schema.Provider + stopCh chan struct{} + stopMu sync.Mutex +} + +// mergeStop is called in a goroutine and waits for the global stop signal +// and propagates cancellation to the passed in ctx/cancel func. The ctx is +// also passed to this function and waited upon so no goroutine leak is caused. +func mergeStop(ctx context.Context, cancel context.CancelFunc, stopCh chan struct{}) { + select { + case <-ctx.Done(): + return + case <-stopCh: + cancel() + } +} + +// StopContext derives a new context from the passed in grpc context. +// It creates a goroutine to wait for the server stop and propagates +// cancellation to the derived grpc context. +func (s *GRPCProviderServer) StopContext(ctx context.Context) context.Context { + s.stopMu.Lock() + defer s.stopMu.Unlock() + + stoppable, cancel := context.WithCancel(ctx) + go mergeStop(stoppable, cancel, s.stopCh) + return stoppable +} + +func (s *GRPCProviderServer) GetSchema(_ context.Context, req *proto.GetProviderSchema_Request) (*proto.GetProviderSchema_Response, error) { + + resp := &proto.GetProviderSchema_Response{ + ResourceSchemas: make(map[string]*proto.Schema), + DataSourceSchemas: make(map[string]*proto.Schema), + } + + resp.Provider = &proto.Schema{ + Block: convert.ConfigSchemaToProto(s.getProviderSchemaBlock()), + } + + resp.ProviderMeta = &proto.Schema{ + Block: convert.ConfigSchemaToProto(s.getProviderMetaSchemaBlock()), + } + + for typ, res := range s.provider.ResourcesMap { + resp.ResourceSchemas[typ] = &proto.Schema{ + Version: int64(res.SchemaVersion), + Block: convert.ConfigSchemaToProto(res.CoreConfigSchema()), + } + } + + for typ, dat := range s.provider.DataSourcesMap { + resp.DataSourceSchemas[typ] = &proto.Schema{ + Version: int64(dat.SchemaVersion), + Block: convert.ConfigSchemaToProto(dat.CoreConfigSchema()), + } + } + + return resp, nil +} + +func (s *GRPCProviderServer) getProviderSchemaBlock() *configschema.Block { + return schema.InternalMap(s.provider.Schema).CoreConfigSchema() +} + +func (s *GRPCProviderServer) getProviderMetaSchemaBlock() *configschema.Block { + return schema.InternalMap(s.provider.ProviderMetaSchema).CoreConfigSchema() +} + +func (s *GRPCProviderServer) getResourceSchemaBlock(name string) *configschema.Block { + res := s.provider.ResourcesMap[name] + return res.CoreConfigSchema() +} + +func (s *GRPCProviderServer) getDatasourceSchemaBlock(name string) *configschema.Block { + dat := s.provider.DataSourcesMap[name] + return dat.CoreConfigSchema() +} + +func (s *GRPCProviderServer) PrepareProviderConfig(_ context.Context, req *proto.PrepareProviderConfig_Request) (*proto.PrepareProviderConfig_Response, error) { + resp := &proto.PrepareProviderConfig_Response{} + + schemaBlock := s.getProviderSchemaBlock() + + configVal, err := msgpack.Unmarshal(req.Config.Msgpack, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // lookup any required, top-level attributes that are Null, and see if we + // have a Default value available. + configVal, err = cty.Transform(configVal, func(path cty.Path, val cty.Value) (cty.Value, error) { + // we're only looking for top-level attributes + if len(path) != 1 { + return val, nil + } + + // nothing to do if we already have a value + if !val.IsNull() { + return val, nil + } + + // get the Schema definition for this attribute + getAttr, ok := path[0].(cty.GetAttrStep) + // these should all exist, but just ignore anything strange + if !ok { + return val, nil + } + + attrSchema := s.provider.Schema[getAttr.Name] + // continue to ignore anything that doesn't match + if attrSchema == nil { + return val, nil + } + + // this is deprecated, so don't set it + if attrSchema.Deprecated != "" { + return val, nil + } + + // find a default value if it exists + def, err := attrSchema.DefaultValue() + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("error getting default for %q: %s", getAttr.Name, err)) + return val, err + } + + // no default + if def == nil { + return val, nil + } + + // create a cty.Value and make sure it's the correct type + tmpVal := hcl2shim.HCL2ValueFromConfigValue(def) + + // helper/schema used to allow setting "" to a bool + if val.Type() == cty.Bool && tmpVal.RawEquals(cty.StringVal("")) { + // return a warning about the conversion + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, "provider set empty string as default value for bool "+getAttr.Name) + tmpVal = cty.False + } + + val, err = ctyconvert.Convert(tmpVal, val.Type()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("error setting default for %q: %s", getAttr.Name, err)) + } + + return val, err + }) + if err != nil { + // any error here was already added to the diagnostics + return resp, nil + } + + configVal, err = schemaBlock.CoerceValue(configVal) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // Ensure there are no nulls that will cause helper/schema to panic. + if err := validateConfigNulls(configVal, nil); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) + + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, s.provider.Validate(config)) + + preparedConfigMP, err := msgpack.Marshal(configVal, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + resp.PreparedConfig = &proto.DynamicValue{Msgpack: preparedConfigMP} + + return resp, nil +} + +func (s *GRPCProviderServer) ValidateResourceTypeConfig(_ context.Context, req *proto.ValidateResourceTypeConfig_Request) (*proto.ValidateResourceTypeConfig_Response, error) { + resp := &proto.ValidateResourceTypeConfig_Response{} + + schemaBlock := s.getResourceSchemaBlock(req.TypeName) + + configVal, err := msgpack.Unmarshal(req.Config.Msgpack, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) + + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, s.provider.ValidateResource(req.TypeName, config)) + + return resp, nil +} + +func (s *GRPCProviderServer) ValidateDataSourceConfig(_ context.Context, req *proto.ValidateDataSourceConfig_Request) (*proto.ValidateDataSourceConfig_Response, error) { + resp := &proto.ValidateDataSourceConfig_Response{} + + schemaBlock := s.getDatasourceSchemaBlock(req.TypeName) + + configVal, err := msgpack.Unmarshal(req.Config.Msgpack, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // Ensure there are no nulls that will cause helper/schema to panic. + if err := validateConfigNulls(configVal, nil); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) + + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, s.provider.ValidateDataSource(req.TypeName, config)) + + return resp, nil +} + +func (s *GRPCProviderServer) UpgradeResourceState(ctx context.Context, req *proto.UpgradeResourceState_Request) (*proto.UpgradeResourceState_Response, error) { + resp := &proto.UpgradeResourceState_Response{} + + res, ok := s.provider.ResourcesMap[req.TypeName] + if !ok { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) + return resp, nil + } + schemaBlock := s.getResourceSchemaBlock(req.TypeName) + + version := int(req.Version) + + jsonMap := map[string]interface{}{} + var err error + + switch { + // We first need to upgrade a flatmap state if it exists. + // There should never be both a JSON and Flatmap state in the request. + case len(req.RawState.Flatmap) > 0: + jsonMap, version, err = s.upgradeFlatmapState(ctx, version, req.RawState.Flatmap, res) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + // if there's a JSON state, we need to decode it. + case len(req.RawState.Json) > 0: + err = json.Unmarshal(req.RawState.Json, &jsonMap) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + default: + log.Println("[DEBUG] no state provided to upgrade") + return resp, nil + } + + // complete the upgrade of the JSON states + jsonMap, err = s.upgradeJSONState(ctx, version, jsonMap, res) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // The provider isn't required to clean out removed fields + s.removeAttributes(jsonMap, schemaBlock.ImpliedType()) + + // now we need to turn the state into the default json representation, so + // that it can be re-decoded using the actual schema. + val, err := schema.JSONMapToStateValue(jsonMap, schemaBlock) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // Now we need to make sure blocks are represented correctly, which means + // that missing blocks are empty collections, rather than null. + // First we need to CoerceValue to ensure that all object types match. + val, err = schemaBlock.CoerceValue(val) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + // Normalize the value and fill in any missing blocks. + val = objchange.NormalizeObjectFromLegacySDK(val, schemaBlock) + + // encode the final state to the expected msgpack format + newStateMP, err := msgpack.Marshal(val, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + resp.UpgradedState = &proto.DynamicValue{Msgpack: newStateMP} + return resp, nil +} + +// upgradeFlatmapState takes a legacy flatmap state, upgrades it using Migrate +// state if necessary, and converts it to the new JSON state format decoded as a +// map[string]interface{}. +// upgradeFlatmapState returns the json map along with the corresponding schema +// version. +func (s *GRPCProviderServer) upgradeFlatmapState(ctx context.Context, version int, m map[string]string, res *schema.Resource) (map[string]interface{}, int, error) { + // this will be the version we've upgraded so, defaulting to the given + // version in case no migration was called. + upgradedVersion := version + + // first determine if we need to call the legacy MigrateState func + requiresMigrate := version < res.SchemaVersion + + schemaType := res.CoreConfigSchema().ImpliedType() + + // if there are any StateUpgraders, then we need to only compare + // against the first version there + if len(res.StateUpgraders) > 0 { + requiresMigrate = version < res.StateUpgraders[0].Version + } + + if requiresMigrate && res.MigrateState == nil { + // Providers were previously allowed to bump the version + // without declaring MigrateState. + // If there are further upgraders, then we've only updated that far. + if len(res.StateUpgraders) > 0 { + schemaType = res.StateUpgraders[0].Type + upgradedVersion = res.StateUpgraders[0].Version + } + } else if requiresMigrate { + is := &terraform.InstanceState{ + ID: m["id"], + Attributes: m, + Meta: map[string]interface{}{ + "schema_version": strconv.Itoa(version), + }, + } + is, err := res.MigrateState(version, is, s.provider.Meta()) + if err != nil { + return nil, 0, err + } + + // re-assign the map in case there was a copy made, making sure to keep + // the ID + m := is.Attributes + m["id"] = is.ID + + // if there are further upgraders, then we've only updated that far + if len(res.StateUpgraders) > 0 { + schemaType = res.StateUpgraders[0].Type + upgradedVersion = res.StateUpgraders[0].Version + } + } else { + // the schema version may be newer than the MigrateState functions + // handled and older than the current, but still stored in the flatmap + // form. If that's the case, we need to find the correct schema type to + // convert the state. + for _, upgrader := range res.StateUpgraders { + if upgrader.Version == version { + schemaType = upgrader.Type + break + } + } + } + + // now we know the state is up to the latest version that handled the + // flatmap format state. Now we can upgrade the format and continue from + // there. + newConfigVal, err := hcl2shim.HCL2ValueFromFlatmap(m, schemaType) + if err != nil { + return nil, 0, err + } + + jsonMap, err := schema.StateValueToJSONMap(newConfigVal, schemaType) + return jsonMap, upgradedVersion, err +} + +func (s *GRPCProviderServer) upgradeJSONState(ctx context.Context, version int, m map[string]interface{}, res *schema.Resource) (map[string]interface{}, error) { + var err error + + for _, upgrader := range res.StateUpgraders { + if version != upgrader.Version { + continue + } + + m, err = upgrader.Upgrade(ctx, m, s.provider.Meta()) + if err != nil { + return nil, err + } + version++ + } + + return m, nil +} + +// Remove any attributes no longer present in the schema, so that the json can +// be correctly decoded. +func (s *GRPCProviderServer) removeAttributes(v interface{}, ty cty.Type) { + // we're only concerned with finding maps that corespond to object + // attributes + switch v := v.(type) { + case []interface{}: + // If these aren't blocks the next call will be a noop + if ty.IsListType() || ty.IsSetType() { + eTy := ty.ElementType() + for _, eV := range v { + s.removeAttributes(eV, eTy) + } + } + return + case map[string]interface{}: + // map blocks aren't yet supported, but handle this just in case + if ty.IsMapType() { + eTy := ty.ElementType() + for _, eV := range v { + s.removeAttributes(eV, eTy) + } + return + } + + if ty == cty.DynamicPseudoType { + log.Printf("[DEBUG] ignoring dynamic block: %#v\n", v) + return + } + + if !ty.IsObjectType() { + // This shouldn't happen, and will fail to decode further on, so + // there's no need to handle it here. + log.Printf("[WARN] unexpected type %#v for map in json state", ty) + return + } + + attrTypes := ty.AttributeTypes() + for attr, attrV := range v { + attrTy, ok := attrTypes[attr] + if !ok { + log.Printf("[DEBUG] attribute %q no longer present in schema", attr) + delete(v, attr) + continue + } + + s.removeAttributes(attrV, attrTy) + } + } +} + +func (s *GRPCProviderServer) Stop(_ context.Context, _ *proto.Stop_Request) (*proto.Stop_Response, error) { + s.stopMu.Lock() + defer s.stopMu.Unlock() + + // stop + close(s.stopCh) + // reset the stop signal + s.stopCh = make(chan struct{}) + + return &proto.Stop_Response{}, nil +} + +func (s *GRPCProviderServer) Configure(ctx context.Context, req *proto.Configure_Request) (*proto.Configure_Response, error) { + resp := &proto.Configure_Response{} + + schemaBlock := s.getProviderSchemaBlock() + + configVal, err := msgpack.Unmarshal(req.Config.Msgpack, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + s.provider.TerraformVersion = req.TerraformVersion + + // Ensure there are no nulls that will cause helper/schema to panic. + if err := validateConfigNulls(configVal, nil); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) + // TODO: remove global stop context hack + // This attaches a global stop synchro'd context onto the provider.Configure + // request scoped context. This provides a substitute for the removed provider.StopContext() + // function. Ideally a provider should migrate to the context aware API that receives + // request scoped contexts, however this is a large undertaking for very large providers. + ctxHack := context.WithValue(ctx, c.StopContextKey, s.StopContext(context.Background())) + diags := s.provider.Configure(ctxHack, config) + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, diags) + + return resp, nil +} + +func (s *GRPCProviderServer) ReadResource(ctx context.Context, req *proto.ReadResource_Request) (*proto.ReadResource_Response, error) { + resp := &proto.ReadResource_Response{ + // helper/schema did previously handle private data during refresh, but + // core is now going to expect this to be maintained in order to + // persist it in the state. + Private: req.Private, + } + + res, ok := s.provider.ResourcesMap[req.TypeName] + if !ok { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) + return resp, nil + } + schemaBlock := s.getResourceSchemaBlock(req.TypeName) + + stateVal, err := msgpack.Unmarshal(req.CurrentState.Msgpack, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + instanceState, err := res.ShimInstanceStateFromValue(stateVal) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + private := make(map[string]interface{}) + if len(req.Private) > 0 { + if err := json.Unmarshal(req.Private, &private); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + } + instanceState.Meta = private + + pmSchemaBlock := s.getProviderMetaSchemaBlock() + if pmSchemaBlock != nil && req.ProviderMeta != nil { + providerSchemaVal, err := msgpack.Unmarshal(req.ProviderMeta.Msgpack, pmSchemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + instanceState.ProviderMeta = providerSchemaVal + } + + newInstanceState, diags := res.RefreshWithoutUpgrade(ctx, instanceState, s.provider.Meta()) + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, diags) + if diags.HasError() { + return resp, nil + } + + if newInstanceState == nil || newInstanceState.ID == "" { + // The old provider API used an empty id to signal that the remote + // object appears to have been deleted, but our new protocol expects + // to see a null value (in the cty sense) in that case. + newStateMP, err := msgpack.Marshal(cty.NullVal(schemaBlock.ImpliedType()), schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + } + resp.NewState = &proto.DynamicValue{ + Msgpack: newStateMP, + } + return resp, nil + } + + // helper/schema should always copy the ID over, but do it again just to be safe + newInstanceState.Attributes["id"] = newInstanceState.ID + + newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(newInstanceState.Attributes, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + newStateVal = normalizeNullValues(newStateVal, stateVal, false) + newStateVal = copyTimeoutValues(newStateVal, stateVal) + + newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + resp.NewState = &proto.DynamicValue{ + Msgpack: newStateMP, + } + + return resp, nil +} + +func (s *GRPCProviderServer) PlanResourceChange(ctx context.Context, req *proto.PlanResourceChange_Request) (*proto.PlanResourceChange_Response, error) { + resp := &proto.PlanResourceChange_Response{} + + // This is a signal to Terraform Core that we're doing the best we can to + // shim the legacy type system of the SDK onto the Terraform type system + // but we need it to cut us some slack. This setting should not be taken + // forward to any new SDK implementations, since setting it prevents us + // from catching certain classes of provider bug that can lead to + // confusing downstream errors. + resp.LegacyTypeSystem = true + + res, ok := s.provider.ResourcesMap[req.TypeName] + if !ok { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) + return resp, nil + } + schemaBlock := s.getResourceSchemaBlock(req.TypeName) + + priorStateVal, err := msgpack.Unmarshal(req.PriorState.Msgpack, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + create := priorStateVal.IsNull() + + proposedNewStateVal, err := msgpack.Unmarshal(req.ProposedNewState.Msgpack, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // We don't usually plan destroys, but this can return early in any case. + if proposedNewStateVal.IsNull() { + resp.PlannedState = req.ProposedNewState + resp.PlannedPrivate = req.PriorPrivate + return resp, nil + } + + priorState, err := res.ShimInstanceStateFromValue(priorStateVal) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + priorPrivate := make(map[string]interface{}) + if len(req.PriorPrivate) > 0 { + if err := json.Unmarshal(req.PriorPrivate, &priorPrivate); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + } + + priorState.Meta = priorPrivate + + pmSchemaBlock := s.getProviderMetaSchemaBlock() + if pmSchemaBlock != nil && req.ProviderMeta != nil { + providerSchemaVal, err := msgpack.Unmarshal(req.ProviderMeta.Msgpack, pmSchemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + priorState.ProviderMeta = providerSchemaVal + } + + // Ensure there are no nulls that will cause helper/schema to panic. + if err := validateConfigNulls(proposedNewStateVal, nil); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // turn the proposed state into a legacy configuration + cfg := terraform.NewResourceConfigShimmed(proposedNewStateVal, schemaBlock) + + diff, err := res.SimpleDiff(ctx, priorState, cfg, s.provider.Meta()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // if this is a new instance, we need to make sure ID is going to be computed + if create { + if diff == nil { + diff = terraform.NewInstanceDiff() + } + + diff.Attributes["id"] = &terraform.ResourceAttrDiff{ + NewComputed: true, + } + } + + if diff == nil || len(diff.Attributes) == 0 { + // schema.Provider.Diff returns nil if it ends up making a diff with no + // changes, but our new interface wants us to return an actual change + // description that _shows_ there are no changes. This is always the + // prior state, because we force a diff above if this is a new instance. + resp.PlannedState = req.PriorState + resp.PlannedPrivate = req.PriorPrivate + return resp, nil + } + + if priorState == nil { + priorState = &terraform.InstanceState{} + } + + // now we need to apply the diff to the prior state, so get the planned state + plannedAttrs, err := diff.Apply(priorState.Attributes, schemaBlock) + + plannedStateVal, err := hcl2shim.HCL2ValueFromFlatmap(plannedAttrs, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + plannedStateVal, err = schemaBlock.CoerceValue(plannedStateVal) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + plannedStateVal = normalizeNullValues(plannedStateVal, proposedNewStateVal, false) + + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + plannedStateVal = copyTimeoutValues(plannedStateVal, proposedNewStateVal) + + // The old SDK code has some imprecisions that cause it to sometimes + // generate differences that the SDK itself does not consider significant + // but Terraform Core would. To avoid producing weird do-nothing diffs + // in that case, we'll check if the provider as produced something we + // think is "equivalent" to the prior state and just return the prior state + // itself if so, thus ensuring that Terraform Core will treat this as + // a no-op. See the docs for ValuesSDKEquivalent for some caveats on its + // accuracy. + forceNoChanges := false + if hcl2shim.ValuesSDKEquivalent(priorStateVal, plannedStateVal) { + plannedStateVal = priorStateVal + forceNoChanges = true + } + + // if this was creating the resource, we need to set any remaining computed + // fields + if create { + plannedStateVal = SetUnknowns(plannedStateVal, schemaBlock) + } + + plannedMP, err := msgpack.Marshal(plannedStateVal, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + resp.PlannedState = &proto.DynamicValue{ + Msgpack: plannedMP, + } + + // encode any timeouts into the diff Meta + t := &schema.ResourceTimeout{} + if err := t.ConfigDecode(res, cfg); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + if err := t.DiffEncode(diff); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // Now we need to store any NewExtra values, which are where any actual + // StateFunc modified config fields are hidden. + privateMap := diff.Meta + if privateMap == nil { + privateMap = map[string]interface{}{} + } + + newExtra := map[string]interface{}{} + + for k, v := range diff.Attributes { + if v.NewExtra != nil { + newExtra[k] = v.NewExtra + } + } + privateMap[newExtraKey] = newExtra + + // the Meta field gets encoded into PlannedPrivate + plannedPrivate, err := json.Marshal(privateMap) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + resp.PlannedPrivate = plannedPrivate + + // collect the attributes that require instance replacement, and convert + // them to cty.Paths. + var requiresNew []string + if !forceNoChanges { + for attr, d := range diff.Attributes { + if d.RequiresNew { + requiresNew = append(requiresNew, attr) + } + } + } + + // If anything requires a new resource already, or the "id" field indicates + // that we will be creating a new resource, then we need to add that to + // RequiresReplace so that core can tell if the instance is being replaced + // even if changes are being suppressed via "ignore_changes". + id := plannedStateVal.GetAttr("id") + if len(requiresNew) > 0 || id.IsNull() || !id.IsKnown() { + requiresNew = append(requiresNew, "id") + } + + requiresReplace, err := hcl2shim.RequiresReplace(requiresNew, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // convert these to the protocol structures + for _, p := range requiresReplace { + resp.RequiresReplace = append(resp.RequiresReplace, pathToAttributePath(p)) + } + + return resp, nil +} + +func (s *GRPCProviderServer) ApplyResourceChange(ctx context.Context, req *proto.ApplyResourceChange_Request) (*proto.ApplyResourceChange_Response, error) { + resp := &proto.ApplyResourceChange_Response{ + // Start with the existing state as a fallback + NewState: req.PriorState, + } + + res, ok := s.provider.ResourcesMap[req.TypeName] + if !ok { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName)) + return resp, nil + } + schemaBlock := s.getResourceSchemaBlock(req.TypeName) + + priorStateVal, err := msgpack.Unmarshal(req.PriorState.Msgpack, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + plannedStateVal, err := msgpack.Unmarshal(req.PlannedState.Msgpack, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + priorState, err := res.ShimInstanceStateFromValue(priorStateVal) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + private := make(map[string]interface{}) + if len(req.PlannedPrivate) > 0 { + if err := json.Unmarshal(req.PlannedPrivate, &private); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + } + + var diff *terraform.InstanceDiff + destroy := false + + // a null state means we are destroying the instance + if plannedStateVal.IsNull() { + destroy = true + diff = &terraform.InstanceDiff{ + Attributes: make(map[string]*terraform.ResourceAttrDiff), + Meta: make(map[string]interface{}), + Destroy: true, + } + } else { + diff, err = schema.DiffFromValues(ctx, priorStateVal, plannedStateVal, stripResourceModifiers(res)) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + } + + if diff == nil { + diff = &terraform.InstanceDiff{ + Attributes: make(map[string]*terraform.ResourceAttrDiff), + Meta: make(map[string]interface{}), + } + } + + // add NewExtra Fields that may have been stored in the private data + if newExtra := private[newExtraKey]; newExtra != nil { + for k, v := range newExtra.(map[string]interface{}) { + d := diff.Attributes[k] + + if d == nil { + d = &terraform.ResourceAttrDiff{} + } + + d.NewExtra = v + diff.Attributes[k] = d + } + } + + if private != nil { + diff.Meta = private + } + + for k, d := range diff.Attributes { + // We need to turn off any RequiresNew. There could be attributes + // without changes in here inserted by helper/schema, but if they have + // RequiresNew then the state will be dropped from the ResourceData. + d.RequiresNew = false + + // Check that any "removed" attributes that don't actually exist in the + // prior state, or helper/schema will confuse itself + if d.NewRemoved { + if _, ok := priorState.Attributes[k]; !ok { + delete(diff.Attributes, k) + } + } + } + + pmSchemaBlock := s.getProviderMetaSchemaBlock() + if pmSchemaBlock != nil && req.ProviderMeta != nil { + providerSchemaVal, err := msgpack.Unmarshal(req.ProviderMeta.Msgpack, pmSchemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + priorState.ProviderMeta = providerSchemaVal + } + + newInstanceState, diags := res.Apply(ctx, priorState, diff, s.provider.Meta()) + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, diags) + + newStateVal := cty.NullVal(schemaBlock.ImpliedType()) + + // Always return a null value for destroy. + // While this is usually indicated by a nil state, check for missing ID or + // attributes in the case of a provider failure. + if destroy || newInstanceState == nil || newInstanceState.Attributes == nil || newInstanceState.ID == "" { + newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + resp.NewState = &proto.DynamicValue{ + Msgpack: newStateMP, + } + return resp, nil + } + + // We keep the null val if we destroyed the resource, otherwise build the + // entire object, even if the new state was nil. + newStateVal, err = schema.StateValueFromInstanceState(newInstanceState, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + newStateVal = normalizeNullValues(newStateVal, plannedStateVal, true) + + newStateVal = copyTimeoutValues(newStateVal, plannedStateVal) + + newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + resp.NewState = &proto.DynamicValue{ + Msgpack: newStateMP, + } + + meta, err := json.Marshal(newInstanceState.Meta) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + resp.Private = meta + + // This is a signal to Terraform Core that we're doing the best we can to + // shim the legacy type system of the SDK onto the Terraform type system + // but we need it to cut us some slack. This setting should not be taken + // forward to any new SDK implementations, since setting it prevents us + // from catching certain classes of provider bug that can lead to + // confusing downstream errors. + resp.LegacyTypeSystem = true + + return resp, nil +} + +func (s *GRPCProviderServer) ImportResourceState(ctx context.Context, req *proto.ImportResourceState_Request) (*proto.ImportResourceState_Response, error) { + resp := &proto.ImportResourceState_Response{} + + info := &terraform.InstanceInfo{ + Type: req.TypeName, + } + + newInstanceStates, err := s.provider.ImportState(ctx, info, req.Id) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + for _, is := range newInstanceStates { + // copy the ID again just to be sure it wasn't missed + is.Attributes["id"] = is.ID + + resourceType := is.Ephemeral.Type + if resourceType == "" { + resourceType = req.TypeName + } + + schemaBlock := s.getResourceSchemaBlock(resourceType) + newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(is.Attributes, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // Normalize the value and fill in any missing blocks. + newStateVal = objchange.NormalizeObjectFromLegacySDK(newStateVal, schemaBlock) + + newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + meta, err := json.Marshal(is.Meta) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + importedResource := &proto.ImportResourceState_ImportedResource{ + TypeName: resourceType, + State: &proto.DynamicValue{ + Msgpack: newStateMP, + }, + Private: meta, + } + + resp.ImportedResources = append(resp.ImportedResources, importedResource) + } + + return resp, nil +} + +func (s *GRPCProviderServer) ReadDataSource(ctx context.Context, req *proto.ReadDataSource_Request) (*proto.ReadDataSource_Response, error) { + resp := &proto.ReadDataSource_Response{} + + schemaBlock := s.getDatasourceSchemaBlock(req.TypeName) + + configVal, err := msgpack.Unmarshal(req.Config.Msgpack, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // Ensure there are no nulls that will cause helper/schema to panic. + if err := validateConfigNulls(configVal, nil); err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + config := terraform.NewResourceConfigShimmed(configVal, schemaBlock) + + // we need to still build the diff separately with the Read method to match + // the old behavior + res, ok := s.provider.DataSourcesMap[req.TypeName] + if !ok { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, fmt.Errorf("unknown data source: %s", req.TypeName)) + return resp, nil + } + diff, err := res.Diff(ctx, nil, config, s.provider.Meta()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + // now we can get the new complete data source + newInstanceState, diags := res.ReadDataApply(ctx, diff, s.provider.Meta()) + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, diags) + if diags.HasError() { + return resp, nil + } + + newStateVal, err := schema.StateValueFromInstanceState(newInstanceState, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + + newStateVal = copyTimeoutValues(newStateVal, configVal) + + newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType()) + if err != nil { + resp.Diagnostics = convert.AppendProtoDiag(resp.Diagnostics, err) + return resp, nil + } + resp.State = &proto.DynamicValue{ + Msgpack: newStateMP, + } + return resp, nil +} + +func pathToAttributePath(path cty.Path) *proto.AttributePath { + var steps []*proto.AttributePath_Step + + for _, step := range path { + switch s := step.(type) { + case cty.GetAttrStep: + steps = append(steps, &proto.AttributePath_Step{ + Selector: &proto.AttributePath_Step_AttributeName{ + AttributeName: s.Name, + }, + }) + case cty.IndexStep: + ty := s.Key.Type() + switch ty { + case cty.Number: + i, _ := s.Key.AsBigFloat().Int64() + steps = append(steps, &proto.AttributePath_Step{ + Selector: &proto.AttributePath_Step_ElementKeyInt{ + ElementKeyInt: i, + }, + }) + case cty.String: + steps = append(steps, &proto.AttributePath_Step{ + Selector: &proto.AttributePath_Step_ElementKeyString{ + ElementKeyString: s.Key.AsString(), + }, + }) + } + } + } + + return &proto.AttributePath{Steps: steps} +} + +// helper/schema throws away timeout values from the config and stores them in +// the Private/Meta fields. we need to copy those values into the planned state +// so that core doesn't see a perpetual diff with the timeout block. +func copyTimeoutValues(to cty.Value, from cty.Value) cty.Value { + // if `to` is null we are planning to remove it altogether. + if to.IsNull() { + return to + } + toAttrs := to.AsValueMap() + // We need to remove the key since the hcl2shims will add a non-null block + // because we can't determine if a single block was null from the flatmapped + // values. This needs to conform to the correct schema for marshaling, so + // change the value to null rather than deleting it from the object map. + timeouts, ok := toAttrs[schema.TimeoutsConfigKey] + if ok { + toAttrs[schema.TimeoutsConfigKey] = cty.NullVal(timeouts.Type()) + } + + // if from is null then there are no timeouts to copy + if from.IsNull() { + return cty.ObjectVal(toAttrs) + } + + fromAttrs := from.AsValueMap() + timeouts, ok = fromAttrs[schema.TimeoutsConfigKey] + + // timeouts shouldn't be unknown, but don't copy possibly invalid values either + if !ok || timeouts.IsNull() || !timeouts.IsWhollyKnown() { + // no timeouts block to copy + return cty.ObjectVal(toAttrs) + } + + toAttrs[schema.TimeoutsConfigKey] = timeouts + + return cty.ObjectVal(toAttrs) +} + +// stripResourceModifiers takes a *schema.Resource and returns a deep copy with all +// StateFuncs and CustomizeDiffs removed. This will be used during apply to +// create a diff from a planned state where the diff modifications have already +// been applied. +func stripResourceModifiers(r *schema.Resource) *schema.Resource { + if r == nil { + return nil + } + // start with a shallow copy + newResource := new(schema.Resource) + *newResource = *r + + newResource.CustomizeDiff = nil + newResource.Schema = map[string]*schema.Schema{} + + for k, s := range r.Schema { + newResource.Schema[k] = stripSchema(s) + } + + return newResource +} + +func stripSchema(s *schema.Schema) *schema.Schema { + if s == nil { + return nil + } + // start with a shallow copy + newSchema := new(schema.Schema) + *newSchema = *s + + newSchema.StateFunc = nil + + switch e := newSchema.Elem.(type) { + case *schema.Schema: + newSchema.Elem = stripSchema(e) + case *schema.Resource: + newSchema.Elem = stripResourceModifiers(e) + } + + return newSchema +} + +// Zero values and empty containers may be interchanged by the apply process. +// When there is a discrepency between src and dst value being null or empty, +// prefer the src value. This takes a little more liberty with set types, since +// we can't correlate modified set values. In the case of sets, if the src set +// was wholly known we assume the value was correctly applied and copy that +// entirely to the new value. +// While apply prefers the src value, during plan we prefer dst whenever there +// is an unknown or a set is involved, since the plan can alter the value +// however it sees fit. This however means that a CustomizeDiffFunction may not +// be able to change a null to an empty value or vice versa, but that should be +// very uncommon nor was it reliable before 0.12 either. +func normalizeNullValues(dst, src cty.Value, apply bool) cty.Value { + ty := dst.Type() + if !src.IsNull() && !src.IsKnown() { + // Return src during plan to retain unknown interpolated placeholders, + // which could be lost if we're only updating a resource. If this is a + // read scenario, then there shouldn't be any unknowns at all. + if dst.IsNull() && !apply { + return src + } + return dst + } + + // Handle null/empty changes for collections during apply. + // A change between null and empty values prefers src to make sure the state + // is consistent between plan and apply. + if ty.IsCollectionType() && apply { + dstEmpty := !dst.IsNull() && dst.IsKnown() && dst.LengthInt() == 0 + srcEmpty := !src.IsNull() && src.IsKnown() && src.LengthInt() == 0 + + if (src.IsNull() && dstEmpty) || (srcEmpty && dst.IsNull()) { + return src + } + } + + // check the invariants that we need below, to ensure we are working with + // non-null and known values. + if src.IsNull() || !src.IsKnown() || !dst.IsKnown() { + return dst + } + + switch { + case ty.IsMapType(), ty.IsObjectType(): + var dstMap map[string]cty.Value + if !dst.IsNull() { + dstMap = dst.AsValueMap() + } + if dstMap == nil { + dstMap = map[string]cty.Value{} + } + + srcMap := src.AsValueMap() + for key, v := range srcMap { + dstVal, ok := dstMap[key] + if !ok && apply && ty.IsMapType() { + // don't transfer old map values to dst during apply + continue + } + + if dstVal == cty.NilVal { + if !apply && ty.IsMapType() { + // let plan shape this map however it wants + continue + } + dstVal = cty.NullVal(v.Type()) + } + + dstMap[key] = normalizeNullValues(dstVal, v, apply) + } + + // you can't call MapVal/ObjectVal with empty maps, but nothing was + // copied in anyway. If the dst is nil, and the src is known, assume the + // src is correct. + if len(dstMap) == 0 { + if dst.IsNull() && src.IsWhollyKnown() && apply { + return src + } + return dst + } + + if ty.IsMapType() { + // helper/schema will populate an optional+computed map with + // unknowns which we have to fixup here. + // It would be preferable to simply prevent any known value from + // becoming unknown, but concessions have to be made to retain the + // broken legacy behavior when possible. + for k, srcVal := range srcMap { + if !srcVal.IsNull() && srcVal.IsKnown() { + dstVal, ok := dstMap[k] + if !ok { + continue + } + + if !dstVal.IsNull() && !dstVal.IsKnown() { + dstMap[k] = srcVal + } + } + } + + return cty.MapVal(dstMap) + } + + return cty.ObjectVal(dstMap) + + case ty.IsSetType(): + // If the original was wholly known, then we expect that is what the + // provider applied. The apply process loses too much information to + // reliably re-create the set. + if src.IsWhollyKnown() && apply { + return src + } + + case ty.IsListType(), ty.IsTupleType(): + // If the dst is null, and the src is known, then we lost an empty value + // so take the original. + if dst.IsNull() { + if src.IsWhollyKnown() && src.LengthInt() == 0 && apply { + return src + } + + // if dst is null and src only contains unknown values, then we lost + // those during a read or plan. + if !apply && !src.IsNull() { + allUnknown := true + for _, v := range src.AsValueSlice() { + if v.IsKnown() { + allUnknown = false + break + } + } + if allUnknown { + return src + } + } + + return dst + } + + // if the lengths are identical, then iterate over each element in succession. + srcLen := src.LengthInt() + dstLen := dst.LengthInt() + if srcLen == dstLen && srcLen > 0 { + srcs := src.AsValueSlice() + dsts := dst.AsValueSlice() + + for i := 0; i < srcLen; i++ { + dsts[i] = normalizeNullValues(dsts[i], srcs[i], apply) + } + + if ty.IsTupleType() { + return cty.TupleVal(dsts) + } + return cty.ListVal(dsts) + } + + case ty == cty.String: + // The legacy SDK should not be able to remove a value during plan or + // apply, however we are only going to overwrite this if the source was + // an empty string, since that is what is often equated with unset and + // lost in the diff process. + if dst.IsNull() && src.AsString() == "" { + return src + } + } + + return dst +} + +// validateConfigNulls checks a config value for unsupported nulls before +// attempting to shim the value. While null values can mostly be ignored in the +// configuration, since they're not supported in HCL1, the case where a null +// appears in a list-like attribute (list, set, tuple) will present a nil value +// to helper/schema which can panic. Return an error to the user in this case, +// indicating the attribute with the null value. +func validateConfigNulls(v cty.Value, path cty.Path) []*proto.Diagnostic { + var diags []*proto.Diagnostic + if v.IsNull() || !v.IsKnown() { + return diags + } + + switch { + case v.Type().IsListType() || v.Type().IsSetType() || v.Type().IsTupleType(): + it := v.ElementIterator() + for it.Next() { + kv, ev := it.Element() + if ev.IsNull() { + // if this is a set, the kv is also going to be null which + // isn't a valid path element, so we can't append it to the + // diagnostic. + p := path + if !kv.IsNull() { + p = append(p, cty.IndexStep{Key: kv}) + } + + diags = append(diags, &proto.Diagnostic{ + Severity: proto.Diagnostic_ERROR, + Summary: "Null value found in list", + Detail: "Null values are not allowed for this attribute value.", + Attribute: convert.PathToAttributePath(p), + }) + continue + } + + d := validateConfigNulls(ev, append(path, cty.IndexStep{Key: kv})) + diags = convert.AppendProtoDiag(diags, d) + } + + case v.Type().IsMapType() || v.Type().IsObjectType(): + it := v.ElementIterator() + for it.Next() { + kv, ev := it.Element() + var step cty.PathStep + switch { + case v.Type().IsMapType(): + step = cty.IndexStep{Key: kv} + case v.Type().IsObjectType(): + step = cty.GetAttrStep{Name: kv.AsString()} + } + d := validateConfigNulls(ev, append(path, step)) + diags = convert.AppendProtoDiag(diags, d) + } + } + + return diags +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/unknown.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/unknown.go new file mode 100644 index 00000000000..fcf156b2dad --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin/unknown.go @@ -0,0 +1,132 @@ +package plugin + +import ( + "fmt" + + "github.com/hashicorp/go-cty/cty" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" +) + +// SetUnknowns takes a cty.Value, and compares it to the schema setting any null +// values which are computed to unknown. +func SetUnknowns(val cty.Value, schema *configschema.Block) cty.Value { + if !val.IsKnown() { + return val + } + + // If the object was null, we still need to handle the top level attributes + // which might be computed, but we don't need to expand the blocks. + if val.IsNull() { + objMap := map[string]cty.Value{} + allNull := true + for name, attr := range schema.Attributes { + switch { + case attr.Computed: + objMap[name] = cty.UnknownVal(attr.Type) + allNull = false + default: + objMap[name] = cty.NullVal(attr.Type) + } + } + + // If this object has no unknown attributes, then we can leave it null. + if allNull { + return val + } + + return cty.ObjectVal(objMap) + } + + valMap := val.AsValueMap() + newVals := make(map[string]cty.Value) + + for name, attr := range schema.Attributes { + v := valMap[name] + + if attr.Computed && v.IsNull() { + newVals[name] = cty.UnknownVal(attr.Type) + continue + } + + newVals[name] = v + } + + for name, blockS := range schema.BlockTypes { + blockVal := valMap[name] + if blockVal.IsNull() || !blockVal.IsKnown() { + newVals[name] = blockVal + continue + } + + blockValType := blockVal.Type() + blockElementType := blockS.Block.ImpliedType() + + // This switches on the value type here, so we can correctly switch + // between Tuples/Lists and Maps/Objects. + switch { + case blockS.Nesting == configschema.NestingSingle || blockS.Nesting == configschema.NestingGroup: + // NestingSingle is the only exception here, where we treat the + // block directly as an object + newVals[name] = SetUnknowns(blockVal, &blockS.Block) + + case blockValType.IsSetType(), blockValType.IsListType(), blockValType.IsTupleType(): + listVals := blockVal.AsValueSlice() + newListVals := make([]cty.Value, 0, len(listVals)) + + for _, v := range listVals { + newListVals = append(newListVals, SetUnknowns(v, &blockS.Block)) + } + + switch { + case blockValType.IsSetType(): + switch len(newListVals) { + case 0: + newVals[name] = cty.SetValEmpty(blockElementType) + default: + newVals[name] = cty.SetVal(newListVals) + } + case blockValType.IsListType(): + switch len(newListVals) { + case 0: + newVals[name] = cty.ListValEmpty(blockElementType) + default: + newVals[name] = cty.ListVal(newListVals) + } + case blockValType.IsTupleType(): + newVals[name] = cty.TupleVal(newListVals) + } + + case blockValType.IsMapType(), blockValType.IsObjectType(): + mapVals := blockVal.AsValueMap() + newMapVals := make(map[string]cty.Value) + + for k, v := range mapVals { + newMapVals[k] = SetUnknowns(v, &blockS.Block) + } + + switch { + case blockValType.IsMapType(): + switch len(newMapVals) { + case 0: + newVals[name] = cty.MapValEmpty(blockElementType) + default: + newVals[name] = cty.MapVal(newMapVals) + } + case blockValType.IsObjectType(): + if len(newMapVals) == 0 { + // We need to populate empty values to make a valid object. + for attr, ty := range blockElementType.AttributeTypes() { + newMapVals[attr] = cty.NullVal(ty) + } + } + newVals[name] = cty.ObjectVal(newMapVals) + } + + default: + panic(fmt.Sprintf("failed to set unknown values for nested block %q:%#v", name, blockValType)) + } + } + + return cty.ObjectVal(newVals) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/normalize_obj.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plans/objchange/normalize_obj.go similarity index 97% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/normalize_obj.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plans/objchange/normalize_obj.go index a8629046cad..0189190ed08 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/plans/objchange/normalize_obj.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plans/objchange/normalize_obj.go @@ -1,8 +1,9 @@ package objchange import ( - "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" - "github.com/zclconf/go-cty/cty" + "github.com/hashicorp/go-cty/cty" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" ) // NormalizeObjectFromLegacySDK takes an object that may have been generated diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/diagnostics.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/diagnostics.go new file mode 100644 index 00000000000..d7bfb06768f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/diagnostics.go @@ -0,0 +1,142 @@ +package convert + +import ( + "fmt" + + "github.com/hashicorp/go-cty/cty" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + proto "github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5" +) + +// AppendProtoDiag appends a new diagnostic from a warning string or an error. +// This panics if d is not a string or error. +func AppendProtoDiag(diags []*proto.Diagnostic, d interface{}) []*proto.Diagnostic { + switch d := d.(type) { + case cty.PathError: + ap := PathToAttributePath(d.Path) + diags = append(diags, &proto.Diagnostic{ + Severity: proto.Diagnostic_ERROR, + Summary: d.Error(), + Attribute: ap, + }) + case diag.Diagnostics: + diags = append(diags, DiagsToProto(d)...) + case error: + diags = append(diags, &proto.Diagnostic{ + Severity: proto.Diagnostic_ERROR, + Summary: d.Error(), + }) + case string: + diags = append(diags, &proto.Diagnostic{ + Severity: proto.Diagnostic_WARNING, + Summary: d, + }) + case *proto.Diagnostic: + diags = append(diags, d) + case []*proto.Diagnostic: + diags = append(diags, d...) + } + return diags +} + +// ProtoToDiags converts a list of proto.Diagnostics to a diag.Diagnostics. +func ProtoToDiags(ds []*proto.Diagnostic) diag.Diagnostics { + var diags diag.Diagnostics + for _, d := range ds { + var severity diag.Severity + + switch d.Severity { + case proto.Diagnostic_ERROR: + severity = diag.Error + case proto.Diagnostic_WARNING: + severity = diag.Warning + } + + diags = append(diags, diag.Diagnostic{ + Severity: severity, + Summary: d.Summary, + Detail: d.Detail, + AttributePath: AttributePathToPath(d.Attribute), + }) + } + + return diags +} + +func DiagsToProto(diags diag.Diagnostics) []*proto.Diagnostic { + var ds []*proto.Diagnostic + for _, d := range diags { + if err := d.Validate(); err != nil { + panic(fmt.Errorf("Invalid diagnostic: %s. This is always a bug in the provider implementation", err)) + } + protoDiag := &proto.Diagnostic{ + Summary: d.Summary, + Detail: d.Detail, + Attribute: PathToAttributePath(d.AttributePath), + } + if d.Severity == diag.Error { + protoDiag.Severity = proto.Diagnostic_ERROR + } else if d.Severity == diag.Warning { + protoDiag.Severity = proto.Diagnostic_WARNING + } + ds = append(ds, protoDiag) + } + return ds +} + +// AttributePathToPath takes the proto encoded path and converts it to a cty.Path +func AttributePathToPath(ap *proto.AttributePath) cty.Path { + var p cty.Path + if ap == nil { + return p + } + for _, step := range ap.Steps { + switch selector := step.Selector.(type) { + case *proto.AttributePath_Step_AttributeName: + p = p.GetAttr(selector.AttributeName) + case *proto.AttributePath_Step_ElementKeyString: + p = p.Index(cty.StringVal(selector.ElementKeyString)) + case *proto.AttributePath_Step_ElementKeyInt: + p = p.Index(cty.NumberIntVal(selector.ElementKeyInt)) + } + } + return p +} + +// PathToAttributePath takes a cty.Path and converts it to a proto-encoded path. +func PathToAttributePath(p cty.Path) *proto.AttributePath { + ap := &proto.AttributePath{} + for _, step := range p { + switch selector := step.(type) { + case cty.GetAttrStep: + ap.Steps = append(ap.Steps, &proto.AttributePath_Step{ + Selector: &proto.AttributePath_Step_AttributeName{ + AttributeName: selector.Name, + }, + }) + case cty.IndexStep: + key := selector.Key + switch key.Type() { + case cty.String: + ap.Steps = append(ap.Steps, &proto.AttributePath_Step{ + Selector: &proto.AttributePath_Step_ElementKeyString{ + ElementKeyString: key.AsString(), + }, + }) + case cty.Number: + v, _ := key.AsBigFloat().Int64() + ap.Steps = append(ap.Steps, &proto.AttributePath_Step{ + Selector: &proto.AttributePath_Step_ElementKeyInt{ + ElementKeyInt: v, + }, + }) + default: + // We'll bail early if we encounter anything else, and just + // return the valid prefix. + return ap + } + } + } + return ap +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/schema.go new file mode 100644 index 00000000000..4921ebab2e9 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert/schema.go @@ -0,0 +1,183 @@ +package convert + +import ( + "encoding/json" + "log" + "reflect" + "sort" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" + proto "github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5" +) + +// ConfigSchemaToProto takes a *configschema.Block and converts it to a +// proto.Schema_Block for a grpc response. +func ConfigSchemaToProto(b *configschema.Block) *proto.Schema_Block { + block := &proto.Schema_Block{ + Description: b.Description, + DescriptionKind: protoStringKind(b.DescriptionKind), + Deprecated: b.Deprecated, + } + + for _, name := range sortedKeys(b.Attributes) { + a := b.Attributes[name] + + attr := &proto.Schema_Attribute{ + Name: name, + Description: a.Description, + DescriptionKind: protoStringKind(a.DescriptionKind), + Optional: a.Optional, + Computed: a.Computed, + Required: a.Required, + Sensitive: a.Sensitive, + Deprecated: a.Deprecated, + } + + ty, err := json.Marshal(a.Type) + if err != nil { + panic(err) + } + + attr.Type = ty + + block.Attributes = append(block.Attributes, attr) + } + + for _, name := range sortedKeys(b.BlockTypes) { + b := b.BlockTypes[name] + block.BlockTypes = append(block.BlockTypes, protoSchemaNestedBlock(name, b)) + } + + return block +} + +func protoStringKind(k configschema.StringKind) proto.StringKind { + switch k { + default: + log.Printf("[TRACE] unexpected configschema.StringKind: %d", k) + return proto.StringKind_PLAIN + case configschema.StringPlain: + return proto.StringKind_PLAIN + case configschema.StringMarkdown: + return proto.StringKind_MARKDOWN + } +} + +func protoSchemaNestedBlock(name string, b *configschema.NestedBlock) *proto.Schema_NestedBlock { + var nesting proto.Schema_NestedBlock_NestingMode + switch b.Nesting { + case configschema.NestingSingle: + nesting = proto.Schema_NestedBlock_SINGLE + case configschema.NestingGroup: + nesting = proto.Schema_NestedBlock_GROUP + case configschema.NestingList: + nesting = proto.Schema_NestedBlock_LIST + case configschema.NestingSet: + nesting = proto.Schema_NestedBlock_SET + case configschema.NestingMap: + nesting = proto.Schema_NestedBlock_MAP + default: + nesting = proto.Schema_NestedBlock_INVALID + } + return &proto.Schema_NestedBlock{ + TypeName: name, + Block: ConfigSchemaToProto(&b.Block), + Nesting: nesting, + MinItems: int64(b.MinItems), + MaxItems: int64(b.MaxItems), + } +} + +// ProtoToConfigSchema takes the GetSchcema_Block from a grpc response and converts it +// to a terraform *configschema.Block. +func ProtoToConfigSchema(b *proto.Schema_Block) *configschema.Block { + block := &configschema.Block{ + Attributes: make(map[string]*configschema.Attribute), + BlockTypes: make(map[string]*configschema.NestedBlock), + + Description: b.Description, + DescriptionKind: schemaStringKind(b.DescriptionKind), + Deprecated: b.Deprecated, + } + + for _, a := range b.Attributes { + attr := &configschema.Attribute{ + Description: a.Description, + DescriptionKind: schemaStringKind(a.DescriptionKind), + Required: a.Required, + Optional: a.Optional, + Computed: a.Computed, + Sensitive: a.Sensitive, + Deprecated: a.Deprecated, + } + + if err := json.Unmarshal(a.Type, &attr.Type); err != nil { + panic(err) + } + + block.Attributes[a.Name] = attr + } + + for _, b := range b.BlockTypes { + block.BlockTypes[b.TypeName] = schemaNestedBlock(b) + } + + return block +} + +func schemaStringKind(k proto.StringKind) configschema.StringKind { + switch k { + default: + log.Printf("[TRACE] unexpected proto.StringKind: %d", k) + return configschema.StringPlain + case proto.StringKind_PLAIN: + return configschema.StringPlain + case proto.StringKind_MARKDOWN: + return configschema.StringMarkdown + } +} + +func schemaNestedBlock(b *proto.Schema_NestedBlock) *configschema.NestedBlock { + var nesting configschema.NestingMode + switch b.Nesting { + case proto.Schema_NestedBlock_SINGLE: + nesting = configschema.NestingSingle + case proto.Schema_NestedBlock_GROUP: + nesting = configschema.NestingGroup + case proto.Schema_NestedBlock_LIST: + nesting = configschema.NestingList + case proto.Schema_NestedBlock_MAP: + nesting = configschema.NestingMap + case proto.Schema_NestedBlock_SET: + nesting = configschema.NestingSet + default: + // In all other cases we'll leave it as the zero value (invalid) and + // let the caller validate it and deal with this. + } + + nb := &configschema.NestedBlock{ + Nesting: nesting, + MinItems: int(b.MinItems), + MaxItems: int(b.MaxItems), + } + + nested := ProtoToConfigSchema(b.Block) + nb.Block = *nested + return nb +} + +// sortedKeys returns the lexically sorted keys from the given map. This is +// used to make schema conversions are deterministic. This panics if map keys +// are not a string. +func sortedKeys(m interface{}) []string { + v := reflect.ValueOf(m) + keys := make([]string, v.Len()) + + mapKeys := v.MapKeys() + for i, k := range mapKeys { + keys[i] = k.Interface().(string) + } + + sort.Strings(keys) + return keys +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/config_traversals.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/config_traversals.go new file mode 100644 index 00000000000..2201d0c0bef --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/config_traversals.go @@ -0,0 +1,56 @@ +package tfdiags + +import ( + "bytes" + "fmt" + "strconv" + + "github.com/hashicorp/go-cty/cty" +) + +// FormatCtyPath is a helper function to produce a user-friendly string +// representation of a cty.Path. The result uses a syntax similar to the +// HCL expression language in the hope of it being familiar to users. +func FormatCtyPath(path cty.Path) string { + var buf bytes.Buffer + for _, step := range path { + switch ts := step.(type) { + case cty.GetAttrStep: + fmt.Fprintf(&buf, ".%s", ts.Name) + case cty.IndexStep: + buf.WriteByte('[') + key := ts.Key + keyTy := key.Type() + switch { + case key.IsNull(): + buf.WriteString("null") + case !key.IsKnown(): + buf.WriteString("(not yet known)") + case keyTy == cty.Number: + bf := key.AsBigFloat() + buf.WriteString(bf.Text('g', -1)) + case keyTy == cty.String: + buf.WriteString(strconv.Quote(key.AsString())) + default: + buf.WriteString("...") + } + buf.WriteByte(']') + } + } + return buf.String() +} + +// FormatError is a helper function to produce a user-friendly string +// representation of certain special error types that we might want to +// include in diagnostic messages. +// +// This currently has special behavior only for cty.PathError, where a +// non-empty path is rendered in a HCL-like syntax as context. +func FormatError(err error) string { + perr, ok := err.(cty.PathError) + if !ok || len(perr.Path) == 0 { + return err.Error() + } + + return fmt.Sprintf("%s: %s", FormatCtyPath(perr.Path), perr.Error()) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/contextual.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/contextual.go new file mode 100644 index 00000000000..b063bc1de23 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/contextual.go @@ -0,0 +1,81 @@ +package tfdiags + +import ( + "github.com/hashicorp/go-cty/cty" +) + +// AttributeValue returns a diagnostic about an attribute value in an implied current +// configuration context. This should be returned only from functions whose +// interface specifies a clear configuration context that this will be +// resolved in. +// +// The given path is relative to the implied configuration context. To describe +// a top-level attribute, it should be a single-element cty.Path with a +// cty.GetAttrStep. It's assumed that the path is returning into a structure +// that would be produced by our conventions in the configschema package; it +// may return unexpected results for structures that can't be represented by +// configschema. +// +// Since mapping attribute paths back onto configuration is an imprecise +// operation (e.g. dynamic block generation may cause the same block to be +// evaluated multiple times) the diagnostic detail should include the attribute +// name and other context required to help the user understand what is being +// referenced in case the identified source range is not unique. +// +// The returned attribute will not have source location information until +// context is applied to the containing diagnostics using diags.InConfigBody. +// After context is applied, the source location is the value assigned to the +// named attribute, or the containing body's "missing item range" if no +// value is present. +func AttributeValue(severity Severity, summary, detail string, attrPath cty.Path) Diagnostic { + return &attributeDiagnostic{ + diagnosticBase: diagnosticBase{ + severity: severity, + summary: summary, + detail: detail, + }, + attrPath: attrPath, + } +} + +// GetAttribute extracts an attribute cty.Path from a diagnostic if it contains +// one. Normally this is not accessed directly, and instead the config body is +// added to the Diagnostic to create a more complete message for the user. In +// some cases however, we may want to know just the name of the attribute that +// generated the Diagnostic message. +// This returns a nil cty.Path if it does not exist in the Diagnostic. +func GetAttribute(d Diagnostic) cty.Path { + if d, ok := d.(*attributeDiagnostic); ok { + return d.attrPath + } + return nil +} + +type attributeDiagnostic struct { + diagnosticBase + attrPath cty.Path +} + +// WholeContainingBody returns a diagnostic about the body that is an implied +// current configuration context. This should be returned only from +// functions whose interface specifies a clear configuration context that this +// will be resolved in. +// +// The returned attribute will not have source location information until +// context is applied to the containing diagnostics using diags.InConfigBody. +// After context is applied, the source location is currently the missing item +// range of the body. In future, this may change to some other suitable +// part of the containing body. +func WholeContainingBody(severity Severity, summary, detail string) Diagnostic { + return &wholeBodyDiagnostic{ + diagnosticBase: diagnosticBase{ + severity: severity, + summary: summary, + detail: detail, + }, + } +} + +type wholeBodyDiagnostic struct { + diagnosticBase +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/diagnostic.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/diagnostic.go new file mode 100644 index 00000000000..a36da370f8d --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/diagnostic.go @@ -0,0 +1,20 @@ +package tfdiags + +type Diagnostic interface { + Severity() Severity + Description() Description +} + +type Severity rune + +//go:generate go run golang.org/x/tools/cmd/stringer -type=Severity + +const ( + Error Severity = 'E' + Warning Severity = 'W' +) + +type Description struct { + Summary string + Detail string +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/diagnostic_base.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/diagnostic_base.go new file mode 100644 index 00000000000..34816208786 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/diagnostic_base.go @@ -0,0 +1,31 @@ +package tfdiags + +// diagnosticBase can be embedded in other diagnostic structs to get +// default implementations of Severity and Description. This type also +// has default implementations of Source that return no source +// location or expression-related information, so embedders should generally +// override those method to return more useful results where possible. +type diagnosticBase struct { + severity Severity + summary string + detail string +} + +func (d diagnosticBase) Severity() Severity { + return d.severity +} + +func (d diagnosticBase) Description() Description { + return Description{ + Summary: d.summary, + Detail: d.detail, + } +} + +func Diag(sev Severity, summary, detail string) Diagnostic { + return &diagnosticBase{ + severity: sev, + summary: summary, + detail: detail, + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/diagnostics.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/diagnostics.go new file mode 100644 index 00000000000..925c14fa7b6 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/diagnostics.go @@ -0,0 +1,211 @@ +package tfdiags + +import ( + "bytes" + "fmt" + "sort" +) + +// Diagnostics is a list of diagnostics. Diagnostics is intended to be used +// where a Go "error" might normally be used, allowing richer information +// to be conveyed (more context, support for warnings). +// +// A nil Diagnostics is a valid, empty diagnostics list, thus allowing +// heap allocation to be avoided in the common case where there are no +// diagnostics to report at all. +type Diagnostics []Diagnostic + +// HasErrors returns true if any of the diagnostics in the list have +// a severity of Error. +func (diags Diagnostics) HasErrors() bool { + for _, diag := range diags { + if diag.Severity() == Error { + return true + } + } + return false +} + +// ForRPC returns a version of the receiver that has been simplified so that +// it is friendly to RPC protocols. +// +// Currently this means that it can be serialized with encoding/gob and +// subsequently re-inflated. It may later grow to include other serialization +// formats. +// +// Note that this loses information about the original objects used to +// construct the diagnostics, so e.g. the errwrap API will not work as +// expected on an error-wrapped Diagnostics that came from ForRPC. +func (diags Diagnostics) ForRPC() Diagnostics { + ret := make(Diagnostics, len(diags)) + for i := range diags { + ret[i] = makeRPCFriendlyDiag(diags[i]) + } + return ret +} + +// Err flattens a diagnostics list into a single Go error, or to nil +// if the diagnostics list does not include any error-level diagnostics. +// +// This can be used to smuggle diagnostics through an API that deals in +// native errors, but unfortunately it will lose naked warnings (warnings +// that aren't accompanied by at least one error) since such APIs have no +// mechanism through which to report these. +// +// return result, diags.Error() +func (diags Diagnostics) Err() error { + if !diags.HasErrors() { + return nil + } + return diagnosticsAsError{diags} +} + +// ErrWithWarnings is similar to Err except that it will also return a non-nil +// error if the receiver contains only warnings. +// +// In the warnings-only situation, the result is guaranteed to be of dynamic +// type NonFatalError, allowing diagnostics-aware callers to type-assert +// and unwrap it, treating it as non-fatal. +// +// This should be used only in contexts where the caller is able to recognize +// and handle NonFatalError. For normal callers that expect a lack of errors +// to be signaled by nil, use just Diagnostics.Err. +func (diags Diagnostics) ErrWithWarnings() error { + if len(diags) == 0 { + return nil + } + if diags.HasErrors() { + return diags.Err() + } + return NonFatalError{diags} +} + +// NonFatalErr is similar to Err except that it always returns either nil +// (if there are no diagnostics at all) or NonFatalError. +// +// This allows diagnostics to be returned over an error return channel while +// being explicit that the diagnostics should not halt processing. +// +// This should be used only in contexts where the caller is able to recognize +// and handle NonFatalError. For normal callers that expect a lack of errors +// to be signaled by nil, use just Diagnostics.Err. +func (diags Diagnostics) NonFatalErr() error { + if len(diags) == 0 { + return nil + } + return NonFatalError{diags} +} + +type diagnosticsAsError struct { + Diagnostics +} + +func (dae diagnosticsAsError) Error() string { + diags := dae.Diagnostics + switch { + case len(diags) == 0: + // should never happen, since we don't create this wrapper if + // there are no diagnostics in the list. + return "no errors" + case len(diags) == 1: + desc := diags[0].Description() + if desc.Detail == "" { + return desc.Summary + } + return fmt.Sprintf("%s: %s", desc.Summary, desc.Detail) + default: + var ret bytes.Buffer + fmt.Fprintf(&ret, "%d problems:\n", len(diags)) + for _, diag := range dae.Diagnostics { + desc := diag.Description() + if desc.Detail == "" { + fmt.Fprintf(&ret, "\n- %s", desc.Summary) + } else { + fmt.Fprintf(&ret, "\n- %s: %s", desc.Summary, desc.Detail) + } + } + return ret.String() + } +} + +// WrappedErrors is an implementation of errwrap.Wrapper so that an error-wrapped +// diagnostics object can be picked apart by errwrap-aware code. +func (dae diagnosticsAsError) WrappedErrors() []error { + var errs []error + for _, diag := range dae.Diagnostics { + if wrapper, isErr := diag.(nativeError); isErr { + errs = append(errs, wrapper.err) + } + } + return errs +} + +// NonFatalError is a special error type, returned by +// Diagnostics.ErrWithWarnings and Diagnostics.NonFatalErr, +// that indicates that the wrapped diagnostics should be treated as non-fatal. +// Callers can conditionally type-assert an error to this type in order to +// detect the non-fatal scenario and handle it in a different way. +type NonFatalError struct { + Diagnostics +} + +func (woe NonFatalError) Error() string { + diags := woe.Diagnostics + switch { + case len(diags) == 0: + // should never happen, since we don't create this wrapper if + // there are no diagnostics in the list. + return "no errors or warnings" + case len(diags) == 1: + desc := diags[0].Description() + if desc.Detail == "" { + return desc.Summary + } + return fmt.Sprintf("%s: %s", desc.Summary, desc.Detail) + default: + var ret bytes.Buffer + if diags.HasErrors() { + fmt.Fprintf(&ret, "%d problems:\n", len(diags)) + } else { + fmt.Fprintf(&ret, "%d warnings:\n", len(diags)) + } + for _, diag := range woe.Diagnostics { + desc := diag.Description() + if desc.Detail == "" { + fmt.Fprintf(&ret, "\n- %s", desc.Summary) + } else { + fmt.Fprintf(&ret, "\n- %s: %s", desc.Summary, desc.Detail) + } + } + return ret.String() + } +} + +// sortDiagnostics is an implementation of sort.Interface +type sortDiagnostics []Diagnostic + +var _ sort.Interface = sortDiagnostics(nil) + +func (sd sortDiagnostics) Len() int { + return len(sd) +} + +func (sd sortDiagnostics) Less(i, j int) bool { + iD, jD := sd[i], sd[j] + iSev, jSev := iD.Severity(), jD.Severity() + + switch { + case iSev != jSev: + return iSev == Warning + default: + // The remaining properties do not have a defined ordering, so + // we'll leave it unspecified. Since we use sort.Stable in + // the caller of this, the ordering of remaining items will + // be preserved. + return false + } +} + +func (sd sortDiagnostics) Swap(i, j int) { + sd[i], sd[j] = sd[j], sd[i] +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/doc.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/doc.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/doc.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/doc.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/error.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/error.go new file mode 100644 index 00000000000..b63c5d74150 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/error.go @@ -0,0 +1,24 @@ +package tfdiags + +// nativeError is a Diagnostic implementation that wraps a normal Go error +type nativeError struct { + err error +} + +var _ Diagnostic = nativeError{} + +func (e nativeError) Severity() Severity { + return Error +} + +func (e nativeError) Description() Description { + return Description{ + Summary: FormatError(e.err), + } +} + +func FromError(err error) Diagnostic { + return &nativeError{ + err: err, + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/rpc_friendly.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/rpc_friendly.go new file mode 100644 index 00000000000..1b78887eb98 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/rpc_friendly.go @@ -0,0 +1,41 @@ +package tfdiags + +import ( + "encoding/gob" +) + +type rpcFriendlyDiag struct { + Severity_ Severity + Summary_ string + Detail_ string +} + +// rpcFriendlyDiag transforms a given diagnostic so that is more friendly to +// RPC. +// +// In particular, it currently returns an object that can be serialized and +// later re-inflated using gob. This definition may grow to include other +// serializations later. +func makeRPCFriendlyDiag(diag Diagnostic) Diagnostic { + desc := diag.Description() + return &rpcFriendlyDiag{ + Severity_: diag.Severity(), + Summary_: desc.Summary, + Detail_: desc.Detail, + } +} + +func (d *rpcFriendlyDiag) Severity() Severity { + return d.Severity_ +} + +func (d *rpcFriendlyDiag) Description() Description { + return Description{ + Summary: d.Summary_, + Detail: d.Detail_, + } +} + +func init() { + gob.Register((*rpcFriendlyDiag)(nil)) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/severity_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/severity_string.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/severity_string.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/severity_string.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/simple_warning.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/simple_warning.go new file mode 100644 index 00000000000..0919170456c --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfdiags/simple_warning.go @@ -0,0 +1,20 @@ +package tfdiags + +type simpleWarning string + +var _ Diagnostic = simpleWarning("") + +// SimpleWarning constructs a simple (summary-only) warning diagnostic. +func SimpleWarning(msg string) Diagnostic { + return simpleWarning(msg) +} + +func (e simpleWarning) Severity() Severity { + return Warning +} + +func (e simpleWarning) Description() Description { + return Description{ + Summary: string(e), + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5/generate.sh b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5/generate.sh similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5/generate.sh rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5/generate.sh diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5/tfplugin5.pb.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5/tfplugin5.pb.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5/tfplugin5.pb.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5/tfplugin5.pb.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5/tfplugin5.proto b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5/tfplugin5.proto similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfplugin5/tfplugin5.proto rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5/tfplugin5.proto diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/meta/meta.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/meta/meta.go new file mode 100644 index 00000000000..e626faa3a3a --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/meta/meta.go @@ -0,0 +1,36 @@ +// The meta package provides a location to set the release version +// and any other relevant metadata for the SDK. +// +// This package should not import any other SDK packages. +package meta + +import ( + "fmt" + + version "github.com/hashicorp/go-version" +) + +// The main version number that is being run at the moment. +var SDKVersion = "2.0.1" + +// A pre-release marker for the version. If this is "" (empty string) +// then it means that it is a final release. Otherwise, this is a pre-release +// such as "dev" (in development), "beta", "rc1", etc. +var SDKPrerelease = "" + +// SemVer is an instance of version.Version. This has the secondary +// benefit of verifying during tests and init time that our version is a +// proper semantic version, which should always be the case. +var SemVer *version.Version + +func init() { + SemVer = version.Must(version.NewVersion(SDKVersion)) +} + +// VersionString returns the complete version string, including prerelease +func SDKVersionString() string { + if SDKPrerelease != "" { + return fmt.Sprintf("%s-%s", SDKVersion, SDKPrerelease) + } + return SDKVersion +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/debug.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/debug.go new file mode 100644 index 00000000000..6f30f1d1e9e --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/debug.go @@ -0,0 +1,102 @@ +package plugin + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/signal" + "time" + + "github.com/hashicorp/go-plugin" +) + +// ReattachConfig holds the information Terraform needs to be able to attach +// itself to a provider process, so it can drive the process. +type ReattachConfig struct { + Protocol string + Pid int + Test bool + Addr ReattachConfigAddr +} + +// ReattachConfigAddr is a JSON-encoding friendly version of net.Addr. +type ReattachConfigAddr struct { + Network string + String string +} + +// DebugServe starts a plugin server in debug mode; this should only be used +// when the provider will manage its own lifecycle. It is not recommended for +// normal usage; Serve is the correct function for that. +func DebugServe(ctx context.Context, opts *ServeOpts) (ReattachConfig, <-chan struct{}, error) { + reattachCh := make(chan *plugin.ReattachConfig) + closeCh := make(chan struct{}) + + opts.TestConfig = &plugin.ServeTestConfig{ + Context: ctx, + ReattachConfigCh: reattachCh, + CloseCh: closeCh, + } + + go Serve(opts) + + var config *plugin.ReattachConfig + select { + case config = <-reattachCh: + case <-time.After(2 * time.Second): + return ReattachConfig{}, closeCh, errors.New("timeout waiting on reattach config") + } + + if config == nil { + return ReattachConfig{}, closeCh, errors.New("nil reattach config received") + } + + return ReattachConfig{ + Protocol: string(config.Protocol), + Pid: config.Pid, + Test: config.Test, + Addr: ReattachConfigAddr{ + Network: config.Addr.Network(), + String: config.Addr.String(), + }, + }, closeCh, nil +} + +// Debug starts a debug server and controls its lifecycle, printing the +// information needed for Terraform to connect to the provider to stdout. +// os.Interrupt will be captured and used to stop the server. +func Debug(ctx context.Context, providerAddr string, opts *ServeOpts) error { + ctx, cancel := context.WithCancel(ctx) + // Ctrl-C will stop the server + sigCh := make(chan os.Signal, 1) + signal.Notify(sigCh, os.Interrupt) + defer func() { + signal.Stop(sigCh) + cancel() + }() + config, closeCh, err := DebugServe(ctx, opts) + if err != nil { + return fmt.Errorf("Error launching debug server: %w", err) + } + go func() { + select { + case <-sigCh: + cancel() + case <-ctx.Done(): + } + }() + reattachStr, err := json.Marshal(map[string]ReattachConfig{ + providerAddr: config, + }) + if err != nil { + return fmt.Errorf("Error building reattach string: %w", err) + } + + fmt.Printf("Provider server started; to attach Terraform, set TF_REATTACH_PROVIDERS to the following:\n%s\n", string(reattachStr)) + + // wait for the server to be done + <-closeCh + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/grpc_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/grpc_provider.go new file mode 100644 index 00000000000..4a605ce3ac5 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/grpc_provider.go @@ -0,0 +1,41 @@ +package plugin + +import ( + "context" + "errors" + "net/rpc" + + plugin "github.com/hashicorp/go-plugin" + "google.golang.org/grpc" + + proto "github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5" +) + +var ( + _ plugin.GRPCPlugin = (*gRPCProviderPlugin)(nil) + _ plugin.Plugin = (*gRPCProviderPlugin)(nil) +) + +// gRPCProviderPlugin implements plugin.GRPCPlugin and plugin.Plugin for the go-plugin package. +// the only real implementation is GRPCSServer, the other methods are only satisfied +// for compatibility with go-plugin +type gRPCProviderPlugin struct { + GRPCProvider func() proto.ProviderServer +} + +func (p *gRPCProviderPlugin) Server(*plugin.MuxBroker) (interface{}, error) { + return nil, errors.New("terraform-plugin-sdk only implements grpc servers") +} + +func (p *gRPCProviderPlugin) Client(*plugin.MuxBroker, *rpc.Client) (interface{}, error) { + return nil, errors.New("terraform-plugin-sdk only implements grpc servers") +} + +func (p *gRPCProviderPlugin) GRPCClient(context.Context, *plugin.GRPCBroker, *grpc.ClientConn) (interface{}, error) { + return nil, errors.New("terraform-plugin-sdk only implements grpc servers") +} + +func (p *gRPCProviderPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error { + proto.RegisterProviderServer(s, p.GRPCProvider()) + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/serve.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/serve.go new file mode 100644 index 00000000000..e5649d07097 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/plugin/serve.go @@ -0,0 +1,82 @@ +package plugin + +import ( + "context" + + hclog "github.com/hashicorp/go-hclog" + "github.com/hashicorp/go-plugin" + "google.golang.org/grpc" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + grpcplugin "github.com/hashicorp/terraform-plugin-sdk/v2/internal/helper/plugin" + proto "github.com/hashicorp/terraform-plugin-sdk/v2/internal/tfplugin5" +) + +const ( + // The constants below are the names of the plugins that can be dispensed + // from the plugin server. + ProviderPluginName = "provider" +) + +// Handshake is the HandshakeConfig used to configure clients and servers. +var Handshake = plugin.HandshakeConfig{ + // The magic cookie values should NEVER be changed. + MagicCookieKey: "TF_PLUGIN_MAGIC_COOKIE", + MagicCookieValue: "d602bf8f470bc67ca7faa0386276bbdd4330efaf76d1a219cb4d6991ca9872b2", +} + +type ProviderFunc func() *schema.Provider +type GRPCProviderFunc func() proto.ProviderServer + +// ServeOpts are the configurations to serve a plugin. +type ServeOpts struct { + ProviderFunc ProviderFunc + + // Wrapped versions of the above plugins will automatically shimmed and + // added to the GRPC functions when possible. + GRPCProviderFunc GRPCProviderFunc + + // Logger is the logger that go-plugin will use. + Logger hclog.Logger + + // TestConfig should only be set when the provider is being tested; it + // will opt out of go-plugin's lifecycle management and other features, + // and will use the supplied configuration options to control the + // plugin's lifecycle and communicate connection information. See the + // go-plugin GoDoc for more information. + TestConfig *plugin.ServeTestConfig +} + +// Serve serves a plugin. This function never returns and should be the final +// function called in the main function of the plugin. +func Serve(opts *ServeOpts) { + // since the plugins may not yet be aware of the new protocol, we + // automatically wrap the plugins in the grpc shims. + if opts.GRPCProviderFunc == nil && opts.ProviderFunc != nil { + opts.GRPCProviderFunc = func() proto.ProviderServer { + return grpcplugin.NewGRPCProviderServer(opts.ProviderFunc()) + } + } + + provider := opts.GRPCProviderFunc() + plugin.Serve(&plugin.ServeConfig{ + HandshakeConfig: Handshake, + VersionedPlugins: map[int]plugin.PluginSet{ + 5: { + ProviderPluginName: &gRPCProviderPlugin{ + GRPCProvider: func() proto.ProviderServer { + return provider + }, + }, + }, + }, + GRPCServer: func(opts []grpc.ServerOption) *grpc.Server { + return grpc.NewServer(append(opts, grpc.UnaryInterceptor(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + ctx = provider.(*grpcplugin.GRPCProviderServer).StopContext(ctx) + return handler(ctx, req) + }))...) + }, + Logger: opts.Logger, + Test: opts.TestConfig, + }) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/diff.go new file mode 100644 index 00000000000..c7d82cf3d0f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/diff.go @@ -0,0 +1,990 @@ +package terraform + +import ( + "fmt" + "log" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "sync" + + "github.com/hashicorp/go-cty/cty" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim" +) + +// diffChangeType is an enum with the kind of changes a diff has planned. +type diffChangeType byte + +const ( + diffInvalid diffChangeType = iota + diffNone + diffCreate + diffUpdate + diffDestroy + diffDestroyCreate +) + +// multiVal matches the index key to a flatmapped set, list or map +var multiVal = regexp.MustCompile(`\.(#|%)$`) + +// InstanceDiff is the diff of a resource from some state to another. +type InstanceDiff struct { + mu sync.Mutex + Attributes map[string]*ResourceAttrDiff + Destroy bool + DestroyDeposed bool + DestroyTainted bool + + // Meta is a simple K/V map that is stored in a diff and persisted to + // plans but otherwise is completely ignored by Terraform core. It is + // meant to be used for additional data a resource may want to pass through. + // The value here must only contain Go primitives and collections. + Meta map[string]interface{} +} + +func (d *InstanceDiff) Lock() { d.mu.Lock() } +func (d *InstanceDiff) Unlock() { d.mu.Unlock() } + +// ApplyToValue merges the receiver into the given base value, returning a +// new value that incorporates the planned changes. The given value must +// conform to the given schema, or this method will panic. +// +// This method is intended for shimming old subsystems that still use this +// legacy diff type to work with the new-style types. +func (d *InstanceDiff) ApplyToValue(base cty.Value, schema *configschema.Block) (cty.Value, error) { + // Create an InstanceState attributes from our existing state. + // We can use this to more easily apply the diff changes. + attrs := hcl2shim.FlatmapValueFromHCL2(base) + applied, err := d.Apply(attrs, schema) + if err != nil { + return base, err + } + + val, err := hcl2shim.HCL2ValueFromFlatmap(applied, schema.ImpliedType()) + if err != nil { + return base, err + } + + return schema.CoerceValue(val) +} + +// Apply applies the diff to the provided flatmapped attributes, +// returning the new instance attributes. +// +// This method is intended for shimming old subsystems that still use this +// legacy diff type to work with the new-style types. +func (d *InstanceDiff) Apply(attrs map[string]string, schema *configschema.Block) (map[string]string, error) { + // We always build a new value here, even if the given diff is "empty", + // because we might be planning to create a new instance that happens + // to have no attributes set, and so we want to produce an empty object + // rather than just echoing back the null old value. + if attrs == nil { + attrs = map[string]string{} + } + + // Rather applying the diff to mutate the attrs, we'll copy new values into + // here to avoid the possibility of leaving stale values. + result := map[string]string{} + + if d.Destroy || d.DestroyDeposed || d.DestroyTainted { + return result, nil + } + + return d.applyBlockDiff(nil, attrs, schema) +} + +func (d *InstanceDiff) applyBlockDiff(path []string, attrs map[string]string, schema *configschema.Block) (map[string]string, error) { + result := map[string]string{} + name := "" + if len(path) > 0 { + name = path[len(path)-1] + } + + // localPrefix is used to build the local result map + localPrefix := "" + if name != "" { + localPrefix = name + "." + } + + // iterate over the schema rather than the attributes, so we can handle + // different block types separately from plain attributes + for n, attrSchema := range schema.Attributes { + var err error + newAttrs, err := d.applyAttrDiff(append(path, n), attrs, attrSchema) + + if err != nil { + return result, err + } + + for k, v := range newAttrs { + result[localPrefix+k] = v + } + } + + blockPrefix := strings.Join(path, ".") + if blockPrefix != "" { + blockPrefix += "." + } + for n, block := range schema.BlockTypes { + // we need to find the set of all keys that traverse this block + candidateKeys := map[string]bool{} + blockKey := blockPrefix + n + "." + localBlockPrefix := localPrefix + n + "." + + // we can only trust the diff for sets, since the path changes, so don't + // count existing values as candidate keys. If it turns out we're + // keeping the attributes, we will catch it down below with "keepBlock" + // after we check the set count. + if block.Nesting != configschema.NestingSet { + for k := range attrs { + if strings.HasPrefix(k, blockKey) { + nextDot := strings.Index(k[len(blockKey):], ".") + if nextDot < 0 { + continue + } + nextDot += len(blockKey) + candidateKeys[k[len(blockKey):nextDot]] = true + } + } + } + + for k, diff := range d.Attributes { + // helper/schema should not insert nil diff values, but don't panic + // if it does. + if diff == nil { + continue + } + + if strings.HasPrefix(k, blockKey) { + nextDot := strings.Index(k[len(blockKey):], ".") + if nextDot < 0 { + continue + } + + if diff.NewRemoved { + continue + } + + nextDot += len(blockKey) + candidateKeys[k[len(blockKey):nextDot]] = true + } + } + + // check each set candidate to see if it was removed. + // we need to do this, because when entire sets are removed, they may + // have the wrong key, and ony show diffs going to "" + if block.Nesting == configschema.NestingSet { + for k := range candidateKeys { + indexPrefix := strings.Join(append(path, n, k), ".") + "." + keep := false + // now check each set element to see if it's a new diff, or one + // that we're dropping. Since we're only applying the "New" + // portion of the set, we can ignore diffs that only contain "Old" + for attr, diff := range d.Attributes { + // helper/schema should not insert nil diff values, but don't panic + // if it does. + if diff == nil { + continue + } + + if !strings.HasPrefix(attr, indexPrefix) { + continue + } + + // check for empty "count" keys + if (strings.HasSuffix(attr, ".#") || strings.HasSuffix(attr, ".%")) && diff.New == "0" { + continue + } + + // removed items don't count either + if diff.NewRemoved { + continue + } + + // this must be a diff to keep + keep = true + break + } + if !keep { + delete(candidateKeys, k) + } + } + } + + for k := range candidateKeys { + newAttrs, err := d.applyBlockDiff(append(path, n, k), attrs, &block.Block) + if err != nil { + return result, err + } + + for attr, v := range newAttrs { + result[localBlockPrefix+attr] = v + } + } + + keepBlock := true + // check this block's count diff directly first, since we may not + // have candidates because it was removed and only set to "0" + if diff, ok := d.Attributes[blockKey+"#"]; ok { + if diff.New == "0" || diff.NewRemoved { + keepBlock = false + } + } + + // if there was no diff at all, then we need to keep the block attributes + if len(candidateKeys) == 0 && keepBlock { + for k, v := range attrs { + if strings.HasPrefix(k, blockKey) { + // we need the key relative to this block, so remove the + // entire prefix, then re-insert the block name. + localKey := localBlockPrefix + k[len(blockKey):] + result[localKey] = v + } + } + } + + countAddr := strings.Join(append(path, n, "#"), ".") + if countDiff, ok := d.Attributes[countAddr]; ok { + if countDiff.NewComputed { + result[localBlockPrefix+"#"] = hcl2shim.UnknownVariableValue + } else { + result[localBlockPrefix+"#"] = countDiff.New + + // While sets are complete, list are not, and we may not have all the + // information to track removals. If the list was truncated, we need to + // remove the extra items from the result. + if block.Nesting == configschema.NestingList && + countDiff.New != "" && countDiff.New != hcl2shim.UnknownVariableValue { + length, _ := strconv.Atoi(countDiff.New) + for k := range result { + if !strings.HasPrefix(k, localBlockPrefix) { + continue + } + + index := k[len(localBlockPrefix):] + nextDot := strings.Index(index, ".") + if nextDot < 1 { + continue + } + index = index[:nextDot] + i, err := strconv.Atoi(index) + if err != nil { + // this shouldn't happen since we added these + // ourself, but make note of it just in case. + log.Printf("[ERROR] bad list index in %q: %s", k, err) + continue + } + if i >= length { + delete(result, k) + } + } + } + } + } else if origCount, ok := attrs[countAddr]; ok && keepBlock { + result[localBlockPrefix+"#"] = origCount + } else { + result[localBlockPrefix+"#"] = countFlatmapContainerValues(localBlockPrefix+"#", result) + } + } + + return result, nil +} + +func (d *InstanceDiff) applyAttrDiff(path []string, attrs map[string]string, attrSchema *configschema.Attribute) (map[string]string, error) { + ty := attrSchema.Type + switch { + case ty.IsListType(), ty.IsTupleType(), ty.IsMapType(): + return d.applyCollectionDiff(path, attrs, attrSchema) + case ty.IsSetType(): + return d.applySetDiff(path, attrs, attrSchema) + default: + return d.applySingleAttrDiff(path, attrs, attrSchema) + } +} + +func (d *InstanceDiff) applySingleAttrDiff(path []string, attrs map[string]string, attrSchema *configschema.Attribute) (map[string]string, error) { + currentKey := strings.Join(path, ".") + + attr := path[len(path)-1] + + result := map[string]string{} + diff := d.Attributes[currentKey] + old, exists := attrs[currentKey] + + if diff != nil && diff.NewComputed { + result[attr] = hcl2shim.UnknownVariableValue + return result, nil + } + + // "id" must exist and not be an empty string, or it must be unknown. + // This only applied to top-level "id" fields. + if attr == "id" && len(path) == 1 { + if old == "" { + result[attr] = hcl2shim.UnknownVariableValue + } else { + result[attr] = old + } + return result, nil + } + + // attribute diffs are sometimes missed, so assume no diff means keep the + // old value + if diff == nil { + if exists { + result[attr] = old + } else { + // We need required values, so set those with an empty value. It + // must be set in the config, since if it were missing it would have + // failed validation. + if attrSchema.Required { + // we only set a missing string here, since bool or number types + // would have distinct zero value which shouldn't have been + // lost. + if attrSchema.Type == cty.String { + result[attr] = "" + } + } + } + return result, nil + } + + // check for missmatched diff values + if exists && + old != diff.Old && + old != hcl2shim.UnknownVariableValue && + diff.Old != hcl2shim.UnknownVariableValue { + return result, fmt.Errorf("diff apply conflict for %s: diff expects %q, but prior value has %q", attr, diff.Old, old) + } + + if diff.NewRemoved { + // don't set anything in the new value + return map[string]string{}, nil + } + + if diff.Old == diff.New && diff.New == "" { + // this can only be a valid empty string + if attrSchema.Type == cty.String { + result[attr] = "" + } + return result, nil + } + + if attrSchema.Computed && diff.NewComputed { + result[attr] = hcl2shim.UnknownVariableValue + return result, nil + } + + result[attr] = diff.New + + return result, nil +} + +func (d *InstanceDiff) applyCollectionDiff(path []string, attrs map[string]string, attrSchema *configschema.Attribute) (map[string]string, error) { + result := map[string]string{} + + prefix := "" + if len(path) > 1 { + prefix = strings.Join(path[:len(path)-1], ".") + "." + } + + name := "" + if len(path) > 0 { + name = path[len(path)-1] + } + + currentKey := prefix + name + + // check the index first for special handling + for k, diff := range d.Attributes { + // check the index value, which can be set, and 0 + if k == currentKey+".#" || k == currentKey+".%" || k == currentKey { + if diff.NewRemoved { + return result, nil + } + + if diff.NewComputed { + result[k[len(prefix):]] = hcl2shim.UnknownVariableValue + return result, nil + } + + // do what the diff tells us to here, so that it's consistent with applies + if diff.New == "0" { + result[k[len(prefix):]] = "0" + return result, nil + } + } + } + + // collect all the keys from the diff and the old state + noDiff := true + keys := map[string]bool{} + for k := range d.Attributes { + if !strings.HasPrefix(k, currentKey+".") { + continue + } + noDiff = false + keys[k] = true + } + + noAttrs := true + for k := range attrs { + if !strings.HasPrefix(k, currentKey+".") { + continue + } + noAttrs = false + keys[k] = true + } + + // If there's no diff and no attrs, then there's no value at all. + // This prevents an unexpected zero-count attribute in the attributes. + if noDiff && noAttrs { + return result, nil + } + + idx := "#" + if attrSchema.Type.IsMapType() { + idx = "%" + } + + for k := range keys { + // generate an schema placeholder for the values + elSchema := &configschema.Attribute{ + Type: attrSchema.Type.ElementType(), + } + + res, err := d.applySingleAttrDiff(append(path, k[len(currentKey)+1:]), attrs, elSchema) + if err != nil { + return result, err + } + + for k, v := range res { + result[name+"."+k] = v + } + } + + // Just like in nested list blocks, for simple lists we may need to fill in + // missing empty strings. + countKey := name + "." + idx + count := result[countKey] + length, _ := strconv.Atoi(count) + + if count != "" && count != hcl2shim.UnknownVariableValue && + attrSchema.Type.Equals(cty.List(cty.String)) { + // insert empty strings into missing indexes + for i := 0; i < length; i++ { + key := fmt.Sprintf("%s.%d", name, i) + if _, ok := result[key]; !ok { + result[key] = "" + } + } + } + + // now check for truncation in any type of list + if attrSchema.Type.IsListType() { + for key := range result { + if key == countKey { + continue + } + + if len(key) <= len(name)+1 { + // not sure what this is, but don't panic + continue + } + + index := key[len(name)+1:] + + // It is possible to have nested sets or maps, so look for another dot + dot := strings.Index(index, ".") + if dot > 0 { + index = index[:dot] + } + + // This shouldn't have any more dots, since the element type is only string. + num, err := strconv.Atoi(index) + if err != nil { + log.Printf("[ERROR] bad list index in %q: %s", currentKey, err) + continue + } + + if num >= length { + delete(result, key) + } + } + } + + // Fill in the count value if it wasn't present in the diff for some reason, + // or if there is no count at all. + _, countDiff := d.Attributes[countKey] + if result[countKey] == "" || (!countDiff && len(keys) != len(result)) { + result[countKey] = countFlatmapContainerValues(countKey, result) + } + + return result, nil +} + +func (d *InstanceDiff) applySetDiff(path []string, attrs map[string]string, attrSchema *configschema.Attribute) (map[string]string, error) { + // We only need this special behavior for sets of object. + if !attrSchema.Type.ElementType().IsObjectType() { + // The normal collection apply behavior will work okay for this one, then. + return d.applyCollectionDiff(path, attrs, attrSchema) + } + + // When we're dealing with a set of an object type we actually want to + // use our normal _block type_ apply behaviors, so we'll construct ourselves + // a synthetic schema that treats the object type as a block type and + // then delegate to our block apply method. + synthSchema := &configschema.Block{ + Attributes: make(map[string]*configschema.Attribute), + } + + for name, ty := range attrSchema.Type.ElementType().AttributeTypes() { + // We can safely make everything into an attribute here because in the + // event that there are nested set attributes we'll end up back in + // here again recursively and can then deal with the next level of + // expansion. + synthSchema.Attributes[name] = &configschema.Attribute{ + Type: ty, + Optional: true, + } + } + + parentPath := path[:len(path)-1] + childName := path[len(path)-1] + containerSchema := &configschema.Block{ + BlockTypes: map[string]*configschema.NestedBlock{ + childName: { + Nesting: configschema.NestingSet, + Block: *synthSchema, + }, + }, + } + + return d.applyBlockDiff(parentPath, attrs, containerSchema) +} + +// countFlatmapContainerValues returns the number of values in the flatmapped container +// (set, map, list) indexed by key. The key argument is expected to include the +// trailing ".#", or ".%". +func countFlatmapContainerValues(key string, attrs map[string]string) string { + if len(key) < 3 || !(strings.HasSuffix(key, ".#") || strings.HasSuffix(key, ".%")) { + panic(fmt.Sprintf("invalid index value %q", key)) + } + + prefix := key[:len(key)-1] + items := map[string]int{} + + for k := range attrs { + if k == key { + continue + } + if !strings.HasPrefix(k, prefix) { + continue + } + + suffix := k[len(prefix):] + dot := strings.Index(suffix, ".") + if dot > 0 { + suffix = suffix[:dot] + } + + items[suffix]++ + } + return strconv.Itoa(len(items)) +} + +// ResourceAttrDiff is the diff of a single attribute of a resource. +type ResourceAttrDiff struct { + Old string // Old Value + New string // New Value + NewComputed bool // True if new value is computed (unknown currently) + NewRemoved bool // True if this attribute is being removed + NewExtra interface{} // Extra information for the provider + RequiresNew bool // True if change requires new resource + Sensitive bool // True if the data should not be displayed in UI output + Type diffAttrType +} + +func (d *ResourceAttrDiff) GoString() string { + return fmt.Sprintf("*%#v", *d) +} + +// DiffAttrType is an enum type that says whether a resource attribute +// diff is an input attribute (comes from the configuration) or an +// output attribute (comes as a result of applying the configuration). An +// example input would be "ami" for AWS and an example output would be +// "private_ip". +type diffAttrType byte + +func NewInstanceDiff() *InstanceDiff { + return &InstanceDiff{Attributes: make(map[string]*ResourceAttrDiff)} +} + +// ChangeType returns the diffChangeType represented by the diff +// for this single instance. +func (d *InstanceDiff) ChangeType() diffChangeType { + if d.Empty() { + return diffNone + } + + if d.RequiresNew() && (d.GetDestroy() || d.GetDestroyTainted()) { + return diffDestroyCreate + } + + if d.GetDestroy() || d.GetDestroyDeposed() { + return diffDestroy + } + + if d.RequiresNew() { + return diffCreate + } + + return diffUpdate +} + +// Empty returns true if this diff encapsulates no changes. +func (d *InstanceDiff) Empty() bool { + if d == nil { + return true + } + + d.mu.Lock() + defer d.mu.Unlock() + return !d.Destroy && + !d.DestroyTainted && + !d.DestroyDeposed && + len(d.Attributes) == 0 +} + +// Equal compares two diffs for exact equality. +// +// This is different from the Same comparison that is supported which +// checks for operation equality taking into account computed values. Equal +// instead checks for exact equality. +// TODO: investigate why removing this unused method causes panic in tests +func (d *InstanceDiff) Equal(d2 *InstanceDiff) bool { + // If one is nil, they must both be nil + if d == nil || d2 == nil { + return d == d2 + } + + // Use DeepEqual + return reflect.DeepEqual(d, d2) +} + +func (d *InstanceDiff) GoString() string { + return fmt.Sprintf("*%#v", InstanceDiff{ + Attributes: d.Attributes, + Destroy: d.Destroy, + DestroyTainted: d.DestroyTainted, + DestroyDeposed: d.DestroyDeposed, + }) +} + +// RequiresNew returns true if the diff requires the creation of a new +// resource (implying the destruction of the old). +func (d *InstanceDiff) RequiresNew() bool { + if d == nil { + return false + } + + d.mu.Lock() + defer d.mu.Unlock() + + return d.requiresNew() +} + +func (d *InstanceDiff) requiresNew() bool { + if d == nil { + return false + } + + if d.DestroyTainted { + return true + } + + for _, rd := range d.Attributes { + if rd != nil && rd.RequiresNew { + return true + } + } + + return false +} + +func (d *InstanceDiff) GetDestroyDeposed() bool { + d.mu.Lock() + defer d.mu.Unlock() + + return d.DestroyDeposed +} + +func (d *InstanceDiff) GetDestroyTainted() bool { + d.mu.Lock() + defer d.mu.Unlock() + + return d.DestroyTainted +} + +func (d *InstanceDiff) GetDestroy() bool { + d.mu.Lock() + defer d.mu.Unlock() + + return d.Destroy +} + +func (d *InstanceDiff) GetAttribute(key string) (*ResourceAttrDiff, bool) { + d.mu.Lock() + defer d.mu.Unlock() + + attr, ok := d.Attributes[key] + return attr, ok +} + +// Safely copies the Attributes map +func (d *InstanceDiff) CopyAttributes() map[string]*ResourceAttrDiff { + d.mu.Lock() + defer d.mu.Unlock() + + attrs := make(map[string]*ResourceAttrDiff) + for k, v := range d.Attributes { + attrs[k] = v + } + + return attrs +} + +// Same checks whether or not two InstanceDiff's are the "same". When +// we say "same", it is not necessarily exactly equal. Instead, it is +// just checking that the same attributes are changing, a destroy +// isn't suddenly happening, etc. +func (d *InstanceDiff) Same(d2 *InstanceDiff) (bool, string) { + // we can safely compare the pointers without a lock + switch { + case d == nil && d2 == nil: + return true, "" + case d == nil || d2 == nil: + return false, "one nil" + case d == d2: + return true, "" + } + + d.mu.Lock() + defer d.mu.Unlock() + + // If we're going from requiring new to NOT requiring new, then we have + // to see if all required news were computed. If so, it is allowed since + // computed may also mean "same value and therefore not new". + oldNew := d.requiresNew() + newNew := d2.RequiresNew() + if oldNew && !newNew { + oldNew = false + + // This section builds a list of ignorable attributes for requiresNew + // by removing off any elements of collections going to zero elements. + // For collections going to zero, they may not exist at all in the + // new diff (and hence RequiresNew == false). + ignoreAttrs := make(map[string]struct{}) + for k, diffOld := range d.Attributes { + if !strings.HasSuffix(k, ".%") && !strings.HasSuffix(k, ".#") { + continue + } + + // This case is in here as a protection measure. The bug that this + // code originally fixed (GH-11349) didn't have to deal with computed + // so I'm not 100% sure what the correct behavior is. Best to leave + // the old behavior. + if diffOld.NewComputed { + continue + } + + // We're looking for the case a map goes to exactly 0. + if diffOld.New != "0" { + continue + } + + // Found it! Ignore all of these. The prefix here is stripping + // off the "%" so it is just "k." + prefix := k[:len(k)-1] + for k2 := range d.Attributes { + if strings.HasPrefix(k2, prefix) { + ignoreAttrs[k2] = struct{}{} + } + } + } + + for k, rd := range d.Attributes { + if _, ok := ignoreAttrs[k]; ok { + continue + } + + // If the field is requires new and NOT computed, then what + // we have is a diff mismatch for sure. We set that the old + // diff does REQUIRE a ForceNew. + if rd != nil && rd.RequiresNew && !rd.NewComputed { + oldNew = true + break + } + } + } + + if oldNew != newNew { + return false, fmt.Sprintf( + "diff RequiresNew; old: %t, new: %t", oldNew, newNew) + } + + // Verify that destroy matches. The second boolean here allows us to + // have mismatching Destroy if we're moving from RequiresNew true + // to false above. Therefore, the second boolean will only pass if + // we're moving from Destroy: true to false as well. + if d.Destroy != d2.GetDestroy() && d.requiresNew() == oldNew { + return false, fmt.Sprintf( + "diff: Destroy; old: %t, new: %t", d.Destroy, d2.GetDestroy()) + } + + // Go through the old diff and make sure the new diff has all the + // same attributes. To start, build up the check map to be all the keys. + checkOld := make(map[string]struct{}) + checkNew := make(map[string]struct{}) + for k := range d.Attributes { + checkOld[k] = struct{}{} + } + for k := range d2.CopyAttributes() { + checkNew[k] = struct{}{} + } + + // Make an ordered list so we are sure the approximated hashes are left + // to process at the end of the loop + keys := make([]string, 0, len(d.Attributes)) + for k := range d.Attributes { + keys = append(keys, k) + } + sort.StringSlice(keys).Sort() + + for _, k := range keys { + diffOld := d.Attributes[k] + + if _, ok := checkOld[k]; !ok { + // We're not checking this key for whatever reason (see where + // check is modified). + continue + } + + // Remove this key since we'll never hit it again + delete(checkOld, k) + delete(checkNew, k) + + _, ok := d2.GetAttribute(k) + if !ok { + // If there's no new attribute, and the old diff expected the attribute + // to be removed, that's just fine. + if diffOld.NewRemoved { + continue + } + + // If the last diff was a computed value then the absense of + // that value is allowed since it may mean the value ended up + // being the same. + if diffOld.NewComputed { + ok = true + } + + // No exact match, but maybe this is a set containing computed + // values. So check if there is an approximate hash in the key + // and if so, try to match the key. + if strings.Contains(k, "~") { + parts := strings.Split(k, ".") + parts2 := append([]string(nil), parts...) + + re := regexp.MustCompile(`^~\d+$`) + for i, part := range parts { + if re.MatchString(part) { + // we're going to consider this the base of a + // computed hash, and remove all longer matching fields + ok = true + + parts2[i] = `\d+` + parts2 = parts2[:i+1] + break + } + } + + re, err := regexp.Compile("^" + strings.Join(parts2, `\.`)) + if err != nil { + return false, fmt.Sprintf("regexp failed to compile; err: %#v", err) + } + + for k2 := range checkNew { + if re.MatchString(k2) { + delete(checkNew, k2) + } + } + } + + // This is a little tricky, but when a diff contains a computed + // list, set, or map that can only be interpolated after the apply + // command has created the dependent resources, it could turn out + // that the result is actually the same as the existing state which + // would remove the key from the diff. + if diffOld.NewComputed && (strings.HasSuffix(k, ".#") || strings.HasSuffix(k, ".%")) { + ok = true + } + + // Similarly, in a RequiresNew scenario, a list that shows up in the plan + // diff can disappear from the apply diff, which is calculated from an + // empty state. + if d.requiresNew() && (strings.HasSuffix(k, ".#") || strings.HasSuffix(k, ".%")) { + ok = true + } + + if !ok { + return false, fmt.Sprintf("attribute mismatch: %s", k) + } + } + + // search for the suffix of the base of a [computed] map, list or set. + match := multiVal.FindStringSubmatch(k) + + if diffOld.NewComputed && len(match) == 2 { + matchLen := len(match[1]) + + // This is a computed list, set, or map, so remove any keys with + // this prefix from the check list. + kprefix := k[:len(k)-matchLen] + for k2 := range checkOld { + if strings.HasPrefix(k2, kprefix) { + delete(checkOld, k2) + } + } + for k2 := range checkNew { + if strings.HasPrefix(k2, kprefix) { + delete(checkNew, k2) + } + } + } + + // We don't compare the values because we can't currently actually + // guarantee to generate the same value two two diffs created from + // the same state+config: we have some pesky interpolation functions + // that do not behave as pure functions (uuid, timestamp) and so they + // can be different each time a diff is produced. + // FIXME: Re-organize our config handling so that we don't re-evaluate + // expressions when we produce a second comparison diff during + // apply (for EvalCompareDiff). + } + + // Check for leftover attributes + if len(checkNew) > 0 { + extras := make([]string, 0, len(checkNew)) + for attr := range checkNew { + extras = append(extras, attr) + } + return false, + fmt.Sprintf("extra attributes: %s", strings.Join(extras, ", ")) + } + + return true, "" +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/instancetype.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/instancetype.go new file mode 100644 index 00000000000..b01e5a48dfa --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/instancetype.go @@ -0,0 +1,13 @@ +package terraform + +//go:generate go run golang.org/x/tools/cmd/stringer -type=instanceType instancetype.go + +// instanceType is an enum of the various types of instances store in the State +type instanceType int + +const ( + typeInvalid instanceType = iota + typePrimary + typeTainted + typeDeposed +) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/instancetype_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/instancetype_string.go new file mode 100644 index 00000000000..782ef90c05c --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/instancetype_string.go @@ -0,0 +1,26 @@ +// Code generated by "stringer -type=instanceType instancetype.go"; DO NOT EDIT. + +package terraform + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[typeInvalid-0] + _ = x[typePrimary-1] + _ = x[typeTainted-2] + _ = x[typeDeposed-3] +} + +const _instanceType_name = "typeInvalidtypePrimarytypeTaintedtypeDeposed" + +var _instanceType_index = [...]uint8{0, 11, 22, 33, 44} + +func (i instanceType) String() string { + if i < 0 || i >= instanceType(len(_instanceType_index)-1) { + return "instanceType(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _instanceType_name[_instanceType_index[i]:_instanceType_index[i+1]] +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource.go new file mode 100644 index 00000000000..11b63de8a29 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource.go @@ -0,0 +1,333 @@ +package terraform + +import ( + "fmt" + "reflect" + "sort" + "strconv" + "strings" + + "github.com/hashicorp/go-cty/cty" + "github.com/mitchellh/copystructure" + "github.com/mitchellh/reflectwalk" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim" +) + +// InstanceInfo is used to hold information about the instance and/or +// resource being modified. +type InstanceInfo struct { + // Id is a unique name to represent this instance. This is not related + // to InstanceState.ID in any way. + Id string + + // ModulePath is the complete path of the module containing this + // instance. + ModulePath []string + + // Type is the resource type of this instance + Type string +} + +// ResourceConfig is a legacy type that was formerly used to represent +// interpolatable configuration blocks. It is now only used to shim to old +// APIs that still use this type, via NewResourceConfigShimmed. +type ResourceConfig struct { + ComputedKeys []string + Raw map[string]interface{} + Config map[string]interface{} +} + +// NewResourceConfigRaw constructs a ResourceConfig whose content is exactly +// the given value. +// +// The given value may contain hcl2shim.UnknownVariableValue to signal that +// something is computed, but it must not contain unprocessed interpolation +// sequences as we might've seen in Terraform v0.11 and prior. +func NewResourceConfigRaw(raw map[string]interface{}) *ResourceConfig { + v := hcl2shim.HCL2ValueFromConfigValue(raw) + + // This is a little weird but we round-trip the value through the hcl2shim + // package here for two reasons: firstly, because that reduces the risk + // of it including something unlike what NewResourceConfigShimmed would + // produce, and secondly because it creates a copy of "raw" just in case + // something is relying on the fact that in the old world the raw and + // config maps were always distinct, and thus you could in principle mutate + // one without affecting the other. (I sure hope nobody was doing that, though!) + cfg := hcl2shim.ConfigValueFromHCL2(v).(map[string]interface{}) + + return &ResourceConfig{ + Raw: raw, + Config: cfg, + + ComputedKeys: newResourceConfigShimmedComputedKeys(v, ""), + } +} + +// NewResourceConfigShimmed wraps a cty.Value of object type in a legacy +// ResourceConfig object, so that it can be passed to older APIs that expect +// this wrapping. +// +// The returned ResourceConfig is already interpolated and cannot be +// re-interpolated. It is, therefore, useful only to functions that expect +// an already-populated ResourceConfig which they then treat as read-only. +// +// If the given value is not of an object type that conforms to the given +// schema then this function will panic. +func NewResourceConfigShimmed(val cty.Value, schema *configschema.Block) *ResourceConfig { + if !val.Type().IsObjectType() { + panic(fmt.Errorf("NewResourceConfigShimmed given %#v; an object type is required", val.Type())) + } + ret := &ResourceConfig{} + + legacyVal := hcl2shim.ConfigValueFromHCL2Block(val, schema) + if legacyVal != nil { + ret.Config = legacyVal + + // Now we need to walk through our structure and find any unknown values, + // producing the separate list ComputedKeys to represent these. We use the + // schema here so that we can preserve the expected invariant + // that an attribute is always either wholly known or wholly unknown, while + // a child block can be partially unknown. + ret.ComputedKeys = newResourceConfigShimmedComputedKeys(val, "") + } else { + ret.Config = make(map[string]interface{}) + } + ret.Raw = ret.Config + + return ret +} + +// Record the any config values in ComputedKeys. This field had been unused in +// helper/schema, but in the new protocol we're using this so that the SDK can +// now handle having an unknown collection. The legacy diff code doesn't +// properly handle the unknown, because it can't be expressed in the same way +// between the config and diff. +func newResourceConfigShimmedComputedKeys(val cty.Value, path string) []string { + var ret []string + ty := val.Type() + + if val.IsNull() { + return ret + } + + if !val.IsKnown() { + // we shouldn't have an entirely unknown resource, but prevent empty + // strings just in case + if len(path) > 0 { + ret = append(ret, path) + } + return ret + } + + if path != "" { + path += "." + } + switch { + case ty.IsListType(), ty.IsTupleType(), ty.IsSetType(): + i := 0 + for it := val.ElementIterator(); it.Next(); i++ { + _, subVal := it.Element() + keys := newResourceConfigShimmedComputedKeys(subVal, fmt.Sprintf("%s%d", path, i)) + ret = append(ret, keys...) + } + + case ty.IsMapType(), ty.IsObjectType(): + for it := val.ElementIterator(); it.Next(); { + subK, subVal := it.Element() + keys := newResourceConfigShimmedComputedKeys(subVal, fmt.Sprintf("%s%s", path, subK.AsString())) + ret = append(ret, keys...) + } + } + + return ret +} + +// DeepCopy performs a deep copy of the configuration. This makes it safe +// to modify any of the structures that are part of the resource config without +// affecting the original configuration. +func (c *ResourceConfig) DeepCopy() *ResourceConfig { + // DeepCopying a nil should return a nil to avoid panics + if c == nil { + return nil + } + + // Copy, this will copy all the exported attributes + copy, err := copystructure.Config{Lock: true}.Copy(c) + if err != nil { + panic(err) + } + + // Force the type + result := copy.(*ResourceConfig) + + return result +} + +// Equal checks the equality of two resource configs. +func (c *ResourceConfig) Equal(c2 *ResourceConfig) bool { + // If either are nil, then they're only equal if they're both nil + if c == nil || c2 == nil { + return c == c2 + } + + // Sort the computed keys so they're deterministic + sort.Strings(c.ComputedKeys) + sort.Strings(c2.ComputedKeys) + + // Two resource configs if their exported properties are equal. + // We don't compare "raw" because it is never used again after + // initialization and for all intents and purposes they are equal + // if the exported properties are equal. + check := [][2]interface{}{ + {c.ComputedKeys, c2.ComputedKeys}, + {c.Raw, c2.Raw}, + {c.Config, c2.Config}, + } + for _, pair := range check { + if !reflect.DeepEqual(pair[0], pair[1]) { + return false + } + } + + return true +} + +// Get looks up a configuration value by key and returns the value. +// +// The second return value is true if the get was successful. Get will +// return the raw value if the key is computed, so you should pair this +// with IsComputed. +func (c *ResourceConfig) Get(k string) (interface{}, bool) { + // We aim to get a value from the configuration. If it is computed, + // then we return the pure raw value. + source := c.Config + if c.IsComputed(k) { + source = c.Raw + } + + return c.get(k, source) +} + +// GetRaw looks up a configuration value by key and returns the value, +// from the raw, uninterpolated config. +// +// The second return value is true if the get was successful. Get will +// not succeed if the value is being computed. +func (c *ResourceConfig) GetRaw(k string) (interface{}, bool) { + return c.get(k, c.Raw) +} + +// IsComputed returns whether the given key is computed or not. +func (c *ResourceConfig) IsComputed(k string) bool { + // The next thing we do is check the config if we get a computed + // value out of it. + v, ok := c.get(k, c.Config) + if !ok { + return false + } + + // If value is nil, then it isn't computed + if v == nil { + return false + } + + // Test if the value contains an unknown value + var w unknownCheckWalker + if err := reflectwalk.Walk(v, &w); err != nil { + panic(err) + } + + return w.Unknown +} + +func (c *ResourceConfig) get( + k string, raw map[string]interface{}) (interface{}, bool) { + parts := strings.Split(k, ".") + if len(parts) == 1 && parts[0] == "" { + parts = nil + } + + var current interface{} = raw + var previous interface{} = nil + for i, part := range parts { + if current == nil { + return nil, false + } + + cv := reflect.ValueOf(current) + switch cv.Kind() { + case reflect.Map: + previous = current + v := cv.MapIndex(reflect.ValueOf(part)) + if !v.IsValid() { + if i > 0 && i != (len(parts)-1) { + tryKey := strings.Join(parts[i:], ".") + v := cv.MapIndex(reflect.ValueOf(tryKey)) + if !v.IsValid() { + return nil, false + } + + return v.Interface(), true + } + + return nil, false + } + + current = v.Interface() + case reflect.Slice: + previous = current + + if part == "#" { + // If any value in a list is computed, this whole thing + // is computed and we can't read any part of it. + for i := 0; i < cv.Len(); i++ { + if v := cv.Index(i).Interface(); v == hcl2shim.UnknownVariableValue { + return v, true + } + } + + current = cv.Len() + } else { + i, err := strconv.ParseInt(part, 0, 0) + if err != nil { + return nil, false + } + if int(i) < 0 || int(i) >= cv.Len() { + return nil, false + } + current = cv.Index(int(i)).Interface() + } + case reflect.String: + // This happens when map keys contain "." and have a common + // prefix so were split as path components above. + actualKey := strings.Join(parts[i-1:], ".") + if prevMap, ok := previous.(map[string]interface{}); ok { + v, ok := prevMap[actualKey] + return v, ok + } + + return nil, false + default: + panic(fmt.Sprintf("Unknown kind: %s", cv.Kind())) + } + } + + return current, true +} + +// unknownCheckWalker +type unknownCheckWalker struct { + Unknown bool +} + +// TODO: investigate why deleting this causes odd runtime test failures +// must be some kind of interface implementation +func (w *unknownCheckWalker) Primitive(v reflect.Value) error { + if v.Interface() == hcl2shim.UnknownVariableValue { + w.Unknown = true + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource_address.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource_address.go new file mode 100644 index 00000000000..ec2665d3133 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource_address.go @@ -0,0 +1,226 @@ +package terraform + +import ( + "fmt" + "reflect" + "regexp" + "strconv" + "strings" +) + +// resourceAddress is a way of identifying an individual resource (or, +// eventually, a subset of resources) within the state. It is used for Targets. +type resourceAddress struct { + // Addresses a resource falling somewhere in the module path + // When specified alone, addresses all resources within a module path + Path []string + + // Addresses a specific resource that occurs in a list + Index int + + InstanceType instanceType + InstanceTypeSet bool + Name string + Type string + Mode ResourceMode // significant only if InstanceTypeSet +} + +// String outputs the address that parses into this address. +func (r *resourceAddress) String() string { + var result []string + for _, p := range r.Path { + result = append(result, "module", p) + } + + switch r.Mode { + case ManagedResourceMode: + // nothing to do + case DataResourceMode: + result = append(result, "data") + default: + panic(fmt.Errorf("unsupported resource mode %s", r.Mode)) + } + + if r.Type != "" { + result = append(result, r.Type) + } + + if r.Name != "" { + name := r.Name + if r.InstanceTypeSet { + switch r.InstanceType { + case typePrimary: + name += ".primary" + case typeDeposed: + name += ".deposed" + case typeTainted: + name += ".tainted" + } + } + + if r.Index >= 0 { + name += fmt.Sprintf("[%d]", r.Index) + } + result = append(result, name) + } + + return strings.Join(result, ".") +} + +func parseResourceAddress(s string) (*resourceAddress, error) { + matches, err := tokenizeResourceAddress(s) + if err != nil { + return nil, err + } + mode := ManagedResourceMode + if matches["data_prefix"] != "" { + mode = DataResourceMode + } + resourceIndex, err := parseResourceIndex(matches["index"]) + if err != nil { + return nil, err + } + instanceType, err := parseInstanceType(matches["instance_type"]) + if err != nil { + return nil, err + } + path := parseResourcePath(matches["path"]) + + // not allowed to say "data." without a type following + if mode == DataResourceMode && matches["type"] == "" { + return nil, fmt.Errorf( + "invalid resource address %q: must target specific data instance", + s, + ) + } + + return &resourceAddress{ + Path: path, + Index: resourceIndex, + InstanceType: instanceType, + InstanceTypeSet: matches["instance_type"] != "", + Name: matches["name"], + Type: matches["type"], + Mode: mode, + }, nil +} + +// Less returns true if and only if the receiver should be sorted before +// the given address when presenting a list of resource addresses to +// an end-user. +// +// This sort uses lexicographic sorting for most components, but uses +// numeric sort for indices, thus causing index 10 to sort after +// index 9, rather than after index 1. +func (addr *resourceAddress) Less(other *resourceAddress) bool { + + switch { + + case len(addr.Path) != len(other.Path): + return len(addr.Path) < len(other.Path) + + case !reflect.DeepEqual(addr.Path, other.Path): + // If the two paths are the same length but don't match, we'll just + // cheat and compare the string forms since it's easier than + // comparing all of the path segments in turn, and lexicographic + // comparison is correct for the module path portion. + addrStr := addr.String() + otherStr := other.String() + return addrStr < otherStr + + case addr.Mode != other.Mode: + return addr.Mode == DataResourceMode + + case addr.Type != other.Type: + return addr.Type < other.Type + + case addr.Name != other.Name: + return addr.Name < other.Name + + case addr.Index != other.Index: + // Since "Index" is -1 for an un-indexed address, this also conveniently + // sorts unindexed addresses before indexed ones, should they both + // appear for some reason. + return addr.Index < other.Index + + case addr.InstanceTypeSet != other.InstanceTypeSet: + return !addr.InstanceTypeSet + + case addr.InstanceType != other.InstanceType: + // InstanceType is actually an enum, so this is just an arbitrary + // sort based on the enum numeric values, and thus not particularly + // meaningful. + return addr.InstanceType < other.InstanceType + + default: + return false + + } +} + +func parseResourceIndex(s string) (int, error) { + if s == "" { + return -1, nil + } + return strconv.Atoi(s) +} + +func parseResourcePath(s string) []string { + if s == "" { + return nil + } + parts := strings.Split(s, ".") + path := make([]string, 0, len(parts)) + for _, s := range parts { + // Due to the limitations of the regexp match below, the path match has + // some noise in it we have to filter out :| + if s == "" || s == "module" { + continue + } + path = append(path, s) + } + return path +} + +func parseInstanceType(s string) (instanceType, error) { + switch s { + case "", "primary": + return typePrimary, nil + case "deposed": + return typeDeposed, nil + case "tainted": + return typeTainted, nil + default: + return typeInvalid, fmt.Errorf("Unexpected value for instanceType field: %q", s) + } +} + +func tokenizeResourceAddress(s string) (map[string]string, error) { + // Example of portions of the regexp below using the + // string "aws_instance.web.tainted[1]" + re := regexp.MustCompile(`\A` + + // "module.foo.module.bar" (optional) + `(?P(?:module\.(?P[^.]+)\.?)*)` + + // possibly "data.", if targeting is a data resource + `(?P(?:data\.)?)` + + // "aws_instance.web" (optional when module path specified) + `(?:(?P[^.]+)\.(?P[^.[]+))?` + + // "tainted" (optional, omission implies: "primary") + `(?:\.(?P\w+))?` + + // "1" (optional, omission implies: "0") + `(?:\[(?P\d+)\])?` + + `\z`) + + groupNames := re.SubexpNames() + rawMatches := re.FindAllStringSubmatch(s, -1) + if len(rawMatches) != 1 { + return nil, fmt.Errorf("invalid resource address %q", s) + } + + matches := make(map[string]string) + for i, m := range rawMatches[0] { + matches[groupNames[i]] = m + } + + return matches, nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_mode.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource_mode.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_mode.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource_mode.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_mode_string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource_mode_string.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/resource_mode_string.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource_mode_string.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource_provider.go new file mode 100644 index 00000000000..ece8fc66042 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/resource_provider.go @@ -0,0 +1,26 @@ +package terraform + +// ResourceType is a type of resource that a resource provider can manage. +type ResourceType struct { + Name string // Name of the resource, example "instance" (no provider prefix) + Importable bool // Whether this resource supports importing + + // SchemaAvailable is set if the provider supports the ProviderSchema, + // ResourceTypeSchema and DataSourceSchema methods. Although it is + // included on each resource type, it's actually a provider-wide setting + // that's smuggled here only because that avoids a breaking change to + // the plugin protocol. + SchemaAvailable bool +} + +// DataSource is a data source that a resource provider implements. +type DataSource struct { + Name string + + // SchemaAvailable is set if the provider supports the ProviderSchema, + // ResourceTypeSchema and DataSourceSchema methods. Although it is + // included on each resource type, it's actually a provider-wide setting + // that's smuggled here only because that avoids a breaking change to + // the plugin protocol. + SchemaAvailable bool +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/schemas.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/schemas.go new file mode 100644 index 00000000000..07e5a84fa1d --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/schemas.go @@ -0,0 +1,26 @@ +package terraform + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema" +) + +// ProviderSchema represents the schema for a provider's own configuration +// and the configuration for some or all of its resources and data sources. +// +// The completeness of this structure depends on how it was constructed. +// When constructed for a configuration, it will generally include only +// resource types and data sources used by that configuration. +type ProviderSchema struct { + Provider *configschema.Block + ResourceTypes map[string]*configschema.Block + DataSources map[string]*configschema.Block + + ResourceTypeSchemaVersions map[string]uint64 +} + +// ProviderSchemaRequest is used to describe to a ResourceProvider which +// aspects of schema are required, when calling the GetSchema method. +type ProviderSchemaRequest struct { + ResourceTypes []string + DataSources []string +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state.go new file mode 100644 index 00000000000..87f7610a93d --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state.go @@ -0,0 +1,1685 @@ +package terraform + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "log" + "os" + "reflect" + "sort" + "strconv" + "strings" + "sync" + + "github.com/hashicorp/go-cty/cty" + multierror "github.com/hashicorp/go-multierror" + uuid "github.com/hashicorp/go-uuid" + "github.com/mitchellh/copystructure" + + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/addrs" + "github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim" +) + +const ( + // StateVersion is the current version for our state file + stateVersion = 3 +) + +// rootModulePath is the path of the root module +var rootModulePath = []string{"root"} + +// normalizeModulePath transforms a legacy module path (which may or may not +// have a redundant "root" label at the start of it) into an +// addrs.ModuleInstance representing the same module. +// +// For legacy reasons, different parts of Terraform disagree about whether the +// root module has the path []string{} or []string{"root"}, and so this +// function accepts both and trims off the "root". An implication of this is +// that it's not possible to actually have a module call in the root module +// that is itself named "root", since that would be ambiguous. +// +// normalizeModulePath takes a raw module path and returns a path that +// has the rootModulePath prepended to it. If I could go back in time I +// would've never had a rootModulePath (empty path would be root). We can +// still fix this but thats a big refactor that my branch doesn't make sense +// for. Instead, this function normalizes paths. +func normalizeModulePath(p []string) addrs.ModuleInstance { + // FIXME: Remove this once everyone is using addrs.ModuleInstance. + + if len(p) > 0 && p[0] == "root" { + p = p[1:] + } + + ret := make(addrs.ModuleInstance, len(p)) + for i, name := range p { + // For now we don't actually support modules with multiple instances + // identified by keys, so we just treat every path element as a + // step with no key. + ret[i] = addrs.ModuleInstanceStep{ + Name: name, + } + } + return ret +} + +// State keeps track of a snapshot state-of-the-world that Terraform +// can use to keep track of what real world resources it is actually +// managing. +type State struct { + // Version is the state file protocol version. + Version int `json:"version"` + + // TFVersion is the version of Terraform that wrote this state. + TFVersion string `json:"terraform_version,omitempty"` + + // Serial is incremented on any operation that modifies + // the State file. It is used to detect potentially conflicting + // updates. + Serial int64 `json:"serial"` + + // Lineage is set when a new, blank state is created and then + // never updated. This allows us to determine whether the serials + // of two states can be meaningfully compared. + // Apart from the guarantee that collisions between two lineages + // are very unlikely, this value is opaque and external callers + // should only compare lineage strings byte-for-byte for equality. + Lineage string `json:"lineage"` + + // Remote is used to track the metadata required to + // pull and push state files from a remote storage endpoint. + Remote *RemoteState `json:"remote,omitempty"` + + // Backend tracks the configuration for the backend in use with + // this state. This is used to track any changes in the backend + // configuration. + Backend *BackendState `json:"backend,omitempty"` + + // Modules contains all the modules in a breadth-first order + Modules []*ModuleState `json:"modules"` + + mu sync.Mutex + + // IsBinaryDrivenTest is a special flag that assists with a binary driver + // heuristic, it should not be set externally + IsBinaryDrivenTest bool +} + +func (s *State) Lock() { s.mu.Lock() } +func (s *State) Unlock() { s.mu.Unlock() } + +// NewState is used to initialize a blank state +func NewState() *State { + s := &State{} + s.init() + return s +} + +// Children returns the ModuleStates that are direct children of +// the given path. If the path is "root", for example, then children +// returned might be "root.child", but not "root.child.grandchild". +func (s *State) Children(path []string) []*ModuleState { + s.Lock() + defer s.Unlock() + // TODO: test + + return s.children(path) +} + +func (s *State) children(path []string) []*ModuleState { + result := make([]*ModuleState, 0) + for _, m := range s.Modules { + if m == nil { + continue + } + + if len(m.Path) != len(path)+1 { + continue + } + if !reflect.DeepEqual(path, m.Path[:len(path)]) { + continue + } + + result = append(result, m) + } + + return result +} + +// AddModule adds the module with the given path to the state. +// +// This should be the preferred method to add module states since it +// allows us to optimize lookups later as well as control sorting. +func (s *State) AddModule(path addrs.ModuleInstance) *ModuleState { + s.Lock() + defer s.Unlock() + + return s.addModule(path) +} + +func (s *State) addModule(path addrs.ModuleInstance) *ModuleState { + // check if the module exists first + m := s.moduleByPath(path) + if m != nil { + return m + } + + // Lower the new-style address into a legacy-style address. + // This requires that none of the steps have instance keys, which is + // true for all addresses at the time of implementing this because + // "count" and "for_each" are not yet implemented for modules. + // For the purposes of state, the legacy address format also includes + // a redundant extra prefix element "root". It is important to include + // this because the "prune" method will remove any module that has a + // path length less than one, and other parts of the state code will + // trim off the first element indiscriminately. + legacyPath := make([]string, len(path)+1) + legacyPath[0] = "root" + for i, step := range path { + if step.InstanceKey != addrs.NoKey { + // FIXME: Once the rest of Terraform is ready to use count and + // for_each, remove all of this and just write the addrs.ModuleInstance + // value itself into the ModuleState. + panic("state cannot represent modules with count or for_each keys") + } + + legacyPath[i+1] = step.Name + } + + m = &ModuleState{Path: legacyPath} + m.init() + s.Modules = append(s.Modules, m) + s.sort() + return m +} + +// ModuleByPath is used to lookup the module state for the given path. +// This should be the preferred lookup mechanism as it allows for future +// lookup optimizations. +func (s *State) ModuleByPath(path addrs.ModuleInstance) *ModuleState { + if s == nil { + return nil + } + s.Lock() + defer s.Unlock() + + return s.moduleByPath(path) +} + +func (s *State) moduleByPath(path addrs.ModuleInstance) *ModuleState { + for _, mod := range s.Modules { + if mod == nil { + continue + } + if mod.Path == nil { + panic("missing module path") + } + modPath := normalizeModulePath(mod.Path) + if modPath.String() == path.String() { + return mod + } + } + return nil +} + +// Empty returns true if the state is empty. +func (s *State) Empty() bool { + if s == nil { + return true + } + s.Lock() + defer s.Unlock() + + return len(s.Modules) == 0 +} + +// HasResources returns true if the state contains any resources. +// +// This is similar to !s.Empty, but returns true also in the case where the +// state has modules but all of them are devoid of resources. +func (s *State) HasResources() bool { + if s.Empty() { + return false + } + + for _, mod := range s.Modules { + if len(mod.Resources) > 0 { + return true + } + } + + return false +} + +// IsRemote returns true if State represents a state that exists and is +// remote. +func (s *State) IsRemote() bool { + if s == nil { + return false + } + s.Lock() + defer s.Unlock() + + if s.Remote == nil { + return false + } + if s.Remote.Type == "" { + return false + } + + return true +} + +// Validate validates the integrity of this state file. +// +// Certain properties of the statefile are expected by Terraform in order +// to behave properly. The core of Terraform will assume that once it +// receives a State structure that it has been validated. This validation +// check should be called to ensure that. +// +// If this returns an error, then the user should be notified. The error +// response will include detailed information on the nature of the error. +func (s *State) Validate() error { + s.Lock() + defer s.Unlock() + + var result error + + // !!!! FOR DEVELOPERS !!!! + // + // Any errors returned from this Validate function will BLOCK TERRAFORM + // from loading a state file. Therefore, this should only contain checks + // that are only resolvable through manual intervention. + // + // !!!! FOR DEVELOPERS !!!! + + // Make sure there are no duplicate module states. We open a new + // block here so we can use basic variable names and future validations + // can do the same. + { + found := make(map[string]struct{}) + for _, ms := range s.Modules { + if ms == nil { + continue + } + + key := strings.Join(ms.Path, ".") + if _, ok := found[key]; ok { + result = multierror.Append(result, fmt.Errorf( + strings.TrimSpace(stateValidateErrMultiModule), key)) + continue + } + + found[key] = struct{}{} + } + } + + return result +} + +// Remove removes the item in the state at the given address, returning +// any errors that may have occurred. +// +// If the address references a module state or resource, it will delete +// all children as well. To check what will be deleted, use a StateFilter +// first. +func (s *State) Remove(addr ...string) error { + s.Lock() + defer s.Unlock() + + // Filter out what we need to delete + filter := &stateFilter{State: s} + results, err := filter.filter(addr...) + if err != nil { + return err + } + + // If we have no results, just exit early, we're not going to do anything. + // While what happens below is fairly fast, this is an important early + // exit since the prune below might modify the state more and we don't + // want to modify the state if we don't have to. + if len(results) == 0 { + return nil + } + + // Go through each result and grab what we need + removed := make(map[interface{}]struct{}) + for _, r := range results { + // Convert the path to our own type + path := append([]string{"root"}, r.Path...) + + // If we removed this already, then ignore + if _, ok := removed[r.Value]; ok { + continue + } + + // If we removed the parent already, then ignore + if r.Parent != nil { + if _, ok := removed[r.Parent.Value]; ok { + continue + } + } + + // Add this to the removed list + removed[r.Value] = struct{}{} + + switch v := r.Value.(type) { + case *ModuleState: + s.removeModule(path, v) + case *ResourceState: + s.removeResource(path, v) + case *InstanceState: + s.removeInstance(path, r.Parent.Value.(*ResourceState), v) + default: + return fmt.Errorf("unknown type to delete: %T", r.Value) + } + } + + // Prune since the removal functions often do the bare minimum to + // remove a thing and may leave around dangling empty modules, resources, + // etc. Prune will clean that all up. + s.prune() + + return nil +} + +func (s *State) removeModule(path []string, v *ModuleState) { + for i, m := range s.Modules { + if m == v { + s.Modules, s.Modules[len(s.Modules)-1] = append(s.Modules[:i], s.Modules[i+1:]...), nil + return + } + } +} + +func (s *State) removeResource(path []string, v *ResourceState) { + // Get the module this resource lives in. If it doesn't exist, we're done. + mod := s.moduleByPath(normalizeModulePath(path)) + if mod == nil { + return + } + + // Find this resource. This is a O(N) lookup when if we had the key + // it could be O(1) but even with thousands of resources this shouldn't + // matter right now. We can easily up performance here when the time comes. + for k, r := range mod.Resources { + if r == v { + // Found it + delete(mod.Resources, k) + return + } + } +} + +func (s *State) removeInstance(path []string, r *ResourceState, v *InstanceState) { + // Go through the resource and find the instance that matches this + // (if any) and remove it. + + // Check primary + if r.Primary == v { + r.Primary = nil + return + } + + // Check lists + lists := [][]*InstanceState{r.Deposed} + for _, is := range lists { + for i, instance := range is { + if instance == v { + // Found it, remove it + is, is[len(is)-1] = append(is[:i], is[i+1:]...), nil + + // Done + return + } + } + } +} + +// RootModule returns the ModuleState for the root module +func (s *State) RootModule() *ModuleState { + root := s.ModuleByPath(addrs.RootModuleInstance) + if root == nil { + panic("missing root module") + } + return root +} + +// Equal tests if one state is equal to another. +func (s *State) Equal(other *State) bool { + // If one is nil, we do a direct check + if s == nil || other == nil { + return s == other + } + + s.Lock() + defer s.Unlock() + return s.equal(other) +} + +func (s *State) equal(other *State) bool { + if s == nil || other == nil { + return s == other + } + + // If the versions are different, they're certainly not equal + if s.Version != other.Version { + return false + } + + // If any of the modules are not equal, then this state isn't equal + if len(s.Modules) != len(other.Modules) { + return false + } + for _, m := range s.Modules { + // This isn't very optimal currently but works. + otherM := other.moduleByPath(normalizeModulePath(m.Path)) + if otherM == nil { + return false + } + + // If they're not equal, then we're not equal! + if !m.Equal(otherM) { + return false + } + } + + return true +} + +type StateAgeComparison int + +const ( + StateAgeEqual StateAgeComparison = 0 + StateAgeReceiverNewer StateAgeComparison = 1 + StateAgeReceiverOlder StateAgeComparison = -1 +) + +// CompareAges compares one state with another for which is "older". +// +// This is a simple check using the state's serial, and is thus only as +// reliable as the serial itself. In the normal case, only one state +// exists for a given combination of lineage/serial, but Terraform +// does not guarantee this and so the result of this method should be +// used with care. +// +// Returns an integer that is negative if the receiver is older than +// the argument, positive if the converse, and zero if they are equal. +// An error is returned if the two states are not of the same lineage, +// in which case the integer returned has no meaning. +func (s *State) CompareAges(other *State) (StateAgeComparison, error) { + // nil states are "older" than actual states + switch { + case s != nil && other == nil: + return StateAgeReceiverNewer, nil + case s == nil && other != nil: + return StateAgeReceiverOlder, nil + case s == nil && other == nil: + return StateAgeEqual, nil + } + + if !s.SameLineage(other) { + return StateAgeEqual, fmt.Errorf( + "can't compare two states of differing lineage", + ) + } + + s.Lock() + defer s.Unlock() + + switch { + case s.Serial < other.Serial: + return StateAgeReceiverOlder, nil + case s.Serial > other.Serial: + return StateAgeReceiverNewer, nil + default: + return StateAgeEqual, nil + } +} + +// SameLineage returns true only if the state given in argument belongs +// to the same "lineage" of states as the receiver. +func (s *State) SameLineage(other *State) bool { + s.Lock() + defer s.Unlock() + + // If one of the states has no lineage then it is assumed to predate + // this concept, and so we'll accept it as belonging to any lineage + // so that a lineage string can be assigned to newer versions + // without breaking compatibility with older versions. + if s.Lineage == "" || other.Lineage == "" { + return true + } + + return s.Lineage == other.Lineage +} + +// DeepCopy performs a deep copy of the state structure and returns +// a new structure. +func (s *State) DeepCopy() *State { + if s == nil { + return nil + } + + copy, err := copystructure.Config{Lock: true}.Copy(s) + if err != nil { + panic(err) + } + + return copy.(*State) +} + +func (s *State) Init() { + s.Lock() + defer s.Unlock() + s.init() +} + +func (s *State) init() { + if s.Version == 0 { + s.Version = stateVersion + } + + if s.moduleByPath(addrs.RootModuleInstance) == nil { + s.addModule(addrs.RootModuleInstance) + } + s.ensureHasLineage() + + for _, mod := range s.Modules { + if mod != nil { + mod.init() + } + } + + if s.Remote != nil { + s.Remote.init() + } + +} + +func (s *State) EnsureHasLineage() { + s.Lock() + defer s.Unlock() + + s.ensureHasLineage() +} + +func (s *State) ensureHasLineage() { + if s.Lineage == "" { + lineage, err := uuid.GenerateUUID() + if err != nil { + panic(fmt.Errorf("Failed to generate lineage: %v", err)) + } + s.Lineage = lineage + if os.Getenv("TF_ACC") == "" || os.Getenv("TF_ACC_STATE_LINEAGE") == "1" { + log.Printf("[DEBUG] New state was assigned lineage %q\n", s.Lineage) + } + } else { + if os.Getenv("TF_ACC") == "" || os.Getenv("TF_ACC_STATE_LINEAGE") == "1" { + log.Printf("[TRACE] Preserving existing state lineage %q\n", s.Lineage) + } + } +} + +// AddModuleState insert this module state and override any existing ModuleState +func (s *State) AddModuleState(mod *ModuleState) { + mod.init() + s.Lock() + defer s.Unlock() + + s.addModuleState(mod) +} + +func (s *State) addModuleState(mod *ModuleState) { + for i, m := range s.Modules { + if reflect.DeepEqual(m.Path, mod.Path) { + s.Modules[i] = mod + return + } + } + + s.Modules = append(s.Modules, mod) + s.sort() +} + +// prune is used to remove any resources that are no longer required +func (s *State) prune() { + if s == nil { + return + } + + // Filter out empty modules. + // A module is always assumed to have a path, and it's length isn't always + // bounds checked later on. Modules may be "emptied" during destroy, but we + // never want to store those in the state. + for i := 0; i < len(s.Modules); i++ { + if s.Modules[i] == nil || len(s.Modules[i].Path) == 0 { + s.Modules = append(s.Modules[:i], s.Modules[i+1:]...) + i-- + } + } + + for _, mod := range s.Modules { + mod.prune() + } + if s.Remote != nil && s.Remote.Empty() { + s.Remote = nil + } +} + +// sort sorts the modules +func (s *State) sort() { + sort.Sort(moduleStateSort(s.Modules)) + + // Allow modules to be sorted + for _, m := range s.Modules { + if m != nil { + m.sort() + } + } +} + +func (s *State) String() string { + if s == nil { + return "" + } + s.Lock() + defer s.Unlock() + + var buf bytes.Buffer + for _, m := range s.Modules { + mStr := m.String() + + // If we're the root module, we just write the output directly. + if reflect.DeepEqual(m.Path, rootModulePath) { + buf.WriteString(mStr + "\n") + continue + } + + buf.WriteString(fmt.Sprintf("module.%s:\n", strings.Join(m.Path[1:], "."))) + + s := bufio.NewScanner(strings.NewReader(mStr)) + for s.Scan() { + text := s.Text() + if text != "" { + text = " " + text + } + + buf.WriteString(fmt.Sprintf("%s\n", text)) + } + } + + return strings.TrimSpace(buf.String()) +} + +// BackendState stores the configuration to connect to a remote backend. +type BackendState struct { + Type string `json:"type"` // Backend type + ConfigRaw json.RawMessage `json:"config"` // Backend raw config + Hash uint64 `json:"hash"` // Hash of portion of configuration from config files +} + +// RemoteState is used to track the information about a remote +// state store that we push/pull state to. +type RemoteState struct { + // Type controls the client we use for the remote state + Type string `json:"type"` + + // Config is used to store arbitrary configuration that + // is type specific + Config map[string]string `json:"config"` + + mu sync.Mutex +} + +func (s *RemoteState) Lock() { s.mu.Lock() } +func (s *RemoteState) Unlock() { s.mu.Unlock() } + +func (r *RemoteState) init() { + r.Lock() + defer r.Unlock() + + if r.Config == nil { + r.Config = make(map[string]string) + } +} + +func (r *RemoteState) Empty() bool { + if r == nil { + return true + } + r.Lock() + defer r.Unlock() + + return r.Type == "" +} + +// OutputState is used to track the state relevant to a single output. +type OutputState struct { + // Sensitive describes whether the output is considered sensitive, + // which may lead to masking the value on screen in some cases. + Sensitive bool `json:"sensitive"` + // Type describes the structure of Value. Valid values are "string", + // "map" and "list" + Type string `json:"type"` + // Value contains the value of the output, in the structure described + // by the Type field. + Value interface{} `json:"value"` + + mu sync.Mutex +} + +func (s *OutputState) Lock() { s.mu.Lock() } +func (s *OutputState) Unlock() { s.mu.Unlock() } + +func (s *OutputState) String() string { + return fmt.Sprintf("%#v", s.Value) +} + +// Equal compares two OutputState structures for equality. nil values are +// considered equal. +func (s *OutputState) Equal(other *OutputState) bool { + if s == nil && other == nil { + return true + } + + if s == nil || other == nil { + return false + } + s.Lock() + defer s.Unlock() + + if s.Type != other.Type { + return false + } + + if s.Sensitive != other.Sensitive { + return false + } + + if !reflect.DeepEqual(s.Value, other.Value) { + return false + } + + return true +} + +// ModuleState is used to track all the state relevant to a single +// module. Previous to Terraform 0.3, all state belonged to the "root" +// module. +type ModuleState struct { + // Path is the import path from the root module. Modules imports are + // always disjoint, so the path represents amodule tree + Path []string `json:"path"` + + // Locals are kept only transiently in-memory, because we can always + // re-compute them. + Locals map[string]interface{} `json:"-"` + + // Outputs declared by the module and maintained for each module + // even though only the root module technically needs to be kept. + // This allows operators to inspect values at the boundaries. + Outputs map[string]*OutputState `json:"outputs"` + + // Resources is a mapping of the logically named resource to + // the state of the resource. Each resource may actually have + // N instances underneath, although a user only needs to think + // about the 1:1 case. + Resources map[string]*ResourceState `json:"resources"` + + // Dependencies are a list of things that this module relies on + // existing to remain intact. For example: an module may depend + // on a VPC ID given by an aws_vpc resource. + // + // Terraform uses this information to build valid destruction + // orders and to warn the user if they're destroying a module that + // another resource depends on. + // + // Things can be put into this list that may not be managed by + // Terraform. If Terraform doesn't find a matching ID in the + // overall state, then it assumes it isn't managed and doesn't + // worry about it. + Dependencies []string `json:"depends_on"` + + mu sync.Mutex +} + +func (s *ModuleState) Lock() { s.mu.Lock() } +func (s *ModuleState) Unlock() { s.mu.Unlock() } + +// Equal tests whether one module state is equal to another. +func (m *ModuleState) Equal(other *ModuleState) bool { + m.Lock() + defer m.Unlock() + + // Paths must be equal + if !reflect.DeepEqual(m.Path, other.Path) { + return false + } + + // Outputs must be equal + if len(m.Outputs) != len(other.Outputs) { + return false + } + for k, v := range m.Outputs { + if !other.Outputs[k].Equal(v) { + return false + } + } + + // Dependencies must be equal. This sorts these in place but + // this shouldn't cause any problems. + sort.Strings(m.Dependencies) + sort.Strings(other.Dependencies) + if len(m.Dependencies) != len(other.Dependencies) { + return false + } + for i, d := range m.Dependencies { + if other.Dependencies[i] != d { + return false + } + } + + // Resources must be equal + if len(m.Resources) != len(other.Resources) { + return false + } + for k, r := range m.Resources { + otherR, ok := other.Resources[k] + if !ok { + return false + } + + if !r.Equal(otherR) { + return false + } + } + + return true +} + +func (m *ModuleState) init() { + m.Lock() + defer m.Unlock() + + if m.Path == nil { + m.Path = []string{} + } + if m.Outputs == nil { + m.Outputs = make(map[string]*OutputState) + } + if m.Resources == nil { + m.Resources = make(map[string]*ResourceState) + } + + if m.Dependencies == nil { + m.Dependencies = make([]string, 0) + } + + for _, rs := range m.Resources { + rs.init() + } +} + +// prune is used to remove any resources that are no longer required +func (m *ModuleState) prune() { + m.Lock() + defer m.Unlock() + + for k, v := range m.Resources { + if v == nil || (v.Primary == nil || v.Primary.ID == "") && len(v.Deposed) == 0 { + delete(m.Resources, k) + continue + } + + v.prune() + } + + for k, v := range m.Outputs { + if v.Value == hcl2shim.UnknownVariableValue { + delete(m.Outputs, k) + } + } + + m.Dependencies = uniqueStrings(m.Dependencies) +} + +func (m *ModuleState) sort() { + for _, v := range m.Resources { + v.sort() + } +} + +func (m *ModuleState) String() string { + m.Lock() + defer m.Unlock() + + var buf bytes.Buffer + + if len(m.Resources) == 0 { + buf.WriteString("") + } + + names := make([]string, 0, len(m.Resources)) + for name := range m.Resources { + names = append(names, name) + } + + sort.Sort(resourceNameSort(names)) + + for _, k := range names { + rs := m.Resources[k] + var id string + if rs.Primary != nil { + id = rs.Primary.ID + } + if id == "" { + id = "" + } + + taintStr := "" + if rs.Primary.Tainted { + taintStr = " (tainted)" + } + + deposedStr := "" + if len(rs.Deposed) > 0 { + deposedStr = fmt.Sprintf(" (%d deposed)", len(rs.Deposed)) + } + + buf.WriteString(fmt.Sprintf("%s:%s%s\n", k, taintStr, deposedStr)) + buf.WriteString(fmt.Sprintf(" ID = %s\n", id)) + if rs.Provider != "" { + buf.WriteString(fmt.Sprintf(" provider = %s\n", rs.Provider)) + } + + var attributes map[string]string + if rs.Primary != nil { + attributes = rs.Primary.Attributes + } + attrKeys := make([]string, 0, len(attributes)) + for ak := range attributes { + if ak == "id" { + continue + } + + attrKeys = append(attrKeys, ak) + } + + sort.Strings(attrKeys) + + for _, ak := range attrKeys { + av := attributes[ak] + buf.WriteString(fmt.Sprintf(" %s = %s\n", ak, av)) + } + + for idx, t := range rs.Deposed { + taintStr := "" + if t.Tainted { + taintStr = " (tainted)" + } + buf.WriteString(fmt.Sprintf(" Deposed ID %d = %s%s\n", idx+1, t.ID, taintStr)) + } + + if len(rs.Dependencies) > 0 { + buf.WriteString(fmt.Sprintf("\n Dependencies:\n")) + for _, dep := range rs.Dependencies { + buf.WriteString(fmt.Sprintf(" %s\n", dep)) + } + } + } + + if len(m.Outputs) > 0 { + buf.WriteString("\nOutputs:\n\n") + + ks := make([]string, 0, len(m.Outputs)) + for k := range m.Outputs { + ks = append(ks, k) + } + + sort.Strings(ks) + + for _, k := range ks { + v := m.Outputs[k] + switch vTyped := v.Value.(type) { + case string: + buf.WriteString(fmt.Sprintf("%s = %s\n", k, vTyped)) + case []interface{}: + buf.WriteString(fmt.Sprintf("%s = %s\n", k, vTyped)) + case map[string]interface{}: + var mapKeys []string + for key := range vTyped { + mapKeys = append(mapKeys, key) + } + sort.Strings(mapKeys) + + var mapBuf bytes.Buffer + mapBuf.WriteString("{") + for _, key := range mapKeys { + mapBuf.WriteString(fmt.Sprintf("%s:%s ", key, vTyped[key])) + } + mapBuf.WriteString("}") + + buf.WriteString(fmt.Sprintf("%s = %s\n", k, mapBuf.String())) + } + } + } + + return buf.String() +} + +// ResourceStateKey is a structured representation of the key used for the +// ModuleState.Resources mapping +type ResourceStateKey struct { + Name string + Type string + Mode ResourceMode + Index int +} + +// Equal determines whether two ResourceStateKeys are the same +func (rsk *ResourceStateKey) Equal(other *ResourceStateKey) bool { + if rsk == nil || other == nil { + return false + } + if rsk.Mode != other.Mode { + return false + } + if rsk.Type != other.Type { + return false + } + if rsk.Name != other.Name { + return false + } + if rsk.Index != other.Index { + return false + } + return true +} + +func (rsk *ResourceStateKey) String() string { + if rsk == nil { + return "" + } + var prefix string + switch rsk.Mode { + case ManagedResourceMode: + prefix = "" + case DataResourceMode: + prefix = "data." + default: + panic(fmt.Errorf("unknown resource mode %s", rsk.Mode)) + } + if rsk.Index == -1 { + return fmt.Sprintf("%s%s.%s", prefix, rsk.Type, rsk.Name) + } + return fmt.Sprintf("%s%s.%s.%d", prefix, rsk.Type, rsk.Name, rsk.Index) +} + +// ParseResourceStateKey accepts a key in the format used by +// ModuleState.Resources and returns a resource name and resource index. In the +// state, a resource has the format "type.name.index" or "type.name". In the +// latter case, the index is returned as -1. +func parseResourceStateKey(k string) (*ResourceStateKey, error) { + parts := strings.Split(k, ".") + mode := ManagedResourceMode + if len(parts) > 0 && parts[0] == "data" { + mode = DataResourceMode + // Don't need the constant "data" prefix for parsing + // now that we've figured out the mode. + parts = parts[1:] + } + if len(parts) < 2 || len(parts) > 3 { + return nil, fmt.Errorf("Malformed resource state key: %s", k) + } + rsk := &ResourceStateKey{ + Mode: mode, + Type: parts[0], + Name: parts[1], + Index: -1, + } + if len(parts) == 3 { + index, err := strconv.Atoi(parts[2]) + if err != nil { + return nil, fmt.Errorf("Malformed resource state key index: %s", k) + } + rsk.Index = index + } + return rsk, nil +} + +// ResourceState holds the state of a resource that is used so that +// a provider can find and manage an existing resource as well as for +// storing attributes that are used to populate variables of child +// resources. +// +// Attributes has attributes about the created resource that are +// queryable in interpolation: "${type.id.attr}" +// +// Extra is just extra data that a provider can return that we store +// for later, but is not exposed in any way to the user. +// +type ResourceState struct { + // This is filled in and managed by Terraform, and is the resource + // type itself such as "mycloud_instance". If a resource provider sets + // this value, it won't be persisted. + Type string `json:"type"` + + // Dependencies are a list of things that this resource relies on + // existing to remain intact. For example: an AWS instance might + // depend on a subnet (which itself might depend on a VPC, and so + // on). + // + // Terraform uses this information to build valid destruction + // orders and to warn the user if they're destroying a resource that + // another resource depends on. + // + // Things can be put into this list that may not be managed by + // Terraform. If Terraform doesn't find a matching ID in the + // overall state, then it assumes it isn't managed and doesn't + // worry about it. + Dependencies []string `json:"depends_on"` + + // Primary is the current active instance for this resource. + // It can be replaced but only after a successful creation. + // This is the instances on which providers will act. + Primary *InstanceState `json:"primary"` + + // Deposed is used in the mechanics of CreateBeforeDestroy: the existing + // Primary is Deposed to get it out of the way for the replacement Primary to + // be created by Apply. If the replacement Primary creates successfully, the + // Deposed instance is cleaned up. + // + // If there were problems creating the replacement Primary, the Deposed + // instance and the (now tainted) replacement Primary will be swapped so the + // tainted replacement will be cleaned up instead. + // + // An instance will remain in the Deposed list until it is successfully + // destroyed and purged. + Deposed []*InstanceState `json:"deposed"` + + // Provider is used when a resource is connected to a provider with an alias. + // If this string is empty, the resource is connected to the default provider, + // e.g. "aws_instance" goes with the "aws" provider. + // If the resource block contained a "provider" key, that value will be set here. + Provider string `json:"provider"` + + mu sync.Mutex +} + +func (s *ResourceState) Lock() { s.mu.Lock() } +func (s *ResourceState) Unlock() { s.mu.Unlock() } + +// Equal tests whether two ResourceStates are equal. +func (s *ResourceState) Equal(other *ResourceState) bool { + s.Lock() + defer s.Unlock() + + if s.Type != other.Type { + return false + } + + if s.Provider != other.Provider { + return false + } + + // Dependencies must be equal + sort.Strings(s.Dependencies) + sort.Strings(other.Dependencies) + if len(s.Dependencies) != len(other.Dependencies) { + return false + } + for i, d := range s.Dependencies { + if other.Dependencies[i] != d { + return false + } + } + + // States must be equal + if !s.Primary.Equal(other.Primary) { + return false + } + + return true +} + +// Taint marks a resource as tainted. +func (s *ResourceState) Taint() { + s.Lock() + defer s.Unlock() + + if s.Primary != nil { + s.Primary.Tainted = true + } +} + +// Untaint unmarks a resource as tainted. +func (s *ResourceState) Untaint() { + s.Lock() + defer s.Unlock() + + if s.Primary != nil { + s.Primary.Tainted = false + } +} + +func (s *ResourceState) init() { + s.Lock() + defer s.Unlock() + + if s.Primary == nil { + s.Primary = &InstanceState{} + } + s.Primary.init() + + if s.Dependencies == nil { + s.Dependencies = []string{} + } + + if s.Deposed == nil { + s.Deposed = make([]*InstanceState, 0) + } +} + +// prune is used to remove any instances that are no longer required +func (s *ResourceState) prune() { + s.Lock() + defer s.Unlock() + + n := len(s.Deposed) + for i := 0; i < n; i++ { + inst := s.Deposed[i] + if inst == nil || inst.ID == "" { + copy(s.Deposed[i:], s.Deposed[i+1:]) + s.Deposed[n-1] = nil + n-- + i-- + } + } + s.Deposed = s.Deposed[:n] + + s.Dependencies = uniqueStrings(s.Dependencies) +} + +func (s *ResourceState) sort() { + s.Lock() + defer s.Unlock() + + sort.Strings(s.Dependencies) +} + +func (s *ResourceState) String() string { + s.Lock() + defer s.Unlock() + + var buf bytes.Buffer + buf.WriteString(fmt.Sprintf("Type = %s", s.Type)) + return buf.String() +} + +// InstanceState is used to track the unique state information belonging +// to a given instance. +type InstanceState struct { + // A unique ID for this resource. This is opaque to Terraform + // and is only meant as a lookup mechanism for the providers. + ID string `json:"id"` + + // Attributes are basic information about the resource. Any keys here + // are accessible in variable format within Terraform configurations: + // ${resourcetype.name.attribute}. + Attributes map[string]string `json:"attributes"` + + // Ephemeral is used to store any state associated with this instance + // that is necessary for the Terraform run to complete, but is not + // persisted to a state file. + Ephemeral EphemeralState `json:"-"` + + // Meta is a simple K/V map that is persisted to the State but otherwise + // ignored by Terraform core. It's meant to be used for accounting by + // external client code. The value here must only contain Go primitives + // and collections. + Meta map[string]interface{} `json:"meta"` + + ProviderMeta cty.Value + + // Tainted is used to mark a resource for recreation. + Tainted bool `json:"tainted"` + + mu sync.Mutex +} + +func (s *InstanceState) Lock() { s.mu.Lock() } +func (s *InstanceState) Unlock() { s.mu.Unlock() } + +func (s *InstanceState) init() { + s.Lock() + defer s.Unlock() + + if s.Attributes == nil { + s.Attributes = make(map[string]string) + } + if s.Meta == nil { + s.Meta = make(map[string]interface{}) + } + s.Ephemeral.init() +} + +// NewInstanceStateShimmedFromValue is a shim method to lower a new-style +// object value representing the attributes of an instance object into the +// legacy InstanceState representation. +// +// This is for shimming to old components only and should not be used in new code. +func NewInstanceStateShimmedFromValue(state cty.Value, schemaVersion int) *InstanceState { + attrs := hcl2shim.FlatmapValueFromHCL2(state) + return &InstanceState{ + ID: attrs["id"], + Attributes: attrs, + Meta: map[string]interface{}{ + "schema_version": schemaVersion, + }, + } +} + +// AttrsAsObjectValue shims from the legacy InstanceState representation to +// a new-style cty object value representation of the state attributes, using +// the given type for guidance. +// +// The given type must be the implied type of the schema of the resource type +// of the object whose state is being converted, or the result is undefined. +// +// This is for shimming from old components only and should not be used in +// new code. +func (s *InstanceState) AttrsAsObjectValue(ty cty.Type) (cty.Value, error) { + if s == nil { + // if the state is nil, we need to construct a complete cty.Value with + // null attributes, rather than a single cty.NullVal(ty) + s = &InstanceState{} + } + + if s.Attributes == nil { + s.Attributes = map[string]string{} + } + + // make sure ID is included in the attributes. The InstanceState.ID value + // takes precedence. + if s.ID != "" { + s.Attributes["id"] = s.ID + } + + return hcl2shim.HCL2ValueFromFlatmap(s.Attributes, ty) +} + +// Copy all the Fields from another InstanceState +func (s *InstanceState) Set(from *InstanceState) { + s.Lock() + defer s.Unlock() + + from.Lock() + defer from.Unlock() + + s.ID = from.ID + s.Attributes = from.Attributes + s.Ephemeral = from.Ephemeral + s.Meta = from.Meta + s.Tainted = from.Tainted +} + +func (s *InstanceState) DeepCopy() *InstanceState { + copy, err := copystructure.Config{Lock: true}.Copy(s) + if err != nil { + panic(err) + } + + return copy.(*InstanceState) +} + +func (s *InstanceState) Empty() bool { + if s == nil { + return true + } + s.Lock() + defer s.Unlock() + + return s.ID == "" +} + +func (s *InstanceState) Equal(other *InstanceState) bool { + // Short circuit some nil checks + if s == nil || other == nil { + return s == other + } + s.Lock() + defer s.Unlock() + + // IDs must be equal + if s.ID != other.ID { + return false + } + + // Attributes must be equal + if len(s.Attributes) != len(other.Attributes) { + return false + } + for k, v := range s.Attributes { + otherV, ok := other.Attributes[k] + if !ok { + return false + } + + if v != otherV { + return false + } + } + + // Meta must be equal + if len(s.Meta) != len(other.Meta) { + return false + } + if s.Meta != nil && other.Meta != nil { + // We only do the deep check if both are non-nil. If one is nil + // we treat it as equal since their lengths are both zero (check + // above). + // + // Since this can contain numeric values that may change types during + // serialization, let's compare the serialized values. + sMeta, err := json.Marshal(s.Meta) + if err != nil { + // marshaling primitives shouldn't ever error out + panic(err) + } + otherMeta, err := json.Marshal(other.Meta) + if err != nil { + panic(err) + } + + if !bytes.Equal(sMeta, otherMeta) { + return false + } + } + + if s.Tainted != other.Tainted { + return false + } + + return true +} + +// MergeDiff takes a ResourceDiff and merges the attributes into +// this resource state in order to generate a new state. This new +// state can be used to provide updated attribute lookups for +// variable interpolation. +// +// If the diff attribute requires computing the value, and hence +// won't be available until apply, the value is replaced with the +// computeID. +func (s *InstanceState) MergeDiff(d *InstanceDiff) *InstanceState { + result := s.DeepCopy() + if result == nil { + result = new(InstanceState) + } + result.init() + + if s != nil { + s.Lock() + defer s.Unlock() + for k, v := range s.Attributes { + result.Attributes[k] = v + } + } + if d != nil { + for k, diff := range d.CopyAttributes() { + if diff.NewRemoved { + delete(result.Attributes, k) + continue + } + if diff.NewComputed { + result.Attributes[k] = hcl2shim.UnknownVariableValue + continue + } + + result.Attributes[k] = diff.New + } + } + + return result +} + +func (s *InstanceState) String() string { + notCreated := "" + + if s == nil { + return notCreated + } + + s.Lock() + defer s.Unlock() + + var buf bytes.Buffer + + if s.ID == "" { + return notCreated + } + + buf.WriteString(fmt.Sprintf("ID = %s\n", s.ID)) + + attributes := s.Attributes + attrKeys := make([]string, 0, len(attributes)) + for ak := range attributes { + if ak == "id" { + continue + } + + attrKeys = append(attrKeys, ak) + } + sort.Strings(attrKeys) + + for _, ak := range attrKeys { + av := attributes[ak] + buf.WriteString(fmt.Sprintf("%s = %s\n", ak, av)) + } + + buf.WriteString(fmt.Sprintf("Tainted = %t\n", s.Tainted)) + + return buf.String() +} + +// EphemeralState is used for transient state that is only kept in-memory +type EphemeralState struct { + // ConnInfo is used for the providers to export information which is + // used to connect to the resource for provisioning. For example, + // this could contain SSH or WinRM credentials. + ConnInfo map[string]string `json:"-"` + + // Type is used to specify the resource type for this instance. This is only + // required for import operations (as documented). If the documentation + // doesn't state that you need to set this, then don't worry about + // setting it. + Type string `json:"-"` +} + +func (e *EphemeralState) init() { + if e.ConnInfo == nil { + e.ConnInfo = make(map[string]string) + } +} + +// resourceNameSort implements the sort.Interface to sort name parts lexically for +// strings and numerically for integer indexes. +type resourceNameSort []string + +func (r resourceNameSort) Len() int { return len(r) } +func (r resourceNameSort) Swap(i, j int) { r[i], r[j] = r[j], r[i] } + +func (r resourceNameSort) Less(i, j int) bool { + iParts := strings.Split(r[i], ".") + jParts := strings.Split(r[j], ".") + + end := len(iParts) + if len(jParts) < end { + end = len(jParts) + } + + for idx := 0; idx < end; idx++ { + if iParts[idx] == jParts[idx] { + continue + } + + // sort on the first non-matching part + iInt, iIntErr := strconv.Atoi(iParts[idx]) + jInt, jIntErr := strconv.Atoi(jParts[idx]) + + switch { + case iIntErr == nil && jIntErr == nil: + // sort numerically if both parts are integers + return iInt < jInt + case iIntErr == nil: + // numbers sort before strings + return true + case jIntErr == nil: + return false + default: + return iParts[idx] < jParts[idx] + } + } + + return r[i] < r[j] +} + +// moduleStateSort implements sort.Interface to sort module states +type moduleStateSort []*ModuleState + +func (s moduleStateSort) Len() int { + return len(s) +} + +func (s moduleStateSort) Less(i, j int) bool { + a := s[i] + b := s[j] + + // If either is nil, then the nil one is "less" than + if a == nil || b == nil { + return a == nil + } + + // If the lengths are different, then the shorter one always wins + if len(a.Path) != len(b.Path) { + return len(a.Path) < len(b.Path) + } + + // Otherwise, compare lexically + return strings.Join(a.Path, ".") < strings.Join(b.Path, ".") +} + +func (s moduleStateSort) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} + +const stateValidateErrMultiModule = ` +Multiple modules with the same path: %s + +This means that there are multiple entries in the "modules" field +in your state file that point to the same module. This will cause Terraform +to behave in unexpected and error prone ways and is invalid. Please back up +and modify your state file manually to resolve this. +` diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_filter.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state_filter.go similarity index 77% rename from vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_filter.go rename to vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state_filter.go index 2dcb11b76b9..01d039272e3 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/state_filter.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/state_filter.go @@ -5,7 +5,7 @@ import ( "sort" ) -// StateFilter is responsible for filtering and searching a state. +// stateFilter is responsible for filtering and searching a state. // // This is a separate struct from State rather than a method on State // because StateFilter might create sidecar data structures to optimize @@ -15,18 +15,18 @@ import ( // Reset should be called or a new one should be allocated. StateFilter // will not watch State for changes and do this for you. If you filter after // changing the State without calling Reset, the behavior is not defined. -type StateFilter struct { +type stateFilter struct { State *State } // Filter takes the addresses specified by fs and finds all the matches. // The values of fs are resource addressing syntax that can be parsed by -// ParseResourceAddress. -func (f *StateFilter) Filter(fs ...string) ([]*StateFilterResult, error) { +// parseResourceAddress. +func (f *stateFilter) filter(fs ...string) ([]*stateFilterResult, error) { // Parse all the addresses - as := make([]*ResourceAddress, len(fs)) + as := make([]*resourceAddress, len(fs)) for i, v := range fs { - a, err := ParseResourceAddress(v) + a, err := parseResourceAddress(v) if err != nil { return nil, fmt.Errorf("Error parsing address '%s': %s", v, err) } @@ -36,12 +36,12 @@ func (f *StateFilter) Filter(fs ...string) ([]*StateFilterResult, error) { // If we weren't given any filters, then we list all if len(fs) == 0 { - as = append(as, &ResourceAddress{Index: -1}) + as = append(as, &resourceAddress{Index: -1}) } // Filter each of the address. We keep track of this in a map to // strip duplicates. - resultSet := make(map[string]*StateFilterResult) + resultSet := make(map[string]*stateFilterResult) for _, a := range as { for _, r := range f.filterSingle(a) { resultSet[r.String()] = r @@ -49,19 +49,19 @@ func (f *StateFilter) Filter(fs ...string) ([]*StateFilterResult, error) { } // Make the result list - results := make([]*StateFilterResult, 0, len(resultSet)) + results := make([]*stateFilterResult, 0, len(resultSet)) for _, v := range resultSet { results = append(results, v) } // Sort them and return - sort.Sort(StateFilterResultSlice(results)) + sort.Sort(stateFilterResultSlice(results)) return results, nil } -func (f *StateFilter) filterSingle(a *ResourceAddress) []*StateFilterResult { +func (f *stateFilter) filterSingle(a *resourceAddress) []*stateFilterResult { // The slice to keep track of results - var results []*StateFilterResult + var results []*stateFilterResult // Go through modules first. modules := make([]*ModuleState, 0, len(f.State.Modules)) @@ -72,9 +72,9 @@ func (f *StateFilter) filterSingle(a *ResourceAddress) []*StateFilterResult { // Only add the module to the results if we haven't specified a type. // We also ignore the root module. if a.Type == "" && len(m.Path) > 1 { - results = append(results, &StateFilterResult{ + results = append(results, &stateFilterResult{ Path: m.Path[1:], - Address: (&ResourceAddress{Path: m.Path[1:]}).String(), + Address: (&resourceAddress{Path: m.Path[1:]}).String(), Value: m, }) } @@ -86,7 +86,7 @@ func (f *StateFilter) filterSingle(a *ResourceAddress) []*StateFilterResult { for _, m := range modules { for n, r := range m.Resources { // The name in the state contains valuable information. Parse. - key, err := ParseResourceStateKey(n) + key, err := parseResourceStateKey(n) if err != nil { // If we get an error parsing, then just ignore it // out of the state. @@ -116,7 +116,7 @@ func (f *StateFilter) filterSingle(a *ResourceAddress) []*StateFilterResult { } // Build the address for this resource - addr := &ResourceAddress{ + addr := &resourceAddress{ Path: m.Path[1:], Name: key.Name, Type: key.Type, @@ -124,7 +124,7 @@ func (f *StateFilter) filterSingle(a *ResourceAddress) []*StateFilterResult { } // Add the resource level result - resourceResult := &StateFilterResult{ + resourceResult := &stateFilterResult{ Path: addr.Path, Address: addr.String(), Value: r, @@ -135,9 +135,9 @@ func (f *StateFilter) filterSingle(a *ResourceAddress) []*StateFilterResult { // Add the instances if r.Primary != nil { - addr.InstanceType = TypePrimary + addr.InstanceType = typePrimary addr.InstanceTypeSet = false - results = append(results, &StateFilterResult{ + results = append(results, &stateFilterResult{ Path: addr.Path, Address: addr.String(), Parent: resourceResult, @@ -147,9 +147,9 @@ func (f *StateFilter) filterSingle(a *ResourceAddress) []*StateFilterResult { for _, instance := range r.Deposed { if f.relevant(a, instance) { - addr.InstanceType = TypeDeposed + addr.InstanceType = typeDeposed addr.InstanceTypeSet = true - results = append(results, &StateFilterResult{ + results = append(results, &stateFilterResult{ Path: addr.Path, Address: addr.String(), Parent: resourceResult, @@ -165,7 +165,7 @@ func (f *StateFilter) filterSingle(a *ResourceAddress) []*StateFilterResult { } // relevant checks for relevance of this address against the given value. -func (f *StateFilter) relevant(addr *ResourceAddress, raw interface{}) bool { +func (f *stateFilter) relevant(addr *resourceAddress, raw interface{}) bool { switch v := raw.(type) { case *ModuleState: path := v.Path[1:] @@ -202,10 +202,10 @@ func (f *StateFilter) relevant(addr *ResourceAddress, raw interface{}) bool { } } -// StateFilterResult is a single result from a filter operation. Filter +// stateFilterResult is a single result from a filter operation. Filter // can match multiple things within a state (module, resource, instance, etc.) // and this unifies that. -type StateFilterResult struct { +type stateFilterResult struct { // Module path of the result Path []string @@ -215,7 +215,7 @@ type StateFilterResult struct { // Parent, if non-nil, is a parent of this result. For instances, the // parent would be a resource. For resources, the parent would be // a module. For modules, this is currently nil. - Parent *StateFilterResult + Parent *stateFilterResult // Value is the actual value. This must be type switched on. It can be // any data structures that `State` can hold: `ModuleState`, @@ -223,11 +223,11 @@ type StateFilterResult struct { Value interface{} } -func (r *StateFilterResult) String() string { +func (r *stateFilterResult) String() string { return fmt.Sprintf("%T: %s", r.Value, r.Address) } -func (r *StateFilterResult) sortedType() int { +func (r *stateFilterResult) sortedType() int { switch r.Value.(type) { case *ModuleState: return 0 @@ -240,19 +240,19 @@ func (r *StateFilterResult) sortedType() int { } } -// StateFilterResultSlice is a slice of results that implements +// stateFilterResultSlice is a slice of results that implements // sort.Interface. The sorting goal is what is most appealing to // human output. -type StateFilterResultSlice []*StateFilterResult +type stateFilterResultSlice []*stateFilterResult -func (s StateFilterResultSlice) Len() int { return len(s) } -func (s StateFilterResultSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s StateFilterResultSlice) Less(i, j int) bool { +func (s stateFilterResultSlice) Len() int { return len(s) } +func (s stateFilterResultSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s stateFilterResultSlice) Less(i, j int) bool { a, b := s[i], s[j] // if these address contain an index, we want to sort by index rather than name - addrA, errA := ParseResourceAddress(a.Address) - addrB, errB := ParseResourceAddress(b.Address) + addrA, errA := parseResourceAddress(a.Address) + addrB, errB := parseResourceAddress(b.Address) if errA == nil && errB == nil && addrA.Name == addrB.Name && addrA.Index != addrB.Index { return addrA.Index < addrB.Index } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/util.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/util.go new file mode 100644 index 00000000000..01ac810f103 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/v2/terraform/util.go @@ -0,0 +1,22 @@ +package terraform + +import ( + "sort" +) + +// 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/vendor/github.com/hashicorp/terraform-plugin-test/LICENSE b/vendor/github.com/hashicorp/terraform-plugin-test/LICENSE deleted file mode 100644 index 82b4de97c7e..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-test/LICENSE +++ /dev/null @@ -1,353 +0,0 @@ -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-plugin-test/config.go b/vendor/github.com/hashicorp/terraform-plugin-test/config.go deleted file mode 100644 index a40460e9b4c..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-test/config.go +++ /dev/null @@ -1,60 +0,0 @@ -package tftest - -import ( - "fmt" - "os" - "path/filepath" -) - -// Config is used to configure the test helper. In most normal test programs -// the configuration is discovered automatically by an Init* function using -// DiscoverConfig, but this is exposed so that more complex scenarios can be -// implemented by direct configuration. -type Config struct { - PluginName string - SourceDir string - TerraformExec string - CurrentPluginExec string - PreviousPluginExec string -} - -// DiscoverConfig uses environment variables and other means to automatically -// discover a reasonable test helper configuration. -func DiscoverConfig(pluginName string, sourceDir string) (*Config, error) { - var tfExec string - var err error - tfVersion := os.Getenv("TF_ACC_TERRAFORM_VERSION") - if tfVersion == "" { - tfExec = FindTerraform() - if tfExec == "" { - return nil, fmt.Errorf("unable to find 'terraform' executable for testing; either place it in PATH or set TF_ACC_TERRAFORM_PATH explicitly to a direct executable path") - } - } else { - tfExec, err = InstallTerraform(tfVersion) - if err != nil { - return nil, fmt.Errorf("could not install Terraform version %s: %s", tfVersion, err) - } - } - - prevExec := os.Getenv("TF_ACC_PREVIOUS_EXEC") - if prevExec != "" { - if info, err := os.Stat(prevExec); err != nil { - return nil, fmt.Errorf("TF_ACC_PREVIOUS_EXEC of %s cannot be used: %s", prevExec, err) - } else if info.IsDir() { - return nil, fmt.Errorf("TF_ACC_PREVIOUS_EXEC of %s is directory, not file", prevExec) - } - } - - absPluginExecPath, err := filepath.Abs(os.Args[0]) - if err != nil { - return nil, fmt.Errorf("could not resolve plugin exec path %s: %s", os.Args[0], err) - } - - return &Config{ - PluginName: pluginName, - SourceDir: sourceDir, - TerraformExec: tfExec, - CurrentPluginExec: absPluginExecPath, - PreviousPluginExec: os.Getenv("TF_ACC_PREVIOUS_EXEC"), - }, nil -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/go.mod b/vendor/github.com/hashicorp/terraform-plugin-test/go.mod deleted file mode 100644 index 1c3c29a154a..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-test/go.mod +++ /dev/null @@ -1,8 +0,0 @@ -module github.com/hashicorp/terraform-plugin-test - -go 1.12 - -require ( - github.com/hashicorp/go-getter v1.4.0 - github.com/hashicorp/terraform-json v0.4.0 -) diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/go.sum b/vendor/github.com/hashicorp/terraform-plugin-test/go.sum deleted file mode 100644 index 9d69283aa4b..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-test/go.sum +++ /dev/null @@ -1,170 +0,0 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= -cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= -cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.45.1 h1:lRi0CHyU+ytlvylOlFKKq0af6JncuyoRh1J+QJBqQx0= -cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= -cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= -github.com/aws/aws-sdk-go v1.15.78 h1:LaXy6lWR0YK7LKyuU0QWy2ws/LWTPfYV/UgfiBu4tvY= -github.com/aws/aws-sdk-go v1.15.78/go.mod h1:E3/ieXAlvM0XWO57iftYVDLLvQ824smPP3ATZkfNZeM= -github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= -github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= -github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= -github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= -github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= -github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-getter v1.4.0 h1:ENHNi8494porjD0ZhIrjlAHnveSFhY7hvOJrV/fsKkw= -github.com/hashicorp/go-getter v1.4.0/go.mod h1:7qxyCd8rBfcShwsvxgIguu4KbS3l8bUCwg2Umn7RjeY= -github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo= -github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= -github.com/hashicorp/go-version v1.1.0 h1:bPIoEKD27tNdebFGGxxYwcL4nepeY4j1QP23PFRGzg0= -github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/terraform-json v0.4.0 h1:KNh29iNxozP5adfUFBJ4/fWd0Cu3taGgjHB38JYqOF4= -github.com/hashicorp/terraform-json v0.4.0/go.mod h1:eAbqb4w0pSlRmdvl8fOyHAi/+8jnkVYN28gJkSJrLhU= -github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8 h1:12VvqtR6Aowv3l/EQUlocDHW2Cp4G9WJVH7uyH8QFJE= -github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= -github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= -github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v1.0.0 h1:fzU/JVNcaqHQEcVFAKeR41fkiLdIPrefOvVG1VZ96U0= -github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/ulikunitz/xz v0.5.5 h1:pFrO0lVpTBXLpYw+pnLj6TbvHuyjXMfjGeCwSqCVwok= -github.com/ulikunitz/xz v0.5.5/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= -github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= -github.com/zclconf/go-cty v1.2.1 h1:vGMsygfmeCl4Xb6OA5U5XVAaQZ69FvoG7X2jUtQujb8= -github.com/zclconf/go-cty v1.2.1/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= -go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0 h1:C9hSCOW830chIVkdja34wa6Ky+IzWllkUinR+BtRZd4= -go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0 h1:HyfiK1WMnHj5FXFXatD+Qs1A/xC2Run6RzeW1SyHxpc= -golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= -google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= -google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0 h1:jbyannxz0XFD3zdjgrSUsaJbgpH4eTrkdhRChkHPfO8= -google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1 h1:QzqyMA1tlu6CgqCDUtU9V+ZKhLFT2dkJuANu5QaxI3I= -google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.1 h1:j6XxA85m/6txkUCHvzlV5f+HBNl/1r5cZ2A/3IEFOO8= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/cheggaaa/pb.v1 v1.0.27/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/helper.go b/vendor/github.com/hashicorp/terraform-plugin-test/helper.go deleted file mode 100644 index d4de44680e8..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-test/helper.go +++ /dev/null @@ -1,285 +0,0 @@ -package tftest - -import ( - "fmt" - "io/ioutil" - "os" - "path/filepath" - "runtime" - "strings" - - getter "github.com/hashicorp/go-getter" -) - -const subprocessCurrentSigil = "4acd63807899403ca4859f5bb948d2c6" -const subprocessPreviousSigil = "2279afb8cf71423996be1fd65d32f13b" - -// AutoInitProviderHelper is the main entrypoint for testing provider plugins -// using this package. It is intended to be called during TestMain to prepare -// for provider testing. -// -// AutoInitProviderHelper will discover the location of a current Terraform CLI -// executable to test against, detect whether a prior version of the plugin is -// available for upgrade tests, and then will return an object containing the -// results of that initialization which can then be stored in a global variable -// for use in other tests. -func AutoInitProviderHelper(name string, sourceDir string) *Helper { - helper, err := AutoInitHelper("terraform-provider-"+name, sourceDir) - if err != nil { - fmt.Fprintf(os.Stderr, "cannot run Terraform provider tests: %s\n", err) - os.Exit(1) - } - return helper -} - -// Helper is intended as a per-package singleton created in TestMain which -// other tests in a package can use to create Terraform execution contexts -type Helper struct { - baseDir string - - // sourceDir is the dir containing the provider source code, needed - // for tests that use fixture files. - sourceDir string - pluginName string - terraformExec string - thisPluginDir, prevPluginDir string -} - -// AutoInitHelper uses the auto-discovery behavior of DiscoverConfig to prepare -// a configuration and then calls InitHelper with it. This is a convenient -// way to get the standard init behavior based on environment variables, and -// callers should use this unless they have an unusual requirement that calls -// for constructing a config in a different way. -func AutoInitHelper(pluginName string, sourceDir string) (*Helper, error) { - config, err := DiscoverConfig(pluginName, sourceDir) - if err != nil { - return nil, err - } - - return InitHelper(config) -} - -// InitHelper prepares a testing helper with the given configuration. -// -// For most callers it is sufficient to call AutoInitHelper instead, which -// will construct a configuration automatically based on certain environment -// variables. -// -// If this function returns an error then it may have left some temporary files -// behind in the system's temporary directory. There is currently no way to -// automatically clean those up. -func InitHelper(config *Config) (*Helper, error) { - tempDir := os.Getenv("TF_ACC_TEMP_DIR") - baseDir, err := ioutil.TempDir(tempDir, "tftest-"+config.PluginName) - if err != nil { - return nil, fmt.Errorf("failed to create temporary directory for test helper: %s", err) - } - - var thisPluginDir, prevPluginDir string - if config.CurrentPluginExec != "" { - thisPluginDir, err = ioutil.TempDir(baseDir, "plugins-current") - if err != nil { - return nil, fmt.Errorf("failed to create temporary directory for -plugin-dir: %s", err) - } - currentExecPath := filepath.Join(thisPluginDir, config.PluginName) - err = symlinkFile(config.CurrentPluginExec, currentExecPath) - if err != nil { - return nil, fmt.Errorf("failed to create symlink at %s to %s: %s", currentExecPath, config.CurrentPluginExec, err) - } - - err = symlinkAuxiliaryProviders(thisPluginDir) - if err != nil { - return nil, fmt.Errorf("failed to symlink auxiliary providers: %s", err) - } - } else { - return nil, fmt.Errorf("CurrentPluginExec is not set") - } - if config.PreviousPluginExec != "" { - prevPluginDir, err = ioutil.TempDir(baseDir, "plugins-previous") - if err != nil { - return nil, fmt.Errorf("failed to create temporary directory for previous -plugin-dir: %s", err) - } - prevExecPath := filepath.Join(prevPluginDir, config.PluginName) - err = symlinkFile(config.PreviousPluginExec, prevExecPath) - if err != nil { - return nil, fmt.Errorf("failed to create symlink at %s to %s: %s", prevExecPath, config.PreviousPluginExec, err) - } - - err = symlinkAuxiliaryProviders(prevPluginDir) - if err != nil { - return nil, fmt.Errorf("failed to symlink auxiliary providers: %s", err) - } - } - - return &Helper{ - baseDir: baseDir, - sourceDir: config.SourceDir, - pluginName: config.PluginName, - terraformExec: config.TerraformExec, - thisPluginDir: thisPluginDir, - prevPluginDir: prevPluginDir, - }, nil -} - -// symlinkAuxiliaryProviders discovers auxiliary provider binaries, used in -// multi-provider tests, and symlinks them to the plugin directory. -// -// Auxiliary provider binaries should be included in the provider source code -// directory, under the path terraform.d/plugins/$GOOS_$GOARCH/provider-name. -// -// The environment variable TF_ACC_PROVIDER_ROOT_DIR must be set to the path of -// the provider source code directory root in order to use this feature. -func symlinkAuxiliaryProviders(pluginDir string) error { - providerRootDir := os.Getenv("TF_ACC_PROVIDER_ROOT_DIR") - if providerRootDir == "" { - // common case; assume intentional and do not log - return nil - } - - _, err := os.Stat(filepath.Join(providerRootDir, "terraform.d", "plugins")) - if os.IsNotExist(err) { - fmt.Printf("No terraform.d/plugins directory found: continuing. Unset TF_ACC_PROVIDER_ROOT_DIR or supply provider binaries in terraform.d/plugins/$GOOS_$GOARCH to disable this message.") - return nil - } else if err != nil { - return fmt.Errorf("Unexpected error: %s", err) - } - - auxiliaryProviderDir := filepath.Join(providerRootDir, "terraform.d", "plugins", runtime.GOOS+"_"+runtime.GOARCH) - - // If we can't os.Stat() terraform.d/plugins/$GOOS_$GOARCH, however, - // assume the omission was unintentional, and error. - _, err = os.Stat(auxiliaryProviderDir) - if os.IsNotExist(err) { - return fmt.Errorf("error finding auxiliary provider dir %s: %s", auxiliaryProviderDir, err) - } else if err != nil { - return fmt.Errorf("Unexpected error: %s", err) - } - - // now find all the providers in that dir and symlink them to the plugin dir - providers, err := ioutil.ReadDir(auxiliaryProviderDir) - if err != nil { - return fmt.Errorf("error reading auxiliary providers: %s", err) - } - - zipDecompressor := new(getter.ZipDecompressor) - - for _, provider := range providers { - filename := provider.Name() - filenameExt := filepath.Ext(filename) - name := strings.TrimSuffix(filename, filenameExt) - path := filepath.Join(auxiliaryProviderDir, name) - symlinkPath := filepath.Join(pluginDir, name) - - // exit early if we have already symlinked this provider - _, err := os.Stat(symlinkPath) - if err == nil { - continue - } - - // if filename ends in .zip, assume it is a zip and extract it - // otherwise assume it is a provider binary - if filenameExt == ".zip" { - _, err = os.Stat(path) - if os.IsNotExist(err) { - zipDecompressor.Decompress(path, filepath.Join(auxiliaryProviderDir, filename), false) - } else if err != nil { - return fmt.Errorf("Unexpected error: %s", err) - } - } - - err = symlinkFile(path, symlinkPath) - if err != nil { - return fmt.Errorf("error symlinking auxiliary provider %s: %s", name, err) - } - } - - return nil -} - -// Close cleans up temporary files and directories created to support this -// helper, returning an error if any of the cleanup fails. -// -// Call this before returning from TestMain to minimize the amount of detritus -// left behind in the filesystem after the tests complete. -func (h *Helper) Close() error { - return os.RemoveAll(h.baseDir) -} - -// NewWorkingDir creates a new working directory for use in the implementation -// of a single test, returning a WorkingDir object representing that directory. -// -// If the working directory object is not itself closed by the time the test -// program exits, the Close method on the helper itself will attempt to -// delete it. -func (h *Helper) NewWorkingDir() (*WorkingDir, error) { - dir, err := ioutil.TempDir(h.baseDir, "work") - if err != nil { - return nil, err - } - - // symlink the provider source files into the base directory - err = symlinkDir(h.sourceDir, dir) - if err != nil { - return nil, err - } - - // symlink the provider binaries into the base directory - err = symlinkDir(h.thisPluginDir, dir) - if err != nil { - return nil, err - } - - return &WorkingDir{ - h: h, - baseArgs: []string{"-no-color"}, - baseDir: dir, - }, nil -} - -// RequireNewWorkingDir is a variant of NewWorkingDir that takes a TestControl -// object and will immediately fail the running test if the creation of the -// working directory fails. -func (h *Helper) RequireNewWorkingDir(t TestControl) *WorkingDir { - t.Helper() - - wd, err := h.NewWorkingDir() - if err != nil { - t := testingT{t} - t.Fatalf("failed to create new working directory: %s", err) - return nil - } - return wd -} - -// HasPreviousVersion returns true if and only if the receiving helper has a -// previous plugin version available for use in tests. -func (h *Helper) HasPreviousVersion() bool { - return h.prevPluginDir != "" -} - -// TerraformExecPath returns the location of the Terraform CLI executable that -// should be used when running tests. -func (h *Helper) TerraformExecPath() string { - return h.terraformExec -} - -// PluginDir returns the directory that should be used as the -plugin-dir when -// running "terraform init" in order to make Terraform detect the current -// version of the plugin. -func (h *Helper) PluginDir() string { - return h.thisPluginDir -} - -// PreviousPluginDir returns the directory that should be used as the -plugin-dir -// when running "terraform init" in order to make Terraform detect the previous -// version of the plugin, if available. -// -// If no previous version is available, this method will panic. Use -// RequirePreviousVersion or HasPreviousVersion to ensure a previous version is -// available before calling this. -func (h *Helper) PreviousPluginDir() string { - if h.prevPluginDir != "" { - panic("PreviousPluginDir not available") - } - return h.prevPluginDir -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/terraform.go b/vendor/github.com/hashicorp/terraform-plugin-test/terraform.go deleted file mode 100644 index d2f118e1556..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-test/terraform.go +++ /dev/null @@ -1,163 +0,0 @@ -package tftest - -import ( - "bytes" - "encoding/json" - "fmt" - getter "github.com/hashicorp/go-getter" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" -) - -const releaseHost = "https://releases.hashicorp.com" - -// FindTerraform attempts to find a Terraform CLI executable for plugin testing. -// -// As a first preference it will look for the environment variable -// TF_ACC_TERRAFORM_PATH and return its value. If that variable is not set, it will -// look in PATH for a program named "terraform" and, if one is found, return -// its absolute path. -// -// If no Terraform executable can be found, the result is the empty string. In -// that case, the test program will usually fail outright. -func FindTerraform() string { - if p := os.Getenv("TF_ACC_TERRAFORM_PATH"); p != "" { - return p - } - p, err := exec.LookPath("terraform") - if err != nil { - return "" - } - return p -} - -func tfURL(version, osName, archName string) string { - return fmt.Sprintf( - "%s/terraform/%s/terraform_%s_%s_%s.zip", - releaseHost, version, version, osName, archName, - ) -} - -// InstallTerraform downloads and decompresses a Terraform CLI executable with -// the specified version, downloaded from the HashiCorp releases page over HTTP. -// -// The version string must match an existing Terraform release semver version, -// e.g. 0.12.5. -// -// The terraform executable is installed to a temporary folder. -// -// FIXME: Temporary folder should be cleaned up after tests have finished. -func InstallTerraform(tfVersion string) (string, error) { - osName := runtime.GOOS - archName := runtime.GOARCH - - var tfDir string - var err error - - tempDir := os.Getenv("TF_ACC_TEMP_DIR") - tfDir, err = ioutil.TempDir(tempDir, "tftest-terraform") - if err != nil { - return "", fmt.Errorf("failed to create temp dir: %s", err) - } - - url := tfURL(tfVersion, osName, archName) - - client := getter.Client{ - Src: url, - Dst: tfDir, - - Mode: getter.ClientModeDir, - } - - err = client.Get() - if err != nil { - return "", fmt.Errorf("failed to download terraform from %s: %s", url, err) - } - - return filepath.Join(tfDir, "terraform"), nil -} - -// getTerraformEnv returns the appropriate Env for the Terraform command. -func getTerraformEnv() []string { - var env []string - for _, e := range os.Environ() { - env = append(env, e) - } - - env = append(env, "TF_DISABLE_PLUGIN_TLS=1") - env = append(env, "TF_SKIP_PROVIDER_VERIFY=1") - - // FIXME: Ideally in testing.Verbose mode we'd turn on Terraform DEBUG - // logging, perhaps redirected to a separate fd other than stderr to avoid - // polluting it, and then propagate the log lines out into t.Log so that - // they are visible to the person running the test. Currently though, - // Terraform CLI is able to send logs only to either an on-disk file or - // to stderr. - env = append(env, "TF_LOG=") // so logging can't pollute our stderr output - env = append(env, "TF_INPUT=0") - - if p := os.Getenv("TF_ACC_LOG_PATH"); p != "" { - env = append(env, "TF_LOG=TRACE") - env = append(env, "TF_LOG_PATH="+p) - } - return env -} - -// RunTerraform runs the configured Terraform CLI executable with the given -// arguments, returning an error if it produces a non-successful exit status. -func (wd *WorkingDir) runTerraform(args ...string) error { - allArgs := []string{"terraform"} - allArgs = append(allArgs, args...) - - env := getTerraformEnv() - - var errBuf strings.Builder - - cmd := &exec.Cmd{ - Path: wd.h.TerraformExecPath(), - Args: allArgs, - Dir: wd.baseDir, - Stderr: &errBuf, - Env: env, - } - err := cmd.Run() - if tErr, ok := err.(*exec.ExitError); ok { - err = fmt.Errorf("terraform failed: %s\n\nstderr:\n%s", tErr.ProcessState.String(), errBuf.String()) - } - return err -} - -// runTerraformJSON runs the configured Terraform CLI executable with the given -// arguments and tries to decode its stdout into the given target value (which -// must be a non-nil pointer) as JSON. -func (wd *WorkingDir) runTerraformJSON(target interface{}, args ...string) error { - allArgs := []string{"terraform"} - allArgs = append(allArgs, args...) - - env := getTerraformEnv() - - var outBuf bytes.Buffer - var errBuf strings.Builder - - cmd := &exec.Cmd{ - Path: wd.h.TerraformExecPath(), - Args: allArgs, - Dir: wd.baseDir, - Stderr: &errBuf, - Stdout: &outBuf, - Env: env, - } - err := cmd.Run() - if err != nil { - if tErr, ok := err.(*exec.ExitError); ok { - err = fmt.Errorf("terraform failed: %s\n\nstderr:\n%s", tErr.ProcessState.String(), errBuf.String()) - } - return err - } - - return json.Unmarshal(outBuf.Bytes(), target) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/util.go b/vendor/github.com/hashicorp/terraform-plugin-test/util.go deleted file mode 100644 index 0732c82d197..00000000000 --- a/vendor/github.com/hashicorp/terraform-plugin-test/util.go +++ /dev/null @@ -1,55 +0,0 @@ -package tftest - -import ( - "os" - "path/filepath" -) - -func symlinkFile(src string, dest string) (err error) { - err = os.Symlink(src, dest) - if err == nil { - srcInfo, err := os.Stat(src) - if err != nil { - err = os.Chmod(dest, srcInfo.Mode()) - } - } - - return -} - -// symlinkDir is a simplistic function for recursively symlinking all files in a directory to a new path. -// It is intended only for limited internal use and does not cover all edge cases. -func symlinkDir(srcDir string, destDir string) (err error) { - srcInfo, err := os.Stat(srcDir) - if err != nil { - return err - } - - err = os.MkdirAll(destDir, srcInfo.Mode()) - if err != nil { - return err - } - - directory, _ := os.Open(srcDir) - defer directory.Close() - objects, err := directory.Readdir(-1) - - for _, obj := range objects { - srcPath := filepath.Join(srcDir, obj.Name()) - destPath := filepath.Join(destDir, obj.Name()) - - if obj.IsDir() { - err = symlinkDir(srcPath, destPath) - if err != nil { - return err - } - } else { - err = symlinkFile(srcPath, destPath) - if err != nil { - return err - } - } - - } - return -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/v2/CHANGELOG.md b/vendor/github.com/hashicorp/terraform-plugin-test/v2/CHANGELOG.md new file mode 100644 index 00000000000..b1ed7213124 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-test/v2/CHANGELOG.md @@ -0,0 +1,30 @@ +# 2.0.0 (August 10, 2020) + +FEATURES: + + - Simplified API signatures to reflect no longer needing provider name ([#32](https://github.com/hashicorp/terraform-plugin-test/pull/32)) + - Implement SavedPlanStdout which captures a non-json stdout run of `terraform show` of a planfile ([#34](https://github.com/hashicorp/terraform-plugin-test/pull/34)) + +# 1.4.4 (July 10, 2020) + +BUG FIXES: + + - Fix Windows bug in versions of Terraform below 0.13.0-beta2 ([#30](https://github.com/hashicorp/terraform-plugin-test/pull/30)) + +# 1.4.3 (July 7, 2020) + +DEPENDENCIES: + + - `github.com/hashicorp/go-getter@v1.4.0` ([#29](https://github.com/hashicorp/terraform-plugin-test/pull/29)) + +# 1.4.2 (July 7, 2020) + +DEPENDENCIES: + + - `github.com/hashicorp/terraform-exec@v0.1.1` ([#28](https://github.com/hashicorp/terraform-plugin-test/pull/28)) + +# 1.4.1 (July 7, 2020) + +BUG FIXES: + + - Fix auto-install Terraform feature ([#26](https://github.com/hashicorp/terraform-plugin-test/pull/26)) diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/LICENSE b/vendor/github.com/hashicorp/terraform-plugin-test/v2/LICENSE similarity index 100% rename from vendor/github.com/hashicorp/terraform-config-inspect/LICENSE rename to vendor/github.com/hashicorp/terraform-plugin-test/v2/LICENSE diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/README.md b/vendor/github.com/hashicorp/terraform-plugin-test/v2/README.md similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-test/README.md rename to vendor/github.com/hashicorp/terraform-plugin-test/v2/README.md diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/v2/config.go b/vendor/github.com/hashicorp/terraform-plugin-test/v2/config.go new file mode 100644 index 00000000000..9f72c3e8af8 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-test/v2/config.go @@ -0,0 +1,53 @@ +package tftest + +import ( + "fmt" + "io/ioutil" + "os" + + "github.com/hashicorp/terraform-exec/tfinstall" +) + +// Config is used to configure the test helper. In most normal test programs +// the configuration is discovered automatically by an Init* function using +// DiscoverConfig, but this is exposed so that more complex scenarios can be +// implemented by direct configuration. +type Config struct { + SourceDir string + TerraformExec string + execTempDir string + PreviousPluginExec string +} + +// DiscoverConfig uses environment variables and other means to automatically +// discover a reasonable test helper configuration. +func DiscoverConfig(sourceDir string) (*Config, error) { + tfVersion := os.Getenv("TF_ACC_TERRAFORM_VERSION") + tfPath := os.Getenv("TF_ACC_TERRAFORM_PATH") + + tempDir := os.Getenv("TF_ACC_TEMP_DIR") + tfDir, err := ioutil.TempDir(tempDir, "tftest-terraform") + if err != nil { + return nil, fmt.Errorf("failed to create temp dir: %w", err) + } + + finders := []tfinstall.ExecPathFinder{} + switch { + case tfPath != "": + finders = append(finders, tfinstall.ExactPath(tfPath)) + case tfVersion != "": + finders = append(finders, tfinstall.ExactVersion(tfVersion, tfDir)) + default: + finders = append(finders, tfinstall.LookPath(), tfinstall.LatestVersion(tfDir, true)) + } + tfExec, err := tfinstall.Find(finders...) + if err != nil { + return nil, err + } + + return &Config{ + SourceDir: sourceDir, + TerraformExec: tfExec, + execTempDir: tfDir, + }, nil +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/doc.go b/vendor/github.com/hashicorp/terraform-plugin-test/v2/doc.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-test/doc.go rename to vendor/github.com/hashicorp/terraform-plugin-test/v2/doc.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/v2/go.mod b/vendor/github.com/hashicorp/terraform-plugin-test/v2/go.mod new file mode 100644 index 00000000000..857517efb53 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-test/v2/go.mod @@ -0,0 +1,9 @@ +module github.com/hashicorp/terraform-plugin-test/v2 + +go 1.12 + +require ( + github.com/hashicorp/go-getter v1.4.0 + github.com/hashicorp/terraform-exec v0.3.0 + github.com/hashicorp/terraform-json v0.5.0 +) diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/v2/go.sum b/vendor/github.com/hashicorp/terraform-plugin-test/v2/go.sum new file mode 100644 index 00000000000..3151061c0c1 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-test/v2/go.sum @@ -0,0 +1,177 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1 h1:lRi0CHyU+ytlvylOlFKKq0af6JncuyoRh1J+QJBqQx0= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= +github.com/aws/aws-sdk-go v1.15.78 h1:LaXy6lWR0YK7LKyuU0QWy2ws/LWTPfYV/UgfiBu4tvY= +github.com/aws/aws-sdk-go v1.15.78/go.mod h1:E3/ieXAlvM0XWO57iftYVDLLvQ824smPP3ATZkfNZeM= +github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= +github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= +github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/hashicorp/go-checkpoint v0.5.0 h1:MFYpPZCnQqQTE18jFwSII6eUQrD/oxMFp3mlgcqk5mU= +github.com/hashicorp/go-checkpoint v0.5.0/go.mod h1:7nfLNL10NsxqO4iWuW6tWW0HjZuDrwkBuEQsVcpCOgg= +github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-getter v1.4.0 h1:ENHNi8494porjD0ZhIrjlAHnveSFhY7hvOJrV/fsKkw= +github.com/hashicorp/go-getter v1.4.0/go.mod h1:7qxyCd8rBfcShwsvxgIguu4KbS3l8bUCwg2Umn7RjeY= +github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo= +github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= +github.com/hashicorp/go-uuid v1.0.0 h1:RS8zrF7PhGwyNPOtxSClXXj9HA8feRnJzgnI1RJCSnM= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.1.0 h1:bPIoEKD27tNdebFGGxxYwcL4nepeY4j1QP23PFRGzg0= +github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/terraform-exec v0.3.0 h1:5WLBsnv9BoEUGlHJZETROZZxw+qO3/TFQEh6JMP2uaY= +github.com/hashicorp/terraform-exec v0.3.0/go.mod h1:yKWvMPtkTaHpeAmllw+1qdHZ7E5u+pAZ+x8e2jQF6gM= +github.com/hashicorp/terraform-json v0.5.0 h1:7TV3/F3y7QVSuN4r9BEXqnWqrAyeOtON8f0wvREtyzs= +github.com/hashicorp/terraform-json v0.5.0/go.mod h1:eAbqb4w0pSlRmdvl8fOyHAi/+8jnkVYN28gJkSJrLhU= +github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8 h1:12VvqtR6Aowv3l/EQUlocDHW2Cp4G9WJVH7uyH8QFJE= +github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= +github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-testing-interface v1.0.0 h1:fzU/JVNcaqHQEcVFAKeR41fkiLdIPrefOvVG1VZ96U0= +github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/ulikunitz/xz v0.5.5 h1:pFrO0lVpTBXLpYw+pnLj6TbvHuyjXMfjGeCwSqCVwok= +github.com/ulikunitz/xz v0.5.5/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= +github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= +github.com/zclconf/go-cty v1.2.1 h1:vGMsygfmeCl4Xb6OA5U5XVAaQZ69FvoG7X2jUtQujb8= +github.com/zclconf/go-cty v1.2.1/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0 h1:C9hSCOW830chIVkdja34wa6Ky+IzWllkUinR+BtRZd4= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5 h1:58fnuSXlxZmFdJyvtTFVmVhcMLU6v5fEb/ok4wyqtNU= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0 h1:HyfiK1WMnHj5FXFXatD+Qs1A/xC2Run6RzeW1SyHxpc= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0 h1:jbyannxz0XFD3zdjgrSUsaJbgpH4eTrkdhRChkHPfO8= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1 h1:QzqyMA1tlu6CgqCDUtU9V+ZKhLFT2dkJuANu5QaxI3I= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.1 h1:j6XxA85m/6txkUCHvzlV5f+HBNl/1r5cZ2A/3IEFOO8= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/cheggaaa/pb.v1 v1.0.27/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/guard.go b/vendor/github.com/hashicorp/terraform-plugin-test/v2/guard.go similarity index 84% rename from vendor/github.com/hashicorp/terraform-plugin-test/guard.go rename to vendor/github.com/hashicorp/terraform-plugin-test/v2/guard.go index a8fe5630346..819937b38e8 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-test/guard.go +++ b/vendor/github.com/hashicorp/terraform-plugin-test/v2/guard.go @@ -50,22 +50,6 @@ func LongTest(t TestControl) { } } -// RequirePreviousVersion is a test guard that will produce a log and call -// SkipNow on the given TestControl if the receiving Helper does not have a -// previous plugin version to test against. -// -// Call this immediately at the start of any "upgrade test" that expects to -// be able to run some operations with a previous version of the plugin before -// "upgrading" to the current version under test to continue with other -// operations. -func (h *Helper) RequirePreviousVersion(t TestControl) { - t.Helper() - if !h.HasPreviousVersion() { - t.Log("no previous plugin version available") - t.SkipNow() - } -} - // TestControl is an interface requiring a subset of *testing.T which is used // by the test guards and helpers in this package. Most callers can simply // pass their *testing.T value here, but the interface allows other diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/v2/helper.go b/vendor/github.com/hashicorp/terraform-plugin-test/v2/helper.go new file mode 100644 index 00000000000..a9878899a96 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-test/v2/helper.go @@ -0,0 +1,222 @@ +package tftest + +import ( + "fmt" + "io/ioutil" + "os" + "path/filepath" + "runtime" + "strings" + + getter "github.com/hashicorp/go-getter" +) + +const subprocessCurrentSigil = "4acd63807899403ca4859f5bb948d2c6" +const subprocessPreviousSigil = "2279afb8cf71423996be1fd65d32f13b" + +// AutoInitProviderHelper is the main entrypoint for testing provider plugins +// using this package. It is intended to be called during TestMain to prepare +// for provider testing. +// +// AutoInitProviderHelper will discover the location of a current Terraform CLI +// executable to test against, detect whether a prior version of the plugin is +// available for upgrade tests, and then will return an object containing the +// results of that initialization which can then be stored in a global variable +// for use in other tests. +func AutoInitProviderHelper(sourceDir string) *Helper { + helper, err := AutoInitHelper(sourceDir) + if err != nil { + fmt.Fprintf(os.Stderr, "cannot run Terraform provider tests: %s\n", err) + os.Exit(1) + } + return helper +} + +// Helper is intended as a per-package singleton created in TestMain which +// other tests in a package can use to create Terraform execution contexts +type Helper struct { + baseDir string + + // sourceDir is the dir containing the provider source code, needed + // for tests that use fixture files. + sourceDir string + terraformExec string + + // execTempDir is created during DiscoverConfig to store any downloaded + // binaries + execTempDir string +} + +// AutoInitHelper uses the auto-discovery behavior of DiscoverConfig to prepare +// a configuration and then calls InitHelper with it. This is a convenient +// way to get the standard init behavior based on environment variables, and +// callers should use this unless they have an unusual requirement that calls +// for constructing a config in a different way. +func AutoInitHelper(sourceDir string) (*Helper, error) { + config, err := DiscoverConfig(sourceDir) + if err != nil { + return nil, err + } + + return InitHelper(config) +} + +// InitHelper prepares a testing helper with the given configuration. +// +// For most callers it is sufficient to call AutoInitHelper instead, which +// will construct a configuration automatically based on certain environment +// variables. +// +// If this function returns an error then it may have left some temporary files +// behind in the system's temporary directory. There is currently no way to +// automatically clean those up. +func InitHelper(config *Config) (*Helper, error) { + tempDir := os.Getenv("TF_ACC_TEMP_DIR") + baseDir, err := ioutil.TempDir(tempDir, "tftest") + if err != nil { + return nil, fmt.Errorf("failed to create temporary directory for test helper: %s", err) + } + + return &Helper{ + baseDir: baseDir, + sourceDir: config.SourceDir, + terraformExec: config.TerraformExec, + execTempDir: config.execTempDir, + }, nil +} + +// symlinkAuxiliaryProviders discovers auxiliary provider binaries, used in +// multi-provider tests, and symlinks them to the plugin directory. +// +// Auxiliary provider binaries should be included in the provider source code +// directory, under the path terraform.d/plugins/$GOOS_$GOARCH/provider-name. +// +// The environment variable TF_ACC_PROVIDER_ROOT_DIR must be set to the path of +// the provider source code directory root in order to use this feature. +func symlinkAuxiliaryProviders(pluginDir string) error { + providerRootDir := os.Getenv("TF_ACC_PROVIDER_ROOT_DIR") + if providerRootDir == "" { + // common case; assume intentional and do not log + return nil + } + + _, err := os.Stat(filepath.Join(providerRootDir, "terraform.d", "plugins")) + if os.IsNotExist(err) { + fmt.Printf("No terraform.d/plugins directory found: continuing. Unset TF_ACC_PROVIDER_ROOT_DIR or supply provider binaries in terraform.d/plugins/$GOOS_$GOARCH to disable this message.") + return nil + } else if err != nil { + return fmt.Errorf("Unexpected error: %s", err) + } + + auxiliaryProviderDir := filepath.Join(providerRootDir, "terraform.d", "plugins", runtime.GOOS+"_"+runtime.GOARCH) + + // If we can't os.Stat() terraform.d/plugins/$GOOS_$GOARCH, however, + // assume the omission was unintentional, and error. + _, err = os.Stat(auxiliaryProviderDir) + if os.IsNotExist(err) { + return fmt.Errorf("error finding auxiliary provider dir %s: %s", auxiliaryProviderDir, err) + } else if err != nil { + return fmt.Errorf("Unexpected error: %s", err) + } + + // now find all the providers in that dir and symlink them to the plugin dir + providers, err := ioutil.ReadDir(auxiliaryProviderDir) + if err != nil { + return fmt.Errorf("error reading auxiliary providers: %s", err) + } + + zipDecompressor := new(getter.ZipDecompressor) + + for _, provider := range providers { + filename := provider.Name() + filenameExt := filepath.Ext(filename) + name := strings.TrimSuffix(filename, filenameExt) + path := filepath.Join(auxiliaryProviderDir, name) + symlinkPath := filepath.Join(pluginDir, name) + + // exit early if we have already symlinked this provider + _, err := os.Stat(symlinkPath) + if err == nil { + continue + } + + // if filename ends in .zip, assume it is a zip and extract it + // otherwise assume it is a provider binary + if filenameExt == ".zip" { + _, err = os.Stat(path) + if os.IsNotExist(err) { + zipDecompressor.Decompress(path, filepath.Join(auxiliaryProviderDir, filename), false) + } else if err != nil { + return fmt.Errorf("Unexpected error: %s", err) + } + } + + err = symlinkFile(path, symlinkPath) + if err != nil { + return fmt.Errorf("error symlinking auxiliary provider %s: %s", name, err) + } + } + + return nil +} + +// Close cleans up temporary files and directories created to support this +// helper, returning an error if any of the cleanup fails. +// +// Call this before returning from TestMain to minimize the amount of detritus +// left behind in the filesystem after the tests complete. +func (h *Helper) Close() error { + if h.execTempDir != "" { + err := os.RemoveAll(h.execTempDir) + if err != nil { + return err + } + } + return os.RemoveAll(h.baseDir) +} + +// NewWorkingDir creates a new working directory for use in the implementation +// of a single test, returning a WorkingDir object representing that directory. +// +// If the working directory object is not itself closed by the time the test +// program exits, the Close method on the helper itself will attempt to +// delete it. +func (h *Helper) NewWorkingDir() (*WorkingDir, error) { + dir, err := ioutil.TempDir(h.baseDir, "work") + if err != nil { + return nil, err + } + + // symlink the provider source files into the base directory + err = symlinkDirectoriesOnly(h.sourceDir, dir) + if err != nil { + return nil, err + } + + return &WorkingDir{ + h: h, + baseArgs: []string{"-no-color"}, + baseDir: dir, + }, nil +} + +// RequireNewWorkingDir is a variant of NewWorkingDir that takes a TestControl +// object and will immediately fail the running test if the creation of the +// working directory fails. +func (h *Helper) RequireNewWorkingDir(t TestControl) *WorkingDir { + t.Helper() + + wd, err := h.NewWorkingDir() + if err != nil { + t := testingT{t} + t.Fatalf("failed to create new working directory: %s", err) + return nil + } + return wd +} + +// TerraformExecPath returns the location of the Terraform CLI executable that +// should be used when running tests. +func (h *Helper) TerraformExecPath() string { + return h.terraformExec +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/plugin.go b/vendor/github.com/hashicorp/terraform-plugin-test/v2/plugin.go similarity index 100% rename from vendor/github.com/hashicorp/terraform-plugin-test/plugin.go rename to vendor/github.com/hashicorp/terraform-plugin-test/v2/plugin.go diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/v2/terraform.go b/vendor/github.com/hashicorp/terraform-plugin-test/v2/terraform.go new file mode 100644 index 00000000000..124c9e44c1d --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-test/v2/terraform.go @@ -0,0 +1,106 @@ +package tftest + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "os" + "os/exec" + "strings" +) + +// getTerraformEnv returns the appropriate Env for the Terraform command. +func (wd *WorkingDir) getTerraformEnv() []string { + var env []string + for _, e := range os.Environ() { + env = append(env, e) + } + + env = append(env, "TF_DISABLE_PLUGIN_TLS=1") + env = append(env, "TF_SKIP_PROVIDER_VERIFY=1") + + // FIXME: Ideally in testing.Verbose mode we'd turn on Terraform DEBUG + // logging, perhaps redirected to a separate fd other than stderr to avoid + // polluting it, and then propagate the log lines out into t.Log so that + // they are visible to the person running the test. Currently though, + // Terraform CLI is able to send logs only to either an on-disk file or + // to stderr. + env = append(env, "TF_LOG=") // so logging can't pollute our stderr output + env = append(env, "TF_INPUT=0") + + // don't propagate the magic cookie + env = append(env, "TF_PLUGIN_MAGIC_COOKIE=") + + if p := os.Getenv("TF_ACC_LOG_PATH"); p != "" { + env = append(env, "TF_LOG=TRACE") + env = append(env, "TF_LOG_PATH="+p) + } + + for k, v := range wd.env { + env = append(env, k+"="+v) + } + return env +} + +// runTerraform runs the configured Terraform CLI executable with the given +// arguments, returning an error if it produces a non-successful exit status. +// if captureStdout is non-nil, the process will write it's stdout to the +// provided io.Writer +func (wd *WorkingDir) runTerraform(captureStdout io.Writer, args ...string) error { + allArgs := []string{"terraform"} + allArgs = append(allArgs, args...) + + env := wd.getTerraformEnv() + + var errBuf strings.Builder + + cmd := &exec.Cmd{ + Path: wd.h.TerraformExecPath(), + Args: allArgs, + Dir: wd.baseDir, + Stderr: &errBuf, + Env: env, + } + + if captureStdout != nil { + cmd.Stdout = captureStdout + } + + err := cmd.Run() + if tErr, ok := err.(*exec.ExitError); ok { + err = fmt.Errorf("terraform failed: %s\n\nstderr:\n%s", tErr.ProcessState.String(), errBuf.String()) + } + return err +} + +// runTerraformJSON runs the configured Terraform CLI executable with the given +// arguments and tries to decode its stdout into the given target value (which +// must be a non-nil pointer) as JSON. +func (wd *WorkingDir) runTerraformJSON(target interface{}, args ...string) error { + allArgs := []string{"terraform"} + allArgs = append(allArgs, args...) + + env := wd.getTerraformEnv() + + var outBuf bytes.Buffer + var errBuf strings.Builder + + cmd := &exec.Cmd{ + Path: wd.h.TerraformExecPath(), + Args: allArgs, + Dir: wd.baseDir, + Stderr: &errBuf, + Stdout: &outBuf, + Env: env, + } + err := cmd.Run() + if err != nil { + if tErr, ok := err.(*exec.ExitError); ok { + err = fmt.Errorf("terraform failed: %s\n\nstderr:\n%s", tErr.ProcessState.String(), errBuf.String()) + } + return err + } + + return json.Unmarshal(outBuf.Bytes(), target) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/v2/util.go b/vendor/github.com/hashicorp/terraform-plugin-test/v2/util.go new file mode 100644 index 00000000000..57bc84f2dcc --- /dev/null +++ b/vendor/github.com/hashicorp/terraform-plugin-test/v2/util.go @@ -0,0 +1,95 @@ +package tftest + +import ( + "os" + "path/filepath" +) + +func symlinkFile(src string, dest string) (err error) { + err = os.Symlink(src, dest) + if err == nil { + srcInfo, err := os.Stat(src) + if err != nil { + err = os.Chmod(dest, srcInfo.Mode()) + } + } + + return +} + +// symlinkDir is a simplistic function for recursively symlinking all files in a directory to a new path. +// It is intended only for limited internal use and does not cover all edge cases. +func symlinkDir(srcDir string, destDir string) (err error) { + srcInfo, err := os.Stat(srcDir) + if err != nil { + return err + } + + err = os.MkdirAll(destDir, srcInfo.Mode()) + if err != nil { + return err + } + + directory, _ := os.Open(srcDir) + defer directory.Close() + objects, err := directory.Readdir(-1) + + for _, obj := range objects { + srcPath := filepath.Join(srcDir, obj.Name()) + destPath := filepath.Join(destDir, obj.Name()) + + if obj.IsDir() { + err = symlinkDir(srcPath, destPath) + if err != nil { + return err + } + } else { + err = symlinkFile(srcPath, destPath) + if err != nil { + return err + } + } + + } + return +} + +// symlinkDirectoriesOnly finds only the first-level child directories in srcDir +// and symlinks them into destDir. +// Unlike symlinkDir, this is done non-recursively in order to limit the number +// of file descriptors used. +func symlinkDirectoriesOnly(srcDir string, destDir string) (err error) { + srcInfo, err := os.Stat(srcDir) + if err != nil { + return err + } + + err = os.MkdirAll(destDir, srcInfo.Mode()) + if err != nil { + return err + } + + directory, err := os.Open(srcDir) + if err != nil { + return err + } + defer directory.Close() + objects, err := directory.Readdir(-1) + if err != nil { + return err + } + + for _, obj := range objects { + srcPath := filepath.Join(srcDir, obj.Name()) + destPath := filepath.Join(destDir, obj.Name()) + + if obj.IsDir() { + err = symlinkFile(srcPath, destPath) + if err != nil { + return err + } + } + + } + return +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-test/working_dir.go b/vendor/github.com/hashicorp/terraform-plugin-test/v2/working_dir.go similarity index 81% rename from vendor/github.com/hashicorp/terraform-plugin-test/working_dir.go rename to vendor/github.com/hashicorp/terraform-plugin-test/v2/working_dir.go index 7f64706f120..e9179235996 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-test/working_dir.go +++ b/vendor/github.com/hashicorp/terraform-plugin-test/v2/working_dir.go @@ -1,6 +1,7 @@ package tftest import ( + "bytes" "fmt" "io/ioutil" "os" @@ -24,6 +25,8 @@ type WorkingDir struct { // configDir contains the singular config file generated for each test configDir string + + env map[string]string } // Close deletes the directories and files created to represent the receiving @@ -33,6 +36,32 @@ func (wd *WorkingDir) Close() error { return os.RemoveAll(wd.baseDir) } +// Setenv sets an environment variable on the WorkingDir. +func (wd *WorkingDir) Setenv(envVar, val string) { + if wd.env == nil { + wd.env = map[string]string{} + } + wd.env[envVar] = val +} + +// Unsetenv removes an environment variable from the WorkingDir. +func (wd *WorkingDir) Unsetenv(envVar string) { + delete(wd.env, envVar) +} + +// GetHelper returns the Helper set on the WorkingDir. +func (wd *WorkingDir) GetHelper() *Helper { + return wd.h +} + +func (wd *WorkingDir) relativeConfigDir() (string, error) { + relPath, err := filepath.Rel(wd.baseDir, wd.configDir) + if err != nil { + return "", fmt.Errorf("Error determining relative path of configuration directory: %w", err) + } + return relPath, nil +} + // SetConfig sets a new configuration for the working directory. // // This must be called at least once before any call to Init, Plan, Apply, or @@ -113,10 +142,10 @@ func (wd *WorkingDir) RequireClearPlan(t TestControl) { } } -func (wd *WorkingDir) init(pluginDir string) error { - args := []string{"init"} +func (wd *WorkingDir) init() error { + args := []string{"init", wd.configDir} args = append(args, wd.baseArgs...) - return wd.runTerraform(args...) + return wd.runTerraform(nil, args...) } // Init runs "terraform init" for the given working directory, forcing Terraform @@ -125,7 +154,7 @@ func (wd *WorkingDir) Init() error { if wd.configDir == "" { return fmt.Errorf("must call SetConfig before Init") } - return wd.init(wd.h.PluginDir()) + return wd.init() } // RequireInit is a variant of Init that will fail the test via the given @@ -138,29 +167,6 @@ func (wd *WorkingDir) RequireInit(t TestControl) { } } -// InitPrevious runs "terraform init" for the given working directory, forcing -// Terraform to use the previous version of the plugin under test. -// -// This method will panic if no previous plugin version is available. Use -// HasPreviousVersion or RequirePreviousVersion on the test helper singleton -// to check this first. -func (wd *WorkingDir) InitPrevious() error { - if wd.configDir == "" { - return fmt.Errorf("must call SetConfig before InitPrevious") - } - return wd.init(wd.h.PreviousPluginDir()) -} - -// RequireInitPrevious is a variant of InitPrevious that will fail the test -// via the given TestControl if init fails. -func (wd *WorkingDir) RequireInitPrevious(t TestControl) { - t.Helper() - if err := wd.InitPrevious(); err != nil { - t := testingT{t} - t.Fatalf("init failed: %s", err) - } -} - func (wd *WorkingDir) planFilename() string { return filepath.Join(wd.baseDir, "tfplan") } @@ -171,7 +177,7 @@ func (wd *WorkingDir) CreatePlan() error { args := []string{"plan", "-refresh=false"} args = append(args, wd.baseArgs...) args = append(args, "-out=tfplan", wd.configDir) - return wd.runTerraform(args...) + return wd.runTerraform(nil, args...) } // RequireCreatePlan is a variant of CreatePlan that will fail the test via @@ -195,11 +201,19 @@ func (wd *WorkingDir) Apply() error { if wd.HasSavedPlan() { args = append(args, "tfplan") } else { + // we need to use a relative config dir here or we get an + // error about Terraform not having any configuration. See + // https://github.com/hashicorp/terraform-plugin-sdk/issues/495 + // for more info. + configDir, err := wd.relativeConfigDir() + if err != nil { + return err + } args = append(args, "-auto-approve") - args = append(args, wd.configDir) + args = append(args, configDir) } - return wd.runTerraform(args...) + return wd.runTerraform(nil, args...) } // RequireApply is a variant of Apply that will fail the test via @@ -222,7 +236,7 @@ func (wd *WorkingDir) Destroy() error { args = append(args, wd.baseArgs...) args = append(args, "-auto-approve", wd.configDir) - return wd.runTerraform(args...) + return wd.runTerraform(nil, args...) } // RequireDestroy is a variant of Destroy that will fail the test via @@ -281,6 +295,41 @@ func (wd *WorkingDir) RequireSavedPlan(t TestControl) *tfjson.Plan { return ret } +// SavedPlanStdout returns a stdout capture of the current saved plan file, if any. +// +// If no plan is saved or if the plan file cannot be read, SavedPlanStdout returns +// an error. +func (wd *WorkingDir) SavedPlanStdout() (string, error) { + if !wd.HasSavedPlan() { + return "", fmt.Errorf("there is no current saved plan") + } + + var ret bytes.Buffer + + args := []string{"show"} + args = append(args, wd.baseArgs...) + args = append(args, wd.planFilename()) + + err := wd.runTerraform(&ret, args...) + if err != nil { + return "", err + } + + return ret.String(), nil +} + +// RequireSavedPlanStdout is a variant of SavedPlanStdout that will fail the test via +// the given TestControl if the plan cannot be read. +func (wd *WorkingDir) RequireSavedPlanStdout(t TestControl) string { + t.Helper() + ret, err := wd.SavedPlanStdout() + if err != nil { + t := testingT{t} + t.Fatalf("failed to read saved plan: %s", err) + } + return ret +} + // State returns an object describing the current state. // // If the state cannot be read, State returns an error. @@ -316,7 +365,7 @@ func (wd *WorkingDir) Import(resource, id string) error { args := []string{"import"} args = append(args, wd.baseArgs...) args = append(args, "-config="+wd.configDir, resource, id) - return wd.runTerraform(args...) + return wd.runTerraform(nil, args...) } // RequireImport is a variant of Import that will fail the test via @@ -335,7 +384,7 @@ func (wd *WorkingDir) Refresh() error { args = append(args, wd.baseArgs...) args = append(args, "-state="+filepath.Join(wd.baseDir, "terraform.tfstate")) args = append(args, wd.configDir) - return wd.runTerraform(args...) + return wd.runTerraform(nil, args...) } // RequireRefresh is a variant of Refresh that will fail the test via diff --git a/vendor/github.com/hashicorp/terraform-svchost/auth/cache.go b/vendor/github.com/hashicorp/terraform-svchost/auth/cache.go deleted file mode 100644 index 0dae567db97..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/auth/cache.go +++ /dev/null @@ -1,61 +0,0 @@ -package auth - -import ( - "github.com/hashicorp/terraform-svchost" -) - -// CachingCredentialsSource creates a new credentials source that wraps another -// and caches its results in memory, on a per-hostname basis. -// -// No means is provided for expiration of cached credentials, so a caching -// credentials source should have a limited lifetime (one Terraform operation, -// for example) to ensure that time-limited credentials don't expire before -// their cache entries do. -func CachingCredentialsSource(source CredentialsSource) CredentialsSource { - return &cachingCredentialsSource{ - source: source, - cache: map[svchost.Hostname]HostCredentials{}, - } -} - -type cachingCredentialsSource struct { - source CredentialsSource - cache map[svchost.Hostname]HostCredentials -} - -// ForHost passes the given hostname on to the wrapped credentials source and -// caches the result to return for future requests with the same hostname. -// -// Both credentials and non-credentials (nil) responses are cached. -// -// No cache entry is created if the wrapped source returns an error, to allow -// the caller to retry the failing operation. -func (s *cachingCredentialsSource) ForHost(host svchost.Hostname) (HostCredentials, error) { - if cache, cached := s.cache[host]; cached { - return cache, nil - } - - result, err := s.source.ForHost(host) - if err != nil { - return result, err - } - - s.cache[host] = result - return result, nil -} - -func (s *cachingCredentialsSource) StoreForHost(host svchost.Hostname, credentials HostCredentialsWritable) error { - // We'll delete the cache entry even if the store fails, since that just - // means that the next read will go to the real store and get a chance to - // see which object (old or new) is actually present. - delete(s.cache, host) - return s.source.StoreForHost(host, credentials) -} - -func (s *cachingCredentialsSource) ForgetForHost(host svchost.Hostname) error { - // We'll delete the cache entry even if the store fails, since that just - // means that the next read will go to the real store and get a chance to - // see if the object is still present. - delete(s.cache, host) - return s.source.ForgetForHost(host) -} diff --git a/vendor/github.com/hashicorp/terraform-svchost/auth/credentials.go b/vendor/github.com/hashicorp/terraform-svchost/auth/credentials.go deleted file mode 100644 index 36441cd115f..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/auth/credentials.go +++ /dev/null @@ -1,118 +0,0 @@ -// Package auth contains types and functions to manage authentication -// credentials for service hosts. -package auth - -import ( - "fmt" - "net/http" - - "github.com/zclconf/go-cty/cty" - - "github.com/hashicorp/terraform-svchost" -) - -// Credentials is a list of CredentialsSource objects that can be tried in -// turn until one returns credentials for a host, or one returns an error. -// -// A Credentials is itself a CredentialsSource, wrapping its members. -// In principle one CredentialsSource can be nested inside another, though -// there is no good reason to do so. -// -// The write operations on a Credentials are tried only on the first object, -// under the assumption that it is the primary store. -type Credentials []CredentialsSource - -// NoCredentials is an empty CredentialsSource that always returns nil -// when asked for credentials. -var NoCredentials CredentialsSource = Credentials{} - -// A CredentialsSource is an object that may be able to provide credentials -// for a given host. -// -// Credentials lookups are not guaranteed to be concurrency-safe. Callers -// using these facilities in concurrent code must use external concurrency -// primitives to prevent race conditions. -type CredentialsSource interface { - // ForHost returns a non-nil HostCredentials if the source has credentials - // available for the host, and a nil HostCredentials if it does not. - // - // If an error is returned, progress through a list of CredentialsSources - // is halted and the error is returned to the user. - ForHost(host svchost.Hostname) (HostCredentials, error) - - // StoreForHost takes a HostCredentialsWritable and saves it as the - // credentials for the given host. - // - // If credentials are already stored for the given host, it will try to - // replace those credentials but may produce an error if such replacement - // is not possible. - StoreForHost(host svchost.Hostname, credentials HostCredentialsWritable) error - - // ForgetForHost discards any stored credentials for the given host. It - // does nothing and returns successfully if no credentials are saved - // for that host. - ForgetForHost(host svchost.Hostname) error -} - -// HostCredentials represents a single set of credentials for a particular -// host. -type HostCredentials interface { - // PrepareRequest modifies the given request in-place to apply the - // receiving credentials. The usual behavior of this method is to - // add some sort of Authorization header to the request. - PrepareRequest(req *http.Request) - - // Token returns the authentication token. - Token() string -} - -// HostCredentialsWritable is an extension of HostCredentials for credentials -// objects that can be serialized as a JSON-compatible object value for -// storage. -type HostCredentialsWritable interface { - HostCredentials - - // ToStore returns a cty.Value, always of an object type, - // representing data that can be serialized to represent this object - // in persistent storage. - // - // The resulting value may uses only cty values that can be accepted - // by the cty JSON encoder, though the caller may elect to instead store - // it in some other format that has a JSON-compatible type system. - ToStore() cty.Value -} - -// ForHost iterates over the contained CredentialsSource objects and -// tries to obtain credentials for the given host from each one in turn. -// -// If any source returns either a non-nil HostCredentials or a non-nil error -// then this result is returned. Otherwise, the result is nil, nil. -func (c Credentials) ForHost(host svchost.Hostname) (HostCredentials, error) { - for _, source := range c { - creds, err := source.ForHost(host) - if creds != nil || err != nil { - return creds, err - } - } - return nil, nil -} - -// StoreForHost passes the given arguments to the same operation on the -// first CredentialsSource in the receiver. -func (c Credentials) StoreForHost(host svchost.Hostname, credentials HostCredentialsWritable) error { - if len(c) == 0 { - return fmt.Errorf("no credentials store is available") - } - - return c[0].StoreForHost(host, credentials) -} - -// ForgetForHost passes the given arguments to the same operation on the -// first CredentialsSource in the receiver. -func (c Credentials) ForgetForHost(host svchost.Hostname) error { - if len(c) == 0 { - return fmt.Errorf("no credentials store is available") - } - - return c[0].ForgetForHost(host) -} diff --git a/vendor/github.com/hashicorp/terraform-svchost/auth/from_map.go b/vendor/github.com/hashicorp/terraform-svchost/auth/from_map.go deleted file mode 100644 index 7198c6744b3..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/auth/from_map.go +++ /dev/null @@ -1,48 +0,0 @@ -package auth - -import ( - "github.com/zclconf/go-cty/cty" -) - -// HostCredentialsFromMap converts a map of key-value pairs from a credentials -// definition provided by the user (e.g. in a config file, or via a credentials -// helper) into a HostCredentials object if possible, or returns nil if -// no credentials could be extracted from the map. -// -// This function ignores map keys it is unfamiliar with, to allow for future -// expansion of the credentials map format for new credential types. -func HostCredentialsFromMap(m map[string]interface{}) HostCredentials { - if m == nil { - return nil - } - if token, ok := m["token"].(string); ok { - return HostCredentialsToken(token) - } - return nil -} - -// HostCredentialsFromObject converts a cty.Value of an object type into a -// HostCredentials object if possible, or returns nil if no credentials could -// be extracted from the map. -// -// This function ignores object attributes it is unfamiliar with, to allow for -// future expansion of the credentials object structure for new credential types. -// -// If the given value is not of an object type, this function will panic. -func HostCredentialsFromObject(obj cty.Value) HostCredentials { - if !obj.Type().HasAttribute("token") { - return nil - } - - tokenV := obj.GetAttr("token") - if tokenV.IsNull() || !tokenV.IsKnown() { - return nil - } - if !cty.String.Equals(tokenV.Type()) { - // Weird, but maybe some future Terraform version accepts an object - // here for some reason, so we'll be resilient. - return nil - } - - return HostCredentialsToken(tokenV.AsString()) -} diff --git a/vendor/github.com/hashicorp/terraform-svchost/auth/helper_program.go b/vendor/github.com/hashicorp/terraform-svchost/auth/helper_program.go deleted file mode 100644 index 76505f20991..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/auth/helper_program.go +++ /dev/null @@ -1,149 +0,0 @@ -package auth - -import ( - "bytes" - "encoding/json" - "fmt" - "os/exec" - "path/filepath" - - ctyjson "github.com/zclconf/go-cty/cty/json" - - "github.com/hashicorp/terraform-svchost" -) - -type helperProgramCredentialsSource struct { - executable string - args []string -} - -// HelperProgramCredentialsSource returns a CredentialsSource that runs the -// given program with the given arguments in order to obtain credentials. -// -// The given executable path must be an absolute path; it is the caller's -// responsibility to validate and process a relative path or other input -// provided by an end-user. If the given path is not absolute, this -// function will panic. -// -// When credentials are requested, the program will be run in a child process -// with the given arguments along with two additional arguments added to the -// end of the list: the literal string "get", followed by the requested -// hostname in ASCII compatibility form (punycode form). -func HelperProgramCredentialsSource(executable string, args ...string) CredentialsSource { - if !filepath.IsAbs(executable) { - panic("NewCredentialsSourceHelperProgram requires absolute path to executable") - } - - fullArgs := make([]string, len(args)+1) - fullArgs[0] = executable - copy(fullArgs[1:], args) - - return &helperProgramCredentialsSource{ - executable: executable, - args: fullArgs, - } -} - -func (s *helperProgramCredentialsSource) ForHost(host svchost.Hostname) (HostCredentials, error) { - args := make([]string, len(s.args), len(s.args)+2) - copy(args, s.args) - args = append(args, "get") - args = append(args, string(host)) - - outBuf := bytes.Buffer{} - errBuf := bytes.Buffer{} - - cmd := exec.Cmd{ - Path: s.executable, - Args: args, - Stdin: nil, - Stdout: &outBuf, - Stderr: &errBuf, - } - err := cmd.Run() - if _, isExitErr := err.(*exec.ExitError); isExitErr { - errText := errBuf.String() - if errText == "" { - // Shouldn't happen for a well-behaved helper program - return nil, fmt.Errorf("error in %s, but it produced no error message", s.executable) - } - return nil, fmt.Errorf("error in %s: %s", s.executable, errText) - } else if err != nil { - return nil, fmt.Errorf("failed to run %s: %s", s.executable, err) - } - - var m map[string]interface{} - err = json.Unmarshal(outBuf.Bytes(), &m) - if err != nil { - return nil, fmt.Errorf("malformed output from %s: %s", s.executable, err) - } - - return HostCredentialsFromMap(m), nil -} - -func (s *helperProgramCredentialsSource) StoreForHost(host svchost.Hostname, credentials HostCredentialsWritable) error { - args := make([]string, len(s.args), len(s.args)+2) - copy(args, s.args) - args = append(args, "store") - args = append(args, string(host)) - - toStore := credentials.ToStore() - toStoreRaw, err := ctyjson.Marshal(toStore, toStore.Type()) - if err != nil { - return fmt.Errorf("can't serialize credentials to store: %s", err) - } - - inReader := bytes.NewReader(toStoreRaw) - errBuf := bytes.Buffer{} - - cmd := exec.Cmd{ - Path: s.executable, - Args: args, - Stdin: inReader, - Stderr: &errBuf, - Stdout: nil, - } - err = cmd.Run() - if _, isExitErr := err.(*exec.ExitError); isExitErr { - errText := errBuf.String() - if errText == "" { - // Shouldn't happen for a well-behaved helper program - return fmt.Errorf("error in %s, but it produced no error message", s.executable) - } - return fmt.Errorf("error in %s: %s", s.executable, errText) - } else if err != nil { - return fmt.Errorf("failed to run %s: %s", s.executable, err) - } - - return nil -} - -func (s *helperProgramCredentialsSource) ForgetForHost(host svchost.Hostname) error { - args := make([]string, len(s.args), len(s.args)+2) - copy(args, s.args) - args = append(args, "forget") - args = append(args, string(host)) - - errBuf := bytes.Buffer{} - - cmd := exec.Cmd{ - Path: s.executable, - Args: args, - Stdin: nil, - Stderr: &errBuf, - Stdout: nil, - } - err := cmd.Run() - if _, isExitErr := err.(*exec.ExitError); isExitErr { - errText := errBuf.String() - if errText == "" { - // Shouldn't happen for a well-behaved helper program - return fmt.Errorf("error in %s, but it produced no error message", s.executable) - } - return fmt.Errorf("error in %s: %s", s.executable, errText) - } else if err != nil { - return fmt.Errorf("failed to run %s: %s", s.executable, err) - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform-svchost/auth/static.go b/vendor/github.com/hashicorp/terraform-svchost/auth/static.go deleted file mode 100644 index f8b0b076e8c..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/auth/static.go +++ /dev/null @@ -1,38 +0,0 @@ -package auth - -import ( - "fmt" - - "github.com/hashicorp/terraform-svchost" -) - -// StaticCredentialsSource is a credentials source that retrieves credentials -// from the provided map. It returns nil if a requested hostname is not -// present in the map. -// -// The caller should not modify the given map after passing it to this function. -func StaticCredentialsSource(creds map[svchost.Hostname]map[string]interface{}) CredentialsSource { - return staticCredentialsSource(creds) -} - -type staticCredentialsSource map[svchost.Hostname]map[string]interface{} - -func (s staticCredentialsSource) ForHost(host svchost.Hostname) (HostCredentials, error) { - if s == nil { - return nil, nil - } - - if m, exists := s[host]; exists { - return HostCredentialsFromMap(m), nil - } - - return nil, nil -} - -func (s staticCredentialsSource) StoreForHost(host svchost.Hostname, credentials HostCredentialsWritable) error { - return fmt.Errorf("can't store new credentials in a static credentials source") -} - -func (s staticCredentialsSource) ForgetForHost(host svchost.Hostname) error { - return fmt.Errorf("can't discard credentials from a static credentials source") -} diff --git a/vendor/github.com/hashicorp/terraform-svchost/auth/token_credentials.go b/vendor/github.com/hashicorp/terraform-svchost/auth/token_credentials.go deleted file mode 100644 index 1d36553aeef..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/auth/token_credentials.go +++ /dev/null @@ -1,43 +0,0 @@ -package auth - -import ( - "net/http" - - "github.com/zclconf/go-cty/cty" -) - -// HostCredentialsToken is a HostCredentials implementation that represents a -// single "bearer token", to be sent to the server via an Authorization header -// with the auth type set to "Bearer". -// -// To save a token as the credentials for a host, convert the token string to -// this type and use the result as a HostCredentialsWritable implementation. -type HostCredentialsToken string - -// Interface implementation assertions. Compilation will fail here if -// HostCredentialsToken does not fully implement these interfaces. -var _ HostCredentials = HostCredentialsToken("") -var _ HostCredentialsWritable = HostCredentialsToken("") - -// PrepareRequest alters the given HTTP request by setting its Authorization -// header to the string "Bearer " followed by the encapsulated authentication -// token. -func (tc HostCredentialsToken) PrepareRequest(req *http.Request) { - if req.Header == nil { - req.Header = http.Header{} - } - req.Header.Set("Authorization", "Bearer "+string(tc)) -} - -// Token returns the authentication token. -func (tc HostCredentialsToken) Token() string { - return string(tc) -} - -// ToStore returns a credentials object with a single attribute "token" whose -// value is the token string. -func (tc HostCredentialsToken) ToStore() cty.Value { - return cty.ObjectVal(map[string]cty.Value{ - "token": cty.StringVal(string(tc)), - }) -} diff --git a/vendor/github.com/hashicorp/terraform-svchost/disco/disco.go b/vendor/github.com/hashicorp/terraform-svchost/disco/disco.go deleted file mode 100644 index 978313633f6..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/disco/disco.go +++ /dev/null @@ -1,275 +0,0 @@ -// Package disco handles Terraform's remote service discovery protocol. -// -// This protocol allows mapping from a service hostname, as produced by the -// svchost package, to a set of services supported by that host and the -// endpoint information for each supported service. -package disco - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "mime" - "net/http" - "net/url" - "time" - - "github.com/hashicorp/terraform-svchost" - "github.com/hashicorp/terraform-svchost/auth" -) - -const ( - // Fixed path to the discovery manifest. - discoPath = "/.well-known/terraform.json" - - // Arbitrary-but-small number to prevent runaway redirect loops. - maxRedirects = 3 - - // Arbitrary-but-small time limit to prevent UI "hangs" during discovery. - discoTimeout = 11 * time.Second - - // 1MB - to prevent abusive services from using loads of our memory. - maxDiscoDocBytes = 1 * 1024 * 1024 -) - -// httpTransport is overridden during tests, to skip TLS verification. -var httpTransport = defaultHttpTransport() - -// Disco is the main type in this package, which allows discovery on given -// hostnames and caches the results by hostname to avoid repeated requests -// for the same information. -type Disco struct { - hostCache map[svchost.Hostname]*Host - credsSrc auth.CredentialsSource - - // Transport is a custom http.RoundTripper to use. - Transport http.RoundTripper -} - -// New returns a new initialized discovery object. -func New() *Disco { - return NewWithCredentialsSource(nil) -} - -// NewWithCredentialsSource returns a new discovery object initialized with -// the given credentials source. -func NewWithCredentialsSource(credsSrc auth.CredentialsSource) *Disco { - return &Disco{ - hostCache: make(map[svchost.Hostname]*Host), - credsSrc: credsSrc, - Transport: httpTransport, - } -} - -func (d *Disco) SetUserAgent(uaString string) { - d.Transport = &userAgentRoundTripper{ - innerRt: d.Transport, - userAgent: uaString, - } -} - -// SetCredentialsSource provides a credentials source that will be used to -// add credentials to outgoing discovery requests, where available. -// -// If this method is never called, no outgoing discovery requests will have -// credentials. -func (d *Disco) SetCredentialsSource(src auth.CredentialsSource) { - d.credsSrc = src -} - -// CredentialsSource returns the credentials source associated with the receiver, -// or an empty credentials source if none is associated. -func (d *Disco) CredentialsSource() auth.CredentialsSource { - if d.credsSrc == nil { - // We'll return an empty one just to save the caller from having to - // protect against the nil case, since this interface already allows - // for the possibility of there being no credentials at all. - return auth.StaticCredentialsSource(nil) - } - return d.credsSrc -} - -// CredentialsForHost returns a non-nil HostCredentials if the embedded source has -// credentials available for the host, and a nil HostCredentials if it does not. -func (d *Disco) CredentialsForHost(hostname svchost.Hostname) (auth.HostCredentials, error) { - if d.credsSrc == nil { - return nil, nil - } - return d.credsSrc.ForHost(hostname) -} - -// ForceHostServices provides a pre-defined set of services for a given -// host, which prevents the receiver from attempting network-based discovery -// for the given host. Instead, the given services map will be returned -// verbatim. -// -// When providing "forced" services, any relative URLs are resolved against -// the initial discovery URL that would have been used for network-based -// discovery, yielding the same results as if the given map were published -// at the host's default discovery URL, though using absolute URLs is strongly -// recommended to make the configured behavior more explicit. -func (d *Disco) ForceHostServices(hostname svchost.Hostname, services map[string]interface{}) { - if services == nil { - services = map[string]interface{}{} - } - - d.hostCache[hostname] = &Host{ - discoURL: &url.URL{ - Scheme: "https", - Host: string(hostname), - Path: discoPath, - }, - hostname: hostname.ForDisplay(), - services: services, - transport: d.Transport, - } -} - -// Discover runs the discovery protocol against the given hostname (which must -// already have been validated and prepared with svchost.ForComparison) and -// returns an object describing the services available at that host. -// -// If a given hostname supports no Terraform services at all, a non-nil but -// empty Host object is returned. When giving feedback to the end user about -// such situations, we say "host does not provide a service", -// regardless of whether that is due to that service specifically being absent -// or due to the host not providing Terraform services at all, since we don't -// wish to expose the detail of whole-host discovery to an end-user. -func (d *Disco) Discover(hostname svchost.Hostname) (*Host, error) { - if host, cached := d.hostCache[hostname]; cached { - return host, nil - } - - host, err := d.discover(hostname) - if err != nil { - return nil, err - } - d.hostCache[hostname] = host - - return host, nil -} - -// DiscoverServiceURL is a convenience wrapper for discovery on a given -// hostname and then looking up a particular service in the result. -func (d *Disco) DiscoverServiceURL(hostname svchost.Hostname, serviceID string) (*url.URL, error) { - host, err := d.Discover(hostname) - if err != nil { - return nil, err - } - return host.ServiceURL(serviceID) -} - -// discover implements the actual discovery process, with its result cached -// by the public-facing Discover method. -func (d *Disco) discover(hostname svchost.Hostname) (*Host, error) { - discoURL := &url.URL{ - Scheme: "https", - Host: hostname.String(), - Path: discoPath, - } - - client := &http.Client{ - Transport: d.Transport, - Timeout: discoTimeout, - - CheckRedirect: func(req *http.Request, via []*http.Request) error { - log.Printf("[DEBUG] Service discovery redirected to %s", req.URL) - if len(via) > maxRedirects { - return errors.New("too many redirects") // this error will never actually be seen - } - return nil - }, - } - - req := &http.Request{ - Header: make(http.Header), - Method: "GET", - URL: discoURL, - } - req.Header.Set("Accept", "application/json") - - creds, err := d.CredentialsForHost(hostname) - if err != nil { - log.Printf("[WARN] Failed to get credentials for %s: %s (ignoring)", hostname, err) - } - if creds != nil { - // Update the request to include credentials. - creds.PrepareRequest(req) - } - - log.Printf("[DEBUG] Service discovery for %s at %s", hostname, discoURL) - - resp, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("Failed to request discovery document: %v", err) - } - defer resp.Body.Close() - - host := &Host{ - // Use the discovery URL from resp.Request in - // case the client followed any redirects. - discoURL: resp.Request.URL, - hostname: hostname.ForDisplay(), - transport: d.Transport, - } - - // Return the host without any services. - if resp.StatusCode == 404 { - return host, nil - } - - if resp.StatusCode != 200 { - return nil, fmt.Errorf("Failed to request discovery document: %s", resp.Status) - } - - contentType := resp.Header.Get("Content-Type") - mediaType, _, err := mime.ParseMediaType(contentType) - if err != nil { - return nil, fmt.Errorf("Discovery URL has a malformed Content-Type %q", contentType) - } - if mediaType != "application/json" { - return nil, fmt.Errorf("Discovery URL returned an unsupported Content-Type %q", mediaType) - } - - // This doesn't catch chunked encoding, because ContentLength is -1 in that case. - if resp.ContentLength > maxDiscoDocBytes { - // Size limit here is not a contractual requirement and so we may - // adjust it over time if we find a different limit is warranted. - return nil, fmt.Errorf( - "Discovery doc response is too large (got %d bytes; limit %d)", - resp.ContentLength, maxDiscoDocBytes, - ) - } - - // If the response is using chunked encoding then we can't predict its - // size, but we'll at least prevent reading the entire thing into memory. - lr := io.LimitReader(resp.Body, maxDiscoDocBytes) - - servicesBytes, err := ioutil.ReadAll(lr) - if err != nil { - return nil, fmt.Errorf("Error reading discovery document body: %v", err) - } - - var services map[string]interface{} - err = json.Unmarshal(servicesBytes, &services) - if err != nil { - return nil, fmt.Errorf("Failed to decode discovery document as a JSON object: %v", err) - } - host.services = services - - return host, nil -} - -// Forget invalidates any cached record of the given hostname. If the host -// has no cache entry then this is a no-op. -func (d *Disco) Forget(hostname svchost.Hostname) { - delete(d.hostCache, hostname) -} - -// ForgetAll is like Forget, but for all of the hostnames that have cache entries. -func (d *Disco) ForgetAll() { - d.hostCache = make(map[svchost.Hostname]*Host) -} diff --git a/vendor/github.com/hashicorp/terraform-svchost/disco/host.go b/vendor/github.com/hashicorp/terraform-svchost/disco/host.go deleted file mode 100644 index 2d0fc9f12f1..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/disco/host.go +++ /dev/null @@ -1,412 +0,0 @@ -package disco - -import ( - "encoding/json" - "fmt" - "log" - "net/http" - "net/url" - "os" - "strconv" - "strings" - "time" - - "github.com/hashicorp/go-version" -) - -const versionServiceID = "versions.v1" - -// Host represents a service discovered host. -type Host struct { - discoURL *url.URL - hostname string - services map[string]interface{} - transport http.RoundTripper -} - -// Constraints represents the version constraints of a service. -type Constraints struct { - Service string `json:"service"` - Product string `json:"product"` - Minimum string `json:"minimum"` - Maximum string `json:"maximum"` - Excluding []string `json:"excluding"` -} - -// ErrServiceNotProvided is returned when the service is not provided. -type ErrServiceNotProvided struct { - hostname string - service string -} - -// Error returns a customized error message. -func (e *ErrServiceNotProvided) Error() string { - if e.hostname == "" { - return fmt.Sprintf("host does not provide a %s service", e.service) - } - return fmt.Sprintf("host %s does not provide a %s service", e.hostname, e.service) -} - -// ErrVersionNotSupported is returned when the version is not supported. -type ErrVersionNotSupported struct { - hostname string - service string - version string -} - -// Error returns a customized error message. -func (e *ErrVersionNotSupported) Error() string { - if e.hostname == "" { - return fmt.Sprintf("host does not support %s version %s", e.service, e.version) - } - return fmt.Sprintf("host %s does not support %s version %s", e.hostname, e.service, e.version) -} - -// ErrNoVersionConstraints is returned when checkpoint was disabled -// or the endpoint to query for version constraints was unavailable. -type ErrNoVersionConstraints struct { - disabled bool -} - -// Error returns a customized error message. -func (e *ErrNoVersionConstraints) Error() string { - if e.disabled { - return "checkpoint disabled" - } - return "unable to contact versions service" -} - -// ServiceURL returns the URL associated with the given service identifier, -// which should be of the form "servicename.vN". -// -// A non-nil result is always an absolute URL with a scheme of either HTTPS -// or HTTP. -func (h *Host) ServiceURL(id string) (*url.URL, error) { - svc, ver, err := parseServiceID(id) - if err != nil { - return nil, err - } - - // No services supported for an empty Host. - if h == nil || h.services == nil { - return nil, &ErrServiceNotProvided{service: svc} - } - - urlStr, ok := h.services[id].(string) - if !ok { - // See if we have a matching service as that would indicate - // the service is supported, but not the requested version. - for serviceID := range h.services { - if strings.HasPrefix(serviceID, svc+".") { - return nil, &ErrVersionNotSupported{ - hostname: h.hostname, - service: svc, - version: ver.Original(), - } - } - } - - // No discovered services match the requested service. - return nil, &ErrServiceNotProvided{hostname: h.hostname, service: svc} - } - - u, err := h.parseURL(urlStr) - if err != nil { - return nil, fmt.Errorf("Failed to parse service URL: %v", err) - } - - return u, nil -} - -// ServiceOAuthClient returns the OAuth client configuration associated with the -// given service identifier, which should be of the form "servicename.vN". -// -// This is an alternative to ServiceURL for unusual services that require -// a full OAuth2 client definition rather than just a URL. Use this only -// for services whose specification calls for this sort of definition. -func (h *Host) ServiceOAuthClient(id string) (*OAuthClient, error) { - svc, ver, err := parseServiceID(id) - if err != nil { - return nil, err - } - - // No services supported for an empty Host. - if h == nil || h.services == nil { - return nil, &ErrServiceNotProvided{service: svc} - } - - if _, ok := h.services[id]; !ok { - // See if we have a matching service as that would indicate - // the service is supported, but not the requested version. - for serviceID := range h.services { - if strings.HasPrefix(serviceID, svc+".") { - return nil, &ErrVersionNotSupported{ - hostname: h.hostname, - service: svc, - version: ver.Original(), - } - } - } - - // No discovered services match the requested service. - return nil, &ErrServiceNotProvided{hostname: h.hostname, service: svc} - } - - var raw map[string]interface{} - switch v := h.services[id].(type) { - case map[string]interface{}: - raw = v // Great! - case []map[string]interface{}: - // An absolutely infuriating legacy HCL ambiguity. - raw = v[0] - default: - // Debug message because raw Go types don't belong in our UI. - log.Printf("[DEBUG] The definition for %s has Go type %T", id, h.services[id]) - return nil, fmt.Errorf("Service %s must be declared with an object value in the service discovery document", id) - } - - var grantTypes OAuthGrantTypeSet - if rawGTs, ok := raw["grant_types"]; ok { - if gts, ok := rawGTs.([]interface{}); ok { - var kws []string - for _, gtI := range gts { - gt, ok := gtI.(string) - if !ok { - // We'll ignore this so that we can potentially introduce - // other types into this array later if we need to. - continue - } - kws = append(kws, gt) - } - grantTypes = NewOAuthGrantTypeSet(kws...) - } else { - return nil, fmt.Errorf("Service %s is defined with invalid grant_types property: must be an array of grant type strings", id) - } - } else { - grantTypes = NewOAuthGrantTypeSet("authz_code") - } - - ret := &OAuthClient{ - SupportedGrantTypes: grantTypes, - } - if clientIDStr, ok := raw["client"].(string); ok { - ret.ID = clientIDStr - } else { - return nil, fmt.Errorf("Service %s definition is missing required property \"client\"", id) - } - if urlStr, ok := raw["authz"].(string); ok { - u, err := h.parseURL(urlStr) - if err != nil { - return nil, fmt.Errorf("Failed to parse authorization URL: %v", err) - } - ret.AuthorizationURL = u - } else { - if grantTypes.RequiresAuthorizationEndpoint() { - return nil, fmt.Errorf("Service %s definition is missing required property \"authz\"", id) - } - } - if urlStr, ok := raw["token"].(string); ok { - u, err := h.parseURL(urlStr) - if err != nil { - return nil, fmt.Errorf("Failed to parse token URL: %v", err) - } - ret.TokenURL = u - } else { - if grantTypes.RequiresTokenEndpoint() { - return nil, fmt.Errorf("Service %s definition is missing required property \"token\"", id) - } - } - if portsRaw, ok := raw["ports"].([]interface{}); ok { - if len(portsRaw) != 2 { - return nil, fmt.Errorf("Invalid \"ports\" definition for service %s: must be a two-element array", id) - } - invalidPortsErr := fmt.Errorf("Invalid \"ports\" definition for service %s: both ports must be whole numbers between 1024 and 65535", id) - ports := make([]uint16, 2) - for i := range ports { - switch v := portsRaw[i].(type) { - case float64: - // JSON unmarshaling always produces float64. HCL 2 might, if - // an invalid fractional number were given. - if float64(uint16(v)) != v || v < 1024 { - return nil, invalidPortsErr - } - ports[i] = uint16(v) - case int: - // Legacy HCL produces int. HCL 2 will too, if the given number - // is a whole number. - if v < 1024 || v > 65535 { - return nil, invalidPortsErr - } - ports[i] = uint16(v) - default: - // Debug message because raw Go types don't belong in our UI. - log.Printf("[DEBUG] Port value %d has Go type %T", i, portsRaw[i]) - return nil, invalidPortsErr - } - } - if ports[1] < ports[0] { - return nil, fmt.Errorf("Invalid \"ports\" definition for service %s: minimum port cannot be greater than maximum port", id) - } - ret.MinPort = ports[0] - ret.MaxPort = ports[1] - } else { - // Default is to accept any port in the range, for a client that is - // able to call back to any localhost port. - ret.MinPort = 1024 - ret.MaxPort = 65535 - } - - return ret, nil -} - -func (h *Host) parseURL(urlStr string) (*url.URL, error) { - u, err := url.Parse(urlStr) - if err != nil { - return nil, err - } - - // Make relative URLs absolute using our discovery URL. - if !u.IsAbs() { - u = h.discoURL.ResolveReference(u) - } - - if u.Scheme != "https" && u.Scheme != "http" { - return nil, fmt.Errorf("unsupported scheme %s", u.Scheme) - } - if u.User != nil { - return nil, fmt.Errorf("embedded username/password information is not permitted") - } - - // Fragment part is irrelevant, since we're not a browser. - u.Fragment = "" - - return u, nil -} - -// VersionConstraints returns the contraints for a given service identifier -// (which should be of the form "servicename.vN") and product. -// -// When an exact (service and version) match is found, the constraints for -// that service are returned. -// -// When the requested version is not provided but the service is, we will -// search for all alternative versions. If mutliple alternative versions -// are found, the contrains of the latest available version are returned. -// -// When a service is not provided at all an error will be returned instead. -// -// When checkpoint is disabled or when a 404 is returned after making the -// HTTP call, an ErrNoVersionConstraints error will be returned. -func (h *Host) VersionConstraints(id, product string) (*Constraints, error) { - svc, _, err := parseServiceID(id) - if err != nil { - return nil, err - } - - // Return early if checkpoint is disabled. - if disabled := os.Getenv("CHECKPOINT_DISABLE"); disabled != "" { - return nil, &ErrNoVersionConstraints{disabled: true} - } - - // No services supported for an empty Host. - if h == nil || h.services == nil { - return nil, &ErrServiceNotProvided{service: svc} - } - - // Try to get the service URL for the version service and - // return early if the service isn't provided by the host. - u, err := h.ServiceURL(versionServiceID) - if err != nil { - return nil, err - } - - // Check if we have an exact (service and version) match. - if _, ok := h.services[id].(string); !ok { - // If we don't have an exact match, we search for all matching - // services and then use the service ID of the latest version. - var services []string - for serviceID := range h.services { - if strings.HasPrefix(serviceID, svc+".") { - services = append(services, serviceID) - } - } - - if len(services) == 0 { - // No discovered services match the requested service. - return nil, &ErrServiceNotProvided{hostname: h.hostname, service: svc} - } - - // Set id to the latest service ID we found. - var latest *version.Version - for _, serviceID := range services { - if _, ver, err := parseServiceID(serviceID); err == nil { - if latest == nil || latest.LessThan(ver) { - id = serviceID - latest = ver - } - } - } - } - - // Set a default timeout of 1 sec for the versions request (in milliseconds) - timeout := 1000 - if v, err := strconv.Atoi(os.Getenv("CHECKPOINT_TIMEOUT")); err == nil { - timeout = v - } - - client := &http.Client{ - Transport: h.transport, - Timeout: time.Duration(timeout) * time.Millisecond, - } - - // Prepare the service URL by setting the service and product. - v := u.Query() - v.Set("product", product) - u.Path += id - u.RawQuery = v.Encode() - - // Create a new request. - req, err := http.NewRequest("GET", u.String(), nil) - if err != nil { - return nil, fmt.Errorf("Failed to create version constraints request: %v", err) - } - req.Header.Set("Accept", "application/json") - - log.Printf("[DEBUG] Retrieve version constraints for service %s and product %s", id, product) - - resp, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("Failed to request version constraints: %v", err) - } - defer resp.Body.Close() - - if resp.StatusCode == 404 { - return nil, &ErrNoVersionConstraints{disabled: false} - } - - if resp.StatusCode != 200 { - return nil, fmt.Errorf("Failed to request version constraints: %s", resp.Status) - } - - // Parse the constraints from the response body. - result := &Constraints{} - if err := json.NewDecoder(resp.Body).Decode(result); err != nil { - return nil, fmt.Errorf("Error parsing version constraints: %v", err) - } - - return result, nil -} - -func parseServiceID(id string) (string, *version.Version, error) { - parts := strings.SplitN(id, ".", 2) - if len(parts) != 2 { - return "", nil, fmt.Errorf("Invalid service ID format (i.e. service.vN): %s", id) - } - - version, err := version.NewVersion(parts[1]) - if err != nil { - return "", nil, fmt.Errorf("Invalid service version: %v", err) - } - - return parts[0], version, nil -} diff --git a/vendor/github.com/hashicorp/terraform-svchost/disco/http_transport.go b/vendor/github.com/hashicorp/terraform-svchost/disco/http_transport.go deleted file mode 100644 index 7e4a38567ec..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/disco/http_transport.go +++ /dev/null @@ -1,30 +0,0 @@ -package disco - -import ( - "net/http" - - "github.com/hashicorp/go-cleanhttp" -) - -const DefaultUserAgent = "terraform-svchost/1.0" - -func defaultHttpTransport() http.RoundTripper { - t := cleanhttp.DefaultPooledTransport() - return &userAgentRoundTripper{ - innerRt: t, - userAgent: DefaultUserAgent, - } -} - -type userAgentRoundTripper struct { - innerRt http.RoundTripper - userAgent string -} - -func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - if _, ok := req.Header["User-Agent"]; !ok { - req.Header.Set("User-Agent", rt.userAgent) - } - - return rt.innerRt.RoundTrip(req) -} diff --git a/vendor/github.com/hashicorp/terraform-svchost/disco/oauth_client.go b/vendor/github.com/hashicorp/terraform-svchost/disco/oauth_client.go deleted file mode 100644 index 9308bbf72a5..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/disco/oauth_client.go +++ /dev/null @@ -1,178 +0,0 @@ -package disco - -import ( - "fmt" - "net/url" - "strings" - - "golang.org/x/oauth2" -) - -// OAuthClient represents an OAuth client configuration, which is used for -// unusual services that require an entire OAuth client configuration as part -// of their service discovery, rather than just a URL. -type OAuthClient struct { - // ID is the identifier for the client, to be used as "client_id" in - // OAuth requests. - ID string - - // Authorization URL is the URL of the authorization endpoint that must - // be used for this OAuth client, as defined in the OAuth2 specifications. - // - // Not all grant types use the authorization endpoint, so it may be omitted - // if none of the grant types in SupportedGrantTypes require it. - AuthorizationURL *url.URL - - // Token URL is the URL of the token endpoint that must be used for this - // OAuth client, as defined in the OAuth2 specifications. - // - // Not all grant types use the token endpoint, so it may be omitted - // if none of the grant types in SupportedGrantTypes require it. - TokenURL *url.URL - - // MinPort and MaxPort define a range of TCP ports on localhost that this - // client is able to use as redirect_uri in an authorization request. - // Terraform will select a port from this range for the temporary HTTP - // server it creates to receive the authorization response, giving - // a URL like http://localhost:NNN/ where NNN is the selected port number. - // - // Terraform will reject any port numbers in this range less than 1024, - // to respect the common convention (enforced on some operating systems) - // that lower port numbers are reserved for "privileged" services. - MinPort, MaxPort uint16 - - // SupportedGrantTypes is a set of the grant types that the client may - // choose from. This includes an entry for each distinct type advertised - // by the server, even if a particular keyword is not supported by the - // current version of Terraform. - SupportedGrantTypes OAuthGrantTypeSet -} - -// Endpoint returns an oauth2.Endpoint value ready to be used with the oauth2 -// library, representing the URLs from the receiver. -func (c *OAuthClient) Endpoint() oauth2.Endpoint { - ep := oauth2.Endpoint{ - // We don't actually auth because we're not a server-based OAuth client, - // so this instead just means that we include client_id as an argument - // in our requests. - AuthStyle: oauth2.AuthStyleInParams, - } - - if c.AuthorizationURL != nil { - ep.AuthURL = c.AuthorizationURL.String() - } - if c.TokenURL != nil { - ep.TokenURL = c.TokenURL.String() - } - - return ep -} - -// OAuthGrantType is an enumeration of grant type strings that a host can -// advertise support for. -// -// Values of this type don't necessarily match with a known constant of the -// type, because they may represent grant type keywords defined in a later -// version of Terraform which this version doesn't yet know about. -type OAuthGrantType string - -const ( - // OAuthAuthzCodeGrant represents an authorization code grant, as - // defined in IETF RFC 6749 section 4.1. - OAuthAuthzCodeGrant = OAuthGrantType("authz_code") - - // OAuthOwnerPasswordGrant represents a resource owner password - // credentials grant, as defined in IETF RFC 6749 section 4.3. - OAuthOwnerPasswordGrant = OAuthGrantType("password") -) - -// UsesAuthorizationEndpoint returns true if the receiving grant type makes -// use of the authorization endpoint from the client configuration, and thus -// if the authorization endpoint ought to be required. -func (t OAuthGrantType) UsesAuthorizationEndpoint() bool { - switch t { - case OAuthAuthzCodeGrant: - return true - case OAuthOwnerPasswordGrant: - return false - default: - // We'll default to false so that we don't impose any requirements - // on any grant type keywords that might be defined for future - // versions of Terraform. - return false - } -} - -// UsesTokenEndpoint returns true if the receiving grant type makes -// use of the token endpoint from the client configuration, and thus -// if the authorization endpoint ought to be required. -func (t OAuthGrantType) UsesTokenEndpoint() bool { - switch t { - case OAuthAuthzCodeGrant: - return true - case OAuthOwnerPasswordGrant: - return true - default: - // We'll default to false so that we don't impose any requirements - // on any grant type keywords that might be defined for future - // versions of Terraform. - return false - } -} - -// OAuthGrantTypeSet represents a set of OAuthGrantType values. -type OAuthGrantTypeSet map[OAuthGrantType]struct{} - -// NewOAuthGrantTypeSet constructs a new grant type set from the given list -// of grant type keyword strings. Any duplicates in the list are ignored. -func NewOAuthGrantTypeSet(keywords ...string) OAuthGrantTypeSet { - ret := make(OAuthGrantTypeSet, len(keywords)) - for _, kw := range keywords { - ret[OAuthGrantType(kw)] = struct{}{} - } - return ret -} - -// Has returns true if the given grant type is in the receiving set. -func (s OAuthGrantTypeSet) Has(t OAuthGrantType) bool { - _, ok := s[t] - return ok -} - -// RequiresAuthorizationEndpoint returns true if any of the grant types in -// the set are known to require an authorization endpoint. -func (s OAuthGrantTypeSet) RequiresAuthorizationEndpoint() bool { - for t := range s { - if t.UsesAuthorizationEndpoint() { - return true - } - } - return false -} - -// RequiresTokenEndpoint returns true if any of the grant types in -// the set are known to require a token endpoint. -func (s OAuthGrantTypeSet) RequiresTokenEndpoint() bool { - for t := range s { - if t.UsesTokenEndpoint() { - return true - } - } - return false -} - -// GoString implements fmt.GoStringer. -func (s OAuthGrantTypeSet) GoString() string { - var buf strings.Builder - i := 0 - buf.WriteString("disco.NewOAuthGrantTypeSet(") - for t := range s { - if i > 0 { - buf.WriteString(", ") - } - fmt.Fprintf(&buf, "%q", string(t)) - i++ - } - buf.WriteString(")") - return buf.String() -} diff --git a/vendor/github.com/hashicorp/terraform-svchost/go.mod b/vendor/github.com/hashicorp/terraform-svchost/go.mod deleted file mode 100644 index 8f29e4ac5ba..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/go.mod +++ /dev/null @@ -1,12 +0,0 @@ -module github.com/hashicorp/terraform-svchost - -go 1.12 - -require ( - github.com/google/go-cmp v0.3.1 - github.com/hashicorp/go-cleanhttp v0.5.1 - github.com/hashicorp/go-version v1.2.0 - github.com/zclconf/go-cty v1.1.0 - golang.org/x/net v0.0.0-20191009170851-d66e71096ffb - golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 -) diff --git a/vendor/github.com/hashicorp/terraform-svchost/go.sum b/vendor/github.com/hashicorp/terraform-svchost/go.sum deleted file mode 100644 index 9ad1712f80d..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/go.sum +++ /dev/null @@ -1,36 +0,0 @@ -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= -github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= -github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-version v1.2.0 h1:3vNe/fWF5CBgRIguda1meWhsZHy3m8gCJ5wx+dIzX/E= -github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= -github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= -github.com/zclconf/go-cty v1.1.0 h1:uJwc9HiBOCpoKIObTQaLR+tsEXx1HBHnOsOOpcdhZgw= -github.com/zclconf/go-cty v1.1.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20191009170851-d66e71096ffb h1:TR699M2v0qoKTOHxeLgp6zPqaQNs74f01a/ob9W0qko= -golang.org/x/net v0.0.0-20191009170851-d66e71096ffb/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= -google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/vendor/github.com/hashicorp/terraform-svchost/label_iter.go b/vendor/github.com/hashicorp/terraform-svchost/label_iter.go deleted file mode 100644 index af8ccbab208..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/label_iter.go +++ /dev/null @@ -1,69 +0,0 @@ -package svchost - -import ( - "strings" -) - -// A labelIter allows iterating over domain name labels. -// -// This type is copied from golang.org/x/net/idna, where it is used -// to segment hostnames into their separate labels for analysis. We use -// it for the same purpose here, in ForComparison. -type labelIter struct { - orig string - slice []string - curStart int - curEnd int - i int -} - -func (l *labelIter) reset() { - l.curStart = 0 - l.curEnd = 0 - l.i = 0 -} - -func (l *labelIter) done() bool { - return l.curStart >= len(l.orig) -} - -func (l *labelIter) result() string { - if l.slice != nil { - return strings.Join(l.slice, ".") - } - return l.orig -} - -func (l *labelIter) label() string { - if l.slice != nil { - return l.slice[l.i] - } - p := strings.IndexByte(l.orig[l.curStart:], '.') - l.curEnd = l.curStart + p - if p == -1 { - l.curEnd = len(l.orig) - } - return l.orig[l.curStart:l.curEnd] -} - -// next sets the value to the next label. It skips the last label if it is empty. -func (l *labelIter) next() { - l.i++ - if l.slice != nil { - if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" { - l.curStart = len(l.orig) - } - } else { - l.curStart = l.curEnd + 1 - if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' { - l.curStart = len(l.orig) - } - } -} - -func (l *labelIter) set(s string) { - if l.slice == nil { - l.slice = strings.Split(l.orig, ".") - } - l.slice[l.i] = s -} diff --git a/vendor/github.com/hashicorp/terraform-svchost/svchost.go b/vendor/github.com/hashicorp/terraform-svchost/svchost.go deleted file mode 100644 index 4060b767e58..00000000000 --- a/vendor/github.com/hashicorp/terraform-svchost/svchost.go +++ /dev/null @@ -1,207 +0,0 @@ -// Package svchost deals with the representations of the so-called "friendly -// hostnames" that we use to represent systems that provide Terraform-native -// remote services, such as module registry, remote operations, etc. -// -// Friendly hostnames are specified such that, as much as possible, they -// are consistent with how web browsers think of hostnames, so that users -// can bring their intuitions about how hostnames behave when they access -// a Terraform Enterprise instance's web UI (or indeed any other website) -// and have this behave in a similar way. -package svchost - -import ( - "errors" - "fmt" - "strconv" - "strings" - - "golang.org/x/net/idna" -) - -// Hostname is specialized name for string that indicates that the string -// has been converted to (or was already in) the storage and comparison form. -// -// Hostname values are not suitable for display in the user-interface. Use -// the ForDisplay method to obtain a form suitable for display in the UI. -// -// Unlike user-supplied hostnames, strings of type Hostname (assuming they -// were constructed by a function within this package) can be compared for -// equality using the standard Go == operator. -type Hostname string - -// acePrefix is the ASCII Compatible Encoding prefix, used to indicate that -// a domain name label is in "punycode" form. -const acePrefix = "xn--" - -// displayProfile is a very liberal idna profile that we use to do -// normalization for display without imposing validation rules. -var displayProfile = idna.New( - idna.MapForLookup(), - idna.Transitional(true), -) - -// ForDisplay takes a user-specified hostname and returns a normalized form of -// it suitable for display in the UI. -// -// If the input is so invalid that no normalization can be performed then -// this will return the input, assuming that the caller still wants to -// display _something_. This function is, however, more tolerant than the -// other functions in this package and will make a best effort to prepare -// _any_ given hostname for display. -// -// For validation, use either IsValid (for explicit validation) or -// ForComparison (which implicitly validates, returning an error if invalid). -func ForDisplay(given string) string { - var portPortion string - if colonPos := strings.Index(given, ":"); colonPos != -1 { - given, portPortion = given[:colonPos], given[colonPos:] - } - portPortion, _ = normalizePortPortion(portPortion) - - ascii, err := displayProfile.ToASCII(given) - if err != nil { - return given + portPortion - } - display, err := displayProfile.ToUnicode(ascii) - if err != nil { - return given + portPortion - } - return display + portPortion -} - -// IsValid returns true if the given user-specified hostname is a valid -// service hostname. -// -// Validity is determined by complying with the RFC 5891 requirements for -// names that are valid for domain lookup (section 5), with the additional -// requirement that user-supplied forms must not _already_ contain -// Punycode segments. -func IsValid(given string) bool { - _, err := ForComparison(given) - return err == nil -} - -// ForComparison takes a user-specified hostname and returns a normalized -// form of it suitable for storage and comparison. The result is not suitable -// for display to end-users because it uses Punycode to represent non-ASCII -// characters, and this form is unreadable for non-ASCII-speaking humans. -// -// The result is typed as Hostname -- a specialized name for string -- so that -// other APIs can make it clear within the type system whether they expect a -// user-specified or display-form hostname or a value already normalized for -// comparison. -// -// The returned Hostname is not valid if the returned error is non-nil. -func ForComparison(given string) (Hostname, error) { - var portPortion string - if colonPos := strings.Index(given, ":"); colonPos != -1 { - given, portPortion = given[:colonPos], given[colonPos:] - } - - var err error - portPortion, err = normalizePortPortion(portPortion) - if err != nil { - return Hostname(""), err - } - - if given == "" { - return Hostname(""), fmt.Errorf("empty string is not a valid hostname") - } - - // First we'll apply our additional constraint that Punycode must not - // be given directly by the user. This is not an IDN specification - // requirement, but we prohibit it to force users to use human-readable - // hostname forms within Terraform configuration. - labels := labelIter{orig: given} - for ; !labels.done(); labels.next() { - label := labels.label() - if label == "" { - return Hostname(""), fmt.Errorf( - "hostname contains empty label (two consecutive periods)", - ) - } - if strings.HasPrefix(label, acePrefix) { - return Hostname(""), fmt.Errorf( - "hostname label %q specified in punycode format; service hostnames must be given in unicode", - label, - ) - } - } - - result, err := idna.Lookup.ToASCII(given) - if err != nil { - return Hostname(""), err - } - return Hostname(result + portPortion), nil -} - -// ForDisplay returns a version of the receiver that is appropriate for display -// in the UI. This includes converting any punycode labels to their -// corresponding Unicode characters. -// -// A round-trip through ForComparison and this ForDisplay method does not -// guarantee the same result as calling this package's top-level ForDisplay -// function, since a round-trip through the Hostname type implies stricter -// handling than we do when doing basic display-only processing. -func (h Hostname) ForDisplay() string { - given := string(h) - var portPortion string - if colonPos := strings.Index(given, ":"); colonPos != -1 { - given, portPortion = given[:colonPos], given[colonPos:] - } - // We don't normalize the port portion here because we assume it's - // already been normalized on the way in. - - result, err := idna.Lookup.ToUnicode(given) - if err != nil { - // Should never happen, since type Hostname indicates that a string - // passed through our validation rules. - panic(fmt.Errorf("ForDisplay called on invalid Hostname: %s", err)) - } - return result + portPortion -} - -func (h Hostname) String() string { - return string(h) -} - -func (h Hostname) GoString() string { - return fmt.Sprintf("svchost.Hostname(%q)", string(h)) -} - -// normalizePortPortion attempts to normalize the "port portion" of a hostname, -// which begins with the first colon in the hostname and should be followed -// by a string of decimal digits. -// -// If the port portion is valid, a normalized version of it is returned along -// with a nil error. -// -// If the port portion is invalid, the input string is returned verbatim along -// with a non-nil error. -// -// An empty string is a valid port portion representing the absence of a port. -// If non-empty, the first character must be a colon. -func normalizePortPortion(s string) (string, error) { - if s == "" { - return s, nil - } - - if s[0] != ':' { - // should never happen, since caller tends to guarantee the presence - // of a colon due to how it's extracted from the string. - return s, errors.New("port portion is missing its initial colon") - } - - numStr := s[1:] - num, err := strconv.Atoi(numStr) - if err != nil { - return s, errors.New("port portion contains non-digit characters") - } - if num == 443 { - return "", nil // ":443" is the default - } - if num > 65535 { - return s, errors.New("port number is greater than 65535") - } - return fmt.Sprintf(":%d", num), nil -} diff --git a/vendor/github.com/hashicorp/vault/LICENSE b/vendor/github.com/hashicorp/vault/LICENSE deleted file mode 100644 index e87a115e462..00000000000 --- a/vendor/github.com/hashicorp/vault/LICENSE +++ /dev/null @@ -1,363 +0,0 @@ -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/vault/helper/compressutil/compress.go b/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go deleted file mode 100644 index a7fb87bcfff..00000000000 --- a/vendor/github.com/hashicorp/vault/helper/compressutil/compress.go +++ /dev/null @@ -1,192 +0,0 @@ -package compressutil - -import ( - "bytes" - "compress/gzip" - "compress/lzw" - "fmt" - "io" - - "github.com/golang/snappy" - "github.com/hashicorp/errwrap" -) - -const ( - // A byte value used as a canary prefix for the compressed information - // which is used to distinguish if a JSON input is compressed or not. - // The value of this constant should not be a first character of any - // valid JSON string. - - // Byte value used as canary when using Gzip format - CompressionCanaryGzip byte = 'G' - - // Byte value used as canary when using Lzw format - CompressionCanaryLzw byte = 'L' - - // Byte value used as canary when using Snappy format - CompressionCanarySnappy byte = 'S' - - CompressionTypeLzw = "lzw" - - CompressionTypeGzip = "gzip" - - CompressionTypeSnappy = "snappy" -) - -// SnappyReadCloser embeds the snappy reader which implements the io.Reader -// interface. The decompress procedure in this utility expects an -// io.ReadCloser. This type implements the io.Closer interface to retain the -// generic way of decompression. -type SnappyReadCloser struct { - *snappy.Reader -} - -// Close is a noop method implemented only to satisfy the io.Closer interface -func (s *SnappyReadCloser) Close() error { - return nil -} - -// CompressionConfig is used to select a compression type to be performed by -// Compress and Decompress utilities. -// Supported types are: -// * CompressionTypeLzw -// * CompressionTypeGzip -// * CompressionTypeSnappy -// -// When using CompressionTypeGzip, the compression levels can also be chosen: -// * gzip.DefaultCompression -// * gzip.BestSpeed -// * gzip.BestCompression -type CompressionConfig struct { - // Type of the compression algorithm to be used - Type string - - // When using Gzip format, the compression level to employ - GzipCompressionLevel int -} - -// Compress places the canary byte in a buffer and uses the same buffer to fill -// in the compressed information of the given input. The configuration supports -// two type of compression: LZW and Gzip. When using Gzip compression format, -// if GzipCompressionLevel is not specified, the 'gzip.DefaultCompression' will -// be assumed. -func Compress(data []byte, config *CompressionConfig) ([]byte, error) { - var buf bytes.Buffer - var writer io.WriteCloser - var err error - - if config == nil { - return nil, fmt.Errorf("config is nil") - } - - // Write the canary into the buffer and create writer to compress the - // input data based on the configured type - switch config.Type { - case CompressionTypeLzw: - buf.Write([]byte{CompressionCanaryLzw}) - - writer = lzw.NewWriter(&buf, lzw.LSB, 8) - case CompressionTypeGzip: - buf.Write([]byte{CompressionCanaryGzip}) - - switch { - case config.GzipCompressionLevel == gzip.BestCompression, - config.GzipCompressionLevel == gzip.BestSpeed, - config.GzipCompressionLevel == gzip.DefaultCompression: - // These are valid compression levels - default: - // If compression level is set to NoCompression or to - // any invalid value, fallback to Defaultcompression - config.GzipCompressionLevel = gzip.DefaultCompression - } - writer, err = gzip.NewWriterLevel(&buf, config.GzipCompressionLevel) - case CompressionTypeSnappy: - buf.Write([]byte{CompressionCanarySnappy}) - writer = snappy.NewBufferedWriter(&buf) - default: - return nil, fmt.Errorf("unsupported compression type") - } - - if err != nil { - return nil, errwrap.Wrapf("failed to create a compression writer: {{err}}", err) - } - - if writer == nil { - return nil, fmt.Errorf("failed to create a compression writer") - } - - // Compress the input and place it in the same buffer containing the - // canary byte. - if _, err = writer.Write(data); err != nil { - return nil, errwrap.Wrapf("failed to compress input data: err: {{err}}", err) - } - - // Close the io.WriteCloser - if err = writer.Close(); err != nil { - return nil, err - } - - // Return the compressed bytes with canary byte at the start - return buf.Bytes(), nil -} - -// Decompress checks if the first byte in the input matches the canary byte. -// If the first byte is a canary byte, then the input past the canary byte -// will be decompressed using the method specified in the given configuration. -// If the first byte isn't a canary byte, then the utility returns a boolean -// value indicating that the input was not compressed. -func Decompress(data []byte) ([]byte, bool, error) { - var err error - var reader io.ReadCloser - if data == nil || len(data) == 0 { - return nil, false, fmt.Errorf("'data' being decompressed is empty") - } - - switch { - // If the first byte matches the canary byte, remove the canary - // byte and try to decompress the data that is after the canary. - case data[0] == CompressionCanaryGzip: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - data = data[1:] - reader, err = gzip.NewReader(bytes.NewReader(data)) - case data[0] == CompressionCanaryLzw: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - data = data[1:] - reader = lzw.NewReader(bytes.NewReader(data), lzw.LSB, 8) - - case data[0] == CompressionCanarySnappy: - if len(data) < 2 { - return nil, false, fmt.Errorf("invalid 'data' after the canary") - } - data = data[1:] - reader = &SnappyReadCloser{ - Reader: snappy.NewReader(bytes.NewReader(data)), - } - default: - // If the first byte doesn't match the canary byte, it means - // that the content was not compressed at all. Indicate the - // caller that the input was not compressed. - return nil, true, nil - } - if err != nil { - return nil, false, errwrap.Wrapf("failed to create a compression reader: {{err}}", err) - } - if reader == nil { - return nil, false, fmt.Errorf("failed to create a compression reader") - } - - // Close the io.ReadCloser - defer reader.Close() - - // Read all the compressed data into a buffer - var buf bytes.Buffer - if _, err = io.Copy(&buf, reader); err != nil { - return nil, false, err - } - - return buf.Bytes(), false, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go b/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go deleted file mode 100644 index d03ddef5f06..00000000000 --- a/vendor/github.com/hashicorp/vault/helper/jsonutil/json.go +++ /dev/null @@ -1,100 +0,0 @@ -package jsonutil - -import ( - "bytes" - "compress/gzip" - "encoding/json" - "fmt" - "io" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/vault/helper/compressutil" -) - -// Encodes/Marshals the given object into JSON -func EncodeJSON(in interface{}) ([]byte, error) { - if in == nil { - return nil, fmt.Errorf("input for encoding is nil") - } - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - if err := enc.Encode(in); err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// EncodeJSONAndCompress encodes the given input into JSON and compresses the -// encoded value (using Gzip format BestCompression level, by default). A -// canary byte is placed at the beginning of the returned bytes for the logic -// in decompression method to identify compressed input. -func EncodeJSONAndCompress(in interface{}, config *compressutil.CompressionConfig) ([]byte, error) { - if in == nil { - return nil, fmt.Errorf("input for encoding is nil") - } - - // First JSON encode the given input - encodedBytes, err := EncodeJSON(in) - if err != nil { - return nil, err - } - - if config == nil { - config = &compressutil.CompressionConfig{ - Type: compressutil.CompressionTypeGzip, - GzipCompressionLevel: gzip.BestCompression, - } - } - - return compressutil.Compress(encodedBytes, config) -} - -// DecodeJSON tries to decompress the given data. The call to decompress, fails -// if the content was not compressed in the first place, which is identified by -// a canary byte before the compressed data. If the data is not compressed, it -// is JSON decoded directly. Otherwise the decompressed data will be JSON -// decoded. -func DecodeJSON(data []byte, out interface{}) error { - if data == nil || len(data) == 0 { - return fmt.Errorf("'data' being decoded is nil") - } - if out == nil { - return fmt.Errorf("output parameter 'out' is nil") - } - - // Decompress the data if it was compressed in the first place - decompressedBytes, uncompressed, err := compressutil.Decompress(data) - if err != nil { - return errwrap.Wrapf("failed to decompress JSON: {{err}}", err) - } - if !uncompressed && (decompressedBytes == nil || len(decompressedBytes) == 0) { - return fmt.Errorf("decompressed data being decoded is invalid") - } - - // If the input supplied failed to contain the compression canary, it - // will be notified by the compression utility. Decode the decompressed - // input. - if !uncompressed { - data = decompressedBytes - } - - return DecodeJSONFromReader(bytes.NewReader(data), out) -} - -// Decodes/Unmarshals the given io.Reader pointing to a JSON, into a desired object -func DecodeJSONFromReader(r io.Reader, out interface{}) error { - if r == nil { - return fmt.Errorf("'io.Reader' being decoded is nil") - } - if out == nil { - return fmt.Errorf("output parameter 'out' is nil") - } - - dec := json.NewDecoder(r) - - // While decoding JSON values, interpret the integer values as `json.Number`s instead of `float64`. - dec.UseNumber() - - // Since 'out' is an interface representing a pointer, pass it to the decoder without an '&' - return dec.Decode(out) -} diff --git a/vendor/github.com/hashicorp/vault/helper/pgpkeys/encrypt_decrypt.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/encrypt_decrypt.go deleted file mode 100644 index eef4c5ed007..00000000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/encrypt_decrypt.go +++ /dev/null @@ -1,118 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/keybase/go-crypto/openpgp" - "github.com/keybase/go-crypto/openpgp/packet" -) - -// EncryptShares takes an ordered set of byte slices to encrypt and the -// corresponding base64-encoded public keys to encrypt them with, encrypts each -// byte slice with the corresponding public key. -// -// Note: There is no corresponding test function; this functionality is -// thoroughly tested in the init and rekey command unit tests -func EncryptShares(input [][]byte, pgpKeys []string) ([]string, [][]byte, error) { - if len(input) != len(pgpKeys) { - return nil, nil, fmt.Errorf("mismatch between number items to encrypt and number of PGP keys") - } - encryptedShares := make([][]byte, 0, len(pgpKeys)) - entities, err := GetEntities(pgpKeys) - if err != nil { - return nil, nil, err - } - for i, entity := range entities { - ctBuf := bytes.NewBuffer(nil) - pt, err := openpgp.Encrypt(ctBuf, []*openpgp.Entity{entity}, nil, nil, nil) - if err != nil { - return nil, nil, errwrap.Wrapf("error setting up encryption for PGP message: {{err}}", err) - } - _, err = pt.Write(input[i]) - if err != nil { - return nil, nil, errwrap.Wrapf("error encrypting PGP message: {{err}}", err) - } - pt.Close() - encryptedShares = append(encryptedShares, ctBuf.Bytes()) - } - - fingerprints, err := GetFingerprints(nil, entities) - if err != nil { - return nil, nil, err - } - - return fingerprints, encryptedShares, nil -} - -// GetFingerprints takes in a list of openpgp Entities and returns the -// fingerprints. If entities is nil, it will instead parse both entities and -// fingerprints from the pgpKeys string slice. -func GetFingerprints(pgpKeys []string, entities []*openpgp.Entity) ([]string, error) { - if entities == nil { - var err error - entities, err = GetEntities(pgpKeys) - - if err != nil { - return nil, err - } - } - ret := make([]string, 0, len(entities)) - for _, entity := range entities { - ret = append(ret, fmt.Sprintf("%x", entity.PrimaryKey.Fingerprint)) - } - return ret, nil -} - -// GetEntities takes in a string array of base64-encoded PGP keys and returns -// the openpgp Entities -func GetEntities(pgpKeys []string) ([]*openpgp.Entity, error) { - ret := make([]*openpgp.Entity, 0, len(pgpKeys)) - for _, keystring := range pgpKeys { - data, err := base64.StdEncoding.DecodeString(keystring) - if err != nil { - return nil, errwrap.Wrapf("error decoding given PGP key: {{err}}", err) - } - entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(data))) - if err != nil { - return nil, errwrap.Wrapf("error parsing given PGP key: {{err}}", err) - } - ret = append(ret, entity) - } - return ret, nil -} - -// DecryptBytes takes in base64-encoded encrypted bytes and the base64-encoded -// private key and decrypts it. A bytes.Buffer is returned to allow the caller -// to do useful thing with it (get it as a []byte, get it as a string, use it -// as an io.Reader, etc), and also because this function doesn't know if what -// comes out is binary data or a string, so let the caller decide. -func DecryptBytes(encodedCrypt, privKey string) (*bytes.Buffer, error) { - privKeyBytes, err := base64.StdEncoding.DecodeString(privKey) - if err != nil { - return nil, errwrap.Wrapf("error decoding base64 private key: {{err}}", err) - } - - cryptBytes, err := base64.StdEncoding.DecodeString(encodedCrypt) - if err != nil { - return nil, errwrap.Wrapf("error decoding base64 crypted bytes: {{err}}", err) - } - - entity, err := openpgp.ReadEntity(packet.NewReader(bytes.NewBuffer(privKeyBytes))) - if err != nil { - return nil, errwrap.Wrapf("error parsing private key: {{err}}", err) - } - - entityList := &openpgp.EntityList{entity} - md, err := openpgp.ReadMessage(bytes.NewBuffer(cryptBytes), entityList, nil, nil) - if err != nil { - return nil, errwrap.Wrapf("error decrypting the messages: {{err}}", err) - } - - ptBuf := bytes.NewBuffer(nil) - ptBuf.ReadFrom(md.UnverifiedBody) - - return ptBuf, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/pgpkeys/flag.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/flag.go deleted file mode 100644 index bb0f367d6bf..00000000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/flag.go +++ /dev/null @@ -1,140 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "errors" - "fmt" - "os" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/keybase/go-crypto/openpgp" -) - -// PubKeyFileFlag implements flag.Value and command.Example to receive exactly -// one PGP or keybase key via a flag. -type PubKeyFileFlag string - -func (p *PubKeyFileFlag) String() string { return string(*p) } - -func (p *PubKeyFileFlag) Set(val string) error { - if p != nil && *p != "" { - return errors.New("can only be specified once") - } - - keys, err := ParsePGPKeys(strings.Split(val, ",")) - if err != nil { - return err - } - - if len(keys) > 1 { - return errors.New("can only specify one pgp key") - } - - *p = PubKeyFileFlag(keys[0]) - return nil -} - -func (p *PubKeyFileFlag) Example() string { return "keybase:user" } - -// PGPPubKeyFiles implements the flag.Value interface and allows parsing and -// reading a list of PGP public key files. -type PubKeyFilesFlag []string - -func (p *PubKeyFilesFlag) String() string { - return fmt.Sprint(*p) -} - -func (p *PubKeyFilesFlag) Set(val string) error { - if len(*p) > 0 { - return errors.New("can only be specified once") - } - - keys, err := ParsePGPKeys(strings.Split(val, ",")) - if err != nil { - return err - } - - *p = PubKeyFilesFlag(keys) - return nil -} - -func (p *PubKeyFilesFlag) Example() string { return "keybase:user1, keybase:user2, ..." } - -// ParsePGPKeys takes a list of PGP keys and parses them either using keybase -// or reading them from disk and returns the "expanded" list of pgp keys in -// the same order. -func ParsePGPKeys(keyfiles []string) ([]string, error) { - keys := make([]string, len(keyfiles)) - - keybaseMap, err := FetchKeybasePubkeys(keyfiles) - if err != nil { - return nil, err - } - - for i, keyfile := range keyfiles { - keyfile = strings.TrimSpace(keyfile) - - if strings.HasPrefix(keyfile, kbPrefix) { - key, ok := keybaseMap[keyfile] - if !ok || key == "" { - return nil, fmt.Errorf("keybase user %q not found", strings.TrimPrefix(keyfile, kbPrefix)) - } - keys[i] = key - continue - } - - pgpStr, err := ReadPGPFile(keyfile) - if err != nil { - return nil, err - } - keys[i] = pgpStr - } - - return keys, nil -} - -// ReadPGPFile reads the given PGP file from disk. -func ReadPGPFile(path string) (string, error) { - if path[0] == '@' { - path = path[1:] - } - f, err := os.Open(path) - if err != nil { - return "", err - } - defer f.Close() - buf := bytes.NewBuffer(nil) - _, err = buf.ReadFrom(f) - if err != nil { - return "", err - } - - // First parse as an armored keyring file, if that doesn't work, treat it as a straight binary/b64 string - keyReader := bytes.NewReader(buf.Bytes()) - entityList, err := openpgp.ReadArmoredKeyRing(keyReader) - if err == nil { - if len(entityList) != 1 { - return "", fmt.Errorf("more than one key found in file %q", path) - } - if entityList[0] == nil { - return "", fmt.Errorf("primary key was nil for file %q", path) - } - - serializedEntity := bytes.NewBuffer(nil) - err = entityList[0].Serialize(serializedEntity) - if err != nil { - return "", errwrap.Wrapf(fmt.Sprintf("error serializing entity for file %q: {{err}}", path), err) - } - - return base64.StdEncoding.EncodeToString(serializedEntity.Bytes()), nil - } - - _, err = base64.StdEncoding.DecodeString(buf.String()) - if err == nil { - return buf.String(), nil - } - return base64.StdEncoding.EncodeToString(buf.Bytes()), nil - -} diff --git a/vendor/github.com/hashicorp/vault/helper/pgpkeys/keybase.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/keybase.go deleted file mode 100644 index eba06776232..00000000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/keybase.go +++ /dev/null @@ -1,117 +0,0 @@ -package pgpkeys - -import ( - "bytes" - "encoding/base64" - "fmt" - "strings" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/go-cleanhttp" - "github.com/hashicorp/vault/helper/jsonutil" - "github.com/keybase/go-crypto/openpgp" -) - -const ( - kbPrefix = "keybase:" -) - -// FetchKeybasePubkeys fetches public keys from Keybase given a set of -// usernames, which are derived from correctly formatted input entries. It -// doesn't use their client code due to both the API and the fact that it is -// considered alpha and probably best not to rely on it. The keys are returned -// as base64-encoded strings. -func FetchKeybasePubkeys(input []string) (map[string]string, error) { - client := cleanhttp.DefaultClient() - if client == nil { - return nil, fmt.Errorf("unable to create an http client") - } - - if len(input) == 0 { - return nil, nil - } - - usernames := make([]string, 0, len(input)) - for _, v := range input { - if strings.HasPrefix(v, kbPrefix) { - usernames = append(usernames, strings.TrimPrefix(v, kbPrefix)) - } - } - - if len(usernames) == 0 { - return nil, nil - } - - ret := make(map[string]string, len(usernames)) - url := fmt.Sprintf("https://keybase.io/_/api/1.0/user/lookup.json?usernames=%s&fields=public_keys", strings.Join(usernames, ",")) - resp, err := client.Get(url) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - type PublicKeys struct { - Primary struct { - Bundle string - } - } - - type LThem struct { - PublicKeys `json:"public_keys"` - } - - type KbResp struct { - Status struct { - Name string - } - Them []LThem - } - - out := &KbResp{ - Them: []LThem{}, - } - - if err := jsonutil.DecodeJSONFromReader(resp.Body, out); err != nil { - return nil, err - } - - if out.Status.Name != "OK" { - return nil, fmt.Errorf("got non-OK response: %q", out.Status.Name) - } - - missingNames := make([]string, 0, len(usernames)) - var keyReader *bytes.Reader - serializedEntity := bytes.NewBuffer(nil) - for i, themVal := range out.Them { - if themVal.Primary.Bundle == "" { - missingNames = append(missingNames, usernames[i]) - continue - } - keyReader = bytes.NewReader([]byte(themVal.Primary.Bundle)) - entityList, err := openpgp.ReadArmoredKeyRing(keyReader) - if err != nil { - return nil, err - } - if len(entityList) != 1 { - return nil, fmt.Errorf("primary key could not be parsed for user %q", usernames[i]) - } - if entityList[0] == nil { - return nil, fmt.Errorf("primary key was nil for user %q", usernames[i]) - } - - serializedEntity.Reset() - err = entityList[0].Serialize(serializedEntity) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("error serializing entity for user %q: {{err}}", usernames[i]), err) - } - - // The API returns values in the same ordering requested, so this should properly match - ret[kbPrefix+usernames[i]] = base64.StdEncoding.EncodeToString(serializedEntity.Bytes()) - } - - if len(missingNames) > 0 { - return nil, fmt.Errorf("unable to fetch keys for user(s) %q from keybase", strings.Join(missingNames, ",")) - } - - return ret, nil -} diff --git a/vendor/github.com/hashicorp/vault/helper/pgpkeys/test_keys.go b/vendor/github.com/hashicorp/vault/helper/pgpkeys/test_keys.go deleted file mode 100644 index c10a9055ed0..00000000000 --- a/vendor/github.com/hashicorp/vault/helper/pgpkeys/test_keys.go +++ /dev/null @@ -1,271 +0,0 @@ -package pgpkeys - -const ( - TestPrivKey1 = `lQOYBFXbjPUBCADjNjCUQwfxKL+RR2GA6pv/1K+zJZ8UWIF9S0lk7cVIEfJiprzzwiMwBS5cD0da -rGin1FHvIWOZxujA7oW0O2TUuatqI3aAYDTfRYurh6iKLC+VS+F7H+/mhfFvKmgr0Y5kDCF1j0T/ -063QZ84IRGucR/X43IY7kAtmxGXH0dYOCzOe5UBX1fTn3mXGe2ImCDWBH7gOViynXmb6XNvXkP0f -sF5St9jhO7mbZU9EFkv9O3t3EaURfHopsCVDOlCkFCw5ArY+DUORHRzoMX0PnkyQb5OzibkChzpg -8hQssKeVGpuskTdz5Q7PtdW71jXd4fFVzoNH8fYwRpziD2xNvi6HABEBAAEAB/wL+KX0mdeISEpX -oDgt766Key1Kthe8nbEs5dOXIsP7OR7ZPcnE2hy6gftgVFnBGEZnWVN70vmJd6Z5y9d1mI+GecXj -UL0EpI0EmohyYDJsHUnght/5ecRNFA+VeNmGPYNQGCeHJyZOiFunGGENpHU7BbubAht8delz37Mx -JQgvMyR6AKvg8HKBoQeqV1uMWNJE/vKwV/z1dh1sjK/GFxu05Qaq0GTfAjVLuFOyJTS95yq6gblD -jUdbHLp7tBeqIKo9voWCJF5mGOlq3973vVoWETy9b0YYPCE/M7fXmK9dJITHqkROLMW6TgcFeIw4 -yL5KOBCHk+QGPSvyQN7R7Fd5BADwuT1HZmvg7Y9GjarKXDjxdNemUiHtba2rUzfH6uNmKNQvwQek -nma5palNUJ4/dz1aPB21FUBXJF5yWwXEdApl+lIDU0J5m4UD26rqEVRq9Kx3GsX+yfcwObkrSzW6 -kmnQSB5KI0fIuegMTM+Jxo3pB/mIRwDTMmk+vfzIGyW+7QQA8aFwFLMdKdfLgSGbl5Z6etmOAVQ2 -Oe2ebegU9z/ewi/Rdt2s9yQiAdGVM8+q15Saz8a+kyS/l1CjNPzr3VpYx1OdZ3gb7i2xoy9GdMYR -ZpTq3TuST95kx/9DqA97JrP23G47U0vwF/cg8ixCYF8Fz5dG4DEsxgMwKqhGdW58wMMD/iytkfMk -Vk6Z958Rpy7lhlC6L3zpO38767bSeZ8gRRi/NMFVOSGYepKFarnfxcTiNa+EoSVA6hUo1N64nALE -sJBpyOoTfKIpz7WwTF1+WogkiYrfM6lHon1+3qlziAcRW0IohM3g2C1i3GWdON4Cl8/PDO3R0E52 -N6iG/ctNNeMiPe60EFZhdWx0IFRlc3QgS2V5IDGJATgEEwECACIFAlXbjPUCGy8GCwkIBwMCBhUI -AgkKCwQWAgMBAh4BAheAAAoJEOfLr44BHbeTo+sH/i7bapIgPnZsJ81hmxPj4W12uvunksGJiC7d -4hIHsG7kmJRTJfjECi+AuTGeDwBy84TDcRaOB6e79fj65Fg6HgSahDUtKJbGxj/lWzmaBuTzlN3C -Ee8cMwIPqPT2kajJVdOyrvkyuFOdPFOEA7bdCH0MqgIdM2SdF8t40k/ATfuD2K1ZmumJ508I3gF3 -9jgTnPzD4C8quswrMQ3bzfvKC3klXRlBC0yoArn+0QA3cf2B9T4zJ2qnvgotVbeK/b1OJRNj6Poe -o+SsWNc/A5mw7lGScnDgL3yfwCm1gQXaQKfOt5x+7GqhWDw10q+bJpJlI10FfzAnhMF9etSqSeUR -BRWdA5gEVduM9QEIAL53hJ5bZJ7oEDCnaY+SCzt9QsAfnFTAnZJQrvkvusJzrTQ088eUQmAjvxkf -Rqnv981fFwGnh2+I1Ktm698UAZS9Jt8yjak9wWUICKQO5QUt5k8cHwldQXNXVXFa+TpQWQR5yW1a -9okjh5o/3d4cBt1yZPUJJyLKY43Wvptb6EuEsScO2DnRkh5wSMDQ7dTooddJCmaq3LTjOleRFQbu -9ij386Do6jzK69mJU56TfdcydkxkWF5NZLGnED3lq+hQNbe+8UI5tD2oP/3r5tXKgMy1R/XPvR/z -bfwvx4FAKFOP01awLq4P3d/2xOkMu4Lu9p315E87DOleYwxk+FoTqXEAEQEAAQAH+wVyQXaNwnjQ -xfW+M8SJNo0C7e+0d7HsuBTA/d/eP4bj6+X8RaRFVwiMvSAoxsqBNCLJP00qzzKfRQWJseD1H35z -UjM7rNVUEL2k1yppyp61S0qj0TdhVUfJDYZqRYonVgRMvzfDTB1ryKrefKenQYL/jGd9VYMnKmWZ -6GVk4WWXXx61iOt2HNcmSXKetMM1Mg67woPZkA3fJaXZ+zW0zMu4lTSB7yl3+vLGIFYILkCFnREr -drQ+pmIMwozUAt+pBq8dylnkHh6g/FtRfWmLIMDqM1NlyuHRp3dyLDFdTA93osLG0QJblfX54W34 -byX7a4HASelGi3nPjjOAsTFDkuEEANV2viaWk1CV4ryDrXGmy4Xo32Md+laGPRcVfbJ0mjZjhQsO -gWC1tjMs1qZMPhcrKIBCjjdAcAIrGV9h3CXc0uGuez4XxLO+TPBKaS0B8rKhnKph1YZuf+HrOhzS -astDnOjNIT+qucCL/qSbdYpj9of3yY61S59WphPOBjoVM3BFBADka6ZCk81gx8jA2E1e9UqQDmdM -FZaVA1E7++kqVSFRDJGnq+5GrBTwCJ+sevi+Rvf8Nx4AXvpCdtMBPX9RogsUFcR0pMrKBrgRo/Vg -EpuodY2Ef1VtqXR24OxtRf1UwvHKydIsU05rzMAy5uGgQvTzRTXxZFLGUY31wjWqmo9VPQP+PnwA -K83EV2kk2bsXwZ9MXg05iXqGQYR4bEc/12v04BtaNaDS53hBDO4JIa3Bnz+5oUoYhb8FgezUKA9I -n6RdKTTP1BLAu8titeozpNF07V++dPiSE2wrIVsaNHL1pUwW0ql50titVwe+EglWiCKPtJBcCPUA -3oepSPchiDjPqrNCYIkCPgQYAQIACQUCVduM9QIbLgEpCRDny6+OAR23k8BdIAQZAQIABgUCVduM -9QAKCRAID0JGyHtSGmqYB/4m4rJbbWa7dBJ8VqRU7ZKnNRDR9CVhEGipBmpDGRYulEimOPzLUX/Z -XZmTZzgemeXLBaJJlWnopVUWuAsyjQuZAfdd8nHkGRHG0/DGum0l4sKTta3OPGHNC1z1dAcQ1RCr -9bTD3PxjLBczdGqhzw71trkQRBRdtPiUchltPMIyjUHqVJ0xmg0hPqFic0fICsr0YwKoz3h9+QEc -ZHvsjSZjgydKvfLYcm+4DDMCCqcHuJrbXJKUWmJcXR0y/+HQONGrGJ5xWdO+6eJioPn2jVMnXCm4 -EKc7fcLFrz/LKmJ8seXhxjM3EdFtylBGCrx3xdK0f+JDNQaC/rhUb5V2XuX6VwoH/AtY+XsKVYRf -NIupLOUcf/srsm3IXT4SXWVomOc9hjGQiJ3rraIbADsc+6bCAr4XNZS7moViAAcIPXFv3m3WfUln -G/om78UjQqyVACRZqqAGmuPq+TSkRUCpt9h+A39LQWkojHqyob3cyLgy6z9Q557O9uK3lQozbw2g -H9zC0RqnePl+rsWIUU/ga16fH6pWc1uJiEBt8UZGypQ/E56/343epmYAe0a87sHx8iDV+dNtDVKf -PRENiLOOc19MmS+phmUyrbHqI91c0pmysYcJZCD3a502X1gpjFbPZcRtiTmGnUKdOIu60YPNE4+h -7u2CfYyFPu3AlUaGNMBlvy6PEpU=` - - TestPrivKey2 = `lQOYBFXbkJEBCADKb1ZvlT14XrJa2rTOe5924LQr2PTZlRv+651TXy33yEhelZ+V4sMrELN8fKEG -Zy1kNixmbq3MCF/671k3LigHA7VrOaH9iiQgr6IIq2MeIkUYKZ27C992vQkYLjbYUG8+zl5h69S4 -0Ixm0yL0M54XOJ0gm+maEK1ZESKTUlDNkIS7l0jLZSYwfUeGXSEt6FWs8OgbyRTaHw4PDHrDEE9e -Q67K6IZ3YMhPOL4fVk4Jwrp5R/RwiklT+lNozWEyFVwPFH4MeQMs9nMbt+fWlTzEA7tI4acI9yDk -Cm1yN2R9rmY0UjODRiJw6z6sLV2T+Pf32n3MNSUOYczOjZa4VBwjABEBAAEAB/oCBqTIsxlUgLtz -HRpWW5MJ+93xvmVV0JHhRK/ygKghq+zpC6S+cn7dwrEj1JTPh+17lyemYQK+RMeiBEduoWNKuHUd -WX353w2411rrc/VuGTglzhd8Ir2BdJlPesCzw4JQnrWqcBqN52W+iwhnE7PWVhnvItWnx6APK5Se -q7dzFWy8Z8tNIHm0pBQbeyo6x2rHHSWkr2fs7V02qFQhii1ayFRMcgdOWSNX6CaZJuYhk/DyjApN -9pVhi3P1pNMpFeV0Pt8Gl1f/9o6/HpAYYEt/6vtVRhFUGgtNi95oc0oyzIJxliRvd6+Z236osigQ -QEBwj1ImRK8TKyWPlykiJWc5BADfldgOCA55o3Qz/z/oVE1mm+a3FmPPTQlHBXotNEsrWV2wmJHe -lNQPI6ZwMtLrBSg8PUpG2Rvao6XJ4ZBl/VcDwfcLgCnALPCcL0L0Z3vH3Sc9Ta/bQWJODG7uSaI1 -iVJ7ArKNtVzTqRQWK967mol9CCqh4A0jRrH0aVEFbrqQ/QQA58iEJaFhzFZjufjC9N8Isn3Ky7xu -h+dk001RNCb1GnNZcx4Ld2IB+uXyYjtg7dNaUhGgGuCBo9nax89bMsBzzUukx3SHq1pxopMg6Dm8 -ImBoIAicuQWgEkaP2T0rlwCozUalJZaG1gyrzkPhkeY7CglpJycHLHfY2MIb46c8+58D/iJ83Q5j -Y4x+sqW2QeUYFwqCcOW8Urg64UxEkgXZXiNMwTAJCaxp/Pz7cgeUDwgv+6CXEdnT1910+byzK9ha -V1Q/65+/JYuCeyHxcoAb4Wtpdl7GALGd/1G0UAmq47yrefEr/b00uS35i1qUUhOzo1NmEZch/bvF -kmJ+WtAHunZcOCu0EFZhdWx0IFRlc3QgS2V5IDKJATgEEwECACIFAlXbkJECGy8GCwkIBwMCBhUI -AgkKCwQWAgMBAh4BAheAAAoJEOuDLGfrXolXqz4H/28IuoRxGKoJ064YHjPkkpoddW6zdzzNfHip -ZnNfEUiTEls4qF1IB81M2xqfiXIFRIdO2kaLkRPFhO0hRxbtI6VuZYLgG3QCaXhxW6GyFa5zKABq -hb5ojexdnAYRswaHV201ZCclj9rnJN1PAg0Rz6MdX/w1euEWktQxWKo42oZKyx8oT9p6lrv5KRmG -kdrg8K8ARmRILjmwuBAgJM0eXBZHNGWXelk4YmOgnAAcZA6ZAo1G+8Pg6pKKP61ETewuCg3/u7N0 -vDttB+ZXqF88W9jAYlvdgbTtajNF5IDYDjTzWfeCaIB18F9gOzXq15SwWeDDI+CU9Nmq358IzXlx -k4edA5gEVduQkQEIAOjZV5tbpfIh5QefpIp2dpGMVfpgPj4RNc15CyFnb8y6dhCrdybkY9GveXJe -4F3GNYnSfB42cgxrfhizX3LakmZQ/SAg+YO5KxfCIN7Q9LPNeTgPsZZT6h8lVuXUxOFKXfRaR3/t -GF5xE3e5CoZRsHV/c92h3t1LdJNOnC5mUKIPO4zDxiw/C2T2q3rP1kmIMaOH724kEH5A+xcp1cBH -yt0tdHtIWuQv6joTJzujqViRhlCwQYzQSKpSBxwhBsorPvyinZI/ZXA4XXZc5RoMqV9rikedrb1r -ENO8JOuPu6tMS+znFu67skq2gFFZwCQWIjdHm+2ukE+PE580WAWudyMAEQEAAQAH/i7ndRPI+t0T -AdEu0dTIdyrrg3g7gd471kQtIVZZwTYSy2yhNY/Ciu72s3ab8QNCxY8dNL5bRk8FKjHslAoNSFdO -8iZSLiDgIHOZOcjYe6pqdgQaeTHodm1Otrn2SbB+K/3oX6W/y1xe18aSojGba/nHMj5PeJbIN9Pi -jmh0WMLD/0rmkTTxR7qQ5+kMV4O29xY4qjdYRD5O0adeZX0mNncmlmQ+rX9yxrtSgFROu1jwVtfP -hcNetifTTshJnTwND8hux5ECEadlIVBHypW28Hth9TRBXmddTmv7L7mdtUO6DybgkpWpw4k4LPsk -uZ6aY4wcGRp7EVfWGr9NHbq/n+0EAOlhDXIGdylkQsndjBMyhPsXZa5fFBmOyHjXj733195Jgr1v -ZjaIomrA9cvYrmN75oKrG1jJsMEl6HfC/ZPzEj6E51/p1PRdHP7CdUUA+DG8x4M3jn+e43psVuAR -a1XbN+8/bOa0ubt7ljVPjAEvWRSvU9dRaQz93w3fduAuM07dBAD/ayK3e0d6JMJMrU50lNOXQBgL -rFbg4rWzPO9BJQdhjOhmOZQiUa1Q+EV+s95yIUg1OAfaMP9KRIljr5RCdGNS6WoMNBAQOSrZpelf -jW4NpzphNfWDGVkUoPoskVtJz/nu9d860dGd3Al0kSmtUpMu5QKlo+sSxXUPbWLUn8V9/wP/ScCW -H+0gtL4R7SFazPeTIP+Cu5oR7A/DlFVLJKa3vo+atkhSvwxHGbg04vb/W4mKhGGVtMBtlhRmaWOe -PhUulU5FdaYsdlpN/Yd+hhgU6NHlyImPGVEHWD8c6CG8qoZfpR33j2sqshs4i/MtJZeBvl62vxPn -9bDN7KAjFNll9axAjIkCPgQYAQIACQUCVduQkQIbLgEpCRDrgyxn616JV8BdIAQZAQIABgUCVduQ -kQAKCRArYtevdF38xtzgB/4zVzozBpVOnagRkA7FDsHo36xX60Lik+ew0m28ueDDhnV3bXQsCvn/ -6wiCVWqLOTDeYCPlyTTpEMyk8zwdCICW6MgSkVHWcEDOrRqIrqm86rirjTGjJSgQe3l4CqJvkn6j -ybShYoBk1OZZV6vVv9hPTXXv9E6dLKoEW5YZBrrF+VC0w1iOIvaAQ+QXph20eV4KBIrp/bhG6Pdn -igKxuBZ79cdqDnXIzT9UiIa6LYpR0rbeg+7BmuZTTPS8t+41hIiKS+UZFdKa67eYENtyOmEMWOFC -LLRJGxkleukchiMJ70rknloZXsvJIweXBzSZ6m7mJQBgaig/L/dXyjv6+j2pNB4H/1trYUtJjXQK -HmqlgCmpCkHt3g7JoxWvglnDNmE6q3hIWuVIYQpnzZy1g05+X9Egwc1WVpBB02H7PkUZTfpaP/L6 -DLneMmSKPhZE3I+lPIPjwrxqh6xy5uQezcWkJTNKvPWF4FJzrVvx7XTPjfGvOB0UPEnjvtZTp5yO -hTeZK7DgIEtb/Wcrqs+iRArQKboM930ORSZhwvGK3F9V/gMDpIrvge5vDFsTEYQdw/2epIewH0L/ -FUb/6jBRcVEpGo9Ayg+Jnhq14GOGcd1y9oMZ48kYVLVBTA9tQ+82WE8Bch7uFPj4MFOMVRn1dc3q -dXlg3mimA+iK7tABQfG0RJ9YzWs=` - - TestPrivKey3 = `lQOXBFXbkiMBCACiHW4/VI2JkfvSEINddS7vE6wEu5e1leNQDaLUh6PrATQZS2a4Q6kRE6WlJumj -6wCeN753Cm93UGQl2Bi3USIEeArIZnPTcocrckOVXxtoLBNKXgqKvEsDXgfw8A+doSfXoDm/3Js4 -Wy3WsYKNR9LaPuJZHnpjsFAJhvRVyhH4UFD+1RTSSefq1mozPfDdMoZeZNEpfhwt3DuTJs7RqcTH -CgR2CqhEHnOOE5jJUljHKYLCglE2+8dth1bZlQi4xly/VHZzP3Bn7wKeolK/ROP6VZz/e0xq/BKy -resmxvlBWZ1zWwqGIrV9b0uwYvGrh2hOd5C5+5oGaA2MGcjxwaLBABEBAAEAB/dQbElFIa0VklZa -39ZLhtbBxACSWH3ql3EtRZaB2Mh4zSALbFyJDQfScOy8AZHmv66Ozxit9X9WsYr9OzcHujgl/2da -A3lybF6iLw1YDNaL11G6kuyn5sFP6lYGMRGOIWSik9oSVF6slo8m8ujRLdBsdMXVcElHKzCJiWmt -JZHEnUkl9X96fIPajMBfWjHHwcaeMOc77nvjwqy5wC4EY8TSVYzxeZHL7DADQ0EHBcThlmfizpCq -26LMVb6ju8STH7uDDFyKmhr/hC2vOkt+PKsvBCmW8/ESanO1zKPD9cvSsOWr2rZWNnkDRftqzOU5 -OCrI+3o9E74+toNb07bPntEEAMEStOzSvqZ6NKdh7EZYPA4mkkFC+EiHYIoinP1sd9V8O2Hq+dzx -yFHtWu0LmP6uWXk45vsP9y1UMJcEa33ew5JJa7zgucI772/BNvd/Oys/PqwIAl6uNIY8uYLgmn4L -1IPatp7vDiXzZSivPZd4yN4S4zCypZp9cnpO3qv8q7CtBADW87IA0TabdoxiN+m4XL7sYDRIfglr -MRPAlfrkAUaGDBx/t1xb6IaKk7giFdwHpTI6+g9XNkqKqogMe4Fp+nsd1xtfsNUBn6iKZavm5kXe -Lp9QgE+K6mvIreOTe2PKQqXqgPRG6+SRGatoKeY76fIpd8AxOJyWERxcq2lUHLn45QP/UXDTcYB7 -gzJtZrfpXN0GqQ0lYXMzbQfLnkUsu3mYzArfNy0otzEmKTkwmKclNY1/EJSzSdHfgmeA260a0nLK -64C0wPgSmOqw90qwi5odAYSjSFBapDbyGF86JpHrLxyEEpGoXanRPwWfbiWp19Nwg6nknA87AtaM -3+AHjbWzwCpHL7QQVmF1bHQgVGVzdCBLZXkgM4kBOAQTAQIAIgUCVduSIwIbLwYLCQgHAwIGFQgC -CQoLBBYCAwECHgECF4AACgkQ9HlLVvwtxt1aMQf/aaGoL1rRWTUjM6DEShXFhWpV29rEjSdNk5N+ -ZwVifgdCVD5IsSjI1Z7mO2SHHiTm4eKnHAofM6/TZgzXg1YLpu8rDYJARMsM8bgK/xgxSamGjm2c -wN220jOnwePIlG0drNTW5N6zb/K6qHoscJ6NUkjS5JPdGJuq7B0bdCM8/xSbG75gL34U5bYqK38B -DwmW4UMl2rf/BJfxV9hmsZ2Cat4TspgyiWEKTMZI+PugXKDDwuoqgm+320K4EqFkwG4y/WwHkKgk -hZ0+io5lzhTsvVd2p8q8VlH9GG5eA3WWQj0yqucsOmKQvcuT5y0vFY6NQJbyuioqgdlgEXtc+p0B -+Z0DmARV25IjAQgA49yN3hCBsuWoiTezoE9FHJXOCVOBR1/4jStQPJtoMl8mhtl3xTp7iGQ+9GhD -y0l5+fP+qcP/rfBq0BslhxVOZ7jQjdUoM6ZUZzJoPGIo/V2KwqpwQl3tdCIjvagCJeYQfTL7lTCc -4ySz+XBoAYMwZVGMcRcjp+JE8Wx9Ovzuq8wnelbU6I5dVJ7O4E1OWbIkLuytDX+fDEvfft6/oPXN -Bl3cm6FzEuQetQQss3DOG9xnvS+DrjmMCbPwR2a++ioQ8+geoqA/kB4cAI6xOb3ncoeGDHc1i4Y9 -T9Ggi+6Aq3girmfDtNYVOM8cZUXcZNCvLkJn8DNeIvnuFUSEO+a5PwARAQABAAf/TPd98CmRNdV/ -VUI8aYT9Kkervdi4DVzsfvrHcoFn88PSJrCkVTmI6qw526Kwa6VZD0YMmll7LszLt5nD1lorDrwN -rir3FmMzlVwge20IvXRwX4rkunYxtA2oFvL+LsEEhtXGx0ERbWRDapk+eGxQ15hxIO4Y/Cdg9E+a -CWfQUrTSnC6qMVfVYMGfnM1yNX3OWattEFfmxQas5XqQk/0FgjCZALixdanjN/r1tjp5/2MiSD8N -Wkemzsr6yPicnc3+BOZc5YOOnH8FqBvVHcDlSJI6pCOCEiO3Pq2QEk/1evONulbF116mLnQoGrpp -W77l+5O42VUpZfjROCPd5DYyMQQA492CFXZpDIJ2emB9/nK8X6IzdVRK3oof8btbSNnme5afIzhs -wR1ruX30O7ThfB+5ezpbgK1C988CWkr9SNSTy43omarafGig6/Y1RzdiITILuIGfbChoSpc70jXx -U0nzJ/1i9yZ/vDgP3EC2miRhlDcp5w0Bu0oMBlgG/1uhj0cEAP/+7aFGP0fo2MZPhyl5feHKWj4k -85XoAIpMBnzF6HTGU3ljAE56a+4sVw3bWB755DPhvpZvDkX60I9iIJxio8TK5ITdfjlLhxuskXyt -ycwWI/4J+soeq4meoxK9jxZJuDl/qvoGfyzNg1oy2OBehX8+6erW46kr6Z/MQutS3zJJBACmJHrK -VR40qD7a8KbvfuM3ruwlm5JqT/Ykq1gfKKxHjWDIUIeyBX/axGQvAGNYeuuQCzZ0+QsEWur3C4kN -U+Pb5K1WGyOKkhJzivSI56AG3d8TA/Q0JhqST6maY0fvUoahWSCcpd7MULa3n1zx5Wsvi8mkVtup -Js/IDi/kqneqM0XviQI+BBgBAgAJBQJV25IjAhsuASkJEPR5S1b8LcbdwF0gBBkBAgAGBQJV25Ij -AAoJEAUj/03Hcrkg84UIAKxn9nizYtwSgDnVNb5PnD5h6+Ui6r7ffYm2o0im4YhakbFTHIPI9PRh -BavRI5sE5Fg2vtE/x38jattoUrJoNoq9Gh9iv5PBfL3amEGjul0RRqYGl+ub+yv7YGAAHbHcdZen -4gx15VWGpB7y3hycWbdzV8h3EAPKIm5XmB7YyXmArnI3CoJA+HtTZGoL6WZWUwka9YichGfaZ/oD -umENg1l87Pp2RqvjLKHmv2tGCtnDzyv/IiWur9zopFQiCc8ysVgRq6CA5x5nzbv6MqRspYUS4e2I -LFbuREA3blR+caw9oX41IYzarW8IbgeIXJ3HqUyhczRKF/z5nDKtX/kHMCqlbAgAnfu0TALnwVuj -KeXLo4Y7OA9LTEqfORcw62q5OjSoQf/VsRSwGSefv3kGZk5N/igELluU3qpG/twZI/TSL6zGqXU2 -FOMlyMm1849TOB9b4B//4dHrjzPhztzowKMMUqeTxmSgYtFTshKN6eQ0XO+7ZuOXEmSKXS4kOUs9 -ttfzSiPNXUZL2D5nFU9H7rw3VAuXYVTrOx+Dfi6mYsscbxUbi8THODI2Q7B9Ni92DJE1OOe4+57o -fXZ9ln24I14bna/uVHd6hBwLEE6eLCCKkHxQnnZFZduXDHMK0a0OL8RYHfMtNSem4pyC5wDQui1u -KFIzGEPKVoBF9U7VBXpyxpsz+A==` - - TestPubKey1 = `mQENBFXbjPUBCADjNjCUQwfxKL+RR2GA6pv/1K+zJZ8UWIF9S0lk7cVIEfJiprzzwiMwBS5cD0da -rGin1FHvIWOZxujA7oW0O2TUuatqI3aAYDTfRYurh6iKLC+VS+F7H+/mhfFvKmgr0Y5kDCF1j0T/ -063QZ84IRGucR/X43IY7kAtmxGXH0dYOCzOe5UBX1fTn3mXGe2ImCDWBH7gOViynXmb6XNvXkP0f -sF5St9jhO7mbZU9EFkv9O3t3EaURfHopsCVDOlCkFCw5ArY+DUORHRzoMX0PnkyQb5OzibkChzpg -8hQssKeVGpuskTdz5Q7PtdW71jXd4fFVzoNH8fYwRpziD2xNvi6HABEBAAG0EFZhdWx0IFRlc3Qg -S2V5IDGJATgEEwECACIFAlXbjPUCGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEOfLr44B -HbeTo+sH/i7bapIgPnZsJ81hmxPj4W12uvunksGJiC7d4hIHsG7kmJRTJfjECi+AuTGeDwBy84TD -cRaOB6e79fj65Fg6HgSahDUtKJbGxj/lWzmaBuTzlN3CEe8cMwIPqPT2kajJVdOyrvkyuFOdPFOE -A7bdCH0MqgIdM2SdF8t40k/ATfuD2K1ZmumJ508I3gF39jgTnPzD4C8quswrMQ3bzfvKC3klXRlB -C0yoArn+0QA3cf2B9T4zJ2qnvgotVbeK/b1OJRNj6Poeo+SsWNc/A5mw7lGScnDgL3yfwCm1gQXa -QKfOt5x+7GqhWDw10q+bJpJlI10FfzAnhMF9etSqSeURBRW5AQ0EVduM9QEIAL53hJ5bZJ7oEDCn -aY+SCzt9QsAfnFTAnZJQrvkvusJzrTQ088eUQmAjvxkfRqnv981fFwGnh2+I1Ktm698UAZS9Jt8y -jak9wWUICKQO5QUt5k8cHwldQXNXVXFa+TpQWQR5yW1a9okjh5o/3d4cBt1yZPUJJyLKY43Wvptb -6EuEsScO2DnRkh5wSMDQ7dTooddJCmaq3LTjOleRFQbu9ij386Do6jzK69mJU56TfdcydkxkWF5N -ZLGnED3lq+hQNbe+8UI5tD2oP/3r5tXKgMy1R/XPvR/zbfwvx4FAKFOP01awLq4P3d/2xOkMu4Lu -9p315E87DOleYwxk+FoTqXEAEQEAAYkCPgQYAQIACQUCVduM9QIbLgEpCRDny6+OAR23k8BdIAQZ -AQIABgUCVduM9QAKCRAID0JGyHtSGmqYB/4m4rJbbWa7dBJ8VqRU7ZKnNRDR9CVhEGipBmpDGRYu -lEimOPzLUX/ZXZmTZzgemeXLBaJJlWnopVUWuAsyjQuZAfdd8nHkGRHG0/DGum0l4sKTta3OPGHN -C1z1dAcQ1RCr9bTD3PxjLBczdGqhzw71trkQRBRdtPiUchltPMIyjUHqVJ0xmg0hPqFic0fICsr0 -YwKoz3h9+QEcZHvsjSZjgydKvfLYcm+4DDMCCqcHuJrbXJKUWmJcXR0y/+HQONGrGJ5xWdO+6eJi -oPn2jVMnXCm4EKc7fcLFrz/LKmJ8seXhxjM3EdFtylBGCrx3xdK0f+JDNQaC/rhUb5V2XuX6VwoH -/AtY+XsKVYRfNIupLOUcf/srsm3IXT4SXWVomOc9hjGQiJ3rraIbADsc+6bCAr4XNZS7moViAAcI -PXFv3m3WfUlnG/om78UjQqyVACRZqqAGmuPq+TSkRUCpt9h+A39LQWkojHqyob3cyLgy6z9Q557O -9uK3lQozbw2gH9zC0RqnePl+rsWIUU/ga16fH6pWc1uJiEBt8UZGypQ/E56/343epmYAe0a87sHx -8iDV+dNtDVKfPRENiLOOc19MmS+phmUyrbHqI91c0pmysYcJZCD3a502X1gpjFbPZcRtiTmGnUKd -OIu60YPNE4+h7u2CfYyFPu3AlUaGNMBlvy6PEpU=` - - TestPubKey2 = `mQENBFXbkJEBCADKb1ZvlT14XrJa2rTOe5924LQr2PTZlRv+651TXy33yEhelZ+V4sMrELN8fKEG -Zy1kNixmbq3MCF/671k3LigHA7VrOaH9iiQgr6IIq2MeIkUYKZ27C992vQkYLjbYUG8+zl5h69S4 -0Ixm0yL0M54XOJ0gm+maEK1ZESKTUlDNkIS7l0jLZSYwfUeGXSEt6FWs8OgbyRTaHw4PDHrDEE9e -Q67K6IZ3YMhPOL4fVk4Jwrp5R/RwiklT+lNozWEyFVwPFH4MeQMs9nMbt+fWlTzEA7tI4acI9yDk -Cm1yN2R9rmY0UjODRiJw6z6sLV2T+Pf32n3MNSUOYczOjZa4VBwjABEBAAG0EFZhdWx0IFRlc3Qg -S2V5IDKJATgEEwECACIFAlXbkJECGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEOuDLGfr -XolXqz4H/28IuoRxGKoJ064YHjPkkpoddW6zdzzNfHipZnNfEUiTEls4qF1IB81M2xqfiXIFRIdO -2kaLkRPFhO0hRxbtI6VuZYLgG3QCaXhxW6GyFa5zKABqhb5ojexdnAYRswaHV201ZCclj9rnJN1P -Ag0Rz6MdX/w1euEWktQxWKo42oZKyx8oT9p6lrv5KRmGkdrg8K8ARmRILjmwuBAgJM0eXBZHNGWX -elk4YmOgnAAcZA6ZAo1G+8Pg6pKKP61ETewuCg3/u7N0vDttB+ZXqF88W9jAYlvdgbTtajNF5IDY -DjTzWfeCaIB18F9gOzXq15SwWeDDI+CU9Nmq358IzXlxk4e5AQ0EVduQkQEIAOjZV5tbpfIh5Qef -pIp2dpGMVfpgPj4RNc15CyFnb8y6dhCrdybkY9GveXJe4F3GNYnSfB42cgxrfhizX3LakmZQ/SAg -+YO5KxfCIN7Q9LPNeTgPsZZT6h8lVuXUxOFKXfRaR3/tGF5xE3e5CoZRsHV/c92h3t1LdJNOnC5m -UKIPO4zDxiw/C2T2q3rP1kmIMaOH724kEH5A+xcp1cBHyt0tdHtIWuQv6joTJzujqViRhlCwQYzQ -SKpSBxwhBsorPvyinZI/ZXA4XXZc5RoMqV9rikedrb1rENO8JOuPu6tMS+znFu67skq2gFFZwCQW -IjdHm+2ukE+PE580WAWudyMAEQEAAYkCPgQYAQIACQUCVduQkQIbLgEpCRDrgyxn616JV8BdIAQZ -AQIABgUCVduQkQAKCRArYtevdF38xtzgB/4zVzozBpVOnagRkA7FDsHo36xX60Lik+ew0m28ueDD -hnV3bXQsCvn/6wiCVWqLOTDeYCPlyTTpEMyk8zwdCICW6MgSkVHWcEDOrRqIrqm86rirjTGjJSgQ -e3l4CqJvkn6jybShYoBk1OZZV6vVv9hPTXXv9E6dLKoEW5YZBrrF+VC0w1iOIvaAQ+QXph20eV4K -BIrp/bhG6PdnigKxuBZ79cdqDnXIzT9UiIa6LYpR0rbeg+7BmuZTTPS8t+41hIiKS+UZFdKa67eY -ENtyOmEMWOFCLLRJGxkleukchiMJ70rknloZXsvJIweXBzSZ6m7mJQBgaig/L/dXyjv6+j2pNB4H -/1trYUtJjXQKHmqlgCmpCkHt3g7JoxWvglnDNmE6q3hIWuVIYQpnzZy1g05+X9Egwc1WVpBB02H7 -PkUZTfpaP/L6DLneMmSKPhZE3I+lPIPjwrxqh6xy5uQezcWkJTNKvPWF4FJzrVvx7XTPjfGvOB0U -PEnjvtZTp5yOhTeZK7DgIEtb/Wcrqs+iRArQKboM930ORSZhwvGK3F9V/gMDpIrvge5vDFsTEYQd -w/2epIewH0L/FUb/6jBRcVEpGo9Ayg+Jnhq14GOGcd1y9oMZ48kYVLVBTA9tQ+82WE8Bch7uFPj4 -MFOMVRn1dc3qdXlg3mimA+iK7tABQfG0RJ9YzWs=` - - TestPubKey3 = `mQENBFXbkiMBCACiHW4/VI2JkfvSEINddS7vE6wEu5e1leNQDaLUh6PrATQZS2a4Q6kRE6WlJumj -6wCeN753Cm93UGQl2Bi3USIEeArIZnPTcocrckOVXxtoLBNKXgqKvEsDXgfw8A+doSfXoDm/3Js4 -Wy3WsYKNR9LaPuJZHnpjsFAJhvRVyhH4UFD+1RTSSefq1mozPfDdMoZeZNEpfhwt3DuTJs7RqcTH -CgR2CqhEHnOOE5jJUljHKYLCglE2+8dth1bZlQi4xly/VHZzP3Bn7wKeolK/ROP6VZz/e0xq/BKy -resmxvlBWZ1zWwqGIrV9b0uwYvGrh2hOd5C5+5oGaA2MGcjxwaLBABEBAAG0EFZhdWx0IFRlc3Qg -S2V5IDOJATgEEwECACIFAlXbkiMCGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEPR5S1b8 -LcbdWjEH/2mhqC9a0Vk1IzOgxEoVxYVqVdvaxI0nTZOTfmcFYn4HQlQ+SLEoyNWe5jtkhx4k5uHi -pxwKHzOv02YM14NWC6bvKw2CQETLDPG4Cv8YMUmpho5tnMDdttIzp8HjyJRtHazU1uTes2/yuqh6 -LHCejVJI0uST3RibquwdG3QjPP8Umxu+YC9+FOW2Kit/AQ8JluFDJdq3/wSX8VfYZrGdgmreE7KY -MolhCkzGSPj7oFygw8LqKoJvt9tCuBKhZMBuMv1sB5CoJIWdPoqOZc4U7L1XdqfKvFZR/RhuXgN1 -lkI9MqrnLDpikL3Lk+ctLxWOjUCW8roqKoHZYBF7XPqdAfm5AQ0EVduSIwEIAOPcjd4QgbLlqIk3 -s6BPRRyVzglTgUdf+I0rUDybaDJfJobZd8U6e4hkPvRoQ8tJefnz/qnD/63watAbJYcVTme40I3V -KDOmVGcyaDxiKP1disKqcEJd7XQiI72oAiXmEH0y+5UwnOMks/lwaAGDMGVRjHEXI6fiRPFsfTr8 -7qvMJ3pW1OiOXVSezuBNTlmyJC7srQ1/nwxL337ev6D1zQZd3JuhcxLkHrUELLNwzhvcZ70vg645 -jAmz8EdmvvoqEPPoHqKgP5AeHACOsTm953KHhgx3NYuGPU/RoIvugKt4Iq5nw7TWFTjPHGVF3GTQ -ry5CZ/AzXiL57hVEhDvmuT8AEQEAAYkCPgQYAQIACQUCVduSIwIbLgEpCRD0eUtW/C3G3cBdIAQZ -AQIABgUCVduSIwAKCRAFI/9Nx3K5IPOFCACsZ/Z4s2LcEoA51TW+T5w+YevlIuq+332JtqNIpuGI -WpGxUxyDyPT0YQWr0SObBORYNr7RP8d/I2rbaFKyaDaKvRofYr+TwXy92phBo7pdEUamBpfrm/sr -+2BgAB2x3HWXp+IMdeVVhqQe8t4cnFm3c1fIdxADyiJuV5ge2Ml5gK5yNwqCQPh7U2RqC+lmVlMJ -GvWInIRn2mf6A7phDYNZfOz6dkar4yyh5r9rRgrZw88r/yIlrq/c6KRUIgnPMrFYEauggOceZ827 -+jKkbKWFEuHtiCxW7kRAN25UfnGsPaF+NSGM2q1vCG4HiFydx6lMoXM0Shf8+ZwyrV/5BzAqpWwI -AJ37tEwC58Fboynly6OGOzgPS0xKnzkXMOtquTo0qEH/1bEUsBknn795BmZOTf4oBC5blN6qRv7c -GSP00i+sxql1NhTjJcjJtfOPUzgfW+Af/+HR648z4c7c6MCjDFKnk8ZkoGLRU7ISjenkNFzvu2bj -lxJkil0uJDlLPbbX80ojzV1GS9g+ZxVPR+68N1QLl2FU6zsfg34upmLLHG8VG4vExzgyNkOwfTYv -dgyRNTjnuPue6H12fZZ9uCNeG52v7lR3eoQcCxBOniwgipB8UJ52RWXblwxzCtGtDi/EWB3zLTUn -puKcgucA0LotbihSMxhDylaARfVO1QV6csabM/g=` - - TestAAPubKey1 = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1 - -mQENBFXbjPUBCADjNjCUQwfxKL+RR2GA6pv/1K+zJZ8UWIF9S0lk7cVIEfJiprzz -wiMwBS5cD0darGin1FHvIWOZxujA7oW0O2TUuatqI3aAYDTfRYurh6iKLC+VS+F7 -H+/mhfFvKmgr0Y5kDCF1j0T/063QZ84IRGucR/X43IY7kAtmxGXH0dYOCzOe5UBX -1fTn3mXGe2ImCDWBH7gOViynXmb6XNvXkP0fsF5St9jhO7mbZU9EFkv9O3t3EaUR -fHopsCVDOlCkFCw5ArY+DUORHRzoMX0PnkyQb5OzibkChzpg8hQssKeVGpuskTdz -5Q7PtdW71jXd4fFVzoNH8fYwRpziD2xNvi6HABEBAAG0EFZhdWx0IFRlc3QgS2V5 -IDGJATgEEwECACIFAlXbjPUCGy8GCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJ -EOfLr44BHbeTo+sH/i7bapIgPnZsJ81hmxPj4W12uvunksGJiC7d4hIHsG7kmJRT -JfjECi+AuTGeDwBy84TDcRaOB6e79fj65Fg6HgSahDUtKJbGxj/lWzmaBuTzlN3C -Ee8cMwIPqPT2kajJVdOyrvkyuFOdPFOEA7bdCH0MqgIdM2SdF8t40k/ATfuD2K1Z -mumJ508I3gF39jgTnPzD4C8quswrMQ3bzfvKC3klXRlBC0yoArn+0QA3cf2B9T4z -J2qnvgotVbeK/b1OJRNj6Poeo+SsWNc/A5mw7lGScnDgL3yfwCm1gQXaQKfOt5x+ -7GqhWDw10q+bJpJlI10FfzAnhMF9etSqSeURBRW5AQ0EVduM9QEIAL53hJ5bZJ7o -EDCnaY+SCzt9QsAfnFTAnZJQrvkvusJzrTQ088eUQmAjvxkfRqnv981fFwGnh2+I -1Ktm698UAZS9Jt8yjak9wWUICKQO5QUt5k8cHwldQXNXVXFa+TpQWQR5yW1a9okj -h5o/3d4cBt1yZPUJJyLKY43Wvptb6EuEsScO2DnRkh5wSMDQ7dTooddJCmaq3LTj -OleRFQbu9ij386Do6jzK69mJU56TfdcydkxkWF5NZLGnED3lq+hQNbe+8UI5tD2o -P/3r5tXKgMy1R/XPvR/zbfwvx4FAKFOP01awLq4P3d/2xOkMu4Lu9p315E87DOle -Ywxk+FoTqXEAEQEAAYkCPgQYAQIACQUCVduM9QIbLgEpCRDny6+OAR23k8BdIAQZ -AQIABgUCVduM9QAKCRAID0JGyHtSGmqYB/4m4rJbbWa7dBJ8VqRU7ZKnNRDR9CVh -EGipBmpDGRYulEimOPzLUX/ZXZmTZzgemeXLBaJJlWnopVUWuAsyjQuZAfdd8nHk -GRHG0/DGum0l4sKTta3OPGHNC1z1dAcQ1RCr9bTD3PxjLBczdGqhzw71trkQRBRd -tPiUchltPMIyjUHqVJ0xmg0hPqFic0fICsr0YwKoz3h9+QEcZHvsjSZjgydKvfLY -cm+4DDMCCqcHuJrbXJKUWmJcXR0y/+HQONGrGJ5xWdO+6eJioPn2jVMnXCm4EKc7 -fcLFrz/LKmJ8seXhxjM3EdFtylBGCrx3xdK0f+JDNQaC/rhUb5V2XuX6VwoH/AtY -+XsKVYRfNIupLOUcf/srsm3IXT4SXWVomOc9hjGQiJ3rraIbADsc+6bCAr4XNZS7 -moViAAcIPXFv3m3WfUlnG/om78UjQqyVACRZqqAGmuPq+TSkRUCpt9h+A39LQWko -jHqyob3cyLgy6z9Q557O9uK3lQozbw2gH9zC0RqnePl+rsWIUU/ga16fH6pWc1uJ -iEBt8UZGypQ/E56/343epmYAe0a87sHx8iDV+dNtDVKfPRENiLOOc19MmS+phmUy -rbHqI91c0pmysYcJZCD3a502X1gpjFbPZcRtiTmGnUKdOIu60YPNE4+h7u2CfYyF -Pu3AlUaGNMBlvy6PEpU= -=NUTS ------END PGP PUBLIC KEY BLOCK-----` -) diff --git a/vendor/github.com/jstemmer/go-junit-report/.gitignore b/vendor/github.com/jstemmer/go-junit-report/.gitignore new file mode 100644 index 00000000000..720bda6070d --- /dev/null +++ b/vendor/github.com/jstemmer/go-junit-report/.gitignore @@ -0,0 +1 @@ +go-junit-report diff --git a/vendor/github.com/jstemmer/go-junit-report/.travis.yml b/vendor/github.com/jstemmer/go-junit-report/.travis.yml new file mode 100644 index 00000000000..d0dff3ef8e5 --- /dev/null +++ b/vendor/github.com/jstemmer/go-junit-report/.travis.yml @@ -0,0 +1,16 @@ +language: go + +go: + - tip + - "1.13.x" + - "1.12.x" + - "1.11.x" + - "1.10.x" + - "1.9.x" + - "1.8.x" + - "1.7.x" + - "1.6.x" + - "1.5.x" + - "1.4.x" + - "1.3.x" + - "1.2.x" diff --git a/vendor/github.com/jstemmer/go-junit-report/LICENSE b/vendor/github.com/jstemmer/go-junit-report/LICENSE new file mode 100644 index 00000000000..f346564cefd --- /dev/null +++ b/vendor/github.com/jstemmer/go-junit-report/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2012 Joel Stemmer + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jstemmer/go-junit-report/README.md b/vendor/github.com/jstemmer/go-junit-report/README.md new file mode 100644 index 00000000000..5b5f608be3d --- /dev/null +++ b/vendor/github.com/jstemmer/go-junit-report/README.md @@ -0,0 +1,49 @@ +# go-junit-report + +Converts `go test` output to an xml report, suitable for applications that +expect junit xml reports (e.g. [Jenkins](http://jenkins-ci.org)). + +[![Build Status][travis-badge]][travis-link] +[![Report Card][report-badge]][report-link] + +## Installation + +Go version 1.2 or higher is required. Install or update using the `go get` +command: + +```bash +go get -u github.com/jstemmer/go-junit-report +``` + +## Usage + +go-junit-report reads the `go test` verbose output from standard in and writes +junit compatible XML to standard out. + +```bash +go test -v 2>&1 | go-junit-report > report.xml +``` + +Note that it also can parse benchmark output with `-bench` flag: +```bash +go test -v -bench . -count 5 2>&1 | go-junit-report > report.xml +``` + +## Contribution + +Create an Issue and discuss the fix or feature, then fork the package. +Clone to github.com/jstemmer/go-junit-report. This is necessary because go import uses this path. +Fix or implement feature. Test and then commit change. +Specify #Issue and describe change in the commit message. +Create Pull Request. It can be merged by owner or administrator then. + +### Run Tests + +```bash +go test +``` + +[travis-badge]: https://travis-ci.org/jstemmer/go-junit-report.svg +[travis-link]: https://travis-ci.org/jstemmer/go-junit-report +[report-badge]: https://goreportcard.com/badge/github.com/jstemmer/go-junit-report +[report-link]: https://goreportcard.com/report/github.com/jstemmer/go-junit-report diff --git a/vendor/github.com/jstemmer/go-junit-report/formatter/formatter.go b/vendor/github.com/jstemmer/go-junit-report/formatter/formatter.go new file mode 100644 index 00000000000..6e1a0f31d68 --- /dev/null +++ b/vendor/github.com/jstemmer/go-junit-report/formatter/formatter.go @@ -0,0 +1,182 @@ +package formatter + +import ( + "bufio" + "encoding/xml" + "fmt" + "io" + "runtime" + "strings" + "time" + + "github.com/jstemmer/go-junit-report/parser" +) + +// JUnitTestSuites is a collection of JUnit test suites. +type JUnitTestSuites struct { + XMLName xml.Name `xml:"testsuites"` + Suites []JUnitTestSuite `xml:"testsuite"` +} + +// JUnitTestSuite is a single JUnit test suite which may contain many +// testcases. +type JUnitTestSuite struct { + XMLName xml.Name `xml:"testsuite"` + Tests int `xml:"tests,attr"` + Failures int `xml:"failures,attr"` + Time string `xml:"time,attr"` + Name string `xml:"name,attr"` + Properties []JUnitProperty `xml:"properties>property,omitempty"` + TestCases []JUnitTestCase `xml:"testcase"` +} + +// JUnitTestCase is a single test case with its result. +type JUnitTestCase struct { + XMLName xml.Name `xml:"testcase"` + Classname string `xml:"classname,attr"` + Name string `xml:"name,attr"` + Time string `xml:"time,attr"` + SkipMessage *JUnitSkipMessage `xml:"skipped,omitempty"` + Failure *JUnitFailure `xml:"failure,omitempty"` +} + +// JUnitSkipMessage contains the reason why a testcase was skipped. +type JUnitSkipMessage struct { + Message string `xml:"message,attr"` +} + +// JUnitProperty represents a key/value pair used to define properties. +type JUnitProperty struct { + Name string `xml:"name,attr"` + Value string `xml:"value,attr"` +} + +// JUnitFailure contains data related to a failed test. +type JUnitFailure struct { + Message string `xml:"message,attr"` + Type string `xml:"type,attr"` + Contents string `xml:",chardata"` +} + +// JUnitReportXML writes a JUnit xml representation of the given report to w +// in the format described at http://windyroad.org/dl/Open%20Source/JUnit.xsd +func JUnitReportXML(report *parser.Report, noXMLHeader bool, goVersion string, w io.Writer) error { + suites := JUnitTestSuites{} + + // convert Report to JUnit test suites + for _, pkg := range report.Packages { + pkg.Benchmarks = mergeBenchmarks(pkg.Benchmarks) + ts := JUnitTestSuite{ + Tests: len(pkg.Tests) + len(pkg.Benchmarks), + Failures: 0, + Time: formatTime(pkg.Duration), + Name: pkg.Name, + Properties: []JUnitProperty{}, + TestCases: []JUnitTestCase{}, + } + + classname := pkg.Name + if idx := strings.LastIndex(classname, "/"); idx > -1 && idx < len(pkg.Name) { + classname = pkg.Name[idx+1:] + } + + // properties + if goVersion == "" { + // if goVersion was not specified as a flag, fall back to version reported by runtime + goVersion = runtime.Version() + } + ts.Properties = append(ts.Properties, JUnitProperty{"go.version", goVersion}) + if pkg.CoveragePct != "" { + ts.Properties = append(ts.Properties, JUnitProperty{"coverage.statements.pct", pkg.CoveragePct}) + } + + // individual test cases + for _, test := range pkg.Tests { + testCase := JUnitTestCase{ + Classname: classname, + Name: test.Name, + Time: formatTime(test.Duration), + Failure: nil, + } + + if test.Result == parser.FAIL { + ts.Failures++ + testCase.Failure = &JUnitFailure{ + Message: "Failed", + Type: "", + Contents: strings.Join(test.Output, "\n"), + } + } + + if test.Result == parser.SKIP { + testCase.SkipMessage = &JUnitSkipMessage{strings.Join(test.Output, "\n")} + } + + ts.TestCases = append(ts.TestCases, testCase) + } + + // individual benchmarks + for _, benchmark := range pkg.Benchmarks { + benchmarkCase := JUnitTestCase{ + Classname: classname, + Name: benchmark.Name, + Time: formatBenchmarkTime(benchmark.Duration), + } + + ts.TestCases = append(ts.TestCases, benchmarkCase) + } + + suites.Suites = append(suites.Suites, ts) + } + + // to xml + bytes, err := xml.MarshalIndent(suites, "", "\t") + if err != nil { + return err + } + + writer := bufio.NewWriter(w) + + if !noXMLHeader { + writer.WriteString(xml.Header) + } + + writer.Write(bytes) + writer.WriteByte('\n') + writer.Flush() + + return nil +} + +func mergeBenchmarks(benchmarks []*parser.Benchmark) []*parser.Benchmark { + var merged []*parser.Benchmark + benchmap := make(map[string][]*parser.Benchmark) + for _, bm := range benchmarks { + if _, ok := benchmap[bm.Name]; !ok { + merged = append(merged, &parser.Benchmark{Name: bm.Name}) + } + benchmap[bm.Name] = append(benchmap[bm.Name], bm) + } + + for _, bm := range merged { + for _, b := range benchmap[bm.Name] { + bm.Allocs += b.Allocs + bm.Bytes += b.Bytes + bm.Duration += b.Duration + } + n := len(benchmap[bm.Name]) + bm.Allocs /= n + bm.Bytes /= n + bm.Duration /= time.Duration(n) + } + + return merged +} + +func formatTime(d time.Duration) string { + return fmt.Sprintf("%.3f", d.Seconds()) +} + +func formatBenchmarkTime(d time.Duration) string { + return fmt.Sprintf("%.9f", d.Seconds()) +} diff --git a/vendor/github.com/jstemmer/go-junit-report/go-junit-report.go b/vendor/github.com/jstemmer/go-junit-report/go-junit-report.go new file mode 100644 index 00000000000..1332f3b65b1 --- /dev/null +++ b/vendor/github.com/jstemmer/go-junit-report/go-junit-report.go @@ -0,0 +1,45 @@ +package main + +import ( + "flag" + "fmt" + "os" + + "github.com/jstemmer/go-junit-report/formatter" + "github.com/jstemmer/go-junit-report/parser" +) + +var ( + noXMLHeader = flag.Bool("no-xml-header", false, "do not print xml header") + packageName = flag.String("package-name", "", "specify a package name (compiled test have no package name in output)") + goVersionFlag = flag.String("go-version", "", "specify the value to use for the go.version property in the generated XML") + setExitCode = flag.Bool("set-exit-code", false, "set exit code to 1 if tests failed") +) + +func main() { + flag.Parse() + + if flag.NArg() != 0 { + fmt.Fprintf(os.Stderr, "%s does not accept positional arguments\n", os.Args[0]) + flag.Usage() + os.Exit(1) + } + + // Read input + report, err := parser.Parse(os.Stdin, *packageName) + if err != nil { + fmt.Printf("Error reading input: %s\n", err) + os.Exit(1) + } + + // Write xml + err = formatter.JUnitReportXML(report, *noXMLHeader, *goVersionFlag, os.Stdout) + if err != nil { + fmt.Printf("Error writing XML: %s\n", err) + os.Exit(1) + } + + if *setExitCode && report.Failures() > 0 { + os.Exit(1) + } +} diff --git a/vendor/github.com/jstemmer/go-junit-report/go.mod b/vendor/github.com/jstemmer/go-junit-report/go.mod new file mode 100644 index 00000000000..de52369acc9 --- /dev/null +++ b/vendor/github.com/jstemmer/go-junit-report/go.mod @@ -0,0 +1,3 @@ +module github.com/jstemmer/go-junit-report + +go 1.2 diff --git a/vendor/github.com/jstemmer/go-junit-report/parser/parser.go b/vendor/github.com/jstemmer/go-junit-report/parser/parser.go new file mode 100644 index 00000000000..e268128a2dc --- /dev/null +++ b/vendor/github.com/jstemmer/go-junit-report/parser/parser.go @@ -0,0 +1,319 @@ +package parser + +import ( + "bufio" + "io" + "regexp" + "strconv" + "strings" + "time" +) + +// Result represents a test result. +type Result int + +// Test result constants +const ( + PASS Result = iota + FAIL + SKIP +) + +// Report is a collection of package tests. +type Report struct { + Packages []Package +} + +// Package contains the test results of a single package. +type Package struct { + Name string + Duration time.Duration + Tests []*Test + Benchmarks []*Benchmark + CoveragePct string + + // Time is deprecated, use Duration instead. + Time int // in milliseconds +} + +// Test contains the results of a single test. +type Test struct { + Name string + Duration time.Duration + Result Result + Output []string + + SubtestIndent string + + // Time is deprecated, use Duration instead. + Time int // in milliseconds +} + +// Benchmark contains the results of a single benchmark. +type Benchmark struct { + Name string + Duration time.Duration + // number of B/op + Bytes int + // number of allocs/op + Allocs int +} + +var ( + regexStatus = regexp.MustCompile(`--- (PASS|FAIL|SKIP): (.+) \((\d+\.\d+)(?: seconds|s)\)`) + regexIndent = regexp.MustCompile(`^([ \t]+)---`) + regexCoverage = regexp.MustCompile(`^coverage:\s+(\d+\.\d+)%\s+of\s+statements(?:\sin\s.+)?$`) + regexResult = regexp.MustCompile(`^(ok|FAIL)\s+([^ ]+)\s+(?:(\d+\.\d+)s|\(cached\)|(\[\w+ failed]))(?:\s+coverage:\s+(\d+\.\d+)%\sof\sstatements(?:\sin\s.+)?)?$`) + // regexBenchmark captures 3-5 groups: benchmark name, number of times ran, ns/op (with or without decimal), B/op (optional), and allocs/op (optional). + regexBenchmark = regexp.MustCompile(`^(Benchmark[^ -]+)(?:-\d+\s+|\s+)(\d+)\s+(\d+|\d+\.\d+)\sns/op(?:\s+(\d+)\sB/op)?(?:\s+(\d+)\sallocs/op)?`) + regexOutput = regexp.MustCompile(`( )*\t(.*)`) + regexSummary = regexp.MustCompile(`^(PASS|FAIL|SKIP)$`) + regexPackageWithTest = regexp.MustCompile(`^# ([^\[\]]+) \[[^\]]+\]$`) +) + +// Parse parses go test output from reader r and returns a report with the +// results. An optional pkgName can be given, which is used in case a package +// result line is missing. +func Parse(r io.Reader, pkgName string) (*Report, error) { + reader := bufio.NewReader(r) + + report := &Report{make([]Package, 0)} + + // keep track of tests we find + var tests []*Test + + // keep track of benchmarks we find + var benchmarks []*Benchmark + + // sum of tests' time, use this if current test has no result line (when it is compiled test) + var testsTime time.Duration + + // current test + var cur string + + // coverage percentage report for current package + var coveragePct string + + // stores mapping between package name and output of build failures + var packageCaptures = map[string][]string{} + + // the name of the package which it's build failure output is being captured + var capturedPackage string + + // capture any non-test output + var buffers = map[string][]string{} + + // parse lines + for { + l, _, err := reader.ReadLine() + if err != nil && err == io.EOF { + break + } else if err != nil { + return nil, err + } + + line := string(l) + + if strings.HasPrefix(line, "=== RUN ") { + // new test + cur = strings.TrimSpace(line[8:]) + tests = append(tests, &Test{ + Name: cur, + Result: FAIL, + Output: make([]string, 0), + }) + + // clear the current build package, so output lines won't be added to that build + capturedPackage = "" + } else if matches := regexBenchmark.FindStringSubmatch(line); len(matches) == 6 { + bytes, _ := strconv.Atoi(matches[4]) + allocs, _ := strconv.Atoi(matches[5]) + + benchmarks = append(benchmarks, &Benchmark{ + Name: matches[1], + Duration: parseNanoseconds(matches[3]), + Bytes: bytes, + Allocs: allocs, + }) + } else if strings.HasPrefix(line, "=== PAUSE ") { + continue + } else if strings.HasPrefix(line, "=== CONT ") { + cur = strings.TrimSpace(line[8:]) + continue + } else if matches := regexResult.FindStringSubmatch(line); len(matches) == 6 { + if matches[5] != "" { + coveragePct = matches[5] + } + if strings.HasSuffix(matches[4], "failed]") { + // the build of the package failed, inject a dummy test into the package + // which indicate about the failure and contain the failure description. + tests = append(tests, &Test{ + Name: matches[4], + Result: FAIL, + Output: packageCaptures[matches[2]], + }) + } else if matches[1] == "FAIL" && !containsFailures(tests) && len(buffers[cur]) > 0 { + // This package didn't have any failing tests, but still it + // failed with some output. Create a dummy test with the + // output. + tests = append(tests, &Test{ + Name: "Failure", + Result: FAIL, + Output: buffers[cur], + }) + buffers[cur] = buffers[cur][0:0] + } + + // all tests in this package are finished + report.Packages = append(report.Packages, Package{ + Name: matches[2], + Duration: parseSeconds(matches[3]), + Tests: tests, + Benchmarks: benchmarks, + CoveragePct: coveragePct, + + Time: int(parseSeconds(matches[3]) / time.Millisecond), // deprecated + }) + + buffers[cur] = buffers[cur][0:0] + tests = make([]*Test, 0) + benchmarks = make([]*Benchmark, 0) + coveragePct = "" + cur = "" + testsTime = 0 + } else if matches := regexStatus.FindStringSubmatch(line); len(matches) == 4 { + cur = matches[2] + test := findTest(tests, cur) + if test == nil { + continue + } + + // test status + if matches[1] == "PASS" { + test.Result = PASS + } else if matches[1] == "SKIP" { + test.Result = SKIP + } else { + test.Result = FAIL + } + + if matches := regexIndent.FindStringSubmatch(line); len(matches) == 2 { + test.SubtestIndent = matches[1] + } + + test.Output = buffers[cur] + + test.Name = matches[2] + test.Duration = parseSeconds(matches[3]) + testsTime += test.Duration + + test.Time = int(test.Duration / time.Millisecond) // deprecated + } else if matches := regexCoverage.FindStringSubmatch(line); len(matches) == 2 { + coveragePct = matches[1] + } else if matches := regexOutput.FindStringSubmatch(line); capturedPackage == "" && len(matches) == 3 { + // Sub-tests start with one or more series of 4-space indents, followed by a hard tab, + // followed by the test output + // Top-level tests start with a hard tab. + test := findTest(tests, cur) + if test == nil { + continue + } + test.Output = append(test.Output, matches[2]) + } else if strings.HasPrefix(line, "# ") { + // indicates a capture of build output of a package. set the current build package. + packageWithTestBinary := regexPackageWithTest.FindStringSubmatch(line) + if packageWithTestBinary != nil { + // Sometimes, the text after "# " shows the name of the test binary + // (".test") in addition to the package + // e.g.: "# package/name [package/name.test]" + capturedPackage = packageWithTestBinary[1] + } else { + capturedPackage = line[2:] + } + } else if capturedPackage != "" { + // current line is build failure capture for the current built package + packageCaptures[capturedPackage] = append(packageCaptures[capturedPackage], line) + } else if regexSummary.MatchString(line) { + // unset current test name so any additional output after the + // summary is captured separately. + cur = "" + } else { + // buffer anything else that we didn't recognize + buffers[cur] = append(buffers[cur], line) + + // if we have a current test, also append to its output + test := findTest(tests, cur) + if test != nil { + if strings.HasPrefix(line, test.SubtestIndent+" ") { + test.Output = append(test.Output, strings.TrimPrefix(line, test.SubtestIndent+" ")) + } + } + } + } + + if len(tests) > 0 { + // no result line found + report.Packages = append(report.Packages, Package{ + Name: pkgName, + Duration: testsTime, + Time: int(testsTime / time.Millisecond), + Tests: tests, + Benchmarks: benchmarks, + CoveragePct: coveragePct, + }) + } + + return report, nil +} + +func parseSeconds(t string) time.Duration { + if t == "" { + return time.Duration(0) + } + // ignore error + d, _ := time.ParseDuration(t + "s") + return d +} + +func parseNanoseconds(t string) time.Duration { + // note: if input < 1 ns precision, result will be 0s. + if t == "" { + return time.Duration(0) + } + // ignore error + d, _ := time.ParseDuration(t + "ns") + return d +} + +func findTest(tests []*Test, name string) *Test { + for i := len(tests) - 1; i >= 0; i-- { + if tests[i].Name == name { + return tests[i] + } + } + return nil +} + +func containsFailures(tests []*Test) bool { + for _, test := range tests { + if test.Result == FAIL { + return true + } + } + return false +} + +// Failures counts the number of failed tests in this report +func (r *Report) Failures() int { + count := 0 + + for _, p := range r.Packages { + for _, t := range p.Tests { + if t.Result == FAIL { + count++ + } + } + } + + return count +} diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md b/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md index 949b77e304e..09a4a35c9bb 100644 --- a/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/README.md @@ -26,6 +26,8 @@ The tool is sponsored by the [marvin + konsorten GmbH](http://www.konsorten.de). We thank all the authors who provided code to this library: * Felix Kollmann +* Nicolas Perraut +* @dirty49374 ## License diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go index ef18d8f9787..57f530ae83f 100644 --- a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go @@ -4,7 +4,6 @@ package sequences import ( "syscall" - "unsafe" ) var ( @@ -27,7 +26,7 @@ func EnableVirtualTerminalProcessing(stream syscall.Handle, enable bool) error { mode &^= ENABLE_VIRTUAL_TERMINAL_PROCESSING } - ret, _, err := setConsoleMode.Call(uintptr(unsafe.Pointer(stream)), uintptr(mode)) + ret, _, err := setConsoleMode.Call(uintptr(stream), uintptr(mode)) if ret == 0 { return err } diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go new file mode 100644 index 00000000000..df61a6f2f6f --- /dev/null +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go @@ -0,0 +1,11 @@ +// +build linux darwin + +package sequences + +import ( + "fmt" +) + +func EnableVirtualTerminalProcessing(stream uintptr, enable bool) error { + return fmt.Errorf("windows only package") +} diff --git a/vendor/github.com/kyoh86/exportloopref/.golangci.yml b/vendor/github.com/kyoh86/exportloopref/.golangci.yml new file mode 100644 index 00000000000..58667b2157e --- /dev/null +++ b/vendor/github.com/kyoh86/exportloopref/.golangci.yml @@ -0,0 +1,4 @@ +linters: + enable: + - unparam + - scopelint diff --git a/vendor/github.com/kyoh86/exportloopref/.goreleaser.yml b/vendor/github.com/kyoh86/exportloopref/.goreleaser.yml new file mode 100644 index 00000000000..22ff44040c1 --- /dev/null +++ b/vendor/github.com/kyoh86/exportloopref/.goreleaser.yml @@ -0,0 +1,43 @@ +project_name: exportloopref +release: + github: + owner: kyoh86 + name: exportloopref +brews: +- install: | + bin.install "exportloopref" + github: + owner: kyoh86 + name: homebrew-tap + folder: Formula + homepage: https://github.com/kyoh86/exportloopref + description: An analyzer that finds exporting pointers for loop variables. +builds: +- goos: + - linux + - darwin + - windows + goarch: + - amd64 + - "386" + main: ./cmd/exportloopref + ldflags: -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}} + binary: exportloopref +archives: +- id: gzip + format: tar.gz + format_overrides: + - goos: windows + format: zip + name_template: "{{ .Binary }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" + files: + - licence* + - LICENCE* + - license* + - LICENSE* + - readme* + - README* + - changelog* + - CHANGELOG* +snapshot: + name_template: SNAPSHOT-{{ .Commit }} diff --git a/vendor/github.com/kyoh86/exportloopref/LICENSE b/vendor/github.com/kyoh86/exportloopref/LICENSE new file mode 100644 index 00000000000..7ac9dba4a0c --- /dev/null +++ b/vendor/github.com/kyoh86/exportloopref/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 kyoh86 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/kyoh86/exportloopref/Makefile b/vendor/github.com/kyoh86/exportloopref/Makefile new file mode 100644 index 00000000000..4d3ef22f7f4 --- /dev/null +++ b/vendor/github.com/kyoh86/exportloopref/Makefile @@ -0,0 +1,16 @@ +.PHONY: gen lint test install man + +VERSION := `git vertag get` +COMMIT := `git rev-parse HEAD` + +gen: + go generate ./... + +lint: gen + golangci-lint run + +test: lint + go test -v --race ./... + +install: test + go install -a -ldflags "-X=main.version=$(VERSION) -X=main.commit=$(COMMIT)" ./... diff --git a/vendor/github.com/kyoh86/exportloopref/README.md b/vendor/github.com/kyoh86/exportloopref/README.md new file mode 100644 index 00000000000..5b154915924 --- /dev/null +++ b/vendor/github.com/kyoh86/exportloopref/README.md @@ -0,0 +1,178 @@ +# exportloopref + +An analyzer that finds exporting pointers for loop variables. + +[![Go Report Card](https://goreportcard.com/badge/github.com/kyoh86/exportloopref)](https://goreportcard.com/report/github.com/kyoh86/exportloopref) +[![Coverage Status](https://img.shields.io/codecov/c/github/kyoh86/exportloopref.svg)](https://codecov.io/gh/kyoh86/exportloopref) +[![Release](https://github.com/kyoh86/exportloopref/workflows/Release/badge.svg)](https://github.com/kyoh86/exportloopref/releases) + +## What's this? + +Sample problem code from: https://github.com/kyoh86/exportloopref/blob/master/testdata/simple/simple.go + +```go +package main + +func main() { + var intArray [4]*int + var intSlice []*int + var intRef *int + var intStr struct{ x *int } + + println("loop expecting 10, 11, 12, 13") + for i, p := range []int{10, 11, 12, 13} { + printp(&p) // not a diagnostic + intSlice = append(intSlice, &p) // want "exporting a pointer for the loop variable p" + intArray[i] = &p // want "exporting a pointer for the loop variable p" + if i%2 == 0 { + intRef = &p // want "exporting a pointer for the loop variable p" + intStr.x = &p // want "exporting a pointer for the loop variable p" + } + var vStr struct{ x *int } + var vArray [4]*int + var v *int + if i%2 == 0 { + v = &p // not a diagnostic (x is inner variable) + vArray[1] = &p // not a diagnostic (x is inner variable) + vStr.x = &p + } + _ = v + } + + println(`slice expecting "10, 11, 12, 13" but "13, 13, 13, 13"`) + for _, p := range intSlice { + printp(p) + } + println(`array expecting "10, 11, 12, 13" but "13, 13, 13, 13"`) + for _, p := range intArray { + printp(p) + } + println(`captured value expecting "12" but "13"`) + printp(intRef) +} + +func printp(p *int) { + println(*p) +} +``` + +In Go, the `p` variable in the above loops is actually a single variable. +So in many case (like the above), using it makes for us annoying bugs. + +You can find them with `exportloopref`, and fix it. + +```go +package main + +func main() { + var intArray [4]*int + var intSlice []*int + var intRef *int + var intStr struct{ x *int } + + println("loop expecting 10, 11, 12, 13") + for i, p := range []int{10, 11, 12, 13} { + p := p // FIX variable into the inner variable + printp(&p) + intSlice = append(intSlice, &p) + intArray[i] = &p + if i%2 == 0 { + intRef = &p + intStr.x = &p + } + var vStr struct{ x *int } + var vArray [4]*int + var v *int + if i%2 == 0 { + v = &p + vArray[1] = &p + vStr.x = &p + } + _ = v + } + + println(`slice expecting "10, 11, 12, 13"`) + for _, p := range intSlice { + printp(p) + } + println(`array expecting "10, 11, 12, 13"`) + for _, p := range intArray { + printp(p) + } + println(`captured value expecting "12"`) + printp(intRef) +} + +func printp(p *int) { + println(*p) +} +``` + +ref: https://github.com/kyoh86/exportloopref/blob/master/testdata/fixed/fixed.go + +## Sensing policy + +I want to make exportloopref as accurately as possible. +So some cases of lints will be ignored. + +e.g. + +```go +var s Foo +for _, p := []int{10, 11, 12, 13} { + s.Bar(&p) // If s stores the pointer, it will be bug. +} +``` + +If you want to report all of lints (with some false-positives), +you should use [looppointer](https://github.com/kyoh86/looppointer). + +## Install + +go: + +```console +$ go get github.com/kyoh86/exportloopref/cmd/exportloopref +``` + +[homebrew](https://brew.sh/): + +```console +$ brew install kyoh86/tap/exportloopref +``` + +[gordon](https://github.com/kyoh86/gordon): + +```console +$ gordon install kyoh86/exportloopref +``` + +## Usage + +``` +exportloopref [-flag] [package] +``` + +### Flags + +| Flag | Description | +| --- | --- | +| -V | print version and exit | +| -all | no effect (deprecated) | +| -c int | display offending line with this many lines of context (default -1) | +| -cpuprofile string | write CPU profile to this file | +| -debug string | debug flags, any subset of "fpstv" | +| -fix | apply all suggested fixes | +| -flags | print analyzer flags in JSON | +| -json | emit JSON output | +| -memprofile string | write memory profile to this file | +| -source | no effect (deprecated) | +| -tags string | no effect (deprecated) | +| -trace string | write trace log to this file | +| -v | no effect (deprecated) | + +# LICENSE + +[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg)](http://www.opensource.org/licenses/MIT) + +This is distributed under the [MIT License](http://www.opensource.org/licenses/MIT). diff --git a/vendor/github.com/kyoh86/exportloopref/exportloopref.go b/vendor/github.com/kyoh86/exportloopref/exportloopref.go new file mode 100644 index 00000000000..0b310b3c9c0 --- /dev/null +++ b/vendor/github.com/kyoh86/exportloopref/exportloopref.go @@ -0,0 +1,276 @@ +package exportloopref + +import ( + "go/ast" + "go/token" + "go/types" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +var Analyzer = &analysis.Analyzer{ + Name: "exportloopref", + Doc: "checks for pointers to enclosing loop variables", + Run: run, + RunDespiteErrors: true, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + // ResultType reflect.Type + // FactTypes []Fact +} + +func init() { + // Analyzer.Flags.StringVar(&v, "name", "default", "description") +} + +func run(pass *analysis.Pass) (interface{}, error) { + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + + search := &Searcher{ + Stats: map[token.Pos]struct{}{}, + Vars: map[token.Pos]map[token.Pos]struct{}{}, + Types: pass.TypesInfo.Types, + } + + nodeFilter := []ast.Node{ + (*ast.RangeStmt)(nil), + (*ast.ForStmt)(nil), + (*ast.DeclStmt)(nil), + (*ast.AssignStmt)(nil), + (*ast.UnaryExpr)(nil), + } + + inspect.WithStack(nodeFilter, func(n ast.Node, push bool, stack []ast.Node) bool { + id, digg := search.Check(n, stack) + if id != nil { + pass.ReportRangef(id, "exporting a pointer for the loop variable %s", id.Name) + } + return digg + }) + + return nil, nil +} + +type Searcher struct { + // Statement variables : map to collect positions that + // variables are declared like below. + // - for , := range ... + // - var int + // - D := ... + Stats map[token.Pos]struct{} + // Internal variables maps loop-position, decl-location to ignore + // safe pointers for variable which declared in the loop. + Vars map[token.Pos]map[token.Pos]struct{} + Types map[ast.Expr]types.TypeAndValue +} + +func (s *Searcher) Check(n ast.Node, stack []ast.Node) (*ast.Ident, bool) { + switch typed := n.(type) { + case *ast.RangeStmt: + s.parseRangeStmt(typed) + case *ast.ForStmt: + s.parseForStmt(typed) + case *ast.DeclStmt: + s.parseDeclStmt(typed, stack) + case *ast.AssignStmt: + s.parseAssignStmt(typed, stack) + + case *ast.UnaryExpr: + return s.checkUnaryExpr(typed, stack) + } + return nil, true +} + +func (s *Searcher) parseRangeStmt(n *ast.RangeStmt) { + s.addStat(n.Key) + s.addStat(n.Value) +} + +func (s *Searcher) parseForStmt(n *ast.ForStmt) { + switch post := n.Post.(type) { + case *ast.AssignStmt: + // e.g. for p = head; p != nil; p = p.next + for _, lhs := range post.Lhs { + s.addStat(lhs) + } + case *ast.IncDecStmt: + // e.g. for i := 0; i < n; i++ + s.addStat(post.X) + } +} + +func (s *Searcher) addStat(expr ast.Expr) { + if id, ok := expr.(*ast.Ident); ok { + s.Stats[id.Pos()] = struct{}{} + } +} + +func (s *Searcher) parseDeclStmt(n *ast.DeclStmt, stack []ast.Node) { + loop := s.innermostLoop(stack) + if loop == nil { + return + } + + // Register declaring variables + if genDecl, ok := n.Decl.(*ast.GenDecl); ok && genDecl.Tok == token.VAR { + for _, spec := range genDecl.Specs { + for _, name := range spec.(*ast.ValueSpec).Names { + s.addVar(loop, name) + } + } + } +} + +func (s *Searcher) parseAssignStmt(n *ast.AssignStmt, stack []ast.Node) { + loop := s.innermostLoop(stack) + if loop == nil { + return + } + + // Find statements declaring internal variable + if n.Tok == token.DEFINE { + for _, h := range n.Lhs { + s.addVar(loop, h) + } + } +} + +func (s *Searcher) addVar(loop ast.Node, expr ast.Expr) { + loopPos := loop.Pos() + id, ok := expr.(*ast.Ident) + if !ok { + return + } + vars, ok := s.Vars[loopPos] + if !ok { + vars = map[token.Pos]struct{}{} + } + vars[id.Obj.Pos()] = struct{}{} + s.Vars[loopPos] = vars +} + +func (s *Searcher) innermostLoop(stack []ast.Node) ast.Node { + for i := len(stack) - 1; i >= 0; i-- { + switch stack[i].(type) { + case *ast.RangeStmt, *ast.ForStmt: + return stack[i] + } + } + return nil +} + +func (s *Searcher) checkUnaryExpr(n *ast.UnaryExpr, stack []ast.Node) (*ast.Ident, bool) { + loop := s.innermostLoop(stack) + if loop == nil { + return nil, true + } + + if n.Op != token.AND { + return nil, true + } + + // Get identity of the referred item + id := s.getIdentity(n.X) + if id == nil { + return nil, true + } + + // If the identity is not the loop statement variable, + // it will not be reported. + if _, isStat := s.Stats[id.Obj.Pos()]; !isStat { + return nil, true + } + + // check stack append(), []X{}, map[Type]X{}, Struct{}, &Struct{}, X.(Type), (X) + // in the = + var mayRHPos token.Pos + for i := len(stack) - 2; i >= 0; i-- { + switch typed := stack[i].(type) { + case (*ast.UnaryExpr): + // noop + case (*ast.CompositeLit): + // noop + case (*ast.KeyValueExpr): + // noop + case (*ast.CallExpr): + fun, ok := typed.Fun.(*ast.Ident) + if !ok { + return nil, false // it's calling a function other of `append`. It cannot be checked + } + + if fun.Name != "append" { + return nil, false // it's calling a function other of `append`. It cannot be checked + } + + case (*ast.AssignStmt): + if len(typed.Rhs) != len(typed.Lhs) { + return nil, false // dead logic + } + + // search x where Rhs[x].Pos() == mayRHPos + var index int + for ri, rh := range typed.Rhs { + if rh.Pos() == mayRHPos { + index = ri + break + } + } + + // check Lhs[x] is not inner variable + lh := typed.Lhs[index] + isVar := s.isVar(loop, lh) + if !isVar { + return id, false + } + + return nil, true + default: + // Other statement is not able to be checked. + return nil, false + } + + // memory an expr that may be right-hand in the AssignStmt + mayRHPos = stack[i].Pos() + } + return nil, true +} + +func (s *Searcher) isVar(loop ast.Node, expr ast.Expr) bool { + vars := s.Vars[loop.Pos()] // map[token.Pos]struct{} + if vars == nil { + return false + } + switch typed := expr.(type) { + case (*ast.Ident): + _, isVar := vars[typed.Obj.Pos()] + return isVar + case (*ast.IndexExpr): // like X[Y], check X + return s.isVar(loop, typed.X) + case (*ast.SelectorExpr): // like X.Y, check X + return s.isVar(loop, typed.X) + } + return false +} + +// Get variable identity +func (s *Searcher) getIdentity(expr ast.Expr) *ast.Ident { + switch typed := expr.(type) { + case *ast.SelectorExpr: + // Ignore if the parent is pointer ref (fix for #2) + if _, ok := s.Types[typed.X].Type.(*types.Pointer); ok { + return nil + } + + // Get parent identity; i.e. `a.b` of the `a.b.c`. + return s.getIdentity(typed.X) + + case *ast.Ident: + // Get simple identity; i.e. `a` of the `a`. + if typed.Obj == nil { + return nil + } + return typed + } + return nil +} diff --git a/vendor/github.com/kyoh86/exportloopref/go.mod b/vendor/github.com/kyoh86/exportloopref/go.mod new file mode 100644 index 00000000000..2b61b220b35 --- /dev/null +++ b/vendor/github.com/kyoh86/exportloopref/go.mod @@ -0,0 +1,5 @@ +module github.com/kyoh86/exportloopref + +go 1.14 + +require golang.org/x/tools v0.0.0-20200321224714-0d839f3cf2ed diff --git a/vendor/github.com/kyoh86/exportloopref/go.sum b/vendor/github.com/kyoh86/exportloopref/go.sum new file mode 100644 index 00000000000..eb0e5ab1e4c --- /dev/null +++ b/vendor/github.com/kyoh86/exportloopref/go.sum @@ -0,0 +1,20 @@ +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200321224714-0d839f3cf2ed h1:OCZDlBlLYiUK6T33/8+3BnojrS2W+Dg1rKYJhR89xGE= +golang.org/x/tools v0.0.0-20200321224714-0d839f3cf2ed/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/vendor/github.com/mattn/go-colorable/.travis.yml b/vendor/github.com/mattn/go-colorable/.travis.yml index 98db8f060bd..7942c565ce6 100644 --- a/vendor/github.com/mattn/go-colorable/.travis.yml +++ b/vendor/github.com/mattn/go-colorable/.travis.yml @@ -1,9 +1,15 @@ language: go +sudo: false go: + - 1.13.x - tip before_install: - - go get github.com/mattn/goveralls - - go get golang.org/x/tools/cmd/cover + - go get -t -v ./... + script: - - $HOME/gopath/bin/goveralls -repotoken xnXqRGwgW3SXIguzxf90ZSK1GPYZPaGrw + - ./go.test.sh + +after_success: + - bash <(curl -s https://codecov.io/bash) + diff --git a/vendor/github.com/mattn/go-colorable/README.md b/vendor/github.com/mattn/go-colorable/README.md index 56729a92ca6..e055952b667 100644 --- a/vendor/github.com/mattn/go-colorable/README.md +++ b/vendor/github.com/mattn/go-colorable/README.md @@ -1,8 +1,8 @@ # go-colorable -[![Godoc Reference](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable) [![Build Status](https://travis-ci.org/mattn/go-colorable.svg?branch=master)](https://travis-ci.org/mattn/go-colorable) -[![Coverage Status](https://coveralls.io/repos/github/mattn/go-colorable/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-colorable?branch=master) +[![Codecov](https://codecov.io/gh/mattn/go-colorable/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-colorable) +[![GoDoc](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable) [![Go Report Card](https://goreportcard.com/badge/mattn/go-colorable)](https://goreportcard.com/report/mattn/go-colorable) Colorable writer for windows. diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go index 0b0aef83700..1f7806fe16b 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_appengine.go +++ b/vendor/github.com/mattn/go-colorable/colorable_appengine.go @@ -27,3 +27,11 @@ func NewColorableStdout() io.Writer { func NewColorableStderr() io.Writer { return os.Stderr } + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + if enabled != nil { + *enabled = true + } + return func() {} +} diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go index 3fb771dcca2..08cbd1e0fa2 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_others.go +++ b/vendor/github.com/mattn/go-colorable/colorable_others.go @@ -28,3 +28,11 @@ func NewColorableStdout() io.Writer { func NewColorableStderr() io.Writer { return os.Stderr } + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + if enabled != nil { + *enabled = true + } + return func() {} +} diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go index 1bd628f25c0..04c4229c4b7 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ b/vendor/github.com/mattn/go-colorable/colorable_windows.go @@ -10,6 +10,7 @@ import ( "os" "strconv" "strings" + "sync" "syscall" "unsafe" @@ -27,6 +28,9 @@ const ( backgroundRed = 0x40 backgroundIntensity = 0x80 backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) + commonLvbUnderscore = 0x8000 + + cENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4 ) const ( @@ -78,6 +82,8 @@ var ( procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") + procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + procSetConsoleMode = kernel32.NewProc("SetConsoleMode") procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") ) @@ -89,6 +95,7 @@ type Writer struct { oldattr word oldpos coord rest bytes.Buffer + mutex sync.Mutex } // NewColorable returns new instance of Writer which handles escape sequence from File. @@ -98,6 +105,10 @@ func NewColorable(file *os.File) io.Writer { } if isatty.IsTerminal(file.Fd()) { + var mode uint32 + if r, _, _ := procGetConsoleMode.Call(file.Fd(), uintptr(unsafe.Pointer(&mode))); r != 0 && mode&cENABLE_VIRTUAL_TERMINAL_PROCESSING != 0 { + return file + } var csbi consoleScreenBufferInfo handle := syscall.Handle(file.Fd()) procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) @@ -424,6 +435,8 @@ func atoiWithDefault(s string, def int) (int, error) { // Write writes data on console func (w *Writer) Write(data []byte) (n int, err error) { + w.mutex.Lock() + defer w.mutex.Unlock() var csbi consoleScreenBufferInfo procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) @@ -675,14 +688,19 @@ loop: switch { case n == 0 || n == 100: attr = w.oldattr - case 1 <= n && n <= 5: - attr |= foregroundIntensity - case n == 7: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) - case n == 22 || n == 25: + case n == 4: + attr |= commonLvbUnderscore + case (1 <= n && n <= 3) || n == 5: attr |= foregroundIntensity - case n == 27: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) + case n == 7 || n == 27: + attr = + (attr &^ (foregroundMask | backgroundMask)) | + ((attr & foregroundMask) << 4) | + ((attr & backgroundMask) >> 4) + case n == 22: + attr &^= foregroundIntensity + case n == 24: + attr &^= commonLvbUnderscore case 30 <= n && n <= 37: attr &= backgroundMask if (n-30)&1 != 0 { @@ -1003,3 +1021,23 @@ func n256setup() { n256backAttr[i] = c.backgroundAttr() } } + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + var mode uint32 + h := os.Stdout.Fd() + if r, _, _ := procGetConsoleMode.Call(h, uintptr(unsafe.Pointer(&mode))); r != 0 { + if r, _, _ = procSetConsoleMode.Call(h, uintptr(mode|cENABLE_VIRTUAL_TERMINAL_PROCESSING)); r != 0 { + if enabled != nil { + *enabled = true + } + return func() { + procSetConsoleMode.Call(h, uintptr(mode)) + } + } + } + if enabled != nil { + *enabled = true + } + return func() {} +} diff --git a/vendor/github.com/mattn/go-colorable/go.mod b/vendor/github.com/mattn/go-colorable/go.mod index ef3ca9d4c31..1e590b8199d 100644 --- a/vendor/github.com/mattn/go-colorable/go.mod +++ b/vendor/github.com/mattn/go-colorable/go.mod @@ -1,3 +1,8 @@ module github.com/mattn/go-colorable -require github.com/mattn/go-isatty v0.0.8 +require ( + github.com/mattn/go-isatty v0.0.12 + golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae // indirect +) + +go 1.13 diff --git a/vendor/github.com/mattn/go-colorable/go.sum b/vendor/github.com/mattn/go-colorable/go.sum index 2c12960ec73..cf5b95d97cd 100644 --- a/vendor/github.com/mattn/go-colorable/go.sum +++ b/vendor/github.com/mattn/go-colorable/go.sum @@ -1,4 +1,5 @@ -github.com/mattn/go-isatty v0.0.5 h1:tHXDdz1cpzGaovsTB+TVB8q90WEokoVmfMqoVcrLUgw= -github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae h1:/WDfKMnPU+m5M4xB+6x4kaepxRw6jWvR5iDRdvjHgy8= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/vendor/github.com/mattn/go-colorable/go.test.sh b/vendor/github.com/mattn/go-colorable/go.test.sh new file mode 100644 index 00000000000..012162b077c --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/go.test.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +set -e +echo "" > coverage.txt + +for d in $(go list ./... | grep -v vendor); do + go test -race -coverprofile=profile.out -covermode=atomic "$d" + if [ -f profile.out ]; then + cat profile.out >> coverage.txt + rm profile.out + fi +done diff --git a/vendor/github.com/mattn/go-isatty/.travis.yml b/vendor/github.com/mattn/go-isatty/.travis.yml index 5597e026ddf..604314dd44c 100644 --- a/vendor/github.com/mattn/go-isatty/.travis.yml +++ b/vendor/github.com/mattn/go-isatty/.travis.yml @@ -1,13 +1,14 @@ language: go +sudo: false go: + - 1.13.x - tip -os: - - linux - - osx - before_install: - - go get github.com/mattn/goveralls - - go get golang.org/x/tools/cmd/cover + - go get -t -v ./... + script: - - $HOME/gopath/bin/goveralls -repotoken 3gHdORO5k5ziZcWMBxnd9LrMZaJs8m9x5 + - ./go.test.sh + +after_success: + - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/mattn/go-isatty/README.md b/vendor/github.com/mattn/go-isatty/README.md index 1e69004bb03..38418353e31 100644 --- a/vendor/github.com/mattn/go-isatty/README.md +++ b/vendor/github.com/mattn/go-isatty/README.md @@ -1,7 +1,7 @@ # go-isatty [![Godoc Reference](https://godoc.org/github.com/mattn/go-isatty?status.svg)](http://godoc.org/github.com/mattn/go-isatty) -[![Build Status](https://travis-ci.org/mattn/go-isatty.svg?branch=master)](https://travis-ci.org/mattn/go-isatty) +[![Codecov](https://codecov.io/gh/mattn/go-isatty/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-isatty) [![Coverage Status](https://coveralls.io/repos/github/mattn/go-isatty/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-isatty?branch=master) [![Go Report Card](https://goreportcard.com/badge/mattn/go-isatty)](https://goreportcard.com/report/mattn/go-isatty) diff --git a/vendor/github.com/mattn/go-isatty/go.mod b/vendor/github.com/mattn/go-isatty/go.mod index a8ddf404fc1..605c4c22109 100644 --- a/vendor/github.com/mattn/go-isatty/go.mod +++ b/vendor/github.com/mattn/go-isatty/go.mod @@ -1,5 +1,5 @@ module github.com/mattn/go-isatty -require golang.org/x/sys v0.0.0-20191008105621-543471e840be +go 1.12 -go 1.14 +require golang.org/x/sys v0.0.0-20200116001909-b77594299b42 diff --git a/vendor/github.com/mattn/go-isatty/go.sum b/vendor/github.com/mattn/go-isatty/go.sum index c141fc53a95..912e29cbc19 100644 --- a/vendor/github.com/mattn/go-isatty/go.sum +++ b/vendor/github.com/mattn/go-isatty/go.sum @@ -1,4 +1,2 @@ -golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ= -golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191008105621-543471e840be h1:QAcqgptGM8IQBC9K/RC4o+O9YmqEm0diQn9QmZw/0mU= -golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/vendor/github.com/mattn/go-isatty/go.test.sh b/vendor/github.com/mattn/go-isatty/go.test.sh new file mode 100644 index 00000000000..012162b077c --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/go.test.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +set -e +echo "" > coverage.txt + +for d in $(go list ./... | grep -v vendor); do + go test -race -coverprofile=profile.out -covermode=atomic "$d" + if [ -f profile.out ]; then + cat profile.out >> coverage.txt + rm profile.out + fi +done diff --git a/vendor/github.com/mattn/go-isatty/isatty_android.go b/vendor/github.com/mattn/go-isatty/isatty_android.go deleted file mode 100644 index d3567cb5bf2..00000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_android.go +++ /dev/null @@ -1,23 +0,0 @@ -// +build android - -package isatty - -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TCGETS - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} - -// IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go index 07e93039dbe..711f288085a 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_bsd.go +++ b/vendor/github.com/mattn/go-isatty/isatty_bsd.go @@ -3,18 +3,12 @@ package isatty -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TIOCGETA +import "golang.org/x/sys/unix" // IsTerminal return true if the file descriptor is terminal. func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 + _, err := unix.IoctlGetTermios(int(fd), unix.TIOCGETA) + return err == nil } // IsCygwinTerminal return true if the file descriptor is a cygwin or msys2 diff --git a/vendor/github.com/mattn/go-isatty/isatty_plan9.go b/vendor/github.com/mattn/go-isatty/isatty_plan9.go index bc0a70920f4..c5b6e0c084a 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_plan9.go +++ b/vendor/github.com/mattn/go-isatty/isatty_plan9.go @@ -8,7 +8,7 @@ import ( // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd uintptr) bool { - path, err := syscall.Fd2path(fd) + path, err := syscall.Fd2path(int(fd)) if err != nil { return false } diff --git a/vendor/github.com/mattn/go-isatty/isatty_tcgets.go b/vendor/github.com/mattn/go-isatty/isatty_tcgets.go index 453b025d0df..31a1ca973c7 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_tcgets.go +++ b/vendor/github.com/mattn/go-isatty/isatty_tcgets.go @@ -1,6 +1,5 @@ // +build linux aix // +build !appengine -// +build !android package isatty diff --git a/vendor/github.com/mattn/go-isatty/renovate.json b/vendor/github.com/mattn/go-isatty/renovate.json new file mode 100644 index 00000000000..5ae9d96b74b --- /dev/null +++ b/vendor/github.com/mattn/go-isatty/renovate.json @@ -0,0 +1,8 @@ +{ + "extends": [ + "config:base" + ], + "postUpdateOptions": [ + "gomodTidy" + ] +} diff --git a/vendor/github.com/mitchellh/colorstring/.travis.yml b/vendor/github.com/mitchellh/colorstring/.travis.yml deleted file mode 100644 index 74e286ae127..00000000000 --- a/vendor/github.com/mitchellh/colorstring/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go - -go: - - 1.0 - - 1.1 - - 1.2 - - 1.3 - - tip - -script: - - go test - -matrix: - allow_failures: - - go: tip diff --git a/vendor/github.com/mitchellh/colorstring/LICENSE b/vendor/github.com/mitchellh/colorstring/LICENSE deleted file mode 100644 index 22985159044..00000000000 --- a/vendor/github.com/mitchellh/colorstring/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Mitchell Hashimoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/mitchellh/colorstring/README.md b/vendor/github.com/mitchellh/colorstring/README.md deleted file mode 100644 index 0654d454dea..00000000000 --- a/vendor/github.com/mitchellh/colorstring/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# colorstring [![Build Status](https://travis-ci.org/mitchellh/colorstring.svg)](https://travis-ci.org/mitchellh/colorstring) - -colorstring is a [Go](http://www.golang.org) library for outputting colored -strings to a console using a simple inline syntax in your string to specify -the color to print as. - -For example, the string `[blue]hello [red]world` would output the text -"hello world" in two colors. The API of colorstring allows for easily disabling -colors, adding aliases, etc. - -## Installation - -Standard `go get`: - -``` -$ go get github.com/mitchellh/colorstring -``` - -## Usage & Example - -For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/colorstring). - -Usage is easy enough: - -```go -colorstring.Println("[blue]Hello [red]World!") -``` - -Additionally, the `Colorize` struct can be used to set options such as -custom colors, color disabling, etc. diff --git a/vendor/github.com/mitchellh/colorstring/colorstring.go b/vendor/github.com/mitchellh/colorstring/colorstring.go deleted file mode 100644 index 3de5b241d90..00000000000 --- a/vendor/github.com/mitchellh/colorstring/colorstring.go +++ /dev/null @@ -1,244 +0,0 @@ -// colorstring provides functions for colorizing strings for terminal -// output. -package colorstring - -import ( - "bytes" - "fmt" - "io" - "regexp" - "strings" -) - -// Color colorizes your strings using the default settings. -// -// Strings given to Color should use the syntax `[color]` to specify the -// color for text following. For example: `[blue]Hello` will return "Hello" -// in blue. See DefaultColors for all the supported colors and attributes. -// -// If an unrecognized color is given, it is ignored and assumed to be part -// of the string. For example: `[hi]world` will result in "[hi]world". -// -// A color reset is appended to the end of every string. This will reset -// the color of following strings when you output this text to the same -// terminal session. -// -// If you want to customize any of this behavior, use the Colorize struct. -func Color(v string) string { - return def.Color(v) -} - -// ColorPrefix returns the color sequence that prefixes the given text. -// -// This is useful when wrapping text if you want to inherit the color -// of the wrapped text. For example, "[green]foo" will return "[green]". -// If there is no color sequence, then this will return "". -func ColorPrefix(v string) string { - return def.ColorPrefix(v) -} - -// Colorize colorizes your strings, giving you the ability to customize -// some of the colorization process. -// -// The options in Colorize can be set to customize colorization. If you're -// only interested in the defaults, just use the top Color function directly, -// which creates a default Colorize. -type Colorize struct { - // Colors maps a color string to the code for that color. The code - // is a string so that you can use more complex colors to set foreground, - // background, attributes, etc. For example, "boldblue" might be - // "1;34" - Colors map[string]string - - // If true, color attributes will be ignored. This is useful if you're - // outputting to a location that doesn't support colors and you just - // want the strings returned. - Disable bool - - // Reset, if true, will reset the color after each colorization by - // adding a reset code at the end. - Reset bool -} - -// Color colorizes a string according to the settings setup in the struct. -// -// For more details on the syntax, see the top-level Color function. -func (c *Colorize) Color(v string) string { - matches := parseRe.FindAllStringIndex(v, -1) - if len(matches) == 0 { - return v - } - - result := new(bytes.Buffer) - colored := false - m := []int{0, 0} - for _, nm := range matches { - // Write the text in between this match and the last - result.WriteString(v[m[1]:nm[0]]) - m = nm - - var replace string - if code, ok := c.Colors[v[m[0]+1:m[1]-1]]; ok { - colored = true - - if !c.Disable { - replace = fmt.Sprintf("\033[%sm", code) - } - } else { - replace = v[m[0]:m[1]] - } - - result.WriteString(replace) - } - result.WriteString(v[m[1]:]) - - if colored && c.Reset && !c.Disable { - // Write the clear byte at the end - result.WriteString("\033[0m") - } - - return result.String() -} - -// ColorPrefix returns the first color sequence that exists in this string. -// -// For example: "[green]foo" would return "[green]". If no color sequence -// exists, then "" is returned. This is especially useful when wrapping -// colored texts to inherit the color of the wrapped text. -func (c *Colorize) ColorPrefix(v string) string { - return prefixRe.FindString(strings.TrimSpace(v)) -} - -// DefaultColors are the default colors used when colorizing. -// -// If the color is surrounded in underscores, such as "_blue_", then that -// color will be used for the background color. -var DefaultColors map[string]string - -func init() { - DefaultColors = map[string]string{ - // Default foreground/background colors - "default": "39", - "_default_": "49", - - // Foreground colors - "black": "30", - "red": "31", - "green": "32", - "yellow": "33", - "blue": "34", - "magenta": "35", - "cyan": "36", - "light_gray": "37", - "dark_gray": "90", - "light_red": "91", - "light_green": "92", - "light_yellow": "93", - "light_blue": "94", - "light_magenta": "95", - "light_cyan": "96", - "white": "97", - - // Background colors - "_black_": "40", - "_red_": "41", - "_green_": "42", - "_yellow_": "43", - "_blue_": "44", - "_magenta_": "45", - "_cyan_": "46", - "_light_gray_": "47", - "_dark_gray_": "100", - "_light_red_": "101", - "_light_green_": "102", - "_light_yellow_": "103", - "_light_blue_": "104", - "_light_magenta_": "105", - "_light_cyan_": "106", - "_white_": "107", - - // Attributes - "bold": "1", - "dim": "2", - "underline": "4", - "blink_slow": "5", - "blink_fast": "6", - "invert": "7", - "hidden": "8", - - // Reset to reset everything to their defaults - "reset": "0", - "reset_bold": "21", - } - - def = Colorize{ - Colors: DefaultColors, - Reset: true, - } -} - -var def Colorize -var parseReRaw = `\[[a-z0-9_-]+\]` -var parseRe = regexp.MustCompile(`(?i)` + parseReRaw) -var prefixRe = regexp.MustCompile(`^(?i)(` + parseReRaw + `)+`) - -// Print is a convenience wrapper for fmt.Print with support for color codes. -// -// Print formats using the default formats for its operands and writes to -// standard output with support for color codes. Spaces are added between -// operands when neither is a string. It returns the number of bytes written -// and any write error encountered. -func Print(a string) (n int, err error) { - return fmt.Print(Color(a)) -} - -// Println is a convenience wrapper for fmt.Println with support for color -// codes. -// -// Println formats using the default formats for its operands and writes to -// standard output with support for color codes. Spaces are always added -// between operands and a newline is appended. It returns the number of bytes -// written and any write error encountered. -func Println(a string) (n int, err error) { - return fmt.Println(Color(a)) -} - -// Printf is a convenience wrapper for fmt.Printf with support for color codes. -// -// Printf formats according to a format specifier and writes to standard output -// with support for color codes. It returns the number of bytes written and any -// write error encountered. -func Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(Color(format), a...) -} - -// Fprint is a convenience wrapper for fmt.Fprint with support for color codes. -// -// Fprint formats using the default formats for its operands and writes to w -// with support for color codes. Spaces are added between operands when neither -// is a string. It returns the number of bytes written and any write error -// encountered. -func Fprint(w io.Writer, a string) (n int, err error) { - return fmt.Fprint(w, Color(a)) -} - -// Fprintln is a convenience wrapper for fmt.Fprintln with support for color -// codes. -// -// Fprintln formats using the default formats for its operands and writes to w -// with support for color codes. Spaces are always added between operands and a -// newline is appended. It returns the number of bytes written and any write -// error encountered. -func Fprintln(w io.Writer, a string) (n int, err error) { - return fmt.Fprintln(w, Color(a)) -} - -// Fprintf is a convenience wrapper for fmt.Fprintf with support for color -// codes. -// -// Fprintf formats according to a format specifier and writes to w with support -// for color codes. It returns the number of bytes written and any write error -// encountered. -func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, Color(format), a...) -} diff --git a/vendor/github.com/mitchellh/colorstring/go.mod b/vendor/github.com/mitchellh/colorstring/go.mod deleted file mode 100644 index 446ff8d3074..00000000000 --- a/vendor/github.com/mitchellh/colorstring/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/mitchellh/colorstring diff --git a/vendor/github.com/mitchellh/go-testing-interface/testing.go b/vendor/github.com/mitchellh/go-testing-interface/testing.go index 204afb42005..b05a49a6907 100644 --- a/vendor/github.com/mitchellh/go-testing-interface/testing.go +++ b/vendor/github.com/mitchellh/go-testing-interface/testing.go @@ -22,6 +22,7 @@ type T interface { Log(args ...interface{}) Logf(format string, args ...interface{}) Name() string + Parallel() Skip(args ...interface{}) SkipNow() Skipf(format string, args ...interface{}) @@ -31,10 +32,12 @@ type T interface { // RuntimeT implements T and can be instantiated and run at runtime to // mimic *testing.T behavior. Unlike *testing.T, this will simply panic // for calls to Fatal. For calls to Error, you'll have to check the errors -// list to determine whether to exit yourself. Name and Skip methods are -// unimplemented noops. +// list to determine whether to exit yourself. +// +// Parallel does not do anything. type RuntimeT struct { - failed bool + failed bool + skipped bool } func (t *RuntimeT) Error(args ...interface{}) { @@ -77,8 +80,26 @@ func (t *RuntimeT) Logf(format string, args ...interface{}) { log.Println(fmt.Sprintf(format, args...)) } -func (t *RuntimeT) Name() string { return "" } -func (t *RuntimeT) Skip(args ...interface{}) {} -func (t *RuntimeT) SkipNow() {} -func (t *RuntimeT) Skipf(format string, args ...interface{}) {} -func (t *RuntimeT) Skipped() bool { return false } +func (t *RuntimeT) Name() string { + return "" +} + +func (t *RuntimeT) Parallel() {} + +func (t *RuntimeT) Skip(args ...interface{}) { + log.Print(args...) + t.SkipNow() +} + +func (t *RuntimeT) SkipNow() { + t.skipped = true +} + +func (t *RuntimeT) Skipf(format string, args ...interface{}) { + log.Printf(format, args...) + t.SkipNow() +} + +func (t *RuntimeT) Skipped() bool { + return t.skipped +} diff --git a/vendor/github.com/mitchellh/go-testing-interface/testing_go19.go b/vendor/github.com/mitchellh/go-testing-interface/testing_go19.go index 31b42cadf8d..f09c066a424 100644 --- a/vendor/github.com/mitchellh/go-testing-interface/testing_go19.go +++ b/vendor/github.com/mitchellh/go-testing-interface/testing_go19.go @@ -27,6 +27,7 @@ type T interface { Log(args ...interface{}) Logf(format string, args ...interface{}) Name() string + Parallel() Skip(args ...interface{}) SkipNow() Skipf(format string, args ...interface{}) @@ -38,9 +39,11 @@ type T interface { // mimic *testing.T behavior. Unlike *testing.T, this will simply panic // for calls to Fatal. For calls to Error, you'll have to check the errors // list to determine whether to exit yourself. +// +// Parallel does not do anything. type RuntimeT struct { - skipped bool failed bool + skipped bool } func (t *RuntimeT) Error(args ...interface{}) { @@ -87,6 +90,8 @@ func (t *RuntimeT) Name() string { return "" } +func (t *RuntimeT) Parallel() {} + func (t *RuntimeT) Skip(args ...interface{}) { log.Print(args...) t.SkipNow() diff --git a/vendor/github.com/nishanths/exhaustive/.gitignore b/vendor/github.com/nishanths/exhaustive/.gitignore new file mode 100644 index 00000000000..4aca0e85a5d --- /dev/null +++ b/vendor/github.com/nishanths/exhaustive/.gitignore @@ -0,0 +1,4 @@ +.DS_Store + +# binary +cmd/exhaustive/exhaustive diff --git a/vendor/github.com/nishanths/exhaustive/LICENSE b/vendor/github.com/nishanths/exhaustive/LICENSE new file mode 100644 index 00000000000..32befa68f5a --- /dev/null +++ b/vendor/github.com/nishanths/exhaustive/LICENSE @@ -0,0 +1,25 @@ +BSD 2-Clause License + +Copyright (c) 2020, Nishanth Shanmugham +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/nishanths/exhaustive/README.md b/vendor/github.com/nishanths/exhaustive/README.md new file mode 100644 index 00000000000..ecc76c7c5dd --- /dev/null +++ b/vendor/github.com/nishanths/exhaustive/README.md @@ -0,0 +1,85 @@ +# exhaustive + +[![Godoc](https://godoc.org/github.com/nishanths/exhaustive?status.svg)](https://godoc.org/github.com/nishanths/exhaustive) + +The `exhaustive` package and command line program can be used to detect +enum switch statements that are not exhaustive. + +An enum switch statement is exhaustive if it has cases for each of the enum's members. See godoc for the definition of enum used by the program. + +The `exhaustive` package provides an `Analyzer` that follows the guidelines +described in the [go/analysis](https://godoc.org/golang.org/x/tools/go/analysis) package; this makes +it possible to integrate into existing analysis driver programs. + +## Install + +``` +go get github.com/nishanths/exhaustive/... +``` + +## Docs + +https://godoc.org/github.com/nishanths/exhaustive + +## Usage + +The command line usage is: + +``` +Usage: exhaustive [-flags] [packages...] + +Flags: + -default-signifies-exhaustive + indicates that switch statements are to be considered exhaustive if a 'default' case + is present, even if all enum members aren't listed in the switch (default false) + -fix + apply all suggested fixes (default false) + +Examples: + exhaustive code.org/proj/... + exhaustive -fix example.org/foo/pkg example.org/foo/bar +``` + +## Example + +Given the code: + +```diff +package token + +type Token int + +const ( + Add Token = iota + Subtract + Multiply ++ Quotient ++ Remainder +) +``` +``` +package calc + +import "token" + +func processToken(t token.Token) { + switch t { + case token.Add: + // ... + case token.Subtract: + // ... + case token.Multiply: + // ... + } +} +``` + +Running the `exhaustive` command will print: + +``` +calc.go:6:2: missing cases in switch of type token.Token: Quotient, Remainder +``` + +## License + +BSD 2-Clause diff --git a/vendor/github.com/nishanths/exhaustive/enum.go b/vendor/github.com/nishanths/exhaustive/enum.go new file mode 100644 index 00000000000..98b5656b6e1 --- /dev/null +++ b/vendor/github.com/nishanths/exhaustive/enum.go @@ -0,0 +1,99 @@ +package exhaustive + +import ( + "go/ast" + "go/token" + "go/types" + + "golang.org/x/tools/go/analysis" +) + +type enums map[string][]string // enum type name -> enum member names + +func findEnums(pass *analysis.Pass) enums { + pkgEnums := make(enums) + + // Gather enum types. + for _, f := range pass.Files { + for _, decl := range f.Decls { + gen, ok := decl.(*ast.GenDecl) + if !ok { + continue + } + if gen.Tok != token.TYPE { + continue + } + for _, s := range gen.Specs { + // Must be TypeSpec since we've filtered on token.TYPE. + t, ok := s.(*ast.TypeSpec) + obj := pass.TypesInfo.Defs[t.Name] + if obj == nil { + continue + } + + named, ok := obj.Type().(*types.Named) + if !ok { + continue + } + basic, ok := named.Underlying().(*types.Basic) + if !ok { + continue + } + switch i := basic.Info(); { + case i&types.IsInteger != 0: + pkgEnums[named.Obj().Name()] = nil + case i&types.IsFloat != 0: + pkgEnums[named.Obj().Name()] = nil + case i&types.IsString != 0: + pkgEnums[named.Obj().Name()] = nil + } + } + } + } + + // Gather enum members. + for _, f := range pass.Files { + for _, decl := range f.Decls { + gen, ok := decl.(*ast.GenDecl) + if !ok { + continue + } + if gen.Tok != token.CONST && gen.Tok != token.VAR { + continue + } + for _, s := range gen.Specs { + // Must be ValueSpec since we've filtered on token.CONST, token.VAR. + v := s.(*ast.ValueSpec) + for _, name := range v.Names { + obj := pass.TypesInfo.Defs[name] + if obj == nil { + continue + } + named, ok := obj.Type().(*types.Named) + if !ok { + continue + } + + members, ok := pkgEnums[named.Obj().Name()] + if !ok { + continue + } + members = append(members, obj.Name()) + pkgEnums[named.Obj().Name()] = members + } + } + } + } + + // Delete member-less enum types. + // We can't call these enums, since we can't be sure without + // the existence of members. (The type may just be a named type, + // for instance.) + for k, v := range pkgEnums { + if len(v) == 0 { + delete(pkgEnums, k) + } + } + + return pkgEnums +} diff --git a/vendor/github.com/nishanths/exhaustive/exhaustive.go b/vendor/github.com/nishanths/exhaustive/exhaustive.go new file mode 100644 index 00000000000..ef869f26833 --- /dev/null +++ b/vendor/github.com/nishanths/exhaustive/exhaustive.go @@ -0,0 +1,182 @@ +// Package exhaustive provides an analyzer that helps ensure enum switch statements +// are exhaustive. The analyzer also provides fixes to make the offending switch +// statements exhaustive (see "Fixes" section). +// +// See "cmd/exhaustive" subpackage for the related command line program. +// +// Definition of enum +// +// The language spec does not provide an explicit definition for enums. +// For the purpose of this program, an enum type is a package-level named type +// whose underlying type is an integer (includes byte and rune), a float, or +// a string type. An enum type must have associated with it one or more +// package-level variables of the named type in the package. These variables +// constitute the enum's members. +// +// In the code snippet below, Biome is an enum type with 3 members. +// +// type Biome int +// +// const ( +// Tundra Biome = iota +// Savanna +// Desert +// ) +// +// Switch statement exhaustiveness +// +// An enum switch statement is exhaustive if it has cases for each of the enum's members. +// +// For an enum type defined in the same package as the switch statement, both +// exported and unexported enum members must be present in order to consider +// the switch exhaustive. On the other hand, for an enum type defined +// in an external package it is sufficient for just exported enum members +// to be present in order to consider the switch exhaustive. +// +// Flags +// +// The analyzer accepts a boolean flag: -default-signifies-exhaustive. +// The flag, if set, indicates to the analyzer that switch statements +// are to be considered exhaustive as long as a 'default' case is present, even +// if all enum members aren't listed in the switch statements cases. +// +// The other relevant flag is the -fix flag. +// +// Fixes +// +// The analyzer suggests fixes for a switch statement if it is not exhaustive +// and does not have a 'default' case. The suggested fix always adds a single +// case clause for the missing enum members. +// +// case missingA, missingB, missingC: +// panic(fmt.Sprintf("unhandled value: %v", v)) +// +// where v is the expression in the switch statement's tag (in other words, the +// value being switched upon). If the switch statement's tag is a function or a +// method call the analyzer does not suggest a fix, as reusing the call expression +// in the panic/fmt.Sprintf call could be mutative. +// +// The rationale for the fix using panic is that it might be better to fail loudly on +// existing unhandled or impossible cases than to let them slip by quietly unnoticed. +// An even better fix may, of course, be to manually inspect the sites reported +// by the package and handle the missing cases if necessary. +// +// Imports will be adjusted automatically to account for the "fmt" dependency. +// +// Skip analysis of specific switch statements +// +// If the following directive comment: +// +// //exhaustive:ignore +// +// is associated with a switch statement, the analyzer skips +// checking of the switch statement and no diagnostics are reported. +package exhaustive + +import ( + "go/ast" + "go/types" + "sort" + "strings" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/inspector" +) + +const ( + // DefaultSignifiesExhaustiveFlag is a flag name used by the analyzer. It + // is exported for use by analyzer driver programs. + DefaultSignifiesExhaustiveFlag = "default-signifies-exhaustive" +) + +var ( + fCheckMaps bool + fDefaultSignifiesExhaustive bool +) + +func init() { + Analyzer.Flags.BoolVar(&fCheckMaps, "maps", false, "check key exhaustiveness for map literals of enum key type, in addition to checking switch statements") + Analyzer.Flags.BoolVar(&fDefaultSignifiesExhaustive, DefaultSignifiesExhaustiveFlag, false, "indicates that switch statements are to be considered exhaustive if a 'default' case is present, even if all enum members aren't listed in the switch") +} + +var Analyzer = &analysis.Analyzer{ + Name: "exhaustive", + Doc: "check exhaustiveness of enum switch statements", + Run: run, + Requires: []*analysis.Analyzer{inspect.Analyzer}, + FactTypes: []analysis.Fact{&enumsFact{}}, +} + +// IgnoreDirectivePrefix is used to exclude checking of specific switch statements. +// See https://godoc.org/github.com/nishanths/exhaustive#hdr-Skip_analysis_of_specific_switch_statements +// for details. +const IgnoreDirectivePrefix = "//exhaustive:ignore" + +func containsIgnoreDirective(comments []*ast.Comment) bool { + for _, c := range comments { + if strings.HasPrefix(c.Text, IgnoreDirectivePrefix) { + return true + } + } + return false +} + +type enumsFact struct { + Entries enums +} + +var _ analysis.Fact = (*enumsFact)(nil) + +func (e *enumsFact) AFact() {} + +func (e *enumsFact) String() string { + // sort for stability (required for testing) + var sortedKeys []string + for k := range e.Entries { + sortedKeys = append(sortedKeys, k) + } + sort.Strings(sortedKeys) + + var buf strings.Builder + for i, k := range sortedKeys { + v := e.Entries[k] + buf.WriteString(k) + buf.WriteString(":") + for j, vv := range v { + buf.WriteString(vv) + // add comma separator between each enum member in an enum type + if j != len(v)-1 { + buf.WriteString(",") + } + } + // add semicolon separator between each enum type + if i != len(sortedKeys)-1 { + buf.WriteString("; ") + } + } + return buf.String() +} + +func run(pass *analysis.Pass) (interface{}, error) { + e := findEnums(pass) + if len(e) != 0 { + pass.ExportPackageFact(&enumsFact{Entries: e}) + } + + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) + comments := make(map[*ast.File]ast.CommentMap) // CommentMap per package file, lazily populated by reference + + checkSwitchStatements(pass, inspect, comments) + if fCheckMaps { + checkMapLiterals(pass, inspect, comments) + } + return nil, nil +} + +func enumTypeName(e *types.Named, samePkg bool) string { + if samePkg { + return e.Obj().Name() + } + return e.Obj().Pkg().Name() + "." + e.Obj().Name() +} diff --git a/vendor/github.com/nishanths/exhaustive/go.mod b/vendor/github.com/nishanths/exhaustive/go.mod new file mode 100644 index 00000000000..b15048eab4a --- /dev/null +++ b/vendor/github.com/nishanths/exhaustive/go.mod @@ -0,0 +1,5 @@ +module github.com/nishanths/exhaustive + +go 1.14 + +require golang.org/x/tools v0.0.0-20200519015757-0d0afa43d58a diff --git a/vendor/github.com/nishanths/exhaustive/go.sum b/vendor/github.com/nishanths/exhaustive/go.sum new file mode 100644 index 00000000000..01ba9996547 --- /dev/null +++ b/vendor/github.com/nishanths/exhaustive/go.sum @@ -0,0 +1,21 @@ +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200519015757-0d0afa43d58a h1:gILuVKC+ZPD6g/tj6zBOdnOH1ZHI0zZ86+KLMogc6/s= +golang.org/x/tools v0.0.0-20200519015757-0d0afa43d58a/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200519142718-10921354bc51 h1:GtYAC9y+dpwWCXBwbcZgxcFfiqW4SI93yvQqpF+9+P8= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/vendor/github.com/nishanths/exhaustive/map.go b/vendor/github.com/nishanths/exhaustive/map.go new file mode 100644 index 00000000000..95e5627c260 --- /dev/null +++ b/vendor/github.com/nishanths/exhaustive/map.go @@ -0,0 +1,148 @@ +package exhaustive + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + "sort" + "strings" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/ast/astutil" + "golang.org/x/tools/go/ast/inspector" +) + +func checkMapLiterals(pass *analysis.Pass, inspect *inspector.Inspector, comments map[*ast.File]ast.CommentMap) { + for _, f := range pass.Files { + for _, d := range f.Decls { + gen, ok := d.(*ast.GenDecl) + if !ok { + continue + } + if gen.Tok != token.VAR { + continue // map literals have to be declared as "var" + } + for _, s := range gen.Specs { + valueSpec := s.(*ast.ValueSpec) + for idx, name := range valueSpec.Names { + obj := pass.TypesInfo.Defs[name] + if obj == nil { + continue + } + + mapType, ok := obj.Type().(*types.Map) + if !ok { + continue + } + + keyType, ok := mapType.Key().(*types.Named) + if !ok { + continue + } + keyPkg := keyType.Obj().Pkg() + if keyPkg == nil { + // Doc comment: nil for labels and objects in the Universe scope. + // This happens for the `error` type, for example. + // Continuing would mean that ImportPackageFact panics. + continue + } + + var enums enumsFact + if !pass.ImportPackageFact(keyPkg, &enums) { + // Can't do anything further. + continue + } + + enumMembers, ok := enums.Entries[keyType.Obj().Name()] + if !ok { + // Key type is not a known enum. + continue + } + + // Check comments for the ignore directive. + + var allComments ast.CommentMap + if cm, ok := comments[f]; ok { + allComments = cm + } else { + allComments = ast.NewCommentMap(pass.Fset, f, f.Comments) + comments[f] = allComments + } + + genDeclComments := allComments.Filter(gen) + genDeclIgnore := false + for _, group := range genDeclComments.Comments() { + if containsIgnoreDirective(group.List) && gen.Lparen == token.NoPos && len(gen.Specs) == 1 { + genDeclIgnore = true + break + } + } + if genDeclIgnore { + continue + } + + if (valueSpec.Doc != nil && containsIgnoreDirective(valueSpec.Doc.List)) || + (valueSpec.Comment != nil && containsIgnoreDirective(valueSpec.Comment.List)) { + continue + } + + samePkg := keyPkg == pass.Pkg + checkUnexported := samePkg + + hitlist := hitlistFromEnumMembers(enumMembers, checkUnexported) + if len(hitlist) == 0 { + // can happen if external package and enum consists only of + // unexported members + continue + } + + if !(len(valueSpec.Values) > idx) { + continue // no value for name + } + comp, ok := valueSpec.Values[idx].(*ast.CompositeLit) + if !ok { + continue + } + for _, el := range comp.Elts { + kvExpr, ok := el.(*ast.KeyValueExpr) + if !ok { + continue + } + e := astutil.Unparen(kvExpr.Key) + if samePkg { + ident, ok := e.(*ast.Ident) + if !ok { + continue + } + delete(hitlist, ident.Name) + } else { + selExpr, ok := e.(*ast.SelectorExpr) + if !ok { + continue + } + delete(hitlist, selExpr.Sel.Name) + } + } + + if len(hitlist) > 0 { + reportMapLiteral(pass, name, samePkg, keyType, hitlist) + } + } + } + } + } +} + +func reportMapLiteral(pass *analysis.Pass, mapVarIdent *ast.Ident, samePkg bool, enumType *types.Named, missingMembers map[string]struct{}) { + missing := make([]string, 0, len(missingMembers)) + for m := range missingMembers { + missing = append(missing, m) + } + sort.Strings(missing) + + pass.Report(analysis.Diagnostic{ + Pos: mapVarIdent.Pos(), + Message: fmt.Sprintf("missing keys in map %s of key type %s: %s", mapVarIdent.Name, enumTypeName(enumType, samePkg), strings.Join(missing, ", ")), + }) +} diff --git a/vendor/github.com/nishanths/exhaustive/switch.go b/vendor/github.com/nishanths/exhaustive/switch.go new file mode 100644 index 00000000000..47b970fb9b3 --- /dev/null +++ b/vendor/github.com/nishanths/exhaustive/switch.go @@ -0,0 +1,348 @@ +package exhaustive + +import ( + "bytes" + "fmt" + "go/ast" + "go/printer" + "go/token" + "go/types" + "sort" + "strconv" + "strings" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/ast/astutil" + "golang.org/x/tools/go/ast/inspector" +) + +func isDefaultCase(c *ast.CaseClause) bool { + return c.List == nil // see doc comment on field +} + +func checkSwitchStatements(pass *analysis.Pass, inspect *inspector.Inspector, comments map[*ast.File]ast.CommentMap) { + inspect.WithStack([]ast.Node{&ast.SwitchStmt{}}, func(n ast.Node, push bool, stack []ast.Node) bool { + if !push { + return true + } + sw := n.(*ast.SwitchStmt) + if sw.Tag == nil { + return true + } + t := pass.TypesInfo.Types[sw.Tag] + if !t.IsValue() { + return true + } + tagType, ok := t.Type.(*types.Named) + if !ok { + return true + } + + tagPkg := tagType.Obj().Pkg() + if tagPkg == nil { + // Doc comment: nil for labels and objects in the Universe scope. + // This happens for the `error` type, for example. + // Continuing would mean that ImportPackageFact panics. + return true + } + + var enums enumsFact + if !pass.ImportPackageFact(tagPkg, &enums) { + // Can't do anything further. + return true + } + + enumMembers, isEnum := enums.Entries[tagType.Obj().Name()] + if !isEnum { + // Tag's type is not a known enum. + return true + } + + // Get comment map. + file := stack[0].(*ast.File) + var allComments ast.CommentMap + if cm, ok := comments[file]; ok { + allComments = cm + } else { + allComments = ast.NewCommentMap(pass.Fset, file, file.Comments) + comments[file] = allComments + } + + specificComments := allComments.Filter(sw) + for _, group := range specificComments.Comments() { + if containsIgnoreDirective(group.List) { + return true // skip checking due to ignore directive + } + } + + samePkg := tagPkg == pass.Pkg + checkUnexported := samePkg + + hitlist := hitlistFromEnumMembers(enumMembers, checkUnexported) + if len(hitlist) == 0 { + // can happen if external package and enum consists only of + // unexported members + return true + } + + defaultCaseExists := false + for _, stmt := range sw.Body.List { + caseCl := stmt.(*ast.CaseClause) + if isDefaultCase(caseCl) { + defaultCaseExists = true + continue // nothing more to do if it's the default case + } + for _, e := range caseCl.List { + e = astutil.Unparen(e) + if samePkg { + ident, ok := e.(*ast.Ident) + if !ok { + continue + } + delete(hitlist, ident.Name) + } else { + selExpr, ok := e.(*ast.SelectorExpr) + if !ok { + continue + } + delete(hitlist, selExpr.Sel.Name) + } + } + } + + defaultSuffices := fDefaultSignifiesExhaustive && defaultCaseExists + shouldReport := len(hitlist) > 0 && !defaultSuffices + + if shouldReport { + reportSwitch(pass, sw, samePkg, tagType, hitlist, defaultCaseExists, file) + } + return true + }) +} + +func hitlistFromEnumMembers(enumMembers []string, checkUnexported bool) map[string]struct{} { + hitlist := make(map[string]struct{}) + for _, m := range enumMembers { + if m == "_" { + // blank identifier is often used to skip entries in iota lists + continue + } + if ast.IsExported(m) || checkUnexported { + hitlist[m] = struct{}{} + } + } + return hitlist +} + +func reportSwitch(pass *analysis.Pass, sw *ast.SwitchStmt, samePkg bool, enumType *types.Named, missingMembers map[string]struct{}, defaultCaseExists bool, f *ast.File) { + missing := make([]string, 0, len(missingMembers)) + for m := range missingMembers { + missing = append(missing, m) + } + sort.Strings(missing) + + var fixes []analysis.SuggestedFix + if !defaultCaseExists { + if fix, ok := computeFix(pass, pass.Fset, f, sw, enumType, samePkg, missingMembers); ok { + fixes = append(fixes, fix) + } + } + + pass.Report(analysis.Diagnostic{ + Pos: sw.Pos(), + End: sw.End(), + Message: fmt.Sprintf("missing cases in switch of type %s: %s", enumTypeName(enumType, samePkg), strings.Join(missing, ", ")), + SuggestedFixes: fixes, + }) +} + +func computeFix(pass *analysis.Pass, fset *token.FileSet, f *ast.File, sw *ast.SwitchStmt, enumType *types.Named, samePkg bool, missingMembers map[string]struct{}) (analysis.SuggestedFix, bool) { + // Function and method calls may be mutative, so we don't want to reuse the + // call expression in the about-to-be-inserted case clause body. So we just + // don't suggest a fix in such situations. + // + // However, we need to make an exception for type conversions, which are + // also call expressions in the AST. + // + // We'll need to lookup type information for this, and can't rely solely + // on the AST. + if containsFuncCall(pass, sw.Tag) { + return analysis.SuggestedFix{}, false + } + + textEdits := []analysis.TextEdit{ + missingCasesTextEdit(fset, f, samePkg, sw, enumType, missingMembers), + } + + // need to add "fmt" import if "fmt" import doesn't already exist + if !hasImportWithPath(fset, f, `"fmt"`) { + textEdits = append(textEdits, fmtImportTextEdit(fset, f)) + } + + missing := make([]string, 0, len(missingMembers)) + for m := range missingMembers { + missing = append(missing, m) + } + sort.Strings(missing) + + return analysis.SuggestedFix{ + Message: fmt.Sprintf("add case clause for: %s?", strings.Join(missing, ", ")), + TextEdits: textEdits, + }, true +} + +func containsFuncCall(pass *analysis.Pass, e ast.Expr) bool { + e = astutil.Unparen(e) + c, ok := e.(*ast.CallExpr) + if !ok { + return false + } + if _, isFunc := pass.TypesInfo.TypeOf(c.Fun).Underlying().(*types.Signature); isFunc { + return true + } + for _, a := range c.Args { + if containsFuncCall(pass, a) { + return true + } + } + return false +} + +func firstImportDecl(fset *token.FileSet, f *ast.File) *ast.GenDecl { + for _, decl := range f.Decls { + genDecl, ok := decl.(*ast.GenDecl) + if ok && genDecl.Tok == token.IMPORT { + // first IMPORT GenDecl + return genDecl + } + } + return nil +} + +// copies an GenDecl in a manner such that appending to the returned GenDecl's Specs field +// doesn't mutate the original GenDecl +func copyGenDecl(im *ast.GenDecl) *ast.GenDecl { + imCopy := *im + imCopy.Specs = make([]ast.Spec, len(im.Specs)) + for i := range im.Specs { + imCopy.Specs[i] = im.Specs[i] + } + return &imCopy +} + +func hasImportWithPath(fset *token.FileSet, f *ast.File, pathLiteral string) bool { + igroups := astutil.Imports(fset, f) + for _, igroup := range igroups { + for _, importSpec := range igroup { + if importSpec.Path.Value == pathLiteral { + return true + } + } + } + return false +} + +func fmtImportTextEdit(fset *token.FileSet, f *ast.File) analysis.TextEdit { + firstDecl := firstImportDecl(fset, f) + + if firstDecl == nil { + // file has no import declarations + // insert "fmt" import spec after package statement + return analysis.TextEdit{ + Pos: f.Name.End() + 1, // end of package name + 1 + End: f.Name.End() + 1, + NewText: []byte(`import ( + "fmt" + )`), + } + } + + // copy because we'll be mutating its Specs field + firstDeclCopy := copyGenDecl(firstDecl) + + // find insertion index for "fmt" import spec + var i int + for ; i < len(firstDeclCopy.Specs); i++ { + im := firstDeclCopy.Specs[i].(*ast.ImportSpec) + if v, _ := strconv.Unquote(im.Path.Value); v > "fmt" { + break + } + } + + // insert "fmt" import spec at the index + fmtSpec := &ast.ImportSpec{ + Path: &ast.BasicLit{ + // NOTE: Pos field doesn't seem to be required for our + // purposes here. + Kind: token.STRING, + Value: `"fmt"`, + }, + } + s := firstDeclCopy.Specs // local var for easier comprehension of next line + s = append(s[:i], append([]ast.Spec{fmtSpec}, s[i:]...)...) + firstDeclCopy.Specs = s + + // create the text edit + var buf bytes.Buffer + printer.Fprint(&buf, fset, firstDeclCopy) + + return analysis.TextEdit{ + Pos: firstDecl.Pos(), + End: firstDecl.End(), + NewText: buf.Bytes(), + } +} + +func missingCasesTextEdit(fset *token.FileSet, f *ast.File, samePkg bool, sw *ast.SwitchStmt, enumType *types.Named, missingMembers map[string]struct{}) analysis.TextEdit { + // ... Construct insertion text for case clause and its body ... + + var tag bytes.Buffer + printer.Fprint(&tag, fset, sw.Tag) + + // If possible and if necessary, determine the package identifier based on the AST of other `case` clauses. + var pkgIdent *ast.Ident + if !samePkg { + for _, stmt := range sw.Body.List { + caseCl := stmt.(*ast.CaseClause) + // At least one expression must exist in List at this point. + // List cannot be nil because we only arrive here if the "default" clause + // does not exist. Additionally, a syntactically valid case clause must + // have at least one expression. + if sel, ok := caseCl.List[0].(*ast.SelectorExpr); ok { + pkgIdent = sel.X.(*ast.Ident) + break + } + } + } + + missing := make([]string, 0, len(missingMembers)) + for m := range missingMembers { + if !samePkg { + if pkgIdent != nil { + // we were able to determine package identifier + missing = append(missing, pkgIdent.Name+"."+m) + } else { + // use the package name (may not be correct always) + // + // TODO: May need to also add import if the package isn't imported + // elsewhere. This (ie, a switch with zero case clauses) should + // happen rarely, so don't implement this for now. + missing = append(missing, enumType.Obj().Pkg().Name()+"."+m) + } + } else { + missing = append(missing, m) + } + } + sort.Strings(missing) + + insert := `case ` + strings.Join(missing, ", ") + `: + panic(fmt.Sprintf("unhandled value: %v",` + tag.String() + `))` + + // ... Create the text edit ... + + return analysis.TextEdit{ + Pos: sw.Body.Rbrace - 1, + End: sw.Body.Rbrace - 1, + NewText: []byte(insert), + } +} diff --git a/vendor/github.com/phayes/checkstyle/.scrutinizer.yml b/vendor/github.com/phayes/checkstyle/.scrutinizer.yml new file mode 100644 index 00000000000..d9284b6b4b7 --- /dev/null +++ b/vendor/github.com/phayes/checkstyle/.scrutinizer.yml @@ -0,0 +1,15 @@ +build: + dependencies: + before: + - 'source <(curl -fsSL https://raw.githubusercontent.com/phayes/go-scrutinize/master/install-golang)' + + tests: + override: + - + command: 'cd $PROJECTPATH && go-scrutinize' + coverage: + file: 'coverage.xml' + format: 'clover' + analysis: + file: 'checkstyle_report.xml' + format: 'general-checkstyle' \ No newline at end of file diff --git a/vendor/github.com/phayes/checkstyle/LICENSE b/vendor/github.com/phayes/checkstyle/LICENSE new file mode 100644 index 00000000000..6dc912f39e5 --- /dev/null +++ b/vendor/github.com/phayes/checkstyle/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2017, Patrick D Hayes +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 the copyright holder 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/phayes/checkstyle/README.md b/vendor/github.com/phayes/checkstyle/README.md new file mode 100644 index 00000000000..358cf6752cf --- /dev/null +++ b/vendor/github.com/phayes/checkstyle/README.md @@ -0,0 +1,44 @@ +# checkstyle +[![GoDoc](https://godoc.org/github.com/phayes/checkstyle?status.svg)](https://godoc.org/github.com/phayes/checkstyle) +[![Go Report Card](https://goreportcard.com/badge/github.com/phayes/checkstyle)](https://goreportcard.com/report/github.com/phayes/checkstyle) +[![Build Status](https://scrutinizer-ci.com/g/phayes/checkstyle/badges/build.png?b=master)](https://scrutinizer-ci.com/g/phayes/checkstyle/build-status/master) + +Read and write checksyle_report.xml files with golang + +Checkstyle XML files are a standard file format for reporting errors in source code, and is often generated by static analysis tools. + +Example usage: + +```go + +import "github.com/phayes/checkstyle" + +// Print XML into human readable format +checkSyle, err := checkstyle.ReadFile("checkstyle_report.xml") +if err != nil { + log.Fatal(err) +} +for _, file := range checkStyle.File { + fmt.Println(File.Name) + for _, codingError := range file.Error { + fmt.Println("\t", codingError.Line, codingError.Message) + } +} + +// Create a new XML file from scratch +check := checkstyle.New() + +// Ensure that a file has been added +file := check.EnsureFile("/path/to/file") + +// Create an error on line 10 +codingError := checkstyle.NewError(10, "format", "line must end with a full stop") + +// Add the error to the file +file.AddError(codingError) + +// Output XML +fmt.Print(check) +``` + +For more information on checkstyle XML see: http://checkstyle.sourceforge.net/checks.html diff --git a/vendor/github.com/phayes/checkstyle/checkstyle.go b/vendor/github.com/phayes/checkstyle/checkstyle.go new file mode 100644 index 00000000000..cabbd4b40ed --- /dev/null +++ b/vendor/github.com/phayes/checkstyle/checkstyle.go @@ -0,0 +1,112 @@ +package checkstyle + +import "encoding/xml" +import "io/ioutil" + +// DefaultCheckStyleVersion defines the default "version" attribute on "" lememnt +var DefaultCheckStyleVersion = "1.0.0" + +// Severity defines a checkstyle severity code +type Severity string + +var ( + SeverityError Severity = "error" + SeverityInfo Severity = "info" + SeverityWarning Severity = "warning" + SeverityIgnore Severity = "ignore" + SeverityNone Severity +) + +// CheckStyle represents a xml element found in a checkstyle_report.xml file. +type CheckStyle struct { + XMLName xml.Name `xml:"checkstyle"` + Version string `xml:"version,attr"` + File []*File `xml:"file"` +} + +// AddFile adds a checkstyle.File with the given filename. +func (cs *CheckStyle) AddFile(csf *File) { + cs.File = append(cs.File, csf) +} + +// GetFile gets a CheckStyleFile with the given filename. +func (cs *CheckStyle) GetFile(filename string) (csf *File, ok bool) { + for _, file := range cs.File { + if file.Name == filename { + csf = file + ok = true + return + } + } + return +} + +// EnsureFile ensures that a CheckStyleFile with the given name exists +// Returns either an exiting CheckStyleFile (if a file with that name exists) +// or a new CheckStyleFile (if a file with that name does not exists) +func (cs *CheckStyle) EnsureFile(filename string) (csf *File) { + csf, ok := cs.GetFile(filename) + if !ok { + csf = NewFile(filename) + cs.AddFile(csf) + } + return csf +} + +// String implements Stringer. Returns as xml. +func (cs *CheckStyle) String() string { + checkStyleXML, err := xml.Marshal(cs) + if err != nil { + panic(err) + } + return string(checkStyleXML) +} + +// New returns a new CheckStyle +func New() *CheckStyle { + return &CheckStyle{Version: DefaultCheckStyleVersion, File: []*File{}} +} + +// File represents a xml element. +type File struct { + XMLName xml.Name `xml:"file"` + Name string `xml:"name,attr"` + Error []*Error `xml:"error"` +} + +// AddError adds a checkstyle.Error to the file. +func (csf *File) AddError(cse *Error) { + csf.Error = append(csf.Error, cse) +} + +// NewFile creates a new checkstyle.File +func NewFile(filename string) *File { + return &File{Name: filename, Error: []*Error{}} +} + +// Error represents a xml element +type Error struct { + XMLName xml.Name `xml:"error"` + Line int `xml:"line,attr"` + Column int `xml:"column,attr,omitempty"` + Severity Severity `xml:"severity,attr,omitempty"` + Message string `xml:"message,attr"` + Source string `xml:"source,attr"` +} + +// NewError creates a new checkstyle.Error +// Note that line starts at 0, and column starts at 1 +func NewError(line int, column int, severity Severity, message string, source string) *Error { + return &Error{Line: line, Column: column, Severity: severity, Message: message, Source: source} +} + +// ReadFile reads a checkfile.xml file and returns a CheckStyle object. +func ReadFile(filename string) (*CheckStyle, error) { + checkStyleXML, err := ioutil.ReadFile(filename) + if err != nil { + return nil, err + } + checkStyle := New() + err = xml.Unmarshal(checkStyleXML, checkStyle) + return checkStyle, err +} diff --git a/vendor/github.com/phayes/checkstyle/godoc.go b/vendor/github.com/phayes/checkstyle/godoc.go new file mode 100644 index 00000000000..c9662fe9ed2 --- /dev/null +++ b/vendor/github.com/phayes/checkstyle/godoc.go @@ -0,0 +1,36 @@ +/* +Package checkstyle allows the parsing of generation of checkstyle XML files. + +Checkstyle XML files are a standard file format for reporting errors in source code, and is often generated by static analysis tools. + +Example usage: + // Print XML into human readable format + checkSyle, err := checkstyle.ReadFile("checkstyle_report.xml") + if err != nil { + log.Fatal(err) + } + for _, file := range checkStyle.File { + fmt.Println(File.Name) + for _, codingError := range file.Error { + fmt.Println("\t", codingError.Line, codingError.Message) + } + } + + // Create a new XML file from scratch + check := checkstyle.New() + + // Ensure that a file has been added + file := check.EnsureFile("/path/to/file") + + // Create an error on line 10, column 5 + codingError := checkstyle.NewError(10, 5, checkstyle.SeverityWarning, "format", "line must end with a full stop") + + // Add the error to the file + file.AddError(codingError) + + // Output XML + fmt.Print(check) + +For more information on checkstyle XML see: http://checkstyle.sourceforge.net/checks.html +*/ +package checkstyle diff --git a/vendor/github.com/pierrec/lz4/.gitignore b/vendor/github.com/pierrec/lz4/.gitignore deleted file mode 100644 index e48bab32a5d..00000000000 --- a/vendor/github.com/pierrec/lz4/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -# Created by https://www.gitignore.io/api/macos - -### macOS ### -*.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two \r -Icon - - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.com.apple.timemachine.donotpresent - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -# End of https://www.gitignore.io/api/macos - -lz4c/lz4c diff --git a/vendor/github.com/pierrec/lz4/.travis.yml b/vendor/github.com/pierrec/lz4/.travis.yml deleted file mode 100644 index b2c806d577e..00000000000 --- a/vendor/github.com/pierrec/lz4/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: go - -go: - - 1.8.x - - 1.9.x - - 1.10.x - - master - -matrix: - fast_finish: true - allow_failures: - - go: master - -sudo: false - -script: - - go test -v -cpu=2 - - go test -v -cpu=2 -race diff --git a/vendor/github.com/pierrec/lz4/LICENSE b/vendor/github.com/pierrec/lz4/LICENSE deleted file mode 100644 index bd899d8353d..00000000000 --- a/vendor/github.com/pierrec/lz4/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2015, Pierre Curto -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 xxHash 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/vendor/github.com/pierrec/lz4/README.md b/vendor/github.com/pierrec/lz4/README.md deleted file mode 100644 index 50a10ee1608..00000000000 --- a/vendor/github.com/pierrec/lz4/README.md +++ /dev/null @@ -1,24 +0,0 @@ -[![godoc](https://godoc.org/github.com/pierrec/lz4?status.png)](https://godoc.org/github.com/pierrec/lz4) - -# lz4 -LZ4 compression and decompression in pure Go. - -## Usage - -```go -import "github.com/pierrec/lz4" -``` - -## Description -Package lz4 implements reading and writing lz4 compressed data (a frame), -as specified in http://fastcompression.blogspot.fr/2013/04/lz4-streaming-format-final.html. - -This package is **compatible with the LZ4 frame format** although the block level compression -and decompression functions are exposed and are fully compatible with the lz4 block format -definition, they are low level and should not be used directly. - -For a complete description of an lz4 compressed block, see: -http://fastcompression.blogspot.fr/2011/05/lz4-explained.html - -See https://github.com/Cyan4973/lz4 for the reference C implementation. - diff --git a/vendor/github.com/pierrec/lz4/block.go b/vendor/github.com/pierrec/lz4/block.go deleted file mode 100644 index ef24f17e57a..00000000000 --- a/vendor/github.com/pierrec/lz4/block.go +++ /dev/null @@ -1,397 +0,0 @@ -package lz4 - -import ( - "encoding/binary" - "errors" -) - -var ( - // ErrInvalidSourceShortBuffer is returned by UncompressBlock or CompressBLock when a compressed - // block is corrupted or the destination buffer is not large enough for the uncompressed data. - ErrInvalidSourceShortBuffer = errors.New("lz4: invalid source or destination buffer too short") - // ErrInvalid is returned when reading an invalid LZ4 archive. - ErrInvalid = errors.New("lz4: bad magic number") -) - -// blockHash hashes 4 bytes into a value < winSize. -func blockHash(x uint32) uint32 { - const hasher uint32 = 2654435761 // Knuth multiplicative hash. - return x * hasher >> hashShift -} - -// CompressBlockBound returns the maximum size of a given buffer of size n, when not compressible. -func CompressBlockBound(n int) int { - return n + n/255 + 16 -} - -// UncompressBlock uncompresses the source buffer into the destination one, -// and returns the uncompressed size. -// -// The destination buffer must be sized appropriately. -// -// An error is returned if the source data is invalid or the destination buffer is too small. -func UncompressBlock(src, dst []byte) (si int, err error) { - defer func() { - // It is now faster to let the runtime panic and recover on out of bound slice access - // than checking indices as we go along. - if recover() != nil { - err = ErrInvalidSourceShortBuffer - } - }() - sn := len(src) - if sn == 0 { - return 0, nil - } - var di int - - for { - // Literals and match lengths (token). - b := int(src[si]) - si++ - - // Literals. - if lLen := b >> 4; lLen > 0 { - if lLen == 0xF { - for src[si] == 0xFF { - lLen += 0xFF - si++ - } - lLen += int(src[si]) - si++ - } - i := si - si += lLen - di += copy(dst[di:], src[i:si]) - - if si >= sn { - return di, nil - } - } - - si++ - _ = src[si] // Bound check elimination. - offset := int(src[si-1]) | int(src[si])<<8 - si++ - - // Match. - mLen := b & 0xF - if mLen == 0xF { - for src[si] == 0xFF { - mLen += 0xFF - si++ - } - mLen += int(src[si]) - si++ - } - mLen += minMatch - - // Copy the match. - i := di - offset - if offset > 0 && mLen >= offset { - // Efficiently copy the match dst[di-offset:di] into the dst slice. - bytesToCopy := offset * (mLen / offset) - expanded := dst[i:] - for n := offset; n <= bytesToCopy+offset; n *= 2 { - copy(expanded[n:], expanded[:n]) - } - di += bytesToCopy - mLen -= bytesToCopy - } - di += copy(dst[di:], dst[i:i+mLen]) - } -} - -// CompressBlock compresses the source buffer into the destination one. -// This is the fast version of LZ4 compression and also the default one. -// The size of hashTable must be at least 64Kb. -// -// The size of the compressed data is returned. If it is 0 and no error, then the data is incompressible. -// -// An error is returned if the destination buffer is too small. -func CompressBlock(src, dst []byte, hashTable []int) (di int, err error) { - defer func() { - if recover() != nil { - err = ErrInvalidSourceShortBuffer - } - }() - - sn, dn := len(src)-mfLimit, len(dst) - if sn <= 0 || dn == 0 { - return 0, nil - } - var si int - - // Fast scan strategy: the hash table only stores the last 4 bytes sequences. - // const accInit = 1 << skipStrength - - anchor := si // Position of the current literals. - // acc := accInit // Variable step: improves performance on non-compressible data. - - for si < sn { - // Hash the next 4 bytes (sequence)... - match := binary.LittleEndian.Uint32(src[si:]) - h := blockHash(match) - - ref := hashTable[h] - hashTable[h] = si - if ref >= sn { // Invalid reference (dirty hashtable). - si++ - continue - } - offset := si - ref - if offset <= 0 || offset >= winSize || // Out of window. - match != binary.LittleEndian.Uint32(src[ref:]) { // Hash collision on different matches. - // si += acc >> skipStrength - // acc++ - si++ - continue - } - - // Match found. - // acc = accInit - lLen := si - anchor // Literal length. - - // Encode match length part 1. - si += minMatch - mLen := si // Match length has minMatch already. - // Find the longest match, first looking by batches of 8 bytes. - for si < sn && binary.LittleEndian.Uint64(src[si:]) == binary.LittleEndian.Uint64(src[si-offset:]) { - si += 8 - } - // Then byte by byte. - for si < sn && src[si] == src[si-offset] { - si++ - } - - mLen = si - mLen - if mLen < 0xF { - dst[di] = byte(mLen) - } else { - dst[di] = 0xF - } - - // Encode literals length. - if lLen < 0xF { - dst[di] |= byte(lLen << 4) - } else { - dst[di] |= 0xF0 - di++ - l := lLen - 0xF - for ; l >= 0xFF; l -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(l) - } - di++ - - // Literals. - copy(dst[di:], src[anchor:anchor+lLen]) - di += lLen + 2 - anchor = si - - // Encode offset. - _ = dst[di] // Bound check elimination. - dst[di-2], dst[di-1] = byte(offset), byte(offset>>8) - - // Encode match length part 2. - if mLen >= 0xF { - for mLen -= 0xF; mLen >= 0xFF; mLen -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(mLen) - di++ - } - } - - if anchor == 0 { - // Incompressible. - return 0, nil - } - - // Last literals. - lLen := len(src) - anchor - if lLen < 0xF { - dst[di] = byte(lLen << 4) - } else { - dst[di] = 0xF0 - di++ - for lLen -= 0xF; lLen >= 0xFF; lLen -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(lLen) - } - di++ - - // Write the last literals. - if di >= anchor { - // Incompressible. - return 0, nil - } - di += copy(dst[di:], src[anchor:]) - return di, nil -} - -// CompressBlockHC compresses the source buffer src into the destination dst -// with max search depth (use 0 or negative value for no max). -// -// CompressBlockHC compression ratio is better than CompressBlock but it is also slower. -// -// The size of the compressed data is returned. If it is 0 and no error, then the data is not compressible. -// -// An error is returned if the destination buffer is too small. -func CompressBlockHC(src, dst []byte, depth int) (di int, err error) { - defer func() { - if recover() != nil { - err = ErrInvalidSourceShortBuffer - } - }() - - sn, dn := len(src)-mfLimit, len(dst) - if sn <= 0 || dn == 0 { - return 0, nil - } - var si int - - // hashTable: stores the last position found for a given hash - // chaingTable: stores previous positions for a given hash - var hashTable, chainTable [winSize]int - - if depth <= 0 { - depth = winSize - } - - anchor := si - for si < sn { - // Hash the next 4 bytes (sequence). - match := binary.LittleEndian.Uint32(src[si:]) - h := blockHash(match) - - // Follow the chain until out of window and give the longest match. - mLen := 0 - offset := 0 - for next, try := hashTable[h], depth; try > 0 && next > 0 && si-next < winSize; next = chainTable[next&winMask] { - // The first (mLen==0) or next byte (mLen>=minMatch) at current match length - // must match to improve on the match length. - if src[next+mLen] != src[si+mLen] { - continue - } - ml := 0 - // Compare the current position with a previous with the same hash. - for ml < sn-si && binary.LittleEndian.Uint64(src[next+ml:]) == binary.LittleEndian.Uint64(src[si+ml:]) { - ml += 8 - } - for ml < sn-si && src[next+ml] == src[si+ml] { - ml++ - } - if ml+1 < minMatch || ml <= mLen { - // Match too small ( winStart { - winStart = ws - } - for si, ml := winStart, si+mLen; si < ml; { - match >>= 8 - match |= uint32(src[si+3]) << 24 - h := blockHash(match) - chainTable[si&winMask] = hashTable[h] - hashTable[h] = si - si++ - } - - lLen := si - anchor - si += mLen - mLen -= minMatch // Match length does not include minMatch. - - if mLen < 0xF { - dst[di] = byte(mLen) - } else { - dst[di] = 0xF - } - - // Encode literals length. - if lLen < 0xF { - dst[di] |= byte(lLen << 4) - } else { - dst[di] |= 0xF0 - di++ - l := lLen - 0xF - for ; l >= 0xFF; l -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(l) - } - di++ - - // Literals. - copy(dst[di:], src[anchor:anchor+lLen]) - di += lLen - anchor = si - - // Encode offset. - di += 2 - dst[di-2], dst[di-1] = byte(offset), byte(offset>>8) - - // Encode match length part 2. - if mLen >= 0xF { - for mLen -= 0xF; mLen >= 0xFF; mLen -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(mLen) - di++ - } - } - - if anchor == 0 { - // Incompressible. - return 0, nil - } - - // Last literals. - lLen := len(src) - anchor - if lLen < 0xF { - dst[di] = byte(lLen << 4) - } else { - dst[di] = 0xF0 - di++ - lLen -= 0xF - for ; lLen >= 0xFF; lLen -= 0xFF { - dst[di] = 0xFF - di++ - } - dst[di] = byte(lLen) - } - di++ - - // Write the last literals. - if di >= anchor { - // Incompressible. - return 0, nil - } - di += copy(dst[di:], src[anchor:]) - return di, nil -} diff --git a/vendor/github.com/pierrec/lz4/debug.go b/vendor/github.com/pierrec/lz4/debug.go deleted file mode 100644 index bc5e78d40f0..00000000000 --- a/vendor/github.com/pierrec/lz4/debug.go +++ /dev/null @@ -1,23 +0,0 @@ -// +build lz4debug - -package lz4 - -import ( - "fmt" - "os" - "path/filepath" - "runtime" -) - -const debugFlag = true - -func debug(args ...interface{}) { - _, file, line, _ := runtime.Caller(1) - file = filepath.Base(file) - - f := fmt.Sprintf("LZ4: %s:%d %s", file, line, args[0]) - if f[len(f)-1] != '\n' { - f += "\n" - } - fmt.Fprintf(os.Stderr, f, args[1:]...) -} diff --git a/vendor/github.com/pierrec/lz4/debug_stub.go b/vendor/github.com/pierrec/lz4/debug_stub.go deleted file mode 100644 index 44211ad9645..00000000000 --- a/vendor/github.com/pierrec/lz4/debug_stub.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !lz4debug - -package lz4 - -const debugFlag = false - -func debug(args ...interface{}) {} diff --git a/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go b/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go deleted file mode 100644 index 850a6fdf614..00000000000 --- a/vendor/github.com/pierrec/lz4/internal/xxh32/xxh32zero.go +++ /dev/null @@ -1,222 +0,0 @@ -// Package xxh32 implements the very fast XXH hashing algorithm (32 bits version). -// (https://github.com/Cyan4973/XXH/) -package xxh32 - -import ( - "encoding/binary" -) - -const ( - prime32_1 uint32 = 2654435761 - prime32_2 uint32 = 2246822519 - prime32_3 uint32 = 3266489917 - prime32_4 uint32 = 668265263 - prime32_5 uint32 = 374761393 - - prime32_1plus2 uint32 = 606290984 - prime32_minus1 uint32 = 1640531535 -) - -// XXHZero represents an xxhash32 object with seed 0. -type XXHZero struct { - v1 uint32 - v2 uint32 - v3 uint32 - v4 uint32 - totalLen uint64 - buf [16]byte - bufused int -} - -// Sum appends the current hash to b and returns the resulting slice. -// It does not change the underlying hash state. -func (xxh XXHZero) Sum(b []byte) []byte { - h32 := xxh.Sum32() - return append(b, byte(h32), byte(h32>>8), byte(h32>>16), byte(h32>>24)) -} - -// Reset resets the Hash to its initial state. -func (xxh *XXHZero) Reset() { - xxh.v1 = prime32_1plus2 - xxh.v2 = prime32_2 - xxh.v3 = 0 - xxh.v4 = prime32_minus1 - xxh.totalLen = 0 - xxh.bufused = 0 -} - -// Size returns the number of bytes returned by Sum(). -func (xxh *XXHZero) Size() int { - return 4 -} - -// BlockSize gives the minimum number of bytes accepted by Write(). -func (xxh *XXHZero) BlockSize() int { - return 1 -} - -// Write adds input bytes to the Hash. -// It never returns an error. -func (xxh *XXHZero) Write(input []byte) (int, error) { - if xxh.totalLen == 0 { - xxh.Reset() - } - n := len(input) - m := xxh.bufused - - xxh.totalLen += uint64(n) - - r := len(xxh.buf) - m - if n < r { - copy(xxh.buf[m:], input) - xxh.bufused += len(input) - return n, nil - } - - p := 0 - // Causes compiler to work directly from registers instead of stack: - v1, v2, v3, v4 := xxh.v1, xxh.v2, xxh.v3, xxh.v4 - if m > 0 { - // some data left from previous update - copy(xxh.buf[xxh.bufused:], input[:r]) - xxh.bufused += len(input) - r - - // fast rotl(13) - buf := xxh.buf[:16] // BCE hint. - v1 = rol13(v1+binary.LittleEndian.Uint32(buf[:])*prime32_2) * prime32_1 - v2 = rol13(v2+binary.LittleEndian.Uint32(buf[4:])*prime32_2) * prime32_1 - v3 = rol13(v3+binary.LittleEndian.Uint32(buf[8:])*prime32_2) * prime32_1 - v4 = rol13(v4+binary.LittleEndian.Uint32(buf[12:])*prime32_2) * prime32_1 - p = r - xxh.bufused = 0 - } - - for n := n - 16; p <= n; p += 16 { - sub := input[p:][:16] //BCE hint for compiler - v1 = rol13(v1+binary.LittleEndian.Uint32(sub[:])*prime32_2) * prime32_1 - v2 = rol13(v2+binary.LittleEndian.Uint32(sub[4:])*prime32_2) * prime32_1 - v3 = rol13(v3+binary.LittleEndian.Uint32(sub[8:])*prime32_2) * prime32_1 - v4 = rol13(v4+binary.LittleEndian.Uint32(sub[12:])*prime32_2) * prime32_1 - } - xxh.v1, xxh.v2, xxh.v3, xxh.v4 = v1, v2, v3, v4 - - copy(xxh.buf[xxh.bufused:], input[p:]) - xxh.bufused += len(input) - p - - return n, nil -} - -// Sum32 returns the 32 bits Hash value. -func (xxh *XXHZero) Sum32() uint32 { - h32 := uint32(xxh.totalLen) - if h32 >= 16 { - h32 += rol1(xxh.v1) + rol7(xxh.v2) + rol12(xxh.v3) + rol18(xxh.v4) - } else { - h32 += prime32_5 - } - - p := 0 - n := xxh.bufused - buf := xxh.buf - for n := n - 4; p <= n; p += 4 { - h32 += binary.LittleEndian.Uint32(buf[p:p+4]) * prime32_3 - h32 = rol17(h32) * prime32_4 - } - for ; p < n; p++ { - h32 += uint32(buf[p]) * prime32_5 - h32 = rol11(h32) * prime32_1 - } - - h32 ^= h32 >> 15 - h32 *= prime32_2 - h32 ^= h32 >> 13 - h32 *= prime32_3 - h32 ^= h32 >> 16 - - return h32 -} - -// ChecksumZero returns the 32bits Hash value. -func ChecksumZero(input []byte) uint32 { - n := len(input) - h32 := uint32(n) - - if n < 16 { - h32 += prime32_5 - } else { - v1 := prime32_1plus2 - v2 := prime32_2 - v3 := uint32(0) - v4 := prime32_minus1 - p := 0 - for n := n - 16; p <= n; p += 16 { - sub := input[p:][:16] //BCE hint for compiler - v1 = rol13(v1+binary.LittleEndian.Uint32(sub[:])*prime32_2) * prime32_1 - v2 = rol13(v2+binary.LittleEndian.Uint32(sub[4:])*prime32_2) * prime32_1 - v3 = rol13(v3+binary.LittleEndian.Uint32(sub[8:])*prime32_2) * prime32_1 - v4 = rol13(v4+binary.LittleEndian.Uint32(sub[12:])*prime32_2) * prime32_1 - } - input = input[p:] - n -= p - h32 += rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) - } - - p := 0 - for n := n - 4; p <= n; p += 4 { - h32 += binary.LittleEndian.Uint32(input[p:p+4]) * prime32_3 - h32 = rol17(h32) * prime32_4 - } - for p < n { - h32 += uint32(input[p]) * prime32_5 - h32 = rol11(h32) * prime32_1 - p++ - } - - h32 ^= h32 >> 15 - h32 *= prime32_2 - h32 ^= h32 >> 13 - h32 *= prime32_3 - h32 ^= h32 >> 16 - - return h32 -} - -// Uint32Zero hashes x with seed 0. -func Uint32Zero(x uint32) uint32 { - h := prime32_5 + 4 + x*prime32_3 - h = rol17(h) * prime32_4 - h ^= h >> 15 - h *= prime32_2 - h ^= h >> 13 - h *= prime32_3 - h ^= h >> 16 - return h -} - -func rol1(u uint32) uint32 { - return u<<1 | u>>31 -} - -func rol7(u uint32) uint32 { - return u<<7 | u>>25 -} - -func rol11(u uint32) uint32 { - return u<<11 | u>>21 -} - -func rol12(u uint32) uint32 { - return u<<12 | u>>20 -} - -func rol13(u uint32) uint32 { - return u<<13 | u>>19 -} - -func rol17(u uint32) uint32 { - return u<<17 | u>>15 -} - -func rol18(u uint32) uint32 { - return u<<18 | u>>14 -} diff --git a/vendor/github.com/pierrec/lz4/lz4.go b/vendor/github.com/pierrec/lz4/lz4.go deleted file mode 100644 index 35802756c48..00000000000 --- a/vendor/github.com/pierrec/lz4/lz4.go +++ /dev/null @@ -1,68 +0,0 @@ -// Package lz4 implements reading and writing lz4 compressed data (a frame), -// as specified in http://fastcompression.blogspot.fr/2013/04/lz4-streaming-format-final.html. -// -// Although the block level compression and decompression functions are exposed and are fully compatible -// with the lz4 block format definition, they are low level and should not be used directly. -// For a complete description of an lz4 compressed block, see: -// http://fastcompression.blogspot.fr/2011/05/lz4-explained.html -// -// See https://github.com/Cyan4973/lz4 for the reference C implementation. -// -package lz4 - -const ( - // Extension is the LZ4 frame file name extension - Extension = ".lz4" - // Version is the LZ4 frame format version - Version = 1 - - frameMagic uint32 = 0x184D2204 - frameSkipMagic uint32 = 0x184D2A50 - - // The following constants are used to setup the compression algorithm. - minMatch = 4 // the minimum size of the match sequence size (4 bytes) - winSizeLog = 16 // LZ4 64Kb window size limit - winSize = 1 << winSizeLog - winMask = winSize - 1 // 64Kb window of previous data for dependent blocks - compressedBlockFlag = 1 << 31 - compressedBlockMask = compressedBlockFlag - 1 - - // hashLog determines the size of the hash table used to quickly find a previous match position. - // Its value influences the compression speed and memory usage, the lower the faster, - // but at the expense of the compression ratio. - // 16 seems to be the best compromise. - hashLog = 16 - hashTableSize = 1 << hashLog - hashShift = uint((minMatch * 8) - hashLog) - - mfLimit = 8 + minMatch // The last match cannot start within the last 12 bytes. - skipStrength = 6 // variable step for fast scan -) - -// map the block max size id with its value in bytes: 64Kb, 256Kb, 1Mb and 4Mb. -var ( - bsMapID = map[byte]int{4: 64 << 10, 5: 256 << 10, 6: 1 << 20, 7: 4 << 20} - bsMapValue = make(map[int]byte, len(bsMapID)) -) - -// Reversed. -func init() { - for i, v := range bsMapID { - bsMapValue[v] = i - } -} - -// Header describes the various flags that can be set on a Writer or obtained from a Reader. -// The default values match those of the LZ4 frame format definition -// (http://fastcompression.blogspot.com/2013/04/lz4-streaming-format-final.html). -// -// NB. in a Reader, in case of concatenated frames, the Header values may change between Read() calls. -// It is the caller responsibility to check them if necessary. -type Header struct { - BlockChecksum bool // Compressed blocks checksum flag. - NoChecksum bool // Frame checksum flag. - BlockMaxSize int // Size of the uncompressed data block (one of [64KB, 256KB, 1MB, 4MB]). Default=4MB. - Size uint64 // Frame total size. It is _not_ computed by the Writer. - CompressionLevel int // Compression level (higher is better, use 0 for fastest compression). - done bool // Header processed flag (Read or Write and checked). -} diff --git a/vendor/github.com/pierrec/lz4/lz4_go1.10.go b/vendor/github.com/pierrec/lz4/lz4_go1.10.go deleted file mode 100644 index 9a0fb00709d..00000000000 --- a/vendor/github.com/pierrec/lz4/lz4_go1.10.go +++ /dev/null @@ -1,29 +0,0 @@ -//+build go1.10 - -package lz4 - -import ( - "fmt" - "strings" -) - -func (h Header) String() string { - var s strings.Builder - - s.WriteString(fmt.Sprintf("%T{", h)) - if h.BlockChecksum { - s.WriteString("BlockChecksum: true ") - } - if h.NoChecksum { - s.WriteString("NoChecksum: true ") - } - if bs := h.BlockMaxSize; bs != 0 && bs != 4<<20 { - s.WriteString(fmt.Sprintf("BlockMaxSize: %d ", bs)) - } - if l := h.CompressionLevel; l != 0 { - s.WriteString(fmt.Sprintf("CompressionLevel: %d ", l)) - } - s.WriteByte('}') - - return s.String() -} diff --git a/vendor/github.com/pierrec/lz4/lz4_notgo1.10.go b/vendor/github.com/pierrec/lz4/lz4_notgo1.10.go deleted file mode 100644 index 12c761a2e7f..00000000000 --- a/vendor/github.com/pierrec/lz4/lz4_notgo1.10.go +++ /dev/null @@ -1,29 +0,0 @@ -//+build !go1.10 - -package lz4 - -import ( - "bytes" - "fmt" -) - -func (h Header) String() string { - var s bytes.Buffer - - s.WriteString(fmt.Sprintf("%T{", h)) - if h.BlockChecksum { - s.WriteString("BlockChecksum: true ") - } - if h.NoChecksum { - s.WriteString("NoChecksum: true ") - } - if bs := h.BlockMaxSize; bs != 0 && bs != 4<<20 { - s.WriteString(fmt.Sprintf("BlockMaxSize: %d ", bs)) - } - if l := h.CompressionLevel; l != 0 { - s.WriteString(fmt.Sprintf("CompressionLevel: %d ", l)) - } - s.WriteByte('}') - - return s.String() -} diff --git a/vendor/github.com/pierrec/lz4/reader.go b/vendor/github.com/pierrec/lz4/reader.go deleted file mode 100644 index f08db47df7b..00000000000 --- a/vendor/github.com/pierrec/lz4/reader.go +++ /dev/null @@ -1,295 +0,0 @@ -package lz4 - -import ( - "encoding/binary" - "fmt" - "io" - "io/ioutil" - - "github.com/pierrec/lz4/internal/xxh32" -) - -// Reader implements the LZ4 frame decoder. -// The Header is set after the first call to Read(). -// The Header may change between Read() calls in case of concatenated frames. -type Reader struct { - Header - - buf [8]byte // Scrap buffer. - pos int64 // Current position in src. - src io.Reader // Source. - zdata []byte // Compressed data. - data []byte // Uncompressed data. - idx int // Index of unread bytes into data. - checksum xxh32.XXHZero // Frame hash. -} - -// NewReader returns a new LZ4 frame decoder. -// No access to the underlying io.Reader is performed. -func NewReader(src io.Reader) *Reader { - r := &Reader{src: src} - return r -} - -// readHeader checks the frame magic number and parses the frame descriptoz. -// Skippable frames are supported even as a first frame although the LZ4 -// specifications recommends skippable frames not to be used as first frames. -func (z *Reader) readHeader(first bool) error { - defer z.checksum.Reset() - - buf := z.buf[:] - for { - magic, err := z.readUint32() - if err != nil { - z.pos += 4 - if !first && err == io.ErrUnexpectedEOF { - return io.EOF - } - return err - } - if magic == frameMagic { - break - } - if magic>>8 != frameSkipMagic>>8 { - return ErrInvalid - } - skipSize, err := z.readUint32() - if err != nil { - return err - } - z.pos += 4 - m, err := io.CopyN(ioutil.Discard, z.src, int64(skipSize)) - if err != nil { - return err - } - z.pos += m - } - - // Header. - if _, err := io.ReadFull(z.src, buf[:2]); err != nil { - return err - } - z.pos += 8 - - b := buf[0] - if v := b >> 6; v != Version { - return fmt.Errorf("lz4: invalid version: got %d; expected %d", v, Version) - } - if b>>5&1 == 0 { - return fmt.Errorf("lz4: block dependency not supported") - } - z.BlockChecksum = b>>4&1 > 0 - frameSize := b>>3&1 > 0 - z.NoChecksum = b>>2&1 == 0 - - bmsID := buf[1] >> 4 & 0x7 - bSize, ok := bsMapID[bmsID] - if !ok { - return fmt.Errorf("lz4: invalid block max size ID: %d", bmsID) - } - z.BlockMaxSize = bSize - - // Allocate the compressed/uncompressed buffers. - // The compressed buffer cannot exceed the uncompressed one. - if n := 2 * bSize; cap(z.zdata) < n { - z.zdata = make([]byte, n, n) - } - if debugFlag { - debug("header block max size id=%d size=%d", bmsID, bSize) - } - z.zdata = z.zdata[:bSize] - z.data = z.zdata[:cap(z.zdata)][bSize:] - z.idx = len(z.data) - - z.checksum.Write(buf[0:2]) - - if frameSize { - buf := buf[:8] - if _, err := io.ReadFull(z.src, buf); err != nil { - return err - } - z.Size = binary.LittleEndian.Uint64(buf) - z.pos += 8 - z.checksum.Write(buf) - } - - // Header checksum. - if _, err := io.ReadFull(z.src, buf[:1]); err != nil { - return err - } - z.pos++ - if h := byte(z.checksum.Sum32() >> 8 & 0xFF); h != buf[0] { - return fmt.Errorf("lz4: invalid header checksum: got %x; expected %x", buf[0], h) - } - - z.Header.done = true - if debugFlag { - debug("header read: %v", z.Header) - } - - return nil -} - -// Read decompresses data from the underlying source into the supplied buffer. -// -// Since there can be multiple streams concatenated, Header values may -// change between calls to Read(). If that is the case, no data is actually read from -// the underlying io.Reader, to allow for potential input buffer resizing. -func (z *Reader) Read(buf []byte) (int, error) { - if debugFlag { - debug("Read buf len=%d", len(buf)) - } - if !z.Header.done { - if err := z.readHeader(true); err != nil { - return 0, err - } - if debugFlag { - debug("header read OK compressed buffer %d / %d uncompressed buffer %d : %d index=%d", - len(z.zdata), cap(z.zdata), len(z.data), cap(z.data), z.idx) - } - } - - if len(buf) == 0 { - return 0, nil - } - - if z.idx == len(z.data) { - // No data ready for reading, process the next block. - if debugFlag { - debug("reading block from writer") - } - // Block length: 0 = end of frame, highest bit set: uncompressed. - bLen, err := z.readUint32() - if err != nil { - return 0, err - } - z.pos += 4 - - if bLen == 0 { - // End of frame reached. - if !z.NoChecksum { - // Validate the frame checksum. - checksum, err := z.readUint32() - if err != nil { - return 0, err - } - if debugFlag { - debug("frame checksum got=%x / want=%x", z.checksum.Sum32(), checksum) - } - z.pos += 4 - if h := z.checksum.Sum32(); checksum != h { - return 0, fmt.Errorf("lz4: invalid frame checksum: got %x; expected %x", h, checksum) - } - } - - // Get ready for the next concatenated frame and keep the position. - pos := z.pos - z.Reset(z.src) - z.pos = pos - - // Since multiple frames can be concatenated, check for more. - return 0, z.readHeader(false) - } - - if debugFlag { - debug("raw block size %d", bLen) - } - if bLen&compressedBlockFlag > 0 { - // Uncompressed block. - bLen &= compressedBlockMask - if debugFlag { - debug("uncompressed block size %d", bLen) - } - if int(bLen) > cap(z.data) { - return 0, fmt.Errorf("lz4: invalid block size: %d", bLen) - } - z.data = z.data[:bLen] - if _, err := io.ReadFull(z.src, z.data); err != nil { - return 0, err - } - z.pos += int64(bLen) - - if z.BlockChecksum { - checksum, err := z.readUint32() - if err != nil { - return 0, err - } - z.pos += 4 - - if h := xxh32.ChecksumZero(z.data); h != checksum { - return 0, fmt.Errorf("lz4: invalid block checksum: got %x; expected %x", h, checksum) - } - } - - } else { - // Compressed block. - if debugFlag { - debug("compressed block size %d", bLen) - } - if int(bLen) > cap(z.data) { - return 0, fmt.Errorf("lz4: invalid block size: %d", bLen) - } - zdata := z.zdata[:bLen] - if _, err := io.ReadFull(z.src, zdata); err != nil { - return 0, err - } - z.pos += int64(bLen) - - if z.BlockChecksum { - checksum, err := z.readUint32() - if err != nil { - return 0, err - } - z.pos += 4 - - if h := xxh32.ChecksumZero(zdata); h != checksum { - return 0, fmt.Errorf("lz4: invalid block checksum: got %x; expected %x", h, checksum) - } - } - - n, err := UncompressBlock(zdata, z.data) - if err != nil { - return 0, err - } - z.data = z.data[:n] - } - - if !z.NoChecksum { - z.checksum.Write(z.data) - if debugFlag { - debug("current frame checksum %x", z.checksum.Sum32()) - } - } - z.idx = 0 - } - - n := copy(buf, z.data[z.idx:]) - z.idx += n - if debugFlag { - debug("copied %d bytes to input", n) - } - - return n, nil -} - -// Reset discards the Reader's state and makes it equivalent to the -// result of its original state from NewReader, but reading from r instead. -// This permits reusing a Reader rather than allocating a new one. -func (z *Reader) Reset(r io.Reader) { - z.Header = Header{} - z.pos = 0 - z.src = r - z.zdata = z.zdata[:0] - z.data = z.data[:0] - z.idx = 0 - z.checksum.Reset() -} - -// readUint32 reads an uint32 into the supplied buffer. -// The idea is to make use of the already allocated buffers avoiding additional allocations. -func (z *Reader) readUint32() (uint32, error) { - buf := z.buf[:4] - _, err := io.ReadFull(z.src, buf) - x := binary.LittleEndian.Uint32(buf) - return x, err -} diff --git a/vendor/github.com/pierrec/lz4/writer.go b/vendor/github.com/pierrec/lz4/writer.go deleted file mode 100644 index 0120438025d..00000000000 --- a/vendor/github.com/pierrec/lz4/writer.go +++ /dev/null @@ -1,267 +0,0 @@ -package lz4 - -import ( - "encoding/binary" - "fmt" - "io" - - "github.com/pierrec/lz4/internal/xxh32" -) - -// Writer implements the LZ4 frame encoder. -type Writer struct { - Header - - buf [19]byte // magic number(4) + header(flags(2)+[Size(8)+DictID(4)]+checksum(1)) does not exceed 19 bytes - dst io.Writer // Destination. - checksum xxh32.XXHZero // Frame checksum. - zdata []byte // Compressed data. - data []byte // Data to be compressed. - idx int // Index into data. - hashtable [winSize]int // Hash table used in CompressBlock(). -} - -// NewWriter returns a new LZ4 frame encoder. -// No access to the underlying io.Writer is performed. -// The supplied Header is checked at the first Write. -// It is ok to change it before the first Write but then not until a Reset() is performed. -func NewWriter(dst io.Writer) *Writer { - return &Writer{dst: dst} -} - -// writeHeader builds and writes the header (magic+header) to the underlying io.Writer. -func (z *Writer) writeHeader() error { - // Default to 4Mb if BlockMaxSize is not set. - if z.Header.BlockMaxSize == 0 { - z.Header.BlockMaxSize = bsMapID[7] - } - // The only option that needs to be validated. - bSize := z.Header.BlockMaxSize - bSizeID, ok := bsMapValue[bSize] - if !ok { - return fmt.Errorf("lz4: invalid block max size: %d", bSize) - } - // Allocate the compressed/uncompressed buffers. - // The compressed buffer cannot exceed the uncompressed one. - if n := 2 * bSize; cap(z.zdata) < n { - z.zdata = make([]byte, n, n) - } - z.zdata = z.zdata[:bSize] - z.data = z.zdata[:cap(z.zdata)][bSize:] - z.idx = 0 - - // Size is optional. - buf := z.buf[:] - - // Set the fixed size data: magic number, block max size and flags. - binary.LittleEndian.PutUint32(buf[0:], frameMagic) - flg := byte(Version << 6) - flg |= 1 << 5 // No block dependency. - if z.Header.BlockChecksum { - flg |= 1 << 4 - } - if z.Header.Size > 0 { - flg |= 1 << 3 - } - if !z.Header.NoChecksum { - flg |= 1 << 2 - } - buf[4] = flg - buf[5] = bSizeID << 4 - - // Current buffer size: magic(4) + flags(1) + block max size (1). - n := 6 - // Optional items. - if z.Header.Size > 0 { - binary.LittleEndian.PutUint64(buf[n:], z.Header.Size) - n += 8 - } - - // The header checksum includes the flags, block max size and optional Size. - buf[n] = byte(xxh32.ChecksumZero(buf[4:n]) >> 8 & 0xFF) - z.checksum.Reset() - - // Header ready, write it out. - if _, err := z.dst.Write(buf[0 : n+1]); err != nil { - return err - } - z.Header.done = true - if debugFlag { - debug("wrote header %v", z.Header) - } - - return nil -} - -// Write compresses data from the supplied buffer into the underlying io.Writer. -// Write does not return until the data has been written. -func (z *Writer) Write(buf []byte) (int, error) { - if !z.Header.done { - if err := z.writeHeader(); err != nil { - return 0, err - } - } - if debugFlag { - debug("input buffer len=%d index=%d", len(buf), z.idx) - } - - zn := len(z.data) - var n int - for len(buf) > 0 { - if z.idx == 0 && len(buf) >= zn { - // Avoid a copy as there is enough data for a block. - if err := z.compressBlock(buf[:zn]); err != nil { - return n, err - } - n += zn - buf = buf[zn:] - continue - } - // Accumulate the data to be compressed. - m := copy(z.data[z.idx:], buf) - n += m - z.idx += m - buf = buf[m:] - if debugFlag { - debug("%d bytes copied to buf, current index %d", n, z.idx) - } - - if z.idx < len(z.data) { - // Buffer not filled. - if debugFlag { - debug("need more data for compression") - } - return n, nil - } - - // Buffer full. - if err := z.compressBlock(z.data); err != nil { - return n, err - } - z.idx = 0 - } - - return n, nil -} - -// compressBlock compresses a block. -func (z *Writer) compressBlock(data []byte) error { - if !z.NoChecksum { - z.checksum.Write(data) - } - - // The compressed block size cannot exceed the input's. - var zn int - var err error - - if level := z.Header.CompressionLevel; level != 0 { - zn, err = CompressBlockHC(data, z.zdata, level) - } else { - zn, err = CompressBlock(data, z.zdata, z.hashtable[:]) - } - - var zdata []byte - var bLen uint32 - if debugFlag { - debug("block compression %d => %d", len(data), zn) - } - if err == nil && zn > 0 && zn < len(data) { - // Compressible and compressed size smaller than uncompressed: ok! - bLen = uint32(zn) - zdata = z.zdata[:zn] - } else { - // Uncompressed block. - bLen = uint32(len(data)) | compressedBlockFlag - zdata = data - } - if debugFlag { - debug("block compression to be written len=%d data len=%d", bLen, len(zdata)) - } - - // Write the block. - if err := z.writeUint32(bLen); err != nil { - return err - } - if _, err := z.dst.Write(zdata); err != nil { - return err - } - - if z.BlockChecksum { - checksum := xxh32.ChecksumZero(zdata) - if debugFlag { - debug("block checksum %x", checksum) - } - if err := z.writeUint32(checksum); err != nil { - return err - } - } - if debugFlag { - debug("current frame checksum %x", z.checksum.Sum32()) - } - - return nil -} - -// Flush flushes any pending compressed data to the underlying writer. -// Flush does not return until the data has been written. -// If the underlying writer returns an error, Flush returns that error. -func (z *Writer) Flush() error { - if debugFlag { - debug("flush with index %d", z.idx) - } - if z.idx == 0 { - return nil - } - - return z.compressBlock(z.data[:z.idx]) -} - -// Close closes the Writer, flushing any unwritten data to the underlying io.Writer, but does not close the underlying io.Writer. -func (z *Writer) Close() error { - if !z.Header.done { - if err := z.writeHeader(); err != nil { - return err - } - } - - if err := z.Flush(); err != nil { - return err - } - - if debugFlag { - debug("writing last empty block") - } - if err := z.writeUint32(0); err != nil { - return err - } - if !z.NoChecksum { - checksum := z.checksum.Sum32() - if debugFlag { - debug("stream checksum %x", checksum) - } - if err := z.writeUint32(checksum); err != nil { - return err - } - } - return nil -} - -// Reset clears the state of the Writer z such that it is equivalent to its -// initial state from NewWriter, but instead writing to w. -// No access to the underlying io.Writer is performed. -func (z *Writer) Reset(w io.Writer) { - z.Header = Header{} - z.dst = w - z.checksum.Reset() - z.zdata = z.zdata[:0] - z.data = z.data[:0] - z.idx = 0 -} - -// writeUint32 writes a uint32 to the underlying writer. -func (z *Writer) writeUint32(x uint32) error { - buf := z.buf[:4] - binary.LittleEndian.PutUint32(buf, x) - _, err := z.dst.Write(buf) - return err -} diff --git a/vendor/github.com/quasilyte/go-ruleguard/LICENSE b/vendor/github.com/quasilyte/go-ruleguard/LICENSE new file mode 100644 index 00000000000..f0381fb4981 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2019, Iskander (Alex) Sharipov / quasilyte +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. 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. + +3. Neither the name of the copyright holder 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/quasilyte/go-ruleguard/dslgen/dsl_sources.go b/vendor/github.com/quasilyte/go-ruleguard/dslgen/dsl_sources.go new file mode 100644 index 00000000000..54c500f4e3e --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/dslgen/dsl_sources.go @@ -0,0 +1,3 @@ +package dslgen + +var Fluent = []byte("package fluent\n\n// Matcher is a main API group-level entry point.\n// It's used to define and configure the group rules.\n// It also represents a map of all rule-local variables.\ntype Matcher map[string]Var\n\n// Import loads given package path into a rule group imports table.\n//\n// That table is used during the rules compilation.\n//\n// The table has the following effect on the rules:\n//\t* For type expressions, it's used to resolve the\n//\t full package paths of qualified types, like `foo.Bar`.\n//\t If Import(`a/b/foo`) is called, `foo.Bar` will match\n//\t `a/b/foo.Bar` type during the pattern execution.\nfunc (m Matcher) Import(pkgPath string) {}\n\n// Match specifies a set of patterns that match a rule being defined.\n// Pattern matching succeeds if at least 1 pattern matches.\n//\n// If none of the given patterns matched, rule execution stops.\nfunc (m Matcher) Match(pattern string, alternatives ...string) Matcher {\n\treturn m\n}\n\n// Where applies additional constraint to a match.\n// If a given cond is not satisfied, a match is rejected and\n// rule execution stops.\nfunc (m Matcher) Where(cond bool) Matcher {\n\treturn m\n}\n\n// Report prints a message if associated rule match is successful.\n//\n// A message is a string that can contain interpolated expressions.\n// For every matched variable it's possible to interpolate\n// their printed representation into the message text with $.\n// An entire match can be addressed with $$.\nfunc (m Matcher) Report(message string) Matcher {\n\treturn m\n}\n\n// Suggest assigns a quickfix suggestion for the matched code.\nfunc (m Matcher) Suggest(suggestion string) Matcher {\n\treturn m\n}\n\n// At binds the reported node to a named submatch.\n// If no explicit location is given, the outermost node ($$) is used.\nfunc (m Matcher) At(v Var) Matcher {\n\treturn m\n}\n\n// Var is a pattern variable that describes a named submatch.\ntype Var struct {\n\t// Pure reports whether expr matched by var is side-effect-free.\n\tPure bool\n\n\t// Const reports whether expr matched by var is a constant value.\n\tConst bool\n\n\t// Addressable reports whether the corresponding expression is addressable.\n\t// See https://golang.org/ref/spec#Address_operators.\n\tAddressable bool\n\n\t// Type is a type of a matched expr.\n\tType ExprType\n}\n\n// ExprType describes a type of a matcher expr.\ntype ExprType struct {\n\t// Size represents expression type size in bytes.\n\tSize int\n}\n\n// AssignableTo reports whether a type is assign-compatible with a given type.\n// See https://golang.org/pkg/go/types/#AssignableTo.\nfunc (ExprType) AssignableTo(typ string) bool { return boolResult }\n\n// ConvertibleTo reports whether a type is conversible to a given type.\n// See https://golang.org/pkg/go/types/#ConvertibleTo.\nfunc (ExprType) ConvertibleTo(typ string) bool { return boolResult }\n\n// Implements reports whether a type implements a given interface.\n// See https://golang.org/pkg/go/types/#Implements.\nfunc (ExprType) Implements(typ string) bool { return boolResult }\n\n// Is reports whether a type is identical to a given type.\nfunc (ExprType) Is(typ string) bool { return boolResult }\n\n\n\nvar boolResult bool\n\n") diff --git a/vendor/github.com/quasilyte/go-ruleguard/dslgen/dslgen.go b/vendor/github.com/quasilyte/go-ruleguard/dslgen/dslgen.go new file mode 100644 index 00000000000..a2269b2ed1c --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/dslgen/dslgen.go @@ -0,0 +1,53 @@ +// +build generate + +package main + +import ( + "bytes" + "fmt" + "io/ioutil" + "os" + "path/filepath" +) + +func main() { + // See #23. + + data, err := dirToBytes("../dsl/fluent") + if err != nil { + panic(err) + } + + f, err := os.Create("./dsl_sources.go") + if err != nil { + panic(err) + } + defer f.Close() + + fmt.Fprintf(f, `package dslgen + +var Fluent = []byte(%q) +`, string(data)) +} + +func dirToBytes(dir string) ([]byte, error) { + files, err := ioutil.ReadDir(dir) + if err != nil { + return nil, err + } + + var buf bytes.Buffer + for i, f := range files { + data, err := ioutil.ReadFile(filepath.Join(dir, f.Name())) + if err != nil { + return nil, err + } + if i != 0 { + newline := bytes.IndexByte(data, '\n') + data = data[newline:] + } + buf.Write(data) + buf.WriteByte('\n') + } + return buf.Bytes(), nil +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/.gitattributes b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/.gitattributes new file mode 100644 index 00000000000..6f952299270 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/.gitattributes @@ -0,0 +1,2 @@ +# To prevent CRLF breakages on Windows for fragile files, like testdata. +* -text diff --git a/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/LICENSE b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/LICENSE new file mode 100644 index 00000000000..a06c5ebfc88 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2017, Daniel Martí. 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 the copyright holder 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/README.md b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/README.md new file mode 100644 index 00000000000..12cb0fdc47b --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/README.md @@ -0,0 +1,55 @@ +# gogrep + + go get mvdan.cc/gogrep + +Search for Go code using syntax trees. Work in progress. + + gogrep -x 'if $x != nil { return $x, $*_ }' + +### Instructions + + usage: gogrep commands [packages] + +A command is of the form "-A pattern", where -A is one of: + + -x find all nodes matching a pattern + -g discard nodes not matching a pattern + -v discard nodes matching a pattern + -a filter nodes by certain attributes + -s substitute with a given syntax tree + -w write source back to disk or stdout + +A pattern is a piece of Go code which may include wildcards. It can be: + + a statement (many if split by semicolonss) + an expression (many if split by commas) + a type expression + a top-level declaration (var, func, const) + an entire file + +Wildcards consist of `$` and a name. All wildcards with the same name +within an expression must match the same node, excluding "_". Example: + + $x.$_ = $x // assignment of self to a field in self + +If `*` is before the name, it will match any number of nodes. Example: + + fmt.Fprintf(os.Stdout, $*_) // all Fprintfs on stdout + +`*` can also be used to match optional nodes, like: + + for $*_ { $*_ } // will match all for loops + if $*_; $b { $*_ } // will match all ifs with condition $b + +Regexes can also be used to match certain identifier names only. The +`.*` pattern can be used to match all identifiers. Example: + + fmt.$(_ /Fprint.*/)(os.Stdout, $*_) // all Fprint* on stdout + +The nodes resulting from applying the commands will be printed line by +line to standard output. + +Here are two simple examples of the -a operand: + + gogrep -x '$x + $y' // will match both numerical and string "+" operations + gogrep -x '$x + $y' -a 'type(string)' // matches only string concatenations diff --git a/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/kludge.go b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/kludge.go new file mode 100644 index 00000000000..f366af84f51 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/kludge.go @@ -0,0 +1,61 @@ +package gogrep + +import ( + "go/ast" + "go/token" + "go/types" +) + +// This is an ugly way to use gogrep as a library. +// It can go away when there will be another option. + +// Parse creates a gogrep pattern out of a given string expression. +func Parse(fset *token.FileSet, expr string) (*Pattern, error) { + m := matcher{ + fset: fset, + Info: &types.Info{}, + } + node, err := m.parseExpr(expr) + if err != nil { + return nil, err + } + return &Pattern{m: &m, Expr: node}, nil +} + +// Pattern is a compiled gogrep pattern. +type Pattern struct { + Expr ast.Node + m *matcher +} + +// MatchData describes a successful pattern match. +type MatchData struct { + Node ast.Node + Values map[string]ast.Node +} + +// MatchNode calls cb if n matches a pattern. +func (p *Pattern) MatchNode(n ast.Node, cb func(MatchData)) { + p.m.values = map[string]ast.Node{} + if p.m.node(p.Expr, n) { + cb(MatchData{ + Values: p.m.values, + Node: n, + }) + } +} + +// Match calls cb for any pattern match found in n. +func (p *Pattern) Match(n ast.Node, cb func(MatchData)) { + cmd := exprCmd{name: "x", value: p.Expr} + matches := p.m.cmdRange(cmd, []submatch{{ + values: map[string]ast.Node{}, + node: n, + }}) + for _, match := range matches { + cb(MatchData{ + Values: match.values, + Node: match.node, + }) + } +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/load.go b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/load.go new file mode 100644 index 00000000000..09ab3fd015b --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/load.go @@ -0,0 +1,72 @@ +// Copyright (c) 2017, Daniel Martí +// See LICENSE for licensing information + +package gogrep + +import ( + "fmt" + "sort" + "strings" + + "golang.org/x/tools/go/packages" +) + +func (m *matcher) load(wd string, args ...string) ([]*packages.Package, error) { + mode := packages.NeedName | packages.NeedImports | packages.NeedSyntax | + packages.NeedTypes | packages.NeedTypesInfo + if m.recursive { // need the syntax trees for the dependencies too + mode |= packages.NeedDeps + } + cfg := &packages.Config{ + Mode: mode, + Dir: wd, + Fset: m.fset, + Tests: m.tests, + } + pkgs, err := packages.Load(cfg, args...) + if err != nil { + return nil, err + } + jointErr := "" + packages.Visit(pkgs, nil, func(pkg *packages.Package) { + for _, err := range pkg.Errors { + jointErr += err.Error() + "\n" + } + }) + if jointErr != "" { + return nil, fmt.Errorf("%s", jointErr) + } + + // Make a sorted list of the packages, including transitive dependencies + // if recurse is true. + byPath := make(map[string]*packages.Package) + var addDeps func(*packages.Package) + addDeps = func(pkg *packages.Package) { + if strings.HasSuffix(pkg.PkgPath, ".test") { + // don't add recursive test deps + return + } + for _, imp := range pkg.Imports { + if _, ok := byPath[imp.PkgPath]; ok { + continue // seen; avoid recursive call + } + byPath[imp.PkgPath] = imp + addDeps(imp) + } + } + for _, pkg := range pkgs { + byPath[pkg.PkgPath] = pkg + if m.recursive { + // add all dependencies once + addDeps(pkg) + } + } + pkgs = pkgs[:0] + for _, pkg := range byPath { + pkgs = append(pkgs, pkg) + } + sort.Slice(pkgs, func(i, j int) bool { + return pkgs[i].PkgPath < pkgs[j].PkgPath + }) + return pkgs, nil +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/main.go b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/main.go new file mode 100644 index 00000000000..004cb32e9b7 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/main.go @@ -0,0 +1,332 @@ +// Copyright (c) 2017, Daniel Martí +// See LICENSE for licensing information + +package gogrep + +import ( + "bytes" + "flag" + "fmt" + "go/ast" + "go/build" + "go/printer" + "go/token" + "go/types" + "io" + "os" + "regexp" + "strconv" + "strings" +) + +var usage = func() { + fmt.Fprint(os.Stderr, `usage: gogrep commands [packages] + +gogrep performs a query on the given Go packages. + + -r search dependencies recursively too + -tests search test files too (and direct test deps, with -r) + +A command is one of the following: + + -x pattern find all nodes matching a pattern + -g pattern discard nodes not matching a pattern + -v pattern discard nodes matching a pattern + -a attribute discard nodes without an attribute + -s pattern substitute with a given syntax tree + -p number navigate up a number of node parents + -w write the entire source code back + +A pattern is a piece of Go code which may include dollar expressions. It can be +a number of statements, a number of expressions, a declaration, or an entire +file. + +A dollar expression consist of '$' and a name. Dollar expressions with the same +name within a query always match the same node, excluding "_". Example: + + -x '$x.$_ = $x' # assignment of self to a field in self + +If '*' is before the name, it will match any number of nodes. Example: + + -x 'fmt.Fprintf(os.Stdout, $*_)' # all Fprintfs on stdout + +By default, the resulting nodes will be printed one per line to standard output. +To update the input files, use -w. +`) +} + +func main() { + m := matcher{ + out: os.Stdout, + ctx: &build.Default, + } + err := m.fromArgs(".", os.Args[1:]) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +type matcher struct { + out io.Writer + ctx *build.Context + + fset *token.FileSet + + parents map[ast.Node]ast.Node + + recursive, tests bool + aggressive bool + + // information about variables (wildcards), by id (which is an + // integer starting at 0) + vars []varInfo + + // node values recorded by name, excluding "_" (used only by the + // actual matching phase) + values map[string]ast.Node + scope *types.Scope + + *types.Info + stdImporter types.Importer +} + +type varInfo struct { + name string + any bool +} + +func (m *matcher) info(id int) varInfo { + if id < 0 { + return varInfo{} + } + return m.vars[id] +} + +type exprCmd struct { + name string + src string + value interface{} +} + +type strCmdFlag struct { + name string + cmds *[]exprCmd +} + +func (o *strCmdFlag) String() string { return "" } +func (o *strCmdFlag) Set(val string) error { + *o.cmds = append(*o.cmds, exprCmd{name: o.name, src: val}) + return nil +} + +type boolCmdFlag struct { + name string + cmds *[]exprCmd +} + +func (o *boolCmdFlag) String() string { return "" } +func (o *boolCmdFlag) Set(val string) error { + if val != "true" { + return fmt.Errorf("flag can only be true") + } + *o.cmds = append(*o.cmds, exprCmd{name: o.name}) + return nil +} +func (o *boolCmdFlag) IsBoolFlag() bool { return true } + +func (m *matcher) fromArgs(wd string, args []string) error { + m.fset = token.NewFileSet() + cmds, args, err := m.parseCmds(args) + if err != nil { + return err + } + pkgs, err := m.load(wd, args...) + if err != nil { + return err + } + var all []ast.Node + for _, pkg := range pkgs { + m.Info = pkg.TypesInfo + nodes := make([]ast.Node, len(pkg.Syntax)) + for i, f := range pkg.Syntax { + nodes[i] = f + } + all = append(all, m.matches(cmds, nodes)...) + } + for _, n := range all { + fpos := m.fset.Position(n.Pos()) + if strings.HasPrefix(fpos.Filename, wd) { + fpos.Filename = fpos.Filename[len(wd)+1:] + } + fmt.Fprintf(m.out, "%v: %s\n", fpos, singleLinePrint(n)) + } + return nil +} + +func (m *matcher) parseCmds(args []string) ([]exprCmd, []string, error) { + flagSet := flag.NewFlagSet("gogrep", flag.ExitOnError) + flagSet.Usage = usage + flagSet.BoolVar(&m.recursive, "r", false, "search dependencies recursively too") + flagSet.BoolVar(&m.tests, "tests", false, "search test files too (and direct test deps, with -r)") + + var cmds []exprCmd + flagSet.Var(&strCmdFlag{ + name: "x", + cmds: &cmds, + }, "x", "") + flagSet.Var(&strCmdFlag{ + name: "g", + cmds: &cmds, + }, "g", "") + flagSet.Var(&strCmdFlag{ + name: "v", + cmds: &cmds, + }, "v", "") + flagSet.Var(&strCmdFlag{ + name: "a", + cmds: &cmds, + }, "a", "") + flagSet.Var(&strCmdFlag{ + name: "s", + cmds: &cmds, + }, "s", "") + flagSet.Var(&strCmdFlag{ + name: "p", + cmds: &cmds, + }, "p", "") + flagSet.Var(&boolCmdFlag{ + name: "w", + cmds: &cmds, + }, "w", "") + flagSet.Parse(args) + paths := flagSet.Args() + + if len(cmds) < 1 { + return nil, nil, fmt.Errorf("need at least one command") + } + for i, cmd := range cmds { + switch cmd.name { + case "w": + continue // no expr + case "p": + n, err := strconv.Atoi(cmd.src) + if err != nil { + return nil, nil, err + } + cmds[i].value = n + case "a": + m, err := m.parseAttrs(cmd.src) + if err != nil { + return nil, nil, fmt.Errorf("cannot parse mods: %v", err) + } + cmds[i].value = m + default: + node, err := m.parseExpr(cmd.src) + if err != nil { + return nil, nil, err + } + cmds[i].value = node + } + } + return cmds, paths, nil +} + +type bufferJoinLines struct { + bytes.Buffer + last string +} + +var rxNeedSemicolon = regexp.MustCompile(`([])}a-zA-Z0-9"'` + "`" + `]|\+\+|--)$`) + +func (b *bufferJoinLines) Write(p []byte) (n int, err error) { + if string(p) == "\n" { + if b.last == "\n" { + return 1, nil + } + if rxNeedSemicolon.MatchString(b.last) { + b.Buffer.WriteByte(';') + } + b.Buffer.WriteByte(' ') + b.last = "\n" + return 1, nil + } + p = bytes.Trim(p, "\t") + n, err = b.Buffer.Write(p) + b.last = string(p) + return +} + +func (b *bufferJoinLines) String() string { + return strings.TrimSuffix(b.Buffer.String(), "; ") +} + +// inspect is like ast.Inspect, but it supports our extra nodeList Node +// type (only at the top level). +func inspect(node ast.Node, fn func(ast.Node) bool) { + // ast.Walk barfs on ast.Node types it doesn't know, so + // do the first level manually here + list, ok := node.(nodeList) + if !ok { + ast.Inspect(node, fn) + return + } + if !fn(list) { + return + } + for i := 0; i < list.len(); i++ { + ast.Inspect(list.at(i), fn) + } + fn(nil) +} + +var emptyFset = token.NewFileSet() + +func singleLinePrint(node ast.Node) string { + var buf bufferJoinLines + inspect(node, func(node ast.Node) bool { + bl, ok := node.(*ast.BasicLit) + if !ok || bl.Kind != token.STRING { + return true + } + if !strings.HasPrefix(bl.Value, "`") { + return true + } + if !strings.Contains(bl.Value, "\n") { + return true + } + bl.Value = strconv.Quote(bl.Value[1 : len(bl.Value)-1]) + return true + }) + printNode(&buf, emptyFset, node) + return buf.String() +} + +func printNode(w io.Writer, fset *token.FileSet, node ast.Node) { + switch x := node.(type) { + case exprList: + if len(x) == 0 { + return + } + printNode(w, fset, x[0]) + for _, n := range x[1:] { + fmt.Fprintf(w, ", ") + printNode(w, fset, n) + } + case stmtList: + if len(x) == 0 { + return + } + printNode(w, fset, x[0]) + for _, n := range x[1:] { + fmt.Fprintf(w, "; ") + printNode(w, fset, n) + } + default: + err := printer.Fprint(w, fset, node) + if err != nil && strings.Contains(err.Error(), "go/printer: unsupported node type") { + // Should never happen, but make it obvious when it does. + panic(fmt.Errorf("cannot print node %T: %v", node, err)) + } + } +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/match.go b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/match.go new file mode 100644 index 00000000000..08b53d87da0 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/match.go @@ -0,0 +1,1108 @@ +// Copyright (c) 2017, Daniel Martí +// See LICENSE for licensing information + +package gogrep + +import ( + "fmt" + "go/ast" + "go/importer" + "go/token" + "go/types" + "regexp" + "strconv" +) + +func (m *matcher) matches(cmds []exprCmd, nodes []ast.Node) []ast.Node { + m.parents = make(map[ast.Node]ast.Node) + m.fillParents(nodes...) + initial := make([]submatch, len(nodes)) + for i, node := range nodes { + initial[i].node = node + initial[i].values = make(map[string]ast.Node) + } + final := m.submatches(cmds, initial) + finalNodes := make([]ast.Node, len(final)) + for i := range finalNodes { + finalNodes[i] = final[i].node + } + return finalNodes +} + +func (m *matcher) fillParents(nodes ...ast.Node) { + stack := make([]ast.Node, 1, 32) + for _, node := range nodes { + inspect(node, func(node ast.Node) bool { + if node == nil { + stack = stack[:len(stack)-1] + return true + } + if _, ok := node.(nodeList); !ok { + m.parents[node] = stack[len(stack)-1] + } + stack = append(stack, node) + return true + }) + } +} + +type submatch struct { + node ast.Node + values map[string]ast.Node +} + +func valsCopy(values map[string]ast.Node) map[string]ast.Node { + v2 := make(map[string]ast.Node, len(values)) + for k, v := range values { + v2[k] = v + } + return v2 +} + +func (m *matcher) submatches(cmds []exprCmd, subs []submatch) []submatch { + if len(cmds) == 0 { + return subs + } + cmd := cmds[0] + var fn func(exprCmd, []submatch) []submatch + switch cmd.name { + case "x": + fn = m.cmdRange + case "g": + fn = m.cmdFilter(true) + case "v": + fn = m.cmdFilter(false) + case "s": + fn = m.cmdSubst + case "a": + fn = m.cmdAttr + case "p": + fn = m.cmdParents + case "w": + if len(cmds) > 1 { + panic("-w must be the last command") + } + fn = m.cmdWrite + default: + panic(fmt.Sprintf("unknown command: %q", cmd.name)) + } + return m.submatches(cmds[1:], fn(cmd, subs)) +} + +func (m *matcher) cmdRange(cmd exprCmd, subs []submatch) []submatch { + var matches []submatch + seen := map[nodePosHash]bool{} + + // The values context for each new submatch must be a new copy + // from its parent submatch. If we don't do this copy, all the + // submatches would share the same map and have side effects. + var startValues map[string]ast.Node + + match := func(exprNode, node ast.Node) { + if node == nil { + return + } + m.values = valsCopy(startValues) + found := m.topNode(exprNode, node) + if found == nil { + return + } + hash := posHash(found) + if !seen[hash] { + matches = append(matches, submatch{ + node: found, + values: m.values, + }) + seen[hash] = true + } + } + for _, sub := range subs { + startValues = valsCopy(sub.values) + m.walkWithLists(cmd.value.(ast.Node), sub.node, match) + } + return matches +} + +func (m *matcher) cmdFilter(wantAny bool) func(exprCmd, []submatch) []submatch { + return func(cmd exprCmd, subs []submatch) []submatch { + var matches []submatch + any := false + match := func(exprNode, node ast.Node) { + if node == nil { + return + } + found := m.topNode(exprNode, node) + if found != nil { + any = true + } + } + for _, sub := range subs { + any = false + m.values = sub.values + m.walkWithLists(cmd.value.(ast.Node), sub.node, match) + if any == wantAny { + matches = append(matches, sub) + } + } + return matches + } +} + +func (m *matcher) cmdAttr(cmd exprCmd, subs []submatch) []submatch { + var matches []submatch + for _, sub := range subs { + m.values = sub.values + if m.attrApplies(sub.node, cmd.value.(attribute)) { + matches = append(matches, sub) + } + } + return matches +} + +func (m *matcher) cmdParents(cmd exprCmd, subs []submatch) []submatch { + for i := range subs { + sub := &subs[i] + reps := cmd.value.(int) + for j := 0; j < reps; j++ { + sub.node = m.parentOf(sub.node) + } + } + return subs +} + +func (m *matcher) attrApplies(node ast.Node, attr interface{}) bool { + if rx, ok := attr.(*regexp.Regexp); ok { + if exprStmt, ok := node.(*ast.ExprStmt); ok { + // since we prefer matching entire statements, get the + // ident from the ExprStmt + node = exprStmt.X + } + ident, ok := node.(*ast.Ident) + return ok && rx.MatchString(ident.Name) + } + expr, _ := node.(ast.Expr) + if expr == nil { + return false // only exprs have types + } + t := m.Info.TypeOf(expr) + if t == nil { + return false // an expr, but no type? + } + tv := m.Info.Types[expr] + switch x := attr.(type) { + case typeCheck: + want := m.resolveType(m.scope, x.expr) + switch { + case x.op == "type" && !types.Identical(t, want): + return false + case x.op == "asgn" && !types.AssignableTo(t, want): + return false + case x.op == "conv" && !types.ConvertibleTo(t, want): + return false + } + case typProperty: + switch { + case x == "comp" && !types.Comparable(t): + return false + case x == "addr" && !tv.Addressable(): + return false + } + case typUnderlying: + u := t.Underlying() + uok := true + switch x { + case "basic": + _, uok = u.(*types.Basic) + case "array": + _, uok = u.(*types.Array) + case "slice": + _, uok = u.(*types.Slice) + case "struct": + _, uok = u.(*types.Struct) + case "interface": + _, uok = u.(*types.Interface) + case "pointer": + _, uok = u.(*types.Pointer) + case "func": + _, uok = u.(*types.Signature) + case "map": + _, uok = u.(*types.Map) + case "chan": + _, uok = u.(*types.Chan) + } + if !uok { + return false + } + } + return true +} + +func (m *matcher) walkWithLists(exprNode, node ast.Node, fn func(exprNode, node ast.Node)) { + visit := func(node ast.Node) bool { + fn(exprNode, node) + for _, list := range nodeLists(node) { + fn(exprNode, list) + if id := m.wildAnyIdent(exprNode); id != nil { + // so that "$*a" will match "a, b" + fn(exprList([]ast.Expr{id}), list) + // so that "$*a" will match "a; b" + fn(toStmtList(id), list) + } + } + return true + } + inspect(node, visit) +} + +func (m *matcher) topNode(exprNode, node ast.Node) ast.Node { + sts1, ok1 := exprNode.(stmtList) + sts2, ok2 := node.(stmtList) + if ok1 && ok2 { + // allow a partial match at the top level + return m.nodes(sts1, sts2, true) + } + if m.node(exprNode, node) { + return node + } + return nil +} + +// optNode is like node, but for those nodes that can be nil and are not +// part of a list. For example, init and post statements in a for loop. +func (m *matcher) optNode(expr, node ast.Node) bool { + if ident := m.wildAnyIdent(expr); ident != nil { + if m.node(toStmtList(ident), toStmtList(node)) { + return true + } + } + return m.node(expr, node) +} + +func (m *matcher) node(expr, node ast.Node) bool { + switch node.(type) { + case *ast.File, *ast.FuncType, *ast.BlockStmt, *ast.IfStmt, + *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.CaseClause, + *ast.CommClause, *ast.ForStmt, *ast.RangeStmt: + if scope := m.Info.Scopes[node]; scope != nil { + m.scope = scope + } + } + if !m.aggressive { + if expr == nil || node == nil { + return expr == node + } + } else { + if expr == nil && node == nil { + return true + } + if node == nil { + expr, node = node, expr + } + } + switch x := expr.(type) { + case nil: // only in aggressive mode + y, ok := node.(*ast.Ident) + return ok && y.Name == "_" + + case *ast.File: + y, ok := node.(*ast.File) + if !ok || !m.node(x.Name, y.Name) || len(x.Decls) != len(y.Decls) || + len(x.Imports) != len(y.Imports) { + return false + } + for i, decl := range x.Decls { + if !m.node(decl, y.Decls[i]) { + return false + } + } + for i, imp := range x.Imports { + if !m.node(imp, y.Imports[i]) { + return false + } + } + return true + + case *ast.Ident: + y, yok := node.(*ast.Ident) + if !isWildName(x.Name) { + // not a wildcard + return yok && x.Name == y.Name + } + if _, ok := node.(ast.Node); !ok { + return false // to not include our extra node types + } + id := fromWildName(x.Name) + info := m.info(id) + if info.any { + return false + } + if info.name == "_" { + // values are discarded, matches anything + return true + } + prev, ok := m.values[info.name] + if !ok { + // first occurrence, record value + m.values[info.name] = node + return true + } + // multiple uses must match + return m.node(prev, node) + + // lists (ys are generated by us while walking) + case exprList: + y, ok := node.(exprList) + return ok && m.exprs(x, y) + case stmtList: + y, ok := node.(stmtList) + return ok && m.stmts(x, y) + + // lits + case *ast.BasicLit: + y, ok := node.(*ast.BasicLit) + return ok && x.Kind == y.Kind && x.Value == y.Value + case *ast.CompositeLit: + y, ok := node.(*ast.CompositeLit) + return ok && m.node(x.Type, y.Type) && m.exprs(x.Elts, y.Elts) + case *ast.FuncLit: + y, ok := node.(*ast.FuncLit) + return ok && m.node(x.Type, y.Type) && m.node(x.Body, y.Body) + + // types + case *ast.ArrayType: + y, ok := node.(*ast.ArrayType) + return ok && m.node(x.Len, y.Len) && m.node(x.Elt, y.Elt) + case *ast.MapType: + y, ok := node.(*ast.MapType) + return ok && m.node(x.Key, y.Key) && m.node(x.Value, y.Value) + case *ast.StructType: + y, ok := node.(*ast.StructType) + return ok && m.fields(x.Fields, y.Fields) + case *ast.Field: + // TODO: tags? + y, ok := node.(*ast.Field) + if !ok { + return false + } + if len(x.Names) == 0 && x.Tag == nil && m.node(x.Type, y) { + // Allow $var to match a field. + return true + } + return m.idents(x.Names, y.Names) && m.node(x.Type, y.Type) + case *ast.FuncType: + y, ok := node.(*ast.FuncType) + return ok && m.fields(x.Params, y.Params) && + m.fields(x.Results, y.Results) + case *ast.InterfaceType: + y, ok := node.(*ast.InterfaceType) + return ok && m.fields(x.Methods, y.Methods) + case *ast.ChanType: + y, ok := node.(*ast.ChanType) + return ok && x.Dir == y.Dir && m.node(x.Value, y.Value) + + // other exprs + case *ast.Ellipsis: + y, ok := node.(*ast.Ellipsis) + return ok && m.node(x.Elt, y.Elt) + case *ast.ParenExpr: + y, ok := node.(*ast.ParenExpr) + return ok && m.node(x.X, y.X) + case *ast.UnaryExpr: + y, ok := node.(*ast.UnaryExpr) + return ok && x.Op == y.Op && m.node(x.X, y.X) + case *ast.BinaryExpr: + y, ok := node.(*ast.BinaryExpr) + return ok && x.Op == y.Op && m.node(x.X, y.X) && m.node(x.Y, y.Y) + case *ast.CallExpr: + y, ok := node.(*ast.CallExpr) + return ok && m.node(x.Fun, y.Fun) && m.exprs(x.Args, y.Args) && + bothValid(x.Ellipsis, y.Ellipsis) + case *ast.KeyValueExpr: + y, ok := node.(*ast.KeyValueExpr) + return ok && m.node(x.Key, y.Key) && m.node(x.Value, y.Value) + case *ast.StarExpr: + y, ok := node.(*ast.StarExpr) + return ok && m.node(x.X, y.X) + case *ast.SelectorExpr: + y, ok := node.(*ast.SelectorExpr) + return ok && m.node(x.X, y.X) && m.node(x.Sel, y.Sel) + case *ast.IndexExpr: + y, ok := node.(*ast.IndexExpr) + return ok && m.node(x.X, y.X) && m.node(x.Index, y.Index) + case *ast.SliceExpr: + y, ok := node.(*ast.SliceExpr) + return ok && m.node(x.X, y.X) && m.node(x.Low, y.Low) && + m.node(x.High, y.High) && m.node(x.Max, y.Max) + case *ast.TypeAssertExpr: + y, ok := node.(*ast.TypeAssertExpr) + return ok && m.node(x.X, y.X) && m.node(x.Type, y.Type) + + // decls + case *ast.GenDecl: + y, ok := node.(*ast.GenDecl) + return ok && x.Tok == y.Tok && m.specs(x.Specs, y.Specs) + case *ast.FuncDecl: + y, ok := node.(*ast.FuncDecl) + return ok && m.fields(x.Recv, y.Recv) && m.node(x.Name, y.Name) && + m.node(x.Type, y.Type) && m.node(x.Body, y.Body) + + // specs + case *ast.ValueSpec: + y, ok := node.(*ast.ValueSpec) + if !ok || !m.node(x.Type, y.Type) { + return false + } + if m.aggressive && len(x.Names) == 1 { + for i := range y.Names { + if m.node(x.Names[i], y.Names[i]) && + (x.Values == nil || m.node(x.Values[i], y.Values[i])) { + return true + } + } + } + return m.idents(x.Names, y.Names) && m.exprs(x.Values, y.Values) + + // stmt bridge nodes + case *ast.ExprStmt: + if id, ok := x.X.(*ast.Ident); ok && isWildName(id.Name) { + // prefer matching $x as a statement, as it's + // the parent + return m.node(id, node) + } + y, ok := node.(*ast.ExprStmt) + return ok && m.node(x.X, y.X) + case *ast.DeclStmt: + y, ok := node.(*ast.DeclStmt) + return ok && m.node(x.Decl, y.Decl) + + // stmts + case *ast.EmptyStmt: + _, ok := node.(*ast.EmptyStmt) + return ok + case *ast.LabeledStmt: + y, ok := node.(*ast.LabeledStmt) + return ok && m.node(x.Label, y.Label) && m.node(x.Stmt, y.Stmt) + case *ast.SendStmt: + y, ok := node.(*ast.SendStmt) + return ok && m.node(x.Chan, y.Chan) && m.node(x.Value, y.Value) + case *ast.IncDecStmt: + y, ok := node.(*ast.IncDecStmt) + return ok && x.Tok == y.Tok && m.node(x.X, y.X) + case *ast.AssignStmt: + y, ok := node.(*ast.AssignStmt) + if !m.aggressive { + return ok && x.Tok == y.Tok && + m.exprs(x.Lhs, y.Lhs) && m.exprs(x.Rhs, y.Rhs) + } + if ok { + return m.exprs(x.Lhs, y.Lhs) && m.exprs(x.Rhs, y.Rhs) + } + vs, ok := node.(*ast.ValueSpec) + return ok && m.nodesMatch(exprList(x.Lhs), identList(vs.Names)) && + m.exprs(x.Rhs, vs.Values) + case *ast.GoStmt: + y, ok := node.(*ast.GoStmt) + return ok && m.node(x.Call, y.Call) + case *ast.DeferStmt: + y, ok := node.(*ast.DeferStmt) + return ok && m.node(x.Call, y.Call) + case *ast.ReturnStmt: + y, ok := node.(*ast.ReturnStmt) + return ok && m.exprs(x.Results, y.Results) + case *ast.BranchStmt: + y, ok := node.(*ast.BranchStmt) + return ok && x.Tok == y.Tok && m.node(maybeNilIdent(x.Label), maybeNilIdent(y.Label)) + case *ast.BlockStmt: + if m.aggressive && m.node(stmtList(x.List), node) { + return true + } + y, ok := node.(*ast.BlockStmt) + if !ok { + return false + } + if x == nil || y == nil { + return x == y + } + return m.cases(x.List, y.List) || m.stmts(x.List, y.List) + case *ast.IfStmt: + y, ok := node.(*ast.IfStmt) + if !ok { + return false + } + condAny := m.wildAnyIdent(x.Cond) + if condAny != nil && x.Init == nil { + // if $*x { ... } on the left + left := toStmtList(condAny) + return m.node(left, toStmtList(y.Init, y.Cond)) && + m.node(x.Body, y.Body) && m.optNode(x.Else, y.Else) + } + return m.optNode(x.Init, y.Init) && m.node(x.Cond, y.Cond) && + m.node(x.Body, y.Body) && m.node(x.Else, y.Else) + case *ast.CaseClause: + y, ok := node.(*ast.CaseClause) + return ok && m.exprs(x.List, y.List) && m.stmts(x.Body, y.Body) + case *ast.SwitchStmt: + y, ok := node.(*ast.SwitchStmt) + if !ok { + return false + } + tagAny := m.wildAnyIdent(x.Tag) + if tagAny != nil && x.Init == nil { + // switch $*x { ... } on the left + left := toStmtList(tagAny) + return m.node(left, toStmtList(y.Init, y.Tag)) && + m.node(x.Body, y.Body) + } + return m.optNode(x.Init, y.Init) && m.node(x.Tag, y.Tag) && m.node(x.Body, y.Body) + case *ast.TypeSwitchStmt: + y, ok := node.(*ast.TypeSwitchStmt) + return ok && m.optNode(x.Init, y.Init) && m.node(x.Assign, y.Assign) && m.node(x.Body, y.Body) + case *ast.CommClause: + y, ok := node.(*ast.CommClause) + return ok && m.node(x.Comm, y.Comm) && m.stmts(x.Body, y.Body) + case *ast.SelectStmt: + y, ok := node.(*ast.SelectStmt) + return ok && m.node(x.Body, y.Body) + case *ast.ForStmt: + condIdent := m.wildAnyIdent(x.Cond) + if condIdent != nil && x.Init == nil && x.Post == nil { + // "for $*x { ... }" on the left + left := toStmtList(condIdent) + // also accept RangeStmt on the right + switch y := node.(type) { + case *ast.ForStmt: + return m.node(left, toStmtList(y.Init, y.Cond, y.Post)) && + m.node(x.Body, y.Body) + case *ast.RangeStmt: + return m.node(left, toStmtList(y.Key, y.Value, y.X)) && + m.node(x.Body, y.Body) + default: + return false + } + } + y, ok := node.(*ast.ForStmt) + if !ok { + return false + } + return m.optNode(x.Init, y.Init) && m.node(x.Cond, y.Cond) && + m.optNode(x.Post, y.Post) && m.node(x.Body, y.Body) + case *ast.RangeStmt: + y, ok := node.(*ast.RangeStmt) + return ok && m.node(x.Key, y.Key) && m.node(x.Value, y.Value) && + m.node(x.X, y.X) && m.node(x.Body, y.Body) + + case *ast.TypeSpec: + y, ok := node.(*ast.TypeSpec) + return ok && m.node(x.Name, y.Name) && m.node(x.Type, y.Type) + + case *ast.FieldList: + // we ignore these, for now + return false + default: + panic(fmt.Sprintf("unexpected node: %T", x)) + } +} + +func (m *matcher) wildAnyIdent(node ast.Node) *ast.Ident { + switch x := node.(type) { + case *ast.ExprStmt: + return m.wildAnyIdent(x.X) + case *ast.Ident: + if !isWildName(x.Name) { + return nil + } + if !m.info(fromWildName(x.Name)).any { + return nil + } + return x + } + return nil +} + +// resolveType resolves a type expression from a given scope. +func (m *matcher) resolveType(scope *types.Scope, expr ast.Expr) types.Type { + switch x := expr.(type) { + case *ast.Ident: + _, obj := scope.LookupParent(x.Name, token.NoPos) + if obj == nil { + // TODO: error if all resolveType calls on a type + // expression fail? or perhaps resolve type expressions + // across the entire program? + return nil + } + return obj.Type() + case *ast.ArrayType: + elt := m.resolveType(scope, x.Elt) + if x.Len == nil { + return types.NewSlice(elt) + } + bl, ok := x.Len.(*ast.BasicLit) + if !ok || bl.Kind != token.INT { + panic(fmt.Sprintf("TODO: %T", x)) + } + len, _ := strconv.ParseInt(bl.Value, 0, 0) + return types.NewArray(elt, len) + case *ast.StarExpr: + return types.NewPointer(m.resolveType(scope, x.X)) + case *ast.ChanType: + dir := types.SendRecv + switch x.Dir { + case ast.SEND: + dir = types.SendOnly + case ast.RECV: + dir = types.RecvOnly + } + return types.NewChan(dir, m.resolveType(scope, x.Value)) + case *ast.SelectorExpr: + scope = m.findScope(scope, x.X) + return m.resolveType(scope, x.Sel) + default: + panic(fmt.Sprintf("resolveType TODO: %T", x)) + } +} + +func (m *matcher) findScope(scope *types.Scope, expr ast.Expr) *types.Scope { + switch x := expr.(type) { + case *ast.Ident: + _, obj := scope.LookupParent(x.Name, token.NoPos) + if pkg, ok := obj.(*types.PkgName); ok { + return pkg.Imported().Scope() + } + // try to fall back to std + if m.stdImporter == nil { + m.stdImporter = importer.Default() + } + path := x.Name + if longer, ok := stdImportFixes[path]; ok { + path = longer + } + pkg, err := m.stdImporter.Import(path) + if err != nil { + panic(fmt.Sprintf("findScope err: %v", err)) + } + return pkg.Scope() + default: + panic(fmt.Sprintf("findScope TODO: %T", x)) + } +} + +var stdImportFixes = map[string]string{ + // go list std | grep -vE 'vendor|internal' | grep '/' | sed -r 's@^(.*)/([^/]*)$@"\2": "\1/\2",@' | sort + // (after commenting out the less likely duplicates) + "adler32": "hash/adler32", + "aes": "crypto/aes", + "ascii85": "encoding/ascii85", + "asn1": "encoding/asn1", + "ast": "go/ast", + "atomic": "sync/atomic", + "base32": "encoding/base32", + "base64": "encoding/base64", + "big": "math/big", + "binary": "encoding/binary", + "bits": "math/bits", + "build": "go/build", + "bzip2": "compress/bzip2", + "cgi": "net/http/cgi", + "cgo": "runtime/cgo", + "cipher": "crypto/cipher", + "cmplx": "math/cmplx", + "color": "image/color", + "constant": "go/constant", + "cookiejar": "net/http/cookiejar", + "crc32": "hash/crc32", + "crc64": "hash/crc64", + "csv": "encoding/csv", + "debug": "runtime/debug", + "des": "crypto/des", + "doc": "go/doc", + "draw": "image/draw", + "driver": "database/sql/driver", + "dsa": "crypto/dsa", + "dwarf": "debug/dwarf", + "ecdsa": "crypto/ecdsa", + "elf": "debug/elf", + "elliptic": "crypto/elliptic", + "exec": "os/exec", + "fcgi": "net/http/fcgi", + "filepath": "path/filepath", + "flate": "compress/flate", + "fnv": "hash/fnv", + "format": "go/format", + "gif": "image/gif", + "gob": "encoding/gob", + "gosym": "debug/gosym", + "gzip": "compress/gzip", + "heap": "container/heap", + "hex": "encoding/hex", + "hmac": "crypto/hmac", + "http": "net/http", + "httptest": "net/http/httptest", + "httptrace": "net/http/httptrace", + "httputil": "net/http/httputil", + "importer": "go/importer", + "iotest": "testing/iotest", + "ioutil": "io/ioutil", + "jpeg": "image/jpeg", + "json": "encoding/json", + "jsonrpc": "net/rpc/jsonrpc", + "list": "container/list", + "lzw": "compress/lzw", + "macho": "debug/macho", + "mail": "net/mail", + "md5": "crypto/md5", + "multipart": "mime/multipart", + "palette": "image/color/palette", + "parser": "go/parser", + "parse": "text/template/parse", + "pe": "debug/pe", + "pem": "encoding/pem", + "pkix": "crypto/x509/pkix", + "plan9obj": "debug/plan9obj", + "png": "image/png", + //"pprof": "net/http/pprof", + "pprof": "runtime/pprof", + "printer": "go/printer", + "quick": "testing/quick", + "quotedprintable": "mime/quotedprintable", + "race": "runtime/race", + //"rand": "crypto/rand", + "rand": "math/rand", + "rc4": "crypto/rc4", + "ring": "container/ring", + "rpc": "net/rpc", + "rsa": "crypto/rsa", + //"scanner": "go/scanner", + "scanner": "text/scanner", + "sha1": "crypto/sha1", + "sha256": "crypto/sha256", + "sha512": "crypto/sha512", + "signal": "os/signal", + "smtp": "net/smtp", + "sql": "database/sql", + "subtle": "crypto/subtle", + "suffixarray": "index/suffixarray", + "syntax": "regexp/syntax", + "syslog": "log/syslog", + "tabwriter": "text/tabwriter", + "tar": "archive/tar", + //"template": "html/template", + "template": "text/template", + "textproto": "net/textproto", + "tls": "crypto/tls", + "token": "go/token", + "trace": "runtime/trace", + "types": "go/types", + "url": "net/url", + "user": "os/user", + "utf16": "unicode/utf16", + "utf8": "unicode/utf8", + "x509": "crypto/x509", + "xml": "encoding/xml", + "zip": "archive/zip", + "zlib": "compress/zlib", +} + +func maybeNilIdent(x *ast.Ident) ast.Node { + if x == nil { + return nil + } + return x +} + +func bothValid(p1, p2 token.Pos) bool { + return p1.IsValid() == p2.IsValid() +} + +type nodeList interface { + at(i int) ast.Node + len() int + slice(from, to int) nodeList + ast.Node +} + +// nodes matches two lists of nodes. It uses a common algorithm to match +// wildcard patterns with any number of nodes without recursion. +func (m *matcher) nodes(ns1, ns2 nodeList, partial bool) ast.Node { + ns1len, ns2len := ns1.len(), ns2.len() + if ns1len == 0 { + if ns2len == 0 { + return ns2 + } + return nil + } + partialStart, partialEnd := 0, ns2len + i1, i2 := 0, 0 + next1, next2 := 0, 0 + + // We need to keep a copy of m.values so that we can restart + // with a different "any of" match while discarding any matches + // we found while trying it. + type restart struct { + matches map[string]ast.Node + next1, next2 int + } + // We need to stack these because otherwise some edge cases + // would not match properly. Since we have various kinds of + // wildcards (nodes containing them, $_, and $*_), in some cases + // we may have to go back and do multiple restarts to get to the + // right starting position. + var stack []restart + push := func(n1, n2 int) { + if n2 > ns2len { + return // would be discarded anyway + } + stack = append(stack, restart{valsCopy(m.values), n1, n2}) + next1, next2 = n1, n2 + } + pop := func() { + i1, i2 = next1, next2 + m.values = stack[len(stack)-1].matches + stack = stack[:len(stack)-1] + next1, next2 = 0, 0 + if len(stack) > 0 { + next1 = stack[len(stack)-1].next1 + next2 = stack[len(stack)-1].next2 + } + } + wildName := "" + wildStart := 0 + + // wouldMatch returns whether the current wildcard - if any - + // matches the nodes we are currently trying it on. + wouldMatch := func() bool { + switch wildName { + case "", "_": + return true + } + list := ns2.slice(wildStart, i2) + // check that it matches any nodes found elsewhere + prev, ok := m.values[wildName] + if ok && !m.node(prev, list) { + return false + } + m.values[wildName] = list + return true + } + for i1 < ns1len || i2 < ns2len { + if i1 < ns1len { + n1 := ns1.at(i1) + id := fromWildNode(n1) + info := m.info(id) + if info.any { + // keep track of where this wildcard + // started (if info.name == wildName, + // we're trying the same wildcard + // matching one more node) + if info.name != wildName { + wildStart = i2 + wildName = info.name + } + // try to match zero or more at i2, + // restarting at i2+1 if it fails + push(i1, i2+1) + i1++ + continue + } + if partial && i1 == 0 { + // let "b; c" match "a; b; c" + // (simulates a $*_ at the beginning) + partialStart = i2 + push(i1, i2+1) + } + if i2 < ns2len && wouldMatch() && m.node(n1, ns2.at(i2)) { + wildName = "" + // ordinary match + i1++ + i2++ + continue + } + } + if partial && i1 == ns1len && wildName == "" { + partialEnd = i2 + break // let "b; c" match "b; c; d" + } + // mismatch, try to restart + if 0 < next2 && next2 <= ns2len && (i1 != next1 || i2 != next2) { + pop() + continue + } + return nil + } + if !wouldMatch() { + return nil + } + return ns2.slice(partialStart, partialEnd) +} + +func (m *matcher) nodesMatch(list1, list2 nodeList) bool { + return m.nodes(list1, list2, false) != nil +} + +func (m *matcher) exprs(exprs1, exprs2 []ast.Expr) bool { + return m.nodesMatch(exprList(exprs1), exprList(exprs2)) +} + +func (m *matcher) idents(ids1, ids2 []*ast.Ident) bool { + return m.nodesMatch(identList(ids1), identList(ids2)) +} + +func toStmtList(nodes ...ast.Node) stmtList { + var stmts []ast.Stmt + for _, node := range nodes { + switch x := node.(type) { + case nil: + case ast.Stmt: + stmts = append(stmts, x) + case ast.Expr: + stmts = append(stmts, &ast.ExprStmt{X: x}) + default: + panic(fmt.Sprintf("unexpected node type: %T", x)) + } + } + return stmtList(stmts) +} + +func (m *matcher) cases(stmts1, stmts2 []ast.Stmt) bool { + for _, stmt := range stmts2 { + switch stmt.(type) { + case *ast.CaseClause, *ast.CommClause: + default: + return false + } + } + var left []*ast.Ident + for _, stmt := range stmts1 { + var expr ast.Expr + var bstmt ast.Stmt + switch x := stmt.(type) { + case *ast.CaseClause: + if len(x.List) != 1 || len(x.Body) != 1 { + return false + } + expr, bstmt = x.List[0], x.Body[0] + case *ast.CommClause: + if x.Comm == nil || len(x.Body) != 1 { + return false + } + if commExpr, ok := x.Comm.(*ast.ExprStmt); ok { + expr = commExpr.X + } + bstmt = x.Body[0] + default: + return false + } + xs, ok := bstmt.(*ast.ExprStmt) + if !ok { + return false + } + bodyIdent, ok := xs.X.(*ast.Ident) + if !ok || bodyIdent.Name != "gogrep_body" { + return false + } + id, ok := expr.(*ast.Ident) + if !ok || !isWildName(id.Name) { + return false + } + left = append(left, id) + } + return m.nodesMatch(identList(left), stmtList(stmts2)) +} + +func (m *matcher) stmts(stmts1, stmts2 []ast.Stmt) bool { + return m.nodesMatch(stmtList(stmts1), stmtList(stmts2)) +} + +func (m *matcher) specs(specs1, specs2 []ast.Spec) bool { + return m.nodesMatch(specList(specs1), specList(specs2)) +} + +func (m *matcher) fields(fields1, fields2 *ast.FieldList) bool { + if fields1 == nil || fields2 == nil { + return fields1 == fields2 + } + return m.nodesMatch(fieldList(fields1.List), fieldList(fields2.List)) +} + +func fromWildNode(node ast.Node) int { + switch node := node.(type) { + case *ast.Ident: + return fromWildName(node.Name) + case *ast.ExprStmt: + return fromWildNode(node.X) + case *ast.Field: + // Allow $var to represent an entire field; the lone identifier + // gets picked up as an anonymous field. + if len(node.Names) == 0 && node.Tag == nil { + return fromWildNode(node.Type) + } + } + return -1 +} + +func nodeLists(n ast.Node) []nodeList { + var lists []nodeList + addList := func(list nodeList) { + if list.len() > 0 { + lists = append(lists, list) + } + } + switch x := n.(type) { + case nodeList: + addList(x) + case *ast.CompositeLit: + addList(exprList(x.Elts)) + case *ast.CallExpr: + addList(exprList(x.Args)) + case *ast.AssignStmt: + addList(exprList(x.Lhs)) + addList(exprList(x.Rhs)) + case *ast.ReturnStmt: + addList(exprList(x.Results)) + case *ast.ValueSpec: + addList(exprList(x.Values)) + case *ast.BlockStmt: + addList(stmtList(x.List)) + case *ast.CaseClause: + addList(exprList(x.List)) + addList(stmtList(x.Body)) + case *ast.CommClause: + addList(stmtList(x.Body)) + } + return lists +} + +type exprList []ast.Expr +type identList []*ast.Ident +type stmtList []ast.Stmt +type specList []ast.Spec +type fieldList []*ast.Field + +func (l exprList) len() int { return len(l) } +func (l identList) len() int { return len(l) } +func (l stmtList) len() int { return len(l) } +func (l specList) len() int { return len(l) } +func (l fieldList) len() int { return len(l) } + +func (l exprList) at(i int) ast.Node { return l[i] } +func (l identList) at(i int) ast.Node { return l[i] } +func (l stmtList) at(i int) ast.Node { return l[i] } +func (l specList) at(i int) ast.Node { return l[i] } +func (l fieldList) at(i int) ast.Node { return l[i] } + +func (l exprList) slice(i, j int) nodeList { return l[i:j] } +func (l identList) slice(i, j int) nodeList { return l[i:j] } +func (l stmtList) slice(i, j int) nodeList { return l[i:j] } +func (l specList) slice(i, j int) nodeList { return l[i:j] } +func (l fieldList) slice(i, j int) nodeList { return l[i:j] } + +func (l exprList) Pos() token.Pos { return l[0].Pos() } +func (l identList) Pos() token.Pos { return l[0].Pos() } +func (l stmtList) Pos() token.Pos { return l[0].Pos() } +func (l specList) Pos() token.Pos { return l[0].Pos() } +func (l fieldList) Pos() token.Pos { return l[0].Pos() } + +func (l exprList) End() token.Pos { return l[len(l)-1].End() } +func (l identList) End() token.Pos { return l[len(l)-1].End() } +func (l stmtList) End() token.Pos { return l[len(l)-1].End() } +func (l specList) End() token.Pos { return l[len(l)-1].End() } +func (l fieldList) End() token.Pos { return l[len(l)-1].End() } diff --git a/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/parse.go b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/parse.go new file mode 100644 index 00000000000..b46e6439338 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/parse.go @@ -0,0 +1,452 @@ +// Copyright (c) 2017, Daniel Martí +// See LICENSE for licensing information + +package gogrep + +import ( + "bytes" + "fmt" + "go/ast" + "go/parser" + "go/scanner" + "go/token" + "regexp" + "strconv" + "strings" + "text/template" +) + +func (m *matcher) transformSource(expr string) (string, []posOffset, error) { + toks, err := m.tokenize([]byte(expr)) + if err != nil { + return "", nil, fmt.Errorf("cannot tokenize expr: %v", err) + } + var offs []posOffset + lbuf := lineColBuffer{line: 1, col: 1} + addOffset := func(length int) { + lbuf.offs -= length + offs = append(offs, posOffset{ + atLine: lbuf.line, + atCol: lbuf.col, + offset: length, + }) + } + if len(toks) > 0 && toks[0].tok == tokAggressive { + toks = toks[1:] + m.aggressive = true + } + lastLit := false + for _, t := range toks { + if lbuf.offs >= t.pos.Offset && lastLit && t.lit != "" { + lbuf.WriteString(" ") + } + for lbuf.offs < t.pos.Offset { + lbuf.WriteString(" ") + } + if t.lit == "" { + lbuf.WriteString(t.tok.String()) + lastLit = false + continue + } + if isWildName(t.lit) { + // to correct the position offsets for the extra + // info attached to ident name strings + addOffset(len(wildPrefix) - 1) + } + lbuf.WriteString(t.lit) + lastLit = strings.TrimSpace(t.lit) != "" + } + // trailing newlines can cause issues with commas + return strings.TrimSpace(lbuf.String()), offs, nil +} + +func (m *matcher) parseExpr(expr string) (ast.Node, error) { + exprStr, offs, err := m.transformSource(expr) + if err != nil { + return nil, err + } + node, _, err := parseDetectingNode(m.fset, exprStr) + if err != nil { + err = subPosOffsets(err, offs...) + return nil, fmt.Errorf("cannot parse expr: %v", err) + } + return node, nil +} + +type lineColBuffer struct { + bytes.Buffer + line, col, offs int +} + +func (l *lineColBuffer) WriteString(s string) (n int, err error) { + for _, r := range s { + if r == '\n' { + l.line++ + l.col = 1 + } else { + l.col++ + } + l.offs++ + } + return l.Buffer.WriteString(s) +} + +var tmplDecl = template.Must(template.New("").Parse(`` + + `package p; {{ . }}`)) + +var tmplExprs = template.Must(template.New("").Parse(`` + + `package p; var _ = []interface{}{ {{ . }}, }`)) + +var tmplStmts = template.Must(template.New("").Parse(`` + + `package p; func _() { {{ . }} }`)) + +var tmplType = template.Must(template.New("").Parse(`` + + `package p; var _ {{ . }}`)) + +var tmplValSpec = template.Must(template.New("").Parse(`` + + `package p; var {{ . }}`)) + +func execTmpl(tmpl *template.Template, src string) string { + var buf bytes.Buffer + if err := tmpl.Execute(&buf, src); err != nil { + panic(err) + } + return buf.String() +} + +func noBadNodes(node ast.Node) bool { + any := false + ast.Inspect(node, func(n ast.Node) bool { + if any { + return false + } + switch n.(type) { + case *ast.BadExpr, *ast.BadDecl: + any = true + } + return true + }) + return !any +} + +func parseType(fset *token.FileSet, src string) (ast.Expr, *ast.File, error) { + asType := execTmpl(tmplType, src) + f, err := parser.ParseFile(fset, "", asType, 0) + if err != nil { + err = subPosOffsets(err, posOffset{1, 1, 17}) + return nil, nil, err + } + vs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec) + return vs.Type, f, nil +} + +// parseDetectingNode tries its best to parse the ast.Node contained in src, as +// one of: *ast.File, ast.Decl, ast.Expr, ast.Stmt, *ast.ValueSpec. +// It also returns the *ast.File used for the parsing, so that the returned node +// can be easily type-checked. +func parseDetectingNode(fset *token.FileSet, src string) (ast.Node, *ast.File, error) { + file := fset.AddFile("", fset.Base(), len(src)) + scan := scanner.Scanner{} + scan.Init(file, []byte(src), nil, 0) + if _, tok, _ := scan.Scan(); tok == token.EOF { + return nil, nil, fmt.Errorf("empty source code") + } + var mainErr error + + // first try as a whole file + if f, err := parser.ParseFile(fset, "", src, 0); err == nil && noBadNodes(f) { + return f, f, nil + } + + // then as a single declaration, or many + asDecl := execTmpl(tmplDecl, src) + if f, err := parser.ParseFile(fset, "", asDecl, 0); err == nil && noBadNodes(f) { + if len(f.Decls) == 1 { + return f.Decls[0], f, nil + } + return f, f, nil + } + + // then as value expressions + asExprs := execTmpl(tmplExprs, src) + if f, err := parser.ParseFile(fset, "", asExprs, 0); err == nil && noBadNodes(f) { + vs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec) + cl := vs.Values[0].(*ast.CompositeLit) + if len(cl.Elts) == 1 { + return cl.Elts[0], f, nil + } + return exprList(cl.Elts), f, nil + } + + // then try as statements + asStmts := execTmpl(tmplStmts, src) + if f, err := parser.ParseFile(fset, "", asStmts, 0); err == nil && noBadNodes(f) { + bl := f.Decls[0].(*ast.FuncDecl).Body + if len(bl.List) == 1 { + return bl.List[0], f, nil + } + return stmtList(bl.List), f, nil + } else { + // Statements is what covers most cases, so it will give + // the best overall error message. Show positions + // relative to where the user's code is put in the + // template. + mainErr = subPosOffsets(err, posOffset{1, 1, 22}) + } + + // type expressions not yet picked up, for e.g. chans and interfaces + if typ, f, err := parseType(fset, src); err == nil && noBadNodes(f) { + return typ, f, nil + } + + // value specs + asValSpec := execTmpl(tmplValSpec, src) + if f, err := parser.ParseFile(fset, "", asValSpec, 0); err == nil && noBadNodes(f) { + vs := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec) + return vs, f, nil + } + return nil, nil, mainErr +} + +type posOffset struct { + atLine, atCol int + offset int +} + +func subPosOffsets(err error, offs ...posOffset) error { + list, ok := err.(scanner.ErrorList) + if !ok { + return err + } + for i, err := range list { + for _, off := range offs { + if err.Pos.Line != off.atLine { + continue + } + if err.Pos.Column < off.atCol { + continue + } + err.Pos.Column -= off.offset + } + list[i] = err + } + return list +} + +const ( + _ token.Token = -iota + tokAggressive +) + +type fullToken struct { + pos token.Position + tok token.Token + lit string +} + +type caseStatus uint + +const ( + caseNone caseStatus = iota + caseNeedBlock + caseHere +) + +func (m *matcher) tokenize(src []byte) ([]fullToken, error) { + var s scanner.Scanner + fset := token.NewFileSet() + file := fset.AddFile("", fset.Base(), len(src)) + + var err error + onError := func(pos token.Position, msg string) { + switch msg { // allow certain extra chars + case `illegal character U+0024 '$'`: + case `illegal character U+007E '~'`: + default: + err = fmt.Errorf("%v: %s", pos, msg) + } + } + + // we will modify the input source under the scanner's nose to + // enable some features such as regexes. + s.Init(file, src, onError, scanner.ScanComments) + + next := func() fullToken { + pos, tok, lit := s.Scan() + return fullToken{fset.Position(pos), tok, lit} + } + + caseStat := caseNone + + var toks []fullToken + for t := next(); t.tok != token.EOF; t = next() { + switch t.lit { + case "$": // continues below + case "~": + toks = append(toks, fullToken{t.pos, tokAggressive, ""}) + continue + case "switch", "select", "case": + if t.lit == "case" { + caseStat = caseNone + } else { + caseStat = caseNeedBlock + } + fallthrough + default: // regular Go code + if t.tok == token.LBRACE && caseStat == caseNeedBlock { + caseStat = caseHere + } + toks = append(toks, t) + continue + } + wt, err := m.wildcard(t.pos, next) + if err != nil { + return nil, err + } + if caseStat == caseHere { + toks = append(toks, fullToken{wt.pos, token.IDENT, "case"}) + } + toks = append(toks, wt) + if caseStat == caseHere { + toks = append(toks, fullToken{wt.pos, token.COLON, ""}) + toks = append(toks, fullToken{wt.pos, token.IDENT, "gogrep_body"}) + } + } + return toks, err +} + +func (m *matcher) wildcard(pos token.Position, next func() fullToken) (fullToken, error) { + wt := fullToken{pos, token.IDENT, wildPrefix} + t := next() + var info varInfo + if t.tok == token.MUL { + t = next() + info.any = true + } + if t.tok != token.IDENT { + return wt, fmt.Errorf("%v: $ must be followed by ident, got %v", + t.pos, t.tok) + } + id := len(m.vars) + wt.lit += strconv.Itoa(id) + info.name = t.lit + m.vars = append(m.vars, info) + return wt, nil +} + +type typeCheck struct { + op string // "type", "asgn", "conv" + expr ast.Expr +} + +type attribute interface{} + +type typProperty string + +type typUnderlying string + +func (m *matcher) parseAttrs(src string) (attribute, error) { + toks, err := m.tokenize([]byte(src)) + if err != nil { + return nil, err + } + i := -1 + var t fullToken + next := func() fullToken { + if i++; i < len(toks) { + return toks[i] + } + return fullToken{tok: token.EOF, pos: t.pos} + } + t = next() + op := t.lit + switch op { // the ones that don't take args + case "comp", "addr": + if t = next(); t.tok != token.SEMICOLON { + return nil, fmt.Errorf("%v: wanted EOF, got %v", t.pos, t.tok) + } + return typProperty(op), nil + } + opPos := t.pos + if t = next(); t.tok != token.LPAREN { + return nil, fmt.Errorf("%v: wanted (", t.pos) + } + var attr attribute + switch op { + case "rx": + t = next() + rxStr, err := strconv.Unquote(t.lit) + if err != nil { + return nil, fmt.Errorf("%v: %v", t.pos, err) + } + if !strings.HasPrefix(rxStr, "^") { + rxStr = "^" + rxStr + } + if !strings.HasSuffix(rxStr, "$") { + rxStr = rxStr + "$" + } + rx, err := regexp.Compile(rxStr) + if err != nil { + return nil, fmt.Errorf("%v: %v", t.pos, err) + } + attr = rx + case "type", "asgn", "conv": + t = next() + start := t.pos.Offset + for open := 1; open > 0; t = next() { + switch t.tok { + case token.LPAREN: + open++ + case token.RPAREN: + open-- + case token.EOF: + return nil, fmt.Errorf("%v: expected ) to close (", t.pos) + } + } + end := t.pos.Offset - 1 + typeStr := strings.TrimSpace(string(src[start:end])) + fset := token.NewFileSet() + typeExpr, _, err := parseType(fset, typeStr) + if err != nil { + return nil, err + } + attr = typeCheck{op, typeExpr} + i -= 2 // since we went past RPAREN above + case "is": + switch t = next(); t.lit { + case "basic", "array", "slice", "struct", "interface", + "pointer", "func", "map", "chan": + default: + return nil, fmt.Errorf("%v: unknown type: %q", t.pos, + t.lit) + } + attr = typUnderlying(t.lit) + default: + return nil, fmt.Errorf("%v: unknown op %q", opPos, op) + } + if t = next(); t.tok != token.RPAREN { + return nil, fmt.Errorf("%v: wanted ), got %v", t.pos, t.tok) + } + if t = next(); t.tok != token.SEMICOLON { + return nil, fmt.Errorf("%v: wanted EOF, got %v", t.pos, t.tok) + } + return attr, nil +} + +// using a prefix is good enough for now +const wildPrefix = "gogrep_" + +func isWildName(name string) bool { + return strings.HasPrefix(name, wildPrefix) +} + +func fromWildName(s string) int { + if !isWildName(s) { + return -1 + } + n, err := strconv.Atoi(s[len(wildPrefix):]) + if err != nil { + return -1 + } + return n +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/subst.go b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/subst.go new file mode 100644 index 00000000000..8870858ed76 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/subst.go @@ -0,0 +1,261 @@ +// Copyright (c) 2018, Daniel Martí +// See LICENSE for licensing information + +package gogrep + +import ( + "fmt" + "go/ast" + "go/token" + "reflect" +) + +func (m *matcher) cmdSubst(cmd exprCmd, subs []submatch) []submatch { + for i := range subs { + sub := &subs[i] + nodeCopy, _ := m.parseExpr(cmd.src) + // since we'll want to set positions within the file's + // FileSet + scrubPositions(nodeCopy) + + m.fillParents(nodeCopy) + nodeCopy = m.fillValues(nodeCopy, sub.values) + m.substNode(sub.node, nodeCopy) + sub.node = nodeCopy + } + return subs +} + +type topNode struct { + Node ast.Node +} + +func (t topNode) Pos() token.Pos { return t.Node.Pos() } +func (t topNode) End() token.Pos { return t.Node.End() } + +func (m *matcher) fillValues(node ast.Node, values map[string]ast.Node) ast.Node { + // node might not have a parent, in which case we need to set an + // artificial one. Its pointer interface is a copy, so we must also + // return it. + top := &topNode{node} + m.setParentOf(node, top) + + inspect(node, func(node ast.Node) bool { + id := fromWildNode(node) + info := m.info(id) + if info.name == "" { + return true + } + prev := values[info.name] + switch prev.(type) { + case exprList: + node = exprList([]ast.Expr{ + node.(*ast.Ident), + }) + case stmtList: + if ident, ok := node.(*ast.Ident); ok { + node = &ast.ExprStmt{X: ident} + } + node = stmtList([]ast.Stmt{ + node.(*ast.ExprStmt), + }) + } + m.substNode(node, prev) + return true + }) + m.setParentOf(node, nil) + return top.Node +} + +func (m *matcher) substNode(oldNode, newNode ast.Node) { + parent := m.parentOf(oldNode) + m.setParentOf(newNode, parent) + + ptr := m.nodePtr(oldNode) + switch x := ptr.(type) { + case **ast.Ident: + *x = newNode.(*ast.Ident) + case *ast.Node: + *x = newNode + case *ast.Expr: + *x = newNode.(ast.Expr) + case *ast.Stmt: + switch y := newNode.(type) { + case ast.Expr: + stmt := &ast.ExprStmt{X: y} + m.setParentOf(stmt, parent) + *x = stmt + case ast.Stmt: + *x = y + default: + panic(fmt.Sprintf("cannot replace stmt with %T", y)) + } + case *[]ast.Expr: + oldList := oldNode.(exprList) + var first, last []ast.Expr + for i, expr := range *x { + if expr == oldList[0] { + first = (*x)[:i] + last = (*x)[i+len(oldList):] + break + } + } + switch y := newNode.(type) { + case ast.Expr: + *x = append(first, y) + case exprList: + *x = append(first, y...) + default: + panic(fmt.Sprintf("cannot replace exprs with %T", y)) + } + *x = append(*x, last...) + case *[]ast.Stmt: + oldList := oldNode.(stmtList) + var first, last []ast.Stmt + for i, stmt := range *x { + if stmt == oldList[0] { + first = (*x)[:i] + last = (*x)[i+len(oldList):] + break + } + } + switch y := newNode.(type) { + case ast.Expr: + stmt := &ast.ExprStmt{X: y} + m.setParentOf(stmt, parent) + *x = append(first, stmt) + case ast.Stmt: + *x = append(first, y) + case stmtList: + *x = append(first, y...) + default: + panic(fmt.Sprintf("cannot replace stmts with %T", y)) + } + *x = append(*x, last...) + case nil: + return + default: + panic(fmt.Sprintf("unsupported substitution: %T", x)) + } + // the new nodes have scrubbed positions, so try our best to use + // sensible ones + fixPositions(parent) +} + +func (m *matcher) parentOf(node ast.Node) ast.Node { + list, ok := node.(nodeList) + if ok { + node = list.at(0) + } + return m.parents[node] +} + +func (m *matcher) setParentOf(node, parent ast.Node) { + list, ok := node.(nodeList) + if ok { + if list.len() == 0 { + return + } + node = list.at(0) + } + m.parents[node] = parent +} + +func (m *matcher) nodePtr(node ast.Node) interface{} { + list, wantSlice := node.(nodeList) + if wantSlice { + node = list.at(0) + } + parent := m.parentOf(node) + if parent == nil { + return nil + } + v := reflect.ValueOf(parent).Elem() + for i := 0; i < v.NumField(); i++ { + fld := v.Field(i) + switch fld.Type().Kind() { + case reflect.Slice: + for i := 0; i < fld.Len(); i++ { + ifld := fld.Index(i) + if ifld.Interface() != node { + continue + } + if wantSlice { + return fld.Addr().Interface() + } + return ifld.Addr().Interface() + } + case reflect.Interface: + if fld.Interface() == node { + return fld.Addr().Interface() + } + } + } + return nil +} + +// nodePosHash is an ast.Node that can always be used as a key in maps, +// even for nodes that are slices like nodeList. +type nodePosHash struct { + pos, end token.Pos +} + +func (n nodePosHash) Pos() token.Pos { return n.pos } +func (n nodePosHash) End() token.Pos { return n.end } + +func posHash(node ast.Node) nodePosHash { + return nodePosHash{pos: node.Pos(), end: node.End()} +} + +var posType = reflect.TypeOf(token.NoPos) + +func scrubPositions(node ast.Node) { + inspect(node, func(node ast.Node) bool { + v := reflect.ValueOf(node) + if v.Kind() != reflect.Ptr { + return true + } + v = v.Elem() + if v.Kind() != reflect.Struct { + return true + } + for i := 0; i < v.NumField(); i++ { + fld := v.Field(i) + if fld.Type() == posType { + fld.SetInt(0) + } + } + return true + }) +} + +// fixPositions tries to fix common syntax errors caused from syntax rewrites. +func fixPositions(node ast.Node) { + if top, ok := node.(*topNode); ok { + node = top.Node + } + // fallback sets pos to the 'to' position if not valid. + fallback := func(pos *token.Pos, to token.Pos) { + if !pos.IsValid() { + *pos = to + } + } + ast.Inspect(node, func(node ast.Node) bool { + // TODO: many more node types + switch x := node.(type) { + case *ast.GoStmt: + fallback(&x.Go, x.Call.Pos()) + case *ast.ReturnStmt: + if len(x.Results) == 0 { + break + } + // Ensure that there's no newline before the returned + // values, as otherwise we have a naked return. See + // https://github.com/golang/go/issues/32854. + if pos := x.Results[0].Pos(); pos > x.Return { + x.Return = pos + } + } + return true + }) +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/write.go b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/write.go new file mode 100644 index 00000000000..b4796a8965c --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep/write.go @@ -0,0 +1,63 @@ +// Copyright (c) 2018, Daniel Martí +// See LICENSE for licensing information + +package gogrep + +import ( + "go/ast" + "go/printer" + "os" +) + +func (m *matcher) cmdWrite(cmd exprCmd, subs []submatch) []submatch { + seenRoot := make(map[nodePosHash]bool) + filePaths := make(map[*ast.File]string) + var next []submatch + for _, sub := range subs { + root := m.nodeRoot(sub.node) + hash := posHash(root) + if seenRoot[hash] { + continue // avoid dups + } + seenRoot[hash] = true + file, ok := root.(*ast.File) + if ok { + path := m.fset.Position(file.Package).Filename + if path != "" { + // write to disk + filePaths[file] = path + continue + } + } + // pass it on, to print to stdout + next = append(next, submatch{node: root}) + } + for file, path := range filePaths { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0) + if err != nil { + // TODO: return errors instead + panic(err) + } + if err := printConfig.Fprint(f, m.fset, file); err != nil { + // TODO: return errors instead + panic(err) + } + } + return next +} + +var printConfig = printer.Config{ + Mode: printer.UseSpaces | printer.TabIndent, + Tabwidth: 8, +} + +func (m *matcher) nodeRoot(node ast.Node) ast.Node { + parent := m.parentOf(node) + if parent == nil { + return node + } + if _, ok := parent.(nodeList); ok { + return parent + } + return m.nodeRoot(parent) +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/ruleguard/bool3.go b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/bool3.go new file mode 100644 index 00000000000..6e9550c1a19 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/bool3.go @@ -0,0 +1,9 @@ +package ruleguard + +type bool3 int + +const ( + bool3unset bool3 = iota + bool3false + bool3true +) diff --git a/vendor/github.com/quasilyte/go-ruleguard/ruleguard/dsl_importer.go b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/dsl_importer.go new file mode 100644 index 00000000000..c566578d371 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/dsl_importer.go @@ -0,0 +1,40 @@ +package ruleguard + +import ( + "go/ast" + "go/importer" + "go/parser" + "go/token" + "go/types" + + "github.com/quasilyte/go-ruleguard/dslgen" +) + +type dslImporter struct { + fallback types.Importer +} + +func newDSLImporter() *dslImporter { + return &dslImporter{fallback: importer.Default()} +} + +func (i *dslImporter) Import(path string) (*types.Package, error) { + switch path { + case "github.com/quasilyte/go-ruleguard/dsl/fluent": + return i.importDSL(path, dslgen.Fluent) + + default: + return i.fallback.Import(path) + } +} + +func (i *dslImporter) importDSL(path string, src []byte) (*types.Package, error) { + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, "dsl.go", src, 0) + if err != nil { + return nil, err + } + var typecheker types.Config + var info types.Info + return typecheker.Check(path, fset, []*ast.File{f}, &info) +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/ruleguard/gorule.go b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/gorule.go new file mode 100644 index 00000000000..6cdaae48d3e --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/gorule.go @@ -0,0 +1,34 @@ +package ruleguard + +import ( + "go/types" + + "github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep" +) + +type scopedGoRuleSet struct { + uncategorized []goRule + categorizedNum int + rulesByCategory [nodeCategoriesCount][]goRule +} + +type goRule struct { + severity string + pat *gogrep.Pattern + msg string + location string + suggestion string + filters map[string]submatchFilter +} + +type submatchFilter struct { + typePred func(typeQuery) bool + pure bool3 + constant bool3 + addressable bool3 +} + +type typeQuery struct { + x types.Type + ctx *Context +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/ruleguard/node_category.go b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/node_category.go new file mode 100644 index 00000000000..859ed39a4f0 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/node_category.go @@ -0,0 +1,159 @@ +package ruleguard + +import ( + "go/ast" +) + +type nodeCategory int + +const ( + nodeUnknown nodeCategory = iota + + nodeArrayType + nodeAssignStmt + nodeBasicLit + nodeBinaryExpr + nodeBlockStmt + nodeBranchStmt + nodeCallExpr + nodeCaseClause + nodeChanType + nodeCommClause + nodeCompositeLit + nodeDeclStmt + nodeDeferStmt + nodeEllipsis + nodeEmptyStmt + nodeExprStmt + nodeForStmt + nodeFuncDecl + nodeFuncLit + nodeFuncType + nodeGenDecl + nodeGoStmt + nodeIdent + nodeIfStmt + nodeImportSpec + nodeIncDecStmt + nodeIndexExpr + nodeInterfaceType + nodeKeyValueExpr + nodeLabeledStmt + nodeMapType + nodeParenExpr + nodeRangeStmt + nodeReturnStmt + nodeSelectStmt + nodeSelectorExpr + nodeSendStmt + nodeSliceExpr + nodeStarExpr + nodeStructType + nodeSwitchStmt + nodeTypeAssertExpr + nodeTypeSpec + nodeTypeSwitchStmt + nodeUnaryExpr + nodeValueSpec + + nodeCategoriesCount +) + +func categorizeNode(n ast.Node) nodeCategory { + switch n.(type) { + case *ast.ArrayType: + return nodeArrayType + case *ast.AssignStmt: + return nodeAssignStmt + case *ast.BasicLit: + return nodeBasicLit + case *ast.BinaryExpr: + return nodeBinaryExpr + case *ast.BlockStmt: + return nodeBlockStmt + case *ast.BranchStmt: + return nodeBranchStmt + case *ast.CallExpr: + return nodeCallExpr + case *ast.CaseClause: + return nodeCaseClause + case *ast.ChanType: + return nodeChanType + case *ast.CommClause: + return nodeCommClause + case *ast.CompositeLit: + return nodeCompositeLit + case *ast.DeclStmt: + return nodeDeclStmt + case *ast.DeferStmt: + return nodeDeferStmt + case *ast.Ellipsis: + return nodeEllipsis + case *ast.EmptyStmt: + return nodeEmptyStmt + case *ast.ExprStmt: + return nodeExprStmt + case *ast.ForStmt: + return nodeForStmt + case *ast.FuncDecl: + return nodeFuncDecl + case *ast.FuncLit: + return nodeFuncLit + case *ast.FuncType: + return nodeFuncType + case *ast.GenDecl: + return nodeGenDecl + case *ast.GoStmt: + return nodeGoStmt + case *ast.Ident: + return nodeIdent + case *ast.IfStmt: + return nodeIfStmt + case *ast.ImportSpec: + return nodeImportSpec + case *ast.IncDecStmt: + return nodeIncDecStmt + case *ast.IndexExpr: + return nodeIndexExpr + case *ast.InterfaceType: + return nodeInterfaceType + case *ast.KeyValueExpr: + return nodeKeyValueExpr + case *ast.LabeledStmt: + return nodeLabeledStmt + case *ast.MapType: + return nodeMapType + case *ast.ParenExpr: + return nodeParenExpr + case *ast.RangeStmt: + return nodeRangeStmt + case *ast.ReturnStmt: + return nodeReturnStmt + case *ast.SelectStmt: + return nodeSelectStmt + case *ast.SelectorExpr: + return nodeSelectorExpr + case *ast.SendStmt: + return nodeSendStmt + case *ast.SliceExpr: + return nodeSliceExpr + case *ast.StarExpr: + return nodeStarExpr + case *ast.StructType: + return nodeStructType + case *ast.SwitchStmt: + return nodeSwitchStmt + case *ast.TypeAssertExpr: + return nodeTypeAssertExpr + case *ast.TypeSpec: + return nodeTypeSpec + case *ast.TypeSwitchStmt: + return nodeTypeSwitchStmt + case *ast.UnaryExpr: + return nodeUnaryExpr + case *ast.ValueSpec: + return nodeValueSpec + default: + return nodeUnknown + } +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/ruleguard/parser.go b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/parser.go new file mode 100644 index 00000000000..f5b93679fd3 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/parser.go @@ -0,0 +1,634 @@ +package ruleguard + +import ( + "fmt" + "go/ast" + "go/constant" + "go/importer" + "go/parser" + "go/token" + "go/types" + "io" + "path" + "strconv" + + "github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep" + "github.com/quasilyte/go-ruleguard/ruleguard/typematch" +) + +type rulesParser struct { + fset *token.FileSet + res *GoRuleSet + types *types.Info + + itab *typematch.ImportsTab + dslImporter types.Importer + stdImporter types.Importer // TODO(quasilyte): share importer with gogrep? + srcImporter types.Importer +} + +func newRulesParser() *rulesParser { + var stdlib = map[string]string{ + "adler32": "hash/adler32", + "aes": "crypto/aes", + "ascii85": "encoding/ascii85", + "asn1": "encoding/asn1", + "ast": "go/ast", + "atomic": "sync/atomic", + "base32": "encoding/base32", + "base64": "encoding/base64", + "big": "math/big", + "binary": "encoding/binary", + "bits": "math/bits", + "bufio": "bufio", + "build": "go/build", + "bytes": "bytes", + "bzip2": "compress/bzip2", + "cgi": "net/http/cgi", + "cgo": "runtime/cgo", + "cipher": "crypto/cipher", + "cmplx": "math/cmplx", + "color": "image/color", + "constant": "go/constant", + "context": "context", + "cookiejar": "net/http/cookiejar", + "crc32": "hash/crc32", + "crc64": "hash/crc64", + "crypto": "crypto", + "csv": "encoding/csv", + "debug": "runtime/debug", + "des": "crypto/des", + "doc": "go/doc", + "draw": "image/draw", + "driver": "database/sql/driver", + "dsa": "crypto/dsa", + "dwarf": "debug/dwarf", + "ecdsa": "crypto/ecdsa", + "ed25519": "crypto/ed25519", + "elf": "debug/elf", + "elliptic": "crypto/elliptic", + "encoding": "encoding", + "errors": "errors", + "exec": "os/exec", + "expvar": "expvar", + "fcgi": "net/http/fcgi", + "filepath": "path/filepath", + "flag": "flag", + "flate": "compress/flate", + "fmt": "fmt", + "fnv": "hash/fnv", + "format": "go/format", + "gif": "image/gif", + "gob": "encoding/gob", + "gosym": "debug/gosym", + "gzip": "compress/gzip", + "hash": "hash", + "heap": "container/heap", + "hex": "encoding/hex", + "hmac": "crypto/hmac", + "html": "html", + "http": "net/http", + "httptest": "net/http/httptest", + "httptrace": "net/http/httptrace", + "httputil": "net/http/httputil", + "image": "image", + "importer": "go/importer", + "io": "io", + "iotest": "testing/iotest", + "ioutil": "io/ioutil", + "jpeg": "image/jpeg", + "json": "encoding/json", + "jsonrpc": "net/rpc/jsonrpc", + "list": "container/list", + "log": "log", + "lzw": "compress/lzw", + "macho": "debug/macho", + "mail": "net/mail", + "math": "math", + "md5": "crypto/md5", + "mime": "mime", + "multipart": "mime/multipart", + "net": "net", + "os": "os", + "palette": "image/color/palette", + "parse": "text/template/parse", + "parser": "go/parser", + "path": "path", + "pe": "debug/pe", + "pem": "encoding/pem", + "pkix": "crypto/x509/pkix", + "plan9obj": "debug/plan9obj", + "plugin": "plugin", + "png": "image/png", + "pprof": "runtime/pprof", + "printer": "go/printer", + "quick": "testing/quick", + "quotedprintable": "mime/quotedprintable", + "race": "runtime/race", + "rand": "math/rand", + "rc4": "crypto/rc4", + "reflect": "reflect", + "regexp": "regexp", + "ring": "container/ring", + "rpc": "net/rpc", + "rsa": "crypto/rsa", + "runtime": "runtime", + "scanner": "text/scanner", + "sha1": "crypto/sha1", + "sha256": "crypto/sha256", + "sha512": "crypto/sha512", + "signal": "os/signal", + "smtp": "net/smtp", + "sort": "sort", + "sql": "database/sql", + "strconv": "strconv", + "strings": "strings", + "subtle": "crypto/subtle", + "suffixarray": "index/suffixarray", + "sync": "sync", + "syntax": "regexp/syntax", + "syscall": "syscall", + "syslog": "log/syslog", + "tabwriter": "text/tabwriter", + "tar": "archive/tar", + "template": "text/template", + "testing": "testing", + "textproto": "net/textproto", + "time": "time", + "tls": "crypto/tls", + "token": "go/token", + "trace": "runtime/trace", + "types": "go/types", + "unicode": "unicode", + "unsafe": "unsafe", + "url": "net/url", + "user": "os/user", + "utf16": "unicode/utf16", + "utf8": "unicode/utf8", + "x509": "crypto/x509", + "xml": "encoding/xml", + "zip": "archive/zip", + "zlib": "compress/zlib", + } + + // TODO(quasilyte): do we need to pass the fileset here? + fset := token.NewFileSet() + return &rulesParser{ + itab: typematch.NewImportsTab(stdlib), + stdImporter: importer.Default(), + srcImporter: importer.ForCompiler(fset, "source", nil), + dslImporter: newDSLImporter(), + } +} + +func (p *rulesParser) ParseFile(filename string, fset *token.FileSet, r io.Reader) (*GoRuleSet, error) { + p.fset = fset + p.res = &GoRuleSet{ + local: &scopedGoRuleSet{}, + universal: &scopedGoRuleSet{}, + } + + parserFlags := parser.Mode(0) + f, err := parser.ParseFile(fset, filename, r, parserFlags) + if err != nil { + return nil, fmt.Errorf("parser error: %v", err) + } + + if f.Name.Name != "gorules" { + return nil, fmt.Errorf("expected a gorules package name, found %s", f.Name.Name) + } + + typechecker := types.Config{Importer: p.dslImporter} + p.types = &types.Info{Types: map[ast.Expr]types.TypeAndValue{}} + _, err = typechecker.Check("gorules", fset, []*ast.File{f}, p.types) + if err != nil { + return nil, fmt.Errorf("typechecker error: %v", err) + } + + for _, decl := range f.Decls { + decl, ok := decl.(*ast.FuncDecl) + if !ok { + continue + } + if err := p.parseRuleGroup(decl); err != nil { + return nil, err + } + } + + return p.res, nil +} + +func (p *rulesParser) parseRuleGroup(f *ast.FuncDecl) error { + if f.Body == nil { + return p.errorf(f, "unexpected empty function body") + } + if f.Type.Results != nil { + return p.errorf(f.Type.Results, "rule group function should not return anything") + } + params := f.Type.Params.List + if len(params) != 1 || len(params[0].Names) != 1 { + return p.errorf(f.Type.Params, "rule group function should accept exactly 1 Matcher param") + } + // TODO(quasilyte): do an actual matcher param type check? + matcher := params[0].Names[0].Name + + p.itab.EnterScope() + defer p.itab.LeaveScope() + + for _, stmt := range f.Body.List { + if _, ok := stmt.(*ast.DeclStmt); ok { + continue + } + stmtExpr, ok := stmt.(*ast.ExprStmt) + if !ok { + return p.errorf(stmt, "expected a %s method call, found %s", matcher, sprintNode(p.fset, stmt)) + } + call, ok := stmtExpr.X.(*ast.CallExpr) + if !ok { + return p.errorf(stmt, "expected a %s method call, found %s", matcher, sprintNode(p.fset, stmt)) + } + if err := p.parseCall(matcher, call); err != nil { + return err + } + + } + + return nil +} + +func (p *rulesParser) parseCall(matcher string, call *ast.CallExpr) error { + f := call.Fun.(*ast.SelectorExpr) + x, ok := f.X.(*ast.Ident) + if ok && x.Name == matcher { + return p.parseStmt(f.Sel, call.Args) + } + + return p.parseRule(matcher, call) +} + +func (p *rulesParser) parseStmt(fn *ast.Ident, args []ast.Expr) error { + switch fn.Name { + case "Import": + pkgPath, ok := p.toStringValue(args[0]) + if !ok { + return p.errorf(args[0], "expected a string literal argument") + } + pkgName := path.Base(pkgPath) + p.itab.Load(pkgName, pkgPath) + return nil + default: + return p.errorf(fn, "unexpected %s method", fn.Name) + } +} + +func (p *rulesParser) parseRule(matcher string, call *ast.CallExpr) error { + origCall := call + var ( + matchArgs *[]ast.Expr + whereArgs *[]ast.Expr + suggestArgs *[]ast.Expr + reportArgs *[]ast.Expr + atArgs *[]ast.Expr + ) + for { + chain, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + break + } + switch chain.Sel.Name { + case "Match": + matchArgs = &call.Args + case "Where": + whereArgs = &call.Args + case "Suggest": + suggestArgs = &call.Args + case "Report": + reportArgs = &call.Args + case "At": + atArgs = &call.Args + default: + return p.errorf(chain.Sel, "unexpected %s method", chain.Sel.Name) + } + call, ok = chain.X.(*ast.CallExpr) + if !ok { + break + } + } + + dst := p.res.universal + filters := map[string]submatchFilter{} + proto := goRule{ + filters: filters, + } + var alternatives []string + + if matchArgs == nil { + return p.errorf(origCall, "missing Match() call") + } + for _, arg := range *matchArgs { + alt, ok := p.toStringValue(arg) + if !ok { + return p.errorf(arg, "expected a string literal argument") + } + alternatives = append(alternatives, alt) + } + + if whereArgs != nil { + if err := p.walkFilter(filters, (*whereArgs)[0], false); err != nil { + return err + } + } + + if suggestArgs != nil { + s, ok := p.toStringValue((*suggestArgs)[0]) + if !ok { + return p.errorf((*suggestArgs)[0], "expected string literal argument") + } + proto.suggestion = s + } + + if reportArgs == nil { + if suggestArgs == nil { + return p.errorf(origCall, "missing Report() or Suggest() call") + } + proto.msg = "suggestion: " + proto.suggestion + } else { + message, ok := p.toStringValue((*reportArgs)[0]) + if !ok { + return p.errorf((*reportArgs)[0], "expected string literal argument") + } + proto.msg = message + } + + if atArgs != nil { + index, ok := (*atArgs)[0].(*ast.IndexExpr) + if !ok { + return p.errorf((*atArgs)[0], "expected %s[`varname`] expression", matcher) + } + arg, ok := p.toStringValue(index.Index) + if !ok { + return p.errorf(index.Index, "expected a string literal index") + } + proto.location = arg + } + + for i, alt := range alternatives { + rule := proto + pat, err := gogrep.Parse(p.fset, alt) + if err != nil { + return p.errorf((*matchArgs)[i], "gogrep parse: %v", err) + } + rule.pat = pat + cat := categorizeNode(pat.Expr) + if cat == nodeUnknown { + dst.uncategorized = append(dst.uncategorized, rule) + } else { + dst.categorizedNum++ + dst.rulesByCategory[cat] = append(dst.rulesByCategory[cat], rule) + } + } + + return nil +} + +func (p *rulesParser) walkFilter(dst map[string]submatchFilter, e ast.Expr, negate bool) error { + AND := func(x, y func(typeQuery) bool) func(typeQuery) bool { + if x == nil { + return y + } + return func(q typeQuery) bool { + return x(q) && y(q) + } + } + + switch e := e.(type) { + case *ast.UnaryExpr: + if e.Op == token.NOT { + return p.walkFilter(dst, e.X, !negate) + } + case *ast.BinaryExpr: + switch e.Op { + case token.LAND: + err := p.walkFilter(dst, e.X, negate) + if err != nil { + return err + } + return p.walkFilter(dst, e.Y, negate) + case token.GEQ, token.LEQ, token.LSS, token.GTR, token.EQL, token.NEQ: + operand := p.toFilterOperand(e.X) + size := p.types.Types[e.Y].Value + if operand.path == "Type.Size" && size != nil { + filter := dst[operand.varName] + filter.typePred = AND(filter.typePred, func(q typeQuery) bool { + x := constant.MakeInt64(q.ctx.Sizes.Sizeof(q.x)) + return constant.Compare(x, e.Op, size) + }) + dst[operand.varName] = filter + + return nil + } + } + } + + // TODO(quasilyte): refactor and extend. + operand := p.toFilterOperand(e) + args := operand.args + filter := dst[operand.varName] + switch operand.path { + default: + return p.errorf(e, "%s is not a valid filter expression", sprintNode(p.fset, e)) + case "Pure": + if negate { + filter.pure = bool3false + } else { + filter.pure = bool3true + } + dst[operand.varName] = filter + case "Const": + if negate { + filter.constant = bool3false + } else { + filter.constant = bool3true + } + dst[operand.varName] = filter + case "Addressable": + if negate { + filter.addressable = bool3false + } else { + filter.addressable = bool3true + } + dst[operand.varName] = filter + case "Type.Is": + typeString, ok := p.toStringValue(args[0]) + if !ok { + return p.errorf(args[0], "expected a string literal argument") + } + ctx := typematch.Context{Itab: p.itab} + pat, err := typematch.Parse(&ctx, typeString) + if err != nil { + return p.errorf(args[0], "parse type expr: %v", err) + } + wantIdentical := !negate + filter.typePred = AND(filter.typePred, func(q typeQuery) bool { + return wantIdentical == pat.MatchIdentical(q.x) + }) + dst[operand.varName] = filter + case "Type.ConvertibleTo": + typeString, ok := p.toStringValue(args[0]) + if !ok { + return p.errorf(args[0], "expected a string literal argument") + } + y, err := typeFromString(typeString) + if err != nil { + return p.errorf(args[0], "parse type expr: %v", err) + } + if y == nil { + return p.errorf(args[0], "can't convert %s into a type constraint yet", typeString) + } + wantConvertible := !negate + filter.typePred = AND(filter.typePred, func(q typeQuery) bool { + return wantConvertible == types.ConvertibleTo(q.x, y) + }) + dst[operand.varName] = filter + case "Type.AssignableTo": + typeString, ok := p.toStringValue(args[0]) + if !ok { + return p.errorf(args[0], "expected a string literal argument") + } + y, err := typeFromString(typeString) + if err != nil { + return p.errorf(args[0], "parse type expr: %v", err) + } + if y == nil { + return p.errorf(args[0], "can't convert %s into a type constraint yet", typeString) + } + wantAssignable := !negate + filter.typePred = AND(filter.typePred, func(q typeQuery) bool { + return wantAssignable == types.AssignableTo(q.x, y) + }) + dst[operand.varName] = filter + case "Type.Implements": + typeString, ok := p.toStringValue(args[0]) + if !ok { + return p.errorf(args[0], "expected a string literal argument") + } + n, err := parser.ParseExpr(typeString) + if err != nil { + return p.errorf(args[0], "parse type expr: %v", err) + } + e, ok := n.(*ast.SelectorExpr) + if !ok { + return p.errorf(args[0], "only qualified names are supported") + } + pkgName, ok := e.X.(*ast.Ident) + if !ok { + return p.errorf(e.X, "invalid package name") + } + pkgPath, ok := p.itab.Lookup(pkgName.Name) + if !ok { + return p.errorf(e.X, "package %s is not imported", pkgName.Name) + } + pkg, err := p.stdImporter.Import(pkgPath) + if err != nil { + pkg, err = p.srcImporter.Import(pkgPath) + if err != nil { + return p.errorf(e, "can't load %s: %v", pkgPath, err) + } + } + obj := pkg.Scope().Lookup(e.Sel.Name) + if obj == nil { + return p.errorf(e, "%s is not found in %s", e.Sel.Name, pkgPath) + } + iface, ok := obj.Type().Underlying().(*types.Interface) + if !ok { + return p.errorf(e, "%s is not an interface type", e.Sel.Name) + } + wantImplemented := !negate + filter.typePred = AND(filter.typePred, func(q typeQuery) bool { + return wantImplemented == types.Implements(q.x, iface) + }) + dst[operand.varName] = filter + } + + return nil +} + +func (p *rulesParser) toIntValue(x ast.Node) (int64, bool) { + lit, ok := x.(*ast.BasicLit) + if !ok || lit.Kind != token.INT { + return 0, false + } + v, err := strconv.ParseInt(lit.Value, 10, 64) + return v, err == nil +} + +func (p *rulesParser) toStringValue(x ast.Node) (string, bool) { + switch x := x.(type) { + case *ast.BasicLit: + if x.Kind != token.STRING { + return "", false + } + return unquoteNode(x), true + case ast.Expr: + typ, ok := p.types.Types[x] + if !ok || typ.Type.String() != "string" { + return "", false + } + str := typ.Value.ExactString() + str = str[1 : len(str)-1] // remove quotes + return str, true + } + return "", false +} + +func (p *rulesParser) toFilterOperand(e ast.Expr) filterOperand { + var o filterOperand + + if call, ok := e.(*ast.CallExpr); ok { + o.args = call.Args + e = call.Fun + } + var path string + for { + selector, ok := e.(*ast.SelectorExpr) + if !ok { + break + } + if path == "" { + path = selector.Sel.Name + } else { + path = selector.Sel.Name + "." + path + } + e = selector.X + } + indexing, ok := e.(*ast.IndexExpr) + if !ok { + return o + } + mapIdent, ok := indexing.X.(*ast.Ident) + if !ok { + return o + } + indexString, ok := p.toStringValue(indexing.Index) + if !ok { + return o + } + + o.mapName = mapIdent.Name + o.varName = indexString + o.path = path + return o +} + +func (p *rulesParser) errorf(n ast.Node, format string, args ...interface{}) error { + loc := p.fset.Position(n.Pos()) + return fmt.Errorf("%s:%d: %s", + loc.Filename, loc.Line, fmt.Sprintf(format, args...)) +} + +type filterOperand struct { + mapName string + varName string + path string + args []ast.Expr +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ruleguard.go b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ruleguard.go new file mode 100644 index 00000000000..591fc2a5572 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/ruleguard.go @@ -0,0 +1,36 @@ +package ruleguard + +import ( + "go/ast" + "go/token" + "go/types" + "io" +) + +type Context struct { + Types *types.Info + Sizes types.Sizes + Fset *token.FileSet + Report func(n ast.Node, msg string, s *Suggestion) + Pkg *types.Package +} + +type Suggestion struct { + From token.Pos + To token.Pos + Replacement []byte +} + +func ParseRules(filename string, fset *token.FileSet, r io.Reader) (*GoRuleSet, error) { + p := newRulesParser() + return p.ParseFile(filename, fset, r) +} + +func RunRules(ctx *Context, f *ast.File, rules *GoRuleSet) error { + return newRulesRunner(ctx, rules).run(f) +} + +type GoRuleSet struct { + universal *scopedGoRuleSet + local *scopedGoRuleSet +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/ruleguard/runner.go b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/runner.go new file mode 100644 index 00000000000..9610199a2e5 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/runner.go @@ -0,0 +1,183 @@ +package ruleguard + +import ( + "go/ast" + "go/printer" + "io/ioutil" + "strings" + + "github.com/quasilyte/go-ruleguard/internal/mvdan.cc/gogrep" +) + +type rulesRunner struct { + ctx *Context + rules *GoRuleSet + + filename string + src []byte +} + +func newRulesRunner(ctx *Context, rules *GoRuleSet) *rulesRunner { + return &rulesRunner{ + ctx: ctx, + rules: rules, + } +} + +func (rr *rulesRunner) fileBytes() []byte { + if rr.src != nil { + return rr.src + } + + // TODO(quasilyte): re-use src slice? + src, err := ioutil.ReadFile(rr.filename) + if err != nil || src == nil { + // Assign a zero-length slice so rr.src + // is never nil during the second fileBytes call. + rr.src = make([]byte, 0) + } else { + rr.src = src + } + return rr.src +} + +func (rr *rulesRunner) run(f *ast.File) error { + // TODO(quasilyte): run local rules as well. + + rr.filename = rr.ctx.Fset.Position(f.Pos()).Filename + + for _, rule := range rr.rules.universal.uncategorized { + rule.pat.Match(f, func(m gogrep.MatchData) { + rr.handleMatch(rule, m) + }) + } + + if rr.rules.universal.categorizedNum != 0 { + ast.Inspect(f, func(n ast.Node) bool { + cat := categorizeNode(n) + for _, rule := range rr.rules.universal.rulesByCategory[cat] { + matched := false + rule.pat.MatchNode(n, func(m gogrep.MatchData) { + matched = rr.handleMatch(rule, m) + }) + if matched { + break + } + } + return true + }) + } + + return nil +} + +func (rr *rulesRunner) handleMatch(rule goRule, m gogrep.MatchData) bool { + for name, node := range m.Values { + expr, ok := node.(ast.Expr) + if !ok { + continue + } + filter, ok := rule.filters[name] + if !ok { + continue + } + if filter.typePred != nil { + typ := rr.ctx.Types.TypeOf(expr) + q := typeQuery{x: typ, ctx: rr.ctx} + if !filter.typePred(q) { + return false + } + } + switch filter.addressable { + case bool3true: + if !isAddressable(rr.ctx.Types, expr) { + return false + } + case bool3false: + if isAddressable(rr.ctx.Types, expr) { + return false + } + } + switch filter.pure { + case bool3true: + if !isPure(rr.ctx.Types, expr) { + return false + } + case bool3false: + if isPure(rr.ctx.Types, expr) { + return false + } + } + switch filter.constant { + case bool3true: + if !isConstant(rr.ctx.Types, expr) { + return false + } + case bool3false: + if isConstant(rr.ctx.Types, expr) { + return false + } + } + } + + prefix := "" + if rule.severity != "" { + prefix = rule.severity + ": " + } + message := prefix + rr.renderMessage(rule.msg, m.Node, m.Values) + node := m.Node + if rule.location != "" { + node = m.Values[rule.location] + } + var suggestion *Suggestion + if rule.suggestion != "" { + suggestion = &Suggestion{ + Replacement: []byte(rr.renderMessage(rule.suggestion, m.Node, m.Values)), + From: node.Pos(), + To: node.End(), + } + } + rr.ctx.Report(node, message, suggestion) + return true +} + +func (rr *rulesRunner) renderMessage(msg string, n ast.Node, nodes map[string]ast.Node) string { + var buf strings.Builder + if strings.Contains(msg, "$$") { + rr.writeNode(&buf, n) + msg = strings.ReplaceAll(msg, "$$", buf.String()) + } + if len(nodes) == 0 { + return msg + } + for name, n := range nodes { + key := "$" + name + if !strings.Contains(msg, key) { + continue + } + buf.Reset() + rr.writeNode(&buf, n) + // Don't interpolate strings that are too long. + var replacement string + if buf.Len() > 40 { + replacement = key + } else { + replacement = buf.String() + } + msg = strings.ReplaceAll(msg, key, replacement) + } + return msg +} + +func (rr *rulesRunner) writeNode(buf *strings.Builder, n ast.Node) { + from := rr.ctx.Fset.Position(n.Pos()).Offset + to := rr.ctx.Fset.Position(n.End()).Offset + src := rr.fileBytes() + if (from >= 0 && int(from) < len(src)) && (to >= 0 && int(to) < len(src)) { + buf.Write(src[from:to]) + return + } + if err := printer.Fprint(buf, rr.ctx.Fset, n); err != nil { + panic(err) + } +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/ruleguard/typematch/typematch.go b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/typematch/typematch.go new file mode 100644 index 00000000000..e6d85ac5f70 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/typematch/typematch.go @@ -0,0 +1,329 @@ +package typematch + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "go/types" + "strconv" + "strings" +) + +type patternOp int + +const ( + opBuiltinType patternOp = iota + opPointer + opVar + opSlice + opArray + opMap + opChan + opNamed +) + +type Pattern struct { + typeMatches map[string]types.Type + int64Matches map[string]int64 + + root *pattern +} + +type pattern struct { + value interface{} + op patternOp + subs []*pattern +} + +type ImportsTab struct { + imports []map[string]string +} + +func NewImportsTab(initial map[string]string) *ImportsTab { + return &ImportsTab{imports: []map[string]string{initial}} +} + +func (itab *ImportsTab) Lookup(pkgName string) (string, bool) { + for i := len(itab.imports) - 1; i >= 0; i-- { + pkgPath, ok := itab.imports[i][pkgName] + if ok { + return pkgPath, true + } + } + return "", false +} + +func (itab *ImportsTab) Load(pkgName, pkgPath string) { + itab.imports[len(itab.imports)-1][pkgName] = pkgPath +} + +func (itab *ImportsTab) EnterScope() { + itab.imports = append(itab.imports, map[string]string{}) +} + +func (itab *ImportsTab) LeaveScope() { + itab.imports = itab.imports[:len(itab.imports)-1] +} + +type Context struct { + Itab *ImportsTab +} + +func Parse(ctx *Context, s string) (*Pattern, error) { + noDollars := strings.ReplaceAll(s, "$", "__") + n, err := parser.ParseExpr(noDollars) + if err != nil { + return nil, err + } + root := parseExpr(ctx, n) + if root == nil { + return nil, fmt.Errorf("can't convert %s type expression", s) + } + p := &Pattern{ + typeMatches: map[string]types.Type{}, + int64Matches: map[string]int64{}, + root: root, + } + return p, nil +} + +var ( + builtinTypeByName = map[string]types.Type{ + "bool": types.Typ[types.Bool], + "int": types.Typ[types.Int], + "int8": types.Typ[types.Int8], + "int16": types.Typ[types.Int16], + "int32": types.Typ[types.Int32], + "int64": types.Typ[types.Int64], + "uint": types.Typ[types.Uint], + "uint8": types.Typ[types.Uint8], + "uint16": types.Typ[types.Uint16], + "uint32": types.Typ[types.Uint32], + "uint64": types.Typ[types.Uint64], + "uintptr": types.Typ[types.Uintptr], + "float32": types.Typ[types.Float32], + "float64": types.Typ[types.Float64], + "complex64": types.Typ[types.Complex64], + "complex128": types.Typ[types.Complex128], + "string": types.Typ[types.String], + + "error": types.Universe.Lookup("error").Type(), + } + + efaceType = types.NewInterfaceType(nil, nil) +) + +func parseExpr(ctx *Context, e ast.Expr) *pattern { + switch e := e.(type) { + case *ast.Ident: + basic, ok := builtinTypeByName[e.Name] + if ok { + return &pattern{op: opBuiltinType, value: basic} + } + if strings.HasPrefix(e.Name, "__") { + name := strings.TrimPrefix(e.Name, "__") + return &pattern{op: opVar, value: name} + } + + case *ast.SelectorExpr: + pkg, ok := e.X.(*ast.Ident) + if !ok { + return nil + } + pkgPath, ok := ctx.Itab.Lookup(pkg.Name) + if !ok { + return nil + } + return &pattern{op: opNamed, value: [2]string{pkgPath, e.Sel.Name}} + + case *ast.StarExpr: + elem := parseExpr(ctx, e.X) + if elem == nil { + return nil + } + return &pattern{op: opPointer, subs: []*pattern{elem}} + + case *ast.ArrayType: + elem := parseExpr(ctx, e.Elt) + if elem == nil { + return nil + } + if e.Len == nil { + return &pattern{ + op: opSlice, + subs: []*pattern{elem}, + } + } + if id, ok := e.Len.(*ast.Ident); ok && strings.HasPrefix(id.Name, "__") { + name := strings.TrimPrefix(id.Name, "__") + return &pattern{ + op: opArray, + value: name, + subs: []*pattern{elem}, + } + } + lit, ok := e.Len.(*ast.BasicLit) + if !ok || lit.Kind != token.INT { + return nil + } + length, err := strconv.ParseInt(lit.Value, 10, 64) + if err != nil { + return nil + } + return &pattern{ + op: opArray, + value: length, + subs: []*pattern{elem}, + } + + case *ast.MapType: + keyType := parseExpr(ctx, e.Key) + if keyType == nil { + return nil + } + valType := parseExpr(ctx, e.Value) + if valType == nil { + return nil + } + return &pattern{ + op: opMap, + subs: []*pattern{keyType, valType}, + } + + case *ast.ChanType: + valType := parseExpr(ctx, e.Value) + if valType == nil { + return nil + } + var dir types.ChanDir + switch { + case e.Dir&ast.SEND != 0 && e.Dir&ast.RECV != 0: + dir = types.SendRecv + case e.Dir&ast.SEND != 0: + dir = types.SendOnly + case e.Dir&ast.RECV != 0: + dir = types.RecvOnly + default: + return nil + } + return &pattern{ + op: opChan, + value: dir, + subs: []*pattern{valType}, + } + + case *ast.ParenExpr: + return parseExpr(ctx, e.X) + + case *ast.InterfaceType: + if len(e.Methods.List) == 0 { + return &pattern{op: opBuiltinType, value: efaceType} + } + } + + return nil +} + +func (p *Pattern) MatchIdentical(typ types.Type) bool { + p.reset() + return p.matchIdentical(p.root, typ) +} + +func (p *Pattern) reset() { + if len(p.int64Matches) != 0 { + p.int64Matches = map[string]int64{} + } + if len(p.typeMatches) != 0 { + p.typeMatches = map[string]types.Type{} + } +} + +func (p *Pattern) matchIdentical(sub *pattern, typ types.Type) bool { + switch sub.op { + case opVar: + name := sub.value.(string) + if name == "_" { + return true + } + y, ok := p.typeMatches[name] + if !ok { + p.typeMatches[name] = typ + return true + } + if y == nil { + return typ == nil + } + return types.Identical(typ, y) + + case opBuiltinType: + return types.Identical(typ, sub.value.(types.Type)) + + case opPointer: + typ, ok := typ.(*types.Pointer) + if !ok { + return false + } + return p.matchIdentical(sub.subs[0], typ.Elem()) + + case opSlice: + typ, ok := typ.(*types.Slice) + if !ok { + return false + } + return p.matchIdentical(sub.subs[0], typ.Elem()) + + case opArray: + typ, ok := typ.(*types.Array) + if !ok { + return false + } + var wantLen int64 + switch v := sub.value.(type) { + case string: + if v == "_" { + wantLen = typ.Len() + break + } + length, ok := p.int64Matches[v] + if ok { + wantLen = length + } else { + p.int64Matches[v] = typ.Len() + wantLen = typ.Len() + } + case int64: + wantLen = v + } + return wantLen == typ.Len() && p.matchIdentical(sub.subs[0], typ.Elem()) + + case opMap: + typ, ok := typ.(*types.Map) + if !ok { + return false + } + return p.matchIdentical(sub.subs[0], typ.Key()) && + p.matchIdentical(sub.subs[1], typ.Elem()) + + case opChan: + typ, ok := typ.(*types.Chan) + if !ok { + return false + } + dir := sub.value.(types.ChanDir) + return dir == typ.Dir() && p.matchIdentical(sub.subs[0], typ.Elem()) + + case opNamed: + typ, ok := typ.(*types.Named) + if !ok { + return false + } + pkgPath := sub.value.([2]string)[0] + typeName := sub.value.([2]string)[1] + obj := typ.Obj() + return obj.Pkg().Path() == pkgPath && typeName == obj.Name() + + default: + return false + } +} diff --git a/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go new file mode 100644 index 00000000000..c17dc243135 --- /dev/null +++ b/vendor/github.com/quasilyte/go-ruleguard/ruleguard/utils.go @@ -0,0 +1,205 @@ +package ruleguard + +import ( + "go/ast" + "go/parser" + "go/printer" + "go/token" + "go/types" + "strconv" + "strings" +) + +func unquoteNode(lit *ast.BasicLit) string { + return lit.Value[1 : len(lit.Value)-1] +} + +func sprintNode(fset *token.FileSet, n ast.Node) string { + if fset == nil { + fset = token.NewFileSet() + } + var buf strings.Builder + if err := printer.Fprint(&buf, fset, n); err != nil { + return "" + } + return buf.String() +} + +var basicTypeByName = map[string]types.Type{ + "bool": types.Typ[types.Bool], + "int": types.Typ[types.Int], + "int8": types.Typ[types.Int8], + "int16": types.Typ[types.Int16], + "int32": types.Typ[types.Int32], + "int64": types.Typ[types.Int64], + "uint": types.Typ[types.Uint], + "uint8": types.Typ[types.Uint8], + "uint16": types.Typ[types.Uint16], + "uint32": types.Typ[types.Uint32], + "uint64": types.Typ[types.Uint64], + "uintptr": types.Typ[types.Uintptr], + "float32": types.Typ[types.Float32], + "float64": types.Typ[types.Float64], + "complex64": types.Typ[types.Complex64], + "complex128": types.Typ[types.Complex128], + "string": types.Typ[types.String], +} + +func typeFromString(s string) (types.Type, error) { + s = strings.ReplaceAll(s, "?", "__any") + + n, err := parser.ParseExpr(s) + if err != nil { + return nil, err + } + return typeFromNode(n), nil +} + +func typeFromNode(e ast.Expr) types.Type { + switch e := e.(type) { + case *ast.Ident: + basic, ok := basicTypeByName[e.Name] + if ok { + return basic + } + + case *ast.ArrayType: + elem := typeFromNode(e.Elt) + if elem == nil { + return nil + } + if e.Len == nil { + return types.NewSlice(elem) + } + lit, ok := e.Len.(*ast.BasicLit) + if !ok || lit.Kind != token.INT { + return nil + } + length, err := strconv.Atoi(lit.Value) + if err != nil { + return nil + } + types.NewArray(elem, int64(length)) + + case *ast.MapType: + keyType := typeFromNode(e.Key) + if keyType == nil { + return nil + } + valType := typeFromNode(e.Value) + if valType == nil { + return nil + } + return types.NewMap(keyType, valType) + + case *ast.StarExpr: + typ := typeFromNode(e.X) + if typ != nil { + return types.NewPointer(typ) + } + + case *ast.ParenExpr: + return typeFromNode(e.X) + + case *ast.InterfaceType: + if len(e.Methods.List) == 0 { + return types.NewInterfaceType(nil, nil) + } + } + + return nil +} + +// isPure reports whether expr is a softly safe expression and contains +// no significant side-effects. As opposed to strictly safe expressions, +// soft safe expressions permit some forms of side-effects, like +// panic possibility during indexing or nil pointer dereference. +// +// Uses types info to determine type conversion expressions that +// are the only permitted kinds of call expressions. +// Note that is does not check whether called function really +// has any side effects. The analysis is very conservative. +func isPure(info *types.Info, expr ast.Expr) bool { + // This list switch is not comprehensive and uses + // whitelist to be on the conservative side. + // Can be extended as needed. + + switch expr := expr.(type) { + case *ast.StarExpr: + return isPure(info, expr.X) + case *ast.BinaryExpr: + return isPure(info, expr.X) && + isPure(info, expr.Y) + case *ast.UnaryExpr: + return expr.Op != token.ARROW && + isPure(info, expr.X) + case *ast.BasicLit, *ast.Ident: + return true + case *ast.IndexExpr: + return isPure(info, expr.X) && + isPure(info, expr.Index) + case *ast.SelectorExpr: + return isPure(info, expr.X) + case *ast.ParenExpr: + return isPure(info, expr.X) + case *ast.CompositeLit: + return isPureList(info, expr.Elts) + case *ast.CallExpr: + return isTypeExpr(info, expr.Fun) && isPureList(info, expr.Args) + + default: + return false + } +} + +// isPureList reports whether every expr in list is safe. +// +// See isPure. +func isPureList(info *types.Info, list []ast.Expr) bool { + for _, expr := range list { + if !isPure(info, expr) { + return false + } + } + return true +} + +func isAddressable(info *types.Info, expr ast.Expr) bool { + tv, ok := info.Types[expr] + return ok && tv.Addressable() +} + +func isConstant(info *types.Info, expr ast.Expr) bool { + tv, ok := info.Types[expr] + return ok && tv.Value != nil +} + +// isTypeExpr reports whether x represents a type expression. +// +// Type expression does not evaluate to any run time value, +// but rather describes a type that is used inside Go expression. +// +// For example, (*T)(v) is a CallExpr that "calls" (*T). +// (*T) is a type expression that tells Go compiler type v should be converted to. +func isTypeExpr(info *types.Info, x ast.Expr) bool { + switch x := x.(type) { + case *ast.StarExpr: + return isTypeExpr(info, x.X) + case *ast.ParenExpr: + return isTypeExpr(info, x.X) + case *ast.SelectorExpr: + return isTypeExpr(info, x.Sel) + + case *ast.Ident: + // Identifier may be a type expression if object + // it reffers to is a type name. + _, ok := info.ObjectOf(x).(*types.TypeName) + return ok + + case *ast.FuncType, *ast.StructType, *ast.InterfaceType, *ast.ArrayType, *ast.MapType, *ast.ChanType: + return true + + default: + return false + } +} diff --git a/vendor/github.com/quasilyte/regex/syntax/LICENSE b/vendor/github.com/quasilyte/regex/syntax/LICENSE new file mode 100644 index 00000000000..f0c81282b61 --- /dev/null +++ b/vendor/github.com/quasilyte/regex/syntax/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Iskander (Alex) Sharipov / quasilyte + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/quasilyte/regex/syntax/README.md b/vendor/github.com/quasilyte/regex/syntax/README.md new file mode 100644 index 00000000000..13064ec39a9 --- /dev/null +++ b/vendor/github.com/quasilyte/regex/syntax/README.md @@ -0,0 +1,26 @@ +# Package `regex/syntax` + +Package `syntax` provides regular expressions parser as well as AST definitions. + +## Rationale + +There are several problems with the stdlib [regexp/syntax](https://golang.org/pkg/regexp/syntax/) package: + +1. It does several transformations during the parsing that make it + hard to do any kind of syntax analysis afterward. + +2. The AST used there is optimized for the compilation and + execution inside the [regexp](https://golang.org/pkg/regexp) package. + It's somewhat complicated, especially in a way character ranges are encoded. + +3. It only supports [re2](https://github.com/google/re2/wiki/Syntax) syntax. + This parser recognizes most PCRE operations. + +4. It's easier to extend this package than something from the standard library. + +This package does almost no assumptions about how generated AST is going to be used +so it preserves as much syntax information as possible. + +It's easy to write another intermediate representation on top of it. The main +function of this package is to convert a textual regexp pattern into a more +structured form that can be processed more easily. diff --git a/vendor/github.com/quasilyte/regex/syntax/ast.go b/vendor/github.com/quasilyte/regex/syntax/ast.go new file mode 100644 index 00000000000..44b7b61bb33 --- /dev/null +++ b/vendor/github.com/quasilyte/regex/syntax/ast.go @@ -0,0 +1,147 @@ +package syntax + +import ( + "fmt" + "strings" +) + +type Regexp struct { + Pattern string + Expr Expr +} + +type RegexpPCRE struct { + Pattern string + Expr Expr + + Source string + Modifiers string + Delim [2]byte +} + +func (re *RegexpPCRE) HasModifier(mod byte) bool { + return strings.IndexByte(re.Modifiers, mod) >= 0 +} + +type Expr struct { + // The operations that this expression performs. See `operation.go`. + Op Operation + + Form Form + + _ [2]byte // Reserved + + // Pos describes a source location inside regexp pattern. + Pos Position + + // Args is a list of sub-expressions of this expression. + // + // See Operation constants documentation to learn how to + // interpret the particular expression args. + Args []Expr + + // Value holds expression textual value. + // + // Usually, that value is identical to src[Begin():End()], + // but this is not true for programmatically generated objects. + Value string +} + +// Begin returns expression leftmost offset. +func (e Expr) Begin() uint16 { return e.Pos.Begin } + +// End returns expression rightmost offset. +func (e Expr) End() uint16 { return e.Pos.End } + +// LastArg returns expression last argument. +// +// Should not be called on expressions that may have 0 arguments. +func (e Expr) LastArg() Expr { + return e.Args[len(e.Args)-1] +} + +type Operation byte + +type Form byte + +func FormatSyntax(re *Regexp) string { + return formatExprSyntax(re, re.Expr) +} + +func formatExprSyntax(re *Regexp, e Expr) string { + switch e.Op { + case OpChar, OpLiteral: + switch e.Value { + case "{": + return "'{'" + case "}": + return "'}'" + default: + return e.Value + } + case OpString, OpEscapeChar, OpEscapeMeta, OpEscapeOctal, OpEscapeUni, OpEscapeHex, OpPosixClass: + return e.Value + case OpRepeat: + return fmt.Sprintf("(repeat %s %s)", formatExprSyntax(re, e.Args[0]), e.Args[1].Value) + case OpCaret: + return "^" + case OpDollar: + return "$" + case OpDot: + return "." + case OpQuote: + return fmt.Sprintf("(q %s)", e.Value) + case OpCharRange: + return fmt.Sprintf("%s-%s", formatExprSyntax(re, e.Args[0]), formatExprSyntax(re, e.Args[1])) + case OpCharClass: + return fmt.Sprintf("[%s]", formatArgsSyntax(re, e.Args)) + case OpNegCharClass: + return fmt.Sprintf("[^%s]", formatArgsSyntax(re, e.Args)) + case OpConcat: + return fmt.Sprintf("{%s}", formatArgsSyntax(re, e.Args)) + case OpAlt: + return fmt.Sprintf("(or %s)", formatArgsSyntax(re, e.Args)) + case OpCapture: + return fmt.Sprintf("(capture %s)", formatExprSyntax(re, e.Args[0])) + case OpNamedCapture: + return fmt.Sprintf("(capture %s %s)", formatExprSyntax(re, e.Args[0]), e.Args[1].Value) + case OpGroup: + return fmt.Sprintf("(group %s)", formatExprSyntax(re, e.Args[0])) + case OpAtomicGroup: + return fmt.Sprintf("(atomic %s)", formatExprSyntax(re, e.Args[0])) + case OpGroupWithFlags: + return fmt.Sprintf("(group %s ?%s)", formatExprSyntax(re, e.Args[0]), e.Args[1].Value) + case OpFlagOnlyGroup: + return fmt.Sprintf("(flags ?%s)", formatExprSyntax(re, e.Args[0])) + case OpPositiveLookahead: + return fmt.Sprintf("(?= %s)", formatExprSyntax(re, e.Args[0])) + case OpNegativeLookahead: + return fmt.Sprintf("(?! %s)", formatExprSyntax(re, e.Args[0])) + case OpPositiveLookbehind: + return fmt.Sprintf("(?<= %s)", formatExprSyntax(re, e.Args[0])) + case OpNegativeLookbehind: + return fmt.Sprintf("(?", e.Op) + } +} + +func formatArgsSyntax(re *Regexp, args []Expr) string { + parts := make([]string, len(args)) + for i, e := range args { + parts[i] = formatExprSyntax(re, e) + } + return strings.Join(parts, " ") +} diff --git a/vendor/github.com/quasilyte/regex/syntax/errors.go b/vendor/github.com/quasilyte/regex/syntax/errors.go new file mode 100644 index 00000000000..cfafc1d0e87 --- /dev/null +++ b/vendor/github.com/quasilyte/regex/syntax/errors.go @@ -0,0 +1,27 @@ +package syntax + +import ( + "fmt" +) + +type ParseError struct { + Pos Position + Message string +} + +func (e ParseError) Error() string { return e.Message } + +func throwfPos(pos Position, format string, args ...interface{}) { + panic(ParseError{ + Pos: pos, + Message: fmt.Sprintf(format, args...), + }) +} + +func throwErrorf(posBegin, posEnd int, format string, args ...interface{}) { + pos := Position{ + Begin: uint16(posBegin), + End: uint16(posEnd), + } + throwfPos(pos, format, args...) +} diff --git a/vendor/github.com/quasilyte/regex/syntax/go.mod b/vendor/github.com/quasilyte/regex/syntax/go.mod new file mode 100644 index 00000000000..2a4e1f33b55 --- /dev/null +++ b/vendor/github.com/quasilyte/regex/syntax/go.mod @@ -0,0 +1,3 @@ +module github.com/quasilyte/regex/syntax + +go 1.14 diff --git a/vendor/github.com/quasilyte/regex/syntax/lexer.go b/vendor/github.com/quasilyte/regex/syntax/lexer.go new file mode 100644 index 00000000000..e92b038c20e --- /dev/null +++ b/vendor/github.com/quasilyte/regex/syntax/lexer.go @@ -0,0 +1,455 @@ +package syntax + +import ( + "strings" + "unicode" + "unicode/utf8" +) + +type token struct { + kind tokenKind + pos Position +} + +func (tok token) String() string { + return tok.kind.String() +} + +type tokenKind byte + +//go:generate stringer -type=tokenKind -trimprefix=tok -linecomment=true +const ( + tokNone tokenKind = iota + + tokChar + tokGroupFlags + tokPosixClass + tokConcat + tokRepeat + tokEscapeChar + tokEscapeMeta + tokEscapeOctal + tokEscapeUni + tokEscapeUniFull + tokEscapeHex + tokEscapeHexFull + tokComment + + tokQ // \Q + tokMinus // - + tokLbracket // [ + tokLbracketCaret // [^ + tokRbracket // ] + tokDollar // $ + tokCaret // ^ + tokQuestion // ? + tokDot // . + tokPlus // + + tokStar // * + tokPipe // | + tokLparen // ( + tokLparenName // (?P + tokLparenNameAngle // (? + tokLparenNameQuote // (?'name' + tokLparenFlags // (?flags + tokLparenAtomic // (?> + tokLparenPositiveLookahead // (?= + tokLparenPositiveLookbehind // (?<= + tokLparenNegativeLookahead // (?! + tokLparenNegativeLookbehind // (? unicode.MaxASCII { + _, size := utf8.DecodeRuneInString(l.input[l.pos:]) + l.pushTok(tokChar, size) + l.maybeInsertConcat() + continue + } + switch ch { + case '\\': + l.scanEscape(false) + case '.': + l.pushTok(tokDot, 1) + case '+': + l.pushTok(tokPlus, 1) + case '*': + l.pushTok(tokStar, 1) + case '^': + l.pushTok(tokCaret, 1) + case '$': + l.pushTok(tokDollar, 1) + case '?': + l.pushTok(tokQuestion, 1) + case ')': + l.pushTok(tokRparen, 1) + case '|': + l.pushTok(tokPipe, 1) + case '[': + if l.byteAt(l.pos+1) == '^' { + l.pushTok(tokLbracketCaret, 2) + } else { + l.pushTok(tokLbracket, 1) + } + l.scanCharClass() + case '(': + if l.byteAt(l.pos+1) == '?' { + switch { + case l.byteAt(l.pos+2) == '>': + l.pushTok(tokLparenAtomic, len("(?>")) + case l.byteAt(l.pos+2) == '=': + l.pushTok(tokLparenPositiveLookahead, len("(?=")) + case l.byteAt(l.pos+2) == '!': + l.pushTok(tokLparenNegativeLookahead, len("(?!")) + case l.byteAt(l.pos+2) == '<' && l.byteAt(l.pos+3) == '=': + l.pushTok(tokLparenPositiveLookbehind, len("(?<=")) + case l.byteAt(l.pos+2) == '<' && l.byteAt(l.pos+3) == '!': + l.pushTok(tokLparenNegativeLookbehind, len("(?= 0 { + l.pushTok(tokRepeat, len("{")+j) + } else { + l.pushTok(tokChar, 1) + } + default: + l.pushTok(tokChar, 1) + } + l.maybeInsertConcat() + } +} + +func (l *lexer) scanCharClass() { + l.maybeInsertConcat() + + // We need to handle first `]` in a special way. See #3. + if l.byteAt(l.pos) == ']' { + l.pushTok(tokChar, 1) + } + + for l.pos < len(l.input) { + ch := l.input[l.pos] + if ch > unicode.MaxASCII { + _, size := utf8.DecodeRuneInString(l.input[l.pos:]) + l.pushTok(tokChar, size) + continue + } + switch ch { + case '\\': + l.scanEscape(true) + case '[': + isPosixClass := false + if l.byteAt(l.pos+1) == ':' { + j := l.stringIndex(l.pos+2, ":]") + if j >= 0 { + isPosixClass = true + l.pushTok(tokPosixClass, j+len("[::]")) + } + } + if !isPosixClass { + l.pushTok(tokChar, 1) + } + case '-': + l.pushTok(tokMinus, 1) + case ']': + l.pushTok(tokRbracket, 1) + return // Stop scanning in the char context + default: + l.pushTok(tokChar, 1) + } + } +} + +func (l *lexer) scanEscape(insideCharClass bool) { + s := l.input + if l.pos+1 >= len(s) { + throwErrorf(l.pos, l.pos+1, `unexpected end of pattern: trailing '\'`) + } + switch { + case s[l.pos+1] == 'p' || s[l.pos+1] == 'P': + if l.pos+2 >= len(s) { + throwErrorf(l.pos, l.pos+2, "unexpected end of pattern: expected uni-class-short or '{'") + } + if s[l.pos+2] == '{' { + j := strings.IndexByte(s[l.pos+2:], '}') + if j < 0 { + throwErrorf(l.pos, l.pos+2, "can't find closing '}'") + } + l.pushTok(tokEscapeUniFull, len(`\p{`)+j) + } else { + l.pushTok(tokEscapeUni, len(`\pL`)) + } + case s[l.pos+1] == 'x': + if l.pos+2 >= len(s) { + throwErrorf(l.pos, l.pos+2, "unexpected end of pattern: expected hex-digit or '{'") + } + if s[l.pos+2] == '{' { + j := strings.IndexByte(s[l.pos+2:], '}') + if j < 0 { + throwErrorf(l.pos, l.pos+2, "can't find closing '}'") + } + l.pushTok(tokEscapeHexFull, len(`\x{`)+j) + } else { + if isHexDigit(l.byteAt(l.pos + 3)) { + l.pushTok(tokEscapeHex, len(`\xFF`)) + } else { + l.pushTok(tokEscapeHex, len(`\xF`)) + } + } + case isOctalDigit(s[l.pos+1]): + digits := 1 + if isOctalDigit(l.byteAt(l.pos + 2)) { + if isOctalDigit(l.byteAt(l.pos + 3)) { + digits = 3 + } else { + digits = 2 + } + } + l.pushTok(tokEscapeOctal, len(`\`)+digits) + case s[l.pos+1] == 'Q': + size := len(s) - l.pos // Until the pattern ends + j := l.stringIndex(l.pos+2, `\E`) + if j >= 0 { + size = j + len(`\Q\E`) + } + l.pushTok(tokQ, size) + + default: + ch := l.byteAt(l.pos + 1) + if ch > unicode.MaxASCII { + _, size := utf8.DecodeRuneInString(l.input[l.pos+1:]) + l.pushTok(tokEscapeChar, len(`\`)+size) + return + } + kind := tokEscapeChar + if insideCharClass { + if charClassMetachar[ch] { + kind = tokEscapeMeta + } + } else { + if reMetachar[ch] { + kind = tokEscapeMeta + } + } + l.pushTok(kind, 2) + } +} + +func (l *lexer) maybeInsertConcat() { + if l.isConcatPos() { + last := len(l.tokens) - 1 + tok := l.tokens[last] + l.tokens[last].kind = tokConcat + l.tokens = append(l.tokens, tok) + } +} + +func (l *lexer) Init(s string) { + l.pos = 0 + l.tokens = l.tokens[:0] + l.input = s + + l.scan() + + l.pos = 0 +} + +func (l *lexer) tryScanGroupName(pos int) bool { + tok := tokLparenName + endCh := byte('>') + offset := 1 + switch l.byteAt(pos) { + case '\'': + endCh = '\'' + tok = tokLparenNameQuote + case '<': + tok = tokLparenNameAngle + case 'P': + offset = 2 + default: + return false + } + if pos+offset >= len(l.input) { + return false + } + end := strings.IndexByte(l.input[pos+offset:], endCh) + if end < 0 { + return false + } + l.pushTok(tok, len("(?")+offset+end+1) + return true +} + +func (l *lexer) tryScanGroupFlags(pos int) bool { + colonPos := strings.IndexByte(l.input[pos:], ':') + parenPos := strings.IndexByte(l.input[pos:], ')') + if parenPos < 0 { + return false + } + end := parenPos + if colonPos >= 0 && colonPos < parenPos { + end = colonPos + len(":") + } + l.pushTok(tokLparenFlags, len("(?")+end) + return true +} + +func (l *lexer) tryScanComment(pos int) bool { + if l.byteAt(pos) != '#' { + return false + } + parenPos := strings.IndexByte(l.input[pos:], ')') + if parenPos < 0 { + return false + } + l.pushTok(tokComment, len("(?")+parenPos+len(")")) + return true +} + +func (l *lexer) repeatWidth(pos int) int { + j := pos + for isDigit(l.byteAt(j)) { + j++ + } + if j == pos { + return -1 + } + if l.byteAt(j) == '}' { + return (j + len("}")) - pos // {min} + } + if l.byteAt(j) != ',' { + return -1 + } + j += len(",") + for isDigit(l.byteAt(j)) { + j++ + } + if l.byteAt(j) == '}' { + return (j + len("}")) - pos // {min,} or {min,max} + } + return -1 +} + +func (l *lexer) stringIndex(offset int, s string) int { + if offset < len(l.input) { + return strings.Index(l.input[offset:], s) + } + return -1 +} + +func (l *lexer) byteAt(pos int) byte { + if pos >= 0 && pos < len(l.input) { + return l.input[pos] + } + return 0 +} + +func (l *lexer) pushTok(kind tokenKind, size int) { + l.tokens = append(l.tokens, token{ + kind: kind, + pos: Position{Begin: uint16(l.pos), End: uint16(l.pos + size)}, + }) + l.pos += size +} + +func (l *lexer) isConcatPos() bool { + if len(l.tokens) < 2 { + return false + } + x := l.tokens[len(l.tokens)-2].kind + if concatTable[x]&concatX != 0 { + return false + } + y := l.tokens[len(l.tokens)-1].kind + return concatTable[y]&concatY == 0 +} + +const ( + concatX byte = 1 << iota + concatY +) + +var concatTable = [256]byte{ + tokPipe: concatX | concatY, + + tokLparen: concatX, + tokLparenFlags: concatX, + tokLparenName: concatX, + tokLparenNameAngle: concatX, + tokLparenNameQuote: concatX, + tokLparenAtomic: concatX, + tokLbracket: concatX, + tokLbracketCaret: concatX, + tokLparenPositiveLookahead: concatX, + tokLparenPositiveLookbehind: concatX, + tokLparenNegativeLookahead: concatX, + tokLparenNegativeLookbehind: concatX, + + tokRparen: concatY, + tokRbracket: concatY, + tokPlus: concatY, + tokStar: concatY, + tokQuestion: concatY, + tokRepeat: concatY, +} diff --git a/vendor/github.com/quasilyte/regex/syntax/operation.go b/vendor/github.com/quasilyte/regex/syntax/operation.go new file mode 100644 index 00000000000..284e5dc5b49 --- /dev/null +++ b/vendor/github.com/quasilyte/regex/syntax/operation.go @@ -0,0 +1,189 @@ +package syntax + +//go:generate stringer -type=Operation -trimprefix=Op +const ( + OpNone Operation = iota + + // OpConcat is a concatenation of ops. + // Examples: `xy` `abc\d` `` + // Args - concatenated ops + // + // As a special case, OpConcat with 0 Args is used for "empty" + // set of operations. + OpConcat + + // OpDot is a '.' wildcard. + OpDot + + // OpAlt is x|y alternation of ops. + // Examples: `a|bc` `x(.*?)|y(.*?)` + // Args - union-connected regexp branches + OpAlt + + // OpStar is a shorthand for {0,} repetition. + // Examples: `x*` + // Args[0] - repeated expression + OpStar + + // OpPlus is a shorthand for {1,} repetition. + // Examples: `x+` + // Args[0] - repeated expression + OpPlus + + // OpQuestion is a shorthand for {0,1} repetition. + // Examples: `x?` + // Args[0] - repeated expression + OpQuestion + + // OpNonGreedy makes its operand quantifier non-greedy. + // Examples: `x??` `x*?` `x+?` + // Args[0] - quantified expression + OpNonGreedy + + // OpPossessive makes its operand quantifier possessive. + // Examples: `x?+` `x*+` `x++` + // Args[0] - quantified expression + OpPossessive + + // OpCaret is ^ anchor. + OpCaret + + // OpDollar is $ anchor. + OpDollar + + // OpLiteral is a collection of consecutive chars. + // Examples: `ab` `10x` + // Args - enclosed characters (OpChar) + OpLiteral + + // OpChar is a single literal pattern character. + // Examples: `a` `6` `ф` + OpChar + + // OpString is an artificial element that is used in other expressions. + OpString + + // OpQuote is a \Q...\E enclosed literal. + // Examples: `\Q.?\E` `\Q?q[]=1` + // + // Note that closing \E is not mandatory. + OpQuote + + // OpEscapeChar is a single char escape. + // Examples: `\d` `\a` `\n` + OpEscapeChar + + // OpEscapeMeta is an escaped meta char. + // Examples: `\(` `\[` `\+` + OpEscapeMeta + + // OpEscapeOctal is an octal char code escape (up to 3 digits). + // Examples: `\123` `\12` + OpEscapeOctal + + // OpEscapeHex is a hex char code escape. + // Examples: `\x7F` `\xF7` + // FormEscapeHexFull examples: `\x{10FFFF}` `\x{F}`. + OpEscapeHex + + // OpEscapeUni is a Unicode char class escape. + // Examples: `\pS` `\pL` `\PL` + // FormEscapeUniFull examples: `\p{Greek}` `\p{Symbol}` `\p{^L}` + OpEscapeUni + + // OpCharClass is a char class enclosed in []. + // Examples: `[abc]` `[a-z0-9\]]` + // Args - char class elements (can include OpCharRange and OpPosixClass). + OpCharClass + + // OpNegCharClass is a negated char class enclosed in []. + // Examples: `[^abc]` `[^a-z0-9\]]` + // Args - char class elements (can include OpCharRange and OpPosixClass). + OpNegCharClass + + // OpCharRange is an inclusive char range inside a char class. + // Examples: `0-9` `A-Z` + // Args[0] - range lower bound (OpChar or OpEscape). + // Args[1] - range upper bound (OpChar or OpEscape). + OpCharRange + + // OpPosixClass is a named ASCII char set inside a char class. + // Examples: `[:alpha:]` `[:blank:]` + OpPosixClass + + // OpRepeat is a {min,max} repetition quantifier. + // Examples: `x{5}` `x{min,max}` `x{min,}` + // Args[0] - repeated expression + // Args[1] - repeat count (OpString) + OpRepeat + + // OpCapture is `(re)` capturing group. + // Examples: `(abc)` `(x|y)` + // Args[0] - enclosed expression + OpCapture + + // OpNamedCapture is `(?Pre)` capturing group. + // Examples: `(?Pabc)` `(?Px|y)` + // FormNamedCaptureAngle examples: `(?abc)` `(?x|y)` + // FormNamedCaptureQuote examples: `(?'foo'abc)` `(?'name'x|y)` + // Args[0] - enclosed expression (OpConcat with 0 args for empty group) + // Args[1] - group name (OpString) + OpNamedCapture + + // OpGroup is `(?:re)` non-capturing group. + // Examples: `(?:abc)` `(?:x|y)` + // Args[0] - enclosed expression (OpConcat with 0 args for empty group) + OpGroup + + // OpGroupWithFlags is `(?flags:re)` non-capturing group. + // Examples: `(?i:abc)` `(?i:x|y)` + // Args[0] - enclosed expression (OpConcat with 0 args for empty group) + // Args[1] - flags (OpString) + OpGroupWithFlags + + // OpAtomicGroup is `(?>re)` non-capturing group without backtracking. + // Examples: `(?>foo)` `(?>)` + // Args[0] - enclosed expression (OpConcat with 0 args for empty group) + OpAtomicGroup + + // OpPositiveLookahead is `(?=re)` asserts that following text matches re. + // Examples: `(?=foo)` + // Args[0] - enclosed expression (OpConcat with 0 args for empty group) + OpPositiveLookahead + + // OpNegativeLookahead is `(?!re)` asserts that following text doesn't match re. + // Examples: `(?!foo)` + // Args[0] - enclosed expression (OpConcat with 0 args for empty group) + OpNegativeLookahead + + // OpPositiveLookbehind is `(?<=re)` asserts that preceding text matches re. + // Examples: `(?<=foo)` + // Args[0] - enclosed expression (OpConcat with 0 args for empty group) + OpPositiveLookbehind + + // OpNegativeLookbehind is `(?=re)` asserts that preceding text doesn't match re. + // Examples: `(?= Operation(len(_Operation_index)-1) { + return "Operation(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Operation_name[_Operation_index[i]:_Operation_index[i+1]] +} diff --git a/vendor/github.com/quasilyte/regex/syntax/parser.go b/vendor/github.com/quasilyte/regex/syntax/parser.go new file mode 100644 index 00000000000..faf0f8b2120 --- /dev/null +++ b/vendor/github.com/quasilyte/regex/syntax/parser.go @@ -0,0 +1,471 @@ +package syntax + +import ( + "errors" + "fmt" + "strings" +) + +type ParserOptions struct { + // NoLiterals disables OpChar merging into OpLiteral. + NoLiterals bool +} + +func NewParser(opts *ParserOptions) *Parser { + return newParser(opts) +} + +type Parser struct { + out Regexp + lexer lexer + exprPool []Expr + + prefixParselets [256]prefixParselet + infixParselets [256]infixParselet + + charClass []Expr + allocated uint + + opts ParserOptions +} + +// ParsePCRE parses PHP-style pattern with delimiters. +// An example of such pattern is `/foo/i`. +func (p *Parser) ParsePCRE(pattern string) (*RegexpPCRE, error) { + pcre, err := p.newPCRE(pattern) + if err != nil { + return nil, err + } + if pcre.HasModifier('x') { + return nil, errors.New("'x' modifier is not supported") + } + re, err := p.Parse(pcre.Pattern) + if re != nil { + pcre.Expr = re.Expr + } + return pcre, err +} + +func (p *Parser) Parse(pattern string) (result *Regexp, err error) { + defer func() { + r := recover() + if r == nil { + return + } + if err2, ok := r.(ParseError); ok { + err = err2 + return + } + panic(r) + }() + + p.lexer.Init(pattern) + p.allocated = 0 + p.out.Pattern = pattern + if pattern == "" { + p.out.Expr = *p.newExpr(OpConcat, Position{}) + } else { + p.out.Expr = *p.parseExpr(0) + } + + if !p.opts.NoLiterals { + p.mergeChars(&p.out.Expr) + } + p.setValues(&p.out.Expr) + + return &p.out, nil +} + +type prefixParselet func(token) *Expr + +type infixParselet func(*Expr, token) *Expr + +func newParser(opts *ParserOptions) *Parser { + var p Parser + + if opts != nil { + p.opts = *opts + } + p.exprPool = make([]Expr, 256) + + for tok, op := range tok2op { + if op != 0 { + p.prefixParselets[tokenKind(tok)] = p.parsePrefixElementary + } + } + + p.prefixParselets[tokEscapeHexFull] = func(tok token) *Expr { + return p.newExprForm(OpEscapeHex, FormEscapeHexFull, tok.pos) + } + p.prefixParselets[tokEscapeUniFull] = func(tok token) *Expr { + return p.newExprForm(OpEscapeUni, FormEscapeUniFull, tok.pos) + } + + p.prefixParselets[tokLparen] = func(tok token) *Expr { return p.parseGroup(OpCapture, tok) } + p.prefixParselets[tokLparenAtomic] = func(tok token) *Expr { return p.parseGroup(OpAtomicGroup, tok) } + p.prefixParselets[tokLparenPositiveLookahead] = func(tok token) *Expr { return p.parseGroup(OpPositiveLookahead, tok) } + p.prefixParselets[tokLparenNegativeLookahead] = func(tok token) *Expr { return p.parseGroup(OpNegativeLookahead, tok) } + p.prefixParselets[tokLparenPositiveLookbehind] = func(tok token) *Expr { return p.parseGroup(OpPositiveLookbehind, tok) } + p.prefixParselets[tokLparenNegativeLookbehind] = func(tok token) *Expr { return p.parseGroup(OpNegativeLookbehind, tok) } + + p.prefixParselets[tokLparenName] = func(tok token) *Expr { + return p.parseNamedCapture(FormDefault, tok) + } + p.prefixParselets[tokLparenNameAngle] = func(tok token) *Expr { + return p.parseNamedCapture(FormNamedCaptureAngle, tok) + } + p.prefixParselets[tokLparenNameQuote] = func(tok token) *Expr { + return p.parseNamedCapture(FormNamedCaptureQuote, tok) + } + + p.prefixParselets[tokLparenFlags] = p.parseGroupWithFlags + + p.prefixParselets[tokPipe] = func(tok token) *Expr { + // We need prefix pipe parselet to handle `(|x)` syntax. + right := p.parseExpr(1) + return p.newExpr(OpAlt, tok.pos, p.newEmpty(tok.pos), right) + } + p.prefixParselets[tokLbracket] = func(tok token) *Expr { + return p.parseCharClass(OpCharClass, tok) + } + p.prefixParselets[tokLbracketCaret] = func(tok token) *Expr { + return p.parseCharClass(OpNegCharClass, tok) + } + + p.infixParselets[tokRepeat] = func(left *Expr, tok token) *Expr { + repeatLit := p.newExpr(OpString, tok.pos) + return p.newExpr(OpRepeat, combinePos(left.Pos, tok.pos), left, repeatLit) + } + p.infixParselets[tokStar] = func(left *Expr, tok token) *Expr { + return p.newExpr(OpStar, combinePos(left.Pos, tok.pos), left) + } + p.infixParselets[tokConcat] = func(left *Expr, tok token) *Expr { + right := p.parseExpr(2) + if left.Op == OpConcat { + left.Args = append(left.Args, *right) + left.Pos.End = right.End() + return left + } + return p.newExpr(OpConcat, combinePos(left.Pos, right.Pos), left, right) + } + p.infixParselets[tokPipe] = p.parseAlt + p.infixParselets[tokMinus] = p.parseMinus + p.infixParselets[tokPlus] = p.parsePlus + p.infixParselets[tokQuestion] = p.parseQuestion + + return &p +} + +func (p *Parser) setValues(e *Expr) { + for i := range e.Args { + p.setValues(&e.Args[i]) + } + e.Value = p.exprValue(e) +} + +func (p *Parser) exprValue(e *Expr) string { + return p.out.Pattern[e.Begin():e.End()] +} + +func (p *Parser) mergeChars(e *Expr) { + for i := range e.Args { + p.mergeChars(&e.Args[i]) + } + if e.Op != OpConcat || len(e.Args) < 2 { + return + } + + args := e.Args[:0] + i := 0 + for i < len(e.Args) { + first := i + chars := 0 + for j := i; j < len(e.Args) && e.Args[j].Op == OpChar; j++ { + chars++ + } + if chars > 1 { + c1 := e.Args[first] + c2 := e.Args[first+chars-1] + lit := p.newExpr(OpLiteral, combinePos(c1.Pos, c2.Pos)) + for j := 0; j < chars; j++ { + lit.Args = append(lit.Args, e.Args[first+j]) + } + args = append(args, *lit) + i += chars + } else { + args = append(args, e.Args[i]) + i++ + } + } + if len(args) == 1 { + *e = args[0] // Turn OpConcat into OpLiteral + } else { + e.Args = args + } +} + +func (p *Parser) newEmpty(pos Position) *Expr { + return p.newExpr(OpConcat, pos) +} + +func (p *Parser) newExprForm(op Operation, form Form, pos Position, args ...*Expr) *Expr { + e := p.newExpr(op, pos, args...) + e.Form = form + return e +} + +func (p *Parser) newExpr(op Operation, pos Position, args ...*Expr) *Expr { + e := p.allocExpr() + *e = Expr{ + Op: op, + Pos: pos, + Args: e.Args[:0], + } + for _, arg := range args { + e.Args = append(e.Args, *arg) + } + return e +} + +func (p *Parser) allocExpr() *Expr { + i := p.allocated + if i < uint(len(p.exprPool)) { + p.allocated++ + return &p.exprPool[i] + } + return &Expr{} +} + +func (p *Parser) expect(kind tokenKind) Position { + tok := p.lexer.NextToken() + if tok.kind != kind { + throwErrorf(int(tok.pos.Begin), int(tok.pos.End), "expected '%s', found '%s'", kind, tok.kind) + } + return tok.pos +} + +func (p *Parser) parseExpr(precedence int) *Expr { + tok := p.lexer.NextToken() + prefix := p.prefixParselets[tok.kind] + if prefix == nil { + throwfPos(tok.pos, "unexpected token: %v", tok) + } + left := prefix(tok) + + for precedence < p.precedenceOf(p.lexer.Peek()) { + tok := p.lexer.NextToken() + infix := p.infixParselets[tok.kind] + left = infix(left, tok) + } + + return left +} + +func (p *Parser) parsePrefixElementary(tok token) *Expr { + return p.newExpr(tok2op[tok.kind], tok.pos) +} + +func (p *Parser) parseCharClass(op Operation, tok token) *Expr { + var endPos Position + p.charClass = p.charClass[:0] + for { + p.charClass = append(p.charClass, *p.parseExpr(0)) + next := p.lexer.Peek() + if next.kind == tokRbracket { + endPos = next.pos + p.lexer.NextToken() + break + } + if next.kind == tokNone { + throwfPos(tok.pos, "unterminated '['") + } + } + + result := p.newExpr(op, combinePos(tok.pos, endPos)) + result.Args = append(result.Args, p.charClass...) + return result +} + +func (p *Parser) parseMinus(left *Expr, tok token) *Expr { + if p.isValidCharRangeOperand(left) { + if p.lexer.Peek().kind != tokRbracket { + right := p.parseExpr(2) + return p.newExpr(OpCharRange, combinePos(left.Pos, right.Pos), left, right) + } + } + p.charClass = append(p.charClass, *left) + return p.newExpr(OpChar, tok.pos) +} + +func (p *Parser) isValidCharRangeOperand(e *Expr) bool { + switch e.Op { + case OpEscapeHex, OpEscapeOctal, OpEscapeMeta, OpChar: + return true + case OpEscapeChar: + switch p.exprValue(e) { + case `\\`, `\|`, `\*`, `\+`, `\?`, `\.`, `\[`, `\^`, `\$`, `\(`, `\)`: + return true + } + } + return false +} + +func (p *Parser) parsePlus(left *Expr, tok token) *Expr { + op := OpPlus + switch left.Op { + case OpPlus, OpStar, OpQuestion, OpRepeat: + op = OpPossessive + } + return p.newExpr(op, combinePos(left.Pos, tok.pos), left) +} + +func (p *Parser) parseQuestion(left *Expr, tok token) *Expr { + op := OpQuestion + switch left.Op { + case OpPlus, OpStar, OpQuestion, OpRepeat: + op = OpNonGreedy + } + return p.newExpr(op, combinePos(left.Pos, tok.pos), left) +} + +func (p *Parser) parseAlt(left *Expr, tok token) *Expr { + var right *Expr + switch p.lexer.Peek().kind { + case tokRparen, tokNone: + // This is needed to handle `(x|)` syntax. + right = p.newEmpty(tok.pos) + default: + right = p.parseExpr(1) + } + if left.Op == OpAlt { + left.Args = append(left.Args, *right) + left.Pos.End = right.End() + return left + } + return p.newExpr(OpAlt, combinePos(left.Pos, right.Pos), left, right) +} + +func (p *Parser) parseGroupItem(tok token) *Expr { + if p.lexer.Peek().kind == tokRparen { + // This is needed to handle `() syntax.` + return p.newEmpty(tok.pos) + } + return p.parseExpr(0) +} + +func (p *Parser) parseGroup(op Operation, tok token) *Expr { + x := p.parseGroupItem(tok) + result := p.newExpr(op, tok.pos, x) + result.Pos.End = p.expect(tokRparen).End + return result +} + +func (p *Parser) parseNamedCapture(form Form, tok token) *Expr { + prefixLen := len("(?<") + if form == FormDefault { + prefixLen = len("(?P<") + } + name := p.newExpr(OpString, Position{ + Begin: tok.pos.Begin + uint16(prefixLen), + End: tok.pos.End - uint16(len(">")), + }) + x := p.parseGroupItem(tok) + result := p.newExprForm(OpNamedCapture, form, tok.pos, x, name) + result.Pos.End = p.expect(tokRparen).End + return result +} + +func (p *Parser) parseGroupWithFlags(tok token) *Expr { + var result *Expr + val := p.out.Pattern[tok.pos.Begin+1 : tok.pos.End] + switch { + case !strings.HasSuffix(val, ":"): + flags := p.newExpr(OpString, Position{ + Begin: tok.pos.Begin + uint16(len("(?")), + End: tok.pos.End, + }) + result = p.newExpr(OpFlagOnlyGroup, tok.pos, flags) + case val == "?:": + x := p.parseGroupItem(tok) + result = p.newExpr(OpGroup, tok.pos, x) + default: + flags := p.newExpr(OpString, Position{ + Begin: tok.pos.Begin + uint16(len("(?")), + End: tok.pos.End - uint16(len(":")), + }) + x := p.parseGroupItem(tok) + result = p.newExpr(OpGroupWithFlags, tok.pos, x, flags) + } + result.Pos.End = p.expect(tokRparen).End + return result +} + +func (p *Parser) precedenceOf(tok token) int { + switch tok.kind { + case tokPipe: + return 1 + case tokConcat, tokMinus: + return 2 + case tokPlus, tokStar, tokQuestion, tokRepeat: + return 3 + default: + return 0 + } +} + +func (p *Parser) newPCRE(source string) (*RegexpPCRE, error) { + if source == "" { + return nil, errors.New("empty pattern: can't find delimiters") + } + + delim := source[0] + endDelim := delim + switch delim { + case '(': + endDelim = ')' + case '{': + endDelim = '}' + case '[': + endDelim = ']' + case '<': + endDelim = '>' + case '\\': + return nil, errors.New("'\\' is not a valid delimiter") + default: + if isSpace(delim) { + return nil, errors.New("whitespace is not a valid delimiter") + } + if isAlphanumeric(delim) { + return nil, fmt.Errorf("'%c' is not a valid delimiter", delim) + } + } + + j := strings.LastIndexByte(source, endDelim) + if j == -1 { + return nil, fmt.Errorf("can't find '%c' ending delimiter", endDelim) + } + + pcre := &RegexpPCRE{ + Pattern: source[1:j], + Source: source, + Delim: [2]byte{delim, endDelim}, + Modifiers: source[j+1:], + } + return pcre, nil +} + +var tok2op = [256]Operation{ + tokDollar: OpDollar, + tokCaret: OpCaret, + tokDot: OpDot, + tokChar: OpChar, + tokMinus: OpChar, + tokEscapeChar: OpEscapeChar, + tokEscapeMeta: OpEscapeMeta, + tokEscapeHex: OpEscapeHex, + tokEscapeOctal: OpEscapeOctal, + tokEscapeUni: OpEscapeUni, + tokPosixClass: OpPosixClass, + tokQ: OpQuote, + tokComment: OpComment, +} diff --git a/vendor/github.com/quasilyte/regex/syntax/pos.go b/vendor/github.com/quasilyte/regex/syntax/pos.go new file mode 100644 index 00000000000..51bdbf87a5f --- /dev/null +++ b/vendor/github.com/quasilyte/regex/syntax/pos.go @@ -0,0 +1,10 @@ +package syntax + +type Position struct { + Begin uint16 + End uint16 +} + +func combinePos(begin, end Position) Position { + return Position{Begin: begin.Begin, End: end.End} +} diff --git a/vendor/github.com/quasilyte/regex/syntax/tokenkind_string.go b/vendor/github.com/quasilyte/regex/syntax/tokenkind_string.go new file mode 100644 index 00000000000..8800436bcd0 --- /dev/null +++ b/vendor/github.com/quasilyte/regex/syntax/tokenkind_string.go @@ -0,0 +1,59 @@ +// Code generated by "stringer -type=tokenKind -trimprefix=tok -linecomment=true"; DO NOT EDIT. + +package syntax + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[tokNone-0] + _ = x[tokChar-1] + _ = x[tokGroupFlags-2] + _ = x[tokPosixClass-3] + _ = x[tokConcat-4] + _ = x[tokRepeat-5] + _ = x[tokEscapeChar-6] + _ = x[tokEscapeMeta-7] + _ = x[tokEscapeOctal-8] + _ = x[tokEscapeUni-9] + _ = x[tokEscapeUniFull-10] + _ = x[tokEscapeHex-11] + _ = x[tokEscapeHexFull-12] + _ = x[tokComment-13] + _ = x[tokQ-14] + _ = x[tokMinus-15] + _ = x[tokLbracket-16] + _ = x[tokLbracketCaret-17] + _ = x[tokRbracket-18] + _ = x[tokDollar-19] + _ = x[tokCaret-20] + _ = x[tokQuestion-21] + _ = x[tokDot-22] + _ = x[tokPlus-23] + _ = x[tokStar-24] + _ = x[tokPipe-25] + _ = x[tokLparen-26] + _ = x[tokLparenName-27] + _ = x[tokLparenNameAngle-28] + _ = x[tokLparenNameQuote-29] + _ = x[tokLparenFlags-30] + _ = x[tokLparenAtomic-31] + _ = x[tokLparenPositiveLookahead-32] + _ = x[tokLparenPositiveLookbehind-33] + _ = x[tokLparenNegativeLookahead-34] + _ = x[tokLparenNegativeLookbehind-35] + _ = x[tokRparen-36] +} + +const _tokenKind_name = "NoneCharGroupFlagsPosixClassConcatRepeatEscapeCharEscapeMetaEscapeOctalEscapeUniEscapeUniFullEscapeHexEscapeHexFullComment\\Q-[[^]$^?.+*|((?P(?(?'name'(?flags(?>(?=(?<=(?!(?= tokenKind(len(_tokenKind_index)-1) { + return "tokenKind(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _tokenKind_name[_tokenKind_index[i]:_tokenKind_index[i+1]] +} diff --git a/vendor/github.com/quasilyte/regex/syntax/utils.go b/vendor/github.com/quasilyte/regex/syntax/utils.go new file mode 100644 index 00000000000..934680c8ba0 --- /dev/null +++ b/vendor/github.com/quasilyte/regex/syntax/utils.go @@ -0,0 +1,30 @@ +package syntax + +func isSpace(ch byte) bool { + switch ch { + case '\r', '\n', '\t', '\f', '\v': + return true + default: + return false + } +} + +func isAlphanumeric(ch byte) bool { + return (ch >= 'a' && ch <= 'z') || + (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') +} + +func isDigit(ch byte) bool { + return ch >= '0' && ch <= '9' +} + +func isOctalDigit(ch byte) bool { + return ch >= '0' && ch <= '7' +} + +func isHexDigit(ch byte) bool { + return (ch >= '0' && ch <= '9') || + (ch >= 'a' && ch <= 'f') || + (ch >= 'A' && ch <= 'F') +} diff --git a/vendor/github.com/ryancurrah/gomodguard/.gitignore b/vendor/github.com/ryancurrah/gomodguard/.gitignore index 5131b46d6b5..030056d4659 100644 --- a/vendor/github.com/ryancurrah/gomodguard/.gitignore +++ b/vendor/github.com/ryancurrah/gomodguard/.gitignore @@ -19,3 +19,5 @@ *.xml dist/ + +coverage.* \ No newline at end of file diff --git a/vendor/github.com/ryancurrah/gomodguard/.golangci.yml b/vendor/github.com/ryancurrah/gomodguard/.golangci.yml new file mode 100644 index 00000000000..9c19e63a171 --- /dev/null +++ b/vendor/github.com/ryancurrah/gomodguard/.golangci.yml @@ -0,0 +1,6 @@ +linters: + enable-all: true + disable: + - funlen + - gochecknoglobals + - lll diff --git a/vendor/github.com/ryancurrah/gomodguard/.gomodguard.yaml b/vendor/github.com/ryancurrah/gomodguard/.gomodguard.yaml index c0f061f59ff..38a2f0be02a 100644 --- a/vendor/github.com/ryancurrah/gomodguard/.gomodguard.yaml +++ b/vendor/github.com/ryancurrah/gomodguard/.gomodguard.yaml @@ -2,7 +2,7 @@ allowed: modules: # List of allowed modules - gopkg.in/yaml.v2 - github.com/go-xmlfmt/xmlfmt - - github.com/phayes/checkstyle + - github.com/Masterminds/semver domains: # List of allowed module domains - golang.org @@ -15,4 +15,13 @@ blocked: - github.com/mitchellh/go-homedir: recommendations: - github.com/ryancurrah/gomodguard - reason: "testing if the linted module is not blocked when it is recommended" + reason: "testing if the current/linted module is not blocked when it is recommended" + - github.com/phayes/checkstyle: + recommendations: + - github.com/someother/module + reason: "testing if module is blocked with recommendation" + + versions: + - github.com/mitchellh/go-homedir: + version: "<= 1.1.0" + reason: "testing if blocked version constraint works." diff --git a/vendor/github.com/ryancurrah/gomodguard/Makefile b/vendor/github.com/ryancurrah/gomodguard/Makefile index d765f52d5da..9af2f76e4fc 100644 --- a/vendor/github.com/ryancurrah/gomodguard/Makefile +++ b/vendor/github.com/ryancurrah/gomodguard/Makefile @@ -3,7 +3,7 @@ version = $(shell printf '%s' $$(cat VERSION)) .PHONEY: lint lint: - golangci-lint run -v --enable-all --disable funlen,gochecknoglobals,lll ./... + golangci-lint run ./... .PHONEY: build build: @@ -17,6 +17,14 @@ dockerbuild: run: build ./gomodguard +.PHONEY: test +test: + go test -v -coverprofile coverage.out + +.PHONEY: cover +cover: + gocover-cobertura < coverage.out > coverage.xml + .PHONEY: dockerrun dockerrun: dockerbuild docker run -v "${current_dir}/.gomodguard.yaml:/.gomodguard.yaml" ryancurrah/gomodguard:latest @@ -30,8 +38,12 @@ release: .PHONEY: clean clean: rm -rf dist/ - rm -f gomodguard + rm -f gomodguard coverage.xml coverage.out .PHONEY: install-tools-mac install-tools-mac: brew install goreleaser/tap/goreleaser + +.PHONEY: install-go-tools +install-go-tools: + go get github.com/t-yuki/gocover-cobertura diff --git a/vendor/github.com/ryancurrah/gomodguard/README.md b/vendor/github.com/ryancurrah/gomodguard/README.md index 89a2398be03..f09b5e1f47c 100644 --- a/vendor/github.com/ryancurrah/gomodguard/README.md +++ b/vendor/github.com/ryancurrah/gomodguard/README.md @@ -1,4 +1,6 @@ # gomodguard +![Codecov](https://img.shields.io/codecov/c/gh/ryancurrah/gomodguard?style=flat-square) +![GitHub Workflow Status](https://img.shields.io/github/workflow/status/ryancurrah/gomodguard/Go?logo=Go&style=flat-square) @@ -18,6 +20,8 @@ Alternative modules can be optionally recommended in the blocked modules list. If the linted module imports a blocked module but the linted module is in the recommended modules list the blocked module is ignored. Usually, this means the linted module wraps that blocked module for use by other modules, therefore the import of the blocked module should not be blocked. +Version constraints can be specified for modules as well which lets you block new or old versions of modules or specific versions. + Results are printed to `stdout`. Logging statements are printed to `stderr`. @@ -42,6 +46,10 @@ blocked: recommendations: # Recommended modules that should be used instead (Optional) - golang.org/x/mod reason: "`mod` is the official go.mod parser library." # Reason why the recommended module should be used (Optional) + versions: # List of blocked module version constraints. + - github.com/mitchellh/go-homedir: # Blocked module with version constraint. + version: "<= 1.1.0" # Version constraint, see https://github.com/Masterminds/semver#basic-comparisons. + reason: "testing if blocked version constraint works." # Reason why the version constraint exists. ``` ## Usage @@ -52,17 +60,22 @@ Usage: gomodguard [files...] Also supports package syntax but will use it in relative path, i.e. ./pkg/... Flags: -f string - Report results to the specified file. A report type must also be specified + Report results to the specified file. A report type must also be specified -file string - -h Show this help text + -h Show this help text -help - -n Don't lint test files + -i int + Exit code when issues were found (default 2) + -issues-exit-code int + (default 2) + + -n Don't lint test files -no-test -r string - Report results to one of the following formats: checkstyle. A report file destination must also be specified + Report results to one of the following formats: checkstyle. A report file destination must also be specified -report string ``` diff --git a/vendor/github.com/ryancurrah/gomodguard/cmd.go b/vendor/github.com/ryancurrah/gomodguard/cmd.go new file mode 100644 index 00000000000..652e61f8cd6 --- /dev/null +++ b/vendor/github.com/ryancurrah/gomodguard/cmd.go @@ -0,0 +1,239 @@ +package gomodguard + +import ( + "flag" + "fmt" + "io/ioutil" + "log" + "os" + "path/filepath" + "strings" + + "github.com/go-xmlfmt/xmlfmt" + "github.com/mitchellh/go-homedir" + "github.com/phayes/checkstyle" + "gopkg.in/yaml.v2" +) + +const ( + errFindingHomedir = "unable to find home directory, %w" + errReadingConfigFile = "could not read config file: %w" + errParsingConfigFile = "could not parse config file: %w" +) + +var ( + configFile = ".gomodguard.yaml" + logger = log.New(os.Stderr, "", 0) + errFindingConfigFile = fmt.Errorf("could not find config file") +) + +// Run the gomodguard linter. Returns the exit code to use. +func Run() int { + var ( + args []string + help bool + noTest bool + report string + reportFile string + issuesExitCode int + cwd, _ = os.Getwd() + ) + + flag.BoolVar(&help, "h", false, "Show this help text") + flag.BoolVar(&help, "help", false, "") + flag.BoolVar(&noTest, "n", false, "Don't lint test files") + flag.BoolVar(&noTest, "no-test", false, "") + flag.StringVar(&report, "r", "", "Report results to one of the following formats: checkstyle. A report file destination must also be specified") + flag.StringVar(&report, "report", "", "") + flag.StringVar(&reportFile, "f", "", "Report results to the specified file. A report type must also be specified") + flag.StringVar(&reportFile, "file", "", "") + flag.IntVar(&issuesExitCode, "i", 2, "Exit code when issues were found") + flag.IntVar(&issuesExitCode, "issues-exit-code", 2, "") + flag.Parse() + + report = strings.TrimSpace(strings.ToLower(report)) + + if help { + showHelp() + return 0 + } + + if report != "" && report != "checkstyle" { + logger.Fatalf("error: invalid report type '%s'", report) + } + + if report != "" && reportFile == "" { + logger.Fatalf("error: a report file must be specified when a report is enabled") + } + + if report == "" && reportFile != "" { + logger.Fatalf("error: a report type must be specified when a report file is enabled") + } + + args = flag.Args() + if len(args) == 0 { + args = []string{"./..."} + } + + config, err := GetConfig(configFile) + if err != nil { + logger.Fatalf("error: %s", err) + } + + filteredFiles := GetFilteredFiles(cwd, noTest, args) + + processor, err := NewProcessor(*config, logger) + if err != nil { + logger.Fatalf("error: %s", err) + } + + results := processor.ProcessFiles(filteredFiles) + + if report == "checkstyle" { + err := WriteCheckstyle(reportFile, results) + if err != nil { + logger.Fatalf("error: %s", err) + } + } + + for _, r := range results { + fmt.Println(r.String()) + } + + if len(results) > 0 { + return issuesExitCode + } + + return 0 +} + +// GetConfig from YAML file. +func GetConfig(configFile string) (*Configuration, error) { + config := Configuration{} + + home, err := homedir.Dir() + if err != nil { + return nil, fmt.Errorf(errFindingHomedir, err) + } + + cfgFile := "" + homeDirCfgFile := filepath.Join(home, configFile) + + switch { + case fileExists(configFile): + cfgFile = configFile + case fileExists(homeDirCfgFile): + cfgFile = homeDirCfgFile + default: + return nil, fmt.Errorf("%w: %s %s", errFindingConfigFile, configFile, homeDirCfgFile) + } + + data, err := ioutil.ReadFile(cfgFile) + if err != nil { + return nil, fmt.Errorf(errReadingConfigFile, err) + } + + err = yaml.Unmarshal(data, &config) + if err != nil { + return nil, fmt.Errorf(errParsingConfigFile, err) + } + + return &config, nil +} + +// GetFilteredFiles returns files based on search string arguments and filters. +func GetFilteredFiles(cwd string, skipTests bool, args []string) []string { + var ( + foundFiles = []string{} + filteredFiles = []string{} + ) + + for _, f := range args { + if strings.HasSuffix(f, "/...") { + dir, _ := filepath.Split(f) + + foundFiles = append(foundFiles, expandGoWildcard(dir)...) + + continue + } + + if _, err := os.Stat(f); err == nil { + foundFiles = append(foundFiles, f) + } + } + + // Use relative path to print shorter names, sort out test foundFiles if chosen. + for _, f := range foundFiles { + if skipTests { + if strings.HasSuffix(f, "_test.go") { + continue + } + } + + if relativePath, err := filepath.Rel(cwd, f); err == nil { + filteredFiles = append(filteredFiles, relativePath) + + continue + } + + filteredFiles = append(filteredFiles, f) + } + + return filteredFiles +} + +// showHelp text for command line. +func showHelp() { + helpText := `Usage: gomodguard [files...] +Also supports package syntax but will use it in relative path, i.e. ./pkg/... +Flags:` + fmt.Println(helpText) + flag.PrintDefaults() +} + +// WriteCheckstyle takes the results and writes them to a checkstyle formated file. +func WriteCheckstyle(checkstyleFilePath string, results []Result) error { + check := checkstyle.New() + + for i := range results { + file := check.EnsureFile(results[i].FileName) + file.AddError(checkstyle.NewError(results[i].LineNumber, 1, checkstyle.SeverityError, results[i].Reason, "gomodguard")) + } + + checkstyleXML := fmt.Sprintf("\n%s", check.String()) + + err := ioutil.WriteFile(checkstyleFilePath, []byte(xmlfmt.FormatXML(checkstyleXML, "", " ")), 0644) // nolint:gosec + if err != nil { + return err + } + + return nil +} + +// fileExists returns true if the file path provided exists. +func fileExists(filename string) bool { + info, err := os.Stat(filename) + if os.IsNotExist(err) { + return false + } + + return !info.IsDir() +} + +// expandGoWildcard path provided. +func expandGoWildcard(root string) []string { + foundFiles := []string{} + + _ = filepath.Walk(root, func(path string, info os.FileInfo, err error) error { + // Only append go foundFiles. + if !strings.HasSuffix(info.Name(), ".go") { + return nil + } + + foundFiles = append(foundFiles, path) + + return nil + }) + + return foundFiles +} diff --git a/vendor/github.com/ryancurrah/gomodguard/go.mod b/vendor/github.com/ryancurrah/gomodguard/go.mod index 0f0e92e4e1a..15231c986ea 100644 --- a/vendor/github.com/ryancurrah/gomodguard/go.mod +++ b/vendor/github.com/ryancurrah/gomodguard/go.mod @@ -3,9 +3,11 @@ module github.com/ryancurrah/gomodguard go 1.14 require ( + github.com/Masterminds/semver v1.5.0 github.com/go-xmlfmt/xmlfmt v0.0.0-20191208150333-d5b6f63a941b github.com/mitchellh/go-homedir v1.1.0 github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d + github.com/pkg/errors v0.9.1 golang.org/x/mod v0.2.0 gopkg.in/yaml.v2 v2.2.8 ) diff --git a/vendor/github.com/ryancurrah/gomodguard/go.sum b/vendor/github.com/ryancurrah/gomodguard/go.sum index 0f4bf323120..55ae4e5715b 100644 --- a/vendor/github.com/ryancurrah/gomodguard/go.sum +++ b/vendor/github.com/ryancurrah/gomodguard/go.sum @@ -1,9 +1,13 @@ +github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= +github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= github.com/go-xmlfmt/xmlfmt v0.0.0-20191208150333-d5b6f63a941b h1:khEcpUM4yFcxg4/FHQWkvVRmgijNXRfzkIDHh23ggEo= github.com/go-xmlfmt/xmlfmt v0.0.0-20191208150333-d5b6f63a941b/go.mod h1:aUCEOzzezBEjDBbFBoSiya/gduyIiWYRP6CnSFIV8AM= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d h1:CdDQnGF8Nq9ocOS/xlSptM1N3BbrA6/kmaep5ggwaIA= github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d/go.mod h1:3OzsM7FXDQlpCiw2j81fOmAwQLnZnLGXVKUzeKQXIAw= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ= diff --git a/vendor/github.com/ryancurrah/gomodguard/gomodguard.go b/vendor/github.com/ryancurrah/gomodguard/gomodguard.go index cd4f7d66e57..16467734c08 100644 --- a/vendor/github.com/ryancurrah/gomodguard/gomodguard.go +++ b/vendor/github.com/ryancurrah/gomodguard/gomodguard.go @@ -12,25 +12,104 @@ import ( "os/exec" "strings" + "github.com/Masterminds/semver" + "golang.org/x/mod/modfile" ) +const ( + goModFilename = "go.mod" + errReadingGoModFile = "unable to read go mod file %s: %w" + errParsingGoModFile = "unable to parsing go mod file %s: %w" +) + var ( - blockedReasonNotInAllowedList = "import of package `%s` is blocked because the module is not in the allowed modules list." - blockedReasonInBlockedList = "import of package `%s` is blocked because the module is in the blocked modules list." - goModFilename = "go.mod" + blockReasonNotInAllowedList = "import of package `%s` is blocked because the module is not in the allowed modules list." + blockReasonInBlockedList = "import of package `%s` is blocked because the module is in the blocked modules list." ) -// Recommendations are alternative modules to use and a reason why. -type Recommendations struct { - Recommendations []string `yaml:"recommendations"` - Reason string `yaml:"reason"` +// BlockedVersion has a version constraint a reason why the the module version is blocked. +type BlockedVersion struct { + Version string `yaml:"version"` + Reason string `yaml:"reason"` + lintedModuleVersion string `yaml:"-"` +} + +// Set required values for performing checks. This must be ran before running anything else. +func (r *BlockedVersion) Set(lintedModuleVersion string) { + r.lintedModuleVersion = lintedModuleVersion +} + +// IsAllowed returns true if the blocked module is allowed. You must Set() values first. +func (r *BlockedVersion) IsAllowed() bool { + return !r.isLintedModuleVersionBlocked() +} + +// isLintedModuleVersionBlocked returns true if version constraint specified and the +// linted module version meets the constraint. +func (r *BlockedVersion) isLintedModuleVersionBlocked() bool { + if r.Version == "" { + return false + } + + constraint, err := semver.NewConstraint(r.Version) + if err != nil { + return false + } + + version, err := semver.NewVersion(strings.TrimLeft(r.lintedModuleVersion, "v")) + if err != nil { + return false + } + + return constraint.Check(version) +} + +// Message returns the reason why the module version is blocked. +func (r *BlockedVersion) Message() string { + msg := "" + + // Add version contraint to message + msg += fmt.Sprintf("version `%s` is blocked because it does not meet the version constraint `%s`.", r.lintedModuleVersion, r.Version) + + if r.Reason == "" { + return msg + } + + // Add reason to message + msg += fmt.Sprintf(" %s.", strings.TrimRight(r.Reason, ".")) + + return msg +} + +// BlockedModule has alternative modules to use and a reason why the module is blocked. +type BlockedModule struct { + Recommendations []string `yaml:"recommendations"` + Reason string `yaml:"reason"` + currentModuleName string `yaml:"-"` } -// IsRecommended returns true if the package provided is in the Recommendations list -func (r *Recommendations) IsRecommended(pkg string) bool { +// Set required values for performing checks. This must be ran before running anything else. +func (r *BlockedModule) Set(currentModuleName string) { + r.currentModuleName = currentModuleName +} + +// IsAllowed returns true if the blocked module is allowed. You must Set() values first. +func (r *BlockedModule) IsAllowed() bool { + // If the current go.mod file being linted is a recommended module of a + // blocked module and it imports that blocked module, do not set as blocked. + // This could mean that the linted module is a wrapper for that blocked module. + return r.isCurrentModuleARecommendation() +} + +// isCurrentModuleARecommendation returns true if the current module is in the Recommendations list. +func (r *BlockedModule) isCurrentModuleARecommendation() bool { + if r == nil { + return false + } + for n := range r.Recommendations { - if strings.TrimSpace(pkg) == strings.TrimSpace(r.Recommendations[n]) { + if strings.TrimSpace(r.currentModuleName) == strings.TrimSpace(r.Recommendations[n]) { return true } } @@ -38,14 +117,11 @@ func (r *Recommendations) IsRecommended(pkg string) bool { return false } -// String returns the recommended modules and reason message. -func (r *Recommendations) String() string { +// Message returns the reason why the module is blocked and a list of recommended modules if provided. +func (r *BlockedModule) Message() string { msg := "" - if r == nil { - return msg - } - + // Add recommendations to message for i := range r.Recommendations { switch { case len(r.Recommendations) == 1: @@ -59,8 +135,15 @@ func (r *Recommendations) String() string { } } - if r.Reason != "" { - msg += fmt.Sprintf(" %s", r.Reason) + if r.Reason == "" { + return msg + } + + // Add reason to message + if msg == "" { + msg = fmt.Sprintf("%s.", strings.TrimRight(r.Reason, ".")) + } else { + msg += fmt.Sprintf(" %s.", strings.TrimRight(r.Reason, ".")) } return msg @@ -68,25 +151,24 @@ func (r *Recommendations) String() string { // HasRecommendations returns true if the blocked package has // recommended modules. -func (r *Recommendations) HasRecommendations() bool { +func (r *BlockedModule) HasRecommendations() bool { + if r == nil { + return false + } + return len(r.Recommendations) > 0 } -// BlockedModule is a blocked module name and -// optionally a list of recommended modules -// and a reason message. -type BlockedModule map[string]Recommendations +// BlockedVersions a list of blocked modules by a version constraint. +type BlockedVersions []map[string]BlockedVersion -// BlockedModules a list of blocked modules. -type BlockedModules []BlockedModule - -// Get returns the modules that are blocked. -func (b BlockedModules) Get() []string { +// Get returns the module names that are blocked. +func (b BlockedVersions) Get() []string { modules := make([]string, len(b)) - for i := range b { - for module := range b[i] { - modules[i] = module + for n := range b { + for module := range b[n] { + modules[n] = module break } } @@ -94,46 +176,49 @@ func (b BlockedModules) Get() []string { return modules } -// RecommendedModules will return a list of recommended modules for the -// package provided. If there is no recommendation nil will be returned. -func (b BlockedModules) RecommendedModules(pkg string) *Recommendations { - for i := range b { - for blockedModule, recommendations := range b[i] { - if strings.HasPrefix(strings.ToLower(pkg), strings.ToLower(blockedModule)) && recommendations.HasRecommendations() { - return &recommendations +// GetBlockReason returns a block version if one is set for the provided linted module name. +func (b BlockedVersions) GetBlockReason(lintedModuleName, lintedModuleVersion string) *BlockedVersion { + for _, blockedModule := range b { + for blockedModuleName, blockedVersion := range blockedModule { + if strings.EqualFold(strings.TrimSpace(lintedModuleName), strings.TrimSpace(blockedModuleName)) { + blockedVersion.Set(lintedModuleVersion) + return &blockedVersion } - - break } } return nil } -// IsBlockedPackage returns true if the package name is in -// the blocked modules list. -func (b BlockedModules) IsBlockedPackage(pkg string) bool { - blockedModules := b.Get() - for i := range blockedModules { - if strings.HasPrefix(strings.ToLower(pkg), strings.ToLower(blockedModules[i])) { - return true +// BlockedModules a list of blocked modules. +type BlockedModules []map[string]BlockedModule + +// Get returns the module names that are blocked. +func (b BlockedModules) Get() []string { + modules := make([]string, len(b)) + + for n := range b { + for module := range b[n] { + modules[n] = module + break } } - return false + return modules } -// IsBlockedModule returns true if the given module name is in the -// blocked modules list. -func (b BlockedModules) IsBlockedModule(module string) bool { - blockedModules := b.Get() - for i := range blockedModules { - if strings.EqualFold(module, strings.TrimSpace(blockedModules[i])) { - return true +// GetBlockReason returns a block module if one is set for the provided linted module name. +func (b BlockedModules) GetBlockReason(currentModuleName, lintedModuleName string) *BlockedModule { + for _, blockedModule := range b { + for blockedModuleName, blockedModule := range blockedModule { + if strings.EqualFold(strings.TrimSpace(lintedModuleName), strings.TrimSpace(blockedModuleName)) { + blockedModule.Set(currentModuleName) + return &blockedModule + } } } - return false + return nil } // Allowed is a list of modules and module @@ -145,10 +230,11 @@ type Allowed struct { // IsAllowedModule returns true if the given module // name is in the allowed modules list. -func (a *Allowed) IsAllowedModule(module string) bool { +func (a *Allowed) IsAllowedModule(moduleName string) bool { allowedModules := a.Modules + for i := range allowedModules { - if strings.EqualFold(module, strings.TrimSpace(allowedModules[i])) { + if strings.EqualFold(strings.TrimSpace(moduleName), strings.TrimSpace(allowedModules[i])) { return true } } @@ -158,10 +244,11 @@ func (a *Allowed) IsAllowedModule(module string) bool { // IsAllowedModuleDomain returns true if the given modules domain is // in the allowed module domains list. -func (a *Allowed) IsAllowedModuleDomain(module string) bool { +func (a *Allowed) IsAllowedModuleDomain(moduleName string) bool { allowedDomains := a.Domains + for i := range allowedDomains { - if strings.HasPrefix(strings.ToLower(module), strings.TrimSpace(strings.ToLower(allowedDomains[i]))) { + if strings.HasPrefix(strings.TrimSpace(strings.ToLower(moduleName)), strings.TrimSpace(strings.ToLower(allowedDomains[i]))) { return true } } @@ -172,7 +259,8 @@ func (a *Allowed) IsAllowedModuleDomain(module string) bool { // Blocked is a list of modules that are // blocked and not to be used. type Blocked struct { - Modules BlockedModules `yaml:"modules"` + Modules BlockedModules `yaml:"modules"` + Versions BlockedVersions `yaml:"versions"` } // Configuration of gomodguard allow and block lists. @@ -192,46 +280,43 @@ type Result struct { // String returns the filename, line // number and reason of a Result. func (r *Result) String() string { - return fmt.Sprintf("%s:%d: %s", r.FileName, r.LineNumber, r.Reason) + return fmt.Sprintf("%s:%d:1 %s", r.FileName, r.LineNumber, r.Reason) } // Processor processes Go files. type Processor struct { - config Configuration - logger *log.Logger - modfile *modfile.File - blockedModulesFromModFile []string - result []Result + Config Configuration + Logger *log.Logger + Modfile *modfile.File + blockedModulesFromModFile map[string][]string + Result []Result } // NewProcessor will create a Processor to lint blocked packages. func NewProcessor(config Configuration, logger *log.Logger) (*Processor, error) { goModFileBytes, err := loadGoModFile() if err != nil { - errMsg := fmt.Sprintf("unable to read %s file: %s", goModFilename, err) - - return nil, fmt.Errorf(errMsg) + return nil, fmt.Errorf(errReadingGoModFile, goModFilename, err) } mfile, err := modfile.Parse(goModFilename, goModFileBytes, nil) if err != nil { - errMsg := fmt.Sprintf("unable to parse %s file: %s", goModFilename, err) - - return nil, fmt.Errorf(errMsg) + return nil, fmt.Errorf(errParsingGoModFile, goModFilename, err) } logger.Printf("info: allowed modules, %+v", config.Allowed.Modules) logger.Printf("info: allowed module domains, %+v", config.Allowed.Domains) logger.Printf("info: blocked modules, %+v", config.Blocked.Modules.Get()) + logger.Printf("info: blocked modules with version constraints, %+v", config.Blocked.Versions.Get()) p := &Processor{ - config: config, - logger: logger, - modfile: mfile, - result: []Result{}, + Config: config, + Logger: logger, + Modfile: mfile, + Result: []Result{}, } - p.setBlockedModulesFromModFile() + p.SetBlockedModulesFromModFile() return p, nil } @@ -244,13 +329,18 @@ func (p *Processor) ProcessFiles(filenames []string) []Result { pluralModuleMsg = "" } - p.logger.Printf("info: found `%d` blocked module%s in the %s file, %+v", - len(p.blockedModulesFromModFile), pluralModuleMsg, goModFilename, p.blockedModulesFromModFile) + blockedModules := make([]string, 0, len(p.blockedModulesFromModFile)) + for blockedModuleName := range p.blockedModulesFromModFile { + blockedModules = append(blockedModules, blockedModuleName) + } + + p.Logger.Printf("info: found %d blocked module%s in %s: %+v", + len(p.blockedModulesFromModFile), pluralModuleMsg, goModFilename, blockedModules) for _, filename := range filenames { data, err := ioutil.ReadFile(filename) if err != nil { - p.result = append(p.result, Result{ + p.Result = append(p.Result, Result{ FileName: filename, LineNumber: 0, Reason: fmt.Sprintf("unable to read file, file cannot be linted (%s)", err.Error()), @@ -260,7 +350,7 @@ func (p *Processor) ProcessFiles(filenames []string) []Result { p.process(filename, data) } - return p.result + return p.Result } // process file imports and add lint error if blocked package is imported. @@ -269,7 +359,7 @@ func (p *Processor) process(filename string, data []byte) { file, err := parser.ParseFile(fileSet, filename, data, parser.ParseComments) if err != nil { - p.result = append(p.result, Result{ + p.Result = append(p.Result, Result{ FileName: filename, LineNumber: 0, Reason: fmt.Sprintf("invalid syntax, file cannot be linted (%s)", err.Error()), @@ -279,23 +369,16 @@ func (p *Processor) process(filename string, data []byte) { } imports := file.Imports - for i := range imports { - importedPkg := strings.TrimSpace(strings.Trim(imports[i].Path.Value, "\"")) - if p.isBlockedPackageFromModFile(importedPkg) { - reason := "" - - if p.config.Blocked.Modules.IsBlockedPackage(importedPkg) { - reason = fmt.Sprintf(blockedReasonInBlockedList, importedPkg) - } else { - reason = fmt.Sprintf(blockedReasonNotInAllowedList, importedPkg) - } + for n := range imports { + importedPkg := strings.TrimSpace(strings.Trim(imports[n].Path.Value, "\"")) - recommendedModules := p.config.Blocked.Modules.RecommendedModules(importedPkg) - if recommendedModules != nil { - reason += fmt.Sprintf(" %s", recommendedModules.String()) - } + blockReasons := p.isBlockedPackageFromModFile(importedPkg) + if blockReasons == nil { + continue + } - p.addError(fileSet, imports[i].Pos(), reason) + for _, blockReason := range blockReasons { + p.addError(fileSet, imports[n].Pos(), blockReason) } } } @@ -305,7 +388,7 @@ func (p *Processor) process(filename string, data []byte) { func (p *Processor) addError(fileset *token.FileSet, pos token.Pos, reason string) { position := fileset.Position(pos) - p.result = append(p.result, Result{ + p.Result = append(p.Result, Result{ FileName: position.Filename, LineNumber: position.Line, Position: position, @@ -313,64 +396,69 @@ func (p *Processor) addError(fileset *token.FileSet, pos token.Pos, reason strin }) } -// setBlockedModules determines which modules are blocked by reading +// SetBlockedModulesFromModFile determines which modules are blocked by reading // the go.mod file and comparing the require modules to the allowed modules. -func (p *Processor) setBlockedModulesFromModFile() { - blockedModules := make([]string, 0, len(p.modfile.Require)) - requiredModules := p.modfile.Require - lintedModule := p.modfile.Module.Mod.Path - - for i := range requiredModules { - if !requiredModules[i].Indirect { - requiredModule := strings.TrimSpace(requiredModules[i].Mod.Path) +func (p *Processor) SetBlockedModulesFromModFile() { + blockedModules := make(map[string][]string, len(p.Modfile.Require)) + currentModuleName := p.Modfile.Module.Mod.Path + lintedModules := p.Modfile.Require + + for i := range lintedModules { + if lintedModules[i].Indirect { + continue + } - if p.config.Allowed.IsAllowedModuleDomain(requiredModule) { - continue - } + lintedModuleName := strings.TrimSpace(lintedModules[i].Mod.Path) + lintedModuleVersion := strings.TrimSpace(lintedModules[i].Mod.Version) - if p.config.Allowed.IsAllowedModule(requiredModule) { - continue - } + var isAllowed bool - requiredModuleIsBlocked := p.config.Blocked.Modules.IsBlockedModule(requiredModule) + switch { + case len(p.Config.Allowed.Modules) == 0 && len(p.Config.Allowed.Domains) == 0: + isAllowed = true + case p.Config.Allowed.IsAllowedModuleDomain(lintedModuleName): + isAllowed = true + case p.Config.Allowed.IsAllowedModule(lintedModuleName): + isAllowed = true + default: + isAllowed = false + } - if len(p.config.Allowed.Modules) == 0 && - len(p.config.Allowed.Domains) == 0 && - !requiredModuleIsBlocked { - continue - } + blockModuleReason := p.Config.Blocked.Modules.GetBlockReason(currentModuleName, lintedModuleName) + blockVersionReason := p.Config.Blocked.Versions.GetBlockReason(lintedModuleName, lintedModuleVersion) - // If the go.mod file being linted is a recommended module of a blocked module - // and it imports that blocked module, do not set as a blocked. This means - // that the linted module wraps that blocked module - if requiredModuleIsBlocked { - recommendedModules := p.config.Blocked.Modules.RecommendedModules(requiredModule) + if !isAllowed && blockModuleReason == nil && blockVersionReason == nil { + blockedModules[lintedModuleName] = append(blockedModules[lintedModuleName], blockReasonNotInAllowedList) + continue + } - if recommendedModules.IsRecommended(lintedModule) { - continue - } - } + if blockModuleReason != nil && !blockModuleReason.IsAllowed() { + blockedModules[lintedModuleName] = append(blockedModules[lintedModuleName], fmt.Sprintf("%s %s", blockReasonInBlockedList, blockModuleReason.Message())) + } - blockedModules = append(blockedModules, requiredModule) + if blockVersionReason != nil && !blockVersionReason.IsAllowed() { + blockedModules[lintedModuleName] = append(blockedModules[lintedModuleName], fmt.Sprintf("%s %s", blockReasonInBlockedList, blockVersionReason.Message())) } } - if len(blockedModules) > 0 { - p.blockedModulesFromModFile = blockedModules - } + p.blockedModulesFromModFile = blockedModules } -// isBlockedPackageFromModFile returns true if the imported packages -// module is in the go.mod file and was blocked. -func (p *Processor) isBlockedPackageFromModFile(pkg string) bool { - blockedModulesFromModFile := p.blockedModulesFromModFile - for i := range blockedModulesFromModFile { - if strings.HasPrefix(strings.ToLower(pkg), strings.ToLower(blockedModulesFromModFile[i])) { - return true +// isBlockedPackageFromModFile returns the block reason if the package is blocked. +func (p *Processor) isBlockedPackageFromModFile(packageName string) []string { + for blockedModuleName, blockReasons := range p.blockedModulesFromModFile { + if strings.HasPrefix(strings.TrimSpace(packageName), strings.TrimSpace(blockedModuleName)) { + formattedReasons := make([]string, 0, len(blockReasons)) + + for _, blockReason := range blockReasons { + formattedReasons = append(formattedReasons, fmt.Sprintf(blockReason, packageName)) + } + + return formattedReasons } } - return false + return nil } func loadGoModFile() ([]byte, error) { @@ -386,6 +474,7 @@ func loadGoModFile() ([]byte, error) { _, _ = buf.ReadFrom(stdout) goEnv := make(map[string]string) + err := json.Unmarshal(buf.Bytes(), &goEnv) if err != nil { return ioutil.ReadFile(goModFilename) diff --git a/vendor/github.com/ryanrolds/sqlclosecheck/LICENSE b/vendor/github.com/ryanrolds/sqlclosecheck/LICENSE new file mode 100644 index 00000000000..77b261d7a1f --- /dev/null +++ b/vendor/github.com/ryanrolds/sqlclosecheck/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020 Ryan R. Olds + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/analyzer.go b/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/analyzer.go new file mode 100644 index 00000000000..bc42dfb3a07 --- /dev/null +++ b/vendor/github.com/ryanrolds/sqlclosecheck/pkg/analyzer/analyzer.go @@ -0,0 +1,311 @@ +package analyzer + +import ( + "go/types" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/buildssa" + "golang.org/x/tools/go/ssa" +) + +const ( + rowsName = "Rows" + stmtName = "Stmt" + closeMethod = "Close" +) + +var ( + sqlPackages = []string{ + "database/sql", + "github.com/jmoiron/sqlx", + } +) + +func NewAnalyzer() *analysis.Analyzer { + return &analysis.Analyzer{ + Name: "sqlclosecheck", + Doc: "Checks that sql.Rows and sql.Stmt are closed.", + Run: run, + Requires: []*analysis.Analyzer{ + buildssa.Analyzer, + }, + } +} + +func run(pass *analysis.Pass) (interface{}, error) { + pssa := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA) + + // Build list of types we are looking for + targetTypes := getTargetTypes(pssa, sqlPackages) + + // If non of the types are found, skip + if len(targetTypes) == 0 { + return nil, nil + } + + funcs := pssa.SrcFuncs + for _, f := range funcs { + for _, b := range f.Blocks { + for i := range b.Instrs { + // Check if instruction is call that returns a target type + targetValues := getTargetTypesValues(b, i, targetTypes) + if len(targetValues) == 0 { + continue + } + + // log.Printf("%s", f.Name()) + + // For each found target check if they are closed and deferred + for _, targetValue := range targetValues { + refs := (*targetValue.value).Referrers() + isClosed := checkClosed(refs, targetTypes) + if !isClosed { + pass.Reportf((targetValue.instr).Pos(), "Rows/Stmt was not closed") + } + + checkDeferred(pass, refs, targetTypes, false) + } + } + } + } + + return nil, nil +} + +func getTargetTypes(pssa *buildssa.SSA, targetPackages []string) []*types.Pointer { + targets := []*types.Pointer{} + + for _, sqlPkg := range targetPackages { + pkg := pssa.Pkg.Prog.ImportedPackage(sqlPkg) + if pkg == nil { + // the SQL package being checked isn't imported + return targets + } + + rowsType := getTypePointerFromName(pkg, rowsName) + if rowsType != nil { + targets = append(targets, rowsType) + } + + stmtType := getTypePointerFromName(pkg, stmtName) + if stmtType != nil { + targets = append(targets, stmtType) + } + } + + return targets +} + +func getTypePointerFromName(pkg *ssa.Package, name string) *types.Pointer { + pkgType := pkg.Type(name) + if pkgType == nil { + // this package does not use Rows/Stmt + return nil + } + + obj := pkgType.Object() + named, ok := obj.Type().(*types.Named) + if !ok { + return nil + } + + return types.NewPointer(named) +} + +type targetValue struct { + value *ssa.Value + instr ssa.Instruction +} + +func getTargetTypesValues(b *ssa.BasicBlock, i int, targetTypes []*types.Pointer) []targetValue { + targetValues := []targetValue{} + + instr := b.Instrs[i] + call, ok := instr.(*ssa.Call) + if !ok { + return targetValues + } + + signature := call.Call.Signature() + results := signature.Results() + for i := 0; i < results.Len(); i++ { + v := results.At(i) + varType := v.Type() + + for _, targetType := range targetTypes { + if !types.Identical(varType, targetType) { + continue + } + + for _, cRef := range *call.Referrers() { + switch instr := cRef.(type) { + case *ssa.Call: + if len(instr.Call.Args) >= 1 && types.Identical(instr.Call.Args[0].Type(), targetType) { + targetValues = append(targetValues, targetValue{ + value: &instr.Call.Args[0], + instr: call, + }) + } + case ssa.Value: + if types.Identical(instr.Type(), targetType) { + targetValues = append(targetValues, targetValue{ + value: &instr, + instr: call, + }) + } + } + } + } + } + + return targetValues +} + +func checkClosed(refs *[]ssa.Instruction, targetTypes []*types.Pointer) bool { + numInstrs := len(*refs) + for idx, ref := range *refs { + // log.Printf("%T - %s", ref, ref) + + action := getAction(ref, targetTypes) + switch action { + case "closed": + return true + case "passed": + // Passed and not used after + if numInstrs == idx+1 { + return true + } + case "returned": + return true + case "handled": + return true + default: + // log.Printf(action) + } + } + + return false +} + +func getAction(instr ssa.Instruction, targetTypes []*types.Pointer) string { + switch instr := instr.(type) { + case *ssa.Defer: + if instr.Call.Value == nil { + return "unvalued defer" + } + + name := instr.Call.Value.Name() + if name == closeMethod { + return "closed" + } + case *ssa.Call: + if instr.Call.Value == nil { + return "unvalued call" + } + + isTarget := false + receiver := instr.Call.StaticCallee().Signature.Recv() + if receiver != nil { + isTarget = isTargetType(receiver.Type(), targetTypes) + } + + name := instr.Call.Value.Name() + if isTarget && name == closeMethod { + return "closed" + } + + if !isTarget { + return "passed" + } + case *ssa.Phi: + return "passed" + case *ssa.MakeInterface: + return "passed" + case *ssa.Store: + if len(*instr.Addr.Referrers()) == 0 { + return "noop" + } + + for _, aRef := range *instr.Addr.Referrers() { + if c, ok := aRef.(*ssa.MakeClosure); ok { + f := c.Fn.(*ssa.Function) + for _, b := range f.Blocks { + if checkClosed(&b.Instrs, targetTypes) { + return "handled" + } + } + } + } + case *ssa.UnOp: + instrType := instr.Type() + for _, targetType := range targetTypes { + if types.Identical(instrType, targetType) { + if checkClosed(instr.Referrers(), targetTypes) { + return "handled" + } + } + } + case *ssa.FieldAddr: + if checkClosed(instr.Referrers(), targetTypes) { + return "handled" + } + case *ssa.Return: + return "returned" + default: + // log.Printf("%s", instr) + } + + return "unhandled" +} + +func checkDeferred(pass *analysis.Pass, instrs *[]ssa.Instruction, targetTypes []*types.Pointer, inDefer bool) { + for _, instr := range *instrs { + switch instr := instr.(type) { + case *ssa.Defer: + if instr.Call.Value != nil && instr.Call.Value.Name() == closeMethod { + return + } + case *ssa.Call: + if instr.Call.Value != nil && instr.Call.Value.Name() == closeMethod { + if !inDefer { + pass.Reportf(instr.Pos(), "Close should use defer") + } + + return + } + case *ssa.Store: + if len(*instr.Addr.Referrers()) == 0 { + return + } + + for _, aRef := range *instr.Addr.Referrers() { + if c, ok := aRef.(*ssa.MakeClosure); ok { + f := c.Fn.(*ssa.Function) + + for _, b := range f.Blocks { + checkDeferred(pass, &b.Instrs, targetTypes, true) + } + } + } + case *ssa.UnOp: + instrType := instr.Type() + for _, targetType := range targetTypes { + if types.Identical(instrType, targetType) { + checkDeferred(pass, instr.Referrers(), targetTypes, inDefer) + } + } + case *ssa.FieldAddr: + checkDeferred(pass, instr.Referrers(), targetTypes, inDefer) + } + } +} + +func isTargetType(t types.Type, targetTypes []*types.Pointer) bool { + for _, targetType := range targetTypes { + if types.Identical(t, targetType) { + return true + } + } + + return false +} diff --git a/vendor/github.com/securego/gosec/.goreleaser.yml b/vendor/github.com/securego/gosec/.goreleaser.yml deleted file mode 100644 index 9951a9656bf..00000000000 --- a/vendor/github.com/securego/gosec/.goreleaser.yml +++ /dev/null @@ -1,25 +0,0 @@ ---- -project_name: gosec - -release: - github: - owner: securego - name: gosec - -builds: - - main : ./cmd/gosec/ - binary: gosec - goos: - - darwin - - linux - - windows - goarch: - - amd64 - ldflags: -X main.Version={{.Version}} -X main.GitTag={{.Tag}} -X main.BuildDate={{.Date}} - env: - - CGO_ENABLED=0 - -archive: - files: - - README.md - - LICENSE.txt diff --git a/vendor/github.com/securego/gosec/.travis.yml b/vendor/github.com/securego/gosec/.travis.yml deleted file mode 100644 index 265b2a623f3..00000000000 --- a/vendor/github.com/securego/gosec/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -language: go - -go: - - "1.12.x" - - "1.13.x" - - "1.14.x" - - tip - -install: - - go get -u golang.org/x/crypto/ssh - - go get -u github.com/lib/pq - - export PATH=$PATH:$HOME/gopath/bin - - export GO111MODULE=on - -script: make test - -after_success: - - make test-coverage - - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/securego/gosec/Makefile b/vendor/github.com/securego/gosec/Makefile deleted file mode 100644 index 21d8f837ec6..00000000000 --- a/vendor/github.com/securego/gosec/Makefile +++ /dev/null @@ -1,66 +0,0 @@ -GIT_TAG?= $(shell git describe --always --tags) -BIN = gosec -FMT_CMD = $(gofmt -s -l -w $(find . -type f -name '*.go' -not -path './vendor/*') | tee /dev/stderr) -IMAGE_REPO = securego -BUILDFLAGS := '-w -s' -CGO_ENABLED = 0 -GO := GO111MODULE=on go -GO_NOMOD :=GO111MODULE=off go -GOPATH ?= $(shell $(GO) env GOPATH) -GOBIN ?= $(GOPATH)/bin -GOLINT ?= $(GOBIN)/golint -GOSEC ?= $(GOBIN)/gosec -GINKGO ?= $(GOBIN)/ginkgo - -default: - $(MAKE) build - -test: build fmt lint sec - $(GO_NOMOD) get -u github.com/onsi/ginkgo/ginkgo - $(GINKGO) -r -v - -fmt: - @echo "FORMATTING" - @FORMATTED=`$(GO) fmt ./...` - @([[ ! -z "$(FORMATTED)" ]] && printf "Fixed unformatted files:\n$(FORMATTED)") || true - -lint: - @echo "LINTING" - $(GO_NOMOD) get -u golang.org/x/lint/golint - $(GOLINT) -set_exit_status ./... - @echo "VETTING" - $(GO) vet ./... - -sec: - @echo "SECURITY SCANNING" - ./$(BIN) ./... - -test-coverage: - go test -race -coverprofile=coverage.txt -covermode=atomic - -build: - go build -o $(BIN) ./cmd/gosec/ - -clean: - rm -rf build vendor dist - rm -f release image $(BIN) - -release: - @echo "Releasing the gosec binary..." - goreleaser release - -build-linux: - CGO_ENABLED=$(CGO_ENABLED) GOOS=linux GOARCH=amd64 go build -ldflags $(BUILDFLAGS) -o $(BIN) ./cmd/gosec/ - -image: - @echo "Building the Docker image..." - docker build -t $(IMAGE_REPO)/$(BIN):$(GIT_TAG) . - docker tag $(IMAGE_REPO)/$(BIN):$(GIT_TAG) $(IMAGE_REPO)/$(BIN):latest - touch image - -image-push: image - @echo "Pushing the Docker image..." - docker push $(IMAGE_REPO)/$(BIN):$(GIT_TAG) - docker push $(IMAGE_REPO)/$(BIN):latest - -.PHONY: test build clean release image image-push diff --git a/vendor/github.com/securego/gosec/README.md b/vendor/github.com/securego/gosec/README.md deleted file mode 100644 index fcd2faef4d6..00000000000 --- a/vendor/github.com/securego/gosec/README.md +++ /dev/null @@ -1,297 +0,0 @@ - -# gosec - Golang Security Checker - -Inspects source code for security problems by scanning the Go AST. - - - -## 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 [here](http://www.apache.org/licenses/LICENSE-2.0). - -## Project status - -[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/3218/badge)](https://bestpractices.coreinfrastructure.org/projects/3218) -[![Build Status](https://travis-ci.org/securego/gosec.svg?branch=master)](https://travis-ci.org/securego/gosec) -[![Coverage Status](https://codecov.io/gh/securego/gosec/branch/master/graph/badge.svg)](https://codecov.io/gh/securego/gosec) -[![GoReport](https://goreportcard.com/badge/github.com/securego/gosec)](https://goreportcard.com/badge/github.com/securego/gosec) -[![GoDoc](https://godoc.org/github.com/securego/gosec?status.svg)](https://godoc.org/github.com/securego/gosec) -[![Docs](https://readthedocs.org/projects/docs/badge/?version=latest)](https://securego.io/) -[![Downloads](https://img.shields.io/github/downloads/securego/gosec/total.svg)](https://github.com/securego/gosec/releases) -[![Docker Pulls](https://img.shields.io/docker/pulls/securego/gosec.svg)](https://hub.docker.com/r/securego/gosec/tags) -[![Slack](http://securego.herokuapp.com/badge.svg)](http://securego.herokuapp.com) - -## Install - -### CI Installation - -```bash -# binary will be $GOPATH/bin/gosec -curl -sfL https://raw.githubusercontent.com/securego/gosec/master/install.sh | sh -s -- -b $GOPATH/bin vX.Y.Z - -# or install it into ./bin/ -curl -sfL https://raw.githubusercontent.com/securego/gosec/master/install.sh | sh -s vX.Y.Z - -# In alpine linux (as it does not come with curl by default) -wget -O - -q https://raw.githubusercontent.com/securego/gosec/master/install.sh | sh -s vX.Y.Z - -# If you want to use the checksums provided on the "Releases" page -# then you will have to download a tar.gz file for your operating system instead of a binary file -wget https://github.com/securego/gosec/releases/download/vX.Y.Z/gosec_vX.Y.Z_OS.tar.gz - -# The file will be in the current folder where you run the command -# and you can check the checksum like this -echo " gosec_vX.Y.Z_OS.tar.gz" | sha256sum -c - - -gosec --help -``` - -### Local Installation - -```bash -go get github.com/securego/gosec/cmd/gosec -``` - -## Usage - -Gosec can be configured to only run a subset of rules, to exclude certain file -paths, and produce reports in different formats. By default all rules will be -run against the supplied input files. To recursively scan from the current -directory you can supply `./...` as the input argument. - - -### Available rules - -- G101: Look for hard coded credentials -- G102: Bind to all interfaces -- G103: Audit the use of unsafe block -- G104: Audit errors not checked -- G106: Audit the use of ssh.InsecureIgnoreHostKey -- G107: Url provided to HTTP request as taint input -- G108: Profiling endpoint automatically exposed on /debug/pprof -- G109: Potential Integer overflow made by strconv.Atoi result conversion to int16/32 -- G110: Potential DoS vulnerability via decompression bomb -- G201: SQL query construction using format string -- G202: SQL query construction using string concatenation -- G203: Use of unescaped data in HTML templates -- G204: Audit use of command execution -- G301: Poor file permissions used when creating a directory -- G302: Poor file permissions used with chmod -- G303: Creating tempfile using a predictable path -- G304: File path provided as taint input -- G305: File traversal when extracting zip archive -- G306: Poor file permissions used when writing to a new file -- G307: Deferring a method which returns an error -- G401: Detect the usage of DES, RC4, MD5 or SHA1 -- G402: Look for bad TLS connection settings -- G403: Ensure minimum RSA key length of 2048 bits -- G404: Insecure random number source (rand) -- G501: Import blacklist: crypto/md5 -- G502: Import blacklist: crypto/des -- G503: Import blacklist: crypto/rc4 -- G504: Import blacklist: net/http/cgi -- G505: Import blacklist: crypto/sha1 - -### Retired rules - -- G105: Audit the use of math/big.Int.Exp - [CVE is fixed](https://github.com/golang/go/issues/15184) - -### Selecting rules - -By default, gosec will run all rules against the supplied file paths. It is however possible to select a subset of rules to run via the `-include=` flag, -or to specify a set of rules to explicitly exclude using the `-exclude=` flag. - -```bash -# Run a specific set of rules -$ gosec -include=G101,G203,G401 ./... - -# Run everything except for rule G303 -$ gosec -exclude=G303 ./... -``` -### CWE Mapping - -Every issue detected by `gosec` is mapped to a [CWE (Common Weakness Enumeration)](http://cwe.mitre.org/data/index.html) which describes in more generic terms the vulnerability. The exact mapping can be found [here](https://github.com/securego/gosec/blob/53be8dd8644ee48802114178cff6eb7e29757414/issue.go#L49). - -### Configuration - -A number of global settings can be provided in a configuration file as follows: - -```JSON -{ - "global": { - "nosec": "enabled", - "audit": "enabled" - } -} -``` - -- `nosec`: this setting will overwrite all `#nosec` directives defined throughout the code base -- `audit`: runs in audit mode which enables addition checks that for normal code analysis might be too nosy - -```bash -# Run with a global configuration file -$ gosec -conf config.json . -``` -Also some rules accept configuration. For instance on rule `G104`, it is possible to define packages along with a list -of functions which will be skipped when auditing the not checked errors: - -```JSON -{ - "G104": { - "io/ioutil": ["WriteFile"] - } -} -``` - -### Dependencies - -gosec will fetch automatically the dependencies of the code which is being analyzed when go module is turned on (e.g.` GO111MODULE=on`). If this is not the case, -the dependencies need to be explicitly downloaded by running the `go get -d` command before the scan. - -### Excluding test files and folders - -gosec will ignore test files across all packages and any dependencies in your vendor directory. - -The scanning of test files can be enabled with the following flag: - -```bash - -gosec -tests ./... -``` - -Also additional folders can be excluded as follows: - -```bash - gosec -exclude-dir=rules -exclude-dir=cmd ./... -``` - -### Annotating code - -As with all automated detection tools, there will be cases of false positives. In cases where gosec reports a failure that has been manually verified as being safe, -it is possible to annotate the code with a `#nosec` comment. - -The annotation causes gosec to stop processing any further nodes within the -AST so can apply to a whole block or more granularly to a single expression. - -```go - -import "md5" // #nosec - - -func main(){ - - /* #nosec */ - if x > y { - h := md5.New() // this will also be ignored - } - -} - -``` - -When a specific false positive has been identified and verified as safe, you may wish to suppress only that single rule (or a specific set of rules) -within a section of code, while continuing to scan for other problems. To do this, you can list the rule(s) to be suppressed within -the `#nosec` annotation, e.g: `/* #nosec G401 */` or `// #nosec G201 G202 G203` - -In some cases you may also want to revisit places where `#nosec` annotations -have been used. To run the scanner and ignore any `#nosec` annotations you -can do the following: - -```bash -gosec -nosec=true ./... -``` - -### Build tags - -gosec is able to pass your [Go build tags](https://golang.org/pkg/go/build/) to the analyzer. -They can be provided as a comma separated list as follows: - -```bash -gosec -tag debug,ignore ./... -``` - -### Output formats - -gosec currently supports text, json, yaml, csv, sonarqube, JUnit XML and golint output formats. By default -results will be reported to stdout, but can also be written to an output -file. The output format is controlled by the '-fmt' flag, and the output file is controlled by the '-out' flag as follows: - -```bash -# Write output in json format to results.json -$ gosec -fmt=json -out=results.json *.go -``` - -## Development - -### Build - -```bash -make -``` - -### Tests - -```bash -make test -``` - -### Release Build - -Make sure you have installed the [goreleaser](https://github.com/goreleaser/goreleaser) tool and then you can release gosec as follows: - -```bash -git tag v1.0.0 -export GITHUB_TOKEN= -make release -``` - -The released version of the tool is available in the `dist` folder. The build information should be displayed in the usage text. - -```bash -./dist/darwin_amd64/gosec -h -gosec - Golang security checker - -gosec analyzes Go source code to look for common programming mistakes that - - -VERSION: 1.0.0 -GIT TAG: v1.0.0 -BUILD DATE: 2018-04-27T12:41:38Z -``` - -Note that all released archives are also uploaded to GitHub. - -### Docker image - -You can build the docker image as follows: - -```bash -make image -``` - -You can run the `gosec` tool in a container against your local Go project. You just have to mount the project -into a volume as follows: - -```bash -docker run -it -v /:/ securego/gosec //... -``` - -### Generate TLS rule - -The configuration of TLS rule can be generated from [Mozilla's TLS ciphers recommendation](https://statics.tls.security.mozilla.org/server-side-tls-conf.json). - -First you need to install the generator tool: - -```bash -go get github.com/securego/gosec/cmd/tlsconfig/... -``` - -You can invoke now the `go generate` in the root of the project: - -```bash -go generate ./... -``` - -This will generate the `rules/tls_config.go` file which will contain the current ciphers recommendation from Mozilla. diff --git a/vendor/github.com/securego/gosec/go.mod b/vendor/github.com/securego/gosec/go.mod deleted file mode 100644 index 5a9b826130e..00000000000 --- a/vendor/github.com/securego/gosec/go.mod +++ /dev/null @@ -1,22 +0,0 @@ -module github.com/securego/gosec - -require ( - github.com/golang/protobuf v1.3.2 // indirect - github.com/kr/pretty v0.1.0 // indirect - github.com/kr/pty v1.1.8 // indirect - github.com/lib/pq v1.2.0 // indirect - github.com/mozilla/tls-observatory v0.0.0-20200220173314-aae45faa4006 - github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d - github.com/onsi/ginkgo v1.12.0 - github.com/onsi/gomega v1.9.0 - github.com/stretchr/objx v0.2.0 // indirect - github.com/stretchr/testify v1.4.0 // indirect - golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f // indirect - golang.org/x/net v0.0.0-20190923162816-aa69164e4478 // indirect - golang.org/x/text v0.3.2 // indirect - golang.org/x/tools v0.0.0-20200228224639-71482053b885 - gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect - gopkg.in/yaml.v2 v2.2.8 -) - -go 1.13 diff --git a/vendor/github.com/securego/gosec/go.sum b/vendor/github.com/securego/gosec/go.sum deleted file mode 100644 index d784e974117..00000000000 --- a/vendor/github.com/securego/gosec/go.sum +++ /dev/null @@ -1,158 +0,0 @@ -github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0= -github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= -github.com/mozilla/tls-observatory v0.0.0-20190404164649-a3c1b6cfecfd h1:Av0AX0PnAlPZ3AY2rQUobGFaZfE4KHVRdKWIEPvsCWY= -github.com/mozilla/tls-observatory v0.0.0-20190404164649-a3c1b6cfecfd/go.mod h1:SrKMQvPiws7F7iqYp8/TX+IhxCYhzr6N/1yb8cwHsGk= -github.com/mozilla/tls-observatory v0.0.0-20200220173314-aae45faa4006 h1:MZ4Tk6cAXt694UZYVwB+rNZ5D/e5cXf0G6p4yjKm1v4= -github.com/mozilla/tls-observatory v0.0.0-20200220173314-aae45faa4006/go.mod h1:SrKMQvPiws7F7iqYp8/TX+IhxCYhzr6N/1yb8cwHsGk= -github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d h1:AREM5mwr4u1ORQBMvzfzBgpsctsbQikCVpvC+tX285E= -github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d/go.mod h1:o96djdrsSGy3AWPyBgZMAGfxZNfgntdJG+11KU4QvbU= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.8.0 h1:VkHVNpR4iVnU8XQR6DBm8BqYjN7CRzw+xKUbVVbbW9w= -github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.10.1 h1:q/mM8GF/n0shIN8SaAZ0V+jnLPzen6WIVZdiwrRlMlo= -github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.10.3 h1:OoxbjfXVZyod1fmWYhI7SEyaD8B00ynP3T+D5GiyHOY= -github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.11.0 h1:JAKSXpt1YjtLA7YpPiqO9ss6sNXEsPfSGdwN0UHqzrw= -github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= -github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo= -github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= -github.com/onsi/gomega v1.7.0 h1:XPnZz8VVBHjVsy1vzJmRwIcSwiUO+JFfrv/xGiigmME= -github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= -github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.8.1 h1:C5Dqfs/LeauYDX0jJXIe2SWmwCbGzx9yF8C8xy3Lh34= -github.com/onsi/gomega v1.8.1/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA= -github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190907121410-71b5226ff739 h1:Gc7JIyxvWgD6m+QmVryY0MstDORNYididDGxgZ6Tnpk= -golang.org/x/crypto v0.0.0-20190907121410-71b5226ff739/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190909091759-094676da4a83 h1:mgAKeshyNqWKdENOnQsg+8dRTwZFIwFaO3HNl52sweA= -golang.org/x/crypto v0.0.0-20190909091759-094676da4a83/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190911031432-227b76d455e7/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392 h1:ACG4HJsFiNMf47Y4PeRoebLNy/2lXT9EtprMuTFWt1M= -golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f h1:J5lckAjkw6qYlOZNj90mLYNTEKDvWeuc1yieZ8qUzUE= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190420063019-afa5a82059c6 h1:HdqqaWmYAUI7/dmByKKEw+yxDksGSo+9GjkUc9Zp34E= -golang.org/x/net v0.0.0-20190420063019-afa5a82059c6/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190909003024-a7b16738d86b h1:XfVGCX+0T4WOStkaOsJRllbsiImhB2jgVBGc9L0lPGc= -golang.org/x/net v0.0.0-20190909003024-a7b16738d86b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190912160710-24e19bdeb0f2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190916140828-c8589233b77d/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190921015927-1a5e07d1ff72/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190923162816-aa69164e4478 h1:l5EDrHhldLYb3ZRHDUhXF7Om7MvYXnkV9/iQNo1lX6g= -golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190907184412-d223b2b6db03 h1:b3JiLYVaG9kHjTcOQIoUh978YMCO7oVTQQBLudU47zY= -golang.org/x/sys v0.0.0-20190907184412-d223b2b6db03/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190909082730-f460065e899a h1:mIzbOulag9/gXacgxKlFVwpCOWSfBT3/pDyyCwGA9as= -golang.org/x/sys v0.0.0-20190909082730-f460065e899a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190910064555-bbd175535a8b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190911201528-7ad0cfa0b7b5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190913121621-c3b328c6e5a7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190922100055-0a153f010e69 h1:rOhMmluY6kLMhdnrivzec6lLgaVbMHMn2ISQXJeJ5EM= -golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190422233926-fe54fb35175b h1:NVD8gBK33xpdqCaZVVtd6OFJp+3dxkXuz7+U7KaVN6s= -golang.org/x/tools v0.0.0-20190422233926-fe54fb35175b/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190909030654-5b82db07426d h1:PhtdWYteEBebOX7KXm4qkIAVSUTHQ883/2hRB92r9lk= -golang.org/x/tools v0.0.0-20190909030654-5b82db07426d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190909214602-067311248421 h1:NmmWqJbt02YJHmp4A4gBXvsXXIzzixjzE1y6PKUyIjk= -golang.org/x/tools v0.0.0-20190909214602-067311248421/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190910044552-dd2b5c81c578 h1:f0Gfd654rnnfXT1+BK1YHPTS1qQdKrPIaGQwWxNE44k= -golang.org/x/tools v0.0.0-20190910044552-dd2b5c81c578/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911022129-16c5e0f7d110 h1:6S6bidS7O4yAwA5ORRbRIjvNQ9tGbLd5e+LRIaTeVDQ= -golang.org/x/tools v0.0.0-20190911022129-16c5e0f7d110/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911230505-6bfd74cf029c h1:ZgedNh8bIOBjyY5XEG0kR/41dSN9H+5jFZWuR/TgA1g= -golang.org/x/tools v0.0.0-20190911230505-6bfd74cf029c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190916034716-92af9d69eff2 h1:cvSBP3q8DeS4up5q8ssbGdEtSGiDgRV7HBvOpr3g5RM= -golang.org/x/tools v0.0.0-20190916034716-92af9d69eff2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190917032747-2dc213d980bc h1:AzQrNvr65FlhSjBpg0eVCY43QLsuOqtzWGtjcBqT6J8= -golang.org/x/tools v0.0.0-20190917032747-2dc213d980bc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190920225731-5eefd052ad72 h1:bw9doJza/SFBEweII/rHQh338oozWyiFsBRHtrflcws= -golang.org/x/tools v0.0.0-20190920225731-5eefd052ad72/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190923230126-0f9bb8f614ff h1:palXc2/lH3aFG86BII2o6pUYgrcAjON5FyYk7zthL3Q= -golang.org/x/tools v0.0.0-20190923230126-0f9bb8f614ff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190924052046-3ac2a5bbd98a h1:DJzZ1GRmbjp7ihxzAN6UTVpVMi6k4CXZEr7A3wi2kRA= -golang.org/x/tools v0.0.0-20190924052046-3ac2a5bbd98a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190930201159-7c411dea38b0 h1:7+F62GGWUowoiJOUDivedlBECd/fTeUDJnCu0JetQO0= -golang.org/x/tools v0.0.0-20190930201159-7c411dea38b0/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191101200257-8dbcdeb83d3f h1:+QO45yvqhfD79HVNFPAgvstYLFye8zA+rd0mHFsGV9s= -golang.org/x/tools v0.0.0-20191101200257-8dbcdeb83d3f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191217033636-bbbf87ae2631 h1:6/HU2wqgxuc1kG3FdVH8K60WlieDAlIYaVc21Cit9Us= -golang.org/x/tools v0.0.0-20191217033636-bbbf87ae2631/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200103221440-774c71fcf114 h1:DnSr2mCsxyCE6ZgIkmcWUQY2R5cH/6wL7eIxEmQOMSE= -golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200203023011-6f24f261dadb h1:Mjk7HEiAvEl5eS8doSYHgS8vXw90VXegoY/vbw8uRGE= -golang.org/x/tools v0.0.0-20200203023011-6f24f261dadb/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200228224639-71482053b885 h1:y09Juz/HD0YjGlyEd4bLUWG0s8Yx6iPniPqUGzUxNrU= -golang.org/x/tools v0.0.0-20200228224639-71482053b885/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898 h1:/atklqdjdhuosWIl6AIbOeHJjicWYPqR9bpxqxYG2pA= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo= -gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/securego/gosec/issue.go b/vendor/github.com/securego/gosec/issue.go deleted file mode 100644 index 829bbb5d27c..00000000000 --- a/vendor/github.com/securego/gosec/issue.go +++ /dev/null @@ -1,172 +0,0 @@ -// (c) Copyright 2016 Hewlett Packard Enterprise Development LP -// -// 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 gosec - -import ( - "encoding/json" - "fmt" - "go/ast" - "os" - "strconv" -) - -// Score type used by severity and confidence values -type Score int - -const ( - // Low severity or confidence - Low Score = iota - // Medium severity or confidence - Medium - // High severity or confidence - High -) - -// Cwe id and url -type Cwe struct { - ID string - URL string -} - -// GetCwe creates a cwe object for a given RuleID -func GetCwe(id string) Cwe { - return Cwe{ID: id, URL: fmt.Sprintf("https://cwe.mitre.org/data/definitions/%s.html", id)} -} - -// IssueToCWE maps gosec rules to CWEs -var IssueToCWE = map[string]Cwe{ - "G101": GetCwe("798"), - "G102": GetCwe("200"), - "G103": GetCwe("242"), - "G104": GetCwe("703"), - "G106": GetCwe("322"), - "G107": GetCwe("88"), - "G109": GetCwe("190"), - "G110": GetCwe("409"), - "G201": GetCwe("89"), - "G202": GetCwe("89"), - "G203": GetCwe("79"), - "G204": GetCwe("78"), - "G301": GetCwe("276"), - "G302": GetCwe("276"), - "G303": GetCwe("377"), - "G304": GetCwe("22"), - "G305": GetCwe("22"), - "G401": GetCwe("326"), - "G402": GetCwe("295"), - "G403": GetCwe("310"), - "G404": GetCwe("338"), - "G501": GetCwe("327"), - "G502": GetCwe("327"), - "G503": GetCwe("327"), - "G504": GetCwe("327"), - "G505": GetCwe("327"), -} - -// Issue is returned by a gosec rule if it discovers an issue with the scanned code. -type Issue struct { - Severity Score `json:"severity"` // issue severity (how problematic it is) - Confidence Score `json:"confidence"` // issue confidence (how sure we are we found it) - Cwe Cwe `json:"cwe"` // Cwe associated with RuleID - RuleID string `json:"rule_id"` // Human readable explanation - What string `json:"details"` // Human readable explanation - File string `json:"file"` // File name we found it in - Code string `json:"code"` // Impacted code line - Line string `json:"line"` // Line number in file - Col string `json:"column"` // Column number in line -} - -// MetaData is embedded in all gosec rules. The Severity, Confidence and What message -// will be passed through to reported issues. -type MetaData struct { - ID string - Severity Score - Confidence Score - What string -} - -// MarshalJSON is used convert a Score object into a JSON representation -func (c Score) MarshalJSON() ([]byte, error) { - return json.Marshal(c.String()) -} - -// String converts a Score into a string -func (c Score) String() string { - switch c { - case High: - return "HIGH" - case Medium: - return "MEDIUM" - case Low: - return "LOW" - } - return "UNDEFINED" -} - -func codeSnippet(file *os.File, start int64, end int64, n ast.Node) (string, error) { - if n == nil { - return "", fmt.Errorf("Invalid AST node provided") - } - - size := (int)(end - start) // Go bug, os.File.Read should return int64 ... - _, err := file.Seek(start, 0) // #nosec - if err != nil { - return "", fmt.Errorf("move to the beginning of file: %v", err) - } - - buf := make([]byte, size) - if nread, err := file.Read(buf); err != nil || nread != size { - return "", fmt.Errorf("Unable to read code") - } - return string(buf), nil -} - -// NewIssue creates a new Issue -func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, confidence Score) *Issue { - var code string - fobj := ctx.FileSet.File(node.Pos()) - name := fobj.Name() - - start, end := fobj.Line(node.Pos()), fobj.Line(node.End()) - line := strconv.Itoa(start) - if start != end { - line = fmt.Sprintf("%d-%d", start, end) - } - - col := strconv.Itoa(fobj.Position(node.Pos()).Column) - - // #nosec - if file, err := os.Open(fobj.Name()); err == nil { - defer file.Close() - s := (int64)(fobj.Position(node.Pos()).Offset) // Go bug, should be int64 - e := (int64)(fobj.Position(node.End()).Offset) // Go bug, should be int64 - code, err = codeSnippet(file, s, e, node) - if err != nil { - code = err.Error() - } - } - - return &Issue{ - File: name, - Line: line, - Col: col, - RuleID: ruleID, - What: desc, - Confidence: confidence, - Severity: severity, - Code: code, - Cwe: IssueToCWE[ruleID], - } -} diff --git a/vendor/github.com/securego/gosec/rules/archive.go b/vendor/github.com/securego/gosec/rules/archive.go deleted file mode 100644 index d9e7ea9a317..00000000000 --- a/vendor/github.com/securego/gosec/rules/archive.go +++ /dev/null @@ -1,60 +0,0 @@ -package rules - -import ( - "go/ast" - "go/types" - - "github.com/securego/gosec" -) - -type archive struct { - gosec.MetaData - calls gosec.CallList - argType string -} - -func (a *archive) ID() string { - return a.MetaData.ID -} - -// Match inspects AST nodes to determine if the filepath.Joins uses any argument derived from type zip.File -func (a *archive) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { - if node := a.calls.ContainsPkgCallExpr(n, c, false); node != nil { - for _, arg := range node.Args { - var argType types.Type - if selector, ok := arg.(*ast.SelectorExpr); ok { - argType = c.Info.TypeOf(selector.X) - } else if ident, ok := arg.(*ast.Ident); ok { - if ident.Obj != nil && ident.Obj.Kind == ast.Var { - decl := ident.Obj.Decl - if assign, ok := decl.(*ast.AssignStmt); ok { - if selector, ok := assign.Rhs[0].(*ast.SelectorExpr); ok { - argType = c.Info.TypeOf(selector.X) - } - } - } - } - - if argType != nil && argType.String() == a.argType { - return gosec.NewIssue(c, n, a.ID(), a.What, a.Severity, a.Confidence), nil - } - } - } - return nil, nil -} - -// NewArchive creates a new rule which detects the file traversal when extracting zip archives -func NewArchive(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { - calls := gosec.NewCallList() - calls.Add("path/filepath", "Join") - return &archive{ - calls: calls, - argType: "*archive/zip.File", - MetaData: gosec.MetaData{ - ID: id, - Severity: gosec.Medium, - Confidence: gosec.High, - What: "File traversal when extracting zip archive", - }, - }, []ast.Node{(*ast.CallExpr)(nil)} -} diff --git a/vendor/github.com/securego/gosec/rules/errors.go b/vendor/github.com/securego/gosec/rules/errors.go deleted file mode 100644 index de3163e9e46..00000000000 --- a/vendor/github.com/securego/gosec/rules/errors.go +++ /dev/null @@ -1,119 +0,0 @@ -// (c) Copyright 2016 Hewlett Packard Enterprise Development LP -// -// 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 rules - -import ( - "go/ast" - "go/types" - - "github.com/securego/gosec" -) - -type noErrorCheck struct { - gosec.MetaData - whitelist gosec.CallList -} - -func (r *noErrorCheck) ID() string { - return r.MetaData.ID -} - -func returnsError(callExpr *ast.CallExpr, ctx *gosec.Context) int { - if tv := ctx.Info.TypeOf(callExpr); tv != nil { - switch t := tv.(type) { - case *types.Tuple: - for pos := 0; pos < t.Len(); pos++ { - variable := t.At(pos) - if variable != nil && variable.Type().String() == "error" { - return pos - } - } - case *types.Named: - if t.String() == "error" { - return 0 - } - } - } - return -1 -} - -func (r *noErrorCheck) Match(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) { - switch stmt := n.(type) { - case *ast.AssignStmt: - cfg := ctx.Config - if enabled, err := cfg.IsGlobalEnabled(gosec.Audit); err == nil && enabled { - for _, expr := range stmt.Rhs { - if callExpr, ok := expr.(*ast.CallExpr); ok && r.whitelist.ContainsCallExpr(expr, ctx) == nil { - pos := returnsError(callExpr, ctx) - if pos < 0 || pos >= len(stmt.Lhs) { - return nil, nil - } - if id, ok := stmt.Lhs[pos].(*ast.Ident); ok && id.Name == "_" { - return gosec.NewIssue(ctx, n, r.ID(), r.What, r.Severity, r.Confidence), nil - } - } - } - } - case *ast.ExprStmt: - if callExpr, ok := stmt.X.(*ast.CallExpr); ok && r.whitelist.ContainsCallExpr(stmt.X, ctx) == nil { - pos := returnsError(callExpr, ctx) - if pos >= 0 { - return gosec.NewIssue(ctx, n, r.ID(), r.What, r.Severity, r.Confidence), nil - } - } - } - return nil, nil -} - -// NewNoErrorCheck detects if the returned error is unchecked -func NewNoErrorCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { - // TODO(gm) Come up with sensible defaults here. Or flip it to use a - // black list instead. - whitelist := gosec.NewCallList() - whitelist.AddAll("bytes.Buffer", "Write", "WriteByte", "WriteRune", "WriteString") - whitelist.AddAll("fmt", "Print", "Printf", "Println", "Fprint", "Fprintf", "Fprintln") - whitelist.AddAll("strings.Builder", "Write", "WriteByte", "WriteRune", "WriteString") - whitelist.Add("io.PipeWriter", "CloseWithError") - - if configured, ok := conf["G104"]; ok { - if whitelisted, ok := configured.(map[string]interface{}); ok { - for pkg, funcs := range whitelisted { - if funcs, ok := funcs.([]interface{}); ok { - whitelist.AddAll(pkg, toStringSlice(funcs)...) - } - } - } - } - - return &noErrorCheck{ - MetaData: gosec.MetaData{ - ID: id, - Severity: gosec.Low, - Confidence: gosec.High, - What: "Errors unhandled.", - }, - whitelist: whitelist, - }, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ExprStmt)(nil)} -} - -func toStringSlice(values []interface{}) []string { - result := []string{} - for _, value := range values { - if value, ok := value.(string); ok { - result = append(result, value) - } - } - return result -} diff --git a/vendor/github.com/securego/gosec/rules/hardcoded_credentials.go b/vendor/github.com/securego/gosec/rules/hardcoded_credentials.go deleted file mode 100644 index 17a5cdfe29a..00000000000 --- a/vendor/github.com/securego/gosec/rules/hardcoded_credentials.go +++ /dev/null @@ -1,147 +0,0 @@ -// (c) Copyright 2016 Hewlett Packard Enterprise Development LP -// -// 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 rules - -import ( - "go/ast" - "regexp" - "strconv" - - zxcvbn "github.com/nbutton23/zxcvbn-go" - "github.com/securego/gosec" -) - -type credentials struct { - gosec.MetaData - pattern *regexp.Regexp - entropyThreshold float64 - perCharThreshold float64 - truncate int - ignoreEntropy bool -} - -func (r *credentials) ID() string { - return r.MetaData.ID -} - -func truncate(s string, n int) string { - if n > len(s) { - return s - } - return s[:n] -} - -func (r *credentials) isHighEntropyString(str string) bool { - s := truncate(str, r.truncate) - info := zxcvbn.PasswordStrength(s, []string{}) - entropyPerChar := info.Entropy / float64(len(s)) - return (info.Entropy >= r.entropyThreshold || - (info.Entropy >= (r.entropyThreshold/2) && - entropyPerChar >= r.perCharThreshold)) -} - -func (r *credentials) Match(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) { - switch node := n.(type) { - case *ast.AssignStmt: - return r.matchAssign(node, ctx) - case *ast.ValueSpec: - return r.matchValueSpec(node, ctx) - } - return nil, nil -} - -func (r *credentials) matchAssign(assign *ast.AssignStmt, ctx *gosec.Context) (*gosec.Issue, error) { - for _, i := range assign.Lhs { - if ident, ok := i.(*ast.Ident); ok { - if r.pattern.MatchString(ident.Name) { - for _, e := range assign.Rhs { - if val, err := gosec.GetString(e); err == nil { - if r.ignoreEntropy || (!r.ignoreEntropy && r.isHighEntropyString(val)) { - return gosec.NewIssue(ctx, assign, r.ID(), r.What, r.Severity, r.Confidence), nil - } - } - } - } - } - } - return nil, nil -} - -func (r *credentials) matchValueSpec(valueSpec *ast.ValueSpec, ctx *gosec.Context) (*gosec.Issue, error) { - for index, ident := range valueSpec.Names { - if r.pattern.MatchString(ident.Name) && valueSpec.Values != nil { - // const foo, bar = "same value" - if len(valueSpec.Values) <= index { - index = len(valueSpec.Values) - 1 - } - if val, err := gosec.GetString(valueSpec.Values[index]); err == nil { - if r.ignoreEntropy || (!r.ignoreEntropy && r.isHighEntropyString(val)) { - return gosec.NewIssue(ctx, valueSpec, r.ID(), r.What, r.Severity, r.Confidence), nil - } - } - } - } - return nil, nil -} - -// NewHardcodedCredentials attempts to find high entropy string constants being -// assigned to variables that appear to be related to credentials. -func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { - pattern := `(?i)passwd|pass|password|pwd|secret|token` - entropyThreshold := 80.0 - perCharThreshold := 3.0 - ignoreEntropy := false - var truncateString = 16 - if val, ok := conf["G101"]; ok { - conf := val.(map[string]string) - if configPattern, ok := conf["pattern"]; ok { - pattern = configPattern - } - if configIgnoreEntropy, ok := conf["ignore_entropy"]; ok { - if parsedBool, err := strconv.ParseBool(configIgnoreEntropy); err == nil { - ignoreEntropy = parsedBool - } - } - if configEntropyThreshold, ok := conf["entropy_threshold"]; ok { - if parsedNum, err := strconv.ParseFloat(configEntropyThreshold, 64); err == nil { - entropyThreshold = parsedNum - } - } - if configCharThreshold, ok := conf["per_char_threshold"]; ok { - if parsedNum, err := strconv.ParseFloat(configCharThreshold, 64); err == nil { - perCharThreshold = parsedNum - } - } - if configTruncate, ok := conf["truncate"]; ok { - if parsedInt, err := strconv.Atoi(configTruncate); err == nil { - truncateString = parsedInt - } - } - } - - return &credentials{ - pattern: regexp.MustCompile(pattern), - entropyThreshold: entropyThreshold, - perCharThreshold: perCharThreshold, - ignoreEntropy: ignoreEntropy, - truncate: truncateString, - MetaData: gosec.MetaData{ - ID: id, - What: "Potential hardcoded credentials", - Confidence: gosec.Low, - Severity: gosec.High, - }, - }, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ValueSpec)(nil)} -} diff --git a/vendor/github.com/securego/gosec/rules/rand.go b/vendor/github.com/securego/gosec/rules/rand.go deleted file mode 100644 index a2bdabe169f..00000000000 --- a/vendor/github.com/securego/gosec/rules/rand.go +++ /dev/null @@ -1,55 +0,0 @@ -// (c) Copyright 2016 Hewlett Packard Enterprise Development LP -// -// 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 rules - -import ( - "go/ast" - - "github.com/securego/gosec" -) - -type weakRand struct { - gosec.MetaData - funcNames []string - packagePath string -} - -func (w *weakRand) ID() string { - return w.MetaData.ID -} - -func (w *weakRand) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { - for _, funcName := range w.funcNames { - if _, matched := gosec.MatchCallByPackage(n, c, w.packagePath, funcName); matched { - return gosec.NewIssue(c, n, w.ID(), w.What, w.Severity, w.Confidence), nil - } - } - - return nil, nil -} - -// NewWeakRandCheck detects the use of random number generator that isn't cryptographically secure -func NewWeakRandCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { - return &weakRand{ - funcNames: []string{"Read", "Int"}, - packagePath: "math/rand", - MetaData: gosec.MetaData{ - ID: id, - Severity: gosec.High, - Confidence: gosec.Medium, - What: "Use of weak random number generator (math/rand instead of crypto/rand)", - }, - }, []ast.Node{(*ast.CallExpr)(nil)} -} diff --git a/vendor/github.com/securego/gosec/rules/sql.go b/vendor/github.com/securego/gosec/rules/sql.go deleted file mode 100644 index 885f1057b6f..00000000000 --- a/vendor/github.com/securego/gosec/rules/sql.go +++ /dev/null @@ -1,219 +0,0 @@ -// (c) Copyright 2016 Hewlett Packard Enterprise Development LP -// -// 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 rules - -import ( - "go/ast" - "regexp" - - "github.com/securego/gosec" -) - -type sqlStatement struct { - gosec.MetaData - - // Contains a list of patterns which must all match for the rule to match. - patterns []*regexp.Regexp -} - -func (s *sqlStatement) ID() string { - return s.MetaData.ID -} - -// See if the string matches the patterns for the statement. -func (s *sqlStatement) MatchPatterns(str string) bool { - for _, pattern := range s.patterns { - if !pattern.MatchString(str) { - return false - } - } - return true -} - -type sqlStrConcat struct { - sqlStatement -} - -func (s *sqlStrConcat) ID() string { - return s.MetaData.ID -} - -// see if we can figure out what it is -func (s *sqlStrConcat) checkObject(n *ast.Ident, c *gosec.Context) bool { - if n.Obj != nil { - return n.Obj.Kind != ast.Var && n.Obj.Kind != ast.Fun - } - - // Try to resolve unresolved identifiers using other files in same package - for _, file := range c.PkgFiles { - if node, ok := file.Scope.Objects[n.String()]; ok { - return node.Kind != ast.Var && node.Kind != ast.Fun - } - } - return false -} - -// Look for "SELECT * FROM table WHERE " + " ' OR 1=1" -func (s *sqlStrConcat) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { - if node, ok := n.(*ast.BinaryExpr); ok { - if start, ok := node.X.(*ast.BasicLit); ok { - if str, e := gosec.GetString(start); e == nil { - if !s.MatchPatterns(str) { - return nil, nil - } - if _, ok := node.Y.(*ast.BasicLit); ok { - return nil, nil // string cat OK - } - if second, ok := node.Y.(*ast.Ident); ok && s.checkObject(second, c) { - return nil, nil - } - return gosec.NewIssue(c, n, s.ID(), s.What, s.Severity, s.Confidence), nil - } - } - } - return nil, nil -} - -// NewSQLStrConcat looks for cases where we are building SQL strings via concatenation -func NewSQLStrConcat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { - return &sqlStrConcat{ - sqlStatement: sqlStatement{ - patterns: []*regexp.Regexp{ - regexp.MustCompile(`(?)(SELECT|DELETE|INSERT|UPDATE|INTO|FROM|WHERE) `), - }, - MetaData: gosec.MetaData{ - ID: id, - Severity: gosec.Medium, - Confidence: gosec.High, - What: "SQL string concatenation", - }, - }, - }, []ast.Node{(*ast.BinaryExpr)(nil)} -} - -type sqlStrFormat struct { - sqlStatement - calls gosec.CallList - noIssue gosec.CallList - noIssueQuoted gosec.CallList -} - -// see if we can figure out what it is -func (s *sqlStrFormat) constObject(e ast.Expr, c *gosec.Context) bool { - n, ok := e.(*ast.Ident) - if !ok { - return false - } - - if n.Obj != nil { - return n.Obj.Kind == ast.Con - } - - // Try to resolve unresolved identifiers using other files in same package - for _, file := range c.PkgFiles { - if node, ok := file.Scope.Objects[n.String()]; ok { - return node.Kind == ast.Con - } - } - return false -} - -// Looks for "fmt.Sprintf("SELECT * FROM foo where '%s', userInput)" -func (s *sqlStrFormat) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { - - // argIndex changes the function argument which gets matched to the regex - argIndex := 0 - - // TODO(gm) improve confidence if database/sql is being used - if node := s.calls.ContainsPkgCallExpr(n, c, false); node != nil { - // if the function is fmt.Fprintf, search for SQL statement in Args[1] instead - if sel, ok := node.Fun.(*ast.SelectorExpr); ok { - if sel.Sel.Name == "Fprintf" { - // if os.Stderr or os.Stdout is in Arg[0], mark as no issue - if arg, ok := node.Args[0].(*ast.SelectorExpr); ok { - if ident, ok := arg.X.(*ast.Ident); ok { - if s.noIssue.Contains(ident.Name, arg.Sel.Name) { - return nil, nil - } - } - } - // the function is Fprintf so set argIndex = 1 - argIndex = 1 - } - } - - // no formatter - if len(node.Args) == 0 { - return nil, nil - } - - var formatter string - - // concats callexpr arg strings together if needed before regex evaluation - if argExpr, ok := node.Args[argIndex].(*ast.BinaryExpr); ok { - if fullStr, ok := gosec.ConcatString(argExpr); ok { - formatter = fullStr - } - } else if arg, e := gosec.GetString(node.Args[argIndex]); e == nil { - formatter = arg - } - if len(formatter) <= 0 { - return nil, nil - } - - // If all formatter args are quoted or constant, then the SQL construction is safe - if argIndex+1 < len(node.Args) { - allSafe := true - for _, arg := range node.Args[argIndex+1:] { - if n := s.noIssueQuoted.ContainsPkgCallExpr(arg, c, true); n == nil && !s.constObject(arg, c) { - allSafe = false - break - } - } - if allSafe { - return nil, nil - } - } - if s.MatchPatterns(formatter) { - return gosec.NewIssue(c, n, s.ID(), s.What, s.Severity, s.Confidence), nil - } - } - return nil, nil -} - -// NewSQLStrFormat looks for cases where we're building SQL query strings using format strings -func NewSQLStrFormat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { - rule := &sqlStrFormat{ - calls: gosec.NewCallList(), - noIssue: gosec.NewCallList(), - noIssueQuoted: gosec.NewCallList(), - sqlStatement: sqlStatement{ - patterns: []*regexp.Regexp{ - regexp.MustCompile("(?)(SELECT|DELETE|INSERT|UPDATE|INTO|FROM|WHERE) "), - regexp.MustCompile("%[^bdoxXfFp]"), - }, - MetaData: gosec.MetaData{ - ID: id, - Severity: gosec.Medium, - Confidence: gosec.High, - What: "SQL string formatting", - }, - }, - } - rule.calls.AddAll("fmt", "Sprint", "Sprintf", "Sprintln", "Fprintf") - rule.noIssue.AddAll("os", "Stdout", "Stderr") - rule.noIssueQuoted.Add("github.com/lib/pq", "QuoteIdentifier") - return rule, []ast.Node{(*ast.CallExpr)(nil)} -} diff --git a/vendor/github.com/securego/gosec/.gitignore b/vendor/github.com/securego/gosec/v2/.gitignore similarity index 100% rename from vendor/github.com/securego/gosec/.gitignore rename to vendor/github.com/securego/gosec/v2/.gitignore diff --git a/vendor/github.com/securego/gosec/v2/.goreleaser.yml b/vendor/github.com/securego/gosec/v2/.goreleaser.yml new file mode 100644 index 00000000000..4f8fc4128b2 --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/.goreleaser.yml @@ -0,0 +1,20 @@ +--- +project_name: gosec + +release: + github: + owner: securego + name: gosec + +builds: + - main : ./cmd/gosec/ + binary: gosec + goos: + - darwin + - linux + - windows + goarch: + - amd64 + ldflags: -X main.Version={{.Version}} -X main.GitTag={{.Tag}} -X main.BuildDate={{.Date}} + env: + - CGO_ENABLED=0 diff --git a/vendor/github.com/securego/gosec/Dockerfile b/vendor/github.com/securego/gosec/v2/Dockerfile similarity index 95% rename from vendor/github.com/securego/gosec/Dockerfile rename to vendor/github.com/securego/gosec/v2/Dockerfile index 7e8fe02fa88..a874697e974 100644 --- a/vendor/github.com/securego/gosec/Dockerfile +++ b/vendor/github.com/securego/gosec/v2/Dockerfile @@ -1,4 +1,4 @@ -ARG GO_VERSION=1.13 +ARG GO_VERSION FROM golang:${GO_VERSION}-alpine AS builder RUN apk add --update --no-cache ca-certificates make git curl gcc libc-dev RUN mkdir -p /build diff --git a/vendor/github.com/securego/gosec/LICENSE.txt b/vendor/github.com/securego/gosec/v2/LICENSE.txt similarity index 100% rename from vendor/github.com/securego/gosec/LICENSE.txt rename to vendor/github.com/securego/gosec/v2/LICENSE.txt diff --git a/vendor/github.com/securego/gosec/v2/Makefile b/vendor/github.com/securego/gosec/v2/Makefile new file mode 100644 index 00000000000..217651c4318 --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/Makefile @@ -0,0 +1,71 @@ +GIT_TAG?= $(shell git describe --always --tags) +BIN = gosec +FMT_CMD = $(gofmt -s -l -w $(find . -type f -name '*.go' -not -path './vendor/*') | tee /dev/stderr) +IMAGE_REPO = securego +BUILDFLAGS := '-w -s' +CGO_ENABLED = 0 +GO := GO111MODULE=on go +GO_NOMOD :=GO111MODULE=off go +GOPATH ?= $(shell $(GO) env GOPATH) +GOBIN ?= $(GOPATH)/bin +GOLINT ?= $(GOBIN)/golint +GOSEC ?= $(GOBIN)/gosec +GINKGO ?= $(GOBIN)/ginkgo +GO_VERSION = 1.14 + +default: + $(MAKE) build + +install-test-deps: + $(GO_NOMOD) get -u github.com/onsi/ginkgo/ginkgo + $(GO_NOMOD) get -u golang.org/x/crypto/ssh + $(GO_NOMOD) get -u github.com/lib/pq + +test: install-test-deps build fmt lint sec + $(GINKGO) -r -v + +fmt: + @echo "FORMATTING" + @FORMATTED=`$(GO) fmt ./...` + @([[ ! -z "$(FORMATTED)" ]] && printf "Fixed unformatted files:\n$(FORMATTED)") || true + +lint: + @echo "LINTING" + $(GO_NOMOD) get -u golang.org/x/lint/golint + $(GOLINT) -set_exit_status ./... + @echo "VETTING" + $(GO) vet ./... + +sec: + @echo "SECURITY SCANNING" + ./$(BIN) ./... + +test-coverage: install-test-deps + go test -race -coverprofile=coverage.txt -covermode=atomic + +build: + go build -o $(BIN) ./cmd/gosec/ + +clean: + rm -rf build vendor dist coverage.txt + rm -f release image $(BIN) + +release: + @echo "Releasing the gosec binary..." + goreleaser release + +build-linux: + CGO_ENABLED=$(CGO_ENABLED) GOOS=linux GOARCH=amd64 go build -ldflags $(BUILDFLAGS) -o $(BIN) ./cmd/gosec/ + +image: + @echo "Building the Docker image..." + docker build -t $(IMAGE_REPO)/$(BIN):$(GIT_TAG) --build-arg GO_VERSION=$(GO_VERSION) . + docker tag $(IMAGE_REPO)/$(BIN):$(GIT_TAG) $(IMAGE_REPO)/$(BIN):latest + touch image + +image-push: image + @echo "Pushing the Docker image..." + docker push $(IMAGE_REPO)/$(BIN):$(GIT_TAG) + docker push $(IMAGE_REPO)/$(BIN):latest + +.PHONY: test build clean release image image-push diff --git a/vendor/github.com/securego/gosec/v2/README.md b/vendor/github.com/securego/gosec/v2/README.md new file mode 100644 index 00000000000..52be7342345 --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/README.md @@ -0,0 +1,326 @@ + +# gosec - Golang Security Checker + +Inspects source code for security problems by scanning the Go AST. + + + +## 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 [here](http://www.apache.org/licenses/LICENSE-2.0). + +## Project status + +[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/3218/badge)](https://bestpractices.coreinfrastructure.org/projects/3218) +[![Build Status](https://github.com/securego/gosec/workflows/CI/badge.svg)](https://github.com/securego/gosec/actions?query=workflows%3ACI) +[![Coverage Status](https://codecov.io/gh/securego/gosec/branch/master/graph/badge.svg)](https://codecov.io/gh/securego/gosec) +[![GoReport](https://goreportcard.com/badge/github.com/securego/gosec)](https://goreportcard.com/badge/github.com/securego/gosec) +[![GoDoc](https://godoc.org/github.com/securego/gosec?status.svg)](https://godoc.org/github.com/securego/gosec) +[![Docs](https://readthedocs.org/projects/docs/badge/?version=latest)](https://securego.io/) +[![Downloads](https://img.shields.io/github/downloads/securego/gosec/total.svg)](https://github.com/securego/gosec/releases) +[![Docker Pulls](https://img.shields.io/docker/pulls/securego/gosec.svg)](https://hub.docker.com/r/securego/gosec/tags) +[![Slack](http://securego.herokuapp.com/badge.svg)](http://securego.herokuapp.com) + +## Install + +### CI Installation + +```bash +# binary will be $GOPATH/bin/gosec +curl -sfL https://raw.githubusercontent.com/securego/gosec/master/install.sh | sh -s -- -b $GOPATH/bin vX.Y.Z + +# or install it into ./bin/ +curl -sfL https://raw.githubusercontent.com/securego/gosec/master/install.sh | sh -s vX.Y.Z + +# In alpine linux (as it does not come with curl by default) +wget -O - -q https://raw.githubusercontent.com/securego/gosec/master/install.sh | sh -s vX.Y.Z + +# If you want to use the checksums provided on the "Releases" page +# then you will have to download a tar.gz file for your operating system instead of a binary file +wget https://github.com/securego/gosec/releases/download/vX.Y.Z/gosec_vX.Y.Z_OS.tar.gz + +# The file will be in the current folder where you run the command +# and you can check the checksum like this +echo " gosec_vX.Y.Z_OS.tar.gz" | sha256sum -c - + +gosec --help +``` +### GitHub Action + +You can run `gosec` as a GitHub action as follows: + +```yaml +name: Run Gosec +on: + push: + branches: + - master + pull_request: + branches: + - master +jobs: + tests: + runs-on: ubuntu-latest + env: + GO111MODULE: on + steps: + - name: Checkout Source + uses: actions/checkout@v2 + - name: Run Gosec Security Scanner + uses: securego/gosec@master + with: + args: ./... +``` + +### Local Installation + +```bash +go get github.com/securego/gosec/cmd/gosec +``` + +## Usage + +Gosec can be configured to only run a subset of rules, to exclude certain file +paths, and produce reports in different formats. By default all rules will be +run against the supplied input files. To recursively scan from the current +directory you can supply `./...` as the input argument. + + +### Available rules + +- G101: Look for hard coded credentials +- G102: Bind to all interfaces +- G103: Audit the use of unsafe block +- G104: Audit errors not checked +- G106: Audit the use of ssh.InsecureIgnoreHostKey +- G107: Url provided to HTTP request as taint input +- G108: Profiling endpoint automatically exposed on /debug/pprof +- G109: Potential Integer overflow made by strconv.Atoi result conversion to int16/32 +- G110: Potential DoS vulnerability via decompression bomb +- G201: SQL query construction using format string +- G202: SQL query construction using string concatenation +- G203: Use of unescaped data in HTML templates +- G204: Audit use of command execution +- G301: Poor file permissions used when creating a directory +- G302: Poor file permissions used with chmod +- G303: Creating tempfile using a predictable path +- G304: File path provided as taint input +- G305: File traversal when extracting zip archive +- G306: Poor file permissions used when writing to a new file +- G307: Deferring a method which returns an error +- G401: Detect the usage of DES, RC4, MD5 or SHA1 +- G402: Look for bad TLS connection settings +- G403: Ensure minimum RSA key length of 2048 bits +- G404: Insecure random number source (rand) +- G501: Import blacklist: crypto/md5 +- G502: Import blacklist: crypto/des +- G503: Import blacklist: crypto/rc4 +- G504: Import blacklist: net/http/cgi +- G505: Import blacklist: crypto/sha1 +- G601: Implicit memory aliasing of items from a range statement + +### Retired rules + +- G105: Audit the use of math/big.Int.Exp - [CVE is fixed](https://github.com/golang/go/issues/15184) + +### Selecting rules + +By default, gosec will run all rules against the supplied file paths. It is however possible to select a subset of rules to run via the `-include=` flag, +or to specify a set of rules to explicitly exclude using the `-exclude=` flag. + +```bash +# Run a specific set of rules +$ gosec -include=G101,G203,G401 ./... + +# Run everything except for rule G303 +$ gosec -exclude=G303 ./... +``` +### CWE Mapping + +Every issue detected by `gosec` is mapped to a [CWE (Common Weakness Enumeration)](http://cwe.mitre.org/data/index.html) which describes in more generic terms the vulnerability. The exact mapping can be found [here](https://github.com/securego/gosec/blob/53be8dd8644ee48802114178cff6eb7e29757414/issue.go#L49). + +### Configuration + +A number of global settings can be provided in a configuration file as follows: + +```JSON +{ + "global": { + "nosec": "enabled", + "audit": "enabled" + } +} +``` + +- `nosec`: this setting will overwrite all `#nosec` directives defined throughout the code base +- `audit`: runs in audit mode which enables addition checks that for normal code analysis might be too nosy + +```bash +# Run with a global configuration file +$ gosec -conf config.json . +``` +Also some rules accept configuration. For instance on rule `G104`, it is possible to define packages along with a list +of functions which will be skipped when auditing the not checked errors: + +```JSON +{ + "G104": { + "io/ioutil": ["WriteFile"] + } +} +``` + +You can also configure the hard-coded credentials rule `G101` with additional patters, or adjust the entropy threshold: + +```JSON +{ + "G101": { + "pattern": "(?i)passwd|pass|password|pwd|secret|private_key|token", + "ingnore_entropy": false, + "entropy_threshold": "80.0", + "per_char_threshold": "3.0", + "trucate": "32" + } +} +``` + +### Dependencies + +gosec will fetch automatically the dependencies of the code which is being analyzed when go module is turned on (e.g.` GO111MODULE=on`). If this is not the case, +the dependencies need to be explicitly downloaded by running the `go get -d` command before the scan. + +### Excluding test files and folders + +gosec will ignore test files across all packages and any dependencies in your vendor directory. + +The scanning of test files can be enabled with the following flag: + +```bash + +gosec -tests ./... +``` + +Also additional folders can be excluded as follows: + +```bash + gosec -exclude-dir=rules -exclude-dir=cmd ./... +``` + +### Annotating code + +As with all automated detection tools, there will be cases of false positives. In cases where gosec reports a failure that has been manually verified as being safe, +it is possible to annotate the code with a `#nosec` comment. + +The annotation causes gosec to stop processing any further nodes within the +AST so can apply to a whole block or more granularly to a single expression. + +```go + +import "md5" // #nosec + + +func main(){ + + /* #nosec */ + if x > y { + h := md5.New() // this will also be ignored + } + +} + +``` + +When a specific false positive has been identified and verified as safe, you may wish to suppress only that single rule (or a specific set of rules) +within a section of code, while continuing to scan for other problems. To do this, you can list the rule(s) to be suppressed within +the `#nosec` annotation, e.g: `/* #nosec G401 */` or `// #nosec G201 G202 G203` + +In some cases you may also want to revisit places where `#nosec` annotations +have been used. To run the scanner and ignore any `#nosec` annotations you +can do the following: + +```bash +gosec -nosec=true ./... +``` + +### Build tags + +gosec is able to pass your [Go build tags](https://golang.org/pkg/go/build/) to the analyzer. +They can be provided as a comma separated list as follows: + +```bash +gosec -tag debug,ignore ./... +``` + +### Output formats + +gosec currently supports `text`, `json`, `yaml`, `csv`, `sonarqube`, `JUnit XML`, `html` and `golint` output formats. By default +results will be reported to stdout, but can also be written to an output +file. The output format is controlled by the `-fmt` flag, and the output file is controlled by the `-out` flag as follows: + +```bash +# Write output in json format to results.json +$ gosec -fmt=json -out=results.json *.go +``` + +## Development + +### Build + +You can build the binary with: +```bash +make +``` + +### Tests + +You can run all unit tests using: +```bash +make test +``` + +### Release + +You can create a release by tagging the version as follows: + +``` bash +git tag v1.0.0 -m "Release version v1.0.0" +git push origin v1.0.0 +``` + +The GitHub [release workflow](.github/workflows/release.yml) triggers immediately after the tag is pushed upstream. This flow will +release the binaries using the [goreleaser](https://goreleaser.com/actions/) action and then it will build and publish the docker image into Docker Hub. + +### Docker image + +You can also build locally the docker image by using the command: + +```bash +make image +``` + +You can run the `gosec` tool in a container against your local Go project. You only have to mount the project +into a volume as follows: + +```bash +docker run -it -v /:/ securego/gosec //... +``` + +### Generate TLS rule + +The configuration of TLS rule can be generated from [Mozilla's TLS ciphers recommendation](https://statics.tls.security.mozilla.org/server-side-tls-conf.json). + +First you need to install the generator tool: + +```bash +go get github.com/securego/gosec/cmd/tlsconfig/... +``` + +You can invoke now the `go generate` in the root of the project: + +```bash +go generate ./... +``` + +This will generate the `rules/tls_config.go` file which will contain the current ciphers recommendation from Mozilla. diff --git a/vendor/github.com/securego/gosec/v2/action.yml b/vendor/github.com/securego/gosec/v2/action.yml new file mode 100644 index 00000000000..aab6c8039d6 --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/action.yml @@ -0,0 +1,19 @@ +name: 'Gosec Security Checker' +description: 'Runs the gosec security checker' +author: '@ccojocar' + +inputs: + args: + description: 'Arguments for gosec' + required: true + default: '-h' + +runs: + using: 'docker' + image: 'docker://securego/gosec' + args: + - ${{ inputs.args }} + +branding: + icon: 'shield' + color: 'blue' diff --git a/vendor/github.com/securego/gosec/analyzer.go b/vendor/github.com/securego/gosec/v2/analyzer.go similarity index 100% rename from vendor/github.com/securego/gosec/analyzer.go rename to vendor/github.com/securego/gosec/v2/analyzer.go diff --git a/vendor/github.com/securego/gosec/call_list.go b/vendor/github.com/securego/gosec/v2/call_list.go similarity index 100% rename from vendor/github.com/securego/gosec/call_list.go rename to vendor/github.com/securego/gosec/v2/call_list.go diff --git a/vendor/github.com/securego/gosec/config.go b/vendor/github.com/securego/gosec/v2/config.go similarity index 100% rename from vendor/github.com/securego/gosec/config.go rename to vendor/github.com/securego/gosec/v2/config.go diff --git a/vendor/github.com/securego/gosec/errors.go b/vendor/github.com/securego/gosec/v2/errors.go similarity index 100% rename from vendor/github.com/securego/gosec/errors.go rename to vendor/github.com/securego/gosec/v2/errors.go diff --git a/vendor/github.com/securego/gosec/v2/go.mod b/vendor/github.com/securego/gosec/v2/go.mod new file mode 100644 index 00000000000..edfa3434c34 --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/go.mod @@ -0,0 +1,19 @@ +module github.com/securego/gosec/v2 + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/golang/protobuf v1.3.2 // indirect + github.com/gookit/color v1.2.4 + github.com/kr/pretty v0.1.0 // indirect + github.com/mozilla/tls-observatory v0.0.0-20200317151703-4fa42e1c2dee + github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d + github.com/onsi/ginkgo v1.12.0 + github.com/onsi/gomega v1.9.0 + github.com/stretchr/testify v1.4.0 // indirect + golang.org/x/text v0.3.2 // indirect + golang.org/x/tools v0.0.0-20200331202046-9d5940d49312 + gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect + gopkg.in/yaml.v2 v2.2.8 +) + +go 1.14 diff --git a/vendor/github.com/securego/gosec/v2/go.sum b/vendor/github.com/securego/gosec/v2/go.sum new file mode 100644 index 00000000000..fff56a309ec --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/go.sum @@ -0,0 +1,82 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/gookit/color v1.2.4 h1:xOYBan3Fwlrqj1M1UN2TlHOCRiek3bGzWf/vPnJ1roE= +github.com/gookit/color v1.2.4/go.mod h1:AhIE+pS6D4Ql0SQWbBeXPHw7gY0/sjHoA4s/n1KB7xg= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/mozilla/tls-observatory v0.0.0-20200317151703-4fa42e1c2dee h1:1xJ+Xi9lYWLaaP4yB67ah0+548CD3110mCPWhVVjFkI= +github.com/mozilla/tls-observatory v0.0.0-20200317151703-4fa42e1c2dee/go.mod h1:SrKMQvPiws7F7iqYp8/TX+IhxCYhzr6N/1yb8cwHsGk= +github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d h1:AREM5mwr4u1ORQBMvzfzBgpsctsbQikCVpvC+tX285E= +github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d/go.mod h1:o96djdrsSGy3AWPyBgZMAGfxZNfgntdJG+11KU4QvbU= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.9.0 h1:R1uwffexN6Pr340GtYRIdZmAiN4J+iw6WG4wog1DUXg= +github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b h1:0mm1VjtFUOIlE1SbDlwjYaDxZVDP2S5ou6y0gSgXHu8= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e h1:N7DeIrjYszNmSW409R3frPPwglRwMkXSBzwVbkOjLLA= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200331202046-9d5940d49312 h1:2PHG+Ia3gK1K2kjxZnSylizb//eyaMG8gDFbOG7wLV8= +golang.org/x/tools v0.0.0-20200331202046-9d5940d49312/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898 h1:/atklqdjdhuosWIl6AIbOeHJjicWYPqR9bpxqxYG2pA= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/securego/gosec/helpers.go b/vendor/github.com/securego/gosec/v2/helpers.go similarity index 100% rename from vendor/github.com/securego/gosec/helpers.go rename to vendor/github.com/securego/gosec/v2/helpers.go diff --git a/vendor/github.com/securego/gosec/import_tracker.go b/vendor/github.com/securego/gosec/v2/import_tracker.go similarity index 100% rename from vendor/github.com/securego/gosec/import_tracker.go rename to vendor/github.com/securego/gosec/v2/import_tracker.go diff --git a/vendor/github.com/securego/gosec/install.sh b/vendor/github.com/securego/gosec/v2/install.sh similarity index 100% rename from vendor/github.com/securego/gosec/install.sh rename to vendor/github.com/securego/gosec/v2/install.sh diff --git a/vendor/github.com/securego/gosec/v2/issue.go b/vendor/github.com/securego/gosec/v2/issue.go new file mode 100644 index 00000000000..28ad726bac7 --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/issue.go @@ -0,0 +1,177 @@ +// (c) Copyright 2016 Hewlett Packard Enterprise Development LP +// +// 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 gosec + +import ( + "encoding/json" + "fmt" + "go/ast" + "os" + "strconv" +) + +// Score type used by severity and confidence values +type Score int + +const ( + // Low severity or confidence + Low Score = iota + // Medium severity or confidence + Medium + // High severity or confidence + High +) + +// Cwe id and url +type Cwe struct { + ID string + URL string +} + +// GetCwe creates a cwe object for a given RuleID +func GetCwe(id string) Cwe { + return Cwe{ID: id, URL: fmt.Sprintf("https://cwe.mitre.org/data/definitions/%s.html", id)} +} + +// IssueToCWE maps gosec rules to CWEs +var IssueToCWE = map[string]Cwe{ + "G101": GetCwe("798"), + "G102": GetCwe("200"), + "G103": GetCwe("242"), + "G104": GetCwe("703"), + "G106": GetCwe("322"), + "G107": GetCwe("88"), + "G109": GetCwe("190"), + "G110": GetCwe("409"), + "G201": GetCwe("89"), + "G202": GetCwe("89"), + "G203": GetCwe("79"), + "G204": GetCwe("78"), + "G301": GetCwe("276"), + "G302": GetCwe("276"), + "G303": GetCwe("377"), + "G304": GetCwe("22"), + "G305": GetCwe("22"), + "G401": GetCwe("326"), + "G402": GetCwe("295"), + "G403": GetCwe("310"), + "G404": GetCwe("338"), + "G501": GetCwe("327"), + "G502": GetCwe("327"), + "G503": GetCwe("327"), + "G504": GetCwe("327"), + "G505": GetCwe("327"), +} + +// Issue is returned by a gosec rule if it discovers an issue with the scanned code. +type Issue struct { + Severity Score `json:"severity"` // issue severity (how problematic it is) + Confidence Score `json:"confidence"` // issue confidence (how sure we are we found it) + Cwe Cwe `json:"cwe"` // Cwe associated with RuleID + RuleID string `json:"rule_id"` // Human readable explanation + What string `json:"details"` // Human readable explanation + File string `json:"file"` // File name we found it in + Code string `json:"code"` // Impacted code line + Line string `json:"line"` // Line number in file + Col string `json:"column"` // Column number in line +} + +// FileLocation point out the file path and line number in file +func (i Issue) FileLocation() string { + return fmt.Sprintf("%s:%s", i.File, i.Line) +} + +// MetaData is embedded in all gosec rules. The Severity, Confidence and What message +// will be passed through to reported issues. +type MetaData struct { + ID string + Severity Score + Confidence Score + What string +} + +// MarshalJSON is used convert a Score object into a JSON representation +func (c Score) MarshalJSON() ([]byte, error) { + return json.Marshal(c.String()) +} + +// String converts a Score into a string +func (c Score) String() string { + switch c { + case High: + return "HIGH" + case Medium: + return "MEDIUM" + case Low: + return "LOW" + } + return "UNDEFINED" +} + +func codeSnippet(file *os.File, start int64, end int64, n ast.Node) (string, error) { + if n == nil { + return "", fmt.Errorf("Invalid AST node provided") + } + + size := (int)(end - start) // Go bug, os.File.Read should return int64 ... + _, err := file.Seek(start, 0) // #nosec + if err != nil { + return "", fmt.Errorf("move to the beginning of file: %v", err) + } + + buf := make([]byte, size) + if nread, err := file.Read(buf); err != nil || nread != size { + return "", fmt.Errorf("Unable to read code") + } + return string(buf), nil +} + +// NewIssue creates a new Issue +func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, confidence Score) *Issue { + var code string + fobj := ctx.FileSet.File(node.Pos()) + name := fobj.Name() + + start, end := fobj.Line(node.Pos()), fobj.Line(node.End()) + line := strconv.Itoa(start) + if start != end { + line = fmt.Sprintf("%d-%d", start, end) + } + + col := strconv.Itoa(fobj.Position(node.Pos()).Column) + + // #nosec + if file, err := os.Open(fobj.Name()); err == nil { + defer file.Close() + s := (int64)(fobj.Position(node.Pos()).Offset) // Go bug, should be int64 + e := (int64)(fobj.Position(node.End()).Offset) // Go bug, should be int64 + code, err = codeSnippet(file, s, e, node) + if err != nil { + code = err.Error() + } + } + + return &Issue{ + File: name, + Line: line, + Col: col, + RuleID: ruleID, + What: desc, + Confidence: confidence, + Severity: severity, + Code: code, + Cwe: IssueToCWE[ruleID], + } +} diff --git a/vendor/github.com/securego/gosec/renovate.json b/vendor/github.com/securego/gosec/v2/renovate.json similarity index 100% rename from vendor/github.com/securego/gosec/renovate.json rename to vendor/github.com/securego/gosec/v2/renovate.json diff --git a/vendor/github.com/securego/gosec/resolve.go b/vendor/github.com/securego/gosec/v2/resolve.go similarity index 100% rename from vendor/github.com/securego/gosec/resolve.go rename to vendor/github.com/securego/gosec/v2/resolve.go diff --git a/vendor/github.com/securego/gosec/rule.go b/vendor/github.com/securego/gosec/v2/rule.go similarity index 100% rename from vendor/github.com/securego/gosec/rule.go rename to vendor/github.com/securego/gosec/v2/rule.go diff --git a/vendor/github.com/securego/gosec/v2/rules/archive.go b/vendor/github.com/securego/gosec/v2/rules/archive.go new file mode 100644 index 00000000000..ca7a46e0b0f --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/rules/archive.go @@ -0,0 +1,60 @@ +package rules + +import ( + "go/ast" + "go/types" + + "github.com/securego/gosec/v2" +) + +type archive struct { + gosec.MetaData + calls gosec.CallList + argType string +} + +func (a *archive) ID() string { + return a.MetaData.ID +} + +// Match inspects AST nodes to determine if the filepath.Joins uses any argument derived from type zip.File +func (a *archive) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { + if node := a.calls.ContainsPkgCallExpr(n, c, false); node != nil { + for _, arg := range node.Args { + var argType types.Type + if selector, ok := arg.(*ast.SelectorExpr); ok { + argType = c.Info.TypeOf(selector.X) + } else if ident, ok := arg.(*ast.Ident); ok { + if ident.Obj != nil && ident.Obj.Kind == ast.Var { + decl := ident.Obj.Decl + if assign, ok := decl.(*ast.AssignStmt); ok { + if selector, ok := assign.Rhs[0].(*ast.SelectorExpr); ok { + argType = c.Info.TypeOf(selector.X) + } + } + } + } + + if argType != nil && argType.String() == a.argType { + return gosec.NewIssue(c, n, a.ID(), a.What, a.Severity, a.Confidence), nil + } + } + } + return nil, nil +} + +// NewArchive creates a new rule which detects the file traversal when extracting zip archives +func NewArchive(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { + calls := gosec.NewCallList() + calls.Add("path/filepath", "Join") + return &archive{ + calls: calls, + argType: "*archive/zip.File", + MetaData: gosec.MetaData{ + ID: id, + Severity: gosec.Medium, + Confidence: gosec.High, + What: "File traversal when extracting zip archive", + }, + }, []ast.Node{(*ast.CallExpr)(nil)} +} diff --git a/vendor/github.com/securego/gosec/rules/bad_defer.go b/vendor/github.com/securego/gosec/v2/rules/bad_defer.go similarity index 97% rename from vendor/github.com/securego/gosec/rules/bad_defer.go rename to vendor/github.com/securego/gosec/v2/rules/bad_defer.go index 9d8b21105e4..3c358806fe7 100644 --- a/vendor/github.com/securego/gosec/rules/bad_defer.go +++ b/vendor/github.com/securego/gosec/v2/rules/bad_defer.go @@ -5,7 +5,7 @@ import ( "go/ast" "strings" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type deferType struct { diff --git a/vendor/github.com/securego/gosec/rules/bind.go b/vendor/github.com/securego/gosec/v2/rules/bind.go similarity index 98% rename from vendor/github.com/securego/gosec/rules/bind.go rename to vendor/github.com/securego/gosec/v2/rules/bind.go index eb2ed05b464..8f6af067ad5 100644 --- a/vendor/github.com/securego/gosec/rules/bind.go +++ b/vendor/github.com/securego/gosec/v2/rules/bind.go @@ -18,7 +18,7 @@ import ( "go/ast" "regexp" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) // Looks for net.Listen("0.0.0.0") or net.Listen(":8080") diff --git a/vendor/github.com/securego/gosec/rules/blacklist.go b/vendor/github.com/securego/gosec/v2/rules/blacklist.go similarity index 99% rename from vendor/github.com/securego/gosec/rules/blacklist.go rename to vendor/github.com/securego/gosec/v2/rules/blacklist.go index 24fbf12211a..9bb73381f72 100644 --- a/vendor/github.com/securego/gosec/rules/blacklist.go +++ b/vendor/github.com/securego/gosec/v2/rules/blacklist.go @@ -18,7 +18,7 @@ import ( "go/ast" "strings" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type blacklistedImport struct { diff --git a/vendor/github.com/securego/gosec/rules/decompression-bomb.go b/vendor/github.com/securego/gosec/v2/rules/decompression-bomb.go similarity index 99% rename from vendor/github.com/securego/gosec/rules/decompression-bomb.go rename to vendor/github.com/securego/gosec/v2/rules/decompression-bomb.go index 9b9caf57fb2..bfc58976384 100644 --- a/vendor/github.com/securego/gosec/rules/decompression-bomb.go +++ b/vendor/github.com/securego/gosec/v2/rules/decompression-bomb.go @@ -18,7 +18,7 @@ import ( "fmt" "go/ast" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type decompressionBombCheck struct { diff --git a/vendor/github.com/securego/gosec/v2/rules/errors.go b/vendor/github.com/securego/gosec/v2/rules/errors.go new file mode 100644 index 00000000000..f16f91d0466 --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/rules/errors.go @@ -0,0 +1,119 @@ +// (c) Copyright 2016 Hewlett Packard Enterprise Development LP +// +// 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 rules + +import ( + "go/ast" + "go/types" + + "github.com/securego/gosec/v2" +) + +type noErrorCheck struct { + gosec.MetaData + whitelist gosec.CallList +} + +func (r *noErrorCheck) ID() string { + return r.MetaData.ID +} + +func returnsError(callExpr *ast.CallExpr, ctx *gosec.Context) int { + if tv := ctx.Info.TypeOf(callExpr); tv != nil { + switch t := tv.(type) { + case *types.Tuple: + for pos := 0; pos < t.Len(); pos++ { + variable := t.At(pos) + if variable != nil && variable.Type().String() == "error" { + return pos + } + } + case *types.Named: + if t.String() == "error" { + return 0 + } + } + } + return -1 +} + +func (r *noErrorCheck) Match(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) { + switch stmt := n.(type) { + case *ast.AssignStmt: + cfg := ctx.Config + if enabled, err := cfg.IsGlobalEnabled(gosec.Audit); err == nil && enabled { + for _, expr := range stmt.Rhs { + if callExpr, ok := expr.(*ast.CallExpr); ok && r.whitelist.ContainsCallExpr(expr, ctx) == nil { + pos := returnsError(callExpr, ctx) + if pos < 0 || pos >= len(stmt.Lhs) { + return nil, nil + } + if id, ok := stmt.Lhs[pos].(*ast.Ident); ok && id.Name == "_" { + return gosec.NewIssue(ctx, n, r.ID(), r.What, r.Severity, r.Confidence), nil + } + } + } + } + case *ast.ExprStmt: + if callExpr, ok := stmt.X.(*ast.CallExpr); ok && r.whitelist.ContainsCallExpr(stmt.X, ctx) == nil { + pos := returnsError(callExpr, ctx) + if pos >= 0 { + return gosec.NewIssue(ctx, n, r.ID(), r.What, r.Severity, r.Confidence), nil + } + } + } + return nil, nil +} + +// NewNoErrorCheck detects if the returned error is unchecked +func NewNoErrorCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { + // TODO(gm) Come up with sensible defaults here. Or flip it to use a + // black list instead. + whitelist := gosec.NewCallList() + whitelist.AddAll("bytes.Buffer", "Write", "WriteByte", "WriteRune", "WriteString") + whitelist.AddAll("fmt", "Print", "Printf", "Println", "Fprint", "Fprintf", "Fprintln") + whitelist.AddAll("strings.Builder", "Write", "WriteByte", "WriteRune", "WriteString") + whitelist.Add("io.PipeWriter", "CloseWithError") + + if configured, ok := conf["G104"]; ok { + if whitelisted, ok := configured.(map[string]interface{}); ok { + for pkg, funcs := range whitelisted { + if funcs, ok := funcs.([]interface{}); ok { + whitelist.AddAll(pkg, toStringSlice(funcs)...) + } + } + } + } + + return &noErrorCheck{ + MetaData: gosec.MetaData{ + ID: id, + Severity: gosec.Low, + Confidence: gosec.High, + What: "Errors unhandled.", + }, + whitelist: whitelist, + }, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ExprStmt)(nil)} +} + +func toStringSlice(values []interface{}) []string { + result := []string{} + for _, value := range values { + if value, ok := value.(string); ok { + result = append(result, value) + } + } + return result +} diff --git a/vendor/github.com/securego/gosec/rules/fileperms.go b/vendor/github.com/securego/gosec/v2/rules/fileperms.go similarity index 99% rename from vendor/github.com/securego/gosec/rules/fileperms.go rename to vendor/github.com/securego/gosec/v2/rules/fileperms.go index b9c0d68ba6f..ffe7b97d593 100644 --- a/vendor/github.com/securego/gosec/rules/fileperms.go +++ b/vendor/github.com/securego/gosec/v2/rules/fileperms.go @@ -19,7 +19,7 @@ import ( "go/ast" "strconv" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type filePermissions struct { diff --git a/vendor/github.com/securego/gosec/v2/rules/hardcoded_credentials.go b/vendor/github.com/securego/gosec/v2/rules/hardcoded_credentials.go new file mode 100644 index 00000000000..6b360c5b9bf --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/rules/hardcoded_credentials.go @@ -0,0 +1,173 @@ +// (c) Copyright 2016 Hewlett Packard Enterprise Development LP +// +// 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 rules + +import ( + "go/ast" + "go/token" + "regexp" + "strconv" + + zxcvbn "github.com/nbutton23/zxcvbn-go" + "github.com/securego/gosec/v2" +) + +type credentials struct { + gosec.MetaData + pattern *regexp.Regexp + entropyThreshold float64 + perCharThreshold float64 + truncate int + ignoreEntropy bool +} + +func (r *credentials) ID() string { + return r.MetaData.ID +} + +func truncate(s string, n int) string { + if n > len(s) { + return s + } + return s[:n] +} + +func (r *credentials) isHighEntropyString(str string) bool { + s := truncate(str, r.truncate) + info := zxcvbn.PasswordStrength(s, []string{}) + entropyPerChar := info.Entropy / float64(len(s)) + return (info.Entropy >= r.entropyThreshold || + (info.Entropy >= (r.entropyThreshold/2) && + entropyPerChar >= r.perCharThreshold)) +} + +func (r *credentials) Match(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) { + switch node := n.(type) { + case *ast.AssignStmt: + return r.matchAssign(node, ctx) + case *ast.ValueSpec: + return r.matchValueSpec(node, ctx) + case *ast.BinaryExpr: + return r.matchEqualityCheck(node, ctx) + } + return nil, nil +} + +func (r *credentials) matchAssign(assign *ast.AssignStmt, ctx *gosec.Context) (*gosec.Issue, error) { + for _, i := range assign.Lhs { + if ident, ok := i.(*ast.Ident); ok { + if r.pattern.MatchString(ident.Name) { + for _, e := range assign.Rhs { + if val, err := gosec.GetString(e); err == nil { + if r.ignoreEntropy || (!r.ignoreEntropy && r.isHighEntropyString(val)) { + return gosec.NewIssue(ctx, assign, r.ID(), r.What, r.Severity, r.Confidence), nil + } + } + } + } + } + } + return nil, nil +} + +func (r *credentials) matchValueSpec(valueSpec *ast.ValueSpec, ctx *gosec.Context) (*gosec.Issue, error) { + for index, ident := range valueSpec.Names { + if r.pattern.MatchString(ident.Name) && valueSpec.Values != nil { + // const foo, bar = "same value" + if len(valueSpec.Values) <= index { + index = len(valueSpec.Values) - 1 + } + if val, err := gosec.GetString(valueSpec.Values[index]); err == nil { + if r.ignoreEntropy || (!r.ignoreEntropy && r.isHighEntropyString(val)) { + return gosec.NewIssue(ctx, valueSpec, r.ID(), r.What, r.Severity, r.Confidence), nil + } + } + } + } + return nil, nil +} + +func (r *credentials) matchEqualityCheck(binaryExpr *ast.BinaryExpr, ctx *gosec.Context) (*gosec.Issue, error) { + if binaryExpr.Op == token.EQL || binaryExpr.Op == token.NEQ { + if ident, ok := binaryExpr.X.(*ast.Ident); ok { + if r.pattern.MatchString(ident.Name) { + if val, err := gosec.GetString(binaryExpr.Y); err == nil { + if r.ignoreEntropy || (!r.ignoreEntropy && r.isHighEntropyString(val)) { + return gosec.NewIssue(ctx, binaryExpr, r.ID(), r.What, r.Severity, r.Confidence), nil + } + } + } + } + } + return nil, nil +} + +// NewHardcodedCredentials attempts to find high entropy string constants being +// assigned to variables that appear to be related to credentials. +func NewHardcodedCredentials(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { + pattern := `(?i)passwd|pass|password|pwd|secret|token` + entropyThreshold := 80.0 + perCharThreshold := 3.0 + ignoreEntropy := false + var truncateString = 16 + if val, ok := conf["G101"]; ok { + conf := val.(map[string]interface{}) + if configPattern, ok := conf["pattern"]; ok { + if cfgPattern, ok := configPattern.(string); ok { + pattern = cfgPattern + } + } + if configIgnoreEntropy, ok := conf["ignore_entropy"]; ok { + if cfgIgnoreEntropy, ok := configIgnoreEntropy.(bool); ok { + ignoreEntropy = cfgIgnoreEntropy + } + } + if configEntropyThreshold, ok := conf["entropy_threshold"]; ok { + if cfgEntropyThreshold, ok := configEntropyThreshold.(string); ok { + if parsedNum, err := strconv.ParseFloat(cfgEntropyThreshold, 64); err == nil { + entropyThreshold = parsedNum + } + } + } + if configCharThreshold, ok := conf["per_char_threshold"]; ok { + if cfgCharThreshold, ok := configCharThreshold.(string); ok { + if parsedNum, err := strconv.ParseFloat(cfgCharThreshold, 64); err == nil { + perCharThreshold = parsedNum + } + } + } + if configTruncate, ok := conf["truncate"]; ok { + if cfgTruncate, ok := configTruncate.(string); ok { + if parsedInt, err := strconv.Atoi(cfgTruncate); err == nil { + truncateString = parsedInt + } + } + } + } + + return &credentials{ + pattern: regexp.MustCompile(pattern), + entropyThreshold: entropyThreshold, + perCharThreshold: perCharThreshold, + ignoreEntropy: ignoreEntropy, + truncate: truncateString, + MetaData: gosec.MetaData{ + ID: id, + What: "Potential hardcoded credentials", + Confidence: gosec.Low, + Severity: gosec.High, + }, + }, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ValueSpec)(nil), (*ast.BinaryExpr)(nil)} +} diff --git a/vendor/github.com/securego/gosec/v2/rules/implicit_aliasing.go b/vendor/github.com/securego/gosec/v2/rules/implicit_aliasing.go new file mode 100644 index 00000000000..65c7ae36daf --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/rules/implicit_aliasing.go @@ -0,0 +1,116 @@ +package rules + +import ( + "fmt" + "github.com/securego/gosec/v2" + "go/ast" + "go/token" +) + +type implicitAliasing struct { + gosec.MetaData + aliases map[*ast.Object]struct{} + rightBrace token.Pos + acceptableAlias []*ast.UnaryExpr +} + +func (r *implicitAliasing) ID() string { + return r.MetaData.ID +} + +func containsUnary(exprs []*ast.UnaryExpr, expr *ast.UnaryExpr) bool { + for _, e := range exprs { + if e == expr { + return true + } + } + return false +} + +func (r *implicitAliasing) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { + switch node := n.(type) { + case *ast.RangeStmt: + // When presented with a range statement, get the underlying Object bound to + // by assignment and add it to our set (r.aliases) of objects to check for. + if key, ok := node.Value.(*ast.Ident); ok { + if assignment, ok := key.Obj.Decl.(*ast.AssignStmt); ok { + if len(assignment.Lhs) < 2 { + return nil, nil + } + + if object, ok := assignment.Lhs[1].(*ast.Ident); ok { + r.aliases[object.Obj] = struct{}{} + + if r.rightBrace < node.Body.Rbrace { + r.rightBrace = node.Body.Rbrace + } + } + } + } + case *ast.UnaryExpr: + // If this unary expression is outside of the last range statement we were looking at + // then clear the list of objects we're concerned about because they're no longer in + // scope + if node.Pos() > r.rightBrace { + r.aliases = make(map[*ast.Object]struct{}) + r.acceptableAlias = make([]*ast.UnaryExpr, 0) + } + + // Short circuit logic to skip checking aliases if we have nothing to check against. + if len(r.aliases) == 0 { + return nil, nil + } + + // If this unary is at the top level of a return statement then it is okay-- + // see *ast.ReturnStmt comment below. + if containsUnary(r.acceptableAlias, node) { + return nil, nil + } + + // If we find a unary op of & (reference) of an object within r.aliases, complain. + if ident, ok := node.X.(*ast.Ident); ok && node.Op.String() == "&" { + if _, contains := r.aliases[ident.Obj]; contains { + return gosec.NewIssue(c, n, r.ID(), r.What, r.Severity, r.Confidence), nil + } + } + case *ast.ReturnStmt: + // Returning a rangeStmt yielded value is acceptable since only one value will be returned + for _, item := range node.Results { + if unary, ok := item.(*ast.UnaryExpr); ok && unary.Op.String() == "&" { + r.acceptableAlias = append(r.acceptableAlias, unary) + } + } + } + + return nil, nil +} + +// NewImplicitAliasing detects implicit memory aliasing of type: for blah := SomeCall() {... SomeOtherCall(&blah) ...} +func NewImplicitAliasing(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { + return &implicitAliasing{ + aliases: make(map[*ast.Object]struct{}), + rightBrace: token.NoPos, + acceptableAlias: make([]*ast.UnaryExpr, 0), + MetaData: gosec.MetaData{ + ID: id, + Severity: gosec.Medium, + Confidence: gosec.Medium, + What: fmt.Sprintf("Implicit memory aliasing in for loop."), + }, + }, []ast.Node{(*ast.RangeStmt)(nil), (*ast.UnaryExpr)(nil), (*ast.ReturnStmt)(nil)} +} + +/* +This rule is prone to flag false positives. + +Within GoSec, the rule is just an AST match-- there are a handful of other +implementation strategies which might lend more nuance to the rule at the +cost of allowing false negatives. + +From a tooling side, I'd rather have this rule flag false positives than +potentially have some false negatives-- especially if the sentiment of this +rule (as I understand it, and Go) is that referencing a rangeStmt-yielded +value is kinda strange and does not have a strongly justified use case. + +Which is to say-- a false positive _should_ just be changed. +*/ diff --git a/vendor/github.com/securego/gosec/rules/integer_overflow.go b/vendor/github.com/securego/gosec/v2/rules/integer_overflow.go similarity index 98% rename from vendor/github.com/securego/gosec/rules/integer_overflow.go rename to vendor/github.com/securego/gosec/v2/rules/integer_overflow.go index 311ff52907a..dfcda94a8f8 100644 --- a/vendor/github.com/securego/gosec/rules/integer_overflow.go +++ b/vendor/github.com/securego/gosec/v2/rules/integer_overflow.go @@ -18,7 +18,7 @@ import ( "fmt" "go/ast" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type integerOverflowCheck struct { diff --git a/vendor/github.com/securego/gosec/rules/pprof.go b/vendor/github.com/securego/gosec/v2/rules/pprof.go similarity index 96% rename from vendor/github.com/securego/gosec/rules/pprof.go rename to vendor/github.com/securego/gosec/v2/rules/pprof.go index 9f5e8cdb39c..4c99af7523c 100644 --- a/vendor/github.com/securego/gosec/rules/pprof.go +++ b/vendor/github.com/securego/gosec/v2/rules/pprof.go @@ -3,7 +3,7 @@ package rules import ( "go/ast" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type pprofCheck struct { diff --git a/vendor/github.com/securego/gosec/v2/rules/rand.go b/vendor/github.com/securego/gosec/v2/rules/rand.go new file mode 100644 index 00000000000..08c28fcad77 --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/rules/rand.go @@ -0,0 +1,55 @@ +// (c) Copyright 2016 Hewlett Packard Enterprise Development LP +// +// 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 rules + +import ( + "go/ast" + + "github.com/securego/gosec/v2" +) + +type weakRand struct { + gosec.MetaData + funcNames []string + packagePath string +} + +func (w *weakRand) ID() string { + return w.MetaData.ID +} + +func (w *weakRand) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { + for _, funcName := range w.funcNames { + if _, matched := gosec.MatchCallByPackage(n, c, w.packagePath, funcName); matched { + return gosec.NewIssue(c, n, w.ID(), w.What, w.Severity, w.Confidence), nil + } + } + + return nil, nil +} + +// NewWeakRandCheck detects the use of random number generator that isn't cryptographically secure +func NewWeakRandCheck(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { + return &weakRand{ + funcNames: []string{"Read", "Int"}, + packagePath: "math/rand", + MetaData: gosec.MetaData{ + ID: id, + Severity: gosec.High, + Confidence: gosec.Medium, + What: "Use of weak random number generator (math/rand instead of crypto/rand)", + }, + }, []ast.Node{(*ast.CallExpr)(nil)} +} diff --git a/vendor/github.com/securego/gosec/rules/readfile.go b/vendor/github.com/securego/gosec/v2/rules/readfile.go similarity index 99% rename from vendor/github.com/securego/gosec/rules/readfile.go rename to vendor/github.com/securego/gosec/v2/rules/readfile.go index 6464360a1c5..a52f7425f9f 100644 --- a/vendor/github.com/securego/gosec/rules/readfile.go +++ b/vendor/github.com/securego/gosec/v2/rules/readfile.go @@ -18,7 +18,7 @@ import ( "go/ast" "go/types" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type readfile struct { diff --git a/vendor/github.com/securego/gosec/rules/rsa.go b/vendor/github.com/securego/gosec/v2/rules/rsa.go similarity index 98% rename from vendor/github.com/securego/gosec/rules/rsa.go rename to vendor/github.com/securego/gosec/v2/rules/rsa.go index 1ceee37b408..f2ed5db53dc 100644 --- a/vendor/github.com/securego/gosec/rules/rsa.go +++ b/vendor/github.com/securego/gosec/v2/rules/rsa.go @@ -18,7 +18,7 @@ import ( "fmt" "go/ast" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type weakKeyStrength struct { diff --git a/vendor/github.com/securego/gosec/rules/rulelist.go b/vendor/github.com/securego/gosec/v2/rules/rulelist.go similarity index 97% rename from vendor/github.com/securego/gosec/rules/rulelist.go rename to vendor/github.com/securego/gosec/v2/rules/rulelist.go index c45f5175e64..06e1dfb97d3 100644 --- a/vendor/github.com/securego/gosec/rules/rulelist.go +++ b/vendor/github.com/securego/gosec/v2/rules/rulelist.go @@ -14,7 +14,7 @@ package rules -import "github.com/securego/gosec" +import "github.com/securego/gosec/v2" // RuleDefinition contains the description of a rule and a mechanism to // create it. @@ -96,6 +96,9 @@ func Generate(filters ...RuleFilter) RuleList { {"G503", "Import blacklist: crypto/rc4", NewBlacklistedImportRC4}, {"G504", "Import blacklist: net/http/cgi", NewBlacklistedImportCGI}, {"G505", "Import blacklist: crypto/sha1", NewBlacklistedImportSHA1}, + + // memory safety + {"G601", "Implicit memory aliasing in RangeStmt", NewImplicitAliasing}, } ruleMap := make(map[string]RuleDefinition) diff --git a/vendor/github.com/securego/gosec/v2/rules/sql.go b/vendor/github.com/securego/gosec/v2/rules/sql.go new file mode 100644 index 00000000000..3279a340000 --- /dev/null +++ b/vendor/github.com/securego/gosec/v2/rules/sql.go @@ -0,0 +1,219 @@ +// (c) Copyright 2016 Hewlett Packard Enterprise Development LP +// +// 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 rules + +import ( + "go/ast" + "regexp" + + "github.com/securego/gosec/v2" +) + +type sqlStatement struct { + gosec.MetaData + + // Contains a list of patterns which must all match for the rule to match. + patterns []*regexp.Regexp +} + +func (s *sqlStatement) ID() string { + return s.MetaData.ID +} + +// See if the string matches the patterns for the statement. +func (s *sqlStatement) MatchPatterns(str string) bool { + for _, pattern := range s.patterns { + if !pattern.MatchString(str) { + return false + } + } + return true +} + +type sqlStrConcat struct { + sqlStatement +} + +func (s *sqlStrConcat) ID() string { + return s.MetaData.ID +} + +// see if we can figure out what it is +func (s *sqlStrConcat) checkObject(n *ast.Ident, c *gosec.Context) bool { + if n.Obj != nil { + return n.Obj.Kind != ast.Var && n.Obj.Kind != ast.Fun + } + + // Try to resolve unresolved identifiers using other files in same package + for _, file := range c.PkgFiles { + if node, ok := file.Scope.Objects[n.String()]; ok { + return node.Kind != ast.Var && node.Kind != ast.Fun + } + } + return false +} + +// Look for "SELECT * FROM table WHERE " + " ' OR 1=1" +func (s *sqlStrConcat) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { + if node, ok := n.(*ast.BinaryExpr); ok { + if start, ok := node.X.(*ast.BasicLit); ok { + if str, e := gosec.GetString(start); e == nil { + if !s.MatchPatterns(str) { + return nil, nil + } + if _, ok := node.Y.(*ast.BasicLit); ok { + return nil, nil // string cat OK + } + if second, ok := node.Y.(*ast.Ident); ok && s.checkObject(second, c) { + return nil, nil + } + return gosec.NewIssue(c, n, s.ID(), s.What, s.Severity, s.Confidence), nil + } + } + } + return nil, nil +} + +// NewSQLStrConcat looks for cases where we are building SQL strings via concatenation +func NewSQLStrConcat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { + return &sqlStrConcat{ + sqlStatement: sqlStatement{ + patterns: []*regexp.Regexp{ + regexp.MustCompile(`(?)(SELECT|DELETE|INSERT|UPDATE|INTO|FROM|WHERE) `), + }, + MetaData: gosec.MetaData{ + ID: id, + Severity: gosec.Medium, + Confidence: gosec.High, + What: "SQL string concatenation", + }, + }, + }, []ast.Node{(*ast.BinaryExpr)(nil)} +} + +type sqlStrFormat struct { + sqlStatement + calls gosec.CallList + noIssue gosec.CallList + noIssueQuoted gosec.CallList +} + +// see if we can figure out what it is +func (s *sqlStrFormat) constObject(e ast.Expr, c *gosec.Context) bool { + n, ok := e.(*ast.Ident) + if !ok { + return false + } + + if n.Obj != nil { + return n.Obj.Kind == ast.Con + } + + // Try to resolve unresolved identifiers using other files in same package + for _, file := range c.PkgFiles { + if node, ok := file.Scope.Objects[n.String()]; ok { + return node.Kind == ast.Con + } + } + return false +} + +// Looks for "fmt.Sprintf("SELECT * FROM foo where '%s', userInput)" +func (s *sqlStrFormat) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) { + + // argIndex changes the function argument which gets matched to the regex + argIndex := 0 + + // TODO(gm) improve confidence if database/sql is being used + if node := s.calls.ContainsPkgCallExpr(n, c, false); node != nil { + // if the function is fmt.Fprintf, search for SQL statement in Args[1] instead + if sel, ok := node.Fun.(*ast.SelectorExpr); ok { + if sel.Sel.Name == "Fprintf" { + // if os.Stderr or os.Stdout is in Arg[0], mark as no issue + if arg, ok := node.Args[0].(*ast.SelectorExpr); ok { + if ident, ok := arg.X.(*ast.Ident); ok { + if s.noIssue.Contains(ident.Name, arg.Sel.Name) { + return nil, nil + } + } + } + // the function is Fprintf so set argIndex = 1 + argIndex = 1 + } + } + + // no formatter + if len(node.Args) == 0 { + return nil, nil + } + + var formatter string + + // concats callexpr arg strings together if needed before regex evaluation + if argExpr, ok := node.Args[argIndex].(*ast.BinaryExpr); ok { + if fullStr, ok := gosec.ConcatString(argExpr); ok { + formatter = fullStr + } + } else if arg, e := gosec.GetString(node.Args[argIndex]); e == nil { + formatter = arg + } + if len(formatter) <= 0 { + return nil, nil + } + + // If all formatter args are quoted or constant, then the SQL construction is safe + if argIndex+1 < len(node.Args) { + allSafe := true + for _, arg := range node.Args[argIndex+1:] { + if n := s.noIssueQuoted.ContainsPkgCallExpr(arg, c, true); n == nil && !s.constObject(arg, c) { + allSafe = false + break + } + } + if allSafe { + return nil, nil + } + } + if s.MatchPatterns(formatter) { + return gosec.NewIssue(c, n, s.ID(), s.What, s.Severity, s.Confidence), nil + } + } + return nil, nil +} + +// NewSQLStrFormat looks for cases where we're building SQL query strings using format strings +func NewSQLStrFormat(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { + rule := &sqlStrFormat{ + calls: gosec.NewCallList(), + noIssue: gosec.NewCallList(), + noIssueQuoted: gosec.NewCallList(), + sqlStatement: sqlStatement{ + patterns: []*regexp.Regexp{ + regexp.MustCompile("(?)(SELECT|DELETE|INSERT|UPDATE|INTO|FROM|WHERE) "), + regexp.MustCompile("%[^bdoxXfFp]"), + }, + MetaData: gosec.MetaData{ + ID: id, + Severity: gosec.Medium, + Confidence: gosec.High, + What: "SQL string formatting", + }, + }, + } + rule.calls.AddAll("fmt", "Sprint", "Sprintf", "Sprintln", "Fprintf") + rule.noIssue.AddAll("os", "Stdout", "Stderr") + rule.noIssueQuoted.Add("github.com/lib/pq", "QuoteIdentifier") + return rule, []ast.Node{(*ast.CallExpr)(nil)} +} diff --git a/vendor/github.com/securego/gosec/rules/ssh.go b/vendor/github.com/securego/gosec/v2/rules/ssh.go similarity index 96% rename from vendor/github.com/securego/gosec/rules/ssh.go rename to vendor/github.com/securego/gosec/v2/rules/ssh.go index 7496b5f89b2..01f37da5106 100644 --- a/vendor/github.com/securego/gosec/rules/ssh.go +++ b/vendor/github.com/securego/gosec/v2/rules/ssh.go @@ -3,7 +3,7 @@ package rules import ( "go/ast" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type sshHostKey struct { diff --git a/vendor/github.com/securego/gosec/rules/ssrf.go b/vendor/github.com/securego/gosec/v2/rules/ssrf.go similarity index 98% rename from vendor/github.com/securego/gosec/rules/ssrf.go rename to vendor/github.com/securego/gosec/v2/rules/ssrf.go index 41b53865742..86bb8278d3c 100644 --- a/vendor/github.com/securego/gosec/rules/ssrf.go +++ b/vendor/github.com/securego/gosec/v2/rules/ssrf.go @@ -4,7 +4,7 @@ import ( "go/ast" "go/types" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type ssrf struct { diff --git a/vendor/github.com/securego/gosec/rules/subproc.go b/vendor/github.com/securego/gosec/v2/rules/subproc.go similarity index 98% rename from vendor/github.com/securego/gosec/rules/subproc.go rename to vendor/github.com/securego/gosec/v2/rules/subproc.go index 536e99dc458..30c32cc03a5 100644 --- a/vendor/github.com/securego/gosec/rules/subproc.go +++ b/vendor/github.com/securego/gosec/v2/rules/subproc.go @@ -18,7 +18,7 @@ import ( "go/ast" "go/types" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type subprocess struct { diff --git a/vendor/github.com/securego/gosec/rules/tempfiles.go b/vendor/github.com/securego/gosec/v2/rules/tempfiles.go similarity index 98% rename from vendor/github.com/securego/gosec/rules/tempfiles.go rename to vendor/github.com/securego/gosec/v2/rules/tempfiles.go index 4adafd10f54..36f0f979bca 100644 --- a/vendor/github.com/securego/gosec/rules/tempfiles.go +++ b/vendor/github.com/securego/gosec/v2/rules/tempfiles.go @@ -18,7 +18,7 @@ import ( "go/ast" "regexp" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type badTempFile struct { diff --git a/vendor/github.com/securego/gosec/rules/templates.go b/vendor/github.com/securego/gosec/v2/rules/templates.go similarity index 98% rename from vendor/github.com/securego/gosec/rules/templates.go rename to vendor/github.com/securego/gosec/v2/rules/templates.go index 3c663f15de0..81924090531 100644 --- a/vendor/github.com/securego/gosec/rules/templates.go +++ b/vendor/github.com/securego/gosec/v2/rules/templates.go @@ -17,7 +17,7 @@ package rules import ( "go/ast" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type templateCheck struct { diff --git a/vendor/github.com/securego/gosec/rules/tls.go b/vendor/github.com/securego/gosec/v2/rules/tls.go similarity index 99% rename from vendor/github.com/securego/gosec/rules/tls.go rename to vendor/github.com/securego/gosec/v2/rules/tls.go index d4b7fa2be7c..fab9ee16486 100644 --- a/vendor/github.com/securego/gosec/rules/tls.go +++ b/vendor/github.com/securego/gosec/v2/rules/tls.go @@ -20,7 +20,7 @@ import ( "fmt" "go/ast" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type insecureConfigTLS struct { diff --git a/vendor/github.com/securego/gosec/rules/tls_config.go b/vendor/github.com/securego/gosec/v2/rules/tls_config.go similarity index 98% rename from vendor/github.com/securego/gosec/rules/tls_config.go rename to vendor/github.com/securego/gosec/v2/rules/tls_config.go index 42ec85db41b..ff4f3fe2eb1 100644 --- a/vendor/github.com/securego/gosec/rules/tls_config.go +++ b/vendor/github.com/securego/gosec/v2/rules/tls_config.go @@ -3,7 +3,7 @@ package rules import ( "go/ast" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) // NewModernTLSCheck creates a check for Modern TLS ciphers diff --git a/vendor/github.com/securego/gosec/rules/unsafe.go b/vendor/github.com/securego/gosec/v2/rules/unsafe.go similarity index 97% rename from vendor/github.com/securego/gosec/rules/unsafe.go rename to vendor/github.com/securego/gosec/v2/rules/unsafe.go index f4a38be3d44..88a298fb521 100644 --- a/vendor/github.com/securego/gosec/rules/unsafe.go +++ b/vendor/github.com/securego/gosec/v2/rules/unsafe.go @@ -17,7 +17,7 @@ package rules import ( "go/ast" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type usingUnsafe struct { diff --git a/vendor/github.com/securego/gosec/rules/weakcrypto.go b/vendor/github.com/securego/gosec/v2/rules/weakcrypto.go similarity index 98% rename from vendor/github.com/securego/gosec/rules/weakcrypto.go rename to vendor/github.com/securego/gosec/v2/rules/weakcrypto.go index 60c63aa84d6..0e45393db60 100644 --- a/vendor/github.com/securego/gosec/rules/weakcrypto.go +++ b/vendor/github.com/securego/gosec/v2/rules/weakcrypto.go @@ -17,7 +17,7 @@ package rules import ( "go/ast" - "github.com/securego/gosec" + "github.com/securego/gosec/v2" ) type usesWeakCryptography struct { diff --git a/vendor/github.com/shazow/go-diff/LICENSE b/vendor/github.com/shazow/go-diff/LICENSE new file mode 100644 index 00000000000..85e1e4b33ad --- /dev/null +++ b/vendor/github.com/shazow/go-diff/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andrey Petrov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/vendor/github.com/shazow/go-diff/difflib/differ.go b/vendor/github.com/shazow/go-diff/difflib/differ.go new file mode 100644 index 00000000000..43dc84d9a79 --- /dev/null +++ b/vendor/github.com/shazow/go-diff/difflib/differ.go @@ -0,0 +1,39 @@ +// This package implements the diff.Differ interface using github.com/mb0/diff as a backend. +package difflib + +import ( + "io" + "io/ioutil" + + "github.com/pmezard/go-difflib/difflib" +) + +type differ struct{} + +// New returns an implementation of diff.Differ using mb0diff as the backend. +func New() *differ { + return &differ{} +} + +// Diff consumes the entire reader streams into memory before generating a diff +// which then gets filled into the buffer. This implementation stores and +// manipulates all three values in memory. +func (diff *differ) Diff(out io.Writer, a io.ReadSeeker, b io.ReadSeeker) error { + var src, dst []byte + var err error + + if src, err = ioutil.ReadAll(a); err != nil { + return err + } + if dst, err = ioutil.ReadAll(b); err != nil { + return err + } + + d := difflib.UnifiedDiff{ + A: difflib.SplitLines(string(src)), + B: difflib.SplitLines(string(dst)), + Context: 3, + } + + return difflib.WriteUnifiedDiff(out, d) +} diff --git a/vendor/github.com/sirupsen/logrus/.golangci.yml b/vendor/github.com/sirupsen/logrus/.golangci.yml new file mode 100644 index 00000000000..65dc2850377 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/.golangci.yml @@ -0,0 +1,40 @@ +run: + # do not run on test files yet + tests: false + +# all available settings of specific linters +linters-settings: + errcheck: + # report about not checking of errors in type assetions: `a := b.(MyStruct)`; + # default is false: such cases aren't reported by default. + check-type-assertions: false + + # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; + # default is false: such cases aren't reported by default. + check-blank: false + + lll: + line-length: 100 + tab-width: 4 + + prealloc: + simple: false + range-loops: false + for-loops: false + + whitespace: + multi-if: false # Enforces newlines (or comments) after every multi-line if statement + multi-func: false # Enforces newlines (or comments) after every multi-line function signature + +linters: + enable: + - megacheck + - govet + disable: + - maligned + - prealloc + disable-all: false + presets: + - bugs + - unused + fast: false diff --git a/vendor/github.com/sirupsen/logrus/.travis.yml b/vendor/github.com/sirupsen/logrus/.travis.yml index 848938a6d4e..5e20aa4140c 100644 --- a/vendor/github.com/sirupsen/logrus/.travis.yml +++ b/vendor/github.com/sirupsen/logrus/.travis.yml @@ -4,21 +4,13 @@ git: depth: 1 env: - GO111MODULE=on - - GO111MODULE=off -go: [ 1.11.x, 1.12.x ] -os: [ linux, osx ] -matrix: - exclude: - - go: 1.12.x - env: GO111MODULE=off - - go: 1.11.x - os: osx +go: [1.13.x, 1.14.x] +os: [linux, osx] install: - ./travis/install.sh - - if [[ "$GO111MODULE" == "on" ]]; then go mod download; fi - - if [[ "$GO111MODULE" == "off" ]]; then go get github.com/stretchr/testify/assert golang.org/x/sys/unix github.com/konsorten/go-windows-terminal-sequences; fi script: - ./travis/cross_build.sh + - ./travis/lint.sh - export GOMAXPROCS=4 - export GORACE=halt_on_error=1 - go test -race -v ./... diff --git a/vendor/github.com/sirupsen/logrus/CHANGELOG.md b/vendor/github.com/sirupsen/logrus/CHANGELOG.md index 51a7ab0cab9..584026d67ca 100644 --- a/vendor/github.com/sirupsen/logrus/CHANGELOG.md +++ b/vendor/github.com/sirupsen/logrus/CHANGELOG.md @@ -1,9 +1,32 @@ +# 1.6.0 +Fixes: + * end of line cleanup + * revert the entry concurrency bug fix whic leads to deadlock under some circumstances + * update dependency on go-windows-terminal-sequences to fix a crash with go 1.14 + +Features: + * add an option to the `TextFormatter` to completely disable fields quoting + +# 1.5.0 +Code quality: + * add golangci linter run on travis + +Fixes: + * add mutex for hooks concurrent access on `Entry` data + * caller function field for go1.14 + * fix build issue for gopherjs target + +Feature: + * add an hooks/writer sub-package whose goal is to split output on different stream depending on the trace level + * add a `DisableHTMLEscape` option in the `JSONFormatter` + * add `ForceQuote` and `PadLevelText` options in the `TextFormatter` + # 1.4.2 * Fixes build break for plan9, nacl, solaris # 1.4.1 This new release introduces: * Enhance TextFormatter to not print caller information when they are empty (#944) - * Remove dependency on golang.org/x/crypto (#932, #943) + * Remove dependency on golang.org/x/crypto (#932, #943) Fixes: * Fix Entry.WithContext method to return a copy of the initial entry (#941) @@ -11,7 +34,7 @@ Fixes: # 1.4.0 This new release introduces: * Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848). - * Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter (#909, #911) + * Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter` (#909, #911) * Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919). Fixes: diff --git a/vendor/github.com/sirupsen/logrus/README.md b/vendor/github.com/sirupsen/logrus/README.md index a4796eb07d4..5796706dbfa 100644 --- a/vendor/github.com/sirupsen/logrus/README.md +++ b/vendor/github.com/sirupsen/logrus/README.md @@ -1,8 +1,28 @@ -# Logrus :walrus: [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus) +# Logrus :walrus: [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus) Logrus is a structured logger for Go (golang), completely API compatible with the standard library logger. +**Logrus is in maintenance-mode.** We will not be introducing new features. It's +simply too hard to do in a way that won't break many people's projects, which is +the last thing you want from your Logging library (again...). + +This does not mean Logrus is dead. Logrus will continue to be maintained for +security, (backwards compatible) bug fixes, and performance (where we are +limited by the interface). + +I believe Logrus' biggest contribution is to have played a part in today's +widespread use of structured logging in Golang. There doesn't seem to be a +reason to do a major, breaking iteration into Logrus V2, since the fantastic Go +community has built those independently. Many fantastic alternatives have sprung +up. Logrus would look like those, had it been re-designed with what we know +about structured logging in Go today. Check out, for example, +[Zerolog][zerolog], [Zap][zap], and [Apex][apex]. + +[zerolog]: https://github.com/rs/zerolog +[zap]: https://github.com/uber-go/zap +[apex]: https://github.com/apex/log + **Seeing weird case-sensitive problems?** It's in the past been possible to import Logrus as both upper- and lower-case. Due to the Go package environment, this caused issues in the community and we needed a standard. Some environments @@ -15,11 +35,6 @@ comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437). For an in-depth explanation of the casing issue, see [this comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276). -**Are you interested in assisting in maintaining Logrus?** Currently I have a -lot of obligations, and I am unable to provide Logrus with the maintainership it -needs. If you'd like to help, please reach out to me at `simon at author's -username dot com`. - Nicely color-coded in development (when a TTY is attached, otherwise just plain text): @@ -187,7 +202,7 @@ func main() { log.Out = os.Stdout // You could set this to any `io.Writer` such as a file - // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666) + // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) // if err == nil { // log.Out = file // } else { @@ -272,7 +287,7 @@ func init() { ``` Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). -A list of currently known of service hook can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks) +A list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks) #### Level logging @@ -354,6 +369,7 @@ The built-in logging formatters are: [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). * When colors are enabled, levels are truncated to 4 characters by default. To disable truncation set the `DisableLevelTruncation` field to `true`. + * When outputting to a TTY, it's often helpful to visually scan down a column where all the levels are the same width. Setting the `PadLevelText` field to `true` enables this behavior, by adding padding to the level text. * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). * `logrus.JSONFormatter`. Logs fields as JSON. * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). @@ -364,8 +380,10 @@ Third party logging formatters: * [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html). * [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. * [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. -* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. +* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the Power of Zalgo. * [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure. +* [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Sava log to files. +* [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added. You can define your formatter by implementing the `Formatter` interface, requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a @@ -430,14 +448,14 @@ entries. It should not be a feature of the application-level logger. | Tool | Description | | ---- | ----------- | -|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.| +|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will be generated with different configs in different environments.| |[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | #### Testing Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: -* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook +* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just adds the `test` hook * a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): ```go @@ -465,7 +483,7 @@ func TestSomething(t*testing.T){ Logrus can register one or more functions that will be called when any `fatal` level message is logged. The registered handlers will be executed before -logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need +logrus performs an `os.Exit(1)`. This behavior may be helpful if callers need to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. ``` @@ -490,6 +508,6 @@ Situation when locking is not needed includes: 1) logger.Out is protected by locks. - 2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing) + 2) logger.Out is an os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allows multi-thread/multi-process writing) (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) diff --git a/vendor/github.com/sirupsen/logrus/appveyor.yml b/vendor/github.com/sirupsen/logrus/appveyor.yml index 96c2ce15f84..df9d65c3a5b 100644 --- a/vendor/github.com/sirupsen/logrus/appveyor.yml +++ b/vendor/github.com/sirupsen/logrus/appveyor.yml @@ -1,14 +1,14 @@ -version: "{build}" -platform: x64 -clone_folder: c:\gopath\src\github.com\sirupsen\logrus -environment: - GOPATH: c:\gopath -branches: - only: - - master -install: - - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% - - go version -build_script: - - go get -t - - go test +version: "{build}" +platform: x64 +clone_folder: c:\gopath\src\github.com\sirupsen\logrus +environment: + GOPATH: c:\gopath +branches: + only: + - master +install: + - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% + - go version +build_script: + - go get -t + - go test diff --git a/vendor/github.com/sirupsen/logrus/entry.go b/vendor/github.com/sirupsen/logrus/entry.go index 63e25583cb0..f6e062a3466 100644 --- a/vendor/github.com/sirupsen/logrus/entry.go +++ b/vendor/github.com/sirupsen/logrus/entry.go @@ -85,10 +85,15 @@ func NewEntry(logger *Logger) *Entry { } } +// Returns the bytes representation of this entry from the formatter. +func (entry *Entry) Bytes() ([]byte, error) { + return entry.Logger.Formatter.Format(entry) +} + // Returns the string representation from the reader and ultimately the // formatter. func (entry *Entry) String() (string, error) { - serialized, err := entry.Logger.Formatter.Format(entry) + serialized, err := entry.Bytes() if err != nil { return "", err } @@ -103,7 +108,11 @@ func (entry *Entry) WithError(err error) *Entry { // Add a context to the Entry. func (entry *Entry) WithContext(ctx context.Context) *Entry { - return &Entry{Logger: entry.Logger, Data: entry.Data, Time: entry.Time, err: entry.err, Context: ctx} + dataCopy := make(Fields, len(entry.Data)) + for k, v := range entry.Data { + dataCopy[k] = v + } + return &Entry{Logger: entry.Logger, Data: dataCopy, Time: entry.Time, err: entry.err, Context: ctx} } // Add a single field to the Entry. @@ -144,7 +153,11 @@ func (entry *Entry) WithFields(fields Fields) *Entry { // Overrides the time of the Entry. func (entry *Entry) WithTime(t time.Time) *Entry { - return &Entry{Logger: entry.Logger, Data: entry.Data, Time: t, err: entry.err, Context: entry.Context} + dataCopy := make(Fields, len(entry.Data)) + for k, v := range entry.Data { + dataCopy[k] = v + } + return &Entry{Logger: entry.Logger, Data: dataCopy, Time: t, err: entry.err, Context: entry.Context} } // getPackageName reduces a fully qualified function name to the package name @@ -165,15 +178,20 @@ func getPackageName(f string) string { // getCaller retrieves the name of the first non-logrus calling function func getCaller() *runtime.Frame { - // cache this package's fully-qualified name callerInitOnce.Do(func() { - pcs := make([]uintptr, 2) + pcs := make([]uintptr, maximumCallerDepth) _ = runtime.Callers(0, pcs) - logrusPackage = getPackageName(runtime.FuncForPC(pcs[1]).Name()) - // now that we have the cache, we can skip a minimum count of known-logrus functions - // XXX this is dubious, the number of frames may vary + // dynamic get the package name and the minimum caller depth + for i := 0; i < maximumCallerDepth; i++ { + funcName := runtime.FuncForPC(pcs[i]).Name() + if strings.Contains(funcName, "getCaller") { + logrusPackage = getPackageName(funcName) + break + } + } + minimumCallerDepth = knownLogrusFrames }) @@ -187,7 +205,7 @@ func getCaller() *runtime.Frame { // If the caller isn't part of this package, we're done if pkg != logrusPackage { - return &f + return &f //nolint:scopelint } } @@ -217,9 +235,11 @@ func (entry Entry) log(level Level, msg string) { entry.Level = level entry.Message = msg + entry.Logger.mu.Lock() if entry.Logger.ReportCaller { entry.Caller = getCaller() } + entry.Logger.mu.Unlock() entry.fireHooks() @@ -255,11 +275,10 @@ func (entry *Entry) write() { serialized, err := entry.Logger.Formatter.Format(entry) if err != nil { fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) - } else { - _, err = entry.Logger.Out.Write(serialized) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) - } + return + } + if _, err = entry.Logger.Out.Write(serialized); err != nil { + fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) } } diff --git a/vendor/github.com/sirupsen/logrus/exported.go b/vendor/github.com/sirupsen/logrus/exported.go index 62fc2f2193c..42b04f6c809 100644 --- a/vendor/github.com/sirupsen/logrus/exported.go +++ b/vendor/github.com/sirupsen/logrus/exported.go @@ -80,7 +80,7 @@ func WithFields(fields Fields) *Entry { return std.WithFields(fields) } -// WithTime creats an entry from the standard logger and overrides the time of +// WithTime creates an entry from the standard logger and overrides the time of // logs generated with it. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal diff --git a/vendor/github.com/sirupsen/logrus/go.mod b/vendor/github.com/sirupsen/logrus/go.mod index 12fdf989847..d41329679f8 100644 --- a/vendor/github.com/sirupsen/logrus/go.mod +++ b/vendor/github.com/sirupsen/logrus/go.mod @@ -2,9 +2,10 @@ module github.com/sirupsen/logrus require ( github.com/davecgh/go-spew v1.1.1 // indirect - github.com/konsorten/go-windows-terminal-sequences v1.0.1 + github.com/konsorten/go-windows-terminal-sequences v1.0.3 github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/stretchr/objx v0.1.1 // indirect github.com/stretchr/testify v1.2.2 golang.org/x/sys v0.0.0-20190422165155-953cdadca894 ) + +go 1.13 diff --git a/vendor/github.com/sirupsen/logrus/go.sum b/vendor/github.com/sirupsen/logrus/go.sum index 596c318b9f7..49c690f2383 100644 --- a/vendor/github.com/sirupsen/logrus/go.sum +++ b/vendor/github.com/sirupsen/logrus/go.sum @@ -1,16 +1,12 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe h1:CHRGQ8V7OlCYtwaKPJi3iA7J+YdNKdo8j7nG5IgDhjs= -github.com/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33 h1:I6FyU15t786LL7oL/hn43zqTuEGr4PN7F4XJ1p4E3Y8= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/vendor/github.com/sirupsen/logrus/json_formatter.go b/vendor/github.com/sirupsen/logrus/json_formatter.go index 098a21a0679..ba7f237112b 100644 --- a/vendor/github.com/sirupsen/logrus/json_formatter.go +++ b/vendor/github.com/sirupsen/logrus/json_formatter.go @@ -28,6 +28,9 @@ type JSONFormatter struct { // DisableTimestamp allows disabling automatic timestamps in output DisableTimestamp bool + // DisableHTMLEscape allows disabling html escaping in output + DisableHTMLEscape bool + // DataKey allows users to put all the log entry parameters into a nested dictionary at a given key. DataKey string @@ -110,6 +113,7 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { } encoder := json.NewEncoder(b) + encoder.SetEscapeHTML(!f.DisableHTMLEscape) if f.PrettyPrint { encoder.SetIndent("", " ") } diff --git a/vendor/github.com/sirupsen/logrus/logger.go b/vendor/github.com/sirupsen/logrus/logger.go index c0c0b1e5590..6fdda748e4d 100644 --- a/vendor/github.com/sirupsen/logrus/logger.go +++ b/vendor/github.com/sirupsen/logrus/logger.go @@ -68,10 +68,10 @@ func (mw *MutexWrap) Disable() { // `Out` and `Hooks` directly on the default logger instance. You can also just // instantiate your own: // -// var log = &Logger{ +// var log = &logrus.Logger{ // Out: os.Stderr, -// Formatter: new(JSONFormatter), -// Hooks: make(LevelHooks), +// Formatter: new(logrus.JSONFormatter), +// Hooks: make(logrus.LevelHooks), // Level: logrus.DebugLevel, // } // @@ -100,8 +100,9 @@ func (logger *Logger) releaseEntry(entry *Entry) { logger.entryPool.Put(entry) } -// Adds a field to the log entry, note that it doesn't log until you call -// Debug, Print, Info, Warn, Error, Fatal or Panic. It only creates a log entry. +// WithField allocates a new entry and adds a field to it. +// Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to +// this new returned entry. // If you want multiple fields, use `WithFields`. func (logger *Logger) WithField(key string, value interface{}) *Entry { entry := logger.newEntry() diff --git a/vendor/github.com/sirupsen/logrus/logrus.go b/vendor/github.com/sirupsen/logrus/logrus.go index 8644761f73c..2f16224cb9f 100644 --- a/vendor/github.com/sirupsen/logrus/logrus.go +++ b/vendor/github.com/sirupsen/logrus/logrus.go @@ -51,7 +51,7 @@ func (level *Level) UnmarshalText(text []byte) error { return err } - *level = Level(l) + *level = l return nil } diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go index 3c4f43f91cd..499789984d2 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go @@ -1,4 +1,5 @@ // +build darwin dragonfly freebsd netbsd openbsd +// +build !js package logrus @@ -10,4 +11,3 @@ func isTerminal(fd int) bool { _, err := unix.IoctlGetTermios(fd, ioctlReadTermios) return err == nil } - diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_js.go b/vendor/github.com/sirupsen/logrus/terminal_check_js.go new file mode 100644 index 00000000000..ebdae3ec626 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_js.go @@ -0,0 +1,7 @@ +// +build js + +package logrus + +func isTerminal(fd int) bool { + return false +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go index 355dc966f00..cc4fe6e3177 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go @@ -1,4 +1,5 @@ // +build linux aix +// +build !js package logrus @@ -10,4 +11,3 @@ func isTerminal(fd int) bool { _, err := unix.IoctlGetTermios(fd, ioctlReadTermios) return err == nil } - diff --git a/vendor/github.com/sirupsen/logrus/text_formatter.go b/vendor/github.com/sirupsen/logrus/text_formatter.go index e01587c437d..3c28b54caba 100644 --- a/vendor/github.com/sirupsen/logrus/text_formatter.go +++ b/vendor/github.com/sirupsen/logrus/text_formatter.go @@ -6,9 +6,11 @@ import ( "os" "runtime" "sort" + "strconv" "strings" "sync" "time" + "unicode/utf8" ) const ( @@ -32,6 +34,14 @@ type TextFormatter struct { // Force disabling colors. DisableColors bool + // Force quoting of all values + ForceQuote bool + + // DisableQuote disables quoting for all values. + // DisableQuote will have a lower priority than ForceQuote. + // If both of them are set to true, quote will be forced on all values. + DisableQuote bool + // Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/ EnvironmentOverrideColors bool @@ -57,6 +67,10 @@ type TextFormatter struct { // Disables the truncation of the level text to 4 characters. DisableLevelTruncation bool + // PadLevelText Adds padding the level text so that all the levels output at the same length + // PadLevelText is a superset of the DisableLevelTruncation option + PadLevelText bool + // QuoteEmptyFields will wrap empty fields in quotes if true QuoteEmptyFields bool @@ -79,23 +93,32 @@ type TextFormatter struct { CallerPrettyfier func(*runtime.Frame) (function string, file string) terminalInitOnce sync.Once + + // The max length of the level text, generated dynamically on init + levelTextMaxLength int } func (f *TextFormatter) init(entry *Entry) { if entry.Logger != nil { f.isTerminal = checkIfTerminal(entry.Logger.Out) } + // Get the max length of the level text + for _, level := range AllLevels { + levelTextLength := utf8.RuneCount([]byte(level.String())) + if levelTextLength > f.levelTextMaxLength { + f.levelTextMaxLength = levelTextLength + } + } } func (f *TextFormatter) isColored() bool { isColored := f.ForceColors || (f.isTerminal && (runtime.GOOS != "windows")) if f.EnvironmentOverrideColors { - if force, ok := os.LookupEnv("CLICOLOR_FORCE"); ok && force != "0" { + switch force, ok := os.LookupEnv("CLICOLOR_FORCE"); { + case ok && force != "0": isColored = true - } else if ok && force == "0" { - isColored = false - } else if os.Getenv("CLICOLOR") == "0" { + case ok && force == "0", os.Getenv("CLICOLOR") == "0": isColored = false } } @@ -217,9 +240,18 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin } levelText := strings.ToUpper(entry.Level.String()) - if !f.DisableLevelTruncation { + if !f.DisableLevelTruncation && !f.PadLevelText { levelText = levelText[0:4] } + if f.PadLevelText { + // Generates the format string used in the next line, for example "%-6s" or "%-7s". + // Based on the max level text length. + formatString := "%-" + strconv.Itoa(f.levelTextMaxLength) + "s" + // Formats the level text by appending spaces up to the max length, for example: + // - "INFO " + // - "WARNING" + levelText = fmt.Sprintf(formatString, levelText) + } // Remove a single newline if it already exists in the message to keep // the behavior of logrus text_formatter the same as the stdlib log package @@ -243,11 +275,12 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin } } - if f.DisableTimestamp { + switch { + case f.DisableTimestamp: fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message) - } else if !f.FullTimestamp { + case !f.FullTimestamp: fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message) - } else { + default: fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message) } for _, k := range keys { @@ -258,9 +291,15 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin } func (f *TextFormatter) needsQuoting(text string) bool { + if f.ForceQuote { + return true + } if f.QuoteEmptyFields && len(text) == 0 { return true } + if f.DisableQuote { + return false + } for _, ch := range text { if !((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || diff --git a/vendor/github.com/sirupsen/logrus/writer.go b/vendor/github.com/sirupsen/logrus/writer.go index 9e1f7513597..72e8e3a1b65 100644 --- a/vendor/github.com/sirupsen/logrus/writer.go +++ b/vendor/github.com/sirupsen/logrus/writer.go @@ -6,10 +6,16 @@ import ( "runtime" ) +// Writer at INFO level. See WriterLevel for details. func (logger *Logger) Writer() *io.PipeWriter { return logger.WriterLevel(InfoLevel) } +// WriterLevel returns an io.Writer that can be used to write arbitrary text to +// the logger at the given log level. Each line written to the writer will be +// printed in the usual way using formatters and hooks. The writer is part of an +// io.Pipe and it is the callers responsibility to close the writer when done. +// This can be used to override the standard library logger easily. func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { return NewEntry(logger).WriterLevel(level) } diff --git a/vendor/github.com/sonatard/noctx/.gitignore b/vendor/github.com/sonatard/noctx/.gitignore new file mode 100644 index 00000000000..2d830686d42 --- /dev/null +++ b/vendor/github.com/sonatard/noctx/.gitignore @@ -0,0 +1 @@ +coverage.out diff --git a/vendor/github.com/sonatard/noctx/.golangci.yml b/vendor/github.com/sonatard/noctx/.golangci.yml new file mode 100644 index 00000000000..1580acde279 --- /dev/null +++ b/vendor/github.com/sonatard/noctx/.golangci.yml @@ -0,0 +1,20 @@ +run: + +linters-settings: + govet: + enable-all: true + +linters: + enable-all: true + disable: + - gochecknoglobals + - gomnd + - gocognit + - nestif + +issues: + exclude-rules: + - path: reqwithoutctx/ssa.go + text: "Consider preallocating `exts`" + linters: + - prealloc diff --git a/vendor/github.com/sonatard/noctx/LICENSE b/vendor/github.com/sonatard/noctx/LICENSE new file mode 100644 index 00000000000..a00d5727f69 --- /dev/null +++ b/vendor/github.com/sonatard/noctx/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 sonatard + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/sonatard/noctx/Makefile b/vendor/github.com/sonatard/noctx/Makefile new file mode 100644 index 00000000000..1a27f6b595a --- /dev/null +++ b/vendor/github.com/sonatard/noctx/Makefile @@ -0,0 +1,16 @@ +.PHONY: all imports test lint + +all: imports test lint + +imports: + goimports -w ./ + +test: + go test -race ./... + +test_coverage: + go test -race -coverprofile=coverage.out -covermode=atomic ./... + +lint: + golangci-lint run ./... + diff --git a/vendor/github.com/sonatard/noctx/README.md b/vendor/github.com/sonatard/noctx/README.md new file mode 100644 index 00000000000..bfe9782c6d3 --- /dev/null +++ b/vendor/github.com/sonatard/noctx/README.md @@ -0,0 +1,95 @@ +# noctx + +![](https://github.com/sonatard/noctx/workflows/.github/workflows/ci.yml/badge.svg) + +`noctx` finds sending http request without context.Context. + +You should use `noctx` if sending http request in your library. +Passing `context.Context` enables library user to cancel http request, getting trace information and so on. + +## Install + +```sh +$ go get -u github.com/sonatard/noctx/cmd/noctx +``` + +## Usage + +```sh +$ go vet -vettool=`which noctx` main.go +./main.go:6:11: net/http.Get must not be called +``` + +## Detection rules +- Executing following functions + - `net/http.Get` + - `net/http.Head` + - `net/http.Post` + - `net/http.PostForm` + - `(*net/http.Client).Get` + - `(*net/http.Client).Head` + - `(*net/http.Client).Post` + - `(*net/http.Client).PostForm` +- `http.Request` returned by `http.NewRequest` function and passes it to other function. + +## How to fix +- Send http request using `(*http.Client).Do(*http.Request)` method. +- In Go 1.13 and later, use `http.NewRequestWithContext` function instead of using `http.NewRequest` function. +- In Go 1.12 and earlier, call `(http.Request).WithContext(ctx)` after `http.NewRequest`. + +`(http.Request).WithContext(ctx)` has a disadvantage of performance because it returns a copy of `http.Request`. Use `http.NewRequestWithContext` function if you only support Go1.13 or later. + +## Sample Code + +```go +package main + +import ( + "context" + "net/http" +) + +func main() { + const url = "http://example.com" + http.Get(url) // want `net/http\.Get must not be called` + http.Head(url) // want `net/http\.Head must not be called` + http.Post(url, "", nil) // want `net/http\.Post must not be called` + http.PostForm(url, nil) // want `net/http\.PostForm must not be called` + + cli := &http.Client{} + cli.Get(url) // want `\(\*net/http\.Client\)\.Get must not be called` + cli.Head(url) // want `\(\*net/http\.Client\)\.Head must not be called` + cli.Post(url, "", nil) // want `\(\*net/http\.Client\)\.Post must not be called` + cli.PostForm(url, nil) // want `\(\*net/http\.Client\)\.PostForm must not be called` + + req, _ := http.NewRequest(http.MethodPost, url, nil) // want `should rewrite http.NewRequestWithContext or add \(\*Request\).WithContext` + cli.Do(req) + + ctx := context.Background() + req2, _ := http.NewRequestWithContext(ctx, http.MethodPost, url, nil) // OK + cli.Do(req2) + + req3, _ := http.NewRequest(http.MethodPost, url, nil) // OK + req3 = req3.WithContext(ctx) + cli.Do(req3) + + f2 := func(req *http.Request, ctx context.Context) *http.Request { + return req + } + req4, _ := http.NewRequest(http.MethodPost, url, nil) // want `should rewrite http.NewRequestWithContext or add \(\*Request\).WithContext` + req4 = f2(req4, ctx) + cli.Do(req4) + + req5, _ := func() (*http.Request, error) { + return http.NewRequest(http.MethodPost, url, nil) // want `should rewrite http.NewRequestWithContext or add \(\*Request\).WithContext` + }() + cli.Do(req5) + +} +``` + +## Reference +- [net/http - NewRequest](https://golang.org/pkg/net/http/#NewRequest) +- [net/http - NewRequestWithContext](https://golang.org/pkg/net/http/#NewRequestWithContext) +- [net/http - Request.WithContext](https://golang.org/pkg/net/http/#Request.WithContext) + diff --git a/vendor/github.com/sonatard/noctx/go.mod b/vendor/github.com/sonatard/noctx/go.mod new file mode 100644 index 00000000000..47b7901a0c0 --- /dev/null +++ b/vendor/github.com/sonatard/noctx/go.mod @@ -0,0 +1,8 @@ +module github.com/sonatard/noctx + +go 1.13 + +require ( + github.com/gostaticanalysis/analysisutil v0.0.3 + golang.org/x/tools v0.0.0-20200117220505-0cba7a3a9ee9 +) diff --git a/vendor/github.com/sonatard/noctx/go.sum b/vendor/github.com/sonatard/noctx/go.sum new file mode 100644 index 00000000000..f8e5b075949 --- /dev/null +++ b/vendor/github.com/sonatard/noctx/go.sum @@ -0,0 +1,16 @@ +github.com/gostaticanalysis/analysisutil v0.0.3 h1:iwp+5/UAyzQSFgQ4uR2sni99sJ8Eo9DEacKWM5pekIg= +github.com/gostaticanalysis/analysisutil v0.0.3/go.mod h1:eEOZF4jCKGi+aprrirO9e7WKB3beBRtWgqGunKl6pKE= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190311215038-5c2858a9cfe5/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20200117220505-0cba7a3a9ee9 h1:KOkk4e2xd5OeCDJGwacvr75ICCbCsShrHiqPEdsA9hg= +golang.org/x/tools v0.0.0-20200117220505-0cba7a3a9ee9/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/vendor/github.com/sonatard/noctx/ngfunc/main.go b/vendor/github.com/sonatard/noctx/ngfunc/main.go new file mode 100644 index 00000000000..cfeb0f00105 --- /dev/null +++ b/vendor/github.com/sonatard/noctx/ngfunc/main.go @@ -0,0 +1,57 @@ +package ngfunc + +import ( + "go/types" + + "github.com/gostaticanalysis/analysisutil" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/buildssa" +) + +func Run(pass *analysis.Pass) (interface{}, error) { + ngFuncNames := []string{ + "net/http.Get", + "net/http.Head", + "net/http.Post", + "net/http.PostForm", + "(*net/http.Client).Get", + "(*net/http.Client).Head", + "(*net/http.Client).Post", + "(*net/http.Client).PostForm", + } + + ngFuncs := typeFuncs(pass, ngFuncNames) + if len(ngFuncs) == 0 { + return nil, nil + } + + reportFuncs := ngCalledFuncs(pass, ngFuncs) + report(pass, reportFuncs) + + return nil, nil +} + +func ngCalledFuncs(pass *analysis.Pass, ngFuncs []*types.Func) []*Report { + var reports []*Report + + srcFuncs := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs + for _, sf := range srcFuncs { + for _, b := range sf.Blocks { + for _, instr := range b.Instrs { + for _, ngFunc := range ngFuncs { + if analysisutil.Called(instr, nil, ngFunc) { + ngCalledFunc := &Report{ + Instruction: instr, + function: ngFunc, + } + reports = append(reports, ngCalledFunc) + + break + } + } + } + } + } + + return reports +} diff --git a/vendor/github.com/sonatard/noctx/ngfunc/report.go b/vendor/github.com/sonatard/noctx/ngfunc/report.go new file mode 100644 index 00000000000..e5005179867 --- /dev/null +++ b/vendor/github.com/sonatard/noctx/ngfunc/report.go @@ -0,0 +1,29 @@ +package ngfunc + +import ( + "fmt" + "go/token" + "go/types" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/ssa" +) + +type Report struct { + Instruction ssa.Instruction + function *types.Func +} + +func (n *Report) Pos() token.Pos { + return n.Instruction.Pos() +} + +func (n *Report) Message() string { + return fmt.Sprintf("%s must not be called", n.function.FullName()) +} + +func report(pass *analysis.Pass, reports []*Report) { + for _, report := range reports { + pass.Reportf(report.Pos(), report.Message()) + } +} diff --git a/vendor/github.com/sonatard/noctx/ngfunc/types.go b/vendor/github.com/sonatard/noctx/ngfunc/types.go new file mode 100644 index 00000000000..f1877386ce0 --- /dev/null +++ b/vendor/github.com/sonatard/noctx/ngfunc/types.go @@ -0,0 +1,65 @@ +package ngfunc + +import ( + "fmt" + "go/types" + "strings" + + "github.com/gostaticanalysis/analysisutil" + "golang.org/x/tools/go/analysis" +) + +var errNotFound = fmt.Errorf("function not found") + +func typeFuncs(pass *analysis.Pass, funcs []string) []*types.Func { + fs := make([]*types.Func, 0, len(funcs)) + + for _, fn := range funcs { + f, err := typeFunc(pass, fn) + if err != nil { + continue + } + + fs = append(fs, f) + } + + return fs +} + +func typeFunc(pass *analysis.Pass, funcName string) (*types.Func, error) { + ss := strings.Split(strings.TrimSpace(funcName), ".") + + switch len(ss) { + case 2: + // package function: pkgname.Func + f, ok := analysisutil.ObjectOf(pass, ss[0], ss[1]).(*types.Func) + if !ok || f == nil { + return nil, errNotFound + } + + return f, nil + case 3: + // method: (*pkgname.Type).Method + pkgname := strings.TrimLeft(ss[0], "(") + typename := strings.TrimRight(ss[1], ")") + + if pkgname != "" && pkgname[0] == '*' { + pkgname = pkgname[1:] + typename = "*" + typename + } + + typ := analysisutil.TypeOf(pass, pkgname, typename) + if typ == nil { + return nil, errNotFound + } + + m := analysisutil.MethodOf(typ, ss[2]) + if m == nil { + return nil, errNotFound + } + + return m, nil + } + + return nil, errNotFound +} diff --git a/vendor/github.com/sonatard/noctx/noctx.go b/vendor/github.com/sonatard/noctx/noctx.go new file mode 100644 index 00000000000..478ad8855dd --- /dev/null +++ b/vendor/github.com/sonatard/noctx/noctx.go @@ -0,0 +1,31 @@ +package noctx + +import ( + "github.com/sonatard/noctx/ngfunc" + "github.com/sonatard/noctx/reqwithoutctx" + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/buildssa" +) + +var Analyzer = &analysis.Analyzer{ + Name: "noctx", + Doc: Doc, + Run: run, + Requires: []*analysis.Analyzer{ + buildssa.Analyzer, + }, +} + +const Doc = "noctx finds sending http request without context.Context" + +func run(pass *analysis.Pass) (interface{}, error) { + if _, err := ngfunc.Run(pass); err != nil { + return nil, err + } + + if _, err := reqwithoutctx.Run(pass); err != nil { + return nil, err + } + + return nil, nil +} diff --git a/vendor/github.com/sonatard/noctx/reqwithoutctx/main.go b/vendor/github.com/sonatard/noctx/reqwithoutctx/main.go new file mode 100644 index 00000000000..b09e1de1b0d --- /dev/null +++ b/vendor/github.com/sonatard/noctx/reqwithoutctx/main.go @@ -0,0 +1,14 @@ +package reqwithoutctx + +import ( + "golang.org/x/tools/go/analysis" +) + +func Run(pass *analysis.Pass) (interface{}, error) { + analyzer := NewAnalyzer(pass) + reports := analyzer.Exec() + + report(pass, reports) + + return nil, nil +} diff --git a/vendor/github.com/sonatard/noctx/reqwithoutctx/report.go b/vendor/github.com/sonatard/noctx/reqwithoutctx/report.go new file mode 100644 index 00000000000..1c94e3148c2 --- /dev/null +++ b/vendor/github.com/sonatard/noctx/reqwithoutctx/report.go @@ -0,0 +1,26 @@ +package reqwithoutctx + +import ( + "go/token" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/ssa" +) + +type Report struct { + Instruction ssa.Instruction +} + +func (n *Report) Pos() token.Pos { + return n.Instruction.Pos() +} + +func (n *Report) Message() string { + return "should rewrite http.NewRequestWithContext or add (*Request).WithContext" +} + +func report(pass *analysis.Pass, reports []*Report) { + for _, report := range reports { + pass.Reportf(report.Pos(), report.Message()) + } +} diff --git a/vendor/github.com/sonatard/noctx/reqwithoutctx/ssa.go b/vendor/github.com/sonatard/noctx/reqwithoutctx/ssa.go new file mode 100644 index 00000000000..35751269ee9 --- /dev/null +++ b/vendor/github.com/sonatard/noctx/reqwithoutctx/ssa.go @@ -0,0 +1,180 @@ +package reqwithoutctx + +import ( + "go/types" + + "github.com/gostaticanalysis/analysisutil" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/buildssa" + "golang.org/x/tools/go/ssa" +) + +type Analyzer struct { + Funcs []*ssa.Function + newRequestType types.Type + requestType types.Type +} + +func NewAnalyzer(pass *analysis.Pass) *Analyzer { + newRequestType := analysisutil.TypeOf(pass, "net/http", "NewRequest") + requestType := analysisutil.TypeOf(pass, "net/http", "*Request") + + srcFuncs := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs + + return &Analyzer{ + Funcs: srcFuncs, + newRequestType: newRequestType, + requestType: requestType, + } +} + +func (a *Analyzer) Exec() []*Report { + if a.newRequestType == nil || a.requestType == nil { + return []*Report{} + } + + usedReqs := a.usedReqs() + newReqs := a.requestsByNewRequest() + + return a.report(usedReqs, newReqs) +} + +func (a *Analyzer) report(usedReqs map[string]*ssa.Extract, newReqs map[*ssa.Call]*ssa.Extract) []*Report { + var reports []*Report + + for _, fReq := range usedReqs { + for newRequest, req := range newReqs { + if fReq == req { + reports = append(reports, &Report{Instruction: newRequest}) + } + } + } + + return reports +} + +func (a *Analyzer) usedReqs() map[string]*ssa.Extract { + reqExts := make(map[string]*ssa.Extract) + + for _, f := range a.Funcs { + for _, b := range f.Blocks { + for _, instr := range b.Instrs { + switch i := instr.(type) { + case *ssa.Call: + exts := a.usedReqByCall(i) + for _, ext := range exts { + key := i.String() + ext.String() + reqExts[key] = ext + } + case *ssa.UnOp: + ext := a.usedReqByUnOp(i) + if ext != nil { + key := i.String() + ext.String() + reqExts[key] = ext + } + case *ssa.Return: + exts := a.usedReqByReturn(i) + for _, ext := range exts { + key := i.String() + ext.String() + reqExts[key] = ext + } + } + } + } + } + + return reqExts +} + +func (a *Analyzer) usedReqByCall(call *ssa.Call) []*ssa.Extract { + var exts []*ssa.Extract + + // skip net/http.Request method call + if call.Common().Signature().Recv() != nil && types.Identical(call.Value().Type(), a.requestType) { + return exts + } + + args := call.Common().Args + if len(args) == 0 { + return exts + } + + for _, arg := range args { + ext, ok := arg.(*ssa.Extract) + if !ok { + continue + } + + if !types.Identical(ext.Type(), a.requestType) { + continue + } + + exts = append(exts, ext) + } + + return exts +} + +func (a *Analyzer) usedReqByUnOp(op *ssa.UnOp) *ssa.Extract { + if ext, ok := op.X.(*ssa.Extract); ok && types.Identical(ext.Type(), a.requestType) { + return ext + } + + return nil +} + +func (a *Analyzer) usedReqByReturn(ret *ssa.Return) []*ssa.Extract { + rets := ret.Results + exts := make([]*ssa.Extract, 0, len(rets)) + + for _, ret := range rets { + ext, ok := ret.(*ssa.Extract) + if !ok { + continue + } + + if types.Identical(ext.Type(), a.requestType) { + exts = append(exts, ext) + } + } + + return exts +} + +func (a *Analyzer) requestsByNewRequest() map[*ssa.Call]*ssa.Extract { + reqs := make(map[*ssa.Call]*ssa.Extract) + + for _, f := range a.Funcs { + for _, b := range f.Blocks { + for _, instr := range b.Instrs { + ext, ok := instr.(*ssa.Extract) + if !ok { + continue + } + + if !types.Identical(ext.Type(), a.requestType) { + continue + } + + operands := ext.Operands([]*ssa.Value{}) + if len(operands) != 1 { + continue + } + + operand := *operands[0] + + f, ok := operand.(*ssa.Call) + if !ok { + continue + } + + if types.Identical(f.Call.Value.Type(), a.newRequestType) { + reqs[f] = ext + } + } + } + } + + return reqs +} diff --git a/vendor/github.com/sourcegraph/go-diff/diff/parse.go b/vendor/github.com/sourcegraph/go-diff/diff/parse.go index 1e77df48f5c..08cba667892 100644 --- a/vendor/github.com/sourcegraph/go-diff/diff/parse.go +++ b/vendor/github.com/sourcegraph/go-diff/diff/parse.go @@ -6,15 +6,17 @@ import ( "errors" "fmt" "io" + "strconv" "strings" "time" "sourcegraph.com/sqs/pbtypes" ) -// ParseMultiFileDiff parses a multi-file unified diff. It returns an error if parsing failed as a whole, but does its -// best to parse as many files in the case of per-file errors. In the case of non-fatal per-file errors, the error -// return value is null and the Errs field in the returned MultiFileDiff is set. +// ParseMultiFileDiff parses a multi-file unified diff. It returns an error if +// parsing failed as a whole, but does its best to parse as many files in the +// case of per-file errors. If it cannot detect when the diff of the next file +// begins, the hunks are added to the FileDiff of the previous file. func ParseMultiFileDiff(diff []byte) ([]*FileDiff, error) { return NewMultiFileDiffReader(bytes.NewReader(diff)).ReadAllFiles() } @@ -78,7 +80,7 @@ func (r *MultiFileDiffReader) ReadFile() (*FileDiff, error) { // need to perform the check here. hr := fr.HunksReader() line, err := readLine(r.reader) - if err != nil { + if err != nil && err != io.EOF { return fd, err } line = bytes.TrimSuffix(line, []byte{'\n'}) @@ -233,6 +235,15 @@ func (r *FileDiffReader) ReadFileHeaders() (origName, newName string, origTimest return "", "", nil, nil, err } + unquotedOrigName, err := strconv.Unquote(origName) + if err == nil { + origName = unquotedOrigName + } + unquotedNewName, err := strconv.Unquote(newName) + if err == nil { + newName = unquotedNewName + } + return origName, newName, origTimestamp, newTimestamp, nil } @@ -328,30 +339,53 @@ func (r *FileDiffReader) ReadExtendedHeaders() ([]string, error) { // handleEmpty detects when FileDiff was an empty diff and will not have any hunks // that follow. It updates fd fields from the parsed extended headers. func handleEmpty(fd *FileDiff) (wasEmpty bool) { + var err error + lineCount := len(fd.Extended) + if lineCount > 0 && !strings.HasPrefix(fd.Extended[0], "diff --git ") { + return false + } switch { - case (len(fd.Extended) == 3 || len(fd.Extended) == 4 && strings.HasPrefix(fd.Extended[3], "Binary files ")) && - strings.HasPrefix(fd.Extended[1], "new file mode ") && strings.HasPrefix(fd.Extended[0], "diff --git "): + case (lineCount == 3 || lineCount == 4 && strings.HasPrefix(fd.Extended[3], "Binary files ") || lineCount > 4 && strings.HasPrefix(fd.Extended[3], "GIT binary patch")) && + strings.HasPrefix(fd.Extended[1], "new file mode "): names := strings.SplitN(fd.Extended[0][len("diff --git "):], " ", 2) fd.OrigName = "/dev/null" - fd.NewName = names[1] + fd.NewName, err = strconv.Unquote(names[1]) + if err != nil { + fd.NewName = names[1] + } return true - case (len(fd.Extended) == 3 || len(fd.Extended) == 4 && strings.HasPrefix(fd.Extended[3], "Binary files ")) && - strings.HasPrefix(fd.Extended[1], "deleted file mode ") && strings.HasPrefix(fd.Extended[0], "diff --git "): + case (lineCount == 3 || lineCount == 4 && strings.HasPrefix(fd.Extended[3], "Binary files ") || lineCount > 4 && strings.HasPrefix(fd.Extended[3], "GIT binary patch")) && + strings.HasPrefix(fd.Extended[1], "deleted file mode "): names := strings.SplitN(fd.Extended[0][len("diff --git "):], " ", 2) - fd.OrigName = names[0] + fd.OrigName, err = strconv.Unquote(names[0]) + if err != nil { + fd.OrigName = names[0] + } fd.NewName = "/dev/null" return true - case len(fd.Extended) == 4 && strings.HasPrefix(fd.Extended[2], "rename from ") && strings.HasPrefix(fd.Extended[3], "rename to ") && strings.HasPrefix(fd.Extended[0], "diff --git "): + case lineCount == 4 && strings.HasPrefix(fd.Extended[2], "rename from ") && strings.HasPrefix(fd.Extended[3], "rename to "): names := strings.SplitN(fd.Extended[0][len("diff --git "):], " ", 2) - fd.OrigName = names[0] - fd.NewName = names[1] + fd.OrigName, err = strconv.Unquote(names[0]) + if err != nil { + fd.OrigName = names[0] + } + fd.NewName, err = strconv.Unquote(names[1]) + if err != nil { + fd.NewName = names[1] + } return true - case len(fd.Extended) == 3 && strings.HasPrefix(fd.Extended[2], "Binary files ") && strings.HasPrefix(fd.Extended[0], "diff --git "): + case lineCount == 3 && strings.HasPrefix(fd.Extended[2], "Binary files ") || lineCount > 3 && strings.HasPrefix(fd.Extended[2], "GIT binary patch"): names := strings.SplitN(fd.Extended[0][len("diff --git "):], " ", 2) - fd.OrigName = names[0] - fd.NewName = names[1] + fd.OrigName, err = strconv.Unquote(names[0]) + if err != nil { + fd.OrigName = names[0] + } + fd.NewName, err = strconv.Unquote(names[1]) + if err != nil { + fd.NewName = names[1] + } return true default: return false diff --git a/vendor/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore index 3b053c59ec2..c7b459e4dd0 100644 --- a/vendor/github.com/spf13/cobra/.gitignore +++ b/vendor/github.com/spf13/cobra/.gitignore @@ -32,7 +32,8 @@ Session.vim tags *.exe - cobra.test +bin -.idea/* +.idea/ +*.iml diff --git a/vendor/github.com/spf13/cobra/.travis.yml b/vendor/github.com/spf13/cobra/.travis.yml index 38b85f499ca..a9bd4e54785 100644 --- a/vendor/github.com/spf13/cobra/.travis.yml +++ b/vendor/github.com/spf13/cobra/.travis.yml @@ -3,29 +3,27 @@ language: go stages: - diff - test + - build go: - - 1.10.x - - 1.11.x - 1.12.x + - 1.13.x - tip +before_install: + - go get -u github.com/kyoh86/richgo + - go get -u github.com/mitchellh/gox + matrix: allow_failures: - go: tip include: - stage: diff - go: 1.12.x - script: diff -u <(echo -n) <(gofmt -d -s .) + go: 1.13.x + script: make fmt + - stage: build + go: 1.13.x + script: make cobra_generator -before_install: - - mkdir -p bin - - curl -Lso bin/shellcheck https://github.com/caarlos0/shellcheck-docker/releases/download/v0.6.0/shellcheck - - chmod +x bin/shellcheck - - go get -u github.com/kyoh86/richgo -script: - - PATH=$PATH:$PWD/bin richgo test -v ./... - - go build - - if [ -z $NOVET ]; then - diff -u <(echo -n) <(go vet . 2>&1 | grep -vE 'ExampleCommand|bash_completions.*Fprint'); - fi +script: + - make test diff --git a/vendor/github.com/spf13/cobra/Makefile b/vendor/github.com/spf13/cobra/Makefile new file mode 100644 index 00000000000..e9740d1e175 --- /dev/null +++ b/vendor/github.com/spf13/cobra/Makefile @@ -0,0 +1,36 @@ +BIN="./bin" +SRC=$(shell find . -name "*.go") + +ifeq (, $(shell which richgo)) +$(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo") +endif + +.PHONY: fmt vet test cobra_generator install_deps clean + +default: all + +all: fmt vet test cobra_generator + +fmt: + $(info ******************** checking formatting ********************) + @test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1) + +test: install_deps vet + $(info ******************** running tests ********************) + richgo test -v ./... + +cobra_generator: install_deps + $(info ******************** building generator ********************) + mkdir -p $(BIN) + make -C cobra all + +install_deps: + $(info ******************** downloading dependencies ********************) + go get -v ./... + +vet: + $(info ******************** vetting ********************) + go vet ./... + +clean: + rm -rf $(BIN) diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md index 60c5a425bc9..9d79934260f 100644 --- a/vendor/github.com/spf13/cobra/README.md +++ b/vendor/github.com/spf13/cobra/README.md @@ -24,11 +24,13 @@ Many of the most widely used Go projects are built using Cobra, such as: [Prototool](https://github.com/uber/prototool), [mattermost-server](https://github.com/mattermost/mattermost-server), [Gardener](https://github.com/gardener/gardenctl), +[Linkerd](https://linkerd.io/), +[Github CLI](https://github.com/cli/cli) etc. [![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra) -[![CircleCI status](https://circleci.com/gh/spf13/cobra.png?circle-token=:circle-token "CircleCI status")](https://circleci.com/gh/spf13/cobra) [![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra) +[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra) # Table of Contents @@ -208,51 +210,78 @@ You will additionally define flags and handle configuration in your init() funct For example cmd/root.go: ```go +package cmd + import ( - "fmt" - "os" + "fmt" + "os" - homedir "github.com/mitchellh/go-homedir" - "github.com/spf13/cobra" - "github.com/spf13/viper" + homedir "github.com/mitchellh/go-homedir" + "github.com/spf13/cobra" + "github.com/spf13/viper" ) -func init() { - cobra.OnInitialize(initConfig) - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - rootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/") - rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution") - rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)") - rootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) - viper.BindPFlag("projectbase", rootCmd.PersistentFlags().Lookup("projectbase")) - viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) - viper.SetDefault("author", "NAME HERE ") - viper.SetDefault("license", "apache") +var ( + // Used for flags. + cfgFile string + userLicense string + + rootCmd = &cobra.Command{ + Use: "cobra", + Short: "A generator for Cobra based Applications", + Long: `Cobra is a CLI library for Go that empowers applications. +This application is a tool to generate the needed files +to quickly create a Cobra application.`, + } +) + +// Execute executes the root command. +func Execute() error { + return rootCmd.Execute() } -func initConfig() { - // Don't forget to read config either from cfgFile or from home directory! - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := homedir.Dir() - if err != nil { - fmt.Println(err) - os.Exit(1) - } +func init() { + cobra.OnInitialize(initConfig) + + rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") + rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") + rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") + rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") + viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) + viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) + viper.SetDefault("author", "NAME HERE ") + viper.SetDefault("license", "apache") + + rootCmd.AddCommand(addCmd) + rootCmd.AddCommand(initCmd) +} - // Search config in home directory with name ".cobra" (without extension). - viper.AddConfigPath(home) - viper.SetConfigName(".cobra") - } +func er(msg interface{}) { + fmt.Println("Error:", msg) + os.Exit(1) +} - if err := viper.ReadInConfig(); err != nil { - fmt.Println("Can't read config:", err) - os.Exit(1) - } +func initConfig() { + if cfgFile != "" { + // Use config file from the flag. + viper.SetConfigFile(cfgFile) + } else { + // Find home directory. + home, err := homedir.Dir() + if err != nil { + er(err) + } + + // Search config in home directory with name ".cobra" (without extension). + viper.AddConfigPath(home) + viper.SetConfigName(".cobra") + } + + viper.AutomaticEnv() + + if err := viper.ReadInConfig(); err == nil { + fmt.Println("Using config file:", viper.ConfigFileUsed()) + } } ``` @@ -459,7 +488,7 @@ For many years people have printed back to the screen.`, Echo works a lot like print, except it has a child command.`, Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) + fmt.Println("Echo: " + strings.Join(args, " ")) }, } diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go index c4d820b8531..70e9b262912 100644 --- a/vendor/github.com/spf13/cobra/args.go +++ b/vendor/github.com/spf13/cobra/args.go @@ -2,6 +2,7 @@ package cobra import ( "fmt" + "strings" ) type PositionalArgs func(cmd *Command, args []string) error @@ -34,8 +35,15 @@ func NoArgs(cmd *Command, args []string) error { // OnlyValidArgs returns an error if any args are not in the list of ValidArgs. func OnlyValidArgs(cmd *Command, args []string) error { if len(cmd.ValidArgs) > 0 { + // Remove any description that may be included in ValidArgs. + // A description is following a tab character. + var validArgs []string + for _, v := range cmd.ValidArgs { + validArgs = append(validArgs, strings.Split(v, "\t")[0]) + } + for _, v := range args { - if !stringInSlice(v, cmd.ValidArgs) { + if !stringInSlice(v, validArgs) { return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) } } diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go index 57bb8e1b3fd..1e27188c3d2 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -58,9 +58,71 @@ __%[1]s_contains_word() return 1 } +__%[1]s_handle_go_custom_completion() +{ + __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}" + + local out requestComp lastParam lastChar comp directive args + + # Prepare the command to request completions for the program. + # Calling ${words[0]} instead of directly %[1]s allows to handle aliases + args=("${words[@]:1}") + requestComp="${words[0]} %[2]s ${args[*]}" + + lastParam=${words[$((${#words[@]}-1))]} + lastChar=${lastParam:$((${#lastParam}-1)):1} + __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}" + + if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go method. + __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter" + requestComp="${requestComp} \"\"" + fi + + __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}" + # Use eval to handle any environment variables and such + out=$(eval "${requestComp}" 2>/dev/null) + + # Extract the directive integer at the very end of the output following a colon (:) + directive=${out##*:} + # Remove the directive + out=${out%%:*} + if [ "${directive}" = "${out}" ]; then + # There is not directive specified + directive=0 + fi + __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}" + __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out[*]}" + + if [ $((directive & %[3]d)) -ne 0 ]; then + # Error code. No completion. + __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code" + return + else + if [ $((directive & %[4]d)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __%[1]s_debug "${FUNCNAME[0]}: activating no space" + compopt -o nospace + fi + fi + if [ $((directive & %[5]d)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __%[1]s_debug "${FUNCNAME[0]}: activating no file completion" + compopt +o default + fi + fi + + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${out[*]}" -- "$cur") + fi +} + __%[1]s_handle_reply() { __%[1]s_debug "${FUNCNAME[0]}" + local comp case $cur in -*) if [[ $(type -t compopt) = "builtin" ]]; then @@ -72,7 +134,9 @@ __%[1]s_handle_reply() else allflags=("${flags[*]} ${two_word_flags[*]}") fi - COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") ) + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${allflags[*]}" -- "$cur") if [[ $(type -t compopt) = "builtin" ]]; then [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace fi @@ -118,14 +182,22 @@ __%[1]s_handle_reply() completions=("${commands[@]}") if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then completions=("${must_have_one_noun[@]}") + elif [[ -n "${has_completion_function}" ]]; then + # if a go completion function is provided, defer to that function + completions=() + __%[1]s_handle_go_custom_completion fi if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then completions+=("${must_have_one_flag[@]}") fi - COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") ) + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${completions[*]}" -- "$cur") if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then - COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") ) + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${noun_aliases[*]}" -- "$cur") fi if [[ ${#COMPREPLY[@]} -eq 0 ]]; then @@ -160,7 +232,7 @@ __%[1]s_handle_filename_extension_flag() __%[1]s_handle_subdirs_in_dir_flag() { local dir="$1" - pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 + pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return } __%[1]s_handle_flag() @@ -272,7 +344,7 @@ __%[1]s_handle_word() __%[1]s_handle_word } -`, name)) +`, name, ShellCompNoDescRequestCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp)) } func writePostscript(buf *bytes.Buffer, name string) { @@ -297,6 +369,7 @@ func writePostscript(buf *bytes.Buffer, name string) { local commands=("%[1]s") local must_have_one_flag=() local must_have_one_noun=() + local has_completion_function local last_command local nouns=() @@ -397,7 +470,22 @@ func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) { buf.WriteString(fmt.Sprintf(format, name)) } +// Setup annotations for go completions for registered flags +func prepareCustomAnnotationsForFlags(cmd *Command) { + for flag := range flagCompletionFunctions { + // Make sure the completion script calls the __*_go_custom_completion function for + // every registered flag. We need to do this here (and not when the flag was registered + // for completion) so that we can know the root command name for the prefix + // of ___go_custom_completion + if flag.Annotations == nil { + flag.Annotations = map[string][]string{} + } + flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())} + } +} + func writeFlags(buf *bytes.Buffer, cmd *Command) { + prepareCustomAnnotationsForFlags(cmd) buf.WriteString(` flags=() two_word_flags=() local_nonpersistent_flags=() @@ -460,8 +548,14 @@ func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) { buf.WriteString(" must_have_one_noun=()\n") sort.Sort(sort.StringSlice(cmd.ValidArgs)) for _, value := range cmd.ValidArgs { + // Remove any description that may be included following a tab character. + // Descriptions are not supported by bash completion. + value = strings.Split(value, "\t")[0] buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) } + if cmd.ValidArgsFunction != nil { + buf.WriteString(" has_completion_function=1\n") + } } func writeCmdAliases(buf *bytes.Buffer, cmd *Command) { diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md index 4ac61ee132a..e61a3a6546b 100644 --- a/vendor/github.com/spf13/cobra/bash_completions.md +++ b/vendor/github.com/spf13/cobra/bash_completions.md @@ -56,7 +56,149 @@ func main() { `out.sh` will get you completions of subcommands and flags. Copy it to `/etc/bash_completion.d/` as described [here](https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1) and reset your terminal to use autocompletion. If you make additional annotations to your code, you can get even more intelligent and flexible behavior. -## Creating your own custom functions +## Have the completions code complete your 'nouns' + +### Static completion of nouns + +This method allows you to provide a pre-defined list of completion choices for your nouns using the `validArgs` field. +For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like: + +```go +validArgs []string = { "pod", "node", "service", "replicationcontroller" } + +cmd := &cobra.Command{ + Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", + Short: "Display one or many resources", + Long: get_long, + Example: get_example, + Run: func(cmd *cobra.Command, args []string) { + err := RunGet(f, out, cmd, args) + util.CheckErr(err) + }, + ValidArgs: validArgs, +} +``` + +Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like + +```bash +# kubectl get [tab][tab] +node pod replicationcontroller service +``` + +### Plural form and shortcuts for nouns + +If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`: + +```go +argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" } + +cmd := &cobra.Command{ + ... + ValidArgs: validArgs, + ArgAliases: argAliases +} +``` + +The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by +the completion algorithm if entered manually, e.g. in: + +```bash +# kubectl get rc [tab][tab] +backend frontend database +``` + +Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns +in this example again instead of the replication controllers. + +### Dynamic completion of nouns + +In some cases it is not possible to provide a list of possible completions in advance. Instead, the list of completions must be determined at execution-time. Cobra provides two ways of defining such dynamic completion of nouns. Note that both these methods can be used along-side each other as long as they are not both used for the same command. + +**Note**: *Custom Completions written in Go* will automatically work for other shell-completion scripts (e.g., Fish shell), while *Custom Completions written in Bash* will only work for Bash shell-completion. It is therefore recommended to use *Custom Completions written in Go*. + +#### 1. Custom completions of nouns written in Go + +In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both. +Simplified code from `helm status` looks like: + +```go +cmd := &cobra.Command{ + Use: "status RELEASE_NAME", + Short: "Display the status of the named release", + Long: status_long, + RunE: func(cmd *cobra.Command, args []string) { + RunGet(args[0]) + }, + ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + if len(args) != 0 { + return nil, cobra.ShellCompDirectiveNoFileComp + } + return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp + }, +} +``` +Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster. +Notice we put the `ValidArgsFunction` on the `status` subcommand. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like + +```bash +# helm status [tab][tab] +harbor notary rook thanos +``` +You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp` +```go +// Indicates an error occurred and completions should be ignored. +ShellCompDirectiveError +// Indicates that the shell should not add a space after the completion, +// even if there is a single completion provided. +ShellCompDirectiveNoSpace +// Indicates that the shell should not provide file completion even when +// no completion is provided. +// This currently does not work for zsh or bash < 4 +ShellCompDirectiveNoFileComp +// Indicates that the shell will perform its default behavior after completions +// have been provided (this implies !ShellCompDirectiveNoSpace && !ShellCompDirectiveNoFileComp). +ShellCompDirectiveDefault +``` + +When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function. + +##### Debugging + +Cobra achieves dynamic completions written in Go through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly: +```bash +# helm __complete status har +harbor +:4 +Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr +``` +***Important:*** If the noun to complete is empty, you must pass an empty parameter to the `__complete` command: +```bash +# helm __complete status "" +harbor +notary +rook +thanos +:4 +Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr +``` +Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code: +```go +// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE +// is set to a file path) and optionally prints to stderr. +cobra.CompDebug(msg string, printToStdErr bool) { +cobra.CompDebugln(msg string, printToStdErr bool) + +// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE +// is set to a file path) and to stderr. +cobra.CompError(msg string) +cobra.CompErrorln(msg string) +``` +***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above. + +#### 2. Custom completions of nouns written in Bash + +This method allows you to inject bash functions into the completion script. Those bash functions are responsible for providing the completion choices for your own completions. Some more actual code that works in kubernetes: @@ -111,58 +253,6 @@ Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`, The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`___custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods! -## Have the completions code complete your 'nouns' - -In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like: - -```go -validArgs []string = { "pod", "node", "service", "replicationcontroller" } - -cmd := &cobra.Command{ - Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", - Short: "Display one or many resources", - Long: get_long, - Example: get_example, - Run: func(cmd *cobra.Command, args []string) { - err := RunGet(f, out, cmd, args) - util.CheckErr(err) - }, - ValidArgs: validArgs, -} -``` - -Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like - -```bash -# kubectl get [tab][tab] -node pod replicationcontroller service -``` - -## Plural form and shortcuts for nouns - -If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`: - -```go -argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" } - -cmd := &cobra.Command{ - ... - ValidArgs: validArgs, - ArgAliases: argAliases -} -``` - -The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by -the completion algorithm if entered manually, e.g. in: - -```bash -# kubectl get rc [tab][tab] -backend frontend database -``` - -Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns -in this example again instead of the replication controllers. - ## Mark flags as required Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy. @@ -211,8 +301,45 @@ So while there are many other files in the CWD it only shows me subdirs and thos # Specify custom flag completion -Similar to the filename completion and filtering using cobra.BashCompFilenameExt, you can specify -a custom flag completion function with cobra.BashCompCustom: +As for nouns, Cobra provides two ways of defining dynamic completion of flags. Note that both these methods can be used along-side each other as long as they are not both used for the same flag. + +**Note**: *Custom Completions written in Go* will automatically work for other shell-completion scripts (e.g., Fish shell), while *Custom Completions written in Bash* will only work for Bash shell-completion. It is therefore recommended to use *Custom Completions written in Go*. + +## 1. Custom completions of flags written in Go + +To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function in the following manner: + +```go +flagName := "output" +cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault +}) +``` +Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so: + +```bash +# helm status --output [tab][tab] +json table yaml +``` + +### Debugging + +You can also easily debug your Go completion code for flags: +```bash +# helm __complete status --output "" +json +table +yaml +:4 +Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr +``` +***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned in the above section. + +## 2. Custom completions of flags written in Bash + +Alternatively, you can use bash code for flag custom completion. Similar to the filename +completion and filtering using `cobra.BashCompFilenameExt`, you can specify +a custom flag completion bash function with `cobra.BashCompCustom`: ```go annotation := make(map[string][]string) @@ -226,7 +353,7 @@ a custom flag completion function with cobra.BashCompCustom: cmd.Flags().AddFlag(flag) ``` -In addition add the `__handle_namespace_flag` implementation in the `BashCompletionFunction` +In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction` value, e.g.: ```bash diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go index 6505c070b40..d01becc8fa6 100644 --- a/vendor/github.com/spf13/cobra/cobra.go +++ b/vendor/github.com/spf13/cobra/cobra.go @@ -52,7 +52,7 @@ var EnableCommandSorting = true // if the CLI is started from explorer.exe. // To disable the mousetrap, just set this variable to blank string (""). // Works only on Microsoft Windows. -var MousetrapHelpText string = `This is a command line tool. +var MousetrapHelpText = `This is a command line tool. You need to open cmd.exe and run it from there. ` @@ -61,7 +61,7 @@ You need to open cmd.exe and run it from there. // if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed. // To disable the mousetrap, just set MousetrapHelpText to blank string (""). // Works only on Microsoft Windows. -var MousetrapDisplayDuration time.Duration = 5 * time.Second +var MousetrapDisplayDuration = 5 * time.Second // AddTemplateFunc adds a template function that's available to Usage and Help // template generation. diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go index c7e89830343..88e6ed77d0e 100644 --- a/vendor/github.com/spf13/cobra/command.go +++ b/vendor/github.com/spf13/cobra/command.go @@ -17,6 +17,7 @@ package cobra import ( "bytes" + "context" "fmt" "io" "os" @@ -56,6 +57,10 @@ type Command struct { // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions ValidArgs []string + // ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion. + // It is a dynamic version of using ValidArgs. + // Only one of ValidArgs and ValidArgsFunction can be used for a command. + ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) // Expected arguments Args PositionalArgs @@ -80,7 +85,8 @@ type Command struct { // Version defines the version for this command. If this value is non-empty and the command does not // define a "version" flag, a "version" boolean flag will be added to the command and, if specified, - // will print content of the "Version" variable. + // will print content of the "Version" variable. A shorthand "v" flag will also be added if the + // command does not define one. Version string // The *Run functions are executed in the following order: @@ -140,9 +146,11 @@ type Command struct { // TraverseChildren parses flags on all parents before executing child command. TraverseChildren bool - //FParseErrWhitelist flag parse errors to be ignored + // FParseErrWhitelist flag parse errors to be ignored FParseErrWhitelist FParseErrWhitelist + ctx context.Context + // commands is the list of commands supported by this program. commands []*Command // parent is a parent command for this command. @@ -202,6 +210,12 @@ type Command struct { errWriter io.Writer } +// Context returns underlying command context. If command wasn't +// executed with ExecuteContext Context returns Background context. +func (c *Command) Context() context.Context { + return c.ctx +} + // SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden // particularly useful when testing. func (c *Command) SetArgs(a []string) { @@ -228,7 +242,7 @@ func (c *Command) SetErr(newErr io.Writer) { c.errWriter = newErr } -// SetOut sets the source for input data +// SetIn sets the source for input data // If newIn is nil, os.Stdin is used. func (c *Command) SetIn(newIn io.Reader) { c.inReader = newIn @@ -297,7 +311,7 @@ func (c *Command) ErrOrStderr() io.Writer { return c.getErr(os.Stderr) } -// ErrOrStderr returns output to stderr +// InOrStdin returns input to stdin func (c *Command) InOrStdin() io.Reader { return c.getIn(os.Stdin) } @@ -369,6 +383,8 @@ func (c *Command) HelpFunc() func(*Command, []string) { } return func(c *Command, a []string) { c.mergePersistentFlags() + // The help should be sent to stdout + // See https://github.com/spf13/cobra/issues/1002 err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c) if err != nil { c.Println(err) @@ -857,6 +873,13 @@ func (c *Command) preRun() { } } +// ExecuteContext is the same as Execute(), but sets the ctx on the command. +// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle functions. +func (c *Command) ExecuteContext(ctx context.Context) error { + c.ctx = ctx + return c.Execute() +} + // Execute uses the args (os.Args[1:] by default) // and run through the command tree finding appropriate matches // for commands and then corresponding flags. @@ -867,6 +890,10 @@ func (c *Command) Execute() error { // ExecuteC executes the command. func (c *Command) ExecuteC() (cmd *Command, err error) { + if c.ctx == nil { + c.ctx = context.Background() + } + // Regardless of what command execute is called on, run on Root only if c.HasParent() { return c.Root().ExecuteC() @@ -888,6 +915,9 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { args = os.Args[1:] } + // initialize the hidden command to be used for bash completion + c.initCompleteCmd(args) + var flags []string if c.TraverseChildren { cmd, flags, err = c.Traverse(args) @@ -911,6 +941,12 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { cmd.commandCalledAs.name = cmd.Name() } + // We have to pass global context to children command + // if context is present on the parent command. + if cmd.ctx == nil { + cmd.ctx = c.ctx + } + err = cmd.execute(flags) if err != nil { // Always show help if requested, even if SilenceErrors is in @@ -994,7 +1030,11 @@ func (c *Command) InitDefaultVersionFlag() { } else { usage += c.Name() } - c.Flags().Bool("version", false, usage) + if c.Flags().ShorthandLookup("v") == nil { + c.Flags().BoolP("version", "v", false, usage) + } else { + c.Flags().Bool("version", false, usage) + } } } @@ -1547,7 +1587,7 @@ func (c *Command) ParseFlags(args []string) error { beforeErrorBufLen := c.flagErrorBuf.Len() c.mergePersistentFlags() - //do it here after merging all flags and just before parse + // do it here after merging all flags and just before parse c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist) err := c.Flags().Parse(args) diff --git a/vendor/github.com/spf13/cobra/custom_completions.go b/vendor/github.com/spf13/cobra/custom_completions.go new file mode 100644 index 00000000000..ba57327c153 --- /dev/null +++ b/vendor/github.com/spf13/cobra/custom_completions.go @@ -0,0 +1,384 @@ +package cobra + +import ( + "errors" + "fmt" + "os" + "strings" + + "github.com/spf13/pflag" +) + +const ( + // ShellCompRequestCmd is the name of the hidden command that is used to request + // completion results from the program. It is used by the shell completion scripts. + ShellCompRequestCmd = "__complete" + // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request + // completion results without their description. It is used by the shell completion scripts. + ShellCompNoDescRequestCmd = "__completeNoDesc" +) + +// Global map of flag completion functions. +var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){} + +// ShellCompDirective is a bit map representing the different behaviors the shell +// can be instructed to have once completions have been provided. +type ShellCompDirective int + +const ( + // ShellCompDirectiveError indicates an error occurred and completions should be ignored. + ShellCompDirectiveError ShellCompDirective = 1 << iota + + // ShellCompDirectiveNoSpace indicates that the shell should not add a space + // after the completion even if there is a single completion provided. + ShellCompDirectiveNoSpace + + // ShellCompDirectiveNoFileComp indicates that the shell should not provide + // file completion even when no completion is provided. + // This currently does not work for zsh or bash < 4 + ShellCompDirectiveNoFileComp + + // ShellCompDirectiveDefault indicates to let the shell perform its default + // behavior after completions have been provided. + ShellCompDirectiveDefault ShellCompDirective = 0 +) + +// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. +func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error { + flag := c.Flag(flagName) + if flag == nil { + return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) + } + if _, exists := flagCompletionFunctions[flag]; exists { + return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName) + } + flagCompletionFunctions[flag] = f + return nil +} + +// Returns a string listing the different directive enabled in the specified parameter +func (d ShellCompDirective) string() string { + var directives []string + if d&ShellCompDirectiveError != 0 { + directives = append(directives, "ShellCompDirectiveError") + } + if d&ShellCompDirectiveNoSpace != 0 { + directives = append(directives, "ShellCompDirectiveNoSpace") + } + if d&ShellCompDirectiveNoFileComp != 0 { + directives = append(directives, "ShellCompDirectiveNoFileComp") + } + if len(directives) == 0 { + directives = append(directives, "ShellCompDirectiveDefault") + } + + if d > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp { + return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d) + } + return strings.Join(directives, ", ") +} + +// Adds a special hidden command that can be used to request custom completions. +func (c *Command) initCompleteCmd(args []string) { + completeCmd := &Command{ + Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd), + Aliases: []string{ShellCompNoDescRequestCmd}, + DisableFlagsInUseLine: true, + Hidden: true, + DisableFlagParsing: true, + Args: MinimumNArgs(1), + Short: "Request shell completion choices for the specified command-line", + Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s", + "to request completion choices for the specified command-line.", ShellCompRequestCmd), + Run: func(cmd *Command, args []string) { + finalCmd, completions, directive, err := cmd.getCompletions(args) + if err != nil { + CompErrorln(err.Error()) + // Keep going for multiple reasons: + // 1- There could be some valid completions even though there was an error + // 2- Even without completions, we need to print the directive + } + + noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd) + for _, comp := range completions { + if noDescriptions { + // Remove any description that may be included following a tab character. + comp = strings.Split(comp, "\t")[0] + } + // Print each possible completion to stdout for the completion script to consume. + fmt.Fprintln(finalCmd.OutOrStdout(), comp) + } + + if directive > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp { + directive = ShellCompDirectiveDefault + } + + // As the last printout, print the completion directive for the completion script to parse. + // The directive integer must be that last character following a single colon (:). + // The completion script expects : + fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive) + + // Print some helpful info to stderr for the user to understand. + // Output from stderr must be ignored by the completion script. + fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string()) + }, + } + c.AddCommand(completeCmd) + subCmd, _, err := c.Find(args) + if err != nil || subCmd.Name() != ShellCompRequestCmd { + // Only create this special command if it is actually being called. + // This reduces possible side-effects of creating such a command; + // for example, having this command would cause problems to a + // cobra program that only consists of the root command, since this + // command would cause the root command to suddenly have a subcommand. + c.RemoveCommand(completeCmd) + } +} + +func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) { + var completions []string + + // The last argument, which is not completely typed by the user, + // should not be part of the list of arguments + toComplete := args[len(args)-1] + trimmedArgs := args[:len(args)-1] + + // Find the real command for which completion must be performed + finalCmd, finalArgs, err := c.Root().Find(trimmedArgs) + if err != nil { + // Unable to find the real command. E.g., someInvalidCmd + return c, completions, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs) + } + + // When doing completion of a flag name, as soon as an argument starts with + // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires + // the flag to be complete + if len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") { + // We are completing a flag name + finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { + completions = append(completions, getFlagNameCompletions(flag, toComplete)...) + }) + finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { + completions = append(completions, getFlagNameCompletions(flag, toComplete)...) + }) + + directive := ShellCompDirectiveDefault + if len(completions) > 0 { + if strings.HasSuffix(completions[0], "=") { + directive = ShellCompDirectiveNoSpace + } + } + return finalCmd, completions, directive, nil + } + + var flag *pflag.Flag + if !finalCmd.DisableFlagParsing { + // We only do flag completion if we are allowed to parse flags + // This is important for commands which have requested to do their own flag completion. + flag, finalArgs, toComplete, err = checkIfFlagCompletion(finalCmd, finalArgs, toComplete) + if err != nil { + // Error while attempting to parse flags + return finalCmd, completions, ShellCompDirectiveDefault, err + } + } + + if flag == nil { + // Complete subcommand names + for _, subCmd := range finalCmd.Commands() { + if subCmd.IsAvailableCommand() && strings.HasPrefix(subCmd.Name(), toComplete) { + completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short)) + } + } + + if len(finalCmd.ValidArgs) > 0 { + // Always complete ValidArgs, even if we are completing a subcommand name. + // This is for commands that have both subcommands and ValidArgs. + for _, validArg := range finalCmd.ValidArgs { + if strings.HasPrefix(validArg, toComplete) { + completions = append(completions, validArg) + } + } + + // If there are ValidArgs specified (even if they don't match), we stop completion. + // Only one of ValidArgs or ValidArgsFunction can be used for a single command. + return finalCmd, completions, ShellCompDirectiveNoFileComp, nil + } + + // Always let the logic continue so as to add any ValidArgsFunction completions, + // even if we already found sub-commands. + // This is for commands that have subcommands but also specify a ValidArgsFunction. + } + + // Parse the flags and extract the arguments to prepare for calling the completion function + if err = finalCmd.ParseFlags(finalArgs); err != nil { + return finalCmd, completions, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) + } + + // We only remove the flags from the arguments if DisableFlagParsing is not set. + // This is important for commands which have requested to do their own flag completion. + if !finalCmd.DisableFlagParsing { + finalArgs = finalCmd.Flags().Args() + } + + // Find the completion function for the flag or command + var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) + if flag != nil { + completionFn = flagCompletionFunctions[flag] + } else { + completionFn = finalCmd.ValidArgsFunction + } + if completionFn == nil { + // Go custom completion not supported/needed for this flag or command + return finalCmd, completions, ShellCompDirectiveDefault, nil + } + + // Call the registered completion function to get the completions + comps, directive := completionFn(finalCmd, finalArgs, toComplete) + completions = append(completions, comps...) + return finalCmd, completions, directive, nil +} + +func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string { + if nonCompletableFlag(flag) { + return []string{} + } + + var completions []string + flagName := "--" + flag.Name + if strings.HasPrefix(flagName, toComplete) { + // Flag without the = + completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) + + if len(flag.NoOptDefVal) == 0 { + // Flag requires a value, so it can be suffixed with = + flagName += "=" + completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) + } + } + + flagName = "-" + flag.Shorthand + if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) { + completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) + } + + return completions +} + +func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) { + var flagName string + trimmedArgs := args + flagWithEqual := false + if isFlagArg(lastArg) { + if index := strings.Index(lastArg, "="); index >= 0 { + flagName = strings.TrimLeft(lastArg[:index], "-") + lastArg = lastArg[index+1:] + flagWithEqual = true + } else { + return nil, nil, "", errors.New("Unexpected completion request for flag") + } + } + + if len(flagName) == 0 { + if len(args) > 0 { + prevArg := args[len(args)-1] + if isFlagArg(prevArg) { + // Only consider the case where the flag does not contain an =. + // If the flag contains an = it means it has already been fully processed, + // so we don't need to deal with it here. + if index := strings.Index(prevArg, "="); index < 0 { + flagName = strings.TrimLeft(prevArg, "-") + + // Remove the uncompleted flag or else there could be an error created + // for an invalid value for that flag + trimmedArgs = args[:len(args)-1] + } + } + } + } + + if len(flagName) == 0 { + // Not doing flag completion + return nil, trimmedArgs, lastArg, nil + } + + flag := findFlag(finalCmd, flagName) + if flag == nil { + // Flag not supported by this command, nothing to complete + err := fmt.Errorf("Subcommand '%s' does not support flag '%s'", finalCmd.Name(), flagName) + return nil, nil, "", err + } + + if !flagWithEqual { + if len(flag.NoOptDefVal) != 0 { + // We had assumed dealing with a two-word flag but the flag is a boolean flag. + // In that case, there is no value following it, so we are not really doing flag completion. + // Reset everything to do noun completion. + trimmedArgs = args + flag = nil + } + } + + return flag, trimmedArgs, lastArg, nil +} + +func findFlag(cmd *Command, name string) *pflag.Flag { + flagSet := cmd.Flags() + if len(name) == 1 { + // First convert the short flag into a long flag + // as the cmd.Flag() search only accepts long flags + if short := flagSet.ShorthandLookup(name); short != nil { + name = short.Name + } else { + set := cmd.InheritedFlags() + if short = set.ShorthandLookup(name); short != nil { + name = short.Name + } else { + return nil + } + } + } + return cmd.Flag(name) +} + +// CompDebug prints the specified string to the same file as where the +// completion script prints its logs. +// Note that completion printouts should never be on stdout as they would +// be wrongly interpreted as actual completion choices by the completion script. +func CompDebug(msg string, printToStdErr bool) { + msg = fmt.Sprintf("[Debug] %s", msg) + + // Such logs are only printed when the user has set the environment + // variable BASH_COMP_DEBUG_FILE to the path of some file to be used. + if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" { + f, err := os.OpenFile(path, + os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err == nil { + defer f.Close() + f.WriteString(msg) + } + } + + if printToStdErr { + // Must print to stderr for this not to be read by the completion script. + fmt.Fprintf(os.Stderr, msg) + } +} + +// CompDebugln prints the specified string with a newline at the end +// to the same file as where the completion script prints its logs. +// Such logs are only printed when the user has set the environment +// variable BASH_COMP_DEBUG_FILE to the path of some file to be used. +func CompDebugln(msg string, printToStdErr bool) { + CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr) +} + +// CompError prints the specified completion message to stderr. +func CompError(msg string) { + msg = fmt.Sprintf("[Error] %s", msg) + CompDebug(msg, true) +} + +// CompErrorln prints the specified completion message to stderr with a newline at the end. +func CompErrorln(msg string) { + CompError(fmt.Sprintf("%s\n", msg)) +} diff --git a/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go new file mode 100644 index 00000000000..c83609c83b6 --- /dev/null +++ b/vendor/github.com/spf13/cobra/fish_completions.go @@ -0,0 +1,172 @@ +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" +) + +func genFishComp(buf *bytes.Buffer, name string, includeDesc bool) { + compCmd := ShellCompRequestCmd + if !includeDesc { + compCmd = ShellCompNoDescRequestCmd + } + buf.WriteString(fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name)) + buf.WriteString(fmt.Sprintf(` +function __%[1]s_debug + set file "$BASH_COMP_DEBUG_FILE" + if test -n "$file" + echo "$argv" >> $file + end +end + +function __%[1]s_perform_completion + __%[1]s_debug "Starting __%[1]s_perform_completion with: $argv" + + set args (string split -- " " "$argv") + set lastArg "$args[-1]" + + __%[1]s_debug "args: $args" + __%[1]s_debug "last arg: $lastArg" + + set emptyArg "" + if test -z "$lastArg" + __%[1]s_debug "Setting emptyArg" + set emptyArg \"\" + end + __%[1]s_debug "emptyArg: $emptyArg" + + set requestComp "$args[1] %[2]s $args[2..-1] $emptyArg" + __%[1]s_debug "Calling $requestComp" + + set results (eval $requestComp 2> /dev/null) + set comps $results[1..-2] + set directiveLine $results[-1] + + # For Fish, when completing a flag with an = (e.g., -n=) + # completions must be prefixed with the flag + set flagPrefix (string match -r -- '-.*=' "$lastArg") + + __%[1]s_debug "Comps: $comps" + __%[1]s_debug "DirectiveLine: $directiveLine" + __%[1]s_debug "flagPrefix: $flagPrefix" + + for comp in $comps + printf "%%s%%s\n" "$flagPrefix" "$comp" + end + + printf "%%s\n" "$directiveLine" +end + +# This function does three things: +# 1- Obtain the completions and store them in the global __%[1]s_comp_results +# 2- Set the __%[1]s_comp_do_file_comp flag if file completion should be performed +# and unset it otherwise +# 3- Return true if the completion results are not empty +function __%[1]s_prepare_completions + # Start fresh + set --erase __%[1]s_comp_do_file_comp + set --erase __%[1]s_comp_results + + # Check if the command-line is already provided. This is useful for testing. + if not set --query __%[1]s_comp_commandLine + set __%[1]s_comp_commandLine (commandline) + end + __%[1]s_debug "commandLine is: $__%[1]s_comp_commandLine" + + set results (__%[1]s_perform_completion "$__%[1]s_comp_commandLine") + set --erase __%[1]s_comp_commandLine + __%[1]s_debug "Completion results: $results" + + if test -z "$results" + __%[1]s_debug "No completion, probably due to a failure" + # Might as well do file completion, in case it helps + set --global __%[1]s_comp_do_file_comp 1 + return 0 + end + + set directive (string sub --start 2 $results[-1]) + set --global __%[1]s_comp_results $results[1..-2] + + __%[1]s_debug "Completions are: $__%[1]s_comp_results" + __%[1]s_debug "Directive is: $directive" + + if test -z "$directive" + set directive 0 + end + + set compErr (math (math --scale 0 $directive / %[3]d) %% 2) + if test $compErr -eq 1 + __%[1]s_debug "Received error directive: aborting." + # Might as well do file completion, in case it helps + set --global __%[1]s_comp_do_file_comp 1 + return 0 + end + + set nospace (math (math --scale 0 $directive / %[4]d) %% 2) + set nofiles (math (math --scale 0 $directive / %[5]d) %% 2) + + __%[1]s_debug "nospace: $nospace, nofiles: $nofiles" + + # Important not to quote the variable for count to work + set numComps (count $__%[1]s_comp_results) + __%[1]s_debug "numComps: $numComps" + + if test $numComps -eq 1; and test $nospace -ne 0 + # To support the "nospace" directive we trick the shell + # by outputting an extra, longer completion. + __%[1]s_debug "Adding second completion to perform nospace directive" + set --append __%[1]s_comp_results $__%[1]s_comp_results[1]. + end + + if test $numComps -eq 0; and test $nofiles -eq 0 + __%[1]s_debug "Requesting file completion" + set --global __%[1]s_comp_do_file_comp 1 + end + + # If we don't want file completion, we must return true even if there + # are no completions found. This is because fish will perform the last + # completion command, even if its condition is false, if no other + # completion command was triggered + return (not set --query __%[1]s_comp_do_file_comp) +end + +# Remove any pre-existing completions for the program since we will be handling all of them +# TODO this cleanup is not sufficient. Fish completions are only loaded once the user triggers +# them, so the below deletion will not work as it is run too early. What else can we do? +complete -c %[1]s -e + +# The order in which the below two lines are defined is very important so that __%[1]s_prepare_completions +# is called first. It is __%[1]s_prepare_completions that sets up the __%[1]s_comp_do_file_comp variable. +# +# This completion will be run second as complete commands are added FILO. +# It triggers file completion choices when __%[1]s_comp_do_file_comp is set. +complete -c %[1]s -n 'set --query __%[1]s_comp_do_file_comp' + +# This completion will be run first as complete commands are added FILO. +# The call to __%[1]s_prepare_completions will setup both __%[1]s_comp_results abd __%[1]s_comp_do_file_comp. +# It provides the program's completion choices. +complete -c %[1]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' + +`, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp)) +} + +// GenFishCompletion generates fish completion file and writes to the passed writer. +func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error { + buf := new(bytes.Buffer) + genFishComp(buf, c.Name(), includeDesc) + _, err := buf.WriteTo(w) + return err +} + +// GenFishCompletionFile generates fish completion file. +func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.GenFishCompletion(outFile, includeDesc) +} diff --git a/vendor/github.com/spf13/cobra/fish_completions.md b/vendor/github.com/spf13/cobra/fish_completions.md new file mode 100644 index 00000000000..6bfe5f88ef2 --- /dev/null +++ b/vendor/github.com/spf13/cobra/fish_completions.md @@ -0,0 +1,7 @@ +## Generating Fish Completions for your own cobra.Command + +Cobra supports native Fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. + +### Limitations + +* Custom completions implemented using the `ValidArgsFunction` and `RegisterFlagCompletionFunc()` are supported automatically but the ones implemented in Bash scripting are not. diff --git a/vendor/github.com/spf13/cobra/go.mod b/vendor/github.com/spf13/cobra/go.mod index 9a9eb65a370..dea1030ba43 100644 --- a/vendor/github.com/spf13/cobra/go.mod +++ b/vendor/github.com/spf13/cobra/go.mod @@ -3,11 +3,10 @@ module github.com/spf13/cobra go 1.12 require ( - github.com/BurntSushi/toml v0.3.1 // indirect - github.com/cpuguy83/go-md2man v1.0.10 + github.com/cpuguy83/go-md2man/v2 v2.0.0 github.com/inconshreveable/mousetrap v1.0.0 github.com/mitchellh/go-homedir v1.1.0 github.com/spf13/pflag v1.0.3 - github.com/spf13/viper v1.3.2 + github.com/spf13/viper v1.4.0 gopkg.in/yaml.v2 v2.2.2 ) diff --git a/vendor/github.com/spf13/cobra/go.sum b/vendor/github.com/spf13/cobra/go.sum index 9761f4d03fe..3aaa2ac0fd6 100644 --- a/vendor/github.com/spf13/cobra/go.sum +++ b/vendor/github.com/spf13/cobra/go.sum @@ -1,31 +1,91 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= -github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/cpuguy83/go-md2man v1.0.10 h1:BSKMNlYxDvnunlTymqtgONjNnaRV1sTpcovwwjF22jk= -github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/cpuguy83/go-md2man/v2 v2.0.0 h1:EoUDS0afbrsXAZ9YQ9jdu/mZ2sXgT1/2yyNng4PGlyM= +github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/russross/blackfriday v1.5.2 h1:HyvC0ARfnZBqnXwABFeSZHpKvJHJJfPz81GNueLj0oo= -github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= +github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= +github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= @@ -34,18 +94,56 @@ github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9 github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/viper v1.3.2 h1:VUFqw5KcqRf7i70GOzW7N+Q7+gxVBkSSqiXB12+JQ4M= -github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/spf13/viper v1.4.0 h1:yXHLWeravcrgGyFSyCgdYpXQ9dR9c/WED3pg1RhxqEU= +github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= -golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a h1:1n5lsVfiQW3yfsRGu98756EH1YthsFqr/5mxHduZW2A= -golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= +gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/vendor/github.com/spf13/viper/.editorconfig b/vendor/github.com/spf13/viper/.editorconfig new file mode 100644 index 00000000000..63afcbcdd4d --- /dev/null +++ b/vendor/github.com/spf13/viper/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.go] +indent_style = tab + +[{Makefile, *.mk}] +indent_style = tab diff --git a/vendor/github.com/spf13/viper/.gitignore b/vendor/github.com/spf13/viper/.gitignore index d6941f324bb..89625083986 100644 --- a/vendor/github.com/spf13/viper/.gitignore +++ b/vendor/github.com/spf13/viper/.gitignore @@ -1,20 +1,5 @@ +/.idea/ /bin/ /build/ /var/ /vendor/ - -# IDE integration -/.vscode/* -!/.vscode/launch.json -!/.vscode/tasks.json -/.idea/* -!/.idea/codeStyles/ -!/.idea/copyright/ -!/.idea/dataSources.xml -!/.idea/*.iml -!/.idea/externalDependencies.xml -!/.idea/go.imports.xml -!/.idea/modules.xml -!/.idea/runConfigurations/ -!/.idea/scopes/ -!/.idea/sqldialects.xml diff --git a/vendor/github.com/spf13/viper/.golangci.yml b/vendor/github.com/spf13/viper/.golangci.yml index 0ea9249e798..a0755ce7e15 100644 --- a/vendor/github.com/spf13/viper/.golangci.yml +++ b/vendor/github.com/spf13/viper/.golangci.yml @@ -21,4 +21,7 @@ linters: - scopelint - gocyclo - gocognit - - gocritic \ No newline at end of file + - gocritic + +service: + golangci-lint-version: 1.21.x diff --git a/vendor/github.com/spf13/viper/.travis.yml b/vendor/github.com/spf13/viper/.travis.yml deleted file mode 100644 index ed677bbb814..00000000000 --- a/vendor/github.com/spf13/viper/.travis.yml +++ /dev/null @@ -1,32 +0,0 @@ -go_import_path: github.com/spf13/viper - -language: go - -env: - global: - - GO111MODULE="on" - - GOFLAGS="-mod=readonly" - -go: - - 1.11.x - - 1.12.x - - 1.13.x - - tip - -os: - - linux - - osx - -matrix: - allow_failures: - - go: tip - fast_finish: true - -script: - - go install ./... - - diff -u <(echo -n) <(gofmt -d .) - - go test -v ./... - -after_success: - - go get -u -d github.com/spf13/hugo - - cd $GOPATH/src/github.com/spf13/hugo && make && ./hugo -s docs && cd - diff --git a/vendor/github.com/spf13/viper/Makefile b/vendor/github.com/spf13/viper/Makefile index e39b8b5efa2..1c2cab03f45 100644 --- a/vendor/github.com/spf13/viper/Makefile +++ b/vendor/github.com/spf13/viper/Makefile @@ -1,9 +1,12 @@ # A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html OS = $(shell uname | tr A-Z a-z) +export PATH := $(abspath bin/):${PATH} # Build variables BUILD_DIR ?= build +export CGO_ENABLED ?= 0 +export GOOS = $(shell go env GOOS) ifeq (${VERBOSE}, 1) ifeq ($(filter -v,${GOARGS}),) GOARGS += -v @@ -12,7 +15,7 @@ TEST_FORMAT = short-verbose endif # Dependency versions -GOTESTSUM_VERSION = 0.3.5 +GOTESTSUM_VERSION = 0.4.0 GOLANGCI_VERSION = 1.21.0 # Add the ability to override some variables @@ -33,20 +36,19 @@ bin/gotestsum-${GOTESTSUM_VERSION}: curl -L https://github.com/gotestyourself/gotestsum/releases/download/v${GOTESTSUM_VERSION}/gotestsum_${GOTESTSUM_VERSION}_${OS}_amd64.tar.gz | tar -zOxf - gotestsum > ./bin/gotestsum-${GOTESTSUM_VERSION} && chmod +x ./bin/gotestsum-${GOTESTSUM_VERSION} TEST_PKGS ?= ./... -TEST_REPORT_NAME ?= results.xml .PHONY: test -test: TEST_REPORT ?= main test: TEST_FORMAT ?= short test: SHELL = /bin/bash +test: export CGO_ENABLED=1 test: bin/gotestsum ## Run tests - @mkdir -p ${BUILD_DIR}/test_results/${TEST_REPORT} - bin/gotestsum --no-summary=skipped --junitfile ${BUILD_DIR}/test_results/${TEST_REPORT}/${TEST_REPORT_NAME} --format ${TEST_FORMAT} -- $(filter-out -v,${GOARGS}) $(if ${TEST_PKGS},${TEST_PKGS},./...) + @mkdir -p ${BUILD_DIR} + bin/gotestsum --no-summary=skipped --junitfile ${BUILD_DIR}/coverage.xml --format ${TEST_FORMAT} -- -race -coverprofile=${BUILD_DIR}/coverage.txt -covermode=atomic $(filter-out -v,${GOARGS}) $(if ${TEST_PKGS},${TEST_PKGS},./...) bin/golangci-lint: bin/golangci-lint-${GOLANGCI_VERSION} @ln -sf golangci-lint-${GOLANGCI_VERSION} bin/golangci-lint bin/golangci-lint-${GOLANGCI_VERSION}: @mkdir -p bin - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | BINARY=golangci-lint bash -s -- v${GOLANGCI_VERSION} + curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b ./bin/ v${GOLANGCI_VERSION} @mv bin/golangci-lint $@ .PHONY: lint @@ -57,6 +59,9 @@ lint: bin/golangci-lint ## Run linter fix: bin/golangci-lint ## Fix lint violations bin/golangci-lint run --fix +# Add custom targets here +-include custom.mk + .PHONY: list list: ## List all make targets @${MAKE} -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | egrep -v -e '^[^[:alnum:]]' -e '^$@$$' | sort diff --git a/vendor/github.com/spf13/viper/README.md b/vendor/github.com/spf13/viper/README.md index 327308bc6ff..dfd8034fd56 100644 --- a/vendor/github.com/spf13/viper/README.md +++ b/vendor/github.com/spf13/viper/README.md @@ -1,10 +1,13 @@ -![viper logo](https://cloud.githubusercontent.com/assets/173412/10886745/998df88a-8151-11e5-9448-4736db51020d.png) +![Viper](.github/logo.png?raw=true) -Go configuration with fangs! +[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge-flat.svg)](https://github.com/avelino/awesome-go#configuration) -[![Actions](https://github.com/spf13/viper/workflows/CI/badge.svg)](https://github.com/spf13/viper) +[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/spf13/viper/CI?style=flat-square)](https://github.com/spf13/viper/actions?query=workflow%3ACI) [![Join the chat at https://gitter.im/spf13/viper](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/spf13/viper?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![GoDoc](https://godoc.org/github.com/spf13/viper?status.svg)](https://godoc.org/github.com/spf13/viper) +[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/viper?style=flat-square)](https://goreportcard.com/report/github.com/spf13/viper) +[![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/mod/github.com/spf13/viper) + +**Go configuration with fangs!** Many Go projects are built using Viper including: @@ -101,6 +104,7 @@ where a configuration file is expected. ```go viper.SetConfigName("config") // name of config file (without extension) +viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name viper.AddConfigPath("/etc/appname/") // path to look for the config file in viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search paths viper.AddConfigPath(".") // optionally look for config in the working directory @@ -124,7 +128,7 @@ if err := viper.ReadInConfig(); err != nil { // Config file found and successfully parsed ``` -*NOTE:* You can also have a file without an extension and specify the format programmaticaly. For those configuration files that lie in the home of the user without any extension like `.bashrc` +*NOTE [since 1.6]:* You can also have a file without an extension and specify the format programmaticaly. For those configuration files that lie in the home of the user without any extension like `.bashrc` ### Writing Config Files @@ -399,7 +403,7 @@ in a Key/Value store such as etcd or Consul. These values take precedence over default values, but are overridden by configuration values retrieved from disk, flags, or environment variables. -Viper uses [crypt](https://github.com/xordataexchange/crypt) to retrieve +Viper uses [crypt](https://github.com/bketelsen/crypt) to retrieve configuration from the K/V store, which means that you can store your configuration values encrypted and have them automatically decrypted if you have the correct gpg keyring. Encryption is optional. @@ -411,7 +415,7 @@ independently of it. K/V store. `crypt` defaults to etcd on http://127.0.0.1:4001. ```bash -$ go get github.com/xordataexchange/crypt/bin/crypt +$ go get github.com/bketelsen/crypt/bin/crypt $ crypt set -plaintext /config/hugo.json /Users/hugo/settings/config.json ``` @@ -434,7 +438,7 @@ err := viper.ReadRemoteConfig() ``` #### Consul -You need to set a key to Consul key/value storage with JSON value containing your desired config. +You need to set a key to Consul key/value storage with JSON value containing your desired config. For example, create a Consul key/value store key `MY_CONSUL_KEY` with value: ```json @@ -453,6 +457,16 @@ fmt.Println(viper.Get("port")) // 8080 fmt.Println(viper.Get("hostname")) // myhostname.com ``` +#### Firestore + +```go +viper.AddRemoteProvider("firestore", "google-cloud-project-id", "collection/document") +viper.SetConfigType("json") // Config's format: "json", "toml", "yaml", "yml" +err := viper.ReadRemoteConfig() +``` + +Of course, you're allowed to use `SecureRemoteProvider` also + ### Remote Key/Value Store Example - Encrypted ```go @@ -692,18 +706,49 @@ var C config v.Unmarshal(&C) ``` +Viper also supports unmarshaling into embedded structs: + +```go +/* +Example config: + +module: + enabled: true + token: 89h3f98hbwf987h3f98wenf89ehf +*/ +type config struct { + Module struct { + Enabled bool + + moduleConfig `mapstructure:",squash"` + } +} + +// moduleConfig could be in a module specific package +type moduleConfig struct { + Token string +} + +var C config + +err := viper.Unmarshal(&C) +if err != nil { + t.Fatalf("unable to decode into struct, %v", err) +} +``` + Viper uses [github.com/mitchellh/mapstructure](https://github.com/mitchellh/mapstructure) under the hood for unmarshaling values which uses `mapstructure` tags by default. ### Marshalling to string -You may need to marshal all the settings held in viper into a string rather than write them to a file. +You may need to marshal all the settings held in viper into a string rather than write them to a file. You can use your favorite format's marshaller with the config returned by `AllSettings()`. ```go import ( yaml "gopkg.in/yaml.v2" // ... -) +) func yamlStringSettings() string { c := viper.AllSettings() diff --git a/vendor/github.com/spf13/viper/go.mod b/vendor/github.com/spf13/viper/go.mod index 0e358cbefb4..7d108dcc210 100644 --- a/vendor/github.com/spf13/viper/go.mod +++ b/vendor/github.com/spf13/viper/go.mod @@ -3,18 +3,15 @@ module github.com/spf13/viper go 1.12 require ( - github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6 // indirect + github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c github.com/coreos/bbolt v1.3.2 // indirect - github.com/coreos/etcd v3.3.10+incompatible // indirect - github.com/coreos/go-semver v0.2.0 // indirect github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e // indirect github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f // indirect github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect github.com/fsnotify/fsnotify v1.4.7 github.com/gogo/protobuf v1.2.1 // indirect github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef // indirect - github.com/google/btree v1.0.0 // indirect - github.com/gorilla/websocket v1.4.0 // indirect + github.com/gorilla/websocket v1.4.2 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 // indirect github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect github.com/grpc-ecosystem/grpc-gateway v1.9.0 // indirect @@ -30,19 +27,14 @@ require ( github.com/spf13/cast v1.3.0 github.com/spf13/jwalterweatherman v1.0.0 github.com/spf13/pflag v1.0.3 - github.com/stretchr/testify v1.2.2 + github.com/stretchr/testify v1.3.0 github.com/subosito/gotenv v1.2.0 github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 // indirect - github.com/ugorji/go v1.1.4 // indirect github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2 // indirect - github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77 go.etcd.io/bbolt v1.3.2 // indirect go.uber.org/atomic v1.4.0 // indirect go.uber.org/multierr v1.1.0 // indirect go.uber.org/zap v1.10.0 // indirect - golang.org/x/net v0.0.0-20190522155817-f3200d17e092 // indirect - golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 // indirect - google.golang.org/grpc v1.21.0 // indirect gopkg.in/ini.v1 v1.51.0 gopkg.in/yaml.v2 v2.2.4 ) diff --git a/vendor/github.com/spf13/viper/go.sum b/vendor/github.com/spf13/viper/go.sum index d75aee23d83..463aa7dbf5e 100644 --- a/vendor/github.com/spf13/viper/go.sum +++ b/vendor/github.com/spf13/viper/go.sum @@ -1,35 +1,62 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3 h1:AVXDdKsrtX33oR9fbCMu/+c1o8Ofjq6Ku/MInaLVg5Y= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go/bigquery v1.0.1 h1:hL+ycaJpVE9M7nLoiXb/Pn10ENE2u+oddxbD8uu0ZVU= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/datastore v1.0.0 h1:Kt+gOPPp2LEPWp8CSfxhsM8ik9CcyE/gYu+0r+RnZvM= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/firestore v1.1.0 h1:9x7Bx0A9R5/M9jibeJeZWqjeVEIxYW9fZYqB9a70/bY= +cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= +cloud.google.com/go/pubsub v1.0.1 h1:W9tAK3E57P75u0XLLR82LZyw8VpAnhmyTOxW9qzmyj8= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/storage v1.0.0 h1:VV2nUM3wwLLGh9lSABFgZMjInyUbJeaRSE64WuAIQ+4= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6 h1:G1bPvciwNyF7IUmKXNt9Ak3m6u9DE1rF+RmtIkBpVdA= -github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= +github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da h1:8GUt8eRujhVEGZFFEjBj46YV4rDjvGrNxb0KMWYkL2I= +github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0 h1:HWo1m869IqiPhD389kmkxeTalrjNbbJTC8LXupb+sl0= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c h1:+0HFd5KSZ/mm3JmhmrDukiId5iR6w4+BdFtfSy4yWIc= +github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/coreos/bbolt v1.3.2 h1:wZwiHHUieZCquLkDL0B8UhzreNWsPHooDAG3q34zk0s= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= -github.com/coreos/etcd v3.3.10+incompatible h1:jFneRYjIvLMLhDLCzuTuU4rSJUjRplcJQ7pD7MnhC04= -github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= -github.com/coreos/go-semver v0.2.0 h1:3Jm3tLmsgAYcjC+4Up7hJrFBPr+n7rAqYeSw/SZazuY= -github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/etcd v3.3.13+incompatible h1:8F3hqu9fGYLBifCmRCJsicFqDx/D68Rt3q1JMazcgBQ= +github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.3.0 h1:wkHLiw0WNATZnSG7epLsujiMCgPAc9xhjJ4tgnAxmfM= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e h1:Wf6HqHfScWJN9/ZjdUKyjop4mf3Qdd+1TvvltAvM3m8= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f h1:lBNOc5arjvs8E5mO2tbpBpLoyyu8B6e44T7hJy6potg= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= @@ -42,26 +69,77 @@ github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfU github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef h1:veQD95Isof8w9/WXiA+pa3tz3fJXkt5B7QaRBrM62gk= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= -github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0 h1:Iju5GlWwrvL6UBg4zJJt3btmonfrMlCDdsejg4CZE7c= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.9.0 h1:bM6ZAFZmc/wPFaRDi0d5L7hGEZEx/2u+Tmr2evNHDiI= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/hashicorp/consul/api v1.1.0 h1:BNQPM9ytxj6jbjjdRPioQ94T6YXriSopn0i8COv6SRA= +github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= +github.com/hashicorp/consul/sdk v0.1.1 h1:LnuDWGNsoajlhGyHJvuWW6FVqRl8JOTPqS6CPTsYjhY= +github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= +github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-immutable-radix v1.0.0 h1:AKDB1HM5PWEA7i4nhcpwOrO2byshxBjXVn/J/3+z5/0= +github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-msgpack v0.5.3 h1:zKjpN5BK/P5lMYrLmBHdBULWbJ0XpYR+7NGzqkZzoD4= +github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= +github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-rootcerts v1.0.0 h1:Rqb66Oo1X/eSV1x66xbDccZjhJigjg0+e82kpwzSwCI= +github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= +github.com/hashicorp/go-sockaddr v1.0.0 h1:GeH6tui99pF4NJgfnhp+L6+FfobzVW3Ah46sLo0ICXs= +github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= +github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.1 h1:fv1ep09latC32wFoVwnqcnKJGnMSdBanPczbHAYm1BE= +github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= +github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= +github.com/hashicorp/memberlist v0.1.3 h1:EmmoJme1matNzb+hMpDuR/0sbJSUisxyqBGG676r31M= +github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= +github.com/hashicorp/serf v0.8.2 h1:YZ7UKsJv+hKjqGVUUbtE3HNj79Eln2oQ75tniF6iPt0= +github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/jonboulle/clockwork v0.1.0 h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/json-iterator/go v1.1.6 h1:MrUvLMLTMxbqFJ9kzlvat/rYZqZnW3u4wkLzWTaFwKs= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024 h1:rBMNdlhTLzJjJSDIjNEXX1Pz3Hmwmz91v+zycvx9PJc= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= @@ -77,18 +155,39 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/miekg/dns v1.0.14 h1:9jZdLNd/P4+SfEJ0TNyxYpsK8N4GtfylBLqtbYN1sbA= +github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= +github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= +github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-testing-interface v1.0.0 h1:fzU/JVNcaqHQEcVFAKeR41fkiLdIPrefOvVG1VZ96U0= +github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= +github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= +github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c h1:Lgl0gzECD8GnQ5QCWA8o6BtfL6mDH5rQgM4/fX3avOs= +github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3 h1:9iH4JKXLzFbOAdtqv/a+j8aewx2Y8lAjAydhbaScPF8= github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= @@ -103,6 +202,10 @@ github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084 h1:sofwID9zm4tzr github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I= +github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= @@ -120,21 +223,23 @@ github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9 github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5 h1:LnC5Kc/wtumK+WB441p7ynQJzVuNRJiqddSIE3IlSEQ= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/ugorji/go v1.1.4 h1:j4s+tAvLfL3bZyefP2SEWmhBzmuIlH/eqNuPdFPgngw= -github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2 h1:eY9dn8+vbi4tKz5Qo6v2eYzo7kUS51QINcR5jNpbZS8= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77 h1:ESFSdwYZvkeru3RtdrYueztKhOBCSAAzS4Gf+k0tEow= -github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= go.etcd.io/bbolt v1.3.2 h1:Z/90sZLPOeCy2PwprqkFa25PdkusRzaj9P8zm/KNyvk= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0 h1:C9hSCOW830chIVkdja34wa6Ky+IzWllkUinR+BtRZd4= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= @@ -142,46 +247,132 @@ go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/ go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5 h1:58fnuSXlxZmFdJyvtTFVmVhcMLU6v5fEb/ok4wyqtNU= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136 h1:A1gGSx58LAGVHUUsOf7IiR0u8Xb6W51gRwfDBhkdcaw= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190522155817-f3200d17e092 h1:4QSRKanuywn15aTZvI/mIDEgPQpswuFndXpOj3rKEco= -golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0 h1:HyfiK1WMnHj5FXFXatD+Qs1A/xC2Run6RzeW1SyHxpc= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 h1:SvFZT6jyqRaOeXpc5h/JSfZenJ2O330aBsf7JfSUXmQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384 h1:TFlARGu6Czu1z7q93HTxcP1P+/ZFC/IKythI5RzrnRg= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc h1:NCy3Ohtk6Iny5V/reW2Ktypo4zIpWBdRJ1uFMjBxdg8= +golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0 h1:Q3Ui3V3/CVinFWFiW39Iw0kMuVrRzYX0wN6OPFp0lTA= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1 h1:QzqyMA1tlu6CgqCDUtU9V+ZKhLFT2dkJuANu5QaxI3I= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8 h1:Nw54tB0rB7hY/N0NQvRW8DG4Yk3Q6T9cu9RcFQDu1tc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a h1:Ob5/580gVHBJZgXnff1cZDbG+xLtMVE5mDRTe+nIsX4= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.21.0 h1:G+97AoqBnmZIT91cLG/EkCoK9NSelj64P8bOHHNmGn0= -google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.1 h1:j6XxA85m/6txkUCHvzlV5f+HBNl/1r5cZ2A/3IEFOO8= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= @@ -190,3 +381,8 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= diff --git a/vendor/github.com/spf13/viper/viper.go b/vendor/github.com/spf13/viper/viper.go index eb2f5177adc..f61f4ed7555 100644 --- a/vendor/github.com/spf13/viper/viper.go +++ b/vendor/github.com/spf13/viper/viper.go @@ -287,7 +287,7 @@ func NewWithOptions(opts ...Option) *Viper { func Reset() { v = New() SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "dotenv", "env", "ini"} - SupportedRemoteProviders = []string{"etcd", "consul"} + SupportedRemoteProviders = []string{"etcd", "consul", "firestore"} } type defaultRemoteProvider struct { @@ -328,7 +328,7 @@ type RemoteProvider interface { var SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "dotenv", "env", "ini"} // SupportedRemoteProviders are universally supported remote providers. -var SupportedRemoteProviders = []string{"etcd", "consul"} +var SupportedRemoteProviders = []string{"etcd", "consul", "firestore"} func OnConfigChange(run func(in fsnotify.Event)) { v.OnConfigChange(run) } func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) { @@ -477,7 +477,7 @@ func (v *Viper) AddConfigPath(in string) { // AddRemoteProvider adds a remote configuration source. // Remote Providers are searched in the order they are added. -// provider is a string value, "etcd" or "consul" are currently supported. +// provider is a string value: "etcd", "consul" or "firestore" are currently supported. // endpoint is the url. etcd requires http://ip:port consul requires ip:port // path is the path in the k/v store to retrieve configuration // To retrieve a config file called myapp.json from /configs/myapp.json @@ -506,14 +506,14 @@ func (v *Viper) AddRemoteProvider(provider, endpoint, path string) error { // AddSecureRemoteProvider adds a remote configuration source. // Secure Remote Providers are searched in the order they are added. -// provider is a string value, "etcd" or "consul" are currently supported. +// provider is a string value: "etcd", "consul" or "firestore" are currently supported. // endpoint is the url. etcd requires http://ip:port consul requires ip:port // secretkeyring is the filepath to your openpgp secret keyring. e.g. /etc/secrets/myring.gpg // path is the path in the k/v store to retrieve configuration // To retrieve a config file called myapp.json from /configs/myapp.json // you should set path to /configs and set config name (SetConfigName()) to // "myapp" -// Secure Remote Providers are implemented with github.com/xordataexchange/crypt +// Secure Remote Providers are implemented with github.com/bketelsen/crypt func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error { return v.AddSecureRemoteProvider(provider, endpoint, path, secretkeyring) } @@ -996,11 +996,6 @@ func (v *Viper) BindFlagValues(flags FlagValueSet) (err error) { } // BindFlagValue binds a specific key to a FlagValue. -// Example (where serverCmd is a Cobra instance): -// -// serverCmd.Flags().Int("port", 1138, "Port to run Application server on") -// Viper.BindFlagValue("port", serverCmd.Flags().Lookup("port")) -// func BindFlagValue(key string, flag FlagValue) error { return v.BindFlagValue(key, flag) } func (v *Viper) BindFlagValue(key string, flag FlagValue) error { if flag == nil { @@ -1088,6 +1083,8 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} { s = strings.TrimSuffix(s, "]") res, _ := readAsCSV(s) return cast.ToIntSlice(res) + case "stringToString": + return stringToStringConv(flag.ValueString()) default: return flag.ValueString() } @@ -1163,6 +1160,8 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} { s = strings.TrimSuffix(s, "]") res, _ := readAsCSV(s) return cast.ToIntSlice(res) + case "stringToString": + return stringToStringConv(flag.ValueString()) default: return flag.ValueString() } @@ -1182,6 +1181,30 @@ func readAsCSV(val string) ([]string, error) { return csvReader.Read() } +// mostly copied from pflag's implementation of this operation here https://github.com/spf13/pflag/blob/master/string_to_string.go#L79 +// alterations are: errors are swallowed, map[string]interface{} is returned in order to enable cast.ToStringMap +func stringToStringConv(val string) interface{} { + val = strings.Trim(val, "[]") + // An empty string would cause an empty map + if len(val) == 0 { + return map[string]interface{}{} + } + r := csv.NewReader(strings.NewReader(val)) + ss, err := r.Read() + if err != nil { + return nil + } + out := make(map[string]interface{}, len(ss)) + for _, pair := range ss { + kv := strings.SplitN(pair, "=", 2) + if len(kv) != 2 { + return nil + } + out[kv[0]] = kv[1] + } + return out +} + // IsSet checks to see if the key has been set in any of the data locations. // IsSet is case-insensitive for a key. func IsSet(key string) bool { return v.IsSet(key) } @@ -1418,11 +1441,18 @@ func (v *Viper) SafeWriteConfigAs(filename string) error { func (v *Viper) writeConfig(filename string, force bool) error { jww.INFO.Println("Attempting to write configuration to file.") + var configType string + ext := filepath.Ext(filename) - if len(ext) <= 1 { - return fmt.Errorf("filename: %s requires valid extension", filename) + if ext != "" { + configType = ext[1:] + } else { + configType = v.configType } - configType := ext[1:] + if configType == "" { + return fmt.Errorf("config type could not be determined for %s", filename) + } + if !stringInSlice(configType, SupportedExts) { return UnsupportedConfigError(configType) } @@ -1619,7 +1649,7 @@ func (v *Viper) marshalWriter(f afero.File, configType string) error { if sectionName == "default" { sectionName = "" } - cfg.Section(sectionName).Key(keyName).SetValue(Get(key).(string)) + cfg.Section(sectionName).Key(keyName).SetValue(v.Get(key).(string)) } cfg.WriteTo(f) } @@ -1976,8 +2006,10 @@ func (v *Viper) searchInPath(in string) (filename string) { } } - if b, _ := exists(v.fs, filepath.Join(in, v.configName)); b { - return filepath.Join(in, v.configName) + if v.configType != "" { + if b, _ := exists(v.fs, filepath.Join(in, v.configName)); b { + return filepath.Join(in, v.configName) + } } return "" diff --git a/vendor/github.com/stretchr/objx/.codeclimate.yml b/vendor/github.com/stretchr/objx/.codeclimate.yml index 559fa399c13..010d4ccd582 100644 --- a/vendor/github.com/stretchr/objx/.codeclimate.yml +++ b/vendor/github.com/stretchr/objx/.codeclimate.yml @@ -10,12 +10,4 @@ exclude_patterns: - ".github/" - "vendor/" - "codegen/" -- "*.yml" -- ".*.yml" -- "*.md" -- "Gopkg.*" - "doc.go" -- "type_specific_codegen_test.go" -- "type_specific_codegen.go" -- ".gitignore" -- "LICENSE" diff --git a/vendor/github.com/stretchr/objx/.travis.yml b/vendor/github.com/stretchr/objx/.travis.yml index cde6eb2affd..a63efa59d1d 100644 --- a/vendor/github.com/stretchr/objx/.travis.yml +++ b/vendor/github.com/stretchr/objx/.travis.yml @@ -1,14 +1,8 @@ language: go go: - - "1.10.x" - - "1.11.x" - - "1.12.x" - - master - -matrix: - allow_failures: - - go: master -fast_finish: true + - 1.8 + - 1.9 + - tip env: global: @@ -20,11 +14,12 @@ before_script: - ./cc-test-reporter before-build install: - - curl -sL https://taskfile.dev/install.sh | sh +- go get github.com/go-task/task/cmd/task script: - - diff -u <(echo -n) <(./bin/task lint) - - ./bin/task test-coverage +- task dl-deps +- task lint +- task test-coverage after_script: - ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT diff --git a/vendor/github.com/stretchr/objx/Gopkg.lock b/vendor/github.com/stretchr/objx/Gopkg.lock new file mode 100644 index 00000000000..eebe342a960 --- /dev/null +++ b/vendor/github.com/stretchr/objx/Gopkg.lock @@ -0,0 +1,30 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + name = "github.com/davecgh/go-spew" + packages = ["spew"] + revision = "346938d642f2ec3594ed81d874461961cd0faa76" + version = "v1.1.0" + +[[projects]] + name = "github.com/pmezard/go-difflib" + packages = ["difflib"] + revision = "792786c7400a136282c1664665ae0a8db921c6c2" + version = "v1.0.0" + +[[projects]] + name = "github.com/stretchr/testify" + packages = [ + "assert", + "require" + ] + revision = "b91bfb9ebec76498946beb6af7c0230c7cc7ba6c" + version = "v1.2.0" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + inputs-digest = "2d160a7dea4ffd13c6c31dab40373822f9d78c73beba016d662bef8f7a998876" + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/vendor/github.com/stretchr/objx/Gopkg.toml b/vendor/github.com/stretchr/objx/Gopkg.toml new file mode 100644 index 00000000000..d70f1570b95 --- /dev/null +++ b/vendor/github.com/stretchr/objx/Gopkg.toml @@ -0,0 +1,8 @@ +[prune] + unused-packages = true + non-go = true + go-tests = true + +[[constraint]] + name = "github.com/stretchr/testify" + version = "~1.2.0" diff --git a/vendor/github.com/stretchr/objx/README.md b/vendor/github.com/stretchr/objx/README.md index 246660b21a9..be5750c94c8 100644 --- a/vendor/github.com/stretchr/objx/README.md +++ b/vendor/github.com/stretchr/objx/README.md @@ -74,7 +74,7 @@ To update Objx to the latest version, run: go get -u github.com/stretchr/objx ### Supported go versions -We support the lastest three major Go versions, which are 1.10, 1.11 and 1.12 at the moment. +We support the lastest two major Go versions, which are 1.8 and 1.9 at the moment. ## Contributing Please feel free to submit issues, fork the repository and send pull requests! diff --git a/vendor/github.com/stretchr/objx/Taskfile.yml b/vendor/github.com/stretchr/objx/Taskfile.yml index a749ac5492e..f8035641f2d 100644 --- a/vendor/github.com/stretchr/objx/Taskfile.yml +++ b/vendor/github.com/stretchr/objx/Taskfile.yml @@ -1,30 +1,32 @@ -version: '2' +default: + deps: [test] -env: - GOFLAGS: -mod=vendor +dl-deps: + desc: Downloads cli dependencies + cmds: + - go get -u github.com/golang/lint/golint + - go get -u github.com/golang/dep/cmd/dep -tasks: - default: - deps: [test] +update-deps: + desc: Updates dependencies + cmds: + - dep ensure + - dep ensure -update - lint: - desc: Checks code style - cmds: - - gofmt -d -s *.go - - go vet ./... - silent: true +lint: + desc: Runs golint + cmds: + - go fmt $(go list ./... | grep -v /vendor/) + - go vet $(go list ./... | grep -v /vendor/) + - golint $(ls *.go | grep -v "doc.go") + silent: true - lint-fix: - desc: Fixes code style - cmds: - - gofmt -w -s *.go +test: + desc: Runs go tests + cmds: + - go test -race . - test: - desc: Runs go tests - cmds: - - go test -race ./... - - test-coverage: - desc: Runs go tests and calucates test coverage - cmds: - - go test -race -coverprofile=c.out ./... +test-coverage: + desc: Runs go tests and calucates test coverage + cmds: + - go test -coverprofile=c.out . diff --git a/vendor/github.com/stretchr/objx/accessors.go b/vendor/github.com/stretchr/objx/accessors.go index 67631628115..204356a2285 100644 --- a/vendor/github.com/stretchr/objx/accessors.go +++ b/vendor/github.com/stretchr/objx/accessors.go @@ -6,17 +6,9 @@ import ( "strings" ) -const ( - // PathSeparator is the character used to separate the elements - // of the keypath. - // - // For example, `location.address.city` - PathSeparator string = "." - - // arrayAccesRegexString is the regex used to extract the array number - // from the access path - arrayAccesRegexString = `^(.+)\[([0-9]+)\]$` -) +// arrayAccesRegexString is the regex used to extract the array number +// from the access path +const arrayAccesRegexString = `^(.+)\[([0-9]+)\]$` // arrayAccesRegex is the compiled arrayAccesRegexString var arrayAccesRegex = regexp.MustCompile(arrayAccesRegexString) @@ -54,66 +46,103 @@ func (m Map) Set(selector string, value interface{}) Map { return m } -// getIndex returns the index, which is hold in s by two braches. -// It also returns s withour the index part, e.g. name[1] will return (1, name). -// If no index is found, -1 is returned -func getIndex(s string) (int, string) { - arrayMatches := arrayAccesRegex.FindStringSubmatch(s) - if len(arrayMatches) > 0 { - // Get the key into the map - selector := arrayMatches[1] - // Get the index into the array at the key - // We know this cannt fail because arrayMatches[2] is an int for sure - index, _ := strconv.Atoi(arrayMatches[2]) - return index, selector - } - return -1, s -} - // access accesses the object using the selector and performs the // appropriate action. -func access(current interface{}, selector string, value interface{}, isSet bool) interface{} { - selSegs := strings.SplitN(selector, PathSeparator, 2) - thisSel := selSegs[0] - index := -1 +func access(current, selector, value interface{}, isSet bool) interface{} { + switch selector.(type) { + case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: + if array, ok := current.([]interface{}); ok { + index := intFromInterface(selector) + if index >= len(array) { + return nil + } + return array[index] + } + return nil - if strings.Contains(thisSel, "[") { - index, thisSel = getIndex(thisSel) - } + case string: + selStr := selector.(string) + selSegs := strings.SplitN(selStr, PathSeparator, 2) + thisSel := selSegs[0] + index := -1 + var err error - if curMap, ok := current.(Map); ok { - current = map[string]interface{}(curMap) - } - // get the object in question - switch current.(type) { - case map[string]interface{}: - curMSI := current.(map[string]interface{}) - if len(selSegs) <= 1 && isSet { - curMSI[thisSel] = value - return nil - } + if strings.Contains(thisSel, "[") { + arrayMatches := arrayAccesRegex.FindStringSubmatch(thisSel) + if len(arrayMatches) > 0 { + // Get the key into the map + thisSel = arrayMatches[1] - _, ok := curMSI[thisSel].(map[string]interface{}) - if (curMSI[thisSel] == nil || !ok) && index == -1 && isSet { - curMSI[thisSel] = map[string]interface{}{} - } + // Get the index into the array at the key + index, err = strconv.Atoi(arrayMatches[2]) - current = curMSI[thisSel] - default: - current = nil - } - // do we need to access the item of an array? - if index > -1 { - if array, ok := current.([]interface{}); ok { - if index < len(array) { - current = array[index] - } else { - current = nil + if err != nil { + // This should never happen. If it does, something has gone + // seriously wrong. Panic. + panic("objx: Array index is not an integer. Must use array[int].") + } } } - } - if len(selSegs) > 1 { - current = access(current, selSegs[1], value, isSet) + if curMap, ok := current.(Map); ok { + current = map[string]interface{}(curMap) + } + // get the object in question + switch current.(type) { + case map[string]interface{}: + curMSI := current.(map[string]interface{}) + if len(selSegs) <= 1 && isSet { + curMSI[thisSel] = value + return nil + } + current = curMSI[thisSel] + default: + current = nil + } + // do we need to access the item of an array? + if index > -1 { + if array, ok := current.([]interface{}); ok { + if index < len(array) { + current = array[index] + } else { + current = nil + } + } + } + if len(selSegs) > 1 { + current = access(current, selSegs[1], value, isSet) + } } return current } + +// intFromInterface converts an interface object to the largest +// representation of an unsigned integer using a type switch and +// assertions +func intFromInterface(selector interface{}) int { + var value int + switch selector.(type) { + case int: + value = selector.(int) + case int8: + value = int(selector.(int8)) + case int16: + value = int(selector.(int16)) + case int32: + value = int(selector.(int32)) + case int64: + value = int(selector.(int64)) + case uint: + value = int(selector.(uint)) + case uint8: + value = int(selector.(uint8)) + case uint16: + value = int(selector.(uint16)) + case uint32: + value = int(selector.(uint32)) + case uint64: + value = int(selector.(uint64)) + default: + return 0 + } + return value +} diff --git a/vendor/github.com/stretchr/objx/constants.go b/vendor/github.com/stretchr/objx/constants.go new file mode 100644 index 00000000000..f9eb42a25e0 --- /dev/null +++ b/vendor/github.com/stretchr/objx/constants.go @@ -0,0 +1,13 @@ +package objx + +const ( + // PathSeparator is the character used to separate the elements + // of the keypath. + // + // For example, `location.address.city` + PathSeparator string = "." + + // SignatureSeparator is the character that is used to + // separate the Base64 string from the security signature. + SignatureSeparator = "_" +) diff --git a/vendor/github.com/stretchr/objx/conversions.go b/vendor/github.com/stretchr/objx/conversions.go index 080aa46e472..5e020f310ad 100644 --- a/vendor/github.com/stretchr/objx/conversions.go +++ b/vendor/github.com/stretchr/objx/conversions.go @@ -7,51 +7,11 @@ import ( "errors" "fmt" "net/url" - "strconv" ) -// SignatureSeparator is the character that is used to -// separate the Base64 string from the security signature. -const SignatureSeparator = "_" - -// URLValuesSliceKeySuffix is the character that is used to -// specify a suffic for slices parsed by URLValues. -// If the suffix is set to "[i]", then the index of the slice -// is used in place of i -// Ex: Suffix "[]" would have the form a[]=b&a[]=c -// OR Suffix "[i]" would have the form a[0]=b&a[1]=c -// OR Suffix "" would have the form a=b&a=c -var urlValuesSliceKeySuffix = "[]" - -const ( - URLValuesSliceKeySuffixEmpty = "" - URLValuesSliceKeySuffixArray = "[]" - URLValuesSliceKeySuffixIndex = "[i]" -) - -// SetURLValuesSliceKeySuffix sets the character that is used to -// specify a suffic for slices parsed by URLValues. -// If the suffix is set to "[i]", then the index of the slice -// is used in place of i -// Ex: Suffix "[]" would have the form a[]=b&a[]=c -// OR Suffix "[i]" would have the form a[0]=b&a[1]=c -// OR Suffix "" would have the form a=b&a=c -func SetURLValuesSliceKeySuffix(s string) error { - if s == URLValuesSliceKeySuffixEmpty || s == URLValuesSliceKeySuffixArray || s == URLValuesSliceKeySuffixIndex { - urlValuesSliceKeySuffix = s - return nil - } - - return errors.New("objx: Invalid URLValuesSliceKeySuffix provided.") -} - // JSON converts the contained object to a JSON string // representation func (m Map) JSON() (string, error) { - for k, v := range m { - m[k] = cleanUp(v) - } - result, err := json.Marshal(m) if err != nil { err = errors.New("objx: JSON encode failed with: " + err.Error()) @@ -59,63 +19,6 @@ func (m Map) JSON() (string, error) { return string(result), err } -func cleanUpInterfaceArray(in []interface{}) []interface{} { - result := make([]interface{}, len(in)) - for i, v := range in { - result[i] = cleanUp(v) - } - return result -} - -func cleanUpInterfaceMap(in map[interface{}]interface{}) Map { - result := Map{} - for k, v := range in { - result[fmt.Sprintf("%v", k)] = cleanUp(v) - } - return result -} - -func cleanUpStringMap(in map[string]interface{}) Map { - result := Map{} - for k, v := range in { - result[k] = cleanUp(v) - } - return result -} - -func cleanUpMSIArray(in []map[string]interface{}) []Map { - result := make([]Map, len(in)) - for i, v := range in { - result[i] = cleanUpStringMap(v) - } - return result -} - -func cleanUpMapArray(in []Map) []Map { - result := make([]Map, len(in)) - for i, v := range in { - result[i] = cleanUpStringMap(v) - } - return result -} - -func cleanUp(v interface{}) interface{} { - switch v := v.(type) { - case []interface{}: - return cleanUpInterfaceArray(v) - case []map[string]interface{}: - return cleanUpMSIArray(v) - case map[interface{}]interface{}: - return cleanUpInterfaceMap(v) - case Map: - return cleanUpStringMap(v) - case []Map: - return cleanUpMapArray(v) - default: - return v - } -} - // MustJSON converts the contained object to a JSON string // representation and panics if there is an error func (m Map) MustJSON() string { @@ -137,7 +40,10 @@ func (m Map) Base64() (string, error) { } encoder := base64.NewEncoder(base64.StdEncoding, &buf) - _, _ = encoder.Write([]byte(jsonData)) + _, err = encoder.Write([]byte(jsonData)) + if err != nil { + return "", err + } _ = encoder.Close() return buf.String(), nil @@ -187,89 +93,11 @@ func (m Map) MustSignedBase64(key string) string { // function requires that the wrapped object be a map[string]interface{} func (m Map) URLValues() url.Values { vals := make(url.Values) - - m.parseURLValues(m, vals, "") - - return vals -} - -func (m Map) parseURLValues(queryMap Map, vals url.Values, key string) { - useSliceIndex := false - if urlValuesSliceKeySuffix == "[i]" { - useSliceIndex = true - } - - for k, v := range queryMap { - val := &Value{data: v} - switch { - case val.IsObjxMap(): - if key == "" { - m.parseURLValues(val.ObjxMap(), vals, k) - } else { - m.parseURLValues(val.ObjxMap(), vals, key+"["+k+"]") - } - case val.IsObjxMapSlice(): - sliceKey := k - if key != "" { - sliceKey = key + "[" + k + "]" - } - - if useSliceIndex { - for i, sv := range val.MustObjxMapSlice() { - sk := sliceKey + "[" + strconv.FormatInt(int64(i), 10) + "]" - m.parseURLValues(sv, vals, sk) - } - } else { - sliceKey = sliceKey + urlValuesSliceKeySuffix - for _, sv := range val.MustObjxMapSlice() { - m.parseURLValues(sv, vals, sliceKey) - } - } - case val.IsMSISlice(): - sliceKey := k - if key != "" { - sliceKey = key + "[" + k + "]" - } - - if useSliceIndex { - for i, sv := range val.MustMSISlice() { - sk := sliceKey + "[" + strconv.FormatInt(int64(i), 10) + "]" - m.parseURLValues(New(sv), vals, sk) - } - } else { - sliceKey = sliceKey + urlValuesSliceKeySuffix - for _, sv := range val.MustMSISlice() { - m.parseURLValues(New(sv), vals, sliceKey) - } - } - case val.IsStrSlice(), val.IsBoolSlice(), - val.IsFloat32Slice(), val.IsFloat64Slice(), - val.IsIntSlice(), val.IsInt8Slice(), val.IsInt16Slice(), val.IsInt32Slice(), val.IsInt64Slice(), - val.IsUintSlice(), val.IsUint8Slice(), val.IsUint16Slice(), val.IsUint32Slice(), val.IsUint64Slice(): - - sliceKey := k - if key != "" { - sliceKey = key + "[" + k + "]" - } - - if useSliceIndex { - for i, sv := range val.StringSlice() { - sk := sliceKey + "[" + strconv.FormatInt(int64(i), 10) + "]" - vals.Set(sk, sv) - } - } else { - sliceKey = sliceKey + urlValuesSliceKeySuffix - vals[sliceKey] = val.StringSlice() - } - - default: - if key == "" { - vals.Set(k, val.String()) - } else { - vals.Set(key+"["+k+"]", val.String()) - } - } + for k, v := range m { + //TODO: can this be done without sprintf? + vals.Set(k, fmt.Sprintf("%v", v)) } + return vals } // URLQuery gets an encoded URL query representing the given diff --git a/vendor/github.com/stretchr/objx/go.mod b/vendor/github.com/stretchr/objx/go.mod deleted file mode 100644 index 31ec5a7d948..00000000000 --- a/vendor/github.com/stretchr/objx/go.mod +++ /dev/null @@ -1,8 +0,0 @@ -module github.com/stretchr/objx - -go 1.12 - -require ( - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/stretchr/testify v1.3.0 -) diff --git a/vendor/github.com/stretchr/objx/go.sum b/vendor/github.com/stretchr/objx/go.sum deleted file mode 100644 index 4f89841505b..00000000000 --- a/vendor/github.com/stretchr/objx/go.sum +++ /dev/null @@ -1,8 +0,0 @@ -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= diff --git a/vendor/github.com/stretchr/objx/map.go b/vendor/github.com/stretchr/objx/map.go index 95149c06a6d..406bc892635 100644 --- a/vendor/github.com/stretchr/objx/map.go +++ b/vendor/github.com/stretchr/objx/map.go @@ -97,50 +97,12 @@ func MustFromJSON(jsonString string) Map { // // Returns an error if the JSON is invalid. func FromJSON(jsonString string) (Map, error) { - var m Map - err := json.Unmarshal([]byte(jsonString), &m) + var data interface{} + err := json.Unmarshal([]byte(jsonString), &data) if err != nil { return Nil, err } - m.tryConvertFloat64() - return m, nil -} - -func (m Map) tryConvertFloat64() { - for k, v := range m { - switch v.(type) { - case float64: - f := v.(float64) - if float64(int(f)) == f { - m[k] = int(f) - } - case map[string]interface{}: - t := New(v) - t.tryConvertFloat64() - m[k] = t - case []interface{}: - m[k] = tryConvertFloat64InSlice(v.([]interface{})) - } - } -} - -func tryConvertFloat64InSlice(s []interface{}) []interface{} { - for k, v := range s { - switch v.(type) { - case float64: - f := v.(float64) - if float64(int(f)) == f { - s[k] = int(f) - } - case map[string]interface{}: - t := New(v) - t.tryConvertFloat64() - s[k] = t - case []interface{}: - s[k] = tryConvertFloat64InSlice(v.([]interface{})) - } - } - return s + return New(data), nil } // FromBase64 creates a new Obj containing the data specified diff --git a/vendor/github.com/stretchr/objx/type_specific.go b/vendor/github.com/stretchr/objx/type_specific.go deleted file mode 100644 index 80f88d9fa29..00000000000 --- a/vendor/github.com/stretchr/objx/type_specific.go +++ /dev/null @@ -1,346 +0,0 @@ -package objx - -/* - MSI (map[string]interface{} and []map[string]interface{}) -*/ - -// MSI gets the value as a map[string]interface{}, returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) MSI(optionalDefault ...map[string]interface{}) map[string]interface{} { - if s, ok := v.data.(map[string]interface{}); ok { - return s - } - if s, ok := v.data.(Map); ok { - return map[string]interface{}(s) - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil -} - -// MustMSI gets the value as a map[string]interface{}. -// -// Panics if the object is not a map[string]interface{}. -func (v *Value) MustMSI() map[string]interface{} { - if s, ok := v.data.(Map); ok { - return map[string]interface{}(s) - } - return v.data.(map[string]interface{}) -} - -// MSISlice gets the value as a []map[string]interface{}, returns the optionalDefault -// value or nil if the value is not a []map[string]interface{}. -func (v *Value) MSISlice(optionalDefault ...[]map[string]interface{}) []map[string]interface{} { - if s, ok := v.data.([]map[string]interface{}); ok { - return s - } - - s := v.ObjxMapSlice() - if s == nil { - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil - } - - result := make([]map[string]interface{}, len(s)) - for i := range s { - result[i] = s[i].Value().MSI() - } - return result -} - -// MustMSISlice gets the value as a []map[string]interface{}. -// -// Panics if the object is not a []map[string]interface{}. -func (v *Value) MustMSISlice() []map[string]interface{} { - if s := v.MSISlice(); s != nil { - return s - } - - return v.data.([]map[string]interface{}) -} - -// IsMSI gets whether the object contained is a map[string]interface{} or not. -func (v *Value) IsMSI() bool { - _, ok := v.data.(map[string]interface{}) - if !ok { - _, ok = v.data.(Map) - } - return ok -} - -// IsMSISlice gets whether the object contained is a []map[string]interface{} or not. -func (v *Value) IsMSISlice() bool { - _, ok := v.data.([]map[string]interface{}) - if !ok { - _, ok = v.data.([]Map) - if !ok { - s, ok := v.data.([]interface{}) - if ok { - for i := range s { - switch s[i].(type) { - case Map: - case map[string]interface{}: - default: - return false - } - } - return true - } - } - } - return ok -} - -// EachMSI calls the specified callback for each object -// in the []map[string]interface{}. -// -// Panics if the object is the wrong type. -func (v *Value) EachMSI(callback func(int, map[string]interface{}) bool) *Value { - for index, val := range v.MustMSISlice() { - carryon := callback(index, val) - if !carryon { - break - } - } - return v -} - -// WhereMSI uses the specified decider function to select items -// from the []map[string]interface{}. The object contained in the result will contain -// only the selected items. -func (v *Value) WhereMSI(decider func(int, map[string]interface{}) bool) *Value { - var selected []map[string]interface{} - v.EachMSI(func(index int, val map[string]interface{}) bool { - shouldSelect := decider(index, val) - if !shouldSelect { - selected = append(selected, val) - } - return true - }) - return &Value{data: selected} -} - -// GroupMSI uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][]map[string]interface{}. -func (v *Value) GroupMSI(grouper func(int, map[string]interface{}) string) *Value { - groups := make(map[string][]map[string]interface{}) - v.EachMSI(func(index int, val map[string]interface{}) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([]map[string]interface{}, 0) - } - groups[group] = append(groups[group], val) - return true - }) - return &Value{data: groups} -} - -// ReplaceMSI uses the specified function to replace each map[string]interface{}s -// by iterating each item. The data in the returned result will be a -// []map[string]interface{} containing the replaced items. -func (v *Value) ReplaceMSI(replacer func(int, map[string]interface{}) map[string]interface{}) *Value { - arr := v.MustMSISlice() - replaced := make([]map[string]interface{}, len(arr)) - v.EachMSI(func(index int, val map[string]interface{}) bool { - replaced[index] = replacer(index, val) - return true - }) - return &Value{data: replaced} -} - -// CollectMSI uses the specified collector function to collect a value -// for each of the map[string]interface{}s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectMSI(collector func(int, map[string]interface{}) interface{}) *Value { - arr := v.MustMSISlice() - collected := make([]interface{}, len(arr)) - v.EachMSI(func(index int, val map[string]interface{}) bool { - collected[index] = collector(index, val) - return true - }) - return &Value{data: collected} -} - -/* - ObjxMap ((Map) and [](Map)) -*/ - -// ObjxMap gets the value as a (Map), returns the optionalDefault -// value or a system default object if the value is the wrong type. -func (v *Value) ObjxMap(optionalDefault ...(Map)) Map { - if s, ok := v.data.((Map)); ok { - return s - } - if s, ok := v.data.(map[string]interface{}); ok { - return s - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return New(nil) -} - -// MustObjxMap gets the value as a (Map). -// -// Panics if the object is not a (Map). -func (v *Value) MustObjxMap() Map { - if s, ok := v.data.(map[string]interface{}); ok { - return s - } - return v.data.((Map)) -} - -// ObjxMapSlice gets the value as a [](Map), returns the optionalDefault -// value or nil if the value is not a [](Map). -func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) { - if s, ok := v.data.([]Map); ok { - return s - } - - if s, ok := v.data.([]map[string]interface{}); ok { - result := make([]Map, len(s)) - for i := range s { - result[i] = s[i] - } - return result - } - - s, ok := v.data.([]interface{}) - if !ok { - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - return nil - } - - result := make([]Map, len(s)) - for i := range s { - switch s[i].(type) { - case Map: - result[i] = s[i].(Map) - case map[string]interface{}: - result[i] = New(s[i]) - default: - return nil - } - } - return result -} - -// MustObjxMapSlice gets the value as a [](Map). -// -// Panics if the object is not a [](Map). -func (v *Value) MustObjxMapSlice() [](Map) { - if s := v.ObjxMapSlice(); s != nil { - return s - } - return v.data.([](Map)) -} - -// IsObjxMap gets whether the object contained is a (Map) or not. -func (v *Value) IsObjxMap() bool { - _, ok := v.data.((Map)) - if !ok { - _, ok = v.data.(map[string]interface{}) - } - return ok -} - -// IsObjxMapSlice gets whether the object contained is a [](Map) or not. -func (v *Value) IsObjxMapSlice() bool { - _, ok := v.data.([](Map)) - if !ok { - _, ok = v.data.([]map[string]interface{}) - if !ok { - s, ok := v.data.([]interface{}) - if ok { - for i := range s { - switch s[i].(type) { - case Map: - case map[string]interface{}: - default: - return false - } - } - return true - } - } - } - - return ok -} - -// EachObjxMap calls the specified callback for each object -// in the [](Map). -// -// Panics if the object is the wrong type. -func (v *Value) EachObjxMap(callback func(int, Map) bool) *Value { - for index, val := range v.MustObjxMapSlice() { - carryon := callback(index, val) - if !carryon { - break - } - } - return v -} - -// WhereObjxMap uses the specified decider function to select items -// from the [](Map). The object contained in the result will contain -// only the selected items. -func (v *Value) WhereObjxMap(decider func(int, Map) bool) *Value { - var selected [](Map) - v.EachObjxMap(func(index int, val Map) bool { - shouldSelect := decider(index, val) - if !shouldSelect { - selected = append(selected, val) - } - return true - }) - return &Value{data: selected} -} - -// GroupObjxMap uses the specified grouper function to group the items -// keyed by the return of the grouper. The object contained in the -// result will contain a map[string][](Map). -func (v *Value) GroupObjxMap(grouper func(int, Map) string) *Value { - groups := make(map[string][](Map)) - v.EachObjxMap(func(index int, val Map) bool { - group := grouper(index, val) - if _, ok := groups[group]; !ok { - groups[group] = make([](Map), 0) - } - groups[group] = append(groups[group], val) - return true - }) - return &Value{data: groups} -} - -// ReplaceObjxMap uses the specified function to replace each (Map)s -// by iterating each item. The data in the returned result will be a -// [](Map) containing the replaced items. -func (v *Value) ReplaceObjxMap(replacer func(int, Map) Map) *Value { - arr := v.MustObjxMapSlice() - replaced := make([](Map), len(arr)) - v.EachObjxMap(func(index int, val Map) bool { - replaced[index] = replacer(index, val) - return true - }) - return &Value{data: replaced} -} - -// CollectObjxMap uses the specified collector function to collect a value -// for each of the (Map)s in the slice. The data returned will be a -// []interface{}. -func (v *Value) CollectObjxMap(collector func(int, Map) interface{}) *Value { - arr := v.MustObjxMapSlice() - collected := make([]interface{}, len(arr)) - v.EachObjxMap(func(index int, val Map) bool { - collected[index] = collector(index, val) - return true - }) - return &Value{data: collected} -} diff --git a/vendor/github.com/stretchr/objx/type_specific_codegen.go b/vendor/github.com/stretchr/objx/type_specific_codegen.go index 9859b407f02..202a91f8c19 100644 --- a/vendor/github.com/stretchr/objx/type_specific_codegen.go +++ b/vendor/github.com/stretchr/objx/type_specific_codegen.go @@ -1,7 +1,7 @@ package objx /* - Inter (interface{} and []interface{}) + Inter (interface{} and []interface{}) */ // Inter gets the value as a interface{}, returns the optionalDefault @@ -126,7 +126,257 @@ func (v *Value) CollectInter(collector func(int, interface{}) interface{}) *Valu } /* - Bool (bool and []bool) + MSI (map[string]interface{} and []map[string]interface{}) +*/ + +// MSI gets the value as a map[string]interface{}, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) MSI(optionalDefault ...map[string]interface{}) map[string]interface{} { + if s, ok := v.data.(map[string]interface{}); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustMSI gets the value as a map[string]interface{}. +// +// Panics if the object is not a map[string]interface{}. +func (v *Value) MustMSI() map[string]interface{} { + return v.data.(map[string]interface{}) +} + +// MSISlice gets the value as a []map[string]interface{}, returns the optionalDefault +// value or nil if the value is not a []map[string]interface{}. +func (v *Value) MSISlice(optionalDefault ...[]map[string]interface{}) []map[string]interface{} { + if s, ok := v.data.([]map[string]interface{}); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustMSISlice gets the value as a []map[string]interface{}. +// +// Panics if the object is not a []map[string]interface{}. +func (v *Value) MustMSISlice() []map[string]interface{} { + return v.data.([]map[string]interface{}) +} + +// IsMSI gets whether the object contained is a map[string]interface{} or not. +func (v *Value) IsMSI() bool { + _, ok := v.data.(map[string]interface{}) + return ok +} + +// IsMSISlice gets whether the object contained is a []map[string]interface{} or not. +func (v *Value) IsMSISlice() bool { + _, ok := v.data.([]map[string]interface{}) + return ok +} + +// EachMSI calls the specified callback for each object +// in the []map[string]interface{}. +// +// Panics if the object is the wrong type. +func (v *Value) EachMSI(callback func(int, map[string]interface{}) bool) *Value { + for index, val := range v.MustMSISlice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereMSI uses the specified decider function to select items +// from the []map[string]interface{}. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereMSI(decider func(int, map[string]interface{}) bool) *Value { + var selected []map[string]interface{} + v.EachMSI(func(index int, val map[string]interface{}) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupMSI uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]map[string]interface{}. +func (v *Value) GroupMSI(grouper func(int, map[string]interface{}) string) *Value { + groups := make(map[string][]map[string]interface{}) + v.EachMSI(func(index int, val map[string]interface{}) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]map[string]interface{}, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceMSI uses the specified function to replace each map[string]interface{}s +// by iterating each item. The data in the returned result will be a +// []map[string]interface{} containing the replaced items. +func (v *Value) ReplaceMSI(replacer func(int, map[string]interface{}) map[string]interface{}) *Value { + arr := v.MustMSISlice() + replaced := make([]map[string]interface{}, len(arr)) + v.EachMSI(func(index int, val map[string]interface{}) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectMSI uses the specified collector function to collect a value +// for each of the map[string]interface{}s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectMSI(collector func(int, map[string]interface{}) interface{}) *Value { + arr := v.MustMSISlice() + collected := make([]interface{}, len(arr)) + v.EachMSI(func(index int, val map[string]interface{}) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + ObjxMap ((Map) and [](Map)) +*/ + +// ObjxMap gets the value as a (Map), returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) ObjxMap(optionalDefault ...(Map)) Map { + if s, ok := v.data.((Map)); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return New(nil) +} + +// MustObjxMap gets the value as a (Map). +// +// Panics if the object is not a (Map). +func (v *Value) MustObjxMap() Map { + return v.data.((Map)) +} + +// ObjxMapSlice gets the value as a [](Map), returns the optionalDefault +// value or nil if the value is not a [](Map). +func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) { + if s, ok := v.data.([](Map)); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustObjxMapSlice gets the value as a [](Map). +// +// Panics if the object is not a [](Map). +func (v *Value) MustObjxMapSlice() [](Map) { + return v.data.([](Map)) +} + +// IsObjxMap gets whether the object contained is a (Map) or not. +func (v *Value) IsObjxMap() bool { + _, ok := v.data.((Map)) + return ok +} + +// IsObjxMapSlice gets whether the object contained is a [](Map) or not. +func (v *Value) IsObjxMapSlice() bool { + _, ok := v.data.([](Map)) + return ok +} + +// EachObjxMap calls the specified callback for each object +// in the [](Map). +// +// Panics if the object is the wrong type. +func (v *Value) EachObjxMap(callback func(int, Map) bool) *Value { + for index, val := range v.MustObjxMapSlice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereObjxMap uses the specified decider function to select items +// from the [](Map). The object contained in the result will contain +// only the selected items. +func (v *Value) WhereObjxMap(decider func(int, Map) bool) *Value { + var selected [](Map) + v.EachObjxMap(func(index int, val Map) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupObjxMap uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][](Map). +func (v *Value) GroupObjxMap(grouper func(int, Map) string) *Value { + groups := make(map[string][](Map)) + v.EachObjxMap(func(index int, val Map) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([](Map), 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceObjxMap uses the specified function to replace each (Map)s +// by iterating each item. The data in the returned result will be a +// [](Map) containing the replaced items. +func (v *Value) ReplaceObjxMap(replacer func(int, Map) Map) *Value { + arr := v.MustObjxMapSlice() + replaced := make([](Map), len(arr)) + v.EachObjxMap(func(index int, val Map) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectObjxMap uses the specified collector function to collect a value +// for each of the (Map)s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectObjxMap(collector func(int, Map) interface{}) *Value { + arr := v.MustObjxMapSlice() + collected := make([]interface{}, len(arr)) + v.EachObjxMap(func(index int, val Map) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Bool (bool and []bool) */ // Bool gets the value as a bool, returns the optionalDefault @@ -251,7 +501,7 @@ func (v *Value) CollectBool(collector func(int, bool) interface{}) *Value { } /* - Str (string and []string) + Str (string and []string) */ // Str gets the value as a string, returns the optionalDefault @@ -376,7 +626,7 @@ func (v *Value) CollectStr(collector func(int, string) interface{}) *Value { } /* - Int (int and []int) + Int (int and []int) */ // Int gets the value as a int, returns the optionalDefault @@ -501,7 +751,7 @@ func (v *Value) CollectInt(collector func(int, int) interface{}) *Value { } /* - Int8 (int8 and []int8) + Int8 (int8 and []int8) */ // Int8 gets the value as a int8, returns the optionalDefault @@ -626,7 +876,7 @@ func (v *Value) CollectInt8(collector func(int, int8) interface{}) *Value { } /* - Int16 (int16 and []int16) + Int16 (int16 and []int16) */ // Int16 gets the value as a int16, returns the optionalDefault @@ -751,7 +1001,7 @@ func (v *Value) CollectInt16(collector func(int, int16) interface{}) *Value { } /* - Int32 (int32 and []int32) + Int32 (int32 and []int32) */ // Int32 gets the value as a int32, returns the optionalDefault @@ -876,7 +1126,7 @@ func (v *Value) CollectInt32(collector func(int, int32) interface{}) *Value { } /* - Int64 (int64 and []int64) + Int64 (int64 and []int64) */ // Int64 gets the value as a int64, returns the optionalDefault @@ -1001,7 +1251,7 @@ func (v *Value) CollectInt64(collector func(int, int64) interface{}) *Value { } /* - Uint (uint and []uint) + Uint (uint and []uint) */ // Uint gets the value as a uint, returns the optionalDefault @@ -1126,7 +1376,7 @@ func (v *Value) CollectUint(collector func(int, uint) interface{}) *Value { } /* - Uint8 (uint8 and []uint8) + Uint8 (uint8 and []uint8) */ // Uint8 gets the value as a uint8, returns the optionalDefault @@ -1251,7 +1501,7 @@ func (v *Value) CollectUint8(collector func(int, uint8) interface{}) *Value { } /* - Uint16 (uint16 and []uint16) + Uint16 (uint16 and []uint16) */ // Uint16 gets the value as a uint16, returns the optionalDefault @@ -1376,7 +1626,7 @@ func (v *Value) CollectUint16(collector func(int, uint16) interface{}) *Value { } /* - Uint32 (uint32 and []uint32) + Uint32 (uint32 and []uint32) */ // Uint32 gets the value as a uint32, returns the optionalDefault @@ -1501,7 +1751,7 @@ func (v *Value) CollectUint32(collector func(int, uint32) interface{}) *Value { } /* - Uint64 (uint64 and []uint64) + Uint64 (uint64 and []uint64) */ // Uint64 gets the value as a uint64, returns the optionalDefault @@ -1626,7 +1876,7 @@ func (v *Value) CollectUint64(collector func(int, uint64) interface{}) *Value { } /* - Uintptr (uintptr and []uintptr) + Uintptr (uintptr and []uintptr) */ // Uintptr gets the value as a uintptr, returns the optionalDefault @@ -1751,7 +2001,7 @@ func (v *Value) CollectUintptr(collector func(int, uintptr) interface{}) *Value } /* - Float32 (float32 and []float32) + Float32 (float32 and []float32) */ // Float32 gets the value as a float32, returns the optionalDefault @@ -1876,7 +2126,7 @@ func (v *Value) CollectFloat32(collector func(int, float32) interface{}) *Value } /* - Float64 (float64 and []float64) + Float64 (float64 and []float64) */ // Float64 gets the value as a float64, returns the optionalDefault @@ -2001,7 +2251,7 @@ func (v *Value) CollectFloat64(collector func(int, float64) interface{}) *Value } /* - Complex64 (complex64 and []complex64) + Complex64 (complex64 and []complex64) */ // Complex64 gets the value as a complex64, returns the optionalDefault @@ -2126,7 +2376,7 @@ func (v *Value) CollectComplex64(collector func(int, complex64) interface{}) *Va } /* - Complex128 (complex128 and []complex128) + Complex128 (complex128 and []complex128) */ // Complex128 gets the value as a complex128, returns the optionalDefault diff --git a/vendor/github.com/stretchr/objx/value.go b/vendor/github.com/stretchr/objx/value.go index 4e5f9b77e69..e4b4a14335d 100644 --- a/vendor/github.com/stretchr/objx/value.go +++ b/vendor/github.com/stretchr/objx/value.go @@ -20,8 +20,6 @@ func (v *Value) Data() interface{} { // String returns the value always as a string func (v *Value) String() string { switch { - case v.IsNil(): - return "" case v.IsStr(): return v.Str() case v.IsBool(): @@ -53,107 +51,3 @@ func (v *Value) String() string { } return fmt.Sprintf("%#v", v.Data()) } - -// StringSlice returns the value always as a []string -func (v *Value) StringSlice(optionalDefault ...[]string) []string { - switch { - case v.IsStrSlice(): - return v.MustStrSlice() - case v.IsBoolSlice(): - slice := v.MustBoolSlice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatBool(iv) - } - return vals - case v.IsFloat32Slice(): - slice := v.MustFloat32Slice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatFloat(float64(iv), 'f', -1, 32) - } - return vals - case v.IsFloat64Slice(): - slice := v.MustFloat64Slice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatFloat(iv, 'f', -1, 64) - } - return vals - case v.IsIntSlice(): - slice := v.MustIntSlice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatInt(int64(iv), 10) - } - return vals - case v.IsInt8Slice(): - slice := v.MustInt8Slice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatInt(int64(iv), 10) - } - return vals - case v.IsInt16Slice(): - slice := v.MustInt16Slice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatInt(int64(iv), 10) - } - return vals - case v.IsInt32Slice(): - slice := v.MustInt32Slice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatInt(int64(iv), 10) - } - return vals - case v.IsInt64Slice(): - slice := v.MustInt64Slice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatInt(iv, 10) - } - return vals - case v.IsUintSlice(): - slice := v.MustUintSlice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatUint(uint64(iv), 10) - } - return vals - case v.IsUint8Slice(): - slice := v.MustUint8Slice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatUint(uint64(iv), 10) - } - return vals - case v.IsUint16Slice(): - slice := v.MustUint16Slice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatUint(uint64(iv), 10) - } - return vals - case v.IsUint32Slice(): - slice := v.MustUint32Slice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatUint(uint64(iv), 10) - } - return vals - case v.IsUint64Slice(): - slice := v.MustUint64Slice() - vals := make([]string, len(slice)) - for i, iv := range slice { - vals[i] = strconv.FormatUint(iv, 10) - } - return vals - } - if len(optionalDefault) == 1 { - return optionalDefault[0] - } - - return []string{} -} diff --git a/vendor/github.com/stretchr/testify/LICENSE b/vendor/github.com/stretchr/testify/LICENSE index f38ec5956b6..4b0421cf9ee 100644 --- a/vendor/github.com/stretchr/testify/LICENSE +++ b/vendor/github.com/stretchr/testify/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2012-2018 Mat Ryer and Tyler Bunnell +Copyright (c) 2012-2020 Mat Ryer, Tyler Bunnell and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/github.com/stretchr/testify/assert/assertion_compare.go b/vendor/github.com/stretchr/testify/assert/assertion_compare.go new file mode 100644 index 00000000000..dc200395ceb --- /dev/null +++ b/vendor/github.com/stretchr/testify/assert/assertion_compare.go @@ -0,0 +1,274 @@ +package assert + +import ( + "fmt" + "reflect" +) + +type CompareType int + +const ( + compareLess CompareType = iota - 1 + compareEqual + compareGreater +) + +func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) { + switch kind { + case reflect.Int: + { + intobj1 := obj1.(int) + intobj2 := obj2.(int) + if intobj1 > intobj2 { + return compareGreater, true + } + if intobj1 == intobj2 { + return compareEqual, true + } + if intobj1 < intobj2 { + return compareLess, true + } + } + case reflect.Int8: + { + int8obj1 := obj1.(int8) + int8obj2 := obj2.(int8) + if int8obj1 > int8obj2 { + return compareGreater, true + } + if int8obj1 == int8obj2 { + return compareEqual, true + } + if int8obj1 < int8obj2 { + return compareLess, true + } + } + case reflect.Int16: + { + int16obj1 := obj1.(int16) + int16obj2 := obj2.(int16) + if int16obj1 > int16obj2 { + return compareGreater, true + } + if int16obj1 == int16obj2 { + return compareEqual, true + } + if int16obj1 < int16obj2 { + return compareLess, true + } + } + case reflect.Int32: + { + int32obj1 := obj1.(int32) + int32obj2 := obj2.(int32) + if int32obj1 > int32obj2 { + return compareGreater, true + } + if int32obj1 == int32obj2 { + return compareEqual, true + } + if int32obj1 < int32obj2 { + return compareLess, true + } + } + case reflect.Int64: + { + int64obj1 := obj1.(int64) + int64obj2 := obj2.(int64) + if int64obj1 > int64obj2 { + return compareGreater, true + } + if int64obj1 == int64obj2 { + return compareEqual, true + } + if int64obj1 < int64obj2 { + return compareLess, true + } + } + case reflect.Uint: + { + uintobj1 := obj1.(uint) + uintobj2 := obj2.(uint) + if uintobj1 > uintobj2 { + return compareGreater, true + } + if uintobj1 == uintobj2 { + return compareEqual, true + } + if uintobj1 < uintobj2 { + return compareLess, true + } + } + case reflect.Uint8: + { + uint8obj1 := obj1.(uint8) + uint8obj2 := obj2.(uint8) + if uint8obj1 > uint8obj2 { + return compareGreater, true + } + if uint8obj1 == uint8obj2 { + return compareEqual, true + } + if uint8obj1 < uint8obj2 { + return compareLess, true + } + } + case reflect.Uint16: + { + uint16obj1 := obj1.(uint16) + uint16obj2 := obj2.(uint16) + if uint16obj1 > uint16obj2 { + return compareGreater, true + } + if uint16obj1 == uint16obj2 { + return compareEqual, true + } + if uint16obj1 < uint16obj2 { + return compareLess, true + } + } + case reflect.Uint32: + { + uint32obj1 := obj1.(uint32) + uint32obj2 := obj2.(uint32) + if uint32obj1 > uint32obj2 { + return compareGreater, true + } + if uint32obj1 == uint32obj2 { + return compareEqual, true + } + if uint32obj1 < uint32obj2 { + return compareLess, true + } + } + case reflect.Uint64: + { + uint64obj1 := obj1.(uint64) + uint64obj2 := obj2.(uint64) + if uint64obj1 > uint64obj2 { + return compareGreater, true + } + if uint64obj1 == uint64obj2 { + return compareEqual, true + } + if uint64obj1 < uint64obj2 { + return compareLess, true + } + } + case reflect.Float32: + { + float32obj1 := obj1.(float32) + float32obj2 := obj2.(float32) + if float32obj1 > float32obj2 { + return compareGreater, true + } + if float32obj1 == float32obj2 { + return compareEqual, true + } + if float32obj1 < float32obj2 { + return compareLess, true + } + } + case reflect.Float64: + { + float64obj1 := obj1.(float64) + float64obj2 := obj2.(float64) + if float64obj1 > float64obj2 { + return compareGreater, true + } + if float64obj1 == float64obj2 { + return compareEqual, true + } + if float64obj1 < float64obj2 { + return compareLess, true + } + } + case reflect.String: + { + stringobj1 := obj1.(string) + stringobj2 := obj2.(string) + if stringobj1 > stringobj2 { + return compareGreater, true + } + if stringobj1 == stringobj2 { + return compareEqual, true + } + if stringobj1 < stringobj2 { + return compareLess, true + } + } + } + + return compareEqual, false +} + +// Greater asserts that the first element is greater than the second +// +// assert.Greater(t, 2, 1) +// assert.Greater(t, float64(2), float64(1)) +// assert.Greater(t, "b", "a") +func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { + return compareTwoValues(t, e1, e2, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs) +} + +// GreaterOrEqual asserts that the first element is greater than or equal to the second +// +// assert.GreaterOrEqual(t, 2, 1) +// assert.GreaterOrEqual(t, 2, 2) +// assert.GreaterOrEqual(t, "b", "a") +// assert.GreaterOrEqual(t, "b", "b") +func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { + return compareTwoValues(t, e1, e2, []CompareType{compareGreater, compareEqual}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs) +} + +// Less asserts that the first element is less than the second +// +// assert.Less(t, 1, 2) +// assert.Less(t, float64(1), float64(2)) +// assert.Less(t, "a", "b") +func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { + return compareTwoValues(t, e1, e2, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs) +} + +// LessOrEqual asserts that the first element is less than or equal to the second +// +// assert.LessOrEqual(t, 1, 2) +// assert.LessOrEqual(t, 2, 2) +// assert.LessOrEqual(t, "a", "b") +// assert.LessOrEqual(t, "b", "b") +func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { + return compareTwoValues(t, e1, e2, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs) +} + +func compareTwoValues(t TestingT, e1 interface{}, e2 interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + e1Kind := reflect.ValueOf(e1).Kind() + e2Kind := reflect.ValueOf(e2).Kind() + if e1Kind != e2Kind { + return Fail(t, "Elements should be the same type", msgAndArgs...) + } + + compareResult, isComparable := compare(e1, e2, e1Kind) + if !isComparable { + return Fail(t, fmt.Sprintf("Can not compare type \"%s\"", reflect.TypeOf(e1)), msgAndArgs...) + } + + if !containsValue(allowedComparesResults, compareResult) { + return Fail(t, fmt.Sprintf(failMessage, e1, e2), msgAndArgs...) + } + + return true +} + +func containsValue(values []CompareType, value CompareType) bool { + for _, v := range values { + if v == value { + return true + } + } + + return false +} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go b/vendor/github.com/stretchr/testify/assert/assertion_format.go index bf89ecd21f7..49370eb1674 100644 --- a/vendor/github.com/stretchr/testify/assert/assertion_format.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_format.go @@ -93,7 +93,7 @@ func EqualErrorf(t TestingT, theError error, errString string, msg string, args // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // -// assert.EqualValuesf(t, uint32(123, "error message %s", "formatted"), int32(123)) +// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -127,7 +127,7 @@ func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick // Exactlyf asserts that two objects are equal in value and type. // -// assert.Exactlyf(t, int32(123, "error message %s", "formatted"), int64(123)) +// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -173,7 +173,7 @@ func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool // Greaterf asserts that the first element is greater than the second // // assert.Greaterf(t, 2, 1, "error message %s", "formatted") -// assert.Greaterf(t, float64(2, "error message %s", "formatted"), float64(1)) +// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") // assert.Greaterf(t, "b", "a", "error message %s", "formatted") func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { @@ -225,7 +225,7 @@ func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, u // // assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +// Returns whether the assertion was successful (true) or not (false). func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -237,7 +237,7 @@ func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, // // assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +// Returns whether the assertion was successful (true) or not (false). func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -245,6 +245,18 @@ func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url stri return HTTPRedirect(t, handler, method, url, values, append([]interface{}{msg}, args...)...) } +// HTTPStatusCodef asserts that a specified handler returns a specified status code. +// +// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return HTTPStatusCode(t, handler, method, url, values, statuscode, append([]interface{}{msg}, args...)...) +} + // HTTPSuccessf asserts that a specified handler returns a success status code. // // assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") @@ -259,7 +271,7 @@ func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url strin // Implementsf asserts that an object is implemented by the specified interface. // -// assert.Implementsf(t, (*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) +// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -341,7 +353,7 @@ func Lenf(t TestingT, object interface{}, length int, msg string, args ...interf // Lessf asserts that the first element is less than the second // // assert.Lessf(t, 1, 2, "error message %s", "formatted") -// assert.Lessf(t, float64(1, "error message %s", "formatted"), float64(2)) +// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted") // assert.Lessf(t, "a", "b", "error message %s", "formatted") func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { @@ -454,6 +466,16 @@ func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, return NotEqual(t, expected, actual, append([]interface{}{msg}, args...)...) } +// NotEqualValuesf asserts that two objects are not equal even when converted to the same type +// +// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") +func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return NotEqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) +} + // NotNilf asserts that the specified object is not nil. // // assert.NotNilf(t, err, "error message %s", "formatted") @@ -476,7 +498,7 @@ func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bo // NotRegexpf asserts that a specified regexp does not match a string. // -// assert.NotRegexpf(t, regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") +// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") // assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { @@ -552,7 +574,7 @@ func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg str // Regexpf asserts that a specified regexp matches a string. // -// assert.Regexpf(t, regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") +// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") // assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go index 75ecdcaa2f3..9db889427a7 100644 --- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go @@ -169,7 +169,7 @@ func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAn // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // -// a.EqualValuesf(uint32(123, "error message %s", "formatted"), int32(123)) +// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -251,7 +251,7 @@ func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArg // Exactlyf asserts that two objects are equal in value and type. // -// a.Exactlyf(int32(123, "error message %s", "formatted"), int64(123)) +// a.Exactlyf(int32(123), int64(123), "error message %s", "formatted") func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -370,7 +370,7 @@ func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, // Greaterf asserts that the first element is greater than the second // // a.Greaterf(2, 1, "error message %s", "formatted") -// a.Greaterf(float64(2, "error message %s", "formatted"), float64(1)) +// a.Greaterf(float64(2), float64(1), "error message %s", "formatted") // a.Greaterf("b", "a", "error message %s", "formatted") func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { @@ -447,7 +447,7 @@ func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url stri // // a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +// Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -471,7 +471,7 @@ func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url s // // a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // -// Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). +// Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -479,6 +479,30 @@ func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url return HTTPRedirectf(a.t, handler, method, url, values, msg, args...) } +// HTTPStatusCode asserts that a specified handler returns a specified status code. +// +// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501) +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPStatusCode(a.t, handler, method, url, values, statuscode, msgAndArgs...) +} + +// HTTPStatusCodef asserts that a specified handler returns a specified status code. +// +// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") +// +// Returns whether the assertion was successful (true) or not (false). +func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return HTTPStatusCodef(a.t, handler, method, url, values, statuscode, msg, args...) +} + // HTTPSuccess asserts that a specified handler returns a success status code. // // a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) @@ -515,7 +539,7 @@ func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, // Implementsf asserts that an object is implemented by the specified interface. // -// a.Implementsf((*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) +// a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -706,7 +730,7 @@ func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, ar // Lessf asserts that the first element is less than the second // // a.Lessf(1, 2, "error message %s", "formatted") -// a.Lessf(float64(1, "error message %s", "formatted"), float64(2)) +// a.Lessf(float64(1), float64(2), "error message %s", "formatted") // a.Lessf("a", "b", "error message %s", "formatted") func (a *Assertions) Lessf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { @@ -884,6 +908,26 @@ func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndAr return NotEqual(a.t, expected, actual, msgAndArgs...) } +// NotEqualValues asserts that two objects are not equal even when converted to the same type +// +// a.NotEqualValues(obj1, obj2) +func (a *Assertions) NotEqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotEqualValues(a.t, expected, actual, msgAndArgs...) +} + +// NotEqualValuesf asserts that two objects are not equal even when converted to the same type +// +// a.NotEqualValuesf(obj1, obj2, "error message %s", "formatted") +func (a *Assertions) NotEqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return NotEqualValuesf(a.t, expected, actual, msg, args...) +} + // NotEqualf asserts that the specified values are NOT equal. // // a.NotEqualf(obj1, obj2, "error message %s", "formatted") @@ -950,7 +994,7 @@ func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...in // NotRegexpf asserts that a specified regexp does not match a string. // -// a.NotRegexpf(regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") +// a.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") // a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { @@ -1102,7 +1146,7 @@ func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...inter // Regexpf asserts that a specified regexp matches a string. // -// a.Regexpf(regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") +// a.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") // a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { diff --git a/vendor/github.com/stretchr/testify/assert/assertion_order.go b/vendor/github.com/stretchr/testify/assert/assertion_order.go deleted file mode 100644 index 15a486ca6e2..00000000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_order.go +++ /dev/null @@ -1,309 +0,0 @@ -package assert - -import ( - "fmt" - "reflect" -) - -func compare(obj1, obj2 interface{}, kind reflect.Kind) (int, bool) { - switch kind { - case reflect.Int: - { - intobj1 := obj1.(int) - intobj2 := obj2.(int) - if intobj1 > intobj2 { - return -1, true - } - if intobj1 == intobj2 { - return 0, true - } - if intobj1 < intobj2 { - return 1, true - } - } - case reflect.Int8: - { - int8obj1 := obj1.(int8) - int8obj2 := obj2.(int8) - if int8obj1 > int8obj2 { - return -1, true - } - if int8obj1 == int8obj2 { - return 0, true - } - if int8obj1 < int8obj2 { - return 1, true - } - } - case reflect.Int16: - { - int16obj1 := obj1.(int16) - int16obj2 := obj2.(int16) - if int16obj1 > int16obj2 { - return -1, true - } - if int16obj1 == int16obj2 { - return 0, true - } - if int16obj1 < int16obj2 { - return 1, true - } - } - case reflect.Int32: - { - int32obj1 := obj1.(int32) - int32obj2 := obj2.(int32) - if int32obj1 > int32obj2 { - return -1, true - } - if int32obj1 == int32obj2 { - return 0, true - } - if int32obj1 < int32obj2 { - return 1, true - } - } - case reflect.Int64: - { - int64obj1 := obj1.(int64) - int64obj2 := obj2.(int64) - if int64obj1 > int64obj2 { - return -1, true - } - if int64obj1 == int64obj2 { - return 0, true - } - if int64obj1 < int64obj2 { - return 1, true - } - } - case reflect.Uint: - { - uintobj1 := obj1.(uint) - uintobj2 := obj2.(uint) - if uintobj1 > uintobj2 { - return -1, true - } - if uintobj1 == uintobj2 { - return 0, true - } - if uintobj1 < uintobj2 { - return 1, true - } - } - case reflect.Uint8: - { - uint8obj1 := obj1.(uint8) - uint8obj2 := obj2.(uint8) - if uint8obj1 > uint8obj2 { - return -1, true - } - if uint8obj1 == uint8obj2 { - return 0, true - } - if uint8obj1 < uint8obj2 { - return 1, true - } - } - case reflect.Uint16: - { - uint16obj1 := obj1.(uint16) - uint16obj2 := obj2.(uint16) - if uint16obj1 > uint16obj2 { - return -1, true - } - if uint16obj1 == uint16obj2 { - return 0, true - } - if uint16obj1 < uint16obj2 { - return 1, true - } - } - case reflect.Uint32: - { - uint32obj1 := obj1.(uint32) - uint32obj2 := obj2.(uint32) - if uint32obj1 > uint32obj2 { - return -1, true - } - if uint32obj1 == uint32obj2 { - return 0, true - } - if uint32obj1 < uint32obj2 { - return 1, true - } - } - case reflect.Uint64: - { - uint64obj1 := obj1.(uint64) - uint64obj2 := obj2.(uint64) - if uint64obj1 > uint64obj2 { - return -1, true - } - if uint64obj1 == uint64obj2 { - return 0, true - } - if uint64obj1 < uint64obj2 { - return 1, true - } - } - case reflect.Float32: - { - float32obj1 := obj1.(float32) - float32obj2 := obj2.(float32) - if float32obj1 > float32obj2 { - return -1, true - } - if float32obj1 == float32obj2 { - return 0, true - } - if float32obj1 < float32obj2 { - return 1, true - } - } - case reflect.Float64: - { - float64obj1 := obj1.(float64) - float64obj2 := obj2.(float64) - if float64obj1 > float64obj2 { - return -1, true - } - if float64obj1 == float64obj2 { - return 0, true - } - if float64obj1 < float64obj2 { - return 1, true - } - } - case reflect.String: - { - stringobj1 := obj1.(string) - stringobj2 := obj2.(string) - if stringobj1 > stringobj2 { - return -1, true - } - if stringobj1 == stringobj2 { - return 0, true - } - if stringobj1 < stringobj2 { - return 1, true - } - } - } - - return 0, false -} - -// Greater asserts that the first element is greater than the second -// -// assert.Greater(t, 2, 1) -// assert.Greater(t, float64(2), float64(1)) -// assert.Greater(t, "b", "a") -func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - e1Kind := reflect.ValueOf(e1).Kind() - e2Kind := reflect.ValueOf(e2).Kind() - if e1Kind != e2Kind { - return Fail(t, "Elements should be the same type", msgAndArgs...) - } - - res, isComparable := compare(e1, e2, e1Kind) - if !isComparable { - return Fail(t, fmt.Sprintf("Can not compare type \"%s\"", reflect.TypeOf(e1)), msgAndArgs...) - } - - if res != -1 { - return Fail(t, fmt.Sprintf("\"%v\" is not greater than \"%v\"", e1, e2), msgAndArgs...) - } - - return true -} - -// GreaterOrEqual asserts that the first element is greater than or equal to the second -// -// assert.GreaterOrEqual(t, 2, 1) -// assert.GreaterOrEqual(t, 2, 2) -// assert.GreaterOrEqual(t, "b", "a") -// assert.GreaterOrEqual(t, "b", "b") -func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - e1Kind := reflect.ValueOf(e1).Kind() - e2Kind := reflect.ValueOf(e2).Kind() - if e1Kind != e2Kind { - return Fail(t, "Elements should be the same type", msgAndArgs...) - } - - res, isComparable := compare(e1, e2, e1Kind) - if !isComparable { - return Fail(t, fmt.Sprintf("Can not compare type \"%s\"", reflect.TypeOf(e1)), msgAndArgs...) - } - - if res != -1 && res != 0 { - return Fail(t, fmt.Sprintf("\"%v\" is not greater than or equal to \"%v\"", e1, e2), msgAndArgs...) - } - - return true -} - -// Less asserts that the first element is less than the second -// -// assert.Less(t, 1, 2) -// assert.Less(t, float64(1), float64(2)) -// assert.Less(t, "a", "b") -func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - e1Kind := reflect.ValueOf(e1).Kind() - e2Kind := reflect.ValueOf(e2).Kind() - if e1Kind != e2Kind { - return Fail(t, "Elements should be the same type", msgAndArgs...) - } - - res, isComparable := compare(e1, e2, e1Kind) - if !isComparable { - return Fail(t, fmt.Sprintf("Can not compare type \"%s\"", reflect.TypeOf(e1)), msgAndArgs...) - } - - if res != 1 { - return Fail(t, fmt.Sprintf("\"%v\" is not less than \"%v\"", e1, e2), msgAndArgs...) - } - - return true -} - -// LessOrEqual asserts that the first element is less than or equal to the second -// -// assert.LessOrEqual(t, 1, 2) -// assert.LessOrEqual(t, 2, 2) -// assert.LessOrEqual(t, "a", "b") -// assert.LessOrEqual(t, "b", "b") -func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - e1Kind := reflect.ValueOf(e1).Kind() - e2Kind := reflect.ValueOf(e2).Kind() - if e1Kind != e2Kind { - return Fail(t, "Elements should be the same type", msgAndArgs...) - } - - res, isComparable := compare(e1, e2, e1Kind) - if !isComparable { - return Fail(t, fmt.Sprintf("Can not compare type \"%s\"", reflect.TypeOf(e1)), msgAndArgs...) - } - - if res != 1 && res != 0 { - return Fail(t, fmt.Sprintf("\"%v\" is not less than or equal to \"%v\"", e1, e2), msgAndArgs...) - } - - return true -} diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go index bdd81389a97..914a10d83af 100644 --- a/vendor/github.com/stretchr/testify/assert/assertions.go +++ b/vendor/github.com/stretchr/testify/assert/assertions.go @@ -19,7 +19,7 @@ import ( "github.com/davecgh/go-spew/spew" "github.com/pmezard/go-difflib/difflib" - yaml "gopkg.in/yaml.v2" + yaml "gopkg.in/yaml.v3" ) //go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl" @@ -45,7 +45,7 @@ type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool // for table driven tests. type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool -// Comparison a custom function that returns true on success and false on failure +// Comparison is a custom function that returns true on success and false on failure type Comparison func() (success bool) /* @@ -104,11 +104,11 @@ the problem actually occurred in calling code.*/ // failed. func CallerInfo() []string { - pc := uintptr(0) - file := "" - line := 0 - ok := false - name := "" + var pc uintptr + var ok bool + var file string + var line int + var name string callers := []string{} for i := 0; ; i++ { @@ -429,14 +429,27 @@ func samePointers(first, second interface{}) bool { // to a type conversion in the Go grammar. func formatUnequalValues(expected, actual interface{}) (e string, a string) { if reflect.TypeOf(expected) != reflect.TypeOf(actual) { - return fmt.Sprintf("%T(%#v)", expected, expected), - fmt.Sprintf("%T(%#v)", actual, actual) + return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)), + fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual)) } switch expected.(type) { case time.Duration: return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual) } - return fmt.Sprintf("%#v", expected), fmt.Sprintf("%#v", actual) + return truncatingFormat(expected), truncatingFormat(actual) +} + +// truncatingFormat formats the data and truncates it if it's too long. +// +// This helps keep formatted error messages lines from exceeding the +// bufio.MaxScanTokenSize max line length that the go testing framework imposes. +func truncatingFormat(data interface{}) string { + value := fmt.Sprintf("%#v", data) + max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed. + if len(value) > max { + value = value[0:max] + "<... truncated>" + } + return value } // EqualValues asserts that two objects are equal or convertable to the same types @@ -483,12 +496,12 @@ func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{} // // assert.NotNil(t, err) func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } if !isNil(object) { return true } + if h, ok := t.(tHelper); ok { + h.Helper() + } return Fail(t, "Expected value not to be nil.", msgAndArgs...) } @@ -529,12 +542,12 @@ func isNil(object interface{}) bool { // // assert.Nil(t, err) func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } if isNil(object) { return true } + if h, ok := t.(tHelper); ok { + h.Helper() + } return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) } @@ -571,12 +584,11 @@ func isEmpty(object interface{}) bool { // // assert.Empty(t, obj) func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - pass := isEmpty(object) if !pass { + if h, ok := t.(tHelper); ok { + h.Helper() + } Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) } @@ -591,12 +603,11 @@ func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { // assert.Equal(t, "two", obj[1]) // } func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - pass := !isEmpty(object) if !pass { + if h, ok := t.(tHelper); ok { + h.Helper() + } Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) } @@ -639,16 +650,10 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) // // assert.True(t, myBool) func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if h, ok := t.(interface { - Helper() - }); ok { - h.Helper() - } - - if value != true { + if !value { + if h, ok := t.(tHelper); ok { + h.Helper() + } return Fail(t, "Should be true", msgAndArgs...) } @@ -660,11 +665,10 @@ func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { // // assert.False(t, myBool) func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if value != false { + if value { + if h, ok := t.(tHelper); ok { + h.Helper() + } return Fail(t, "Should be false", msgAndArgs...) } @@ -695,6 +699,21 @@ func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{ } +// NotEqualValues asserts that two objects are not equal even when converted to the same type +// +// assert.NotEqualValues(t, obj1, obj2) +func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + if ObjectsAreEqualValues(expected, actual) { + return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) + } + + return true +} + // containsElement try loop over the list check if the list includes the element. // return (false, false) if impossible. // return (true, false) if element was not found. @@ -747,10 +766,10 @@ func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bo ok, found := includeElement(s, contains) if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) + return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...) } if !found { - return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) + return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...) } return true @@ -881,27 +900,39 @@ func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface return true } - aKind := reflect.TypeOf(listA).Kind() - bKind := reflect.TypeOf(listB).Kind() + if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) { + return false + } - if aKind != reflect.Array && aKind != reflect.Slice { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listA, aKind), msgAndArgs...) + extraA, extraB := diffLists(listA, listB) + + if len(extraA) == 0 && len(extraB) == 0 { + return true } - if bKind != reflect.Array && bKind != reflect.Slice { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listB, bKind), msgAndArgs...) + return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...) +} + +// isList checks that the provided value is array or slice. +func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) { + kind := reflect.TypeOf(list).Kind() + if kind != reflect.Array && kind != reflect.Slice { + return Fail(t, fmt.Sprintf("%q has an unsupported type %s, expecting array or slice", list, kind), + msgAndArgs...) } + return true +} +// diffLists diffs two arrays/slices and returns slices of elements that are only in A and only in B. +// If some element is present multiple times, each instance is counted separately (e.g. if something is 2x in A and +// 5x in B, it will be 0x in extraA and 3x in extraB). The order of items in both lists is ignored. +func diffLists(listA, listB interface{}) (extraA, extraB []interface{}) { aValue := reflect.ValueOf(listA) bValue := reflect.ValueOf(listB) aLen := aValue.Len() bLen := bValue.Len() - if aLen != bLen { - return Fail(t, fmt.Sprintf("lengths don't match: %d != %d", aLen, bLen), msgAndArgs...) - } - // Mark indexes in bValue that we already used visited := make([]bool, bLen) for i := 0; i < aLen; i++ { @@ -918,11 +949,38 @@ func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface } } if !found { - return Fail(t, fmt.Sprintf("element %s appears more times in %s than in %s", element, aValue, bValue), msgAndArgs...) + extraA = append(extraA, element) } } - return true + for j := 0; j < bLen; j++ { + if visited[j] { + continue + } + extraB = append(extraB, bValue.Index(j).Interface()) + } + + return +} + +func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) string { + var msg bytes.Buffer + + msg.WriteString("elements differ") + if len(extraA) > 0 { + msg.WriteString("\n\nextra elements in list A:\n") + msg.WriteString(spewConfig.Sdump(extraA)) + } + if len(extraB) > 0 { + msg.WriteString("\n\nextra elements in list B:\n") + msg.WriteString(spewConfig.Sdump(extraB)) + } + msg.WriteString("\n\nlistA:\n") + msg.WriteString(spewConfig.Sdump(listA)) + msg.WriteString("\n\nlistB:\n") + msg.WriteString(spewConfig.Sdump(listB)) + + return msg.String() } // Condition uses a Comparison to assert a complex condition. @@ -1058,6 +1116,8 @@ func toFloat(x interface{}) (float64, bool) { xok := true switch xn := x.(type) { + case uint: + xf = float64(xn) case uint8: xf = float64(xn) case uint16: @@ -1079,7 +1139,7 @@ func toFloat(x interface{}) (float64, bool) { case float32: xf = float64(xn) case float64: - xf = float64(xn) + xf = xn case time.Duration: xf = float64(xn) default: @@ -1193,6 +1253,9 @@ func calcRelativeError(expected, actual interface{}) (float64, error) { if !aok { return 0, fmt.Errorf("expected value %q cannot be converted to float", expected) } + if math.IsNaN(af) { + return 0, errors.New("expected value must not be NaN") + } if af == 0 { return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error") } @@ -1200,6 +1263,9 @@ func calcRelativeError(expected, actual interface{}) (float64, error) { if !bok { return 0, fmt.Errorf("actual value %q cannot be converted to float", actual) } + if math.IsNaN(bf) { + return 0, errors.New("actual value must not be NaN") + } return math.Abs(af-bf) / math.Abs(af), nil } @@ -1209,6 +1275,9 @@ func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAnd if h, ok := t.(tHelper); ok { h.Helper() } + if math.IsNaN(epsilon) { + return Fail(t, "epsilon must not be NaN") + } actualEpsilon, err := calcRelativeError(expected, actual) if err != nil { return Fail(t, err.Error(), msgAndArgs...) @@ -1256,10 +1325,10 @@ func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, m // assert.Equal(t, expectedObj, actualObj) // } func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } if err != nil { + if h, ok := t.(tHelper); ok { + h.Helper() + } return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...) } @@ -1273,11 +1342,10 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { // assert.Equal(t, expectedError, err) // } func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if err == nil { + if h, ok := t.(tHelper); ok { + h.Helper() + } return Fail(t, "An error is expected but got nil.", msgAndArgs...) } @@ -1553,6 +1621,7 @@ var spewConfig = spew.ConfigState{ DisablePointerAddresses: true, DisableCapacities: true, SortKeys: true, + DisableMethods: true, } type tHelper interface { diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go index df46fa777ac..4ed341dd289 100644 --- a/vendor/github.com/stretchr/testify/assert/http_assertions.go +++ b/vendor/github.com/stretchr/testify/assert/http_assertions.go @@ -33,7 +33,6 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, value code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) - return false } isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent @@ -56,7 +55,6 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, valu code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) - return false } isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect @@ -79,7 +77,6 @@ func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) - return false } isErrorCode := code >= http.StatusBadRequest @@ -90,6 +87,28 @@ func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values return isErrorCode } +// HTTPStatusCode asserts that a specified handler returns a specified status code. +// +// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501) +// +// Returns whether the assertion was successful (true) or not (false). +func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + code, err := httpCode(handler, method, url, values) + if err != nil { + Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) + } + + successful := code == statuscode + if !successful { + Fail(t, fmt.Sprintf("Expected HTTP status code %d for %q but received %d", statuscode, url+"?"+values.Encode(), code)) + } + + return successful +} + // HTTPBody is a helper that returns HTTP body of the response. It returns // empty string if building a new request fails. func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { diff --git a/vendor/github.com/stretchr/testify/mock/mock.go b/vendor/github.com/stretchr/testify/mock/mock.go index 58e0798da43..c6df4485abc 100644 --- a/vendor/github.com/stretchr/testify/mock/mock.go +++ b/vendor/github.com/stretchr/testify/mock/mock.go @@ -65,6 +65,11 @@ type Call struct { // reference. It's useful when mocking methods such as unmarshalers or // decoders. RunFn func(Arguments) + + // PanicMsg holds msg to be used to mock panic on the function call + // if the PanicMsg is set to a non nil string the function call will panic + // irrespective of other settings + PanicMsg *string } func newCall(parent *Mock, methodName string, callerInfo []string, methodArguments ...interface{}) *Call { @@ -77,6 +82,7 @@ func newCall(parent *Mock, methodName string, callerInfo []string, methodArgumen Repeatability: 0, WaitFor: nil, RunFn: nil, + PanicMsg: nil, } } @@ -100,6 +106,18 @@ func (c *Call) Return(returnArguments ...interface{}) *Call { return c } +// Panic specifies if the functon call should fail and the panic message +// +// Mock.On("DoSomething").Panic("test panic") +func (c *Call) Panic(msg string) *Call { + c.lock() + defer c.unlock() + + c.PanicMsg = &msg + + return c +} + // Once indicates that that the mock should only return the value once. // // Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once() @@ -150,7 +168,7 @@ func (c *Call) After(d time.Duration) *Call { // mocking a method (such as an unmarshaler) that takes a pointer to a struct and // sets properties in such struct // -// Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}").Return().Run(func(args Arguments) { +// Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}")).Return().Run(func(args Arguments) { // arg := args.Get(0).(*map[string]interface{}) // arg["foo"] = "bar" // }) @@ -392,6 +410,13 @@ func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Argumen time.Sleep(call.waitTime) } + m.mutex.Lock() + panicMsg := call.PanicMsg + m.mutex.Unlock() + if panicMsg != nil { + panic(*panicMsg) + } + m.mutex.Lock() runFn := call.RunFn m.mutex.Unlock() @@ -527,6 +552,45 @@ func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...inter return true } +// IsMethodCallable checking that the method can be called +// If the method was called more than `Repeatability` return false +func (m *Mock) IsMethodCallable(t TestingT, methodName string, arguments ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + m.mutex.Lock() + defer m.mutex.Unlock() + + for _, v := range m.ExpectedCalls { + if v.Method != methodName { + continue + } + if len(arguments) != len(v.Arguments) { + continue + } + if v.Repeatability < v.totalCalls { + continue + } + if isArgsEqual(v.Arguments, arguments) { + return true + } + } + return false +} + +// isArgsEqual compares arguments +func isArgsEqual(expected Arguments, args []interface{}) bool { + if len(expected) != len(args) { + return false + } + for i, v := range args { + if !reflect.DeepEqual(expected[i], v) { + return false + } + } + return true +} + func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool { for _, call := range m.calls() { if call.Method == methodName { @@ -791,7 +855,7 @@ func (args Arguments) String(indexOrNil ...int) string { // normal String() method - return a string representation of the args var argsStr []string for _, arg := range args { - argsStr = append(argsStr, fmt.Sprintf("%s", reflect.TypeOf(arg))) + argsStr = append(argsStr, fmt.Sprintf("%T", arg)) // handles nil nicely } return strings.Join(argsStr, ",") } else if len(indexOrNil) == 1 { diff --git a/vendor/github.com/tetafro/godot/.gitignore b/vendor/github.com/tetafro/godot/.gitignore index 339f1705266..2b87e3915a9 100644 --- a/vendor/github.com/tetafro/godot/.gitignore +++ b/vendor/github.com/tetafro/godot/.gitignore @@ -1 +1,2 @@ +/dist/ /godot diff --git a/vendor/github.com/tetafro/godot/.golangci.yml b/vendor/github.com/tetafro/godot/.golangci.yml new file mode 100644 index 00000000000..17744dfbcc7 --- /dev/null +++ b/vendor/github.com/tetafro/godot/.golangci.yml @@ -0,0 +1,64 @@ +run: + concurrency: 2 + deadline: 5m + +skip-dirs: + - path: ./testdata/ + +linters: + disable-all: true + enable: + - deadcode + - errcheck + - gosimple + - govet + - ineffassign + - staticcheck + - structcheck + - typecheck + - unused + - varcheck + - bodyclose + - depguard + - dogsled + - dupl + - funlen + - gochecknoinits + - goconst + - gocritic + - gocyclo + - godot + - gofmt + - goimports + - golint + - gomnd + - gomodguard + - goprintffuncname + - gosec + - lll + - maligned + - misspell + - nakedret + - nestif + - prealloc + - rowserrcheck + - scopelint + - stylecheck + - unconvert + - unparam + - whitespace + +linters-settings: + godot: + check-all: true + +issues: + exclude-use-default: false + exclude-rules: + - path: _test\.go + linters: + - dupl + - funlen + - path: cmd/godot/main\.go + linters: + - gomnd diff --git a/vendor/github.com/tetafro/godot/.goreleaser.yml b/vendor/github.com/tetafro/godot/.goreleaser.yml new file mode 100644 index 00000000000..c0fc2b6b1f5 --- /dev/null +++ b/vendor/github.com/tetafro/godot/.goreleaser.yml @@ -0,0 +1,11 @@ +builds: + - dir: ./cmd/godot +checksum: + name_template: checksums.txt +snapshot: + name_template: "{{ .Tag }}" +changelog: + sort: asc + filters: + exclude: + - '^Merge pull request' diff --git a/vendor/github.com/tetafro/godot/Makefile b/vendor/github.com/tetafro/godot/Makefile new file mode 100644 index 00000000000..98a691d78cf --- /dev/null +++ b/vendor/github.com/tetafro/godot/Makefile @@ -0,0 +1,21 @@ +.PHONY: test +test: + go test ./... + +.PHONY: cover +cover: + go test -coverprofile cover.out ./... + go tool cover -html=cover.out + rm -f cover.out + +.PHONY: lint +lint: + golangci-lint run + +.PHONY: build +build: + go build -o godot ./cmd/godot + +.PHONY: release +release: + goreleaser release --rm-dist diff --git a/vendor/github.com/tetafro/godot/README.md b/vendor/github.com/tetafro/godot/README.md index 569d4e512ef..a47b163d08c 100644 --- a/vendor/github.com/tetafro/godot/README.md +++ b/vendor/github.com/tetafro/godot/README.md @@ -13,13 +13,32 @@ end of the last sentence if needed. > Comments should begin with the name of the thing being described > and end in a period -## Install and run +## Install + +*NOTE: Godot is available as a part of [GolangCI Lint](https://github.com/golangci/golangci-lint) +(disabled by default).* + +Build from source ```sh go get -u github.com/tetafro/godot/cmd/godot +``` + +or download binary from [releases page](https://github.com/tetafro/godot/releases). + +## Run + +```sh godot ./myproject ``` +Autofix flags are also available + +```sh +godot -f ./myproject # fix issues and print the result +godot -w ./myproject # fix issues and replace the original file +``` + ## Examples Code @@ -40,5 +59,5 @@ Top level comment should end in a period: math/math.go:3:1 ``` See more examples in test files: -- [for default mode](testdata/example_default.go) -- [for using --all flag](testdata/example_checkall.go) +- [for default mode](testdata/default/check/main.go) +- [for using --all flag](testdata/checkall/check/main.go) diff --git a/vendor/github.com/tetafro/godot/go.mod b/vendor/github.com/tetafro/godot/go.mod index ae9467ba479..d86531c42d6 100644 --- a/vendor/github.com/tetafro/godot/go.mod +++ b/vendor/github.com/tetafro/godot/go.mod @@ -1,3 +1,3 @@ module github.com/tetafro/godot -go 1.13 +go 1.14 diff --git a/vendor/github.com/tetafro/godot/godot.go b/vendor/github.com/tetafro/godot/godot.go index c5381396114..7cbcc5228e5 100644 --- a/vendor/github.com/tetafro/godot/godot.go +++ b/vendor/github.com/tetafro/godot/godot.go @@ -3,26 +3,36 @@ package godot import ( + "fmt" "go/ast" "go/token" + "io/ioutil" + "os" "regexp" "strings" ) const noPeriodMessage = "Top level comment should end in a period" -// Message contains a message of linting error. -type Message struct { - Pos token.Position - Message string -} - // Settings contains linter settings. type Settings struct { // Check all top-level comments, not only declarations CheckAll bool } +// Issue contains a description of linting error and a possible replacement. +type Issue struct { + Pos token.Position + Message string + Replacement string +} + +// position is an position inside a comment (might be multiline comment). +type position struct { + line int + column int +} + var ( // List of valid last characters. lastChars = []string{".", "?", "!"} @@ -38,43 +48,95 @@ var ( ) // Run runs this linter on the provided code. -func Run(file *ast.File, fset *token.FileSet, settings Settings) []Message { - msgs := []Message{} +func Run(file *ast.File, fset *token.FileSet, settings Settings) []Issue { + issues := []Issue{} // Check all top-level comments if settings.CheckAll { for _, group := range file.Comments { - if ok, msg := check(fset, group); !ok { - msgs = append(msgs, msg) + if iss, ok := check(fset, group); !ok { + issues = append(issues, iss) } } - return msgs + return issues } // Check only declaration comments for _, decl := range file.Decls { switch d := decl.(type) { case *ast.GenDecl: - if ok, msg := check(fset, d.Doc); !ok { - msgs = append(msgs, msg) + if iss, ok := check(fset, d.Doc); !ok { + issues = append(issues, iss) } case *ast.FuncDecl: - if ok, msg := check(fset, d.Doc); !ok { - msgs = append(msgs, msg) + if iss, ok := check(fset, d.Doc); !ok { + issues = append(issues, iss) } } } - return msgs + return issues +} + +// Fix fixes all issues and return new version of file content. +func Fix(path string, file *ast.File, fset *token.FileSet, settings Settings) ([]byte, error) { + // Read file + content, err := ioutil.ReadFile(path) // nolint: gosec + if err != nil { + return nil, fmt.Errorf("read file: %v", err) + } + if len(content) == 0 { + return nil, nil + } + + issues := Run(file, fset, settings) + + // slice -> map + m := map[int]Issue{} + for _, iss := range issues { + m[iss.Pos.Line] = iss + } + + // Replace lines from issues + fixed := make([]byte, 0, len(content)) + for i, line := range strings.Split(string(content), "\n") { + newline := line + if iss, ok := m[i+1]; ok { + newline = iss.Replacement + } + fixed = append(fixed, []byte(newline+"\n")...) + } + fixed = fixed[:len(fixed)-1] // trim last "\n" + + return fixed, nil +} + +// Replace rewrites original file with it's fixed version. +func Replace(path string, file *ast.File, fset *token.FileSet, settings Settings) error { + info, err := os.Stat(path) + if err != nil { + return fmt.Errorf("check file: %v", err) + } + mode := info.Mode() + + fixed, err := Fix(path, file, fset, settings) + if err != nil { + return fmt.Errorf("fix issues: %v", err) + } + + if err := ioutil.WriteFile(path, fixed, mode); err != nil { + return fmt.Errorf("write file: %v", err) + } + return nil } -func check(fset *token.FileSet, group *ast.CommentGroup) (ok bool, msg Message) { +func check(fset *token.FileSet, group *ast.CommentGroup) (iss Issue, ok bool) { if group == nil || len(group.List) == 0 { - return true, Message{} + return Issue{}, true } // Check only top-level comments if fset.Position(group.Pos()).Column > 1 { - return true, Message{} + return Issue{}, true } // Get last element from comment group - it can be either @@ -82,29 +144,36 @@ func check(fset *token.FileSet, group *ast.CommentGroup) (ok bool, msg Message) // for "/*"-comment last := group.List[len(group.List)-1] - line, ok := checkComment(last.Text) + p, ok := checkComment(last.Text) if ok { - return true, Message{} + return Issue{}, true } pos := fset.Position(last.Slash) - pos.Line += line - return false, Message{ - Pos: pos, - Message: noPeriodMessage, + pos.Line += p.line + pos.Column = p.column + iss = Issue{ + Pos: pos, + Message: noPeriodMessage, + Replacement: makeReplacement(last.Text, p), } + return iss, false } -func checkComment(comment string) (line int, ok bool) { +func checkComment(comment string) (pos position, ok bool) { // Check last line of "//"-comment if strings.HasPrefix(comment, "//") { + pos.column = len([]rune(comment)) // runes for non-latin chars comment = strings.TrimPrefix(comment, "//") - return 0, checkLastChar(comment) + if checkLastChar(comment) { + return position{}, true + } + return pos, false } // Skip cgo code blocks - // TODO: Find a better way to detect cgo code. + // TODO: Find a better way to detect cgo code if strings.Contains(comment, "#include") || strings.Contains(comment, "#define") { - return 0, true + return position{}, true } // Check last non-empty line in multiline "/*"-comment block @@ -116,15 +185,29 @@ func checkComment(comment string) (line int, ok bool) { } break } - comment = strings.TrimPrefix(lines[i], "/*") + pos.line = i + comment = lines[i] comment = strings.TrimSuffix(comment, "*/") - return i, checkLastChar(comment) + comment = strings.TrimRight(comment, " ") + // Get position of the last non-space char in comment line, use runes + // in case of non-latin chars + pos.column = len([]rune(comment)) + comment = strings.TrimPrefix(comment, "/*") + + if checkLastChar(comment) { + return position{}, true + } + return pos, false } func checkLastChar(s string) bool { // Don't check comments starting with space indentation - they may // contain code examples, which shouldn't end with period - if strings.HasPrefix(s, " ") || strings.HasPrefix(s, "\t") { + if strings.HasPrefix(s, " ") || strings.HasPrefix(s, " \t") || strings.HasPrefix(s, "\t") { + return true + } + // Skip cgo export tags: https://golang.org/cmd/cgo/#hdr-C_references_to_Go + if strings.HasPrefix(s, "export") { return true } s = strings.TrimSpace(s) @@ -145,3 +228,24 @@ func checkLastChar(s string) bool { } return false } + +// makeReplacement basically just inserts a period into comment on +// the given position. +func makeReplacement(s string, pos position) string { + lines := strings.Split(s, "\n") + if len(lines) < pos.line { + // This should never happen + return s + } + line := []rune(lines[pos.line]) + if len(line) < pos.column { + // This should never happen + return s + } + // Insert a period + newline := append( + line[:pos.column], + append([]rune{'.'}, line[pos.column:]...)..., + ) + return string(newline) +} diff --git a/vendor/github.com/ulikunitz/xz/LICENSE b/vendor/github.com/ulikunitz/xz/LICENSE index 58ebdc162f5..d32149979df 100644 --- a/vendor/github.com/ulikunitz/xz/LICENSE +++ b/vendor/github.com/ulikunitz/xz/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2014-2016 Ulrich Kunitz +Copyright (c) 2014-2020 Ulrich Kunitz All rights reserved. Redistribution and use in source and binary forms, with or without diff --git a/vendor/github.com/ulikunitz/xz/TODO.md b/vendor/github.com/ulikunitz/xz/TODO.md index c10e51b9aa2..a4224ce142d 100644 --- a/vendor/github.com/ulikunitz/xz/TODO.md +++ b/vendor/github.com/ulikunitz/xz/TODO.md @@ -1,5 +1,9 @@ # TODO list +## Release v0.5.x + +1. Support check flag in gxz command. + ## Release v0.6 1. Review encoder and check for lzma improvements under xz. @@ -86,6 +90,15 @@ ## Log +### 2020-02-24 + +Release v0.5.7 supports the check-ID None and fixes +[issue #27](https://github.com/ulikunitz/xz/issues/27). + +### 2019-02-20 + +Release v0.5.6 supports the go.mod file. + ### 2018-10-28 Release v0.5.5 fixes issues #19 observing ErrLimit outputs. diff --git a/vendor/github.com/ulikunitz/xz/bits.go b/vendor/github.com/ulikunitz/xz/bits.go index fadc1a59449..364213dd94b 100644 --- a/vendor/github.com/ulikunitz/xz/bits.go +++ b/vendor/github.com/ulikunitz/xz/bits.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/crc.go b/vendor/github.com/ulikunitz/xz/crc.go index b44dca96e8e..638774ada6b 100644 --- a/vendor/github.com/ulikunitz/xz/crc.go +++ b/vendor/github.com/ulikunitz/xz/crc.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/format.go b/vendor/github.com/ulikunitz/xz/format.go index 798159c6c6f..edfec9a94a8 100644 --- a/vendor/github.com/ulikunitz/xz/format.go +++ b/vendor/github.com/ulikunitz/xz/format.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -46,7 +46,8 @@ const HeaderLen = 12 // Constants for the checksum methods supported by xz. const ( - CRC32 byte = 0x1 + None byte = 0x0 + CRC32 = 0x1 CRC64 = 0x4 SHA256 = 0xa ) @@ -58,7 +59,7 @@ var errInvalidFlags = errors.New("xz: invalid flags") // invalid. func verifyFlags(flags byte) error { switch flags { - case CRC32, CRC64, SHA256: + case None, CRC32, CRC64, SHA256: return nil default: return errInvalidFlags @@ -67,6 +68,7 @@ func verifyFlags(flags byte) error { // flagstrings maps flag values to strings. var flagstrings = map[byte]string{ + None: "None", CRC32: "CRC-32", CRC64: "CRC-64", SHA256: "SHA-256", @@ -85,6 +87,8 @@ func flagString(flags byte) string { // hash method encoded in flags. func newHashFunc(flags byte) (newHash func() hash.Hash, err error) { switch flags { + case None: + newHash = newNoneHash case CRC32: newHash = newCRC32 case CRC64: diff --git a/vendor/github.com/ulikunitz/xz/fox-check-none.xz b/vendor/github.com/ulikunitz/xz/fox-check-none.xz new file mode 100644 index 00000000000..46043f7dc89 Binary files /dev/null and b/vendor/github.com/ulikunitz/xz/fox-check-none.xz differ diff --git a/vendor/github.com/ulikunitz/xz/go.mod b/vendor/github.com/ulikunitz/xz/go.mod new file mode 100644 index 00000000000..330b675bd72 --- /dev/null +++ b/vendor/github.com/ulikunitz/xz/go.mod @@ -0,0 +1,3 @@ +module github.com/ulikunitz/xz + +go 1.12 diff --git a/vendor/github.com/ulikunitz/xz/internal/hash/cyclic_poly.go b/vendor/github.com/ulikunitz/xz/internal/hash/cyclic_poly.go index a32887872e1..f2861ba3f7f 100644 --- a/vendor/github.com/ulikunitz/xz/internal/hash/cyclic_poly.go +++ b/vendor/github.com/ulikunitz/xz/internal/hash/cyclic_poly.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/internal/hash/doc.go b/vendor/github.com/ulikunitz/xz/internal/hash/doc.go index f99ec220680..e28d23be47e 100644 --- a/vendor/github.com/ulikunitz/xz/internal/hash/doc.go +++ b/vendor/github.com/ulikunitz/xz/internal/hash/doc.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/internal/hash/rabin_karp.go b/vendor/github.com/ulikunitz/xz/internal/hash/rabin_karp.go index 58635b113a9..b8e66d9721c 100644 --- a/vendor/github.com/ulikunitz/xz/internal/hash/rabin_karp.go +++ b/vendor/github.com/ulikunitz/xz/internal/hash/rabin_karp.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/internal/hash/roller.go b/vendor/github.com/ulikunitz/xz/internal/hash/roller.go index ab6a19ca4cc..34c81b38a72 100644 --- a/vendor/github.com/ulikunitz/xz/internal/hash/roller.go +++ b/vendor/github.com/ulikunitz/xz/internal/hash/roller.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/internal/xlog/xlog.go b/vendor/github.com/ulikunitz/xz/internal/xlog/xlog.go index 0ba45e8ff33..678b5a0589d 100644 --- a/vendor/github.com/ulikunitz/xz/internal/xlog/xlog.go +++ b/vendor/github.com/ulikunitz/xz/internal/xlog/xlog.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/bintree.go b/vendor/github.com/ulikunitz/xz/lzma/bintree.go index a781bd1953d..58d6a92a72c 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/bintree.go +++ b/vendor/github.com/ulikunitz/xz/lzma/bintree.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/bitops.go b/vendor/github.com/ulikunitz/xz/lzma/bitops.go index e9bab019901..2784ec6ba04 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/bitops.go +++ b/vendor/github.com/ulikunitz/xz/lzma/bitops.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/breader.go b/vendor/github.com/ulikunitz/xz/lzma/breader.go index 5350d814fa7..4ad09a14e7e 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/breader.go +++ b/vendor/github.com/ulikunitz/xz/lzma/breader.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/buffer.go b/vendor/github.com/ulikunitz/xz/lzma/buffer.go index 50e0b6d57b5..9cb7838acb5 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/buffer.go +++ b/vendor/github.com/ulikunitz/xz/lzma/buffer.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/bytewriter.go b/vendor/github.com/ulikunitz/xz/lzma/bytewriter.go index a3696ba08be..290606ddccd 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/bytewriter.go +++ b/vendor/github.com/ulikunitz/xz/lzma/bytewriter.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/decoder.go b/vendor/github.com/ulikunitz/xz/lzma/decoder.go index 16e14db3941..e5a760a50b0 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/decoder.go +++ b/vendor/github.com/ulikunitz/xz/lzma/decoder.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/decoderdict.go b/vendor/github.com/ulikunitz/xz/lzma/decoderdict.go index 564a12b834c..ba06712b03f 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/decoderdict.go +++ b/vendor/github.com/ulikunitz/xz/lzma/decoderdict.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/directcodec.go b/vendor/github.com/ulikunitz/xz/lzma/directcodec.go index e08eb989ff9..e6e0c6ddf36 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/directcodec.go +++ b/vendor/github.com/ulikunitz/xz/lzma/directcodec.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/distcodec.go b/vendor/github.com/ulikunitz/xz/lzma/distcodec.go index b053a2dce21..69871c04ad5 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/distcodec.go +++ b/vendor/github.com/ulikunitz/xz/lzma/distcodec.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/encoder.go b/vendor/github.com/ulikunitz/xz/lzma/encoder.go index fe1900a66e8..59055eb64cc 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/encoder.go +++ b/vendor/github.com/ulikunitz/xz/lzma/encoder.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/encoderdict.go b/vendor/github.com/ulikunitz/xz/lzma/encoderdict.go index 9d0fbc70332..40f3d3f64a7 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/encoderdict.go +++ b/vendor/github.com/ulikunitz/xz/lzma/encoderdict.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/hashtable.go b/vendor/github.com/ulikunitz/xz/lzma/hashtable.go index d786a9745d4..e82970eac2f 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/hashtable.go +++ b/vendor/github.com/ulikunitz/xz/lzma/hashtable.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/header.go b/vendor/github.com/ulikunitz/xz/lzma/header.go index bc708969fd3..cda39462ce4 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/header.go +++ b/vendor/github.com/ulikunitz/xz/lzma/header.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/header2.go b/vendor/github.com/ulikunitz/xz/lzma/header2.go index ac6a71a5a98..cd148812cd5 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/header2.go +++ b/vendor/github.com/ulikunitz/xz/lzma/header2.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/lengthcodec.go b/vendor/github.com/ulikunitz/xz/lzma/lengthcodec.go index e517730924f..927395bd809 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/lengthcodec.go +++ b/vendor/github.com/ulikunitz/xz/lzma/lengthcodec.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/literalcodec.go b/vendor/github.com/ulikunitz/xz/lzma/literalcodec.go index c949d6ebd12..ca31530fd57 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/literalcodec.go +++ b/vendor/github.com/ulikunitz/xz/lzma/literalcodec.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/matchalgorithm.go b/vendor/github.com/ulikunitz/xz/lzma/matchalgorithm.go index 4a244eb1ac7..7d03ec0dc50 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/matchalgorithm.go +++ b/vendor/github.com/ulikunitz/xz/lzma/matchalgorithm.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/operation.go b/vendor/github.com/ulikunitz/xz/lzma/operation.go index 733bb99da41..a75c9b46c52 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/operation.go +++ b/vendor/github.com/ulikunitz/xz/lzma/operation.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/prob.go b/vendor/github.com/ulikunitz/xz/lzma/prob.go index 24d50ec6814..6987a166f07 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/prob.go +++ b/vendor/github.com/ulikunitz/xz/lzma/prob.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/properties.go b/vendor/github.com/ulikunitz/xz/lzma/properties.go index 23418e25d26..662feba872e 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/properties.go +++ b/vendor/github.com/ulikunitz/xz/lzma/properties.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/rangecodec.go b/vendor/github.com/ulikunitz/xz/lzma/rangecodec.go index 6361c5e7c83..7189a037764 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/rangecodec.go +++ b/vendor/github.com/ulikunitz/xz/lzma/rangecodec.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/reader.go b/vendor/github.com/ulikunitz/xz/lzma/reader.go index 2ef3dcaaa9b..7b7eef31f81 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/reader.go +++ b/vendor/github.com/ulikunitz/xz/lzma/reader.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/reader2.go b/vendor/github.com/ulikunitz/xz/lzma/reader2.go index a55cfaa4e3f..33074e62429 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/reader2.go +++ b/vendor/github.com/ulikunitz/xz/lzma/reader2.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/state.go b/vendor/github.com/ulikunitz/xz/lzma/state.go index 502351052fd..03f061cf109 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/state.go +++ b/vendor/github.com/ulikunitz/xz/lzma/state.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/treecodecs.go b/vendor/github.com/ulikunitz/xz/lzma/treecodecs.go index 504b3d78e44..1cb3596fe1e 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/treecodecs.go +++ b/vendor/github.com/ulikunitz/xz/lzma/treecodecs.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/writer.go b/vendor/github.com/ulikunitz/xz/lzma/writer.go index efe34fb6bfe..5803ecca961 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/writer.go +++ b/vendor/github.com/ulikunitz/xz/lzma/writer.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzma/writer2.go b/vendor/github.com/ulikunitz/xz/lzma/writer2.go index 7c1afe15725..c263b0666a4 100644 --- a/vendor/github.com/ulikunitz/xz/lzma/writer2.go +++ b/vendor/github.com/ulikunitz/xz/lzma/writer2.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/lzmafilter.go b/vendor/github.com/ulikunitz/xz/lzmafilter.go index 69cf5f7c279..6f4aa2c09c9 100644 --- a/vendor/github.com/ulikunitz/xz/lzmafilter.go +++ b/vendor/github.com/ulikunitz/xz/lzmafilter.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/github.com/ulikunitz/xz/none-check.go b/vendor/github.com/ulikunitz/xz/none-check.go new file mode 100644 index 00000000000..e12d8e476b5 --- /dev/null +++ b/vendor/github.com/ulikunitz/xz/none-check.go @@ -0,0 +1,23 @@ +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package xz + +import "hash" + +type noneHash struct{} + +func (h noneHash) Write(p []byte) (n int, err error) { return len(p), nil } + +func (h noneHash) Sum(b []byte) []byte { return b } + +func (h noneHash) Reset() {} + +func (h noneHash) Size() int { return 0 } + +func (h noneHash) BlockSize() int { return 0 } + +func newNoneHash() hash.Hash { + return &noneHash{} +} diff --git a/vendor/github.com/ulikunitz/xz/reader.go b/vendor/github.com/ulikunitz/xz/reader.go index 0634c6bcc0c..22cd6d5007f 100644 --- a/vendor/github.com/ulikunitz/xz/reader.go +++ b/vendor/github.com/ulikunitz/xz/reader.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -283,7 +283,11 @@ func (c *ReaderConfig) newBlockReader(xz io.Reader, h *blockHeader, if err != nil { return nil, err } - br.r = io.TeeReader(fr, br.hash) + if br.hash.Size() != 0 { + br.r = io.TeeReader(fr, br.hash) + } else { + br.r = fr + } return br, nil } diff --git a/vendor/github.com/ulikunitz/xz/writer.go b/vendor/github.com/ulikunitz/xz/writer.go index c126f70995d..aec10dfa624 100644 --- a/vendor/github.com/ulikunitz/xz/writer.go +++ b/vendor/github.com/ulikunitz/xz/writer.go @@ -1,4 +1,4 @@ -// Copyright 2014-2017 Ulrich Kunitz. All rights reserved. +// Copyright 2014-2019 Ulrich Kunitz. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -18,8 +18,10 @@ type WriterConfig struct { DictCap int BufSize int BlockSize int64 - // checksum method: CRC32, CRC64 or SHA256 + // checksum method: CRC32, CRC64 or SHA256 (default: CRC64) CheckSum byte + // Forces NoChecksum (default: false) + NoCheckSum bool // match algorithm Matcher lzma.MatchAlgorithm } @@ -41,6 +43,9 @@ func (c *WriterConfig) fill() { if c.CheckSum == 0 { c.CheckSum = CRC64 } + if c.NoCheckSum { + c.CheckSum = None + } } // Verify checks the configuration for errors. Zero values will be @@ -284,7 +289,11 @@ func (c *WriterConfig) newBlockWriter(xz io.Writer, hash hash.Hash) (bw *blockWr if err != nil { return nil, err } - bw.mw = io.MultiWriter(bw.w, bw.hash) + if bw.hash.Size() != 0 { + bw.mw = io.MultiWriter(bw.w, bw.hash) + } else { + bw.mw = bw.w + } return bw, nil } diff --git a/vendor/github.com/zclconf/go-cty-yaml/.travis.yml b/vendor/github.com/zclconf/go-cty-yaml/.travis.yml deleted file mode 100644 index 13ff9986686..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: go - -go: - - 1.12 - diff --git a/vendor/github.com/zclconf/go-cty-yaml/CHANGELOG.md b/vendor/github.com/zclconf/go-cty-yaml/CHANGELOG.md deleted file mode 100644 index b3bc3b61893..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/CHANGELOG.md +++ /dev/null @@ -1,10 +0,0 @@ -# 1.0.1 (July 30, 2019) - -* The YAML decoder is now correctly treating quoted scalars as verbatim literal - strings rather than using the fuzzy type selection rules for them. Fuzzy - type selection rules still apply to unquoted scalars. - ([#4](https://github.com/zclconf/go-cty-yaml/pull/4)) - -# 1.0.0 (May 26, 2019) - -Initial release. diff --git a/vendor/github.com/zclconf/go-cty-yaml/LICENSE b/vendor/github.com/zclconf/go-cty-yaml/LICENSE deleted file mode 100644 index 8dada3edaf5..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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/zclconf/go-cty-yaml/LICENSE.libyaml b/vendor/github.com/zclconf/go-cty-yaml/LICENSE.libyaml deleted file mode 100644 index 8da58fbf6f8..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/LICENSE.libyaml +++ /dev/null @@ -1,31 +0,0 @@ -The following files were ported to Go from C files of libyaml, and thus -are still covered by their original copyright and license: - - apic.go - emitterc.go - parserc.go - readerc.go - scannerc.go - writerc.go - yamlh.go - yamlprivateh.go - -Copyright (c) 2006 Kirill Simonov - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/zclconf/go-cty-yaml/NOTICE b/vendor/github.com/zclconf/go-cty-yaml/NOTICE deleted file mode 100644 index 4e6c00ab317..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/NOTICE +++ /dev/null @@ -1,20 +0,0 @@ -This package is derived from gopkg.in/yaml.v2, which is copyright -2011-2016 Canonical Ltd. - -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. - -Includes mechanical ports of code from libyaml, distributed under its original -license. See LICENSE.libyaml for more information. - -Modifications for cty interfacing copyright 2019 Martin Atkins, and -distributed under the same license terms. diff --git a/vendor/github.com/zclconf/go-cty-yaml/converter.go b/vendor/github.com/zclconf/go-cty-yaml/converter.go deleted file mode 100644 index a73b34a8b2a..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/converter.go +++ /dev/null @@ -1,69 +0,0 @@ -package yaml - -import ( - "github.com/zclconf/go-cty/cty" -) - -// ConverterConfig is used to configure a new converter, using NewConverter. -type ConverterConfig struct { - // EncodeAsFlow, when set to true, causes Marshal to produce flow-style - // mapping and sequence serializations. - EncodeAsFlow bool -} - -// A Converter can marshal and unmarshal between cty values and YAML bytes. -// -// Because there are many different ways to map cty to YAML and vice-versa, -// a converter is configurable using the settings in ConverterConfig, which -// allow for a few different permutations of mapping to YAML. -// -// If you are just trying to work with generic, standard YAML, the predefined -// converter in Standard should be good enough. -type Converter struct { - encodeAsFlow bool -} - -// NewConverter creates a new Converter with the given configuration. -func NewConverter(config *ConverterConfig) *Converter { - return &Converter{ - encodeAsFlow: config.EncodeAsFlow, - } -} - -// Standard is a predefined Converter that produces and consumes generic YAML -// using only built-in constructs that any other YAML implementation ought to -// understand. -var Standard *Converter = NewConverter(&ConverterConfig{}) - -// ImpliedType analyzes the given source code and returns a suitable type that -// it could be decoded into. -// -// For a converter that is using standard YAML rather than cty-specific custom -// tags, only a subset of cty types can be produced: strings, numbers, bools, -// tuple types, and object types. -func (c *Converter) ImpliedType(src []byte) (cty.Type, error) { - return c.impliedType(src) -} - -// Marshal serializes the given value into a YAML document, using a fixed -// mapping from cty types to YAML constructs. -// -// Note that unlike the function of the same name in the cty JSON package, -// this does not take a type constraint and therefore the YAML serialization -// cannot preserve late-bound type information in the serialization to be -// recovered from Unmarshal. Instead, any cty.DynamicPseudoType in the type -// constraint given to Unmarshal will be decoded as if the corresponding portion -// of the input were processed with ImpliedType to find a target type. -func (c *Converter) Marshal(v cty.Value) ([]byte, error) { - return c.marshal(v) -} - -// Unmarshal reads the document found within the given source buffer -// and attempts to convert it into a value conforming to the given type -// constraint. -// -// An error is returned if the given source contains any YAML document -// delimiters. -func (c *Converter) Unmarshal(src []byte, ty cty.Type) (cty.Value, error) { - return c.unmarshal(src, ty) -} diff --git a/vendor/github.com/zclconf/go-cty-yaml/cty_funcs.go b/vendor/github.com/zclconf/go-cty-yaml/cty_funcs.go deleted file mode 100644 index b91141ccaa9..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/cty_funcs.go +++ /dev/null @@ -1,57 +0,0 @@ -package yaml - -import ( - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" -) - -// YAMLDecodeFunc is a cty function for decoding arbitrary YAML source code -// into a cty Value, using the ImpliedType and Unmarshal methods of the -// Standard pre-defined converter. -var YAMLDecodeFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "src", - Type: cty.String, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - if !args[0].IsKnown() { - return cty.DynamicPseudoType, nil - } - if args[0].IsNull() { - return cty.NilType, function.NewArgErrorf(0, "YAML source code cannot be null") - } - return Standard.ImpliedType([]byte(args[0].AsString())) - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - if retType == cty.DynamicPseudoType { - return cty.DynamicVal, nil - } - return Standard.Unmarshal([]byte(args[0].AsString()), retType) - }, -}) - -// YAMLEncodeFunc is a cty function for encoding an arbitrary cty value -// into YAML. -var YAMLEncodeFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "value", - Type: cty.DynamicPseudoType, - AllowNull: true, - AllowDynamicType: true, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - if !args[0].IsWhollyKnown() { - return cty.UnknownVal(retType), nil - } - raw, err := Standard.Marshal(args[0]) - if err != nil { - return cty.NilVal, err - } - return cty.StringVal(string(raw)), nil - }, -}) diff --git a/vendor/github.com/zclconf/go-cty-yaml/decode.go b/vendor/github.com/zclconf/go-cty-yaml/decode.go deleted file mode 100644 index e369ff27c88..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/decode.go +++ /dev/null @@ -1,261 +0,0 @@ -package yaml - -import ( - "errors" - "fmt" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -func (c *Converter) unmarshal(src []byte, ty cty.Type) (cty.Value, error) { - p := &yaml_parser_t{} - if !yaml_parser_initialize(p) { - return cty.NilVal, errors.New("failed to initialize YAML parser") - } - if len(src) == 0 { - src = []byte{'\n'} - } - - an := &valueAnalysis{ - anchorsPending: map[string]int{}, - anchorVals: map[string]cty.Value{}, - } - - yaml_parser_set_input_string(p, src) - - var evt yaml_event_t - if !yaml_parser_parse(p, &evt) { - return cty.NilVal, parserError(p) - } - if evt.typ != yaml_STREAM_START_EVENT { - return cty.NilVal, parseEventErrorf(&evt, "missing stream start token") - } - if !yaml_parser_parse(p, &evt) { - return cty.NilVal, parserError(p) - } - if evt.typ != yaml_DOCUMENT_START_EVENT { - return cty.NilVal, parseEventErrorf(&evt, "missing start of document") - } - - v, err := c.unmarshalParse(an, p) - if err != nil { - return cty.NilVal, err - } - - if !yaml_parser_parse(p, &evt) { - return cty.NilVal, parserError(p) - } - if evt.typ == yaml_DOCUMENT_START_EVENT { - return cty.NilVal, parseEventErrorf(&evt, "only a single document is allowed") - } - if evt.typ != yaml_DOCUMENT_END_EVENT { - return cty.NilVal, parseEventErrorf(&evt, "unexpected extra content (%s) after value", evt.typ.String()) - } - if !yaml_parser_parse(p, &evt) { - return cty.NilVal, parserError(p) - } - if evt.typ != yaml_STREAM_END_EVENT { - return cty.NilVal, parseEventErrorf(&evt, "unexpected extra content after value") - } - - return convert.Convert(v, ty) -} - -func (c *Converter) unmarshalParse(an *valueAnalysis, p *yaml_parser_t) (cty.Value, error) { - var evt yaml_event_t - if !yaml_parser_parse(p, &evt) { - return cty.NilVal, parserError(p) - } - return c.unmarshalParseRemainder(an, &evt, p) -} - -func (c *Converter) unmarshalParseRemainder(an *valueAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Value, error) { - switch evt.typ { - case yaml_SCALAR_EVENT: - return c.unmarshalScalar(an, evt, p) - case yaml_ALIAS_EVENT: - return c.unmarshalAlias(an, evt, p) - case yaml_MAPPING_START_EVENT: - return c.unmarshalMapping(an, evt, p) - case yaml_SEQUENCE_START_EVENT: - return c.unmarshalSequence(an, evt, p) - case yaml_DOCUMENT_START_EVENT: - return cty.NilVal, parseEventErrorf(evt, "only a single document is allowed") - case yaml_STREAM_END_EVENT: - // Decoding an empty buffer, probably - return cty.NilVal, parseEventErrorf(evt, "expecting value but found end of stream") - default: - // Should never happen; the above should be comprehensive - return cty.NilVal, parseEventErrorf(evt, "unexpected parser event %s", evt.typ.String()) - } -} - -func (c *Converter) unmarshalScalar(an *valueAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Value, error) { - src := evt.value - tag := string(evt.tag) - anchor := string(evt.anchor) - - if len(anchor) > 0 { - an.beginAnchor(anchor) - } - - val, err := c.resolveScalar(tag, string(src), yaml_scalar_style_t(evt.style)) - if err != nil { - return cty.NilVal, parseEventErrorWrap(evt, err) - } - - if val.RawEquals(mergeMappingVal) { - // In any context other than a mapping key, this is just a plain string - val = cty.StringVal("<<") - } - - if len(anchor) > 0 { - an.completeAnchor(anchor, val) - } - return val, nil -} - -func (c *Converter) unmarshalMapping(an *valueAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Value, error) { - tag := string(evt.tag) - anchor := string(evt.anchor) - - if tag != "" && tag != yaml_MAP_TAG { - return cty.NilVal, parseEventErrorf(evt, "can't interpret mapping as %s", tag) - } - - if anchor != "" { - an.beginAnchor(anchor) - } - - vals := make(map[string]cty.Value) - for { - var nextEvt yaml_event_t - if !yaml_parser_parse(p, &nextEvt) { - return cty.NilVal, parserError(p) - } - if nextEvt.typ == yaml_MAPPING_END_EVENT { - v := cty.ObjectVal(vals) - if anchor != "" { - an.completeAnchor(anchor, v) - } - return v, nil - } - - if nextEvt.typ != yaml_SCALAR_EVENT { - return cty.NilVal, parseEventErrorf(&nextEvt, "only strings are allowed as mapping keys") - } - keyVal, err := c.resolveScalar(string(nextEvt.tag), string(nextEvt.value), yaml_scalar_style_t(nextEvt.style)) - if err != nil { - return cty.NilVal, err - } - if keyVal.RawEquals(mergeMappingVal) { - // Merging the value (which must be a mapping) into our mapping, - // then. - val, err := c.unmarshalParse(an, p) - if err != nil { - return cty.NilVal, err - } - ty := val.Type() - if !(ty.IsObjectType() || ty.IsMapType()) { - return cty.NilVal, parseEventErrorf(&nextEvt, "cannot merge %s into mapping", ty.FriendlyName()) - } - for it := val.ElementIterator(); it.Next(); { - k, v := it.Element() - vals[k.AsString()] = v - } - continue - } - if keyValStr, err := convert.Convert(keyVal, cty.String); err == nil { - keyVal = keyValStr - } else { - return cty.NilVal, parseEventErrorf(&nextEvt, "only strings are allowed as mapping keys") - } - if keyVal.IsNull() { - return cty.NilVal, parseEventErrorf(&nextEvt, "mapping key cannot be null") - } - if !keyVal.IsKnown() { - return cty.NilVal, parseEventErrorf(&nextEvt, "mapping key must be known") - } - val, err := c.unmarshalParse(an, p) - if err != nil { - return cty.NilVal, err - } - - vals[keyVal.AsString()] = val - } -} - -func (c *Converter) unmarshalSequence(an *valueAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Value, error) { - tag := string(evt.tag) - anchor := string(evt.anchor) - - if tag != "" && tag != yaml_SEQ_TAG { - return cty.NilVal, parseEventErrorf(evt, "can't interpret sequence as %s", tag) - } - - if anchor != "" { - an.beginAnchor(anchor) - } - - var vals []cty.Value - for { - var nextEvt yaml_event_t - if !yaml_parser_parse(p, &nextEvt) { - return cty.NilVal, parserError(p) - } - if nextEvt.typ == yaml_SEQUENCE_END_EVENT { - ty := cty.TupleVal(vals) - if anchor != "" { - an.completeAnchor(anchor, ty) - } - return ty, nil - } - - val, err := c.unmarshalParseRemainder(an, &nextEvt, p) - if err != nil { - return cty.NilVal, err - } - - vals = append(vals, val) - } -} - -func (c *Converter) unmarshalAlias(an *valueAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Value, error) { - v, err := an.anchorVal(string(evt.anchor)) - if err != nil { - err = parseEventErrorWrap(evt, err) - } - return v, err -} - -type valueAnalysis struct { - anchorsPending map[string]int - anchorVals map[string]cty.Value -} - -func (an *valueAnalysis) beginAnchor(name string) { - an.anchorsPending[name]++ -} - -func (an *valueAnalysis) completeAnchor(name string, v cty.Value) { - an.anchorsPending[name]-- - if an.anchorsPending[name] == 0 { - delete(an.anchorsPending, name) - } - an.anchorVals[name] = v -} - -func (an *valueAnalysis) anchorVal(name string) (cty.Value, error) { - if _, pending := an.anchorsPending[name]; pending { - // YAML normally allows self-referencing structures, but cty cannot - // represent them (it requires all structures to be finite) so we - // must fail here. - return cty.NilVal, fmt.Errorf("cannot refer to anchor %q from inside its own definition", name) - } - ty, ok := an.anchorVals[name] - if !ok { - return cty.NilVal, fmt.Errorf("reference to undefined anchor %q", name) - } - return ty, nil -} diff --git a/vendor/github.com/zclconf/go-cty-yaml/encode.go b/vendor/github.com/zclconf/go-cty-yaml/encode.go deleted file mode 100644 index daa1478a934..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/encode.go +++ /dev/null @@ -1,189 +0,0 @@ -package yaml - -import ( - "bytes" - "fmt" - "strings" - - "github.com/zclconf/go-cty/cty" -) - -func (c *Converter) marshal(v cty.Value) ([]byte, error) { - var buf bytes.Buffer - - e := &yaml_emitter_t{} - yaml_emitter_initialize(e) - yaml_emitter_set_output_writer(e, &buf) - yaml_emitter_set_unicode(e, true) - - var evt yaml_event_t - yaml_stream_start_event_initialize(&evt, yaml_UTF8_ENCODING) - if !yaml_emitter_emit(e, &evt) { - return nil, emitterError(e) - } - yaml_document_start_event_initialize(&evt, nil, nil, true) - if !yaml_emitter_emit(e, &evt) { - return nil, emitterError(e) - } - - if err := c.marshalEmit(v, e); err != nil { - return nil, err - } - - yaml_document_end_event_initialize(&evt, true) - if !yaml_emitter_emit(e, &evt) { - return nil, emitterError(e) - } - yaml_stream_end_event_initialize(&evt) - if !yaml_emitter_emit(e, &evt) { - return nil, emitterError(e) - } - - return buf.Bytes(), nil -} - -func (c *Converter) marshalEmit(v cty.Value, e *yaml_emitter_t) error { - ty := v.Type() - switch { - case v.IsNull(): - return c.marshalPrimitive(v, e) - case !v.IsKnown(): - return fmt.Errorf("cannot serialize unknown value as YAML") - case ty.IsPrimitiveType(): - return c.marshalPrimitive(v, e) - case ty.IsTupleType(), ty.IsListType(), ty.IsSetType(): - return c.marshalSequence(v, e) - case ty.IsObjectType(), ty.IsMapType(): - return c.marshalMapping(v, e) - default: - return fmt.Errorf("can't marshal %s as YAML", ty.FriendlyName()) - } -} - -func (c *Converter) marshalPrimitive(v cty.Value, e *yaml_emitter_t) error { - var evt yaml_event_t - - if v.IsNull() { - yaml_scalar_event_initialize( - &evt, - nil, - nil, - []byte("null"), - true, - true, - yaml_PLAIN_SCALAR_STYLE, - ) - if !yaml_emitter_emit(e, &evt) { - return emitterError(e) - } - return nil - } - - switch v.Type() { - case cty.String: - str := v.AsString() - style := yaml_DOUBLE_QUOTED_SCALAR_STYLE - if strings.Contains(str, "\n") { - style = yaml_LITERAL_SCALAR_STYLE - } - yaml_scalar_event_initialize( - &evt, - nil, - nil, - []byte(str), - true, - true, - style, - ) - case cty.Number: - str := v.AsBigFloat().Text('f', -1) - yaml_scalar_event_initialize( - &evt, - nil, - nil, - []byte(str), - true, - true, - yaml_PLAIN_SCALAR_STYLE, - ) - case cty.Bool: - var str string - switch v { - case cty.True: - str = "true" - case cty.False: - str = "false" - } - yaml_scalar_event_initialize( - &evt, - nil, - nil, - []byte(str), - true, - true, - yaml_PLAIN_SCALAR_STYLE, - ) - } - if !yaml_emitter_emit(e, &evt) { - return emitterError(e) - } - return nil -} - -func (c *Converter) marshalSequence(v cty.Value, e *yaml_emitter_t) error { - style := yaml_BLOCK_SEQUENCE_STYLE - if c.encodeAsFlow { - style = yaml_FLOW_SEQUENCE_STYLE - } - - var evt yaml_event_t - yaml_sequence_start_event_initialize(&evt, nil, nil, true, style) - if !yaml_emitter_emit(e, &evt) { - return emitterError(e) - } - - for it := v.ElementIterator(); it.Next(); { - _, v := it.Element() - err := c.marshalEmit(v, e) - if err != nil { - return err - } - } - - yaml_sequence_end_event_initialize(&evt) - if !yaml_emitter_emit(e, &evt) { - return emitterError(e) - } - return nil -} - -func (c *Converter) marshalMapping(v cty.Value, e *yaml_emitter_t) error { - style := yaml_BLOCK_MAPPING_STYLE - if c.encodeAsFlow { - style = yaml_FLOW_MAPPING_STYLE - } - - var evt yaml_event_t - yaml_mapping_start_event_initialize(&evt, nil, nil, true, style) - if !yaml_emitter_emit(e, &evt) { - return emitterError(e) - } - - for it := v.ElementIterator(); it.Next(); { - k, v := it.Element() - err := c.marshalEmit(k, e) - if err != nil { - return err - } - err = c.marshalEmit(v, e) - if err != nil { - return err - } - } - - yaml_mapping_end_event_initialize(&evt) - if !yaml_emitter_emit(e, &evt) { - return emitterError(e) - } - return nil -} diff --git a/vendor/github.com/zclconf/go-cty-yaml/error.go b/vendor/github.com/zclconf/go-cty-yaml/error.go deleted file mode 100644 index ae41c488f87..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/error.go +++ /dev/null @@ -1,97 +0,0 @@ -package yaml - -import ( - "errors" - "fmt" -) - -// Error is an error implementation used to report errors that correspond to -// a particular position in an input buffer. -type Error struct { - cause error - Line, Column int -} - -func (e Error) Error() string { - return fmt.Sprintf("on line %d, column %d: %s", e.Line, e.Column, e.cause.Error()) -} - -// Cause is an implementation of the interface used by -// github.com/pkg/errors.Cause, returning the underlying error without the -// position information. -func (e Error) Cause() error { - return e.cause -} - -// WrappedErrors is an implementation of github.com/hashicorp/errwrap.Wrapper -// returning the underlying error without the position information. -func (e Error) WrappedErrors() []error { - return []error{e.cause} -} - -func parserError(p *yaml_parser_t) error { - var cause error - if len(p.problem) > 0 { - cause = errors.New(p.problem) - } else { - cause = errors.New("invalid YAML syntax") // useless generic error, then - } - - return parserErrorWrap(p, cause) -} - -func parserErrorWrap(p *yaml_parser_t, cause error) error { - switch { - case p.problem_mark.line != 0: - line := p.problem_mark.line - column := p.problem_mark.column - // Scanner errors don't iterate line before returning error - if p.error == yaml_SCANNER_ERROR { - line++ - column = 0 - } - return Error{ - cause: cause, - Line: line, - Column: column + 1, - } - case p.context_mark.line != 0: - return Error{ - cause: cause, - Line: p.context_mark.line, - Column: p.context_mark.column + 1, - } - default: - return cause - } -} - -func parserErrorf(p *yaml_parser_t, f string, vals ...interface{}) error { - return parserErrorWrap(p, fmt.Errorf(f, vals...)) -} - -func parseEventErrorWrap(evt *yaml_event_t, cause error) error { - if evt.start_mark.line == 0 { - // Event does not have a start mark, so we won't wrap the error at all - return cause - } - return Error{ - cause: cause, - Line: evt.start_mark.line, - Column: evt.start_mark.column + 1, - } -} - -func parseEventErrorf(evt *yaml_event_t, f string, vals ...interface{}) error { - return parseEventErrorWrap(evt, fmt.Errorf(f, vals...)) -} - -func emitterError(e *yaml_emitter_t) error { - var cause error - if len(e.problem) > 0 { - cause = errors.New(e.problem) - } else { - cause = errors.New("failed to write YAML token") // useless generic error, then - } - return cause -} diff --git a/vendor/github.com/zclconf/go-cty-yaml/go.mod b/vendor/github.com/zclconf/go-cty-yaml/go.mod deleted file mode 100644 index 3d522687196..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/zclconf/go-cty-yaml - -require github.com/zclconf/go-cty v1.0.0 diff --git a/vendor/github.com/zclconf/go-cty-yaml/go.sum b/vendor/github.com/zclconf/go-cty-yaml/go.sum deleted file mode 100644 index 841f7fcfe3c..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/go.sum +++ /dev/null @@ -1,18 +0,0 @@ -github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= -github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= -github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= -github.com/zclconf/go-cty v1.0.0 h1:EWtv3gKe2wPLIB9hQRQJa7k/059oIfAqcEkCNnaVckk= -github.com/zclconf/go-cty v1.0.0/go.mod h1:xnAOWiHeOqg2nWS62VtQ7pbOu17FtxJNW8RLEih+O3s= -golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/vendor/github.com/zclconf/go-cty-yaml/implied_type.go b/vendor/github.com/zclconf/go-cty-yaml/implied_type.go deleted file mode 100644 index 5b7b0686fab..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/implied_type.go +++ /dev/null @@ -1,268 +0,0 @@ -package yaml - -import ( - "errors" - "fmt" - - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -func (c *Converter) impliedType(src []byte) (cty.Type, error) { - p := &yaml_parser_t{} - if !yaml_parser_initialize(p) { - return cty.NilType, errors.New("failed to initialize YAML parser") - } - if len(src) == 0 { - src = []byte{'\n'} - } - - an := &typeAnalysis{ - anchorsPending: map[string]int{}, - anchorTypes: map[string]cty.Type{}, - } - - yaml_parser_set_input_string(p, src) - - var evt yaml_event_t - if !yaml_parser_parse(p, &evt) { - return cty.NilType, parserError(p) - } - if evt.typ != yaml_STREAM_START_EVENT { - return cty.NilType, parseEventErrorf(&evt, "missing stream start token") - } - if !yaml_parser_parse(p, &evt) { - return cty.NilType, parserError(p) - } - if evt.typ != yaml_DOCUMENT_START_EVENT { - return cty.NilType, parseEventErrorf(&evt, "missing start of document") - } - - ty, err := c.impliedTypeParse(an, p) - if err != nil { - return cty.NilType, err - } - - if !yaml_parser_parse(p, &evt) { - return cty.NilType, parserError(p) - } - if evt.typ == yaml_DOCUMENT_START_EVENT { - return cty.NilType, parseEventErrorf(&evt, "only a single document is allowed") - } - if evt.typ != yaml_DOCUMENT_END_EVENT { - return cty.NilType, parseEventErrorf(&evt, "unexpected extra content (%s) after value", evt.typ.String()) - } - if !yaml_parser_parse(p, &evt) { - return cty.NilType, parserError(p) - } - if evt.typ != yaml_STREAM_END_EVENT { - return cty.NilType, parseEventErrorf(&evt, "unexpected extra content after value") - } - - return ty, err -} - -func (c *Converter) impliedTypeParse(an *typeAnalysis, p *yaml_parser_t) (cty.Type, error) { - var evt yaml_event_t - if !yaml_parser_parse(p, &evt) { - return cty.NilType, parserError(p) - } - return c.impliedTypeParseRemainder(an, &evt, p) -} - -func (c *Converter) impliedTypeParseRemainder(an *typeAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Type, error) { - switch evt.typ { - case yaml_SCALAR_EVENT: - return c.impliedTypeScalar(an, evt, p) - case yaml_ALIAS_EVENT: - return c.impliedTypeAlias(an, evt, p) - case yaml_MAPPING_START_EVENT: - return c.impliedTypeMapping(an, evt, p) - case yaml_SEQUENCE_START_EVENT: - return c.impliedTypeSequence(an, evt, p) - case yaml_DOCUMENT_START_EVENT: - return cty.NilType, parseEventErrorf(evt, "only a single document is allowed") - case yaml_STREAM_END_EVENT: - // Decoding an empty buffer, probably - return cty.NilType, parseEventErrorf(evt, "expecting value but found end of stream") - default: - // Should never happen; the above should be comprehensive - return cty.NilType, parseEventErrorf(evt, "unexpected parser event %s", evt.typ.String()) - } -} - -func (c *Converter) impliedTypeScalar(an *typeAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Type, error) { - src := evt.value - tag := string(evt.tag) - anchor := string(evt.anchor) - implicit := evt.implicit - - if len(anchor) > 0 { - an.beginAnchor(anchor) - } - - var ty cty.Type - switch { - case tag == "" && !implicit: - // Untagged explicit string - ty = cty.String - default: - v, err := c.resolveScalar(tag, string(src), yaml_scalar_style_t(evt.style)) - if err != nil { - return cty.NilType, parseEventErrorWrap(evt, err) - } - if v.RawEquals(mergeMappingVal) { - // In any context other than a mapping key, this is just a plain string - ty = cty.String - } else { - ty = v.Type() - } - } - - if len(anchor) > 0 { - an.completeAnchor(anchor, ty) - } - return ty, nil -} - -func (c *Converter) impliedTypeMapping(an *typeAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Type, error) { - tag := string(evt.tag) - anchor := string(evt.anchor) - - if tag != "" && tag != yaml_MAP_TAG { - return cty.NilType, parseEventErrorf(evt, "can't interpret mapping as %s", tag) - } - - if anchor != "" { - an.beginAnchor(anchor) - } - - atys := make(map[string]cty.Type) - for { - var nextEvt yaml_event_t - if !yaml_parser_parse(p, &nextEvt) { - return cty.NilType, parserError(p) - } - if nextEvt.typ == yaml_MAPPING_END_EVENT { - ty := cty.Object(atys) - if anchor != "" { - an.completeAnchor(anchor, ty) - } - return ty, nil - } - - if nextEvt.typ != yaml_SCALAR_EVENT { - return cty.NilType, parseEventErrorf(&nextEvt, "only strings are allowed as mapping keys") - } - keyVal, err := c.resolveScalar(string(nextEvt.tag), string(nextEvt.value), yaml_scalar_style_t(nextEvt.style)) - if err != nil { - return cty.NilType, err - } - if keyVal.RawEquals(mergeMappingVal) { - // Merging the value (which must be a mapping) into our mapping, - // then. - ty, err := c.impliedTypeParse(an, p) - if err != nil { - return cty.NilType, err - } - if !ty.IsObjectType() { - return cty.NilType, parseEventErrorf(&nextEvt, "cannot merge %s into mapping", ty.FriendlyName()) - } - for name, aty := range ty.AttributeTypes() { - atys[name] = aty - } - continue - } - if keyValStr, err := convert.Convert(keyVal, cty.String); err == nil { - keyVal = keyValStr - } else { - return cty.NilType, parseEventErrorf(&nextEvt, "only strings are allowed as mapping keys") - } - if keyVal.IsNull() { - return cty.NilType, parseEventErrorf(&nextEvt, "mapping key cannot be null") - } - if !keyVal.IsKnown() { - return cty.NilType, parseEventErrorf(&nextEvt, "mapping key must be known") - } - valTy, err := c.impliedTypeParse(an, p) - if err != nil { - return cty.NilType, err - } - - atys[keyVal.AsString()] = valTy - } -} - -func (c *Converter) impliedTypeSequence(an *typeAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Type, error) { - tag := string(evt.tag) - anchor := string(evt.anchor) - - if tag != "" && tag != yaml_SEQ_TAG { - return cty.NilType, parseEventErrorf(evt, "can't interpret sequence as %s", tag) - } - - if anchor != "" { - an.beginAnchor(anchor) - } - - var atys []cty.Type - for { - var nextEvt yaml_event_t - if !yaml_parser_parse(p, &nextEvt) { - return cty.NilType, parserError(p) - } - if nextEvt.typ == yaml_SEQUENCE_END_EVENT { - ty := cty.Tuple(atys) - if anchor != "" { - an.completeAnchor(anchor, ty) - } - return ty, nil - } - - valTy, err := c.impliedTypeParseRemainder(an, &nextEvt, p) - if err != nil { - return cty.NilType, err - } - - atys = append(atys, valTy) - } -} - -func (c *Converter) impliedTypeAlias(an *typeAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Type, error) { - ty, err := an.anchorType(string(evt.anchor)) - if err != nil { - err = parseEventErrorWrap(evt, err) - } - return ty, err -} - -type typeAnalysis struct { - anchorsPending map[string]int - anchorTypes map[string]cty.Type -} - -func (an *typeAnalysis) beginAnchor(name string) { - an.anchorsPending[name]++ -} - -func (an *typeAnalysis) completeAnchor(name string, ty cty.Type) { - an.anchorsPending[name]-- - if an.anchorsPending[name] == 0 { - delete(an.anchorsPending, name) - } - an.anchorTypes[name] = ty -} - -func (an *typeAnalysis) anchorType(name string) (cty.Type, error) { - if _, pending := an.anchorsPending[name]; pending { - // YAML normally allows self-referencing structures, but cty cannot - // represent them (it requires all structures to be finite) so we - // must fail here. - return cty.NilType, fmt.Errorf("cannot refer to anchor %q from inside its own definition", name) - } - ty, ok := an.anchorTypes[name] - if !ok { - return cty.NilType, fmt.Errorf("reference to undefined anchor %q", name) - } - return ty, nil -} diff --git a/vendor/github.com/zclconf/go-cty-yaml/resolve.go b/vendor/github.com/zclconf/go-cty-yaml/resolve.go deleted file mode 100644 index 0f643834285..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/resolve.go +++ /dev/null @@ -1,288 +0,0 @@ -package yaml - -import ( - "encoding/base64" - "fmt" - "reflect" - "regexp" - "strconv" - "strings" - "time" - - "github.com/zclconf/go-cty/cty" -) - -type resolveMapItem struct { - value cty.Value - tag string -} - -var resolveTable = make([]byte, 256) -var resolveMap = make(map[string]resolveMapItem) - -func init() { - t := resolveTable - t[int('+')] = 'S' // Sign - t[int('-')] = 'S' - for _, c := range "0123456789" { - t[int(c)] = 'D' // Digit - } - for _, c := range "yYnNtTfFoO~" { - t[int(c)] = 'M' // In map - } - t[int('.')] = '.' // Float (potentially in map) - - var resolveMapList = []struct { - v cty.Value - tag string - l []string - }{ - {cty.True, yaml_BOOL_TAG, []string{"y", "Y", "yes", "Yes", "YES"}}, - {cty.True, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}}, - {cty.True, yaml_BOOL_TAG, []string{"on", "On", "ON"}}, - {cty.False, yaml_BOOL_TAG, []string{"n", "N", "no", "No", "NO"}}, - {cty.False, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}}, - {cty.False, yaml_BOOL_TAG, []string{"off", "Off", "OFF"}}, - {cty.NullVal(cty.DynamicPseudoType), yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}}, - {cty.PositiveInfinity, yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}}, - {cty.PositiveInfinity, yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}}, - {cty.NegativeInfinity, yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}}, - } - - m := resolveMap - for _, item := range resolveMapList { - for _, s := range item.l { - m[s] = resolveMapItem{item.v, item.tag} - } - } -} - -const longTagPrefix = "tag:yaml.org,2002:" - -func shortTag(tag string) string { - // TODO This can easily be made faster and produce less garbage. - if strings.HasPrefix(tag, longTagPrefix) { - return "!!" + tag[len(longTagPrefix):] - } - return tag -} - -func longTag(tag string) string { - if strings.HasPrefix(tag, "!!") { - return longTagPrefix + tag[2:] - } - return tag -} - -func resolvableTag(tag string) bool { - switch tag { - case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG, yaml_TIMESTAMP_TAG, yaml_BINARY_TAG: - return true - } - return false -} - -var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) - -func (c *Converter) resolveScalar(tag string, src string, style yaml_scalar_style_t) (cty.Value, error) { - if !resolvableTag(tag) { - return cty.NilVal, fmt.Errorf("unsupported tag %q", tag) - } - - // Any data is accepted as a !!str or !!binary. - // Otherwise, the prefix is enough of a hint about what it might be. - hint := byte('N') - if src != "" { - hint = resolveTable[src[0]] - } - if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG { - if style == yaml_SINGLE_QUOTED_SCALAR_STYLE || style == yaml_DOUBLE_QUOTED_SCALAR_STYLE { - return cty.StringVal(src), nil - } - - // Handle things we can lookup in a map. - if item, ok := resolveMap[src]; ok { - return item.value, nil - } - - if tag == "" { - for _, nan := range []string{".nan", ".NaN", ".NAN"} { - if src == nan { - // cty cannot represent NaN, so this is an error - return cty.NilVal, fmt.Errorf("floating point NaN is not supported") - } - } - } - - // Base 60 floats are intentionally not supported. - - switch hint { - case 'M': - // We've already checked the map above. - - case '.': - // Not in the map, so maybe a normal float. - if numberVal, err := cty.ParseNumberVal(src); err == nil { - return numberVal, nil - } - - case 'D', 'S': - // Int, float, or timestamp. - // Only try values as a timestamp if the value is unquoted or there's an explicit - // !!timestamp tag. - if tag == "" || tag == yaml_TIMESTAMP_TAG { - t, ok := parseTimestamp(src) - if ok { - // cty has no timestamp type, but its functions stdlib - // conventionally uses strings in an RFC3339 encoding - // to represent time, so we'll follow that convention here. - return cty.StringVal(t.Format(time.RFC3339)), nil - } - } - - plain := strings.Replace(src, "_", "", -1) - if numberVal, err := cty.ParseNumberVal(plain); err == nil { - return numberVal, nil - } - if strings.HasPrefix(plain, "0b") || strings.HasPrefix(plain, "-0b") { - tag = yaml_INT_TAG // will handle parsing below in our tag switch - } - default: - panic(fmt.Sprintf("cannot resolve tag %q with source %q", tag, src)) - } - } - - if tag == "" && src == "<<" { - return mergeMappingVal, nil - } - - switch tag { - case yaml_STR_TAG, yaml_BINARY_TAG: - // If it's binary then we want to keep the base64 representation, because - // cty has no binary type, but we will check that it's actually base64. - if tag == yaml_BINARY_TAG { - _, err := base64.StdEncoding.DecodeString(src) - if err != nil { - return cty.NilVal, fmt.Errorf("cannot parse %q as %s: not valid base64", src, tag) - } - } - return cty.StringVal(src), nil - case yaml_BOOL_TAG: - item, ok := resolveMap[src] - if !ok || item.tag != yaml_BOOL_TAG { - return cty.NilVal, fmt.Errorf("cannot parse %q as %s", src, tag) - } - return item.value, nil - case yaml_FLOAT_TAG, yaml_INT_TAG: - // Note: We don't actually check that a value tagged INT is a whole - // number here. We could, but cty generally doesn't care about the - // int/float distinction, so we'll just be generous and accept it. - plain := strings.Replace(src, "_", "", -1) - if numberVal, err := cty.ParseNumberVal(plain); err == nil { // handles decimal integers and floats - return numberVal, nil - } - if intv, err := strconv.ParseInt(plain, 0, 64); err == nil { // handles 0x and 00 prefixes - return cty.NumberIntVal(intv), nil - } - if uintv, err := strconv.ParseUint(plain, 0, 64); err == nil { // handles 0x and 00 prefixes - return cty.NumberUIntVal(uintv), nil - } - if strings.HasPrefix(plain, "0b") { - intv, err := strconv.ParseInt(plain[2:], 2, 64) - if err == nil { - return cty.NumberIntVal(intv), nil - } - uintv, err := strconv.ParseUint(plain[2:], 2, 64) - if err == nil { - return cty.NumberUIntVal(uintv), nil - } - } else if strings.HasPrefix(plain, "-0b") { - intv, err := strconv.ParseInt("-"+plain[3:], 2, 64) - if err == nil { - return cty.NumberIntVal(intv), nil - } - } - return cty.NilVal, fmt.Errorf("cannot parse %q as %s", src, tag) - case yaml_TIMESTAMP_TAG: - t, ok := parseTimestamp(src) - if ok { - // cty has no timestamp type, but its functions stdlib - // conventionally uses strings in an RFC3339 encoding - // to represent time, so we'll follow that convention here. - return cty.StringVal(t.Format(time.RFC3339)), nil - } - return cty.NilVal, fmt.Errorf("cannot parse %q as %s", src, tag) - case yaml_NULL_TAG: - return cty.NullVal(cty.DynamicPseudoType), nil - case "": - return cty.StringVal(src), nil - default: - return cty.NilVal, fmt.Errorf("unsupported tag %q", tag) - } -} - -// encodeBase64 encodes s as base64 that is broken up into multiple lines -// as appropriate for the resulting length. -func encodeBase64(s string) string { - const lineLen = 70 - encLen := base64.StdEncoding.EncodedLen(len(s)) - lines := encLen/lineLen + 1 - buf := make([]byte, encLen*2+lines) - in := buf[0:encLen] - out := buf[encLen:] - base64.StdEncoding.Encode(in, []byte(s)) - k := 0 - for i := 0; i < len(in); i += lineLen { - j := i + lineLen - if j > len(in) { - j = len(in) - } - k += copy(out[k:], in[i:j]) - if lines > 1 { - out[k] = '\n' - k++ - } - } - return string(out[:k]) -} - -// This is a subset of the formats allowed by the regular expression -// defined at http://yaml.org/type/timestamp.html. -var allowedTimestampFormats = []string{ - "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. - "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". - "2006-1-2 15:4:5.999999999", // space separated with no time zone - "2006-1-2", // date only - // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" - // from the set of examples. -} - -// parseTimestamp parses s as a timestamp string and -// returns the timestamp and reports whether it succeeded. -// Timestamp formats are defined at http://yaml.org/type/timestamp.html -func parseTimestamp(s string) (time.Time, bool) { - // TODO write code to check all the formats supported by - // http://yaml.org/type/timestamp.html instead of using time.Parse. - - // Quick check: all date formats start with YYYY-. - i := 0 - for ; i < len(s); i++ { - if c := s[i]; c < '0' || c > '9' { - break - } - } - if i != 4 || i == len(s) || s[i] != '-' { - return time.Time{}, false - } - for _, format := range allowedTimestampFormats { - if t, err := time.Parse(format, s); err == nil { - return t, true - } - } - return time.Time{}, false -} - -type mergeMapping struct{} - -var mergeMappingTy = cty.Capsule("merge mapping", reflect.TypeOf(mergeMapping{})) -var mergeMappingVal = cty.CapsuleVal(mergeMappingTy, &mergeMapping{}) diff --git a/vendor/github.com/zclconf/go-cty-yaml/writerc.go b/vendor/github.com/zclconf/go-cty-yaml/writerc.go deleted file mode 100644 index a2dde608cb7..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/writerc.go +++ /dev/null @@ -1,26 +0,0 @@ -package yaml - -// Set the writer error and return false. -func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { - emitter.error = yaml_WRITER_ERROR - emitter.problem = problem - return false -} - -// Flush the output buffer. -func yaml_emitter_flush(emitter *yaml_emitter_t) bool { - if emitter.write_handler == nil { - panic("write handler not set") - } - - // Check if the buffer is empty. - if emitter.buffer_pos == 0 { - return true - } - - if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { - return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) - } - emitter.buffer_pos = 0 - return true -} diff --git a/vendor/github.com/zclconf/go-cty-yaml/yaml.go b/vendor/github.com/zclconf/go-cty-yaml/yaml.go deleted file mode 100644 index 2c314cc1646..00000000000 --- a/vendor/github.com/zclconf/go-cty-yaml/yaml.go +++ /dev/null @@ -1,215 +0,0 @@ -// Package yaml can marshal and unmarshal cty values in YAML format. -package yaml - -import ( - "errors" - "fmt" - "reflect" - "strings" - "sync" - - "github.com/zclconf/go-cty/cty" -) - -// Unmarshal reads the document found within the given source buffer -// and attempts to convert it into a value conforming to the given type -// constraint. -// -// This is an alias for Unmarshal on the predefined Converter in "Standard". -// -// An error is returned if the given source contains any YAML document -// delimiters. -func Unmarshal(src []byte, ty cty.Type) (cty.Value, error) { - return Standard.Unmarshal(src, ty) -} - -// Marshal serializes the given value into a YAML document, using a fixed -// mapping from cty types to YAML constructs. -// -// This is an alias for Marshal on the predefined Converter in "Standard". -// -// Note that unlike the function of the same name in the cty JSON package, -// this does not take a type constraint and therefore the YAML serialization -// cannot preserve late-bound type information in the serialization to be -// recovered from Unmarshal. Instead, any cty.DynamicPseudoType in the type -// constraint given to Unmarshal will be decoded as if the corresponding portion -// of the input were processed with ImpliedType to find a target type. -func Marshal(v cty.Value) ([]byte, error) { - return Standard.Marshal(v) -} - -// ImpliedType analyzes the given source code and returns a suitable type that -// it could be decoded into. -// -// For a converter that is using standard YAML rather than cty-specific custom -// tags, only a subset of cty types can be produced: strings, numbers, bools, -// tuple types, and object types. -// -// This is an alias for ImpliedType on the predefined Converter in "Standard". -func ImpliedType(src []byte) (cty.Type, error) { - return Standard.ImpliedType(src) -} - -func handleErr(err *error) { - if v := recover(); v != nil { - if e, ok := v.(yamlError); ok { - *err = e.err - } else { - panic(v) - } - } -} - -type yamlError struct { - err error -} - -func fail(err error) { - panic(yamlError{err}) -} - -func failf(format string, args ...interface{}) { - panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) -} - -// -------------------------------------------------------------------------- -// Maintain a mapping of keys to structure field indexes - -// The code in this section was copied from mgo/bson. - -// structInfo holds details for the serialization of fields of -// a given struct. -type structInfo struct { - FieldsMap map[string]fieldInfo - FieldsList []fieldInfo - - // InlineMap is the number of the field in the struct that - // contains an ,inline map, or -1 if there's none. - InlineMap int -} - -type fieldInfo struct { - Key string - Num int - OmitEmpty bool - Flow bool - // Id holds the unique field identifier, so we can cheaply - // check for field duplicates without maintaining an extra map. - Id int - - // Inline holds the field index if the field is part of an inlined struct. - Inline []int -} - -var structMap = make(map[reflect.Type]*structInfo) -var fieldMapMutex sync.RWMutex - -func getStructInfo(st reflect.Type) (*structInfo, error) { - fieldMapMutex.RLock() - sinfo, found := structMap[st] - fieldMapMutex.RUnlock() - if found { - return sinfo, nil - } - - n := st.NumField() - fieldsMap := make(map[string]fieldInfo) - fieldsList := make([]fieldInfo, 0, n) - inlineMap := -1 - for i := 0; i != n; i++ { - field := st.Field(i) - if field.PkgPath != "" && !field.Anonymous { - continue // Private field - } - - info := fieldInfo{Num: i} - - tag := field.Tag.Get("yaml") - if tag == "" && strings.Index(string(field.Tag), ":") < 0 { - tag = string(field.Tag) - } - if tag == "-" { - continue - } - - inline := false - fields := strings.Split(tag, ",") - if len(fields) > 1 { - for _, flag := range fields[1:] { - switch flag { - case "omitempty": - info.OmitEmpty = true - case "flow": - info.Flow = true - case "inline": - inline = true - default: - return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st)) - } - } - tag = fields[0] - } - - if inline { - switch field.Type.Kind() { - case reflect.Map: - if inlineMap >= 0 { - return nil, errors.New("Multiple ,inline maps in struct " + st.String()) - } - if field.Type.Key() != reflect.TypeOf("") { - return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String()) - } - inlineMap = info.Num - case reflect.Struct: - sinfo, err := getStructInfo(field.Type) - if err != nil { - return nil, err - } - for _, finfo := range sinfo.FieldsList { - if _, found := fieldsMap[finfo.Key]; found { - msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - if finfo.Inline == nil { - finfo.Inline = []int{i, finfo.Num} - } else { - finfo.Inline = append([]int{i}, finfo.Inline...) - } - finfo.Id = len(fieldsList) - fieldsMap[finfo.Key] = finfo - fieldsList = append(fieldsList, finfo) - } - default: - //return nil, errors.New("Option ,inline needs a struct value or map field") - return nil, errors.New("Option ,inline needs a struct value field") - } - continue - } - - if tag != "" { - info.Key = tag - } else { - info.Key = strings.ToLower(field.Name) - } - - if _, found = fieldsMap[info.Key]; found { - msg := "Duplicated key '" + info.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - - info.Id = len(fieldsList) - fieldsList = append(fieldsList, info) - fieldsMap[info.Key] = info - } - - sinfo = &structInfo{ - FieldsMap: fieldsMap, - FieldsList: fieldsList, - InlineMap: inlineMap, - } - - fieldMapMutex.Lock() - structMap[st] = sinfo - fieldMapMutex.Unlock() - return sinfo, nil -} diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/marshal.go b/vendor/github.com/zclconf/go-cty/cty/msgpack/marshal.go deleted file mode 100644 index 51c75aa8d32..00000000000 --- a/vendor/github.com/zclconf/go-cty/cty/msgpack/marshal.go +++ /dev/null @@ -1,211 +0,0 @@ -package msgpack - -import ( - "bytes" - "math/big" - "sort" - - "github.com/vmihailenco/msgpack" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" -) - -// Marshal produces a msgpack serialization of the given value that -// can be decoded into the given type later using Unmarshal. -// -// The given value must conform to the given type, or an error will -// be returned. -func Marshal(val cty.Value, ty cty.Type) ([]byte, error) { - errs := val.Type().TestConformance(ty) - if errs != nil { - // Attempt a conversion - var err error - val, err = convert.Convert(val, ty) - if err != nil { - return nil, err - } - } - - // From this point onward, val can be assumed to be conforming to t. - - var path cty.Path - var buf bytes.Buffer - enc := msgpack.NewEncoder(&buf) - - err := marshal(val, ty, path, enc) - if err != nil { - return nil, err - } - - return buf.Bytes(), nil -} - -func marshal(val cty.Value, ty cty.Type, path cty.Path, enc *msgpack.Encoder) error { - if val.IsMarked() { - return path.NewErrorf("value has marks, so it cannot be seralized") - } - - // If we're going to decode as DynamicPseudoType then we need to save - // dynamic type information to recover the real type. - if ty == cty.DynamicPseudoType && val.Type() != cty.DynamicPseudoType { - return marshalDynamic(val, path, enc) - } - - if !val.IsKnown() { - err := enc.Encode(unknownVal) - if err != nil { - return path.NewError(err) - } - return nil - } - if val.IsNull() { - err := enc.EncodeNil() - if err != nil { - return path.NewError(err) - } - return nil - } - - // The caller should've guaranteed that the given val is conformant with - // the given type ty, so we'll proceed under that assumption here. - switch { - case ty.IsPrimitiveType(): - switch ty { - case cty.String: - err := enc.EncodeString(val.AsString()) - if err != nil { - return path.NewError(err) - } - return nil - case cty.Number: - var err error - switch { - case val.RawEquals(cty.PositiveInfinity): - err = enc.EncodeFloat64(positiveInfinity) - case val.RawEquals(cty.NegativeInfinity): - err = enc.EncodeFloat64(negativeInfinity) - default: - bf := val.AsBigFloat() - if iv, acc := bf.Int64(); acc == big.Exact { - err = enc.EncodeInt(iv) - } else if fv, acc := bf.Float64(); acc == big.Exact { - err = enc.EncodeFloat64(fv) - } else { - err = enc.EncodeString(bf.Text('f', -1)) - } - } - if err != nil { - return path.NewError(err) - } - return nil - case cty.Bool: - err := enc.EncodeBool(val.True()) - if err != nil { - return path.NewError(err) - } - return nil - default: - panic("unsupported primitive type") - } - case ty.IsListType(), ty.IsSetType(): - enc.EncodeArrayLen(val.LengthInt()) - ety := ty.ElementType() - it := val.ElementIterator() - path := append(path, nil) // local override of 'path' with extra element - for it.Next() { - ek, ev := it.Element() - path[len(path)-1] = cty.IndexStep{ - Key: ek, - } - err := marshal(ev, ety, path, enc) - if err != nil { - return err - } - } - return nil - case ty.IsMapType(): - enc.EncodeMapLen(val.LengthInt()) - ety := ty.ElementType() - it := val.ElementIterator() - path := append(path, nil) // local override of 'path' with extra element - for it.Next() { - ek, ev := it.Element() - path[len(path)-1] = cty.IndexStep{ - Key: ek, - } - var err error - err = marshal(ek, ek.Type(), path, enc) - if err != nil { - return err - } - err = marshal(ev, ety, path, enc) - if err != nil { - return err - } - } - return nil - case ty.IsTupleType(): - etys := ty.TupleElementTypes() - it := val.ElementIterator() - path := append(path, nil) // local override of 'path' with extra element - i := 0 - enc.EncodeArrayLen(len(etys)) - for it.Next() { - ety := etys[i] - ek, ev := it.Element() - path[len(path)-1] = cty.IndexStep{ - Key: ek, - } - err := marshal(ev, ety, path, enc) - if err != nil { - return err - } - i++ - } - return nil - case ty.IsObjectType(): - atys := ty.AttributeTypes() - path := append(path, nil) // local override of 'path' with extra element - - names := make([]string, 0, len(atys)) - for k := range atys { - names = append(names, k) - } - sort.Strings(names) - - enc.EncodeMapLen(len(names)) - - for _, k := range names { - aty := atys[k] - av := val.GetAttr(k) - path[len(path)-1] = cty.GetAttrStep{ - Name: k, - } - var err error - err = marshal(cty.StringVal(k), cty.String, path, enc) - if err != nil { - return err - } - err = marshal(av, aty, path, enc) - if err != nil { - return err - } - } - return nil - case ty.IsCapsuleType(): - return path.NewErrorf("capsule types not supported for msgpack encoding") - default: - // should never happen - return path.NewErrorf("cannot msgpack-serialize %s", ty.FriendlyName()) - } -} - -// marshalDynamic adds an extra wrapping object containing dynamic type -// information for the given value. -func marshalDynamic(val cty.Value, path cty.Path, enc *msgpack.Encoder) error { - dv := dynamicVal{ - Value: val, - Path: path, - } - return enc.Encode(&dv) -} diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/type_implied.go b/vendor/github.com/zclconf/go-cty/cty/msgpack/type_implied.go deleted file mode 100644 index 6f6022e4d5b..00000000000 --- a/vendor/github.com/zclconf/go-cty/cty/msgpack/type_implied.go +++ /dev/null @@ -1,167 +0,0 @@ -package msgpack - -import ( - "bytes" - "fmt" - "io" - - "github.com/vmihailenco/msgpack" - msgpackcodes "github.com/vmihailenco/msgpack/codes" - "github.com/zclconf/go-cty/cty" -) - -// ImpliedType returns the cty Type implied by the structure of the given -// msgpack-compliant buffer. This function implements the default type mapping -// behavior used when decoding arbitrary msgpack without explicit cty Type -// information. -// -// The rules are as follows: -// -// msgpack strings, numbers and bools map to their equivalent primitive type in -// cty. -// -// msgpack maps become cty object types, with the attributes defined by the -// map keys and the types of their values. -// -// msgpack arrays become cty tuple types, with the elements defined by the -// types of the array members. -// -// Any nulls are typed as DynamicPseudoType, so callers of this function -// must be prepared to deal with this. Callers that do not wish to deal with -// dynamic typing should not use this function and should instead describe -// their required types explicitly with a cty.Type instance when decoding. -// -// Any unknown values are similarly typed as DynamicPseudoType, because these -// do not carry type information on the wire. -// -// Any parse errors will be returned as an error, and the type will be the -// invalid value cty.NilType. -func ImpliedType(buf []byte) (cty.Type, error) { - r := bytes.NewReader(buf) - dec := msgpack.NewDecoder(r) - - ty, err := impliedType(dec) - if err != nil { - return cty.NilType, err - } - - // We must now be at the end of the buffer - err = dec.Skip() - if err != io.EOF { - return ty, fmt.Errorf("extra bytes after msgpack value") - } - - return ty, nil -} - -func impliedType(dec *msgpack.Decoder) (cty.Type, error) { - // If this function returns with a nil error then it must have already - // consumed the next value from the decoder, since when called recursively - // the caller will be expecting to find a following value here. - - code, err := dec.PeekCode() - if err != nil { - return cty.NilType, err - } - - switch { - - case code == msgpackcodes.Nil || msgpackcodes.IsExt(code): - err := dec.Skip() - return cty.DynamicPseudoType, err - - case code == msgpackcodes.True || code == msgpackcodes.False: - _, err := dec.DecodeBool() - return cty.Bool, err - - case msgpackcodes.IsFixedNum(code): - _, err := dec.DecodeInt64() - return cty.Number, err - - case code == msgpackcodes.Int8 || code == msgpackcodes.Int16 || code == msgpackcodes.Int32 || code == msgpackcodes.Int64: - _, err := dec.DecodeInt64() - return cty.Number, err - - case code == msgpackcodes.Uint8 || code == msgpackcodes.Uint16 || code == msgpackcodes.Uint32 || code == msgpackcodes.Uint64: - _, err := dec.DecodeUint64() - return cty.Number, err - - case code == msgpackcodes.Float || code == msgpackcodes.Double: - _, err := dec.DecodeFloat64() - return cty.Number, err - - case msgpackcodes.IsString(code): - _, err := dec.DecodeString() - return cty.String, err - - case msgpackcodes.IsFixedMap(code) || code == msgpackcodes.Map16 || code == msgpackcodes.Map32: - return impliedObjectType(dec) - - case msgpackcodes.IsFixedArray(code) || code == msgpackcodes.Array16 || code == msgpackcodes.Array32: - return impliedTupleType(dec) - - default: - return cty.NilType, fmt.Errorf("unsupported msgpack code %#v", code) - } -} - -func impliedObjectType(dec *msgpack.Decoder) (cty.Type, error) { - // If we get in here then we've already peeked the next code and know - // it's some sort of map. - l, err := dec.DecodeMapLen() - if err != nil { - return cty.DynamicPseudoType, nil - } - - var atys map[string]cty.Type - - for i := 0; i < l; i++ { - // Read the map key first. We require maps to be strings, but msgpack - // doesn't so we're prepared to error here if not. - k, err := dec.DecodeString() - if err != nil { - return cty.DynamicPseudoType, err - } - - aty, err := impliedType(dec) - if err != nil { - return cty.DynamicPseudoType, err - } - - if atys == nil { - atys = make(map[string]cty.Type) - } - atys[k] = aty - } - - if len(atys) == 0 { - return cty.EmptyObject, nil - } - - return cty.Object(atys), nil -} - -func impliedTupleType(dec *msgpack.Decoder) (cty.Type, error) { - // If we get in here then we've already peeked the next code and know - // it's some sort of array. - l, err := dec.DecodeArrayLen() - if err != nil { - return cty.DynamicPseudoType, nil - } - - if l == 0 { - return cty.EmptyTuple, nil - } - - etys := make([]cty.Type, l) - - for i := 0; i < l; i++ { - ety, err := impliedType(dec) - if err != nil { - return cty.DynamicPseudoType, err - } - etys[i] = ety - } - - return cty.Tuple(etys), nil -} diff --git a/vendor/github.com/zclconf/go-cty/cty/msgpack/unmarshal.go b/vendor/github.com/zclconf/go-cty/cty/msgpack/unmarshal.go deleted file mode 100644 index 51bb76a8a78..00000000000 --- a/vendor/github.com/zclconf/go-cty/cty/msgpack/unmarshal.go +++ /dev/null @@ -1,334 +0,0 @@ -package msgpack - -import ( - "bytes" - - "github.com/vmihailenco/msgpack" - msgpackCodes "github.com/vmihailenco/msgpack/codes" - "github.com/zclconf/go-cty/cty" -) - -// Unmarshal interprets the given bytes as a msgpack-encoded cty Value of -// the given type, returning the result. -// -// If an error is returned, the error is written with a hypothetical -// end-user that wrote the msgpack file as its audience, using cty type -// system concepts rather than Go type system concepts. -func Unmarshal(b []byte, ty cty.Type) (cty.Value, error) { - r := bytes.NewReader(b) - dec := msgpack.NewDecoder(r) - - var path cty.Path - return unmarshal(dec, ty, path) -} - -func unmarshal(dec *msgpack.Decoder, ty cty.Type, path cty.Path) (cty.Value, error) { - peek, err := dec.PeekCode() - if err != nil { - return cty.DynamicVal, path.NewError(err) - } - if msgpackCodes.IsExt(peek) { - // We just assume _all_ extensions are unknown values, - // since we don't have any other extensions. - dec.Skip() // skip what we've peeked - return cty.UnknownVal(ty), nil - } - if ty == cty.DynamicPseudoType { - return unmarshalDynamic(dec, path) - } - if peek == msgpackCodes.Nil { - dec.Skip() // skip what we've peeked - return cty.NullVal(ty), nil - } - - switch { - case ty.IsPrimitiveType(): - val, err := unmarshalPrimitive(dec, ty, path) - if err != nil { - return cty.NilVal, err - } - return val, nil - case ty.IsListType(): - return unmarshalList(dec, ty.ElementType(), path) - case ty.IsSetType(): - return unmarshalSet(dec, ty.ElementType(), path) - case ty.IsMapType(): - return unmarshalMap(dec, ty.ElementType(), path) - case ty.IsTupleType(): - return unmarshalTuple(dec, ty.TupleElementTypes(), path) - case ty.IsObjectType(): - return unmarshalObject(dec, ty.AttributeTypes(), path) - default: - return cty.NilVal, path.NewErrorf("unsupported type %s", ty.FriendlyName()) - } -} - -func unmarshalPrimitive(dec *msgpack.Decoder, ty cty.Type, path cty.Path) (cty.Value, error) { - switch ty { - case cty.Bool: - rv, err := dec.DecodeBool() - if err != nil { - return cty.DynamicVal, path.NewErrorf("bool is required") - } - return cty.BoolVal(rv), nil - case cty.Number: - // Marshal will try int and float first, if the value can be - // losslessly represented in these encodings, and then fall - // back on a string if the number is too large or too precise. - peek, err := dec.PeekCode() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - - if msgpackCodes.IsFixedNum(peek) { - rv, err := dec.DecodeInt64() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - return cty.NumberIntVal(rv), nil - } - - switch peek { - case msgpackCodes.Int8, msgpackCodes.Int16, msgpackCodes.Int32, msgpackCodes.Int64: - rv, err := dec.DecodeInt64() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - return cty.NumberIntVal(rv), nil - case msgpackCodes.Uint8, msgpackCodes.Uint16, msgpackCodes.Uint32, msgpackCodes.Uint64: - rv, err := dec.DecodeUint64() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - return cty.NumberUIntVal(rv), nil - case msgpackCodes.Float, msgpackCodes.Double: - rv, err := dec.DecodeFloat64() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - return cty.NumberFloatVal(rv), nil - default: - rv, err := dec.DecodeString() - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - v, err := cty.ParseNumberVal(rv) - if err != nil { - return cty.DynamicVal, path.NewErrorf("number is required") - } - return v, nil - } - case cty.String: - rv, err := dec.DecodeString() - if err != nil { - return cty.DynamicVal, path.NewErrorf("string is required") - } - return cty.StringVal(rv), nil - default: - // should never happen - panic("unsupported primitive type") - } -} - -func unmarshalList(dec *msgpack.Decoder, ety cty.Type, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeArrayLen() - if err != nil { - return cty.DynamicVal, path.NewErrorf("a list is required") - } - - switch { - case length < 0: - return cty.NullVal(cty.List(ety)), nil - case length == 0: - return cty.ListValEmpty(ety), nil - } - - vals := make([]cty.Value, 0, length) - path = append(path, nil) - for i := 0; i < length; i++ { - path[len(path)-1] = cty.IndexStep{ - Key: cty.NumberIntVal(int64(i)), - } - - val, err := unmarshal(dec, ety, path) - if err != nil { - return cty.DynamicVal, err - } - - vals = append(vals, val) - } - - return cty.ListVal(vals), nil -} - -func unmarshalSet(dec *msgpack.Decoder, ety cty.Type, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeArrayLen() - if err != nil { - return cty.DynamicVal, path.NewErrorf("a set is required") - } - - switch { - case length < 0: - return cty.NullVal(cty.Set(ety)), nil - case length == 0: - return cty.SetValEmpty(ety), nil - } - - vals := make([]cty.Value, 0, length) - path = append(path, nil) - for i := 0; i < length; i++ { - path[len(path)-1] = cty.IndexStep{ - Key: cty.NumberIntVal(int64(i)), - } - - val, err := unmarshal(dec, ety, path) - if err != nil { - return cty.DynamicVal, err - } - - vals = append(vals, val) - } - - return cty.SetVal(vals), nil -} - -func unmarshalMap(dec *msgpack.Decoder, ety cty.Type, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeMapLen() - if err != nil { - return cty.DynamicVal, path.NewErrorf("a map is required") - } - - switch { - case length < 0: - return cty.NullVal(cty.Map(ety)), nil - case length == 0: - return cty.MapValEmpty(ety), nil - } - - vals := make(map[string]cty.Value, length) - path = append(path, nil) - for i := 0; i < length; i++ { - key, err := dec.DecodeString() - if err != nil { - path[:len(path)-1].NewErrorf("non-string key in map") - } - - path[len(path)-1] = cty.IndexStep{ - Key: cty.StringVal(key), - } - - val, err := unmarshal(dec, ety, path) - if err != nil { - return cty.DynamicVal, err - } - - vals[key] = val - } - - return cty.MapVal(vals), nil -} - -func unmarshalTuple(dec *msgpack.Decoder, etys []cty.Type, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeArrayLen() - if err != nil { - return cty.DynamicVal, path.NewErrorf("a tuple is required") - } - - switch { - case length < 0: - return cty.NullVal(cty.Tuple(etys)), nil - case length == 0: - return cty.TupleVal(nil), nil - case length != len(etys): - return cty.DynamicVal, path.NewErrorf("a tuple of length %d is required", len(etys)) - } - - vals := make([]cty.Value, 0, length) - path = append(path, nil) - for i := 0; i < length; i++ { - path[len(path)-1] = cty.IndexStep{ - Key: cty.NumberIntVal(int64(i)), - } - ety := etys[i] - - val, err := unmarshal(dec, ety, path) - if err != nil { - return cty.DynamicVal, err - } - - vals = append(vals, val) - } - - return cty.TupleVal(vals), nil -} - -func unmarshalObject(dec *msgpack.Decoder, atys map[string]cty.Type, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeMapLen() - if err != nil { - return cty.DynamicVal, path.NewErrorf("an object is required") - } - - switch { - case length < 0: - return cty.NullVal(cty.Object(atys)), nil - case length == 0: - return cty.ObjectVal(nil), nil - case length != len(atys): - return cty.DynamicVal, path.NewErrorf("an object with %d attributes is required (%d given)", - len(atys), length) - } - - vals := make(map[string]cty.Value, length) - path = append(path, nil) - for i := 0; i < length; i++ { - key, err := dec.DecodeString() - if err != nil { - return cty.DynamicVal, path[:len(path)-1].NewErrorf("all keys must be strings") - } - - path[len(path)-1] = cty.IndexStep{ - Key: cty.StringVal(key), - } - aty, exists := atys[key] - if !exists { - return cty.DynamicVal, path.NewErrorf("unsupported attribute") - } - - val, err := unmarshal(dec, aty, path) - if err != nil { - return cty.DynamicVal, err - } - - vals[key] = val - } - - return cty.ObjectVal(vals), nil -} - -func unmarshalDynamic(dec *msgpack.Decoder, path cty.Path) (cty.Value, error) { - length, err := dec.DecodeArrayLen() - if err != nil { - return cty.DynamicVal, path.NewError(err) - } - - switch { - case length == -1: - return cty.NullVal(cty.DynamicPseudoType), nil - case length != 2: - return cty.DynamicVal, path.NewErrorf( - "dynamic value array must have exactly two elements", - ) - } - - typeJSON, err := dec.DecodeBytes() - if err != nil { - return cty.DynamicVal, path.NewError(err) - } - var ty cty.Type - err = (&ty).UnmarshalJSON(typeJSON) - if err != nil { - return cty.DynamicVal, path.NewError(err) - } - - return unmarshal(dec, ty, path) -} diff --git a/vendor/go.opencensus.io/Gopkg.lock b/vendor/go.opencensus.io/Gopkg.lock deleted file mode 100644 index 3be12ac8f24..00000000000 --- a/vendor/go.opencensus.io/Gopkg.lock +++ /dev/null @@ -1,231 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - branch = "master" - digest = "1:eee9386329f4fcdf8d6c0def0c9771b634bdd5ba460d888aa98c17d59b37a76c" - name = "git.apache.org/thrift.git" - packages = ["lib/go/thrift"] - pruneopts = "UT" - revision = "6e67faa92827ece022380b211c2caaadd6145bf5" - source = "github.com/apache/thrift" - -[[projects]] - branch = "master" - digest = "1:d6afaeed1502aa28e80a4ed0981d570ad91b2579193404256ce672ed0a609e0d" - name = "github.com/beorn7/perks" - packages = ["quantile"] - pruneopts = "UT" - revision = "3a771d992973f24aa725d07868b467d1ddfceafb" - -[[projects]] - digest = "1:4c0989ca0bcd10799064318923b9bc2db6b4d6338dd75f3f2d86c3511aaaf5cf" - name = "github.com/golang/protobuf" - packages = [ - "proto", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/timestamp", - ] - pruneopts = "UT" - revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5" - version = "v1.2.0" - -[[projects]] - digest = "1:ff5ebae34cfbf047d505ee150de27e60570e8c394b3b8fdbb720ff6ac71985fc" - name = "github.com/matttproud/golang_protobuf_extensions" - packages = ["pbutil"] - pruneopts = "UT" - revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" - version = "v1.0.1" - -[[projects]] - digest = "1:824c8f3aa4c5f23928fa84ebbd5ed2e9443b3f0cb958a40c1f2fbed5cf5e64b1" - name = "github.com/openzipkin/zipkin-go" - packages = [ - ".", - "idgenerator", - "model", - "propagation", - "reporter", - "reporter/http", - ] - pruneopts = "UT" - revision = "d455a5674050831c1e187644faa4046d653433c2" - version = "v0.1.1" - -[[projects]] - digest = "1:d14a5f4bfecf017cb780bdde1b6483e5deb87e12c332544d2c430eda58734bcb" - name = "github.com/prometheus/client_golang" - packages = [ - "prometheus", - "prometheus/promhttp", - ] - pruneopts = "UT" - revision = "c5b7fccd204277076155f10851dad72b76a49317" - version = "v0.8.0" - -[[projects]] - branch = "master" - digest = "1:2d5cd61daa5565187e1d96bae64dbbc6080dacf741448e9629c64fd93203b0d4" - name = "github.com/prometheus/client_model" - packages = ["go"] - pruneopts = "UT" - revision = "5c3871d89910bfb32f5fcab2aa4b9ec68e65a99f" - -[[projects]] - branch = "master" - digest = "1:63b68062b8968092eb86bedc4e68894bd096ea6b24920faca8b9dcf451f54bb5" - name = "github.com/prometheus/common" - packages = [ - "expfmt", - "internal/bitbucket.org/ww/goautoneg", - "model", - ] - pruneopts = "UT" - revision = "c7de2306084e37d54b8be01f3541a8464345e9a5" - -[[projects]] - branch = "master" - digest = "1:8c49953a1414305f2ff5465147ee576dd705487c35b15918fcd4efdc0cb7a290" - name = "github.com/prometheus/procfs" - packages = [ - ".", - "internal/util", - "nfs", - "xfs", - ] - pruneopts = "UT" - revision = "05ee40e3a273f7245e8777337fc7b46e533a9a92" - -[[projects]] - branch = "master" - digest = "1:deafe4ab271911fec7de5b693d7faae3f38796d9eb8622e2b9e7df42bb3dfea9" - name = "golang.org/x/net" - packages = [ - "context", - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace", - ] - pruneopts = "UT" - revision = "922f4815f713f213882e8ef45e0d315b164d705c" - -[[projects]] - branch = "master" - digest = "1:e0140c0c868c6e0f01c0380865194592c011fe521d6e12d78bfd33e756fe018a" - name = "golang.org/x/sync" - packages = ["semaphore"] - pruneopts = "UT" - revision = "1d60e4601c6fd243af51cc01ddf169918a5407ca" - -[[projects]] - branch = "master" - digest = "1:a3f00ac457c955fe86a41e1495e8f4c54cb5399d609374c5cc26aa7d72e542c8" - name = "golang.org/x/sys" - packages = ["unix"] - pruneopts = "UT" - revision = "3b58ed4ad3395d483fc92d5d14123ce2c3581fec" - -[[projects]] - digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18" - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "UT" - revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" - version = "v0.3.0" - -[[projects]] - branch = "master" - digest = "1:c0c17c94fe8bc1ab34e7f586a4a8b788c5e1f4f9f750ff23395b8b2f5a523530" - name = "google.golang.org/api" - packages = ["support/bundler"] - pruneopts = "UT" - revision = "e21acd801f91da814261b938941d193bb036441a" - -[[projects]] - branch = "master" - digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c" - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - pruneopts = "UT" - revision = "c66870c02cf823ceb633bcd05be3c7cda29976f4" - -[[projects]] - digest = "1:3dd7996ce6bf52dec6a2f69fa43e7c4cefea1d4dfa3c8ab7a5f8a9f7434e239d" - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "codes", - "connectivity", - "credentials", - "encoding", - "encoding/proto", - "grpclog", - "internal", - "internal/backoff", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "stats", - "status", - "tap", - ] - pruneopts = "UT" - revision = "32fb0ac620c32ba40a4626ddf94d90d12cce3455" - version = "v1.14.0" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "git.apache.org/thrift.git/lib/go/thrift", - "github.com/golang/protobuf/proto", - "github.com/openzipkin/zipkin-go", - "github.com/openzipkin/zipkin-go/model", - "github.com/openzipkin/zipkin-go/reporter", - "github.com/openzipkin/zipkin-go/reporter/http", - "github.com/prometheus/client_golang/prometheus", - "github.com/prometheus/client_golang/prometheus/promhttp", - "golang.org/x/net/context", - "golang.org/x/net/http2", - "google.golang.org/api/support/bundler", - "google.golang.org/grpc", - "google.golang.org/grpc/codes", - "google.golang.org/grpc/grpclog", - "google.golang.org/grpc/metadata", - "google.golang.org/grpc/stats", - "google.golang.org/grpc/status", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/go.opencensus.io/Gopkg.toml b/vendor/go.opencensus.io/Gopkg.toml deleted file mode 100644 index a9f3cd68eb3..00000000000 --- a/vendor/go.opencensus.io/Gopkg.toml +++ /dev/null @@ -1,36 +0,0 @@ -# For v0.x.y dependencies, prefer adding a constraints of the form: version=">= 0.x.y" -# to avoid locking to a particular minor version which can cause dep to not be -# able to find a satisfying dependency graph. - -[[constraint]] - branch = "master" - name = "git.apache.org/thrift.git" - source = "github.com/apache/thrift" - -[[constraint]] - name = "github.com/golang/protobuf" - version = "1.0.0" - -[[constraint]] - name = "github.com/openzipkin/zipkin-go" - version = ">=0.1.0" - -[[constraint]] - name = "github.com/prometheus/client_golang" - version = ">=0.8.0" - -[[constraint]] - branch = "master" - name = "golang.org/x/net" - -[[constraint]] - branch = "master" - name = "google.golang.org/api" - -[[constraint]] - name = "google.golang.org/grpc" - version = "1.11.3" - -[prune] - go-tests = true - unused-packages = true diff --git a/vendor/go.opencensus.io/Makefile b/vendor/go.opencensus.io/Makefile index 457866cb1f2..b3ce3df3032 100644 --- a/vendor/go.opencensus.io/Makefile +++ b/vendor/go.opencensus.io/Makefile @@ -8,7 +8,7 @@ ALL_PKGS := $(shell go list $(sort $(dir $(ALL_SRC)))) GOTEST_OPT?=-v -race -timeout 30s GOTEST_OPT_WITH_COVERAGE = $(GOTEST_OPT) -coverprofile=coverage.txt -covermode=atomic GOTEST=go test -GOFMT=gofmt +GOIMPORTS=goimports GOLINT=golint GOVET=go vet EMBEDMD=embedmd @@ -17,14 +17,14 @@ TRACE_ID_LINT_EXCEPTION="type name will be used as trace.TraceID by other packag TRACE_OPTION_LINT_EXCEPTION="type name will be used as trace.TraceOptions by other packages" README_FILES := $(shell find . -name '*README.md' | sort | tr '\n' ' ') -.DEFAULT_GOAL := fmt-lint-vet-embedmd-test +.DEFAULT_GOAL := imports-lint-vet-embedmd-test -.PHONY: fmt-lint-vet-embedmd-test -fmt-lint-vet-embedmd-test: fmt lint vet embedmd test +.PHONY: imports-lint-vet-embedmd-test +imports-lint-vet-embedmd-test: imports lint vet embedmd test # TODO enable test-with-coverage in tavis .PHONY: travis-ci -travis-ci: fmt lint vet embedmd test test-386 +travis-ci: imports lint vet embedmd test test-386 all-pkgs: @echo $(ALL_PKGS) | tr ' ' '\n' | sort @@ -44,15 +44,15 @@ test-386: test-with-coverage: $(GOTEST) $(GOTEST_OPT_WITH_COVERAGE) $(ALL_PKGS) -.PHONY: fmt -fmt: - @FMTOUT=`$(GOFMT) -s -l $(ALL_SRC) 2>&1`; \ - if [ "$$FMTOUT" ]; then \ - echo "$(GOFMT) FAILED => gofmt the following files:\n"; \ - echo "$$FMTOUT\n"; \ +.PHONY: imports +imports: + @IMPORTSOUT=`$(GOIMPORTS) -l $(ALL_SRC) 2>&1`; \ + if [ "$$IMPORTSOUT" ]; then \ + echo "$(GOIMPORTS) FAILED => goimports the following files:\n"; \ + echo "$$IMPORTSOUT\n"; \ exit 1; \ else \ - echo "Fmt finished successfully"; \ + echo "Imports finished successfully"; \ fi .PHONY: lint @@ -91,6 +91,7 @@ embedmd: .PHONY: install-tools install-tools: - go get -u golang.org/x/tools/cmd/cover go get -u golang.org/x/lint/golint + go get -u golang.org/x/tools/cmd/cover + go get -u golang.org/x/tools/cmd/goimports go get -u github.com/rakyll/embedmd diff --git a/vendor/go.opencensus.io/README.md b/vendor/go.opencensus.io/README.md index fabab2e0600..1d7e837116f 100644 --- a/vendor/go.opencensus.io/README.md +++ b/vendor/go.opencensus.io/README.md @@ -9,6 +9,8 @@ OpenCensus Go is a Go implementation of OpenCensus, a toolkit for collecting application performance and behavior monitoring data. Currently it consists of three major components: tags, stats and tracing. +#### OpenCensus and OpenTracing have merged to form OpenTelemetry, which serves as the next major version of OpenCensus and OpenTracing. OpenTelemetry will offer backwards compatibility with existing OpenCensus integrations, and we will continue to make security patches to existing OpenCensus libraries for two years. Read more about the merger [here](https://medium.com/opentracing/a-roadmap-to-convergence-b074e5815289). + ## Installation ``` @@ -57,6 +59,7 @@ can implement their own exporters by implementing the exporter interfaces * [Datadog][exporter-datadog] for stats and traces * [Graphite][exporter-graphite] for stats * [Honeycomb][exporter-honeycomb] for traces +* [New Relic][exporter-newrelic] for stats and traces ## Overview @@ -78,7 +81,7 @@ Package `tag` allows adding or modifying tags in the current context. [embedmd]:# (internal/readme/tags.go new) ```go -ctx, err = tag.New(ctx, +ctx, err := tag.New(ctx, tag.Insert(osKey, "macOS-10.12.5"), tag.Upsert(userIDKey, "cde36753ed"), ) @@ -261,3 +264,4 @@ release in which the functionality was marked *Deprecated*. [exporter-datadog]: https://github.com/DataDog/opencensus-go-exporter-datadog [exporter-graphite]: https://github.com/census-ecosystem/opencensus-go-exporter-graphite [exporter-honeycomb]: https://github.com/honeycombio/opencensus-exporter +[exporter-newrelic]: https://github.com/newrelic/newrelic-opencensus-exporter-go diff --git a/vendor/go.opencensus.io/appveyor.yml b/vendor/go.opencensus.io/appveyor.yml index 12bd7c4c73d..d08f0edaff9 100644 --- a/vendor/go.opencensus.io/appveyor.yml +++ b/vendor/go.opencensus.io/appveyor.yml @@ -6,13 +6,12 @@ clone_folder: c:\gopath\src\go.opencensus.io environment: GOPATH: 'c:\gopath' - GOVERSION: '1.11' GO111MODULE: 'on' CGO_ENABLED: '0' # See: https://github.com/appveyor/ci/issues/2613 -install: - - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% - - choco upgrade golang --version 1.11.5 # Temporary fix because of a go.sum bug in 1.11 +stack: go 1.11 + +before_test: - go version - go env diff --git a/vendor/go.opencensus.io/go.mod b/vendor/go.opencensus.io/go.mod index cb4de80f3bc..c867df5f5c4 100644 --- a/vendor/go.opencensus.io/go.mod +++ b/vendor/go.opencensus.io/go.mod @@ -1,12 +1,15 @@ module go.opencensus.io require ( + github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 github.com/golang/protobuf v1.3.1 github.com/google/go-cmp v0.3.0 - github.com/hashicorp/golang-lru v0.5.1 - golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09 + github.com/stretchr/testify v1.4.0 + golang.org/x/net v0.0.0-20190620200207-3b0461eec859 golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd // indirect golang.org/x/text v0.3.2 // indirect google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb // indirect google.golang.org/grpc v1.20.1 ) + +go 1.13 diff --git a/vendor/go.opencensus.io/go.sum b/vendor/go.opencensus.io/go.sum index 0b948c2b40c..01c02972c7e 100644 --- a/vendor/go.opencensus.io/go.sum +++ b/vendor/go.opencensus.io/go.sum @@ -1,8 +1,12 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 h1:ZgQEtGgCBiWRM39fZuwSd1LwSqqSW0hOdXCYYDX0R3I= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -10,20 +14,24 @@ github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 h1:XQyxROzUlZH+WIQwySDgnISgOivlhjIEwaQaJEJrrN0= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09 h1:KaQtG+aDELoNmXYas3TVkGNYRuq8JQ1aa7LJt8EXVyo= -golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -45,6 +53,7 @@ golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd h1:/e+gpKk9r3dJobndpTytxS2gOy6m5uvpg+ISQoEcusQ= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -58,4 +67,8 @@ google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZi google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1 h1:Hz2g2wirWK7H0qIIhGIqRGTuMwTE8HEKFnDZZ7lm9NU= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/vendor/go.opencensus.io/internal/internal.go b/vendor/go.opencensus.io/internal/internal.go index 9a638781cf1..81dc7183ec3 100644 --- a/vendor/go.opencensus.io/internal/internal.go +++ b/vendor/go.opencensus.io/internal/internal.go @@ -33,5 +33,5 @@ var UserAgent = fmt.Sprintf("opencensus-go/%s", opencensus.Version()) // end as a monotonic time. // See https://golang.org/pkg/time/#hdr-Monotonic_Clocks func MonotonicEndTime(start time.Time) time.Time { - return start.Add(time.Now().Sub(start)) + return start.Add(time.Since(start)) } diff --git a/vendor/go.opencensus.io/opencensus.go b/vendor/go.opencensus.io/opencensus.go index 626d73645df..e5e4b4368c1 100644 --- a/vendor/go.opencensus.io/opencensus.go +++ b/vendor/go.opencensus.io/opencensus.go @@ -17,5 +17,5 @@ package opencensus // import "go.opencensus.io" // Version is the current release version of OpenCensus in use. func Version() string { - return "0.22.0" + return "0.23.0" } diff --git a/vendor/go.opencensus.io/plugin/ochttp/propagation/b3/b3.go b/vendor/go.opencensus.io/plugin/ochttp/propagation/b3/b3.go index 2f1c7f0063e..9ad8852198d 100644 --- a/vendor/go.opencensus.io/plugin/ochttp/propagation/b3/b3.go +++ b/vendor/go.opencensus.io/plugin/ochttp/propagation/b3/b3.go @@ -68,7 +68,7 @@ func ParseTraceID(tid string) (trace.TraceID, bool) { return trace.TraceID{}, false } b, err := hex.DecodeString(tid) - if err != nil { + if err != nil || len(b) > 16 { return trace.TraceID{}, false } var traceID trace.TraceID @@ -90,7 +90,7 @@ func ParseSpanID(sid string) (spanID trace.SpanID, ok bool) { return trace.SpanID{}, false } b, err := hex.DecodeString(sid) - if err != nil { + if err != nil || len(b) > 8 { return trace.SpanID{}, false } start := 8 - len(b) diff --git a/vendor/go.opencensus.io/plugin/ochttp/server.go b/vendor/go.opencensus.io/plugin/ochttp/server.go index 4f6404fa790..c7ea6423572 100644 --- a/vendor/go.opencensus.io/plugin/ochttp/server.go +++ b/vendor/go.opencensus.io/plugin/ochttp/server.go @@ -70,6 +70,12 @@ type Handler struct { // from the information found in the incoming HTTP Request. By default the // name equals the URL Path. FormatSpanName func(*http.Request) string + + // IsHealthEndpoint holds the function to use for determining if the + // incoming HTTP request should be considered a health check. This is in + // addition to the private isHealthEndpoint func which may also indicate + // tracing should be skipped. + IsHealthEndpoint func(*http.Request) bool } func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -87,7 +93,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } func (h *Handler) startTrace(w http.ResponseWriter, r *http.Request) (*http.Request, func()) { - if isHealthEndpoint(r.URL.Path) { + if h.IsHealthEndpoint != nil && h.IsHealthEndpoint(r) || isHealthEndpoint(r.URL.Path) { return r, func() {} } var name string @@ -128,7 +134,7 @@ func (h *Handler) startTrace(w http.ResponseWriter, r *http.Request) (*http.Requ // TODO: Handle cases where ContentLength is not set. } else if r.ContentLength > 0 { span.AddMessageReceiveEvent(0, /* TODO: messageID */ - int64(r.ContentLength), -1) + r.ContentLength, -1) } return r.WithContext(ctx), span.End } @@ -174,8 +180,6 @@ type trackingResponseWriter struct { // Compile time assertion for ResponseWriter interface var _ http.ResponseWriter = (*trackingResponseWriter)(nil) -var logTagsErrorOnce sync.Once - func (t *trackingResponseWriter) end(tags *addedTags) { t.endOnce.Do(func() { if t.statusCode == 0 { diff --git a/vendor/go.opencensus.io/plugin/ochttp/stats.go b/vendor/go.opencensus.io/plugin/ochttp/stats.go index 63bbcda5e33..ee3729040dd 100644 --- a/vendor/go.opencensus.io/plugin/ochttp/stats.go +++ b/vendor/go.opencensus.io/plugin/ochttp/stats.go @@ -92,38 +92,38 @@ var ( // The value of this tag can be controlled by the HTTP client, so you need // to watch out for potentially generating high-cardinality labels in your // metrics backend if you use this tag in views. - Host, _ = tag.NewKey("http.host") + Host = tag.MustNewKey("http.host") // StatusCode is the numeric HTTP response status code, // or "error" if a transport error occurred and no status code was read. - StatusCode, _ = tag.NewKey("http.status") + StatusCode = tag.MustNewKey("http.status") // Path is the URL path (not including query string) in the request. // // The value of this tag can be controlled by the HTTP client, so you need // to watch out for potentially generating high-cardinality labels in your // metrics backend if you use this tag in views. - Path, _ = tag.NewKey("http.path") + Path = tag.MustNewKey("http.path") // Method is the HTTP method of the request, capitalized (GET, POST, etc.). - Method, _ = tag.NewKey("http.method") + Method = tag.MustNewKey("http.method") // KeyServerRoute is a low cardinality string representing the logical // handler of the request. This is usually the pattern registered on the a // ServeMux (or similar string). - KeyServerRoute, _ = tag.NewKey("http_server_route") + KeyServerRoute = tag.MustNewKey("http_server_route") ) // Client tag keys. var ( // KeyClientMethod is the HTTP method, capitalized (i.e. GET, POST, PUT, DELETE, etc.). - KeyClientMethod, _ = tag.NewKey("http_client_method") + KeyClientMethod = tag.MustNewKey("http_client_method") // KeyClientPath is the URL path (not including query string). - KeyClientPath, _ = tag.NewKey("http_client_path") + KeyClientPath = tag.MustNewKey("http_client_path") // KeyClientStatus is the HTTP status code as an integer (e.g. 200, 404, 500.), or "error" if no response status line was received. - KeyClientStatus, _ = tag.NewKey("http_client_status") + KeyClientStatus = tag.MustNewKey("http_client_status") // KeyClientHost is the value of the request Host header. - KeyClientHost, _ = tag.NewKey("http_client_host") + KeyClientHost = tag.MustNewKey("http_client_host") ) // Default distributions used by views in this package. diff --git a/vendor/go.opencensus.io/plugin/ochttp/trace.go b/vendor/go.opencensus.io/plugin/ochttp/trace.go index c23b97fb1fe..ed3a5db5611 100644 --- a/vendor/go.opencensus.io/plugin/ochttp/trace.go +++ b/vendor/go.opencensus.io/plugin/ochttp/trace.go @@ -186,6 +186,8 @@ func TraceStatus(httpStatusCode int, statusLine string) trace.Status { code = trace.StatusCodeCancelled case http.StatusBadRequest: code = trace.StatusCodeInvalidArgument + case http.StatusUnprocessableEntity: + code = trace.StatusCodeInvalidArgument case http.StatusGatewayTimeout: code = trace.StatusCodeDeadlineExceeded case http.StatusNotFound: @@ -202,7 +204,10 @@ func TraceStatus(httpStatusCode int, statusLine string) trace.Status { code = trace.StatusCodeUnavailable case http.StatusOK: code = trace.StatusCodeOK + case http.StatusConflict: + code = trace.StatusCodeAlreadyExists } + return trace.Status{Code: code, Message: codeToStr[code]} } diff --git a/vendor/go.opencensus.io/stats/record.go b/vendor/go.opencensus.io/stats/record.go index ad4691184df..2b97283462e 100644 --- a/vendor/go.opencensus.io/stats/record.go +++ b/vendor/go.opencensus.io/stats/record.go @@ -31,10 +31,19 @@ func init() { } } +// Recorder provides an interface for exporting measurement information from +// the static Record method by using the WithRecorder option. +type Recorder interface { + // Record records a set of measurements associated with the given tags and attachments. + // The second argument is a `[]Measurement`. + Record(*tag.Map, interface{}, map[string]interface{}) +} + type recordOptions struct { attachments metricdata.Attachments mutators []tag.Mutator measurements []Measurement + recorder Recorder } // WithAttachments applies provided exemplar attachments. @@ -58,6 +67,14 @@ func WithMeasurements(measurements ...Measurement) Options { } } +// WithRecorder records the measurements to the specified `Recorder`, rather +// than to the global metrics recorder. +func WithRecorder(meter Recorder) Options { + return func(ro *recordOptions) { + ro.recorder = meter + } +} + // Options apply changes to recordOptions. type Options func(*recordOptions) @@ -93,6 +110,9 @@ func RecordWithOptions(ctx context.Context, ros ...Options) error { return nil } recorder := internal.DefaultRecorder + if o.recorder != nil { + recorder = o.recorder.Record + } if recorder == nil { return nil } diff --git a/vendor/go.opencensus.io/stats/units.go b/vendor/go.opencensus.io/stats/units.go index 6931a5f2966..736399652cc 100644 --- a/vendor/go.opencensus.io/stats/units.go +++ b/vendor/go.opencensus.io/stats/units.go @@ -22,4 +22,5 @@ const ( UnitDimensionless = "1" UnitBytes = "By" UnitMilliseconds = "ms" + UnitSeconds = "s" ) diff --git a/vendor/go.opencensus.io/stats/view/aggregation.go b/vendor/go.opencensus.io/stats/view/aggregation.go index b7f169b4a5f..9d7093728ed 100644 --- a/vendor/go.opencensus.io/stats/view/aggregation.go +++ b/vendor/go.opencensus.io/stats/view/aggregation.go @@ -82,7 +82,7 @@ func Sum() *Aggregation { // Distribution indicates that the desired aggregation is // a histogram distribution. // -// An distribution aggregation may contain a histogram of the values in the +// A distribution aggregation may contain a histogram of the values in the // population. The bucket boundaries for that histogram are described // by the bounds. This defines len(bounds)+1 buckets. // @@ -99,13 +99,14 @@ func Sum() *Aggregation { // If len(bounds) is 1 then there is no finite buckets, and that single // element is the common boundary of the overflow and underflow buckets. func Distribution(bounds ...float64) *Aggregation { - return &Aggregation{ + agg := &Aggregation{ Type: AggTypeDistribution, Buckets: bounds, - newData: func() AggregationData { - return newDistributionData(bounds) - }, } + agg.newData = func() AggregationData { + return newDistributionData(agg) + } + return agg } // LastValue only reports the last value recorded using this diff --git a/vendor/go.opencensus.io/stats/view/aggregation_data.go b/vendor/go.opencensus.io/stats/view/aggregation_data.go index d500e67f733..f331d456e9b 100644 --- a/vendor/go.opencensus.io/stats/view/aggregation_data.go +++ b/vendor/go.opencensus.io/stats/view/aggregation_data.go @@ -128,12 +128,12 @@ type DistributionData struct { bounds []float64 // histogram distribution of the values } -func newDistributionData(bounds []float64) *DistributionData { - bucketCount := len(bounds) + 1 +func newDistributionData(agg *Aggregation) *DistributionData { + bucketCount := len(agg.Buckets) + 1 return &DistributionData{ CountPerBucket: make([]int64, bucketCount), ExemplarsPerBucket: make([]*metricdata.Exemplar, bucketCount), - bounds: bounds, + bounds: agg.Buckets, Min: math.MaxFloat64, Max: math.SmallestNonzeroFloat64, } diff --git a/vendor/go.opencensus.io/stats/view/doc.go b/vendor/go.opencensus.io/stats/view/doc.go index dced225c3dc..7bbedfe1ff2 100644 --- a/vendor/go.opencensus.io/stats/view/doc.go +++ b/vendor/go.opencensus.io/stats/view/doc.go @@ -29,7 +29,7 @@ // LastValue just keeps track of the most recently recorded measurement value. // All aggregations are cumulative. // -// Views can be registerd and unregistered at any time during program execution. +// Views can be registered and unregistered at any time during program execution. // // Libraries can define views but it is recommended that in most cases registering // views be left up to applications. diff --git a/vendor/go.opencensus.io/stats/view/export.go b/vendor/go.opencensus.io/stats/view/export.go index 7cb59718f5f..73ba11f5b6e 100644 --- a/vendor/go.opencensus.io/stats/view/export.go +++ b/vendor/go.opencensus.io/stats/view/export.go @@ -14,13 +14,6 @@ package view -import "sync" - -var ( - exportersMu sync.RWMutex // guards exporters - exporters = make(map[Exporter]struct{}) -) - // Exporter exports the collected records as view data. // // The ExportView method should return quickly; if an @@ -43,16 +36,10 @@ type Exporter interface { // // Binaries can register exporters, libraries shouldn't register exporters. func RegisterExporter(e Exporter) { - exportersMu.Lock() - defer exportersMu.Unlock() - - exporters[e] = struct{}{} + defaultWorker.RegisterExporter(e) } // UnregisterExporter unregisters an exporter. func UnregisterExporter(e Exporter) { - exportersMu.Lock() - defer exportersMu.Unlock() - - delete(exporters, e) + defaultWorker.UnregisterExporter(e) } diff --git a/vendor/go.opencensus.io/stats/view/view.go b/vendor/go.opencensus.io/stats/view/view.go index 37f88e1d9fa..293b54ecbed 100644 --- a/vendor/go.opencensus.io/stats/view/view.go +++ b/vendor/go.opencensus.io/stats/view/view.go @@ -30,7 +30,7 @@ import ( ) // View allows users to aggregate the recorded stats.Measurements. -// Views need to be passed to the Register function to be before data will be +// Views need to be passed to the Register function before data will be // collected and sent to Exporters. type View struct { Name string // Name of View. Must be unique. If unset, will default to the name of the Measure. @@ -43,7 +43,7 @@ type View struct { // Measure is a stats.Measure to aggregate in this view. Measure stats.Measure - // Aggregation is the aggregation function tp apply to the set of Measurements. + // Aggregation is the aggregation function to apply to the set of Measurements. Aggregation *Aggregation } @@ -189,7 +189,7 @@ func (r *Row) String() string { } // Equal returns true if both rows are equal. Tags are expected to be ordered -// by the key name. Even both rows have the same tags but the tags appear in +// by the key name. Even if both rows have the same tags but the tags appear in // different orders it will return false. func (r *Row) Equal(other *Row) bool { if r == other { diff --git a/vendor/go.opencensus.io/stats/view/view_to_metric.go b/vendor/go.opencensus.io/stats/view/view_to_metric.go index f67b5c46430..5e1656a1f2b 100644 --- a/vendor/go.opencensus.io/stats/view/view_to_metric.go +++ b/vendor/go.opencensus.io/stats/view/view_to_metric.go @@ -18,6 +18,8 @@ package view import ( "time" + "go.opencensus.io/resource" + "go.opencensus.io/metric/metricdata" "go.opencensus.io/stats" ) @@ -85,12 +87,21 @@ func viewToMetricDescriptor(v *View) *metricdata.Descriptor { return &metricdata.Descriptor{ Name: v.Name, Description: v.Description, - Unit: getUnit(v.Measure.Unit()), + Unit: convertUnit(v), Type: getType(v), LabelKeys: getLabelKeys(v), } } +func convertUnit(v *View) metricdata.Unit { + switch v.Aggregation.Type { + case AggTypeCount: + return metricdata.UnitDimensionless + default: + return getUnit(v.Measure.Unit()) + } +} + func toLabelValues(row *Row, expectedKeys []metricdata.LabelKey) []metricdata.LabelValue { labelValues := []metricdata.LabelValue{} tagMap := make(map[string]string) @@ -116,7 +127,7 @@ func rowToTimeseries(v *viewInternal, row *Row, now time.Time, startTime time.Ti } } -func viewToMetric(v *viewInternal, now time.Time, startTime time.Time) *metricdata.Metric { +func viewToMetric(v *viewInternal, r *resource.Resource, now time.Time, startTime time.Time) *metricdata.Metric { if v.metricDescriptor.Type == metricdata.TypeGaugeInt64 || v.metricDescriptor.Type == metricdata.TypeGaugeFloat64 { startTime = time.Time{} @@ -135,6 +146,7 @@ func viewToMetric(v *viewInternal, now time.Time, startTime time.Time) *metricda m := &metricdata.Metric{ Descriptor: *v.metricDescriptor, TimeSeries: ts, + Resource: r, } return m } diff --git a/vendor/go.opencensus.io/stats/view/worker.go b/vendor/go.opencensus.io/stats/view/worker.go index 2f3c018af0e..ab8bfd46d0b 100644 --- a/vendor/go.opencensus.io/stats/view/worker.go +++ b/vendor/go.opencensus.io/stats/view/worker.go @@ -20,6 +20,8 @@ import ( "sync" "time" + "go.opencensus.io/resource" + "go.opencensus.io/metric/metricdata" "go.opencensus.io/metric/metricproducer" "go.opencensus.io/stats" @@ -28,7 +30,7 @@ import ( ) func init() { - defaultWorker = newWorker() + defaultWorker = NewMeter().(*worker) go defaultWorker.start() internal.DefaultRecorder = record } @@ -47,8 +49,69 @@ type worker struct { c chan command quit, done chan bool mu sync.RWMutex + r *resource.Resource + + exportersMu sync.RWMutex + exporters map[Exporter]struct{} +} + +// Meter defines an interface which allows a single process to maintain +// multiple sets of metrics exports (intended for the advanced case where a +// single process wants to report metrics about multiple objects, such as +// multiple databases or HTTP services). +// +// Note that this is an advanced use case, and the static functions in this +// module should cover the common use cases. +type Meter interface { + stats.Recorder + // Find returns a registered view associated with this name. + // If no registered view is found, nil is returned. + Find(name string) *View + // Register begins collecting data for the given views. + // Once a view is registered, it reports data to the registered exporters. + Register(views ...*View) error + // Unregister the given views. Data will not longer be exported for these views + // after Unregister returns. + // It is not necessary to unregister from views you expect to collect for the + // duration of your program execution. + Unregister(views ...*View) + // SetReportingPeriod sets the interval between reporting aggregated views in + // the program. If duration is less than or equal to zero, it enables the + // default behavior. + // + // Note: each exporter makes different promises about what the lowest supported + // duration is. For example, the Stackdriver exporter recommends a value no + // lower than 1 minute. Consult each exporter per your needs. + SetReportingPeriod(time.Duration) + + // RegisterExporter registers an exporter. + // Collected data will be reported via all the + // registered exporters. Once you no longer + // want data to be exported, invoke UnregisterExporter + // with the previously registered exporter. + // + // Binaries can register exporters, libraries shouldn't register exporters. + RegisterExporter(Exporter) + // UnregisterExporter unregisters an exporter. + UnregisterExporter(Exporter) + // SetResource may be used to set the Resource associated with this registry. + // This is intended to be used in cases where a single process exports metrics + // for multiple Resources, typically in a multi-tenant situation. + SetResource(*resource.Resource) + + // Start causes the Meter to start processing Record calls and aggregating + // statistics as well as exporting data. + Start() + // Stop causes the Meter to stop processing calls and terminate data export. + Stop() + + // RetrieveData gets a snapshot of the data collected for the the view registered + // with the given name. It is intended for testing only. + RetrieveData(viewName string) ([]*Row, error) } +var _ Meter = (*worker)(nil) + var defaultWorker *worker var defaultReportingDuration = 10 * time.Second @@ -56,11 +119,17 @@ var defaultReportingDuration = 10 * time.Second // Find returns a registered view associated with this name. // If no registered view is found, nil is returned. func Find(name string) (v *View) { + return defaultWorker.Find(name) +} + +// Find returns a registered view associated with this name. +// If no registered view is found, nil is returned. +func (w *worker) Find(name string) (v *View) { req := &getViewByNameReq{ name: name, c: make(chan *getViewByNameResp), } - defaultWorker.c <- req + w.c <- req resp := <-req.c return resp.v } @@ -68,11 +137,17 @@ func Find(name string) (v *View) { // Register begins collecting data for the given views. // Once a view is registered, it reports data to the registered exporters. func Register(views ...*View) error { + return defaultWorker.Register(views...) +} + +// Register begins collecting data for the given views. +// Once a view is registered, it reports data to the registered exporters. +func (w *worker) Register(views ...*View) error { req := ®isterViewReq{ views: views, err: make(chan error), } - defaultWorker.c <- req + w.c <- req return <-req.err } @@ -81,6 +156,14 @@ func Register(views ...*View) error { // It is not necessary to unregister from views you expect to collect for the // duration of your program execution. func Unregister(views ...*View) { + defaultWorker.Unregister(views...) +} + +// Unregister the given views. Data will not longer be exported for these views +// after Unregister returns. +// It is not necessary to unregister from views you expect to collect for the +// duration of your program execution. +func (w *worker) Unregister(views ...*View) { names := make([]string, len(views)) for i := range views { names[i] = views[i].Name @@ -89,31 +172,42 @@ func Unregister(views ...*View) { views: names, done: make(chan struct{}), } - defaultWorker.c <- req + w.c <- req <-req.done } // RetrieveData gets a snapshot of the data collected for the the view registered // with the given name. It is intended for testing only. func RetrieveData(viewName string) ([]*Row, error) { + return defaultWorker.RetrieveData(viewName) +} + +// RetrieveData gets a snapshot of the data collected for the the view registered +// with the given name. It is intended for testing only. +func (w *worker) RetrieveData(viewName string) ([]*Row, error) { req := &retrieveDataReq{ now: time.Now(), v: viewName, c: make(chan *retrieveDataResp), } - defaultWorker.c <- req + w.c <- req resp := <-req.c return resp.rows, resp.err } func record(tags *tag.Map, ms interface{}, attachments map[string]interface{}) { + defaultWorker.Record(tags, ms, attachments) +} + +// Record records a set of measurements ms associated with the given tags and attachments. +func (w *worker) Record(tags *tag.Map, ms interface{}, attachments map[string]interface{}) { req := &recordReq{ tm: tags, ms: ms.([]stats.Measurement), attachments: attachments, t: time.Now(), } - defaultWorker.c <- req + w.c <- req } // SetReportingPeriod sets the interval between reporting aggregated views in @@ -124,17 +218,31 @@ func record(tags *tag.Map, ms interface{}, attachments map[string]interface{}) { // duration is. For example, the Stackdriver exporter recommends a value no // lower than 1 minute. Consult each exporter per your needs. func SetReportingPeriod(d time.Duration) { + defaultWorker.SetReportingPeriod(d) +} + +// SetReportingPeriod sets the interval between reporting aggregated views in +// the program. If duration is less than or equal to zero, it enables the +// default behavior. +// +// Note: each exporter makes different promises about what the lowest supported +// duration is. For example, the Stackdriver exporter recommends a value no +// lower than 1 minute. Consult each exporter per your needs. +func (w *worker) SetReportingPeriod(d time.Duration) { // TODO(acetechnologist): ensure that the duration d is more than a certain // value. e.g. 1s req := &setReportingPeriodReq{ d: d, c: make(chan bool), } - defaultWorker.c <- req + w.c <- req <-req.c // don't return until the timer is set to the new duration. } -func newWorker() *worker { +// NewMeter constructs a Meter instance. You should only need to use this if +// you need to separate out Measurement recordings and View aggregations within +// a single process. +func NewMeter() Meter { return &worker{ measures: make(map[string]*measureRef), views: make(map[string]*viewInternal), @@ -143,9 +251,23 @@ func newWorker() *worker { c: make(chan command, 1024), quit: make(chan bool), done: make(chan bool), + + exporters: make(map[Exporter]struct{}), } } +// SetResource associates all data collected by this Meter with the specified +// resource. This resource is reported when using metricexport.ReadAndExport; +// it is not provided when used with ExportView/RegisterExporter, because that +// interface does not provide a means for reporting the Resource. +func (w *worker) SetResource(r *resource.Resource) { + w.r = r +} + +func (w *worker) Start() { + go w.start() +} + func (w *worker) start() { prodMgr := metricproducer.GlobalManager() prodMgr.AddProducer(w) @@ -155,7 +277,7 @@ func (w *worker) start() { case cmd := <-w.c: cmd.handleCommand(w) case <-w.timer.C: - w.reportUsage(time.Now()) + w.reportUsage() case <-w.quit: w.timer.Stop() close(w.c) @@ -165,7 +287,7 @@ func (w *worker) start() { } } -func (w *worker) stop() { +func (w *worker) Stop() { prodMgr := metricproducer.GlobalManager() prodMgr.DeleteProducer(w) @@ -202,44 +324,45 @@ func (w *worker) tryRegisterView(v *View) (*viewInternal, error) { return x, nil } w.views[vi.view.Name] = vi + w.startTimes[vi] = time.Now() ref := w.getMeasureRef(vi.view.Measure.Name()) ref.views[vi] = struct{}{} return vi, nil } -func (w *worker) unregisterView(viewName string) { +func (w *worker) unregisterView(v *viewInternal) { w.mu.Lock() defer w.mu.Unlock() - delete(w.views, viewName) + delete(w.views, v.view.Name) + delete(w.startTimes, v) + if measure := w.measures[v.view.Measure.Name()]; measure != nil { + delete(measure.views, v) + } } -func (w *worker) reportView(v *viewInternal, now time.Time) { +func (w *worker) reportView(v *viewInternal) { if !v.isSubscribed() { return } rows := v.collectedRows() - _, ok := w.startTimes[v] - if !ok { - w.startTimes[v] = now - } viewData := &Data{ View: v.view, Start: w.startTimes[v], End: time.Now(), Rows: rows, } - exportersMu.Lock() - for e := range exporters { + w.exportersMu.Lock() + defer w.exportersMu.Unlock() + for e := range w.exporters { e.ExportView(viewData) } - exportersMu.Unlock() } -func (w *worker) reportUsage(now time.Time) { +func (w *worker) reportUsage() { w.mu.Lock() defer w.mu.Unlock() for _, v := range w.views { - w.reportView(v, now) + w.reportView(v) } } @@ -248,11 +371,6 @@ func (w *worker) toMetric(v *viewInternal, now time.Time) *metricdata.Metric { return nil } - _, ok := w.startTimes[v] - if !ok { - w.startTimes[v] = now - } - var startTime time.Time if v.metricDescriptor.Type == metricdata.TypeGaugeInt64 || v.metricDescriptor.Type == metricdata.TypeGaugeFloat64 { @@ -261,7 +379,7 @@ func (w *worker) toMetric(v *viewInternal, now time.Time) *metricdata.Metric { startTime = w.startTimes[v] } - return viewToMetric(v, now, startTime) + return viewToMetric(v, w.r, now, startTime) } // Read reads all view data and returns them as metrics. @@ -279,3 +397,17 @@ func (w *worker) Read() []*metricdata.Metric { } return metrics } + +func (w *worker) RegisterExporter(e Exporter) { + w.exportersMu.Lock() + defer w.exportersMu.Unlock() + + w.exporters[e] = struct{}{} +} + +func (w *worker) UnregisterExporter(e Exporter) { + w.exportersMu.Lock() + defer w.exportersMu.Unlock() + + delete(w.exporters, e) +} diff --git a/vendor/go.opencensus.io/stats/view/worker_commands.go b/vendor/go.opencensus.io/stats/view/worker_commands.go index 0267e179aed..9ac4cc05992 100644 --- a/vendor/go.opencensus.io/stats/view/worker_commands.go +++ b/vendor/go.opencensus.io/stats/view/worker_commands.go @@ -95,7 +95,7 @@ func (cmd *unregisterFromViewReq) handleCommand(w *worker) { } // Report pending data for this view before removing it. - w.reportView(vi, time.Now()) + w.reportView(vi) vi.unsubscribe() if !vi.isSubscribed() { @@ -103,7 +103,7 @@ func (cmd *unregisterFromViewReq) handleCommand(w *worker) { // The collected data can be cleared. vi.clearRows() } - w.unregisterView(name) + w.unregisterView(vi) } cmd.done <- struct{}{} } @@ -163,7 +163,7 @@ func (cmd *recordReq) handleCommand(w *worker) { } ref := w.getMeasureRef(m.Measure().Name()) for v := range ref.views { - v.addSample(cmd.tm, m.Value(), cmd.attachments, time.Now()) + v.addSample(cmd.tm, m.Value(), cmd.attachments, cmd.t) } } } diff --git a/vendor/go.opencensus.io/tag/key.go b/vendor/go.opencensus.io/tag/key.go index 4e63d08c937..71ec913657b 100644 --- a/vendor/go.opencensus.io/tag/key.go +++ b/vendor/go.opencensus.io/tag/key.go @@ -21,7 +21,7 @@ type Key struct { } // NewKey creates or retrieves a string key identified by name. -// Calling NewKey consequently with the same name returns the same key. +// Calling NewKey more than once with the same name returns the same key. func NewKey(name string) (Key, error) { if !checkKeyName(name) { return Key{}, errInvalidKeyName @@ -29,8 +29,7 @@ func NewKey(name string) (Key, error) { return Key{name: name}, nil } -// MustNewKey creates or retrieves a string key identified by name. -// An invalid key name raises a panic. +// MustNewKey returns a key with the given name, and panics if name is an invalid key name. func MustNewKey(name string) Key { k, err := NewKey(name) if err != nil { diff --git a/vendor/go.opencensus.io/tag/map_codec.go b/vendor/go.opencensus.io/tag/map_codec.go index f8b58276153..c242e695c8c 100644 --- a/vendor/go.opencensus.io/tag/map_codec.go +++ b/vendor/go.opencensus.io/tag/map_codec.go @@ -168,7 +168,7 @@ func Encode(m *Map) []byte { eg := &encoderGRPC{ buf: make([]byte, len(m.m)), } - eg.writeByte(byte(tagsVersionID)) + eg.writeByte(tagsVersionID) for k, v := range m.m { if v.m.ttl.ttl == valueTTLUnlimitedPropagation { eg.writeByte(byte(keyTypeString)) diff --git a/vendor/go.opencensus.io/trace/lrumap.go b/vendor/go.opencensus.io/trace/lrumap.go index 3f80a336813..908c2497ed5 100644 --- a/vendor/go.opencensus.io/trace/lrumap.go +++ b/vendor/go.opencensus.io/trace/lrumap.go @@ -15,23 +15,47 @@ package trace import ( - "github.com/hashicorp/golang-lru/simplelru" + "github.com/golang/groupcache/lru" ) +// A simple lru.Cache wrapper that tracks the keys of the current contents and +// the cumulative number of evicted items. type lruMap struct { - simpleLruMap *simplelru.LRU + cacheKeys map[lru.Key]bool + cache *lru.Cache droppedCount int } func newLruMap(size int) *lruMap { - lm := &lruMap{} - lm.simpleLruMap, _ = simplelru.NewLRU(size, nil) + lm := &lruMap{ + cacheKeys: make(map[lru.Key]bool), + cache: lru.New(size), + droppedCount: 0, + } + lm.cache.OnEvicted = func(key lru.Key, value interface{}) { + delete(lm.cacheKeys, key) + lm.droppedCount++ + } return lm } -func (lm *lruMap) add(key, value interface{}) { - evicted := lm.simpleLruMap.Add(key, value) - if evicted { - lm.droppedCount++ +func (lm lruMap) len() int { + return lm.cache.Len() +} + +func (lm lruMap) keys() []interface{} { + keys := make([]interface{}, len(lm.cacheKeys)) + for k := range lm.cacheKeys { + keys = append(keys, k) } + return keys +} + +func (lm *lruMap) add(key, value interface{}) { + lm.cacheKeys[lru.Key(key)] = true + lm.cache.Add(lru.Key(key), value) +} + +func (lm *lruMap) get(key interface{}) (interface{}, bool) { + return lm.cache.Get(key) } diff --git a/vendor/go.opencensus.io/trace/trace.go b/vendor/go.opencensus.io/trace/trace.go index 38ead7bf0ad..125e2cd9012 100644 --- a/vendor/go.opencensus.io/trace/trace.go +++ b/vendor/go.opencensus.io/trace/trace.go @@ -296,7 +296,7 @@ func (s *Span) makeSpanData() *SpanData { var sd SpanData s.mu.Lock() sd = *s.data - if s.lruAttributes.simpleLruMap.Len() > 0 { + if s.lruAttributes.len() > 0 { sd.Attributes = s.lruAttributesToAttributeMap() sd.DroppedAttributeCount = s.lruAttributes.droppedCount } @@ -345,7 +345,7 @@ func (s *Span) SetStatus(status Status) { } func (s *Span) interfaceArrayToLinksArray() []Link { - linksArr := make([]Link, 0) + linksArr := make([]Link, 0, len(s.links.queue)) for _, value := range s.links.queue { linksArr = append(linksArr, value.(Link)) } @@ -353,7 +353,7 @@ func (s *Span) interfaceArrayToLinksArray() []Link { } func (s *Span) interfaceArrayToMessageEventArray() []MessageEvent { - messageEventArr := make([]MessageEvent, 0) + messageEventArr := make([]MessageEvent, 0, len(s.messageEvents.queue)) for _, value := range s.messageEvents.queue { messageEventArr = append(messageEventArr, value.(MessageEvent)) } @@ -361,7 +361,7 @@ func (s *Span) interfaceArrayToMessageEventArray() []MessageEvent { } func (s *Span) interfaceArrayToAnnotationArray() []Annotation { - annotationArr := make([]Annotation, 0) + annotationArr := make([]Annotation, 0, len(s.annotations.queue)) for _, value := range s.annotations.queue { annotationArr = append(annotationArr, value.(Annotation)) } @@ -369,9 +369,9 @@ func (s *Span) interfaceArrayToAnnotationArray() []Annotation { } func (s *Span) lruAttributesToAttributeMap() map[string]interface{} { - attributes := make(map[string]interface{}) - for _, key := range s.lruAttributes.simpleLruMap.Keys() { - value, ok := s.lruAttributes.simpleLruMap.Get(key) + attributes := make(map[string]interface{}, s.lruAttributes.len()) + for _, key := range s.lruAttributes.keys() { + value, ok := s.lruAttributes.get(key) if ok { keyStr := key.(string) attributes[keyStr] = value @@ -420,7 +420,7 @@ func (s *Span) lazyPrintfInternal(attributes []Attribute, format string, a ...in var m map[string]interface{} s.mu.Lock() if len(attributes) != 0 { - m = make(map[string]interface{}) + m = make(map[string]interface{}, len(attributes)) copyAttributes(m, attributes) } s.annotations.add(Annotation{ @@ -436,7 +436,7 @@ func (s *Span) printStringInternal(attributes []Attribute, str string) { var a map[string]interface{} s.mu.Lock() if len(attributes) != 0 { - a = make(map[string]interface{}) + a = make(map[string]interface{}, len(attributes)) copyAttributes(a, attributes) } s.annotations.add(Annotation{ diff --git a/vendor/golang.org/x/crypto/bcrypt/base64.go b/vendor/golang.org/x/crypto/bcrypt/base64.go deleted file mode 100644 index fc311609081..00000000000 --- a/vendor/golang.org/x/crypto/bcrypt/base64.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bcrypt - -import "encoding/base64" - -const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" - -var bcEncoding = base64.NewEncoding(alphabet) - -func base64Encode(src []byte) []byte { - n := bcEncoding.EncodedLen(len(src)) - dst := make([]byte, n) - bcEncoding.Encode(dst, src) - for dst[n-1] == '=' { - n-- - } - return dst[:n] -} - -func base64Decode(src []byte) ([]byte, error) { - numOfEquals := 4 - (len(src) % 4) - for i := 0; i < numOfEquals; i++ { - src = append(src, '=') - } - - dst := make([]byte, bcEncoding.DecodedLen(len(src))) - n, err := bcEncoding.Decode(dst, src) - if err != nil { - return nil, err - } - return dst[:n], nil -} diff --git a/vendor/golang.org/x/crypto/bcrypt/bcrypt.go b/vendor/golang.org/x/crypto/bcrypt/bcrypt.go deleted file mode 100644 index aeb73f81a14..00000000000 --- a/vendor/golang.org/x/crypto/bcrypt/bcrypt.go +++ /dev/null @@ -1,295 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package bcrypt implements Provos and Mazières's bcrypt adaptive hashing -// algorithm. See http://www.usenix.org/event/usenix99/provos/provos.pdf -package bcrypt // import "golang.org/x/crypto/bcrypt" - -// The code is a port of Provos and Mazières's C implementation. -import ( - "crypto/rand" - "crypto/subtle" - "errors" - "fmt" - "io" - "strconv" - - "golang.org/x/crypto/blowfish" -) - -const ( - MinCost int = 4 // the minimum allowable cost as passed in to GenerateFromPassword - MaxCost int = 31 // the maximum allowable cost as passed in to GenerateFromPassword - DefaultCost int = 10 // the cost that will actually be set if a cost below MinCost is passed into GenerateFromPassword -) - -// The error returned from CompareHashAndPassword when a password and hash do -// not match. -var ErrMismatchedHashAndPassword = errors.New("crypto/bcrypt: hashedPassword is not the hash of the given password") - -// The error returned from CompareHashAndPassword when a hash is too short to -// be a bcrypt hash. -var ErrHashTooShort = errors.New("crypto/bcrypt: hashedSecret too short to be a bcrypted password") - -// The error returned from CompareHashAndPassword when a hash was created with -// a bcrypt algorithm newer than this implementation. -type HashVersionTooNewError byte - -func (hv HashVersionTooNewError) Error() string { - return fmt.Sprintf("crypto/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'", byte(hv), majorVersion) -} - -// The error returned from CompareHashAndPassword when a hash starts with something other than '$' -type InvalidHashPrefixError byte - -func (ih InvalidHashPrefixError) Error() string { - return fmt.Sprintf("crypto/bcrypt: bcrypt hashes must start with '$', but hashedSecret started with '%c'", byte(ih)) -} - -type InvalidCostError int - -func (ic InvalidCostError) Error() string { - return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed range (%d,%d)", int(ic), int(MinCost), int(MaxCost)) -} - -const ( - majorVersion = '2' - minorVersion = 'a' - maxSaltSize = 16 - maxCryptedHashSize = 23 - encodedSaltSize = 22 - encodedHashSize = 31 - minHashSize = 59 -) - -// magicCipherData is an IV for the 64 Blowfish encryption calls in -// bcrypt(). It's the string "OrpheanBeholderScryDoubt" in big-endian bytes. -var magicCipherData = []byte{ - 0x4f, 0x72, 0x70, 0x68, - 0x65, 0x61, 0x6e, 0x42, - 0x65, 0x68, 0x6f, 0x6c, - 0x64, 0x65, 0x72, 0x53, - 0x63, 0x72, 0x79, 0x44, - 0x6f, 0x75, 0x62, 0x74, -} - -type hashed struct { - hash []byte - salt []byte - cost int // allowed range is MinCost to MaxCost - major byte - minor byte -} - -// GenerateFromPassword returns the bcrypt hash of the password at the given -// cost. If the cost given is less than MinCost, the cost will be set to -// DefaultCost, instead. Use CompareHashAndPassword, as defined in this package, -// to compare the returned hashed password with its cleartext version. -func GenerateFromPassword(password []byte, cost int) ([]byte, error) { - p, err := newFromPassword(password, cost) - if err != nil { - return nil, err - } - return p.Hash(), nil -} - -// CompareHashAndPassword compares a bcrypt hashed password with its possible -// plaintext equivalent. Returns nil on success, or an error on failure. -func CompareHashAndPassword(hashedPassword, password []byte) error { - p, err := newFromHash(hashedPassword) - if err != nil { - return err - } - - otherHash, err := bcrypt(password, p.cost, p.salt) - if err != nil { - return err - } - - otherP := &hashed{otherHash, p.salt, p.cost, p.major, p.minor} - if subtle.ConstantTimeCompare(p.Hash(), otherP.Hash()) == 1 { - return nil - } - - return ErrMismatchedHashAndPassword -} - -// Cost returns the hashing cost used to create the given hashed -// password. When, in the future, the hashing cost of a password system needs -// to be increased in order to adjust for greater computational power, this -// function allows one to establish which passwords need to be updated. -func Cost(hashedPassword []byte) (int, error) { - p, err := newFromHash(hashedPassword) - if err != nil { - return 0, err - } - return p.cost, nil -} - -func newFromPassword(password []byte, cost int) (*hashed, error) { - if cost < MinCost { - cost = DefaultCost - } - p := new(hashed) - p.major = majorVersion - p.minor = minorVersion - - err := checkCost(cost) - if err != nil { - return nil, err - } - p.cost = cost - - unencodedSalt := make([]byte, maxSaltSize) - _, err = io.ReadFull(rand.Reader, unencodedSalt) - if err != nil { - return nil, err - } - - p.salt = base64Encode(unencodedSalt) - hash, err := bcrypt(password, p.cost, p.salt) - if err != nil { - return nil, err - } - p.hash = hash - return p, err -} - -func newFromHash(hashedSecret []byte) (*hashed, error) { - if len(hashedSecret) < minHashSize { - return nil, ErrHashTooShort - } - p := new(hashed) - n, err := p.decodeVersion(hashedSecret) - if err != nil { - return nil, err - } - hashedSecret = hashedSecret[n:] - n, err = p.decodeCost(hashedSecret) - if err != nil { - return nil, err - } - hashedSecret = hashedSecret[n:] - - // The "+2" is here because we'll have to append at most 2 '=' to the salt - // when base64 decoding it in expensiveBlowfishSetup(). - p.salt = make([]byte, encodedSaltSize, encodedSaltSize+2) - copy(p.salt, hashedSecret[:encodedSaltSize]) - - hashedSecret = hashedSecret[encodedSaltSize:] - p.hash = make([]byte, len(hashedSecret)) - copy(p.hash, hashedSecret) - - return p, nil -} - -func bcrypt(password []byte, cost int, salt []byte) ([]byte, error) { - cipherData := make([]byte, len(magicCipherData)) - copy(cipherData, magicCipherData) - - c, err := expensiveBlowfishSetup(password, uint32(cost), salt) - if err != nil { - return nil, err - } - - for i := 0; i < 24; i += 8 { - for j := 0; j < 64; j++ { - c.Encrypt(cipherData[i:i+8], cipherData[i:i+8]) - } - } - - // Bug compatibility with C bcrypt implementations. We only encode 23 of - // the 24 bytes encrypted. - hsh := base64Encode(cipherData[:maxCryptedHashSize]) - return hsh, nil -} - -func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, error) { - csalt, err := base64Decode(salt) - if err != nil { - return nil, err - } - - // Bug compatibility with C bcrypt implementations. They use the trailing - // NULL in the key string during expansion. - // We copy the key to prevent changing the underlying array. - ckey := append(key[:len(key):len(key)], 0) - - c, err := blowfish.NewSaltedCipher(ckey, csalt) - if err != nil { - return nil, err - } - - var i, rounds uint64 - rounds = 1 << cost - for i = 0; i < rounds; i++ { - blowfish.ExpandKey(ckey, c) - blowfish.ExpandKey(csalt, c) - } - - return c, nil -} - -func (p *hashed) Hash() []byte { - arr := make([]byte, 60) - arr[0] = '$' - arr[1] = p.major - n := 2 - if p.minor != 0 { - arr[2] = p.minor - n = 3 - } - arr[n] = '$' - n++ - copy(arr[n:], []byte(fmt.Sprintf("%02d", p.cost))) - n += 2 - arr[n] = '$' - n++ - copy(arr[n:], p.salt) - n += encodedSaltSize - copy(arr[n:], p.hash) - n += encodedHashSize - return arr[:n] -} - -func (p *hashed) decodeVersion(sbytes []byte) (int, error) { - if sbytes[0] != '$' { - return -1, InvalidHashPrefixError(sbytes[0]) - } - if sbytes[1] > majorVersion { - return -1, HashVersionTooNewError(sbytes[1]) - } - p.major = sbytes[1] - n := 3 - if sbytes[2] != '$' { - p.minor = sbytes[2] - n++ - } - return n, nil -} - -// sbytes should begin where decodeVersion left off. -func (p *hashed) decodeCost(sbytes []byte) (int, error) { - cost, err := strconv.Atoi(string(sbytes[0:2])) - if err != nil { - return -1, err - } - err = checkCost(cost) - if err != nil { - return -1, err - } - p.cost = cost - return 3, nil -} - -func (p *hashed) String() string { - return fmt.Sprintf("&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}", string(p.hash), p.salt, p.cost, p.major, p.minor) -} - -func checkCost(cost int) error { - if cost < MinCost || cost > MaxCost { - return InvalidCostError(cost) - } - return nil -} diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_arm64.go b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.go new file mode 100644 index 00000000000..b799e440b4a --- /dev/null +++ b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.go @@ -0,0 +1,16 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.11,!gccgo,!purego + +package chacha20 + +const bufSize = 256 + +//go:noescape +func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) + +func (c *Cipher) xorKeyStreamBlocks(dst, src []byte) { + xorKeyStreamVX(dst, src, &c.key, &c.nonce, &c.counter) +} diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_arm64.s b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.s new file mode 100644 index 00000000000..891481539a1 --- /dev/null +++ b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.s @@ -0,0 +1,307 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.11,!gccgo,!purego + +#include "textflag.h" + +#define NUM_ROUNDS 10 + +// func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) +TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0 + MOVD dst+0(FP), R1 + MOVD src+24(FP), R2 + MOVD src_len+32(FP), R3 + MOVD key+48(FP), R4 + MOVD nonce+56(FP), R6 + MOVD counter+64(FP), R7 + + MOVD $·constants(SB), R10 + MOVD $·incRotMatrix(SB), R11 + + MOVW (R7), R20 + + AND $~255, R3, R13 + ADD R2, R13, R12 // R12 for block end + AND $255, R3, R13 +loop: + MOVD $NUM_ROUNDS, R21 + VLD1 (R11), [V30.S4, V31.S4] + + // load contants + // VLD4R (R10), [V0.S4, V1.S4, V2.S4, V3.S4] + WORD $0x4D60E940 + + // load keys + // VLD4R 16(R4), [V4.S4, V5.S4, V6.S4, V7.S4] + WORD $0x4DFFE884 + // VLD4R 16(R4), [V8.S4, V9.S4, V10.S4, V11.S4] + WORD $0x4DFFE888 + SUB $32, R4 + + // load counter + nonce + // VLD1R (R7), [V12.S4] + WORD $0x4D40C8EC + + // VLD3R (R6), [V13.S4, V14.S4, V15.S4] + WORD $0x4D40E8CD + + // update counter + VADD V30.S4, V12.S4, V12.S4 + +chacha: + // V0..V3 += V4..V7 + // V12..V15 <<<= ((V12..V15 XOR V0..V3), 16) + VADD V0.S4, V4.S4, V0.S4 + VADD V1.S4, V5.S4, V1.S4 + VADD V2.S4, V6.S4, V2.S4 + VADD V3.S4, V7.S4, V3.S4 + VEOR V12.B16, V0.B16, V12.B16 + VEOR V13.B16, V1.B16, V13.B16 + VEOR V14.B16, V2.B16, V14.B16 + VEOR V15.B16, V3.B16, V15.B16 + VREV32 V12.H8, V12.H8 + VREV32 V13.H8, V13.H8 + VREV32 V14.H8, V14.H8 + VREV32 V15.H8, V15.H8 + // V8..V11 += V12..V15 + // V4..V7 <<<= ((V4..V7 XOR V8..V11), 12) + VADD V8.S4, V12.S4, V8.S4 + VADD V9.S4, V13.S4, V9.S4 + VADD V10.S4, V14.S4, V10.S4 + VADD V11.S4, V15.S4, V11.S4 + VEOR V8.B16, V4.B16, V16.B16 + VEOR V9.B16, V5.B16, V17.B16 + VEOR V10.B16, V6.B16, V18.B16 + VEOR V11.B16, V7.B16, V19.B16 + VSHL $12, V16.S4, V4.S4 + VSHL $12, V17.S4, V5.S4 + VSHL $12, V18.S4, V6.S4 + VSHL $12, V19.S4, V7.S4 + VSRI $20, V16.S4, V4.S4 + VSRI $20, V17.S4, V5.S4 + VSRI $20, V18.S4, V6.S4 + VSRI $20, V19.S4, V7.S4 + + // V0..V3 += V4..V7 + // V12..V15 <<<= ((V12..V15 XOR V0..V3), 8) + VADD V0.S4, V4.S4, V0.S4 + VADD V1.S4, V5.S4, V1.S4 + VADD V2.S4, V6.S4, V2.S4 + VADD V3.S4, V7.S4, V3.S4 + VEOR V12.B16, V0.B16, V12.B16 + VEOR V13.B16, V1.B16, V13.B16 + VEOR V14.B16, V2.B16, V14.B16 + VEOR V15.B16, V3.B16, V15.B16 + VTBL V31.B16, [V12.B16], V12.B16 + VTBL V31.B16, [V13.B16], V13.B16 + VTBL V31.B16, [V14.B16], V14.B16 + VTBL V31.B16, [V15.B16], V15.B16 + + // V8..V11 += V12..V15 + // V4..V7 <<<= ((V4..V7 XOR V8..V11), 7) + VADD V12.S4, V8.S4, V8.S4 + VADD V13.S4, V9.S4, V9.S4 + VADD V14.S4, V10.S4, V10.S4 + VADD V15.S4, V11.S4, V11.S4 + VEOR V8.B16, V4.B16, V16.B16 + VEOR V9.B16, V5.B16, V17.B16 + VEOR V10.B16, V6.B16, V18.B16 + VEOR V11.B16, V7.B16, V19.B16 + VSHL $7, V16.S4, V4.S4 + VSHL $7, V17.S4, V5.S4 + VSHL $7, V18.S4, V6.S4 + VSHL $7, V19.S4, V7.S4 + VSRI $25, V16.S4, V4.S4 + VSRI $25, V17.S4, V5.S4 + VSRI $25, V18.S4, V6.S4 + VSRI $25, V19.S4, V7.S4 + + // V0..V3 += V5..V7, V4 + // V15,V12-V14 <<<= ((V15,V12-V14 XOR V0..V3), 16) + VADD V0.S4, V5.S4, V0.S4 + VADD V1.S4, V6.S4, V1.S4 + VADD V2.S4, V7.S4, V2.S4 + VADD V3.S4, V4.S4, V3.S4 + VEOR V15.B16, V0.B16, V15.B16 + VEOR V12.B16, V1.B16, V12.B16 + VEOR V13.B16, V2.B16, V13.B16 + VEOR V14.B16, V3.B16, V14.B16 + VREV32 V12.H8, V12.H8 + VREV32 V13.H8, V13.H8 + VREV32 V14.H8, V14.H8 + VREV32 V15.H8, V15.H8 + + // V10 += V15; V5 <<<= ((V10 XOR V5), 12) + // ... + VADD V15.S4, V10.S4, V10.S4 + VADD V12.S4, V11.S4, V11.S4 + VADD V13.S4, V8.S4, V8.S4 + VADD V14.S4, V9.S4, V9.S4 + VEOR V10.B16, V5.B16, V16.B16 + VEOR V11.B16, V6.B16, V17.B16 + VEOR V8.B16, V7.B16, V18.B16 + VEOR V9.B16, V4.B16, V19.B16 + VSHL $12, V16.S4, V5.S4 + VSHL $12, V17.S4, V6.S4 + VSHL $12, V18.S4, V7.S4 + VSHL $12, V19.S4, V4.S4 + VSRI $20, V16.S4, V5.S4 + VSRI $20, V17.S4, V6.S4 + VSRI $20, V18.S4, V7.S4 + VSRI $20, V19.S4, V4.S4 + + // V0 += V5; V15 <<<= ((V0 XOR V15), 8) + // ... + VADD V5.S4, V0.S4, V0.S4 + VADD V6.S4, V1.S4, V1.S4 + VADD V7.S4, V2.S4, V2.S4 + VADD V4.S4, V3.S4, V3.S4 + VEOR V0.B16, V15.B16, V15.B16 + VEOR V1.B16, V12.B16, V12.B16 + VEOR V2.B16, V13.B16, V13.B16 + VEOR V3.B16, V14.B16, V14.B16 + VTBL V31.B16, [V12.B16], V12.B16 + VTBL V31.B16, [V13.B16], V13.B16 + VTBL V31.B16, [V14.B16], V14.B16 + VTBL V31.B16, [V15.B16], V15.B16 + + // V10 += V15; V5 <<<= ((V10 XOR V5), 7) + // ... + VADD V15.S4, V10.S4, V10.S4 + VADD V12.S4, V11.S4, V11.S4 + VADD V13.S4, V8.S4, V8.S4 + VADD V14.S4, V9.S4, V9.S4 + VEOR V10.B16, V5.B16, V16.B16 + VEOR V11.B16, V6.B16, V17.B16 + VEOR V8.B16, V7.B16, V18.B16 + VEOR V9.B16, V4.B16, V19.B16 + VSHL $7, V16.S4, V5.S4 + VSHL $7, V17.S4, V6.S4 + VSHL $7, V18.S4, V7.S4 + VSHL $7, V19.S4, V4.S4 + VSRI $25, V16.S4, V5.S4 + VSRI $25, V17.S4, V6.S4 + VSRI $25, V18.S4, V7.S4 + VSRI $25, V19.S4, V4.S4 + + SUB $1, R21 + CBNZ R21, chacha + + // VLD4R (R10), [V16.S4, V17.S4, V18.S4, V19.S4] + WORD $0x4D60E950 + + // VLD4R 16(R4), [V20.S4, V21.S4, V22.S4, V23.S4] + WORD $0x4DFFE894 + VADD V30.S4, V12.S4, V12.S4 + VADD V16.S4, V0.S4, V0.S4 + VADD V17.S4, V1.S4, V1.S4 + VADD V18.S4, V2.S4, V2.S4 + VADD V19.S4, V3.S4, V3.S4 + // VLD4R 16(R4), [V24.S4, V25.S4, V26.S4, V27.S4] + WORD $0x4DFFE898 + // restore R4 + SUB $32, R4 + + // load counter + nonce + // VLD1R (R7), [V28.S4] + WORD $0x4D40C8FC + // VLD3R (R6), [V29.S4, V30.S4, V31.S4] + WORD $0x4D40E8DD + + VADD V20.S4, V4.S4, V4.S4 + VADD V21.S4, V5.S4, V5.S4 + VADD V22.S4, V6.S4, V6.S4 + VADD V23.S4, V7.S4, V7.S4 + VADD V24.S4, V8.S4, V8.S4 + VADD V25.S4, V9.S4, V9.S4 + VADD V26.S4, V10.S4, V10.S4 + VADD V27.S4, V11.S4, V11.S4 + VADD V28.S4, V12.S4, V12.S4 + VADD V29.S4, V13.S4, V13.S4 + VADD V30.S4, V14.S4, V14.S4 + VADD V31.S4, V15.S4, V15.S4 + + VZIP1 V1.S4, V0.S4, V16.S4 + VZIP2 V1.S4, V0.S4, V17.S4 + VZIP1 V3.S4, V2.S4, V18.S4 + VZIP2 V3.S4, V2.S4, V19.S4 + VZIP1 V5.S4, V4.S4, V20.S4 + VZIP2 V5.S4, V4.S4, V21.S4 + VZIP1 V7.S4, V6.S4, V22.S4 + VZIP2 V7.S4, V6.S4, V23.S4 + VZIP1 V9.S4, V8.S4, V24.S4 + VZIP2 V9.S4, V8.S4, V25.S4 + VZIP1 V11.S4, V10.S4, V26.S4 + VZIP2 V11.S4, V10.S4, V27.S4 + VZIP1 V13.S4, V12.S4, V28.S4 + VZIP2 V13.S4, V12.S4, V29.S4 + VZIP1 V15.S4, V14.S4, V30.S4 + VZIP2 V15.S4, V14.S4, V31.S4 + VZIP1 V18.D2, V16.D2, V0.D2 + VZIP2 V18.D2, V16.D2, V4.D2 + VZIP1 V19.D2, V17.D2, V8.D2 + VZIP2 V19.D2, V17.D2, V12.D2 + VLD1.P 64(R2), [V16.B16, V17.B16, V18.B16, V19.B16] + + VZIP1 V22.D2, V20.D2, V1.D2 + VZIP2 V22.D2, V20.D2, V5.D2 + VZIP1 V23.D2, V21.D2, V9.D2 + VZIP2 V23.D2, V21.D2, V13.D2 + VLD1.P 64(R2), [V20.B16, V21.B16, V22.B16, V23.B16] + VZIP1 V26.D2, V24.D2, V2.D2 + VZIP2 V26.D2, V24.D2, V6.D2 + VZIP1 V27.D2, V25.D2, V10.D2 + VZIP2 V27.D2, V25.D2, V14.D2 + VLD1.P 64(R2), [V24.B16, V25.B16, V26.B16, V27.B16] + VZIP1 V30.D2, V28.D2, V3.D2 + VZIP2 V30.D2, V28.D2, V7.D2 + VZIP1 V31.D2, V29.D2, V11.D2 + VZIP2 V31.D2, V29.D2, V15.D2 + VLD1.P 64(R2), [V28.B16, V29.B16, V30.B16, V31.B16] + VEOR V0.B16, V16.B16, V16.B16 + VEOR V1.B16, V17.B16, V17.B16 + VEOR V2.B16, V18.B16, V18.B16 + VEOR V3.B16, V19.B16, V19.B16 + VST1.P [V16.B16, V17.B16, V18.B16, V19.B16], 64(R1) + VEOR V4.B16, V20.B16, V20.B16 + VEOR V5.B16, V21.B16, V21.B16 + VEOR V6.B16, V22.B16, V22.B16 + VEOR V7.B16, V23.B16, V23.B16 + VST1.P [V20.B16, V21.B16, V22.B16, V23.B16], 64(R1) + VEOR V8.B16, V24.B16, V24.B16 + VEOR V9.B16, V25.B16, V25.B16 + VEOR V10.B16, V26.B16, V26.B16 + VEOR V11.B16, V27.B16, V27.B16 + VST1.P [V24.B16, V25.B16, V26.B16, V27.B16], 64(R1) + VEOR V12.B16, V28.B16, V28.B16 + VEOR V13.B16, V29.B16, V29.B16 + VEOR V14.B16, V30.B16, V30.B16 + VEOR V15.B16, V31.B16, V31.B16 + VST1.P [V28.B16, V29.B16, V30.B16, V31.B16], 64(R1) + + ADD $4, R20 + MOVW R20, (R7) // update counter + + CMP R2, R12 + BGT loop + + RET + + +DATA ·constants+0x00(SB)/4, $0x61707865 +DATA ·constants+0x04(SB)/4, $0x3320646e +DATA ·constants+0x08(SB)/4, $0x79622d32 +DATA ·constants+0x0c(SB)/4, $0x6b206574 +GLOBL ·constants(SB), NOPTR|RODATA, $32 + +DATA ·incRotMatrix+0x00(SB)/4, $0x00000000 +DATA ·incRotMatrix+0x04(SB)/4, $0x00000001 +DATA ·incRotMatrix+0x08(SB)/4, $0x00000002 +DATA ·incRotMatrix+0x0c(SB)/4, $0x00000003 +DATA ·incRotMatrix+0x10(SB)/4, $0x02010003 +DATA ·incRotMatrix+0x14(SB)/4, $0x06050407 +DATA ·incRotMatrix+0x18(SB)/4, $0x0A09080B +DATA ·incRotMatrix+0x1c(SB)/4, $0x0E0D0C0F +GLOBL ·incRotMatrix(SB), NOPTR|RODATA, $32 diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_generic.go b/vendor/golang.org/x/crypto/chacha20/chacha_generic.go new file mode 100644 index 00000000000..a2ecf5c325b --- /dev/null +++ b/vendor/golang.org/x/crypto/chacha20/chacha_generic.go @@ -0,0 +1,398 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package chacha20 implements the ChaCha20 and XChaCha20 encryption algorithms +// as specified in RFC 8439 and draft-irtf-cfrg-xchacha-01. +package chacha20 + +import ( + "crypto/cipher" + "encoding/binary" + "errors" + "math/bits" + + "golang.org/x/crypto/internal/subtle" +) + +const ( + // KeySize is the size of the key used by this cipher, in bytes. + KeySize = 32 + + // NonceSize is the size of the nonce used with the standard variant of this + // cipher, in bytes. + // + // Note that this is too short to be safely generated at random if the same + // key is reused more than 2³² times. + NonceSize = 12 + + // NonceSizeX is the size of the nonce used with the XChaCha20 variant of + // this cipher, in bytes. + NonceSizeX = 24 +) + +// Cipher is a stateful instance of ChaCha20 or XChaCha20 using a particular key +// and nonce. A *Cipher implements the cipher.Stream interface. +type Cipher struct { + // The ChaCha20 state is 16 words: 4 constant, 8 of key, 1 of counter + // (incremented after each block), and 3 of nonce. + key [8]uint32 + counter uint32 + nonce [3]uint32 + + // The last len bytes of buf are leftover key stream bytes from the previous + // XORKeyStream invocation. The size of buf depends on how many blocks are + // computed at a time by xorKeyStreamBlocks. + buf [bufSize]byte + len int + + // overflow is set when the counter overflowed, no more blocks can be + // generated, and the next XORKeyStream call should panic. + overflow bool + + // The counter-independent results of the first round are cached after they + // are computed the first time. + precompDone bool + p1, p5, p9, p13 uint32 + p2, p6, p10, p14 uint32 + p3, p7, p11, p15 uint32 +} + +var _ cipher.Stream = (*Cipher)(nil) + +// NewUnauthenticatedCipher creates a new ChaCha20 stream cipher with the given +// 32 bytes key and a 12 or 24 bytes nonce. If a nonce of 24 bytes is provided, +// the XChaCha20 construction will be used. It returns an error if key or nonce +// have any other length. +// +// Note that ChaCha20, like all stream ciphers, is not authenticated and allows +// attackers to silently tamper with the plaintext. For this reason, it is more +// appropriate as a building block than as a standalone encryption mechanism. +// Instead, consider using package golang.org/x/crypto/chacha20poly1305. +func NewUnauthenticatedCipher(key, nonce []byte) (*Cipher, error) { + // This function is split into a wrapper so that the Cipher allocation will + // be inlined, and depending on how the caller uses the return value, won't + // escape to the heap. + c := &Cipher{} + return newUnauthenticatedCipher(c, key, nonce) +} + +func newUnauthenticatedCipher(c *Cipher, key, nonce []byte) (*Cipher, error) { + if len(key) != KeySize { + return nil, errors.New("chacha20: wrong key size") + } + if len(nonce) == NonceSizeX { + // XChaCha20 uses the ChaCha20 core to mix 16 bytes of the nonce into a + // derived key, allowing it to operate on a nonce of 24 bytes. See + // draft-irtf-cfrg-xchacha-01, Section 2.3. + key, _ = HChaCha20(key, nonce[0:16]) + cNonce := make([]byte, NonceSize) + copy(cNonce[4:12], nonce[16:24]) + nonce = cNonce + } else if len(nonce) != NonceSize { + return nil, errors.New("chacha20: wrong nonce size") + } + + key, nonce = key[:KeySize], nonce[:NonceSize] // bounds check elimination hint + c.key = [8]uint32{ + binary.LittleEndian.Uint32(key[0:4]), + binary.LittleEndian.Uint32(key[4:8]), + binary.LittleEndian.Uint32(key[8:12]), + binary.LittleEndian.Uint32(key[12:16]), + binary.LittleEndian.Uint32(key[16:20]), + binary.LittleEndian.Uint32(key[20:24]), + binary.LittleEndian.Uint32(key[24:28]), + binary.LittleEndian.Uint32(key[28:32]), + } + c.nonce = [3]uint32{ + binary.LittleEndian.Uint32(nonce[0:4]), + binary.LittleEndian.Uint32(nonce[4:8]), + binary.LittleEndian.Uint32(nonce[8:12]), + } + return c, nil +} + +// The constant first 4 words of the ChaCha20 state. +const ( + j0 uint32 = 0x61707865 // expa + j1 uint32 = 0x3320646e // nd 3 + j2 uint32 = 0x79622d32 // 2-by + j3 uint32 = 0x6b206574 // te k +) + +const blockSize = 64 + +// quarterRound is the core of ChaCha20. It shuffles the bits of 4 state words. +// It's executed 4 times for each of the 20 ChaCha20 rounds, operating on all 16 +// words each round, in columnar or diagonal groups of 4 at a time. +func quarterRound(a, b, c, d uint32) (uint32, uint32, uint32, uint32) { + a += b + d ^= a + d = bits.RotateLeft32(d, 16) + c += d + b ^= c + b = bits.RotateLeft32(b, 12) + a += b + d ^= a + d = bits.RotateLeft32(d, 8) + c += d + b ^= c + b = bits.RotateLeft32(b, 7) + return a, b, c, d +} + +// SetCounter sets the Cipher counter. The next invocation of XORKeyStream will +// behave as if (64 * counter) bytes had been encrypted so far. +// +// To prevent accidental counter reuse, SetCounter panics if counter is less +// than the current value. +// +// Note that the execution time of XORKeyStream is not independent of the +// counter value. +func (s *Cipher) SetCounter(counter uint32) { + // Internally, s may buffer multiple blocks, which complicates this + // implementation slightly. When checking whether the counter has rolled + // back, we must use both s.counter and s.len to determine how many blocks + // we have already output. + outputCounter := s.counter - uint32(s.len)/blockSize + if s.overflow || counter < outputCounter { + panic("chacha20: SetCounter attempted to rollback counter") + } + + // In the general case, we set the new counter value and reset s.len to 0, + // causing the next call to XORKeyStream to refill the buffer. However, if + // we're advancing within the existing buffer, we can save work by simply + // setting s.len. + if counter < s.counter { + s.len = int(s.counter-counter) * blockSize + } else { + s.counter = counter + s.len = 0 + } +} + +// XORKeyStream XORs each byte in the given slice with a byte from the +// cipher's key stream. Dst and src must overlap entirely or not at all. +// +// If len(dst) < len(src), XORKeyStream will panic. It is acceptable +// to pass a dst bigger than src, and in that case, XORKeyStream will +// only update dst[:len(src)] and will not touch the rest of dst. +// +// Multiple calls to XORKeyStream behave as if the concatenation of +// the src buffers was passed in a single run. That is, Cipher +// maintains state and does not reset at each XORKeyStream call. +func (s *Cipher) XORKeyStream(dst, src []byte) { + if len(src) == 0 { + return + } + if len(dst) < len(src) { + panic("chacha20: output smaller than input") + } + dst = dst[:len(src)] + if subtle.InexactOverlap(dst, src) { + panic("chacha20: invalid buffer overlap") + } + + // First, drain any remaining key stream from a previous XORKeyStream. + if s.len != 0 { + keyStream := s.buf[bufSize-s.len:] + if len(src) < len(keyStream) { + keyStream = keyStream[:len(src)] + } + _ = src[len(keyStream)-1] // bounds check elimination hint + for i, b := range keyStream { + dst[i] = src[i] ^ b + } + s.len -= len(keyStream) + dst, src = dst[len(keyStream):], src[len(keyStream):] + } + if len(src) == 0 { + return + } + + // If we'd need to let the counter overflow and keep generating output, + // panic immediately. If instead we'd only reach the last block, remember + // not to generate any more output after the buffer is drained. + numBlocks := (uint64(len(src)) + blockSize - 1) / blockSize + if s.overflow || uint64(s.counter)+numBlocks > 1<<32 { + panic("chacha20: counter overflow") + } else if uint64(s.counter)+numBlocks == 1<<32 { + s.overflow = true + } + + // xorKeyStreamBlocks implementations expect input lengths that are a + // multiple of bufSize. Platform-specific ones process multiple blocks at a + // time, so have bufSizes that are a multiple of blockSize. + + full := len(src) - len(src)%bufSize + if full > 0 { + s.xorKeyStreamBlocks(dst[:full], src[:full]) + } + dst, src = dst[full:], src[full:] + + // If using a multi-block xorKeyStreamBlocks would overflow, use the generic + // one that does one block at a time. + const blocksPerBuf = bufSize / blockSize + if uint64(s.counter)+blocksPerBuf > 1<<32 { + s.buf = [bufSize]byte{} + numBlocks := (len(src) + blockSize - 1) / blockSize + buf := s.buf[bufSize-numBlocks*blockSize:] + copy(buf, src) + s.xorKeyStreamBlocksGeneric(buf, buf) + s.len = len(buf) - copy(dst, buf) + return + } + + // If we have a partial (multi-)block, pad it for xorKeyStreamBlocks, and + // keep the leftover keystream for the next XORKeyStream invocation. + if len(src) > 0 { + s.buf = [bufSize]byte{} + copy(s.buf[:], src) + s.xorKeyStreamBlocks(s.buf[:], s.buf[:]) + s.len = bufSize - copy(dst, s.buf[:]) + } +} + +func (s *Cipher) xorKeyStreamBlocksGeneric(dst, src []byte) { + if len(dst) != len(src) || len(dst)%blockSize != 0 { + panic("chacha20: internal error: wrong dst and/or src length") + } + + // To generate each block of key stream, the initial cipher state + // (represented below) is passed through 20 rounds of shuffling, + // alternatively applying quarterRounds by columns (like 1, 5, 9, 13) + // or by diagonals (like 1, 6, 11, 12). + // + // 0:cccccccc 1:cccccccc 2:cccccccc 3:cccccccc + // 4:kkkkkkkk 5:kkkkkkkk 6:kkkkkkkk 7:kkkkkkkk + // 8:kkkkkkkk 9:kkkkkkkk 10:kkkkkkkk 11:kkkkkkkk + // 12:bbbbbbbb 13:nnnnnnnn 14:nnnnnnnn 15:nnnnnnnn + // + // c=constant k=key b=blockcount n=nonce + var ( + c0, c1, c2, c3 = j0, j1, j2, j3 + c4, c5, c6, c7 = s.key[0], s.key[1], s.key[2], s.key[3] + c8, c9, c10, c11 = s.key[4], s.key[5], s.key[6], s.key[7] + _, c13, c14, c15 = s.counter, s.nonce[0], s.nonce[1], s.nonce[2] + ) + + // Three quarters of the first round don't depend on the counter, so we can + // calculate them here, and reuse them for multiple blocks in the loop, and + // for future XORKeyStream invocations. + if !s.precompDone { + s.p1, s.p5, s.p9, s.p13 = quarterRound(c1, c5, c9, c13) + s.p2, s.p6, s.p10, s.p14 = quarterRound(c2, c6, c10, c14) + s.p3, s.p7, s.p11, s.p15 = quarterRound(c3, c7, c11, c15) + s.precompDone = true + } + + // A condition of len(src) > 0 would be sufficient, but this also + // acts as a bounds check elimination hint. + for len(src) >= 64 && len(dst) >= 64 { + // The remainder of the first column round. + fcr0, fcr4, fcr8, fcr12 := quarterRound(c0, c4, c8, s.counter) + + // The second diagonal round. + x0, x5, x10, x15 := quarterRound(fcr0, s.p5, s.p10, s.p15) + x1, x6, x11, x12 := quarterRound(s.p1, s.p6, s.p11, fcr12) + x2, x7, x8, x13 := quarterRound(s.p2, s.p7, fcr8, s.p13) + x3, x4, x9, x14 := quarterRound(s.p3, fcr4, s.p9, s.p14) + + // The remaining 18 rounds. + for i := 0; i < 9; i++ { + // Column round. + x0, x4, x8, x12 = quarterRound(x0, x4, x8, x12) + x1, x5, x9, x13 = quarterRound(x1, x5, x9, x13) + x2, x6, x10, x14 = quarterRound(x2, x6, x10, x14) + x3, x7, x11, x15 = quarterRound(x3, x7, x11, x15) + + // Diagonal round. + x0, x5, x10, x15 = quarterRound(x0, x5, x10, x15) + x1, x6, x11, x12 = quarterRound(x1, x6, x11, x12) + x2, x7, x8, x13 = quarterRound(x2, x7, x8, x13) + x3, x4, x9, x14 = quarterRound(x3, x4, x9, x14) + } + + // Add back the initial state to generate the key stream, then + // XOR the key stream with the source and write out the result. + addXor(dst[0:4], src[0:4], x0, c0) + addXor(dst[4:8], src[4:8], x1, c1) + addXor(dst[8:12], src[8:12], x2, c2) + addXor(dst[12:16], src[12:16], x3, c3) + addXor(dst[16:20], src[16:20], x4, c4) + addXor(dst[20:24], src[20:24], x5, c5) + addXor(dst[24:28], src[24:28], x6, c6) + addXor(dst[28:32], src[28:32], x7, c7) + addXor(dst[32:36], src[32:36], x8, c8) + addXor(dst[36:40], src[36:40], x9, c9) + addXor(dst[40:44], src[40:44], x10, c10) + addXor(dst[44:48], src[44:48], x11, c11) + addXor(dst[48:52], src[48:52], x12, s.counter) + addXor(dst[52:56], src[52:56], x13, c13) + addXor(dst[56:60], src[56:60], x14, c14) + addXor(dst[60:64], src[60:64], x15, c15) + + s.counter += 1 + + src, dst = src[blockSize:], dst[blockSize:] + } +} + +// HChaCha20 uses the ChaCha20 core to generate a derived key from a 32 bytes +// key and a 16 bytes nonce. It returns an error if key or nonce have any other +// length. It is used as part of the XChaCha20 construction. +func HChaCha20(key, nonce []byte) ([]byte, error) { + // This function is split into a wrapper so that the slice allocation will + // be inlined, and depending on how the caller uses the return value, won't + // escape to the heap. + out := make([]byte, 32) + return hChaCha20(out, key, nonce) +} + +func hChaCha20(out, key, nonce []byte) ([]byte, error) { + if len(key) != KeySize { + return nil, errors.New("chacha20: wrong HChaCha20 key size") + } + if len(nonce) != 16 { + return nil, errors.New("chacha20: wrong HChaCha20 nonce size") + } + + x0, x1, x2, x3 := j0, j1, j2, j3 + x4 := binary.LittleEndian.Uint32(key[0:4]) + x5 := binary.LittleEndian.Uint32(key[4:8]) + x6 := binary.LittleEndian.Uint32(key[8:12]) + x7 := binary.LittleEndian.Uint32(key[12:16]) + x8 := binary.LittleEndian.Uint32(key[16:20]) + x9 := binary.LittleEndian.Uint32(key[20:24]) + x10 := binary.LittleEndian.Uint32(key[24:28]) + x11 := binary.LittleEndian.Uint32(key[28:32]) + x12 := binary.LittleEndian.Uint32(nonce[0:4]) + x13 := binary.LittleEndian.Uint32(nonce[4:8]) + x14 := binary.LittleEndian.Uint32(nonce[8:12]) + x15 := binary.LittleEndian.Uint32(nonce[12:16]) + + for i := 0; i < 10; i++ { + // Diagonal round. + x0, x4, x8, x12 = quarterRound(x0, x4, x8, x12) + x1, x5, x9, x13 = quarterRound(x1, x5, x9, x13) + x2, x6, x10, x14 = quarterRound(x2, x6, x10, x14) + x3, x7, x11, x15 = quarterRound(x3, x7, x11, x15) + + // Column round. + x0, x5, x10, x15 = quarterRound(x0, x5, x10, x15) + x1, x6, x11, x12 = quarterRound(x1, x6, x11, x12) + x2, x7, x8, x13 = quarterRound(x2, x7, x8, x13) + x3, x4, x9, x14 = quarterRound(x3, x4, x9, x14) + } + + _ = out[31] // bounds check elimination hint + binary.LittleEndian.PutUint32(out[0:4], x0) + binary.LittleEndian.PutUint32(out[4:8], x1) + binary.LittleEndian.PutUint32(out[8:12], x2) + binary.LittleEndian.PutUint32(out[12:16], x3) + binary.LittleEndian.PutUint32(out[16:20], x12) + binary.LittleEndian.PutUint32(out[20:24], x13) + binary.LittleEndian.PutUint32(out[24:28], x14) + binary.LittleEndian.PutUint32(out[28:32], x15) + return out, nil +} diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go b/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go new file mode 100644 index 00000000000..4635307b8f2 --- /dev/null +++ b/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go @@ -0,0 +1,13 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !arm64,!s390x,!ppc64le arm64,!go1.11 gccgo purego + +package chacha20 + +const bufSize = blockSize + +func (s *Cipher) xorKeyStreamBlocks(dst, src []byte) { + s.xorKeyStreamBlocksGeneric(dst, src) +} diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.go b/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.go new file mode 100644 index 00000000000..b7993303415 --- /dev/null +++ b/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.go @@ -0,0 +1,16 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !gccgo,!purego + +package chacha20 + +const bufSize = 256 + +//go:noescape +func chaCha20_ctr32_vsx(out, inp *byte, len int, key *[8]uint32, counter *uint32) + +func (c *Cipher) xorKeyStreamBlocks(dst, src []byte) { + chaCha20_ctr32_vsx(&dst[0], &src[0], len(src), &c.key, &c.counter) +} diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.s b/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.s new file mode 100644 index 00000000000..23c60216430 --- /dev/null +++ b/vendor/golang.org/x/crypto/chacha20/chacha_ppc64le.s @@ -0,0 +1,449 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Based on CRYPTOGAMS code with the following comment: +// # ==================================================================== +// # Written by Andy Polyakov for the OpenSSL +// # project. The module is, however, dual licensed under OpenSSL and +// # CRYPTOGAMS licenses depending on where you obtain it. For further +// # details see http://www.openssl.org/~appro/cryptogams/. +// # ==================================================================== + +// Code for the perl script that generates the ppc64 assembler +// can be found in the cryptogams repository at the link below. It is based on +// the original from openssl. + +// https://github.com/dot-asm/cryptogams/commit/a60f5b50ed908e91 + +// The differences in this and the original implementation are +// due to the calling conventions and initialization of constants. + +// +build !gccgo,!purego + +#include "textflag.h" + +#define OUT R3 +#define INP R4 +#define LEN R5 +#define KEY R6 +#define CNT R7 +#define TMP R15 + +#define CONSTBASE R16 +#define BLOCKS R17 + +DATA consts<>+0x00(SB)/8, $0x3320646e61707865 +DATA consts<>+0x08(SB)/8, $0x6b20657479622d32 +DATA consts<>+0x10(SB)/8, $0x0000000000000001 +DATA consts<>+0x18(SB)/8, $0x0000000000000000 +DATA consts<>+0x20(SB)/8, $0x0000000000000004 +DATA consts<>+0x28(SB)/8, $0x0000000000000000 +DATA consts<>+0x30(SB)/8, $0x0a0b08090e0f0c0d +DATA consts<>+0x38(SB)/8, $0x0203000106070405 +DATA consts<>+0x40(SB)/8, $0x090a0b080d0e0f0c +DATA consts<>+0x48(SB)/8, $0x0102030005060704 +DATA consts<>+0x50(SB)/8, $0x6170786561707865 +DATA consts<>+0x58(SB)/8, $0x6170786561707865 +DATA consts<>+0x60(SB)/8, $0x3320646e3320646e +DATA consts<>+0x68(SB)/8, $0x3320646e3320646e +DATA consts<>+0x70(SB)/8, $0x79622d3279622d32 +DATA consts<>+0x78(SB)/8, $0x79622d3279622d32 +DATA consts<>+0x80(SB)/8, $0x6b2065746b206574 +DATA consts<>+0x88(SB)/8, $0x6b2065746b206574 +DATA consts<>+0x90(SB)/8, $0x0000000100000000 +DATA consts<>+0x98(SB)/8, $0x0000000300000002 +GLOBL consts<>(SB), RODATA, $0xa0 + +//func chaCha20_ctr32_vsx(out, inp *byte, len int, key *[8]uint32, counter *uint32) +TEXT ·chaCha20_ctr32_vsx(SB),NOSPLIT,$64-40 + MOVD out+0(FP), OUT + MOVD inp+8(FP), INP + MOVD len+16(FP), LEN + MOVD key+24(FP), KEY + MOVD counter+32(FP), CNT + + // Addressing for constants + MOVD $consts<>+0x00(SB), CONSTBASE + MOVD $16, R8 + MOVD $32, R9 + MOVD $48, R10 + MOVD $64, R11 + SRD $6, LEN, BLOCKS + // V16 + LXVW4X (CONSTBASE)(R0), VS48 + ADD $80,CONSTBASE + + // Load key into V17,V18 + LXVW4X (KEY)(R0), VS49 + LXVW4X (KEY)(R8), VS50 + + // Load CNT, NONCE into V19 + LXVW4X (CNT)(R0), VS51 + + // Clear V27 + VXOR V27, V27, V27 + + // V28 + LXVW4X (CONSTBASE)(R11), VS60 + + // splat slot from V19 -> V26 + VSPLTW $0, V19, V26 + + VSLDOI $4, V19, V27, V19 + VSLDOI $12, V27, V19, V19 + + VADDUWM V26, V28, V26 + + MOVD $10, R14 + MOVD R14, CTR + +loop_outer_vsx: + // V0, V1, V2, V3 + LXVW4X (R0)(CONSTBASE), VS32 + LXVW4X (R8)(CONSTBASE), VS33 + LXVW4X (R9)(CONSTBASE), VS34 + LXVW4X (R10)(CONSTBASE), VS35 + + // splat values from V17, V18 into V4-V11 + VSPLTW $0, V17, V4 + VSPLTW $1, V17, V5 + VSPLTW $2, V17, V6 + VSPLTW $3, V17, V7 + VSPLTW $0, V18, V8 + VSPLTW $1, V18, V9 + VSPLTW $2, V18, V10 + VSPLTW $3, V18, V11 + + // VOR + VOR V26, V26, V12 + + // splat values from V19 -> V13, V14, V15 + VSPLTW $1, V19, V13 + VSPLTW $2, V19, V14 + VSPLTW $3, V19, V15 + + // splat const values + VSPLTISW $-16, V27 + VSPLTISW $12, V28 + VSPLTISW $8, V29 + VSPLTISW $7, V30 + +loop_vsx: + VADDUWM V0, V4, V0 + VADDUWM V1, V5, V1 + VADDUWM V2, V6, V2 + VADDUWM V3, V7, V3 + + VXOR V12, V0, V12 + VXOR V13, V1, V13 + VXOR V14, V2, V14 + VXOR V15, V3, V15 + + VRLW V12, V27, V12 + VRLW V13, V27, V13 + VRLW V14, V27, V14 + VRLW V15, V27, V15 + + VADDUWM V8, V12, V8 + VADDUWM V9, V13, V9 + VADDUWM V10, V14, V10 + VADDUWM V11, V15, V11 + + VXOR V4, V8, V4 + VXOR V5, V9, V5 + VXOR V6, V10, V6 + VXOR V7, V11, V7 + + VRLW V4, V28, V4 + VRLW V5, V28, V5 + VRLW V6, V28, V6 + VRLW V7, V28, V7 + + VADDUWM V0, V4, V0 + VADDUWM V1, V5, V1 + VADDUWM V2, V6, V2 + VADDUWM V3, V7, V3 + + VXOR V12, V0, V12 + VXOR V13, V1, V13 + VXOR V14, V2, V14 + VXOR V15, V3, V15 + + VRLW V12, V29, V12 + VRLW V13, V29, V13 + VRLW V14, V29, V14 + VRLW V15, V29, V15 + + VADDUWM V8, V12, V8 + VADDUWM V9, V13, V9 + VADDUWM V10, V14, V10 + VADDUWM V11, V15, V11 + + VXOR V4, V8, V4 + VXOR V5, V9, V5 + VXOR V6, V10, V6 + VXOR V7, V11, V7 + + VRLW V4, V30, V4 + VRLW V5, V30, V5 + VRLW V6, V30, V6 + VRLW V7, V30, V7 + + VADDUWM V0, V5, V0 + VADDUWM V1, V6, V1 + VADDUWM V2, V7, V2 + VADDUWM V3, V4, V3 + + VXOR V15, V0, V15 + VXOR V12, V1, V12 + VXOR V13, V2, V13 + VXOR V14, V3, V14 + + VRLW V15, V27, V15 + VRLW V12, V27, V12 + VRLW V13, V27, V13 + VRLW V14, V27, V14 + + VADDUWM V10, V15, V10 + VADDUWM V11, V12, V11 + VADDUWM V8, V13, V8 + VADDUWM V9, V14, V9 + + VXOR V5, V10, V5 + VXOR V6, V11, V6 + VXOR V7, V8, V7 + VXOR V4, V9, V4 + + VRLW V5, V28, V5 + VRLW V6, V28, V6 + VRLW V7, V28, V7 + VRLW V4, V28, V4 + + VADDUWM V0, V5, V0 + VADDUWM V1, V6, V1 + VADDUWM V2, V7, V2 + VADDUWM V3, V4, V3 + + VXOR V15, V0, V15 + VXOR V12, V1, V12 + VXOR V13, V2, V13 + VXOR V14, V3, V14 + + VRLW V15, V29, V15 + VRLW V12, V29, V12 + VRLW V13, V29, V13 + VRLW V14, V29, V14 + + VADDUWM V10, V15, V10 + VADDUWM V11, V12, V11 + VADDUWM V8, V13, V8 + VADDUWM V9, V14, V9 + + VXOR V5, V10, V5 + VXOR V6, V11, V6 + VXOR V7, V8, V7 + VXOR V4, V9, V4 + + VRLW V5, V30, V5 + VRLW V6, V30, V6 + VRLW V7, V30, V7 + VRLW V4, V30, V4 + BC 16, LT, loop_vsx + + VADDUWM V12, V26, V12 + + WORD $0x13600F8C // VMRGEW V0, V1, V27 + WORD $0x13821F8C // VMRGEW V2, V3, V28 + + WORD $0x10000E8C // VMRGOW V0, V1, V0 + WORD $0x10421E8C // VMRGOW V2, V3, V2 + + WORD $0x13A42F8C // VMRGEW V4, V5, V29 + WORD $0x13C63F8C // VMRGEW V6, V7, V30 + + XXPERMDI VS32, VS34, $0, VS33 + XXPERMDI VS32, VS34, $3, VS35 + XXPERMDI VS59, VS60, $0, VS32 + XXPERMDI VS59, VS60, $3, VS34 + + WORD $0x10842E8C // VMRGOW V4, V5, V4 + WORD $0x10C63E8C // VMRGOW V6, V7, V6 + + WORD $0x13684F8C // VMRGEW V8, V9, V27 + WORD $0x138A5F8C // VMRGEW V10, V11, V28 + + XXPERMDI VS36, VS38, $0, VS37 + XXPERMDI VS36, VS38, $3, VS39 + XXPERMDI VS61, VS62, $0, VS36 + XXPERMDI VS61, VS62, $3, VS38 + + WORD $0x11084E8C // VMRGOW V8, V9, V8 + WORD $0x114A5E8C // VMRGOW V10, V11, V10 + + WORD $0x13AC6F8C // VMRGEW V12, V13, V29 + WORD $0x13CE7F8C // VMRGEW V14, V15, V30 + + XXPERMDI VS40, VS42, $0, VS41 + XXPERMDI VS40, VS42, $3, VS43 + XXPERMDI VS59, VS60, $0, VS40 + XXPERMDI VS59, VS60, $3, VS42 + + WORD $0x118C6E8C // VMRGOW V12, V13, V12 + WORD $0x11CE7E8C // VMRGOW V14, V15, V14 + + VSPLTISW $4, V27 + VADDUWM V26, V27, V26 + + XXPERMDI VS44, VS46, $0, VS45 + XXPERMDI VS44, VS46, $3, VS47 + XXPERMDI VS61, VS62, $0, VS44 + XXPERMDI VS61, VS62, $3, VS46 + + VADDUWM V0, V16, V0 + VADDUWM V4, V17, V4 + VADDUWM V8, V18, V8 + VADDUWM V12, V19, V12 + + CMPU LEN, $64 + BLT tail_vsx + + // Bottom of loop + LXVW4X (INP)(R0), VS59 + LXVW4X (INP)(R8), VS60 + LXVW4X (INP)(R9), VS61 + LXVW4X (INP)(R10), VS62 + + VXOR V27, V0, V27 + VXOR V28, V4, V28 + VXOR V29, V8, V29 + VXOR V30, V12, V30 + + STXVW4X VS59, (OUT)(R0) + STXVW4X VS60, (OUT)(R8) + ADD $64, INP + STXVW4X VS61, (OUT)(R9) + ADD $-64, LEN + STXVW4X VS62, (OUT)(R10) + ADD $64, OUT + BEQ done_vsx + + VADDUWM V1, V16, V0 + VADDUWM V5, V17, V4 + VADDUWM V9, V18, V8 + VADDUWM V13, V19, V12 + + CMPU LEN, $64 + BLT tail_vsx + + LXVW4X (INP)(R0), VS59 + LXVW4X (INP)(R8), VS60 + LXVW4X (INP)(R9), VS61 + LXVW4X (INP)(R10), VS62 + VXOR V27, V0, V27 + + VXOR V28, V4, V28 + VXOR V29, V8, V29 + VXOR V30, V12, V30 + + STXVW4X VS59, (OUT)(R0) + STXVW4X VS60, (OUT)(R8) + ADD $64, INP + STXVW4X VS61, (OUT)(R9) + ADD $-64, LEN + STXVW4X VS62, (OUT)(V10) + ADD $64, OUT + BEQ done_vsx + + VADDUWM V2, V16, V0 + VADDUWM V6, V17, V4 + VADDUWM V10, V18, V8 + VADDUWM V14, V19, V12 + + CMPU LEN, $64 + BLT tail_vsx + + LXVW4X (INP)(R0), VS59 + LXVW4X (INP)(R8), VS60 + LXVW4X (INP)(R9), VS61 + LXVW4X (INP)(R10), VS62 + + VXOR V27, V0, V27 + VXOR V28, V4, V28 + VXOR V29, V8, V29 + VXOR V30, V12, V30 + + STXVW4X VS59, (OUT)(R0) + STXVW4X VS60, (OUT)(R8) + ADD $64, INP + STXVW4X VS61, (OUT)(R9) + ADD $-64, LEN + STXVW4X VS62, (OUT)(R10) + ADD $64, OUT + BEQ done_vsx + + VADDUWM V3, V16, V0 + VADDUWM V7, V17, V4 + VADDUWM V11, V18, V8 + VADDUWM V15, V19, V12 + + CMPU LEN, $64 + BLT tail_vsx + + LXVW4X (INP)(R0), VS59 + LXVW4X (INP)(R8), VS60 + LXVW4X (INP)(R9), VS61 + LXVW4X (INP)(R10), VS62 + + VXOR V27, V0, V27 + VXOR V28, V4, V28 + VXOR V29, V8, V29 + VXOR V30, V12, V30 + + STXVW4X VS59, (OUT)(R0) + STXVW4X VS60, (OUT)(R8) + ADD $64, INP + STXVW4X VS61, (OUT)(R9) + ADD $-64, LEN + STXVW4X VS62, (OUT)(R10) + ADD $64, OUT + + MOVD $10, R14 + MOVD R14, CTR + BNE loop_outer_vsx + +done_vsx: + // Increment counter by number of 64 byte blocks + MOVD (CNT), R14 + ADD BLOCKS, R14 + MOVD R14, (CNT) + RET + +tail_vsx: + ADD $32, R1, R11 + MOVD LEN, CTR + + // Save values on stack to copy from + STXVW4X VS32, (R11)(R0) + STXVW4X VS36, (R11)(R8) + STXVW4X VS40, (R11)(R9) + STXVW4X VS44, (R11)(R10) + ADD $-1, R11, R12 + ADD $-1, INP + ADD $-1, OUT + +looptail_vsx: + // Copying the result to OUT + // in bytes. + MOVBZU 1(R12), KEY + MOVBZU 1(INP), TMP + XOR KEY, TMP, KEY + MOVBU KEY, 1(OUT) + BC 16, LT, looptail_vsx + + // Clear the stack values + STXVW4X VS48, (R11)(R0) + STXVW4X VS48, (R11)(R8) + STXVW4X VS48, (R11)(R9) + STXVW4X VS48, (R11)(R10) + BR done_vsx diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_s390x.go b/vendor/golang.org/x/crypto/chacha20/chacha_s390x.go new file mode 100644 index 00000000000..a9244bdf4db --- /dev/null +++ b/vendor/golang.org/x/crypto/chacha20/chacha_s390x.go @@ -0,0 +1,26 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !gccgo,!purego + +package chacha20 + +import "golang.org/x/sys/cpu" + +var haveAsm = cpu.S390X.HasVX + +const bufSize = 256 + +// xorKeyStreamVX is an assembly implementation of XORKeyStream. It must only +// be called when the vector facility is available. Implementation in asm_s390x.s. +//go:noescape +func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) + +func (c *Cipher) xorKeyStreamBlocks(dst, src []byte) { + if cpu.S390X.HasVX { + xorKeyStreamVX(dst, src, &c.key, &c.nonce, &c.counter) + } else { + c.xorKeyStreamBlocksGeneric(dst, src) + } +} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.s b/vendor/golang.org/x/crypto/chacha20/chacha_s390x.s similarity index 87% rename from vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.s rename to vendor/golang.org/x/crypto/chacha20/chacha_s390x.s index 57df404465c..89c658c410b 100644 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.s +++ b/vendor/golang.org/x/crypto/chacha20/chacha_s390x.s @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build s390x,!gccgo,!appengine +// +build !gccgo,!purego #include "go_asm.h" #include "textflag.h" @@ -24,15 +24,6 @@ DATA ·constants<>+0x14(SB)/4, $0x3320646e DATA ·constants<>+0x18(SB)/4, $0x79622d32 DATA ·constants<>+0x1c(SB)/4, $0x6b206574 -// EXRL targets: -TEXT ·mvcSrcToBuf(SB), NOFRAME|NOSPLIT, $0 - MVC $1, (R1), (R8) - RET - -TEXT ·mvcBufToDst(SB), NOFRAME|NOSPLIT, $0 - MVC $1, (R8), (R9) - RET - #define BSWAP V5 #define J0 V6 #define KEY0 V7 @@ -144,7 +135,7 @@ TEXT ·mvcBufToDst(SB), NOFRAME|NOSPLIT, $0 VMRHF v, w, c \ // c = {a[2], b[2], c[2], d[2]} VMRLF v, w, d // d = {a[3], b[3], c[3], d[3]} -// func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32, buf *[256]byte, len *int) +// func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0 MOVD $·constants<>(SB), R1 MOVD dst+0(FP), R2 // R2=&dst[0] @@ -152,25 +143,10 @@ TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0 MOVD key+48(FP), R5 // R5=key MOVD nonce+56(FP), R6 // R6=nonce MOVD counter+64(FP), R7 // R7=counter - MOVD buf+72(FP), R8 // R8=buf - MOVD len+80(FP), R9 // R9=len // load BSWAP and J0 VLM (R1), BSWAP, J0 - // set up tail buffer - ADD $-1, R4, R12 - MOVBZ R12, R12 - CMPUBEQ R12, $255, aligned - MOVD R4, R1 - AND $~255, R1 - MOVD $(R3)(R1*1), R1 - EXRL $·mvcSrcToBuf(SB), R12 - MOVD $255, R0 - SUB R12, R0 - MOVD R0, (R9) // update len - -aligned: // setup MOVD $95, R0 VLM (R5), KEY0, KEY1 @@ -217,9 +193,7 @@ loop: // decrement length ADD $-256, R4 - BLT tail -continue: // rearrange vectors SHUFFLE(X0, X1, X2, X3, M0, M1, M2, M3) ADDV(J0, X0, X1, X2, X3) @@ -245,16 +219,6 @@ continue: MOVD $256(R3), R3 CMPBNE R4, $0, chacha - CMPUBEQ R12, $255, return - EXRL $·mvcBufToDst(SB), R12 // len was updated during setup -return: VSTEF $0, CTR, (R7) RET - -tail: - MOVD R2, R9 - MOVD R8, R2 - MOVD R8, R3 - MOVD $0, R4 - JMP continue diff --git a/vendor/golang.org/x/crypto/chacha20/xor.go b/vendor/golang.org/x/crypto/chacha20/xor.go new file mode 100644 index 00000000000..c2d04851e0d --- /dev/null +++ b/vendor/golang.org/x/crypto/chacha20/xor.go @@ -0,0 +1,42 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found src the LICENSE file. + +package chacha20 + +import "runtime" + +// Platforms that have fast unaligned 32-bit little endian accesses. +const unaligned = runtime.GOARCH == "386" || + runtime.GOARCH == "amd64" || + runtime.GOARCH == "arm64" || + runtime.GOARCH == "ppc64le" || + runtime.GOARCH == "s390x" + +// addXor reads a little endian uint32 from src, XORs it with (a + b) and +// places the result in little endian byte order in dst. +func addXor(dst, src []byte, a, b uint32) { + _, _ = src[3], dst[3] // bounds check elimination hint + if unaligned { + // The compiler should optimize this code into + // 32-bit unaligned little endian loads and stores. + // TODO: delete once the compiler does a reliably + // good job with the generic code below. + // See issue #25111 for more details. + v := uint32(src[0]) + v |= uint32(src[1]) << 8 + v |= uint32(src[2]) << 16 + v |= uint32(src[3]) << 24 + v ^= a + b + dst[0] = byte(v) + dst[1] = byte(v >> 8) + dst[2] = byte(v >> 16) + dst[3] = byte(v >> 24) + } else { + a += b + dst[0] = src[0] ^ byte(a) + dst[1] = src[1] ^ byte(a>>8) + dst[2] = src[2] ^ byte(a>>16) + dst[3] = src[3] ^ byte(a>>24) + } +} diff --git a/vendor/golang.org/x/crypto/curve25519/const_amd64.h b/vendor/golang.org/x/crypto/curve25519/const_amd64.h deleted file mode 100644 index b3f74162f60..00000000000 --- a/vendor/golang.org/x/crypto/curve25519/const_amd64.h +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -#define REDMASK51 0x0007FFFFFFFFFFFF diff --git a/vendor/golang.org/x/crypto/curve25519/const_amd64.s b/vendor/golang.org/x/crypto/curve25519/const_amd64.s deleted file mode 100644 index ee7b4bd5f8e..00000000000 --- a/vendor/golang.org/x/crypto/curve25519/const_amd64.s +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -// These constants cannot be encoded in non-MOVQ immediates. -// We access them directly from memory instead. - -DATA ·_121666_213(SB)/8, $996687872 -GLOBL ·_121666_213(SB), 8, $8 - -DATA ·_2P0(SB)/8, $0xFFFFFFFFFFFDA -GLOBL ·_2P0(SB), 8, $8 - -DATA ·_2P1234(SB)/8, $0xFFFFFFFFFFFFE -GLOBL ·_2P1234(SB), 8, $8 diff --git a/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s b/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s deleted file mode 100644 index cd793a5b5f2..00000000000 --- a/vendor/golang.org/x/crypto/curve25519/cswap_amd64.s +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64,!gccgo,!appengine - -// func cswap(inout *[4][5]uint64, v uint64) -TEXT ·cswap(SB),7,$0 - MOVQ inout+0(FP),DI - MOVQ v+8(FP),SI - - SUBQ $1, SI - NOTQ SI - MOVQ SI, X15 - PSHUFD $0x44, X15, X15 - - MOVOU 0(DI), X0 - MOVOU 16(DI), X2 - MOVOU 32(DI), X4 - MOVOU 48(DI), X6 - MOVOU 64(DI), X8 - MOVOU 80(DI), X1 - MOVOU 96(DI), X3 - MOVOU 112(DI), X5 - MOVOU 128(DI), X7 - MOVOU 144(DI), X9 - - MOVO X1, X10 - MOVO X3, X11 - MOVO X5, X12 - MOVO X7, X13 - MOVO X9, X14 - - PXOR X0, X10 - PXOR X2, X11 - PXOR X4, X12 - PXOR X6, X13 - PXOR X8, X14 - PAND X15, X10 - PAND X15, X11 - PAND X15, X12 - PAND X15, X13 - PAND X15, X14 - PXOR X10, X0 - PXOR X10, X1 - PXOR X11, X2 - PXOR X11, X3 - PXOR X12, X4 - PXOR X12, X5 - PXOR X13, X6 - PXOR X13, X7 - PXOR X14, X8 - PXOR X14, X9 - - MOVOU X0, 0(DI) - MOVOU X2, 16(DI) - MOVOU X4, 32(DI) - MOVOU X6, 48(DI) - MOVOU X8, 64(DI) - MOVOU X1, 80(DI) - MOVOU X3, 96(DI) - MOVOU X5, 112(DI) - MOVOU X7, 128(DI) - MOVOU X9, 144(DI) - RET diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519.go b/vendor/golang.org/x/crypto/curve25519/curve25519.go index 75f24babb69..4b9a655d1b5 100644 --- a/vendor/golang.org/x/crypto/curve25519/curve25519.go +++ b/vendor/golang.org/x/crypto/curve25519/curve25519.go @@ -1,834 +1,95 @@ -// Copyright 2013 The Go Authors. All rights reserved. +// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// We have an implementation in amd64 assembly so this code is only run on -// non-amd64 platforms. The amd64 assembly does not support gccgo. -// +build !amd64 gccgo appengine - -package curve25519 +// Package curve25519 provides an implementation of the X25519 function, which +// performs scalar multiplication on the elliptic curve known as Curve25519. +// See RFC 7748. +package curve25519 // import "golang.org/x/crypto/curve25519" import ( - "encoding/binary" + "crypto/subtle" + "fmt" ) -// This code is a port of the public domain, "ref10" implementation of -// curve25519 from SUPERCOP 20130419 by D. J. Bernstein. - -// fieldElement represents an element of the field GF(2^255 - 19). An element -// t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 -// t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on -// context. -type fieldElement [10]int32 - -func feZero(fe *fieldElement) { - for i := range fe { - fe[i] = 0 - } -} - -func feOne(fe *fieldElement) { - feZero(fe) - fe[0] = 1 -} - -func feAdd(dst, a, b *fieldElement) { - for i := range dst { - dst[i] = a[i] + b[i] - } -} - -func feSub(dst, a, b *fieldElement) { - for i := range dst { - dst[i] = a[i] - b[i] - } -} - -func feCopy(dst, src *fieldElement) { - for i := range dst { - dst[i] = src[i] - } -} - -// feCSwap replaces (f,g) with (g,f) if b == 1; replaces (f,g) with (f,g) if b == 0. -// -// Preconditions: b in {0,1}. -func feCSwap(f, g *fieldElement, b int32) { - b = -b - for i := range f { - t := b & (f[i] ^ g[i]) - f[i] ^= t - g[i] ^= t - } -} - -// load3 reads a 24-bit, little-endian value from in. -func load3(in []byte) int64 { - var r int64 - r = int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - return r -} - -// load4 reads a 32-bit, little-endian value from in. -func load4(in []byte) int64 { - return int64(binary.LittleEndian.Uint32(in)) -} - -func feFromBytes(dst *fieldElement, src *[32]byte) { - h0 := load4(src[:]) - h1 := load3(src[4:]) << 6 - h2 := load3(src[7:]) << 5 - h3 := load3(src[10:]) << 3 - h4 := load3(src[13:]) << 2 - h5 := load4(src[16:]) - h6 := load3(src[20:]) << 7 - h7 := load3(src[23:]) << 5 - h8 := load3(src[26:]) << 4 - h9 := (load3(src[29:]) & 0x7fffff) << 2 - - var carry [10]int64 - carry[9] = (h9 + 1<<24) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - carry[1] = (h1 + 1<<24) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[3] = (h3 + 1<<24) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[5] = (h5 + 1<<24) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - carry[7] = (h7 + 1<<24) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[0] = (h0 + 1<<25) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[2] = (h2 + 1<<25) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[4] = (h4 + 1<<25) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[6] = (h6 + 1<<25) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - carry[8] = (h8 + 1<<25) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - dst[0] = int32(h0) - dst[1] = int32(h1) - dst[2] = int32(h2) - dst[3] = int32(h3) - dst[4] = int32(h4) - dst[5] = int32(h5) - dst[6] = int32(h6) - dst[7] = int32(h7) - dst[8] = int32(h8) - dst[9] = int32(h9) -} - -// feToBytes marshals h to s. -// Preconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Write p=2^255-19; q=floor(h/p). -// Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). -// -// Proof: -// Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. -// Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. -// -// Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). -// Then 0> 25 - q = (h[0] + q) >> 26 - q = (h[1] + q) >> 25 - q = (h[2] + q) >> 26 - q = (h[3] + q) >> 25 - q = (h[4] + q) >> 26 - q = (h[5] + q) >> 25 - q = (h[6] + q) >> 26 - q = (h[7] + q) >> 25 - q = (h[8] + q) >> 26 - q = (h[9] + q) >> 25 - - // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. - h[0] += 19 * q - // Goal: Output h-2^255 q, which is between 0 and 2^255-20. - - carry[0] = h[0] >> 26 - h[1] += carry[0] - h[0] -= carry[0] << 26 - carry[1] = h[1] >> 25 - h[2] += carry[1] - h[1] -= carry[1] << 25 - carry[2] = h[2] >> 26 - h[3] += carry[2] - h[2] -= carry[2] << 26 - carry[3] = h[3] >> 25 - h[4] += carry[3] - h[3] -= carry[3] << 25 - carry[4] = h[4] >> 26 - h[5] += carry[4] - h[4] -= carry[4] << 26 - carry[5] = h[5] >> 25 - h[6] += carry[5] - h[5] -= carry[5] << 25 - carry[6] = h[6] >> 26 - h[7] += carry[6] - h[6] -= carry[6] << 26 - carry[7] = h[7] >> 25 - h[8] += carry[7] - h[7] -= carry[7] << 25 - carry[8] = h[8] >> 26 - h[9] += carry[8] - h[8] -= carry[8] << 26 - carry[9] = h[9] >> 25 - h[9] -= carry[9] << 25 - // h10 = carry9 - - // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. - // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; - // evidently 2^255 h10-2^255 q = 0. - // Goal: Output h[0]+...+2^230 h[9]. - - s[0] = byte(h[0] >> 0) - s[1] = byte(h[0] >> 8) - s[2] = byte(h[0] >> 16) - s[3] = byte((h[0] >> 24) | (h[1] << 2)) - s[4] = byte(h[1] >> 6) - s[5] = byte(h[1] >> 14) - s[6] = byte((h[1] >> 22) | (h[2] << 3)) - s[7] = byte(h[2] >> 5) - s[8] = byte(h[2] >> 13) - s[9] = byte((h[2] >> 21) | (h[3] << 5)) - s[10] = byte(h[3] >> 3) - s[11] = byte(h[3] >> 11) - s[12] = byte((h[3] >> 19) | (h[4] << 6)) - s[13] = byte(h[4] >> 2) - s[14] = byte(h[4] >> 10) - s[15] = byte(h[4] >> 18) - s[16] = byte(h[5] >> 0) - s[17] = byte(h[5] >> 8) - s[18] = byte(h[5] >> 16) - s[19] = byte((h[5] >> 24) | (h[6] << 1)) - s[20] = byte(h[6] >> 7) - s[21] = byte(h[6] >> 15) - s[22] = byte((h[6] >> 23) | (h[7] << 3)) - s[23] = byte(h[7] >> 5) - s[24] = byte(h[7] >> 13) - s[25] = byte((h[7] >> 21) | (h[8] << 4)) - s[26] = byte(h[8] >> 4) - s[27] = byte(h[8] >> 12) - s[28] = byte((h[8] >> 20) | (h[9] << 6)) - s[29] = byte(h[9] >> 2) - s[30] = byte(h[9] >> 10) - s[31] = byte(h[9] >> 18) +// Deprecated: when provided a low-order point, ScalarMult will set dst to all +// zeroes, irrespective of the scalar. Instead, use the X25519 function, which +// will return an error. +func ScalarMult(dst, scalar, point *[32]byte) { + scalarMult(dst, scalar, point) } -// feMul calculates h = f * g -// Can overlap h with f or g. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -// -// Notes on implementation strategy: -// -// Using schoolbook multiplication. -// Karatsuba would save a little in some cost models. +// ScalarBaseMult sets dst to the product scalar * base where base is the +// standard generator. // -// Most multiplications by 2 and 19 are 32-bit precomputations; -// cheaper than 64-bit postcomputations. -// -// There is one remaining multiplication by 19 in the carry chain; -// one *19 precomputation can be merged into this, -// but the resulting data flow is considerably less clean. -// -// There are 12 carries below. -// 10 of them are 2-way parallelizable and vectorizable. -// Can get away with 11 carries, but then data flow is much deeper. -// -// With tighter constraints on inputs can squeeze carries into int32. -func feMul(h, f, g *fieldElement) { - f0 := f[0] - f1 := f[1] - f2 := f[2] - f3 := f[3] - f4 := f[4] - f5 := f[5] - f6 := f[6] - f7 := f[7] - f8 := f[8] - f9 := f[9] - g0 := g[0] - g1 := g[1] - g2 := g[2] - g3 := g[3] - g4 := g[4] - g5 := g[5] - g6 := g[6] - g7 := g[7] - g8 := g[8] - g9 := g[9] - g1_19 := 19 * g1 // 1.4*2^29 - g2_19 := 19 * g2 // 1.4*2^30; still ok - g3_19 := 19 * g3 - g4_19 := 19 * g4 - g5_19 := 19 * g5 - g6_19 := 19 * g6 - g7_19 := 19 * g7 - g8_19 := 19 * g8 - g9_19 := 19 * g9 - f1_2 := 2 * f1 - f3_2 := 2 * f3 - f5_2 := 2 * f5 - f7_2 := 2 * f7 - f9_2 := 2 * f9 - f0g0 := int64(f0) * int64(g0) - f0g1 := int64(f0) * int64(g1) - f0g2 := int64(f0) * int64(g2) - f0g3 := int64(f0) * int64(g3) - f0g4 := int64(f0) * int64(g4) - f0g5 := int64(f0) * int64(g5) - f0g6 := int64(f0) * int64(g6) - f0g7 := int64(f0) * int64(g7) - f0g8 := int64(f0) * int64(g8) - f0g9 := int64(f0) * int64(g9) - f1g0 := int64(f1) * int64(g0) - f1g1_2 := int64(f1_2) * int64(g1) - f1g2 := int64(f1) * int64(g2) - f1g3_2 := int64(f1_2) * int64(g3) - f1g4 := int64(f1) * int64(g4) - f1g5_2 := int64(f1_2) * int64(g5) - f1g6 := int64(f1) * int64(g6) - f1g7_2 := int64(f1_2) * int64(g7) - f1g8 := int64(f1) * int64(g8) - f1g9_38 := int64(f1_2) * int64(g9_19) - f2g0 := int64(f2) * int64(g0) - f2g1 := int64(f2) * int64(g1) - f2g2 := int64(f2) * int64(g2) - f2g3 := int64(f2) * int64(g3) - f2g4 := int64(f2) * int64(g4) - f2g5 := int64(f2) * int64(g5) - f2g6 := int64(f2) * int64(g6) - f2g7 := int64(f2) * int64(g7) - f2g8_19 := int64(f2) * int64(g8_19) - f2g9_19 := int64(f2) * int64(g9_19) - f3g0 := int64(f3) * int64(g0) - f3g1_2 := int64(f3_2) * int64(g1) - f3g2 := int64(f3) * int64(g2) - f3g3_2 := int64(f3_2) * int64(g3) - f3g4 := int64(f3) * int64(g4) - f3g5_2 := int64(f3_2) * int64(g5) - f3g6 := int64(f3) * int64(g6) - f3g7_38 := int64(f3_2) * int64(g7_19) - f3g8_19 := int64(f3) * int64(g8_19) - f3g9_38 := int64(f3_2) * int64(g9_19) - f4g0 := int64(f4) * int64(g0) - f4g1 := int64(f4) * int64(g1) - f4g2 := int64(f4) * int64(g2) - f4g3 := int64(f4) * int64(g3) - f4g4 := int64(f4) * int64(g4) - f4g5 := int64(f4) * int64(g5) - f4g6_19 := int64(f4) * int64(g6_19) - f4g7_19 := int64(f4) * int64(g7_19) - f4g8_19 := int64(f4) * int64(g8_19) - f4g9_19 := int64(f4) * int64(g9_19) - f5g0 := int64(f5) * int64(g0) - f5g1_2 := int64(f5_2) * int64(g1) - f5g2 := int64(f5) * int64(g2) - f5g3_2 := int64(f5_2) * int64(g3) - f5g4 := int64(f5) * int64(g4) - f5g5_38 := int64(f5_2) * int64(g5_19) - f5g6_19 := int64(f5) * int64(g6_19) - f5g7_38 := int64(f5_2) * int64(g7_19) - f5g8_19 := int64(f5) * int64(g8_19) - f5g9_38 := int64(f5_2) * int64(g9_19) - f6g0 := int64(f6) * int64(g0) - f6g1 := int64(f6) * int64(g1) - f6g2 := int64(f6) * int64(g2) - f6g3 := int64(f6) * int64(g3) - f6g4_19 := int64(f6) * int64(g4_19) - f6g5_19 := int64(f6) * int64(g5_19) - f6g6_19 := int64(f6) * int64(g6_19) - f6g7_19 := int64(f6) * int64(g7_19) - f6g8_19 := int64(f6) * int64(g8_19) - f6g9_19 := int64(f6) * int64(g9_19) - f7g0 := int64(f7) * int64(g0) - f7g1_2 := int64(f7_2) * int64(g1) - f7g2 := int64(f7) * int64(g2) - f7g3_38 := int64(f7_2) * int64(g3_19) - f7g4_19 := int64(f7) * int64(g4_19) - f7g5_38 := int64(f7_2) * int64(g5_19) - f7g6_19 := int64(f7) * int64(g6_19) - f7g7_38 := int64(f7_2) * int64(g7_19) - f7g8_19 := int64(f7) * int64(g8_19) - f7g9_38 := int64(f7_2) * int64(g9_19) - f8g0 := int64(f8) * int64(g0) - f8g1 := int64(f8) * int64(g1) - f8g2_19 := int64(f8) * int64(g2_19) - f8g3_19 := int64(f8) * int64(g3_19) - f8g4_19 := int64(f8) * int64(g4_19) - f8g5_19 := int64(f8) * int64(g5_19) - f8g6_19 := int64(f8) * int64(g6_19) - f8g7_19 := int64(f8) * int64(g7_19) - f8g8_19 := int64(f8) * int64(g8_19) - f8g9_19 := int64(f8) * int64(g9_19) - f9g0 := int64(f9) * int64(g0) - f9g1_38 := int64(f9_2) * int64(g1_19) - f9g2_19 := int64(f9) * int64(g2_19) - f9g3_38 := int64(f9_2) * int64(g3_19) - f9g4_19 := int64(f9) * int64(g4_19) - f9g5_38 := int64(f9_2) * int64(g5_19) - f9g6_19 := int64(f9) * int64(g6_19) - f9g7_38 := int64(f9_2) * int64(g7_19) - f9g8_19 := int64(f9) * int64(g8_19) - f9g9_38 := int64(f9_2) * int64(g9_19) - h0 := f0g0 + f1g9_38 + f2g8_19 + f3g7_38 + f4g6_19 + f5g5_38 + f6g4_19 + f7g3_38 + f8g2_19 + f9g1_38 - h1 := f0g1 + f1g0 + f2g9_19 + f3g8_19 + f4g7_19 + f5g6_19 + f6g5_19 + f7g4_19 + f8g3_19 + f9g2_19 - h2 := f0g2 + f1g1_2 + f2g0 + f3g9_38 + f4g8_19 + f5g7_38 + f6g6_19 + f7g5_38 + f8g4_19 + f9g3_38 - h3 := f0g3 + f1g2 + f2g1 + f3g0 + f4g9_19 + f5g8_19 + f6g7_19 + f7g6_19 + f8g5_19 + f9g4_19 - h4 := f0g4 + f1g3_2 + f2g2 + f3g1_2 + f4g0 + f5g9_38 + f6g8_19 + f7g7_38 + f8g6_19 + f9g5_38 - h5 := f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + f6g9_19 + f7g8_19 + f8g7_19 + f9g6_19 - h6 := f0g6 + f1g5_2 + f2g4 + f3g3_2 + f4g2 + f5g1_2 + f6g0 + f7g9_38 + f8g8_19 + f9g7_38 - h7 := f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 + f8g9_19 + f9g8_19 - h8 := f0g8 + f1g7_2 + f2g6 + f3g5_2 + f4g4 + f5g3_2 + f6g2 + f7g1_2 + f8g0 + f9g9_38 - h9 := f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0 - var carry [10]int64 - - // |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) - // i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 - // |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) - // i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - // |h0| <= 2^25 - // |h4| <= 2^25 - // |h1| <= 1.51*2^58 - // |h5| <= 1.51*2^58 - - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - // |h1| <= 2^24; from now on fits into int32 - // |h5| <= 2^24; from now on fits into int32 - // |h2| <= 1.21*2^59 - // |h6| <= 1.21*2^59 - - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - // |h2| <= 2^25; from now on fits into int32 unchanged - // |h6| <= 2^25; from now on fits into int32 unchanged - // |h3| <= 1.51*2^58 - // |h7| <= 1.51*2^58 - - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - // |h3| <= 2^24; from now on fits into int32 unchanged - // |h7| <= 2^24; from now on fits into int32 unchanged - // |h4| <= 1.52*2^33 - // |h8| <= 1.52*2^33 - - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - // |h4| <= 2^25; from now on fits into int32 unchanged - // |h8| <= 2^25; from now on fits into int32 unchanged - // |h5| <= 1.01*2^24 - // |h9| <= 1.51*2^58 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - // |h9| <= 2^24; from now on fits into int32 unchanged - // |h0| <= 1.8*2^37 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - // |h0| <= 2^25; from now on fits into int32 unchanged - // |h1| <= 1.01*2^24 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) +// It is recommended to use the X25519 function with Basepoint instead, as +// copying into fixed size arrays can lead to unexpected bugs. +func ScalarBaseMult(dst, scalar *[32]byte) { + ScalarMult(dst, scalar, &basePoint) } -// feSquare calculates h = f*f. Can overlap h with f. -// -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. -// -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func feSquare(h, f *fieldElement) { - f0 := f[0] - f1 := f[1] - f2 := f[2] - f3 := f[3] - f4 := f[4] - f5 := f[5] - f6 := f[6] - f7 := f[7] - f8 := f[8] - f9 := f[9] - f0_2 := 2 * f0 - f1_2 := 2 * f1 - f2_2 := 2 * f2 - f3_2 := 2 * f3 - f4_2 := 2 * f4 - f5_2 := 2 * f5 - f6_2 := 2 * f6 - f7_2 := 2 * f7 - f5_38 := 38 * f5 // 1.31*2^30 - f6_19 := 19 * f6 // 1.31*2^30 - f7_38 := 38 * f7 // 1.31*2^30 - f8_19 := 19 * f8 // 1.31*2^30 - f9_38 := 38 * f9 // 1.31*2^30 - f0f0 := int64(f0) * int64(f0) - f0f1_2 := int64(f0_2) * int64(f1) - f0f2_2 := int64(f0_2) * int64(f2) - f0f3_2 := int64(f0_2) * int64(f3) - f0f4_2 := int64(f0_2) * int64(f4) - f0f5_2 := int64(f0_2) * int64(f5) - f0f6_2 := int64(f0_2) * int64(f6) - f0f7_2 := int64(f0_2) * int64(f7) - f0f8_2 := int64(f0_2) * int64(f8) - f0f9_2 := int64(f0_2) * int64(f9) - f1f1_2 := int64(f1_2) * int64(f1) - f1f2_2 := int64(f1_2) * int64(f2) - f1f3_4 := int64(f1_2) * int64(f3_2) - f1f4_2 := int64(f1_2) * int64(f4) - f1f5_4 := int64(f1_2) * int64(f5_2) - f1f6_2 := int64(f1_2) * int64(f6) - f1f7_4 := int64(f1_2) * int64(f7_2) - f1f8_2 := int64(f1_2) * int64(f8) - f1f9_76 := int64(f1_2) * int64(f9_38) - f2f2 := int64(f2) * int64(f2) - f2f3_2 := int64(f2_2) * int64(f3) - f2f4_2 := int64(f2_2) * int64(f4) - f2f5_2 := int64(f2_2) * int64(f5) - f2f6_2 := int64(f2_2) * int64(f6) - f2f7_2 := int64(f2_2) * int64(f7) - f2f8_38 := int64(f2_2) * int64(f8_19) - f2f9_38 := int64(f2) * int64(f9_38) - f3f3_2 := int64(f3_2) * int64(f3) - f3f4_2 := int64(f3_2) * int64(f4) - f3f5_4 := int64(f3_2) * int64(f5_2) - f3f6_2 := int64(f3_2) * int64(f6) - f3f7_76 := int64(f3_2) * int64(f7_38) - f3f8_38 := int64(f3_2) * int64(f8_19) - f3f9_76 := int64(f3_2) * int64(f9_38) - f4f4 := int64(f4) * int64(f4) - f4f5_2 := int64(f4_2) * int64(f5) - f4f6_38 := int64(f4_2) * int64(f6_19) - f4f7_38 := int64(f4) * int64(f7_38) - f4f8_38 := int64(f4_2) * int64(f8_19) - f4f9_38 := int64(f4) * int64(f9_38) - f5f5_38 := int64(f5) * int64(f5_38) - f5f6_38 := int64(f5_2) * int64(f6_19) - f5f7_76 := int64(f5_2) * int64(f7_38) - f5f8_38 := int64(f5_2) * int64(f8_19) - f5f9_76 := int64(f5_2) * int64(f9_38) - f6f6_19 := int64(f6) * int64(f6_19) - f6f7_38 := int64(f6) * int64(f7_38) - f6f8_38 := int64(f6_2) * int64(f8_19) - f6f9_38 := int64(f6) * int64(f9_38) - f7f7_38 := int64(f7) * int64(f7_38) - f7f8_38 := int64(f7_2) * int64(f8_19) - f7f9_76 := int64(f7_2) * int64(f9_38) - f8f8_19 := int64(f8) * int64(f8_19) - f8f9_38 := int64(f8) * int64(f9_38) - f9f9_38 := int64(f9) * int64(f9_38) - h0 := f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38 - h1 := f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38 - h2 := f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19 - h3 := f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38 - h4 := f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38 - h5 := f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38 - h6 := f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19 - h7 := f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38 - h8 := f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38 - h9 := f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2 - var carry [10]int64 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 +const ( + // ScalarSize is the size of the scalar input to X25519. + ScalarSize = 32 + // PointSize is the size of the point input to X25519. + PointSize = 32 +) - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 +// Basepoint is the canonical Curve25519 generator. +var Basepoint []byte - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 +var basePoint = [32]byte{9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 +func init() { Basepoint = basePoint[:] } - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) +func checkBasepoint() { + if subtle.ConstantTimeCompare(Basepoint, []byte{ + 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }) != 1 { + panic("curve25519: global Basepoint value was modified") + } } -// feMul121666 calculates h = f * 121666. Can overlap h with f. +// X25519 returns the result of the scalar multiplication (scalar * point), +// according to RFC 7748, Section 5. scalar, point and the return value are +// slices of 32 bytes. // -// Preconditions: -// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. +// scalar can be generated at random, for example with crypto/rand. point should +// be either Basepoint or the output of another X25519 call. // -// Postconditions: -// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. -func feMul121666(h, f *fieldElement) { - h0 := int64(f[0]) * 121666 - h1 := int64(f[1]) * 121666 - h2 := int64(f[2]) * 121666 - h3 := int64(f[3]) * 121666 - h4 := int64(f[4]) * 121666 - h5 := int64(f[5]) * 121666 - h6 := int64(f[6]) * 121666 - h7 := int64(f[7]) * 121666 - h8 := int64(f[8]) * 121666 - h9 := int64(f[9]) * 121666 - var carry [10]int64 - - carry[9] = (h9 + (1 << 24)) >> 25 - h0 += carry[9] * 19 - h9 -= carry[9] << 25 - carry[1] = (h1 + (1 << 24)) >> 25 - h2 += carry[1] - h1 -= carry[1] << 25 - carry[3] = (h3 + (1 << 24)) >> 25 - h4 += carry[3] - h3 -= carry[3] << 25 - carry[5] = (h5 + (1 << 24)) >> 25 - h6 += carry[5] - h5 -= carry[5] << 25 - carry[7] = (h7 + (1 << 24)) >> 25 - h8 += carry[7] - h7 -= carry[7] << 25 - - carry[0] = (h0 + (1 << 25)) >> 26 - h1 += carry[0] - h0 -= carry[0] << 26 - carry[2] = (h2 + (1 << 25)) >> 26 - h3 += carry[2] - h2 -= carry[2] << 26 - carry[4] = (h4 + (1 << 25)) >> 26 - h5 += carry[4] - h4 -= carry[4] << 26 - carry[6] = (h6 + (1 << 25)) >> 26 - h7 += carry[6] - h6 -= carry[6] << 26 - carry[8] = (h8 + (1 << 25)) >> 26 - h9 += carry[8] - h8 -= carry[8] << 26 - - h[0] = int32(h0) - h[1] = int32(h1) - h[2] = int32(h2) - h[3] = int32(h3) - h[4] = int32(h4) - h[5] = int32(h5) - h[6] = int32(h6) - h[7] = int32(h7) - h[8] = int32(h8) - h[9] = int32(h9) -} - -// feInvert sets out = z^-1. -func feInvert(out, z *fieldElement) { - var t0, t1, t2, t3 fieldElement - var i int - - feSquare(&t0, z) - for i = 1; i < 1; i++ { - feSquare(&t0, &t0) - } - feSquare(&t1, &t0) - for i = 1; i < 2; i++ { - feSquare(&t1, &t1) - } - feMul(&t1, z, &t1) - feMul(&t0, &t0, &t1) - feSquare(&t2, &t0) - for i = 1; i < 1; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t1, &t2) - feSquare(&t2, &t1) - for i = 1; i < 5; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t2, &t1) - for i = 1; i < 10; i++ { - feSquare(&t2, &t2) - } - feMul(&t2, &t2, &t1) - feSquare(&t3, &t2) - for i = 1; i < 20; i++ { - feSquare(&t3, &t3) - } - feMul(&t2, &t3, &t2) - feSquare(&t2, &t2) - for i = 1; i < 10; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t2, &t1) - for i = 1; i < 50; i++ { - feSquare(&t2, &t2) - } - feMul(&t2, &t2, &t1) - feSquare(&t3, &t2) - for i = 1; i < 100; i++ { - feSquare(&t3, &t3) - } - feMul(&t2, &t3, &t2) - feSquare(&t2, &t2) - for i = 1; i < 50; i++ { - feSquare(&t2, &t2) - } - feMul(&t1, &t2, &t1) - feSquare(&t1, &t1) - for i = 1; i < 5; i++ { - feSquare(&t1, &t1) - } - feMul(out, &t1, &t0) +// If point is Basepoint (but not if it's a different slice with the same +// contents) a precomputed implementation might be used for performance. +func X25519(scalar, point []byte) ([]byte, error) { + // Outline the body of function, to let the allocation be inlined in the + // caller, and possibly avoid escaping to the heap. + var dst [32]byte + return x25519(&dst, scalar, point) } -func scalarMult(out, in, base *[32]byte) { - var e [32]byte - - copy(e[:], in[:]) - e[0] &= 248 - e[31] &= 127 - e[31] |= 64 - - var x1, x2, z2, x3, z3, tmp0, tmp1 fieldElement - feFromBytes(&x1, base) - feOne(&x2) - feCopy(&x3, &x1) - feOne(&z3) - - swap := int32(0) - for pos := 254; pos >= 0; pos-- { - b := e[pos/8] >> uint(pos&7) - b &= 1 - swap ^= int32(b) - feCSwap(&x2, &x3, swap) - feCSwap(&z2, &z3, swap) - swap = int32(b) - - feSub(&tmp0, &x3, &z3) - feSub(&tmp1, &x2, &z2) - feAdd(&x2, &x2, &z2) - feAdd(&z2, &x3, &z3) - feMul(&z3, &tmp0, &x2) - feMul(&z2, &z2, &tmp1) - feSquare(&tmp0, &tmp1) - feSquare(&tmp1, &x2) - feAdd(&x3, &z3, &z2) - feSub(&z2, &z3, &z2) - feMul(&x2, &tmp1, &tmp0) - feSub(&tmp1, &tmp1, &tmp0) - feSquare(&z2, &z2) - feMul121666(&z3, &tmp1) - feSquare(&x3, &x3) - feAdd(&tmp0, &tmp0, &z3) - feMul(&z3, &x1, &z2) - feMul(&z2, &tmp1, &tmp0) - } - - feCSwap(&x2, &x3, swap) - feCSwap(&z2, &z3, swap) - - feInvert(&z2, &z2) - feMul(&x2, &x2, &z2) - feToBytes(out, &x2) +func x25519(dst *[32]byte, scalar, point []byte) ([]byte, error) { + var in [32]byte + if l := len(scalar); l != 32 { + return nil, fmt.Errorf("bad scalar length: %d, expected %d", l, 32) + } + if l := len(point); l != 32 { + return nil, fmt.Errorf("bad point length: %d, expected %d", l, 32) + } + copy(in[:], scalar) + if &point[0] == &Basepoint[0] { + checkBasepoint() + ScalarBaseMult(dst, &in) + } else { + var base, zero [32]byte + copy(base[:], point) + ScalarMult(dst, &in, &base) + if subtle.ConstantTimeCompare(dst[:], zero[:]) == 1 { + return nil, fmt.Errorf("bad input point: low order point") + } + } + return dst[:], nil } diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519_amd64.go b/vendor/golang.org/x/crypto/curve25519/curve25519_amd64.go new file mode 100644 index 00000000000..5120b779b9b --- /dev/null +++ b/vendor/golang.org/x/crypto/curve25519/curve25519_amd64.go @@ -0,0 +1,240 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build amd64,!gccgo,!appengine,!purego + +package curve25519 + +// These functions are implemented in the .s files. The names of the functions +// in the rest of the file are also taken from the SUPERCOP sources to help +// people following along. + +//go:noescape + +func cswap(inout *[5]uint64, v uint64) + +//go:noescape + +func ladderstep(inout *[5][5]uint64) + +//go:noescape + +func freeze(inout *[5]uint64) + +//go:noescape + +func mul(dest, a, b *[5]uint64) + +//go:noescape + +func square(out, in *[5]uint64) + +// mladder uses a Montgomery ladder to calculate (xr/zr) *= s. +func mladder(xr, zr *[5]uint64, s *[32]byte) { + var work [5][5]uint64 + + work[0] = *xr + setint(&work[1], 1) + setint(&work[2], 0) + work[3] = *xr + setint(&work[4], 1) + + j := uint(6) + var prevbit byte + + for i := 31; i >= 0; i-- { + for j < 8 { + bit := ((*s)[i] >> j) & 1 + swap := bit ^ prevbit + prevbit = bit + cswap(&work[1], uint64(swap)) + ladderstep(&work) + j-- + } + j = 7 + } + + *xr = work[1] + *zr = work[2] +} + +func scalarMult(out, in, base *[32]byte) { + var e [32]byte + copy(e[:], (*in)[:]) + e[0] &= 248 + e[31] &= 127 + e[31] |= 64 + + var t, z [5]uint64 + unpack(&t, base) + mladder(&t, &z, &e) + invert(&z, &z) + mul(&t, &t, &z) + pack(out, &t) +} + +func setint(r *[5]uint64, v uint64) { + r[0] = v + r[1] = 0 + r[2] = 0 + r[3] = 0 + r[4] = 0 +} + +// unpack sets r = x where r consists of 5, 51-bit limbs in little-endian +// order. +func unpack(r *[5]uint64, x *[32]byte) { + r[0] = uint64(x[0]) | + uint64(x[1])<<8 | + uint64(x[2])<<16 | + uint64(x[3])<<24 | + uint64(x[4])<<32 | + uint64(x[5])<<40 | + uint64(x[6]&7)<<48 + + r[1] = uint64(x[6])>>3 | + uint64(x[7])<<5 | + uint64(x[8])<<13 | + uint64(x[9])<<21 | + uint64(x[10])<<29 | + uint64(x[11])<<37 | + uint64(x[12]&63)<<45 + + r[2] = uint64(x[12])>>6 | + uint64(x[13])<<2 | + uint64(x[14])<<10 | + uint64(x[15])<<18 | + uint64(x[16])<<26 | + uint64(x[17])<<34 | + uint64(x[18])<<42 | + uint64(x[19]&1)<<50 + + r[3] = uint64(x[19])>>1 | + uint64(x[20])<<7 | + uint64(x[21])<<15 | + uint64(x[22])<<23 | + uint64(x[23])<<31 | + uint64(x[24])<<39 | + uint64(x[25]&15)<<47 + + r[4] = uint64(x[25])>>4 | + uint64(x[26])<<4 | + uint64(x[27])<<12 | + uint64(x[28])<<20 | + uint64(x[29])<<28 | + uint64(x[30])<<36 | + uint64(x[31]&127)<<44 +} + +// pack sets out = x where out is the usual, little-endian form of the 5, +// 51-bit limbs in x. +func pack(out *[32]byte, x *[5]uint64) { + t := *x + freeze(&t) + + out[0] = byte(t[0]) + out[1] = byte(t[0] >> 8) + out[2] = byte(t[0] >> 16) + out[3] = byte(t[0] >> 24) + out[4] = byte(t[0] >> 32) + out[5] = byte(t[0] >> 40) + out[6] = byte(t[0] >> 48) + + out[6] ^= byte(t[1]<<3) & 0xf8 + out[7] = byte(t[1] >> 5) + out[8] = byte(t[1] >> 13) + out[9] = byte(t[1] >> 21) + out[10] = byte(t[1] >> 29) + out[11] = byte(t[1] >> 37) + out[12] = byte(t[1] >> 45) + + out[12] ^= byte(t[2]<<6) & 0xc0 + out[13] = byte(t[2] >> 2) + out[14] = byte(t[2] >> 10) + out[15] = byte(t[2] >> 18) + out[16] = byte(t[2] >> 26) + out[17] = byte(t[2] >> 34) + out[18] = byte(t[2] >> 42) + out[19] = byte(t[2] >> 50) + + out[19] ^= byte(t[3]<<1) & 0xfe + out[20] = byte(t[3] >> 7) + out[21] = byte(t[3] >> 15) + out[22] = byte(t[3] >> 23) + out[23] = byte(t[3] >> 31) + out[24] = byte(t[3] >> 39) + out[25] = byte(t[3] >> 47) + + out[25] ^= byte(t[4]<<4) & 0xf0 + out[26] = byte(t[4] >> 4) + out[27] = byte(t[4] >> 12) + out[28] = byte(t[4] >> 20) + out[29] = byte(t[4] >> 28) + out[30] = byte(t[4] >> 36) + out[31] = byte(t[4] >> 44) +} + +// invert calculates r = x^-1 mod p using Fermat's little theorem. +func invert(r *[5]uint64, x *[5]uint64) { + var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_50_0, z2_100_0, t [5]uint64 + + square(&z2, x) /* 2 */ + square(&t, &z2) /* 4 */ + square(&t, &t) /* 8 */ + mul(&z9, &t, x) /* 9 */ + mul(&z11, &z9, &z2) /* 11 */ + square(&t, &z11) /* 22 */ + mul(&z2_5_0, &t, &z9) /* 2^5 - 2^0 = 31 */ + + square(&t, &z2_5_0) /* 2^6 - 2^1 */ + for i := 1; i < 5; i++ { /* 2^20 - 2^10 */ + square(&t, &t) + } + mul(&z2_10_0, &t, &z2_5_0) /* 2^10 - 2^0 */ + + square(&t, &z2_10_0) /* 2^11 - 2^1 */ + for i := 1; i < 10; i++ { /* 2^20 - 2^10 */ + square(&t, &t) + } + mul(&z2_20_0, &t, &z2_10_0) /* 2^20 - 2^0 */ + + square(&t, &z2_20_0) /* 2^21 - 2^1 */ + for i := 1; i < 20; i++ { /* 2^40 - 2^20 */ + square(&t, &t) + } + mul(&t, &t, &z2_20_0) /* 2^40 - 2^0 */ + + square(&t, &t) /* 2^41 - 2^1 */ + for i := 1; i < 10; i++ { /* 2^50 - 2^10 */ + square(&t, &t) + } + mul(&z2_50_0, &t, &z2_10_0) /* 2^50 - 2^0 */ + + square(&t, &z2_50_0) /* 2^51 - 2^1 */ + for i := 1; i < 50; i++ { /* 2^100 - 2^50 */ + square(&t, &t) + } + mul(&z2_100_0, &t, &z2_50_0) /* 2^100 - 2^0 */ + + square(&t, &z2_100_0) /* 2^101 - 2^1 */ + for i := 1; i < 100; i++ { /* 2^200 - 2^100 */ + square(&t, &t) + } + mul(&t, &t, &z2_100_0) /* 2^200 - 2^0 */ + + square(&t, &t) /* 2^201 - 2^1 */ + for i := 1; i < 50; i++ { /* 2^250 - 2^50 */ + square(&t, &t) + } + mul(&t, &t, &z2_50_0) /* 2^250 - 2^0 */ + + square(&t, &t) /* 2^251 - 2^1 */ + square(&t, &t) /* 2^252 - 2^2 */ + square(&t, &t) /* 2^253 - 2^3 */ + + square(&t, &t) /* 2^254 - 2^4 */ + + square(&t, &t) /* 2^255 - 2^5 */ + mul(r, &t, &z11) /* 2^255 - 21 */ +} diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519_amd64.s b/vendor/golang.org/x/crypto/curve25519/curve25519_amd64.s new file mode 100644 index 00000000000..0250c888592 --- /dev/null +++ b/vendor/golang.org/x/crypto/curve25519/curve25519_amd64.s @@ -0,0 +1,1793 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This code was translated into a form compatible with 6a from the public +// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html + +// +build amd64,!gccgo,!appengine,!purego + +#define REDMASK51 0x0007FFFFFFFFFFFF + +// These constants cannot be encoded in non-MOVQ immediates. +// We access them directly from memory instead. + +DATA ·_121666_213(SB)/8, $996687872 +GLOBL ·_121666_213(SB), 8, $8 + +DATA ·_2P0(SB)/8, $0xFFFFFFFFFFFDA +GLOBL ·_2P0(SB), 8, $8 + +DATA ·_2P1234(SB)/8, $0xFFFFFFFFFFFFE +GLOBL ·_2P1234(SB), 8, $8 + +// func freeze(inout *[5]uint64) +TEXT ·freeze(SB),7,$0-8 + MOVQ inout+0(FP), DI + + MOVQ 0(DI),SI + MOVQ 8(DI),DX + MOVQ 16(DI),CX + MOVQ 24(DI),R8 + MOVQ 32(DI),R9 + MOVQ $REDMASK51,AX + MOVQ AX,R10 + SUBQ $18,R10 + MOVQ $3,R11 +REDUCELOOP: + MOVQ SI,R12 + SHRQ $51,R12 + ANDQ AX,SI + ADDQ R12,DX + MOVQ DX,R12 + SHRQ $51,R12 + ANDQ AX,DX + ADDQ R12,CX + MOVQ CX,R12 + SHRQ $51,R12 + ANDQ AX,CX + ADDQ R12,R8 + MOVQ R8,R12 + SHRQ $51,R12 + ANDQ AX,R8 + ADDQ R12,R9 + MOVQ R9,R12 + SHRQ $51,R12 + ANDQ AX,R9 + IMUL3Q $19,R12,R12 + ADDQ R12,SI + SUBQ $1,R11 + JA REDUCELOOP + MOVQ $1,R12 + CMPQ R10,SI + CMOVQLT R11,R12 + CMPQ AX,DX + CMOVQNE R11,R12 + CMPQ AX,CX + CMOVQNE R11,R12 + CMPQ AX,R8 + CMOVQNE R11,R12 + CMPQ AX,R9 + CMOVQNE R11,R12 + NEGQ R12 + ANDQ R12,AX + ANDQ R12,R10 + SUBQ R10,SI + SUBQ AX,DX + SUBQ AX,CX + SUBQ AX,R8 + SUBQ AX,R9 + MOVQ SI,0(DI) + MOVQ DX,8(DI) + MOVQ CX,16(DI) + MOVQ R8,24(DI) + MOVQ R9,32(DI) + RET + +// func ladderstep(inout *[5][5]uint64) +TEXT ·ladderstep(SB),0,$296-8 + MOVQ inout+0(FP),DI + + MOVQ 40(DI),SI + MOVQ 48(DI),DX + MOVQ 56(DI),CX + MOVQ 64(DI),R8 + MOVQ 72(DI),R9 + MOVQ SI,AX + MOVQ DX,R10 + MOVQ CX,R11 + MOVQ R8,R12 + MOVQ R9,R13 + ADDQ ·_2P0(SB),AX + ADDQ ·_2P1234(SB),R10 + ADDQ ·_2P1234(SB),R11 + ADDQ ·_2P1234(SB),R12 + ADDQ ·_2P1234(SB),R13 + ADDQ 80(DI),SI + ADDQ 88(DI),DX + ADDQ 96(DI),CX + ADDQ 104(DI),R8 + ADDQ 112(DI),R9 + SUBQ 80(DI),AX + SUBQ 88(DI),R10 + SUBQ 96(DI),R11 + SUBQ 104(DI),R12 + SUBQ 112(DI),R13 + MOVQ SI,0(SP) + MOVQ DX,8(SP) + MOVQ CX,16(SP) + MOVQ R8,24(SP) + MOVQ R9,32(SP) + MOVQ AX,40(SP) + MOVQ R10,48(SP) + MOVQ R11,56(SP) + MOVQ R12,64(SP) + MOVQ R13,72(SP) + MOVQ 40(SP),AX + MULQ 40(SP) + MOVQ AX,SI + MOVQ DX,CX + MOVQ 40(SP),AX + SHLQ $1,AX + MULQ 48(SP) + MOVQ AX,R8 + MOVQ DX,R9 + MOVQ 40(SP),AX + SHLQ $1,AX + MULQ 56(SP) + MOVQ AX,R10 + MOVQ DX,R11 + MOVQ 40(SP),AX + SHLQ $1,AX + MULQ 64(SP) + MOVQ AX,R12 + MOVQ DX,R13 + MOVQ 40(SP),AX + SHLQ $1,AX + MULQ 72(SP) + MOVQ AX,R14 + MOVQ DX,R15 + MOVQ 48(SP),AX + MULQ 48(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 48(SP),AX + SHLQ $1,AX + MULQ 56(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 48(SP),AX + SHLQ $1,AX + MULQ 64(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 48(SP),DX + IMUL3Q $38,DX,AX + MULQ 72(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 56(SP),AX + MULQ 56(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 56(SP),DX + IMUL3Q $38,DX,AX + MULQ 64(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 56(SP),DX + IMUL3Q $38,DX,AX + MULQ 72(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 64(SP),DX + IMUL3Q $19,DX,AX + MULQ 64(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 64(SP),DX + IMUL3Q $38,DX,AX + MULQ 72(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 72(SP),DX + IMUL3Q $19,DX,AX + MULQ 72(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ $REDMASK51,DX + SHLQ $13,SI,CX + ANDQ DX,SI + SHLQ $13,R8,R9 + ANDQ DX,R8 + ADDQ CX,R8 + SHLQ $13,R10,R11 + ANDQ DX,R10 + ADDQ R9,R10 + SHLQ $13,R12,R13 + ANDQ DX,R12 + ADDQ R11,R12 + SHLQ $13,R14,R15 + ANDQ DX,R14 + ADDQ R13,R14 + IMUL3Q $19,R15,CX + ADDQ CX,SI + MOVQ SI,CX + SHRQ $51,CX + ADDQ R8,CX + ANDQ DX,SI + MOVQ CX,R8 + SHRQ $51,CX + ADDQ R10,CX + ANDQ DX,R8 + MOVQ CX,R9 + SHRQ $51,CX + ADDQ R12,CX + ANDQ DX,R9 + MOVQ CX,AX + SHRQ $51,CX + ADDQ R14,CX + ANDQ DX,AX + MOVQ CX,R10 + SHRQ $51,CX + IMUL3Q $19,CX,CX + ADDQ CX,SI + ANDQ DX,R10 + MOVQ SI,80(SP) + MOVQ R8,88(SP) + MOVQ R9,96(SP) + MOVQ AX,104(SP) + MOVQ R10,112(SP) + MOVQ 0(SP),AX + MULQ 0(SP) + MOVQ AX,SI + MOVQ DX,CX + MOVQ 0(SP),AX + SHLQ $1,AX + MULQ 8(SP) + MOVQ AX,R8 + MOVQ DX,R9 + MOVQ 0(SP),AX + SHLQ $1,AX + MULQ 16(SP) + MOVQ AX,R10 + MOVQ DX,R11 + MOVQ 0(SP),AX + SHLQ $1,AX + MULQ 24(SP) + MOVQ AX,R12 + MOVQ DX,R13 + MOVQ 0(SP),AX + SHLQ $1,AX + MULQ 32(SP) + MOVQ AX,R14 + MOVQ DX,R15 + MOVQ 8(SP),AX + MULQ 8(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 8(SP),AX + SHLQ $1,AX + MULQ 16(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 8(SP),AX + SHLQ $1,AX + MULQ 24(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 8(SP),DX + IMUL3Q $38,DX,AX + MULQ 32(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 16(SP),AX + MULQ 16(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 16(SP),DX + IMUL3Q $38,DX,AX + MULQ 24(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 16(SP),DX + IMUL3Q $38,DX,AX + MULQ 32(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 24(SP),DX + IMUL3Q $19,DX,AX + MULQ 24(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 24(SP),DX + IMUL3Q $38,DX,AX + MULQ 32(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 32(SP),DX + IMUL3Q $19,DX,AX + MULQ 32(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ $REDMASK51,DX + SHLQ $13,SI,CX + ANDQ DX,SI + SHLQ $13,R8,R9 + ANDQ DX,R8 + ADDQ CX,R8 + SHLQ $13,R10,R11 + ANDQ DX,R10 + ADDQ R9,R10 + SHLQ $13,R12,R13 + ANDQ DX,R12 + ADDQ R11,R12 + SHLQ $13,R14,R15 + ANDQ DX,R14 + ADDQ R13,R14 + IMUL3Q $19,R15,CX + ADDQ CX,SI + MOVQ SI,CX + SHRQ $51,CX + ADDQ R8,CX + ANDQ DX,SI + MOVQ CX,R8 + SHRQ $51,CX + ADDQ R10,CX + ANDQ DX,R8 + MOVQ CX,R9 + SHRQ $51,CX + ADDQ R12,CX + ANDQ DX,R9 + MOVQ CX,AX + SHRQ $51,CX + ADDQ R14,CX + ANDQ DX,AX + MOVQ CX,R10 + SHRQ $51,CX + IMUL3Q $19,CX,CX + ADDQ CX,SI + ANDQ DX,R10 + MOVQ SI,120(SP) + MOVQ R8,128(SP) + MOVQ R9,136(SP) + MOVQ AX,144(SP) + MOVQ R10,152(SP) + MOVQ SI,SI + MOVQ R8,DX + MOVQ R9,CX + MOVQ AX,R8 + MOVQ R10,R9 + ADDQ ·_2P0(SB),SI + ADDQ ·_2P1234(SB),DX + ADDQ ·_2P1234(SB),CX + ADDQ ·_2P1234(SB),R8 + ADDQ ·_2P1234(SB),R9 + SUBQ 80(SP),SI + SUBQ 88(SP),DX + SUBQ 96(SP),CX + SUBQ 104(SP),R8 + SUBQ 112(SP),R9 + MOVQ SI,160(SP) + MOVQ DX,168(SP) + MOVQ CX,176(SP) + MOVQ R8,184(SP) + MOVQ R9,192(SP) + MOVQ 120(DI),SI + MOVQ 128(DI),DX + MOVQ 136(DI),CX + MOVQ 144(DI),R8 + MOVQ 152(DI),R9 + MOVQ SI,AX + MOVQ DX,R10 + MOVQ CX,R11 + MOVQ R8,R12 + MOVQ R9,R13 + ADDQ ·_2P0(SB),AX + ADDQ ·_2P1234(SB),R10 + ADDQ ·_2P1234(SB),R11 + ADDQ ·_2P1234(SB),R12 + ADDQ ·_2P1234(SB),R13 + ADDQ 160(DI),SI + ADDQ 168(DI),DX + ADDQ 176(DI),CX + ADDQ 184(DI),R8 + ADDQ 192(DI),R9 + SUBQ 160(DI),AX + SUBQ 168(DI),R10 + SUBQ 176(DI),R11 + SUBQ 184(DI),R12 + SUBQ 192(DI),R13 + MOVQ SI,200(SP) + MOVQ DX,208(SP) + MOVQ CX,216(SP) + MOVQ R8,224(SP) + MOVQ R9,232(SP) + MOVQ AX,240(SP) + MOVQ R10,248(SP) + MOVQ R11,256(SP) + MOVQ R12,264(SP) + MOVQ R13,272(SP) + MOVQ 224(SP),SI + IMUL3Q $19,SI,AX + MOVQ AX,280(SP) + MULQ 56(SP) + MOVQ AX,SI + MOVQ DX,CX + MOVQ 232(SP),DX + IMUL3Q $19,DX,AX + MOVQ AX,288(SP) + MULQ 48(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 200(SP),AX + MULQ 40(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 200(SP),AX + MULQ 48(SP) + MOVQ AX,R8 + MOVQ DX,R9 + MOVQ 200(SP),AX + MULQ 56(SP) + MOVQ AX,R10 + MOVQ DX,R11 + MOVQ 200(SP),AX + MULQ 64(SP) + MOVQ AX,R12 + MOVQ DX,R13 + MOVQ 200(SP),AX + MULQ 72(SP) + MOVQ AX,R14 + MOVQ DX,R15 + MOVQ 208(SP),AX + MULQ 40(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 208(SP),AX + MULQ 48(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 208(SP),AX + MULQ 56(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 208(SP),AX + MULQ 64(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 208(SP),DX + IMUL3Q $19,DX,AX + MULQ 72(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 216(SP),AX + MULQ 40(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 216(SP),AX + MULQ 48(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 216(SP),AX + MULQ 56(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 216(SP),DX + IMUL3Q $19,DX,AX + MULQ 64(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 216(SP),DX + IMUL3Q $19,DX,AX + MULQ 72(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 224(SP),AX + MULQ 40(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 224(SP),AX + MULQ 48(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 280(SP),AX + MULQ 64(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 280(SP),AX + MULQ 72(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 232(SP),AX + MULQ 40(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 288(SP),AX + MULQ 56(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 288(SP),AX + MULQ 64(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 288(SP),AX + MULQ 72(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ $REDMASK51,DX + SHLQ $13,SI,CX + ANDQ DX,SI + SHLQ $13,R8,R9 + ANDQ DX,R8 + ADDQ CX,R8 + SHLQ $13,R10,R11 + ANDQ DX,R10 + ADDQ R9,R10 + SHLQ $13,R12,R13 + ANDQ DX,R12 + ADDQ R11,R12 + SHLQ $13,R14,R15 + ANDQ DX,R14 + ADDQ R13,R14 + IMUL3Q $19,R15,CX + ADDQ CX,SI + MOVQ SI,CX + SHRQ $51,CX + ADDQ R8,CX + MOVQ CX,R8 + SHRQ $51,CX + ANDQ DX,SI + ADDQ R10,CX + MOVQ CX,R9 + SHRQ $51,CX + ANDQ DX,R8 + ADDQ R12,CX + MOVQ CX,AX + SHRQ $51,CX + ANDQ DX,R9 + ADDQ R14,CX + MOVQ CX,R10 + SHRQ $51,CX + ANDQ DX,AX + IMUL3Q $19,CX,CX + ADDQ CX,SI + ANDQ DX,R10 + MOVQ SI,40(SP) + MOVQ R8,48(SP) + MOVQ R9,56(SP) + MOVQ AX,64(SP) + MOVQ R10,72(SP) + MOVQ 264(SP),SI + IMUL3Q $19,SI,AX + MOVQ AX,200(SP) + MULQ 16(SP) + MOVQ AX,SI + MOVQ DX,CX + MOVQ 272(SP),DX + IMUL3Q $19,DX,AX + MOVQ AX,208(SP) + MULQ 8(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 240(SP),AX + MULQ 0(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 240(SP),AX + MULQ 8(SP) + MOVQ AX,R8 + MOVQ DX,R9 + MOVQ 240(SP),AX + MULQ 16(SP) + MOVQ AX,R10 + MOVQ DX,R11 + MOVQ 240(SP),AX + MULQ 24(SP) + MOVQ AX,R12 + MOVQ DX,R13 + MOVQ 240(SP),AX + MULQ 32(SP) + MOVQ AX,R14 + MOVQ DX,R15 + MOVQ 248(SP),AX + MULQ 0(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 248(SP),AX + MULQ 8(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 248(SP),AX + MULQ 16(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 248(SP),AX + MULQ 24(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 248(SP),DX + IMUL3Q $19,DX,AX + MULQ 32(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 256(SP),AX + MULQ 0(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 256(SP),AX + MULQ 8(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 256(SP),AX + MULQ 16(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 256(SP),DX + IMUL3Q $19,DX,AX + MULQ 24(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 256(SP),DX + IMUL3Q $19,DX,AX + MULQ 32(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 264(SP),AX + MULQ 0(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 264(SP),AX + MULQ 8(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 200(SP),AX + MULQ 24(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 200(SP),AX + MULQ 32(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 272(SP),AX + MULQ 0(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 208(SP),AX + MULQ 16(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 208(SP),AX + MULQ 24(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 208(SP),AX + MULQ 32(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ $REDMASK51,DX + SHLQ $13,SI,CX + ANDQ DX,SI + SHLQ $13,R8,R9 + ANDQ DX,R8 + ADDQ CX,R8 + SHLQ $13,R10,R11 + ANDQ DX,R10 + ADDQ R9,R10 + SHLQ $13,R12,R13 + ANDQ DX,R12 + ADDQ R11,R12 + SHLQ $13,R14,R15 + ANDQ DX,R14 + ADDQ R13,R14 + IMUL3Q $19,R15,CX + ADDQ CX,SI + MOVQ SI,CX + SHRQ $51,CX + ADDQ R8,CX + MOVQ CX,R8 + SHRQ $51,CX + ANDQ DX,SI + ADDQ R10,CX + MOVQ CX,R9 + SHRQ $51,CX + ANDQ DX,R8 + ADDQ R12,CX + MOVQ CX,AX + SHRQ $51,CX + ANDQ DX,R9 + ADDQ R14,CX + MOVQ CX,R10 + SHRQ $51,CX + ANDQ DX,AX + IMUL3Q $19,CX,CX + ADDQ CX,SI + ANDQ DX,R10 + MOVQ SI,DX + MOVQ R8,CX + MOVQ R9,R11 + MOVQ AX,R12 + MOVQ R10,R13 + ADDQ ·_2P0(SB),DX + ADDQ ·_2P1234(SB),CX + ADDQ ·_2P1234(SB),R11 + ADDQ ·_2P1234(SB),R12 + ADDQ ·_2P1234(SB),R13 + ADDQ 40(SP),SI + ADDQ 48(SP),R8 + ADDQ 56(SP),R9 + ADDQ 64(SP),AX + ADDQ 72(SP),R10 + SUBQ 40(SP),DX + SUBQ 48(SP),CX + SUBQ 56(SP),R11 + SUBQ 64(SP),R12 + SUBQ 72(SP),R13 + MOVQ SI,120(DI) + MOVQ R8,128(DI) + MOVQ R9,136(DI) + MOVQ AX,144(DI) + MOVQ R10,152(DI) + MOVQ DX,160(DI) + MOVQ CX,168(DI) + MOVQ R11,176(DI) + MOVQ R12,184(DI) + MOVQ R13,192(DI) + MOVQ 120(DI),AX + MULQ 120(DI) + MOVQ AX,SI + MOVQ DX,CX + MOVQ 120(DI),AX + SHLQ $1,AX + MULQ 128(DI) + MOVQ AX,R8 + MOVQ DX,R9 + MOVQ 120(DI),AX + SHLQ $1,AX + MULQ 136(DI) + MOVQ AX,R10 + MOVQ DX,R11 + MOVQ 120(DI),AX + SHLQ $1,AX + MULQ 144(DI) + MOVQ AX,R12 + MOVQ DX,R13 + MOVQ 120(DI),AX + SHLQ $1,AX + MULQ 152(DI) + MOVQ AX,R14 + MOVQ DX,R15 + MOVQ 128(DI),AX + MULQ 128(DI) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 128(DI),AX + SHLQ $1,AX + MULQ 136(DI) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 128(DI),AX + SHLQ $1,AX + MULQ 144(DI) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 128(DI),DX + IMUL3Q $38,DX,AX + MULQ 152(DI) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 136(DI),AX + MULQ 136(DI) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 136(DI),DX + IMUL3Q $38,DX,AX + MULQ 144(DI) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 136(DI),DX + IMUL3Q $38,DX,AX + MULQ 152(DI) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 144(DI),DX + IMUL3Q $19,DX,AX + MULQ 144(DI) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 144(DI),DX + IMUL3Q $38,DX,AX + MULQ 152(DI) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 152(DI),DX + IMUL3Q $19,DX,AX + MULQ 152(DI) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ $REDMASK51,DX + SHLQ $13,SI,CX + ANDQ DX,SI + SHLQ $13,R8,R9 + ANDQ DX,R8 + ADDQ CX,R8 + SHLQ $13,R10,R11 + ANDQ DX,R10 + ADDQ R9,R10 + SHLQ $13,R12,R13 + ANDQ DX,R12 + ADDQ R11,R12 + SHLQ $13,R14,R15 + ANDQ DX,R14 + ADDQ R13,R14 + IMUL3Q $19,R15,CX + ADDQ CX,SI + MOVQ SI,CX + SHRQ $51,CX + ADDQ R8,CX + ANDQ DX,SI + MOVQ CX,R8 + SHRQ $51,CX + ADDQ R10,CX + ANDQ DX,R8 + MOVQ CX,R9 + SHRQ $51,CX + ADDQ R12,CX + ANDQ DX,R9 + MOVQ CX,AX + SHRQ $51,CX + ADDQ R14,CX + ANDQ DX,AX + MOVQ CX,R10 + SHRQ $51,CX + IMUL3Q $19,CX,CX + ADDQ CX,SI + ANDQ DX,R10 + MOVQ SI,120(DI) + MOVQ R8,128(DI) + MOVQ R9,136(DI) + MOVQ AX,144(DI) + MOVQ R10,152(DI) + MOVQ 160(DI),AX + MULQ 160(DI) + MOVQ AX,SI + MOVQ DX,CX + MOVQ 160(DI),AX + SHLQ $1,AX + MULQ 168(DI) + MOVQ AX,R8 + MOVQ DX,R9 + MOVQ 160(DI),AX + SHLQ $1,AX + MULQ 176(DI) + MOVQ AX,R10 + MOVQ DX,R11 + MOVQ 160(DI),AX + SHLQ $1,AX + MULQ 184(DI) + MOVQ AX,R12 + MOVQ DX,R13 + MOVQ 160(DI),AX + SHLQ $1,AX + MULQ 192(DI) + MOVQ AX,R14 + MOVQ DX,R15 + MOVQ 168(DI),AX + MULQ 168(DI) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 168(DI),AX + SHLQ $1,AX + MULQ 176(DI) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 168(DI),AX + SHLQ $1,AX + MULQ 184(DI) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 168(DI),DX + IMUL3Q $38,DX,AX + MULQ 192(DI) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 176(DI),AX + MULQ 176(DI) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 176(DI),DX + IMUL3Q $38,DX,AX + MULQ 184(DI) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 176(DI),DX + IMUL3Q $38,DX,AX + MULQ 192(DI) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 184(DI),DX + IMUL3Q $19,DX,AX + MULQ 184(DI) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 184(DI),DX + IMUL3Q $38,DX,AX + MULQ 192(DI) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 192(DI),DX + IMUL3Q $19,DX,AX + MULQ 192(DI) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ $REDMASK51,DX + SHLQ $13,SI,CX + ANDQ DX,SI + SHLQ $13,R8,R9 + ANDQ DX,R8 + ADDQ CX,R8 + SHLQ $13,R10,R11 + ANDQ DX,R10 + ADDQ R9,R10 + SHLQ $13,R12,R13 + ANDQ DX,R12 + ADDQ R11,R12 + SHLQ $13,R14,R15 + ANDQ DX,R14 + ADDQ R13,R14 + IMUL3Q $19,R15,CX + ADDQ CX,SI + MOVQ SI,CX + SHRQ $51,CX + ADDQ R8,CX + ANDQ DX,SI + MOVQ CX,R8 + SHRQ $51,CX + ADDQ R10,CX + ANDQ DX,R8 + MOVQ CX,R9 + SHRQ $51,CX + ADDQ R12,CX + ANDQ DX,R9 + MOVQ CX,AX + SHRQ $51,CX + ADDQ R14,CX + ANDQ DX,AX + MOVQ CX,R10 + SHRQ $51,CX + IMUL3Q $19,CX,CX + ADDQ CX,SI + ANDQ DX,R10 + MOVQ SI,160(DI) + MOVQ R8,168(DI) + MOVQ R9,176(DI) + MOVQ AX,184(DI) + MOVQ R10,192(DI) + MOVQ 184(DI),SI + IMUL3Q $19,SI,AX + MOVQ AX,0(SP) + MULQ 16(DI) + MOVQ AX,SI + MOVQ DX,CX + MOVQ 192(DI),DX + IMUL3Q $19,DX,AX + MOVQ AX,8(SP) + MULQ 8(DI) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 160(DI),AX + MULQ 0(DI) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 160(DI),AX + MULQ 8(DI) + MOVQ AX,R8 + MOVQ DX,R9 + MOVQ 160(DI),AX + MULQ 16(DI) + MOVQ AX,R10 + MOVQ DX,R11 + MOVQ 160(DI),AX + MULQ 24(DI) + MOVQ AX,R12 + MOVQ DX,R13 + MOVQ 160(DI),AX + MULQ 32(DI) + MOVQ AX,R14 + MOVQ DX,R15 + MOVQ 168(DI),AX + MULQ 0(DI) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 168(DI),AX + MULQ 8(DI) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 168(DI),AX + MULQ 16(DI) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 168(DI),AX + MULQ 24(DI) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 168(DI),DX + IMUL3Q $19,DX,AX + MULQ 32(DI) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 176(DI),AX + MULQ 0(DI) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 176(DI),AX + MULQ 8(DI) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 176(DI),AX + MULQ 16(DI) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 176(DI),DX + IMUL3Q $19,DX,AX + MULQ 24(DI) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 176(DI),DX + IMUL3Q $19,DX,AX + MULQ 32(DI) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 184(DI),AX + MULQ 0(DI) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 184(DI),AX + MULQ 8(DI) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 0(SP),AX + MULQ 24(DI) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 0(SP),AX + MULQ 32(DI) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 192(DI),AX + MULQ 0(DI) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 8(SP),AX + MULQ 16(DI) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 8(SP),AX + MULQ 24(DI) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 8(SP),AX + MULQ 32(DI) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ $REDMASK51,DX + SHLQ $13,SI,CX + ANDQ DX,SI + SHLQ $13,R8,R9 + ANDQ DX,R8 + ADDQ CX,R8 + SHLQ $13,R10,R11 + ANDQ DX,R10 + ADDQ R9,R10 + SHLQ $13,R12,R13 + ANDQ DX,R12 + ADDQ R11,R12 + SHLQ $13,R14,R15 + ANDQ DX,R14 + ADDQ R13,R14 + IMUL3Q $19,R15,CX + ADDQ CX,SI + MOVQ SI,CX + SHRQ $51,CX + ADDQ R8,CX + MOVQ CX,R8 + SHRQ $51,CX + ANDQ DX,SI + ADDQ R10,CX + MOVQ CX,R9 + SHRQ $51,CX + ANDQ DX,R8 + ADDQ R12,CX + MOVQ CX,AX + SHRQ $51,CX + ANDQ DX,R9 + ADDQ R14,CX + MOVQ CX,R10 + SHRQ $51,CX + ANDQ DX,AX + IMUL3Q $19,CX,CX + ADDQ CX,SI + ANDQ DX,R10 + MOVQ SI,160(DI) + MOVQ R8,168(DI) + MOVQ R9,176(DI) + MOVQ AX,184(DI) + MOVQ R10,192(DI) + MOVQ 144(SP),SI + IMUL3Q $19,SI,AX + MOVQ AX,0(SP) + MULQ 96(SP) + MOVQ AX,SI + MOVQ DX,CX + MOVQ 152(SP),DX + IMUL3Q $19,DX,AX + MOVQ AX,8(SP) + MULQ 88(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 120(SP),AX + MULQ 80(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 120(SP),AX + MULQ 88(SP) + MOVQ AX,R8 + MOVQ DX,R9 + MOVQ 120(SP),AX + MULQ 96(SP) + MOVQ AX,R10 + MOVQ DX,R11 + MOVQ 120(SP),AX + MULQ 104(SP) + MOVQ AX,R12 + MOVQ DX,R13 + MOVQ 120(SP),AX + MULQ 112(SP) + MOVQ AX,R14 + MOVQ DX,R15 + MOVQ 128(SP),AX + MULQ 80(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 128(SP),AX + MULQ 88(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 128(SP),AX + MULQ 96(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 128(SP),AX + MULQ 104(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 128(SP),DX + IMUL3Q $19,DX,AX + MULQ 112(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 136(SP),AX + MULQ 80(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 136(SP),AX + MULQ 88(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 136(SP),AX + MULQ 96(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 136(SP),DX + IMUL3Q $19,DX,AX + MULQ 104(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 136(SP),DX + IMUL3Q $19,DX,AX + MULQ 112(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 144(SP),AX + MULQ 80(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 144(SP),AX + MULQ 88(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 0(SP),AX + MULQ 104(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 0(SP),AX + MULQ 112(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 152(SP),AX + MULQ 80(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 8(SP),AX + MULQ 96(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 8(SP),AX + MULQ 104(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 8(SP),AX + MULQ 112(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ $REDMASK51,DX + SHLQ $13,SI,CX + ANDQ DX,SI + SHLQ $13,R8,R9 + ANDQ DX,R8 + ADDQ CX,R8 + SHLQ $13,R10,R11 + ANDQ DX,R10 + ADDQ R9,R10 + SHLQ $13,R12,R13 + ANDQ DX,R12 + ADDQ R11,R12 + SHLQ $13,R14,R15 + ANDQ DX,R14 + ADDQ R13,R14 + IMUL3Q $19,R15,CX + ADDQ CX,SI + MOVQ SI,CX + SHRQ $51,CX + ADDQ R8,CX + MOVQ CX,R8 + SHRQ $51,CX + ANDQ DX,SI + ADDQ R10,CX + MOVQ CX,R9 + SHRQ $51,CX + ANDQ DX,R8 + ADDQ R12,CX + MOVQ CX,AX + SHRQ $51,CX + ANDQ DX,R9 + ADDQ R14,CX + MOVQ CX,R10 + SHRQ $51,CX + ANDQ DX,AX + IMUL3Q $19,CX,CX + ADDQ CX,SI + ANDQ DX,R10 + MOVQ SI,40(DI) + MOVQ R8,48(DI) + MOVQ R9,56(DI) + MOVQ AX,64(DI) + MOVQ R10,72(DI) + MOVQ 160(SP),AX + MULQ ·_121666_213(SB) + SHRQ $13,AX + MOVQ AX,SI + MOVQ DX,CX + MOVQ 168(SP),AX + MULQ ·_121666_213(SB) + SHRQ $13,AX + ADDQ AX,CX + MOVQ DX,R8 + MOVQ 176(SP),AX + MULQ ·_121666_213(SB) + SHRQ $13,AX + ADDQ AX,R8 + MOVQ DX,R9 + MOVQ 184(SP),AX + MULQ ·_121666_213(SB) + SHRQ $13,AX + ADDQ AX,R9 + MOVQ DX,R10 + MOVQ 192(SP),AX + MULQ ·_121666_213(SB) + SHRQ $13,AX + ADDQ AX,R10 + IMUL3Q $19,DX,DX + ADDQ DX,SI + ADDQ 80(SP),SI + ADDQ 88(SP),CX + ADDQ 96(SP),R8 + ADDQ 104(SP),R9 + ADDQ 112(SP),R10 + MOVQ SI,80(DI) + MOVQ CX,88(DI) + MOVQ R8,96(DI) + MOVQ R9,104(DI) + MOVQ R10,112(DI) + MOVQ 104(DI),SI + IMUL3Q $19,SI,AX + MOVQ AX,0(SP) + MULQ 176(SP) + MOVQ AX,SI + MOVQ DX,CX + MOVQ 112(DI),DX + IMUL3Q $19,DX,AX + MOVQ AX,8(SP) + MULQ 168(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 80(DI),AX + MULQ 160(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 80(DI),AX + MULQ 168(SP) + MOVQ AX,R8 + MOVQ DX,R9 + MOVQ 80(DI),AX + MULQ 176(SP) + MOVQ AX,R10 + MOVQ DX,R11 + MOVQ 80(DI),AX + MULQ 184(SP) + MOVQ AX,R12 + MOVQ DX,R13 + MOVQ 80(DI),AX + MULQ 192(SP) + MOVQ AX,R14 + MOVQ DX,R15 + MOVQ 88(DI),AX + MULQ 160(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 88(DI),AX + MULQ 168(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 88(DI),AX + MULQ 176(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 88(DI),AX + MULQ 184(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 88(DI),DX + IMUL3Q $19,DX,AX + MULQ 192(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 96(DI),AX + MULQ 160(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 96(DI),AX + MULQ 168(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 96(DI),AX + MULQ 176(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 96(DI),DX + IMUL3Q $19,DX,AX + MULQ 184(SP) + ADDQ AX,SI + ADCQ DX,CX + MOVQ 96(DI),DX + IMUL3Q $19,DX,AX + MULQ 192(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 104(DI),AX + MULQ 160(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 104(DI),AX + MULQ 168(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 0(SP),AX + MULQ 184(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 0(SP),AX + MULQ 192(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 112(DI),AX + MULQ 160(SP) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 8(SP),AX + MULQ 176(SP) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 8(SP),AX + MULQ 184(SP) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 8(SP),AX + MULQ 192(SP) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ $REDMASK51,DX + SHLQ $13,SI,CX + ANDQ DX,SI + SHLQ $13,R8,R9 + ANDQ DX,R8 + ADDQ CX,R8 + SHLQ $13,R10,R11 + ANDQ DX,R10 + ADDQ R9,R10 + SHLQ $13,R12,R13 + ANDQ DX,R12 + ADDQ R11,R12 + SHLQ $13,R14,R15 + ANDQ DX,R14 + ADDQ R13,R14 + IMUL3Q $19,R15,CX + ADDQ CX,SI + MOVQ SI,CX + SHRQ $51,CX + ADDQ R8,CX + MOVQ CX,R8 + SHRQ $51,CX + ANDQ DX,SI + ADDQ R10,CX + MOVQ CX,R9 + SHRQ $51,CX + ANDQ DX,R8 + ADDQ R12,CX + MOVQ CX,AX + SHRQ $51,CX + ANDQ DX,R9 + ADDQ R14,CX + MOVQ CX,R10 + SHRQ $51,CX + ANDQ DX,AX + IMUL3Q $19,CX,CX + ADDQ CX,SI + ANDQ DX,R10 + MOVQ SI,80(DI) + MOVQ R8,88(DI) + MOVQ R9,96(DI) + MOVQ AX,104(DI) + MOVQ R10,112(DI) + RET + +// func cswap(inout *[4][5]uint64, v uint64) +TEXT ·cswap(SB),7,$0 + MOVQ inout+0(FP),DI + MOVQ v+8(FP),SI + + SUBQ $1, SI + NOTQ SI + MOVQ SI, X15 + PSHUFD $0x44, X15, X15 + + MOVOU 0(DI), X0 + MOVOU 16(DI), X2 + MOVOU 32(DI), X4 + MOVOU 48(DI), X6 + MOVOU 64(DI), X8 + MOVOU 80(DI), X1 + MOVOU 96(DI), X3 + MOVOU 112(DI), X5 + MOVOU 128(DI), X7 + MOVOU 144(DI), X9 + + MOVO X1, X10 + MOVO X3, X11 + MOVO X5, X12 + MOVO X7, X13 + MOVO X9, X14 + + PXOR X0, X10 + PXOR X2, X11 + PXOR X4, X12 + PXOR X6, X13 + PXOR X8, X14 + PAND X15, X10 + PAND X15, X11 + PAND X15, X12 + PAND X15, X13 + PAND X15, X14 + PXOR X10, X0 + PXOR X10, X1 + PXOR X11, X2 + PXOR X11, X3 + PXOR X12, X4 + PXOR X12, X5 + PXOR X13, X6 + PXOR X13, X7 + PXOR X14, X8 + PXOR X14, X9 + + MOVOU X0, 0(DI) + MOVOU X2, 16(DI) + MOVOU X4, 32(DI) + MOVOU X6, 48(DI) + MOVOU X8, 64(DI) + MOVOU X1, 80(DI) + MOVOU X3, 96(DI) + MOVOU X5, 112(DI) + MOVOU X7, 128(DI) + MOVOU X9, 144(DI) + RET + +// func mul(dest, a, b *[5]uint64) +TEXT ·mul(SB),0,$16-24 + MOVQ dest+0(FP), DI + MOVQ a+8(FP), SI + MOVQ b+16(FP), DX + + MOVQ DX,CX + MOVQ 24(SI),DX + IMUL3Q $19,DX,AX + MOVQ AX,0(SP) + MULQ 16(CX) + MOVQ AX,R8 + MOVQ DX,R9 + MOVQ 32(SI),DX + IMUL3Q $19,DX,AX + MOVQ AX,8(SP) + MULQ 8(CX) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 0(SI),AX + MULQ 0(CX) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 0(SI),AX + MULQ 8(CX) + MOVQ AX,R10 + MOVQ DX,R11 + MOVQ 0(SI),AX + MULQ 16(CX) + MOVQ AX,R12 + MOVQ DX,R13 + MOVQ 0(SI),AX + MULQ 24(CX) + MOVQ AX,R14 + MOVQ DX,R15 + MOVQ 0(SI),AX + MULQ 32(CX) + MOVQ AX,BX + MOVQ DX,BP + MOVQ 8(SI),AX + MULQ 0(CX) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 8(SI),AX + MULQ 8(CX) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 8(SI),AX + MULQ 16(CX) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 8(SI),AX + MULQ 24(CX) + ADDQ AX,BX + ADCQ DX,BP + MOVQ 8(SI),DX + IMUL3Q $19,DX,AX + MULQ 32(CX) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 16(SI),AX + MULQ 0(CX) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 16(SI),AX + MULQ 8(CX) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 16(SI),AX + MULQ 16(CX) + ADDQ AX,BX + ADCQ DX,BP + MOVQ 16(SI),DX + IMUL3Q $19,DX,AX + MULQ 24(CX) + ADDQ AX,R8 + ADCQ DX,R9 + MOVQ 16(SI),DX + IMUL3Q $19,DX,AX + MULQ 32(CX) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 24(SI),AX + MULQ 0(CX) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ 24(SI),AX + MULQ 8(CX) + ADDQ AX,BX + ADCQ DX,BP + MOVQ 0(SP),AX + MULQ 24(CX) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 0(SP),AX + MULQ 32(CX) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 32(SI),AX + MULQ 0(CX) + ADDQ AX,BX + ADCQ DX,BP + MOVQ 8(SP),AX + MULQ 16(CX) + ADDQ AX,R10 + ADCQ DX,R11 + MOVQ 8(SP),AX + MULQ 24(CX) + ADDQ AX,R12 + ADCQ DX,R13 + MOVQ 8(SP),AX + MULQ 32(CX) + ADDQ AX,R14 + ADCQ DX,R15 + MOVQ $REDMASK51,SI + SHLQ $13,R8,R9 + ANDQ SI,R8 + SHLQ $13,R10,R11 + ANDQ SI,R10 + ADDQ R9,R10 + SHLQ $13,R12,R13 + ANDQ SI,R12 + ADDQ R11,R12 + SHLQ $13,R14,R15 + ANDQ SI,R14 + ADDQ R13,R14 + SHLQ $13,BX,BP + ANDQ SI,BX + ADDQ R15,BX + IMUL3Q $19,BP,DX + ADDQ DX,R8 + MOVQ R8,DX + SHRQ $51,DX + ADDQ R10,DX + MOVQ DX,CX + SHRQ $51,DX + ANDQ SI,R8 + ADDQ R12,DX + MOVQ DX,R9 + SHRQ $51,DX + ANDQ SI,CX + ADDQ R14,DX + MOVQ DX,AX + SHRQ $51,DX + ANDQ SI,R9 + ADDQ BX,DX + MOVQ DX,R10 + SHRQ $51,DX + ANDQ SI,AX + IMUL3Q $19,DX,DX + ADDQ DX,R8 + ANDQ SI,R10 + MOVQ R8,0(DI) + MOVQ CX,8(DI) + MOVQ R9,16(DI) + MOVQ AX,24(DI) + MOVQ R10,32(DI) + RET + +// func square(out, in *[5]uint64) +TEXT ·square(SB),7,$0-16 + MOVQ out+0(FP), DI + MOVQ in+8(FP), SI + + MOVQ 0(SI),AX + MULQ 0(SI) + MOVQ AX,CX + MOVQ DX,R8 + MOVQ 0(SI),AX + SHLQ $1,AX + MULQ 8(SI) + MOVQ AX,R9 + MOVQ DX,R10 + MOVQ 0(SI),AX + SHLQ $1,AX + MULQ 16(SI) + MOVQ AX,R11 + MOVQ DX,R12 + MOVQ 0(SI),AX + SHLQ $1,AX + MULQ 24(SI) + MOVQ AX,R13 + MOVQ DX,R14 + MOVQ 0(SI),AX + SHLQ $1,AX + MULQ 32(SI) + MOVQ AX,R15 + MOVQ DX,BX + MOVQ 8(SI),AX + MULQ 8(SI) + ADDQ AX,R11 + ADCQ DX,R12 + MOVQ 8(SI),AX + SHLQ $1,AX + MULQ 16(SI) + ADDQ AX,R13 + ADCQ DX,R14 + MOVQ 8(SI),AX + SHLQ $1,AX + MULQ 24(SI) + ADDQ AX,R15 + ADCQ DX,BX + MOVQ 8(SI),DX + IMUL3Q $38,DX,AX + MULQ 32(SI) + ADDQ AX,CX + ADCQ DX,R8 + MOVQ 16(SI),AX + MULQ 16(SI) + ADDQ AX,R15 + ADCQ DX,BX + MOVQ 16(SI),DX + IMUL3Q $38,DX,AX + MULQ 24(SI) + ADDQ AX,CX + ADCQ DX,R8 + MOVQ 16(SI),DX + IMUL3Q $38,DX,AX + MULQ 32(SI) + ADDQ AX,R9 + ADCQ DX,R10 + MOVQ 24(SI),DX + IMUL3Q $19,DX,AX + MULQ 24(SI) + ADDQ AX,R9 + ADCQ DX,R10 + MOVQ 24(SI),DX + IMUL3Q $38,DX,AX + MULQ 32(SI) + ADDQ AX,R11 + ADCQ DX,R12 + MOVQ 32(SI),DX + IMUL3Q $19,DX,AX + MULQ 32(SI) + ADDQ AX,R13 + ADCQ DX,R14 + MOVQ $REDMASK51,SI + SHLQ $13,CX,R8 + ANDQ SI,CX + SHLQ $13,R9,R10 + ANDQ SI,R9 + ADDQ R8,R9 + SHLQ $13,R11,R12 + ANDQ SI,R11 + ADDQ R10,R11 + SHLQ $13,R13,R14 + ANDQ SI,R13 + ADDQ R12,R13 + SHLQ $13,R15,BX + ANDQ SI,R15 + ADDQ R14,R15 + IMUL3Q $19,BX,DX + ADDQ DX,CX + MOVQ CX,DX + SHRQ $51,DX + ADDQ R9,DX + ANDQ SI,CX + MOVQ DX,R8 + SHRQ $51,DX + ADDQ R11,DX + ANDQ SI,R8 + MOVQ DX,R9 + SHRQ $51,DX + ADDQ R13,DX + ANDQ SI,R9 + MOVQ DX,AX + SHRQ $51,DX + ADDQ R15,DX + ANDQ SI,AX + MOVQ DX,R10 + SHRQ $51,DX + IMUL3Q $19,DX,DX + ADDQ DX,CX + ANDQ SI,R10 + MOVQ CX,0(DI) + MOVQ R8,8(DI) + MOVQ R9,16(DI) + MOVQ AX,24(DI) + MOVQ R10,32(DI) + RET diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519_generic.go b/vendor/golang.org/x/crypto/curve25519/curve25519_generic.go new file mode 100644 index 00000000000..c43b13fc83e --- /dev/null +++ b/vendor/golang.org/x/crypto/curve25519/curve25519_generic.go @@ -0,0 +1,828 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package curve25519 + +import "encoding/binary" + +// This code is a port of the public domain, "ref10" implementation of +// curve25519 from SUPERCOP 20130419 by D. J. Bernstein. + +// fieldElement represents an element of the field GF(2^255 - 19). An element +// t, entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 +// t[3]+2^102 t[4]+...+2^230 t[9]. Bounds on each t[i] vary depending on +// context. +type fieldElement [10]int32 + +func feZero(fe *fieldElement) { + for i := range fe { + fe[i] = 0 + } +} + +func feOne(fe *fieldElement) { + feZero(fe) + fe[0] = 1 +} + +func feAdd(dst, a, b *fieldElement) { + for i := range dst { + dst[i] = a[i] + b[i] + } +} + +func feSub(dst, a, b *fieldElement) { + for i := range dst { + dst[i] = a[i] - b[i] + } +} + +func feCopy(dst, src *fieldElement) { + for i := range dst { + dst[i] = src[i] + } +} + +// feCSwap replaces (f,g) with (g,f) if b == 1; replaces (f,g) with (f,g) if b == 0. +// +// Preconditions: b in {0,1}. +func feCSwap(f, g *fieldElement, b int32) { + b = -b + for i := range f { + t := b & (f[i] ^ g[i]) + f[i] ^= t + g[i] ^= t + } +} + +// load3 reads a 24-bit, little-endian value from in. +func load3(in []byte) int64 { + var r int64 + r = int64(in[0]) + r |= int64(in[1]) << 8 + r |= int64(in[2]) << 16 + return r +} + +// load4 reads a 32-bit, little-endian value from in. +func load4(in []byte) int64 { + return int64(binary.LittleEndian.Uint32(in)) +} + +func feFromBytes(dst *fieldElement, src *[32]byte) { + h0 := load4(src[:]) + h1 := load3(src[4:]) << 6 + h2 := load3(src[7:]) << 5 + h3 := load3(src[10:]) << 3 + h4 := load3(src[13:]) << 2 + h5 := load4(src[16:]) + h6 := load3(src[20:]) << 7 + h7 := load3(src[23:]) << 5 + h8 := load3(src[26:]) << 4 + h9 := (load3(src[29:]) & 0x7fffff) << 2 + + var carry [10]int64 + carry[9] = (h9 + 1<<24) >> 25 + h0 += carry[9] * 19 + h9 -= carry[9] << 25 + carry[1] = (h1 + 1<<24) >> 25 + h2 += carry[1] + h1 -= carry[1] << 25 + carry[3] = (h3 + 1<<24) >> 25 + h4 += carry[3] + h3 -= carry[3] << 25 + carry[5] = (h5 + 1<<24) >> 25 + h6 += carry[5] + h5 -= carry[5] << 25 + carry[7] = (h7 + 1<<24) >> 25 + h8 += carry[7] + h7 -= carry[7] << 25 + + carry[0] = (h0 + 1<<25) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + carry[2] = (h2 + 1<<25) >> 26 + h3 += carry[2] + h2 -= carry[2] << 26 + carry[4] = (h4 + 1<<25) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + carry[6] = (h6 + 1<<25) >> 26 + h7 += carry[6] + h6 -= carry[6] << 26 + carry[8] = (h8 + 1<<25) >> 26 + h9 += carry[8] + h8 -= carry[8] << 26 + + dst[0] = int32(h0) + dst[1] = int32(h1) + dst[2] = int32(h2) + dst[3] = int32(h3) + dst[4] = int32(h4) + dst[5] = int32(h5) + dst[6] = int32(h6) + dst[7] = int32(h7) + dst[8] = int32(h8) + dst[9] = int32(h9) +} + +// feToBytes marshals h to s. +// Preconditions: +// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. +// +// Write p=2^255-19; q=floor(h/p). +// Basic claim: q = floor(2^(-255)(h + 19 2^(-25)h9 + 2^(-1))). +// +// Proof: +// Have |h|<=p so |q|<=1 so |19^2 2^(-255) q|<1/4. +// Also have |h-2^230 h9|<2^230 so |19 2^(-255)(h-2^230 h9)|<1/4. +// +// Write y=2^(-1)-19^2 2^(-255)q-19 2^(-255)(h-2^230 h9). +// Then 0> 25 + q = (h[0] + q) >> 26 + q = (h[1] + q) >> 25 + q = (h[2] + q) >> 26 + q = (h[3] + q) >> 25 + q = (h[4] + q) >> 26 + q = (h[5] + q) >> 25 + q = (h[6] + q) >> 26 + q = (h[7] + q) >> 25 + q = (h[8] + q) >> 26 + q = (h[9] + q) >> 25 + + // Goal: Output h-(2^255-19)q, which is between 0 and 2^255-20. + h[0] += 19 * q + // Goal: Output h-2^255 q, which is between 0 and 2^255-20. + + carry[0] = h[0] >> 26 + h[1] += carry[0] + h[0] -= carry[0] << 26 + carry[1] = h[1] >> 25 + h[2] += carry[1] + h[1] -= carry[1] << 25 + carry[2] = h[2] >> 26 + h[3] += carry[2] + h[2] -= carry[2] << 26 + carry[3] = h[3] >> 25 + h[4] += carry[3] + h[3] -= carry[3] << 25 + carry[4] = h[4] >> 26 + h[5] += carry[4] + h[4] -= carry[4] << 26 + carry[5] = h[5] >> 25 + h[6] += carry[5] + h[5] -= carry[5] << 25 + carry[6] = h[6] >> 26 + h[7] += carry[6] + h[6] -= carry[6] << 26 + carry[7] = h[7] >> 25 + h[8] += carry[7] + h[7] -= carry[7] << 25 + carry[8] = h[8] >> 26 + h[9] += carry[8] + h[8] -= carry[8] << 26 + carry[9] = h[9] >> 25 + h[9] -= carry[9] << 25 + // h10 = carry9 + + // Goal: Output h[0]+...+2^255 h10-2^255 q, which is between 0 and 2^255-20. + // Have h[0]+...+2^230 h[9] between 0 and 2^255-1; + // evidently 2^255 h10-2^255 q = 0. + // Goal: Output h[0]+...+2^230 h[9]. + + s[0] = byte(h[0] >> 0) + s[1] = byte(h[0] >> 8) + s[2] = byte(h[0] >> 16) + s[3] = byte((h[0] >> 24) | (h[1] << 2)) + s[4] = byte(h[1] >> 6) + s[5] = byte(h[1] >> 14) + s[6] = byte((h[1] >> 22) | (h[2] << 3)) + s[7] = byte(h[2] >> 5) + s[8] = byte(h[2] >> 13) + s[9] = byte((h[2] >> 21) | (h[3] << 5)) + s[10] = byte(h[3] >> 3) + s[11] = byte(h[3] >> 11) + s[12] = byte((h[3] >> 19) | (h[4] << 6)) + s[13] = byte(h[4] >> 2) + s[14] = byte(h[4] >> 10) + s[15] = byte(h[4] >> 18) + s[16] = byte(h[5] >> 0) + s[17] = byte(h[5] >> 8) + s[18] = byte(h[5] >> 16) + s[19] = byte((h[5] >> 24) | (h[6] << 1)) + s[20] = byte(h[6] >> 7) + s[21] = byte(h[6] >> 15) + s[22] = byte((h[6] >> 23) | (h[7] << 3)) + s[23] = byte(h[7] >> 5) + s[24] = byte(h[7] >> 13) + s[25] = byte((h[7] >> 21) | (h[8] << 4)) + s[26] = byte(h[8] >> 4) + s[27] = byte(h[8] >> 12) + s[28] = byte((h[8] >> 20) | (h[9] << 6)) + s[29] = byte(h[9] >> 2) + s[30] = byte(h[9] >> 10) + s[31] = byte(h[9] >> 18) +} + +// feMul calculates h = f * g +// Can overlap h with f or g. +// +// Preconditions: +// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. +// |g| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. +// +// Postconditions: +// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. +// +// Notes on implementation strategy: +// +// Using schoolbook multiplication. +// Karatsuba would save a little in some cost models. +// +// Most multiplications by 2 and 19 are 32-bit precomputations; +// cheaper than 64-bit postcomputations. +// +// There is one remaining multiplication by 19 in the carry chain; +// one *19 precomputation can be merged into this, +// but the resulting data flow is considerably less clean. +// +// There are 12 carries below. +// 10 of them are 2-way parallelizable and vectorizable. +// Can get away with 11 carries, but then data flow is much deeper. +// +// With tighter constraints on inputs can squeeze carries into int32. +func feMul(h, f, g *fieldElement) { + f0 := f[0] + f1 := f[1] + f2 := f[2] + f3 := f[3] + f4 := f[4] + f5 := f[5] + f6 := f[6] + f7 := f[7] + f8 := f[8] + f9 := f[9] + g0 := g[0] + g1 := g[1] + g2 := g[2] + g3 := g[3] + g4 := g[4] + g5 := g[5] + g6 := g[6] + g7 := g[7] + g8 := g[8] + g9 := g[9] + g1_19 := 19 * g1 // 1.4*2^29 + g2_19 := 19 * g2 // 1.4*2^30; still ok + g3_19 := 19 * g3 + g4_19 := 19 * g4 + g5_19 := 19 * g5 + g6_19 := 19 * g6 + g7_19 := 19 * g7 + g8_19 := 19 * g8 + g9_19 := 19 * g9 + f1_2 := 2 * f1 + f3_2 := 2 * f3 + f5_2 := 2 * f5 + f7_2 := 2 * f7 + f9_2 := 2 * f9 + f0g0 := int64(f0) * int64(g0) + f0g1 := int64(f0) * int64(g1) + f0g2 := int64(f0) * int64(g2) + f0g3 := int64(f0) * int64(g3) + f0g4 := int64(f0) * int64(g4) + f0g5 := int64(f0) * int64(g5) + f0g6 := int64(f0) * int64(g6) + f0g7 := int64(f0) * int64(g7) + f0g8 := int64(f0) * int64(g8) + f0g9 := int64(f0) * int64(g9) + f1g0 := int64(f1) * int64(g0) + f1g1_2 := int64(f1_2) * int64(g1) + f1g2 := int64(f1) * int64(g2) + f1g3_2 := int64(f1_2) * int64(g3) + f1g4 := int64(f1) * int64(g4) + f1g5_2 := int64(f1_2) * int64(g5) + f1g6 := int64(f1) * int64(g6) + f1g7_2 := int64(f1_2) * int64(g7) + f1g8 := int64(f1) * int64(g8) + f1g9_38 := int64(f1_2) * int64(g9_19) + f2g0 := int64(f2) * int64(g0) + f2g1 := int64(f2) * int64(g1) + f2g2 := int64(f2) * int64(g2) + f2g3 := int64(f2) * int64(g3) + f2g4 := int64(f2) * int64(g4) + f2g5 := int64(f2) * int64(g5) + f2g6 := int64(f2) * int64(g6) + f2g7 := int64(f2) * int64(g7) + f2g8_19 := int64(f2) * int64(g8_19) + f2g9_19 := int64(f2) * int64(g9_19) + f3g0 := int64(f3) * int64(g0) + f3g1_2 := int64(f3_2) * int64(g1) + f3g2 := int64(f3) * int64(g2) + f3g3_2 := int64(f3_2) * int64(g3) + f3g4 := int64(f3) * int64(g4) + f3g5_2 := int64(f3_2) * int64(g5) + f3g6 := int64(f3) * int64(g6) + f3g7_38 := int64(f3_2) * int64(g7_19) + f3g8_19 := int64(f3) * int64(g8_19) + f3g9_38 := int64(f3_2) * int64(g9_19) + f4g0 := int64(f4) * int64(g0) + f4g1 := int64(f4) * int64(g1) + f4g2 := int64(f4) * int64(g2) + f4g3 := int64(f4) * int64(g3) + f4g4 := int64(f4) * int64(g4) + f4g5 := int64(f4) * int64(g5) + f4g6_19 := int64(f4) * int64(g6_19) + f4g7_19 := int64(f4) * int64(g7_19) + f4g8_19 := int64(f4) * int64(g8_19) + f4g9_19 := int64(f4) * int64(g9_19) + f5g0 := int64(f5) * int64(g0) + f5g1_2 := int64(f5_2) * int64(g1) + f5g2 := int64(f5) * int64(g2) + f5g3_2 := int64(f5_2) * int64(g3) + f5g4 := int64(f5) * int64(g4) + f5g5_38 := int64(f5_2) * int64(g5_19) + f5g6_19 := int64(f5) * int64(g6_19) + f5g7_38 := int64(f5_2) * int64(g7_19) + f5g8_19 := int64(f5) * int64(g8_19) + f5g9_38 := int64(f5_2) * int64(g9_19) + f6g0 := int64(f6) * int64(g0) + f6g1 := int64(f6) * int64(g1) + f6g2 := int64(f6) * int64(g2) + f6g3 := int64(f6) * int64(g3) + f6g4_19 := int64(f6) * int64(g4_19) + f6g5_19 := int64(f6) * int64(g5_19) + f6g6_19 := int64(f6) * int64(g6_19) + f6g7_19 := int64(f6) * int64(g7_19) + f6g8_19 := int64(f6) * int64(g8_19) + f6g9_19 := int64(f6) * int64(g9_19) + f7g0 := int64(f7) * int64(g0) + f7g1_2 := int64(f7_2) * int64(g1) + f7g2 := int64(f7) * int64(g2) + f7g3_38 := int64(f7_2) * int64(g3_19) + f7g4_19 := int64(f7) * int64(g4_19) + f7g5_38 := int64(f7_2) * int64(g5_19) + f7g6_19 := int64(f7) * int64(g6_19) + f7g7_38 := int64(f7_2) * int64(g7_19) + f7g8_19 := int64(f7) * int64(g8_19) + f7g9_38 := int64(f7_2) * int64(g9_19) + f8g0 := int64(f8) * int64(g0) + f8g1 := int64(f8) * int64(g1) + f8g2_19 := int64(f8) * int64(g2_19) + f8g3_19 := int64(f8) * int64(g3_19) + f8g4_19 := int64(f8) * int64(g4_19) + f8g5_19 := int64(f8) * int64(g5_19) + f8g6_19 := int64(f8) * int64(g6_19) + f8g7_19 := int64(f8) * int64(g7_19) + f8g8_19 := int64(f8) * int64(g8_19) + f8g9_19 := int64(f8) * int64(g9_19) + f9g0 := int64(f9) * int64(g0) + f9g1_38 := int64(f9_2) * int64(g1_19) + f9g2_19 := int64(f9) * int64(g2_19) + f9g3_38 := int64(f9_2) * int64(g3_19) + f9g4_19 := int64(f9) * int64(g4_19) + f9g5_38 := int64(f9_2) * int64(g5_19) + f9g6_19 := int64(f9) * int64(g6_19) + f9g7_38 := int64(f9_2) * int64(g7_19) + f9g8_19 := int64(f9) * int64(g8_19) + f9g9_38 := int64(f9_2) * int64(g9_19) + h0 := f0g0 + f1g9_38 + f2g8_19 + f3g7_38 + f4g6_19 + f5g5_38 + f6g4_19 + f7g3_38 + f8g2_19 + f9g1_38 + h1 := f0g1 + f1g0 + f2g9_19 + f3g8_19 + f4g7_19 + f5g6_19 + f6g5_19 + f7g4_19 + f8g3_19 + f9g2_19 + h2 := f0g2 + f1g1_2 + f2g0 + f3g9_38 + f4g8_19 + f5g7_38 + f6g6_19 + f7g5_38 + f8g4_19 + f9g3_38 + h3 := f0g3 + f1g2 + f2g1 + f3g0 + f4g9_19 + f5g8_19 + f6g7_19 + f7g6_19 + f8g5_19 + f9g4_19 + h4 := f0g4 + f1g3_2 + f2g2 + f3g1_2 + f4g0 + f5g9_38 + f6g8_19 + f7g7_38 + f8g6_19 + f9g5_38 + h5 := f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + f6g9_19 + f7g8_19 + f8g7_19 + f9g6_19 + h6 := f0g6 + f1g5_2 + f2g4 + f3g3_2 + f4g2 + f5g1_2 + f6g0 + f7g9_38 + f8g8_19 + f9g7_38 + h7 := f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 + f8g9_19 + f9g8_19 + h8 := f0g8 + f1g7_2 + f2g6 + f3g5_2 + f4g4 + f5g3_2 + f6g2 + f7g1_2 + f8g0 + f9g9_38 + h9 := f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0 + var carry [10]int64 + + // |h0| <= (1.1*1.1*2^52*(1+19+19+19+19)+1.1*1.1*2^50*(38+38+38+38+38)) + // i.e. |h0| <= 1.2*2^59; narrower ranges for h2, h4, h6, h8 + // |h1| <= (1.1*1.1*2^51*(1+1+19+19+19+19+19+19+19+19)) + // i.e. |h1| <= 1.5*2^58; narrower ranges for h3, h5, h7, h9 + + carry[0] = (h0 + (1 << 25)) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + carry[4] = (h4 + (1 << 25)) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + // |h0| <= 2^25 + // |h4| <= 2^25 + // |h1| <= 1.51*2^58 + // |h5| <= 1.51*2^58 + + carry[1] = (h1 + (1 << 24)) >> 25 + h2 += carry[1] + h1 -= carry[1] << 25 + carry[5] = (h5 + (1 << 24)) >> 25 + h6 += carry[5] + h5 -= carry[5] << 25 + // |h1| <= 2^24; from now on fits into int32 + // |h5| <= 2^24; from now on fits into int32 + // |h2| <= 1.21*2^59 + // |h6| <= 1.21*2^59 + + carry[2] = (h2 + (1 << 25)) >> 26 + h3 += carry[2] + h2 -= carry[2] << 26 + carry[6] = (h6 + (1 << 25)) >> 26 + h7 += carry[6] + h6 -= carry[6] << 26 + // |h2| <= 2^25; from now on fits into int32 unchanged + // |h6| <= 2^25; from now on fits into int32 unchanged + // |h3| <= 1.51*2^58 + // |h7| <= 1.51*2^58 + + carry[3] = (h3 + (1 << 24)) >> 25 + h4 += carry[3] + h3 -= carry[3] << 25 + carry[7] = (h7 + (1 << 24)) >> 25 + h8 += carry[7] + h7 -= carry[7] << 25 + // |h3| <= 2^24; from now on fits into int32 unchanged + // |h7| <= 2^24; from now on fits into int32 unchanged + // |h4| <= 1.52*2^33 + // |h8| <= 1.52*2^33 + + carry[4] = (h4 + (1 << 25)) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + carry[8] = (h8 + (1 << 25)) >> 26 + h9 += carry[8] + h8 -= carry[8] << 26 + // |h4| <= 2^25; from now on fits into int32 unchanged + // |h8| <= 2^25; from now on fits into int32 unchanged + // |h5| <= 1.01*2^24 + // |h9| <= 1.51*2^58 + + carry[9] = (h9 + (1 << 24)) >> 25 + h0 += carry[9] * 19 + h9 -= carry[9] << 25 + // |h9| <= 2^24; from now on fits into int32 unchanged + // |h0| <= 1.8*2^37 + + carry[0] = (h0 + (1 << 25)) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + // |h0| <= 2^25; from now on fits into int32 unchanged + // |h1| <= 1.01*2^24 + + h[0] = int32(h0) + h[1] = int32(h1) + h[2] = int32(h2) + h[3] = int32(h3) + h[4] = int32(h4) + h[5] = int32(h5) + h[6] = int32(h6) + h[7] = int32(h7) + h[8] = int32(h8) + h[9] = int32(h9) +} + +// feSquare calculates h = f*f. Can overlap h with f. +// +// Preconditions: +// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. +// +// Postconditions: +// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. +func feSquare(h, f *fieldElement) { + f0 := f[0] + f1 := f[1] + f2 := f[2] + f3 := f[3] + f4 := f[4] + f5 := f[5] + f6 := f[6] + f7 := f[7] + f8 := f[8] + f9 := f[9] + f0_2 := 2 * f0 + f1_2 := 2 * f1 + f2_2 := 2 * f2 + f3_2 := 2 * f3 + f4_2 := 2 * f4 + f5_2 := 2 * f5 + f6_2 := 2 * f6 + f7_2 := 2 * f7 + f5_38 := 38 * f5 // 1.31*2^30 + f6_19 := 19 * f6 // 1.31*2^30 + f7_38 := 38 * f7 // 1.31*2^30 + f8_19 := 19 * f8 // 1.31*2^30 + f9_38 := 38 * f9 // 1.31*2^30 + f0f0 := int64(f0) * int64(f0) + f0f1_2 := int64(f0_2) * int64(f1) + f0f2_2 := int64(f0_2) * int64(f2) + f0f3_2 := int64(f0_2) * int64(f3) + f0f4_2 := int64(f0_2) * int64(f4) + f0f5_2 := int64(f0_2) * int64(f5) + f0f6_2 := int64(f0_2) * int64(f6) + f0f7_2 := int64(f0_2) * int64(f7) + f0f8_2 := int64(f0_2) * int64(f8) + f0f9_2 := int64(f0_2) * int64(f9) + f1f1_2 := int64(f1_2) * int64(f1) + f1f2_2 := int64(f1_2) * int64(f2) + f1f3_4 := int64(f1_2) * int64(f3_2) + f1f4_2 := int64(f1_2) * int64(f4) + f1f5_4 := int64(f1_2) * int64(f5_2) + f1f6_2 := int64(f1_2) * int64(f6) + f1f7_4 := int64(f1_2) * int64(f7_2) + f1f8_2 := int64(f1_2) * int64(f8) + f1f9_76 := int64(f1_2) * int64(f9_38) + f2f2 := int64(f2) * int64(f2) + f2f3_2 := int64(f2_2) * int64(f3) + f2f4_2 := int64(f2_2) * int64(f4) + f2f5_2 := int64(f2_2) * int64(f5) + f2f6_2 := int64(f2_2) * int64(f6) + f2f7_2 := int64(f2_2) * int64(f7) + f2f8_38 := int64(f2_2) * int64(f8_19) + f2f9_38 := int64(f2) * int64(f9_38) + f3f3_2 := int64(f3_2) * int64(f3) + f3f4_2 := int64(f3_2) * int64(f4) + f3f5_4 := int64(f3_2) * int64(f5_2) + f3f6_2 := int64(f3_2) * int64(f6) + f3f7_76 := int64(f3_2) * int64(f7_38) + f3f8_38 := int64(f3_2) * int64(f8_19) + f3f9_76 := int64(f3_2) * int64(f9_38) + f4f4 := int64(f4) * int64(f4) + f4f5_2 := int64(f4_2) * int64(f5) + f4f6_38 := int64(f4_2) * int64(f6_19) + f4f7_38 := int64(f4) * int64(f7_38) + f4f8_38 := int64(f4_2) * int64(f8_19) + f4f9_38 := int64(f4) * int64(f9_38) + f5f5_38 := int64(f5) * int64(f5_38) + f5f6_38 := int64(f5_2) * int64(f6_19) + f5f7_76 := int64(f5_2) * int64(f7_38) + f5f8_38 := int64(f5_2) * int64(f8_19) + f5f9_76 := int64(f5_2) * int64(f9_38) + f6f6_19 := int64(f6) * int64(f6_19) + f6f7_38 := int64(f6) * int64(f7_38) + f6f8_38 := int64(f6_2) * int64(f8_19) + f6f9_38 := int64(f6) * int64(f9_38) + f7f7_38 := int64(f7) * int64(f7_38) + f7f8_38 := int64(f7_2) * int64(f8_19) + f7f9_76 := int64(f7_2) * int64(f9_38) + f8f8_19 := int64(f8) * int64(f8_19) + f8f9_38 := int64(f8) * int64(f9_38) + f9f9_38 := int64(f9) * int64(f9_38) + h0 := f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38 + h1 := f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38 + h2 := f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19 + h3 := f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38 + h4 := f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38 + h5 := f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38 + h6 := f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19 + h7 := f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38 + h8 := f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38 + h9 := f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2 + var carry [10]int64 + + carry[0] = (h0 + (1 << 25)) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + carry[4] = (h4 + (1 << 25)) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + + carry[1] = (h1 + (1 << 24)) >> 25 + h2 += carry[1] + h1 -= carry[1] << 25 + carry[5] = (h5 + (1 << 24)) >> 25 + h6 += carry[5] + h5 -= carry[5] << 25 + + carry[2] = (h2 + (1 << 25)) >> 26 + h3 += carry[2] + h2 -= carry[2] << 26 + carry[6] = (h6 + (1 << 25)) >> 26 + h7 += carry[6] + h6 -= carry[6] << 26 + + carry[3] = (h3 + (1 << 24)) >> 25 + h4 += carry[3] + h3 -= carry[3] << 25 + carry[7] = (h7 + (1 << 24)) >> 25 + h8 += carry[7] + h7 -= carry[7] << 25 + + carry[4] = (h4 + (1 << 25)) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + carry[8] = (h8 + (1 << 25)) >> 26 + h9 += carry[8] + h8 -= carry[8] << 26 + + carry[9] = (h9 + (1 << 24)) >> 25 + h0 += carry[9] * 19 + h9 -= carry[9] << 25 + + carry[0] = (h0 + (1 << 25)) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + + h[0] = int32(h0) + h[1] = int32(h1) + h[2] = int32(h2) + h[3] = int32(h3) + h[4] = int32(h4) + h[5] = int32(h5) + h[6] = int32(h6) + h[7] = int32(h7) + h[8] = int32(h8) + h[9] = int32(h9) +} + +// feMul121666 calculates h = f * 121666. Can overlap h with f. +// +// Preconditions: +// |f| bounded by 1.1*2^26,1.1*2^25,1.1*2^26,1.1*2^25,etc. +// +// Postconditions: +// |h| bounded by 1.1*2^25,1.1*2^24,1.1*2^25,1.1*2^24,etc. +func feMul121666(h, f *fieldElement) { + h0 := int64(f[0]) * 121666 + h1 := int64(f[1]) * 121666 + h2 := int64(f[2]) * 121666 + h3 := int64(f[3]) * 121666 + h4 := int64(f[4]) * 121666 + h5 := int64(f[5]) * 121666 + h6 := int64(f[6]) * 121666 + h7 := int64(f[7]) * 121666 + h8 := int64(f[8]) * 121666 + h9 := int64(f[9]) * 121666 + var carry [10]int64 + + carry[9] = (h9 + (1 << 24)) >> 25 + h0 += carry[9] * 19 + h9 -= carry[9] << 25 + carry[1] = (h1 + (1 << 24)) >> 25 + h2 += carry[1] + h1 -= carry[1] << 25 + carry[3] = (h3 + (1 << 24)) >> 25 + h4 += carry[3] + h3 -= carry[3] << 25 + carry[5] = (h5 + (1 << 24)) >> 25 + h6 += carry[5] + h5 -= carry[5] << 25 + carry[7] = (h7 + (1 << 24)) >> 25 + h8 += carry[7] + h7 -= carry[7] << 25 + + carry[0] = (h0 + (1 << 25)) >> 26 + h1 += carry[0] + h0 -= carry[0] << 26 + carry[2] = (h2 + (1 << 25)) >> 26 + h3 += carry[2] + h2 -= carry[2] << 26 + carry[4] = (h4 + (1 << 25)) >> 26 + h5 += carry[4] + h4 -= carry[4] << 26 + carry[6] = (h6 + (1 << 25)) >> 26 + h7 += carry[6] + h6 -= carry[6] << 26 + carry[8] = (h8 + (1 << 25)) >> 26 + h9 += carry[8] + h8 -= carry[8] << 26 + + h[0] = int32(h0) + h[1] = int32(h1) + h[2] = int32(h2) + h[3] = int32(h3) + h[4] = int32(h4) + h[5] = int32(h5) + h[6] = int32(h6) + h[7] = int32(h7) + h[8] = int32(h8) + h[9] = int32(h9) +} + +// feInvert sets out = z^-1. +func feInvert(out, z *fieldElement) { + var t0, t1, t2, t3 fieldElement + var i int + + feSquare(&t0, z) + for i = 1; i < 1; i++ { + feSquare(&t0, &t0) + } + feSquare(&t1, &t0) + for i = 1; i < 2; i++ { + feSquare(&t1, &t1) + } + feMul(&t1, z, &t1) + feMul(&t0, &t0, &t1) + feSquare(&t2, &t0) + for i = 1; i < 1; i++ { + feSquare(&t2, &t2) + } + feMul(&t1, &t1, &t2) + feSquare(&t2, &t1) + for i = 1; i < 5; i++ { + feSquare(&t2, &t2) + } + feMul(&t1, &t2, &t1) + feSquare(&t2, &t1) + for i = 1; i < 10; i++ { + feSquare(&t2, &t2) + } + feMul(&t2, &t2, &t1) + feSquare(&t3, &t2) + for i = 1; i < 20; i++ { + feSquare(&t3, &t3) + } + feMul(&t2, &t3, &t2) + feSquare(&t2, &t2) + for i = 1; i < 10; i++ { + feSquare(&t2, &t2) + } + feMul(&t1, &t2, &t1) + feSquare(&t2, &t1) + for i = 1; i < 50; i++ { + feSquare(&t2, &t2) + } + feMul(&t2, &t2, &t1) + feSquare(&t3, &t2) + for i = 1; i < 100; i++ { + feSquare(&t3, &t3) + } + feMul(&t2, &t3, &t2) + feSquare(&t2, &t2) + for i = 1; i < 50; i++ { + feSquare(&t2, &t2) + } + feMul(&t1, &t2, &t1) + feSquare(&t1, &t1) + for i = 1; i < 5; i++ { + feSquare(&t1, &t1) + } + feMul(out, &t1, &t0) +} + +func scalarMultGeneric(out, in, base *[32]byte) { + var e [32]byte + + copy(e[:], in[:]) + e[0] &= 248 + e[31] &= 127 + e[31] |= 64 + + var x1, x2, z2, x3, z3, tmp0, tmp1 fieldElement + feFromBytes(&x1, base) + feOne(&x2) + feCopy(&x3, &x1) + feOne(&z3) + + swap := int32(0) + for pos := 254; pos >= 0; pos-- { + b := e[pos/8] >> uint(pos&7) + b &= 1 + swap ^= int32(b) + feCSwap(&x2, &x3, swap) + feCSwap(&z2, &z3, swap) + swap = int32(b) + + feSub(&tmp0, &x3, &z3) + feSub(&tmp1, &x2, &z2) + feAdd(&x2, &x2, &z2) + feAdd(&z2, &x3, &z3) + feMul(&z3, &tmp0, &x2) + feMul(&z2, &z2, &tmp1) + feSquare(&tmp0, &tmp1) + feSquare(&tmp1, &x2) + feAdd(&x3, &z3, &z2) + feSub(&z2, &z3, &z2) + feMul(&x2, &tmp1, &tmp0) + feSub(&tmp1, &tmp1, &tmp0) + feSquare(&z2, &z2) + feMul121666(&z3, &tmp1) + feSquare(&x3, &x3) + feAdd(&tmp0, &tmp0, &z3) + feMul(&z3, &x1, &z2) + feMul(&z2, &tmp1, &tmp0) + } + + feCSwap(&x2, &x3, swap) + feCSwap(&z2, &z3, swap) + + feInvert(&z2, &z2) + feMul(&x2, &x2, &z2) + feToBytes(out, &x2) +} diff --git a/vendor/golang.org/x/crypto/curve25519/curve25519_noasm.go b/vendor/golang.org/x/crypto/curve25519/curve25519_noasm.go new file mode 100644 index 00000000000..047d49afc27 --- /dev/null +++ b/vendor/golang.org/x/crypto/curve25519/curve25519_noasm.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !amd64 gccgo appengine purego + +package curve25519 + +func scalarMult(out, in, base *[32]byte) { + scalarMultGeneric(out, in, base) +} diff --git a/vendor/golang.org/x/crypto/curve25519/doc.go b/vendor/golang.org/x/crypto/curve25519/doc.go deleted file mode 100644 index da9b10d9c1f..00000000000 --- a/vendor/golang.org/x/crypto/curve25519/doc.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package curve25519 provides an implementation of scalar multiplication on -// the elliptic curve known as curve25519. See https://cr.yp.to/ecdh.html -package curve25519 // import "golang.org/x/crypto/curve25519" - -// basePoint is the x coordinate of the generator of the curve. -var basePoint = [32]byte{9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} - -// ScalarMult sets dst to the product in*base where dst and base are the x -// coordinates of group points and all values are in little-endian form. -func ScalarMult(dst, in, base *[32]byte) { - scalarMult(dst, in, base) -} - -// ScalarBaseMult sets dst to the product in*base where dst and base are the x -// coordinates of group points, base is the standard generator and all values -// are in little-endian form. -func ScalarBaseMult(dst, in *[32]byte) { - ScalarMult(dst, in, &basePoint) -} diff --git a/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s b/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s deleted file mode 100644 index 390816106ee..00000000000 --- a/vendor/golang.org/x/crypto/curve25519/freeze_amd64.s +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func freeze(inout *[5]uint64) -TEXT ·freeze(SB),7,$0-8 - MOVQ inout+0(FP), DI - - MOVQ 0(DI),SI - MOVQ 8(DI),DX - MOVQ 16(DI),CX - MOVQ 24(DI),R8 - MOVQ 32(DI),R9 - MOVQ $REDMASK51,AX - MOVQ AX,R10 - SUBQ $18,R10 - MOVQ $3,R11 -REDUCELOOP: - MOVQ SI,R12 - SHRQ $51,R12 - ANDQ AX,SI - ADDQ R12,DX - MOVQ DX,R12 - SHRQ $51,R12 - ANDQ AX,DX - ADDQ R12,CX - MOVQ CX,R12 - SHRQ $51,R12 - ANDQ AX,CX - ADDQ R12,R8 - MOVQ R8,R12 - SHRQ $51,R12 - ANDQ AX,R8 - ADDQ R12,R9 - MOVQ R9,R12 - SHRQ $51,R12 - ANDQ AX,R9 - IMUL3Q $19,R12,R12 - ADDQ R12,SI - SUBQ $1,R11 - JA REDUCELOOP - MOVQ $1,R12 - CMPQ R10,SI - CMOVQLT R11,R12 - CMPQ AX,DX - CMOVQNE R11,R12 - CMPQ AX,CX - CMOVQNE R11,R12 - CMPQ AX,R8 - CMOVQNE R11,R12 - CMPQ AX,R9 - CMOVQNE R11,R12 - NEGQ R12 - ANDQ R12,AX - ANDQ R12,R10 - SUBQ R10,SI - SUBQ AX,DX - SUBQ AX,CX - SUBQ AX,R8 - SUBQ AX,R9 - MOVQ SI,0(DI) - MOVQ DX,8(DI) - MOVQ CX,16(DI) - MOVQ R8,24(DI) - MOVQ R9,32(DI) - RET diff --git a/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s b/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s deleted file mode 100644 index e0ac30c70f1..00000000000 --- a/vendor/golang.org/x/crypto/curve25519/ladderstep_amd64.s +++ /dev/null @@ -1,1377 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func ladderstep(inout *[5][5]uint64) -TEXT ·ladderstep(SB),0,$296-8 - MOVQ inout+0(FP),DI - - MOVQ 40(DI),SI - MOVQ 48(DI),DX - MOVQ 56(DI),CX - MOVQ 64(DI),R8 - MOVQ 72(DI),R9 - MOVQ SI,AX - MOVQ DX,R10 - MOVQ CX,R11 - MOVQ R8,R12 - MOVQ R9,R13 - ADDQ ·_2P0(SB),AX - ADDQ ·_2P1234(SB),R10 - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 80(DI),SI - ADDQ 88(DI),DX - ADDQ 96(DI),CX - ADDQ 104(DI),R8 - ADDQ 112(DI),R9 - SUBQ 80(DI),AX - SUBQ 88(DI),R10 - SUBQ 96(DI),R11 - SUBQ 104(DI),R12 - SUBQ 112(DI),R13 - MOVQ SI,0(SP) - MOVQ DX,8(SP) - MOVQ CX,16(SP) - MOVQ R8,24(SP) - MOVQ R9,32(SP) - MOVQ AX,40(SP) - MOVQ R10,48(SP) - MOVQ R11,56(SP) - MOVQ R12,64(SP) - MOVQ R13,72(SP) - MOVQ 40(SP),AX - MULQ 40(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 48(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 56(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 64(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 40(SP),AX - SHLQ $1,AX - MULQ 72(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 48(SP),AX - MULQ 48(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 48(SP),AX - SHLQ $1,AX - MULQ 56(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 48(SP),AX - SHLQ $1,AX - MULQ 64(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 48(SP),DX - IMUL3Q $38,DX,AX - MULQ 72(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 56(SP),AX - MULQ 56(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 56(SP),DX - IMUL3Q $38,DX,AX - MULQ 64(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 56(SP),DX - IMUL3Q $38,DX,AX - MULQ 72(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 64(SP),DX - IMUL3Q $19,DX,AX - MULQ 64(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 64(SP),DX - IMUL3Q $38,DX,AX - MULQ 72(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 72(SP),DX - IMUL3Q $19,DX,AX - MULQ 72(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,SI,CX - ANDQ DX,SI - SHLQ $13,R8,R9 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R10,R11 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R12,R13 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R14,R15 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,80(SP) - MOVQ R8,88(SP) - MOVQ R9,96(SP) - MOVQ AX,104(SP) - MOVQ R10,112(SP) - MOVQ 0(SP),AX - MULQ 0(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 8(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 16(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 24(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 0(SP),AX - SHLQ $1,AX - MULQ 32(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 8(SP),AX - MULQ 8(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - SHLQ $1,AX - MULQ 16(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 8(SP),AX - SHLQ $1,AX - MULQ 24(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),DX - IMUL3Q $38,DX,AX - MULQ 32(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 16(SP),AX - MULQ 16(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 16(SP),DX - IMUL3Q $38,DX,AX - MULQ 24(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 16(SP),DX - IMUL3Q $38,DX,AX - MULQ 32(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 24(SP),DX - IMUL3Q $19,DX,AX - MULQ 24(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 24(SP),DX - IMUL3Q $38,DX,AX - MULQ 32(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 32(SP),DX - IMUL3Q $19,DX,AX - MULQ 32(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,SI,CX - ANDQ DX,SI - SHLQ $13,R8,R9 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R10,R11 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R12,R13 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R14,R15 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,120(SP) - MOVQ R8,128(SP) - MOVQ R9,136(SP) - MOVQ AX,144(SP) - MOVQ R10,152(SP) - MOVQ SI,SI - MOVQ R8,DX - MOVQ R9,CX - MOVQ AX,R8 - MOVQ R10,R9 - ADDQ ·_2P0(SB),SI - ADDQ ·_2P1234(SB),DX - ADDQ ·_2P1234(SB),CX - ADDQ ·_2P1234(SB),R8 - ADDQ ·_2P1234(SB),R9 - SUBQ 80(SP),SI - SUBQ 88(SP),DX - SUBQ 96(SP),CX - SUBQ 104(SP),R8 - SUBQ 112(SP),R9 - MOVQ SI,160(SP) - MOVQ DX,168(SP) - MOVQ CX,176(SP) - MOVQ R8,184(SP) - MOVQ R9,192(SP) - MOVQ 120(DI),SI - MOVQ 128(DI),DX - MOVQ 136(DI),CX - MOVQ 144(DI),R8 - MOVQ 152(DI),R9 - MOVQ SI,AX - MOVQ DX,R10 - MOVQ CX,R11 - MOVQ R8,R12 - MOVQ R9,R13 - ADDQ ·_2P0(SB),AX - ADDQ ·_2P1234(SB),R10 - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 160(DI),SI - ADDQ 168(DI),DX - ADDQ 176(DI),CX - ADDQ 184(DI),R8 - ADDQ 192(DI),R9 - SUBQ 160(DI),AX - SUBQ 168(DI),R10 - SUBQ 176(DI),R11 - SUBQ 184(DI),R12 - SUBQ 192(DI),R13 - MOVQ SI,200(SP) - MOVQ DX,208(SP) - MOVQ CX,216(SP) - MOVQ R8,224(SP) - MOVQ R9,232(SP) - MOVQ AX,240(SP) - MOVQ R10,248(SP) - MOVQ R11,256(SP) - MOVQ R12,264(SP) - MOVQ R13,272(SP) - MOVQ 224(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,280(SP) - MULQ 56(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 232(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,288(SP) - MULQ 48(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 200(SP),AX - MULQ 40(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 200(SP),AX - MULQ 48(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 200(SP),AX - MULQ 56(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 200(SP),AX - MULQ 64(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 200(SP),AX - MULQ 72(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 208(SP),AX - MULQ 40(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 208(SP),AX - MULQ 48(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 208(SP),AX - MULQ 56(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 208(SP),AX - MULQ 64(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 208(SP),DX - IMUL3Q $19,DX,AX - MULQ 72(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 216(SP),AX - MULQ 40(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 216(SP),AX - MULQ 48(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 216(SP),AX - MULQ 56(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 216(SP),DX - IMUL3Q $19,DX,AX - MULQ 64(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 216(SP),DX - IMUL3Q $19,DX,AX - MULQ 72(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 224(SP),AX - MULQ 40(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 224(SP),AX - MULQ 48(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 280(SP),AX - MULQ 64(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 280(SP),AX - MULQ 72(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 232(SP),AX - MULQ 40(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 288(SP),AX - MULQ 56(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 288(SP),AX - MULQ 64(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 288(SP),AX - MULQ 72(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,SI,CX - ANDQ DX,SI - SHLQ $13,R8,R9 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R10,R11 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R12,R13 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R14,R15 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,40(SP) - MOVQ R8,48(SP) - MOVQ R9,56(SP) - MOVQ AX,64(SP) - MOVQ R10,72(SP) - MOVQ 264(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,200(SP) - MULQ 16(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 272(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,208(SP) - MULQ 8(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 240(SP),AX - MULQ 0(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 240(SP),AX - MULQ 8(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 240(SP),AX - MULQ 16(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 240(SP),AX - MULQ 24(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 240(SP),AX - MULQ 32(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 248(SP),AX - MULQ 0(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 248(SP),AX - MULQ 8(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 248(SP),AX - MULQ 16(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 248(SP),AX - MULQ 24(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 248(SP),DX - IMUL3Q $19,DX,AX - MULQ 32(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 256(SP),AX - MULQ 0(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 256(SP),AX - MULQ 8(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 256(SP),AX - MULQ 16(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 256(SP),DX - IMUL3Q $19,DX,AX - MULQ 24(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 256(SP),DX - IMUL3Q $19,DX,AX - MULQ 32(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 264(SP),AX - MULQ 0(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 264(SP),AX - MULQ 8(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 200(SP),AX - MULQ 24(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 200(SP),AX - MULQ 32(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 272(SP),AX - MULQ 0(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 208(SP),AX - MULQ 16(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 208(SP),AX - MULQ 24(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 208(SP),AX - MULQ 32(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,SI,CX - ANDQ DX,SI - SHLQ $13,R8,R9 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R10,R11 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R12,R13 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R14,R15 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,DX - MOVQ R8,CX - MOVQ R9,R11 - MOVQ AX,R12 - MOVQ R10,R13 - ADDQ ·_2P0(SB),DX - ADDQ ·_2P1234(SB),CX - ADDQ ·_2P1234(SB),R11 - ADDQ ·_2P1234(SB),R12 - ADDQ ·_2P1234(SB),R13 - ADDQ 40(SP),SI - ADDQ 48(SP),R8 - ADDQ 56(SP),R9 - ADDQ 64(SP),AX - ADDQ 72(SP),R10 - SUBQ 40(SP),DX - SUBQ 48(SP),CX - SUBQ 56(SP),R11 - SUBQ 64(SP),R12 - SUBQ 72(SP),R13 - MOVQ SI,120(DI) - MOVQ R8,128(DI) - MOVQ R9,136(DI) - MOVQ AX,144(DI) - MOVQ R10,152(DI) - MOVQ DX,160(DI) - MOVQ CX,168(DI) - MOVQ R11,176(DI) - MOVQ R12,184(DI) - MOVQ R13,192(DI) - MOVQ 120(DI),AX - MULQ 120(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 128(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 136(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 144(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 120(DI),AX - SHLQ $1,AX - MULQ 152(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 128(DI),AX - MULQ 128(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 128(DI),AX - SHLQ $1,AX - MULQ 136(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 128(DI),AX - SHLQ $1,AX - MULQ 144(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 128(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(DI),AX - MULQ 136(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 136(DI),DX - IMUL3Q $38,DX,AX - MULQ 144(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 144(DI),DX - IMUL3Q $19,DX,AX - MULQ 144(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 144(DI),DX - IMUL3Q $38,DX,AX - MULQ 152(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 152(DI),DX - IMUL3Q $19,DX,AX - MULQ 152(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,SI,CX - ANDQ DX,SI - SHLQ $13,R8,R9 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R10,R11 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R12,R13 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R14,R15 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,120(DI) - MOVQ R8,128(DI) - MOVQ R9,136(DI) - MOVQ AX,144(DI) - MOVQ R10,152(DI) - MOVQ 160(DI),AX - MULQ 160(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 168(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 176(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 184(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 160(DI),AX - SHLQ $1,AX - MULQ 192(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 168(DI),AX - MULQ 168(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 168(DI),AX - SHLQ $1,AX - MULQ 176(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 168(DI),AX - SHLQ $1,AX - MULQ 184(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 168(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),AX - MULQ 176(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 176(DI),DX - IMUL3Q $38,DX,AX - MULQ 184(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),DX - IMUL3Q $19,DX,AX - MULQ 184(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),DX - IMUL3Q $38,DX,AX - MULQ 192(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 192(DI),DX - IMUL3Q $19,DX,AX - MULQ 192(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,SI,CX - ANDQ DX,SI - SHLQ $13,R8,R9 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R10,R11 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R12,R13 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R14,R15 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - ANDQ DX,SI - MOVQ CX,R8 - SHRQ $51,CX - ADDQ R10,CX - ANDQ DX,R8 - MOVQ CX,R9 - SHRQ $51,CX - ADDQ R12,CX - ANDQ DX,R9 - MOVQ CX,AX - SHRQ $51,CX - ADDQ R14,CX - ANDQ DX,AX - MOVQ CX,R10 - SHRQ $51,CX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,160(DI) - MOVQ R8,168(DI) - MOVQ R9,176(DI) - MOVQ AX,184(DI) - MOVQ R10,192(DI) - MOVQ 184(DI),SI - IMUL3Q $19,SI,AX - MOVQ AX,0(SP) - MULQ 16(DI) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 192(DI),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 8(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 160(DI),AX - MULQ 0(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 160(DI),AX - MULQ 8(DI) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 160(DI),AX - MULQ 16(DI) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 160(DI),AX - MULQ 24(DI) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 160(DI),AX - MULQ 32(DI) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 168(DI),AX - MULQ 0(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 168(DI),AX - MULQ 8(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 168(DI),AX - MULQ 16(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 168(DI),AX - MULQ 24(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 168(DI),DX - IMUL3Q $19,DX,AX - MULQ 32(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),AX - MULQ 0(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 176(DI),AX - MULQ 8(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 176(DI),AX - MULQ 16(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 176(DI),DX - IMUL3Q $19,DX,AX - MULQ 24(DI) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 176(DI),DX - IMUL3Q $19,DX,AX - MULQ 32(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 184(DI),AX - MULQ 0(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 184(DI),AX - MULQ 8(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 0(SP),AX - MULQ 24(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SP),AX - MULQ 32(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 192(DI),AX - MULQ 0(DI) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),AX - MULQ 16(DI) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 8(SP),AX - MULQ 24(DI) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 32(DI) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,SI,CX - ANDQ DX,SI - SHLQ $13,R8,R9 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R10,R11 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R12,R13 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R14,R15 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,160(DI) - MOVQ R8,168(DI) - MOVQ R9,176(DI) - MOVQ AX,184(DI) - MOVQ R10,192(DI) - MOVQ 144(SP),SI - IMUL3Q $19,SI,AX - MOVQ AX,0(SP) - MULQ 96(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 152(SP),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 88(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 120(SP),AX - MULQ 80(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 120(SP),AX - MULQ 88(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 120(SP),AX - MULQ 96(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 120(SP),AX - MULQ 104(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 120(SP),AX - MULQ 112(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 128(SP),AX - MULQ 80(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 128(SP),AX - MULQ 88(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 128(SP),AX - MULQ 96(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 128(SP),AX - MULQ 104(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 128(SP),DX - IMUL3Q $19,DX,AX - MULQ 112(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(SP),AX - MULQ 80(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 136(SP),AX - MULQ 88(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 136(SP),AX - MULQ 96(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 136(SP),DX - IMUL3Q $19,DX,AX - MULQ 104(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 136(SP),DX - IMUL3Q $19,DX,AX - MULQ 112(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 144(SP),AX - MULQ 80(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 144(SP),AX - MULQ 88(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 0(SP),AX - MULQ 104(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SP),AX - MULQ 112(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 152(SP),AX - MULQ 80(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),AX - MULQ 96(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 8(SP),AX - MULQ 104(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 112(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,SI,CX - ANDQ DX,SI - SHLQ $13,R8,R9 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R10,R11 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R12,R13 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R14,R15 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,40(DI) - MOVQ R8,48(DI) - MOVQ R9,56(DI) - MOVQ AX,64(DI) - MOVQ R10,72(DI) - MOVQ 160(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - MOVQ AX,SI - MOVQ DX,CX - MOVQ 168(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,CX - MOVQ DX,R8 - MOVQ 176(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R8 - MOVQ DX,R9 - MOVQ 184(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R9 - MOVQ DX,R10 - MOVQ 192(SP),AX - MULQ ·_121666_213(SB) - SHRQ $13,AX - ADDQ AX,R10 - IMUL3Q $19,DX,DX - ADDQ DX,SI - ADDQ 80(SP),SI - ADDQ 88(SP),CX - ADDQ 96(SP),R8 - ADDQ 104(SP),R9 - ADDQ 112(SP),R10 - MOVQ SI,80(DI) - MOVQ CX,88(DI) - MOVQ R8,96(DI) - MOVQ R9,104(DI) - MOVQ R10,112(DI) - MOVQ 104(DI),SI - IMUL3Q $19,SI,AX - MOVQ AX,0(SP) - MULQ 176(SP) - MOVQ AX,SI - MOVQ DX,CX - MOVQ 112(DI),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 168(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 80(DI),AX - MULQ 160(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 80(DI),AX - MULQ 168(SP) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 80(DI),AX - MULQ 176(SP) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 80(DI),AX - MULQ 184(SP) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 80(DI),AX - MULQ 192(SP) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 88(DI),AX - MULQ 160(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 88(DI),AX - MULQ 168(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 88(DI),AX - MULQ 176(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 88(DI),AX - MULQ 184(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 88(DI),DX - IMUL3Q $19,DX,AX - MULQ 192(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 96(DI),AX - MULQ 160(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 96(DI),AX - MULQ 168(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 96(DI),AX - MULQ 176(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 96(DI),DX - IMUL3Q $19,DX,AX - MULQ 184(SP) - ADDQ AX,SI - ADCQ DX,CX - MOVQ 96(DI),DX - IMUL3Q $19,DX,AX - MULQ 192(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 104(DI),AX - MULQ 160(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 104(DI),AX - MULQ 168(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 0(SP),AX - MULQ 184(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SP),AX - MULQ 192(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 112(DI),AX - MULQ 160(SP) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SP),AX - MULQ 176(SP) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 8(SP),AX - MULQ 184(SP) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 192(SP) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ $REDMASK51,DX - SHLQ $13,SI,CX - ANDQ DX,SI - SHLQ $13,R8,R9 - ANDQ DX,R8 - ADDQ CX,R8 - SHLQ $13,R10,R11 - ANDQ DX,R10 - ADDQ R9,R10 - SHLQ $13,R12,R13 - ANDQ DX,R12 - ADDQ R11,R12 - SHLQ $13,R14,R15 - ANDQ DX,R14 - ADDQ R13,R14 - IMUL3Q $19,R15,CX - ADDQ CX,SI - MOVQ SI,CX - SHRQ $51,CX - ADDQ R8,CX - MOVQ CX,R8 - SHRQ $51,CX - ANDQ DX,SI - ADDQ R10,CX - MOVQ CX,R9 - SHRQ $51,CX - ANDQ DX,R8 - ADDQ R12,CX - MOVQ CX,AX - SHRQ $51,CX - ANDQ DX,R9 - ADDQ R14,CX - MOVQ CX,R10 - SHRQ $51,CX - ANDQ DX,AX - IMUL3Q $19,CX,CX - ADDQ CX,SI - ANDQ DX,R10 - MOVQ SI,80(DI) - MOVQ R8,88(DI) - MOVQ R9,96(DI) - MOVQ AX,104(DI) - MOVQ R10,112(DI) - RET diff --git a/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go b/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go deleted file mode 100644 index 5822bd53383..00000000000 --- a/vendor/golang.org/x/crypto/curve25519/mont25519_amd64.go +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64,!gccgo,!appengine - -package curve25519 - -// These functions are implemented in the .s files. The names of the functions -// in the rest of the file are also taken from the SUPERCOP sources to help -// people following along. - -//go:noescape - -func cswap(inout *[5]uint64, v uint64) - -//go:noescape - -func ladderstep(inout *[5][5]uint64) - -//go:noescape - -func freeze(inout *[5]uint64) - -//go:noescape - -func mul(dest, a, b *[5]uint64) - -//go:noescape - -func square(out, in *[5]uint64) - -// mladder uses a Montgomery ladder to calculate (xr/zr) *= s. -func mladder(xr, zr *[5]uint64, s *[32]byte) { - var work [5][5]uint64 - - work[0] = *xr - setint(&work[1], 1) - setint(&work[2], 0) - work[3] = *xr - setint(&work[4], 1) - - j := uint(6) - var prevbit byte - - for i := 31; i >= 0; i-- { - for j < 8 { - bit := ((*s)[i] >> j) & 1 - swap := bit ^ prevbit - prevbit = bit - cswap(&work[1], uint64(swap)) - ladderstep(&work) - j-- - } - j = 7 - } - - *xr = work[1] - *zr = work[2] -} - -func scalarMult(out, in, base *[32]byte) { - var e [32]byte - copy(e[:], (*in)[:]) - e[0] &= 248 - e[31] &= 127 - e[31] |= 64 - - var t, z [5]uint64 - unpack(&t, base) - mladder(&t, &z, &e) - invert(&z, &z) - mul(&t, &t, &z) - pack(out, &t) -} - -func setint(r *[5]uint64, v uint64) { - r[0] = v - r[1] = 0 - r[2] = 0 - r[3] = 0 - r[4] = 0 -} - -// unpack sets r = x where r consists of 5, 51-bit limbs in little-endian -// order. -func unpack(r *[5]uint64, x *[32]byte) { - r[0] = uint64(x[0]) | - uint64(x[1])<<8 | - uint64(x[2])<<16 | - uint64(x[3])<<24 | - uint64(x[4])<<32 | - uint64(x[5])<<40 | - uint64(x[6]&7)<<48 - - r[1] = uint64(x[6])>>3 | - uint64(x[7])<<5 | - uint64(x[8])<<13 | - uint64(x[9])<<21 | - uint64(x[10])<<29 | - uint64(x[11])<<37 | - uint64(x[12]&63)<<45 - - r[2] = uint64(x[12])>>6 | - uint64(x[13])<<2 | - uint64(x[14])<<10 | - uint64(x[15])<<18 | - uint64(x[16])<<26 | - uint64(x[17])<<34 | - uint64(x[18])<<42 | - uint64(x[19]&1)<<50 - - r[3] = uint64(x[19])>>1 | - uint64(x[20])<<7 | - uint64(x[21])<<15 | - uint64(x[22])<<23 | - uint64(x[23])<<31 | - uint64(x[24])<<39 | - uint64(x[25]&15)<<47 - - r[4] = uint64(x[25])>>4 | - uint64(x[26])<<4 | - uint64(x[27])<<12 | - uint64(x[28])<<20 | - uint64(x[29])<<28 | - uint64(x[30])<<36 | - uint64(x[31]&127)<<44 -} - -// pack sets out = x where out is the usual, little-endian form of the 5, -// 51-bit limbs in x. -func pack(out *[32]byte, x *[5]uint64) { - t := *x - freeze(&t) - - out[0] = byte(t[0]) - out[1] = byte(t[0] >> 8) - out[2] = byte(t[0] >> 16) - out[3] = byte(t[0] >> 24) - out[4] = byte(t[0] >> 32) - out[5] = byte(t[0] >> 40) - out[6] = byte(t[0] >> 48) - - out[6] ^= byte(t[1]<<3) & 0xf8 - out[7] = byte(t[1] >> 5) - out[8] = byte(t[1] >> 13) - out[9] = byte(t[1] >> 21) - out[10] = byte(t[1] >> 29) - out[11] = byte(t[1] >> 37) - out[12] = byte(t[1] >> 45) - - out[12] ^= byte(t[2]<<6) & 0xc0 - out[13] = byte(t[2] >> 2) - out[14] = byte(t[2] >> 10) - out[15] = byte(t[2] >> 18) - out[16] = byte(t[2] >> 26) - out[17] = byte(t[2] >> 34) - out[18] = byte(t[2] >> 42) - out[19] = byte(t[2] >> 50) - - out[19] ^= byte(t[3]<<1) & 0xfe - out[20] = byte(t[3] >> 7) - out[21] = byte(t[3] >> 15) - out[22] = byte(t[3] >> 23) - out[23] = byte(t[3] >> 31) - out[24] = byte(t[3] >> 39) - out[25] = byte(t[3] >> 47) - - out[25] ^= byte(t[4]<<4) & 0xf0 - out[26] = byte(t[4] >> 4) - out[27] = byte(t[4] >> 12) - out[28] = byte(t[4] >> 20) - out[29] = byte(t[4] >> 28) - out[30] = byte(t[4] >> 36) - out[31] = byte(t[4] >> 44) -} - -// invert calculates r = x^-1 mod p using Fermat's little theorem. -func invert(r *[5]uint64, x *[5]uint64) { - var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_50_0, z2_100_0, t [5]uint64 - - square(&z2, x) /* 2 */ - square(&t, &z2) /* 4 */ - square(&t, &t) /* 8 */ - mul(&z9, &t, x) /* 9 */ - mul(&z11, &z9, &z2) /* 11 */ - square(&t, &z11) /* 22 */ - mul(&z2_5_0, &t, &z9) /* 2^5 - 2^0 = 31 */ - - square(&t, &z2_5_0) /* 2^6 - 2^1 */ - for i := 1; i < 5; i++ { /* 2^20 - 2^10 */ - square(&t, &t) - } - mul(&z2_10_0, &t, &z2_5_0) /* 2^10 - 2^0 */ - - square(&t, &z2_10_0) /* 2^11 - 2^1 */ - for i := 1; i < 10; i++ { /* 2^20 - 2^10 */ - square(&t, &t) - } - mul(&z2_20_0, &t, &z2_10_0) /* 2^20 - 2^0 */ - - square(&t, &z2_20_0) /* 2^21 - 2^1 */ - for i := 1; i < 20; i++ { /* 2^40 - 2^20 */ - square(&t, &t) - } - mul(&t, &t, &z2_20_0) /* 2^40 - 2^0 */ - - square(&t, &t) /* 2^41 - 2^1 */ - for i := 1; i < 10; i++ { /* 2^50 - 2^10 */ - square(&t, &t) - } - mul(&z2_50_0, &t, &z2_10_0) /* 2^50 - 2^0 */ - - square(&t, &z2_50_0) /* 2^51 - 2^1 */ - for i := 1; i < 50; i++ { /* 2^100 - 2^50 */ - square(&t, &t) - } - mul(&z2_100_0, &t, &z2_50_0) /* 2^100 - 2^0 */ - - square(&t, &z2_100_0) /* 2^101 - 2^1 */ - for i := 1; i < 100; i++ { /* 2^200 - 2^100 */ - square(&t, &t) - } - mul(&t, &t, &z2_100_0) /* 2^200 - 2^0 */ - - square(&t, &t) /* 2^201 - 2^1 */ - for i := 1; i < 50; i++ { /* 2^250 - 2^50 */ - square(&t, &t) - } - mul(&t, &t, &z2_50_0) /* 2^250 - 2^0 */ - - square(&t, &t) /* 2^251 - 2^1 */ - square(&t, &t) /* 2^252 - 2^2 */ - square(&t, &t) /* 2^253 - 2^3 */ - - square(&t, &t) /* 2^254 - 2^4 */ - - square(&t, &t) /* 2^255 - 2^5 */ - mul(r, &t, &z11) /* 2^255 - 21 */ -} diff --git a/vendor/golang.org/x/crypto/curve25519/mul_amd64.s b/vendor/golang.org/x/crypto/curve25519/mul_amd64.s deleted file mode 100644 index 1f76d1a3f59..00000000000 --- a/vendor/golang.org/x/crypto/curve25519/mul_amd64.s +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func mul(dest, a, b *[5]uint64) -TEXT ·mul(SB),0,$16-24 - MOVQ dest+0(FP), DI - MOVQ a+8(FP), SI - MOVQ b+16(FP), DX - - MOVQ DX,CX - MOVQ 24(SI),DX - IMUL3Q $19,DX,AX - MOVQ AX,0(SP) - MULQ 16(CX) - MOVQ AX,R8 - MOVQ DX,R9 - MOVQ 32(SI),DX - IMUL3Q $19,DX,AX - MOVQ AX,8(SP) - MULQ 8(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SI),AX - MULQ 0(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 0(SI),AX - MULQ 8(CX) - MOVQ AX,R10 - MOVQ DX,R11 - MOVQ 0(SI),AX - MULQ 16(CX) - MOVQ AX,R12 - MOVQ DX,R13 - MOVQ 0(SI),AX - MULQ 24(CX) - MOVQ AX,R14 - MOVQ DX,R15 - MOVQ 0(SI),AX - MULQ 32(CX) - MOVQ AX,BX - MOVQ DX,BP - MOVQ 8(SI),AX - MULQ 0(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SI),AX - MULQ 8(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 8(SI),AX - MULQ 16(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 8(SI),AX - MULQ 24(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 8(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 16(SI),AX - MULQ 0(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 16(SI),AX - MULQ 8(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 16(SI),AX - MULQ 16(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 16(SI),DX - IMUL3Q $19,DX,AX - MULQ 24(CX) - ADDQ AX,R8 - ADCQ DX,R9 - MOVQ 16(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 24(SI),AX - MULQ 0(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ 24(SI),AX - MULQ 8(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 0(SP),AX - MULQ 24(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 0(SP),AX - MULQ 32(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 32(SI),AX - MULQ 0(CX) - ADDQ AX,BX - ADCQ DX,BP - MOVQ 8(SP),AX - MULQ 16(CX) - ADDQ AX,R10 - ADCQ DX,R11 - MOVQ 8(SP),AX - MULQ 24(CX) - ADDQ AX,R12 - ADCQ DX,R13 - MOVQ 8(SP),AX - MULQ 32(CX) - ADDQ AX,R14 - ADCQ DX,R15 - MOVQ $REDMASK51,SI - SHLQ $13,R8,R9 - ANDQ SI,R8 - SHLQ $13,R10,R11 - ANDQ SI,R10 - ADDQ R9,R10 - SHLQ $13,R12,R13 - ANDQ SI,R12 - ADDQ R11,R12 - SHLQ $13,R14,R15 - ANDQ SI,R14 - ADDQ R13,R14 - SHLQ $13,BX,BP - ANDQ SI,BX - ADDQ R15,BX - IMUL3Q $19,BP,DX - ADDQ DX,R8 - MOVQ R8,DX - SHRQ $51,DX - ADDQ R10,DX - MOVQ DX,CX - SHRQ $51,DX - ANDQ SI,R8 - ADDQ R12,DX - MOVQ DX,R9 - SHRQ $51,DX - ANDQ SI,CX - ADDQ R14,DX - MOVQ DX,AX - SHRQ $51,DX - ANDQ SI,R9 - ADDQ BX,DX - MOVQ DX,R10 - SHRQ $51,DX - ANDQ SI,AX - IMUL3Q $19,DX,DX - ADDQ DX,R8 - ANDQ SI,R10 - MOVQ R8,0(DI) - MOVQ CX,8(DI) - MOVQ R9,16(DI) - MOVQ AX,24(DI) - MOVQ R10,32(DI) - RET diff --git a/vendor/golang.org/x/crypto/curve25519/square_amd64.s b/vendor/golang.org/x/crypto/curve25519/square_amd64.s deleted file mode 100644 index 07511a45af2..00000000000 --- a/vendor/golang.org/x/crypto/curve25519/square_amd64.s +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This code was translated into a form compatible with 6a from the public -// domain sources in SUPERCOP: https://bench.cr.yp.to/supercop.html - -// +build amd64,!gccgo,!appengine - -#include "const_amd64.h" - -// func square(out, in *[5]uint64) -TEXT ·square(SB),7,$0-16 - MOVQ out+0(FP), DI - MOVQ in+8(FP), SI - - MOVQ 0(SI),AX - MULQ 0(SI) - MOVQ AX,CX - MOVQ DX,R8 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 8(SI) - MOVQ AX,R9 - MOVQ DX,R10 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 16(SI) - MOVQ AX,R11 - MOVQ DX,R12 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 24(SI) - MOVQ AX,R13 - MOVQ DX,R14 - MOVQ 0(SI),AX - SHLQ $1,AX - MULQ 32(SI) - MOVQ AX,R15 - MOVQ DX,BX - MOVQ 8(SI),AX - MULQ 8(SI) - ADDQ AX,R11 - ADCQ DX,R12 - MOVQ 8(SI),AX - SHLQ $1,AX - MULQ 16(SI) - ADDQ AX,R13 - ADCQ DX,R14 - MOVQ 8(SI),AX - SHLQ $1,AX - MULQ 24(SI) - ADDQ AX,R15 - ADCQ DX,BX - MOVQ 8(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,CX - ADCQ DX,R8 - MOVQ 16(SI),AX - MULQ 16(SI) - ADDQ AX,R15 - ADCQ DX,BX - MOVQ 16(SI),DX - IMUL3Q $38,DX,AX - MULQ 24(SI) - ADDQ AX,CX - ADCQ DX,R8 - MOVQ 16(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,R9 - ADCQ DX,R10 - MOVQ 24(SI),DX - IMUL3Q $19,DX,AX - MULQ 24(SI) - ADDQ AX,R9 - ADCQ DX,R10 - MOVQ 24(SI),DX - IMUL3Q $38,DX,AX - MULQ 32(SI) - ADDQ AX,R11 - ADCQ DX,R12 - MOVQ 32(SI),DX - IMUL3Q $19,DX,AX - MULQ 32(SI) - ADDQ AX,R13 - ADCQ DX,R14 - MOVQ $REDMASK51,SI - SHLQ $13,CX,R8 - ANDQ SI,CX - SHLQ $13,R9,R10 - ANDQ SI,R9 - ADDQ R8,R9 - SHLQ $13,R11,R12 - ANDQ SI,R11 - ADDQ R10,R11 - SHLQ $13,R13,R14 - ANDQ SI,R13 - ADDQ R12,R13 - SHLQ $13,R15,BX - ANDQ SI,R15 - ADDQ R14,R15 - IMUL3Q $19,BX,DX - ADDQ DX,CX - MOVQ CX,DX - SHRQ $51,DX - ADDQ R9,DX - ANDQ SI,CX - MOVQ DX,R8 - SHRQ $51,DX - ADDQ R11,DX - ANDQ SI,R8 - MOVQ DX,R9 - SHRQ $51,DX - ADDQ R13,DX - ANDQ SI,R9 - MOVQ DX,AX - SHRQ $51,DX - ADDQ R15,DX - ANDQ SI,AX - MOVQ DX,R10 - SHRQ $51,DX - IMUL3Q $19,DX,DX - ADDQ DX,CX - ANDQ SI,R10 - MOVQ CX,0(DI) - MOVQ R8,8(DI) - MOVQ R9,16(DI) - MOVQ AX,24(DI) - MOVQ R10,32(DI) - RET diff --git a/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s b/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s deleted file mode 100644 index b3a16ef751a..00000000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/asm_arm64.s +++ /dev/null @@ -1,308 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.11 -// +build !gccgo,!appengine - -#include "textflag.h" - -#define NUM_ROUNDS 10 - -// func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) -TEXT ·xorKeyStreamVX(SB), NOSPLIT, $0 - MOVD dst+0(FP), R1 - MOVD src+24(FP), R2 - MOVD src_len+32(FP), R3 - MOVD key+48(FP), R4 - MOVD nonce+56(FP), R6 - MOVD counter+64(FP), R7 - - MOVD $·constants(SB), R10 - MOVD $·incRotMatrix(SB), R11 - - MOVW (R7), R20 - - AND $~255, R3, R13 - ADD R2, R13, R12 // R12 for block end - AND $255, R3, R13 -loop: - MOVD $NUM_ROUNDS, R21 - VLD1 (R11), [V30.S4, V31.S4] - - // load contants - // VLD4R (R10), [V0.S4, V1.S4, V2.S4, V3.S4] - WORD $0x4D60E940 - - // load keys - // VLD4R 16(R4), [V4.S4, V5.S4, V6.S4, V7.S4] - WORD $0x4DFFE884 - // VLD4R 16(R4), [V8.S4, V9.S4, V10.S4, V11.S4] - WORD $0x4DFFE888 - SUB $32, R4 - - // load counter + nonce - // VLD1R (R7), [V12.S4] - WORD $0x4D40C8EC - - // VLD3R (R6), [V13.S4, V14.S4, V15.S4] - WORD $0x4D40E8CD - - // update counter - VADD V30.S4, V12.S4, V12.S4 - -chacha: - // V0..V3 += V4..V7 - // V12..V15 <<<= ((V12..V15 XOR V0..V3), 16) - VADD V0.S4, V4.S4, V0.S4 - VADD V1.S4, V5.S4, V1.S4 - VADD V2.S4, V6.S4, V2.S4 - VADD V3.S4, V7.S4, V3.S4 - VEOR V12.B16, V0.B16, V12.B16 - VEOR V13.B16, V1.B16, V13.B16 - VEOR V14.B16, V2.B16, V14.B16 - VEOR V15.B16, V3.B16, V15.B16 - VREV32 V12.H8, V12.H8 - VREV32 V13.H8, V13.H8 - VREV32 V14.H8, V14.H8 - VREV32 V15.H8, V15.H8 - // V8..V11 += V12..V15 - // V4..V7 <<<= ((V4..V7 XOR V8..V11), 12) - VADD V8.S4, V12.S4, V8.S4 - VADD V9.S4, V13.S4, V9.S4 - VADD V10.S4, V14.S4, V10.S4 - VADD V11.S4, V15.S4, V11.S4 - VEOR V8.B16, V4.B16, V16.B16 - VEOR V9.B16, V5.B16, V17.B16 - VEOR V10.B16, V6.B16, V18.B16 - VEOR V11.B16, V7.B16, V19.B16 - VSHL $12, V16.S4, V4.S4 - VSHL $12, V17.S4, V5.S4 - VSHL $12, V18.S4, V6.S4 - VSHL $12, V19.S4, V7.S4 - VSRI $20, V16.S4, V4.S4 - VSRI $20, V17.S4, V5.S4 - VSRI $20, V18.S4, V6.S4 - VSRI $20, V19.S4, V7.S4 - - // V0..V3 += V4..V7 - // V12..V15 <<<= ((V12..V15 XOR V0..V3), 8) - VADD V0.S4, V4.S4, V0.S4 - VADD V1.S4, V5.S4, V1.S4 - VADD V2.S4, V6.S4, V2.S4 - VADD V3.S4, V7.S4, V3.S4 - VEOR V12.B16, V0.B16, V12.B16 - VEOR V13.B16, V1.B16, V13.B16 - VEOR V14.B16, V2.B16, V14.B16 - VEOR V15.B16, V3.B16, V15.B16 - VTBL V31.B16, [V12.B16], V12.B16 - VTBL V31.B16, [V13.B16], V13.B16 - VTBL V31.B16, [V14.B16], V14.B16 - VTBL V31.B16, [V15.B16], V15.B16 - - // V8..V11 += V12..V15 - // V4..V7 <<<= ((V4..V7 XOR V8..V11), 7) - VADD V12.S4, V8.S4, V8.S4 - VADD V13.S4, V9.S4, V9.S4 - VADD V14.S4, V10.S4, V10.S4 - VADD V15.S4, V11.S4, V11.S4 - VEOR V8.B16, V4.B16, V16.B16 - VEOR V9.B16, V5.B16, V17.B16 - VEOR V10.B16, V6.B16, V18.B16 - VEOR V11.B16, V7.B16, V19.B16 - VSHL $7, V16.S4, V4.S4 - VSHL $7, V17.S4, V5.S4 - VSHL $7, V18.S4, V6.S4 - VSHL $7, V19.S4, V7.S4 - VSRI $25, V16.S4, V4.S4 - VSRI $25, V17.S4, V5.S4 - VSRI $25, V18.S4, V6.S4 - VSRI $25, V19.S4, V7.S4 - - // V0..V3 += V5..V7, V4 - // V15,V12-V14 <<<= ((V15,V12-V14 XOR V0..V3), 16) - VADD V0.S4, V5.S4, V0.S4 - VADD V1.S4, V6.S4, V1.S4 - VADD V2.S4, V7.S4, V2.S4 - VADD V3.S4, V4.S4, V3.S4 - VEOR V15.B16, V0.B16, V15.B16 - VEOR V12.B16, V1.B16, V12.B16 - VEOR V13.B16, V2.B16, V13.B16 - VEOR V14.B16, V3.B16, V14.B16 - VREV32 V12.H8, V12.H8 - VREV32 V13.H8, V13.H8 - VREV32 V14.H8, V14.H8 - VREV32 V15.H8, V15.H8 - - // V10 += V15; V5 <<<= ((V10 XOR V5), 12) - // ... - VADD V15.S4, V10.S4, V10.S4 - VADD V12.S4, V11.S4, V11.S4 - VADD V13.S4, V8.S4, V8.S4 - VADD V14.S4, V9.S4, V9.S4 - VEOR V10.B16, V5.B16, V16.B16 - VEOR V11.B16, V6.B16, V17.B16 - VEOR V8.B16, V7.B16, V18.B16 - VEOR V9.B16, V4.B16, V19.B16 - VSHL $12, V16.S4, V5.S4 - VSHL $12, V17.S4, V6.S4 - VSHL $12, V18.S4, V7.S4 - VSHL $12, V19.S4, V4.S4 - VSRI $20, V16.S4, V5.S4 - VSRI $20, V17.S4, V6.S4 - VSRI $20, V18.S4, V7.S4 - VSRI $20, V19.S4, V4.S4 - - // V0 += V5; V15 <<<= ((V0 XOR V15), 8) - // ... - VADD V5.S4, V0.S4, V0.S4 - VADD V6.S4, V1.S4, V1.S4 - VADD V7.S4, V2.S4, V2.S4 - VADD V4.S4, V3.S4, V3.S4 - VEOR V0.B16, V15.B16, V15.B16 - VEOR V1.B16, V12.B16, V12.B16 - VEOR V2.B16, V13.B16, V13.B16 - VEOR V3.B16, V14.B16, V14.B16 - VTBL V31.B16, [V12.B16], V12.B16 - VTBL V31.B16, [V13.B16], V13.B16 - VTBL V31.B16, [V14.B16], V14.B16 - VTBL V31.B16, [V15.B16], V15.B16 - - // V10 += V15; V5 <<<= ((V10 XOR V5), 7) - // ... - VADD V15.S4, V10.S4, V10.S4 - VADD V12.S4, V11.S4, V11.S4 - VADD V13.S4, V8.S4, V8.S4 - VADD V14.S4, V9.S4, V9.S4 - VEOR V10.B16, V5.B16, V16.B16 - VEOR V11.B16, V6.B16, V17.B16 - VEOR V8.B16, V7.B16, V18.B16 - VEOR V9.B16, V4.B16, V19.B16 - VSHL $7, V16.S4, V5.S4 - VSHL $7, V17.S4, V6.S4 - VSHL $7, V18.S4, V7.S4 - VSHL $7, V19.S4, V4.S4 - VSRI $25, V16.S4, V5.S4 - VSRI $25, V17.S4, V6.S4 - VSRI $25, V18.S4, V7.S4 - VSRI $25, V19.S4, V4.S4 - - SUB $1, R21 - CBNZ R21, chacha - - // VLD4R (R10), [V16.S4, V17.S4, V18.S4, V19.S4] - WORD $0x4D60E950 - - // VLD4R 16(R4), [V20.S4, V21.S4, V22.S4, V23.S4] - WORD $0x4DFFE894 - VADD V30.S4, V12.S4, V12.S4 - VADD V16.S4, V0.S4, V0.S4 - VADD V17.S4, V1.S4, V1.S4 - VADD V18.S4, V2.S4, V2.S4 - VADD V19.S4, V3.S4, V3.S4 - // VLD4R 16(R4), [V24.S4, V25.S4, V26.S4, V27.S4] - WORD $0x4DFFE898 - // restore R4 - SUB $32, R4 - - // load counter + nonce - // VLD1R (R7), [V28.S4] - WORD $0x4D40C8FC - // VLD3R (R6), [V29.S4, V30.S4, V31.S4] - WORD $0x4D40E8DD - - VADD V20.S4, V4.S4, V4.S4 - VADD V21.S4, V5.S4, V5.S4 - VADD V22.S4, V6.S4, V6.S4 - VADD V23.S4, V7.S4, V7.S4 - VADD V24.S4, V8.S4, V8.S4 - VADD V25.S4, V9.S4, V9.S4 - VADD V26.S4, V10.S4, V10.S4 - VADD V27.S4, V11.S4, V11.S4 - VADD V28.S4, V12.S4, V12.S4 - VADD V29.S4, V13.S4, V13.S4 - VADD V30.S4, V14.S4, V14.S4 - VADD V31.S4, V15.S4, V15.S4 - - VZIP1 V1.S4, V0.S4, V16.S4 - VZIP2 V1.S4, V0.S4, V17.S4 - VZIP1 V3.S4, V2.S4, V18.S4 - VZIP2 V3.S4, V2.S4, V19.S4 - VZIP1 V5.S4, V4.S4, V20.S4 - VZIP2 V5.S4, V4.S4, V21.S4 - VZIP1 V7.S4, V6.S4, V22.S4 - VZIP2 V7.S4, V6.S4, V23.S4 - VZIP1 V9.S4, V8.S4, V24.S4 - VZIP2 V9.S4, V8.S4, V25.S4 - VZIP1 V11.S4, V10.S4, V26.S4 - VZIP2 V11.S4, V10.S4, V27.S4 - VZIP1 V13.S4, V12.S4, V28.S4 - VZIP2 V13.S4, V12.S4, V29.S4 - VZIP1 V15.S4, V14.S4, V30.S4 - VZIP2 V15.S4, V14.S4, V31.S4 - VZIP1 V18.D2, V16.D2, V0.D2 - VZIP2 V18.D2, V16.D2, V4.D2 - VZIP1 V19.D2, V17.D2, V8.D2 - VZIP2 V19.D2, V17.D2, V12.D2 - VLD1.P 64(R2), [V16.B16, V17.B16, V18.B16, V19.B16] - - VZIP1 V22.D2, V20.D2, V1.D2 - VZIP2 V22.D2, V20.D2, V5.D2 - VZIP1 V23.D2, V21.D2, V9.D2 - VZIP2 V23.D2, V21.D2, V13.D2 - VLD1.P 64(R2), [V20.B16, V21.B16, V22.B16, V23.B16] - VZIP1 V26.D2, V24.D2, V2.D2 - VZIP2 V26.D2, V24.D2, V6.D2 - VZIP1 V27.D2, V25.D2, V10.D2 - VZIP2 V27.D2, V25.D2, V14.D2 - VLD1.P 64(R2), [V24.B16, V25.B16, V26.B16, V27.B16] - VZIP1 V30.D2, V28.D2, V3.D2 - VZIP2 V30.D2, V28.D2, V7.D2 - VZIP1 V31.D2, V29.D2, V11.D2 - VZIP2 V31.D2, V29.D2, V15.D2 - VLD1.P 64(R2), [V28.B16, V29.B16, V30.B16, V31.B16] - VEOR V0.B16, V16.B16, V16.B16 - VEOR V1.B16, V17.B16, V17.B16 - VEOR V2.B16, V18.B16, V18.B16 - VEOR V3.B16, V19.B16, V19.B16 - VST1.P [V16.B16, V17.B16, V18.B16, V19.B16], 64(R1) - VEOR V4.B16, V20.B16, V20.B16 - VEOR V5.B16, V21.B16, V21.B16 - VEOR V6.B16, V22.B16, V22.B16 - VEOR V7.B16, V23.B16, V23.B16 - VST1.P [V20.B16, V21.B16, V22.B16, V23.B16], 64(R1) - VEOR V8.B16, V24.B16, V24.B16 - VEOR V9.B16, V25.B16, V25.B16 - VEOR V10.B16, V26.B16, V26.B16 - VEOR V11.B16, V27.B16, V27.B16 - VST1.P [V24.B16, V25.B16, V26.B16, V27.B16], 64(R1) - VEOR V12.B16, V28.B16, V28.B16 - VEOR V13.B16, V29.B16, V29.B16 - VEOR V14.B16, V30.B16, V30.B16 - VEOR V15.B16, V31.B16, V31.B16 - VST1.P [V28.B16, V29.B16, V30.B16, V31.B16], 64(R1) - - ADD $4, R20 - MOVW R20, (R7) // update counter - - CMP R2, R12 - BGT loop - - RET - - -DATA ·constants+0x00(SB)/4, $0x61707865 -DATA ·constants+0x04(SB)/4, $0x3320646e -DATA ·constants+0x08(SB)/4, $0x79622d32 -DATA ·constants+0x0c(SB)/4, $0x6b206574 -GLOBL ·constants(SB), NOPTR|RODATA, $32 - -DATA ·incRotMatrix+0x00(SB)/4, $0x00000000 -DATA ·incRotMatrix+0x04(SB)/4, $0x00000001 -DATA ·incRotMatrix+0x08(SB)/4, $0x00000002 -DATA ·incRotMatrix+0x0c(SB)/4, $0x00000003 -DATA ·incRotMatrix+0x10(SB)/4, $0x02010003 -DATA ·incRotMatrix+0x14(SB)/4, $0x06050407 -DATA ·incRotMatrix+0x18(SB)/4, $0x0A09080B -DATA ·incRotMatrix+0x1c(SB)/4, $0x0E0D0C0F -GLOBL ·incRotMatrix(SB), NOPTR|RODATA, $32 diff --git a/vendor/golang.org/x/crypto/internal/chacha20/asm_ppc64le.s b/vendor/golang.org/x/crypto/internal/chacha20/asm_ppc64le.s deleted file mode 100644 index 54418522994..00000000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/asm_ppc64le.s +++ /dev/null @@ -1,465 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Based on CRYPTOGAMS code with the following comment: -// # ==================================================================== -// # Written by Andy Polyakov for the OpenSSL -// # project. The module is, however, dual licensed under OpenSSL and -// # CRYPTOGAMS licenses depending on where you obtain it. For further -// # details see http://www.openssl.org/~appro/cryptogams/. -// # ==================================================================== - -// Code for the perl script that generates the ppc64 assembler -// can be found in the cryptogams repository at the link below. It is based on -// the original from openssl. - -// https://github.com/dot-asm/cryptogams/commit/a60f5b50ed908e91 - -// The differences in this and the original implementation are -// due to the calling conventions and initialization of constants. - -// +build ppc64le,!gccgo,!appengine - -#include "textflag.h" - -#define OUT R3 -#define INP R4 -#define LEN R5 -#define KEY R6 -#define CNT R7 -#define TMP R15 - -#define CONSTBASE R16 - -#define X0 R11 -#define X1 R12 -#define X2 R14 -#define X3 R15 -#define X4 R16 -#define X5 R17 -#define X6 R18 -#define X7 R19 -#define X8 R20 -#define X9 R21 -#define X10 R22 -#define X11 R23 -#define X12 R24 -#define X13 R25 -#define X14 R26 -#define X15 R27 - - -DATA consts<>+0x00(SB)/8, $0x3320646e61707865 -DATA consts<>+0x08(SB)/8, $0x6b20657479622d32 -DATA consts<>+0x10(SB)/8, $0x0000000000000001 -DATA consts<>+0x18(SB)/8, $0x0000000000000000 -DATA consts<>+0x20(SB)/8, $0x0000000000000004 -DATA consts<>+0x28(SB)/8, $0x0000000000000000 -DATA consts<>+0x30(SB)/8, $0x0a0b08090e0f0c0d -DATA consts<>+0x38(SB)/8, $0x0203000106070405 -DATA consts<>+0x40(SB)/8, $0x090a0b080d0e0f0c -DATA consts<>+0x48(SB)/8, $0x0102030005060704 -DATA consts<>+0x50(SB)/8, $0x6170786561707865 -DATA consts<>+0x58(SB)/8, $0x6170786561707865 -DATA consts<>+0x60(SB)/8, $0x3320646e3320646e -DATA consts<>+0x68(SB)/8, $0x3320646e3320646e -DATA consts<>+0x70(SB)/8, $0x79622d3279622d32 -DATA consts<>+0x78(SB)/8, $0x79622d3279622d32 -DATA consts<>+0x80(SB)/8, $0x6b2065746b206574 -DATA consts<>+0x88(SB)/8, $0x6b2065746b206574 -DATA consts<>+0x90(SB)/8, $0x0000000100000000 -DATA consts<>+0x98(SB)/8, $0x0000000300000002 -GLOBL consts<>(SB), RODATA, $0xa0 - -//func chaCha20_ctr32_vsx(out, inp []byte, len int, key *[32]byte, counter *[16]byte) -TEXT ·chaCha20_ctr32_vsx(SB),NOSPLIT,$64-40 - MOVD out+0(FP), OUT - MOVD inp+8(FP), INP - MOVD len+16(FP), LEN - MOVD key+24(FP), KEY - MOVD cnt+32(FP), CNT - - // Addressing for constants - MOVD $consts<>+0x00(SB), CONSTBASE - MOVD $16, R8 - MOVD $32, R9 - MOVD $48, R10 - MOVD $64, R11 - // V16 - LXVW4X (CONSTBASE)(R0), VS48 - ADD $80,CONSTBASE - - // Load key into V17,V18 - LXVW4X (KEY)(R0), VS49 - LXVW4X (KEY)(R8), VS50 - - // Load CNT, NONCE into V19 - LXVW4X (CNT)(R0), VS51 - - // Clear V27 - VXOR V27, V27, V27 - - // V28 - LXVW4X (CONSTBASE)(R11), VS60 - - // splat slot from V19 -> V26 - VSPLTW $0, V19, V26 - - VSLDOI $4, V19, V27, V19 - VSLDOI $12, V27, V19, V19 - - VADDUWM V26, V28, V26 - - MOVD $10, R14 - MOVD R14, CTR - -loop_outer_vsx: - // V0, V1, V2, V3 - LXVW4X (R0)(CONSTBASE), VS32 - LXVW4X (R8)(CONSTBASE), VS33 - LXVW4X (R9)(CONSTBASE), VS34 - LXVW4X (R10)(CONSTBASE), VS35 - - // splat values from V17, V18 into V4-V11 - VSPLTW $0, V17, V4 - VSPLTW $1, V17, V5 - VSPLTW $2, V17, V6 - VSPLTW $3, V17, V7 - VSPLTW $0, V18, V8 - VSPLTW $1, V18, V9 - VSPLTW $2, V18, V10 - VSPLTW $3, V18, V11 - - // VOR - VOR V26, V26, V12 - - // splat values from V19 -> V13, V14, V15 - VSPLTW $1, V19, V13 - VSPLTW $2, V19, V14 - VSPLTW $3, V19, V15 - - // splat const values - VSPLTISW $-16, V27 - VSPLTISW $12, V28 - VSPLTISW $8, V29 - VSPLTISW $7, V30 - -loop_vsx: - VADDUWM V0, V4, V0 - VADDUWM V1, V5, V1 - VADDUWM V2, V6, V2 - VADDUWM V3, V7, V3 - - VXOR V12, V0, V12 - VXOR V13, V1, V13 - VXOR V14, V2, V14 - VXOR V15, V3, V15 - - VRLW V12, V27, V12 - VRLW V13, V27, V13 - VRLW V14, V27, V14 - VRLW V15, V27, V15 - - VADDUWM V8, V12, V8 - VADDUWM V9, V13, V9 - VADDUWM V10, V14, V10 - VADDUWM V11, V15, V11 - - VXOR V4, V8, V4 - VXOR V5, V9, V5 - VXOR V6, V10, V6 - VXOR V7, V11, V7 - - VRLW V4, V28, V4 - VRLW V5, V28, V5 - VRLW V6, V28, V6 - VRLW V7, V28, V7 - - VADDUWM V0, V4, V0 - VADDUWM V1, V5, V1 - VADDUWM V2, V6, V2 - VADDUWM V3, V7, V3 - - VXOR V12, V0, V12 - VXOR V13, V1, V13 - VXOR V14, V2, V14 - VXOR V15, V3, V15 - - VRLW V12, V29, V12 - VRLW V13, V29, V13 - VRLW V14, V29, V14 - VRLW V15, V29, V15 - - VADDUWM V8, V12, V8 - VADDUWM V9, V13, V9 - VADDUWM V10, V14, V10 - VADDUWM V11, V15, V11 - - VXOR V4, V8, V4 - VXOR V5, V9, V5 - VXOR V6, V10, V6 - VXOR V7, V11, V7 - - VRLW V4, V30, V4 - VRLW V5, V30, V5 - VRLW V6, V30, V6 - VRLW V7, V30, V7 - - VADDUWM V0, V5, V0 - VADDUWM V1, V6, V1 - VADDUWM V2, V7, V2 - VADDUWM V3, V4, V3 - - VXOR V15, V0, V15 - VXOR V12, V1, V12 - VXOR V13, V2, V13 - VXOR V14, V3, V14 - - VRLW V15, V27, V15 - VRLW V12, V27, V12 - VRLW V13, V27, V13 - VRLW V14, V27, V14 - - VADDUWM V10, V15, V10 - VADDUWM V11, V12, V11 - VADDUWM V8, V13, V8 - VADDUWM V9, V14, V9 - - VXOR V5, V10, V5 - VXOR V6, V11, V6 - VXOR V7, V8, V7 - VXOR V4, V9, V4 - - VRLW V5, V28, V5 - VRLW V6, V28, V6 - VRLW V7, V28, V7 - VRLW V4, V28, V4 - - VADDUWM V0, V5, V0 - VADDUWM V1, V6, V1 - VADDUWM V2, V7, V2 - VADDUWM V3, V4, V3 - - VXOR V15, V0, V15 - VXOR V12, V1, V12 - VXOR V13, V2, V13 - VXOR V14, V3, V14 - - VRLW V15, V29, V15 - VRLW V12, V29, V12 - VRLW V13, V29, V13 - VRLW V14, V29, V14 - - VADDUWM V10, V15, V10 - VADDUWM V11, V12, V11 - VADDUWM V8, V13, V8 - VADDUWM V9, V14, V9 - - VXOR V5, V10, V5 - VXOR V6, V11, V6 - VXOR V7, V8, V7 - VXOR V4, V9, V4 - - VRLW V5, V30, V5 - VRLW V6, V30, V6 - VRLW V7, V30, V7 - VRLW V4, V30, V4 - BC 16, LT, loop_vsx - - VADDUWM V12, V26, V12 - - WORD $0x13600F8C // VMRGEW V0, V1, V27 - WORD $0x13821F8C // VMRGEW V2, V3, V28 - - WORD $0x10000E8C // VMRGOW V0, V1, V0 - WORD $0x10421E8C // VMRGOW V2, V3, V2 - - WORD $0x13A42F8C // VMRGEW V4, V5, V29 - WORD $0x13C63F8C // VMRGEW V6, V7, V30 - - XXPERMDI VS32, VS34, $0, VS33 - XXPERMDI VS32, VS34, $3, VS35 - XXPERMDI VS59, VS60, $0, VS32 - XXPERMDI VS59, VS60, $3, VS34 - - WORD $0x10842E8C // VMRGOW V4, V5, V4 - WORD $0x10C63E8C // VMRGOW V6, V7, V6 - - WORD $0x13684F8C // VMRGEW V8, V9, V27 - WORD $0x138A5F8C // VMRGEW V10, V11, V28 - - XXPERMDI VS36, VS38, $0, VS37 - XXPERMDI VS36, VS38, $3, VS39 - XXPERMDI VS61, VS62, $0, VS36 - XXPERMDI VS61, VS62, $3, VS38 - - WORD $0x11084E8C // VMRGOW V8, V9, V8 - WORD $0x114A5E8C // VMRGOW V10, V11, V10 - - WORD $0x13AC6F8C // VMRGEW V12, V13, V29 - WORD $0x13CE7F8C // VMRGEW V14, V15, V30 - - XXPERMDI VS40, VS42, $0, VS41 - XXPERMDI VS40, VS42, $3, VS43 - XXPERMDI VS59, VS60, $0, VS40 - XXPERMDI VS59, VS60, $3, VS42 - - WORD $0x118C6E8C // VMRGOW V12, V13, V12 - WORD $0x11CE7E8C // VMRGOW V14, V15, V14 - - VSPLTISW $4, V27 - VADDUWM V26, V27, V26 - - XXPERMDI VS44, VS46, $0, VS45 - XXPERMDI VS44, VS46, $3, VS47 - XXPERMDI VS61, VS62, $0, VS44 - XXPERMDI VS61, VS62, $3, VS46 - - VADDUWM V0, V16, V0 - VADDUWM V4, V17, V4 - VADDUWM V8, V18, V8 - VADDUWM V12, V19, V12 - - CMPU LEN, $64 - BLT tail_vsx - - // Bottom of loop - LXVW4X (INP)(R0), VS59 - LXVW4X (INP)(R8), VS60 - LXVW4X (INP)(R9), VS61 - LXVW4X (INP)(R10), VS62 - - VXOR V27, V0, V27 - VXOR V28, V4, V28 - VXOR V29, V8, V29 - VXOR V30, V12, V30 - - STXVW4X VS59, (OUT)(R0) - STXVW4X VS60, (OUT)(R8) - ADD $64, INP - STXVW4X VS61, (OUT)(R9) - ADD $-64, LEN - STXVW4X VS62, (OUT)(R10) - ADD $64, OUT - BEQ done_vsx - - VADDUWM V1, V16, V0 - VADDUWM V5, V17, V4 - VADDUWM V9, V18, V8 - VADDUWM V13, V19, V12 - - CMPU LEN, $64 - BLT tail_vsx - - LXVW4X (INP)(R0), VS59 - LXVW4X (INP)(R8), VS60 - LXVW4X (INP)(R9), VS61 - LXVW4X (INP)(R10), VS62 - VXOR V27, V0, V27 - - VXOR V28, V4, V28 - VXOR V29, V8, V29 - VXOR V30, V12, V30 - - STXVW4X VS59, (OUT)(R0) - STXVW4X VS60, (OUT)(R8) - ADD $64, INP - STXVW4X VS61, (OUT)(R9) - ADD $-64, LEN - STXVW4X VS62, (OUT)(V10) - ADD $64, OUT - BEQ done_vsx - - VADDUWM V2, V16, V0 - VADDUWM V6, V17, V4 - VADDUWM V10, V18, V8 - VADDUWM V14, V19, V12 - - CMPU LEN, $64 - BLT tail_vsx - - LXVW4X (INP)(R0), VS59 - LXVW4X (INP)(R8), VS60 - LXVW4X (INP)(R9), VS61 - LXVW4X (INP)(R10), VS62 - - VXOR V27, V0, V27 - VXOR V28, V4, V28 - VXOR V29, V8, V29 - VXOR V30, V12, V30 - - STXVW4X VS59, (OUT)(R0) - STXVW4X VS60, (OUT)(R8) - ADD $64, INP - STXVW4X VS61, (OUT)(R9) - ADD $-64, LEN - STXVW4X VS62, (OUT)(R10) - ADD $64, OUT - BEQ done_vsx - - VADDUWM V3, V16, V0 - VADDUWM V7, V17, V4 - VADDUWM V11, V18, V8 - VADDUWM V15, V19, V12 - - CMPU LEN, $64 - BLT tail_vsx - - LXVW4X (INP)(R0), VS59 - LXVW4X (INP)(R8), VS60 - LXVW4X (INP)(R9), VS61 - LXVW4X (INP)(R10), VS62 - - VXOR V27, V0, V27 - VXOR V28, V4, V28 - VXOR V29, V8, V29 - VXOR V30, V12, V30 - - STXVW4X VS59, (OUT)(R0) - STXVW4X VS60, (OUT)(R8) - ADD $64, INP - STXVW4X VS61, (OUT)(R9) - ADD $-64, LEN - STXVW4X VS62, (OUT)(R10) - ADD $64, OUT - - MOVD $10, R14 - MOVD R14, CTR - BNE loop_outer_vsx - -done_vsx: - // Increment counter by 4 - MOVD (CNT), R14 - ADD $4, R14 - MOVD R14, (CNT) - RET - -tail_vsx: - ADD $32, R1, R11 - MOVD LEN, CTR - - // Save values on stack to copy from - STXVW4X VS32, (R11)(R0) - STXVW4X VS36, (R11)(R8) - STXVW4X VS40, (R11)(R9) - STXVW4X VS44, (R11)(R10) - ADD $-1, R11, R12 - ADD $-1, INP - ADD $-1, OUT - -looptail_vsx: - // Copying the result to OUT - // in bytes. - MOVBZU 1(R12), KEY - MOVBZU 1(INP), TMP - XOR KEY, TMP, KEY - MOVBU KEY, 1(OUT) - BC 16, LT, looptail_vsx - - // Clear the stack values - STXVW4X VS48, (R11)(R0) - STXVW4X VS48, (R11)(R8) - STXVW4X VS48, (R11)(R9) - STXVW4X VS48, (R11)(R10) - BR done_vsx diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go deleted file mode 100644 index ad74e23aef4..00000000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_arm64.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.11 -// +build !gccgo - -package chacha20 - -const ( - haveAsm = true - bufSize = 256 -) - -//go:noescape -func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32) - -func (c *Cipher) xorKeyStreamAsm(dst, src []byte) { - - if len(src) >= bufSize { - xorKeyStreamVX(dst, src, &c.key, &c.nonce, &c.counter) - } - - if len(src)%bufSize != 0 { - i := len(src) - len(src)%bufSize - c.buf = [bufSize]byte{} - copy(c.buf[:], src[i:]) - xorKeyStreamVX(c.buf[:], c.buf[:], &c.key, &c.nonce, &c.counter) - c.len = bufSize - copy(dst[i:], c.buf[:len(src)%bufSize]) - } -} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_generic.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_generic.go deleted file mode 100644 index 6570847f5e0..00000000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_generic.go +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ChaCha20 implements the core ChaCha20 function as specified -// in https://tools.ietf.org/html/rfc7539#section-2.3. -package chacha20 - -import ( - "crypto/cipher" - "encoding/binary" - - "golang.org/x/crypto/internal/subtle" -) - -// assert that *Cipher implements cipher.Stream -var _ cipher.Stream = (*Cipher)(nil) - -// Cipher is a stateful instance of ChaCha20 using a particular key -// and nonce. A *Cipher implements the cipher.Stream interface. -type Cipher struct { - key [8]uint32 - counter uint32 // incremented after each block - nonce [3]uint32 - buf [bufSize]byte // buffer for unused keystream bytes - len int // number of unused keystream bytes at end of buf -} - -// New creates a new ChaCha20 stream cipher with the given key and nonce. -// The initial counter value is set to 0. -func New(key [8]uint32, nonce [3]uint32) *Cipher { - return &Cipher{key: key, nonce: nonce} -} - -// ChaCha20 constants spelling "expand 32-byte k" -const ( - j0 uint32 = 0x61707865 - j1 uint32 = 0x3320646e - j2 uint32 = 0x79622d32 - j3 uint32 = 0x6b206574 -) - -func quarterRound(a, b, c, d uint32) (uint32, uint32, uint32, uint32) { - a += b - d ^= a - d = (d << 16) | (d >> 16) - c += d - b ^= c - b = (b << 12) | (b >> 20) - a += b - d ^= a - d = (d << 8) | (d >> 24) - c += d - b ^= c - b = (b << 7) | (b >> 25) - return a, b, c, d -} - -// XORKeyStream XORs each byte in the given slice with a byte from the -// cipher's key stream. Dst and src must overlap entirely or not at all. -// -// If len(dst) < len(src), XORKeyStream will panic. It is acceptable -// to pass a dst bigger than src, and in that case, XORKeyStream will -// only update dst[:len(src)] and will not touch the rest of dst. -// -// Multiple calls to XORKeyStream behave as if the concatenation of -// the src buffers was passed in a single run. That is, Cipher -// maintains state and does not reset at each XORKeyStream call. -func (s *Cipher) XORKeyStream(dst, src []byte) { - if len(dst) < len(src) { - panic("chacha20: output smaller than input") - } - if subtle.InexactOverlap(dst[:len(src)], src) { - panic("chacha20: invalid buffer overlap") - } - - // xor src with buffered keystream first - if s.len != 0 { - buf := s.buf[len(s.buf)-s.len:] - if len(src) < len(buf) { - buf = buf[:len(src)] - } - td, ts := dst[:len(buf)], src[:len(buf)] // BCE hint - for i, b := range buf { - td[i] = ts[i] ^ b - } - s.len -= len(buf) - if s.len != 0 { - return - } - s.buf = [len(s.buf)]byte{} // zero the empty buffer - src = src[len(buf):] - dst = dst[len(buf):] - } - - if len(src) == 0 { - return - } - if haveAsm { - if uint64(len(src))+uint64(s.counter)*64 > (1<<38)-64 { - panic("chacha20: counter overflow") - } - s.xorKeyStreamAsm(dst, src) - return - } - - // set up a 64-byte buffer to pad out the final block if needed - // (hoisted out of the main loop to avoid spills) - rem := len(src) % 64 // length of final block - fin := len(src) - rem // index of final block - if rem > 0 { - copy(s.buf[len(s.buf)-64:], src[fin:]) - } - - // pre-calculate most of the first round - s1, s5, s9, s13 := quarterRound(j1, s.key[1], s.key[5], s.nonce[0]) - s2, s6, s10, s14 := quarterRound(j2, s.key[2], s.key[6], s.nonce[1]) - s3, s7, s11, s15 := quarterRound(j3, s.key[3], s.key[7], s.nonce[2]) - - n := len(src) - src, dst = src[:n:n], dst[:n:n] // BCE hint - for i := 0; i < n; i += 64 { - // calculate the remainder of the first round - s0, s4, s8, s12 := quarterRound(j0, s.key[0], s.key[4], s.counter) - - // execute the second round - x0, x5, x10, x15 := quarterRound(s0, s5, s10, s15) - x1, x6, x11, x12 := quarterRound(s1, s6, s11, s12) - x2, x7, x8, x13 := quarterRound(s2, s7, s8, s13) - x3, x4, x9, x14 := quarterRound(s3, s4, s9, s14) - - // execute the remaining 18 rounds - for i := 0; i < 9; i++ { - x0, x4, x8, x12 = quarterRound(x0, x4, x8, x12) - x1, x5, x9, x13 = quarterRound(x1, x5, x9, x13) - x2, x6, x10, x14 = quarterRound(x2, x6, x10, x14) - x3, x7, x11, x15 = quarterRound(x3, x7, x11, x15) - - x0, x5, x10, x15 = quarterRound(x0, x5, x10, x15) - x1, x6, x11, x12 = quarterRound(x1, x6, x11, x12) - x2, x7, x8, x13 = quarterRound(x2, x7, x8, x13) - x3, x4, x9, x14 = quarterRound(x3, x4, x9, x14) - } - - x0 += j0 - x1 += j1 - x2 += j2 - x3 += j3 - - x4 += s.key[0] - x5 += s.key[1] - x6 += s.key[2] - x7 += s.key[3] - x8 += s.key[4] - x9 += s.key[5] - x10 += s.key[6] - x11 += s.key[7] - - x12 += s.counter - x13 += s.nonce[0] - x14 += s.nonce[1] - x15 += s.nonce[2] - - // increment the counter - s.counter += 1 - if s.counter == 0 { - panic("chacha20: counter overflow") - } - - // pad to 64 bytes if needed - in, out := src[i:], dst[i:] - if i == fin { - // src[fin:] has already been copied into s.buf before - // the main loop - in, out = s.buf[len(s.buf)-64:], s.buf[len(s.buf)-64:] - } - in, out = in[:64], out[:64] // BCE hint - - // XOR the key stream with the source and write out the result - xor(out[0:], in[0:], x0) - xor(out[4:], in[4:], x1) - xor(out[8:], in[8:], x2) - xor(out[12:], in[12:], x3) - xor(out[16:], in[16:], x4) - xor(out[20:], in[20:], x5) - xor(out[24:], in[24:], x6) - xor(out[28:], in[28:], x7) - xor(out[32:], in[32:], x8) - xor(out[36:], in[36:], x9) - xor(out[40:], in[40:], x10) - xor(out[44:], in[44:], x11) - xor(out[48:], in[48:], x12) - xor(out[52:], in[52:], x13) - xor(out[56:], in[56:], x14) - xor(out[60:], in[60:], x15) - } - // copy any trailing bytes out of the buffer and into dst - if rem != 0 { - s.len = 64 - rem - copy(dst[fin:], s.buf[len(s.buf)-64:]) - } -} - -// Advance discards bytes in the key stream until the next 64 byte block -// boundary is reached and updates the counter accordingly. If the key -// stream is already at a block boundary no bytes will be discarded and -// the counter will be unchanged. -func (s *Cipher) Advance() { - s.len -= s.len % 64 - if s.len == 0 { - s.buf = [len(s.buf)]byte{} - } -} - -// XORKeyStream crypts bytes from in to out using the given key and counters. -// In and out must overlap entirely or not at all. Counter contains the raw -// ChaCha20 counter bytes (i.e. block counter followed by nonce). -func XORKeyStream(out, in []byte, counter *[16]byte, key *[32]byte) { - s := Cipher{ - key: [8]uint32{ - binary.LittleEndian.Uint32(key[0:4]), - binary.LittleEndian.Uint32(key[4:8]), - binary.LittleEndian.Uint32(key[8:12]), - binary.LittleEndian.Uint32(key[12:16]), - binary.LittleEndian.Uint32(key[16:20]), - binary.LittleEndian.Uint32(key[20:24]), - binary.LittleEndian.Uint32(key[24:28]), - binary.LittleEndian.Uint32(key[28:32]), - }, - nonce: [3]uint32{ - binary.LittleEndian.Uint32(counter[4:8]), - binary.LittleEndian.Uint32(counter[8:12]), - binary.LittleEndian.Uint32(counter[12:16]), - }, - counter: binary.LittleEndian.Uint32(counter[0:4]), - } - s.XORKeyStream(out, in) -} - -// HChaCha20 uses the ChaCha20 core to generate a derived key from a key and a -// nonce. It should only be used as part of the XChaCha20 construction. -func HChaCha20(key *[8]uint32, nonce *[4]uint32) [8]uint32 { - x0, x1, x2, x3 := j0, j1, j2, j3 - x4, x5, x6, x7 := key[0], key[1], key[2], key[3] - x8, x9, x10, x11 := key[4], key[5], key[6], key[7] - x12, x13, x14, x15 := nonce[0], nonce[1], nonce[2], nonce[3] - - for i := 0; i < 10; i++ { - x0, x4, x8, x12 = quarterRound(x0, x4, x8, x12) - x1, x5, x9, x13 = quarterRound(x1, x5, x9, x13) - x2, x6, x10, x14 = quarterRound(x2, x6, x10, x14) - x3, x7, x11, x15 = quarterRound(x3, x7, x11, x15) - - x0, x5, x10, x15 = quarterRound(x0, x5, x10, x15) - x1, x6, x11, x12 = quarterRound(x1, x6, x11, x12) - x2, x7, x8, x13 = quarterRound(x2, x7, x8, x13) - x3, x4, x9, x14 = quarterRound(x3, x4, x9, x14) - } - - var out [8]uint32 - out[0], out[1], out[2], out[3] = x0, x1, x2, x3 - out[4], out[5], out[6], out[7] = x12, x13, x14, x15 - return out -} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go deleted file mode 100644 index fc2682528b5..00000000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_noasm.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !arm64,!s390x,!ppc64le arm64,!go1.11 gccgo appengine - -package chacha20 - -const ( - bufSize = 64 - haveAsm = false -) - -func (*Cipher) xorKeyStreamAsm(dst, src []byte) { - panic("not implemented") -} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_ppc64le.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_ppc64le.go deleted file mode 100644 index d38a7d380a2..00000000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_ppc64le.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ppc64le,!gccgo,!appengine - -package chacha20 - -import ( - "encoding/binary" -) - -var haveAsm = true - -const bufSize = 256 - -//go:noescape -func chaCha20_ctr32_vsx(out, inp *byte, len int, key *[8]uint32, counter *uint32) - -func (c *Cipher) xorKeyStreamAsm(dst, src []byte) { - // This implementation can handle buffers that aren't multiples of - // 256. - if len(src) >= bufSize { - chaCha20_ctr32_vsx(&dst[0], &src[0], len(src), &c.key, &c.counter) - } else if len(src)%bufSize != 0 { - chaCha20_ctr32_vsx(&c.buf[0], &c.buf[0], bufSize, &c.key, &c.counter) - start := len(src) - len(src)%bufSize - ts, td, tb := src[start:], dst[start:], c.buf[:] - // Unroll loop to XOR 32 bytes per iteration. - for i := 0; i < len(ts)-32; i += 32 { - td, tb = td[:len(ts)], tb[:len(ts)] // bounds check elimination - s0 := binary.LittleEndian.Uint64(ts[0:8]) - s1 := binary.LittleEndian.Uint64(ts[8:16]) - s2 := binary.LittleEndian.Uint64(ts[16:24]) - s3 := binary.LittleEndian.Uint64(ts[24:32]) - b0 := binary.LittleEndian.Uint64(tb[0:8]) - b1 := binary.LittleEndian.Uint64(tb[8:16]) - b2 := binary.LittleEndian.Uint64(tb[16:24]) - b3 := binary.LittleEndian.Uint64(tb[24:32]) - binary.LittleEndian.PutUint64(td[0:8], s0^b0) - binary.LittleEndian.PutUint64(td[8:16], s1^b1) - binary.LittleEndian.PutUint64(td[16:24], s2^b2) - binary.LittleEndian.PutUint64(td[24:32], s3^b3) - ts, td, tb = ts[32:], td[32:], tb[32:] - } - td, tb = td[:len(ts)], tb[:len(ts)] // bounds check elimination - for i, v := range ts { - td[i] = tb[i] ^ v - } - c.len = bufSize - (len(src) % bufSize) - } - -} diff --git a/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.go b/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.go deleted file mode 100644 index aad645b4476..00000000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/chacha_s390x.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build s390x,!gccgo,!appengine - -package chacha20 - -import ( - "golang.org/x/sys/cpu" -) - -var haveAsm = cpu.S390X.HasVX - -const bufSize = 256 - -// xorKeyStreamVX is an assembly implementation of XORKeyStream. It must only -// be called when the vector facility is available. -// Implementation in asm_s390x.s. -//go:noescape -func xorKeyStreamVX(dst, src []byte, key *[8]uint32, nonce *[3]uint32, counter *uint32, buf *[256]byte, len *int) - -func (c *Cipher) xorKeyStreamAsm(dst, src []byte) { - xorKeyStreamVX(dst, src, &c.key, &c.nonce, &c.counter, &c.buf, &c.len) -} - -// EXRL targets, DO NOT CALL! -func mvcSrcToBuf() -func mvcBufToDst() diff --git a/vendor/golang.org/x/crypto/internal/chacha20/xor.go b/vendor/golang.org/x/crypto/internal/chacha20/xor.go deleted file mode 100644 index 9c5ba0b33ae..00000000000 --- a/vendor/golang.org/x/crypto/internal/chacha20/xor.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found src the LICENSE file. - -package chacha20 - -import ( - "runtime" -) - -// Platforms that have fast unaligned 32-bit little endian accesses. -const unaligned = runtime.GOARCH == "386" || - runtime.GOARCH == "amd64" || - runtime.GOARCH == "arm64" || - runtime.GOARCH == "ppc64le" || - runtime.GOARCH == "s390x" - -// xor reads a little endian uint32 from src, XORs it with u and -// places the result in little endian byte order in dst. -func xor(dst, src []byte, u uint32) { - _, _ = src[3], dst[3] // eliminate bounds checks - if unaligned { - // The compiler should optimize this code into - // 32-bit unaligned little endian loads and stores. - // TODO: delete once the compiler does a reliably - // good job with the generic code below. - // See issue #25111 for more details. - v := uint32(src[0]) - v |= uint32(src[1]) << 8 - v |= uint32(src[2]) << 16 - v |= uint32(src[3]) << 24 - v ^= u - dst[0] = byte(v) - dst[1] = byte(v >> 8) - dst[2] = byte(v >> 16) - dst[3] = byte(v >> 24) - } else { - dst[0] = src[0] ^ byte(u) - dst[1] = src[1] ^ byte(u>>8) - dst[2] = src[2] ^ byte(u>>16) - dst[3] = src[3] ^ byte(u>>24) - } -} diff --git a/vendor/golang.org/x/crypto/openpgp/armor/armor.go b/vendor/golang.org/x/crypto/openpgp/armor/armor.go index 592d1864361..36a6804364c 100644 --- a/vendor/golang.org/x/crypto/openpgp/armor/armor.go +++ b/vendor/golang.org/x/crypto/openpgp/armor/armor.go @@ -62,10 +62,11 @@ var armorEndOfLine = []byte("-----") // lineReader wraps a line based reader. It watches for the end of an armor // block and records the expected CRC value. type lineReader struct { - in *bufio.Reader - buf []byte - eof bool - crc uint32 + in *bufio.Reader + buf []byte + eof bool + crc uint32 + crcSet bool } func (l *lineReader) Read(p []byte) (n int, err error) { @@ -87,6 +88,11 @@ func (l *lineReader) Read(p []byte) (n int, err error) { return 0, ArmorCorrupt } + if bytes.HasPrefix(line, armorEnd) { + l.eof = true + return 0, io.EOF + } + if len(line) == 5 && line[0] == '=' { // This is the checksum line var expectedBytes [3]byte @@ -108,6 +114,7 @@ func (l *lineReader) Read(p []byte) (n int, err error) { } l.eof = true + l.crcSet = true return 0, io.EOF } @@ -141,10 +148,8 @@ func (r *openpgpReader) Read(p []byte) (n int, err error) { n, err = r.b64Reader.Read(p) r.currentCRC = crc24(r.currentCRC, p[:n]) - if err == io.EOF { - if r.lReader.crc != uint32(r.currentCRC&crc24Mask) { - return 0, ArmorCorrupt - } + if err == io.EOF && r.lReader.crcSet && r.lReader.crc != uint32(r.currentCRC&crc24Mask) { + return 0, ArmorCorrupt } return diff --git a/vendor/golang.org/x/crypto/openpgp/elgamal/elgamal.go b/vendor/golang.org/x/crypto/openpgp/elgamal/elgamal.go index 73f4fe37859..72a6a739471 100644 --- a/vendor/golang.org/x/crypto/openpgp/elgamal/elgamal.go +++ b/vendor/golang.org/x/crypto/openpgp/elgamal/elgamal.go @@ -76,7 +76,9 @@ func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err // Bleichenbacher, Advances in Cryptology (Crypto '98), func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err error) { s := new(big.Int).Exp(c1, priv.X, priv.P) - s.ModInverse(s, priv.P) + if s.ModInverse(s, priv.P) == nil { + return nil, errors.New("elgamal: invalid private key") + } s.Mul(s, c2) s.Mod(s, priv.P) em := s.Bytes() diff --git a/vendor/golang.org/x/crypto/openpgp/packet/packet.go b/vendor/golang.org/x/crypto/openpgp/packet/packet.go index 5af64c5421b..9728d61d7aa 100644 --- a/vendor/golang.org/x/crypto/openpgp/packet/packet.go +++ b/vendor/golang.org/x/crypto/openpgp/packet/packet.go @@ -14,6 +14,7 @@ import ( "crypto/rsa" "io" "math/big" + "math/bits" "golang.org/x/crypto/cast5" "golang.org/x/crypto/openpgp/errors" @@ -100,33 +101,65 @@ func (r *partialLengthReader) Read(p []byte) (n int, err error) { type partialLengthWriter struct { w io.WriteCloser lengthByte [1]byte + sentFirst bool + buf []byte } +// RFC 4880 4.2.2.4: the first partial length MUST be at least 512 octets long. +const minFirstPartialWrite = 512 + func (w *partialLengthWriter) Write(p []byte) (n int, err error) { + off := 0 + if !w.sentFirst { + if len(w.buf) > 0 || len(p) < minFirstPartialWrite { + off = len(w.buf) + w.buf = append(w.buf, p...) + if len(w.buf) < minFirstPartialWrite { + return len(p), nil + } + p = w.buf + w.buf = nil + } + w.sentFirst = true + } + + power := uint8(30) for len(p) > 0 { - for power := uint(14); power < 32; power-- { - l := 1 << power - if len(p) >= l { - w.lengthByte[0] = 224 + uint8(power) - _, err = w.w.Write(w.lengthByte[:]) - if err != nil { - return - } - var m int - m, err = w.w.Write(p[:l]) - n += m - if err != nil { - return - } - p = p[l:] - break + l := 1 << power + if len(p) < l { + power = uint8(bits.Len32(uint32(len(p)))) - 1 + l = 1 << power + } + w.lengthByte[0] = 224 + power + _, err = w.w.Write(w.lengthByte[:]) + if err == nil { + var m int + m, err = w.w.Write(p[:l]) + n += m + } + if err != nil { + if n < off { + return 0, err } + return n - off, err } + p = p[l:] } - return + return n - off, nil } func (w *partialLengthWriter) Close() error { + if len(w.buf) > 0 { + // In this case we can't send a 512 byte packet. + // Just send what we have. + p := w.buf + w.sentFirst = true + w.buf = nil + if _, err := w.Write(p); err != nil { + return err + } + } + w.lengthByte[0] = 0 _, err := w.w.Write(w.lengthByte[:]) if err != nil { diff --git a/vendor/golang.org/x/crypto/poly1305/bits_compat.go b/vendor/golang.org/x/crypto/poly1305/bits_compat.go new file mode 100644 index 00000000000..157a69f61bd --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/bits_compat.go @@ -0,0 +1,39 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.13 + +package poly1305 + +// Generic fallbacks for the math/bits intrinsics, copied from +// src/math/bits/bits.go. They were added in Go 1.12, but Add64 and Sum64 had +// variable time fallbacks until Go 1.13. + +func bitsAdd64(x, y, carry uint64) (sum, carryOut uint64) { + sum = x + y + carry + carryOut = ((x & y) | ((x | y) &^ sum)) >> 63 + return +} + +func bitsSub64(x, y, borrow uint64) (diff, borrowOut uint64) { + diff = x - y - borrow + borrowOut = ((^x & y) | (^(x ^ y) & diff)) >> 63 + return +} + +func bitsMul64(x, y uint64) (hi, lo uint64) { + const mask32 = 1<<32 - 1 + x0 := x & mask32 + x1 := x >> 32 + y0 := y & mask32 + y1 := y >> 32 + w0 := x0 * y0 + t := x1*y0 + w0>>32 + w1 := t & mask32 + w2 := t >> 32 + w1 += x0 * y1 + hi = x1*y1 + w2 + w1>>32 + lo = x * y + return +} diff --git a/vendor/golang.org/x/crypto/poly1305/bits_go1.13.go b/vendor/golang.org/x/crypto/poly1305/bits_go1.13.go new file mode 100644 index 00000000000..a0a185f0fc7 --- /dev/null +++ b/vendor/golang.org/x/crypto/poly1305/bits_go1.13.go @@ -0,0 +1,21 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.13 + +package poly1305 + +import "math/bits" + +func bitsAdd64(x, y, carry uint64) (sum, carryOut uint64) { + return bits.Add64(x, y, carry) +} + +func bitsSub64(x, y, borrow uint64) (diff, borrowOut uint64) { + return bits.Sub64(x, y, borrow) +} + +func bitsMul64(x, y uint64) (hi, lo uint64) { + return bits.Mul64(x, y) +} diff --git a/vendor/golang.org/x/crypto/poly1305/mac_noasm.go b/vendor/golang.org/x/crypto/poly1305/mac_noasm.go index a8dd589ae39..d118f30ed56 100644 --- a/vendor/golang.org/x/crypto/poly1305/mac_noasm.go +++ b/vendor/golang.org/x/crypto/poly1305/mac_noasm.go @@ -2,10 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build !amd64,!ppc64le gccgo appengine +// +build !amd64,!ppc64le,!s390x gccgo purego package poly1305 type mac struct{ macGeneric } - -func newMAC(key *[32]byte) mac { return mac{newMACGeneric(key)} } diff --git a/vendor/golang.org/x/crypto/poly1305/poly1305.go b/vendor/golang.org/x/crypto/poly1305/poly1305.go index d076a562351..9d7a6af09fe 100644 --- a/vendor/golang.org/x/crypto/poly1305/poly1305.go +++ b/vendor/golang.org/x/crypto/poly1305/poly1305.go @@ -22,8 +22,16 @@ import "crypto/subtle" // TagSize is the size, in bytes, of a poly1305 authenticator. const TagSize = 16 -// Verify returns true if mac is a valid authenticator for m with the given -// key. +// Sum generates an authenticator for msg using a one-time key and puts the +// 16-byte result into out. Authenticating two different messages with the same +// key allows an attacker to forge messages at will. +func Sum(out *[16]byte, m []byte, key *[32]byte) { + h := New(key) + h.Write(m) + h.Sum(out[:0]) +} + +// Verify returns true if mac is a valid authenticator for m with the given key. func Verify(mac *[16]byte, m []byte, key *[32]byte) bool { var tmp [16]byte Sum(&tmp, m, key) @@ -40,10 +48,9 @@ func Verify(mac *[16]byte, m []byte, key *[32]byte) bool { // two different messages with the same key allows an attacker // to forge messages at will. func New(key *[32]byte) *MAC { - return &MAC{ - mac: newMAC(key), - finalized: false, - } + m := &MAC{} + initialize(key, &m.macState) + return m } // MAC is an io.Writer computing an authentication tag @@ -52,7 +59,7 @@ func New(key *[32]byte) *MAC { // MAC cannot be used like common hash.Hash implementations, // because using a poly1305 key twice breaks its security. // Therefore writing data to a running MAC after calling -// Sum causes it to panic. +// Sum or Verify causes it to panic. type MAC struct { mac // platform-dependent implementation @@ -65,10 +72,10 @@ func (h *MAC) Size() int { return TagSize } // Write adds more data to the running message authentication code. // It never returns an error. // -// It must not be called after the first call of Sum. +// It must not be called after the first call of Sum or Verify. func (h *MAC) Write(p []byte) (n int, err error) { if h.finalized { - panic("poly1305: write to MAC after Sum") + panic("poly1305: write to MAC after Sum or Verify") } return h.mac.Write(p) } @@ -81,3 +88,12 @@ func (h *MAC) Sum(b []byte) []byte { h.finalized = true return append(b, mac[:]...) } + +// Verify returns whether the authenticator of all data written to +// the message authentication code matches the expected value. +func (h *MAC) Verify(expected []byte) bool { + var mac [TagSize]byte + h.mac.Sum(&mac) + h.finalized = true + return subtle.ConstantTimeCompare(expected, mac[:]) == 1 +} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_amd64.go b/vendor/golang.org/x/crypto/poly1305/sum_amd64.go index 2dbf42aa537..99e5a1d50ef 100644 --- a/vendor/golang.org/x/crypto/poly1305/sum_amd64.go +++ b/vendor/golang.org/x/crypto/poly1305/sum_amd64.go @@ -2,67 +2,46 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build amd64,!gccgo,!appengine +// +build !gccgo,!purego package poly1305 //go:noescape -func initialize(state *[7]uint64, key *[32]byte) +func update(state *macState, msg []byte) -//go:noescape -func update(state *[7]uint64, msg []byte) - -//go:noescape -func finalize(tag *[TagSize]byte, state *[7]uint64) - -// Sum generates an authenticator for m using a one-time key and puts the -// 16-byte result into out. Authenticating two different messages with the same -// key allows an attacker to forge messages at will. -func Sum(out *[16]byte, m []byte, key *[32]byte) { - h := newMAC(key) - h.Write(m) - h.Sum(out) -} - -func newMAC(key *[32]byte) (h mac) { - initialize(&h.state, key) - return -} - -type mac struct { - state [7]uint64 // := uint64{ h0, h1, h2, r0, r1, pad0, pad1 } - - buffer [TagSize]byte - offset int -} +// mac is a wrapper for macGeneric that redirects calls that would have gone to +// updateGeneric to update. +// +// Its Write and Sum methods are otherwise identical to the macGeneric ones, but +// using function pointers would carry a major performance cost. +type mac struct{ macGeneric } -func (h *mac) Write(p []byte) (n int, err error) { - n = len(p) +func (h *mac) Write(p []byte) (int, error) { + nn := len(p) if h.offset > 0 { - remaining := TagSize - h.offset - if n < remaining { - h.offset += copy(h.buffer[h.offset:], p) - return n, nil + n := copy(h.buffer[h.offset:], p) + if h.offset+n < TagSize { + h.offset += n + return nn, nil } - copy(h.buffer[h.offset:], p[:remaining]) - p = p[remaining:] + p = p[n:] h.offset = 0 - update(&h.state, h.buffer[:]) + update(&h.macState, h.buffer[:]) } - if nn := len(p) - (len(p) % TagSize); nn > 0 { - update(&h.state, p[:nn]) - p = p[nn:] + if n := len(p) - (len(p) % TagSize); n > 0 { + update(&h.macState, p[:n]) + p = p[n:] } if len(p) > 0 { h.offset += copy(h.buffer[h.offset:], p) } - return n, nil + return nn, nil } func (h *mac) Sum(out *[16]byte) { - state := h.state + state := h.macState if h.offset > 0 { update(&state, h.buffer[:h.offset]) } - finalize(out, &state) + finalize(out, &state.h, &state.s) } diff --git a/vendor/golang.org/x/crypto/poly1305/sum_amd64.s b/vendor/golang.org/x/crypto/poly1305/sum_amd64.s index 7d600f13cc8..8d394a212ee 100644 --- a/vendor/golang.org/x/crypto/poly1305/sum_amd64.s +++ b/vendor/golang.org/x/crypto/poly1305/sum_amd64.s @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build amd64,!gccgo,!appengine +// +build !gccgo,!purego #include "textflag.h" @@ -54,10 +54,6 @@ ADCQ t3, h1; \ ADCQ $0, h2 -DATA ·poly1305Mask<>+0x00(SB)/8, $0x0FFFFFFC0FFFFFFF -DATA ·poly1305Mask<>+0x08(SB)/8, $0x0FFFFFFC0FFFFFFC -GLOBL ·poly1305Mask<>(SB), RODATA, $16 - // func update(state *[7]uint64, msg []byte) TEXT ·update(SB), $0-32 MOVQ state+0(FP), DI @@ -110,39 +106,3 @@ done: MOVQ R9, 8(DI) MOVQ R10, 16(DI) RET - -// func initialize(state *[7]uint64, key *[32]byte) -TEXT ·initialize(SB), $0-16 - MOVQ state+0(FP), DI - MOVQ key+8(FP), SI - - // state[0...7] is initialized with zero - MOVOU 0(SI), X0 - MOVOU 16(SI), X1 - MOVOU ·poly1305Mask<>(SB), X2 - PAND X2, X0 - MOVOU X0, 24(DI) - MOVOU X1, 40(DI) - RET - -// func finalize(tag *[TagSize]byte, state *[7]uint64) -TEXT ·finalize(SB), $0-16 - MOVQ tag+0(FP), DI - MOVQ state+8(FP), SI - - MOVQ 0(SI), AX - MOVQ 8(SI), BX - MOVQ 16(SI), CX - MOVQ AX, R8 - MOVQ BX, R9 - SUBQ $0xFFFFFFFFFFFFFFFB, AX - SBBQ $0xFFFFFFFFFFFFFFFF, BX - SBBQ $3, CX - CMOVQCS R8, AX - CMOVQCS R9, BX - ADDQ 40(SI), AX - ADCQ 48(SI), BX - - MOVQ AX, 0(DI) - MOVQ BX, 8(DI) - RET diff --git a/vendor/golang.org/x/crypto/poly1305/sum_arm.go b/vendor/golang.org/x/crypto/poly1305/sum_arm.go deleted file mode 100644 index 5dc321c2f39..00000000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_arm.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm,!gccgo,!appengine,!nacl - -package poly1305 - -// This function is implemented in sum_arm.s -//go:noescape -func poly1305_auth_armv6(out *[16]byte, m *byte, mlen uint32, key *[32]byte) - -// Sum generates an authenticator for m using a one-time key and puts the -// 16-byte result into out. Authenticating two different messages with the same -// key allows an attacker to forge messages at will. -func Sum(out *[16]byte, m []byte, key *[32]byte) { - var mPtr *byte - if len(m) > 0 { - mPtr = &m[0] - } - poly1305_auth_armv6(out, mPtr, uint32(len(m)), key) -} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_arm.s b/vendor/golang.org/x/crypto/poly1305/sum_arm.s deleted file mode 100644 index f70b4ac4845..00000000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_arm.s +++ /dev/null @@ -1,427 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build arm,!gccgo,!appengine,!nacl - -#include "textflag.h" - -// This code was translated into a form compatible with 5a from the public -// domain source by Andrew Moon: github.com/floodyberry/poly1305-opt/blob/master/app/extensions/poly1305. - -DATA ·poly1305_init_constants_armv6<>+0x00(SB)/4, $0x3ffffff -DATA ·poly1305_init_constants_armv6<>+0x04(SB)/4, $0x3ffff03 -DATA ·poly1305_init_constants_armv6<>+0x08(SB)/4, $0x3ffc0ff -DATA ·poly1305_init_constants_armv6<>+0x0c(SB)/4, $0x3f03fff -DATA ·poly1305_init_constants_armv6<>+0x10(SB)/4, $0x00fffff -GLOBL ·poly1305_init_constants_armv6<>(SB), 8, $20 - -// Warning: the linker may use R11 to synthesize certain instructions. Please -// take care and verify that no synthetic instructions use it. - -TEXT poly1305_init_ext_armv6<>(SB), NOSPLIT, $0 - // Needs 16 bytes of stack and 64 bytes of space pointed to by R0. (It - // might look like it's only 60 bytes of space but the final four bytes - // will be written by another function.) We need to skip over four - // bytes of stack because that's saving the value of 'g'. - ADD $4, R13, R8 - MOVM.IB [R4-R7], (R8) - MOVM.IA.W (R1), [R2-R5] - MOVW $·poly1305_init_constants_armv6<>(SB), R7 - MOVW R2, R8 - MOVW R2>>26, R9 - MOVW R3>>20, g - MOVW R4>>14, R11 - MOVW R5>>8, R12 - ORR R3<<6, R9, R9 - ORR R4<<12, g, g - ORR R5<<18, R11, R11 - MOVM.IA (R7), [R2-R6] - AND R8, R2, R2 - AND R9, R3, R3 - AND g, R4, R4 - AND R11, R5, R5 - AND R12, R6, R6 - MOVM.IA.W [R2-R6], (R0) - EOR R2, R2, R2 - EOR R3, R3, R3 - EOR R4, R4, R4 - EOR R5, R5, R5 - EOR R6, R6, R6 - MOVM.IA.W [R2-R6], (R0) - MOVM.IA.W (R1), [R2-R5] - MOVM.IA [R2-R6], (R0) - ADD $20, R13, R0 - MOVM.DA (R0), [R4-R7] - RET - -#define MOVW_UNALIGNED(Rsrc, Rdst, Rtmp, offset) \ - MOVBU (offset+0)(Rsrc), Rtmp; \ - MOVBU Rtmp, (offset+0)(Rdst); \ - MOVBU (offset+1)(Rsrc), Rtmp; \ - MOVBU Rtmp, (offset+1)(Rdst); \ - MOVBU (offset+2)(Rsrc), Rtmp; \ - MOVBU Rtmp, (offset+2)(Rdst); \ - MOVBU (offset+3)(Rsrc), Rtmp; \ - MOVBU Rtmp, (offset+3)(Rdst) - -TEXT poly1305_blocks_armv6<>(SB), NOSPLIT, $0 - // Needs 24 bytes of stack for saved registers and then 88 bytes of - // scratch space after that. We assume that 24 bytes at (R13) have - // already been used: four bytes for the link register saved in the - // prelude of poly1305_auth_armv6, four bytes for saving the value of g - // in that function and 16 bytes of scratch space used around - // poly1305_finish_ext_armv6_skip1. - ADD $24, R13, R12 - MOVM.IB [R4-R8, R14], (R12) - MOVW R0, 88(R13) - MOVW R1, 92(R13) - MOVW R2, 96(R13) - MOVW R1, R14 - MOVW R2, R12 - MOVW 56(R0), R8 - WORD $0xe1180008 // TST R8, R8 not working see issue 5921 - EOR R6, R6, R6 - MOVW.EQ $(1<<24), R6 - MOVW R6, 84(R13) - ADD $116, R13, g - MOVM.IA (R0), [R0-R9] - MOVM.IA [R0-R4], (g) - CMP $16, R12 - BLO poly1305_blocks_armv6_done - -poly1305_blocks_armv6_mainloop: - WORD $0xe31e0003 // TST R14, #3 not working see issue 5921 - BEQ poly1305_blocks_armv6_mainloop_aligned - ADD $100, R13, g - MOVW_UNALIGNED(R14, g, R0, 0) - MOVW_UNALIGNED(R14, g, R0, 4) - MOVW_UNALIGNED(R14, g, R0, 8) - MOVW_UNALIGNED(R14, g, R0, 12) - MOVM.IA (g), [R0-R3] - ADD $16, R14 - B poly1305_blocks_armv6_mainloop_loaded - -poly1305_blocks_armv6_mainloop_aligned: - MOVM.IA.W (R14), [R0-R3] - -poly1305_blocks_armv6_mainloop_loaded: - MOVW R0>>26, g - MOVW R1>>20, R11 - MOVW R2>>14, R12 - MOVW R14, 92(R13) - MOVW R3>>8, R4 - ORR R1<<6, g, g - ORR R2<<12, R11, R11 - ORR R3<<18, R12, R12 - BIC $0xfc000000, R0, R0 - BIC $0xfc000000, g, g - MOVW 84(R13), R3 - BIC $0xfc000000, R11, R11 - BIC $0xfc000000, R12, R12 - ADD R0, R5, R5 - ADD g, R6, R6 - ORR R3, R4, R4 - ADD R11, R7, R7 - ADD $116, R13, R14 - ADD R12, R8, R8 - ADD R4, R9, R9 - MOVM.IA (R14), [R0-R4] - MULLU R4, R5, (R11, g) - MULLU R3, R5, (R14, R12) - MULALU R3, R6, (R11, g) - MULALU R2, R6, (R14, R12) - MULALU R2, R7, (R11, g) - MULALU R1, R7, (R14, R12) - ADD R4<<2, R4, R4 - ADD R3<<2, R3, R3 - MULALU R1, R8, (R11, g) - MULALU R0, R8, (R14, R12) - MULALU R0, R9, (R11, g) - MULALU R4, R9, (R14, R12) - MOVW g, 76(R13) - MOVW R11, 80(R13) - MOVW R12, 68(R13) - MOVW R14, 72(R13) - MULLU R2, R5, (R11, g) - MULLU R1, R5, (R14, R12) - MULALU R1, R6, (R11, g) - MULALU R0, R6, (R14, R12) - MULALU R0, R7, (R11, g) - MULALU R4, R7, (R14, R12) - ADD R2<<2, R2, R2 - ADD R1<<2, R1, R1 - MULALU R4, R8, (R11, g) - MULALU R3, R8, (R14, R12) - MULALU R3, R9, (R11, g) - MULALU R2, R9, (R14, R12) - MOVW g, 60(R13) - MOVW R11, 64(R13) - MOVW R12, 52(R13) - MOVW R14, 56(R13) - MULLU R0, R5, (R11, g) - MULALU R4, R6, (R11, g) - MULALU R3, R7, (R11, g) - MULALU R2, R8, (R11, g) - MULALU R1, R9, (R11, g) - ADD $52, R13, R0 - MOVM.IA (R0), [R0-R7] - MOVW g>>26, R12 - MOVW R4>>26, R14 - ORR R11<<6, R12, R12 - ORR R5<<6, R14, R14 - BIC $0xfc000000, g, g - BIC $0xfc000000, R4, R4 - ADD.S R12, R0, R0 - ADC $0, R1, R1 - ADD.S R14, R6, R6 - ADC $0, R7, R7 - MOVW R0>>26, R12 - MOVW R6>>26, R14 - ORR R1<<6, R12, R12 - ORR R7<<6, R14, R14 - BIC $0xfc000000, R0, R0 - BIC $0xfc000000, R6, R6 - ADD R14<<2, R14, R14 - ADD.S R12, R2, R2 - ADC $0, R3, R3 - ADD R14, g, g - MOVW R2>>26, R12 - MOVW g>>26, R14 - ORR R3<<6, R12, R12 - BIC $0xfc000000, g, R5 - BIC $0xfc000000, R2, R7 - ADD R12, R4, R4 - ADD R14, R0, R0 - MOVW R4>>26, R12 - BIC $0xfc000000, R4, R8 - ADD R12, R6, R9 - MOVW 96(R13), R12 - MOVW 92(R13), R14 - MOVW R0, R6 - CMP $32, R12 - SUB $16, R12, R12 - MOVW R12, 96(R13) - BHS poly1305_blocks_armv6_mainloop - -poly1305_blocks_armv6_done: - MOVW 88(R13), R12 - MOVW R5, 20(R12) - MOVW R6, 24(R12) - MOVW R7, 28(R12) - MOVW R8, 32(R12) - MOVW R9, 36(R12) - ADD $48, R13, R0 - MOVM.DA (R0), [R4-R8, R14] - RET - -#define MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp) \ - MOVBU.P 1(Rsrc), Rtmp; \ - MOVBU.P Rtmp, 1(Rdst); \ - MOVBU.P 1(Rsrc), Rtmp; \ - MOVBU.P Rtmp, 1(Rdst) - -#define MOVWP_UNALIGNED(Rsrc, Rdst, Rtmp) \ - MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp); \ - MOVHUP_UNALIGNED(Rsrc, Rdst, Rtmp) - -// func poly1305_auth_armv6(out *[16]byte, m *byte, mlen uint32, key *[32]key) -TEXT ·poly1305_auth_armv6(SB), $196-16 - // The value 196, just above, is the sum of 64 (the size of the context - // structure) and 132 (the amount of stack needed). - // - // At this point, the stack pointer (R13) has been moved down. It - // points to the saved link register and there's 196 bytes of free - // space above it. - // - // The stack for this function looks like: - // - // +--------------------- - // | - // | 64 bytes of context structure - // | - // +--------------------- - // | - // | 112 bytes for poly1305_blocks_armv6 - // | - // +--------------------- - // | 16 bytes of final block, constructed at - // | poly1305_finish_ext_armv6_skip8 - // +--------------------- - // | four bytes of saved 'g' - // +--------------------- - // | lr, saved by prelude <- R13 points here - // +--------------------- - MOVW g, 4(R13) - - MOVW out+0(FP), R4 - MOVW m+4(FP), R5 - MOVW mlen+8(FP), R6 - MOVW key+12(FP), R7 - - ADD $136, R13, R0 // 136 = 4 + 4 + 16 + 112 - MOVW R7, R1 - - // poly1305_init_ext_armv6 will write to the stack from R13+4, but - // that's ok because none of the other values have been written yet. - BL poly1305_init_ext_armv6<>(SB) - BIC.S $15, R6, R2 - BEQ poly1305_auth_armv6_noblocks - ADD $136, R13, R0 - MOVW R5, R1 - ADD R2, R5, R5 - SUB R2, R6, R6 - BL poly1305_blocks_armv6<>(SB) - -poly1305_auth_armv6_noblocks: - ADD $136, R13, R0 - MOVW R5, R1 - MOVW R6, R2 - MOVW R4, R3 - - MOVW R0, R5 - MOVW R1, R6 - MOVW R2, R7 - MOVW R3, R8 - AND.S R2, R2, R2 - BEQ poly1305_finish_ext_armv6_noremaining - EOR R0, R0 - ADD $8, R13, R9 // 8 = offset to 16 byte scratch space - MOVW R0, (R9) - MOVW R0, 4(R9) - MOVW R0, 8(R9) - MOVW R0, 12(R9) - WORD $0xe3110003 // TST R1, #3 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_aligned - WORD $0xe3120008 // TST R2, #8 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip8 - MOVWP_UNALIGNED(R1, R9, g) - MOVWP_UNALIGNED(R1, R9, g) - -poly1305_finish_ext_armv6_skip8: - WORD $0xe3120004 // TST $4, R2 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip4 - MOVWP_UNALIGNED(R1, R9, g) - -poly1305_finish_ext_armv6_skip4: - WORD $0xe3120002 // TST $2, R2 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip2 - MOVHUP_UNALIGNED(R1, R9, g) - B poly1305_finish_ext_armv6_skip2 - -poly1305_finish_ext_armv6_aligned: - WORD $0xe3120008 // TST R2, #8 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip8_aligned - MOVM.IA.W (R1), [g-R11] - MOVM.IA.W [g-R11], (R9) - -poly1305_finish_ext_armv6_skip8_aligned: - WORD $0xe3120004 // TST $4, R2 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip4_aligned - MOVW.P 4(R1), g - MOVW.P g, 4(R9) - -poly1305_finish_ext_armv6_skip4_aligned: - WORD $0xe3120002 // TST $2, R2 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip2 - MOVHU.P 2(R1), g - MOVH.P g, 2(R9) - -poly1305_finish_ext_armv6_skip2: - WORD $0xe3120001 // TST $1, R2 not working see issue 5921 - BEQ poly1305_finish_ext_armv6_skip1 - MOVBU.P 1(R1), g - MOVBU.P g, 1(R9) - -poly1305_finish_ext_armv6_skip1: - MOVW $1, R11 - MOVBU R11, 0(R9) - MOVW R11, 56(R5) - MOVW R5, R0 - ADD $8, R13, R1 - MOVW $16, R2 - BL poly1305_blocks_armv6<>(SB) - -poly1305_finish_ext_armv6_noremaining: - MOVW 20(R5), R0 - MOVW 24(R5), R1 - MOVW 28(R5), R2 - MOVW 32(R5), R3 - MOVW 36(R5), R4 - MOVW R4>>26, R12 - BIC $0xfc000000, R4, R4 - ADD R12<<2, R12, R12 - ADD R12, R0, R0 - MOVW R0>>26, R12 - BIC $0xfc000000, R0, R0 - ADD R12, R1, R1 - MOVW R1>>26, R12 - BIC $0xfc000000, R1, R1 - ADD R12, R2, R2 - MOVW R2>>26, R12 - BIC $0xfc000000, R2, R2 - ADD R12, R3, R3 - MOVW R3>>26, R12 - BIC $0xfc000000, R3, R3 - ADD R12, R4, R4 - ADD $5, R0, R6 - MOVW R6>>26, R12 - BIC $0xfc000000, R6, R6 - ADD R12, R1, R7 - MOVW R7>>26, R12 - BIC $0xfc000000, R7, R7 - ADD R12, R2, g - MOVW g>>26, R12 - BIC $0xfc000000, g, g - ADD R12, R3, R11 - MOVW $-(1<<26), R12 - ADD R11>>26, R12, R12 - BIC $0xfc000000, R11, R11 - ADD R12, R4, R9 - MOVW R9>>31, R12 - SUB $1, R12 - AND R12, R6, R6 - AND R12, R7, R7 - AND R12, g, g - AND R12, R11, R11 - AND R12, R9, R9 - MVN R12, R12 - AND R12, R0, R0 - AND R12, R1, R1 - AND R12, R2, R2 - AND R12, R3, R3 - AND R12, R4, R4 - ORR R6, R0, R0 - ORR R7, R1, R1 - ORR g, R2, R2 - ORR R11, R3, R3 - ORR R9, R4, R4 - ORR R1<<26, R0, R0 - MOVW R1>>6, R1 - ORR R2<<20, R1, R1 - MOVW R2>>12, R2 - ORR R3<<14, R2, R2 - MOVW R3>>18, R3 - ORR R4<<8, R3, R3 - MOVW 40(R5), R6 - MOVW 44(R5), R7 - MOVW 48(R5), g - MOVW 52(R5), R11 - ADD.S R6, R0, R0 - ADC.S R7, R1, R1 - ADC.S g, R2, R2 - ADC.S R11, R3, R3 - MOVM.IA [R0-R3], (R8) - MOVW R5, R12 - EOR R0, R0, R0 - EOR R1, R1, R1 - EOR R2, R2, R2 - EOR R3, R3, R3 - EOR R4, R4, R4 - EOR R5, R5, R5 - EOR R6, R6, R6 - EOR R7, R7, R7 - MOVM.IA.W [R0-R7], (R12) - MOVM.IA [R0-R7], (R12) - MOVW 4(R13), g - RET diff --git a/vendor/golang.org/x/crypto/poly1305/sum_generic.go b/vendor/golang.org/x/crypto/poly1305/sum_generic.go index bab76ef0d83..c942a65904f 100644 --- a/vendor/golang.org/x/crypto/poly1305/sum_generic.go +++ b/vendor/golang.org/x/crypto/poly1305/sum_generic.go @@ -2,171 +2,309 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +// This file provides the generic implementation of Sum and MAC. Other files +// might provide optimized assembly implementations of some of this code. + package poly1305 import "encoding/binary" -const ( - msgBlock = uint32(1 << 24) - finalBlock = uint32(0) -) +// Poly1305 [RFC 7539] is a relatively simple algorithm: the authentication tag +// for a 64 bytes message is approximately +// +// s + m[0:16] * r⁴ + m[16:32] * r³ + m[32:48] * r² + m[48:64] * r mod 2¹³⁰ - 5 +// +// for some secret r and s. It can be computed sequentially like +// +// for len(msg) > 0: +// h += read(msg, 16) +// h *= r +// h %= 2¹³⁰ - 5 +// return h + s +// +// All the complexity is about doing performant constant-time math on numbers +// larger than any available numeric type. -// sumGeneric generates an authenticator for msg using a one-time key and -// puts the 16-byte result into out. This is the generic implementation of -// Sum and should be called if no assembly implementation is available. func sumGeneric(out *[TagSize]byte, msg []byte, key *[32]byte) { h := newMACGeneric(key) h.Write(msg) h.Sum(out) } -func newMACGeneric(key *[32]byte) (h macGeneric) { - h.r[0] = binary.LittleEndian.Uint32(key[0:]) & 0x3ffffff - h.r[1] = (binary.LittleEndian.Uint32(key[3:]) >> 2) & 0x3ffff03 - h.r[2] = (binary.LittleEndian.Uint32(key[6:]) >> 4) & 0x3ffc0ff - h.r[3] = (binary.LittleEndian.Uint32(key[9:]) >> 6) & 0x3f03fff - h.r[4] = (binary.LittleEndian.Uint32(key[12:]) >> 8) & 0x00fffff - - h.s[0] = binary.LittleEndian.Uint32(key[16:]) - h.s[1] = binary.LittleEndian.Uint32(key[20:]) - h.s[2] = binary.LittleEndian.Uint32(key[24:]) - h.s[3] = binary.LittleEndian.Uint32(key[28:]) - return +func newMACGeneric(key *[32]byte) macGeneric { + m := macGeneric{} + initialize(key, &m.macState) + return m +} + +// macState holds numbers in saturated 64-bit little-endian limbs. That is, +// the value of [x0, x1, x2] is x[0] + x[1] * 2⁶⁴ + x[2] * 2¹²⁸. +type macState struct { + // h is the main accumulator. It is to be interpreted modulo 2¹³⁰ - 5, but + // can grow larger during and after rounds. It must, however, remain below + // 2 * (2¹³⁰ - 5). + h [3]uint64 + // r and s are the private key components. + r [2]uint64 + s [2]uint64 } type macGeneric struct { - h, r [5]uint32 - s [4]uint32 + macState buffer [TagSize]byte offset int } -func (h *macGeneric) Write(p []byte) (n int, err error) { - n = len(p) +// Write splits the incoming message into TagSize chunks, and passes them to +// update. It buffers incomplete chunks. +func (h *macGeneric) Write(p []byte) (int, error) { + nn := len(p) if h.offset > 0 { - remaining := TagSize - h.offset - if n < remaining { - h.offset += copy(h.buffer[h.offset:], p) - return n, nil + n := copy(h.buffer[h.offset:], p) + if h.offset+n < TagSize { + h.offset += n + return nn, nil } - copy(h.buffer[h.offset:], p[:remaining]) - p = p[remaining:] + p = p[n:] h.offset = 0 - updateGeneric(h.buffer[:], msgBlock, &(h.h), &(h.r)) + updateGeneric(&h.macState, h.buffer[:]) } - if nn := len(p) - (len(p) % TagSize); nn > 0 { - updateGeneric(p, msgBlock, &(h.h), &(h.r)) - p = p[nn:] + if n := len(p) - (len(p) % TagSize); n > 0 { + updateGeneric(&h.macState, p[:n]) + p = p[n:] } if len(p) > 0 { h.offset += copy(h.buffer[h.offset:], p) } - return n, nil + return nn, nil } -func (h *macGeneric) Sum(out *[16]byte) { - H, R := h.h, h.r +// Sum flushes the last incomplete chunk from the buffer, if any, and generates +// the MAC output. It does not modify its state, in order to allow for multiple +// calls to Sum, even if no Write is allowed after Sum. +func (h *macGeneric) Sum(out *[TagSize]byte) { + state := h.macState if h.offset > 0 { - var buffer [TagSize]byte - copy(buffer[:], h.buffer[:h.offset]) - buffer[h.offset] = 1 // invariant: h.offset < TagSize - updateGeneric(buffer[:], finalBlock, &H, &R) + updateGeneric(&state, h.buffer[:h.offset]) } - finalizeGeneric(out, &H, &(h.s)) + finalize(out, &state.h, &state.s) +} + +// [rMask0, rMask1] is the specified Poly1305 clamping mask in little-endian. It +// clears some bits of the secret coefficient to make it possible to implement +// multiplication more efficiently. +const ( + rMask0 = 0x0FFFFFFC0FFFFFFF + rMask1 = 0x0FFFFFFC0FFFFFFC +) + +// initialize loads the 256-bit key into the two 128-bit secret values r and s. +func initialize(key *[32]byte, m *macState) { + m.r[0] = binary.LittleEndian.Uint64(key[0:8]) & rMask0 + m.r[1] = binary.LittleEndian.Uint64(key[8:16]) & rMask1 + m.s[0] = binary.LittleEndian.Uint64(key[16:24]) + m.s[1] = binary.LittleEndian.Uint64(key[24:32]) +} + +// uint128 holds a 128-bit number as two 64-bit limbs, for use with the +// bits.Mul64 and bits.Add64 intrinsics. +type uint128 struct { + lo, hi uint64 +} + +func mul64(a, b uint64) uint128 { + hi, lo := bitsMul64(a, b) + return uint128{lo, hi} } -func updateGeneric(msg []byte, flag uint32, h, r *[5]uint32) { - h0, h1, h2, h3, h4 := h[0], h[1], h[2], h[3], h[4] - r0, r1, r2, r3, r4 := uint64(r[0]), uint64(r[1]), uint64(r[2]), uint64(r[3]), uint64(r[4]) - R1, R2, R3, R4 := r1*5, r2*5, r3*5, r4*5 - - for len(msg) >= TagSize { - // h += msg - h0 += binary.LittleEndian.Uint32(msg[0:]) & 0x3ffffff - h1 += (binary.LittleEndian.Uint32(msg[3:]) >> 2) & 0x3ffffff - h2 += (binary.LittleEndian.Uint32(msg[6:]) >> 4) & 0x3ffffff - h3 += (binary.LittleEndian.Uint32(msg[9:]) >> 6) & 0x3ffffff - h4 += (binary.LittleEndian.Uint32(msg[12:]) >> 8) | flag - - // h *= r - d0 := (uint64(h0) * r0) + (uint64(h1) * R4) + (uint64(h2) * R3) + (uint64(h3) * R2) + (uint64(h4) * R1) - d1 := (d0 >> 26) + (uint64(h0) * r1) + (uint64(h1) * r0) + (uint64(h2) * R4) + (uint64(h3) * R3) + (uint64(h4) * R2) - d2 := (d1 >> 26) + (uint64(h0) * r2) + (uint64(h1) * r1) + (uint64(h2) * r0) + (uint64(h3) * R4) + (uint64(h4) * R3) - d3 := (d2 >> 26) + (uint64(h0) * r3) + (uint64(h1) * r2) + (uint64(h2) * r1) + (uint64(h3) * r0) + (uint64(h4) * R4) - d4 := (d3 >> 26) + (uint64(h0) * r4) + (uint64(h1) * r3) + (uint64(h2) * r2) + (uint64(h3) * r1) + (uint64(h4) * r0) - - // h %= p - h0 = uint32(d0) & 0x3ffffff - h1 = uint32(d1) & 0x3ffffff - h2 = uint32(d2) & 0x3ffffff - h3 = uint32(d3) & 0x3ffffff - h4 = uint32(d4) & 0x3ffffff - - h0 += uint32(d4>>26) * 5 - h1 += h0 >> 26 - h0 = h0 & 0x3ffffff - - msg = msg[TagSize:] +func add128(a, b uint128) uint128 { + lo, c := bitsAdd64(a.lo, b.lo, 0) + hi, c := bitsAdd64(a.hi, b.hi, c) + if c != 0 { + panic("poly1305: unexpected overflow") } + return uint128{lo, hi} +} - h[0], h[1], h[2], h[3], h[4] = h0, h1, h2, h3, h4 +func shiftRightBy2(a uint128) uint128 { + a.lo = a.lo>>2 | (a.hi&3)<<62 + a.hi = a.hi >> 2 + return a } -func finalizeGeneric(out *[TagSize]byte, h *[5]uint32, s *[4]uint32) { - h0, h1, h2, h3, h4 := h[0], h[1], h[2], h[3], h[4] - - // h %= p reduction - h2 += h1 >> 26 - h1 &= 0x3ffffff - h3 += h2 >> 26 - h2 &= 0x3ffffff - h4 += h3 >> 26 - h3 &= 0x3ffffff - h0 += 5 * (h4 >> 26) - h4 &= 0x3ffffff - h1 += h0 >> 26 - h0 &= 0x3ffffff - - // h - p - t0 := h0 + 5 - t1 := h1 + (t0 >> 26) - t2 := h2 + (t1 >> 26) - t3 := h3 + (t2 >> 26) - t4 := h4 + (t3 >> 26) - (1 << 26) - t0 &= 0x3ffffff - t1 &= 0x3ffffff - t2 &= 0x3ffffff - t3 &= 0x3ffffff - - // select h if h < p else h - p - t_mask := (t4 >> 31) - 1 - h_mask := ^t_mask - h0 = (h0 & h_mask) | (t0 & t_mask) - h1 = (h1 & h_mask) | (t1 & t_mask) - h2 = (h2 & h_mask) | (t2 & t_mask) - h3 = (h3 & h_mask) | (t3 & t_mask) - h4 = (h4 & h_mask) | (t4 & t_mask) - - // h %= 2^128 - h0 |= h1 << 26 - h1 = ((h1 >> 6) | (h2 << 20)) - h2 = ((h2 >> 12) | (h3 << 14)) - h3 = ((h3 >> 18) | (h4 << 8)) - - // s: the s part of the key - // tag = (h + s) % (2^128) - t := uint64(h0) + uint64(s[0]) - h0 = uint32(t) - t = uint64(h1) + uint64(s[1]) + (t >> 32) - h1 = uint32(t) - t = uint64(h2) + uint64(s[2]) + (t >> 32) - h2 = uint32(t) - t = uint64(h3) + uint64(s[3]) + (t >> 32) - h3 = uint32(t) - - binary.LittleEndian.PutUint32(out[0:], h0) - binary.LittleEndian.PutUint32(out[4:], h1) - binary.LittleEndian.PutUint32(out[8:], h2) - binary.LittleEndian.PutUint32(out[12:], h3) +// updateGeneric absorbs msg into the state.h accumulator. For each chunk m of +// 128 bits of message, it computes +// +// h₊ = (h + m) * r mod 2¹³⁰ - 5 +// +// If the msg length is not a multiple of TagSize, it assumes the last +// incomplete chunk is the final one. +func updateGeneric(state *macState, msg []byte) { + h0, h1, h2 := state.h[0], state.h[1], state.h[2] + r0, r1 := state.r[0], state.r[1] + + for len(msg) > 0 { + var c uint64 + + // For the first step, h + m, we use a chain of bits.Add64 intrinsics. + // The resulting value of h might exceed 2¹³⁰ - 5, but will be partially + // reduced at the end of the multiplication below. + // + // The spec requires us to set a bit just above the message size, not to + // hide leading zeroes. For full chunks, that's 1 << 128, so we can just + // add 1 to the most significant (2¹²⁸) limb, h2. + if len(msg) >= TagSize { + h0, c = bitsAdd64(h0, binary.LittleEndian.Uint64(msg[0:8]), 0) + h1, c = bitsAdd64(h1, binary.LittleEndian.Uint64(msg[8:16]), c) + h2 += c + 1 + + msg = msg[TagSize:] + } else { + var buf [TagSize]byte + copy(buf[:], msg) + buf[len(msg)] = 1 + + h0, c = bitsAdd64(h0, binary.LittleEndian.Uint64(buf[0:8]), 0) + h1, c = bitsAdd64(h1, binary.LittleEndian.Uint64(buf[8:16]), c) + h2 += c + + msg = nil + } + + // Multiplication of big number limbs is similar to elementary school + // columnar multiplication. Instead of digits, there are 64-bit limbs. + // + // We are multiplying a 3 limbs number, h, by a 2 limbs number, r. + // + // h2 h1 h0 x + // r1 r0 = + // ---------------- + // h2r0 h1r0 h0r0 <-- individual 128-bit products + // + h2r1 h1r1 h0r1 + // ------------------------ + // m3 m2 m1 m0 <-- result in 128-bit overlapping limbs + // ------------------------ + // m3.hi m2.hi m1.hi m0.hi <-- carry propagation + // + m3.lo m2.lo m1.lo m0.lo + // ------------------------------- + // t4 t3 t2 t1 t0 <-- final result in 64-bit limbs + // + // The main difference from pen-and-paper multiplication is that we do + // carry propagation in a separate step, as if we wrote two digit sums + // at first (the 128-bit limbs), and then carried the tens all at once. + + h0r0 := mul64(h0, r0) + h1r0 := mul64(h1, r0) + h2r0 := mul64(h2, r0) + h0r1 := mul64(h0, r1) + h1r1 := mul64(h1, r1) + h2r1 := mul64(h2, r1) + + // Since h2 is known to be at most 7 (5 + 1 + 1), and r0 and r1 have their + // top 4 bits cleared by rMask{0,1}, we know that their product is not going + // to overflow 64 bits, so we can ignore the high part of the products. + // + // This also means that the product doesn't have a fifth limb (t4). + if h2r0.hi != 0 { + panic("poly1305: unexpected overflow") + } + if h2r1.hi != 0 { + panic("poly1305: unexpected overflow") + } + + m0 := h0r0 + m1 := add128(h1r0, h0r1) // These two additions don't overflow thanks again + m2 := add128(h2r0, h1r1) // to the 4 masked bits at the top of r0 and r1. + m3 := h2r1 + + t0 := m0.lo + t1, c := bitsAdd64(m1.lo, m0.hi, 0) + t2, c := bitsAdd64(m2.lo, m1.hi, c) + t3, _ := bitsAdd64(m3.lo, m2.hi, c) + + // Now we have the result as 4 64-bit limbs, and we need to reduce it + // modulo 2¹³⁰ - 5. The special shape of this Crandall prime lets us do + // a cheap partial reduction according to the reduction identity + // + // c * 2¹³⁰ + n = c * 5 + n mod 2¹³⁰ - 5 + // + // because 2¹³⁰ = 5 mod 2¹³⁰ - 5. Partial reduction since the result is + // likely to be larger than 2¹³⁰ - 5, but still small enough to fit the + // assumptions we make about h in the rest of the code. + // + // See also https://speakerdeck.com/gtank/engineering-prime-numbers?slide=23 + + // We split the final result at the 2¹³⁰ mark into h and cc, the carry. + // Note that the carry bits are effectively shifted left by 2, in other + // words, cc = c * 4 for the c in the reduction identity. + h0, h1, h2 = t0, t1, t2&maskLow2Bits + cc := uint128{t2 & maskNotLow2Bits, t3} + + // To add c * 5 to h, we first add cc = c * 4, and then add (cc >> 2) = c. + + h0, c = bitsAdd64(h0, cc.lo, 0) + h1, c = bitsAdd64(h1, cc.hi, c) + h2 += c + + cc = shiftRightBy2(cc) + + h0, c = bitsAdd64(h0, cc.lo, 0) + h1, c = bitsAdd64(h1, cc.hi, c) + h2 += c + + // h2 is at most 3 + 1 + 1 = 5, making the whole of h at most + // + // 5 * 2¹²⁸ + (2¹²⁸ - 1) = 6 * 2¹²⁸ - 1 + } + + state.h[0], state.h[1], state.h[2] = h0, h1, h2 +} + +const ( + maskLow2Bits uint64 = 0x0000000000000003 + maskNotLow2Bits uint64 = ^maskLow2Bits +) + +// select64 returns x if v == 1 and y if v == 0, in constant time. +func select64(v, x, y uint64) uint64 { return ^(v-1)&x | (v-1)&y } + +// [p0, p1, p2] is 2¹³⁰ - 5 in little endian order. +const ( + p0 = 0xFFFFFFFFFFFFFFFB + p1 = 0xFFFFFFFFFFFFFFFF + p2 = 0x0000000000000003 +) + +// finalize completes the modular reduction of h and computes +// +// out = h + s mod 2¹²⁸ +// +func finalize(out *[TagSize]byte, h *[3]uint64, s *[2]uint64) { + h0, h1, h2 := h[0], h[1], h[2] + + // After the partial reduction in updateGeneric, h might be more than + // 2¹³⁰ - 5, but will be less than 2 * (2¹³⁰ - 5). To complete the reduction + // in constant time, we compute t = h - (2¹³⁰ - 5), and select h as the + // result if the subtraction underflows, and t otherwise. + + hMinusP0, b := bitsSub64(h0, p0, 0) + hMinusP1, b := bitsSub64(h1, p1, b) + _, b = bitsSub64(h2, p2, b) + + // h = h if h < p else h - p + h0 = select64(b, h0, hMinusP0) + h1 = select64(b, h1, hMinusP1) + + // Finally, we compute the last Poly1305 step + // + // tag = h + s mod 2¹²⁸ + // + // by just doing a wide addition with the 128 low bits of h and discarding + // the overflow. + h0, c := bitsAdd64(h0, s[0], 0) + h1, _ = bitsAdd64(h1, s[1], c) + + binary.LittleEndian.PutUint64(out[0:8], h0) + binary.LittleEndian.PutUint64(out[8:16], h1) } diff --git a/vendor/golang.org/x/crypto/poly1305/sum_noasm.go b/vendor/golang.org/x/crypto/poly1305/sum_noasm.go deleted file mode 100644 index 8a9c2070b9f..00000000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_noasm.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build s390x,!go1.11 !arm,!amd64,!s390x,!ppc64le gccgo appengine nacl - -package poly1305 - -// Sum generates an authenticator for msg using a one-time key and puts the -// 16-byte result into out. Authenticating two different messages with the same -// key allows an attacker to forge messages at will. -func Sum(out *[TagSize]byte, msg []byte, key *[32]byte) { - h := newMAC(key) - h.Write(msg) - h.Sum(out) -} diff --git a/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.go b/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.go index 2402b6371bf..2e7a120b192 100644 --- a/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.go +++ b/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.go @@ -2,67 +2,46 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build ppc64le,!gccgo,!appengine +// +build !gccgo,!purego package poly1305 //go:noescape -func initialize(state *[7]uint64, key *[32]byte) +func update(state *macState, msg []byte) -//go:noescape -func update(state *[7]uint64, msg []byte) - -//go:noescape -func finalize(tag *[TagSize]byte, state *[7]uint64) - -// Sum generates an authenticator for m using a one-time key and puts the -// 16-byte result into out. Authenticating two different messages with the same -// key allows an attacker to forge messages at will. -func Sum(out *[16]byte, m []byte, key *[32]byte) { - h := newMAC(key) - h.Write(m) - h.Sum(out) -} - -func newMAC(key *[32]byte) (h mac) { - initialize(&h.state, key) - return -} - -type mac struct { - state [7]uint64 // := uint64{ h0, h1, h2, r0, r1, pad0, pad1 } - - buffer [TagSize]byte - offset int -} +// mac is a wrapper for macGeneric that redirects calls that would have gone to +// updateGeneric to update. +// +// Its Write and Sum methods are otherwise identical to the macGeneric ones, but +// using function pointers would carry a major performance cost. +type mac struct{ macGeneric } -func (h *mac) Write(p []byte) (n int, err error) { - n = len(p) +func (h *mac) Write(p []byte) (int, error) { + nn := len(p) if h.offset > 0 { - remaining := TagSize - h.offset - if n < remaining { - h.offset += copy(h.buffer[h.offset:], p) - return n, nil + n := copy(h.buffer[h.offset:], p) + if h.offset+n < TagSize { + h.offset += n + return nn, nil } - copy(h.buffer[h.offset:], p[:remaining]) - p = p[remaining:] + p = p[n:] h.offset = 0 - update(&h.state, h.buffer[:]) + update(&h.macState, h.buffer[:]) } - if nn := len(p) - (len(p) % TagSize); nn > 0 { - update(&h.state, p[:nn]) - p = p[nn:] + if n := len(p) - (len(p) % TagSize); n > 0 { + update(&h.macState, p[:n]) + p = p[n:] } if len(p) > 0 { h.offset += copy(h.buffer[h.offset:], p) } - return n, nil + return nn, nil } func (h *mac) Sum(out *[16]byte) { - state := h.state + state := h.macState if h.offset > 0 { update(&state, h.buffer[:h.offset]) } - finalize(out, &state) + finalize(out, &state.h, &state.s) } diff --git a/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.s b/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.s index 55c7167ec98..4e028138796 100644 --- a/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.s +++ b/vendor/golang.org/x/crypto/poly1305/sum_ppc64le.s @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build ppc64le,!gccgo,!appengine +// +build !gccgo,!purego #include "textflag.h" @@ -58,7 +58,6 @@ DATA ·poly1305Mask<>+0x08(SB)/8, $0x0FFFFFFC0FFFFFFC GLOBL ·poly1305Mask<>(SB), RODATA, $16 // func update(state *[7]uint64, msg []byte) - TEXT ·update(SB), $0-32 MOVD state+0(FP), R3 MOVD msg_base+8(FP), R4 @@ -180,68 +179,3 @@ done: MOVD R9, 8(R3) MOVD R10, 16(R3) RET - -// func initialize(state *[7]uint64, key *[32]byte) -TEXT ·initialize(SB), $0-16 - MOVD state+0(FP), R3 - MOVD key+8(FP), R4 - - // state[0...7] is initialized with zero - // Load key - MOVD 0(R4), R5 - MOVD 8(R4), R6 - MOVD 16(R4), R7 - MOVD 24(R4), R8 - - // Address of key mask - MOVD $·poly1305Mask<>(SB), R9 - - // Save original key in state - MOVD R7, 40(R3) - MOVD R8, 48(R3) - - // Get mask - MOVD (R9), R7 - MOVD 8(R9), R8 - - // And with key - AND R5, R7, R5 - AND R6, R8, R6 - - // Save masked key in state - MOVD R5, 24(R3) - MOVD R6, 32(R3) - RET - -// func finalize(tag *[TagSize]byte, state *[7]uint64) -TEXT ·finalize(SB), $0-16 - MOVD tag+0(FP), R3 - MOVD state+8(FP), R4 - - // Get h0, h1, h2 from state - MOVD 0(R4), R5 - MOVD 8(R4), R6 - MOVD 16(R4), R7 - - // Save h0, h1 - MOVD R5, R8 - MOVD R6, R9 - MOVD $3, R20 - MOVD $-1, R21 - SUBC $-5, R5 - SUBE R21, R6 - SUBE R20, R7 - MOVD $0, R21 - SUBZE R21 - - // Check for carry - CMP $0, R21 - ISEL $2, R5, R8, R5 - ISEL $2, R6, R9, R6 - MOVD 40(R4), R8 - MOVD 48(R4), R9 - ADDC R8, R5 - ADDE R9, R6 - MOVD R5, 0(R3) - MOVD R6, 8(R3) - RET diff --git a/vendor/golang.org/x/crypto/poly1305/sum_s390x.go b/vendor/golang.org/x/crypto/poly1305/sum_s390x.go index ec99e07e9fb..958fedc0790 100644 --- a/vendor/golang.org/x/crypto/poly1305/sum_s390x.go +++ b/vendor/golang.org/x/crypto/poly1305/sum_s390x.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build s390x,go1.11,!gccgo,!appengine +// +build !gccgo,!purego package poly1305 @@ -10,33 +10,66 @@ import ( "golang.org/x/sys/cpu" ) -// poly1305vx is an assembly implementation of Poly1305 that uses vector +// updateVX is an assembly implementation of Poly1305 that uses vector // instructions. It must only be called if the vector facility (vx) is // available. //go:noescape -func poly1305vx(out *[16]byte, m *byte, mlen uint64, key *[32]byte) +func updateVX(state *macState, msg []byte) -// poly1305vmsl is an assembly implementation of Poly1305 that uses vector -// instructions, including VMSL. It must only be called if the vector facility (vx) is -// available and if VMSL is supported. -//go:noescape -func poly1305vmsl(out *[16]byte, m *byte, mlen uint64, key *[32]byte) - -// Sum generates an authenticator for m using a one-time key and puts the -// 16-byte result into out. Authenticating two different messages with the same -// key allows an attacker to forge messages at will. -func Sum(out *[16]byte, m []byte, key *[32]byte) { - if cpu.S390X.HasVX { - var mPtr *byte - if len(m) > 0 { - mPtr = &m[0] +// mac is a replacement for macGeneric that uses a larger buffer and redirects +// calls that would have gone to updateGeneric to updateVX if the vector +// facility is installed. +// +// A larger buffer is required for good performance because the vector +// implementation has a higher fixed cost per call than the generic +// implementation. +type mac struct { + macState + + buffer [16 * TagSize]byte // size must be a multiple of block size (16) + offset int +} + +func (h *mac) Write(p []byte) (int, error) { + nn := len(p) + if h.offset > 0 { + n := copy(h.buffer[h.offset:], p) + if h.offset+n < len(h.buffer) { + h.offset += n + return nn, nil + } + p = p[n:] + h.offset = 0 + if cpu.S390X.HasVX { + updateVX(&h.macState, h.buffer[:]) + } else { + updateGeneric(&h.macState, h.buffer[:]) } - if cpu.S390X.HasVXE && len(m) > 256 { - poly1305vmsl(out, mPtr, uint64(len(m)), key) + } + + tail := len(p) % len(h.buffer) // number of bytes to copy into buffer + body := len(p) - tail // number of bytes to process now + if body > 0 { + if cpu.S390X.HasVX { + updateVX(&h.macState, p[:body]) } else { - poly1305vx(out, mPtr, uint64(len(m)), key) + updateGeneric(&h.macState, p[:body]) } - } else { - sumGeneric(out, m, key) } + h.offset = copy(h.buffer[:], p[body:]) // copy tail bytes - can be 0 + return nn, nil +} + +func (h *mac) Sum(out *[TagSize]byte) { + state := h.macState + remainder := h.buffer[:h.offset] + + // Use the generic implementation if we have 2 or fewer blocks left + // to sum. The vector implementation has a higher startup time. + if cpu.S390X.HasVX && len(remainder) > 2*TagSize { + updateVX(&state, remainder) + } else if len(remainder) > 0 { + updateGeneric(&state, remainder) + } + finalize(out, &state.h, &state.s) } diff --git a/vendor/golang.org/x/crypto/poly1305/sum_s390x.s b/vendor/golang.org/x/crypto/poly1305/sum_s390x.s index ca5a309d867..0fa9ee6e0bf 100644 --- a/vendor/golang.org/x/crypto/poly1305/sum_s390x.s +++ b/vendor/golang.org/x/crypto/poly1305/sum_s390x.s @@ -2,115 +2,187 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build s390x,go1.11,!gccgo,!appengine +// +build !gccgo,!purego #include "textflag.h" -// Implementation of Poly1305 using the vector facility (vx). - -// constants -#define MOD26 V0 -#define EX0 V1 -#define EX1 V2 -#define EX2 V3 - -// temporaries -#define T_0 V4 -#define T_1 V5 -#define T_2 V6 -#define T_3 V7 -#define T_4 V8 - -// key (r) -#define R_0 V9 -#define R_1 V10 -#define R_2 V11 -#define R_3 V12 -#define R_4 V13 -#define R5_1 V14 -#define R5_2 V15 -#define R5_3 V16 -#define R5_4 V17 -#define RSAVE_0 R5 -#define RSAVE_1 R6 -#define RSAVE_2 R7 -#define RSAVE_3 R8 -#define RSAVE_4 R9 -#define R5SAVE_1 V28 -#define R5SAVE_2 V29 -#define R5SAVE_3 V30 -#define R5SAVE_4 V31 - -// message block -#define F_0 V18 -#define F_1 V19 -#define F_2 V20 -#define F_3 V21 -#define F_4 V22 - -// accumulator -#define H_0 V23 -#define H_1 V24 -#define H_2 V25 -#define H_3 V26 -#define H_4 V27 - -GLOBL ·keyMask<>(SB), RODATA, $16 -DATA ·keyMask<>+0(SB)/8, $0xffffff0ffcffff0f -DATA ·keyMask<>+8(SB)/8, $0xfcffff0ffcffff0f - -GLOBL ·bswapMask<>(SB), RODATA, $16 -DATA ·bswapMask<>+0(SB)/8, $0x0f0e0d0c0b0a0908 -DATA ·bswapMask<>+8(SB)/8, $0x0706050403020100 - -GLOBL ·constants<>(SB), RODATA, $64 -// MOD26 -DATA ·constants<>+0(SB)/8, $0x3ffffff -DATA ·constants<>+8(SB)/8, $0x3ffffff +// This implementation of Poly1305 uses the vector facility (vx) +// to process up to 2 blocks (32 bytes) per iteration using an +// algorithm based on the one described in: +// +// NEON crypto, Daniel J. Bernstein & Peter Schwabe +// https://cryptojedi.org/papers/neoncrypto-20120320.pdf +// +// This algorithm uses 5 26-bit limbs to represent a 130-bit +// value. These limbs are, for the most part, zero extended and +// placed into 64-bit vector register elements. Each vector +// register is 128-bits wide and so holds 2 of these elements. +// Using 26-bit limbs allows us plenty of headroom to accomodate +// accumulations before and after multiplication without +// overflowing either 32-bits (before multiplication) or 64-bits +// (after multiplication). +// +// In order to parallelise the operations required to calculate +// the sum we use two separate accumulators and then sum those +// in an extra final step. For compatibility with the generic +// implementation we perform this summation at the end of every +// updateVX call. +// +// To use two accumulators we must multiply the message blocks +// by r² rather than r. Only the final message block should be +// multiplied by r. +// +// Example: +// +// We want to calculate the sum (h) for a 64 byte message (m): +// +// h = m[0:16]r⁴ + m[16:32]r³ + m[32:48]r² + m[48:64]r +// +// To do this we split the calculation into the even indices +// and odd indices of the message. These form our SIMD 'lanes': +// +// h = m[ 0:16]r⁴ + m[32:48]r² + <- lane 0 +// m[16:32]r³ + m[48:64]r <- lane 1 +// +// To calculate this iteratively we refactor so that both lanes +// are written in terms of r² and r: +// +// h = (m[ 0:16]r² + m[32:48])r² + <- lane 0 +// (m[16:32]r² + m[48:64])r <- lane 1 +// ^ ^ +// | coefficients for second iteration +// coefficients for first iteration +// +// So in this case we would have two iterations. In the first +// both lanes are multiplied by r². In the second only the +// first lane is multiplied by r² and the second lane is +// instead multiplied by r. This gives use the odd and even +// powers of r that we need from the original equation. +// +// Notation: +// +// h - accumulator +// r - key +// m - message +// +// [a, b] - SIMD register holding two 64-bit values +// [a, b, c, d] - SIMD register holding four 32-bit values +// xᵢ[n] - limb n of variable x with bit width i +// +// Limbs are expressed in little endian order, so for 26-bit +// limbs x₂₆[4] will be the most significant limb and x₂₆[0] +// will be the least significant limb. + +// masking constants +#define MOD24 V0 // [0x0000000000ffffff, 0x0000000000ffffff] - mask low 24-bits +#define MOD26 V1 // [0x0000000003ffffff, 0x0000000003ffffff] - mask low 26-bits + +// expansion constants (see EXPAND macro) +#define EX0 V2 +#define EX1 V3 +#define EX2 V4 + +// key (r², r or 1 depending on context) +#define R_0 V5 +#define R_1 V6 +#define R_2 V7 +#define R_3 V8 +#define R_4 V9 + +// precalculated coefficients (5r², 5r or 0 depending on context) +#define R5_1 V10 +#define R5_2 V11 +#define R5_3 V12 +#define R5_4 V13 + +// message block (m) +#define M_0 V14 +#define M_1 V15 +#define M_2 V16 +#define M_3 V17 +#define M_4 V18 + +// accumulator (h) +#define H_0 V19 +#define H_1 V20 +#define H_2 V21 +#define H_3 V22 +#define H_4 V23 + +// temporary registers (for short-lived values) +#define T_0 V24 +#define T_1 V25 +#define T_2 V26 +#define T_3 V27 +#define T_4 V28 + +GLOBL ·constants<>(SB), RODATA, $0x30 // EX0 -DATA ·constants<>+16(SB)/8, $0x0006050403020100 -DATA ·constants<>+24(SB)/8, $0x1016151413121110 +DATA ·constants<>+0x00(SB)/8, $0x0006050403020100 +DATA ·constants<>+0x08(SB)/8, $0x1016151413121110 // EX1 -DATA ·constants<>+32(SB)/8, $0x060c0b0a09080706 -DATA ·constants<>+40(SB)/8, $0x161c1b1a19181716 +DATA ·constants<>+0x10(SB)/8, $0x060c0b0a09080706 +DATA ·constants<>+0x18(SB)/8, $0x161c1b1a19181716 // EX2 -DATA ·constants<>+48(SB)/8, $0x0d0d0d0d0d0f0e0d -DATA ·constants<>+56(SB)/8, $0x1d1d1d1d1d1f1e1d - -// h = (f*g) % (2**130-5) [partial reduction] +DATA ·constants<>+0x20(SB)/8, $0x0d0d0d0d0d0f0e0d +DATA ·constants<>+0x28(SB)/8, $0x1d1d1d1d1d1f1e1d + +// MULTIPLY multiplies each lane of f and g, partially reduced +// modulo 2¹³⁰ - 5. The result, h, consists of partial products +// in each lane that need to be reduced further to produce the +// final result. +// +// h₁₃₀ = (f₁₃₀g₁₃₀) % 2¹³⁰ + (5f₁₃₀g₁₃₀) / 2¹³⁰ +// +// Note that the multiplication by 5 of the high bits is +// achieved by precalculating the multiplication of four of the +// g coefficients by 5. These are g51-g54. #define MULTIPLY(f0, f1, f2, f3, f4, g0, g1, g2, g3, g4, g51, g52, g53, g54, h0, h1, h2, h3, h4) \ VMLOF f0, g0, h0 \ - VMLOF f0, g1, h1 \ - VMLOF f0, g2, h2 \ VMLOF f0, g3, h3 \ + VMLOF f0, g1, h1 \ VMLOF f0, g4, h4 \ + VMLOF f0, g2, h2 \ VMLOF f1, g54, T_0 \ - VMLOF f1, g0, T_1 \ - VMLOF f1, g1, T_2 \ VMLOF f1, g2, T_3 \ + VMLOF f1, g0, T_1 \ VMLOF f1, g3, T_4 \ + VMLOF f1, g1, T_2 \ VMALOF f2, g53, h0, h0 \ - VMALOF f2, g54, h1, h1 \ - VMALOF f2, g0, h2, h2 \ VMALOF f2, g1, h3, h3 \ + VMALOF f2, g54, h1, h1 \ VMALOF f2, g2, h4, h4 \ + VMALOF f2, g0, h2, h2 \ VMALOF f3, g52, T_0, T_0 \ - VMALOF f3, g53, T_1, T_1 \ - VMALOF f3, g54, T_2, T_2 \ VMALOF f3, g0, T_3, T_3 \ + VMALOF f3, g53, T_1, T_1 \ VMALOF f3, g1, T_4, T_4 \ + VMALOF f3, g54, T_2, T_2 \ VMALOF f4, g51, h0, h0 \ - VMALOF f4, g52, h1, h1 \ - VMALOF f4, g53, h2, h2 \ VMALOF f4, g54, h3, h3 \ + VMALOF f4, g52, h1, h1 \ VMALOF f4, g0, h4, h4 \ + VMALOF f4, g53, h2, h2 \ VAG T_0, h0, h0 \ - VAG T_1, h1, h1 \ - VAG T_2, h2, h2 \ VAG T_3, h3, h3 \ - VAG T_4, h4, h4 - -// carry h0->h1 h3->h4, h1->h2 h4->h0, h0->h1 h2->h3, h3->h4 + VAG T_1, h1, h1 \ + VAG T_4, h4, h4 \ + VAG T_2, h2, h2 + +// REDUCE performs the following carry operations in four +// stages, as specified in Bernstein & Schwabe: +// +// 1: h₂₆[0]->h₂₆[1] h₂₆[3]->h₂₆[4] +// 2: h₂₆[1]->h₂₆[2] h₂₆[4]->h₂₆[0] +// 3: h₂₆[0]->h₂₆[1] h₂₆[2]->h₂₆[3] +// 4: h₂₆[3]->h₂₆[4] +// +// The result is that all of the limbs are limited to 26-bits +// except for h₂₆[1] and h₂₆[4] which are limited to 27-bits. +// +// Note that although each limb is aligned at 26-bit intervals +// they may contain values that exceed 2²⁶ - 1, hence the need +// to carry the excess bits in each limb. #define REDUCE(h0, h1, h2, h3, h4) \ VESRLG $26, h0, T_0 \ VESRLG $26, h3, T_1 \ @@ -136,144 +208,155 @@ DATA ·constants<>+56(SB)/8, $0x1d1d1d1d1d1f1e1d VN MOD26, h3, h3 \ VAG T_2, h4, h4 -// expand in0 into d[0] and in1 into d[1] +// EXPAND splits the 128-bit little-endian values in0 and in1 +// into 26-bit big-endian limbs and places the results into +// the first and second lane of d₂₆[0:4] respectively. +// +// The EX0, EX1 and EX2 constants are arrays of byte indices +// for permutation. The permutation both reverses the bytes +// in the input and ensures the bytes are copied into the +// destination limb ready to be shifted into their final +// position. #define EXPAND(in0, in1, d0, d1, d2, d3, d4) \ - VGBM $0x0707, d1 \ // d1=tmp - VPERM in0, in1, EX2, d4 \ VPERM in0, in1, EX0, d0 \ VPERM in0, in1, EX1, d2 \ - VN d1, d4, d4 \ + VPERM in0, in1, EX2, d4 \ VESRLG $26, d0, d1 \ VESRLG $30, d2, d3 \ VESRLG $4, d2, d2 \ - VN MOD26, d0, d0 \ - VN MOD26, d1, d1 \ - VN MOD26, d2, d2 \ - VN MOD26, d3, d3 - -// pack h4:h0 into h1:h0 (no carry) -#define PACK(h0, h1, h2, h3, h4) \ - VESLG $26, h1, h1 \ - VESLG $26, h3, h3 \ - VO h0, h1, h0 \ - VO h2, h3, h2 \ - VESLG $4, h2, h2 \ - VLEIB $7, $48, h1 \ - VSLB h1, h2, h2 \ - VO h0, h2, h0 \ - VLEIB $7, $104, h1 \ - VSLB h1, h4, h3 \ - VO h3, h0, h0 \ - VLEIB $7, $24, h1 \ - VSRLB h1, h4, h1 - -// if h > 2**130-5 then h -= 2**130-5 -#define MOD(h0, h1, t0, t1, t2) \ - VZERO t0 \ - VLEIG $1, $5, t0 \ - VACCQ h0, t0, t1 \ - VAQ h0, t0, t0 \ - VONE t2 \ - VLEIG $1, $-4, t2 \ - VAQ t2, t1, t1 \ - VACCQ h1, t1, t1 \ - VONE t2 \ - VAQ t2, t1, t1 \ - VN h0, t1, t2 \ - VNC t0, t1, t1 \ - VO t1, t2, h0 - -// func poly1305vx(out *[16]byte, m *byte, mlen uint64, key *[32]key) -TEXT ·poly1305vx(SB), $0-32 - // This code processes up to 2 blocks (32 bytes) per iteration - // using the algorithm described in: - // NEON crypto, Daniel J. Bernstein & Peter Schwabe - // https://cryptojedi.org/papers/neoncrypto-20120320.pdf - LMG out+0(FP), R1, R4 // R1=out, R2=m, R3=mlen, R4=key - - // load MOD26, EX0, EX1 and EX2 + VN MOD26, d0, d0 \ // [in0₂₆[0], in1₂₆[0]] + VN MOD26, d3, d3 \ // [in0₂₆[3], in1₂₆[3]] + VN MOD26, d1, d1 \ // [in0₂₆[1], in1₂₆[1]] + VN MOD24, d4, d4 \ // [in0₂₆[4], in1₂₆[4]] + VN MOD26, d2, d2 // [in0₂₆[2], in1₂₆[2]] + +// func updateVX(state *macState, msg []byte) +TEXT ·updateVX(SB), NOSPLIT, $0 + MOVD state+0(FP), R1 + LMG msg+8(FP), R2, R3 // R2=msg_base, R3=msg_len + + // load EX0, EX1 and EX2 MOVD $·constants<>(SB), R5 - VLM (R5), MOD26, EX2 - - // setup r - VL (R4), T_0 - MOVD $·keyMask<>(SB), R6 - VL (R6), T_1 - VN T_0, T_1, T_0 - EXPAND(T_0, T_0, R_0, R_1, R_2, R_3, R_4) - - // setup r*5 - VLEIG $0, $5, T_0 - VLEIG $1, $5, T_0 - - // store r (for final block) - VMLOF T_0, R_1, R5SAVE_1 - VMLOF T_0, R_2, R5SAVE_2 - VMLOF T_0, R_3, R5SAVE_3 - VMLOF T_0, R_4, R5SAVE_4 - VLGVG $0, R_0, RSAVE_0 - VLGVG $0, R_1, RSAVE_1 - VLGVG $0, R_2, RSAVE_2 - VLGVG $0, R_3, RSAVE_3 - VLGVG $0, R_4, RSAVE_4 - - // skip r**2 calculation + VLM (R5), EX0, EX2 + + // generate masks + VGMG $(64-24), $63, MOD24 // [0x00ffffff, 0x00ffffff] + VGMG $(64-26), $63, MOD26 // [0x03ffffff, 0x03ffffff] + + // load h (accumulator) and r (key) from state + VZERO T_1 // [0, 0] + VL 0(R1), T_0 // [h₆₄[0], h₆₄[1]] + VLEG $0, 16(R1), T_1 // [h₆₄[2], 0] + VL 24(R1), T_2 // [r₆₄[0], r₆₄[1]] + VPDI $0, T_0, T_2, T_3 // [h₆₄[0], r₆₄[0]] + VPDI $5, T_0, T_2, T_4 // [h₆₄[1], r₆₄[1]] + + // unpack h and r into 26-bit limbs + // note: h₆₄[2] may have the low 3 bits set, so h₂₆[4] is a 27-bit value + VN MOD26, T_3, H_0 // [h₂₆[0], r₂₆[0]] + VZERO H_1 // [0, 0] + VZERO H_3 // [0, 0] + VGMG $(64-12-14), $(63-12), T_0 // [0x03fff000, 0x03fff000] - 26-bit mask with low 12 bits masked out + VESLG $24, T_1, T_1 // [h₆₄[2]<<24, 0] + VERIMG $-26&63, T_3, MOD26, H_1 // [h₂₆[1], r₂₆[1]] + VESRLG $+52&63, T_3, H_2 // [h₂₆[2], r₂₆[2]] - low 12 bits only + VERIMG $-14&63, T_4, MOD26, H_3 // [h₂₆[1], r₂₆[1]] + VESRLG $40, T_4, H_4 // [h₂₆[4], r₂₆[4]] - low 24 bits only + VERIMG $+12&63, T_4, T_0, H_2 // [h₂₆[2], r₂₆[2]] - complete + VO T_1, H_4, H_4 // [h₂₆[4], r₂₆[4]] - complete + + // replicate r across all 4 vector elements + VREPF $3, H_0, R_0 // [r₂₆[0], r₂₆[0], r₂₆[0], r₂₆[0]] + VREPF $3, H_1, R_1 // [r₂₆[1], r₂₆[1], r₂₆[1], r₂₆[1]] + VREPF $3, H_2, R_2 // [r₂₆[2], r₂₆[2], r₂₆[2], r₂₆[2]] + VREPF $3, H_3, R_3 // [r₂₆[3], r₂₆[3], r₂₆[3], r₂₆[3]] + VREPF $3, H_4, R_4 // [r₂₆[4], r₂₆[4], r₂₆[4], r₂₆[4]] + + // zero out lane 1 of h + VLEIG $1, $0, H_0 // [h₂₆[0], 0] + VLEIG $1, $0, H_1 // [h₂₆[1], 0] + VLEIG $1, $0, H_2 // [h₂₆[2], 0] + VLEIG $1, $0, H_3 // [h₂₆[3], 0] + VLEIG $1, $0, H_4 // [h₂₆[4], 0] + + // calculate 5r (ignore least significant limb) + VREPIF $5, T_0 + VMLF T_0, R_1, R5_1 // [5r₂₆[1], 5r₂₆[1], 5r₂₆[1], 5r₂₆[1]] + VMLF T_0, R_2, R5_2 // [5r₂₆[2], 5r₂₆[2], 5r₂₆[2], 5r₂₆[2]] + VMLF T_0, R_3, R5_3 // [5r₂₆[3], 5r₂₆[3], 5r₂₆[3], 5r₂₆[3]] + VMLF T_0, R_4, R5_4 // [5r₂₆[4], 5r₂₆[4], 5r₂₆[4], 5r₂₆[4]] + + // skip r² calculation if we are only calculating one block CMPBLE R3, $16, skip - // calculate r**2 - MULTIPLY(R_0, R_1, R_2, R_3, R_4, R_0, R_1, R_2, R_3, R_4, R5SAVE_1, R5SAVE_2, R5SAVE_3, R5SAVE_4, H_0, H_1, H_2, H_3, H_4) - REDUCE(H_0, H_1, H_2, H_3, H_4) - VLEIG $0, $5, T_0 - VLEIG $1, $5, T_0 - VMLOF T_0, H_1, R5_1 - VMLOF T_0, H_2, R5_2 - VMLOF T_0, H_3, R5_3 - VMLOF T_0, H_4, R5_4 - VLR H_0, R_0 - VLR H_1, R_1 - VLR H_2, R_2 - VLR H_3, R_3 - VLR H_4, R_4 - - // initialize h - VZERO H_0 - VZERO H_1 - VZERO H_2 - VZERO H_3 - VZERO H_4 + // calculate r² + MULTIPLY(R_0, R_1, R_2, R_3, R_4, R_0, R_1, R_2, R_3, R_4, R5_1, R5_2, R5_3, R5_4, M_0, M_1, M_2, M_3, M_4) + REDUCE(M_0, M_1, M_2, M_3, M_4) + VGBM $0x0f0f, T_0 + VERIMG $0, M_0, T_0, R_0 // [r₂₆[0], r²₂₆[0], r₂₆[0], r²₂₆[0]] + VERIMG $0, M_1, T_0, R_1 // [r₂₆[1], r²₂₆[1], r₂₆[1], r²₂₆[1]] + VERIMG $0, M_2, T_0, R_2 // [r₂₆[2], r²₂₆[2], r₂₆[2], r²₂₆[2]] + VERIMG $0, M_3, T_0, R_3 // [r₂₆[3], r²₂₆[3], r₂₆[3], r²₂₆[3]] + VERIMG $0, M_4, T_0, R_4 // [r₂₆[4], r²₂₆[4], r₂₆[4], r²₂₆[4]] + + // calculate 5r² (ignore least significant limb) + VREPIF $5, T_0 + VMLF T_0, R_1, R5_1 // [5r₂₆[1], 5r²₂₆[1], 5r₂₆[1], 5r²₂₆[1]] + VMLF T_0, R_2, R5_2 // [5r₂₆[2], 5r²₂₆[2], 5r₂₆[2], 5r²₂₆[2]] + VMLF T_0, R_3, R5_3 // [5r₂₆[3], 5r²₂₆[3], 5r₂₆[3], 5r²₂₆[3]] + VMLF T_0, R_4, R5_4 // [5r₂₆[4], 5r²₂₆[4], 5r₂₆[4], 5r²₂₆[4]] loop: - CMPBLE R3, $32, b2 - VLM (R2), T_0, T_1 - SUB $32, R3 - MOVD $32(R2), R2 - EXPAND(T_0, T_1, F_0, F_1, F_2, F_3, F_4) - VLEIB $4, $1, F_4 - VLEIB $12, $1, F_4 + CMPBLE R3, $32, b2 // 2 or fewer blocks remaining, need to change key coefficients + + // load next 2 blocks from message + VLM (R2), T_0, T_1 + + // update message slice + SUB $32, R3 + MOVD $32(R2), R2 + + // unpack message blocks into 26-bit big-endian limbs + EXPAND(T_0, T_1, M_0, M_1, M_2, M_3, M_4) + + // add 2¹²⁸ to each message block value + VLEIB $4, $1, M_4 + VLEIB $12, $1, M_4 multiply: - VAG H_0, F_0, F_0 - VAG H_1, F_1, F_1 - VAG H_2, F_2, F_2 - VAG H_3, F_3, F_3 - VAG H_4, F_4, F_4 - MULTIPLY(F_0, F_1, F_2, F_3, F_4, R_0, R_1, R_2, R_3, R_4, R5_1, R5_2, R5_3, R5_4, H_0, H_1, H_2, H_3, H_4) + // accumulate the incoming message + VAG H_0, M_0, M_0 + VAG H_3, M_3, M_3 + VAG H_1, M_1, M_1 + VAG H_4, M_4, M_4 + VAG H_2, M_2, M_2 + + // multiply the accumulator by the key coefficient + MULTIPLY(M_0, M_1, M_2, M_3, M_4, R_0, R_1, R_2, R_3, R_4, R5_1, R5_2, R5_3, R5_4, H_0, H_1, H_2, H_3, H_4) + + // carry and partially reduce the partial products REDUCE(H_0, H_1, H_2, H_3, H_4) + CMPBNE R3, $0, loop finish: - // sum vectors + // sum lane 0 and lane 1 and put the result in lane 1 VZERO T_0 VSUMQG H_0, T_0, H_0 - VSUMQG H_1, T_0, H_1 - VSUMQG H_2, T_0, H_2 VSUMQG H_3, T_0, H_3 + VSUMQG H_1, T_0, H_1 VSUMQG H_4, T_0, H_4 + VSUMQG H_2, T_0, H_2 - // h may be >= 2*(2**130-5) so we need to reduce it again + // reduce again after summation + // TODO(mundaym): there might be a more efficient way to do this + // now that we only have 1 active lane. For example, we could + // simultaneously pack the values as we reduce them. REDUCE(H_0, H_1, H_2, H_3, H_4) - // carry h1->h4 + // carry h[1] through to h[4] so that only h[4] can exceed 2²⁶ - 1 + // TODO(mundaym): in testing this final carry was unnecessary. + // Needs a proof before it can be removed though. VESRLG $26, H_1, T_1 VN MOD26, H_1, H_1 VAQ T_1, H_2, H_2 @@ -284,95 +367,137 @@ finish: VN MOD26, H_3, H_3 VAQ T_3, H_4, H_4 - // h is now < 2*(2**130-5) - // pack h into h1 (hi) and h0 (lo) - PACK(H_0, H_1, H_2, H_3, H_4) - - // if h > 2**130-5 then h -= 2**130-5 - MOD(H_0, H_1, T_0, T_1, T_2) - - // h += s - MOVD $·bswapMask<>(SB), R5 - VL (R5), T_1 - VL 16(R4), T_0 - VPERM T_0, T_0, T_1, T_0 // reverse bytes (to big) - VAQ T_0, H_0, H_0 - VPERM H_0, H_0, T_1, H_0 // reverse bytes (to little) - VST H_0, (R1) - + // h is now < 2(2¹³⁰ - 5) + // Pack each lane in h₂₆[0:4] into h₁₂₈[0:1]. + VESLG $26, H_1, H_1 + VESLG $26, H_3, H_3 + VO H_0, H_1, H_0 + VO H_2, H_3, H_2 + VESLG $4, H_2, H_2 + VLEIB $7, $48, H_1 + VSLB H_1, H_2, H_2 + VO H_0, H_2, H_0 + VLEIB $7, $104, H_1 + VSLB H_1, H_4, H_3 + VO H_3, H_0, H_0 + VLEIB $7, $24, H_1 + VSRLB H_1, H_4, H_1 + + // update state + VSTEG $1, H_0, 0(R1) + VSTEG $0, H_0, 8(R1) + VSTEG $1, H_1, 16(R1) RET -b2: +b2: // 2 or fewer blocks remaining CMPBLE R3, $16, b1 - // 2 blocks remaining - SUB $17, R3 - VL (R2), T_0 - VLL R3, 16(R2), T_1 - ADD $1, R3 + // Load the 2 remaining blocks (17-32 bytes remaining). + MOVD $-17(R3), R0 // index of final byte to load modulo 16 + VL (R2), T_0 // load full 16 byte block + VLL R0, 16(R2), T_1 // load final (possibly partial) block and pad with zeros to 16 bytes + + // The Poly1305 algorithm requires that a 1 bit be appended to + // each message block. If the final block is less than 16 bytes + // long then it is easiest to insert the 1 before the message + // block is split into 26-bit limbs. If, on the other hand, the + // final message block is 16 bytes long then we append the 1 bit + // after expansion as normal. MOVBZ $1, R0 - CMPBEQ R3, $16, 2(PC) - VLVGB R3, R0, T_1 - EXPAND(T_0, T_1, F_0, F_1, F_2, F_3, F_4) + MOVD $-16(R3), R3 // index of byte in last block to insert 1 at (could be 16) + CMPBEQ R3, $16, 2(PC) // skip the insertion if the final block is 16 bytes long + VLVGB R3, R0, T_1 // insert 1 into the byte at index R3 + + // Split both blocks into 26-bit limbs in the appropriate lanes. + EXPAND(T_0, T_1, M_0, M_1, M_2, M_3, M_4) + + // Append a 1 byte to the end of the second to last block. + VLEIB $4, $1, M_4 + + // Append a 1 byte to the end of the last block only if it is a + // full 16 byte block. CMPBNE R3, $16, 2(PC) - VLEIB $12, $1, F_4 - VLEIB $4, $1, F_4 - - // setup [r²,r] - VLVGG $1, RSAVE_0, R_0 - VLVGG $1, RSAVE_1, R_1 - VLVGG $1, RSAVE_2, R_2 - VLVGG $1, RSAVE_3, R_3 - VLVGG $1, RSAVE_4, R_4 - VPDI $0, R5_1, R5SAVE_1, R5_1 - VPDI $0, R5_2, R5SAVE_2, R5_2 - VPDI $0, R5_3, R5SAVE_3, R5_3 - VPDI $0, R5_4, R5SAVE_4, R5_4 + VLEIB $12, $1, M_4 + + // Finally, set up the coefficients for the final multiplication. + // We have previously saved r and 5r in the 32-bit even indexes + // of the R_[0-4] and R5_[1-4] coefficient registers. + // + // We want lane 0 to be multiplied by r² so that can be kept the + // same. We want lane 1 to be multiplied by r so we need to move + // the saved r value into the 32-bit odd index in lane 1 by + // rotating the 64-bit lane by 32. + VGBM $0x00ff, T_0 // [0, 0xffffffffffffffff] - mask lane 1 only + VERIMG $32, R_0, T_0, R_0 // [_, r²₂₆[0], _, r₂₆[0]] + VERIMG $32, R_1, T_0, R_1 // [_, r²₂₆[1], _, r₂₆[1]] + VERIMG $32, R_2, T_0, R_2 // [_, r²₂₆[2], _, r₂₆[2]] + VERIMG $32, R_3, T_0, R_3 // [_, r²₂₆[3], _, r₂₆[3]] + VERIMG $32, R_4, T_0, R_4 // [_, r²₂₆[4], _, r₂₆[4]] + VERIMG $32, R5_1, T_0, R5_1 // [_, 5r²₂₆[1], _, 5r₂₆[1]] + VERIMG $32, R5_2, T_0, R5_2 // [_, 5r²₂₆[2], _, 5r₂₆[2]] + VERIMG $32, R5_3, T_0, R5_3 // [_, 5r²₂₆[3], _, 5r₂₆[3]] + VERIMG $32, R5_4, T_0, R5_4 // [_, 5r²₂₆[4], _, 5r₂₆[4]] MOVD $0, R3 BR multiply skip: - VZERO H_0 - VZERO H_1 - VZERO H_2 - VZERO H_3 - VZERO H_4 - CMPBEQ R3, $0, finish -b1: - // 1 block remaining - SUB $1, R3 - VLL R3, (R2), T_0 - ADD $1, R3 +b1: // 1 block remaining + + // Load the final block (1-16 bytes). This will be placed into + // lane 0. + MOVD $-1(R3), R0 + VLL R0, (R2), T_0 // pad to 16 bytes with zeros + + // The Poly1305 algorithm requires that a 1 bit be appended to + // each message block. If the final block is less than 16 bytes + // long then it is easiest to insert the 1 before the message + // block is split into 26-bit limbs. If, on the other hand, the + // final message block is 16 bytes long then we append the 1 bit + // after expansion as normal. MOVBZ $1, R0 CMPBEQ R3, $16, 2(PC) VLVGB R3, R0, T_0 - VZERO T_1 - EXPAND(T_0, T_1, F_0, F_1, F_2, F_3, F_4) + + // Set the message block in lane 1 to the value 0 so that it + // can be accumulated without affecting the final result. + VZERO T_1 + + // Split the final message block into 26-bit limbs in lane 0. + // Lane 1 will be contain 0. + EXPAND(T_0, T_1, M_0, M_1, M_2, M_3, M_4) + + // Append a 1 byte to the end of the last block only if it is a + // full 16 byte block. CMPBNE R3, $16, 2(PC) - VLEIB $4, $1, F_4 - VLEIG $1, $1, R_0 - VZERO R_1 - VZERO R_2 - VZERO R_3 - VZERO R_4 - VZERO R5_1 - VZERO R5_2 - VZERO R5_3 - VZERO R5_4 - - // setup [r, 1] - VLVGG $0, RSAVE_0, R_0 - VLVGG $0, RSAVE_1, R_1 - VLVGG $0, RSAVE_2, R_2 - VLVGG $0, RSAVE_3, R_3 - VLVGG $0, RSAVE_4, R_4 - VPDI $0, R5SAVE_1, R5_1, R5_1 - VPDI $0, R5SAVE_2, R5_2, R5_2 - VPDI $0, R5SAVE_3, R5_3, R5_3 - VPDI $0, R5SAVE_4, R5_4, R5_4 + VLEIB $4, $1, M_4 + + // We have previously saved r and 5r in the 32-bit even indexes + // of the R_[0-4] and R5_[1-4] coefficient registers. + // + // We want lane 0 to be multiplied by r so we need to move the + // saved r value into the 32-bit odd index in lane 0. We want + // lane 1 to be set to the value 1. This makes multiplication + // a no-op. We do this by setting lane 1 in every register to 0 + // and then just setting the 32-bit index 3 in R_0 to 1. + VZERO T_0 + MOVD $0, R0 + MOVD $0x10111213, R12 + VLVGP R12, R0, T_1 // [_, 0x10111213, _, 0x00000000] + VPERM T_0, R_0, T_1, R_0 // [_, r₂₆[0], _, 0] + VPERM T_0, R_1, T_1, R_1 // [_, r₂₆[1], _, 0] + VPERM T_0, R_2, T_1, R_2 // [_, r₂₆[2], _, 0] + VPERM T_0, R_3, T_1, R_3 // [_, r₂₆[3], _, 0] + VPERM T_0, R_4, T_1, R_4 // [_, r₂₆[4], _, 0] + VPERM T_0, R5_1, T_1, R5_1 // [_, 5r₂₆[1], _, 0] + VPERM T_0, R5_2, T_1, R5_2 // [_, 5r₂₆[2], _, 0] + VPERM T_0, R5_3, T_1, R5_3 // [_, 5r₂₆[3], _, 0] + VPERM T_0, R5_4, T_1, R5_4 // [_, 5r₂₆[4], _, 0] + + // Set the value of lane 1 to be 1. + VLEIF $3, $1, R_0 // [_, r₂₆[0], _, 1] MOVD $0, R3 BR multiply diff --git a/vendor/golang.org/x/crypto/poly1305/sum_vmsl_s390x.s b/vendor/golang.org/x/crypto/poly1305/sum_vmsl_s390x.s deleted file mode 100644 index e60bbc1d7f8..00000000000 --- a/vendor/golang.org/x/crypto/poly1305/sum_vmsl_s390x.s +++ /dev/null @@ -1,909 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build s390x,go1.11,!gccgo,!appengine - -#include "textflag.h" - -// Implementation of Poly1305 using the vector facility (vx) and the VMSL instruction. - -// constants -#define EX0 V1 -#define EX1 V2 -#define EX2 V3 - -// temporaries -#define T_0 V4 -#define T_1 V5 -#define T_2 V6 -#define T_3 V7 -#define T_4 V8 -#define T_5 V9 -#define T_6 V10 -#define T_7 V11 -#define T_8 V12 -#define T_9 V13 -#define T_10 V14 - -// r**2 & r**4 -#define R_0 V15 -#define R_1 V16 -#define R_2 V17 -#define R5_1 V18 -#define R5_2 V19 -// key (r) -#define RSAVE_0 R7 -#define RSAVE_1 R8 -#define RSAVE_2 R9 -#define R5SAVE_1 R10 -#define R5SAVE_2 R11 - -// message block -#define M0 V20 -#define M1 V21 -#define M2 V22 -#define M3 V23 -#define M4 V24 -#define M5 V25 - -// accumulator -#define H0_0 V26 -#define H1_0 V27 -#define H2_0 V28 -#define H0_1 V29 -#define H1_1 V30 -#define H2_1 V31 - -GLOBL ·keyMask<>(SB), RODATA, $16 -DATA ·keyMask<>+0(SB)/8, $0xffffff0ffcffff0f -DATA ·keyMask<>+8(SB)/8, $0xfcffff0ffcffff0f - -GLOBL ·bswapMask<>(SB), RODATA, $16 -DATA ·bswapMask<>+0(SB)/8, $0x0f0e0d0c0b0a0908 -DATA ·bswapMask<>+8(SB)/8, $0x0706050403020100 - -GLOBL ·constants<>(SB), RODATA, $48 -// EX0 -DATA ·constants<>+0(SB)/8, $0x18191a1b1c1d1e1f -DATA ·constants<>+8(SB)/8, $0x0000050403020100 -// EX1 -DATA ·constants<>+16(SB)/8, $0x18191a1b1c1d1e1f -DATA ·constants<>+24(SB)/8, $0x00000a0908070605 -// EX2 -DATA ·constants<>+32(SB)/8, $0x18191a1b1c1d1e1f -DATA ·constants<>+40(SB)/8, $0x0000000f0e0d0c0b - -GLOBL ·c<>(SB), RODATA, $48 -// EX0 -DATA ·c<>+0(SB)/8, $0x0000050403020100 -DATA ·c<>+8(SB)/8, $0x0000151413121110 -// EX1 -DATA ·c<>+16(SB)/8, $0x00000a0908070605 -DATA ·c<>+24(SB)/8, $0x00001a1918171615 -// EX2 -DATA ·c<>+32(SB)/8, $0x0000000f0e0d0c0b -DATA ·c<>+40(SB)/8, $0x0000001f1e1d1c1b - -GLOBL ·reduce<>(SB), RODATA, $32 -// 44 bit -DATA ·reduce<>+0(SB)/8, $0x0 -DATA ·reduce<>+8(SB)/8, $0xfffffffffff -// 42 bit -DATA ·reduce<>+16(SB)/8, $0x0 -DATA ·reduce<>+24(SB)/8, $0x3ffffffffff - -// h = (f*g) % (2**130-5) [partial reduction] -// uses T_0...T_9 temporary registers -// input: m02_0, m02_1, m02_2, m13_0, m13_1, m13_2, r_0, r_1, r_2, r5_1, r5_2, m4_0, m4_1, m4_2, m5_0, m5_1, m5_2 -// temp: t0, t1, t2, t3, t4, t5, t6, t7, t8, t9 -// output: m02_0, m02_1, m02_2, m13_0, m13_1, m13_2 -#define MULTIPLY(m02_0, m02_1, m02_2, m13_0, m13_1, m13_2, r_0, r_1, r_2, r5_1, r5_2, m4_0, m4_1, m4_2, m5_0, m5_1, m5_2, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9) \ - \ // Eliminate the dependency for the last 2 VMSLs - VMSLG m02_0, r_2, m4_2, m4_2 \ - VMSLG m13_0, r_2, m5_2, m5_2 \ // 8 VMSLs pipelined - VMSLG m02_0, r_0, m4_0, m4_0 \ - VMSLG m02_1, r5_2, V0, T_0 \ - VMSLG m02_0, r_1, m4_1, m4_1 \ - VMSLG m02_1, r_0, V0, T_1 \ - VMSLG m02_1, r_1, V0, T_2 \ - VMSLG m02_2, r5_1, V0, T_3 \ - VMSLG m02_2, r5_2, V0, T_4 \ - VMSLG m13_0, r_0, m5_0, m5_0 \ - VMSLG m13_1, r5_2, V0, T_5 \ - VMSLG m13_0, r_1, m5_1, m5_1 \ - VMSLG m13_1, r_0, V0, T_6 \ - VMSLG m13_1, r_1, V0, T_7 \ - VMSLG m13_2, r5_1, V0, T_8 \ - VMSLG m13_2, r5_2, V0, T_9 \ - VMSLG m02_2, r_0, m4_2, m4_2 \ - VMSLG m13_2, r_0, m5_2, m5_2 \ - VAQ m4_0, T_0, m02_0 \ - VAQ m4_1, T_1, m02_1 \ - VAQ m5_0, T_5, m13_0 \ - VAQ m5_1, T_6, m13_1 \ - VAQ m02_0, T_3, m02_0 \ - VAQ m02_1, T_4, m02_1 \ - VAQ m13_0, T_8, m13_0 \ - VAQ m13_1, T_9, m13_1 \ - VAQ m4_2, T_2, m02_2 \ - VAQ m5_2, T_7, m13_2 \ - -// SQUARE uses three limbs of r and r_2*5 to output square of r -// uses T_1, T_5 and T_7 temporary registers -// input: r_0, r_1, r_2, r5_2 -// temp: TEMP0, TEMP1, TEMP2 -// output: p0, p1, p2 -#define SQUARE(r_0, r_1, r_2, r5_2, p0, p1, p2, TEMP0, TEMP1, TEMP2) \ - VMSLG r_0, r_0, p0, p0 \ - VMSLG r_1, r5_2, V0, TEMP0 \ - VMSLG r_2, r5_2, p1, p1 \ - VMSLG r_0, r_1, V0, TEMP1 \ - VMSLG r_1, r_1, p2, p2 \ - VMSLG r_0, r_2, V0, TEMP2 \ - VAQ TEMP0, p0, p0 \ - VAQ TEMP1, p1, p1 \ - VAQ TEMP2, p2, p2 \ - VAQ TEMP0, p0, p0 \ - VAQ TEMP1, p1, p1 \ - VAQ TEMP2, p2, p2 \ - -// carry h0->h1->h2->h0 || h3->h4->h5->h3 -// uses T_2, T_4, T_5, T_7, T_8, T_9 -// t6, t7, t8, t9, t10, t11 -// input: h0, h1, h2, h3, h4, h5 -// temp: t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11 -// output: h0, h1, h2, h3, h4, h5 -#define REDUCE(h0, h1, h2, h3, h4, h5, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11) \ - VLM (R12), t6, t7 \ // 44 and 42 bit clear mask - VLEIB $7, $0x28, t10 \ // 5 byte shift mask - VREPIB $4, t8 \ // 4 bit shift mask - VREPIB $2, t11 \ // 2 bit shift mask - VSRLB t10, h0, t0 \ // h0 byte shift - VSRLB t10, h1, t1 \ // h1 byte shift - VSRLB t10, h2, t2 \ // h2 byte shift - VSRLB t10, h3, t3 \ // h3 byte shift - VSRLB t10, h4, t4 \ // h4 byte shift - VSRLB t10, h5, t5 \ // h5 byte shift - VSRL t8, t0, t0 \ // h0 bit shift - VSRL t8, t1, t1 \ // h2 bit shift - VSRL t11, t2, t2 \ // h2 bit shift - VSRL t8, t3, t3 \ // h3 bit shift - VSRL t8, t4, t4 \ // h4 bit shift - VESLG $2, t2, t9 \ // h2 carry x5 - VSRL t11, t5, t5 \ // h5 bit shift - VN t6, h0, h0 \ // h0 clear carry - VAQ t2, t9, t2 \ // h2 carry x5 - VESLG $2, t5, t9 \ // h5 carry x5 - VN t6, h1, h1 \ // h1 clear carry - VN t7, h2, h2 \ // h2 clear carry - VAQ t5, t9, t5 \ // h5 carry x5 - VN t6, h3, h3 \ // h3 clear carry - VN t6, h4, h4 \ // h4 clear carry - VN t7, h5, h5 \ // h5 clear carry - VAQ t0, h1, h1 \ // h0->h1 - VAQ t3, h4, h4 \ // h3->h4 - VAQ t1, h2, h2 \ // h1->h2 - VAQ t4, h5, h5 \ // h4->h5 - VAQ t2, h0, h0 \ // h2->h0 - VAQ t5, h3, h3 \ // h5->h3 - VREPG $1, t6, t6 \ // 44 and 42 bit masks across both halves - VREPG $1, t7, t7 \ - VSLDB $8, h0, h0, h0 \ // set up [h0/1/2, h3/4/5] - VSLDB $8, h1, h1, h1 \ - VSLDB $8, h2, h2, h2 \ - VO h0, h3, h3 \ - VO h1, h4, h4 \ - VO h2, h5, h5 \ - VESRLG $44, h3, t0 \ // 44 bit shift right - VESRLG $44, h4, t1 \ - VESRLG $42, h5, t2 \ - VN t6, h3, h3 \ // clear carry bits - VN t6, h4, h4 \ - VN t7, h5, h5 \ - VESLG $2, t2, t9 \ // multiply carry by 5 - VAQ t9, t2, t2 \ - VAQ t0, h4, h4 \ - VAQ t1, h5, h5 \ - VAQ t2, h3, h3 \ - -// carry h0->h1->h2->h0 -// input: h0, h1, h2 -// temp: t0, t1, t2, t3, t4, t5, t6, t7, t8 -// output: h0, h1, h2 -#define REDUCE2(h0, h1, h2, t0, t1, t2, t3, t4, t5, t6, t7, t8) \ - VLEIB $7, $0x28, t3 \ // 5 byte shift mask - VREPIB $4, t4 \ // 4 bit shift mask - VREPIB $2, t7 \ // 2 bit shift mask - VGBM $0x003F, t5 \ // mask to clear carry bits - VSRLB t3, h0, t0 \ - VSRLB t3, h1, t1 \ - VSRLB t3, h2, t2 \ - VESRLG $4, t5, t5 \ // 44 bit clear mask - VSRL t4, t0, t0 \ - VSRL t4, t1, t1 \ - VSRL t7, t2, t2 \ - VESRLG $2, t5, t6 \ // 42 bit clear mask - VESLG $2, t2, t8 \ - VAQ t8, t2, t2 \ - VN t5, h0, h0 \ - VN t5, h1, h1 \ - VN t6, h2, h2 \ - VAQ t0, h1, h1 \ - VAQ t1, h2, h2 \ - VAQ t2, h0, h0 \ - VSRLB t3, h0, t0 \ - VSRLB t3, h1, t1 \ - VSRLB t3, h2, t2 \ - VSRL t4, t0, t0 \ - VSRL t4, t1, t1 \ - VSRL t7, t2, t2 \ - VN t5, h0, h0 \ - VN t5, h1, h1 \ - VESLG $2, t2, t8 \ - VN t6, h2, h2 \ - VAQ t0, h1, h1 \ - VAQ t8, t2, t2 \ - VAQ t1, h2, h2 \ - VAQ t2, h0, h0 \ - -// expands two message blocks into the lower halfs of the d registers -// moves the contents of the d registers into upper halfs -// input: in1, in2, d0, d1, d2, d3, d4, d5 -// temp: TEMP0, TEMP1, TEMP2, TEMP3 -// output: d0, d1, d2, d3, d4, d5 -#define EXPACC(in1, in2, d0, d1, d2, d3, d4, d5, TEMP0, TEMP1, TEMP2, TEMP3) \ - VGBM $0xff3f, TEMP0 \ - VGBM $0xff1f, TEMP1 \ - VESLG $4, d1, TEMP2 \ - VESLG $4, d4, TEMP3 \ - VESRLG $4, TEMP0, TEMP0 \ - VPERM in1, d0, EX0, d0 \ - VPERM in2, d3, EX0, d3 \ - VPERM in1, d2, EX2, d2 \ - VPERM in2, d5, EX2, d5 \ - VPERM in1, TEMP2, EX1, d1 \ - VPERM in2, TEMP3, EX1, d4 \ - VN TEMP0, d0, d0 \ - VN TEMP0, d3, d3 \ - VESRLG $4, d1, d1 \ - VESRLG $4, d4, d4 \ - VN TEMP1, d2, d2 \ - VN TEMP1, d5, d5 \ - VN TEMP0, d1, d1 \ - VN TEMP0, d4, d4 \ - -// expands one message block into the lower halfs of the d registers -// moves the contents of the d registers into upper halfs -// input: in, d0, d1, d2 -// temp: TEMP0, TEMP1, TEMP2 -// output: d0, d1, d2 -#define EXPACC2(in, d0, d1, d2, TEMP0, TEMP1, TEMP2) \ - VGBM $0xff3f, TEMP0 \ - VESLG $4, d1, TEMP2 \ - VGBM $0xff1f, TEMP1 \ - VPERM in, d0, EX0, d0 \ - VESRLG $4, TEMP0, TEMP0 \ - VPERM in, d2, EX2, d2 \ - VPERM in, TEMP2, EX1, d1 \ - VN TEMP0, d0, d0 \ - VN TEMP1, d2, d2 \ - VESRLG $4, d1, d1 \ - VN TEMP0, d1, d1 \ - -// pack h2:h0 into h1:h0 (no carry) -// input: h0, h1, h2 -// output: h0, h1, h2 -#define PACK(h0, h1, h2) \ - VMRLG h1, h2, h2 \ // copy h1 to upper half h2 - VESLG $44, h1, h1 \ // shift limb 1 44 bits, leaving 20 - VO h0, h1, h0 \ // combine h0 with 20 bits from limb 1 - VESRLG $20, h2, h1 \ // put top 24 bits of limb 1 into h1 - VLEIG $1, $0, h1 \ // clear h2 stuff from lower half of h1 - VO h0, h1, h0 \ // h0 now has 88 bits (limb 0 and 1) - VLEIG $0, $0, h2 \ // clear upper half of h2 - VESRLG $40, h2, h1 \ // h1 now has upper two bits of result - VLEIB $7, $88, h1 \ // for byte shift (11 bytes) - VSLB h1, h2, h2 \ // shift h2 11 bytes to the left - VO h0, h2, h0 \ // combine h0 with 20 bits from limb 1 - VLEIG $0, $0, h1 \ // clear upper half of h1 - -// if h > 2**130-5 then h -= 2**130-5 -// input: h0, h1 -// temp: t0, t1, t2 -// output: h0 -#define MOD(h0, h1, t0, t1, t2) \ - VZERO t0 \ - VLEIG $1, $5, t0 \ - VACCQ h0, t0, t1 \ - VAQ h0, t0, t0 \ - VONE t2 \ - VLEIG $1, $-4, t2 \ - VAQ t2, t1, t1 \ - VACCQ h1, t1, t1 \ - VONE t2 \ - VAQ t2, t1, t1 \ - VN h0, t1, t2 \ - VNC t0, t1, t1 \ - VO t1, t2, h0 \ - -// func poly1305vmsl(out *[16]byte, m *byte, mlen uint64, key *[32]key) -TEXT ·poly1305vmsl(SB), $0-32 - // This code processes 6 + up to 4 blocks (32 bytes) per iteration - // using the algorithm described in: - // NEON crypto, Daniel J. Bernstein & Peter Schwabe - // https://cryptojedi.org/papers/neoncrypto-20120320.pdf - // And as moddified for VMSL as described in - // Accelerating Poly1305 Cryptographic Message Authentication on the z14 - // O'Farrell et al, CASCON 2017, p48-55 - // https://ibm.ent.box.com/s/jf9gedj0e9d2vjctfyh186shaztavnht - - LMG out+0(FP), R1, R4 // R1=out, R2=m, R3=mlen, R4=key - VZERO V0 // c - - // load EX0, EX1 and EX2 - MOVD $·constants<>(SB), R5 - VLM (R5), EX0, EX2 // c - - // setup r - VL (R4), T_0 - MOVD $·keyMask<>(SB), R6 - VL (R6), T_1 - VN T_0, T_1, T_0 - VZERO T_2 // limbs for r - VZERO T_3 - VZERO T_4 - EXPACC2(T_0, T_2, T_3, T_4, T_1, T_5, T_7) - - // T_2, T_3, T_4: [0, r] - - // setup r*20 - VLEIG $0, $0, T_0 - VLEIG $1, $20, T_0 // T_0: [0, 20] - VZERO T_5 - VZERO T_6 - VMSLG T_0, T_3, T_5, T_5 - VMSLG T_0, T_4, T_6, T_6 - - // store r for final block in GR - VLGVG $1, T_2, RSAVE_0 // c - VLGVG $1, T_3, RSAVE_1 // c - VLGVG $1, T_4, RSAVE_2 // c - VLGVG $1, T_5, R5SAVE_1 // c - VLGVG $1, T_6, R5SAVE_2 // c - - // initialize h - VZERO H0_0 - VZERO H1_0 - VZERO H2_0 - VZERO H0_1 - VZERO H1_1 - VZERO H2_1 - - // initialize pointer for reduce constants - MOVD $·reduce<>(SB), R12 - - // calculate r**2 and 20*(r**2) - VZERO R_0 - VZERO R_1 - VZERO R_2 - SQUARE(T_2, T_3, T_4, T_6, R_0, R_1, R_2, T_1, T_5, T_7) - REDUCE2(R_0, R_1, R_2, M0, M1, M2, M3, M4, R5_1, R5_2, M5, T_1) - VZERO R5_1 - VZERO R5_2 - VMSLG T_0, R_1, R5_1, R5_1 - VMSLG T_0, R_2, R5_2, R5_2 - - // skip r**4 calculation if 3 blocks or less - CMPBLE R3, $48, b4 - - // calculate r**4 and 20*(r**4) - VZERO T_8 - VZERO T_9 - VZERO T_10 - SQUARE(R_0, R_1, R_2, R5_2, T_8, T_9, T_10, T_1, T_5, T_7) - REDUCE2(T_8, T_9, T_10, M0, M1, M2, M3, M4, T_2, T_3, M5, T_1) - VZERO T_2 - VZERO T_3 - VMSLG T_0, T_9, T_2, T_2 - VMSLG T_0, T_10, T_3, T_3 - - // put r**2 to the right and r**4 to the left of R_0, R_1, R_2 - VSLDB $8, T_8, T_8, T_8 - VSLDB $8, T_9, T_9, T_9 - VSLDB $8, T_10, T_10, T_10 - VSLDB $8, T_2, T_2, T_2 - VSLDB $8, T_3, T_3, T_3 - - VO T_8, R_0, R_0 - VO T_9, R_1, R_1 - VO T_10, R_2, R_2 - VO T_2, R5_1, R5_1 - VO T_3, R5_2, R5_2 - - CMPBLE R3, $80, load // less than or equal to 5 blocks in message - - // 6(or 5+1) blocks - SUB $81, R3 - VLM (R2), M0, M4 - VLL R3, 80(R2), M5 - ADD $1, R3 - MOVBZ $1, R0 - CMPBGE R3, $16, 2(PC) - VLVGB R3, R0, M5 - MOVD $96(R2), R2 - EXPACC(M0, M1, H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_0, T_1, T_2, T_3) - EXPACC(M2, M3, H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_0, T_1, T_2, T_3) - VLEIB $2, $1, H2_0 - VLEIB $2, $1, H2_1 - VLEIB $10, $1, H2_0 - VLEIB $10, $1, H2_1 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO T_4 - VZERO T_10 - EXPACC(M4, M5, M0, M1, M2, M3, T_4, T_10, T_0, T_1, T_2, T_3) - VLR T_4, M4 - VLEIB $10, $1, M2 - CMPBLT R3, $16, 2(PC) - VLEIB $10, $1, T_10 - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, T_10, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M2, M3, M4, T_4, T_5, T_2, T_7, T_8, T_9) - VMRHG V0, H0_1, H0_0 - VMRHG V0, H1_1, H1_0 - VMRHG V0, H2_1, H2_0 - VMRLG V0, H0_1, H0_1 - VMRLG V0, H1_1, H1_1 - VMRLG V0, H2_1, H2_1 - - SUB $16, R3 - CMPBLE R3, $0, square - -load: - // load EX0, EX1 and EX2 - MOVD $·c<>(SB), R5 - VLM (R5), EX0, EX2 - -loop: - CMPBLE R3, $64, add // b4 // last 4 or less blocks left - - // next 4 full blocks - VLM (R2), M2, M5 - SUB $64, R3 - MOVD $64(R2), R2 - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, T_0, T_1, T_3, T_4, T_5, T_2, T_7, T_8, T_9) - - // expacc in-lined to create [m2, m3] limbs - VGBM $0x3f3f, T_0 // 44 bit clear mask - VGBM $0x1f1f, T_1 // 40 bit clear mask - VPERM M2, M3, EX0, T_3 - VESRLG $4, T_0, T_0 // 44 bit clear mask ready - VPERM M2, M3, EX1, T_4 - VPERM M2, M3, EX2, T_5 - VN T_0, T_3, T_3 - VESRLG $4, T_4, T_4 - VN T_1, T_5, T_5 - VN T_0, T_4, T_4 - VMRHG H0_1, T_3, H0_0 - VMRHG H1_1, T_4, H1_0 - VMRHG H2_1, T_5, H2_0 - VMRLG H0_1, T_3, H0_1 - VMRLG H1_1, T_4, H1_1 - VMRLG H2_1, T_5, H2_1 - VLEIB $10, $1, H2_0 - VLEIB $10, $1, H2_1 - VPERM M4, M5, EX0, T_3 - VPERM M4, M5, EX1, T_4 - VPERM M4, M5, EX2, T_5 - VN T_0, T_3, T_3 - VESRLG $4, T_4, T_4 - VN T_1, T_5, T_5 - VN T_0, T_4, T_4 - VMRHG V0, T_3, M0 - VMRHG V0, T_4, M1 - VMRHG V0, T_5, M2 - VMRLG V0, T_3, M3 - VMRLG V0, T_4, M4 - VMRLG V0, T_5, M5 - VLEIB $10, $1, M2 - VLEIB $10, $1, M5 - - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - CMPBNE R3, $0, loop - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M3, M4, M5, T_4, T_5, T_2, T_7, T_8, T_9) - VMRHG V0, H0_1, H0_0 - VMRHG V0, H1_1, H1_0 - VMRHG V0, H2_1, H2_0 - VMRLG V0, H0_1, H0_1 - VMRLG V0, H1_1, H1_1 - VMRLG V0, H2_1, H2_1 - - // load EX0, EX1, EX2 - MOVD $·constants<>(SB), R5 - VLM (R5), EX0, EX2 - - // sum vectors - VAQ H0_0, H0_1, H0_0 - VAQ H1_0, H1_1, H1_0 - VAQ H2_0, H2_1, H2_0 - - // h may be >= 2*(2**130-5) so we need to reduce it again - // M0...M4 are used as temps here - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) - -next: // carry h1->h2 - VLEIB $7, $0x28, T_1 - VREPIB $4, T_2 - VGBM $0x003F, T_3 - VESRLG $4, T_3 - - // byte shift - VSRLB T_1, H1_0, T_4 - - // bit shift - VSRL T_2, T_4, T_4 - - // clear h1 carry bits - VN T_3, H1_0, H1_0 - - // add carry - VAQ T_4, H2_0, H2_0 - - // h is now < 2*(2**130-5) - // pack h into h1 (hi) and h0 (lo) - PACK(H0_0, H1_0, H2_0) - - // if h > 2**130-5 then h -= 2**130-5 - MOD(H0_0, H1_0, T_0, T_1, T_2) - - // h += s - MOVD $·bswapMask<>(SB), R5 - VL (R5), T_1 - VL 16(R4), T_0 - VPERM T_0, T_0, T_1, T_0 // reverse bytes (to big) - VAQ T_0, H0_0, H0_0 - VPERM H0_0, H0_0, T_1, H0_0 // reverse bytes (to little) - VST H0_0, (R1) - RET - -add: - // load EX0, EX1, EX2 - MOVD $·constants<>(SB), R5 - VLM (R5), EX0, EX2 - - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M3, M4, M5, T_4, T_5, T_2, T_7, T_8, T_9) - VMRHG V0, H0_1, H0_0 - VMRHG V0, H1_1, H1_0 - VMRHG V0, H2_1, H2_0 - VMRLG V0, H0_1, H0_1 - VMRLG V0, H1_1, H1_1 - VMRLG V0, H2_1, H2_1 - CMPBLE R3, $64, b4 - -b4: - CMPBLE R3, $48, b3 // 3 blocks or less - - // 4(3+1) blocks remaining - SUB $49, R3 - VLM (R2), M0, M2 - VLL R3, 48(R2), M3 - ADD $1, R3 - MOVBZ $1, R0 - CMPBEQ R3, $16, 2(PC) - VLVGB R3, R0, M3 - MOVD $64(R2), R2 - EXPACC(M0, M1, H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_0, T_1, T_2, T_3) - VLEIB $10, $1, H2_0 - VLEIB $10, $1, H2_1 - VZERO M0 - VZERO M1 - VZERO M4 - VZERO M5 - VZERO T_4 - VZERO T_10 - EXPACC(M2, M3, M0, M1, M4, M5, T_4, T_10, T_0, T_1, T_2, T_3) - VLR T_4, M2 - VLEIB $10, $1, M4 - CMPBNE R3, $16, 2(PC) - VLEIB $10, $1, T_10 - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M4, M5, M2, T_10, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M3, M4, M5, T_4, T_5, T_2, T_7, T_8, T_9) - VMRHG V0, H0_1, H0_0 - VMRHG V0, H1_1, H1_0 - VMRHG V0, H2_1, H2_0 - VMRLG V0, H0_1, H0_1 - VMRLG V0, H1_1, H1_1 - VMRLG V0, H2_1, H2_1 - SUB $16, R3 - CMPBLE R3, $0, square // this condition must always hold true! - -b3: - CMPBLE R3, $32, b2 - - // 3 blocks remaining - - // setup [r²,r] - VSLDB $8, R_0, R_0, R_0 - VSLDB $8, R_1, R_1, R_1 - VSLDB $8, R_2, R_2, R_2 - VSLDB $8, R5_1, R5_1, R5_1 - VSLDB $8, R5_2, R5_2, R5_2 - - VLVGG $1, RSAVE_0, R_0 - VLVGG $1, RSAVE_1, R_1 - VLVGG $1, RSAVE_2, R_2 - VLVGG $1, R5SAVE_1, R5_1 - VLVGG $1, R5SAVE_2, R5_2 - - // setup [h0, h1] - VSLDB $8, H0_0, H0_0, H0_0 - VSLDB $8, H1_0, H1_0, H1_0 - VSLDB $8, H2_0, H2_0, H2_0 - VO H0_1, H0_0, H0_0 - VO H1_1, H1_0, H1_0 - VO H2_1, H2_0, H2_0 - VZERO H0_1 - VZERO H1_1 - VZERO H2_1 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - - // H*[r**2, r] - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, H0_1, H1_1, T_10, M5) - - SUB $33, R3 - VLM (R2), M0, M1 - VLL R3, 32(R2), M2 - ADD $1, R3 - MOVBZ $1, R0 - CMPBEQ R3, $16, 2(PC) - VLVGB R3, R0, M2 - - // H += m0 - VZERO T_1 - VZERO T_2 - VZERO T_3 - EXPACC2(M0, T_1, T_2, T_3, T_4, T_5, T_6) - VLEIB $10, $1, T_3 - VAG H0_0, T_1, H0_0 - VAG H1_0, T_2, H1_0 - VAG H2_0, T_3, H2_0 - - VZERO M0 - VZERO M3 - VZERO M4 - VZERO M5 - VZERO T_10 - - // (H+m0)*r - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M3, M4, M5, V0, T_10, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M3, M4, M5, T_10, H0_1, H1_1, H2_1, T_9) - - // H += m1 - VZERO V0 - VZERO T_1 - VZERO T_2 - VZERO T_3 - EXPACC2(M1, T_1, T_2, T_3, T_4, T_5, T_6) - VLEIB $10, $1, T_3 - VAQ H0_0, T_1, H0_0 - VAQ H1_0, T_2, H1_0 - VAQ H2_0, T_3, H2_0 - REDUCE2(H0_0, H1_0, H2_0, M0, M3, M4, M5, T_9, H0_1, H1_1, H2_1, T_10) - - // [H, m2] * [r**2, r] - EXPACC2(M2, H0_0, H1_0, H2_0, T_1, T_2, T_3) - CMPBNE R3, $16, 2(PC) - VLEIB $10, $1, H2_0 - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, H0_1, H1_1, M5, T_10) - SUB $16, R3 - CMPBLE R3, $0, next // this condition must always hold true! - -b2: - CMPBLE R3, $16, b1 - - // 2 blocks remaining - - // setup [r²,r] - VSLDB $8, R_0, R_0, R_0 - VSLDB $8, R_1, R_1, R_1 - VSLDB $8, R_2, R_2, R_2 - VSLDB $8, R5_1, R5_1, R5_1 - VSLDB $8, R5_2, R5_2, R5_2 - - VLVGG $1, RSAVE_0, R_0 - VLVGG $1, RSAVE_1, R_1 - VLVGG $1, RSAVE_2, R_2 - VLVGG $1, R5SAVE_1, R5_1 - VLVGG $1, R5SAVE_2, R5_2 - - // setup [h0, h1] - VSLDB $8, H0_0, H0_0, H0_0 - VSLDB $8, H1_0, H1_0, H1_0 - VSLDB $8, H2_0, H2_0, H2_0 - VO H0_1, H0_0, H0_0 - VO H1_1, H1_0, H1_0 - VO H2_1, H2_0, H2_0 - VZERO H0_1 - VZERO H1_1 - VZERO H2_1 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - - // H*[r**2, r] - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, T_10, M0, M1, M2, M3, M4, T_4, T_5, T_2, T_7, T_8, T_9) - VMRHG V0, H0_1, H0_0 - VMRHG V0, H1_1, H1_0 - VMRHG V0, H2_1, H2_0 - VMRLG V0, H0_1, H0_1 - VMRLG V0, H1_1, H1_1 - VMRLG V0, H2_1, H2_1 - - // move h to the left and 0s at the right - VSLDB $8, H0_0, H0_0, H0_0 - VSLDB $8, H1_0, H1_0, H1_0 - VSLDB $8, H2_0, H2_0, H2_0 - - // get message blocks and append 1 to start - SUB $17, R3 - VL (R2), M0 - VLL R3, 16(R2), M1 - ADD $1, R3 - MOVBZ $1, R0 - CMPBEQ R3, $16, 2(PC) - VLVGB R3, R0, M1 - VZERO T_6 - VZERO T_7 - VZERO T_8 - EXPACC2(M0, T_6, T_7, T_8, T_1, T_2, T_3) - EXPACC2(M1, T_6, T_7, T_8, T_1, T_2, T_3) - VLEIB $2, $1, T_8 - CMPBNE R3, $16, 2(PC) - VLEIB $10, $1, T_8 - - // add [m0, m1] to h - VAG H0_0, T_6, H0_0 - VAG H1_0, T_7, H1_0 - VAG H2_0, T_8, H2_0 - - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - VZERO T_10 - VZERO M0 - - // at this point R_0 .. R5_2 look like [r**2, r] - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M2, M3, M4, M5, T_10, M0, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M2, M3, M4, M5, T_9, H0_1, H1_1, H2_1, T_10) - SUB $16, R3, R3 - CMPBLE R3, $0, next - -b1: - CMPBLE R3, $0, next - - // 1 block remaining - - // setup [r²,r] - VSLDB $8, R_0, R_0, R_0 - VSLDB $8, R_1, R_1, R_1 - VSLDB $8, R_2, R_2, R_2 - VSLDB $8, R5_1, R5_1, R5_1 - VSLDB $8, R5_2, R5_2, R5_2 - - VLVGG $1, RSAVE_0, R_0 - VLVGG $1, RSAVE_1, R_1 - VLVGG $1, RSAVE_2, R_2 - VLVGG $1, R5SAVE_1, R5_1 - VLVGG $1, R5SAVE_2, R5_2 - - // setup [h0, h1] - VSLDB $8, H0_0, H0_0, H0_0 - VSLDB $8, H1_0, H1_0, H1_0 - VSLDB $8, H2_0, H2_0, H2_0 - VO H0_1, H0_0, H0_0 - VO H1_1, H1_0, H1_0 - VO H2_1, H2_0, H2_0 - VZERO H0_1 - VZERO H1_1 - VZERO H2_1 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - - // H*[r**2, r] - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) - - // set up [0, m0] limbs - SUB $1, R3 - VLL R3, (R2), M0 - ADD $1, R3 - MOVBZ $1, R0 - CMPBEQ R3, $16, 2(PC) - VLVGB R3, R0, M0 - VZERO T_1 - VZERO T_2 - VZERO T_3 - EXPACC2(M0, T_1, T_2, T_3, T_4, T_5, T_6)// limbs: [0, m] - CMPBNE R3, $16, 2(PC) - VLEIB $10, $1, T_3 - - // h+m0 - VAQ H0_0, T_1, H0_0 - VAQ H1_0, T_2, H1_0 - VAQ H2_0, T_3, H2_0 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) - - BR next - -square: - // setup [r²,r] - VSLDB $8, R_0, R_0, R_0 - VSLDB $8, R_1, R_1, R_1 - VSLDB $8, R_2, R_2, R_2 - VSLDB $8, R5_1, R5_1, R5_1 - VSLDB $8, R5_2, R5_2, R5_2 - - VLVGG $1, RSAVE_0, R_0 - VLVGG $1, RSAVE_1, R_1 - VLVGG $1, RSAVE_2, R_2 - VLVGG $1, R5SAVE_1, R5_1 - VLVGG $1, R5SAVE_2, R5_2 - - // setup [h0, h1] - VSLDB $8, H0_0, H0_0, H0_0 - VSLDB $8, H1_0, H1_0, H1_0 - VSLDB $8, H2_0, H2_0, H2_0 - VO H0_1, H0_0, H0_0 - VO H1_1, H1_0, H1_0 - VO H2_1, H2_0, H2_0 - VZERO H0_1 - VZERO H1_1 - VZERO H2_1 - - VZERO M0 - VZERO M1 - VZERO M2 - VZERO M3 - VZERO M4 - VZERO M5 - - // (h0*r**2) + (h1*r) - MULTIPLY(H0_0, H1_0, H2_0, H0_1, H1_1, H2_1, R_0, R_1, R_2, R5_1, R5_2, M0, M1, M2, M3, M4, M5, T_0, T_1, T_2, T_3, T_4, T_5, T_6, T_7, T_8, T_9) - REDUCE2(H0_0, H1_0, H2_0, M0, M1, M2, M3, M4, T_9, T_10, H0_1, M5) - BR next diff --git a/vendor/golang.org/x/crypto/ssh/certs.go b/vendor/golang.org/x/crypto/ssh/certs.go index 00ed9923e78..916c840b698 100644 --- a/vendor/golang.org/x/crypto/ssh/certs.go +++ b/vendor/golang.org/x/crypto/ssh/certs.go @@ -17,12 +17,14 @@ import ( // These constants from [PROTOCOL.certkeys] represent the algorithm names // for certificate types supported by this package. const ( - CertAlgoRSAv01 = "ssh-rsa-cert-v01@openssh.com" - CertAlgoDSAv01 = "ssh-dss-cert-v01@openssh.com" - CertAlgoECDSA256v01 = "ecdsa-sha2-nistp256-cert-v01@openssh.com" - CertAlgoECDSA384v01 = "ecdsa-sha2-nistp384-cert-v01@openssh.com" - CertAlgoECDSA521v01 = "ecdsa-sha2-nistp521-cert-v01@openssh.com" - CertAlgoED25519v01 = "ssh-ed25519-cert-v01@openssh.com" + CertAlgoRSAv01 = "ssh-rsa-cert-v01@openssh.com" + CertAlgoDSAv01 = "ssh-dss-cert-v01@openssh.com" + CertAlgoECDSA256v01 = "ecdsa-sha2-nistp256-cert-v01@openssh.com" + CertAlgoECDSA384v01 = "ecdsa-sha2-nistp384-cert-v01@openssh.com" + CertAlgoECDSA521v01 = "ecdsa-sha2-nistp521-cert-v01@openssh.com" + CertAlgoSKECDSA256v01 = "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com" + CertAlgoED25519v01 = "ssh-ed25519-cert-v01@openssh.com" + CertAlgoSKED25519v01 = "sk-ssh-ed25519-cert-v01@openssh.com" ) // Certificate types distinguish between host and user @@ -37,6 +39,7 @@ const ( type Signature struct { Format string Blob []byte + Rest []byte `ssh:"rest"` } // CertTimeInfinity can be used for OpenSSHCertV01.ValidBefore to indicate that @@ -411,8 +414,8 @@ func (c *CertChecker) CheckCert(principal string, cert *Certificate) error { return nil } -// SignCert sets c.SignatureKey to the authority's public key and stores a -// Signature, by authority, in the certificate. +// SignCert signs the certificate with an authority, setting the Nonce, +// SignatureKey, and Signature fields. func (c *Certificate) SignCert(rand io.Reader, authority Signer) error { c.Nonce = make([]byte, 32) if _, err := io.ReadFull(rand, c.Nonce); err != nil { @@ -429,12 +432,14 @@ func (c *Certificate) SignCert(rand io.Reader, authority Signer) error { } var certAlgoNames = map[string]string{ - KeyAlgoRSA: CertAlgoRSAv01, - KeyAlgoDSA: CertAlgoDSAv01, - KeyAlgoECDSA256: CertAlgoECDSA256v01, - KeyAlgoECDSA384: CertAlgoECDSA384v01, - KeyAlgoECDSA521: CertAlgoECDSA521v01, - KeyAlgoED25519: CertAlgoED25519v01, + KeyAlgoRSA: CertAlgoRSAv01, + KeyAlgoDSA: CertAlgoDSAv01, + KeyAlgoECDSA256: CertAlgoECDSA256v01, + KeyAlgoECDSA384: CertAlgoECDSA384v01, + KeyAlgoECDSA521: CertAlgoECDSA521v01, + KeyAlgoSKECDSA256: CertAlgoSKECDSA256v01, + KeyAlgoED25519: CertAlgoED25519v01, + KeyAlgoSKED25519: CertAlgoSKED25519v01, } // certToPrivAlgo returns the underlying algorithm for a certificate algorithm. @@ -518,6 +523,12 @@ func parseSignatureBody(in []byte) (out *Signature, rest []byte, ok bool) { return } + switch out.Format { + case KeyAlgoSKECDSA256, CertAlgoSKECDSA256v01, KeyAlgoSKED25519, CertAlgoSKED25519v01: + out.Rest = in + return out, nil, ok + } + return out, in, ok } diff --git a/vendor/golang.org/x/crypto/ssh/cipher.go b/vendor/golang.org/x/crypto/ssh/cipher.go index a65a923be3d..8bd6b3daff5 100644 --- a/vendor/golang.org/x/crypto/ssh/cipher.go +++ b/vendor/golang.org/x/crypto/ssh/cipher.go @@ -16,9 +16,8 @@ import ( "hash" "io" "io/ioutil" - "math/bits" - "golang.org/x/crypto/internal/chacha20" + "golang.org/x/crypto/chacha20" "golang.org/x/crypto/poly1305" ) @@ -120,7 +119,7 @@ var cipherModes = map[string]*cipherMode{ chacha20Poly1305ID: {64, 0, newChaCha20Cipher}, // CBC mode is insecure and so is not included in the default config. - // (See http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf). If absolutely + // (See https://www.ieee-security.org/TC/SP2013/papers/4977a526.pdf). If absolutely // needed, it's possible to specify a custom Config to enable it. // You should expect that an active attacker can recover plaintext if // you do. @@ -642,8 +641,8 @@ const chacha20Poly1305ID = "chacha20-poly1305@openssh.com" // the methods here also implement padding, which RFC4253 Section 6 // also requires of stream ciphers. type chacha20Poly1305Cipher struct { - lengthKey [8]uint32 - contentKey [8]uint32 + lengthKey [32]byte + contentKey [32]byte buf []byte } @@ -656,21 +655,21 @@ func newChaCha20Cipher(key, unusedIV, unusedMACKey []byte, unusedAlgs directionA buf: make([]byte, 256), } - for i := range c.contentKey { - c.contentKey[i] = binary.LittleEndian.Uint32(key[i*4 : (i+1)*4]) - } - for i := range c.lengthKey { - c.lengthKey[i] = binary.LittleEndian.Uint32(key[(i+8)*4 : (i+9)*4]) - } + copy(c.contentKey[:], key[:32]) + copy(c.lengthKey[:], key[32:]) return c, nil } func (c *chacha20Poly1305Cipher) readCipherPacket(seqNum uint32, r io.Reader) ([]byte, error) { - nonce := [3]uint32{0, 0, bits.ReverseBytes32(seqNum)} - s := chacha20.New(c.contentKey, nonce) - var polyKey [32]byte + nonce := make([]byte, 12) + binary.BigEndian.PutUint32(nonce[8:], seqNum) + s, err := chacha20.NewUnauthenticatedCipher(c.contentKey[:], nonce) + if err != nil { + return nil, err + } + var polyKey, discardBuf [32]byte s.XORKeyStream(polyKey[:], polyKey[:]) - s.Advance() // skip next 32 bytes + s.XORKeyStream(discardBuf[:], discardBuf[:]) // skip the next 32 bytes encryptedLength := c.buf[:4] if _, err := io.ReadFull(r, encryptedLength); err != nil { @@ -678,7 +677,11 @@ func (c *chacha20Poly1305Cipher) readCipherPacket(seqNum uint32, r io.Reader) ([ } var lenBytes [4]byte - chacha20.New(c.lengthKey, nonce).XORKeyStream(lenBytes[:], encryptedLength) + ls, err := chacha20.NewUnauthenticatedCipher(c.lengthKey[:], nonce) + if err != nil { + return nil, err + } + ls.XORKeyStream(lenBytes[:], encryptedLength) length := binary.BigEndian.Uint32(lenBytes[:]) if length > maxPacket { @@ -724,11 +727,15 @@ func (c *chacha20Poly1305Cipher) readCipherPacket(seqNum uint32, r io.Reader) ([ } func (c *chacha20Poly1305Cipher) writeCipherPacket(seqNum uint32, w io.Writer, rand io.Reader, payload []byte) error { - nonce := [3]uint32{0, 0, bits.ReverseBytes32(seqNum)} - s := chacha20.New(c.contentKey, nonce) - var polyKey [32]byte + nonce := make([]byte, 12) + binary.BigEndian.PutUint32(nonce[8:], seqNum) + s, err := chacha20.NewUnauthenticatedCipher(c.contentKey[:], nonce) + if err != nil { + return err + } + var polyKey, discardBuf [32]byte s.XORKeyStream(polyKey[:], polyKey[:]) - s.Advance() // skip next 32 bytes + s.XORKeyStream(discardBuf[:], discardBuf[:]) // skip the next 32 bytes // There is no blocksize, so fall back to multiple of 8 byte // padding, as described in RFC 4253, Sec 6. @@ -748,7 +755,11 @@ func (c *chacha20Poly1305Cipher) writeCipherPacket(seqNum uint32, w io.Writer, r } binary.BigEndian.PutUint32(c.buf, uint32(1+len(payload)+padding)) - chacha20.New(c.lengthKey, nonce).XORKeyStream(c.buf, c.buf[:4]) + ls, err := chacha20.NewUnauthenticatedCipher(c.lengthKey[:], nonce) + if err != nil { + return err + } + ls.XORKeyStream(c.buf, c.buf[:4]) c.buf[4] = byte(padding) copy(c.buf[5:], payload) packetEnd := 5 + len(payload) + padding diff --git a/vendor/golang.org/x/crypto/ssh/client_auth.go b/vendor/golang.org/x/crypto/ssh/client_auth.go index 0590070e220..f3265655eec 100644 --- a/vendor/golang.org/x/crypto/ssh/client_auth.go +++ b/vendor/golang.org/x/crypto/ssh/client_auth.go @@ -36,7 +36,7 @@ func (c *connection) clientAuthenticate(config *ClientConfig) error { // during the authentication phase the client first attempts the "none" method // then any untried methods suggested by the server. - tried := make(map[string]bool) + var tried []string var lastMethods []string sessionID := c.transport.getSessionID() @@ -49,7 +49,9 @@ func (c *connection) clientAuthenticate(config *ClientConfig) error { // success return nil } else if ok == authFailure { - tried[auth.method()] = true + if m := auth.method(); !contains(tried, m) { + tried = append(tried, m) + } } if methods == nil { methods = lastMethods @@ -61,7 +63,7 @@ func (c *connection) clientAuthenticate(config *ClientConfig) error { findNext: for _, a := range config.Auth { candidateMethod := a.method() - if tried[candidateMethod] { + if contains(tried, candidateMethod) { continue } for _, meth := range methods { @@ -72,16 +74,16 @@ func (c *connection) clientAuthenticate(config *ClientConfig) error { } } } - return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", keys(tried)) + return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", tried) } -func keys(m map[string]bool) []string { - s := make([]string, 0, len(m)) - - for key := range m { - s = append(s, key) +func contains(list []string, e string) bool { + for _, s := range list { + if s == e { + return true + } } - return s + return false } // An AuthMethod represents an instance of an RFC 4252 authentication method. diff --git a/vendor/golang.org/x/crypto/ssh/internal/bcrypt_pbkdf/bcrypt_pbkdf.go b/vendor/golang.org/x/crypto/ssh/internal/bcrypt_pbkdf/bcrypt_pbkdf.go new file mode 100644 index 00000000000..af81d266546 --- /dev/null +++ b/vendor/golang.org/x/crypto/ssh/internal/bcrypt_pbkdf/bcrypt_pbkdf.go @@ -0,0 +1,93 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package bcrypt_pbkdf implements bcrypt_pbkdf(3) from OpenBSD. +// +// See https://flak.tedunangst.com/post/bcrypt-pbkdf and +// https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/lib/libutil/bcrypt_pbkdf.c. +package bcrypt_pbkdf + +import ( + "crypto/sha512" + "errors" + "golang.org/x/crypto/blowfish" +) + +const blockSize = 32 + +// Key derives a key from the password, salt and rounds count, returning a +// []byte of length keyLen that can be used as cryptographic key. +func Key(password, salt []byte, rounds, keyLen int) ([]byte, error) { + if rounds < 1 { + return nil, errors.New("bcrypt_pbkdf: number of rounds is too small") + } + if len(password) == 0 { + return nil, errors.New("bcrypt_pbkdf: empty password") + } + if len(salt) == 0 || len(salt) > 1<<20 { + return nil, errors.New("bcrypt_pbkdf: bad salt length") + } + if keyLen > 1024 { + return nil, errors.New("bcrypt_pbkdf: keyLen is too large") + } + + numBlocks := (keyLen + blockSize - 1) / blockSize + key := make([]byte, numBlocks*blockSize) + + h := sha512.New() + h.Write(password) + shapass := h.Sum(nil) + + shasalt := make([]byte, 0, sha512.Size) + cnt, tmp := make([]byte, 4), make([]byte, blockSize) + for block := 1; block <= numBlocks; block++ { + h.Reset() + h.Write(salt) + cnt[0] = byte(block >> 24) + cnt[1] = byte(block >> 16) + cnt[2] = byte(block >> 8) + cnt[3] = byte(block) + h.Write(cnt) + bcryptHash(tmp, shapass, h.Sum(shasalt)) + + out := make([]byte, blockSize) + copy(out, tmp) + for i := 2; i <= rounds; i++ { + h.Reset() + h.Write(tmp) + bcryptHash(tmp, shapass, h.Sum(shasalt)) + for j := 0; j < len(out); j++ { + out[j] ^= tmp[j] + } + } + + for i, v := range out { + key[i*numBlocks+(block-1)] = v + } + } + return key[:keyLen], nil +} + +var magic = []byte("OxychromaticBlowfishSwatDynamite") + +func bcryptHash(out, shapass, shasalt []byte) { + c, err := blowfish.NewSaltedCipher(shapass, shasalt) + if err != nil { + panic(err) + } + for i := 0; i < 64; i++ { + blowfish.ExpandKey(shasalt, c) + blowfish.ExpandKey(shapass, c) + } + copy(out, magic) + for i := 0; i < 32; i += 8 { + for j := 0; j < 64; j++ { + c.Encrypt(out[i:i+8], out[i:i+8]) + } + } + // Swap bytes due to different endianness. + for i := 0; i < 32; i += 4 { + out[i+3], out[i+2], out[i+1], out[i] = out[i], out[i+1], out[i+2], out[i+3] + } +} diff --git a/vendor/golang.org/x/crypto/ssh/kex.go b/vendor/golang.org/x/crypto/ssh/kex.go index 16072004b17..7eedb209fa7 100644 --- a/vendor/golang.org/x/crypto/ssh/kex.go +++ b/vendor/golang.org/x/crypto/ssh/kex.go @@ -212,7 +212,7 @@ func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handsha HostKey: hostKeyBytes, Signature: sig, Hash: crypto.SHA1, - }, nil + }, err } // ecdh performs Elliptic Curve Diffie-Hellman key exchange as @@ -572,7 +572,7 @@ func (gex *dhGEXSHA) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, e return new(big.Int).Exp(theirPublic, myPrivate, gex.p), nil } -func (gex *dhGEXSHA) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) { +func (gex dhGEXSHA) Client(c packetConn, randSource io.Reader, magics *handshakeMagics) (*kexResult, error) { // Send GexRequest kexDHGexRequest := kexDHGexRequestMsg{ MinBits: dhGroupExchangeMinimumBits, @@ -677,7 +677,7 @@ func (gex *dhGEXSHA) Client(c packetConn, randSource io.Reader, magics *handshak // Server half implementation of the Diffie Hellman Key Exchange with SHA1 and SHA256. // // This is a minimal implementation to satisfy the automated tests. -func (gex *dhGEXSHA) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { +func (gex dhGEXSHA) Server(c packetConn, randSource io.Reader, magics *handshakeMagics, priv Signer) (result *kexResult, err error) { // Receive GexRequest packet, err := c.readPacket() if err != nil { diff --git a/vendor/golang.org/x/crypto/ssh/keys.go b/vendor/golang.org/x/crypto/ssh/keys.go index 969804794fb..31f26349a05 100644 --- a/vendor/golang.org/x/crypto/ssh/keys.go +++ b/vendor/golang.org/x/crypto/ssh/keys.go @@ -7,6 +7,8 @@ package ssh import ( "bytes" "crypto" + "crypto/aes" + "crypto/cipher" "crypto/dsa" "crypto/ecdsa" "crypto/elliptic" @@ -25,17 +27,20 @@ import ( "strings" "golang.org/x/crypto/ed25519" + "golang.org/x/crypto/ssh/internal/bcrypt_pbkdf" ) // These constants represent the algorithm names for key types supported by this // package. const ( - KeyAlgoRSA = "ssh-rsa" - KeyAlgoDSA = "ssh-dss" - KeyAlgoECDSA256 = "ecdsa-sha2-nistp256" - KeyAlgoECDSA384 = "ecdsa-sha2-nistp384" - KeyAlgoECDSA521 = "ecdsa-sha2-nistp521" - KeyAlgoED25519 = "ssh-ed25519" + KeyAlgoRSA = "ssh-rsa" + KeyAlgoDSA = "ssh-dss" + KeyAlgoECDSA256 = "ecdsa-sha2-nistp256" + KeyAlgoSKECDSA256 = "sk-ecdsa-sha2-nistp256@openssh.com" + KeyAlgoECDSA384 = "ecdsa-sha2-nistp384" + KeyAlgoECDSA521 = "ecdsa-sha2-nistp521" + KeyAlgoED25519 = "ssh-ed25519" + KeyAlgoSKED25519 = "sk-ssh-ed25519@openssh.com" ) // These constants represent non-default signature algorithms that are supported @@ -58,9 +63,13 @@ func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err err return parseDSA(in) case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521: return parseECDSA(in) + case KeyAlgoSKECDSA256: + return parseSKECDSA(in) case KeyAlgoED25519: return parseED25519(in) - case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01: + case KeyAlgoSKED25519: + return parseSKEd25519(in) + case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoSKECDSA256v01, CertAlgoED25519v01, CertAlgoSKED25519v01: cert, err := parseCert(in, certToPrivAlgo(algo)) if err != nil { return nil, nil, err @@ -553,9 +562,11 @@ func parseED25519(in []byte) (out PublicKey, rest []byte, err error) { return nil, nil, err } - key := ed25519.PublicKey(w.KeyBytes) + if l := len(w.KeyBytes); l != ed25519.PublicKeySize { + return nil, nil, fmt.Errorf("invalid size %d for Ed25519 public key", l) + } - return (ed25519PublicKey)(key), w.Rest, nil + return ed25519PublicKey(w.KeyBytes), w.Rest, nil } func (k ed25519PublicKey) Marshal() []byte { @@ -573,9 +584,11 @@ func (k ed25519PublicKey) Verify(b []byte, sig *Signature) error { if sig.Format != k.Type() { return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) } + if l := len(k); l != ed25519.PublicKeySize { + return fmt.Errorf("ssh: invalid size %d for Ed25519 public key", l) + } - edKey := (ed25519.PublicKey)(k) - if ok := ed25519.Verify(edKey, b, sig.Blob); !ok { + if ok := ed25519.Verify(ed25519.PublicKey(k), b, sig.Blob); !ok { return errors.New("ssh: signature did not verify") } @@ -685,6 +698,224 @@ func (k *ecdsaPublicKey) CryptoPublicKey() crypto.PublicKey { return (*ecdsa.PublicKey)(k) } +// skFields holds the additional fields present in U2F/FIDO2 signatures. +// See openssh/PROTOCOL.u2f 'SSH U2F Signatures' for details. +type skFields struct { + // Flags contains U2F/FIDO2 flags such as 'user present' + Flags byte + // Counter is a monotonic signature counter which can be + // used to detect concurrent use of a private key, should + // it be extracted from hardware. + Counter uint32 +} + +type skECDSAPublicKey struct { + // application is a URL-like string, typically "ssh:" for SSH. + // see openssh/PROTOCOL.u2f for details. + application string + ecdsa.PublicKey +} + +func (k *skECDSAPublicKey) Type() string { + return KeyAlgoSKECDSA256 +} + +func (k *skECDSAPublicKey) nistID() string { + return "nistp256" +} + +func parseSKECDSA(in []byte) (out PublicKey, rest []byte, err error) { + var w struct { + Curve string + KeyBytes []byte + Application string + Rest []byte `ssh:"rest"` + } + + if err := Unmarshal(in, &w); err != nil { + return nil, nil, err + } + + key := new(skECDSAPublicKey) + key.application = w.Application + + if w.Curve != "nistp256" { + return nil, nil, errors.New("ssh: unsupported curve") + } + key.Curve = elliptic.P256() + + key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes) + if key.X == nil || key.Y == nil { + return nil, nil, errors.New("ssh: invalid curve point") + } + + return key, w.Rest, nil +} + +func (k *skECDSAPublicKey) Marshal() []byte { + // See RFC 5656, section 3.1. + keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y) + w := struct { + Name string + ID string + Key []byte + Application string + }{ + k.Type(), + k.nistID(), + keyBytes, + k.application, + } + + return Marshal(&w) +} + +func (k *skECDSAPublicKey) Verify(data []byte, sig *Signature) error { + if sig.Format != k.Type() { + return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) + } + + h := ecHash(k.Curve).New() + h.Write([]byte(k.application)) + appDigest := h.Sum(nil) + + h.Reset() + h.Write(data) + dataDigest := h.Sum(nil) + + var ecSig struct { + R *big.Int + S *big.Int + } + if err := Unmarshal(sig.Blob, &ecSig); err != nil { + return err + } + + var skf skFields + if err := Unmarshal(sig.Rest, &skf); err != nil { + return err + } + + blob := struct { + ApplicationDigest []byte `ssh:"rest"` + Flags byte + Counter uint32 + MessageDigest []byte `ssh:"rest"` + }{ + appDigest, + skf.Flags, + skf.Counter, + dataDigest, + } + + original := Marshal(blob) + + h.Reset() + h.Write(original) + digest := h.Sum(nil) + + if ecdsa.Verify((*ecdsa.PublicKey)(&k.PublicKey), digest, ecSig.R, ecSig.S) { + return nil + } + return errors.New("ssh: signature did not verify") +} + +type skEd25519PublicKey struct { + // application is a URL-like string, typically "ssh:" for SSH. + // see openssh/PROTOCOL.u2f for details. + application string + ed25519.PublicKey +} + +func (k *skEd25519PublicKey) Type() string { + return KeyAlgoSKED25519 +} + +func parseSKEd25519(in []byte) (out PublicKey, rest []byte, err error) { + var w struct { + KeyBytes []byte + Application string + Rest []byte `ssh:"rest"` + } + + if err := Unmarshal(in, &w); err != nil { + return nil, nil, err + } + + if l := len(w.KeyBytes); l != ed25519.PublicKeySize { + return nil, nil, fmt.Errorf("invalid size %d for Ed25519 public key", l) + } + + key := new(skEd25519PublicKey) + key.application = w.Application + key.PublicKey = ed25519.PublicKey(w.KeyBytes) + + return key, w.Rest, nil +} + +func (k *skEd25519PublicKey) Marshal() []byte { + w := struct { + Name string + KeyBytes []byte + Application string + }{ + KeyAlgoSKED25519, + []byte(k.PublicKey), + k.application, + } + return Marshal(&w) +} + +func (k *skEd25519PublicKey) Verify(data []byte, sig *Signature) error { + if sig.Format != k.Type() { + return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) + } + if l := len(k.PublicKey); l != ed25519.PublicKeySize { + return fmt.Errorf("invalid size %d for Ed25519 public key", l) + } + + h := sha256.New() + h.Write([]byte(k.application)) + appDigest := h.Sum(nil) + + h.Reset() + h.Write(data) + dataDigest := h.Sum(nil) + + var edSig struct { + Signature []byte `ssh:"rest"` + } + + if err := Unmarshal(sig.Blob, &edSig); err != nil { + return err + } + + var skf skFields + if err := Unmarshal(sig.Rest, &skf); err != nil { + return err + } + + blob := struct { + ApplicationDigest []byte `ssh:"rest"` + Flags byte + Counter uint32 + MessageDigest []byte `ssh:"rest"` + }{ + appDigest, + skf.Flags, + skf.Counter, + dataDigest, + } + + original := Marshal(blob) + + if ok := ed25519.Verify(k.PublicKey, original, edSig.Signature); !ok { + return errors.New("ssh: signature did not verify") + } + + return nil +} + // NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey, // *ecdsa.PrivateKey or any other crypto.Signer and returns a // corresponding Signer instance. ECDSA keys must use P-256, P-384 or @@ -830,14 +1061,18 @@ func NewPublicKey(key interface{}) (PublicKey, error) { case *dsa.PublicKey: return (*dsaPublicKey)(key), nil case ed25519.PublicKey: - return (ed25519PublicKey)(key), nil + if l := len(key); l != ed25519.PublicKeySize { + return nil, fmt.Errorf("ssh: invalid size %d for Ed25519 public key", l) + } + return ed25519PublicKey(key), nil default: return nil, fmt.Errorf("ssh: unsupported key type %T", key) } } // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports -// the same keys as ParseRawPrivateKey. +// the same keys as ParseRawPrivateKey. If the private key is encrypted, it +// will return a PassphraseMissingError. func ParsePrivateKey(pemBytes []byte) (Signer, error) { key, err := ParseRawPrivateKey(pemBytes) if err != nil { @@ -850,8 +1085,8 @@ func ParsePrivateKey(pemBytes []byte) (Signer, error) { // ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private // key and passphrase. It supports the same keys as // ParseRawPrivateKeyWithPassphrase. -func ParsePrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (Signer, error) { - key, err := ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase) +func ParsePrivateKeyWithPassphrase(pemBytes, passphrase []byte) (Signer, error) { + key, err := ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase) if err != nil { return nil, err } @@ -867,8 +1102,21 @@ func encryptedBlock(block *pem.Block) bool { return strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED") } +// A PassphraseMissingError indicates that parsing this private key requires a +// passphrase. Use ParsePrivateKeyWithPassphrase. +type PassphraseMissingError struct { + // PublicKey will be set if the private key format includes an unencrypted + // public key along with the encrypted private key. + PublicKey PublicKey +} + +func (*PassphraseMissingError) Error() string { + return "ssh: this private key is passphrase protected" +} + // ParseRawPrivateKey returns a private key from a PEM encoded private key. It -// supports RSA (PKCS#1), PKCS#8, DSA (OpenSSL), and ECDSA private keys. +// supports RSA (PKCS#1), PKCS#8, DSA (OpenSSL), and ECDSA private keys. If the +// private key is encrypted, it will return a PassphraseMissingError. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) { block, _ := pem.Decode(pemBytes) if block == nil { @@ -876,7 +1124,7 @@ func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) { } if encryptedBlock(block) { - return nil, errors.New("ssh: cannot decode encrypted private keys") + return nil, &PassphraseMissingError{} } switch block.Type { @@ -890,33 +1138,35 @@ func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) { case "DSA PRIVATE KEY": return ParseDSAPrivateKey(block.Bytes) case "OPENSSH PRIVATE KEY": - return parseOpenSSHPrivateKey(block.Bytes) + return parseOpenSSHPrivateKey(block.Bytes, unencryptedOpenSSHKey) default: return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type) } } // ParseRawPrivateKeyWithPassphrase returns a private key decrypted with -// passphrase from a PEM encoded private key. If wrong passphrase, return -// x509.IncorrectPasswordError. -func ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (interface{}, error) { +// passphrase from a PEM encoded private key. If the passphrase is wrong, it +// will return x509.IncorrectPasswordError. +func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{}, error) { block, _ := pem.Decode(pemBytes) if block == nil { return nil, errors.New("ssh: no key found") } - buf := block.Bytes - if encryptedBlock(block) { - if x509.IsEncryptedPEMBlock(block) { - var err error - buf, err = x509.DecryptPEMBlock(block, passPhrase) - if err != nil { - if err == x509.IncorrectPasswordError { - return nil, err - } - return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err) - } + if block.Type == "OPENSSH PRIVATE KEY" { + return parseOpenSSHPrivateKey(block.Bytes, passphraseProtectedOpenSSHKey(passphrase)) + } + + if !encryptedBlock(block) || !x509.IsEncryptedPEMBlock(block) { + return nil, errors.New("ssh: not an encrypted key") + } + + buf, err := x509.DecryptPEMBlock(block, passphrase) + if err != nil { + if err == x509.IncorrectPasswordError { + return nil, err } + return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err) } switch block.Type { @@ -926,8 +1176,6 @@ func ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (interface{}, return x509.ParseECPrivateKey(buf) case "DSA PRIVATE KEY": return ParseDSAPrivateKey(buf) - case "OPENSSH PRIVATE KEY": - return parseOpenSSHPrivateKey(buf) default: return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type) } @@ -965,9 +1213,68 @@ func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) { }, nil } -// Implemented based on the documentation at -// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key -func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) { +func unencryptedOpenSSHKey(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) { + if kdfName != "none" || cipherName != "none" { + return nil, &PassphraseMissingError{} + } + if kdfOpts != "" { + return nil, errors.New("ssh: invalid openssh private key") + } + return privKeyBlock, nil +} + +func passphraseProtectedOpenSSHKey(passphrase []byte) openSSHDecryptFunc { + return func(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) { + if kdfName == "none" || cipherName == "none" { + return nil, errors.New("ssh: key is not password protected") + } + if kdfName != "bcrypt" { + return nil, fmt.Errorf("ssh: unknown KDF %q, only supports %q", kdfName, "bcrypt") + } + + var opts struct { + Salt string + Rounds uint32 + } + if err := Unmarshal([]byte(kdfOpts), &opts); err != nil { + return nil, err + } + + k, err := bcrypt_pbkdf.Key(passphrase, []byte(opts.Salt), int(opts.Rounds), 32+16) + if err != nil { + return nil, err + } + key, iv := k[:32], k[32:] + + c, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + switch cipherName { + case "aes256-ctr": + ctr := cipher.NewCTR(c, iv) + ctr.XORKeyStream(privKeyBlock, privKeyBlock) + case "aes256-cbc": + if len(privKeyBlock)%c.BlockSize() != 0 { + return nil, fmt.Errorf("ssh: invalid encrypted private key length, not a multiple of the block size") + } + cbc := cipher.NewCBCDecrypter(c, iv) + cbc.CryptBlocks(privKeyBlock, privKeyBlock) + default: + return nil, fmt.Errorf("ssh: unknown cipher %q, only supports %q or %q", cipherName, "aes256-ctr", "aes256-cbc") + } + + return privKeyBlock, nil + } +} + +type openSSHDecryptFunc func(CipherName, KdfName, KdfOpts string, PrivKeyBlock []byte) ([]byte, error) + +// parseOpenSSHPrivateKey parses an OpenSSH private key, using the decrypt +// function to unwrap the encrypted portion. unencryptedOpenSSHKey can be used +// as the decrypt function to parse an unencrypted private key. See +// https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key. +func parseOpenSSHPrivateKey(key []byte, decrypt openSSHDecryptFunc) (crypto.PrivateKey, error) { const magic = "openssh-key-v1\x00" if len(key) < len(magic) || string(key[:len(magic)]) != magic { return nil, errors.New("ssh: invalid openssh private key format") @@ -986,9 +1293,22 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) { if err := Unmarshal(remaining, &w); err != nil { return nil, err } + if w.NumKeys != 1 { + // We only support single key files, and so does OpenSSH. + // https://github.com/openssh/openssh-portable/blob/4103a3ec7/sshkey.c#L4171 + return nil, errors.New("ssh: multi-key files are not supported") + } - if w.KdfName != "none" || w.CipherName != "none" { - return nil, errors.New("ssh: cannot decode encrypted private keys") + privKeyBlock, err := decrypt(w.CipherName, w.KdfName, w.KdfOpts, w.PrivKeyBlock) + if err != nil { + if err, ok := err.(*PassphraseMissingError); ok { + pub, errPub := ParsePublicKey(w.PubKey) + if errPub != nil { + return nil, fmt.Errorf("ssh: failed to parse embedded public key: %v", errPub) + } + err.PublicKey = pub + } + return nil, err } pk1 := struct { @@ -998,15 +1318,13 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) { Rest []byte `ssh:"rest"` }{} - if err := Unmarshal(w.PrivKeyBlock, &pk1); err != nil { - return nil, err - } - - if pk1.Check1 != pk1.Check2 { - return nil, errors.New("ssh: checkint mismatch") + if err := Unmarshal(privKeyBlock, &pk1); err != nil || pk1.Check1 != pk1.Check2 { + if w.CipherName != "none" { + return nil, x509.IncorrectPasswordError + } + return nil, errors.New("ssh: malformed OpenSSH key") } - // we only handle ed25519 and rsa keys currently switch pk1.Keytype { case KeyAlgoRSA: // https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L2760-L2773 @@ -1025,10 +1343,8 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) { return nil, err } - for i, b := range key.Pad { - if int(b) != i+1 { - return nil, errors.New("ssh: padding not as expected") - } + if err := checkOpenSSHKeyPadding(key.Pad); err != nil { + return nil, err } pk := &rsa.PrivateKey{ @@ -1063,20 +1379,78 @@ func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) { return nil, errors.New("ssh: private key unexpected length") } - for i, b := range key.Pad { - if int(b) != i+1 { - return nil, errors.New("ssh: padding not as expected") - } + if err := checkOpenSSHKeyPadding(key.Pad); err != nil { + return nil, err } pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize)) copy(pk, key.Priv) return &pk, nil + case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521: + key := struct { + Curve string + Pub []byte + D *big.Int + Comment string + Pad []byte `ssh:"rest"` + }{} + + if err := Unmarshal(pk1.Rest, &key); err != nil { + return nil, err + } + + if err := checkOpenSSHKeyPadding(key.Pad); err != nil { + return nil, err + } + + var curve elliptic.Curve + switch key.Curve { + case "nistp256": + curve = elliptic.P256() + case "nistp384": + curve = elliptic.P384() + case "nistp521": + curve = elliptic.P521() + default: + return nil, errors.New("ssh: unhandled elliptic curve: " + key.Curve) + } + + X, Y := elliptic.Unmarshal(curve, key.Pub) + if X == nil || Y == nil { + return nil, errors.New("ssh: failed to unmarshal public key") + } + + if key.D.Cmp(curve.Params().N) >= 0 { + return nil, errors.New("ssh: scalar is out of range") + } + + x, y := curve.ScalarBaseMult(key.D.Bytes()) + if x.Cmp(X) != 0 || y.Cmp(Y) != 0 { + return nil, errors.New("ssh: public key does not match private key") + } + + return &ecdsa.PrivateKey{ + PublicKey: ecdsa.PublicKey{ + Curve: curve, + X: X, + Y: Y, + }, + D: key.D, + }, nil default: return nil, errors.New("ssh: unhandled key type") } } +func checkOpenSSHKeyPadding(pad []byte) error { + for i, b := range pad { + if int(b) != i+1 { + return errors.New("ssh: padding not as expected") + } + } + return nil +} + // FingerprintLegacyMD5 returns the user presentation of the key's // fingerprint as described by RFC 4716 section 4. func FingerprintLegacyMD5(pubKey PublicKey) string { diff --git a/vendor/golang.org/x/crypto/ssh/mux.go b/vendor/golang.org/x/crypto/ssh/mux.go index f19016270e8..9654c01869a 100644 --- a/vendor/golang.org/x/crypto/ssh/mux.go +++ b/vendor/golang.org/x/crypto/ssh/mux.go @@ -240,7 +240,7 @@ func (m *mux) onePacket() error { id := binary.BigEndian.Uint32(packet[1:]) ch := m.chanList.getChan(id) if ch == nil { - return fmt.Errorf("ssh: invalid channel %d", id) + return m.handleUnknownChannelPacket(id, packet) } return ch.handlePacket(packet) @@ -328,3 +328,24 @@ func (m *mux) openChannel(chanType string, extra []byte) (*channel, error) { return nil, fmt.Errorf("ssh: unexpected packet in response to channel open: %T", msg) } } + +func (m *mux) handleUnknownChannelPacket(id uint32, packet []byte) error { + msg, err := decode(packet) + if err != nil { + return err + } + + switch msg := msg.(type) { + // RFC 4254 section 5.4 says unrecognized channel requests should + // receive a failure response. + case *channelRequestMsg: + if msg.WantReply { + return m.sendMessage(channelRequestFailureMsg{ + PeersID: msg.PeersID, + }) + } + return nil + default: + return fmt.Errorf("ssh: invalid channel %d", id) + } +} diff --git a/vendor/golang.org/x/crypto/ssh/server.go b/vendor/golang.org/x/crypto/ssh/server.go index 7a5a1d7ad39..7d42a8c88d2 100644 --- a/vendor/golang.org/x/crypto/ssh/server.go +++ b/vendor/golang.org/x/crypto/ssh/server.go @@ -284,8 +284,8 @@ func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) func isAcceptableAlgo(algo string) bool { switch algo { - case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, KeyAlgoED25519, - CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01: + case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, KeyAlgoSKECDSA256, KeyAlgoED25519, KeyAlgoSKED25519, + CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoSKECDSA256v01, CertAlgoED25519v01, CertAlgoSKED25519v01: return true } return false diff --git a/vendor/golang.org/x/lint/.travis.yml b/vendor/golang.org/x/lint/.travis.yml new file mode 100644 index 00000000000..50553ebd004 --- /dev/null +++ b/vendor/golang.org/x/lint/.travis.yml @@ -0,0 +1,19 @@ +sudo: false +language: go +go: + - 1.10.x + - 1.11.x + - master + +go_import_path: golang.org/x/lint + +install: + - go get -t -v ./... + +script: + - go test -v -race ./... + +matrix: + allow_failures: + - go: master + fast_finish: true diff --git a/vendor/golang.org/x/lint/CONTRIBUTING.md b/vendor/golang.org/x/lint/CONTRIBUTING.md new file mode 100644 index 00000000000..1fadda62d2f --- /dev/null +++ b/vendor/golang.org/x/lint/CONTRIBUTING.md @@ -0,0 +1,15 @@ +# Contributing to Golint + +## Before filing an issue: + +### Are you having trouble building golint? + +Check you have the latest version of its dependencies. Run +``` +go get -u golang.org/x/lint/golint +``` +If you still have problems, consider searching for existing issues before filing a new issue. + +## Before sending a pull request: + +Have you understood the purpose of golint? Make sure to carefully read `README`. diff --git a/vendor/golang.org/x/lint/LICENSE b/vendor/golang.org/x/lint/LICENSE new file mode 100644 index 00000000000..65d761bc9f2 --- /dev/null +++ b/vendor/golang.org/x/lint/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2013 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/lint/README.md b/vendor/golang.org/x/lint/README.md new file mode 100644 index 00000000000..4968b13aef7 --- /dev/null +++ b/vendor/golang.org/x/lint/README.md @@ -0,0 +1,88 @@ +Golint is a linter for Go source code. + +[![Build Status](https://travis-ci.org/golang/lint.svg?branch=master)](https://travis-ci.org/golang/lint) + +## Installation + +Golint requires a +[supported release of Go](https://golang.org/doc/devel/release.html#policy). + + go get -u golang.org/x/lint/golint + +To find out where `golint` was installed you can run `go list -f {{.Target}} golang.org/x/lint/golint`. For `golint` to be used globally add that directory to the `$PATH` environment setting. + +## Usage + +Invoke `golint` with one or more filenames, directories, or packages named +by its import path. Golint uses the same +[import path syntax](https://golang.org/cmd/go/#hdr-Import_path_syntax) as +the `go` command and therefore +also supports relative import paths like `./...`. Additionally the `...` +wildcard can be used as suffix on relative and absolute file paths to recurse +into them. + +The output of this tool is a list of suggestions in Vim quickfix format, +which is accepted by lots of different editors. + +## Purpose + +Golint differs from gofmt. Gofmt reformats Go source code, whereas +golint prints out style mistakes. + +Golint differs from govet. Govet is concerned with correctness, whereas +golint is concerned with coding style. Golint is in use at Google, and it +seeks to match the accepted style of the open source Go project. + +The suggestions made by golint are exactly that: suggestions. +Golint is not perfect, and has both false positives and false negatives. +Do not treat its output as a gold standard. We will not be adding pragmas +or other knobs to suppress specific warnings, so do not expect or require +code to be completely "lint-free". +In short, this tool is not, and will never be, trustworthy enough for its +suggestions to be enforced automatically, for example as part of a build process. +Golint makes suggestions for many of the mechanically checkable items listed in +[Effective Go](https://golang.org/doc/effective_go.html) and the +[CodeReviewComments wiki page](https://golang.org/wiki/CodeReviewComments). + +## Scope + +Golint is meant to carry out the stylistic conventions put forth in +[Effective Go](https://golang.org/doc/effective_go.html) and +[CodeReviewComments](https://golang.org/wiki/CodeReviewComments). +Changes that are not aligned with those documents will not be considered. + +## Contributions + +Contributions to this project are welcome provided they are [in scope](#scope), +though please send mail before starting work on anything major. +Contributors retain their copyright, so we need you to fill out +[a short form](https://developers.google.com/open-source/cla/individual) +before we can accept your contribution. + +## Vim + +Add this to your ~/.vimrc: + + set rtp+=$GOPATH/src/golang.org/x/lint/misc/vim + +If you have multiple entries in your GOPATH, replace `$GOPATH` with the right value. + +Running `:Lint` will run golint on the current file and populate the quickfix list. + +Optionally, add this to your `~/.vimrc` to automatically run `golint` on `:w` + + autocmd BufWritePost,FileWritePost *.go execute 'Lint' | cwindow + + +## Emacs + +Add this to your `.emacs` file: + + (add-to-list 'load-path (concat (getenv "GOPATH") "/src/golang.org/x/lint/misc/emacs/")) + (require 'golint) + +If you have multiple entries in your GOPATH, replace `$GOPATH` with the right value. + +Running M-x golint will run golint on the current file. + +For more usage, see [Compilation-Mode](http://www.gnu.org/software/emacs/manual/html_node/emacs/Compilation-Mode.html). diff --git a/vendor/golang.org/x/lint/go.mod b/vendor/golang.org/x/lint/go.mod new file mode 100644 index 00000000000..b32309c45fd --- /dev/null +++ b/vendor/golang.org/x/lint/go.mod @@ -0,0 +1,5 @@ +module golang.org/x/lint + +go 1.11 + +require golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7 diff --git a/vendor/golang.org/x/lint/go.sum b/vendor/golang.org/x/lint/go.sum new file mode 100644 index 00000000000..2ad45cae246 --- /dev/null +++ b/vendor/golang.org/x/lint/go.sum @@ -0,0 +1,12 @@ +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7 h1:EBZoQjiKKPaLbPrbpssUfuHtwM6KV/vb4U85g/cigFY= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/vendor/golang.org/x/lint/golint/golint.go b/vendor/golang.org/x/lint/golint/golint.go new file mode 100644 index 00000000000..ac024b6d26f --- /dev/null +++ b/vendor/golang.org/x/lint/golint/golint.go @@ -0,0 +1,159 @@ +// Copyright (c) 2013 The Go Authors. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd. + +// golint lints the Go source files named on its command line. +package main + +import ( + "flag" + "fmt" + "go/build" + "io/ioutil" + "os" + "path/filepath" + "strings" + + "golang.org/x/lint" +) + +var ( + minConfidence = flag.Float64("min_confidence", 0.8, "minimum confidence of a problem to print it") + setExitStatus = flag.Bool("set_exit_status", false, "set exit status to 1 if any issues are found") + suggestions int +) + +func usage() { + fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) + fmt.Fprintf(os.Stderr, "\tgolint [flags] # runs on package in current directory\n") + fmt.Fprintf(os.Stderr, "\tgolint [flags] [packages]\n") + fmt.Fprintf(os.Stderr, "\tgolint [flags] [directories] # where a '/...' suffix includes all sub-directories\n") + fmt.Fprintf(os.Stderr, "\tgolint [flags] [files] # all must belong to a single package\n") + fmt.Fprintf(os.Stderr, "Flags:\n") + flag.PrintDefaults() +} + +func main() { + flag.Usage = usage + flag.Parse() + + if flag.NArg() == 0 { + lintDir(".") + } else { + // dirsRun, filesRun, and pkgsRun indicate whether golint is applied to + // directory, file or package targets. The distinction affects which + // checks are run. It is no valid to mix target types. + var dirsRun, filesRun, pkgsRun int + var args []string + for _, arg := range flag.Args() { + if strings.HasSuffix(arg, "/...") && isDir(arg[:len(arg)-len("/...")]) { + dirsRun = 1 + for _, dirname := range allPackagesInFS(arg) { + args = append(args, dirname) + } + } else if isDir(arg) { + dirsRun = 1 + args = append(args, arg) + } else if exists(arg) { + filesRun = 1 + args = append(args, arg) + } else { + pkgsRun = 1 + args = append(args, arg) + } + } + + if dirsRun+filesRun+pkgsRun != 1 { + usage() + os.Exit(2) + } + switch { + case dirsRun == 1: + for _, dir := range args { + lintDir(dir) + } + case filesRun == 1: + lintFiles(args...) + case pkgsRun == 1: + for _, pkg := range importPaths(args) { + lintPackage(pkg) + } + } + } + + if *setExitStatus && suggestions > 0 { + fmt.Fprintf(os.Stderr, "Found %d lint suggestions; failing.\n", suggestions) + os.Exit(1) + } +} + +func isDir(filename string) bool { + fi, err := os.Stat(filename) + return err == nil && fi.IsDir() +} + +func exists(filename string) bool { + _, err := os.Stat(filename) + return err == nil +} + +func lintFiles(filenames ...string) { + files := make(map[string][]byte) + for _, filename := range filenames { + src, err := ioutil.ReadFile(filename) + if err != nil { + fmt.Fprintln(os.Stderr, err) + continue + } + files[filename] = src + } + + l := new(lint.Linter) + ps, err := l.LintFiles(files) + if err != nil { + fmt.Fprintf(os.Stderr, "%v\n", err) + return + } + for _, p := range ps { + if p.Confidence >= *minConfidence { + fmt.Printf("%v: %s\n", p.Position, p.Text) + suggestions++ + } + } +} + +func lintDir(dirname string) { + pkg, err := build.ImportDir(dirname, 0) + lintImportedPackage(pkg, err) +} + +func lintPackage(pkgname string) { + pkg, err := build.Import(pkgname, ".", 0) + lintImportedPackage(pkg, err) +} + +func lintImportedPackage(pkg *build.Package, err error) { + if err != nil { + if _, nogo := err.(*build.NoGoError); nogo { + // Don't complain if the failure is due to no Go source files. + return + } + fmt.Fprintln(os.Stderr, err) + return + } + + var files []string + files = append(files, pkg.GoFiles...) + files = append(files, pkg.CgoFiles...) + files = append(files, pkg.TestGoFiles...) + if pkg.Dir != "." { + for i, f := range files { + files[i] = filepath.Join(pkg.Dir, f) + } + } + // TODO(dsymonds): Do foo_test too (pkg.XTestGoFiles) + + lintFiles(files...) +} diff --git a/vendor/golang.org/x/lint/golint/import.go b/vendor/golang.org/x/lint/golint/import.go new file mode 100644 index 00000000000..2ba9dea7792 --- /dev/null +++ b/vendor/golang.org/x/lint/golint/import.go @@ -0,0 +1,309 @@ +package main + +/* + +This file holds a direct copy of the import path matching code of +https://github.com/golang/go/blob/master/src/cmd/go/main.go. It can be +replaced when https://golang.org/issue/8768 is resolved. + +It has been updated to follow upstream changes in a few ways. + +*/ + +import ( + "fmt" + "go/build" + "log" + "os" + "path" + "path/filepath" + "regexp" + "runtime" + "strings" +) + +var ( + buildContext = build.Default + goroot = filepath.Clean(runtime.GOROOT()) + gorootSrc = filepath.Join(goroot, "src") +) + +// importPathsNoDotExpansion returns the import paths to use for the given +// command line, but it does no ... expansion. +func importPathsNoDotExpansion(args []string) []string { + if len(args) == 0 { + return []string{"."} + } + var out []string + for _, a := range args { + // Arguments are supposed to be import paths, but + // as a courtesy to Windows developers, rewrite \ to / + // in command-line arguments. Handles .\... and so on. + if filepath.Separator == '\\' { + a = strings.Replace(a, `\`, `/`, -1) + } + + // Put argument in canonical form, but preserve leading ./. + if strings.HasPrefix(a, "./") { + a = "./" + path.Clean(a) + if a == "./." { + a = "." + } + } else { + a = path.Clean(a) + } + if a == "all" || a == "std" { + out = append(out, allPackages(a)...) + continue + } + out = append(out, a) + } + return out +} + +// importPaths returns the import paths to use for the given command line. +func importPaths(args []string) []string { + args = importPathsNoDotExpansion(args) + var out []string + for _, a := range args { + if strings.Contains(a, "...") { + if build.IsLocalImport(a) { + out = append(out, allPackagesInFS(a)...) + } else { + out = append(out, allPackages(a)...) + } + continue + } + out = append(out, a) + } + return out +} + +// matchPattern(pattern)(name) reports whether +// name matches pattern. Pattern is a limited glob +// pattern in which '...' means 'any string' and there +// is no other special syntax. +func matchPattern(pattern string) func(name string) bool { + re := regexp.QuoteMeta(pattern) + re = strings.Replace(re, `\.\.\.`, `.*`, -1) + // Special case: foo/... matches foo too. + if strings.HasSuffix(re, `/.*`) { + re = re[:len(re)-len(`/.*`)] + `(/.*)?` + } + reg := regexp.MustCompile(`^` + re + `$`) + return func(name string) bool { + return reg.MatchString(name) + } +} + +// hasPathPrefix reports whether the path s begins with the +// elements in prefix. +func hasPathPrefix(s, prefix string) bool { + switch { + default: + return false + case len(s) == len(prefix): + return s == prefix + case len(s) > len(prefix): + if prefix != "" && prefix[len(prefix)-1] == '/' { + return strings.HasPrefix(s, prefix) + } + return s[len(prefix)] == '/' && s[:len(prefix)] == prefix + } +} + +// treeCanMatchPattern(pattern)(name) reports whether +// name or children of name can possibly match pattern. +// Pattern is the same limited glob accepted by matchPattern. +func treeCanMatchPattern(pattern string) func(name string) bool { + wildCard := false + if i := strings.Index(pattern, "..."); i >= 0 { + wildCard = true + pattern = pattern[:i] + } + return func(name string) bool { + return len(name) <= len(pattern) && hasPathPrefix(pattern, name) || + wildCard && strings.HasPrefix(name, pattern) + } +} + +// allPackages returns all the packages that can be found +// under the $GOPATH directories and $GOROOT matching pattern. +// The pattern is either "all" (all packages), "std" (standard packages) +// or a path including "...". +func allPackages(pattern string) []string { + pkgs := matchPackages(pattern) + if len(pkgs) == 0 { + fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern) + } + return pkgs +} + +func matchPackages(pattern string) []string { + match := func(string) bool { return true } + treeCanMatch := func(string) bool { return true } + if pattern != "all" && pattern != "std" { + match = matchPattern(pattern) + treeCanMatch = treeCanMatchPattern(pattern) + } + + have := map[string]bool{ + "builtin": true, // ignore pseudo-package that exists only for documentation + } + if !buildContext.CgoEnabled { + have["runtime/cgo"] = true // ignore during walk + } + var pkgs []string + + // Commands + cmd := filepath.Join(goroot, "src/cmd") + string(filepath.Separator) + filepath.Walk(cmd, func(path string, fi os.FileInfo, err error) error { + if err != nil || !fi.IsDir() || path == cmd { + return nil + } + name := path[len(cmd):] + if !treeCanMatch(name) { + return filepath.SkipDir + } + // Commands are all in cmd/, not in subdirectories. + if strings.Contains(name, string(filepath.Separator)) { + return filepath.SkipDir + } + + // We use, e.g., cmd/gofmt as the pseudo import path for gofmt. + name = "cmd/" + name + if have[name] { + return nil + } + have[name] = true + if !match(name) { + return nil + } + _, err = buildContext.ImportDir(path, 0) + if err != nil { + if _, noGo := err.(*build.NoGoError); !noGo { + log.Print(err) + } + return nil + } + pkgs = append(pkgs, name) + return nil + }) + + for _, src := range buildContext.SrcDirs() { + if (pattern == "std" || pattern == "cmd") && src != gorootSrc { + continue + } + src = filepath.Clean(src) + string(filepath.Separator) + root := src + if pattern == "cmd" { + root += "cmd" + string(filepath.Separator) + } + filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { + if err != nil || !fi.IsDir() || path == src { + return nil + } + + // Avoid .foo, _foo, and testdata directory trees. + _, elem := filepath.Split(path) + if strings.HasPrefix(elem, ".") || strings.HasPrefix(elem, "_") || elem == "testdata" { + return filepath.SkipDir + } + + name := filepath.ToSlash(path[len(src):]) + if pattern == "std" && (strings.Contains(name, ".") || name == "cmd") { + // The name "std" is only the standard library. + // If the name is cmd, it's the root of the command tree. + return filepath.SkipDir + } + if !treeCanMatch(name) { + return filepath.SkipDir + } + if have[name] { + return nil + } + have[name] = true + if !match(name) { + return nil + } + _, err = buildContext.ImportDir(path, 0) + if err != nil { + if _, noGo := err.(*build.NoGoError); noGo { + return nil + } + } + pkgs = append(pkgs, name) + return nil + }) + } + return pkgs +} + +// allPackagesInFS is like allPackages but is passed a pattern +// beginning ./ or ../, meaning it should scan the tree rooted +// at the given directory. There are ... in the pattern too. +func allPackagesInFS(pattern string) []string { + pkgs := matchPackagesInFS(pattern) + if len(pkgs) == 0 { + fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern) + } + return pkgs +} + +func matchPackagesInFS(pattern string) []string { + // Find directory to begin the scan. + // Could be smarter but this one optimization + // is enough for now, since ... is usually at the + // end of a path. + i := strings.Index(pattern, "...") + dir, _ := path.Split(pattern[:i]) + + // pattern begins with ./ or ../. + // path.Clean will discard the ./ but not the ../. + // We need to preserve the ./ for pattern matching + // and in the returned import paths. + prefix := "" + if strings.HasPrefix(pattern, "./") { + prefix = "./" + } + match := matchPattern(pattern) + + var pkgs []string + filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error { + if err != nil || !fi.IsDir() { + return nil + } + if path == dir { + // filepath.Walk starts at dir and recurses. For the recursive case, + // the path is the result of filepath.Join, which calls filepath.Clean. + // The initial case is not Cleaned, though, so we do this explicitly. + // + // This converts a path like "./io/" to "io". Without this step, running + // "cd $GOROOT/src/pkg; go list ./io/..." would incorrectly skip the io + // package, because prepending the prefix "./" to the unclean path would + // result in "././io", and match("././io") returns false. + path = filepath.Clean(path) + } + + // Avoid .foo, _foo, and testdata directory trees, but do not avoid "." or "..". + _, elem := filepath.Split(path) + dot := strings.HasPrefix(elem, ".") && elem != "." && elem != ".." + if dot || strings.HasPrefix(elem, "_") || elem == "testdata" { + return filepath.SkipDir + } + + name := prefix + filepath.ToSlash(path) + if !match(name) { + return nil + } + if _, err = build.ImportDir(path, 0); err != nil { + if _, noGo := err.(*build.NoGoError); !noGo { + log.Print(err) + } + return nil + } + pkgs = append(pkgs, name) + return nil + }) + return pkgs +} diff --git a/vendor/golang.org/x/lint/golint/importcomment.go b/vendor/golang.org/x/lint/golint/importcomment.go new file mode 100644 index 00000000000..d5b32f73464 --- /dev/null +++ b/vendor/golang.org/x/lint/golint/importcomment.go @@ -0,0 +1,13 @@ +// Copyright (c) 2018 The Go Authors. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd. + +// +build go1.12 + +// Require use of the correct import path only for Go 1.12+ users, so +// any breakages coincide with people updating their CI configs or +// whatnot. + +package main // import "golang.org/x/lint/golint" diff --git a/vendor/golang.org/x/lint/lint.go b/vendor/golang.org/x/lint/lint.go new file mode 100644 index 00000000000..7d813e061ad --- /dev/null +++ b/vendor/golang.org/x/lint/lint.go @@ -0,0 +1,1615 @@ +// Copyright (c) 2013 The Go Authors. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file or at +// https://developers.google.com/open-source/licenses/bsd. + +// Package lint contains a linter for Go source code. +package lint // import "golang.org/x/lint" + +import ( + "bufio" + "bytes" + "fmt" + "go/ast" + "go/parser" + "go/printer" + "go/token" + "go/types" + "regexp" + "sort" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "golang.org/x/tools/go/ast/astutil" + "golang.org/x/tools/go/gcexportdata" +) + +const styleGuideBase = "https://golang.org/wiki/CodeReviewComments" + +// A Linter lints Go source code. +type Linter struct { +} + +// Problem represents a problem in some source code. +type Problem struct { + Position token.Position // position in source file + Text string // the prose that describes the problem + Link string // (optional) the link to the style guide for the problem + Confidence float64 // a value in (0,1] estimating the confidence in this problem's correctness + LineText string // the source line + Category string // a short name for the general category of the problem + + // If the problem has a suggested fix (the minority case), + // ReplacementLine is a full replacement for the relevant line of the source file. + ReplacementLine string +} + +func (p *Problem) String() string { + if p.Link != "" { + return p.Text + "\n\n" + p.Link + } + return p.Text +} + +type byPosition []Problem + +func (p byPosition) Len() int { return len(p) } +func (p byPosition) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +func (p byPosition) Less(i, j int) bool { + pi, pj := p[i].Position, p[j].Position + + if pi.Filename != pj.Filename { + return pi.Filename < pj.Filename + } + if pi.Line != pj.Line { + return pi.Line < pj.Line + } + if pi.Column != pj.Column { + return pi.Column < pj.Column + } + + return p[i].Text < p[j].Text +} + +// Lint lints src. +func (l *Linter) Lint(filename string, src []byte) ([]Problem, error) { + return l.LintFiles(map[string][]byte{filename: src}) +} + +// LintFiles lints a set of files of a single package. +// The argument is a map of filename to source. +func (l *Linter) LintFiles(files map[string][]byte) ([]Problem, error) { + pkg := &pkg{ + fset: token.NewFileSet(), + files: make(map[string]*file), + } + var pkgName string + for filename, src := range files { + if isGenerated(src) { + continue // See issue #239 + } + f, err := parser.ParseFile(pkg.fset, filename, src, parser.ParseComments) + if err != nil { + return nil, err + } + if pkgName == "" { + pkgName = f.Name.Name + } else if f.Name.Name != pkgName { + return nil, fmt.Errorf("%s is in package %s, not %s", filename, f.Name.Name, pkgName) + } + pkg.files[filename] = &file{ + pkg: pkg, + f: f, + fset: pkg.fset, + src: src, + filename: filename, + } + } + if len(pkg.files) == 0 { + return nil, nil + } + return pkg.lint(), nil +} + +var ( + genHdr = []byte("// Code generated ") + genFtr = []byte(" DO NOT EDIT.") +) + +// isGenerated reports whether the source file is generated code +// according the rules from https://golang.org/s/generatedcode. +func isGenerated(src []byte) bool { + sc := bufio.NewScanner(bytes.NewReader(src)) + for sc.Scan() { + b := sc.Bytes() + if bytes.HasPrefix(b, genHdr) && bytes.HasSuffix(b, genFtr) && len(b) >= len(genHdr)+len(genFtr) { + return true + } + } + return false +} + +// pkg represents a package being linted. +type pkg struct { + fset *token.FileSet + files map[string]*file + + typesPkg *types.Package + typesInfo *types.Info + + // sortable is the set of types in the package that implement sort.Interface. + sortable map[string]bool + // main is whether this is a "main" package. + main bool + + problems []Problem +} + +func (p *pkg) lint() []Problem { + if err := p.typeCheck(); err != nil { + /* TODO(dsymonds): Consider reporting these errors when golint operates on entire packages. + if e, ok := err.(types.Error); ok { + pos := p.fset.Position(e.Pos) + conf := 1.0 + if strings.Contains(e.Msg, "can't find import: ") { + // Golint is probably being run in a context that doesn't support + // typechecking (e.g. package files aren't found), so don't warn about it. + conf = 0 + } + if conf > 0 { + p.errorfAt(pos, conf, category("typechecking"), e.Msg) + } + + // TODO(dsymonds): Abort if !e.Soft? + } + */ + } + + p.scanSortable() + p.main = p.isMain() + + for _, f := range p.files { + f.lint() + } + + sort.Sort(byPosition(p.problems)) + + return p.problems +} + +// file represents a file being linted. +type file struct { + pkg *pkg + f *ast.File + fset *token.FileSet + src []byte + filename string +} + +func (f *file) isTest() bool { return strings.HasSuffix(f.filename, "_test.go") } + +func (f *file) lint() { + f.lintPackageComment() + f.lintImports() + f.lintBlankImports() + f.lintExported() + f.lintNames() + f.lintElses() + f.lintRanges() + f.lintErrorf() + f.lintErrors() + f.lintErrorStrings() + f.lintReceiverNames() + f.lintIncDec() + f.lintErrorReturn() + f.lintUnexportedReturn() + f.lintTimeNames() + f.lintContextKeyTypes() + f.lintContextArgs() +} + +type link string +type category string + +// The variadic arguments may start with link and category types, +// and must end with a format string and any arguments. +// It returns the new Problem. +func (f *file) errorf(n ast.Node, confidence float64, args ...interface{}) *Problem { + pos := f.fset.Position(n.Pos()) + if pos.Filename == "" { + pos.Filename = f.filename + } + return f.pkg.errorfAt(pos, confidence, args...) +} + +func (p *pkg) errorfAt(pos token.Position, confidence float64, args ...interface{}) *Problem { + problem := Problem{ + Position: pos, + Confidence: confidence, + } + if pos.Filename != "" { + // The file might not exist in our mapping if a //line directive was encountered. + if f, ok := p.files[pos.Filename]; ok { + problem.LineText = srcLine(f.src, pos) + } + } + +argLoop: + for len(args) > 1 { // always leave at least the format string in args + switch v := args[0].(type) { + case link: + problem.Link = string(v) + case category: + problem.Category = string(v) + default: + break argLoop + } + args = args[1:] + } + + problem.Text = fmt.Sprintf(args[0].(string), args[1:]...) + + p.problems = append(p.problems, problem) + return &p.problems[len(p.problems)-1] +} + +var newImporter = func(fset *token.FileSet) types.ImporterFrom { + return gcexportdata.NewImporter(fset, make(map[string]*types.Package)) +} + +func (p *pkg) typeCheck() error { + config := &types.Config{ + // By setting a no-op error reporter, the type checker does as much work as possible. + Error: func(error) {}, + Importer: newImporter(p.fset), + } + info := &types.Info{ + Types: make(map[ast.Expr]types.TypeAndValue), + Defs: make(map[*ast.Ident]types.Object), + Uses: make(map[*ast.Ident]types.Object), + Scopes: make(map[ast.Node]*types.Scope), + } + var anyFile *file + var astFiles []*ast.File + for _, f := range p.files { + anyFile = f + astFiles = append(astFiles, f.f) + } + pkg, err := config.Check(anyFile.f.Name.Name, p.fset, astFiles, info) + // Remember the typechecking info, even if config.Check failed, + // since we will get partial information. + p.typesPkg = pkg + p.typesInfo = info + return err +} + +func (p *pkg) typeOf(expr ast.Expr) types.Type { + if p.typesInfo == nil { + return nil + } + return p.typesInfo.TypeOf(expr) +} + +func (p *pkg) isNamedType(typ types.Type, importPath, name string) bool { + n, ok := typ.(*types.Named) + if !ok { + return false + } + tn := n.Obj() + return tn != nil && tn.Pkg() != nil && tn.Pkg().Path() == importPath && tn.Name() == name +} + +// scopeOf returns the tightest scope encompassing id. +func (p *pkg) scopeOf(id *ast.Ident) *types.Scope { + var scope *types.Scope + if obj := p.typesInfo.ObjectOf(id); obj != nil { + scope = obj.Parent() + } + if scope == p.typesPkg.Scope() { + // We were given a top-level identifier. + // Use the file-level scope instead of the package-level scope. + pos := id.Pos() + for _, f := range p.files { + if f.f.Pos() <= pos && pos < f.f.End() { + scope = p.typesInfo.Scopes[f.f] + break + } + } + } + return scope +} + +func (p *pkg) scanSortable() { + p.sortable = make(map[string]bool) + + // bitfield for which methods exist on each type. + const ( + Len = 1 << iota + Less + Swap + ) + nmap := map[string]int{"Len": Len, "Less": Less, "Swap": Swap} + has := make(map[string]int) + for _, f := range p.files { + f.walk(func(n ast.Node) bool { + fn, ok := n.(*ast.FuncDecl) + if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 { + return true + } + // TODO(dsymonds): We could check the signature to be more precise. + recv := receiverType(fn) + if i, ok := nmap[fn.Name.Name]; ok { + has[recv] |= i + } + return false + }) + } + for typ, ms := range has { + if ms == Len|Less|Swap { + p.sortable[typ] = true + } + } +} + +func (p *pkg) isMain() bool { + for _, f := range p.files { + if f.isMain() { + return true + } + } + return false +} + +func (f *file) isMain() bool { + if f.f.Name.Name == "main" { + return true + } + return false +} + +// lintPackageComment checks package comments. It complains if +// there is no package comment, or if it is not of the right form. +// This has a notable false positive in that a package comment +// could rightfully appear in a different file of the same package, +// but that's not easy to fix since this linter is file-oriented. +func (f *file) lintPackageComment() { + if f.isTest() { + return + } + + const ref = styleGuideBase + "#package-comments" + prefix := "Package " + f.f.Name.Name + " " + + // Look for a detached package comment. + // First, scan for the last comment that occurs before the "package" keyword. + var lastCG *ast.CommentGroup + for _, cg := range f.f.Comments { + if cg.Pos() > f.f.Package { + // Gone past "package" keyword. + break + } + lastCG = cg + } + if lastCG != nil && strings.HasPrefix(lastCG.Text(), prefix) { + endPos := f.fset.Position(lastCG.End()) + pkgPos := f.fset.Position(f.f.Package) + if endPos.Line+1 < pkgPos.Line { + // There isn't a great place to anchor this error; + // the start of the blank lines between the doc and the package statement + // is at least pointing at the location of the problem. + pos := token.Position{ + Filename: endPos.Filename, + // Offset not set; it is non-trivial, and doesn't appear to be needed. + Line: endPos.Line + 1, + Column: 1, + } + f.pkg.errorfAt(pos, 0.9, link(ref), category("comments"), "package comment is detached; there should be no blank lines between it and the package statement") + return + } + } + + if f.f.Doc == nil { + f.errorf(f.f, 0.2, link(ref), category("comments"), "should have a package comment, unless it's in another file for this package") + return + } + s := f.f.Doc.Text() + if ts := strings.TrimLeft(s, " \t"); ts != s { + f.errorf(f.f.Doc, 1, link(ref), category("comments"), "package comment should not have leading space") + s = ts + } + // Only non-main packages need to keep to this form. + if !f.pkg.main && !strings.HasPrefix(s, prefix) { + f.errorf(f.f.Doc, 1, link(ref), category("comments"), `package comment should be of the form "%s..."`, prefix) + } +} + +// lintBlankImports complains if a non-main package has blank imports that are +// not documented. +func (f *file) lintBlankImports() { + // In package main and in tests, we don't complain about blank imports. + if f.pkg.main || f.isTest() { + return + } + + // The first element of each contiguous group of blank imports should have + // an explanatory comment of some kind. + for i, imp := range f.f.Imports { + pos := f.fset.Position(imp.Pos()) + + if !isBlank(imp.Name) { + continue // Ignore non-blank imports. + } + if i > 0 { + prev := f.f.Imports[i-1] + prevPos := f.fset.Position(prev.Pos()) + if isBlank(prev.Name) && prevPos.Line+1 == pos.Line { + continue // A subsequent blank in a group. + } + } + + // This is the first blank import of a group. + if imp.Doc == nil && imp.Comment == nil { + ref := "" + f.errorf(imp, 1, link(ref), category("imports"), "a blank import should be only in a main or test package, or have a comment justifying it") + } + } +} + +// lintImports examines import blocks. +func (f *file) lintImports() { + for i, is := range f.f.Imports { + _ = i + if is.Name != nil && is.Name.Name == "." && !f.isTest() { + f.errorf(is, 1, link(styleGuideBase+"#import-dot"), category("imports"), "should not use dot imports") + } + + } +} + +const docCommentsLink = styleGuideBase + "#doc-comments" + +// lintExported examines the exported names. +// It complains if any required doc comments are missing, +// or if they are not of the right form. The exact rules are in +// lintFuncDoc, lintTypeDoc and lintValueSpecDoc; this function +// also tracks the GenDecl structure being traversed to permit +// doc comments for constants to be on top of the const block. +// It also complains if the names stutter when combined with +// the package name. +func (f *file) lintExported() { + if f.isTest() { + return + } + + var lastGen *ast.GenDecl // last GenDecl entered. + + // Set of GenDecls that have already had missing comments flagged. + genDeclMissingComments := make(map[*ast.GenDecl]bool) + + f.walk(func(node ast.Node) bool { + switch v := node.(type) { + case *ast.GenDecl: + if v.Tok == token.IMPORT { + return false + } + // token.CONST, token.TYPE or token.VAR + lastGen = v + return true + case *ast.FuncDecl: + f.lintFuncDoc(v) + if v.Recv == nil { + // Only check for stutter on functions, not methods. + // Method names are not used package-qualified. + f.checkStutter(v.Name, "func") + } + // Don't proceed inside funcs. + return false + case *ast.TypeSpec: + // inside a GenDecl, which usually has the doc + doc := v.Doc + if doc == nil { + doc = lastGen.Doc + } + f.lintTypeDoc(v, doc) + f.checkStutter(v.Name, "type") + // Don't proceed inside types. + return false + case *ast.ValueSpec: + f.lintValueSpecDoc(v, lastGen, genDeclMissingComments) + return false + } + return true + }) +} + +var ( + allCapsRE = regexp.MustCompile(`^[A-Z0-9_]+$`) + anyCapsRE = regexp.MustCompile(`[A-Z]`) +) + +// knownNameExceptions is a set of names that are known to be exempt from naming checks. +// This is usually because they are constrained by having to match names in the +// standard library. +var knownNameExceptions = map[string]bool{ + "LastInsertId": true, // must match database/sql + "kWh": true, +} + +func isInTopLevel(f *ast.File, ident *ast.Ident) bool { + path, _ := astutil.PathEnclosingInterval(f, ident.Pos(), ident.End()) + for _, f := range path { + switch f.(type) { + case *ast.File, *ast.GenDecl, *ast.ValueSpec, *ast.Ident: + continue + } + return false + } + return true +} + +// lintNames examines all names in the file. +// It complains if any use underscores or incorrect known initialisms. +func (f *file) lintNames() { + // Package names need slightly different handling than other names. + if strings.Contains(f.f.Name.Name, "_") && !strings.HasSuffix(f.f.Name.Name, "_test") { + f.errorf(f.f, 1, link("http://golang.org/doc/effective_go.html#package-names"), category("naming"), "don't use an underscore in package name") + } + if anyCapsRE.MatchString(f.f.Name.Name) { + f.errorf(f.f, 1, link("http://golang.org/doc/effective_go.html#package-names"), category("mixed-caps"), "don't use MixedCaps in package name; %s should be %s", f.f.Name.Name, strings.ToLower(f.f.Name.Name)) + } + + check := func(id *ast.Ident, thing string) { + if id.Name == "_" { + return + } + if knownNameExceptions[id.Name] { + return + } + + // Handle two common styles from other languages that don't belong in Go. + if len(id.Name) >= 5 && allCapsRE.MatchString(id.Name) && strings.Contains(id.Name, "_") { + capCount := 0 + for _, c := range id.Name { + if 'A' <= c && c <= 'Z' { + capCount++ + } + } + if capCount >= 2 { + f.errorf(id, 0.8, link(styleGuideBase+"#mixed-caps"), category("naming"), "don't use ALL_CAPS in Go names; use CamelCase") + return + } + } + if thing == "const" || (thing == "var" && isInTopLevel(f.f, id)) { + if len(id.Name) > 2 && id.Name[0] == 'k' && id.Name[1] >= 'A' && id.Name[1] <= 'Z' { + should := string(id.Name[1]+'a'-'A') + id.Name[2:] + f.errorf(id, 0.8, link(styleGuideBase+"#mixed-caps"), category("naming"), "don't use leading k in Go names; %s %s should be %s", thing, id.Name, should) + } + } + + should := lintName(id.Name) + if id.Name == should { + return + } + + if len(id.Name) > 2 && strings.Contains(id.Name[1:], "_") { + f.errorf(id, 0.9, link("http://golang.org/doc/effective_go.html#mixed-caps"), category("naming"), "don't use underscores in Go names; %s %s should be %s", thing, id.Name, should) + return + } + f.errorf(id, 0.8, link(styleGuideBase+"#initialisms"), category("naming"), "%s %s should be %s", thing, id.Name, should) + } + checkList := func(fl *ast.FieldList, thing string) { + if fl == nil { + return + } + for _, f := range fl.List { + for _, id := range f.Names { + check(id, thing) + } + } + } + f.walk(func(node ast.Node) bool { + switch v := node.(type) { + case *ast.AssignStmt: + if v.Tok == token.ASSIGN { + return true + } + for _, exp := range v.Lhs { + if id, ok := exp.(*ast.Ident); ok { + check(id, "var") + } + } + case *ast.FuncDecl: + if f.isTest() && (strings.HasPrefix(v.Name.Name, "Example") || strings.HasPrefix(v.Name.Name, "Test") || strings.HasPrefix(v.Name.Name, "Benchmark")) { + return true + } + + thing := "func" + if v.Recv != nil { + thing = "method" + } + + // Exclude naming warnings for functions that are exported to C but + // not exported in the Go API. + // See https://github.com/golang/lint/issues/144. + if ast.IsExported(v.Name.Name) || !isCgoExported(v) { + check(v.Name, thing) + } + + checkList(v.Type.Params, thing+" parameter") + checkList(v.Type.Results, thing+" result") + case *ast.GenDecl: + if v.Tok == token.IMPORT { + return true + } + var thing string + switch v.Tok { + case token.CONST: + thing = "const" + case token.TYPE: + thing = "type" + case token.VAR: + thing = "var" + } + for _, spec := range v.Specs { + switch s := spec.(type) { + case *ast.TypeSpec: + check(s.Name, thing) + case *ast.ValueSpec: + for _, id := range s.Names { + check(id, thing) + } + } + } + case *ast.InterfaceType: + // Do not check interface method names. + // They are often constrainted by the method names of concrete types. + for _, x := range v.Methods.List { + ft, ok := x.Type.(*ast.FuncType) + if !ok { // might be an embedded interface name + continue + } + checkList(ft.Params, "interface method parameter") + checkList(ft.Results, "interface method result") + } + case *ast.RangeStmt: + if v.Tok == token.ASSIGN { + return true + } + if id, ok := v.Key.(*ast.Ident); ok { + check(id, "range var") + } + if id, ok := v.Value.(*ast.Ident); ok { + check(id, "range var") + } + case *ast.StructType: + for _, f := range v.Fields.List { + for _, id := range f.Names { + check(id, "struct field") + } + } + } + return true + }) +} + +// lintName returns a different name if it should be different. +func lintName(name string) (should string) { + // Fast path for simple cases: "_" and all lowercase. + if name == "_" { + return name + } + allLower := true + for _, r := range name { + if !unicode.IsLower(r) { + allLower = false + break + } + } + if allLower { + return name + } + + // Split camelCase at any lower->upper transition, and split on underscores. + // Check each word for common initialisms. + runes := []rune(name) + w, i := 0, 0 // index of start of word, scan + for i+1 <= len(runes) { + eow := false // whether we hit the end of a word + if i+1 == len(runes) { + eow = true + } else if runes[i+1] == '_' { + // underscore; shift the remainder forward over any run of underscores + eow = true + n := 1 + for i+n+1 < len(runes) && runes[i+n+1] == '_' { + n++ + } + + // Leave at most one underscore if the underscore is between two digits + if i+n+1 < len(runes) && unicode.IsDigit(runes[i]) && unicode.IsDigit(runes[i+n+1]) { + n-- + } + + copy(runes[i+1:], runes[i+n+1:]) + runes = runes[:len(runes)-n] + } else if unicode.IsLower(runes[i]) && !unicode.IsLower(runes[i+1]) { + // lower->non-lower + eow = true + } + i++ + if !eow { + continue + } + + // [w,i) is a word. + word := string(runes[w:i]) + if u := strings.ToUpper(word); commonInitialisms[u] { + // Keep consistent case, which is lowercase only at the start. + if w == 0 && unicode.IsLower(runes[w]) { + u = strings.ToLower(u) + } + // All the common initialisms are ASCII, + // so we can replace the bytes exactly. + copy(runes[w:], []rune(u)) + } else if w > 0 && strings.ToLower(word) == word { + // already all lowercase, and not the first word, so uppercase the first character. + runes[w] = unicode.ToUpper(runes[w]) + } + w = i + } + return string(runes) +} + +// commonInitialisms is a set of common initialisms. +// Only add entries that are highly unlikely to be non-initialisms. +// For instance, "ID" is fine (Freudian code is rare), but "AND" is not. +var commonInitialisms = map[string]bool{ + "ACL": true, + "API": true, + "ASCII": true, + "CPU": true, + "CSS": true, + "DNS": true, + "EOF": true, + "GUID": true, + "HTML": true, + "HTTP": true, + "HTTPS": true, + "ID": true, + "IP": true, + "JSON": true, + "LHS": true, + "QPS": true, + "RAM": true, + "RHS": true, + "RPC": true, + "SLA": true, + "SMTP": true, + "SQL": true, + "SSH": true, + "TCP": true, + "TLS": true, + "TTL": true, + "UDP": true, + "UI": true, + "UID": true, + "UUID": true, + "URI": true, + "URL": true, + "UTF8": true, + "VM": true, + "XML": true, + "XMPP": true, + "XSRF": true, + "XSS": true, +} + +// lintTypeDoc examines the doc comment on a type. +// It complains if they are missing from an exported type, +// or if they are not of the standard form. +func (f *file) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup) { + if !ast.IsExported(t.Name.Name) { + return + } + if doc == nil { + f.errorf(t, 1, link(docCommentsLink), category("comments"), "exported type %v should have comment or be unexported", t.Name) + return + } + + s := doc.Text() + articles := [...]string{"A", "An", "The"} + for _, a := range articles { + if strings.HasPrefix(s, a+" ") { + s = s[len(a)+1:] + break + } + } + if !strings.HasPrefix(s, t.Name.Name+" ") { + f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported type %v should be of the form "%v ..." (with optional leading article)`, t.Name, t.Name) + } +} + +var commonMethods = map[string]bool{ + "Error": true, + "Read": true, + "ServeHTTP": true, + "String": true, + "Write": true, + "Unwrap": true, +} + +// lintFuncDoc examines doc comments on functions and methods. +// It complains if they are missing, or not of the right form. +// It has specific exclusions for well-known methods (see commonMethods above). +func (f *file) lintFuncDoc(fn *ast.FuncDecl) { + if !ast.IsExported(fn.Name.Name) { + // func is unexported + return + } + kind := "function" + name := fn.Name.Name + if fn.Recv != nil && len(fn.Recv.List) > 0 { + // method + kind = "method" + recv := receiverType(fn) + if !ast.IsExported(recv) { + // receiver is unexported + return + } + if commonMethods[name] { + return + } + switch name { + case "Len", "Less", "Swap": + if f.pkg.sortable[recv] { + return + } + } + name = recv + "." + name + } + if fn.Doc == nil { + f.errorf(fn, 1, link(docCommentsLink), category("comments"), "exported %s %s should have comment or be unexported", kind, name) + return + } + s := fn.Doc.Text() + prefix := fn.Name.Name + " " + if !strings.HasPrefix(s, prefix) { + f.errorf(fn.Doc, 1, link(docCommentsLink), category("comments"), `comment on exported %s %s should be of the form "%s..."`, kind, name, prefix) + } +} + +// lintValueSpecDoc examines package-global variables and constants. +// It complains if they are not individually declared, +// or if they are not suitably documented in the right form (unless they are in a block that is commented). +func (f *file) lintValueSpecDoc(vs *ast.ValueSpec, gd *ast.GenDecl, genDeclMissingComments map[*ast.GenDecl]bool) { + kind := "var" + if gd.Tok == token.CONST { + kind = "const" + } + + if len(vs.Names) > 1 { + // Check that none are exported except for the first. + for _, n := range vs.Names[1:] { + if ast.IsExported(n.Name) { + f.errorf(vs, 1, category("comments"), "exported %s %s should have its own declaration", kind, n.Name) + return + } + } + } + + // Only one name. + name := vs.Names[0].Name + if !ast.IsExported(name) { + return + } + + if vs.Doc == nil && gd.Doc == nil { + if genDeclMissingComments[gd] { + return + } + block := "" + if kind == "const" && gd.Lparen.IsValid() { + block = " (or a comment on this block)" + } + f.errorf(vs, 1, link(docCommentsLink), category("comments"), "exported %s %s should have comment%s or be unexported", kind, name, block) + genDeclMissingComments[gd] = true + return + } + // If this GenDecl has parens and a comment, we don't check its comment form. + if gd.Lparen.IsValid() && gd.Doc != nil { + return + } + // The relevant text to check will be on either vs.Doc or gd.Doc. + // Use vs.Doc preferentially. + doc := vs.Doc + if doc == nil { + doc = gd.Doc + } + prefix := name + " " + if !strings.HasPrefix(doc.Text(), prefix) { + f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported %s %s should be of the form "%s..."`, kind, name, prefix) + } +} + +func (f *file) checkStutter(id *ast.Ident, thing string) { + pkg, name := f.f.Name.Name, id.Name + if !ast.IsExported(name) { + // unexported name + return + } + // A name stutters if the package name is a strict prefix + // and the next character of the name starts a new word. + if len(name) <= len(pkg) { + // name is too short to stutter. + // This permits the name to be the same as the package name. + return + } + if !strings.EqualFold(pkg, name[:len(pkg)]) { + return + } + // We can assume the name is well-formed UTF-8. + // If the next rune after the package name is uppercase or an underscore + // the it's starting a new word and thus this name stutters. + rem := name[len(pkg):] + if next, _ := utf8.DecodeRuneInString(rem); next == '_' || unicode.IsUpper(next) { + f.errorf(id, 0.8, link(styleGuideBase+"#package-names"), category("naming"), "%s name will be used as %s.%s by other packages, and that stutters; consider calling this %s", thing, pkg, name, rem) + } +} + +// zeroLiteral is a set of ast.BasicLit values that are zero values. +// It is not exhaustive. +var zeroLiteral = map[string]bool{ + "false": true, // bool + // runes + `'\x00'`: true, + `'\000'`: true, + // strings + `""`: true, + "``": true, + // numerics + "0": true, + "0.": true, + "0.0": true, + "0i": true, +} + +// lintElses examines else blocks. It complains about any else block whose if block ends in a return. +func (f *file) lintElses() { + // We don't want to flag if { } else if { } else { } constructions. + // They will appear as an IfStmt whose Else field is also an IfStmt. + // Record such a node so we ignore it when we visit it. + ignore := make(map[*ast.IfStmt]bool) + + f.walk(func(node ast.Node) bool { + ifStmt, ok := node.(*ast.IfStmt) + if !ok || ifStmt.Else == nil { + return true + } + if elseif, ok := ifStmt.Else.(*ast.IfStmt); ok { + ignore[elseif] = true + return true + } + if ignore[ifStmt] { + return true + } + if _, ok := ifStmt.Else.(*ast.BlockStmt); !ok { + // only care about elses without conditions + return true + } + if len(ifStmt.Body.List) == 0 { + return true + } + shortDecl := false // does the if statement have a ":=" initialization statement? + if ifStmt.Init != nil { + if as, ok := ifStmt.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE { + shortDecl = true + } + } + lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1] + if _, ok := lastStmt.(*ast.ReturnStmt); ok { + extra := "" + if shortDecl { + extra = " (move short variable declaration to its own line if necessary)" + } + f.errorf(ifStmt.Else, 1, link(styleGuideBase+"#indent-error-flow"), category("indent"), "if block ends with a return statement, so drop this else and outdent its block"+extra) + } + return true + }) +} + +// lintRanges examines range clauses. It complains about redundant constructions. +func (f *file) lintRanges() { + f.walk(func(node ast.Node) bool { + rs, ok := node.(*ast.RangeStmt) + if !ok { + return true + } + + if isIdent(rs.Key, "_") && (rs.Value == nil || isIdent(rs.Value, "_")) { + p := f.errorf(rs.Key, 1, category("range-loop"), "should omit values from range; this loop is equivalent to `for range ...`") + + newRS := *rs // shallow copy + newRS.Value = nil + newRS.Key = nil + p.ReplacementLine = f.firstLineOf(&newRS, rs) + + return true + } + + if isIdent(rs.Value, "_") { + p := f.errorf(rs.Value, 1, category("range-loop"), "should omit 2nd value from range; this loop is equivalent to `for %s %s range ...`", f.render(rs.Key), rs.Tok) + + newRS := *rs // shallow copy + newRS.Value = nil + p.ReplacementLine = f.firstLineOf(&newRS, rs) + } + + return true + }) +} + +// lintErrorf examines errors.New and testing.Error calls. It complains if its only argument is an fmt.Sprintf invocation. +func (f *file) lintErrorf() { + f.walk(func(node ast.Node) bool { + ce, ok := node.(*ast.CallExpr) + if !ok || len(ce.Args) != 1 { + return true + } + isErrorsNew := isPkgDot(ce.Fun, "errors", "New") + var isTestingError bool + se, ok := ce.Fun.(*ast.SelectorExpr) + if ok && se.Sel.Name == "Error" { + if typ := f.pkg.typeOf(se.X); typ != nil { + isTestingError = typ.String() == "*testing.T" + } + } + if !isErrorsNew && !isTestingError { + return true + } + if !f.imports("errors") { + return true + } + arg := ce.Args[0] + ce, ok = arg.(*ast.CallExpr) + if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") { + return true + } + errorfPrefix := "fmt" + if isTestingError { + errorfPrefix = f.render(se.X) + } + p := f.errorf(node, 1, category("errors"), "should replace %s(fmt.Sprintf(...)) with %s.Errorf(...)", f.render(se), errorfPrefix) + + m := f.srcLineWithMatch(ce, `^(.*)`+f.render(se)+`\(fmt\.Sprintf\((.*)\)\)(.*)$`) + if m != nil { + p.ReplacementLine = m[1] + errorfPrefix + ".Errorf(" + m[2] + ")" + m[3] + } + + return true + }) +} + +// lintErrors examines global error vars. It complains if they aren't named in the standard way. +func (f *file) lintErrors() { + for _, decl := range f.f.Decls { + gd, ok := decl.(*ast.GenDecl) + if !ok || gd.Tok != token.VAR { + continue + } + for _, spec := range gd.Specs { + spec := spec.(*ast.ValueSpec) + if len(spec.Names) != 1 || len(spec.Values) != 1 { + continue + } + ce, ok := spec.Values[0].(*ast.CallExpr) + if !ok { + continue + } + if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") { + continue + } + + id := spec.Names[0] + prefix := "err" + if id.IsExported() { + prefix = "Err" + } + if !strings.HasPrefix(id.Name, prefix) { + f.errorf(id, 0.9, category("naming"), "error var %s should have name of the form %sFoo", id.Name, prefix) + } + } + } +} + +func lintErrorString(s string) (isClean bool, conf float64) { + const basicConfidence = 0.8 + const capConfidence = basicConfidence - 0.2 + first, firstN := utf8.DecodeRuneInString(s) + last, _ := utf8.DecodeLastRuneInString(s) + if last == '.' || last == ':' || last == '!' || last == '\n' { + return false, basicConfidence + } + if unicode.IsUpper(first) { + // People use proper nouns and exported Go identifiers in error strings, + // so decrease the confidence of warnings for capitalization. + if len(s) <= firstN { + return false, capConfidence + } + // Flag strings starting with something that doesn't look like an initialism. + if second, _ := utf8.DecodeRuneInString(s[firstN:]); !unicode.IsUpper(second) { + return false, capConfidence + } + } + return true, 0 +} + +// lintErrorStrings examines error strings. +// It complains if they are capitalized or end in punctuation or a newline. +func (f *file) lintErrorStrings() { + f.walk(func(node ast.Node) bool { + ce, ok := node.(*ast.CallExpr) + if !ok { + return true + } + if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") { + return true + } + if len(ce.Args) < 1 { + return true + } + str, ok := ce.Args[0].(*ast.BasicLit) + if !ok || str.Kind != token.STRING { + return true + } + s, _ := strconv.Unquote(str.Value) // can assume well-formed Go + if s == "" { + return true + } + clean, conf := lintErrorString(s) + if clean { + return true + } + + f.errorf(str, conf, link(styleGuideBase+"#error-strings"), category("errors"), + "error strings should not be capitalized or end with punctuation or a newline") + return true + }) +} + +// lintReceiverNames examines receiver names. It complains about inconsistent +// names used for the same type and names such as "this". +func (f *file) lintReceiverNames() { + typeReceiver := map[string]string{} + f.walk(func(n ast.Node) bool { + fn, ok := n.(*ast.FuncDecl) + if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 { + return true + } + names := fn.Recv.List[0].Names + if len(names) < 1 { + return true + } + name := names[0].Name + const ref = styleGuideBase + "#receiver-names" + if name == "_" { + f.errorf(n, 1, link(ref), category("naming"), `receiver name should not be an underscore, omit the name if it is unused`) + return true + } + if name == "this" || name == "self" { + f.errorf(n, 1, link(ref), category("naming"), `receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"`) + return true + } + recv := receiverType(fn) + if prev, ok := typeReceiver[recv]; ok && prev != name { + f.errorf(n, 1, link(ref), category("naming"), "receiver name %s should be consistent with previous receiver name %s for %s", name, prev, recv) + return true + } + typeReceiver[recv] = name + return true + }) +} + +// lintIncDec examines statements that increment or decrement a variable. +// It complains if they don't use x++ or x--. +func (f *file) lintIncDec() { + f.walk(func(n ast.Node) bool { + as, ok := n.(*ast.AssignStmt) + if !ok { + return true + } + if len(as.Lhs) != 1 { + return true + } + if !isOne(as.Rhs[0]) { + return true + } + var suffix string + switch as.Tok { + case token.ADD_ASSIGN: + suffix = "++" + case token.SUB_ASSIGN: + suffix = "--" + default: + return true + } + f.errorf(as, 0.8, category("unary-op"), "should replace %s with %s%s", f.render(as), f.render(as.Lhs[0]), suffix) + return true + }) +} + +// lintErrorReturn examines function declarations that return an error. +// It complains if the error isn't the last parameter. +func (f *file) lintErrorReturn() { + f.walk(func(n ast.Node) bool { + fn, ok := n.(*ast.FuncDecl) + if !ok || fn.Type.Results == nil { + return true + } + ret := fn.Type.Results.List + if len(ret) <= 1 { + return true + } + if isIdent(ret[len(ret)-1].Type, "error") { + return true + } + // An error return parameter should be the last parameter. + // Flag any error parameters found before the last. + for _, r := range ret[:len(ret)-1] { + if isIdent(r.Type, "error") { + f.errorf(fn, 0.9, category("arg-order"), "error should be the last type when returning multiple items") + break // only flag one + } + } + return true + }) +} + +// lintUnexportedReturn examines exported function declarations. +// It complains if any return an unexported type. +func (f *file) lintUnexportedReturn() { + f.walk(func(n ast.Node) bool { + fn, ok := n.(*ast.FuncDecl) + if !ok { + return true + } + if fn.Type.Results == nil { + return false + } + if !fn.Name.IsExported() { + return false + } + thing := "func" + if fn.Recv != nil && len(fn.Recv.List) > 0 { + thing = "method" + if !ast.IsExported(receiverType(fn)) { + // Don't report exported methods of unexported types, + // such as private implementations of sort.Interface. + return false + } + } + for _, ret := range fn.Type.Results.List { + typ := f.pkg.typeOf(ret.Type) + if exportedType(typ) { + continue + } + f.errorf(ret.Type, 0.8, category("unexported-type-in-api"), + "exported %s %s returns unexported type %s, which can be annoying to use", + thing, fn.Name.Name, typ) + break // only flag one + } + return false + }) +} + +// exportedType reports whether typ is an exported type. +// It is imprecise, and will err on the side of returning true, +// such as for composite types. +func exportedType(typ types.Type) bool { + switch T := typ.(type) { + case *types.Named: + // Builtin types have no package. + return T.Obj().Pkg() == nil || T.Obj().Exported() + case *types.Map: + return exportedType(T.Key()) && exportedType(T.Elem()) + case interface { + Elem() types.Type + }: // array, slice, pointer, chan + return exportedType(T.Elem()) + } + // Be conservative about other types, such as struct, interface, etc. + return true +} + +// timeSuffixes is a list of name suffixes that imply a time unit. +// This is not an exhaustive list. +var timeSuffixes = []string{ + "Sec", "Secs", "Seconds", + "Msec", "Msecs", + "Milli", "Millis", "Milliseconds", + "Usec", "Usecs", "Microseconds", + "MS", "Ms", +} + +func (f *file) lintTimeNames() { + f.walk(func(node ast.Node) bool { + v, ok := node.(*ast.ValueSpec) + if !ok { + return true + } + for _, name := range v.Names { + origTyp := f.pkg.typeOf(name) + // Look for time.Duration or *time.Duration; + // the latter is common when using flag.Duration. + typ := origTyp + if pt, ok := typ.(*types.Pointer); ok { + typ = pt.Elem() + } + if !f.pkg.isNamedType(typ, "time", "Duration") { + continue + } + suffix := "" + for _, suf := range timeSuffixes { + if strings.HasSuffix(name.Name, suf) { + suffix = suf + break + } + } + if suffix == "" { + continue + } + f.errorf(v, 0.9, category("time"), "var %s is of type %v; don't use unit-specific suffix %q", name.Name, origTyp, suffix) + } + return true + }) +} + +// lintContextKeyTypes checks for call expressions to context.WithValue with +// basic types used for the key argument. +// See: https://golang.org/issue/17293 +func (f *file) lintContextKeyTypes() { + f.walk(func(node ast.Node) bool { + switch node := node.(type) { + case *ast.CallExpr: + f.checkContextKeyType(node) + } + + return true + }) +} + +// checkContextKeyType reports an error if the call expression calls +// context.WithValue with a key argument of basic type. +func (f *file) checkContextKeyType(x *ast.CallExpr) { + sel, ok := x.Fun.(*ast.SelectorExpr) + if !ok { + return + } + pkg, ok := sel.X.(*ast.Ident) + if !ok || pkg.Name != "context" { + return + } + if sel.Sel.Name != "WithValue" { + return + } + + // key is second argument to context.WithValue + if len(x.Args) != 3 { + return + } + key := f.pkg.typesInfo.Types[x.Args[1]] + + if ktyp, ok := key.Type.(*types.Basic); ok && ktyp.Kind() != types.Invalid { + f.errorf(x, 1.0, category("context"), fmt.Sprintf("should not use basic type %s as key in context.WithValue", key.Type)) + } +} + +// lintContextArgs examines function declarations that contain an +// argument with a type of context.Context +// It complains if that argument isn't the first parameter. +func (f *file) lintContextArgs() { + f.walk(func(n ast.Node) bool { + fn, ok := n.(*ast.FuncDecl) + if !ok || len(fn.Type.Params.List) <= 1 { + return true + } + // A context.Context should be the first parameter of a function. + // Flag any that show up after the first. + for _, arg := range fn.Type.Params.List[1:] { + if isPkgDot(arg.Type, "context", "Context") { + f.errorf(fn, 0.9, link("https://golang.org/pkg/context/"), category("arg-order"), "context.Context should be the first parameter of a function") + break // only flag one + } + } + return true + }) +} + +// containsComments returns whether the interval [start, end) contains any +// comments without "// MATCH " prefix. +func (f *file) containsComments(start, end token.Pos) bool { + for _, cgroup := range f.f.Comments { + comments := cgroup.List + if comments[0].Slash >= end { + // All comments starting with this group are after end pos. + return false + } + if comments[len(comments)-1].Slash < start { + // Comments group ends before start pos. + continue + } + for _, c := range comments { + if start <= c.Slash && c.Slash < end && !strings.HasPrefix(c.Text, "// MATCH ") { + return true + } + } + } + return false +} + +// receiverType returns the named type of the method receiver, sans "*", +// or "invalid-type" if fn.Recv is ill formed. +func receiverType(fn *ast.FuncDecl) string { + switch e := fn.Recv.List[0].Type.(type) { + case *ast.Ident: + return e.Name + case *ast.StarExpr: + if id, ok := e.X.(*ast.Ident); ok { + return id.Name + } + } + // The parser accepts much more than just the legal forms. + return "invalid-type" +} + +func (f *file) walk(fn func(ast.Node) bool) { + ast.Walk(walker(fn), f.f) +} + +func (f *file) render(x interface{}) string { + var buf bytes.Buffer + if err := printer.Fprint(&buf, f.fset, x); err != nil { + panic(err) + } + return buf.String() +} + +func (f *file) debugRender(x interface{}) string { + var buf bytes.Buffer + if err := ast.Fprint(&buf, f.fset, x, nil); err != nil { + panic(err) + } + return buf.String() +} + +// walker adapts a function to satisfy the ast.Visitor interface. +// The function return whether the walk should proceed into the node's children. +type walker func(ast.Node) bool + +func (w walker) Visit(node ast.Node) ast.Visitor { + if w(node) { + return w + } + return nil +} + +func isIdent(expr ast.Expr, ident string) bool { + id, ok := expr.(*ast.Ident) + return ok && id.Name == ident +} + +// isBlank returns whether id is the blank identifier "_". +// If id == nil, the answer is false. +func isBlank(id *ast.Ident) bool { return id != nil && id.Name == "_" } + +func isPkgDot(expr ast.Expr, pkg, name string) bool { + sel, ok := expr.(*ast.SelectorExpr) + return ok && isIdent(sel.X, pkg) && isIdent(sel.Sel, name) +} + +func isOne(expr ast.Expr) bool { + lit, ok := expr.(*ast.BasicLit) + return ok && lit.Kind == token.INT && lit.Value == "1" +} + +func isCgoExported(f *ast.FuncDecl) bool { + if f.Recv != nil || f.Doc == nil { + return false + } + + cgoExport := regexp.MustCompile(fmt.Sprintf("(?m)^//export %s$", regexp.QuoteMeta(f.Name.Name))) + for _, c := range f.Doc.List { + if cgoExport.MatchString(c.Text) { + return true + } + } + return false +} + +var basicTypeKinds = map[types.BasicKind]string{ + types.UntypedBool: "bool", + types.UntypedInt: "int", + types.UntypedRune: "rune", + types.UntypedFloat: "float64", + types.UntypedComplex: "complex128", + types.UntypedString: "string", +} + +// isUntypedConst reports whether expr is an untyped constant, +// and indicates what its default type is. +// scope may be nil. +func (f *file) isUntypedConst(expr ast.Expr) (defType string, ok bool) { + // Re-evaluate expr outside of its context to see if it's untyped. + // (An expr evaluated within, for example, an assignment context will get the type of the LHS.) + exprStr := f.render(expr) + tv, err := types.Eval(f.fset, f.pkg.typesPkg, expr.Pos(), exprStr) + if err != nil { + return "", false + } + if b, ok := tv.Type.(*types.Basic); ok { + if dt, ok := basicTypeKinds[b.Kind()]; ok { + return dt, true + } + } + + return "", false +} + +// firstLineOf renders the given node and returns its first line. +// It will also match the indentation of another node. +func (f *file) firstLineOf(node, match ast.Node) string { + line := f.render(node) + if i := strings.Index(line, "\n"); i >= 0 { + line = line[:i] + } + return f.indentOf(match) + line +} + +func (f *file) indentOf(node ast.Node) string { + line := srcLine(f.src, f.fset.Position(node.Pos())) + for i, r := range line { + switch r { + case ' ', '\t': + default: + return line[:i] + } + } + return line // unusual or empty line +} + +func (f *file) srcLineWithMatch(node ast.Node, pattern string) (m []string) { + line := srcLine(f.src, f.fset.Position(node.Pos())) + line = strings.TrimSuffix(line, "\n") + rx := regexp.MustCompile(pattern) + return rx.FindStringSubmatch(line) +} + +// imports returns true if the current file imports the specified package path. +func (f *file) imports(importPath string) bool { + all := astutil.Imports(f.fset, f.f) + for _, p := range all { + for _, i := range p { + uq, err := strconv.Unquote(i.Path.Value) + if err == nil && importPath == uq { + return true + } + } + } + return false +} + +// srcLine returns the complete line at p, including the terminating newline. +func srcLine(src []byte, p token.Position) string { + // Run to end of line in both directions if not at line start/end. + lo, hi := p.Offset, p.Offset+1 + for lo > 0 && src[lo-1] != '\n' { + lo-- + } + for hi < len(src) && src[hi-1] != '\n' { + hi++ + } + return string(src[lo:hi]) +} diff --git a/vendor/golang.org/x/mod/modfile/print.go b/vendor/golang.org/x/mod/modfile/print.go index 3bbea38529f..524f93022ac 100644 --- a/vendor/golang.org/x/mod/modfile/print.go +++ b/vendor/golang.org/x/mod/modfile/print.go @@ -138,16 +138,11 @@ func (p *printer) expr(x Expr) { p.printf(")") case *Line: - sep := "" - for _, tok := range x.Token { - p.printf("%s%s", sep, tok) - sep = " " - } + p.tokens(x.Token) case *LineBlock: - for _, tok := range x.Token { - p.printf("%s ", tok) - } + p.tokens(x.Token) + p.printf(" ") p.expr(&x.LParen) p.margin++ for _, l := range x.Line { @@ -163,3 +158,17 @@ func (p *printer) expr(x Expr) { // reach the end of the line. p.comment = append(p.comment, x.Comment().Suffix...) } + +func (p *printer) tokens(tokens []string) { + sep := "" + for _, t := range tokens { + if t == "," || t == ")" || t == "]" || t == "}" { + sep = "" + } + p.printf("%s%s", sep, t) + sep = " " + if t == "(" || t == "[" || t == "{" { + sep = "" + } + } +} diff --git a/vendor/golang.org/x/mod/modfile/read.go b/vendor/golang.org/x/mod/modfile/read.go index 616d00efdb1..c1f2008ee4c 100644 --- a/vendor/golang.org/x/mod/modfile/read.go +++ b/vendor/golang.org/x/mod/modfile/read.go @@ -2,13 +2,11 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Module file parser. -// This is a simplified copy of Google's buildifier parser. - package modfile import ( "bytes" + "errors" "fmt" "os" "strconv" @@ -323,18 +321,17 @@ func (x *RParen) Span() (start, end Position) { // An input represents a single input file being parsed. type input struct { // Lexing state. - filename string // name of input file, for errors - complete []byte // entire input - remaining []byte // remaining input - token []byte // token being scanned - lastToken string // most recently returned token, for error messages - pos Position // current input position - comments []Comment // accumulated comments - endRule int // position of end of current rule + filename string // name of input file, for errors + complete []byte // entire input + remaining []byte // remaining input + tokenStart []byte // token being scanned to end of input + token token // next token to be returned by lex, peek + pos Position // current input position + comments []Comment // accumulated comments // Parser state. - file *FileSyntax // returned top-level syntax tree - parseError error // error encountered during parsing + file *FileSyntax // returned top-level syntax tree + parseErrors ErrorList // errors encountered during parsing // Comment assignment state. pre []Expr // all expressions, in preorder traversal @@ -352,25 +349,32 @@ func newInput(filename string, data []byte) *input { // parse parses the input file. func parse(file string, data []byte) (f *FileSyntax, err error) { - in := newInput(file, data) // The parser panics for both routine errors like syntax errors // and for programmer bugs like array index errors. // Turn both into error returns. Catching bug panics is // especially important when processing many files. + in := newInput(file, data) defer func() { - if e := recover(); e != nil { - if e == in.parseError { - err = in.parseError - } else { - err = fmt.Errorf("%s:%d:%d: internal error: %v", in.filename, in.pos.Line, in.pos.LineRune, e) - } + if e := recover(); e != nil && e != &in.parseErrors { + in.parseErrors = append(in.parseErrors, Error{ + Filename: in.filename, + Pos: in.pos, + Err: fmt.Errorf("internal error: %v", e), + }) + } + if err == nil && len(in.parseErrors) > 0 { + err = in.parseErrors } }() + // Prime the lexer by reading in the first token. It will be available + // in the next peek() or lex() call. + in.readToken() + // Invoke the parser. in.parseFile() - if in.parseError != nil { - return nil, in.parseError + if len(in.parseErrors) > 0 { + return nil, in.parseErrors } in.file.Name = in.filename @@ -381,14 +385,14 @@ func parse(file string, data []byte) (f *FileSyntax, err error) { } // Error is called to report an error. -// The reason s is often "syntax error". // Error does not return: it panics. func (in *input) Error(s string) { - if s == "syntax error" && in.lastToken != "" { - s += " near " + in.lastToken - } - in.parseError = fmt.Errorf("%s:%d:%d: %v", in.filename, in.pos.Line, in.pos.LineRune, s) - panic(in.parseError) + in.parseErrors = append(in.parseErrors, Error{ + Filename: in.filename, + Pos: in.pos, + Err: errors.New(s), + }) + panic(&in.parseErrors) } // eof reports whether the input has reached end of file. @@ -434,46 +438,68 @@ func (in *input) readRune() int { return int(r) } -type symType struct { +type token struct { + kind tokenKind pos Position endPos Position text string } +type tokenKind int + +const ( + _EOF tokenKind = -(iota + 1) + _EOLCOMMENT + _IDENT + _STRING + _COMMENT + + // newlines and punctuation tokens are allowed as ASCII codes. +) + +func (k tokenKind) isComment() bool { + return k == _COMMENT || k == _EOLCOMMENT +} + +// isEOL returns whether a token terminates a line. +func (k tokenKind) isEOL() bool { + return k == _EOF || k == _EOLCOMMENT || k == '\n' +} + // startToken marks the beginning of the next input token. -// It must be followed by a call to endToken, once the token has +// It must be followed by a call to endToken, once the token's text has // been consumed using readRune. -func (in *input) startToken(sym *symType) { - in.token = in.remaining - sym.text = "" - sym.pos = in.pos +func (in *input) startToken() { + in.tokenStart = in.remaining + in.token.text = "" + in.token.pos = in.pos } // endToken marks the end of an input token. -// It records the actual token string in sym.text if the caller -// has not done that already. -func (in *input) endToken(sym *symType) { - if sym.text == "" { - tok := string(in.token[:len(in.token)-len(in.remaining)]) - sym.text = tok - in.lastToken = sym.text - } - sym.endPos = in.pos +// It records the actual token string in tok.text. +func (in *input) endToken(kind tokenKind) { + in.token.kind = kind + text := string(in.tokenStart[:len(in.tokenStart)-len(in.remaining)]) + in.token.text = text + in.token.endPos = in.pos +} + +// peek returns the kind of the the next token returned by lex. +func (in *input) peek() tokenKind { + return in.token.kind } // lex is called from the parser to obtain the next input token. -// It returns the token value (either a rune like '+' or a symbolic token _FOR) -// and sets val to the data associated with the token. -// For all our input tokens, the associated data is -// val.Pos (the position where the token begins) -// and val.Token (the input string corresponding to the token). -func (in *input) lex(sym *symType) int { +func (in *input) lex() token { + tok := in.token + in.readToken() + return tok +} + +// readToken lexes the next token from the text and stores it in in.token. +func (in *input) readToken() { // Skip past spaces, stopping at non-space or EOF. - countNL := 0 // number of newlines we've skipped past for !in.eof() { - // Skip over spaces. Count newlines so we can give the parser - // information about where top-level blank lines are, - // for top-level comment assignment. c := in.peekRune() if c == ' ' || c == '\t' || c == '\r' { in.readRune() @@ -482,7 +508,7 @@ func (in *input) lex(sym *symType) int { // Comment runs to end of line. if in.peekPrefix("//") { - in.startToken(sym) + in.startToken() // Is this comment the only thing on its line? // Find the last \n before this // and see if it's all @@ -495,30 +521,23 @@ func (in *input) lex(sym *symType) int { // Consume comment. for len(in.remaining) > 0 && in.readRune() != '\n' { } - in.endToken(sym) - - sym.text = strings.TrimRight(sym.text, "\n") - in.lastToken = "comment" // If we are at top level (not in a statement), hand the comment to // the parser as a _COMMENT token. The grammar is written // to handle top-level comments itself. if !suffix { - // Not in a statement. Tell parser about top-level comment. - return _COMMENT + in.endToken(_COMMENT) + return } // Otherwise, save comment for later attachment to syntax tree. - if countNL > 1 { - in.comments = append(in.comments, Comment{sym.pos, "", false}) - } - in.comments = append(in.comments, Comment{sym.pos, sym.text, suffix}) - countNL = 1 - return _EOL + in.endToken(_EOLCOMMENT) + in.comments = append(in.comments, Comment{in.token.pos, in.token.text, suffix}) + return } if in.peekPrefix("/*") { - in.Error(fmt.Sprintf("mod files must use // comments (not /* */ comments)")) + in.Error("mod files must use // comments (not /* */ comments)") } // Found non-space non-comment. @@ -526,35 +545,27 @@ func (in *input) lex(sym *symType) int { } // Found the beginning of the next token. - in.startToken(sym) - defer in.endToken(sym) + in.startToken() // End of file. if in.eof() { - in.lastToken = "EOF" - return _EOF + in.endToken(_EOF) + return } // Punctuation tokens. switch c := in.peekRune(); c { - case '\n': + case '\n', '(', ')', '[', ']', '{', '}', ',': in.readRune() - return c - - case '(': - in.readRune() - return c - - case ')': - in.readRune() - return c + in.endToken(tokenKind(c)) + return case '"', '`': // quoted string quote := c in.readRune() for { if in.eof() { - in.pos = sym.pos + in.pos = in.token.pos in.Error("unexpected EOF in string") } if in.peekRune() == '\n' { @@ -566,14 +577,14 @@ func (in *input) lex(sym *symType) int { } if c == '\\' && quote != '`' { if in.eof() { - in.pos = sym.pos + in.pos = in.token.pos in.Error("unexpected EOF in string") } in.readRune() } } - in.endToken(sym) - return _STRING + in.endToken(_STRING) + return } // Checked all punctuation. Must be identifier token. @@ -587,17 +598,23 @@ func (in *input) lex(sym *symType) int { break } if in.peekPrefix("/*") { - in.Error(fmt.Sprintf("mod files must use // comments (not /* */ comments)")) + in.Error("mod files must use // comments (not /* */ comments)") } in.readRune() } - return _IDENT + in.endToken(_IDENT) } // isIdent reports whether c is an identifier rune. -// We treat nearly all runes as identifier runes. +// We treat most printable runes as identifier runes, except for a handful of +// ASCII punctuation characters. func isIdent(c int) bool { - return c != 0 && !unicode.IsSpace(rune(c)) + switch r := rune(c); r { + case ' ', '(', ')', '[', ']', '{', '}', ',': + return false + default: + return !unicode.IsSpace(r) && unicode.IsPrint(r) + } } // Comment assignment. @@ -668,7 +685,7 @@ func (in *input) assignComments() { for _, x := range in.pre { start, _ := x.Span() if debug { - fmt.Printf("pre %T :%d:%d #%d\n", x, start.Line, start.LineRune, start.Byte) + fmt.Fprintf(os.Stderr, "pre %T :%d:%d #%d\n", x, start.Line, start.LineRune, start.Byte) } xcom := x.Comment() for len(line) > 0 && start.Byte >= line[0].Start.Byte { @@ -695,7 +712,7 @@ func (in *input) assignComments() { start, end := x.Span() if debug { - fmt.Printf("post %T :%d:%d #%d :%d:%d #%d\n", x, start.Line, start.LineRune, start.Byte, end.Line, end.LineRune, end.Byte) + fmt.Fprintf(os.Stderr, "post %T :%d:%d #%d :%d:%d #%d\n", x, start.Line, start.LineRune, start.Byte, end.Line, end.LineRune, end.Byte) } // Do not assign suffix comments to end of line block or whole file. @@ -745,29 +762,29 @@ func reverseComments(list []Comment) { func (in *input) parseFile() { in.file = new(FileSyntax) - var sym symType var cb *CommentBlock for { - tok := in.lex(&sym) - switch tok { + switch in.peek() { case '\n': + in.lex() if cb != nil { in.file.Stmt = append(in.file.Stmt, cb) cb = nil } case _COMMENT: + tok := in.lex() if cb == nil { - cb = &CommentBlock{Start: sym.pos} + cb = &CommentBlock{Start: tok.pos} } com := cb.Comment() - com.Before = append(com.Before, Comment{Start: sym.pos, Token: sym.text}) + com.Before = append(com.Before, Comment{Start: tok.pos, Token: tok.text}) case _EOF: if cb != nil { in.file.Stmt = append(in.file.Stmt, cb) } return default: - in.parseStmt(&sym) + in.parseStmt() if cb != nil { in.file.Stmt[len(in.file.Stmt)-1].Comment().Before = cb.Before cb = nil @@ -776,60 +793,88 @@ func (in *input) parseFile() { } } -func (in *input) parseStmt(sym *symType) { - start := sym.pos - end := sym.endPos - token := []string{sym.text} +func (in *input) parseStmt() { + tok := in.lex() + start := tok.pos + end := tok.endPos + tokens := []string{tok.text} for { - tok := in.lex(sym) - switch tok { - case '\n', _EOF, _EOL: + tok := in.lex() + switch { + case tok.kind.isEOL(): in.file.Stmt = append(in.file.Stmt, &Line{ Start: start, - Token: token, + Token: tokens, End: end, }) return - case '(': - in.file.Stmt = append(in.file.Stmt, in.parseLineBlock(start, token, sym)) - return + + case tok.kind == '(': + if next := in.peek(); next.isEOL() { + // Start of block: no more tokens on this line. + in.file.Stmt = append(in.file.Stmt, in.parseLineBlock(start, tokens, tok)) + return + } else if next == ')' { + rparen := in.lex() + if in.peek().isEOL() { + // Empty block. + in.lex() + in.file.Stmt = append(in.file.Stmt, &LineBlock{ + Start: start, + Token: tokens, + LParen: LParen{Pos: tok.pos}, + RParen: RParen{Pos: rparen.pos}, + }) + return + } + // '( )' in the middle of the line, not a block. + tokens = append(tokens, tok.text, rparen.text) + } else { + // '(' in the middle of the line, not a block. + tokens = append(tokens, tok.text) + } + default: - token = append(token, sym.text) - end = sym.endPos + tokens = append(tokens, tok.text) + end = tok.endPos } } } -func (in *input) parseLineBlock(start Position, token []string, sym *symType) *LineBlock { +func (in *input) parseLineBlock(start Position, token []string, lparen token) *LineBlock { x := &LineBlock{ Start: start, Token: token, - LParen: LParen{Pos: sym.pos}, + LParen: LParen{Pos: lparen.pos}, } var comments []Comment for { - tok := in.lex(sym) - switch tok { - case _EOL: - // ignore + switch in.peek() { + case _EOLCOMMENT: + // Suffix comment, will be attached later by assignComments. + in.lex() case '\n': + // Blank line. Add an empty comment to preserve it. + in.lex() if len(comments) == 0 && len(x.Line) > 0 || len(comments) > 0 && comments[len(comments)-1].Token != "" { comments = append(comments, Comment{}) } case _COMMENT: - comments = append(comments, Comment{Start: sym.pos, Token: sym.text}) + tok := in.lex() + comments = append(comments, Comment{Start: tok.pos, Token: tok.text}) case _EOF: in.Error(fmt.Sprintf("syntax error (unterminated block started at %s:%d:%d)", in.filename, x.Start.Line, x.Start.LineRune)) case ')': + rparen := in.lex() x.RParen.Before = comments - x.RParen.Pos = sym.pos - tok = in.lex(sym) - if tok != '\n' && tok != _EOF && tok != _EOL { + x.RParen.Pos = rparen.pos + if !in.peek().isEOL() { in.Error("syntax error (expected newline after closing paren)") } + in.lex() return x default: - l := in.parseLine(sym) + l := in.parseLine() x.Line = append(x.Line, l) l.Comment().Before = comments comments = nil @@ -837,35 +882,29 @@ func (in *input) parseLineBlock(start Position, token []string, sym *symType) *L } } -func (in *input) parseLine(sym *symType) *Line { - start := sym.pos - end := sym.endPos - token := []string{sym.text} +func (in *input) parseLine() *Line { + tok := in.lex() + if tok.kind.isEOL() { + in.Error("internal parse error: parseLine at end of line") + } + start := tok.pos + end := tok.endPos + tokens := []string{tok.text} for { - tok := in.lex(sym) - switch tok { - case '\n', _EOF, _EOL: + tok := in.lex() + if tok.kind.isEOL() { return &Line{ Start: start, - Token: token, + Token: tokens, End: end, InBlock: true, } - default: - token = append(token, sym.text) - end = sym.endPos } + tokens = append(tokens, tok.text) + end = tok.endPos } } -const ( - _EOF = -(1 + iota) - _EOL - _IDENT - _STRING - _COMMENT -) - var ( slashSlash = []byte("//") moduleStr = []byte("module") diff --git a/vendor/golang.org/x/mod/modfile/rule.go b/vendor/golang.org/x/mod/modfile/rule.go index 62af06889f6..91ca6828df0 100644 --- a/vendor/golang.org/x/mod/modfile/rule.go +++ b/vendor/golang.org/x/mod/modfile/rule.go @@ -2,10 +2,24 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +// Package modfile implements a parser and formatter for go.mod files. +// +// The go.mod syntax is described in +// https://golang.org/cmd/go/#hdr-The_go_mod_file. +// +// The Parse and ParseLax functions both parse a go.mod file and return an +// abstract syntax tree. ParseLax ignores unknown statements and may be used to +// parse go.mod files that may have been developed with newer versions of Go. +// +// The File struct returned by Parse and ParseLax represent an abstract +// go.mod file. File has several methods like AddNewRequire and DropReplace +// that can be used to programmatically edit a file. +// +// The Format function formats a File back to a byte slice which can be +// written to a file. package modfile import ( - "bytes" "errors" "fmt" "path/filepath" @@ -120,7 +134,7 @@ func parseToFile(file string, data []byte, fix VersionFixer, strict bool) (*File Syntax: fs, } - var errs bytes.Buffer + var errs ErrorList for _, x := range fs.Stmt { switch x := x.(type) { case *Line: @@ -129,14 +143,22 @@ func parseToFile(file string, data []byte, fix VersionFixer, strict bool) (*File case *LineBlock: if len(x.Token) > 1 { if strict { - fmt.Fprintf(&errs, "%s:%d: unknown block type: %s\n", file, x.Start.Line, strings.Join(x.Token, " ")) + errs = append(errs, Error{ + Filename: file, + Pos: x.Start, + Err: fmt.Errorf("unknown block type: %s", strings.Join(x.Token, " ")), + }) } continue } switch x.Token[0] { default: if strict { - fmt.Fprintf(&errs, "%s:%d: unknown block type: %s\n", file, x.Start.Line, strings.Join(x.Token, " ")) + errs = append(errs, Error{ + Filename: file, + Pos: x.Start, + Err: fmt.Errorf("unknown block type: %s", strings.Join(x.Token, " ")), + }) } continue case "module", "require", "exclude", "replace": @@ -147,15 +169,15 @@ func parseToFile(file string, data []byte, fix VersionFixer, strict bool) (*File } } - if errs.Len() > 0 { - return nil, errors.New(strings.TrimRight(errs.String(), "\n")) + if len(errs) > 0 { + return nil, errs } return f, nil } var GoVersionRE = lazyregexp.New(`^([1-9][0-9]*)\.(0|[1-9][0-9]*)$`) -func (f *File) add(errs *bytes.Buffer, line *Line, verb string, args []string, fix VersionFixer, strict bool) { +func (f *File) add(errs *ErrorList, line *Line, verb string, args []string, fix VersionFixer, strict bool) { // If strict is false, this module is a dependency. // We ignore all unknown directives as well as main-module-only // directives like replace and exclude. It will work better for @@ -171,60 +193,83 @@ func (f *File) add(errs *bytes.Buffer, line *Line, verb string, args []string, f } } + wrapModPathError := func(modPath string, err error) { + *errs = append(*errs, Error{ + Filename: f.Syntax.Name, + Pos: line.Start, + ModPath: modPath, + Verb: verb, + Err: err, + }) + } + wrapError := func(err error) { + *errs = append(*errs, Error{ + Filename: f.Syntax.Name, + Pos: line.Start, + Err: err, + }) + } + errorf := func(format string, args ...interface{}) { + wrapError(fmt.Errorf(format, args...)) + } + switch verb { default: - fmt.Fprintf(errs, "%s:%d: unknown directive: %s\n", f.Syntax.Name, line.Start.Line, verb) + errorf("unknown directive: %s", verb) case "go": if f.Go != nil { - fmt.Fprintf(errs, "%s:%d: repeated go statement\n", f.Syntax.Name, line.Start.Line) + errorf("repeated go statement") return } - if len(args) != 1 || !GoVersionRE.MatchString(args[0]) { - fmt.Fprintf(errs, "%s:%d: usage: go 1.23\n", f.Syntax.Name, line.Start.Line) + if len(args) != 1 { + errorf("go directive expects exactly one argument") + return + } else if !GoVersionRE.MatchString(args[0]) { + errorf("invalid go version '%s': must match format 1.23", args[0]) return } + f.Go = &Go{Syntax: line} f.Go.Version = args[0] case "module": if f.Module != nil { - fmt.Fprintf(errs, "%s:%d: repeated module statement\n", f.Syntax.Name, line.Start.Line) + errorf("repeated module statement") return } f.Module = &Module{Syntax: line} if len(args) != 1 { - - fmt.Fprintf(errs, "%s:%d: usage: module module/path\n", f.Syntax.Name, line.Start.Line) + errorf("usage: module module/path") return } s, err := parseString(&args[0]) if err != nil { - fmt.Fprintf(errs, "%s:%d: invalid quoted string: %v\n", f.Syntax.Name, line.Start.Line, err) + errorf("invalid quoted string: %v", err) return } f.Module.Mod = module.Version{Path: s} case "require", "exclude": if len(args) != 2 { - fmt.Fprintf(errs, "%s:%d: usage: %s module/path v1.2.3\n", f.Syntax.Name, line.Start.Line, verb) + errorf("usage: %s module/path v1.2.3", verb) return } s, err := parseString(&args[0]) if err != nil { - fmt.Fprintf(errs, "%s:%d: invalid quoted string: %v\n", f.Syntax.Name, line.Start.Line, err) + errorf("invalid quoted string: %v", err) return } v, err := parseVersion(verb, s, &args[1], fix) if err != nil { - fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, err) + wrapError(err) return } pathMajor, err := modulePathMajor(s) if err != nil { - fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, err) + wrapError(err) return } if err := module.CheckPathMajor(v, pathMajor); err != nil { - fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, &Error{Verb: verb, ModPath: s, Err: err}) + wrapModPathError(s, err) return } if verb == "require" { @@ -245,55 +290,55 @@ func (f *File) add(errs *bytes.Buffer, line *Line, verb string, args []string, f arrow = 1 } if len(args) < arrow+2 || len(args) > arrow+3 || args[arrow] != "=>" { - fmt.Fprintf(errs, "%s:%d: usage: %s module/path [v1.2.3] => other/module v1.4\n\t or %s module/path [v1.2.3] => ../local/directory\n", f.Syntax.Name, line.Start.Line, verb, verb) + errorf("usage: %s module/path [v1.2.3] => other/module v1.4\n\t or %s module/path [v1.2.3] => ../local/directory", verb, verb) return } s, err := parseString(&args[0]) if err != nil { - fmt.Fprintf(errs, "%s:%d: invalid quoted string: %v\n", f.Syntax.Name, line.Start.Line, err) + errorf("invalid quoted string: %v", err) return } pathMajor, err := modulePathMajor(s) if err != nil { - fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, err) + wrapModPathError(s, err) return } var v string if arrow == 2 { v, err = parseVersion(verb, s, &args[1], fix) if err != nil { - fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, err) + wrapError(err) return } if err := module.CheckPathMajor(v, pathMajor); err != nil { - fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, &Error{Verb: verb, ModPath: s, Err: err}) + wrapModPathError(s, err) return } } ns, err := parseString(&args[arrow+1]) if err != nil { - fmt.Fprintf(errs, "%s:%d: invalid quoted string: %v\n", f.Syntax.Name, line.Start.Line, err) + errorf("invalid quoted string: %v", err) return } nv := "" if len(args) == arrow+2 { if !IsDirectoryPath(ns) { - fmt.Fprintf(errs, "%s:%d: replacement module without version must be directory path (rooted or starting with ./ or ../)\n", f.Syntax.Name, line.Start.Line) + errorf("replacement module without version must be directory path (rooted or starting with ./ or ../)") return } if filepath.Separator == '/' && strings.Contains(ns, `\`) { - fmt.Fprintf(errs, "%s:%d: replacement directory appears to be Windows path (on a non-windows system)\n", f.Syntax.Name, line.Start.Line) + errorf("replacement directory appears to be Windows path (on a non-windows system)") return } } if len(args) == arrow+3 { nv, err = parseVersion(verb, ns, &args[arrow+2], fix) if err != nil { - fmt.Fprintf(errs, "%s:%d: %v\n", f.Syntax.Name, line.Start.Line, err) + wrapError(err) return } if IsDirectoryPath(ns) { - fmt.Fprintf(errs, "%s:%d: replacement module directory path %q cannot have version\n", f.Syntax.Name, line.Start.Line, ns) + errorf("replacement module directory path %q cannot have version", ns) return } } @@ -372,8 +417,19 @@ func IsDirectoryPath(ns string) bool { // a single token in a go.mod line. func MustQuote(s string) bool { for _, r := range s { - if !unicode.IsPrint(r) || r == ' ' || r == '"' || r == '\'' || r == '`' { + switch r { + case ' ', '"', '\'', '`': return true + + case '(', ')', '[', ']', '{', '}', ',': + if len(s) > 1 { + return true + } + + default: + if !unicode.IsPrint(r) { + return true + } } } return s == "" || strings.Contains(s, "//") || strings.Contains(s, "/*") @@ -405,14 +461,42 @@ func parseString(s *string) (string, error) { return t, nil } +type ErrorList []Error + +func (e ErrorList) Error() string { + errStrs := make([]string, len(e)) + for i, err := range e { + errStrs[i] = err.Error() + } + return strings.Join(errStrs, "\n") +} + type Error struct { - Verb string - ModPath string - Err error + Filename string + Pos Position + Verb string + ModPath string + Err error } func (e *Error) Error() string { - return fmt.Sprintf("%s %s: %v", e.Verb, e.ModPath, e.Err) + var pos string + if e.Pos.LineRune > 1 { + // Don't print LineRune if it's 1 (beginning of line). + // It's always 1 except in scanner errors, which are rare. + pos = fmt.Sprintf("%s:%d:%d: ", e.Filename, e.Pos.Line, e.Pos.LineRune) + } else if e.Pos.Line > 0 { + pos = fmt.Sprintf("%s:%d: ", e.Filename, e.Pos.Line) + } else if e.Filename != "" { + pos = fmt.Sprintf("%s: ", e.Filename) + } + + var directive string + if e.ModPath != "" { + directive = fmt.Sprintf("%s %s: ", e.Verb, e.ModPath) + } + + return pos + directive + e.Err.Error() } func (e *Error) Unwrap() error { return e.Err } diff --git a/vendor/golang.org/x/net/http2/client_conn_pool.go b/vendor/golang.org/x/net/http2/client_conn_pool.go index f4d9b5ece3e..3a67636fe25 100644 --- a/vendor/golang.org/x/net/http2/client_conn_pool.go +++ b/vendor/golang.org/x/net/http2/client_conn_pool.go @@ -107,6 +107,7 @@ func (p *clientConnPool) getClientConn(req *http.Request, addr string, dialOnMis // dialCall is an in-flight Transport dial call to a host. type dialCall struct { + _ incomparable p *clientConnPool done chan struct{} // closed when done res *ClientConn // valid after done is closed @@ -180,6 +181,7 @@ func (p *clientConnPool) addConnIfNeeded(key string, t *Transport, c *tls.Conn) } type addConnCall struct { + _ incomparable p *clientConnPool done chan struct{} // closed when done err error @@ -200,12 +202,6 @@ func (c *addConnCall) run(t *Transport, key string, tc *tls.Conn) { close(c.done) } -func (p *clientConnPool) addConn(key string, cc *ClientConn) { - p.mu.Lock() - p.addConnLocked(key, cc) - p.mu.Unlock() -} - // p.mu must be held func (p *clientConnPool) addConnLocked(key string, cc *ClientConn) { for _, v := range p.conns[key] { diff --git a/vendor/golang.org/x/net/http2/flow.go b/vendor/golang.org/x/net/http2/flow.go index cea601fcdf4..b51f0e0cf1f 100644 --- a/vendor/golang.org/x/net/http2/flow.go +++ b/vendor/golang.org/x/net/http2/flow.go @@ -8,6 +8,8 @@ package http2 // flow is the flow control window's size. type flow struct { + _ incomparable + // n is the number of DATA bytes we're allowed to send. // A flow is kept both on a conn and a per-stream. n int32 diff --git a/vendor/golang.org/x/net/http2/hpack/huffman.go b/vendor/golang.org/x/net/http2/hpack/huffman.go index b412a96c504..a1ab2f05679 100644 --- a/vendor/golang.org/x/net/http2/hpack/huffman.go +++ b/vendor/golang.org/x/net/http2/hpack/huffman.go @@ -105,7 +105,14 @@ func huffmanDecode(buf *bytes.Buffer, maxLen int, v []byte) error { return nil } +// incomparable is a zero-width, non-comparable type. Adding it to a struct +// makes that struct also non-comparable, and generally doesn't add +// any size (as long as it's first). +type incomparable [0]func() + type node struct { + _ incomparable + // children is non-nil for internal nodes children *[256]*node diff --git a/vendor/golang.org/x/net/http2/http2.go b/vendor/golang.org/x/net/http2/http2.go index 27cc893cc0e..5571ccfd261 100644 --- a/vendor/golang.org/x/net/http2/http2.go +++ b/vendor/golang.org/x/net/http2/http2.go @@ -241,6 +241,7 @@ func (cw closeWaiter) Wait() { // Its buffered writer is lazily allocated as needed, to minimize // idle memory usage with many connections. type bufferedWriter struct { + _ incomparable w io.Writer // immutable bw *bufio.Writer // non-nil when data is buffered } @@ -313,6 +314,7 @@ func bodyAllowedForStatus(status int) bool { } type httpError struct { + _ incomparable msg string timeout bool } @@ -376,3 +378,8 @@ func (s *sorter) SortStrings(ss []string) { func validPseudoPath(v string) bool { return (len(v) > 0 && v[0] == '/') || v == "*" } + +// incomparable is a zero-width, non-comparable type. Adding it to a struct +// makes that struct also non-comparable, and generally doesn't add +// any size (as long as it's first). +type incomparable [0]func() diff --git a/vendor/golang.org/x/net/http2/server.go b/vendor/golang.org/x/net/http2/server.go index bc9e41a1b77..345b7cd85db 100644 --- a/vendor/golang.org/x/net/http2/server.go +++ b/vendor/golang.org/x/net/http2/server.go @@ -761,6 +761,7 @@ func (sc *serverConn) readFrames() { // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine. type frameWriteResult struct { + _ incomparable wr FrameWriteRequest // what was written (or attempted) err error // result of the writeFrame call } @@ -771,7 +772,7 @@ type frameWriteResult struct { // serverConn. func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest) { err := wr.write.writeFrame(sc) - sc.wroteFrameCh <- frameWriteResult{wr, err} + sc.wroteFrameCh <- frameWriteResult{wr: wr, err: err} } func (sc *serverConn) closeAllStreamsOnConnClose() { @@ -1161,7 +1162,7 @@ func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) { if wr.write.staysWithinBuffer(sc.bw.Available()) { sc.writingFrameAsync = false err := wr.write.writeFrame(sc) - sc.wroteFrame(frameWriteResult{wr, err}) + sc.wroteFrame(frameWriteResult{wr: wr, err: err}) } else { sc.writingFrameAsync = true go sc.writeFrameAsync(wr) @@ -2057,7 +2058,7 @@ func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*r var trailer http.Header for _, v := range rp.header["Trailer"] { for _, key := range strings.Split(v, ",") { - key = http.CanonicalHeaderKey(strings.TrimSpace(key)) + key = http.CanonicalHeaderKey(textproto.TrimString(key)) switch key { case "Transfer-Encoding", "Trailer", "Content-Length": // Bogus. (copy of http1 rules) @@ -2275,6 +2276,7 @@ func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) { // requestBody is the Handler's Request.Body type. // Read and Close may be called concurrently. type requestBody struct { + _ incomparable stream *stream conn *serverConn closed bool // for use by Close only diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go index 81778bec612..76a92e0ca6b 100644 --- a/vendor/golang.org/x/net/http2/transport.go +++ b/vendor/golang.org/x/net/http2/transport.go @@ -108,6 +108,19 @@ type Transport struct { // waiting for their turn. StrictMaxConcurrentStreams bool + // ReadIdleTimeout is the timeout after which a health check using ping + // frame will be carried out if no frame is received on the connection. + // Note that a ping response will is considered a received frame, so if + // there is no other traffic on the connection, the health check will + // be performed every ReadIdleTimeout interval. + // If zero, no health check is performed. + ReadIdleTimeout time.Duration + + // PingTimeout is the timeout after which the connection will be closed + // if a response to Ping is not received. + // Defaults to 15s. + PingTimeout time.Duration + // t1, if non-nil, is the standard library Transport using // this transport. Its settings are used (but not its // RoundTrip method, etc). @@ -131,6 +144,14 @@ func (t *Transport) disableCompression() bool { return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression) } +func (t *Transport) pingTimeout() time.Duration { + if t.PingTimeout == 0 { + return 15 * time.Second + } + return t.PingTimeout + +} + // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2. // It returns an error if t1 has already been HTTP/2-enabled. func ConfigureTransport(t1 *http.Transport) error { @@ -675,6 +696,20 @@ func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, erro return cc, nil } +func (cc *ClientConn) healthCheck() { + pingTimeout := cc.t.pingTimeout() + // We don't need to periodically ping in the health check, because the readLoop of ClientConn will + // trigger the healthCheck again if there is no frame received. + ctx, cancel := context.WithTimeout(context.Background(), pingTimeout) + defer cancel() + err := cc.Ping(ctx) + if err != nil { + cc.closeForLostPing() + cc.t.connPool().MarkDead(cc) + return + } +} + func (cc *ClientConn) setGoAway(f *GoAwayFrame) { cc.mu.Lock() defer cc.mu.Unlock() @@ -846,14 +881,12 @@ func (cc *ClientConn) sendGoAway() error { return nil } -// Close closes the client connection immediately. -// -// In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead. -func (cc *ClientConn) Close() error { +// closes the client connection immediately. In-flight requests are interrupted. +// err is sent to streams. +func (cc *ClientConn) closeForError(err error) error { cc.mu.Lock() defer cc.cond.Broadcast() defer cc.mu.Unlock() - err := errors.New("http2: client connection force closed via ClientConn.Close") for id, cs := range cc.streams { select { case cs.resc <- resAndError{err: err}: @@ -866,6 +899,20 @@ func (cc *ClientConn) Close() error { return cc.tconn.Close() } +// Close closes the client connection immediately. +// +// In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead. +func (cc *ClientConn) Close() error { + err := errors.New("http2: client connection force closed via ClientConn.Close") + return cc.closeForError(err) +} + +// closes the client connection immediately. In-flight requests are interrupted. +func (cc *ClientConn) closeForLostPing() error { + err := errors.New("http2: client connection lost") + return cc.closeForError(err) +} + const maxAllocFrameSize = 512 << 10 // frameBuffer returns a scratch buffer suitable for writing DATA frames. @@ -916,7 +963,7 @@ func commaSeparatedTrailers(req *http.Request) (string, error) { k = http.CanonicalHeaderKey(k) switch k { case "Transfer-Encoding", "Trailer", "Content-Length": - return "", &badStringError{"invalid Trailer key", k} + return "", fmt.Errorf("invalid Trailer key %q", k) } keys = append(keys, k) } @@ -1394,13 +1441,6 @@ func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) } } -type badStringError struct { - what string - str string -} - -func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) } - // requires cc.mu be held. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) { cc.hbuf.Reset() @@ -1616,6 +1656,7 @@ func (cc *ClientConn) writeHeader(name, value string) { } type resAndError struct { + _ incomparable res *http.Response err error } @@ -1663,6 +1704,7 @@ func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream { // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop. type clientConnReadLoop struct { + _ incomparable cc *ClientConn closeWhenIdle bool } @@ -1742,8 +1784,17 @@ func (rl *clientConnReadLoop) run() error { rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse gotReply := false // ever saw a HEADERS reply gotSettings := false + readIdleTimeout := cc.t.ReadIdleTimeout + var t *time.Timer + if readIdleTimeout != 0 { + t = time.AfterFunc(readIdleTimeout, cc.healthCheck) + defer t.Stop() + } for { f, err := cc.fr.ReadFrame() + if t != nil { + t.Reset(readIdleTimeout) + } if err != nil { cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err) } @@ -1892,7 +1943,9 @@ func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFra return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header") } - header := make(http.Header) + regularFields := f.RegularFields() + strs := make([]string, len(regularFields)) + header := make(http.Header, len(regularFields)) res := &http.Response{ Proto: "HTTP/2.0", ProtoMajor: 2, @@ -1900,7 +1953,7 @@ func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFra StatusCode: statusCode, Status: status + " " + http.StatusText(statusCode), } - for _, hf := range f.RegularFields() { + for _, hf := range regularFields { key := http.CanonicalHeaderKey(hf.Name) if key == "Trailer" { t := res.Trailer @@ -1912,7 +1965,18 @@ func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFra t[http.CanonicalHeaderKey(v)] = nil }) } else { - header[key] = append(header[key], hf.Value) + vv := header[key] + if vv == nil && len(strs) > 0 { + // More than likely this will be a single-element key. + // Most headers aren't multi-valued. + // Set the capacity on strs[0] to 1, so any future append + // won't extend the slice into the other strings. + vv, strs = strs[:1:1], strs[1:] + vv[0] = hf.Value + header[key] = vv + } else { + header[key] = append(vv, hf.Value) + } } } @@ -2466,6 +2530,7 @@ func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { // gzipReader wraps a response body so it can lazily // call gzip.NewReader on the first call to Read type gzipReader struct { + _ incomparable body io.ReadCloser // underlying Response.Body zr *gzip.Reader // lazily-initialized gzip reader zerr error // sticky error diff --git a/vendor/golang.org/x/oauth2/README.md b/vendor/golang.org/x/oauth2/README.md index 0f443e6934d..8cfd6063e72 100644 --- a/vendor/golang.org/x/oauth2/README.md +++ b/vendor/golang.org/x/oauth2/README.md @@ -16,15 +16,16 @@ Or you can manually git clone the repository to See godoc for further documentation and examples. -* [godoc.org/golang.org/x/oauth2](http://godoc.org/golang.org/x/oauth2) -* [godoc.org/golang.org/x/oauth2/google](http://godoc.org/golang.org/x/oauth2/google) +* [godoc.org/golang.org/x/oauth2](https://godoc.org/golang.org/x/oauth2) +* [godoc.org/golang.org/x/oauth2/google](https://godoc.org/golang.org/x/oauth2/google) ## Policy for new packages -We no longer accept new provider-specific packages in this repo. For -defining provider endpoints and provider-specific OAuth2 behavior, we -encourage you to create packages elsewhere. We'll keep the existing -packages for compatibility. +We no longer accept new provider-specific packages in this repo if all +they do is add a single endpoint variable. If you just want to add a +single endpoint, add it to the +[godoc.org/golang.org/x/oauth2/endpoints](https://godoc.org/golang.org/x/oauth2/endpoints) +package. ## Report Issues / Send Patches diff --git a/vendor/golang.org/x/oauth2/transport.go b/vendor/golang.org/x/oauth2/transport.go index aa0d34f1e0e..90657915fbc 100644 --- a/vendor/golang.org/x/oauth2/transport.go +++ b/vendor/golang.org/x/oauth2/transport.go @@ -6,7 +6,7 @@ package oauth2 import ( "errors" - "io" + "log" "net/http" "sync" ) @@ -25,9 +25,6 @@ type Transport struct { // Base is the base RoundTripper used to make HTTP requests. // If nil, http.DefaultTransport is used. Base http.RoundTripper - - mu sync.Mutex // guards modReq - modReq map[*http.Request]*http.Request // original -> modified } // RoundTrip authorizes and authenticates the request with an @@ -52,35 +49,22 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { req2 := cloneRequest(req) // per RoundTripper contract token.SetAuthHeader(req2) - t.setModReq(req, req2) - res, err := t.base().RoundTrip(req2) - // req.Body is assumed to have been closed by the base RoundTripper. + // req.Body is assumed to be closed by the base RoundTripper. reqBodyClosed = true - - if err != nil { - t.setModReq(req, nil) - return nil, err - } - res.Body = &onEOFReader{ - rc: res.Body, - fn: func() { t.setModReq(req, nil) }, - } - return res, nil + return t.base().RoundTrip(req2) } -// CancelRequest cancels an in-flight request by closing its connection. +var cancelOnce sync.Once + +// CancelRequest does nothing. It used to be a legacy cancellation mechanism +// but now only it only logs on first use to warn that it's deprecated. +// +// Deprecated: use contexts for cancellation instead. func (t *Transport) CancelRequest(req *http.Request) { - type canceler interface { - CancelRequest(*http.Request) - } - if cr, ok := t.base().(canceler); ok { - t.mu.Lock() - modReq := t.modReq[req] - delete(t.modReq, req) - t.mu.Unlock() - cr.CancelRequest(modReq) - } + cancelOnce.Do(func() { + log.Printf("deprecated: golang.org/x/oauth2: Transport.CancelRequest no longer does anything; use contexts") + }) } func (t *Transport) base() http.RoundTripper { @@ -90,19 +74,6 @@ func (t *Transport) base() http.RoundTripper { return http.DefaultTransport } -func (t *Transport) setModReq(orig, mod *http.Request) { - t.mu.Lock() - defer t.mu.Unlock() - if t.modReq == nil { - t.modReq = make(map[*http.Request]*http.Request) - } - if mod == nil { - delete(t.modReq, orig) - } else { - t.modReq[orig] = mod - } -} - // cloneRequest returns a clone of the provided *http.Request. // The clone is a shallow copy of the struct and its Header map. func cloneRequest(r *http.Request) *http.Request { @@ -116,29 +87,3 @@ func cloneRequest(r *http.Request) *http.Request { } return r2 } - -type onEOFReader struct { - rc io.ReadCloser - fn func() -} - -func (r *onEOFReader) Read(p []byte) (n int, err error) { - n, err = r.rc.Read(p) - if err == io.EOF { - r.runFunc() - } - return -} - -func (r *onEOFReader) Close() error { - err := r.rc.Close() - r.runFunc() - return err -} - -func (r *onEOFReader) runFunc() { - if fn := r.fn; fn != nil { - fn() - r.fn = nil - } -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_aix.go b/vendor/golang.org/x/sys/cpu/cpu_aix.go new file mode 100644 index 00000000000..da298966872 --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/cpu_aix.go @@ -0,0 +1,34 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build aix + +package cpu + +const cacheLineSize = 128 + +const ( + // getsystemcfg constants + _SC_IMPL = 2 + _IMPL_POWER8 = 0x10000 + _IMPL_POWER9 = 0x20000 +) + +func init() { + impl := getsystemcfg(_SC_IMPL) + if impl&_IMPL_POWER8 != 0 { + PPC64.IsPOWER8 = true + } + if impl&_IMPL_POWER9 != 0 { + PPC64.IsPOWER9 = true + } + + Initialized = true +} + +func getsystemcfg(label int) (n uint64) { + r0, _ := callgetsystemcfg(label) + n = uint64(r0) + return +} diff --git a/vendor/golang.org/x/sys/cpu/cpu_aix_ppc64.go b/vendor/golang.org/x/sys/cpu/cpu_aix_ppc64.go deleted file mode 100644 index be602722472..00000000000 --- a/vendor/golang.org/x/sys/cpu/cpu_aix_ppc64.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build aix,ppc64 - -package cpu - -const cacheLineSize = 128 - -const ( - // getsystemcfg constants - _SC_IMPL = 2 - _IMPL_POWER8 = 0x10000 - _IMPL_POWER9 = 0x20000 -) - -func init() { - impl := getsystemcfg(_SC_IMPL) - if impl&_IMPL_POWER8 != 0 { - PPC64.IsPOWER8 = true - } - if impl&_IMPL_POWER9 != 0 { - PPC64.IsPOWER9 = true - } - - Initialized = true -} - -func getsystemcfg(label int) (n uint64) { - r0, _ := callgetsystemcfg(label) - n = uint64(r0) - return -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_arm64.go index 9c87677aef9..7bcb36c7bb5 100644 --- a/vendor/golang.org/x/sys/cpu/cpu_arm64.go +++ b/vendor/golang.org/x/sys/cpu/cpu_arm64.go @@ -10,8 +10,14 @@ const cacheLineSize = 64 func init() { switch runtime.GOOS { - case "android", "darwin": + case "android", "darwin", "netbsd": // Android and iOS don't seem to allow reading these registers. + // + // NetBSD: + // ID_AA64ISAR0_EL1 is a privileged register and cannot be read from EL0. + // It can be read via sysctl(3). Example for future implementers: + // https://nxr.netbsd.org/xref/src/usr.sbin/cpuctl/arch/aarch64.c + // // Fake the minimal features expected by // TestARM64minimalFeatures. ARM64.HasASIMD = true diff --git a/vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go b/vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go new file mode 100644 index 00000000000..76fbe40b762 --- /dev/null +++ b/vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go @@ -0,0 +1,27 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Recreate a getsystemcfg syscall handler instead of +// using the one provided by x/sys/unix to avoid having +// the dependency between them. (See golang.org/issue/32102) +// Morever, this file will be used during the building of +// gccgo's libgo and thus must not used a CGo method. + +// +build aix +// +build gccgo + +package cpu + +import ( + "syscall" +) + +//extern getsystemcfg +func gccgoGetsystemcfg(label uint32) (r uint64) + +func callgetsystemcfg(label int) (r1 uintptr, e1 syscall.Errno) { + r1 = uintptr(gccgoGetsystemcfg(uint32(label))) + e1 = syscall.GetErrno() + return +} diff --git a/vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go b/vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go new file mode 100644 index 00000000000..e07899b909b --- /dev/null +++ b/vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go @@ -0,0 +1,30 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package unsafeheader contains header declarations for the Go runtime's +// slice and string implementations. +// +// This package allows x/sys to use types equivalent to +// reflect.SliceHeader and reflect.StringHeader without introducing +// a dependency on the (relatively heavy) "reflect" package. +package unsafeheader + +import ( + "unsafe" +) + +// Slice is the runtime representation of a slice. +// It cannot be used safely or portably and its representation may change in a later release. +type Slice struct { + Data unsafe.Pointer + Len int + Cap int +} + +// String is the runtime representation of a string. +// It cannot be used safely or portably and its representation may change in a later release. +type String struct { + Data unsafe.Pointer + Len int +} diff --git a/vendor/golang.org/x/sys/unix/README.md b/vendor/golang.org/x/sys/unix/README.md index ab433ccfbb4..579d2d73557 100644 --- a/vendor/golang.org/x/sys/unix/README.md +++ b/vendor/golang.org/x/sys/unix/README.md @@ -89,7 +89,7 @@ constants. Adding new syscall numbers is mostly done by running the build on a sufficiently new installation of the target OS (or updating the source checkouts for the -new build system). However, depending on the OS, you make need to update the +new build system). However, depending on the OS, you may need to update the parsing in mksysnum. ### mksyscall.go @@ -163,7 +163,7 @@ The merge is performed in the following steps: ## Generated files -### `zerror_${GOOS}_${GOARCH}.go` +### `zerrors_${GOOS}_${GOARCH}.go` A file containing all of the system's generated error numbers, error strings, signal numbers, and constants. Generated by `mkerrors.sh` (see above). diff --git a/vendor/golang.org/x/sys/unix/errors_freebsd_386.go b/vendor/golang.org/x/sys/unix/errors_freebsd_386.go index c56bc8b05e0..761db66efec 100644 --- a/vendor/golang.org/x/sys/unix/errors_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/errors_freebsd_386.go @@ -8,6 +8,7 @@ package unix const ( + DLT_HHDLC = 0x79 IFF_SMART = 0x20 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 @@ -210,13 +211,18 @@ const ( IFT_XETHER = 0x1a IPPROTO_MAXID = 0x34 IPV6_FAITH = 0x1d + IPV6_MIN_MEMBERSHIPS = 0x1f IP_FAITH = 0x16 + IP_MAX_SOURCE_FILTER = 0x400 + IP_MIN_MEMBERSHIPS = 0x1f MAP_NORESERVE = 0x40 MAP_RENAME = 0x20 NET_RT_MAXID = 0x6 RTF_PRCLONING = 0x10000 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa + RT_CACHING_CONTEXT = 0x1 + RT_NORTREF = 0x2 SIOCADDRT = 0x8030720a SIOCALIFADDR = 0x8118691b SIOCDELRT = 0x8030720b diff --git a/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go index 3e9771175ab..070f44b6510 100644 --- a/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/errors_freebsd_amd64.go @@ -8,6 +8,7 @@ package unix const ( + DLT_HHDLC = 0x79 IFF_SMART = 0x20 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 @@ -210,13 +211,18 @@ const ( IFT_XETHER = 0x1a IPPROTO_MAXID = 0x34 IPV6_FAITH = 0x1d + IPV6_MIN_MEMBERSHIPS = 0x1f IP_FAITH = 0x16 + IP_MAX_SOURCE_FILTER = 0x400 + IP_MIN_MEMBERSHIPS = 0x1f MAP_NORESERVE = 0x40 MAP_RENAME = 0x20 NET_RT_MAXID = 0x6 RTF_PRCLONING = 0x10000 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa + RT_CACHING_CONTEXT = 0x1 + RT_NORTREF = 0x2 SIOCADDRT = 0x8040720a SIOCALIFADDR = 0x8118691b SIOCDELRT = 0x8040720b diff --git a/vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go new file mode 100644 index 00000000000..946dcf3fc7e --- /dev/null +++ b/vendor/golang.org/x/sys/unix/errors_freebsd_arm64.go @@ -0,0 +1,17 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Constants that were deprecated or moved to enums in the FreeBSD headers. Keep +// them here for backwards compatibility. + +package unix + +const ( + DLT_HHDLC = 0x79 + IPV6_MIN_MEMBERSHIPS = 0x1f + IP_MAX_SOURCE_FILTER = 0x400 + IP_MIN_MEMBERSHIPS = 0x1f + RT_CACHING_CONTEXT = 0x1 + RT_NORTREF = 0x2 +) diff --git a/vendor/golang.org/x/sys/unix/mkall.sh b/vendor/golang.org/x/sys/unix/mkall.sh index fa0c69b9da0..ece31e9dcdc 100644 --- a/vendor/golang.org/x/sys/unix/mkall.sh +++ b/vendor/golang.org/x/sys/unix/mkall.sh @@ -124,7 +124,7 @@ freebsd_arm) freebsd_arm64) mkerrors="$mkerrors -m64" mksysnum="go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" + mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; netbsd_386) mkerrors="$mkerrors -m32" @@ -190,6 +190,12 @@ solaris_amd64) mksysnum= mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; +illumos_amd64) + mksyscall="go run mksyscall_solaris.go" + mkerrors= + mksysnum= + mktypes= + ;; *) echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 exit 1 @@ -217,6 +223,11 @@ esac echo "$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; # 1.13 and later, syscalls via libSystem (including syscallPtr) echo "$mksyscall -tags $GOOS,$GOARCH,go1.13 syscall_darwin.1_13.go |gofmt >zsyscall_$GOOSARCH.1_13.go"; + elif [ "$GOOS" == "illumos" ]; then + # illumos code generation requires a --illumos switch + echo "$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go"; + # illumos implies solaris, so solaris code generation is also required + echo "$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go"; else echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; fi diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index 96bf2a91978..780e387e3f1 100644 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -105,6 +105,7 @@ includes_FreeBSD=' #include #include #include +#include #include #include #include @@ -186,6 +187,7 @@ struct ltchars { #include #include #include +#include #include #include #include @@ -199,6 +201,7 @@ struct ltchars { #include #include #include +#include #include #include #include @@ -280,6 +283,11 @@ struct ltchars { // for the tipc_subscr timeout __u32 field. #undef TIPC_WAIT_FOREVER #define TIPC_WAIT_FOREVER 0xffffffff + +// Copied from linux/l2tp.h +// Including linux/l2tp.h here causes conflicts between linux/in.h +// and netinet/in.h included via net/route.h above. +#define IPPROTO_L2TP 115 ' includes_NetBSD=' @@ -473,12 +481,13 @@ ccflags="$@" $2 ~ /^(MS|MNT|UMOUNT)_/ || $2 ~ /^NS_GET_/ || $2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ || - $2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT)_/ || + $2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|TFD)_/ || $2 ~ /^KEXEC_/ || $2 ~ /^LINUX_REBOOT_CMD_/ || $2 ~ /^LINUX_REBOOT_MAGIC[12]$/ || $2 ~ /^MODULE_INIT_/ || $2 !~ "NLA_TYPE_MASK" && + $2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ && $2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ || $2 ~ /^SIOC/ || $2 ~ /^TIOC/ || @@ -488,6 +497,7 @@ ccflags="$@" $2 !~ "RTF_BITS" && $2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ || $2 ~ /^BIOC/ || + $2 ~ /^DIOC/ || $2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ || $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ || $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || @@ -499,7 +509,8 @@ ccflags="$@" $2 ~ /^CAP_/ || $2 ~ /^ALG_/ || $2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ || - $2 ~ /^FS_IOC_.*ENCRYPTION/ || + $2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|GETFLAGS)/ || + $2 ~ /^FS_VERITY_/ || $2 ~ /^FSCRYPT_/ || $2 ~ /^GRND_/ || $2 ~ /^RND/ || diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.1_13.go b/vendor/golang.org/x/sys/unix/syscall_darwin.1_13.go index f911617be95..dc0befee37e 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.1_13.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.1_13.go @@ -6,7 +6,11 @@ package unix -import "unsafe" +import ( + "unsafe" + + "golang.org/x/sys/internal/unsafeheader" +) //sys closedir(dir uintptr) (err error) //sys readdir_r(dir uintptr, entry *Dirent, result **Dirent) (res Errno) @@ -71,6 +75,7 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { cnt++ continue } + reclen := int(entry.Reclen) if reclen > len(buf) { // Not enough room. Return for now. @@ -79,13 +84,15 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { // restarting is O(n^2) in the length of the directory. Oh well. break } + // Copy entry into return buffer. - s := struct { - ptr unsafe.Pointer - siz int - cap int - }{ptr: unsafe.Pointer(&entry), siz: reclen, cap: reclen} - copy(buf, *(*[]byte)(unsafe.Pointer(&s))) + var s []byte + hdr := (*unsafeheader.Slice)(unsafe.Pointer(&s)) + hdr.Data = unsafe.Pointer(&entry) + hdr.Cap = reclen + hdr.Len = reclen + copy(buf, s) + buf = buf[reclen:] n += reclen cnt++ diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go index 9a5a6ee5445..0cf31acf02c 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -423,6 +423,7 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e //sysnb Getrlimit(which int, lim *Rlimit) (err error) //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Getsid(pid int) (sid int, err error) +//sysnb Gettimeofday(tp *Timeval) (err error) //sysnb Getuid() (uid int) //sysnb Issetugid() (tainted bool) //sys Kqueue() (fd int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin_386.go b/vendor/golang.org/x/sys/unix/syscall_darwin_386.go index 707ba4f59a2..2724e3a5128 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin_386.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin_386.go @@ -20,17 +20,6 @@ func setTimeval(sec, usec int64) Timeval { return Timeval{Sec: int32(sec), Usec: int32(usec)} } -//sysnb gettimeofday(tp *Timeval) (sec int32, usec int32, err error) -func Gettimeofday(tv *Timeval) (err error) { - // The tv passed to gettimeofday must be non-nil - // but is otherwise unused. The answers come back - // in the two registers. - sec, usec, err := gettimeofday(tv) - tv.Sec = int32(sec) - tv.Usec = int32(usec) - return err -} - func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint32(fd) k.Filter = int16(mode) diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go index fdbfb5911ac..ce2e0d24973 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go @@ -20,17 +20,6 @@ func setTimeval(sec, usec int64) Timeval { return Timeval{Sec: sec, Usec: int32(usec)} } -//sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error) -func Gettimeofday(tv *Timeval) (err error) { - // The tv passed to gettimeofday must be non-nil - // but is otherwise unused. The answers come back - // in the two registers. - sec, usec, err := gettimeofday(tv) - tv.Sec = sec - tv.Usec = usec - return err -} - func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint64(fd) k.Filter = int16(mode) diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go b/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go index f8bc4cfb1fa..fc17a3f232e 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go @@ -20,17 +20,6 @@ func setTimeval(sec, usec int64) Timeval { return Timeval{Sec: int32(sec), Usec: int32(usec)} } -//sysnb gettimeofday(tp *Timeval) (sec int32, usec int32, err error) -func Gettimeofday(tv *Timeval) (err error) { - // The tv passed to gettimeofday must be non-nil - // but is otherwise unused. The answers come back - // in the two registers. - sec, usec, err := gettimeofday(tv) - tv.Sec = int32(sec) - tv.Usec = int32(usec) - return err -} - func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint32(fd) k.Filter = int16(mode) diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go index 5ede3ac316a..1e91ddf3257 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go @@ -22,17 +22,6 @@ func setTimeval(sec, usec int64) Timeval { return Timeval{Sec: sec, Usec: int32(usec)} } -//sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error) -func Gettimeofday(tv *Timeval) (err error) { - // The tv passed to gettimeofday must be non-nil - // but is otherwise unused. The answers come back - // in the two registers. - sec, usec, err := gettimeofday(tv) - tv.Sec = sec - tv.Usec = usec - return err -} - func SetKevent(k *Kevent_t, fd, mode, flags int) { k.Ident = uint64(fd) k.Filter = int16(mode) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/golang.org/x/sys/unix/syscall_freebsd.go index 6b2eca493d1..6932e7c2c1a 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd.go @@ -521,10 +521,6 @@ func PtraceGetFpRegs(pid int, fpregsout *FpReg) (err error) { return ptrace(PTRACE_GETFPREGS, pid, uintptr(unsafe.Pointer(fpregsout)), 0) } -func PtraceGetFsBase(pid int, fsbase *int64) (err error) { - return ptrace(PTRACE_GETFSBASE, pid, uintptr(unsafe.Pointer(fsbase)), 0) -} - func PtraceGetRegs(pid int, regsout *Reg) (err error) { return ptrace(PTRACE_GETREGS, pid, uintptr(unsafe.Pointer(regsout)), 0) } diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go index 0a5a66fabd9..72a506ddcb5 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_386.go @@ -55,6 +55,10 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) +func PtraceGetFsBase(pid int, fsbase *int64) (err error) { + return ptrace(PTRACE_GETFSBASE, pid, uintptr(unsafe.Pointer(fsbase)), 0) +} + func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) { ioDesc := PtraceIoDesc{Op: int32(req), Offs: (*byte)(unsafe.Pointer(addr)), Addr: (*byte)(unsafe.Pointer(&out[0])), Len: uint32(countin)} err = ptrace(PTRACE_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go index 8025b22d089..d5e376acaea 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go @@ -55,6 +55,10 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) +func PtraceGetFsBase(pid int, fsbase *int64) (err error) { + return ptrace(PTRACE_GETFSBASE, pid, uintptr(unsafe.Pointer(fsbase)), 0) +} + func PtraceIO(req int, pid int, addr uintptr, out []byte, countin int) (count int, err error) { ioDesc := PtraceIoDesc{Op: int32(req), Offs: (*byte)(unsafe.Pointer(addr)), Addr: (*byte)(unsafe.Pointer(&out[0])), Len: uint64(countin)} err = ptrace(PTRACE_IO, pid, uintptr(unsafe.Pointer(&ioDesc)), 0) diff --git a/vendor/golang.org/x/sys/unix/syscall_illumos.go b/vendor/golang.org/x/sys/unix/syscall_illumos.go new file mode 100644 index 00000000000..99e62dcd828 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/syscall_illumos.go @@ -0,0 +1,57 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// illumos system calls not present on Solaris. + +// +build amd64,illumos + +package unix + +import "unsafe" + +func bytes2iovec(bs [][]byte) []Iovec { + iovecs := make([]Iovec, len(bs)) + for i, b := range bs { + iovecs[i].SetLen(len(b)) + if len(b) > 0 { + // somehow Iovec.Base on illumos is (*int8), not (*byte) + iovecs[i].Base = (*int8)(unsafe.Pointer(&b[0])) + } else { + iovecs[i].Base = (*int8)(unsafe.Pointer(&_zero)) + } + } + return iovecs +} + +//sys readv(fd int, iovs []Iovec) (n int, err error) + +func Readv(fd int, iovs [][]byte) (n int, err error) { + iovecs := bytes2iovec(iovs) + n, err = readv(fd, iovecs) + return n, err +} + +//sys preadv(fd int, iovs []Iovec, off int64) (n int, err error) + +func Preadv(fd int, iovs [][]byte, off int64) (n int, err error) { + iovecs := bytes2iovec(iovs) + n, err = preadv(fd, iovecs, off) + return n, err +} + +//sys writev(fd int, iovs []Iovec) (n int, err error) + +func Writev(fd int, iovs [][]byte) (n int, err error) { + iovecs := bytes2iovec(iovs) + n, err = writev(fd, iovecs) + return n, err +} + +//sys pwritev(fd int, iovs []Iovec, off int64) (n int, err error) + +func Pwritev(fd int, iovs [][]byte, off int64) (n int, err error) { + iovecs := bytes2iovec(iovs) + n, err = pwritev(fd, iovecs, off) + return n, err +} diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 95f7a159ad7..942a4bbf746 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -839,6 +839,40 @@ func (sa *SockaddrTIPC) sockaddr() (unsafe.Pointer, _Socklen, error) { return unsafe.Pointer(&sa.raw), SizeofSockaddrTIPC, nil } +// SockaddrL2TPIP implements the Sockaddr interface for IPPROTO_L2TP/AF_INET sockets. +type SockaddrL2TPIP struct { + Addr [4]byte + ConnId uint32 + raw RawSockaddrL2TPIP +} + +func (sa *SockaddrL2TPIP) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_INET + sa.raw.Conn_id = sa.ConnId + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Addr[i] = sa.Addr[i] + } + return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP, nil +} + +// SockaddrL2TPIP6 implements the Sockaddr interface for IPPROTO_L2TP/AF_INET6 sockets. +type SockaddrL2TPIP6 struct { + Addr [16]byte + ZoneId uint32 + ConnId uint32 + raw RawSockaddrL2TPIP6 +} + +func (sa *SockaddrL2TPIP6) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_INET6 + sa.raw.Conn_id = sa.ConnId + sa.raw.Scope_id = sa.ZoneId + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Addr[i] = sa.Addr[i] + } + return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP6, nil +} + func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { switch rsa.Addr.Family { case AF_NETLINK: @@ -889,25 +923,58 @@ func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) { return sa, nil case AF_INET: - pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet4) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] + proto, err := GetsockoptInt(fd, SOL_SOCKET, SO_PROTOCOL) + if err != nil { + return nil, err + } + + switch proto { + case IPPROTO_L2TP: + pp := (*RawSockaddrL2TPIP)(unsafe.Pointer(rsa)) + sa := new(SockaddrL2TPIP) + sa.ConnId = pp.Conn_id + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } + return sa, nil + default: + pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet4) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } + return sa, nil } - return sa, nil case AF_INET6: - pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) - sa := new(SockaddrInet6) - p := (*[2]byte)(unsafe.Pointer(&pp.Port)) - sa.Port = int(p[0])<<8 + int(p[1]) - sa.ZoneId = pp.Scope_id - for i := 0; i < len(sa.Addr); i++ { - sa.Addr[i] = pp.Addr[i] + proto, err := GetsockoptInt(fd, SOL_SOCKET, SO_PROTOCOL) + if err != nil { + return nil, err + } + + switch proto { + case IPPROTO_L2TP: + pp := (*RawSockaddrL2TPIP6)(unsafe.Pointer(rsa)) + sa := new(SockaddrL2TPIP6) + sa.ConnId = pp.Conn_id + sa.ZoneId = pp.Scope_id + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } + return sa, nil + default: + pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa)) + sa := new(SockaddrInet6) + p := (*[2]byte)(unsafe.Pointer(&pp.Port)) + sa.Port = int(p[0])<<8 + int(p[1]) + sa.ZoneId = pp.Scope_id + for i := 0; i < len(sa.Addr); i++ { + sa.Addr[i] = pp.Addr[i] + } + return sa, nil } - return sa, nil case AF_VSOCK: pp := (*RawSockaddrVM)(unsafe.Pointer(rsa)) @@ -1566,6 +1633,15 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e //sys CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) //sys DeleteModule(name string, flags int) (err error) //sys Dup(oldfd int) (fd int, err error) + +func Dup2(oldfd, newfd int) error { + // Android O and newer blocks dup2; riscv and arm64 don't implement dup2. + if runtime.GOOS == "android" || runtime.GOARCH == "riscv64" || runtime.GOARCH == "arm64" { + return Dup3(oldfd, newfd, 0) + } + return dup2(oldfd, newfd) +} + //sys Dup3(oldfd int, newfd int, flags int) (err error) //sysnb EpollCreate1(flag int) (fd int, err error) //sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) @@ -1690,6 +1766,9 @@ func Signalfd(fd int, sigmask *Sigset_t, flags int) (newfd int, err error) { //sys Syncfs(fd int) (err error) //sysnb Sysinfo(info *Sysinfo_t) (err error) //sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error) +//sysnb TimerfdCreate(clockid int, flags int) (fd int, err error) +//sysnb TimerfdGettime(fd int, currValue *ItimerSpec) (err error) +//sysnb TimerfdSettime(fd int, flags int, newValue *ItimerSpec, oldValue *ItimerSpec) (err error) //sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error) //sysnb Times(tms *Tms) (ticks uintptr, err error) //sysnb Umask(mask int) (oldmask int) @@ -2111,7 +2190,6 @@ func Klogset(typ int, arg int) (err error) { // TimerGetoverrun // TimerGettime // TimerSettime -// Timerfd // Tkill (obsolete) // Tuxcall // Umount2 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_386.go b/vendor/golang.org/x/sys/unix/syscall_linux_386.go index a8374b67cf8..048d18e3c81 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_386.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_386.go @@ -49,7 +49,7 @@ func Pipe2(p []int, flags int) (err error) { // 64-bit file system and 32-bit uid calls // (386 default is 32-bit file system and 16-bit uid). -//sys Dup2(oldfd int, newfd int) (err error) +//sys dup2(oldfd int, newfd int) (err error) //sysnb EpollCreate(size int) (fd int, err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64_64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go index 8ed1d546f0b..72efe86ed4f 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go @@ -6,7 +6,7 @@ package unix -//sys Dup2(oldfd int, newfd int) (err error) +//sys dup2(oldfd int, newfd int) (err error) //sysnb EpollCreate(size int) (fd int, err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go index 99ae6137332..e1913e2c934 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go @@ -80,7 +80,7 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { // 64-bit file system and 32-bit uid calls // (16-bit uid calls are not always supported in newer kernels) -//sys Dup2(oldfd int, newfd int) (err error) +//sys dup2(oldfd int, newfd int) (err error) //sysnb EpollCreate(size int) (fd int, err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go index 807a0b20c3f..c6de6b91345 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go @@ -25,7 +25,7 @@ func EpollCreate(size int) (fd int, err error) { //sysnb Getegid() (egid int) //sysnb Geteuid() (euid int) //sysnb Getgid() (gid int) -//sysnb Getrlimit(resource int, rlim *Rlimit) (err error) +//sysnb getrlimit(resource int, rlim *Rlimit) (err error) //sysnb Getuid() (uid int) //sys Listen(s int, n int) (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 @@ -47,7 +47,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) -//sysnb Setrlimit(resource int, rlim *Rlimit) (err error) +//sysnb setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) @@ -168,6 +168,24 @@ func Pipe2(p []int, flags int) (err error) { return } +// Getrlimit prefers the prlimit64 system call. See issue 38604. +func Getrlimit(resource int, rlim *Rlimit) error { + err := prlimit(0, resource, nil, rlim) + if err != ENOSYS { + return err + } + return getrlimit(resource, rlim) +} + +// Setrlimit prefers the prlimit64 system call. See issue 38604. +func Setrlimit(resource int, rlim *Rlimit) error { + err := prlimit(0, resource, rlim, nil) + if err != ENOSYS { + return err + } + return setrlimit(resource, rlim) +} + func (r *PtraceRegs) PC() uint64 { return r.Pc } func (r *PtraceRegs) SetPC(pc uint64) { r.Pc = pc } @@ -192,9 +210,9 @@ func InotifyInit() (fd int, err error) { return InotifyInit1(0) } -func Dup2(oldfd int, newfd int) (err error) { - return Dup3(oldfd, newfd, 0) -} +// dup2 exists because func Dup3 in syscall_linux.go references +// it in an unreachable path. dup2 isn't available on arm64. +func dup2(oldfd int, newfd int) error func Pause() error { _, err := ppoll(nil, 0, nil, nil) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go index af77e6e25eb..f0287476cd5 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go @@ -7,7 +7,7 @@ package unix -//sys Dup2(oldfd int, newfd int) (err error) +//sys dup2(oldfd int, newfd int) (err error) //sysnb EpollCreate(size int) (fd int, err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go index e286c6ba317..c11328111d1 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go @@ -14,7 +14,7 @@ import ( func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) -//sys Dup2(oldfd int, newfd int) (err error) +//sys dup2(oldfd int, newfd int) (err error) //sysnb EpollCreate(size int) (fd int, err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go index ca0345aabf2..349374409ba 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go @@ -7,7 +7,7 @@ package unix -//sys Dup2(oldfd int, newfd int) (err error) +//sys dup2(oldfd int, newfd int) (err error) //sysnb EpollCreate(size int) (fd int, err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go index abdabbac3f4..b0b1505565b 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_riscv64.go @@ -191,10 +191,6 @@ func InotifyInit() (fd int, err error) { return InotifyInit1(0) } -func Dup2(oldfd int, newfd int) (err error) { - return Dup3(oldfd, newfd, 0) -} - func Pause() error { _, err := ppoll(nil, 0, nil, nil) return err @@ -228,3 +224,7 @@ func KexecFileLoad(kernelFd int, initrdFd int, cmdline string, flags int) error } return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags) } + +// dup2 exists because func Dup3 in syscall_linux.go references +// it in an unreachable path. dup2 isn't available on arm64. +func dup2(oldfd int, newfd int) error diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go index 533e9305e7d..2363f749913 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go @@ -10,7 +10,7 @@ import ( "unsafe" ) -//sys Dup2(oldfd int, newfd int) (err error) +//sys dup2(oldfd int, newfd int) (err error) //sysnb EpollCreate(size int) (fd int, err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go index d890a227bf0..d389f1518fa 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go @@ -8,7 +8,7 @@ package unix //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 -//sys Dup2(oldfd int, newfd int) (err error) +//sys dup2(oldfd int, newfd int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 diff --git a/vendor/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go index 3de37566c6f..400ba9fbc90 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix.go @@ -12,6 +12,8 @@ import ( "sync" "syscall" "unsafe" + + "golang.org/x/sys/internal/unsafeheader" ) var ( @@ -76,7 +78,7 @@ func SignalName(s syscall.Signal) string { // The signal name should start with "SIG". func SignalNum(s string) syscall.Signal { signalNameMapOnce.Do(func() { - signalNameMap = make(map[string]syscall.Signal) + signalNameMap = make(map[string]syscall.Signal, len(signalList)) for _, signal := range signalList { signalNameMap[signal.name] = signal.num } @@ -113,15 +115,12 @@ func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (d return nil, errno } - // Slice memory layout - var sl = struct { - addr uintptr - len int - cap int - }{addr, length, length} - - // Use unsafe to turn sl into a []byte. - b := *(*[]byte)(unsafe.Pointer(&sl)) + // Use unsafe to convert addr into a []byte. + var b []byte + hdr := (*unsafeheader.Slice)(unsafe.Pointer(&b)) + hdr.Data = unsafe.Pointer(addr) + hdr.Cap = length + hdr.Len = length // Register mapping in m and return it. p := &b[cap(b)-1] diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go index b72544fcd2f..84824587346 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go @@ -355,6 +355,22 @@ const ( CTL_KERN = 0x1 CTL_MAXNAME = 0x18 CTL_NET = 0x4 + DIOCGATTR = 0xc144648e + DIOCGDELETE = 0x80106488 + DIOCGFLUSH = 0x20006487 + DIOCGFRONTSTUFF = 0x40086486 + DIOCGFWHEADS = 0x40046483 + DIOCGFWSECTORS = 0x40046482 + DIOCGIDENT = 0x41006489 + DIOCGMEDIASIZE = 0x40086481 + DIOCGPHYSPATH = 0x4400648d + DIOCGPROVIDERNAME = 0x4400648a + DIOCGSECTORSIZE = 0x40046480 + DIOCGSTRIPEOFFSET = 0x4008648c + DIOCGSTRIPESIZE = 0x4008648b + DIOCSKERNELDUMP = 0x804c6490 + DIOCSKERNELDUMP_FREEBSD11 = 0x80046485 + DIOCZONECMD = 0xc06c648f DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 @@ -379,11 +395,14 @@ const ( DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 + DLT_CLASS_NETBSD_RAWAF = 0x2240000 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd + DLT_DISPLAYPORT_AUX = 0x113 DLT_DOCSIS = 0x8f + DLT_DOCSIS31_XRA31 = 0x111 DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 @@ -393,6 +412,7 @@ const ( DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 + DLT_ETHERNET_MPACKET = 0x112 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa @@ -406,7 +426,6 @@ const ( DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 @@ -429,6 +448,7 @@ const ( DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a + DLT_ISO_14443 = 0x108 DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee @@ -461,8 +481,9 @@ const ( DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c + DLT_LORATAP = 0x10e DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0x104 + DLT_MATCHING_MAX = 0x113 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 @@ -478,14 +499,16 @@ const ( DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 + DLT_NORDIC_BLE = 0x110 DLT_NULL = 0x0 + DLT_OPENFLOW = 0x10b DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x79 DLT_PKTAP = 0x102 DLT_PPI = 0xc0 DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 + DLT_PPP_BSDOS = 0xe DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 @@ -496,19 +519,25 @@ const ( DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc + DLT_RDS = 0x109 + DLT_REDBACK_SMARTEDGE = 0x20 DLT_RIO = 0x7c DLT_RTAC_SERIAL = 0xfa DLT_SCCP = 0x8e DLT_SCTP = 0xf8 + DLT_SDLC = 0x10c DLT_SITA = 0xc4 DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf + DLT_SLIP_BSDOS = 0xd DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 + DLT_TI_LLN_SNIFFER = 0x10d DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USBPCAP = 0xf9 + DLT_USB_DARWIN = 0x10a + DLT_USB_FREEBSD = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 @@ -527,10 +556,14 @@ const ( DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c + DLT_VSOCK = 0x10f + DLT_WATTSTOPPER_DLM = 0x107 DLT_WIHART = 0xdf DLT_WIRESHARK_UPPER_PDU = 0xfc DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 + DLT_ZWAVE_R1_R2 = 0x105 + DLT_ZWAVE_R3 = 0x106 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -548,6 +581,7 @@ const ( ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 + EVFILT_EMPTY = -0xd EVFILT_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 @@ -555,11 +589,12 @@ const ( EVFILT_READ = -0x1 EVFILT_SENDFILE = -0xc EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xc + EVFILT_SYSCOUNT = 0xd EVFILT_TIMER = -0x7 EVFILT_USER = -0xb EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 + EVNAMEMAP_NAME_SIZE = 0x40 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 @@ -576,6 +611,7 @@ const ( EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 + EXTATTR_MAXNAMELEN = 0xff EXTATTR_NAMESPACE_EMPTY = 0x0 EXTATTR_NAMESPACE_SYSTEM = 0x2 EXTATTR_NAMESPACE_USER = 0x1 @@ -617,6 +653,7 @@ const ( IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 + IFCAP_WOL_MAGIC = 0x2000 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 @@ -633,6 +670,7 @@ const ( IFF_MONITOR = 0x40000 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 + IFF_NOGROUP = 0x800000 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PPROMISC = 0x20000 @@ -807,6 +845,7 @@ const ( IPV6_DSTOPTS = 0x32 IPV6_FLOWID = 0x43 IPV6_FLOWINFO_MASK = 0xffffff0f + IPV6_FLOWLABEL_LEN = 0x14 IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FLOWTYPE = 0x44 IPV6_FRAGTTL = 0x78 @@ -827,13 +866,13 @@ const ( IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MSFILTER = 0x4a IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 + IPV6_ORIGDSTADDR = 0x48 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe @@ -845,6 +884,7 @@ const ( IPV6_RECVFLOWID = 0x46 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 + IPV6_RECVORIGDSTADDR = 0x48 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRSSBUCKETID = 0x47 @@ -905,10 +945,8 @@ const ( IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MAX_SOURCE_FILTER = 0x400 IP_MF = 0x2000 IP_MINTTL = 0x42 - IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 @@ -918,6 +956,7 @@ const ( IP_OFFMASK = 0x1fff IP_ONESBCAST = 0x17 IP_OPTIONS = 0x1 + IP_ORIGDSTADDR = 0x1b IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 @@ -926,6 +965,7 @@ const ( IP_RECVFLOWID = 0x5d IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 + IP_RECVORIGDSTADDR = 0x1b IP_RECVRETOPTS = 0x6 IP_RECVRSSBUCKETID = 0x5e IP_RECVTOS = 0x44 @@ -975,6 +1015,7 @@ const ( MAP_EXCL = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 + MAP_GUARD = 0x2000 MAP_HASSEMAPHORE = 0x200 MAP_NOCORE = 0x20000 MAP_NOSYNC = 0x800 @@ -986,6 +1027,15 @@ const ( MAP_RESERVED0100 = 0x100 MAP_SHARED = 0x1 MAP_STACK = 0x400 + MCAST_BLOCK_SOURCE = 0x54 + MCAST_EXCLUDE = 0x2 + MCAST_INCLUDE = 0x1 + MCAST_JOIN_GROUP = 0x50 + MCAST_JOIN_SOURCE_GROUP = 0x52 + MCAST_LEAVE_GROUP = 0x51 + MCAST_LEAVE_SOURCE_GROUP = 0x53 + MCAST_UNBLOCK_SOURCE = 0x55 + MCAST_UNDEFINED = 0x0 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ACLS = 0x8000000 @@ -1026,10 +1076,12 @@ const ( MNT_SUSPEND = 0x4 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 + MNT_UNTRUSTED = 0x800000000 MNT_UPDATE = 0x10000 - MNT_UPDATEMASK = 0x2d8d0807e + MNT_UPDATEMASK = 0xad8d0807e MNT_USER = 0x8000 - MNT_VISFLAGMASK = 0x3fef0ffff + MNT_VERIFIED = 0x400000000 + MNT_VISFLAGMASK = 0xffef0ffff MNT_WAIT = 0x1 MSG_CMSG_CLOEXEC = 0x40000 MSG_COMPAT = 0x8000 @@ -1058,6 +1110,7 @@ const ( NFDBITS = 0x20 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 + NOTE_ABSTIME = 0x10 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_CLOSE = 0x100 @@ -1212,7 +1265,6 @@ const ( RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_BLACKHOLE = 0x40 - RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_HAS_GW = 0x80 RT_HAS_HEADER = 0x10 @@ -1222,15 +1274,17 @@ const ( RT_LLE_CACHE = 0x100 RT_MAY_LOOP = 0x8 RT_MAY_LOOP_BIT = 0x3 - RT_NORTREF = 0x2 RT_REJECT = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_BINTIME = 0x4 SCM_CREDS = 0x3 + SCM_MONOTONIC = 0x6 + SCM_REALTIME = 0x5 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 + SCM_TIME_INFO = 0x7 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1246,6 +1300,7 @@ const ( SIOCGETSGCNT = 0xc0147210 SIOCGETVIFCNT = 0xc014720f SIOCGHIWAT = 0x40047301 + SIOCGHWADDR = 0xc020693e SIOCGI2C = 0xc020693d SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 @@ -1267,8 +1322,11 @@ const ( SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc0206947 + SIOCGIFRSSHASH = 0xc0186997 + SIOCGIFRSSKEY = 0xc0946996 SIOCGIFSTATUS = 0xc331693b SIOCGIFXMEDIA = 0xc028698b + SIOCGLANPCP = 0xc0206998 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 @@ -1299,6 +1357,7 @@ const ( SIOCSIFPHYS = 0x80206936 SIOCSIFRVNET = 0xc020695b SIOCSIFVNET = 0xc020695a + SIOCSLANPCP = 0x80206999 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSTUNFIB = 0x8020695f @@ -1317,6 +1376,7 @@ const ( SO_BINTIME = 0x2000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 + SO_DOMAIN = 0x1019 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 @@ -1325,6 +1385,7 @@ const ( SO_LISTENINCQLEN = 0x1013 SO_LISTENQLEN = 0x1012 SO_LISTENQLIMIT = 0x1011 + SO_MAX_PACING_RATE = 0x1018 SO_NOSIGPIPE = 0x800 SO_NO_DDP = 0x8000 SO_NO_OFFLOAD = 0x4000 @@ -1337,11 +1398,19 @@ const ( SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 + SO_REUSEPORT_LB = 0x10000 SO_SETFIB = 0x1014 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 + SO_TS_BINTIME = 0x1 + SO_TS_CLOCK = 0x1017 + SO_TS_CLOCK_MAX = 0x3 + SO_TS_DEFAULT = 0x0 + SO_TS_MONOTONIC = 0x3 + SO_TS_REALTIME = 0x2 + SO_TS_REALTIME_MICRO = 0x0 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_USER_COOKIE = 0x1015 @@ -1385,10 +1454,45 @@ const ( TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 + TCP_BBR_ACK_COMP_ALG = 0x448 + TCP_BBR_DRAIN_INC_EXTRA = 0x43c + TCP_BBR_DRAIN_PG = 0x42e + TCP_BBR_EXTRA_GAIN = 0x449 + TCP_BBR_IWINTSO = 0x42b + TCP_BBR_LOWGAIN_FD = 0x436 + TCP_BBR_LOWGAIN_HALF = 0x435 + TCP_BBR_LOWGAIN_THRESH = 0x434 + TCP_BBR_MAX_RTO = 0x439 + TCP_BBR_MIN_RTO = 0x438 + TCP_BBR_ONE_RETRAN = 0x431 + TCP_BBR_PACE_CROSS = 0x442 + TCP_BBR_PACE_DEL_TAR = 0x43f + TCP_BBR_PACE_PER_SEC = 0x43e + TCP_BBR_PACE_SEG_MAX = 0x440 + TCP_BBR_PACE_SEG_MIN = 0x441 + TCP_BBR_PROBE_RTT_GAIN = 0x44d + TCP_BBR_PROBE_RTT_INT = 0x430 + TCP_BBR_PROBE_RTT_LEN = 0x44e + TCP_BBR_RACK_RTT_USE = 0x44a + TCP_BBR_RECFORCE = 0x42c + TCP_BBR_REC_OVER_HPTS = 0x43a + TCP_BBR_RETRAN_WTSO = 0x44b + TCP_BBR_RWND_IS_APP = 0x42f + TCP_BBR_STARTUP_EXIT_EPOCH = 0x43d + TCP_BBR_STARTUP_LOSS_EXIT = 0x432 + TCP_BBR_STARTUP_PG = 0x42d + TCP_BBR_UNLIMITED = 0x43b + TCP_BBR_USEDEL_RATE = 0x437 + TCP_BBR_USE_LOWGAIN = 0x433 TCP_CA_NAME_MAX = 0x10 TCP_CCALGOOPT = 0x41 TCP_CONGESTION = 0x40 + TCP_DATA_AFTER_CLOSE = 0x44c + TCP_DELACK = 0x48 TCP_FASTOPEN = 0x401 + TCP_FASTOPEN_MAX_COOKIE_LEN = 0x10 + TCP_FASTOPEN_MIN_COOKIE_LEN = 0x4 + TCP_FASTOPEN_PSK_LEN = 0x10 TCP_FUNCTION_BLK = 0x2000 TCP_FUNCTION_NAME_LEN_MAX = 0x20 TCP_INFO = 0x20 @@ -1396,6 +1500,12 @@ const ( TCP_KEEPIDLE = 0x100 TCP_KEEPINIT = 0x80 TCP_KEEPINTVL = 0x200 + TCP_LOG = 0x22 + TCP_LOGBUF = 0x23 + TCP_LOGDUMP = 0x25 + TCP_LOGDUMPID = 0x26 + TCP_LOGID = 0x24 + TCP_LOG_ID_LEN = 0x40 TCP_MAXBURST = 0x4 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 @@ -1411,8 +1521,30 @@ const ( TCP_NOPUSH = 0x4 TCP_PCAP_IN = 0x1000 TCP_PCAP_OUT = 0x800 + TCP_RACK_EARLY_RECOV = 0x423 + TCP_RACK_EARLY_SEG = 0x424 + TCP_RACK_IDLE_REDUCE_HIGH = 0x444 + TCP_RACK_MIN_PACE = 0x445 + TCP_RACK_MIN_PACE_SEG = 0x446 + TCP_RACK_MIN_TO = 0x422 + TCP_RACK_PACE_ALWAYS = 0x41f + TCP_RACK_PACE_MAX_SEG = 0x41e + TCP_RACK_PACE_REDUCE = 0x41d + TCP_RACK_PKT_DELAY = 0x428 + TCP_RACK_PROP = 0x41b + TCP_RACK_PROP_RATE = 0x420 + TCP_RACK_PRR_SENDALOT = 0x421 + TCP_RACK_REORD_FADE = 0x426 + TCP_RACK_REORD_THRESH = 0x425 + TCP_RACK_SESS_CWV = 0x42a + TCP_RACK_TLP_INC_VAR = 0x429 + TCP_RACK_TLP_REDUCE = 0x41c + TCP_RACK_TLP_THRESH = 0x427 + TCP_RACK_TLP_USE = 0x447 TCP_VENDOR = 0x80000000 TCSAFLUSH = 0x2 + TIMER_ABSTIME = 0x1 + TIMER_RELTIME = 0x0 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 @@ -1476,6 +1608,8 @@ const ( TIOCTIMESTAMP = 0x40087459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 + UTIME_NOW = -0x1 + UTIME_OMIT = -0x2 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 @@ -1487,6 +1621,8 @@ const ( VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 + VM_BCACHE_SIZE_MAX = 0x70e0000 + VM_SWZONE_SIZE_MAX = 0x2280000 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go index 9f382678e5a..4acd101c3ee 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go @@ -355,6 +355,22 @@ const ( CTL_KERN = 0x1 CTL_MAXNAME = 0x18 CTL_NET = 0x4 + DIOCGATTR = 0xc148648e + DIOCGDELETE = 0x80106488 + DIOCGFLUSH = 0x20006487 + DIOCGFRONTSTUFF = 0x40086486 + DIOCGFWHEADS = 0x40046483 + DIOCGFWSECTORS = 0x40046482 + DIOCGIDENT = 0x41006489 + DIOCGMEDIASIZE = 0x40086481 + DIOCGPHYSPATH = 0x4400648d + DIOCGPROVIDERNAME = 0x4400648a + DIOCGSECTORSIZE = 0x40046480 + DIOCGSTRIPEOFFSET = 0x4008648c + DIOCGSTRIPESIZE = 0x4008648b + DIOCSKERNELDUMP = 0x80506490 + DIOCSKERNELDUMP_FREEBSD11 = 0x80046485 + DIOCZONECMD = 0xc080648f DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 @@ -379,11 +395,14 @@ const ( DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 + DLT_CLASS_NETBSD_RAWAF = 0x2240000 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd + DLT_DISPLAYPORT_AUX = 0x113 DLT_DOCSIS = 0x8f + DLT_DOCSIS31_XRA31 = 0x111 DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 @@ -393,6 +412,7 @@ const ( DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 + DLT_ETHERNET_MPACKET = 0x112 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa @@ -406,7 +426,6 @@ const ( DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 @@ -429,6 +448,7 @@ const ( DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a + DLT_ISO_14443 = 0x108 DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee @@ -461,8 +481,9 @@ const ( DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c + DLT_LORATAP = 0x10e DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0x104 + DLT_MATCHING_MAX = 0x113 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 @@ -478,14 +499,16 @@ const ( DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 + DLT_NORDIC_BLE = 0x110 DLT_NULL = 0x0 + DLT_OPENFLOW = 0x10b DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x79 DLT_PKTAP = 0x102 DLT_PPI = 0xc0 DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 + DLT_PPP_BSDOS = 0xe DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 @@ -496,19 +519,25 @@ const ( DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc + DLT_RDS = 0x109 + DLT_REDBACK_SMARTEDGE = 0x20 DLT_RIO = 0x7c DLT_RTAC_SERIAL = 0xfa DLT_SCCP = 0x8e DLT_SCTP = 0xf8 + DLT_SDLC = 0x10c DLT_SITA = 0xc4 DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf + DLT_SLIP_BSDOS = 0xd DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 + DLT_TI_LLN_SNIFFER = 0x10d DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USBPCAP = 0xf9 + DLT_USB_DARWIN = 0x10a + DLT_USB_FREEBSD = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 @@ -527,10 +556,14 @@ const ( DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c + DLT_VSOCK = 0x10f + DLT_WATTSTOPPER_DLM = 0x107 DLT_WIHART = 0xdf DLT_WIRESHARK_UPPER_PDU = 0xfc DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 + DLT_ZWAVE_R1_R2 = 0x105 + DLT_ZWAVE_R3 = 0x106 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -548,6 +581,7 @@ const ( ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 + EVFILT_EMPTY = -0xd EVFILT_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 @@ -555,11 +589,12 @@ const ( EVFILT_READ = -0x1 EVFILT_SENDFILE = -0xc EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xc + EVFILT_SYSCOUNT = 0xd EVFILT_TIMER = -0x7 EVFILT_USER = -0xb EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 + EVNAMEMAP_NAME_SIZE = 0x40 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 @@ -576,6 +611,7 @@ const ( EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 + EXTATTR_MAXNAMELEN = 0xff EXTATTR_NAMESPACE_EMPTY = 0x0 EXTATTR_NAMESPACE_SYSTEM = 0x2 EXTATTR_NAMESPACE_USER = 0x1 @@ -617,6 +653,7 @@ const ( IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 + IFCAP_WOL_MAGIC = 0x2000 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 @@ -633,6 +670,7 @@ const ( IFF_MONITOR = 0x40000 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 + IFF_NOGROUP = 0x800000 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PPROMISC = 0x20000 @@ -807,6 +845,7 @@ const ( IPV6_DSTOPTS = 0x32 IPV6_FLOWID = 0x43 IPV6_FLOWINFO_MASK = 0xffffff0f + IPV6_FLOWLABEL_LEN = 0x14 IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FLOWTYPE = 0x44 IPV6_FRAGTTL = 0x78 @@ -827,13 +866,13 @@ const ( IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MSFILTER = 0x4a IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 + IPV6_ORIGDSTADDR = 0x48 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe @@ -845,6 +884,7 @@ const ( IPV6_RECVFLOWID = 0x46 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 + IPV6_RECVORIGDSTADDR = 0x48 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRSSBUCKETID = 0x47 @@ -905,10 +945,8 @@ const ( IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MAX_SOURCE_FILTER = 0x400 IP_MF = 0x2000 IP_MINTTL = 0x42 - IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 @@ -918,6 +956,7 @@ const ( IP_OFFMASK = 0x1fff IP_ONESBCAST = 0x17 IP_OPTIONS = 0x1 + IP_ORIGDSTADDR = 0x1b IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 @@ -926,6 +965,7 @@ const ( IP_RECVFLOWID = 0x5d IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 + IP_RECVORIGDSTADDR = 0x1b IP_RECVRETOPTS = 0x6 IP_RECVRSSBUCKETID = 0x5e IP_RECVTOS = 0x44 @@ -976,6 +1016,7 @@ const ( MAP_EXCL = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 + MAP_GUARD = 0x2000 MAP_HASSEMAPHORE = 0x200 MAP_NOCORE = 0x20000 MAP_NOSYNC = 0x800 @@ -987,6 +1028,15 @@ const ( MAP_RESERVED0100 = 0x100 MAP_SHARED = 0x1 MAP_STACK = 0x400 + MCAST_BLOCK_SOURCE = 0x54 + MCAST_EXCLUDE = 0x2 + MCAST_INCLUDE = 0x1 + MCAST_JOIN_GROUP = 0x50 + MCAST_JOIN_SOURCE_GROUP = 0x52 + MCAST_LEAVE_GROUP = 0x51 + MCAST_LEAVE_SOURCE_GROUP = 0x53 + MCAST_UNBLOCK_SOURCE = 0x55 + MCAST_UNDEFINED = 0x0 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ACLS = 0x8000000 @@ -1027,10 +1077,12 @@ const ( MNT_SUSPEND = 0x4 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 + MNT_UNTRUSTED = 0x800000000 MNT_UPDATE = 0x10000 - MNT_UPDATEMASK = 0x2d8d0807e + MNT_UPDATEMASK = 0xad8d0807e MNT_USER = 0x8000 - MNT_VISFLAGMASK = 0x3fef0ffff + MNT_VERIFIED = 0x400000000 + MNT_VISFLAGMASK = 0xffef0ffff MNT_WAIT = 0x1 MSG_CMSG_CLOEXEC = 0x40000 MSG_COMPAT = 0x8000 @@ -1059,6 +1111,7 @@ const ( NFDBITS = 0x40 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 + NOTE_ABSTIME = 0x10 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_CLOSE = 0x100 @@ -1213,7 +1266,6 @@ const ( RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_BLACKHOLE = 0x40 - RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_HAS_GW = 0x80 RT_HAS_HEADER = 0x10 @@ -1223,15 +1275,17 @@ const ( RT_LLE_CACHE = 0x100 RT_MAY_LOOP = 0x8 RT_MAY_LOOP_BIT = 0x3 - RT_NORTREF = 0x2 RT_REJECT = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_BINTIME = 0x4 SCM_CREDS = 0x3 + SCM_MONOTONIC = 0x6 + SCM_REALTIME = 0x5 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 + SCM_TIME_INFO = 0x7 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1247,6 +1301,7 @@ const ( SIOCGETSGCNT = 0xc0207210 SIOCGETVIFCNT = 0xc028720f SIOCGHIWAT = 0x40047301 + SIOCGHWADDR = 0xc020693e SIOCGI2C = 0xc020693d SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 @@ -1268,8 +1323,11 @@ const ( SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc0206947 + SIOCGIFRSSHASH = 0xc0186997 + SIOCGIFRSSKEY = 0xc0946996 SIOCGIFSTATUS = 0xc331693b SIOCGIFXMEDIA = 0xc030698b + SIOCGLANPCP = 0xc0206998 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 @@ -1300,6 +1358,7 @@ const ( SIOCSIFPHYS = 0x80206936 SIOCSIFRVNET = 0xc020695b SIOCSIFVNET = 0xc020695a + SIOCSLANPCP = 0x80206999 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSTUNFIB = 0x8020695f @@ -1318,6 +1377,7 @@ const ( SO_BINTIME = 0x2000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 + SO_DOMAIN = 0x1019 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 @@ -1326,6 +1386,7 @@ const ( SO_LISTENINCQLEN = 0x1013 SO_LISTENQLEN = 0x1012 SO_LISTENQLIMIT = 0x1011 + SO_MAX_PACING_RATE = 0x1018 SO_NOSIGPIPE = 0x800 SO_NO_DDP = 0x8000 SO_NO_OFFLOAD = 0x4000 @@ -1338,11 +1399,19 @@ const ( SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 + SO_REUSEPORT_LB = 0x10000 SO_SETFIB = 0x1014 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 + SO_TS_BINTIME = 0x1 + SO_TS_CLOCK = 0x1017 + SO_TS_CLOCK_MAX = 0x3 + SO_TS_DEFAULT = 0x0 + SO_TS_MONOTONIC = 0x3 + SO_TS_REALTIME = 0x2 + SO_TS_REALTIME_MICRO = 0x0 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_USER_COOKIE = 0x1015 @@ -1386,10 +1455,45 @@ const ( TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 + TCP_BBR_ACK_COMP_ALG = 0x448 + TCP_BBR_DRAIN_INC_EXTRA = 0x43c + TCP_BBR_DRAIN_PG = 0x42e + TCP_BBR_EXTRA_GAIN = 0x449 + TCP_BBR_IWINTSO = 0x42b + TCP_BBR_LOWGAIN_FD = 0x436 + TCP_BBR_LOWGAIN_HALF = 0x435 + TCP_BBR_LOWGAIN_THRESH = 0x434 + TCP_BBR_MAX_RTO = 0x439 + TCP_BBR_MIN_RTO = 0x438 + TCP_BBR_ONE_RETRAN = 0x431 + TCP_BBR_PACE_CROSS = 0x442 + TCP_BBR_PACE_DEL_TAR = 0x43f + TCP_BBR_PACE_PER_SEC = 0x43e + TCP_BBR_PACE_SEG_MAX = 0x440 + TCP_BBR_PACE_SEG_MIN = 0x441 + TCP_BBR_PROBE_RTT_GAIN = 0x44d + TCP_BBR_PROBE_RTT_INT = 0x430 + TCP_BBR_PROBE_RTT_LEN = 0x44e + TCP_BBR_RACK_RTT_USE = 0x44a + TCP_BBR_RECFORCE = 0x42c + TCP_BBR_REC_OVER_HPTS = 0x43a + TCP_BBR_RETRAN_WTSO = 0x44b + TCP_BBR_RWND_IS_APP = 0x42f + TCP_BBR_STARTUP_EXIT_EPOCH = 0x43d + TCP_BBR_STARTUP_LOSS_EXIT = 0x432 + TCP_BBR_STARTUP_PG = 0x42d + TCP_BBR_UNLIMITED = 0x43b + TCP_BBR_USEDEL_RATE = 0x437 + TCP_BBR_USE_LOWGAIN = 0x433 TCP_CA_NAME_MAX = 0x10 TCP_CCALGOOPT = 0x41 TCP_CONGESTION = 0x40 + TCP_DATA_AFTER_CLOSE = 0x44c + TCP_DELACK = 0x48 TCP_FASTOPEN = 0x401 + TCP_FASTOPEN_MAX_COOKIE_LEN = 0x10 + TCP_FASTOPEN_MIN_COOKIE_LEN = 0x4 + TCP_FASTOPEN_PSK_LEN = 0x10 TCP_FUNCTION_BLK = 0x2000 TCP_FUNCTION_NAME_LEN_MAX = 0x20 TCP_INFO = 0x20 @@ -1397,6 +1501,12 @@ const ( TCP_KEEPIDLE = 0x100 TCP_KEEPINIT = 0x80 TCP_KEEPINTVL = 0x200 + TCP_LOG = 0x22 + TCP_LOGBUF = 0x23 + TCP_LOGDUMP = 0x25 + TCP_LOGDUMPID = 0x26 + TCP_LOGID = 0x24 + TCP_LOG_ID_LEN = 0x40 TCP_MAXBURST = 0x4 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 @@ -1412,8 +1522,30 @@ const ( TCP_NOPUSH = 0x4 TCP_PCAP_IN = 0x1000 TCP_PCAP_OUT = 0x800 + TCP_RACK_EARLY_RECOV = 0x423 + TCP_RACK_EARLY_SEG = 0x424 + TCP_RACK_IDLE_REDUCE_HIGH = 0x444 + TCP_RACK_MIN_PACE = 0x445 + TCP_RACK_MIN_PACE_SEG = 0x446 + TCP_RACK_MIN_TO = 0x422 + TCP_RACK_PACE_ALWAYS = 0x41f + TCP_RACK_PACE_MAX_SEG = 0x41e + TCP_RACK_PACE_REDUCE = 0x41d + TCP_RACK_PKT_DELAY = 0x428 + TCP_RACK_PROP = 0x41b + TCP_RACK_PROP_RATE = 0x420 + TCP_RACK_PRR_SENDALOT = 0x421 + TCP_RACK_REORD_FADE = 0x426 + TCP_RACK_REORD_THRESH = 0x425 + TCP_RACK_SESS_CWV = 0x42a + TCP_RACK_TLP_INC_VAR = 0x429 + TCP_RACK_TLP_REDUCE = 0x41c + TCP_RACK_TLP_THRESH = 0x427 + TCP_RACK_TLP_USE = 0x447 TCP_VENDOR = 0x80000000 TCSAFLUSH = 0x2 + TIMER_ABSTIME = 0x1 + TIMER_RELTIME = 0x0 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 @@ -1477,6 +1609,8 @@ const ( TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 + UTIME_NOW = -0x1 + UTIME_OMIT = -0x2 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go index 16db56abc46..e4719873b9e 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go @@ -355,6 +355,22 @@ const ( CTL_KERN = 0x1 CTL_MAXNAME = 0x18 CTL_NET = 0x4 + DIOCGATTR = 0xc144648e + DIOCGDELETE = 0x80106488 + DIOCGFLUSH = 0x20006487 + DIOCGFRONTSTUFF = 0x40086486 + DIOCGFWHEADS = 0x40046483 + DIOCGFWSECTORS = 0x40046482 + DIOCGIDENT = 0x41006489 + DIOCGMEDIASIZE = 0x40086481 + DIOCGPHYSPATH = 0x4400648d + DIOCGPROVIDERNAME = 0x4400648a + DIOCGSECTORSIZE = 0x40046480 + DIOCGSTRIPEOFFSET = 0x4008648c + DIOCGSTRIPESIZE = 0x4008648b + DIOCSKERNELDUMP = 0x804c6490 + DIOCSKERNELDUMP_FREEBSD11 = 0x80046485 + DIOCZONECMD = 0xc06c648f DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go index 1a1de345431..5e49769d96a 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm64.go @@ -355,6 +355,22 @@ const ( CTL_KERN = 0x1 CTL_MAXNAME = 0x18 CTL_NET = 0x4 + DIOCGATTR = 0xc148648e + DIOCGDELETE = 0x80106488 + DIOCGFLUSH = 0x20006487 + DIOCGFRONTSTUFF = 0x40086486 + DIOCGFWHEADS = 0x40046483 + DIOCGFWSECTORS = 0x40046482 + DIOCGIDENT = 0x41006489 + DIOCGMEDIASIZE = 0x40086481 + DIOCGPHYSPATH = 0x4400648d + DIOCGPROVIDERNAME = 0x4400648a + DIOCGSECTORSIZE = 0x40046480 + DIOCGSTRIPEOFFSET = 0x4008648c + DIOCGSTRIPESIZE = 0x4008648b + DIOCSKERNELDUMP = 0x80506490 + DIOCSKERNELDUMP_FREEBSD11 = 0x80046485 + DIOCZONECMD = 0xc080648f DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 @@ -379,11 +395,14 @@ const ( DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 + DLT_CLASS_NETBSD_RAWAF = 0x2240000 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DBUS = 0xe7 DLT_DECT = 0xdd + DLT_DISPLAYPORT_AUX = 0x113 DLT_DOCSIS = 0x8f + DLT_DOCSIS31_XRA31 = 0x111 DLT_DVB_CI = 0xeb DLT_ECONET = 0x73 DLT_EN10MB = 0x1 @@ -393,6 +412,7 @@ const ( DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 + DLT_ETHERNET_MPACKET = 0x112 DLT_FC_2 = 0xe0 DLT_FC_2_WITH_FRAME_DELIMS = 0xe1 DLT_FDDI = 0xa @@ -406,7 +426,6 @@ const ( DLT_GPRS_LLC = 0xa9 DLT_GSMTAP_ABIS = 0xda DLT_GSMTAP_UM = 0xd9 - DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 @@ -429,6 +448,7 @@ const ( DLT_IPV4 = 0xe4 DLT_IPV6 = 0xe5 DLT_IP_OVER_FC = 0x7a + DLT_ISO_14443 = 0x108 DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_ATM_CEMIC = 0xee @@ -461,8 +481,9 @@ const ( DLT_LINUX_PPP_WITHDIRECTION = 0xa6 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c + DLT_LORATAP = 0x10e DLT_LTALK = 0x72 - DLT_MATCHING_MAX = 0x104 + DLT_MATCHING_MAX = 0x113 DLT_MATCHING_MIN = 0x68 DLT_MFR = 0xb6 DLT_MOST = 0xd3 @@ -478,14 +499,16 @@ const ( DLT_NFC_LLCP = 0xf5 DLT_NFLOG = 0xef DLT_NG40 = 0xf4 + DLT_NORDIC_BLE = 0x110 DLT_NULL = 0x0 + DLT_OPENFLOW = 0x10b DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x79 DLT_PKTAP = 0x102 DLT_PPI = 0xc0 DLT_PPP = 0x9 - DLT_PPP_BSDOS = 0x10 + DLT_PPP_BSDOS = 0xe DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 @@ -496,19 +519,25 @@ const ( DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc + DLT_RDS = 0x109 + DLT_REDBACK_SMARTEDGE = 0x20 DLT_RIO = 0x7c DLT_RTAC_SERIAL = 0xfa DLT_SCCP = 0x8e DLT_SCTP = 0xf8 + DLT_SDLC = 0x10c DLT_SITA = 0xc4 DLT_SLIP = 0x8 - DLT_SLIP_BSDOS = 0xf + DLT_SLIP_BSDOS = 0xd DLT_STANAG_5066_D_PDU = 0xed DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 + DLT_TI_LLN_SNIFFER = 0x10d DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USBPCAP = 0xf9 + DLT_USB_DARWIN = 0x10a + DLT_USB_FREEBSD = 0xba DLT_USB_LINUX = 0xbd DLT_USB_LINUX_MMAPPED = 0xdc DLT_USER0 = 0x93 @@ -527,10 +556,14 @@ const ( DLT_USER7 = 0x9a DLT_USER8 = 0x9b DLT_USER9 = 0x9c + DLT_VSOCK = 0x10f + DLT_WATTSTOPPER_DLM = 0x107 DLT_WIHART = 0xdf DLT_WIRESHARK_UPPER_PDU = 0xfc DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 + DLT_ZWAVE_R1_R2 = 0x105 + DLT_ZWAVE_R3 = 0x106 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -548,6 +581,7 @@ const ( ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 + EVFILT_EMPTY = -0xd EVFILT_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 @@ -555,11 +589,12 @@ const ( EVFILT_READ = -0x1 EVFILT_SENDFILE = -0xc EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0xc + EVFILT_SYSCOUNT = 0xd EVFILT_TIMER = -0x7 EVFILT_USER = -0xb EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 + EVNAMEMAP_NAME_SIZE = 0x40 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 @@ -576,6 +611,7 @@ const ( EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 + EXTATTR_MAXNAMELEN = 0xff EXTATTR_NAMESPACE_EMPTY = 0x0 EXTATTR_NAMESPACE_SYSTEM = 0x2 EXTATTR_NAMESPACE_USER = 0x1 @@ -617,6 +653,7 @@ const ( IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 + IFCAP_WOL_MAGIC = 0x2000 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 @@ -633,6 +670,7 @@ const ( IFF_MONITOR = 0x40000 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 + IFF_NOGROUP = 0x800000 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PPROMISC = 0x20000 @@ -807,6 +845,7 @@ const ( IPV6_DSTOPTS = 0x32 IPV6_FLOWID = 0x43 IPV6_FLOWINFO_MASK = 0xffffff0f + IPV6_FLOWLABEL_LEN = 0x14 IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FLOWTYPE = 0x44 IPV6_FRAGTTL = 0x78 @@ -827,13 +866,13 @@ const ( IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 - IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MSFILTER = 0x4a IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 + IPV6_ORIGDSTADDR = 0x48 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe @@ -845,6 +884,7 @@ const ( IPV6_RECVFLOWID = 0x46 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 + IPV6_RECVORIGDSTADDR = 0x48 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRSSBUCKETID = 0x47 @@ -905,10 +945,8 @@ const ( IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 - IP_MAX_SOURCE_FILTER = 0x400 IP_MF = 0x2000 IP_MINTTL = 0x42 - IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 @@ -918,6 +956,7 @@ const ( IP_OFFMASK = 0x1fff IP_ONESBCAST = 0x17 IP_OPTIONS = 0x1 + IP_ORIGDSTADDR = 0x1b IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 @@ -926,6 +965,7 @@ const ( IP_RECVFLOWID = 0x5d IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 + IP_RECVORIGDSTADDR = 0x1b IP_RECVRETOPTS = 0x6 IP_RECVRSSBUCKETID = 0x5e IP_RECVTOS = 0x44 @@ -976,6 +1016,7 @@ const ( MAP_EXCL = 0x4000 MAP_FILE = 0x0 MAP_FIXED = 0x10 + MAP_GUARD = 0x2000 MAP_HASSEMAPHORE = 0x200 MAP_NOCORE = 0x20000 MAP_NOSYNC = 0x800 @@ -987,6 +1028,15 @@ const ( MAP_RESERVED0100 = 0x100 MAP_SHARED = 0x1 MAP_STACK = 0x400 + MCAST_BLOCK_SOURCE = 0x54 + MCAST_EXCLUDE = 0x2 + MCAST_INCLUDE = 0x1 + MCAST_JOIN_GROUP = 0x50 + MCAST_JOIN_SOURCE_GROUP = 0x52 + MCAST_LEAVE_GROUP = 0x51 + MCAST_LEAVE_SOURCE_GROUP = 0x53 + MCAST_UNBLOCK_SOURCE = 0x55 + MCAST_UNDEFINED = 0x0 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ACLS = 0x8000000 @@ -1027,10 +1077,12 @@ const ( MNT_SUSPEND = 0x4 MNT_SYNCHRONOUS = 0x2 MNT_UNION = 0x20 + MNT_UNTRUSTED = 0x800000000 MNT_UPDATE = 0x10000 - MNT_UPDATEMASK = 0x2d8d0807e + MNT_UPDATEMASK = 0xad8d0807e MNT_USER = 0x8000 - MNT_VISFLAGMASK = 0x3fef0ffff + MNT_VERIFIED = 0x400000000 + MNT_VISFLAGMASK = 0xffef0ffff MNT_WAIT = 0x1 MSG_CMSG_CLOEXEC = 0x40000 MSG_COMPAT = 0x8000 @@ -1059,6 +1111,7 @@ const ( NFDBITS = 0x40 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 + NOTE_ABSTIME = 0x10 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_CLOSE = 0x100 @@ -1213,7 +1266,6 @@ const ( RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_BLACKHOLE = 0x40 - RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_HAS_GW = 0x80 RT_HAS_HEADER = 0x10 @@ -1223,15 +1275,17 @@ const ( RT_LLE_CACHE = 0x100 RT_MAY_LOOP = 0x8 RT_MAY_LOOP_BIT = 0x3 - RT_NORTREF = 0x2 RT_REJECT = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_BINTIME = 0x4 SCM_CREDS = 0x3 + SCM_MONOTONIC = 0x6 + SCM_REALTIME = 0x5 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 + SCM_TIME_INFO = 0x7 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1247,6 +1301,7 @@ const ( SIOCGETSGCNT = 0xc0207210 SIOCGETVIFCNT = 0xc028720f SIOCGHIWAT = 0x40047301 + SIOCGHWADDR = 0xc020693e SIOCGI2C = 0xc020693d SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 @@ -1268,8 +1323,11 @@ const ( SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc0206947 + SIOCGIFRSSHASH = 0xc0186997 + SIOCGIFRSSKEY = 0xc0946996 SIOCGIFSTATUS = 0xc331693b SIOCGIFXMEDIA = 0xc030698b + SIOCGLANPCP = 0xc0206998 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 @@ -1300,6 +1358,7 @@ const ( SIOCSIFPHYS = 0x80206936 SIOCSIFRVNET = 0xc020695b SIOCSIFVNET = 0xc020695a + SIOCSLANPCP = 0x80206999 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSTUNFIB = 0x8020695f @@ -1318,6 +1377,7 @@ const ( SO_BINTIME = 0x2000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 + SO_DOMAIN = 0x1019 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 @@ -1326,6 +1386,7 @@ const ( SO_LISTENINCQLEN = 0x1013 SO_LISTENQLEN = 0x1012 SO_LISTENQLIMIT = 0x1011 + SO_MAX_PACING_RATE = 0x1018 SO_NOSIGPIPE = 0x800 SO_NO_DDP = 0x8000 SO_NO_OFFLOAD = 0x4000 @@ -1338,11 +1399,19 @@ const ( SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 + SO_REUSEPORT_LB = 0x10000 SO_SETFIB = 0x1014 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 + SO_TS_BINTIME = 0x1 + SO_TS_CLOCK = 0x1017 + SO_TS_CLOCK_MAX = 0x3 + SO_TS_DEFAULT = 0x0 + SO_TS_MONOTONIC = 0x3 + SO_TS_REALTIME = 0x2 + SO_TS_REALTIME_MICRO = 0x0 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 SO_USER_COOKIE = 0x1015 @@ -1386,10 +1455,45 @@ const ( TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 + TCP_BBR_ACK_COMP_ALG = 0x448 + TCP_BBR_DRAIN_INC_EXTRA = 0x43c + TCP_BBR_DRAIN_PG = 0x42e + TCP_BBR_EXTRA_GAIN = 0x449 + TCP_BBR_IWINTSO = 0x42b + TCP_BBR_LOWGAIN_FD = 0x436 + TCP_BBR_LOWGAIN_HALF = 0x435 + TCP_BBR_LOWGAIN_THRESH = 0x434 + TCP_BBR_MAX_RTO = 0x439 + TCP_BBR_MIN_RTO = 0x438 + TCP_BBR_ONE_RETRAN = 0x431 + TCP_BBR_PACE_CROSS = 0x442 + TCP_BBR_PACE_DEL_TAR = 0x43f + TCP_BBR_PACE_PER_SEC = 0x43e + TCP_BBR_PACE_SEG_MAX = 0x440 + TCP_BBR_PACE_SEG_MIN = 0x441 + TCP_BBR_PROBE_RTT_GAIN = 0x44d + TCP_BBR_PROBE_RTT_INT = 0x430 + TCP_BBR_PROBE_RTT_LEN = 0x44e + TCP_BBR_RACK_RTT_USE = 0x44a + TCP_BBR_RECFORCE = 0x42c + TCP_BBR_REC_OVER_HPTS = 0x43a + TCP_BBR_RETRAN_WTSO = 0x44b + TCP_BBR_RWND_IS_APP = 0x42f + TCP_BBR_STARTUP_EXIT_EPOCH = 0x43d + TCP_BBR_STARTUP_LOSS_EXIT = 0x432 + TCP_BBR_STARTUP_PG = 0x42d + TCP_BBR_UNLIMITED = 0x43b + TCP_BBR_USEDEL_RATE = 0x437 + TCP_BBR_USE_LOWGAIN = 0x433 TCP_CA_NAME_MAX = 0x10 TCP_CCALGOOPT = 0x41 TCP_CONGESTION = 0x40 + TCP_DATA_AFTER_CLOSE = 0x44c + TCP_DELACK = 0x48 TCP_FASTOPEN = 0x401 + TCP_FASTOPEN_MAX_COOKIE_LEN = 0x10 + TCP_FASTOPEN_MIN_COOKIE_LEN = 0x4 + TCP_FASTOPEN_PSK_LEN = 0x10 TCP_FUNCTION_BLK = 0x2000 TCP_FUNCTION_NAME_LEN_MAX = 0x20 TCP_INFO = 0x20 @@ -1397,6 +1501,12 @@ const ( TCP_KEEPIDLE = 0x100 TCP_KEEPINIT = 0x80 TCP_KEEPINTVL = 0x200 + TCP_LOG = 0x22 + TCP_LOGBUF = 0x23 + TCP_LOGDUMP = 0x25 + TCP_LOGDUMPID = 0x26 + TCP_LOGID = 0x24 + TCP_LOG_ID_LEN = 0x40 TCP_MAXBURST = 0x4 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 @@ -1412,8 +1522,30 @@ const ( TCP_NOPUSH = 0x4 TCP_PCAP_IN = 0x1000 TCP_PCAP_OUT = 0x800 + TCP_RACK_EARLY_RECOV = 0x423 + TCP_RACK_EARLY_SEG = 0x424 + TCP_RACK_IDLE_REDUCE_HIGH = 0x444 + TCP_RACK_MIN_PACE = 0x445 + TCP_RACK_MIN_PACE_SEG = 0x446 + TCP_RACK_MIN_TO = 0x422 + TCP_RACK_PACE_ALWAYS = 0x41f + TCP_RACK_PACE_MAX_SEG = 0x41e + TCP_RACK_PACE_REDUCE = 0x41d + TCP_RACK_PKT_DELAY = 0x428 + TCP_RACK_PROP = 0x41b + TCP_RACK_PROP_RATE = 0x420 + TCP_RACK_PRR_SENDALOT = 0x421 + TCP_RACK_REORD_FADE = 0x426 + TCP_RACK_REORD_THRESH = 0x425 + TCP_RACK_SESS_CWV = 0x42a + TCP_RACK_TLP_INC_VAR = 0x429 + TCP_RACK_TLP_REDUCE = 0x41c + TCP_RACK_TLP_THRESH = 0x427 + TCP_RACK_TLP_USE = 0x447 TCP_VENDOR = 0x80000000 TCSAFLUSH = 0x2 + TIMER_ABSTIME = 0x1 + TIMER_RELTIME = 0x0 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 @@ -1477,6 +1609,8 @@ const ( TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 + UTIME_NOW = -0x1 + UTIME_OMIT = -0x2 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 @@ -1488,6 +1622,7 @@ const ( VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 + VM_BCACHE_SIZE_MAX = 0x19000000 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index 5be454c0d1c..6e3cfec46c9 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -216,6 +216,7 @@ const ( BPF_F_RDONLY = 0x8 BPF_F_RDONLY_PROG = 0x80 BPF_F_RECOMPUTE_CSUM = 0x1 + BPF_F_REPLACE = 0x4 BPF_F_REUSE_STACKID = 0x400 BPF_F_SEQ_NUMBER = 0x8 BPF_F_SKIP_FIELD_MASK = 0xff @@ -389,6 +390,7 @@ const ( CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 + CLONE_NEWTIME = 0x80 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 @@ -671,6 +673,7 @@ const ( FS_IOC_ADD_ENCRYPTION_KEY = 0xc0506617 FS_IOC_GET_ENCRYPTION_KEY_STATUS = 0xc080661a FS_IOC_GET_ENCRYPTION_POLICY_EX = 0xc0096616 + FS_IOC_MEASURE_VERITY = 0xc0046686 FS_IOC_REMOVE_ENCRYPTION_KEY = 0xc0406618 FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS = 0xc0406619 FS_KEY_DESCRIPTOR_SIZE = 0x8 @@ -683,6 +686,9 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0xf + FS_VERITY_FL = 0x100000 + FS_VERITY_HASH_ALG_SHA256 = 0x1 + FS_VERITY_HASH_ALG_SHA512 = 0x2 FUTEXFS_SUPER_MAGIC = 0xbad1dea F_ADD_SEALS = 0x409 F_DUPFD = 0x0 @@ -733,6 +739,7 @@ const ( GENL_NAMSIZ = 0x10 GENL_START_ALLOC = 0x13 GENL_UNS_ADMIN_PERM = 0x10 + GRND_INSECURE = 0x4 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 HDIO_DRIVE_CMD = 0x31f @@ -890,6 +897,7 @@ const ( IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 + IPPROTO_L2TP = 0x73 IPPROTO_MH = 0x87 IPPROTO_MPLS = 0x89 IPPROTO_MTP = 0x5c @@ -1482,6 +1490,7 @@ const ( PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_FP_MODE = 0x2e + PR_GET_IO_FLUSHER = 0x3a PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 @@ -1517,6 +1526,7 @@ const ( PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_FP_MODE = 0x2d + PR_SET_IO_FLUSHER = 0x39 PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_ARG_END = 0x9 @@ -1745,12 +1755,15 @@ const ( RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d + RTM_DELVLAN = 0x71 RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_FIB_MATCH = 0x2000 RTM_F_LOOKUP_TABLE = 0x1000 RTM_F_NOTIFY = 0x100 + RTM_F_OFFLOAD = 0x4000 RTM_F_PREFIX = 0x800 + RTM_F_TRAP = 0x8000 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a @@ -1772,7 +1785,8 @@ const ( RTM_GETSTATS = 0x5e RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e - RTM_MAX = 0x6f + RTM_GETVLAN = 0x72 + RTM_MAX = 0x73 RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 @@ -1787,6 +1801,7 @@ const ( RTM_NEWNETCONF = 0x50 RTM_NEWNEXTHOP = 0x68 RTM_NEWNSID = 0x58 + RTM_NEWNVLAN = 0x70 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 @@ -1794,8 +1809,8 @@ const ( RTM_NEWSTATS = 0x5c RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c - RTM_NR_FAMILIES = 0x18 - RTM_NR_MSGTYPES = 0x60 + RTM_NR_FAMILIES = 0x19 + RTM_NR_MSGTYPES = 0x64 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 @@ -2085,7 +2100,7 @@ const ( TASKSTATS_GENL_NAME = "TASKSTATS" TASKSTATS_GENL_VERSION = 0x1 TASKSTATS_TYPE_MAX = 0x6 - TASKSTATS_VERSION = 0x9 + TASKSTATS_VERSION = 0xa TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 @@ -2150,6 +2165,8 @@ const ( TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCP_ZEROCOPY_RECEIVE = 0x23 + TFD_TIMER_ABSTIME = 0x1 + TFD_TIMER_CANCEL_ON_SET = 0x2 TIMER_ABSTIME = 0x1 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 @@ -2266,7 +2283,7 @@ const ( VMADDR_CID_ANY = 0xffffffff VMADDR_CID_HOST = 0x2 VMADDR_CID_HYPERVISOR = 0x0 - VMADDR_CID_RESERVED = 0x1 + VMADDR_CID_LOCAL = 0x1 VMADDR_PORT_ANY = 0xffffffff VM_SOCKETS_INVALID_VERSION = 0xffffffff VQUIT = 0x1 @@ -2393,6 +2410,7 @@ const ( XENFS_SUPER_MAGIC = 0xabba1974 XFS_SUPER_MAGIC = 0x58465342 Z3FOLD_MAGIC = 0x33 + ZONEFS_MAGIC = 0x5a4f4653 ZSMALLOC_MAGIC = 0x58295829 ) diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index 0876cf92ff3..5e974110d9a 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -73,6 +73,8 @@ const ( FFDLY = 0x8000 FLUSHO = 0x1000 FP_XSTATE_MAGIC2 = 0x46505845 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80046601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 @@ -340,6 +342,8 @@ const ( TCSETXF = 0x5434 TCSETXW = 0x5435 TCXONC = 0x540a + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x800 TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index d5be2e83770..47a57fe4688 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -73,6 +73,8 @@ const ( FFDLY = 0x8000 FLUSHO = 0x1000 FP_XSTATE_MAGIC2 = 0x46505845 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 @@ -341,6 +343,8 @@ const ( TCSETXF = 0x5434 TCSETXW = 0x5435 TCXONC = 0x540a + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x800 TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index fbeef832523..df2eea4bb7b 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80046601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 @@ -347,6 +349,8 @@ const ( TCSETXF = 0x5434 TCSETXW = 0x5435 TCXONC = 0x540a + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x800 TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index 06daa50ebdc..4e1214217f2 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -75,6 +75,8 @@ const ( FFDLY = 0x8000 FLUSHO = 0x1000 FPSIMD_MAGIC = 0x46508001 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 @@ -334,6 +336,8 @@ const ( TCSETXF = 0x5434 TCSETXW = 0x5435 TCXONC = 0x540a + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x800 TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index 7c866b8f5be..a23b08029a9 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40046601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 @@ -337,6 +339,8 @@ const ( TCSETSW = 0x540f TCSETSW2 = 0x8030542c TCXONC = 0x5406 + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x80 TIOCCBRK = 0x5428 TIOCCONS = 0x80047478 TIOCEXCL = 0x740d diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index c42966d19ce..a5a921e43b8 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 @@ -337,6 +339,8 @@ const ( TCSETSW = 0x540f TCSETSW2 = 0x8030542c TCXONC = 0x5406 + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x80 TIOCCBRK = 0x5428 TIOCCONS = 0x80047478 TIOCEXCL = 0x740d diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index a5b2b42739d..d088e197bd4 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 @@ -337,6 +339,8 @@ const ( TCSETSW = 0x540f TCSETSW2 = 0x8030542c TCXONC = 0x5406 + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x80 TIOCCBRK = 0x5428 TIOCCONS = 0x80047478 TIOCEXCL = 0x740d diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index 7f91881b819..0ddf9d5fe86 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x2000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40046601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 @@ -337,6 +339,8 @@ const ( TCSETSW = 0x540f TCSETSW2 = 0x8030542c TCXONC = 0x5406 + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x80 TIOCCBRK = 0x5428 TIOCCONS = 0x80047478 TIOCEXCL = 0x740d diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 63df35597ec..a93ffc18072 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -72,6 +72,8 @@ const ( FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 @@ -391,6 +393,8 @@ const ( TCSETSF = 0x802c7416 TCSETSW = 0x802c7415 TCXONC = 0x2000741e + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x800 TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index 7ab68f7c8a3..c1ea48b95fd 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -72,6 +72,8 @@ const ( FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 @@ -391,6 +393,8 @@ const ( TCSETSF = 0x802c7416 TCSETSW = 0x802c7415 TCXONC = 0x2000741e + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x800 TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index f99cf1b9e08..7def950ba51 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 @@ -328,6 +330,8 @@ const ( TCSETXF = 0x5434 TCSETXW = 0x5435 TCXONC = 0x540a + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x800 TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index 613ee237e30..d39293c8717 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -72,6 +72,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 + FS_IOC_ENABLE_VERITY = 0x40806685 + FS_IOC_GETFLAGS = 0x80086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x400c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x40106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x800c6613 @@ -401,6 +403,8 @@ const ( TCSETXF = 0x5434 TCSETXW = 0x5435 TCXONC = 0x540a + TFD_CLOEXEC = 0x80000 + TFD_NONBLOCK = 0x800 TIOCCBRK = 0x5428 TIOCCONS = 0x541d TIOCEXCL = 0x540c diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index 1f7a68d5cce..3ff3ec681b0 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -76,6 +76,8 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 + FS_IOC_ENABLE_VERITY = 0x80806685 + FS_IOC_GETFLAGS = 0x40086601 FS_IOC_GET_ENCRYPTION_POLICY = 0x800c6615 FS_IOC_GET_ENCRYPTION_PWSALT = 0x80106614 FS_IOC_SET_ENCRYPTION_POLICY = 0x400c6613 @@ -390,6 +392,8 @@ const ( TCSETSW = 0x8024540a TCSETSW2 = 0x802c540e TCXONC = 0x20005406 + TFD_CLOEXEC = 0x400000 + TFD_NONBLOCK = 0x4000 TIOCCBRK = 0x2000747a TIOCCONS = 0x20007424 TIOCEXCL = 0x2000740d diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.1_11.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.1_11.go index c1cc0a415fe..23e94d3663c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.1_11.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.1_11.go @@ -966,6 +966,16 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Gettimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) @@ -1709,18 +1719,6 @@ func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func gettimeofday(tp *Timeval) (sec int32, usec int32, err error) { - r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - sec = int32(r0) - usec = int32(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go index a3fc4900412..e2ffb3bed33 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go @@ -1376,6 +1376,21 @@ func libc_getsid_trampoline() // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Gettimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(funcPC(libc_gettimeofday_trampoline), uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_gettimeofday_trampoline() + +//go:linkname libc_gettimeofday libc_gettimeofday +//go:cgo_import_dynamic libc_gettimeofday gettimeofday "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getuid() (uid int) { r0, _, _ := syscall_rawSyscall(funcPC(libc_getuid_trampoline), 0, 0, 0) uid = int(r0) @@ -2357,23 +2372,6 @@ func libc_ptrace_trampoline() // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func gettimeofday(tp *Timeval) (sec int32, usec int32, err error) { - r0, r1, e1 := syscall_rawSyscall(funcPC(libc_gettimeofday_trampoline), uintptr(unsafe.Pointer(tp)), 0, 0) - sec = int32(r0) - usec = int32(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -func libc_gettimeofday_trampoline() - -//go:linkname libc_gettimeofday libc_gettimeofday -//go:cgo_import_dynamic libc_gettimeofday gettimeofday "/usr/lib/libSystem.B.dylib" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := syscall_syscall(funcPC(libc_fstat64_trampoline), uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_11.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_11.go index f8e5c37c5ca..102561730ab 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_11.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.1_11.go @@ -966,6 +966,16 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Gettimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) @@ -1709,18 +1719,6 @@ func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) { - r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - sec = int64(r0) - usec = int32(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go index 50d6437e6b8..c67e336e2ab 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go @@ -1376,6 +1376,21 @@ func libc_getsid_trampoline() // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Gettimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(funcPC(libc_gettimeofday_trampoline), uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_gettimeofday_trampoline() + +//go:linkname libc_gettimeofday libc_gettimeofday +//go:cgo_import_dynamic libc_gettimeofday gettimeofday "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getuid() (uid int) { r0, _, _ := syscall_rawSyscall(funcPC(libc_getuid_trampoline), 0, 0, 0) uid = int(r0) @@ -2357,23 +2372,6 @@ func libc_ptrace_trampoline() // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) { - r0, r1, e1 := syscall_rawSyscall(funcPC(libc_gettimeofday_trampoline), uintptr(unsafe.Pointer(tp)), 0, 0) - sec = int64(r0) - usec = int32(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -func libc_gettimeofday_trampoline() - -//go:linkname libc_gettimeofday libc_gettimeofday -//go:cgo_import_dynamic libc_gettimeofday gettimeofday "/usr/lib/libSystem.B.dylib" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := syscall_syscall(funcPC(libc_fstat64_trampoline), uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.1_11.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.1_11.go index cea04e041c4..d34e6df2fe0 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.1_11.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.1_11.go @@ -966,6 +966,16 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Gettimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) @@ -1682,18 +1692,6 @@ func writelen(fd int, buf *byte, nbuf int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func gettimeofday(tp *Timeval) (sec int32, usec int32, err error) { - r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - sec = int32(r0) - usec = int32(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go index 63103950ca7..b759757a77a 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go @@ -1376,6 +1376,21 @@ func libc_getsid_trampoline() // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Gettimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(funcPC(libc_gettimeofday_trampoline), uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_gettimeofday_trampoline() + +//go:linkname libc_gettimeofday libc_gettimeofday +//go:cgo_import_dynamic libc_gettimeofday gettimeofday "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getuid() (uid int) { r0, _, _ := syscall_rawSyscall(funcPC(libc_getuid_trampoline), 0, 0, 0) uid = int(r0) @@ -2342,23 +2357,6 @@ func writelen(fd int, buf *byte, nbuf int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func gettimeofday(tp *Timeval) (sec int32, usec int32, err error) { - r0, r1, e1 := syscall_rawSyscall(funcPC(libc_gettimeofday_trampoline), uintptr(unsafe.Pointer(tp)), 0, 0) - sec = int32(r0) - usec = int32(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -func libc_gettimeofday_trampoline() - -//go:linkname libc_gettimeofday libc_gettimeofday -//go:cgo_import_dynamic libc_gettimeofday gettimeofday "/usr/lib/libSystem.B.dylib" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := syscall_syscall(funcPC(libc_fstat_trampoline), uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_11.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_11.go index 8c3bb3a25d1..8d39a09f721 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_11.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.1_11.go @@ -966,6 +966,16 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Gettimeofday(tp *Timeval) (err error) { + _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) @@ -1682,18 +1692,6 @@ func writelen(fd int, buf *byte, nbuf int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) { - r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) - sec = int64(r0) - usec = int32(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go index a8709f72dd7..b2886126003 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go @@ -1376,6 +1376,21 @@ func libc_getsid_trampoline() // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Gettimeofday(tp *Timeval) (err error) { + _, _, e1 := syscall_rawSyscall(funcPC(libc_gettimeofday_trampoline), uintptr(unsafe.Pointer(tp)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_gettimeofday_trampoline() + +//go:linkname libc_gettimeofday libc_gettimeofday +//go:cgo_import_dynamic libc_gettimeofday gettimeofday "/usr/lib/libSystem.B.dylib" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getuid() (uid int) { r0, _, _ := syscall_rawSyscall(funcPC(libc_getuid_trampoline), 0, 0, 0) uid = int(r0) @@ -2342,23 +2357,6 @@ func writelen(fd int, buf *byte, nbuf int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) { - r0, r1, e1 := syscall_rawSyscall(funcPC(libc_gettimeofday_trampoline), uintptr(unsafe.Pointer(tp)), 0, 0) - sec = int64(r0) - usec = int32(r1) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -func libc_gettimeofday_trampoline() - -//go:linkname libc_gettimeofday libc_gettimeofday -//go:cgo_import_dynamic libc_gettimeofday gettimeofday "/usr/lib/libSystem.B.dylib" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := syscall_syscall(funcPC(libc_fstat_trampoline), uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go index c9058f3091b..600f1d26d21 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go @@ -214,22 +214,6 @@ func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, ne // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) @@ -376,8 +360,15 @@ func pipe2(p *[2]_C_int, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func ptrace(request int, pid int, addr uintptr, data int) (err error) { - _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) if e1 != 0 { err = errnoErr(e1) } @@ -386,15 +377,24 @@ func ptrace(request int, pid int, addr uintptr, data int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getcwd(buf []byte) (n int, err error) { +func ioctl(fd int, req uint, arg uintptr) (err error) { + _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer - if len(buf) > 0 { - _p0 = unsafe.Pointer(&buf[0]) + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) - n = int(r0) + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) if e1 != 0 { err = errnoErr(e1) } @@ -403,8 +403,8 @@ func Getcwd(buf []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func ioctl(fd int, req uint, arg uintptr) (err error) { - _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) +func ptrace(request int, pid int, addr uintptr, data int) (err error) { + _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } @@ -1352,7 +1352,7 @@ func mknodat_freebsd12(fd int, path string, mode uint32, dev uint64) (err error) if err != nil { return } - _, _, e1 := Syscall6(SYS_MKNODAT_FREEBSD12, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) + _, _, e1 := Syscall6(SYS_MKNODAT_FREEBSD12, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), uintptr(dev>>32), 0) if e1 != 0 { err = errnoErr(e1) } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go index 49b20c22966..064934b0d13 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go @@ -350,22 +350,6 @@ func Munlockall() (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { @@ -403,6 +387,22 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ptrace(request int, pid int, addr uintptr, data int) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go index abab3d7cbe3..4adaaa56183 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go @@ -1,4 +1,4 @@ -// go run mksyscall.go -tags freebsd,arm64 -- syscall_bsd.go syscall_freebsd.go syscall_freebsd_arm64.go +// go run mksyscall.go -tags freebsd,arm64 syscall_bsd.go syscall_freebsd.go syscall_freebsd_arm64.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build freebsd,arm64 @@ -350,22 +350,6 @@ func Munlockall() (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { @@ -403,6 +387,22 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { + var _p0 unsafe.Pointer + if len(mib) > 0 { + _p0 = unsafe.Pointer(&mib[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ptrace(request int, pid int, addr uintptr, data int) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go new file mode 100644 index 00000000000..92efa1da3cd --- /dev/null +++ b/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go @@ -0,0 +1,87 @@ +// go run mksyscall_solaris.go -illumos -tags illumos,amd64 syscall_illumos.go +// Code generated by the command above; see README.md. DO NOT EDIT. + +// +build illumos,amd64 + +package unix + +import ( + "unsafe" +) + +//go:cgo_import_dynamic libc_readv readv "libc.so" +//go:cgo_import_dynamic libc_preadv preadv "libc.so" +//go:cgo_import_dynamic libc_writev writev "libc.so" +//go:cgo_import_dynamic libc_pwritev pwritev "libc.so" + +//go:linkname procreadv libc_readv +//go:linkname procpreadv libc_preadv +//go:linkname procwritev libc_writev +//go:linkname procpwritev libc_pwritev + +var ( + procreadv, + procpreadv, + procwritev, + procpwritev syscallFunc +) + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func readv(fd int, iovs []Iovec) (n int, err error) { + var _p0 *Iovec + if len(iovs) > 0 { + _p0 = &iovs[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procreadv)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = e1 + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func preadv(fd int, iovs []Iovec, off int64) (n int, err error) { + var _p0 *Iovec + if len(iovs) > 0 { + _p0 = &iovs[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpreadv)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), uintptr(off), 0, 0) + n = int(r0) + if e1 != 0 { + err = e1 + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writev(fd int, iovs []Iovec) (n int, err error) { + var _p0 *Iovec + if len(iovs) > 0 { + _p0 = &iovs[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwritev)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = e1 + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func pwritev(fd int, iovs []Iovec, off int64) (n int, err error) { + var _p0 *Iovec + if len(iovs) > 0 { + _p0 = &iovs[0] + } + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpwritev)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), uintptr(off), 0, 0) + n = int(r0) + if e1 != 0 { + err = e1 + } + return +} diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/vendor/golang.org/x/sys/unix/zsyscall_linux.go index fd2dae8e577..df217825f06 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -1450,6 +1450,37 @@ func Sysinfo(info *Sysinfo_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func TimerfdCreate(clockid int, flags int) (fd int, err error) { + r0, _, e1 := RawSyscall(SYS_TIMERFD_CREATE, uintptr(clockid), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func TimerfdGettime(fd int, currValue *ItimerSpec) (err error) { + _, _, e1 := RawSyscall(SYS_TIMERFD_GETTIME, uintptr(fd), uintptr(unsafe.Pointer(currValue)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func TimerfdSettime(fd int, flags int, newValue *ItimerSpec, oldValue *ItimerSpec) (err error) { + _, _, e1 := RawSyscall6(SYS_TIMERFD_SETTIME, uintptr(fd), uintptr(flags), uintptr(unsafe.Pointer(newValue)), uintptr(unsafe.Pointer(oldValue)), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go index ba63af7b08d..19ebd3ff75f 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go @@ -55,7 +55,7 @@ func pipe(p *[2]_C_int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { +func dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go index f64adef415a..5c562182a19 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go @@ -45,7 +45,7 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { +func dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go index ac19523e887..dc69d99c612 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go @@ -234,7 +234,7 @@ func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { +func dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go index f0d2890b161..1b897dee05d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go @@ -151,7 +151,7 @@ func Getgid() (gid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Getrlimit(resource int, rlim *Rlimit) (err error) { +func getrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) @@ -307,7 +307,7 @@ func Setresuid(ruid int, euid int, suid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Setrlimit(resource int, rlim *Rlimit) (err error) { +func setrlimit(resource int, rlim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(resource), uintptr(unsafe.Pointer(rlim)), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go index aecbbca7542..49186843ae5 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go @@ -45,7 +45,7 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { +func dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go index 424fb7fb601..9171d3bd2a6 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go @@ -45,7 +45,7 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { +func dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go index 28c7239cf64..82286f04f9a 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go @@ -45,7 +45,7 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { +func dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go index 84596b300a6..15920621c47 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go @@ -45,7 +45,7 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { +func dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go index de022639d68..73a42e2ccba 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go @@ -45,7 +45,7 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { +func dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go index 888f21d37ac..6b85595366a 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go @@ -45,7 +45,7 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { +func dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go index 9bc353f0c42..d7032ab1e4a 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go @@ -45,7 +45,7 @@ func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { +func dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go index 854e816d672..bcbbdd906e8 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go @@ -72,7 +72,7 @@ func Fadvise(fd int, offset int64, length int64, advice int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Dup2(oldfd int, newfd int) (err error) { +func dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) diff --git a/vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go b/vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go index 37dcc74c2de..102f1ab4750 100644 --- a/vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsysctl_openbsd_386.go @@ -1,4 +1,4 @@ -// mksysctl_openbsd.pl +// go run mksysctl_openbsd.go // Code generated by the command above; DO NOT EDIT. // +build 386,openbsd @@ -30,6 +30,7 @@ var sysctlMib = []mibentry{ {"hw.model", []_C_int{6, 2}}, {"hw.ncpu", []_C_int{6, 3}}, {"hw.ncpufound", []_C_int{6, 21}}, + {"hw.ncpuonline", []_C_int{6, 25}}, {"hw.pagesize", []_C_int{6, 7}}, {"hw.physmem", []_C_int{6, 19}}, {"hw.product", []_C_int{6, 15}}, diff --git a/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go index fe6caa6eb7f..4866fced8ae 100644 --- a/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go @@ -31,6 +31,7 @@ var sysctlMib = []mibentry{ {"hw.model", []_C_int{6, 2}}, {"hw.ncpu", []_C_int{6, 3}}, {"hw.ncpufound", []_C_int{6, 21}}, + {"hw.ncpuonline", []_C_int{6, 25}}, {"hw.pagesize", []_C_int{6, 7}}, {"hw.perfpolicy", []_C_int{6, 23}}, {"hw.physmem", []_C_int{6, 19}}, diff --git a/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go b/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go index 6eb8c0b086a..d3801eb24b3 100644 --- a/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsysctl_openbsd_arm.go @@ -30,6 +30,7 @@ var sysctlMib = []mibentry{ {"hw.model", []_C_int{6, 2}}, {"hw.ncpu", []_C_int{6, 3}}, {"hw.ncpufound", []_C_int{6, 21}}, + {"hw.ncpuonline", []_C_int{6, 25}}, {"hw.pagesize", []_C_int{6, 7}}, {"hw.physmem", []_C_int{6, 19}}, {"hw.product", []_C_int{6, 15}}, diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go index 7aae554f210..54559a8956d 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go @@ -431,4 +431,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go index 7968439a926..054a741b7fc 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go @@ -353,4 +353,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go index 3c663c69d4b..307f2ba12ec 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go @@ -395,4 +395,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go index 1f3b4d150fe..e9404dd545f 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go @@ -298,4 +298,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go index 00da3de9077..68bb6d29b8d 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go @@ -416,4 +416,6 @@ const ( SYS_FSPICK = 4433 SYS_PIDFD_OPEN = 4434 SYS_CLONE3 = 4435 + SYS_OPENAT2 = 4437 + SYS_PIDFD_GETFD = 4438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go index d404fbd4d42..4e5251185f4 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go @@ -346,4 +346,6 @@ const ( SYS_FSPICK = 5433 SYS_PIDFD_OPEN = 5434 SYS_CLONE3 = 5435 + SYS_OPENAT2 = 5437 + SYS_PIDFD_GETFD = 5438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go index bfbf242f331..4d9aa3003b9 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go @@ -346,4 +346,6 @@ const ( SYS_FSPICK = 5433 SYS_PIDFD_OPEN = 5434 SYS_CLONE3 = 5435 + SYS_OPENAT2 = 5437 + SYS_PIDFD_GETFD = 5438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go index 3826f497ad7..64af0707d5a 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go @@ -416,4 +416,6 @@ const ( SYS_FSPICK = 4433 SYS_PIDFD_OPEN = 4434 SYS_CLONE3 = 4435 + SYS_OPENAT2 = 4437 + SYS_PIDFD_GETFD = 4438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go index 52e3da64904..cc3c067ba31 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go @@ -395,4 +395,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go index 6141f90a823..4050ff98361 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go @@ -395,4 +395,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go index 4f7261a884d..529abb6a7f4 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go @@ -297,4 +297,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go index f47014ac058..27665001092 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go @@ -360,4 +360,6 @@ const ( SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 SYS_CLONE3 = 435 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go index dd78abb0d6b..4dc82bb2492 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go @@ -374,4 +374,6 @@ const ( SYS_FSMOUNT = 432 SYS_FSPICK = 433 SYS_PIDFD_OPEN = 434 + SYS_OPENAT2 = 437 + SYS_PIDFD_GETFD = 438 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go index 0ec159680b9..2a3ec615f75 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go @@ -128,9 +128,9 @@ type Statfs_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [1024]int8 - Mntonname [1024]int8 + Fstypename [16]byte + Mntfromname [1024]byte + Mntonname [1024]byte } type statfs_freebsd11_t struct { @@ -153,9 +153,9 @@ type statfs_freebsd11_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [88]int8 - Mntonname [88]int8 + Fstypename [16]byte + Mntfromname [88]byte + Mntonname [88]byte } type Flock_t struct { @@ -375,15 +375,15 @@ type PtraceLwpInfoStruct struct { } type __Siginfo struct { - Signo int32 - Errno int32 - Code int32 - Pid int32 - Uid uint32 - Status int32 - Addr *byte - Value [4]byte - X_reason [32]byte + Signo int32 + Errno int32 + Code int32 + Pid int32 + Uid uint32 + Status int32 + Addr *byte + Value [4]byte + _ [32]byte } type Sigset_t struct { @@ -458,7 +458,7 @@ type ifMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Data ifData } @@ -469,7 +469,6 @@ type IfMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte Data IfData } @@ -536,7 +535,7 @@ type IfaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Metric int32 } @@ -547,7 +546,7 @@ type IfmaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 } type IfAnnounceMsghdr struct { @@ -564,7 +563,7 @@ type RtMsghdr struct { Version uint8 Type uint8 Index uint16 - _ [2]byte + _ uint16 Flags int32 Addrs int32 Pid int32 diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go index 8340f577536..e11e95499e8 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go @@ -123,9 +123,9 @@ type Statfs_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [1024]int8 - Mntonname [1024]int8 + Fstypename [16]byte + Mntfromname [1024]byte + Mntonname [1024]byte } type statfs_freebsd11_t struct { @@ -148,9 +148,9 @@ type statfs_freebsd11_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [88]int8 - Mntonname [88]int8 + Fstypename [16]byte + Mntfromname [88]byte + Mntonname [88]byte } type Flock_t struct { @@ -275,10 +275,8 @@ type IPv6Mreq struct { type Msghdr struct { Name *byte Namelen uint32 - _ [4]byte Iov *Iovec Iovlen int32 - _ [4]byte Control *byte Controllen uint32 Flags int32 @@ -463,7 +461,7 @@ type ifMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Data ifData } @@ -474,7 +472,6 @@ type IfMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte Data IfData } @@ -541,7 +538,7 @@ type IfaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Metric int32 } @@ -552,7 +549,7 @@ type IfmaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 } type IfAnnounceMsghdr struct { @@ -569,7 +566,7 @@ type RtMsghdr struct { Version uint8 Type uint8 Index uint16 - _ [2]byte + _ uint16 Flags int32 Addrs int32 Pid int32 @@ -623,7 +620,6 @@ type BpfZbuf struct { type BpfProgram struct { Len uint32 - _ [4]byte Insns *BpfInsn } diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go index e751e00336b..c6fe1d097d8 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm64.go @@ -1,4 +1,4 @@ -// cgo -godefs types_freebsd.go | go run mkpost.go +// cgo -godefs -- -fsigned-char types_freebsd.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build arm64,freebsd @@ -123,9 +123,9 @@ type Statfs_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [1024]int8 - Mntonname [1024]int8 + Fstypename [16]byte + Mntfromname [1024]byte + Mntonname [1024]byte } type statfs_freebsd11_t struct { @@ -148,9 +148,9 @@ type statfs_freebsd11_t struct { Owner uint32 Fsid Fsid Charspare [80]int8 - Fstypename [16]int8 - Mntfromname [88]int8 - Mntonname [88]int8 + Fstypename [16]byte + Mntfromname [88]byte + Mntonname [88]byte } type Flock_t struct { @@ -275,10 +275,8 @@ type IPv6Mreq struct { type Msghdr struct { Name *byte Namelen uint32 - _ [4]byte Iov *Iovec Iovlen int32 - _ [4]byte Control *byte Controllen uint32 Flags int32 @@ -326,11 +324,9 @@ const ( PTRACE_CONT = 0x7 PTRACE_DETACH = 0xb PTRACE_GETFPREGS = 0x23 - PTRACE_GETFSBASE = 0x47 PTRACE_GETLWPLIST = 0xf PTRACE_GETNUMLWPS = 0xe PTRACE_GETREGS = 0x21 - PTRACE_GETXSTATE = 0x45 PTRACE_IO = 0xc PTRACE_KILL = 0x8 PTRACE_LWPEVENTS = 0x18 @@ -373,15 +369,15 @@ type PtraceLwpInfoStruct struct { } type __Siginfo struct { - Signo int32 - Errno int32 - Code int32 - Pid int32 - Uid uint32 - Status int32 - Addr *byte - Value [8]byte - X_reason [40]byte + Signo int32 + Errno int32 + Code int32 + Pid int32 + Uid uint32 + Status int32 + Addr *byte + Value [8]byte + _ [40]byte } type Sigset_t struct { @@ -394,12 +390,14 @@ type Reg struct { Sp uint64 Elr uint64 Spsr uint32 + _ [4]byte } type FpReg struct { - Fp_q [512]uint8 - Fp_sr uint32 - Fp_cr uint32 + Q [32][16]uint8 + Sr uint32 + Cr uint32 + _ [8]byte } type PtraceIoDesc struct { @@ -441,7 +439,7 @@ type ifMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Data ifData } @@ -452,7 +450,6 @@ type IfMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte Data IfData } @@ -519,7 +516,7 @@ type IfaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 Metric int32 } @@ -530,7 +527,7 @@ type IfmaMsghdr struct { Addrs int32 Flags int32 Index uint16 - _ [2]byte + _ uint16 } type IfAnnounceMsghdr struct { @@ -547,7 +544,7 @@ type RtMsghdr struct { Version uint8 Type uint8 Index uint16 - _ [2]byte + _ uint16 Flags int32 Addrs int32 Pid int32 @@ -601,7 +598,6 @@ type BpfZbuf struct { type BpfProgram struct { Len uint32 - _ [4]byte Insns *BpfInsn } diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux.go b/vendor/golang.org/x/sys/unix/ztypes_linux.go index 6c81e7515c8..416f7767e7d 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -18,6 +18,11 @@ type ( _C_long_long int64 ) +type ItimerSpec struct { + Interval Timespec + Value Timespec +} + const ( TIME_OK = 0x0 TIME_INS = 0x1 @@ -114,7 +119,8 @@ type FscryptKeySpecifier struct { type FscryptAddKeyArg struct { Key_spec FscryptKeySpecifier Raw_size uint32 - _ [9]uint32 + Key_id uint32 + _ [8]uint32 } type FscryptRemoveKeyArg struct { @@ -243,6 +249,23 @@ type RawSockaddrTIPC struct { Addr [12]byte } +type RawSockaddrL2TPIP struct { + Family uint16 + Unused uint16 + Addr [4]byte /* in_addr */ + Conn_id uint32 + _ [4]uint8 +} + +type RawSockaddrL2TPIP6 struct { + Family uint16 + Unused uint16 + Flowinfo uint32 + Addr [16]byte /* in6_addr */ + Scope_id uint32 + Conn_id uint32 +} + type _Socklen uint32 type Linger struct { @@ -353,6 +376,8 @@ const ( SizeofSockaddrXDP = 0x10 SizeofSockaddrPPPoX = 0x1e SizeofSockaddrTIPC = 0x10 + SizeofSockaddrL2TPIP = 0x10 + SizeofSockaddrL2TPIP6 = 0x20 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc @@ -460,7 +485,7 @@ const ( IFLA_NEW_IFINDEX = 0x31 IFLA_MIN_MTU = 0x32 IFLA_MAX_MTU = 0x33 - IFLA_MAX = 0x35 + IFLA_MAX = 0x36 IFLA_INFO_KIND = 0x1 IFLA_INFO_DATA = 0x2 IFLA_INFO_XSTATS = 0x3 @@ -2272,3 +2297,49 @@ const ( DEVLINK_DPIPE_HEADER_IPV4 = 0x1 DEVLINK_DPIPE_HEADER_IPV6 = 0x2 ) + +type FsverityDigest struct { + Algorithm uint16 + Size uint16 +} + +type FsverityEnableArg struct { + Version uint32 + Hash_algorithm uint32 + Block_size uint32 + Salt_size uint32 + Salt_ptr uint64 + Sig_size uint32 + _ uint32 + Sig_ptr uint64 + _ [11]uint64 +} + +type Nhmsg struct { + Family uint8 + Scope uint8 + Protocol uint8 + Resvd uint8 + Flags uint32 +} + +type NexthopGrp struct { + Id uint32 + Weight uint8 + Resvd1 uint8 + Resvd2 uint16 +} + +const ( + NHA_UNSPEC = 0x0 + NHA_ID = 0x1 + NHA_GROUP = 0x2 + NHA_GROUP_TYPE = 0x3 + NHA_BLACKHOLE = 0x4 + NHA_OIF = 0x5 + NHA_GATEWAY = 0x6 + NHA_ENCAP_TYPE = 0x7 + NHA_ENCAP = 0x8 + NHA_GROUPS = 0x9 + NHA_MASTER = 0xa +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go index fc6b3fb5c4e..761b67c8643 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go @@ -287,6 +287,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint32 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go index 26c30b84d09..201fb3482de 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go @@ -298,6 +298,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go index 814d42d5435..8051b56108f 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go @@ -276,6 +276,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint32 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go index d9664c71355..a936f21692f 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go @@ -277,6 +277,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go index 0d721454f5f..aaca03dd7db 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go @@ -281,6 +281,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint32 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go index ef697684d13..2e7f3b8ca48 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go @@ -280,6 +280,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go index 485fda70be1..16add5a2575 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go @@ -280,6 +280,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go index 569477eef8e..4ed2c8e54c4 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go @@ -281,6 +281,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint32 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go index 602d8b4eede..74151909976 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go @@ -287,6 +287,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go index 6db9a7b7377..046c2debd4f 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go @@ -287,6 +287,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go index 52b5348c2e9..0f2f61a6ad1 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go @@ -305,6 +305,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go index a111387b3ac..cca1b6be270 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go @@ -300,6 +300,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go index 8153af18189..33a73bf183b 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go @@ -282,6 +282,7 @@ type Taskstats struct { Freepages_delay_total uint64 Thrashing_count uint64 Thrashing_delay_total uint64 + Ac_btime64 uint64 } type cpuMask uint64 diff --git a/vendor/golang.org/x/text/transform/transform.go b/vendor/golang.org/x/text/transform/transform.go index 520b9ada0e2..48ec64b40ca 100644 --- a/vendor/golang.org/x/text/transform/transform.go +++ b/vendor/golang.org/x/text/transform/transform.go @@ -648,7 +648,8 @@ func String(t Transformer, s string) (result string, n int, err error) { // Transform the remaining input, growing dst and src buffers as necessary. for { n := copy(src, s[pSrc:]) - nDst, nSrc, err := t.Transform(dst[pDst:], src[:n], pSrc+n == len(s)) + atEOF := pSrc+n == len(s) + nDst, nSrc, err := t.Transform(dst[pDst:], src[:n], atEOF) pDst += nDst pSrc += nSrc @@ -659,6 +660,9 @@ func String(t Transformer, s string) (result string, n int, err error) { dst = grow(dst, pDst) } } else if err == ErrShortSrc { + if atEOF { + return string(dst[:pDst]), pSrc, err + } if nSrc == 0 { src = grow(src, 0) } diff --git a/vendor/golang.org/x/text/unicode/bidi/core.go b/vendor/golang.org/x/text/unicode/bidi/core.go index 48d144008aa..50deb6600a3 100644 --- a/vendor/golang.org/x/text/unicode/bidi/core.go +++ b/vendor/golang.org/x/text/unicode/bidi/core.go @@ -480,15 +480,15 @@ func (s *isolatingRunSequence) resolveWeakTypes() { // Rule W1. // Changes all NSMs. - preceedingCharacterType := s.sos + precedingCharacterType := s.sos for i, t := range s.types { if t == NSM { - s.types[i] = preceedingCharacterType + s.types[i] = precedingCharacterType } else { if t.in(LRI, RLI, FSI, PDI) { - preceedingCharacterType = ON + precedingCharacterType = ON } - preceedingCharacterType = t + precedingCharacterType = t } } diff --git a/vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go b/vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go index 022e3c69092..16b11db5388 100644 --- a/vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go +++ b/vendor/golang.org/x/text/unicode/bidi/tables11.0.0.go @@ -1,6 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. -// +build go1.13 +// +build go1.13,!go1.14 package bidi diff --git a/vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go b/vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go new file mode 100644 index 00000000000..7ffa365121c --- /dev/null +++ b/vendor/golang.org/x/text/unicode/bidi/tables12.0.0.go @@ -0,0 +1,1923 @@ +// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. + +// +build go1.14 + +package bidi + +// UnicodeVersion is the Unicode version from which the tables in this package are derived. +const UnicodeVersion = "12.0.0" + +// xorMasks contains masks to be xor-ed with brackets to get the reverse +// version. +var xorMasks = []int32{ // 8 elements + 0, 1, 6, 7, 3, 15, 29, 63, +} // Size: 56 bytes + +// lookup returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *bidiTrie) lookup(s []byte) (v uint8, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return bidiValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = bidiIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = bidiIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = bidiIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *bidiTrie) lookupUnsafe(s []byte) uint8 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return bidiValues[c0] + } + i := bidiIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = bidiIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = bidiIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// lookupString returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *bidiTrie) lookupString(s string) (v uint8, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return bidiValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = bidiIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = bidiIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = bidiIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *bidiTrie) lookupStringUnsafe(s string) uint8 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return bidiValues[c0] + } + i := bidiIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = bidiIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = bidiIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// bidiTrie. Total size: 16896 bytes (16.50 KiB). Checksum: 6f0927067913dc6d. +type bidiTrie struct{} + +func newBidiTrie(i int) *bidiTrie { + return &bidiTrie{} +} + +// lookupValue determines the type of block n and looks up the value for b. +func (t *bidiTrie) lookupValue(n uint32, b byte) uint8 { + switch { + default: + return uint8(bidiValues[n<<6+uint32(b)]) + } +} + +// bidiValues: 240 blocks, 15360 entries, 15360 bytes +// The third block is the zero block. +var bidiValues = [15360]uint8{ + // Block 0x0, offset 0x0 + 0x00: 0x000b, 0x01: 0x000b, 0x02: 0x000b, 0x03: 0x000b, 0x04: 0x000b, 0x05: 0x000b, + 0x06: 0x000b, 0x07: 0x000b, 0x08: 0x000b, 0x09: 0x0008, 0x0a: 0x0007, 0x0b: 0x0008, + 0x0c: 0x0009, 0x0d: 0x0007, 0x0e: 0x000b, 0x0f: 0x000b, 0x10: 0x000b, 0x11: 0x000b, + 0x12: 0x000b, 0x13: 0x000b, 0x14: 0x000b, 0x15: 0x000b, 0x16: 0x000b, 0x17: 0x000b, + 0x18: 0x000b, 0x19: 0x000b, 0x1a: 0x000b, 0x1b: 0x000b, 0x1c: 0x0007, 0x1d: 0x0007, + 0x1e: 0x0007, 0x1f: 0x0008, 0x20: 0x0009, 0x21: 0x000a, 0x22: 0x000a, 0x23: 0x0004, + 0x24: 0x0004, 0x25: 0x0004, 0x26: 0x000a, 0x27: 0x000a, 0x28: 0x003a, 0x29: 0x002a, + 0x2a: 0x000a, 0x2b: 0x0003, 0x2c: 0x0006, 0x2d: 0x0003, 0x2e: 0x0006, 0x2f: 0x0006, + 0x30: 0x0002, 0x31: 0x0002, 0x32: 0x0002, 0x33: 0x0002, 0x34: 0x0002, 0x35: 0x0002, + 0x36: 0x0002, 0x37: 0x0002, 0x38: 0x0002, 0x39: 0x0002, 0x3a: 0x0006, 0x3b: 0x000a, + 0x3c: 0x000a, 0x3d: 0x000a, 0x3e: 0x000a, 0x3f: 0x000a, + // Block 0x1, offset 0x40 + 0x40: 0x000a, + 0x5b: 0x005a, 0x5c: 0x000a, 0x5d: 0x004a, + 0x5e: 0x000a, 0x5f: 0x000a, 0x60: 0x000a, + 0x7b: 0x005a, + 0x7c: 0x000a, 0x7d: 0x004a, 0x7e: 0x000a, 0x7f: 0x000b, + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc0: 0x000b, 0xc1: 0x000b, 0xc2: 0x000b, 0xc3: 0x000b, 0xc4: 0x000b, 0xc5: 0x0007, + 0xc6: 0x000b, 0xc7: 0x000b, 0xc8: 0x000b, 0xc9: 0x000b, 0xca: 0x000b, 0xcb: 0x000b, + 0xcc: 0x000b, 0xcd: 0x000b, 0xce: 0x000b, 0xcf: 0x000b, 0xd0: 0x000b, 0xd1: 0x000b, + 0xd2: 0x000b, 0xd3: 0x000b, 0xd4: 0x000b, 0xd5: 0x000b, 0xd6: 0x000b, 0xd7: 0x000b, + 0xd8: 0x000b, 0xd9: 0x000b, 0xda: 0x000b, 0xdb: 0x000b, 0xdc: 0x000b, 0xdd: 0x000b, + 0xde: 0x000b, 0xdf: 0x000b, 0xe0: 0x0006, 0xe1: 0x000a, 0xe2: 0x0004, 0xe3: 0x0004, + 0xe4: 0x0004, 0xe5: 0x0004, 0xe6: 0x000a, 0xe7: 0x000a, 0xe8: 0x000a, 0xe9: 0x000a, + 0xeb: 0x000a, 0xec: 0x000a, 0xed: 0x000b, 0xee: 0x000a, 0xef: 0x000a, + 0xf0: 0x0004, 0xf1: 0x0004, 0xf2: 0x0002, 0xf3: 0x0002, 0xf4: 0x000a, + 0xf6: 0x000a, 0xf7: 0x000a, 0xf8: 0x000a, 0xf9: 0x0002, 0xfb: 0x000a, + 0xfc: 0x000a, 0xfd: 0x000a, 0xfe: 0x000a, 0xff: 0x000a, + // Block 0x4, offset 0x100 + 0x117: 0x000a, + 0x137: 0x000a, + // Block 0x5, offset 0x140 + 0x179: 0x000a, 0x17a: 0x000a, + // Block 0x6, offset 0x180 + 0x182: 0x000a, 0x183: 0x000a, 0x184: 0x000a, 0x185: 0x000a, + 0x186: 0x000a, 0x187: 0x000a, 0x188: 0x000a, 0x189: 0x000a, 0x18a: 0x000a, 0x18b: 0x000a, + 0x18c: 0x000a, 0x18d: 0x000a, 0x18e: 0x000a, 0x18f: 0x000a, + 0x192: 0x000a, 0x193: 0x000a, 0x194: 0x000a, 0x195: 0x000a, 0x196: 0x000a, 0x197: 0x000a, + 0x198: 0x000a, 0x199: 0x000a, 0x19a: 0x000a, 0x19b: 0x000a, 0x19c: 0x000a, 0x19d: 0x000a, + 0x19e: 0x000a, 0x19f: 0x000a, + 0x1a5: 0x000a, 0x1a6: 0x000a, 0x1a7: 0x000a, 0x1a8: 0x000a, 0x1a9: 0x000a, + 0x1aa: 0x000a, 0x1ab: 0x000a, 0x1ac: 0x000a, 0x1ad: 0x000a, 0x1af: 0x000a, + 0x1b0: 0x000a, 0x1b1: 0x000a, 0x1b2: 0x000a, 0x1b3: 0x000a, 0x1b4: 0x000a, 0x1b5: 0x000a, + 0x1b6: 0x000a, 0x1b7: 0x000a, 0x1b8: 0x000a, 0x1b9: 0x000a, 0x1ba: 0x000a, 0x1bb: 0x000a, + 0x1bc: 0x000a, 0x1bd: 0x000a, 0x1be: 0x000a, 0x1bf: 0x000a, + // Block 0x7, offset 0x1c0 + 0x1c0: 0x000c, 0x1c1: 0x000c, 0x1c2: 0x000c, 0x1c3: 0x000c, 0x1c4: 0x000c, 0x1c5: 0x000c, + 0x1c6: 0x000c, 0x1c7: 0x000c, 0x1c8: 0x000c, 0x1c9: 0x000c, 0x1ca: 0x000c, 0x1cb: 0x000c, + 0x1cc: 0x000c, 0x1cd: 0x000c, 0x1ce: 0x000c, 0x1cf: 0x000c, 0x1d0: 0x000c, 0x1d1: 0x000c, + 0x1d2: 0x000c, 0x1d3: 0x000c, 0x1d4: 0x000c, 0x1d5: 0x000c, 0x1d6: 0x000c, 0x1d7: 0x000c, + 0x1d8: 0x000c, 0x1d9: 0x000c, 0x1da: 0x000c, 0x1db: 0x000c, 0x1dc: 0x000c, 0x1dd: 0x000c, + 0x1de: 0x000c, 0x1df: 0x000c, 0x1e0: 0x000c, 0x1e1: 0x000c, 0x1e2: 0x000c, 0x1e3: 0x000c, + 0x1e4: 0x000c, 0x1e5: 0x000c, 0x1e6: 0x000c, 0x1e7: 0x000c, 0x1e8: 0x000c, 0x1e9: 0x000c, + 0x1ea: 0x000c, 0x1eb: 0x000c, 0x1ec: 0x000c, 0x1ed: 0x000c, 0x1ee: 0x000c, 0x1ef: 0x000c, + 0x1f0: 0x000c, 0x1f1: 0x000c, 0x1f2: 0x000c, 0x1f3: 0x000c, 0x1f4: 0x000c, 0x1f5: 0x000c, + 0x1f6: 0x000c, 0x1f7: 0x000c, 0x1f8: 0x000c, 0x1f9: 0x000c, 0x1fa: 0x000c, 0x1fb: 0x000c, + 0x1fc: 0x000c, 0x1fd: 0x000c, 0x1fe: 0x000c, 0x1ff: 0x000c, + // Block 0x8, offset 0x200 + 0x200: 0x000c, 0x201: 0x000c, 0x202: 0x000c, 0x203: 0x000c, 0x204: 0x000c, 0x205: 0x000c, + 0x206: 0x000c, 0x207: 0x000c, 0x208: 0x000c, 0x209: 0x000c, 0x20a: 0x000c, 0x20b: 0x000c, + 0x20c: 0x000c, 0x20d: 0x000c, 0x20e: 0x000c, 0x20f: 0x000c, 0x210: 0x000c, 0x211: 0x000c, + 0x212: 0x000c, 0x213: 0x000c, 0x214: 0x000c, 0x215: 0x000c, 0x216: 0x000c, 0x217: 0x000c, + 0x218: 0x000c, 0x219: 0x000c, 0x21a: 0x000c, 0x21b: 0x000c, 0x21c: 0x000c, 0x21d: 0x000c, + 0x21e: 0x000c, 0x21f: 0x000c, 0x220: 0x000c, 0x221: 0x000c, 0x222: 0x000c, 0x223: 0x000c, + 0x224: 0x000c, 0x225: 0x000c, 0x226: 0x000c, 0x227: 0x000c, 0x228: 0x000c, 0x229: 0x000c, + 0x22a: 0x000c, 0x22b: 0x000c, 0x22c: 0x000c, 0x22d: 0x000c, 0x22e: 0x000c, 0x22f: 0x000c, + 0x234: 0x000a, 0x235: 0x000a, + 0x23e: 0x000a, + // Block 0x9, offset 0x240 + 0x244: 0x000a, 0x245: 0x000a, + 0x247: 0x000a, + // Block 0xa, offset 0x280 + 0x2b6: 0x000a, + // Block 0xb, offset 0x2c0 + 0x2c3: 0x000c, 0x2c4: 0x000c, 0x2c5: 0x000c, + 0x2c6: 0x000c, 0x2c7: 0x000c, 0x2c8: 0x000c, 0x2c9: 0x000c, + // Block 0xc, offset 0x300 + 0x30a: 0x000a, + 0x30d: 0x000a, 0x30e: 0x000a, 0x30f: 0x0004, 0x310: 0x0001, 0x311: 0x000c, + 0x312: 0x000c, 0x313: 0x000c, 0x314: 0x000c, 0x315: 0x000c, 0x316: 0x000c, 0x317: 0x000c, + 0x318: 0x000c, 0x319: 0x000c, 0x31a: 0x000c, 0x31b: 0x000c, 0x31c: 0x000c, 0x31d: 0x000c, + 0x31e: 0x000c, 0x31f: 0x000c, 0x320: 0x000c, 0x321: 0x000c, 0x322: 0x000c, 0x323: 0x000c, + 0x324: 0x000c, 0x325: 0x000c, 0x326: 0x000c, 0x327: 0x000c, 0x328: 0x000c, 0x329: 0x000c, + 0x32a: 0x000c, 0x32b: 0x000c, 0x32c: 0x000c, 0x32d: 0x000c, 0x32e: 0x000c, 0x32f: 0x000c, + 0x330: 0x000c, 0x331: 0x000c, 0x332: 0x000c, 0x333: 0x000c, 0x334: 0x000c, 0x335: 0x000c, + 0x336: 0x000c, 0x337: 0x000c, 0x338: 0x000c, 0x339: 0x000c, 0x33a: 0x000c, 0x33b: 0x000c, + 0x33c: 0x000c, 0x33d: 0x000c, 0x33e: 0x0001, 0x33f: 0x000c, + // Block 0xd, offset 0x340 + 0x340: 0x0001, 0x341: 0x000c, 0x342: 0x000c, 0x343: 0x0001, 0x344: 0x000c, 0x345: 0x000c, + 0x346: 0x0001, 0x347: 0x000c, 0x348: 0x0001, 0x349: 0x0001, 0x34a: 0x0001, 0x34b: 0x0001, + 0x34c: 0x0001, 0x34d: 0x0001, 0x34e: 0x0001, 0x34f: 0x0001, 0x350: 0x0001, 0x351: 0x0001, + 0x352: 0x0001, 0x353: 0x0001, 0x354: 0x0001, 0x355: 0x0001, 0x356: 0x0001, 0x357: 0x0001, + 0x358: 0x0001, 0x359: 0x0001, 0x35a: 0x0001, 0x35b: 0x0001, 0x35c: 0x0001, 0x35d: 0x0001, + 0x35e: 0x0001, 0x35f: 0x0001, 0x360: 0x0001, 0x361: 0x0001, 0x362: 0x0001, 0x363: 0x0001, + 0x364: 0x0001, 0x365: 0x0001, 0x366: 0x0001, 0x367: 0x0001, 0x368: 0x0001, 0x369: 0x0001, + 0x36a: 0x0001, 0x36b: 0x0001, 0x36c: 0x0001, 0x36d: 0x0001, 0x36e: 0x0001, 0x36f: 0x0001, + 0x370: 0x0001, 0x371: 0x0001, 0x372: 0x0001, 0x373: 0x0001, 0x374: 0x0001, 0x375: 0x0001, + 0x376: 0x0001, 0x377: 0x0001, 0x378: 0x0001, 0x379: 0x0001, 0x37a: 0x0001, 0x37b: 0x0001, + 0x37c: 0x0001, 0x37d: 0x0001, 0x37e: 0x0001, 0x37f: 0x0001, + // Block 0xe, offset 0x380 + 0x380: 0x0005, 0x381: 0x0005, 0x382: 0x0005, 0x383: 0x0005, 0x384: 0x0005, 0x385: 0x0005, + 0x386: 0x000a, 0x387: 0x000a, 0x388: 0x000d, 0x389: 0x0004, 0x38a: 0x0004, 0x38b: 0x000d, + 0x38c: 0x0006, 0x38d: 0x000d, 0x38e: 0x000a, 0x38f: 0x000a, 0x390: 0x000c, 0x391: 0x000c, + 0x392: 0x000c, 0x393: 0x000c, 0x394: 0x000c, 0x395: 0x000c, 0x396: 0x000c, 0x397: 0x000c, + 0x398: 0x000c, 0x399: 0x000c, 0x39a: 0x000c, 0x39b: 0x000d, 0x39c: 0x000d, 0x39d: 0x000d, + 0x39e: 0x000d, 0x39f: 0x000d, 0x3a0: 0x000d, 0x3a1: 0x000d, 0x3a2: 0x000d, 0x3a3: 0x000d, + 0x3a4: 0x000d, 0x3a5: 0x000d, 0x3a6: 0x000d, 0x3a7: 0x000d, 0x3a8: 0x000d, 0x3a9: 0x000d, + 0x3aa: 0x000d, 0x3ab: 0x000d, 0x3ac: 0x000d, 0x3ad: 0x000d, 0x3ae: 0x000d, 0x3af: 0x000d, + 0x3b0: 0x000d, 0x3b1: 0x000d, 0x3b2: 0x000d, 0x3b3: 0x000d, 0x3b4: 0x000d, 0x3b5: 0x000d, + 0x3b6: 0x000d, 0x3b7: 0x000d, 0x3b8: 0x000d, 0x3b9: 0x000d, 0x3ba: 0x000d, 0x3bb: 0x000d, + 0x3bc: 0x000d, 0x3bd: 0x000d, 0x3be: 0x000d, 0x3bf: 0x000d, + // Block 0xf, offset 0x3c0 + 0x3c0: 0x000d, 0x3c1: 0x000d, 0x3c2: 0x000d, 0x3c3: 0x000d, 0x3c4: 0x000d, 0x3c5: 0x000d, + 0x3c6: 0x000d, 0x3c7: 0x000d, 0x3c8: 0x000d, 0x3c9: 0x000d, 0x3ca: 0x000d, 0x3cb: 0x000c, + 0x3cc: 0x000c, 0x3cd: 0x000c, 0x3ce: 0x000c, 0x3cf: 0x000c, 0x3d0: 0x000c, 0x3d1: 0x000c, + 0x3d2: 0x000c, 0x3d3: 0x000c, 0x3d4: 0x000c, 0x3d5: 0x000c, 0x3d6: 0x000c, 0x3d7: 0x000c, + 0x3d8: 0x000c, 0x3d9: 0x000c, 0x3da: 0x000c, 0x3db: 0x000c, 0x3dc: 0x000c, 0x3dd: 0x000c, + 0x3de: 0x000c, 0x3df: 0x000c, 0x3e0: 0x0005, 0x3e1: 0x0005, 0x3e2: 0x0005, 0x3e3: 0x0005, + 0x3e4: 0x0005, 0x3e5: 0x0005, 0x3e6: 0x0005, 0x3e7: 0x0005, 0x3e8: 0x0005, 0x3e9: 0x0005, + 0x3ea: 0x0004, 0x3eb: 0x0005, 0x3ec: 0x0005, 0x3ed: 0x000d, 0x3ee: 0x000d, 0x3ef: 0x000d, + 0x3f0: 0x000c, 0x3f1: 0x000d, 0x3f2: 0x000d, 0x3f3: 0x000d, 0x3f4: 0x000d, 0x3f5: 0x000d, + 0x3f6: 0x000d, 0x3f7: 0x000d, 0x3f8: 0x000d, 0x3f9: 0x000d, 0x3fa: 0x000d, 0x3fb: 0x000d, + 0x3fc: 0x000d, 0x3fd: 0x000d, 0x3fe: 0x000d, 0x3ff: 0x000d, + // Block 0x10, offset 0x400 + 0x400: 0x000d, 0x401: 0x000d, 0x402: 0x000d, 0x403: 0x000d, 0x404: 0x000d, 0x405: 0x000d, + 0x406: 0x000d, 0x407: 0x000d, 0x408: 0x000d, 0x409: 0x000d, 0x40a: 0x000d, 0x40b: 0x000d, + 0x40c: 0x000d, 0x40d: 0x000d, 0x40e: 0x000d, 0x40f: 0x000d, 0x410: 0x000d, 0x411: 0x000d, + 0x412: 0x000d, 0x413: 0x000d, 0x414: 0x000d, 0x415: 0x000d, 0x416: 0x000d, 0x417: 0x000d, + 0x418: 0x000d, 0x419: 0x000d, 0x41a: 0x000d, 0x41b: 0x000d, 0x41c: 0x000d, 0x41d: 0x000d, + 0x41e: 0x000d, 0x41f: 0x000d, 0x420: 0x000d, 0x421: 0x000d, 0x422: 0x000d, 0x423: 0x000d, + 0x424: 0x000d, 0x425: 0x000d, 0x426: 0x000d, 0x427: 0x000d, 0x428: 0x000d, 0x429: 0x000d, + 0x42a: 0x000d, 0x42b: 0x000d, 0x42c: 0x000d, 0x42d: 0x000d, 0x42e: 0x000d, 0x42f: 0x000d, + 0x430: 0x000d, 0x431: 0x000d, 0x432: 0x000d, 0x433: 0x000d, 0x434: 0x000d, 0x435: 0x000d, + 0x436: 0x000d, 0x437: 0x000d, 0x438: 0x000d, 0x439: 0x000d, 0x43a: 0x000d, 0x43b: 0x000d, + 0x43c: 0x000d, 0x43d: 0x000d, 0x43e: 0x000d, 0x43f: 0x000d, + // Block 0x11, offset 0x440 + 0x440: 0x000d, 0x441: 0x000d, 0x442: 0x000d, 0x443: 0x000d, 0x444: 0x000d, 0x445: 0x000d, + 0x446: 0x000d, 0x447: 0x000d, 0x448: 0x000d, 0x449: 0x000d, 0x44a: 0x000d, 0x44b: 0x000d, + 0x44c: 0x000d, 0x44d: 0x000d, 0x44e: 0x000d, 0x44f: 0x000d, 0x450: 0x000d, 0x451: 0x000d, + 0x452: 0x000d, 0x453: 0x000d, 0x454: 0x000d, 0x455: 0x000d, 0x456: 0x000c, 0x457: 0x000c, + 0x458: 0x000c, 0x459: 0x000c, 0x45a: 0x000c, 0x45b: 0x000c, 0x45c: 0x000c, 0x45d: 0x0005, + 0x45e: 0x000a, 0x45f: 0x000c, 0x460: 0x000c, 0x461: 0x000c, 0x462: 0x000c, 0x463: 0x000c, + 0x464: 0x000c, 0x465: 0x000d, 0x466: 0x000d, 0x467: 0x000c, 0x468: 0x000c, 0x469: 0x000a, + 0x46a: 0x000c, 0x46b: 0x000c, 0x46c: 0x000c, 0x46d: 0x000c, 0x46e: 0x000d, 0x46f: 0x000d, + 0x470: 0x0002, 0x471: 0x0002, 0x472: 0x0002, 0x473: 0x0002, 0x474: 0x0002, 0x475: 0x0002, + 0x476: 0x0002, 0x477: 0x0002, 0x478: 0x0002, 0x479: 0x0002, 0x47a: 0x000d, 0x47b: 0x000d, + 0x47c: 0x000d, 0x47d: 0x000d, 0x47e: 0x000d, 0x47f: 0x000d, + // Block 0x12, offset 0x480 + 0x480: 0x000d, 0x481: 0x000d, 0x482: 0x000d, 0x483: 0x000d, 0x484: 0x000d, 0x485: 0x000d, + 0x486: 0x000d, 0x487: 0x000d, 0x488: 0x000d, 0x489: 0x000d, 0x48a: 0x000d, 0x48b: 0x000d, + 0x48c: 0x000d, 0x48d: 0x000d, 0x48e: 0x000d, 0x48f: 0x000d, 0x490: 0x000d, 0x491: 0x000c, + 0x492: 0x000d, 0x493: 0x000d, 0x494: 0x000d, 0x495: 0x000d, 0x496: 0x000d, 0x497: 0x000d, + 0x498: 0x000d, 0x499: 0x000d, 0x49a: 0x000d, 0x49b: 0x000d, 0x49c: 0x000d, 0x49d: 0x000d, + 0x49e: 0x000d, 0x49f: 0x000d, 0x4a0: 0x000d, 0x4a1: 0x000d, 0x4a2: 0x000d, 0x4a3: 0x000d, + 0x4a4: 0x000d, 0x4a5: 0x000d, 0x4a6: 0x000d, 0x4a7: 0x000d, 0x4a8: 0x000d, 0x4a9: 0x000d, + 0x4aa: 0x000d, 0x4ab: 0x000d, 0x4ac: 0x000d, 0x4ad: 0x000d, 0x4ae: 0x000d, 0x4af: 0x000d, + 0x4b0: 0x000c, 0x4b1: 0x000c, 0x4b2: 0x000c, 0x4b3: 0x000c, 0x4b4: 0x000c, 0x4b5: 0x000c, + 0x4b6: 0x000c, 0x4b7: 0x000c, 0x4b8: 0x000c, 0x4b9: 0x000c, 0x4ba: 0x000c, 0x4bb: 0x000c, + 0x4bc: 0x000c, 0x4bd: 0x000c, 0x4be: 0x000c, 0x4bf: 0x000c, + // Block 0x13, offset 0x4c0 + 0x4c0: 0x000c, 0x4c1: 0x000c, 0x4c2: 0x000c, 0x4c3: 0x000c, 0x4c4: 0x000c, 0x4c5: 0x000c, + 0x4c6: 0x000c, 0x4c7: 0x000c, 0x4c8: 0x000c, 0x4c9: 0x000c, 0x4ca: 0x000c, 0x4cb: 0x000d, + 0x4cc: 0x000d, 0x4cd: 0x000d, 0x4ce: 0x000d, 0x4cf: 0x000d, 0x4d0: 0x000d, 0x4d1: 0x000d, + 0x4d2: 0x000d, 0x4d3: 0x000d, 0x4d4: 0x000d, 0x4d5: 0x000d, 0x4d6: 0x000d, 0x4d7: 0x000d, + 0x4d8: 0x000d, 0x4d9: 0x000d, 0x4da: 0x000d, 0x4db: 0x000d, 0x4dc: 0x000d, 0x4dd: 0x000d, + 0x4de: 0x000d, 0x4df: 0x000d, 0x4e0: 0x000d, 0x4e1: 0x000d, 0x4e2: 0x000d, 0x4e3: 0x000d, + 0x4e4: 0x000d, 0x4e5: 0x000d, 0x4e6: 0x000d, 0x4e7: 0x000d, 0x4e8: 0x000d, 0x4e9: 0x000d, + 0x4ea: 0x000d, 0x4eb: 0x000d, 0x4ec: 0x000d, 0x4ed: 0x000d, 0x4ee: 0x000d, 0x4ef: 0x000d, + 0x4f0: 0x000d, 0x4f1: 0x000d, 0x4f2: 0x000d, 0x4f3: 0x000d, 0x4f4: 0x000d, 0x4f5: 0x000d, + 0x4f6: 0x000d, 0x4f7: 0x000d, 0x4f8: 0x000d, 0x4f9: 0x000d, 0x4fa: 0x000d, 0x4fb: 0x000d, + 0x4fc: 0x000d, 0x4fd: 0x000d, 0x4fe: 0x000d, 0x4ff: 0x000d, + // Block 0x14, offset 0x500 + 0x500: 0x000d, 0x501: 0x000d, 0x502: 0x000d, 0x503: 0x000d, 0x504: 0x000d, 0x505: 0x000d, + 0x506: 0x000d, 0x507: 0x000d, 0x508: 0x000d, 0x509: 0x000d, 0x50a: 0x000d, 0x50b: 0x000d, + 0x50c: 0x000d, 0x50d: 0x000d, 0x50e: 0x000d, 0x50f: 0x000d, 0x510: 0x000d, 0x511: 0x000d, + 0x512: 0x000d, 0x513: 0x000d, 0x514: 0x000d, 0x515: 0x000d, 0x516: 0x000d, 0x517: 0x000d, + 0x518: 0x000d, 0x519: 0x000d, 0x51a: 0x000d, 0x51b: 0x000d, 0x51c: 0x000d, 0x51d: 0x000d, + 0x51e: 0x000d, 0x51f: 0x000d, 0x520: 0x000d, 0x521: 0x000d, 0x522: 0x000d, 0x523: 0x000d, + 0x524: 0x000d, 0x525: 0x000d, 0x526: 0x000c, 0x527: 0x000c, 0x528: 0x000c, 0x529: 0x000c, + 0x52a: 0x000c, 0x52b: 0x000c, 0x52c: 0x000c, 0x52d: 0x000c, 0x52e: 0x000c, 0x52f: 0x000c, + 0x530: 0x000c, 0x531: 0x000d, 0x532: 0x000d, 0x533: 0x000d, 0x534: 0x000d, 0x535: 0x000d, + 0x536: 0x000d, 0x537: 0x000d, 0x538: 0x000d, 0x539: 0x000d, 0x53a: 0x000d, 0x53b: 0x000d, + 0x53c: 0x000d, 0x53d: 0x000d, 0x53e: 0x000d, 0x53f: 0x000d, + // Block 0x15, offset 0x540 + 0x540: 0x0001, 0x541: 0x0001, 0x542: 0x0001, 0x543: 0x0001, 0x544: 0x0001, 0x545: 0x0001, + 0x546: 0x0001, 0x547: 0x0001, 0x548: 0x0001, 0x549: 0x0001, 0x54a: 0x0001, 0x54b: 0x0001, + 0x54c: 0x0001, 0x54d: 0x0001, 0x54e: 0x0001, 0x54f: 0x0001, 0x550: 0x0001, 0x551: 0x0001, + 0x552: 0x0001, 0x553: 0x0001, 0x554: 0x0001, 0x555: 0x0001, 0x556: 0x0001, 0x557: 0x0001, + 0x558: 0x0001, 0x559: 0x0001, 0x55a: 0x0001, 0x55b: 0x0001, 0x55c: 0x0001, 0x55d: 0x0001, + 0x55e: 0x0001, 0x55f: 0x0001, 0x560: 0x0001, 0x561: 0x0001, 0x562: 0x0001, 0x563: 0x0001, + 0x564: 0x0001, 0x565: 0x0001, 0x566: 0x0001, 0x567: 0x0001, 0x568: 0x0001, 0x569: 0x0001, + 0x56a: 0x0001, 0x56b: 0x000c, 0x56c: 0x000c, 0x56d: 0x000c, 0x56e: 0x000c, 0x56f: 0x000c, + 0x570: 0x000c, 0x571: 0x000c, 0x572: 0x000c, 0x573: 0x000c, 0x574: 0x0001, 0x575: 0x0001, + 0x576: 0x000a, 0x577: 0x000a, 0x578: 0x000a, 0x579: 0x000a, 0x57a: 0x0001, 0x57b: 0x0001, + 0x57c: 0x0001, 0x57d: 0x000c, 0x57e: 0x0001, 0x57f: 0x0001, + // Block 0x16, offset 0x580 + 0x580: 0x0001, 0x581: 0x0001, 0x582: 0x0001, 0x583: 0x0001, 0x584: 0x0001, 0x585: 0x0001, + 0x586: 0x0001, 0x587: 0x0001, 0x588: 0x0001, 0x589: 0x0001, 0x58a: 0x0001, 0x58b: 0x0001, + 0x58c: 0x0001, 0x58d: 0x0001, 0x58e: 0x0001, 0x58f: 0x0001, 0x590: 0x0001, 0x591: 0x0001, + 0x592: 0x0001, 0x593: 0x0001, 0x594: 0x0001, 0x595: 0x0001, 0x596: 0x000c, 0x597: 0x000c, + 0x598: 0x000c, 0x599: 0x000c, 0x59a: 0x0001, 0x59b: 0x000c, 0x59c: 0x000c, 0x59d: 0x000c, + 0x59e: 0x000c, 0x59f: 0x000c, 0x5a0: 0x000c, 0x5a1: 0x000c, 0x5a2: 0x000c, 0x5a3: 0x000c, + 0x5a4: 0x0001, 0x5a5: 0x000c, 0x5a6: 0x000c, 0x5a7: 0x000c, 0x5a8: 0x0001, 0x5a9: 0x000c, + 0x5aa: 0x000c, 0x5ab: 0x000c, 0x5ac: 0x000c, 0x5ad: 0x000c, 0x5ae: 0x0001, 0x5af: 0x0001, + 0x5b0: 0x0001, 0x5b1: 0x0001, 0x5b2: 0x0001, 0x5b3: 0x0001, 0x5b4: 0x0001, 0x5b5: 0x0001, + 0x5b6: 0x0001, 0x5b7: 0x0001, 0x5b8: 0x0001, 0x5b9: 0x0001, 0x5ba: 0x0001, 0x5bb: 0x0001, + 0x5bc: 0x0001, 0x5bd: 0x0001, 0x5be: 0x0001, 0x5bf: 0x0001, + // Block 0x17, offset 0x5c0 + 0x5c0: 0x0001, 0x5c1: 0x0001, 0x5c2: 0x0001, 0x5c3: 0x0001, 0x5c4: 0x0001, 0x5c5: 0x0001, + 0x5c6: 0x0001, 0x5c7: 0x0001, 0x5c8: 0x0001, 0x5c9: 0x0001, 0x5ca: 0x0001, 0x5cb: 0x0001, + 0x5cc: 0x0001, 0x5cd: 0x0001, 0x5ce: 0x0001, 0x5cf: 0x0001, 0x5d0: 0x0001, 0x5d1: 0x0001, + 0x5d2: 0x0001, 0x5d3: 0x0001, 0x5d4: 0x0001, 0x5d5: 0x0001, 0x5d6: 0x0001, 0x5d7: 0x0001, + 0x5d8: 0x0001, 0x5d9: 0x000c, 0x5da: 0x000c, 0x5db: 0x000c, 0x5dc: 0x0001, 0x5dd: 0x0001, + 0x5de: 0x0001, 0x5df: 0x0001, 0x5e0: 0x000d, 0x5e1: 0x000d, 0x5e2: 0x000d, 0x5e3: 0x000d, + 0x5e4: 0x000d, 0x5e5: 0x000d, 0x5e6: 0x000d, 0x5e7: 0x000d, 0x5e8: 0x000d, 0x5e9: 0x000d, + 0x5ea: 0x000d, 0x5eb: 0x000d, 0x5ec: 0x000d, 0x5ed: 0x000d, 0x5ee: 0x000d, 0x5ef: 0x000d, + 0x5f0: 0x0001, 0x5f1: 0x0001, 0x5f2: 0x0001, 0x5f3: 0x0001, 0x5f4: 0x0001, 0x5f5: 0x0001, + 0x5f6: 0x0001, 0x5f7: 0x0001, 0x5f8: 0x0001, 0x5f9: 0x0001, 0x5fa: 0x0001, 0x5fb: 0x0001, + 0x5fc: 0x0001, 0x5fd: 0x0001, 0x5fe: 0x0001, 0x5ff: 0x0001, + // Block 0x18, offset 0x600 + 0x600: 0x0001, 0x601: 0x0001, 0x602: 0x0001, 0x603: 0x0001, 0x604: 0x0001, 0x605: 0x0001, + 0x606: 0x0001, 0x607: 0x0001, 0x608: 0x0001, 0x609: 0x0001, 0x60a: 0x0001, 0x60b: 0x0001, + 0x60c: 0x0001, 0x60d: 0x0001, 0x60e: 0x0001, 0x60f: 0x0001, 0x610: 0x0001, 0x611: 0x0001, + 0x612: 0x0001, 0x613: 0x0001, 0x614: 0x0001, 0x615: 0x0001, 0x616: 0x0001, 0x617: 0x0001, + 0x618: 0x0001, 0x619: 0x0001, 0x61a: 0x0001, 0x61b: 0x0001, 0x61c: 0x0001, 0x61d: 0x0001, + 0x61e: 0x0001, 0x61f: 0x0001, 0x620: 0x000d, 0x621: 0x000d, 0x622: 0x000d, 0x623: 0x000d, + 0x624: 0x000d, 0x625: 0x000d, 0x626: 0x000d, 0x627: 0x000d, 0x628: 0x000d, 0x629: 0x000d, + 0x62a: 0x000d, 0x62b: 0x000d, 0x62c: 0x000d, 0x62d: 0x000d, 0x62e: 0x000d, 0x62f: 0x000d, + 0x630: 0x000d, 0x631: 0x000d, 0x632: 0x000d, 0x633: 0x000d, 0x634: 0x000d, 0x635: 0x000d, + 0x636: 0x000d, 0x637: 0x000d, 0x638: 0x000d, 0x639: 0x000d, 0x63a: 0x000d, 0x63b: 0x000d, + 0x63c: 0x000d, 0x63d: 0x000d, 0x63e: 0x000d, 0x63f: 0x000d, + // Block 0x19, offset 0x640 + 0x640: 0x000d, 0x641: 0x000d, 0x642: 0x000d, 0x643: 0x000d, 0x644: 0x000d, 0x645: 0x000d, + 0x646: 0x000d, 0x647: 0x000d, 0x648: 0x000d, 0x649: 0x000d, 0x64a: 0x000d, 0x64b: 0x000d, + 0x64c: 0x000d, 0x64d: 0x000d, 0x64e: 0x000d, 0x64f: 0x000d, 0x650: 0x000d, 0x651: 0x000d, + 0x652: 0x000d, 0x653: 0x000c, 0x654: 0x000c, 0x655: 0x000c, 0x656: 0x000c, 0x657: 0x000c, + 0x658: 0x000c, 0x659: 0x000c, 0x65a: 0x000c, 0x65b: 0x000c, 0x65c: 0x000c, 0x65d: 0x000c, + 0x65e: 0x000c, 0x65f: 0x000c, 0x660: 0x000c, 0x661: 0x000c, 0x662: 0x0005, 0x663: 0x000c, + 0x664: 0x000c, 0x665: 0x000c, 0x666: 0x000c, 0x667: 0x000c, 0x668: 0x000c, 0x669: 0x000c, + 0x66a: 0x000c, 0x66b: 0x000c, 0x66c: 0x000c, 0x66d: 0x000c, 0x66e: 0x000c, 0x66f: 0x000c, + 0x670: 0x000c, 0x671: 0x000c, 0x672: 0x000c, 0x673: 0x000c, 0x674: 0x000c, 0x675: 0x000c, + 0x676: 0x000c, 0x677: 0x000c, 0x678: 0x000c, 0x679: 0x000c, 0x67a: 0x000c, 0x67b: 0x000c, + 0x67c: 0x000c, 0x67d: 0x000c, 0x67e: 0x000c, 0x67f: 0x000c, + // Block 0x1a, offset 0x680 + 0x680: 0x000c, 0x681: 0x000c, 0x682: 0x000c, + 0x6ba: 0x000c, + 0x6bc: 0x000c, + // Block 0x1b, offset 0x6c0 + 0x6c1: 0x000c, 0x6c2: 0x000c, 0x6c3: 0x000c, 0x6c4: 0x000c, 0x6c5: 0x000c, + 0x6c6: 0x000c, 0x6c7: 0x000c, 0x6c8: 0x000c, + 0x6cd: 0x000c, 0x6d1: 0x000c, + 0x6d2: 0x000c, 0x6d3: 0x000c, 0x6d4: 0x000c, 0x6d5: 0x000c, 0x6d6: 0x000c, 0x6d7: 0x000c, + 0x6e2: 0x000c, 0x6e3: 0x000c, + // Block 0x1c, offset 0x700 + 0x701: 0x000c, + 0x73c: 0x000c, + // Block 0x1d, offset 0x740 + 0x741: 0x000c, 0x742: 0x000c, 0x743: 0x000c, 0x744: 0x000c, + 0x74d: 0x000c, + 0x762: 0x000c, 0x763: 0x000c, + 0x772: 0x0004, 0x773: 0x0004, + 0x77b: 0x0004, + 0x77e: 0x000c, + // Block 0x1e, offset 0x780 + 0x781: 0x000c, 0x782: 0x000c, + 0x7bc: 0x000c, + // Block 0x1f, offset 0x7c0 + 0x7c1: 0x000c, 0x7c2: 0x000c, + 0x7c7: 0x000c, 0x7c8: 0x000c, 0x7cb: 0x000c, + 0x7cc: 0x000c, 0x7cd: 0x000c, 0x7d1: 0x000c, + 0x7f0: 0x000c, 0x7f1: 0x000c, 0x7f5: 0x000c, + // Block 0x20, offset 0x800 + 0x801: 0x000c, 0x802: 0x000c, 0x803: 0x000c, 0x804: 0x000c, 0x805: 0x000c, + 0x807: 0x000c, 0x808: 0x000c, + 0x80d: 0x000c, + 0x822: 0x000c, 0x823: 0x000c, + 0x831: 0x0004, + 0x83a: 0x000c, 0x83b: 0x000c, + 0x83c: 0x000c, 0x83d: 0x000c, 0x83e: 0x000c, 0x83f: 0x000c, + // Block 0x21, offset 0x840 + 0x841: 0x000c, + 0x87c: 0x000c, 0x87f: 0x000c, + // Block 0x22, offset 0x880 + 0x881: 0x000c, 0x882: 0x000c, 0x883: 0x000c, 0x884: 0x000c, + 0x88d: 0x000c, + 0x896: 0x000c, + 0x8a2: 0x000c, 0x8a3: 0x000c, + // Block 0x23, offset 0x8c0 + 0x8c2: 0x000c, + // Block 0x24, offset 0x900 + 0x900: 0x000c, + 0x90d: 0x000c, + 0x933: 0x000a, 0x934: 0x000a, 0x935: 0x000a, + 0x936: 0x000a, 0x937: 0x000a, 0x938: 0x000a, 0x939: 0x0004, 0x93a: 0x000a, + // Block 0x25, offset 0x940 + 0x940: 0x000c, 0x944: 0x000c, + 0x97e: 0x000c, 0x97f: 0x000c, + // Block 0x26, offset 0x980 + 0x980: 0x000c, + 0x986: 0x000c, 0x987: 0x000c, 0x988: 0x000c, 0x98a: 0x000c, 0x98b: 0x000c, + 0x98c: 0x000c, 0x98d: 0x000c, + 0x995: 0x000c, 0x996: 0x000c, + 0x9a2: 0x000c, 0x9a3: 0x000c, + 0x9b8: 0x000a, 0x9b9: 0x000a, 0x9ba: 0x000a, 0x9bb: 0x000a, + 0x9bc: 0x000a, 0x9bd: 0x000a, 0x9be: 0x000a, + // Block 0x27, offset 0x9c0 + 0x9cc: 0x000c, 0x9cd: 0x000c, + 0x9e2: 0x000c, 0x9e3: 0x000c, + // Block 0x28, offset 0xa00 + 0xa00: 0x000c, 0xa01: 0x000c, + 0xa3b: 0x000c, + 0xa3c: 0x000c, + // Block 0x29, offset 0xa40 + 0xa41: 0x000c, 0xa42: 0x000c, 0xa43: 0x000c, 0xa44: 0x000c, + 0xa4d: 0x000c, + 0xa62: 0x000c, 0xa63: 0x000c, + // Block 0x2a, offset 0xa80 + 0xa8a: 0x000c, + 0xa92: 0x000c, 0xa93: 0x000c, 0xa94: 0x000c, 0xa96: 0x000c, + // Block 0x2b, offset 0xac0 + 0xaf1: 0x000c, 0xaf4: 0x000c, 0xaf5: 0x000c, + 0xaf6: 0x000c, 0xaf7: 0x000c, 0xaf8: 0x000c, 0xaf9: 0x000c, 0xafa: 0x000c, + 0xaff: 0x0004, + // Block 0x2c, offset 0xb00 + 0xb07: 0x000c, 0xb08: 0x000c, 0xb09: 0x000c, 0xb0a: 0x000c, 0xb0b: 0x000c, + 0xb0c: 0x000c, 0xb0d: 0x000c, 0xb0e: 0x000c, + // Block 0x2d, offset 0xb40 + 0xb71: 0x000c, 0xb74: 0x000c, 0xb75: 0x000c, + 0xb76: 0x000c, 0xb77: 0x000c, 0xb78: 0x000c, 0xb79: 0x000c, 0xb7a: 0x000c, 0xb7b: 0x000c, + 0xb7c: 0x000c, + // Block 0x2e, offset 0xb80 + 0xb88: 0x000c, 0xb89: 0x000c, 0xb8a: 0x000c, 0xb8b: 0x000c, + 0xb8c: 0x000c, 0xb8d: 0x000c, + // Block 0x2f, offset 0xbc0 + 0xbd8: 0x000c, 0xbd9: 0x000c, + 0xbf5: 0x000c, + 0xbf7: 0x000c, 0xbf9: 0x000c, 0xbfa: 0x003a, 0xbfb: 0x002a, + 0xbfc: 0x003a, 0xbfd: 0x002a, + // Block 0x30, offset 0xc00 + 0xc31: 0x000c, 0xc32: 0x000c, 0xc33: 0x000c, 0xc34: 0x000c, 0xc35: 0x000c, + 0xc36: 0x000c, 0xc37: 0x000c, 0xc38: 0x000c, 0xc39: 0x000c, 0xc3a: 0x000c, 0xc3b: 0x000c, + 0xc3c: 0x000c, 0xc3d: 0x000c, 0xc3e: 0x000c, + // Block 0x31, offset 0xc40 + 0xc40: 0x000c, 0xc41: 0x000c, 0xc42: 0x000c, 0xc43: 0x000c, 0xc44: 0x000c, + 0xc46: 0x000c, 0xc47: 0x000c, + 0xc4d: 0x000c, 0xc4e: 0x000c, 0xc4f: 0x000c, 0xc50: 0x000c, 0xc51: 0x000c, + 0xc52: 0x000c, 0xc53: 0x000c, 0xc54: 0x000c, 0xc55: 0x000c, 0xc56: 0x000c, 0xc57: 0x000c, + 0xc59: 0x000c, 0xc5a: 0x000c, 0xc5b: 0x000c, 0xc5c: 0x000c, 0xc5d: 0x000c, + 0xc5e: 0x000c, 0xc5f: 0x000c, 0xc60: 0x000c, 0xc61: 0x000c, 0xc62: 0x000c, 0xc63: 0x000c, + 0xc64: 0x000c, 0xc65: 0x000c, 0xc66: 0x000c, 0xc67: 0x000c, 0xc68: 0x000c, 0xc69: 0x000c, + 0xc6a: 0x000c, 0xc6b: 0x000c, 0xc6c: 0x000c, 0xc6d: 0x000c, 0xc6e: 0x000c, 0xc6f: 0x000c, + 0xc70: 0x000c, 0xc71: 0x000c, 0xc72: 0x000c, 0xc73: 0x000c, 0xc74: 0x000c, 0xc75: 0x000c, + 0xc76: 0x000c, 0xc77: 0x000c, 0xc78: 0x000c, 0xc79: 0x000c, 0xc7a: 0x000c, 0xc7b: 0x000c, + 0xc7c: 0x000c, + // Block 0x32, offset 0xc80 + 0xc86: 0x000c, + // Block 0x33, offset 0xcc0 + 0xced: 0x000c, 0xcee: 0x000c, 0xcef: 0x000c, + 0xcf0: 0x000c, 0xcf2: 0x000c, 0xcf3: 0x000c, 0xcf4: 0x000c, 0xcf5: 0x000c, + 0xcf6: 0x000c, 0xcf7: 0x000c, 0xcf9: 0x000c, 0xcfa: 0x000c, + 0xcfd: 0x000c, 0xcfe: 0x000c, + // Block 0x34, offset 0xd00 + 0xd18: 0x000c, 0xd19: 0x000c, + 0xd1e: 0x000c, 0xd1f: 0x000c, 0xd20: 0x000c, + 0xd31: 0x000c, 0xd32: 0x000c, 0xd33: 0x000c, 0xd34: 0x000c, + // Block 0x35, offset 0xd40 + 0xd42: 0x000c, 0xd45: 0x000c, + 0xd46: 0x000c, + 0xd4d: 0x000c, + 0xd5d: 0x000c, + // Block 0x36, offset 0xd80 + 0xd9d: 0x000c, + 0xd9e: 0x000c, 0xd9f: 0x000c, + // Block 0x37, offset 0xdc0 + 0xdd0: 0x000a, 0xdd1: 0x000a, + 0xdd2: 0x000a, 0xdd3: 0x000a, 0xdd4: 0x000a, 0xdd5: 0x000a, 0xdd6: 0x000a, 0xdd7: 0x000a, + 0xdd8: 0x000a, 0xdd9: 0x000a, + // Block 0x38, offset 0xe00 + 0xe00: 0x000a, + // Block 0x39, offset 0xe40 + 0xe40: 0x0009, + 0xe5b: 0x007a, 0xe5c: 0x006a, + // Block 0x3a, offset 0xe80 + 0xe92: 0x000c, 0xe93: 0x000c, 0xe94: 0x000c, + 0xeb2: 0x000c, 0xeb3: 0x000c, 0xeb4: 0x000c, + // Block 0x3b, offset 0xec0 + 0xed2: 0x000c, 0xed3: 0x000c, + 0xef2: 0x000c, 0xef3: 0x000c, + // Block 0x3c, offset 0xf00 + 0xf34: 0x000c, 0xf35: 0x000c, + 0xf37: 0x000c, 0xf38: 0x000c, 0xf39: 0x000c, 0xf3a: 0x000c, 0xf3b: 0x000c, + 0xf3c: 0x000c, 0xf3d: 0x000c, + // Block 0x3d, offset 0xf40 + 0xf46: 0x000c, 0xf49: 0x000c, 0xf4a: 0x000c, 0xf4b: 0x000c, + 0xf4c: 0x000c, 0xf4d: 0x000c, 0xf4e: 0x000c, 0xf4f: 0x000c, 0xf50: 0x000c, 0xf51: 0x000c, + 0xf52: 0x000c, 0xf53: 0x000c, + 0xf5b: 0x0004, 0xf5d: 0x000c, + 0xf70: 0x000a, 0xf71: 0x000a, 0xf72: 0x000a, 0xf73: 0x000a, 0xf74: 0x000a, 0xf75: 0x000a, + 0xf76: 0x000a, 0xf77: 0x000a, 0xf78: 0x000a, 0xf79: 0x000a, + // Block 0x3e, offset 0xf80 + 0xf80: 0x000a, 0xf81: 0x000a, 0xf82: 0x000a, 0xf83: 0x000a, 0xf84: 0x000a, 0xf85: 0x000a, + 0xf86: 0x000a, 0xf87: 0x000a, 0xf88: 0x000a, 0xf89: 0x000a, 0xf8a: 0x000a, 0xf8b: 0x000c, + 0xf8c: 0x000c, 0xf8d: 0x000c, 0xf8e: 0x000b, + // Block 0x3f, offset 0xfc0 + 0xfc5: 0x000c, + 0xfc6: 0x000c, + 0xfe9: 0x000c, + // Block 0x40, offset 0x1000 + 0x1020: 0x000c, 0x1021: 0x000c, 0x1022: 0x000c, + 0x1027: 0x000c, 0x1028: 0x000c, + 0x1032: 0x000c, + 0x1039: 0x000c, 0x103a: 0x000c, 0x103b: 0x000c, + // Block 0x41, offset 0x1040 + 0x1040: 0x000a, 0x1044: 0x000a, 0x1045: 0x000a, + // Block 0x42, offset 0x1080 + 0x109e: 0x000a, 0x109f: 0x000a, 0x10a0: 0x000a, 0x10a1: 0x000a, 0x10a2: 0x000a, 0x10a3: 0x000a, + 0x10a4: 0x000a, 0x10a5: 0x000a, 0x10a6: 0x000a, 0x10a7: 0x000a, 0x10a8: 0x000a, 0x10a9: 0x000a, + 0x10aa: 0x000a, 0x10ab: 0x000a, 0x10ac: 0x000a, 0x10ad: 0x000a, 0x10ae: 0x000a, 0x10af: 0x000a, + 0x10b0: 0x000a, 0x10b1: 0x000a, 0x10b2: 0x000a, 0x10b3: 0x000a, 0x10b4: 0x000a, 0x10b5: 0x000a, + 0x10b6: 0x000a, 0x10b7: 0x000a, 0x10b8: 0x000a, 0x10b9: 0x000a, 0x10ba: 0x000a, 0x10bb: 0x000a, + 0x10bc: 0x000a, 0x10bd: 0x000a, 0x10be: 0x000a, 0x10bf: 0x000a, + // Block 0x43, offset 0x10c0 + 0x10d7: 0x000c, + 0x10d8: 0x000c, 0x10db: 0x000c, + // Block 0x44, offset 0x1100 + 0x1116: 0x000c, + 0x1118: 0x000c, 0x1119: 0x000c, 0x111a: 0x000c, 0x111b: 0x000c, 0x111c: 0x000c, 0x111d: 0x000c, + 0x111e: 0x000c, 0x1120: 0x000c, 0x1122: 0x000c, + 0x1125: 0x000c, 0x1126: 0x000c, 0x1127: 0x000c, 0x1128: 0x000c, 0x1129: 0x000c, + 0x112a: 0x000c, 0x112b: 0x000c, 0x112c: 0x000c, + 0x1133: 0x000c, 0x1134: 0x000c, 0x1135: 0x000c, + 0x1136: 0x000c, 0x1137: 0x000c, 0x1138: 0x000c, 0x1139: 0x000c, 0x113a: 0x000c, 0x113b: 0x000c, + 0x113c: 0x000c, 0x113f: 0x000c, + // Block 0x45, offset 0x1140 + 0x1170: 0x000c, 0x1171: 0x000c, 0x1172: 0x000c, 0x1173: 0x000c, 0x1174: 0x000c, 0x1175: 0x000c, + 0x1176: 0x000c, 0x1177: 0x000c, 0x1178: 0x000c, 0x1179: 0x000c, 0x117a: 0x000c, 0x117b: 0x000c, + 0x117c: 0x000c, 0x117d: 0x000c, 0x117e: 0x000c, + // Block 0x46, offset 0x1180 + 0x1180: 0x000c, 0x1181: 0x000c, 0x1182: 0x000c, 0x1183: 0x000c, + 0x11b4: 0x000c, + 0x11b6: 0x000c, 0x11b7: 0x000c, 0x11b8: 0x000c, 0x11b9: 0x000c, 0x11ba: 0x000c, + 0x11bc: 0x000c, + // Block 0x47, offset 0x11c0 + 0x11c2: 0x000c, + 0x11eb: 0x000c, 0x11ec: 0x000c, 0x11ed: 0x000c, 0x11ee: 0x000c, 0x11ef: 0x000c, + 0x11f0: 0x000c, 0x11f1: 0x000c, 0x11f2: 0x000c, 0x11f3: 0x000c, + // Block 0x48, offset 0x1200 + 0x1200: 0x000c, 0x1201: 0x000c, + 0x1222: 0x000c, 0x1223: 0x000c, + 0x1224: 0x000c, 0x1225: 0x000c, 0x1228: 0x000c, 0x1229: 0x000c, + 0x122b: 0x000c, 0x122c: 0x000c, 0x122d: 0x000c, + // Block 0x49, offset 0x1240 + 0x1266: 0x000c, 0x1268: 0x000c, 0x1269: 0x000c, + 0x126d: 0x000c, 0x126f: 0x000c, + 0x1270: 0x000c, 0x1271: 0x000c, + // Block 0x4a, offset 0x1280 + 0x12ac: 0x000c, 0x12ad: 0x000c, 0x12ae: 0x000c, 0x12af: 0x000c, + 0x12b0: 0x000c, 0x12b1: 0x000c, 0x12b2: 0x000c, 0x12b3: 0x000c, + 0x12b6: 0x000c, 0x12b7: 0x000c, + // Block 0x4b, offset 0x12c0 + 0x12d0: 0x000c, 0x12d1: 0x000c, + 0x12d2: 0x000c, 0x12d4: 0x000c, 0x12d5: 0x000c, 0x12d6: 0x000c, 0x12d7: 0x000c, + 0x12d8: 0x000c, 0x12d9: 0x000c, 0x12da: 0x000c, 0x12db: 0x000c, 0x12dc: 0x000c, 0x12dd: 0x000c, + 0x12de: 0x000c, 0x12df: 0x000c, 0x12e0: 0x000c, 0x12e2: 0x000c, 0x12e3: 0x000c, + 0x12e4: 0x000c, 0x12e5: 0x000c, 0x12e6: 0x000c, 0x12e7: 0x000c, 0x12e8: 0x000c, + 0x12ed: 0x000c, + 0x12f4: 0x000c, + 0x12f8: 0x000c, 0x12f9: 0x000c, + // Block 0x4c, offset 0x1300 + 0x1300: 0x000c, 0x1301: 0x000c, 0x1302: 0x000c, 0x1303: 0x000c, 0x1304: 0x000c, 0x1305: 0x000c, + 0x1306: 0x000c, 0x1307: 0x000c, 0x1308: 0x000c, 0x1309: 0x000c, 0x130a: 0x000c, 0x130b: 0x000c, + 0x130c: 0x000c, 0x130d: 0x000c, 0x130e: 0x000c, 0x130f: 0x000c, 0x1310: 0x000c, 0x1311: 0x000c, + 0x1312: 0x000c, 0x1313: 0x000c, 0x1314: 0x000c, 0x1315: 0x000c, 0x1316: 0x000c, 0x1317: 0x000c, + 0x1318: 0x000c, 0x1319: 0x000c, 0x131a: 0x000c, 0x131b: 0x000c, 0x131c: 0x000c, 0x131d: 0x000c, + 0x131e: 0x000c, 0x131f: 0x000c, 0x1320: 0x000c, 0x1321: 0x000c, 0x1322: 0x000c, 0x1323: 0x000c, + 0x1324: 0x000c, 0x1325: 0x000c, 0x1326: 0x000c, 0x1327: 0x000c, 0x1328: 0x000c, 0x1329: 0x000c, + 0x132a: 0x000c, 0x132b: 0x000c, 0x132c: 0x000c, 0x132d: 0x000c, 0x132e: 0x000c, 0x132f: 0x000c, + 0x1330: 0x000c, 0x1331: 0x000c, 0x1332: 0x000c, 0x1333: 0x000c, 0x1334: 0x000c, 0x1335: 0x000c, + 0x1336: 0x000c, 0x1337: 0x000c, 0x1338: 0x000c, 0x1339: 0x000c, 0x133b: 0x000c, + 0x133c: 0x000c, 0x133d: 0x000c, 0x133e: 0x000c, 0x133f: 0x000c, + // Block 0x4d, offset 0x1340 + 0x137d: 0x000a, 0x137f: 0x000a, + // Block 0x4e, offset 0x1380 + 0x1380: 0x000a, 0x1381: 0x000a, + 0x138d: 0x000a, 0x138e: 0x000a, 0x138f: 0x000a, + 0x139d: 0x000a, + 0x139e: 0x000a, 0x139f: 0x000a, + 0x13ad: 0x000a, 0x13ae: 0x000a, 0x13af: 0x000a, + 0x13bd: 0x000a, 0x13be: 0x000a, + // Block 0x4f, offset 0x13c0 + 0x13c0: 0x0009, 0x13c1: 0x0009, 0x13c2: 0x0009, 0x13c3: 0x0009, 0x13c4: 0x0009, 0x13c5: 0x0009, + 0x13c6: 0x0009, 0x13c7: 0x0009, 0x13c8: 0x0009, 0x13c9: 0x0009, 0x13ca: 0x0009, 0x13cb: 0x000b, + 0x13cc: 0x000b, 0x13cd: 0x000b, 0x13cf: 0x0001, 0x13d0: 0x000a, 0x13d1: 0x000a, + 0x13d2: 0x000a, 0x13d3: 0x000a, 0x13d4: 0x000a, 0x13d5: 0x000a, 0x13d6: 0x000a, 0x13d7: 0x000a, + 0x13d8: 0x000a, 0x13d9: 0x000a, 0x13da: 0x000a, 0x13db: 0x000a, 0x13dc: 0x000a, 0x13dd: 0x000a, + 0x13de: 0x000a, 0x13df: 0x000a, 0x13e0: 0x000a, 0x13e1: 0x000a, 0x13e2: 0x000a, 0x13e3: 0x000a, + 0x13e4: 0x000a, 0x13e5: 0x000a, 0x13e6: 0x000a, 0x13e7: 0x000a, 0x13e8: 0x0009, 0x13e9: 0x0007, + 0x13ea: 0x000e, 0x13eb: 0x000e, 0x13ec: 0x000e, 0x13ed: 0x000e, 0x13ee: 0x000e, 0x13ef: 0x0006, + 0x13f0: 0x0004, 0x13f1: 0x0004, 0x13f2: 0x0004, 0x13f3: 0x0004, 0x13f4: 0x0004, 0x13f5: 0x000a, + 0x13f6: 0x000a, 0x13f7: 0x000a, 0x13f8: 0x000a, 0x13f9: 0x000a, 0x13fa: 0x000a, 0x13fb: 0x000a, + 0x13fc: 0x000a, 0x13fd: 0x000a, 0x13fe: 0x000a, 0x13ff: 0x000a, + // Block 0x50, offset 0x1400 + 0x1400: 0x000a, 0x1401: 0x000a, 0x1402: 0x000a, 0x1403: 0x000a, 0x1404: 0x0006, 0x1405: 0x009a, + 0x1406: 0x008a, 0x1407: 0x000a, 0x1408: 0x000a, 0x1409: 0x000a, 0x140a: 0x000a, 0x140b: 0x000a, + 0x140c: 0x000a, 0x140d: 0x000a, 0x140e: 0x000a, 0x140f: 0x000a, 0x1410: 0x000a, 0x1411: 0x000a, + 0x1412: 0x000a, 0x1413: 0x000a, 0x1414: 0x000a, 0x1415: 0x000a, 0x1416: 0x000a, 0x1417: 0x000a, + 0x1418: 0x000a, 0x1419: 0x000a, 0x141a: 0x000a, 0x141b: 0x000a, 0x141c: 0x000a, 0x141d: 0x000a, + 0x141e: 0x000a, 0x141f: 0x0009, 0x1420: 0x000b, 0x1421: 0x000b, 0x1422: 0x000b, 0x1423: 0x000b, + 0x1424: 0x000b, 0x1425: 0x000b, 0x1426: 0x000e, 0x1427: 0x000e, 0x1428: 0x000e, 0x1429: 0x000e, + 0x142a: 0x000b, 0x142b: 0x000b, 0x142c: 0x000b, 0x142d: 0x000b, 0x142e: 0x000b, 0x142f: 0x000b, + 0x1430: 0x0002, 0x1434: 0x0002, 0x1435: 0x0002, + 0x1436: 0x0002, 0x1437: 0x0002, 0x1438: 0x0002, 0x1439: 0x0002, 0x143a: 0x0003, 0x143b: 0x0003, + 0x143c: 0x000a, 0x143d: 0x009a, 0x143e: 0x008a, + // Block 0x51, offset 0x1440 + 0x1440: 0x0002, 0x1441: 0x0002, 0x1442: 0x0002, 0x1443: 0x0002, 0x1444: 0x0002, 0x1445: 0x0002, + 0x1446: 0x0002, 0x1447: 0x0002, 0x1448: 0x0002, 0x1449: 0x0002, 0x144a: 0x0003, 0x144b: 0x0003, + 0x144c: 0x000a, 0x144d: 0x009a, 0x144e: 0x008a, + 0x1460: 0x0004, 0x1461: 0x0004, 0x1462: 0x0004, 0x1463: 0x0004, + 0x1464: 0x0004, 0x1465: 0x0004, 0x1466: 0x0004, 0x1467: 0x0004, 0x1468: 0x0004, 0x1469: 0x0004, + 0x146a: 0x0004, 0x146b: 0x0004, 0x146c: 0x0004, 0x146d: 0x0004, 0x146e: 0x0004, 0x146f: 0x0004, + 0x1470: 0x0004, 0x1471: 0x0004, 0x1472: 0x0004, 0x1473: 0x0004, 0x1474: 0x0004, 0x1475: 0x0004, + 0x1476: 0x0004, 0x1477: 0x0004, 0x1478: 0x0004, 0x1479: 0x0004, 0x147a: 0x0004, 0x147b: 0x0004, + 0x147c: 0x0004, 0x147d: 0x0004, 0x147e: 0x0004, 0x147f: 0x0004, + // Block 0x52, offset 0x1480 + 0x1480: 0x0004, 0x1481: 0x0004, 0x1482: 0x0004, 0x1483: 0x0004, 0x1484: 0x0004, 0x1485: 0x0004, + 0x1486: 0x0004, 0x1487: 0x0004, 0x1488: 0x0004, 0x1489: 0x0004, 0x148a: 0x0004, 0x148b: 0x0004, + 0x148c: 0x0004, 0x148d: 0x0004, 0x148e: 0x0004, 0x148f: 0x0004, 0x1490: 0x000c, 0x1491: 0x000c, + 0x1492: 0x000c, 0x1493: 0x000c, 0x1494: 0x000c, 0x1495: 0x000c, 0x1496: 0x000c, 0x1497: 0x000c, + 0x1498: 0x000c, 0x1499: 0x000c, 0x149a: 0x000c, 0x149b: 0x000c, 0x149c: 0x000c, 0x149d: 0x000c, + 0x149e: 0x000c, 0x149f: 0x000c, 0x14a0: 0x000c, 0x14a1: 0x000c, 0x14a2: 0x000c, 0x14a3: 0x000c, + 0x14a4: 0x000c, 0x14a5: 0x000c, 0x14a6: 0x000c, 0x14a7: 0x000c, 0x14a8: 0x000c, 0x14a9: 0x000c, + 0x14aa: 0x000c, 0x14ab: 0x000c, 0x14ac: 0x000c, 0x14ad: 0x000c, 0x14ae: 0x000c, 0x14af: 0x000c, + 0x14b0: 0x000c, + // Block 0x53, offset 0x14c0 + 0x14c0: 0x000a, 0x14c1: 0x000a, 0x14c3: 0x000a, 0x14c4: 0x000a, 0x14c5: 0x000a, + 0x14c6: 0x000a, 0x14c8: 0x000a, 0x14c9: 0x000a, + 0x14d4: 0x000a, 0x14d6: 0x000a, 0x14d7: 0x000a, + 0x14d8: 0x000a, + 0x14de: 0x000a, 0x14df: 0x000a, 0x14e0: 0x000a, 0x14e1: 0x000a, 0x14e2: 0x000a, 0x14e3: 0x000a, + 0x14e5: 0x000a, 0x14e7: 0x000a, 0x14e9: 0x000a, + 0x14ee: 0x0004, + 0x14fa: 0x000a, 0x14fb: 0x000a, + // Block 0x54, offset 0x1500 + 0x1500: 0x000a, 0x1501: 0x000a, 0x1502: 0x000a, 0x1503: 0x000a, 0x1504: 0x000a, + 0x150a: 0x000a, 0x150b: 0x000a, + 0x150c: 0x000a, 0x150d: 0x000a, 0x1510: 0x000a, 0x1511: 0x000a, + 0x1512: 0x000a, 0x1513: 0x000a, 0x1514: 0x000a, 0x1515: 0x000a, 0x1516: 0x000a, 0x1517: 0x000a, + 0x1518: 0x000a, 0x1519: 0x000a, 0x151a: 0x000a, 0x151b: 0x000a, 0x151c: 0x000a, 0x151d: 0x000a, + 0x151e: 0x000a, 0x151f: 0x000a, + // Block 0x55, offset 0x1540 + 0x1549: 0x000a, 0x154a: 0x000a, 0x154b: 0x000a, + 0x1550: 0x000a, 0x1551: 0x000a, + 0x1552: 0x000a, 0x1553: 0x000a, 0x1554: 0x000a, 0x1555: 0x000a, 0x1556: 0x000a, 0x1557: 0x000a, + 0x1558: 0x000a, 0x1559: 0x000a, 0x155a: 0x000a, 0x155b: 0x000a, 0x155c: 0x000a, 0x155d: 0x000a, + 0x155e: 0x000a, 0x155f: 0x000a, 0x1560: 0x000a, 0x1561: 0x000a, 0x1562: 0x000a, 0x1563: 0x000a, + 0x1564: 0x000a, 0x1565: 0x000a, 0x1566: 0x000a, 0x1567: 0x000a, 0x1568: 0x000a, 0x1569: 0x000a, + 0x156a: 0x000a, 0x156b: 0x000a, 0x156c: 0x000a, 0x156d: 0x000a, 0x156e: 0x000a, 0x156f: 0x000a, + 0x1570: 0x000a, 0x1571: 0x000a, 0x1572: 0x000a, 0x1573: 0x000a, 0x1574: 0x000a, 0x1575: 0x000a, + 0x1576: 0x000a, 0x1577: 0x000a, 0x1578: 0x000a, 0x1579: 0x000a, 0x157a: 0x000a, 0x157b: 0x000a, + 0x157c: 0x000a, 0x157d: 0x000a, 0x157e: 0x000a, 0x157f: 0x000a, + // Block 0x56, offset 0x1580 + 0x1580: 0x000a, 0x1581: 0x000a, 0x1582: 0x000a, 0x1583: 0x000a, 0x1584: 0x000a, 0x1585: 0x000a, + 0x1586: 0x000a, 0x1587: 0x000a, 0x1588: 0x000a, 0x1589: 0x000a, 0x158a: 0x000a, 0x158b: 0x000a, + 0x158c: 0x000a, 0x158d: 0x000a, 0x158e: 0x000a, 0x158f: 0x000a, 0x1590: 0x000a, 0x1591: 0x000a, + 0x1592: 0x000a, 0x1593: 0x000a, 0x1594: 0x000a, 0x1595: 0x000a, 0x1596: 0x000a, 0x1597: 0x000a, + 0x1598: 0x000a, 0x1599: 0x000a, 0x159a: 0x000a, 0x159b: 0x000a, 0x159c: 0x000a, 0x159d: 0x000a, + 0x159e: 0x000a, 0x159f: 0x000a, 0x15a0: 0x000a, 0x15a1: 0x000a, 0x15a2: 0x000a, 0x15a3: 0x000a, + 0x15a4: 0x000a, 0x15a5: 0x000a, 0x15a6: 0x000a, 0x15a7: 0x000a, 0x15a8: 0x000a, 0x15a9: 0x000a, + 0x15aa: 0x000a, 0x15ab: 0x000a, 0x15ac: 0x000a, 0x15ad: 0x000a, 0x15ae: 0x000a, 0x15af: 0x000a, + 0x15b0: 0x000a, 0x15b1: 0x000a, 0x15b2: 0x000a, 0x15b3: 0x000a, 0x15b4: 0x000a, 0x15b5: 0x000a, + 0x15b6: 0x000a, 0x15b7: 0x000a, 0x15b8: 0x000a, 0x15b9: 0x000a, 0x15ba: 0x000a, 0x15bb: 0x000a, + 0x15bc: 0x000a, 0x15bd: 0x000a, 0x15be: 0x000a, 0x15bf: 0x000a, + // Block 0x57, offset 0x15c0 + 0x15c0: 0x000a, 0x15c1: 0x000a, 0x15c2: 0x000a, 0x15c3: 0x000a, 0x15c4: 0x000a, 0x15c5: 0x000a, + 0x15c6: 0x000a, 0x15c7: 0x000a, 0x15c8: 0x000a, 0x15c9: 0x000a, 0x15ca: 0x000a, 0x15cb: 0x000a, + 0x15cc: 0x000a, 0x15cd: 0x000a, 0x15ce: 0x000a, 0x15cf: 0x000a, 0x15d0: 0x000a, 0x15d1: 0x000a, + 0x15d2: 0x0003, 0x15d3: 0x0004, 0x15d4: 0x000a, 0x15d5: 0x000a, 0x15d6: 0x000a, 0x15d7: 0x000a, + 0x15d8: 0x000a, 0x15d9: 0x000a, 0x15da: 0x000a, 0x15db: 0x000a, 0x15dc: 0x000a, 0x15dd: 0x000a, + 0x15de: 0x000a, 0x15df: 0x000a, 0x15e0: 0x000a, 0x15e1: 0x000a, 0x15e2: 0x000a, 0x15e3: 0x000a, + 0x15e4: 0x000a, 0x15e5: 0x000a, 0x15e6: 0x000a, 0x15e7: 0x000a, 0x15e8: 0x000a, 0x15e9: 0x000a, + 0x15ea: 0x000a, 0x15eb: 0x000a, 0x15ec: 0x000a, 0x15ed: 0x000a, 0x15ee: 0x000a, 0x15ef: 0x000a, + 0x15f0: 0x000a, 0x15f1: 0x000a, 0x15f2: 0x000a, 0x15f3: 0x000a, 0x15f4: 0x000a, 0x15f5: 0x000a, + 0x15f6: 0x000a, 0x15f7: 0x000a, 0x15f8: 0x000a, 0x15f9: 0x000a, 0x15fa: 0x000a, 0x15fb: 0x000a, + 0x15fc: 0x000a, 0x15fd: 0x000a, 0x15fe: 0x000a, 0x15ff: 0x000a, + // Block 0x58, offset 0x1600 + 0x1600: 0x000a, 0x1601: 0x000a, 0x1602: 0x000a, 0x1603: 0x000a, 0x1604: 0x000a, 0x1605: 0x000a, + 0x1606: 0x000a, 0x1607: 0x000a, 0x1608: 0x003a, 0x1609: 0x002a, 0x160a: 0x003a, 0x160b: 0x002a, + 0x160c: 0x000a, 0x160d: 0x000a, 0x160e: 0x000a, 0x160f: 0x000a, 0x1610: 0x000a, 0x1611: 0x000a, + 0x1612: 0x000a, 0x1613: 0x000a, 0x1614: 0x000a, 0x1615: 0x000a, 0x1616: 0x000a, 0x1617: 0x000a, + 0x1618: 0x000a, 0x1619: 0x000a, 0x161a: 0x000a, 0x161b: 0x000a, 0x161c: 0x000a, 0x161d: 0x000a, + 0x161e: 0x000a, 0x161f: 0x000a, 0x1620: 0x000a, 0x1621: 0x000a, 0x1622: 0x000a, 0x1623: 0x000a, + 0x1624: 0x000a, 0x1625: 0x000a, 0x1626: 0x000a, 0x1627: 0x000a, 0x1628: 0x000a, 0x1629: 0x009a, + 0x162a: 0x008a, 0x162b: 0x000a, 0x162c: 0x000a, 0x162d: 0x000a, 0x162e: 0x000a, 0x162f: 0x000a, + 0x1630: 0x000a, 0x1631: 0x000a, 0x1632: 0x000a, 0x1633: 0x000a, 0x1634: 0x000a, 0x1635: 0x000a, + // Block 0x59, offset 0x1640 + 0x167b: 0x000a, + 0x167c: 0x000a, 0x167d: 0x000a, 0x167e: 0x000a, 0x167f: 0x000a, + // Block 0x5a, offset 0x1680 + 0x1680: 0x000a, 0x1681: 0x000a, 0x1682: 0x000a, 0x1683: 0x000a, 0x1684: 0x000a, 0x1685: 0x000a, + 0x1686: 0x000a, 0x1687: 0x000a, 0x1688: 0x000a, 0x1689: 0x000a, 0x168a: 0x000a, 0x168b: 0x000a, + 0x168c: 0x000a, 0x168d: 0x000a, 0x168e: 0x000a, 0x168f: 0x000a, 0x1690: 0x000a, 0x1691: 0x000a, + 0x1692: 0x000a, 0x1693: 0x000a, 0x1694: 0x000a, 0x1696: 0x000a, 0x1697: 0x000a, + 0x1698: 0x000a, 0x1699: 0x000a, 0x169a: 0x000a, 0x169b: 0x000a, 0x169c: 0x000a, 0x169d: 0x000a, + 0x169e: 0x000a, 0x169f: 0x000a, 0x16a0: 0x000a, 0x16a1: 0x000a, 0x16a2: 0x000a, 0x16a3: 0x000a, + 0x16a4: 0x000a, 0x16a5: 0x000a, 0x16a6: 0x000a, 0x16a7: 0x000a, 0x16a8: 0x000a, 0x16a9: 0x000a, + 0x16aa: 0x000a, 0x16ab: 0x000a, 0x16ac: 0x000a, 0x16ad: 0x000a, 0x16ae: 0x000a, 0x16af: 0x000a, + 0x16b0: 0x000a, 0x16b1: 0x000a, 0x16b2: 0x000a, 0x16b3: 0x000a, 0x16b4: 0x000a, 0x16b5: 0x000a, + 0x16b6: 0x000a, 0x16b7: 0x000a, 0x16b8: 0x000a, 0x16b9: 0x000a, 0x16ba: 0x000a, 0x16bb: 0x000a, + 0x16bc: 0x000a, 0x16bd: 0x000a, 0x16be: 0x000a, 0x16bf: 0x000a, + // Block 0x5b, offset 0x16c0 + 0x16c0: 0x000a, 0x16c1: 0x000a, 0x16c2: 0x000a, 0x16c3: 0x000a, 0x16c4: 0x000a, 0x16c5: 0x000a, + 0x16c6: 0x000a, 0x16c7: 0x000a, 0x16c8: 0x000a, 0x16c9: 0x000a, 0x16ca: 0x000a, 0x16cb: 0x000a, + 0x16cc: 0x000a, 0x16cd: 0x000a, 0x16ce: 0x000a, 0x16cf: 0x000a, 0x16d0: 0x000a, 0x16d1: 0x000a, + 0x16d2: 0x000a, 0x16d3: 0x000a, 0x16d4: 0x000a, 0x16d5: 0x000a, 0x16d6: 0x000a, 0x16d7: 0x000a, + 0x16d8: 0x000a, 0x16d9: 0x000a, 0x16da: 0x000a, 0x16db: 0x000a, 0x16dc: 0x000a, 0x16dd: 0x000a, + 0x16de: 0x000a, 0x16df: 0x000a, 0x16e0: 0x000a, 0x16e1: 0x000a, 0x16e2: 0x000a, 0x16e3: 0x000a, + 0x16e4: 0x000a, 0x16e5: 0x000a, 0x16e6: 0x000a, + // Block 0x5c, offset 0x1700 + 0x1700: 0x000a, 0x1701: 0x000a, 0x1702: 0x000a, 0x1703: 0x000a, 0x1704: 0x000a, 0x1705: 0x000a, + 0x1706: 0x000a, 0x1707: 0x000a, 0x1708: 0x000a, 0x1709: 0x000a, 0x170a: 0x000a, + 0x1720: 0x000a, 0x1721: 0x000a, 0x1722: 0x000a, 0x1723: 0x000a, + 0x1724: 0x000a, 0x1725: 0x000a, 0x1726: 0x000a, 0x1727: 0x000a, 0x1728: 0x000a, 0x1729: 0x000a, + 0x172a: 0x000a, 0x172b: 0x000a, 0x172c: 0x000a, 0x172d: 0x000a, 0x172e: 0x000a, 0x172f: 0x000a, + 0x1730: 0x000a, 0x1731: 0x000a, 0x1732: 0x000a, 0x1733: 0x000a, 0x1734: 0x000a, 0x1735: 0x000a, + 0x1736: 0x000a, 0x1737: 0x000a, 0x1738: 0x000a, 0x1739: 0x000a, 0x173a: 0x000a, 0x173b: 0x000a, + 0x173c: 0x000a, 0x173d: 0x000a, 0x173e: 0x000a, 0x173f: 0x000a, + // Block 0x5d, offset 0x1740 + 0x1740: 0x000a, 0x1741: 0x000a, 0x1742: 0x000a, 0x1743: 0x000a, 0x1744: 0x000a, 0x1745: 0x000a, + 0x1746: 0x000a, 0x1747: 0x000a, 0x1748: 0x0002, 0x1749: 0x0002, 0x174a: 0x0002, 0x174b: 0x0002, + 0x174c: 0x0002, 0x174d: 0x0002, 0x174e: 0x0002, 0x174f: 0x0002, 0x1750: 0x0002, 0x1751: 0x0002, + 0x1752: 0x0002, 0x1753: 0x0002, 0x1754: 0x0002, 0x1755: 0x0002, 0x1756: 0x0002, 0x1757: 0x0002, + 0x1758: 0x0002, 0x1759: 0x0002, 0x175a: 0x0002, 0x175b: 0x0002, + // Block 0x5e, offset 0x1780 + 0x17aa: 0x000a, 0x17ab: 0x000a, 0x17ac: 0x000a, 0x17ad: 0x000a, 0x17ae: 0x000a, 0x17af: 0x000a, + 0x17b0: 0x000a, 0x17b1: 0x000a, 0x17b2: 0x000a, 0x17b3: 0x000a, 0x17b4: 0x000a, 0x17b5: 0x000a, + 0x17b6: 0x000a, 0x17b7: 0x000a, 0x17b8: 0x000a, 0x17b9: 0x000a, 0x17ba: 0x000a, 0x17bb: 0x000a, + 0x17bc: 0x000a, 0x17bd: 0x000a, 0x17be: 0x000a, 0x17bf: 0x000a, + // Block 0x5f, offset 0x17c0 + 0x17c0: 0x000a, 0x17c1: 0x000a, 0x17c2: 0x000a, 0x17c3: 0x000a, 0x17c4: 0x000a, 0x17c5: 0x000a, + 0x17c6: 0x000a, 0x17c7: 0x000a, 0x17c8: 0x000a, 0x17c9: 0x000a, 0x17ca: 0x000a, 0x17cb: 0x000a, + 0x17cc: 0x000a, 0x17cd: 0x000a, 0x17ce: 0x000a, 0x17cf: 0x000a, 0x17d0: 0x000a, 0x17d1: 0x000a, + 0x17d2: 0x000a, 0x17d3: 0x000a, 0x17d4: 0x000a, 0x17d5: 0x000a, 0x17d6: 0x000a, 0x17d7: 0x000a, + 0x17d8: 0x000a, 0x17d9: 0x000a, 0x17da: 0x000a, 0x17db: 0x000a, 0x17dc: 0x000a, 0x17dd: 0x000a, + 0x17de: 0x000a, 0x17df: 0x000a, 0x17e0: 0x000a, 0x17e1: 0x000a, 0x17e2: 0x000a, 0x17e3: 0x000a, + 0x17e4: 0x000a, 0x17e5: 0x000a, 0x17e6: 0x000a, 0x17e7: 0x000a, 0x17e8: 0x000a, 0x17e9: 0x000a, + 0x17ea: 0x000a, 0x17eb: 0x000a, 0x17ed: 0x000a, 0x17ee: 0x000a, 0x17ef: 0x000a, + 0x17f0: 0x000a, 0x17f1: 0x000a, 0x17f2: 0x000a, 0x17f3: 0x000a, 0x17f4: 0x000a, 0x17f5: 0x000a, + 0x17f6: 0x000a, 0x17f7: 0x000a, 0x17f8: 0x000a, 0x17f9: 0x000a, 0x17fa: 0x000a, 0x17fb: 0x000a, + 0x17fc: 0x000a, 0x17fd: 0x000a, 0x17fe: 0x000a, 0x17ff: 0x000a, + // Block 0x60, offset 0x1800 + 0x1800: 0x000a, 0x1801: 0x000a, 0x1802: 0x000a, 0x1803: 0x000a, 0x1804: 0x000a, 0x1805: 0x000a, + 0x1806: 0x000a, 0x1807: 0x000a, 0x1808: 0x000a, 0x1809: 0x000a, 0x180a: 0x000a, 0x180b: 0x000a, + 0x180c: 0x000a, 0x180d: 0x000a, 0x180e: 0x000a, 0x180f: 0x000a, 0x1810: 0x000a, 0x1811: 0x000a, + 0x1812: 0x000a, 0x1813: 0x000a, 0x1814: 0x000a, 0x1815: 0x000a, 0x1816: 0x000a, 0x1817: 0x000a, + 0x1818: 0x000a, 0x1819: 0x000a, 0x181a: 0x000a, 0x181b: 0x000a, 0x181c: 0x000a, 0x181d: 0x000a, + 0x181e: 0x000a, 0x181f: 0x000a, 0x1820: 0x000a, 0x1821: 0x000a, 0x1822: 0x000a, 0x1823: 0x000a, + 0x1824: 0x000a, 0x1825: 0x000a, 0x1826: 0x000a, 0x1827: 0x000a, 0x1828: 0x003a, 0x1829: 0x002a, + 0x182a: 0x003a, 0x182b: 0x002a, 0x182c: 0x003a, 0x182d: 0x002a, 0x182e: 0x003a, 0x182f: 0x002a, + 0x1830: 0x003a, 0x1831: 0x002a, 0x1832: 0x003a, 0x1833: 0x002a, 0x1834: 0x003a, 0x1835: 0x002a, + 0x1836: 0x000a, 0x1837: 0x000a, 0x1838: 0x000a, 0x1839: 0x000a, 0x183a: 0x000a, 0x183b: 0x000a, + 0x183c: 0x000a, 0x183d: 0x000a, 0x183e: 0x000a, 0x183f: 0x000a, + // Block 0x61, offset 0x1840 + 0x1840: 0x000a, 0x1841: 0x000a, 0x1842: 0x000a, 0x1843: 0x000a, 0x1844: 0x000a, 0x1845: 0x009a, + 0x1846: 0x008a, 0x1847: 0x000a, 0x1848: 0x000a, 0x1849: 0x000a, 0x184a: 0x000a, 0x184b: 0x000a, + 0x184c: 0x000a, 0x184d: 0x000a, 0x184e: 0x000a, 0x184f: 0x000a, 0x1850: 0x000a, 0x1851: 0x000a, + 0x1852: 0x000a, 0x1853: 0x000a, 0x1854: 0x000a, 0x1855: 0x000a, 0x1856: 0x000a, 0x1857: 0x000a, + 0x1858: 0x000a, 0x1859: 0x000a, 0x185a: 0x000a, 0x185b: 0x000a, 0x185c: 0x000a, 0x185d: 0x000a, + 0x185e: 0x000a, 0x185f: 0x000a, 0x1860: 0x000a, 0x1861: 0x000a, 0x1862: 0x000a, 0x1863: 0x000a, + 0x1864: 0x000a, 0x1865: 0x000a, 0x1866: 0x003a, 0x1867: 0x002a, 0x1868: 0x003a, 0x1869: 0x002a, + 0x186a: 0x003a, 0x186b: 0x002a, 0x186c: 0x003a, 0x186d: 0x002a, 0x186e: 0x003a, 0x186f: 0x002a, + 0x1870: 0x000a, 0x1871: 0x000a, 0x1872: 0x000a, 0x1873: 0x000a, 0x1874: 0x000a, 0x1875: 0x000a, + 0x1876: 0x000a, 0x1877: 0x000a, 0x1878: 0x000a, 0x1879: 0x000a, 0x187a: 0x000a, 0x187b: 0x000a, + 0x187c: 0x000a, 0x187d: 0x000a, 0x187e: 0x000a, 0x187f: 0x000a, + // Block 0x62, offset 0x1880 + 0x1880: 0x000a, 0x1881: 0x000a, 0x1882: 0x000a, 0x1883: 0x007a, 0x1884: 0x006a, 0x1885: 0x009a, + 0x1886: 0x008a, 0x1887: 0x00ba, 0x1888: 0x00aa, 0x1889: 0x009a, 0x188a: 0x008a, 0x188b: 0x007a, + 0x188c: 0x006a, 0x188d: 0x00da, 0x188e: 0x002a, 0x188f: 0x003a, 0x1890: 0x00ca, 0x1891: 0x009a, + 0x1892: 0x008a, 0x1893: 0x007a, 0x1894: 0x006a, 0x1895: 0x009a, 0x1896: 0x008a, 0x1897: 0x00ba, + 0x1898: 0x00aa, 0x1899: 0x000a, 0x189a: 0x000a, 0x189b: 0x000a, 0x189c: 0x000a, 0x189d: 0x000a, + 0x189e: 0x000a, 0x189f: 0x000a, 0x18a0: 0x000a, 0x18a1: 0x000a, 0x18a2: 0x000a, 0x18a3: 0x000a, + 0x18a4: 0x000a, 0x18a5: 0x000a, 0x18a6: 0x000a, 0x18a7: 0x000a, 0x18a8: 0x000a, 0x18a9: 0x000a, + 0x18aa: 0x000a, 0x18ab: 0x000a, 0x18ac: 0x000a, 0x18ad: 0x000a, 0x18ae: 0x000a, 0x18af: 0x000a, + 0x18b0: 0x000a, 0x18b1: 0x000a, 0x18b2: 0x000a, 0x18b3: 0x000a, 0x18b4: 0x000a, 0x18b5: 0x000a, + 0x18b6: 0x000a, 0x18b7: 0x000a, 0x18b8: 0x000a, 0x18b9: 0x000a, 0x18ba: 0x000a, 0x18bb: 0x000a, + 0x18bc: 0x000a, 0x18bd: 0x000a, 0x18be: 0x000a, 0x18bf: 0x000a, + // Block 0x63, offset 0x18c0 + 0x18c0: 0x000a, 0x18c1: 0x000a, 0x18c2: 0x000a, 0x18c3: 0x000a, 0x18c4: 0x000a, 0x18c5: 0x000a, + 0x18c6: 0x000a, 0x18c7: 0x000a, 0x18c8: 0x000a, 0x18c9: 0x000a, 0x18ca: 0x000a, 0x18cb: 0x000a, + 0x18cc: 0x000a, 0x18cd: 0x000a, 0x18ce: 0x000a, 0x18cf: 0x000a, 0x18d0: 0x000a, 0x18d1: 0x000a, + 0x18d2: 0x000a, 0x18d3: 0x000a, 0x18d4: 0x000a, 0x18d5: 0x000a, 0x18d6: 0x000a, 0x18d7: 0x000a, + 0x18d8: 0x003a, 0x18d9: 0x002a, 0x18da: 0x003a, 0x18db: 0x002a, 0x18dc: 0x000a, 0x18dd: 0x000a, + 0x18de: 0x000a, 0x18df: 0x000a, 0x18e0: 0x000a, 0x18e1: 0x000a, 0x18e2: 0x000a, 0x18e3: 0x000a, + 0x18e4: 0x000a, 0x18e5: 0x000a, 0x18e6: 0x000a, 0x18e7: 0x000a, 0x18e8: 0x000a, 0x18e9: 0x000a, + 0x18ea: 0x000a, 0x18eb: 0x000a, 0x18ec: 0x000a, 0x18ed: 0x000a, 0x18ee: 0x000a, 0x18ef: 0x000a, + 0x18f0: 0x000a, 0x18f1: 0x000a, 0x18f2: 0x000a, 0x18f3: 0x000a, 0x18f4: 0x000a, 0x18f5: 0x000a, + 0x18f6: 0x000a, 0x18f7: 0x000a, 0x18f8: 0x000a, 0x18f9: 0x000a, 0x18fa: 0x000a, 0x18fb: 0x000a, + 0x18fc: 0x003a, 0x18fd: 0x002a, 0x18fe: 0x000a, 0x18ff: 0x000a, + // Block 0x64, offset 0x1900 + 0x1900: 0x000a, 0x1901: 0x000a, 0x1902: 0x000a, 0x1903: 0x000a, 0x1904: 0x000a, 0x1905: 0x000a, + 0x1906: 0x000a, 0x1907: 0x000a, 0x1908: 0x000a, 0x1909: 0x000a, 0x190a: 0x000a, 0x190b: 0x000a, + 0x190c: 0x000a, 0x190d: 0x000a, 0x190e: 0x000a, 0x190f: 0x000a, 0x1910: 0x000a, 0x1911: 0x000a, + 0x1912: 0x000a, 0x1913: 0x000a, 0x1914: 0x000a, 0x1915: 0x000a, 0x1916: 0x000a, 0x1917: 0x000a, + 0x1918: 0x000a, 0x1919: 0x000a, 0x191a: 0x000a, 0x191b: 0x000a, 0x191c: 0x000a, 0x191d: 0x000a, + 0x191e: 0x000a, 0x191f: 0x000a, 0x1920: 0x000a, 0x1921: 0x000a, 0x1922: 0x000a, 0x1923: 0x000a, + 0x1924: 0x000a, 0x1925: 0x000a, 0x1926: 0x000a, 0x1927: 0x000a, 0x1928: 0x000a, 0x1929: 0x000a, + 0x192a: 0x000a, 0x192b: 0x000a, 0x192c: 0x000a, 0x192d: 0x000a, 0x192e: 0x000a, 0x192f: 0x000a, + 0x1930: 0x000a, 0x1931: 0x000a, 0x1932: 0x000a, 0x1933: 0x000a, + 0x1936: 0x000a, 0x1937: 0x000a, 0x1938: 0x000a, 0x1939: 0x000a, 0x193a: 0x000a, 0x193b: 0x000a, + 0x193c: 0x000a, 0x193d: 0x000a, 0x193e: 0x000a, 0x193f: 0x000a, + // Block 0x65, offset 0x1940 + 0x1940: 0x000a, 0x1941: 0x000a, 0x1942: 0x000a, 0x1943: 0x000a, 0x1944: 0x000a, 0x1945: 0x000a, + 0x1946: 0x000a, 0x1947: 0x000a, 0x1948: 0x000a, 0x1949: 0x000a, 0x194a: 0x000a, 0x194b: 0x000a, + 0x194c: 0x000a, 0x194d: 0x000a, 0x194e: 0x000a, 0x194f: 0x000a, 0x1950: 0x000a, 0x1951: 0x000a, + 0x1952: 0x000a, 0x1953: 0x000a, 0x1954: 0x000a, 0x1955: 0x000a, + 0x1958: 0x000a, 0x1959: 0x000a, 0x195a: 0x000a, 0x195b: 0x000a, 0x195c: 0x000a, 0x195d: 0x000a, + 0x195e: 0x000a, 0x195f: 0x000a, 0x1960: 0x000a, 0x1961: 0x000a, 0x1962: 0x000a, 0x1963: 0x000a, + 0x1964: 0x000a, 0x1965: 0x000a, 0x1966: 0x000a, 0x1967: 0x000a, 0x1968: 0x000a, 0x1969: 0x000a, + 0x196a: 0x000a, 0x196b: 0x000a, 0x196c: 0x000a, 0x196d: 0x000a, 0x196e: 0x000a, 0x196f: 0x000a, + 0x1970: 0x000a, 0x1971: 0x000a, 0x1972: 0x000a, 0x1973: 0x000a, 0x1974: 0x000a, 0x1975: 0x000a, + 0x1976: 0x000a, 0x1977: 0x000a, 0x1978: 0x000a, 0x1979: 0x000a, 0x197a: 0x000a, 0x197b: 0x000a, + 0x197c: 0x000a, 0x197d: 0x000a, 0x197e: 0x000a, 0x197f: 0x000a, + // Block 0x66, offset 0x1980 + 0x19a5: 0x000a, 0x19a6: 0x000a, 0x19a7: 0x000a, 0x19a8: 0x000a, 0x19a9: 0x000a, + 0x19aa: 0x000a, 0x19af: 0x000c, + 0x19b0: 0x000c, 0x19b1: 0x000c, + 0x19b9: 0x000a, 0x19ba: 0x000a, 0x19bb: 0x000a, + 0x19bc: 0x000a, 0x19bd: 0x000a, 0x19be: 0x000a, 0x19bf: 0x000a, + // Block 0x67, offset 0x19c0 + 0x19ff: 0x000c, + // Block 0x68, offset 0x1a00 + 0x1a20: 0x000c, 0x1a21: 0x000c, 0x1a22: 0x000c, 0x1a23: 0x000c, + 0x1a24: 0x000c, 0x1a25: 0x000c, 0x1a26: 0x000c, 0x1a27: 0x000c, 0x1a28: 0x000c, 0x1a29: 0x000c, + 0x1a2a: 0x000c, 0x1a2b: 0x000c, 0x1a2c: 0x000c, 0x1a2d: 0x000c, 0x1a2e: 0x000c, 0x1a2f: 0x000c, + 0x1a30: 0x000c, 0x1a31: 0x000c, 0x1a32: 0x000c, 0x1a33: 0x000c, 0x1a34: 0x000c, 0x1a35: 0x000c, + 0x1a36: 0x000c, 0x1a37: 0x000c, 0x1a38: 0x000c, 0x1a39: 0x000c, 0x1a3a: 0x000c, 0x1a3b: 0x000c, + 0x1a3c: 0x000c, 0x1a3d: 0x000c, 0x1a3e: 0x000c, 0x1a3f: 0x000c, + // Block 0x69, offset 0x1a40 + 0x1a40: 0x000a, 0x1a41: 0x000a, 0x1a42: 0x000a, 0x1a43: 0x000a, 0x1a44: 0x000a, 0x1a45: 0x000a, + 0x1a46: 0x000a, 0x1a47: 0x000a, 0x1a48: 0x000a, 0x1a49: 0x000a, 0x1a4a: 0x000a, 0x1a4b: 0x000a, + 0x1a4c: 0x000a, 0x1a4d: 0x000a, 0x1a4e: 0x000a, 0x1a4f: 0x000a, 0x1a50: 0x000a, 0x1a51: 0x000a, + 0x1a52: 0x000a, 0x1a53: 0x000a, 0x1a54: 0x000a, 0x1a55: 0x000a, 0x1a56: 0x000a, 0x1a57: 0x000a, + 0x1a58: 0x000a, 0x1a59: 0x000a, 0x1a5a: 0x000a, 0x1a5b: 0x000a, 0x1a5c: 0x000a, 0x1a5d: 0x000a, + 0x1a5e: 0x000a, 0x1a5f: 0x000a, 0x1a60: 0x000a, 0x1a61: 0x000a, 0x1a62: 0x003a, 0x1a63: 0x002a, + 0x1a64: 0x003a, 0x1a65: 0x002a, 0x1a66: 0x003a, 0x1a67: 0x002a, 0x1a68: 0x003a, 0x1a69: 0x002a, + 0x1a6a: 0x000a, 0x1a6b: 0x000a, 0x1a6c: 0x000a, 0x1a6d: 0x000a, 0x1a6e: 0x000a, 0x1a6f: 0x000a, + 0x1a70: 0x000a, 0x1a71: 0x000a, 0x1a72: 0x000a, 0x1a73: 0x000a, 0x1a74: 0x000a, 0x1a75: 0x000a, + 0x1a76: 0x000a, 0x1a77: 0x000a, 0x1a78: 0x000a, 0x1a79: 0x000a, 0x1a7a: 0x000a, 0x1a7b: 0x000a, + 0x1a7c: 0x000a, 0x1a7d: 0x000a, 0x1a7e: 0x000a, 0x1a7f: 0x000a, + // Block 0x6a, offset 0x1a80 + 0x1a80: 0x000a, 0x1a81: 0x000a, 0x1a82: 0x000a, 0x1a83: 0x000a, 0x1a84: 0x000a, 0x1a85: 0x000a, + 0x1a86: 0x000a, 0x1a87: 0x000a, 0x1a88: 0x000a, 0x1a89: 0x000a, 0x1a8a: 0x000a, 0x1a8b: 0x000a, + 0x1a8c: 0x000a, 0x1a8d: 0x000a, 0x1a8e: 0x000a, 0x1a8f: 0x000a, + // Block 0x6b, offset 0x1ac0 + 0x1ac0: 0x000a, 0x1ac1: 0x000a, 0x1ac2: 0x000a, 0x1ac3: 0x000a, 0x1ac4: 0x000a, 0x1ac5: 0x000a, + 0x1ac6: 0x000a, 0x1ac7: 0x000a, 0x1ac8: 0x000a, 0x1ac9: 0x000a, 0x1aca: 0x000a, 0x1acb: 0x000a, + 0x1acc: 0x000a, 0x1acd: 0x000a, 0x1ace: 0x000a, 0x1acf: 0x000a, 0x1ad0: 0x000a, 0x1ad1: 0x000a, + 0x1ad2: 0x000a, 0x1ad3: 0x000a, 0x1ad4: 0x000a, 0x1ad5: 0x000a, 0x1ad6: 0x000a, 0x1ad7: 0x000a, + 0x1ad8: 0x000a, 0x1ad9: 0x000a, 0x1adb: 0x000a, 0x1adc: 0x000a, 0x1add: 0x000a, + 0x1ade: 0x000a, 0x1adf: 0x000a, 0x1ae0: 0x000a, 0x1ae1: 0x000a, 0x1ae2: 0x000a, 0x1ae3: 0x000a, + 0x1ae4: 0x000a, 0x1ae5: 0x000a, 0x1ae6: 0x000a, 0x1ae7: 0x000a, 0x1ae8: 0x000a, 0x1ae9: 0x000a, + 0x1aea: 0x000a, 0x1aeb: 0x000a, 0x1aec: 0x000a, 0x1aed: 0x000a, 0x1aee: 0x000a, 0x1aef: 0x000a, + 0x1af0: 0x000a, 0x1af1: 0x000a, 0x1af2: 0x000a, 0x1af3: 0x000a, 0x1af4: 0x000a, 0x1af5: 0x000a, + 0x1af6: 0x000a, 0x1af7: 0x000a, 0x1af8: 0x000a, 0x1af9: 0x000a, 0x1afa: 0x000a, 0x1afb: 0x000a, + 0x1afc: 0x000a, 0x1afd: 0x000a, 0x1afe: 0x000a, 0x1aff: 0x000a, + // Block 0x6c, offset 0x1b00 + 0x1b00: 0x000a, 0x1b01: 0x000a, 0x1b02: 0x000a, 0x1b03: 0x000a, 0x1b04: 0x000a, 0x1b05: 0x000a, + 0x1b06: 0x000a, 0x1b07: 0x000a, 0x1b08: 0x000a, 0x1b09: 0x000a, 0x1b0a: 0x000a, 0x1b0b: 0x000a, + 0x1b0c: 0x000a, 0x1b0d: 0x000a, 0x1b0e: 0x000a, 0x1b0f: 0x000a, 0x1b10: 0x000a, 0x1b11: 0x000a, + 0x1b12: 0x000a, 0x1b13: 0x000a, 0x1b14: 0x000a, 0x1b15: 0x000a, 0x1b16: 0x000a, 0x1b17: 0x000a, + 0x1b18: 0x000a, 0x1b19: 0x000a, 0x1b1a: 0x000a, 0x1b1b: 0x000a, 0x1b1c: 0x000a, 0x1b1d: 0x000a, + 0x1b1e: 0x000a, 0x1b1f: 0x000a, 0x1b20: 0x000a, 0x1b21: 0x000a, 0x1b22: 0x000a, 0x1b23: 0x000a, + 0x1b24: 0x000a, 0x1b25: 0x000a, 0x1b26: 0x000a, 0x1b27: 0x000a, 0x1b28: 0x000a, 0x1b29: 0x000a, + 0x1b2a: 0x000a, 0x1b2b: 0x000a, 0x1b2c: 0x000a, 0x1b2d: 0x000a, 0x1b2e: 0x000a, 0x1b2f: 0x000a, + 0x1b30: 0x000a, 0x1b31: 0x000a, 0x1b32: 0x000a, 0x1b33: 0x000a, + // Block 0x6d, offset 0x1b40 + 0x1b40: 0x000a, 0x1b41: 0x000a, 0x1b42: 0x000a, 0x1b43: 0x000a, 0x1b44: 0x000a, 0x1b45: 0x000a, + 0x1b46: 0x000a, 0x1b47: 0x000a, 0x1b48: 0x000a, 0x1b49: 0x000a, 0x1b4a: 0x000a, 0x1b4b: 0x000a, + 0x1b4c: 0x000a, 0x1b4d: 0x000a, 0x1b4e: 0x000a, 0x1b4f: 0x000a, 0x1b50: 0x000a, 0x1b51: 0x000a, + 0x1b52: 0x000a, 0x1b53: 0x000a, 0x1b54: 0x000a, 0x1b55: 0x000a, + 0x1b70: 0x000a, 0x1b71: 0x000a, 0x1b72: 0x000a, 0x1b73: 0x000a, 0x1b74: 0x000a, 0x1b75: 0x000a, + 0x1b76: 0x000a, 0x1b77: 0x000a, 0x1b78: 0x000a, 0x1b79: 0x000a, 0x1b7a: 0x000a, 0x1b7b: 0x000a, + // Block 0x6e, offset 0x1b80 + 0x1b80: 0x0009, 0x1b81: 0x000a, 0x1b82: 0x000a, 0x1b83: 0x000a, 0x1b84: 0x000a, + 0x1b88: 0x003a, 0x1b89: 0x002a, 0x1b8a: 0x003a, 0x1b8b: 0x002a, + 0x1b8c: 0x003a, 0x1b8d: 0x002a, 0x1b8e: 0x003a, 0x1b8f: 0x002a, 0x1b90: 0x003a, 0x1b91: 0x002a, + 0x1b92: 0x000a, 0x1b93: 0x000a, 0x1b94: 0x003a, 0x1b95: 0x002a, 0x1b96: 0x003a, 0x1b97: 0x002a, + 0x1b98: 0x003a, 0x1b99: 0x002a, 0x1b9a: 0x003a, 0x1b9b: 0x002a, 0x1b9c: 0x000a, 0x1b9d: 0x000a, + 0x1b9e: 0x000a, 0x1b9f: 0x000a, 0x1ba0: 0x000a, + 0x1baa: 0x000c, 0x1bab: 0x000c, 0x1bac: 0x000c, 0x1bad: 0x000c, + 0x1bb0: 0x000a, + 0x1bb6: 0x000a, 0x1bb7: 0x000a, + 0x1bbd: 0x000a, 0x1bbe: 0x000a, 0x1bbf: 0x000a, + // Block 0x6f, offset 0x1bc0 + 0x1bd9: 0x000c, 0x1bda: 0x000c, 0x1bdb: 0x000a, 0x1bdc: 0x000a, + 0x1be0: 0x000a, + // Block 0x70, offset 0x1c00 + 0x1c3b: 0x000a, + // Block 0x71, offset 0x1c40 + 0x1c40: 0x000a, 0x1c41: 0x000a, 0x1c42: 0x000a, 0x1c43: 0x000a, 0x1c44: 0x000a, 0x1c45: 0x000a, + 0x1c46: 0x000a, 0x1c47: 0x000a, 0x1c48: 0x000a, 0x1c49: 0x000a, 0x1c4a: 0x000a, 0x1c4b: 0x000a, + 0x1c4c: 0x000a, 0x1c4d: 0x000a, 0x1c4e: 0x000a, 0x1c4f: 0x000a, 0x1c50: 0x000a, 0x1c51: 0x000a, + 0x1c52: 0x000a, 0x1c53: 0x000a, 0x1c54: 0x000a, 0x1c55: 0x000a, 0x1c56: 0x000a, 0x1c57: 0x000a, + 0x1c58: 0x000a, 0x1c59: 0x000a, 0x1c5a: 0x000a, 0x1c5b: 0x000a, 0x1c5c: 0x000a, 0x1c5d: 0x000a, + 0x1c5e: 0x000a, 0x1c5f: 0x000a, 0x1c60: 0x000a, 0x1c61: 0x000a, 0x1c62: 0x000a, 0x1c63: 0x000a, + // Block 0x72, offset 0x1c80 + 0x1c9d: 0x000a, + 0x1c9e: 0x000a, + // Block 0x73, offset 0x1cc0 + 0x1cd0: 0x000a, 0x1cd1: 0x000a, + 0x1cd2: 0x000a, 0x1cd3: 0x000a, 0x1cd4: 0x000a, 0x1cd5: 0x000a, 0x1cd6: 0x000a, 0x1cd7: 0x000a, + 0x1cd8: 0x000a, 0x1cd9: 0x000a, 0x1cda: 0x000a, 0x1cdb: 0x000a, 0x1cdc: 0x000a, 0x1cdd: 0x000a, + 0x1cde: 0x000a, 0x1cdf: 0x000a, + 0x1cfc: 0x000a, 0x1cfd: 0x000a, 0x1cfe: 0x000a, + // Block 0x74, offset 0x1d00 + 0x1d31: 0x000a, 0x1d32: 0x000a, 0x1d33: 0x000a, 0x1d34: 0x000a, 0x1d35: 0x000a, + 0x1d36: 0x000a, 0x1d37: 0x000a, 0x1d38: 0x000a, 0x1d39: 0x000a, 0x1d3a: 0x000a, 0x1d3b: 0x000a, + 0x1d3c: 0x000a, 0x1d3d: 0x000a, 0x1d3e: 0x000a, 0x1d3f: 0x000a, + // Block 0x75, offset 0x1d40 + 0x1d4c: 0x000a, 0x1d4d: 0x000a, 0x1d4e: 0x000a, 0x1d4f: 0x000a, + // Block 0x76, offset 0x1d80 + 0x1db7: 0x000a, 0x1db8: 0x000a, 0x1db9: 0x000a, 0x1dba: 0x000a, + // Block 0x77, offset 0x1dc0 + 0x1dde: 0x000a, 0x1ddf: 0x000a, + 0x1dff: 0x000a, + // Block 0x78, offset 0x1e00 + 0x1e10: 0x000a, 0x1e11: 0x000a, + 0x1e12: 0x000a, 0x1e13: 0x000a, 0x1e14: 0x000a, 0x1e15: 0x000a, 0x1e16: 0x000a, 0x1e17: 0x000a, + 0x1e18: 0x000a, 0x1e19: 0x000a, 0x1e1a: 0x000a, 0x1e1b: 0x000a, 0x1e1c: 0x000a, 0x1e1d: 0x000a, + 0x1e1e: 0x000a, 0x1e1f: 0x000a, 0x1e20: 0x000a, 0x1e21: 0x000a, 0x1e22: 0x000a, 0x1e23: 0x000a, + 0x1e24: 0x000a, 0x1e25: 0x000a, 0x1e26: 0x000a, 0x1e27: 0x000a, 0x1e28: 0x000a, 0x1e29: 0x000a, + 0x1e2a: 0x000a, 0x1e2b: 0x000a, 0x1e2c: 0x000a, 0x1e2d: 0x000a, 0x1e2e: 0x000a, 0x1e2f: 0x000a, + 0x1e30: 0x000a, 0x1e31: 0x000a, 0x1e32: 0x000a, 0x1e33: 0x000a, 0x1e34: 0x000a, 0x1e35: 0x000a, + 0x1e36: 0x000a, 0x1e37: 0x000a, 0x1e38: 0x000a, 0x1e39: 0x000a, 0x1e3a: 0x000a, 0x1e3b: 0x000a, + 0x1e3c: 0x000a, 0x1e3d: 0x000a, 0x1e3e: 0x000a, 0x1e3f: 0x000a, + // Block 0x79, offset 0x1e40 + 0x1e40: 0x000a, 0x1e41: 0x000a, 0x1e42: 0x000a, 0x1e43: 0x000a, 0x1e44: 0x000a, 0x1e45: 0x000a, + 0x1e46: 0x000a, + // Block 0x7a, offset 0x1e80 + 0x1e8d: 0x000a, 0x1e8e: 0x000a, 0x1e8f: 0x000a, + // Block 0x7b, offset 0x1ec0 + 0x1eef: 0x000c, + 0x1ef0: 0x000c, 0x1ef1: 0x000c, 0x1ef2: 0x000c, 0x1ef3: 0x000a, 0x1ef4: 0x000c, 0x1ef5: 0x000c, + 0x1ef6: 0x000c, 0x1ef7: 0x000c, 0x1ef8: 0x000c, 0x1ef9: 0x000c, 0x1efa: 0x000c, 0x1efb: 0x000c, + 0x1efc: 0x000c, 0x1efd: 0x000c, 0x1efe: 0x000a, 0x1eff: 0x000a, + // Block 0x7c, offset 0x1f00 + 0x1f1e: 0x000c, 0x1f1f: 0x000c, + // Block 0x7d, offset 0x1f40 + 0x1f70: 0x000c, 0x1f71: 0x000c, + // Block 0x7e, offset 0x1f80 + 0x1f80: 0x000a, 0x1f81: 0x000a, 0x1f82: 0x000a, 0x1f83: 0x000a, 0x1f84: 0x000a, 0x1f85: 0x000a, + 0x1f86: 0x000a, 0x1f87: 0x000a, 0x1f88: 0x000a, 0x1f89: 0x000a, 0x1f8a: 0x000a, 0x1f8b: 0x000a, + 0x1f8c: 0x000a, 0x1f8d: 0x000a, 0x1f8e: 0x000a, 0x1f8f: 0x000a, 0x1f90: 0x000a, 0x1f91: 0x000a, + 0x1f92: 0x000a, 0x1f93: 0x000a, 0x1f94: 0x000a, 0x1f95: 0x000a, 0x1f96: 0x000a, 0x1f97: 0x000a, + 0x1f98: 0x000a, 0x1f99: 0x000a, 0x1f9a: 0x000a, 0x1f9b: 0x000a, 0x1f9c: 0x000a, 0x1f9d: 0x000a, + 0x1f9e: 0x000a, 0x1f9f: 0x000a, 0x1fa0: 0x000a, 0x1fa1: 0x000a, + // Block 0x7f, offset 0x1fc0 + 0x1fc8: 0x000a, + // Block 0x80, offset 0x2000 + 0x2002: 0x000c, + 0x2006: 0x000c, 0x200b: 0x000c, + 0x2025: 0x000c, 0x2026: 0x000c, 0x2028: 0x000a, 0x2029: 0x000a, + 0x202a: 0x000a, 0x202b: 0x000a, + 0x2038: 0x0004, 0x2039: 0x0004, + // Block 0x81, offset 0x2040 + 0x2074: 0x000a, 0x2075: 0x000a, + 0x2076: 0x000a, 0x2077: 0x000a, + // Block 0x82, offset 0x2080 + 0x2084: 0x000c, 0x2085: 0x000c, + 0x20a0: 0x000c, 0x20a1: 0x000c, 0x20a2: 0x000c, 0x20a3: 0x000c, + 0x20a4: 0x000c, 0x20a5: 0x000c, 0x20a6: 0x000c, 0x20a7: 0x000c, 0x20a8: 0x000c, 0x20a9: 0x000c, + 0x20aa: 0x000c, 0x20ab: 0x000c, 0x20ac: 0x000c, 0x20ad: 0x000c, 0x20ae: 0x000c, 0x20af: 0x000c, + 0x20b0: 0x000c, 0x20b1: 0x000c, + 0x20bf: 0x000c, + // Block 0x83, offset 0x20c0 + 0x20e6: 0x000c, 0x20e7: 0x000c, 0x20e8: 0x000c, 0x20e9: 0x000c, + 0x20ea: 0x000c, 0x20eb: 0x000c, 0x20ec: 0x000c, 0x20ed: 0x000c, + // Block 0x84, offset 0x2100 + 0x2107: 0x000c, 0x2108: 0x000c, 0x2109: 0x000c, 0x210a: 0x000c, 0x210b: 0x000c, + 0x210c: 0x000c, 0x210d: 0x000c, 0x210e: 0x000c, 0x210f: 0x000c, 0x2110: 0x000c, 0x2111: 0x000c, + // Block 0x85, offset 0x2140 + 0x2140: 0x000c, 0x2141: 0x000c, 0x2142: 0x000c, + 0x2173: 0x000c, + 0x2176: 0x000c, 0x2177: 0x000c, 0x2178: 0x000c, 0x2179: 0x000c, + 0x217c: 0x000c, 0x217d: 0x000c, + // Block 0x86, offset 0x2180 + 0x21a5: 0x000c, + // Block 0x87, offset 0x21c0 + 0x21e9: 0x000c, + 0x21ea: 0x000c, 0x21eb: 0x000c, 0x21ec: 0x000c, 0x21ed: 0x000c, 0x21ee: 0x000c, + 0x21f1: 0x000c, 0x21f2: 0x000c, 0x21f5: 0x000c, + 0x21f6: 0x000c, + // Block 0x88, offset 0x2200 + 0x2203: 0x000c, + 0x220c: 0x000c, + 0x223c: 0x000c, + // Block 0x89, offset 0x2240 + 0x2270: 0x000c, 0x2272: 0x000c, 0x2273: 0x000c, 0x2274: 0x000c, + 0x2277: 0x000c, 0x2278: 0x000c, + 0x227e: 0x000c, 0x227f: 0x000c, + // Block 0x8a, offset 0x2280 + 0x2281: 0x000c, + 0x22ac: 0x000c, 0x22ad: 0x000c, + 0x22b6: 0x000c, + // Block 0x8b, offset 0x22c0 + 0x22e5: 0x000c, 0x22e8: 0x000c, + 0x22ed: 0x000c, + // Block 0x8c, offset 0x2300 + 0x231d: 0x0001, + 0x231e: 0x000c, 0x231f: 0x0001, 0x2320: 0x0001, 0x2321: 0x0001, 0x2322: 0x0001, 0x2323: 0x0001, + 0x2324: 0x0001, 0x2325: 0x0001, 0x2326: 0x0001, 0x2327: 0x0001, 0x2328: 0x0001, 0x2329: 0x0003, + 0x232a: 0x0001, 0x232b: 0x0001, 0x232c: 0x0001, 0x232d: 0x0001, 0x232e: 0x0001, 0x232f: 0x0001, + 0x2330: 0x0001, 0x2331: 0x0001, 0x2332: 0x0001, 0x2333: 0x0001, 0x2334: 0x0001, 0x2335: 0x0001, + 0x2336: 0x0001, 0x2337: 0x0001, 0x2338: 0x0001, 0x2339: 0x0001, 0x233a: 0x0001, 0x233b: 0x0001, + 0x233c: 0x0001, 0x233d: 0x0001, 0x233e: 0x0001, 0x233f: 0x0001, + // Block 0x8d, offset 0x2340 + 0x2340: 0x0001, 0x2341: 0x0001, 0x2342: 0x0001, 0x2343: 0x0001, 0x2344: 0x0001, 0x2345: 0x0001, + 0x2346: 0x0001, 0x2347: 0x0001, 0x2348: 0x0001, 0x2349: 0x0001, 0x234a: 0x0001, 0x234b: 0x0001, + 0x234c: 0x0001, 0x234d: 0x0001, 0x234e: 0x0001, 0x234f: 0x0001, 0x2350: 0x000d, 0x2351: 0x000d, + 0x2352: 0x000d, 0x2353: 0x000d, 0x2354: 0x000d, 0x2355: 0x000d, 0x2356: 0x000d, 0x2357: 0x000d, + 0x2358: 0x000d, 0x2359: 0x000d, 0x235a: 0x000d, 0x235b: 0x000d, 0x235c: 0x000d, 0x235d: 0x000d, + 0x235e: 0x000d, 0x235f: 0x000d, 0x2360: 0x000d, 0x2361: 0x000d, 0x2362: 0x000d, 0x2363: 0x000d, + 0x2364: 0x000d, 0x2365: 0x000d, 0x2366: 0x000d, 0x2367: 0x000d, 0x2368: 0x000d, 0x2369: 0x000d, + 0x236a: 0x000d, 0x236b: 0x000d, 0x236c: 0x000d, 0x236d: 0x000d, 0x236e: 0x000d, 0x236f: 0x000d, + 0x2370: 0x000d, 0x2371: 0x000d, 0x2372: 0x000d, 0x2373: 0x000d, 0x2374: 0x000d, 0x2375: 0x000d, + 0x2376: 0x000d, 0x2377: 0x000d, 0x2378: 0x000d, 0x2379: 0x000d, 0x237a: 0x000d, 0x237b: 0x000d, + 0x237c: 0x000d, 0x237d: 0x000d, 0x237e: 0x000d, 0x237f: 0x000d, + // Block 0x8e, offset 0x2380 + 0x2380: 0x000d, 0x2381: 0x000d, 0x2382: 0x000d, 0x2383: 0x000d, 0x2384: 0x000d, 0x2385: 0x000d, + 0x2386: 0x000d, 0x2387: 0x000d, 0x2388: 0x000d, 0x2389: 0x000d, 0x238a: 0x000d, 0x238b: 0x000d, + 0x238c: 0x000d, 0x238d: 0x000d, 0x238e: 0x000d, 0x238f: 0x000d, 0x2390: 0x000d, 0x2391: 0x000d, + 0x2392: 0x000d, 0x2393: 0x000d, 0x2394: 0x000d, 0x2395: 0x000d, 0x2396: 0x000d, 0x2397: 0x000d, + 0x2398: 0x000d, 0x2399: 0x000d, 0x239a: 0x000d, 0x239b: 0x000d, 0x239c: 0x000d, 0x239d: 0x000d, + 0x239e: 0x000d, 0x239f: 0x000d, 0x23a0: 0x000d, 0x23a1: 0x000d, 0x23a2: 0x000d, 0x23a3: 0x000d, + 0x23a4: 0x000d, 0x23a5: 0x000d, 0x23a6: 0x000d, 0x23a7: 0x000d, 0x23a8: 0x000d, 0x23a9: 0x000d, + 0x23aa: 0x000d, 0x23ab: 0x000d, 0x23ac: 0x000d, 0x23ad: 0x000d, 0x23ae: 0x000d, 0x23af: 0x000d, + 0x23b0: 0x000d, 0x23b1: 0x000d, 0x23b2: 0x000d, 0x23b3: 0x000d, 0x23b4: 0x000d, 0x23b5: 0x000d, + 0x23b6: 0x000d, 0x23b7: 0x000d, 0x23b8: 0x000d, 0x23b9: 0x000d, 0x23ba: 0x000d, 0x23bb: 0x000d, + 0x23bc: 0x000d, 0x23bd: 0x000d, 0x23be: 0x000a, 0x23bf: 0x000a, + // Block 0x8f, offset 0x23c0 + 0x23c0: 0x000d, 0x23c1: 0x000d, 0x23c2: 0x000d, 0x23c3: 0x000d, 0x23c4: 0x000d, 0x23c5: 0x000d, + 0x23c6: 0x000d, 0x23c7: 0x000d, 0x23c8: 0x000d, 0x23c9: 0x000d, 0x23ca: 0x000d, 0x23cb: 0x000d, + 0x23cc: 0x000d, 0x23cd: 0x000d, 0x23ce: 0x000d, 0x23cf: 0x000d, 0x23d0: 0x000b, 0x23d1: 0x000b, + 0x23d2: 0x000b, 0x23d3: 0x000b, 0x23d4: 0x000b, 0x23d5: 0x000b, 0x23d6: 0x000b, 0x23d7: 0x000b, + 0x23d8: 0x000b, 0x23d9: 0x000b, 0x23da: 0x000b, 0x23db: 0x000b, 0x23dc: 0x000b, 0x23dd: 0x000b, + 0x23de: 0x000b, 0x23df: 0x000b, 0x23e0: 0x000b, 0x23e1: 0x000b, 0x23e2: 0x000b, 0x23e3: 0x000b, + 0x23e4: 0x000b, 0x23e5: 0x000b, 0x23e6: 0x000b, 0x23e7: 0x000b, 0x23e8: 0x000b, 0x23e9: 0x000b, + 0x23ea: 0x000b, 0x23eb: 0x000b, 0x23ec: 0x000b, 0x23ed: 0x000b, 0x23ee: 0x000b, 0x23ef: 0x000b, + 0x23f0: 0x000d, 0x23f1: 0x000d, 0x23f2: 0x000d, 0x23f3: 0x000d, 0x23f4: 0x000d, 0x23f5: 0x000d, + 0x23f6: 0x000d, 0x23f7: 0x000d, 0x23f8: 0x000d, 0x23f9: 0x000d, 0x23fa: 0x000d, 0x23fb: 0x000d, + 0x23fc: 0x000d, 0x23fd: 0x000a, 0x23fe: 0x000d, 0x23ff: 0x000d, + // Block 0x90, offset 0x2400 + 0x2400: 0x000c, 0x2401: 0x000c, 0x2402: 0x000c, 0x2403: 0x000c, 0x2404: 0x000c, 0x2405: 0x000c, + 0x2406: 0x000c, 0x2407: 0x000c, 0x2408: 0x000c, 0x2409: 0x000c, 0x240a: 0x000c, 0x240b: 0x000c, + 0x240c: 0x000c, 0x240d: 0x000c, 0x240e: 0x000c, 0x240f: 0x000c, 0x2410: 0x000a, 0x2411: 0x000a, + 0x2412: 0x000a, 0x2413: 0x000a, 0x2414: 0x000a, 0x2415: 0x000a, 0x2416: 0x000a, 0x2417: 0x000a, + 0x2418: 0x000a, 0x2419: 0x000a, + 0x2420: 0x000c, 0x2421: 0x000c, 0x2422: 0x000c, 0x2423: 0x000c, + 0x2424: 0x000c, 0x2425: 0x000c, 0x2426: 0x000c, 0x2427: 0x000c, 0x2428: 0x000c, 0x2429: 0x000c, + 0x242a: 0x000c, 0x242b: 0x000c, 0x242c: 0x000c, 0x242d: 0x000c, 0x242e: 0x000c, 0x242f: 0x000c, + 0x2430: 0x000a, 0x2431: 0x000a, 0x2432: 0x000a, 0x2433: 0x000a, 0x2434: 0x000a, 0x2435: 0x000a, + 0x2436: 0x000a, 0x2437: 0x000a, 0x2438: 0x000a, 0x2439: 0x000a, 0x243a: 0x000a, 0x243b: 0x000a, + 0x243c: 0x000a, 0x243d: 0x000a, 0x243e: 0x000a, 0x243f: 0x000a, + // Block 0x91, offset 0x2440 + 0x2440: 0x000a, 0x2441: 0x000a, 0x2442: 0x000a, 0x2443: 0x000a, 0x2444: 0x000a, 0x2445: 0x000a, + 0x2446: 0x000a, 0x2447: 0x000a, 0x2448: 0x000a, 0x2449: 0x000a, 0x244a: 0x000a, 0x244b: 0x000a, + 0x244c: 0x000a, 0x244d: 0x000a, 0x244e: 0x000a, 0x244f: 0x000a, 0x2450: 0x0006, 0x2451: 0x000a, + 0x2452: 0x0006, 0x2454: 0x000a, 0x2455: 0x0006, 0x2456: 0x000a, 0x2457: 0x000a, + 0x2458: 0x000a, 0x2459: 0x009a, 0x245a: 0x008a, 0x245b: 0x007a, 0x245c: 0x006a, 0x245d: 0x009a, + 0x245e: 0x008a, 0x245f: 0x0004, 0x2460: 0x000a, 0x2461: 0x000a, 0x2462: 0x0003, 0x2463: 0x0003, + 0x2464: 0x000a, 0x2465: 0x000a, 0x2466: 0x000a, 0x2468: 0x000a, 0x2469: 0x0004, + 0x246a: 0x0004, 0x246b: 0x000a, + 0x2470: 0x000d, 0x2471: 0x000d, 0x2472: 0x000d, 0x2473: 0x000d, 0x2474: 0x000d, 0x2475: 0x000d, + 0x2476: 0x000d, 0x2477: 0x000d, 0x2478: 0x000d, 0x2479: 0x000d, 0x247a: 0x000d, 0x247b: 0x000d, + 0x247c: 0x000d, 0x247d: 0x000d, 0x247e: 0x000d, 0x247f: 0x000d, + // Block 0x92, offset 0x2480 + 0x2480: 0x000d, 0x2481: 0x000d, 0x2482: 0x000d, 0x2483: 0x000d, 0x2484: 0x000d, 0x2485: 0x000d, + 0x2486: 0x000d, 0x2487: 0x000d, 0x2488: 0x000d, 0x2489: 0x000d, 0x248a: 0x000d, 0x248b: 0x000d, + 0x248c: 0x000d, 0x248d: 0x000d, 0x248e: 0x000d, 0x248f: 0x000d, 0x2490: 0x000d, 0x2491: 0x000d, + 0x2492: 0x000d, 0x2493: 0x000d, 0x2494: 0x000d, 0x2495: 0x000d, 0x2496: 0x000d, 0x2497: 0x000d, + 0x2498: 0x000d, 0x2499: 0x000d, 0x249a: 0x000d, 0x249b: 0x000d, 0x249c: 0x000d, 0x249d: 0x000d, + 0x249e: 0x000d, 0x249f: 0x000d, 0x24a0: 0x000d, 0x24a1: 0x000d, 0x24a2: 0x000d, 0x24a3: 0x000d, + 0x24a4: 0x000d, 0x24a5: 0x000d, 0x24a6: 0x000d, 0x24a7: 0x000d, 0x24a8: 0x000d, 0x24a9: 0x000d, + 0x24aa: 0x000d, 0x24ab: 0x000d, 0x24ac: 0x000d, 0x24ad: 0x000d, 0x24ae: 0x000d, 0x24af: 0x000d, + 0x24b0: 0x000d, 0x24b1: 0x000d, 0x24b2: 0x000d, 0x24b3: 0x000d, 0x24b4: 0x000d, 0x24b5: 0x000d, + 0x24b6: 0x000d, 0x24b7: 0x000d, 0x24b8: 0x000d, 0x24b9: 0x000d, 0x24ba: 0x000d, 0x24bb: 0x000d, + 0x24bc: 0x000d, 0x24bd: 0x000d, 0x24be: 0x000d, 0x24bf: 0x000b, + // Block 0x93, offset 0x24c0 + 0x24c1: 0x000a, 0x24c2: 0x000a, 0x24c3: 0x0004, 0x24c4: 0x0004, 0x24c5: 0x0004, + 0x24c6: 0x000a, 0x24c7: 0x000a, 0x24c8: 0x003a, 0x24c9: 0x002a, 0x24ca: 0x000a, 0x24cb: 0x0003, + 0x24cc: 0x0006, 0x24cd: 0x0003, 0x24ce: 0x0006, 0x24cf: 0x0006, 0x24d0: 0x0002, 0x24d1: 0x0002, + 0x24d2: 0x0002, 0x24d3: 0x0002, 0x24d4: 0x0002, 0x24d5: 0x0002, 0x24d6: 0x0002, 0x24d7: 0x0002, + 0x24d8: 0x0002, 0x24d9: 0x0002, 0x24da: 0x0006, 0x24db: 0x000a, 0x24dc: 0x000a, 0x24dd: 0x000a, + 0x24de: 0x000a, 0x24df: 0x000a, 0x24e0: 0x000a, + 0x24fb: 0x005a, + 0x24fc: 0x000a, 0x24fd: 0x004a, 0x24fe: 0x000a, 0x24ff: 0x000a, + // Block 0x94, offset 0x2500 + 0x2500: 0x000a, + 0x251b: 0x005a, 0x251c: 0x000a, 0x251d: 0x004a, + 0x251e: 0x000a, 0x251f: 0x00fa, 0x2520: 0x00ea, 0x2521: 0x000a, 0x2522: 0x003a, 0x2523: 0x002a, + 0x2524: 0x000a, 0x2525: 0x000a, + // Block 0x95, offset 0x2540 + 0x2560: 0x0004, 0x2561: 0x0004, 0x2562: 0x000a, 0x2563: 0x000a, + 0x2564: 0x000a, 0x2565: 0x0004, 0x2566: 0x0004, 0x2568: 0x000a, 0x2569: 0x000a, + 0x256a: 0x000a, 0x256b: 0x000a, 0x256c: 0x000a, 0x256d: 0x000a, 0x256e: 0x000a, + 0x2570: 0x000b, 0x2571: 0x000b, 0x2572: 0x000b, 0x2573: 0x000b, 0x2574: 0x000b, 0x2575: 0x000b, + 0x2576: 0x000b, 0x2577: 0x000b, 0x2578: 0x000b, 0x2579: 0x000a, 0x257a: 0x000a, 0x257b: 0x000a, + 0x257c: 0x000a, 0x257d: 0x000a, 0x257e: 0x000b, 0x257f: 0x000b, + // Block 0x96, offset 0x2580 + 0x2581: 0x000a, + // Block 0x97, offset 0x25c0 + 0x25c0: 0x000a, 0x25c1: 0x000a, 0x25c2: 0x000a, 0x25c3: 0x000a, 0x25c4: 0x000a, 0x25c5: 0x000a, + 0x25c6: 0x000a, 0x25c7: 0x000a, 0x25c8: 0x000a, 0x25c9: 0x000a, 0x25ca: 0x000a, 0x25cb: 0x000a, + 0x25cc: 0x000a, 0x25d0: 0x000a, 0x25d1: 0x000a, + 0x25d2: 0x000a, 0x25d3: 0x000a, 0x25d4: 0x000a, 0x25d5: 0x000a, 0x25d6: 0x000a, 0x25d7: 0x000a, + 0x25d8: 0x000a, 0x25d9: 0x000a, 0x25da: 0x000a, 0x25db: 0x000a, + 0x25e0: 0x000a, + // Block 0x98, offset 0x2600 + 0x263d: 0x000c, + // Block 0x99, offset 0x2640 + 0x2660: 0x000c, 0x2661: 0x0002, 0x2662: 0x0002, 0x2663: 0x0002, + 0x2664: 0x0002, 0x2665: 0x0002, 0x2666: 0x0002, 0x2667: 0x0002, 0x2668: 0x0002, 0x2669: 0x0002, + 0x266a: 0x0002, 0x266b: 0x0002, 0x266c: 0x0002, 0x266d: 0x0002, 0x266e: 0x0002, 0x266f: 0x0002, + 0x2670: 0x0002, 0x2671: 0x0002, 0x2672: 0x0002, 0x2673: 0x0002, 0x2674: 0x0002, 0x2675: 0x0002, + 0x2676: 0x0002, 0x2677: 0x0002, 0x2678: 0x0002, 0x2679: 0x0002, 0x267a: 0x0002, 0x267b: 0x0002, + // Block 0x9a, offset 0x2680 + 0x26b6: 0x000c, 0x26b7: 0x000c, 0x26b8: 0x000c, 0x26b9: 0x000c, 0x26ba: 0x000c, + // Block 0x9b, offset 0x26c0 + 0x26c0: 0x0001, 0x26c1: 0x0001, 0x26c2: 0x0001, 0x26c3: 0x0001, 0x26c4: 0x0001, 0x26c5: 0x0001, + 0x26c6: 0x0001, 0x26c7: 0x0001, 0x26c8: 0x0001, 0x26c9: 0x0001, 0x26ca: 0x0001, 0x26cb: 0x0001, + 0x26cc: 0x0001, 0x26cd: 0x0001, 0x26ce: 0x0001, 0x26cf: 0x0001, 0x26d0: 0x0001, 0x26d1: 0x0001, + 0x26d2: 0x0001, 0x26d3: 0x0001, 0x26d4: 0x0001, 0x26d5: 0x0001, 0x26d6: 0x0001, 0x26d7: 0x0001, + 0x26d8: 0x0001, 0x26d9: 0x0001, 0x26da: 0x0001, 0x26db: 0x0001, 0x26dc: 0x0001, 0x26dd: 0x0001, + 0x26de: 0x0001, 0x26df: 0x0001, 0x26e0: 0x0001, 0x26e1: 0x0001, 0x26e2: 0x0001, 0x26e3: 0x0001, + 0x26e4: 0x0001, 0x26e5: 0x0001, 0x26e6: 0x0001, 0x26e7: 0x0001, 0x26e8: 0x0001, 0x26e9: 0x0001, + 0x26ea: 0x0001, 0x26eb: 0x0001, 0x26ec: 0x0001, 0x26ed: 0x0001, 0x26ee: 0x0001, 0x26ef: 0x0001, + 0x26f0: 0x0001, 0x26f1: 0x0001, 0x26f2: 0x0001, 0x26f3: 0x0001, 0x26f4: 0x0001, 0x26f5: 0x0001, + 0x26f6: 0x0001, 0x26f7: 0x0001, 0x26f8: 0x0001, 0x26f9: 0x0001, 0x26fa: 0x0001, 0x26fb: 0x0001, + 0x26fc: 0x0001, 0x26fd: 0x0001, 0x26fe: 0x0001, 0x26ff: 0x0001, + // Block 0x9c, offset 0x2700 + 0x2700: 0x0001, 0x2701: 0x0001, 0x2702: 0x0001, 0x2703: 0x0001, 0x2704: 0x0001, 0x2705: 0x0001, + 0x2706: 0x0001, 0x2707: 0x0001, 0x2708: 0x0001, 0x2709: 0x0001, 0x270a: 0x0001, 0x270b: 0x0001, + 0x270c: 0x0001, 0x270d: 0x0001, 0x270e: 0x0001, 0x270f: 0x0001, 0x2710: 0x0001, 0x2711: 0x0001, + 0x2712: 0x0001, 0x2713: 0x0001, 0x2714: 0x0001, 0x2715: 0x0001, 0x2716: 0x0001, 0x2717: 0x0001, + 0x2718: 0x0001, 0x2719: 0x0001, 0x271a: 0x0001, 0x271b: 0x0001, 0x271c: 0x0001, 0x271d: 0x0001, + 0x271e: 0x0001, 0x271f: 0x000a, 0x2720: 0x0001, 0x2721: 0x0001, 0x2722: 0x0001, 0x2723: 0x0001, + 0x2724: 0x0001, 0x2725: 0x0001, 0x2726: 0x0001, 0x2727: 0x0001, 0x2728: 0x0001, 0x2729: 0x0001, + 0x272a: 0x0001, 0x272b: 0x0001, 0x272c: 0x0001, 0x272d: 0x0001, 0x272e: 0x0001, 0x272f: 0x0001, + 0x2730: 0x0001, 0x2731: 0x0001, 0x2732: 0x0001, 0x2733: 0x0001, 0x2734: 0x0001, 0x2735: 0x0001, + 0x2736: 0x0001, 0x2737: 0x0001, 0x2738: 0x0001, 0x2739: 0x0001, 0x273a: 0x0001, 0x273b: 0x0001, + 0x273c: 0x0001, 0x273d: 0x0001, 0x273e: 0x0001, 0x273f: 0x0001, + // Block 0x9d, offset 0x2740 + 0x2740: 0x0001, 0x2741: 0x000c, 0x2742: 0x000c, 0x2743: 0x000c, 0x2744: 0x0001, 0x2745: 0x000c, + 0x2746: 0x000c, 0x2747: 0x0001, 0x2748: 0x0001, 0x2749: 0x0001, 0x274a: 0x0001, 0x274b: 0x0001, + 0x274c: 0x000c, 0x274d: 0x000c, 0x274e: 0x000c, 0x274f: 0x000c, 0x2750: 0x0001, 0x2751: 0x0001, + 0x2752: 0x0001, 0x2753: 0x0001, 0x2754: 0x0001, 0x2755: 0x0001, 0x2756: 0x0001, 0x2757: 0x0001, + 0x2758: 0x0001, 0x2759: 0x0001, 0x275a: 0x0001, 0x275b: 0x0001, 0x275c: 0x0001, 0x275d: 0x0001, + 0x275e: 0x0001, 0x275f: 0x0001, 0x2760: 0x0001, 0x2761: 0x0001, 0x2762: 0x0001, 0x2763: 0x0001, + 0x2764: 0x0001, 0x2765: 0x0001, 0x2766: 0x0001, 0x2767: 0x0001, 0x2768: 0x0001, 0x2769: 0x0001, + 0x276a: 0x0001, 0x276b: 0x0001, 0x276c: 0x0001, 0x276d: 0x0001, 0x276e: 0x0001, 0x276f: 0x0001, + 0x2770: 0x0001, 0x2771: 0x0001, 0x2772: 0x0001, 0x2773: 0x0001, 0x2774: 0x0001, 0x2775: 0x0001, + 0x2776: 0x0001, 0x2777: 0x0001, 0x2778: 0x000c, 0x2779: 0x000c, 0x277a: 0x000c, 0x277b: 0x0001, + 0x277c: 0x0001, 0x277d: 0x0001, 0x277e: 0x0001, 0x277f: 0x000c, + // Block 0x9e, offset 0x2780 + 0x2780: 0x0001, 0x2781: 0x0001, 0x2782: 0x0001, 0x2783: 0x0001, 0x2784: 0x0001, 0x2785: 0x0001, + 0x2786: 0x0001, 0x2787: 0x0001, 0x2788: 0x0001, 0x2789: 0x0001, 0x278a: 0x0001, 0x278b: 0x0001, + 0x278c: 0x0001, 0x278d: 0x0001, 0x278e: 0x0001, 0x278f: 0x0001, 0x2790: 0x0001, 0x2791: 0x0001, + 0x2792: 0x0001, 0x2793: 0x0001, 0x2794: 0x0001, 0x2795: 0x0001, 0x2796: 0x0001, 0x2797: 0x0001, + 0x2798: 0x0001, 0x2799: 0x0001, 0x279a: 0x0001, 0x279b: 0x0001, 0x279c: 0x0001, 0x279d: 0x0001, + 0x279e: 0x0001, 0x279f: 0x0001, 0x27a0: 0x0001, 0x27a1: 0x0001, 0x27a2: 0x0001, 0x27a3: 0x0001, + 0x27a4: 0x0001, 0x27a5: 0x000c, 0x27a6: 0x000c, 0x27a7: 0x0001, 0x27a8: 0x0001, 0x27a9: 0x0001, + 0x27aa: 0x0001, 0x27ab: 0x0001, 0x27ac: 0x0001, 0x27ad: 0x0001, 0x27ae: 0x0001, 0x27af: 0x0001, + 0x27b0: 0x0001, 0x27b1: 0x0001, 0x27b2: 0x0001, 0x27b3: 0x0001, 0x27b4: 0x0001, 0x27b5: 0x0001, + 0x27b6: 0x0001, 0x27b7: 0x0001, 0x27b8: 0x0001, 0x27b9: 0x0001, 0x27ba: 0x0001, 0x27bb: 0x0001, + 0x27bc: 0x0001, 0x27bd: 0x0001, 0x27be: 0x0001, 0x27bf: 0x0001, + // Block 0x9f, offset 0x27c0 + 0x27c0: 0x0001, 0x27c1: 0x0001, 0x27c2: 0x0001, 0x27c3: 0x0001, 0x27c4: 0x0001, 0x27c5: 0x0001, + 0x27c6: 0x0001, 0x27c7: 0x0001, 0x27c8: 0x0001, 0x27c9: 0x0001, 0x27ca: 0x0001, 0x27cb: 0x0001, + 0x27cc: 0x0001, 0x27cd: 0x0001, 0x27ce: 0x0001, 0x27cf: 0x0001, 0x27d0: 0x0001, 0x27d1: 0x0001, + 0x27d2: 0x0001, 0x27d3: 0x0001, 0x27d4: 0x0001, 0x27d5: 0x0001, 0x27d6: 0x0001, 0x27d7: 0x0001, + 0x27d8: 0x0001, 0x27d9: 0x0001, 0x27da: 0x0001, 0x27db: 0x0001, 0x27dc: 0x0001, 0x27dd: 0x0001, + 0x27de: 0x0001, 0x27df: 0x0001, 0x27e0: 0x0001, 0x27e1: 0x0001, 0x27e2: 0x0001, 0x27e3: 0x0001, + 0x27e4: 0x0001, 0x27e5: 0x0001, 0x27e6: 0x0001, 0x27e7: 0x0001, 0x27e8: 0x0001, 0x27e9: 0x0001, + 0x27ea: 0x0001, 0x27eb: 0x0001, 0x27ec: 0x0001, 0x27ed: 0x0001, 0x27ee: 0x0001, 0x27ef: 0x0001, + 0x27f0: 0x0001, 0x27f1: 0x0001, 0x27f2: 0x0001, 0x27f3: 0x0001, 0x27f4: 0x0001, 0x27f5: 0x0001, + 0x27f6: 0x0001, 0x27f7: 0x0001, 0x27f8: 0x0001, 0x27f9: 0x000a, 0x27fa: 0x000a, 0x27fb: 0x000a, + 0x27fc: 0x000a, 0x27fd: 0x000a, 0x27fe: 0x000a, 0x27ff: 0x000a, + // Block 0xa0, offset 0x2800 + 0x2800: 0x000d, 0x2801: 0x000d, 0x2802: 0x000d, 0x2803: 0x000d, 0x2804: 0x000d, 0x2805: 0x000d, + 0x2806: 0x000d, 0x2807: 0x000d, 0x2808: 0x000d, 0x2809: 0x000d, 0x280a: 0x000d, 0x280b: 0x000d, + 0x280c: 0x000d, 0x280d: 0x000d, 0x280e: 0x000d, 0x280f: 0x000d, 0x2810: 0x000d, 0x2811: 0x000d, + 0x2812: 0x000d, 0x2813: 0x000d, 0x2814: 0x000d, 0x2815: 0x000d, 0x2816: 0x000d, 0x2817: 0x000d, + 0x2818: 0x000d, 0x2819: 0x000d, 0x281a: 0x000d, 0x281b: 0x000d, 0x281c: 0x000d, 0x281d: 0x000d, + 0x281e: 0x000d, 0x281f: 0x000d, 0x2820: 0x000d, 0x2821: 0x000d, 0x2822: 0x000d, 0x2823: 0x000d, + 0x2824: 0x000c, 0x2825: 0x000c, 0x2826: 0x000c, 0x2827: 0x000c, 0x2828: 0x000d, 0x2829: 0x000d, + 0x282a: 0x000d, 0x282b: 0x000d, 0x282c: 0x000d, 0x282d: 0x000d, 0x282e: 0x000d, 0x282f: 0x000d, + 0x2830: 0x0005, 0x2831: 0x0005, 0x2832: 0x0005, 0x2833: 0x0005, 0x2834: 0x0005, 0x2835: 0x0005, + 0x2836: 0x0005, 0x2837: 0x0005, 0x2838: 0x0005, 0x2839: 0x0005, 0x283a: 0x000d, 0x283b: 0x000d, + 0x283c: 0x000d, 0x283d: 0x000d, 0x283e: 0x000d, 0x283f: 0x000d, + // Block 0xa1, offset 0x2840 + 0x2840: 0x0001, 0x2841: 0x0001, 0x2842: 0x0001, 0x2843: 0x0001, 0x2844: 0x0001, 0x2845: 0x0001, + 0x2846: 0x0001, 0x2847: 0x0001, 0x2848: 0x0001, 0x2849: 0x0001, 0x284a: 0x0001, 0x284b: 0x0001, + 0x284c: 0x0001, 0x284d: 0x0001, 0x284e: 0x0001, 0x284f: 0x0001, 0x2850: 0x0001, 0x2851: 0x0001, + 0x2852: 0x0001, 0x2853: 0x0001, 0x2854: 0x0001, 0x2855: 0x0001, 0x2856: 0x0001, 0x2857: 0x0001, + 0x2858: 0x0001, 0x2859: 0x0001, 0x285a: 0x0001, 0x285b: 0x0001, 0x285c: 0x0001, 0x285d: 0x0001, + 0x285e: 0x0001, 0x285f: 0x0001, 0x2860: 0x0005, 0x2861: 0x0005, 0x2862: 0x0005, 0x2863: 0x0005, + 0x2864: 0x0005, 0x2865: 0x0005, 0x2866: 0x0005, 0x2867: 0x0005, 0x2868: 0x0005, 0x2869: 0x0005, + 0x286a: 0x0005, 0x286b: 0x0005, 0x286c: 0x0005, 0x286d: 0x0005, 0x286e: 0x0005, 0x286f: 0x0005, + 0x2870: 0x0005, 0x2871: 0x0005, 0x2872: 0x0005, 0x2873: 0x0005, 0x2874: 0x0005, 0x2875: 0x0005, + 0x2876: 0x0005, 0x2877: 0x0005, 0x2878: 0x0005, 0x2879: 0x0005, 0x287a: 0x0005, 0x287b: 0x0005, + 0x287c: 0x0005, 0x287d: 0x0005, 0x287e: 0x0005, 0x287f: 0x0001, + // Block 0xa2, offset 0x2880 + 0x2880: 0x0001, 0x2881: 0x0001, 0x2882: 0x0001, 0x2883: 0x0001, 0x2884: 0x0001, 0x2885: 0x0001, + 0x2886: 0x0001, 0x2887: 0x0001, 0x2888: 0x0001, 0x2889: 0x0001, 0x288a: 0x0001, 0x288b: 0x0001, + 0x288c: 0x0001, 0x288d: 0x0001, 0x288e: 0x0001, 0x288f: 0x0001, 0x2890: 0x0001, 0x2891: 0x0001, + 0x2892: 0x0001, 0x2893: 0x0001, 0x2894: 0x0001, 0x2895: 0x0001, 0x2896: 0x0001, 0x2897: 0x0001, + 0x2898: 0x0001, 0x2899: 0x0001, 0x289a: 0x0001, 0x289b: 0x0001, 0x289c: 0x0001, 0x289d: 0x0001, + 0x289e: 0x0001, 0x289f: 0x0001, 0x28a0: 0x0001, 0x28a1: 0x0001, 0x28a2: 0x0001, 0x28a3: 0x0001, + 0x28a4: 0x0001, 0x28a5: 0x0001, 0x28a6: 0x0001, 0x28a7: 0x0001, 0x28a8: 0x0001, 0x28a9: 0x0001, + 0x28aa: 0x0001, 0x28ab: 0x0001, 0x28ac: 0x0001, 0x28ad: 0x0001, 0x28ae: 0x0001, 0x28af: 0x0001, + 0x28b0: 0x000d, 0x28b1: 0x000d, 0x28b2: 0x000d, 0x28b3: 0x000d, 0x28b4: 0x000d, 0x28b5: 0x000d, + 0x28b6: 0x000d, 0x28b7: 0x000d, 0x28b8: 0x000d, 0x28b9: 0x000d, 0x28ba: 0x000d, 0x28bb: 0x000d, + 0x28bc: 0x000d, 0x28bd: 0x000d, 0x28be: 0x000d, 0x28bf: 0x000d, + // Block 0xa3, offset 0x28c0 + 0x28c0: 0x000d, 0x28c1: 0x000d, 0x28c2: 0x000d, 0x28c3: 0x000d, 0x28c4: 0x000d, 0x28c5: 0x000d, + 0x28c6: 0x000c, 0x28c7: 0x000c, 0x28c8: 0x000c, 0x28c9: 0x000c, 0x28ca: 0x000c, 0x28cb: 0x000c, + 0x28cc: 0x000c, 0x28cd: 0x000c, 0x28ce: 0x000c, 0x28cf: 0x000c, 0x28d0: 0x000c, 0x28d1: 0x000d, + 0x28d2: 0x000d, 0x28d3: 0x000d, 0x28d4: 0x000d, 0x28d5: 0x000d, 0x28d6: 0x000d, 0x28d7: 0x000d, + 0x28d8: 0x000d, 0x28d9: 0x000d, 0x28da: 0x000d, 0x28db: 0x000d, 0x28dc: 0x000d, 0x28dd: 0x000d, + 0x28de: 0x000d, 0x28df: 0x000d, 0x28e0: 0x000d, 0x28e1: 0x000d, 0x28e2: 0x000d, 0x28e3: 0x000d, + 0x28e4: 0x000d, 0x28e5: 0x000d, 0x28e6: 0x000d, 0x28e7: 0x000d, 0x28e8: 0x000d, 0x28e9: 0x000d, + 0x28ea: 0x000d, 0x28eb: 0x000d, 0x28ec: 0x000d, 0x28ed: 0x000d, 0x28ee: 0x000d, 0x28ef: 0x000d, + 0x28f0: 0x0001, 0x28f1: 0x0001, 0x28f2: 0x0001, 0x28f3: 0x0001, 0x28f4: 0x0001, 0x28f5: 0x0001, + 0x28f6: 0x0001, 0x28f7: 0x0001, 0x28f8: 0x0001, 0x28f9: 0x0001, 0x28fa: 0x0001, 0x28fb: 0x0001, + 0x28fc: 0x0001, 0x28fd: 0x0001, 0x28fe: 0x0001, 0x28ff: 0x0001, + // Block 0xa4, offset 0x2900 + 0x2901: 0x000c, + 0x2938: 0x000c, 0x2939: 0x000c, 0x293a: 0x000c, 0x293b: 0x000c, + 0x293c: 0x000c, 0x293d: 0x000c, 0x293e: 0x000c, 0x293f: 0x000c, + // Block 0xa5, offset 0x2940 + 0x2940: 0x000c, 0x2941: 0x000c, 0x2942: 0x000c, 0x2943: 0x000c, 0x2944: 0x000c, 0x2945: 0x000c, + 0x2946: 0x000c, + 0x2952: 0x000a, 0x2953: 0x000a, 0x2954: 0x000a, 0x2955: 0x000a, 0x2956: 0x000a, 0x2957: 0x000a, + 0x2958: 0x000a, 0x2959: 0x000a, 0x295a: 0x000a, 0x295b: 0x000a, 0x295c: 0x000a, 0x295d: 0x000a, + 0x295e: 0x000a, 0x295f: 0x000a, 0x2960: 0x000a, 0x2961: 0x000a, 0x2962: 0x000a, 0x2963: 0x000a, + 0x2964: 0x000a, 0x2965: 0x000a, + 0x297f: 0x000c, + // Block 0xa6, offset 0x2980 + 0x2980: 0x000c, 0x2981: 0x000c, + 0x29b3: 0x000c, 0x29b4: 0x000c, 0x29b5: 0x000c, + 0x29b6: 0x000c, 0x29b9: 0x000c, 0x29ba: 0x000c, + // Block 0xa7, offset 0x29c0 + 0x29c0: 0x000c, 0x29c1: 0x000c, 0x29c2: 0x000c, + 0x29e7: 0x000c, 0x29e8: 0x000c, 0x29e9: 0x000c, + 0x29ea: 0x000c, 0x29eb: 0x000c, 0x29ed: 0x000c, 0x29ee: 0x000c, 0x29ef: 0x000c, + 0x29f0: 0x000c, 0x29f1: 0x000c, 0x29f2: 0x000c, 0x29f3: 0x000c, 0x29f4: 0x000c, + // Block 0xa8, offset 0x2a00 + 0x2a33: 0x000c, + // Block 0xa9, offset 0x2a40 + 0x2a40: 0x000c, 0x2a41: 0x000c, + 0x2a76: 0x000c, 0x2a77: 0x000c, 0x2a78: 0x000c, 0x2a79: 0x000c, 0x2a7a: 0x000c, 0x2a7b: 0x000c, + 0x2a7c: 0x000c, 0x2a7d: 0x000c, 0x2a7e: 0x000c, + // Block 0xaa, offset 0x2a80 + 0x2a89: 0x000c, 0x2a8a: 0x000c, 0x2a8b: 0x000c, + 0x2a8c: 0x000c, + // Block 0xab, offset 0x2ac0 + 0x2aef: 0x000c, + 0x2af0: 0x000c, 0x2af1: 0x000c, 0x2af4: 0x000c, + 0x2af6: 0x000c, 0x2af7: 0x000c, + 0x2afe: 0x000c, + // Block 0xac, offset 0x2b00 + 0x2b1f: 0x000c, 0x2b23: 0x000c, + 0x2b24: 0x000c, 0x2b25: 0x000c, 0x2b26: 0x000c, 0x2b27: 0x000c, 0x2b28: 0x000c, 0x2b29: 0x000c, + 0x2b2a: 0x000c, + // Block 0xad, offset 0x2b40 + 0x2b40: 0x000c, + 0x2b66: 0x000c, 0x2b67: 0x000c, 0x2b68: 0x000c, 0x2b69: 0x000c, + 0x2b6a: 0x000c, 0x2b6b: 0x000c, 0x2b6c: 0x000c, + 0x2b70: 0x000c, 0x2b71: 0x000c, 0x2b72: 0x000c, 0x2b73: 0x000c, 0x2b74: 0x000c, + // Block 0xae, offset 0x2b80 + 0x2bb8: 0x000c, 0x2bb9: 0x000c, 0x2bba: 0x000c, 0x2bbb: 0x000c, + 0x2bbc: 0x000c, 0x2bbd: 0x000c, 0x2bbe: 0x000c, 0x2bbf: 0x000c, + // Block 0xaf, offset 0x2bc0 + 0x2bc2: 0x000c, 0x2bc3: 0x000c, 0x2bc4: 0x000c, + 0x2bc6: 0x000c, + 0x2bde: 0x000c, + // Block 0xb0, offset 0x2c00 + 0x2c33: 0x000c, 0x2c34: 0x000c, 0x2c35: 0x000c, + 0x2c36: 0x000c, 0x2c37: 0x000c, 0x2c38: 0x000c, 0x2c3a: 0x000c, + 0x2c3f: 0x000c, + // Block 0xb1, offset 0x2c40 + 0x2c40: 0x000c, 0x2c42: 0x000c, 0x2c43: 0x000c, + // Block 0xb2, offset 0x2c80 + 0x2cb2: 0x000c, 0x2cb3: 0x000c, 0x2cb4: 0x000c, 0x2cb5: 0x000c, + 0x2cbc: 0x000c, 0x2cbd: 0x000c, 0x2cbf: 0x000c, + // Block 0xb3, offset 0x2cc0 + 0x2cc0: 0x000c, + 0x2cdc: 0x000c, 0x2cdd: 0x000c, + // Block 0xb4, offset 0x2d00 + 0x2d33: 0x000c, 0x2d34: 0x000c, 0x2d35: 0x000c, + 0x2d36: 0x000c, 0x2d37: 0x000c, 0x2d38: 0x000c, 0x2d39: 0x000c, 0x2d3a: 0x000c, + 0x2d3d: 0x000c, 0x2d3f: 0x000c, + // Block 0xb5, offset 0x2d40 + 0x2d40: 0x000c, + 0x2d60: 0x000a, 0x2d61: 0x000a, 0x2d62: 0x000a, 0x2d63: 0x000a, + 0x2d64: 0x000a, 0x2d65: 0x000a, 0x2d66: 0x000a, 0x2d67: 0x000a, 0x2d68: 0x000a, 0x2d69: 0x000a, + 0x2d6a: 0x000a, 0x2d6b: 0x000a, 0x2d6c: 0x000a, + // Block 0xb6, offset 0x2d80 + 0x2dab: 0x000c, 0x2dad: 0x000c, + 0x2db0: 0x000c, 0x2db1: 0x000c, 0x2db2: 0x000c, 0x2db3: 0x000c, 0x2db4: 0x000c, 0x2db5: 0x000c, + 0x2db7: 0x000c, + // Block 0xb7, offset 0x2dc0 + 0x2ddd: 0x000c, + 0x2dde: 0x000c, 0x2ddf: 0x000c, 0x2de2: 0x000c, 0x2de3: 0x000c, + 0x2de4: 0x000c, 0x2de5: 0x000c, 0x2de7: 0x000c, 0x2de8: 0x000c, 0x2de9: 0x000c, + 0x2dea: 0x000c, 0x2deb: 0x000c, + // Block 0xb8, offset 0x2e00 + 0x2e2f: 0x000c, + 0x2e30: 0x000c, 0x2e31: 0x000c, 0x2e32: 0x000c, 0x2e33: 0x000c, 0x2e34: 0x000c, 0x2e35: 0x000c, + 0x2e36: 0x000c, 0x2e37: 0x000c, 0x2e39: 0x000c, 0x2e3a: 0x000c, + // Block 0xb9, offset 0x2e40 + 0x2e54: 0x000c, 0x2e55: 0x000c, 0x2e56: 0x000c, 0x2e57: 0x000c, + 0x2e5a: 0x000c, 0x2e5b: 0x000c, + 0x2e60: 0x000c, + // Block 0xba, offset 0x2e80 + 0x2e81: 0x000c, 0x2e82: 0x000c, 0x2e83: 0x000c, 0x2e84: 0x000c, 0x2e85: 0x000c, + 0x2e86: 0x000c, 0x2e89: 0x000c, 0x2e8a: 0x000c, + 0x2eb3: 0x000c, 0x2eb4: 0x000c, 0x2eb5: 0x000c, + 0x2eb6: 0x000c, 0x2eb7: 0x000c, 0x2eb8: 0x000c, 0x2ebb: 0x000c, + 0x2ebc: 0x000c, 0x2ebd: 0x000c, 0x2ebe: 0x000c, + // Block 0xbb, offset 0x2ec0 + 0x2ec7: 0x000c, + 0x2ed1: 0x000c, + 0x2ed2: 0x000c, 0x2ed3: 0x000c, 0x2ed4: 0x000c, 0x2ed5: 0x000c, 0x2ed6: 0x000c, + 0x2ed9: 0x000c, 0x2eda: 0x000c, 0x2edb: 0x000c, + // Block 0xbc, offset 0x2f00 + 0x2f0a: 0x000c, 0x2f0b: 0x000c, + 0x2f0c: 0x000c, 0x2f0d: 0x000c, 0x2f0e: 0x000c, 0x2f0f: 0x000c, 0x2f10: 0x000c, 0x2f11: 0x000c, + 0x2f12: 0x000c, 0x2f13: 0x000c, 0x2f14: 0x000c, 0x2f15: 0x000c, 0x2f16: 0x000c, + 0x2f18: 0x000c, 0x2f19: 0x000c, + // Block 0xbd, offset 0x2f40 + 0x2f70: 0x000c, 0x2f71: 0x000c, 0x2f72: 0x000c, 0x2f73: 0x000c, 0x2f74: 0x000c, 0x2f75: 0x000c, + 0x2f76: 0x000c, 0x2f78: 0x000c, 0x2f79: 0x000c, 0x2f7a: 0x000c, 0x2f7b: 0x000c, + 0x2f7c: 0x000c, 0x2f7d: 0x000c, + // Block 0xbe, offset 0x2f80 + 0x2f92: 0x000c, 0x2f93: 0x000c, 0x2f94: 0x000c, 0x2f95: 0x000c, 0x2f96: 0x000c, 0x2f97: 0x000c, + 0x2f98: 0x000c, 0x2f99: 0x000c, 0x2f9a: 0x000c, 0x2f9b: 0x000c, 0x2f9c: 0x000c, 0x2f9d: 0x000c, + 0x2f9e: 0x000c, 0x2f9f: 0x000c, 0x2fa0: 0x000c, 0x2fa1: 0x000c, 0x2fa2: 0x000c, 0x2fa3: 0x000c, + 0x2fa4: 0x000c, 0x2fa5: 0x000c, 0x2fa6: 0x000c, 0x2fa7: 0x000c, + 0x2faa: 0x000c, 0x2fab: 0x000c, 0x2fac: 0x000c, 0x2fad: 0x000c, 0x2fae: 0x000c, 0x2faf: 0x000c, + 0x2fb0: 0x000c, 0x2fb2: 0x000c, 0x2fb3: 0x000c, 0x2fb5: 0x000c, + 0x2fb6: 0x000c, + // Block 0xbf, offset 0x2fc0 + 0x2ff1: 0x000c, 0x2ff2: 0x000c, 0x2ff3: 0x000c, 0x2ff4: 0x000c, 0x2ff5: 0x000c, + 0x2ff6: 0x000c, 0x2ffa: 0x000c, + 0x2ffc: 0x000c, 0x2ffd: 0x000c, 0x2fff: 0x000c, + // Block 0xc0, offset 0x3000 + 0x3000: 0x000c, 0x3001: 0x000c, 0x3002: 0x000c, 0x3003: 0x000c, 0x3004: 0x000c, 0x3005: 0x000c, + 0x3007: 0x000c, + // Block 0xc1, offset 0x3040 + 0x3050: 0x000c, 0x3051: 0x000c, + 0x3055: 0x000c, 0x3057: 0x000c, + // Block 0xc2, offset 0x3080 + 0x30b3: 0x000c, 0x30b4: 0x000c, + // Block 0xc3, offset 0x30c0 + 0x30d5: 0x000a, 0x30d6: 0x000a, 0x30d7: 0x000a, + 0x30d8: 0x000a, 0x30d9: 0x000a, 0x30da: 0x000a, 0x30db: 0x000a, 0x30dc: 0x000a, 0x30dd: 0x0004, + 0x30de: 0x0004, 0x30df: 0x0004, 0x30e0: 0x0004, 0x30e1: 0x000a, 0x30e2: 0x000a, 0x30e3: 0x000a, + 0x30e4: 0x000a, 0x30e5: 0x000a, 0x30e6: 0x000a, 0x30e7: 0x000a, 0x30e8: 0x000a, 0x30e9: 0x000a, + 0x30ea: 0x000a, 0x30eb: 0x000a, 0x30ec: 0x000a, 0x30ed: 0x000a, 0x30ee: 0x000a, 0x30ef: 0x000a, + 0x30f0: 0x000a, 0x30f1: 0x000a, + // Block 0xc4, offset 0x3100 + 0x3130: 0x000c, 0x3131: 0x000c, 0x3132: 0x000c, 0x3133: 0x000c, 0x3134: 0x000c, + // Block 0xc5, offset 0x3140 + 0x3170: 0x000c, 0x3171: 0x000c, 0x3172: 0x000c, 0x3173: 0x000c, 0x3174: 0x000c, 0x3175: 0x000c, + 0x3176: 0x000c, + // Block 0xc6, offset 0x3180 + 0x318f: 0x000c, + // Block 0xc7, offset 0x31c0 + 0x31cf: 0x000c, 0x31d0: 0x000c, 0x31d1: 0x000c, + 0x31d2: 0x000c, + // Block 0xc8, offset 0x3200 + 0x3222: 0x000a, + // Block 0xc9, offset 0x3240 + 0x325d: 0x000c, + 0x325e: 0x000c, 0x3260: 0x000b, 0x3261: 0x000b, 0x3262: 0x000b, 0x3263: 0x000b, + // Block 0xca, offset 0x3280 + 0x32a7: 0x000c, 0x32a8: 0x000c, 0x32a9: 0x000c, + 0x32b3: 0x000b, 0x32b4: 0x000b, 0x32b5: 0x000b, + 0x32b6: 0x000b, 0x32b7: 0x000b, 0x32b8: 0x000b, 0x32b9: 0x000b, 0x32ba: 0x000b, 0x32bb: 0x000c, + 0x32bc: 0x000c, 0x32bd: 0x000c, 0x32be: 0x000c, 0x32bf: 0x000c, + // Block 0xcb, offset 0x32c0 + 0x32c0: 0x000c, 0x32c1: 0x000c, 0x32c2: 0x000c, 0x32c5: 0x000c, + 0x32c6: 0x000c, 0x32c7: 0x000c, 0x32c8: 0x000c, 0x32c9: 0x000c, 0x32ca: 0x000c, 0x32cb: 0x000c, + 0x32ea: 0x000c, 0x32eb: 0x000c, 0x32ec: 0x000c, 0x32ed: 0x000c, + // Block 0xcc, offset 0x3300 + 0x3300: 0x000a, 0x3301: 0x000a, 0x3302: 0x000c, 0x3303: 0x000c, 0x3304: 0x000c, 0x3305: 0x000a, + // Block 0xcd, offset 0x3340 + 0x3340: 0x000a, 0x3341: 0x000a, 0x3342: 0x000a, 0x3343: 0x000a, 0x3344: 0x000a, 0x3345: 0x000a, + 0x3346: 0x000a, 0x3347: 0x000a, 0x3348: 0x000a, 0x3349: 0x000a, 0x334a: 0x000a, 0x334b: 0x000a, + 0x334c: 0x000a, 0x334d: 0x000a, 0x334e: 0x000a, 0x334f: 0x000a, 0x3350: 0x000a, 0x3351: 0x000a, + 0x3352: 0x000a, 0x3353: 0x000a, 0x3354: 0x000a, 0x3355: 0x000a, 0x3356: 0x000a, + // Block 0xce, offset 0x3380 + 0x339b: 0x000a, + // Block 0xcf, offset 0x33c0 + 0x33d5: 0x000a, + // Block 0xd0, offset 0x3400 + 0x340f: 0x000a, + // Block 0xd1, offset 0x3440 + 0x3449: 0x000a, + // Block 0xd2, offset 0x3480 + 0x3483: 0x000a, + 0x348e: 0x0002, 0x348f: 0x0002, 0x3490: 0x0002, 0x3491: 0x0002, + 0x3492: 0x0002, 0x3493: 0x0002, 0x3494: 0x0002, 0x3495: 0x0002, 0x3496: 0x0002, 0x3497: 0x0002, + 0x3498: 0x0002, 0x3499: 0x0002, 0x349a: 0x0002, 0x349b: 0x0002, 0x349c: 0x0002, 0x349d: 0x0002, + 0x349e: 0x0002, 0x349f: 0x0002, 0x34a0: 0x0002, 0x34a1: 0x0002, 0x34a2: 0x0002, 0x34a3: 0x0002, + 0x34a4: 0x0002, 0x34a5: 0x0002, 0x34a6: 0x0002, 0x34a7: 0x0002, 0x34a8: 0x0002, 0x34a9: 0x0002, + 0x34aa: 0x0002, 0x34ab: 0x0002, 0x34ac: 0x0002, 0x34ad: 0x0002, 0x34ae: 0x0002, 0x34af: 0x0002, + 0x34b0: 0x0002, 0x34b1: 0x0002, 0x34b2: 0x0002, 0x34b3: 0x0002, 0x34b4: 0x0002, 0x34b5: 0x0002, + 0x34b6: 0x0002, 0x34b7: 0x0002, 0x34b8: 0x0002, 0x34b9: 0x0002, 0x34ba: 0x0002, 0x34bb: 0x0002, + 0x34bc: 0x0002, 0x34bd: 0x0002, 0x34be: 0x0002, 0x34bf: 0x0002, + // Block 0xd3, offset 0x34c0 + 0x34c0: 0x000c, 0x34c1: 0x000c, 0x34c2: 0x000c, 0x34c3: 0x000c, 0x34c4: 0x000c, 0x34c5: 0x000c, + 0x34c6: 0x000c, 0x34c7: 0x000c, 0x34c8: 0x000c, 0x34c9: 0x000c, 0x34ca: 0x000c, 0x34cb: 0x000c, + 0x34cc: 0x000c, 0x34cd: 0x000c, 0x34ce: 0x000c, 0x34cf: 0x000c, 0x34d0: 0x000c, 0x34d1: 0x000c, + 0x34d2: 0x000c, 0x34d3: 0x000c, 0x34d4: 0x000c, 0x34d5: 0x000c, 0x34d6: 0x000c, 0x34d7: 0x000c, + 0x34d8: 0x000c, 0x34d9: 0x000c, 0x34da: 0x000c, 0x34db: 0x000c, 0x34dc: 0x000c, 0x34dd: 0x000c, + 0x34de: 0x000c, 0x34df: 0x000c, 0x34e0: 0x000c, 0x34e1: 0x000c, 0x34e2: 0x000c, 0x34e3: 0x000c, + 0x34e4: 0x000c, 0x34e5: 0x000c, 0x34e6: 0x000c, 0x34e7: 0x000c, 0x34e8: 0x000c, 0x34e9: 0x000c, + 0x34ea: 0x000c, 0x34eb: 0x000c, 0x34ec: 0x000c, 0x34ed: 0x000c, 0x34ee: 0x000c, 0x34ef: 0x000c, + 0x34f0: 0x000c, 0x34f1: 0x000c, 0x34f2: 0x000c, 0x34f3: 0x000c, 0x34f4: 0x000c, 0x34f5: 0x000c, + 0x34f6: 0x000c, 0x34fb: 0x000c, + 0x34fc: 0x000c, 0x34fd: 0x000c, 0x34fe: 0x000c, 0x34ff: 0x000c, + // Block 0xd4, offset 0x3500 + 0x3500: 0x000c, 0x3501: 0x000c, 0x3502: 0x000c, 0x3503: 0x000c, 0x3504: 0x000c, 0x3505: 0x000c, + 0x3506: 0x000c, 0x3507: 0x000c, 0x3508: 0x000c, 0x3509: 0x000c, 0x350a: 0x000c, 0x350b: 0x000c, + 0x350c: 0x000c, 0x350d: 0x000c, 0x350e: 0x000c, 0x350f: 0x000c, 0x3510: 0x000c, 0x3511: 0x000c, + 0x3512: 0x000c, 0x3513: 0x000c, 0x3514: 0x000c, 0x3515: 0x000c, 0x3516: 0x000c, 0x3517: 0x000c, + 0x3518: 0x000c, 0x3519: 0x000c, 0x351a: 0x000c, 0x351b: 0x000c, 0x351c: 0x000c, 0x351d: 0x000c, + 0x351e: 0x000c, 0x351f: 0x000c, 0x3520: 0x000c, 0x3521: 0x000c, 0x3522: 0x000c, 0x3523: 0x000c, + 0x3524: 0x000c, 0x3525: 0x000c, 0x3526: 0x000c, 0x3527: 0x000c, 0x3528: 0x000c, 0x3529: 0x000c, + 0x352a: 0x000c, 0x352b: 0x000c, 0x352c: 0x000c, + 0x3535: 0x000c, + // Block 0xd5, offset 0x3540 + 0x3544: 0x000c, + 0x355b: 0x000c, 0x355c: 0x000c, 0x355d: 0x000c, + 0x355e: 0x000c, 0x355f: 0x000c, 0x3561: 0x000c, 0x3562: 0x000c, 0x3563: 0x000c, + 0x3564: 0x000c, 0x3565: 0x000c, 0x3566: 0x000c, 0x3567: 0x000c, 0x3568: 0x000c, 0x3569: 0x000c, + 0x356a: 0x000c, 0x356b: 0x000c, 0x356c: 0x000c, 0x356d: 0x000c, 0x356e: 0x000c, 0x356f: 0x000c, + // Block 0xd6, offset 0x3580 + 0x3580: 0x000c, 0x3581: 0x000c, 0x3582: 0x000c, 0x3583: 0x000c, 0x3584: 0x000c, 0x3585: 0x000c, + 0x3586: 0x000c, 0x3588: 0x000c, 0x3589: 0x000c, 0x358a: 0x000c, 0x358b: 0x000c, + 0x358c: 0x000c, 0x358d: 0x000c, 0x358e: 0x000c, 0x358f: 0x000c, 0x3590: 0x000c, 0x3591: 0x000c, + 0x3592: 0x000c, 0x3593: 0x000c, 0x3594: 0x000c, 0x3595: 0x000c, 0x3596: 0x000c, 0x3597: 0x000c, + 0x3598: 0x000c, 0x359b: 0x000c, 0x359c: 0x000c, 0x359d: 0x000c, + 0x359e: 0x000c, 0x359f: 0x000c, 0x35a0: 0x000c, 0x35a1: 0x000c, 0x35a3: 0x000c, + 0x35a4: 0x000c, 0x35a6: 0x000c, 0x35a7: 0x000c, 0x35a8: 0x000c, 0x35a9: 0x000c, + 0x35aa: 0x000c, + // Block 0xd7, offset 0x35c0 + 0x35ec: 0x000c, 0x35ed: 0x000c, 0x35ee: 0x000c, 0x35ef: 0x000c, + 0x35ff: 0x0004, + // Block 0xd8, offset 0x3600 + 0x3600: 0x0001, 0x3601: 0x0001, 0x3602: 0x0001, 0x3603: 0x0001, 0x3604: 0x0001, 0x3605: 0x0001, + 0x3606: 0x0001, 0x3607: 0x0001, 0x3608: 0x0001, 0x3609: 0x0001, 0x360a: 0x0001, 0x360b: 0x0001, + 0x360c: 0x0001, 0x360d: 0x0001, 0x360e: 0x0001, 0x360f: 0x0001, 0x3610: 0x000c, 0x3611: 0x000c, + 0x3612: 0x000c, 0x3613: 0x000c, 0x3614: 0x000c, 0x3615: 0x000c, 0x3616: 0x000c, 0x3617: 0x0001, + 0x3618: 0x0001, 0x3619: 0x0001, 0x361a: 0x0001, 0x361b: 0x0001, 0x361c: 0x0001, 0x361d: 0x0001, + 0x361e: 0x0001, 0x361f: 0x0001, 0x3620: 0x0001, 0x3621: 0x0001, 0x3622: 0x0001, 0x3623: 0x0001, + 0x3624: 0x0001, 0x3625: 0x0001, 0x3626: 0x0001, 0x3627: 0x0001, 0x3628: 0x0001, 0x3629: 0x0001, + 0x362a: 0x0001, 0x362b: 0x0001, 0x362c: 0x0001, 0x362d: 0x0001, 0x362e: 0x0001, 0x362f: 0x0001, + 0x3630: 0x0001, 0x3631: 0x0001, 0x3632: 0x0001, 0x3633: 0x0001, 0x3634: 0x0001, 0x3635: 0x0001, + 0x3636: 0x0001, 0x3637: 0x0001, 0x3638: 0x0001, 0x3639: 0x0001, 0x363a: 0x0001, 0x363b: 0x0001, + 0x363c: 0x0001, 0x363d: 0x0001, 0x363e: 0x0001, 0x363f: 0x0001, + // Block 0xd9, offset 0x3640 + 0x3640: 0x0001, 0x3641: 0x0001, 0x3642: 0x0001, 0x3643: 0x0001, 0x3644: 0x000c, 0x3645: 0x000c, + 0x3646: 0x000c, 0x3647: 0x000c, 0x3648: 0x000c, 0x3649: 0x000c, 0x364a: 0x000c, 0x364b: 0x0001, + 0x364c: 0x0001, 0x364d: 0x0001, 0x364e: 0x0001, 0x364f: 0x0001, 0x3650: 0x0001, 0x3651: 0x0001, + 0x3652: 0x0001, 0x3653: 0x0001, 0x3654: 0x0001, 0x3655: 0x0001, 0x3656: 0x0001, 0x3657: 0x0001, + 0x3658: 0x0001, 0x3659: 0x0001, 0x365a: 0x0001, 0x365b: 0x0001, 0x365c: 0x0001, 0x365d: 0x0001, + 0x365e: 0x0001, 0x365f: 0x0001, 0x3660: 0x0001, 0x3661: 0x0001, 0x3662: 0x0001, 0x3663: 0x0001, + 0x3664: 0x0001, 0x3665: 0x0001, 0x3666: 0x0001, 0x3667: 0x0001, 0x3668: 0x0001, 0x3669: 0x0001, + 0x366a: 0x0001, 0x366b: 0x0001, 0x366c: 0x0001, 0x366d: 0x0001, 0x366e: 0x0001, 0x366f: 0x0001, + 0x3670: 0x0001, 0x3671: 0x0001, 0x3672: 0x0001, 0x3673: 0x0001, 0x3674: 0x0001, 0x3675: 0x0001, + 0x3676: 0x0001, 0x3677: 0x0001, 0x3678: 0x0001, 0x3679: 0x0001, 0x367a: 0x0001, 0x367b: 0x0001, + 0x367c: 0x0001, 0x367d: 0x0001, 0x367e: 0x0001, 0x367f: 0x0001, + // Block 0xda, offset 0x3680 + 0x3680: 0x000d, 0x3681: 0x000d, 0x3682: 0x000d, 0x3683: 0x000d, 0x3684: 0x000d, 0x3685: 0x000d, + 0x3686: 0x000d, 0x3687: 0x000d, 0x3688: 0x000d, 0x3689: 0x000d, 0x368a: 0x000d, 0x368b: 0x000d, + 0x368c: 0x000d, 0x368d: 0x000d, 0x368e: 0x000d, 0x368f: 0x000d, 0x3690: 0x0001, 0x3691: 0x0001, + 0x3692: 0x0001, 0x3693: 0x0001, 0x3694: 0x0001, 0x3695: 0x0001, 0x3696: 0x0001, 0x3697: 0x0001, + 0x3698: 0x0001, 0x3699: 0x0001, 0x369a: 0x0001, 0x369b: 0x0001, 0x369c: 0x0001, 0x369d: 0x0001, + 0x369e: 0x0001, 0x369f: 0x0001, 0x36a0: 0x0001, 0x36a1: 0x0001, 0x36a2: 0x0001, 0x36a3: 0x0001, + 0x36a4: 0x0001, 0x36a5: 0x0001, 0x36a6: 0x0001, 0x36a7: 0x0001, 0x36a8: 0x0001, 0x36a9: 0x0001, + 0x36aa: 0x0001, 0x36ab: 0x0001, 0x36ac: 0x0001, 0x36ad: 0x0001, 0x36ae: 0x0001, 0x36af: 0x0001, + 0x36b0: 0x0001, 0x36b1: 0x0001, 0x36b2: 0x0001, 0x36b3: 0x0001, 0x36b4: 0x0001, 0x36b5: 0x0001, + 0x36b6: 0x0001, 0x36b7: 0x0001, 0x36b8: 0x0001, 0x36b9: 0x0001, 0x36ba: 0x0001, 0x36bb: 0x0001, + 0x36bc: 0x0001, 0x36bd: 0x0001, 0x36be: 0x0001, 0x36bf: 0x0001, + // Block 0xdb, offset 0x36c0 + 0x36c0: 0x000d, 0x36c1: 0x000d, 0x36c2: 0x000d, 0x36c3: 0x000d, 0x36c4: 0x000d, 0x36c5: 0x000d, + 0x36c6: 0x000d, 0x36c7: 0x000d, 0x36c8: 0x000d, 0x36c9: 0x000d, 0x36ca: 0x000d, 0x36cb: 0x000d, + 0x36cc: 0x000d, 0x36cd: 0x000d, 0x36ce: 0x000d, 0x36cf: 0x000d, 0x36d0: 0x000d, 0x36d1: 0x000d, + 0x36d2: 0x000d, 0x36d3: 0x000d, 0x36d4: 0x000d, 0x36d5: 0x000d, 0x36d6: 0x000d, 0x36d7: 0x000d, + 0x36d8: 0x000d, 0x36d9: 0x000d, 0x36da: 0x000d, 0x36db: 0x000d, 0x36dc: 0x000d, 0x36dd: 0x000d, + 0x36de: 0x000d, 0x36df: 0x000d, 0x36e0: 0x000d, 0x36e1: 0x000d, 0x36e2: 0x000d, 0x36e3: 0x000d, + 0x36e4: 0x000d, 0x36e5: 0x000d, 0x36e6: 0x000d, 0x36e7: 0x000d, 0x36e8: 0x000d, 0x36e9: 0x000d, + 0x36ea: 0x000d, 0x36eb: 0x000d, 0x36ec: 0x000d, 0x36ed: 0x000d, 0x36ee: 0x000d, 0x36ef: 0x000d, + 0x36f0: 0x000a, 0x36f1: 0x000a, 0x36f2: 0x000d, 0x36f3: 0x000d, 0x36f4: 0x000d, 0x36f5: 0x000d, + 0x36f6: 0x000d, 0x36f7: 0x000d, 0x36f8: 0x000d, 0x36f9: 0x000d, 0x36fa: 0x000d, 0x36fb: 0x000d, + 0x36fc: 0x000d, 0x36fd: 0x000d, 0x36fe: 0x000d, 0x36ff: 0x000d, + // Block 0xdc, offset 0x3700 + 0x3700: 0x000a, 0x3701: 0x000a, 0x3702: 0x000a, 0x3703: 0x000a, 0x3704: 0x000a, 0x3705: 0x000a, + 0x3706: 0x000a, 0x3707: 0x000a, 0x3708: 0x000a, 0x3709: 0x000a, 0x370a: 0x000a, 0x370b: 0x000a, + 0x370c: 0x000a, 0x370d: 0x000a, 0x370e: 0x000a, 0x370f: 0x000a, 0x3710: 0x000a, 0x3711: 0x000a, + 0x3712: 0x000a, 0x3713: 0x000a, 0x3714: 0x000a, 0x3715: 0x000a, 0x3716: 0x000a, 0x3717: 0x000a, + 0x3718: 0x000a, 0x3719: 0x000a, 0x371a: 0x000a, 0x371b: 0x000a, 0x371c: 0x000a, 0x371d: 0x000a, + 0x371e: 0x000a, 0x371f: 0x000a, 0x3720: 0x000a, 0x3721: 0x000a, 0x3722: 0x000a, 0x3723: 0x000a, + 0x3724: 0x000a, 0x3725: 0x000a, 0x3726: 0x000a, 0x3727: 0x000a, 0x3728: 0x000a, 0x3729: 0x000a, + 0x372a: 0x000a, 0x372b: 0x000a, + 0x3730: 0x000a, 0x3731: 0x000a, 0x3732: 0x000a, 0x3733: 0x000a, 0x3734: 0x000a, 0x3735: 0x000a, + 0x3736: 0x000a, 0x3737: 0x000a, 0x3738: 0x000a, 0x3739: 0x000a, 0x373a: 0x000a, 0x373b: 0x000a, + 0x373c: 0x000a, 0x373d: 0x000a, 0x373e: 0x000a, 0x373f: 0x000a, + // Block 0xdd, offset 0x3740 + 0x3740: 0x000a, 0x3741: 0x000a, 0x3742: 0x000a, 0x3743: 0x000a, 0x3744: 0x000a, 0x3745: 0x000a, + 0x3746: 0x000a, 0x3747: 0x000a, 0x3748: 0x000a, 0x3749: 0x000a, 0x374a: 0x000a, 0x374b: 0x000a, + 0x374c: 0x000a, 0x374d: 0x000a, 0x374e: 0x000a, 0x374f: 0x000a, 0x3750: 0x000a, 0x3751: 0x000a, + 0x3752: 0x000a, 0x3753: 0x000a, + 0x3760: 0x000a, 0x3761: 0x000a, 0x3762: 0x000a, 0x3763: 0x000a, + 0x3764: 0x000a, 0x3765: 0x000a, 0x3766: 0x000a, 0x3767: 0x000a, 0x3768: 0x000a, 0x3769: 0x000a, + 0x376a: 0x000a, 0x376b: 0x000a, 0x376c: 0x000a, 0x376d: 0x000a, 0x376e: 0x000a, + 0x3771: 0x000a, 0x3772: 0x000a, 0x3773: 0x000a, 0x3774: 0x000a, 0x3775: 0x000a, + 0x3776: 0x000a, 0x3777: 0x000a, 0x3778: 0x000a, 0x3779: 0x000a, 0x377a: 0x000a, 0x377b: 0x000a, + 0x377c: 0x000a, 0x377d: 0x000a, 0x377e: 0x000a, 0x377f: 0x000a, + // Block 0xde, offset 0x3780 + 0x3781: 0x000a, 0x3782: 0x000a, 0x3783: 0x000a, 0x3784: 0x000a, 0x3785: 0x000a, + 0x3786: 0x000a, 0x3787: 0x000a, 0x3788: 0x000a, 0x3789: 0x000a, 0x378a: 0x000a, 0x378b: 0x000a, + 0x378c: 0x000a, 0x378d: 0x000a, 0x378e: 0x000a, 0x378f: 0x000a, 0x3791: 0x000a, + 0x3792: 0x000a, 0x3793: 0x000a, 0x3794: 0x000a, 0x3795: 0x000a, 0x3796: 0x000a, 0x3797: 0x000a, + 0x3798: 0x000a, 0x3799: 0x000a, 0x379a: 0x000a, 0x379b: 0x000a, 0x379c: 0x000a, 0x379d: 0x000a, + 0x379e: 0x000a, 0x379f: 0x000a, 0x37a0: 0x000a, 0x37a1: 0x000a, 0x37a2: 0x000a, 0x37a3: 0x000a, + 0x37a4: 0x000a, 0x37a5: 0x000a, 0x37a6: 0x000a, 0x37a7: 0x000a, 0x37a8: 0x000a, 0x37a9: 0x000a, + 0x37aa: 0x000a, 0x37ab: 0x000a, 0x37ac: 0x000a, 0x37ad: 0x000a, 0x37ae: 0x000a, 0x37af: 0x000a, + 0x37b0: 0x000a, 0x37b1: 0x000a, 0x37b2: 0x000a, 0x37b3: 0x000a, 0x37b4: 0x000a, 0x37b5: 0x000a, + // Block 0xdf, offset 0x37c0 + 0x37c0: 0x0002, 0x37c1: 0x0002, 0x37c2: 0x0002, 0x37c3: 0x0002, 0x37c4: 0x0002, 0x37c5: 0x0002, + 0x37c6: 0x0002, 0x37c7: 0x0002, 0x37c8: 0x0002, 0x37c9: 0x0002, 0x37ca: 0x0002, 0x37cb: 0x000a, + 0x37cc: 0x000a, + 0x37ef: 0x000a, + // Block 0xe0, offset 0x3800 + 0x382a: 0x000a, 0x382b: 0x000a, 0x382c: 0x000a, + // Block 0xe1, offset 0x3840 + 0x3860: 0x000a, 0x3861: 0x000a, 0x3862: 0x000a, 0x3863: 0x000a, + 0x3864: 0x000a, 0x3865: 0x000a, + // Block 0xe2, offset 0x3880 + 0x3880: 0x000a, 0x3881: 0x000a, 0x3882: 0x000a, 0x3883: 0x000a, 0x3884: 0x000a, 0x3885: 0x000a, + 0x3886: 0x000a, 0x3887: 0x000a, 0x3888: 0x000a, 0x3889: 0x000a, 0x388a: 0x000a, 0x388b: 0x000a, + 0x388c: 0x000a, 0x388d: 0x000a, 0x388e: 0x000a, 0x388f: 0x000a, 0x3890: 0x000a, 0x3891: 0x000a, + 0x3892: 0x000a, 0x3893: 0x000a, 0x3894: 0x000a, 0x3895: 0x000a, + 0x38a0: 0x000a, 0x38a1: 0x000a, 0x38a2: 0x000a, 0x38a3: 0x000a, + 0x38a4: 0x000a, 0x38a5: 0x000a, 0x38a6: 0x000a, 0x38a7: 0x000a, 0x38a8: 0x000a, 0x38a9: 0x000a, + 0x38aa: 0x000a, 0x38ab: 0x000a, 0x38ac: 0x000a, + 0x38b0: 0x000a, 0x38b1: 0x000a, 0x38b2: 0x000a, 0x38b3: 0x000a, 0x38b4: 0x000a, 0x38b5: 0x000a, + 0x38b6: 0x000a, 0x38b7: 0x000a, 0x38b8: 0x000a, 0x38b9: 0x000a, 0x38ba: 0x000a, + // Block 0xe3, offset 0x38c0 + 0x38c0: 0x000a, 0x38c1: 0x000a, 0x38c2: 0x000a, 0x38c3: 0x000a, 0x38c4: 0x000a, 0x38c5: 0x000a, + 0x38c6: 0x000a, 0x38c7: 0x000a, 0x38c8: 0x000a, 0x38c9: 0x000a, 0x38ca: 0x000a, 0x38cb: 0x000a, + 0x38cc: 0x000a, 0x38cd: 0x000a, 0x38ce: 0x000a, 0x38cf: 0x000a, 0x38d0: 0x000a, 0x38d1: 0x000a, + 0x38d2: 0x000a, 0x38d3: 0x000a, 0x38d4: 0x000a, 0x38d5: 0x000a, 0x38d6: 0x000a, 0x38d7: 0x000a, + 0x38d8: 0x000a, + 0x38e0: 0x000a, 0x38e1: 0x000a, 0x38e2: 0x000a, 0x38e3: 0x000a, + 0x38e4: 0x000a, 0x38e5: 0x000a, 0x38e6: 0x000a, 0x38e7: 0x000a, 0x38e8: 0x000a, 0x38e9: 0x000a, + 0x38ea: 0x000a, 0x38eb: 0x000a, + // Block 0xe4, offset 0x3900 + 0x3900: 0x000a, 0x3901: 0x000a, 0x3902: 0x000a, 0x3903: 0x000a, 0x3904: 0x000a, 0x3905: 0x000a, + 0x3906: 0x000a, 0x3907: 0x000a, 0x3908: 0x000a, 0x3909: 0x000a, 0x390a: 0x000a, 0x390b: 0x000a, + 0x3910: 0x000a, 0x3911: 0x000a, + 0x3912: 0x000a, 0x3913: 0x000a, 0x3914: 0x000a, 0x3915: 0x000a, 0x3916: 0x000a, 0x3917: 0x000a, + 0x3918: 0x000a, 0x3919: 0x000a, 0x391a: 0x000a, 0x391b: 0x000a, 0x391c: 0x000a, 0x391d: 0x000a, + 0x391e: 0x000a, 0x391f: 0x000a, 0x3920: 0x000a, 0x3921: 0x000a, 0x3922: 0x000a, 0x3923: 0x000a, + 0x3924: 0x000a, 0x3925: 0x000a, 0x3926: 0x000a, 0x3927: 0x000a, 0x3928: 0x000a, 0x3929: 0x000a, + 0x392a: 0x000a, 0x392b: 0x000a, 0x392c: 0x000a, 0x392d: 0x000a, 0x392e: 0x000a, 0x392f: 0x000a, + 0x3930: 0x000a, 0x3931: 0x000a, 0x3932: 0x000a, 0x3933: 0x000a, 0x3934: 0x000a, 0x3935: 0x000a, + 0x3936: 0x000a, 0x3937: 0x000a, 0x3938: 0x000a, 0x3939: 0x000a, 0x393a: 0x000a, 0x393b: 0x000a, + 0x393c: 0x000a, 0x393d: 0x000a, 0x393e: 0x000a, 0x393f: 0x000a, + // Block 0xe5, offset 0x3940 + 0x3940: 0x000a, 0x3941: 0x000a, 0x3942: 0x000a, 0x3943: 0x000a, 0x3944: 0x000a, 0x3945: 0x000a, + 0x3946: 0x000a, 0x3947: 0x000a, + 0x3950: 0x000a, 0x3951: 0x000a, + 0x3952: 0x000a, 0x3953: 0x000a, 0x3954: 0x000a, 0x3955: 0x000a, 0x3956: 0x000a, 0x3957: 0x000a, + 0x3958: 0x000a, 0x3959: 0x000a, + 0x3960: 0x000a, 0x3961: 0x000a, 0x3962: 0x000a, 0x3963: 0x000a, + 0x3964: 0x000a, 0x3965: 0x000a, 0x3966: 0x000a, 0x3967: 0x000a, 0x3968: 0x000a, 0x3969: 0x000a, + 0x396a: 0x000a, 0x396b: 0x000a, 0x396c: 0x000a, 0x396d: 0x000a, 0x396e: 0x000a, 0x396f: 0x000a, + 0x3970: 0x000a, 0x3971: 0x000a, 0x3972: 0x000a, 0x3973: 0x000a, 0x3974: 0x000a, 0x3975: 0x000a, + 0x3976: 0x000a, 0x3977: 0x000a, 0x3978: 0x000a, 0x3979: 0x000a, 0x397a: 0x000a, 0x397b: 0x000a, + 0x397c: 0x000a, 0x397d: 0x000a, 0x397e: 0x000a, 0x397f: 0x000a, + // Block 0xe6, offset 0x3980 + 0x3980: 0x000a, 0x3981: 0x000a, 0x3982: 0x000a, 0x3983: 0x000a, 0x3984: 0x000a, 0x3985: 0x000a, + 0x3986: 0x000a, 0x3987: 0x000a, + 0x3990: 0x000a, 0x3991: 0x000a, + 0x3992: 0x000a, 0x3993: 0x000a, 0x3994: 0x000a, 0x3995: 0x000a, 0x3996: 0x000a, 0x3997: 0x000a, + 0x3998: 0x000a, 0x3999: 0x000a, 0x399a: 0x000a, 0x399b: 0x000a, 0x399c: 0x000a, 0x399d: 0x000a, + 0x399e: 0x000a, 0x399f: 0x000a, 0x39a0: 0x000a, 0x39a1: 0x000a, 0x39a2: 0x000a, 0x39a3: 0x000a, + 0x39a4: 0x000a, 0x39a5: 0x000a, 0x39a6: 0x000a, 0x39a7: 0x000a, 0x39a8: 0x000a, 0x39a9: 0x000a, + 0x39aa: 0x000a, 0x39ab: 0x000a, 0x39ac: 0x000a, 0x39ad: 0x000a, + // Block 0xe7, offset 0x39c0 + 0x39c0: 0x000a, 0x39c1: 0x000a, 0x39c2: 0x000a, 0x39c3: 0x000a, 0x39c4: 0x000a, 0x39c5: 0x000a, + 0x39c6: 0x000a, 0x39c7: 0x000a, 0x39c8: 0x000a, 0x39c9: 0x000a, 0x39ca: 0x000a, 0x39cb: 0x000a, + 0x39cd: 0x000a, 0x39ce: 0x000a, 0x39cf: 0x000a, 0x39d0: 0x000a, 0x39d1: 0x000a, + 0x39d2: 0x000a, 0x39d3: 0x000a, 0x39d4: 0x000a, 0x39d5: 0x000a, 0x39d6: 0x000a, 0x39d7: 0x000a, + 0x39d8: 0x000a, 0x39d9: 0x000a, 0x39da: 0x000a, 0x39db: 0x000a, 0x39dc: 0x000a, 0x39dd: 0x000a, + 0x39de: 0x000a, 0x39df: 0x000a, 0x39e0: 0x000a, 0x39e1: 0x000a, 0x39e2: 0x000a, 0x39e3: 0x000a, + 0x39e4: 0x000a, 0x39e5: 0x000a, 0x39e6: 0x000a, 0x39e7: 0x000a, 0x39e8: 0x000a, 0x39e9: 0x000a, + 0x39ea: 0x000a, 0x39eb: 0x000a, 0x39ec: 0x000a, 0x39ed: 0x000a, 0x39ee: 0x000a, 0x39ef: 0x000a, + 0x39f0: 0x000a, 0x39f1: 0x000a, 0x39f2: 0x000a, 0x39f3: 0x000a, 0x39f4: 0x000a, 0x39f5: 0x000a, + 0x39f6: 0x000a, 0x39f7: 0x000a, 0x39f8: 0x000a, 0x39f9: 0x000a, 0x39fa: 0x000a, 0x39fb: 0x000a, + 0x39fc: 0x000a, 0x39fd: 0x000a, 0x39fe: 0x000a, 0x39ff: 0x000a, + // Block 0xe8, offset 0x3a00 + 0x3a00: 0x000a, 0x3a01: 0x000a, 0x3a02: 0x000a, 0x3a03: 0x000a, 0x3a04: 0x000a, 0x3a05: 0x000a, + 0x3a06: 0x000a, 0x3a07: 0x000a, 0x3a08: 0x000a, 0x3a09: 0x000a, 0x3a0a: 0x000a, 0x3a0b: 0x000a, + 0x3a0c: 0x000a, 0x3a0d: 0x000a, 0x3a0e: 0x000a, 0x3a0f: 0x000a, 0x3a10: 0x000a, 0x3a11: 0x000a, + 0x3a12: 0x000a, 0x3a13: 0x000a, 0x3a14: 0x000a, 0x3a15: 0x000a, 0x3a16: 0x000a, 0x3a17: 0x000a, + 0x3a18: 0x000a, 0x3a19: 0x000a, 0x3a1a: 0x000a, 0x3a1b: 0x000a, 0x3a1c: 0x000a, 0x3a1d: 0x000a, + 0x3a1e: 0x000a, 0x3a1f: 0x000a, 0x3a20: 0x000a, 0x3a21: 0x000a, 0x3a22: 0x000a, 0x3a23: 0x000a, + 0x3a24: 0x000a, 0x3a25: 0x000a, 0x3a26: 0x000a, 0x3a27: 0x000a, 0x3a28: 0x000a, 0x3a29: 0x000a, + 0x3a2a: 0x000a, 0x3a2b: 0x000a, 0x3a2c: 0x000a, 0x3a2d: 0x000a, 0x3a2e: 0x000a, 0x3a2f: 0x000a, + 0x3a30: 0x000a, 0x3a31: 0x000a, 0x3a33: 0x000a, 0x3a34: 0x000a, 0x3a35: 0x000a, + 0x3a36: 0x000a, 0x3a3a: 0x000a, 0x3a3b: 0x000a, + 0x3a3c: 0x000a, 0x3a3d: 0x000a, 0x3a3e: 0x000a, 0x3a3f: 0x000a, + // Block 0xe9, offset 0x3a40 + 0x3a40: 0x000a, 0x3a41: 0x000a, 0x3a42: 0x000a, 0x3a43: 0x000a, 0x3a44: 0x000a, 0x3a45: 0x000a, + 0x3a46: 0x000a, 0x3a47: 0x000a, 0x3a48: 0x000a, 0x3a49: 0x000a, 0x3a4a: 0x000a, 0x3a4b: 0x000a, + 0x3a4c: 0x000a, 0x3a4d: 0x000a, 0x3a4e: 0x000a, 0x3a4f: 0x000a, 0x3a50: 0x000a, 0x3a51: 0x000a, + 0x3a52: 0x000a, 0x3a53: 0x000a, 0x3a54: 0x000a, 0x3a55: 0x000a, 0x3a56: 0x000a, 0x3a57: 0x000a, + 0x3a58: 0x000a, 0x3a59: 0x000a, 0x3a5a: 0x000a, 0x3a5b: 0x000a, 0x3a5c: 0x000a, 0x3a5d: 0x000a, + 0x3a5e: 0x000a, 0x3a5f: 0x000a, 0x3a60: 0x000a, 0x3a61: 0x000a, 0x3a62: 0x000a, + 0x3a65: 0x000a, 0x3a66: 0x000a, 0x3a67: 0x000a, 0x3a68: 0x000a, 0x3a69: 0x000a, + 0x3a6a: 0x000a, 0x3a6e: 0x000a, 0x3a6f: 0x000a, + 0x3a70: 0x000a, 0x3a71: 0x000a, 0x3a72: 0x000a, 0x3a73: 0x000a, 0x3a74: 0x000a, 0x3a75: 0x000a, + 0x3a76: 0x000a, 0x3a77: 0x000a, 0x3a78: 0x000a, 0x3a79: 0x000a, 0x3a7a: 0x000a, 0x3a7b: 0x000a, + 0x3a7c: 0x000a, 0x3a7d: 0x000a, 0x3a7e: 0x000a, 0x3a7f: 0x000a, + // Block 0xea, offset 0x3a80 + 0x3a80: 0x000a, 0x3a81: 0x000a, 0x3a82: 0x000a, 0x3a83: 0x000a, 0x3a84: 0x000a, 0x3a85: 0x000a, + 0x3a86: 0x000a, 0x3a87: 0x000a, 0x3a88: 0x000a, 0x3a89: 0x000a, 0x3a8a: 0x000a, + 0x3a8d: 0x000a, 0x3a8e: 0x000a, 0x3a8f: 0x000a, 0x3a90: 0x000a, 0x3a91: 0x000a, + 0x3a92: 0x000a, 0x3a93: 0x000a, 0x3a94: 0x000a, 0x3a95: 0x000a, 0x3a96: 0x000a, 0x3a97: 0x000a, + 0x3a98: 0x000a, 0x3a99: 0x000a, 0x3a9a: 0x000a, 0x3a9b: 0x000a, 0x3a9c: 0x000a, 0x3a9d: 0x000a, + 0x3a9e: 0x000a, 0x3a9f: 0x000a, 0x3aa0: 0x000a, 0x3aa1: 0x000a, 0x3aa2: 0x000a, 0x3aa3: 0x000a, + 0x3aa4: 0x000a, 0x3aa5: 0x000a, 0x3aa6: 0x000a, 0x3aa7: 0x000a, 0x3aa8: 0x000a, 0x3aa9: 0x000a, + 0x3aaa: 0x000a, 0x3aab: 0x000a, 0x3aac: 0x000a, 0x3aad: 0x000a, 0x3aae: 0x000a, 0x3aaf: 0x000a, + 0x3ab0: 0x000a, 0x3ab1: 0x000a, 0x3ab2: 0x000a, 0x3ab3: 0x000a, 0x3ab4: 0x000a, 0x3ab5: 0x000a, + 0x3ab6: 0x000a, 0x3ab7: 0x000a, 0x3ab8: 0x000a, 0x3ab9: 0x000a, 0x3aba: 0x000a, 0x3abb: 0x000a, + 0x3abc: 0x000a, 0x3abd: 0x000a, 0x3abe: 0x000a, 0x3abf: 0x000a, + // Block 0xeb, offset 0x3ac0 + 0x3ac0: 0x000a, 0x3ac1: 0x000a, 0x3ac2: 0x000a, 0x3ac3: 0x000a, 0x3ac4: 0x000a, 0x3ac5: 0x000a, + 0x3ac6: 0x000a, 0x3ac7: 0x000a, 0x3ac8: 0x000a, 0x3ac9: 0x000a, 0x3aca: 0x000a, 0x3acb: 0x000a, + 0x3acc: 0x000a, 0x3acd: 0x000a, 0x3ace: 0x000a, 0x3acf: 0x000a, 0x3ad0: 0x000a, 0x3ad1: 0x000a, + 0x3ad2: 0x000a, 0x3ad3: 0x000a, + 0x3ae0: 0x000a, 0x3ae1: 0x000a, 0x3ae2: 0x000a, 0x3ae3: 0x000a, + 0x3ae4: 0x000a, 0x3ae5: 0x000a, 0x3ae6: 0x000a, 0x3ae7: 0x000a, 0x3ae8: 0x000a, 0x3ae9: 0x000a, + 0x3aea: 0x000a, 0x3aeb: 0x000a, 0x3aec: 0x000a, 0x3aed: 0x000a, + 0x3af0: 0x000a, 0x3af1: 0x000a, 0x3af2: 0x000a, 0x3af3: 0x000a, + 0x3af8: 0x000a, 0x3af9: 0x000a, 0x3afa: 0x000a, + // Block 0xec, offset 0x3b00 + 0x3b00: 0x000a, 0x3b01: 0x000a, 0x3b02: 0x000a, + 0x3b10: 0x000a, 0x3b11: 0x000a, + 0x3b12: 0x000a, 0x3b13: 0x000a, 0x3b14: 0x000a, 0x3b15: 0x000a, + // Block 0xed, offset 0x3b40 + 0x3b7e: 0x000b, 0x3b7f: 0x000b, + // Block 0xee, offset 0x3b80 + 0x3b80: 0x000b, 0x3b81: 0x000b, 0x3b82: 0x000b, 0x3b83: 0x000b, 0x3b84: 0x000b, 0x3b85: 0x000b, + 0x3b86: 0x000b, 0x3b87: 0x000b, 0x3b88: 0x000b, 0x3b89: 0x000b, 0x3b8a: 0x000b, 0x3b8b: 0x000b, + 0x3b8c: 0x000b, 0x3b8d: 0x000b, 0x3b8e: 0x000b, 0x3b8f: 0x000b, 0x3b90: 0x000b, 0x3b91: 0x000b, + 0x3b92: 0x000b, 0x3b93: 0x000b, 0x3b94: 0x000b, 0x3b95: 0x000b, 0x3b96: 0x000b, 0x3b97: 0x000b, + 0x3b98: 0x000b, 0x3b99: 0x000b, 0x3b9a: 0x000b, 0x3b9b: 0x000b, 0x3b9c: 0x000b, 0x3b9d: 0x000b, + 0x3b9e: 0x000b, 0x3b9f: 0x000b, 0x3ba0: 0x000b, 0x3ba1: 0x000b, 0x3ba2: 0x000b, 0x3ba3: 0x000b, + 0x3ba4: 0x000b, 0x3ba5: 0x000b, 0x3ba6: 0x000b, 0x3ba7: 0x000b, 0x3ba8: 0x000b, 0x3ba9: 0x000b, + 0x3baa: 0x000b, 0x3bab: 0x000b, 0x3bac: 0x000b, 0x3bad: 0x000b, 0x3bae: 0x000b, 0x3baf: 0x000b, + 0x3bb0: 0x000b, 0x3bb1: 0x000b, 0x3bb2: 0x000b, 0x3bb3: 0x000b, 0x3bb4: 0x000b, 0x3bb5: 0x000b, + 0x3bb6: 0x000b, 0x3bb7: 0x000b, 0x3bb8: 0x000b, 0x3bb9: 0x000b, 0x3bba: 0x000b, 0x3bbb: 0x000b, + 0x3bbc: 0x000b, 0x3bbd: 0x000b, 0x3bbe: 0x000b, 0x3bbf: 0x000b, + // Block 0xef, offset 0x3bc0 + 0x3bc0: 0x000c, 0x3bc1: 0x000c, 0x3bc2: 0x000c, 0x3bc3: 0x000c, 0x3bc4: 0x000c, 0x3bc5: 0x000c, + 0x3bc6: 0x000c, 0x3bc7: 0x000c, 0x3bc8: 0x000c, 0x3bc9: 0x000c, 0x3bca: 0x000c, 0x3bcb: 0x000c, + 0x3bcc: 0x000c, 0x3bcd: 0x000c, 0x3bce: 0x000c, 0x3bcf: 0x000c, 0x3bd0: 0x000c, 0x3bd1: 0x000c, + 0x3bd2: 0x000c, 0x3bd3: 0x000c, 0x3bd4: 0x000c, 0x3bd5: 0x000c, 0x3bd6: 0x000c, 0x3bd7: 0x000c, + 0x3bd8: 0x000c, 0x3bd9: 0x000c, 0x3bda: 0x000c, 0x3bdb: 0x000c, 0x3bdc: 0x000c, 0x3bdd: 0x000c, + 0x3bde: 0x000c, 0x3bdf: 0x000c, 0x3be0: 0x000c, 0x3be1: 0x000c, 0x3be2: 0x000c, 0x3be3: 0x000c, + 0x3be4: 0x000c, 0x3be5: 0x000c, 0x3be6: 0x000c, 0x3be7: 0x000c, 0x3be8: 0x000c, 0x3be9: 0x000c, + 0x3bea: 0x000c, 0x3beb: 0x000c, 0x3bec: 0x000c, 0x3bed: 0x000c, 0x3bee: 0x000c, 0x3bef: 0x000c, + 0x3bf0: 0x000b, 0x3bf1: 0x000b, 0x3bf2: 0x000b, 0x3bf3: 0x000b, 0x3bf4: 0x000b, 0x3bf5: 0x000b, + 0x3bf6: 0x000b, 0x3bf7: 0x000b, 0x3bf8: 0x000b, 0x3bf9: 0x000b, 0x3bfa: 0x000b, 0x3bfb: 0x000b, + 0x3bfc: 0x000b, 0x3bfd: 0x000b, 0x3bfe: 0x000b, 0x3bff: 0x000b, +} + +// bidiIndex: 24 blocks, 1536 entries, 1536 bytes +// Block 0 is the zero block. +var bidiIndex = [1536]uint8{ + // Block 0x0, offset 0x0 + // Block 0x1, offset 0x40 + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc2: 0x01, 0xc3: 0x02, + 0xca: 0x03, 0xcb: 0x04, 0xcc: 0x05, 0xcd: 0x06, 0xce: 0x07, 0xcf: 0x08, + 0xd2: 0x09, 0xd6: 0x0a, 0xd7: 0x0b, + 0xd8: 0x0c, 0xd9: 0x0d, 0xda: 0x0e, 0xdb: 0x0f, 0xdc: 0x10, 0xdd: 0x11, 0xde: 0x12, 0xdf: 0x13, + 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05, 0xe4: 0x06, + 0xea: 0x07, 0xef: 0x08, + 0xf0: 0x11, 0xf1: 0x12, 0xf2: 0x12, 0xf3: 0x14, 0xf4: 0x15, + // Block 0x4, offset 0x100 + 0x120: 0x14, 0x121: 0x15, 0x122: 0x16, 0x123: 0x17, 0x124: 0x18, 0x125: 0x19, 0x126: 0x1a, 0x127: 0x1b, + 0x128: 0x1c, 0x129: 0x1d, 0x12a: 0x1c, 0x12b: 0x1e, 0x12c: 0x1f, 0x12d: 0x20, 0x12e: 0x21, 0x12f: 0x22, + 0x130: 0x23, 0x131: 0x24, 0x132: 0x1a, 0x133: 0x25, 0x134: 0x26, 0x135: 0x27, 0x137: 0x28, + 0x138: 0x29, 0x139: 0x2a, 0x13a: 0x2b, 0x13b: 0x2c, 0x13c: 0x2d, 0x13d: 0x2e, 0x13e: 0x2f, 0x13f: 0x30, + // Block 0x5, offset 0x140 + 0x140: 0x31, 0x141: 0x32, 0x142: 0x33, + 0x14d: 0x34, 0x14e: 0x35, + 0x150: 0x36, + 0x15a: 0x37, 0x15c: 0x38, 0x15d: 0x39, 0x15e: 0x3a, 0x15f: 0x3b, + 0x160: 0x3c, 0x162: 0x3d, 0x164: 0x3e, 0x165: 0x3f, 0x167: 0x40, + 0x168: 0x41, 0x169: 0x42, 0x16a: 0x43, 0x16c: 0x44, 0x16d: 0x45, 0x16e: 0x46, 0x16f: 0x47, + 0x170: 0x48, 0x173: 0x49, 0x177: 0x4a, + 0x17e: 0x4b, 0x17f: 0x4c, + // Block 0x6, offset 0x180 + 0x180: 0x4d, 0x181: 0x4e, 0x182: 0x4f, 0x183: 0x50, 0x184: 0x51, 0x185: 0x52, 0x186: 0x53, 0x187: 0x54, + 0x188: 0x55, 0x189: 0x54, 0x18a: 0x54, 0x18b: 0x54, 0x18c: 0x56, 0x18d: 0x57, 0x18e: 0x58, 0x18f: 0x54, + 0x190: 0x59, 0x191: 0x5a, 0x192: 0x5b, 0x193: 0x5c, 0x194: 0x54, 0x195: 0x54, 0x196: 0x54, 0x197: 0x54, + 0x198: 0x54, 0x199: 0x54, 0x19a: 0x5d, 0x19b: 0x54, 0x19c: 0x54, 0x19d: 0x5e, 0x19e: 0x54, 0x19f: 0x5f, + 0x1a4: 0x54, 0x1a5: 0x54, 0x1a6: 0x60, 0x1a7: 0x61, + 0x1a8: 0x54, 0x1a9: 0x54, 0x1aa: 0x54, 0x1ab: 0x54, 0x1ac: 0x54, 0x1ad: 0x62, 0x1ae: 0x63, 0x1af: 0x54, + 0x1b3: 0x64, 0x1b5: 0x65, 0x1b7: 0x66, + 0x1b8: 0x67, 0x1b9: 0x68, 0x1ba: 0x69, 0x1bb: 0x6a, 0x1bc: 0x54, 0x1bd: 0x54, 0x1be: 0x54, 0x1bf: 0x6b, + // Block 0x7, offset 0x1c0 + 0x1c0: 0x6c, 0x1c2: 0x6d, 0x1c3: 0x6e, 0x1c7: 0x6f, + 0x1c8: 0x70, 0x1c9: 0x71, 0x1ca: 0x72, 0x1cb: 0x73, 0x1cd: 0x74, 0x1cf: 0x75, + // Block 0x8, offset 0x200 + 0x237: 0x54, + // Block 0x9, offset 0x240 + 0x252: 0x76, 0x253: 0x77, + 0x258: 0x78, 0x259: 0x79, 0x25a: 0x7a, 0x25b: 0x7b, 0x25c: 0x7c, 0x25e: 0x7d, + 0x260: 0x7e, 0x261: 0x7f, 0x263: 0x80, 0x264: 0x81, 0x265: 0x82, 0x266: 0x83, 0x267: 0x84, + 0x268: 0x85, 0x269: 0x86, 0x26a: 0x87, 0x26b: 0x88, 0x26f: 0x89, + // Block 0xa, offset 0x280 + 0x2ac: 0x8a, 0x2ad: 0x8b, 0x2ae: 0x0e, 0x2af: 0x0e, + 0x2b0: 0x0e, 0x2b1: 0x0e, 0x2b2: 0x0e, 0x2b3: 0x0e, 0x2b4: 0x8c, 0x2b5: 0x0e, 0x2b6: 0x0e, 0x2b7: 0x8d, + 0x2b8: 0x8e, 0x2b9: 0x8f, 0x2ba: 0x0e, 0x2bb: 0x90, 0x2bc: 0x91, 0x2bd: 0x92, 0x2bf: 0x93, + // Block 0xb, offset 0x2c0 + 0x2c4: 0x94, 0x2c5: 0x54, 0x2c6: 0x95, 0x2c7: 0x96, + 0x2cb: 0x97, 0x2cd: 0x98, + 0x2e0: 0x99, 0x2e1: 0x99, 0x2e2: 0x99, 0x2e3: 0x99, 0x2e4: 0x9a, 0x2e5: 0x99, 0x2e6: 0x99, 0x2e7: 0x99, + 0x2e8: 0x9b, 0x2e9: 0x99, 0x2ea: 0x99, 0x2eb: 0x9c, 0x2ec: 0x9d, 0x2ed: 0x99, 0x2ee: 0x99, 0x2ef: 0x99, + 0x2f0: 0x99, 0x2f1: 0x99, 0x2f2: 0x99, 0x2f3: 0x99, 0x2f4: 0x9e, 0x2f5: 0x99, 0x2f6: 0x99, 0x2f7: 0x99, + 0x2f8: 0x99, 0x2f9: 0x9f, 0x2fa: 0x99, 0x2fb: 0x99, 0x2fc: 0xa0, 0x2fd: 0xa1, 0x2fe: 0x99, 0x2ff: 0x99, + // Block 0xc, offset 0x300 + 0x300: 0xa2, 0x301: 0xa3, 0x302: 0xa4, 0x304: 0xa5, 0x305: 0xa6, 0x306: 0xa7, 0x307: 0xa8, + 0x308: 0xa9, 0x30b: 0xaa, 0x30c: 0x26, 0x30d: 0xab, + 0x310: 0xac, 0x311: 0xad, 0x312: 0xae, 0x313: 0xaf, 0x316: 0xb0, 0x317: 0xb1, + 0x318: 0xb2, 0x319: 0xb3, 0x31a: 0xb4, 0x31c: 0xb5, + 0x320: 0xb6, 0x327: 0xb7, + 0x328: 0xb8, 0x329: 0xb9, 0x32a: 0xba, + 0x330: 0xbb, 0x332: 0xbc, 0x334: 0xbd, 0x335: 0xbe, 0x336: 0xbf, + 0x33b: 0xc0, 0x33f: 0xc1, + // Block 0xd, offset 0x340 + 0x36b: 0xc2, 0x36c: 0xc3, + 0x37d: 0xc4, 0x37e: 0xc5, 0x37f: 0xc6, + // Block 0xe, offset 0x380 + 0x3b2: 0xc7, + // Block 0xf, offset 0x3c0 + 0x3c5: 0xc8, 0x3c6: 0xc9, + 0x3c8: 0x54, 0x3c9: 0xca, 0x3cc: 0x54, 0x3cd: 0xcb, + 0x3db: 0xcc, 0x3dc: 0xcd, 0x3dd: 0xce, 0x3de: 0xcf, 0x3df: 0xd0, + 0x3e8: 0xd1, 0x3e9: 0xd2, 0x3ea: 0xd3, + // Block 0x10, offset 0x400 + 0x400: 0xd4, 0x404: 0xc3, + 0x40b: 0xd5, + 0x420: 0x99, 0x421: 0x99, 0x422: 0x99, 0x423: 0xd6, 0x424: 0x99, 0x425: 0xd7, 0x426: 0x99, 0x427: 0x99, + 0x428: 0x99, 0x429: 0x99, 0x42a: 0x99, 0x42b: 0x99, 0x42c: 0x99, 0x42d: 0x99, 0x42e: 0x99, 0x42f: 0x99, + 0x430: 0x99, 0x431: 0xa0, 0x432: 0x0e, 0x433: 0x99, 0x434: 0x0e, 0x435: 0xd8, 0x436: 0x99, 0x437: 0x99, + 0x438: 0x0e, 0x439: 0x0e, 0x43a: 0x0e, 0x43b: 0xd9, 0x43c: 0x99, 0x43d: 0x99, 0x43e: 0x99, 0x43f: 0x99, + // Block 0x11, offset 0x440 + 0x440: 0xda, 0x441: 0x54, 0x442: 0xdb, 0x443: 0xdc, 0x444: 0xdd, 0x445: 0xde, + 0x449: 0xdf, 0x44c: 0x54, 0x44d: 0x54, 0x44e: 0x54, 0x44f: 0x54, + 0x450: 0x54, 0x451: 0x54, 0x452: 0x54, 0x453: 0x54, 0x454: 0x54, 0x455: 0x54, 0x456: 0x54, 0x457: 0x54, + 0x458: 0x54, 0x459: 0x54, 0x45a: 0x54, 0x45b: 0xe0, 0x45c: 0x54, 0x45d: 0x6a, 0x45e: 0x54, 0x45f: 0xe1, + 0x460: 0xe2, 0x461: 0xe3, 0x462: 0xe4, 0x464: 0xe5, 0x465: 0xe6, 0x466: 0xe7, 0x467: 0xe8, + 0x468: 0x54, 0x469: 0xe9, 0x46a: 0xea, + 0x47f: 0xeb, + // Block 0x12, offset 0x480 + 0x4bf: 0xeb, + // Block 0x13, offset 0x4c0 + 0x4d0: 0x09, 0x4d1: 0x0a, 0x4d6: 0x0b, + 0x4db: 0x0c, 0x4dd: 0x0d, 0x4de: 0x0e, 0x4df: 0x0f, + 0x4ef: 0x10, + 0x4ff: 0x10, + // Block 0x14, offset 0x500 + 0x50f: 0x10, + 0x51f: 0x10, + 0x52f: 0x10, + 0x53f: 0x10, + // Block 0x15, offset 0x540 + 0x540: 0xec, 0x541: 0xec, 0x542: 0xec, 0x543: 0xec, 0x544: 0x05, 0x545: 0x05, 0x546: 0x05, 0x547: 0xed, + 0x548: 0xec, 0x549: 0xec, 0x54a: 0xec, 0x54b: 0xec, 0x54c: 0xec, 0x54d: 0xec, 0x54e: 0xec, 0x54f: 0xec, + 0x550: 0xec, 0x551: 0xec, 0x552: 0xec, 0x553: 0xec, 0x554: 0xec, 0x555: 0xec, 0x556: 0xec, 0x557: 0xec, + 0x558: 0xec, 0x559: 0xec, 0x55a: 0xec, 0x55b: 0xec, 0x55c: 0xec, 0x55d: 0xec, 0x55e: 0xec, 0x55f: 0xec, + 0x560: 0xec, 0x561: 0xec, 0x562: 0xec, 0x563: 0xec, 0x564: 0xec, 0x565: 0xec, 0x566: 0xec, 0x567: 0xec, + 0x568: 0xec, 0x569: 0xec, 0x56a: 0xec, 0x56b: 0xec, 0x56c: 0xec, 0x56d: 0xec, 0x56e: 0xec, 0x56f: 0xec, + 0x570: 0xec, 0x571: 0xec, 0x572: 0xec, 0x573: 0xec, 0x574: 0xec, 0x575: 0xec, 0x576: 0xec, 0x577: 0xec, + 0x578: 0xec, 0x579: 0xec, 0x57a: 0xec, 0x57b: 0xec, 0x57c: 0xec, 0x57d: 0xec, 0x57e: 0xec, 0x57f: 0xec, + // Block 0x16, offset 0x580 + 0x58f: 0x10, + 0x59f: 0x10, + 0x5a0: 0x13, + 0x5af: 0x10, + 0x5bf: 0x10, + // Block 0x17, offset 0x5c0 + 0x5cf: 0x10, +} + +// Total table size 16952 bytes (16KiB); checksum: F50EF68C diff --git a/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go index 7297cce32b7..2c58f09baa4 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go +++ b/vendor/golang.org/x/text/unicode/norm/tables11.0.0.go @@ -1,6 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. -// +build go1.13 +// +build go1.13,!go1.14 package norm diff --git a/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go new file mode 100644 index 00000000000..10f5202c693 --- /dev/null +++ b/vendor/golang.org/x/text/unicode/norm/tables12.0.0.go @@ -0,0 +1,7710 @@ +// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. + +// +build go1.14 + +package norm + +import "sync" + +const ( + // Version is the Unicode edition from which the tables are derived. + Version = "12.0.0" + + // MaxTransformChunkSize indicates the maximum number of bytes that Transform + // may need to write atomically for any Form. Making a destination buffer at + // least this size ensures that Transform can always make progress and that + // the user does not need to grow the buffer on an ErrShortDst. + MaxTransformChunkSize = 35 + maxNonStarters*4 +) + +var ccc = [55]uint8{ + 0, 1, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, + 84, 91, 103, 107, 118, 122, 129, 130, + 132, 202, 214, 216, 218, 220, 222, 224, + 226, 228, 230, 232, 233, 234, 240, +} + +const ( + firstMulti = 0x186D + firstCCC = 0x2CA1 + endMulti = 0x2F63 + firstLeadingCCC = 0x49B1 + firstCCCZeroExcept = 0x4A7B + firstStarterWithNLead = 0x4AA2 + lastDecomp = 0x4AA4 + maxDecomp = 0x8000 +) + +// decomps: 19108 bytes +var decomps = [...]byte{ + // Bytes 0 - 3f + 0x00, 0x41, 0x20, 0x41, 0x21, 0x41, 0x22, 0x41, + 0x23, 0x41, 0x24, 0x41, 0x25, 0x41, 0x26, 0x41, + 0x27, 0x41, 0x28, 0x41, 0x29, 0x41, 0x2A, 0x41, + 0x2B, 0x41, 0x2C, 0x41, 0x2D, 0x41, 0x2E, 0x41, + 0x2F, 0x41, 0x30, 0x41, 0x31, 0x41, 0x32, 0x41, + 0x33, 0x41, 0x34, 0x41, 0x35, 0x41, 0x36, 0x41, + 0x37, 0x41, 0x38, 0x41, 0x39, 0x41, 0x3A, 0x41, + 0x3B, 0x41, 0x3C, 0x41, 0x3D, 0x41, 0x3E, 0x41, + // Bytes 40 - 7f + 0x3F, 0x41, 0x40, 0x41, 0x41, 0x41, 0x42, 0x41, + 0x43, 0x41, 0x44, 0x41, 0x45, 0x41, 0x46, 0x41, + 0x47, 0x41, 0x48, 0x41, 0x49, 0x41, 0x4A, 0x41, + 0x4B, 0x41, 0x4C, 0x41, 0x4D, 0x41, 0x4E, 0x41, + 0x4F, 0x41, 0x50, 0x41, 0x51, 0x41, 0x52, 0x41, + 0x53, 0x41, 0x54, 0x41, 0x55, 0x41, 0x56, 0x41, + 0x57, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5A, 0x41, + 0x5B, 0x41, 0x5C, 0x41, 0x5D, 0x41, 0x5E, 0x41, + // Bytes 80 - bf + 0x5F, 0x41, 0x60, 0x41, 0x61, 0x41, 0x62, 0x41, + 0x63, 0x41, 0x64, 0x41, 0x65, 0x41, 0x66, 0x41, + 0x67, 0x41, 0x68, 0x41, 0x69, 0x41, 0x6A, 0x41, + 0x6B, 0x41, 0x6C, 0x41, 0x6D, 0x41, 0x6E, 0x41, + 0x6F, 0x41, 0x70, 0x41, 0x71, 0x41, 0x72, 0x41, + 0x73, 0x41, 0x74, 0x41, 0x75, 0x41, 0x76, 0x41, + 0x77, 0x41, 0x78, 0x41, 0x79, 0x41, 0x7A, 0x41, + 0x7B, 0x41, 0x7C, 0x41, 0x7D, 0x41, 0x7E, 0x42, + // Bytes c0 - ff + 0xC2, 0xA2, 0x42, 0xC2, 0xA3, 0x42, 0xC2, 0xA5, + 0x42, 0xC2, 0xA6, 0x42, 0xC2, 0xAC, 0x42, 0xC2, + 0xB7, 0x42, 0xC3, 0x86, 0x42, 0xC3, 0xB0, 0x42, + 0xC4, 0xA6, 0x42, 0xC4, 0xA7, 0x42, 0xC4, 0xB1, + 0x42, 0xC5, 0x8B, 0x42, 0xC5, 0x93, 0x42, 0xC6, + 0x8E, 0x42, 0xC6, 0x90, 0x42, 0xC6, 0xAB, 0x42, + 0xC8, 0xA2, 0x42, 0xC8, 0xB7, 0x42, 0xC9, 0x90, + 0x42, 0xC9, 0x91, 0x42, 0xC9, 0x92, 0x42, 0xC9, + // Bytes 100 - 13f + 0x94, 0x42, 0xC9, 0x95, 0x42, 0xC9, 0x99, 0x42, + 0xC9, 0x9B, 0x42, 0xC9, 0x9C, 0x42, 0xC9, 0x9F, + 0x42, 0xC9, 0xA1, 0x42, 0xC9, 0xA3, 0x42, 0xC9, + 0xA5, 0x42, 0xC9, 0xA6, 0x42, 0xC9, 0xA8, 0x42, + 0xC9, 0xA9, 0x42, 0xC9, 0xAA, 0x42, 0xC9, 0xAB, + 0x42, 0xC9, 0xAD, 0x42, 0xC9, 0xAF, 0x42, 0xC9, + 0xB0, 0x42, 0xC9, 0xB1, 0x42, 0xC9, 0xB2, 0x42, + 0xC9, 0xB3, 0x42, 0xC9, 0xB4, 0x42, 0xC9, 0xB5, + // Bytes 140 - 17f + 0x42, 0xC9, 0xB8, 0x42, 0xC9, 0xB9, 0x42, 0xC9, + 0xBB, 0x42, 0xCA, 0x81, 0x42, 0xCA, 0x82, 0x42, + 0xCA, 0x83, 0x42, 0xCA, 0x89, 0x42, 0xCA, 0x8A, + 0x42, 0xCA, 0x8B, 0x42, 0xCA, 0x8C, 0x42, 0xCA, + 0x90, 0x42, 0xCA, 0x91, 0x42, 0xCA, 0x92, 0x42, + 0xCA, 0x95, 0x42, 0xCA, 0x9D, 0x42, 0xCA, 0x9F, + 0x42, 0xCA, 0xB9, 0x42, 0xCE, 0x91, 0x42, 0xCE, + 0x92, 0x42, 0xCE, 0x93, 0x42, 0xCE, 0x94, 0x42, + // Bytes 180 - 1bf + 0xCE, 0x95, 0x42, 0xCE, 0x96, 0x42, 0xCE, 0x97, + 0x42, 0xCE, 0x98, 0x42, 0xCE, 0x99, 0x42, 0xCE, + 0x9A, 0x42, 0xCE, 0x9B, 0x42, 0xCE, 0x9C, 0x42, + 0xCE, 0x9D, 0x42, 0xCE, 0x9E, 0x42, 0xCE, 0x9F, + 0x42, 0xCE, 0xA0, 0x42, 0xCE, 0xA1, 0x42, 0xCE, + 0xA3, 0x42, 0xCE, 0xA4, 0x42, 0xCE, 0xA5, 0x42, + 0xCE, 0xA6, 0x42, 0xCE, 0xA7, 0x42, 0xCE, 0xA8, + 0x42, 0xCE, 0xA9, 0x42, 0xCE, 0xB1, 0x42, 0xCE, + // Bytes 1c0 - 1ff + 0xB2, 0x42, 0xCE, 0xB3, 0x42, 0xCE, 0xB4, 0x42, + 0xCE, 0xB5, 0x42, 0xCE, 0xB6, 0x42, 0xCE, 0xB7, + 0x42, 0xCE, 0xB8, 0x42, 0xCE, 0xB9, 0x42, 0xCE, + 0xBA, 0x42, 0xCE, 0xBB, 0x42, 0xCE, 0xBC, 0x42, + 0xCE, 0xBD, 0x42, 0xCE, 0xBE, 0x42, 0xCE, 0xBF, + 0x42, 0xCF, 0x80, 0x42, 0xCF, 0x81, 0x42, 0xCF, + 0x82, 0x42, 0xCF, 0x83, 0x42, 0xCF, 0x84, 0x42, + 0xCF, 0x85, 0x42, 0xCF, 0x86, 0x42, 0xCF, 0x87, + // Bytes 200 - 23f + 0x42, 0xCF, 0x88, 0x42, 0xCF, 0x89, 0x42, 0xCF, + 0x9C, 0x42, 0xCF, 0x9D, 0x42, 0xD0, 0xBD, 0x42, + 0xD1, 0x8A, 0x42, 0xD1, 0x8C, 0x42, 0xD7, 0x90, + 0x42, 0xD7, 0x91, 0x42, 0xD7, 0x92, 0x42, 0xD7, + 0x93, 0x42, 0xD7, 0x94, 0x42, 0xD7, 0x9B, 0x42, + 0xD7, 0x9C, 0x42, 0xD7, 0x9D, 0x42, 0xD7, 0xA2, + 0x42, 0xD7, 0xA8, 0x42, 0xD7, 0xAA, 0x42, 0xD8, + 0xA1, 0x42, 0xD8, 0xA7, 0x42, 0xD8, 0xA8, 0x42, + // Bytes 240 - 27f + 0xD8, 0xA9, 0x42, 0xD8, 0xAA, 0x42, 0xD8, 0xAB, + 0x42, 0xD8, 0xAC, 0x42, 0xD8, 0xAD, 0x42, 0xD8, + 0xAE, 0x42, 0xD8, 0xAF, 0x42, 0xD8, 0xB0, 0x42, + 0xD8, 0xB1, 0x42, 0xD8, 0xB2, 0x42, 0xD8, 0xB3, + 0x42, 0xD8, 0xB4, 0x42, 0xD8, 0xB5, 0x42, 0xD8, + 0xB6, 0x42, 0xD8, 0xB7, 0x42, 0xD8, 0xB8, 0x42, + 0xD8, 0xB9, 0x42, 0xD8, 0xBA, 0x42, 0xD9, 0x81, + 0x42, 0xD9, 0x82, 0x42, 0xD9, 0x83, 0x42, 0xD9, + // Bytes 280 - 2bf + 0x84, 0x42, 0xD9, 0x85, 0x42, 0xD9, 0x86, 0x42, + 0xD9, 0x87, 0x42, 0xD9, 0x88, 0x42, 0xD9, 0x89, + 0x42, 0xD9, 0x8A, 0x42, 0xD9, 0xAE, 0x42, 0xD9, + 0xAF, 0x42, 0xD9, 0xB1, 0x42, 0xD9, 0xB9, 0x42, + 0xD9, 0xBA, 0x42, 0xD9, 0xBB, 0x42, 0xD9, 0xBE, + 0x42, 0xD9, 0xBF, 0x42, 0xDA, 0x80, 0x42, 0xDA, + 0x83, 0x42, 0xDA, 0x84, 0x42, 0xDA, 0x86, 0x42, + 0xDA, 0x87, 0x42, 0xDA, 0x88, 0x42, 0xDA, 0x8C, + // Bytes 2c0 - 2ff + 0x42, 0xDA, 0x8D, 0x42, 0xDA, 0x8E, 0x42, 0xDA, + 0x91, 0x42, 0xDA, 0x98, 0x42, 0xDA, 0xA1, 0x42, + 0xDA, 0xA4, 0x42, 0xDA, 0xA6, 0x42, 0xDA, 0xA9, + 0x42, 0xDA, 0xAD, 0x42, 0xDA, 0xAF, 0x42, 0xDA, + 0xB1, 0x42, 0xDA, 0xB3, 0x42, 0xDA, 0xBA, 0x42, + 0xDA, 0xBB, 0x42, 0xDA, 0xBE, 0x42, 0xDB, 0x81, + 0x42, 0xDB, 0x85, 0x42, 0xDB, 0x86, 0x42, 0xDB, + 0x87, 0x42, 0xDB, 0x88, 0x42, 0xDB, 0x89, 0x42, + // Bytes 300 - 33f + 0xDB, 0x8B, 0x42, 0xDB, 0x8C, 0x42, 0xDB, 0x90, + 0x42, 0xDB, 0x92, 0x43, 0xE0, 0xBC, 0x8B, 0x43, + 0xE1, 0x83, 0x9C, 0x43, 0xE1, 0x84, 0x80, 0x43, + 0xE1, 0x84, 0x81, 0x43, 0xE1, 0x84, 0x82, 0x43, + 0xE1, 0x84, 0x83, 0x43, 0xE1, 0x84, 0x84, 0x43, + 0xE1, 0x84, 0x85, 0x43, 0xE1, 0x84, 0x86, 0x43, + 0xE1, 0x84, 0x87, 0x43, 0xE1, 0x84, 0x88, 0x43, + 0xE1, 0x84, 0x89, 0x43, 0xE1, 0x84, 0x8A, 0x43, + // Bytes 340 - 37f + 0xE1, 0x84, 0x8B, 0x43, 0xE1, 0x84, 0x8C, 0x43, + 0xE1, 0x84, 0x8D, 0x43, 0xE1, 0x84, 0x8E, 0x43, + 0xE1, 0x84, 0x8F, 0x43, 0xE1, 0x84, 0x90, 0x43, + 0xE1, 0x84, 0x91, 0x43, 0xE1, 0x84, 0x92, 0x43, + 0xE1, 0x84, 0x94, 0x43, 0xE1, 0x84, 0x95, 0x43, + 0xE1, 0x84, 0x9A, 0x43, 0xE1, 0x84, 0x9C, 0x43, + 0xE1, 0x84, 0x9D, 0x43, 0xE1, 0x84, 0x9E, 0x43, + 0xE1, 0x84, 0xA0, 0x43, 0xE1, 0x84, 0xA1, 0x43, + // Bytes 380 - 3bf + 0xE1, 0x84, 0xA2, 0x43, 0xE1, 0x84, 0xA3, 0x43, + 0xE1, 0x84, 0xA7, 0x43, 0xE1, 0x84, 0xA9, 0x43, + 0xE1, 0x84, 0xAB, 0x43, 0xE1, 0x84, 0xAC, 0x43, + 0xE1, 0x84, 0xAD, 0x43, 0xE1, 0x84, 0xAE, 0x43, + 0xE1, 0x84, 0xAF, 0x43, 0xE1, 0x84, 0xB2, 0x43, + 0xE1, 0x84, 0xB6, 0x43, 0xE1, 0x85, 0x80, 0x43, + 0xE1, 0x85, 0x87, 0x43, 0xE1, 0x85, 0x8C, 0x43, + 0xE1, 0x85, 0x97, 0x43, 0xE1, 0x85, 0x98, 0x43, + // Bytes 3c0 - 3ff + 0xE1, 0x85, 0x99, 0x43, 0xE1, 0x85, 0xA0, 0x43, + 0xE1, 0x86, 0x84, 0x43, 0xE1, 0x86, 0x85, 0x43, + 0xE1, 0x86, 0x88, 0x43, 0xE1, 0x86, 0x91, 0x43, + 0xE1, 0x86, 0x92, 0x43, 0xE1, 0x86, 0x94, 0x43, + 0xE1, 0x86, 0x9E, 0x43, 0xE1, 0x86, 0xA1, 0x43, + 0xE1, 0x87, 0x87, 0x43, 0xE1, 0x87, 0x88, 0x43, + 0xE1, 0x87, 0x8C, 0x43, 0xE1, 0x87, 0x8E, 0x43, + 0xE1, 0x87, 0x93, 0x43, 0xE1, 0x87, 0x97, 0x43, + // Bytes 400 - 43f + 0xE1, 0x87, 0x99, 0x43, 0xE1, 0x87, 0x9D, 0x43, + 0xE1, 0x87, 0x9F, 0x43, 0xE1, 0x87, 0xB1, 0x43, + 0xE1, 0x87, 0xB2, 0x43, 0xE1, 0xB4, 0x82, 0x43, + 0xE1, 0xB4, 0x96, 0x43, 0xE1, 0xB4, 0x97, 0x43, + 0xE1, 0xB4, 0x9C, 0x43, 0xE1, 0xB4, 0x9D, 0x43, + 0xE1, 0xB4, 0xA5, 0x43, 0xE1, 0xB5, 0xBB, 0x43, + 0xE1, 0xB6, 0x85, 0x43, 0xE2, 0x80, 0x82, 0x43, + 0xE2, 0x80, 0x83, 0x43, 0xE2, 0x80, 0x90, 0x43, + // Bytes 440 - 47f + 0xE2, 0x80, 0x93, 0x43, 0xE2, 0x80, 0x94, 0x43, + 0xE2, 0x82, 0xA9, 0x43, 0xE2, 0x86, 0x90, 0x43, + 0xE2, 0x86, 0x91, 0x43, 0xE2, 0x86, 0x92, 0x43, + 0xE2, 0x86, 0x93, 0x43, 0xE2, 0x88, 0x82, 0x43, + 0xE2, 0x88, 0x87, 0x43, 0xE2, 0x88, 0x91, 0x43, + 0xE2, 0x88, 0x92, 0x43, 0xE2, 0x94, 0x82, 0x43, + 0xE2, 0x96, 0xA0, 0x43, 0xE2, 0x97, 0x8B, 0x43, + 0xE2, 0xA6, 0x85, 0x43, 0xE2, 0xA6, 0x86, 0x43, + // Bytes 480 - 4bf + 0xE2, 0xB5, 0xA1, 0x43, 0xE3, 0x80, 0x81, 0x43, + 0xE3, 0x80, 0x82, 0x43, 0xE3, 0x80, 0x88, 0x43, + 0xE3, 0x80, 0x89, 0x43, 0xE3, 0x80, 0x8A, 0x43, + 0xE3, 0x80, 0x8B, 0x43, 0xE3, 0x80, 0x8C, 0x43, + 0xE3, 0x80, 0x8D, 0x43, 0xE3, 0x80, 0x8E, 0x43, + 0xE3, 0x80, 0x8F, 0x43, 0xE3, 0x80, 0x90, 0x43, + 0xE3, 0x80, 0x91, 0x43, 0xE3, 0x80, 0x92, 0x43, + 0xE3, 0x80, 0x94, 0x43, 0xE3, 0x80, 0x95, 0x43, + // Bytes 4c0 - 4ff + 0xE3, 0x80, 0x96, 0x43, 0xE3, 0x80, 0x97, 0x43, + 0xE3, 0x82, 0xA1, 0x43, 0xE3, 0x82, 0xA2, 0x43, + 0xE3, 0x82, 0xA3, 0x43, 0xE3, 0x82, 0xA4, 0x43, + 0xE3, 0x82, 0xA5, 0x43, 0xE3, 0x82, 0xA6, 0x43, + 0xE3, 0x82, 0xA7, 0x43, 0xE3, 0x82, 0xA8, 0x43, + 0xE3, 0x82, 0xA9, 0x43, 0xE3, 0x82, 0xAA, 0x43, + 0xE3, 0x82, 0xAB, 0x43, 0xE3, 0x82, 0xAD, 0x43, + 0xE3, 0x82, 0xAF, 0x43, 0xE3, 0x82, 0xB1, 0x43, + // Bytes 500 - 53f + 0xE3, 0x82, 0xB3, 0x43, 0xE3, 0x82, 0xB5, 0x43, + 0xE3, 0x82, 0xB7, 0x43, 0xE3, 0x82, 0xB9, 0x43, + 0xE3, 0x82, 0xBB, 0x43, 0xE3, 0x82, 0xBD, 0x43, + 0xE3, 0x82, 0xBF, 0x43, 0xE3, 0x83, 0x81, 0x43, + 0xE3, 0x83, 0x83, 0x43, 0xE3, 0x83, 0x84, 0x43, + 0xE3, 0x83, 0x86, 0x43, 0xE3, 0x83, 0x88, 0x43, + 0xE3, 0x83, 0x8A, 0x43, 0xE3, 0x83, 0x8B, 0x43, + 0xE3, 0x83, 0x8C, 0x43, 0xE3, 0x83, 0x8D, 0x43, + // Bytes 540 - 57f + 0xE3, 0x83, 0x8E, 0x43, 0xE3, 0x83, 0x8F, 0x43, + 0xE3, 0x83, 0x92, 0x43, 0xE3, 0x83, 0x95, 0x43, + 0xE3, 0x83, 0x98, 0x43, 0xE3, 0x83, 0x9B, 0x43, + 0xE3, 0x83, 0x9E, 0x43, 0xE3, 0x83, 0x9F, 0x43, + 0xE3, 0x83, 0xA0, 0x43, 0xE3, 0x83, 0xA1, 0x43, + 0xE3, 0x83, 0xA2, 0x43, 0xE3, 0x83, 0xA3, 0x43, + 0xE3, 0x83, 0xA4, 0x43, 0xE3, 0x83, 0xA5, 0x43, + 0xE3, 0x83, 0xA6, 0x43, 0xE3, 0x83, 0xA7, 0x43, + // Bytes 580 - 5bf + 0xE3, 0x83, 0xA8, 0x43, 0xE3, 0x83, 0xA9, 0x43, + 0xE3, 0x83, 0xAA, 0x43, 0xE3, 0x83, 0xAB, 0x43, + 0xE3, 0x83, 0xAC, 0x43, 0xE3, 0x83, 0xAD, 0x43, + 0xE3, 0x83, 0xAF, 0x43, 0xE3, 0x83, 0xB0, 0x43, + 0xE3, 0x83, 0xB1, 0x43, 0xE3, 0x83, 0xB2, 0x43, + 0xE3, 0x83, 0xB3, 0x43, 0xE3, 0x83, 0xBB, 0x43, + 0xE3, 0x83, 0xBC, 0x43, 0xE3, 0x92, 0x9E, 0x43, + 0xE3, 0x92, 0xB9, 0x43, 0xE3, 0x92, 0xBB, 0x43, + // Bytes 5c0 - 5ff + 0xE3, 0x93, 0x9F, 0x43, 0xE3, 0x94, 0x95, 0x43, + 0xE3, 0x9B, 0xAE, 0x43, 0xE3, 0x9B, 0xBC, 0x43, + 0xE3, 0x9E, 0x81, 0x43, 0xE3, 0xA0, 0xAF, 0x43, + 0xE3, 0xA1, 0xA2, 0x43, 0xE3, 0xA1, 0xBC, 0x43, + 0xE3, 0xA3, 0x87, 0x43, 0xE3, 0xA3, 0xA3, 0x43, + 0xE3, 0xA4, 0x9C, 0x43, 0xE3, 0xA4, 0xBA, 0x43, + 0xE3, 0xA8, 0xAE, 0x43, 0xE3, 0xA9, 0xAC, 0x43, + 0xE3, 0xAB, 0xA4, 0x43, 0xE3, 0xAC, 0x88, 0x43, + // Bytes 600 - 63f + 0xE3, 0xAC, 0x99, 0x43, 0xE3, 0xAD, 0x89, 0x43, + 0xE3, 0xAE, 0x9D, 0x43, 0xE3, 0xB0, 0x98, 0x43, + 0xE3, 0xB1, 0x8E, 0x43, 0xE3, 0xB4, 0xB3, 0x43, + 0xE3, 0xB6, 0x96, 0x43, 0xE3, 0xBA, 0xAC, 0x43, + 0xE3, 0xBA, 0xB8, 0x43, 0xE3, 0xBC, 0x9B, 0x43, + 0xE3, 0xBF, 0xBC, 0x43, 0xE4, 0x80, 0x88, 0x43, + 0xE4, 0x80, 0x98, 0x43, 0xE4, 0x80, 0xB9, 0x43, + 0xE4, 0x81, 0x86, 0x43, 0xE4, 0x82, 0x96, 0x43, + // Bytes 640 - 67f + 0xE4, 0x83, 0xA3, 0x43, 0xE4, 0x84, 0xAF, 0x43, + 0xE4, 0x88, 0x82, 0x43, 0xE4, 0x88, 0xA7, 0x43, + 0xE4, 0x8A, 0xA0, 0x43, 0xE4, 0x8C, 0x81, 0x43, + 0xE4, 0x8C, 0xB4, 0x43, 0xE4, 0x8D, 0x99, 0x43, + 0xE4, 0x8F, 0x95, 0x43, 0xE4, 0x8F, 0x99, 0x43, + 0xE4, 0x90, 0x8B, 0x43, 0xE4, 0x91, 0xAB, 0x43, + 0xE4, 0x94, 0xAB, 0x43, 0xE4, 0x95, 0x9D, 0x43, + 0xE4, 0x95, 0xA1, 0x43, 0xE4, 0x95, 0xAB, 0x43, + // Bytes 680 - 6bf + 0xE4, 0x97, 0x97, 0x43, 0xE4, 0x97, 0xB9, 0x43, + 0xE4, 0x98, 0xB5, 0x43, 0xE4, 0x9A, 0xBE, 0x43, + 0xE4, 0x9B, 0x87, 0x43, 0xE4, 0xA6, 0x95, 0x43, + 0xE4, 0xA7, 0xA6, 0x43, 0xE4, 0xA9, 0xAE, 0x43, + 0xE4, 0xA9, 0xB6, 0x43, 0xE4, 0xAA, 0xB2, 0x43, + 0xE4, 0xAC, 0xB3, 0x43, 0xE4, 0xAF, 0x8E, 0x43, + 0xE4, 0xB3, 0x8E, 0x43, 0xE4, 0xB3, 0xAD, 0x43, + 0xE4, 0xB3, 0xB8, 0x43, 0xE4, 0xB5, 0x96, 0x43, + // Bytes 6c0 - 6ff + 0xE4, 0xB8, 0x80, 0x43, 0xE4, 0xB8, 0x81, 0x43, + 0xE4, 0xB8, 0x83, 0x43, 0xE4, 0xB8, 0x89, 0x43, + 0xE4, 0xB8, 0x8A, 0x43, 0xE4, 0xB8, 0x8B, 0x43, + 0xE4, 0xB8, 0x8D, 0x43, 0xE4, 0xB8, 0x99, 0x43, + 0xE4, 0xB8, 0xA6, 0x43, 0xE4, 0xB8, 0xA8, 0x43, + 0xE4, 0xB8, 0xAD, 0x43, 0xE4, 0xB8, 0xB2, 0x43, + 0xE4, 0xB8, 0xB6, 0x43, 0xE4, 0xB8, 0xB8, 0x43, + 0xE4, 0xB8, 0xB9, 0x43, 0xE4, 0xB8, 0xBD, 0x43, + // Bytes 700 - 73f + 0xE4, 0xB8, 0xBF, 0x43, 0xE4, 0xB9, 0x81, 0x43, + 0xE4, 0xB9, 0x99, 0x43, 0xE4, 0xB9, 0x9D, 0x43, + 0xE4, 0xBA, 0x82, 0x43, 0xE4, 0xBA, 0x85, 0x43, + 0xE4, 0xBA, 0x86, 0x43, 0xE4, 0xBA, 0x8C, 0x43, + 0xE4, 0xBA, 0x94, 0x43, 0xE4, 0xBA, 0xA0, 0x43, + 0xE4, 0xBA, 0xA4, 0x43, 0xE4, 0xBA, 0xAE, 0x43, + 0xE4, 0xBA, 0xBA, 0x43, 0xE4, 0xBB, 0x80, 0x43, + 0xE4, 0xBB, 0x8C, 0x43, 0xE4, 0xBB, 0xA4, 0x43, + // Bytes 740 - 77f + 0xE4, 0xBC, 0x81, 0x43, 0xE4, 0xBC, 0x91, 0x43, + 0xE4, 0xBD, 0xA0, 0x43, 0xE4, 0xBE, 0x80, 0x43, + 0xE4, 0xBE, 0x86, 0x43, 0xE4, 0xBE, 0x8B, 0x43, + 0xE4, 0xBE, 0xAE, 0x43, 0xE4, 0xBE, 0xBB, 0x43, + 0xE4, 0xBE, 0xBF, 0x43, 0xE5, 0x80, 0x82, 0x43, + 0xE5, 0x80, 0xAB, 0x43, 0xE5, 0x81, 0xBA, 0x43, + 0xE5, 0x82, 0x99, 0x43, 0xE5, 0x83, 0x8F, 0x43, + 0xE5, 0x83, 0x9A, 0x43, 0xE5, 0x83, 0xA7, 0x43, + // Bytes 780 - 7bf + 0xE5, 0x84, 0xAA, 0x43, 0xE5, 0x84, 0xBF, 0x43, + 0xE5, 0x85, 0x80, 0x43, 0xE5, 0x85, 0x85, 0x43, + 0xE5, 0x85, 0x8D, 0x43, 0xE5, 0x85, 0x94, 0x43, + 0xE5, 0x85, 0xA4, 0x43, 0xE5, 0x85, 0xA5, 0x43, + 0xE5, 0x85, 0xA7, 0x43, 0xE5, 0x85, 0xA8, 0x43, + 0xE5, 0x85, 0xA9, 0x43, 0xE5, 0x85, 0xAB, 0x43, + 0xE5, 0x85, 0xAD, 0x43, 0xE5, 0x85, 0xB7, 0x43, + 0xE5, 0x86, 0x80, 0x43, 0xE5, 0x86, 0x82, 0x43, + // Bytes 7c0 - 7ff + 0xE5, 0x86, 0x8D, 0x43, 0xE5, 0x86, 0x92, 0x43, + 0xE5, 0x86, 0x95, 0x43, 0xE5, 0x86, 0x96, 0x43, + 0xE5, 0x86, 0x97, 0x43, 0xE5, 0x86, 0x99, 0x43, + 0xE5, 0x86, 0xA4, 0x43, 0xE5, 0x86, 0xAB, 0x43, + 0xE5, 0x86, 0xAC, 0x43, 0xE5, 0x86, 0xB5, 0x43, + 0xE5, 0x86, 0xB7, 0x43, 0xE5, 0x87, 0x89, 0x43, + 0xE5, 0x87, 0x8C, 0x43, 0xE5, 0x87, 0x9C, 0x43, + 0xE5, 0x87, 0x9E, 0x43, 0xE5, 0x87, 0xA0, 0x43, + // Bytes 800 - 83f + 0xE5, 0x87, 0xB5, 0x43, 0xE5, 0x88, 0x80, 0x43, + 0xE5, 0x88, 0x83, 0x43, 0xE5, 0x88, 0x87, 0x43, + 0xE5, 0x88, 0x97, 0x43, 0xE5, 0x88, 0x9D, 0x43, + 0xE5, 0x88, 0xA9, 0x43, 0xE5, 0x88, 0xBA, 0x43, + 0xE5, 0x88, 0xBB, 0x43, 0xE5, 0x89, 0x86, 0x43, + 0xE5, 0x89, 0x8D, 0x43, 0xE5, 0x89, 0xB2, 0x43, + 0xE5, 0x89, 0xB7, 0x43, 0xE5, 0x8A, 0x89, 0x43, + 0xE5, 0x8A, 0x9B, 0x43, 0xE5, 0x8A, 0xA3, 0x43, + // Bytes 840 - 87f + 0xE5, 0x8A, 0xB3, 0x43, 0xE5, 0x8A, 0xB4, 0x43, + 0xE5, 0x8B, 0x87, 0x43, 0xE5, 0x8B, 0x89, 0x43, + 0xE5, 0x8B, 0x92, 0x43, 0xE5, 0x8B, 0x9E, 0x43, + 0xE5, 0x8B, 0xA4, 0x43, 0xE5, 0x8B, 0xB5, 0x43, + 0xE5, 0x8B, 0xB9, 0x43, 0xE5, 0x8B, 0xBA, 0x43, + 0xE5, 0x8C, 0x85, 0x43, 0xE5, 0x8C, 0x86, 0x43, + 0xE5, 0x8C, 0x95, 0x43, 0xE5, 0x8C, 0x97, 0x43, + 0xE5, 0x8C, 0x9A, 0x43, 0xE5, 0x8C, 0xB8, 0x43, + // Bytes 880 - 8bf + 0xE5, 0x8C, 0xBB, 0x43, 0xE5, 0x8C, 0xBF, 0x43, + 0xE5, 0x8D, 0x81, 0x43, 0xE5, 0x8D, 0x84, 0x43, + 0xE5, 0x8D, 0x85, 0x43, 0xE5, 0x8D, 0x89, 0x43, + 0xE5, 0x8D, 0x91, 0x43, 0xE5, 0x8D, 0x94, 0x43, + 0xE5, 0x8D, 0x9A, 0x43, 0xE5, 0x8D, 0x9C, 0x43, + 0xE5, 0x8D, 0xA9, 0x43, 0xE5, 0x8D, 0xB0, 0x43, + 0xE5, 0x8D, 0xB3, 0x43, 0xE5, 0x8D, 0xB5, 0x43, + 0xE5, 0x8D, 0xBD, 0x43, 0xE5, 0x8D, 0xBF, 0x43, + // Bytes 8c0 - 8ff + 0xE5, 0x8E, 0x82, 0x43, 0xE5, 0x8E, 0xB6, 0x43, + 0xE5, 0x8F, 0x83, 0x43, 0xE5, 0x8F, 0x88, 0x43, + 0xE5, 0x8F, 0x8A, 0x43, 0xE5, 0x8F, 0x8C, 0x43, + 0xE5, 0x8F, 0x9F, 0x43, 0xE5, 0x8F, 0xA3, 0x43, + 0xE5, 0x8F, 0xA5, 0x43, 0xE5, 0x8F, 0xAB, 0x43, + 0xE5, 0x8F, 0xAF, 0x43, 0xE5, 0x8F, 0xB1, 0x43, + 0xE5, 0x8F, 0xB3, 0x43, 0xE5, 0x90, 0x86, 0x43, + 0xE5, 0x90, 0x88, 0x43, 0xE5, 0x90, 0x8D, 0x43, + // Bytes 900 - 93f + 0xE5, 0x90, 0x8F, 0x43, 0xE5, 0x90, 0x9D, 0x43, + 0xE5, 0x90, 0xB8, 0x43, 0xE5, 0x90, 0xB9, 0x43, + 0xE5, 0x91, 0x82, 0x43, 0xE5, 0x91, 0x88, 0x43, + 0xE5, 0x91, 0xA8, 0x43, 0xE5, 0x92, 0x9E, 0x43, + 0xE5, 0x92, 0xA2, 0x43, 0xE5, 0x92, 0xBD, 0x43, + 0xE5, 0x93, 0xB6, 0x43, 0xE5, 0x94, 0x90, 0x43, + 0xE5, 0x95, 0x8F, 0x43, 0xE5, 0x95, 0x93, 0x43, + 0xE5, 0x95, 0x95, 0x43, 0xE5, 0x95, 0xA3, 0x43, + // Bytes 940 - 97f + 0xE5, 0x96, 0x84, 0x43, 0xE5, 0x96, 0x87, 0x43, + 0xE5, 0x96, 0x99, 0x43, 0xE5, 0x96, 0x9D, 0x43, + 0xE5, 0x96, 0xAB, 0x43, 0xE5, 0x96, 0xB3, 0x43, + 0xE5, 0x96, 0xB6, 0x43, 0xE5, 0x97, 0x80, 0x43, + 0xE5, 0x97, 0x82, 0x43, 0xE5, 0x97, 0xA2, 0x43, + 0xE5, 0x98, 0x86, 0x43, 0xE5, 0x99, 0x91, 0x43, + 0xE5, 0x99, 0xA8, 0x43, 0xE5, 0x99, 0xB4, 0x43, + 0xE5, 0x9B, 0x97, 0x43, 0xE5, 0x9B, 0x9B, 0x43, + // Bytes 980 - 9bf + 0xE5, 0x9B, 0xB9, 0x43, 0xE5, 0x9C, 0x96, 0x43, + 0xE5, 0x9C, 0x97, 0x43, 0xE5, 0x9C, 0x9F, 0x43, + 0xE5, 0x9C, 0xB0, 0x43, 0xE5, 0x9E, 0x8B, 0x43, + 0xE5, 0x9F, 0x8E, 0x43, 0xE5, 0x9F, 0xB4, 0x43, + 0xE5, 0xA0, 0x8D, 0x43, 0xE5, 0xA0, 0xB1, 0x43, + 0xE5, 0xA0, 0xB2, 0x43, 0xE5, 0xA1, 0x80, 0x43, + 0xE5, 0xA1, 0x9A, 0x43, 0xE5, 0xA1, 0x9E, 0x43, + 0xE5, 0xA2, 0xA8, 0x43, 0xE5, 0xA2, 0xAC, 0x43, + // Bytes 9c0 - 9ff + 0xE5, 0xA2, 0xB3, 0x43, 0xE5, 0xA3, 0x98, 0x43, + 0xE5, 0xA3, 0x9F, 0x43, 0xE5, 0xA3, 0xAB, 0x43, + 0xE5, 0xA3, 0xAE, 0x43, 0xE5, 0xA3, 0xB0, 0x43, + 0xE5, 0xA3, 0xB2, 0x43, 0xE5, 0xA3, 0xB7, 0x43, + 0xE5, 0xA4, 0x82, 0x43, 0xE5, 0xA4, 0x86, 0x43, + 0xE5, 0xA4, 0x8A, 0x43, 0xE5, 0xA4, 0x95, 0x43, + 0xE5, 0xA4, 0x9A, 0x43, 0xE5, 0xA4, 0x9C, 0x43, + 0xE5, 0xA4, 0xA2, 0x43, 0xE5, 0xA4, 0xA7, 0x43, + // Bytes a00 - a3f + 0xE5, 0xA4, 0xA9, 0x43, 0xE5, 0xA5, 0x84, 0x43, + 0xE5, 0xA5, 0x88, 0x43, 0xE5, 0xA5, 0x91, 0x43, + 0xE5, 0xA5, 0x94, 0x43, 0xE5, 0xA5, 0xA2, 0x43, + 0xE5, 0xA5, 0xB3, 0x43, 0xE5, 0xA7, 0x98, 0x43, + 0xE5, 0xA7, 0xAC, 0x43, 0xE5, 0xA8, 0x9B, 0x43, + 0xE5, 0xA8, 0xA7, 0x43, 0xE5, 0xA9, 0xA2, 0x43, + 0xE5, 0xA9, 0xA6, 0x43, 0xE5, 0xAA, 0xB5, 0x43, + 0xE5, 0xAC, 0x88, 0x43, 0xE5, 0xAC, 0xA8, 0x43, + // Bytes a40 - a7f + 0xE5, 0xAC, 0xBE, 0x43, 0xE5, 0xAD, 0x90, 0x43, + 0xE5, 0xAD, 0x97, 0x43, 0xE5, 0xAD, 0xA6, 0x43, + 0xE5, 0xAE, 0x80, 0x43, 0xE5, 0xAE, 0x85, 0x43, + 0xE5, 0xAE, 0x97, 0x43, 0xE5, 0xAF, 0x83, 0x43, + 0xE5, 0xAF, 0x98, 0x43, 0xE5, 0xAF, 0xA7, 0x43, + 0xE5, 0xAF, 0xAE, 0x43, 0xE5, 0xAF, 0xB3, 0x43, + 0xE5, 0xAF, 0xB8, 0x43, 0xE5, 0xAF, 0xBF, 0x43, + 0xE5, 0xB0, 0x86, 0x43, 0xE5, 0xB0, 0x8F, 0x43, + // Bytes a80 - abf + 0xE5, 0xB0, 0xA2, 0x43, 0xE5, 0xB0, 0xB8, 0x43, + 0xE5, 0xB0, 0xBF, 0x43, 0xE5, 0xB1, 0xA0, 0x43, + 0xE5, 0xB1, 0xA2, 0x43, 0xE5, 0xB1, 0xA4, 0x43, + 0xE5, 0xB1, 0xA5, 0x43, 0xE5, 0xB1, 0xAE, 0x43, + 0xE5, 0xB1, 0xB1, 0x43, 0xE5, 0xB2, 0x8D, 0x43, + 0xE5, 0xB3, 0x80, 0x43, 0xE5, 0xB4, 0x99, 0x43, + 0xE5, 0xB5, 0x83, 0x43, 0xE5, 0xB5, 0x90, 0x43, + 0xE5, 0xB5, 0xAB, 0x43, 0xE5, 0xB5, 0xAE, 0x43, + // Bytes ac0 - aff + 0xE5, 0xB5, 0xBC, 0x43, 0xE5, 0xB6, 0xB2, 0x43, + 0xE5, 0xB6, 0xBA, 0x43, 0xE5, 0xB7, 0x9B, 0x43, + 0xE5, 0xB7, 0xA1, 0x43, 0xE5, 0xB7, 0xA2, 0x43, + 0xE5, 0xB7, 0xA5, 0x43, 0xE5, 0xB7, 0xA6, 0x43, + 0xE5, 0xB7, 0xB1, 0x43, 0xE5, 0xB7, 0xBD, 0x43, + 0xE5, 0xB7, 0xBE, 0x43, 0xE5, 0xB8, 0xA8, 0x43, + 0xE5, 0xB8, 0xBD, 0x43, 0xE5, 0xB9, 0xA9, 0x43, + 0xE5, 0xB9, 0xB2, 0x43, 0xE5, 0xB9, 0xB4, 0x43, + // Bytes b00 - b3f + 0xE5, 0xB9, 0xBA, 0x43, 0xE5, 0xB9, 0xBC, 0x43, + 0xE5, 0xB9, 0xBF, 0x43, 0xE5, 0xBA, 0xA6, 0x43, + 0xE5, 0xBA, 0xB0, 0x43, 0xE5, 0xBA, 0xB3, 0x43, + 0xE5, 0xBA, 0xB6, 0x43, 0xE5, 0xBB, 0x89, 0x43, + 0xE5, 0xBB, 0x8A, 0x43, 0xE5, 0xBB, 0x92, 0x43, + 0xE5, 0xBB, 0x93, 0x43, 0xE5, 0xBB, 0x99, 0x43, + 0xE5, 0xBB, 0xAC, 0x43, 0xE5, 0xBB, 0xB4, 0x43, + 0xE5, 0xBB, 0xBE, 0x43, 0xE5, 0xBC, 0x84, 0x43, + // Bytes b40 - b7f + 0xE5, 0xBC, 0x8B, 0x43, 0xE5, 0xBC, 0x93, 0x43, + 0xE5, 0xBC, 0xA2, 0x43, 0xE5, 0xBD, 0x90, 0x43, + 0xE5, 0xBD, 0x93, 0x43, 0xE5, 0xBD, 0xA1, 0x43, + 0xE5, 0xBD, 0xA2, 0x43, 0xE5, 0xBD, 0xA9, 0x43, + 0xE5, 0xBD, 0xAB, 0x43, 0xE5, 0xBD, 0xB3, 0x43, + 0xE5, 0xBE, 0x8B, 0x43, 0xE5, 0xBE, 0x8C, 0x43, + 0xE5, 0xBE, 0x97, 0x43, 0xE5, 0xBE, 0x9A, 0x43, + 0xE5, 0xBE, 0xA9, 0x43, 0xE5, 0xBE, 0xAD, 0x43, + // Bytes b80 - bbf + 0xE5, 0xBF, 0x83, 0x43, 0xE5, 0xBF, 0x8D, 0x43, + 0xE5, 0xBF, 0x97, 0x43, 0xE5, 0xBF, 0xB5, 0x43, + 0xE5, 0xBF, 0xB9, 0x43, 0xE6, 0x80, 0x92, 0x43, + 0xE6, 0x80, 0x9C, 0x43, 0xE6, 0x81, 0xB5, 0x43, + 0xE6, 0x82, 0x81, 0x43, 0xE6, 0x82, 0x94, 0x43, + 0xE6, 0x83, 0x87, 0x43, 0xE6, 0x83, 0x98, 0x43, + 0xE6, 0x83, 0xA1, 0x43, 0xE6, 0x84, 0x88, 0x43, + 0xE6, 0x85, 0x84, 0x43, 0xE6, 0x85, 0x88, 0x43, + // Bytes bc0 - bff + 0xE6, 0x85, 0x8C, 0x43, 0xE6, 0x85, 0x8E, 0x43, + 0xE6, 0x85, 0xA0, 0x43, 0xE6, 0x85, 0xA8, 0x43, + 0xE6, 0x85, 0xBA, 0x43, 0xE6, 0x86, 0x8E, 0x43, + 0xE6, 0x86, 0x90, 0x43, 0xE6, 0x86, 0xA4, 0x43, + 0xE6, 0x86, 0xAF, 0x43, 0xE6, 0x86, 0xB2, 0x43, + 0xE6, 0x87, 0x9E, 0x43, 0xE6, 0x87, 0xB2, 0x43, + 0xE6, 0x87, 0xB6, 0x43, 0xE6, 0x88, 0x80, 0x43, + 0xE6, 0x88, 0x88, 0x43, 0xE6, 0x88, 0x90, 0x43, + // Bytes c00 - c3f + 0xE6, 0x88, 0x9B, 0x43, 0xE6, 0x88, 0xAE, 0x43, + 0xE6, 0x88, 0xB4, 0x43, 0xE6, 0x88, 0xB6, 0x43, + 0xE6, 0x89, 0x8B, 0x43, 0xE6, 0x89, 0x93, 0x43, + 0xE6, 0x89, 0x9D, 0x43, 0xE6, 0x8A, 0x95, 0x43, + 0xE6, 0x8A, 0xB1, 0x43, 0xE6, 0x8B, 0x89, 0x43, + 0xE6, 0x8B, 0x8F, 0x43, 0xE6, 0x8B, 0x93, 0x43, + 0xE6, 0x8B, 0x94, 0x43, 0xE6, 0x8B, 0xBC, 0x43, + 0xE6, 0x8B, 0xBE, 0x43, 0xE6, 0x8C, 0x87, 0x43, + // Bytes c40 - c7f + 0xE6, 0x8C, 0xBD, 0x43, 0xE6, 0x8D, 0x90, 0x43, + 0xE6, 0x8D, 0x95, 0x43, 0xE6, 0x8D, 0xA8, 0x43, + 0xE6, 0x8D, 0xBB, 0x43, 0xE6, 0x8E, 0x83, 0x43, + 0xE6, 0x8E, 0xA0, 0x43, 0xE6, 0x8E, 0xA9, 0x43, + 0xE6, 0x8F, 0x84, 0x43, 0xE6, 0x8F, 0x85, 0x43, + 0xE6, 0x8F, 0xA4, 0x43, 0xE6, 0x90, 0x9C, 0x43, + 0xE6, 0x90, 0xA2, 0x43, 0xE6, 0x91, 0x92, 0x43, + 0xE6, 0x91, 0xA9, 0x43, 0xE6, 0x91, 0xB7, 0x43, + // Bytes c80 - cbf + 0xE6, 0x91, 0xBE, 0x43, 0xE6, 0x92, 0x9A, 0x43, + 0xE6, 0x92, 0x9D, 0x43, 0xE6, 0x93, 0x84, 0x43, + 0xE6, 0x94, 0xAF, 0x43, 0xE6, 0x94, 0xB4, 0x43, + 0xE6, 0x95, 0x8F, 0x43, 0xE6, 0x95, 0x96, 0x43, + 0xE6, 0x95, 0xAC, 0x43, 0xE6, 0x95, 0xB8, 0x43, + 0xE6, 0x96, 0x87, 0x43, 0xE6, 0x96, 0x97, 0x43, + 0xE6, 0x96, 0x99, 0x43, 0xE6, 0x96, 0xA4, 0x43, + 0xE6, 0x96, 0xB0, 0x43, 0xE6, 0x96, 0xB9, 0x43, + // Bytes cc0 - cff + 0xE6, 0x97, 0x85, 0x43, 0xE6, 0x97, 0xA0, 0x43, + 0xE6, 0x97, 0xA2, 0x43, 0xE6, 0x97, 0xA3, 0x43, + 0xE6, 0x97, 0xA5, 0x43, 0xE6, 0x98, 0x93, 0x43, + 0xE6, 0x98, 0xA0, 0x43, 0xE6, 0x99, 0x89, 0x43, + 0xE6, 0x99, 0xB4, 0x43, 0xE6, 0x9A, 0x88, 0x43, + 0xE6, 0x9A, 0x91, 0x43, 0xE6, 0x9A, 0x9C, 0x43, + 0xE6, 0x9A, 0xB4, 0x43, 0xE6, 0x9B, 0x86, 0x43, + 0xE6, 0x9B, 0xB0, 0x43, 0xE6, 0x9B, 0xB4, 0x43, + // Bytes d00 - d3f + 0xE6, 0x9B, 0xB8, 0x43, 0xE6, 0x9C, 0x80, 0x43, + 0xE6, 0x9C, 0x88, 0x43, 0xE6, 0x9C, 0x89, 0x43, + 0xE6, 0x9C, 0x97, 0x43, 0xE6, 0x9C, 0x9B, 0x43, + 0xE6, 0x9C, 0xA1, 0x43, 0xE6, 0x9C, 0xA8, 0x43, + 0xE6, 0x9D, 0x8E, 0x43, 0xE6, 0x9D, 0x93, 0x43, + 0xE6, 0x9D, 0x96, 0x43, 0xE6, 0x9D, 0x9E, 0x43, + 0xE6, 0x9D, 0xBB, 0x43, 0xE6, 0x9E, 0x85, 0x43, + 0xE6, 0x9E, 0x97, 0x43, 0xE6, 0x9F, 0xB3, 0x43, + // Bytes d40 - d7f + 0xE6, 0x9F, 0xBA, 0x43, 0xE6, 0xA0, 0x97, 0x43, + 0xE6, 0xA0, 0x9F, 0x43, 0xE6, 0xA0, 0xAA, 0x43, + 0xE6, 0xA1, 0x92, 0x43, 0xE6, 0xA2, 0x81, 0x43, + 0xE6, 0xA2, 0x85, 0x43, 0xE6, 0xA2, 0x8E, 0x43, + 0xE6, 0xA2, 0xA8, 0x43, 0xE6, 0xA4, 0x94, 0x43, + 0xE6, 0xA5, 0x82, 0x43, 0xE6, 0xA6, 0xA3, 0x43, + 0xE6, 0xA7, 0xAA, 0x43, 0xE6, 0xA8, 0x82, 0x43, + 0xE6, 0xA8, 0x93, 0x43, 0xE6, 0xAA, 0xA8, 0x43, + // Bytes d80 - dbf + 0xE6, 0xAB, 0x93, 0x43, 0xE6, 0xAB, 0x9B, 0x43, + 0xE6, 0xAC, 0x84, 0x43, 0xE6, 0xAC, 0xA0, 0x43, + 0xE6, 0xAC, 0xA1, 0x43, 0xE6, 0xAD, 0x94, 0x43, + 0xE6, 0xAD, 0xA2, 0x43, 0xE6, 0xAD, 0xA3, 0x43, + 0xE6, 0xAD, 0xB2, 0x43, 0xE6, 0xAD, 0xB7, 0x43, + 0xE6, 0xAD, 0xB9, 0x43, 0xE6, 0xAE, 0x9F, 0x43, + 0xE6, 0xAE, 0xAE, 0x43, 0xE6, 0xAE, 0xB3, 0x43, + 0xE6, 0xAE, 0xBA, 0x43, 0xE6, 0xAE, 0xBB, 0x43, + // Bytes dc0 - dff + 0xE6, 0xAF, 0x8B, 0x43, 0xE6, 0xAF, 0x8D, 0x43, + 0xE6, 0xAF, 0x94, 0x43, 0xE6, 0xAF, 0x9B, 0x43, + 0xE6, 0xB0, 0x8F, 0x43, 0xE6, 0xB0, 0x94, 0x43, + 0xE6, 0xB0, 0xB4, 0x43, 0xE6, 0xB1, 0x8E, 0x43, + 0xE6, 0xB1, 0xA7, 0x43, 0xE6, 0xB2, 0x88, 0x43, + 0xE6, 0xB2, 0xBF, 0x43, 0xE6, 0xB3, 0x8C, 0x43, + 0xE6, 0xB3, 0x8D, 0x43, 0xE6, 0xB3, 0xA5, 0x43, + 0xE6, 0xB3, 0xA8, 0x43, 0xE6, 0xB4, 0x96, 0x43, + // Bytes e00 - e3f + 0xE6, 0xB4, 0x9B, 0x43, 0xE6, 0xB4, 0x9E, 0x43, + 0xE6, 0xB4, 0xB4, 0x43, 0xE6, 0xB4, 0xBE, 0x43, + 0xE6, 0xB5, 0x81, 0x43, 0xE6, 0xB5, 0xA9, 0x43, + 0xE6, 0xB5, 0xAA, 0x43, 0xE6, 0xB5, 0xB7, 0x43, + 0xE6, 0xB5, 0xB8, 0x43, 0xE6, 0xB6, 0x85, 0x43, + 0xE6, 0xB7, 0x8B, 0x43, 0xE6, 0xB7, 0x9A, 0x43, + 0xE6, 0xB7, 0xAA, 0x43, 0xE6, 0xB7, 0xB9, 0x43, + 0xE6, 0xB8, 0x9A, 0x43, 0xE6, 0xB8, 0xAF, 0x43, + // Bytes e40 - e7f + 0xE6, 0xB9, 0xAE, 0x43, 0xE6, 0xBA, 0x80, 0x43, + 0xE6, 0xBA, 0x9C, 0x43, 0xE6, 0xBA, 0xBA, 0x43, + 0xE6, 0xBB, 0x87, 0x43, 0xE6, 0xBB, 0x8B, 0x43, + 0xE6, 0xBB, 0x91, 0x43, 0xE6, 0xBB, 0x9B, 0x43, + 0xE6, 0xBC, 0x8F, 0x43, 0xE6, 0xBC, 0x94, 0x43, + 0xE6, 0xBC, 0xA2, 0x43, 0xE6, 0xBC, 0xA3, 0x43, + 0xE6, 0xBD, 0xAE, 0x43, 0xE6, 0xBF, 0x86, 0x43, + 0xE6, 0xBF, 0xAB, 0x43, 0xE6, 0xBF, 0xBE, 0x43, + // Bytes e80 - ebf + 0xE7, 0x80, 0x9B, 0x43, 0xE7, 0x80, 0x9E, 0x43, + 0xE7, 0x80, 0xB9, 0x43, 0xE7, 0x81, 0x8A, 0x43, + 0xE7, 0x81, 0xAB, 0x43, 0xE7, 0x81, 0xB0, 0x43, + 0xE7, 0x81, 0xB7, 0x43, 0xE7, 0x81, 0xBD, 0x43, + 0xE7, 0x82, 0x99, 0x43, 0xE7, 0x82, 0xAD, 0x43, + 0xE7, 0x83, 0x88, 0x43, 0xE7, 0x83, 0x99, 0x43, + 0xE7, 0x84, 0xA1, 0x43, 0xE7, 0x85, 0x85, 0x43, + 0xE7, 0x85, 0x89, 0x43, 0xE7, 0x85, 0xAE, 0x43, + // Bytes ec0 - eff + 0xE7, 0x86, 0x9C, 0x43, 0xE7, 0x87, 0x8E, 0x43, + 0xE7, 0x87, 0x90, 0x43, 0xE7, 0x88, 0x90, 0x43, + 0xE7, 0x88, 0x9B, 0x43, 0xE7, 0x88, 0xA8, 0x43, + 0xE7, 0x88, 0xAA, 0x43, 0xE7, 0x88, 0xAB, 0x43, + 0xE7, 0x88, 0xB5, 0x43, 0xE7, 0x88, 0xB6, 0x43, + 0xE7, 0x88, 0xBB, 0x43, 0xE7, 0x88, 0xBF, 0x43, + 0xE7, 0x89, 0x87, 0x43, 0xE7, 0x89, 0x90, 0x43, + 0xE7, 0x89, 0x99, 0x43, 0xE7, 0x89, 0x9B, 0x43, + // Bytes f00 - f3f + 0xE7, 0x89, 0xA2, 0x43, 0xE7, 0x89, 0xB9, 0x43, + 0xE7, 0x8A, 0x80, 0x43, 0xE7, 0x8A, 0x95, 0x43, + 0xE7, 0x8A, 0xAC, 0x43, 0xE7, 0x8A, 0xAF, 0x43, + 0xE7, 0x8B, 0x80, 0x43, 0xE7, 0x8B, 0xBC, 0x43, + 0xE7, 0x8C, 0xAA, 0x43, 0xE7, 0x8D, 0xB5, 0x43, + 0xE7, 0x8D, 0xBA, 0x43, 0xE7, 0x8E, 0x84, 0x43, + 0xE7, 0x8E, 0x87, 0x43, 0xE7, 0x8E, 0x89, 0x43, + 0xE7, 0x8E, 0x8B, 0x43, 0xE7, 0x8E, 0xA5, 0x43, + // Bytes f40 - f7f + 0xE7, 0x8E, 0xB2, 0x43, 0xE7, 0x8F, 0x9E, 0x43, + 0xE7, 0x90, 0x86, 0x43, 0xE7, 0x90, 0x89, 0x43, + 0xE7, 0x90, 0xA2, 0x43, 0xE7, 0x91, 0x87, 0x43, + 0xE7, 0x91, 0x9C, 0x43, 0xE7, 0x91, 0xA9, 0x43, + 0xE7, 0x91, 0xB1, 0x43, 0xE7, 0x92, 0x85, 0x43, + 0xE7, 0x92, 0x89, 0x43, 0xE7, 0x92, 0x98, 0x43, + 0xE7, 0x93, 0x8A, 0x43, 0xE7, 0x93, 0x9C, 0x43, + 0xE7, 0x93, 0xA6, 0x43, 0xE7, 0x94, 0x86, 0x43, + // Bytes f80 - fbf + 0xE7, 0x94, 0x98, 0x43, 0xE7, 0x94, 0x9F, 0x43, + 0xE7, 0x94, 0xA4, 0x43, 0xE7, 0x94, 0xA8, 0x43, + 0xE7, 0x94, 0xB0, 0x43, 0xE7, 0x94, 0xB2, 0x43, + 0xE7, 0x94, 0xB3, 0x43, 0xE7, 0x94, 0xB7, 0x43, + 0xE7, 0x94, 0xBB, 0x43, 0xE7, 0x94, 0xBE, 0x43, + 0xE7, 0x95, 0x99, 0x43, 0xE7, 0x95, 0xA5, 0x43, + 0xE7, 0x95, 0xB0, 0x43, 0xE7, 0x96, 0x8B, 0x43, + 0xE7, 0x96, 0x92, 0x43, 0xE7, 0x97, 0xA2, 0x43, + // Bytes fc0 - fff + 0xE7, 0x98, 0x90, 0x43, 0xE7, 0x98, 0x9D, 0x43, + 0xE7, 0x98, 0x9F, 0x43, 0xE7, 0x99, 0x82, 0x43, + 0xE7, 0x99, 0xA9, 0x43, 0xE7, 0x99, 0xB6, 0x43, + 0xE7, 0x99, 0xBD, 0x43, 0xE7, 0x9A, 0xAE, 0x43, + 0xE7, 0x9A, 0xBF, 0x43, 0xE7, 0x9B, 0x8A, 0x43, + 0xE7, 0x9B, 0x9B, 0x43, 0xE7, 0x9B, 0xA3, 0x43, + 0xE7, 0x9B, 0xA7, 0x43, 0xE7, 0x9B, 0xAE, 0x43, + 0xE7, 0x9B, 0xB4, 0x43, 0xE7, 0x9C, 0x81, 0x43, + // Bytes 1000 - 103f + 0xE7, 0x9C, 0x9E, 0x43, 0xE7, 0x9C, 0x9F, 0x43, + 0xE7, 0x9D, 0x80, 0x43, 0xE7, 0x9D, 0x8A, 0x43, + 0xE7, 0x9E, 0x8B, 0x43, 0xE7, 0x9E, 0xA7, 0x43, + 0xE7, 0x9F, 0x9B, 0x43, 0xE7, 0x9F, 0xA2, 0x43, + 0xE7, 0x9F, 0xB3, 0x43, 0xE7, 0xA1, 0x8E, 0x43, + 0xE7, 0xA1, 0xAB, 0x43, 0xE7, 0xA2, 0x8C, 0x43, + 0xE7, 0xA2, 0x91, 0x43, 0xE7, 0xA3, 0x8A, 0x43, + 0xE7, 0xA3, 0x8C, 0x43, 0xE7, 0xA3, 0xBB, 0x43, + // Bytes 1040 - 107f + 0xE7, 0xA4, 0xAA, 0x43, 0xE7, 0xA4, 0xBA, 0x43, + 0xE7, 0xA4, 0xBC, 0x43, 0xE7, 0xA4, 0xBE, 0x43, + 0xE7, 0xA5, 0x88, 0x43, 0xE7, 0xA5, 0x89, 0x43, + 0xE7, 0xA5, 0x90, 0x43, 0xE7, 0xA5, 0x96, 0x43, + 0xE7, 0xA5, 0x9D, 0x43, 0xE7, 0xA5, 0x9E, 0x43, + 0xE7, 0xA5, 0xA5, 0x43, 0xE7, 0xA5, 0xBF, 0x43, + 0xE7, 0xA6, 0x81, 0x43, 0xE7, 0xA6, 0x8D, 0x43, + 0xE7, 0xA6, 0x8E, 0x43, 0xE7, 0xA6, 0x8F, 0x43, + // Bytes 1080 - 10bf + 0xE7, 0xA6, 0xAE, 0x43, 0xE7, 0xA6, 0xB8, 0x43, + 0xE7, 0xA6, 0xBE, 0x43, 0xE7, 0xA7, 0x8A, 0x43, + 0xE7, 0xA7, 0x98, 0x43, 0xE7, 0xA7, 0xAB, 0x43, + 0xE7, 0xA8, 0x9C, 0x43, 0xE7, 0xA9, 0x80, 0x43, + 0xE7, 0xA9, 0x8A, 0x43, 0xE7, 0xA9, 0x8F, 0x43, + 0xE7, 0xA9, 0xB4, 0x43, 0xE7, 0xA9, 0xBA, 0x43, + 0xE7, 0xAA, 0x81, 0x43, 0xE7, 0xAA, 0xB1, 0x43, + 0xE7, 0xAB, 0x8B, 0x43, 0xE7, 0xAB, 0xAE, 0x43, + // Bytes 10c0 - 10ff + 0xE7, 0xAB, 0xB9, 0x43, 0xE7, 0xAC, 0xA0, 0x43, + 0xE7, 0xAE, 0x8F, 0x43, 0xE7, 0xAF, 0x80, 0x43, + 0xE7, 0xAF, 0x86, 0x43, 0xE7, 0xAF, 0x89, 0x43, + 0xE7, 0xB0, 0xBE, 0x43, 0xE7, 0xB1, 0xA0, 0x43, + 0xE7, 0xB1, 0xB3, 0x43, 0xE7, 0xB1, 0xBB, 0x43, + 0xE7, 0xB2, 0x92, 0x43, 0xE7, 0xB2, 0xBE, 0x43, + 0xE7, 0xB3, 0x92, 0x43, 0xE7, 0xB3, 0x96, 0x43, + 0xE7, 0xB3, 0xA3, 0x43, 0xE7, 0xB3, 0xA7, 0x43, + // Bytes 1100 - 113f + 0xE7, 0xB3, 0xA8, 0x43, 0xE7, 0xB3, 0xB8, 0x43, + 0xE7, 0xB4, 0x80, 0x43, 0xE7, 0xB4, 0x90, 0x43, + 0xE7, 0xB4, 0xA2, 0x43, 0xE7, 0xB4, 0xAF, 0x43, + 0xE7, 0xB5, 0x82, 0x43, 0xE7, 0xB5, 0x9B, 0x43, + 0xE7, 0xB5, 0xA3, 0x43, 0xE7, 0xB6, 0xA0, 0x43, + 0xE7, 0xB6, 0xBE, 0x43, 0xE7, 0xB7, 0x87, 0x43, + 0xE7, 0xB7, 0xB4, 0x43, 0xE7, 0xB8, 0x82, 0x43, + 0xE7, 0xB8, 0x89, 0x43, 0xE7, 0xB8, 0xB7, 0x43, + // Bytes 1140 - 117f + 0xE7, 0xB9, 0x81, 0x43, 0xE7, 0xB9, 0x85, 0x43, + 0xE7, 0xBC, 0xB6, 0x43, 0xE7, 0xBC, 0xBE, 0x43, + 0xE7, 0xBD, 0x91, 0x43, 0xE7, 0xBD, 0xB2, 0x43, + 0xE7, 0xBD, 0xB9, 0x43, 0xE7, 0xBD, 0xBA, 0x43, + 0xE7, 0xBE, 0x85, 0x43, 0xE7, 0xBE, 0x8A, 0x43, + 0xE7, 0xBE, 0x95, 0x43, 0xE7, 0xBE, 0x9A, 0x43, + 0xE7, 0xBE, 0xBD, 0x43, 0xE7, 0xBF, 0xBA, 0x43, + 0xE8, 0x80, 0x81, 0x43, 0xE8, 0x80, 0x85, 0x43, + // Bytes 1180 - 11bf + 0xE8, 0x80, 0x8C, 0x43, 0xE8, 0x80, 0x92, 0x43, + 0xE8, 0x80, 0xB3, 0x43, 0xE8, 0x81, 0x86, 0x43, + 0xE8, 0x81, 0xA0, 0x43, 0xE8, 0x81, 0xAF, 0x43, + 0xE8, 0x81, 0xB0, 0x43, 0xE8, 0x81, 0xBE, 0x43, + 0xE8, 0x81, 0xBF, 0x43, 0xE8, 0x82, 0x89, 0x43, + 0xE8, 0x82, 0x8B, 0x43, 0xE8, 0x82, 0xAD, 0x43, + 0xE8, 0x82, 0xB2, 0x43, 0xE8, 0x84, 0x83, 0x43, + 0xE8, 0x84, 0xBE, 0x43, 0xE8, 0x87, 0x98, 0x43, + // Bytes 11c0 - 11ff + 0xE8, 0x87, 0xA3, 0x43, 0xE8, 0x87, 0xA8, 0x43, + 0xE8, 0x87, 0xAA, 0x43, 0xE8, 0x87, 0xAD, 0x43, + 0xE8, 0x87, 0xB3, 0x43, 0xE8, 0x87, 0xBC, 0x43, + 0xE8, 0x88, 0x81, 0x43, 0xE8, 0x88, 0x84, 0x43, + 0xE8, 0x88, 0x8C, 0x43, 0xE8, 0x88, 0x98, 0x43, + 0xE8, 0x88, 0x9B, 0x43, 0xE8, 0x88, 0x9F, 0x43, + 0xE8, 0x89, 0xAE, 0x43, 0xE8, 0x89, 0xAF, 0x43, + 0xE8, 0x89, 0xB2, 0x43, 0xE8, 0x89, 0xB8, 0x43, + // Bytes 1200 - 123f + 0xE8, 0x89, 0xB9, 0x43, 0xE8, 0x8A, 0x8B, 0x43, + 0xE8, 0x8A, 0x91, 0x43, 0xE8, 0x8A, 0x9D, 0x43, + 0xE8, 0x8A, 0xB1, 0x43, 0xE8, 0x8A, 0xB3, 0x43, + 0xE8, 0x8A, 0xBD, 0x43, 0xE8, 0x8B, 0xA5, 0x43, + 0xE8, 0x8B, 0xA6, 0x43, 0xE8, 0x8C, 0x9D, 0x43, + 0xE8, 0x8C, 0xA3, 0x43, 0xE8, 0x8C, 0xB6, 0x43, + 0xE8, 0x8D, 0x92, 0x43, 0xE8, 0x8D, 0x93, 0x43, + 0xE8, 0x8D, 0xA3, 0x43, 0xE8, 0x8E, 0xAD, 0x43, + // Bytes 1240 - 127f + 0xE8, 0x8E, 0xBD, 0x43, 0xE8, 0x8F, 0x89, 0x43, + 0xE8, 0x8F, 0x8A, 0x43, 0xE8, 0x8F, 0x8C, 0x43, + 0xE8, 0x8F, 0x9C, 0x43, 0xE8, 0x8F, 0xA7, 0x43, + 0xE8, 0x8F, 0xAF, 0x43, 0xE8, 0x8F, 0xB1, 0x43, + 0xE8, 0x90, 0xBD, 0x43, 0xE8, 0x91, 0x89, 0x43, + 0xE8, 0x91, 0x97, 0x43, 0xE8, 0x93, 0xAE, 0x43, + 0xE8, 0x93, 0xB1, 0x43, 0xE8, 0x93, 0xB3, 0x43, + 0xE8, 0x93, 0xBC, 0x43, 0xE8, 0x94, 0x96, 0x43, + // Bytes 1280 - 12bf + 0xE8, 0x95, 0xA4, 0x43, 0xE8, 0x97, 0x8D, 0x43, + 0xE8, 0x97, 0xBA, 0x43, 0xE8, 0x98, 0x86, 0x43, + 0xE8, 0x98, 0x92, 0x43, 0xE8, 0x98, 0xAD, 0x43, + 0xE8, 0x98, 0xBF, 0x43, 0xE8, 0x99, 0x8D, 0x43, + 0xE8, 0x99, 0x90, 0x43, 0xE8, 0x99, 0x9C, 0x43, + 0xE8, 0x99, 0xA7, 0x43, 0xE8, 0x99, 0xA9, 0x43, + 0xE8, 0x99, 0xAB, 0x43, 0xE8, 0x9A, 0x88, 0x43, + 0xE8, 0x9A, 0xA9, 0x43, 0xE8, 0x9B, 0xA2, 0x43, + // Bytes 12c0 - 12ff + 0xE8, 0x9C, 0x8E, 0x43, 0xE8, 0x9C, 0xA8, 0x43, + 0xE8, 0x9D, 0xAB, 0x43, 0xE8, 0x9D, 0xB9, 0x43, + 0xE8, 0x9E, 0x86, 0x43, 0xE8, 0x9E, 0xBA, 0x43, + 0xE8, 0x9F, 0xA1, 0x43, 0xE8, 0xA0, 0x81, 0x43, + 0xE8, 0xA0, 0x9F, 0x43, 0xE8, 0xA1, 0x80, 0x43, + 0xE8, 0xA1, 0x8C, 0x43, 0xE8, 0xA1, 0xA0, 0x43, + 0xE8, 0xA1, 0xA3, 0x43, 0xE8, 0xA3, 0x82, 0x43, + 0xE8, 0xA3, 0x8F, 0x43, 0xE8, 0xA3, 0x97, 0x43, + // Bytes 1300 - 133f + 0xE8, 0xA3, 0x9E, 0x43, 0xE8, 0xA3, 0xA1, 0x43, + 0xE8, 0xA3, 0xB8, 0x43, 0xE8, 0xA3, 0xBA, 0x43, + 0xE8, 0xA4, 0x90, 0x43, 0xE8, 0xA5, 0x81, 0x43, + 0xE8, 0xA5, 0xA4, 0x43, 0xE8, 0xA5, 0xBE, 0x43, + 0xE8, 0xA6, 0x86, 0x43, 0xE8, 0xA6, 0x8B, 0x43, + 0xE8, 0xA6, 0x96, 0x43, 0xE8, 0xA7, 0x92, 0x43, + 0xE8, 0xA7, 0xA3, 0x43, 0xE8, 0xA8, 0x80, 0x43, + 0xE8, 0xAA, 0xA0, 0x43, 0xE8, 0xAA, 0xAA, 0x43, + // Bytes 1340 - 137f + 0xE8, 0xAA, 0xBF, 0x43, 0xE8, 0xAB, 0x8B, 0x43, + 0xE8, 0xAB, 0x92, 0x43, 0xE8, 0xAB, 0x96, 0x43, + 0xE8, 0xAB, 0xAD, 0x43, 0xE8, 0xAB, 0xB8, 0x43, + 0xE8, 0xAB, 0xBE, 0x43, 0xE8, 0xAC, 0x81, 0x43, + 0xE8, 0xAC, 0xB9, 0x43, 0xE8, 0xAD, 0x98, 0x43, + 0xE8, 0xAE, 0x80, 0x43, 0xE8, 0xAE, 0x8A, 0x43, + 0xE8, 0xB0, 0xB7, 0x43, 0xE8, 0xB1, 0x86, 0x43, + 0xE8, 0xB1, 0x88, 0x43, 0xE8, 0xB1, 0x95, 0x43, + // Bytes 1380 - 13bf + 0xE8, 0xB1, 0xB8, 0x43, 0xE8, 0xB2, 0x9D, 0x43, + 0xE8, 0xB2, 0xA1, 0x43, 0xE8, 0xB2, 0xA9, 0x43, + 0xE8, 0xB2, 0xAB, 0x43, 0xE8, 0xB3, 0x81, 0x43, + 0xE8, 0xB3, 0x82, 0x43, 0xE8, 0xB3, 0x87, 0x43, + 0xE8, 0xB3, 0x88, 0x43, 0xE8, 0xB3, 0x93, 0x43, + 0xE8, 0xB4, 0x88, 0x43, 0xE8, 0xB4, 0x9B, 0x43, + 0xE8, 0xB5, 0xA4, 0x43, 0xE8, 0xB5, 0xB0, 0x43, + 0xE8, 0xB5, 0xB7, 0x43, 0xE8, 0xB6, 0xB3, 0x43, + // Bytes 13c0 - 13ff + 0xE8, 0xB6, 0xBC, 0x43, 0xE8, 0xB7, 0x8B, 0x43, + 0xE8, 0xB7, 0xAF, 0x43, 0xE8, 0xB7, 0xB0, 0x43, + 0xE8, 0xBA, 0xAB, 0x43, 0xE8, 0xBB, 0x8A, 0x43, + 0xE8, 0xBB, 0x94, 0x43, 0xE8, 0xBC, 0xA6, 0x43, + 0xE8, 0xBC, 0xAA, 0x43, 0xE8, 0xBC, 0xB8, 0x43, + 0xE8, 0xBC, 0xBB, 0x43, 0xE8, 0xBD, 0xA2, 0x43, + 0xE8, 0xBE, 0x9B, 0x43, 0xE8, 0xBE, 0x9E, 0x43, + 0xE8, 0xBE, 0xB0, 0x43, 0xE8, 0xBE, 0xB5, 0x43, + // Bytes 1400 - 143f + 0xE8, 0xBE, 0xB6, 0x43, 0xE9, 0x80, 0xA3, 0x43, + 0xE9, 0x80, 0xB8, 0x43, 0xE9, 0x81, 0x8A, 0x43, + 0xE9, 0x81, 0xA9, 0x43, 0xE9, 0x81, 0xB2, 0x43, + 0xE9, 0x81, 0xBC, 0x43, 0xE9, 0x82, 0x8F, 0x43, + 0xE9, 0x82, 0x91, 0x43, 0xE9, 0x82, 0x94, 0x43, + 0xE9, 0x83, 0x8E, 0x43, 0xE9, 0x83, 0x9E, 0x43, + 0xE9, 0x83, 0xB1, 0x43, 0xE9, 0x83, 0xBD, 0x43, + 0xE9, 0x84, 0x91, 0x43, 0xE9, 0x84, 0x9B, 0x43, + // Bytes 1440 - 147f + 0xE9, 0x85, 0x89, 0x43, 0xE9, 0x85, 0x8D, 0x43, + 0xE9, 0x85, 0xAA, 0x43, 0xE9, 0x86, 0x99, 0x43, + 0xE9, 0x86, 0xB4, 0x43, 0xE9, 0x87, 0x86, 0x43, + 0xE9, 0x87, 0x8C, 0x43, 0xE9, 0x87, 0x8F, 0x43, + 0xE9, 0x87, 0x91, 0x43, 0xE9, 0x88, 0xB4, 0x43, + 0xE9, 0x88, 0xB8, 0x43, 0xE9, 0x89, 0xB6, 0x43, + 0xE9, 0x89, 0xBC, 0x43, 0xE9, 0x8B, 0x97, 0x43, + 0xE9, 0x8B, 0x98, 0x43, 0xE9, 0x8C, 0x84, 0x43, + // Bytes 1480 - 14bf + 0xE9, 0x8D, 0x8A, 0x43, 0xE9, 0x8F, 0xB9, 0x43, + 0xE9, 0x90, 0x95, 0x43, 0xE9, 0x95, 0xB7, 0x43, + 0xE9, 0x96, 0x80, 0x43, 0xE9, 0x96, 0x8B, 0x43, + 0xE9, 0x96, 0xAD, 0x43, 0xE9, 0x96, 0xB7, 0x43, + 0xE9, 0x98, 0x9C, 0x43, 0xE9, 0x98, 0xAE, 0x43, + 0xE9, 0x99, 0x8B, 0x43, 0xE9, 0x99, 0x8D, 0x43, + 0xE9, 0x99, 0xB5, 0x43, 0xE9, 0x99, 0xB8, 0x43, + 0xE9, 0x99, 0xBC, 0x43, 0xE9, 0x9A, 0x86, 0x43, + // Bytes 14c0 - 14ff + 0xE9, 0x9A, 0xA3, 0x43, 0xE9, 0x9A, 0xB6, 0x43, + 0xE9, 0x9A, 0xB7, 0x43, 0xE9, 0x9A, 0xB8, 0x43, + 0xE9, 0x9A, 0xB9, 0x43, 0xE9, 0x9B, 0x83, 0x43, + 0xE9, 0x9B, 0xA2, 0x43, 0xE9, 0x9B, 0xA3, 0x43, + 0xE9, 0x9B, 0xA8, 0x43, 0xE9, 0x9B, 0xB6, 0x43, + 0xE9, 0x9B, 0xB7, 0x43, 0xE9, 0x9C, 0xA3, 0x43, + 0xE9, 0x9C, 0xB2, 0x43, 0xE9, 0x9D, 0x88, 0x43, + 0xE9, 0x9D, 0x91, 0x43, 0xE9, 0x9D, 0x96, 0x43, + // Bytes 1500 - 153f + 0xE9, 0x9D, 0x9E, 0x43, 0xE9, 0x9D, 0xA2, 0x43, + 0xE9, 0x9D, 0xA9, 0x43, 0xE9, 0x9F, 0x8B, 0x43, + 0xE9, 0x9F, 0x9B, 0x43, 0xE9, 0x9F, 0xA0, 0x43, + 0xE9, 0x9F, 0xAD, 0x43, 0xE9, 0x9F, 0xB3, 0x43, + 0xE9, 0x9F, 0xBF, 0x43, 0xE9, 0xA0, 0x81, 0x43, + 0xE9, 0xA0, 0x85, 0x43, 0xE9, 0xA0, 0x8B, 0x43, + 0xE9, 0xA0, 0x98, 0x43, 0xE9, 0xA0, 0xA9, 0x43, + 0xE9, 0xA0, 0xBB, 0x43, 0xE9, 0xA1, 0x9E, 0x43, + // Bytes 1540 - 157f + 0xE9, 0xA2, 0xA8, 0x43, 0xE9, 0xA3, 0x9B, 0x43, + 0xE9, 0xA3, 0x9F, 0x43, 0xE9, 0xA3, 0xA2, 0x43, + 0xE9, 0xA3, 0xAF, 0x43, 0xE9, 0xA3, 0xBC, 0x43, + 0xE9, 0xA4, 0xA8, 0x43, 0xE9, 0xA4, 0xA9, 0x43, + 0xE9, 0xA6, 0x96, 0x43, 0xE9, 0xA6, 0x99, 0x43, + 0xE9, 0xA6, 0xA7, 0x43, 0xE9, 0xA6, 0xAC, 0x43, + 0xE9, 0xA7, 0x82, 0x43, 0xE9, 0xA7, 0xB1, 0x43, + 0xE9, 0xA7, 0xBE, 0x43, 0xE9, 0xA9, 0xAA, 0x43, + // Bytes 1580 - 15bf + 0xE9, 0xAA, 0xA8, 0x43, 0xE9, 0xAB, 0x98, 0x43, + 0xE9, 0xAB, 0x9F, 0x43, 0xE9, 0xAC, 0x92, 0x43, + 0xE9, 0xAC, 0xA5, 0x43, 0xE9, 0xAC, 0xAF, 0x43, + 0xE9, 0xAC, 0xB2, 0x43, 0xE9, 0xAC, 0xBC, 0x43, + 0xE9, 0xAD, 0x9A, 0x43, 0xE9, 0xAD, 0xAF, 0x43, + 0xE9, 0xB1, 0x80, 0x43, 0xE9, 0xB1, 0x97, 0x43, + 0xE9, 0xB3, 0xA5, 0x43, 0xE9, 0xB3, 0xBD, 0x43, + 0xE9, 0xB5, 0xA7, 0x43, 0xE9, 0xB6, 0xB4, 0x43, + // Bytes 15c0 - 15ff + 0xE9, 0xB7, 0xBA, 0x43, 0xE9, 0xB8, 0x9E, 0x43, + 0xE9, 0xB9, 0xB5, 0x43, 0xE9, 0xB9, 0xBF, 0x43, + 0xE9, 0xBA, 0x97, 0x43, 0xE9, 0xBA, 0x9F, 0x43, + 0xE9, 0xBA, 0xA5, 0x43, 0xE9, 0xBA, 0xBB, 0x43, + 0xE9, 0xBB, 0x83, 0x43, 0xE9, 0xBB, 0x8D, 0x43, + 0xE9, 0xBB, 0x8E, 0x43, 0xE9, 0xBB, 0x91, 0x43, + 0xE9, 0xBB, 0xB9, 0x43, 0xE9, 0xBB, 0xBD, 0x43, + 0xE9, 0xBB, 0xBE, 0x43, 0xE9, 0xBC, 0x85, 0x43, + // Bytes 1600 - 163f + 0xE9, 0xBC, 0x8E, 0x43, 0xE9, 0xBC, 0x8F, 0x43, + 0xE9, 0xBC, 0x93, 0x43, 0xE9, 0xBC, 0x96, 0x43, + 0xE9, 0xBC, 0xA0, 0x43, 0xE9, 0xBC, 0xBB, 0x43, + 0xE9, 0xBD, 0x83, 0x43, 0xE9, 0xBD, 0x8A, 0x43, + 0xE9, 0xBD, 0x92, 0x43, 0xE9, 0xBE, 0x8D, 0x43, + 0xE9, 0xBE, 0x8E, 0x43, 0xE9, 0xBE, 0x9C, 0x43, + 0xE9, 0xBE, 0x9F, 0x43, 0xE9, 0xBE, 0xA0, 0x43, + 0xEA, 0x9C, 0xA7, 0x43, 0xEA, 0x9D, 0xAF, 0x43, + // Bytes 1640 - 167f + 0xEA, 0xAC, 0xB7, 0x43, 0xEA, 0xAD, 0x92, 0x44, + 0xF0, 0xA0, 0x84, 0xA2, 0x44, 0xF0, 0xA0, 0x94, + 0x9C, 0x44, 0xF0, 0xA0, 0x94, 0xA5, 0x44, 0xF0, + 0xA0, 0x95, 0x8B, 0x44, 0xF0, 0xA0, 0x98, 0xBA, + 0x44, 0xF0, 0xA0, 0xA0, 0x84, 0x44, 0xF0, 0xA0, + 0xA3, 0x9E, 0x44, 0xF0, 0xA0, 0xA8, 0xAC, 0x44, + 0xF0, 0xA0, 0xAD, 0xA3, 0x44, 0xF0, 0xA1, 0x93, + 0xA4, 0x44, 0xF0, 0xA1, 0x9A, 0xA8, 0x44, 0xF0, + // Bytes 1680 - 16bf + 0xA1, 0x9B, 0xAA, 0x44, 0xF0, 0xA1, 0xA7, 0x88, + 0x44, 0xF0, 0xA1, 0xAC, 0x98, 0x44, 0xF0, 0xA1, + 0xB4, 0x8B, 0x44, 0xF0, 0xA1, 0xB7, 0xA4, 0x44, + 0xF0, 0xA1, 0xB7, 0xA6, 0x44, 0xF0, 0xA2, 0x86, + 0x83, 0x44, 0xF0, 0xA2, 0x86, 0x9F, 0x44, 0xF0, + 0xA2, 0x8C, 0xB1, 0x44, 0xF0, 0xA2, 0x9B, 0x94, + 0x44, 0xF0, 0xA2, 0xA1, 0x84, 0x44, 0xF0, 0xA2, + 0xA1, 0x8A, 0x44, 0xF0, 0xA2, 0xAC, 0x8C, 0x44, + // Bytes 16c0 - 16ff + 0xF0, 0xA2, 0xAF, 0xB1, 0x44, 0xF0, 0xA3, 0x80, + 0x8A, 0x44, 0xF0, 0xA3, 0x8A, 0xB8, 0x44, 0xF0, + 0xA3, 0x8D, 0x9F, 0x44, 0xF0, 0xA3, 0x8E, 0x93, + 0x44, 0xF0, 0xA3, 0x8E, 0x9C, 0x44, 0xF0, 0xA3, + 0x8F, 0x83, 0x44, 0xF0, 0xA3, 0x8F, 0x95, 0x44, + 0xF0, 0xA3, 0x91, 0xAD, 0x44, 0xF0, 0xA3, 0x9A, + 0xA3, 0x44, 0xF0, 0xA3, 0xA2, 0xA7, 0x44, 0xF0, + 0xA3, 0xAA, 0x8D, 0x44, 0xF0, 0xA3, 0xAB, 0xBA, + // Bytes 1700 - 173f + 0x44, 0xF0, 0xA3, 0xB2, 0xBC, 0x44, 0xF0, 0xA3, + 0xB4, 0x9E, 0x44, 0xF0, 0xA3, 0xBB, 0x91, 0x44, + 0xF0, 0xA3, 0xBD, 0x9E, 0x44, 0xF0, 0xA3, 0xBE, + 0x8E, 0x44, 0xF0, 0xA4, 0x89, 0xA3, 0x44, 0xF0, + 0xA4, 0x8B, 0xAE, 0x44, 0xF0, 0xA4, 0x8E, 0xAB, + 0x44, 0xF0, 0xA4, 0x98, 0x88, 0x44, 0xF0, 0xA4, + 0x9C, 0xB5, 0x44, 0xF0, 0xA4, 0xA0, 0x94, 0x44, + 0xF0, 0xA4, 0xB0, 0xB6, 0x44, 0xF0, 0xA4, 0xB2, + // Bytes 1740 - 177f + 0x92, 0x44, 0xF0, 0xA4, 0xBE, 0xA1, 0x44, 0xF0, + 0xA4, 0xBE, 0xB8, 0x44, 0xF0, 0xA5, 0x81, 0x84, + 0x44, 0xF0, 0xA5, 0x83, 0xB2, 0x44, 0xF0, 0xA5, + 0x83, 0xB3, 0x44, 0xF0, 0xA5, 0x84, 0x99, 0x44, + 0xF0, 0xA5, 0x84, 0xB3, 0x44, 0xF0, 0xA5, 0x89, + 0x89, 0x44, 0xF0, 0xA5, 0x90, 0x9D, 0x44, 0xF0, + 0xA5, 0x98, 0xA6, 0x44, 0xF0, 0xA5, 0x9A, 0x9A, + 0x44, 0xF0, 0xA5, 0x9B, 0x85, 0x44, 0xF0, 0xA5, + // Bytes 1780 - 17bf + 0xA5, 0xBC, 0x44, 0xF0, 0xA5, 0xAA, 0xA7, 0x44, + 0xF0, 0xA5, 0xAE, 0xAB, 0x44, 0xF0, 0xA5, 0xB2, + 0x80, 0x44, 0xF0, 0xA5, 0xB3, 0x90, 0x44, 0xF0, + 0xA5, 0xBE, 0x86, 0x44, 0xF0, 0xA6, 0x87, 0x9A, + 0x44, 0xF0, 0xA6, 0x88, 0xA8, 0x44, 0xF0, 0xA6, + 0x89, 0x87, 0x44, 0xF0, 0xA6, 0x8B, 0x99, 0x44, + 0xF0, 0xA6, 0x8C, 0xBE, 0x44, 0xF0, 0xA6, 0x93, + 0x9A, 0x44, 0xF0, 0xA6, 0x94, 0xA3, 0x44, 0xF0, + // Bytes 17c0 - 17ff + 0xA6, 0x96, 0xA8, 0x44, 0xF0, 0xA6, 0x9E, 0xA7, + 0x44, 0xF0, 0xA6, 0x9E, 0xB5, 0x44, 0xF0, 0xA6, + 0xAC, 0xBC, 0x44, 0xF0, 0xA6, 0xB0, 0xB6, 0x44, + 0xF0, 0xA6, 0xB3, 0x95, 0x44, 0xF0, 0xA6, 0xB5, + 0xAB, 0x44, 0xF0, 0xA6, 0xBC, 0xAC, 0x44, 0xF0, + 0xA6, 0xBE, 0xB1, 0x44, 0xF0, 0xA7, 0x83, 0x92, + 0x44, 0xF0, 0xA7, 0x8F, 0x8A, 0x44, 0xF0, 0xA7, + 0x99, 0xA7, 0x44, 0xF0, 0xA7, 0xA2, 0xAE, 0x44, + // Bytes 1800 - 183f + 0xF0, 0xA7, 0xA5, 0xA6, 0x44, 0xF0, 0xA7, 0xB2, + 0xA8, 0x44, 0xF0, 0xA7, 0xBB, 0x93, 0x44, 0xF0, + 0xA7, 0xBC, 0xAF, 0x44, 0xF0, 0xA8, 0x97, 0x92, + 0x44, 0xF0, 0xA8, 0x97, 0xAD, 0x44, 0xF0, 0xA8, + 0x9C, 0xAE, 0x44, 0xF0, 0xA8, 0xAF, 0xBA, 0x44, + 0xF0, 0xA8, 0xB5, 0xB7, 0x44, 0xF0, 0xA9, 0x85, + 0x85, 0x44, 0xF0, 0xA9, 0x87, 0x9F, 0x44, 0xF0, + 0xA9, 0x88, 0x9A, 0x44, 0xF0, 0xA9, 0x90, 0x8A, + // Bytes 1840 - 187f + 0x44, 0xF0, 0xA9, 0x92, 0x96, 0x44, 0xF0, 0xA9, + 0x96, 0xB6, 0x44, 0xF0, 0xA9, 0xAC, 0xB0, 0x44, + 0xF0, 0xAA, 0x83, 0x8E, 0x44, 0xF0, 0xAA, 0x84, + 0x85, 0x44, 0xF0, 0xAA, 0x88, 0x8E, 0x44, 0xF0, + 0xAA, 0x8A, 0x91, 0x44, 0xF0, 0xAA, 0x8E, 0x92, + 0x44, 0xF0, 0xAA, 0x98, 0x80, 0x42, 0x21, 0x21, + 0x42, 0x21, 0x3F, 0x42, 0x2E, 0x2E, 0x42, 0x30, + 0x2C, 0x42, 0x30, 0x2E, 0x42, 0x31, 0x2C, 0x42, + // Bytes 1880 - 18bf + 0x31, 0x2E, 0x42, 0x31, 0x30, 0x42, 0x31, 0x31, + 0x42, 0x31, 0x32, 0x42, 0x31, 0x33, 0x42, 0x31, + 0x34, 0x42, 0x31, 0x35, 0x42, 0x31, 0x36, 0x42, + 0x31, 0x37, 0x42, 0x31, 0x38, 0x42, 0x31, 0x39, + 0x42, 0x32, 0x2C, 0x42, 0x32, 0x2E, 0x42, 0x32, + 0x30, 0x42, 0x32, 0x31, 0x42, 0x32, 0x32, 0x42, + 0x32, 0x33, 0x42, 0x32, 0x34, 0x42, 0x32, 0x35, + 0x42, 0x32, 0x36, 0x42, 0x32, 0x37, 0x42, 0x32, + // Bytes 18c0 - 18ff + 0x38, 0x42, 0x32, 0x39, 0x42, 0x33, 0x2C, 0x42, + 0x33, 0x2E, 0x42, 0x33, 0x30, 0x42, 0x33, 0x31, + 0x42, 0x33, 0x32, 0x42, 0x33, 0x33, 0x42, 0x33, + 0x34, 0x42, 0x33, 0x35, 0x42, 0x33, 0x36, 0x42, + 0x33, 0x37, 0x42, 0x33, 0x38, 0x42, 0x33, 0x39, + 0x42, 0x34, 0x2C, 0x42, 0x34, 0x2E, 0x42, 0x34, + 0x30, 0x42, 0x34, 0x31, 0x42, 0x34, 0x32, 0x42, + 0x34, 0x33, 0x42, 0x34, 0x34, 0x42, 0x34, 0x35, + // Bytes 1900 - 193f + 0x42, 0x34, 0x36, 0x42, 0x34, 0x37, 0x42, 0x34, + 0x38, 0x42, 0x34, 0x39, 0x42, 0x35, 0x2C, 0x42, + 0x35, 0x2E, 0x42, 0x35, 0x30, 0x42, 0x36, 0x2C, + 0x42, 0x36, 0x2E, 0x42, 0x37, 0x2C, 0x42, 0x37, + 0x2E, 0x42, 0x38, 0x2C, 0x42, 0x38, 0x2E, 0x42, + 0x39, 0x2C, 0x42, 0x39, 0x2E, 0x42, 0x3D, 0x3D, + 0x42, 0x3F, 0x21, 0x42, 0x3F, 0x3F, 0x42, 0x41, + 0x55, 0x42, 0x42, 0x71, 0x42, 0x43, 0x44, 0x42, + // Bytes 1940 - 197f + 0x44, 0x4A, 0x42, 0x44, 0x5A, 0x42, 0x44, 0x7A, + 0x42, 0x47, 0x42, 0x42, 0x47, 0x79, 0x42, 0x48, + 0x50, 0x42, 0x48, 0x56, 0x42, 0x48, 0x67, 0x42, + 0x48, 0x7A, 0x42, 0x49, 0x49, 0x42, 0x49, 0x4A, + 0x42, 0x49, 0x55, 0x42, 0x49, 0x56, 0x42, 0x49, + 0x58, 0x42, 0x4B, 0x42, 0x42, 0x4B, 0x4B, 0x42, + 0x4B, 0x4D, 0x42, 0x4C, 0x4A, 0x42, 0x4C, 0x6A, + 0x42, 0x4D, 0x42, 0x42, 0x4D, 0x43, 0x42, 0x4D, + // Bytes 1980 - 19bf + 0x44, 0x42, 0x4D, 0x52, 0x42, 0x4D, 0x56, 0x42, + 0x4D, 0x57, 0x42, 0x4E, 0x4A, 0x42, 0x4E, 0x6A, + 0x42, 0x4E, 0x6F, 0x42, 0x50, 0x48, 0x42, 0x50, + 0x52, 0x42, 0x50, 0x61, 0x42, 0x52, 0x73, 0x42, + 0x53, 0x44, 0x42, 0x53, 0x4D, 0x42, 0x53, 0x53, + 0x42, 0x53, 0x76, 0x42, 0x54, 0x4D, 0x42, 0x56, + 0x49, 0x42, 0x57, 0x43, 0x42, 0x57, 0x5A, 0x42, + 0x57, 0x62, 0x42, 0x58, 0x49, 0x42, 0x63, 0x63, + // Bytes 19c0 - 19ff + 0x42, 0x63, 0x64, 0x42, 0x63, 0x6D, 0x42, 0x64, + 0x42, 0x42, 0x64, 0x61, 0x42, 0x64, 0x6C, 0x42, + 0x64, 0x6D, 0x42, 0x64, 0x7A, 0x42, 0x65, 0x56, + 0x42, 0x66, 0x66, 0x42, 0x66, 0x69, 0x42, 0x66, + 0x6C, 0x42, 0x66, 0x6D, 0x42, 0x68, 0x61, 0x42, + 0x69, 0x69, 0x42, 0x69, 0x6A, 0x42, 0x69, 0x6E, + 0x42, 0x69, 0x76, 0x42, 0x69, 0x78, 0x42, 0x6B, + 0x41, 0x42, 0x6B, 0x56, 0x42, 0x6B, 0x57, 0x42, + // Bytes 1a00 - 1a3f + 0x6B, 0x67, 0x42, 0x6B, 0x6C, 0x42, 0x6B, 0x6D, + 0x42, 0x6B, 0x74, 0x42, 0x6C, 0x6A, 0x42, 0x6C, + 0x6D, 0x42, 0x6C, 0x6E, 0x42, 0x6C, 0x78, 0x42, + 0x6D, 0x32, 0x42, 0x6D, 0x33, 0x42, 0x6D, 0x41, + 0x42, 0x6D, 0x56, 0x42, 0x6D, 0x57, 0x42, 0x6D, + 0x62, 0x42, 0x6D, 0x67, 0x42, 0x6D, 0x6C, 0x42, + 0x6D, 0x6D, 0x42, 0x6D, 0x73, 0x42, 0x6E, 0x41, + 0x42, 0x6E, 0x46, 0x42, 0x6E, 0x56, 0x42, 0x6E, + // Bytes 1a40 - 1a7f + 0x57, 0x42, 0x6E, 0x6A, 0x42, 0x6E, 0x6D, 0x42, + 0x6E, 0x73, 0x42, 0x6F, 0x56, 0x42, 0x70, 0x41, + 0x42, 0x70, 0x46, 0x42, 0x70, 0x56, 0x42, 0x70, + 0x57, 0x42, 0x70, 0x63, 0x42, 0x70, 0x73, 0x42, + 0x73, 0x72, 0x42, 0x73, 0x74, 0x42, 0x76, 0x69, + 0x42, 0x78, 0x69, 0x43, 0x28, 0x31, 0x29, 0x43, + 0x28, 0x32, 0x29, 0x43, 0x28, 0x33, 0x29, 0x43, + 0x28, 0x34, 0x29, 0x43, 0x28, 0x35, 0x29, 0x43, + // Bytes 1a80 - 1abf + 0x28, 0x36, 0x29, 0x43, 0x28, 0x37, 0x29, 0x43, + 0x28, 0x38, 0x29, 0x43, 0x28, 0x39, 0x29, 0x43, + 0x28, 0x41, 0x29, 0x43, 0x28, 0x42, 0x29, 0x43, + 0x28, 0x43, 0x29, 0x43, 0x28, 0x44, 0x29, 0x43, + 0x28, 0x45, 0x29, 0x43, 0x28, 0x46, 0x29, 0x43, + 0x28, 0x47, 0x29, 0x43, 0x28, 0x48, 0x29, 0x43, + 0x28, 0x49, 0x29, 0x43, 0x28, 0x4A, 0x29, 0x43, + 0x28, 0x4B, 0x29, 0x43, 0x28, 0x4C, 0x29, 0x43, + // Bytes 1ac0 - 1aff + 0x28, 0x4D, 0x29, 0x43, 0x28, 0x4E, 0x29, 0x43, + 0x28, 0x4F, 0x29, 0x43, 0x28, 0x50, 0x29, 0x43, + 0x28, 0x51, 0x29, 0x43, 0x28, 0x52, 0x29, 0x43, + 0x28, 0x53, 0x29, 0x43, 0x28, 0x54, 0x29, 0x43, + 0x28, 0x55, 0x29, 0x43, 0x28, 0x56, 0x29, 0x43, + 0x28, 0x57, 0x29, 0x43, 0x28, 0x58, 0x29, 0x43, + 0x28, 0x59, 0x29, 0x43, 0x28, 0x5A, 0x29, 0x43, + 0x28, 0x61, 0x29, 0x43, 0x28, 0x62, 0x29, 0x43, + // Bytes 1b00 - 1b3f + 0x28, 0x63, 0x29, 0x43, 0x28, 0x64, 0x29, 0x43, + 0x28, 0x65, 0x29, 0x43, 0x28, 0x66, 0x29, 0x43, + 0x28, 0x67, 0x29, 0x43, 0x28, 0x68, 0x29, 0x43, + 0x28, 0x69, 0x29, 0x43, 0x28, 0x6A, 0x29, 0x43, + 0x28, 0x6B, 0x29, 0x43, 0x28, 0x6C, 0x29, 0x43, + 0x28, 0x6D, 0x29, 0x43, 0x28, 0x6E, 0x29, 0x43, + 0x28, 0x6F, 0x29, 0x43, 0x28, 0x70, 0x29, 0x43, + 0x28, 0x71, 0x29, 0x43, 0x28, 0x72, 0x29, 0x43, + // Bytes 1b40 - 1b7f + 0x28, 0x73, 0x29, 0x43, 0x28, 0x74, 0x29, 0x43, + 0x28, 0x75, 0x29, 0x43, 0x28, 0x76, 0x29, 0x43, + 0x28, 0x77, 0x29, 0x43, 0x28, 0x78, 0x29, 0x43, + 0x28, 0x79, 0x29, 0x43, 0x28, 0x7A, 0x29, 0x43, + 0x2E, 0x2E, 0x2E, 0x43, 0x31, 0x30, 0x2E, 0x43, + 0x31, 0x31, 0x2E, 0x43, 0x31, 0x32, 0x2E, 0x43, + 0x31, 0x33, 0x2E, 0x43, 0x31, 0x34, 0x2E, 0x43, + 0x31, 0x35, 0x2E, 0x43, 0x31, 0x36, 0x2E, 0x43, + // Bytes 1b80 - 1bbf + 0x31, 0x37, 0x2E, 0x43, 0x31, 0x38, 0x2E, 0x43, + 0x31, 0x39, 0x2E, 0x43, 0x32, 0x30, 0x2E, 0x43, + 0x3A, 0x3A, 0x3D, 0x43, 0x3D, 0x3D, 0x3D, 0x43, + 0x43, 0x6F, 0x2E, 0x43, 0x46, 0x41, 0x58, 0x43, + 0x47, 0x48, 0x7A, 0x43, 0x47, 0x50, 0x61, 0x43, + 0x49, 0x49, 0x49, 0x43, 0x4C, 0x54, 0x44, 0x43, + 0x4C, 0xC2, 0xB7, 0x43, 0x4D, 0x48, 0x7A, 0x43, + 0x4D, 0x50, 0x61, 0x43, 0x4D, 0xCE, 0xA9, 0x43, + // Bytes 1bc0 - 1bff + 0x50, 0x50, 0x4D, 0x43, 0x50, 0x50, 0x56, 0x43, + 0x50, 0x54, 0x45, 0x43, 0x54, 0x45, 0x4C, 0x43, + 0x54, 0x48, 0x7A, 0x43, 0x56, 0x49, 0x49, 0x43, + 0x58, 0x49, 0x49, 0x43, 0x61, 0x2F, 0x63, 0x43, + 0x61, 0x2F, 0x73, 0x43, 0x61, 0xCA, 0xBE, 0x43, + 0x62, 0x61, 0x72, 0x43, 0x63, 0x2F, 0x6F, 0x43, + 0x63, 0x2F, 0x75, 0x43, 0x63, 0x61, 0x6C, 0x43, + 0x63, 0x6D, 0x32, 0x43, 0x63, 0x6D, 0x33, 0x43, + // Bytes 1c00 - 1c3f + 0x64, 0x6D, 0x32, 0x43, 0x64, 0x6D, 0x33, 0x43, + 0x65, 0x72, 0x67, 0x43, 0x66, 0x66, 0x69, 0x43, + 0x66, 0x66, 0x6C, 0x43, 0x67, 0x61, 0x6C, 0x43, + 0x68, 0x50, 0x61, 0x43, 0x69, 0x69, 0x69, 0x43, + 0x6B, 0x48, 0x7A, 0x43, 0x6B, 0x50, 0x61, 0x43, + 0x6B, 0x6D, 0x32, 0x43, 0x6B, 0x6D, 0x33, 0x43, + 0x6B, 0xCE, 0xA9, 0x43, 0x6C, 0x6F, 0x67, 0x43, + 0x6C, 0xC2, 0xB7, 0x43, 0x6D, 0x69, 0x6C, 0x43, + // Bytes 1c40 - 1c7f + 0x6D, 0x6D, 0x32, 0x43, 0x6D, 0x6D, 0x33, 0x43, + 0x6D, 0x6F, 0x6C, 0x43, 0x72, 0x61, 0x64, 0x43, + 0x76, 0x69, 0x69, 0x43, 0x78, 0x69, 0x69, 0x43, + 0xC2, 0xB0, 0x43, 0x43, 0xC2, 0xB0, 0x46, 0x43, + 0xCA, 0xBC, 0x6E, 0x43, 0xCE, 0xBC, 0x41, 0x43, + 0xCE, 0xBC, 0x46, 0x43, 0xCE, 0xBC, 0x56, 0x43, + 0xCE, 0xBC, 0x57, 0x43, 0xCE, 0xBC, 0x67, 0x43, + 0xCE, 0xBC, 0x6C, 0x43, 0xCE, 0xBC, 0x6D, 0x43, + // Bytes 1c80 - 1cbf + 0xCE, 0xBC, 0x73, 0x44, 0x28, 0x31, 0x30, 0x29, + 0x44, 0x28, 0x31, 0x31, 0x29, 0x44, 0x28, 0x31, + 0x32, 0x29, 0x44, 0x28, 0x31, 0x33, 0x29, 0x44, + 0x28, 0x31, 0x34, 0x29, 0x44, 0x28, 0x31, 0x35, + 0x29, 0x44, 0x28, 0x31, 0x36, 0x29, 0x44, 0x28, + 0x31, 0x37, 0x29, 0x44, 0x28, 0x31, 0x38, 0x29, + 0x44, 0x28, 0x31, 0x39, 0x29, 0x44, 0x28, 0x32, + 0x30, 0x29, 0x44, 0x30, 0xE7, 0x82, 0xB9, 0x44, + // Bytes 1cc0 - 1cff + 0x31, 0xE2, 0x81, 0x84, 0x44, 0x31, 0xE6, 0x97, + 0xA5, 0x44, 0x31, 0xE6, 0x9C, 0x88, 0x44, 0x31, + 0xE7, 0x82, 0xB9, 0x44, 0x32, 0xE6, 0x97, 0xA5, + 0x44, 0x32, 0xE6, 0x9C, 0x88, 0x44, 0x32, 0xE7, + 0x82, 0xB9, 0x44, 0x33, 0xE6, 0x97, 0xA5, 0x44, + 0x33, 0xE6, 0x9C, 0x88, 0x44, 0x33, 0xE7, 0x82, + 0xB9, 0x44, 0x34, 0xE6, 0x97, 0xA5, 0x44, 0x34, + 0xE6, 0x9C, 0x88, 0x44, 0x34, 0xE7, 0x82, 0xB9, + // Bytes 1d00 - 1d3f + 0x44, 0x35, 0xE6, 0x97, 0xA5, 0x44, 0x35, 0xE6, + 0x9C, 0x88, 0x44, 0x35, 0xE7, 0x82, 0xB9, 0x44, + 0x36, 0xE6, 0x97, 0xA5, 0x44, 0x36, 0xE6, 0x9C, + 0x88, 0x44, 0x36, 0xE7, 0x82, 0xB9, 0x44, 0x37, + 0xE6, 0x97, 0xA5, 0x44, 0x37, 0xE6, 0x9C, 0x88, + 0x44, 0x37, 0xE7, 0x82, 0xB9, 0x44, 0x38, 0xE6, + 0x97, 0xA5, 0x44, 0x38, 0xE6, 0x9C, 0x88, 0x44, + 0x38, 0xE7, 0x82, 0xB9, 0x44, 0x39, 0xE6, 0x97, + // Bytes 1d40 - 1d7f + 0xA5, 0x44, 0x39, 0xE6, 0x9C, 0x88, 0x44, 0x39, + 0xE7, 0x82, 0xB9, 0x44, 0x56, 0x49, 0x49, 0x49, + 0x44, 0x61, 0x2E, 0x6D, 0x2E, 0x44, 0x6B, 0x63, + 0x61, 0x6C, 0x44, 0x70, 0x2E, 0x6D, 0x2E, 0x44, + 0x76, 0x69, 0x69, 0x69, 0x44, 0xD5, 0xA5, 0xD6, + 0x82, 0x44, 0xD5, 0xB4, 0xD5, 0xA5, 0x44, 0xD5, + 0xB4, 0xD5, 0xAB, 0x44, 0xD5, 0xB4, 0xD5, 0xAD, + 0x44, 0xD5, 0xB4, 0xD5, 0xB6, 0x44, 0xD5, 0xBE, + // Bytes 1d80 - 1dbf + 0xD5, 0xB6, 0x44, 0xD7, 0x90, 0xD7, 0x9C, 0x44, + 0xD8, 0xA7, 0xD9, 0xB4, 0x44, 0xD8, 0xA8, 0xD8, + 0xAC, 0x44, 0xD8, 0xA8, 0xD8, 0xAD, 0x44, 0xD8, + 0xA8, 0xD8, 0xAE, 0x44, 0xD8, 0xA8, 0xD8, 0xB1, + 0x44, 0xD8, 0xA8, 0xD8, 0xB2, 0x44, 0xD8, 0xA8, + 0xD9, 0x85, 0x44, 0xD8, 0xA8, 0xD9, 0x86, 0x44, + 0xD8, 0xA8, 0xD9, 0x87, 0x44, 0xD8, 0xA8, 0xD9, + 0x89, 0x44, 0xD8, 0xA8, 0xD9, 0x8A, 0x44, 0xD8, + // Bytes 1dc0 - 1dff + 0xAA, 0xD8, 0xAC, 0x44, 0xD8, 0xAA, 0xD8, 0xAD, + 0x44, 0xD8, 0xAA, 0xD8, 0xAE, 0x44, 0xD8, 0xAA, + 0xD8, 0xB1, 0x44, 0xD8, 0xAA, 0xD8, 0xB2, 0x44, + 0xD8, 0xAA, 0xD9, 0x85, 0x44, 0xD8, 0xAA, 0xD9, + 0x86, 0x44, 0xD8, 0xAA, 0xD9, 0x87, 0x44, 0xD8, + 0xAA, 0xD9, 0x89, 0x44, 0xD8, 0xAA, 0xD9, 0x8A, + 0x44, 0xD8, 0xAB, 0xD8, 0xAC, 0x44, 0xD8, 0xAB, + 0xD8, 0xB1, 0x44, 0xD8, 0xAB, 0xD8, 0xB2, 0x44, + // Bytes 1e00 - 1e3f + 0xD8, 0xAB, 0xD9, 0x85, 0x44, 0xD8, 0xAB, 0xD9, + 0x86, 0x44, 0xD8, 0xAB, 0xD9, 0x87, 0x44, 0xD8, + 0xAB, 0xD9, 0x89, 0x44, 0xD8, 0xAB, 0xD9, 0x8A, + 0x44, 0xD8, 0xAC, 0xD8, 0xAD, 0x44, 0xD8, 0xAC, + 0xD9, 0x85, 0x44, 0xD8, 0xAC, 0xD9, 0x89, 0x44, + 0xD8, 0xAC, 0xD9, 0x8A, 0x44, 0xD8, 0xAD, 0xD8, + 0xAC, 0x44, 0xD8, 0xAD, 0xD9, 0x85, 0x44, 0xD8, + 0xAD, 0xD9, 0x89, 0x44, 0xD8, 0xAD, 0xD9, 0x8A, + // Bytes 1e40 - 1e7f + 0x44, 0xD8, 0xAE, 0xD8, 0xAC, 0x44, 0xD8, 0xAE, + 0xD8, 0xAD, 0x44, 0xD8, 0xAE, 0xD9, 0x85, 0x44, + 0xD8, 0xAE, 0xD9, 0x89, 0x44, 0xD8, 0xAE, 0xD9, + 0x8A, 0x44, 0xD8, 0xB3, 0xD8, 0xAC, 0x44, 0xD8, + 0xB3, 0xD8, 0xAD, 0x44, 0xD8, 0xB3, 0xD8, 0xAE, + 0x44, 0xD8, 0xB3, 0xD8, 0xB1, 0x44, 0xD8, 0xB3, + 0xD9, 0x85, 0x44, 0xD8, 0xB3, 0xD9, 0x87, 0x44, + 0xD8, 0xB3, 0xD9, 0x89, 0x44, 0xD8, 0xB3, 0xD9, + // Bytes 1e80 - 1ebf + 0x8A, 0x44, 0xD8, 0xB4, 0xD8, 0xAC, 0x44, 0xD8, + 0xB4, 0xD8, 0xAD, 0x44, 0xD8, 0xB4, 0xD8, 0xAE, + 0x44, 0xD8, 0xB4, 0xD8, 0xB1, 0x44, 0xD8, 0xB4, + 0xD9, 0x85, 0x44, 0xD8, 0xB4, 0xD9, 0x87, 0x44, + 0xD8, 0xB4, 0xD9, 0x89, 0x44, 0xD8, 0xB4, 0xD9, + 0x8A, 0x44, 0xD8, 0xB5, 0xD8, 0xAD, 0x44, 0xD8, + 0xB5, 0xD8, 0xAE, 0x44, 0xD8, 0xB5, 0xD8, 0xB1, + 0x44, 0xD8, 0xB5, 0xD9, 0x85, 0x44, 0xD8, 0xB5, + // Bytes 1ec0 - 1eff + 0xD9, 0x89, 0x44, 0xD8, 0xB5, 0xD9, 0x8A, 0x44, + 0xD8, 0xB6, 0xD8, 0xAC, 0x44, 0xD8, 0xB6, 0xD8, + 0xAD, 0x44, 0xD8, 0xB6, 0xD8, 0xAE, 0x44, 0xD8, + 0xB6, 0xD8, 0xB1, 0x44, 0xD8, 0xB6, 0xD9, 0x85, + 0x44, 0xD8, 0xB6, 0xD9, 0x89, 0x44, 0xD8, 0xB6, + 0xD9, 0x8A, 0x44, 0xD8, 0xB7, 0xD8, 0xAD, 0x44, + 0xD8, 0xB7, 0xD9, 0x85, 0x44, 0xD8, 0xB7, 0xD9, + 0x89, 0x44, 0xD8, 0xB7, 0xD9, 0x8A, 0x44, 0xD8, + // Bytes 1f00 - 1f3f + 0xB8, 0xD9, 0x85, 0x44, 0xD8, 0xB9, 0xD8, 0xAC, + 0x44, 0xD8, 0xB9, 0xD9, 0x85, 0x44, 0xD8, 0xB9, + 0xD9, 0x89, 0x44, 0xD8, 0xB9, 0xD9, 0x8A, 0x44, + 0xD8, 0xBA, 0xD8, 0xAC, 0x44, 0xD8, 0xBA, 0xD9, + 0x85, 0x44, 0xD8, 0xBA, 0xD9, 0x89, 0x44, 0xD8, + 0xBA, 0xD9, 0x8A, 0x44, 0xD9, 0x81, 0xD8, 0xAC, + 0x44, 0xD9, 0x81, 0xD8, 0xAD, 0x44, 0xD9, 0x81, + 0xD8, 0xAE, 0x44, 0xD9, 0x81, 0xD9, 0x85, 0x44, + // Bytes 1f40 - 1f7f + 0xD9, 0x81, 0xD9, 0x89, 0x44, 0xD9, 0x81, 0xD9, + 0x8A, 0x44, 0xD9, 0x82, 0xD8, 0xAD, 0x44, 0xD9, + 0x82, 0xD9, 0x85, 0x44, 0xD9, 0x82, 0xD9, 0x89, + 0x44, 0xD9, 0x82, 0xD9, 0x8A, 0x44, 0xD9, 0x83, + 0xD8, 0xA7, 0x44, 0xD9, 0x83, 0xD8, 0xAC, 0x44, + 0xD9, 0x83, 0xD8, 0xAD, 0x44, 0xD9, 0x83, 0xD8, + 0xAE, 0x44, 0xD9, 0x83, 0xD9, 0x84, 0x44, 0xD9, + 0x83, 0xD9, 0x85, 0x44, 0xD9, 0x83, 0xD9, 0x89, + // Bytes 1f80 - 1fbf + 0x44, 0xD9, 0x83, 0xD9, 0x8A, 0x44, 0xD9, 0x84, + 0xD8, 0xA7, 0x44, 0xD9, 0x84, 0xD8, 0xAC, 0x44, + 0xD9, 0x84, 0xD8, 0xAD, 0x44, 0xD9, 0x84, 0xD8, + 0xAE, 0x44, 0xD9, 0x84, 0xD9, 0x85, 0x44, 0xD9, + 0x84, 0xD9, 0x87, 0x44, 0xD9, 0x84, 0xD9, 0x89, + 0x44, 0xD9, 0x84, 0xD9, 0x8A, 0x44, 0xD9, 0x85, + 0xD8, 0xA7, 0x44, 0xD9, 0x85, 0xD8, 0xAC, 0x44, + 0xD9, 0x85, 0xD8, 0xAD, 0x44, 0xD9, 0x85, 0xD8, + // Bytes 1fc0 - 1fff + 0xAE, 0x44, 0xD9, 0x85, 0xD9, 0x85, 0x44, 0xD9, + 0x85, 0xD9, 0x89, 0x44, 0xD9, 0x85, 0xD9, 0x8A, + 0x44, 0xD9, 0x86, 0xD8, 0xAC, 0x44, 0xD9, 0x86, + 0xD8, 0xAD, 0x44, 0xD9, 0x86, 0xD8, 0xAE, 0x44, + 0xD9, 0x86, 0xD8, 0xB1, 0x44, 0xD9, 0x86, 0xD8, + 0xB2, 0x44, 0xD9, 0x86, 0xD9, 0x85, 0x44, 0xD9, + 0x86, 0xD9, 0x86, 0x44, 0xD9, 0x86, 0xD9, 0x87, + 0x44, 0xD9, 0x86, 0xD9, 0x89, 0x44, 0xD9, 0x86, + // Bytes 2000 - 203f + 0xD9, 0x8A, 0x44, 0xD9, 0x87, 0xD8, 0xAC, 0x44, + 0xD9, 0x87, 0xD9, 0x85, 0x44, 0xD9, 0x87, 0xD9, + 0x89, 0x44, 0xD9, 0x87, 0xD9, 0x8A, 0x44, 0xD9, + 0x88, 0xD9, 0xB4, 0x44, 0xD9, 0x8A, 0xD8, 0xAC, + 0x44, 0xD9, 0x8A, 0xD8, 0xAD, 0x44, 0xD9, 0x8A, + 0xD8, 0xAE, 0x44, 0xD9, 0x8A, 0xD8, 0xB1, 0x44, + 0xD9, 0x8A, 0xD8, 0xB2, 0x44, 0xD9, 0x8A, 0xD9, + 0x85, 0x44, 0xD9, 0x8A, 0xD9, 0x86, 0x44, 0xD9, + // Bytes 2040 - 207f + 0x8A, 0xD9, 0x87, 0x44, 0xD9, 0x8A, 0xD9, 0x89, + 0x44, 0xD9, 0x8A, 0xD9, 0x8A, 0x44, 0xD9, 0x8A, + 0xD9, 0xB4, 0x44, 0xDB, 0x87, 0xD9, 0xB4, 0x45, + 0x28, 0xE1, 0x84, 0x80, 0x29, 0x45, 0x28, 0xE1, + 0x84, 0x82, 0x29, 0x45, 0x28, 0xE1, 0x84, 0x83, + 0x29, 0x45, 0x28, 0xE1, 0x84, 0x85, 0x29, 0x45, + 0x28, 0xE1, 0x84, 0x86, 0x29, 0x45, 0x28, 0xE1, + 0x84, 0x87, 0x29, 0x45, 0x28, 0xE1, 0x84, 0x89, + // Bytes 2080 - 20bf + 0x29, 0x45, 0x28, 0xE1, 0x84, 0x8B, 0x29, 0x45, + 0x28, 0xE1, 0x84, 0x8C, 0x29, 0x45, 0x28, 0xE1, + 0x84, 0x8E, 0x29, 0x45, 0x28, 0xE1, 0x84, 0x8F, + 0x29, 0x45, 0x28, 0xE1, 0x84, 0x90, 0x29, 0x45, + 0x28, 0xE1, 0x84, 0x91, 0x29, 0x45, 0x28, 0xE1, + 0x84, 0x92, 0x29, 0x45, 0x28, 0xE4, 0xB8, 0x80, + 0x29, 0x45, 0x28, 0xE4, 0xB8, 0x83, 0x29, 0x45, + 0x28, 0xE4, 0xB8, 0x89, 0x29, 0x45, 0x28, 0xE4, + // Bytes 20c0 - 20ff + 0xB9, 0x9D, 0x29, 0x45, 0x28, 0xE4, 0xBA, 0x8C, + 0x29, 0x45, 0x28, 0xE4, 0xBA, 0x94, 0x29, 0x45, + 0x28, 0xE4, 0xBB, 0xA3, 0x29, 0x45, 0x28, 0xE4, + 0xBC, 0x81, 0x29, 0x45, 0x28, 0xE4, 0xBC, 0x91, + 0x29, 0x45, 0x28, 0xE5, 0x85, 0xAB, 0x29, 0x45, + 0x28, 0xE5, 0x85, 0xAD, 0x29, 0x45, 0x28, 0xE5, + 0x8A, 0xB4, 0x29, 0x45, 0x28, 0xE5, 0x8D, 0x81, + 0x29, 0x45, 0x28, 0xE5, 0x8D, 0x94, 0x29, 0x45, + // Bytes 2100 - 213f + 0x28, 0xE5, 0x90, 0x8D, 0x29, 0x45, 0x28, 0xE5, + 0x91, 0xBC, 0x29, 0x45, 0x28, 0xE5, 0x9B, 0x9B, + 0x29, 0x45, 0x28, 0xE5, 0x9C, 0x9F, 0x29, 0x45, + 0x28, 0xE5, 0xAD, 0xA6, 0x29, 0x45, 0x28, 0xE6, + 0x97, 0xA5, 0x29, 0x45, 0x28, 0xE6, 0x9C, 0x88, + 0x29, 0x45, 0x28, 0xE6, 0x9C, 0x89, 0x29, 0x45, + 0x28, 0xE6, 0x9C, 0xA8, 0x29, 0x45, 0x28, 0xE6, + 0xA0, 0xAA, 0x29, 0x45, 0x28, 0xE6, 0xB0, 0xB4, + // Bytes 2140 - 217f + 0x29, 0x45, 0x28, 0xE7, 0x81, 0xAB, 0x29, 0x45, + 0x28, 0xE7, 0x89, 0xB9, 0x29, 0x45, 0x28, 0xE7, + 0x9B, 0xA3, 0x29, 0x45, 0x28, 0xE7, 0xA4, 0xBE, + 0x29, 0x45, 0x28, 0xE7, 0xA5, 0x9D, 0x29, 0x45, + 0x28, 0xE7, 0xA5, 0xAD, 0x29, 0x45, 0x28, 0xE8, + 0x87, 0xAA, 0x29, 0x45, 0x28, 0xE8, 0x87, 0xB3, + 0x29, 0x45, 0x28, 0xE8, 0xB2, 0xA1, 0x29, 0x45, + 0x28, 0xE8, 0xB3, 0x87, 0x29, 0x45, 0x28, 0xE9, + // Bytes 2180 - 21bf + 0x87, 0x91, 0x29, 0x45, 0x30, 0xE2, 0x81, 0x84, + 0x33, 0x45, 0x31, 0x30, 0xE6, 0x97, 0xA5, 0x45, + 0x31, 0x30, 0xE6, 0x9C, 0x88, 0x45, 0x31, 0x30, + 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x31, 0xE6, 0x97, + 0xA5, 0x45, 0x31, 0x31, 0xE6, 0x9C, 0x88, 0x45, + 0x31, 0x31, 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x32, + 0xE6, 0x97, 0xA5, 0x45, 0x31, 0x32, 0xE6, 0x9C, + 0x88, 0x45, 0x31, 0x32, 0xE7, 0x82, 0xB9, 0x45, + // Bytes 21c0 - 21ff + 0x31, 0x33, 0xE6, 0x97, 0xA5, 0x45, 0x31, 0x33, + 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x34, 0xE6, 0x97, + 0xA5, 0x45, 0x31, 0x34, 0xE7, 0x82, 0xB9, 0x45, + 0x31, 0x35, 0xE6, 0x97, 0xA5, 0x45, 0x31, 0x35, + 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x36, 0xE6, 0x97, + 0xA5, 0x45, 0x31, 0x36, 0xE7, 0x82, 0xB9, 0x45, + 0x31, 0x37, 0xE6, 0x97, 0xA5, 0x45, 0x31, 0x37, + 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x38, 0xE6, 0x97, + // Bytes 2200 - 223f + 0xA5, 0x45, 0x31, 0x38, 0xE7, 0x82, 0xB9, 0x45, + 0x31, 0x39, 0xE6, 0x97, 0xA5, 0x45, 0x31, 0x39, + 0xE7, 0x82, 0xB9, 0x45, 0x31, 0xE2, 0x81, 0x84, + 0x32, 0x45, 0x31, 0xE2, 0x81, 0x84, 0x33, 0x45, + 0x31, 0xE2, 0x81, 0x84, 0x34, 0x45, 0x31, 0xE2, + 0x81, 0x84, 0x35, 0x45, 0x31, 0xE2, 0x81, 0x84, + 0x36, 0x45, 0x31, 0xE2, 0x81, 0x84, 0x37, 0x45, + 0x31, 0xE2, 0x81, 0x84, 0x38, 0x45, 0x31, 0xE2, + // Bytes 2240 - 227f + 0x81, 0x84, 0x39, 0x45, 0x32, 0x30, 0xE6, 0x97, + 0xA5, 0x45, 0x32, 0x30, 0xE7, 0x82, 0xB9, 0x45, + 0x32, 0x31, 0xE6, 0x97, 0xA5, 0x45, 0x32, 0x31, + 0xE7, 0x82, 0xB9, 0x45, 0x32, 0x32, 0xE6, 0x97, + 0xA5, 0x45, 0x32, 0x32, 0xE7, 0x82, 0xB9, 0x45, + 0x32, 0x33, 0xE6, 0x97, 0xA5, 0x45, 0x32, 0x33, + 0xE7, 0x82, 0xB9, 0x45, 0x32, 0x34, 0xE6, 0x97, + 0xA5, 0x45, 0x32, 0x34, 0xE7, 0x82, 0xB9, 0x45, + // Bytes 2280 - 22bf + 0x32, 0x35, 0xE6, 0x97, 0xA5, 0x45, 0x32, 0x36, + 0xE6, 0x97, 0xA5, 0x45, 0x32, 0x37, 0xE6, 0x97, + 0xA5, 0x45, 0x32, 0x38, 0xE6, 0x97, 0xA5, 0x45, + 0x32, 0x39, 0xE6, 0x97, 0xA5, 0x45, 0x32, 0xE2, + 0x81, 0x84, 0x33, 0x45, 0x32, 0xE2, 0x81, 0x84, + 0x35, 0x45, 0x33, 0x30, 0xE6, 0x97, 0xA5, 0x45, + 0x33, 0x31, 0xE6, 0x97, 0xA5, 0x45, 0x33, 0xE2, + 0x81, 0x84, 0x34, 0x45, 0x33, 0xE2, 0x81, 0x84, + // Bytes 22c0 - 22ff + 0x35, 0x45, 0x33, 0xE2, 0x81, 0x84, 0x38, 0x45, + 0x34, 0xE2, 0x81, 0x84, 0x35, 0x45, 0x35, 0xE2, + 0x81, 0x84, 0x36, 0x45, 0x35, 0xE2, 0x81, 0x84, + 0x38, 0x45, 0x37, 0xE2, 0x81, 0x84, 0x38, 0x45, + 0x41, 0xE2, 0x88, 0x95, 0x6D, 0x45, 0x56, 0xE2, + 0x88, 0x95, 0x6D, 0x45, 0x6D, 0xE2, 0x88, 0x95, + 0x73, 0x46, 0x31, 0xE2, 0x81, 0x84, 0x31, 0x30, + 0x46, 0x43, 0xE2, 0x88, 0x95, 0x6B, 0x67, 0x46, + // Bytes 2300 - 233f + 0x6D, 0xE2, 0x88, 0x95, 0x73, 0x32, 0x46, 0xD8, + 0xA8, 0xD8, 0xAD, 0xD9, 0x8A, 0x46, 0xD8, 0xA8, + 0xD8, 0xAE, 0xD9, 0x8A, 0x46, 0xD8, 0xAA, 0xD8, + 0xAC, 0xD9, 0x85, 0x46, 0xD8, 0xAA, 0xD8, 0xAC, + 0xD9, 0x89, 0x46, 0xD8, 0xAA, 0xD8, 0xAC, 0xD9, + 0x8A, 0x46, 0xD8, 0xAA, 0xD8, 0xAD, 0xD8, 0xAC, + 0x46, 0xD8, 0xAA, 0xD8, 0xAD, 0xD9, 0x85, 0x46, + 0xD8, 0xAA, 0xD8, 0xAE, 0xD9, 0x85, 0x46, 0xD8, + // Bytes 2340 - 237f + 0xAA, 0xD8, 0xAE, 0xD9, 0x89, 0x46, 0xD8, 0xAA, + 0xD8, 0xAE, 0xD9, 0x8A, 0x46, 0xD8, 0xAA, 0xD9, + 0x85, 0xD8, 0xAC, 0x46, 0xD8, 0xAA, 0xD9, 0x85, + 0xD8, 0xAD, 0x46, 0xD8, 0xAA, 0xD9, 0x85, 0xD8, + 0xAE, 0x46, 0xD8, 0xAA, 0xD9, 0x85, 0xD9, 0x89, + 0x46, 0xD8, 0xAA, 0xD9, 0x85, 0xD9, 0x8A, 0x46, + 0xD8, 0xAC, 0xD8, 0xAD, 0xD9, 0x89, 0x46, 0xD8, + 0xAC, 0xD8, 0xAD, 0xD9, 0x8A, 0x46, 0xD8, 0xAC, + // Bytes 2380 - 23bf + 0xD9, 0x85, 0xD8, 0xAD, 0x46, 0xD8, 0xAC, 0xD9, + 0x85, 0xD9, 0x89, 0x46, 0xD8, 0xAC, 0xD9, 0x85, + 0xD9, 0x8A, 0x46, 0xD8, 0xAD, 0xD8, 0xAC, 0xD9, + 0x8A, 0x46, 0xD8, 0xAD, 0xD9, 0x85, 0xD9, 0x89, + 0x46, 0xD8, 0xAD, 0xD9, 0x85, 0xD9, 0x8A, 0x46, + 0xD8, 0xB3, 0xD8, 0xAC, 0xD8, 0xAD, 0x46, 0xD8, + 0xB3, 0xD8, 0xAC, 0xD9, 0x89, 0x46, 0xD8, 0xB3, + 0xD8, 0xAD, 0xD8, 0xAC, 0x46, 0xD8, 0xB3, 0xD8, + // Bytes 23c0 - 23ff + 0xAE, 0xD9, 0x89, 0x46, 0xD8, 0xB3, 0xD8, 0xAE, + 0xD9, 0x8A, 0x46, 0xD8, 0xB3, 0xD9, 0x85, 0xD8, + 0xAC, 0x46, 0xD8, 0xB3, 0xD9, 0x85, 0xD8, 0xAD, + 0x46, 0xD8, 0xB3, 0xD9, 0x85, 0xD9, 0x85, 0x46, + 0xD8, 0xB4, 0xD8, 0xAC, 0xD9, 0x8A, 0x46, 0xD8, + 0xB4, 0xD8, 0xAD, 0xD9, 0x85, 0x46, 0xD8, 0xB4, + 0xD8, 0xAD, 0xD9, 0x8A, 0x46, 0xD8, 0xB4, 0xD9, + 0x85, 0xD8, 0xAE, 0x46, 0xD8, 0xB4, 0xD9, 0x85, + // Bytes 2400 - 243f + 0xD9, 0x85, 0x46, 0xD8, 0xB5, 0xD8, 0xAD, 0xD8, + 0xAD, 0x46, 0xD8, 0xB5, 0xD8, 0xAD, 0xD9, 0x8A, + 0x46, 0xD8, 0xB5, 0xD9, 0x84, 0xD9, 0x89, 0x46, + 0xD8, 0xB5, 0xD9, 0x84, 0xDB, 0x92, 0x46, 0xD8, + 0xB5, 0xD9, 0x85, 0xD9, 0x85, 0x46, 0xD8, 0xB6, + 0xD8, 0xAD, 0xD9, 0x89, 0x46, 0xD8, 0xB6, 0xD8, + 0xAD, 0xD9, 0x8A, 0x46, 0xD8, 0xB6, 0xD8, 0xAE, + 0xD9, 0x85, 0x46, 0xD8, 0xB7, 0xD9, 0x85, 0xD8, + // Bytes 2440 - 247f + 0xAD, 0x46, 0xD8, 0xB7, 0xD9, 0x85, 0xD9, 0x85, + 0x46, 0xD8, 0xB7, 0xD9, 0x85, 0xD9, 0x8A, 0x46, + 0xD8, 0xB9, 0xD8, 0xAC, 0xD9, 0x85, 0x46, 0xD8, + 0xB9, 0xD9, 0x85, 0xD9, 0x85, 0x46, 0xD8, 0xB9, + 0xD9, 0x85, 0xD9, 0x89, 0x46, 0xD8, 0xB9, 0xD9, + 0x85, 0xD9, 0x8A, 0x46, 0xD8, 0xBA, 0xD9, 0x85, + 0xD9, 0x85, 0x46, 0xD8, 0xBA, 0xD9, 0x85, 0xD9, + 0x89, 0x46, 0xD8, 0xBA, 0xD9, 0x85, 0xD9, 0x8A, + // Bytes 2480 - 24bf + 0x46, 0xD9, 0x81, 0xD8, 0xAE, 0xD9, 0x85, 0x46, + 0xD9, 0x81, 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD9, + 0x82, 0xD9, 0x84, 0xDB, 0x92, 0x46, 0xD9, 0x82, + 0xD9, 0x85, 0xD8, 0xAD, 0x46, 0xD9, 0x82, 0xD9, + 0x85, 0xD9, 0x85, 0x46, 0xD9, 0x82, 0xD9, 0x85, + 0xD9, 0x8A, 0x46, 0xD9, 0x83, 0xD9, 0x85, 0xD9, + 0x85, 0x46, 0xD9, 0x83, 0xD9, 0x85, 0xD9, 0x8A, + 0x46, 0xD9, 0x84, 0xD8, 0xAC, 0xD8, 0xAC, 0x46, + // Bytes 24c0 - 24ff + 0xD9, 0x84, 0xD8, 0xAC, 0xD9, 0x85, 0x46, 0xD9, + 0x84, 0xD8, 0xAC, 0xD9, 0x8A, 0x46, 0xD9, 0x84, + 0xD8, 0xAD, 0xD9, 0x85, 0x46, 0xD9, 0x84, 0xD8, + 0xAD, 0xD9, 0x89, 0x46, 0xD9, 0x84, 0xD8, 0xAD, + 0xD9, 0x8A, 0x46, 0xD9, 0x84, 0xD8, 0xAE, 0xD9, + 0x85, 0x46, 0xD9, 0x84, 0xD9, 0x85, 0xD8, 0xAD, + 0x46, 0xD9, 0x84, 0xD9, 0x85, 0xD9, 0x8A, 0x46, + 0xD9, 0x85, 0xD8, 0xAC, 0xD8, 0xAD, 0x46, 0xD9, + // Bytes 2500 - 253f + 0x85, 0xD8, 0xAC, 0xD8, 0xAE, 0x46, 0xD9, 0x85, + 0xD8, 0xAC, 0xD9, 0x85, 0x46, 0xD9, 0x85, 0xD8, + 0xAC, 0xD9, 0x8A, 0x46, 0xD9, 0x85, 0xD8, 0xAD, + 0xD8, 0xAC, 0x46, 0xD9, 0x85, 0xD8, 0xAD, 0xD9, + 0x85, 0x46, 0xD9, 0x85, 0xD8, 0xAD, 0xD9, 0x8A, + 0x46, 0xD9, 0x85, 0xD8, 0xAE, 0xD8, 0xAC, 0x46, + 0xD9, 0x85, 0xD8, 0xAE, 0xD9, 0x85, 0x46, 0xD9, + 0x85, 0xD8, 0xAE, 0xD9, 0x8A, 0x46, 0xD9, 0x85, + // Bytes 2540 - 257f + 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD9, 0x86, 0xD8, + 0xAC, 0xD8, 0xAD, 0x46, 0xD9, 0x86, 0xD8, 0xAC, + 0xD9, 0x85, 0x46, 0xD9, 0x86, 0xD8, 0xAC, 0xD9, + 0x89, 0x46, 0xD9, 0x86, 0xD8, 0xAC, 0xD9, 0x8A, + 0x46, 0xD9, 0x86, 0xD8, 0xAD, 0xD9, 0x85, 0x46, + 0xD9, 0x86, 0xD8, 0xAD, 0xD9, 0x89, 0x46, 0xD9, + 0x86, 0xD8, 0xAD, 0xD9, 0x8A, 0x46, 0xD9, 0x86, + 0xD9, 0x85, 0xD9, 0x89, 0x46, 0xD9, 0x86, 0xD9, + // Bytes 2580 - 25bf + 0x85, 0xD9, 0x8A, 0x46, 0xD9, 0x87, 0xD9, 0x85, + 0xD8, 0xAC, 0x46, 0xD9, 0x87, 0xD9, 0x85, 0xD9, + 0x85, 0x46, 0xD9, 0x8A, 0xD8, 0xAC, 0xD9, 0x8A, + 0x46, 0xD9, 0x8A, 0xD8, 0xAD, 0xD9, 0x8A, 0x46, + 0xD9, 0x8A, 0xD9, 0x85, 0xD9, 0x85, 0x46, 0xD9, + 0x8A, 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD9, 0x8A, + 0xD9, 0x94, 0xD8, 0xA7, 0x46, 0xD9, 0x8A, 0xD9, + 0x94, 0xD8, 0xAC, 0x46, 0xD9, 0x8A, 0xD9, 0x94, + // Bytes 25c0 - 25ff + 0xD8, 0xAD, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD8, + 0xAE, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD8, 0xB1, + 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD8, 0xB2, 0x46, + 0xD9, 0x8A, 0xD9, 0x94, 0xD9, 0x85, 0x46, 0xD9, + 0x8A, 0xD9, 0x94, 0xD9, 0x86, 0x46, 0xD9, 0x8A, + 0xD9, 0x94, 0xD9, 0x87, 0x46, 0xD9, 0x8A, 0xD9, + 0x94, 0xD9, 0x88, 0x46, 0xD9, 0x8A, 0xD9, 0x94, + 0xD9, 0x89, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD9, + // Bytes 2600 - 263f + 0x8A, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xDB, 0x86, + 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xDB, 0x87, 0x46, + 0xD9, 0x8A, 0xD9, 0x94, 0xDB, 0x88, 0x46, 0xD9, + 0x8A, 0xD9, 0x94, 0xDB, 0x90, 0x46, 0xD9, 0x8A, + 0xD9, 0x94, 0xDB, 0x95, 0x46, 0xE0, 0xB9, 0x8D, + 0xE0, 0xB8, 0xB2, 0x46, 0xE0, 0xBA, 0xAB, 0xE0, + 0xBA, 0x99, 0x46, 0xE0, 0xBA, 0xAB, 0xE0, 0xBA, + 0xA1, 0x46, 0xE0, 0xBB, 0x8D, 0xE0, 0xBA, 0xB2, + // Bytes 2640 - 267f + 0x46, 0xE0, 0xBD, 0x80, 0xE0, 0xBE, 0xB5, 0x46, + 0xE0, 0xBD, 0x82, 0xE0, 0xBE, 0xB7, 0x46, 0xE0, + 0xBD, 0x8C, 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBD, + 0x91, 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBD, 0x96, + 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBD, 0x9B, 0xE0, + 0xBE, 0xB7, 0x46, 0xE0, 0xBE, 0x90, 0xE0, 0xBE, + 0xB5, 0x46, 0xE0, 0xBE, 0x92, 0xE0, 0xBE, 0xB7, + 0x46, 0xE0, 0xBE, 0x9C, 0xE0, 0xBE, 0xB7, 0x46, + // Bytes 2680 - 26bf + 0xE0, 0xBE, 0xA1, 0xE0, 0xBE, 0xB7, 0x46, 0xE0, + 0xBE, 0xA6, 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBE, + 0xAB, 0xE0, 0xBE, 0xB7, 0x46, 0xE2, 0x80, 0xB2, + 0xE2, 0x80, 0xB2, 0x46, 0xE2, 0x80, 0xB5, 0xE2, + 0x80, 0xB5, 0x46, 0xE2, 0x88, 0xAB, 0xE2, 0x88, + 0xAB, 0x46, 0xE2, 0x88, 0xAE, 0xE2, 0x88, 0xAE, + 0x46, 0xE3, 0x81, 0xBB, 0xE3, 0x81, 0x8B, 0x46, + 0xE3, 0x82, 0x88, 0xE3, 0x82, 0x8A, 0x46, 0xE3, + // Bytes 26c0 - 26ff + 0x82, 0xAD, 0xE3, 0x83, 0xAD, 0x46, 0xE3, 0x82, + 0xB3, 0xE3, 0x82, 0xB3, 0x46, 0xE3, 0x82, 0xB3, + 0xE3, 0x83, 0x88, 0x46, 0xE3, 0x83, 0x88, 0xE3, + 0x83, 0xB3, 0x46, 0xE3, 0x83, 0x8A, 0xE3, 0x83, + 0x8E, 0x46, 0xE3, 0x83, 0x9B, 0xE3, 0x83, 0xB3, + 0x46, 0xE3, 0x83, 0x9F, 0xE3, 0x83, 0xAA, 0x46, + 0xE3, 0x83, 0xAA, 0xE3, 0x83, 0xA9, 0x46, 0xE3, + 0x83, 0xAC, 0xE3, 0x83, 0xA0, 0x46, 0xE5, 0xA4, + // Bytes 2700 - 273f + 0xA7, 0xE6, 0xAD, 0xA3, 0x46, 0xE5, 0xB9, 0xB3, + 0xE6, 0x88, 0x90, 0x46, 0xE6, 0x98, 0x8E, 0xE6, + 0xB2, 0xBB, 0x46, 0xE6, 0x98, 0xAD, 0xE5, 0x92, + 0x8C, 0x47, 0x72, 0x61, 0x64, 0xE2, 0x88, 0x95, + 0x73, 0x47, 0xE3, 0x80, 0x94, 0x53, 0xE3, 0x80, + 0x95, 0x48, 0x28, 0xE1, 0x84, 0x80, 0xE1, 0x85, + 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x82, 0xE1, + 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x83, + // Bytes 2740 - 277f + 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, + 0x85, 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, + 0x84, 0x86, 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, + 0xE1, 0x84, 0x87, 0xE1, 0x85, 0xA1, 0x29, 0x48, + 0x28, 0xE1, 0x84, 0x89, 0xE1, 0x85, 0xA1, 0x29, + 0x48, 0x28, 0xE1, 0x84, 0x8B, 0xE1, 0x85, 0xA1, + 0x29, 0x48, 0x28, 0xE1, 0x84, 0x8C, 0xE1, 0x85, + 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x8C, 0xE1, + // Bytes 2780 - 27bf + 0x85, 0xAE, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x8E, + 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, + 0x8F, 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, + 0x84, 0x90, 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, + 0xE1, 0x84, 0x91, 0xE1, 0x85, 0xA1, 0x29, 0x48, + 0x28, 0xE1, 0x84, 0x92, 0xE1, 0x85, 0xA1, 0x29, + 0x48, 0x72, 0x61, 0x64, 0xE2, 0x88, 0x95, 0x73, + 0x32, 0x48, 0xD8, 0xA7, 0xD9, 0x83, 0xD8, 0xA8, + // Bytes 27c0 - 27ff + 0xD8, 0xB1, 0x48, 0xD8, 0xA7, 0xD9, 0x84, 0xD9, + 0x84, 0xD9, 0x87, 0x48, 0xD8, 0xB1, 0xD8, 0xB3, + 0xD9, 0x88, 0xD9, 0x84, 0x48, 0xD8, 0xB1, 0xDB, + 0x8C, 0xD8, 0xA7, 0xD9, 0x84, 0x48, 0xD8, 0xB5, + 0xD9, 0x84, 0xD8, 0xB9, 0xD9, 0x85, 0x48, 0xD8, + 0xB9, 0xD9, 0x84, 0xD9, 0x8A, 0xD9, 0x87, 0x48, + 0xD9, 0x85, 0xD8, 0xAD, 0xD9, 0x85, 0xD8, 0xAF, + 0x48, 0xD9, 0x88, 0xD8, 0xB3, 0xD9, 0x84, 0xD9, + // Bytes 2800 - 283f + 0x85, 0x49, 0xE2, 0x80, 0xB2, 0xE2, 0x80, 0xB2, + 0xE2, 0x80, 0xB2, 0x49, 0xE2, 0x80, 0xB5, 0xE2, + 0x80, 0xB5, 0xE2, 0x80, 0xB5, 0x49, 0xE2, 0x88, + 0xAB, 0xE2, 0x88, 0xAB, 0xE2, 0x88, 0xAB, 0x49, + 0xE2, 0x88, 0xAE, 0xE2, 0x88, 0xAE, 0xE2, 0x88, + 0xAE, 0x49, 0xE3, 0x80, 0x94, 0xE4, 0xB8, 0x89, + 0xE3, 0x80, 0x95, 0x49, 0xE3, 0x80, 0x94, 0xE4, + 0xBA, 0x8C, 0xE3, 0x80, 0x95, 0x49, 0xE3, 0x80, + // Bytes 2840 - 287f + 0x94, 0xE5, 0x8B, 0x9D, 0xE3, 0x80, 0x95, 0x49, + 0xE3, 0x80, 0x94, 0xE5, 0xAE, 0x89, 0xE3, 0x80, + 0x95, 0x49, 0xE3, 0x80, 0x94, 0xE6, 0x89, 0x93, + 0xE3, 0x80, 0x95, 0x49, 0xE3, 0x80, 0x94, 0xE6, + 0x95, 0x97, 0xE3, 0x80, 0x95, 0x49, 0xE3, 0x80, + 0x94, 0xE6, 0x9C, 0xAC, 0xE3, 0x80, 0x95, 0x49, + 0xE3, 0x80, 0x94, 0xE7, 0x82, 0xB9, 0xE3, 0x80, + 0x95, 0x49, 0xE3, 0x80, 0x94, 0xE7, 0x9B, 0x97, + // Bytes 2880 - 28bf + 0xE3, 0x80, 0x95, 0x49, 0xE3, 0x82, 0xA2, 0xE3, + 0x83, 0xBC, 0xE3, 0x83, 0xAB, 0x49, 0xE3, 0x82, + 0xA4, 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x81, 0x49, + 0xE3, 0x82, 0xA6, 0xE3, 0x82, 0xA9, 0xE3, 0x83, + 0xB3, 0x49, 0xE3, 0x82, 0xAA, 0xE3, 0x83, 0xB3, + 0xE3, 0x82, 0xB9, 0x49, 0xE3, 0x82, 0xAA, 0xE3, + 0x83, 0xBC, 0xE3, 0x83, 0xA0, 0x49, 0xE3, 0x82, + 0xAB, 0xE3, 0x82, 0xA4, 0xE3, 0x83, 0xAA, 0x49, + // Bytes 28c0 - 28ff + 0xE3, 0x82, 0xB1, 0xE3, 0x83, 0xBC, 0xE3, 0x82, + 0xB9, 0x49, 0xE3, 0x82, 0xB3, 0xE3, 0x83, 0xAB, + 0xE3, 0x83, 0x8A, 0x49, 0xE3, 0x82, 0xBB, 0xE3, + 0x83, 0xB3, 0xE3, 0x83, 0x81, 0x49, 0xE3, 0x82, + 0xBB, 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x88, 0x49, + 0xE3, 0x83, 0x86, 0xE3, 0x82, 0x99, 0xE3, 0x82, + 0xB7, 0x49, 0xE3, 0x83, 0x88, 0xE3, 0x82, 0x99, + 0xE3, 0x83, 0xAB, 0x49, 0xE3, 0x83, 0x8E, 0xE3, + // Bytes 2900 - 293f + 0x83, 0x83, 0xE3, 0x83, 0x88, 0x49, 0xE3, 0x83, + 0x8F, 0xE3, 0x82, 0xA4, 0xE3, 0x83, 0x84, 0x49, + 0xE3, 0x83, 0x92, 0xE3, 0x82, 0x99, 0xE3, 0x83, + 0xAB, 0x49, 0xE3, 0x83, 0x92, 0xE3, 0x82, 0x9A, + 0xE3, 0x82, 0xB3, 0x49, 0xE3, 0x83, 0x95, 0xE3, + 0x83, 0xA9, 0xE3, 0x83, 0xB3, 0x49, 0xE3, 0x83, + 0x98, 0xE3, 0x82, 0x9A, 0xE3, 0x82, 0xBD, 0x49, + 0xE3, 0x83, 0x98, 0xE3, 0x83, 0xAB, 0xE3, 0x83, + // Bytes 2940 - 297f + 0x84, 0x49, 0xE3, 0x83, 0x9B, 0xE3, 0x83, 0xBC, + 0xE3, 0x83, 0xAB, 0x49, 0xE3, 0x83, 0x9B, 0xE3, + 0x83, 0xBC, 0xE3, 0x83, 0xB3, 0x49, 0xE3, 0x83, + 0x9E, 0xE3, 0x82, 0xA4, 0xE3, 0x83, 0xAB, 0x49, + 0xE3, 0x83, 0x9E, 0xE3, 0x83, 0x83, 0xE3, 0x83, + 0x8F, 0x49, 0xE3, 0x83, 0x9E, 0xE3, 0x83, 0xAB, + 0xE3, 0x82, 0xAF, 0x49, 0xE3, 0x83, 0xA4, 0xE3, + 0x83, 0xBC, 0xE3, 0x83, 0xAB, 0x49, 0xE3, 0x83, + // Bytes 2980 - 29bf + 0xA6, 0xE3, 0x82, 0xA2, 0xE3, 0x83, 0xB3, 0x49, + 0xE3, 0x83, 0xAF, 0xE3, 0x83, 0x83, 0xE3, 0x83, + 0x88, 0x4C, 0xE2, 0x80, 0xB2, 0xE2, 0x80, 0xB2, + 0xE2, 0x80, 0xB2, 0xE2, 0x80, 0xB2, 0x4C, 0xE2, + 0x88, 0xAB, 0xE2, 0x88, 0xAB, 0xE2, 0x88, 0xAB, + 0xE2, 0x88, 0xAB, 0x4C, 0xE3, 0x82, 0xA2, 0xE3, + 0x83, 0xAB, 0xE3, 0x83, 0x95, 0xE3, 0x82, 0xA1, + 0x4C, 0xE3, 0x82, 0xA8, 0xE3, 0x83, 0xBC, 0xE3, + // Bytes 29c0 - 29ff + 0x82, 0xAB, 0xE3, 0x83, 0xBC, 0x4C, 0xE3, 0x82, + 0xAB, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xAD, 0xE3, + 0x83, 0xB3, 0x4C, 0xE3, 0x82, 0xAB, 0xE3, 0x82, + 0x99, 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x9E, 0x4C, + 0xE3, 0x82, 0xAB, 0xE3, 0x83, 0xA9, 0xE3, 0x83, + 0x83, 0xE3, 0x83, 0x88, 0x4C, 0xE3, 0x82, 0xAB, + 0xE3, 0x83, 0xAD, 0xE3, 0x83, 0xAA, 0xE3, 0x83, + 0xBC, 0x4C, 0xE3, 0x82, 0xAD, 0xE3, 0x82, 0x99, + // Bytes 2a00 - 2a3f + 0xE3, 0x83, 0x8B, 0xE3, 0x83, 0xBC, 0x4C, 0xE3, + 0x82, 0xAD, 0xE3, 0x83, 0xA5, 0xE3, 0x83, 0xAA, + 0xE3, 0x83, 0xBC, 0x4C, 0xE3, 0x82, 0xAF, 0xE3, + 0x82, 0x99, 0xE3, 0x83, 0xA9, 0xE3, 0x83, 0xA0, + 0x4C, 0xE3, 0x82, 0xAF, 0xE3, 0x83, 0xAD, 0xE3, + 0x83, 0xBC, 0xE3, 0x83, 0x8D, 0x4C, 0xE3, 0x82, + 0xB5, 0xE3, 0x82, 0xA4, 0xE3, 0x82, 0xAF, 0xE3, + 0x83, 0xAB, 0x4C, 0xE3, 0x82, 0xBF, 0xE3, 0x82, + // Bytes 2a40 - 2a7f + 0x99, 0xE3, 0x83, 0xBC, 0xE3, 0x82, 0xB9, 0x4C, + 0xE3, 0x83, 0x8F, 0xE3, 0x82, 0x9A, 0xE3, 0x83, + 0xBC, 0xE3, 0x83, 0x84, 0x4C, 0xE3, 0x83, 0x92, + 0xE3, 0x82, 0x9A, 0xE3, 0x82, 0xAF, 0xE3, 0x83, + 0xAB, 0x4C, 0xE3, 0x83, 0x95, 0xE3, 0x82, 0xA3, + 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x88, 0x4C, 0xE3, + 0x83, 0x98, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xBC, + 0xE3, 0x82, 0xBF, 0x4C, 0xE3, 0x83, 0x98, 0xE3, + // Bytes 2a80 - 2abf + 0x82, 0x9A, 0xE3, 0x83, 0x8B, 0xE3, 0x83, 0x92, + 0x4C, 0xE3, 0x83, 0x98, 0xE3, 0x82, 0x9A, 0xE3, + 0x83, 0xB3, 0xE3, 0x82, 0xB9, 0x4C, 0xE3, 0x83, + 0x9B, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xAB, 0xE3, + 0x83, 0x88, 0x4C, 0xE3, 0x83, 0x9E, 0xE3, 0x82, + 0xA4, 0xE3, 0x82, 0xAF, 0xE3, 0x83, 0xAD, 0x4C, + 0xE3, 0x83, 0x9F, 0xE3, 0x82, 0xAF, 0xE3, 0x83, + 0xAD, 0xE3, 0x83, 0xB3, 0x4C, 0xE3, 0x83, 0xA1, + // Bytes 2ac0 - 2aff + 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x88, 0xE3, 0x83, + 0xAB, 0x4C, 0xE3, 0x83, 0xAA, 0xE3, 0x83, 0x83, + 0xE3, 0x83, 0x88, 0xE3, 0x83, 0xAB, 0x4C, 0xE3, + 0x83, 0xAB, 0xE3, 0x83, 0x92, 0xE3, 0x82, 0x9A, + 0xE3, 0x83, 0xBC, 0x4C, 0xE6, 0xA0, 0xAA, 0xE5, + 0xBC, 0x8F, 0xE4, 0xBC, 0x9A, 0xE7, 0xA4, 0xBE, + 0x4E, 0x28, 0xE1, 0x84, 0x8B, 0xE1, 0x85, 0xA9, + 0xE1, 0x84, 0x92, 0xE1, 0x85, 0xAE, 0x29, 0x4F, + // Bytes 2b00 - 2b3f + 0xD8, 0xAC, 0xD9, 0x84, 0x20, 0xD8, 0xAC, 0xD9, + 0x84, 0xD8, 0xA7, 0xD9, 0x84, 0xD9, 0x87, 0x4F, + 0xE3, 0x82, 0xA2, 0xE3, 0x83, 0x8F, 0xE3, 0x82, + 0x9A, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x88, 0x4F, + 0xE3, 0x82, 0xA2, 0xE3, 0x83, 0xB3, 0xE3, 0x83, + 0x98, 0xE3, 0x82, 0x9A, 0xE3, 0x82, 0xA2, 0x4F, + 0xE3, 0x82, 0xAD, 0xE3, 0x83, 0xAD, 0xE3, 0x83, + 0xAF, 0xE3, 0x83, 0x83, 0xE3, 0x83, 0x88, 0x4F, + // Bytes 2b40 - 2b7f + 0xE3, 0x82, 0xB5, 0xE3, 0x83, 0xB3, 0xE3, 0x83, + 0x81, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0xA0, 0x4F, + 0xE3, 0x83, 0x8F, 0xE3, 0x82, 0x99, 0xE3, 0x83, + 0xBC, 0xE3, 0x83, 0xAC, 0xE3, 0x83, 0xAB, 0x4F, + 0xE3, 0x83, 0x98, 0xE3, 0x82, 0xAF, 0xE3, 0x82, + 0xBF, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0xAB, 0x4F, + 0xE3, 0x83, 0x9B, 0xE3, 0x82, 0x9A, 0xE3, 0x82, + 0xA4, 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x88, 0x4F, + // Bytes 2b80 - 2bbf + 0xE3, 0x83, 0x9E, 0xE3, 0x83, 0xB3, 0xE3, 0x82, + 0xB7, 0xE3, 0x83, 0xA7, 0xE3, 0x83, 0xB3, 0x4F, + 0xE3, 0x83, 0xA1, 0xE3, 0x82, 0xAB, 0xE3, 0x82, + 0x99, 0xE3, 0x83, 0x88, 0xE3, 0x83, 0xB3, 0x4F, + 0xE3, 0x83, 0xAB, 0xE3, 0x83, 0xBC, 0xE3, 0x83, + 0x95, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xAB, 0x51, + 0x28, 0xE1, 0x84, 0x8B, 0xE1, 0x85, 0xA9, 0xE1, + 0x84, 0x8C, 0xE1, 0x85, 0xA5, 0xE1, 0x86, 0xAB, + // Bytes 2bc0 - 2bff + 0x29, 0x52, 0xE3, 0x82, 0xAD, 0xE3, 0x82, 0x99, + 0xE3, 0x83, 0xAB, 0xE3, 0x82, 0xBF, 0xE3, 0x82, + 0x99, 0xE3, 0x83, 0xBC, 0x52, 0xE3, 0x82, 0xAD, + 0xE3, 0x83, 0xAD, 0xE3, 0x82, 0xAF, 0xE3, 0x82, + 0x99, 0xE3, 0x83, 0xA9, 0xE3, 0x83, 0xA0, 0x52, + 0xE3, 0x82, 0xAD, 0xE3, 0x83, 0xAD, 0xE3, 0x83, + 0xA1, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x88, 0xE3, + 0x83, 0xAB, 0x52, 0xE3, 0x82, 0xAF, 0xE3, 0x82, + // Bytes 2c00 - 2c3f + 0x99, 0xE3, 0x83, 0xA9, 0xE3, 0x83, 0xA0, 0xE3, + 0x83, 0x88, 0xE3, 0x83, 0xB3, 0x52, 0xE3, 0x82, + 0xAF, 0xE3, 0x83, 0xAB, 0xE3, 0x82, 0xBB, 0xE3, + 0x82, 0x99, 0xE3, 0x82, 0xA4, 0xE3, 0x83, 0xAD, + 0x52, 0xE3, 0x83, 0x8F, 0xE3, 0x82, 0x9A, 0xE3, + 0x83, 0xBC, 0xE3, 0x82, 0xBB, 0xE3, 0x83, 0xB3, + 0xE3, 0x83, 0x88, 0x52, 0xE3, 0x83, 0x92, 0xE3, + 0x82, 0x9A, 0xE3, 0x82, 0xA2, 0xE3, 0x82, 0xB9, + // Bytes 2c40 - 2c7f + 0xE3, 0x83, 0x88, 0xE3, 0x83, 0xAB, 0x52, 0xE3, + 0x83, 0x95, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0x83, + 0xE3, 0x82, 0xB7, 0xE3, 0x82, 0xA7, 0xE3, 0x83, + 0xAB, 0x52, 0xE3, 0x83, 0x9F, 0xE3, 0x83, 0xAA, + 0xE3, 0x83, 0x8F, 0xE3, 0x82, 0x99, 0xE3, 0x83, + 0xBC, 0xE3, 0x83, 0xAB, 0x52, 0xE3, 0x83, 0xAC, + 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x88, 0xE3, 0x82, + 0xB1, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xB3, 0x61, + // Bytes 2c80 - 2cbf + 0xD8, 0xB5, 0xD9, 0x84, 0xD9, 0x89, 0x20, 0xD8, + 0xA7, 0xD9, 0x84, 0xD9, 0x84, 0xD9, 0x87, 0x20, + 0xD8, 0xB9, 0xD9, 0x84, 0xD9, 0x8A, 0xD9, 0x87, + 0x20, 0xD9, 0x88, 0xD8, 0xB3, 0xD9, 0x84, 0xD9, + 0x85, 0x06, 0xE0, 0xA7, 0x87, 0xE0, 0xA6, 0xBE, + 0x01, 0x06, 0xE0, 0xA7, 0x87, 0xE0, 0xA7, 0x97, + 0x01, 0x06, 0xE0, 0xAD, 0x87, 0xE0, 0xAC, 0xBE, + 0x01, 0x06, 0xE0, 0xAD, 0x87, 0xE0, 0xAD, 0x96, + // Bytes 2cc0 - 2cff + 0x01, 0x06, 0xE0, 0xAD, 0x87, 0xE0, 0xAD, 0x97, + 0x01, 0x06, 0xE0, 0xAE, 0x92, 0xE0, 0xAF, 0x97, + 0x01, 0x06, 0xE0, 0xAF, 0x86, 0xE0, 0xAE, 0xBE, + 0x01, 0x06, 0xE0, 0xAF, 0x86, 0xE0, 0xAF, 0x97, + 0x01, 0x06, 0xE0, 0xAF, 0x87, 0xE0, 0xAE, 0xBE, + 0x01, 0x06, 0xE0, 0xB2, 0xBF, 0xE0, 0xB3, 0x95, + 0x01, 0x06, 0xE0, 0xB3, 0x86, 0xE0, 0xB3, 0x95, + 0x01, 0x06, 0xE0, 0xB3, 0x86, 0xE0, 0xB3, 0x96, + // Bytes 2d00 - 2d3f + 0x01, 0x06, 0xE0, 0xB5, 0x86, 0xE0, 0xB4, 0xBE, + 0x01, 0x06, 0xE0, 0xB5, 0x86, 0xE0, 0xB5, 0x97, + 0x01, 0x06, 0xE0, 0xB5, 0x87, 0xE0, 0xB4, 0xBE, + 0x01, 0x06, 0xE0, 0xB7, 0x99, 0xE0, 0xB7, 0x9F, + 0x01, 0x06, 0xE1, 0x80, 0xA5, 0xE1, 0x80, 0xAE, + 0x01, 0x06, 0xE1, 0xAC, 0x85, 0xE1, 0xAC, 0xB5, + 0x01, 0x06, 0xE1, 0xAC, 0x87, 0xE1, 0xAC, 0xB5, + 0x01, 0x06, 0xE1, 0xAC, 0x89, 0xE1, 0xAC, 0xB5, + // Bytes 2d40 - 2d7f + 0x01, 0x06, 0xE1, 0xAC, 0x8B, 0xE1, 0xAC, 0xB5, + 0x01, 0x06, 0xE1, 0xAC, 0x8D, 0xE1, 0xAC, 0xB5, + 0x01, 0x06, 0xE1, 0xAC, 0x91, 0xE1, 0xAC, 0xB5, + 0x01, 0x06, 0xE1, 0xAC, 0xBA, 0xE1, 0xAC, 0xB5, + 0x01, 0x06, 0xE1, 0xAC, 0xBC, 0xE1, 0xAC, 0xB5, + 0x01, 0x06, 0xE1, 0xAC, 0xBE, 0xE1, 0xAC, 0xB5, + 0x01, 0x06, 0xE1, 0xAC, 0xBF, 0xE1, 0xAC, 0xB5, + 0x01, 0x06, 0xE1, 0xAD, 0x82, 0xE1, 0xAC, 0xB5, + // Bytes 2d80 - 2dbf + 0x01, 0x08, 0xF0, 0x91, 0x84, 0xB1, 0xF0, 0x91, + 0x84, 0xA7, 0x01, 0x08, 0xF0, 0x91, 0x84, 0xB2, + 0xF0, 0x91, 0x84, 0xA7, 0x01, 0x08, 0xF0, 0x91, + 0x8D, 0x87, 0xF0, 0x91, 0x8C, 0xBE, 0x01, 0x08, + 0xF0, 0x91, 0x8D, 0x87, 0xF0, 0x91, 0x8D, 0x97, + 0x01, 0x08, 0xF0, 0x91, 0x92, 0xB9, 0xF0, 0x91, + 0x92, 0xB0, 0x01, 0x08, 0xF0, 0x91, 0x92, 0xB9, + 0xF0, 0x91, 0x92, 0xBA, 0x01, 0x08, 0xF0, 0x91, + // Bytes 2dc0 - 2dff + 0x92, 0xB9, 0xF0, 0x91, 0x92, 0xBD, 0x01, 0x08, + 0xF0, 0x91, 0x96, 0xB8, 0xF0, 0x91, 0x96, 0xAF, + 0x01, 0x08, 0xF0, 0x91, 0x96, 0xB9, 0xF0, 0x91, + 0x96, 0xAF, 0x01, 0x09, 0xE0, 0xB3, 0x86, 0xE0, + 0xB3, 0x82, 0xE0, 0xB3, 0x95, 0x02, 0x09, 0xE0, + 0xB7, 0x99, 0xE0, 0xB7, 0x8F, 0xE0, 0xB7, 0x8A, + 0x12, 0x44, 0x44, 0x5A, 0xCC, 0x8C, 0xC9, 0x44, + 0x44, 0x7A, 0xCC, 0x8C, 0xC9, 0x44, 0x64, 0x7A, + // Bytes 2e00 - 2e3f + 0xCC, 0x8C, 0xC9, 0x46, 0xD9, 0x84, 0xD8, 0xA7, + 0xD9, 0x93, 0xC9, 0x46, 0xD9, 0x84, 0xD8, 0xA7, + 0xD9, 0x94, 0xC9, 0x46, 0xD9, 0x84, 0xD8, 0xA7, + 0xD9, 0x95, 0xB5, 0x46, 0xE1, 0x84, 0x80, 0xE1, + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x82, 0xE1, + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x83, 0xE1, + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x85, 0xE1, + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x86, 0xE1, + // Bytes 2e40 - 2e7f + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x87, 0xE1, + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x89, 0xE1, + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x8B, 0xE1, + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x8B, 0xE1, + 0x85, 0xAE, 0x01, 0x46, 0xE1, 0x84, 0x8C, 0xE1, + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x8E, 0xE1, + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x8F, 0xE1, + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x90, 0xE1, + // Bytes 2e80 - 2ebf + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x91, 0xE1, + 0x85, 0xA1, 0x01, 0x46, 0xE1, 0x84, 0x92, 0xE1, + 0x85, 0xA1, 0x01, 0x49, 0xE3, 0x83, 0xA1, 0xE3, + 0x82, 0xAB, 0xE3, 0x82, 0x99, 0x0D, 0x4C, 0xE1, + 0x84, 0x8C, 0xE1, 0x85, 0xAE, 0xE1, 0x84, 0x8B, + 0xE1, 0x85, 0xB4, 0x01, 0x4C, 0xE3, 0x82, 0xAD, + 0xE3, 0x82, 0x99, 0xE3, 0x82, 0xAB, 0xE3, 0x82, + 0x99, 0x0D, 0x4C, 0xE3, 0x82, 0xB3, 0xE3, 0x83, + // Bytes 2ec0 - 2eff + 0xBC, 0xE3, 0x83, 0x9B, 0xE3, 0x82, 0x9A, 0x0D, + 0x4C, 0xE3, 0x83, 0xA4, 0xE3, 0x83, 0xBC, 0xE3, + 0x83, 0x88, 0xE3, 0x82, 0x99, 0x0D, 0x4F, 0xE1, + 0x84, 0x8E, 0xE1, 0x85, 0xA1, 0xE1, 0x86, 0xB7, + 0xE1, 0x84, 0x80, 0xE1, 0x85, 0xA9, 0x01, 0x4F, + 0xE3, 0x82, 0xA4, 0xE3, 0x83, 0x8B, 0xE3, 0x83, + 0xB3, 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0x99, 0x0D, + 0x4F, 0xE3, 0x82, 0xB7, 0xE3, 0x83, 0xAA, 0xE3, + // Bytes 2f00 - 2f3f + 0x83, 0xB3, 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0x99, + 0x0D, 0x4F, 0xE3, 0x83, 0x98, 0xE3, 0x82, 0x9A, + 0xE3, 0x83, 0xBC, 0xE3, 0x82, 0xB7, 0xE3, 0x82, + 0x99, 0x0D, 0x4F, 0xE3, 0x83, 0x9B, 0xE3, 0x82, + 0x9A, 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x88, 0xE3, + 0x82, 0x99, 0x0D, 0x52, 0xE3, 0x82, 0xA8, 0xE3, + 0x82, 0xB9, 0xE3, 0x82, 0xAF, 0xE3, 0x83, 0xBC, + 0xE3, 0x83, 0x88, 0xE3, 0x82, 0x99, 0x0D, 0x52, + // Bytes 2f40 - 2f7f + 0xE3, 0x83, 0x95, 0xE3, 0x82, 0xA1, 0xE3, 0x83, + 0xA9, 0xE3, 0x83, 0x83, 0xE3, 0x83, 0x88, 0xE3, + 0x82, 0x99, 0x0D, 0x86, 0xE0, 0xB3, 0x86, 0xE0, + 0xB3, 0x82, 0x01, 0x86, 0xE0, 0xB7, 0x99, 0xE0, + 0xB7, 0x8F, 0x01, 0x03, 0x3C, 0xCC, 0xB8, 0x05, + 0x03, 0x3D, 0xCC, 0xB8, 0x05, 0x03, 0x3E, 0xCC, + 0xB8, 0x05, 0x03, 0x41, 0xCC, 0x80, 0xC9, 0x03, + 0x41, 0xCC, 0x81, 0xC9, 0x03, 0x41, 0xCC, 0x83, + // Bytes 2f80 - 2fbf + 0xC9, 0x03, 0x41, 0xCC, 0x84, 0xC9, 0x03, 0x41, + 0xCC, 0x89, 0xC9, 0x03, 0x41, 0xCC, 0x8C, 0xC9, + 0x03, 0x41, 0xCC, 0x8F, 0xC9, 0x03, 0x41, 0xCC, + 0x91, 0xC9, 0x03, 0x41, 0xCC, 0xA5, 0xB5, 0x03, + 0x41, 0xCC, 0xA8, 0xA5, 0x03, 0x42, 0xCC, 0x87, + 0xC9, 0x03, 0x42, 0xCC, 0xA3, 0xB5, 0x03, 0x42, + 0xCC, 0xB1, 0xB5, 0x03, 0x43, 0xCC, 0x81, 0xC9, + 0x03, 0x43, 0xCC, 0x82, 0xC9, 0x03, 0x43, 0xCC, + // Bytes 2fc0 - 2fff + 0x87, 0xC9, 0x03, 0x43, 0xCC, 0x8C, 0xC9, 0x03, + 0x44, 0xCC, 0x87, 0xC9, 0x03, 0x44, 0xCC, 0x8C, + 0xC9, 0x03, 0x44, 0xCC, 0xA3, 0xB5, 0x03, 0x44, + 0xCC, 0xA7, 0xA5, 0x03, 0x44, 0xCC, 0xAD, 0xB5, + 0x03, 0x44, 0xCC, 0xB1, 0xB5, 0x03, 0x45, 0xCC, + 0x80, 0xC9, 0x03, 0x45, 0xCC, 0x81, 0xC9, 0x03, + 0x45, 0xCC, 0x83, 0xC9, 0x03, 0x45, 0xCC, 0x86, + 0xC9, 0x03, 0x45, 0xCC, 0x87, 0xC9, 0x03, 0x45, + // Bytes 3000 - 303f + 0xCC, 0x88, 0xC9, 0x03, 0x45, 0xCC, 0x89, 0xC9, + 0x03, 0x45, 0xCC, 0x8C, 0xC9, 0x03, 0x45, 0xCC, + 0x8F, 0xC9, 0x03, 0x45, 0xCC, 0x91, 0xC9, 0x03, + 0x45, 0xCC, 0xA8, 0xA5, 0x03, 0x45, 0xCC, 0xAD, + 0xB5, 0x03, 0x45, 0xCC, 0xB0, 0xB5, 0x03, 0x46, + 0xCC, 0x87, 0xC9, 0x03, 0x47, 0xCC, 0x81, 0xC9, + 0x03, 0x47, 0xCC, 0x82, 0xC9, 0x03, 0x47, 0xCC, + 0x84, 0xC9, 0x03, 0x47, 0xCC, 0x86, 0xC9, 0x03, + // Bytes 3040 - 307f + 0x47, 0xCC, 0x87, 0xC9, 0x03, 0x47, 0xCC, 0x8C, + 0xC9, 0x03, 0x47, 0xCC, 0xA7, 0xA5, 0x03, 0x48, + 0xCC, 0x82, 0xC9, 0x03, 0x48, 0xCC, 0x87, 0xC9, + 0x03, 0x48, 0xCC, 0x88, 0xC9, 0x03, 0x48, 0xCC, + 0x8C, 0xC9, 0x03, 0x48, 0xCC, 0xA3, 0xB5, 0x03, + 0x48, 0xCC, 0xA7, 0xA5, 0x03, 0x48, 0xCC, 0xAE, + 0xB5, 0x03, 0x49, 0xCC, 0x80, 0xC9, 0x03, 0x49, + 0xCC, 0x81, 0xC9, 0x03, 0x49, 0xCC, 0x82, 0xC9, + // Bytes 3080 - 30bf + 0x03, 0x49, 0xCC, 0x83, 0xC9, 0x03, 0x49, 0xCC, + 0x84, 0xC9, 0x03, 0x49, 0xCC, 0x86, 0xC9, 0x03, + 0x49, 0xCC, 0x87, 0xC9, 0x03, 0x49, 0xCC, 0x89, + 0xC9, 0x03, 0x49, 0xCC, 0x8C, 0xC9, 0x03, 0x49, + 0xCC, 0x8F, 0xC9, 0x03, 0x49, 0xCC, 0x91, 0xC9, + 0x03, 0x49, 0xCC, 0xA3, 0xB5, 0x03, 0x49, 0xCC, + 0xA8, 0xA5, 0x03, 0x49, 0xCC, 0xB0, 0xB5, 0x03, + 0x4A, 0xCC, 0x82, 0xC9, 0x03, 0x4B, 0xCC, 0x81, + // Bytes 30c0 - 30ff + 0xC9, 0x03, 0x4B, 0xCC, 0x8C, 0xC9, 0x03, 0x4B, + 0xCC, 0xA3, 0xB5, 0x03, 0x4B, 0xCC, 0xA7, 0xA5, + 0x03, 0x4B, 0xCC, 0xB1, 0xB5, 0x03, 0x4C, 0xCC, + 0x81, 0xC9, 0x03, 0x4C, 0xCC, 0x8C, 0xC9, 0x03, + 0x4C, 0xCC, 0xA7, 0xA5, 0x03, 0x4C, 0xCC, 0xAD, + 0xB5, 0x03, 0x4C, 0xCC, 0xB1, 0xB5, 0x03, 0x4D, + 0xCC, 0x81, 0xC9, 0x03, 0x4D, 0xCC, 0x87, 0xC9, + 0x03, 0x4D, 0xCC, 0xA3, 0xB5, 0x03, 0x4E, 0xCC, + // Bytes 3100 - 313f + 0x80, 0xC9, 0x03, 0x4E, 0xCC, 0x81, 0xC9, 0x03, + 0x4E, 0xCC, 0x83, 0xC9, 0x03, 0x4E, 0xCC, 0x87, + 0xC9, 0x03, 0x4E, 0xCC, 0x8C, 0xC9, 0x03, 0x4E, + 0xCC, 0xA3, 0xB5, 0x03, 0x4E, 0xCC, 0xA7, 0xA5, + 0x03, 0x4E, 0xCC, 0xAD, 0xB5, 0x03, 0x4E, 0xCC, + 0xB1, 0xB5, 0x03, 0x4F, 0xCC, 0x80, 0xC9, 0x03, + 0x4F, 0xCC, 0x81, 0xC9, 0x03, 0x4F, 0xCC, 0x86, + 0xC9, 0x03, 0x4F, 0xCC, 0x89, 0xC9, 0x03, 0x4F, + // Bytes 3140 - 317f + 0xCC, 0x8B, 0xC9, 0x03, 0x4F, 0xCC, 0x8C, 0xC9, + 0x03, 0x4F, 0xCC, 0x8F, 0xC9, 0x03, 0x4F, 0xCC, + 0x91, 0xC9, 0x03, 0x50, 0xCC, 0x81, 0xC9, 0x03, + 0x50, 0xCC, 0x87, 0xC9, 0x03, 0x52, 0xCC, 0x81, + 0xC9, 0x03, 0x52, 0xCC, 0x87, 0xC9, 0x03, 0x52, + 0xCC, 0x8C, 0xC9, 0x03, 0x52, 0xCC, 0x8F, 0xC9, + 0x03, 0x52, 0xCC, 0x91, 0xC9, 0x03, 0x52, 0xCC, + 0xA7, 0xA5, 0x03, 0x52, 0xCC, 0xB1, 0xB5, 0x03, + // Bytes 3180 - 31bf + 0x53, 0xCC, 0x82, 0xC9, 0x03, 0x53, 0xCC, 0x87, + 0xC9, 0x03, 0x53, 0xCC, 0xA6, 0xB5, 0x03, 0x53, + 0xCC, 0xA7, 0xA5, 0x03, 0x54, 0xCC, 0x87, 0xC9, + 0x03, 0x54, 0xCC, 0x8C, 0xC9, 0x03, 0x54, 0xCC, + 0xA3, 0xB5, 0x03, 0x54, 0xCC, 0xA6, 0xB5, 0x03, + 0x54, 0xCC, 0xA7, 0xA5, 0x03, 0x54, 0xCC, 0xAD, + 0xB5, 0x03, 0x54, 0xCC, 0xB1, 0xB5, 0x03, 0x55, + 0xCC, 0x80, 0xC9, 0x03, 0x55, 0xCC, 0x81, 0xC9, + // Bytes 31c0 - 31ff + 0x03, 0x55, 0xCC, 0x82, 0xC9, 0x03, 0x55, 0xCC, + 0x86, 0xC9, 0x03, 0x55, 0xCC, 0x89, 0xC9, 0x03, + 0x55, 0xCC, 0x8A, 0xC9, 0x03, 0x55, 0xCC, 0x8B, + 0xC9, 0x03, 0x55, 0xCC, 0x8C, 0xC9, 0x03, 0x55, + 0xCC, 0x8F, 0xC9, 0x03, 0x55, 0xCC, 0x91, 0xC9, + 0x03, 0x55, 0xCC, 0xA3, 0xB5, 0x03, 0x55, 0xCC, + 0xA4, 0xB5, 0x03, 0x55, 0xCC, 0xA8, 0xA5, 0x03, + 0x55, 0xCC, 0xAD, 0xB5, 0x03, 0x55, 0xCC, 0xB0, + // Bytes 3200 - 323f + 0xB5, 0x03, 0x56, 0xCC, 0x83, 0xC9, 0x03, 0x56, + 0xCC, 0xA3, 0xB5, 0x03, 0x57, 0xCC, 0x80, 0xC9, + 0x03, 0x57, 0xCC, 0x81, 0xC9, 0x03, 0x57, 0xCC, + 0x82, 0xC9, 0x03, 0x57, 0xCC, 0x87, 0xC9, 0x03, + 0x57, 0xCC, 0x88, 0xC9, 0x03, 0x57, 0xCC, 0xA3, + 0xB5, 0x03, 0x58, 0xCC, 0x87, 0xC9, 0x03, 0x58, + 0xCC, 0x88, 0xC9, 0x03, 0x59, 0xCC, 0x80, 0xC9, + 0x03, 0x59, 0xCC, 0x81, 0xC9, 0x03, 0x59, 0xCC, + // Bytes 3240 - 327f + 0x82, 0xC9, 0x03, 0x59, 0xCC, 0x83, 0xC9, 0x03, + 0x59, 0xCC, 0x84, 0xC9, 0x03, 0x59, 0xCC, 0x87, + 0xC9, 0x03, 0x59, 0xCC, 0x88, 0xC9, 0x03, 0x59, + 0xCC, 0x89, 0xC9, 0x03, 0x59, 0xCC, 0xA3, 0xB5, + 0x03, 0x5A, 0xCC, 0x81, 0xC9, 0x03, 0x5A, 0xCC, + 0x82, 0xC9, 0x03, 0x5A, 0xCC, 0x87, 0xC9, 0x03, + 0x5A, 0xCC, 0x8C, 0xC9, 0x03, 0x5A, 0xCC, 0xA3, + 0xB5, 0x03, 0x5A, 0xCC, 0xB1, 0xB5, 0x03, 0x61, + // Bytes 3280 - 32bf + 0xCC, 0x80, 0xC9, 0x03, 0x61, 0xCC, 0x81, 0xC9, + 0x03, 0x61, 0xCC, 0x83, 0xC9, 0x03, 0x61, 0xCC, + 0x84, 0xC9, 0x03, 0x61, 0xCC, 0x89, 0xC9, 0x03, + 0x61, 0xCC, 0x8C, 0xC9, 0x03, 0x61, 0xCC, 0x8F, + 0xC9, 0x03, 0x61, 0xCC, 0x91, 0xC9, 0x03, 0x61, + 0xCC, 0xA5, 0xB5, 0x03, 0x61, 0xCC, 0xA8, 0xA5, + 0x03, 0x62, 0xCC, 0x87, 0xC9, 0x03, 0x62, 0xCC, + 0xA3, 0xB5, 0x03, 0x62, 0xCC, 0xB1, 0xB5, 0x03, + // Bytes 32c0 - 32ff + 0x63, 0xCC, 0x81, 0xC9, 0x03, 0x63, 0xCC, 0x82, + 0xC9, 0x03, 0x63, 0xCC, 0x87, 0xC9, 0x03, 0x63, + 0xCC, 0x8C, 0xC9, 0x03, 0x64, 0xCC, 0x87, 0xC9, + 0x03, 0x64, 0xCC, 0x8C, 0xC9, 0x03, 0x64, 0xCC, + 0xA3, 0xB5, 0x03, 0x64, 0xCC, 0xA7, 0xA5, 0x03, + 0x64, 0xCC, 0xAD, 0xB5, 0x03, 0x64, 0xCC, 0xB1, + 0xB5, 0x03, 0x65, 0xCC, 0x80, 0xC9, 0x03, 0x65, + 0xCC, 0x81, 0xC9, 0x03, 0x65, 0xCC, 0x83, 0xC9, + // Bytes 3300 - 333f + 0x03, 0x65, 0xCC, 0x86, 0xC9, 0x03, 0x65, 0xCC, + 0x87, 0xC9, 0x03, 0x65, 0xCC, 0x88, 0xC9, 0x03, + 0x65, 0xCC, 0x89, 0xC9, 0x03, 0x65, 0xCC, 0x8C, + 0xC9, 0x03, 0x65, 0xCC, 0x8F, 0xC9, 0x03, 0x65, + 0xCC, 0x91, 0xC9, 0x03, 0x65, 0xCC, 0xA8, 0xA5, + 0x03, 0x65, 0xCC, 0xAD, 0xB5, 0x03, 0x65, 0xCC, + 0xB0, 0xB5, 0x03, 0x66, 0xCC, 0x87, 0xC9, 0x03, + 0x67, 0xCC, 0x81, 0xC9, 0x03, 0x67, 0xCC, 0x82, + // Bytes 3340 - 337f + 0xC9, 0x03, 0x67, 0xCC, 0x84, 0xC9, 0x03, 0x67, + 0xCC, 0x86, 0xC9, 0x03, 0x67, 0xCC, 0x87, 0xC9, + 0x03, 0x67, 0xCC, 0x8C, 0xC9, 0x03, 0x67, 0xCC, + 0xA7, 0xA5, 0x03, 0x68, 0xCC, 0x82, 0xC9, 0x03, + 0x68, 0xCC, 0x87, 0xC9, 0x03, 0x68, 0xCC, 0x88, + 0xC9, 0x03, 0x68, 0xCC, 0x8C, 0xC9, 0x03, 0x68, + 0xCC, 0xA3, 0xB5, 0x03, 0x68, 0xCC, 0xA7, 0xA5, + 0x03, 0x68, 0xCC, 0xAE, 0xB5, 0x03, 0x68, 0xCC, + // Bytes 3380 - 33bf + 0xB1, 0xB5, 0x03, 0x69, 0xCC, 0x80, 0xC9, 0x03, + 0x69, 0xCC, 0x81, 0xC9, 0x03, 0x69, 0xCC, 0x82, + 0xC9, 0x03, 0x69, 0xCC, 0x83, 0xC9, 0x03, 0x69, + 0xCC, 0x84, 0xC9, 0x03, 0x69, 0xCC, 0x86, 0xC9, + 0x03, 0x69, 0xCC, 0x89, 0xC9, 0x03, 0x69, 0xCC, + 0x8C, 0xC9, 0x03, 0x69, 0xCC, 0x8F, 0xC9, 0x03, + 0x69, 0xCC, 0x91, 0xC9, 0x03, 0x69, 0xCC, 0xA3, + 0xB5, 0x03, 0x69, 0xCC, 0xA8, 0xA5, 0x03, 0x69, + // Bytes 33c0 - 33ff + 0xCC, 0xB0, 0xB5, 0x03, 0x6A, 0xCC, 0x82, 0xC9, + 0x03, 0x6A, 0xCC, 0x8C, 0xC9, 0x03, 0x6B, 0xCC, + 0x81, 0xC9, 0x03, 0x6B, 0xCC, 0x8C, 0xC9, 0x03, + 0x6B, 0xCC, 0xA3, 0xB5, 0x03, 0x6B, 0xCC, 0xA7, + 0xA5, 0x03, 0x6B, 0xCC, 0xB1, 0xB5, 0x03, 0x6C, + 0xCC, 0x81, 0xC9, 0x03, 0x6C, 0xCC, 0x8C, 0xC9, + 0x03, 0x6C, 0xCC, 0xA7, 0xA5, 0x03, 0x6C, 0xCC, + 0xAD, 0xB5, 0x03, 0x6C, 0xCC, 0xB1, 0xB5, 0x03, + // Bytes 3400 - 343f + 0x6D, 0xCC, 0x81, 0xC9, 0x03, 0x6D, 0xCC, 0x87, + 0xC9, 0x03, 0x6D, 0xCC, 0xA3, 0xB5, 0x03, 0x6E, + 0xCC, 0x80, 0xC9, 0x03, 0x6E, 0xCC, 0x81, 0xC9, + 0x03, 0x6E, 0xCC, 0x83, 0xC9, 0x03, 0x6E, 0xCC, + 0x87, 0xC9, 0x03, 0x6E, 0xCC, 0x8C, 0xC9, 0x03, + 0x6E, 0xCC, 0xA3, 0xB5, 0x03, 0x6E, 0xCC, 0xA7, + 0xA5, 0x03, 0x6E, 0xCC, 0xAD, 0xB5, 0x03, 0x6E, + 0xCC, 0xB1, 0xB5, 0x03, 0x6F, 0xCC, 0x80, 0xC9, + // Bytes 3440 - 347f + 0x03, 0x6F, 0xCC, 0x81, 0xC9, 0x03, 0x6F, 0xCC, + 0x86, 0xC9, 0x03, 0x6F, 0xCC, 0x89, 0xC9, 0x03, + 0x6F, 0xCC, 0x8B, 0xC9, 0x03, 0x6F, 0xCC, 0x8C, + 0xC9, 0x03, 0x6F, 0xCC, 0x8F, 0xC9, 0x03, 0x6F, + 0xCC, 0x91, 0xC9, 0x03, 0x70, 0xCC, 0x81, 0xC9, + 0x03, 0x70, 0xCC, 0x87, 0xC9, 0x03, 0x72, 0xCC, + 0x81, 0xC9, 0x03, 0x72, 0xCC, 0x87, 0xC9, 0x03, + 0x72, 0xCC, 0x8C, 0xC9, 0x03, 0x72, 0xCC, 0x8F, + // Bytes 3480 - 34bf + 0xC9, 0x03, 0x72, 0xCC, 0x91, 0xC9, 0x03, 0x72, + 0xCC, 0xA7, 0xA5, 0x03, 0x72, 0xCC, 0xB1, 0xB5, + 0x03, 0x73, 0xCC, 0x82, 0xC9, 0x03, 0x73, 0xCC, + 0x87, 0xC9, 0x03, 0x73, 0xCC, 0xA6, 0xB5, 0x03, + 0x73, 0xCC, 0xA7, 0xA5, 0x03, 0x74, 0xCC, 0x87, + 0xC9, 0x03, 0x74, 0xCC, 0x88, 0xC9, 0x03, 0x74, + 0xCC, 0x8C, 0xC9, 0x03, 0x74, 0xCC, 0xA3, 0xB5, + 0x03, 0x74, 0xCC, 0xA6, 0xB5, 0x03, 0x74, 0xCC, + // Bytes 34c0 - 34ff + 0xA7, 0xA5, 0x03, 0x74, 0xCC, 0xAD, 0xB5, 0x03, + 0x74, 0xCC, 0xB1, 0xB5, 0x03, 0x75, 0xCC, 0x80, + 0xC9, 0x03, 0x75, 0xCC, 0x81, 0xC9, 0x03, 0x75, + 0xCC, 0x82, 0xC9, 0x03, 0x75, 0xCC, 0x86, 0xC9, + 0x03, 0x75, 0xCC, 0x89, 0xC9, 0x03, 0x75, 0xCC, + 0x8A, 0xC9, 0x03, 0x75, 0xCC, 0x8B, 0xC9, 0x03, + 0x75, 0xCC, 0x8C, 0xC9, 0x03, 0x75, 0xCC, 0x8F, + 0xC9, 0x03, 0x75, 0xCC, 0x91, 0xC9, 0x03, 0x75, + // Bytes 3500 - 353f + 0xCC, 0xA3, 0xB5, 0x03, 0x75, 0xCC, 0xA4, 0xB5, + 0x03, 0x75, 0xCC, 0xA8, 0xA5, 0x03, 0x75, 0xCC, + 0xAD, 0xB5, 0x03, 0x75, 0xCC, 0xB0, 0xB5, 0x03, + 0x76, 0xCC, 0x83, 0xC9, 0x03, 0x76, 0xCC, 0xA3, + 0xB5, 0x03, 0x77, 0xCC, 0x80, 0xC9, 0x03, 0x77, + 0xCC, 0x81, 0xC9, 0x03, 0x77, 0xCC, 0x82, 0xC9, + 0x03, 0x77, 0xCC, 0x87, 0xC9, 0x03, 0x77, 0xCC, + 0x88, 0xC9, 0x03, 0x77, 0xCC, 0x8A, 0xC9, 0x03, + // Bytes 3540 - 357f + 0x77, 0xCC, 0xA3, 0xB5, 0x03, 0x78, 0xCC, 0x87, + 0xC9, 0x03, 0x78, 0xCC, 0x88, 0xC9, 0x03, 0x79, + 0xCC, 0x80, 0xC9, 0x03, 0x79, 0xCC, 0x81, 0xC9, + 0x03, 0x79, 0xCC, 0x82, 0xC9, 0x03, 0x79, 0xCC, + 0x83, 0xC9, 0x03, 0x79, 0xCC, 0x84, 0xC9, 0x03, + 0x79, 0xCC, 0x87, 0xC9, 0x03, 0x79, 0xCC, 0x88, + 0xC9, 0x03, 0x79, 0xCC, 0x89, 0xC9, 0x03, 0x79, + 0xCC, 0x8A, 0xC9, 0x03, 0x79, 0xCC, 0xA3, 0xB5, + // Bytes 3580 - 35bf + 0x03, 0x7A, 0xCC, 0x81, 0xC9, 0x03, 0x7A, 0xCC, + 0x82, 0xC9, 0x03, 0x7A, 0xCC, 0x87, 0xC9, 0x03, + 0x7A, 0xCC, 0x8C, 0xC9, 0x03, 0x7A, 0xCC, 0xA3, + 0xB5, 0x03, 0x7A, 0xCC, 0xB1, 0xB5, 0x04, 0xC2, + 0xA8, 0xCC, 0x80, 0xCA, 0x04, 0xC2, 0xA8, 0xCC, + 0x81, 0xCA, 0x04, 0xC2, 0xA8, 0xCD, 0x82, 0xCA, + 0x04, 0xC3, 0x86, 0xCC, 0x81, 0xC9, 0x04, 0xC3, + 0x86, 0xCC, 0x84, 0xC9, 0x04, 0xC3, 0x98, 0xCC, + // Bytes 35c0 - 35ff + 0x81, 0xC9, 0x04, 0xC3, 0xA6, 0xCC, 0x81, 0xC9, + 0x04, 0xC3, 0xA6, 0xCC, 0x84, 0xC9, 0x04, 0xC3, + 0xB8, 0xCC, 0x81, 0xC9, 0x04, 0xC5, 0xBF, 0xCC, + 0x87, 0xC9, 0x04, 0xC6, 0xB7, 0xCC, 0x8C, 0xC9, + 0x04, 0xCA, 0x92, 0xCC, 0x8C, 0xC9, 0x04, 0xCE, + 0x91, 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0x91, 0xCC, + 0x81, 0xC9, 0x04, 0xCE, 0x91, 0xCC, 0x84, 0xC9, + 0x04, 0xCE, 0x91, 0xCC, 0x86, 0xC9, 0x04, 0xCE, + // Bytes 3600 - 363f + 0x91, 0xCD, 0x85, 0xD9, 0x04, 0xCE, 0x95, 0xCC, + 0x80, 0xC9, 0x04, 0xCE, 0x95, 0xCC, 0x81, 0xC9, + 0x04, 0xCE, 0x97, 0xCC, 0x80, 0xC9, 0x04, 0xCE, + 0x97, 0xCC, 0x81, 0xC9, 0x04, 0xCE, 0x97, 0xCD, + 0x85, 0xD9, 0x04, 0xCE, 0x99, 0xCC, 0x80, 0xC9, + 0x04, 0xCE, 0x99, 0xCC, 0x81, 0xC9, 0x04, 0xCE, + 0x99, 0xCC, 0x84, 0xC9, 0x04, 0xCE, 0x99, 0xCC, + 0x86, 0xC9, 0x04, 0xCE, 0x99, 0xCC, 0x88, 0xC9, + // Bytes 3640 - 367f + 0x04, 0xCE, 0x9F, 0xCC, 0x80, 0xC9, 0x04, 0xCE, + 0x9F, 0xCC, 0x81, 0xC9, 0x04, 0xCE, 0xA1, 0xCC, + 0x94, 0xC9, 0x04, 0xCE, 0xA5, 0xCC, 0x80, 0xC9, + 0x04, 0xCE, 0xA5, 0xCC, 0x81, 0xC9, 0x04, 0xCE, + 0xA5, 0xCC, 0x84, 0xC9, 0x04, 0xCE, 0xA5, 0xCC, + 0x86, 0xC9, 0x04, 0xCE, 0xA5, 0xCC, 0x88, 0xC9, + 0x04, 0xCE, 0xA9, 0xCC, 0x80, 0xC9, 0x04, 0xCE, + 0xA9, 0xCC, 0x81, 0xC9, 0x04, 0xCE, 0xA9, 0xCD, + // Bytes 3680 - 36bf + 0x85, 0xD9, 0x04, 0xCE, 0xB1, 0xCC, 0x84, 0xC9, + 0x04, 0xCE, 0xB1, 0xCC, 0x86, 0xC9, 0x04, 0xCE, + 0xB1, 0xCD, 0x85, 0xD9, 0x04, 0xCE, 0xB5, 0xCC, + 0x80, 0xC9, 0x04, 0xCE, 0xB5, 0xCC, 0x81, 0xC9, + 0x04, 0xCE, 0xB7, 0xCD, 0x85, 0xD9, 0x04, 0xCE, + 0xB9, 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0xB9, 0xCC, + 0x81, 0xC9, 0x04, 0xCE, 0xB9, 0xCC, 0x84, 0xC9, + 0x04, 0xCE, 0xB9, 0xCC, 0x86, 0xC9, 0x04, 0xCE, + // Bytes 36c0 - 36ff + 0xB9, 0xCD, 0x82, 0xC9, 0x04, 0xCE, 0xBF, 0xCC, + 0x80, 0xC9, 0x04, 0xCE, 0xBF, 0xCC, 0x81, 0xC9, + 0x04, 0xCF, 0x81, 0xCC, 0x93, 0xC9, 0x04, 0xCF, + 0x81, 0xCC, 0x94, 0xC9, 0x04, 0xCF, 0x85, 0xCC, + 0x80, 0xC9, 0x04, 0xCF, 0x85, 0xCC, 0x81, 0xC9, + 0x04, 0xCF, 0x85, 0xCC, 0x84, 0xC9, 0x04, 0xCF, + 0x85, 0xCC, 0x86, 0xC9, 0x04, 0xCF, 0x85, 0xCD, + 0x82, 0xC9, 0x04, 0xCF, 0x89, 0xCD, 0x85, 0xD9, + // Bytes 3700 - 373f + 0x04, 0xCF, 0x92, 0xCC, 0x81, 0xC9, 0x04, 0xCF, + 0x92, 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0x86, 0xCC, + 0x88, 0xC9, 0x04, 0xD0, 0x90, 0xCC, 0x86, 0xC9, + 0x04, 0xD0, 0x90, 0xCC, 0x88, 0xC9, 0x04, 0xD0, + 0x93, 0xCC, 0x81, 0xC9, 0x04, 0xD0, 0x95, 0xCC, + 0x80, 0xC9, 0x04, 0xD0, 0x95, 0xCC, 0x86, 0xC9, + 0x04, 0xD0, 0x95, 0xCC, 0x88, 0xC9, 0x04, 0xD0, + 0x96, 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0x96, 0xCC, + // Bytes 3740 - 377f + 0x88, 0xC9, 0x04, 0xD0, 0x97, 0xCC, 0x88, 0xC9, + 0x04, 0xD0, 0x98, 0xCC, 0x80, 0xC9, 0x04, 0xD0, + 0x98, 0xCC, 0x84, 0xC9, 0x04, 0xD0, 0x98, 0xCC, + 0x86, 0xC9, 0x04, 0xD0, 0x98, 0xCC, 0x88, 0xC9, + 0x04, 0xD0, 0x9A, 0xCC, 0x81, 0xC9, 0x04, 0xD0, + 0x9E, 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0xA3, 0xCC, + 0x84, 0xC9, 0x04, 0xD0, 0xA3, 0xCC, 0x86, 0xC9, + 0x04, 0xD0, 0xA3, 0xCC, 0x88, 0xC9, 0x04, 0xD0, + // Bytes 3780 - 37bf + 0xA3, 0xCC, 0x8B, 0xC9, 0x04, 0xD0, 0xA7, 0xCC, + 0x88, 0xC9, 0x04, 0xD0, 0xAB, 0xCC, 0x88, 0xC9, + 0x04, 0xD0, 0xAD, 0xCC, 0x88, 0xC9, 0x04, 0xD0, + 0xB0, 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0xB0, 0xCC, + 0x88, 0xC9, 0x04, 0xD0, 0xB3, 0xCC, 0x81, 0xC9, + 0x04, 0xD0, 0xB5, 0xCC, 0x80, 0xC9, 0x04, 0xD0, + 0xB5, 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0xB5, 0xCC, + 0x88, 0xC9, 0x04, 0xD0, 0xB6, 0xCC, 0x86, 0xC9, + // Bytes 37c0 - 37ff + 0x04, 0xD0, 0xB6, 0xCC, 0x88, 0xC9, 0x04, 0xD0, + 0xB7, 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0xB8, 0xCC, + 0x80, 0xC9, 0x04, 0xD0, 0xB8, 0xCC, 0x84, 0xC9, + 0x04, 0xD0, 0xB8, 0xCC, 0x86, 0xC9, 0x04, 0xD0, + 0xB8, 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0xBA, 0xCC, + 0x81, 0xC9, 0x04, 0xD0, 0xBE, 0xCC, 0x88, 0xC9, + 0x04, 0xD1, 0x83, 0xCC, 0x84, 0xC9, 0x04, 0xD1, + 0x83, 0xCC, 0x86, 0xC9, 0x04, 0xD1, 0x83, 0xCC, + // Bytes 3800 - 383f + 0x88, 0xC9, 0x04, 0xD1, 0x83, 0xCC, 0x8B, 0xC9, + 0x04, 0xD1, 0x87, 0xCC, 0x88, 0xC9, 0x04, 0xD1, + 0x8B, 0xCC, 0x88, 0xC9, 0x04, 0xD1, 0x8D, 0xCC, + 0x88, 0xC9, 0x04, 0xD1, 0x96, 0xCC, 0x88, 0xC9, + 0x04, 0xD1, 0xB4, 0xCC, 0x8F, 0xC9, 0x04, 0xD1, + 0xB5, 0xCC, 0x8F, 0xC9, 0x04, 0xD3, 0x98, 0xCC, + 0x88, 0xC9, 0x04, 0xD3, 0x99, 0xCC, 0x88, 0xC9, + 0x04, 0xD3, 0xA8, 0xCC, 0x88, 0xC9, 0x04, 0xD3, + // Bytes 3840 - 387f + 0xA9, 0xCC, 0x88, 0xC9, 0x04, 0xD8, 0xA7, 0xD9, + 0x93, 0xC9, 0x04, 0xD8, 0xA7, 0xD9, 0x94, 0xC9, + 0x04, 0xD8, 0xA7, 0xD9, 0x95, 0xB5, 0x04, 0xD9, + 0x88, 0xD9, 0x94, 0xC9, 0x04, 0xD9, 0x8A, 0xD9, + 0x94, 0xC9, 0x04, 0xDB, 0x81, 0xD9, 0x94, 0xC9, + 0x04, 0xDB, 0x92, 0xD9, 0x94, 0xC9, 0x04, 0xDB, + 0x95, 0xD9, 0x94, 0xC9, 0x05, 0x41, 0xCC, 0x82, + 0xCC, 0x80, 0xCA, 0x05, 0x41, 0xCC, 0x82, 0xCC, + // Bytes 3880 - 38bf + 0x81, 0xCA, 0x05, 0x41, 0xCC, 0x82, 0xCC, 0x83, + 0xCA, 0x05, 0x41, 0xCC, 0x82, 0xCC, 0x89, 0xCA, + 0x05, 0x41, 0xCC, 0x86, 0xCC, 0x80, 0xCA, 0x05, + 0x41, 0xCC, 0x86, 0xCC, 0x81, 0xCA, 0x05, 0x41, + 0xCC, 0x86, 0xCC, 0x83, 0xCA, 0x05, 0x41, 0xCC, + 0x86, 0xCC, 0x89, 0xCA, 0x05, 0x41, 0xCC, 0x87, + 0xCC, 0x84, 0xCA, 0x05, 0x41, 0xCC, 0x88, 0xCC, + 0x84, 0xCA, 0x05, 0x41, 0xCC, 0x8A, 0xCC, 0x81, + // Bytes 38c0 - 38ff + 0xCA, 0x05, 0x41, 0xCC, 0xA3, 0xCC, 0x82, 0xCA, + 0x05, 0x41, 0xCC, 0xA3, 0xCC, 0x86, 0xCA, 0x05, + 0x43, 0xCC, 0xA7, 0xCC, 0x81, 0xCA, 0x05, 0x45, + 0xCC, 0x82, 0xCC, 0x80, 0xCA, 0x05, 0x45, 0xCC, + 0x82, 0xCC, 0x81, 0xCA, 0x05, 0x45, 0xCC, 0x82, + 0xCC, 0x83, 0xCA, 0x05, 0x45, 0xCC, 0x82, 0xCC, + 0x89, 0xCA, 0x05, 0x45, 0xCC, 0x84, 0xCC, 0x80, + 0xCA, 0x05, 0x45, 0xCC, 0x84, 0xCC, 0x81, 0xCA, + // Bytes 3900 - 393f + 0x05, 0x45, 0xCC, 0xA3, 0xCC, 0x82, 0xCA, 0x05, + 0x45, 0xCC, 0xA7, 0xCC, 0x86, 0xCA, 0x05, 0x49, + 0xCC, 0x88, 0xCC, 0x81, 0xCA, 0x05, 0x4C, 0xCC, + 0xA3, 0xCC, 0x84, 0xCA, 0x05, 0x4F, 0xCC, 0x82, + 0xCC, 0x80, 0xCA, 0x05, 0x4F, 0xCC, 0x82, 0xCC, + 0x81, 0xCA, 0x05, 0x4F, 0xCC, 0x82, 0xCC, 0x83, + 0xCA, 0x05, 0x4F, 0xCC, 0x82, 0xCC, 0x89, 0xCA, + 0x05, 0x4F, 0xCC, 0x83, 0xCC, 0x81, 0xCA, 0x05, + // Bytes 3940 - 397f + 0x4F, 0xCC, 0x83, 0xCC, 0x84, 0xCA, 0x05, 0x4F, + 0xCC, 0x83, 0xCC, 0x88, 0xCA, 0x05, 0x4F, 0xCC, + 0x84, 0xCC, 0x80, 0xCA, 0x05, 0x4F, 0xCC, 0x84, + 0xCC, 0x81, 0xCA, 0x05, 0x4F, 0xCC, 0x87, 0xCC, + 0x84, 0xCA, 0x05, 0x4F, 0xCC, 0x88, 0xCC, 0x84, + 0xCA, 0x05, 0x4F, 0xCC, 0x9B, 0xCC, 0x80, 0xCA, + 0x05, 0x4F, 0xCC, 0x9B, 0xCC, 0x81, 0xCA, 0x05, + 0x4F, 0xCC, 0x9B, 0xCC, 0x83, 0xCA, 0x05, 0x4F, + // Bytes 3980 - 39bf + 0xCC, 0x9B, 0xCC, 0x89, 0xCA, 0x05, 0x4F, 0xCC, + 0x9B, 0xCC, 0xA3, 0xB6, 0x05, 0x4F, 0xCC, 0xA3, + 0xCC, 0x82, 0xCA, 0x05, 0x4F, 0xCC, 0xA8, 0xCC, + 0x84, 0xCA, 0x05, 0x52, 0xCC, 0xA3, 0xCC, 0x84, + 0xCA, 0x05, 0x53, 0xCC, 0x81, 0xCC, 0x87, 0xCA, + 0x05, 0x53, 0xCC, 0x8C, 0xCC, 0x87, 0xCA, 0x05, + 0x53, 0xCC, 0xA3, 0xCC, 0x87, 0xCA, 0x05, 0x55, + 0xCC, 0x83, 0xCC, 0x81, 0xCA, 0x05, 0x55, 0xCC, + // Bytes 39c0 - 39ff + 0x84, 0xCC, 0x88, 0xCA, 0x05, 0x55, 0xCC, 0x88, + 0xCC, 0x80, 0xCA, 0x05, 0x55, 0xCC, 0x88, 0xCC, + 0x81, 0xCA, 0x05, 0x55, 0xCC, 0x88, 0xCC, 0x84, + 0xCA, 0x05, 0x55, 0xCC, 0x88, 0xCC, 0x8C, 0xCA, + 0x05, 0x55, 0xCC, 0x9B, 0xCC, 0x80, 0xCA, 0x05, + 0x55, 0xCC, 0x9B, 0xCC, 0x81, 0xCA, 0x05, 0x55, + 0xCC, 0x9B, 0xCC, 0x83, 0xCA, 0x05, 0x55, 0xCC, + 0x9B, 0xCC, 0x89, 0xCA, 0x05, 0x55, 0xCC, 0x9B, + // Bytes 3a00 - 3a3f + 0xCC, 0xA3, 0xB6, 0x05, 0x61, 0xCC, 0x82, 0xCC, + 0x80, 0xCA, 0x05, 0x61, 0xCC, 0x82, 0xCC, 0x81, + 0xCA, 0x05, 0x61, 0xCC, 0x82, 0xCC, 0x83, 0xCA, + 0x05, 0x61, 0xCC, 0x82, 0xCC, 0x89, 0xCA, 0x05, + 0x61, 0xCC, 0x86, 0xCC, 0x80, 0xCA, 0x05, 0x61, + 0xCC, 0x86, 0xCC, 0x81, 0xCA, 0x05, 0x61, 0xCC, + 0x86, 0xCC, 0x83, 0xCA, 0x05, 0x61, 0xCC, 0x86, + 0xCC, 0x89, 0xCA, 0x05, 0x61, 0xCC, 0x87, 0xCC, + // Bytes 3a40 - 3a7f + 0x84, 0xCA, 0x05, 0x61, 0xCC, 0x88, 0xCC, 0x84, + 0xCA, 0x05, 0x61, 0xCC, 0x8A, 0xCC, 0x81, 0xCA, + 0x05, 0x61, 0xCC, 0xA3, 0xCC, 0x82, 0xCA, 0x05, + 0x61, 0xCC, 0xA3, 0xCC, 0x86, 0xCA, 0x05, 0x63, + 0xCC, 0xA7, 0xCC, 0x81, 0xCA, 0x05, 0x65, 0xCC, + 0x82, 0xCC, 0x80, 0xCA, 0x05, 0x65, 0xCC, 0x82, + 0xCC, 0x81, 0xCA, 0x05, 0x65, 0xCC, 0x82, 0xCC, + 0x83, 0xCA, 0x05, 0x65, 0xCC, 0x82, 0xCC, 0x89, + // Bytes 3a80 - 3abf + 0xCA, 0x05, 0x65, 0xCC, 0x84, 0xCC, 0x80, 0xCA, + 0x05, 0x65, 0xCC, 0x84, 0xCC, 0x81, 0xCA, 0x05, + 0x65, 0xCC, 0xA3, 0xCC, 0x82, 0xCA, 0x05, 0x65, + 0xCC, 0xA7, 0xCC, 0x86, 0xCA, 0x05, 0x69, 0xCC, + 0x88, 0xCC, 0x81, 0xCA, 0x05, 0x6C, 0xCC, 0xA3, + 0xCC, 0x84, 0xCA, 0x05, 0x6F, 0xCC, 0x82, 0xCC, + 0x80, 0xCA, 0x05, 0x6F, 0xCC, 0x82, 0xCC, 0x81, + 0xCA, 0x05, 0x6F, 0xCC, 0x82, 0xCC, 0x83, 0xCA, + // Bytes 3ac0 - 3aff + 0x05, 0x6F, 0xCC, 0x82, 0xCC, 0x89, 0xCA, 0x05, + 0x6F, 0xCC, 0x83, 0xCC, 0x81, 0xCA, 0x05, 0x6F, + 0xCC, 0x83, 0xCC, 0x84, 0xCA, 0x05, 0x6F, 0xCC, + 0x83, 0xCC, 0x88, 0xCA, 0x05, 0x6F, 0xCC, 0x84, + 0xCC, 0x80, 0xCA, 0x05, 0x6F, 0xCC, 0x84, 0xCC, + 0x81, 0xCA, 0x05, 0x6F, 0xCC, 0x87, 0xCC, 0x84, + 0xCA, 0x05, 0x6F, 0xCC, 0x88, 0xCC, 0x84, 0xCA, + 0x05, 0x6F, 0xCC, 0x9B, 0xCC, 0x80, 0xCA, 0x05, + // Bytes 3b00 - 3b3f + 0x6F, 0xCC, 0x9B, 0xCC, 0x81, 0xCA, 0x05, 0x6F, + 0xCC, 0x9B, 0xCC, 0x83, 0xCA, 0x05, 0x6F, 0xCC, + 0x9B, 0xCC, 0x89, 0xCA, 0x05, 0x6F, 0xCC, 0x9B, + 0xCC, 0xA3, 0xB6, 0x05, 0x6F, 0xCC, 0xA3, 0xCC, + 0x82, 0xCA, 0x05, 0x6F, 0xCC, 0xA8, 0xCC, 0x84, + 0xCA, 0x05, 0x72, 0xCC, 0xA3, 0xCC, 0x84, 0xCA, + 0x05, 0x73, 0xCC, 0x81, 0xCC, 0x87, 0xCA, 0x05, + 0x73, 0xCC, 0x8C, 0xCC, 0x87, 0xCA, 0x05, 0x73, + // Bytes 3b40 - 3b7f + 0xCC, 0xA3, 0xCC, 0x87, 0xCA, 0x05, 0x75, 0xCC, + 0x83, 0xCC, 0x81, 0xCA, 0x05, 0x75, 0xCC, 0x84, + 0xCC, 0x88, 0xCA, 0x05, 0x75, 0xCC, 0x88, 0xCC, + 0x80, 0xCA, 0x05, 0x75, 0xCC, 0x88, 0xCC, 0x81, + 0xCA, 0x05, 0x75, 0xCC, 0x88, 0xCC, 0x84, 0xCA, + 0x05, 0x75, 0xCC, 0x88, 0xCC, 0x8C, 0xCA, 0x05, + 0x75, 0xCC, 0x9B, 0xCC, 0x80, 0xCA, 0x05, 0x75, + 0xCC, 0x9B, 0xCC, 0x81, 0xCA, 0x05, 0x75, 0xCC, + // Bytes 3b80 - 3bbf + 0x9B, 0xCC, 0x83, 0xCA, 0x05, 0x75, 0xCC, 0x9B, + 0xCC, 0x89, 0xCA, 0x05, 0x75, 0xCC, 0x9B, 0xCC, + 0xA3, 0xB6, 0x05, 0xE1, 0xBE, 0xBF, 0xCC, 0x80, + 0xCA, 0x05, 0xE1, 0xBE, 0xBF, 0xCC, 0x81, 0xCA, + 0x05, 0xE1, 0xBE, 0xBF, 0xCD, 0x82, 0xCA, 0x05, + 0xE1, 0xBF, 0xBE, 0xCC, 0x80, 0xCA, 0x05, 0xE1, + 0xBF, 0xBE, 0xCC, 0x81, 0xCA, 0x05, 0xE1, 0xBF, + 0xBE, 0xCD, 0x82, 0xCA, 0x05, 0xE2, 0x86, 0x90, + // Bytes 3bc0 - 3bff + 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x86, 0x92, 0xCC, + 0xB8, 0x05, 0x05, 0xE2, 0x86, 0x94, 0xCC, 0xB8, + 0x05, 0x05, 0xE2, 0x87, 0x90, 0xCC, 0xB8, 0x05, + 0x05, 0xE2, 0x87, 0x92, 0xCC, 0xB8, 0x05, 0x05, + 0xE2, 0x87, 0x94, 0xCC, 0xB8, 0x05, 0x05, 0xE2, + 0x88, 0x83, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x88, + 0x88, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x88, 0x8B, + 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x88, 0xA3, 0xCC, + // Bytes 3c00 - 3c3f + 0xB8, 0x05, 0x05, 0xE2, 0x88, 0xA5, 0xCC, 0xB8, + 0x05, 0x05, 0xE2, 0x88, 0xBC, 0xCC, 0xB8, 0x05, + 0x05, 0xE2, 0x89, 0x83, 0xCC, 0xB8, 0x05, 0x05, + 0xE2, 0x89, 0x85, 0xCC, 0xB8, 0x05, 0x05, 0xE2, + 0x89, 0x88, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, + 0x8D, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xA1, + 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xA4, 0xCC, + 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xA5, 0xCC, 0xB8, + // Bytes 3c40 - 3c7f + 0x05, 0x05, 0xE2, 0x89, 0xB2, 0xCC, 0xB8, 0x05, + 0x05, 0xE2, 0x89, 0xB3, 0xCC, 0xB8, 0x05, 0x05, + 0xE2, 0x89, 0xB6, 0xCC, 0xB8, 0x05, 0x05, 0xE2, + 0x89, 0xB7, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, + 0xBA, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xBB, + 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xBC, 0xCC, + 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xBD, 0xCC, 0xB8, + 0x05, 0x05, 0xE2, 0x8A, 0x82, 0xCC, 0xB8, 0x05, + // Bytes 3c80 - 3cbf + 0x05, 0xE2, 0x8A, 0x83, 0xCC, 0xB8, 0x05, 0x05, + 0xE2, 0x8A, 0x86, 0xCC, 0xB8, 0x05, 0x05, 0xE2, + 0x8A, 0x87, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, + 0x91, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0x92, + 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0xA2, 0xCC, + 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0xA8, 0xCC, 0xB8, + 0x05, 0x05, 0xE2, 0x8A, 0xA9, 0xCC, 0xB8, 0x05, + 0x05, 0xE2, 0x8A, 0xAB, 0xCC, 0xB8, 0x05, 0x05, + // Bytes 3cc0 - 3cff + 0xE2, 0x8A, 0xB2, 0xCC, 0xB8, 0x05, 0x05, 0xE2, + 0x8A, 0xB3, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, + 0xB4, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0xB5, + 0xCC, 0xB8, 0x05, 0x06, 0xCE, 0x91, 0xCC, 0x93, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0x91, 0xCC, 0x94, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0x95, 0xCC, 0x93, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0x95, 0xCC, 0x93, + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0x95, 0xCC, 0x94, + // Bytes 3d00 - 3d3f + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0x95, 0xCC, 0x94, + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0x97, 0xCC, 0x93, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0x97, 0xCC, 0x94, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0x99, 0xCC, 0x93, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0x99, 0xCC, 0x93, + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0x99, 0xCC, 0x93, + 0xCD, 0x82, 0xCA, 0x06, 0xCE, 0x99, 0xCC, 0x94, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0x99, 0xCC, 0x94, + // Bytes 3d40 - 3d7f + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0x99, 0xCC, 0x94, + 0xCD, 0x82, 0xCA, 0x06, 0xCE, 0x9F, 0xCC, 0x93, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0x9F, 0xCC, 0x93, + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0x9F, 0xCC, 0x94, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0x9F, 0xCC, 0x94, + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0xA5, 0xCC, 0x94, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0xA5, 0xCC, 0x94, + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0xA5, 0xCC, 0x94, + // Bytes 3d80 - 3dbf + 0xCD, 0x82, 0xCA, 0x06, 0xCE, 0xA9, 0xCC, 0x93, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xA9, 0xCC, 0x94, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xB1, 0xCC, 0x80, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xB1, 0xCC, 0x81, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xB1, 0xCC, 0x93, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xB1, 0xCC, 0x94, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xB1, 0xCD, 0x82, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xB5, 0xCC, 0x93, + // Bytes 3dc0 - 3dff + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0xB5, 0xCC, 0x93, + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0xB5, 0xCC, 0x94, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0xB5, 0xCC, 0x94, + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0xB7, 0xCC, 0x80, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xB7, 0xCC, 0x81, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xB7, 0xCC, 0x93, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xB7, 0xCC, 0x94, + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xB7, 0xCD, 0x82, + // Bytes 3e00 - 3e3f + 0xCD, 0x85, 0xDA, 0x06, 0xCE, 0xB9, 0xCC, 0x88, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0xB9, 0xCC, 0x88, + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0xB9, 0xCC, 0x88, + 0xCD, 0x82, 0xCA, 0x06, 0xCE, 0xB9, 0xCC, 0x93, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0xB9, 0xCC, 0x93, + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0xB9, 0xCC, 0x93, + 0xCD, 0x82, 0xCA, 0x06, 0xCE, 0xB9, 0xCC, 0x94, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0xB9, 0xCC, 0x94, + // Bytes 3e40 - 3e7f + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0xB9, 0xCC, 0x94, + 0xCD, 0x82, 0xCA, 0x06, 0xCE, 0xBF, 0xCC, 0x93, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0xBF, 0xCC, 0x93, + 0xCC, 0x81, 0xCA, 0x06, 0xCE, 0xBF, 0xCC, 0x94, + 0xCC, 0x80, 0xCA, 0x06, 0xCE, 0xBF, 0xCC, 0x94, + 0xCC, 0x81, 0xCA, 0x06, 0xCF, 0x85, 0xCC, 0x88, + 0xCC, 0x80, 0xCA, 0x06, 0xCF, 0x85, 0xCC, 0x88, + 0xCC, 0x81, 0xCA, 0x06, 0xCF, 0x85, 0xCC, 0x88, + // Bytes 3e80 - 3ebf + 0xCD, 0x82, 0xCA, 0x06, 0xCF, 0x85, 0xCC, 0x93, + 0xCC, 0x80, 0xCA, 0x06, 0xCF, 0x85, 0xCC, 0x93, + 0xCC, 0x81, 0xCA, 0x06, 0xCF, 0x85, 0xCC, 0x93, + 0xCD, 0x82, 0xCA, 0x06, 0xCF, 0x85, 0xCC, 0x94, + 0xCC, 0x80, 0xCA, 0x06, 0xCF, 0x85, 0xCC, 0x94, + 0xCC, 0x81, 0xCA, 0x06, 0xCF, 0x85, 0xCC, 0x94, + 0xCD, 0x82, 0xCA, 0x06, 0xCF, 0x89, 0xCC, 0x80, + 0xCD, 0x85, 0xDA, 0x06, 0xCF, 0x89, 0xCC, 0x81, + // Bytes 3ec0 - 3eff + 0xCD, 0x85, 0xDA, 0x06, 0xCF, 0x89, 0xCC, 0x93, + 0xCD, 0x85, 0xDA, 0x06, 0xCF, 0x89, 0xCC, 0x94, + 0xCD, 0x85, 0xDA, 0x06, 0xCF, 0x89, 0xCD, 0x82, + 0xCD, 0x85, 0xDA, 0x06, 0xE0, 0xA4, 0xA8, 0xE0, + 0xA4, 0xBC, 0x09, 0x06, 0xE0, 0xA4, 0xB0, 0xE0, + 0xA4, 0xBC, 0x09, 0x06, 0xE0, 0xA4, 0xB3, 0xE0, + 0xA4, 0xBC, 0x09, 0x06, 0xE0, 0xB1, 0x86, 0xE0, + 0xB1, 0x96, 0x85, 0x06, 0xE0, 0xB7, 0x99, 0xE0, + // Bytes 3f00 - 3f3f + 0xB7, 0x8A, 0x11, 0x06, 0xE3, 0x81, 0x86, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0x8B, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0x8D, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0x8F, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0x91, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0x93, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0x95, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0x97, 0xE3, + // Bytes 3f40 - 3f7f + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0x99, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0x9B, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0x9D, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0x9F, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0xA1, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0xA4, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0xA6, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0xA8, 0xE3, + // Bytes 3f80 - 3fbf + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0xAF, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0xAF, 0xE3, + 0x82, 0x9A, 0x0D, 0x06, 0xE3, 0x81, 0xB2, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0xB2, 0xE3, + 0x82, 0x9A, 0x0D, 0x06, 0xE3, 0x81, 0xB5, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0xB5, 0xE3, + 0x82, 0x9A, 0x0D, 0x06, 0xE3, 0x81, 0xB8, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0xB8, 0xE3, + // Bytes 3fc0 - 3fff + 0x82, 0x9A, 0x0D, 0x06, 0xE3, 0x81, 0xBB, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x81, 0xBB, 0xE3, + 0x82, 0x9A, 0x0D, 0x06, 0xE3, 0x82, 0x9D, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xA6, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xAB, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xAD, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xAF, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xB1, 0xE3, + // Bytes 4000 - 403f + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xB3, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xB5, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xB7, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xB9, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xBB, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xBD, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x82, 0xBF, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0x81, 0xE3, + // Bytes 4040 - 407f + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0x84, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0x86, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0x88, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0x8F, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0x8F, 0xE3, + 0x82, 0x9A, 0x0D, 0x06, 0xE3, 0x83, 0x92, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0x92, 0xE3, + 0x82, 0x9A, 0x0D, 0x06, 0xE3, 0x83, 0x95, 0xE3, + // Bytes 4080 - 40bf + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0x95, 0xE3, + 0x82, 0x9A, 0x0D, 0x06, 0xE3, 0x83, 0x98, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0x98, 0xE3, + 0x82, 0x9A, 0x0D, 0x06, 0xE3, 0x83, 0x9B, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0x9B, 0xE3, + 0x82, 0x9A, 0x0D, 0x06, 0xE3, 0x83, 0xAF, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0xB0, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0xB1, 0xE3, + // Bytes 40c0 - 40ff + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0xB2, 0xE3, + 0x82, 0x99, 0x0D, 0x06, 0xE3, 0x83, 0xBD, 0xE3, + 0x82, 0x99, 0x0D, 0x08, 0xCE, 0x91, 0xCC, 0x93, + 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0x91, + 0xCC, 0x93, 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, + 0xCE, 0x91, 0xCC, 0x93, 0xCD, 0x82, 0xCD, 0x85, + 0xDB, 0x08, 0xCE, 0x91, 0xCC, 0x94, 0xCC, 0x80, + 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0x91, 0xCC, 0x94, + // Bytes 4100 - 413f + 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0x91, + 0xCC, 0x94, 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, + 0xCE, 0x97, 0xCC, 0x93, 0xCC, 0x80, 0xCD, 0x85, + 0xDB, 0x08, 0xCE, 0x97, 0xCC, 0x93, 0xCC, 0x81, + 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0x97, 0xCC, 0x93, + 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0x97, + 0xCC, 0x94, 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, + 0xCE, 0x97, 0xCC, 0x94, 0xCC, 0x81, 0xCD, 0x85, + // Bytes 4140 - 417f + 0xDB, 0x08, 0xCE, 0x97, 0xCC, 0x94, 0xCD, 0x82, + 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xA9, 0xCC, 0x93, + 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xA9, + 0xCC, 0x93, 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, + 0xCE, 0xA9, 0xCC, 0x93, 0xCD, 0x82, 0xCD, 0x85, + 0xDB, 0x08, 0xCE, 0xA9, 0xCC, 0x94, 0xCC, 0x80, + 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xA9, 0xCC, 0x94, + 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xA9, + // Bytes 4180 - 41bf + 0xCC, 0x94, 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, + 0xCE, 0xB1, 0xCC, 0x93, 0xCC, 0x80, 0xCD, 0x85, + 0xDB, 0x08, 0xCE, 0xB1, 0xCC, 0x93, 0xCC, 0x81, + 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB1, 0xCC, 0x93, + 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB1, + 0xCC, 0x94, 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, + 0xCE, 0xB1, 0xCC, 0x94, 0xCC, 0x81, 0xCD, 0x85, + 0xDB, 0x08, 0xCE, 0xB1, 0xCC, 0x94, 0xCD, 0x82, + // Bytes 41c0 - 41ff + 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB7, 0xCC, 0x93, + 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB7, + 0xCC, 0x93, 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, + 0xCE, 0xB7, 0xCC, 0x93, 0xCD, 0x82, 0xCD, 0x85, + 0xDB, 0x08, 0xCE, 0xB7, 0xCC, 0x94, 0xCC, 0x80, + 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB7, 0xCC, 0x94, + 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB7, + 0xCC, 0x94, 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, + // Bytes 4200 - 423f + 0xCF, 0x89, 0xCC, 0x93, 0xCC, 0x80, 0xCD, 0x85, + 0xDB, 0x08, 0xCF, 0x89, 0xCC, 0x93, 0xCC, 0x81, + 0xCD, 0x85, 0xDB, 0x08, 0xCF, 0x89, 0xCC, 0x93, + 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCF, 0x89, + 0xCC, 0x94, 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, + 0xCF, 0x89, 0xCC, 0x94, 0xCC, 0x81, 0xCD, 0x85, + 0xDB, 0x08, 0xCF, 0x89, 0xCC, 0x94, 0xCD, 0x82, + 0xCD, 0x85, 0xDB, 0x08, 0xF0, 0x91, 0x82, 0x99, + // Bytes 4240 - 427f + 0xF0, 0x91, 0x82, 0xBA, 0x09, 0x08, 0xF0, 0x91, + 0x82, 0x9B, 0xF0, 0x91, 0x82, 0xBA, 0x09, 0x08, + 0xF0, 0x91, 0x82, 0xA5, 0xF0, 0x91, 0x82, 0xBA, + 0x09, 0x42, 0xC2, 0xB4, 0x01, 0x43, 0x20, 0xCC, + 0x81, 0xC9, 0x43, 0x20, 0xCC, 0x83, 0xC9, 0x43, + 0x20, 0xCC, 0x84, 0xC9, 0x43, 0x20, 0xCC, 0x85, + 0xC9, 0x43, 0x20, 0xCC, 0x86, 0xC9, 0x43, 0x20, + 0xCC, 0x87, 0xC9, 0x43, 0x20, 0xCC, 0x88, 0xC9, + // Bytes 4280 - 42bf + 0x43, 0x20, 0xCC, 0x8A, 0xC9, 0x43, 0x20, 0xCC, + 0x8B, 0xC9, 0x43, 0x20, 0xCC, 0x93, 0xC9, 0x43, + 0x20, 0xCC, 0x94, 0xC9, 0x43, 0x20, 0xCC, 0xA7, + 0xA5, 0x43, 0x20, 0xCC, 0xA8, 0xA5, 0x43, 0x20, + 0xCC, 0xB3, 0xB5, 0x43, 0x20, 0xCD, 0x82, 0xC9, + 0x43, 0x20, 0xCD, 0x85, 0xD9, 0x43, 0x20, 0xD9, + 0x8B, 0x59, 0x43, 0x20, 0xD9, 0x8C, 0x5D, 0x43, + 0x20, 0xD9, 0x8D, 0x61, 0x43, 0x20, 0xD9, 0x8E, + // Bytes 42c0 - 42ff + 0x65, 0x43, 0x20, 0xD9, 0x8F, 0x69, 0x43, 0x20, + 0xD9, 0x90, 0x6D, 0x43, 0x20, 0xD9, 0x91, 0x71, + 0x43, 0x20, 0xD9, 0x92, 0x75, 0x43, 0x41, 0xCC, + 0x8A, 0xC9, 0x43, 0x73, 0xCC, 0x87, 0xC9, 0x44, + 0x20, 0xE3, 0x82, 0x99, 0x0D, 0x44, 0x20, 0xE3, + 0x82, 0x9A, 0x0D, 0x44, 0xC2, 0xA8, 0xCC, 0x81, + 0xCA, 0x44, 0xCE, 0x91, 0xCC, 0x81, 0xC9, 0x44, + 0xCE, 0x95, 0xCC, 0x81, 0xC9, 0x44, 0xCE, 0x97, + // Bytes 4300 - 433f + 0xCC, 0x81, 0xC9, 0x44, 0xCE, 0x99, 0xCC, 0x81, + 0xC9, 0x44, 0xCE, 0x9F, 0xCC, 0x81, 0xC9, 0x44, + 0xCE, 0xA5, 0xCC, 0x81, 0xC9, 0x44, 0xCE, 0xA5, + 0xCC, 0x88, 0xC9, 0x44, 0xCE, 0xA9, 0xCC, 0x81, + 0xC9, 0x44, 0xCE, 0xB1, 0xCC, 0x81, 0xC9, 0x44, + 0xCE, 0xB5, 0xCC, 0x81, 0xC9, 0x44, 0xCE, 0xB7, + 0xCC, 0x81, 0xC9, 0x44, 0xCE, 0xB9, 0xCC, 0x81, + 0xC9, 0x44, 0xCE, 0xBF, 0xCC, 0x81, 0xC9, 0x44, + // Bytes 4340 - 437f + 0xCF, 0x85, 0xCC, 0x81, 0xC9, 0x44, 0xCF, 0x89, + 0xCC, 0x81, 0xC9, 0x44, 0xD7, 0x90, 0xD6, 0xB7, + 0x31, 0x44, 0xD7, 0x90, 0xD6, 0xB8, 0x35, 0x44, + 0xD7, 0x90, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x91, + 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x91, 0xD6, 0xBF, + 0x49, 0x44, 0xD7, 0x92, 0xD6, 0xBC, 0x41, 0x44, + 0xD7, 0x93, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x94, + 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x95, 0xD6, 0xB9, + // Bytes 4380 - 43bf + 0x39, 0x44, 0xD7, 0x95, 0xD6, 0xBC, 0x41, 0x44, + 0xD7, 0x96, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x98, + 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x99, 0xD6, 0xB4, + 0x25, 0x44, 0xD7, 0x99, 0xD6, 0xBC, 0x41, 0x44, + 0xD7, 0x9A, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x9B, + 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x9B, 0xD6, 0xBF, + 0x49, 0x44, 0xD7, 0x9C, 0xD6, 0xBC, 0x41, 0x44, + 0xD7, 0x9E, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0xA0, + // Bytes 43c0 - 43ff + 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0xA1, 0xD6, 0xBC, + 0x41, 0x44, 0xD7, 0xA3, 0xD6, 0xBC, 0x41, 0x44, + 0xD7, 0xA4, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0xA4, + 0xD6, 0xBF, 0x49, 0x44, 0xD7, 0xA6, 0xD6, 0xBC, + 0x41, 0x44, 0xD7, 0xA7, 0xD6, 0xBC, 0x41, 0x44, + 0xD7, 0xA8, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0xA9, + 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0xA9, 0xD7, 0x81, + 0x4D, 0x44, 0xD7, 0xA9, 0xD7, 0x82, 0x51, 0x44, + // Bytes 4400 - 443f + 0xD7, 0xAA, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0xB2, + 0xD6, 0xB7, 0x31, 0x44, 0xD8, 0xA7, 0xD9, 0x8B, + 0x59, 0x44, 0xD8, 0xA7, 0xD9, 0x93, 0xC9, 0x44, + 0xD8, 0xA7, 0xD9, 0x94, 0xC9, 0x44, 0xD8, 0xA7, + 0xD9, 0x95, 0xB5, 0x44, 0xD8, 0xB0, 0xD9, 0xB0, + 0x79, 0x44, 0xD8, 0xB1, 0xD9, 0xB0, 0x79, 0x44, + 0xD9, 0x80, 0xD9, 0x8B, 0x59, 0x44, 0xD9, 0x80, + 0xD9, 0x8E, 0x65, 0x44, 0xD9, 0x80, 0xD9, 0x8F, + // Bytes 4440 - 447f + 0x69, 0x44, 0xD9, 0x80, 0xD9, 0x90, 0x6D, 0x44, + 0xD9, 0x80, 0xD9, 0x91, 0x71, 0x44, 0xD9, 0x80, + 0xD9, 0x92, 0x75, 0x44, 0xD9, 0x87, 0xD9, 0xB0, + 0x79, 0x44, 0xD9, 0x88, 0xD9, 0x94, 0xC9, 0x44, + 0xD9, 0x89, 0xD9, 0xB0, 0x79, 0x44, 0xD9, 0x8A, + 0xD9, 0x94, 0xC9, 0x44, 0xDB, 0x92, 0xD9, 0x94, + 0xC9, 0x44, 0xDB, 0x95, 0xD9, 0x94, 0xC9, 0x45, + 0x20, 0xCC, 0x88, 0xCC, 0x80, 0xCA, 0x45, 0x20, + // Bytes 4480 - 44bf + 0xCC, 0x88, 0xCC, 0x81, 0xCA, 0x45, 0x20, 0xCC, + 0x88, 0xCD, 0x82, 0xCA, 0x45, 0x20, 0xCC, 0x93, + 0xCC, 0x80, 0xCA, 0x45, 0x20, 0xCC, 0x93, 0xCC, + 0x81, 0xCA, 0x45, 0x20, 0xCC, 0x93, 0xCD, 0x82, + 0xCA, 0x45, 0x20, 0xCC, 0x94, 0xCC, 0x80, 0xCA, + 0x45, 0x20, 0xCC, 0x94, 0xCC, 0x81, 0xCA, 0x45, + 0x20, 0xCC, 0x94, 0xCD, 0x82, 0xCA, 0x45, 0x20, + 0xD9, 0x8C, 0xD9, 0x91, 0x72, 0x45, 0x20, 0xD9, + // Bytes 44c0 - 44ff + 0x8D, 0xD9, 0x91, 0x72, 0x45, 0x20, 0xD9, 0x8E, + 0xD9, 0x91, 0x72, 0x45, 0x20, 0xD9, 0x8F, 0xD9, + 0x91, 0x72, 0x45, 0x20, 0xD9, 0x90, 0xD9, 0x91, + 0x72, 0x45, 0x20, 0xD9, 0x91, 0xD9, 0xB0, 0x7A, + 0x45, 0xE2, 0xAB, 0x9D, 0xCC, 0xB8, 0x05, 0x46, + 0xCE, 0xB9, 0xCC, 0x88, 0xCC, 0x81, 0xCA, 0x46, + 0xCF, 0x85, 0xCC, 0x88, 0xCC, 0x81, 0xCA, 0x46, + 0xD7, 0xA9, 0xD6, 0xBC, 0xD7, 0x81, 0x4E, 0x46, + // Bytes 4500 - 453f + 0xD7, 0xA9, 0xD6, 0xBC, 0xD7, 0x82, 0x52, 0x46, + 0xD9, 0x80, 0xD9, 0x8E, 0xD9, 0x91, 0x72, 0x46, + 0xD9, 0x80, 0xD9, 0x8F, 0xD9, 0x91, 0x72, 0x46, + 0xD9, 0x80, 0xD9, 0x90, 0xD9, 0x91, 0x72, 0x46, + 0xE0, 0xA4, 0x95, 0xE0, 0xA4, 0xBC, 0x09, 0x46, + 0xE0, 0xA4, 0x96, 0xE0, 0xA4, 0xBC, 0x09, 0x46, + 0xE0, 0xA4, 0x97, 0xE0, 0xA4, 0xBC, 0x09, 0x46, + 0xE0, 0xA4, 0x9C, 0xE0, 0xA4, 0xBC, 0x09, 0x46, + // Bytes 4540 - 457f + 0xE0, 0xA4, 0xA1, 0xE0, 0xA4, 0xBC, 0x09, 0x46, + 0xE0, 0xA4, 0xA2, 0xE0, 0xA4, 0xBC, 0x09, 0x46, + 0xE0, 0xA4, 0xAB, 0xE0, 0xA4, 0xBC, 0x09, 0x46, + 0xE0, 0xA4, 0xAF, 0xE0, 0xA4, 0xBC, 0x09, 0x46, + 0xE0, 0xA6, 0xA1, 0xE0, 0xA6, 0xBC, 0x09, 0x46, + 0xE0, 0xA6, 0xA2, 0xE0, 0xA6, 0xBC, 0x09, 0x46, + 0xE0, 0xA6, 0xAF, 0xE0, 0xA6, 0xBC, 0x09, 0x46, + 0xE0, 0xA8, 0x96, 0xE0, 0xA8, 0xBC, 0x09, 0x46, + // Bytes 4580 - 45bf + 0xE0, 0xA8, 0x97, 0xE0, 0xA8, 0xBC, 0x09, 0x46, + 0xE0, 0xA8, 0x9C, 0xE0, 0xA8, 0xBC, 0x09, 0x46, + 0xE0, 0xA8, 0xAB, 0xE0, 0xA8, 0xBC, 0x09, 0x46, + 0xE0, 0xA8, 0xB2, 0xE0, 0xA8, 0xBC, 0x09, 0x46, + 0xE0, 0xA8, 0xB8, 0xE0, 0xA8, 0xBC, 0x09, 0x46, + 0xE0, 0xAC, 0xA1, 0xE0, 0xAC, 0xBC, 0x09, 0x46, + 0xE0, 0xAC, 0xA2, 0xE0, 0xAC, 0xBC, 0x09, 0x46, + 0xE0, 0xBE, 0xB2, 0xE0, 0xBE, 0x80, 0x9D, 0x46, + // Bytes 45c0 - 45ff + 0xE0, 0xBE, 0xB3, 0xE0, 0xBE, 0x80, 0x9D, 0x46, + 0xE3, 0x83, 0x86, 0xE3, 0x82, 0x99, 0x0D, 0x48, + 0xF0, 0x9D, 0x85, 0x97, 0xF0, 0x9D, 0x85, 0xA5, + 0xAD, 0x48, 0xF0, 0x9D, 0x85, 0x98, 0xF0, 0x9D, + 0x85, 0xA5, 0xAD, 0x48, 0xF0, 0x9D, 0x86, 0xB9, + 0xF0, 0x9D, 0x85, 0xA5, 0xAD, 0x48, 0xF0, 0x9D, + 0x86, 0xBA, 0xF0, 0x9D, 0x85, 0xA5, 0xAD, 0x49, + 0xE0, 0xBE, 0xB2, 0xE0, 0xBD, 0xB1, 0xE0, 0xBE, + // Bytes 4600 - 463f + 0x80, 0x9E, 0x49, 0xE0, 0xBE, 0xB3, 0xE0, 0xBD, + 0xB1, 0xE0, 0xBE, 0x80, 0x9E, 0x4C, 0xF0, 0x9D, + 0x85, 0x98, 0xF0, 0x9D, 0x85, 0xA5, 0xF0, 0x9D, + 0x85, 0xAE, 0xAE, 0x4C, 0xF0, 0x9D, 0x85, 0x98, + 0xF0, 0x9D, 0x85, 0xA5, 0xF0, 0x9D, 0x85, 0xAF, + 0xAE, 0x4C, 0xF0, 0x9D, 0x85, 0x98, 0xF0, 0x9D, + 0x85, 0xA5, 0xF0, 0x9D, 0x85, 0xB0, 0xAE, 0x4C, + 0xF0, 0x9D, 0x85, 0x98, 0xF0, 0x9D, 0x85, 0xA5, + // Bytes 4640 - 467f + 0xF0, 0x9D, 0x85, 0xB1, 0xAE, 0x4C, 0xF0, 0x9D, + 0x85, 0x98, 0xF0, 0x9D, 0x85, 0xA5, 0xF0, 0x9D, + 0x85, 0xB2, 0xAE, 0x4C, 0xF0, 0x9D, 0x86, 0xB9, + 0xF0, 0x9D, 0x85, 0xA5, 0xF0, 0x9D, 0x85, 0xAE, + 0xAE, 0x4C, 0xF0, 0x9D, 0x86, 0xB9, 0xF0, 0x9D, + 0x85, 0xA5, 0xF0, 0x9D, 0x85, 0xAF, 0xAE, 0x4C, + 0xF0, 0x9D, 0x86, 0xBA, 0xF0, 0x9D, 0x85, 0xA5, + 0xF0, 0x9D, 0x85, 0xAE, 0xAE, 0x4C, 0xF0, 0x9D, + // Bytes 4680 - 46bf + 0x86, 0xBA, 0xF0, 0x9D, 0x85, 0xA5, 0xF0, 0x9D, + 0x85, 0xAF, 0xAE, 0x83, 0x41, 0xCC, 0x82, 0xC9, + 0x83, 0x41, 0xCC, 0x86, 0xC9, 0x83, 0x41, 0xCC, + 0x87, 0xC9, 0x83, 0x41, 0xCC, 0x88, 0xC9, 0x83, + 0x41, 0xCC, 0x8A, 0xC9, 0x83, 0x41, 0xCC, 0xA3, + 0xB5, 0x83, 0x43, 0xCC, 0xA7, 0xA5, 0x83, 0x45, + 0xCC, 0x82, 0xC9, 0x83, 0x45, 0xCC, 0x84, 0xC9, + 0x83, 0x45, 0xCC, 0xA3, 0xB5, 0x83, 0x45, 0xCC, + // Bytes 46c0 - 46ff + 0xA7, 0xA5, 0x83, 0x49, 0xCC, 0x88, 0xC9, 0x83, + 0x4C, 0xCC, 0xA3, 0xB5, 0x83, 0x4F, 0xCC, 0x82, + 0xC9, 0x83, 0x4F, 0xCC, 0x83, 0xC9, 0x83, 0x4F, + 0xCC, 0x84, 0xC9, 0x83, 0x4F, 0xCC, 0x87, 0xC9, + 0x83, 0x4F, 0xCC, 0x88, 0xC9, 0x83, 0x4F, 0xCC, + 0x9B, 0xAD, 0x83, 0x4F, 0xCC, 0xA3, 0xB5, 0x83, + 0x4F, 0xCC, 0xA8, 0xA5, 0x83, 0x52, 0xCC, 0xA3, + 0xB5, 0x83, 0x53, 0xCC, 0x81, 0xC9, 0x83, 0x53, + // Bytes 4700 - 473f + 0xCC, 0x8C, 0xC9, 0x83, 0x53, 0xCC, 0xA3, 0xB5, + 0x83, 0x55, 0xCC, 0x83, 0xC9, 0x83, 0x55, 0xCC, + 0x84, 0xC9, 0x83, 0x55, 0xCC, 0x88, 0xC9, 0x83, + 0x55, 0xCC, 0x9B, 0xAD, 0x83, 0x61, 0xCC, 0x82, + 0xC9, 0x83, 0x61, 0xCC, 0x86, 0xC9, 0x83, 0x61, + 0xCC, 0x87, 0xC9, 0x83, 0x61, 0xCC, 0x88, 0xC9, + 0x83, 0x61, 0xCC, 0x8A, 0xC9, 0x83, 0x61, 0xCC, + 0xA3, 0xB5, 0x83, 0x63, 0xCC, 0xA7, 0xA5, 0x83, + // Bytes 4740 - 477f + 0x65, 0xCC, 0x82, 0xC9, 0x83, 0x65, 0xCC, 0x84, + 0xC9, 0x83, 0x65, 0xCC, 0xA3, 0xB5, 0x83, 0x65, + 0xCC, 0xA7, 0xA5, 0x83, 0x69, 0xCC, 0x88, 0xC9, + 0x83, 0x6C, 0xCC, 0xA3, 0xB5, 0x83, 0x6F, 0xCC, + 0x82, 0xC9, 0x83, 0x6F, 0xCC, 0x83, 0xC9, 0x83, + 0x6F, 0xCC, 0x84, 0xC9, 0x83, 0x6F, 0xCC, 0x87, + 0xC9, 0x83, 0x6F, 0xCC, 0x88, 0xC9, 0x83, 0x6F, + 0xCC, 0x9B, 0xAD, 0x83, 0x6F, 0xCC, 0xA3, 0xB5, + // Bytes 4780 - 47bf + 0x83, 0x6F, 0xCC, 0xA8, 0xA5, 0x83, 0x72, 0xCC, + 0xA3, 0xB5, 0x83, 0x73, 0xCC, 0x81, 0xC9, 0x83, + 0x73, 0xCC, 0x8C, 0xC9, 0x83, 0x73, 0xCC, 0xA3, + 0xB5, 0x83, 0x75, 0xCC, 0x83, 0xC9, 0x83, 0x75, + 0xCC, 0x84, 0xC9, 0x83, 0x75, 0xCC, 0x88, 0xC9, + 0x83, 0x75, 0xCC, 0x9B, 0xAD, 0x84, 0xCE, 0x91, + 0xCC, 0x93, 0xC9, 0x84, 0xCE, 0x91, 0xCC, 0x94, + 0xC9, 0x84, 0xCE, 0x95, 0xCC, 0x93, 0xC9, 0x84, + // Bytes 47c0 - 47ff + 0xCE, 0x95, 0xCC, 0x94, 0xC9, 0x84, 0xCE, 0x97, + 0xCC, 0x93, 0xC9, 0x84, 0xCE, 0x97, 0xCC, 0x94, + 0xC9, 0x84, 0xCE, 0x99, 0xCC, 0x93, 0xC9, 0x84, + 0xCE, 0x99, 0xCC, 0x94, 0xC9, 0x84, 0xCE, 0x9F, + 0xCC, 0x93, 0xC9, 0x84, 0xCE, 0x9F, 0xCC, 0x94, + 0xC9, 0x84, 0xCE, 0xA5, 0xCC, 0x94, 0xC9, 0x84, + 0xCE, 0xA9, 0xCC, 0x93, 0xC9, 0x84, 0xCE, 0xA9, + 0xCC, 0x94, 0xC9, 0x84, 0xCE, 0xB1, 0xCC, 0x80, + // Bytes 4800 - 483f + 0xC9, 0x84, 0xCE, 0xB1, 0xCC, 0x81, 0xC9, 0x84, + 0xCE, 0xB1, 0xCC, 0x93, 0xC9, 0x84, 0xCE, 0xB1, + 0xCC, 0x94, 0xC9, 0x84, 0xCE, 0xB1, 0xCD, 0x82, + 0xC9, 0x84, 0xCE, 0xB5, 0xCC, 0x93, 0xC9, 0x84, + 0xCE, 0xB5, 0xCC, 0x94, 0xC9, 0x84, 0xCE, 0xB7, + 0xCC, 0x80, 0xC9, 0x84, 0xCE, 0xB7, 0xCC, 0x81, + 0xC9, 0x84, 0xCE, 0xB7, 0xCC, 0x93, 0xC9, 0x84, + 0xCE, 0xB7, 0xCC, 0x94, 0xC9, 0x84, 0xCE, 0xB7, + // Bytes 4840 - 487f + 0xCD, 0x82, 0xC9, 0x84, 0xCE, 0xB9, 0xCC, 0x88, + 0xC9, 0x84, 0xCE, 0xB9, 0xCC, 0x93, 0xC9, 0x84, + 0xCE, 0xB9, 0xCC, 0x94, 0xC9, 0x84, 0xCE, 0xBF, + 0xCC, 0x93, 0xC9, 0x84, 0xCE, 0xBF, 0xCC, 0x94, + 0xC9, 0x84, 0xCF, 0x85, 0xCC, 0x88, 0xC9, 0x84, + 0xCF, 0x85, 0xCC, 0x93, 0xC9, 0x84, 0xCF, 0x85, + 0xCC, 0x94, 0xC9, 0x84, 0xCF, 0x89, 0xCC, 0x80, + 0xC9, 0x84, 0xCF, 0x89, 0xCC, 0x81, 0xC9, 0x84, + // Bytes 4880 - 48bf + 0xCF, 0x89, 0xCC, 0x93, 0xC9, 0x84, 0xCF, 0x89, + 0xCC, 0x94, 0xC9, 0x84, 0xCF, 0x89, 0xCD, 0x82, + 0xC9, 0x86, 0xCE, 0x91, 0xCC, 0x93, 0xCC, 0x80, + 0xCA, 0x86, 0xCE, 0x91, 0xCC, 0x93, 0xCC, 0x81, + 0xCA, 0x86, 0xCE, 0x91, 0xCC, 0x93, 0xCD, 0x82, + 0xCA, 0x86, 0xCE, 0x91, 0xCC, 0x94, 0xCC, 0x80, + 0xCA, 0x86, 0xCE, 0x91, 0xCC, 0x94, 0xCC, 0x81, + 0xCA, 0x86, 0xCE, 0x91, 0xCC, 0x94, 0xCD, 0x82, + // Bytes 48c0 - 48ff + 0xCA, 0x86, 0xCE, 0x97, 0xCC, 0x93, 0xCC, 0x80, + 0xCA, 0x86, 0xCE, 0x97, 0xCC, 0x93, 0xCC, 0x81, + 0xCA, 0x86, 0xCE, 0x97, 0xCC, 0x93, 0xCD, 0x82, + 0xCA, 0x86, 0xCE, 0x97, 0xCC, 0x94, 0xCC, 0x80, + 0xCA, 0x86, 0xCE, 0x97, 0xCC, 0x94, 0xCC, 0x81, + 0xCA, 0x86, 0xCE, 0x97, 0xCC, 0x94, 0xCD, 0x82, + 0xCA, 0x86, 0xCE, 0xA9, 0xCC, 0x93, 0xCC, 0x80, + 0xCA, 0x86, 0xCE, 0xA9, 0xCC, 0x93, 0xCC, 0x81, + // Bytes 4900 - 493f + 0xCA, 0x86, 0xCE, 0xA9, 0xCC, 0x93, 0xCD, 0x82, + 0xCA, 0x86, 0xCE, 0xA9, 0xCC, 0x94, 0xCC, 0x80, + 0xCA, 0x86, 0xCE, 0xA9, 0xCC, 0x94, 0xCC, 0x81, + 0xCA, 0x86, 0xCE, 0xA9, 0xCC, 0x94, 0xCD, 0x82, + 0xCA, 0x86, 0xCE, 0xB1, 0xCC, 0x93, 0xCC, 0x80, + 0xCA, 0x86, 0xCE, 0xB1, 0xCC, 0x93, 0xCC, 0x81, + 0xCA, 0x86, 0xCE, 0xB1, 0xCC, 0x93, 0xCD, 0x82, + 0xCA, 0x86, 0xCE, 0xB1, 0xCC, 0x94, 0xCC, 0x80, + // Bytes 4940 - 497f + 0xCA, 0x86, 0xCE, 0xB1, 0xCC, 0x94, 0xCC, 0x81, + 0xCA, 0x86, 0xCE, 0xB1, 0xCC, 0x94, 0xCD, 0x82, + 0xCA, 0x86, 0xCE, 0xB7, 0xCC, 0x93, 0xCC, 0x80, + 0xCA, 0x86, 0xCE, 0xB7, 0xCC, 0x93, 0xCC, 0x81, + 0xCA, 0x86, 0xCE, 0xB7, 0xCC, 0x93, 0xCD, 0x82, + 0xCA, 0x86, 0xCE, 0xB7, 0xCC, 0x94, 0xCC, 0x80, + 0xCA, 0x86, 0xCE, 0xB7, 0xCC, 0x94, 0xCC, 0x81, + 0xCA, 0x86, 0xCE, 0xB7, 0xCC, 0x94, 0xCD, 0x82, + // Bytes 4980 - 49bf + 0xCA, 0x86, 0xCF, 0x89, 0xCC, 0x93, 0xCC, 0x80, + 0xCA, 0x86, 0xCF, 0x89, 0xCC, 0x93, 0xCC, 0x81, + 0xCA, 0x86, 0xCF, 0x89, 0xCC, 0x93, 0xCD, 0x82, + 0xCA, 0x86, 0xCF, 0x89, 0xCC, 0x94, 0xCC, 0x80, + 0xCA, 0x86, 0xCF, 0x89, 0xCC, 0x94, 0xCC, 0x81, + 0xCA, 0x86, 0xCF, 0x89, 0xCC, 0x94, 0xCD, 0x82, + 0xCA, 0x42, 0xCC, 0x80, 0xC9, 0x32, 0x42, 0xCC, + 0x81, 0xC9, 0x32, 0x42, 0xCC, 0x93, 0xC9, 0x32, + // Bytes 49c0 - 49ff + 0x43, 0xE1, 0x85, 0xA1, 0x01, 0x00, 0x43, 0xE1, + 0x85, 0xA2, 0x01, 0x00, 0x43, 0xE1, 0x85, 0xA3, + 0x01, 0x00, 0x43, 0xE1, 0x85, 0xA4, 0x01, 0x00, + 0x43, 0xE1, 0x85, 0xA5, 0x01, 0x00, 0x43, 0xE1, + 0x85, 0xA6, 0x01, 0x00, 0x43, 0xE1, 0x85, 0xA7, + 0x01, 0x00, 0x43, 0xE1, 0x85, 0xA8, 0x01, 0x00, + 0x43, 0xE1, 0x85, 0xA9, 0x01, 0x00, 0x43, 0xE1, + 0x85, 0xAA, 0x01, 0x00, 0x43, 0xE1, 0x85, 0xAB, + // Bytes 4a00 - 4a3f + 0x01, 0x00, 0x43, 0xE1, 0x85, 0xAC, 0x01, 0x00, + 0x43, 0xE1, 0x85, 0xAD, 0x01, 0x00, 0x43, 0xE1, + 0x85, 0xAE, 0x01, 0x00, 0x43, 0xE1, 0x85, 0xAF, + 0x01, 0x00, 0x43, 0xE1, 0x85, 0xB0, 0x01, 0x00, + 0x43, 0xE1, 0x85, 0xB1, 0x01, 0x00, 0x43, 0xE1, + 0x85, 0xB2, 0x01, 0x00, 0x43, 0xE1, 0x85, 0xB3, + 0x01, 0x00, 0x43, 0xE1, 0x85, 0xB4, 0x01, 0x00, + 0x43, 0xE1, 0x85, 0xB5, 0x01, 0x00, 0x43, 0xE1, + // Bytes 4a40 - 4a7f + 0x86, 0xAA, 0x01, 0x00, 0x43, 0xE1, 0x86, 0xAC, + 0x01, 0x00, 0x43, 0xE1, 0x86, 0xAD, 0x01, 0x00, + 0x43, 0xE1, 0x86, 0xB0, 0x01, 0x00, 0x43, 0xE1, + 0x86, 0xB1, 0x01, 0x00, 0x43, 0xE1, 0x86, 0xB2, + 0x01, 0x00, 0x43, 0xE1, 0x86, 0xB3, 0x01, 0x00, + 0x43, 0xE1, 0x86, 0xB4, 0x01, 0x00, 0x43, 0xE1, + 0x86, 0xB5, 0x01, 0x00, 0x44, 0xCC, 0x88, 0xCC, + 0x81, 0xCA, 0x32, 0x43, 0xE3, 0x82, 0x99, 0x0D, + // Bytes 4a80 - 4abf + 0x03, 0x43, 0xE3, 0x82, 0x9A, 0x0D, 0x03, 0x46, + 0xE0, 0xBD, 0xB1, 0xE0, 0xBD, 0xB2, 0x9E, 0x26, + 0x46, 0xE0, 0xBD, 0xB1, 0xE0, 0xBD, 0xB4, 0xA2, + 0x26, 0x46, 0xE0, 0xBD, 0xB1, 0xE0, 0xBE, 0x80, + 0x9E, 0x26, 0x00, 0x01, +} + +// lookup returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *nfcTrie) lookup(s []byte) (v uint16, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return nfcValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = nfcIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *nfcTrie) lookupUnsafe(s []byte) uint16 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return nfcValues[c0] + } + i := nfcIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = nfcIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = nfcIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// lookupString returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *nfcTrie) lookupString(s string) (v uint16, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return nfcValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = nfcIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *nfcTrie) lookupStringUnsafe(s string) uint16 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return nfcValues[c0] + } + i := nfcIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = nfcIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = nfcIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// nfcTrie. Total size: 10610 bytes (10.36 KiB). Checksum: 95e8869a9f81e5e6. +type nfcTrie struct{} + +func newNfcTrie(i int) *nfcTrie { + return &nfcTrie{} +} + +// lookupValue determines the type of block n and looks up the value for b. +func (t *nfcTrie) lookupValue(n uint32, b byte) uint16 { + switch { + case n < 46: + return uint16(nfcValues[n<<6+uint32(b)]) + default: + n -= 46 + return uint16(nfcSparse.lookup(n, b)) + } +} + +// nfcValues: 48 blocks, 3072 entries, 6144 bytes +// The third block is the zero block. +var nfcValues = [3072]uint16{ + // Block 0x0, offset 0x0 + 0x3c: 0xa000, 0x3d: 0xa000, 0x3e: 0xa000, + // Block 0x1, offset 0x40 + 0x41: 0xa000, 0x42: 0xa000, 0x43: 0xa000, 0x44: 0xa000, 0x45: 0xa000, + 0x46: 0xa000, 0x47: 0xa000, 0x48: 0xa000, 0x49: 0xa000, 0x4a: 0xa000, 0x4b: 0xa000, + 0x4c: 0xa000, 0x4d: 0xa000, 0x4e: 0xa000, 0x4f: 0xa000, 0x50: 0xa000, + 0x52: 0xa000, 0x53: 0xa000, 0x54: 0xa000, 0x55: 0xa000, 0x56: 0xa000, 0x57: 0xa000, + 0x58: 0xa000, 0x59: 0xa000, 0x5a: 0xa000, + 0x61: 0xa000, 0x62: 0xa000, 0x63: 0xa000, + 0x64: 0xa000, 0x65: 0xa000, 0x66: 0xa000, 0x67: 0xa000, 0x68: 0xa000, 0x69: 0xa000, + 0x6a: 0xa000, 0x6b: 0xa000, 0x6c: 0xa000, 0x6d: 0xa000, 0x6e: 0xa000, 0x6f: 0xa000, + 0x70: 0xa000, 0x72: 0xa000, 0x73: 0xa000, 0x74: 0xa000, 0x75: 0xa000, + 0x76: 0xa000, 0x77: 0xa000, 0x78: 0xa000, 0x79: 0xa000, 0x7a: 0xa000, + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc0: 0x2f72, 0xc1: 0x2f77, 0xc2: 0x468b, 0xc3: 0x2f7c, 0xc4: 0x469a, 0xc5: 0x469f, + 0xc6: 0xa000, 0xc7: 0x46a9, 0xc8: 0x2fe5, 0xc9: 0x2fea, 0xca: 0x46ae, 0xcb: 0x2ffe, + 0xcc: 0x3071, 0xcd: 0x3076, 0xce: 0x307b, 0xcf: 0x46c2, 0xd1: 0x3107, + 0xd2: 0x312a, 0xd3: 0x312f, 0xd4: 0x46cc, 0xd5: 0x46d1, 0xd6: 0x46e0, + 0xd8: 0xa000, 0xd9: 0x31b6, 0xda: 0x31bb, 0xdb: 0x31c0, 0xdc: 0x4712, 0xdd: 0x3238, + 0xe0: 0x327e, 0xe1: 0x3283, 0xe2: 0x471c, 0xe3: 0x3288, + 0xe4: 0x472b, 0xe5: 0x4730, 0xe6: 0xa000, 0xe7: 0x473a, 0xe8: 0x32f1, 0xe9: 0x32f6, + 0xea: 0x473f, 0xeb: 0x330a, 0xec: 0x3382, 0xed: 0x3387, 0xee: 0x338c, 0xef: 0x4753, + 0xf1: 0x3418, 0xf2: 0x343b, 0xf3: 0x3440, 0xf4: 0x475d, 0xf5: 0x4762, + 0xf6: 0x4771, 0xf8: 0xa000, 0xf9: 0x34cc, 0xfa: 0x34d1, 0xfb: 0x34d6, + 0xfc: 0x47a3, 0xfd: 0x3553, 0xff: 0x356c, + // Block 0x4, offset 0x100 + 0x100: 0x2f81, 0x101: 0x328d, 0x102: 0x4690, 0x103: 0x4721, 0x104: 0x2f9f, 0x105: 0x32ab, + 0x106: 0x2fb3, 0x107: 0x32bf, 0x108: 0x2fb8, 0x109: 0x32c4, 0x10a: 0x2fbd, 0x10b: 0x32c9, + 0x10c: 0x2fc2, 0x10d: 0x32ce, 0x10e: 0x2fcc, 0x10f: 0x32d8, + 0x112: 0x46b3, 0x113: 0x4744, 0x114: 0x2ff4, 0x115: 0x3300, 0x116: 0x2ff9, 0x117: 0x3305, + 0x118: 0x3017, 0x119: 0x3323, 0x11a: 0x3008, 0x11b: 0x3314, 0x11c: 0x3030, 0x11d: 0x333c, + 0x11e: 0x303a, 0x11f: 0x3346, 0x120: 0x303f, 0x121: 0x334b, 0x122: 0x3049, 0x123: 0x3355, + 0x124: 0x304e, 0x125: 0x335a, 0x128: 0x3080, 0x129: 0x3391, + 0x12a: 0x3085, 0x12b: 0x3396, 0x12c: 0x308a, 0x12d: 0x339b, 0x12e: 0x30ad, 0x12f: 0x33b9, + 0x130: 0x308f, 0x134: 0x30b7, 0x135: 0x33c3, + 0x136: 0x30cb, 0x137: 0x33dc, 0x139: 0x30d5, 0x13a: 0x33e6, 0x13b: 0x30df, + 0x13c: 0x33f0, 0x13d: 0x30da, 0x13e: 0x33eb, + // Block 0x5, offset 0x140 + 0x143: 0x3102, 0x144: 0x3413, 0x145: 0x311b, + 0x146: 0x342c, 0x147: 0x3111, 0x148: 0x3422, + 0x14c: 0x46d6, 0x14d: 0x4767, 0x14e: 0x3134, 0x14f: 0x3445, 0x150: 0x313e, 0x151: 0x344f, + 0x154: 0x315c, 0x155: 0x346d, 0x156: 0x3175, 0x157: 0x3486, + 0x158: 0x3166, 0x159: 0x3477, 0x15a: 0x46f9, 0x15b: 0x478a, 0x15c: 0x317f, 0x15d: 0x3490, + 0x15e: 0x318e, 0x15f: 0x349f, 0x160: 0x46fe, 0x161: 0x478f, 0x162: 0x31a7, 0x163: 0x34bd, + 0x164: 0x3198, 0x165: 0x34ae, 0x168: 0x4708, 0x169: 0x4799, + 0x16a: 0x470d, 0x16b: 0x479e, 0x16c: 0x31c5, 0x16d: 0x34db, 0x16e: 0x31cf, 0x16f: 0x34e5, + 0x170: 0x31d4, 0x171: 0x34ea, 0x172: 0x31f2, 0x173: 0x3508, 0x174: 0x3215, 0x175: 0x352b, + 0x176: 0x323d, 0x177: 0x3558, 0x178: 0x3251, 0x179: 0x3260, 0x17a: 0x3580, 0x17b: 0x326a, + 0x17c: 0x358a, 0x17d: 0x326f, 0x17e: 0x358f, 0x17f: 0xa000, + // Block 0x6, offset 0x180 + 0x184: 0x8100, 0x185: 0x8100, + 0x186: 0x8100, + 0x18d: 0x2f8b, 0x18e: 0x3297, 0x18f: 0x3099, 0x190: 0x33a5, 0x191: 0x3143, + 0x192: 0x3454, 0x193: 0x31d9, 0x194: 0x34ef, 0x195: 0x39d2, 0x196: 0x3b61, 0x197: 0x39cb, + 0x198: 0x3b5a, 0x199: 0x39d9, 0x19a: 0x3b68, 0x19b: 0x39c4, 0x19c: 0x3b53, + 0x19e: 0x38b3, 0x19f: 0x3a42, 0x1a0: 0x38ac, 0x1a1: 0x3a3b, 0x1a2: 0x35b6, 0x1a3: 0x35c8, + 0x1a6: 0x3044, 0x1a7: 0x3350, 0x1a8: 0x30c1, 0x1a9: 0x33d2, + 0x1aa: 0x46ef, 0x1ab: 0x4780, 0x1ac: 0x3993, 0x1ad: 0x3b22, 0x1ae: 0x35da, 0x1af: 0x35e0, + 0x1b0: 0x33c8, 0x1b4: 0x302b, 0x1b5: 0x3337, + 0x1b8: 0x30fd, 0x1b9: 0x340e, 0x1ba: 0x38ba, 0x1bb: 0x3a49, + 0x1bc: 0x35b0, 0x1bd: 0x35c2, 0x1be: 0x35bc, 0x1bf: 0x35ce, + // Block 0x7, offset 0x1c0 + 0x1c0: 0x2f90, 0x1c1: 0x329c, 0x1c2: 0x2f95, 0x1c3: 0x32a1, 0x1c4: 0x300d, 0x1c5: 0x3319, + 0x1c6: 0x3012, 0x1c7: 0x331e, 0x1c8: 0x309e, 0x1c9: 0x33aa, 0x1ca: 0x30a3, 0x1cb: 0x33af, + 0x1cc: 0x3148, 0x1cd: 0x3459, 0x1ce: 0x314d, 0x1cf: 0x345e, 0x1d0: 0x316b, 0x1d1: 0x347c, + 0x1d2: 0x3170, 0x1d3: 0x3481, 0x1d4: 0x31de, 0x1d5: 0x34f4, 0x1d6: 0x31e3, 0x1d7: 0x34f9, + 0x1d8: 0x3189, 0x1d9: 0x349a, 0x1da: 0x31a2, 0x1db: 0x34b8, + 0x1de: 0x305d, 0x1df: 0x3369, + 0x1e6: 0x4695, 0x1e7: 0x4726, 0x1e8: 0x46bd, 0x1e9: 0x474e, + 0x1ea: 0x3962, 0x1eb: 0x3af1, 0x1ec: 0x393f, 0x1ed: 0x3ace, 0x1ee: 0x46db, 0x1ef: 0x476c, + 0x1f0: 0x395b, 0x1f1: 0x3aea, 0x1f2: 0x3247, 0x1f3: 0x3562, + // Block 0x8, offset 0x200 + 0x200: 0x9932, 0x201: 0x9932, 0x202: 0x9932, 0x203: 0x9932, 0x204: 0x9932, 0x205: 0x8132, + 0x206: 0x9932, 0x207: 0x9932, 0x208: 0x9932, 0x209: 0x9932, 0x20a: 0x9932, 0x20b: 0x9932, + 0x20c: 0x9932, 0x20d: 0x8132, 0x20e: 0x8132, 0x20f: 0x9932, 0x210: 0x8132, 0x211: 0x9932, + 0x212: 0x8132, 0x213: 0x9932, 0x214: 0x9932, 0x215: 0x8133, 0x216: 0x812d, 0x217: 0x812d, + 0x218: 0x812d, 0x219: 0x812d, 0x21a: 0x8133, 0x21b: 0x992b, 0x21c: 0x812d, 0x21d: 0x812d, + 0x21e: 0x812d, 0x21f: 0x812d, 0x220: 0x812d, 0x221: 0x8129, 0x222: 0x8129, 0x223: 0x992d, + 0x224: 0x992d, 0x225: 0x992d, 0x226: 0x992d, 0x227: 0x9929, 0x228: 0x9929, 0x229: 0x812d, + 0x22a: 0x812d, 0x22b: 0x812d, 0x22c: 0x812d, 0x22d: 0x992d, 0x22e: 0x992d, 0x22f: 0x812d, + 0x230: 0x992d, 0x231: 0x992d, 0x232: 0x812d, 0x233: 0x812d, 0x234: 0x8101, 0x235: 0x8101, + 0x236: 0x8101, 0x237: 0x8101, 0x238: 0x9901, 0x239: 0x812d, 0x23a: 0x812d, 0x23b: 0x812d, + 0x23c: 0x812d, 0x23d: 0x8132, 0x23e: 0x8132, 0x23f: 0x8132, + // Block 0x9, offset 0x240 + 0x240: 0x49b1, 0x241: 0x49b6, 0x242: 0x9932, 0x243: 0x49bb, 0x244: 0x4a74, 0x245: 0x9936, + 0x246: 0x8132, 0x247: 0x812d, 0x248: 0x812d, 0x249: 0x812d, 0x24a: 0x8132, 0x24b: 0x8132, + 0x24c: 0x8132, 0x24d: 0x812d, 0x24e: 0x812d, 0x250: 0x8132, 0x251: 0x8132, + 0x252: 0x8132, 0x253: 0x812d, 0x254: 0x812d, 0x255: 0x812d, 0x256: 0x812d, 0x257: 0x8132, + 0x258: 0x8133, 0x259: 0x812d, 0x25a: 0x812d, 0x25b: 0x8132, 0x25c: 0x8134, 0x25d: 0x8135, + 0x25e: 0x8135, 0x25f: 0x8134, 0x260: 0x8135, 0x261: 0x8135, 0x262: 0x8134, 0x263: 0x8132, + 0x264: 0x8132, 0x265: 0x8132, 0x266: 0x8132, 0x267: 0x8132, 0x268: 0x8132, 0x269: 0x8132, + 0x26a: 0x8132, 0x26b: 0x8132, 0x26c: 0x8132, 0x26d: 0x8132, 0x26e: 0x8132, 0x26f: 0x8132, + 0x274: 0x0170, + 0x27a: 0x8100, + 0x27e: 0x0037, + // Block 0xa, offset 0x280 + 0x284: 0x8100, 0x285: 0x35a4, + 0x286: 0x35ec, 0x287: 0x00ce, 0x288: 0x360a, 0x289: 0x3616, 0x28a: 0x3628, + 0x28c: 0x3646, 0x28e: 0x3658, 0x28f: 0x3676, 0x290: 0x3e0b, 0x291: 0xa000, + 0x295: 0xa000, 0x297: 0xa000, + 0x299: 0xa000, + 0x29f: 0xa000, 0x2a1: 0xa000, + 0x2a5: 0xa000, 0x2a9: 0xa000, + 0x2aa: 0x363a, 0x2ab: 0x366a, 0x2ac: 0x4801, 0x2ad: 0x369a, 0x2ae: 0x482b, 0x2af: 0x36ac, + 0x2b0: 0x3e73, 0x2b1: 0xa000, 0x2b5: 0xa000, + 0x2b7: 0xa000, 0x2b9: 0xa000, + 0x2bf: 0xa000, + // Block 0xb, offset 0x2c0 + 0x2c0: 0x3724, 0x2c1: 0x3730, 0x2c3: 0x371e, + 0x2c6: 0xa000, 0x2c7: 0x370c, + 0x2cc: 0x3760, 0x2cd: 0x3748, 0x2ce: 0x3772, 0x2d0: 0xa000, + 0x2d3: 0xa000, 0x2d5: 0xa000, 0x2d6: 0xa000, 0x2d7: 0xa000, + 0x2d8: 0xa000, 0x2d9: 0x3754, 0x2da: 0xa000, + 0x2de: 0xa000, 0x2e3: 0xa000, + 0x2e7: 0xa000, + 0x2eb: 0xa000, 0x2ed: 0xa000, + 0x2f0: 0xa000, 0x2f3: 0xa000, 0x2f5: 0xa000, + 0x2f6: 0xa000, 0x2f7: 0xa000, 0x2f8: 0xa000, 0x2f9: 0x37d8, 0x2fa: 0xa000, + 0x2fe: 0xa000, + // Block 0xc, offset 0x300 + 0x301: 0x3736, 0x302: 0x37ba, + 0x310: 0x3712, 0x311: 0x3796, + 0x312: 0x3718, 0x313: 0x379c, 0x316: 0x372a, 0x317: 0x37ae, + 0x318: 0xa000, 0x319: 0xa000, 0x31a: 0x382c, 0x31b: 0x3832, 0x31c: 0x373c, 0x31d: 0x37c0, + 0x31e: 0x3742, 0x31f: 0x37c6, 0x322: 0x374e, 0x323: 0x37d2, + 0x324: 0x375a, 0x325: 0x37de, 0x326: 0x3766, 0x327: 0x37ea, 0x328: 0xa000, 0x329: 0xa000, + 0x32a: 0x3838, 0x32b: 0x383e, 0x32c: 0x3790, 0x32d: 0x3814, 0x32e: 0x376c, 0x32f: 0x37f0, + 0x330: 0x3778, 0x331: 0x37fc, 0x332: 0x377e, 0x333: 0x3802, 0x334: 0x3784, 0x335: 0x3808, + 0x338: 0x378a, 0x339: 0x380e, + // Block 0xd, offset 0x340 + 0x351: 0x812d, + 0x352: 0x8132, 0x353: 0x8132, 0x354: 0x8132, 0x355: 0x8132, 0x356: 0x812d, 0x357: 0x8132, + 0x358: 0x8132, 0x359: 0x8132, 0x35a: 0x812e, 0x35b: 0x812d, 0x35c: 0x8132, 0x35d: 0x8132, + 0x35e: 0x8132, 0x35f: 0x8132, 0x360: 0x8132, 0x361: 0x8132, 0x362: 0x812d, 0x363: 0x812d, + 0x364: 0x812d, 0x365: 0x812d, 0x366: 0x812d, 0x367: 0x812d, 0x368: 0x8132, 0x369: 0x8132, + 0x36a: 0x812d, 0x36b: 0x8132, 0x36c: 0x8132, 0x36d: 0x812e, 0x36e: 0x8131, 0x36f: 0x8132, + 0x370: 0x8105, 0x371: 0x8106, 0x372: 0x8107, 0x373: 0x8108, 0x374: 0x8109, 0x375: 0x810a, + 0x376: 0x810b, 0x377: 0x810c, 0x378: 0x810d, 0x379: 0x810e, 0x37a: 0x810e, 0x37b: 0x810f, + 0x37c: 0x8110, 0x37d: 0x8111, 0x37f: 0x8112, + // Block 0xe, offset 0x380 + 0x388: 0xa000, 0x38a: 0xa000, 0x38b: 0x8116, + 0x38c: 0x8117, 0x38d: 0x8118, 0x38e: 0x8119, 0x38f: 0x811a, 0x390: 0x811b, 0x391: 0x811c, + 0x392: 0x811d, 0x393: 0x9932, 0x394: 0x9932, 0x395: 0x992d, 0x396: 0x812d, 0x397: 0x8132, + 0x398: 0x8132, 0x399: 0x8132, 0x39a: 0x8132, 0x39b: 0x8132, 0x39c: 0x812d, 0x39d: 0x8132, + 0x39e: 0x8132, 0x39f: 0x812d, + 0x3b0: 0x811e, + // Block 0xf, offset 0x3c0 + 0x3d3: 0x812d, 0x3d4: 0x8132, 0x3d5: 0x8132, 0x3d6: 0x8132, 0x3d7: 0x8132, + 0x3d8: 0x8132, 0x3d9: 0x8132, 0x3da: 0x8132, 0x3db: 0x8132, 0x3dc: 0x8132, 0x3dd: 0x8132, + 0x3de: 0x8132, 0x3df: 0x8132, 0x3e0: 0x8132, 0x3e1: 0x8132, 0x3e3: 0x812d, + 0x3e4: 0x8132, 0x3e5: 0x8132, 0x3e6: 0x812d, 0x3e7: 0x8132, 0x3e8: 0x8132, 0x3e9: 0x812d, + 0x3ea: 0x8132, 0x3eb: 0x8132, 0x3ec: 0x8132, 0x3ed: 0x812d, 0x3ee: 0x812d, 0x3ef: 0x812d, + 0x3f0: 0x8116, 0x3f1: 0x8117, 0x3f2: 0x8118, 0x3f3: 0x8132, 0x3f4: 0x8132, 0x3f5: 0x8132, + 0x3f6: 0x812d, 0x3f7: 0x8132, 0x3f8: 0x8132, 0x3f9: 0x812d, 0x3fa: 0x812d, 0x3fb: 0x8132, + 0x3fc: 0x8132, 0x3fd: 0x8132, 0x3fe: 0x8132, 0x3ff: 0x8132, + // Block 0x10, offset 0x400 + 0x405: 0xa000, + 0x406: 0x2d29, 0x407: 0xa000, 0x408: 0x2d31, 0x409: 0xa000, 0x40a: 0x2d39, 0x40b: 0xa000, + 0x40c: 0x2d41, 0x40d: 0xa000, 0x40e: 0x2d49, 0x411: 0xa000, + 0x412: 0x2d51, + 0x434: 0x8102, 0x435: 0x9900, + 0x43a: 0xa000, 0x43b: 0x2d59, + 0x43c: 0xa000, 0x43d: 0x2d61, 0x43e: 0xa000, 0x43f: 0xa000, + // Block 0x11, offset 0x440 + 0x440: 0x8132, 0x441: 0x8132, 0x442: 0x812d, 0x443: 0x8132, 0x444: 0x8132, 0x445: 0x8132, + 0x446: 0x8132, 0x447: 0x8132, 0x448: 0x8132, 0x449: 0x8132, 0x44a: 0x812d, 0x44b: 0x8132, + 0x44c: 0x8132, 0x44d: 0x8135, 0x44e: 0x812a, 0x44f: 0x812d, 0x450: 0x8129, 0x451: 0x8132, + 0x452: 0x8132, 0x453: 0x8132, 0x454: 0x8132, 0x455: 0x8132, 0x456: 0x8132, 0x457: 0x8132, + 0x458: 0x8132, 0x459: 0x8132, 0x45a: 0x8132, 0x45b: 0x8132, 0x45c: 0x8132, 0x45d: 0x8132, + 0x45e: 0x8132, 0x45f: 0x8132, 0x460: 0x8132, 0x461: 0x8132, 0x462: 0x8132, 0x463: 0x8132, + 0x464: 0x8132, 0x465: 0x8132, 0x466: 0x8132, 0x467: 0x8132, 0x468: 0x8132, 0x469: 0x8132, + 0x46a: 0x8132, 0x46b: 0x8132, 0x46c: 0x8132, 0x46d: 0x8132, 0x46e: 0x8132, 0x46f: 0x8132, + 0x470: 0x8132, 0x471: 0x8132, 0x472: 0x8132, 0x473: 0x8132, 0x474: 0x8132, 0x475: 0x8132, + 0x476: 0x8133, 0x477: 0x8131, 0x478: 0x8131, 0x479: 0x812d, 0x47b: 0x8132, + 0x47c: 0x8134, 0x47d: 0x812d, 0x47e: 0x8132, 0x47f: 0x812d, + // Block 0x12, offset 0x480 + 0x480: 0x2f9a, 0x481: 0x32a6, 0x482: 0x2fa4, 0x483: 0x32b0, 0x484: 0x2fa9, 0x485: 0x32b5, + 0x486: 0x2fae, 0x487: 0x32ba, 0x488: 0x38cf, 0x489: 0x3a5e, 0x48a: 0x2fc7, 0x48b: 0x32d3, + 0x48c: 0x2fd1, 0x48d: 0x32dd, 0x48e: 0x2fe0, 0x48f: 0x32ec, 0x490: 0x2fd6, 0x491: 0x32e2, + 0x492: 0x2fdb, 0x493: 0x32e7, 0x494: 0x38f2, 0x495: 0x3a81, 0x496: 0x38f9, 0x497: 0x3a88, + 0x498: 0x301c, 0x499: 0x3328, 0x49a: 0x3021, 0x49b: 0x332d, 0x49c: 0x3907, 0x49d: 0x3a96, + 0x49e: 0x3026, 0x49f: 0x3332, 0x4a0: 0x3035, 0x4a1: 0x3341, 0x4a2: 0x3053, 0x4a3: 0x335f, + 0x4a4: 0x3062, 0x4a5: 0x336e, 0x4a6: 0x3058, 0x4a7: 0x3364, 0x4a8: 0x3067, 0x4a9: 0x3373, + 0x4aa: 0x306c, 0x4ab: 0x3378, 0x4ac: 0x30b2, 0x4ad: 0x33be, 0x4ae: 0x390e, 0x4af: 0x3a9d, + 0x4b0: 0x30bc, 0x4b1: 0x33cd, 0x4b2: 0x30c6, 0x4b3: 0x33d7, 0x4b4: 0x30d0, 0x4b5: 0x33e1, + 0x4b6: 0x46c7, 0x4b7: 0x4758, 0x4b8: 0x3915, 0x4b9: 0x3aa4, 0x4ba: 0x30e9, 0x4bb: 0x33fa, + 0x4bc: 0x30e4, 0x4bd: 0x33f5, 0x4be: 0x30ee, 0x4bf: 0x33ff, + // Block 0x13, offset 0x4c0 + 0x4c0: 0x30f3, 0x4c1: 0x3404, 0x4c2: 0x30f8, 0x4c3: 0x3409, 0x4c4: 0x310c, 0x4c5: 0x341d, + 0x4c6: 0x3116, 0x4c7: 0x3427, 0x4c8: 0x3125, 0x4c9: 0x3436, 0x4ca: 0x3120, 0x4cb: 0x3431, + 0x4cc: 0x3938, 0x4cd: 0x3ac7, 0x4ce: 0x3946, 0x4cf: 0x3ad5, 0x4d0: 0x394d, 0x4d1: 0x3adc, + 0x4d2: 0x3954, 0x4d3: 0x3ae3, 0x4d4: 0x3152, 0x4d5: 0x3463, 0x4d6: 0x3157, 0x4d7: 0x3468, + 0x4d8: 0x3161, 0x4d9: 0x3472, 0x4da: 0x46f4, 0x4db: 0x4785, 0x4dc: 0x399a, 0x4dd: 0x3b29, + 0x4de: 0x317a, 0x4df: 0x348b, 0x4e0: 0x3184, 0x4e1: 0x3495, 0x4e2: 0x4703, 0x4e3: 0x4794, + 0x4e4: 0x39a1, 0x4e5: 0x3b30, 0x4e6: 0x39a8, 0x4e7: 0x3b37, 0x4e8: 0x39af, 0x4e9: 0x3b3e, + 0x4ea: 0x3193, 0x4eb: 0x34a4, 0x4ec: 0x319d, 0x4ed: 0x34b3, 0x4ee: 0x31b1, 0x4ef: 0x34c7, + 0x4f0: 0x31ac, 0x4f1: 0x34c2, 0x4f2: 0x31ed, 0x4f3: 0x3503, 0x4f4: 0x31fc, 0x4f5: 0x3512, + 0x4f6: 0x31f7, 0x4f7: 0x350d, 0x4f8: 0x39b6, 0x4f9: 0x3b45, 0x4fa: 0x39bd, 0x4fb: 0x3b4c, + 0x4fc: 0x3201, 0x4fd: 0x3517, 0x4fe: 0x3206, 0x4ff: 0x351c, + // Block 0x14, offset 0x500 + 0x500: 0x320b, 0x501: 0x3521, 0x502: 0x3210, 0x503: 0x3526, 0x504: 0x321f, 0x505: 0x3535, + 0x506: 0x321a, 0x507: 0x3530, 0x508: 0x3224, 0x509: 0x353f, 0x50a: 0x3229, 0x50b: 0x3544, + 0x50c: 0x322e, 0x50d: 0x3549, 0x50e: 0x324c, 0x50f: 0x3567, 0x510: 0x3265, 0x511: 0x3585, + 0x512: 0x3274, 0x513: 0x3594, 0x514: 0x3279, 0x515: 0x3599, 0x516: 0x337d, 0x517: 0x34a9, + 0x518: 0x353a, 0x519: 0x3576, 0x51b: 0x35d4, + 0x520: 0x46a4, 0x521: 0x4735, 0x522: 0x2f86, 0x523: 0x3292, + 0x524: 0x387b, 0x525: 0x3a0a, 0x526: 0x3874, 0x527: 0x3a03, 0x528: 0x3889, 0x529: 0x3a18, + 0x52a: 0x3882, 0x52b: 0x3a11, 0x52c: 0x38c1, 0x52d: 0x3a50, 0x52e: 0x3897, 0x52f: 0x3a26, + 0x530: 0x3890, 0x531: 0x3a1f, 0x532: 0x38a5, 0x533: 0x3a34, 0x534: 0x389e, 0x535: 0x3a2d, + 0x536: 0x38c8, 0x537: 0x3a57, 0x538: 0x46b8, 0x539: 0x4749, 0x53a: 0x3003, 0x53b: 0x330f, + 0x53c: 0x2fef, 0x53d: 0x32fb, 0x53e: 0x38dd, 0x53f: 0x3a6c, + // Block 0x15, offset 0x540 + 0x540: 0x38d6, 0x541: 0x3a65, 0x542: 0x38eb, 0x543: 0x3a7a, 0x544: 0x38e4, 0x545: 0x3a73, + 0x546: 0x3900, 0x547: 0x3a8f, 0x548: 0x3094, 0x549: 0x33a0, 0x54a: 0x30a8, 0x54b: 0x33b4, + 0x54c: 0x46ea, 0x54d: 0x477b, 0x54e: 0x3139, 0x54f: 0x344a, 0x550: 0x3923, 0x551: 0x3ab2, + 0x552: 0x391c, 0x553: 0x3aab, 0x554: 0x3931, 0x555: 0x3ac0, 0x556: 0x392a, 0x557: 0x3ab9, + 0x558: 0x398c, 0x559: 0x3b1b, 0x55a: 0x3970, 0x55b: 0x3aff, 0x55c: 0x3969, 0x55d: 0x3af8, + 0x55e: 0x397e, 0x55f: 0x3b0d, 0x560: 0x3977, 0x561: 0x3b06, 0x562: 0x3985, 0x563: 0x3b14, + 0x564: 0x31e8, 0x565: 0x34fe, 0x566: 0x31ca, 0x567: 0x34e0, 0x568: 0x39e7, 0x569: 0x3b76, + 0x56a: 0x39e0, 0x56b: 0x3b6f, 0x56c: 0x39f5, 0x56d: 0x3b84, 0x56e: 0x39ee, 0x56f: 0x3b7d, + 0x570: 0x39fc, 0x571: 0x3b8b, 0x572: 0x3233, 0x573: 0x354e, 0x574: 0x325b, 0x575: 0x357b, + 0x576: 0x3256, 0x577: 0x3571, 0x578: 0x3242, 0x579: 0x355d, + // Block 0x16, offset 0x580 + 0x580: 0x4807, 0x581: 0x480d, 0x582: 0x4921, 0x583: 0x4939, 0x584: 0x4929, 0x585: 0x4941, + 0x586: 0x4931, 0x587: 0x4949, 0x588: 0x47ad, 0x589: 0x47b3, 0x58a: 0x4891, 0x58b: 0x48a9, + 0x58c: 0x4899, 0x58d: 0x48b1, 0x58e: 0x48a1, 0x58f: 0x48b9, 0x590: 0x4819, 0x591: 0x481f, + 0x592: 0x3dbb, 0x593: 0x3dcb, 0x594: 0x3dc3, 0x595: 0x3dd3, + 0x598: 0x47b9, 0x599: 0x47bf, 0x59a: 0x3ceb, 0x59b: 0x3cfb, 0x59c: 0x3cf3, 0x59d: 0x3d03, + 0x5a0: 0x4831, 0x5a1: 0x4837, 0x5a2: 0x4951, 0x5a3: 0x4969, + 0x5a4: 0x4959, 0x5a5: 0x4971, 0x5a6: 0x4961, 0x5a7: 0x4979, 0x5a8: 0x47c5, 0x5a9: 0x47cb, + 0x5aa: 0x48c1, 0x5ab: 0x48d9, 0x5ac: 0x48c9, 0x5ad: 0x48e1, 0x5ae: 0x48d1, 0x5af: 0x48e9, + 0x5b0: 0x4849, 0x5b1: 0x484f, 0x5b2: 0x3e1b, 0x5b3: 0x3e33, 0x5b4: 0x3e23, 0x5b5: 0x3e3b, + 0x5b6: 0x3e2b, 0x5b7: 0x3e43, 0x5b8: 0x47d1, 0x5b9: 0x47d7, 0x5ba: 0x3d1b, 0x5bb: 0x3d33, + 0x5bc: 0x3d23, 0x5bd: 0x3d3b, 0x5be: 0x3d2b, 0x5bf: 0x3d43, + // Block 0x17, offset 0x5c0 + 0x5c0: 0x4855, 0x5c1: 0x485b, 0x5c2: 0x3e4b, 0x5c3: 0x3e5b, 0x5c4: 0x3e53, 0x5c5: 0x3e63, + 0x5c8: 0x47dd, 0x5c9: 0x47e3, 0x5ca: 0x3d4b, 0x5cb: 0x3d5b, + 0x5cc: 0x3d53, 0x5cd: 0x3d63, 0x5d0: 0x4867, 0x5d1: 0x486d, + 0x5d2: 0x3e83, 0x5d3: 0x3e9b, 0x5d4: 0x3e8b, 0x5d5: 0x3ea3, 0x5d6: 0x3e93, 0x5d7: 0x3eab, + 0x5d9: 0x47e9, 0x5db: 0x3d6b, 0x5dd: 0x3d73, + 0x5df: 0x3d7b, 0x5e0: 0x487f, 0x5e1: 0x4885, 0x5e2: 0x4981, 0x5e3: 0x4999, + 0x5e4: 0x4989, 0x5e5: 0x49a1, 0x5e6: 0x4991, 0x5e7: 0x49a9, 0x5e8: 0x47ef, 0x5e9: 0x47f5, + 0x5ea: 0x48f1, 0x5eb: 0x4909, 0x5ec: 0x48f9, 0x5ed: 0x4911, 0x5ee: 0x4901, 0x5ef: 0x4919, + 0x5f0: 0x47fb, 0x5f1: 0x4321, 0x5f2: 0x3694, 0x5f3: 0x4327, 0x5f4: 0x4825, 0x5f5: 0x432d, + 0x5f6: 0x36a6, 0x5f7: 0x4333, 0x5f8: 0x36c4, 0x5f9: 0x4339, 0x5fa: 0x36dc, 0x5fb: 0x433f, + 0x5fc: 0x4873, 0x5fd: 0x4345, + // Block 0x18, offset 0x600 + 0x600: 0x3da3, 0x601: 0x3dab, 0x602: 0x4187, 0x603: 0x41a5, 0x604: 0x4191, 0x605: 0x41af, + 0x606: 0x419b, 0x607: 0x41b9, 0x608: 0x3cdb, 0x609: 0x3ce3, 0x60a: 0x40d3, 0x60b: 0x40f1, + 0x60c: 0x40dd, 0x60d: 0x40fb, 0x60e: 0x40e7, 0x60f: 0x4105, 0x610: 0x3deb, 0x611: 0x3df3, + 0x612: 0x41c3, 0x613: 0x41e1, 0x614: 0x41cd, 0x615: 0x41eb, 0x616: 0x41d7, 0x617: 0x41f5, + 0x618: 0x3d0b, 0x619: 0x3d13, 0x61a: 0x410f, 0x61b: 0x412d, 0x61c: 0x4119, 0x61d: 0x4137, + 0x61e: 0x4123, 0x61f: 0x4141, 0x620: 0x3ec3, 0x621: 0x3ecb, 0x622: 0x41ff, 0x623: 0x421d, + 0x624: 0x4209, 0x625: 0x4227, 0x626: 0x4213, 0x627: 0x4231, 0x628: 0x3d83, 0x629: 0x3d8b, + 0x62a: 0x414b, 0x62b: 0x4169, 0x62c: 0x4155, 0x62d: 0x4173, 0x62e: 0x415f, 0x62f: 0x417d, + 0x630: 0x3688, 0x631: 0x3682, 0x632: 0x3d93, 0x633: 0x368e, 0x634: 0x3d9b, + 0x636: 0x4813, 0x637: 0x3db3, 0x638: 0x35f8, 0x639: 0x35f2, 0x63a: 0x35e6, 0x63b: 0x42f1, + 0x63c: 0x35fe, 0x63d: 0x8100, 0x63e: 0x01d3, 0x63f: 0xa100, + // Block 0x19, offset 0x640 + 0x640: 0x8100, 0x641: 0x35aa, 0x642: 0x3ddb, 0x643: 0x36a0, 0x644: 0x3de3, + 0x646: 0x483d, 0x647: 0x3dfb, 0x648: 0x3604, 0x649: 0x42f7, 0x64a: 0x3610, 0x64b: 0x42fd, + 0x64c: 0x361c, 0x64d: 0x3b92, 0x64e: 0x3b99, 0x64f: 0x3ba0, 0x650: 0x36b8, 0x651: 0x36b2, + 0x652: 0x3e03, 0x653: 0x44e7, 0x656: 0x36be, 0x657: 0x3e13, + 0x658: 0x3634, 0x659: 0x362e, 0x65a: 0x3622, 0x65b: 0x4303, 0x65d: 0x3ba7, + 0x65e: 0x3bae, 0x65f: 0x3bb5, 0x660: 0x36ee, 0x661: 0x36e8, 0x662: 0x3e6b, 0x663: 0x44ef, + 0x664: 0x36d0, 0x665: 0x36d6, 0x666: 0x36f4, 0x667: 0x3e7b, 0x668: 0x3664, 0x669: 0x365e, + 0x66a: 0x3652, 0x66b: 0x430f, 0x66c: 0x364c, 0x66d: 0x359e, 0x66e: 0x42eb, 0x66f: 0x0081, + 0x672: 0x3eb3, 0x673: 0x36fa, 0x674: 0x3ebb, + 0x676: 0x488b, 0x677: 0x3ed3, 0x678: 0x3640, 0x679: 0x4309, 0x67a: 0x3670, 0x67b: 0x431b, + 0x67c: 0x367c, 0x67d: 0x4259, 0x67e: 0xa100, + // Block 0x1a, offset 0x680 + 0x681: 0x3c09, 0x683: 0xa000, 0x684: 0x3c10, 0x685: 0xa000, + 0x687: 0x3c17, 0x688: 0xa000, 0x689: 0x3c1e, + 0x68d: 0xa000, + 0x6a0: 0x2f68, 0x6a1: 0xa000, 0x6a2: 0x3c2c, + 0x6a4: 0xa000, 0x6a5: 0xa000, + 0x6ad: 0x3c25, 0x6ae: 0x2f63, 0x6af: 0x2f6d, + 0x6b0: 0x3c33, 0x6b1: 0x3c3a, 0x6b2: 0xa000, 0x6b3: 0xa000, 0x6b4: 0x3c41, 0x6b5: 0x3c48, + 0x6b6: 0xa000, 0x6b7: 0xa000, 0x6b8: 0x3c4f, 0x6b9: 0x3c56, 0x6ba: 0xa000, 0x6bb: 0xa000, + 0x6bc: 0xa000, 0x6bd: 0xa000, + // Block 0x1b, offset 0x6c0 + 0x6c0: 0x3c5d, 0x6c1: 0x3c64, 0x6c2: 0xa000, 0x6c3: 0xa000, 0x6c4: 0x3c79, 0x6c5: 0x3c80, + 0x6c6: 0xa000, 0x6c7: 0xa000, 0x6c8: 0x3c87, 0x6c9: 0x3c8e, + 0x6d1: 0xa000, + 0x6d2: 0xa000, + 0x6e2: 0xa000, + 0x6e8: 0xa000, 0x6e9: 0xa000, + 0x6eb: 0xa000, 0x6ec: 0x3ca3, 0x6ed: 0x3caa, 0x6ee: 0x3cb1, 0x6ef: 0x3cb8, + 0x6f2: 0xa000, 0x6f3: 0xa000, 0x6f4: 0xa000, 0x6f5: 0xa000, + // Block 0x1c, offset 0x700 + 0x706: 0xa000, 0x70b: 0xa000, + 0x70c: 0x3f0b, 0x70d: 0xa000, 0x70e: 0x3f13, 0x70f: 0xa000, 0x710: 0x3f1b, 0x711: 0xa000, + 0x712: 0x3f23, 0x713: 0xa000, 0x714: 0x3f2b, 0x715: 0xa000, 0x716: 0x3f33, 0x717: 0xa000, + 0x718: 0x3f3b, 0x719: 0xa000, 0x71a: 0x3f43, 0x71b: 0xa000, 0x71c: 0x3f4b, 0x71d: 0xa000, + 0x71e: 0x3f53, 0x71f: 0xa000, 0x720: 0x3f5b, 0x721: 0xa000, 0x722: 0x3f63, + 0x724: 0xa000, 0x725: 0x3f6b, 0x726: 0xa000, 0x727: 0x3f73, 0x728: 0xa000, 0x729: 0x3f7b, + 0x72f: 0xa000, + 0x730: 0x3f83, 0x731: 0x3f8b, 0x732: 0xa000, 0x733: 0x3f93, 0x734: 0x3f9b, 0x735: 0xa000, + 0x736: 0x3fa3, 0x737: 0x3fab, 0x738: 0xa000, 0x739: 0x3fb3, 0x73a: 0x3fbb, 0x73b: 0xa000, + 0x73c: 0x3fc3, 0x73d: 0x3fcb, + // Block 0x1d, offset 0x740 + 0x754: 0x3f03, + 0x759: 0x9903, 0x75a: 0x9903, 0x75b: 0x8100, 0x75c: 0x8100, 0x75d: 0xa000, + 0x75e: 0x3fd3, + 0x766: 0xa000, + 0x76b: 0xa000, 0x76c: 0x3fe3, 0x76d: 0xa000, 0x76e: 0x3feb, 0x76f: 0xa000, + 0x770: 0x3ff3, 0x771: 0xa000, 0x772: 0x3ffb, 0x773: 0xa000, 0x774: 0x4003, 0x775: 0xa000, + 0x776: 0x400b, 0x777: 0xa000, 0x778: 0x4013, 0x779: 0xa000, 0x77a: 0x401b, 0x77b: 0xa000, + 0x77c: 0x4023, 0x77d: 0xa000, 0x77e: 0x402b, 0x77f: 0xa000, + // Block 0x1e, offset 0x780 + 0x780: 0x4033, 0x781: 0xa000, 0x782: 0x403b, 0x784: 0xa000, 0x785: 0x4043, + 0x786: 0xa000, 0x787: 0x404b, 0x788: 0xa000, 0x789: 0x4053, + 0x78f: 0xa000, 0x790: 0x405b, 0x791: 0x4063, + 0x792: 0xa000, 0x793: 0x406b, 0x794: 0x4073, 0x795: 0xa000, 0x796: 0x407b, 0x797: 0x4083, + 0x798: 0xa000, 0x799: 0x408b, 0x79a: 0x4093, 0x79b: 0xa000, 0x79c: 0x409b, 0x79d: 0x40a3, + 0x7af: 0xa000, + 0x7b0: 0xa000, 0x7b1: 0xa000, 0x7b2: 0xa000, 0x7b4: 0x3fdb, + 0x7b7: 0x40ab, 0x7b8: 0x40b3, 0x7b9: 0x40bb, 0x7ba: 0x40c3, + 0x7bd: 0xa000, 0x7be: 0x40cb, + // Block 0x1f, offset 0x7c0 + 0x7c0: 0x1377, 0x7c1: 0x0cfb, 0x7c2: 0x13d3, 0x7c3: 0x139f, 0x7c4: 0x0e57, 0x7c5: 0x06eb, + 0x7c6: 0x08df, 0x7c7: 0x162b, 0x7c8: 0x162b, 0x7c9: 0x0a0b, 0x7ca: 0x145f, 0x7cb: 0x0943, + 0x7cc: 0x0a07, 0x7cd: 0x0bef, 0x7ce: 0x0fcf, 0x7cf: 0x115f, 0x7d0: 0x1297, 0x7d1: 0x12d3, + 0x7d2: 0x1307, 0x7d3: 0x141b, 0x7d4: 0x0d73, 0x7d5: 0x0dff, 0x7d6: 0x0eab, 0x7d7: 0x0f43, + 0x7d8: 0x125f, 0x7d9: 0x1447, 0x7da: 0x1573, 0x7db: 0x070f, 0x7dc: 0x08b3, 0x7dd: 0x0d87, + 0x7de: 0x0ecf, 0x7df: 0x1293, 0x7e0: 0x15c3, 0x7e1: 0x0ab3, 0x7e2: 0x0e77, 0x7e3: 0x1283, + 0x7e4: 0x1317, 0x7e5: 0x0c23, 0x7e6: 0x11bb, 0x7e7: 0x12df, 0x7e8: 0x0b1f, 0x7e9: 0x0d0f, + 0x7ea: 0x0e17, 0x7eb: 0x0f1b, 0x7ec: 0x1427, 0x7ed: 0x074f, 0x7ee: 0x07e7, 0x7ef: 0x0853, + 0x7f0: 0x0c8b, 0x7f1: 0x0d7f, 0x7f2: 0x0ecb, 0x7f3: 0x0fef, 0x7f4: 0x1177, 0x7f5: 0x128b, + 0x7f6: 0x12a3, 0x7f7: 0x13c7, 0x7f8: 0x14ef, 0x7f9: 0x15a3, 0x7fa: 0x15bf, 0x7fb: 0x102b, + 0x7fc: 0x106b, 0x7fd: 0x1123, 0x7fe: 0x1243, 0x7ff: 0x147b, + // Block 0x20, offset 0x800 + 0x800: 0x15cb, 0x801: 0x134b, 0x802: 0x09c7, 0x803: 0x0b3b, 0x804: 0x10db, 0x805: 0x119b, + 0x806: 0x0eff, 0x807: 0x1033, 0x808: 0x1397, 0x809: 0x14e7, 0x80a: 0x09c3, 0x80b: 0x0a8f, + 0x80c: 0x0d77, 0x80d: 0x0e2b, 0x80e: 0x0e5f, 0x80f: 0x1113, 0x810: 0x113b, 0x811: 0x14a7, + 0x812: 0x084f, 0x813: 0x11a7, 0x814: 0x07f3, 0x815: 0x07ef, 0x816: 0x1097, 0x817: 0x1127, + 0x818: 0x125b, 0x819: 0x14af, 0x81a: 0x1367, 0x81b: 0x0c27, 0x81c: 0x0d73, 0x81d: 0x1357, + 0x81e: 0x06f7, 0x81f: 0x0a63, 0x820: 0x0b93, 0x821: 0x0f2f, 0x822: 0x0faf, 0x823: 0x0873, + 0x824: 0x103b, 0x825: 0x075f, 0x826: 0x0b77, 0x827: 0x06d7, 0x828: 0x0deb, 0x829: 0x0ca3, + 0x82a: 0x110f, 0x82b: 0x08c7, 0x82c: 0x09b3, 0x82d: 0x0ffb, 0x82e: 0x1263, 0x82f: 0x133b, + 0x830: 0x0db7, 0x831: 0x13f7, 0x832: 0x0de3, 0x833: 0x0c37, 0x834: 0x121b, 0x835: 0x0c57, + 0x836: 0x0fab, 0x837: 0x072b, 0x838: 0x07a7, 0x839: 0x07eb, 0x83a: 0x0d53, 0x83b: 0x10fb, + 0x83c: 0x11f3, 0x83d: 0x1347, 0x83e: 0x145b, 0x83f: 0x085b, + // Block 0x21, offset 0x840 + 0x840: 0x090f, 0x841: 0x0a17, 0x842: 0x0b2f, 0x843: 0x0cbf, 0x844: 0x0e7b, 0x845: 0x103f, + 0x846: 0x1497, 0x847: 0x157b, 0x848: 0x15cf, 0x849: 0x15e7, 0x84a: 0x0837, 0x84b: 0x0cf3, + 0x84c: 0x0da3, 0x84d: 0x13eb, 0x84e: 0x0afb, 0x84f: 0x0bd7, 0x850: 0x0bf3, 0x851: 0x0c83, + 0x852: 0x0e6b, 0x853: 0x0eb7, 0x854: 0x0f67, 0x855: 0x108b, 0x856: 0x112f, 0x857: 0x1193, + 0x858: 0x13db, 0x859: 0x126b, 0x85a: 0x1403, 0x85b: 0x147f, 0x85c: 0x080f, 0x85d: 0x083b, + 0x85e: 0x0923, 0x85f: 0x0ea7, 0x860: 0x12f3, 0x861: 0x133b, 0x862: 0x0b1b, 0x863: 0x0b8b, + 0x864: 0x0c4f, 0x865: 0x0daf, 0x866: 0x10d7, 0x867: 0x0f23, 0x868: 0x073b, 0x869: 0x097f, + 0x86a: 0x0a63, 0x86b: 0x0ac7, 0x86c: 0x0b97, 0x86d: 0x0f3f, 0x86e: 0x0f5b, 0x86f: 0x116b, + 0x870: 0x118b, 0x871: 0x1463, 0x872: 0x14e3, 0x873: 0x14f3, 0x874: 0x152f, 0x875: 0x0753, + 0x876: 0x107f, 0x877: 0x144f, 0x878: 0x14cb, 0x879: 0x0baf, 0x87a: 0x0717, 0x87b: 0x0777, + 0x87c: 0x0a67, 0x87d: 0x0a87, 0x87e: 0x0caf, 0x87f: 0x0d73, + // Block 0x22, offset 0x880 + 0x880: 0x0ec3, 0x881: 0x0fcb, 0x882: 0x1277, 0x883: 0x1417, 0x884: 0x1623, 0x885: 0x0ce3, + 0x886: 0x14a3, 0x887: 0x0833, 0x888: 0x0d2f, 0x889: 0x0d3b, 0x88a: 0x0e0f, 0x88b: 0x0e47, + 0x88c: 0x0f4b, 0x88d: 0x0fa7, 0x88e: 0x1027, 0x88f: 0x110b, 0x890: 0x153b, 0x891: 0x07af, + 0x892: 0x0c03, 0x893: 0x14b3, 0x894: 0x0767, 0x895: 0x0aab, 0x896: 0x0e2f, 0x897: 0x13df, + 0x898: 0x0b67, 0x899: 0x0bb7, 0x89a: 0x0d43, 0x89b: 0x0f2f, 0x89c: 0x14bb, 0x89d: 0x0817, + 0x89e: 0x08ff, 0x89f: 0x0a97, 0x8a0: 0x0cd3, 0x8a1: 0x0d1f, 0x8a2: 0x0d5f, 0x8a3: 0x0df3, + 0x8a4: 0x0f47, 0x8a5: 0x0fbb, 0x8a6: 0x1157, 0x8a7: 0x12f7, 0x8a8: 0x1303, 0x8a9: 0x1457, + 0x8aa: 0x14d7, 0x8ab: 0x0883, 0x8ac: 0x0e4b, 0x8ad: 0x0903, 0x8ae: 0x0ec7, 0x8af: 0x0f6b, + 0x8b0: 0x1287, 0x8b1: 0x14bf, 0x8b2: 0x15ab, 0x8b3: 0x15d3, 0x8b4: 0x0d37, 0x8b5: 0x0e27, + 0x8b6: 0x11c3, 0x8b7: 0x10b7, 0x8b8: 0x10c3, 0x8b9: 0x10e7, 0x8ba: 0x0f17, 0x8bb: 0x0e9f, + 0x8bc: 0x1363, 0x8bd: 0x0733, 0x8be: 0x122b, 0x8bf: 0x081b, + // Block 0x23, offset 0x8c0 + 0x8c0: 0x080b, 0x8c1: 0x0b0b, 0x8c2: 0x0c2b, 0x8c3: 0x10f3, 0x8c4: 0x0a53, 0x8c5: 0x0e03, + 0x8c6: 0x0cef, 0x8c7: 0x13e7, 0x8c8: 0x12e7, 0x8c9: 0x14ab, 0x8ca: 0x1323, 0x8cb: 0x0b27, + 0x8cc: 0x0787, 0x8cd: 0x095b, 0x8d0: 0x09af, + 0x8d2: 0x0cdf, 0x8d5: 0x07f7, 0x8d6: 0x0f1f, 0x8d7: 0x0fe3, + 0x8d8: 0x1047, 0x8d9: 0x1063, 0x8da: 0x1067, 0x8db: 0x107b, 0x8dc: 0x14fb, 0x8dd: 0x10eb, + 0x8de: 0x116f, 0x8e0: 0x128f, 0x8e2: 0x1353, + 0x8e5: 0x1407, 0x8e6: 0x1433, + 0x8ea: 0x154f, 0x8eb: 0x1553, 0x8ec: 0x1557, 0x8ed: 0x15bb, 0x8ee: 0x142b, 0x8ef: 0x14c7, + 0x8f0: 0x0757, 0x8f1: 0x077b, 0x8f2: 0x078f, 0x8f3: 0x084b, 0x8f4: 0x0857, 0x8f5: 0x0897, + 0x8f6: 0x094b, 0x8f7: 0x0967, 0x8f8: 0x096f, 0x8f9: 0x09ab, 0x8fa: 0x09b7, 0x8fb: 0x0a93, + 0x8fc: 0x0a9b, 0x8fd: 0x0ba3, 0x8fe: 0x0bcb, 0x8ff: 0x0bd3, + // Block 0x24, offset 0x900 + 0x900: 0x0beb, 0x901: 0x0c97, 0x902: 0x0cc7, 0x903: 0x0ce7, 0x904: 0x0d57, 0x905: 0x0e1b, + 0x906: 0x0e37, 0x907: 0x0e67, 0x908: 0x0ebb, 0x909: 0x0edb, 0x90a: 0x0f4f, 0x90b: 0x102f, + 0x90c: 0x104b, 0x90d: 0x1053, 0x90e: 0x104f, 0x90f: 0x1057, 0x910: 0x105b, 0x911: 0x105f, + 0x912: 0x1073, 0x913: 0x1077, 0x914: 0x109b, 0x915: 0x10af, 0x916: 0x10cb, 0x917: 0x112f, + 0x918: 0x1137, 0x919: 0x113f, 0x91a: 0x1153, 0x91b: 0x117b, 0x91c: 0x11cb, 0x91d: 0x11ff, + 0x91e: 0x11ff, 0x91f: 0x1267, 0x920: 0x130f, 0x921: 0x1327, 0x922: 0x135b, 0x923: 0x135f, + 0x924: 0x13a3, 0x925: 0x13a7, 0x926: 0x13ff, 0x927: 0x1407, 0x928: 0x14db, 0x929: 0x151f, + 0x92a: 0x1537, 0x92b: 0x0b9b, 0x92c: 0x171e, 0x92d: 0x11e3, + 0x930: 0x06df, 0x931: 0x07e3, 0x932: 0x07a3, 0x933: 0x074b, 0x934: 0x078b, 0x935: 0x07b7, + 0x936: 0x0847, 0x937: 0x0863, 0x938: 0x094b, 0x939: 0x0937, 0x93a: 0x0947, 0x93b: 0x0963, + 0x93c: 0x09af, 0x93d: 0x09bf, 0x93e: 0x0a03, 0x93f: 0x0a0f, + // Block 0x25, offset 0x940 + 0x940: 0x0a2b, 0x941: 0x0a3b, 0x942: 0x0b23, 0x943: 0x0b2b, 0x944: 0x0b5b, 0x945: 0x0b7b, + 0x946: 0x0bab, 0x947: 0x0bc3, 0x948: 0x0bb3, 0x949: 0x0bd3, 0x94a: 0x0bc7, 0x94b: 0x0beb, + 0x94c: 0x0c07, 0x94d: 0x0c5f, 0x94e: 0x0c6b, 0x94f: 0x0c73, 0x950: 0x0c9b, 0x951: 0x0cdf, + 0x952: 0x0d0f, 0x953: 0x0d13, 0x954: 0x0d27, 0x955: 0x0da7, 0x956: 0x0db7, 0x957: 0x0e0f, + 0x958: 0x0e5b, 0x959: 0x0e53, 0x95a: 0x0e67, 0x95b: 0x0e83, 0x95c: 0x0ebb, 0x95d: 0x1013, + 0x95e: 0x0edf, 0x95f: 0x0f13, 0x960: 0x0f1f, 0x961: 0x0f5f, 0x962: 0x0f7b, 0x963: 0x0f9f, + 0x964: 0x0fc3, 0x965: 0x0fc7, 0x966: 0x0fe3, 0x967: 0x0fe7, 0x968: 0x0ff7, 0x969: 0x100b, + 0x96a: 0x1007, 0x96b: 0x1037, 0x96c: 0x10b3, 0x96d: 0x10cb, 0x96e: 0x10e3, 0x96f: 0x111b, + 0x970: 0x112f, 0x971: 0x114b, 0x972: 0x117b, 0x973: 0x122f, 0x974: 0x1257, 0x975: 0x12cb, + 0x976: 0x1313, 0x977: 0x131f, 0x978: 0x1327, 0x979: 0x133f, 0x97a: 0x1353, 0x97b: 0x1343, + 0x97c: 0x135b, 0x97d: 0x1357, 0x97e: 0x134f, 0x97f: 0x135f, + // Block 0x26, offset 0x980 + 0x980: 0x136b, 0x981: 0x13a7, 0x982: 0x13e3, 0x983: 0x1413, 0x984: 0x144b, 0x985: 0x146b, + 0x986: 0x14b7, 0x987: 0x14db, 0x988: 0x14fb, 0x989: 0x150f, 0x98a: 0x151f, 0x98b: 0x152b, + 0x98c: 0x1537, 0x98d: 0x158b, 0x98e: 0x162b, 0x98f: 0x16b5, 0x990: 0x16b0, 0x991: 0x16e2, + 0x992: 0x0607, 0x993: 0x062f, 0x994: 0x0633, 0x995: 0x1764, 0x996: 0x1791, 0x997: 0x1809, + 0x998: 0x1617, 0x999: 0x1627, + // Block 0x27, offset 0x9c0 + 0x9c0: 0x06fb, 0x9c1: 0x06f3, 0x9c2: 0x0703, 0x9c3: 0x1647, 0x9c4: 0x0747, 0x9c5: 0x0757, + 0x9c6: 0x075b, 0x9c7: 0x0763, 0x9c8: 0x076b, 0x9c9: 0x076f, 0x9ca: 0x077b, 0x9cb: 0x0773, + 0x9cc: 0x05b3, 0x9cd: 0x165b, 0x9ce: 0x078f, 0x9cf: 0x0793, 0x9d0: 0x0797, 0x9d1: 0x07b3, + 0x9d2: 0x164c, 0x9d3: 0x05b7, 0x9d4: 0x079f, 0x9d5: 0x07bf, 0x9d6: 0x1656, 0x9d7: 0x07cf, + 0x9d8: 0x07d7, 0x9d9: 0x0737, 0x9da: 0x07df, 0x9db: 0x07e3, 0x9dc: 0x1831, 0x9dd: 0x07ff, + 0x9de: 0x0807, 0x9df: 0x05bf, 0x9e0: 0x081f, 0x9e1: 0x0823, 0x9e2: 0x082b, 0x9e3: 0x082f, + 0x9e4: 0x05c3, 0x9e5: 0x0847, 0x9e6: 0x084b, 0x9e7: 0x0857, 0x9e8: 0x0863, 0x9e9: 0x0867, + 0x9ea: 0x086b, 0x9eb: 0x0873, 0x9ec: 0x0893, 0x9ed: 0x0897, 0x9ee: 0x089f, 0x9ef: 0x08af, + 0x9f0: 0x08b7, 0x9f1: 0x08bb, 0x9f2: 0x08bb, 0x9f3: 0x08bb, 0x9f4: 0x166a, 0x9f5: 0x0e93, + 0x9f6: 0x08cf, 0x9f7: 0x08d7, 0x9f8: 0x166f, 0x9f9: 0x08e3, 0x9fa: 0x08eb, 0x9fb: 0x08f3, + 0x9fc: 0x091b, 0x9fd: 0x0907, 0x9fe: 0x0913, 0x9ff: 0x0917, + // Block 0x28, offset 0xa00 + 0xa00: 0x091f, 0xa01: 0x0927, 0xa02: 0x092b, 0xa03: 0x0933, 0xa04: 0x093b, 0xa05: 0x093f, + 0xa06: 0x093f, 0xa07: 0x0947, 0xa08: 0x094f, 0xa09: 0x0953, 0xa0a: 0x095f, 0xa0b: 0x0983, + 0xa0c: 0x0967, 0xa0d: 0x0987, 0xa0e: 0x096b, 0xa0f: 0x0973, 0xa10: 0x080b, 0xa11: 0x09cf, + 0xa12: 0x0997, 0xa13: 0x099b, 0xa14: 0x099f, 0xa15: 0x0993, 0xa16: 0x09a7, 0xa17: 0x09a3, + 0xa18: 0x09bb, 0xa19: 0x1674, 0xa1a: 0x09d7, 0xa1b: 0x09db, 0xa1c: 0x09e3, 0xa1d: 0x09ef, + 0xa1e: 0x09f7, 0xa1f: 0x0a13, 0xa20: 0x1679, 0xa21: 0x167e, 0xa22: 0x0a1f, 0xa23: 0x0a23, + 0xa24: 0x0a27, 0xa25: 0x0a1b, 0xa26: 0x0a2f, 0xa27: 0x05c7, 0xa28: 0x05cb, 0xa29: 0x0a37, + 0xa2a: 0x0a3f, 0xa2b: 0x0a3f, 0xa2c: 0x1683, 0xa2d: 0x0a5b, 0xa2e: 0x0a5f, 0xa2f: 0x0a63, + 0xa30: 0x0a6b, 0xa31: 0x1688, 0xa32: 0x0a73, 0xa33: 0x0a77, 0xa34: 0x0b4f, 0xa35: 0x0a7f, + 0xa36: 0x05cf, 0xa37: 0x0a8b, 0xa38: 0x0a9b, 0xa39: 0x0aa7, 0xa3a: 0x0aa3, 0xa3b: 0x1692, + 0xa3c: 0x0aaf, 0xa3d: 0x1697, 0xa3e: 0x0abb, 0xa3f: 0x0ab7, + // Block 0x29, offset 0xa40 + 0xa40: 0x0abf, 0xa41: 0x0acf, 0xa42: 0x0ad3, 0xa43: 0x05d3, 0xa44: 0x0ae3, 0xa45: 0x0aeb, + 0xa46: 0x0aef, 0xa47: 0x0af3, 0xa48: 0x05d7, 0xa49: 0x169c, 0xa4a: 0x05db, 0xa4b: 0x0b0f, + 0xa4c: 0x0b13, 0xa4d: 0x0b17, 0xa4e: 0x0b1f, 0xa4f: 0x1863, 0xa50: 0x0b37, 0xa51: 0x16a6, + 0xa52: 0x16a6, 0xa53: 0x11d7, 0xa54: 0x0b47, 0xa55: 0x0b47, 0xa56: 0x05df, 0xa57: 0x16c9, + 0xa58: 0x179b, 0xa59: 0x0b57, 0xa5a: 0x0b5f, 0xa5b: 0x05e3, 0xa5c: 0x0b73, 0xa5d: 0x0b83, + 0xa5e: 0x0b87, 0xa5f: 0x0b8f, 0xa60: 0x0b9f, 0xa61: 0x05eb, 0xa62: 0x05e7, 0xa63: 0x0ba3, + 0xa64: 0x16ab, 0xa65: 0x0ba7, 0xa66: 0x0bbb, 0xa67: 0x0bbf, 0xa68: 0x0bc3, 0xa69: 0x0bbf, + 0xa6a: 0x0bcf, 0xa6b: 0x0bd3, 0xa6c: 0x0be3, 0xa6d: 0x0bdb, 0xa6e: 0x0bdf, 0xa6f: 0x0be7, + 0xa70: 0x0beb, 0xa71: 0x0bef, 0xa72: 0x0bfb, 0xa73: 0x0bff, 0xa74: 0x0c17, 0xa75: 0x0c1f, + 0xa76: 0x0c2f, 0xa77: 0x0c43, 0xa78: 0x16ba, 0xa79: 0x0c3f, 0xa7a: 0x0c33, 0xa7b: 0x0c4b, + 0xa7c: 0x0c53, 0xa7d: 0x0c67, 0xa7e: 0x16bf, 0xa7f: 0x0c6f, + // Block 0x2a, offset 0xa80 + 0xa80: 0x0c63, 0xa81: 0x0c5b, 0xa82: 0x05ef, 0xa83: 0x0c77, 0xa84: 0x0c7f, 0xa85: 0x0c87, + 0xa86: 0x0c7b, 0xa87: 0x05f3, 0xa88: 0x0c97, 0xa89: 0x0c9f, 0xa8a: 0x16c4, 0xa8b: 0x0ccb, + 0xa8c: 0x0cff, 0xa8d: 0x0cdb, 0xa8e: 0x05ff, 0xa8f: 0x0ce7, 0xa90: 0x05fb, 0xa91: 0x05f7, + 0xa92: 0x07c3, 0xa93: 0x07c7, 0xa94: 0x0d03, 0xa95: 0x0ceb, 0xa96: 0x11ab, 0xa97: 0x0663, + 0xa98: 0x0d0f, 0xa99: 0x0d13, 0xa9a: 0x0d17, 0xa9b: 0x0d2b, 0xa9c: 0x0d23, 0xa9d: 0x16dd, + 0xa9e: 0x0603, 0xa9f: 0x0d3f, 0xaa0: 0x0d33, 0xaa1: 0x0d4f, 0xaa2: 0x0d57, 0xaa3: 0x16e7, + 0xaa4: 0x0d5b, 0xaa5: 0x0d47, 0xaa6: 0x0d63, 0xaa7: 0x0607, 0xaa8: 0x0d67, 0xaa9: 0x0d6b, + 0xaaa: 0x0d6f, 0xaab: 0x0d7b, 0xaac: 0x16ec, 0xaad: 0x0d83, 0xaae: 0x060b, 0xaaf: 0x0d8f, + 0xab0: 0x16f1, 0xab1: 0x0d93, 0xab2: 0x060f, 0xab3: 0x0d9f, 0xab4: 0x0dab, 0xab5: 0x0db7, + 0xab6: 0x0dbb, 0xab7: 0x16f6, 0xab8: 0x168d, 0xab9: 0x16fb, 0xaba: 0x0ddb, 0xabb: 0x1700, + 0xabc: 0x0de7, 0xabd: 0x0def, 0xabe: 0x0ddf, 0xabf: 0x0dfb, + // Block 0x2b, offset 0xac0 + 0xac0: 0x0e0b, 0xac1: 0x0e1b, 0xac2: 0x0e0f, 0xac3: 0x0e13, 0xac4: 0x0e1f, 0xac5: 0x0e23, + 0xac6: 0x1705, 0xac7: 0x0e07, 0xac8: 0x0e3b, 0xac9: 0x0e3f, 0xaca: 0x0613, 0xacb: 0x0e53, + 0xacc: 0x0e4f, 0xacd: 0x170a, 0xace: 0x0e33, 0xacf: 0x0e6f, 0xad0: 0x170f, 0xad1: 0x1714, + 0xad2: 0x0e73, 0xad3: 0x0e87, 0xad4: 0x0e83, 0xad5: 0x0e7f, 0xad6: 0x0617, 0xad7: 0x0e8b, + 0xad8: 0x0e9b, 0xad9: 0x0e97, 0xada: 0x0ea3, 0xadb: 0x1651, 0xadc: 0x0eb3, 0xadd: 0x1719, + 0xade: 0x0ebf, 0xadf: 0x1723, 0xae0: 0x0ed3, 0xae1: 0x0edf, 0xae2: 0x0ef3, 0xae3: 0x1728, + 0xae4: 0x0f07, 0xae5: 0x0f0b, 0xae6: 0x172d, 0xae7: 0x1732, 0xae8: 0x0f27, 0xae9: 0x0f37, + 0xaea: 0x061b, 0xaeb: 0x0f3b, 0xaec: 0x061f, 0xaed: 0x061f, 0xaee: 0x0f53, 0xaef: 0x0f57, + 0xaf0: 0x0f5f, 0xaf1: 0x0f63, 0xaf2: 0x0f6f, 0xaf3: 0x0623, 0xaf4: 0x0f87, 0xaf5: 0x1737, + 0xaf6: 0x0fa3, 0xaf7: 0x173c, 0xaf8: 0x0faf, 0xaf9: 0x16a1, 0xafa: 0x0fbf, 0xafb: 0x1741, + 0xafc: 0x1746, 0xafd: 0x174b, 0xafe: 0x0627, 0xaff: 0x062b, + // Block 0x2c, offset 0xb00 + 0xb00: 0x0ff7, 0xb01: 0x1755, 0xb02: 0x1750, 0xb03: 0x175a, 0xb04: 0x175f, 0xb05: 0x0fff, + 0xb06: 0x1003, 0xb07: 0x1003, 0xb08: 0x100b, 0xb09: 0x0633, 0xb0a: 0x100f, 0xb0b: 0x0637, + 0xb0c: 0x063b, 0xb0d: 0x1769, 0xb0e: 0x1023, 0xb0f: 0x102b, 0xb10: 0x1037, 0xb11: 0x063f, + 0xb12: 0x176e, 0xb13: 0x105b, 0xb14: 0x1773, 0xb15: 0x1778, 0xb16: 0x107b, 0xb17: 0x1093, + 0xb18: 0x0643, 0xb19: 0x109b, 0xb1a: 0x109f, 0xb1b: 0x10a3, 0xb1c: 0x177d, 0xb1d: 0x1782, + 0xb1e: 0x1782, 0xb1f: 0x10bb, 0xb20: 0x0647, 0xb21: 0x1787, 0xb22: 0x10cf, 0xb23: 0x10d3, + 0xb24: 0x064b, 0xb25: 0x178c, 0xb26: 0x10ef, 0xb27: 0x064f, 0xb28: 0x10ff, 0xb29: 0x10f7, + 0xb2a: 0x1107, 0xb2b: 0x1796, 0xb2c: 0x111f, 0xb2d: 0x0653, 0xb2e: 0x112b, 0xb2f: 0x1133, + 0xb30: 0x1143, 0xb31: 0x0657, 0xb32: 0x17a0, 0xb33: 0x17a5, 0xb34: 0x065b, 0xb35: 0x17aa, + 0xb36: 0x115b, 0xb37: 0x17af, 0xb38: 0x1167, 0xb39: 0x1173, 0xb3a: 0x117b, 0xb3b: 0x17b4, + 0xb3c: 0x17b9, 0xb3d: 0x118f, 0xb3e: 0x17be, 0xb3f: 0x1197, + // Block 0x2d, offset 0xb40 + 0xb40: 0x16ce, 0xb41: 0x065f, 0xb42: 0x11af, 0xb43: 0x11b3, 0xb44: 0x0667, 0xb45: 0x11b7, + 0xb46: 0x0a33, 0xb47: 0x17c3, 0xb48: 0x17c8, 0xb49: 0x16d3, 0xb4a: 0x16d8, 0xb4b: 0x11d7, + 0xb4c: 0x11db, 0xb4d: 0x13f3, 0xb4e: 0x066b, 0xb4f: 0x1207, 0xb50: 0x1203, 0xb51: 0x120b, + 0xb52: 0x083f, 0xb53: 0x120f, 0xb54: 0x1213, 0xb55: 0x1217, 0xb56: 0x121f, 0xb57: 0x17cd, + 0xb58: 0x121b, 0xb59: 0x1223, 0xb5a: 0x1237, 0xb5b: 0x123b, 0xb5c: 0x1227, 0xb5d: 0x123f, + 0xb5e: 0x1253, 0xb5f: 0x1267, 0xb60: 0x1233, 0xb61: 0x1247, 0xb62: 0x124b, 0xb63: 0x124f, + 0xb64: 0x17d2, 0xb65: 0x17dc, 0xb66: 0x17d7, 0xb67: 0x066f, 0xb68: 0x126f, 0xb69: 0x1273, + 0xb6a: 0x127b, 0xb6b: 0x17f0, 0xb6c: 0x127f, 0xb6d: 0x17e1, 0xb6e: 0x0673, 0xb6f: 0x0677, + 0xb70: 0x17e6, 0xb71: 0x17eb, 0xb72: 0x067b, 0xb73: 0x129f, 0xb74: 0x12a3, 0xb75: 0x12a7, + 0xb76: 0x12ab, 0xb77: 0x12b7, 0xb78: 0x12b3, 0xb79: 0x12bf, 0xb7a: 0x12bb, 0xb7b: 0x12cb, + 0xb7c: 0x12c3, 0xb7d: 0x12c7, 0xb7e: 0x12cf, 0xb7f: 0x067f, + // Block 0x2e, offset 0xb80 + 0xb80: 0x12d7, 0xb81: 0x12db, 0xb82: 0x0683, 0xb83: 0x12eb, 0xb84: 0x12ef, 0xb85: 0x17f5, + 0xb86: 0x12fb, 0xb87: 0x12ff, 0xb88: 0x0687, 0xb89: 0x130b, 0xb8a: 0x05bb, 0xb8b: 0x17fa, + 0xb8c: 0x17ff, 0xb8d: 0x068b, 0xb8e: 0x068f, 0xb8f: 0x1337, 0xb90: 0x134f, 0xb91: 0x136b, + 0xb92: 0x137b, 0xb93: 0x1804, 0xb94: 0x138f, 0xb95: 0x1393, 0xb96: 0x13ab, 0xb97: 0x13b7, + 0xb98: 0x180e, 0xb99: 0x1660, 0xb9a: 0x13c3, 0xb9b: 0x13bf, 0xb9c: 0x13cb, 0xb9d: 0x1665, + 0xb9e: 0x13d7, 0xb9f: 0x13e3, 0xba0: 0x1813, 0xba1: 0x1818, 0xba2: 0x1423, 0xba3: 0x142f, + 0xba4: 0x1437, 0xba5: 0x181d, 0xba6: 0x143b, 0xba7: 0x1467, 0xba8: 0x1473, 0xba9: 0x1477, + 0xbaa: 0x146f, 0xbab: 0x1483, 0xbac: 0x1487, 0xbad: 0x1822, 0xbae: 0x1493, 0xbaf: 0x0693, + 0xbb0: 0x149b, 0xbb1: 0x1827, 0xbb2: 0x0697, 0xbb3: 0x14d3, 0xbb4: 0x0ac3, 0xbb5: 0x14eb, + 0xbb6: 0x182c, 0xbb7: 0x1836, 0xbb8: 0x069b, 0xbb9: 0x069f, 0xbba: 0x1513, 0xbbb: 0x183b, + 0xbbc: 0x06a3, 0xbbd: 0x1840, 0xbbe: 0x152b, 0xbbf: 0x152b, + // Block 0x2f, offset 0xbc0 + 0xbc0: 0x1533, 0xbc1: 0x1845, 0xbc2: 0x154b, 0xbc3: 0x06a7, 0xbc4: 0x155b, 0xbc5: 0x1567, + 0xbc6: 0x156f, 0xbc7: 0x1577, 0xbc8: 0x06ab, 0xbc9: 0x184a, 0xbca: 0x158b, 0xbcb: 0x15a7, + 0xbcc: 0x15b3, 0xbcd: 0x06af, 0xbce: 0x06b3, 0xbcf: 0x15b7, 0xbd0: 0x184f, 0xbd1: 0x06b7, + 0xbd2: 0x1854, 0xbd3: 0x1859, 0xbd4: 0x185e, 0xbd5: 0x15db, 0xbd6: 0x06bb, 0xbd7: 0x15ef, + 0xbd8: 0x15f7, 0xbd9: 0x15fb, 0xbda: 0x1603, 0xbdb: 0x160b, 0xbdc: 0x1613, 0xbdd: 0x1868, +} + +// nfcIndex: 22 blocks, 1408 entries, 1408 bytes +// Block 0 is the zero block. +var nfcIndex = [1408]uint8{ + // Block 0x0, offset 0x0 + // Block 0x1, offset 0x40 + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc2: 0x2e, 0xc3: 0x01, 0xc4: 0x02, 0xc5: 0x03, 0xc6: 0x2f, 0xc7: 0x04, + 0xc8: 0x05, 0xca: 0x30, 0xcb: 0x31, 0xcc: 0x06, 0xcd: 0x07, 0xce: 0x08, 0xcf: 0x32, + 0xd0: 0x09, 0xd1: 0x33, 0xd2: 0x34, 0xd3: 0x0a, 0xd6: 0x0b, 0xd7: 0x35, + 0xd8: 0x36, 0xd9: 0x0c, 0xdb: 0x37, 0xdc: 0x38, 0xdd: 0x39, 0xdf: 0x3a, + 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05, + 0xea: 0x06, 0xeb: 0x07, 0xec: 0x08, 0xed: 0x09, 0xef: 0x0a, + 0xf0: 0x13, + // Block 0x4, offset 0x100 + 0x120: 0x3b, 0x121: 0x3c, 0x123: 0x0d, 0x124: 0x3d, 0x125: 0x3e, 0x126: 0x3f, 0x127: 0x40, + 0x128: 0x41, 0x129: 0x42, 0x12a: 0x43, 0x12b: 0x44, 0x12c: 0x3f, 0x12d: 0x45, 0x12e: 0x46, 0x12f: 0x47, + 0x131: 0x48, 0x132: 0x49, 0x133: 0x4a, 0x134: 0x4b, 0x135: 0x4c, 0x137: 0x4d, + 0x138: 0x4e, 0x139: 0x4f, 0x13a: 0x50, 0x13b: 0x51, 0x13c: 0x52, 0x13d: 0x53, 0x13e: 0x54, 0x13f: 0x55, + // Block 0x5, offset 0x140 + 0x140: 0x56, 0x142: 0x57, 0x144: 0x58, 0x145: 0x59, 0x146: 0x5a, 0x147: 0x5b, + 0x14d: 0x5c, + 0x15c: 0x5d, 0x15f: 0x5e, + 0x162: 0x5f, 0x164: 0x60, + 0x168: 0x61, 0x169: 0x62, 0x16a: 0x63, 0x16c: 0x0e, 0x16d: 0x64, 0x16e: 0x65, 0x16f: 0x66, + 0x170: 0x67, 0x173: 0x68, 0x177: 0x0f, + 0x178: 0x10, 0x179: 0x11, 0x17a: 0x12, 0x17b: 0x13, 0x17c: 0x14, 0x17d: 0x15, 0x17e: 0x16, 0x17f: 0x17, + // Block 0x6, offset 0x180 + 0x180: 0x69, 0x183: 0x6a, 0x184: 0x6b, 0x186: 0x6c, 0x187: 0x6d, + 0x188: 0x6e, 0x189: 0x18, 0x18a: 0x19, 0x18b: 0x6f, 0x18c: 0x70, + 0x1ab: 0x71, + 0x1b3: 0x72, 0x1b5: 0x73, 0x1b7: 0x74, + // Block 0x7, offset 0x1c0 + 0x1c0: 0x75, 0x1c1: 0x1a, 0x1c2: 0x1b, 0x1c3: 0x1c, 0x1c4: 0x76, 0x1c5: 0x77, + 0x1c9: 0x78, 0x1cc: 0x79, 0x1cd: 0x7a, + // Block 0x8, offset 0x200 + 0x219: 0x7b, 0x21a: 0x7c, 0x21b: 0x7d, + 0x220: 0x7e, 0x223: 0x7f, 0x224: 0x80, 0x225: 0x81, 0x226: 0x82, 0x227: 0x83, + 0x22a: 0x84, 0x22b: 0x85, 0x22f: 0x86, + 0x230: 0x87, 0x231: 0x88, 0x232: 0x89, 0x233: 0x8a, 0x234: 0x8b, 0x235: 0x8c, 0x236: 0x8d, 0x237: 0x87, + 0x238: 0x88, 0x239: 0x89, 0x23a: 0x8a, 0x23b: 0x8b, 0x23c: 0x8c, 0x23d: 0x8d, 0x23e: 0x87, 0x23f: 0x88, + // Block 0x9, offset 0x240 + 0x240: 0x89, 0x241: 0x8a, 0x242: 0x8b, 0x243: 0x8c, 0x244: 0x8d, 0x245: 0x87, 0x246: 0x88, 0x247: 0x89, + 0x248: 0x8a, 0x249: 0x8b, 0x24a: 0x8c, 0x24b: 0x8d, 0x24c: 0x87, 0x24d: 0x88, 0x24e: 0x89, 0x24f: 0x8a, + 0x250: 0x8b, 0x251: 0x8c, 0x252: 0x8d, 0x253: 0x87, 0x254: 0x88, 0x255: 0x89, 0x256: 0x8a, 0x257: 0x8b, + 0x258: 0x8c, 0x259: 0x8d, 0x25a: 0x87, 0x25b: 0x88, 0x25c: 0x89, 0x25d: 0x8a, 0x25e: 0x8b, 0x25f: 0x8c, + 0x260: 0x8d, 0x261: 0x87, 0x262: 0x88, 0x263: 0x89, 0x264: 0x8a, 0x265: 0x8b, 0x266: 0x8c, 0x267: 0x8d, + 0x268: 0x87, 0x269: 0x88, 0x26a: 0x89, 0x26b: 0x8a, 0x26c: 0x8b, 0x26d: 0x8c, 0x26e: 0x8d, 0x26f: 0x87, + 0x270: 0x88, 0x271: 0x89, 0x272: 0x8a, 0x273: 0x8b, 0x274: 0x8c, 0x275: 0x8d, 0x276: 0x87, 0x277: 0x88, + 0x278: 0x89, 0x279: 0x8a, 0x27a: 0x8b, 0x27b: 0x8c, 0x27c: 0x8d, 0x27d: 0x87, 0x27e: 0x88, 0x27f: 0x89, + // Block 0xa, offset 0x280 + 0x280: 0x8a, 0x281: 0x8b, 0x282: 0x8c, 0x283: 0x8d, 0x284: 0x87, 0x285: 0x88, 0x286: 0x89, 0x287: 0x8a, + 0x288: 0x8b, 0x289: 0x8c, 0x28a: 0x8d, 0x28b: 0x87, 0x28c: 0x88, 0x28d: 0x89, 0x28e: 0x8a, 0x28f: 0x8b, + 0x290: 0x8c, 0x291: 0x8d, 0x292: 0x87, 0x293: 0x88, 0x294: 0x89, 0x295: 0x8a, 0x296: 0x8b, 0x297: 0x8c, + 0x298: 0x8d, 0x299: 0x87, 0x29a: 0x88, 0x29b: 0x89, 0x29c: 0x8a, 0x29d: 0x8b, 0x29e: 0x8c, 0x29f: 0x8d, + 0x2a0: 0x87, 0x2a1: 0x88, 0x2a2: 0x89, 0x2a3: 0x8a, 0x2a4: 0x8b, 0x2a5: 0x8c, 0x2a6: 0x8d, 0x2a7: 0x87, + 0x2a8: 0x88, 0x2a9: 0x89, 0x2aa: 0x8a, 0x2ab: 0x8b, 0x2ac: 0x8c, 0x2ad: 0x8d, 0x2ae: 0x87, 0x2af: 0x88, + 0x2b0: 0x89, 0x2b1: 0x8a, 0x2b2: 0x8b, 0x2b3: 0x8c, 0x2b4: 0x8d, 0x2b5: 0x87, 0x2b6: 0x88, 0x2b7: 0x89, + 0x2b8: 0x8a, 0x2b9: 0x8b, 0x2ba: 0x8c, 0x2bb: 0x8d, 0x2bc: 0x87, 0x2bd: 0x88, 0x2be: 0x89, 0x2bf: 0x8a, + // Block 0xb, offset 0x2c0 + 0x2c0: 0x8b, 0x2c1: 0x8c, 0x2c2: 0x8d, 0x2c3: 0x87, 0x2c4: 0x88, 0x2c5: 0x89, 0x2c6: 0x8a, 0x2c7: 0x8b, + 0x2c8: 0x8c, 0x2c9: 0x8d, 0x2ca: 0x87, 0x2cb: 0x88, 0x2cc: 0x89, 0x2cd: 0x8a, 0x2ce: 0x8b, 0x2cf: 0x8c, + 0x2d0: 0x8d, 0x2d1: 0x87, 0x2d2: 0x88, 0x2d3: 0x89, 0x2d4: 0x8a, 0x2d5: 0x8b, 0x2d6: 0x8c, 0x2d7: 0x8d, + 0x2d8: 0x87, 0x2d9: 0x88, 0x2da: 0x89, 0x2db: 0x8a, 0x2dc: 0x8b, 0x2dd: 0x8c, 0x2de: 0x8e, + // Block 0xc, offset 0x300 + 0x324: 0x1d, 0x325: 0x1e, 0x326: 0x1f, 0x327: 0x20, + 0x328: 0x21, 0x329: 0x22, 0x32a: 0x23, 0x32b: 0x24, 0x32c: 0x8f, 0x32d: 0x90, 0x32e: 0x91, + 0x331: 0x92, 0x332: 0x93, 0x333: 0x94, 0x334: 0x95, + 0x338: 0x96, 0x339: 0x97, 0x33a: 0x98, 0x33b: 0x99, 0x33e: 0x9a, 0x33f: 0x9b, + // Block 0xd, offset 0x340 + 0x347: 0x9c, + 0x34b: 0x9d, 0x34d: 0x9e, + 0x368: 0x9f, 0x36b: 0xa0, + 0x374: 0xa1, + 0x37d: 0xa2, + // Block 0xe, offset 0x380 + 0x381: 0xa3, 0x382: 0xa4, 0x384: 0xa5, 0x385: 0x82, 0x387: 0xa6, + 0x388: 0xa7, 0x38b: 0xa8, 0x38c: 0xa9, 0x38d: 0xaa, + 0x391: 0xab, 0x392: 0xac, 0x393: 0xad, 0x396: 0xae, 0x397: 0xaf, + 0x398: 0x73, 0x39a: 0xb0, 0x39c: 0xb1, + 0x3a0: 0xb2, 0x3a7: 0xb3, + 0x3a8: 0xb4, 0x3a9: 0xb5, 0x3aa: 0xb6, + 0x3b0: 0x73, 0x3b5: 0xb7, 0x3b6: 0xb8, + // Block 0xf, offset 0x3c0 + 0x3eb: 0xb9, 0x3ec: 0xba, + // Block 0x10, offset 0x400 + 0x432: 0xbb, + // Block 0x11, offset 0x440 + 0x445: 0xbc, 0x446: 0xbd, 0x447: 0xbe, + 0x449: 0xbf, + // Block 0x12, offset 0x480 + 0x480: 0xc0, 0x484: 0xba, + 0x48b: 0xc1, + 0x4a3: 0xc2, 0x4a5: 0xc3, + // Block 0x13, offset 0x4c0 + 0x4c8: 0xc4, + // Block 0x14, offset 0x500 + 0x520: 0x25, 0x521: 0x26, 0x522: 0x27, 0x523: 0x28, 0x524: 0x29, 0x525: 0x2a, 0x526: 0x2b, 0x527: 0x2c, + 0x528: 0x2d, + // Block 0x15, offset 0x540 + 0x550: 0x0b, 0x551: 0x0c, 0x556: 0x0d, + 0x55b: 0x0e, 0x55d: 0x0f, 0x55e: 0x10, 0x55f: 0x11, + 0x56f: 0x12, +} + +// nfcSparseOffset: 151 entries, 302 bytes +var nfcSparseOffset = []uint16{0x0, 0x5, 0x9, 0xb, 0xd, 0x18, 0x28, 0x2a, 0x2f, 0x3a, 0x49, 0x56, 0x5e, 0x63, 0x68, 0x6a, 0x72, 0x79, 0x7c, 0x84, 0x88, 0x8c, 0x8e, 0x90, 0x99, 0x9d, 0xa4, 0xa9, 0xac, 0xb6, 0xb9, 0xc0, 0xc8, 0xcb, 0xcd, 0xd0, 0xd2, 0xd7, 0xe8, 0xf4, 0xf6, 0xfc, 0xfe, 0x100, 0x102, 0x104, 0x106, 0x108, 0x10b, 0x10e, 0x110, 0x113, 0x116, 0x11a, 0x11f, 0x128, 0x12a, 0x12d, 0x12f, 0x13a, 0x13e, 0x14c, 0x14f, 0x155, 0x15b, 0x166, 0x16a, 0x16c, 0x16e, 0x170, 0x172, 0x174, 0x17a, 0x17e, 0x180, 0x182, 0x18a, 0x18e, 0x191, 0x193, 0x195, 0x197, 0x19a, 0x19c, 0x19e, 0x1a0, 0x1a2, 0x1a8, 0x1ab, 0x1ad, 0x1b4, 0x1ba, 0x1c0, 0x1c8, 0x1ce, 0x1d4, 0x1da, 0x1de, 0x1ec, 0x1f5, 0x1f8, 0x1fb, 0x1fd, 0x200, 0x202, 0x206, 0x20b, 0x20d, 0x20f, 0x214, 0x21a, 0x21c, 0x21e, 0x220, 0x226, 0x229, 0x22b, 0x231, 0x234, 0x23c, 0x243, 0x246, 0x249, 0x24b, 0x24e, 0x256, 0x25a, 0x261, 0x264, 0x26a, 0x26c, 0x26f, 0x271, 0x274, 0x276, 0x278, 0x27a, 0x27c, 0x27f, 0x281, 0x283, 0x285, 0x287, 0x294, 0x29e, 0x2a0, 0x2a2, 0x2a8, 0x2aa, 0x2ac, 0x2af} + +// nfcSparseValues: 689 entries, 2756 bytes +var nfcSparseValues = [689]valueRange{ + // Block 0x0, offset 0x0 + {value: 0x0000, lo: 0x04}, + {value: 0xa100, lo: 0xa8, hi: 0xa8}, + {value: 0x8100, lo: 0xaf, hi: 0xaf}, + {value: 0x8100, lo: 0xb4, hi: 0xb4}, + {value: 0x8100, lo: 0xb8, hi: 0xb8}, + // Block 0x1, offset 0x5 + {value: 0x0091, lo: 0x03}, + {value: 0x46e5, lo: 0xa0, hi: 0xa1}, + {value: 0x4717, lo: 0xaf, hi: 0xb0}, + {value: 0xa000, lo: 0xb7, hi: 0xb7}, + // Block 0x2, offset 0x9 + {value: 0x0000, lo: 0x01}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + // Block 0x3, offset 0xb + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0x98, hi: 0x9d}, + // Block 0x4, offset 0xd + {value: 0x0006, lo: 0x0a}, + {value: 0xa000, lo: 0x81, hi: 0x81}, + {value: 0xa000, lo: 0x85, hi: 0x85}, + {value: 0xa000, lo: 0x89, hi: 0x89}, + {value: 0x4843, lo: 0x8a, hi: 0x8a}, + {value: 0x4861, lo: 0x8b, hi: 0x8b}, + {value: 0x36ca, lo: 0x8c, hi: 0x8c}, + {value: 0x36e2, lo: 0x8d, hi: 0x8d}, + {value: 0x4879, lo: 0x8e, hi: 0x8e}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x3700, lo: 0x93, hi: 0x94}, + // Block 0x5, offset 0x18 + {value: 0x0000, lo: 0x0f}, + {value: 0xa000, lo: 0x83, hi: 0x83}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0xa000, lo: 0x8b, hi: 0x8b}, + {value: 0xa000, lo: 0x8d, hi: 0x8d}, + {value: 0x37a8, lo: 0x90, hi: 0x90}, + {value: 0x37b4, lo: 0x91, hi: 0x91}, + {value: 0x37a2, lo: 0x93, hi: 0x93}, + {value: 0xa000, lo: 0x96, hi: 0x96}, + {value: 0x381a, lo: 0x97, hi: 0x97}, + {value: 0x37e4, lo: 0x9c, hi: 0x9c}, + {value: 0x37cc, lo: 0x9d, hi: 0x9d}, + {value: 0x37f6, lo: 0x9e, hi: 0x9e}, + {value: 0xa000, lo: 0xb4, hi: 0xb5}, + {value: 0x3820, lo: 0xb6, hi: 0xb6}, + {value: 0x3826, lo: 0xb7, hi: 0xb7}, + // Block 0x6, offset 0x28 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x83, hi: 0x87}, + // Block 0x7, offset 0x2a + {value: 0x0001, lo: 0x04}, + {value: 0x8113, lo: 0x81, hi: 0x82}, + {value: 0x8132, lo: 0x84, hi: 0x84}, + {value: 0x812d, lo: 0x85, hi: 0x85}, + {value: 0x810d, lo: 0x87, hi: 0x87}, + // Block 0x8, offset 0x2f + {value: 0x0000, lo: 0x0a}, + {value: 0x8132, lo: 0x90, hi: 0x97}, + {value: 0x8119, lo: 0x98, hi: 0x98}, + {value: 0x811a, lo: 0x99, hi: 0x99}, + {value: 0x811b, lo: 0x9a, hi: 0x9a}, + {value: 0x3844, lo: 0xa2, hi: 0xa2}, + {value: 0x384a, lo: 0xa3, hi: 0xa3}, + {value: 0x3856, lo: 0xa4, hi: 0xa4}, + {value: 0x3850, lo: 0xa5, hi: 0xa5}, + {value: 0x385c, lo: 0xa6, hi: 0xa6}, + {value: 0xa000, lo: 0xa7, hi: 0xa7}, + // Block 0x9, offset 0x3a + {value: 0x0000, lo: 0x0e}, + {value: 0x386e, lo: 0x80, hi: 0x80}, + {value: 0xa000, lo: 0x81, hi: 0x81}, + {value: 0x3862, lo: 0x82, hi: 0x82}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x3868, lo: 0x93, hi: 0x93}, + {value: 0xa000, lo: 0x95, hi: 0x95}, + {value: 0x8132, lo: 0x96, hi: 0x9c}, + {value: 0x8132, lo: 0x9f, hi: 0xa2}, + {value: 0x812d, lo: 0xa3, hi: 0xa3}, + {value: 0x8132, lo: 0xa4, hi: 0xa4}, + {value: 0x8132, lo: 0xa7, hi: 0xa8}, + {value: 0x812d, lo: 0xaa, hi: 0xaa}, + {value: 0x8132, lo: 0xab, hi: 0xac}, + {value: 0x812d, lo: 0xad, hi: 0xad}, + // Block 0xa, offset 0x49 + {value: 0x0000, lo: 0x0c}, + {value: 0x811f, lo: 0x91, hi: 0x91}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + {value: 0x812d, lo: 0xb1, hi: 0xb1}, + {value: 0x8132, lo: 0xb2, hi: 0xb3}, + {value: 0x812d, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb5, hi: 0xb6}, + {value: 0x812d, lo: 0xb7, hi: 0xb9}, + {value: 0x8132, lo: 0xba, hi: 0xba}, + {value: 0x812d, lo: 0xbb, hi: 0xbc}, + {value: 0x8132, lo: 0xbd, hi: 0xbd}, + {value: 0x812d, lo: 0xbe, hi: 0xbe}, + {value: 0x8132, lo: 0xbf, hi: 0xbf}, + // Block 0xb, offset 0x56 + {value: 0x0005, lo: 0x07}, + {value: 0x8132, lo: 0x80, hi: 0x80}, + {value: 0x8132, lo: 0x81, hi: 0x81}, + {value: 0x812d, lo: 0x82, hi: 0x83}, + {value: 0x812d, lo: 0x84, hi: 0x85}, + {value: 0x812d, lo: 0x86, hi: 0x87}, + {value: 0x812d, lo: 0x88, hi: 0x89}, + {value: 0x8132, lo: 0x8a, hi: 0x8a}, + // Block 0xc, offset 0x5e + {value: 0x0000, lo: 0x04}, + {value: 0x8132, lo: 0xab, hi: 0xb1}, + {value: 0x812d, lo: 0xb2, hi: 0xb2}, + {value: 0x8132, lo: 0xb3, hi: 0xb3}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + // Block 0xd, offset 0x63 + {value: 0x0000, lo: 0x04}, + {value: 0x8132, lo: 0x96, hi: 0x99}, + {value: 0x8132, lo: 0x9b, hi: 0xa3}, + {value: 0x8132, lo: 0xa5, hi: 0xa7}, + {value: 0x8132, lo: 0xa9, hi: 0xad}, + // Block 0xe, offset 0x68 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x99, hi: 0x9b}, + // Block 0xf, offset 0x6a + {value: 0x0000, lo: 0x07}, + {value: 0xa000, lo: 0xa8, hi: 0xa8}, + {value: 0x3edb, lo: 0xa9, hi: 0xa9}, + {value: 0xa000, lo: 0xb0, hi: 0xb0}, + {value: 0x3ee3, lo: 0xb1, hi: 0xb1}, + {value: 0xa000, lo: 0xb3, hi: 0xb3}, + {value: 0x3eeb, lo: 0xb4, hi: 0xb4}, + {value: 0x9902, lo: 0xbc, hi: 0xbc}, + // Block 0x10, offset 0x72 + {value: 0x0008, lo: 0x06}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x8132, lo: 0x91, hi: 0x91}, + {value: 0x812d, lo: 0x92, hi: 0x92}, + {value: 0x8132, lo: 0x93, hi: 0x93}, + {value: 0x8132, lo: 0x94, hi: 0x94}, + {value: 0x451f, lo: 0x98, hi: 0x9f}, + // Block 0x11, offset 0x79 + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x12, offset 0x7c + {value: 0x0008, lo: 0x07}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2ca1, lo: 0x8b, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + {value: 0x455f, lo: 0x9c, hi: 0x9d}, + {value: 0x456f, lo: 0x9f, hi: 0x9f}, + {value: 0x8132, lo: 0xbe, hi: 0xbe}, + // Block 0x13, offset 0x84 + {value: 0x0000, lo: 0x03}, + {value: 0x4597, lo: 0xb3, hi: 0xb3}, + {value: 0x459f, lo: 0xb6, hi: 0xb6}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + // Block 0x14, offset 0x88 + {value: 0x0008, lo: 0x03}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x4577, lo: 0x99, hi: 0x9b}, + {value: 0x458f, lo: 0x9e, hi: 0x9e}, + // Block 0x15, offset 0x8c + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + // Block 0x16, offset 0x8e + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + // Block 0x17, offset 0x90 + {value: 0x0000, lo: 0x08}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2cb9, lo: 0x88, hi: 0x88}, + {value: 0x2cb1, lo: 0x8b, hi: 0x8b}, + {value: 0x2cc1, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x96, hi: 0x97}, + {value: 0x45a7, lo: 0x9c, hi: 0x9c}, + {value: 0x45af, lo: 0x9d, hi: 0x9d}, + // Block 0x18, offset 0x99 + {value: 0x0000, lo: 0x03}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x2cc9, lo: 0x94, hi: 0x94}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x19, offset 0x9d + {value: 0x0000, lo: 0x06}, + {value: 0xa000, lo: 0x86, hi: 0x87}, + {value: 0x2cd1, lo: 0x8a, hi: 0x8a}, + {value: 0x2ce1, lo: 0x8b, hi: 0x8b}, + {value: 0x2cd9, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + // Block 0x1a, offset 0xa4 + {value: 0x1801, lo: 0x04}, + {value: 0xa000, lo: 0x86, hi: 0x86}, + {value: 0x3ef3, lo: 0x88, hi: 0x88}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x8120, lo: 0x95, hi: 0x96}, + // Block 0x1b, offset 0xa9 + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + {value: 0xa000, lo: 0xbf, hi: 0xbf}, + // Block 0x1c, offset 0xac + {value: 0x0000, lo: 0x09}, + {value: 0x2ce9, lo: 0x80, hi: 0x80}, + {value: 0x9900, lo: 0x82, hi: 0x82}, + {value: 0xa000, lo: 0x86, hi: 0x86}, + {value: 0x2cf1, lo: 0x87, hi: 0x87}, + {value: 0x2cf9, lo: 0x88, hi: 0x88}, + {value: 0x2f53, lo: 0x8a, hi: 0x8a}, + {value: 0x2ddb, lo: 0x8b, hi: 0x8b}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x95, hi: 0x96}, + // Block 0x1d, offset 0xb6 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xbb, hi: 0xbc}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x1e, offset 0xb9 + {value: 0x0000, lo: 0x06}, + {value: 0xa000, lo: 0x86, hi: 0x87}, + {value: 0x2d01, lo: 0x8a, hi: 0x8a}, + {value: 0x2d11, lo: 0x8b, hi: 0x8b}, + {value: 0x2d09, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + // Block 0x1f, offset 0xc0 + {value: 0x6be7, lo: 0x07}, + {value: 0x9904, lo: 0x8a, hi: 0x8a}, + {value: 0x9900, lo: 0x8f, hi: 0x8f}, + {value: 0xa000, lo: 0x99, hi: 0x99}, + {value: 0x3efb, lo: 0x9a, hi: 0x9a}, + {value: 0x2f5b, lo: 0x9c, hi: 0x9c}, + {value: 0x2de6, lo: 0x9d, hi: 0x9d}, + {value: 0x2d19, lo: 0x9e, hi: 0x9f}, + // Block 0x20, offset 0xc8 + {value: 0x0000, lo: 0x02}, + {value: 0x8122, lo: 0xb8, hi: 0xb9}, + {value: 0x8104, lo: 0xba, hi: 0xba}, + // Block 0x21, offset 0xcb + {value: 0x0000, lo: 0x01}, + {value: 0x8123, lo: 0x88, hi: 0x8b}, + // Block 0x22, offset 0xcd + {value: 0x0000, lo: 0x02}, + {value: 0x8124, lo: 0xb8, hi: 0xb9}, + {value: 0x8104, lo: 0xba, hi: 0xba}, + // Block 0x23, offset 0xd0 + {value: 0x0000, lo: 0x01}, + {value: 0x8125, lo: 0x88, hi: 0x8b}, + // Block 0x24, offset 0xd2 + {value: 0x0000, lo: 0x04}, + {value: 0x812d, lo: 0x98, hi: 0x99}, + {value: 0x812d, lo: 0xb5, hi: 0xb5}, + {value: 0x812d, lo: 0xb7, hi: 0xb7}, + {value: 0x812b, lo: 0xb9, hi: 0xb9}, + // Block 0x25, offset 0xd7 + {value: 0x0000, lo: 0x10}, + {value: 0x2647, lo: 0x83, hi: 0x83}, + {value: 0x264e, lo: 0x8d, hi: 0x8d}, + {value: 0x2655, lo: 0x92, hi: 0x92}, + {value: 0x265c, lo: 0x97, hi: 0x97}, + {value: 0x2663, lo: 0x9c, hi: 0x9c}, + {value: 0x2640, lo: 0xa9, hi: 0xa9}, + {value: 0x8126, lo: 0xb1, hi: 0xb1}, + {value: 0x8127, lo: 0xb2, hi: 0xb2}, + {value: 0x4a87, lo: 0xb3, hi: 0xb3}, + {value: 0x8128, lo: 0xb4, hi: 0xb4}, + {value: 0x4a90, lo: 0xb5, hi: 0xb5}, + {value: 0x45b7, lo: 0xb6, hi: 0xb6}, + {value: 0x8200, lo: 0xb7, hi: 0xb7}, + {value: 0x45bf, lo: 0xb8, hi: 0xb8}, + {value: 0x8200, lo: 0xb9, hi: 0xb9}, + {value: 0x8127, lo: 0xba, hi: 0xbd}, + // Block 0x26, offset 0xe8 + {value: 0x0000, lo: 0x0b}, + {value: 0x8127, lo: 0x80, hi: 0x80}, + {value: 0x4a99, lo: 0x81, hi: 0x81}, + {value: 0x8132, lo: 0x82, hi: 0x83}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0x86, hi: 0x87}, + {value: 0x2671, lo: 0x93, hi: 0x93}, + {value: 0x2678, lo: 0x9d, hi: 0x9d}, + {value: 0x267f, lo: 0xa2, hi: 0xa2}, + {value: 0x2686, lo: 0xa7, hi: 0xa7}, + {value: 0x268d, lo: 0xac, hi: 0xac}, + {value: 0x266a, lo: 0xb9, hi: 0xb9}, + // Block 0x27, offset 0xf4 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x86, hi: 0x86}, + // Block 0x28, offset 0xf6 + {value: 0x0000, lo: 0x05}, + {value: 0xa000, lo: 0xa5, hi: 0xa5}, + {value: 0x2d21, lo: 0xa6, hi: 0xa6}, + {value: 0x9900, lo: 0xae, hi: 0xae}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + {value: 0x8104, lo: 0xb9, hi: 0xba}, + // Block 0x29, offset 0xfc + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x8d, hi: 0x8d}, + // Block 0x2a, offset 0xfe + {value: 0x0000, lo: 0x01}, + {value: 0xa000, lo: 0x80, hi: 0x92}, + // Block 0x2b, offset 0x100 + {value: 0x0000, lo: 0x01}, + {value: 0xb900, lo: 0xa1, hi: 0xb5}, + // Block 0x2c, offset 0x102 + {value: 0x0000, lo: 0x01}, + {value: 0x9900, lo: 0xa8, hi: 0xbf}, + // Block 0x2d, offset 0x104 + {value: 0x0000, lo: 0x01}, + {value: 0x9900, lo: 0x80, hi: 0x82}, + // Block 0x2e, offset 0x106 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x9d, hi: 0x9f}, + // Block 0x2f, offset 0x108 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x94, hi: 0x94}, + {value: 0x8104, lo: 0xb4, hi: 0xb4}, + // Block 0x30, offset 0x10b + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x92, hi: 0x92}, + {value: 0x8132, lo: 0x9d, hi: 0x9d}, + // Block 0x31, offset 0x10e + {value: 0x0000, lo: 0x01}, + {value: 0x8131, lo: 0xa9, hi: 0xa9}, + // Block 0x32, offset 0x110 + {value: 0x0004, lo: 0x02}, + {value: 0x812e, lo: 0xb9, hi: 0xba}, + {value: 0x812d, lo: 0xbb, hi: 0xbb}, + // Block 0x33, offset 0x113 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x97, hi: 0x97}, + {value: 0x812d, lo: 0x98, hi: 0x98}, + // Block 0x34, offset 0x116 + {value: 0x0000, lo: 0x03}, + {value: 0x8104, lo: 0xa0, hi: 0xa0}, + {value: 0x8132, lo: 0xb5, hi: 0xbc}, + {value: 0x812d, lo: 0xbf, hi: 0xbf}, + // Block 0x35, offset 0x11a + {value: 0x0000, lo: 0x04}, + {value: 0x8132, lo: 0xb0, hi: 0xb4}, + {value: 0x812d, lo: 0xb5, hi: 0xba}, + {value: 0x8132, lo: 0xbb, hi: 0xbc}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + // Block 0x36, offset 0x11f + {value: 0x0000, lo: 0x08}, + {value: 0x2d69, lo: 0x80, hi: 0x80}, + {value: 0x2d71, lo: 0x81, hi: 0x81}, + {value: 0xa000, lo: 0x82, hi: 0x82}, + {value: 0x2d79, lo: 0x83, hi: 0x83}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0xab, hi: 0xab}, + {value: 0x812d, lo: 0xac, hi: 0xac}, + {value: 0x8132, lo: 0xad, hi: 0xb3}, + // Block 0x37, offset 0x128 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xaa, hi: 0xab}, + // Block 0x38, offset 0x12a + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xa6, hi: 0xa6}, + {value: 0x8104, lo: 0xb2, hi: 0xb3}, + // Block 0x39, offset 0x12d + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + // Block 0x3a, offset 0x12f + {value: 0x0000, lo: 0x0a}, + {value: 0x8132, lo: 0x90, hi: 0x92}, + {value: 0x8101, lo: 0x94, hi: 0x94}, + {value: 0x812d, lo: 0x95, hi: 0x99}, + {value: 0x8132, lo: 0x9a, hi: 0x9b}, + {value: 0x812d, lo: 0x9c, hi: 0x9f}, + {value: 0x8132, lo: 0xa0, hi: 0xa0}, + {value: 0x8101, lo: 0xa2, hi: 0xa8}, + {value: 0x812d, lo: 0xad, hi: 0xad}, + {value: 0x8132, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb8, hi: 0xb9}, + // Block 0x3b, offset 0x13a + {value: 0x0004, lo: 0x03}, + {value: 0x0433, lo: 0x80, hi: 0x81}, + {value: 0x8100, lo: 0x97, hi: 0x97}, + {value: 0x8100, lo: 0xbe, hi: 0xbe}, + // Block 0x3c, offset 0x13e + {value: 0x0000, lo: 0x0d}, + {value: 0x8132, lo: 0x90, hi: 0x91}, + {value: 0x8101, lo: 0x92, hi: 0x93}, + {value: 0x8132, lo: 0x94, hi: 0x97}, + {value: 0x8101, lo: 0x98, hi: 0x9a}, + {value: 0x8132, lo: 0x9b, hi: 0x9c}, + {value: 0x8132, lo: 0xa1, hi: 0xa1}, + {value: 0x8101, lo: 0xa5, hi: 0xa6}, + {value: 0x8132, lo: 0xa7, hi: 0xa7}, + {value: 0x812d, lo: 0xa8, hi: 0xa8}, + {value: 0x8132, lo: 0xa9, hi: 0xa9}, + {value: 0x8101, lo: 0xaa, hi: 0xab}, + {value: 0x812d, lo: 0xac, hi: 0xaf}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + // Block 0x3d, offset 0x14c + {value: 0x427e, lo: 0x02}, + {value: 0x01b8, lo: 0xa6, hi: 0xa6}, + {value: 0x0057, lo: 0xaa, hi: 0xab}, + // Block 0x3e, offset 0x14f + {value: 0x0007, lo: 0x05}, + {value: 0xa000, lo: 0x90, hi: 0x90}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0xa000, lo: 0x94, hi: 0x94}, + {value: 0x3bbc, lo: 0x9a, hi: 0x9b}, + {value: 0x3bca, lo: 0xae, hi: 0xae}, + // Block 0x3f, offset 0x155 + {value: 0x000e, lo: 0x05}, + {value: 0x3bd1, lo: 0x8d, hi: 0x8e}, + {value: 0x3bd8, lo: 0x8f, hi: 0x8f}, + {value: 0xa000, lo: 0x90, hi: 0x90}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0xa000, lo: 0x94, hi: 0x94}, + // Block 0x40, offset 0x15b + {value: 0x6405, lo: 0x0a}, + {value: 0xa000, lo: 0x83, hi: 0x83}, + {value: 0x3be6, lo: 0x84, hi: 0x84}, + {value: 0xa000, lo: 0x88, hi: 0x88}, + {value: 0x3bed, lo: 0x89, hi: 0x89}, + {value: 0xa000, lo: 0x8b, hi: 0x8b}, + {value: 0x3bf4, lo: 0x8c, hi: 0x8c}, + {value: 0xa000, lo: 0xa3, hi: 0xa3}, + {value: 0x3bfb, lo: 0xa4, hi: 0xa5}, + {value: 0x3c02, lo: 0xa6, hi: 0xa6}, + {value: 0xa000, lo: 0xbc, hi: 0xbc}, + // Block 0x41, offset 0x166 + {value: 0x0007, lo: 0x03}, + {value: 0x3c6b, lo: 0xa0, hi: 0xa1}, + {value: 0x3c95, lo: 0xa2, hi: 0xa3}, + {value: 0x3cbf, lo: 0xaa, hi: 0xad}, + // Block 0x42, offset 0x16a + {value: 0x0004, lo: 0x01}, + {value: 0x048b, lo: 0xa9, hi: 0xaa}, + // Block 0x43, offset 0x16c + {value: 0x0000, lo: 0x01}, + {value: 0x44e0, lo: 0x9c, hi: 0x9c}, + // Block 0x44, offset 0x16e + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xaf, hi: 0xb1}, + // Block 0x45, offset 0x170 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x46, offset 0x172 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xa0, hi: 0xbf}, + // Block 0x47, offset 0x174 + {value: 0x0000, lo: 0x05}, + {value: 0x812c, lo: 0xaa, hi: 0xaa}, + {value: 0x8131, lo: 0xab, hi: 0xab}, + {value: 0x8133, lo: 0xac, hi: 0xac}, + {value: 0x812e, lo: 0xad, hi: 0xad}, + {value: 0x812f, lo: 0xae, hi: 0xaf}, + // Block 0x48, offset 0x17a + {value: 0x0000, lo: 0x03}, + {value: 0x4aa2, lo: 0xb3, hi: 0xb3}, + {value: 0x4aa2, lo: 0xb5, hi: 0xb6}, + {value: 0x4aa2, lo: 0xba, hi: 0xbf}, + // Block 0x49, offset 0x17e + {value: 0x0000, lo: 0x01}, + {value: 0x4aa2, lo: 0x8f, hi: 0xa3}, + // Block 0x4a, offset 0x180 + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0xae, hi: 0xbe}, + // Block 0x4b, offset 0x182 + {value: 0x0000, lo: 0x07}, + {value: 0x8100, lo: 0x84, hi: 0x84}, + {value: 0x8100, lo: 0x87, hi: 0x87}, + {value: 0x8100, lo: 0x90, hi: 0x90}, + {value: 0x8100, lo: 0x9e, hi: 0x9e}, + {value: 0x8100, lo: 0xa1, hi: 0xa1}, + {value: 0x8100, lo: 0xb2, hi: 0xb2}, + {value: 0x8100, lo: 0xbb, hi: 0xbb}, + // Block 0x4c, offset 0x18a + {value: 0x0000, lo: 0x03}, + {value: 0x8100, lo: 0x80, hi: 0x80}, + {value: 0x8100, lo: 0x8b, hi: 0x8b}, + {value: 0x8100, lo: 0x8e, hi: 0x8e}, + // Block 0x4d, offset 0x18e + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0xaf, hi: 0xaf}, + {value: 0x8132, lo: 0xb4, hi: 0xbd}, + // Block 0x4e, offset 0x191 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x9e, hi: 0x9f}, + // Block 0x4f, offset 0x193 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb0, hi: 0xb1}, + // Block 0x50, offset 0x195 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x86, hi: 0x86}, + // Block 0x51, offset 0x197 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0xa0, hi: 0xb1}, + // Block 0x52, offset 0x19a + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xab, hi: 0xad}, + // Block 0x53, offset 0x19c + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x93, hi: 0x93}, + // Block 0x54, offset 0x19e + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xb3, hi: 0xb3}, + // Block 0x55, offset 0x1a0 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x80, hi: 0x80}, + // Block 0x56, offset 0x1a2 + {value: 0x0000, lo: 0x05}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + {value: 0x8132, lo: 0xb2, hi: 0xb3}, + {value: 0x812d, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb7, hi: 0xb8}, + {value: 0x8132, lo: 0xbe, hi: 0xbf}, + // Block 0x57, offset 0x1a8 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x81, hi: 0x81}, + {value: 0x8104, lo: 0xb6, hi: 0xb6}, + // Block 0x58, offset 0x1ab + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xad, hi: 0xad}, + // Block 0x59, offset 0x1ad + {value: 0x0000, lo: 0x06}, + {value: 0xe500, lo: 0x80, hi: 0x80}, + {value: 0xc600, lo: 0x81, hi: 0x9b}, + {value: 0xe500, lo: 0x9c, hi: 0x9c}, + {value: 0xc600, lo: 0x9d, hi: 0xb7}, + {value: 0xe500, lo: 0xb8, hi: 0xb8}, + {value: 0xc600, lo: 0xb9, hi: 0xbf}, + // Block 0x5a, offset 0x1b4 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x93}, + {value: 0xe500, lo: 0x94, hi: 0x94}, + {value: 0xc600, lo: 0x95, hi: 0xaf}, + {value: 0xe500, lo: 0xb0, hi: 0xb0}, + {value: 0xc600, lo: 0xb1, hi: 0xbf}, + // Block 0x5b, offset 0x1ba + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x8b}, + {value: 0xe500, lo: 0x8c, hi: 0x8c}, + {value: 0xc600, lo: 0x8d, hi: 0xa7}, + {value: 0xe500, lo: 0xa8, hi: 0xa8}, + {value: 0xc600, lo: 0xa9, hi: 0xbf}, + // Block 0x5c, offset 0x1c0 + {value: 0x0000, lo: 0x07}, + {value: 0xc600, lo: 0x80, hi: 0x83}, + {value: 0xe500, lo: 0x84, hi: 0x84}, + {value: 0xc600, lo: 0x85, hi: 0x9f}, + {value: 0xe500, lo: 0xa0, hi: 0xa0}, + {value: 0xc600, lo: 0xa1, hi: 0xbb}, + {value: 0xe500, lo: 0xbc, hi: 0xbc}, + {value: 0xc600, lo: 0xbd, hi: 0xbf}, + // Block 0x5d, offset 0x1c8 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x97}, + {value: 0xe500, lo: 0x98, hi: 0x98}, + {value: 0xc600, lo: 0x99, hi: 0xb3}, + {value: 0xe500, lo: 0xb4, hi: 0xb4}, + {value: 0xc600, lo: 0xb5, hi: 0xbf}, + // Block 0x5e, offset 0x1ce + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x8f}, + {value: 0xe500, lo: 0x90, hi: 0x90}, + {value: 0xc600, lo: 0x91, hi: 0xab}, + {value: 0xe500, lo: 0xac, hi: 0xac}, + {value: 0xc600, lo: 0xad, hi: 0xbf}, + // Block 0x5f, offset 0x1d4 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x87}, + {value: 0xe500, lo: 0x88, hi: 0x88}, + {value: 0xc600, lo: 0x89, hi: 0xa3}, + {value: 0xe500, lo: 0xa4, hi: 0xa4}, + {value: 0xc600, lo: 0xa5, hi: 0xbf}, + // Block 0x60, offset 0x1da + {value: 0x0000, lo: 0x03}, + {value: 0xc600, lo: 0x80, hi: 0x87}, + {value: 0xe500, lo: 0x88, hi: 0x88}, + {value: 0xc600, lo: 0x89, hi: 0xa3}, + // Block 0x61, offset 0x1de + {value: 0x0006, lo: 0x0d}, + {value: 0x4393, lo: 0x9d, hi: 0x9d}, + {value: 0x8115, lo: 0x9e, hi: 0x9e}, + {value: 0x4405, lo: 0x9f, hi: 0x9f}, + {value: 0x43f3, lo: 0xaa, hi: 0xab}, + {value: 0x44f7, lo: 0xac, hi: 0xac}, + {value: 0x44ff, lo: 0xad, hi: 0xad}, + {value: 0x434b, lo: 0xae, hi: 0xb1}, + {value: 0x4369, lo: 0xb2, hi: 0xb4}, + {value: 0x4381, lo: 0xb5, hi: 0xb6}, + {value: 0x438d, lo: 0xb8, hi: 0xb8}, + {value: 0x4399, lo: 0xb9, hi: 0xbb}, + {value: 0x43b1, lo: 0xbc, hi: 0xbc}, + {value: 0x43b7, lo: 0xbe, hi: 0xbe}, + // Block 0x62, offset 0x1ec + {value: 0x0006, lo: 0x08}, + {value: 0x43bd, lo: 0x80, hi: 0x81}, + {value: 0x43c9, lo: 0x83, hi: 0x84}, + {value: 0x43db, lo: 0x86, hi: 0x89}, + {value: 0x43ff, lo: 0x8a, hi: 0x8a}, + {value: 0x437b, lo: 0x8b, hi: 0x8b}, + {value: 0x4363, lo: 0x8c, hi: 0x8c}, + {value: 0x43ab, lo: 0x8d, hi: 0x8d}, + {value: 0x43d5, lo: 0x8e, hi: 0x8e}, + // Block 0x63, offset 0x1f5 + {value: 0x0000, lo: 0x02}, + {value: 0x8100, lo: 0xa4, hi: 0xa5}, + {value: 0x8100, lo: 0xb0, hi: 0xb1}, + // Block 0x64, offset 0x1f8 + {value: 0x0000, lo: 0x02}, + {value: 0x8100, lo: 0x9b, hi: 0x9d}, + {value: 0x8200, lo: 0x9e, hi: 0xa3}, + // Block 0x65, offset 0x1fb + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0x90, hi: 0x90}, + // Block 0x66, offset 0x1fd + {value: 0x0000, lo: 0x02}, + {value: 0x8100, lo: 0x99, hi: 0x99}, + {value: 0x8200, lo: 0xb2, hi: 0xb4}, + // Block 0x67, offset 0x200 + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0xbc, hi: 0xbd}, + // Block 0x68, offset 0x202 + {value: 0x0000, lo: 0x03}, + {value: 0x8132, lo: 0xa0, hi: 0xa6}, + {value: 0x812d, lo: 0xa7, hi: 0xad}, + {value: 0x8132, lo: 0xae, hi: 0xaf}, + // Block 0x69, offset 0x206 + {value: 0x0000, lo: 0x04}, + {value: 0x8100, lo: 0x89, hi: 0x8c}, + {value: 0x8100, lo: 0xb0, hi: 0xb2}, + {value: 0x8100, lo: 0xb4, hi: 0xb4}, + {value: 0x8100, lo: 0xb6, hi: 0xbf}, + // Block 0x6a, offset 0x20b + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0x81, hi: 0x8c}, + // Block 0x6b, offset 0x20d + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0xb5, hi: 0xba}, + // Block 0x6c, offset 0x20f + {value: 0x0000, lo: 0x04}, + {value: 0x4aa2, lo: 0x9e, hi: 0x9f}, + {value: 0x4aa2, lo: 0xa3, hi: 0xa3}, + {value: 0x4aa2, lo: 0xa5, hi: 0xa6}, + {value: 0x4aa2, lo: 0xaa, hi: 0xaf}, + // Block 0x6d, offset 0x214 + {value: 0x0000, lo: 0x05}, + {value: 0x4aa2, lo: 0x82, hi: 0x87}, + {value: 0x4aa2, lo: 0x8a, hi: 0x8f}, + {value: 0x4aa2, lo: 0x92, hi: 0x97}, + {value: 0x4aa2, lo: 0x9a, hi: 0x9c}, + {value: 0x8100, lo: 0xa3, hi: 0xa3}, + // Block 0x6e, offset 0x21a + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + // Block 0x6f, offset 0x21c + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xa0, hi: 0xa0}, + // Block 0x70, offset 0x21e + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb6, hi: 0xba}, + // Block 0x71, offset 0x220 + {value: 0x002c, lo: 0x05}, + {value: 0x812d, lo: 0x8d, hi: 0x8d}, + {value: 0x8132, lo: 0x8f, hi: 0x8f}, + {value: 0x8132, lo: 0xb8, hi: 0xb8}, + {value: 0x8101, lo: 0xb9, hi: 0xba}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x72, offset 0x226 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0xa5, hi: 0xa5}, + {value: 0x812d, lo: 0xa6, hi: 0xa6}, + // Block 0x73, offset 0x229 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xa4, hi: 0xa7}, + // Block 0x74, offset 0x22b + {value: 0x0000, lo: 0x05}, + {value: 0x812d, lo: 0x86, hi: 0x87}, + {value: 0x8132, lo: 0x88, hi: 0x8a}, + {value: 0x812d, lo: 0x8b, hi: 0x8b}, + {value: 0x8132, lo: 0x8c, hi: 0x8c}, + {value: 0x812d, lo: 0x8d, hi: 0x90}, + // Block 0x75, offset 0x231 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x86, hi: 0x86}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x76, offset 0x234 + {value: 0x17fe, lo: 0x07}, + {value: 0xa000, lo: 0x99, hi: 0x99}, + {value: 0x423b, lo: 0x9a, hi: 0x9a}, + {value: 0xa000, lo: 0x9b, hi: 0x9b}, + {value: 0x4245, lo: 0x9c, hi: 0x9c}, + {value: 0xa000, lo: 0xa5, hi: 0xa5}, + {value: 0x424f, lo: 0xab, hi: 0xab}, + {value: 0x8104, lo: 0xb9, hi: 0xba}, + // Block 0x77, offset 0x23c + {value: 0x0000, lo: 0x06}, + {value: 0x8132, lo: 0x80, hi: 0x82}, + {value: 0x9900, lo: 0xa7, hi: 0xa7}, + {value: 0x2d81, lo: 0xae, hi: 0xae}, + {value: 0x2d8b, lo: 0xaf, hi: 0xaf}, + {value: 0xa000, lo: 0xb1, hi: 0xb2}, + {value: 0x8104, lo: 0xb3, hi: 0xb4}, + // Block 0x78, offset 0x243 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x80, hi: 0x80}, + {value: 0x8102, lo: 0x8a, hi: 0x8a}, + // Block 0x79, offset 0x246 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xb5, hi: 0xb5}, + {value: 0x8102, lo: 0xb6, hi: 0xb6}, + // Block 0x7a, offset 0x249 + {value: 0x0002, lo: 0x01}, + {value: 0x8102, lo: 0xa9, hi: 0xaa}, + // Block 0x7b, offset 0x24b + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xbb, hi: 0xbc}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x7c, offset 0x24e + {value: 0x0000, lo: 0x07}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2d95, lo: 0x8b, hi: 0x8b}, + {value: 0x2d9f, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + {value: 0x8132, lo: 0xa6, hi: 0xac}, + {value: 0x8132, lo: 0xb0, hi: 0xb4}, + // Block 0x7d, offset 0x256 + {value: 0x0000, lo: 0x03}, + {value: 0x8104, lo: 0x82, hi: 0x82}, + {value: 0x8102, lo: 0x86, hi: 0x86}, + {value: 0x8132, lo: 0x9e, hi: 0x9e}, + // Block 0x7e, offset 0x25a + {value: 0x6b57, lo: 0x06}, + {value: 0x9900, lo: 0xb0, hi: 0xb0}, + {value: 0xa000, lo: 0xb9, hi: 0xb9}, + {value: 0x9900, lo: 0xba, hi: 0xba}, + {value: 0x2db3, lo: 0xbb, hi: 0xbb}, + {value: 0x2da9, lo: 0xbc, hi: 0xbd}, + {value: 0x2dbd, lo: 0xbe, hi: 0xbe}, + // Block 0x7f, offset 0x261 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x82, hi: 0x82}, + {value: 0x8102, lo: 0x83, hi: 0x83}, + // Block 0x80, offset 0x264 + {value: 0x0000, lo: 0x05}, + {value: 0x9900, lo: 0xaf, hi: 0xaf}, + {value: 0xa000, lo: 0xb8, hi: 0xb9}, + {value: 0x2dc7, lo: 0xba, hi: 0xba}, + {value: 0x2dd1, lo: 0xbb, hi: 0xbb}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x81, offset 0x26a + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0x80, hi: 0x80}, + // Block 0x82, offset 0x26c + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xb6, hi: 0xb6}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + // Block 0x83, offset 0x26f + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xab, hi: 0xab}, + // Block 0x84, offset 0x271 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xb9, hi: 0xb9}, + {value: 0x8102, lo: 0xba, hi: 0xba}, + // Block 0x85, offset 0x274 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xa0, hi: 0xa0}, + // Block 0x86, offset 0x276 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xb4, hi: 0xb4}, + // Block 0x87, offset 0x278 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x87, hi: 0x87}, + // Block 0x88, offset 0x27a + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x99, hi: 0x99}, + // Block 0x89, offset 0x27c + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0x82, hi: 0x82}, + {value: 0x8104, lo: 0x84, hi: 0x85}, + // Block 0x8a, offset 0x27f + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x97, hi: 0x97}, + // Block 0x8b, offset 0x281 + {value: 0x0000, lo: 0x01}, + {value: 0x8101, lo: 0xb0, hi: 0xb4}, + // Block 0x8c, offset 0x283 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb0, hi: 0xb6}, + // Block 0x8d, offset 0x285 + {value: 0x0000, lo: 0x01}, + {value: 0x8101, lo: 0x9e, hi: 0x9e}, + // Block 0x8e, offset 0x287 + {value: 0x0000, lo: 0x0c}, + {value: 0x45cf, lo: 0x9e, hi: 0x9e}, + {value: 0x45d9, lo: 0x9f, hi: 0x9f}, + {value: 0x460d, lo: 0xa0, hi: 0xa0}, + {value: 0x461b, lo: 0xa1, hi: 0xa1}, + {value: 0x4629, lo: 0xa2, hi: 0xa2}, + {value: 0x4637, lo: 0xa3, hi: 0xa3}, + {value: 0x4645, lo: 0xa4, hi: 0xa4}, + {value: 0x812b, lo: 0xa5, hi: 0xa6}, + {value: 0x8101, lo: 0xa7, hi: 0xa9}, + {value: 0x8130, lo: 0xad, hi: 0xad}, + {value: 0x812b, lo: 0xae, hi: 0xb2}, + {value: 0x812d, lo: 0xbb, hi: 0xbf}, + // Block 0x8f, offset 0x294 + {value: 0x0000, lo: 0x09}, + {value: 0x812d, lo: 0x80, hi: 0x82}, + {value: 0x8132, lo: 0x85, hi: 0x89}, + {value: 0x812d, lo: 0x8a, hi: 0x8b}, + {value: 0x8132, lo: 0xaa, hi: 0xad}, + {value: 0x45e3, lo: 0xbb, hi: 0xbb}, + {value: 0x45ed, lo: 0xbc, hi: 0xbc}, + {value: 0x4653, lo: 0xbd, hi: 0xbd}, + {value: 0x466f, lo: 0xbe, hi: 0xbe}, + {value: 0x4661, lo: 0xbf, hi: 0xbf}, + // Block 0x90, offset 0x29e + {value: 0x0000, lo: 0x01}, + {value: 0x467d, lo: 0x80, hi: 0x80}, + // Block 0x91, offset 0x2a0 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x82, hi: 0x84}, + // Block 0x92, offset 0x2a2 + {value: 0x0000, lo: 0x05}, + {value: 0x8132, lo: 0x80, hi: 0x86}, + {value: 0x8132, lo: 0x88, hi: 0x98}, + {value: 0x8132, lo: 0x9b, hi: 0xa1}, + {value: 0x8132, lo: 0xa3, hi: 0xa4}, + {value: 0x8132, lo: 0xa6, hi: 0xaa}, + // Block 0x93, offset 0x2a8 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xac, hi: 0xaf}, + // Block 0x94, offset 0x2aa + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x90, hi: 0x96}, + // Block 0x95, offset 0x2ac + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x84, hi: 0x89}, + {value: 0x8102, lo: 0x8a, hi: 0x8a}, + // Block 0x96, offset 0x2af + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0x93, hi: 0x93}, +} + +// lookup returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *nfkcTrie) lookup(s []byte) (v uint16, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return nfkcValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfkcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfkcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = nfkcIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *nfkcTrie) lookupUnsafe(s []byte) uint16 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return nfkcValues[c0] + } + i := nfkcIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = nfkcIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = nfkcIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// lookupString returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *nfkcTrie) lookupString(s string) (v uint16, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return nfkcValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfkcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfkcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = nfkcIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *nfkcTrie) lookupStringUnsafe(s string) uint16 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return nfkcValues[c0] + } + i := nfkcIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = nfkcIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = nfkcIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// nfkcTrie. Total size: 18684 bytes (18.25 KiB). Checksum: 113e23c477adfabd. +type nfkcTrie struct{} + +func newNfkcTrie(i int) *nfkcTrie { + return &nfkcTrie{} +} + +// lookupValue determines the type of block n and looks up the value for b. +func (t *nfkcTrie) lookupValue(n uint32, b byte) uint16 { + switch { + case n < 92: + return uint16(nfkcValues[n<<6+uint32(b)]) + default: + n -= 92 + return uint16(nfkcSparse.lookup(n, b)) + } +} + +// nfkcValues: 94 blocks, 6016 entries, 12032 bytes +// The third block is the zero block. +var nfkcValues = [6016]uint16{ + // Block 0x0, offset 0x0 + 0x3c: 0xa000, 0x3d: 0xa000, 0x3e: 0xa000, + // Block 0x1, offset 0x40 + 0x41: 0xa000, 0x42: 0xa000, 0x43: 0xa000, 0x44: 0xa000, 0x45: 0xa000, + 0x46: 0xa000, 0x47: 0xa000, 0x48: 0xa000, 0x49: 0xa000, 0x4a: 0xa000, 0x4b: 0xa000, + 0x4c: 0xa000, 0x4d: 0xa000, 0x4e: 0xa000, 0x4f: 0xa000, 0x50: 0xa000, + 0x52: 0xa000, 0x53: 0xa000, 0x54: 0xa000, 0x55: 0xa000, 0x56: 0xa000, 0x57: 0xa000, + 0x58: 0xa000, 0x59: 0xa000, 0x5a: 0xa000, + 0x61: 0xa000, 0x62: 0xa000, 0x63: 0xa000, + 0x64: 0xa000, 0x65: 0xa000, 0x66: 0xa000, 0x67: 0xa000, 0x68: 0xa000, 0x69: 0xa000, + 0x6a: 0xa000, 0x6b: 0xa000, 0x6c: 0xa000, 0x6d: 0xa000, 0x6e: 0xa000, 0x6f: 0xa000, + 0x70: 0xa000, 0x72: 0xa000, 0x73: 0xa000, 0x74: 0xa000, 0x75: 0xa000, + 0x76: 0xa000, 0x77: 0xa000, 0x78: 0xa000, 0x79: 0xa000, 0x7a: 0xa000, + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc0: 0x2f72, 0xc1: 0x2f77, 0xc2: 0x468b, 0xc3: 0x2f7c, 0xc4: 0x469a, 0xc5: 0x469f, + 0xc6: 0xa000, 0xc7: 0x46a9, 0xc8: 0x2fe5, 0xc9: 0x2fea, 0xca: 0x46ae, 0xcb: 0x2ffe, + 0xcc: 0x3071, 0xcd: 0x3076, 0xce: 0x307b, 0xcf: 0x46c2, 0xd1: 0x3107, + 0xd2: 0x312a, 0xd3: 0x312f, 0xd4: 0x46cc, 0xd5: 0x46d1, 0xd6: 0x46e0, + 0xd8: 0xa000, 0xd9: 0x31b6, 0xda: 0x31bb, 0xdb: 0x31c0, 0xdc: 0x4712, 0xdd: 0x3238, + 0xe0: 0x327e, 0xe1: 0x3283, 0xe2: 0x471c, 0xe3: 0x3288, + 0xe4: 0x472b, 0xe5: 0x4730, 0xe6: 0xa000, 0xe7: 0x473a, 0xe8: 0x32f1, 0xe9: 0x32f6, + 0xea: 0x473f, 0xeb: 0x330a, 0xec: 0x3382, 0xed: 0x3387, 0xee: 0x338c, 0xef: 0x4753, + 0xf1: 0x3418, 0xf2: 0x343b, 0xf3: 0x3440, 0xf4: 0x475d, 0xf5: 0x4762, + 0xf6: 0x4771, 0xf8: 0xa000, 0xf9: 0x34cc, 0xfa: 0x34d1, 0xfb: 0x34d6, + 0xfc: 0x47a3, 0xfd: 0x3553, 0xff: 0x356c, + // Block 0x4, offset 0x100 + 0x100: 0x2f81, 0x101: 0x328d, 0x102: 0x4690, 0x103: 0x4721, 0x104: 0x2f9f, 0x105: 0x32ab, + 0x106: 0x2fb3, 0x107: 0x32bf, 0x108: 0x2fb8, 0x109: 0x32c4, 0x10a: 0x2fbd, 0x10b: 0x32c9, + 0x10c: 0x2fc2, 0x10d: 0x32ce, 0x10e: 0x2fcc, 0x10f: 0x32d8, + 0x112: 0x46b3, 0x113: 0x4744, 0x114: 0x2ff4, 0x115: 0x3300, 0x116: 0x2ff9, 0x117: 0x3305, + 0x118: 0x3017, 0x119: 0x3323, 0x11a: 0x3008, 0x11b: 0x3314, 0x11c: 0x3030, 0x11d: 0x333c, + 0x11e: 0x303a, 0x11f: 0x3346, 0x120: 0x303f, 0x121: 0x334b, 0x122: 0x3049, 0x123: 0x3355, + 0x124: 0x304e, 0x125: 0x335a, 0x128: 0x3080, 0x129: 0x3391, + 0x12a: 0x3085, 0x12b: 0x3396, 0x12c: 0x308a, 0x12d: 0x339b, 0x12e: 0x30ad, 0x12f: 0x33b9, + 0x130: 0x308f, 0x132: 0x195d, 0x133: 0x19ea, 0x134: 0x30b7, 0x135: 0x33c3, + 0x136: 0x30cb, 0x137: 0x33dc, 0x139: 0x30d5, 0x13a: 0x33e6, 0x13b: 0x30df, + 0x13c: 0x33f0, 0x13d: 0x30da, 0x13e: 0x33eb, 0x13f: 0x1baf, + // Block 0x5, offset 0x140 + 0x140: 0x1c37, 0x143: 0x3102, 0x144: 0x3413, 0x145: 0x311b, + 0x146: 0x342c, 0x147: 0x3111, 0x148: 0x3422, 0x149: 0x1c5f, + 0x14c: 0x46d6, 0x14d: 0x4767, 0x14e: 0x3134, 0x14f: 0x3445, 0x150: 0x313e, 0x151: 0x344f, + 0x154: 0x315c, 0x155: 0x346d, 0x156: 0x3175, 0x157: 0x3486, + 0x158: 0x3166, 0x159: 0x3477, 0x15a: 0x46f9, 0x15b: 0x478a, 0x15c: 0x317f, 0x15d: 0x3490, + 0x15e: 0x318e, 0x15f: 0x349f, 0x160: 0x46fe, 0x161: 0x478f, 0x162: 0x31a7, 0x163: 0x34bd, + 0x164: 0x3198, 0x165: 0x34ae, 0x168: 0x4708, 0x169: 0x4799, + 0x16a: 0x470d, 0x16b: 0x479e, 0x16c: 0x31c5, 0x16d: 0x34db, 0x16e: 0x31cf, 0x16f: 0x34e5, + 0x170: 0x31d4, 0x171: 0x34ea, 0x172: 0x31f2, 0x173: 0x3508, 0x174: 0x3215, 0x175: 0x352b, + 0x176: 0x323d, 0x177: 0x3558, 0x178: 0x3251, 0x179: 0x3260, 0x17a: 0x3580, 0x17b: 0x326a, + 0x17c: 0x358a, 0x17d: 0x326f, 0x17e: 0x358f, 0x17f: 0x00a7, + // Block 0x6, offset 0x180 + 0x184: 0x2df1, 0x185: 0x2df7, + 0x186: 0x2dfd, 0x187: 0x1972, 0x188: 0x1975, 0x189: 0x1a0b, 0x18a: 0x198a, 0x18b: 0x198d, + 0x18c: 0x1a41, 0x18d: 0x2f8b, 0x18e: 0x3297, 0x18f: 0x3099, 0x190: 0x33a5, 0x191: 0x3143, + 0x192: 0x3454, 0x193: 0x31d9, 0x194: 0x34ef, 0x195: 0x39d2, 0x196: 0x3b61, 0x197: 0x39cb, + 0x198: 0x3b5a, 0x199: 0x39d9, 0x19a: 0x3b68, 0x19b: 0x39c4, 0x19c: 0x3b53, + 0x19e: 0x38b3, 0x19f: 0x3a42, 0x1a0: 0x38ac, 0x1a1: 0x3a3b, 0x1a2: 0x35b6, 0x1a3: 0x35c8, + 0x1a6: 0x3044, 0x1a7: 0x3350, 0x1a8: 0x30c1, 0x1a9: 0x33d2, + 0x1aa: 0x46ef, 0x1ab: 0x4780, 0x1ac: 0x3993, 0x1ad: 0x3b22, 0x1ae: 0x35da, 0x1af: 0x35e0, + 0x1b0: 0x33c8, 0x1b1: 0x1942, 0x1b2: 0x1945, 0x1b3: 0x19d2, 0x1b4: 0x302b, 0x1b5: 0x3337, + 0x1b8: 0x30fd, 0x1b9: 0x340e, 0x1ba: 0x38ba, 0x1bb: 0x3a49, + 0x1bc: 0x35b0, 0x1bd: 0x35c2, 0x1be: 0x35bc, 0x1bf: 0x35ce, + // Block 0x7, offset 0x1c0 + 0x1c0: 0x2f90, 0x1c1: 0x329c, 0x1c2: 0x2f95, 0x1c3: 0x32a1, 0x1c4: 0x300d, 0x1c5: 0x3319, + 0x1c6: 0x3012, 0x1c7: 0x331e, 0x1c8: 0x309e, 0x1c9: 0x33aa, 0x1ca: 0x30a3, 0x1cb: 0x33af, + 0x1cc: 0x3148, 0x1cd: 0x3459, 0x1ce: 0x314d, 0x1cf: 0x345e, 0x1d0: 0x316b, 0x1d1: 0x347c, + 0x1d2: 0x3170, 0x1d3: 0x3481, 0x1d4: 0x31de, 0x1d5: 0x34f4, 0x1d6: 0x31e3, 0x1d7: 0x34f9, + 0x1d8: 0x3189, 0x1d9: 0x349a, 0x1da: 0x31a2, 0x1db: 0x34b8, + 0x1de: 0x305d, 0x1df: 0x3369, + 0x1e6: 0x4695, 0x1e7: 0x4726, 0x1e8: 0x46bd, 0x1e9: 0x474e, + 0x1ea: 0x3962, 0x1eb: 0x3af1, 0x1ec: 0x393f, 0x1ed: 0x3ace, 0x1ee: 0x46db, 0x1ef: 0x476c, + 0x1f0: 0x395b, 0x1f1: 0x3aea, 0x1f2: 0x3247, 0x1f3: 0x3562, + // Block 0x8, offset 0x200 + 0x200: 0x9932, 0x201: 0x9932, 0x202: 0x9932, 0x203: 0x9932, 0x204: 0x9932, 0x205: 0x8132, + 0x206: 0x9932, 0x207: 0x9932, 0x208: 0x9932, 0x209: 0x9932, 0x20a: 0x9932, 0x20b: 0x9932, + 0x20c: 0x9932, 0x20d: 0x8132, 0x20e: 0x8132, 0x20f: 0x9932, 0x210: 0x8132, 0x211: 0x9932, + 0x212: 0x8132, 0x213: 0x9932, 0x214: 0x9932, 0x215: 0x8133, 0x216: 0x812d, 0x217: 0x812d, + 0x218: 0x812d, 0x219: 0x812d, 0x21a: 0x8133, 0x21b: 0x992b, 0x21c: 0x812d, 0x21d: 0x812d, + 0x21e: 0x812d, 0x21f: 0x812d, 0x220: 0x812d, 0x221: 0x8129, 0x222: 0x8129, 0x223: 0x992d, + 0x224: 0x992d, 0x225: 0x992d, 0x226: 0x992d, 0x227: 0x9929, 0x228: 0x9929, 0x229: 0x812d, + 0x22a: 0x812d, 0x22b: 0x812d, 0x22c: 0x812d, 0x22d: 0x992d, 0x22e: 0x992d, 0x22f: 0x812d, + 0x230: 0x992d, 0x231: 0x992d, 0x232: 0x812d, 0x233: 0x812d, 0x234: 0x8101, 0x235: 0x8101, + 0x236: 0x8101, 0x237: 0x8101, 0x238: 0x9901, 0x239: 0x812d, 0x23a: 0x812d, 0x23b: 0x812d, + 0x23c: 0x812d, 0x23d: 0x8132, 0x23e: 0x8132, 0x23f: 0x8132, + // Block 0x9, offset 0x240 + 0x240: 0x49b1, 0x241: 0x49b6, 0x242: 0x9932, 0x243: 0x49bb, 0x244: 0x4a74, 0x245: 0x9936, + 0x246: 0x8132, 0x247: 0x812d, 0x248: 0x812d, 0x249: 0x812d, 0x24a: 0x8132, 0x24b: 0x8132, + 0x24c: 0x8132, 0x24d: 0x812d, 0x24e: 0x812d, 0x250: 0x8132, 0x251: 0x8132, + 0x252: 0x8132, 0x253: 0x812d, 0x254: 0x812d, 0x255: 0x812d, 0x256: 0x812d, 0x257: 0x8132, + 0x258: 0x8133, 0x259: 0x812d, 0x25a: 0x812d, 0x25b: 0x8132, 0x25c: 0x8134, 0x25d: 0x8135, + 0x25e: 0x8135, 0x25f: 0x8134, 0x260: 0x8135, 0x261: 0x8135, 0x262: 0x8134, 0x263: 0x8132, + 0x264: 0x8132, 0x265: 0x8132, 0x266: 0x8132, 0x267: 0x8132, 0x268: 0x8132, 0x269: 0x8132, + 0x26a: 0x8132, 0x26b: 0x8132, 0x26c: 0x8132, 0x26d: 0x8132, 0x26e: 0x8132, 0x26f: 0x8132, + 0x274: 0x0170, + 0x27a: 0x42a8, + 0x27e: 0x0037, + // Block 0xa, offset 0x280 + 0x284: 0x425d, 0x285: 0x447e, + 0x286: 0x35ec, 0x287: 0x00ce, 0x288: 0x360a, 0x289: 0x3616, 0x28a: 0x3628, + 0x28c: 0x3646, 0x28e: 0x3658, 0x28f: 0x3676, 0x290: 0x3e0b, 0x291: 0xa000, + 0x295: 0xa000, 0x297: 0xa000, + 0x299: 0xa000, + 0x29f: 0xa000, 0x2a1: 0xa000, + 0x2a5: 0xa000, 0x2a9: 0xa000, + 0x2aa: 0x363a, 0x2ab: 0x366a, 0x2ac: 0x4801, 0x2ad: 0x369a, 0x2ae: 0x482b, 0x2af: 0x36ac, + 0x2b0: 0x3e73, 0x2b1: 0xa000, 0x2b5: 0xa000, + 0x2b7: 0xa000, 0x2b9: 0xa000, + 0x2bf: 0xa000, + // Block 0xb, offset 0x2c0 + 0x2c1: 0xa000, 0x2c5: 0xa000, + 0x2c9: 0xa000, 0x2ca: 0x4843, 0x2cb: 0x4861, + 0x2cc: 0x36ca, 0x2cd: 0x36e2, 0x2ce: 0x4879, 0x2d0: 0x01be, 0x2d1: 0x01d0, + 0x2d2: 0x01ac, 0x2d3: 0x430f, 0x2d4: 0x4315, 0x2d5: 0x01fa, 0x2d6: 0x01e8, + 0x2f0: 0x01d6, 0x2f1: 0x01eb, 0x2f2: 0x01ee, 0x2f4: 0x0188, 0x2f5: 0x01c7, + 0x2f9: 0x01a6, + // Block 0xc, offset 0x300 + 0x300: 0x3724, 0x301: 0x3730, 0x303: 0x371e, + 0x306: 0xa000, 0x307: 0x370c, + 0x30c: 0x3760, 0x30d: 0x3748, 0x30e: 0x3772, 0x310: 0xa000, + 0x313: 0xa000, 0x315: 0xa000, 0x316: 0xa000, 0x317: 0xa000, + 0x318: 0xa000, 0x319: 0x3754, 0x31a: 0xa000, + 0x31e: 0xa000, 0x323: 0xa000, + 0x327: 0xa000, + 0x32b: 0xa000, 0x32d: 0xa000, + 0x330: 0xa000, 0x333: 0xa000, 0x335: 0xa000, + 0x336: 0xa000, 0x337: 0xa000, 0x338: 0xa000, 0x339: 0x37d8, 0x33a: 0xa000, + 0x33e: 0xa000, + // Block 0xd, offset 0x340 + 0x341: 0x3736, 0x342: 0x37ba, + 0x350: 0x3712, 0x351: 0x3796, + 0x352: 0x3718, 0x353: 0x379c, 0x356: 0x372a, 0x357: 0x37ae, + 0x358: 0xa000, 0x359: 0xa000, 0x35a: 0x382c, 0x35b: 0x3832, 0x35c: 0x373c, 0x35d: 0x37c0, + 0x35e: 0x3742, 0x35f: 0x37c6, 0x362: 0x374e, 0x363: 0x37d2, + 0x364: 0x375a, 0x365: 0x37de, 0x366: 0x3766, 0x367: 0x37ea, 0x368: 0xa000, 0x369: 0xa000, + 0x36a: 0x3838, 0x36b: 0x383e, 0x36c: 0x3790, 0x36d: 0x3814, 0x36e: 0x376c, 0x36f: 0x37f0, + 0x370: 0x3778, 0x371: 0x37fc, 0x372: 0x377e, 0x373: 0x3802, 0x374: 0x3784, 0x375: 0x3808, + 0x378: 0x378a, 0x379: 0x380e, + // Block 0xe, offset 0x380 + 0x387: 0x1d64, + 0x391: 0x812d, + 0x392: 0x8132, 0x393: 0x8132, 0x394: 0x8132, 0x395: 0x8132, 0x396: 0x812d, 0x397: 0x8132, + 0x398: 0x8132, 0x399: 0x8132, 0x39a: 0x812e, 0x39b: 0x812d, 0x39c: 0x8132, 0x39d: 0x8132, + 0x39e: 0x8132, 0x39f: 0x8132, 0x3a0: 0x8132, 0x3a1: 0x8132, 0x3a2: 0x812d, 0x3a3: 0x812d, + 0x3a4: 0x812d, 0x3a5: 0x812d, 0x3a6: 0x812d, 0x3a7: 0x812d, 0x3a8: 0x8132, 0x3a9: 0x8132, + 0x3aa: 0x812d, 0x3ab: 0x8132, 0x3ac: 0x8132, 0x3ad: 0x812e, 0x3ae: 0x8131, 0x3af: 0x8132, + 0x3b0: 0x8105, 0x3b1: 0x8106, 0x3b2: 0x8107, 0x3b3: 0x8108, 0x3b4: 0x8109, 0x3b5: 0x810a, + 0x3b6: 0x810b, 0x3b7: 0x810c, 0x3b8: 0x810d, 0x3b9: 0x810e, 0x3ba: 0x810e, 0x3bb: 0x810f, + 0x3bc: 0x8110, 0x3bd: 0x8111, 0x3bf: 0x8112, + // Block 0xf, offset 0x3c0 + 0x3c8: 0xa000, 0x3ca: 0xa000, 0x3cb: 0x8116, + 0x3cc: 0x8117, 0x3cd: 0x8118, 0x3ce: 0x8119, 0x3cf: 0x811a, 0x3d0: 0x811b, 0x3d1: 0x811c, + 0x3d2: 0x811d, 0x3d3: 0x9932, 0x3d4: 0x9932, 0x3d5: 0x992d, 0x3d6: 0x812d, 0x3d7: 0x8132, + 0x3d8: 0x8132, 0x3d9: 0x8132, 0x3da: 0x8132, 0x3db: 0x8132, 0x3dc: 0x812d, 0x3dd: 0x8132, + 0x3de: 0x8132, 0x3df: 0x812d, + 0x3f0: 0x811e, 0x3f5: 0x1d87, + 0x3f6: 0x2016, 0x3f7: 0x2052, 0x3f8: 0x204d, + // Block 0x10, offset 0x400 + 0x413: 0x812d, 0x414: 0x8132, 0x415: 0x8132, 0x416: 0x8132, 0x417: 0x8132, + 0x418: 0x8132, 0x419: 0x8132, 0x41a: 0x8132, 0x41b: 0x8132, 0x41c: 0x8132, 0x41d: 0x8132, + 0x41e: 0x8132, 0x41f: 0x8132, 0x420: 0x8132, 0x421: 0x8132, 0x423: 0x812d, + 0x424: 0x8132, 0x425: 0x8132, 0x426: 0x812d, 0x427: 0x8132, 0x428: 0x8132, 0x429: 0x812d, + 0x42a: 0x8132, 0x42b: 0x8132, 0x42c: 0x8132, 0x42d: 0x812d, 0x42e: 0x812d, 0x42f: 0x812d, + 0x430: 0x8116, 0x431: 0x8117, 0x432: 0x8118, 0x433: 0x8132, 0x434: 0x8132, 0x435: 0x8132, + 0x436: 0x812d, 0x437: 0x8132, 0x438: 0x8132, 0x439: 0x812d, 0x43a: 0x812d, 0x43b: 0x8132, + 0x43c: 0x8132, 0x43d: 0x8132, 0x43e: 0x8132, 0x43f: 0x8132, + // Block 0x11, offset 0x440 + 0x445: 0xa000, + 0x446: 0x2d29, 0x447: 0xa000, 0x448: 0x2d31, 0x449: 0xa000, 0x44a: 0x2d39, 0x44b: 0xa000, + 0x44c: 0x2d41, 0x44d: 0xa000, 0x44e: 0x2d49, 0x451: 0xa000, + 0x452: 0x2d51, + 0x474: 0x8102, 0x475: 0x9900, + 0x47a: 0xa000, 0x47b: 0x2d59, + 0x47c: 0xa000, 0x47d: 0x2d61, 0x47e: 0xa000, 0x47f: 0xa000, + // Block 0x12, offset 0x480 + 0x480: 0x0069, 0x481: 0x006b, 0x482: 0x006f, 0x483: 0x0083, 0x484: 0x00f5, 0x485: 0x00f8, + 0x486: 0x0413, 0x487: 0x0085, 0x488: 0x0089, 0x489: 0x008b, 0x48a: 0x0104, 0x48b: 0x0107, + 0x48c: 0x010a, 0x48d: 0x008f, 0x48f: 0x0097, 0x490: 0x009b, 0x491: 0x00e0, + 0x492: 0x009f, 0x493: 0x00fe, 0x494: 0x0417, 0x495: 0x041b, 0x496: 0x00a1, 0x497: 0x00a9, + 0x498: 0x00ab, 0x499: 0x0423, 0x49a: 0x012b, 0x49b: 0x00ad, 0x49c: 0x0427, 0x49d: 0x01be, + 0x49e: 0x01c1, 0x49f: 0x01c4, 0x4a0: 0x01fa, 0x4a1: 0x01fd, 0x4a2: 0x0093, 0x4a3: 0x00a5, + 0x4a4: 0x00ab, 0x4a5: 0x00ad, 0x4a6: 0x01be, 0x4a7: 0x01c1, 0x4a8: 0x01eb, 0x4a9: 0x01fa, + 0x4aa: 0x01fd, + 0x4b8: 0x020c, + // Block 0x13, offset 0x4c0 + 0x4db: 0x00fb, 0x4dc: 0x0087, 0x4dd: 0x0101, + 0x4de: 0x00d4, 0x4df: 0x010a, 0x4e0: 0x008d, 0x4e1: 0x010d, 0x4e2: 0x0110, 0x4e3: 0x0116, + 0x4e4: 0x011c, 0x4e5: 0x011f, 0x4e6: 0x0122, 0x4e7: 0x042b, 0x4e8: 0x016a, 0x4e9: 0x0128, + 0x4ea: 0x042f, 0x4eb: 0x016d, 0x4ec: 0x0131, 0x4ed: 0x012e, 0x4ee: 0x0134, 0x4ef: 0x0137, + 0x4f0: 0x013a, 0x4f1: 0x013d, 0x4f2: 0x0140, 0x4f3: 0x014c, 0x4f4: 0x014f, 0x4f5: 0x00ec, + 0x4f6: 0x0152, 0x4f7: 0x0155, 0x4f8: 0x041f, 0x4f9: 0x0158, 0x4fa: 0x015b, 0x4fb: 0x00b5, + 0x4fc: 0x015e, 0x4fd: 0x0161, 0x4fe: 0x0164, 0x4ff: 0x01d0, + // Block 0x14, offset 0x500 + 0x500: 0x8132, 0x501: 0x8132, 0x502: 0x812d, 0x503: 0x8132, 0x504: 0x8132, 0x505: 0x8132, + 0x506: 0x8132, 0x507: 0x8132, 0x508: 0x8132, 0x509: 0x8132, 0x50a: 0x812d, 0x50b: 0x8132, + 0x50c: 0x8132, 0x50d: 0x8135, 0x50e: 0x812a, 0x50f: 0x812d, 0x510: 0x8129, 0x511: 0x8132, + 0x512: 0x8132, 0x513: 0x8132, 0x514: 0x8132, 0x515: 0x8132, 0x516: 0x8132, 0x517: 0x8132, + 0x518: 0x8132, 0x519: 0x8132, 0x51a: 0x8132, 0x51b: 0x8132, 0x51c: 0x8132, 0x51d: 0x8132, + 0x51e: 0x8132, 0x51f: 0x8132, 0x520: 0x8132, 0x521: 0x8132, 0x522: 0x8132, 0x523: 0x8132, + 0x524: 0x8132, 0x525: 0x8132, 0x526: 0x8132, 0x527: 0x8132, 0x528: 0x8132, 0x529: 0x8132, + 0x52a: 0x8132, 0x52b: 0x8132, 0x52c: 0x8132, 0x52d: 0x8132, 0x52e: 0x8132, 0x52f: 0x8132, + 0x530: 0x8132, 0x531: 0x8132, 0x532: 0x8132, 0x533: 0x8132, 0x534: 0x8132, 0x535: 0x8132, + 0x536: 0x8133, 0x537: 0x8131, 0x538: 0x8131, 0x539: 0x812d, 0x53b: 0x8132, + 0x53c: 0x8134, 0x53d: 0x812d, 0x53e: 0x8132, 0x53f: 0x812d, + // Block 0x15, offset 0x540 + 0x540: 0x2f9a, 0x541: 0x32a6, 0x542: 0x2fa4, 0x543: 0x32b0, 0x544: 0x2fa9, 0x545: 0x32b5, + 0x546: 0x2fae, 0x547: 0x32ba, 0x548: 0x38cf, 0x549: 0x3a5e, 0x54a: 0x2fc7, 0x54b: 0x32d3, + 0x54c: 0x2fd1, 0x54d: 0x32dd, 0x54e: 0x2fe0, 0x54f: 0x32ec, 0x550: 0x2fd6, 0x551: 0x32e2, + 0x552: 0x2fdb, 0x553: 0x32e7, 0x554: 0x38f2, 0x555: 0x3a81, 0x556: 0x38f9, 0x557: 0x3a88, + 0x558: 0x301c, 0x559: 0x3328, 0x55a: 0x3021, 0x55b: 0x332d, 0x55c: 0x3907, 0x55d: 0x3a96, + 0x55e: 0x3026, 0x55f: 0x3332, 0x560: 0x3035, 0x561: 0x3341, 0x562: 0x3053, 0x563: 0x335f, + 0x564: 0x3062, 0x565: 0x336e, 0x566: 0x3058, 0x567: 0x3364, 0x568: 0x3067, 0x569: 0x3373, + 0x56a: 0x306c, 0x56b: 0x3378, 0x56c: 0x30b2, 0x56d: 0x33be, 0x56e: 0x390e, 0x56f: 0x3a9d, + 0x570: 0x30bc, 0x571: 0x33cd, 0x572: 0x30c6, 0x573: 0x33d7, 0x574: 0x30d0, 0x575: 0x33e1, + 0x576: 0x46c7, 0x577: 0x4758, 0x578: 0x3915, 0x579: 0x3aa4, 0x57a: 0x30e9, 0x57b: 0x33fa, + 0x57c: 0x30e4, 0x57d: 0x33f5, 0x57e: 0x30ee, 0x57f: 0x33ff, + // Block 0x16, offset 0x580 + 0x580: 0x30f3, 0x581: 0x3404, 0x582: 0x30f8, 0x583: 0x3409, 0x584: 0x310c, 0x585: 0x341d, + 0x586: 0x3116, 0x587: 0x3427, 0x588: 0x3125, 0x589: 0x3436, 0x58a: 0x3120, 0x58b: 0x3431, + 0x58c: 0x3938, 0x58d: 0x3ac7, 0x58e: 0x3946, 0x58f: 0x3ad5, 0x590: 0x394d, 0x591: 0x3adc, + 0x592: 0x3954, 0x593: 0x3ae3, 0x594: 0x3152, 0x595: 0x3463, 0x596: 0x3157, 0x597: 0x3468, + 0x598: 0x3161, 0x599: 0x3472, 0x59a: 0x46f4, 0x59b: 0x4785, 0x59c: 0x399a, 0x59d: 0x3b29, + 0x59e: 0x317a, 0x59f: 0x348b, 0x5a0: 0x3184, 0x5a1: 0x3495, 0x5a2: 0x4703, 0x5a3: 0x4794, + 0x5a4: 0x39a1, 0x5a5: 0x3b30, 0x5a6: 0x39a8, 0x5a7: 0x3b37, 0x5a8: 0x39af, 0x5a9: 0x3b3e, + 0x5aa: 0x3193, 0x5ab: 0x34a4, 0x5ac: 0x319d, 0x5ad: 0x34b3, 0x5ae: 0x31b1, 0x5af: 0x34c7, + 0x5b0: 0x31ac, 0x5b1: 0x34c2, 0x5b2: 0x31ed, 0x5b3: 0x3503, 0x5b4: 0x31fc, 0x5b5: 0x3512, + 0x5b6: 0x31f7, 0x5b7: 0x350d, 0x5b8: 0x39b6, 0x5b9: 0x3b45, 0x5ba: 0x39bd, 0x5bb: 0x3b4c, + 0x5bc: 0x3201, 0x5bd: 0x3517, 0x5be: 0x3206, 0x5bf: 0x351c, + // Block 0x17, offset 0x5c0 + 0x5c0: 0x320b, 0x5c1: 0x3521, 0x5c2: 0x3210, 0x5c3: 0x3526, 0x5c4: 0x321f, 0x5c5: 0x3535, + 0x5c6: 0x321a, 0x5c7: 0x3530, 0x5c8: 0x3224, 0x5c9: 0x353f, 0x5ca: 0x3229, 0x5cb: 0x3544, + 0x5cc: 0x322e, 0x5cd: 0x3549, 0x5ce: 0x324c, 0x5cf: 0x3567, 0x5d0: 0x3265, 0x5d1: 0x3585, + 0x5d2: 0x3274, 0x5d3: 0x3594, 0x5d4: 0x3279, 0x5d5: 0x3599, 0x5d6: 0x337d, 0x5d7: 0x34a9, + 0x5d8: 0x353a, 0x5d9: 0x3576, 0x5da: 0x1be3, 0x5db: 0x42da, + 0x5e0: 0x46a4, 0x5e1: 0x4735, 0x5e2: 0x2f86, 0x5e3: 0x3292, + 0x5e4: 0x387b, 0x5e5: 0x3a0a, 0x5e6: 0x3874, 0x5e7: 0x3a03, 0x5e8: 0x3889, 0x5e9: 0x3a18, + 0x5ea: 0x3882, 0x5eb: 0x3a11, 0x5ec: 0x38c1, 0x5ed: 0x3a50, 0x5ee: 0x3897, 0x5ef: 0x3a26, + 0x5f0: 0x3890, 0x5f1: 0x3a1f, 0x5f2: 0x38a5, 0x5f3: 0x3a34, 0x5f4: 0x389e, 0x5f5: 0x3a2d, + 0x5f6: 0x38c8, 0x5f7: 0x3a57, 0x5f8: 0x46b8, 0x5f9: 0x4749, 0x5fa: 0x3003, 0x5fb: 0x330f, + 0x5fc: 0x2fef, 0x5fd: 0x32fb, 0x5fe: 0x38dd, 0x5ff: 0x3a6c, + // Block 0x18, offset 0x600 + 0x600: 0x38d6, 0x601: 0x3a65, 0x602: 0x38eb, 0x603: 0x3a7a, 0x604: 0x38e4, 0x605: 0x3a73, + 0x606: 0x3900, 0x607: 0x3a8f, 0x608: 0x3094, 0x609: 0x33a0, 0x60a: 0x30a8, 0x60b: 0x33b4, + 0x60c: 0x46ea, 0x60d: 0x477b, 0x60e: 0x3139, 0x60f: 0x344a, 0x610: 0x3923, 0x611: 0x3ab2, + 0x612: 0x391c, 0x613: 0x3aab, 0x614: 0x3931, 0x615: 0x3ac0, 0x616: 0x392a, 0x617: 0x3ab9, + 0x618: 0x398c, 0x619: 0x3b1b, 0x61a: 0x3970, 0x61b: 0x3aff, 0x61c: 0x3969, 0x61d: 0x3af8, + 0x61e: 0x397e, 0x61f: 0x3b0d, 0x620: 0x3977, 0x621: 0x3b06, 0x622: 0x3985, 0x623: 0x3b14, + 0x624: 0x31e8, 0x625: 0x34fe, 0x626: 0x31ca, 0x627: 0x34e0, 0x628: 0x39e7, 0x629: 0x3b76, + 0x62a: 0x39e0, 0x62b: 0x3b6f, 0x62c: 0x39f5, 0x62d: 0x3b84, 0x62e: 0x39ee, 0x62f: 0x3b7d, + 0x630: 0x39fc, 0x631: 0x3b8b, 0x632: 0x3233, 0x633: 0x354e, 0x634: 0x325b, 0x635: 0x357b, + 0x636: 0x3256, 0x637: 0x3571, 0x638: 0x3242, 0x639: 0x355d, + // Block 0x19, offset 0x640 + 0x640: 0x4807, 0x641: 0x480d, 0x642: 0x4921, 0x643: 0x4939, 0x644: 0x4929, 0x645: 0x4941, + 0x646: 0x4931, 0x647: 0x4949, 0x648: 0x47ad, 0x649: 0x47b3, 0x64a: 0x4891, 0x64b: 0x48a9, + 0x64c: 0x4899, 0x64d: 0x48b1, 0x64e: 0x48a1, 0x64f: 0x48b9, 0x650: 0x4819, 0x651: 0x481f, + 0x652: 0x3dbb, 0x653: 0x3dcb, 0x654: 0x3dc3, 0x655: 0x3dd3, + 0x658: 0x47b9, 0x659: 0x47bf, 0x65a: 0x3ceb, 0x65b: 0x3cfb, 0x65c: 0x3cf3, 0x65d: 0x3d03, + 0x660: 0x4831, 0x661: 0x4837, 0x662: 0x4951, 0x663: 0x4969, + 0x664: 0x4959, 0x665: 0x4971, 0x666: 0x4961, 0x667: 0x4979, 0x668: 0x47c5, 0x669: 0x47cb, + 0x66a: 0x48c1, 0x66b: 0x48d9, 0x66c: 0x48c9, 0x66d: 0x48e1, 0x66e: 0x48d1, 0x66f: 0x48e9, + 0x670: 0x4849, 0x671: 0x484f, 0x672: 0x3e1b, 0x673: 0x3e33, 0x674: 0x3e23, 0x675: 0x3e3b, + 0x676: 0x3e2b, 0x677: 0x3e43, 0x678: 0x47d1, 0x679: 0x47d7, 0x67a: 0x3d1b, 0x67b: 0x3d33, + 0x67c: 0x3d23, 0x67d: 0x3d3b, 0x67e: 0x3d2b, 0x67f: 0x3d43, + // Block 0x1a, offset 0x680 + 0x680: 0x4855, 0x681: 0x485b, 0x682: 0x3e4b, 0x683: 0x3e5b, 0x684: 0x3e53, 0x685: 0x3e63, + 0x688: 0x47dd, 0x689: 0x47e3, 0x68a: 0x3d4b, 0x68b: 0x3d5b, + 0x68c: 0x3d53, 0x68d: 0x3d63, 0x690: 0x4867, 0x691: 0x486d, + 0x692: 0x3e83, 0x693: 0x3e9b, 0x694: 0x3e8b, 0x695: 0x3ea3, 0x696: 0x3e93, 0x697: 0x3eab, + 0x699: 0x47e9, 0x69b: 0x3d6b, 0x69d: 0x3d73, + 0x69f: 0x3d7b, 0x6a0: 0x487f, 0x6a1: 0x4885, 0x6a2: 0x4981, 0x6a3: 0x4999, + 0x6a4: 0x4989, 0x6a5: 0x49a1, 0x6a6: 0x4991, 0x6a7: 0x49a9, 0x6a8: 0x47ef, 0x6a9: 0x47f5, + 0x6aa: 0x48f1, 0x6ab: 0x4909, 0x6ac: 0x48f9, 0x6ad: 0x4911, 0x6ae: 0x4901, 0x6af: 0x4919, + 0x6b0: 0x47fb, 0x6b1: 0x4321, 0x6b2: 0x3694, 0x6b3: 0x4327, 0x6b4: 0x4825, 0x6b5: 0x432d, + 0x6b6: 0x36a6, 0x6b7: 0x4333, 0x6b8: 0x36c4, 0x6b9: 0x4339, 0x6ba: 0x36dc, 0x6bb: 0x433f, + 0x6bc: 0x4873, 0x6bd: 0x4345, + // Block 0x1b, offset 0x6c0 + 0x6c0: 0x3da3, 0x6c1: 0x3dab, 0x6c2: 0x4187, 0x6c3: 0x41a5, 0x6c4: 0x4191, 0x6c5: 0x41af, + 0x6c6: 0x419b, 0x6c7: 0x41b9, 0x6c8: 0x3cdb, 0x6c9: 0x3ce3, 0x6ca: 0x40d3, 0x6cb: 0x40f1, + 0x6cc: 0x40dd, 0x6cd: 0x40fb, 0x6ce: 0x40e7, 0x6cf: 0x4105, 0x6d0: 0x3deb, 0x6d1: 0x3df3, + 0x6d2: 0x41c3, 0x6d3: 0x41e1, 0x6d4: 0x41cd, 0x6d5: 0x41eb, 0x6d6: 0x41d7, 0x6d7: 0x41f5, + 0x6d8: 0x3d0b, 0x6d9: 0x3d13, 0x6da: 0x410f, 0x6db: 0x412d, 0x6dc: 0x4119, 0x6dd: 0x4137, + 0x6de: 0x4123, 0x6df: 0x4141, 0x6e0: 0x3ec3, 0x6e1: 0x3ecb, 0x6e2: 0x41ff, 0x6e3: 0x421d, + 0x6e4: 0x4209, 0x6e5: 0x4227, 0x6e6: 0x4213, 0x6e7: 0x4231, 0x6e8: 0x3d83, 0x6e9: 0x3d8b, + 0x6ea: 0x414b, 0x6eb: 0x4169, 0x6ec: 0x4155, 0x6ed: 0x4173, 0x6ee: 0x415f, 0x6ef: 0x417d, + 0x6f0: 0x3688, 0x6f1: 0x3682, 0x6f2: 0x3d93, 0x6f3: 0x368e, 0x6f4: 0x3d9b, + 0x6f6: 0x4813, 0x6f7: 0x3db3, 0x6f8: 0x35f8, 0x6f9: 0x35f2, 0x6fa: 0x35e6, 0x6fb: 0x42f1, + 0x6fc: 0x35fe, 0x6fd: 0x428a, 0x6fe: 0x01d3, 0x6ff: 0x428a, + // Block 0x1c, offset 0x700 + 0x700: 0x42a3, 0x701: 0x4485, 0x702: 0x3ddb, 0x703: 0x36a0, 0x704: 0x3de3, + 0x706: 0x483d, 0x707: 0x3dfb, 0x708: 0x3604, 0x709: 0x42f7, 0x70a: 0x3610, 0x70b: 0x42fd, + 0x70c: 0x361c, 0x70d: 0x448c, 0x70e: 0x4493, 0x70f: 0x449a, 0x710: 0x36b8, 0x711: 0x36b2, + 0x712: 0x3e03, 0x713: 0x44e7, 0x716: 0x36be, 0x717: 0x3e13, + 0x718: 0x3634, 0x719: 0x362e, 0x71a: 0x3622, 0x71b: 0x4303, 0x71d: 0x44a1, + 0x71e: 0x44a8, 0x71f: 0x44af, 0x720: 0x36ee, 0x721: 0x36e8, 0x722: 0x3e6b, 0x723: 0x44ef, + 0x724: 0x36d0, 0x725: 0x36d6, 0x726: 0x36f4, 0x727: 0x3e7b, 0x728: 0x3664, 0x729: 0x365e, + 0x72a: 0x3652, 0x72b: 0x430f, 0x72c: 0x364c, 0x72d: 0x4477, 0x72e: 0x447e, 0x72f: 0x0081, + 0x732: 0x3eb3, 0x733: 0x36fa, 0x734: 0x3ebb, + 0x736: 0x488b, 0x737: 0x3ed3, 0x738: 0x3640, 0x739: 0x4309, 0x73a: 0x3670, 0x73b: 0x431b, + 0x73c: 0x367c, 0x73d: 0x425d, 0x73e: 0x428f, + // Block 0x1d, offset 0x740 + 0x740: 0x1bdb, 0x741: 0x1bdf, 0x742: 0x0047, 0x743: 0x1c57, 0x745: 0x1beb, + 0x746: 0x1bef, 0x747: 0x00e9, 0x749: 0x1c5b, 0x74a: 0x008f, 0x74b: 0x0051, + 0x74c: 0x0051, 0x74d: 0x0051, 0x74e: 0x0091, 0x74f: 0x00da, 0x750: 0x0053, 0x751: 0x0053, + 0x752: 0x0059, 0x753: 0x0099, 0x755: 0x005d, 0x756: 0x1990, + 0x759: 0x0061, 0x75a: 0x0063, 0x75b: 0x0065, 0x75c: 0x0065, 0x75d: 0x0065, + 0x760: 0x19a2, 0x761: 0x1bcb, 0x762: 0x19ab, + 0x764: 0x0075, 0x766: 0x01b8, 0x768: 0x0075, + 0x76a: 0x0057, 0x76b: 0x42d5, 0x76c: 0x0045, 0x76d: 0x0047, 0x76f: 0x008b, + 0x770: 0x004b, 0x771: 0x004d, 0x773: 0x005b, 0x774: 0x009f, 0x775: 0x0215, + 0x776: 0x0218, 0x777: 0x021b, 0x778: 0x021e, 0x779: 0x0093, 0x77b: 0x1b9b, + 0x77c: 0x01e8, 0x77d: 0x01c1, 0x77e: 0x0179, 0x77f: 0x01a0, + // Block 0x1e, offset 0x780 + 0x780: 0x0463, 0x785: 0x0049, + 0x786: 0x0089, 0x787: 0x008b, 0x788: 0x0093, 0x789: 0x0095, + 0x790: 0x2231, 0x791: 0x223d, + 0x792: 0x22f1, 0x793: 0x2219, 0x794: 0x229d, 0x795: 0x2225, 0x796: 0x22a3, 0x797: 0x22bb, + 0x798: 0x22c7, 0x799: 0x222b, 0x79a: 0x22cd, 0x79b: 0x2237, 0x79c: 0x22c1, 0x79d: 0x22d3, + 0x79e: 0x22d9, 0x79f: 0x1cbf, 0x7a0: 0x0053, 0x7a1: 0x195a, 0x7a2: 0x1ba7, 0x7a3: 0x1963, + 0x7a4: 0x006d, 0x7a5: 0x19ae, 0x7a6: 0x1bd3, 0x7a7: 0x1d4b, 0x7a8: 0x1966, 0x7a9: 0x0071, + 0x7aa: 0x19ba, 0x7ab: 0x1bd7, 0x7ac: 0x0059, 0x7ad: 0x0047, 0x7ae: 0x0049, 0x7af: 0x005b, + 0x7b0: 0x0093, 0x7b1: 0x19e7, 0x7b2: 0x1c1b, 0x7b3: 0x19f0, 0x7b4: 0x00ad, 0x7b5: 0x1a65, + 0x7b6: 0x1c4f, 0x7b7: 0x1d5f, 0x7b8: 0x19f3, 0x7b9: 0x00b1, 0x7ba: 0x1a68, 0x7bb: 0x1c53, + 0x7bc: 0x0099, 0x7bd: 0x0087, 0x7be: 0x0089, 0x7bf: 0x009b, + // Block 0x1f, offset 0x7c0 + 0x7c1: 0x3c09, 0x7c3: 0xa000, 0x7c4: 0x3c10, 0x7c5: 0xa000, + 0x7c7: 0x3c17, 0x7c8: 0xa000, 0x7c9: 0x3c1e, + 0x7cd: 0xa000, + 0x7e0: 0x2f68, 0x7e1: 0xa000, 0x7e2: 0x3c2c, + 0x7e4: 0xa000, 0x7e5: 0xa000, + 0x7ed: 0x3c25, 0x7ee: 0x2f63, 0x7ef: 0x2f6d, + 0x7f0: 0x3c33, 0x7f1: 0x3c3a, 0x7f2: 0xa000, 0x7f3: 0xa000, 0x7f4: 0x3c41, 0x7f5: 0x3c48, + 0x7f6: 0xa000, 0x7f7: 0xa000, 0x7f8: 0x3c4f, 0x7f9: 0x3c56, 0x7fa: 0xa000, 0x7fb: 0xa000, + 0x7fc: 0xa000, 0x7fd: 0xa000, + // Block 0x20, offset 0x800 + 0x800: 0x3c5d, 0x801: 0x3c64, 0x802: 0xa000, 0x803: 0xa000, 0x804: 0x3c79, 0x805: 0x3c80, + 0x806: 0xa000, 0x807: 0xa000, 0x808: 0x3c87, 0x809: 0x3c8e, + 0x811: 0xa000, + 0x812: 0xa000, + 0x822: 0xa000, + 0x828: 0xa000, 0x829: 0xa000, + 0x82b: 0xa000, 0x82c: 0x3ca3, 0x82d: 0x3caa, 0x82e: 0x3cb1, 0x82f: 0x3cb8, + 0x832: 0xa000, 0x833: 0xa000, 0x834: 0xa000, 0x835: 0xa000, + // Block 0x21, offset 0x840 + 0x860: 0x0023, 0x861: 0x0025, 0x862: 0x0027, 0x863: 0x0029, + 0x864: 0x002b, 0x865: 0x002d, 0x866: 0x002f, 0x867: 0x0031, 0x868: 0x0033, 0x869: 0x1882, + 0x86a: 0x1885, 0x86b: 0x1888, 0x86c: 0x188b, 0x86d: 0x188e, 0x86e: 0x1891, 0x86f: 0x1894, + 0x870: 0x1897, 0x871: 0x189a, 0x872: 0x189d, 0x873: 0x18a6, 0x874: 0x1a6b, 0x875: 0x1a6f, + 0x876: 0x1a73, 0x877: 0x1a77, 0x878: 0x1a7b, 0x879: 0x1a7f, 0x87a: 0x1a83, 0x87b: 0x1a87, + 0x87c: 0x1a8b, 0x87d: 0x1c83, 0x87e: 0x1c88, 0x87f: 0x1c8d, + // Block 0x22, offset 0x880 + 0x880: 0x1c92, 0x881: 0x1c97, 0x882: 0x1c9c, 0x883: 0x1ca1, 0x884: 0x1ca6, 0x885: 0x1cab, + 0x886: 0x1cb0, 0x887: 0x1cb5, 0x888: 0x187f, 0x889: 0x18a3, 0x88a: 0x18c7, 0x88b: 0x18eb, + 0x88c: 0x190f, 0x88d: 0x1918, 0x88e: 0x191e, 0x88f: 0x1924, 0x890: 0x192a, 0x891: 0x1b63, + 0x892: 0x1b67, 0x893: 0x1b6b, 0x894: 0x1b6f, 0x895: 0x1b73, 0x896: 0x1b77, 0x897: 0x1b7b, + 0x898: 0x1b7f, 0x899: 0x1b83, 0x89a: 0x1b87, 0x89b: 0x1b8b, 0x89c: 0x1af7, 0x89d: 0x1afb, + 0x89e: 0x1aff, 0x89f: 0x1b03, 0x8a0: 0x1b07, 0x8a1: 0x1b0b, 0x8a2: 0x1b0f, 0x8a3: 0x1b13, + 0x8a4: 0x1b17, 0x8a5: 0x1b1b, 0x8a6: 0x1b1f, 0x8a7: 0x1b23, 0x8a8: 0x1b27, 0x8a9: 0x1b2b, + 0x8aa: 0x1b2f, 0x8ab: 0x1b33, 0x8ac: 0x1b37, 0x8ad: 0x1b3b, 0x8ae: 0x1b3f, 0x8af: 0x1b43, + 0x8b0: 0x1b47, 0x8b1: 0x1b4b, 0x8b2: 0x1b4f, 0x8b3: 0x1b53, 0x8b4: 0x1b57, 0x8b5: 0x1b5b, + 0x8b6: 0x0043, 0x8b7: 0x0045, 0x8b8: 0x0047, 0x8b9: 0x0049, 0x8ba: 0x004b, 0x8bb: 0x004d, + 0x8bc: 0x004f, 0x8bd: 0x0051, 0x8be: 0x0053, 0x8bf: 0x0055, + // Block 0x23, offset 0x8c0 + 0x8c0: 0x06bf, 0x8c1: 0x06e3, 0x8c2: 0x06ef, 0x8c3: 0x06ff, 0x8c4: 0x0707, 0x8c5: 0x0713, + 0x8c6: 0x071b, 0x8c7: 0x0723, 0x8c8: 0x072f, 0x8c9: 0x0783, 0x8ca: 0x079b, 0x8cb: 0x07ab, + 0x8cc: 0x07bb, 0x8cd: 0x07cb, 0x8ce: 0x07db, 0x8cf: 0x07fb, 0x8d0: 0x07ff, 0x8d1: 0x0803, + 0x8d2: 0x0837, 0x8d3: 0x085f, 0x8d4: 0x086f, 0x8d5: 0x0877, 0x8d6: 0x087b, 0x8d7: 0x0887, + 0x8d8: 0x08a3, 0x8d9: 0x08a7, 0x8da: 0x08bf, 0x8db: 0x08c3, 0x8dc: 0x08cb, 0x8dd: 0x08db, + 0x8de: 0x0977, 0x8df: 0x098b, 0x8e0: 0x09cb, 0x8e1: 0x09df, 0x8e2: 0x09e7, 0x8e3: 0x09eb, + 0x8e4: 0x09fb, 0x8e5: 0x0a17, 0x8e6: 0x0a43, 0x8e7: 0x0a4f, 0x8e8: 0x0a6f, 0x8e9: 0x0a7b, + 0x8ea: 0x0a7f, 0x8eb: 0x0a83, 0x8ec: 0x0a9b, 0x8ed: 0x0a9f, 0x8ee: 0x0acb, 0x8ef: 0x0ad7, + 0x8f0: 0x0adf, 0x8f1: 0x0ae7, 0x8f2: 0x0af7, 0x8f3: 0x0aff, 0x8f4: 0x0b07, 0x8f5: 0x0b33, + 0x8f6: 0x0b37, 0x8f7: 0x0b3f, 0x8f8: 0x0b43, 0x8f9: 0x0b4b, 0x8fa: 0x0b53, 0x8fb: 0x0b63, + 0x8fc: 0x0b7f, 0x8fd: 0x0bf7, 0x8fe: 0x0c0b, 0x8ff: 0x0c0f, + // Block 0x24, offset 0x900 + 0x900: 0x0c8f, 0x901: 0x0c93, 0x902: 0x0ca7, 0x903: 0x0cab, 0x904: 0x0cb3, 0x905: 0x0cbb, + 0x906: 0x0cc3, 0x907: 0x0ccf, 0x908: 0x0cf7, 0x909: 0x0d07, 0x90a: 0x0d1b, 0x90b: 0x0d8b, + 0x90c: 0x0d97, 0x90d: 0x0da7, 0x90e: 0x0db3, 0x90f: 0x0dbf, 0x910: 0x0dc7, 0x911: 0x0dcb, + 0x912: 0x0dcf, 0x913: 0x0dd3, 0x914: 0x0dd7, 0x915: 0x0e8f, 0x916: 0x0ed7, 0x917: 0x0ee3, + 0x918: 0x0ee7, 0x919: 0x0eeb, 0x91a: 0x0eef, 0x91b: 0x0ef7, 0x91c: 0x0efb, 0x91d: 0x0f0f, + 0x91e: 0x0f2b, 0x91f: 0x0f33, 0x920: 0x0f73, 0x921: 0x0f77, 0x922: 0x0f7f, 0x923: 0x0f83, + 0x924: 0x0f8b, 0x925: 0x0f8f, 0x926: 0x0fb3, 0x927: 0x0fb7, 0x928: 0x0fd3, 0x929: 0x0fd7, + 0x92a: 0x0fdb, 0x92b: 0x0fdf, 0x92c: 0x0ff3, 0x92d: 0x1017, 0x92e: 0x101b, 0x92f: 0x101f, + 0x930: 0x1043, 0x931: 0x1083, 0x932: 0x1087, 0x933: 0x10a7, 0x934: 0x10b7, 0x935: 0x10bf, + 0x936: 0x10df, 0x937: 0x1103, 0x938: 0x1147, 0x939: 0x114f, 0x93a: 0x1163, 0x93b: 0x116f, + 0x93c: 0x1177, 0x93d: 0x117f, 0x93e: 0x1183, 0x93f: 0x1187, + // Block 0x25, offset 0x940 + 0x940: 0x119f, 0x941: 0x11a3, 0x942: 0x11bf, 0x943: 0x11c7, 0x944: 0x11cf, 0x945: 0x11d3, + 0x946: 0x11df, 0x947: 0x11e7, 0x948: 0x11eb, 0x949: 0x11ef, 0x94a: 0x11f7, 0x94b: 0x11fb, + 0x94c: 0x129b, 0x94d: 0x12af, 0x94e: 0x12e3, 0x94f: 0x12e7, 0x950: 0x12ef, 0x951: 0x131b, + 0x952: 0x1323, 0x953: 0x132b, 0x954: 0x1333, 0x955: 0x136f, 0x956: 0x1373, 0x957: 0x137b, + 0x958: 0x137f, 0x959: 0x1383, 0x95a: 0x13af, 0x95b: 0x13b3, 0x95c: 0x13bb, 0x95d: 0x13cf, + 0x95e: 0x13d3, 0x95f: 0x13ef, 0x960: 0x13f7, 0x961: 0x13fb, 0x962: 0x141f, 0x963: 0x143f, + 0x964: 0x1453, 0x965: 0x1457, 0x966: 0x145f, 0x967: 0x148b, 0x968: 0x148f, 0x969: 0x149f, + 0x96a: 0x14c3, 0x96b: 0x14cf, 0x96c: 0x14df, 0x96d: 0x14f7, 0x96e: 0x14ff, 0x96f: 0x1503, + 0x970: 0x1507, 0x971: 0x150b, 0x972: 0x1517, 0x973: 0x151b, 0x974: 0x1523, 0x975: 0x153f, + 0x976: 0x1543, 0x977: 0x1547, 0x978: 0x155f, 0x979: 0x1563, 0x97a: 0x156b, 0x97b: 0x157f, + 0x97c: 0x1583, 0x97d: 0x1587, 0x97e: 0x158f, 0x97f: 0x1593, + // Block 0x26, offset 0x980 + 0x986: 0xa000, 0x98b: 0xa000, + 0x98c: 0x3f0b, 0x98d: 0xa000, 0x98e: 0x3f13, 0x98f: 0xa000, 0x990: 0x3f1b, 0x991: 0xa000, + 0x992: 0x3f23, 0x993: 0xa000, 0x994: 0x3f2b, 0x995: 0xa000, 0x996: 0x3f33, 0x997: 0xa000, + 0x998: 0x3f3b, 0x999: 0xa000, 0x99a: 0x3f43, 0x99b: 0xa000, 0x99c: 0x3f4b, 0x99d: 0xa000, + 0x99e: 0x3f53, 0x99f: 0xa000, 0x9a0: 0x3f5b, 0x9a1: 0xa000, 0x9a2: 0x3f63, + 0x9a4: 0xa000, 0x9a5: 0x3f6b, 0x9a6: 0xa000, 0x9a7: 0x3f73, 0x9a8: 0xa000, 0x9a9: 0x3f7b, + 0x9af: 0xa000, + 0x9b0: 0x3f83, 0x9b1: 0x3f8b, 0x9b2: 0xa000, 0x9b3: 0x3f93, 0x9b4: 0x3f9b, 0x9b5: 0xa000, + 0x9b6: 0x3fa3, 0x9b7: 0x3fab, 0x9b8: 0xa000, 0x9b9: 0x3fb3, 0x9ba: 0x3fbb, 0x9bb: 0xa000, + 0x9bc: 0x3fc3, 0x9bd: 0x3fcb, + // Block 0x27, offset 0x9c0 + 0x9d4: 0x3f03, + 0x9d9: 0x9903, 0x9da: 0x9903, 0x9db: 0x42df, 0x9dc: 0x42e5, 0x9dd: 0xa000, + 0x9de: 0x3fd3, 0x9df: 0x26b7, + 0x9e6: 0xa000, + 0x9eb: 0xa000, 0x9ec: 0x3fe3, 0x9ed: 0xa000, 0x9ee: 0x3feb, 0x9ef: 0xa000, + 0x9f0: 0x3ff3, 0x9f1: 0xa000, 0x9f2: 0x3ffb, 0x9f3: 0xa000, 0x9f4: 0x4003, 0x9f5: 0xa000, + 0x9f6: 0x400b, 0x9f7: 0xa000, 0x9f8: 0x4013, 0x9f9: 0xa000, 0x9fa: 0x401b, 0x9fb: 0xa000, + 0x9fc: 0x4023, 0x9fd: 0xa000, 0x9fe: 0x402b, 0x9ff: 0xa000, + // Block 0x28, offset 0xa00 + 0xa00: 0x4033, 0xa01: 0xa000, 0xa02: 0x403b, 0xa04: 0xa000, 0xa05: 0x4043, + 0xa06: 0xa000, 0xa07: 0x404b, 0xa08: 0xa000, 0xa09: 0x4053, + 0xa0f: 0xa000, 0xa10: 0x405b, 0xa11: 0x4063, + 0xa12: 0xa000, 0xa13: 0x406b, 0xa14: 0x4073, 0xa15: 0xa000, 0xa16: 0x407b, 0xa17: 0x4083, + 0xa18: 0xa000, 0xa19: 0x408b, 0xa1a: 0x4093, 0xa1b: 0xa000, 0xa1c: 0x409b, 0xa1d: 0x40a3, + 0xa2f: 0xa000, + 0xa30: 0xa000, 0xa31: 0xa000, 0xa32: 0xa000, 0xa34: 0x3fdb, + 0xa37: 0x40ab, 0xa38: 0x40b3, 0xa39: 0x40bb, 0xa3a: 0x40c3, + 0xa3d: 0xa000, 0xa3e: 0x40cb, 0xa3f: 0x26cc, + // Block 0x29, offset 0xa40 + 0xa40: 0x0367, 0xa41: 0x032b, 0xa42: 0x032f, 0xa43: 0x0333, 0xa44: 0x037b, 0xa45: 0x0337, + 0xa46: 0x033b, 0xa47: 0x033f, 0xa48: 0x0343, 0xa49: 0x0347, 0xa4a: 0x034b, 0xa4b: 0x034f, + 0xa4c: 0x0353, 0xa4d: 0x0357, 0xa4e: 0x035b, 0xa4f: 0x49c0, 0xa50: 0x49c6, 0xa51: 0x49cc, + 0xa52: 0x49d2, 0xa53: 0x49d8, 0xa54: 0x49de, 0xa55: 0x49e4, 0xa56: 0x49ea, 0xa57: 0x49f0, + 0xa58: 0x49f6, 0xa59: 0x49fc, 0xa5a: 0x4a02, 0xa5b: 0x4a08, 0xa5c: 0x4a0e, 0xa5d: 0x4a14, + 0xa5e: 0x4a1a, 0xa5f: 0x4a20, 0xa60: 0x4a26, 0xa61: 0x4a2c, 0xa62: 0x4a32, 0xa63: 0x4a38, + 0xa64: 0x03c3, 0xa65: 0x035f, 0xa66: 0x0363, 0xa67: 0x03e7, 0xa68: 0x03eb, 0xa69: 0x03ef, + 0xa6a: 0x03f3, 0xa6b: 0x03f7, 0xa6c: 0x03fb, 0xa6d: 0x03ff, 0xa6e: 0x036b, 0xa6f: 0x0403, + 0xa70: 0x0407, 0xa71: 0x036f, 0xa72: 0x0373, 0xa73: 0x0377, 0xa74: 0x037f, 0xa75: 0x0383, + 0xa76: 0x0387, 0xa77: 0x038b, 0xa78: 0x038f, 0xa79: 0x0393, 0xa7a: 0x0397, 0xa7b: 0x039b, + 0xa7c: 0x039f, 0xa7d: 0x03a3, 0xa7e: 0x03a7, 0xa7f: 0x03ab, + // Block 0x2a, offset 0xa80 + 0xa80: 0x03af, 0xa81: 0x03b3, 0xa82: 0x040b, 0xa83: 0x040f, 0xa84: 0x03b7, 0xa85: 0x03bb, + 0xa86: 0x03bf, 0xa87: 0x03c7, 0xa88: 0x03cb, 0xa89: 0x03cf, 0xa8a: 0x03d3, 0xa8b: 0x03d7, + 0xa8c: 0x03db, 0xa8d: 0x03df, 0xa8e: 0x03e3, + 0xa92: 0x06bf, 0xa93: 0x071b, 0xa94: 0x06cb, 0xa95: 0x097b, 0xa96: 0x06cf, 0xa97: 0x06e7, + 0xa98: 0x06d3, 0xa99: 0x0f93, 0xa9a: 0x0707, 0xa9b: 0x06db, 0xa9c: 0x06c3, 0xa9d: 0x09ff, + 0xa9e: 0x098f, 0xa9f: 0x072f, + // Block 0x2b, offset 0xac0 + 0xac0: 0x2057, 0xac1: 0x205d, 0xac2: 0x2063, 0xac3: 0x2069, 0xac4: 0x206f, 0xac5: 0x2075, + 0xac6: 0x207b, 0xac7: 0x2081, 0xac8: 0x2087, 0xac9: 0x208d, 0xaca: 0x2093, 0xacb: 0x2099, + 0xacc: 0x209f, 0xacd: 0x20a5, 0xace: 0x2729, 0xacf: 0x2732, 0xad0: 0x273b, 0xad1: 0x2744, + 0xad2: 0x274d, 0xad3: 0x2756, 0xad4: 0x275f, 0xad5: 0x2768, 0xad6: 0x2771, 0xad7: 0x2783, + 0xad8: 0x278c, 0xad9: 0x2795, 0xada: 0x279e, 0xadb: 0x27a7, 0xadc: 0x277a, 0xadd: 0x2baf, + 0xade: 0x2af0, 0xae0: 0x20ab, 0xae1: 0x20c3, 0xae2: 0x20b7, 0xae3: 0x210b, + 0xae4: 0x20c9, 0xae5: 0x20e7, 0xae6: 0x20b1, 0xae7: 0x20e1, 0xae8: 0x20bd, 0xae9: 0x20f3, + 0xaea: 0x2123, 0xaeb: 0x2141, 0xaec: 0x213b, 0xaed: 0x212f, 0xaee: 0x217d, 0xaef: 0x2111, + 0xaf0: 0x211d, 0xaf1: 0x2135, 0xaf2: 0x2129, 0xaf3: 0x2153, 0xaf4: 0x20ff, 0xaf5: 0x2147, + 0xaf6: 0x2171, 0xaf7: 0x2159, 0xaf8: 0x20ed, 0xaf9: 0x20cf, 0xafa: 0x2105, 0xafb: 0x2117, + 0xafc: 0x214d, 0xafd: 0x20d5, 0xafe: 0x2177, 0xaff: 0x20f9, + // Block 0x2c, offset 0xb00 + 0xb00: 0x215f, 0xb01: 0x20db, 0xb02: 0x2165, 0xb03: 0x216b, 0xb04: 0x092f, 0xb05: 0x0b03, + 0xb06: 0x0ca7, 0xb07: 0x10c7, + 0xb10: 0x1bc7, 0xb11: 0x18a9, + 0xb12: 0x18ac, 0xb13: 0x18af, 0xb14: 0x18b2, 0xb15: 0x18b5, 0xb16: 0x18b8, 0xb17: 0x18bb, + 0xb18: 0x18be, 0xb19: 0x18c1, 0xb1a: 0x18ca, 0xb1b: 0x18cd, 0xb1c: 0x18d0, 0xb1d: 0x18d3, + 0xb1e: 0x18d6, 0xb1f: 0x18d9, 0xb20: 0x0313, 0xb21: 0x031b, 0xb22: 0x031f, 0xb23: 0x0327, + 0xb24: 0x032b, 0xb25: 0x032f, 0xb26: 0x0337, 0xb27: 0x033f, 0xb28: 0x0343, 0xb29: 0x034b, + 0xb2a: 0x034f, 0xb2b: 0x0353, 0xb2c: 0x0357, 0xb2d: 0x035b, 0xb2e: 0x2e1b, 0xb2f: 0x2e23, + 0xb30: 0x2e2b, 0xb31: 0x2e33, 0xb32: 0x2e3b, 0xb33: 0x2e43, 0xb34: 0x2e4b, 0xb35: 0x2e53, + 0xb36: 0x2e63, 0xb37: 0x2e6b, 0xb38: 0x2e73, 0xb39: 0x2e7b, 0xb3a: 0x2e83, 0xb3b: 0x2e8b, + 0xb3c: 0x2ed6, 0xb3d: 0x2e9e, 0xb3e: 0x2e5b, + // Block 0x2d, offset 0xb40 + 0xb40: 0x06bf, 0xb41: 0x071b, 0xb42: 0x06cb, 0xb43: 0x097b, 0xb44: 0x071f, 0xb45: 0x07af, + 0xb46: 0x06c7, 0xb47: 0x07ab, 0xb48: 0x070b, 0xb49: 0x0887, 0xb4a: 0x0d07, 0xb4b: 0x0e8f, + 0xb4c: 0x0dd7, 0xb4d: 0x0d1b, 0xb4e: 0x145f, 0xb4f: 0x098b, 0xb50: 0x0ccf, 0xb51: 0x0d4b, + 0xb52: 0x0d0b, 0xb53: 0x104b, 0xb54: 0x08fb, 0xb55: 0x0f03, 0xb56: 0x1387, 0xb57: 0x105f, + 0xb58: 0x0843, 0xb59: 0x108f, 0xb5a: 0x0f9b, 0xb5b: 0x0a17, 0xb5c: 0x140f, 0xb5d: 0x077f, + 0xb5e: 0x08ab, 0xb5f: 0x0df7, 0xb60: 0x1527, 0xb61: 0x0743, 0xb62: 0x07d3, 0xb63: 0x0d9b, + 0xb64: 0x06cf, 0xb65: 0x06e7, 0xb66: 0x06d3, 0xb67: 0x0adb, 0xb68: 0x08ef, 0xb69: 0x087f, + 0xb6a: 0x0a57, 0xb6b: 0x0a4b, 0xb6c: 0x0feb, 0xb6d: 0x073f, 0xb6e: 0x139b, 0xb6f: 0x089b, + 0xb70: 0x09f3, 0xb71: 0x18dc, 0xb72: 0x18df, 0xb73: 0x18e2, 0xb74: 0x18e5, 0xb75: 0x18ee, + 0xb76: 0x18f1, 0xb77: 0x18f4, 0xb78: 0x18f7, 0xb79: 0x18fa, 0xb7a: 0x18fd, 0xb7b: 0x1900, + 0xb7c: 0x1903, 0xb7d: 0x1906, 0xb7e: 0x1909, 0xb7f: 0x1912, + // Block 0x2e, offset 0xb80 + 0xb80: 0x1cc9, 0xb81: 0x1cd8, 0xb82: 0x1ce7, 0xb83: 0x1cf6, 0xb84: 0x1d05, 0xb85: 0x1d14, + 0xb86: 0x1d23, 0xb87: 0x1d32, 0xb88: 0x1d41, 0xb89: 0x218f, 0xb8a: 0x21a1, 0xb8b: 0x21b3, + 0xb8c: 0x1954, 0xb8d: 0x1c07, 0xb8e: 0x19d5, 0xb8f: 0x1bab, 0xb90: 0x04cb, 0xb91: 0x04d3, + 0xb92: 0x04db, 0xb93: 0x04e3, 0xb94: 0x04eb, 0xb95: 0x04ef, 0xb96: 0x04f3, 0xb97: 0x04f7, + 0xb98: 0x04fb, 0xb99: 0x04ff, 0xb9a: 0x0503, 0xb9b: 0x0507, 0xb9c: 0x050b, 0xb9d: 0x050f, + 0xb9e: 0x0513, 0xb9f: 0x0517, 0xba0: 0x051b, 0xba1: 0x0523, 0xba2: 0x0527, 0xba3: 0x052b, + 0xba4: 0x052f, 0xba5: 0x0533, 0xba6: 0x0537, 0xba7: 0x053b, 0xba8: 0x053f, 0xba9: 0x0543, + 0xbaa: 0x0547, 0xbab: 0x054b, 0xbac: 0x054f, 0xbad: 0x0553, 0xbae: 0x0557, 0xbaf: 0x055b, + 0xbb0: 0x055f, 0xbb1: 0x0563, 0xbb2: 0x0567, 0xbb3: 0x056f, 0xbb4: 0x0577, 0xbb5: 0x057f, + 0xbb6: 0x0583, 0xbb7: 0x0587, 0xbb8: 0x058b, 0xbb9: 0x058f, 0xbba: 0x0593, 0xbbb: 0x0597, + 0xbbc: 0x059b, 0xbbd: 0x059f, 0xbbe: 0x05a3, + // Block 0x2f, offset 0xbc0 + 0xbc0: 0x2b0f, 0xbc1: 0x29ab, 0xbc2: 0x2b1f, 0xbc3: 0x2883, 0xbc4: 0x2ee7, 0xbc5: 0x288d, + 0xbc6: 0x2897, 0xbc7: 0x2f2b, 0xbc8: 0x29b8, 0xbc9: 0x28a1, 0xbca: 0x28ab, 0xbcb: 0x28b5, + 0xbcc: 0x29df, 0xbcd: 0x29ec, 0xbce: 0x29c5, 0xbcf: 0x29d2, 0xbd0: 0x2eac, 0xbd1: 0x29f9, + 0xbd2: 0x2a06, 0xbd3: 0x2bc1, 0xbd4: 0x26be, 0xbd5: 0x2bd4, 0xbd6: 0x2be7, 0xbd7: 0x2b2f, + 0xbd8: 0x2a13, 0xbd9: 0x2bfa, 0xbda: 0x2c0d, 0xbdb: 0x2a20, 0xbdc: 0x28bf, 0xbdd: 0x28c9, + 0xbde: 0x2eba, 0xbdf: 0x2a2d, 0xbe0: 0x2b3f, 0xbe1: 0x2ef8, 0xbe2: 0x28d3, 0xbe3: 0x28dd, + 0xbe4: 0x2a3a, 0xbe5: 0x28e7, 0xbe6: 0x28f1, 0xbe7: 0x26d3, 0xbe8: 0x26da, 0xbe9: 0x28fb, + 0xbea: 0x2905, 0xbeb: 0x2c20, 0xbec: 0x2a47, 0xbed: 0x2b4f, 0xbee: 0x2c33, 0xbef: 0x2a54, + 0xbf0: 0x2919, 0xbf1: 0x290f, 0xbf2: 0x2f3f, 0xbf3: 0x2a61, 0xbf4: 0x2c46, 0xbf5: 0x2923, + 0xbf6: 0x2b5f, 0xbf7: 0x292d, 0xbf8: 0x2a7b, 0xbf9: 0x2937, 0xbfa: 0x2a88, 0xbfb: 0x2f09, + 0xbfc: 0x2a6e, 0xbfd: 0x2b6f, 0xbfe: 0x2a95, 0xbff: 0x26e1, + // Block 0x30, offset 0xc00 + 0xc00: 0x2f1a, 0xc01: 0x2941, 0xc02: 0x294b, 0xc03: 0x2aa2, 0xc04: 0x2955, 0xc05: 0x295f, + 0xc06: 0x2969, 0xc07: 0x2b7f, 0xc08: 0x2aaf, 0xc09: 0x26e8, 0xc0a: 0x2c59, 0xc0b: 0x2e93, + 0xc0c: 0x2b8f, 0xc0d: 0x2abc, 0xc0e: 0x2ec8, 0xc0f: 0x2973, 0xc10: 0x297d, 0xc11: 0x2ac9, + 0xc12: 0x26ef, 0xc13: 0x2ad6, 0xc14: 0x2b9f, 0xc15: 0x26f6, 0xc16: 0x2c6c, 0xc17: 0x2987, + 0xc18: 0x1cba, 0xc19: 0x1cce, 0xc1a: 0x1cdd, 0xc1b: 0x1cec, 0xc1c: 0x1cfb, 0xc1d: 0x1d0a, + 0xc1e: 0x1d19, 0xc1f: 0x1d28, 0xc20: 0x1d37, 0xc21: 0x1d46, 0xc22: 0x2195, 0xc23: 0x21a7, + 0xc24: 0x21b9, 0xc25: 0x21c5, 0xc26: 0x21d1, 0xc27: 0x21dd, 0xc28: 0x21e9, 0xc29: 0x21f5, + 0xc2a: 0x2201, 0xc2b: 0x220d, 0xc2c: 0x2249, 0xc2d: 0x2255, 0xc2e: 0x2261, 0xc2f: 0x226d, + 0xc30: 0x2279, 0xc31: 0x1c17, 0xc32: 0x19c9, 0xc33: 0x1936, 0xc34: 0x1be7, 0xc35: 0x1a4a, + 0xc36: 0x1a59, 0xc37: 0x19cf, 0xc38: 0x1bff, 0xc39: 0x1c03, 0xc3a: 0x1960, 0xc3b: 0x2704, + 0xc3c: 0x2712, 0xc3d: 0x26fd, 0xc3e: 0x270b, 0xc3f: 0x2ae3, + // Block 0x31, offset 0xc40 + 0xc40: 0x1a4d, 0xc41: 0x1a35, 0xc42: 0x1c63, 0xc43: 0x1a1d, 0xc44: 0x19f6, 0xc45: 0x1969, + 0xc46: 0x1978, 0xc47: 0x1948, 0xc48: 0x1bf3, 0xc49: 0x1d55, 0xc4a: 0x1a50, 0xc4b: 0x1a38, + 0xc4c: 0x1c67, 0xc4d: 0x1c73, 0xc4e: 0x1a29, 0xc4f: 0x19ff, 0xc50: 0x1957, 0xc51: 0x1c1f, + 0xc52: 0x1bb3, 0xc53: 0x1b9f, 0xc54: 0x1bcf, 0xc55: 0x1c77, 0xc56: 0x1a2c, 0xc57: 0x19cc, + 0xc58: 0x1a02, 0xc59: 0x19e1, 0xc5a: 0x1a44, 0xc5b: 0x1c7b, 0xc5c: 0x1a2f, 0xc5d: 0x19c3, + 0xc5e: 0x1a05, 0xc5f: 0x1c3f, 0xc60: 0x1bf7, 0xc61: 0x1a17, 0xc62: 0x1c27, 0xc63: 0x1c43, + 0xc64: 0x1bfb, 0xc65: 0x1a1a, 0xc66: 0x1c2b, 0xc67: 0x22eb, 0xc68: 0x22ff, 0xc69: 0x1999, + 0xc6a: 0x1c23, 0xc6b: 0x1bb7, 0xc6c: 0x1ba3, 0xc6d: 0x1c4b, 0xc6e: 0x2719, 0xc6f: 0x27b0, + 0xc70: 0x1a5c, 0xc71: 0x1a47, 0xc72: 0x1c7f, 0xc73: 0x1a32, 0xc74: 0x1a53, 0xc75: 0x1a3b, + 0xc76: 0x1c6b, 0xc77: 0x1a20, 0xc78: 0x19f9, 0xc79: 0x1984, 0xc7a: 0x1a56, 0xc7b: 0x1a3e, + 0xc7c: 0x1c6f, 0xc7d: 0x1a23, 0xc7e: 0x19fc, 0xc7f: 0x1987, + // Block 0x32, offset 0xc80 + 0xc80: 0x1c2f, 0xc81: 0x1bbb, 0xc82: 0x1d50, 0xc83: 0x1939, 0xc84: 0x19bd, 0xc85: 0x19c0, + 0xc86: 0x22f8, 0xc87: 0x1b97, 0xc88: 0x19c6, 0xc89: 0x194b, 0xc8a: 0x19e4, 0xc8b: 0x194e, + 0xc8c: 0x19ed, 0xc8d: 0x196c, 0xc8e: 0x196f, 0xc8f: 0x1a08, 0xc90: 0x1a0e, 0xc91: 0x1a11, + 0xc92: 0x1c33, 0xc93: 0x1a14, 0xc94: 0x1a26, 0xc95: 0x1c3b, 0xc96: 0x1c47, 0xc97: 0x1993, + 0xc98: 0x1d5a, 0xc99: 0x1bbf, 0xc9a: 0x1996, 0xc9b: 0x1a5f, 0xc9c: 0x19a8, 0xc9d: 0x19b7, + 0xc9e: 0x22e5, 0xc9f: 0x22df, 0xca0: 0x1cc4, 0xca1: 0x1cd3, 0xca2: 0x1ce2, 0xca3: 0x1cf1, + 0xca4: 0x1d00, 0xca5: 0x1d0f, 0xca6: 0x1d1e, 0xca7: 0x1d2d, 0xca8: 0x1d3c, 0xca9: 0x2189, + 0xcaa: 0x219b, 0xcab: 0x21ad, 0xcac: 0x21bf, 0xcad: 0x21cb, 0xcae: 0x21d7, 0xcaf: 0x21e3, + 0xcb0: 0x21ef, 0xcb1: 0x21fb, 0xcb2: 0x2207, 0xcb3: 0x2243, 0xcb4: 0x224f, 0xcb5: 0x225b, + 0xcb6: 0x2267, 0xcb7: 0x2273, 0xcb8: 0x227f, 0xcb9: 0x2285, 0xcba: 0x228b, 0xcbb: 0x2291, + 0xcbc: 0x2297, 0xcbd: 0x22a9, 0xcbe: 0x22af, 0xcbf: 0x1c13, + // Block 0x33, offset 0xcc0 + 0xcc0: 0x1377, 0xcc1: 0x0cfb, 0xcc2: 0x13d3, 0xcc3: 0x139f, 0xcc4: 0x0e57, 0xcc5: 0x06eb, + 0xcc6: 0x08df, 0xcc7: 0x162b, 0xcc8: 0x162b, 0xcc9: 0x0a0b, 0xcca: 0x145f, 0xccb: 0x0943, + 0xccc: 0x0a07, 0xccd: 0x0bef, 0xcce: 0x0fcf, 0xccf: 0x115f, 0xcd0: 0x1297, 0xcd1: 0x12d3, + 0xcd2: 0x1307, 0xcd3: 0x141b, 0xcd4: 0x0d73, 0xcd5: 0x0dff, 0xcd6: 0x0eab, 0xcd7: 0x0f43, + 0xcd8: 0x125f, 0xcd9: 0x1447, 0xcda: 0x1573, 0xcdb: 0x070f, 0xcdc: 0x08b3, 0xcdd: 0x0d87, + 0xcde: 0x0ecf, 0xcdf: 0x1293, 0xce0: 0x15c3, 0xce1: 0x0ab3, 0xce2: 0x0e77, 0xce3: 0x1283, + 0xce4: 0x1317, 0xce5: 0x0c23, 0xce6: 0x11bb, 0xce7: 0x12df, 0xce8: 0x0b1f, 0xce9: 0x0d0f, + 0xcea: 0x0e17, 0xceb: 0x0f1b, 0xcec: 0x1427, 0xced: 0x074f, 0xcee: 0x07e7, 0xcef: 0x0853, + 0xcf0: 0x0c8b, 0xcf1: 0x0d7f, 0xcf2: 0x0ecb, 0xcf3: 0x0fef, 0xcf4: 0x1177, 0xcf5: 0x128b, + 0xcf6: 0x12a3, 0xcf7: 0x13c7, 0xcf8: 0x14ef, 0xcf9: 0x15a3, 0xcfa: 0x15bf, 0xcfb: 0x102b, + 0xcfc: 0x106b, 0xcfd: 0x1123, 0xcfe: 0x1243, 0xcff: 0x147b, + // Block 0x34, offset 0xd00 + 0xd00: 0x15cb, 0xd01: 0x134b, 0xd02: 0x09c7, 0xd03: 0x0b3b, 0xd04: 0x10db, 0xd05: 0x119b, + 0xd06: 0x0eff, 0xd07: 0x1033, 0xd08: 0x1397, 0xd09: 0x14e7, 0xd0a: 0x09c3, 0xd0b: 0x0a8f, + 0xd0c: 0x0d77, 0xd0d: 0x0e2b, 0xd0e: 0x0e5f, 0xd0f: 0x1113, 0xd10: 0x113b, 0xd11: 0x14a7, + 0xd12: 0x084f, 0xd13: 0x11a7, 0xd14: 0x07f3, 0xd15: 0x07ef, 0xd16: 0x1097, 0xd17: 0x1127, + 0xd18: 0x125b, 0xd19: 0x14af, 0xd1a: 0x1367, 0xd1b: 0x0c27, 0xd1c: 0x0d73, 0xd1d: 0x1357, + 0xd1e: 0x06f7, 0xd1f: 0x0a63, 0xd20: 0x0b93, 0xd21: 0x0f2f, 0xd22: 0x0faf, 0xd23: 0x0873, + 0xd24: 0x103b, 0xd25: 0x075f, 0xd26: 0x0b77, 0xd27: 0x06d7, 0xd28: 0x0deb, 0xd29: 0x0ca3, + 0xd2a: 0x110f, 0xd2b: 0x08c7, 0xd2c: 0x09b3, 0xd2d: 0x0ffb, 0xd2e: 0x1263, 0xd2f: 0x133b, + 0xd30: 0x0db7, 0xd31: 0x13f7, 0xd32: 0x0de3, 0xd33: 0x0c37, 0xd34: 0x121b, 0xd35: 0x0c57, + 0xd36: 0x0fab, 0xd37: 0x072b, 0xd38: 0x07a7, 0xd39: 0x07eb, 0xd3a: 0x0d53, 0xd3b: 0x10fb, + 0xd3c: 0x11f3, 0xd3d: 0x1347, 0xd3e: 0x145b, 0xd3f: 0x085b, + // Block 0x35, offset 0xd40 + 0xd40: 0x090f, 0xd41: 0x0a17, 0xd42: 0x0b2f, 0xd43: 0x0cbf, 0xd44: 0x0e7b, 0xd45: 0x103f, + 0xd46: 0x1497, 0xd47: 0x157b, 0xd48: 0x15cf, 0xd49: 0x15e7, 0xd4a: 0x0837, 0xd4b: 0x0cf3, + 0xd4c: 0x0da3, 0xd4d: 0x13eb, 0xd4e: 0x0afb, 0xd4f: 0x0bd7, 0xd50: 0x0bf3, 0xd51: 0x0c83, + 0xd52: 0x0e6b, 0xd53: 0x0eb7, 0xd54: 0x0f67, 0xd55: 0x108b, 0xd56: 0x112f, 0xd57: 0x1193, + 0xd58: 0x13db, 0xd59: 0x126b, 0xd5a: 0x1403, 0xd5b: 0x147f, 0xd5c: 0x080f, 0xd5d: 0x083b, + 0xd5e: 0x0923, 0xd5f: 0x0ea7, 0xd60: 0x12f3, 0xd61: 0x133b, 0xd62: 0x0b1b, 0xd63: 0x0b8b, + 0xd64: 0x0c4f, 0xd65: 0x0daf, 0xd66: 0x10d7, 0xd67: 0x0f23, 0xd68: 0x073b, 0xd69: 0x097f, + 0xd6a: 0x0a63, 0xd6b: 0x0ac7, 0xd6c: 0x0b97, 0xd6d: 0x0f3f, 0xd6e: 0x0f5b, 0xd6f: 0x116b, + 0xd70: 0x118b, 0xd71: 0x1463, 0xd72: 0x14e3, 0xd73: 0x14f3, 0xd74: 0x152f, 0xd75: 0x0753, + 0xd76: 0x107f, 0xd77: 0x144f, 0xd78: 0x14cb, 0xd79: 0x0baf, 0xd7a: 0x0717, 0xd7b: 0x0777, + 0xd7c: 0x0a67, 0xd7d: 0x0a87, 0xd7e: 0x0caf, 0xd7f: 0x0d73, + // Block 0x36, offset 0xd80 + 0xd80: 0x0ec3, 0xd81: 0x0fcb, 0xd82: 0x1277, 0xd83: 0x1417, 0xd84: 0x1623, 0xd85: 0x0ce3, + 0xd86: 0x14a3, 0xd87: 0x0833, 0xd88: 0x0d2f, 0xd89: 0x0d3b, 0xd8a: 0x0e0f, 0xd8b: 0x0e47, + 0xd8c: 0x0f4b, 0xd8d: 0x0fa7, 0xd8e: 0x1027, 0xd8f: 0x110b, 0xd90: 0x153b, 0xd91: 0x07af, + 0xd92: 0x0c03, 0xd93: 0x14b3, 0xd94: 0x0767, 0xd95: 0x0aab, 0xd96: 0x0e2f, 0xd97: 0x13df, + 0xd98: 0x0b67, 0xd99: 0x0bb7, 0xd9a: 0x0d43, 0xd9b: 0x0f2f, 0xd9c: 0x14bb, 0xd9d: 0x0817, + 0xd9e: 0x08ff, 0xd9f: 0x0a97, 0xda0: 0x0cd3, 0xda1: 0x0d1f, 0xda2: 0x0d5f, 0xda3: 0x0df3, + 0xda4: 0x0f47, 0xda5: 0x0fbb, 0xda6: 0x1157, 0xda7: 0x12f7, 0xda8: 0x1303, 0xda9: 0x1457, + 0xdaa: 0x14d7, 0xdab: 0x0883, 0xdac: 0x0e4b, 0xdad: 0x0903, 0xdae: 0x0ec7, 0xdaf: 0x0f6b, + 0xdb0: 0x1287, 0xdb1: 0x14bf, 0xdb2: 0x15ab, 0xdb3: 0x15d3, 0xdb4: 0x0d37, 0xdb5: 0x0e27, + 0xdb6: 0x11c3, 0xdb7: 0x10b7, 0xdb8: 0x10c3, 0xdb9: 0x10e7, 0xdba: 0x0f17, 0xdbb: 0x0e9f, + 0xdbc: 0x1363, 0xdbd: 0x0733, 0xdbe: 0x122b, 0xdbf: 0x081b, + // Block 0x37, offset 0xdc0 + 0xdc0: 0x080b, 0xdc1: 0x0b0b, 0xdc2: 0x0c2b, 0xdc3: 0x10f3, 0xdc4: 0x0a53, 0xdc5: 0x0e03, + 0xdc6: 0x0cef, 0xdc7: 0x13e7, 0xdc8: 0x12e7, 0xdc9: 0x14ab, 0xdca: 0x1323, 0xdcb: 0x0b27, + 0xdcc: 0x0787, 0xdcd: 0x095b, 0xdd0: 0x09af, + 0xdd2: 0x0cdf, 0xdd5: 0x07f7, 0xdd6: 0x0f1f, 0xdd7: 0x0fe3, + 0xdd8: 0x1047, 0xdd9: 0x1063, 0xdda: 0x1067, 0xddb: 0x107b, 0xddc: 0x14fb, 0xddd: 0x10eb, + 0xdde: 0x116f, 0xde0: 0x128f, 0xde2: 0x1353, + 0xde5: 0x1407, 0xde6: 0x1433, + 0xdea: 0x154f, 0xdeb: 0x1553, 0xdec: 0x1557, 0xded: 0x15bb, 0xdee: 0x142b, 0xdef: 0x14c7, + 0xdf0: 0x0757, 0xdf1: 0x077b, 0xdf2: 0x078f, 0xdf3: 0x084b, 0xdf4: 0x0857, 0xdf5: 0x0897, + 0xdf6: 0x094b, 0xdf7: 0x0967, 0xdf8: 0x096f, 0xdf9: 0x09ab, 0xdfa: 0x09b7, 0xdfb: 0x0a93, + 0xdfc: 0x0a9b, 0xdfd: 0x0ba3, 0xdfe: 0x0bcb, 0xdff: 0x0bd3, + // Block 0x38, offset 0xe00 + 0xe00: 0x0beb, 0xe01: 0x0c97, 0xe02: 0x0cc7, 0xe03: 0x0ce7, 0xe04: 0x0d57, 0xe05: 0x0e1b, + 0xe06: 0x0e37, 0xe07: 0x0e67, 0xe08: 0x0ebb, 0xe09: 0x0edb, 0xe0a: 0x0f4f, 0xe0b: 0x102f, + 0xe0c: 0x104b, 0xe0d: 0x1053, 0xe0e: 0x104f, 0xe0f: 0x1057, 0xe10: 0x105b, 0xe11: 0x105f, + 0xe12: 0x1073, 0xe13: 0x1077, 0xe14: 0x109b, 0xe15: 0x10af, 0xe16: 0x10cb, 0xe17: 0x112f, + 0xe18: 0x1137, 0xe19: 0x113f, 0xe1a: 0x1153, 0xe1b: 0x117b, 0xe1c: 0x11cb, 0xe1d: 0x11ff, + 0xe1e: 0x11ff, 0xe1f: 0x1267, 0xe20: 0x130f, 0xe21: 0x1327, 0xe22: 0x135b, 0xe23: 0x135f, + 0xe24: 0x13a3, 0xe25: 0x13a7, 0xe26: 0x13ff, 0xe27: 0x1407, 0xe28: 0x14db, 0xe29: 0x151f, + 0xe2a: 0x1537, 0xe2b: 0x0b9b, 0xe2c: 0x171e, 0xe2d: 0x11e3, + 0xe30: 0x06df, 0xe31: 0x07e3, 0xe32: 0x07a3, 0xe33: 0x074b, 0xe34: 0x078b, 0xe35: 0x07b7, + 0xe36: 0x0847, 0xe37: 0x0863, 0xe38: 0x094b, 0xe39: 0x0937, 0xe3a: 0x0947, 0xe3b: 0x0963, + 0xe3c: 0x09af, 0xe3d: 0x09bf, 0xe3e: 0x0a03, 0xe3f: 0x0a0f, + // Block 0x39, offset 0xe40 + 0xe40: 0x0a2b, 0xe41: 0x0a3b, 0xe42: 0x0b23, 0xe43: 0x0b2b, 0xe44: 0x0b5b, 0xe45: 0x0b7b, + 0xe46: 0x0bab, 0xe47: 0x0bc3, 0xe48: 0x0bb3, 0xe49: 0x0bd3, 0xe4a: 0x0bc7, 0xe4b: 0x0beb, + 0xe4c: 0x0c07, 0xe4d: 0x0c5f, 0xe4e: 0x0c6b, 0xe4f: 0x0c73, 0xe50: 0x0c9b, 0xe51: 0x0cdf, + 0xe52: 0x0d0f, 0xe53: 0x0d13, 0xe54: 0x0d27, 0xe55: 0x0da7, 0xe56: 0x0db7, 0xe57: 0x0e0f, + 0xe58: 0x0e5b, 0xe59: 0x0e53, 0xe5a: 0x0e67, 0xe5b: 0x0e83, 0xe5c: 0x0ebb, 0xe5d: 0x1013, + 0xe5e: 0x0edf, 0xe5f: 0x0f13, 0xe60: 0x0f1f, 0xe61: 0x0f5f, 0xe62: 0x0f7b, 0xe63: 0x0f9f, + 0xe64: 0x0fc3, 0xe65: 0x0fc7, 0xe66: 0x0fe3, 0xe67: 0x0fe7, 0xe68: 0x0ff7, 0xe69: 0x100b, + 0xe6a: 0x1007, 0xe6b: 0x1037, 0xe6c: 0x10b3, 0xe6d: 0x10cb, 0xe6e: 0x10e3, 0xe6f: 0x111b, + 0xe70: 0x112f, 0xe71: 0x114b, 0xe72: 0x117b, 0xe73: 0x122f, 0xe74: 0x1257, 0xe75: 0x12cb, + 0xe76: 0x1313, 0xe77: 0x131f, 0xe78: 0x1327, 0xe79: 0x133f, 0xe7a: 0x1353, 0xe7b: 0x1343, + 0xe7c: 0x135b, 0xe7d: 0x1357, 0xe7e: 0x134f, 0xe7f: 0x135f, + // Block 0x3a, offset 0xe80 + 0xe80: 0x136b, 0xe81: 0x13a7, 0xe82: 0x13e3, 0xe83: 0x1413, 0xe84: 0x144b, 0xe85: 0x146b, + 0xe86: 0x14b7, 0xe87: 0x14db, 0xe88: 0x14fb, 0xe89: 0x150f, 0xe8a: 0x151f, 0xe8b: 0x152b, + 0xe8c: 0x1537, 0xe8d: 0x158b, 0xe8e: 0x162b, 0xe8f: 0x16b5, 0xe90: 0x16b0, 0xe91: 0x16e2, + 0xe92: 0x0607, 0xe93: 0x062f, 0xe94: 0x0633, 0xe95: 0x1764, 0xe96: 0x1791, 0xe97: 0x1809, + 0xe98: 0x1617, 0xe99: 0x1627, + // Block 0x3b, offset 0xec0 + 0xec0: 0x19d8, 0xec1: 0x19db, 0xec2: 0x19de, 0xec3: 0x1c0b, 0xec4: 0x1c0f, 0xec5: 0x1a62, + 0xec6: 0x1a62, + 0xed3: 0x1d78, 0xed4: 0x1d69, 0xed5: 0x1d6e, 0xed6: 0x1d7d, 0xed7: 0x1d73, + 0xedd: 0x4393, + 0xede: 0x8115, 0xedf: 0x4405, 0xee0: 0x022d, 0xee1: 0x0215, 0xee2: 0x021e, 0xee3: 0x0221, + 0xee4: 0x0224, 0xee5: 0x0227, 0xee6: 0x022a, 0xee7: 0x0230, 0xee8: 0x0233, 0xee9: 0x0017, + 0xeea: 0x43f3, 0xeeb: 0x43f9, 0xeec: 0x44f7, 0xeed: 0x44ff, 0xeee: 0x434b, 0xeef: 0x4351, + 0xef0: 0x4357, 0xef1: 0x435d, 0xef2: 0x4369, 0xef3: 0x436f, 0xef4: 0x4375, 0xef5: 0x4381, + 0xef6: 0x4387, 0xef8: 0x438d, 0xef9: 0x4399, 0xefa: 0x439f, 0xefb: 0x43a5, + 0xefc: 0x43b1, 0xefe: 0x43b7, + // Block 0x3c, offset 0xf00 + 0xf00: 0x43bd, 0xf01: 0x43c3, 0xf03: 0x43c9, 0xf04: 0x43cf, + 0xf06: 0x43db, 0xf07: 0x43e1, 0xf08: 0x43e7, 0xf09: 0x43ed, 0xf0a: 0x43ff, 0xf0b: 0x437b, + 0xf0c: 0x4363, 0xf0d: 0x43ab, 0xf0e: 0x43d5, 0xf0f: 0x1d82, 0xf10: 0x0299, 0xf11: 0x0299, + 0xf12: 0x02a2, 0xf13: 0x02a2, 0xf14: 0x02a2, 0xf15: 0x02a2, 0xf16: 0x02a5, 0xf17: 0x02a5, + 0xf18: 0x02a5, 0xf19: 0x02a5, 0xf1a: 0x02ab, 0xf1b: 0x02ab, 0xf1c: 0x02ab, 0xf1d: 0x02ab, + 0xf1e: 0x029f, 0xf1f: 0x029f, 0xf20: 0x029f, 0xf21: 0x029f, 0xf22: 0x02a8, 0xf23: 0x02a8, + 0xf24: 0x02a8, 0xf25: 0x02a8, 0xf26: 0x029c, 0xf27: 0x029c, 0xf28: 0x029c, 0xf29: 0x029c, + 0xf2a: 0x02cf, 0xf2b: 0x02cf, 0xf2c: 0x02cf, 0xf2d: 0x02cf, 0xf2e: 0x02d2, 0xf2f: 0x02d2, + 0xf30: 0x02d2, 0xf31: 0x02d2, 0xf32: 0x02b1, 0xf33: 0x02b1, 0xf34: 0x02b1, 0xf35: 0x02b1, + 0xf36: 0x02ae, 0xf37: 0x02ae, 0xf38: 0x02ae, 0xf39: 0x02ae, 0xf3a: 0x02b4, 0xf3b: 0x02b4, + 0xf3c: 0x02b4, 0xf3d: 0x02b4, 0xf3e: 0x02b7, 0xf3f: 0x02b7, + // Block 0x3d, offset 0xf40 + 0xf40: 0x02b7, 0xf41: 0x02b7, 0xf42: 0x02c0, 0xf43: 0x02c0, 0xf44: 0x02bd, 0xf45: 0x02bd, + 0xf46: 0x02c3, 0xf47: 0x02c3, 0xf48: 0x02ba, 0xf49: 0x02ba, 0xf4a: 0x02c9, 0xf4b: 0x02c9, + 0xf4c: 0x02c6, 0xf4d: 0x02c6, 0xf4e: 0x02d5, 0xf4f: 0x02d5, 0xf50: 0x02d5, 0xf51: 0x02d5, + 0xf52: 0x02db, 0xf53: 0x02db, 0xf54: 0x02db, 0xf55: 0x02db, 0xf56: 0x02e1, 0xf57: 0x02e1, + 0xf58: 0x02e1, 0xf59: 0x02e1, 0xf5a: 0x02de, 0xf5b: 0x02de, 0xf5c: 0x02de, 0xf5d: 0x02de, + 0xf5e: 0x02e4, 0xf5f: 0x02e4, 0xf60: 0x02e7, 0xf61: 0x02e7, 0xf62: 0x02e7, 0xf63: 0x02e7, + 0xf64: 0x4471, 0xf65: 0x4471, 0xf66: 0x02ed, 0xf67: 0x02ed, 0xf68: 0x02ed, 0xf69: 0x02ed, + 0xf6a: 0x02ea, 0xf6b: 0x02ea, 0xf6c: 0x02ea, 0xf6d: 0x02ea, 0xf6e: 0x0308, 0xf6f: 0x0308, + 0xf70: 0x446b, 0xf71: 0x446b, + // Block 0x3e, offset 0xf80 + 0xf93: 0x02d8, 0xf94: 0x02d8, 0xf95: 0x02d8, 0xf96: 0x02d8, 0xf97: 0x02f6, + 0xf98: 0x02f6, 0xf99: 0x02f3, 0xf9a: 0x02f3, 0xf9b: 0x02f9, 0xf9c: 0x02f9, 0xf9d: 0x2052, + 0xf9e: 0x02ff, 0xf9f: 0x02ff, 0xfa0: 0x02f0, 0xfa1: 0x02f0, 0xfa2: 0x02fc, 0xfa3: 0x02fc, + 0xfa4: 0x0305, 0xfa5: 0x0305, 0xfa6: 0x0305, 0xfa7: 0x0305, 0xfa8: 0x028d, 0xfa9: 0x028d, + 0xfaa: 0x25ad, 0xfab: 0x25ad, 0xfac: 0x261d, 0xfad: 0x261d, 0xfae: 0x25ec, 0xfaf: 0x25ec, + 0xfb0: 0x2608, 0xfb1: 0x2608, 0xfb2: 0x2601, 0xfb3: 0x2601, 0xfb4: 0x260f, 0xfb5: 0x260f, + 0xfb6: 0x2616, 0xfb7: 0x2616, 0xfb8: 0x2616, 0xfb9: 0x25f3, 0xfba: 0x25f3, 0xfbb: 0x25f3, + 0xfbc: 0x0302, 0xfbd: 0x0302, 0xfbe: 0x0302, 0xfbf: 0x0302, + // Block 0x3f, offset 0xfc0 + 0xfc0: 0x25b4, 0xfc1: 0x25bb, 0xfc2: 0x25d7, 0xfc3: 0x25f3, 0xfc4: 0x25fa, 0xfc5: 0x1d8c, + 0xfc6: 0x1d91, 0xfc7: 0x1d96, 0xfc8: 0x1da5, 0xfc9: 0x1db4, 0xfca: 0x1db9, 0xfcb: 0x1dbe, + 0xfcc: 0x1dc3, 0xfcd: 0x1dc8, 0xfce: 0x1dd7, 0xfcf: 0x1de6, 0xfd0: 0x1deb, 0xfd1: 0x1df0, + 0xfd2: 0x1dff, 0xfd3: 0x1e0e, 0xfd4: 0x1e13, 0xfd5: 0x1e18, 0xfd6: 0x1e1d, 0xfd7: 0x1e2c, + 0xfd8: 0x1e31, 0xfd9: 0x1e40, 0xfda: 0x1e45, 0xfdb: 0x1e4a, 0xfdc: 0x1e59, 0xfdd: 0x1e5e, + 0xfde: 0x1e63, 0xfdf: 0x1e6d, 0xfe0: 0x1ea9, 0xfe1: 0x1eb8, 0xfe2: 0x1ec7, 0xfe3: 0x1ecc, + 0xfe4: 0x1ed1, 0xfe5: 0x1edb, 0xfe6: 0x1eea, 0xfe7: 0x1eef, 0xfe8: 0x1efe, 0xfe9: 0x1f03, + 0xfea: 0x1f08, 0xfeb: 0x1f17, 0xfec: 0x1f1c, 0xfed: 0x1f2b, 0xfee: 0x1f30, 0xfef: 0x1f35, + 0xff0: 0x1f3a, 0xff1: 0x1f3f, 0xff2: 0x1f44, 0xff3: 0x1f49, 0xff4: 0x1f4e, 0xff5: 0x1f53, + 0xff6: 0x1f58, 0xff7: 0x1f5d, 0xff8: 0x1f62, 0xff9: 0x1f67, 0xffa: 0x1f6c, 0xffb: 0x1f71, + 0xffc: 0x1f76, 0xffd: 0x1f7b, 0xffe: 0x1f80, 0xfff: 0x1f8a, + // Block 0x40, offset 0x1000 + 0x1000: 0x1f8f, 0x1001: 0x1f94, 0x1002: 0x1f99, 0x1003: 0x1fa3, 0x1004: 0x1fa8, 0x1005: 0x1fb2, + 0x1006: 0x1fb7, 0x1007: 0x1fbc, 0x1008: 0x1fc1, 0x1009: 0x1fc6, 0x100a: 0x1fcb, 0x100b: 0x1fd0, + 0x100c: 0x1fd5, 0x100d: 0x1fda, 0x100e: 0x1fe9, 0x100f: 0x1ff8, 0x1010: 0x1ffd, 0x1011: 0x2002, + 0x1012: 0x2007, 0x1013: 0x200c, 0x1014: 0x2011, 0x1015: 0x201b, 0x1016: 0x2020, 0x1017: 0x2025, + 0x1018: 0x2034, 0x1019: 0x2043, 0x101a: 0x2048, 0x101b: 0x4423, 0x101c: 0x4429, 0x101d: 0x445f, + 0x101e: 0x44b6, 0x101f: 0x44bd, 0x1020: 0x44c4, 0x1021: 0x44cb, 0x1022: 0x44d2, 0x1023: 0x44d9, + 0x1024: 0x25c9, 0x1025: 0x25d0, 0x1026: 0x25d7, 0x1027: 0x25de, 0x1028: 0x25f3, 0x1029: 0x25fa, + 0x102a: 0x1d9b, 0x102b: 0x1da0, 0x102c: 0x1da5, 0x102d: 0x1daa, 0x102e: 0x1db4, 0x102f: 0x1db9, + 0x1030: 0x1dcd, 0x1031: 0x1dd2, 0x1032: 0x1dd7, 0x1033: 0x1ddc, 0x1034: 0x1de6, 0x1035: 0x1deb, + 0x1036: 0x1df5, 0x1037: 0x1dfa, 0x1038: 0x1dff, 0x1039: 0x1e04, 0x103a: 0x1e0e, 0x103b: 0x1e13, + 0x103c: 0x1f3f, 0x103d: 0x1f44, 0x103e: 0x1f53, 0x103f: 0x1f58, + // Block 0x41, offset 0x1040 + 0x1040: 0x1f5d, 0x1041: 0x1f71, 0x1042: 0x1f76, 0x1043: 0x1f7b, 0x1044: 0x1f80, 0x1045: 0x1f99, + 0x1046: 0x1fa3, 0x1047: 0x1fa8, 0x1048: 0x1fad, 0x1049: 0x1fc1, 0x104a: 0x1fdf, 0x104b: 0x1fe4, + 0x104c: 0x1fe9, 0x104d: 0x1fee, 0x104e: 0x1ff8, 0x104f: 0x1ffd, 0x1050: 0x445f, 0x1051: 0x202a, + 0x1052: 0x202f, 0x1053: 0x2034, 0x1054: 0x2039, 0x1055: 0x2043, 0x1056: 0x2048, 0x1057: 0x25b4, + 0x1058: 0x25bb, 0x1059: 0x25c2, 0x105a: 0x25d7, 0x105b: 0x25e5, 0x105c: 0x1d8c, 0x105d: 0x1d91, + 0x105e: 0x1d96, 0x105f: 0x1da5, 0x1060: 0x1daf, 0x1061: 0x1dbe, 0x1062: 0x1dc3, 0x1063: 0x1dc8, + 0x1064: 0x1dd7, 0x1065: 0x1de1, 0x1066: 0x1dff, 0x1067: 0x1e18, 0x1068: 0x1e1d, 0x1069: 0x1e2c, + 0x106a: 0x1e31, 0x106b: 0x1e40, 0x106c: 0x1e4a, 0x106d: 0x1e59, 0x106e: 0x1e5e, 0x106f: 0x1e63, + 0x1070: 0x1e6d, 0x1071: 0x1ea9, 0x1072: 0x1eae, 0x1073: 0x1eb8, 0x1074: 0x1ec7, 0x1075: 0x1ecc, + 0x1076: 0x1ed1, 0x1077: 0x1edb, 0x1078: 0x1eea, 0x1079: 0x1efe, 0x107a: 0x1f03, 0x107b: 0x1f08, + 0x107c: 0x1f17, 0x107d: 0x1f1c, 0x107e: 0x1f2b, 0x107f: 0x1f30, + // Block 0x42, offset 0x1080 + 0x1080: 0x1f35, 0x1081: 0x1f3a, 0x1082: 0x1f49, 0x1083: 0x1f4e, 0x1084: 0x1f62, 0x1085: 0x1f67, + 0x1086: 0x1f6c, 0x1087: 0x1f71, 0x1088: 0x1f76, 0x1089: 0x1f8a, 0x108a: 0x1f8f, 0x108b: 0x1f94, + 0x108c: 0x1f99, 0x108d: 0x1f9e, 0x108e: 0x1fb2, 0x108f: 0x1fb7, 0x1090: 0x1fbc, 0x1091: 0x1fc1, + 0x1092: 0x1fd0, 0x1093: 0x1fd5, 0x1094: 0x1fda, 0x1095: 0x1fe9, 0x1096: 0x1ff3, 0x1097: 0x2002, + 0x1098: 0x2007, 0x1099: 0x4453, 0x109a: 0x201b, 0x109b: 0x2020, 0x109c: 0x2025, 0x109d: 0x2034, + 0x109e: 0x203e, 0x109f: 0x25d7, 0x10a0: 0x25e5, 0x10a1: 0x1da5, 0x10a2: 0x1daf, 0x10a3: 0x1dd7, + 0x10a4: 0x1de1, 0x10a5: 0x1dff, 0x10a6: 0x1e09, 0x10a7: 0x1e6d, 0x10a8: 0x1e72, 0x10a9: 0x1e95, + 0x10aa: 0x1e9a, 0x10ab: 0x1f71, 0x10ac: 0x1f76, 0x10ad: 0x1f99, 0x10ae: 0x1fe9, 0x10af: 0x1ff3, + 0x10b0: 0x2034, 0x10b1: 0x203e, 0x10b2: 0x4507, 0x10b3: 0x450f, 0x10b4: 0x4517, 0x10b5: 0x1ef4, + 0x10b6: 0x1ef9, 0x10b7: 0x1f0d, 0x10b8: 0x1f12, 0x10b9: 0x1f21, 0x10ba: 0x1f26, 0x10bb: 0x1e77, + 0x10bc: 0x1e7c, 0x10bd: 0x1e9f, 0x10be: 0x1ea4, 0x10bf: 0x1e36, + // Block 0x43, offset 0x10c0 + 0x10c0: 0x1e3b, 0x10c1: 0x1e22, 0x10c2: 0x1e27, 0x10c3: 0x1e4f, 0x10c4: 0x1e54, 0x10c5: 0x1ebd, + 0x10c6: 0x1ec2, 0x10c7: 0x1ee0, 0x10c8: 0x1ee5, 0x10c9: 0x1e81, 0x10ca: 0x1e86, 0x10cb: 0x1e8b, + 0x10cc: 0x1e95, 0x10cd: 0x1e90, 0x10ce: 0x1e68, 0x10cf: 0x1eb3, 0x10d0: 0x1ed6, 0x10d1: 0x1ef4, + 0x10d2: 0x1ef9, 0x10d3: 0x1f0d, 0x10d4: 0x1f12, 0x10d5: 0x1f21, 0x10d6: 0x1f26, 0x10d7: 0x1e77, + 0x10d8: 0x1e7c, 0x10d9: 0x1e9f, 0x10da: 0x1ea4, 0x10db: 0x1e36, 0x10dc: 0x1e3b, 0x10dd: 0x1e22, + 0x10de: 0x1e27, 0x10df: 0x1e4f, 0x10e0: 0x1e54, 0x10e1: 0x1ebd, 0x10e2: 0x1ec2, 0x10e3: 0x1ee0, + 0x10e4: 0x1ee5, 0x10e5: 0x1e81, 0x10e6: 0x1e86, 0x10e7: 0x1e8b, 0x10e8: 0x1e95, 0x10e9: 0x1e90, + 0x10ea: 0x1e68, 0x10eb: 0x1eb3, 0x10ec: 0x1ed6, 0x10ed: 0x1e81, 0x10ee: 0x1e86, 0x10ef: 0x1e8b, + 0x10f0: 0x1e95, 0x10f1: 0x1e72, 0x10f2: 0x1e9a, 0x10f3: 0x1eef, 0x10f4: 0x1e59, 0x10f5: 0x1e5e, + 0x10f6: 0x1e63, 0x10f7: 0x1e81, 0x10f8: 0x1e86, 0x10f9: 0x1e8b, 0x10fa: 0x1eef, 0x10fb: 0x1efe, + 0x10fc: 0x440b, 0x10fd: 0x440b, + // Block 0x44, offset 0x1100 + 0x1110: 0x2314, 0x1111: 0x2329, + 0x1112: 0x2329, 0x1113: 0x2330, 0x1114: 0x2337, 0x1115: 0x234c, 0x1116: 0x2353, 0x1117: 0x235a, + 0x1118: 0x237d, 0x1119: 0x237d, 0x111a: 0x23a0, 0x111b: 0x2399, 0x111c: 0x23b5, 0x111d: 0x23a7, + 0x111e: 0x23ae, 0x111f: 0x23d1, 0x1120: 0x23d1, 0x1121: 0x23ca, 0x1122: 0x23d8, 0x1123: 0x23d8, + 0x1124: 0x2402, 0x1125: 0x2402, 0x1126: 0x241e, 0x1127: 0x23e6, 0x1128: 0x23e6, 0x1129: 0x23df, + 0x112a: 0x23f4, 0x112b: 0x23f4, 0x112c: 0x23fb, 0x112d: 0x23fb, 0x112e: 0x2425, 0x112f: 0x2433, + 0x1130: 0x2433, 0x1131: 0x243a, 0x1132: 0x243a, 0x1133: 0x2441, 0x1134: 0x2448, 0x1135: 0x244f, + 0x1136: 0x2456, 0x1137: 0x2456, 0x1138: 0x245d, 0x1139: 0x246b, 0x113a: 0x2479, 0x113b: 0x2472, + 0x113c: 0x2480, 0x113d: 0x2480, 0x113e: 0x2495, 0x113f: 0x249c, + // Block 0x45, offset 0x1140 + 0x1140: 0x24cd, 0x1141: 0x24db, 0x1142: 0x24d4, 0x1143: 0x24b8, 0x1144: 0x24b8, 0x1145: 0x24e2, + 0x1146: 0x24e2, 0x1147: 0x24e9, 0x1148: 0x24e9, 0x1149: 0x2513, 0x114a: 0x251a, 0x114b: 0x2521, + 0x114c: 0x24f7, 0x114d: 0x2505, 0x114e: 0x2528, 0x114f: 0x252f, + 0x1152: 0x24fe, 0x1153: 0x2583, 0x1154: 0x258a, 0x1155: 0x2560, 0x1156: 0x2567, 0x1157: 0x254b, + 0x1158: 0x254b, 0x1159: 0x2552, 0x115a: 0x257c, 0x115b: 0x2575, 0x115c: 0x259f, 0x115d: 0x259f, + 0x115e: 0x230d, 0x115f: 0x2322, 0x1160: 0x231b, 0x1161: 0x2345, 0x1162: 0x233e, 0x1163: 0x2368, + 0x1164: 0x2361, 0x1165: 0x238b, 0x1166: 0x236f, 0x1167: 0x2384, 0x1168: 0x23bc, 0x1169: 0x2409, + 0x116a: 0x23ed, 0x116b: 0x242c, 0x116c: 0x24c6, 0x116d: 0x24f0, 0x116e: 0x2598, 0x116f: 0x2591, + 0x1170: 0x25a6, 0x1171: 0x253d, 0x1172: 0x24a3, 0x1173: 0x256e, 0x1174: 0x2495, 0x1175: 0x24cd, + 0x1176: 0x2464, 0x1177: 0x24b1, 0x1178: 0x2544, 0x1179: 0x2536, 0x117a: 0x24bf, 0x117b: 0x24aa, + 0x117c: 0x24bf, 0x117d: 0x2544, 0x117e: 0x2376, 0x117f: 0x2392, + // Block 0x46, offset 0x1180 + 0x1180: 0x250c, 0x1181: 0x2487, 0x1182: 0x2306, 0x1183: 0x24aa, 0x1184: 0x244f, 0x1185: 0x241e, + 0x1186: 0x23c3, 0x1187: 0x2559, + 0x11b0: 0x2417, 0x11b1: 0x248e, 0x11b2: 0x27c2, 0x11b3: 0x27b9, 0x11b4: 0x27ef, 0x11b5: 0x27dd, + 0x11b6: 0x27cb, 0x11b7: 0x27e6, 0x11b8: 0x27f8, 0x11b9: 0x2410, 0x11ba: 0x2c7f, 0x11bb: 0x2aff, + 0x11bc: 0x27d4, + // Block 0x47, offset 0x11c0 + 0x11d0: 0x0019, 0x11d1: 0x0483, + 0x11d2: 0x0487, 0x11d3: 0x0035, 0x11d4: 0x0037, 0x11d5: 0x0003, 0x11d6: 0x003f, 0x11d7: 0x04bf, + 0x11d8: 0x04c3, 0x11d9: 0x1b5f, + 0x11e0: 0x8132, 0x11e1: 0x8132, 0x11e2: 0x8132, 0x11e3: 0x8132, + 0x11e4: 0x8132, 0x11e5: 0x8132, 0x11e6: 0x8132, 0x11e7: 0x812d, 0x11e8: 0x812d, 0x11e9: 0x812d, + 0x11ea: 0x812d, 0x11eb: 0x812d, 0x11ec: 0x812d, 0x11ed: 0x812d, 0x11ee: 0x8132, 0x11ef: 0x8132, + 0x11f0: 0x1873, 0x11f1: 0x0443, 0x11f2: 0x043f, 0x11f3: 0x007f, 0x11f4: 0x007f, 0x11f5: 0x0011, + 0x11f6: 0x0013, 0x11f7: 0x00b7, 0x11f8: 0x00bb, 0x11f9: 0x04b7, 0x11fa: 0x04bb, 0x11fb: 0x04ab, + 0x11fc: 0x04af, 0x11fd: 0x0493, 0x11fe: 0x0497, 0x11ff: 0x048b, + // Block 0x48, offset 0x1200 + 0x1200: 0x048f, 0x1201: 0x049b, 0x1202: 0x049f, 0x1203: 0x04a3, 0x1204: 0x04a7, + 0x1207: 0x0077, 0x1208: 0x007b, 0x1209: 0x426c, 0x120a: 0x426c, 0x120b: 0x426c, + 0x120c: 0x426c, 0x120d: 0x007f, 0x120e: 0x007f, 0x120f: 0x007f, 0x1210: 0x0019, 0x1211: 0x0483, + 0x1212: 0x001d, 0x1214: 0x0037, 0x1215: 0x0035, 0x1216: 0x003f, 0x1217: 0x0003, + 0x1218: 0x0443, 0x1219: 0x0011, 0x121a: 0x0013, 0x121b: 0x00b7, 0x121c: 0x00bb, 0x121d: 0x04b7, + 0x121e: 0x04bb, 0x121f: 0x0007, 0x1220: 0x000d, 0x1221: 0x0015, 0x1222: 0x0017, 0x1223: 0x001b, + 0x1224: 0x0039, 0x1225: 0x003d, 0x1226: 0x003b, 0x1228: 0x0079, 0x1229: 0x0009, + 0x122a: 0x000b, 0x122b: 0x0041, + 0x1230: 0x42ad, 0x1231: 0x442f, 0x1232: 0x42b2, 0x1234: 0x42b7, + 0x1236: 0x42bc, 0x1237: 0x4435, 0x1238: 0x42c1, 0x1239: 0x443b, 0x123a: 0x42c6, 0x123b: 0x4441, + 0x123c: 0x42cb, 0x123d: 0x4447, 0x123e: 0x42d0, 0x123f: 0x444d, + // Block 0x49, offset 0x1240 + 0x1240: 0x0236, 0x1241: 0x4411, 0x1242: 0x4411, 0x1243: 0x4417, 0x1244: 0x4417, 0x1245: 0x4459, + 0x1246: 0x4459, 0x1247: 0x441d, 0x1248: 0x441d, 0x1249: 0x4465, 0x124a: 0x4465, 0x124b: 0x4465, + 0x124c: 0x4465, 0x124d: 0x0239, 0x124e: 0x0239, 0x124f: 0x023c, 0x1250: 0x023c, 0x1251: 0x023c, + 0x1252: 0x023c, 0x1253: 0x023f, 0x1254: 0x023f, 0x1255: 0x0242, 0x1256: 0x0242, 0x1257: 0x0242, + 0x1258: 0x0242, 0x1259: 0x0245, 0x125a: 0x0245, 0x125b: 0x0245, 0x125c: 0x0245, 0x125d: 0x0248, + 0x125e: 0x0248, 0x125f: 0x0248, 0x1260: 0x0248, 0x1261: 0x024b, 0x1262: 0x024b, 0x1263: 0x024b, + 0x1264: 0x024b, 0x1265: 0x024e, 0x1266: 0x024e, 0x1267: 0x024e, 0x1268: 0x024e, 0x1269: 0x0251, + 0x126a: 0x0251, 0x126b: 0x0254, 0x126c: 0x0254, 0x126d: 0x0257, 0x126e: 0x0257, 0x126f: 0x025a, + 0x1270: 0x025a, 0x1271: 0x025d, 0x1272: 0x025d, 0x1273: 0x025d, 0x1274: 0x025d, 0x1275: 0x0260, + 0x1276: 0x0260, 0x1277: 0x0260, 0x1278: 0x0260, 0x1279: 0x0263, 0x127a: 0x0263, 0x127b: 0x0263, + 0x127c: 0x0263, 0x127d: 0x0266, 0x127e: 0x0266, 0x127f: 0x0266, + // Block 0x4a, offset 0x1280 + 0x1280: 0x0266, 0x1281: 0x0269, 0x1282: 0x0269, 0x1283: 0x0269, 0x1284: 0x0269, 0x1285: 0x026c, + 0x1286: 0x026c, 0x1287: 0x026c, 0x1288: 0x026c, 0x1289: 0x026f, 0x128a: 0x026f, 0x128b: 0x026f, + 0x128c: 0x026f, 0x128d: 0x0272, 0x128e: 0x0272, 0x128f: 0x0272, 0x1290: 0x0272, 0x1291: 0x0275, + 0x1292: 0x0275, 0x1293: 0x0275, 0x1294: 0x0275, 0x1295: 0x0278, 0x1296: 0x0278, 0x1297: 0x0278, + 0x1298: 0x0278, 0x1299: 0x027b, 0x129a: 0x027b, 0x129b: 0x027b, 0x129c: 0x027b, 0x129d: 0x027e, + 0x129e: 0x027e, 0x129f: 0x027e, 0x12a0: 0x027e, 0x12a1: 0x0281, 0x12a2: 0x0281, 0x12a3: 0x0281, + 0x12a4: 0x0281, 0x12a5: 0x0284, 0x12a6: 0x0284, 0x12a7: 0x0284, 0x12a8: 0x0284, 0x12a9: 0x0287, + 0x12aa: 0x0287, 0x12ab: 0x0287, 0x12ac: 0x0287, 0x12ad: 0x028a, 0x12ae: 0x028a, 0x12af: 0x028d, + 0x12b0: 0x028d, 0x12b1: 0x0290, 0x12b2: 0x0290, 0x12b3: 0x0290, 0x12b4: 0x0290, 0x12b5: 0x2e03, + 0x12b6: 0x2e03, 0x12b7: 0x2e0b, 0x12b8: 0x2e0b, 0x12b9: 0x2e13, 0x12ba: 0x2e13, 0x12bb: 0x1f85, + 0x12bc: 0x1f85, + // Block 0x4b, offset 0x12c0 + 0x12c0: 0x0081, 0x12c1: 0x0083, 0x12c2: 0x0085, 0x12c3: 0x0087, 0x12c4: 0x0089, 0x12c5: 0x008b, + 0x12c6: 0x008d, 0x12c7: 0x008f, 0x12c8: 0x0091, 0x12c9: 0x0093, 0x12ca: 0x0095, 0x12cb: 0x0097, + 0x12cc: 0x0099, 0x12cd: 0x009b, 0x12ce: 0x009d, 0x12cf: 0x009f, 0x12d0: 0x00a1, 0x12d1: 0x00a3, + 0x12d2: 0x00a5, 0x12d3: 0x00a7, 0x12d4: 0x00a9, 0x12d5: 0x00ab, 0x12d6: 0x00ad, 0x12d7: 0x00af, + 0x12d8: 0x00b1, 0x12d9: 0x00b3, 0x12da: 0x00b5, 0x12db: 0x00b7, 0x12dc: 0x00b9, 0x12dd: 0x00bb, + 0x12de: 0x00bd, 0x12df: 0x0477, 0x12e0: 0x047b, 0x12e1: 0x0487, 0x12e2: 0x049b, 0x12e3: 0x049f, + 0x12e4: 0x0483, 0x12e5: 0x05ab, 0x12e6: 0x05a3, 0x12e7: 0x04c7, 0x12e8: 0x04cf, 0x12e9: 0x04d7, + 0x12ea: 0x04df, 0x12eb: 0x04e7, 0x12ec: 0x056b, 0x12ed: 0x0573, 0x12ee: 0x057b, 0x12ef: 0x051f, + 0x12f0: 0x05af, 0x12f1: 0x04cb, 0x12f2: 0x04d3, 0x12f3: 0x04db, 0x12f4: 0x04e3, 0x12f5: 0x04eb, + 0x12f6: 0x04ef, 0x12f7: 0x04f3, 0x12f8: 0x04f7, 0x12f9: 0x04fb, 0x12fa: 0x04ff, 0x12fb: 0x0503, + 0x12fc: 0x0507, 0x12fd: 0x050b, 0x12fe: 0x050f, 0x12ff: 0x0513, + // Block 0x4c, offset 0x1300 + 0x1300: 0x0517, 0x1301: 0x051b, 0x1302: 0x0523, 0x1303: 0x0527, 0x1304: 0x052b, 0x1305: 0x052f, + 0x1306: 0x0533, 0x1307: 0x0537, 0x1308: 0x053b, 0x1309: 0x053f, 0x130a: 0x0543, 0x130b: 0x0547, + 0x130c: 0x054b, 0x130d: 0x054f, 0x130e: 0x0553, 0x130f: 0x0557, 0x1310: 0x055b, 0x1311: 0x055f, + 0x1312: 0x0563, 0x1313: 0x0567, 0x1314: 0x056f, 0x1315: 0x0577, 0x1316: 0x057f, 0x1317: 0x0583, + 0x1318: 0x0587, 0x1319: 0x058b, 0x131a: 0x058f, 0x131b: 0x0593, 0x131c: 0x0597, 0x131d: 0x05a7, + 0x131e: 0x4a7b, 0x131f: 0x4a81, 0x1320: 0x03c3, 0x1321: 0x0313, 0x1322: 0x0317, 0x1323: 0x4a3e, + 0x1324: 0x031b, 0x1325: 0x4a44, 0x1326: 0x4a4a, 0x1327: 0x031f, 0x1328: 0x0323, 0x1329: 0x0327, + 0x132a: 0x4a50, 0x132b: 0x4a56, 0x132c: 0x4a5c, 0x132d: 0x4a62, 0x132e: 0x4a68, 0x132f: 0x4a6e, + 0x1330: 0x0367, 0x1331: 0x032b, 0x1332: 0x032f, 0x1333: 0x0333, 0x1334: 0x037b, 0x1335: 0x0337, + 0x1336: 0x033b, 0x1337: 0x033f, 0x1338: 0x0343, 0x1339: 0x0347, 0x133a: 0x034b, 0x133b: 0x034f, + 0x133c: 0x0353, 0x133d: 0x0357, 0x133e: 0x035b, + // Block 0x4d, offset 0x1340 + 0x1342: 0x49c0, 0x1343: 0x49c6, 0x1344: 0x49cc, 0x1345: 0x49d2, + 0x1346: 0x49d8, 0x1347: 0x49de, 0x134a: 0x49e4, 0x134b: 0x49ea, + 0x134c: 0x49f0, 0x134d: 0x49f6, 0x134e: 0x49fc, 0x134f: 0x4a02, + 0x1352: 0x4a08, 0x1353: 0x4a0e, 0x1354: 0x4a14, 0x1355: 0x4a1a, 0x1356: 0x4a20, 0x1357: 0x4a26, + 0x135a: 0x4a2c, 0x135b: 0x4a32, 0x135c: 0x4a38, + 0x1360: 0x00bf, 0x1361: 0x00c2, 0x1362: 0x00cb, 0x1363: 0x4267, + 0x1364: 0x00c8, 0x1365: 0x00c5, 0x1366: 0x0447, 0x1368: 0x046b, 0x1369: 0x044b, + 0x136a: 0x044f, 0x136b: 0x0453, 0x136c: 0x0457, 0x136d: 0x046f, 0x136e: 0x0473, + // Block 0x4e, offset 0x1380 + 0x1380: 0x0063, 0x1381: 0x0065, 0x1382: 0x0067, 0x1383: 0x0069, 0x1384: 0x006b, 0x1385: 0x006d, + 0x1386: 0x006f, 0x1387: 0x0071, 0x1388: 0x0073, 0x1389: 0x0075, 0x138a: 0x0083, 0x138b: 0x0085, + 0x138c: 0x0087, 0x138d: 0x0089, 0x138e: 0x008b, 0x138f: 0x008d, 0x1390: 0x008f, 0x1391: 0x0091, + 0x1392: 0x0093, 0x1393: 0x0095, 0x1394: 0x0097, 0x1395: 0x0099, 0x1396: 0x009b, 0x1397: 0x009d, + 0x1398: 0x009f, 0x1399: 0x00a1, 0x139a: 0x00a3, 0x139b: 0x00a5, 0x139c: 0x00a7, 0x139d: 0x00a9, + 0x139e: 0x00ab, 0x139f: 0x00ad, 0x13a0: 0x00af, 0x13a1: 0x00b1, 0x13a2: 0x00b3, 0x13a3: 0x00b5, + 0x13a4: 0x00dd, 0x13a5: 0x00f2, 0x13a8: 0x0173, 0x13a9: 0x0176, + 0x13aa: 0x0179, 0x13ab: 0x017c, 0x13ac: 0x017f, 0x13ad: 0x0182, 0x13ae: 0x0185, 0x13af: 0x0188, + 0x13b0: 0x018b, 0x13b1: 0x018e, 0x13b2: 0x0191, 0x13b3: 0x0194, 0x13b4: 0x0197, 0x13b5: 0x019a, + 0x13b6: 0x019d, 0x13b7: 0x01a0, 0x13b8: 0x01a3, 0x13b9: 0x0188, 0x13ba: 0x01a6, 0x13bb: 0x01a9, + 0x13bc: 0x01ac, 0x13bd: 0x01af, 0x13be: 0x01b2, 0x13bf: 0x01b5, + // Block 0x4f, offset 0x13c0 + 0x13c0: 0x01fd, 0x13c1: 0x0200, 0x13c2: 0x0203, 0x13c3: 0x045b, 0x13c4: 0x01c7, 0x13c5: 0x01d0, + 0x13c6: 0x01d6, 0x13c7: 0x01fa, 0x13c8: 0x01eb, 0x13c9: 0x01e8, 0x13ca: 0x0206, 0x13cb: 0x0209, + 0x13ce: 0x0021, 0x13cf: 0x0023, 0x13d0: 0x0025, 0x13d1: 0x0027, + 0x13d2: 0x0029, 0x13d3: 0x002b, 0x13d4: 0x002d, 0x13d5: 0x002f, 0x13d6: 0x0031, 0x13d7: 0x0033, + 0x13d8: 0x0021, 0x13d9: 0x0023, 0x13da: 0x0025, 0x13db: 0x0027, 0x13dc: 0x0029, 0x13dd: 0x002b, + 0x13de: 0x002d, 0x13df: 0x002f, 0x13e0: 0x0031, 0x13e1: 0x0033, 0x13e2: 0x0021, 0x13e3: 0x0023, + 0x13e4: 0x0025, 0x13e5: 0x0027, 0x13e6: 0x0029, 0x13e7: 0x002b, 0x13e8: 0x002d, 0x13e9: 0x002f, + 0x13ea: 0x0031, 0x13eb: 0x0033, 0x13ec: 0x0021, 0x13ed: 0x0023, 0x13ee: 0x0025, 0x13ef: 0x0027, + 0x13f0: 0x0029, 0x13f1: 0x002b, 0x13f2: 0x002d, 0x13f3: 0x002f, 0x13f4: 0x0031, 0x13f5: 0x0033, + 0x13f6: 0x0021, 0x13f7: 0x0023, 0x13f8: 0x0025, 0x13f9: 0x0027, 0x13fa: 0x0029, 0x13fb: 0x002b, + 0x13fc: 0x002d, 0x13fd: 0x002f, 0x13fe: 0x0031, 0x13ff: 0x0033, + // Block 0x50, offset 0x1400 + 0x1400: 0x0239, 0x1401: 0x023c, 0x1402: 0x0248, 0x1403: 0x0251, 0x1405: 0x028a, + 0x1406: 0x025a, 0x1407: 0x024b, 0x1408: 0x0269, 0x1409: 0x0290, 0x140a: 0x027b, 0x140b: 0x027e, + 0x140c: 0x0281, 0x140d: 0x0284, 0x140e: 0x025d, 0x140f: 0x026f, 0x1410: 0x0275, 0x1411: 0x0263, + 0x1412: 0x0278, 0x1413: 0x0257, 0x1414: 0x0260, 0x1415: 0x0242, 0x1416: 0x0245, 0x1417: 0x024e, + 0x1418: 0x0254, 0x1419: 0x0266, 0x141a: 0x026c, 0x141b: 0x0272, 0x141c: 0x0293, 0x141d: 0x02e4, + 0x141e: 0x02cc, 0x141f: 0x0296, 0x1421: 0x023c, 0x1422: 0x0248, + 0x1424: 0x0287, 0x1427: 0x024b, 0x1429: 0x0290, + 0x142a: 0x027b, 0x142b: 0x027e, 0x142c: 0x0281, 0x142d: 0x0284, 0x142e: 0x025d, 0x142f: 0x026f, + 0x1430: 0x0275, 0x1431: 0x0263, 0x1432: 0x0278, 0x1434: 0x0260, 0x1435: 0x0242, + 0x1436: 0x0245, 0x1437: 0x024e, 0x1439: 0x0266, 0x143b: 0x0272, + // Block 0x51, offset 0x1440 + 0x1442: 0x0248, + 0x1447: 0x024b, 0x1449: 0x0290, 0x144b: 0x027e, + 0x144d: 0x0284, 0x144e: 0x025d, 0x144f: 0x026f, 0x1451: 0x0263, + 0x1452: 0x0278, 0x1454: 0x0260, 0x1457: 0x024e, + 0x1459: 0x0266, 0x145b: 0x0272, 0x145d: 0x02e4, + 0x145f: 0x0296, 0x1461: 0x023c, 0x1462: 0x0248, + 0x1464: 0x0287, 0x1467: 0x024b, 0x1468: 0x0269, 0x1469: 0x0290, + 0x146a: 0x027b, 0x146c: 0x0281, 0x146d: 0x0284, 0x146e: 0x025d, 0x146f: 0x026f, + 0x1470: 0x0275, 0x1471: 0x0263, 0x1472: 0x0278, 0x1474: 0x0260, 0x1475: 0x0242, + 0x1476: 0x0245, 0x1477: 0x024e, 0x1479: 0x0266, 0x147a: 0x026c, 0x147b: 0x0272, + 0x147c: 0x0293, 0x147e: 0x02cc, + // Block 0x52, offset 0x1480 + 0x1480: 0x0239, 0x1481: 0x023c, 0x1482: 0x0248, 0x1483: 0x0251, 0x1484: 0x0287, 0x1485: 0x028a, + 0x1486: 0x025a, 0x1487: 0x024b, 0x1488: 0x0269, 0x1489: 0x0290, 0x148b: 0x027e, + 0x148c: 0x0281, 0x148d: 0x0284, 0x148e: 0x025d, 0x148f: 0x026f, 0x1490: 0x0275, 0x1491: 0x0263, + 0x1492: 0x0278, 0x1493: 0x0257, 0x1494: 0x0260, 0x1495: 0x0242, 0x1496: 0x0245, 0x1497: 0x024e, + 0x1498: 0x0254, 0x1499: 0x0266, 0x149a: 0x026c, 0x149b: 0x0272, + 0x14a1: 0x023c, 0x14a2: 0x0248, 0x14a3: 0x0251, + 0x14a5: 0x028a, 0x14a6: 0x025a, 0x14a7: 0x024b, 0x14a8: 0x0269, 0x14a9: 0x0290, + 0x14ab: 0x027e, 0x14ac: 0x0281, 0x14ad: 0x0284, 0x14ae: 0x025d, 0x14af: 0x026f, + 0x14b0: 0x0275, 0x14b1: 0x0263, 0x14b2: 0x0278, 0x14b3: 0x0257, 0x14b4: 0x0260, 0x14b5: 0x0242, + 0x14b6: 0x0245, 0x14b7: 0x024e, 0x14b8: 0x0254, 0x14b9: 0x0266, 0x14ba: 0x026c, 0x14bb: 0x0272, + // Block 0x53, offset 0x14c0 + 0x14c0: 0x1879, 0x14c1: 0x1876, 0x14c2: 0x187c, 0x14c3: 0x18a0, 0x14c4: 0x18c4, 0x14c5: 0x18e8, + 0x14c6: 0x190c, 0x14c7: 0x1915, 0x14c8: 0x191b, 0x14c9: 0x1921, 0x14ca: 0x1927, + 0x14d0: 0x1a8f, 0x14d1: 0x1a93, + 0x14d2: 0x1a97, 0x14d3: 0x1a9b, 0x14d4: 0x1a9f, 0x14d5: 0x1aa3, 0x14d6: 0x1aa7, 0x14d7: 0x1aab, + 0x14d8: 0x1aaf, 0x14d9: 0x1ab3, 0x14da: 0x1ab7, 0x14db: 0x1abb, 0x14dc: 0x1abf, 0x14dd: 0x1ac3, + 0x14de: 0x1ac7, 0x14df: 0x1acb, 0x14e0: 0x1acf, 0x14e1: 0x1ad3, 0x14e2: 0x1ad7, 0x14e3: 0x1adb, + 0x14e4: 0x1adf, 0x14e5: 0x1ae3, 0x14e6: 0x1ae7, 0x14e7: 0x1aeb, 0x14e8: 0x1aef, 0x14e9: 0x1af3, + 0x14ea: 0x2721, 0x14eb: 0x0047, 0x14ec: 0x0065, 0x14ed: 0x193c, 0x14ee: 0x19b4, + 0x14f0: 0x0043, 0x14f1: 0x0045, 0x14f2: 0x0047, 0x14f3: 0x0049, 0x14f4: 0x004b, 0x14f5: 0x004d, + 0x14f6: 0x004f, 0x14f7: 0x0051, 0x14f8: 0x0053, 0x14f9: 0x0055, 0x14fa: 0x0057, 0x14fb: 0x0059, + 0x14fc: 0x005b, 0x14fd: 0x005d, 0x14fe: 0x005f, 0x14ff: 0x0061, + // Block 0x54, offset 0x1500 + 0x1500: 0x26b0, 0x1501: 0x26c5, 0x1502: 0x0503, + 0x1510: 0x0c0f, 0x1511: 0x0a47, + 0x1512: 0x08d3, 0x1513: 0x45c7, 0x1514: 0x071b, 0x1515: 0x09ef, 0x1516: 0x132f, 0x1517: 0x09ff, + 0x1518: 0x0727, 0x1519: 0x0cd7, 0x151a: 0x0eaf, 0x151b: 0x0caf, 0x151c: 0x0827, 0x151d: 0x0b6b, + 0x151e: 0x07bf, 0x151f: 0x0cb7, 0x1520: 0x0813, 0x1521: 0x1117, 0x1522: 0x0f83, 0x1523: 0x138b, + 0x1524: 0x09d3, 0x1525: 0x090b, 0x1526: 0x0e63, 0x1527: 0x0c1b, 0x1528: 0x0c47, 0x1529: 0x06bf, + 0x152a: 0x06cb, 0x152b: 0x140b, 0x152c: 0x0adb, 0x152d: 0x06e7, 0x152e: 0x08ef, 0x152f: 0x0c3b, + 0x1530: 0x13b3, 0x1531: 0x0c13, 0x1532: 0x106f, 0x1533: 0x10ab, 0x1534: 0x08f7, 0x1535: 0x0e43, + 0x1536: 0x0d0b, 0x1537: 0x0d07, 0x1538: 0x0f97, 0x1539: 0x082b, 0x153a: 0x0957, 0x153b: 0x1443, + // Block 0x55, offset 0x1540 + 0x1540: 0x06fb, 0x1541: 0x06f3, 0x1542: 0x0703, 0x1543: 0x1647, 0x1544: 0x0747, 0x1545: 0x0757, + 0x1546: 0x075b, 0x1547: 0x0763, 0x1548: 0x076b, 0x1549: 0x076f, 0x154a: 0x077b, 0x154b: 0x0773, + 0x154c: 0x05b3, 0x154d: 0x165b, 0x154e: 0x078f, 0x154f: 0x0793, 0x1550: 0x0797, 0x1551: 0x07b3, + 0x1552: 0x164c, 0x1553: 0x05b7, 0x1554: 0x079f, 0x1555: 0x07bf, 0x1556: 0x1656, 0x1557: 0x07cf, + 0x1558: 0x07d7, 0x1559: 0x0737, 0x155a: 0x07df, 0x155b: 0x07e3, 0x155c: 0x1831, 0x155d: 0x07ff, + 0x155e: 0x0807, 0x155f: 0x05bf, 0x1560: 0x081f, 0x1561: 0x0823, 0x1562: 0x082b, 0x1563: 0x082f, + 0x1564: 0x05c3, 0x1565: 0x0847, 0x1566: 0x084b, 0x1567: 0x0857, 0x1568: 0x0863, 0x1569: 0x0867, + 0x156a: 0x086b, 0x156b: 0x0873, 0x156c: 0x0893, 0x156d: 0x0897, 0x156e: 0x089f, 0x156f: 0x08af, + 0x1570: 0x08b7, 0x1571: 0x08bb, 0x1572: 0x08bb, 0x1573: 0x08bb, 0x1574: 0x166a, 0x1575: 0x0e93, + 0x1576: 0x08cf, 0x1577: 0x08d7, 0x1578: 0x166f, 0x1579: 0x08e3, 0x157a: 0x08eb, 0x157b: 0x08f3, + 0x157c: 0x091b, 0x157d: 0x0907, 0x157e: 0x0913, 0x157f: 0x0917, + // Block 0x56, offset 0x1580 + 0x1580: 0x091f, 0x1581: 0x0927, 0x1582: 0x092b, 0x1583: 0x0933, 0x1584: 0x093b, 0x1585: 0x093f, + 0x1586: 0x093f, 0x1587: 0x0947, 0x1588: 0x094f, 0x1589: 0x0953, 0x158a: 0x095f, 0x158b: 0x0983, + 0x158c: 0x0967, 0x158d: 0x0987, 0x158e: 0x096b, 0x158f: 0x0973, 0x1590: 0x080b, 0x1591: 0x09cf, + 0x1592: 0x0997, 0x1593: 0x099b, 0x1594: 0x099f, 0x1595: 0x0993, 0x1596: 0x09a7, 0x1597: 0x09a3, + 0x1598: 0x09bb, 0x1599: 0x1674, 0x159a: 0x09d7, 0x159b: 0x09db, 0x159c: 0x09e3, 0x159d: 0x09ef, + 0x159e: 0x09f7, 0x159f: 0x0a13, 0x15a0: 0x1679, 0x15a1: 0x167e, 0x15a2: 0x0a1f, 0x15a3: 0x0a23, + 0x15a4: 0x0a27, 0x15a5: 0x0a1b, 0x15a6: 0x0a2f, 0x15a7: 0x05c7, 0x15a8: 0x05cb, 0x15a9: 0x0a37, + 0x15aa: 0x0a3f, 0x15ab: 0x0a3f, 0x15ac: 0x1683, 0x15ad: 0x0a5b, 0x15ae: 0x0a5f, 0x15af: 0x0a63, + 0x15b0: 0x0a6b, 0x15b1: 0x1688, 0x15b2: 0x0a73, 0x15b3: 0x0a77, 0x15b4: 0x0b4f, 0x15b5: 0x0a7f, + 0x15b6: 0x05cf, 0x15b7: 0x0a8b, 0x15b8: 0x0a9b, 0x15b9: 0x0aa7, 0x15ba: 0x0aa3, 0x15bb: 0x1692, + 0x15bc: 0x0aaf, 0x15bd: 0x1697, 0x15be: 0x0abb, 0x15bf: 0x0ab7, + // Block 0x57, offset 0x15c0 + 0x15c0: 0x0abf, 0x15c1: 0x0acf, 0x15c2: 0x0ad3, 0x15c3: 0x05d3, 0x15c4: 0x0ae3, 0x15c5: 0x0aeb, + 0x15c6: 0x0aef, 0x15c7: 0x0af3, 0x15c8: 0x05d7, 0x15c9: 0x169c, 0x15ca: 0x05db, 0x15cb: 0x0b0f, + 0x15cc: 0x0b13, 0x15cd: 0x0b17, 0x15ce: 0x0b1f, 0x15cf: 0x1863, 0x15d0: 0x0b37, 0x15d1: 0x16a6, + 0x15d2: 0x16a6, 0x15d3: 0x11d7, 0x15d4: 0x0b47, 0x15d5: 0x0b47, 0x15d6: 0x05df, 0x15d7: 0x16c9, + 0x15d8: 0x179b, 0x15d9: 0x0b57, 0x15da: 0x0b5f, 0x15db: 0x05e3, 0x15dc: 0x0b73, 0x15dd: 0x0b83, + 0x15de: 0x0b87, 0x15df: 0x0b8f, 0x15e0: 0x0b9f, 0x15e1: 0x05eb, 0x15e2: 0x05e7, 0x15e3: 0x0ba3, + 0x15e4: 0x16ab, 0x15e5: 0x0ba7, 0x15e6: 0x0bbb, 0x15e7: 0x0bbf, 0x15e8: 0x0bc3, 0x15e9: 0x0bbf, + 0x15ea: 0x0bcf, 0x15eb: 0x0bd3, 0x15ec: 0x0be3, 0x15ed: 0x0bdb, 0x15ee: 0x0bdf, 0x15ef: 0x0be7, + 0x15f0: 0x0beb, 0x15f1: 0x0bef, 0x15f2: 0x0bfb, 0x15f3: 0x0bff, 0x15f4: 0x0c17, 0x15f5: 0x0c1f, + 0x15f6: 0x0c2f, 0x15f7: 0x0c43, 0x15f8: 0x16ba, 0x15f9: 0x0c3f, 0x15fa: 0x0c33, 0x15fb: 0x0c4b, + 0x15fc: 0x0c53, 0x15fd: 0x0c67, 0x15fe: 0x16bf, 0x15ff: 0x0c6f, + // Block 0x58, offset 0x1600 + 0x1600: 0x0c63, 0x1601: 0x0c5b, 0x1602: 0x05ef, 0x1603: 0x0c77, 0x1604: 0x0c7f, 0x1605: 0x0c87, + 0x1606: 0x0c7b, 0x1607: 0x05f3, 0x1608: 0x0c97, 0x1609: 0x0c9f, 0x160a: 0x16c4, 0x160b: 0x0ccb, + 0x160c: 0x0cff, 0x160d: 0x0cdb, 0x160e: 0x05ff, 0x160f: 0x0ce7, 0x1610: 0x05fb, 0x1611: 0x05f7, + 0x1612: 0x07c3, 0x1613: 0x07c7, 0x1614: 0x0d03, 0x1615: 0x0ceb, 0x1616: 0x11ab, 0x1617: 0x0663, + 0x1618: 0x0d0f, 0x1619: 0x0d13, 0x161a: 0x0d17, 0x161b: 0x0d2b, 0x161c: 0x0d23, 0x161d: 0x16dd, + 0x161e: 0x0603, 0x161f: 0x0d3f, 0x1620: 0x0d33, 0x1621: 0x0d4f, 0x1622: 0x0d57, 0x1623: 0x16e7, + 0x1624: 0x0d5b, 0x1625: 0x0d47, 0x1626: 0x0d63, 0x1627: 0x0607, 0x1628: 0x0d67, 0x1629: 0x0d6b, + 0x162a: 0x0d6f, 0x162b: 0x0d7b, 0x162c: 0x16ec, 0x162d: 0x0d83, 0x162e: 0x060b, 0x162f: 0x0d8f, + 0x1630: 0x16f1, 0x1631: 0x0d93, 0x1632: 0x060f, 0x1633: 0x0d9f, 0x1634: 0x0dab, 0x1635: 0x0db7, + 0x1636: 0x0dbb, 0x1637: 0x16f6, 0x1638: 0x168d, 0x1639: 0x16fb, 0x163a: 0x0ddb, 0x163b: 0x1700, + 0x163c: 0x0de7, 0x163d: 0x0def, 0x163e: 0x0ddf, 0x163f: 0x0dfb, + // Block 0x59, offset 0x1640 + 0x1640: 0x0e0b, 0x1641: 0x0e1b, 0x1642: 0x0e0f, 0x1643: 0x0e13, 0x1644: 0x0e1f, 0x1645: 0x0e23, + 0x1646: 0x1705, 0x1647: 0x0e07, 0x1648: 0x0e3b, 0x1649: 0x0e3f, 0x164a: 0x0613, 0x164b: 0x0e53, + 0x164c: 0x0e4f, 0x164d: 0x170a, 0x164e: 0x0e33, 0x164f: 0x0e6f, 0x1650: 0x170f, 0x1651: 0x1714, + 0x1652: 0x0e73, 0x1653: 0x0e87, 0x1654: 0x0e83, 0x1655: 0x0e7f, 0x1656: 0x0617, 0x1657: 0x0e8b, + 0x1658: 0x0e9b, 0x1659: 0x0e97, 0x165a: 0x0ea3, 0x165b: 0x1651, 0x165c: 0x0eb3, 0x165d: 0x1719, + 0x165e: 0x0ebf, 0x165f: 0x1723, 0x1660: 0x0ed3, 0x1661: 0x0edf, 0x1662: 0x0ef3, 0x1663: 0x1728, + 0x1664: 0x0f07, 0x1665: 0x0f0b, 0x1666: 0x172d, 0x1667: 0x1732, 0x1668: 0x0f27, 0x1669: 0x0f37, + 0x166a: 0x061b, 0x166b: 0x0f3b, 0x166c: 0x061f, 0x166d: 0x061f, 0x166e: 0x0f53, 0x166f: 0x0f57, + 0x1670: 0x0f5f, 0x1671: 0x0f63, 0x1672: 0x0f6f, 0x1673: 0x0623, 0x1674: 0x0f87, 0x1675: 0x1737, + 0x1676: 0x0fa3, 0x1677: 0x173c, 0x1678: 0x0faf, 0x1679: 0x16a1, 0x167a: 0x0fbf, 0x167b: 0x1741, + 0x167c: 0x1746, 0x167d: 0x174b, 0x167e: 0x0627, 0x167f: 0x062b, + // Block 0x5a, offset 0x1680 + 0x1680: 0x0ff7, 0x1681: 0x1755, 0x1682: 0x1750, 0x1683: 0x175a, 0x1684: 0x175f, 0x1685: 0x0fff, + 0x1686: 0x1003, 0x1687: 0x1003, 0x1688: 0x100b, 0x1689: 0x0633, 0x168a: 0x100f, 0x168b: 0x0637, + 0x168c: 0x063b, 0x168d: 0x1769, 0x168e: 0x1023, 0x168f: 0x102b, 0x1690: 0x1037, 0x1691: 0x063f, + 0x1692: 0x176e, 0x1693: 0x105b, 0x1694: 0x1773, 0x1695: 0x1778, 0x1696: 0x107b, 0x1697: 0x1093, + 0x1698: 0x0643, 0x1699: 0x109b, 0x169a: 0x109f, 0x169b: 0x10a3, 0x169c: 0x177d, 0x169d: 0x1782, + 0x169e: 0x1782, 0x169f: 0x10bb, 0x16a0: 0x0647, 0x16a1: 0x1787, 0x16a2: 0x10cf, 0x16a3: 0x10d3, + 0x16a4: 0x064b, 0x16a5: 0x178c, 0x16a6: 0x10ef, 0x16a7: 0x064f, 0x16a8: 0x10ff, 0x16a9: 0x10f7, + 0x16aa: 0x1107, 0x16ab: 0x1796, 0x16ac: 0x111f, 0x16ad: 0x0653, 0x16ae: 0x112b, 0x16af: 0x1133, + 0x16b0: 0x1143, 0x16b1: 0x0657, 0x16b2: 0x17a0, 0x16b3: 0x17a5, 0x16b4: 0x065b, 0x16b5: 0x17aa, + 0x16b6: 0x115b, 0x16b7: 0x17af, 0x16b8: 0x1167, 0x16b9: 0x1173, 0x16ba: 0x117b, 0x16bb: 0x17b4, + 0x16bc: 0x17b9, 0x16bd: 0x118f, 0x16be: 0x17be, 0x16bf: 0x1197, + // Block 0x5b, offset 0x16c0 + 0x16c0: 0x16ce, 0x16c1: 0x065f, 0x16c2: 0x11af, 0x16c3: 0x11b3, 0x16c4: 0x0667, 0x16c5: 0x11b7, + 0x16c6: 0x0a33, 0x16c7: 0x17c3, 0x16c8: 0x17c8, 0x16c9: 0x16d3, 0x16ca: 0x16d8, 0x16cb: 0x11d7, + 0x16cc: 0x11db, 0x16cd: 0x13f3, 0x16ce: 0x066b, 0x16cf: 0x1207, 0x16d0: 0x1203, 0x16d1: 0x120b, + 0x16d2: 0x083f, 0x16d3: 0x120f, 0x16d4: 0x1213, 0x16d5: 0x1217, 0x16d6: 0x121f, 0x16d7: 0x17cd, + 0x16d8: 0x121b, 0x16d9: 0x1223, 0x16da: 0x1237, 0x16db: 0x123b, 0x16dc: 0x1227, 0x16dd: 0x123f, + 0x16de: 0x1253, 0x16df: 0x1267, 0x16e0: 0x1233, 0x16e1: 0x1247, 0x16e2: 0x124b, 0x16e3: 0x124f, + 0x16e4: 0x17d2, 0x16e5: 0x17dc, 0x16e6: 0x17d7, 0x16e7: 0x066f, 0x16e8: 0x126f, 0x16e9: 0x1273, + 0x16ea: 0x127b, 0x16eb: 0x17f0, 0x16ec: 0x127f, 0x16ed: 0x17e1, 0x16ee: 0x0673, 0x16ef: 0x0677, + 0x16f0: 0x17e6, 0x16f1: 0x17eb, 0x16f2: 0x067b, 0x16f3: 0x129f, 0x16f4: 0x12a3, 0x16f5: 0x12a7, + 0x16f6: 0x12ab, 0x16f7: 0x12b7, 0x16f8: 0x12b3, 0x16f9: 0x12bf, 0x16fa: 0x12bb, 0x16fb: 0x12cb, + 0x16fc: 0x12c3, 0x16fd: 0x12c7, 0x16fe: 0x12cf, 0x16ff: 0x067f, + // Block 0x5c, offset 0x1700 + 0x1700: 0x12d7, 0x1701: 0x12db, 0x1702: 0x0683, 0x1703: 0x12eb, 0x1704: 0x12ef, 0x1705: 0x17f5, + 0x1706: 0x12fb, 0x1707: 0x12ff, 0x1708: 0x0687, 0x1709: 0x130b, 0x170a: 0x05bb, 0x170b: 0x17fa, + 0x170c: 0x17ff, 0x170d: 0x068b, 0x170e: 0x068f, 0x170f: 0x1337, 0x1710: 0x134f, 0x1711: 0x136b, + 0x1712: 0x137b, 0x1713: 0x1804, 0x1714: 0x138f, 0x1715: 0x1393, 0x1716: 0x13ab, 0x1717: 0x13b7, + 0x1718: 0x180e, 0x1719: 0x1660, 0x171a: 0x13c3, 0x171b: 0x13bf, 0x171c: 0x13cb, 0x171d: 0x1665, + 0x171e: 0x13d7, 0x171f: 0x13e3, 0x1720: 0x1813, 0x1721: 0x1818, 0x1722: 0x1423, 0x1723: 0x142f, + 0x1724: 0x1437, 0x1725: 0x181d, 0x1726: 0x143b, 0x1727: 0x1467, 0x1728: 0x1473, 0x1729: 0x1477, + 0x172a: 0x146f, 0x172b: 0x1483, 0x172c: 0x1487, 0x172d: 0x1822, 0x172e: 0x1493, 0x172f: 0x0693, + 0x1730: 0x149b, 0x1731: 0x1827, 0x1732: 0x0697, 0x1733: 0x14d3, 0x1734: 0x0ac3, 0x1735: 0x14eb, + 0x1736: 0x182c, 0x1737: 0x1836, 0x1738: 0x069b, 0x1739: 0x069f, 0x173a: 0x1513, 0x173b: 0x183b, + 0x173c: 0x06a3, 0x173d: 0x1840, 0x173e: 0x152b, 0x173f: 0x152b, + // Block 0x5d, offset 0x1740 + 0x1740: 0x1533, 0x1741: 0x1845, 0x1742: 0x154b, 0x1743: 0x06a7, 0x1744: 0x155b, 0x1745: 0x1567, + 0x1746: 0x156f, 0x1747: 0x1577, 0x1748: 0x06ab, 0x1749: 0x184a, 0x174a: 0x158b, 0x174b: 0x15a7, + 0x174c: 0x15b3, 0x174d: 0x06af, 0x174e: 0x06b3, 0x174f: 0x15b7, 0x1750: 0x184f, 0x1751: 0x06b7, + 0x1752: 0x1854, 0x1753: 0x1859, 0x1754: 0x185e, 0x1755: 0x15db, 0x1756: 0x06bb, 0x1757: 0x15ef, + 0x1758: 0x15f7, 0x1759: 0x15fb, 0x175a: 0x1603, 0x175b: 0x160b, 0x175c: 0x1613, 0x175d: 0x1868, +} + +// nfkcIndex: 22 blocks, 1408 entries, 2816 bytes +// Block 0 is the zero block. +var nfkcIndex = [1408]uint16{ + // Block 0x0, offset 0x0 + // Block 0x1, offset 0x40 + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc2: 0x5c, 0xc3: 0x01, 0xc4: 0x02, 0xc5: 0x03, 0xc6: 0x5d, 0xc7: 0x04, + 0xc8: 0x05, 0xca: 0x5e, 0xcb: 0x5f, 0xcc: 0x06, 0xcd: 0x07, 0xce: 0x08, 0xcf: 0x09, + 0xd0: 0x0a, 0xd1: 0x60, 0xd2: 0x61, 0xd3: 0x0b, 0xd6: 0x0c, 0xd7: 0x62, + 0xd8: 0x63, 0xd9: 0x0d, 0xdb: 0x64, 0xdc: 0x65, 0xdd: 0x66, 0xdf: 0x67, + 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05, + 0xea: 0x06, 0xeb: 0x07, 0xec: 0x08, 0xed: 0x09, 0xef: 0x0a, + 0xf0: 0x13, + // Block 0x4, offset 0x100 + 0x120: 0x68, 0x121: 0x69, 0x123: 0x0e, 0x124: 0x6a, 0x125: 0x6b, 0x126: 0x6c, 0x127: 0x6d, + 0x128: 0x6e, 0x129: 0x6f, 0x12a: 0x70, 0x12b: 0x71, 0x12c: 0x6c, 0x12d: 0x72, 0x12e: 0x73, 0x12f: 0x74, + 0x131: 0x75, 0x132: 0x76, 0x133: 0x77, 0x134: 0x78, 0x135: 0x79, 0x137: 0x7a, + 0x138: 0x7b, 0x139: 0x7c, 0x13a: 0x7d, 0x13b: 0x7e, 0x13c: 0x7f, 0x13d: 0x80, 0x13e: 0x81, 0x13f: 0x82, + // Block 0x5, offset 0x140 + 0x140: 0x83, 0x142: 0x84, 0x143: 0x85, 0x144: 0x86, 0x145: 0x87, 0x146: 0x88, 0x147: 0x89, + 0x14d: 0x8a, + 0x15c: 0x8b, 0x15f: 0x8c, + 0x162: 0x8d, 0x164: 0x8e, + 0x168: 0x8f, 0x169: 0x90, 0x16a: 0x91, 0x16c: 0x0f, 0x16d: 0x92, 0x16e: 0x93, 0x16f: 0x94, + 0x170: 0x95, 0x173: 0x96, 0x174: 0x97, 0x175: 0x10, 0x176: 0x11, 0x177: 0x12, + 0x178: 0x13, 0x179: 0x14, 0x17a: 0x15, 0x17b: 0x16, 0x17c: 0x17, 0x17d: 0x18, 0x17e: 0x19, 0x17f: 0x1a, + // Block 0x6, offset 0x180 + 0x180: 0x98, 0x181: 0x99, 0x182: 0x9a, 0x183: 0x9b, 0x184: 0x1b, 0x185: 0x1c, 0x186: 0x9c, 0x187: 0x9d, + 0x188: 0x9e, 0x189: 0x1d, 0x18a: 0x1e, 0x18b: 0x9f, 0x18c: 0xa0, + 0x191: 0x1f, 0x192: 0x20, 0x193: 0xa1, + 0x1a8: 0xa2, 0x1a9: 0xa3, 0x1ab: 0xa4, + 0x1b1: 0xa5, 0x1b3: 0xa6, 0x1b5: 0xa7, 0x1b7: 0xa8, + 0x1ba: 0xa9, 0x1bb: 0xaa, 0x1bc: 0x21, 0x1bd: 0x22, 0x1be: 0x23, 0x1bf: 0xab, + // Block 0x7, offset 0x1c0 + 0x1c0: 0xac, 0x1c1: 0x24, 0x1c2: 0x25, 0x1c3: 0x26, 0x1c4: 0xad, 0x1c5: 0x27, 0x1c6: 0x28, + 0x1c8: 0x29, 0x1c9: 0x2a, 0x1ca: 0x2b, 0x1cb: 0x2c, 0x1cc: 0x2d, 0x1cd: 0x2e, 0x1ce: 0x2f, 0x1cf: 0x30, + // Block 0x8, offset 0x200 + 0x219: 0xae, 0x21a: 0xaf, 0x21b: 0xb0, 0x21d: 0xb1, 0x21f: 0xb2, + 0x220: 0xb3, 0x223: 0xb4, 0x224: 0xb5, 0x225: 0xb6, 0x226: 0xb7, 0x227: 0xb8, + 0x22a: 0xb9, 0x22b: 0xba, 0x22d: 0xbb, 0x22f: 0xbc, + 0x230: 0xbd, 0x231: 0xbe, 0x232: 0xbf, 0x233: 0xc0, 0x234: 0xc1, 0x235: 0xc2, 0x236: 0xc3, 0x237: 0xbd, + 0x238: 0xbe, 0x239: 0xbf, 0x23a: 0xc0, 0x23b: 0xc1, 0x23c: 0xc2, 0x23d: 0xc3, 0x23e: 0xbd, 0x23f: 0xbe, + // Block 0x9, offset 0x240 + 0x240: 0xbf, 0x241: 0xc0, 0x242: 0xc1, 0x243: 0xc2, 0x244: 0xc3, 0x245: 0xbd, 0x246: 0xbe, 0x247: 0xbf, + 0x248: 0xc0, 0x249: 0xc1, 0x24a: 0xc2, 0x24b: 0xc3, 0x24c: 0xbd, 0x24d: 0xbe, 0x24e: 0xbf, 0x24f: 0xc0, + 0x250: 0xc1, 0x251: 0xc2, 0x252: 0xc3, 0x253: 0xbd, 0x254: 0xbe, 0x255: 0xbf, 0x256: 0xc0, 0x257: 0xc1, + 0x258: 0xc2, 0x259: 0xc3, 0x25a: 0xbd, 0x25b: 0xbe, 0x25c: 0xbf, 0x25d: 0xc0, 0x25e: 0xc1, 0x25f: 0xc2, + 0x260: 0xc3, 0x261: 0xbd, 0x262: 0xbe, 0x263: 0xbf, 0x264: 0xc0, 0x265: 0xc1, 0x266: 0xc2, 0x267: 0xc3, + 0x268: 0xbd, 0x269: 0xbe, 0x26a: 0xbf, 0x26b: 0xc0, 0x26c: 0xc1, 0x26d: 0xc2, 0x26e: 0xc3, 0x26f: 0xbd, + 0x270: 0xbe, 0x271: 0xbf, 0x272: 0xc0, 0x273: 0xc1, 0x274: 0xc2, 0x275: 0xc3, 0x276: 0xbd, 0x277: 0xbe, + 0x278: 0xbf, 0x279: 0xc0, 0x27a: 0xc1, 0x27b: 0xc2, 0x27c: 0xc3, 0x27d: 0xbd, 0x27e: 0xbe, 0x27f: 0xbf, + // Block 0xa, offset 0x280 + 0x280: 0xc0, 0x281: 0xc1, 0x282: 0xc2, 0x283: 0xc3, 0x284: 0xbd, 0x285: 0xbe, 0x286: 0xbf, 0x287: 0xc0, + 0x288: 0xc1, 0x289: 0xc2, 0x28a: 0xc3, 0x28b: 0xbd, 0x28c: 0xbe, 0x28d: 0xbf, 0x28e: 0xc0, 0x28f: 0xc1, + 0x290: 0xc2, 0x291: 0xc3, 0x292: 0xbd, 0x293: 0xbe, 0x294: 0xbf, 0x295: 0xc0, 0x296: 0xc1, 0x297: 0xc2, + 0x298: 0xc3, 0x299: 0xbd, 0x29a: 0xbe, 0x29b: 0xbf, 0x29c: 0xc0, 0x29d: 0xc1, 0x29e: 0xc2, 0x29f: 0xc3, + 0x2a0: 0xbd, 0x2a1: 0xbe, 0x2a2: 0xbf, 0x2a3: 0xc0, 0x2a4: 0xc1, 0x2a5: 0xc2, 0x2a6: 0xc3, 0x2a7: 0xbd, + 0x2a8: 0xbe, 0x2a9: 0xbf, 0x2aa: 0xc0, 0x2ab: 0xc1, 0x2ac: 0xc2, 0x2ad: 0xc3, 0x2ae: 0xbd, 0x2af: 0xbe, + 0x2b0: 0xbf, 0x2b1: 0xc0, 0x2b2: 0xc1, 0x2b3: 0xc2, 0x2b4: 0xc3, 0x2b5: 0xbd, 0x2b6: 0xbe, 0x2b7: 0xbf, + 0x2b8: 0xc0, 0x2b9: 0xc1, 0x2ba: 0xc2, 0x2bb: 0xc3, 0x2bc: 0xbd, 0x2bd: 0xbe, 0x2be: 0xbf, 0x2bf: 0xc0, + // Block 0xb, offset 0x2c0 + 0x2c0: 0xc1, 0x2c1: 0xc2, 0x2c2: 0xc3, 0x2c3: 0xbd, 0x2c4: 0xbe, 0x2c5: 0xbf, 0x2c6: 0xc0, 0x2c7: 0xc1, + 0x2c8: 0xc2, 0x2c9: 0xc3, 0x2ca: 0xbd, 0x2cb: 0xbe, 0x2cc: 0xbf, 0x2cd: 0xc0, 0x2ce: 0xc1, 0x2cf: 0xc2, + 0x2d0: 0xc3, 0x2d1: 0xbd, 0x2d2: 0xbe, 0x2d3: 0xbf, 0x2d4: 0xc0, 0x2d5: 0xc1, 0x2d6: 0xc2, 0x2d7: 0xc3, + 0x2d8: 0xbd, 0x2d9: 0xbe, 0x2da: 0xbf, 0x2db: 0xc0, 0x2dc: 0xc1, 0x2dd: 0xc2, 0x2de: 0xc4, + // Block 0xc, offset 0x300 + 0x324: 0x31, 0x325: 0x32, 0x326: 0x33, 0x327: 0x34, + 0x328: 0x35, 0x329: 0x36, 0x32a: 0x37, 0x32b: 0x38, 0x32c: 0x39, 0x32d: 0x3a, 0x32e: 0x3b, 0x32f: 0x3c, + 0x330: 0x3d, 0x331: 0x3e, 0x332: 0x3f, 0x333: 0x40, 0x334: 0x41, 0x335: 0x42, 0x336: 0x43, 0x337: 0x44, + 0x338: 0x45, 0x339: 0x46, 0x33a: 0x47, 0x33b: 0x48, 0x33c: 0xc5, 0x33d: 0x49, 0x33e: 0x4a, 0x33f: 0x4b, + // Block 0xd, offset 0x340 + 0x347: 0xc6, + 0x34b: 0xc7, 0x34d: 0xc8, + 0x368: 0xc9, 0x36b: 0xca, + 0x374: 0xcb, + 0x37d: 0xcc, + // Block 0xe, offset 0x380 + 0x381: 0xcd, 0x382: 0xce, 0x384: 0xcf, 0x385: 0xb7, 0x387: 0xd0, + 0x388: 0xd1, 0x38b: 0xd2, 0x38c: 0xd3, 0x38d: 0xd4, + 0x391: 0xd5, 0x392: 0xd6, 0x393: 0xd7, 0x396: 0xd8, 0x397: 0xd9, + 0x398: 0xda, 0x39a: 0xdb, 0x39c: 0xdc, + 0x3a0: 0xdd, 0x3a7: 0xde, + 0x3a8: 0xdf, 0x3a9: 0xe0, 0x3aa: 0xe1, + 0x3b0: 0xda, 0x3b5: 0xe2, 0x3b6: 0xe3, + // Block 0xf, offset 0x3c0 + 0x3eb: 0xe4, 0x3ec: 0xe5, + // Block 0x10, offset 0x400 + 0x432: 0xe6, + // Block 0x11, offset 0x440 + 0x445: 0xe7, 0x446: 0xe8, 0x447: 0xe9, + 0x449: 0xea, + 0x450: 0xeb, 0x451: 0xec, 0x452: 0xed, 0x453: 0xee, 0x454: 0xef, 0x455: 0xf0, 0x456: 0xf1, 0x457: 0xf2, + 0x458: 0xf3, 0x459: 0xf4, 0x45a: 0x4c, 0x45b: 0xf5, 0x45c: 0xf6, 0x45d: 0xf7, 0x45e: 0xf8, 0x45f: 0x4d, + // Block 0x12, offset 0x480 + 0x480: 0xf9, 0x484: 0xe5, + 0x48b: 0xfa, + 0x4a3: 0xfb, 0x4a5: 0xfc, + 0x4b8: 0x4e, 0x4b9: 0x4f, 0x4ba: 0x50, + // Block 0x13, offset 0x4c0 + 0x4c4: 0x51, 0x4c5: 0xfd, 0x4c6: 0xfe, + 0x4c8: 0x52, 0x4c9: 0xff, + // Block 0x14, offset 0x500 + 0x520: 0x53, 0x521: 0x54, 0x522: 0x55, 0x523: 0x56, 0x524: 0x57, 0x525: 0x58, 0x526: 0x59, 0x527: 0x5a, + 0x528: 0x5b, + // Block 0x15, offset 0x540 + 0x550: 0x0b, 0x551: 0x0c, 0x556: 0x0d, + 0x55b: 0x0e, 0x55d: 0x0f, 0x55e: 0x10, 0x55f: 0x11, + 0x56f: 0x12, +} + +// nfkcSparseOffset: 164 entries, 328 bytes +var nfkcSparseOffset = []uint16{0x0, 0xe, 0x12, 0x1b, 0x25, 0x35, 0x37, 0x3c, 0x47, 0x56, 0x63, 0x6b, 0x70, 0x75, 0x77, 0x7f, 0x86, 0x89, 0x91, 0x95, 0x99, 0x9b, 0x9d, 0xa6, 0xaa, 0xb1, 0xb6, 0xb9, 0xc3, 0xc6, 0xcd, 0xd5, 0xd9, 0xdb, 0xdf, 0xe3, 0xe9, 0xfa, 0x106, 0x108, 0x10e, 0x110, 0x112, 0x114, 0x116, 0x118, 0x11a, 0x11c, 0x11f, 0x122, 0x124, 0x127, 0x12a, 0x12e, 0x133, 0x13c, 0x13e, 0x141, 0x143, 0x14e, 0x159, 0x167, 0x175, 0x185, 0x193, 0x19a, 0x1a0, 0x1af, 0x1b3, 0x1b5, 0x1b9, 0x1bb, 0x1be, 0x1c0, 0x1c3, 0x1c5, 0x1c8, 0x1ca, 0x1cc, 0x1ce, 0x1da, 0x1e4, 0x1ee, 0x1f1, 0x1f5, 0x1f7, 0x1f9, 0x1fb, 0x1fd, 0x200, 0x202, 0x204, 0x206, 0x208, 0x20e, 0x211, 0x215, 0x217, 0x21e, 0x224, 0x22a, 0x232, 0x238, 0x23e, 0x244, 0x248, 0x24a, 0x24c, 0x24e, 0x250, 0x256, 0x259, 0x25b, 0x261, 0x264, 0x26c, 0x273, 0x276, 0x279, 0x27b, 0x27e, 0x286, 0x28a, 0x291, 0x294, 0x29a, 0x29c, 0x29e, 0x2a1, 0x2a3, 0x2a6, 0x2a8, 0x2aa, 0x2ac, 0x2ae, 0x2b1, 0x2b3, 0x2b5, 0x2b7, 0x2b9, 0x2c6, 0x2d0, 0x2d2, 0x2d4, 0x2d8, 0x2dd, 0x2e9, 0x2ee, 0x2f7, 0x2fd, 0x302, 0x306, 0x30b, 0x30f, 0x31f, 0x32d, 0x33b, 0x349, 0x34f, 0x351, 0x353, 0x356, 0x361, 0x363} + +// nfkcSparseValues: 877 entries, 3508 bytes +var nfkcSparseValues = [877]valueRange{ + // Block 0x0, offset 0x0 + {value: 0x0002, lo: 0x0d}, + {value: 0x0001, lo: 0xa0, hi: 0xa0}, + {value: 0x427b, lo: 0xa8, hi: 0xa8}, + {value: 0x0083, lo: 0xaa, hi: 0xaa}, + {value: 0x4267, lo: 0xaf, hi: 0xaf}, + {value: 0x0025, lo: 0xb2, hi: 0xb3}, + {value: 0x425d, lo: 0xb4, hi: 0xb4}, + {value: 0x01dc, lo: 0xb5, hi: 0xb5}, + {value: 0x4294, lo: 0xb8, hi: 0xb8}, + {value: 0x0023, lo: 0xb9, hi: 0xb9}, + {value: 0x009f, lo: 0xba, hi: 0xba}, + {value: 0x221f, lo: 0xbc, hi: 0xbc}, + {value: 0x2213, lo: 0xbd, hi: 0xbd}, + {value: 0x22b5, lo: 0xbe, hi: 0xbe}, + // Block 0x1, offset 0xe + {value: 0x0091, lo: 0x03}, + {value: 0x46e5, lo: 0xa0, hi: 0xa1}, + {value: 0x4717, lo: 0xaf, hi: 0xb0}, + {value: 0xa000, lo: 0xb7, hi: 0xb7}, + // Block 0x2, offset 0x12 + {value: 0x0003, lo: 0x08}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x0091, lo: 0xb0, hi: 0xb0}, + {value: 0x0119, lo: 0xb1, hi: 0xb1}, + {value: 0x0095, lo: 0xb2, hi: 0xb2}, + {value: 0x00a5, lo: 0xb3, hi: 0xb3}, + {value: 0x0143, lo: 0xb4, hi: 0xb6}, + {value: 0x00af, lo: 0xb7, hi: 0xb7}, + {value: 0x00b3, lo: 0xb8, hi: 0xb8}, + // Block 0x3, offset 0x1b + {value: 0x000a, lo: 0x09}, + {value: 0x4271, lo: 0x98, hi: 0x98}, + {value: 0x4276, lo: 0x99, hi: 0x9a}, + {value: 0x4299, lo: 0x9b, hi: 0x9b}, + {value: 0x4262, lo: 0x9c, hi: 0x9c}, + {value: 0x4285, lo: 0x9d, hi: 0x9d}, + {value: 0x0113, lo: 0xa0, hi: 0xa0}, + {value: 0x0099, lo: 0xa1, hi: 0xa1}, + {value: 0x00a7, lo: 0xa2, hi: 0xa3}, + {value: 0x0167, lo: 0xa4, hi: 0xa4}, + // Block 0x4, offset 0x25 + {value: 0x0000, lo: 0x0f}, + {value: 0xa000, lo: 0x83, hi: 0x83}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0xa000, lo: 0x8b, hi: 0x8b}, + {value: 0xa000, lo: 0x8d, hi: 0x8d}, + {value: 0x37a8, lo: 0x90, hi: 0x90}, + {value: 0x37b4, lo: 0x91, hi: 0x91}, + {value: 0x37a2, lo: 0x93, hi: 0x93}, + {value: 0xa000, lo: 0x96, hi: 0x96}, + {value: 0x381a, lo: 0x97, hi: 0x97}, + {value: 0x37e4, lo: 0x9c, hi: 0x9c}, + {value: 0x37cc, lo: 0x9d, hi: 0x9d}, + {value: 0x37f6, lo: 0x9e, hi: 0x9e}, + {value: 0xa000, lo: 0xb4, hi: 0xb5}, + {value: 0x3820, lo: 0xb6, hi: 0xb6}, + {value: 0x3826, lo: 0xb7, hi: 0xb7}, + // Block 0x5, offset 0x35 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x83, hi: 0x87}, + // Block 0x6, offset 0x37 + {value: 0x0001, lo: 0x04}, + {value: 0x8113, lo: 0x81, hi: 0x82}, + {value: 0x8132, lo: 0x84, hi: 0x84}, + {value: 0x812d, lo: 0x85, hi: 0x85}, + {value: 0x810d, lo: 0x87, hi: 0x87}, + // Block 0x7, offset 0x3c + {value: 0x0000, lo: 0x0a}, + {value: 0x8132, lo: 0x90, hi: 0x97}, + {value: 0x8119, lo: 0x98, hi: 0x98}, + {value: 0x811a, lo: 0x99, hi: 0x99}, + {value: 0x811b, lo: 0x9a, hi: 0x9a}, + {value: 0x3844, lo: 0xa2, hi: 0xa2}, + {value: 0x384a, lo: 0xa3, hi: 0xa3}, + {value: 0x3856, lo: 0xa4, hi: 0xa4}, + {value: 0x3850, lo: 0xa5, hi: 0xa5}, + {value: 0x385c, lo: 0xa6, hi: 0xa6}, + {value: 0xa000, lo: 0xa7, hi: 0xa7}, + // Block 0x8, offset 0x47 + {value: 0x0000, lo: 0x0e}, + {value: 0x386e, lo: 0x80, hi: 0x80}, + {value: 0xa000, lo: 0x81, hi: 0x81}, + {value: 0x3862, lo: 0x82, hi: 0x82}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x3868, lo: 0x93, hi: 0x93}, + {value: 0xa000, lo: 0x95, hi: 0x95}, + {value: 0x8132, lo: 0x96, hi: 0x9c}, + {value: 0x8132, lo: 0x9f, hi: 0xa2}, + {value: 0x812d, lo: 0xa3, hi: 0xa3}, + {value: 0x8132, lo: 0xa4, hi: 0xa4}, + {value: 0x8132, lo: 0xa7, hi: 0xa8}, + {value: 0x812d, lo: 0xaa, hi: 0xaa}, + {value: 0x8132, lo: 0xab, hi: 0xac}, + {value: 0x812d, lo: 0xad, hi: 0xad}, + // Block 0x9, offset 0x56 + {value: 0x0000, lo: 0x0c}, + {value: 0x811f, lo: 0x91, hi: 0x91}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + {value: 0x812d, lo: 0xb1, hi: 0xb1}, + {value: 0x8132, lo: 0xb2, hi: 0xb3}, + {value: 0x812d, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb5, hi: 0xb6}, + {value: 0x812d, lo: 0xb7, hi: 0xb9}, + {value: 0x8132, lo: 0xba, hi: 0xba}, + {value: 0x812d, lo: 0xbb, hi: 0xbc}, + {value: 0x8132, lo: 0xbd, hi: 0xbd}, + {value: 0x812d, lo: 0xbe, hi: 0xbe}, + {value: 0x8132, lo: 0xbf, hi: 0xbf}, + // Block 0xa, offset 0x63 + {value: 0x0005, lo: 0x07}, + {value: 0x8132, lo: 0x80, hi: 0x80}, + {value: 0x8132, lo: 0x81, hi: 0x81}, + {value: 0x812d, lo: 0x82, hi: 0x83}, + {value: 0x812d, lo: 0x84, hi: 0x85}, + {value: 0x812d, lo: 0x86, hi: 0x87}, + {value: 0x812d, lo: 0x88, hi: 0x89}, + {value: 0x8132, lo: 0x8a, hi: 0x8a}, + // Block 0xb, offset 0x6b + {value: 0x0000, lo: 0x04}, + {value: 0x8132, lo: 0xab, hi: 0xb1}, + {value: 0x812d, lo: 0xb2, hi: 0xb2}, + {value: 0x8132, lo: 0xb3, hi: 0xb3}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + // Block 0xc, offset 0x70 + {value: 0x0000, lo: 0x04}, + {value: 0x8132, lo: 0x96, hi: 0x99}, + {value: 0x8132, lo: 0x9b, hi: 0xa3}, + {value: 0x8132, lo: 0xa5, hi: 0xa7}, + {value: 0x8132, lo: 0xa9, hi: 0xad}, + // Block 0xd, offset 0x75 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x99, hi: 0x9b}, + // Block 0xe, offset 0x77 + {value: 0x0000, lo: 0x07}, + {value: 0xa000, lo: 0xa8, hi: 0xa8}, + {value: 0x3edb, lo: 0xa9, hi: 0xa9}, + {value: 0xa000, lo: 0xb0, hi: 0xb0}, + {value: 0x3ee3, lo: 0xb1, hi: 0xb1}, + {value: 0xa000, lo: 0xb3, hi: 0xb3}, + {value: 0x3eeb, lo: 0xb4, hi: 0xb4}, + {value: 0x9902, lo: 0xbc, hi: 0xbc}, + // Block 0xf, offset 0x7f + {value: 0x0008, lo: 0x06}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x8132, lo: 0x91, hi: 0x91}, + {value: 0x812d, lo: 0x92, hi: 0x92}, + {value: 0x8132, lo: 0x93, hi: 0x93}, + {value: 0x8132, lo: 0x94, hi: 0x94}, + {value: 0x451f, lo: 0x98, hi: 0x9f}, + // Block 0x10, offset 0x86 + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x11, offset 0x89 + {value: 0x0008, lo: 0x07}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2ca1, lo: 0x8b, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + {value: 0x455f, lo: 0x9c, hi: 0x9d}, + {value: 0x456f, lo: 0x9f, hi: 0x9f}, + {value: 0x8132, lo: 0xbe, hi: 0xbe}, + // Block 0x12, offset 0x91 + {value: 0x0000, lo: 0x03}, + {value: 0x4597, lo: 0xb3, hi: 0xb3}, + {value: 0x459f, lo: 0xb6, hi: 0xb6}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + // Block 0x13, offset 0x95 + {value: 0x0008, lo: 0x03}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x4577, lo: 0x99, hi: 0x9b}, + {value: 0x458f, lo: 0x9e, hi: 0x9e}, + // Block 0x14, offset 0x99 + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + // Block 0x15, offset 0x9b + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + // Block 0x16, offset 0x9d + {value: 0x0000, lo: 0x08}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2cb9, lo: 0x88, hi: 0x88}, + {value: 0x2cb1, lo: 0x8b, hi: 0x8b}, + {value: 0x2cc1, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x96, hi: 0x97}, + {value: 0x45a7, lo: 0x9c, hi: 0x9c}, + {value: 0x45af, lo: 0x9d, hi: 0x9d}, + // Block 0x17, offset 0xa6 + {value: 0x0000, lo: 0x03}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x2cc9, lo: 0x94, hi: 0x94}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x18, offset 0xaa + {value: 0x0000, lo: 0x06}, + {value: 0xa000, lo: 0x86, hi: 0x87}, + {value: 0x2cd1, lo: 0x8a, hi: 0x8a}, + {value: 0x2ce1, lo: 0x8b, hi: 0x8b}, + {value: 0x2cd9, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + // Block 0x19, offset 0xb1 + {value: 0x1801, lo: 0x04}, + {value: 0xa000, lo: 0x86, hi: 0x86}, + {value: 0x3ef3, lo: 0x88, hi: 0x88}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x8120, lo: 0x95, hi: 0x96}, + // Block 0x1a, offset 0xb6 + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + {value: 0xa000, lo: 0xbf, hi: 0xbf}, + // Block 0x1b, offset 0xb9 + {value: 0x0000, lo: 0x09}, + {value: 0x2ce9, lo: 0x80, hi: 0x80}, + {value: 0x9900, lo: 0x82, hi: 0x82}, + {value: 0xa000, lo: 0x86, hi: 0x86}, + {value: 0x2cf1, lo: 0x87, hi: 0x87}, + {value: 0x2cf9, lo: 0x88, hi: 0x88}, + {value: 0x2f53, lo: 0x8a, hi: 0x8a}, + {value: 0x2ddb, lo: 0x8b, hi: 0x8b}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x95, hi: 0x96}, + // Block 0x1c, offset 0xc3 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xbb, hi: 0xbc}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x1d, offset 0xc6 + {value: 0x0000, lo: 0x06}, + {value: 0xa000, lo: 0x86, hi: 0x87}, + {value: 0x2d01, lo: 0x8a, hi: 0x8a}, + {value: 0x2d11, lo: 0x8b, hi: 0x8b}, + {value: 0x2d09, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + // Block 0x1e, offset 0xcd + {value: 0x6be7, lo: 0x07}, + {value: 0x9904, lo: 0x8a, hi: 0x8a}, + {value: 0x9900, lo: 0x8f, hi: 0x8f}, + {value: 0xa000, lo: 0x99, hi: 0x99}, + {value: 0x3efb, lo: 0x9a, hi: 0x9a}, + {value: 0x2f5b, lo: 0x9c, hi: 0x9c}, + {value: 0x2de6, lo: 0x9d, hi: 0x9d}, + {value: 0x2d19, lo: 0x9e, hi: 0x9f}, + // Block 0x1f, offset 0xd5 + {value: 0x0000, lo: 0x03}, + {value: 0x2624, lo: 0xb3, hi: 0xb3}, + {value: 0x8122, lo: 0xb8, hi: 0xb9}, + {value: 0x8104, lo: 0xba, hi: 0xba}, + // Block 0x20, offset 0xd9 + {value: 0x0000, lo: 0x01}, + {value: 0x8123, lo: 0x88, hi: 0x8b}, + // Block 0x21, offset 0xdb + {value: 0x0000, lo: 0x03}, + {value: 0x2639, lo: 0xb3, hi: 0xb3}, + {value: 0x8124, lo: 0xb8, hi: 0xb9}, + {value: 0x8104, lo: 0xba, hi: 0xba}, + // Block 0x22, offset 0xdf + {value: 0x0000, lo: 0x03}, + {value: 0x8125, lo: 0x88, hi: 0x8b}, + {value: 0x262b, lo: 0x9c, hi: 0x9c}, + {value: 0x2632, lo: 0x9d, hi: 0x9d}, + // Block 0x23, offset 0xe3 + {value: 0x0000, lo: 0x05}, + {value: 0x030b, lo: 0x8c, hi: 0x8c}, + {value: 0x812d, lo: 0x98, hi: 0x99}, + {value: 0x812d, lo: 0xb5, hi: 0xb5}, + {value: 0x812d, lo: 0xb7, hi: 0xb7}, + {value: 0x812b, lo: 0xb9, hi: 0xb9}, + // Block 0x24, offset 0xe9 + {value: 0x0000, lo: 0x10}, + {value: 0x2647, lo: 0x83, hi: 0x83}, + {value: 0x264e, lo: 0x8d, hi: 0x8d}, + {value: 0x2655, lo: 0x92, hi: 0x92}, + {value: 0x265c, lo: 0x97, hi: 0x97}, + {value: 0x2663, lo: 0x9c, hi: 0x9c}, + {value: 0x2640, lo: 0xa9, hi: 0xa9}, + {value: 0x8126, lo: 0xb1, hi: 0xb1}, + {value: 0x8127, lo: 0xb2, hi: 0xb2}, + {value: 0x4a87, lo: 0xb3, hi: 0xb3}, + {value: 0x8128, lo: 0xb4, hi: 0xb4}, + {value: 0x4a90, lo: 0xb5, hi: 0xb5}, + {value: 0x45b7, lo: 0xb6, hi: 0xb6}, + {value: 0x45f7, lo: 0xb7, hi: 0xb7}, + {value: 0x45bf, lo: 0xb8, hi: 0xb8}, + {value: 0x4602, lo: 0xb9, hi: 0xb9}, + {value: 0x8127, lo: 0xba, hi: 0xbd}, + // Block 0x25, offset 0xfa + {value: 0x0000, lo: 0x0b}, + {value: 0x8127, lo: 0x80, hi: 0x80}, + {value: 0x4a99, lo: 0x81, hi: 0x81}, + {value: 0x8132, lo: 0x82, hi: 0x83}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0x86, hi: 0x87}, + {value: 0x2671, lo: 0x93, hi: 0x93}, + {value: 0x2678, lo: 0x9d, hi: 0x9d}, + {value: 0x267f, lo: 0xa2, hi: 0xa2}, + {value: 0x2686, lo: 0xa7, hi: 0xa7}, + {value: 0x268d, lo: 0xac, hi: 0xac}, + {value: 0x266a, lo: 0xb9, hi: 0xb9}, + // Block 0x26, offset 0x106 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x86, hi: 0x86}, + // Block 0x27, offset 0x108 + {value: 0x0000, lo: 0x05}, + {value: 0xa000, lo: 0xa5, hi: 0xa5}, + {value: 0x2d21, lo: 0xa6, hi: 0xa6}, + {value: 0x9900, lo: 0xae, hi: 0xae}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + {value: 0x8104, lo: 0xb9, hi: 0xba}, + // Block 0x28, offset 0x10e + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x8d, hi: 0x8d}, + // Block 0x29, offset 0x110 + {value: 0x0000, lo: 0x01}, + {value: 0x030f, lo: 0xbc, hi: 0xbc}, + // Block 0x2a, offset 0x112 + {value: 0x0000, lo: 0x01}, + {value: 0xa000, lo: 0x80, hi: 0x92}, + // Block 0x2b, offset 0x114 + {value: 0x0000, lo: 0x01}, + {value: 0xb900, lo: 0xa1, hi: 0xb5}, + // Block 0x2c, offset 0x116 + {value: 0x0000, lo: 0x01}, + {value: 0x9900, lo: 0xa8, hi: 0xbf}, + // Block 0x2d, offset 0x118 + {value: 0x0000, lo: 0x01}, + {value: 0x9900, lo: 0x80, hi: 0x82}, + // Block 0x2e, offset 0x11a + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x9d, hi: 0x9f}, + // Block 0x2f, offset 0x11c + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x94, hi: 0x94}, + {value: 0x8104, lo: 0xb4, hi: 0xb4}, + // Block 0x30, offset 0x11f + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x92, hi: 0x92}, + {value: 0x8132, lo: 0x9d, hi: 0x9d}, + // Block 0x31, offset 0x122 + {value: 0x0000, lo: 0x01}, + {value: 0x8131, lo: 0xa9, hi: 0xa9}, + // Block 0x32, offset 0x124 + {value: 0x0004, lo: 0x02}, + {value: 0x812e, lo: 0xb9, hi: 0xba}, + {value: 0x812d, lo: 0xbb, hi: 0xbb}, + // Block 0x33, offset 0x127 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x97, hi: 0x97}, + {value: 0x812d, lo: 0x98, hi: 0x98}, + // Block 0x34, offset 0x12a + {value: 0x0000, lo: 0x03}, + {value: 0x8104, lo: 0xa0, hi: 0xa0}, + {value: 0x8132, lo: 0xb5, hi: 0xbc}, + {value: 0x812d, lo: 0xbf, hi: 0xbf}, + // Block 0x35, offset 0x12e + {value: 0x0000, lo: 0x04}, + {value: 0x8132, lo: 0xb0, hi: 0xb4}, + {value: 0x812d, lo: 0xb5, hi: 0xba}, + {value: 0x8132, lo: 0xbb, hi: 0xbc}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + // Block 0x36, offset 0x133 + {value: 0x0000, lo: 0x08}, + {value: 0x2d69, lo: 0x80, hi: 0x80}, + {value: 0x2d71, lo: 0x81, hi: 0x81}, + {value: 0xa000, lo: 0x82, hi: 0x82}, + {value: 0x2d79, lo: 0x83, hi: 0x83}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0xab, hi: 0xab}, + {value: 0x812d, lo: 0xac, hi: 0xac}, + {value: 0x8132, lo: 0xad, hi: 0xb3}, + // Block 0x37, offset 0x13c + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xaa, hi: 0xab}, + // Block 0x38, offset 0x13e + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xa6, hi: 0xa6}, + {value: 0x8104, lo: 0xb2, hi: 0xb3}, + // Block 0x39, offset 0x141 + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + // Block 0x3a, offset 0x143 + {value: 0x0000, lo: 0x0a}, + {value: 0x8132, lo: 0x90, hi: 0x92}, + {value: 0x8101, lo: 0x94, hi: 0x94}, + {value: 0x812d, lo: 0x95, hi: 0x99}, + {value: 0x8132, lo: 0x9a, hi: 0x9b}, + {value: 0x812d, lo: 0x9c, hi: 0x9f}, + {value: 0x8132, lo: 0xa0, hi: 0xa0}, + {value: 0x8101, lo: 0xa2, hi: 0xa8}, + {value: 0x812d, lo: 0xad, hi: 0xad}, + {value: 0x8132, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb8, hi: 0xb9}, + // Block 0x3b, offset 0x14e + {value: 0x0002, lo: 0x0a}, + {value: 0x0043, lo: 0xac, hi: 0xac}, + {value: 0x00d1, lo: 0xad, hi: 0xad}, + {value: 0x0045, lo: 0xae, hi: 0xae}, + {value: 0x0049, lo: 0xb0, hi: 0xb1}, + {value: 0x00e6, lo: 0xb2, hi: 0xb2}, + {value: 0x004f, lo: 0xb3, hi: 0xba}, + {value: 0x005f, lo: 0xbc, hi: 0xbc}, + {value: 0x00ef, lo: 0xbd, hi: 0xbd}, + {value: 0x0061, lo: 0xbe, hi: 0xbe}, + {value: 0x0065, lo: 0xbf, hi: 0xbf}, + // Block 0x3c, offset 0x159 + {value: 0x0000, lo: 0x0d}, + {value: 0x0001, lo: 0x80, hi: 0x8a}, + {value: 0x043b, lo: 0x91, hi: 0x91}, + {value: 0x429e, lo: 0x97, hi: 0x97}, + {value: 0x001d, lo: 0xa4, hi: 0xa4}, + {value: 0x1873, lo: 0xa5, hi: 0xa5}, + {value: 0x1b5f, lo: 0xa6, hi: 0xa6}, + {value: 0x0001, lo: 0xaf, hi: 0xaf}, + {value: 0x2694, lo: 0xb3, hi: 0xb3}, + {value: 0x2801, lo: 0xb4, hi: 0xb4}, + {value: 0x269b, lo: 0xb6, hi: 0xb6}, + {value: 0x280b, lo: 0xb7, hi: 0xb7}, + {value: 0x186d, lo: 0xbc, hi: 0xbc}, + {value: 0x426c, lo: 0xbe, hi: 0xbe}, + // Block 0x3d, offset 0x167 + {value: 0x0002, lo: 0x0d}, + {value: 0x1933, lo: 0x87, hi: 0x87}, + {value: 0x1930, lo: 0x88, hi: 0x88}, + {value: 0x1870, lo: 0x89, hi: 0x89}, + {value: 0x2991, lo: 0x97, hi: 0x97}, + {value: 0x0001, lo: 0x9f, hi: 0x9f}, + {value: 0x0021, lo: 0xb0, hi: 0xb0}, + {value: 0x0093, lo: 0xb1, hi: 0xb1}, + {value: 0x0029, lo: 0xb4, hi: 0xb9}, + {value: 0x0017, lo: 0xba, hi: 0xba}, + {value: 0x0467, lo: 0xbb, hi: 0xbb}, + {value: 0x003b, lo: 0xbc, hi: 0xbc}, + {value: 0x0011, lo: 0xbd, hi: 0xbe}, + {value: 0x009d, lo: 0xbf, hi: 0xbf}, + // Block 0x3e, offset 0x175 + {value: 0x0002, lo: 0x0f}, + {value: 0x0021, lo: 0x80, hi: 0x89}, + {value: 0x0017, lo: 0x8a, hi: 0x8a}, + {value: 0x0467, lo: 0x8b, hi: 0x8b}, + {value: 0x003b, lo: 0x8c, hi: 0x8c}, + {value: 0x0011, lo: 0x8d, hi: 0x8e}, + {value: 0x0083, lo: 0x90, hi: 0x90}, + {value: 0x008b, lo: 0x91, hi: 0x91}, + {value: 0x009f, lo: 0x92, hi: 0x92}, + {value: 0x00b1, lo: 0x93, hi: 0x93}, + {value: 0x0104, lo: 0x94, hi: 0x94}, + {value: 0x0091, lo: 0x95, hi: 0x95}, + {value: 0x0097, lo: 0x96, hi: 0x99}, + {value: 0x00a1, lo: 0x9a, hi: 0x9a}, + {value: 0x00a7, lo: 0x9b, hi: 0x9c}, + {value: 0x199c, lo: 0xa8, hi: 0xa8}, + // Block 0x3f, offset 0x185 + {value: 0x0000, lo: 0x0d}, + {value: 0x8132, lo: 0x90, hi: 0x91}, + {value: 0x8101, lo: 0x92, hi: 0x93}, + {value: 0x8132, lo: 0x94, hi: 0x97}, + {value: 0x8101, lo: 0x98, hi: 0x9a}, + {value: 0x8132, lo: 0x9b, hi: 0x9c}, + {value: 0x8132, lo: 0xa1, hi: 0xa1}, + {value: 0x8101, lo: 0xa5, hi: 0xa6}, + {value: 0x8132, lo: 0xa7, hi: 0xa7}, + {value: 0x812d, lo: 0xa8, hi: 0xa8}, + {value: 0x8132, lo: 0xa9, hi: 0xa9}, + {value: 0x8101, lo: 0xaa, hi: 0xab}, + {value: 0x812d, lo: 0xac, hi: 0xaf}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + // Block 0x40, offset 0x193 + {value: 0x0007, lo: 0x06}, + {value: 0x2183, lo: 0x89, hi: 0x89}, + {value: 0xa000, lo: 0x90, hi: 0x90}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0xa000, lo: 0x94, hi: 0x94}, + {value: 0x3bbc, lo: 0x9a, hi: 0x9b}, + {value: 0x3bca, lo: 0xae, hi: 0xae}, + // Block 0x41, offset 0x19a + {value: 0x000e, lo: 0x05}, + {value: 0x3bd1, lo: 0x8d, hi: 0x8e}, + {value: 0x3bd8, lo: 0x8f, hi: 0x8f}, + {value: 0xa000, lo: 0x90, hi: 0x90}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0xa000, lo: 0x94, hi: 0x94}, + // Block 0x42, offset 0x1a0 + {value: 0x0173, lo: 0x0e}, + {value: 0xa000, lo: 0x83, hi: 0x83}, + {value: 0x3be6, lo: 0x84, hi: 0x84}, + {value: 0xa000, lo: 0x88, hi: 0x88}, + {value: 0x3bed, lo: 0x89, hi: 0x89}, + {value: 0xa000, lo: 0x8b, hi: 0x8b}, + {value: 0x3bf4, lo: 0x8c, hi: 0x8c}, + {value: 0xa000, lo: 0xa3, hi: 0xa3}, + {value: 0x3bfb, lo: 0xa4, hi: 0xa4}, + {value: 0xa000, lo: 0xa5, hi: 0xa5}, + {value: 0x3c02, lo: 0xa6, hi: 0xa6}, + {value: 0x26a2, lo: 0xac, hi: 0xad}, + {value: 0x26a9, lo: 0xaf, hi: 0xaf}, + {value: 0x281f, lo: 0xb0, hi: 0xb0}, + {value: 0xa000, lo: 0xbc, hi: 0xbc}, + // Block 0x43, offset 0x1af + {value: 0x0007, lo: 0x03}, + {value: 0x3c6b, lo: 0xa0, hi: 0xa1}, + {value: 0x3c95, lo: 0xa2, hi: 0xa3}, + {value: 0x3cbf, lo: 0xaa, hi: 0xad}, + // Block 0x44, offset 0x1b3 + {value: 0x0004, lo: 0x01}, + {value: 0x048b, lo: 0xa9, hi: 0xaa}, + // Block 0x45, offset 0x1b5 + {value: 0x0002, lo: 0x03}, + {value: 0x0057, lo: 0x80, hi: 0x8f}, + {value: 0x0083, lo: 0x90, hi: 0xa9}, + {value: 0x0021, lo: 0xaa, hi: 0xaa}, + // Block 0x46, offset 0x1b9 + {value: 0x0000, lo: 0x01}, + {value: 0x299e, lo: 0x8c, hi: 0x8c}, + // Block 0x47, offset 0x1bb + {value: 0x0266, lo: 0x02}, + {value: 0x1b8f, lo: 0xb4, hi: 0xb4}, + {value: 0x192d, lo: 0xb5, hi: 0xb6}, + // Block 0x48, offset 0x1be + {value: 0x0000, lo: 0x01}, + {value: 0x44e0, lo: 0x9c, hi: 0x9c}, + // Block 0x49, offset 0x1c0 + {value: 0x0000, lo: 0x02}, + {value: 0x0095, lo: 0xbc, hi: 0xbc}, + {value: 0x006d, lo: 0xbd, hi: 0xbd}, + // Block 0x4a, offset 0x1c3 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xaf, hi: 0xb1}, + // Block 0x4b, offset 0x1c5 + {value: 0x0000, lo: 0x02}, + {value: 0x047f, lo: 0xaf, hi: 0xaf}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x4c, offset 0x1c8 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xa0, hi: 0xbf}, + // Block 0x4d, offset 0x1ca + {value: 0x0000, lo: 0x01}, + {value: 0x0dc3, lo: 0x9f, hi: 0x9f}, + // Block 0x4e, offset 0x1cc + {value: 0x0000, lo: 0x01}, + {value: 0x162f, lo: 0xb3, hi: 0xb3}, + // Block 0x4f, offset 0x1ce + {value: 0x0004, lo: 0x0b}, + {value: 0x1597, lo: 0x80, hi: 0x82}, + {value: 0x15af, lo: 0x83, hi: 0x83}, + {value: 0x15c7, lo: 0x84, hi: 0x85}, + {value: 0x15d7, lo: 0x86, hi: 0x89}, + {value: 0x15eb, lo: 0x8a, hi: 0x8c}, + {value: 0x15ff, lo: 0x8d, hi: 0x8d}, + {value: 0x1607, lo: 0x8e, hi: 0x8e}, + {value: 0x160f, lo: 0x8f, hi: 0x90}, + {value: 0x161b, lo: 0x91, hi: 0x93}, + {value: 0x162b, lo: 0x94, hi: 0x94}, + {value: 0x1633, lo: 0x95, hi: 0x95}, + // Block 0x50, offset 0x1da + {value: 0x0004, lo: 0x09}, + {value: 0x0001, lo: 0x80, hi: 0x80}, + {value: 0x812c, lo: 0xaa, hi: 0xaa}, + {value: 0x8131, lo: 0xab, hi: 0xab}, + {value: 0x8133, lo: 0xac, hi: 0xac}, + {value: 0x812e, lo: 0xad, hi: 0xad}, + {value: 0x812f, lo: 0xae, hi: 0xae}, + {value: 0x812f, lo: 0xaf, hi: 0xaf}, + {value: 0x04b3, lo: 0xb6, hi: 0xb6}, + {value: 0x0887, lo: 0xb8, hi: 0xba}, + // Block 0x51, offset 0x1e4 + {value: 0x0006, lo: 0x09}, + {value: 0x0313, lo: 0xb1, hi: 0xb1}, + {value: 0x0317, lo: 0xb2, hi: 0xb2}, + {value: 0x4a3e, lo: 0xb3, hi: 0xb3}, + {value: 0x031b, lo: 0xb4, hi: 0xb4}, + {value: 0x4a44, lo: 0xb5, hi: 0xb6}, + {value: 0x031f, lo: 0xb7, hi: 0xb7}, + {value: 0x0323, lo: 0xb8, hi: 0xb8}, + {value: 0x0327, lo: 0xb9, hi: 0xb9}, + {value: 0x4a50, lo: 0xba, hi: 0xbf}, + // Block 0x52, offset 0x1ee + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0xaf, hi: 0xaf}, + {value: 0x8132, lo: 0xb4, hi: 0xbd}, + // Block 0x53, offset 0x1f1 + {value: 0x0000, lo: 0x03}, + {value: 0x020f, lo: 0x9c, hi: 0x9c}, + {value: 0x0212, lo: 0x9d, hi: 0x9d}, + {value: 0x8132, lo: 0x9e, hi: 0x9f}, + // Block 0x54, offset 0x1f5 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb0, hi: 0xb1}, + // Block 0x55, offset 0x1f7 + {value: 0x0000, lo: 0x01}, + {value: 0x163b, lo: 0xb0, hi: 0xb0}, + // Block 0x56, offset 0x1f9 + {value: 0x000c, lo: 0x01}, + {value: 0x00d7, lo: 0xb8, hi: 0xb9}, + // Block 0x57, offset 0x1fb + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x86, hi: 0x86}, + // Block 0x58, offset 0x1fd + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0xa0, hi: 0xb1}, + // Block 0x59, offset 0x200 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xab, hi: 0xad}, + // Block 0x5a, offset 0x202 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x93, hi: 0x93}, + // Block 0x5b, offset 0x204 + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xb3, hi: 0xb3}, + // Block 0x5c, offset 0x206 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x80, hi: 0x80}, + // Block 0x5d, offset 0x208 + {value: 0x0000, lo: 0x05}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + {value: 0x8132, lo: 0xb2, hi: 0xb3}, + {value: 0x812d, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb7, hi: 0xb8}, + {value: 0x8132, lo: 0xbe, hi: 0xbf}, + // Block 0x5e, offset 0x20e + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x81, hi: 0x81}, + {value: 0x8104, lo: 0xb6, hi: 0xb6}, + // Block 0x5f, offset 0x211 + {value: 0x0008, lo: 0x03}, + {value: 0x1637, lo: 0x9c, hi: 0x9d}, + {value: 0x0125, lo: 0x9e, hi: 0x9e}, + {value: 0x1643, lo: 0x9f, hi: 0x9f}, + // Block 0x60, offset 0x215 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xad, hi: 0xad}, + // Block 0x61, offset 0x217 + {value: 0x0000, lo: 0x06}, + {value: 0xe500, lo: 0x80, hi: 0x80}, + {value: 0xc600, lo: 0x81, hi: 0x9b}, + {value: 0xe500, lo: 0x9c, hi: 0x9c}, + {value: 0xc600, lo: 0x9d, hi: 0xb7}, + {value: 0xe500, lo: 0xb8, hi: 0xb8}, + {value: 0xc600, lo: 0xb9, hi: 0xbf}, + // Block 0x62, offset 0x21e + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x93}, + {value: 0xe500, lo: 0x94, hi: 0x94}, + {value: 0xc600, lo: 0x95, hi: 0xaf}, + {value: 0xe500, lo: 0xb0, hi: 0xb0}, + {value: 0xc600, lo: 0xb1, hi: 0xbf}, + // Block 0x63, offset 0x224 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x8b}, + {value: 0xe500, lo: 0x8c, hi: 0x8c}, + {value: 0xc600, lo: 0x8d, hi: 0xa7}, + {value: 0xe500, lo: 0xa8, hi: 0xa8}, + {value: 0xc600, lo: 0xa9, hi: 0xbf}, + // Block 0x64, offset 0x22a + {value: 0x0000, lo: 0x07}, + {value: 0xc600, lo: 0x80, hi: 0x83}, + {value: 0xe500, lo: 0x84, hi: 0x84}, + {value: 0xc600, lo: 0x85, hi: 0x9f}, + {value: 0xe500, lo: 0xa0, hi: 0xa0}, + {value: 0xc600, lo: 0xa1, hi: 0xbb}, + {value: 0xe500, lo: 0xbc, hi: 0xbc}, + {value: 0xc600, lo: 0xbd, hi: 0xbf}, + // Block 0x65, offset 0x232 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x97}, + {value: 0xe500, lo: 0x98, hi: 0x98}, + {value: 0xc600, lo: 0x99, hi: 0xb3}, + {value: 0xe500, lo: 0xb4, hi: 0xb4}, + {value: 0xc600, lo: 0xb5, hi: 0xbf}, + // Block 0x66, offset 0x238 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x8f}, + {value: 0xe500, lo: 0x90, hi: 0x90}, + {value: 0xc600, lo: 0x91, hi: 0xab}, + {value: 0xe500, lo: 0xac, hi: 0xac}, + {value: 0xc600, lo: 0xad, hi: 0xbf}, + // Block 0x67, offset 0x23e + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x87}, + {value: 0xe500, lo: 0x88, hi: 0x88}, + {value: 0xc600, lo: 0x89, hi: 0xa3}, + {value: 0xe500, lo: 0xa4, hi: 0xa4}, + {value: 0xc600, lo: 0xa5, hi: 0xbf}, + // Block 0x68, offset 0x244 + {value: 0x0000, lo: 0x03}, + {value: 0xc600, lo: 0x80, hi: 0x87}, + {value: 0xe500, lo: 0x88, hi: 0x88}, + {value: 0xc600, lo: 0x89, hi: 0xa3}, + // Block 0x69, offset 0x248 + {value: 0x0002, lo: 0x01}, + {value: 0x0003, lo: 0x81, hi: 0xbf}, + // Block 0x6a, offset 0x24a + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + // Block 0x6b, offset 0x24c + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xa0, hi: 0xa0}, + // Block 0x6c, offset 0x24e + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb6, hi: 0xba}, + // Block 0x6d, offset 0x250 + {value: 0x002c, lo: 0x05}, + {value: 0x812d, lo: 0x8d, hi: 0x8d}, + {value: 0x8132, lo: 0x8f, hi: 0x8f}, + {value: 0x8132, lo: 0xb8, hi: 0xb8}, + {value: 0x8101, lo: 0xb9, hi: 0xba}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x6e, offset 0x256 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0xa5, hi: 0xa5}, + {value: 0x812d, lo: 0xa6, hi: 0xa6}, + // Block 0x6f, offset 0x259 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xa4, hi: 0xa7}, + // Block 0x70, offset 0x25b + {value: 0x0000, lo: 0x05}, + {value: 0x812d, lo: 0x86, hi: 0x87}, + {value: 0x8132, lo: 0x88, hi: 0x8a}, + {value: 0x812d, lo: 0x8b, hi: 0x8b}, + {value: 0x8132, lo: 0x8c, hi: 0x8c}, + {value: 0x812d, lo: 0x8d, hi: 0x90}, + // Block 0x71, offset 0x261 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x86, hi: 0x86}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x72, offset 0x264 + {value: 0x17fe, lo: 0x07}, + {value: 0xa000, lo: 0x99, hi: 0x99}, + {value: 0x423b, lo: 0x9a, hi: 0x9a}, + {value: 0xa000, lo: 0x9b, hi: 0x9b}, + {value: 0x4245, lo: 0x9c, hi: 0x9c}, + {value: 0xa000, lo: 0xa5, hi: 0xa5}, + {value: 0x424f, lo: 0xab, hi: 0xab}, + {value: 0x8104, lo: 0xb9, hi: 0xba}, + // Block 0x73, offset 0x26c + {value: 0x0000, lo: 0x06}, + {value: 0x8132, lo: 0x80, hi: 0x82}, + {value: 0x9900, lo: 0xa7, hi: 0xa7}, + {value: 0x2d81, lo: 0xae, hi: 0xae}, + {value: 0x2d8b, lo: 0xaf, hi: 0xaf}, + {value: 0xa000, lo: 0xb1, hi: 0xb2}, + {value: 0x8104, lo: 0xb3, hi: 0xb4}, + // Block 0x74, offset 0x273 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x80, hi: 0x80}, + {value: 0x8102, lo: 0x8a, hi: 0x8a}, + // Block 0x75, offset 0x276 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xb5, hi: 0xb5}, + {value: 0x8102, lo: 0xb6, hi: 0xb6}, + // Block 0x76, offset 0x279 + {value: 0x0002, lo: 0x01}, + {value: 0x8102, lo: 0xa9, hi: 0xaa}, + // Block 0x77, offset 0x27b + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xbb, hi: 0xbc}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x78, offset 0x27e + {value: 0x0000, lo: 0x07}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2d95, lo: 0x8b, hi: 0x8b}, + {value: 0x2d9f, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + {value: 0x8132, lo: 0xa6, hi: 0xac}, + {value: 0x8132, lo: 0xb0, hi: 0xb4}, + // Block 0x79, offset 0x286 + {value: 0x0000, lo: 0x03}, + {value: 0x8104, lo: 0x82, hi: 0x82}, + {value: 0x8102, lo: 0x86, hi: 0x86}, + {value: 0x8132, lo: 0x9e, hi: 0x9e}, + // Block 0x7a, offset 0x28a + {value: 0x6b57, lo: 0x06}, + {value: 0x9900, lo: 0xb0, hi: 0xb0}, + {value: 0xa000, lo: 0xb9, hi: 0xb9}, + {value: 0x9900, lo: 0xba, hi: 0xba}, + {value: 0x2db3, lo: 0xbb, hi: 0xbb}, + {value: 0x2da9, lo: 0xbc, hi: 0xbd}, + {value: 0x2dbd, lo: 0xbe, hi: 0xbe}, + // Block 0x7b, offset 0x291 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x82, hi: 0x82}, + {value: 0x8102, lo: 0x83, hi: 0x83}, + // Block 0x7c, offset 0x294 + {value: 0x0000, lo: 0x05}, + {value: 0x9900, lo: 0xaf, hi: 0xaf}, + {value: 0xa000, lo: 0xb8, hi: 0xb9}, + {value: 0x2dc7, lo: 0xba, hi: 0xba}, + {value: 0x2dd1, lo: 0xbb, hi: 0xbb}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x7d, offset 0x29a + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0x80, hi: 0x80}, + // Block 0x7e, offset 0x29c + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x7f, offset 0x29e + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xb6, hi: 0xb6}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + // Block 0x80, offset 0x2a1 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xab, hi: 0xab}, + // Block 0x81, offset 0x2a3 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xb9, hi: 0xb9}, + {value: 0x8102, lo: 0xba, hi: 0xba}, + // Block 0x82, offset 0x2a6 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xa0, hi: 0xa0}, + // Block 0x83, offset 0x2a8 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xb4, hi: 0xb4}, + // Block 0x84, offset 0x2aa + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x87, hi: 0x87}, + // Block 0x85, offset 0x2ac + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x99, hi: 0x99}, + // Block 0x86, offset 0x2ae + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0x82, hi: 0x82}, + {value: 0x8104, lo: 0x84, hi: 0x85}, + // Block 0x87, offset 0x2b1 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x97, hi: 0x97}, + // Block 0x88, offset 0x2b3 + {value: 0x0000, lo: 0x01}, + {value: 0x8101, lo: 0xb0, hi: 0xb4}, + // Block 0x89, offset 0x2b5 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb0, hi: 0xb6}, + // Block 0x8a, offset 0x2b7 + {value: 0x0000, lo: 0x01}, + {value: 0x8101, lo: 0x9e, hi: 0x9e}, + // Block 0x8b, offset 0x2b9 + {value: 0x0000, lo: 0x0c}, + {value: 0x45cf, lo: 0x9e, hi: 0x9e}, + {value: 0x45d9, lo: 0x9f, hi: 0x9f}, + {value: 0x460d, lo: 0xa0, hi: 0xa0}, + {value: 0x461b, lo: 0xa1, hi: 0xa1}, + {value: 0x4629, lo: 0xa2, hi: 0xa2}, + {value: 0x4637, lo: 0xa3, hi: 0xa3}, + {value: 0x4645, lo: 0xa4, hi: 0xa4}, + {value: 0x812b, lo: 0xa5, hi: 0xa6}, + {value: 0x8101, lo: 0xa7, hi: 0xa9}, + {value: 0x8130, lo: 0xad, hi: 0xad}, + {value: 0x812b, lo: 0xae, hi: 0xb2}, + {value: 0x812d, lo: 0xbb, hi: 0xbf}, + // Block 0x8c, offset 0x2c6 + {value: 0x0000, lo: 0x09}, + {value: 0x812d, lo: 0x80, hi: 0x82}, + {value: 0x8132, lo: 0x85, hi: 0x89}, + {value: 0x812d, lo: 0x8a, hi: 0x8b}, + {value: 0x8132, lo: 0xaa, hi: 0xad}, + {value: 0x45e3, lo: 0xbb, hi: 0xbb}, + {value: 0x45ed, lo: 0xbc, hi: 0xbc}, + {value: 0x4653, lo: 0xbd, hi: 0xbd}, + {value: 0x466f, lo: 0xbe, hi: 0xbe}, + {value: 0x4661, lo: 0xbf, hi: 0xbf}, + // Block 0x8d, offset 0x2d0 + {value: 0x0000, lo: 0x01}, + {value: 0x467d, lo: 0x80, hi: 0x80}, + // Block 0x8e, offset 0x2d2 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x82, hi: 0x84}, + // Block 0x8f, offset 0x2d4 + {value: 0x0002, lo: 0x03}, + {value: 0x0043, lo: 0x80, hi: 0x99}, + {value: 0x0083, lo: 0x9a, hi: 0xb3}, + {value: 0x0043, lo: 0xb4, hi: 0xbf}, + // Block 0x90, offset 0x2d8 + {value: 0x0002, lo: 0x04}, + {value: 0x005b, lo: 0x80, hi: 0x8d}, + {value: 0x0083, lo: 0x8e, hi: 0x94}, + {value: 0x0093, lo: 0x96, hi: 0xa7}, + {value: 0x0043, lo: 0xa8, hi: 0xbf}, + // Block 0x91, offset 0x2dd + {value: 0x0002, lo: 0x0b}, + {value: 0x0073, lo: 0x80, hi: 0x81}, + {value: 0x0083, lo: 0x82, hi: 0x9b}, + {value: 0x0043, lo: 0x9c, hi: 0x9c}, + {value: 0x0047, lo: 0x9e, hi: 0x9f}, + {value: 0x004f, lo: 0xa2, hi: 0xa2}, + {value: 0x0055, lo: 0xa5, hi: 0xa6}, + {value: 0x005d, lo: 0xa9, hi: 0xac}, + {value: 0x0067, lo: 0xae, hi: 0xb5}, + {value: 0x0083, lo: 0xb6, hi: 0xb9}, + {value: 0x008d, lo: 0xbb, hi: 0xbb}, + {value: 0x0091, lo: 0xbd, hi: 0xbf}, + // Block 0x92, offset 0x2e9 + {value: 0x0002, lo: 0x04}, + {value: 0x0097, lo: 0x80, hi: 0x83}, + {value: 0x00a1, lo: 0x85, hi: 0x8f}, + {value: 0x0043, lo: 0x90, hi: 0xa9}, + {value: 0x0083, lo: 0xaa, hi: 0xbf}, + // Block 0x93, offset 0x2ee + {value: 0x0002, lo: 0x08}, + {value: 0x00af, lo: 0x80, hi: 0x83}, + {value: 0x0043, lo: 0x84, hi: 0x85}, + {value: 0x0049, lo: 0x87, hi: 0x8a}, + {value: 0x0055, lo: 0x8d, hi: 0x94}, + {value: 0x0067, lo: 0x96, hi: 0x9c}, + {value: 0x0083, lo: 0x9e, hi: 0xb7}, + {value: 0x0043, lo: 0xb8, hi: 0xb9}, + {value: 0x0049, lo: 0xbb, hi: 0xbe}, + // Block 0x94, offset 0x2f7 + {value: 0x0002, lo: 0x05}, + {value: 0x0053, lo: 0x80, hi: 0x84}, + {value: 0x005f, lo: 0x86, hi: 0x86}, + {value: 0x0067, lo: 0x8a, hi: 0x90}, + {value: 0x0083, lo: 0x92, hi: 0xab}, + {value: 0x0043, lo: 0xac, hi: 0xbf}, + // Block 0x95, offset 0x2fd + {value: 0x0002, lo: 0x04}, + {value: 0x006b, lo: 0x80, hi: 0x85}, + {value: 0x0083, lo: 0x86, hi: 0x9f}, + {value: 0x0043, lo: 0xa0, hi: 0xb9}, + {value: 0x0083, lo: 0xba, hi: 0xbf}, + // Block 0x96, offset 0x302 + {value: 0x0002, lo: 0x03}, + {value: 0x008f, lo: 0x80, hi: 0x93}, + {value: 0x0043, lo: 0x94, hi: 0xad}, + {value: 0x0083, lo: 0xae, hi: 0xbf}, + // Block 0x97, offset 0x306 + {value: 0x0002, lo: 0x04}, + {value: 0x00a7, lo: 0x80, hi: 0x87}, + {value: 0x0043, lo: 0x88, hi: 0xa1}, + {value: 0x0083, lo: 0xa2, hi: 0xbb}, + {value: 0x0043, lo: 0xbc, hi: 0xbf}, + // Block 0x98, offset 0x30b + {value: 0x0002, lo: 0x03}, + {value: 0x004b, lo: 0x80, hi: 0x95}, + {value: 0x0083, lo: 0x96, hi: 0xaf}, + {value: 0x0043, lo: 0xb0, hi: 0xbf}, + // Block 0x99, offset 0x30f + {value: 0x0003, lo: 0x0f}, + {value: 0x01b8, lo: 0x80, hi: 0x80}, + {value: 0x045f, lo: 0x81, hi: 0x81}, + {value: 0x01bb, lo: 0x82, hi: 0x9a}, + {value: 0x045b, lo: 0x9b, hi: 0x9b}, + {value: 0x01c7, lo: 0x9c, hi: 0x9c}, + {value: 0x01d0, lo: 0x9d, hi: 0x9d}, + {value: 0x01d6, lo: 0x9e, hi: 0x9e}, + {value: 0x01fa, lo: 0x9f, hi: 0x9f}, + {value: 0x01eb, lo: 0xa0, hi: 0xa0}, + {value: 0x01e8, lo: 0xa1, hi: 0xa1}, + {value: 0x0173, lo: 0xa2, hi: 0xb2}, + {value: 0x0188, lo: 0xb3, hi: 0xb3}, + {value: 0x01a6, lo: 0xb4, hi: 0xba}, + {value: 0x045f, lo: 0xbb, hi: 0xbb}, + {value: 0x01bb, lo: 0xbc, hi: 0xbf}, + // Block 0x9a, offset 0x31f + {value: 0x0003, lo: 0x0d}, + {value: 0x01c7, lo: 0x80, hi: 0x94}, + {value: 0x045b, lo: 0x95, hi: 0x95}, + {value: 0x01c7, lo: 0x96, hi: 0x96}, + {value: 0x01d0, lo: 0x97, hi: 0x97}, + {value: 0x01d6, lo: 0x98, hi: 0x98}, + {value: 0x01fa, lo: 0x99, hi: 0x99}, + {value: 0x01eb, lo: 0x9a, hi: 0x9a}, + {value: 0x01e8, lo: 0x9b, hi: 0x9b}, + {value: 0x0173, lo: 0x9c, hi: 0xac}, + {value: 0x0188, lo: 0xad, hi: 0xad}, + {value: 0x01a6, lo: 0xae, hi: 0xb4}, + {value: 0x045f, lo: 0xb5, hi: 0xb5}, + {value: 0x01bb, lo: 0xb6, hi: 0xbf}, + // Block 0x9b, offset 0x32d + {value: 0x0003, lo: 0x0d}, + {value: 0x01d9, lo: 0x80, hi: 0x8e}, + {value: 0x045b, lo: 0x8f, hi: 0x8f}, + {value: 0x01c7, lo: 0x90, hi: 0x90}, + {value: 0x01d0, lo: 0x91, hi: 0x91}, + {value: 0x01d6, lo: 0x92, hi: 0x92}, + {value: 0x01fa, lo: 0x93, hi: 0x93}, + {value: 0x01eb, lo: 0x94, hi: 0x94}, + {value: 0x01e8, lo: 0x95, hi: 0x95}, + {value: 0x0173, lo: 0x96, hi: 0xa6}, + {value: 0x0188, lo: 0xa7, hi: 0xa7}, + {value: 0x01a6, lo: 0xa8, hi: 0xae}, + {value: 0x045f, lo: 0xaf, hi: 0xaf}, + {value: 0x01bb, lo: 0xb0, hi: 0xbf}, + // Block 0x9c, offset 0x33b + {value: 0x0003, lo: 0x0d}, + {value: 0x01eb, lo: 0x80, hi: 0x88}, + {value: 0x045b, lo: 0x89, hi: 0x89}, + {value: 0x01c7, lo: 0x8a, hi: 0x8a}, + {value: 0x01d0, lo: 0x8b, hi: 0x8b}, + {value: 0x01d6, lo: 0x8c, hi: 0x8c}, + {value: 0x01fa, lo: 0x8d, hi: 0x8d}, + {value: 0x01eb, lo: 0x8e, hi: 0x8e}, + {value: 0x01e8, lo: 0x8f, hi: 0x8f}, + {value: 0x0173, lo: 0x90, hi: 0xa0}, + {value: 0x0188, lo: 0xa1, hi: 0xa1}, + {value: 0x01a6, lo: 0xa2, hi: 0xa8}, + {value: 0x045f, lo: 0xa9, hi: 0xa9}, + {value: 0x01bb, lo: 0xaa, hi: 0xbf}, + // Block 0x9d, offset 0x349 + {value: 0x0000, lo: 0x05}, + {value: 0x8132, lo: 0x80, hi: 0x86}, + {value: 0x8132, lo: 0x88, hi: 0x98}, + {value: 0x8132, lo: 0x9b, hi: 0xa1}, + {value: 0x8132, lo: 0xa3, hi: 0xa4}, + {value: 0x8132, lo: 0xa6, hi: 0xaa}, + // Block 0x9e, offset 0x34f + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xac, hi: 0xaf}, + // Block 0x9f, offset 0x351 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x90, hi: 0x96}, + // Block 0xa0, offset 0x353 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x84, hi: 0x89}, + {value: 0x8102, lo: 0x8a, hi: 0x8a}, + // Block 0xa1, offset 0x356 + {value: 0x0002, lo: 0x0a}, + {value: 0x0063, lo: 0x80, hi: 0x89}, + {value: 0x1951, lo: 0x8a, hi: 0x8a}, + {value: 0x1984, lo: 0x8b, hi: 0x8b}, + {value: 0x199f, lo: 0x8c, hi: 0x8c}, + {value: 0x19a5, lo: 0x8d, hi: 0x8d}, + {value: 0x1bc3, lo: 0x8e, hi: 0x8e}, + {value: 0x19b1, lo: 0x8f, hi: 0x8f}, + {value: 0x197b, lo: 0xaa, hi: 0xaa}, + {value: 0x197e, lo: 0xab, hi: 0xab}, + {value: 0x1981, lo: 0xac, hi: 0xac}, + // Block 0xa2, offset 0x361 + {value: 0x0000, lo: 0x01}, + {value: 0x193f, lo: 0x90, hi: 0x90}, + // Block 0xa3, offset 0x363 + {value: 0x0028, lo: 0x09}, + {value: 0x2865, lo: 0x80, hi: 0x80}, + {value: 0x2829, lo: 0x81, hi: 0x81}, + {value: 0x2833, lo: 0x82, hi: 0x82}, + {value: 0x2847, lo: 0x83, hi: 0x84}, + {value: 0x2851, lo: 0x85, hi: 0x86}, + {value: 0x283d, lo: 0x87, hi: 0x87}, + {value: 0x285b, lo: 0x88, hi: 0x88}, + {value: 0x0b6f, lo: 0x90, hi: 0x90}, + {value: 0x08e7, lo: 0x91, hi: 0x91}, +} + +// recompMap: 7520 bytes (entries only) +var recompMap map[uint32]rune +var recompMapOnce sync.Once + +const recompMapPacked = "" + + "\x00A\x03\x00\x00\x00\x00\xc0" + // 0x00410300: 0x000000C0 + "\x00A\x03\x01\x00\x00\x00\xc1" + // 0x00410301: 0x000000C1 + "\x00A\x03\x02\x00\x00\x00\xc2" + // 0x00410302: 0x000000C2 + "\x00A\x03\x03\x00\x00\x00\xc3" + // 0x00410303: 0x000000C3 + "\x00A\x03\b\x00\x00\x00\xc4" + // 0x00410308: 0x000000C4 + "\x00A\x03\n\x00\x00\x00\xc5" + // 0x0041030A: 0x000000C5 + "\x00C\x03'\x00\x00\x00\xc7" + // 0x00430327: 0x000000C7 + "\x00E\x03\x00\x00\x00\x00\xc8" + // 0x00450300: 0x000000C8 + "\x00E\x03\x01\x00\x00\x00\xc9" + // 0x00450301: 0x000000C9 + "\x00E\x03\x02\x00\x00\x00\xca" + // 0x00450302: 0x000000CA + "\x00E\x03\b\x00\x00\x00\xcb" + // 0x00450308: 0x000000CB + "\x00I\x03\x00\x00\x00\x00\xcc" + // 0x00490300: 0x000000CC + "\x00I\x03\x01\x00\x00\x00\xcd" + // 0x00490301: 0x000000CD + "\x00I\x03\x02\x00\x00\x00\xce" + // 0x00490302: 0x000000CE + "\x00I\x03\b\x00\x00\x00\xcf" + // 0x00490308: 0x000000CF + "\x00N\x03\x03\x00\x00\x00\xd1" + // 0x004E0303: 0x000000D1 + "\x00O\x03\x00\x00\x00\x00\xd2" + // 0x004F0300: 0x000000D2 + "\x00O\x03\x01\x00\x00\x00\xd3" + // 0x004F0301: 0x000000D3 + "\x00O\x03\x02\x00\x00\x00\xd4" + // 0x004F0302: 0x000000D4 + "\x00O\x03\x03\x00\x00\x00\xd5" + // 0x004F0303: 0x000000D5 + "\x00O\x03\b\x00\x00\x00\xd6" + // 0x004F0308: 0x000000D6 + "\x00U\x03\x00\x00\x00\x00\xd9" + // 0x00550300: 0x000000D9 + "\x00U\x03\x01\x00\x00\x00\xda" + // 0x00550301: 0x000000DA + "\x00U\x03\x02\x00\x00\x00\xdb" + // 0x00550302: 0x000000DB + "\x00U\x03\b\x00\x00\x00\xdc" + // 0x00550308: 0x000000DC + "\x00Y\x03\x01\x00\x00\x00\xdd" + // 0x00590301: 0x000000DD + "\x00a\x03\x00\x00\x00\x00\xe0" + // 0x00610300: 0x000000E0 + "\x00a\x03\x01\x00\x00\x00\xe1" + // 0x00610301: 0x000000E1 + "\x00a\x03\x02\x00\x00\x00\xe2" + // 0x00610302: 0x000000E2 + "\x00a\x03\x03\x00\x00\x00\xe3" + // 0x00610303: 0x000000E3 + "\x00a\x03\b\x00\x00\x00\xe4" + // 0x00610308: 0x000000E4 + "\x00a\x03\n\x00\x00\x00\xe5" + // 0x0061030A: 0x000000E5 + "\x00c\x03'\x00\x00\x00\xe7" + // 0x00630327: 0x000000E7 + "\x00e\x03\x00\x00\x00\x00\xe8" + // 0x00650300: 0x000000E8 + "\x00e\x03\x01\x00\x00\x00\xe9" + // 0x00650301: 0x000000E9 + "\x00e\x03\x02\x00\x00\x00\xea" + // 0x00650302: 0x000000EA + "\x00e\x03\b\x00\x00\x00\xeb" + // 0x00650308: 0x000000EB + "\x00i\x03\x00\x00\x00\x00\xec" + // 0x00690300: 0x000000EC + "\x00i\x03\x01\x00\x00\x00\xed" + // 0x00690301: 0x000000ED + "\x00i\x03\x02\x00\x00\x00\xee" + // 0x00690302: 0x000000EE + "\x00i\x03\b\x00\x00\x00\xef" + // 0x00690308: 0x000000EF + "\x00n\x03\x03\x00\x00\x00\xf1" + // 0x006E0303: 0x000000F1 + "\x00o\x03\x00\x00\x00\x00\xf2" + // 0x006F0300: 0x000000F2 + "\x00o\x03\x01\x00\x00\x00\xf3" + // 0x006F0301: 0x000000F3 + "\x00o\x03\x02\x00\x00\x00\xf4" + // 0x006F0302: 0x000000F4 + "\x00o\x03\x03\x00\x00\x00\xf5" + // 0x006F0303: 0x000000F5 + "\x00o\x03\b\x00\x00\x00\xf6" + // 0x006F0308: 0x000000F6 + "\x00u\x03\x00\x00\x00\x00\xf9" + // 0x00750300: 0x000000F9 + "\x00u\x03\x01\x00\x00\x00\xfa" + // 0x00750301: 0x000000FA + "\x00u\x03\x02\x00\x00\x00\xfb" + // 0x00750302: 0x000000FB + "\x00u\x03\b\x00\x00\x00\xfc" + // 0x00750308: 0x000000FC + "\x00y\x03\x01\x00\x00\x00\xfd" + // 0x00790301: 0x000000FD + "\x00y\x03\b\x00\x00\x00\xff" + // 0x00790308: 0x000000FF + "\x00A\x03\x04\x00\x00\x01\x00" + // 0x00410304: 0x00000100 + "\x00a\x03\x04\x00\x00\x01\x01" + // 0x00610304: 0x00000101 + "\x00A\x03\x06\x00\x00\x01\x02" + // 0x00410306: 0x00000102 + "\x00a\x03\x06\x00\x00\x01\x03" + // 0x00610306: 0x00000103 + "\x00A\x03(\x00\x00\x01\x04" + // 0x00410328: 0x00000104 + "\x00a\x03(\x00\x00\x01\x05" + // 0x00610328: 0x00000105 + "\x00C\x03\x01\x00\x00\x01\x06" + // 0x00430301: 0x00000106 + "\x00c\x03\x01\x00\x00\x01\a" + // 0x00630301: 0x00000107 + "\x00C\x03\x02\x00\x00\x01\b" + // 0x00430302: 0x00000108 + "\x00c\x03\x02\x00\x00\x01\t" + // 0x00630302: 0x00000109 + "\x00C\x03\a\x00\x00\x01\n" + // 0x00430307: 0x0000010A + "\x00c\x03\a\x00\x00\x01\v" + // 0x00630307: 0x0000010B + "\x00C\x03\f\x00\x00\x01\f" + // 0x0043030C: 0x0000010C + "\x00c\x03\f\x00\x00\x01\r" + // 0x0063030C: 0x0000010D + "\x00D\x03\f\x00\x00\x01\x0e" + // 0x0044030C: 0x0000010E + "\x00d\x03\f\x00\x00\x01\x0f" + // 0x0064030C: 0x0000010F + "\x00E\x03\x04\x00\x00\x01\x12" + // 0x00450304: 0x00000112 + "\x00e\x03\x04\x00\x00\x01\x13" + // 0x00650304: 0x00000113 + "\x00E\x03\x06\x00\x00\x01\x14" + // 0x00450306: 0x00000114 + "\x00e\x03\x06\x00\x00\x01\x15" + // 0x00650306: 0x00000115 + "\x00E\x03\a\x00\x00\x01\x16" + // 0x00450307: 0x00000116 + "\x00e\x03\a\x00\x00\x01\x17" + // 0x00650307: 0x00000117 + "\x00E\x03(\x00\x00\x01\x18" + // 0x00450328: 0x00000118 + "\x00e\x03(\x00\x00\x01\x19" + // 0x00650328: 0x00000119 + "\x00E\x03\f\x00\x00\x01\x1a" + // 0x0045030C: 0x0000011A + "\x00e\x03\f\x00\x00\x01\x1b" + // 0x0065030C: 0x0000011B + "\x00G\x03\x02\x00\x00\x01\x1c" + // 0x00470302: 0x0000011C + "\x00g\x03\x02\x00\x00\x01\x1d" + // 0x00670302: 0x0000011D + "\x00G\x03\x06\x00\x00\x01\x1e" + // 0x00470306: 0x0000011E + "\x00g\x03\x06\x00\x00\x01\x1f" + // 0x00670306: 0x0000011F + "\x00G\x03\a\x00\x00\x01 " + // 0x00470307: 0x00000120 + "\x00g\x03\a\x00\x00\x01!" + // 0x00670307: 0x00000121 + "\x00G\x03'\x00\x00\x01\"" + // 0x00470327: 0x00000122 + "\x00g\x03'\x00\x00\x01#" + // 0x00670327: 0x00000123 + "\x00H\x03\x02\x00\x00\x01$" + // 0x00480302: 0x00000124 + "\x00h\x03\x02\x00\x00\x01%" + // 0x00680302: 0x00000125 + "\x00I\x03\x03\x00\x00\x01(" + // 0x00490303: 0x00000128 + "\x00i\x03\x03\x00\x00\x01)" + // 0x00690303: 0x00000129 + "\x00I\x03\x04\x00\x00\x01*" + // 0x00490304: 0x0000012A + "\x00i\x03\x04\x00\x00\x01+" + // 0x00690304: 0x0000012B + "\x00I\x03\x06\x00\x00\x01," + // 0x00490306: 0x0000012C + "\x00i\x03\x06\x00\x00\x01-" + // 0x00690306: 0x0000012D + "\x00I\x03(\x00\x00\x01." + // 0x00490328: 0x0000012E + "\x00i\x03(\x00\x00\x01/" + // 0x00690328: 0x0000012F + "\x00I\x03\a\x00\x00\x010" + // 0x00490307: 0x00000130 + "\x00J\x03\x02\x00\x00\x014" + // 0x004A0302: 0x00000134 + "\x00j\x03\x02\x00\x00\x015" + // 0x006A0302: 0x00000135 + "\x00K\x03'\x00\x00\x016" + // 0x004B0327: 0x00000136 + "\x00k\x03'\x00\x00\x017" + // 0x006B0327: 0x00000137 + "\x00L\x03\x01\x00\x00\x019" + // 0x004C0301: 0x00000139 + "\x00l\x03\x01\x00\x00\x01:" + // 0x006C0301: 0x0000013A + "\x00L\x03'\x00\x00\x01;" + // 0x004C0327: 0x0000013B + "\x00l\x03'\x00\x00\x01<" + // 0x006C0327: 0x0000013C + "\x00L\x03\f\x00\x00\x01=" + // 0x004C030C: 0x0000013D + "\x00l\x03\f\x00\x00\x01>" + // 0x006C030C: 0x0000013E + "\x00N\x03\x01\x00\x00\x01C" + // 0x004E0301: 0x00000143 + "\x00n\x03\x01\x00\x00\x01D" + // 0x006E0301: 0x00000144 + "\x00N\x03'\x00\x00\x01E" + // 0x004E0327: 0x00000145 + "\x00n\x03'\x00\x00\x01F" + // 0x006E0327: 0x00000146 + "\x00N\x03\f\x00\x00\x01G" + // 0x004E030C: 0x00000147 + "\x00n\x03\f\x00\x00\x01H" + // 0x006E030C: 0x00000148 + "\x00O\x03\x04\x00\x00\x01L" + // 0x004F0304: 0x0000014C + "\x00o\x03\x04\x00\x00\x01M" + // 0x006F0304: 0x0000014D + "\x00O\x03\x06\x00\x00\x01N" + // 0x004F0306: 0x0000014E + "\x00o\x03\x06\x00\x00\x01O" + // 0x006F0306: 0x0000014F + "\x00O\x03\v\x00\x00\x01P" + // 0x004F030B: 0x00000150 + "\x00o\x03\v\x00\x00\x01Q" + // 0x006F030B: 0x00000151 + "\x00R\x03\x01\x00\x00\x01T" + // 0x00520301: 0x00000154 + "\x00r\x03\x01\x00\x00\x01U" + // 0x00720301: 0x00000155 + "\x00R\x03'\x00\x00\x01V" + // 0x00520327: 0x00000156 + "\x00r\x03'\x00\x00\x01W" + // 0x00720327: 0x00000157 + "\x00R\x03\f\x00\x00\x01X" + // 0x0052030C: 0x00000158 + "\x00r\x03\f\x00\x00\x01Y" + // 0x0072030C: 0x00000159 + "\x00S\x03\x01\x00\x00\x01Z" + // 0x00530301: 0x0000015A + "\x00s\x03\x01\x00\x00\x01[" + // 0x00730301: 0x0000015B + "\x00S\x03\x02\x00\x00\x01\\" + // 0x00530302: 0x0000015C + "\x00s\x03\x02\x00\x00\x01]" + // 0x00730302: 0x0000015D + "\x00S\x03'\x00\x00\x01^" + // 0x00530327: 0x0000015E + "\x00s\x03'\x00\x00\x01_" + // 0x00730327: 0x0000015F + "\x00S\x03\f\x00\x00\x01`" + // 0x0053030C: 0x00000160 + "\x00s\x03\f\x00\x00\x01a" + // 0x0073030C: 0x00000161 + "\x00T\x03'\x00\x00\x01b" + // 0x00540327: 0x00000162 + "\x00t\x03'\x00\x00\x01c" + // 0x00740327: 0x00000163 + "\x00T\x03\f\x00\x00\x01d" + // 0x0054030C: 0x00000164 + "\x00t\x03\f\x00\x00\x01e" + // 0x0074030C: 0x00000165 + "\x00U\x03\x03\x00\x00\x01h" + // 0x00550303: 0x00000168 + "\x00u\x03\x03\x00\x00\x01i" + // 0x00750303: 0x00000169 + "\x00U\x03\x04\x00\x00\x01j" + // 0x00550304: 0x0000016A + "\x00u\x03\x04\x00\x00\x01k" + // 0x00750304: 0x0000016B + "\x00U\x03\x06\x00\x00\x01l" + // 0x00550306: 0x0000016C + "\x00u\x03\x06\x00\x00\x01m" + // 0x00750306: 0x0000016D + "\x00U\x03\n\x00\x00\x01n" + // 0x0055030A: 0x0000016E + "\x00u\x03\n\x00\x00\x01o" + // 0x0075030A: 0x0000016F + "\x00U\x03\v\x00\x00\x01p" + // 0x0055030B: 0x00000170 + "\x00u\x03\v\x00\x00\x01q" + // 0x0075030B: 0x00000171 + "\x00U\x03(\x00\x00\x01r" + // 0x00550328: 0x00000172 + "\x00u\x03(\x00\x00\x01s" + // 0x00750328: 0x00000173 + "\x00W\x03\x02\x00\x00\x01t" + // 0x00570302: 0x00000174 + "\x00w\x03\x02\x00\x00\x01u" + // 0x00770302: 0x00000175 + "\x00Y\x03\x02\x00\x00\x01v" + // 0x00590302: 0x00000176 + "\x00y\x03\x02\x00\x00\x01w" + // 0x00790302: 0x00000177 + "\x00Y\x03\b\x00\x00\x01x" + // 0x00590308: 0x00000178 + "\x00Z\x03\x01\x00\x00\x01y" + // 0x005A0301: 0x00000179 + "\x00z\x03\x01\x00\x00\x01z" + // 0x007A0301: 0x0000017A + "\x00Z\x03\a\x00\x00\x01{" + // 0x005A0307: 0x0000017B + "\x00z\x03\a\x00\x00\x01|" + // 0x007A0307: 0x0000017C + "\x00Z\x03\f\x00\x00\x01}" + // 0x005A030C: 0x0000017D + "\x00z\x03\f\x00\x00\x01~" + // 0x007A030C: 0x0000017E + "\x00O\x03\x1b\x00\x00\x01\xa0" + // 0x004F031B: 0x000001A0 + "\x00o\x03\x1b\x00\x00\x01\xa1" + // 0x006F031B: 0x000001A1 + "\x00U\x03\x1b\x00\x00\x01\xaf" + // 0x0055031B: 0x000001AF + "\x00u\x03\x1b\x00\x00\x01\xb0" + // 0x0075031B: 0x000001B0 + "\x00A\x03\f\x00\x00\x01\xcd" + // 0x0041030C: 0x000001CD + "\x00a\x03\f\x00\x00\x01\xce" + // 0x0061030C: 0x000001CE + "\x00I\x03\f\x00\x00\x01\xcf" + // 0x0049030C: 0x000001CF + "\x00i\x03\f\x00\x00\x01\xd0" + // 0x0069030C: 0x000001D0 + "\x00O\x03\f\x00\x00\x01\xd1" + // 0x004F030C: 0x000001D1 + "\x00o\x03\f\x00\x00\x01\xd2" + // 0x006F030C: 0x000001D2 + "\x00U\x03\f\x00\x00\x01\xd3" + // 0x0055030C: 0x000001D3 + "\x00u\x03\f\x00\x00\x01\xd4" + // 0x0075030C: 0x000001D4 + "\x00\xdc\x03\x04\x00\x00\x01\xd5" + // 0x00DC0304: 0x000001D5 + "\x00\xfc\x03\x04\x00\x00\x01\xd6" + // 0x00FC0304: 0x000001D6 + "\x00\xdc\x03\x01\x00\x00\x01\xd7" + // 0x00DC0301: 0x000001D7 + "\x00\xfc\x03\x01\x00\x00\x01\xd8" + // 0x00FC0301: 0x000001D8 + "\x00\xdc\x03\f\x00\x00\x01\xd9" + // 0x00DC030C: 0x000001D9 + "\x00\xfc\x03\f\x00\x00\x01\xda" + // 0x00FC030C: 0x000001DA + "\x00\xdc\x03\x00\x00\x00\x01\xdb" + // 0x00DC0300: 0x000001DB + "\x00\xfc\x03\x00\x00\x00\x01\xdc" + // 0x00FC0300: 0x000001DC + "\x00\xc4\x03\x04\x00\x00\x01\xde" + // 0x00C40304: 0x000001DE + "\x00\xe4\x03\x04\x00\x00\x01\xdf" + // 0x00E40304: 0x000001DF + "\x02&\x03\x04\x00\x00\x01\xe0" + // 0x02260304: 0x000001E0 + "\x02'\x03\x04\x00\x00\x01\xe1" + // 0x02270304: 0x000001E1 + "\x00\xc6\x03\x04\x00\x00\x01\xe2" + // 0x00C60304: 0x000001E2 + "\x00\xe6\x03\x04\x00\x00\x01\xe3" + // 0x00E60304: 0x000001E3 + "\x00G\x03\f\x00\x00\x01\xe6" + // 0x0047030C: 0x000001E6 + "\x00g\x03\f\x00\x00\x01\xe7" + // 0x0067030C: 0x000001E7 + "\x00K\x03\f\x00\x00\x01\xe8" + // 0x004B030C: 0x000001E8 + "\x00k\x03\f\x00\x00\x01\xe9" + // 0x006B030C: 0x000001E9 + "\x00O\x03(\x00\x00\x01\xea" + // 0x004F0328: 0x000001EA + "\x00o\x03(\x00\x00\x01\xeb" + // 0x006F0328: 0x000001EB + "\x01\xea\x03\x04\x00\x00\x01\xec" + // 0x01EA0304: 0x000001EC + "\x01\xeb\x03\x04\x00\x00\x01\xed" + // 0x01EB0304: 0x000001ED + "\x01\xb7\x03\f\x00\x00\x01\xee" + // 0x01B7030C: 0x000001EE + "\x02\x92\x03\f\x00\x00\x01\xef" + // 0x0292030C: 0x000001EF + "\x00j\x03\f\x00\x00\x01\xf0" + // 0x006A030C: 0x000001F0 + "\x00G\x03\x01\x00\x00\x01\xf4" + // 0x00470301: 0x000001F4 + "\x00g\x03\x01\x00\x00\x01\xf5" + // 0x00670301: 0x000001F5 + "\x00N\x03\x00\x00\x00\x01\xf8" + // 0x004E0300: 0x000001F8 + "\x00n\x03\x00\x00\x00\x01\xf9" + // 0x006E0300: 0x000001F9 + "\x00\xc5\x03\x01\x00\x00\x01\xfa" + // 0x00C50301: 0x000001FA + "\x00\xe5\x03\x01\x00\x00\x01\xfb" + // 0x00E50301: 0x000001FB + "\x00\xc6\x03\x01\x00\x00\x01\xfc" + // 0x00C60301: 0x000001FC + "\x00\xe6\x03\x01\x00\x00\x01\xfd" + // 0x00E60301: 0x000001FD + "\x00\xd8\x03\x01\x00\x00\x01\xfe" + // 0x00D80301: 0x000001FE + "\x00\xf8\x03\x01\x00\x00\x01\xff" + // 0x00F80301: 0x000001FF + "\x00A\x03\x0f\x00\x00\x02\x00" + // 0x0041030F: 0x00000200 + "\x00a\x03\x0f\x00\x00\x02\x01" + // 0x0061030F: 0x00000201 + "\x00A\x03\x11\x00\x00\x02\x02" + // 0x00410311: 0x00000202 + "\x00a\x03\x11\x00\x00\x02\x03" + // 0x00610311: 0x00000203 + "\x00E\x03\x0f\x00\x00\x02\x04" + // 0x0045030F: 0x00000204 + "\x00e\x03\x0f\x00\x00\x02\x05" + // 0x0065030F: 0x00000205 + "\x00E\x03\x11\x00\x00\x02\x06" + // 0x00450311: 0x00000206 + "\x00e\x03\x11\x00\x00\x02\a" + // 0x00650311: 0x00000207 + "\x00I\x03\x0f\x00\x00\x02\b" + // 0x0049030F: 0x00000208 + "\x00i\x03\x0f\x00\x00\x02\t" + // 0x0069030F: 0x00000209 + "\x00I\x03\x11\x00\x00\x02\n" + // 0x00490311: 0x0000020A + "\x00i\x03\x11\x00\x00\x02\v" + // 0x00690311: 0x0000020B + "\x00O\x03\x0f\x00\x00\x02\f" + // 0x004F030F: 0x0000020C + "\x00o\x03\x0f\x00\x00\x02\r" + // 0x006F030F: 0x0000020D + "\x00O\x03\x11\x00\x00\x02\x0e" + // 0x004F0311: 0x0000020E + "\x00o\x03\x11\x00\x00\x02\x0f" + // 0x006F0311: 0x0000020F + "\x00R\x03\x0f\x00\x00\x02\x10" + // 0x0052030F: 0x00000210 + "\x00r\x03\x0f\x00\x00\x02\x11" + // 0x0072030F: 0x00000211 + "\x00R\x03\x11\x00\x00\x02\x12" + // 0x00520311: 0x00000212 + "\x00r\x03\x11\x00\x00\x02\x13" + // 0x00720311: 0x00000213 + "\x00U\x03\x0f\x00\x00\x02\x14" + // 0x0055030F: 0x00000214 + "\x00u\x03\x0f\x00\x00\x02\x15" + // 0x0075030F: 0x00000215 + "\x00U\x03\x11\x00\x00\x02\x16" + // 0x00550311: 0x00000216 + "\x00u\x03\x11\x00\x00\x02\x17" + // 0x00750311: 0x00000217 + "\x00S\x03&\x00\x00\x02\x18" + // 0x00530326: 0x00000218 + "\x00s\x03&\x00\x00\x02\x19" + // 0x00730326: 0x00000219 + "\x00T\x03&\x00\x00\x02\x1a" + // 0x00540326: 0x0000021A + "\x00t\x03&\x00\x00\x02\x1b" + // 0x00740326: 0x0000021B + "\x00H\x03\f\x00\x00\x02\x1e" + // 0x0048030C: 0x0000021E + "\x00h\x03\f\x00\x00\x02\x1f" + // 0x0068030C: 0x0000021F + "\x00A\x03\a\x00\x00\x02&" + // 0x00410307: 0x00000226 + "\x00a\x03\a\x00\x00\x02'" + // 0x00610307: 0x00000227 + "\x00E\x03'\x00\x00\x02(" + // 0x00450327: 0x00000228 + "\x00e\x03'\x00\x00\x02)" + // 0x00650327: 0x00000229 + "\x00\xd6\x03\x04\x00\x00\x02*" + // 0x00D60304: 0x0000022A + "\x00\xf6\x03\x04\x00\x00\x02+" + // 0x00F60304: 0x0000022B + "\x00\xd5\x03\x04\x00\x00\x02," + // 0x00D50304: 0x0000022C + "\x00\xf5\x03\x04\x00\x00\x02-" + // 0x00F50304: 0x0000022D + "\x00O\x03\a\x00\x00\x02." + // 0x004F0307: 0x0000022E + "\x00o\x03\a\x00\x00\x02/" + // 0x006F0307: 0x0000022F + "\x02.\x03\x04\x00\x00\x020" + // 0x022E0304: 0x00000230 + "\x02/\x03\x04\x00\x00\x021" + // 0x022F0304: 0x00000231 + "\x00Y\x03\x04\x00\x00\x022" + // 0x00590304: 0x00000232 + "\x00y\x03\x04\x00\x00\x023" + // 0x00790304: 0x00000233 + "\x00\xa8\x03\x01\x00\x00\x03\x85" + // 0x00A80301: 0x00000385 + "\x03\x91\x03\x01\x00\x00\x03\x86" + // 0x03910301: 0x00000386 + "\x03\x95\x03\x01\x00\x00\x03\x88" + // 0x03950301: 0x00000388 + "\x03\x97\x03\x01\x00\x00\x03\x89" + // 0x03970301: 0x00000389 + "\x03\x99\x03\x01\x00\x00\x03\x8a" + // 0x03990301: 0x0000038A + "\x03\x9f\x03\x01\x00\x00\x03\x8c" + // 0x039F0301: 0x0000038C + "\x03\xa5\x03\x01\x00\x00\x03\x8e" + // 0x03A50301: 0x0000038E + "\x03\xa9\x03\x01\x00\x00\x03\x8f" + // 0x03A90301: 0x0000038F + "\x03\xca\x03\x01\x00\x00\x03\x90" + // 0x03CA0301: 0x00000390 + "\x03\x99\x03\b\x00\x00\x03\xaa" + // 0x03990308: 0x000003AA + "\x03\xa5\x03\b\x00\x00\x03\xab" + // 0x03A50308: 0x000003AB + "\x03\xb1\x03\x01\x00\x00\x03\xac" + // 0x03B10301: 0x000003AC + "\x03\xb5\x03\x01\x00\x00\x03\xad" + // 0x03B50301: 0x000003AD + "\x03\xb7\x03\x01\x00\x00\x03\xae" + // 0x03B70301: 0x000003AE + "\x03\xb9\x03\x01\x00\x00\x03\xaf" + // 0x03B90301: 0x000003AF + "\x03\xcb\x03\x01\x00\x00\x03\xb0" + // 0x03CB0301: 0x000003B0 + "\x03\xb9\x03\b\x00\x00\x03\xca" + // 0x03B90308: 0x000003CA + "\x03\xc5\x03\b\x00\x00\x03\xcb" + // 0x03C50308: 0x000003CB + "\x03\xbf\x03\x01\x00\x00\x03\xcc" + // 0x03BF0301: 0x000003CC + "\x03\xc5\x03\x01\x00\x00\x03\xcd" + // 0x03C50301: 0x000003CD + "\x03\xc9\x03\x01\x00\x00\x03\xce" + // 0x03C90301: 0x000003CE + "\x03\xd2\x03\x01\x00\x00\x03\xd3" + // 0x03D20301: 0x000003D3 + "\x03\xd2\x03\b\x00\x00\x03\xd4" + // 0x03D20308: 0x000003D4 + "\x04\x15\x03\x00\x00\x00\x04\x00" + // 0x04150300: 0x00000400 + "\x04\x15\x03\b\x00\x00\x04\x01" + // 0x04150308: 0x00000401 + "\x04\x13\x03\x01\x00\x00\x04\x03" + // 0x04130301: 0x00000403 + "\x04\x06\x03\b\x00\x00\x04\a" + // 0x04060308: 0x00000407 + "\x04\x1a\x03\x01\x00\x00\x04\f" + // 0x041A0301: 0x0000040C + "\x04\x18\x03\x00\x00\x00\x04\r" + // 0x04180300: 0x0000040D + "\x04#\x03\x06\x00\x00\x04\x0e" + // 0x04230306: 0x0000040E + "\x04\x18\x03\x06\x00\x00\x04\x19" + // 0x04180306: 0x00000419 + "\x048\x03\x06\x00\x00\x049" + // 0x04380306: 0x00000439 + "\x045\x03\x00\x00\x00\x04P" + // 0x04350300: 0x00000450 + "\x045\x03\b\x00\x00\x04Q" + // 0x04350308: 0x00000451 + "\x043\x03\x01\x00\x00\x04S" + // 0x04330301: 0x00000453 + "\x04V\x03\b\x00\x00\x04W" + // 0x04560308: 0x00000457 + "\x04:\x03\x01\x00\x00\x04\\" + // 0x043A0301: 0x0000045C + "\x048\x03\x00\x00\x00\x04]" + // 0x04380300: 0x0000045D + "\x04C\x03\x06\x00\x00\x04^" + // 0x04430306: 0x0000045E + "\x04t\x03\x0f\x00\x00\x04v" + // 0x0474030F: 0x00000476 + "\x04u\x03\x0f\x00\x00\x04w" + // 0x0475030F: 0x00000477 + "\x04\x16\x03\x06\x00\x00\x04\xc1" + // 0x04160306: 0x000004C1 + "\x046\x03\x06\x00\x00\x04\xc2" + // 0x04360306: 0x000004C2 + "\x04\x10\x03\x06\x00\x00\x04\xd0" + // 0x04100306: 0x000004D0 + "\x040\x03\x06\x00\x00\x04\xd1" + // 0x04300306: 0x000004D1 + "\x04\x10\x03\b\x00\x00\x04\xd2" + // 0x04100308: 0x000004D2 + "\x040\x03\b\x00\x00\x04\xd3" + // 0x04300308: 0x000004D3 + "\x04\x15\x03\x06\x00\x00\x04\xd6" + // 0x04150306: 0x000004D6 + "\x045\x03\x06\x00\x00\x04\xd7" + // 0x04350306: 0x000004D7 + "\x04\xd8\x03\b\x00\x00\x04\xda" + // 0x04D80308: 0x000004DA + "\x04\xd9\x03\b\x00\x00\x04\xdb" + // 0x04D90308: 0x000004DB + "\x04\x16\x03\b\x00\x00\x04\xdc" + // 0x04160308: 0x000004DC + "\x046\x03\b\x00\x00\x04\xdd" + // 0x04360308: 0x000004DD + "\x04\x17\x03\b\x00\x00\x04\xde" + // 0x04170308: 0x000004DE + "\x047\x03\b\x00\x00\x04\xdf" + // 0x04370308: 0x000004DF + "\x04\x18\x03\x04\x00\x00\x04\xe2" + // 0x04180304: 0x000004E2 + "\x048\x03\x04\x00\x00\x04\xe3" + // 0x04380304: 0x000004E3 + "\x04\x18\x03\b\x00\x00\x04\xe4" + // 0x04180308: 0x000004E4 + "\x048\x03\b\x00\x00\x04\xe5" + // 0x04380308: 0x000004E5 + "\x04\x1e\x03\b\x00\x00\x04\xe6" + // 0x041E0308: 0x000004E6 + "\x04>\x03\b\x00\x00\x04\xe7" + // 0x043E0308: 0x000004E7 + "\x04\xe8\x03\b\x00\x00\x04\xea" + // 0x04E80308: 0x000004EA + "\x04\xe9\x03\b\x00\x00\x04\xeb" + // 0x04E90308: 0x000004EB + "\x04-\x03\b\x00\x00\x04\xec" + // 0x042D0308: 0x000004EC + "\x04M\x03\b\x00\x00\x04\xed" + // 0x044D0308: 0x000004ED + "\x04#\x03\x04\x00\x00\x04\xee" + // 0x04230304: 0x000004EE + "\x04C\x03\x04\x00\x00\x04\xef" + // 0x04430304: 0x000004EF + "\x04#\x03\b\x00\x00\x04\xf0" + // 0x04230308: 0x000004F0 + "\x04C\x03\b\x00\x00\x04\xf1" + // 0x04430308: 0x000004F1 + "\x04#\x03\v\x00\x00\x04\xf2" + // 0x0423030B: 0x000004F2 + "\x04C\x03\v\x00\x00\x04\xf3" + // 0x0443030B: 0x000004F3 + "\x04'\x03\b\x00\x00\x04\xf4" + // 0x04270308: 0x000004F4 + "\x04G\x03\b\x00\x00\x04\xf5" + // 0x04470308: 0x000004F5 + "\x04+\x03\b\x00\x00\x04\xf8" + // 0x042B0308: 0x000004F8 + "\x04K\x03\b\x00\x00\x04\xf9" + // 0x044B0308: 0x000004F9 + "\x06'\x06S\x00\x00\x06\"" + // 0x06270653: 0x00000622 + "\x06'\x06T\x00\x00\x06#" + // 0x06270654: 0x00000623 + "\x06H\x06T\x00\x00\x06$" + // 0x06480654: 0x00000624 + "\x06'\x06U\x00\x00\x06%" + // 0x06270655: 0x00000625 + "\x06J\x06T\x00\x00\x06&" + // 0x064A0654: 0x00000626 + "\x06\xd5\x06T\x00\x00\x06\xc0" + // 0x06D50654: 0x000006C0 + "\x06\xc1\x06T\x00\x00\x06\xc2" + // 0x06C10654: 0x000006C2 + "\x06\xd2\x06T\x00\x00\x06\xd3" + // 0x06D20654: 0x000006D3 + "\t(\t<\x00\x00\t)" + // 0x0928093C: 0x00000929 + "\t0\t<\x00\x00\t1" + // 0x0930093C: 0x00000931 + "\t3\t<\x00\x00\t4" + // 0x0933093C: 0x00000934 + "\t\xc7\t\xbe\x00\x00\t\xcb" + // 0x09C709BE: 0x000009CB + "\t\xc7\t\xd7\x00\x00\t\xcc" + // 0x09C709D7: 0x000009CC + "\vG\vV\x00\x00\vH" + // 0x0B470B56: 0x00000B48 + "\vG\v>\x00\x00\vK" + // 0x0B470B3E: 0x00000B4B + "\vG\vW\x00\x00\vL" + // 0x0B470B57: 0x00000B4C + "\v\x92\v\xd7\x00\x00\v\x94" + // 0x0B920BD7: 0x00000B94 + "\v\xc6\v\xbe\x00\x00\v\xca" + // 0x0BC60BBE: 0x00000BCA + "\v\xc7\v\xbe\x00\x00\v\xcb" + // 0x0BC70BBE: 0x00000BCB + "\v\xc6\v\xd7\x00\x00\v\xcc" + // 0x0BC60BD7: 0x00000BCC + "\fF\fV\x00\x00\fH" + // 0x0C460C56: 0x00000C48 + "\f\xbf\f\xd5\x00\x00\f\xc0" + // 0x0CBF0CD5: 0x00000CC0 + "\f\xc6\f\xd5\x00\x00\f\xc7" + // 0x0CC60CD5: 0x00000CC7 + "\f\xc6\f\xd6\x00\x00\f\xc8" + // 0x0CC60CD6: 0x00000CC8 + "\f\xc6\f\xc2\x00\x00\f\xca" + // 0x0CC60CC2: 0x00000CCA + "\f\xca\f\xd5\x00\x00\f\xcb" + // 0x0CCA0CD5: 0x00000CCB + "\rF\r>\x00\x00\rJ" + // 0x0D460D3E: 0x00000D4A + "\rG\r>\x00\x00\rK" + // 0x0D470D3E: 0x00000D4B + "\rF\rW\x00\x00\rL" + // 0x0D460D57: 0x00000D4C + "\r\xd9\r\xca\x00\x00\r\xda" + // 0x0DD90DCA: 0x00000DDA + "\r\xd9\r\xcf\x00\x00\r\xdc" + // 0x0DD90DCF: 0x00000DDC + "\r\xdc\r\xca\x00\x00\r\xdd" + // 0x0DDC0DCA: 0x00000DDD + "\r\xd9\r\xdf\x00\x00\r\xde" + // 0x0DD90DDF: 0x00000DDE + "\x10%\x10.\x00\x00\x10&" + // 0x1025102E: 0x00001026 + "\x1b\x05\x1b5\x00\x00\x1b\x06" + // 0x1B051B35: 0x00001B06 + "\x1b\a\x1b5\x00\x00\x1b\b" + // 0x1B071B35: 0x00001B08 + "\x1b\t\x1b5\x00\x00\x1b\n" + // 0x1B091B35: 0x00001B0A + "\x1b\v\x1b5\x00\x00\x1b\f" + // 0x1B0B1B35: 0x00001B0C + "\x1b\r\x1b5\x00\x00\x1b\x0e" + // 0x1B0D1B35: 0x00001B0E + "\x1b\x11\x1b5\x00\x00\x1b\x12" + // 0x1B111B35: 0x00001B12 + "\x1b:\x1b5\x00\x00\x1b;" + // 0x1B3A1B35: 0x00001B3B + "\x1b<\x1b5\x00\x00\x1b=" + // 0x1B3C1B35: 0x00001B3D + "\x1b>\x1b5\x00\x00\x1b@" + // 0x1B3E1B35: 0x00001B40 + "\x1b?\x1b5\x00\x00\x1bA" + // 0x1B3F1B35: 0x00001B41 + "\x1bB\x1b5\x00\x00\x1bC" + // 0x1B421B35: 0x00001B43 + "\x00A\x03%\x00\x00\x1e\x00" + // 0x00410325: 0x00001E00 + "\x00a\x03%\x00\x00\x1e\x01" + // 0x00610325: 0x00001E01 + "\x00B\x03\a\x00\x00\x1e\x02" + // 0x00420307: 0x00001E02 + "\x00b\x03\a\x00\x00\x1e\x03" + // 0x00620307: 0x00001E03 + "\x00B\x03#\x00\x00\x1e\x04" + // 0x00420323: 0x00001E04 + "\x00b\x03#\x00\x00\x1e\x05" + // 0x00620323: 0x00001E05 + "\x00B\x031\x00\x00\x1e\x06" + // 0x00420331: 0x00001E06 + "\x00b\x031\x00\x00\x1e\a" + // 0x00620331: 0x00001E07 + "\x00\xc7\x03\x01\x00\x00\x1e\b" + // 0x00C70301: 0x00001E08 + "\x00\xe7\x03\x01\x00\x00\x1e\t" + // 0x00E70301: 0x00001E09 + "\x00D\x03\a\x00\x00\x1e\n" + // 0x00440307: 0x00001E0A + "\x00d\x03\a\x00\x00\x1e\v" + // 0x00640307: 0x00001E0B + "\x00D\x03#\x00\x00\x1e\f" + // 0x00440323: 0x00001E0C + "\x00d\x03#\x00\x00\x1e\r" + // 0x00640323: 0x00001E0D + "\x00D\x031\x00\x00\x1e\x0e" + // 0x00440331: 0x00001E0E + "\x00d\x031\x00\x00\x1e\x0f" + // 0x00640331: 0x00001E0F + "\x00D\x03'\x00\x00\x1e\x10" + // 0x00440327: 0x00001E10 + "\x00d\x03'\x00\x00\x1e\x11" + // 0x00640327: 0x00001E11 + "\x00D\x03-\x00\x00\x1e\x12" + // 0x0044032D: 0x00001E12 + "\x00d\x03-\x00\x00\x1e\x13" + // 0x0064032D: 0x00001E13 + "\x01\x12\x03\x00\x00\x00\x1e\x14" + // 0x01120300: 0x00001E14 + "\x01\x13\x03\x00\x00\x00\x1e\x15" + // 0x01130300: 0x00001E15 + "\x01\x12\x03\x01\x00\x00\x1e\x16" + // 0x01120301: 0x00001E16 + "\x01\x13\x03\x01\x00\x00\x1e\x17" + // 0x01130301: 0x00001E17 + "\x00E\x03-\x00\x00\x1e\x18" + // 0x0045032D: 0x00001E18 + "\x00e\x03-\x00\x00\x1e\x19" + // 0x0065032D: 0x00001E19 + "\x00E\x030\x00\x00\x1e\x1a" + // 0x00450330: 0x00001E1A + "\x00e\x030\x00\x00\x1e\x1b" + // 0x00650330: 0x00001E1B + "\x02(\x03\x06\x00\x00\x1e\x1c" + // 0x02280306: 0x00001E1C + "\x02)\x03\x06\x00\x00\x1e\x1d" + // 0x02290306: 0x00001E1D + "\x00F\x03\a\x00\x00\x1e\x1e" + // 0x00460307: 0x00001E1E + "\x00f\x03\a\x00\x00\x1e\x1f" + // 0x00660307: 0x00001E1F + "\x00G\x03\x04\x00\x00\x1e " + // 0x00470304: 0x00001E20 + "\x00g\x03\x04\x00\x00\x1e!" + // 0x00670304: 0x00001E21 + "\x00H\x03\a\x00\x00\x1e\"" + // 0x00480307: 0x00001E22 + "\x00h\x03\a\x00\x00\x1e#" + // 0x00680307: 0x00001E23 + "\x00H\x03#\x00\x00\x1e$" + // 0x00480323: 0x00001E24 + "\x00h\x03#\x00\x00\x1e%" + // 0x00680323: 0x00001E25 + "\x00H\x03\b\x00\x00\x1e&" + // 0x00480308: 0x00001E26 + "\x00h\x03\b\x00\x00\x1e'" + // 0x00680308: 0x00001E27 + "\x00H\x03'\x00\x00\x1e(" + // 0x00480327: 0x00001E28 + "\x00h\x03'\x00\x00\x1e)" + // 0x00680327: 0x00001E29 + "\x00H\x03.\x00\x00\x1e*" + // 0x0048032E: 0x00001E2A + "\x00h\x03.\x00\x00\x1e+" + // 0x0068032E: 0x00001E2B + "\x00I\x030\x00\x00\x1e," + // 0x00490330: 0x00001E2C + "\x00i\x030\x00\x00\x1e-" + // 0x00690330: 0x00001E2D + "\x00\xcf\x03\x01\x00\x00\x1e." + // 0x00CF0301: 0x00001E2E + "\x00\xef\x03\x01\x00\x00\x1e/" + // 0x00EF0301: 0x00001E2F + "\x00K\x03\x01\x00\x00\x1e0" + // 0x004B0301: 0x00001E30 + "\x00k\x03\x01\x00\x00\x1e1" + // 0x006B0301: 0x00001E31 + "\x00K\x03#\x00\x00\x1e2" + // 0x004B0323: 0x00001E32 + "\x00k\x03#\x00\x00\x1e3" + // 0x006B0323: 0x00001E33 + "\x00K\x031\x00\x00\x1e4" + // 0x004B0331: 0x00001E34 + "\x00k\x031\x00\x00\x1e5" + // 0x006B0331: 0x00001E35 + "\x00L\x03#\x00\x00\x1e6" + // 0x004C0323: 0x00001E36 + "\x00l\x03#\x00\x00\x1e7" + // 0x006C0323: 0x00001E37 + "\x1e6\x03\x04\x00\x00\x1e8" + // 0x1E360304: 0x00001E38 + "\x1e7\x03\x04\x00\x00\x1e9" + // 0x1E370304: 0x00001E39 + "\x00L\x031\x00\x00\x1e:" + // 0x004C0331: 0x00001E3A + "\x00l\x031\x00\x00\x1e;" + // 0x006C0331: 0x00001E3B + "\x00L\x03-\x00\x00\x1e<" + // 0x004C032D: 0x00001E3C + "\x00l\x03-\x00\x00\x1e=" + // 0x006C032D: 0x00001E3D + "\x00M\x03\x01\x00\x00\x1e>" + // 0x004D0301: 0x00001E3E + "\x00m\x03\x01\x00\x00\x1e?" + // 0x006D0301: 0x00001E3F + "\x00M\x03\a\x00\x00\x1e@" + // 0x004D0307: 0x00001E40 + "\x00m\x03\a\x00\x00\x1eA" + // 0x006D0307: 0x00001E41 + "\x00M\x03#\x00\x00\x1eB" + // 0x004D0323: 0x00001E42 + "\x00m\x03#\x00\x00\x1eC" + // 0x006D0323: 0x00001E43 + "\x00N\x03\a\x00\x00\x1eD" + // 0x004E0307: 0x00001E44 + "\x00n\x03\a\x00\x00\x1eE" + // 0x006E0307: 0x00001E45 + "\x00N\x03#\x00\x00\x1eF" + // 0x004E0323: 0x00001E46 + "\x00n\x03#\x00\x00\x1eG" + // 0x006E0323: 0x00001E47 + "\x00N\x031\x00\x00\x1eH" + // 0x004E0331: 0x00001E48 + "\x00n\x031\x00\x00\x1eI" + // 0x006E0331: 0x00001E49 + "\x00N\x03-\x00\x00\x1eJ" + // 0x004E032D: 0x00001E4A + "\x00n\x03-\x00\x00\x1eK" + // 0x006E032D: 0x00001E4B + "\x00\xd5\x03\x01\x00\x00\x1eL" + // 0x00D50301: 0x00001E4C + "\x00\xf5\x03\x01\x00\x00\x1eM" + // 0x00F50301: 0x00001E4D + "\x00\xd5\x03\b\x00\x00\x1eN" + // 0x00D50308: 0x00001E4E + "\x00\xf5\x03\b\x00\x00\x1eO" + // 0x00F50308: 0x00001E4F + "\x01L\x03\x00\x00\x00\x1eP" + // 0x014C0300: 0x00001E50 + "\x01M\x03\x00\x00\x00\x1eQ" + // 0x014D0300: 0x00001E51 + "\x01L\x03\x01\x00\x00\x1eR" + // 0x014C0301: 0x00001E52 + "\x01M\x03\x01\x00\x00\x1eS" + // 0x014D0301: 0x00001E53 + "\x00P\x03\x01\x00\x00\x1eT" + // 0x00500301: 0x00001E54 + "\x00p\x03\x01\x00\x00\x1eU" + // 0x00700301: 0x00001E55 + "\x00P\x03\a\x00\x00\x1eV" + // 0x00500307: 0x00001E56 + "\x00p\x03\a\x00\x00\x1eW" + // 0x00700307: 0x00001E57 + "\x00R\x03\a\x00\x00\x1eX" + // 0x00520307: 0x00001E58 + "\x00r\x03\a\x00\x00\x1eY" + // 0x00720307: 0x00001E59 + "\x00R\x03#\x00\x00\x1eZ" + // 0x00520323: 0x00001E5A + "\x00r\x03#\x00\x00\x1e[" + // 0x00720323: 0x00001E5B + "\x1eZ\x03\x04\x00\x00\x1e\\" + // 0x1E5A0304: 0x00001E5C + "\x1e[\x03\x04\x00\x00\x1e]" + // 0x1E5B0304: 0x00001E5D + "\x00R\x031\x00\x00\x1e^" + // 0x00520331: 0x00001E5E + "\x00r\x031\x00\x00\x1e_" + // 0x00720331: 0x00001E5F + "\x00S\x03\a\x00\x00\x1e`" + // 0x00530307: 0x00001E60 + "\x00s\x03\a\x00\x00\x1ea" + // 0x00730307: 0x00001E61 + "\x00S\x03#\x00\x00\x1eb" + // 0x00530323: 0x00001E62 + "\x00s\x03#\x00\x00\x1ec" + // 0x00730323: 0x00001E63 + "\x01Z\x03\a\x00\x00\x1ed" + // 0x015A0307: 0x00001E64 + "\x01[\x03\a\x00\x00\x1ee" + // 0x015B0307: 0x00001E65 + "\x01`\x03\a\x00\x00\x1ef" + // 0x01600307: 0x00001E66 + "\x01a\x03\a\x00\x00\x1eg" + // 0x01610307: 0x00001E67 + "\x1eb\x03\a\x00\x00\x1eh" + // 0x1E620307: 0x00001E68 + "\x1ec\x03\a\x00\x00\x1ei" + // 0x1E630307: 0x00001E69 + "\x00T\x03\a\x00\x00\x1ej" + // 0x00540307: 0x00001E6A + "\x00t\x03\a\x00\x00\x1ek" + // 0x00740307: 0x00001E6B + "\x00T\x03#\x00\x00\x1el" + // 0x00540323: 0x00001E6C + "\x00t\x03#\x00\x00\x1em" + // 0x00740323: 0x00001E6D + "\x00T\x031\x00\x00\x1en" + // 0x00540331: 0x00001E6E + "\x00t\x031\x00\x00\x1eo" + // 0x00740331: 0x00001E6F + "\x00T\x03-\x00\x00\x1ep" + // 0x0054032D: 0x00001E70 + "\x00t\x03-\x00\x00\x1eq" + // 0x0074032D: 0x00001E71 + "\x00U\x03$\x00\x00\x1er" + // 0x00550324: 0x00001E72 + "\x00u\x03$\x00\x00\x1es" + // 0x00750324: 0x00001E73 + "\x00U\x030\x00\x00\x1et" + // 0x00550330: 0x00001E74 + "\x00u\x030\x00\x00\x1eu" + // 0x00750330: 0x00001E75 + "\x00U\x03-\x00\x00\x1ev" + // 0x0055032D: 0x00001E76 + "\x00u\x03-\x00\x00\x1ew" + // 0x0075032D: 0x00001E77 + "\x01h\x03\x01\x00\x00\x1ex" + // 0x01680301: 0x00001E78 + "\x01i\x03\x01\x00\x00\x1ey" + // 0x01690301: 0x00001E79 + "\x01j\x03\b\x00\x00\x1ez" + // 0x016A0308: 0x00001E7A + "\x01k\x03\b\x00\x00\x1e{" + // 0x016B0308: 0x00001E7B + "\x00V\x03\x03\x00\x00\x1e|" + // 0x00560303: 0x00001E7C + "\x00v\x03\x03\x00\x00\x1e}" + // 0x00760303: 0x00001E7D + "\x00V\x03#\x00\x00\x1e~" + // 0x00560323: 0x00001E7E + "\x00v\x03#\x00\x00\x1e\u007f" + // 0x00760323: 0x00001E7F + "\x00W\x03\x00\x00\x00\x1e\x80" + // 0x00570300: 0x00001E80 + "\x00w\x03\x00\x00\x00\x1e\x81" + // 0x00770300: 0x00001E81 + "\x00W\x03\x01\x00\x00\x1e\x82" + // 0x00570301: 0x00001E82 + "\x00w\x03\x01\x00\x00\x1e\x83" + // 0x00770301: 0x00001E83 + "\x00W\x03\b\x00\x00\x1e\x84" + // 0x00570308: 0x00001E84 + "\x00w\x03\b\x00\x00\x1e\x85" + // 0x00770308: 0x00001E85 + "\x00W\x03\a\x00\x00\x1e\x86" + // 0x00570307: 0x00001E86 + "\x00w\x03\a\x00\x00\x1e\x87" + // 0x00770307: 0x00001E87 + "\x00W\x03#\x00\x00\x1e\x88" + // 0x00570323: 0x00001E88 + "\x00w\x03#\x00\x00\x1e\x89" + // 0x00770323: 0x00001E89 + "\x00X\x03\a\x00\x00\x1e\x8a" + // 0x00580307: 0x00001E8A + "\x00x\x03\a\x00\x00\x1e\x8b" + // 0x00780307: 0x00001E8B + "\x00X\x03\b\x00\x00\x1e\x8c" + // 0x00580308: 0x00001E8C + "\x00x\x03\b\x00\x00\x1e\x8d" + // 0x00780308: 0x00001E8D + "\x00Y\x03\a\x00\x00\x1e\x8e" + // 0x00590307: 0x00001E8E + "\x00y\x03\a\x00\x00\x1e\x8f" + // 0x00790307: 0x00001E8F + "\x00Z\x03\x02\x00\x00\x1e\x90" + // 0x005A0302: 0x00001E90 + "\x00z\x03\x02\x00\x00\x1e\x91" + // 0x007A0302: 0x00001E91 + "\x00Z\x03#\x00\x00\x1e\x92" + // 0x005A0323: 0x00001E92 + "\x00z\x03#\x00\x00\x1e\x93" + // 0x007A0323: 0x00001E93 + "\x00Z\x031\x00\x00\x1e\x94" + // 0x005A0331: 0x00001E94 + "\x00z\x031\x00\x00\x1e\x95" + // 0x007A0331: 0x00001E95 + "\x00h\x031\x00\x00\x1e\x96" + // 0x00680331: 0x00001E96 + "\x00t\x03\b\x00\x00\x1e\x97" + // 0x00740308: 0x00001E97 + "\x00w\x03\n\x00\x00\x1e\x98" + // 0x0077030A: 0x00001E98 + "\x00y\x03\n\x00\x00\x1e\x99" + // 0x0079030A: 0x00001E99 + "\x01\u007f\x03\a\x00\x00\x1e\x9b" + // 0x017F0307: 0x00001E9B + "\x00A\x03#\x00\x00\x1e\xa0" + // 0x00410323: 0x00001EA0 + "\x00a\x03#\x00\x00\x1e\xa1" + // 0x00610323: 0x00001EA1 + "\x00A\x03\t\x00\x00\x1e\xa2" + // 0x00410309: 0x00001EA2 + "\x00a\x03\t\x00\x00\x1e\xa3" + // 0x00610309: 0x00001EA3 + "\x00\xc2\x03\x01\x00\x00\x1e\xa4" + // 0x00C20301: 0x00001EA4 + "\x00\xe2\x03\x01\x00\x00\x1e\xa5" + // 0x00E20301: 0x00001EA5 + "\x00\xc2\x03\x00\x00\x00\x1e\xa6" + // 0x00C20300: 0x00001EA6 + "\x00\xe2\x03\x00\x00\x00\x1e\xa7" + // 0x00E20300: 0x00001EA7 + "\x00\xc2\x03\t\x00\x00\x1e\xa8" + // 0x00C20309: 0x00001EA8 + "\x00\xe2\x03\t\x00\x00\x1e\xa9" + // 0x00E20309: 0x00001EA9 + "\x00\xc2\x03\x03\x00\x00\x1e\xaa" + // 0x00C20303: 0x00001EAA + "\x00\xe2\x03\x03\x00\x00\x1e\xab" + // 0x00E20303: 0x00001EAB + "\x1e\xa0\x03\x02\x00\x00\x1e\xac" + // 0x1EA00302: 0x00001EAC + "\x1e\xa1\x03\x02\x00\x00\x1e\xad" + // 0x1EA10302: 0x00001EAD + "\x01\x02\x03\x01\x00\x00\x1e\xae" + // 0x01020301: 0x00001EAE + "\x01\x03\x03\x01\x00\x00\x1e\xaf" + // 0x01030301: 0x00001EAF + "\x01\x02\x03\x00\x00\x00\x1e\xb0" + // 0x01020300: 0x00001EB0 + "\x01\x03\x03\x00\x00\x00\x1e\xb1" + // 0x01030300: 0x00001EB1 + "\x01\x02\x03\t\x00\x00\x1e\xb2" + // 0x01020309: 0x00001EB2 + "\x01\x03\x03\t\x00\x00\x1e\xb3" + // 0x01030309: 0x00001EB3 + "\x01\x02\x03\x03\x00\x00\x1e\xb4" + // 0x01020303: 0x00001EB4 + "\x01\x03\x03\x03\x00\x00\x1e\xb5" + // 0x01030303: 0x00001EB5 + "\x1e\xa0\x03\x06\x00\x00\x1e\xb6" + // 0x1EA00306: 0x00001EB6 + "\x1e\xa1\x03\x06\x00\x00\x1e\xb7" + // 0x1EA10306: 0x00001EB7 + "\x00E\x03#\x00\x00\x1e\xb8" + // 0x00450323: 0x00001EB8 + "\x00e\x03#\x00\x00\x1e\xb9" + // 0x00650323: 0x00001EB9 + "\x00E\x03\t\x00\x00\x1e\xba" + // 0x00450309: 0x00001EBA + "\x00e\x03\t\x00\x00\x1e\xbb" + // 0x00650309: 0x00001EBB + "\x00E\x03\x03\x00\x00\x1e\xbc" + // 0x00450303: 0x00001EBC + "\x00e\x03\x03\x00\x00\x1e\xbd" + // 0x00650303: 0x00001EBD + "\x00\xca\x03\x01\x00\x00\x1e\xbe" + // 0x00CA0301: 0x00001EBE + "\x00\xea\x03\x01\x00\x00\x1e\xbf" + // 0x00EA0301: 0x00001EBF + "\x00\xca\x03\x00\x00\x00\x1e\xc0" + // 0x00CA0300: 0x00001EC0 + "\x00\xea\x03\x00\x00\x00\x1e\xc1" + // 0x00EA0300: 0x00001EC1 + "\x00\xca\x03\t\x00\x00\x1e\xc2" + // 0x00CA0309: 0x00001EC2 + "\x00\xea\x03\t\x00\x00\x1e\xc3" + // 0x00EA0309: 0x00001EC3 + "\x00\xca\x03\x03\x00\x00\x1e\xc4" + // 0x00CA0303: 0x00001EC4 + "\x00\xea\x03\x03\x00\x00\x1e\xc5" + // 0x00EA0303: 0x00001EC5 + "\x1e\xb8\x03\x02\x00\x00\x1e\xc6" + // 0x1EB80302: 0x00001EC6 + "\x1e\xb9\x03\x02\x00\x00\x1e\xc7" + // 0x1EB90302: 0x00001EC7 + "\x00I\x03\t\x00\x00\x1e\xc8" + // 0x00490309: 0x00001EC8 + "\x00i\x03\t\x00\x00\x1e\xc9" + // 0x00690309: 0x00001EC9 + "\x00I\x03#\x00\x00\x1e\xca" + // 0x00490323: 0x00001ECA + "\x00i\x03#\x00\x00\x1e\xcb" + // 0x00690323: 0x00001ECB + "\x00O\x03#\x00\x00\x1e\xcc" + // 0x004F0323: 0x00001ECC + "\x00o\x03#\x00\x00\x1e\xcd" + // 0x006F0323: 0x00001ECD + "\x00O\x03\t\x00\x00\x1e\xce" + // 0x004F0309: 0x00001ECE + "\x00o\x03\t\x00\x00\x1e\xcf" + // 0x006F0309: 0x00001ECF + "\x00\xd4\x03\x01\x00\x00\x1e\xd0" + // 0x00D40301: 0x00001ED0 + "\x00\xf4\x03\x01\x00\x00\x1e\xd1" + // 0x00F40301: 0x00001ED1 + "\x00\xd4\x03\x00\x00\x00\x1e\xd2" + // 0x00D40300: 0x00001ED2 + "\x00\xf4\x03\x00\x00\x00\x1e\xd3" + // 0x00F40300: 0x00001ED3 + "\x00\xd4\x03\t\x00\x00\x1e\xd4" + // 0x00D40309: 0x00001ED4 + "\x00\xf4\x03\t\x00\x00\x1e\xd5" + // 0x00F40309: 0x00001ED5 + "\x00\xd4\x03\x03\x00\x00\x1e\xd6" + // 0x00D40303: 0x00001ED6 + "\x00\xf4\x03\x03\x00\x00\x1e\xd7" + // 0x00F40303: 0x00001ED7 + "\x1e\xcc\x03\x02\x00\x00\x1e\xd8" + // 0x1ECC0302: 0x00001ED8 + "\x1e\xcd\x03\x02\x00\x00\x1e\xd9" + // 0x1ECD0302: 0x00001ED9 + "\x01\xa0\x03\x01\x00\x00\x1e\xda" + // 0x01A00301: 0x00001EDA + "\x01\xa1\x03\x01\x00\x00\x1e\xdb" + // 0x01A10301: 0x00001EDB + "\x01\xa0\x03\x00\x00\x00\x1e\xdc" + // 0x01A00300: 0x00001EDC + "\x01\xa1\x03\x00\x00\x00\x1e\xdd" + // 0x01A10300: 0x00001EDD + "\x01\xa0\x03\t\x00\x00\x1e\xde" + // 0x01A00309: 0x00001EDE + "\x01\xa1\x03\t\x00\x00\x1e\xdf" + // 0x01A10309: 0x00001EDF + "\x01\xa0\x03\x03\x00\x00\x1e\xe0" + // 0x01A00303: 0x00001EE0 + "\x01\xa1\x03\x03\x00\x00\x1e\xe1" + // 0x01A10303: 0x00001EE1 + "\x01\xa0\x03#\x00\x00\x1e\xe2" + // 0x01A00323: 0x00001EE2 + "\x01\xa1\x03#\x00\x00\x1e\xe3" + // 0x01A10323: 0x00001EE3 + "\x00U\x03#\x00\x00\x1e\xe4" + // 0x00550323: 0x00001EE4 + "\x00u\x03#\x00\x00\x1e\xe5" + // 0x00750323: 0x00001EE5 + "\x00U\x03\t\x00\x00\x1e\xe6" + // 0x00550309: 0x00001EE6 + "\x00u\x03\t\x00\x00\x1e\xe7" + // 0x00750309: 0x00001EE7 + "\x01\xaf\x03\x01\x00\x00\x1e\xe8" + // 0x01AF0301: 0x00001EE8 + "\x01\xb0\x03\x01\x00\x00\x1e\xe9" + // 0x01B00301: 0x00001EE9 + "\x01\xaf\x03\x00\x00\x00\x1e\xea" + // 0x01AF0300: 0x00001EEA + "\x01\xb0\x03\x00\x00\x00\x1e\xeb" + // 0x01B00300: 0x00001EEB + "\x01\xaf\x03\t\x00\x00\x1e\xec" + // 0x01AF0309: 0x00001EEC + "\x01\xb0\x03\t\x00\x00\x1e\xed" + // 0x01B00309: 0x00001EED + "\x01\xaf\x03\x03\x00\x00\x1e\xee" + // 0x01AF0303: 0x00001EEE + "\x01\xb0\x03\x03\x00\x00\x1e\xef" + // 0x01B00303: 0x00001EEF + "\x01\xaf\x03#\x00\x00\x1e\xf0" + // 0x01AF0323: 0x00001EF0 + "\x01\xb0\x03#\x00\x00\x1e\xf1" + // 0x01B00323: 0x00001EF1 + "\x00Y\x03\x00\x00\x00\x1e\xf2" + // 0x00590300: 0x00001EF2 + "\x00y\x03\x00\x00\x00\x1e\xf3" + // 0x00790300: 0x00001EF3 + "\x00Y\x03#\x00\x00\x1e\xf4" + // 0x00590323: 0x00001EF4 + "\x00y\x03#\x00\x00\x1e\xf5" + // 0x00790323: 0x00001EF5 + "\x00Y\x03\t\x00\x00\x1e\xf6" + // 0x00590309: 0x00001EF6 + "\x00y\x03\t\x00\x00\x1e\xf7" + // 0x00790309: 0x00001EF7 + "\x00Y\x03\x03\x00\x00\x1e\xf8" + // 0x00590303: 0x00001EF8 + "\x00y\x03\x03\x00\x00\x1e\xf9" + // 0x00790303: 0x00001EF9 + "\x03\xb1\x03\x13\x00\x00\x1f\x00" + // 0x03B10313: 0x00001F00 + "\x03\xb1\x03\x14\x00\x00\x1f\x01" + // 0x03B10314: 0x00001F01 + "\x1f\x00\x03\x00\x00\x00\x1f\x02" + // 0x1F000300: 0x00001F02 + "\x1f\x01\x03\x00\x00\x00\x1f\x03" + // 0x1F010300: 0x00001F03 + "\x1f\x00\x03\x01\x00\x00\x1f\x04" + // 0x1F000301: 0x00001F04 + "\x1f\x01\x03\x01\x00\x00\x1f\x05" + // 0x1F010301: 0x00001F05 + "\x1f\x00\x03B\x00\x00\x1f\x06" + // 0x1F000342: 0x00001F06 + "\x1f\x01\x03B\x00\x00\x1f\a" + // 0x1F010342: 0x00001F07 + "\x03\x91\x03\x13\x00\x00\x1f\b" + // 0x03910313: 0x00001F08 + "\x03\x91\x03\x14\x00\x00\x1f\t" + // 0x03910314: 0x00001F09 + "\x1f\b\x03\x00\x00\x00\x1f\n" + // 0x1F080300: 0x00001F0A + "\x1f\t\x03\x00\x00\x00\x1f\v" + // 0x1F090300: 0x00001F0B + "\x1f\b\x03\x01\x00\x00\x1f\f" + // 0x1F080301: 0x00001F0C + "\x1f\t\x03\x01\x00\x00\x1f\r" + // 0x1F090301: 0x00001F0D + "\x1f\b\x03B\x00\x00\x1f\x0e" + // 0x1F080342: 0x00001F0E + "\x1f\t\x03B\x00\x00\x1f\x0f" + // 0x1F090342: 0x00001F0F + "\x03\xb5\x03\x13\x00\x00\x1f\x10" + // 0x03B50313: 0x00001F10 + "\x03\xb5\x03\x14\x00\x00\x1f\x11" + // 0x03B50314: 0x00001F11 + "\x1f\x10\x03\x00\x00\x00\x1f\x12" + // 0x1F100300: 0x00001F12 + "\x1f\x11\x03\x00\x00\x00\x1f\x13" + // 0x1F110300: 0x00001F13 + "\x1f\x10\x03\x01\x00\x00\x1f\x14" + // 0x1F100301: 0x00001F14 + "\x1f\x11\x03\x01\x00\x00\x1f\x15" + // 0x1F110301: 0x00001F15 + "\x03\x95\x03\x13\x00\x00\x1f\x18" + // 0x03950313: 0x00001F18 + "\x03\x95\x03\x14\x00\x00\x1f\x19" + // 0x03950314: 0x00001F19 + "\x1f\x18\x03\x00\x00\x00\x1f\x1a" + // 0x1F180300: 0x00001F1A + "\x1f\x19\x03\x00\x00\x00\x1f\x1b" + // 0x1F190300: 0x00001F1B + "\x1f\x18\x03\x01\x00\x00\x1f\x1c" + // 0x1F180301: 0x00001F1C + "\x1f\x19\x03\x01\x00\x00\x1f\x1d" + // 0x1F190301: 0x00001F1D + "\x03\xb7\x03\x13\x00\x00\x1f " + // 0x03B70313: 0x00001F20 + "\x03\xb7\x03\x14\x00\x00\x1f!" + // 0x03B70314: 0x00001F21 + "\x1f \x03\x00\x00\x00\x1f\"" + // 0x1F200300: 0x00001F22 + "\x1f!\x03\x00\x00\x00\x1f#" + // 0x1F210300: 0x00001F23 + "\x1f \x03\x01\x00\x00\x1f$" + // 0x1F200301: 0x00001F24 + "\x1f!\x03\x01\x00\x00\x1f%" + // 0x1F210301: 0x00001F25 + "\x1f \x03B\x00\x00\x1f&" + // 0x1F200342: 0x00001F26 + "\x1f!\x03B\x00\x00\x1f'" + // 0x1F210342: 0x00001F27 + "\x03\x97\x03\x13\x00\x00\x1f(" + // 0x03970313: 0x00001F28 + "\x03\x97\x03\x14\x00\x00\x1f)" + // 0x03970314: 0x00001F29 + "\x1f(\x03\x00\x00\x00\x1f*" + // 0x1F280300: 0x00001F2A + "\x1f)\x03\x00\x00\x00\x1f+" + // 0x1F290300: 0x00001F2B + "\x1f(\x03\x01\x00\x00\x1f," + // 0x1F280301: 0x00001F2C + "\x1f)\x03\x01\x00\x00\x1f-" + // 0x1F290301: 0x00001F2D + "\x1f(\x03B\x00\x00\x1f." + // 0x1F280342: 0x00001F2E + "\x1f)\x03B\x00\x00\x1f/" + // 0x1F290342: 0x00001F2F + "\x03\xb9\x03\x13\x00\x00\x1f0" + // 0x03B90313: 0x00001F30 + "\x03\xb9\x03\x14\x00\x00\x1f1" + // 0x03B90314: 0x00001F31 + "\x1f0\x03\x00\x00\x00\x1f2" + // 0x1F300300: 0x00001F32 + "\x1f1\x03\x00\x00\x00\x1f3" + // 0x1F310300: 0x00001F33 + "\x1f0\x03\x01\x00\x00\x1f4" + // 0x1F300301: 0x00001F34 + "\x1f1\x03\x01\x00\x00\x1f5" + // 0x1F310301: 0x00001F35 + "\x1f0\x03B\x00\x00\x1f6" + // 0x1F300342: 0x00001F36 + "\x1f1\x03B\x00\x00\x1f7" + // 0x1F310342: 0x00001F37 + "\x03\x99\x03\x13\x00\x00\x1f8" + // 0x03990313: 0x00001F38 + "\x03\x99\x03\x14\x00\x00\x1f9" + // 0x03990314: 0x00001F39 + "\x1f8\x03\x00\x00\x00\x1f:" + // 0x1F380300: 0x00001F3A + "\x1f9\x03\x00\x00\x00\x1f;" + // 0x1F390300: 0x00001F3B + "\x1f8\x03\x01\x00\x00\x1f<" + // 0x1F380301: 0x00001F3C + "\x1f9\x03\x01\x00\x00\x1f=" + // 0x1F390301: 0x00001F3D + "\x1f8\x03B\x00\x00\x1f>" + // 0x1F380342: 0x00001F3E + "\x1f9\x03B\x00\x00\x1f?" + // 0x1F390342: 0x00001F3F + "\x03\xbf\x03\x13\x00\x00\x1f@" + // 0x03BF0313: 0x00001F40 + "\x03\xbf\x03\x14\x00\x00\x1fA" + // 0x03BF0314: 0x00001F41 + "\x1f@\x03\x00\x00\x00\x1fB" + // 0x1F400300: 0x00001F42 + "\x1fA\x03\x00\x00\x00\x1fC" + // 0x1F410300: 0x00001F43 + "\x1f@\x03\x01\x00\x00\x1fD" + // 0x1F400301: 0x00001F44 + "\x1fA\x03\x01\x00\x00\x1fE" + // 0x1F410301: 0x00001F45 + "\x03\x9f\x03\x13\x00\x00\x1fH" + // 0x039F0313: 0x00001F48 + "\x03\x9f\x03\x14\x00\x00\x1fI" + // 0x039F0314: 0x00001F49 + "\x1fH\x03\x00\x00\x00\x1fJ" + // 0x1F480300: 0x00001F4A + "\x1fI\x03\x00\x00\x00\x1fK" + // 0x1F490300: 0x00001F4B + "\x1fH\x03\x01\x00\x00\x1fL" + // 0x1F480301: 0x00001F4C + "\x1fI\x03\x01\x00\x00\x1fM" + // 0x1F490301: 0x00001F4D + "\x03\xc5\x03\x13\x00\x00\x1fP" + // 0x03C50313: 0x00001F50 + "\x03\xc5\x03\x14\x00\x00\x1fQ" + // 0x03C50314: 0x00001F51 + "\x1fP\x03\x00\x00\x00\x1fR" + // 0x1F500300: 0x00001F52 + "\x1fQ\x03\x00\x00\x00\x1fS" + // 0x1F510300: 0x00001F53 + "\x1fP\x03\x01\x00\x00\x1fT" + // 0x1F500301: 0x00001F54 + "\x1fQ\x03\x01\x00\x00\x1fU" + // 0x1F510301: 0x00001F55 + "\x1fP\x03B\x00\x00\x1fV" + // 0x1F500342: 0x00001F56 + "\x1fQ\x03B\x00\x00\x1fW" + // 0x1F510342: 0x00001F57 + "\x03\xa5\x03\x14\x00\x00\x1fY" + // 0x03A50314: 0x00001F59 + "\x1fY\x03\x00\x00\x00\x1f[" + // 0x1F590300: 0x00001F5B + "\x1fY\x03\x01\x00\x00\x1f]" + // 0x1F590301: 0x00001F5D + "\x1fY\x03B\x00\x00\x1f_" + // 0x1F590342: 0x00001F5F + "\x03\xc9\x03\x13\x00\x00\x1f`" + // 0x03C90313: 0x00001F60 + "\x03\xc9\x03\x14\x00\x00\x1fa" + // 0x03C90314: 0x00001F61 + "\x1f`\x03\x00\x00\x00\x1fb" + // 0x1F600300: 0x00001F62 + "\x1fa\x03\x00\x00\x00\x1fc" + // 0x1F610300: 0x00001F63 + "\x1f`\x03\x01\x00\x00\x1fd" + // 0x1F600301: 0x00001F64 + "\x1fa\x03\x01\x00\x00\x1fe" + // 0x1F610301: 0x00001F65 + "\x1f`\x03B\x00\x00\x1ff" + // 0x1F600342: 0x00001F66 + "\x1fa\x03B\x00\x00\x1fg" + // 0x1F610342: 0x00001F67 + "\x03\xa9\x03\x13\x00\x00\x1fh" + // 0x03A90313: 0x00001F68 + "\x03\xa9\x03\x14\x00\x00\x1fi" + // 0x03A90314: 0x00001F69 + "\x1fh\x03\x00\x00\x00\x1fj" + // 0x1F680300: 0x00001F6A + "\x1fi\x03\x00\x00\x00\x1fk" + // 0x1F690300: 0x00001F6B + "\x1fh\x03\x01\x00\x00\x1fl" + // 0x1F680301: 0x00001F6C + "\x1fi\x03\x01\x00\x00\x1fm" + // 0x1F690301: 0x00001F6D + "\x1fh\x03B\x00\x00\x1fn" + // 0x1F680342: 0x00001F6E + "\x1fi\x03B\x00\x00\x1fo" + // 0x1F690342: 0x00001F6F + "\x03\xb1\x03\x00\x00\x00\x1fp" + // 0x03B10300: 0x00001F70 + "\x03\xb5\x03\x00\x00\x00\x1fr" + // 0x03B50300: 0x00001F72 + "\x03\xb7\x03\x00\x00\x00\x1ft" + // 0x03B70300: 0x00001F74 + "\x03\xb9\x03\x00\x00\x00\x1fv" + // 0x03B90300: 0x00001F76 + "\x03\xbf\x03\x00\x00\x00\x1fx" + // 0x03BF0300: 0x00001F78 + "\x03\xc5\x03\x00\x00\x00\x1fz" + // 0x03C50300: 0x00001F7A + "\x03\xc9\x03\x00\x00\x00\x1f|" + // 0x03C90300: 0x00001F7C + "\x1f\x00\x03E\x00\x00\x1f\x80" + // 0x1F000345: 0x00001F80 + "\x1f\x01\x03E\x00\x00\x1f\x81" + // 0x1F010345: 0x00001F81 + "\x1f\x02\x03E\x00\x00\x1f\x82" + // 0x1F020345: 0x00001F82 + "\x1f\x03\x03E\x00\x00\x1f\x83" + // 0x1F030345: 0x00001F83 + "\x1f\x04\x03E\x00\x00\x1f\x84" + // 0x1F040345: 0x00001F84 + "\x1f\x05\x03E\x00\x00\x1f\x85" + // 0x1F050345: 0x00001F85 + "\x1f\x06\x03E\x00\x00\x1f\x86" + // 0x1F060345: 0x00001F86 + "\x1f\a\x03E\x00\x00\x1f\x87" + // 0x1F070345: 0x00001F87 + "\x1f\b\x03E\x00\x00\x1f\x88" + // 0x1F080345: 0x00001F88 + "\x1f\t\x03E\x00\x00\x1f\x89" + // 0x1F090345: 0x00001F89 + "\x1f\n\x03E\x00\x00\x1f\x8a" + // 0x1F0A0345: 0x00001F8A + "\x1f\v\x03E\x00\x00\x1f\x8b" + // 0x1F0B0345: 0x00001F8B + "\x1f\f\x03E\x00\x00\x1f\x8c" + // 0x1F0C0345: 0x00001F8C + "\x1f\r\x03E\x00\x00\x1f\x8d" + // 0x1F0D0345: 0x00001F8D + "\x1f\x0e\x03E\x00\x00\x1f\x8e" + // 0x1F0E0345: 0x00001F8E + "\x1f\x0f\x03E\x00\x00\x1f\x8f" + // 0x1F0F0345: 0x00001F8F + "\x1f \x03E\x00\x00\x1f\x90" + // 0x1F200345: 0x00001F90 + "\x1f!\x03E\x00\x00\x1f\x91" + // 0x1F210345: 0x00001F91 + "\x1f\"\x03E\x00\x00\x1f\x92" + // 0x1F220345: 0x00001F92 + "\x1f#\x03E\x00\x00\x1f\x93" + // 0x1F230345: 0x00001F93 + "\x1f$\x03E\x00\x00\x1f\x94" + // 0x1F240345: 0x00001F94 + "\x1f%\x03E\x00\x00\x1f\x95" + // 0x1F250345: 0x00001F95 + "\x1f&\x03E\x00\x00\x1f\x96" + // 0x1F260345: 0x00001F96 + "\x1f'\x03E\x00\x00\x1f\x97" + // 0x1F270345: 0x00001F97 + "\x1f(\x03E\x00\x00\x1f\x98" + // 0x1F280345: 0x00001F98 + "\x1f)\x03E\x00\x00\x1f\x99" + // 0x1F290345: 0x00001F99 + "\x1f*\x03E\x00\x00\x1f\x9a" + // 0x1F2A0345: 0x00001F9A + "\x1f+\x03E\x00\x00\x1f\x9b" + // 0x1F2B0345: 0x00001F9B + "\x1f,\x03E\x00\x00\x1f\x9c" + // 0x1F2C0345: 0x00001F9C + "\x1f-\x03E\x00\x00\x1f\x9d" + // 0x1F2D0345: 0x00001F9D + "\x1f.\x03E\x00\x00\x1f\x9e" + // 0x1F2E0345: 0x00001F9E + "\x1f/\x03E\x00\x00\x1f\x9f" + // 0x1F2F0345: 0x00001F9F + "\x1f`\x03E\x00\x00\x1f\xa0" + // 0x1F600345: 0x00001FA0 + "\x1fa\x03E\x00\x00\x1f\xa1" + // 0x1F610345: 0x00001FA1 + "\x1fb\x03E\x00\x00\x1f\xa2" + // 0x1F620345: 0x00001FA2 + "\x1fc\x03E\x00\x00\x1f\xa3" + // 0x1F630345: 0x00001FA3 + "\x1fd\x03E\x00\x00\x1f\xa4" + // 0x1F640345: 0x00001FA4 + "\x1fe\x03E\x00\x00\x1f\xa5" + // 0x1F650345: 0x00001FA5 + "\x1ff\x03E\x00\x00\x1f\xa6" + // 0x1F660345: 0x00001FA6 + "\x1fg\x03E\x00\x00\x1f\xa7" + // 0x1F670345: 0x00001FA7 + "\x1fh\x03E\x00\x00\x1f\xa8" + // 0x1F680345: 0x00001FA8 + "\x1fi\x03E\x00\x00\x1f\xa9" + // 0x1F690345: 0x00001FA9 + "\x1fj\x03E\x00\x00\x1f\xaa" + // 0x1F6A0345: 0x00001FAA + "\x1fk\x03E\x00\x00\x1f\xab" + // 0x1F6B0345: 0x00001FAB + "\x1fl\x03E\x00\x00\x1f\xac" + // 0x1F6C0345: 0x00001FAC + "\x1fm\x03E\x00\x00\x1f\xad" + // 0x1F6D0345: 0x00001FAD + "\x1fn\x03E\x00\x00\x1f\xae" + // 0x1F6E0345: 0x00001FAE + "\x1fo\x03E\x00\x00\x1f\xaf" + // 0x1F6F0345: 0x00001FAF + "\x03\xb1\x03\x06\x00\x00\x1f\xb0" + // 0x03B10306: 0x00001FB0 + "\x03\xb1\x03\x04\x00\x00\x1f\xb1" + // 0x03B10304: 0x00001FB1 + "\x1fp\x03E\x00\x00\x1f\xb2" + // 0x1F700345: 0x00001FB2 + "\x03\xb1\x03E\x00\x00\x1f\xb3" + // 0x03B10345: 0x00001FB3 + "\x03\xac\x03E\x00\x00\x1f\xb4" + // 0x03AC0345: 0x00001FB4 + "\x03\xb1\x03B\x00\x00\x1f\xb6" + // 0x03B10342: 0x00001FB6 + "\x1f\xb6\x03E\x00\x00\x1f\xb7" + // 0x1FB60345: 0x00001FB7 + "\x03\x91\x03\x06\x00\x00\x1f\xb8" + // 0x03910306: 0x00001FB8 + "\x03\x91\x03\x04\x00\x00\x1f\xb9" + // 0x03910304: 0x00001FB9 + "\x03\x91\x03\x00\x00\x00\x1f\xba" + // 0x03910300: 0x00001FBA + "\x03\x91\x03E\x00\x00\x1f\xbc" + // 0x03910345: 0x00001FBC + "\x00\xa8\x03B\x00\x00\x1f\xc1" + // 0x00A80342: 0x00001FC1 + "\x1ft\x03E\x00\x00\x1f\xc2" + // 0x1F740345: 0x00001FC2 + "\x03\xb7\x03E\x00\x00\x1f\xc3" + // 0x03B70345: 0x00001FC3 + "\x03\xae\x03E\x00\x00\x1f\xc4" + // 0x03AE0345: 0x00001FC4 + "\x03\xb7\x03B\x00\x00\x1f\xc6" + // 0x03B70342: 0x00001FC6 + "\x1f\xc6\x03E\x00\x00\x1f\xc7" + // 0x1FC60345: 0x00001FC7 + "\x03\x95\x03\x00\x00\x00\x1f\xc8" + // 0x03950300: 0x00001FC8 + "\x03\x97\x03\x00\x00\x00\x1f\xca" + // 0x03970300: 0x00001FCA + "\x03\x97\x03E\x00\x00\x1f\xcc" + // 0x03970345: 0x00001FCC + "\x1f\xbf\x03\x00\x00\x00\x1f\xcd" + // 0x1FBF0300: 0x00001FCD + "\x1f\xbf\x03\x01\x00\x00\x1f\xce" + // 0x1FBF0301: 0x00001FCE + "\x1f\xbf\x03B\x00\x00\x1f\xcf" + // 0x1FBF0342: 0x00001FCF + "\x03\xb9\x03\x06\x00\x00\x1f\xd0" + // 0x03B90306: 0x00001FD0 + "\x03\xb9\x03\x04\x00\x00\x1f\xd1" + // 0x03B90304: 0x00001FD1 + "\x03\xca\x03\x00\x00\x00\x1f\xd2" + // 0x03CA0300: 0x00001FD2 + "\x03\xb9\x03B\x00\x00\x1f\xd6" + // 0x03B90342: 0x00001FD6 + "\x03\xca\x03B\x00\x00\x1f\xd7" + // 0x03CA0342: 0x00001FD7 + "\x03\x99\x03\x06\x00\x00\x1f\xd8" + // 0x03990306: 0x00001FD8 + "\x03\x99\x03\x04\x00\x00\x1f\xd9" + // 0x03990304: 0x00001FD9 + "\x03\x99\x03\x00\x00\x00\x1f\xda" + // 0x03990300: 0x00001FDA + "\x1f\xfe\x03\x00\x00\x00\x1f\xdd" + // 0x1FFE0300: 0x00001FDD + "\x1f\xfe\x03\x01\x00\x00\x1f\xde" + // 0x1FFE0301: 0x00001FDE + "\x1f\xfe\x03B\x00\x00\x1f\xdf" + // 0x1FFE0342: 0x00001FDF + "\x03\xc5\x03\x06\x00\x00\x1f\xe0" + // 0x03C50306: 0x00001FE0 + "\x03\xc5\x03\x04\x00\x00\x1f\xe1" + // 0x03C50304: 0x00001FE1 + "\x03\xcb\x03\x00\x00\x00\x1f\xe2" + // 0x03CB0300: 0x00001FE2 + "\x03\xc1\x03\x13\x00\x00\x1f\xe4" + // 0x03C10313: 0x00001FE4 + "\x03\xc1\x03\x14\x00\x00\x1f\xe5" + // 0x03C10314: 0x00001FE5 + "\x03\xc5\x03B\x00\x00\x1f\xe6" + // 0x03C50342: 0x00001FE6 + "\x03\xcb\x03B\x00\x00\x1f\xe7" + // 0x03CB0342: 0x00001FE7 + "\x03\xa5\x03\x06\x00\x00\x1f\xe8" + // 0x03A50306: 0x00001FE8 + "\x03\xa5\x03\x04\x00\x00\x1f\xe9" + // 0x03A50304: 0x00001FE9 + "\x03\xa5\x03\x00\x00\x00\x1f\xea" + // 0x03A50300: 0x00001FEA + "\x03\xa1\x03\x14\x00\x00\x1f\xec" + // 0x03A10314: 0x00001FEC + "\x00\xa8\x03\x00\x00\x00\x1f\xed" + // 0x00A80300: 0x00001FED + "\x1f|\x03E\x00\x00\x1f\xf2" + // 0x1F7C0345: 0x00001FF2 + "\x03\xc9\x03E\x00\x00\x1f\xf3" + // 0x03C90345: 0x00001FF3 + "\x03\xce\x03E\x00\x00\x1f\xf4" + // 0x03CE0345: 0x00001FF4 + "\x03\xc9\x03B\x00\x00\x1f\xf6" + // 0x03C90342: 0x00001FF6 + "\x1f\xf6\x03E\x00\x00\x1f\xf7" + // 0x1FF60345: 0x00001FF7 + "\x03\x9f\x03\x00\x00\x00\x1f\xf8" + // 0x039F0300: 0x00001FF8 + "\x03\xa9\x03\x00\x00\x00\x1f\xfa" + // 0x03A90300: 0x00001FFA + "\x03\xa9\x03E\x00\x00\x1f\xfc" + // 0x03A90345: 0x00001FFC + "!\x90\x038\x00\x00!\x9a" + // 0x21900338: 0x0000219A + "!\x92\x038\x00\x00!\x9b" + // 0x21920338: 0x0000219B + "!\x94\x038\x00\x00!\xae" + // 0x21940338: 0x000021AE + "!\xd0\x038\x00\x00!\xcd" + // 0x21D00338: 0x000021CD + "!\xd4\x038\x00\x00!\xce" + // 0x21D40338: 0x000021CE + "!\xd2\x038\x00\x00!\xcf" + // 0x21D20338: 0x000021CF + "\"\x03\x038\x00\x00\"\x04" + // 0x22030338: 0x00002204 + "\"\b\x038\x00\x00\"\t" + // 0x22080338: 0x00002209 + "\"\v\x038\x00\x00\"\f" + // 0x220B0338: 0x0000220C + "\"#\x038\x00\x00\"$" + // 0x22230338: 0x00002224 + "\"%\x038\x00\x00\"&" + // 0x22250338: 0x00002226 + "\"<\x038\x00\x00\"A" + // 0x223C0338: 0x00002241 + "\"C\x038\x00\x00\"D" + // 0x22430338: 0x00002244 + "\"E\x038\x00\x00\"G" + // 0x22450338: 0x00002247 + "\"H\x038\x00\x00\"I" + // 0x22480338: 0x00002249 + "\x00=\x038\x00\x00\"`" + // 0x003D0338: 0x00002260 + "\"a\x038\x00\x00\"b" + // 0x22610338: 0x00002262 + "\"M\x038\x00\x00\"m" + // 0x224D0338: 0x0000226D + "\x00<\x038\x00\x00\"n" + // 0x003C0338: 0x0000226E + "\x00>\x038\x00\x00\"o" + // 0x003E0338: 0x0000226F + "\"d\x038\x00\x00\"p" + // 0x22640338: 0x00002270 + "\"e\x038\x00\x00\"q" + // 0x22650338: 0x00002271 + "\"r\x038\x00\x00\"t" + // 0x22720338: 0x00002274 + "\"s\x038\x00\x00\"u" + // 0x22730338: 0x00002275 + "\"v\x038\x00\x00\"x" + // 0x22760338: 0x00002278 + "\"w\x038\x00\x00\"y" + // 0x22770338: 0x00002279 + "\"z\x038\x00\x00\"\x80" + // 0x227A0338: 0x00002280 + "\"{\x038\x00\x00\"\x81" + // 0x227B0338: 0x00002281 + "\"\x82\x038\x00\x00\"\x84" + // 0x22820338: 0x00002284 + "\"\x83\x038\x00\x00\"\x85" + // 0x22830338: 0x00002285 + "\"\x86\x038\x00\x00\"\x88" + // 0x22860338: 0x00002288 + "\"\x87\x038\x00\x00\"\x89" + // 0x22870338: 0x00002289 + "\"\xa2\x038\x00\x00\"\xac" + // 0x22A20338: 0x000022AC + "\"\xa8\x038\x00\x00\"\xad" + // 0x22A80338: 0x000022AD + "\"\xa9\x038\x00\x00\"\xae" + // 0x22A90338: 0x000022AE + "\"\xab\x038\x00\x00\"\xaf" + // 0x22AB0338: 0x000022AF + "\"|\x038\x00\x00\"\xe0" + // 0x227C0338: 0x000022E0 + "\"}\x038\x00\x00\"\xe1" + // 0x227D0338: 0x000022E1 + "\"\x91\x038\x00\x00\"\xe2" + // 0x22910338: 0x000022E2 + "\"\x92\x038\x00\x00\"\xe3" + // 0x22920338: 0x000022E3 + "\"\xb2\x038\x00\x00\"\xea" + // 0x22B20338: 0x000022EA + "\"\xb3\x038\x00\x00\"\xeb" + // 0x22B30338: 0x000022EB + "\"\xb4\x038\x00\x00\"\xec" + // 0x22B40338: 0x000022EC + "\"\xb5\x038\x00\x00\"\xed" + // 0x22B50338: 0x000022ED + "0K0\x99\x00\x000L" + // 0x304B3099: 0x0000304C + "0M0\x99\x00\x000N" + // 0x304D3099: 0x0000304E + "0O0\x99\x00\x000P" + // 0x304F3099: 0x00003050 + "0Q0\x99\x00\x000R" + // 0x30513099: 0x00003052 + "0S0\x99\x00\x000T" + // 0x30533099: 0x00003054 + "0U0\x99\x00\x000V" + // 0x30553099: 0x00003056 + "0W0\x99\x00\x000X" + // 0x30573099: 0x00003058 + "0Y0\x99\x00\x000Z" + // 0x30593099: 0x0000305A + "0[0\x99\x00\x000\\" + // 0x305B3099: 0x0000305C + "0]0\x99\x00\x000^" + // 0x305D3099: 0x0000305E + "0_0\x99\x00\x000`" + // 0x305F3099: 0x00003060 + "0a0\x99\x00\x000b" + // 0x30613099: 0x00003062 + "0d0\x99\x00\x000e" + // 0x30643099: 0x00003065 + "0f0\x99\x00\x000g" + // 0x30663099: 0x00003067 + "0h0\x99\x00\x000i" + // 0x30683099: 0x00003069 + "0o0\x99\x00\x000p" + // 0x306F3099: 0x00003070 + "0o0\x9a\x00\x000q" + // 0x306F309A: 0x00003071 + "0r0\x99\x00\x000s" + // 0x30723099: 0x00003073 + "0r0\x9a\x00\x000t" + // 0x3072309A: 0x00003074 + "0u0\x99\x00\x000v" + // 0x30753099: 0x00003076 + "0u0\x9a\x00\x000w" + // 0x3075309A: 0x00003077 + "0x0\x99\x00\x000y" + // 0x30783099: 0x00003079 + "0x0\x9a\x00\x000z" + // 0x3078309A: 0x0000307A + "0{0\x99\x00\x000|" + // 0x307B3099: 0x0000307C + "0{0\x9a\x00\x000}" + // 0x307B309A: 0x0000307D + "0F0\x99\x00\x000\x94" + // 0x30463099: 0x00003094 + "0\x9d0\x99\x00\x000\x9e" + // 0x309D3099: 0x0000309E + "0\xab0\x99\x00\x000\xac" + // 0x30AB3099: 0x000030AC + "0\xad0\x99\x00\x000\xae" + // 0x30AD3099: 0x000030AE + "0\xaf0\x99\x00\x000\xb0" + // 0x30AF3099: 0x000030B0 + "0\xb10\x99\x00\x000\xb2" + // 0x30B13099: 0x000030B2 + "0\xb30\x99\x00\x000\xb4" + // 0x30B33099: 0x000030B4 + "0\xb50\x99\x00\x000\xb6" + // 0x30B53099: 0x000030B6 + "0\xb70\x99\x00\x000\xb8" + // 0x30B73099: 0x000030B8 + "0\xb90\x99\x00\x000\xba" + // 0x30B93099: 0x000030BA + "0\xbb0\x99\x00\x000\xbc" + // 0x30BB3099: 0x000030BC + "0\xbd0\x99\x00\x000\xbe" + // 0x30BD3099: 0x000030BE + "0\xbf0\x99\x00\x000\xc0" + // 0x30BF3099: 0x000030C0 + "0\xc10\x99\x00\x000\xc2" + // 0x30C13099: 0x000030C2 + "0\xc40\x99\x00\x000\xc5" + // 0x30C43099: 0x000030C5 + "0\xc60\x99\x00\x000\xc7" + // 0x30C63099: 0x000030C7 + "0\xc80\x99\x00\x000\xc9" + // 0x30C83099: 0x000030C9 + "0\xcf0\x99\x00\x000\xd0" + // 0x30CF3099: 0x000030D0 + "0\xcf0\x9a\x00\x000\xd1" + // 0x30CF309A: 0x000030D1 + "0\xd20\x99\x00\x000\xd3" + // 0x30D23099: 0x000030D3 + "0\xd20\x9a\x00\x000\xd4" + // 0x30D2309A: 0x000030D4 + "0\xd50\x99\x00\x000\xd6" + // 0x30D53099: 0x000030D6 + "0\xd50\x9a\x00\x000\xd7" + // 0x30D5309A: 0x000030D7 + "0\xd80\x99\x00\x000\xd9" + // 0x30D83099: 0x000030D9 + "0\xd80\x9a\x00\x000\xda" + // 0x30D8309A: 0x000030DA + "0\xdb0\x99\x00\x000\xdc" + // 0x30DB3099: 0x000030DC + "0\xdb0\x9a\x00\x000\xdd" + // 0x30DB309A: 0x000030DD + "0\xa60\x99\x00\x000\xf4" + // 0x30A63099: 0x000030F4 + "0\xef0\x99\x00\x000\xf7" + // 0x30EF3099: 0x000030F7 + "0\xf00\x99\x00\x000\xf8" + // 0x30F03099: 0x000030F8 + "0\xf10\x99\x00\x000\xf9" + // 0x30F13099: 0x000030F9 + "0\xf20\x99\x00\x000\xfa" + // 0x30F23099: 0x000030FA + "0\xfd0\x99\x00\x000\xfe" + // 0x30FD3099: 0x000030FE + "\x10\x99\x10\xba\x00\x01\x10\x9a" + // 0x109910BA: 0x0001109A + "\x10\x9b\x10\xba\x00\x01\x10\x9c" + // 0x109B10BA: 0x0001109C + "\x10\xa5\x10\xba\x00\x01\x10\xab" + // 0x10A510BA: 0x000110AB + "\x111\x11'\x00\x01\x11." + // 0x11311127: 0x0001112E + "\x112\x11'\x00\x01\x11/" + // 0x11321127: 0x0001112F + "\x13G\x13>\x00\x01\x13K" + // 0x1347133E: 0x0001134B + "\x13G\x13W\x00\x01\x13L" + // 0x13471357: 0x0001134C + "\x14\xb9\x14\xba\x00\x01\x14\xbb" + // 0x14B914BA: 0x000114BB + "\x14\xb9\x14\xb0\x00\x01\x14\xbc" + // 0x14B914B0: 0x000114BC + "\x14\xb9\x14\xbd\x00\x01\x14\xbe" + // 0x14B914BD: 0x000114BE + "\x15\xb8\x15\xaf\x00\x01\x15\xba" + // 0x15B815AF: 0x000115BA + "\x15\xb9\x15\xaf\x00\x01\x15\xbb" + // 0x15B915AF: 0x000115BB + "" + // Total size of tables: 55KB (55977 bytes) diff --git a/vendor/golang.org/x/text/width/tables11.0.0.go b/vendor/golang.org/x/text/width/tables11.0.0.go index d6def0e7be5..3c75e428fd0 100644 --- a/vendor/golang.org/x/text/width/tables11.0.0.go +++ b/vendor/golang.org/x/text/width/tables11.0.0.go @@ -1,6 +1,6 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. -// +build go1.13 +// +build go1.13,!go1.14 package width diff --git a/vendor/golang.org/x/text/width/tables12.0.0.go b/vendor/golang.org/x/text/width/tables12.0.0.go new file mode 100644 index 00000000000..5c859677a79 --- /dev/null +++ b/vendor/golang.org/x/text/width/tables12.0.0.go @@ -0,0 +1,1350 @@ +// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. + +// +build go1.14 + +package width + +// UnicodeVersion is the Unicode version from which the tables in this package are derived. +const UnicodeVersion = "12.0.0" + +// lookup returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *widthTrie) lookup(s []byte) (v uint16, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return widthValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := widthIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := widthIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = widthIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := widthIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = widthIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = widthIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *widthTrie) lookupUnsafe(s []byte) uint16 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return widthValues[c0] + } + i := widthIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = widthIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = widthIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// lookupString returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *widthTrie) lookupString(s string) (v uint16, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return widthValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := widthIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := widthIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = widthIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := widthIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = widthIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = widthIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *widthTrie) lookupStringUnsafe(s string) uint16 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return widthValues[c0] + } + i := widthIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = widthIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = widthIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// widthTrie. Total size: 14720 bytes (14.38 KiB). Checksum: 3f4f2516ded5489b. +type widthTrie struct{} + +func newWidthTrie(i int) *widthTrie { + return &widthTrie{} +} + +// lookupValue determines the type of block n and looks up the value for b. +func (t *widthTrie) lookupValue(n uint32, b byte) uint16 { + switch { + default: + return uint16(widthValues[n<<6+uint32(b)]) + } +} + +// widthValues: 104 blocks, 6656 entries, 13312 bytes +// The third block is the zero block. +var widthValues = [6656]uint16{ + // Block 0x0, offset 0x0 + 0x20: 0x6001, 0x21: 0x6002, 0x22: 0x6002, 0x23: 0x6002, + 0x24: 0x6002, 0x25: 0x6002, 0x26: 0x6002, 0x27: 0x6002, 0x28: 0x6002, 0x29: 0x6002, + 0x2a: 0x6002, 0x2b: 0x6002, 0x2c: 0x6002, 0x2d: 0x6002, 0x2e: 0x6002, 0x2f: 0x6002, + 0x30: 0x6002, 0x31: 0x6002, 0x32: 0x6002, 0x33: 0x6002, 0x34: 0x6002, 0x35: 0x6002, + 0x36: 0x6002, 0x37: 0x6002, 0x38: 0x6002, 0x39: 0x6002, 0x3a: 0x6002, 0x3b: 0x6002, + 0x3c: 0x6002, 0x3d: 0x6002, 0x3e: 0x6002, 0x3f: 0x6002, + // Block 0x1, offset 0x40 + 0x40: 0x6003, 0x41: 0x6003, 0x42: 0x6003, 0x43: 0x6003, 0x44: 0x6003, 0x45: 0x6003, + 0x46: 0x6003, 0x47: 0x6003, 0x48: 0x6003, 0x49: 0x6003, 0x4a: 0x6003, 0x4b: 0x6003, + 0x4c: 0x6003, 0x4d: 0x6003, 0x4e: 0x6003, 0x4f: 0x6003, 0x50: 0x6003, 0x51: 0x6003, + 0x52: 0x6003, 0x53: 0x6003, 0x54: 0x6003, 0x55: 0x6003, 0x56: 0x6003, 0x57: 0x6003, + 0x58: 0x6003, 0x59: 0x6003, 0x5a: 0x6003, 0x5b: 0x6003, 0x5c: 0x6003, 0x5d: 0x6003, + 0x5e: 0x6003, 0x5f: 0x6003, 0x60: 0x6004, 0x61: 0x6004, 0x62: 0x6004, 0x63: 0x6004, + 0x64: 0x6004, 0x65: 0x6004, 0x66: 0x6004, 0x67: 0x6004, 0x68: 0x6004, 0x69: 0x6004, + 0x6a: 0x6004, 0x6b: 0x6004, 0x6c: 0x6004, 0x6d: 0x6004, 0x6e: 0x6004, 0x6f: 0x6004, + 0x70: 0x6004, 0x71: 0x6004, 0x72: 0x6004, 0x73: 0x6004, 0x74: 0x6004, 0x75: 0x6004, + 0x76: 0x6004, 0x77: 0x6004, 0x78: 0x6004, 0x79: 0x6004, 0x7a: 0x6004, 0x7b: 0x6004, + 0x7c: 0x6004, 0x7d: 0x6004, 0x7e: 0x6004, + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xe1: 0x2000, 0xe2: 0x6005, 0xe3: 0x6005, + 0xe4: 0x2000, 0xe5: 0x6006, 0xe6: 0x6005, 0xe7: 0x2000, 0xe8: 0x2000, + 0xea: 0x2000, 0xec: 0x6007, 0xed: 0x2000, 0xee: 0x2000, 0xef: 0x6008, + 0xf0: 0x2000, 0xf1: 0x2000, 0xf2: 0x2000, 0xf3: 0x2000, 0xf4: 0x2000, + 0xf6: 0x2000, 0xf7: 0x2000, 0xf8: 0x2000, 0xf9: 0x2000, 0xfa: 0x2000, + 0xfc: 0x2000, 0xfd: 0x2000, 0xfe: 0x2000, 0xff: 0x2000, + // Block 0x4, offset 0x100 + 0x106: 0x2000, + 0x110: 0x2000, + 0x117: 0x2000, + 0x118: 0x2000, + 0x11e: 0x2000, 0x11f: 0x2000, 0x120: 0x2000, 0x121: 0x2000, + 0x126: 0x2000, 0x128: 0x2000, 0x129: 0x2000, + 0x12a: 0x2000, 0x12c: 0x2000, 0x12d: 0x2000, + 0x130: 0x2000, 0x132: 0x2000, 0x133: 0x2000, + 0x137: 0x2000, 0x138: 0x2000, 0x139: 0x2000, 0x13a: 0x2000, + 0x13c: 0x2000, 0x13e: 0x2000, + // Block 0x5, offset 0x140 + 0x141: 0x2000, + 0x151: 0x2000, + 0x153: 0x2000, + 0x15b: 0x2000, + 0x166: 0x2000, 0x167: 0x2000, + 0x16b: 0x2000, + 0x171: 0x2000, 0x172: 0x2000, 0x173: 0x2000, + 0x178: 0x2000, + 0x17f: 0x2000, + // Block 0x6, offset 0x180 + 0x180: 0x2000, 0x181: 0x2000, 0x182: 0x2000, 0x184: 0x2000, + 0x188: 0x2000, 0x189: 0x2000, 0x18a: 0x2000, 0x18b: 0x2000, + 0x18d: 0x2000, + 0x192: 0x2000, 0x193: 0x2000, + 0x1a6: 0x2000, 0x1a7: 0x2000, + 0x1ab: 0x2000, + // Block 0x7, offset 0x1c0 + 0x1ce: 0x2000, 0x1d0: 0x2000, + 0x1d2: 0x2000, 0x1d4: 0x2000, 0x1d6: 0x2000, + 0x1d8: 0x2000, 0x1da: 0x2000, 0x1dc: 0x2000, + // Block 0x8, offset 0x200 + 0x211: 0x2000, + 0x221: 0x2000, + // Block 0x9, offset 0x240 + 0x244: 0x2000, + 0x247: 0x2000, 0x249: 0x2000, 0x24a: 0x2000, 0x24b: 0x2000, + 0x24d: 0x2000, 0x250: 0x2000, + 0x258: 0x2000, 0x259: 0x2000, 0x25a: 0x2000, 0x25b: 0x2000, 0x25d: 0x2000, + 0x25f: 0x2000, + // Block 0xa, offset 0x280 + 0x280: 0x2000, 0x281: 0x2000, 0x282: 0x2000, 0x283: 0x2000, 0x284: 0x2000, 0x285: 0x2000, + 0x286: 0x2000, 0x287: 0x2000, 0x288: 0x2000, 0x289: 0x2000, 0x28a: 0x2000, 0x28b: 0x2000, + 0x28c: 0x2000, 0x28d: 0x2000, 0x28e: 0x2000, 0x28f: 0x2000, 0x290: 0x2000, 0x291: 0x2000, + 0x292: 0x2000, 0x293: 0x2000, 0x294: 0x2000, 0x295: 0x2000, 0x296: 0x2000, 0x297: 0x2000, + 0x298: 0x2000, 0x299: 0x2000, 0x29a: 0x2000, 0x29b: 0x2000, 0x29c: 0x2000, 0x29d: 0x2000, + 0x29e: 0x2000, 0x29f: 0x2000, 0x2a0: 0x2000, 0x2a1: 0x2000, 0x2a2: 0x2000, 0x2a3: 0x2000, + 0x2a4: 0x2000, 0x2a5: 0x2000, 0x2a6: 0x2000, 0x2a7: 0x2000, 0x2a8: 0x2000, 0x2a9: 0x2000, + 0x2aa: 0x2000, 0x2ab: 0x2000, 0x2ac: 0x2000, 0x2ad: 0x2000, 0x2ae: 0x2000, 0x2af: 0x2000, + 0x2b0: 0x2000, 0x2b1: 0x2000, 0x2b2: 0x2000, 0x2b3: 0x2000, 0x2b4: 0x2000, 0x2b5: 0x2000, + 0x2b6: 0x2000, 0x2b7: 0x2000, 0x2b8: 0x2000, 0x2b9: 0x2000, 0x2ba: 0x2000, 0x2bb: 0x2000, + 0x2bc: 0x2000, 0x2bd: 0x2000, 0x2be: 0x2000, 0x2bf: 0x2000, + // Block 0xb, offset 0x2c0 + 0x2c0: 0x2000, 0x2c1: 0x2000, 0x2c2: 0x2000, 0x2c3: 0x2000, 0x2c4: 0x2000, 0x2c5: 0x2000, + 0x2c6: 0x2000, 0x2c7: 0x2000, 0x2c8: 0x2000, 0x2c9: 0x2000, 0x2ca: 0x2000, 0x2cb: 0x2000, + 0x2cc: 0x2000, 0x2cd: 0x2000, 0x2ce: 0x2000, 0x2cf: 0x2000, 0x2d0: 0x2000, 0x2d1: 0x2000, + 0x2d2: 0x2000, 0x2d3: 0x2000, 0x2d4: 0x2000, 0x2d5: 0x2000, 0x2d6: 0x2000, 0x2d7: 0x2000, + 0x2d8: 0x2000, 0x2d9: 0x2000, 0x2da: 0x2000, 0x2db: 0x2000, 0x2dc: 0x2000, 0x2dd: 0x2000, + 0x2de: 0x2000, 0x2df: 0x2000, 0x2e0: 0x2000, 0x2e1: 0x2000, 0x2e2: 0x2000, 0x2e3: 0x2000, + 0x2e4: 0x2000, 0x2e5: 0x2000, 0x2e6: 0x2000, 0x2e7: 0x2000, 0x2e8: 0x2000, 0x2e9: 0x2000, + 0x2ea: 0x2000, 0x2eb: 0x2000, 0x2ec: 0x2000, 0x2ed: 0x2000, 0x2ee: 0x2000, 0x2ef: 0x2000, + // Block 0xc, offset 0x300 + 0x311: 0x2000, + 0x312: 0x2000, 0x313: 0x2000, 0x314: 0x2000, 0x315: 0x2000, 0x316: 0x2000, 0x317: 0x2000, + 0x318: 0x2000, 0x319: 0x2000, 0x31a: 0x2000, 0x31b: 0x2000, 0x31c: 0x2000, 0x31d: 0x2000, + 0x31e: 0x2000, 0x31f: 0x2000, 0x320: 0x2000, 0x321: 0x2000, 0x323: 0x2000, + 0x324: 0x2000, 0x325: 0x2000, 0x326: 0x2000, 0x327: 0x2000, 0x328: 0x2000, 0x329: 0x2000, + 0x331: 0x2000, 0x332: 0x2000, 0x333: 0x2000, 0x334: 0x2000, 0x335: 0x2000, + 0x336: 0x2000, 0x337: 0x2000, 0x338: 0x2000, 0x339: 0x2000, 0x33a: 0x2000, 0x33b: 0x2000, + 0x33c: 0x2000, 0x33d: 0x2000, 0x33e: 0x2000, 0x33f: 0x2000, + // Block 0xd, offset 0x340 + 0x340: 0x2000, 0x341: 0x2000, 0x343: 0x2000, 0x344: 0x2000, 0x345: 0x2000, + 0x346: 0x2000, 0x347: 0x2000, 0x348: 0x2000, 0x349: 0x2000, + // Block 0xe, offset 0x380 + 0x381: 0x2000, + 0x390: 0x2000, 0x391: 0x2000, + 0x392: 0x2000, 0x393: 0x2000, 0x394: 0x2000, 0x395: 0x2000, 0x396: 0x2000, 0x397: 0x2000, + 0x398: 0x2000, 0x399: 0x2000, 0x39a: 0x2000, 0x39b: 0x2000, 0x39c: 0x2000, 0x39d: 0x2000, + 0x39e: 0x2000, 0x39f: 0x2000, 0x3a0: 0x2000, 0x3a1: 0x2000, 0x3a2: 0x2000, 0x3a3: 0x2000, + 0x3a4: 0x2000, 0x3a5: 0x2000, 0x3a6: 0x2000, 0x3a7: 0x2000, 0x3a8: 0x2000, 0x3a9: 0x2000, + 0x3aa: 0x2000, 0x3ab: 0x2000, 0x3ac: 0x2000, 0x3ad: 0x2000, 0x3ae: 0x2000, 0x3af: 0x2000, + 0x3b0: 0x2000, 0x3b1: 0x2000, 0x3b2: 0x2000, 0x3b3: 0x2000, 0x3b4: 0x2000, 0x3b5: 0x2000, + 0x3b6: 0x2000, 0x3b7: 0x2000, 0x3b8: 0x2000, 0x3b9: 0x2000, 0x3ba: 0x2000, 0x3bb: 0x2000, + 0x3bc: 0x2000, 0x3bd: 0x2000, 0x3be: 0x2000, 0x3bf: 0x2000, + // Block 0xf, offset 0x3c0 + 0x3c0: 0x2000, 0x3c1: 0x2000, 0x3c2: 0x2000, 0x3c3: 0x2000, 0x3c4: 0x2000, 0x3c5: 0x2000, + 0x3c6: 0x2000, 0x3c7: 0x2000, 0x3c8: 0x2000, 0x3c9: 0x2000, 0x3ca: 0x2000, 0x3cb: 0x2000, + 0x3cc: 0x2000, 0x3cd: 0x2000, 0x3ce: 0x2000, 0x3cf: 0x2000, 0x3d1: 0x2000, + // Block 0x10, offset 0x400 + 0x400: 0x4000, 0x401: 0x4000, 0x402: 0x4000, 0x403: 0x4000, 0x404: 0x4000, 0x405: 0x4000, + 0x406: 0x4000, 0x407: 0x4000, 0x408: 0x4000, 0x409: 0x4000, 0x40a: 0x4000, 0x40b: 0x4000, + 0x40c: 0x4000, 0x40d: 0x4000, 0x40e: 0x4000, 0x40f: 0x4000, 0x410: 0x4000, 0x411: 0x4000, + 0x412: 0x4000, 0x413: 0x4000, 0x414: 0x4000, 0x415: 0x4000, 0x416: 0x4000, 0x417: 0x4000, + 0x418: 0x4000, 0x419: 0x4000, 0x41a: 0x4000, 0x41b: 0x4000, 0x41c: 0x4000, 0x41d: 0x4000, + 0x41e: 0x4000, 0x41f: 0x4000, 0x420: 0x4000, 0x421: 0x4000, 0x422: 0x4000, 0x423: 0x4000, + 0x424: 0x4000, 0x425: 0x4000, 0x426: 0x4000, 0x427: 0x4000, 0x428: 0x4000, 0x429: 0x4000, + 0x42a: 0x4000, 0x42b: 0x4000, 0x42c: 0x4000, 0x42d: 0x4000, 0x42e: 0x4000, 0x42f: 0x4000, + 0x430: 0x4000, 0x431: 0x4000, 0x432: 0x4000, 0x433: 0x4000, 0x434: 0x4000, 0x435: 0x4000, + 0x436: 0x4000, 0x437: 0x4000, 0x438: 0x4000, 0x439: 0x4000, 0x43a: 0x4000, 0x43b: 0x4000, + 0x43c: 0x4000, 0x43d: 0x4000, 0x43e: 0x4000, 0x43f: 0x4000, + // Block 0x11, offset 0x440 + 0x440: 0x4000, 0x441: 0x4000, 0x442: 0x4000, 0x443: 0x4000, 0x444: 0x4000, 0x445: 0x4000, + 0x446: 0x4000, 0x447: 0x4000, 0x448: 0x4000, 0x449: 0x4000, 0x44a: 0x4000, 0x44b: 0x4000, + 0x44c: 0x4000, 0x44d: 0x4000, 0x44e: 0x4000, 0x44f: 0x4000, 0x450: 0x4000, 0x451: 0x4000, + 0x452: 0x4000, 0x453: 0x4000, 0x454: 0x4000, 0x455: 0x4000, 0x456: 0x4000, 0x457: 0x4000, + 0x458: 0x4000, 0x459: 0x4000, 0x45a: 0x4000, 0x45b: 0x4000, 0x45c: 0x4000, 0x45d: 0x4000, + 0x45e: 0x4000, 0x45f: 0x4000, + // Block 0x12, offset 0x480 + 0x490: 0x2000, + 0x493: 0x2000, 0x494: 0x2000, 0x495: 0x2000, 0x496: 0x2000, + 0x498: 0x2000, 0x499: 0x2000, 0x49c: 0x2000, 0x49d: 0x2000, + 0x4a0: 0x2000, 0x4a1: 0x2000, 0x4a2: 0x2000, + 0x4a4: 0x2000, 0x4a5: 0x2000, 0x4a6: 0x2000, 0x4a7: 0x2000, + 0x4b0: 0x2000, 0x4b2: 0x2000, 0x4b3: 0x2000, 0x4b5: 0x2000, + 0x4bb: 0x2000, + 0x4be: 0x2000, + // Block 0x13, offset 0x4c0 + 0x4f4: 0x2000, + 0x4ff: 0x2000, + // Block 0x14, offset 0x500 + 0x501: 0x2000, 0x502: 0x2000, 0x503: 0x2000, 0x504: 0x2000, + 0x529: 0xa009, + 0x52c: 0x2000, + // Block 0x15, offset 0x540 + 0x543: 0x2000, 0x545: 0x2000, + 0x549: 0x2000, + 0x553: 0x2000, 0x556: 0x2000, + 0x561: 0x2000, 0x562: 0x2000, + 0x566: 0x2000, + 0x56b: 0x2000, + // Block 0x16, offset 0x580 + 0x593: 0x2000, 0x594: 0x2000, + 0x59b: 0x2000, 0x59c: 0x2000, 0x59d: 0x2000, + 0x59e: 0x2000, 0x5a0: 0x2000, 0x5a1: 0x2000, 0x5a2: 0x2000, 0x5a3: 0x2000, + 0x5a4: 0x2000, 0x5a5: 0x2000, 0x5a6: 0x2000, 0x5a7: 0x2000, 0x5a8: 0x2000, 0x5a9: 0x2000, + 0x5aa: 0x2000, 0x5ab: 0x2000, + 0x5b0: 0x2000, 0x5b1: 0x2000, 0x5b2: 0x2000, 0x5b3: 0x2000, 0x5b4: 0x2000, 0x5b5: 0x2000, + 0x5b6: 0x2000, 0x5b7: 0x2000, 0x5b8: 0x2000, 0x5b9: 0x2000, + // Block 0x17, offset 0x5c0 + 0x5c9: 0x2000, + 0x5d0: 0x200a, 0x5d1: 0x200b, + 0x5d2: 0x200a, 0x5d3: 0x200c, 0x5d4: 0x2000, 0x5d5: 0x2000, 0x5d6: 0x2000, 0x5d7: 0x2000, + 0x5d8: 0x2000, 0x5d9: 0x2000, + 0x5f8: 0x2000, 0x5f9: 0x2000, + // Block 0x18, offset 0x600 + 0x612: 0x2000, 0x614: 0x2000, + 0x627: 0x2000, + // Block 0x19, offset 0x640 + 0x640: 0x2000, 0x642: 0x2000, 0x643: 0x2000, + 0x647: 0x2000, 0x648: 0x2000, 0x64b: 0x2000, + 0x64f: 0x2000, 0x651: 0x2000, + 0x655: 0x2000, + 0x65a: 0x2000, 0x65d: 0x2000, + 0x65e: 0x2000, 0x65f: 0x2000, 0x660: 0x2000, 0x663: 0x2000, + 0x665: 0x2000, 0x667: 0x2000, 0x668: 0x2000, 0x669: 0x2000, + 0x66a: 0x2000, 0x66b: 0x2000, 0x66c: 0x2000, 0x66e: 0x2000, + 0x674: 0x2000, 0x675: 0x2000, + 0x676: 0x2000, 0x677: 0x2000, + 0x67c: 0x2000, 0x67d: 0x2000, + // Block 0x1a, offset 0x680 + 0x688: 0x2000, + 0x68c: 0x2000, + 0x692: 0x2000, + 0x6a0: 0x2000, 0x6a1: 0x2000, + 0x6a4: 0x2000, 0x6a5: 0x2000, 0x6a6: 0x2000, 0x6a7: 0x2000, + 0x6aa: 0x2000, 0x6ab: 0x2000, 0x6ae: 0x2000, 0x6af: 0x2000, + // Block 0x1b, offset 0x6c0 + 0x6c2: 0x2000, 0x6c3: 0x2000, + 0x6c6: 0x2000, 0x6c7: 0x2000, + 0x6d5: 0x2000, + 0x6d9: 0x2000, + 0x6e5: 0x2000, + 0x6ff: 0x2000, + // Block 0x1c, offset 0x700 + 0x712: 0x2000, + 0x71a: 0x4000, 0x71b: 0x4000, + 0x729: 0x4000, + 0x72a: 0x4000, + // Block 0x1d, offset 0x740 + 0x769: 0x4000, + 0x76a: 0x4000, 0x76b: 0x4000, 0x76c: 0x4000, + 0x770: 0x4000, 0x773: 0x4000, + // Block 0x1e, offset 0x780 + 0x7a0: 0x2000, 0x7a1: 0x2000, 0x7a2: 0x2000, 0x7a3: 0x2000, + 0x7a4: 0x2000, 0x7a5: 0x2000, 0x7a6: 0x2000, 0x7a7: 0x2000, 0x7a8: 0x2000, 0x7a9: 0x2000, + 0x7aa: 0x2000, 0x7ab: 0x2000, 0x7ac: 0x2000, 0x7ad: 0x2000, 0x7ae: 0x2000, 0x7af: 0x2000, + 0x7b0: 0x2000, 0x7b1: 0x2000, 0x7b2: 0x2000, 0x7b3: 0x2000, 0x7b4: 0x2000, 0x7b5: 0x2000, + 0x7b6: 0x2000, 0x7b7: 0x2000, 0x7b8: 0x2000, 0x7b9: 0x2000, 0x7ba: 0x2000, 0x7bb: 0x2000, + 0x7bc: 0x2000, 0x7bd: 0x2000, 0x7be: 0x2000, 0x7bf: 0x2000, + // Block 0x1f, offset 0x7c0 + 0x7c0: 0x2000, 0x7c1: 0x2000, 0x7c2: 0x2000, 0x7c3: 0x2000, 0x7c4: 0x2000, 0x7c5: 0x2000, + 0x7c6: 0x2000, 0x7c7: 0x2000, 0x7c8: 0x2000, 0x7c9: 0x2000, 0x7ca: 0x2000, 0x7cb: 0x2000, + 0x7cc: 0x2000, 0x7cd: 0x2000, 0x7ce: 0x2000, 0x7cf: 0x2000, 0x7d0: 0x2000, 0x7d1: 0x2000, + 0x7d2: 0x2000, 0x7d3: 0x2000, 0x7d4: 0x2000, 0x7d5: 0x2000, 0x7d6: 0x2000, 0x7d7: 0x2000, + 0x7d8: 0x2000, 0x7d9: 0x2000, 0x7da: 0x2000, 0x7db: 0x2000, 0x7dc: 0x2000, 0x7dd: 0x2000, + 0x7de: 0x2000, 0x7df: 0x2000, 0x7e0: 0x2000, 0x7e1: 0x2000, 0x7e2: 0x2000, 0x7e3: 0x2000, + 0x7e4: 0x2000, 0x7e5: 0x2000, 0x7e6: 0x2000, 0x7e7: 0x2000, 0x7e8: 0x2000, 0x7e9: 0x2000, + 0x7eb: 0x2000, 0x7ec: 0x2000, 0x7ed: 0x2000, 0x7ee: 0x2000, 0x7ef: 0x2000, + 0x7f0: 0x2000, 0x7f1: 0x2000, 0x7f2: 0x2000, 0x7f3: 0x2000, 0x7f4: 0x2000, 0x7f5: 0x2000, + 0x7f6: 0x2000, 0x7f7: 0x2000, 0x7f8: 0x2000, 0x7f9: 0x2000, 0x7fa: 0x2000, 0x7fb: 0x2000, + 0x7fc: 0x2000, 0x7fd: 0x2000, 0x7fe: 0x2000, 0x7ff: 0x2000, + // Block 0x20, offset 0x800 + 0x800: 0x2000, 0x801: 0x2000, 0x802: 0x200d, 0x803: 0x2000, 0x804: 0x2000, 0x805: 0x2000, + 0x806: 0x2000, 0x807: 0x2000, 0x808: 0x2000, 0x809: 0x2000, 0x80a: 0x2000, 0x80b: 0x2000, + 0x80c: 0x2000, 0x80d: 0x2000, 0x80e: 0x2000, 0x80f: 0x2000, 0x810: 0x2000, 0x811: 0x2000, + 0x812: 0x2000, 0x813: 0x2000, 0x814: 0x2000, 0x815: 0x2000, 0x816: 0x2000, 0x817: 0x2000, + 0x818: 0x2000, 0x819: 0x2000, 0x81a: 0x2000, 0x81b: 0x2000, 0x81c: 0x2000, 0x81d: 0x2000, + 0x81e: 0x2000, 0x81f: 0x2000, 0x820: 0x2000, 0x821: 0x2000, 0x822: 0x2000, 0x823: 0x2000, + 0x824: 0x2000, 0x825: 0x2000, 0x826: 0x2000, 0x827: 0x2000, 0x828: 0x2000, 0x829: 0x2000, + 0x82a: 0x2000, 0x82b: 0x2000, 0x82c: 0x2000, 0x82d: 0x2000, 0x82e: 0x2000, 0x82f: 0x2000, + 0x830: 0x2000, 0x831: 0x2000, 0x832: 0x2000, 0x833: 0x2000, 0x834: 0x2000, 0x835: 0x2000, + 0x836: 0x2000, 0x837: 0x2000, 0x838: 0x2000, 0x839: 0x2000, 0x83a: 0x2000, 0x83b: 0x2000, + 0x83c: 0x2000, 0x83d: 0x2000, 0x83e: 0x2000, 0x83f: 0x2000, + // Block 0x21, offset 0x840 + 0x840: 0x2000, 0x841: 0x2000, 0x842: 0x2000, 0x843: 0x2000, 0x844: 0x2000, 0x845: 0x2000, + 0x846: 0x2000, 0x847: 0x2000, 0x848: 0x2000, 0x849: 0x2000, 0x84a: 0x2000, 0x84b: 0x2000, + 0x850: 0x2000, 0x851: 0x2000, + 0x852: 0x2000, 0x853: 0x2000, 0x854: 0x2000, 0x855: 0x2000, 0x856: 0x2000, 0x857: 0x2000, + 0x858: 0x2000, 0x859: 0x2000, 0x85a: 0x2000, 0x85b: 0x2000, 0x85c: 0x2000, 0x85d: 0x2000, + 0x85e: 0x2000, 0x85f: 0x2000, 0x860: 0x2000, 0x861: 0x2000, 0x862: 0x2000, 0x863: 0x2000, + 0x864: 0x2000, 0x865: 0x2000, 0x866: 0x2000, 0x867: 0x2000, 0x868: 0x2000, 0x869: 0x2000, + 0x86a: 0x2000, 0x86b: 0x2000, 0x86c: 0x2000, 0x86d: 0x2000, 0x86e: 0x2000, 0x86f: 0x2000, + 0x870: 0x2000, 0x871: 0x2000, 0x872: 0x2000, 0x873: 0x2000, + // Block 0x22, offset 0x880 + 0x880: 0x2000, 0x881: 0x2000, 0x882: 0x2000, 0x883: 0x2000, 0x884: 0x2000, 0x885: 0x2000, + 0x886: 0x2000, 0x887: 0x2000, 0x888: 0x2000, 0x889: 0x2000, 0x88a: 0x2000, 0x88b: 0x2000, + 0x88c: 0x2000, 0x88d: 0x2000, 0x88e: 0x2000, 0x88f: 0x2000, + 0x892: 0x2000, 0x893: 0x2000, 0x894: 0x2000, 0x895: 0x2000, + 0x8a0: 0x200e, 0x8a1: 0x2000, 0x8a3: 0x2000, + 0x8a4: 0x2000, 0x8a5: 0x2000, 0x8a6: 0x2000, 0x8a7: 0x2000, 0x8a8: 0x2000, 0x8a9: 0x2000, + 0x8b2: 0x2000, 0x8b3: 0x2000, + 0x8b6: 0x2000, 0x8b7: 0x2000, + 0x8bc: 0x2000, 0x8bd: 0x2000, + // Block 0x23, offset 0x8c0 + 0x8c0: 0x2000, 0x8c1: 0x2000, + 0x8c6: 0x2000, 0x8c7: 0x2000, 0x8c8: 0x2000, 0x8cb: 0x200f, + 0x8ce: 0x2000, 0x8cf: 0x2000, 0x8d0: 0x2000, 0x8d1: 0x2000, + 0x8e2: 0x2000, 0x8e3: 0x2000, + 0x8e4: 0x2000, 0x8e5: 0x2000, + 0x8ef: 0x2000, + 0x8fd: 0x4000, 0x8fe: 0x4000, + // Block 0x24, offset 0x900 + 0x905: 0x2000, + 0x906: 0x2000, 0x909: 0x2000, + 0x90e: 0x2000, 0x90f: 0x2000, + 0x914: 0x4000, 0x915: 0x4000, + 0x91c: 0x2000, + 0x91e: 0x2000, + // Block 0x25, offset 0x940 + 0x940: 0x2000, 0x942: 0x2000, + 0x948: 0x4000, 0x949: 0x4000, 0x94a: 0x4000, 0x94b: 0x4000, + 0x94c: 0x4000, 0x94d: 0x4000, 0x94e: 0x4000, 0x94f: 0x4000, 0x950: 0x4000, 0x951: 0x4000, + 0x952: 0x4000, 0x953: 0x4000, + 0x960: 0x2000, 0x961: 0x2000, 0x963: 0x2000, + 0x964: 0x2000, 0x965: 0x2000, 0x967: 0x2000, 0x968: 0x2000, 0x969: 0x2000, + 0x96a: 0x2000, 0x96c: 0x2000, 0x96d: 0x2000, 0x96f: 0x2000, + 0x97f: 0x4000, + // Block 0x26, offset 0x980 + 0x993: 0x4000, + 0x99e: 0x2000, 0x99f: 0x2000, 0x9a1: 0x4000, + 0x9aa: 0x4000, 0x9ab: 0x4000, + 0x9bd: 0x4000, 0x9be: 0x4000, 0x9bf: 0x2000, + // Block 0x27, offset 0x9c0 + 0x9c4: 0x4000, 0x9c5: 0x4000, + 0x9c6: 0x2000, 0x9c7: 0x2000, 0x9c8: 0x2000, 0x9c9: 0x2000, 0x9ca: 0x2000, 0x9cb: 0x2000, + 0x9cc: 0x2000, 0x9cd: 0x2000, 0x9ce: 0x4000, 0x9cf: 0x2000, 0x9d0: 0x2000, 0x9d1: 0x2000, + 0x9d2: 0x2000, 0x9d3: 0x2000, 0x9d4: 0x4000, 0x9d5: 0x2000, 0x9d6: 0x2000, 0x9d7: 0x2000, + 0x9d8: 0x2000, 0x9d9: 0x2000, 0x9da: 0x2000, 0x9db: 0x2000, 0x9dc: 0x2000, 0x9dd: 0x2000, + 0x9de: 0x2000, 0x9df: 0x2000, 0x9e0: 0x2000, 0x9e1: 0x2000, 0x9e3: 0x2000, + 0x9e8: 0x2000, 0x9e9: 0x2000, + 0x9ea: 0x4000, 0x9eb: 0x2000, 0x9ec: 0x2000, 0x9ed: 0x2000, 0x9ee: 0x2000, 0x9ef: 0x2000, + 0x9f0: 0x2000, 0x9f1: 0x2000, 0x9f2: 0x4000, 0x9f3: 0x4000, 0x9f4: 0x2000, 0x9f5: 0x4000, + 0x9f6: 0x2000, 0x9f7: 0x2000, 0x9f8: 0x2000, 0x9f9: 0x2000, 0x9fa: 0x4000, 0x9fb: 0x2000, + 0x9fc: 0x2000, 0x9fd: 0x4000, 0x9fe: 0x2000, 0x9ff: 0x2000, + // Block 0x28, offset 0xa00 + 0xa05: 0x4000, + 0xa0a: 0x4000, 0xa0b: 0x4000, + 0xa28: 0x4000, + 0xa3d: 0x2000, + // Block 0x29, offset 0xa40 + 0xa4c: 0x4000, 0xa4e: 0x4000, + 0xa53: 0x4000, 0xa54: 0x4000, 0xa55: 0x4000, 0xa57: 0x4000, + 0xa76: 0x2000, 0xa77: 0x2000, 0xa78: 0x2000, 0xa79: 0x2000, 0xa7a: 0x2000, 0xa7b: 0x2000, + 0xa7c: 0x2000, 0xa7d: 0x2000, 0xa7e: 0x2000, 0xa7f: 0x2000, + // Block 0x2a, offset 0xa80 + 0xa95: 0x4000, 0xa96: 0x4000, 0xa97: 0x4000, + 0xab0: 0x4000, + 0xabf: 0x4000, + // Block 0x2b, offset 0xac0 + 0xae6: 0x6000, 0xae7: 0x6000, 0xae8: 0x6000, 0xae9: 0x6000, + 0xaea: 0x6000, 0xaeb: 0x6000, 0xaec: 0x6000, 0xaed: 0x6000, + // Block 0x2c, offset 0xb00 + 0xb05: 0x6010, + 0xb06: 0x6011, + // Block 0x2d, offset 0xb40 + 0xb5b: 0x4000, 0xb5c: 0x4000, + // Block 0x2e, offset 0xb80 + 0xb90: 0x4000, + 0xb95: 0x4000, 0xb96: 0x2000, 0xb97: 0x2000, + 0xb98: 0x2000, 0xb99: 0x2000, + // Block 0x2f, offset 0xbc0 + 0xbc0: 0x4000, 0xbc1: 0x4000, 0xbc2: 0x4000, 0xbc3: 0x4000, 0xbc4: 0x4000, 0xbc5: 0x4000, + 0xbc6: 0x4000, 0xbc7: 0x4000, 0xbc8: 0x4000, 0xbc9: 0x4000, 0xbca: 0x4000, 0xbcb: 0x4000, + 0xbcc: 0x4000, 0xbcd: 0x4000, 0xbce: 0x4000, 0xbcf: 0x4000, 0xbd0: 0x4000, 0xbd1: 0x4000, + 0xbd2: 0x4000, 0xbd3: 0x4000, 0xbd4: 0x4000, 0xbd5: 0x4000, 0xbd6: 0x4000, 0xbd7: 0x4000, + 0xbd8: 0x4000, 0xbd9: 0x4000, 0xbdb: 0x4000, 0xbdc: 0x4000, 0xbdd: 0x4000, + 0xbde: 0x4000, 0xbdf: 0x4000, 0xbe0: 0x4000, 0xbe1: 0x4000, 0xbe2: 0x4000, 0xbe3: 0x4000, + 0xbe4: 0x4000, 0xbe5: 0x4000, 0xbe6: 0x4000, 0xbe7: 0x4000, 0xbe8: 0x4000, 0xbe9: 0x4000, + 0xbea: 0x4000, 0xbeb: 0x4000, 0xbec: 0x4000, 0xbed: 0x4000, 0xbee: 0x4000, 0xbef: 0x4000, + 0xbf0: 0x4000, 0xbf1: 0x4000, 0xbf2: 0x4000, 0xbf3: 0x4000, 0xbf4: 0x4000, 0xbf5: 0x4000, + 0xbf6: 0x4000, 0xbf7: 0x4000, 0xbf8: 0x4000, 0xbf9: 0x4000, 0xbfa: 0x4000, 0xbfb: 0x4000, + 0xbfc: 0x4000, 0xbfd: 0x4000, 0xbfe: 0x4000, 0xbff: 0x4000, + // Block 0x30, offset 0xc00 + 0xc00: 0x4000, 0xc01: 0x4000, 0xc02: 0x4000, 0xc03: 0x4000, 0xc04: 0x4000, 0xc05: 0x4000, + 0xc06: 0x4000, 0xc07: 0x4000, 0xc08: 0x4000, 0xc09: 0x4000, 0xc0a: 0x4000, 0xc0b: 0x4000, + 0xc0c: 0x4000, 0xc0d: 0x4000, 0xc0e: 0x4000, 0xc0f: 0x4000, 0xc10: 0x4000, 0xc11: 0x4000, + 0xc12: 0x4000, 0xc13: 0x4000, 0xc14: 0x4000, 0xc15: 0x4000, 0xc16: 0x4000, 0xc17: 0x4000, + 0xc18: 0x4000, 0xc19: 0x4000, 0xc1a: 0x4000, 0xc1b: 0x4000, 0xc1c: 0x4000, 0xc1d: 0x4000, + 0xc1e: 0x4000, 0xc1f: 0x4000, 0xc20: 0x4000, 0xc21: 0x4000, 0xc22: 0x4000, 0xc23: 0x4000, + 0xc24: 0x4000, 0xc25: 0x4000, 0xc26: 0x4000, 0xc27: 0x4000, 0xc28: 0x4000, 0xc29: 0x4000, + 0xc2a: 0x4000, 0xc2b: 0x4000, 0xc2c: 0x4000, 0xc2d: 0x4000, 0xc2e: 0x4000, 0xc2f: 0x4000, + 0xc30: 0x4000, 0xc31: 0x4000, 0xc32: 0x4000, 0xc33: 0x4000, + // Block 0x31, offset 0xc40 + 0xc40: 0x4000, 0xc41: 0x4000, 0xc42: 0x4000, 0xc43: 0x4000, 0xc44: 0x4000, 0xc45: 0x4000, + 0xc46: 0x4000, 0xc47: 0x4000, 0xc48: 0x4000, 0xc49: 0x4000, 0xc4a: 0x4000, 0xc4b: 0x4000, + 0xc4c: 0x4000, 0xc4d: 0x4000, 0xc4e: 0x4000, 0xc4f: 0x4000, 0xc50: 0x4000, 0xc51: 0x4000, + 0xc52: 0x4000, 0xc53: 0x4000, 0xc54: 0x4000, 0xc55: 0x4000, + 0xc70: 0x4000, 0xc71: 0x4000, 0xc72: 0x4000, 0xc73: 0x4000, 0xc74: 0x4000, 0xc75: 0x4000, + 0xc76: 0x4000, 0xc77: 0x4000, 0xc78: 0x4000, 0xc79: 0x4000, 0xc7a: 0x4000, 0xc7b: 0x4000, + // Block 0x32, offset 0xc80 + 0xc80: 0x9012, 0xc81: 0x4013, 0xc82: 0x4014, 0xc83: 0x4000, 0xc84: 0x4000, 0xc85: 0x4000, + 0xc86: 0x4000, 0xc87: 0x4000, 0xc88: 0x4000, 0xc89: 0x4000, 0xc8a: 0x4000, 0xc8b: 0x4000, + 0xc8c: 0x4015, 0xc8d: 0x4015, 0xc8e: 0x4000, 0xc8f: 0x4000, 0xc90: 0x4000, 0xc91: 0x4000, + 0xc92: 0x4000, 0xc93: 0x4000, 0xc94: 0x4000, 0xc95: 0x4000, 0xc96: 0x4000, 0xc97: 0x4000, + 0xc98: 0x4000, 0xc99: 0x4000, 0xc9a: 0x4000, 0xc9b: 0x4000, 0xc9c: 0x4000, 0xc9d: 0x4000, + 0xc9e: 0x4000, 0xc9f: 0x4000, 0xca0: 0x4000, 0xca1: 0x4000, 0xca2: 0x4000, 0xca3: 0x4000, + 0xca4: 0x4000, 0xca5: 0x4000, 0xca6: 0x4000, 0xca7: 0x4000, 0xca8: 0x4000, 0xca9: 0x4000, + 0xcaa: 0x4000, 0xcab: 0x4000, 0xcac: 0x4000, 0xcad: 0x4000, 0xcae: 0x4000, 0xcaf: 0x4000, + 0xcb0: 0x4000, 0xcb1: 0x4000, 0xcb2: 0x4000, 0xcb3: 0x4000, 0xcb4: 0x4000, 0xcb5: 0x4000, + 0xcb6: 0x4000, 0xcb7: 0x4000, 0xcb8: 0x4000, 0xcb9: 0x4000, 0xcba: 0x4000, 0xcbb: 0x4000, + 0xcbc: 0x4000, 0xcbd: 0x4000, 0xcbe: 0x4000, + // Block 0x33, offset 0xcc0 + 0xcc1: 0x4000, 0xcc2: 0x4000, 0xcc3: 0x4000, 0xcc4: 0x4000, 0xcc5: 0x4000, + 0xcc6: 0x4000, 0xcc7: 0x4000, 0xcc8: 0x4000, 0xcc9: 0x4000, 0xcca: 0x4000, 0xccb: 0x4000, + 0xccc: 0x4000, 0xccd: 0x4000, 0xcce: 0x4000, 0xccf: 0x4000, 0xcd0: 0x4000, 0xcd1: 0x4000, + 0xcd2: 0x4000, 0xcd3: 0x4000, 0xcd4: 0x4000, 0xcd5: 0x4000, 0xcd6: 0x4000, 0xcd7: 0x4000, + 0xcd8: 0x4000, 0xcd9: 0x4000, 0xcda: 0x4000, 0xcdb: 0x4000, 0xcdc: 0x4000, 0xcdd: 0x4000, + 0xcde: 0x4000, 0xcdf: 0x4000, 0xce0: 0x4000, 0xce1: 0x4000, 0xce2: 0x4000, 0xce3: 0x4000, + 0xce4: 0x4000, 0xce5: 0x4000, 0xce6: 0x4000, 0xce7: 0x4000, 0xce8: 0x4000, 0xce9: 0x4000, + 0xcea: 0x4000, 0xceb: 0x4000, 0xcec: 0x4000, 0xced: 0x4000, 0xcee: 0x4000, 0xcef: 0x4000, + 0xcf0: 0x4000, 0xcf1: 0x4000, 0xcf2: 0x4000, 0xcf3: 0x4000, 0xcf4: 0x4000, 0xcf5: 0x4000, + 0xcf6: 0x4000, 0xcf7: 0x4000, 0xcf8: 0x4000, 0xcf9: 0x4000, 0xcfa: 0x4000, 0xcfb: 0x4000, + 0xcfc: 0x4000, 0xcfd: 0x4000, 0xcfe: 0x4000, 0xcff: 0x4000, + // Block 0x34, offset 0xd00 + 0xd00: 0x4000, 0xd01: 0x4000, 0xd02: 0x4000, 0xd03: 0x4000, 0xd04: 0x4000, 0xd05: 0x4000, + 0xd06: 0x4000, 0xd07: 0x4000, 0xd08: 0x4000, 0xd09: 0x4000, 0xd0a: 0x4000, 0xd0b: 0x4000, + 0xd0c: 0x4000, 0xd0d: 0x4000, 0xd0e: 0x4000, 0xd0f: 0x4000, 0xd10: 0x4000, 0xd11: 0x4000, + 0xd12: 0x4000, 0xd13: 0x4000, 0xd14: 0x4000, 0xd15: 0x4000, 0xd16: 0x4000, + 0xd19: 0x4016, 0xd1a: 0x4017, 0xd1b: 0x4000, 0xd1c: 0x4000, 0xd1d: 0x4000, + 0xd1e: 0x4000, 0xd1f: 0x4000, 0xd20: 0x4000, 0xd21: 0x4018, 0xd22: 0x4019, 0xd23: 0x401a, + 0xd24: 0x401b, 0xd25: 0x401c, 0xd26: 0x401d, 0xd27: 0x401e, 0xd28: 0x401f, 0xd29: 0x4020, + 0xd2a: 0x4021, 0xd2b: 0x4022, 0xd2c: 0x4000, 0xd2d: 0x4010, 0xd2e: 0x4000, 0xd2f: 0x4023, + 0xd30: 0x4000, 0xd31: 0x4024, 0xd32: 0x4000, 0xd33: 0x4025, 0xd34: 0x4000, 0xd35: 0x4026, + 0xd36: 0x4000, 0xd37: 0x401a, 0xd38: 0x4000, 0xd39: 0x4027, 0xd3a: 0x4000, 0xd3b: 0x4028, + 0xd3c: 0x4000, 0xd3d: 0x4020, 0xd3e: 0x4000, 0xd3f: 0x4029, + // Block 0x35, offset 0xd40 + 0xd40: 0x4000, 0xd41: 0x402a, 0xd42: 0x4000, 0xd43: 0x402b, 0xd44: 0x402c, 0xd45: 0x4000, + 0xd46: 0x4017, 0xd47: 0x4000, 0xd48: 0x402d, 0xd49: 0x4000, 0xd4a: 0x402e, 0xd4b: 0x402f, + 0xd4c: 0x4030, 0xd4d: 0x4017, 0xd4e: 0x4016, 0xd4f: 0x4017, 0xd50: 0x4000, 0xd51: 0x4000, + 0xd52: 0x4031, 0xd53: 0x4000, 0xd54: 0x4000, 0xd55: 0x4031, 0xd56: 0x4000, 0xd57: 0x4000, + 0xd58: 0x4032, 0xd59: 0x4000, 0xd5a: 0x4000, 0xd5b: 0x4032, 0xd5c: 0x4000, 0xd5d: 0x4000, + 0xd5e: 0x4033, 0xd5f: 0x402e, 0xd60: 0x4034, 0xd61: 0x4035, 0xd62: 0x4034, 0xd63: 0x4036, + 0xd64: 0x4037, 0xd65: 0x4024, 0xd66: 0x4035, 0xd67: 0x4025, 0xd68: 0x4038, 0xd69: 0x4038, + 0xd6a: 0x4039, 0xd6b: 0x4039, 0xd6c: 0x403a, 0xd6d: 0x403a, 0xd6e: 0x4000, 0xd6f: 0x4035, + 0xd70: 0x4000, 0xd71: 0x4000, 0xd72: 0x403b, 0xd73: 0x403c, 0xd74: 0x4000, 0xd75: 0x4000, + 0xd76: 0x4000, 0xd77: 0x4000, 0xd78: 0x4000, 0xd79: 0x4000, 0xd7a: 0x4000, 0xd7b: 0x403d, + 0xd7c: 0x401c, 0xd7d: 0x4000, 0xd7e: 0x4000, 0xd7f: 0x4000, + // Block 0x36, offset 0xd80 + 0xd85: 0x4000, + 0xd86: 0x4000, 0xd87: 0x4000, 0xd88: 0x4000, 0xd89: 0x4000, 0xd8a: 0x4000, 0xd8b: 0x4000, + 0xd8c: 0x4000, 0xd8d: 0x4000, 0xd8e: 0x4000, 0xd8f: 0x4000, 0xd90: 0x4000, 0xd91: 0x4000, + 0xd92: 0x4000, 0xd93: 0x4000, 0xd94: 0x4000, 0xd95: 0x4000, 0xd96: 0x4000, 0xd97: 0x4000, + 0xd98: 0x4000, 0xd99: 0x4000, 0xd9a: 0x4000, 0xd9b: 0x4000, 0xd9c: 0x4000, 0xd9d: 0x4000, + 0xd9e: 0x4000, 0xd9f: 0x4000, 0xda0: 0x4000, 0xda1: 0x4000, 0xda2: 0x4000, 0xda3: 0x4000, + 0xda4: 0x4000, 0xda5: 0x4000, 0xda6: 0x4000, 0xda7: 0x4000, 0xda8: 0x4000, 0xda9: 0x4000, + 0xdaa: 0x4000, 0xdab: 0x4000, 0xdac: 0x4000, 0xdad: 0x4000, 0xdae: 0x4000, 0xdaf: 0x4000, + 0xdb1: 0x403e, 0xdb2: 0x403e, 0xdb3: 0x403e, 0xdb4: 0x403e, 0xdb5: 0x403e, + 0xdb6: 0x403e, 0xdb7: 0x403e, 0xdb8: 0x403e, 0xdb9: 0x403e, 0xdba: 0x403e, 0xdbb: 0x403e, + 0xdbc: 0x403e, 0xdbd: 0x403e, 0xdbe: 0x403e, 0xdbf: 0x403e, + // Block 0x37, offset 0xdc0 + 0xdc0: 0x4037, 0xdc1: 0x4037, 0xdc2: 0x4037, 0xdc3: 0x4037, 0xdc4: 0x4037, 0xdc5: 0x4037, + 0xdc6: 0x4037, 0xdc7: 0x4037, 0xdc8: 0x4037, 0xdc9: 0x4037, 0xdca: 0x4037, 0xdcb: 0x4037, + 0xdcc: 0x4037, 0xdcd: 0x4037, 0xdce: 0x4037, 0xdcf: 0x400e, 0xdd0: 0x403f, 0xdd1: 0x4040, + 0xdd2: 0x4041, 0xdd3: 0x4040, 0xdd4: 0x403f, 0xdd5: 0x4042, 0xdd6: 0x4043, 0xdd7: 0x4044, + 0xdd8: 0x4040, 0xdd9: 0x4041, 0xdda: 0x4040, 0xddb: 0x4045, 0xddc: 0x4009, 0xddd: 0x4045, + 0xdde: 0x4046, 0xddf: 0x4045, 0xde0: 0x4047, 0xde1: 0x400b, 0xde2: 0x400a, 0xde3: 0x400c, + 0xde4: 0x4048, 0xde5: 0x4000, 0xde6: 0x4000, 0xde7: 0x4000, 0xde8: 0x4000, 0xde9: 0x4000, + 0xdea: 0x4000, 0xdeb: 0x4000, 0xdec: 0x4000, 0xded: 0x4000, 0xdee: 0x4000, 0xdef: 0x4000, + 0xdf0: 0x4000, 0xdf1: 0x4000, 0xdf2: 0x4000, 0xdf3: 0x4000, 0xdf4: 0x4000, 0xdf5: 0x4000, + 0xdf6: 0x4000, 0xdf7: 0x4000, 0xdf8: 0x4000, 0xdf9: 0x4000, 0xdfa: 0x4000, 0xdfb: 0x4000, + 0xdfc: 0x4000, 0xdfd: 0x4000, 0xdfe: 0x4000, 0xdff: 0x4000, + // Block 0x38, offset 0xe00 + 0xe00: 0x4000, 0xe01: 0x4000, 0xe02: 0x4000, 0xe03: 0x4000, 0xe04: 0x4000, 0xe05: 0x4000, + 0xe06: 0x4000, 0xe07: 0x4000, 0xe08: 0x4000, 0xe09: 0x4000, 0xe0a: 0x4000, 0xe0b: 0x4000, + 0xe0c: 0x4000, 0xe0d: 0x4000, 0xe0e: 0x4000, 0xe10: 0x4000, 0xe11: 0x4000, + 0xe12: 0x4000, 0xe13: 0x4000, 0xe14: 0x4000, 0xe15: 0x4000, 0xe16: 0x4000, 0xe17: 0x4000, + 0xe18: 0x4000, 0xe19: 0x4000, 0xe1a: 0x4000, 0xe1b: 0x4000, 0xe1c: 0x4000, 0xe1d: 0x4000, + 0xe1e: 0x4000, 0xe1f: 0x4000, 0xe20: 0x4000, 0xe21: 0x4000, 0xe22: 0x4000, 0xe23: 0x4000, + 0xe24: 0x4000, 0xe25: 0x4000, 0xe26: 0x4000, 0xe27: 0x4000, 0xe28: 0x4000, 0xe29: 0x4000, + 0xe2a: 0x4000, 0xe2b: 0x4000, 0xe2c: 0x4000, 0xe2d: 0x4000, 0xe2e: 0x4000, 0xe2f: 0x4000, + 0xe30: 0x4000, 0xe31: 0x4000, 0xe32: 0x4000, 0xe33: 0x4000, 0xe34: 0x4000, 0xe35: 0x4000, + 0xe36: 0x4000, 0xe37: 0x4000, 0xe38: 0x4000, 0xe39: 0x4000, 0xe3a: 0x4000, + // Block 0x39, offset 0xe40 + 0xe40: 0x4000, 0xe41: 0x4000, 0xe42: 0x4000, 0xe43: 0x4000, 0xe44: 0x4000, 0xe45: 0x4000, + 0xe46: 0x4000, 0xe47: 0x4000, 0xe48: 0x4000, 0xe49: 0x4000, 0xe4a: 0x4000, 0xe4b: 0x4000, + 0xe4c: 0x4000, 0xe4d: 0x4000, 0xe4e: 0x4000, 0xe4f: 0x4000, 0xe50: 0x4000, 0xe51: 0x4000, + 0xe52: 0x4000, 0xe53: 0x4000, 0xe54: 0x4000, 0xe55: 0x4000, 0xe56: 0x4000, 0xe57: 0x4000, + 0xe58: 0x4000, 0xe59: 0x4000, 0xe5a: 0x4000, 0xe5b: 0x4000, 0xe5c: 0x4000, 0xe5d: 0x4000, + 0xe5e: 0x4000, 0xe5f: 0x4000, 0xe60: 0x4000, 0xe61: 0x4000, 0xe62: 0x4000, 0xe63: 0x4000, + 0xe70: 0x4000, 0xe71: 0x4000, 0xe72: 0x4000, 0xe73: 0x4000, 0xe74: 0x4000, 0xe75: 0x4000, + 0xe76: 0x4000, 0xe77: 0x4000, 0xe78: 0x4000, 0xe79: 0x4000, 0xe7a: 0x4000, 0xe7b: 0x4000, + 0xe7c: 0x4000, 0xe7d: 0x4000, 0xe7e: 0x4000, 0xe7f: 0x4000, + // Block 0x3a, offset 0xe80 + 0xe80: 0x4000, 0xe81: 0x4000, 0xe82: 0x4000, 0xe83: 0x4000, 0xe84: 0x4000, 0xe85: 0x4000, + 0xe86: 0x4000, 0xe87: 0x4000, 0xe88: 0x4000, 0xe89: 0x4000, 0xe8a: 0x4000, 0xe8b: 0x4000, + 0xe8c: 0x4000, 0xe8d: 0x4000, 0xe8e: 0x4000, 0xe8f: 0x4000, 0xe90: 0x4000, 0xe91: 0x4000, + 0xe92: 0x4000, 0xe93: 0x4000, 0xe94: 0x4000, 0xe95: 0x4000, 0xe96: 0x4000, 0xe97: 0x4000, + 0xe98: 0x4000, 0xe99: 0x4000, 0xe9a: 0x4000, 0xe9b: 0x4000, 0xe9c: 0x4000, 0xe9d: 0x4000, + 0xe9e: 0x4000, 0xea0: 0x4000, 0xea1: 0x4000, 0xea2: 0x4000, 0xea3: 0x4000, + 0xea4: 0x4000, 0xea5: 0x4000, 0xea6: 0x4000, 0xea7: 0x4000, 0xea8: 0x4000, 0xea9: 0x4000, + 0xeaa: 0x4000, 0xeab: 0x4000, 0xeac: 0x4000, 0xead: 0x4000, 0xeae: 0x4000, 0xeaf: 0x4000, + 0xeb0: 0x4000, 0xeb1: 0x4000, 0xeb2: 0x4000, 0xeb3: 0x4000, 0xeb4: 0x4000, 0xeb5: 0x4000, + 0xeb6: 0x4000, 0xeb7: 0x4000, 0xeb8: 0x4000, 0xeb9: 0x4000, 0xeba: 0x4000, 0xebb: 0x4000, + 0xebc: 0x4000, 0xebd: 0x4000, 0xebe: 0x4000, 0xebf: 0x4000, + // Block 0x3b, offset 0xec0 + 0xec0: 0x4000, 0xec1: 0x4000, 0xec2: 0x4000, 0xec3: 0x4000, 0xec4: 0x4000, 0xec5: 0x4000, + 0xec6: 0x4000, 0xec7: 0x4000, 0xec8: 0x2000, 0xec9: 0x2000, 0xeca: 0x2000, 0xecb: 0x2000, + 0xecc: 0x2000, 0xecd: 0x2000, 0xece: 0x2000, 0xecf: 0x2000, 0xed0: 0x4000, 0xed1: 0x4000, + 0xed2: 0x4000, 0xed3: 0x4000, 0xed4: 0x4000, 0xed5: 0x4000, 0xed6: 0x4000, 0xed7: 0x4000, + 0xed8: 0x4000, 0xed9: 0x4000, 0xeda: 0x4000, 0xedb: 0x4000, 0xedc: 0x4000, 0xedd: 0x4000, + 0xede: 0x4000, 0xedf: 0x4000, 0xee0: 0x4000, 0xee1: 0x4000, 0xee2: 0x4000, 0xee3: 0x4000, + 0xee4: 0x4000, 0xee5: 0x4000, 0xee6: 0x4000, 0xee7: 0x4000, 0xee8: 0x4000, 0xee9: 0x4000, + 0xeea: 0x4000, 0xeeb: 0x4000, 0xeec: 0x4000, 0xeed: 0x4000, 0xeee: 0x4000, 0xeef: 0x4000, + 0xef0: 0x4000, 0xef1: 0x4000, 0xef2: 0x4000, 0xef3: 0x4000, 0xef4: 0x4000, 0xef5: 0x4000, + 0xef6: 0x4000, 0xef7: 0x4000, 0xef8: 0x4000, 0xef9: 0x4000, 0xefa: 0x4000, 0xefb: 0x4000, + 0xefc: 0x4000, 0xefd: 0x4000, 0xefe: 0x4000, 0xeff: 0x4000, + // Block 0x3c, offset 0xf00 + 0xf00: 0x4000, 0xf01: 0x4000, 0xf02: 0x4000, 0xf03: 0x4000, 0xf04: 0x4000, 0xf05: 0x4000, + 0xf06: 0x4000, 0xf07: 0x4000, 0xf08: 0x4000, 0xf09: 0x4000, 0xf0a: 0x4000, 0xf0b: 0x4000, + 0xf0c: 0x4000, 0xf0d: 0x4000, 0xf0e: 0x4000, 0xf0f: 0x4000, 0xf10: 0x4000, 0xf11: 0x4000, + 0xf12: 0x4000, 0xf13: 0x4000, 0xf14: 0x4000, 0xf15: 0x4000, 0xf16: 0x4000, 0xf17: 0x4000, + 0xf18: 0x4000, 0xf19: 0x4000, 0xf1a: 0x4000, 0xf1b: 0x4000, 0xf1c: 0x4000, 0xf1d: 0x4000, + 0xf1e: 0x4000, 0xf1f: 0x4000, 0xf20: 0x4000, 0xf21: 0x4000, 0xf22: 0x4000, 0xf23: 0x4000, + 0xf24: 0x4000, 0xf25: 0x4000, 0xf26: 0x4000, 0xf27: 0x4000, 0xf28: 0x4000, 0xf29: 0x4000, + 0xf2a: 0x4000, 0xf2b: 0x4000, 0xf2c: 0x4000, 0xf2d: 0x4000, 0xf2e: 0x4000, 0xf2f: 0x4000, + 0xf30: 0x4000, 0xf31: 0x4000, 0xf32: 0x4000, 0xf33: 0x4000, 0xf34: 0x4000, 0xf35: 0x4000, + 0xf36: 0x4000, 0xf37: 0x4000, 0xf38: 0x4000, 0xf39: 0x4000, 0xf3a: 0x4000, 0xf3b: 0x4000, + 0xf3c: 0x4000, 0xf3d: 0x4000, 0xf3e: 0x4000, + // Block 0x3d, offset 0xf40 + 0xf40: 0x4000, 0xf41: 0x4000, 0xf42: 0x4000, 0xf43: 0x4000, 0xf44: 0x4000, 0xf45: 0x4000, + 0xf46: 0x4000, 0xf47: 0x4000, 0xf48: 0x4000, 0xf49: 0x4000, 0xf4a: 0x4000, 0xf4b: 0x4000, + 0xf4c: 0x4000, 0xf50: 0x4000, 0xf51: 0x4000, + 0xf52: 0x4000, 0xf53: 0x4000, 0xf54: 0x4000, 0xf55: 0x4000, 0xf56: 0x4000, 0xf57: 0x4000, + 0xf58: 0x4000, 0xf59: 0x4000, 0xf5a: 0x4000, 0xf5b: 0x4000, 0xf5c: 0x4000, 0xf5d: 0x4000, + 0xf5e: 0x4000, 0xf5f: 0x4000, 0xf60: 0x4000, 0xf61: 0x4000, 0xf62: 0x4000, 0xf63: 0x4000, + 0xf64: 0x4000, 0xf65: 0x4000, 0xf66: 0x4000, 0xf67: 0x4000, 0xf68: 0x4000, 0xf69: 0x4000, + 0xf6a: 0x4000, 0xf6b: 0x4000, 0xf6c: 0x4000, 0xf6d: 0x4000, 0xf6e: 0x4000, 0xf6f: 0x4000, + 0xf70: 0x4000, 0xf71: 0x4000, 0xf72: 0x4000, 0xf73: 0x4000, 0xf74: 0x4000, 0xf75: 0x4000, + 0xf76: 0x4000, 0xf77: 0x4000, 0xf78: 0x4000, 0xf79: 0x4000, 0xf7a: 0x4000, 0xf7b: 0x4000, + 0xf7c: 0x4000, 0xf7d: 0x4000, 0xf7e: 0x4000, 0xf7f: 0x4000, + // Block 0x3e, offset 0xf80 + 0xf80: 0x4000, 0xf81: 0x4000, 0xf82: 0x4000, 0xf83: 0x4000, 0xf84: 0x4000, 0xf85: 0x4000, + 0xf86: 0x4000, + // Block 0x3f, offset 0xfc0 + 0xfe0: 0x4000, 0xfe1: 0x4000, 0xfe2: 0x4000, 0xfe3: 0x4000, + 0xfe4: 0x4000, 0xfe5: 0x4000, 0xfe6: 0x4000, 0xfe7: 0x4000, 0xfe8: 0x4000, 0xfe9: 0x4000, + 0xfea: 0x4000, 0xfeb: 0x4000, 0xfec: 0x4000, 0xfed: 0x4000, 0xfee: 0x4000, 0xfef: 0x4000, + 0xff0: 0x4000, 0xff1: 0x4000, 0xff2: 0x4000, 0xff3: 0x4000, 0xff4: 0x4000, 0xff5: 0x4000, + 0xff6: 0x4000, 0xff7: 0x4000, 0xff8: 0x4000, 0xff9: 0x4000, 0xffa: 0x4000, 0xffb: 0x4000, + 0xffc: 0x4000, + // Block 0x40, offset 0x1000 + 0x1000: 0x4000, 0x1001: 0x4000, 0x1002: 0x4000, 0x1003: 0x4000, 0x1004: 0x4000, 0x1005: 0x4000, + 0x1006: 0x4000, 0x1007: 0x4000, 0x1008: 0x4000, 0x1009: 0x4000, 0x100a: 0x4000, 0x100b: 0x4000, + 0x100c: 0x4000, 0x100d: 0x4000, 0x100e: 0x4000, 0x100f: 0x4000, 0x1010: 0x4000, 0x1011: 0x4000, + 0x1012: 0x4000, 0x1013: 0x4000, 0x1014: 0x4000, 0x1015: 0x4000, 0x1016: 0x4000, 0x1017: 0x4000, + 0x1018: 0x4000, 0x1019: 0x4000, 0x101a: 0x4000, 0x101b: 0x4000, 0x101c: 0x4000, 0x101d: 0x4000, + 0x101e: 0x4000, 0x101f: 0x4000, 0x1020: 0x4000, 0x1021: 0x4000, 0x1022: 0x4000, 0x1023: 0x4000, + // Block 0x41, offset 0x1040 + 0x1040: 0x2000, 0x1041: 0x2000, 0x1042: 0x2000, 0x1043: 0x2000, 0x1044: 0x2000, 0x1045: 0x2000, + 0x1046: 0x2000, 0x1047: 0x2000, 0x1048: 0x2000, 0x1049: 0x2000, 0x104a: 0x2000, 0x104b: 0x2000, + 0x104c: 0x2000, 0x104d: 0x2000, 0x104e: 0x2000, 0x104f: 0x2000, 0x1050: 0x4000, 0x1051: 0x4000, + 0x1052: 0x4000, 0x1053: 0x4000, 0x1054: 0x4000, 0x1055: 0x4000, 0x1056: 0x4000, 0x1057: 0x4000, + 0x1058: 0x4000, 0x1059: 0x4000, + 0x1070: 0x4000, 0x1071: 0x4000, 0x1072: 0x4000, 0x1073: 0x4000, 0x1074: 0x4000, 0x1075: 0x4000, + 0x1076: 0x4000, 0x1077: 0x4000, 0x1078: 0x4000, 0x1079: 0x4000, 0x107a: 0x4000, 0x107b: 0x4000, + 0x107c: 0x4000, 0x107d: 0x4000, 0x107e: 0x4000, 0x107f: 0x4000, + // Block 0x42, offset 0x1080 + 0x1080: 0x4000, 0x1081: 0x4000, 0x1082: 0x4000, 0x1083: 0x4000, 0x1084: 0x4000, 0x1085: 0x4000, + 0x1086: 0x4000, 0x1087: 0x4000, 0x1088: 0x4000, 0x1089: 0x4000, 0x108a: 0x4000, 0x108b: 0x4000, + 0x108c: 0x4000, 0x108d: 0x4000, 0x108e: 0x4000, 0x108f: 0x4000, 0x1090: 0x4000, 0x1091: 0x4000, + 0x1092: 0x4000, 0x1094: 0x4000, 0x1095: 0x4000, 0x1096: 0x4000, 0x1097: 0x4000, + 0x1098: 0x4000, 0x1099: 0x4000, 0x109a: 0x4000, 0x109b: 0x4000, 0x109c: 0x4000, 0x109d: 0x4000, + 0x109e: 0x4000, 0x109f: 0x4000, 0x10a0: 0x4000, 0x10a1: 0x4000, 0x10a2: 0x4000, 0x10a3: 0x4000, + 0x10a4: 0x4000, 0x10a5: 0x4000, 0x10a6: 0x4000, 0x10a8: 0x4000, 0x10a9: 0x4000, + 0x10aa: 0x4000, 0x10ab: 0x4000, + // Block 0x43, offset 0x10c0 + 0x10c1: 0x9012, 0x10c2: 0x9012, 0x10c3: 0x9012, 0x10c4: 0x9012, 0x10c5: 0x9012, + 0x10c6: 0x9012, 0x10c7: 0x9012, 0x10c8: 0x9012, 0x10c9: 0x9012, 0x10ca: 0x9012, 0x10cb: 0x9012, + 0x10cc: 0x9012, 0x10cd: 0x9012, 0x10ce: 0x9012, 0x10cf: 0x9012, 0x10d0: 0x9012, 0x10d1: 0x9012, + 0x10d2: 0x9012, 0x10d3: 0x9012, 0x10d4: 0x9012, 0x10d5: 0x9012, 0x10d6: 0x9012, 0x10d7: 0x9012, + 0x10d8: 0x9012, 0x10d9: 0x9012, 0x10da: 0x9012, 0x10db: 0x9012, 0x10dc: 0x9012, 0x10dd: 0x9012, + 0x10de: 0x9012, 0x10df: 0x9012, 0x10e0: 0x9049, 0x10e1: 0x9049, 0x10e2: 0x9049, 0x10e3: 0x9049, + 0x10e4: 0x9049, 0x10e5: 0x9049, 0x10e6: 0x9049, 0x10e7: 0x9049, 0x10e8: 0x9049, 0x10e9: 0x9049, + 0x10ea: 0x9049, 0x10eb: 0x9049, 0x10ec: 0x9049, 0x10ed: 0x9049, 0x10ee: 0x9049, 0x10ef: 0x9049, + 0x10f0: 0x9049, 0x10f1: 0x9049, 0x10f2: 0x9049, 0x10f3: 0x9049, 0x10f4: 0x9049, 0x10f5: 0x9049, + 0x10f6: 0x9049, 0x10f7: 0x9049, 0x10f8: 0x9049, 0x10f9: 0x9049, 0x10fa: 0x9049, 0x10fb: 0x9049, + 0x10fc: 0x9049, 0x10fd: 0x9049, 0x10fe: 0x9049, 0x10ff: 0x9049, + // Block 0x44, offset 0x1100 + 0x1100: 0x9049, 0x1101: 0x9049, 0x1102: 0x9049, 0x1103: 0x9049, 0x1104: 0x9049, 0x1105: 0x9049, + 0x1106: 0x9049, 0x1107: 0x9049, 0x1108: 0x9049, 0x1109: 0x9049, 0x110a: 0x9049, 0x110b: 0x9049, + 0x110c: 0x9049, 0x110d: 0x9049, 0x110e: 0x9049, 0x110f: 0x9049, 0x1110: 0x9049, 0x1111: 0x9049, + 0x1112: 0x9049, 0x1113: 0x9049, 0x1114: 0x9049, 0x1115: 0x9049, 0x1116: 0x9049, 0x1117: 0x9049, + 0x1118: 0x9049, 0x1119: 0x9049, 0x111a: 0x9049, 0x111b: 0x9049, 0x111c: 0x9049, 0x111d: 0x9049, + 0x111e: 0x9049, 0x111f: 0x904a, 0x1120: 0x904b, 0x1121: 0xb04c, 0x1122: 0xb04d, 0x1123: 0xb04d, + 0x1124: 0xb04e, 0x1125: 0xb04f, 0x1126: 0xb050, 0x1127: 0xb051, 0x1128: 0xb052, 0x1129: 0xb053, + 0x112a: 0xb054, 0x112b: 0xb055, 0x112c: 0xb056, 0x112d: 0xb057, 0x112e: 0xb058, 0x112f: 0xb059, + 0x1130: 0xb05a, 0x1131: 0xb05b, 0x1132: 0xb05c, 0x1133: 0xb05d, 0x1134: 0xb05e, 0x1135: 0xb05f, + 0x1136: 0xb060, 0x1137: 0xb061, 0x1138: 0xb062, 0x1139: 0xb063, 0x113a: 0xb064, 0x113b: 0xb065, + 0x113c: 0xb052, 0x113d: 0xb066, 0x113e: 0xb067, 0x113f: 0xb055, + // Block 0x45, offset 0x1140 + 0x1140: 0xb068, 0x1141: 0xb069, 0x1142: 0xb06a, 0x1143: 0xb06b, 0x1144: 0xb05a, 0x1145: 0xb056, + 0x1146: 0xb06c, 0x1147: 0xb06d, 0x1148: 0xb06b, 0x1149: 0xb06e, 0x114a: 0xb06b, 0x114b: 0xb06f, + 0x114c: 0xb06f, 0x114d: 0xb070, 0x114e: 0xb070, 0x114f: 0xb071, 0x1150: 0xb056, 0x1151: 0xb072, + 0x1152: 0xb073, 0x1153: 0xb072, 0x1154: 0xb074, 0x1155: 0xb073, 0x1156: 0xb075, 0x1157: 0xb075, + 0x1158: 0xb076, 0x1159: 0xb076, 0x115a: 0xb077, 0x115b: 0xb077, 0x115c: 0xb073, 0x115d: 0xb078, + 0x115e: 0xb079, 0x115f: 0xb067, 0x1160: 0xb07a, 0x1161: 0xb07b, 0x1162: 0xb07b, 0x1163: 0xb07b, + 0x1164: 0xb07b, 0x1165: 0xb07b, 0x1166: 0xb07b, 0x1167: 0xb07b, 0x1168: 0xb07b, 0x1169: 0xb07b, + 0x116a: 0xb07b, 0x116b: 0xb07b, 0x116c: 0xb07b, 0x116d: 0xb07b, 0x116e: 0xb07b, 0x116f: 0xb07b, + 0x1170: 0xb07c, 0x1171: 0xb07c, 0x1172: 0xb07c, 0x1173: 0xb07c, 0x1174: 0xb07c, 0x1175: 0xb07c, + 0x1176: 0xb07c, 0x1177: 0xb07c, 0x1178: 0xb07c, 0x1179: 0xb07c, 0x117a: 0xb07c, 0x117b: 0xb07c, + 0x117c: 0xb07c, 0x117d: 0xb07c, 0x117e: 0xb07c, + // Block 0x46, offset 0x1180 + 0x1182: 0xb07d, 0x1183: 0xb07e, 0x1184: 0xb07f, 0x1185: 0xb080, + 0x1186: 0xb07f, 0x1187: 0xb07e, 0x118a: 0xb081, 0x118b: 0xb082, + 0x118c: 0xb083, 0x118d: 0xb07f, 0x118e: 0xb080, 0x118f: 0xb07f, + 0x1192: 0xb084, 0x1193: 0xb085, 0x1194: 0xb084, 0x1195: 0xb086, 0x1196: 0xb084, 0x1197: 0xb087, + 0x119a: 0xb088, 0x119b: 0xb089, 0x119c: 0xb08a, + 0x11a0: 0x908b, 0x11a1: 0x908b, 0x11a2: 0x908c, 0x11a3: 0x908d, + 0x11a4: 0x908b, 0x11a5: 0x908e, 0x11a6: 0x908f, 0x11a8: 0xb090, 0x11a9: 0xb091, + 0x11aa: 0xb092, 0x11ab: 0xb091, 0x11ac: 0xb093, 0x11ad: 0xb094, 0x11ae: 0xb095, + 0x11bd: 0x2000, + // Block 0x47, offset 0x11c0 + 0x11e0: 0x4000, 0x11e1: 0x4000, 0x11e2: 0x4000, 0x11e3: 0x4000, + // Block 0x48, offset 0x1200 + 0x1200: 0x4000, 0x1201: 0x4000, 0x1202: 0x4000, 0x1203: 0x4000, 0x1204: 0x4000, 0x1205: 0x4000, + 0x1206: 0x4000, 0x1207: 0x4000, 0x1208: 0x4000, 0x1209: 0x4000, 0x120a: 0x4000, 0x120b: 0x4000, + 0x120c: 0x4000, 0x120d: 0x4000, 0x120e: 0x4000, 0x120f: 0x4000, 0x1210: 0x4000, 0x1211: 0x4000, + 0x1212: 0x4000, 0x1213: 0x4000, 0x1214: 0x4000, 0x1215: 0x4000, 0x1216: 0x4000, 0x1217: 0x4000, + 0x1218: 0x4000, 0x1219: 0x4000, 0x121a: 0x4000, 0x121b: 0x4000, 0x121c: 0x4000, 0x121d: 0x4000, + 0x121e: 0x4000, 0x121f: 0x4000, 0x1220: 0x4000, 0x1221: 0x4000, 0x1222: 0x4000, 0x1223: 0x4000, + 0x1224: 0x4000, 0x1225: 0x4000, 0x1226: 0x4000, 0x1227: 0x4000, 0x1228: 0x4000, 0x1229: 0x4000, + 0x122a: 0x4000, 0x122b: 0x4000, 0x122c: 0x4000, 0x122d: 0x4000, 0x122e: 0x4000, 0x122f: 0x4000, + 0x1230: 0x4000, 0x1231: 0x4000, 0x1232: 0x4000, 0x1233: 0x4000, 0x1234: 0x4000, 0x1235: 0x4000, + 0x1236: 0x4000, 0x1237: 0x4000, + // Block 0x49, offset 0x1240 + 0x1240: 0x4000, 0x1241: 0x4000, 0x1242: 0x4000, 0x1243: 0x4000, 0x1244: 0x4000, 0x1245: 0x4000, + 0x1246: 0x4000, 0x1247: 0x4000, 0x1248: 0x4000, 0x1249: 0x4000, 0x124a: 0x4000, 0x124b: 0x4000, + 0x124c: 0x4000, 0x124d: 0x4000, 0x124e: 0x4000, 0x124f: 0x4000, 0x1250: 0x4000, 0x1251: 0x4000, + 0x1252: 0x4000, 0x1253: 0x4000, 0x1254: 0x4000, 0x1255: 0x4000, 0x1256: 0x4000, 0x1257: 0x4000, + 0x1258: 0x4000, 0x1259: 0x4000, 0x125a: 0x4000, 0x125b: 0x4000, 0x125c: 0x4000, 0x125d: 0x4000, + 0x125e: 0x4000, 0x125f: 0x4000, 0x1260: 0x4000, 0x1261: 0x4000, 0x1262: 0x4000, 0x1263: 0x4000, + 0x1264: 0x4000, 0x1265: 0x4000, 0x1266: 0x4000, 0x1267: 0x4000, 0x1268: 0x4000, 0x1269: 0x4000, + 0x126a: 0x4000, 0x126b: 0x4000, 0x126c: 0x4000, 0x126d: 0x4000, 0x126e: 0x4000, 0x126f: 0x4000, + 0x1270: 0x4000, 0x1271: 0x4000, 0x1272: 0x4000, + // Block 0x4a, offset 0x1280 + 0x1280: 0x4000, 0x1281: 0x4000, 0x1282: 0x4000, 0x1283: 0x4000, 0x1284: 0x4000, 0x1285: 0x4000, + 0x1286: 0x4000, 0x1287: 0x4000, 0x1288: 0x4000, 0x1289: 0x4000, 0x128a: 0x4000, 0x128b: 0x4000, + 0x128c: 0x4000, 0x128d: 0x4000, 0x128e: 0x4000, 0x128f: 0x4000, 0x1290: 0x4000, 0x1291: 0x4000, + 0x1292: 0x4000, 0x1293: 0x4000, 0x1294: 0x4000, 0x1295: 0x4000, 0x1296: 0x4000, 0x1297: 0x4000, + 0x1298: 0x4000, 0x1299: 0x4000, 0x129a: 0x4000, 0x129b: 0x4000, 0x129c: 0x4000, 0x129d: 0x4000, + 0x129e: 0x4000, + // Block 0x4b, offset 0x12c0 + 0x12d0: 0x4000, 0x12d1: 0x4000, + 0x12d2: 0x4000, + 0x12e4: 0x4000, 0x12e5: 0x4000, 0x12e6: 0x4000, 0x12e7: 0x4000, + 0x12f0: 0x4000, 0x12f1: 0x4000, 0x12f2: 0x4000, 0x12f3: 0x4000, 0x12f4: 0x4000, 0x12f5: 0x4000, + 0x12f6: 0x4000, 0x12f7: 0x4000, 0x12f8: 0x4000, 0x12f9: 0x4000, 0x12fa: 0x4000, 0x12fb: 0x4000, + 0x12fc: 0x4000, 0x12fd: 0x4000, 0x12fe: 0x4000, 0x12ff: 0x4000, + // Block 0x4c, offset 0x1300 + 0x1300: 0x4000, 0x1301: 0x4000, 0x1302: 0x4000, 0x1303: 0x4000, 0x1304: 0x4000, 0x1305: 0x4000, + 0x1306: 0x4000, 0x1307: 0x4000, 0x1308: 0x4000, 0x1309: 0x4000, 0x130a: 0x4000, 0x130b: 0x4000, + 0x130c: 0x4000, 0x130d: 0x4000, 0x130e: 0x4000, 0x130f: 0x4000, 0x1310: 0x4000, 0x1311: 0x4000, + 0x1312: 0x4000, 0x1313: 0x4000, 0x1314: 0x4000, 0x1315: 0x4000, 0x1316: 0x4000, 0x1317: 0x4000, + 0x1318: 0x4000, 0x1319: 0x4000, 0x131a: 0x4000, 0x131b: 0x4000, 0x131c: 0x4000, 0x131d: 0x4000, + 0x131e: 0x4000, 0x131f: 0x4000, 0x1320: 0x4000, 0x1321: 0x4000, 0x1322: 0x4000, 0x1323: 0x4000, + 0x1324: 0x4000, 0x1325: 0x4000, 0x1326: 0x4000, 0x1327: 0x4000, 0x1328: 0x4000, 0x1329: 0x4000, + 0x132a: 0x4000, 0x132b: 0x4000, 0x132c: 0x4000, 0x132d: 0x4000, 0x132e: 0x4000, 0x132f: 0x4000, + 0x1330: 0x4000, 0x1331: 0x4000, 0x1332: 0x4000, 0x1333: 0x4000, 0x1334: 0x4000, 0x1335: 0x4000, + 0x1336: 0x4000, 0x1337: 0x4000, 0x1338: 0x4000, 0x1339: 0x4000, 0x133a: 0x4000, 0x133b: 0x4000, + // Block 0x4d, offset 0x1340 + 0x1344: 0x4000, + // Block 0x4e, offset 0x1380 + 0x138f: 0x4000, + // Block 0x4f, offset 0x13c0 + 0x13c0: 0x2000, 0x13c1: 0x2000, 0x13c2: 0x2000, 0x13c3: 0x2000, 0x13c4: 0x2000, 0x13c5: 0x2000, + 0x13c6: 0x2000, 0x13c7: 0x2000, 0x13c8: 0x2000, 0x13c9: 0x2000, 0x13ca: 0x2000, + 0x13d0: 0x2000, 0x13d1: 0x2000, + 0x13d2: 0x2000, 0x13d3: 0x2000, 0x13d4: 0x2000, 0x13d5: 0x2000, 0x13d6: 0x2000, 0x13d7: 0x2000, + 0x13d8: 0x2000, 0x13d9: 0x2000, 0x13da: 0x2000, 0x13db: 0x2000, 0x13dc: 0x2000, 0x13dd: 0x2000, + 0x13de: 0x2000, 0x13df: 0x2000, 0x13e0: 0x2000, 0x13e1: 0x2000, 0x13e2: 0x2000, 0x13e3: 0x2000, + 0x13e4: 0x2000, 0x13e5: 0x2000, 0x13e6: 0x2000, 0x13e7: 0x2000, 0x13e8: 0x2000, 0x13e9: 0x2000, + 0x13ea: 0x2000, 0x13eb: 0x2000, 0x13ec: 0x2000, 0x13ed: 0x2000, + 0x13f0: 0x2000, 0x13f1: 0x2000, 0x13f2: 0x2000, 0x13f3: 0x2000, 0x13f4: 0x2000, 0x13f5: 0x2000, + 0x13f6: 0x2000, 0x13f7: 0x2000, 0x13f8: 0x2000, 0x13f9: 0x2000, 0x13fa: 0x2000, 0x13fb: 0x2000, + 0x13fc: 0x2000, 0x13fd: 0x2000, 0x13fe: 0x2000, 0x13ff: 0x2000, + // Block 0x50, offset 0x1400 + 0x1400: 0x2000, 0x1401: 0x2000, 0x1402: 0x2000, 0x1403: 0x2000, 0x1404: 0x2000, 0x1405: 0x2000, + 0x1406: 0x2000, 0x1407: 0x2000, 0x1408: 0x2000, 0x1409: 0x2000, 0x140a: 0x2000, 0x140b: 0x2000, + 0x140c: 0x2000, 0x140d: 0x2000, 0x140e: 0x2000, 0x140f: 0x2000, 0x1410: 0x2000, 0x1411: 0x2000, + 0x1412: 0x2000, 0x1413: 0x2000, 0x1414: 0x2000, 0x1415: 0x2000, 0x1416: 0x2000, 0x1417: 0x2000, + 0x1418: 0x2000, 0x1419: 0x2000, 0x141a: 0x2000, 0x141b: 0x2000, 0x141c: 0x2000, 0x141d: 0x2000, + 0x141e: 0x2000, 0x141f: 0x2000, 0x1420: 0x2000, 0x1421: 0x2000, 0x1422: 0x2000, 0x1423: 0x2000, + 0x1424: 0x2000, 0x1425: 0x2000, 0x1426: 0x2000, 0x1427: 0x2000, 0x1428: 0x2000, 0x1429: 0x2000, + 0x1430: 0x2000, 0x1431: 0x2000, 0x1432: 0x2000, 0x1433: 0x2000, 0x1434: 0x2000, 0x1435: 0x2000, + 0x1436: 0x2000, 0x1437: 0x2000, 0x1438: 0x2000, 0x1439: 0x2000, 0x143a: 0x2000, 0x143b: 0x2000, + 0x143c: 0x2000, 0x143d: 0x2000, 0x143e: 0x2000, 0x143f: 0x2000, + // Block 0x51, offset 0x1440 + 0x1440: 0x2000, 0x1441: 0x2000, 0x1442: 0x2000, 0x1443: 0x2000, 0x1444: 0x2000, 0x1445: 0x2000, + 0x1446: 0x2000, 0x1447: 0x2000, 0x1448: 0x2000, 0x1449: 0x2000, 0x144a: 0x2000, 0x144b: 0x2000, + 0x144c: 0x2000, 0x144d: 0x2000, 0x144e: 0x4000, 0x144f: 0x2000, 0x1450: 0x2000, 0x1451: 0x4000, + 0x1452: 0x4000, 0x1453: 0x4000, 0x1454: 0x4000, 0x1455: 0x4000, 0x1456: 0x4000, 0x1457: 0x4000, + 0x1458: 0x4000, 0x1459: 0x4000, 0x145a: 0x4000, 0x145b: 0x2000, 0x145c: 0x2000, 0x145d: 0x2000, + 0x145e: 0x2000, 0x145f: 0x2000, 0x1460: 0x2000, 0x1461: 0x2000, 0x1462: 0x2000, 0x1463: 0x2000, + 0x1464: 0x2000, 0x1465: 0x2000, 0x1466: 0x2000, 0x1467: 0x2000, 0x1468: 0x2000, 0x1469: 0x2000, + 0x146a: 0x2000, 0x146b: 0x2000, 0x146c: 0x2000, + // Block 0x52, offset 0x1480 + 0x1480: 0x4000, 0x1481: 0x4000, 0x1482: 0x4000, + 0x1490: 0x4000, 0x1491: 0x4000, + 0x1492: 0x4000, 0x1493: 0x4000, 0x1494: 0x4000, 0x1495: 0x4000, 0x1496: 0x4000, 0x1497: 0x4000, + 0x1498: 0x4000, 0x1499: 0x4000, 0x149a: 0x4000, 0x149b: 0x4000, 0x149c: 0x4000, 0x149d: 0x4000, + 0x149e: 0x4000, 0x149f: 0x4000, 0x14a0: 0x4000, 0x14a1: 0x4000, 0x14a2: 0x4000, 0x14a3: 0x4000, + 0x14a4: 0x4000, 0x14a5: 0x4000, 0x14a6: 0x4000, 0x14a7: 0x4000, 0x14a8: 0x4000, 0x14a9: 0x4000, + 0x14aa: 0x4000, 0x14ab: 0x4000, 0x14ac: 0x4000, 0x14ad: 0x4000, 0x14ae: 0x4000, 0x14af: 0x4000, + 0x14b0: 0x4000, 0x14b1: 0x4000, 0x14b2: 0x4000, 0x14b3: 0x4000, 0x14b4: 0x4000, 0x14b5: 0x4000, + 0x14b6: 0x4000, 0x14b7: 0x4000, 0x14b8: 0x4000, 0x14b9: 0x4000, 0x14ba: 0x4000, 0x14bb: 0x4000, + // Block 0x53, offset 0x14c0 + 0x14c0: 0x4000, 0x14c1: 0x4000, 0x14c2: 0x4000, 0x14c3: 0x4000, 0x14c4: 0x4000, 0x14c5: 0x4000, + 0x14c6: 0x4000, 0x14c7: 0x4000, 0x14c8: 0x4000, + 0x14d0: 0x4000, 0x14d1: 0x4000, + 0x14e0: 0x4000, 0x14e1: 0x4000, 0x14e2: 0x4000, 0x14e3: 0x4000, + 0x14e4: 0x4000, 0x14e5: 0x4000, + // Block 0x54, offset 0x1500 + 0x1500: 0x4000, 0x1501: 0x4000, 0x1502: 0x4000, 0x1503: 0x4000, 0x1504: 0x4000, 0x1505: 0x4000, + 0x1506: 0x4000, 0x1507: 0x4000, 0x1508: 0x4000, 0x1509: 0x4000, 0x150a: 0x4000, 0x150b: 0x4000, + 0x150c: 0x4000, 0x150d: 0x4000, 0x150e: 0x4000, 0x150f: 0x4000, 0x1510: 0x4000, 0x1511: 0x4000, + 0x1512: 0x4000, 0x1513: 0x4000, 0x1514: 0x4000, 0x1515: 0x4000, 0x1516: 0x4000, 0x1517: 0x4000, + 0x1518: 0x4000, 0x1519: 0x4000, 0x151a: 0x4000, 0x151b: 0x4000, 0x151c: 0x4000, 0x151d: 0x4000, + 0x151e: 0x4000, 0x151f: 0x4000, 0x1520: 0x4000, + 0x152d: 0x4000, 0x152e: 0x4000, 0x152f: 0x4000, + 0x1530: 0x4000, 0x1531: 0x4000, 0x1532: 0x4000, 0x1533: 0x4000, 0x1534: 0x4000, 0x1535: 0x4000, + 0x1537: 0x4000, 0x1538: 0x4000, 0x1539: 0x4000, 0x153a: 0x4000, 0x153b: 0x4000, + 0x153c: 0x4000, 0x153d: 0x4000, 0x153e: 0x4000, 0x153f: 0x4000, + // Block 0x55, offset 0x1540 + 0x1540: 0x4000, 0x1541: 0x4000, 0x1542: 0x4000, 0x1543: 0x4000, 0x1544: 0x4000, 0x1545: 0x4000, + 0x1546: 0x4000, 0x1547: 0x4000, 0x1548: 0x4000, 0x1549: 0x4000, 0x154a: 0x4000, 0x154b: 0x4000, + 0x154c: 0x4000, 0x154d: 0x4000, 0x154e: 0x4000, 0x154f: 0x4000, 0x1550: 0x4000, 0x1551: 0x4000, + 0x1552: 0x4000, 0x1553: 0x4000, 0x1554: 0x4000, 0x1555: 0x4000, 0x1556: 0x4000, 0x1557: 0x4000, + 0x1558: 0x4000, 0x1559: 0x4000, 0x155a: 0x4000, 0x155b: 0x4000, 0x155c: 0x4000, 0x155d: 0x4000, + 0x155e: 0x4000, 0x155f: 0x4000, 0x1560: 0x4000, 0x1561: 0x4000, 0x1562: 0x4000, 0x1563: 0x4000, + 0x1564: 0x4000, 0x1565: 0x4000, 0x1566: 0x4000, 0x1567: 0x4000, 0x1568: 0x4000, 0x1569: 0x4000, + 0x156a: 0x4000, 0x156b: 0x4000, 0x156c: 0x4000, 0x156d: 0x4000, 0x156e: 0x4000, 0x156f: 0x4000, + 0x1570: 0x4000, 0x1571: 0x4000, 0x1572: 0x4000, 0x1573: 0x4000, 0x1574: 0x4000, 0x1575: 0x4000, + 0x1576: 0x4000, 0x1577: 0x4000, 0x1578: 0x4000, 0x1579: 0x4000, 0x157a: 0x4000, 0x157b: 0x4000, + 0x157c: 0x4000, 0x157e: 0x4000, 0x157f: 0x4000, + // Block 0x56, offset 0x1580 + 0x1580: 0x4000, 0x1581: 0x4000, 0x1582: 0x4000, 0x1583: 0x4000, 0x1584: 0x4000, 0x1585: 0x4000, + 0x1586: 0x4000, 0x1587: 0x4000, 0x1588: 0x4000, 0x1589: 0x4000, 0x158a: 0x4000, 0x158b: 0x4000, + 0x158c: 0x4000, 0x158d: 0x4000, 0x158e: 0x4000, 0x158f: 0x4000, 0x1590: 0x4000, 0x1591: 0x4000, + 0x1592: 0x4000, 0x1593: 0x4000, + 0x15a0: 0x4000, 0x15a1: 0x4000, 0x15a2: 0x4000, 0x15a3: 0x4000, + 0x15a4: 0x4000, 0x15a5: 0x4000, 0x15a6: 0x4000, 0x15a7: 0x4000, 0x15a8: 0x4000, 0x15a9: 0x4000, + 0x15aa: 0x4000, 0x15ab: 0x4000, 0x15ac: 0x4000, 0x15ad: 0x4000, 0x15ae: 0x4000, 0x15af: 0x4000, + 0x15b0: 0x4000, 0x15b1: 0x4000, 0x15b2: 0x4000, 0x15b3: 0x4000, 0x15b4: 0x4000, 0x15b5: 0x4000, + 0x15b6: 0x4000, 0x15b7: 0x4000, 0x15b8: 0x4000, 0x15b9: 0x4000, 0x15ba: 0x4000, 0x15bb: 0x4000, + 0x15bc: 0x4000, 0x15bd: 0x4000, 0x15be: 0x4000, 0x15bf: 0x4000, + // Block 0x57, offset 0x15c0 + 0x15c0: 0x4000, 0x15c1: 0x4000, 0x15c2: 0x4000, 0x15c3: 0x4000, 0x15c4: 0x4000, 0x15c5: 0x4000, + 0x15c6: 0x4000, 0x15c7: 0x4000, 0x15c8: 0x4000, 0x15c9: 0x4000, 0x15ca: 0x4000, + 0x15cf: 0x4000, 0x15d0: 0x4000, 0x15d1: 0x4000, + 0x15d2: 0x4000, 0x15d3: 0x4000, + 0x15e0: 0x4000, 0x15e1: 0x4000, 0x15e2: 0x4000, 0x15e3: 0x4000, + 0x15e4: 0x4000, 0x15e5: 0x4000, 0x15e6: 0x4000, 0x15e7: 0x4000, 0x15e8: 0x4000, 0x15e9: 0x4000, + 0x15ea: 0x4000, 0x15eb: 0x4000, 0x15ec: 0x4000, 0x15ed: 0x4000, 0x15ee: 0x4000, 0x15ef: 0x4000, + 0x15f0: 0x4000, 0x15f4: 0x4000, + 0x15f8: 0x4000, 0x15f9: 0x4000, 0x15fa: 0x4000, 0x15fb: 0x4000, + 0x15fc: 0x4000, 0x15fd: 0x4000, 0x15fe: 0x4000, 0x15ff: 0x4000, + // Block 0x58, offset 0x1600 + 0x1600: 0x4000, 0x1602: 0x4000, 0x1603: 0x4000, 0x1604: 0x4000, 0x1605: 0x4000, + 0x1606: 0x4000, 0x1607: 0x4000, 0x1608: 0x4000, 0x1609: 0x4000, 0x160a: 0x4000, 0x160b: 0x4000, + 0x160c: 0x4000, 0x160d: 0x4000, 0x160e: 0x4000, 0x160f: 0x4000, 0x1610: 0x4000, 0x1611: 0x4000, + 0x1612: 0x4000, 0x1613: 0x4000, 0x1614: 0x4000, 0x1615: 0x4000, 0x1616: 0x4000, 0x1617: 0x4000, + 0x1618: 0x4000, 0x1619: 0x4000, 0x161a: 0x4000, 0x161b: 0x4000, 0x161c: 0x4000, 0x161d: 0x4000, + 0x161e: 0x4000, 0x161f: 0x4000, 0x1620: 0x4000, 0x1621: 0x4000, 0x1622: 0x4000, 0x1623: 0x4000, + 0x1624: 0x4000, 0x1625: 0x4000, 0x1626: 0x4000, 0x1627: 0x4000, 0x1628: 0x4000, 0x1629: 0x4000, + 0x162a: 0x4000, 0x162b: 0x4000, 0x162c: 0x4000, 0x162d: 0x4000, 0x162e: 0x4000, 0x162f: 0x4000, + 0x1630: 0x4000, 0x1631: 0x4000, 0x1632: 0x4000, 0x1633: 0x4000, 0x1634: 0x4000, 0x1635: 0x4000, + 0x1636: 0x4000, 0x1637: 0x4000, 0x1638: 0x4000, 0x1639: 0x4000, 0x163a: 0x4000, 0x163b: 0x4000, + 0x163c: 0x4000, 0x163d: 0x4000, 0x163e: 0x4000, 0x163f: 0x4000, + // Block 0x59, offset 0x1640 + 0x1640: 0x4000, 0x1641: 0x4000, 0x1642: 0x4000, 0x1643: 0x4000, 0x1644: 0x4000, 0x1645: 0x4000, + 0x1646: 0x4000, 0x1647: 0x4000, 0x1648: 0x4000, 0x1649: 0x4000, 0x164a: 0x4000, 0x164b: 0x4000, + 0x164c: 0x4000, 0x164d: 0x4000, 0x164e: 0x4000, 0x164f: 0x4000, 0x1650: 0x4000, 0x1651: 0x4000, + 0x1652: 0x4000, 0x1653: 0x4000, 0x1654: 0x4000, 0x1655: 0x4000, 0x1656: 0x4000, 0x1657: 0x4000, + 0x1658: 0x4000, 0x1659: 0x4000, 0x165a: 0x4000, 0x165b: 0x4000, 0x165c: 0x4000, 0x165d: 0x4000, + 0x165e: 0x4000, 0x165f: 0x4000, 0x1660: 0x4000, 0x1661: 0x4000, 0x1662: 0x4000, 0x1663: 0x4000, + 0x1664: 0x4000, 0x1665: 0x4000, 0x1666: 0x4000, 0x1667: 0x4000, 0x1668: 0x4000, 0x1669: 0x4000, + 0x166a: 0x4000, 0x166b: 0x4000, 0x166c: 0x4000, 0x166d: 0x4000, 0x166e: 0x4000, 0x166f: 0x4000, + 0x1670: 0x4000, 0x1671: 0x4000, 0x1672: 0x4000, 0x1673: 0x4000, 0x1674: 0x4000, 0x1675: 0x4000, + 0x1676: 0x4000, 0x1677: 0x4000, 0x1678: 0x4000, 0x1679: 0x4000, 0x167a: 0x4000, 0x167b: 0x4000, + 0x167c: 0x4000, 0x167f: 0x4000, + // Block 0x5a, offset 0x1680 + 0x1680: 0x4000, 0x1681: 0x4000, 0x1682: 0x4000, 0x1683: 0x4000, 0x1684: 0x4000, 0x1685: 0x4000, + 0x1686: 0x4000, 0x1687: 0x4000, 0x1688: 0x4000, 0x1689: 0x4000, 0x168a: 0x4000, 0x168b: 0x4000, + 0x168c: 0x4000, 0x168d: 0x4000, 0x168e: 0x4000, 0x168f: 0x4000, 0x1690: 0x4000, 0x1691: 0x4000, + 0x1692: 0x4000, 0x1693: 0x4000, 0x1694: 0x4000, 0x1695: 0x4000, 0x1696: 0x4000, 0x1697: 0x4000, + 0x1698: 0x4000, 0x1699: 0x4000, 0x169a: 0x4000, 0x169b: 0x4000, 0x169c: 0x4000, 0x169d: 0x4000, + 0x169e: 0x4000, 0x169f: 0x4000, 0x16a0: 0x4000, 0x16a1: 0x4000, 0x16a2: 0x4000, 0x16a3: 0x4000, + 0x16a4: 0x4000, 0x16a5: 0x4000, 0x16a6: 0x4000, 0x16a7: 0x4000, 0x16a8: 0x4000, 0x16a9: 0x4000, + 0x16aa: 0x4000, 0x16ab: 0x4000, 0x16ac: 0x4000, 0x16ad: 0x4000, 0x16ae: 0x4000, 0x16af: 0x4000, + 0x16b0: 0x4000, 0x16b1: 0x4000, 0x16b2: 0x4000, 0x16b3: 0x4000, 0x16b4: 0x4000, 0x16b5: 0x4000, + 0x16b6: 0x4000, 0x16b7: 0x4000, 0x16b8: 0x4000, 0x16b9: 0x4000, 0x16ba: 0x4000, 0x16bb: 0x4000, + 0x16bc: 0x4000, 0x16bd: 0x4000, + // Block 0x5b, offset 0x16c0 + 0x16cb: 0x4000, + 0x16cc: 0x4000, 0x16cd: 0x4000, 0x16ce: 0x4000, 0x16d0: 0x4000, 0x16d1: 0x4000, + 0x16d2: 0x4000, 0x16d3: 0x4000, 0x16d4: 0x4000, 0x16d5: 0x4000, 0x16d6: 0x4000, 0x16d7: 0x4000, + 0x16d8: 0x4000, 0x16d9: 0x4000, 0x16da: 0x4000, 0x16db: 0x4000, 0x16dc: 0x4000, 0x16dd: 0x4000, + 0x16de: 0x4000, 0x16df: 0x4000, 0x16e0: 0x4000, 0x16e1: 0x4000, 0x16e2: 0x4000, 0x16e3: 0x4000, + 0x16e4: 0x4000, 0x16e5: 0x4000, 0x16e6: 0x4000, 0x16e7: 0x4000, + 0x16fa: 0x4000, + // Block 0x5c, offset 0x1700 + 0x1715: 0x4000, 0x1716: 0x4000, + 0x1724: 0x4000, + // Block 0x5d, offset 0x1740 + 0x177b: 0x4000, + 0x177c: 0x4000, 0x177d: 0x4000, 0x177e: 0x4000, 0x177f: 0x4000, + // Block 0x5e, offset 0x1780 + 0x1780: 0x4000, 0x1781: 0x4000, 0x1782: 0x4000, 0x1783: 0x4000, 0x1784: 0x4000, 0x1785: 0x4000, + 0x1786: 0x4000, 0x1787: 0x4000, 0x1788: 0x4000, 0x1789: 0x4000, 0x178a: 0x4000, 0x178b: 0x4000, + 0x178c: 0x4000, 0x178d: 0x4000, 0x178e: 0x4000, 0x178f: 0x4000, + // Block 0x5f, offset 0x17c0 + 0x17c0: 0x4000, 0x17c1: 0x4000, 0x17c2: 0x4000, 0x17c3: 0x4000, 0x17c4: 0x4000, 0x17c5: 0x4000, + 0x17cc: 0x4000, 0x17d0: 0x4000, 0x17d1: 0x4000, + 0x17d2: 0x4000, 0x17d5: 0x4000, + 0x17eb: 0x4000, 0x17ec: 0x4000, + 0x17f4: 0x4000, 0x17f5: 0x4000, + 0x17f6: 0x4000, 0x17f7: 0x4000, 0x17f8: 0x4000, 0x17f9: 0x4000, 0x17fa: 0x4000, + // Block 0x60, offset 0x1800 + 0x1820: 0x4000, 0x1821: 0x4000, 0x1822: 0x4000, 0x1823: 0x4000, + 0x1824: 0x4000, 0x1825: 0x4000, 0x1826: 0x4000, 0x1827: 0x4000, 0x1828: 0x4000, 0x1829: 0x4000, + 0x182a: 0x4000, 0x182b: 0x4000, + // Block 0x61, offset 0x1840 + 0x184d: 0x4000, 0x184e: 0x4000, 0x184f: 0x4000, 0x1850: 0x4000, 0x1851: 0x4000, + 0x1852: 0x4000, 0x1853: 0x4000, 0x1854: 0x4000, 0x1855: 0x4000, 0x1856: 0x4000, 0x1857: 0x4000, + 0x1858: 0x4000, 0x1859: 0x4000, 0x185a: 0x4000, 0x185b: 0x4000, 0x185c: 0x4000, 0x185d: 0x4000, + 0x185e: 0x4000, 0x185f: 0x4000, 0x1860: 0x4000, 0x1861: 0x4000, 0x1862: 0x4000, 0x1863: 0x4000, + 0x1864: 0x4000, 0x1865: 0x4000, 0x1866: 0x4000, 0x1867: 0x4000, 0x1868: 0x4000, 0x1869: 0x4000, + 0x186a: 0x4000, 0x186b: 0x4000, 0x186c: 0x4000, 0x186d: 0x4000, 0x186e: 0x4000, 0x186f: 0x4000, + 0x1870: 0x4000, 0x1871: 0x4000, 0x1872: 0x4000, 0x1873: 0x4000, 0x1874: 0x4000, 0x1875: 0x4000, + 0x1876: 0x4000, 0x1877: 0x4000, 0x1878: 0x4000, 0x1879: 0x4000, 0x187a: 0x4000, 0x187b: 0x4000, + 0x187c: 0x4000, 0x187d: 0x4000, 0x187e: 0x4000, 0x187f: 0x4000, + // Block 0x62, offset 0x1880 + 0x1880: 0x4000, 0x1881: 0x4000, 0x1882: 0x4000, 0x1883: 0x4000, 0x1884: 0x4000, 0x1885: 0x4000, + 0x1886: 0x4000, 0x1887: 0x4000, 0x1888: 0x4000, 0x1889: 0x4000, 0x188a: 0x4000, 0x188b: 0x4000, + 0x188c: 0x4000, 0x188d: 0x4000, 0x188e: 0x4000, 0x188f: 0x4000, 0x1890: 0x4000, 0x1891: 0x4000, + 0x1892: 0x4000, 0x1893: 0x4000, 0x1894: 0x4000, 0x1895: 0x4000, 0x1896: 0x4000, 0x1897: 0x4000, + 0x1898: 0x4000, 0x1899: 0x4000, 0x189a: 0x4000, 0x189b: 0x4000, 0x189c: 0x4000, 0x189d: 0x4000, + 0x189e: 0x4000, 0x189f: 0x4000, 0x18a0: 0x4000, 0x18a1: 0x4000, 0x18a2: 0x4000, 0x18a3: 0x4000, + 0x18a4: 0x4000, 0x18a5: 0x4000, 0x18a6: 0x4000, 0x18a7: 0x4000, 0x18a8: 0x4000, 0x18a9: 0x4000, + 0x18aa: 0x4000, 0x18ab: 0x4000, 0x18ac: 0x4000, 0x18ad: 0x4000, 0x18ae: 0x4000, 0x18af: 0x4000, + 0x18b0: 0x4000, 0x18b1: 0x4000, 0x18b3: 0x4000, 0x18b4: 0x4000, 0x18b5: 0x4000, + 0x18b6: 0x4000, 0x18ba: 0x4000, 0x18bb: 0x4000, + 0x18bc: 0x4000, 0x18bd: 0x4000, 0x18be: 0x4000, 0x18bf: 0x4000, + // Block 0x63, offset 0x18c0 + 0x18c0: 0x4000, 0x18c1: 0x4000, 0x18c2: 0x4000, 0x18c3: 0x4000, 0x18c4: 0x4000, 0x18c5: 0x4000, + 0x18c6: 0x4000, 0x18c7: 0x4000, 0x18c8: 0x4000, 0x18c9: 0x4000, 0x18ca: 0x4000, 0x18cb: 0x4000, + 0x18cc: 0x4000, 0x18cd: 0x4000, 0x18ce: 0x4000, 0x18cf: 0x4000, 0x18d0: 0x4000, 0x18d1: 0x4000, + 0x18d2: 0x4000, 0x18d3: 0x4000, 0x18d4: 0x4000, 0x18d5: 0x4000, 0x18d6: 0x4000, 0x18d7: 0x4000, + 0x18d8: 0x4000, 0x18d9: 0x4000, 0x18da: 0x4000, 0x18db: 0x4000, 0x18dc: 0x4000, 0x18dd: 0x4000, + 0x18de: 0x4000, 0x18df: 0x4000, 0x18e0: 0x4000, 0x18e1: 0x4000, 0x18e2: 0x4000, + 0x18e5: 0x4000, 0x18e6: 0x4000, 0x18e7: 0x4000, 0x18e8: 0x4000, 0x18e9: 0x4000, + 0x18ea: 0x4000, 0x18ee: 0x4000, 0x18ef: 0x4000, + 0x18f0: 0x4000, 0x18f1: 0x4000, 0x18f2: 0x4000, 0x18f3: 0x4000, 0x18f4: 0x4000, 0x18f5: 0x4000, + 0x18f6: 0x4000, 0x18f7: 0x4000, 0x18f8: 0x4000, 0x18f9: 0x4000, 0x18fa: 0x4000, 0x18fb: 0x4000, + 0x18fc: 0x4000, 0x18fd: 0x4000, 0x18fe: 0x4000, 0x18ff: 0x4000, + // Block 0x64, offset 0x1900 + 0x1900: 0x4000, 0x1901: 0x4000, 0x1902: 0x4000, 0x1903: 0x4000, 0x1904: 0x4000, 0x1905: 0x4000, + 0x1906: 0x4000, 0x1907: 0x4000, 0x1908: 0x4000, 0x1909: 0x4000, 0x190a: 0x4000, + 0x190d: 0x4000, 0x190e: 0x4000, 0x190f: 0x4000, 0x1910: 0x4000, 0x1911: 0x4000, + 0x1912: 0x4000, 0x1913: 0x4000, 0x1914: 0x4000, 0x1915: 0x4000, 0x1916: 0x4000, 0x1917: 0x4000, + 0x1918: 0x4000, 0x1919: 0x4000, 0x191a: 0x4000, 0x191b: 0x4000, 0x191c: 0x4000, 0x191d: 0x4000, + 0x191e: 0x4000, 0x191f: 0x4000, 0x1920: 0x4000, 0x1921: 0x4000, 0x1922: 0x4000, 0x1923: 0x4000, + 0x1924: 0x4000, 0x1925: 0x4000, 0x1926: 0x4000, 0x1927: 0x4000, 0x1928: 0x4000, 0x1929: 0x4000, + 0x192a: 0x4000, 0x192b: 0x4000, 0x192c: 0x4000, 0x192d: 0x4000, 0x192e: 0x4000, 0x192f: 0x4000, + 0x1930: 0x4000, 0x1931: 0x4000, 0x1932: 0x4000, 0x1933: 0x4000, 0x1934: 0x4000, 0x1935: 0x4000, + 0x1936: 0x4000, 0x1937: 0x4000, 0x1938: 0x4000, 0x1939: 0x4000, 0x193a: 0x4000, 0x193b: 0x4000, + 0x193c: 0x4000, 0x193d: 0x4000, 0x193e: 0x4000, 0x193f: 0x4000, + // Block 0x65, offset 0x1940 + 0x1970: 0x4000, 0x1971: 0x4000, 0x1972: 0x4000, 0x1973: 0x4000, + 0x1978: 0x4000, 0x1979: 0x4000, 0x197a: 0x4000, + // Block 0x66, offset 0x1980 + 0x1980: 0x4000, 0x1981: 0x4000, 0x1982: 0x4000, + 0x1990: 0x4000, 0x1991: 0x4000, + 0x1992: 0x4000, 0x1993: 0x4000, 0x1994: 0x4000, 0x1995: 0x4000, + // Block 0x67, offset 0x19c0 + 0x19c0: 0x2000, 0x19c1: 0x2000, 0x19c2: 0x2000, 0x19c3: 0x2000, 0x19c4: 0x2000, 0x19c5: 0x2000, + 0x19c6: 0x2000, 0x19c7: 0x2000, 0x19c8: 0x2000, 0x19c9: 0x2000, 0x19ca: 0x2000, 0x19cb: 0x2000, + 0x19cc: 0x2000, 0x19cd: 0x2000, 0x19ce: 0x2000, 0x19cf: 0x2000, 0x19d0: 0x2000, 0x19d1: 0x2000, + 0x19d2: 0x2000, 0x19d3: 0x2000, 0x19d4: 0x2000, 0x19d5: 0x2000, 0x19d6: 0x2000, 0x19d7: 0x2000, + 0x19d8: 0x2000, 0x19d9: 0x2000, 0x19da: 0x2000, 0x19db: 0x2000, 0x19dc: 0x2000, 0x19dd: 0x2000, + 0x19de: 0x2000, 0x19df: 0x2000, 0x19e0: 0x2000, 0x19e1: 0x2000, 0x19e2: 0x2000, 0x19e3: 0x2000, + 0x19e4: 0x2000, 0x19e5: 0x2000, 0x19e6: 0x2000, 0x19e7: 0x2000, 0x19e8: 0x2000, 0x19e9: 0x2000, + 0x19ea: 0x2000, 0x19eb: 0x2000, 0x19ec: 0x2000, 0x19ed: 0x2000, 0x19ee: 0x2000, 0x19ef: 0x2000, + 0x19f0: 0x2000, 0x19f1: 0x2000, 0x19f2: 0x2000, 0x19f3: 0x2000, 0x19f4: 0x2000, 0x19f5: 0x2000, + 0x19f6: 0x2000, 0x19f7: 0x2000, 0x19f8: 0x2000, 0x19f9: 0x2000, 0x19fa: 0x2000, 0x19fb: 0x2000, + 0x19fc: 0x2000, 0x19fd: 0x2000, +} + +// widthIndex: 22 blocks, 1408 entries, 1408 bytes +// Block 0 is the zero block. +var widthIndex = [1408]uint8{ + // Block 0x0, offset 0x0 + // Block 0x1, offset 0x40 + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc2: 0x01, 0xc3: 0x02, 0xc4: 0x03, 0xc5: 0x04, 0xc7: 0x05, + 0xc9: 0x06, 0xcb: 0x07, 0xcc: 0x08, 0xcd: 0x09, 0xce: 0x0a, 0xcf: 0x0b, + 0xd0: 0x0c, 0xd1: 0x0d, + 0xe1: 0x02, 0xe2: 0x03, 0xe3: 0x04, 0xe4: 0x05, 0xe5: 0x06, 0xe6: 0x06, 0xe7: 0x06, + 0xe8: 0x06, 0xe9: 0x06, 0xea: 0x07, 0xeb: 0x06, 0xec: 0x06, 0xed: 0x08, 0xee: 0x09, 0xef: 0x0a, + 0xf0: 0x0f, 0xf3: 0x12, 0xf4: 0x13, + // Block 0x4, offset 0x100 + 0x104: 0x0e, 0x105: 0x0f, + // Block 0x5, offset 0x140 + 0x140: 0x10, 0x141: 0x11, 0x142: 0x12, 0x144: 0x13, 0x145: 0x14, 0x146: 0x15, 0x147: 0x16, + 0x148: 0x17, 0x149: 0x18, 0x14a: 0x19, 0x14c: 0x1a, 0x14f: 0x1b, + 0x151: 0x1c, 0x152: 0x08, 0x153: 0x1d, 0x154: 0x1e, 0x155: 0x1f, 0x156: 0x20, 0x157: 0x21, + 0x158: 0x22, 0x159: 0x23, 0x15a: 0x24, 0x15b: 0x25, 0x15c: 0x26, 0x15d: 0x27, 0x15e: 0x28, 0x15f: 0x29, + 0x166: 0x2a, + 0x16c: 0x2b, 0x16d: 0x2c, + 0x17a: 0x2d, 0x17b: 0x2e, 0x17c: 0x0e, 0x17d: 0x0e, 0x17e: 0x0e, 0x17f: 0x2f, + // Block 0x6, offset 0x180 + 0x180: 0x30, 0x181: 0x31, 0x182: 0x32, 0x183: 0x33, 0x184: 0x34, 0x185: 0x35, 0x186: 0x36, 0x187: 0x37, + 0x188: 0x38, 0x189: 0x39, 0x18a: 0x0e, 0x18b: 0x3a, 0x18c: 0x0e, 0x18d: 0x0e, 0x18e: 0x0e, 0x18f: 0x0e, + 0x190: 0x0e, 0x191: 0x0e, 0x192: 0x0e, 0x193: 0x0e, 0x194: 0x0e, 0x195: 0x0e, 0x196: 0x0e, 0x197: 0x0e, + 0x198: 0x0e, 0x199: 0x0e, 0x19a: 0x0e, 0x19b: 0x0e, 0x19c: 0x0e, 0x19d: 0x0e, 0x19e: 0x0e, 0x19f: 0x0e, + 0x1a0: 0x0e, 0x1a1: 0x0e, 0x1a2: 0x0e, 0x1a3: 0x0e, 0x1a4: 0x0e, 0x1a5: 0x0e, 0x1a6: 0x0e, 0x1a7: 0x0e, + 0x1a8: 0x0e, 0x1a9: 0x0e, 0x1aa: 0x0e, 0x1ab: 0x0e, 0x1ac: 0x0e, 0x1ad: 0x0e, 0x1ae: 0x0e, 0x1af: 0x0e, + 0x1b0: 0x0e, 0x1b1: 0x0e, 0x1b2: 0x0e, 0x1b3: 0x0e, 0x1b4: 0x0e, 0x1b5: 0x0e, 0x1b6: 0x0e, 0x1b7: 0x0e, + 0x1b8: 0x0e, 0x1b9: 0x0e, 0x1ba: 0x0e, 0x1bb: 0x0e, 0x1bc: 0x0e, 0x1bd: 0x0e, 0x1be: 0x0e, 0x1bf: 0x0e, + // Block 0x7, offset 0x1c0 + 0x1c0: 0x0e, 0x1c1: 0x0e, 0x1c2: 0x0e, 0x1c3: 0x0e, 0x1c4: 0x0e, 0x1c5: 0x0e, 0x1c6: 0x0e, 0x1c7: 0x0e, + 0x1c8: 0x0e, 0x1c9: 0x0e, 0x1ca: 0x0e, 0x1cb: 0x0e, 0x1cc: 0x0e, 0x1cd: 0x0e, 0x1ce: 0x0e, 0x1cf: 0x0e, + 0x1d0: 0x0e, 0x1d1: 0x0e, 0x1d2: 0x0e, 0x1d3: 0x0e, 0x1d4: 0x0e, 0x1d5: 0x0e, 0x1d6: 0x0e, 0x1d7: 0x0e, + 0x1d8: 0x0e, 0x1d9: 0x0e, 0x1da: 0x0e, 0x1db: 0x0e, 0x1dc: 0x0e, 0x1dd: 0x0e, 0x1de: 0x0e, 0x1df: 0x0e, + 0x1e0: 0x0e, 0x1e1: 0x0e, 0x1e2: 0x0e, 0x1e3: 0x0e, 0x1e4: 0x0e, 0x1e5: 0x0e, 0x1e6: 0x0e, 0x1e7: 0x0e, + 0x1e8: 0x0e, 0x1e9: 0x0e, 0x1ea: 0x0e, 0x1eb: 0x0e, 0x1ec: 0x0e, 0x1ed: 0x0e, 0x1ee: 0x0e, 0x1ef: 0x0e, + 0x1f0: 0x0e, 0x1f1: 0x0e, 0x1f2: 0x0e, 0x1f3: 0x0e, 0x1f4: 0x0e, 0x1f5: 0x0e, 0x1f6: 0x0e, + 0x1f8: 0x0e, 0x1f9: 0x0e, 0x1fa: 0x0e, 0x1fb: 0x0e, 0x1fc: 0x0e, 0x1fd: 0x0e, 0x1fe: 0x0e, 0x1ff: 0x0e, + // Block 0x8, offset 0x200 + 0x200: 0x0e, 0x201: 0x0e, 0x202: 0x0e, 0x203: 0x0e, 0x204: 0x0e, 0x205: 0x0e, 0x206: 0x0e, 0x207: 0x0e, + 0x208: 0x0e, 0x209: 0x0e, 0x20a: 0x0e, 0x20b: 0x0e, 0x20c: 0x0e, 0x20d: 0x0e, 0x20e: 0x0e, 0x20f: 0x0e, + 0x210: 0x0e, 0x211: 0x0e, 0x212: 0x0e, 0x213: 0x0e, 0x214: 0x0e, 0x215: 0x0e, 0x216: 0x0e, 0x217: 0x0e, + 0x218: 0x0e, 0x219: 0x0e, 0x21a: 0x0e, 0x21b: 0x0e, 0x21c: 0x0e, 0x21d: 0x0e, 0x21e: 0x0e, 0x21f: 0x0e, + 0x220: 0x0e, 0x221: 0x0e, 0x222: 0x0e, 0x223: 0x0e, 0x224: 0x0e, 0x225: 0x0e, 0x226: 0x0e, 0x227: 0x0e, + 0x228: 0x0e, 0x229: 0x0e, 0x22a: 0x0e, 0x22b: 0x0e, 0x22c: 0x0e, 0x22d: 0x0e, 0x22e: 0x0e, 0x22f: 0x0e, + 0x230: 0x0e, 0x231: 0x0e, 0x232: 0x0e, 0x233: 0x0e, 0x234: 0x0e, 0x235: 0x0e, 0x236: 0x0e, 0x237: 0x0e, + 0x238: 0x0e, 0x239: 0x0e, 0x23a: 0x0e, 0x23b: 0x0e, 0x23c: 0x0e, 0x23d: 0x0e, 0x23e: 0x0e, 0x23f: 0x0e, + // Block 0x9, offset 0x240 + 0x240: 0x0e, 0x241: 0x0e, 0x242: 0x0e, 0x243: 0x0e, 0x244: 0x0e, 0x245: 0x0e, 0x246: 0x0e, 0x247: 0x0e, + 0x248: 0x0e, 0x249: 0x0e, 0x24a: 0x0e, 0x24b: 0x0e, 0x24c: 0x0e, 0x24d: 0x0e, 0x24e: 0x0e, 0x24f: 0x0e, + 0x250: 0x0e, 0x251: 0x0e, 0x252: 0x3b, 0x253: 0x3c, + 0x265: 0x3d, + 0x270: 0x0e, 0x271: 0x0e, 0x272: 0x0e, 0x273: 0x0e, 0x274: 0x0e, 0x275: 0x0e, 0x276: 0x0e, 0x277: 0x0e, + 0x278: 0x0e, 0x279: 0x0e, 0x27a: 0x0e, 0x27b: 0x0e, 0x27c: 0x0e, 0x27d: 0x0e, 0x27e: 0x0e, 0x27f: 0x0e, + // Block 0xa, offset 0x280 + 0x280: 0x0e, 0x281: 0x0e, 0x282: 0x0e, 0x283: 0x0e, 0x284: 0x0e, 0x285: 0x0e, 0x286: 0x0e, 0x287: 0x0e, + 0x288: 0x0e, 0x289: 0x0e, 0x28a: 0x0e, 0x28b: 0x0e, 0x28c: 0x0e, 0x28d: 0x0e, 0x28e: 0x0e, 0x28f: 0x0e, + 0x290: 0x0e, 0x291: 0x0e, 0x292: 0x0e, 0x293: 0x0e, 0x294: 0x0e, 0x295: 0x0e, 0x296: 0x0e, 0x297: 0x0e, + 0x298: 0x0e, 0x299: 0x0e, 0x29a: 0x0e, 0x29b: 0x0e, 0x29c: 0x0e, 0x29d: 0x0e, 0x29e: 0x3e, + // Block 0xb, offset 0x2c0 + 0x2c0: 0x08, 0x2c1: 0x08, 0x2c2: 0x08, 0x2c3: 0x08, 0x2c4: 0x08, 0x2c5: 0x08, 0x2c6: 0x08, 0x2c7: 0x08, + 0x2c8: 0x08, 0x2c9: 0x08, 0x2ca: 0x08, 0x2cb: 0x08, 0x2cc: 0x08, 0x2cd: 0x08, 0x2ce: 0x08, 0x2cf: 0x08, + 0x2d0: 0x08, 0x2d1: 0x08, 0x2d2: 0x08, 0x2d3: 0x08, 0x2d4: 0x08, 0x2d5: 0x08, 0x2d6: 0x08, 0x2d7: 0x08, + 0x2d8: 0x08, 0x2d9: 0x08, 0x2da: 0x08, 0x2db: 0x08, 0x2dc: 0x08, 0x2dd: 0x08, 0x2de: 0x08, 0x2df: 0x08, + 0x2e0: 0x08, 0x2e1: 0x08, 0x2e2: 0x08, 0x2e3: 0x08, 0x2e4: 0x08, 0x2e5: 0x08, 0x2e6: 0x08, 0x2e7: 0x08, + 0x2e8: 0x08, 0x2e9: 0x08, 0x2ea: 0x08, 0x2eb: 0x08, 0x2ec: 0x08, 0x2ed: 0x08, 0x2ee: 0x08, 0x2ef: 0x08, + 0x2f0: 0x08, 0x2f1: 0x08, 0x2f2: 0x08, 0x2f3: 0x08, 0x2f4: 0x08, 0x2f5: 0x08, 0x2f6: 0x08, 0x2f7: 0x08, + 0x2f8: 0x08, 0x2f9: 0x08, 0x2fa: 0x08, 0x2fb: 0x08, 0x2fc: 0x08, 0x2fd: 0x08, 0x2fe: 0x08, 0x2ff: 0x08, + // Block 0xc, offset 0x300 + 0x300: 0x08, 0x301: 0x08, 0x302: 0x08, 0x303: 0x08, 0x304: 0x08, 0x305: 0x08, 0x306: 0x08, 0x307: 0x08, + 0x308: 0x08, 0x309: 0x08, 0x30a: 0x08, 0x30b: 0x08, 0x30c: 0x08, 0x30d: 0x08, 0x30e: 0x08, 0x30f: 0x08, + 0x310: 0x08, 0x311: 0x08, 0x312: 0x08, 0x313: 0x08, 0x314: 0x08, 0x315: 0x08, 0x316: 0x08, 0x317: 0x08, + 0x318: 0x08, 0x319: 0x08, 0x31a: 0x08, 0x31b: 0x08, 0x31c: 0x08, 0x31d: 0x08, 0x31e: 0x08, 0x31f: 0x08, + 0x320: 0x08, 0x321: 0x08, 0x322: 0x08, 0x323: 0x08, 0x324: 0x0e, 0x325: 0x0e, 0x326: 0x0e, 0x327: 0x0e, + 0x328: 0x0e, 0x329: 0x0e, 0x32a: 0x0e, 0x32b: 0x0e, + 0x338: 0x3f, 0x339: 0x40, 0x33c: 0x41, 0x33d: 0x42, 0x33e: 0x43, 0x33f: 0x44, + // Block 0xd, offset 0x340 + 0x37f: 0x45, + // Block 0xe, offset 0x380 + 0x380: 0x0e, 0x381: 0x0e, 0x382: 0x0e, 0x383: 0x0e, 0x384: 0x0e, 0x385: 0x0e, 0x386: 0x0e, 0x387: 0x0e, + 0x388: 0x0e, 0x389: 0x0e, 0x38a: 0x0e, 0x38b: 0x0e, 0x38c: 0x0e, 0x38d: 0x0e, 0x38e: 0x0e, 0x38f: 0x0e, + 0x390: 0x0e, 0x391: 0x0e, 0x392: 0x0e, 0x393: 0x0e, 0x394: 0x0e, 0x395: 0x0e, 0x396: 0x0e, 0x397: 0x0e, + 0x398: 0x0e, 0x399: 0x0e, 0x39a: 0x0e, 0x39b: 0x0e, 0x39c: 0x0e, 0x39d: 0x0e, 0x39e: 0x0e, 0x39f: 0x46, + 0x3a0: 0x0e, 0x3a1: 0x0e, 0x3a2: 0x0e, 0x3a3: 0x0e, 0x3a4: 0x0e, 0x3a5: 0x0e, 0x3a6: 0x0e, 0x3a7: 0x0e, + 0x3a8: 0x0e, 0x3a9: 0x0e, 0x3aa: 0x0e, 0x3ab: 0x47, + // Block 0xf, offset 0x3c0 + 0x3c0: 0x0e, 0x3c1: 0x0e, 0x3c2: 0x0e, 0x3c3: 0x0e, 0x3c4: 0x48, 0x3c5: 0x49, 0x3c6: 0x0e, 0x3c7: 0x0e, + 0x3c8: 0x0e, 0x3c9: 0x0e, 0x3ca: 0x0e, 0x3cb: 0x4a, + // Block 0x10, offset 0x400 + 0x400: 0x4b, 0x403: 0x4c, 0x404: 0x4d, 0x405: 0x4e, 0x406: 0x4f, + 0x408: 0x50, 0x409: 0x51, 0x40c: 0x52, 0x40d: 0x53, 0x40e: 0x54, 0x40f: 0x55, + 0x410: 0x3a, 0x411: 0x56, 0x412: 0x0e, 0x413: 0x57, 0x414: 0x58, 0x415: 0x59, 0x416: 0x5a, 0x417: 0x5b, + 0x418: 0x0e, 0x419: 0x5c, 0x41a: 0x0e, 0x41b: 0x5d, 0x41f: 0x5e, + 0x424: 0x5f, 0x425: 0x60, 0x426: 0x61, 0x427: 0x62, + 0x429: 0x63, 0x42a: 0x64, + // Block 0x11, offset 0x440 + 0x456: 0x0b, 0x457: 0x06, + 0x458: 0x0c, 0x45b: 0x0d, 0x45f: 0x0e, + 0x460: 0x06, 0x461: 0x06, 0x462: 0x06, 0x463: 0x06, 0x464: 0x06, 0x465: 0x06, 0x466: 0x06, 0x467: 0x06, + 0x468: 0x06, 0x469: 0x06, 0x46a: 0x06, 0x46b: 0x06, 0x46c: 0x06, 0x46d: 0x06, 0x46e: 0x06, 0x46f: 0x06, + 0x470: 0x06, 0x471: 0x06, 0x472: 0x06, 0x473: 0x06, 0x474: 0x06, 0x475: 0x06, 0x476: 0x06, 0x477: 0x06, + 0x478: 0x06, 0x479: 0x06, 0x47a: 0x06, 0x47b: 0x06, 0x47c: 0x06, 0x47d: 0x06, 0x47e: 0x06, 0x47f: 0x06, + // Block 0x12, offset 0x480 + 0x484: 0x08, 0x485: 0x08, 0x486: 0x08, 0x487: 0x09, + // Block 0x13, offset 0x4c0 + 0x4c0: 0x08, 0x4c1: 0x08, 0x4c2: 0x08, 0x4c3: 0x08, 0x4c4: 0x08, 0x4c5: 0x08, 0x4c6: 0x08, 0x4c7: 0x08, + 0x4c8: 0x08, 0x4c9: 0x08, 0x4ca: 0x08, 0x4cb: 0x08, 0x4cc: 0x08, 0x4cd: 0x08, 0x4ce: 0x08, 0x4cf: 0x08, + 0x4d0: 0x08, 0x4d1: 0x08, 0x4d2: 0x08, 0x4d3: 0x08, 0x4d4: 0x08, 0x4d5: 0x08, 0x4d6: 0x08, 0x4d7: 0x08, + 0x4d8: 0x08, 0x4d9: 0x08, 0x4da: 0x08, 0x4db: 0x08, 0x4dc: 0x08, 0x4dd: 0x08, 0x4de: 0x08, 0x4df: 0x08, + 0x4e0: 0x08, 0x4e1: 0x08, 0x4e2: 0x08, 0x4e3: 0x08, 0x4e4: 0x08, 0x4e5: 0x08, 0x4e6: 0x08, 0x4e7: 0x08, + 0x4e8: 0x08, 0x4e9: 0x08, 0x4ea: 0x08, 0x4eb: 0x08, 0x4ec: 0x08, 0x4ed: 0x08, 0x4ee: 0x08, 0x4ef: 0x08, + 0x4f0: 0x08, 0x4f1: 0x08, 0x4f2: 0x08, 0x4f3: 0x08, 0x4f4: 0x08, 0x4f5: 0x08, 0x4f6: 0x08, 0x4f7: 0x08, + 0x4f8: 0x08, 0x4f9: 0x08, 0x4fa: 0x08, 0x4fb: 0x08, 0x4fc: 0x08, 0x4fd: 0x08, 0x4fe: 0x08, 0x4ff: 0x65, + // Block 0x14, offset 0x500 + 0x520: 0x10, + 0x530: 0x09, 0x531: 0x09, 0x532: 0x09, 0x533: 0x09, 0x534: 0x09, 0x535: 0x09, 0x536: 0x09, 0x537: 0x09, + 0x538: 0x09, 0x539: 0x09, 0x53a: 0x09, 0x53b: 0x09, 0x53c: 0x09, 0x53d: 0x09, 0x53e: 0x09, 0x53f: 0x11, + // Block 0x15, offset 0x540 + 0x540: 0x09, 0x541: 0x09, 0x542: 0x09, 0x543: 0x09, 0x544: 0x09, 0x545: 0x09, 0x546: 0x09, 0x547: 0x09, + 0x548: 0x09, 0x549: 0x09, 0x54a: 0x09, 0x54b: 0x09, 0x54c: 0x09, 0x54d: 0x09, 0x54e: 0x09, 0x54f: 0x11, +} + +// inverseData contains 4-byte entries of the following format: +// <0 padding> +// The last byte of the UTF-8-encoded rune is xor-ed with the last byte of the +// UTF-8 encoding of the original rune. Mappings often have the following +// pattern: +// A -> A (U+FF21 -> U+0041) +// B -> B (U+FF22 -> U+0042) +// ... +// By xor-ing the last byte the same entry can be shared by many mappings. This +// reduces the total number of distinct entries by about two thirds. +// The resulting entry for the aforementioned mappings is +// { 0x01, 0xE0, 0x00, 0x00 } +// Using this entry to map U+FF21 (UTF-8 [EF BC A1]), we get +// E0 ^ A1 = 41. +// Similarly, for U+FF22 (UTF-8 [EF BC A2]), we get +// E0 ^ A2 = 42. +// Note that because of the xor-ing, the byte sequence stored in the entry is +// not valid UTF-8. +var inverseData = [150][4]byte{ + {0x00, 0x00, 0x00, 0x00}, + {0x03, 0xe3, 0x80, 0xa0}, + {0x03, 0xef, 0xbc, 0xa0}, + {0x03, 0xef, 0xbc, 0xe0}, + {0x03, 0xef, 0xbd, 0xe0}, + {0x03, 0xef, 0xbf, 0x02}, + {0x03, 0xef, 0xbf, 0x00}, + {0x03, 0xef, 0xbf, 0x0e}, + {0x03, 0xef, 0xbf, 0x0c}, + {0x03, 0xef, 0xbf, 0x0f}, + {0x03, 0xef, 0xbf, 0x39}, + {0x03, 0xef, 0xbf, 0x3b}, + {0x03, 0xef, 0xbf, 0x3f}, + {0x03, 0xef, 0xbf, 0x2a}, + {0x03, 0xef, 0xbf, 0x0d}, + {0x03, 0xef, 0xbf, 0x25}, + {0x03, 0xef, 0xbd, 0x1a}, + {0x03, 0xef, 0xbd, 0x26}, + {0x01, 0xa0, 0x00, 0x00}, + {0x03, 0xef, 0xbd, 0x25}, + {0x03, 0xef, 0xbd, 0x23}, + {0x03, 0xef, 0xbd, 0x2e}, + {0x03, 0xef, 0xbe, 0x07}, + {0x03, 0xef, 0xbe, 0x05}, + {0x03, 0xef, 0xbd, 0x06}, + {0x03, 0xef, 0xbd, 0x13}, + {0x03, 0xef, 0xbd, 0x0b}, + {0x03, 0xef, 0xbd, 0x16}, + {0x03, 0xef, 0xbd, 0x0c}, + {0x03, 0xef, 0xbd, 0x15}, + {0x03, 0xef, 0xbd, 0x0d}, + {0x03, 0xef, 0xbd, 0x1c}, + {0x03, 0xef, 0xbd, 0x02}, + {0x03, 0xef, 0xbd, 0x1f}, + {0x03, 0xef, 0xbd, 0x1d}, + {0x03, 0xef, 0xbd, 0x17}, + {0x03, 0xef, 0xbd, 0x08}, + {0x03, 0xef, 0xbd, 0x09}, + {0x03, 0xef, 0xbd, 0x0e}, + {0x03, 0xef, 0xbd, 0x04}, + {0x03, 0xef, 0xbd, 0x05}, + {0x03, 0xef, 0xbe, 0x3f}, + {0x03, 0xef, 0xbe, 0x00}, + {0x03, 0xef, 0xbd, 0x2c}, + {0x03, 0xef, 0xbe, 0x06}, + {0x03, 0xef, 0xbe, 0x0c}, + {0x03, 0xef, 0xbe, 0x0f}, + {0x03, 0xef, 0xbe, 0x0d}, + {0x03, 0xef, 0xbe, 0x0b}, + {0x03, 0xef, 0xbe, 0x19}, + {0x03, 0xef, 0xbe, 0x15}, + {0x03, 0xef, 0xbe, 0x11}, + {0x03, 0xef, 0xbe, 0x31}, + {0x03, 0xef, 0xbe, 0x33}, + {0x03, 0xef, 0xbd, 0x0f}, + {0x03, 0xef, 0xbe, 0x30}, + {0x03, 0xef, 0xbe, 0x3e}, + {0x03, 0xef, 0xbe, 0x32}, + {0x03, 0xef, 0xbe, 0x36}, + {0x03, 0xef, 0xbd, 0x14}, + {0x03, 0xef, 0xbe, 0x2e}, + {0x03, 0xef, 0xbd, 0x1e}, + {0x03, 0xef, 0xbe, 0x10}, + {0x03, 0xef, 0xbf, 0x13}, + {0x03, 0xef, 0xbf, 0x15}, + {0x03, 0xef, 0xbf, 0x17}, + {0x03, 0xef, 0xbf, 0x1f}, + {0x03, 0xef, 0xbf, 0x1d}, + {0x03, 0xef, 0xbf, 0x1b}, + {0x03, 0xef, 0xbf, 0x09}, + {0x03, 0xef, 0xbf, 0x0b}, + {0x03, 0xef, 0xbf, 0x37}, + {0x03, 0xef, 0xbe, 0x04}, + {0x01, 0xe0, 0x00, 0x00}, + {0x03, 0xe2, 0xa6, 0x1a}, + {0x03, 0xe2, 0xa6, 0x26}, + {0x03, 0xe3, 0x80, 0x23}, + {0x03, 0xe3, 0x80, 0x2e}, + {0x03, 0xe3, 0x80, 0x25}, + {0x03, 0xe3, 0x83, 0x1e}, + {0x03, 0xe3, 0x83, 0x14}, + {0x03, 0xe3, 0x82, 0x06}, + {0x03, 0xe3, 0x82, 0x0b}, + {0x03, 0xe3, 0x82, 0x0c}, + {0x03, 0xe3, 0x82, 0x0d}, + {0x03, 0xe3, 0x82, 0x02}, + {0x03, 0xe3, 0x83, 0x0f}, + {0x03, 0xe3, 0x83, 0x08}, + {0x03, 0xe3, 0x83, 0x09}, + {0x03, 0xe3, 0x83, 0x2c}, + {0x03, 0xe3, 0x83, 0x0c}, + {0x03, 0xe3, 0x82, 0x13}, + {0x03, 0xe3, 0x82, 0x16}, + {0x03, 0xe3, 0x82, 0x15}, + {0x03, 0xe3, 0x82, 0x1c}, + {0x03, 0xe3, 0x82, 0x1f}, + {0x03, 0xe3, 0x82, 0x1d}, + {0x03, 0xe3, 0x82, 0x1a}, + {0x03, 0xe3, 0x82, 0x17}, + {0x03, 0xe3, 0x82, 0x08}, + {0x03, 0xe3, 0x82, 0x09}, + {0x03, 0xe3, 0x82, 0x0e}, + {0x03, 0xe3, 0x82, 0x04}, + {0x03, 0xe3, 0x82, 0x05}, + {0x03, 0xe3, 0x82, 0x3f}, + {0x03, 0xe3, 0x83, 0x00}, + {0x03, 0xe3, 0x83, 0x06}, + {0x03, 0xe3, 0x83, 0x05}, + {0x03, 0xe3, 0x83, 0x0d}, + {0x03, 0xe3, 0x83, 0x0b}, + {0x03, 0xe3, 0x83, 0x07}, + {0x03, 0xe3, 0x83, 0x19}, + {0x03, 0xe3, 0x83, 0x15}, + {0x03, 0xe3, 0x83, 0x11}, + {0x03, 0xe3, 0x83, 0x31}, + {0x03, 0xe3, 0x83, 0x33}, + {0x03, 0xe3, 0x83, 0x30}, + {0x03, 0xe3, 0x83, 0x3e}, + {0x03, 0xe3, 0x83, 0x32}, + {0x03, 0xe3, 0x83, 0x36}, + {0x03, 0xe3, 0x83, 0x2e}, + {0x03, 0xe3, 0x82, 0x07}, + {0x03, 0xe3, 0x85, 0x04}, + {0x03, 0xe3, 0x84, 0x10}, + {0x03, 0xe3, 0x85, 0x30}, + {0x03, 0xe3, 0x85, 0x0d}, + {0x03, 0xe3, 0x85, 0x13}, + {0x03, 0xe3, 0x85, 0x15}, + {0x03, 0xe3, 0x85, 0x17}, + {0x03, 0xe3, 0x85, 0x1f}, + {0x03, 0xe3, 0x85, 0x1d}, + {0x03, 0xe3, 0x85, 0x1b}, + {0x03, 0xe3, 0x85, 0x09}, + {0x03, 0xe3, 0x85, 0x0f}, + {0x03, 0xe3, 0x85, 0x0b}, + {0x03, 0xe3, 0x85, 0x37}, + {0x03, 0xe3, 0x85, 0x3b}, + {0x03, 0xe3, 0x85, 0x39}, + {0x03, 0xe3, 0x85, 0x3f}, + {0x02, 0xc2, 0x02, 0x00}, + {0x02, 0xc2, 0x0e, 0x00}, + {0x02, 0xc2, 0x0c, 0x00}, + {0x02, 0xc2, 0x00, 0x00}, + {0x03, 0xe2, 0x82, 0x0f}, + {0x03, 0xe2, 0x94, 0x2a}, + {0x03, 0xe2, 0x86, 0x39}, + {0x03, 0xe2, 0x86, 0x3b}, + {0x03, 0xe2, 0x86, 0x3f}, + {0x03, 0xe2, 0x96, 0x0d}, + {0x03, 0xe2, 0x97, 0x25}, +} + +// Total table size 15320 bytes (14KiB) diff --git a/vendor/golang.org/x/tools/cmd/goimports/doc.go b/vendor/golang.org/x/tools/cmd/goimports/doc.go new file mode 100644 index 00000000000..7033e4d4cff --- /dev/null +++ b/vendor/golang.org/x/tools/cmd/goimports/doc.go @@ -0,0 +1,43 @@ +/* + +Command goimports updates your Go import lines, +adding missing ones and removing unreferenced ones. + + $ go get golang.org/x/tools/cmd/goimports + +In addition to fixing imports, goimports also formats +your code in the same style as gofmt so it can be used +as a replacement for your editor's gofmt-on-save hook. + +For emacs, make sure you have the latest go-mode.el: + https://github.com/dominikh/go-mode.el +Then in your .emacs file: + (setq gofmt-command "goimports") + (add-hook 'before-save-hook 'gofmt-before-save) + +For vim, set "gofmt_command" to "goimports": + https://golang.org/change/39c724dd7f252 + https://golang.org/wiki/IDEsAndTextEditorPlugins + etc + +For GoSublime, follow the steps described here: + http://michaelwhatcott.com/gosublime-goimports/ + +For other editors, you probably know what to do. + +To exclude directories in your $GOPATH from being scanned for Go +files, goimports respects a configuration file at +$GOPATH/src/.goimportsignore which may contain blank lines, comment +lines (beginning with '#'), or lines naming a directory relative to +the configuration file to ignore when scanning. No globbing or regex +patterns are allowed. Use the "-v" verbose flag to verify it's +working and see what goimports is doing. + +File bugs or feature requests at: + + https://golang.org/issues/new?title=x/tools/cmd/goimports:+ + +Happy hacking! + +*/ +package main // import "golang.org/x/tools/cmd/goimports" diff --git a/vendor/golang.org/x/tools/cmd/goimports/goimports.go b/vendor/golang.org/x/tools/cmd/goimports/goimports.go new file mode 100644 index 00000000000..27708972d1e --- /dev/null +++ b/vendor/golang.org/x/tools/cmd/goimports/goimports.go @@ -0,0 +1,380 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "bufio" + "bytes" + "errors" + "flag" + "fmt" + "go/scanner" + "io" + "io/ioutil" + "log" + "os" + "os/exec" + "path/filepath" + "runtime" + "runtime/pprof" + "strings" + + "golang.org/x/tools/internal/gocommand" + "golang.org/x/tools/internal/imports" +) + +var ( + // main operation modes + list = flag.Bool("l", false, "list files whose formatting differs from goimport's") + write = flag.Bool("w", false, "write result to (source) file instead of stdout") + doDiff = flag.Bool("d", false, "display diffs instead of rewriting files") + srcdir = flag.String("srcdir", "", "choose imports as if source code is from `dir`. When operating on a single file, dir may instead be the complete file name.") + + verbose bool // verbose logging + + cpuProfile = flag.String("cpuprofile", "", "CPU profile output") + memProfile = flag.String("memprofile", "", "memory profile output") + memProfileRate = flag.Int("memrate", 0, "if > 0, sets runtime.MemProfileRate") + + options = &imports.Options{ + TabWidth: 8, + TabIndent: true, + Comments: true, + Fragment: true, + Env: &imports.ProcessEnv{ + GocmdRunner: &gocommand.Runner{}, + }, + } + exitCode = 0 +) + +func init() { + flag.BoolVar(&options.AllErrors, "e", false, "report all errors (not just the first 10 on different lines)") + flag.StringVar(&options.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list") + flag.BoolVar(&options.FormatOnly, "format-only", false, "if true, don't fix imports and only format. In this mode, goimports is effectively gofmt, with the addition that imports are grouped into sections.") +} + +func report(err error) { + scanner.PrintError(os.Stderr, err) + exitCode = 2 +} + +func usage() { + fmt.Fprintf(os.Stderr, "usage: goimports [flags] [path ...]\n") + flag.PrintDefaults() + os.Exit(2) +} + +func isGoFile(f os.FileInfo) bool { + // ignore non-Go files + name := f.Name() + return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") +} + +// argumentType is which mode goimports was invoked as. +type argumentType int + +const ( + // fromStdin means the user is piping their source into goimports. + fromStdin argumentType = iota + + // singleArg is the common case from editors, when goimports is run on + // a single file. + singleArg + + // multipleArg is when the user ran "goimports file1.go file2.go" + // or ran goimports on a directory tree. + multipleArg +) + +func processFile(filename string, in io.Reader, out io.Writer, argType argumentType) error { + opt := options + if argType == fromStdin { + nopt := *options + nopt.Fragment = true + opt = &nopt + } + + if in == nil { + f, err := os.Open(filename) + if err != nil { + return err + } + defer f.Close() + in = f + } + + src, err := ioutil.ReadAll(in) + if err != nil { + return err + } + + target := filename + if *srcdir != "" { + // Determine whether the provided -srcdirc is a directory or file + // and then use it to override the target. + // + // See https://github.com/dominikh/go-mode.el/issues/146 + if isFile(*srcdir) { + if argType == multipleArg { + return errors.New("-srcdir value can't be a file when passing multiple arguments or when walking directories") + } + target = *srcdir + } else if argType == singleArg && strings.HasSuffix(*srcdir, ".go") && !isDir(*srcdir) { + // For a file which doesn't exist on disk yet, but might shortly. + // e.g. user in editor opens $DIR/newfile.go and newfile.go doesn't yet exist on disk. + // The goimports on-save hook writes the buffer to a temp file + // first and runs goimports before the actual save to newfile.go. + // The editor's buffer is named "newfile.go" so that is passed to goimports as: + // goimports -srcdir=/gopath/src/pkg/newfile.go /tmp/gofmtXXXXXXXX.go + // and then the editor reloads the result from the tmp file and writes + // it to newfile.go. + target = *srcdir + } else { + // Pretend that file is from *srcdir in order to decide + // visible imports correctly. + target = filepath.Join(*srcdir, filepath.Base(filename)) + } + } + + res, err := imports.Process(target, src, opt) + if err != nil { + return err + } + + if !bytes.Equal(src, res) { + // formatting has changed + if *list { + fmt.Fprintln(out, filename) + } + if *write { + if argType == fromStdin { + // filename is "" + return errors.New("can't use -w on stdin") + } + // On Windows, we need to re-set the permissions from the file. See golang/go#38225. + var perms os.FileMode + if fi, err := os.Stat(filename); err == nil { + perms = fi.Mode() & os.ModePerm + } + err = ioutil.WriteFile(filename, res, perms) + if err != nil { + return err + } + } + if *doDiff { + if argType == fromStdin { + filename = "stdin.go" // because .orig looks silly + } + data, err := diff(src, res, filename) + if err != nil { + return fmt.Errorf("computing diff: %s", err) + } + fmt.Printf("diff -u %s %s\n", filepath.ToSlash(filename+".orig"), filepath.ToSlash(filename)) + out.Write(data) + } + } + + if !*list && !*write && !*doDiff { + _, err = out.Write(res) + } + + return err +} + +func visitFile(path string, f os.FileInfo, err error) error { + if err == nil && isGoFile(f) { + err = processFile(path, nil, os.Stdout, multipleArg) + } + if err != nil { + report(err) + } + return nil +} + +func walkDir(path string) { + filepath.Walk(path, visitFile) +} + +func main() { + runtime.GOMAXPROCS(runtime.NumCPU()) + + // call gofmtMain in a separate function + // so that it can use defer and have them + // run before the exit. + gofmtMain() + os.Exit(exitCode) +} + +// parseFlags parses command line flags and returns the paths to process. +// It's a var so that custom implementations can replace it in other files. +var parseFlags = func() []string { + flag.BoolVar(&verbose, "v", false, "verbose logging") + + flag.Parse() + return flag.Args() +} + +func bufferedFileWriter(dest string) (w io.Writer, close func()) { + f, err := os.Create(dest) + if err != nil { + log.Fatal(err) + } + bw := bufio.NewWriter(f) + return bw, func() { + if err := bw.Flush(); err != nil { + log.Fatalf("error flushing %v: %v", dest, err) + } + if err := f.Close(); err != nil { + log.Fatal(err) + } + } +} + +func gofmtMain() { + flag.Usage = usage + paths := parseFlags() + + if *cpuProfile != "" { + bw, flush := bufferedFileWriter(*cpuProfile) + pprof.StartCPUProfile(bw) + defer flush() + defer pprof.StopCPUProfile() + } + // doTrace is a conditionally compiled wrapper around runtime/trace. It is + // used to allow goimports to compile under gccgo, which does not support + // runtime/trace. See https://golang.org/issue/15544. + defer doTrace()() + if *memProfileRate > 0 { + runtime.MemProfileRate = *memProfileRate + bw, flush := bufferedFileWriter(*memProfile) + defer func() { + runtime.GC() // materialize all statistics + if err := pprof.WriteHeapProfile(bw); err != nil { + log.Fatal(err) + } + flush() + }() + } + + if verbose { + log.SetFlags(log.LstdFlags | log.Lmicroseconds) + options.Env.Logf = log.Printf + } + if options.TabWidth < 0 { + fmt.Fprintf(os.Stderr, "negative tabwidth %d\n", options.TabWidth) + exitCode = 2 + return + } + + if len(paths) == 0 { + if err := processFile("", os.Stdin, os.Stdout, fromStdin); err != nil { + report(err) + } + return + } + + argType := singleArg + if len(paths) > 1 { + argType = multipleArg + } + + for _, path := range paths { + switch dir, err := os.Stat(path); { + case err != nil: + report(err) + case dir.IsDir(): + walkDir(path) + default: + if err := processFile(path, nil, os.Stdout, argType); err != nil { + report(err) + } + } + } +} + +func writeTempFile(dir, prefix string, data []byte) (string, error) { + file, err := ioutil.TempFile(dir, prefix) + if err != nil { + return "", err + } + _, err = file.Write(data) + if err1 := file.Close(); err == nil { + err = err1 + } + if err != nil { + os.Remove(file.Name()) + return "", err + } + return file.Name(), nil +} + +func diff(b1, b2 []byte, filename string) (data []byte, err error) { + f1, err := writeTempFile("", "gofmt", b1) + if err != nil { + return + } + defer os.Remove(f1) + + f2, err := writeTempFile("", "gofmt", b2) + if err != nil { + return + } + defer os.Remove(f2) + + cmd := "diff" + if runtime.GOOS == "plan9" { + cmd = "/bin/ape/diff" + } + + data, err = exec.Command(cmd, "-u", f1, f2).CombinedOutput() + if len(data) > 0 { + // diff exits with a non-zero status when the files don't match. + // Ignore that failure as long as we get output. + return replaceTempFilename(data, filename) + } + return +} + +// replaceTempFilename replaces temporary filenames in diff with actual one. +// +// --- /tmp/gofmt316145376 2017-02-03 19:13:00.280468375 -0500 +// +++ /tmp/gofmt617882815 2017-02-03 19:13:00.280468375 -0500 +// ... +// -> +// --- path/to/file.go.orig 2017-02-03 19:13:00.280468375 -0500 +// +++ path/to/file.go 2017-02-03 19:13:00.280468375 -0500 +// ... +func replaceTempFilename(diff []byte, filename string) ([]byte, error) { + bs := bytes.SplitN(diff, []byte{'\n'}, 3) + if len(bs) < 3 { + return nil, fmt.Errorf("got unexpected diff for %s", filename) + } + // Preserve timestamps. + var t0, t1 []byte + if i := bytes.LastIndexByte(bs[0], '\t'); i != -1 { + t0 = bs[0][i:] + } + if i := bytes.LastIndexByte(bs[1], '\t'); i != -1 { + t1 = bs[1][i:] + } + // Always print filepath with slash separator. + f := filepath.ToSlash(filename) + bs[0] = []byte(fmt.Sprintf("--- %s%s", f+".orig", t0)) + bs[1] = []byte(fmt.Sprintf("+++ %s%s", f, t1)) + return bytes.Join(bs, []byte{'\n'}), nil +} + +// isFile reports whether name is a file. +func isFile(name string) bool { + fi, err := os.Stat(name) + return err == nil && fi.Mode().IsRegular() +} + +// isDir reports whether name is a directory. +func isDir(name string) bool { + fi, err := os.Stat(name) + return err == nil && fi.IsDir() +} diff --git a/vendor/golang.org/x/tools/cmd/goimports/goimports_gc.go b/vendor/golang.org/x/tools/cmd/goimports/goimports_gc.go new file mode 100644 index 00000000000..21d867eaab5 --- /dev/null +++ b/vendor/golang.org/x/tools/cmd/goimports/goimports_gc.go @@ -0,0 +1,26 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build gc + +package main + +import ( + "flag" + "runtime/trace" +) + +var traceProfile = flag.String("trace", "", "trace profile output") + +func doTrace() func() { + if *traceProfile != "" { + bw, flush := bufferedFileWriter(*traceProfile) + trace.Start(bw) + return func() { + flush() + trace.Stop() + } + } + return func() {} +} diff --git a/vendor/golang.org/x/tools/cmd/goimports/goimports_not_gc.go b/vendor/golang.org/x/tools/cmd/goimports/goimports_not_gc.go new file mode 100644 index 00000000000..f5531ceb317 --- /dev/null +++ b/vendor/golang.org/x/tools/cmd/goimports/goimports_not_gc.go @@ -0,0 +1,11 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !gc + +package main + +func doTrace() func() { + return func() {} +} diff --git a/vendor/golang.org/x/tools/go/analysis/analysistest/analysistest.go b/vendor/golang.org/x/tools/go/analysis/analysistest/analysistest.go index 506b77fbfbd..5b22053d00d 100644 --- a/vendor/golang.org/x/tools/go/analysis/analysistest/analysistest.go +++ b/vendor/golang.org/x/tools/go/analysis/analysistest/analysistest.go @@ -2,6 +2,7 @@ package analysistest import ( + "bytes" "fmt" "go/format" "go/token" @@ -23,6 +24,7 @@ import ( "golang.org/x/tools/internal/lsp/diff/myers" "golang.org/x/tools/internal/span" "golang.org/x/tools/internal/testenv" + "golang.org/x/tools/txtar" ) // WriteFiles is a helper function that creates a temporary directory @@ -65,10 +67,38 @@ type Testing interface { Errorf(format string, args ...interface{}) } +// RunWithSuggestedFixes behaves like Run, but additionally verifies suggested fixes. +// It uses golden files placed alongside the source code under analysis: +// suggested fixes for code in example.go will be compared against example.go.golden. +// +// Golden files can be formatted in one of two ways: as plain Go source code, or as txtar archives. +// In the first case, all suggested fixes will be applied to the original source, which will then be compared against the golden file. +// In the second case, suggested fixes will be grouped by their messages, and each set of fixes will be applied and tested separately. +// Each section in the archive corresponds to a single message. +// +// A golden file using txtar may look like this: +// -- turn into single negation -- +// package pkg +// +// func fn(b1, b2 bool) { +// if !b1 { // want `negating a boolean twice` +// println() +// } +// } +// +// -- remove double negation -- +// package pkg +// +// func fn(b1, b2 bool) { +// if b1 { // want `negating a boolean twice` +// println() +// } +// } func RunWithSuggestedFixes(t Testing, dir string, a *analysis.Analyzer, patterns ...string) []*Result { r := Run(t, dir, a, patterns...) - fileEdits := make(map[*token.File][]diff.TextEdit) + // file -> message -> edits + fileEdits := make(map[*token.File]map[string][]diff.TextEdit) fileContents := make(map[*token.File][]byte) // Validate edits, prepare the fileEdits map and read the file contents. @@ -101,7 +131,11 @@ func RunWithSuggestedFixes(t Testing, dir string, a *analysis.Analyzer, patterns if err != nil { t.Errorf("error converting edit to span %s: %v", file.Name(), err) } - fileEdits[file] = append(fileEdits[file], diff.TextEdit{ + + if _, ok := fileEdits[file]; !ok { + fileEdits[file] = make(map[string][]diff.TextEdit) + } + fileEdits[file][sf.Message] = append(fileEdits[file][sf.Message], diff.TextEdit{ Span: spn, NewText: string(edit.NewText), }) @@ -110,27 +144,77 @@ func RunWithSuggestedFixes(t Testing, dir string, a *analysis.Analyzer, patterns } } - for file, edits := range fileEdits { + for file, fixes := range fileEdits { // Get the original file contents. orig, ok := fileContents[file] if !ok { t.Errorf("could not find file contents for %s", file.Name()) continue } - out := diff.ApplyEdits(string(orig), edits) + // Get the golden file and read the contents. - want, err := ioutil.ReadFile(file.Name() + ".golden") + ar, err := txtar.ParseFile(file.Name() + ".golden") if err != nil { t.Errorf("error reading %s.golden: %v", file.Name(), err) continue } - formatted, err := format.Source([]byte(out)) - if err != nil { - continue - } - if string(want) != string(formatted) { - d := myers.ComputeEdits("", string(want), string(formatted)) - t.Errorf("suggested fixes failed for %s:\n%s", file.Name(), diff.ToUnified(file.Name()+".golden", "actual", string(want), d)) + + if len(ar.Files) > 0 { + // one virtual file per kind of suggested fix + + if len(ar.Comment) != 0 { + // we allow either just the comment, or just virtual + // files, not both. it is not clear how "both" should + // behave. + t.Errorf("%s.golden has leading comment; we don't know what to do with it", file.Name()) + continue + } + + for sf, edits := range fixes { + found := false + for _, vf := range ar.Files { + if vf.Name == sf { + found = true + out := diff.ApplyEdits(string(orig), edits) + // the file may contain multiple trailing + // newlines if the user places empty lines + // between files in the archive. normalize + // this to a single newline. + want := string(bytes.TrimRight(vf.Data, "\n")) + "\n" + formatted, err := format.Source([]byte(out)) + if err != nil { + continue + } + if want != string(formatted) { + d := myers.ComputeEdits("", want, string(formatted)) + t.Errorf("suggested fixes failed for %s:\n%s", file.Name(), diff.ToUnified(fmt.Sprintf("%s.golden [%s]", file.Name(), sf), "actual", want, d)) + } + break + } + } + if !found { + t.Errorf("no section for suggested fix %q in %s.golden", sf, file.Name()) + } + } + } else { + // all suggested fixes are represented by a single file + + var catchallEdits []diff.TextEdit + for _, edits := range fixes { + catchallEdits = append(catchallEdits, edits...) + } + + out := diff.ApplyEdits(string(orig), catchallEdits) + want := string(ar.Comment) + + formatted, err := format.Source([]byte(out)) + if err != nil { + continue + } + if want != string(formatted) { + d := myers.ComputeEdits("", want, string(formatted)) + t.Errorf("suggested fixes failed for %s:\n%s", file.Name(), diff.ToUnified(file.Name()+".golden", "actual", want, d)) + } } } return r diff --git a/vendor/golang.org/x/tools/go/analysis/doc.go b/vendor/golang.org/x/tools/go/analysis/doc.go index ea56b724e8b..fb17a0e4154 100644 --- a/vendor/golang.org/x/tools/go/analysis/doc.go +++ b/vendor/golang.org/x/tools/go/analysis/doc.go @@ -170,6 +170,15 @@ Diagnostic is defined as: The optional Category field is a short identifier that classifies the kind of message when an analysis produces several kinds of diagnostic. +Many analyses want to associate diagnostics with a severity level. +Because Diagnostic does not have a severity level field, an Analyzer's +diagnostics effectively all have the same severity level. To separate which +diagnostics are high severity and which are low severity, expose multiple +Analyzers instead. Analyzers should also be separated when their +diagnostics belong in different groups, or could be tagged differently +before being shown to the end user. Analyzers should document their severity +level to help downstream tools surface diagnostics properly. + Most Analyzers inspect typed Go syntax trees, but a few, such as asmdecl and buildtag, inspect the raw text of Go source files or even non-Go files such as assembly. To report a diagnostic against a line of a diff --git a/vendor/golang.org/x/tools/go/analysis/internal/checker/checker.go b/vendor/golang.org/x/tools/go/analysis/internal/checker/checker.go index a26f801b581..5ccfb163748 100644 --- a/vendor/golang.org/x/tools/go/analysis/internal/checker/checker.go +++ b/vendor/golang.org/x/tools/go/analysis/internal/checker/checker.go @@ -800,8 +800,13 @@ func exportedFrom(obj types.Object, pkg *types.Package) bool { return obj.Exported() && obj.Pkg() == pkg || obj.Type().(*types.Signature).Recv() != nil case *types.Var: - return obj.Exported() && obj.Pkg() == pkg || - obj.IsField() + if obj.IsField() { + return true + } + // we can't filter more aggressively than this because we need + // to consider function parameters exported, but have no way + // of telling apart function parameters from local variables. + return obj.Pkg() == pkg case *types.TypeName, *types.Const: return true } diff --git a/vendor/golang.org/x/tools/go/analysis/passes/printf/printf.go b/vendor/golang.org/x/tools/go/analysis/passes/printf/printf.go index 14f3a47610b..ddad4c796cb 100644 --- a/vendor/golang.org/x/tools/go/analysis/passes/printf/printf.go +++ b/vendor/golang.org/x/tools/go/analysis/passes/printf/printf.go @@ -805,6 +805,7 @@ var printVerbs = []printVerb{ {'g', sharpNumFlag, argFloat | argComplex}, {'G', sharpNumFlag, argFloat | argComplex}, {'o', sharpNumFlag, argInt | argPointer}, + {'O', sharpNumFlag, argInt | argPointer}, {'p', "-#", argPointer}, {'q', " -+.0#", argRune | argInt | argString}, {'s', " -+.0", argString}, diff --git a/vendor/golang.org/x/tools/go/packages/golist.go b/vendor/golang.org/x/tools/go/packages/golist.go index 88ca6691de5..1a5aba9f9f3 100644 --- a/vendor/golang.org/x/tools/go/packages/golist.go +++ b/vendor/golang.org/x/tools/go/packages/golist.go @@ -24,7 +24,6 @@ import ( "golang.org/x/tools/go/internal/packagesdriver" "golang.org/x/tools/internal/gocommand" - "golang.org/x/tools/internal/packagesinternal" "golang.org/x/xerrors" ) @@ -382,7 +381,7 @@ type jsonPackage struct { Imports []string ImportMap map[string]string Deps []string - Module *packagesinternal.Module + Module *Module TestGoFiles []string TestImports []string XTestGoFiles []string @@ -541,7 +540,26 @@ func (state *golistState) createDriverResponse(words ...string) (*driverResponse CompiledGoFiles: absJoin(p.Dir, p.CompiledGoFiles), OtherFiles: absJoin(p.Dir, otherFiles(p)...), forTest: p.ForTest, - module: p.Module, + Module: p.Module, + } + + if (state.cfg.Mode&typecheckCgo) != 0 && len(p.CgoFiles) != 0 { + if len(p.CompiledGoFiles) > len(p.GoFiles) { + // We need the cgo definitions, which are in the first + // CompiledGoFile after the non-cgo ones. This is a hack but there + // isn't currently a better way to find it. We also need the pure + // Go files and unprocessed cgo files, all of which are already + // in pkg.GoFiles. + cgoTypes := p.CompiledGoFiles[len(p.GoFiles)] + pkg.CompiledGoFiles = append([]string{cgoTypes}, pkg.GoFiles...) + } else { + // golang/go#38990: go list silently fails to do cgo processing + pkg.CompiledGoFiles = nil + pkg.Errors = append(pkg.Errors, Error{ + Msg: "go list failed to return CompiledGoFiles; https://golang.org/issue/38990?", + Kind: ListError, + }) + } } // Work around https://golang.org/issue/28749: @@ -617,6 +635,23 @@ func (state *golistState) createDriverResponse(words ...string) (*driverResponse pkg.CompiledGoFiles = pkg.GoFiles } + // Temporary work-around for golang/go#39986. Parse filenames out of + // error messages. This happens if there are unrecoverable syntax + // errors in the source, so we can't match on a specific error message. + if err := p.Error; err != nil && len(err.ImportStack) == 0 && len(pkg.CompiledGoFiles) == 0 { + if split := strings.Split(err.Pos, ":"); len(split) > 1 { + if filename := split[0]; filename != "" { + if !filepath.IsAbs(filename) { + filename = filepath.Join(state.cfg.Dir, filename) + } + if info, _ := os.Stat(filename); info != nil { + pkg.CompiledGoFiles = append(pkg.CompiledGoFiles, filename) + pkg.GoFiles = append(pkg.GoFiles, filename) + } + } + } + } + if p.Error != nil { msg := strings.TrimSpace(p.Error.Err) // Trim to work around golang.org/issue/32363. // Address golang.org/issue/35964 by appending import stack to error message. diff --git a/vendor/golang.org/x/tools/go/packages/golist_overlay.go b/vendor/golang.org/x/tools/go/packages/golist_overlay.go index 3c99b6e48d7..4eabfd98c63 100644 --- a/vendor/golang.org/x/tools/go/packages/golist_overlay.go +++ b/vendor/golang.org/x/tools/go/packages/golist_overlay.go @@ -70,9 +70,9 @@ func (state *golistState) processGolistOverlay(response *responseDeduper) (modif // to the overlay. continue } - // if all the overlay files belong to a different package, change the package - // name to that package. Otherwise leave it alone; there will be an error message. - maybeFixPackageName(pkgName, pkgOfDir, dir) + // If all the overlay files belong to a different package, change the + // package name to that package. + maybeFixPackageName(pkgName, isTestFile, pkgOfDir[dir]) nextPackage: for _, p := range response.dr.Packages { if pkgName != p.Name && p.ID != "command-line-arguments" { @@ -102,8 +102,11 @@ func (state *golistState) processGolistOverlay(response *responseDeduper) (modif } } } - // The overlay could have included an entirely new package. - if pkg == nil { + // The overlay could have included an entirely new package or an + // ad-hoc package. An ad-hoc package is one that we have manually + // constructed from inadequate `go list` results for a file= query. + // It will have the ID command-line-arguments. + if pkg == nil || pkg.ID == "command-line-arguments" { // Try to find the module or gopath dir the file is contained in. // Then for modules, add the module opath to the beginning. pkgPath, ok, err := state.getPkgPath(dir) @@ -113,34 +116,53 @@ func (state *golistState) processGolistOverlay(response *responseDeduper) (modif if !ok { break } + var forTest string // only set for x tests isXTest := strings.HasSuffix(pkgName, "_test") if isXTest { + forTest = pkgPath pkgPath += "_test" } id := pkgPath - if isTestFile && !isXTest { - id = fmt.Sprintf("%s [%s.test]", pkgPath, pkgPath) - } - // Try to reclaim a package with the same id if it exists in the response. - for _, p := range response.dr.Packages { - if reclaimPackage(p, id, opath, contents) { - pkg = p - break + if isTestFile { + if isXTest { + id = fmt.Sprintf("%s [%s.test]", pkgPath, forTest) + } else { + id = fmt.Sprintf("%s [%s.test]", pkgPath, pkgPath) } } - // Otherwise, create a new package - if pkg == nil { - pkg = &Package{PkgPath: pkgPath, ID: id, Name: pkgName, Imports: make(map[string]*Package)} - response.addPackage(pkg) - havePkgs[pkg.PkgPath] = id - // Add the production package's sources for a test variant. - if isTestFile && !isXTest && testVariantOf != nil { - pkg.GoFiles = append(pkg.GoFiles, testVariantOf.GoFiles...) - pkg.CompiledGoFiles = append(pkg.CompiledGoFiles, testVariantOf.CompiledGoFiles...) - // Add the package under test and its imports to the test variant. - pkg.forTest = testVariantOf.PkgPath - for k, v := range testVariantOf.Imports { - pkg.Imports[k] = &Package{ID: v.ID} + if pkg != nil { + // TODO(rstambler): We should change the package's path and ID + // here. The only issue is that this messes with the roots. + } else { + // Try to reclaim a package with the same ID, if it exists in the response. + for _, p := range response.dr.Packages { + if reclaimPackage(p, id, opath, contents) { + pkg = p + break + } + } + // Otherwise, create a new package. + if pkg == nil { + pkg = &Package{ + PkgPath: pkgPath, + ID: id, + Name: pkgName, + Imports: make(map[string]*Package), + } + response.addPackage(pkg) + havePkgs[pkg.PkgPath] = id + // Add the production package's sources for a test variant. + if isTestFile && !isXTest && testVariantOf != nil { + pkg.GoFiles = append(pkg.GoFiles, testVariantOf.GoFiles...) + pkg.CompiledGoFiles = append(pkg.CompiledGoFiles, testVariantOf.CompiledGoFiles...) + // Add the package under test and its imports to the test variant. + pkg.forTest = testVariantOf.PkgPath + for k, v := range testVariantOf.Imports { + pkg.Imports[k] = &Package{ID: v.ID} + } + } + if isXTest { + pkg.forTest = forTest } } } @@ -158,6 +180,8 @@ func (state *golistState) processGolistOverlay(response *responseDeduper) (modif continue } for _, imp := range imports { + // TODO(rstambler): If the package is an x test and the import has + // a test variant, make sure to replace it. if _, found := pkg.Imports[imp]; found { continue } @@ -415,24 +439,35 @@ func commonDir(a []string) string { // package name, and they all have the same package name, then that name becomes // the package name. // It returns true if it changes the package name, false otherwise. -func maybeFixPackageName(newName string, pkgOfDir map[string][]*Package, dir string) bool { +func maybeFixPackageName(newName string, isTestFile bool, pkgsOfDir []*Package) { names := make(map[string]int) - for _, p := range pkgOfDir[dir] { + for _, p := range pkgsOfDir { names[p.Name]++ } if len(names) != 1 { // some files are in different packages - return false + return } - oldName := "" + var oldName string for k := range names { oldName = k } if newName == oldName { - return false - } - for _, p := range pkgOfDir[dir] { + return + } + // We might have a case where all of the package names in the directory are + // the same, but the overlay file is for an x test, which belongs to its + // own package. If the x test does not yet exist on disk, we may not yet + // have its package name on disk, but we should not rename the packages. + // + // We use a heuristic to determine if this file belongs to an x test: + // The test file should have a package name whose package name has a _test + // suffix or looks like "newName_test". + maybeXTest := strings.HasPrefix(oldName+"_test", newName) || strings.HasSuffix(newName, "_test") + if isTestFile && maybeXTest { + return + } + for _, p := range pkgsOfDir { p.Name = newName } - return true } diff --git a/vendor/golang.org/x/tools/go/packages/packages.go b/vendor/golang.org/x/tools/go/packages/packages.go index 03fd999c0cb..04053f1e7d4 100644 --- a/vendor/golang.org/x/tools/go/packages/packages.go +++ b/vendor/golang.org/x/tools/go/packages/packages.go @@ -21,10 +21,12 @@ import ( "path/filepath" "strings" "sync" + "time" "golang.org/x/tools/go/gcexportdata" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/packagesinternal" + "golang.org/x/tools/internal/typesinternal" ) // A LoadMode controls the amount of detail to return when loading. @@ -70,6 +72,13 @@ const ( // NeedTypesSizes adds TypesSizes. NeedTypesSizes + + // typecheckCgo enables full support for type checking cgo. Requires Go 1.15+. + // Modifies CompiledGoFiles and Types, and has no effect on its own. + typecheckCgo + + // NeedModule adds Module. + NeedModule ) const ( @@ -182,6 +191,13 @@ type driver func(cfg *Config, patterns ...string) (*driverResponse, error) // driverResponse contains the results for a driver query. type driverResponse struct { + // NotHandled is returned if the request can't be handled by the current + // driver. If an external driver returns a response with NotHandled, the + // rest of the driverResponse is ignored, and go/packages will fallback + // to the next driver. If go/packages is extended in the future to support + // lists of multiple drivers, go/packages will fall back to the next driver. + NotHandled bool + // Sizes, if not nil, is the types.Sizes to use when type checking. Sizes *types.StdSizes @@ -223,14 +239,22 @@ func Load(cfg *Config, patterns ...string) ([]*Package, error) { return l.refine(response.Roots, response.Packages...) } -// defaultDriver is a driver that looks for an external driver binary, and if -// it does not find it falls back to the built in go list driver. +// defaultDriver is a driver that implements go/packages' fallback behavior. +// It will try to request to an external driver, if one exists. If there's +// no external driver, or the driver returns a response with NotHandled set, +// defaultDriver will fall back to the go list driver. func defaultDriver(cfg *Config, patterns ...string) (*driverResponse, error) { driver := findExternalDriver(cfg) if driver == nil { driver = goListDriver } - return driver(cfg, patterns...) + response, err := driver(cfg, patterns...) + if err != nil { + return response, err + } else if response.NotHandled { + return goListDriver(cfg, patterns...) + } + return response, nil } // A Package describes a loaded Go package. @@ -257,7 +281,7 @@ type Package struct { GoFiles []string // CompiledGoFiles lists the absolute file paths of the package's source - // files that were presented to the compiler. + // files that are suitable for type checking. // This may differ from GoFiles if files are processed before compilation. CompiledGoFiles []string @@ -305,22 +329,39 @@ type Package struct { forTest string // module is the module information for the package if it exists. - module *packagesinternal.Module + Module *Module +} + +// Module provides module information for a package. +type Module struct { + Path string // module path + Version string // module version + Replace *Module // replaced by this module + Time *time.Time // time version was created + Main bool // is this the main module? + Indirect bool // is this module only an indirect dependency of main module? + Dir string // directory holding files for this module, if any + GoMod string // path to go.mod file used when loading this module, if any + GoVersion string // go version used in module + Error *ModuleError // error loading module +} + +// ModuleError holds errors loading a module. +type ModuleError struct { + Err string // the error itself } func init() { packagesinternal.GetForTest = func(p interface{}) string { return p.(*Package).forTest } - packagesinternal.GetModule = func(p interface{}) *packagesinternal.Module { - return p.(*Package).module - } packagesinternal.GetGoCmdRunner = func(config interface{}) *gocommand.Runner { return config.(*Config).gocmdRunner } packagesinternal.SetGoCmdRunner = func(config interface{}, runner *gocommand.Runner) { config.(*Config).gocmdRunner = runner } + packagesinternal.TypecheckCgo = int(typecheckCgo) } // An Error describes a problem with a package's metadata, syntax, or types. @@ -703,6 +744,9 @@ func (ld *loader) refine(roots []string, list ...*Package) ([]*Package, error) { if ld.requestedMode&NeedTypesSizes == 0 { ld.pkgs[i].TypesSizes = nil } + if ld.requestedMode&NeedModule == 0 { + ld.pkgs[i].Module = nil + } } return result, nil @@ -878,6 +922,15 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { Error: appendError, Sizes: ld.sizes, } + if (ld.Mode & typecheckCgo) != 0 { + if !typesinternal.SetUsesCgo(tc) { + appendError(Error{ + Msg: "typecheckCgo requires Go 1.15+", + Kind: ListError, + }) + return + } + } types.NewChecker(tc, ld.Fset, lpkg.Types, lpkg.TypesInfo).Files(lpkg.Syntax) lpkg.importErrors = nil // no longer needed diff --git a/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go b/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go index 882e3b3d8a9..cffd7acbee7 100644 --- a/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go +++ b/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go @@ -226,7 +226,8 @@ func For(obj types.Object) (Path, error) { // the best paths because non-types may // refer to types, but not the reverse. empty := make([]byte, 0, 48) // initial space - for _, name := range scope.Names() { + names := scope.Names() + for _, name := range names { o := scope.Lookup(name) tname, ok := o.(*types.TypeName) if !ok { @@ -253,7 +254,7 @@ func For(obj types.Object) (Path, error) { // Then inspect everything else: // non-types, and declared methods of defined types. - for _, name := range scope.Names() { + for _, name := range names { o := scope.Lookup(name) path := append(empty, name...) if _, ok := o.(*types.TypeName); !ok { diff --git a/vendor/golang.org/x/tools/imports/forward.go b/vendor/golang.org/x/tools/imports/forward.go index dbe5b49a9f3..a4e40adba0d 100644 --- a/vendor/golang.org/x/tools/imports/forward.go +++ b/vendor/golang.org/x/tools/imports/forward.go @@ -3,10 +3,10 @@ package imports // import "golang.org/x/tools/imports" import ( - "go/build" + "io/ioutil" "log" - "os" + "golang.org/x/tools/internal/gocommand" intimp "golang.org/x/tools/internal/imports" ) @@ -31,31 +31,34 @@ var Debug = false var LocalPrefix string // Process formats and adjusts imports for the provided file. -// If opt is nil the defaults are used. +// If opt is nil the defaults are used, and if src is nil the source +// is read from the filesystem. // // Note that filename's directory influences which imports can be chosen, // so it is important that filename be accurate. // To process data ``as if'' it were in filename, pass the data as a non-nil src. func Process(filename string, src []byte, opt *Options) ([]byte, error) { + var err error + if src == nil { + src, err = ioutil.ReadFile(filename) + if err != nil { + return nil, err + } + } if opt == nil { opt = &Options{Comments: true, TabIndent: true, TabWidth: 8} } intopt := &intimp.Options{ Env: &intimp.ProcessEnv{ - GOPATH: build.Default.GOPATH, - GOROOT: build.Default.GOROOT, - GOFLAGS: os.Getenv("GOFLAGS"), - GO111MODULE: os.Getenv("GO111MODULE"), - GOPROXY: os.Getenv("GOPROXY"), - GOSUMDB: os.Getenv("GOSUMDB"), - LocalPrefix: LocalPrefix, + GocmdRunner: &gocommand.Runner{}, }, - AllErrors: opt.AllErrors, - Comments: opt.Comments, - FormatOnly: opt.FormatOnly, - Fragment: opt.Fragment, - TabIndent: opt.TabIndent, - TabWidth: opt.TabWidth, + LocalPrefix: LocalPrefix, + AllErrors: opt.AllErrors, + Comments: opt.Comments, + FormatOnly: opt.FormatOnly, + Fragment: opt.Fragment, + TabIndent: opt.TabIndent, + TabWidth: opt.TabWidth, } if Debug { intopt.Env.Logf = log.Printf diff --git a/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go b/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go index 26586810c7f..311fbfd883d 100644 --- a/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go +++ b/vendor/golang.org/x/tools/internal/analysisinternal/analysis.go @@ -48,7 +48,7 @@ func ZeroValue(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.T case *types.Chan, *types.Interface, *types.Map, *types.Pointer, *types.Signature, *types.Slice: return ast.NewIdent("nil") case *types.Struct: - texpr := typeExpr(fset, f, pkg, typ) // typ because we want the name here. + texpr := TypeExpr(fset, f, pkg, typ) // typ because we want the name here. if texpr == nil { return nil } @@ -56,7 +56,7 @@ func ZeroValue(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.T Type: texpr, } case *types.Array: - texpr := typeExpr(fset, f, pkg, u.Elem()) + texpr := TypeExpr(fset, f, pkg, u.Elem()) if texpr == nil { return nil } @@ -70,7 +70,7 @@ func ZeroValue(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.T return nil } -func typeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Type) ast.Expr { +func TypeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Type) ast.Expr { switch t := typ.(type) { case *types.Basic: switch t.Kind() { @@ -80,6 +80,9 @@ func typeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Ty return ast.NewIdent(t.Name()) } case *types.Named: + if t.Obj().Pkg() == nil { + return nil + } if t.Obj().Pkg() == pkg { return ast.NewIdent(t.Obj().Name()) } @@ -101,6 +104,11 @@ func typeExpr(fset *token.FileSet, f *ast.File, pkg *types.Package, typ types.Ty X: ast.NewIdent(pkgName), Sel: ast.NewIdent(t.Obj().Name()), } + case *types.Pointer: + return &ast.UnaryExpr{ + Op: token.MUL, + X: TypeExpr(fset, f, pkg, t.Elem()), + } default: return nil // TODO: anonymous structs, but who does that } @@ -116,3 +124,77 @@ const ( NoResultValues TypeErrorPass = "noresultvalues" UndeclaredName TypeErrorPass = "undeclaredname" ) + +// StmtToInsertVarBefore returns the ast.Stmt before which we can safely insert a new variable. +// Some examples: +// +// Basic Example: +// z := 1 +// y := z + x +// If x is undeclared, then this function would return `y := z + x`, so that we +// can insert `x := ` on the line before `y := z + x`. +// +// If stmt example: +// if z == 1 { +// } else if z == y {} +// If y is undeclared, then this function would return `if z == 1 {`, because we cannot +// insert a statement between an if and an else if statement. As a result, we need to find +// the top of the if chain to insert `y := ` before. +func StmtToInsertVarBefore(path []ast.Node) ast.Stmt { + enclosingIndex := -1 + for i, p := range path { + if _, ok := p.(ast.Stmt); ok { + enclosingIndex = i + break + } + } + if enclosingIndex == -1 { + return nil + } + enclosingStmt := path[enclosingIndex] + switch enclosingStmt.(type) { + case *ast.IfStmt: + // The enclosingStmt is inside of the if declaration, + // We need to check if we are in an else-if stmt and + // get the base if statement. + return baseIfStmt(path, enclosingIndex) + case *ast.CaseClause: + // Get the enclosing switch stmt if the enclosingStmt is + // inside of the case statement. + for i := enclosingIndex + 1; i < len(path); i++ { + if node, ok := path[i].(*ast.SwitchStmt); ok { + return node + } else if node, ok := path[i].(*ast.TypeSwitchStmt); ok { + return node + } + } + } + if len(path) <= enclosingIndex+1 { + return enclosingStmt.(ast.Stmt) + } + // Check if the enclosing statement is inside another node. + switch expr := path[enclosingIndex+1].(type) { + case *ast.IfStmt: + // Get the base if statement. + return baseIfStmt(path, enclosingIndex+1) + case *ast.ForStmt: + if expr.Init == enclosingStmt || expr.Post == enclosingStmt { + return expr + } + } + return enclosingStmt.(ast.Stmt) +} + +// baseIfStmt walks up the if/else-if chain until we get to +// the top of the current if chain. +func baseIfStmt(path []ast.Node, index int) ast.Stmt { + stmt := path[index] + for i := index + 1; i < len(path); i++ { + if node, ok := path[i].(*ast.IfStmt); ok && node.Else == stmt { + stmt = node + continue + } + break + } + return stmt.(ast.Stmt) +} diff --git a/vendor/golang.org/x/tools/internal/event/core/event.go b/vendor/golang.org/x/tools/internal/event/core/event.go new file mode 100644 index 00000000000..e37b4949150 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/core/event.go @@ -0,0 +1,85 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package core provides support for event based telemetry. +package core + +import ( + "fmt" + "time" + + "golang.org/x/tools/internal/event/label" +) + +// Event holds the information about an event of note that ocurred. +type Event struct { + at time.Time + + // As events are often on the stack, storing the first few labels directly + // in the event can avoid an allocation at all for the very common cases of + // simple events. + // The length needs to be large enough to cope with the majority of events + // but no so large as to cause undue stack pressure. + // A log message with two values will use 3 labels (one for each value and + // one for the message itself). + + static [3]label.Label // inline storage for the first few labels + dynamic []label.Label // dynamically sized storage for remaining labels +} + +// eventLabelMap implements label.Map for a the labels of an Event. +type eventLabelMap struct { + event Event +} + +func (ev Event) At() time.Time { return ev.at } + +func (ev Event) Format(f fmt.State, r rune) { + if !ev.at.IsZero() { + fmt.Fprint(f, ev.at.Format("2006/01/02 15:04:05 ")) + } + for index := 0; ev.Valid(index); index++ { + if l := ev.Label(index); l.Valid() { + fmt.Fprintf(f, "\n\t%v", l) + } + } +} + +func (ev Event) Valid(index int) bool { + return index >= 0 && index < len(ev.static)+len(ev.dynamic) +} + +func (ev Event) Label(index int) label.Label { + if index < len(ev.static) { + return ev.static[index] + } + return ev.dynamic[index-len(ev.static)] +} + +func (ev Event) Find(key label.Key) label.Label { + for _, l := range ev.static { + if l.Key() == key { + return l + } + } + for _, l := range ev.dynamic { + if l.Key() == key { + return l + } + } + return label.Label{} +} + +func MakeEvent(static [3]label.Label, labels []label.Label) Event { + return Event{ + static: static, + dynamic: labels, + } +} + +// CloneEvent event returns a copy of the event with the time adjusted to at. +func CloneEvent(ev Event, at time.Time) Event { + ev.at = at + return ev +} diff --git a/vendor/golang.org/x/tools/internal/telemetry/event/export.go b/vendor/golang.org/x/tools/internal/event/core/export.go similarity index 76% rename from vendor/golang.org/x/tools/internal/telemetry/event/export.go rename to vendor/golang.org/x/tools/internal/event/core/export.go index a2633b60230..05f3a9a5791 100644 --- a/vendor/golang.org/x/tools/internal/telemetry/event/export.go +++ b/vendor/golang.org/x/tools/internal/event/core/export.go @@ -2,18 +2,20 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package event +package core import ( "context" "sync/atomic" "time" "unsafe" + + "golang.org/x/tools/internal/event/label" ) // Exporter is a function that handles events. // It may return a modified context and event. -type Exporter func(context.Context, Event, TagMap) context.Context +type Exporter func(context.Context, Event, label.Map) context.Context var ( exporter unsafe.Pointer @@ -35,16 +37,16 @@ func SetExporter(e Exporter) { } // deliver is called to deliver an event to the supplied exporter. -// it will fill in the time and generate the basic tag source. +// it will fill in the time. func deliver(ctx context.Context, exporter Exporter, ev Event) context.Context { // add the current time to the event - ev.At = time.Now() + ev.at = time.Now() // hand the event off to the current exporter return exporter(ctx, ev, ev) } -// dispatch is called to deliver an event to the global exporter if set. -func dispatch(ctx context.Context, ev Event) context.Context { +// Export is called to deliver an event to the global exporter if set. +func Export(ctx context.Context, ev Event) context.Context { // get the global exporter and abort early if there is not one exporterPtr := (*Exporter)(atomic.LoadPointer(&exporter)) if exporterPtr == nil { @@ -53,11 +55,11 @@ func dispatch(ctx context.Context, ev Event) context.Context { return deliver(ctx, *exporterPtr, ev) } -// dispatchPair is called to deliver a start event to the supplied exporter. +// ExportPair is called to deliver a start event to the supplied exporter. // It also returns a function that will deliver the end event to the same // exporter. -// it will fill in the time and generate the basic tag source. -func dispatchPair(ctx context.Context, begin, end Event) (context.Context, func()) { +// It will fill in the time. +func ExportPair(ctx context.Context, begin, end Event) (context.Context, func()) { // get the global exporter and abort early if there is not one exporterPtr := (*Exporter)(atomic.LoadPointer(&exporter)) if exporterPtr == nil { diff --git a/vendor/golang.org/x/tools/internal/event/core/fast.go b/vendor/golang.org/x/tools/internal/event/core/fast.go new file mode 100644 index 00000000000..06c1d4615e6 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/core/fast.go @@ -0,0 +1,77 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package core + +import ( + "context" + + "golang.org/x/tools/internal/event/keys" + "golang.org/x/tools/internal/event/label" +) + +// Log1 takes a message and one label delivers a log event to the exporter. +// It is a customized version of Print that is faster and does no allocation. +func Log1(ctx context.Context, message string, t1 label.Label) { + Export(ctx, MakeEvent([3]label.Label{ + keys.Msg.Of(message), + t1, + }, nil)) +} + +// Log2 takes a message and two labels and delivers a log event to the exporter. +// It is a customized version of Print that is faster and does no allocation. +func Log2(ctx context.Context, message string, t1 label.Label, t2 label.Label) { + Export(ctx, MakeEvent([3]label.Label{ + keys.Msg.Of(message), + t1, + t2, + }, nil)) +} + +// Metric1 sends a label event to the exporter with the supplied labels. +func Metric1(ctx context.Context, t1 label.Label) context.Context { + return Export(ctx, MakeEvent([3]label.Label{ + keys.Metric.New(), + t1, + }, nil)) +} + +// Metric2 sends a label event to the exporter with the supplied labels. +func Metric2(ctx context.Context, t1, t2 label.Label) context.Context { + return Export(ctx, MakeEvent([3]label.Label{ + keys.Metric.New(), + t1, + t2, + }, nil)) +} + +// Start1 sends a span start event with the supplied label list to the exporter. +// It also returns a function that will end the span, which should normally be +// deferred. +func Start1(ctx context.Context, name string, t1 label.Label) (context.Context, func()) { + return ExportPair(ctx, + MakeEvent([3]label.Label{ + keys.Start.Of(name), + t1, + }, nil), + MakeEvent([3]label.Label{ + keys.End.New(), + }, nil)) +} + +// Start2 sends a span start event with the supplied label list to the exporter. +// It also returns a function that will end the span, which should normally be +// deferred. +func Start2(ctx context.Context, name string, t1, t2 label.Label) (context.Context, func()) { + return ExportPair(ctx, + MakeEvent([3]label.Label{ + keys.Start.Of(name), + t1, + t2, + }, nil), + MakeEvent([3]label.Label{ + keys.End.New(), + }, nil)) +} diff --git a/vendor/golang.org/x/tools/internal/event/doc.go b/vendor/golang.org/x/tools/internal/event/doc.go new file mode 100644 index 00000000000..5dc6e6babed --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/doc.go @@ -0,0 +1,7 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package event provides a set of packages that cover the main +// concepts of telemetry in an implementation agnostic way. +package event diff --git a/vendor/golang.org/x/tools/internal/event/event.go b/vendor/golang.org/x/tools/internal/event/event.go new file mode 100644 index 00000000000..4d55e577d1a --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/event.go @@ -0,0 +1,127 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package event + +import ( + "context" + + "golang.org/x/tools/internal/event/core" + "golang.org/x/tools/internal/event/keys" + "golang.org/x/tools/internal/event/label" +) + +// Exporter is a function that handles events. +// It may return a modified context and event. +type Exporter func(context.Context, core.Event, label.Map) context.Context + +// SetExporter sets the global exporter function that handles all events. +// The exporter is called synchronously from the event call site, so it should +// return quickly so as not to hold up user code. +func SetExporter(e Exporter) { + core.SetExporter(core.Exporter(e)) +} + +// Log takes a message and a label list and combines them into a single event +// before delivering them to the exporter. +func Log(ctx context.Context, message string, labels ...label.Label) { + core.Export(ctx, core.MakeEvent([3]label.Label{ + keys.Msg.Of(message), + }, labels)) +} + +// IsLog returns true if the event was built by the Log function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsLog(ev core.Event) bool { + return ev.Label(0).Key() == keys.Msg +} + +// Error takes a message and a label list and combines them into a single event +// before delivering them to the exporter. It captures the error in the +// delivered event. +func Error(ctx context.Context, message string, err error, labels ...label.Label) { + core.Export(ctx, core.MakeEvent([3]label.Label{ + keys.Msg.Of(message), + keys.Err.Of(err), + }, labels)) +} + +// IsError returns true if the event was built by the Error function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsError(ev core.Event) bool { + return ev.Label(0).Key() == keys.Msg && + ev.Label(1).Key() == keys.Err +} + +// Metric sends a label event to the exporter with the supplied labels. +func Metric(ctx context.Context, labels ...label.Label) { + core.Export(ctx, core.MakeEvent([3]label.Label{ + keys.Metric.New(), + }, labels)) +} + +// IsMetric returns true if the event was built by the Metric function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsMetric(ev core.Event) bool { + return ev.Label(0).Key() == keys.Metric +} + +// Label sends a label event to the exporter with the supplied labels. +func Label(ctx context.Context, labels ...label.Label) context.Context { + return core.Export(ctx, core.MakeEvent([3]label.Label{ + keys.Label.New(), + }, labels)) +} + +// IsLabel returns true if the event was built by the Label function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsLabel(ev core.Event) bool { + return ev.Label(0).Key() == keys.Label +} + +// Start sends a span start event with the supplied label list to the exporter. +// It also returns a function that will end the span, which should normally be +// deferred. +func Start(ctx context.Context, name string, labels ...label.Label) (context.Context, func()) { + return core.ExportPair(ctx, + core.MakeEvent([3]label.Label{ + keys.Start.Of(name), + }, labels), + core.MakeEvent([3]label.Label{ + keys.End.New(), + }, nil)) +} + +// IsStart returns true if the event was built by the Start function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsStart(ev core.Event) bool { + return ev.Label(0).Key() == keys.Start +} + +// IsEnd returns true if the event was built by the End function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsEnd(ev core.Event) bool { + return ev.Label(0).Key() == keys.End +} + +// Detach returns a context without an associated span. +// This allows the creation of spans that are not children of the current span. +func Detach(ctx context.Context) context.Context { + return core.Export(ctx, core.MakeEvent([3]label.Label{ + keys.Detach.New(), + }, nil)) +} + +// IsDetach returns true if the event was built by the Detach function. +// It is intended to be used in exporters to identify the semantics of the +// event when deciding what to do with it. +func IsDetach(ev core.Event) bool { + return ev.Label(0).Key() == keys.Detach +} diff --git a/vendor/golang.org/x/tools/internal/event/keys/keys.go b/vendor/golang.org/x/tools/internal/event/keys/keys.go new file mode 100644 index 00000000000..a02206e3015 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/keys/keys.go @@ -0,0 +1,564 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package keys + +import ( + "fmt" + "io" + "math" + "strconv" + + "golang.org/x/tools/internal/event/label" +) + +// Value represents a key for untyped values. +type Value struct { + name string + description string +} + +// New creates a new Key for untyped values. +func New(name, description string) *Value { + return &Value{name: name, description: description} +} + +func (k *Value) Name() string { return k.name } +func (k *Value) Description() string { return k.description } + +func (k *Value) Format(w io.Writer, buf []byte, l label.Label) { + fmt.Fprint(w, k.From(l)) +} + +// Get can be used to get a label for the key from a label.Map. +func (k *Value) Get(lm label.Map) interface{} { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return nil +} + +// From can be used to get a value from a Label. +func (k *Value) From(t label.Label) interface{} { return t.UnpackValue() } + +// Of creates a new Label with this key and the supplied value. +func (k *Value) Of(value interface{}) label.Label { return label.OfValue(k, value) } + +// Tag represents a key for tagging labels that have no value. +// These are used when the existence of the label is the entire information it +// carries, such as marking events to be of a specific kind, or from a specific +// package. +type Tag struct { + name string + description string +} + +// NewTag creates a new Key for tagging labels. +func NewTag(name, description string) *Tag { + return &Tag{name: name, description: description} +} + +func (k *Tag) Name() string { return k.name } +func (k *Tag) Description() string { return k.description } + +func (k *Tag) Format(w io.Writer, buf []byte, l label.Label) {} + +// New creates a new Label with this key. +func (k *Tag) New() label.Label { return label.OfValue(k, nil) } + +// Int represents a key +type Int struct { + name string + description string +} + +// NewInt creates a new Key for int values. +func NewInt(name, description string) *Int { + return &Int{name: name, description: description} +} + +func (k *Int) Name() string { return k.name } +func (k *Int) Description() string { return k.description } + +func (k *Int) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendInt(buf, int64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Int) Of(v int) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Int) Get(lm label.Map) int { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Int) From(t label.Label) int { return int(t.Unpack64()) } + +// Int8 represents a key +type Int8 struct { + name string + description string +} + +// NewInt8 creates a new Key for int8 values. +func NewInt8(name, description string) *Int8 { + return &Int8{name: name, description: description} +} + +func (k *Int8) Name() string { return k.name } +func (k *Int8) Description() string { return k.description } + +func (k *Int8) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendInt(buf, int64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Int8) Of(v int8) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Int8) Get(lm label.Map) int8 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Int8) From(t label.Label) int8 { return int8(t.Unpack64()) } + +// Int16 represents a key +type Int16 struct { + name string + description string +} + +// NewInt16 creates a new Key for int16 values. +func NewInt16(name, description string) *Int16 { + return &Int16{name: name, description: description} +} + +func (k *Int16) Name() string { return k.name } +func (k *Int16) Description() string { return k.description } + +func (k *Int16) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendInt(buf, int64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Int16) Of(v int16) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Int16) Get(lm label.Map) int16 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Int16) From(t label.Label) int16 { return int16(t.Unpack64()) } + +// Int32 represents a key +type Int32 struct { + name string + description string +} + +// NewInt32 creates a new Key for int32 values. +func NewInt32(name, description string) *Int32 { + return &Int32{name: name, description: description} +} + +func (k *Int32) Name() string { return k.name } +func (k *Int32) Description() string { return k.description } + +func (k *Int32) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendInt(buf, int64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Int32) Of(v int32) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Int32) Get(lm label.Map) int32 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Int32) From(t label.Label) int32 { return int32(t.Unpack64()) } + +// Int64 represents a key +type Int64 struct { + name string + description string +} + +// NewInt64 creates a new Key for int64 values. +func NewInt64(name, description string) *Int64 { + return &Int64{name: name, description: description} +} + +func (k *Int64) Name() string { return k.name } +func (k *Int64) Description() string { return k.description } + +func (k *Int64) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendInt(buf, k.From(l), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Int64) Of(v int64) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Int64) Get(lm label.Map) int64 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Int64) From(t label.Label) int64 { return int64(t.Unpack64()) } + +// UInt represents a key +type UInt struct { + name string + description string +} + +// NewUInt creates a new Key for uint values. +func NewUInt(name, description string) *UInt { + return &UInt{name: name, description: description} +} + +func (k *UInt) Name() string { return k.name } +func (k *UInt) Description() string { return k.description } + +func (k *UInt) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendUint(buf, uint64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *UInt) Of(v uint) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *UInt) Get(lm label.Map) uint { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *UInt) From(t label.Label) uint { return uint(t.Unpack64()) } + +// UInt8 represents a key +type UInt8 struct { + name string + description string +} + +// NewUInt8 creates a new Key for uint8 values. +func NewUInt8(name, description string) *UInt8 { + return &UInt8{name: name, description: description} +} + +func (k *UInt8) Name() string { return k.name } +func (k *UInt8) Description() string { return k.description } + +func (k *UInt8) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendUint(buf, uint64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *UInt8) Of(v uint8) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *UInt8) Get(lm label.Map) uint8 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *UInt8) From(t label.Label) uint8 { return uint8(t.Unpack64()) } + +// UInt16 represents a key +type UInt16 struct { + name string + description string +} + +// NewUInt16 creates a new Key for uint16 values. +func NewUInt16(name, description string) *UInt16 { + return &UInt16{name: name, description: description} +} + +func (k *UInt16) Name() string { return k.name } +func (k *UInt16) Description() string { return k.description } + +func (k *UInt16) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendUint(buf, uint64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *UInt16) Of(v uint16) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *UInt16) Get(lm label.Map) uint16 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *UInt16) From(t label.Label) uint16 { return uint16(t.Unpack64()) } + +// UInt32 represents a key +type UInt32 struct { + name string + description string +} + +// NewUInt32 creates a new Key for uint32 values. +func NewUInt32(name, description string) *UInt32 { + return &UInt32{name: name, description: description} +} + +func (k *UInt32) Name() string { return k.name } +func (k *UInt32) Description() string { return k.description } + +func (k *UInt32) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendUint(buf, uint64(k.From(l)), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *UInt32) Of(v uint32) label.Label { return label.Of64(k, uint64(v)) } + +// Get can be used to get a label for the key from a label.Map. +func (k *UInt32) Get(lm label.Map) uint32 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *UInt32) From(t label.Label) uint32 { return uint32(t.Unpack64()) } + +// UInt64 represents a key +type UInt64 struct { + name string + description string +} + +// NewUInt64 creates a new Key for uint64 values. +func NewUInt64(name, description string) *UInt64 { + return &UInt64{name: name, description: description} +} + +func (k *UInt64) Name() string { return k.name } +func (k *UInt64) Description() string { return k.description } + +func (k *UInt64) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendUint(buf, k.From(l), 10)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *UInt64) Of(v uint64) label.Label { return label.Of64(k, v) } + +// Get can be used to get a label for the key from a label.Map. +func (k *UInt64) Get(lm label.Map) uint64 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *UInt64) From(t label.Label) uint64 { return t.Unpack64() } + +// Float32 represents a key +type Float32 struct { + name string + description string +} + +// NewFloat32 creates a new Key for float32 values. +func NewFloat32(name, description string) *Float32 { + return &Float32{name: name, description: description} +} + +func (k *Float32) Name() string { return k.name } +func (k *Float32) Description() string { return k.description } + +func (k *Float32) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendFloat(buf, float64(k.From(l)), 'E', -1, 32)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Float32) Of(v float32) label.Label { + return label.Of64(k, uint64(math.Float32bits(v))) +} + +// Get can be used to get a label for the key from a label.Map. +func (k *Float32) Get(lm label.Map) float32 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Float32) From(t label.Label) float32 { + return math.Float32frombits(uint32(t.Unpack64())) +} + +// Float64 represents a key +type Float64 struct { + name string + description string +} + +// NewFloat64 creates a new Key for int64 values. +func NewFloat64(name, description string) *Float64 { + return &Float64{name: name, description: description} +} + +func (k *Float64) Name() string { return k.name } +func (k *Float64) Description() string { return k.description } + +func (k *Float64) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendFloat(buf, k.From(l), 'E', -1, 64)) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Float64) Of(v float64) label.Label { + return label.Of64(k, math.Float64bits(v)) +} + +// Get can be used to get a label for the key from a label.Map. +func (k *Float64) Get(lm label.Map) float64 { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return 0 +} + +// From can be used to get a value from a Label. +func (k *Float64) From(t label.Label) float64 { + return math.Float64frombits(t.Unpack64()) +} + +// String represents a key +type String struct { + name string + description string +} + +// NewString creates a new Key for int64 values. +func NewString(name, description string) *String { + return &String{name: name, description: description} +} + +func (k *String) Name() string { return k.name } +func (k *String) Description() string { return k.description } + +func (k *String) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendQuote(buf, k.From(l))) +} + +// Of creates a new Label with this key and the supplied value. +func (k *String) Of(v string) label.Label { return label.OfString(k, v) } + +// Get can be used to get a label for the key from a label.Map. +func (k *String) Get(lm label.Map) string { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return "" +} + +// From can be used to get a value from a Label. +func (k *String) From(t label.Label) string { return t.UnpackString() } + +// Boolean represents a key +type Boolean struct { + name string + description string +} + +// NewBoolean creates a new Key for bool values. +func NewBoolean(name, description string) *Boolean { + return &Boolean{name: name, description: description} +} + +func (k *Boolean) Name() string { return k.name } +func (k *Boolean) Description() string { return k.description } + +func (k *Boolean) Format(w io.Writer, buf []byte, l label.Label) { + w.Write(strconv.AppendBool(buf, k.From(l))) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Boolean) Of(v bool) label.Label { + if v { + return label.Of64(k, 1) + } + return label.Of64(k, 0) +} + +// Get can be used to get a label for the key from a label.Map. +func (k *Boolean) Get(lm label.Map) bool { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return false +} + +// From can be used to get a value from a Label. +func (k *Boolean) From(t label.Label) bool { return t.Unpack64() > 0 } + +// Error represents a key +type Error struct { + name string + description string +} + +// NewError creates a new Key for int64 values. +func NewError(name, description string) *Error { + return &Error{name: name, description: description} +} + +func (k *Error) Name() string { return k.name } +func (k *Error) Description() string { return k.description } + +func (k *Error) Format(w io.Writer, buf []byte, l label.Label) { + io.WriteString(w, k.From(l).Error()) +} + +// Of creates a new Label with this key and the supplied value. +func (k *Error) Of(v error) label.Label { return label.OfValue(k, v) } + +// Get can be used to get a label for the key from a label.Map. +func (k *Error) Get(lm label.Map) error { + if t := lm.Find(k); t.Valid() { + return k.From(t) + } + return nil +} + +// From can be used to get a value from a Label. +func (k *Error) From(t label.Label) error { + err, _ := t.UnpackValue().(error) + return err +} diff --git a/vendor/golang.org/x/tools/internal/event/keys/standard.go b/vendor/golang.org/x/tools/internal/event/keys/standard.go new file mode 100644 index 00000000000..7e958665921 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/keys/standard.go @@ -0,0 +1,22 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package keys + +var ( + // Msg is a key used to add message strings to label lists. + Msg = NewString("message", "a readable message") + // Label is a key used to indicate an event adds labels to the context. + Label = NewTag("label", "a label context marker") + // Start is used for things like traces that have a name. + Start = NewString("start", "span start") + // Metric is a key used to indicate an event records metrics. + End = NewTag("end", "a span end marker") + // Metric is a key used to indicate an event records metrics. + Detach = NewTag("detach", "a span detach marker") + // Err is a key used to add error values to label lists. + Err = NewError("error", "an error that occurred") + // Metric is a key used to indicate an event records metrics. + Metric = NewTag("metric", "a metric event marker") +) diff --git a/vendor/golang.org/x/tools/internal/event/label/label.go b/vendor/golang.org/x/tools/internal/event/label/label.go new file mode 100644 index 00000000000..b55c12eb250 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/label/label.go @@ -0,0 +1,213 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package label + +import ( + "fmt" + "io" + "reflect" + "unsafe" +) + +// Key is used as the identity of a Label. +// Keys are intended to be compared by pointer only, the name should be unique +// for communicating with external systems, but it is not required or enforced. +type Key interface { + // Name returns the key name. + Name() string + // Description returns a string that can be used to describe the value. + Description() string + + // Format is used in formatting to append the value of the label to the + // supplied buffer. + // The formatter may use the supplied buf as a scratch area to avoid + // allocations. + Format(w io.Writer, buf []byte, l Label) +} + +// Label holds a key and value pair. +// It is normally used when passing around lists of labels. +type Label struct { + key Key + packed uint64 + untyped interface{} +} + +// Map is the interface to a collection of Labels indexed by key. +type Map interface { + // Find returns the label that matches the supplied key. + Find(key Key) Label +} + +// List is the interface to something that provides an iterable +// list of labels. +// Iteration should start from 0 and continue until Valid returns false. +type List interface { + // Valid returns true if the index is within range for the list. + // It does not imply the label at that index will itself be valid. + Valid(index int) bool + // Label returns the label at the given index. + Label(index int) Label +} + +// list implements LabelList for a list of Labels. +type list struct { + labels []Label +} + +// filter wraps a LabelList filtering out specific labels. +type filter struct { + keys []Key + underlying List +} + +// listMap implements LabelMap for a simple list of labels. +type listMap struct { + labels []Label +} + +// mapChain implements LabelMap for a list of underlying LabelMap. +type mapChain struct { + maps []Map +} + +// OfValue creates a new label from the key and value. +// This method is for implementing new key types, label creation should +// normally be done with the Of method of the key. +func OfValue(k Key, value interface{}) Label { return Label{key: k, untyped: value} } + +// UnpackValue assumes the label was built using LabelOfValue and returns the value +// that was passed to that constructor. +// This method is for implementing new key types, for type safety normal +// access should be done with the From method of the key. +func (t Label) UnpackValue() interface{} { return t.untyped } + +// Of64 creates a new label from a key and a uint64. This is often +// used for non uint64 values that can be packed into a uint64. +// This method is for implementing new key types, label creation should +// normally be done with the Of method of the key. +func Of64(k Key, v uint64) Label { return Label{key: k, packed: v} } + +// Unpack64 assumes the label was built using LabelOf64 and returns the value that +// was passed to that constructor. +// This method is for implementing new key types, for type safety normal +// access should be done with the From method of the key. +func (t Label) Unpack64() uint64 { return t.packed } + +// OfString creates a new label from a key and a string. +// This method is for implementing new key types, label creation should +// normally be done with the Of method of the key. +func OfString(k Key, v string) Label { + hdr := (*reflect.StringHeader)(unsafe.Pointer(&v)) + return Label{ + key: k, + packed: uint64(hdr.Len), + untyped: unsafe.Pointer(hdr.Data), + } +} + +// UnpackString assumes the label was built using LabelOfString and returns the +// value that was passed to that constructor. +// This method is for implementing new key types, for type safety normal +// access should be done with the From method of the key. +func (t Label) UnpackString() string { + var v string + hdr := (*reflect.StringHeader)(unsafe.Pointer(&v)) + hdr.Data = uintptr(t.untyped.(unsafe.Pointer)) + hdr.Len = int(t.packed) + return *(*string)(unsafe.Pointer(hdr)) +} + +// Valid returns true if the Label is a valid one (it has a key). +func (t Label) Valid() bool { return t.key != nil } + +// Key returns the key of this Label. +func (t Label) Key() Key { return t.key } + +// Format is used for debug printing of labels. +func (t Label) Format(f fmt.State, r rune) { + if !t.Valid() { + io.WriteString(f, `nil`) + return + } + io.WriteString(f, t.Key().Name()) + io.WriteString(f, "=") + var buf [128]byte + t.Key().Format(f, buf[:0], t) +} + +func (l *list) Valid(index int) bool { + return index >= 0 && index < len(l.labels) +} + +func (l *list) Label(index int) Label { + return l.labels[index] +} + +func (f *filter) Valid(index int) bool { + return f.underlying.Valid(index) +} + +func (f *filter) Label(index int) Label { + l := f.underlying.Label(index) + for _, f := range f.keys { + if l.Key() == f { + return Label{} + } + } + return l +} + +func (lm listMap) Find(key Key) Label { + for _, l := range lm.labels { + if l.Key() == key { + return l + } + } + return Label{} +} + +func (c mapChain) Find(key Key) Label { + for _, src := range c.maps { + l := src.Find(key) + if l.Valid() { + return l + } + } + return Label{} +} + +var emptyList = &list{} + +func NewList(labels ...Label) List { + if len(labels) == 0 { + return emptyList + } + return &list{labels: labels} +} + +func Filter(l List, keys ...Key) List { + if len(keys) == 0 { + return l + } + return &filter{keys: keys, underlying: l} +} + +func NewMap(labels ...Label) Map { + return listMap{labels: labels} +} + +func MergeMaps(srcs ...Map) Map { + var nonNil []Map + for _, src := range srcs { + if src != nil { + nonNil = append(nonNil, src) + } + } + if len(nonNil) == 1 { + return nonNil[0] + } + return mapChain{maps: nonNil} +} diff --git a/vendor/golang.org/x/tools/internal/gocommand/invoke.go b/vendor/golang.org/x/tools/internal/gocommand/invoke.go index 5b134127089..f516e17623d 100644 --- a/vendor/golang.org/x/tools/internal/gocommand/invoke.go +++ b/vendor/golang.org/x/tools/internal/gocommand/invoke.go @@ -17,63 +17,112 @@ import ( "sync" "time" - "golang.org/x/tools/internal/telemetry/event" + "golang.org/x/tools/internal/event" ) // An Runner will run go command invocations and serialize // them if it sees a concurrency error. type Runner struct { - // LoadMu guards packages.Load calls and associated state. - loadMu sync.Mutex - serializeLoads int + // once guards the runner initialization. + once sync.Once + + // inFlight tracks available workers. + inFlight chan struct{} + + // serialized guards the ability to run a go command serially, + // to avoid deadlocks when claiming workers. + serialized chan struct{} +} + +const maxInFlight = 10 + +func (runner *Runner) initialize() { + runner.once.Do(func() { + runner.inFlight = make(chan struct{}, maxInFlight) + runner.serialized = make(chan struct{}, 1) + }) } // 1.13: go: updates to go.mod needed, but contents have changed // 1.14: go: updating go.mod: existing contents have changed since last read var modConcurrencyError = regexp.MustCompile(`go:.*go.mod.*contents have changed`) -// Run calls Runner.RunRaw, serializing requests if they fight over -// go.mod changes. +// Run is a convenience wrapper around RunRaw. +// It returns only stdout and a "friendly" error. func (runner *Runner) Run(ctx context.Context, inv Invocation) (*bytes.Buffer, error) { stdout, _, friendly, _ := runner.RunRaw(ctx, inv) return stdout, friendly } -// Run calls Innvocation.RunRaw, serializing requests if they fight over +// RunPiped runs the invocation serially, always waiting for any concurrent +// invocations to complete first. +func (runner *Runner) RunPiped(ctx context.Context, inv Invocation, stdout, stderr io.Writer) error { + _, err := runner.runPiped(ctx, inv, stdout, stderr) + return err +} + +// RunRaw runs the invocation, serializing requests only if they fight over // go.mod changes. func (runner *Runner) RunRaw(ctx context.Context, inv Invocation) (*bytes.Buffer, *bytes.Buffer, error, error) { - // We want to run invocations concurrently as much as possible. However, - // if go.mod updates are needed, only one can make them and the others will - // fail. We need to retry in those cases, but we don't want to thrash so - // badly we never recover. To avoid that, once we've seen one concurrency - // error, start serializing everything until the backlog has cleared out. - runner.loadMu.Lock() - var locked bool // If true, we hold the mutex and have incremented. - if runner.serializeLoads == 0 { - runner.loadMu.Unlock() - } else { - locked = true - runner.serializeLoads++ + // Make sure the runner is always initialized. + runner.initialize() + + // First, try to run the go command concurrently. + stdout, stderr, friendlyErr, err := runner.runConcurrent(ctx, inv) + + // If we encounter a load concurrency error, we need to retry serially. + if friendlyErr == nil || !modConcurrencyError.MatchString(friendlyErr.Error()) { + return stdout, stderr, friendlyErr, err } - defer func() { - if locked { - runner.serializeLoads-- - runner.loadMu.Unlock() - } - }() + event.Error(ctx, "Load concurrency error, will retry serially", err) - for { - stdout, stderr, friendlyErr, err := inv.runRaw(ctx) - if friendlyErr == nil || !modConcurrencyError.MatchString(friendlyErr.Error()) { - return stdout, stderr, friendlyErr, err - } - event.Error(ctx, "Load concurrency error, will retry serially", err) - if !locked { - runner.loadMu.Lock() - runner.serializeLoads++ - locked = true + // Run serially by calling runPiped. + stdout.Reset() + stderr.Reset() + friendlyErr, err = runner.runPiped(ctx, inv, stdout, stderr) + return stdout, stderr, friendlyErr, err +} + +func (runner *Runner) runConcurrent(ctx context.Context, inv Invocation) (*bytes.Buffer, *bytes.Buffer, error, error) { + // Wait for 1 worker to become available. + select { + case <-ctx.Done(): + return nil, nil, nil, ctx.Err() + case runner.inFlight <- struct{}{}: + defer func() { <-runner.inFlight }() + } + + stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{} + friendlyErr, err := inv.runWithFriendlyError(ctx, stdout, stderr) + return stdout, stderr, friendlyErr, err +} + +func (runner *Runner) runPiped(ctx context.Context, inv Invocation, stdout, stderr io.Writer) (error, error) { + // Make sure the runner is always initialized. + runner.initialize() + + // Acquire the serialization lock. This avoids deadlocks between two + // runPiped commands. + select { + case <-ctx.Done(): + return nil, ctx.Err() + case runner.serialized <- struct{}{}: + defer func() { <-runner.serialized }() + } + + // Wait for all in-progress go commands to return before proceeding, + // to avoid load concurrency errors. + for i := 0; i < maxInFlight; i++ { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case runner.inFlight <- struct{}{}: + // Make sure we always "return" any workers we took. + defer func() { <-runner.inFlight }() } } + + return inv.runWithFriendlyError(ctx, stdout, stderr) } // An Invocation represents a call to the go command. @@ -86,13 +135,10 @@ type Invocation struct { Logf func(format string, args ...interface{}) } -// RunRaw is like RunPiped, but also returns the raw stderr and error for callers -// that want to do low-level error handling/recovery. -func (i *Invocation) runRaw(ctx context.Context) (stdout *bytes.Buffer, stderr *bytes.Buffer, friendlyError error, rawError error) { - stdout = &bytes.Buffer{} - stderr = &bytes.Buffer{} - rawError = i.RunPiped(ctx, stdout, stderr) +func (i *Invocation) runWithFriendlyError(ctx context.Context, stdout, stderr io.Writer) (friendlyError error, rawError error) { + rawError = i.run(ctx, stdout, stderr) if rawError != nil { + friendlyError = rawError // Check for 'go' executable not being found. if ee, ok := rawError.(*exec.Error); ok && ee.Err == exec.ErrNotFound { friendlyError = fmt.Errorf("go command required, not found: %v", ee) @@ -100,13 +146,12 @@ func (i *Invocation) runRaw(ctx context.Context) (stdout *bytes.Buffer, stderr * if ctx.Err() != nil { friendlyError = ctx.Err() } - friendlyError = fmt.Errorf("err: %v: stderr: %s", rawError, stderr) + friendlyError = fmt.Errorf("err: %v: stderr: %s", friendlyError, stderr) } return } -// RunPiped is like Run, but relies on the given stdout/stderr -func (i *Invocation) RunPiped(ctx context.Context, stdout, stderr io.Writer) error { +func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error { log := i.Logf if log == nil { log = func(string, ...interface{}) {} @@ -140,7 +185,6 @@ func (i *Invocation) RunPiped(ctx context.Context, stdout, stderr io.Writer) err cmd.Env = append(cmd.Env, "PWD="+i.WorkingDir) cmd.Dir = i.WorkingDir } - defer func(start time.Time) { log("%s for %v", time.Since(start), cmdDebugStr(cmd)) }(time.Now()) return runCmdContext(ctx, cmd) diff --git a/vendor/golang.org/x/tools/internal/gocommand/vendor.go b/vendor/golang.org/x/tools/internal/gocommand/vendor.go new file mode 100644 index 00000000000..1cd8d8473e9 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/gocommand/vendor.go @@ -0,0 +1,102 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gocommand + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + + "golang.org/x/mod/semver" +) + +// ModuleJSON holds information about a module. +type ModuleJSON struct { + Path string // module path + Replace *ModuleJSON // replaced by this module + Main bool // is this the main module? + Indirect bool // is this module only an indirect dependency of main module? + Dir string // directory holding files for this module, if any + GoMod string // path to go.mod file for this module, if any + GoVersion string // go version used in module +} + +var modFlagRegexp = regexp.MustCompile(`-mod[ =](\w+)`) + +// VendorEnabled reports whether vendoring is enabled. It takes a *Runner to execute Go commands +// with the supplied context.Context and Invocation. The Invocation can contain pre-defined fields, +// of which only Verb and Args are modified to run the appropriate Go command. +// Inspired by setDefaultBuildMod in modload/init.go +func VendorEnabled(ctx context.Context, inv Invocation, r *Runner) (*ModuleJSON, bool, error) { + mainMod, go114, err := getMainModuleAnd114(ctx, inv, r) + if err != nil { + return nil, false, err + } + + // We check the GOFLAGS to see if there is anything overridden or not. + inv.Verb = "env" + inv.Args = []string{"GOFLAGS"} + stdout, err := r.Run(ctx, inv) + if err != nil { + return nil, false, err + } + goflags := string(bytes.TrimSpace(stdout.Bytes())) + matches := modFlagRegexp.FindStringSubmatch(goflags) + var modFlag string + if len(matches) != 0 { + modFlag = matches[1] + } + if modFlag != "" { + // Don't override an explicit '-mod=' argument. + return mainMod, modFlag == "vendor", nil + } + if mainMod == nil || !go114 { + return mainMod, false, nil + } + // Check 1.14's automatic vendor mode. + if fi, err := os.Stat(filepath.Join(mainMod.Dir, "vendor")); err == nil && fi.IsDir() { + if mainMod.GoVersion != "" && semver.Compare("v"+mainMod.GoVersion, "v1.14") >= 0 { + // The Go version is at least 1.14, and a vendor directory exists. + // Set -mod=vendor by default. + return mainMod, true, nil + } + } + return mainMod, false, nil +} + +// getMainModuleAnd114 gets the main module's information and whether the +// go command in use is 1.14+. This is the information needed to figure out +// if vendoring should be enabled. +func getMainModuleAnd114(ctx context.Context, inv Invocation, r *Runner) (*ModuleJSON, bool, error) { + const format = `{{.Path}} +{{.Dir}} +{{.GoMod}} +{{.GoVersion}} +{{range context.ReleaseTags}}{{if eq . "go1.14"}}{{.}}{{end}}{{end}} +` + inv.Verb = "list" + inv.Args = []string{"-m", "-f", format} + stdout, err := r.Run(ctx, inv) + if err != nil { + return nil, false, err + } + + lines := strings.Split(stdout.String(), "\n") + if len(lines) < 5 { + return nil, false, fmt.Errorf("unexpected stdout: %q", stdout.String()) + } + mod := &ModuleJSON{ + Path: lines[0], + Dir: lines[1], + GoMod: lines[2], + GoVersion: lines[3], + Main: true, + } + return mod, lines[4] == "go1.14", nil +} diff --git a/vendor/golang.org/x/tools/internal/imports/fix.go b/vendor/golang.org/x/tools/internal/imports/fix.go index 264d001edcf..ecd13e87ad5 100644 --- a/vendor/golang.org/x/tools/internal/imports/fix.go +++ b/vendor/golang.org/x/tools/internal/imports/fix.go @@ -7,6 +7,7 @@ package imports import ( "bytes" "context" + "encoding/json" "fmt" "go/ast" "go/build" @@ -31,35 +32,36 @@ import ( // importToGroup is a list of functions which map from an import path to // a group number. -var importToGroup = []func(env *ProcessEnv, importPath string) (num int, ok bool){ - func(env *ProcessEnv, importPath string) (num int, ok bool) { - if env.LocalPrefix == "" { +var importToGroup = []func(localPrefix, importPath string) (num int, ok bool){ + func(localPrefix, importPath string) (num int, ok bool) { + if localPrefix == "" { return } - for _, p := range strings.Split(env.LocalPrefix, ",") { + for _, p := range strings.Split(localPrefix, ",") { if strings.HasPrefix(importPath, p) || strings.TrimSuffix(p, "/") == importPath { return 3, true } } return }, - func(_ *ProcessEnv, importPath string) (num int, ok bool) { + func(_, importPath string) (num int, ok bool) { if strings.HasPrefix(importPath, "appengine") { return 2, true } return }, - func(_ *ProcessEnv, importPath string) (num int, ok bool) { - if strings.Contains(importPath, ".") { + func(_, importPath string) (num int, ok bool) { + firstComponent := strings.Split(importPath, "/")[0] + if strings.Contains(firstComponent, ".") { return 1, true } return }, } -func importGroup(env *ProcessEnv, importPath string) int { +func importGroup(localPrefix, importPath string) int { for _, fn := range importToGroup { - if n, ok := fn(env, importPath); ok { + if n, ok := fn(localPrefix, importPath); ok { return n } } @@ -276,7 +278,12 @@ func (p *pass) loadPackageNames(imports []*ImportInfo) error { unknown = append(unknown, imp.ImportPath) } - names, err := p.env.GetResolver().loadPackageNames(unknown, p.srcDir) + resolver, err := p.env.GetResolver() + if err != nil { + return err + } + + names, err := resolver.loadPackageNames(unknown, p.srcDir) if err != nil { return err } @@ -597,7 +604,7 @@ func getCandidatePkgs(ctx context.Context, wrappedCallback *scanCallback, filena // Start off with the standard library. for importPath, exports := range stdlib { p := &pkg{ - dir: filepath.Join(env.GOROOT, "src", importPath), + dir: filepath.Join(env.goroot(), "src", importPath), importPathShort: importPath, packageName: path.Base(importPath), relevance: MaxRelevance, @@ -638,15 +645,23 @@ func getCandidatePkgs(ctx context.Context, wrappedCallback *scanCallback, filena wrappedCallback.exportsLoaded(pkg, exports) }, } - return env.GetResolver().scan(ctx, scanFilter) + resolver, err := env.GetResolver() + if err != nil { + return err + } + return resolver.scan(ctx, scanFilter) } -func ScoreImportPaths(ctx context.Context, env *ProcessEnv, paths []string) map[string]int { +func ScoreImportPaths(ctx context.Context, env *ProcessEnv, paths []string) (map[string]int, error) { result := make(map[string]int) + resolver, err := env.GetResolver() + if err != nil { + return nil, err + } for _, path := range paths { - result[path] = env.GetResolver().scoreImportPath(ctx, path) + result[path] = resolver.scoreImportPath(ctx, path) } - return result + return result, nil } func PrimeCache(ctx context.Context, env *ProcessEnv) error { @@ -672,8 +687,9 @@ func candidateImportName(pkg *pkg) string { return "" } -// getAllCandidates gets all of the candidates to be imported, regardless of if they are needed. -func getAllCandidates(ctx context.Context, wrapped func(ImportFix), searchPrefix, filename, filePkg string, env *ProcessEnv) error { +// GetAllCandidates gets all of the packages starting with prefix that can be +// imported by filename, sorted by import path. +func GetAllCandidates(ctx context.Context, wrapped func(ImportFix), searchPrefix, filename, filePkg string, env *ProcessEnv) error { callback := &scanCallback{ rootFound: func(gopathwalk.Root) bool { return true @@ -712,7 +728,8 @@ type PackageExport struct { Exports []string } -func getPackageExports(ctx context.Context, wrapped func(PackageExport), searchPkg, filename, filePkg string, env *ProcessEnv) error { +// GetPackageExports returns all known packages with name pkg and their exports. +func GetPackageExports(ctx context.Context, wrapped func(PackageExport), searchPkg, filename, filePkg string, env *ProcessEnv) error { callback := &scanCallback{ rootFound: func(gopathwalk.Root) bool { return true @@ -742,19 +759,22 @@ func getPackageExports(ctx context.Context, wrapped func(PackageExport), searchP return getCandidatePkgs(ctx, callback, filename, filePkg, env) } +var RequiredGoEnvVars = []string{"GO111MODULE", "GOFLAGS", "GOINSECURE", "GOMOD", "GOMODCACHE", "GONOPROXY", "GONOSUMDB", "GOPATH", "GOPROXY", "GOROOT", "GOSUMDB"} + // ProcessEnv contains environment variables and settings that affect the use of // the go command, the go/build package, etc. type ProcessEnv struct { - LocalPrefix string - GocmdRunner *gocommand.Runner BuildFlags []string - // If non-empty, these will be used instead of the - // process-wide values. - GOPATH, GOROOT, GO111MODULE, GOPROXY, GOFLAGS, GOSUMDB string - WorkingDir string + // Env overrides the OS environment, and can be used to specify + // GOPROXY, GO111MODULE, etc. PATH cannot be set here, because + // exec.Command will not honor it. + // Specifying all of RequiredGoEnvVars avoids a call to `go env`. + Env map[string]string + + WorkingDir string // If Logf is non-nil, debug logging is enabled through this function. Logf func(format string, args ...interface{}) @@ -762,6 +782,22 @@ type ProcessEnv struct { resolver Resolver } +func (e *ProcessEnv) goroot() string { + return e.mustGetEnv("GOROOT") +} + +func (e *ProcessEnv) gopath() string { + return e.mustGetEnv("GOPATH") +} + +func (e *ProcessEnv) mustGetEnv(k string) string { + v, ok := e.Env[k] + if !ok { + panic(fmt.Sprintf("%v not set in evaluated environment", k)) + } + return v +} + // CopyConfig copies the env's configuration into a new env. func (e *ProcessEnv) CopyConfig() *ProcessEnv { copy := *e @@ -769,42 +805,63 @@ func (e *ProcessEnv) CopyConfig() *ProcessEnv { return © } -func (e *ProcessEnv) env() []string { - env := os.Environ() - add := func(k, v string) { - if v != "" { - env = append(env, k+"="+v) +func (e *ProcessEnv) init() error { + foundAllRequired := true + for _, k := range RequiredGoEnvVars { + if _, ok := e.Env[k]; !ok { + foundAllRequired = false + break } } - add("GOPATH", e.GOPATH) - add("GOROOT", e.GOROOT) - add("GO111MODULE", e.GO111MODULE) - add("GOPROXY", e.GOPROXY) - add("GOFLAGS", e.GOFLAGS) - add("GOSUMDB", e.GOSUMDB) - if e.WorkingDir != "" { - add("PWD", e.WorkingDir) + if foundAllRequired { + return nil + } + + if e.Env == nil { + e.Env = map[string]string{} + } + + goEnv := map[string]string{} + stdout, err := e.invokeGo(context.TODO(), "env", append([]string{"-json"}, RequiredGoEnvVars...)...) + if err != nil { + return err + } + if err := json.Unmarshal(stdout.Bytes(), &goEnv); err != nil { + return err + } + for k, v := range goEnv { + e.Env[k] = v + } + return nil +} + +func (e *ProcessEnv) env() []string { + var env []string // the gocommand package will prepend os.Environ. + for k, v := range e.Env { + env = append(env, k+"="+v) } return env } -func (e *ProcessEnv) GetResolver() Resolver { +func (e *ProcessEnv) GetResolver() (Resolver, error) { if e.resolver != nil { - return e.resolver + return e.resolver, nil + } + if err := e.init(); err != nil { + return nil, err } - out, err := e.invokeGo(context.TODO(), "env", "GOMOD") - if err != nil || len(bytes.TrimSpace(out.Bytes())) == 0 { + if len(e.Env["GOMOD"]) == 0 { e.resolver = newGopathResolver(e) - return e.resolver + return e.resolver, nil } e.resolver = newModuleResolver(e) - return e.resolver + return e.resolver, nil } func (e *ProcessEnv) buildContext() *build.Context { ctx := build.Default - ctx.GOROOT = e.GOROOT - ctx.GOPATH = e.GOPATH + ctx.GOROOT = e.goroot() + ctx.GOPATH = e.gopath() // As of Go 1.14, build.Context has a Dir field // (see golang.org/issue/34860). @@ -838,7 +895,7 @@ func (e *ProcessEnv) invokeGo(ctx context.Context, verb string, args ...string) func addStdlibCandidates(pass *pass, refs references) { add := func(pkg string) { // Prevent self-imports. - if path.Base(pkg) == pass.f.Name.Name && filepath.Join(pass.env.GOROOT, "src", pkg) == pass.srcDir { + if path.Base(pkg) == pass.f.Name.Name && filepath.Join(pass.env.goroot(), "src", pkg) == pass.srcDir { return } exports := copyExports(stdlib[pkg]) @@ -923,10 +980,13 @@ func addExternalCandidates(pass *pass, refs references, filename string) error { return false // We'll do our own loading after we sort. }, } - err := pass.env.GetResolver().scan(context.Background(), callback) + resolver, err := pass.env.GetResolver() if err != nil { return err } + if err = resolver.scan(context.Background(), callback); err != nil { + return err + } // Search for imports matching potential package references. type result struct { @@ -1324,7 +1384,10 @@ func loadExportsFromFiles(ctx context.Context, env *ProcessEnv, dir string, incl fullFile := filepath.Join(dir, fi.Name()) f, err := parser.ParseFile(fset, fullFile, nil, 0) if err != nil { - return "", nil, fmt.Errorf("parsing %s: %v", fullFile, err) + if env.Logf != nil { + env.Logf("error parsing %v: %v", fullFile, err) + } + continue } if f.Name.Name == "documentation" { // Special case from go/build.ImportDir, not @@ -1364,6 +1427,10 @@ func findImport(ctx context.Context, pass *pass, candidates []pkgDistance, pkgNa pass.env.Logf("%s candidate %d/%d: %v in %v", pkgName, i+1, len(candidates), c.pkg.importPathShort, c.pkg.dir) } } + resolver, err := pass.env.GetResolver() + if err != nil { + return nil, err + } // Collect exports for packages with matching names. rescv := make([]chan *pkg, len(candidates)) @@ -1402,7 +1469,7 @@ func findImport(ctx context.Context, pass *pass, candidates []pkgDistance, pkgNa } // If we're an x_test, load the package under test's test variant. includeTest := strings.HasSuffix(pass.f.Name.Name, "_test") && c.pkg.dir == pass.srcDir - _, exports, err := pass.env.GetResolver().loadExports(ctx, c.pkg, includeTest) + _, exports, err := resolver.loadExports(ctx, c.pkg, includeTest) if err != nil { if pass.env.Logf != nil { pass.env.Logf("loading exports in dir %s (seeking package %s): %v", c.pkg.dir, pkgName, err) diff --git a/vendor/golang.org/x/tools/internal/imports/imports.go b/vendor/golang.org/x/tools/internal/imports/imports.go index f43d6b22e54..2815edc33d7 100644 --- a/vendor/golang.org/x/tools/internal/imports/imports.go +++ b/vendor/golang.org/x/tools/internal/imports/imports.go @@ -11,29 +11,29 @@ package imports import ( "bufio" "bytes" - "context" "fmt" "go/ast" - "go/build" "go/format" "go/parser" "go/printer" "go/token" "io" - "io/ioutil" - "os" "regexp" "strconv" "strings" "golang.org/x/tools/go/ast/astutil" - "golang.org/x/tools/internal/gocommand" ) // Options is golang.org/x/tools/imports.Options with extra internal-only options. type Options struct { Env *ProcessEnv // The environment to use. Note: this contains the cached module and filesystem state. + // LocalPrefix is a comma-separated string of import path prefixes, which, if + // set, instructs Process to sort the import paths with the given prefixes + // into another group after 3rd-party packages. + LocalPrefix string + Fragment bool // Accept fragment of a source file (no package statement) AllErrors bool // Report all errors (not just the first 10 on different lines) @@ -44,13 +44,8 @@ type Options struct { FormatOnly bool // Disable the insertion and deletion of imports } -// Process implements golang.org/x/tools/imports.Process with explicit context in env. +// Process implements golang.org/x/tools/imports.Process with explicit context in opt.Env. func Process(filename string, src []byte, opt *Options) (formatted []byte, err error) { - src, opt, err = initialize(filename, src, opt) - if err != nil { - return nil, err - } - fileSet := token.NewFileSet() file, adjust, err := parse(fileSet, filename, src, opt) if err != nil { @@ -66,16 +61,12 @@ func Process(filename string, src []byte, opt *Options) (formatted []byte, err e } // FixImports returns a list of fixes to the imports that, when applied, -// will leave the imports in the same state as Process. +// will leave the imports in the same state as Process. src and opt must +// be specified. // // Note that filename's directory influences which imports can be chosen, // so it is important that filename be accurate. func FixImports(filename string, src []byte, opt *Options) (fixes []*ImportFix, err error) { - src, opt, err = initialize(filename, src, opt) - if err != nil { - return nil, err - } - fileSet := token.NewFileSet() file, _, err := parse(fileSet, filename, src, opt) if err != nil { @@ -86,13 +77,9 @@ func FixImports(filename string, src []byte, opt *Options) (fixes []*ImportFix, } // ApplyFixes applies all of the fixes to the file and formats it. extraMode -// is added in when parsing the file. +// is added in when parsing the file. src and opts must be specified, but no +// env is needed. func ApplyFixes(fixes []*ImportFix, filename string, src []byte, opt *Options, extraMode parser.Mode) (formatted []byte, err error) { - src, opt, err = initialize(filename, src, opt) - if err != nil { - return nil, err - } - // Don't use parse() -- we don't care about fragments or statement lists // here, and we need to work with unparseable files. fileSet := token.NewFileSet() @@ -116,63 +103,9 @@ func ApplyFixes(fixes []*ImportFix, filename string, src []byte, opt *Options, e return formatFile(fileSet, file, src, nil, opt) } -// GetAllCandidates gets all of the packages starting with prefix that can be -// imported by filename, sorted by import path. -func GetAllCandidates(ctx context.Context, callback func(ImportFix), searchPrefix, filename, filePkg string, opt *Options) error { - _, opt, err := initialize(filename, []byte{}, opt) - if err != nil { - return err - } - return getAllCandidates(ctx, callback, searchPrefix, filename, filePkg, opt.Env) -} - -// GetPackageExports returns all known packages with name pkg and their exports. -func GetPackageExports(ctx context.Context, callback func(PackageExport), searchPkg, filename, filePkg string, opt *Options) error { - _, opt, err := initialize(filename, []byte{}, opt) - if err != nil { - return err - } - return getPackageExports(ctx, callback, searchPkg, filename, filePkg, opt.Env) -} - -// initialize sets the values for opt and src. -// If they are provided, they are not changed. Otherwise opt is set to the -// default values and src is read from the file system. -func initialize(filename string, src []byte, opt *Options) ([]byte, *Options, error) { - // Use defaults if opt is nil. - if opt == nil { - opt = &Options{Comments: true, TabIndent: true, TabWidth: 8} - } - - // Set the env if the user has not provided it. - if opt.Env == nil { - opt.Env = &ProcessEnv{ - GOPATH: build.Default.GOPATH, - GOROOT: build.Default.GOROOT, - GOFLAGS: os.Getenv("GOFLAGS"), - GO111MODULE: os.Getenv("GO111MODULE"), - GOPROXY: os.Getenv("GOPROXY"), - GOSUMDB: os.Getenv("GOSUMDB"), - } - } - // Set the gocmdRunner if the user has not provided it. - if opt.Env.GocmdRunner == nil { - opt.Env.GocmdRunner = &gocommand.Runner{} - } - if src == nil { - b, err := ioutil.ReadFile(filename) - if err != nil { - return nil, nil, err - } - src = b - } - - return src, opt, nil -} - func formatFile(fileSet *token.FileSet, file *ast.File, src []byte, adjust func(orig []byte, src []byte) []byte, opt *Options) ([]byte, error) { - mergeImports(opt.Env, fileSet, file) - sortImports(opt.Env, fileSet, file) + mergeImports(fileSet, file) + sortImports(opt.LocalPrefix, fileSet, file) imps := astutil.Imports(fileSet, file) var spacesBefore []string // import paths we need spaces before for _, impSection := range imps { @@ -183,7 +116,7 @@ func formatFile(fileSet *token.FileSet, file *ast.File, src []byte, adjust func( lastGroup := -1 for _, importSpec := range impSection { importPath, _ := strconv.Unquote(importSpec.Path.Value) - groupNum := importGroup(opt.Env, importPath) + groupNum := importGroup(opt.LocalPrefix, importPath) if groupNum != lastGroup && lastGroup != -1 { spacesBefore = append(spacesBefore, importPath) } diff --git a/vendor/golang.org/x/tools/internal/imports/mod.go b/vendor/golang.org/x/tools/internal/imports/mod.go index 69e3eecc4c7..664fbbf5ba8 100644 --- a/vendor/golang.org/x/tools/internal/imports/mod.go +++ b/vendor/golang.org/x/tools/internal/imports/mod.go @@ -15,7 +15,7 @@ import ( "strings" "golang.org/x/mod/module" - "golang.org/x/mod/semver" + "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/gopathwalk" ) @@ -24,31 +24,21 @@ import ( type ModuleResolver struct { env *ProcessEnv moduleCacheDir string - dummyVendorMod *ModuleJSON // If vendoring is enabled, the pseudo-module that represents the /vendor directory. + dummyVendorMod *gocommand.ModuleJSON // If vendoring is enabled, the pseudo-module that represents the /vendor directory. roots []gopathwalk.Root scanSema chan struct{} // scanSema prevents concurrent scans and guards scannedRoots. scannedRoots map[gopathwalk.Root]bool initialized bool - main *ModuleJSON - modsByModPath []*ModuleJSON // All modules, ordered by # of path components in module Path... - modsByDir []*ModuleJSON // ...or Dir. + main *gocommand.ModuleJSON + modsByModPath []*gocommand.ModuleJSON // All modules, ordered by # of path components in module Path... + modsByDir []*gocommand.ModuleJSON // ...or Dir. // moduleCacheCache stores information about the module cache. moduleCacheCache *dirInfoCache otherCache *dirInfoCache } -type ModuleJSON struct { - Path string // module path - Replace *ModuleJSON // replaced by this module - Main bool // is this the main module? - Indirect bool // is this module only an indirect dependency of main module? - Dir string // directory holding files for this module, if any - GoMod string // path to go.mod file for this module, if any - GoVersion string // go version used in module -} - func newModuleResolver(e *ProcessEnv) *ModuleResolver { r := &ModuleResolver{ env: e, @@ -62,7 +52,14 @@ func (r *ModuleResolver) init() error { if r.initialized { return nil } - mainMod, vendorEnabled, err := vendorEnabled(r.env) + + inv := gocommand.Invocation{ + BuildFlags: r.env.BuildFlags, + Env: r.env.env(), + Logf: r.env.Logf, + WorkingDir: r.env.WorkingDir, + } + mainMod, vendorEnabled, err := gocommand.VendorEnabled(context.TODO(), inv, r.env.GocmdRunner) if err != nil { return err } @@ -71,18 +68,22 @@ func (r *ModuleResolver) init() error { // Vendor mode is on, so all the non-Main modules are irrelevant, // and we need to search /vendor for everything. r.main = mainMod - r.dummyVendorMod = &ModuleJSON{ + r.dummyVendorMod = &gocommand.ModuleJSON{ Path: "", Dir: filepath.Join(mainMod.Dir, "vendor"), } - r.modsByModPath = []*ModuleJSON{mainMod, r.dummyVendorMod} - r.modsByDir = []*ModuleJSON{mainMod, r.dummyVendorMod} + r.modsByModPath = []*gocommand.ModuleJSON{mainMod, r.dummyVendorMod} + r.modsByDir = []*gocommand.ModuleJSON{mainMod, r.dummyVendorMod} } else { // Vendor mode is off, so run go list -m ... to find everything. r.initAllMods() } - r.moduleCacheDir = filepath.Join(filepath.SplitList(r.env.GOPATH)[0], "/pkg/mod") + if gmc := r.env.Env["GOMODCACHE"]; gmc != "" { + r.moduleCacheDir = gmc + } else { + r.moduleCacheDir = filepath.Join(filepath.SplitList(r.env.gopath())[0], "/pkg/mod") + } sort.Slice(r.modsByModPath, func(i, j int) bool { count := func(x int) int { @@ -98,7 +99,7 @@ func (r *ModuleResolver) init() error { }) r.roots = []gopathwalk.Root{ - {filepath.Join(r.env.GOROOT, "/src"), gopathwalk.RootGOROOT}, + {filepath.Join(r.env.goroot(), "/src"), gopathwalk.RootGOROOT}, } if r.main != nil { r.roots = append(r.roots, gopathwalk.Root{r.main.Dir, gopathwalk.RootCurrentModule}) @@ -106,7 +107,7 @@ func (r *ModuleResolver) init() error { if vendorEnabled { r.roots = append(r.roots, gopathwalk.Root{r.dummyVendorMod.Dir, gopathwalk.RootOther}) } else { - addDep := func(mod *ModuleJSON) { + addDep := func(mod *gocommand.ModuleJSON) { if mod.Replace == nil { // This is redundant with the cache, but we'll skip it cheaply enough. r.roots = append(r.roots, gopathwalk.Root{mod.Dir, gopathwalk.RootModuleCache}) @@ -151,7 +152,7 @@ func (r *ModuleResolver) initAllMods() error { return err } for dec := json.NewDecoder(stdout); dec.More(); { - mod := &ModuleJSON{} + mod := &gocommand.ModuleJSON{} if err := dec.Decode(mod); err != nil { return err } @@ -197,7 +198,7 @@ func (r *ModuleResolver) ClearForNewMod() { // findPackage returns the module and directory that contains the package at // the given import path, or returns nil, "" if no module is in scope. -func (r *ModuleResolver) findPackage(importPath string) (*ModuleJSON, string) { +func (r *ModuleResolver) findPackage(importPath string) (*gocommand.ModuleJSON, string) { // This can't find packages in the stdlib, but that's harmless for all // the existing code paths. for _, m := range r.modsByModPath { @@ -283,7 +284,7 @@ func (r *ModuleResolver) cacheExports(ctx context.Context, env *ProcessEnv, info // findModuleByDir returns the module that contains dir, or nil if no such // module is in scope. -func (r *ModuleResolver) findModuleByDir(dir string) *ModuleJSON { +func (r *ModuleResolver) findModuleByDir(dir string) *gocommand.ModuleJSON { // This is quite tricky and may not be correct. dir could be: // - a package in the main module. // - a replace target underneath the main module's directory. @@ -310,7 +311,7 @@ func (r *ModuleResolver) findModuleByDir(dir string) *ModuleJSON { // dirIsNestedModule reports if dir is contained in a nested module underneath // mod, not actually in mod. -func (r *ModuleResolver) dirIsNestedModule(dir string, mod *ModuleJSON) bool { +func (r *ModuleResolver) dirIsNestedModule(dir string, mod *gocommand.ModuleJSON) bool { if !strings.HasPrefix(dir, mod.Dir) { return false } @@ -490,7 +491,7 @@ func (r *ModuleResolver) scoreImportPath(ctx context.Context, path string) int { return modRelevance(mod) } -func modRelevance(mod *ModuleJSON) int { +func modRelevance(mod *gocommand.ModuleJSON) int { switch { case mod == nil: // out of scope return MaxRelevance - 4 @@ -656,63 +657,3 @@ func modulePath(mod []byte) string { } return "" // missing module path } - -var modFlagRegexp = regexp.MustCompile(`-mod[ =](\w+)`) - -// vendorEnabled indicates if vendoring is enabled. -// Inspired by setDefaultBuildMod in modload/init.go -func vendorEnabled(env *ProcessEnv) (*ModuleJSON, bool, error) { - mainMod, go114, err := getMainModuleAnd114(env) - if err != nil { - return nil, false, err - } - matches := modFlagRegexp.FindStringSubmatch(env.GOFLAGS) - var modFlag string - if len(matches) != 0 { - modFlag = matches[1] - } - if modFlag != "" { - // Don't override an explicit '-mod=' argument. - return mainMod, modFlag == "vendor", nil - } - if mainMod == nil || !go114 { - return mainMod, false, nil - } - // Check 1.14's automatic vendor mode. - if fi, err := os.Stat(filepath.Join(mainMod.Dir, "vendor")); err == nil && fi.IsDir() { - if mainMod.GoVersion != "" && semver.Compare("v"+mainMod.GoVersion, "v1.14") >= 0 { - // The Go version is at least 1.14, and a vendor directory exists. - // Set -mod=vendor by default. - return mainMod, true, nil - } - } - return mainMod, false, nil -} - -// getMainModuleAnd114 gets the main module's information and whether the -// go command in use is 1.14+. This is the information needed to figure out -// if vendoring should be enabled. -func getMainModuleAnd114(env *ProcessEnv) (*ModuleJSON, bool, error) { - const format = `{{.Path}} -{{.Dir}} -{{.GoMod}} -{{.GoVersion}} -{{range context.ReleaseTags}}{{if eq . "go1.14"}}{{.}}{{end}}{{end}} -` - stdout, err := env.invokeGo(context.TODO(), "list", "-m", "-f", format) - if err != nil { - return nil, false, nil - } - lines := strings.Split(stdout.String(), "\n") - if len(lines) < 5 { - return nil, false, fmt.Errorf("unexpected stdout: %q", stdout) - } - mod := &ModuleJSON{ - Path: lines[0], - Dir: lines[1], - GoMod: lines[2], - GoVersion: lines[3], - Main: true, - } - return mod, lines[4] == "go1.14", nil -} diff --git a/vendor/golang.org/x/tools/internal/imports/sortimports.go b/vendor/golang.org/x/tools/internal/imports/sortimports.go index 226279471d3..be8ffa25fec 100644 --- a/vendor/golang.org/x/tools/internal/imports/sortimports.go +++ b/vendor/golang.org/x/tools/internal/imports/sortimports.go @@ -15,7 +15,7 @@ import ( // sortImports sorts runs of consecutive import lines in import blocks in f. // It also removes duplicate imports when it is possible to do so without data loss. -func sortImports(env *ProcessEnv, fset *token.FileSet, f *ast.File) { +func sortImports(localPrefix string, fset *token.FileSet, f *ast.File) { for i, d := range f.Decls { d, ok := d.(*ast.GenDecl) if !ok || d.Tok != token.IMPORT { @@ -40,11 +40,11 @@ func sortImports(env *ProcessEnv, fset *token.FileSet, f *ast.File) { for j, s := range d.Specs { if j > i && fset.Position(s.Pos()).Line > 1+fset.Position(d.Specs[j-1].End()).Line { // j begins a new run. End this one. - specs = append(specs, sortSpecs(env, fset, f, d.Specs[i:j])...) + specs = append(specs, sortSpecs(localPrefix, fset, f, d.Specs[i:j])...) i = j } } - specs = append(specs, sortSpecs(env, fset, f, d.Specs[i:])...) + specs = append(specs, sortSpecs(localPrefix, fset, f, d.Specs[i:])...) d.Specs = specs // Deduping can leave a blank line before the rparen; clean that up. @@ -60,7 +60,7 @@ func sortImports(env *ProcessEnv, fset *token.FileSet, f *ast.File) { // mergeImports merges all the import declarations into the first one. // Taken from golang.org/x/tools/ast/astutil. -func mergeImports(env *ProcessEnv, fset *token.FileSet, f *ast.File) { +func mergeImports(fset *token.FileSet, f *ast.File) { if len(f.Decls) <= 1 { return } @@ -142,7 +142,7 @@ type posSpan struct { End token.Pos } -func sortSpecs(env *ProcessEnv, fset *token.FileSet, f *ast.File, specs []ast.Spec) []ast.Spec { +func sortSpecs(localPrefix string, fset *token.FileSet, f *ast.File, specs []ast.Spec) []ast.Spec { // Can't short-circuit here even if specs are already sorted, // since they might yet need deduplication. // A lone import, however, may be safely ignored. @@ -191,7 +191,7 @@ func sortSpecs(env *ProcessEnv, fset *token.FileSet, f *ast.File, specs []ast.Sp // Reassign the import paths to have the same position sequence. // Reassign each comment to abut the end of its spec. // Sort the comments by new position. - sort.Sort(byImportSpec{env, specs}) + sort.Sort(byImportSpec{localPrefix, specs}) // Dedup. Thanks to our sorting, we can just consider // adjacent pairs of imports. @@ -245,8 +245,8 @@ func sortSpecs(env *ProcessEnv, fset *token.FileSet, f *ast.File, specs []ast.Sp } type byImportSpec struct { - env *ProcessEnv - specs []ast.Spec // slice of *ast.ImportSpec + localPrefix string + specs []ast.Spec // slice of *ast.ImportSpec } func (x byImportSpec) Len() int { return len(x.specs) } @@ -255,8 +255,8 @@ func (x byImportSpec) Less(i, j int) bool { ipath := importPath(x.specs[i]) jpath := importPath(x.specs[j]) - igroup := importGroup(x.env, ipath) - jgroup := importGroup(x.env, jpath) + igroup := importGroup(x.localPrefix, ipath) + jgroup := importGroup(x.localPrefix, jpath) if igroup != jgroup { return igroup < jgroup } diff --git a/vendor/golang.org/x/tools/internal/packagesinternal/packages.go b/vendor/golang.org/x/tools/internal/packagesinternal/packages.go index a88750be2b4..2c4527f2436 100644 --- a/vendor/golang.org/x/tools/internal/packagesinternal/packages.go +++ b/vendor/golang.org/x/tools/internal/packagesinternal/packages.go @@ -2,34 +2,13 @@ package packagesinternal import ( - "time" - "golang.org/x/tools/internal/gocommand" ) -// Fields must match go list; -type Module struct { - Path string // module path - Version string // module version - Versions []string // available module versions (with -versions) - Replace *Module // replaced by this module - Time *time.Time // time version was created - Update *Module // available update, if any (with -u) - Main bool // is this the main module? - Indirect bool // is this module only an indirect dependency of main module? - Dir string // directory holding files for this module, if any - GoMod string // path to go.mod file used when loading this module, if any - GoVersion string // go version used in module - Error *ModuleError // error loading module -} -type ModuleError struct { - Err string // the error itself -} - var GetForTest = func(p interface{}) string { return "" } -var GetModule = func(p interface{}) *Module { return nil } - var GetGoCmdRunner = func(config interface{}) *gocommand.Runner { return nil } var SetGoCmdRunner = func(config interface{}, runner *gocommand.Runner) {} + +var TypecheckCgo int diff --git a/vendor/golang.org/x/tools/internal/span/uri.go b/vendor/golang.org/x/tools/internal/span/uri.go index f9f77600761..78e71fe4518 100644 --- a/vendor/golang.org/x/tools/internal/span/uri.go +++ b/vendor/golang.org/x/tools/internal/span/uri.go @@ -54,10 +54,14 @@ func filename(uri URI) (string, error) { } func URIFromURI(s string) URI { - if !strings.HasPrefix(s, "file:///") { + if !strings.HasPrefix(s, "file://") { return URI(s) } + if !strings.HasPrefix(s, "file:///") { + // VS Code sends URLs with only two slashes, which are invalid. golang/go#39789. + s = "file:///" + s[len("file://"):] + } // Even though the input is a URI, it may not be in canonical form. VS Code // in particular over-escapes :, @, etc. Unescape and re-encode to canonicalize. path, err := url.PathUnescape(s[len("file://"):]) diff --git a/vendor/golang.org/x/tools/internal/telemetry/event/event.go b/vendor/golang.org/x/tools/internal/telemetry/event/event.go deleted file mode 100644 index 2b990c5c1e0..00000000000 --- a/vendor/golang.org/x/tools/internal/telemetry/event/event.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package event provides support for event based telemetry. -package event - -import ( - "fmt" - "time" -) - -type eventType uint8 - -const ( - invalidType = eventType(iota) - LogType // an event that should be recorded in a log - StartSpanType // the start of a span of time - EndSpanType // the end of a span of time - LabelType // some values that should be noted for later events - DetachType // an event that causes a context to detach - RecordType // a value that should be tracked -) - -// sTags is used to hold a small number of tags inside an event whichout -// requiring a separate allocation. -// As tags are often on the stack, this avoids an allocation at all for -// the very common cases of simple events. -// The length needs to be large enough to cope with the majority of events -// but no so large as to cause undue stack pressure. -// A log message with two values will use 3 tags (one for each value and -// one for the message itself). -type sTags [3]Tag - -// Event holds the information about an event of note that ocurred. -type Event struct { - At time.Time - - typ eventType - static sTags // inline storage for the first few tags - dynamic []Tag // dynamically sized storage for remaining tags -} - -// eventTagMap implements TagMap for a the tags of an Event. -type eventTagMap struct { - event Event -} - -func (ev Event) IsLog() bool { return ev.typ == LogType } -func (ev Event) IsEndSpan() bool { return ev.typ == EndSpanType } -func (ev Event) IsStartSpan() bool { return ev.typ == StartSpanType } -func (ev Event) IsLabel() bool { return ev.typ == LabelType } -func (ev Event) IsDetach() bool { return ev.typ == DetachType } -func (ev Event) IsRecord() bool { return ev.typ == RecordType } - -func (ev Event) Format(f fmt.State, r rune) { - tagMap := TagMap(ev) - if !ev.At.IsZero() { - fmt.Fprint(f, ev.At.Format("2006/01/02 15:04:05 ")) - } - msg := Msg.Get(tagMap) - err := Err.Get(tagMap) - fmt.Fprint(f, msg) - if err != nil { - if f.Flag('+') { - fmt.Fprintf(f, ": %+v", err) - } else { - fmt.Fprintf(f, ": %v", err) - } - } - for index := 0; ev.Valid(index); index++ { - tag := ev.Tag(index) - // msg and err were both already printed above, so we skip them to avoid - // double printing - if !tag.Valid() || tag.Key() == Msg || tag.Key() == Err { - continue - } - fmt.Fprintf(f, "\n\t%v", tag) - } -} - -func (ev Event) Valid(index int) bool { - return index >= 0 && index < len(ev.static)+len(ev.dynamic) -} - -func (ev Event) Tag(index int) Tag { - if index < len(ev.static) { - return ev.static[index] - } - return ev.dynamic[index-len(ev.static)] -} - -func (ev Event) Find(key Key) Tag { - for _, tag := range ev.static { - if tag.Key() == key { - return tag - } - } - for _, tag := range ev.dynamic { - if tag.Key() == key { - return tag - } - } - return Tag{} -} - -func makeEvent(typ eventType, static sTags, tags []Tag) Event { - return Event{ - typ: typ, - static: static, - dynamic: tags, - } -} diff --git a/vendor/golang.org/x/tools/internal/telemetry/event/key.go b/vendor/golang.org/x/tools/internal/telemetry/event/key.go deleted file mode 100644 index acde7511e39..00000000000 --- a/vendor/golang.org/x/tools/internal/telemetry/event/key.go +++ /dev/null @@ -1,565 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package event - -import ( - "fmt" - "io" - "math" - "strconv" -) - -var ( - // Msg is a key used to add message strings to tag lists. - Msg = NewStringKey("message", "a readable message") - // Name is used for things like traces that have a name. - Name = NewStringKey("name", "an entity name") - // Err is a key used to add error values to tag lists. - Err = NewErrorKey("error", "an error that occurred") -) - -// Key is used as the identity of a Tag. -// Keys are intended to be compared by pointer only, the name should be unique -// for communicating with external systems, but it is not required or enforced. -type Key interface { - // Name returns the key name. - Name() string - // Description returns a string that can be used to describe the value. - Description() string - - // Format is used in formatting to append the value of the tag to the - // supplied buffer. - // The formatter may use the supplied buf as a scratch area to avoid - // allocations. - Format(w io.Writer, buf []byte, tag Tag) -} - -// ValueKey represents a key for untyped values. -type ValueKey struct { - name string - description string -} - -// NewKey creates a new Key for untyped values. -func NewKey(name, description string) *ValueKey { - return &ValueKey{name: name, description: description} -} - -func (k *ValueKey) Name() string { return k.name } -func (k *ValueKey) Description() string { return k.description } - -func (k *ValueKey) Format(w io.Writer, buf []byte, tag Tag) { - fmt.Fprint(w, k.From(tag)) -} - -// Get can be used to get a tag for the key from a TagMap. -func (k *ValueKey) Get(tags TagMap) interface{} { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return nil -} - -// From can be used to get a value from a Tag. -func (k *ValueKey) From(t Tag) interface{} { return t.UnpackValue() } - -// Of creates a new Tag with this key and the supplied value. -func (k *ValueKey) Of(value interface{}) Tag { return TagOfValue(k, value) } - -// IntKey represents a key -type IntKey struct { - name string - description string -} - -// NewIntKey creates a new Key for int values. -func NewIntKey(name, description string) *IntKey { - return &IntKey{name: name, description: description} -} - -func (k *IntKey) Name() string { return k.name } -func (k *IntKey) Description() string { return k.description } - -func (k *IntKey) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendInt(buf, int64(k.From(tag)), 10)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *IntKey) Of(v int) Tag { return TagOf64(k, uint64(v)) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *IntKey) Get(tags TagMap) int { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *IntKey) From(t Tag) int { return int(t.Unpack64()) } - -// Int8Key represents a key -type Int8Key struct { - name string - description string -} - -// NewInt8Key creates a new Key for int8 values. -func NewInt8Key(name, description string) *Int8Key { - return &Int8Key{name: name, description: description} -} - -func (k *Int8Key) Name() string { return k.name } -func (k *Int8Key) Description() string { return k.description } - -func (k *Int8Key) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendInt(buf, int64(k.From(tag)), 10)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *Int8Key) Of(v int8) Tag { return TagOf64(k, uint64(v)) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *Int8Key) Get(tags TagMap) int8 { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *Int8Key) From(t Tag) int8 { return int8(t.Unpack64()) } - -// Int16Key represents a key -type Int16Key struct { - name string - description string -} - -// NewInt16Key creates a new Key for int16 values. -func NewInt16Key(name, description string) *Int16Key { - return &Int16Key{name: name, description: description} -} - -func (k *Int16Key) Name() string { return k.name } -func (k *Int16Key) Description() string { return k.description } - -func (k *Int16Key) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendInt(buf, int64(k.From(tag)), 10)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *Int16Key) Of(v int16) Tag { return TagOf64(k, uint64(v)) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *Int16Key) Get(tags TagMap) int16 { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *Int16Key) From(t Tag) int16 { return int16(t.Unpack64()) } - -// Int32Key represents a key -type Int32Key struct { - name string - description string -} - -// NewInt32Key creates a new Key for int32 values. -func NewInt32Key(name, description string) *Int32Key { - return &Int32Key{name: name, description: description} -} - -func (k *Int32Key) Name() string { return k.name } -func (k *Int32Key) Description() string { return k.description } - -func (k *Int32Key) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendInt(buf, int64(k.From(tag)), 10)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *Int32Key) Of(v int32) Tag { return TagOf64(k, uint64(v)) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *Int32Key) Get(tags TagMap) int32 { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *Int32Key) From(t Tag) int32 { return int32(t.Unpack64()) } - -// Int64Key represents a key -type Int64Key struct { - name string - description string -} - -// NewInt64Key creates a new Key for int64 values. -func NewInt64Key(name, description string) *Int64Key { - return &Int64Key{name: name, description: description} -} - -func (k *Int64Key) Name() string { return k.name } -func (k *Int64Key) Description() string { return k.description } - -func (k *Int64Key) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendInt(buf, k.From(tag), 10)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *Int64Key) Of(v int64) Tag { return TagOf64(k, uint64(v)) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *Int64Key) Get(tags TagMap) int64 { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *Int64Key) From(t Tag) int64 { return int64(t.Unpack64()) } - -// UIntKey represents a key -type UIntKey struct { - name string - description string -} - -// NewUIntKey creates a new Key for uint values. -func NewUIntKey(name, description string) *UIntKey { - return &UIntKey{name: name, description: description} -} - -func (k *UIntKey) Name() string { return k.name } -func (k *UIntKey) Description() string { return k.description } - -func (k *UIntKey) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendUint(buf, uint64(k.From(tag)), 10)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *UIntKey) Of(v uint) Tag { return TagOf64(k, uint64(v)) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *UIntKey) Get(tags TagMap) uint { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *UIntKey) From(t Tag) uint { return uint(t.Unpack64()) } - -// UInt8Key represents a key -type UInt8Key struct { - name string - description string -} - -// NewUInt8Key creates a new Key for uint8 values. -func NewUInt8Key(name, description string) *UInt8Key { - return &UInt8Key{name: name, description: description} -} - -func (k *UInt8Key) Name() string { return k.name } -func (k *UInt8Key) Description() string { return k.description } - -func (k *UInt8Key) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendUint(buf, uint64(k.From(tag)), 10)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *UInt8Key) Of(v uint8) Tag { return TagOf64(k, uint64(v)) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *UInt8Key) Get(tags TagMap) uint8 { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *UInt8Key) From(t Tag) uint8 { return uint8(t.Unpack64()) } - -// UInt16Key represents a key -type UInt16Key struct { - name string - description string -} - -// NewUInt16Key creates a new Key for uint16 values. -func NewUInt16Key(name, description string) *UInt16Key { - return &UInt16Key{name: name, description: description} -} - -func (k *UInt16Key) Name() string { return k.name } -func (k *UInt16Key) Description() string { return k.description } - -func (k *UInt16Key) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendUint(buf, uint64(k.From(tag)), 10)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *UInt16Key) Of(v uint16) Tag { return TagOf64(k, uint64(v)) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *UInt16Key) Get(tags TagMap) uint16 { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *UInt16Key) From(t Tag) uint16 { return uint16(t.Unpack64()) } - -// UInt32Key represents a key -type UInt32Key struct { - name string - description string -} - -// NewUInt32Key creates a new Key for uint32 values. -func NewUInt32Key(name, description string) *UInt32Key { - return &UInt32Key{name: name, description: description} -} - -func (k *UInt32Key) Name() string { return k.name } -func (k *UInt32Key) Description() string { return k.description } - -func (k *UInt32Key) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendUint(buf, uint64(k.From(tag)), 10)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *UInt32Key) Of(v uint32) Tag { return TagOf64(k, uint64(v)) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *UInt32Key) Get(tags TagMap) uint32 { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *UInt32Key) From(t Tag) uint32 { return uint32(t.Unpack64()) } - -// UInt64Key represents a key -type UInt64Key struct { - name string - description string -} - -// NewUInt64Key creates a new Key for uint64 values. -func NewUInt64Key(name, description string) *UInt64Key { - return &UInt64Key{name: name, description: description} -} - -func (k *UInt64Key) Name() string { return k.name } -func (k *UInt64Key) Description() string { return k.description } - -func (k *UInt64Key) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendUint(buf, k.From(tag), 10)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *UInt64Key) Of(v uint64) Tag { return TagOf64(k, v) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *UInt64Key) Get(tags TagMap) uint64 { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *UInt64Key) From(t Tag) uint64 { return t.Unpack64() } - -// Float32Key represents a key -type Float32Key struct { - name string - description string -} - -// NewFloat32Key creates a new Key for float32 values. -func NewFloat32Key(name, description string) *Float32Key { - return &Float32Key{name: name, description: description} -} - -func (k *Float32Key) Name() string { return k.name } -func (k *Float32Key) Description() string { return k.description } - -func (k *Float32Key) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendFloat(buf, float64(k.From(tag)), 'E', -1, 32)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *Float32Key) Of(v float32) Tag { - return TagOf64(k, uint64(math.Float32bits(v))) -} - -// Get can be used to get a tag for the key from a TagMap. -func (k *Float32Key) Get(tags TagMap) float32 { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *Float32Key) From(t Tag) float32 { - return math.Float32frombits(uint32(t.Unpack64())) -} - -// Float64Key represents a key -type Float64Key struct { - name string - description string -} - -// NewFloat64Key creates a new Key for int64 values. -func NewFloat64Key(name, description string) *Float64Key { - return &Float64Key{name: name, description: description} -} - -func (k *Float64Key) Name() string { return k.name } -func (k *Float64Key) Description() string { return k.description } - -func (k *Float64Key) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendFloat(buf, k.From(tag), 'E', -1, 64)) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *Float64Key) Of(v float64) Tag { - return TagOf64(k, math.Float64bits(v)) -} - -// Get can be used to get a tag for the key from a TagMap. -func (k *Float64Key) Get(tags TagMap) float64 { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return 0 -} - -// From can be used to get a value from a Tag. -func (k *Float64Key) From(t Tag) float64 { - return math.Float64frombits(t.Unpack64()) -} - -// StringKey represents a key -type StringKey struct { - name string - description string -} - -// NewStringKey creates a new Key for int64 values. -func NewStringKey(name, description string) *StringKey { - return &StringKey{name: name, description: description} -} - -func (k *StringKey) Name() string { return k.name } -func (k *StringKey) Description() string { return k.description } - -func (k *StringKey) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendQuote(buf, k.From(tag))) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *StringKey) Of(v string) Tag { return TagOfString(k, v) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *StringKey) Get(tags TagMap) string { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return "" -} - -// From can be used to get a value from a Tag. -func (k *StringKey) From(t Tag) string { return t.UnpackString() } - -// BooleanKey represents a key -type BooleanKey struct { - name string - description string -} - -// NewBooleanKey creates a new Key for bool values. -func NewBooleanKey(name, description string) *BooleanKey { - return &BooleanKey{name: name, description: description} -} - -func (k *BooleanKey) Name() string { return k.name } -func (k *BooleanKey) Description() string { return k.description } - -func (k *BooleanKey) Format(w io.Writer, buf []byte, tag Tag) { - w.Write(strconv.AppendBool(buf, k.From(tag))) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *BooleanKey) Of(v bool) Tag { - if v { - return TagOf64(k, 1) - } - return TagOf64(k, 0) -} - -// Get can be used to get a tag for the key from a TagMap. -func (k *BooleanKey) Get(tags TagMap) bool { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return false -} - -// From can be used to get a value from a Tag. -func (k *BooleanKey) From(t Tag) bool { return t.Unpack64() > 0 } - -// ErrorKey represents a key -type ErrorKey struct { - name string - description string -} - -// NewErrorKey creates a new Key for int64 values. -func NewErrorKey(name, description string) *ErrorKey { - return &ErrorKey{name: name, description: description} -} - -func (k *ErrorKey) Name() string { return k.name } -func (k *ErrorKey) Description() string { return k.description } - -func (k *ErrorKey) Format(w io.Writer, buf []byte, tag Tag) { - io.WriteString(w, k.From(tag).Error()) -} - -// Of creates a new Tag with this key and the supplied value. -func (k *ErrorKey) Of(v error) Tag { return TagOfValue(k, v) } - -// Get can be used to get a tag for the key from a TagMap. -func (k *ErrorKey) Get(tags TagMap) error { - if t := tags.Find(k); t.Valid() { - return k.From(t) - } - return nil -} - -// From can be used to get a value from a Tag. -func (k *ErrorKey) From(t Tag) error { - err, _ := t.UnpackValue().(error) - return err -} diff --git a/vendor/golang.org/x/tools/internal/telemetry/event/label.go b/vendor/golang.org/x/tools/internal/telemetry/event/label.go deleted file mode 100644 index edd34bb08c4..00000000000 --- a/vendor/golang.org/x/tools/internal/telemetry/event/label.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package event - -import ( - "context" -) - -// Label sends a label event to the exporter with the supplied tags. -func Label(ctx context.Context, tags ...Tag) context.Context { - return dispatch(ctx, makeEvent(LabelType, sTags{}, tags)) -} - -// Label1 sends a label event to the exporter with the supplied tags. -func Label1(ctx context.Context, t1 Tag) context.Context { - return dispatch(ctx, makeEvent(LabelType, sTags{t1}, nil)) -} - -// Label2 sends a label event to the exporter with the supplied tags. -func Label2(ctx context.Context, t1, t2 Tag) context.Context { - return dispatch(ctx, makeEvent(LabelType, sTags{t1, t2}, nil)) -} - -// Label3 sends a label event to the exporter with the supplied tags. -func Label3(ctx context.Context, t1, t2, t3 Tag) context.Context { - return dispatch(ctx, makeEvent(LabelType, sTags{t1, t2, t3}, nil)) -} diff --git a/vendor/golang.org/x/tools/internal/telemetry/event/log.go b/vendor/golang.org/x/tools/internal/telemetry/event/log.go deleted file mode 100644 index 8d0a046e78b..00000000000 --- a/vendor/golang.org/x/tools/internal/telemetry/event/log.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package event - -import ( - "context" - "errors" - "fmt" -) - -// Log sends a log event with the supplied tag list to the exporter. -func Log(ctx context.Context, tags ...Tag) { - dispatch(ctx, makeEvent(LogType, sTags{}, tags)) -} - -// Log1 sends a label event to the exporter with the supplied tags. -func Log1(ctx context.Context, t1 Tag) context.Context { - return dispatch(ctx, makeEvent(LogType, sTags{t1}, nil)) -} - -// Log2 sends a label event to the exporter with the supplied tags. -func Log2(ctx context.Context, t1, t2 Tag) context.Context { - return dispatch(ctx, makeEvent(LogType, sTags{t1, t2}, nil)) -} - -// Log3 sends a label event to the exporter with the supplied tags. -func Log3(ctx context.Context, t1, t2, t3 Tag) context.Context { - return dispatch(ctx, makeEvent(LogType, sTags{t1, t2, t3}, nil)) -} - -// Print takes a message and a tag list and combines them into a single event -// before delivering them to the exporter. -func Print(ctx context.Context, message string, tags ...Tag) { - dispatch(ctx, makeEvent(LogType, sTags{Msg.Of(message)}, tags)) -} - -// Print1 takes a message and one tag delivers a log event to the exporter. -// It is a customized version of Print that is faster and does no allocation. -func Print1(ctx context.Context, message string, t1 Tag) { - dispatch(ctx, makeEvent(LogType, sTags{Msg.Of(message), t1}, nil)) -} - -// Print2 takes a message and two tags and delivers a log event to the exporter. -// It is a customized version of Print that is faster and does no allocation. -func Print2(ctx context.Context, message string, t1 Tag, t2 Tag) { - dispatch(ctx, makeEvent(LogType, sTags{Msg.Of(message), t1, t2}, nil)) -} - -// Error takes a message and a tag list and combines them into a single event -// before delivering them to the exporter. It captures the error in the -// delivered event. -func Error(ctx context.Context, message string, err error, tags ...Tag) { - if err == nil { - err = errors.New(message) - message = "" - } - dispatch(ctx, makeEvent(LogType, sTags{Msg.Of(message), Err.Of(err)}, tags)) -} - -// Debugf sends a log event with the supplied message to the exporter. -// This is intended only for temporary debugging lines, and usage should not -// normally be checked in, preffering structured log events for things -// that have to be used in production. -func Debugf(ctx context.Context, message string, args ...interface{}) { - dispatch(ctx, makeEvent(LogType, sTags{Msg.Of(fmt.Sprintf(message, args...))}, nil)) -} diff --git a/vendor/golang.org/x/tools/internal/telemetry/event/metric.go b/vendor/golang.org/x/tools/internal/telemetry/event/metric.go deleted file mode 100644 index e4092bb0d33..00000000000 --- a/vendor/golang.org/x/tools/internal/telemetry/event/metric.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package event - -import ( - "context" -) - -// Record sends a label event to the exporter with the supplied tags. -func Record(ctx context.Context, tags ...Tag) context.Context { - return dispatch(ctx, makeEvent(RecordType, sTags{}, tags)) -} - -// Record1 sends a label event to the exporter with the supplied tags. -func Record1(ctx context.Context, t1 Tag) context.Context { - return dispatch(ctx, makeEvent(RecordType, sTags{t1}, nil)) -} - -// Record2 sends a label event to the exporter with the supplied tags. -func Record2(ctx context.Context, t1, t2 Tag) context.Context { - return dispatch(ctx, makeEvent(RecordType, sTags{t1, t2}, nil)) -} - -// Record3 sends a label event to the exporter with the supplied tags. -func Record3(ctx context.Context, t1, t2, t3 Tag) context.Context { - return dispatch(ctx, makeEvent(RecordType, sTags{t1, t2, t3}, nil)) -} diff --git a/vendor/golang.org/x/tools/internal/telemetry/event/tag.go b/vendor/golang.org/x/tools/internal/telemetry/event/tag.go deleted file mode 100644 index 5230736ef3c..00000000000 --- a/vendor/golang.org/x/tools/internal/telemetry/event/tag.go +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package event - -import ( - "fmt" - "io" - "reflect" - "unsafe" -) - -// Tag holds a key and value pair. -// It is normally used when passing around lists of tags. -type Tag struct { - key Key - packed uint64 - untyped interface{} -} - -// TagMap is the interface to a collection of Tags indexed by key. -type TagMap interface { - // Find returns the tag that matches the supplied key. - Find(key Key) Tag -} - -// TagList is the interface to something that provides an iterable -// list of tags. -// Iteration should start from 0 and continue until Valid returns false. -type TagList interface { - // Valid returns true if the index is within range for the list. - // It does not imply the tag at that index will itself be valid. - Valid(index int) bool - // Tag returns the tag at the given index. - Tag(index int) Tag -} - -// tagList implements TagList for a list of Tags. -type tagList struct { - tags []Tag -} - -// tagFilter wraps a TagList filtering out specific tags. -type tagFilter struct { - keys []Key - underlying TagList -} - -// tagMap implements TagMap for a simple list of tags. -type tagMap struct { - tags []Tag -} - -// tagMapChain implements TagMap for a list of underlying TagMap. -type tagMapChain struct { - maps []TagMap -} - -// TagOfValue creates a new tag from the key and value. -// This method is for implementing new key types, tag creation should -// normally be done with the Of method of the key. -func TagOfValue(k Key, value interface{}) Tag { return Tag{key: k, untyped: value} } - -// UnpackValue assumes the tag was built using TagOfValue and returns the value -// that was passed to that constructor. -// This method is for implementing new key types, for type safety normal -// access should be done with the From method of the key. -func (t Tag) UnpackValue() interface{} { return t.untyped } - -// TagOf64 creates a new tag from a key and a uint64. This is often -// used for non uint64 values that can be packed into a uint64. -// This method is for implementing new key types, tag creation should -// normally be done with the Of method of the key. -func TagOf64(k Key, v uint64) Tag { return Tag{key: k, packed: v} } - -// Unpack64 assumes the tag was built using TagOf64 and returns the value that -// was passed to that constructor. -// This method is for implementing new key types, for type safety normal -// access should be done with the From method of the key. -func (t Tag) Unpack64() uint64 { return t.packed } - -// TagOfString creates a new tag from a key and a string. -// This method is for implementing new key types, tag creation should -// normally be done with the Of method of the key. -func TagOfString(k Key, v string) Tag { - hdr := (*reflect.StringHeader)(unsafe.Pointer(&v)) - return Tag{ - key: k, - packed: uint64(hdr.Len), - untyped: unsafe.Pointer(hdr.Data), - } -} - -// UnpackString assumes the tag was built using TagOfString and returns the -// value that was passed to that constructor. -// This method is for implementing new key types, for type safety normal -// access should be done with the From method of the key. -func (t Tag) UnpackString() string { - var v string - hdr := (*reflect.StringHeader)(unsafe.Pointer(&v)) - hdr.Data = uintptr(t.untyped.(unsafe.Pointer)) - hdr.Len = int(t.packed) - return *(*string)(unsafe.Pointer(hdr)) -} - -// Valid returns true if the Tag is a valid one (it has a key). -func (t Tag) Valid() bool { return t.key != nil } - -// Key returns the key of this Tag. -func (t Tag) Key() Key { return t.key } - -// Format is used for debug printing of tags. -func (t Tag) Format(f fmt.State, r rune) { - if !t.Valid() { - io.WriteString(f, `nil`) - return - } - io.WriteString(f, t.Key().Name()) - io.WriteString(f, "=") - var buf [128]byte - t.Key().Format(f, buf[:0], t) -} - -func (l *tagList) Valid(index int) bool { - return index >= 0 && index < len(l.tags) -} - -func (l *tagList) Tag(index int) Tag { - return l.tags[index] -} - -func (f *tagFilter) Valid(index int) bool { - return f.underlying.Valid(index) -} - -func (f *tagFilter) Tag(index int) Tag { - tag := f.underlying.Tag(index) - for _, f := range f.keys { - if tag.Key() == f { - return Tag{} - } - } - return tag -} - -func (l tagMap) Find(key Key) Tag { - for _, tag := range l.tags { - if tag.Key() == key { - return tag - } - } - return Tag{} -} - -func (c tagMapChain) Find(key Key) Tag { - for _, src := range c.maps { - tag := src.Find(key) - if tag.Valid() { - return tag - } - } - return Tag{} -} - -var emptyList = &tagList{} - -func NewTagList(tags ...Tag) TagList { - if len(tags) == 0 { - return emptyList - } - return &tagList{tags: tags} -} - -func Filter(l TagList, keys ...Key) TagList { - if len(keys) == 0 { - return l - } - return &tagFilter{keys: keys, underlying: l} -} - -func NewTagMap(tags ...Tag) TagMap { - return tagMap{tags: tags} -} - -func MergeTagMaps(srcs ...TagMap) TagMap { - var nonNil []TagMap - for _, src := range srcs { - if src != nil { - nonNil = append(nonNil, src) - } - } - if len(nonNil) == 1 { - return nonNil[0] - } - return tagMapChain{maps: nonNil} -} diff --git a/vendor/golang.org/x/tools/internal/telemetry/event/trace.go b/vendor/golang.org/x/tools/internal/telemetry/event/trace.go deleted file mode 100644 index 2c40341ff40..00000000000 --- a/vendor/golang.org/x/tools/internal/telemetry/event/trace.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package event - -import ( - "context" -) - -// StartSpan sends a span start event with the supplied tag list to the exporter. -// It also returns a function that will end the span, which should normally be -// deferred. -func StartSpan(ctx context.Context, name string, tags ...Tag) (context.Context, func()) { - return dispatchPair(ctx, - makeEvent(StartSpanType, sTags{Name.Of(name)}, tags), - makeEvent(EndSpanType, sTags{}, nil)) -} - -// StartSpan1 sends a span start event with the supplied tag list to the exporter. -// It also returns a function that will end the span, which should normally be -// deferred. -func StartSpan1(ctx context.Context, name string, t1 Tag) (context.Context, func()) { - return dispatchPair(ctx, - makeEvent(StartSpanType, sTags{Name.Of(name), t1}, nil), - makeEvent(EndSpanType, sTags{}, nil)) -} - -// StartSpan2 sends a span start event with the supplied tag list to the exporter. -// It also returns a function that will end the span, which should normally be -// deferred. -func StartSpan2(ctx context.Context, name string, t1, t2 Tag) (context.Context, func()) { - return dispatchPair(ctx, - makeEvent(StartSpanType, sTags{Name.Of(name), t1, t2}, nil), - makeEvent(EndSpanType, sTags{}, nil)) -} - -// Detach returns a context without an associated span. -// This allows the creation of spans that are not children of the current span. -func Detach(ctx context.Context) context.Context { - return dispatch(ctx, makeEvent(DetachType, sTags{}, nil)) -} diff --git a/vendor/golang.org/x/tools/internal/testenv/testenv.go b/vendor/golang.org/x/tools/internal/testenv/testenv.go index 0cc90d26a51..f725b959f85 100644 --- a/vendor/golang.org/x/tools/internal/testenv/testenv.go +++ b/vendor/golang.org/x/tools/internal/testenv/testenv.go @@ -7,7 +7,9 @@ package testenv import ( + "bytes" "fmt" + "go/build" "io/ioutil" "os" "os/exec" @@ -39,6 +41,17 @@ var checkGoGoroot struct { } func hasTool(tool string) error { + if tool == "cgo" { + enabled, err := cgoEnabled(false) + if err != nil { + return fmt.Errorf("checking cgo: %v", err) + } + if !enabled { + return fmt.Errorf("cgo not enabled") + } + return nil + } + _, err := exec.LookPath(tool) if err != nil { return err @@ -77,11 +90,35 @@ func hasTool(tool string) error { if checkGoGoroot.err != nil { return checkGoGoroot.err } + + case "diff": + // Check that diff is the GNU version, needed for the -u argument and + // to report missing newlines at the end of files. + out, err := exec.Command(tool, "-version").Output() + if err != nil { + return err + } + if !bytes.Contains(out, []byte("GNU diffutils")) { + return fmt.Errorf("diff is not the GNU version") + } } return nil } +func cgoEnabled(bypassEnvironment bool) (bool, error) { + cmd := exec.Command("go", "env", "CGO_ENABLED") + if bypassEnvironment { + cmd.Env = append(append([]string(nil), os.Environ()...), "CGO_ENABLED=") + } + out, err := cmd.CombinedOutput() + if err != nil { + return false, err + } + enabled := strings.TrimSpace(string(out)) + return enabled == "1", nil +} + func allowMissingTool(tool string) bool { if runtime.GOOS == "android" { // Android builds generally run tests on a separate machine from the build, @@ -90,6 +127,15 @@ func allowMissingTool(tool string) bool { } switch tool { + case "cgo": + if strings.HasSuffix(os.Getenv("GO_BUILDER_NAME"), "-nocgo") { + // Explicitly disabled on -nocgo builders. + return true + } + if enabled, err := cgoEnabled(true); err == nil && !enabled { + // No platform support. + return true + } case "go": if os.Getenv("GO_BUILDER_NAME") == "illumos-amd64-joyent" { // Work around a misconfigured builder (see https://golang.org/issue/33950). @@ -113,6 +159,7 @@ func allowMissingTool(tool string) bool { } // NeedsTool skips t if the named tool is not present in the path. +// As a special case, "cgo" means "go" is present and can compile cgo programs. func NeedsTool(t Testing, tool string) { if t, ok := t.(helperer); ok { t.Helper() @@ -173,13 +220,72 @@ func NeedsGoPackagesEnv(t Testing, env []string) { NeedsGoPackages(t) } +// NeedsGoBuild skips t if the current system can't build programs with ``go build'' +// and then run them with os.StartProcess or exec.Command. +// android, and darwin/arm systems don't have the userspace go build needs to run, +// and js/wasm doesn't support running subprocesses. +func NeedsGoBuild(t Testing) { + if t, ok := t.(helperer); ok { + t.Helper() + } + + NeedsTool(t, "go") + + switch runtime.GOOS { + case "android", "js": + t.Skipf("skipping test: %v can't build and run Go binaries", runtime.GOOS) + case "darwin": + if strings.HasPrefix(runtime.GOARCH, "arm") { + t.Skipf("skipping test: darwin/arm can't build and run Go binaries") + } + } +} + // ExitIfSmallMachine emits a helpful diagnostic and calls os.Exit(0) if the // current machine is a builder known to have scarce resources. // // It should be called from within a TestMain function. func ExitIfSmallMachine() { - if os.Getenv("GO_BUILDER_NAME") == "linux-arm" { + switch os.Getenv("GO_BUILDER_NAME") { + case "linux-arm": fmt.Fprintln(os.Stderr, "skipping test: linux-arm builder lacks sufficient memory (https://golang.org/issue/32834)") os.Exit(0) + case "plan9-arm": + fmt.Fprintln(os.Stderr, "skipping test: plan9-arm builder lacks sufficient memory (https://golang.org/issue/38772)") + os.Exit(0) + } +} + +// Go1Point returns the x in Go 1.x. +func Go1Point() int { + for i := len(build.Default.ReleaseTags) - 1; i >= 0; i-- { + var version int + if _, err := fmt.Sscanf(build.Default.ReleaseTags[i], "go1.%d", &version); err != nil { + continue + } + return version + } + panic("bad release tags") +} + +// NeedsGo1Point skips t if the Go version used to run the test is older than +// 1.x. +func NeedsGo1Point(t Testing, x int) { + if t, ok := t.(helperer); ok { + t.Helper() + } + if Go1Point() < x { + t.Skipf("running Go version %q is version 1.%d, older than required 1.%d", runtime.Version(), Go1Point(), x) + } +} + +// SkipAfterGo1Point skips t if the Go version used to run the test is newer than +// 1.x. +func SkipAfterGo1Point(t Testing, x int) { + if t, ok := t.(helperer); ok { + t.Helper() + } + if Go1Point() > x { + t.Skipf("running Go version %q is version 1.%d, newer than maximum 1.%d", runtime.Version(), Go1Point(), x) } } diff --git a/vendor/golang.org/x/tools/internal/typesinternal/types.go b/vendor/golang.org/x/tools/internal/typesinternal/types.go new file mode 100644 index 00000000000..a5bb408e2f1 --- /dev/null +++ b/vendor/golang.org/x/tools/internal/typesinternal/types.go @@ -0,0 +1,28 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package typesinternal + +import ( + "go/types" + "reflect" + "unsafe" +) + +func SetUsesCgo(conf *types.Config) bool { + v := reflect.ValueOf(conf).Elem() + + f := v.FieldByName("go115UsesCgo") + if !f.IsValid() { + f = v.FieldByName("UsesCgo") + if !f.IsValid() { + return false + } + } + + addr := unsafe.Pointer(f.UnsafeAddr()) + *(*bool)(addr) = true + + return true +} diff --git a/vendor/golang.org/x/tools/txtar/archive.go b/vendor/golang.org/x/tools/txtar/archive.go new file mode 100644 index 00000000000..c384f33bdf8 --- /dev/null +++ b/vendor/golang.org/x/tools/txtar/archive.go @@ -0,0 +1,140 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package txtar implements a trivial text-based file archive format. +// +// The goals for the format are: +// +// - be trivial enough to create and edit by hand. +// - be able to store trees of text files describing go command test cases. +// - diff nicely in git history and code reviews. +// +// Non-goals include being a completely general archive format, +// storing binary data, storing file modes, storing special files like +// symbolic links, and so on. +// +// Txtar format +// +// A txtar archive is zero or more comment lines and then a sequence of file entries. +// Each file entry begins with a file marker line of the form "-- FILENAME --" +// and is followed by zero or more file content lines making up the file data. +// The comment or file content ends at the next file marker line. +// The file marker line must begin with the three-byte sequence "-- " +// and end with the three-byte sequence " --", but the enclosed +// file name can be surrounding by additional white space, +// all of which is stripped. +// +// If the txtar file is missing a trailing newline on the final line, +// parsers should consider a final newline to be present anyway. +// +// There are no possible syntax errors in a txtar archive. +package txtar + +import ( + "bytes" + "fmt" + "io/ioutil" + "strings" +) + +// An Archive is a collection of files. +type Archive struct { + Comment []byte + Files []File +} + +// A File is a single file in an archive. +type File struct { + Name string // name of file ("foo/bar.txt") + Data []byte // text content of file +} + +// Format returns the serialized form of an Archive. +// It is assumed that the Archive data structure is well-formed: +// a.Comment and all a.File[i].Data contain no file marker lines, +// and all a.File[i].Name is non-empty. +func Format(a *Archive) []byte { + var buf bytes.Buffer + buf.Write(fixNL(a.Comment)) + for _, f := range a.Files { + fmt.Fprintf(&buf, "-- %s --\n", f.Name) + buf.Write(fixNL(f.Data)) + } + return buf.Bytes() +} + +// ParseFile parses the named file as an archive. +func ParseFile(file string) (*Archive, error) { + data, err := ioutil.ReadFile(file) + if err != nil { + return nil, err + } + return Parse(data), nil +} + +// Parse parses the serialized form of an Archive. +// The returned Archive holds slices of data. +func Parse(data []byte) *Archive { + a := new(Archive) + var name string + a.Comment, name, data = findFileMarker(data) + for name != "" { + f := File{name, nil} + f.Data, name, data = findFileMarker(data) + a.Files = append(a.Files, f) + } + return a +} + +var ( + newlineMarker = []byte("\n-- ") + marker = []byte("-- ") + markerEnd = []byte(" --") +) + +// findFileMarker finds the next file marker in data, +// extracts the file name, and returns the data before the marker, +// the file name, and the data after the marker. +// If there is no next marker, findFileMarker returns before = fixNL(data), name = "", after = nil. +func findFileMarker(data []byte) (before []byte, name string, after []byte) { + var i int + for { + if name, after = isMarker(data[i:]); name != "" { + return data[:i], name, after + } + j := bytes.Index(data[i:], newlineMarker) + if j < 0 { + return fixNL(data), "", nil + } + i += j + 1 // positioned at start of new possible marker + } +} + +// isMarker checks whether data begins with a file marker line. +// If so, it returns the name from the line and the data after the line. +// Otherwise it returns name == "" with an unspecified after. +func isMarker(data []byte) (name string, after []byte) { + if !bytes.HasPrefix(data, marker) { + return "", nil + } + if i := bytes.IndexByte(data, '\n'); i >= 0 { + data, after = data[:i], data[i+1:] + } + if !bytes.HasSuffix(data, markerEnd) { + return "", nil + } + return strings.TrimSpace(string(data[len(marker) : len(data)-len(markerEnd)])), after +} + +// If data is empty or ends in \n, fixNL returns data. +// Otherwise fixNL returns a new slice consisting of data with a final \n added. +func fixNL(data []byte) []byte { + if len(data) == 0 || data[len(data)-1] == '\n' { + return data + } + d := make([]byte, len(data)+1) + copy(d, data) + d[len(data)] = '\n' + return d +} diff --git a/vendor/google.golang.org/api/AUTHORS b/vendor/google.golang.org/api/AUTHORS index f73b7257457..f07029059d2 100644 --- a/vendor/google.golang.org/api/AUTHORS +++ b/vendor/google.golang.org/api/AUTHORS @@ -8,3 +8,4 @@ # Please keep the list sorted. Google Inc. +LightStep Inc. diff --git a/vendor/google.golang.org/api/CONTRIBUTORS b/vendor/google.golang.org/api/CONTRIBUTORS index fe55ebff072..788677b8f04 100644 --- a/vendor/google.golang.org/api/CONTRIBUTORS +++ b/vendor/google.golang.org/api/CONTRIBUTORS @@ -45,6 +45,7 @@ Jason Hall Johan Euphrosine Kostik Shtoyk Kunpei Sakai +Matthew Dolan Matthew Whisenhunt Michael McGreevy Nick Craig-Wood diff --git a/vendor/google.golang.org/api/gensupport/jsonfloat.go b/vendor/google.golang.org/api/gensupport/jsonfloat.go deleted file mode 100644 index 8377850811f..00000000000 --- a/vendor/google.golang.org/api/gensupport/jsonfloat.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2016 Google LLC -// -// 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 gensupport - -import ( - "encoding/json" - "errors" - "fmt" - "math" -) - -// JSONFloat64 is a float64 that supports proper unmarshaling of special float -// values in JSON, according to -// https://developers.google.com/protocol-buffers/docs/proto3#json. Although -// that is a proto-to-JSON spec, it applies to all Google APIs. -// -// The jsonpb package -// (https://github.com/golang/protobuf/blob/master/jsonpb/jsonpb.go) has -// similar functionality, but only for direct translation from proto messages -// to JSON. -type JSONFloat64 float64 - -func (f *JSONFloat64) UnmarshalJSON(data []byte) error { - var ff float64 - if err := json.Unmarshal(data, &ff); err == nil { - *f = JSONFloat64(ff) - return nil - } - var s string - if err := json.Unmarshal(data, &s); err == nil { - switch s { - case "NaN": - ff = math.NaN() - case "Infinity": - ff = math.Inf(1) - case "-Infinity": - ff = math.Inf(-1) - default: - return fmt.Errorf("google.golang.org/api/internal: bad float string %q", s) - } - *f = JSONFloat64(ff) - return nil - } - return errors.New("google.golang.org/api/internal: data not float or string") -} diff --git a/vendor/google.golang.org/api/gensupport/send.go b/vendor/google.golang.org/api/gensupport/send.go deleted file mode 100644 index 5799393093d..00000000000 --- a/vendor/google.golang.org/api/gensupport/send.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gensupport - -import ( - "context" - "encoding/json" - "errors" - "net/http" -) - -// Hook is the type of a function that is called once before each HTTP request -// that is sent by a generated API. It returns a function that is called after -// the request returns. -// Hooks are not called if the context is nil. -type Hook func(ctx context.Context, req *http.Request) func(resp *http.Response) - -var hooks []Hook - -// RegisterHook registers a Hook to be called before each HTTP request by a -// generated API. Hooks are called in the order they are registered. Each -// hook can return a function; if it is non-nil, it is called after the HTTP -// request returns. These functions are called in the reverse order. -// RegisterHook should not be called concurrently with itself or SendRequest. -func RegisterHook(h Hook) { - hooks = append(hooks, h) -} - -// SendRequest sends a single HTTP request using the given client. -// If ctx is non-nil, it calls all hooks, then sends the request with -// req.WithContext, then calls any functions returned by the hooks in -// reverse order. -func SendRequest(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { - // Disallow Accept-Encoding because it interferes with the automatic gzip handling - // done by the default http.Transport. See https://github.com/google/google-api-go-client/issues/219. - if _, ok := req.Header["Accept-Encoding"]; ok { - return nil, errors.New("google api: custom Accept-Encoding headers not allowed") - } - if ctx == nil { - return client.Do(req) - } - // Call hooks in order of registration, store returned funcs. - post := make([]func(resp *http.Response), len(hooks)) - for i, h := range hooks { - fn := h(ctx, req) - post[i] = fn - } - - // Send request. - resp, err := send(ctx, client, req) - - // Call returned funcs in reverse order. - for i := len(post) - 1; i >= 0; i-- { - if fn := post[i]; fn != nil { - fn(resp) - } - } - return resp, err -} - -func send(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { - if client == nil { - client = http.DefaultClient - } - resp, err := client.Do(req.WithContext(ctx)) - // If we got an error, and the context has been canceled, - // the context's error is probably more useful. - if err != nil { - select { - case <-ctx.Done(): - err = ctx.Err() - default: - } - } - return resp, err -} - -// DecodeResponse decodes the body of res into target. If there is no body, -// target is unchanged. -func DecodeResponse(target interface{}, res *http.Response) error { - if res.StatusCode == http.StatusNoContent { - return nil - } - return json.NewDecoder(res.Body).Decode(target) -} diff --git a/vendor/google.golang.org/api/googleapi/googleapi.go b/vendor/google.golang.org/api/googleapi/googleapi.go index ab53767624a..d1784f1a349 100644 --- a/vendor/google.golang.org/api/googleapi/googleapi.go +++ b/vendor/google.golang.org/api/googleapi/googleapi.go @@ -1,4 +1,4 @@ -// Copyright 2011 Google Inc. All rights reserved. +// Copyright 2011 Google LLC. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -16,7 +16,7 @@ import ( "net/url" "strings" - "google.golang.org/api/googleapi/internal/uritemplates" + "google.golang.org/api/internal/third_party/uritemplates" ) // ContentTyper is an interface for Readers which know (or would like @@ -54,7 +54,7 @@ const ( // DefaultUploadChunkSize is the default chunk size to use for resumable // uploads if not specified by the user. - DefaultUploadChunkSize = 8 * 1024 * 1024 + DefaultUploadChunkSize = 16 * 1024 * 1024 // MinUploadChunkSize is the minimum chunk size that can be used for // resumable uploads. All user-specified chunk sizes must be multiple of @@ -69,6 +69,8 @@ type Error struct { // Message is the server response message and is only populated when // explicitly referenced by the JSON server response. Message string `json:"message"` + // Details provide more context to an error. + Details []interface{} `json:"details"` // Body is the raw response returned by the server. // It is often but not always JSON, depending on how the request fails. Body string @@ -95,6 +97,16 @@ func (e *Error) Error() string { if e.Message != "" { fmt.Fprintf(&buf, "%s", e.Message) } + if len(e.Details) > 0 { + var detailBuf bytes.Buffer + enc := json.NewEncoder(&detailBuf) + enc.SetIndent("", " ") + if err := enc.Encode(e.Details); err == nil { + fmt.Fprint(&buf, "\nDetails:") + fmt.Fprintf(&buf, "\n%s", detailBuf.String()) + + } + } if len(e.Errors) == 0 { return strings.TrimSpace(buf.String()) } @@ -256,14 +268,22 @@ func ProcessMediaOptions(opts []MediaOption) *MediaOptions { // "http://www.golang.org/topics/myproject/mytopic". It strips all parent // references (e.g. ../..) as well as anything after the host // (e.g. /bar/gaz gets stripped out of foo.com/bar/gaz). +// +// ResolveRelative panics if either basestr or relstr is not able to be parsed. func ResolveRelative(basestr, relstr string) string { - u, _ := url.Parse(basestr) + u, err := url.Parse(basestr) + if err != nil { + panic(fmt.Sprintf("failed to parse %q", basestr)) + } afterColonPath := "" if i := strings.IndexRune(relstr, ':'); i > 0 { afterColonPath = relstr[i+1:] relstr = relstr[:i] } - rel, _ := url.Parse(relstr) + rel, err := url.Parse(relstr) + if err != nil { + panic(fmt.Sprintf("failed to parse %q", relstr)) + } u = u.ResolveReference(rel) us := u.String() if afterColonPath != "" { @@ -331,7 +351,7 @@ func ConvertVariant(v map[string]interface{}, dst interface{}) bool { } // A Field names a field to be retrieved with a partial response. -// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse +// https://cloud.google.com/storage/docs/json_api/v1/how-tos/performance // // Partial responses can dramatically reduce the amount of data that must be sent to your application. // In order to request partial responses, you can specify the full list of fields @@ -348,9 +368,6 @@ func ConvertVariant(v map[string]interface{}, dst interface{}) bool { // // svc.Events.List().Fields("nextPageToken", "items(id,updated)").Do() // -// More information about field formatting can be found here: -// https://developers.google.com/+/api/#fields-syntax -// // Another way to find field names is through the Google API explorer: // https://developers.google.com/apis-explorer/#p/ type Field string diff --git a/vendor/google.golang.org/api/googleapi/internal/uritemplates/LICENSE b/vendor/google.golang.org/api/googleapi/internal/uritemplates/LICENSE deleted file mode 100644 index de9c88cb65c..00000000000 --- a/vendor/google.golang.org/api/googleapi/internal/uritemplates/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright (c) 2013 Joshua Tacoma - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/google.golang.org/api/googleapi/transport/apikey.go b/vendor/google.golang.org/api/googleapi/transport/apikey.go index eca1ea25077..61720ec2ea1 100644 --- a/vendor/google.golang.org/api/googleapi/transport/apikey.go +++ b/vendor/google.golang.org/api/googleapi/transport/apikey.go @@ -1,9 +1,13 @@ -// Copyright 2012 Google Inc. All rights reserved. +// Copyright 2012 Google LLC. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package transport contains HTTP transports used to make // authenticated API requests. +// +// This package is DEPRECATED. Users should instead use, +// +// service, err := NewService(..., option.WithAPIKey(...)) package transport import ( @@ -13,6 +17,8 @@ import ( // APIKey is an HTTP Transport which wraps an underlying transport and // appends an API Key "key" parameter to the URL of outgoing requests. +// +// Deprecated: please use NewService(..., option.WithAPIKey(...)) instead. type APIKey struct { // Key is the API Key to set on requests. Key string diff --git a/vendor/google.golang.org/api/googleapi/types.go b/vendor/google.golang.org/api/googleapi/types.go index a280e3021a1..fabf74d50d0 100644 --- a/vendor/google.golang.org/api/googleapi/types.go +++ b/vendor/google.golang.org/api/googleapi/types.go @@ -1,4 +1,4 @@ -// Copyright 2013 Google Inc. All rights reserved. +// Copyright 2013 Google LLC. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. diff --git a/vendor/google.golang.org/api/internal/conn_pool.go b/vendor/google.golang.org/api/internal/conn_pool.go new file mode 100644 index 00000000000..fedcce15b46 --- /dev/null +++ b/vendor/google.golang.org/api/internal/conn_pool.go @@ -0,0 +1,30 @@ +// Copyright 2020 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package internal + +import ( + "google.golang.org/grpc" +) + +// ConnPool is a pool of grpc.ClientConns. +type ConnPool interface { + // Conn returns a ClientConn from the pool. + // + // Conns aren't returned to the pool. + Conn() *grpc.ClientConn + + // Num returns the number of connections in the pool. + // + // It will always return the same value. + Num() int + + // Close closes every ClientConn in the pool. + // + // The error returned by Close may be a single error or multiple errors. + Close() error + + // ConnPool implements grpc.ClientConnInterface to enable it to be used directly with generated proto stubs. + grpc.ClientConnInterface +} diff --git a/vendor/google.golang.org/api/internal/creds.go b/vendor/google.golang.org/api/internal/creds.go index 69b8659fddb..75e9445e1b3 100644 --- a/vendor/google.golang.org/api/internal/creds.go +++ b/vendor/google.golang.org/api/internal/creds.go @@ -1,16 +1,6 @@ -// Copyright 2017 Google LLC -// -// 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. +// Copyright 2017 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. package internal @@ -100,3 +90,16 @@ func selfSignedJWTTokenSource(data []byte, endpoint string, audiences []string) } return google.JWTAccessTokenSourceFromJSON(data, audience) } + +// QuotaProjectFromCreds returns the quota project from the JSON blob in the provided credentials. +// +// NOTE(cbro): consider promoting this to a field on google.Credentials. +func QuotaProjectFromCreds(cred *google.Credentials) string { + var v struct { + QuotaProject string `json:"quota_project_id"` + } + if err := json.Unmarshal(cred.JSON, &v); err != nil { + return "" + } + return v.QuotaProject +} diff --git a/vendor/google.golang.org/api/gensupport/buffer.go b/vendor/google.golang.org/api/internal/gensupport/buffer.go similarity index 100% rename from vendor/google.golang.org/api/gensupport/buffer.go rename to vendor/google.golang.org/api/internal/gensupport/buffer.go diff --git a/vendor/google.golang.org/api/gensupport/doc.go b/vendor/google.golang.org/api/internal/gensupport/doc.go similarity index 100% rename from vendor/google.golang.org/api/gensupport/doc.go rename to vendor/google.golang.org/api/internal/gensupport/doc.go diff --git a/vendor/google.golang.org/api/gensupport/json.go b/vendor/google.golang.org/api/internal/gensupport/json.go similarity index 100% rename from vendor/google.golang.org/api/gensupport/json.go rename to vendor/google.golang.org/api/internal/gensupport/json.go diff --git a/vendor/google.golang.org/api/internal/gensupport/jsonfloat.go b/vendor/google.golang.org/api/internal/gensupport/jsonfloat.go new file mode 100644 index 00000000000..13c2f930207 --- /dev/null +++ b/vendor/google.golang.org/api/internal/gensupport/jsonfloat.go @@ -0,0 +1,47 @@ +// Copyright 2016 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "encoding/json" + "errors" + "fmt" + "math" +) + +// JSONFloat64 is a float64 that supports proper unmarshaling of special float +// values in JSON, according to +// https://developers.google.com/protocol-buffers/docs/proto3#json. Although +// that is a proto-to-JSON spec, it applies to all Google APIs. +// +// The jsonpb package +// (https://github.com/golang/protobuf/blob/master/jsonpb/jsonpb.go) has +// similar functionality, but only for direct translation from proto messages +// to JSON. +type JSONFloat64 float64 + +func (f *JSONFloat64) UnmarshalJSON(data []byte) error { + var ff float64 + if err := json.Unmarshal(data, &ff); err == nil { + *f = JSONFloat64(ff) + return nil + } + var s string + if err := json.Unmarshal(data, &s); err == nil { + switch s { + case "NaN": + ff = math.NaN() + case "Infinity": + ff = math.Inf(1) + case "-Infinity": + ff = math.Inf(-1) + default: + return fmt.Errorf("google.golang.org/api/internal: bad float string %q", s) + } + *f = JSONFloat64(ff) + return nil + } + return errors.New("google.golang.org/api/internal: data not float or string") +} diff --git a/vendor/google.golang.org/api/gensupport/media.go b/vendor/google.golang.org/api/internal/gensupport/media.go similarity index 98% rename from vendor/google.golang.org/api/gensupport/media.go rename to vendor/google.golang.org/api/internal/gensupport/media.go index 0ef96b3f102..0288cc30427 100644 --- a/vendor/google.golang.org/api/gensupport/media.go +++ b/vendor/google.golang.org/api/internal/gensupport/media.go @@ -290,6 +290,9 @@ func (mi *MediaInfo) UploadRequest(reqHeaders http.Header, body io.Reader) (newB fb := readerFunc(body) fm := readerFunc(media) combined, ctype := CombineBodyMedia(body, "application/json", media, mi.mType) + toCleanup := []io.Closer{ + combined, + } if fb != nil && fm != nil { getBody = func() (io.ReadCloser, error) { rb := ioutil.NopCloser(fb()) @@ -299,10 +302,16 @@ func (mi *MediaInfo) UploadRequest(reqHeaders http.Header, body io.Reader) (newB mimeBoundary = params["boundary"] } r, _ := combineBodyMedia(rb, "application/json", rm, mi.mType, mimeBoundary) + toCleanup = append(toCleanup, r) return r, nil } } - cleanup = func() { combined.Close() } + cleanup = func() { + for _, closer := range toCleanup { + _ = closer.Close() + } + + } reqHeaders.Set("Content-Type", ctype) body = combined } diff --git a/vendor/google.golang.org/api/gensupport/params.go b/vendor/google.golang.org/api/internal/gensupport/params.go similarity index 100% rename from vendor/google.golang.org/api/gensupport/params.go rename to vendor/google.golang.org/api/internal/gensupport/params.go diff --git a/vendor/google.golang.org/api/gensupport/resumable.go b/vendor/google.golang.org/api/internal/gensupport/resumable.go similarity index 88% rename from vendor/google.golang.org/api/gensupport/resumable.go rename to vendor/google.golang.org/api/internal/gensupport/resumable.go index e67ccd9a614..edc87ec24f6 100644 --- a/vendor/google.golang.org/api/gensupport/resumable.go +++ b/vendor/google.golang.org/api/internal/gensupport/resumable.go @@ -28,6 +28,8 @@ var ( backoff = func() Backoff { return &gax.Backoff{Initial: 100 * time.Millisecond} } + // isRetryable is a platform-specific hook, specified in retryable_linux.go + syscallRetryable func(error) bool = func(err error) bool { return false } ) const ( @@ -160,21 +162,6 @@ func (rx *ResumableUpload) transferChunk(ctx context.Context) (*http.Response, e // rx is private to the auto-generated API code. // Exactly one of resp or err will be nil. If resp is non-nil, the caller must call resp.Body.Close. func (rx *ResumableUpload) Upload(ctx context.Context) (resp *http.Response, err error) { - var shouldRetry = func(status int, err error) bool { - if 500 <= status && status <= 599 { - return true - } - if status == statusTooManyRequests { - return true - } - if err == io.ErrUnexpectedEOF { - return true - } - if err, ok := err.(interface{ Temporary() bool }); ok { - return err.Temporary() - } - return false - } // There are a couple of cases where it's possible for err and resp to both // be non-nil. However, we expose a simpler contract to our callers: exactly @@ -239,3 +226,33 @@ func (rx *ResumableUpload) Upload(ctx context.Context) (resp *http.Response, err return prepareReturn(resp, err) } } + +// shouldRetry indicates whether an error is retryable for the purposes of this +// package, following guidance from +// https://cloud.google.com/storage/docs/exponential-backoff . +func shouldRetry(status int, err error) bool { + if 500 <= status && status <= 599 { + return true + } + if status == statusTooManyRequests { + return true + } + if err == io.ErrUnexpectedEOF { + return true + } + // Transient network errors should be retried. + if syscallRetryable(err) { + return true + } + if err, ok := err.(interface{ Temporary() bool }); ok { + if err.Temporary() { + return true + } + } + // If Go 1.13 error unwrapping is available, use this to examine wrapped + // errors. + if err, ok := err.(interface{ Unwrap() error }); ok { + return shouldRetry(status, err.Unwrap()) + } + return false +} diff --git a/vendor/google.golang.org/api/internal/gensupport/retryable_linux.go b/vendor/google.golang.org/api/internal/gensupport/retryable_linux.go new file mode 100644 index 00000000000..fed998b5d07 --- /dev/null +++ b/vendor/google.golang.org/api/internal/gensupport/retryable_linux.go @@ -0,0 +1,15 @@ +// Copyright 2020 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build linux + +package gensupport + +import "syscall" + +func init() { + // Initialize syscallRetryable to return true on transient socket-level + // errors. These errors are specific to Linux. + syscallRetryable = func(err error) bool { return err == syscall.ECONNRESET || err == syscall.ECONNREFUSED } +} diff --git a/vendor/google.golang.org/api/internal/gensupport/send.go b/vendor/google.golang.org/api/internal/gensupport/send.go new file mode 100644 index 00000000000..3338c8d193a --- /dev/null +++ b/vendor/google.golang.org/api/internal/gensupport/send.go @@ -0,0 +1,172 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "time" +) + +// Hook is the type of a function that is called once before each HTTP request +// that is sent by a generated API. It returns a function that is called after +// the request returns. +// Hooks are not called if the context is nil. +type Hook func(ctx context.Context, req *http.Request) func(resp *http.Response) + +var hooks []Hook + +// RegisterHook registers a Hook to be called before each HTTP request by a +// generated API. Hooks are called in the order they are registered. Each +// hook can return a function; if it is non-nil, it is called after the HTTP +// request returns. These functions are called in the reverse order. +// RegisterHook should not be called concurrently with itself or SendRequest. +func RegisterHook(h Hook) { + hooks = append(hooks, h) +} + +// SendRequest sends a single HTTP request using the given client. +// If ctx is non-nil, it calls all hooks, then sends the request with +// req.WithContext, then calls any functions returned by the hooks in +// reverse order. +func SendRequest(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { + // Disallow Accept-Encoding because it interferes with the automatic gzip handling + // done by the default http.Transport. See https://github.com/google/google-api-go-client/issues/219. + if _, ok := req.Header["Accept-Encoding"]; ok { + return nil, errors.New("google api: custom Accept-Encoding headers not allowed") + } + if ctx == nil { + return client.Do(req) + } + // Call hooks in order of registration, store returned funcs. + post := make([]func(resp *http.Response), len(hooks)) + for i, h := range hooks { + fn := h(ctx, req) + post[i] = fn + } + + // Send request. + resp, err := send(ctx, client, req) + + // Call returned funcs in reverse order. + for i := len(post) - 1; i >= 0; i-- { + if fn := post[i]; fn != nil { + fn(resp) + } + } + return resp, err +} + +func send(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { + if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(req.WithContext(ctx)) + // If we got an error, and the context has been canceled, + // the context's error is probably more useful. + if err != nil { + select { + case <-ctx.Done(): + err = ctx.Err() + default: + } + } + return resp, err +} + +// SendRequestWithRetry sends a single HTTP request using the given client, +// with retries if a retryable error is returned. +// If ctx is non-nil, it calls all hooks, then sends the request with +// req.WithContext, then calls any functions returned by the hooks in +// reverse order. +func SendRequestWithRetry(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { + // Disallow Accept-Encoding because it interferes with the automatic gzip handling + // done by the default http.Transport. See https://github.com/google/google-api-go-client/issues/219. + if _, ok := req.Header["Accept-Encoding"]; ok { + return nil, errors.New("google api: custom Accept-Encoding headers not allowed") + } + if ctx == nil { + return client.Do(req) + } + // Call hooks in order of registration, store returned funcs. + post := make([]func(resp *http.Response), len(hooks)) + for i, h := range hooks { + fn := h(ctx, req) + post[i] = fn + } + + // Send request with retry. + resp, err := sendAndRetry(ctx, client, req) + + // Call returned funcs in reverse order. + for i := len(post) - 1; i >= 0; i-- { + if fn := post[i]; fn != nil { + fn(resp) + } + } + return resp, err +} + +func sendAndRetry(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { + if client == nil { + client = http.DefaultClient + } + + var resp *http.Response + var err error + + // Loop to retry the request, up to the context deadline. + var pause time.Duration + bo := backoff() + + for { + select { + case <-ctx.Done(): + // If we got an error, and the context has been canceled, + // the context's error is probably more useful. + if err == nil { + err = ctx.Err() + } + return resp, err + case <-time.After(pause): + } + + resp, err = client.Do(req.WithContext(ctx)) + + var status int + if resp != nil { + status = resp.StatusCode + } + + // Check if we can retry the request. A retry can only be done if the error + // is retryable and the request body can be re-created using GetBody (this + // will not be possible if the body was unbuffered). + if req.GetBody == nil || !shouldRetry(status, err) { + break + } + var errBody error + req.Body, errBody = req.GetBody() + if errBody != nil { + break + } + + pause = bo.Pause() + if resp != nil && resp.Body != nil { + resp.Body.Close() + } + } + return resp, err +} + +// DecodeResponse decodes the body of res into target. If there is no body, +// target is unchanged. +func DecodeResponse(target interface{}, res *http.Response) error { + if res.StatusCode == http.StatusNoContent { + return nil + } + return json.NewDecoder(res.Body).Decode(target) +} diff --git a/vendor/google.golang.org/api/internal/gensupport/version.go b/vendor/google.golang.org/api/internal/gensupport/version.go new file mode 100644 index 00000000000..23f6aa24eaf --- /dev/null +++ b/vendor/google.golang.org/api/internal/gensupport/version.go @@ -0,0 +1,53 @@ +// Copyright 2020 Google LLC. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gensupport + +import ( + "runtime" + "strings" + "unicode" +) + +// GoVersion returns the Go runtime version. The returned string +// has no whitespace. +func GoVersion() string { + return goVersion +} + +var goVersion = goVer(runtime.Version()) + +const develPrefix = "devel +" + +func goVer(s string) string { + if strings.HasPrefix(s, develPrefix) { + s = s[len(develPrefix):] + if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 { + s = s[:p] + } + return s + } + + if strings.HasPrefix(s, "go1") { + s = s[2:] + var prerelease string + if p := strings.IndexFunc(s, notSemverRune); p >= 0 { + s, prerelease = s[:p], s[p:] + } + if strings.HasSuffix(s, ".") { + s += "0" + } else if strings.Count(s, ".") < 2 { + s += ".0" + } + if prerelease != "" { + s += "-" + prerelease + } + return s + } + return "" +} + +func notSemverRune(r rune) bool { + return !strings.ContainsRune("0123456789.", r) +} diff --git a/vendor/google.golang.org/api/internal/pool.go b/vendor/google.golang.org/api/internal/pool.go deleted file mode 100644 index a4426dcb700..00000000000 --- a/vendor/google.golang.org/api/internal/pool.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2016 Google LLC -// -// 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 internal - -import ( - "errors" - - "google.golang.org/grpc/naming" -) - -// PoolResolver provides a fixed list of addresses to load balance between -// and does not provide further updates. -type PoolResolver struct { - poolSize int - dialOpt *DialSettings - ch chan []*naming.Update -} - -// NewPoolResolver returns a PoolResolver -// This is an EXPERIMENTAL API and may be changed or removed in the future. -func NewPoolResolver(size int, o *DialSettings) *PoolResolver { - return &PoolResolver{poolSize: size, dialOpt: o} -} - -// Resolve returns a Watcher for the endpoint defined by the DialSettings -// provided to NewPoolResolver. -func (r *PoolResolver) Resolve(target string) (naming.Watcher, error) { - if r.dialOpt.Endpoint == "" { - return nil, errors.New("no endpoint configured") - } - addrs := make([]*naming.Update, 0, r.poolSize) - for i := 0; i < r.poolSize; i++ { - addrs = append(addrs, &naming.Update{Op: naming.Add, Addr: r.dialOpt.Endpoint, Metadata: i}) - } - r.ch = make(chan []*naming.Update, 1) - r.ch <- addrs - return r, nil -} - -// Next returns a static list of updates on the first call, -// and blocks indefinitely until Close is called on subsequent calls. -func (r *PoolResolver) Next() ([]*naming.Update, error) { - return <-r.ch, nil -} - -// Close releases resources associated with the pool and causes Next to unblock. -func (r *PoolResolver) Close() { - close(r.ch) -} diff --git a/vendor/google.golang.org/api/internal/settings.go b/vendor/google.golang.org/api/internal/settings.go index 062301c65fd..f435519decf 100644 --- a/vendor/google.golang.org/api/internal/settings.go +++ b/vendor/google.golang.org/api/internal/settings.go @@ -1,21 +1,12 @@ -// Copyright 2017 Google LLC -// -// 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. +// Copyright 2017 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. // Package internal supports the options and transport packages. package internal import ( + "crypto/tls" "errors" "net/http" @@ -27,19 +18,26 @@ import ( // DialSettings holds information needed to establish a connection with a // Google API service. type DialSettings struct { - Endpoint string - Scopes []string - TokenSource oauth2.TokenSource - Credentials *google.Credentials - CredentialsFile string // if set, Token Source is ignored. - CredentialsJSON []byte - UserAgent string - APIKey string - Audiences []string - HTTPClient *http.Client - GRPCDialOpts []grpc.DialOption - GRPCConn *grpc.ClientConn - NoAuth bool + Endpoint string + DefaultEndpoint string + DefaultMTLSEndpoint string + Scopes []string + TokenSource oauth2.TokenSource + Credentials *google.Credentials + CredentialsFile string // if set, Token Source is ignored. + CredentialsJSON []byte + UserAgent string + APIKey string + Audiences []string + HTTPClient *http.Client + GRPCDialOpts []grpc.DialOption + GRPCConn *grpc.ClientConn + GRPCConnPool ConnPool + GRPCConnPoolSize int + NoAuth bool + TelemetryDisabled bool + ClientCertSource func(*tls.CertificateRequestInfo) (*tls.Certificate, error) + CustomClaims map[string]interface{} // Google API system parameters. For more information please read: // https://cloud.google.com/apis/docs/system-parameters @@ -79,6 +77,12 @@ func (ds *DialSettings) Validate() error { if nCreds > 1 && !(nCreds == 2 && ds.TokenSource != nil && ds.CredentialsFile != "") { return errors.New("multiple credential options provided") } + if ds.GRPCConn != nil && ds.GRPCConnPool != nil { + return errors.New("WithGRPCConn is incompatible with WithConnPool") + } + if ds.HTTPClient != nil && ds.GRPCConnPool != nil { + return errors.New("WithHTTPClient is incompatible with WithConnPool") + } if ds.HTTPClient != nil && ds.GRPCConn != nil { return errors.New("WithHTTPClient is incompatible with WithGRPCConn") } @@ -91,6 +95,12 @@ func (ds *DialSettings) Validate() error { if ds.HTTPClient != nil && ds.RequestReason != "" { return errors.New("WithHTTPClient is incompatible with RequestReason") } + if ds.HTTPClient != nil && ds.ClientCertSource != nil { + return errors.New("WithHTTPClient is incompatible with WithClientCertSource") + } + if ds.ClientCertSource != nil && (ds.GRPCConn != nil || ds.GRPCConnPool != nil || ds.GRPCConnPoolSize != 0 || ds.GRPCDialOpts != nil) { + return errors.New("WithClientCertSource is currently only supported for HTTP. gRPC settings are incompatible") + } return nil } diff --git a/vendor/google.golang.org/api/internal/third_party/uritemplates/LICENSE b/vendor/google.golang.org/api/internal/third_party/uritemplates/LICENSE new file mode 100644 index 00000000000..7109c6ef932 --- /dev/null +++ b/vendor/google.golang.org/api/internal/third_party/uritemplates/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2013 Joshua Tacoma. 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/google.golang.org/api/internal/third_party/uritemplates/METADATA b/vendor/google.golang.org/api/internal/third_party/uritemplates/METADATA new file mode 100644 index 00000000000..c7f86fcd5fd --- /dev/null +++ b/vendor/google.golang.org/api/internal/third_party/uritemplates/METADATA @@ -0,0 +1,14 @@ +name: "uritemplates" +description: + "Package uritemplates is a level 4 implementation of RFC 6570 (URI " + "Template, http://tools.ietf.org/html/rfc6570)." + +third_party { + url { + type: GIT + value: "https://github.com/jtacoma/uritemplates" + } + version: "0.1" + last_upgrade_date { year: 2014 month: 8 day: 18 } + license_type: NOTICE +} diff --git a/vendor/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go b/vendor/google.golang.org/api/internal/third_party/uritemplates/uritemplates.go similarity index 98% rename from vendor/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go rename to vendor/google.golang.org/api/internal/third_party/uritemplates/uritemplates.go index 63bf0538301..8c27d19d752 100644 --- a/vendor/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go +++ b/vendor/google.golang.org/api/internal/third_party/uritemplates/uritemplates.go @@ -191,7 +191,7 @@ func parseTerm(term string) (result templateTerm, err error) { err = errors.New("not a valid name: " + result.name) } if result.explode && result.truncate > 0 { - err = errors.New("both explode and prefix modifers on same term") + err = errors.New("both explode and prefix modifiers on same term") } return result, err } diff --git a/vendor/google.golang.org/api/googleapi/internal/uritemplates/utils.go b/vendor/google.golang.org/api/internal/third_party/uritemplates/utils.go similarity index 100% rename from vendor/google.golang.org/api/googleapi/internal/uritemplates/utils.go rename to vendor/google.golang.org/api/internal/third_party/uritemplates/utils.go diff --git a/vendor/google.golang.org/api/iterator/iterator.go b/vendor/google.golang.org/api/iterator/iterator.go index 3c8ea7732af..1799b5d9af5 100644 --- a/vendor/google.golang.org/api/iterator/iterator.go +++ b/vendor/google.golang.org/api/iterator/iterator.go @@ -1,16 +1,6 @@ -// Copyright 2016 Google LLC -// -// 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. +// Copyright 2016 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. // Package iterator provides support for standard Google API iterators. // See https://github.com/GoogleCloudPlatform/gcloud-golang/wiki/Iterator-Guidelines. @@ -82,17 +72,23 @@ type PageInfo struct { // It is not a stable interface. var NewPageInfo = newPageInfo -// If an iterator can support paging, its iterator-creating method should call -// this (via the NewPageInfo variable above). +// newPageInfo creates and returns a PageInfo and a next func. If an iterator can +// support paging, its iterator-creating method should call this. Each time the +// iterator's Next is called, it should call the returned next fn to determine +// whether a next item exists, and if so it should pop an item from the buffer. // -// The fetch, bufLen and takeBuf arguments provide access to the -// iterator's internal slice of buffered items. They behave as described in -// PageInfo, above. +// The fetch, bufLen and takeBuf arguments provide access to the iterator's +// internal slice of buffered items. They behave as described in PageInfo, above. // // The return value is the PageInfo.next method bound to the returned PageInfo value. // (Returning it avoids exporting PageInfo.next.) -func newPageInfo(fetch func(int, string) (string, error), bufLen func() int, takeBuf func() interface{}) (*PageInfo, func() error) { - pi := &PageInfo{ +// +// Note: the returned PageInfo and next fn do not remove items from the buffer. +// It is up to the iterator using these to remove items from the buffer: +// typically by performing a pop in its Next. If items are not removed from the +// buffer, memory may grow unbounded. +func newPageInfo(fetch func(int, string) (string, error), bufLen func() int, takeBuf func() interface{}) (pi *PageInfo, next func() error) { + pi = &PageInfo{ fetch: fetch, bufLen: bufLen, takeBuf: takeBuf, diff --git a/vendor/google.golang.org/api/option/credentials_go19.go b/vendor/google.golang.org/api/option/credentials_go19.go index 0636a829454..d06f918b0e6 100644 --- a/vendor/google.golang.org/api/option/credentials_go19.go +++ b/vendor/google.golang.org/api/option/credentials_go19.go @@ -1,16 +1,6 @@ -// Copyright 2018 Google LLC -// -// 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. +// Copyright 2018 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. // +build go1.9 diff --git a/vendor/google.golang.org/api/option/credentials_notgo19.go b/vendor/google.golang.org/api/option/credentials_notgo19.go index 74d3a4b5b91..0ce107a624a 100644 --- a/vendor/google.golang.org/api/option/credentials_notgo19.go +++ b/vendor/google.golang.org/api/option/credentials_notgo19.go @@ -1,16 +1,6 @@ -// Copyright 2018 Google LLC -// -// 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. +// Copyright 2018 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. // +build !go1.9 diff --git a/vendor/google.golang.org/api/option/internaloption/internaloption.go b/vendor/google.golang.org/api/option/internaloption/internaloption.go new file mode 100644 index 00000000000..ff5b530cfe0 --- /dev/null +++ b/vendor/google.golang.org/api/option/internaloption/internaloption.go @@ -0,0 +1,40 @@ +// Copyright 2020 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package internaloption contains options used internally by Google client code. +package internaloption + +import ( + "google.golang.org/api/internal" + "google.golang.org/api/option" +) + +type defaultEndpointOption string + +func (o defaultEndpointOption) Apply(settings *internal.DialSettings) { + settings.DefaultEndpoint = string(o) +} + +// WithDefaultEndpoint is an option that indicates the default endpoint. +// +// It should only be used internally by generated clients. +// +// This is similar to WithEndpoint, but allows us to determine whether the user has overriden the default endpoint. +func WithDefaultEndpoint(url string) option.ClientOption { + return defaultEndpointOption(url) +} + +type defaultMTLSEndpointOption string + +func (o defaultMTLSEndpointOption) Apply(settings *internal.DialSettings) { + settings.DefaultMTLSEndpoint = string(o) +} + +// WithDefaultMTLSEndpoint is an option that indicates the default mTLS endpoint. +// +// It should only be used internally by generated clients. +// +func WithDefaultMTLSEndpoint(url string) option.ClientOption { + return defaultMTLSEndpointOption(url) +} diff --git a/vendor/google.golang.org/api/option/option.go b/vendor/google.golang.org/api/option/option.go index 0a1c2dba9e3..b7c40d60a45 100644 --- a/vendor/google.golang.org/api/option/option.go +++ b/vendor/google.golang.org/api/option/option.go @@ -1,21 +1,12 @@ -// Copyright 2017 Google LLC -// -// 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. +// Copyright 2017 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. // Package option contains options for Google API clients. package option import ( + "crypto/tls" "net/http" "golang.org/x/oauth2" @@ -124,7 +115,7 @@ func (w withHTTPClient) Apply(o *internal.DialSettings) { } // WithGRPCConn returns a ClientOption that specifies the gRPC client -// connection to use as the basis of communications. This option many only be +// connection to use as the basis of communications. This option may only be // used with services that support gRPC as their communication transport. When // used, the WithGRPCConn option takes precedent over all other supplied // options. @@ -152,6 +143,7 @@ func (w withGRPCDialOption) Apply(o *internal.DialSettings) { // WithGRPCConnectionPool returns a ClientOption that creates a pool of gRPC // connections that requests will be balanced between. +// // This is an EXPERIMENTAL API and may be changed or removed in the future. func WithGRPCConnectionPool(size int) ClientOption { return withGRPCConnectionPool(size) @@ -160,8 +152,7 @@ func WithGRPCConnectionPool(size int) ClientOption { type withGRPCConnectionPool int func (w withGRPCConnectionPool) Apply(o *internal.DialSettings) { - balancer := grpc.RoundRobin(internal.NewPoolResolver(int(w), o)) - o.GRPCDialOpts = append(o.GRPCDialOpts, grpc.WithBalancer(balancer)) + o.GRPCConnPoolSize = int(w) } // WithAPIKey returns a ClientOption that specifies an API key to be used @@ -233,3 +224,48 @@ type withRequestReason string func (w withRequestReason) Apply(o *internal.DialSettings) { o.RequestReason = string(w) } + +// WithTelemetryDisabled returns a ClientOption that disables default telemetry (OpenCensus) +// settings on gRPC and HTTP clients. +// An example reason would be to bind custom telemetry that overrides the defaults. +func WithTelemetryDisabled() ClientOption { + return withTelemetryDisabled{} +} + +type withTelemetryDisabled struct{} + +func (w withTelemetryDisabled) Apply(o *internal.DialSettings) { + o.TelemetryDisabled = true +} + +// ClientCertSource is a function that returns a TLS client certificate to be used +// when opening TLS connections. +// +// It follows the same semantics as crypto/tls.Config.GetClientCertificate. +// +// This is an EXPERIMENTAL API and may be changed or removed in the future. +type ClientCertSource = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) + +// WithClientCertSource returns a ClientOption that specifies a +// callback function for obtaining a TLS client certificate. +// +// This option is used for supporting mTLS authentication, where the +// server validates the client certifcate when establishing a connection. +// +// The callback function will be invoked whenever the server requests a +// certificate from the client. Implementations of the callback function +// should try to ensure that a valid certificate can be repeatedly returned +// on demand for the entire life cycle of the transport client. If a nil +// Certificate is returned (i.e. no Certificate can be obtained), an error +// should be returned. +// +// This is an EXPERIMENTAL API and may be changed or removed in the future. +func WithClientCertSource(s ClientCertSource) ClientOption { + return withClientCertSource{s} +} + +type withClientCertSource struct{ s ClientCertSource } + +func (w withClientCertSource) Apply(o *internal.DialSettings) { + o.ClientCertSource = w.s +} diff --git a/vendor/google.golang.org/api/storage/v1/storage-api.json b/vendor/google.golang.org/api/storage/v1/storage-api.json index 2a0d2746f1d..e78776b2be8 100644 --- a/vendor/google.golang.org/api/storage/v1/storage-api.json +++ b/vendor/google.golang.org/api/storage/v1/storage-api.json @@ -21,12 +21,12 @@ } }, "basePath": "/storage/v1/", - "baseUrl": "https://www.googleapis.com/storage/v1/", + "baseUrl": "https://storage.googleapis.com/storage/v1/", "batchPath": "batch/storage/v1", "description": "Stores and retrieves potentially large, immutable data objects.", "discoveryVersion": "v1", "documentationLink": "https://developers.google.com/storage/docs/json_api/", - "etag": "\"9eZ1uxVRThTDhLJCZHhqs3eQWz4/m18VxIxuaQHJN-C1B3-yQYvta24\"", + "etag": "\"u9GIe6H63LSGq-9_t39K2Zx_EAc/5Ir-e9ddNPcr5skzvRsSnJlvTYg\"", "icons": { "x16": "https://www.google.com/images/icons/product/cloud_storage-16.png", "x32": "https://www.google.com/images/icons/product/cloud_storage-32.png" @@ -450,6 +450,13 @@ "required": true, "type": "string" }, + "optionsRequestedPolicyVersion": { + "description": "The IAM policy format version to be returned. If the optionsRequestedPolicyVersion is for an older version that doesn't support part of the requested IAM policy, the request fails.", + "format": "int32", + "location": "query", + "minimum": "1", + "type": "integer" + }, "provisionalUserProject": { "description": "The project to be billed for this request if the target bucket is requester-pays bucket.", "location": "query", @@ -1774,7 +1781,7 @@ "type": "string" }, "kmsKeyName": { - "description": "Resource name of the Cloud KMS key, of the form projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key, that will be used to encrypt the object. Overrides the object metadata's kms_key_name value, if any.", + "description": "Not currently supported. Specifying the parameter causes the request to fail with status code 400 - Bad Request.", "location": "query", "type": "string" }, @@ -1819,6 +1826,11 @@ "required": true, "type": "string" }, + "destinationKmsKeyName": { + "description": "Resource name of the Cloud KMS key, of the form projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key, that will be used to encrypt the object. Overrides the object metadata's kms_key_name value, if any.", + "location": "query", + "type": "string" + }, "destinationObject": { "description": "Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any.", "location": "path", @@ -2303,6 +2315,11 @@ "location": "query", "type": "string" }, + "endOffset": { + "description": "Filter results to objects whose names are lexicographically before endOffset. If startOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).", + "location": "query", + "type": "string" + }, "includeTrailingDelimiter": { "description": "If true, objects that end in exactly one instance of delimiter will have their metadata included in items in addition to prefixes.", "location": "query", @@ -2344,6 +2361,11 @@ "location": "query", "type": "string" }, + "startOffset": { + "description": "Filter results to objects whose names are lexicographically equal to or after startOffset. If endOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).", + "location": "query", + "type": "string" + }, "userProject": { "description": "The project to be billed for this request. Required for Requester Pays buckets.", "location": "query", @@ -2875,6 +2897,11 @@ "location": "query", "type": "string" }, + "endOffset": { + "description": "Filter results to objects whose names are lexicographically before endOffset. If startOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).", + "location": "query", + "type": "string" + }, "includeTrailingDelimiter": { "description": "If true, objects that end in exactly one instance of delimiter will have their metadata included in items in addition to prefixes.", "location": "query", @@ -2916,6 +2943,11 @@ "location": "query", "type": "string" }, + "startOffset": { + "description": "Filter results to objects whose names are lexicographically equal to or after startOffset. If endOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).", + "location": "query", + "type": "string" + }, "userProject": { "description": "The project to be billed for this request. Required for Requester Pays buckets.", "location": "query", @@ -3054,6 +3086,7 @@ "scopes": [ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", + "https://www.googleapis.com/auth/devstorage.full_control", "https://www.googleapis.com/auth/devstorage.read_only" ] }, @@ -3196,8 +3229,8 @@ } } }, - "revision": "20190624", - "rootUrl": "https://www.googleapis.com/", + "revision": "20200611", + "rootUrl": "https://storage.googleapis.com/", "schemas": { "Bucket": { "description": "A bucket.", @@ -3289,7 +3322,7 @@ "description": "The bucket's IAM configuration.", "properties": { "bucketPolicyOnly": { - "description": "The bucket's Bucket Policy Only configuration.", + "description": "The bucket's uniform bucket-level access configuration. The feature was formerly known as Bucket Policy Only. For backward compatibility, this field will be populated with identical information as the uniformBucketLevelAccess field. We recommend using the uniformBucketLevelAccess field to enable and disable the feature.", "properties": { "enabled": { "description": "If set, access is controlled only by bucket-level or above IAM policies.", @@ -3372,6 +3405,21 @@ "format": "date", "type": "string" }, + "customTimeBefore": { + "description": "A timestamp in RFC 3339 format. This condition is satisfied when the custom time on an object is before this timestamp.", + "format": "date-time", + "type": "string" + }, + "daysSinceCustomTime": { + "description": "Number of days elapsed since the user-specified timestamp set on an object. The condition is satisfied if the days elapsed is at least this number. If no custom timestamp is specified on an object, the condition does not apply.", + "format": "int32", + "type": "integer" + }, + "daysSinceNoncurrentTime": { + "description": "Number of days elapsed since the noncurrent timestamp of an object. The condition is satisfied if the days elapsed is at least this number. This condition is relevant only for versioned objects. The value of the field must be a nonnegative integer. If it's zero, the object version will become eligible for Lifecycle action as soon as it becomes noncurrent.", + "format": "int32", + "type": "integer" + }, "isLive": { "description": "Relevant only for versioned objects. If the value is true, this condition matches live objects; if the value is false, it matches archived objects.", "type": "boolean" @@ -3381,12 +3429,17 @@ "type": "string" }, "matchesStorageClass": { - "description": "Objects having any of the storage classes specified by this condition will be matched. Values include MULTI_REGIONAL, REGIONAL, NEARLINE, COLDLINE, STANDARD, and DURABLE_REDUCED_AVAILABILITY.", + "description": "Objects having any of the storage classes specified by this condition will be matched. Values include MULTI_REGIONAL, REGIONAL, NEARLINE, COLDLINE, ARCHIVE, STANDARD, and DURABLE_REDUCED_AVAILABILITY.", "items": { "type": "string" }, "type": "array" }, + "noncurrentTimeBefore": { + "description": "A timestamp in RFC 3339 format. This condition is satisfied when the noncurrent time on an object is before this timestamp. This condition is relevant only for versioned objects.", + "format": "date-time", + "type": "string" + }, "numNewerVersions": { "description": "Relevant only for versioned objects. If the value is N, this condition is satisfied when there are at least N versions (including the live version) newer than this version of the object.", "format": "int32", @@ -3483,7 +3536,7 @@ "type": "string" }, "storageClass": { - "description": "The bucket's default storage class, used whenever no storageClass is specified for a newly-created object. This defines how objects in the bucket are stored and determines the SLA and the cost of storage. Values include MULTI_REGIONAL, REGIONAL, STANDARD, NEARLINE, COLDLINE, and DURABLE_REDUCED_AVAILABILITY. If this value is not specified when the bucket is created, it will default to STANDARD. For more information, see storage classes.", + "description": "The bucket's default storage class, used whenever no storageClass is specified for a newly-created object. This defines how objects in the bucket are stored and determines the SLA and the cost of storage. Values include MULTI_REGIONAL, REGIONAL, STANDARD, NEARLINE, COLDLINE, ARCHIVE, and DURABLE_REDUCED_AVAILABILITY. If this value is not specified when the bucket is created, it will default to STANDARD. For more information, see storage classes.", "type": "string" }, "timeCreated": { @@ -3519,6 +3572,17 @@ } }, "type": "object" + }, + "zoneAffinity": { + "description": "The zone or zones from which the bucket is intended to use zonal quota. Requests for data from outside the specified affinities are still allowed but won't be able to use zonal quota. The zone or zones need to be within the bucket location otherwise the requests will fail with a 400 Bad Request response.", + "items": { + "type": "string" + }, + "type": "array" + }, + "zoneSeparation": { + "description": "If set, objects placed in this bucket are required to be separated by disaster domain.", + "type": "boolean" } }, "type": "object" @@ -3990,6 +4054,11 @@ "description": "CRC32c checksum, as described in RFC 4960, Appendix B; encoded using base64 in big-endian byte order. For more information about using the CRC32c checksum, see Hashes and ETags: Best Practices.", "type": "string" }, + "customTime": { + "description": "A timestamp in RFC 3339 format specified by the user for an object.", + "format": "date-time", + "type": "string" + }, "customerEncryption": { "description": "Metadata of customer-supplied encryption key, if the object is encrypted by such a key.", "properties": { @@ -4305,6 +4374,11 @@ "resourceId": { "description": "The ID of the resource to which this policy belongs. Will be of the form projects/_/buckets/bucket for buckets, and projects/_/buckets/bucket/objects/object for objects. A specific generation may be specified by appending #generationNumber to the end of the object name, e.g. projects/_/buckets/my-bucket/objects/data.txt#17. The current generation can be denoted with #0. This field is ignored on input.", "type": "string" + }, + "version": { + "description": "The IAM policy format version.", + "format": "int32", + "type": "integer" } }, "type": "object" diff --git a/vendor/google.golang.org/api/storage/v1/storage-gen.go b/vendor/google.golang.org/api/storage/v1/storage-gen.go index 2eff67418c5..dc51a22ede6 100644 --- a/vendor/google.golang.org/api/storage/v1/storage-gen.go +++ b/vendor/google.golang.org/api/storage/v1/storage-gen.go @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC. +// Copyright 2020 Google LLC. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. @@ -55,9 +55,10 @@ import ( "strconv" "strings" - gensupport "google.golang.org/api/gensupport" googleapi "google.golang.org/api/googleapi" + gensupport "google.golang.org/api/internal/gensupport" option "google.golang.org/api/option" + internaloption "google.golang.org/api/option/internaloption" htransport "google.golang.org/api/transport/http" ) @@ -74,11 +75,12 @@ var _ = googleapi.Version var _ = errors.New var _ = strings.Replace var _ = context.Canceled +var _ = internaloption.WithDefaultEndpoint const apiId = "storage:v1" const apiName = "storage" const apiVersion = "v1" -const basePath = "https://www.googleapis.com/storage/v1/" +const basePath = "https://storage.googleapis.com/storage/v1/" // OAuth2 scopes used by this API. const ( @@ -109,6 +111,7 @@ func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, err ) // NOTE: prepend, so we don't override user-specified scopes. opts = append([]option.ClientOption{scopesOption}, opts...) + opts = append(opts, internaloption.WithDefaultEndpoint(basePath)) client, endpoint, err := htransport.NewClient(ctx, opts...) if err != nil { return nil, err @@ -371,9 +374,9 @@ type Bucket struct { // storageClass is specified for a newly-created object. This defines // how objects in the bucket are stored and determines the SLA and the // cost of storage. Values include MULTI_REGIONAL, REGIONAL, STANDARD, - // NEARLINE, COLDLINE, and DURABLE_REDUCED_AVAILABILITY. If this value - // is not specified when the bucket is created, it will default to - // STANDARD. For more information, see storage classes. + // NEARLINE, COLDLINE, ARCHIVE, and DURABLE_REDUCED_AVAILABILITY. If + // this value is not specified when the bucket is created, it will + // default to STANDARD. For more information, see storage classes. StorageClass string `json:"storageClass,omitempty"` // TimeCreated: The creation time of the bucket in RFC 3339 format. @@ -390,6 +393,17 @@ type Bucket struct { // Static Website Examples for more information. Website *BucketWebsite `json:"website,omitempty"` + // ZoneAffinity: The zone or zones from which the bucket is intended to + // use zonal quota. Requests for data from outside the specified + // affinities are still allowed but won't be able to use zonal quota. + // The zone or zones need to be within the bucket location otherwise the + // requests will fail with a 400 Bad Request response. + ZoneAffinity []string `json:"zoneAffinity,omitempty"` + + // ZoneSeparation: If set, objects placed in this bucket are required to + // be separated by disaster domain. + ZoneSeparation bool `json:"zoneSeparation,omitempty"` + // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` @@ -522,7 +536,12 @@ func (s *BucketEncryption) MarshalJSON() ([]byte, error) { // BucketIamConfiguration: The bucket's IAM configuration. type BucketIamConfiguration struct { - // BucketPolicyOnly: The bucket's Bucket Policy Only configuration. + // BucketPolicyOnly: The bucket's uniform bucket-level access + // configuration. The feature was formerly known as Bucket Policy Only. + // For backward compatibility, this field will be populated with + // identical information as the uniformBucketLevelAccess field. We + // recommend using the uniformBucketLevelAccess field to enable and + // disable the feature. BucketPolicyOnly *BucketIamConfigurationBucketPolicyOnly `json:"bucketPolicyOnly,omitempty"` // UniformBucketLevelAccess: The bucket's uniform bucket-level access @@ -553,8 +572,12 @@ func (s *BucketIamConfiguration) MarshalJSON() ([]byte, error) { return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } -// BucketIamConfigurationBucketPolicyOnly: The bucket's Bucket Policy -// Only configuration. +// BucketIamConfigurationBucketPolicyOnly: The bucket's uniform +// bucket-level access configuration. The feature was formerly known as +// Bucket Policy Only. For backward compatibility, this field will be +// populated with identical information as the uniformBucketLevelAccess +// field. We recommend using the uniformBucketLevelAccess field to +// enable and disable the feature. type BucketIamConfigurationBucketPolicyOnly struct { // Enabled: If set, access is controlled only by bucket-level or above // IAM policies. @@ -733,6 +756,24 @@ type BucketLifecycleRuleCondition struct { // is created before midnight of the specified date in UTC. CreatedBefore string `json:"createdBefore,omitempty"` + // CustomTimeBefore: A timestamp in RFC 3339 format. This condition is + // satisfied when the custom time on an object is before this timestamp. + CustomTimeBefore string `json:"customTimeBefore,omitempty"` + + // DaysSinceCustomTime: Number of days elapsed since the user-specified + // timestamp set on an object. The condition is satisfied if the days + // elapsed is at least this number. If no custom timestamp is specified + // on an object, the condition does not apply. + DaysSinceCustomTime int64 `json:"daysSinceCustomTime,omitempty"` + + // DaysSinceNoncurrentTime: Number of days elapsed since the noncurrent + // timestamp of an object. The condition is satisfied if the days + // elapsed is at least this number. This condition is relevant only for + // versioned objects. The value of the field must be a nonnegative + // integer. If it's zero, the object version will become eligible for + // Lifecycle action as soon as it becomes noncurrent. + DaysSinceNoncurrentTime int64 `json:"daysSinceNoncurrentTime,omitempty"` + // IsLive: Relevant only for versioned objects. If the value is true, // this condition matches live objects; if the value is false, it // matches archived objects. @@ -748,10 +789,15 @@ type BucketLifecycleRuleCondition struct { // MatchesStorageClass: Objects having any of the storage classes // specified by this condition will be matched. Values include - // MULTI_REGIONAL, REGIONAL, NEARLINE, COLDLINE, STANDARD, and + // MULTI_REGIONAL, REGIONAL, NEARLINE, COLDLINE, ARCHIVE, STANDARD, and // DURABLE_REDUCED_AVAILABILITY. MatchesStorageClass []string `json:"matchesStorageClass,omitempty"` + // NoncurrentTimeBefore: A timestamp in RFC 3339 format. This condition + // is satisfied when the noncurrent time on an object is before this + // timestamp. This condition is relevant only for versioned objects. + NoncurrentTimeBefore string `json:"noncurrentTimeBefore,omitempty"` + // NumNewerVersions: Relevant only for versioned objects. If the value // is N, this condition is satisfied when there are at least N versions // (including the live version) newer than this version of the object. @@ -1650,6 +1696,10 @@ type Object struct { // Practices. Crc32c string `json:"crc32c,omitempty"` + // CustomTime: A timestamp in RFC 3339 format specified by the user for + // an object. + CustomTime string `json:"customTime,omitempty"` + // CustomerEncryption: Metadata of customer-supplied encryption key, if // the object is encrypted by such a key. CustomerEncryption *ObjectCustomerEncryption `json:"customerEncryption,omitempty"` @@ -2068,6 +2118,9 @@ type Policy struct { // generation can be denoted with #0. This field is ignored on input. ResourceId string `json:"resourceId,omitempty"` + // Version: The IAM policy format version. + Version int64 `json:"version,omitempty"` + // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` @@ -2389,7 +2442,7 @@ func (c *BucketAccessControlsDeleteCall) Header() http.Header { func (c *BucketAccessControlsDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -2537,7 +2590,7 @@ func (c *BucketAccessControlsGetCall) Header() http.Header { func (c *BucketAccessControlsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -2704,7 +2757,7 @@ func (c *BucketAccessControlsInsertCall) Header() http.Header { func (c *BucketAccessControlsInsertCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -2877,7 +2930,7 @@ func (c *BucketAccessControlsListCall) Header() http.Header { func (c *BucketAccessControlsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -3038,7 +3091,7 @@ func (c *BucketAccessControlsPatchCall) Header() http.Header { func (c *BucketAccessControlsPatchCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -3212,7 +3265,7 @@ func (c *BucketAccessControlsUpdateCall) Header() http.Header { func (c *BucketAccessControlsUpdateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -3398,7 +3451,7 @@ func (c *BucketsDeleteCall) Header() http.Header { func (c *BucketsDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -3577,7 +3630,7 @@ func (c *BucketsGetCall) Header() http.Header { func (c *BucketsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -3721,6 +3774,16 @@ func (r *BucketsService) GetIamPolicy(bucket string) *BucketsGetIamPolicyCall { return c } +// OptionsRequestedPolicyVersion sets the optional parameter +// "optionsRequestedPolicyVersion": The IAM policy format version to be +// returned. If the optionsRequestedPolicyVersion is for an older +// version that doesn't support part of the requested IAM policy, the +// request fails. +func (c *BucketsGetIamPolicyCall) OptionsRequestedPolicyVersion(optionsRequestedPolicyVersion int64) *BucketsGetIamPolicyCall { + c.urlParams_.Set("optionsRequestedPolicyVersion", fmt.Sprint(optionsRequestedPolicyVersion)) + return c +} + // ProvisionalUserProject sets the optional parameter // "provisionalUserProject": The project to be billed for this request // if the target bucket is requester-pays bucket. @@ -3773,7 +3836,7 @@ func (c *BucketsGetIamPolicyCall) Header() http.Header { func (c *BucketsGetIamPolicyCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -3848,6 +3911,13 @@ func (c *BucketsGetIamPolicyCall) Do(opts ...googleapi.CallOption) (*Policy, err // "required": true, // "type": "string" // }, + // "optionsRequestedPolicyVersion": { + // "description": "The IAM policy format version to be returned. If the optionsRequestedPolicyVersion is for an older version that doesn't support part of the requested IAM policy, the request fails.", + // "format": "int32", + // "location": "query", + // "minimum": "1", + // "type": "integer" + // }, // "provisionalUserProject": { // "description": "The project to be billed for this request if the target bucket is requester-pays bucket.", // "location": "query", @@ -3983,7 +4053,7 @@ func (c *BucketsInsertCall) Header() http.Header { func (c *BucketsInsertCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -4240,7 +4310,7 @@ func (c *BucketsListCall) Header() http.Header { func (c *BucketsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -4450,7 +4520,7 @@ func (c *BucketsLockRetentionPolicyCall) Header() http.Header { func (c *BucketsLockRetentionPolicyCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -4685,7 +4755,7 @@ func (c *BucketsPatchCall) Header() http.Header { func (c *BucketsPatchCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -4914,7 +4984,7 @@ func (c *BucketsSetIamPolicyCall) Header() http.Header { func (c *BucketsSetIamPolicyCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -5089,7 +5159,7 @@ func (c *BucketsTestIamPermissionsCall) Header() http.Header { func (c *BucketsTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -5329,7 +5399,7 @@ func (c *BucketsUpdateCall) Header() http.Header { func (c *BucketsUpdateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -5541,7 +5611,7 @@ func (c *ChannelsStopCall) Header() http.Header { func (c *ChannelsStopCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -5658,7 +5728,7 @@ func (c *DefaultObjectAccessControlsDeleteCall) Header() http.Header { func (c *DefaultObjectAccessControlsDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -5806,7 +5876,7 @@ func (c *DefaultObjectAccessControlsGetCall) Header() http.Header { func (c *DefaultObjectAccessControlsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -5974,7 +6044,7 @@ func (c *DefaultObjectAccessControlsInsertCall) Header() http.Header { func (c *DefaultObjectAccessControlsInsertCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -6164,7 +6234,7 @@ func (c *DefaultObjectAccessControlsListCall) Header() http.Header { func (c *DefaultObjectAccessControlsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -6337,7 +6407,7 @@ func (c *DefaultObjectAccessControlsPatchCall) Header() http.Header { func (c *DefaultObjectAccessControlsPatchCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -6511,7 +6581,7 @@ func (c *DefaultObjectAccessControlsUpdateCall) Header() http.Header { func (c *DefaultObjectAccessControlsUpdateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -6683,7 +6753,7 @@ func (c *NotificationsDeleteCall) Header() http.Header { func (c *NotificationsDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -6831,7 +6901,7 @@ func (c *NotificationsGetCall) Header() http.Header { func (c *NotificationsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -7001,7 +7071,7 @@ func (c *NotificationsInsertCall) Header() http.Header { func (c *NotificationsInsertCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -7176,7 +7246,7 @@ func (c *NotificationsListCall) Header() http.Header { func (c *NotificationsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -7349,7 +7419,7 @@ func (c *ObjectAccessControlsDeleteCall) Header() http.Header { func (c *ObjectAccessControlsDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -7521,7 +7591,7 @@ func (c *ObjectAccessControlsGetCall) Header() http.Header { func (c *ObjectAccessControlsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -7712,7 +7782,7 @@ func (c *ObjectAccessControlsInsertCall) Header() http.Header { func (c *ObjectAccessControlsInsertCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -7909,7 +7979,7 @@ func (c *ObjectAccessControlsListCall) Header() http.Header { func (c *ObjectAccessControlsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -8094,7 +8164,7 @@ func (c *ObjectAccessControlsPatchCall) Header() http.Header { func (c *ObjectAccessControlsPatchCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -8292,7 +8362,7 @@ func (c *ObjectAccessControlsUpdateCall) Header() http.Header { func (c *ObjectAccessControlsUpdateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -8477,11 +8547,9 @@ func (c *ObjectsComposeCall) IfMetagenerationMatch(ifMetagenerationMatch int64) return c } -// KmsKeyName sets the optional parameter "kmsKeyName": Resource name of -// the Cloud KMS key, of the form -// projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key, -// that will be used to encrypt the object. Overrides the object -// metadata's kms_key_name value, if any. +// KmsKeyName sets the optional parameter "kmsKeyName": Not currently +// supported. Specifying the parameter causes the request to fail with +// status code 400 - Bad Request. func (c *ObjectsComposeCall) KmsKeyName(kmsKeyName string) *ObjectsComposeCall { c.urlParams_.Set("kmsKeyName", kmsKeyName) return c @@ -8529,7 +8597,7 @@ func (c *ObjectsComposeCall) Header() http.Header { func (c *ObjectsComposeCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -8648,7 +8716,7 @@ func (c *ObjectsComposeCall) Do(opts ...googleapi.CallOption) (*Object, error) { // "type": "string" // }, // "kmsKeyName": { - // "description": "Resource name of the Cloud KMS key, of the form projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key, that will be used to encrypt the object. Overrides the object metadata's kms_key_name value, if any.", + // "description": "Not currently supported. Specifying the parameter causes the request to fail with status code 400 - Bad Request.", // "location": "query", // "type": "string" // }, @@ -8705,6 +8773,17 @@ func (r *ObjectsService) Copy(sourceBucket string, sourceObject string, destinat return c } +// DestinationKmsKeyName sets the optional parameter +// "destinationKmsKeyName": Resource name of the Cloud KMS key, of the +// form +// projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key, +// that will be used to encrypt the object. Overrides the object +// metadata's kms_key_name value, if any. +func (c *ObjectsCopyCall) DestinationKmsKeyName(destinationKmsKeyName string) *ObjectsCopyCall { + c.urlParams_.Set("destinationKmsKeyName", destinationKmsKeyName) + return c +} + // DestinationPredefinedAcl sets the optional parameter // "destinationPredefinedAcl": Apply a predefined set of access controls // to the destination object. @@ -8861,7 +8940,7 @@ func (c *ObjectsCopyCall) Header() http.Header { func (c *ObjectsCopyCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -8944,6 +9023,11 @@ func (c *ObjectsCopyCall) Do(opts ...googleapi.CallOption) (*Object, error) { // "required": true, // "type": "string" // }, + // "destinationKmsKeyName": { + // "description": "Resource name of the Cloud KMS key, of the form projects/my-project/locations/global/keyRings/my-kr/cryptoKeys/my-key, that will be used to encrypt the object. Overrides the object metadata's kms_key_name value, if any.", + // "location": "query", + // "type": "string" + // }, // "destinationObject": { // "description": "Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any.", // "location": "path", @@ -9184,7 +9268,7 @@ func (c *ObjectsDeleteCall) Header() http.Header { func (c *ObjectsDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -9417,7 +9501,7 @@ func (c *ObjectsGetCall) Header() http.Header { func (c *ObjectsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -9667,7 +9751,7 @@ func (c *ObjectsGetIamPolicyCall) Header() http.Header { func (c *ObjectsGetIamPolicyCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -9984,7 +10068,7 @@ func (c *ObjectsInsertCall) Header() http.Header { func (c *ObjectsInsertCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -9999,7 +10083,7 @@ func (c *ObjectsInsertCall) doRequest(alt string) (*http.Response, error) { c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "b/{bucket}/o") if c.mediaInfo_ != nil { - urls = strings.Replace(urls, "https://www.googleapis.com/", "https://www.googleapis.com/upload/", 1) + urls = googleapi.ResolveRelative(c.s.BasePath, "/upload/storage/v1/b/{bucket}/o") c.urlParams_.Set("uploadType", c.mediaInfo_.UploadType()) } if body == nil { @@ -10018,7 +10102,7 @@ func (c *ObjectsInsertCall) doRequest(alt string) (*http.Response, error) { googleapi.Expand(req.URL, map[string]string{ "bucket": c.bucket, }) - return gensupport.SendRequest(c.ctx_, c.s.client, req) + return gensupport.SendRequestWithRetry(c.ctx_, c.s.client, req) } // Do executes the "storage.objects.insert" call. @@ -10234,6 +10318,15 @@ func (c *ObjectsListCall) Delimiter(delimiter string) *ObjectsListCall { return c } +// EndOffset sets the optional parameter "endOffset": Filter results to +// objects whose names are lexicographically before endOffset. If +// startOffset is also set, the objects listed will have names between +// startOffset (inclusive) and endOffset (exclusive). +func (c *ObjectsListCall) EndOffset(endOffset string) *ObjectsListCall { + c.urlParams_.Set("endOffset", endOffset) + return c +} + // IncludeTrailingDelimiter sets the optional parameter // "includeTrailingDelimiter": If true, objects that end in exactly one // instance of delimiter will have their metadata included in items in @@ -10287,6 +10380,15 @@ func (c *ObjectsListCall) ProvisionalUserProject(provisionalUserProject string) return c } +// StartOffset sets the optional parameter "startOffset": Filter results +// to objects whose names are lexicographically equal to or after +// startOffset. If endOffset is also set, the objects listed will have +// names between startOffset (inclusive) and endOffset (exclusive). +func (c *ObjectsListCall) StartOffset(startOffset string) *ObjectsListCall { + c.urlParams_.Set("startOffset", startOffset) + return c +} + // UserProject sets the optional parameter "userProject": The project to // be billed for this request. Required for Requester Pays buckets. func (c *ObjectsListCall) UserProject(userProject string) *ObjectsListCall { @@ -10339,7 +10441,7 @@ func (c *ObjectsListCall) Header() http.Header { func (c *ObjectsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -10419,6 +10521,11 @@ func (c *ObjectsListCall) Do(opts ...googleapi.CallOption) (*Objects, error) { // "location": "query", // "type": "string" // }, + // "endOffset": { + // "description": "Filter results to objects whose names are lexicographically before endOffset. If startOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).", + // "location": "query", + // "type": "string" + // }, // "includeTrailingDelimiter": { // "description": "If true, objects that end in exactly one instance of delimiter will have their metadata included in items in addition to prefixes.", // "location": "query", @@ -10460,6 +10567,11 @@ func (c *ObjectsListCall) Do(opts ...googleapi.CallOption) (*Objects, error) { // "location": "query", // "type": "string" // }, + // "startOffset": { + // "description": "Filter results to objects whose names are lexicographically equal to or after startOffset. If endOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).", + // "location": "query", + // "type": "string" + // }, // "userProject": { // "description": "The project to be billed for this request. Required for Requester Pays buckets.", // "location": "query", @@ -10646,7 +10758,7 @@ func (c *ObjectsPatchCall) Header() http.Header { func (c *ObjectsPatchCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -11038,7 +11150,7 @@ func (c *ObjectsRewriteCall) Header() http.Header { func (c *ObjectsRewriteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -11341,7 +11453,7 @@ func (c *ObjectsSetIamPolicyCall) Header() http.Header { func (c *ObjectsSetIamPolicyCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -11541,7 +11653,7 @@ func (c *ObjectsTestIamPermissionsCall) Header() http.Header { func (c *ObjectsTestIamPermissionsCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -11802,7 +11914,7 @@ func (c *ObjectsUpdateCall) Header() http.Header { func (c *ObjectsUpdateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -12007,6 +12119,15 @@ func (c *ObjectsWatchAllCall) Delimiter(delimiter string) *ObjectsWatchAllCall { return c } +// EndOffset sets the optional parameter "endOffset": Filter results to +// objects whose names are lexicographically before endOffset. If +// startOffset is also set, the objects listed will have names between +// startOffset (inclusive) and endOffset (exclusive). +func (c *ObjectsWatchAllCall) EndOffset(endOffset string) *ObjectsWatchAllCall { + c.urlParams_.Set("endOffset", endOffset) + return c +} + // IncludeTrailingDelimiter sets the optional parameter // "includeTrailingDelimiter": If true, objects that end in exactly one // instance of delimiter will have their metadata included in items in @@ -12060,6 +12181,15 @@ func (c *ObjectsWatchAllCall) ProvisionalUserProject(provisionalUserProject stri return c } +// StartOffset sets the optional parameter "startOffset": Filter results +// to objects whose names are lexicographically equal to or after +// startOffset. If endOffset is also set, the objects listed will have +// names between startOffset (inclusive) and endOffset (exclusive). +func (c *ObjectsWatchAllCall) StartOffset(startOffset string) *ObjectsWatchAllCall { + c.urlParams_.Set("startOffset", startOffset) + return c +} + // UserProject sets the optional parameter "userProject": The project to // be billed for this request. Required for Requester Pays buckets. func (c *ObjectsWatchAllCall) UserProject(userProject string) *ObjectsWatchAllCall { @@ -12102,7 +12232,7 @@ func (c *ObjectsWatchAllCall) Header() http.Header { func (c *ObjectsWatchAllCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -12184,6 +12314,11 @@ func (c *ObjectsWatchAllCall) Do(opts ...googleapi.CallOption) (*Channel, error) // "location": "query", // "type": "string" // }, + // "endOffset": { + // "description": "Filter results to objects whose names are lexicographically before endOffset. If startOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).", + // "location": "query", + // "type": "string" + // }, // "includeTrailingDelimiter": { // "description": "If true, objects that end in exactly one instance of delimiter will have their metadata included in items in addition to prefixes.", // "location": "query", @@ -12225,6 +12360,11 @@ func (c *ObjectsWatchAllCall) Do(opts ...googleapi.CallOption) (*Channel, error) // "location": "query", // "type": "string" // }, + // "startOffset": { + // "description": "Filter results to objects whose names are lexicographically equal to or after startOffset. If endOffset is also set, the objects listed will have names between startOffset (inclusive) and endOffset (exclusive).", + // "location": "query", + // "type": "string" + // }, // "userProject": { // "description": "The project to be billed for this request. Required for Requester Pays buckets.", // "location": "query", @@ -12308,7 +12448,7 @@ func (c *ProjectsHmacKeysCreateCall) Header() http.Header { func (c *ProjectsHmacKeysCreateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -12458,7 +12598,7 @@ func (c *ProjectsHmacKeysDeleteCall) Header() http.Header { func (c *ProjectsHmacKeysDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -12593,7 +12733,7 @@ func (c *ProjectsHmacKeysGetCall) Header() http.Header { func (c *ProjectsHmacKeysGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -12689,6 +12829,7 @@ func (c *ProjectsHmacKeysGetCall) Do(opts ...googleapi.CallOption) (*HmacKeyMeta // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", + // "https://www.googleapis.com/auth/devstorage.full_control", // "https://www.googleapis.com/auth/devstorage.read_only" // ] // } @@ -12792,7 +12933,7 @@ func (c *ProjectsHmacKeysListCall) Header() http.Header { func (c *ProjectsHmacKeysListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -12987,7 +13128,7 @@ func (c *ProjectsHmacKeysUpdateCall) Header() http.Header { func (c *ProjectsHmacKeysUpdateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } @@ -13164,7 +13305,7 @@ func (c *ProjectsServiceAccountGetCall) Header() http.Header { func (c *ProjectsServiceAccountGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) - reqHeaders.Set("x-goog-api-client", "gl-go/1.11.0 gdcl/20190802") + reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20200707") for k, v := range c.header_ { reqHeaders[k] = v } diff --git a/vendor/google.golang.org/api/transport/cert/default_cert.go b/vendor/google.golang.org/api/transport/cert/default_cert.go new file mode 100644 index 00000000000..c03af65fd73 --- /dev/null +++ b/vendor/google.golang.org/api/transport/cert/default_cert.go @@ -0,0 +1,110 @@ +// Copyright 2020 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package cert contains certificate tools for Google API clients. +// This package is intended to be used with crypto/tls.Config.GetClientCertificate. +// +// The certificates can be used to satisfy Google's Endpoint Validation. +// See https://cloud.google.com/endpoint-verification/docs/overview +// +// This package is not intended for use by end developers. Use the +// google.golang.org/api/option package to configure API clients. +package cert + +import ( + "crypto/tls" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "os" + "os/exec" + "os/user" + "path/filepath" + "sync" +) + +const ( + metadataPath = ".secureConnect" + metadataFile = "context_aware_metadata.json" +) + +var ( + defaultSourceOnce sync.Once + defaultSource Source + defaultSourceErr error +) + +// Source is a function that can be passed into crypto/tls.Config.GetClientCertificate. +type Source func(*tls.CertificateRequestInfo) (*tls.Certificate, error) + +// DefaultSource returns a certificate source that execs the command specified +// in the file at ~/.secureConnect/context_aware_metadata.json +// +// If that file does not exist, a nil source is returned. +func DefaultSource() (Source, error) { + defaultSourceOnce.Do(func() { + defaultSource, defaultSourceErr = newSecureConnectSource() + }) + return defaultSource, defaultSourceErr +} + +type secureConnectSource struct { + metadata secureConnectMetadata +} + +type secureConnectMetadata struct { + Cmd []string `json:"cert_provider_command"` +} + +// newSecureConnectSource creates a secureConnectSource by reading the well-known file. +func newSecureConnectSource() (Source, error) { + user, err := user.Current() + if err != nil { + // Ignore. + return nil, nil + } + filename := filepath.Join(user.HomeDir, metadataPath, metadataFile) + file, err := ioutil.ReadFile(filename) + if os.IsNotExist(err) { + // Ignore. + return nil, nil + } + if err != nil { + return nil, err + } + + var metadata secureConnectMetadata + if err := json.Unmarshal(file, &metadata); err != nil { + return nil, fmt.Errorf("cert: could not parse JSON in %q: %v", filename, err) + } + if err := validateMetadata(metadata); err != nil { + return nil, fmt.Errorf("cert: invalid config in %q: %v", filename, err) + } + return (&secureConnectSource{ + metadata: metadata, + }).getClientCertificate, nil +} + +func validateMetadata(metadata secureConnectMetadata) error { + if len(metadata.Cmd) == 0 { + return errors.New("empty cert_provider_command") + } + return nil +} + +func (s *secureConnectSource) getClientCertificate(info *tls.CertificateRequestInfo) (*tls.Certificate, error) { + // TODO(cbro): consider caching valid certificates rather than exec'ing every time. + command := s.metadata.Cmd + data, err := exec.Command(command[0], command[1:]...).Output() + if err != nil { + // TODO(cbro): read stderr for error message? Might contain sensitive info. + return nil, err + } + cert, err := tls.X509KeyPair(data, data) + if err != nil { + return nil, err + } + return &cert, nil +} diff --git a/vendor/google.golang.org/api/transport/http/default_transport_go113.go b/vendor/google.golang.org/api/transport/http/default_transport_go113.go new file mode 100644 index 00000000000..924f2704d1a --- /dev/null +++ b/vendor/google.golang.org/api/transport/http/default_transport_go113.go @@ -0,0 +1,20 @@ +// Copyright 2020 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.13 + +package http + +import "net/http" + +// clonedTransport returns the given RoundTripper as a cloned *http.Transport. +// It returns nil if the RoundTripper can't be cloned or coerced to +// *http.Transport. +func clonedTransport(rt http.RoundTripper) *http.Transport { + t, ok := rt.(*http.Transport) + if !ok { + return nil + } + return t.Clone() +} diff --git a/vendor/google.golang.org/api/transport/http/default_transport_not_go113.go b/vendor/google.golang.org/api/transport/http/default_transport_not_go113.go new file mode 100644 index 00000000000..3cb16c6cb6c --- /dev/null +++ b/vendor/google.golang.org/api/transport/http/default_transport_not_go113.go @@ -0,0 +1,15 @@ +// Copyright 2020 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.13 + +package http + +import "net/http" + +// clonedTransport returns the given RoundTripper as a cloned *http.Transport. +// For versions of Go <1.13, this is not supported, so return nil. +func clonedTransport(rt http.RoundTripper) *http.Transport { + return nil +} diff --git a/vendor/google.golang.org/api/transport/http/dial.go b/vendor/google.golang.org/api/transport/http/dial.go index c0d8bf20b02..44503014172 100644 --- a/vendor/google.golang.org/api/transport/http/dial.go +++ b/vendor/google.golang.org/api/transport/http/dial.go @@ -1,16 +1,6 @@ -// Copyright 2015 Google LLC -// -// 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. +// Copyright 2015 Google LLC. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. // Package http supports network connections to HTTP servers. // This package is not intended for use by end developers. Use the @@ -19,17 +9,30 @@ package http import ( "context" + "crypto/tls" "errors" + "net" "net/http" + "net/url" + "os" + "strings" + "time" "go.opencensus.io/plugin/ochttp" "golang.org/x/oauth2" "google.golang.org/api/googleapi/transport" "google.golang.org/api/internal" "google.golang.org/api/option" + "google.golang.org/api/transport/cert" "google.golang.org/api/transport/http/internal/propagation" ) +const ( + mTLSModeAlways = "always" + mTLSModeNever = "never" + mTLSModeAuto = "auto" +) + // NewClient returns an HTTP client for use communicating with a Google cloud // service, configured with the given ClientOptions. It also returns the endpoint // for the service as specified in the options. @@ -38,15 +41,23 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*http.Client, if err != nil { return nil, "", err } + clientCertSource, err := getClientCertificateSource(settings) + if err != nil { + return nil, "", err + } + endpoint, err := getEndpoint(settings, clientCertSource) + if err != nil { + return nil, "", err + } // TODO(cbro): consider injecting the User-Agent even if an explicit HTTP client is provided? if settings.HTTPClient != nil { - return settings.HTTPClient, settings.Endpoint, nil + return settings.HTTPClient, endpoint, nil } - trans, err := newTransport(ctx, defaultBaseTransport(ctx), settings) + trans, err := newTransport(ctx, defaultBaseTransport(ctx, clientCertSource), settings) if err != nil { return nil, "", err } - return &http.Client{Transport: trans}, settings.Endpoint, nil + return &http.Client{Transport: trans}, endpoint, nil } // NewTransport creates an http.RoundTripper for use communicating with a Google @@ -63,14 +74,14 @@ func NewTransport(ctx context.Context, base http.RoundTripper, opts ...option.Cl } func newTransport(ctx context.Context, base http.RoundTripper, settings *internal.DialSettings) (http.RoundTripper, error) { - trans := base - trans = parameterTransport{ - base: trans, + paramTransport := ¶meterTransport{ + base: base, userAgent: settings.UserAgent, quotaProject: settings.QuotaProject, requestReason: settings.RequestReason, } - trans = addOCTransport(trans) + var trans http.RoundTripper = paramTransport + trans = addOCTransport(trans, settings) switch { case settings.NoAuth: // Do nothing. @@ -84,9 +95,17 @@ func newTransport(ctx context.Context, base http.RoundTripper, settings *interna if err != nil { return nil, err } + if paramTransport.quotaProject == "" { + paramTransport.quotaProject = internal.QuotaProjectFromCreds(creds) + } + + ts := creds.TokenSource + if settings.TokenSource != nil { + ts = settings.TokenSource + } trans = &oauth2.Transport{ Base: trans, - Source: creds.TokenSource, + Source: ts, } } return trans, nil @@ -114,21 +133,20 @@ type parameterTransport struct { base http.RoundTripper } -func (t parameterTransport) RoundTrip(req *http.Request) (*http.Response, error) { +func (t *parameterTransport) RoundTrip(req *http.Request) (*http.Response, error) { rt := t.base if rt == nil { return nil, errors.New("transport: no Transport specified") } - if t.userAgent == "" { - return rt.RoundTrip(req) - } newReq := *req newReq.Header = make(http.Header) for k, vv := range req.Header { newReq.Header[k] = vv } - // TODO(cbro): append to existing User-Agent header? - newReq.Header.Set("User-Agent", t.userAgent) + if t.userAgent != "" { + // TODO(cbro): append to existing User-Agent header? + newReq.Header.Set("User-Agent", t.userAgent) + } // Attach system parameters into the header if t.quotaProject != "" { @@ -145,17 +163,142 @@ func (t parameterTransport) RoundTrip(req *http.Request) (*http.Response, error) var appengineUrlfetchHook func(context.Context) http.RoundTripper // defaultBaseTransport returns the base HTTP transport. -// On App Engine, this is urlfetch.Transport, otherwise it's http.DefaultTransport. -func defaultBaseTransport(ctx context.Context) http.RoundTripper { +// On App Engine, this is urlfetch.Transport. +// Otherwise, use a default transport, taking most defaults from +// http.DefaultTransport. +// If TLSCertificate is available, set TLSClientConfig as well. +func defaultBaseTransport(ctx context.Context, clientCertSource cert.Source) http.RoundTripper { if appengineUrlfetchHook != nil { return appengineUrlfetchHook(ctx) } - return http.DefaultTransport + + // Copy http.DefaultTransport except for MaxIdleConnsPerHost setting, + // which is increased due to reported performance issues under load in the GCS + // client. Transport.Clone is only available in Go 1.13 and up. + trans := clonedTransport(http.DefaultTransport) + if trans == nil { + trans = fallbackBaseTransport() + } + trans.MaxIdleConnsPerHost = 100 + + if clientCertSource != nil { + trans.TLSClientConfig = &tls.Config{ + GetClientCertificate: clientCertSource, + } + } + + return trans +} + +// fallbackBaseTransport is used in google.protobuf.MethodOptions + 1, // 1: google.api.http:type_name -> google.api.HttpRule + 2, // [2:2] is the sub-list for method output_type + 2, // [2:2] is the sub-list for method input_type + 1, // [1:2] is the sub-list for extension type_name + 0, // [0:1] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name } -var fileDescriptor_c591c5aa9fb79aab = []byte{ - // 208 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x49, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x4f, 0x2c, 0xc8, 0xd4, 0x4f, 0xcc, 0xcb, 0xcb, 0x2f, 0x49, 0x2c, 0xc9, 0xcc, - 0xcf, 0x2b, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x82, 0xc8, 0xea, 0x25, 0x16, 0x64, - 0x4a, 0x89, 0x22, 0xa9, 0xcc, 0x28, 0x29, 0x29, 0x80, 0x28, 0x91, 0x52, 0x80, 0x0a, 0x83, 0x79, - 0x49, 0xa5, 0x69, 0xfa, 0x29, 0xa9, 0xc5, 0xc9, 0x45, 0x99, 0x05, 0x25, 0xf9, 0x45, 0x10, 0x15, - 0x56, 0xde, 0x5c, 0x2c, 0x20, 0xf5, 0x42, 0x72, 0x7a, 0x50, 0xd3, 0x60, 0x4a, 0xf5, 0x7c, 0x53, - 0x4b, 0x32, 0xf2, 0x53, 0xfc, 0x0b, 0xc0, 0x56, 0x4a, 0x6c, 0x38, 0xb5, 0x47, 0x49, 0x81, 0x51, - 0x83, 0xdb, 0x48, 0x44, 0x0f, 0x61, 0xad, 0x9e, 0x47, 0x49, 0x49, 0x41, 0x50, 0x69, 0x4e, 0x6a, - 0x10, 0xd8, 0x10, 0xa7, 0x3c, 0x2e, 0xbe, 0xe4, 0xfc, 0x5c, 0x24, 0x05, 0x4e, 0x02, 0x8e, 0x08, - 0x67, 0x07, 0x80, 0x4c, 0x0e, 0x60, 0x8c, 0x72, 0x84, 0xca, 0xa7, 0xe7, 0xe7, 0x24, 0xe6, 0xa5, - 0xeb, 0xe5, 0x17, 0xa5, 0xeb, 0xa7, 0xa7, 0xe6, 0x81, 0xed, 0xd5, 0x87, 0x48, 0x25, 0x16, 0x64, - 0x16, 0xa3, 0x7b, 0xda, 0x1a, 0x89, 0xbd, 0x88, 0x89, 0xc5, 0xdd, 0x31, 0xc0, 0x33, 0x89, 0x0d, - 0xac, 0xc9, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xe3, 0x29, 0x19, 0x62, 0x28, 0x01, 0x00, 0x00, +func init() { file_google_api_annotations_proto_init() } +func file_google_api_annotations_proto_init() { + if File_google_api_annotations_proto != nil { + return + } + file_google_api_http_proto_init() + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_api_annotations_proto_rawDesc, + NumEnums: 0, + NumMessages: 0, + NumExtensions: 1, + NumServices: 0, + }, + GoTypes: file_google_api_annotations_proto_goTypes, + DependencyIndexes: file_google_api_annotations_proto_depIdxs, + ExtensionInfos: file_google_api_annotations_proto_extTypes, + }.Build() + File_google_api_annotations_proto = out.File + file_google_api_annotations_proto_rawDesc = nil + file_google_api_annotations_proto_goTypes = nil + file_google_api_annotations_proto_depIdxs = nil } diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go index 9757593e922..3832df0bd53 100644 --- a/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go @@ -1,81 +1,219 @@ +// Copyright 2020 Google LLC +// +// 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 protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.22.0 +// protoc v3.12.3 // source: google/api/client.proto package annotations import ( - fmt "fmt" - math "math" + reflect "reflect" proto "github.com/golang/protobuf/proto" descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 -var E_MethodSignature = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.MethodOptions)(nil), - ExtensionType: ([]string)(nil), - Field: 1051, - Name: "google.api.method_signature", - Tag: "bytes,1051,rep,name=method_signature", - Filename: "google/api/client.proto", +var file_google_api_client_proto_extTypes = []protoimpl.ExtensionInfo{ + { + ExtendedType: (*descriptor.MethodOptions)(nil), + ExtensionType: ([]string)(nil), + Field: 1051, + Name: "google.api.method_signature", + Tag: "bytes,1051,rep,name=method_signature", + Filename: "google/api/client.proto", + }, + { + ExtendedType: (*descriptor.ServiceOptions)(nil), + ExtensionType: (*string)(nil), + Field: 1049, + Name: "google.api.default_host", + Tag: "bytes,1049,opt,name=default_host", + Filename: "google/api/client.proto", + }, + { + ExtendedType: (*descriptor.ServiceOptions)(nil), + ExtensionType: (*string)(nil), + Field: 1050, + Name: "google.api.oauth_scopes", + Tag: "bytes,1050,opt,name=oauth_scopes", + Filename: "google/api/client.proto", + }, } -var E_DefaultHost = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.ServiceOptions)(nil), - ExtensionType: (*string)(nil), - Field: 1049, - Name: "google.api.default_host", - Tag: "bytes,1049,opt,name=default_host", - Filename: "google/api/client.proto", -} +// Extension fields to descriptor.MethodOptions. +var ( + // A definition of a client library method signature. + // + // In client libraries, each proto RPC corresponds to one or more methods + // which the end user is able to call, and calls the underlying RPC. + // Normally, this method receives a single argument (a struct or instance + // corresponding to the RPC request object). Defining this field will + // add one or more overloads providing flattened or simpler method signatures + // in some languages. + // + // The fields on the method signature are provided as a comma-separated + // string. + // + // For example, the proto RPC and annotation: + // + // rpc CreateSubscription(CreateSubscriptionRequest) + // returns (Subscription) { + // option (google.api.method_signature) = "name,topic"; + // } + // + // Would add the following Java overload (in addition to the method accepting + // the request object): + // + // public final Subscription createSubscription(String name, String topic) + // + // The following backwards-compatibility guidelines apply: + // + // * Adding this annotation to an unannotated method is backwards + // compatible. + // * Adding this annotation to a method which already has existing + // method signature annotations is backwards compatible if and only if + // the new method signature annotation is last in the sequence. + // * Modifying or removing an existing method signature annotation is + // a breaking change. + // * Re-ordering existing method signature annotations is a breaking + // change. + // + // repeated string method_signature = 1051; + E_MethodSignature = &file_google_api_client_proto_extTypes[0] +) -var E_OauthScopes = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.ServiceOptions)(nil), - ExtensionType: (*string)(nil), - Field: 1050, - Name: "google.api.oauth_scopes", - Tag: "bytes,1050,opt,name=oauth_scopes", - Filename: "google/api/client.proto", -} +// Extension fields to descriptor.ServiceOptions. +var ( + // The hostname for this service. + // This should be specified with no prefix or protocol. + // + // Example: + // + // service Foo { + // option (google.api.default_host) = "foo.googleapi.com"; + // ... + // } + // + // optional string default_host = 1049; + E_DefaultHost = &file_google_api_client_proto_extTypes[1] + // OAuth scopes needed for the client. + // + // Example: + // + // service Foo { + // option (google.api.oauth_scopes) = \ + // "https://www.googleapis.com/auth/cloud-platform"; + // ... + // } + // + // If there is more than one scope, use a comma-separated string: + // + // Example: + // + // service Foo { + // option (google.api.oauth_scopes) = \ + // "https://www.googleapis.com/auth/cloud-platform," + // "https://www.googleapis.com/auth/monitoring"; + // ... + // } + // + // optional string oauth_scopes = 1050; + E_OauthScopes = &file_google_api_client_proto_extTypes[2] +) -func init() { - proto.RegisterExtension(E_MethodSignature) - proto.RegisterExtension(E_DefaultHost) - proto.RegisterExtension(E_OauthScopes) +var File_google_api_client_proto protoreflect.FileDescriptor + +var file_google_api_client_proto_rawDesc = []byte{ + 0x0a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6c, 0x69, + 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x61, 0x70, 0x69, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, + 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x3a, 0x4a, 0x0a, 0x10, 0x6d, 0x65, 0x74, 0x68, 0x6f, + 0x64, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x1e, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4d, 0x65, + 0x74, 0x68, 0x6f, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9b, 0x08, 0x20, 0x03, + 0x28, 0x09, 0x52, 0x0f, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, + 0x75, 0x72, 0x65, 0x3a, 0x43, 0x0a, 0x0c, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x5f, 0x68, + 0x6f, 0x73, 0x74, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x99, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x66, + 0x61, 0x75, 0x6c, 0x74, 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x43, 0x0a, 0x0c, 0x6f, 0x61, 0x75, 0x74, + 0x68, 0x5f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, + 0x63, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9a, 0x08, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x0b, 0x6f, 0x61, 0x75, 0x74, 0x68, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x42, 0x69, 0x0a, + 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x42, + 0x0b, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x41, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, + 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0xa2, 0x02, 0x04, 0x47, 0x41, 0x50, 0x49, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } -func init() { - proto.RegisterFile("google/api/client.proto", fileDescriptor_78f2c6f7c3a942c1) +var file_google_api_client_proto_goTypes = []interface{}{ + (*descriptor.MethodOptions)(nil), // 0: google.protobuf.MethodOptions + (*descriptor.ServiceOptions)(nil), // 1: google.protobuf.ServiceOptions +} +var file_google_api_client_proto_depIdxs = []int32{ + 0, // 0: google.api.method_signature:extendee -> google.protobuf.MethodOptions + 1, // 1: google.api.default_host:extendee -> google.protobuf.ServiceOptions + 1, // 2: google.api.oauth_scopes:extendee -> google.protobuf.ServiceOptions + 3, // [3:3] is the sub-list for method output_type + 3, // [3:3] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 0, // [0:3] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name } -var fileDescriptor_78f2c6f7c3a942c1 = []byte{ - // 262 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x90, 0x3f, 0x4f, 0xc3, 0x30, - 0x10, 0xc5, 0x55, 0x40, 0xa8, 0x75, 0x11, 0xa0, 0x2c, 0x20, 0x06, 0xc8, 0xd8, 0xc9, 0x1e, 0xd8, - 0xca, 0xd4, 0x76, 0xe0, 0x8f, 0x84, 0x88, 0x9a, 0x8d, 0x25, 0x72, 0x9d, 0xab, 0x63, 0x29, 0xf5, - 0x59, 0xf6, 0x85, 0xef, 0x02, 0x6c, 0x7c, 0x52, 0x54, 0xc7, 0x11, 0x48, 0x0c, 0x6c, 0x27, 0xbd, - 0xf7, 0xfb, 0x9d, 0xf4, 0xd8, 0x85, 0x46, 0xd4, 0x2d, 0x08, 0xe9, 0x8c, 0x50, 0xad, 0x01, 0x4b, - 0xdc, 0x79, 0x24, 0xcc, 0x58, 0x1f, 0x70, 0xe9, 0xcc, 0x55, 0x9e, 0x4a, 0x31, 0xd9, 0x74, 0x5b, - 0x51, 0x43, 0x50, 0xde, 0x38, 0x42, 0xdf, 0xb7, 0xe7, 0x4f, 0xec, 0x7c, 0x07, 0xd4, 0x60, 0x5d, - 0x05, 0xa3, 0xad, 0xa4, 0xce, 0x43, 0x76, 0xcd, 0x93, 0x62, 0xc0, 0xf8, 0x73, 0xac, 0xbc, 0x38, - 0x32, 0x68, 0xc3, 0xe5, 0xe7, 0x38, 0x3f, 0x9c, 0x4d, 0xd6, 0x67, 0x3d, 0x58, 0x0e, 0xdc, 0x7c, - 0xc5, 0x4e, 0x6a, 0xd8, 0xca, 0xae, 0xa5, 0xaa, 0xc1, 0x40, 0xd9, 0xcd, 0x1f, 0x4f, 0x09, 0xfe, - 0xcd, 0x28, 0x18, 0x44, 0xef, 0xe3, 0x7c, 0x34, 0x9b, 0xac, 0xa7, 0x89, 0x7a, 0xc0, 0x40, 0x7b, - 0x09, 0xca, 0x8e, 0x9a, 0x2a, 0x28, 0x74, 0x10, 0xfe, 0x97, 0x7c, 0x24, 0x49, 0xa4, 0xca, 0x08, - 0x2d, 0x0d, 0x3b, 0x55, 0xb8, 0xe3, 0x3f, 0x4b, 0x2c, 0xa7, 0xab, 0xb8, 0x51, 0xb1, 0x97, 0x14, - 0xa3, 0xd7, 0x45, 0x8a, 0x34, 0xb6, 0xd2, 0x6a, 0x8e, 0x5e, 0x0b, 0x0d, 0x36, 0xbe, 0x10, 0x7d, - 0x24, 0x9d, 0x09, 0x71, 0x5c, 0x69, 0x2d, 0x92, 0x8c, 0xbf, 0xee, 0x7e, 0xdd, 0x5f, 0x07, 0x47, - 0xf7, 0x8b, 0xe2, 0x71, 0x73, 0x1c, 0xa1, 0xdb, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0xcc, 0xc2, - 0xcf, 0x71, 0x90, 0x01, 0x00, 0x00, +func init() { file_google_api_client_proto_init() } +func file_google_api_client_proto_init() { + if File_google_api_client_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_api_client_proto_rawDesc, + NumEnums: 0, + NumMessages: 0, + NumExtensions: 3, + NumServices: 0, + }, + GoTypes: file_google_api_client_proto_goTypes, + DependencyIndexes: file_google_api_client_proto_depIdxs, + ExtensionInfos: file_google_api_client_proto_extTypes, + }.Build() + File_google_api_client_proto = out.File + file_google_api_client_proto_rawDesc = nil + file_google_api_client_proto_goTypes = nil + file_google_api_client_proto_depIdxs = nil } diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/field_behavior.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/field_behavior.pb.go index 6e67a93febe..0038b20e4e4 100644 --- a/vendor/google.golang.org/genproto/googleapis/api/annotations/field_behavior.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/api/annotations/field_behavior.pb.go @@ -1,26 +1,45 @@ +// Copyright 2020 Google LLC +// +// 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 protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.22.0 +// protoc v3.12.3 // source: google/api/field_behavior.proto package annotations import ( - fmt "fmt" - math "math" + reflect "reflect" + sync "sync" proto "github.com/golang/protobuf/proto" descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 // An indicator of the behavior of a given field (for example, that a field // is required in requests, or given as output but ignored as input). @@ -56,69 +75,164 @@ const ( FieldBehavior_IMMUTABLE FieldBehavior = 5 ) -var FieldBehavior_name = map[int32]string{ - 0: "FIELD_BEHAVIOR_UNSPECIFIED", - 1: "OPTIONAL", - 2: "REQUIRED", - 3: "OUTPUT_ONLY", - 4: "INPUT_ONLY", - 5: "IMMUTABLE", -} +// Enum value maps for FieldBehavior. +var ( + FieldBehavior_name = map[int32]string{ + 0: "FIELD_BEHAVIOR_UNSPECIFIED", + 1: "OPTIONAL", + 2: "REQUIRED", + 3: "OUTPUT_ONLY", + 4: "INPUT_ONLY", + 5: "IMMUTABLE", + } + FieldBehavior_value = map[string]int32{ + "FIELD_BEHAVIOR_UNSPECIFIED": 0, + "OPTIONAL": 1, + "REQUIRED": 2, + "OUTPUT_ONLY": 3, + "INPUT_ONLY": 4, + "IMMUTABLE": 5, + } +) -var FieldBehavior_value = map[string]int32{ - "FIELD_BEHAVIOR_UNSPECIFIED": 0, - "OPTIONAL": 1, - "REQUIRED": 2, - "OUTPUT_ONLY": 3, - "INPUT_ONLY": 4, - "IMMUTABLE": 5, +func (x FieldBehavior) Enum() *FieldBehavior { + p := new(FieldBehavior) + *p = x + return p } func (x FieldBehavior) String() string { - return proto.EnumName(FieldBehavior_name, int32(x)) + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (FieldBehavior) Descriptor() protoreflect.EnumDescriptor { + return file_google_api_field_behavior_proto_enumTypes[0].Descriptor() +} + +func (FieldBehavior) Type() protoreflect.EnumType { + return &file_google_api_field_behavior_proto_enumTypes[0] +} + +func (x FieldBehavior) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) } +// Deprecated: Use FieldBehavior.Descriptor instead. func (FieldBehavior) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_4648f18fd5079967, []int{0} + return file_google_api_field_behavior_proto_rawDescGZIP(), []int{0} } -var E_FieldBehavior = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.FieldOptions)(nil), - ExtensionType: ([]FieldBehavior)(nil), - Field: 1052, - Name: "google.api.field_behavior", - Tag: "varint,1052,rep,name=field_behavior,enum=google.api.FieldBehavior", - Filename: "google/api/field_behavior.proto", +var file_google_api_field_behavior_proto_extTypes = []protoimpl.ExtensionInfo{ + { + ExtendedType: (*descriptor.FieldOptions)(nil), + ExtensionType: ([]FieldBehavior)(nil), + Field: 1052, + Name: "google.api.field_behavior", + Tag: "varint,1052,rep,name=field_behavior,enum=google.api.FieldBehavior", + Filename: "google/api/field_behavior.proto", + }, } -func init() { - proto.RegisterEnum("google.api.FieldBehavior", FieldBehavior_name, FieldBehavior_value) - proto.RegisterExtension(E_FieldBehavior) +// Extension fields to descriptor.FieldOptions. +var ( + // A designation of a specific field behavior (required, output only, etc.) + // in protobuf messages. + // + // Examples: + // + // string name = 1 [(google.api.field_behavior) = REQUIRED]; + // State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + // google.protobuf.Duration ttl = 1 + // [(google.api.field_behavior) = INPUT_ONLY]; + // google.protobuf.Timestamp expire_time = 1 + // [(google.api.field_behavior) = OUTPUT_ONLY, + // (google.api.field_behavior) = IMMUTABLE]; + // + // repeated google.api.FieldBehavior field_behavior = 1052; + E_FieldBehavior = &file_google_api_field_behavior_proto_extTypes[0] +) + +var File_google_api_field_behavior_proto protoreflect.FileDescriptor + +var file_google_api_field_behavior_proto_rawDesc = []byte{ + 0x0a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x66, 0x69, 0x65, + 0x6c, 0x64, 0x5f, 0x62, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x12, 0x0a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x1a, 0x20, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, + 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2a, + 0x7b, 0x0a, 0x0d, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x42, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, + 0x12, 0x1e, 0x0a, 0x1a, 0x46, 0x49, 0x45, 0x4c, 0x44, 0x5f, 0x42, 0x45, 0x48, 0x41, 0x56, 0x49, + 0x4f, 0x52, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, + 0x12, 0x0c, 0x0a, 0x08, 0x4f, 0x50, 0x54, 0x49, 0x4f, 0x4e, 0x41, 0x4c, 0x10, 0x01, 0x12, 0x0c, + 0x0a, 0x08, 0x52, 0x45, 0x51, 0x55, 0x49, 0x52, 0x45, 0x44, 0x10, 0x02, 0x12, 0x0f, 0x0a, 0x0b, + 0x4f, 0x55, 0x54, 0x50, 0x55, 0x54, 0x5f, 0x4f, 0x4e, 0x4c, 0x59, 0x10, 0x03, 0x12, 0x0e, 0x0a, + 0x0a, 0x49, 0x4e, 0x50, 0x55, 0x54, 0x5f, 0x4f, 0x4e, 0x4c, 0x59, 0x10, 0x04, 0x12, 0x0d, 0x0a, + 0x09, 0x49, 0x4d, 0x4d, 0x55, 0x54, 0x41, 0x42, 0x4c, 0x45, 0x10, 0x05, 0x3a, 0x60, 0x0a, 0x0e, + 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x62, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x12, 0x1d, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9c, 0x08, + 0x20, 0x03, 0x28, 0x0e, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, + 0x69, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x42, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x52, + 0x0d, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x42, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x42, 0x70, + 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, + 0x42, 0x12, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x42, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x50, + 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x41, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, + 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, 0x70, + 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3b, 0x61, 0x6e, + 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0xa2, 0x02, 0x04, 0x47, 0x41, 0x50, 0x49, + 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } -func init() { - proto.RegisterFile("google/api/field_behavior.proto", fileDescriptor_4648f18fd5079967) +var ( + file_google_api_field_behavior_proto_rawDescOnce sync.Once + file_google_api_field_behavior_proto_rawDescData = file_google_api_field_behavior_proto_rawDesc +) + +func file_google_api_field_behavior_proto_rawDescGZIP() []byte { + file_google_api_field_behavior_proto_rawDescOnce.Do(func() { + file_google_api_field_behavior_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_api_field_behavior_proto_rawDescData) + }) + return file_google_api_field_behavior_proto_rawDescData +} + +var file_google_api_field_behavior_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_google_api_field_behavior_proto_goTypes = []interface{}{ + (FieldBehavior)(0), // 0: google.api.FieldBehavior + (*descriptor.FieldOptions)(nil), // 1: google.protobuf.FieldOptions +} +var file_google_api_field_behavior_proto_depIdxs = []int32{ + 1, // 0: google.api.field_behavior:extendee -> google.protobuf.FieldOptions + 0, // 1: google.api.field_behavior:type_name -> google.api.FieldBehavior + 2, // [2:2] is the sub-list for method output_type + 2, // [2:2] is the sub-list for method input_type + 1, // [1:2] is the sub-list for extension type_name + 0, // [0:1] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name } -var fileDescriptor_4648f18fd5079967 = []byte{ - // 303 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x54, 0x90, 0x4f, 0x4f, 0xb3, 0x30, - 0x1c, 0xc7, 0x9f, 0xfd, 0x79, 0xcc, 0xac, 0x0e, 0x49, 0x4f, 0xba, 0x44, 0xdd, 0xd1, 0x78, 0x28, - 0x89, 0xde, 0xf4, 0x04, 0xae, 0xd3, 0x26, 0x8c, 0x56, 0x04, 0x13, 0xbd, 0x60, 0xb7, 0xb1, 0xda, - 0x64, 0xd2, 0x06, 0xd0, 0x8b, 0x6f, 0xc5, 0x93, 0xaf, 0xd4, 0xd0, 0x31, 0x85, 0x5b, 0xbf, 0xf9, - 0x7d, 0xfa, 0xeb, 0xe7, 0x5b, 0x70, 0x2a, 0x94, 0x12, 0xeb, 0xd4, 0xe1, 0x5a, 0x3a, 0x2b, 0x99, - 0xae, 0x97, 0xc9, 0x3c, 0x7d, 0xe5, 0x1f, 0x52, 0xe5, 0x48, 0xe7, 0xaa, 0x54, 0x10, 0x6c, 0x00, - 0xc4, 0xb5, 0x1c, 0x8d, 0x6b, 0xd8, 0x4c, 0xe6, 0xef, 0x2b, 0x67, 0x99, 0x16, 0x8b, 0x5c, 0xea, - 0x72, 0x4b, 0x9f, 0x7f, 0x82, 0xe1, 0xb4, 0xda, 0xe2, 0xd5, 0x4b, 0xe0, 0x09, 0x18, 0x4d, 0x09, - 0xf6, 0x27, 0x89, 0x87, 0xef, 0xdc, 0x47, 0x42, 0xc3, 0x24, 0x0e, 0x1e, 0x18, 0xbe, 0x21, 0x53, - 0x82, 0x27, 0xf6, 0x3f, 0xb8, 0x0f, 0x06, 0x94, 0x45, 0x84, 0x06, 0xae, 0x6f, 0x77, 0xaa, 0x14, - 0xe2, 0xfb, 0x98, 0x84, 0x78, 0x62, 0x77, 0xe1, 0x01, 0xd8, 0xa3, 0x71, 0xc4, 0xe2, 0x28, 0xa1, - 0x81, 0xff, 0x64, 0xf7, 0xa0, 0x05, 0x00, 0x09, 0x7e, 0x73, 0x1f, 0x0e, 0xc1, 0x2e, 0x99, 0xcd, - 0xe2, 0xc8, 0xf5, 0x7c, 0x6c, 0xff, 0xbf, 0x7a, 0x01, 0x56, 0xbb, 0x02, 0x3c, 0x46, 0xb5, 0xfd, - 0xd6, 0x18, 0x19, 0x3b, 0xaa, 0x4b, 0xa9, 0xb2, 0xe2, 0xf0, 0x6b, 0x30, 0xee, 0x9d, 0x59, 0x17, - 0x47, 0xe8, 0xaf, 0x23, 0x6a, 0xe9, 0x87, 0xc3, 0x55, 0x33, 0x7a, 0x1a, 0x58, 0x0b, 0xf5, 0xd6, - 0xc0, 0x3d, 0xd8, 0xe2, 0x59, 0xf5, 0x0c, 0xeb, 0x3c, 0xbb, 0x35, 0x21, 0xd4, 0x9a, 0x67, 0x02, - 0xa9, 0x5c, 0x38, 0x22, 0xcd, 0x8c, 0x84, 0xb3, 0x19, 0x71, 0x2d, 0x0b, 0xf3, 0xe9, 0x3c, 0xcb, - 0x54, 0xc9, 0x8d, 0xcf, 0x75, 0xe3, 0xfc, 0xdd, 0xed, 0xdf, 0xba, 0x8c, 0xcc, 0x77, 0xcc, 0xa5, - 0xcb, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xfc, 0x94, 0x57, 0x94, 0xa8, 0x01, 0x00, 0x00, +func init() { file_google_api_field_behavior_proto_init() } +func file_google_api_field_behavior_proto_init() { + if File_google_api_field_behavior_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_api_field_behavior_proto_rawDesc, + NumEnums: 1, + NumMessages: 0, + NumExtensions: 1, + NumServices: 0, + }, + GoTypes: file_google_api_field_behavior_proto_goTypes, + DependencyIndexes: file_google_api_field_behavior_proto_depIdxs, + EnumInfos: file_google_api_field_behavior_proto_enumTypes, + ExtensionInfos: file_google_api_field_behavior_proto_extTypes, + }.Build() + File_google_api_field_behavior_proto = out.File + file_google_api_field_behavior_proto_rawDesc = nil + file_google_api_field_behavior_proto_goTypes = nil + file_google_api_field_behavior_proto_depIdxs = nil } diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go index 6ed6f3c9176..955bc56a394 100644 --- a/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go @@ -1,30 +1,53 @@ +// Copyright 2020 Google LLC +// +// 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 protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.22.0 +// protoc v3.12.3 // source: google/api/http.proto package annotations import ( - fmt "fmt" - math "math" + reflect "reflect" + sync "sync" proto "github.com/golang/protobuf/proto" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 // Defines the HTTP configuration for an API service. It contains a list of // [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method // to one or more HTTP REST API methods. type Http struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // A list of HTTP configuration rules that apply to individual API methods. // // **NOTE:** All service configuration rules follow "last one wins" order. @@ -35,47 +58,51 @@ type Http struct { // // The default behavior is to not decode RFC 6570 reserved characters in multi // segment matches. - FullyDecodeReservedExpansion bool `protobuf:"varint,2,opt,name=fully_decode_reserved_expansion,json=fullyDecodeReservedExpansion,proto3" json:"fully_decode_reserved_expansion,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + FullyDecodeReservedExpansion bool `protobuf:"varint,2,opt,name=fully_decode_reserved_expansion,json=fullyDecodeReservedExpansion,proto3" json:"fully_decode_reserved_expansion,omitempty"` } -func (m *Http) Reset() { *m = Http{} } -func (m *Http) String() string { return proto.CompactTextString(m) } -func (*Http) ProtoMessage() {} -func (*Http) Descriptor() ([]byte, []int) { - return fileDescriptor_ff9994be407cdcc9, []int{0} +func (x *Http) Reset() { + *x = Http{} + if protoimpl.UnsafeEnabled { + mi := &file_google_api_http_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Http) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Http.Unmarshal(m, b) -} -func (m *Http) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Http.Marshal(b, m, deterministic) +func (x *Http) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Http) XXX_Merge(src proto.Message) { - xxx_messageInfo_Http.Merge(m, src) -} -func (m *Http) XXX_Size() int { - return xxx_messageInfo_Http.Size(m) -} -func (m *Http) XXX_DiscardUnknown() { - xxx_messageInfo_Http.DiscardUnknown(m) + +func (*Http) ProtoMessage() {} + +func (x *Http) ProtoReflect() protoreflect.Message { + mi := &file_google_api_http_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Http proto.InternalMessageInfo +// Deprecated: Use Http.ProtoReflect.Descriptor instead. +func (*Http) Descriptor() ([]byte, []int) { + return file_google_api_http_proto_rawDescGZIP(), []int{0} +} -func (m *Http) GetRules() []*HttpRule { - if m != nil { - return m.Rules +func (x *Http) GetRules() []*HttpRule { + if x != nil { + return x.Rules } return nil } -func (m *Http) GetFullyDecodeReservedExpansion() bool { - if m != nil { - return m.FullyDecodeReservedExpansion +func (x *Http) GetFullyDecodeReservedExpansion() bool { + if x != nil { + return x.FullyDecodeReservedExpansion } return false } @@ -350,6 +377,10 @@ func (m *Http) GetFullyDecodeReservedExpansion() bool { // the request or response body to a repeated field. However, some gRPC // Transcoding implementations may not support this feature. type HttpRule struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // Selects a method to which this rule applies. // // Refer to [selector][google.api.DocumentationRule.selector] for syntax details. @@ -358,7 +389,7 @@ type HttpRule struct { // used with any of the {get|put|post|delete|patch} methods. A custom method // can be defined using the 'custom' field. // - // Types that are valid to be assigned to Pattern: + // Types that are assignable to Pattern: // *HttpRule_Get // *HttpRule_Put // *HttpRule_Post @@ -383,84 +414,48 @@ type HttpRule struct { // Additional HTTP bindings for the selector. Nested bindings must // not contain an `additional_bindings` field themselves (that is, // the nesting may only be one level deep). - AdditionalBindings []*HttpRule `protobuf:"bytes,11,rep,name=additional_bindings,json=additionalBindings,proto3" json:"additional_bindings,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + AdditionalBindings []*HttpRule `protobuf:"bytes,11,rep,name=additional_bindings,json=additionalBindings,proto3" json:"additional_bindings,omitempty"` } -func (m *HttpRule) Reset() { *m = HttpRule{} } -func (m *HttpRule) String() string { return proto.CompactTextString(m) } -func (*HttpRule) ProtoMessage() {} -func (*HttpRule) Descriptor() ([]byte, []int) { - return fileDescriptor_ff9994be407cdcc9, []int{1} -} - -func (m *HttpRule) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_HttpRule.Unmarshal(m, b) -} -func (m *HttpRule) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_HttpRule.Marshal(b, m, deterministic) -} -func (m *HttpRule) XXX_Merge(src proto.Message) { - xxx_messageInfo_HttpRule.Merge(m, src) -} -func (m *HttpRule) XXX_Size() int { - return xxx_messageInfo_HttpRule.Size(m) -} -func (m *HttpRule) XXX_DiscardUnknown() { - xxx_messageInfo_HttpRule.DiscardUnknown(m) -} - -var xxx_messageInfo_HttpRule proto.InternalMessageInfo - -func (m *HttpRule) GetSelector() string { - if m != nil { - return m.Selector +func (x *HttpRule) Reset() { + *x = HttpRule{} + if protoimpl.UnsafeEnabled { + mi := &file_google_api_http_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } - return "" } -type isHttpRule_Pattern interface { - isHttpRule_Pattern() +func (x *HttpRule) String() string { + return protoimpl.X.MessageStringOf(x) } -type HttpRule_Get struct { - Get string `protobuf:"bytes,2,opt,name=get,proto3,oneof"` -} - -type HttpRule_Put struct { - Put string `protobuf:"bytes,3,opt,name=put,proto3,oneof"` -} - -type HttpRule_Post struct { - Post string `protobuf:"bytes,4,opt,name=post,proto3,oneof"` -} +func (*HttpRule) ProtoMessage() {} -type HttpRule_Delete struct { - Delete string `protobuf:"bytes,5,opt,name=delete,proto3,oneof"` +func (x *HttpRule) ProtoReflect() protoreflect.Message { + mi := &file_google_api_http_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -type HttpRule_Patch struct { - Patch string `protobuf:"bytes,6,opt,name=patch,proto3,oneof"` +// Deprecated: Use HttpRule.ProtoReflect.Descriptor instead. +func (*HttpRule) Descriptor() ([]byte, []int) { + return file_google_api_http_proto_rawDescGZIP(), []int{1} } -type HttpRule_Custom struct { - Custom *CustomHttpPattern `protobuf:"bytes,8,opt,name=custom,proto3,oneof"` +func (x *HttpRule) GetSelector() string { + if x != nil { + return x.Selector + } + return "" } -func (*HttpRule_Get) isHttpRule_Pattern() {} - -func (*HttpRule_Put) isHttpRule_Pattern() {} - -func (*HttpRule_Post) isHttpRule_Pattern() {} - -func (*HttpRule_Delete) isHttpRule_Pattern() {} - -func (*HttpRule_Patch) isHttpRule_Pattern() {} - -func (*HttpRule_Custom) isHttpRule_Pattern() {} - func (m *HttpRule) GetPattern() isHttpRule_Pattern { if m != nil { return m.Pattern @@ -468,168 +463,321 @@ func (m *HttpRule) GetPattern() isHttpRule_Pattern { return nil } -func (m *HttpRule) GetGet() string { - if x, ok := m.GetPattern().(*HttpRule_Get); ok { +func (x *HttpRule) GetGet() string { + if x, ok := x.GetPattern().(*HttpRule_Get); ok { return x.Get } return "" } -func (m *HttpRule) GetPut() string { - if x, ok := m.GetPattern().(*HttpRule_Put); ok { +func (x *HttpRule) GetPut() string { + if x, ok := x.GetPattern().(*HttpRule_Put); ok { return x.Put } return "" } -func (m *HttpRule) GetPost() string { - if x, ok := m.GetPattern().(*HttpRule_Post); ok { +func (x *HttpRule) GetPost() string { + if x, ok := x.GetPattern().(*HttpRule_Post); ok { return x.Post } return "" } -func (m *HttpRule) GetDelete() string { - if x, ok := m.GetPattern().(*HttpRule_Delete); ok { +func (x *HttpRule) GetDelete() string { + if x, ok := x.GetPattern().(*HttpRule_Delete); ok { return x.Delete } return "" } -func (m *HttpRule) GetPatch() string { - if x, ok := m.GetPattern().(*HttpRule_Patch); ok { +func (x *HttpRule) GetPatch() string { + if x, ok := x.GetPattern().(*HttpRule_Patch); ok { return x.Patch } return "" } -func (m *HttpRule) GetCustom() *CustomHttpPattern { - if x, ok := m.GetPattern().(*HttpRule_Custom); ok { +func (x *HttpRule) GetCustom() *CustomHttpPattern { + if x, ok := x.GetPattern().(*HttpRule_Custom); ok { return x.Custom } return nil } -func (m *HttpRule) GetBody() string { - if m != nil { - return m.Body +func (x *HttpRule) GetBody() string { + if x != nil { + return x.Body } return "" } -func (m *HttpRule) GetResponseBody() string { - if m != nil { - return m.ResponseBody +func (x *HttpRule) GetResponseBody() string { + if x != nil { + return x.ResponseBody } return "" } -func (m *HttpRule) GetAdditionalBindings() []*HttpRule { - if m != nil { - return m.AdditionalBindings +func (x *HttpRule) GetAdditionalBindings() []*HttpRule { + if x != nil { + return x.AdditionalBindings } return nil } -// XXX_OneofWrappers is for the internal use of the proto package. -func (*HttpRule) XXX_OneofWrappers() []interface{} { - return []interface{}{ - (*HttpRule_Get)(nil), - (*HttpRule_Put)(nil), - (*HttpRule_Post)(nil), - (*HttpRule_Delete)(nil), - (*HttpRule_Patch)(nil), - (*HttpRule_Custom)(nil), - } +type isHttpRule_Pattern interface { + isHttpRule_Pattern() } +type HttpRule_Get struct { + // Maps to HTTP GET. Used for listing and getting information about + // resources. + Get string `protobuf:"bytes,2,opt,name=get,proto3,oneof"` +} + +type HttpRule_Put struct { + // Maps to HTTP PUT. Used for replacing a resource. + Put string `protobuf:"bytes,3,opt,name=put,proto3,oneof"` +} + +type HttpRule_Post struct { + // Maps to HTTP POST. Used for creating a resource or performing an action. + Post string `protobuf:"bytes,4,opt,name=post,proto3,oneof"` +} + +type HttpRule_Delete struct { + // Maps to HTTP DELETE. Used for deleting a resource. + Delete string `protobuf:"bytes,5,opt,name=delete,proto3,oneof"` +} + +type HttpRule_Patch struct { + // Maps to HTTP PATCH. Used for updating a resource. + Patch string `protobuf:"bytes,6,opt,name=patch,proto3,oneof"` +} + +type HttpRule_Custom struct { + // The custom pattern is used for specifying an HTTP method that is not + // included in the `pattern` field, such as HEAD, or "*" to leave the + // HTTP method unspecified for this rule. The wild-card rule is useful + // for services that provide content to Web (HTML) clients. + Custom *CustomHttpPattern `protobuf:"bytes,8,opt,name=custom,proto3,oneof"` +} + +func (*HttpRule_Get) isHttpRule_Pattern() {} + +func (*HttpRule_Put) isHttpRule_Pattern() {} + +func (*HttpRule_Post) isHttpRule_Pattern() {} + +func (*HttpRule_Delete) isHttpRule_Pattern() {} + +func (*HttpRule_Patch) isHttpRule_Pattern() {} + +func (*HttpRule_Custom) isHttpRule_Pattern() {} + // A custom pattern is used for defining custom HTTP verb. type CustomHttpPattern struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // The name of this custom HTTP verb. Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"` // The path matched by this custom verb. - Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"` } -func (m *CustomHttpPattern) Reset() { *m = CustomHttpPattern{} } -func (m *CustomHttpPattern) String() string { return proto.CompactTextString(m) } -func (*CustomHttpPattern) ProtoMessage() {} -func (*CustomHttpPattern) Descriptor() ([]byte, []int) { - return fileDescriptor_ff9994be407cdcc9, []int{2} +func (x *CustomHttpPattern) Reset() { + *x = CustomHttpPattern{} + if protoimpl.UnsafeEnabled { + mi := &file_google_api_http_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *CustomHttpPattern) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_CustomHttpPattern.Unmarshal(m, b) +func (x *CustomHttpPattern) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *CustomHttpPattern) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_CustomHttpPattern.Marshal(b, m, deterministic) -} -func (m *CustomHttpPattern) XXX_Merge(src proto.Message) { - xxx_messageInfo_CustomHttpPattern.Merge(m, src) -} -func (m *CustomHttpPattern) XXX_Size() int { - return xxx_messageInfo_CustomHttpPattern.Size(m) -} -func (m *CustomHttpPattern) XXX_DiscardUnknown() { - xxx_messageInfo_CustomHttpPattern.DiscardUnknown(m) + +func (*CustomHttpPattern) ProtoMessage() {} + +func (x *CustomHttpPattern) ProtoReflect() protoreflect.Message { + mi := &file_google_api_http_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_CustomHttpPattern proto.InternalMessageInfo +// Deprecated: Use CustomHttpPattern.ProtoReflect.Descriptor instead. +func (*CustomHttpPattern) Descriptor() ([]byte, []int) { + return file_google_api_http_proto_rawDescGZIP(), []int{2} +} -func (m *CustomHttpPattern) GetKind() string { - if m != nil { - return m.Kind +func (x *CustomHttpPattern) GetKind() string { + if x != nil { + return x.Kind } return "" } -func (m *CustomHttpPattern) GetPath() string { - if m != nil { - return m.Path +func (x *CustomHttpPattern) GetPath() string { + if x != nil { + return x.Path } return "" } -func init() { - proto.RegisterType((*Http)(nil), "google.api.Http") - proto.RegisterType((*HttpRule)(nil), "google.api.HttpRule") - proto.RegisterType((*CustomHttpPattern)(nil), "google.api.CustomHttpPattern") -} - -func init() { - proto.RegisterFile("google/api/http.proto", fileDescriptor_ff9994be407cdcc9) -} - -var fileDescriptor_ff9994be407cdcc9 = []byte{ - // 419 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0xc1, 0x8e, 0xd3, 0x30, - 0x10, 0x86, 0x49, 0x9b, 0x76, 0xdb, 0xe9, 0x82, 0x84, 0x59, 0x90, 0x85, 0x40, 0x54, 0xe5, 0x52, - 0x71, 0x48, 0xa5, 0xe5, 0xc0, 0x61, 0x4f, 0x1b, 0xa8, 0x58, 0x6e, 0x55, 0x8e, 0x5c, 0x22, 0x37, - 0x1e, 0x52, 0x83, 0xd7, 0xb6, 0xe2, 0x09, 0xa2, 0xaf, 0xc3, 0x63, 0xf1, 0x24, 0x1c, 0x91, 0x9d, - 0x84, 0x56, 0x42, 0xe2, 0x36, 0xf3, 0xff, 0x9f, 0xa7, 0x7f, 0x27, 0x03, 0x4f, 0x6b, 0x6b, 0x6b, - 0x8d, 0x1b, 0xe1, 0xd4, 0xe6, 0x40, 0xe4, 0x32, 0xd7, 0x58, 0xb2, 0x0c, 0x3a, 0x39, 0x13, 0x4e, - 0xad, 0x8e, 0x90, 0xde, 0x11, 0x39, 0xf6, 0x06, 0x26, 0x4d, 0xab, 0xd1, 0xf3, 0x64, 0x39, 0x5e, - 0x2f, 0xae, 0xaf, 0xb2, 0x13, 0x93, 0x05, 0xa0, 0x68, 0x35, 0x16, 0x1d, 0xc2, 0xb6, 0xf0, 0xea, - 0x4b, 0xab, 0xf5, 0xb1, 0x94, 0x58, 0x59, 0x89, 0x65, 0x83, 0x1e, 0x9b, 0xef, 0x28, 0x4b, 0xfc, - 0xe1, 0x84, 0xf1, 0xca, 0x1a, 0x3e, 0x5a, 0x26, 0xeb, 0x59, 0xf1, 0x22, 0x62, 0x1f, 0x22, 0x55, - 0xf4, 0xd0, 0x76, 0x60, 0x56, 0xbf, 0x46, 0x30, 0x1b, 0x46, 0xb3, 0xe7, 0x30, 0xf3, 0xa8, 0xb1, - 0x22, 0xdb, 0xf0, 0x64, 0x99, 0xac, 0xe7, 0xc5, 0xdf, 0x9e, 0x31, 0x18, 0xd7, 0x48, 0x71, 0xe6, - 0xfc, 0xee, 0x41, 0x11, 0x9a, 0xa0, 0xb9, 0x96, 0xf8, 0x78, 0xd0, 0x5c, 0x4b, 0xec, 0x0a, 0x52, - 0x67, 0x3d, 0xf1, 0xb4, 0x17, 0x63, 0xc7, 0x38, 0x4c, 0x25, 0x6a, 0x24, 0xe4, 0x93, 0x5e, 0xef, - 0x7b, 0xf6, 0x0c, 0x26, 0x4e, 0x50, 0x75, 0xe0, 0xd3, 0xde, 0xe8, 0x5a, 0xf6, 0x0e, 0xa6, 0x55, - 0xeb, 0xc9, 0xde, 0xf3, 0xd9, 0x32, 0x59, 0x2f, 0xae, 0x5f, 0x9e, 0x2f, 0xe3, 0x7d, 0x74, 0x42, - 0xee, 0x9d, 0x20, 0xc2, 0xc6, 0x84, 0x81, 0x1d, 0xce, 0x18, 0xa4, 0x7b, 0x2b, 0x8f, 0xfc, 0x22, - 0xfe, 0x81, 0x58, 0xb3, 0xd7, 0xf0, 0xb0, 0x41, 0xef, 0xac, 0xf1, 0x58, 0x46, 0xf3, 0x32, 0x9a, - 0x97, 0x83, 0x98, 0x07, 0x68, 0x0b, 0x4f, 0x84, 0x94, 0x8a, 0x94, 0x35, 0x42, 0x97, 0x7b, 0x65, - 0xa4, 0x32, 0xb5, 0xe7, 0x8b, 0xff, 0x7c, 0x0b, 0x76, 0x7a, 0x90, 0xf7, 0x7c, 0x3e, 0x87, 0x0b, - 0xd7, 0x85, 0x5a, 0xdd, 0xc0, 0xe3, 0x7f, 0x92, 0x86, 0x7c, 0xdf, 0x94, 0x91, 0xfd, 0x82, 0x63, - 0x1d, 0x34, 0x27, 0xe8, 0xd0, 0x6d, 0xb7, 0x88, 0x75, 0xfe, 0x15, 0x1e, 0x55, 0xf6, 0xfe, 0xec, - 0x67, 0xf3, 0x79, 0x1c, 0x13, 0xae, 0x67, 0x97, 0x7c, 0xbe, 0xed, 0x8d, 0xda, 0x6a, 0x61, 0xea, - 0xcc, 0x36, 0xf5, 0xa6, 0x46, 0x13, 0x6f, 0x6b, 0xd3, 0x59, 0xc2, 0x29, 0x1f, 0xaf, 0x4e, 0x18, - 0x63, 0x49, 0x84, 0x98, 0xfe, 0xe6, 0xac, 0xfe, 0x9d, 0x24, 0x3f, 0x47, 0xe9, 0xc7, 0xdb, 0xdd, - 0xa7, 0xfd, 0x34, 0xbe, 0x7b, 0xfb, 0x27, 0x00, 0x00, 0xff, 0xff, 0xae, 0xde, 0xa1, 0xd0, 0xac, - 0x02, 0x00, 0x00, +var File_google_api_http_proto protoreflect.FileDescriptor + +var file_google_api_http_proto_rawDesc = []byte{ + 0x0a, 0x15, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x68, 0x74, 0x74, + 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x61, 0x70, 0x69, 0x22, 0x79, 0x0a, 0x04, 0x48, 0x74, 0x74, 0x70, 0x12, 0x2a, 0x0a, 0x05, 0x72, + 0x75, 0x6c, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x52, 0x75, 0x6c, 0x65, + 0x52, 0x05, 0x72, 0x75, 0x6c, 0x65, 0x73, 0x12, 0x45, 0x0a, 0x1f, 0x66, 0x75, 0x6c, 0x6c, 0x79, + 0x5f, 0x64, 0x65, 0x63, 0x6f, 0x64, 0x65, 0x5f, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, + 0x5f, 0x65, 0x78, 0x70, 0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, + 0x52, 0x1c, 0x66, 0x75, 0x6c, 0x6c, 0x79, 0x44, 0x65, 0x63, 0x6f, 0x64, 0x65, 0x52, 0x65, 0x73, + 0x65, 0x72, 0x76, 0x65, 0x64, 0x45, 0x78, 0x70, 0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0xda, + 0x02, 0x0a, 0x08, 0x48, 0x74, 0x74, 0x70, 0x52, 0x75, 0x6c, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x73, + 0x65, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, + 0x65, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x12, 0x12, 0x0a, 0x03, 0x67, 0x65, 0x74, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x03, 0x67, 0x65, 0x74, 0x12, 0x12, 0x0a, 0x03, 0x70, + 0x75, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x03, 0x70, 0x75, 0x74, 0x12, + 0x14, 0x0a, 0x04, 0x70, 0x6f, 0x73, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, + 0x04, 0x70, 0x6f, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x06, 0x64, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x18, + 0x05, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x06, 0x64, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x12, + 0x16, 0x0a, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, + 0x52, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x12, 0x37, 0x0a, 0x06, 0x63, 0x75, 0x73, 0x74, 0x6f, + 0x6d, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x48, 0x74, 0x74, 0x70, 0x50, + 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x48, 0x00, 0x52, 0x06, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, + 0x12, 0x12, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, + 0x62, 0x6f, 0x64, 0x79, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x5f, 0x62, 0x6f, 0x64, 0x79, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x72, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x6f, 0x64, 0x79, 0x12, 0x45, 0x0a, 0x13, 0x61, 0x64, 0x64, + 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x73, + 0x18, 0x0b, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x61, 0x70, 0x69, 0x2e, 0x48, 0x74, 0x74, 0x70, 0x52, 0x75, 0x6c, 0x65, 0x52, 0x12, 0x61, 0x64, + 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x42, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x73, + 0x42, 0x09, 0x0a, 0x07, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x22, 0x3b, 0x0a, 0x11, 0x43, + 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x48, 0x74, 0x74, 0x70, 0x50, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, + 0x12, 0x12, 0x0a, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, + 0x6b, 0x69, 0x6e, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x42, 0x6a, 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x42, 0x09, 0x48, 0x74, 0x74, 0x70, + 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x41, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, + 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3b, 0x61, + 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x04, + 0x47, 0x41, 0x50, 0x49, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_google_api_http_proto_rawDescOnce sync.Once + file_google_api_http_proto_rawDescData = file_google_api_http_proto_rawDesc +) + +func file_google_api_http_proto_rawDescGZIP() []byte { + file_google_api_http_proto_rawDescOnce.Do(func() { + file_google_api_http_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_api_http_proto_rawDescData) + }) + return file_google_api_http_proto_rawDescData +} + +var file_google_api_http_proto_msgTypes = make([]protoimpl.MessageInfo, 3) +var file_google_api_http_proto_goTypes = []interface{}{ + (*Http)(nil), // 0: google.api.Http + (*HttpRule)(nil), // 1: google.api.HttpRule + (*CustomHttpPattern)(nil), // 2: google.api.CustomHttpPattern +} +var file_google_api_http_proto_depIdxs = []int32{ + 1, // 0: google.api.Http.rules:type_name -> google.api.HttpRule + 2, // 1: google.api.HttpRule.custom:type_name -> google.api.CustomHttpPattern + 1, // 2: google.api.HttpRule.additional_bindings:type_name -> google.api.HttpRule + 3, // [3:3] is the sub-list for method output_type + 3, // [3:3] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_google_api_http_proto_init() } +func file_google_api_http_proto_init() { + if File_google_api_http_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_api_http_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Http); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_api_http_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*HttpRule); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_api_http_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CustomHttpPattern); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + file_google_api_http_proto_msgTypes[1].OneofWrappers = []interface{}{ + (*HttpRule_Get)(nil), + (*HttpRule_Put)(nil), + (*HttpRule_Post)(nil), + (*HttpRule_Delete)(nil), + (*HttpRule_Patch)(nil), + (*HttpRule_Custom)(nil), + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_api_http_proto_rawDesc, + NumEnums: 0, + NumMessages: 3, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_api_http_proto_goTypes, + DependencyIndexes: file_google_api_http_proto_depIdxs, + MessageInfos: file_google_api_http_proto_msgTypes, + }.Build() + File_google_api_http_proto = out.File + file_google_api_http_proto_rawDesc = nil + file_google_api_http_proto_goTypes = nil + file_google_api_http_proto_depIdxs = nil } diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go index d1d8eb54a3e..ff6147fe277 100644 --- a/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go @@ -1,26 +1,45 @@ +// Copyright 2020 Google LLC +// +// 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 protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.22.0 +// protoc v3.12.3 // source: google/api/resource.proto package annotations import ( - fmt "fmt" - math "math" + reflect "reflect" + sync "sync" proto "github.com/golang/protobuf/proto" descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 // A description of the historical or future-looking state of the // resource pattern. @@ -38,24 +57,45 @@ const ( ResourceDescriptor_FUTURE_MULTI_PATTERN ResourceDescriptor_History = 2 ) -var ResourceDescriptor_History_name = map[int32]string{ - 0: "HISTORY_UNSPECIFIED", - 1: "ORIGINALLY_SINGLE_PATTERN", - 2: "FUTURE_MULTI_PATTERN", -} +// Enum value maps for ResourceDescriptor_History. +var ( + ResourceDescriptor_History_name = map[int32]string{ + 0: "HISTORY_UNSPECIFIED", + 1: "ORIGINALLY_SINGLE_PATTERN", + 2: "FUTURE_MULTI_PATTERN", + } + ResourceDescriptor_History_value = map[string]int32{ + "HISTORY_UNSPECIFIED": 0, + "ORIGINALLY_SINGLE_PATTERN": 1, + "FUTURE_MULTI_PATTERN": 2, + } +) -var ResourceDescriptor_History_value = map[string]int32{ - "HISTORY_UNSPECIFIED": 0, - "ORIGINALLY_SINGLE_PATTERN": 1, - "FUTURE_MULTI_PATTERN": 2, +func (x ResourceDescriptor_History) Enum() *ResourceDescriptor_History { + p := new(ResourceDescriptor_History) + *p = x + return p } func (x ResourceDescriptor_History) String() string { - return proto.EnumName(ResourceDescriptor_History_name, int32(x)) + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ResourceDescriptor_History) Descriptor() protoreflect.EnumDescriptor { + return file_google_api_resource_proto_enumTypes[0].Descriptor() +} + +func (ResourceDescriptor_History) Type() protoreflect.EnumType { + return &file_google_api_resource_proto_enumTypes[0] +} + +func (x ResourceDescriptor_History) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) } +// Deprecated: Use ResourceDescriptor_History.Descriptor instead. func (ResourceDescriptor_History) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_465e9122405d1bb5, []int{0, 0} + return file_google_api_resource_proto_rawDescGZIP(), []int{0, 0} } // A simple descriptor of a resource type. @@ -82,12 +122,12 @@ func (ResourceDescriptor_History) EnumDescriptor() ([]byte, []int) { // // The ResourceDescriptor Yaml config will look like: // -// resources: -// - type: "pubsub.googleapis.com/Topic" -// name_descriptor: -// - pattern: "projects/{project}/topics/{topic}" -// parent_type: "cloudresourcemanager.googleapis.com/Project" -// parent_name_extractor: "projects/{project}" +// resources: +// - type: "pubsub.googleapis.com/Topic" +// name_descriptor: +// - pattern: "projects/{project}/topics/{topic}" +// parent_type: "cloudresourcemanager.googleapis.com/Project" +// parent_name_extractor: "projects/{project}" // // Sometimes, resources have multiple patterns, typically because they can // live under multiple parents. @@ -167,6 +207,10 @@ func (ResourceDescriptor_History) EnumDescriptor() ([]byte, []int) { // - pattern: "shelves/{shelf}" // parent_type: "cloudresourcemanager.googleapis.com/Folder" type ResourceDescriptor struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // The resource type. It must be in the format of // {service_name}/{resource_type_kind}. The `resource_type_kind` must be // singular and must not include version numbers. @@ -217,83 +261,91 @@ type ResourceDescriptor struct { // }; // } History ResourceDescriptor_History `protobuf:"varint,4,opt,name=history,proto3,enum=google.api.ResourceDescriptor_History" json:"history,omitempty"` - // The plural name used in the resource name, such as 'projects' for - // the name of 'projects/{project}'. It is the same concept of the `plural` - // field in k8s CRD spec + // The plural name used in the resource name and permission names, such as + // 'projects' for the resource name of 'projects/{project}' and the permission + // name of 'cloudresourcemanager.googleapis.com/projects.get'. It is the same + // concept of the `plural` field in k8s CRD spec // https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ + // + // Note: The plural form is required even for singleton resources. See + // https://aip.dev/156 Plural string `protobuf:"bytes,5,opt,name=plural,proto3" json:"plural,omitempty"` // The same concept of the `singular` field in k8s CRD spec // https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ // Such as "project" for the `resourcemanager.googleapis.com/Project` type. - Singular string `protobuf:"bytes,6,opt,name=singular,proto3" json:"singular,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Singular string `protobuf:"bytes,6,opt,name=singular,proto3" json:"singular,omitempty"` } -func (m *ResourceDescriptor) Reset() { *m = ResourceDescriptor{} } -func (m *ResourceDescriptor) String() string { return proto.CompactTextString(m) } -func (*ResourceDescriptor) ProtoMessage() {} -func (*ResourceDescriptor) Descriptor() ([]byte, []int) { - return fileDescriptor_465e9122405d1bb5, []int{0} +func (x *ResourceDescriptor) Reset() { + *x = ResourceDescriptor{} + if protoimpl.UnsafeEnabled { + mi := &file_google_api_resource_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *ResourceDescriptor) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ResourceDescriptor.Unmarshal(m, b) -} -func (m *ResourceDescriptor) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ResourceDescriptor.Marshal(b, m, deterministic) +func (x *ResourceDescriptor) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *ResourceDescriptor) XXX_Merge(src proto.Message) { - xxx_messageInfo_ResourceDescriptor.Merge(m, src) -} -func (m *ResourceDescriptor) XXX_Size() int { - return xxx_messageInfo_ResourceDescriptor.Size(m) -} -func (m *ResourceDescriptor) XXX_DiscardUnknown() { - xxx_messageInfo_ResourceDescriptor.DiscardUnknown(m) + +func (*ResourceDescriptor) ProtoMessage() {} + +func (x *ResourceDescriptor) ProtoReflect() protoreflect.Message { + mi := &file_google_api_resource_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_ResourceDescriptor proto.InternalMessageInfo +// Deprecated: Use ResourceDescriptor.ProtoReflect.Descriptor instead. +func (*ResourceDescriptor) Descriptor() ([]byte, []int) { + return file_google_api_resource_proto_rawDescGZIP(), []int{0} +} -func (m *ResourceDescriptor) GetType() string { - if m != nil { - return m.Type +func (x *ResourceDescriptor) GetType() string { + if x != nil { + return x.Type } return "" } -func (m *ResourceDescriptor) GetPattern() []string { - if m != nil { - return m.Pattern +func (x *ResourceDescriptor) GetPattern() []string { + if x != nil { + return x.Pattern } return nil } -func (m *ResourceDescriptor) GetNameField() string { - if m != nil { - return m.NameField +func (x *ResourceDescriptor) GetNameField() string { + if x != nil { + return x.NameField } return "" } -func (m *ResourceDescriptor) GetHistory() ResourceDescriptor_History { - if m != nil { - return m.History +func (x *ResourceDescriptor) GetHistory() ResourceDescriptor_History { + if x != nil { + return x.History } return ResourceDescriptor_HISTORY_UNSPECIFIED } -func (m *ResourceDescriptor) GetPlural() string { - if m != nil { - return m.Plural +func (x *ResourceDescriptor) GetPlural() string { + if x != nil { + return x.Plural } return "" } -func (m *ResourceDescriptor) GetSingular() string { - if m != nil { - return m.Singular +func (x *ResourceDescriptor) GetSingular() string { + if x != nil { + return x.Singular } return "" } @@ -301,6 +353,10 @@ func (m *ResourceDescriptor) GetSingular() string { // Defines a proto annotation that describes a string field that refers to // an API resource. type ResourceReference struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // The resource type that the annotated field references. // // Example: @@ -310,6 +366,17 @@ type ResourceReference struct { // type: "pubsub.googleapis.com/Topic" // }]; // } + // + // Occasionally, a field may reference an arbitrary resource. In this case, + // APIs use the special value * in their resource reference. + // + // Example: + // + // message GetIamPolicyRequest { + // string resource = 2 [(google.api.resource_reference) = { + // type: "*" + // }]; + // } Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` // The resource type of a child collection that the annotated field // references. This is useful for annotating the `parent` field that @@ -317,127 +384,261 @@ type ResourceReference struct { // // Example: // - // message ListLogEntriesRequest { - // string parent = 1 [(google.api.resource_reference) = { - // child_type: "logging.googleapis.com/LogEntry" - // }; - // } - ChildType string `protobuf:"bytes,2,opt,name=child_type,json=childType,proto3" json:"child_type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + // message ListLogEntriesRequest { + // string parent = 1 [(google.api.resource_reference) = { + // child_type: "logging.googleapis.com/LogEntry" + // }; + // } + ChildType string `protobuf:"bytes,2,opt,name=child_type,json=childType,proto3" json:"child_type,omitempty"` } -func (m *ResourceReference) Reset() { *m = ResourceReference{} } -func (m *ResourceReference) String() string { return proto.CompactTextString(m) } -func (*ResourceReference) ProtoMessage() {} -func (*ResourceReference) Descriptor() ([]byte, []int) { - return fileDescriptor_465e9122405d1bb5, []int{1} +func (x *ResourceReference) Reset() { + *x = ResourceReference{} + if protoimpl.UnsafeEnabled { + mi := &file_google_api_resource_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *ResourceReference) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ResourceReference.Unmarshal(m, b) -} -func (m *ResourceReference) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ResourceReference.Marshal(b, m, deterministic) -} -func (m *ResourceReference) XXX_Merge(src proto.Message) { - xxx_messageInfo_ResourceReference.Merge(m, src) -} -func (m *ResourceReference) XXX_Size() int { - return xxx_messageInfo_ResourceReference.Size(m) -} -func (m *ResourceReference) XXX_DiscardUnknown() { - xxx_messageInfo_ResourceReference.DiscardUnknown(m) +func (x *ResourceReference) String() string { + return protoimpl.X.MessageStringOf(x) } -var xxx_messageInfo_ResourceReference proto.InternalMessageInfo +func (*ResourceReference) ProtoMessage() {} -func (m *ResourceReference) GetType() string { - if m != nil { - return m.Type +func (x *ResourceReference) ProtoReflect() protoreflect.Message { + mi := &file_google_api_resource_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms } - return "" + return mi.MessageOf(x) } -func (m *ResourceReference) GetChildType() string { - if m != nil { - return m.ChildType +// Deprecated: Use ResourceReference.ProtoReflect.Descriptor instead. +func (*ResourceReference) Descriptor() ([]byte, []int) { + return file_google_api_resource_proto_rawDescGZIP(), []int{1} +} + +func (x *ResourceReference) GetType() string { + if x != nil { + return x.Type } return "" } -var E_ResourceReference = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.FieldOptions)(nil), - ExtensionType: (*ResourceReference)(nil), - Field: 1055, - Name: "google.api.resource_reference", - Tag: "bytes,1055,opt,name=resource_reference", - Filename: "google/api/resource.proto", +func (x *ResourceReference) GetChildType() string { + if x != nil { + return x.ChildType + } + return "" } -var E_ResourceDefinition = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.FileOptions)(nil), - ExtensionType: ([]*ResourceDescriptor)(nil), - Field: 1053, - Name: "google.api.resource_definition", - Tag: "bytes,1053,rep,name=resource_definition", - Filename: "google/api/resource.proto", -} +var file_google_api_resource_proto_extTypes = []protoimpl.ExtensionInfo{ + { + ExtendedType: (*descriptor.FieldOptions)(nil), + ExtensionType: (*ResourceReference)(nil), + Field: 1055, + Name: "google.api.resource_reference", + Tag: "bytes,1055,opt,name=resource_reference", + Filename: "google/api/resource.proto", + }, + { + ExtendedType: (*descriptor.FileOptions)(nil), + ExtensionType: ([]*ResourceDescriptor)(nil), + Field: 1053, + Name: "google.api.resource_definition", + Tag: "bytes,1053,rep,name=resource_definition", + Filename: "google/api/resource.proto", + }, + { + ExtendedType: (*descriptor.MessageOptions)(nil), + ExtensionType: (*ResourceDescriptor)(nil), + Field: 1053, + Name: "google.api.resource", + Tag: "bytes,1053,opt,name=resource", + Filename: "google/api/resource.proto", + }, +} + +// Extension fields to descriptor.FieldOptions. +var ( + // An annotation that describes a resource reference, see + // [ResourceReference][]. + // + // optional google.api.ResourceReference resource_reference = 1055; + E_ResourceReference = &file_google_api_resource_proto_extTypes[0] +) -var E_Resource = &proto.ExtensionDesc{ - ExtendedType: (*descriptor.MessageOptions)(nil), - ExtensionType: (*ResourceDescriptor)(nil), - Field: 1053, - Name: "google.api.resource", - Tag: "bytes,1053,opt,name=resource", - Filename: "google/api/resource.proto", -} +// Extension fields to descriptor.FileOptions. +var ( + // An annotation that describes a resource definition without a corresponding + // message; see [ResourceDescriptor][]. + // + // repeated google.api.ResourceDescriptor resource_definition = 1053; + E_ResourceDefinition = &file_google_api_resource_proto_extTypes[1] +) -func init() { - proto.RegisterEnum("google.api.ResourceDescriptor_History", ResourceDescriptor_History_name, ResourceDescriptor_History_value) - proto.RegisterType((*ResourceDescriptor)(nil), "google.api.ResourceDescriptor") - proto.RegisterType((*ResourceReference)(nil), "google.api.ResourceReference") - proto.RegisterExtension(E_ResourceReference) - proto.RegisterExtension(E_ResourceDefinition) - proto.RegisterExtension(E_Resource) -} +// Extension fields to descriptor.MessageOptions. +var ( + // An annotation that describes a resource definition, see + // [ResourceDescriptor][]. + // + // optional google.api.ResourceDescriptor resource = 1053; + E_Resource = &file_google_api_resource_proto_extTypes[2] +) -func init() { - proto.RegisterFile("google/api/resource.proto", fileDescriptor_465e9122405d1bb5) -} +var File_google_api_resource_proto protoreflect.FileDescriptor + +var file_google_api_resource_proto_rawDesc = []byte{ + 0x0a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, + 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, + 0x74, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xb4, 0x02, 0x0a, 0x12, 0x52, 0x65, + 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, + 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, + 0x74, 0x79, 0x70, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x18, + 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x07, 0x70, 0x61, 0x74, 0x74, 0x65, 0x72, 0x6e, 0x12, 0x1d, + 0x0a, 0x0a, 0x6e, 0x61, 0x6d, 0x65, 0x5f, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x12, 0x40, 0x0a, + 0x07, 0x68, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x26, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x52, 0x65, 0x73, 0x6f, + 0x75, 0x72, 0x63, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x2e, 0x48, + 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x52, 0x07, 0x68, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x12, + 0x16, 0x0a, 0x06, 0x70, 0x6c, 0x75, 0x72, 0x61, 0x6c, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x06, 0x70, 0x6c, 0x75, 0x72, 0x61, 0x6c, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x69, 0x6e, 0x67, 0x75, + 0x6c, 0x61, 0x72, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x69, 0x6e, 0x67, 0x75, + 0x6c, 0x61, 0x72, 0x22, 0x5b, 0x0a, 0x07, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x12, 0x17, + 0x0a, 0x13, 0x48, 0x49, 0x53, 0x54, 0x4f, 0x52, 0x59, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, + 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x1d, 0x0a, 0x19, 0x4f, 0x52, 0x49, 0x47, 0x49, + 0x4e, 0x41, 0x4c, 0x4c, 0x59, 0x5f, 0x53, 0x49, 0x4e, 0x47, 0x4c, 0x45, 0x5f, 0x50, 0x41, 0x54, + 0x54, 0x45, 0x52, 0x4e, 0x10, 0x01, 0x12, 0x18, 0x0a, 0x14, 0x46, 0x55, 0x54, 0x55, 0x52, 0x45, + 0x5f, 0x4d, 0x55, 0x4c, 0x54, 0x49, 0x5f, 0x50, 0x41, 0x54, 0x54, 0x45, 0x52, 0x4e, 0x10, 0x02, + 0x22, 0x46, 0x0a, 0x11, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x65, 0x66, 0x65, + 0x72, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x68, 0x69, + 0x6c, 0x64, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x63, + 0x68, 0x69, 0x6c, 0x64, 0x54, 0x79, 0x70, 0x65, 0x3a, 0x6c, 0x0a, 0x12, 0x72, 0x65, 0x73, 0x6f, + 0x75, 0x72, 0x63, 0x65, 0x5f, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x1d, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9f, 0x08, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, + 0x69, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x65, 0x66, 0x65, 0x72, 0x65, + 0x6e, 0x63, 0x65, 0x52, 0x11, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x65, 0x66, + 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x3a, 0x6e, 0x0a, 0x13, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x5f, 0x64, 0x65, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1c, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x46, 0x69, 0x6c, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9d, 0x08, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, + 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, + 0x6f, 0x72, 0x52, 0x12, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x44, 0x65, 0x66, 0x69, + 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x5c, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x4f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x18, 0x9d, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, + 0x75, 0x72, 0x63, 0x65, 0x42, 0x6e, 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x42, 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x41, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, + 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3b, 0x61, + 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x04, + 0x47, 0x41, 0x50, 0x49, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_google_api_resource_proto_rawDescOnce sync.Once + file_google_api_resource_proto_rawDescData = file_google_api_resource_proto_rawDesc +) -var fileDescriptor_465e9122405d1bb5 = []byte{ - // 490 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x53, 0xcd, 0x6e, 0xd3, 0x4c, - 0x14, 0xfd, 0x9c, 0xe4, 0xcb, 0xcf, 0xad, 0xa8, 0xda, 0x29, 0x02, 0xb7, 0x22, 0x60, 0x65, 0x81, - 0xb2, 0xb2, 0xa5, 0xb0, 0x0b, 0x1b, 0x52, 0xe2, 0xa4, 0x96, 0xd2, 0xc4, 0x9a, 0x38, 0x8b, 0x02, - 0x92, 0x35, 0x75, 0x26, 0xee, 0x48, 0xee, 0xcc, 0x68, 0xec, 0x2c, 0xf2, 0x30, 0x08, 0x89, 0x67, - 0xe0, 0xe1, 0x58, 0xa2, 0x8c, 0x7f, 0x88, 0x68, 0x84, 0xd8, 0xcd, 0xbd, 0xe7, 0xde, 0x73, 0x8e, - 0xcf, 0x95, 0xe1, 0x32, 0x16, 0x22, 0x4e, 0xa8, 0x43, 0x24, 0x73, 0x14, 0x4d, 0xc5, 0x56, 0x45, - 0xd4, 0x96, 0x4a, 0x64, 0x02, 0x41, 0x0e, 0xd9, 0x44, 0xb2, 0x2b, 0xab, 0x18, 0xd3, 0xc8, 0xfd, - 0x76, 0xe3, 0xac, 0x69, 0x1a, 0x29, 0x26, 0x33, 0xa1, 0xf2, 0xe9, 0xde, 0x8f, 0x1a, 0x20, 0x5c, - 0x10, 0x8c, 0x2b, 0x10, 0x21, 0x68, 0x64, 0x3b, 0x49, 0x4d, 0xc3, 0x32, 0xfa, 0x1d, 0xac, 0xdf, - 0xc8, 0x84, 0x96, 0x24, 0x59, 0x46, 0x15, 0x37, 0x6b, 0x56, 0xbd, 0xdf, 0xc1, 0x65, 0x89, 0xba, - 0x00, 0x9c, 0x3c, 0xd2, 0x70, 0xc3, 0x68, 0xb2, 0x36, 0xeb, 0x7a, 0xa7, 0xb3, 0xef, 0x4c, 0xf6, - 0x0d, 0xf4, 0x01, 0x5a, 0x0f, 0x2c, 0xcd, 0x84, 0xda, 0x99, 0x0d, 0xcb, 0xe8, 0x9f, 0x0e, 0xde, - 0xda, 0xbf, 0x3d, 0xda, 0x4f, 0xd5, 0xed, 0x9b, 0x7c, 0x1a, 0x97, 0x6b, 0xe8, 0x05, 0x34, 0x65, - 0xb2, 0x55, 0x24, 0x31, 0xff, 0xd7, 0xe4, 0x45, 0x85, 0xae, 0xa0, 0x9d, 0x32, 0x1e, 0x6f, 0x13, - 0xa2, 0xcc, 0xa6, 0x46, 0xaa, 0xba, 0xf7, 0x19, 0x5a, 0x05, 0x0f, 0x7a, 0x09, 0x17, 0x37, 0xde, - 0x32, 0x58, 0xe0, 0xbb, 0x70, 0x35, 0x5f, 0xfa, 0xee, 0x47, 0x6f, 0xe2, 0xb9, 0xe3, 0xb3, 0xff, - 0x50, 0x17, 0x2e, 0x17, 0xd8, 0x9b, 0x7a, 0xf3, 0xd1, 0x6c, 0x76, 0x17, 0x2e, 0xbd, 0xf9, 0x74, - 0xe6, 0x86, 0xfe, 0x28, 0x08, 0x5c, 0x3c, 0x3f, 0x33, 0x90, 0x09, 0xcf, 0x27, 0xab, 0x60, 0x85, - 0xdd, 0xf0, 0x76, 0x35, 0x0b, 0xbc, 0x0a, 0xa9, 0xf5, 0x26, 0x70, 0x5e, 0xfa, 0xc6, 0x74, 0x43, - 0x15, 0xe5, 0x11, 0x3d, 0x1a, 0x5a, 0x17, 0x20, 0x7a, 0x60, 0xc9, 0x3a, 0xd4, 0x48, 0x2d, 0x8f, - 0x46, 0x77, 0x82, 0x9d, 0xa4, 0xc3, 0x04, 0x50, 0x79, 0xbe, 0x50, 0x55, 0x44, 0xdd, 0x32, 0x9f, - 0xf2, 0x6e, 0xb6, 0x0e, 0x72, 0x21, 0x33, 0x26, 0x78, 0x6a, 0x7e, 0x6b, 0x5b, 0x46, 0xff, 0x64, - 0xd0, 0x3d, 0x96, 0x62, 0xe5, 0x06, 0x9f, 0xab, 0x3f, 0x5b, 0x43, 0x0e, 0x17, 0x95, 0xda, 0x9a, - 0x6e, 0x18, 0x67, 0x7b, 0x42, 0xf4, 0xea, 0x88, 0x5c, 0x42, 0x4b, 0xb5, 0xaf, 0x6d, 0xab, 0xde, - 0x3f, 0x19, 0xbc, 0xfe, 0xfb, 0xcd, 0x70, 0xf5, 0x1d, 0xe3, 0x8a, 0x78, 0xf8, 0x05, 0xda, 0x65, - 0x17, 0xbd, 0x79, 0x22, 0x72, 0x4b, 0xd3, 0x94, 0xc4, 0x87, 0x3a, 0xc6, 0x3f, 0xe8, 0x54, 0x8c, - 0xd7, 0x1c, 0x4e, 0x23, 0xf1, 0x78, 0x30, 0x7e, 0xfd, 0xac, 0x9c, 0xf7, 0xf7, 0x1a, 0xbe, 0xf1, - 0x69, 0x54, 0x80, 0xb1, 0x48, 0x08, 0x8f, 0x6d, 0xa1, 0x62, 0x27, 0xa6, 0x5c, 0x3b, 0x70, 0x72, - 0x88, 0x48, 0x96, 0xea, 0xbf, 0x88, 0x70, 0x2e, 0x32, 0xa2, 0xad, 0xbc, 0x3f, 0x78, 0xff, 0x34, - 0x8c, 0xef, 0xb5, 0xc6, 0x74, 0xe4, 0x7b, 0xf7, 0x4d, 0xbd, 0xf7, 0xee, 0x57, 0x00, 0x00, 0x00, - 0xff, 0xff, 0x75, 0x12, 0x53, 0xef, 0x7c, 0x03, 0x00, 0x00, +func file_google_api_resource_proto_rawDescGZIP() []byte { + file_google_api_resource_proto_rawDescOnce.Do(func() { + file_google_api_resource_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_api_resource_proto_rawDescData) + }) + return file_google_api_resource_proto_rawDescData +} + +var file_google_api_resource_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_google_api_resource_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_google_api_resource_proto_goTypes = []interface{}{ + (ResourceDescriptor_History)(0), // 0: google.api.ResourceDescriptor.History + (*ResourceDescriptor)(nil), // 1: google.api.ResourceDescriptor + (*ResourceReference)(nil), // 2: google.api.ResourceReference + (*descriptor.FieldOptions)(nil), // 3: google.protobuf.FieldOptions + (*descriptor.FileOptions)(nil), // 4: google.protobuf.FileOptions + (*descriptor.MessageOptions)(nil), // 5: google.protobuf.MessageOptions +} +var file_google_api_resource_proto_depIdxs = []int32{ + 0, // 0: google.api.ResourceDescriptor.history:type_name -> google.api.ResourceDescriptor.History + 3, // 1: google.api.resource_reference:extendee -> google.protobuf.FieldOptions + 4, // 2: google.api.resource_definition:extendee -> google.protobuf.FileOptions + 5, // 3: google.api.resource:extendee -> google.protobuf.MessageOptions + 2, // 4: google.api.resource_reference:type_name -> google.api.ResourceReference + 1, // 5: google.api.resource_definition:type_name -> google.api.ResourceDescriptor + 1, // 6: google.api.resource:type_name -> google.api.ResourceDescriptor + 7, // [7:7] is the sub-list for method output_type + 7, // [7:7] is the sub-list for method input_type + 4, // [4:7] is the sub-list for extension type_name + 1, // [1:4] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_google_api_resource_proto_init() } +func file_google_api_resource_proto_init() { + if File_google_api_resource_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_api_resource_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ResourceDescriptor); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_api_resource_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ResourceReference); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_api_resource_proto_rawDesc, + NumEnums: 1, + NumMessages: 2, + NumExtensions: 3, + NumServices: 0, + }, + GoTypes: file_google_api_resource_proto_goTypes, + DependencyIndexes: file_google_api_resource_proto_depIdxs, + EnumInfos: file_google_api_resource_proto_enumTypes, + MessageInfos: file_google_api_resource_proto_msgTypes, + ExtensionInfos: file_google_api_resource_proto_extTypes, + }.Build() + File_google_api_resource_proto = out.File + file_google_api_resource_proto_rawDesc = nil + file_google_api_resource_proto_goTypes = nil + file_google_api_resource_proto_depIdxs = nil } diff --git a/vendor/google.golang.org/genproto/googleapis/iam/v1/iam_policy.pb.go b/vendor/google.golang.org/genproto/googleapis/iam/v1/iam_policy.pb.go index 9950ac2d325..375d3876535 100644 --- a/vendor/google.golang.org/genproto/googleapis/iam/v1/iam_policy.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/iam/v1/iam_policy.pb.go @@ -1,33 +1,57 @@ +// Copyright 2019 Google LLC. +// +// 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 protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.22.0 +// protoc v3.12.3 // source: google/iam/v1/iam_policy.proto package iam import ( context "context" - fmt "fmt" - math "math" + reflect "reflect" + sync "sync" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 // Request message for `SetIamPolicy` method. type SetIamPolicyRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // REQUIRED: The resource for which the policy is being specified. // See the operation documentation for the appropriate value for this field. Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` @@ -35,105 +59,121 @@ type SetIamPolicyRequest struct { // the policy is limited to a few 10s of KB. An empty policy is a // valid policy but certain Cloud Platform services (such as Projects) // might reject them. - Policy *Policy `protobuf:"bytes,2,opt,name=policy,proto3" json:"policy,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Policy *Policy `protobuf:"bytes,2,opt,name=policy,proto3" json:"policy,omitempty"` } -func (m *SetIamPolicyRequest) Reset() { *m = SetIamPolicyRequest{} } -func (m *SetIamPolicyRequest) String() string { return proto.CompactTextString(m) } -func (*SetIamPolicyRequest) ProtoMessage() {} -func (*SetIamPolicyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_d2728eb97d748a32, []int{0} +func (x *SetIamPolicyRequest) Reset() { + *x = SetIamPolicyRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_google_iam_v1_iam_policy_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *SetIamPolicyRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SetIamPolicyRequest.Unmarshal(m, b) -} -func (m *SetIamPolicyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SetIamPolicyRequest.Marshal(b, m, deterministic) +func (x *SetIamPolicyRequest) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *SetIamPolicyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_SetIamPolicyRequest.Merge(m, src) -} -func (m *SetIamPolicyRequest) XXX_Size() int { - return xxx_messageInfo_SetIamPolicyRequest.Size(m) -} -func (m *SetIamPolicyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_SetIamPolicyRequest.DiscardUnknown(m) + +func (*SetIamPolicyRequest) ProtoMessage() {} + +func (x *SetIamPolicyRequest) ProtoReflect() protoreflect.Message { + mi := &file_google_iam_v1_iam_policy_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_SetIamPolicyRequest proto.InternalMessageInfo +// Deprecated: Use SetIamPolicyRequest.ProtoReflect.Descriptor instead. +func (*SetIamPolicyRequest) Descriptor() ([]byte, []int) { + return file_google_iam_v1_iam_policy_proto_rawDescGZIP(), []int{0} +} -func (m *SetIamPolicyRequest) GetResource() string { - if m != nil { - return m.Resource +func (x *SetIamPolicyRequest) GetResource() string { + if x != nil { + return x.Resource } return "" } -func (m *SetIamPolicyRequest) GetPolicy() *Policy { - if m != nil { - return m.Policy +func (x *SetIamPolicyRequest) GetPolicy() *Policy { + if x != nil { + return x.Policy } return nil } // Request message for `GetIamPolicy` method. type GetIamPolicyRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // REQUIRED: The resource for which the policy is being requested. // See the operation documentation for the appropriate value for this field. Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` // OPTIONAL: A `GetPolicyOptions` object for specifying options to // `GetIamPolicy`. This field is only used by Cloud IAM. - Options *GetPolicyOptions `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Options *GetPolicyOptions `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` } -func (m *GetIamPolicyRequest) Reset() { *m = GetIamPolicyRequest{} } -func (m *GetIamPolicyRequest) String() string { return proto.CompactTextString(m) } -func (*GetIamPolicyRequest) ProtoMessage() {} -func (*GetIamPolicyRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_d2728eb97d748a32, []int{1} +func (x *GetIamPolicyRequest) Reset() { + *x = GetIamPolicyRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_google_iam_v1_iam_policy_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *GetIamPolicyRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetIamPolicyRequest.Unmarshal(m, b) +func (x *GetIamPolicyRequest) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *GetIamPolicyRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetIamPolicyRequest.Marshal(b, m, deterministic) -} -func (m *GetIamPolicyRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetIamPolicyRequest.Merge(m, src) -} -func (m *GetIamPolicyRequest) XXX_Size() int { - return xxx_messageInfo_GetIamPolicyRequest.Size(m) -} -func (m *GetIamPolicyRequest) XXX_DiscardUnknown() { - xxx_messageInfo_GetIamPolicyRequest.DiscardUnknown(m) + +func (*GetIamPolicyRequest) ProtoMessage() {} + +func (x *GetIamPolicyRequest) ProtoReflect() protoreflect.Message { + mi := &file_google_iam_v1_iam_policy_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_GetIamPolicyRequest proto.InternalMessageInfo +// Deprecated: Use GetIamPolicyRequest.ProtoReflect.Descriptor instead. +func (*GetIamPolicyRequest) Descriptor() ([]byte, []int) { + return file_google_iam_v1_iam_policy_proto_rawDescGZIP(), []int{1} +} -func (m *GetIamPolicyRequest) GetResource() string { - if m != nil { - return m.Resource +func (x *GetIamPolicyRequest) GetResource() string { + if x != nil { + return x.Resource } return "" } -func (m *GetIamPolicyRequest) GetOptions() *GetPolicyOptions { - if m != nil { - return m.Options +func (x *GetIamPolicyRequest) GetOptions() *GetPolicyOptions { + if x != nil { + return x.Options } return nil } // Request message for `TestIamPermissions` method. type TestIamPermissionsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // REQUIRED: The resource for which the policy detail is being requested. // See the operation documentation for the appropriate value for this field. Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` @@ -141,139 +181,298 @@ type TestIamPermissionsRequest struct { // wildcards (such as '*' or 'storage.*') are not allowed. For more // information see // [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). - Permissions []string `protobuf:"bytes,2,rep,name=permissions,proto3" json:"permissions,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Permissions []string `protobuf:"bytes,2,rep,name=permissions,proto3" json:"permissions,omitempty"` } -func (m *TestIamPermissionsRequest) Reset() { *m = TestIamPermissionsRequest{} } -func (m *TestIamPermissionsRequest) String() string { return proto.CompactTextString(m) } -func (*TestIamPermissionsRequest) ProtoMessage() {} -func (*TestIamPermissionsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_d2728eb97d748a32, []int{2} +func (x *TestIamPermissionsRequest) Reset() { + *x = TestIamPermissionsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_google_iam_v1_iam_policy_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *TestIamPermissionsRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TestIamPermissionsRequest.Unmarshal(m, b) -} -func (m *TestIamPermissionsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TestIamPermissionsRequest.Marshal(b, m, deterministic) -} -func (m *TestIamPermissionsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_TestIamPermissionsRequest.Merge(m, src) -} -func (m *TestIamPermissionsRequest) XXX_Size() int { - return xxx_messageInfo_TestIamPermissionsRequest.Size(m) +func (x *TestIamPermissionsRequest) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *TestIamPermissionsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_TestIamPermissionsRequest.DiscardUnknown(m) + +func (*TestIamPermissionsRequest) ProtoMessage() {} + +func (x *TestIamPermissionsRequest) ProtoReflect() protoreflect.Message { + mi := &file_google_iam_v1_iam_policy_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_TestIamPermissionsRequest proto.InternalMessageInfo +// Deprecated: Use TestIamPermissionsRequest.ProtoReflect.Descriptor instead. +func (*TestIamPermissionsRequest) Descriptor() ([]byte, []int) { + return file_google_iam_v1_iam_policy_proto_rawDescGZIP(), []int{2} +} -func (m *TestIamPermissionsRequest) GetResource() string { - if m != nil { - return m.Resource +func (x *TestIamPermissionsRequest) GetResource() string { + if x != nil { + return x.Resource } return "" } -func (m *TestIamPermissionsRequest) GetPermissions() []string { - if m != nil { - return m.Permissions +func (x *TestIamPermissionsRequest) GetPermissions() []string { + if x != nil { + return x.Permissions } return nil } // Response message for `TestIamPermissions` method. type TestIamPermissionsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // A subset of `TestPermissionsRequest.permissions` that the caller is // allowed. - Permissions []string `protobuf:"bytes,1,rep,name=permissions,proto3" json:"permissions,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Permissions []string `protobuf:"bytes,1,rep,name=permissions,proto3" json:"permissions,omitempty"` } -func (m *TestIamPermissionsResponse) Reset() { *m = TestIamPermissionsResponse{} } -func (m *TestIamPermissionsResponse) String() string { return proto.CompactTextString(m) } -func (*TestIamPermissionsResponse) ProtoMessage() {} -func (*TestIamPermissionsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_d2728eb97d748a32, []int{3} +func (x *TestIamPermissionsResponse) Reset() { + *x = TestIamPermissionsResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_google_iam_v1_iam_policy_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *TestIamPermissionsResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TestIamPermissionsResponse.Unmarshal(m, b) -} -func (m *TestIamPermissionsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TestIamPermissionsResponse.Marshal(b, m, deterministic) -} -func (m *TestIamPermissionsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TestIamPermissionsResponse.Merge(m, src) -} -func (m *TestIamPermissionsResponse) XXX_Size() int { - return xxx_messageInfo_TestIamPermissionsResponse.Size(m) +func (x *TestIamPermissionsResponse) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *TestIamPermissionsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TestIamPermissionsResponse.DiscardUnknown(m) + +func (*TestIamPermissionsResponse) ProtoMessage() {} + +func (x *TestIamPermissionsResponse) ProtoReflect() protoreflect.Message { + mi := &file_google_iam_v1_iam_policy_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_TestIamPermissionsResponse proto.InternalMessageInfo +// Deprecated: Use TestIamPermissionsResponse.ProtoReflect.Descriptor instead. +func (*TestIamPermissionsResponse) Descriptor() ([]byte, []int) { + return file_google_iam_v1_iam_policy_proto_rawDescGZIP(), []int{3} +} -func (m *TestIamPermissionsResponse) GetPermissions() []string { - if m != nil { - return m.Permissions +func (x *TestIamPermissionsResponse) GetPermissions() []string { + if x != nil { + return x.Permissions } return nil } -func init() { - proto.RegisterType((*SetIamPolicyRequest)(nil), "google.iam.v1.SetIamPolicyRequest") - proto.RegisterType((*GetIamPolicyRequest)(nil), "google.iam.v1.GetIamPolicyRequest") - proto.RegisterType((*TestIamPermissionsRequest)(nil), "google.iam.v1.TestIamPermissionsRequest") - proto.RegisterType((*TestIamPermissionsResponse)(nil), "google.iam.v1.TestIamPermissionsResponse") -} - -func init() { - proto.RegisterFile("google/iam/v1/iam_policy.proto", fileDescriptor_d2728eb97d748a32) -} - -var fileDescriptor_d2728eb97d748a32 = []byte{ - // 514 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x54, 0xc1, 0x8a, 0xd3, 0x40, - 0x18, 0x66, 0x52, 0x58, 0xed, 0xac, 0x0a, 0xa6, 0x88, 0xdd, 0xac, 0x74, 0x4b, 0x74, 0xa1, 0x0d, - 0xec, 0xc4, 0xd6, 0x93, 0x15, 0x85, 0xd4, 0x43, 0xe8, 0x41, 0x2c, 0x55, 0xf6, 0x20, 0x85, 0x65, - 0x36, 0x3b, 0xc6, 0x81, 0x4c, 0x66, 0xcc, 0x4c, 0x2b, 0x22, 0x5e, 0x3c, 0xf8, 0x02, 0xde, 0x7c, - 0x04, 0xcf, 0x3e, 0xc5, 0x5e, 0x7d, 0x81, 0x3d, 0xf8, 0x10, 0xe2, 0x49, 0x92, 0x99, 0x6e, 0x93, - 0xb6, 0x8a, 0xca, 0x9e, 0x0a, 0xff, 0xf7, 0xfd, 0xdf, 0xf7, 0x7f, 0xff, 0xdf, 0x09, 0x6c, 0xc5, - 0x9c, 0xc7, 0x09, 0xf1, 0x29, 0x66, 0xfe, 0xbc, 0x97, 0xff, 0x1c, 0x09, 0x9e, 0xd0, 0xe8, 0x2d, - 0x12, 0x19, 0x57, 0xdc, 0xbe, 0xaa, 0x71, 0x44, 0x31, 0x43, 0xf3, 0x9e, 0xb3, 0x5b, 0xa5, 0x73, - 0xa1, 0x28, 0x4f, 0xa5, 0xe6, 0x3a, 0x4e, 0x15, 0x2c, 0xeb, 0x38, 0xb7, 0x0c, 0x86, 0x05, 0xf5, - 0x71, 0x9a, 0x72, 0x85, 0xcb, 0x9d, 0x37, 0x4b, 0x68, 0x94, 0x50, 0x92, 0x2a, 0x03, 0xec, 0x95, - 0x80, 0x97, 0x94, 0x24, 0x27, 0x47, 0xc7, 0xe4, 0x15, 0x9e, 0x53, 0x9e, 0x19, 0xc2, 0x4e, 0x89, - 0x90, 0x11, 0xc9, 0x67, 0x59, 0x44, 0x34, 0xe4, 0x0a, 0xd8, 0x78, 0x46, 0xd4, 0x08, 0xb3, 0x71, - 0x31, 0xc8, 0x84, 0xbc, 0x9e, 0x11, 0xa9, 0xec, 0x7d, 0x78, 0x79, 0x41, 0x6c, 0x82, 0x36, 0xe8, - 0xd4, 0x87, 0xf5, 0xb3, 0xc0, 0xfa, 0x19, 0xd4, 0x20, 0xf0, 0x26, 0xe7, 0x90, 0xdd, 0x87, 0x5b, - 0x3a, 0x40, 0xd3, 0x6a, 0x83, 0xce, 0x76, 0xff, 0x06, 0xaa, 0x6c, 0x02, 0x69, 0xd1, 0x61, 0xed, - 0x2c, 0xb0, 0x26, 0x86, 0xe9, 0xbe, 0x81, 0x8d, 0xf0, 0xff, 0x1d, 0xef, 0xc3, 0x4b, 0x66, 0x9f, - 0xc6, 0x72, 0x6f, 0xc5, 0x32, 0x24, 0x4a, 0x0b, 0x3f, 0xd5, 0xb4, 0xc9, 0x82, 0xef, 0x52, 0xb8, - 0xf3, 0x9c, 0xc8, 0xc2, 0x99, 0x64, 0x8c, 0x4a, 0x59, 0xc0, 0xff, 0x66, 0xbf, 0x0f, 0xb7, 0xc5, - 0xb2, 0xb9, 0x69, 0xb5, 0x6b, 0x9d, 0xba, 0x8e, 0x57, 0xae, 0xbb, 0x8f, 0xa0, 0xb3, 0xc9, 0x4a, - 0x0a, 0x9e, 0x4a, 0x62, 0xb7, 0xab, 0x22, 0x20, 0x17, 0xa9, 0xf4, 0xf7, 0xbf, 0xd6, 0x60, 0x7d, - 0x14, 0x3c, 0xd1, 0x41, 0x6c, 0x05, 0xaf, 0x94, 0x6f, 0x64, 0xbb, 0x2b, 0x91, 0x37, 0x1c, 0xd0, - 0xd9, 0x7c, 0x09, 0xb7, 0xfb, 0xe1, 0xdb, 0xf7, 0x4f, 0xd6, 0x6d, 0xb7, 0x95, 0xff, 0xf7, 0xde, - 0x2d, 0x62, 0x3d, 0xf4, 0xbc, 0xf7, 0x03, 0x59, 0x52, 0x19, 0x00, 0x2f, 0x77, 0x0d, 0xff, 0xe4, - 0x1a, 0x5e, 0x88, 0x6b, 0xbc, 0xe2, 0xfa, 0x19, 0x40, 0x7b, 0x7d, 0x75, 0x76, 0x67, 0x45, 0xf8, - 0xb7, 0x87, 0x74, 0xba, 0x7f, 0xc1, 0xd4, 0x77, 0x70, 0xfd, 0x62, 0xac, 0xae, 0x7b, 0x67, 0x7d, - 0x2c, 0xb5, 0xd6, 0x35, 0x00, 0x9e, 0xd3, 0x3a, 0x0d, 0x76, 0x29, 0x66, 0x07, 0x8c, 0x28, 0x7c, - 0x80, 0x05, 0x35, 0x56, 0x58, 0x50, 0x89, 0x22, 0xce, 0x86, 0x1f, 0x01, 0xbc, 0x1e, 0x71, 0x56, - 0x9d, 0x60, 0x78, 0xed, 0x3c, 0xe0, 0x38, 0x7f, 0x72, 0x63, 0xf0, 0xe2, 0xae, 0x21, 0xc4, 0x3c, - 0xc1, 0x69, 0x8c, 0x78, 0x16, 0xfb, 0x31, 0x49, 0x8b, 0x07, 0xe9, 0x2f, 0x25, 0xcd, 0x27, 0xe2, - 0x01, 0xc5, 0xec, 0x07, 0x00, 0x5f, 0xac, 0x46, 0xa8, 0xbb, 0x1e, 0x27, 0x7c, 0x76, 0x82, 0x46, - 0x98, 0xa1, 0xc3, 0xde, 0xe9, 0xa2, 0x3a, 0x2d, 0xaa, 0xd3, 0x11, 0x66, 0xd3, 0xc3, 0xde, 0xf1, - 0x56, 0xa1, 0x75, 0xef, 0x57, 0x00, 0x00, 0x00, 0xff, 0xff, 0x32, 0x24, 0xb5, 0x51, 0xb9, 0x04, - 0x00, 0x00, +var File_google_iam_v1_iam_policy_proto protoreflect.FileDescriptor + +var file_google_iam_v1_iam_policy_proto_rawDesc = []byte{ + 0x0a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x76, 0x31, 0x2f, + 0x69, 0x61, 0x6d, 0x5f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x12, 0x0d, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x1a, + 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x76, 0x31, 0x2f, 0x6f, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1a, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x76, 0x31, 0x2f, 0x70, 0x6f, 0x6c, 0x69, + 0x63, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, + 0x70, 0x69, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, + 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x66, 0x69, 0x65, 0x6c, + 0x64, 0x5f, 0x62, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x72, 0x65, 0x73, + 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x70, 0x0a, 0x13, 0x53, + 0x65, 0x74, 0x49, 0x61, 0x6d, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x12, 0x25, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x42, 0x09, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x03, 0x0a, 0x01, 0x2a, 0x52, + 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x32, 0x0a, 0x06, 0x70, 0x6f, 0x6c, + 0x69, 0x63, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, + 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x06, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x22, 0x77, 0x0a, + 0x13, 0x47, 0x65, 0x74, 0x49, 0x61, 0x6d, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x12, 0x25, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x09, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x03, 0x0a, 0x01, + 0x2a, 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x39, 0x0a, 0x07, 0x6f, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, + 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x07, 0x6f, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x69, 0x0a, 0x19, 0x54, 0x65, 0x73, 0x74, 0x49, 0x61, + 0x6d, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x12, 0x25, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x09, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x03, 0x0a, 0x01, 0x2a, + 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x25, 0x0a, 0x0b, 0x70, 0x65, + 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x42, + 0x03, 0xe0, 0x41, 0x02, 0x52, 0x0b, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, + 0x73, 0x22, 0x3e, 0x0a, 0x1a, 0x54, 0x65, 0x73, 0x74, 0x49, 0x61, 0x6d, 0x50, 0x65, 0x72, 0x6d, + 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, + 0x20, 0x0a, 0x0b, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, + 0x20, 0x03, 0x28, 0x09, 0x52, 0x0b, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, + 0x73, 0x32, 0xb4, 0x03, 0x0a, 0x09, 0x49, 0x41, 0x4d, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, + 0x74, 0x0a, 0x0c, 0x53, 0x65, 0x74, 0x49, 0x61, 0x6d, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, + 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x2e, + 0x53, 0x65, 0x74, 0x49, 0x61, 0x6d, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x15, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, + 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x22, 0x29, 0x82, 0xd3, 0xe4, 0x93, + 0x02, 0x23, 0x22, 0x1e, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, + 0x65, 0x3d, 0x2a, 0x2a, 0x7d, 0x3a, 0x73, 0x65, 0x74, 0x49, 0x61, 0x6d, 0x50, 0x6f, 0x6c, 0x69, + 0x63, 0x79, 0x3a, 0x01, 0x2a, 0x12, 0x74, 0x0a, 0x0c, 0x47, 0x65, 0x74, 0x49, 0x61, 0x6d, 0x50, + 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, + 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x49, 0x61, 0x6d, 0x50, 0x6f, 0x6c, 0x69, + 0x63, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x15, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, + 0x22, 0x29, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x23, 0x22, 0x1e, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x72, + 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x3d, 0x2a, 0x2a, 0x7d, 0x3a, 0x67, 0x65, 0x74, 0x49, + 0x61, 0x6d, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x3a, 0x01, 0x2a, 0x12, 0x9a, 0x01, 0x0a, 0x12, + 0x54, 0x65, 0x73, 0x74, 0x49, 0x61, 0x6d, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, + 0x6e, 0x73, 0x12, 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, + 0x76, 0x31, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x49, 0x61, 0x6d, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, + 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x29, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x65, 0x73, + 0x74, 0x49, 0x61, 0x6d, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x2f, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x29, 0x22, + 0x24, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x3d, 0x2a, + 0x2a, 0x7d, 0x3a, 0x74, 0x65, 0x73, 0x74, 0x49, 0x61, 0x6d, 0x50, 0x65, 0x72, 0x6d, 0x69, 0x73, + 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x3a, 0x01, 0x2a, 0x1a, 0x1e, 0xca, 0x41, 0x1b, 0x69, 0x61, 0x6d, + 0x2d, 0x6d, 0x65, 0x74, 0x61, 0x2d, 0x61, 0x70, 0x69, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x42, 0x86, 0x01, 0x0a, 0x11, 0x63, 0x6f, 0x6d, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x42, 0x0e, + 0x49, 0x61, 0x6d, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, + 0x5a, 0x30, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, + 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x76, 0x31, 0x3b, 0x69, + 0x61, 0x6d, 0xf8, 0x01, 0x01, 0xaa, 0x02, 0x13, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, + 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x49, 0x61, 0x6d, 0x2e, 0x56, 0x31, 0xca, 0x02, 0x13, 0x47, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x5c, 0x49, 0x61, 0x6d, 0x5c, 0x56, + 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_google_iam_v1_iam_policy_proto_rawDescOnce sync.Once + file_google_iam_v1_iam_policy_proto_rawDescData = file_google_iam_v1_iam_policy_proto_rawDesc +) + +func file_google_iam_v1_iam_policy_proto_rawDescGZIP() []byte { + file_google_iam_v1_iam_policy_proto_rawDescOnce.Do(func() { + file_google_iam_v1_iam_policy_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_iam_v1_iam_policy_proto_rawDescData) + }) + return file_google_iam_v1_iam_policy_proto_rawDescData +} + +var file_google_iam_v1_iam_policy_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_google_iam_v1_iam_policy_proto_goTypes = []interface{}{ + (*SetIamPolicyRequest)(nil), // 0: google.iam.v1.SetIamPolicyRequest + (*GetIamPolicyRequest)(nil), // 1: google.iam.v1.GetIamPolicyRequest + (*TestIamPermissionsRequest)(nil), // 2: google.iam.v1.TestIamPermissionsRequest + (*TestIamPermissionsResponse)(nil), // 3: google.iam.v1.TestIamPermissionsResponse + (*Policy)(nil), // 4: google.iam.v1.Policy + (*GetPolicyOptions)(nil), // 5: google.iam.v1.GetPolicyOptions +} +var file_google_iam_v1_iam_policy_proto_depIdxs = []int32{ + 4, // 0: google.iam.v1.SetIamPolicyRequest.policy:type_name -> google.iam.v1.Policy + 5, // 1: google.iam.v1.GetIamPolicyRequest.options:type_name -> google.iam.v1.GetPolicyOptions + 0, // 2: google.iam.v1.IAMPolicy.SetIamPolicy:input_type -> google.iam.v1.SetIamPolicyRequest + 1, // 3: google.iam.v1.IAMPolicy.GetIamPolicy:input_type -> google.iam.v1.GetIamPolicyRequest + 2, // 4: google.iam.v1.IAMPolicy.TestIamPermissions:input_type -> google.iam.v1.TestIamPermissionsRequest + 4, // 5: google.iam.v1.IAMPolicy.SetIamPolicy:output_type -> google.iam.v1.Policy + 4, // 6: google.iam.v1.IAMPolicy.GetIamPolicy:output_type -> google.iam.v1.Policy + 3, // 7: google.iam.v1.IAMPolicy.TestIamPermissions:output_type -> google.iam.v1.TestIamPermissionsResponse + 5, // [5:8] is the sub-list for method output_type + 2, // [2:5] is the sub-list for method input_type + 2, // [2:2] is the sub-list for extension type_name + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name +} + +func init() { file_google_iam_v1_iam_policy_proto_init() } +func file_google_iam_v1_iam_policy_proto_init() { + if File_google_iam_v1_iam_policy_proto != nil { + return + } + file_google_iam_v1_options_proto_init() + file_google_iam_v1_policy_proto_init() + if !protoimpl.UnsafeEnabled { + file_google_iam_v1_iam_policy_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SetIamPolicyRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_iam_v1_iam_policy_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetIamPolicyRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_iam_v1_iam_policy_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestIamPermissionsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_iam_v1_iam_policy_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestIamPermissionsResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_iam_v1_iam_policy_proto_rawDesc, + NumEnums: 0, + NumMessages: 4, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_google_iam_v1_iam_policy_proto_goTypes, + DependencyIndexes: file_google_iam_v1_iam_policy_proto_depIdxs, + MessageInfos: file_google_iam_v1_iam_policy_proto_msgTypes, + }.Build() + File_google_iam_v1_iam_policy_proto = out.File + file_google_iam_v1_iam_policy_proto_rawDesc = nil + file_google_iam_v1_iam_policy_proto_goTypes = nil + file_google_iam_v1_iam_policy_proto_depIdxs = nil } // Reference imports to suppress errors if they are not otherwise used. @@ -363,13 +562,13 @@ type IAMPolicyServer interface { type UnimplementedIAMPolicyServer struct { } -func (*UnimplementedIAMPolicyServer) SetIamPolicy(ctx context.Context, req *SetIamPolicyRequest) (*Policy, error) { +func (*UnimplementedIAMPolicyServer) SetIamPolicy(context.Context, *SetIamPolicyRequest) (*Policy, error) { return nil, status.Errorf(codes.Unimplemented, "method SetIamPolicy not implemented") } -func (*UnimplementedIAMPolicyServer) GetIamPolicy(ctx context.Context, req *GetIamPolicyRequest) (*Policy, error) { +func (*UnimplementedIAMPolicyServer) GetIamPolicy(context.Context, *GetIamPolicyRequest) (*Policy, error) { return nil, status.Errorf(codes.Unimplemented, "method GetIamPolicy not implemented") } -func (*UnimplementedIAMPolicyServer) TestIamPermissions(ctx context.Context, req *TestIamPermissionsRequest) (*TestIamPermissionsResponse, error) { +func (*UnimplementedIAMPolicyServer) TestIamPermissions(context.Context, *TestIamPermissionsRequest) (*TestIamPermissionsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method TestIamPermissions not implemented") } diff --git a/vendor/google.golang.org/genproto/googleapis/iam/v1/options.pb.go b/vendor/google.golang.org/genproto/googleapis/iam/v1/options.pb.go index fc3a218b703..e6c2bfcba56 100644 --- a/vendor/google.golang.org/genproto/googleapis/iam/v1/options.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/iam/v1/options.pb.go @@ -1,29 +1,53 @@ +// Copyright 2019 Google LLC. +// +// 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 protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.22.0 +// protoc v3.12.3 // source: google/iam/v1/options.proto package iam import ( - fmt "fmt" - math "math" + reflect "reflect" + sync "sync" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 // Encapsulates settings provided to GetIamPolicy. type GetPolicyOptions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // Optional. The policy format version to be returned. // // Valid values are 0, 1, and 3. Requests specifying an invalid value will be @@ -32,67 +56,131 @@ type GetPolicyOptions struct { // Requests for policies with any conditional bindings must specify version 3. // Policies without any conditional bindings may specify any valid value or // leave the field unset. - RequestedPolicyVersion int32 `protobuf:"varint,1,opt,name=requested_policy_version,json=requestedPolicyVersion,proto3" json:"requested_policy_version,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + RequestedPolicyVersion int32 `protobuf:"varint,1,opt,name=requested_policy_version,json=requestedPolicyVersion,proto3" json:"requested_policy_version,omitempty"` } -func (m *GetPolicyOptions) Reset() { *m = GetPolicyOptions{} } -func (m *GetPolicyOptions) String() string { return proto.CompactTextString(m) } -func (*GetPolicyOptions) ProtoMessage() {} -func (*GetPolicyOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_19aa09e909092bd1, []int{0} +func (x *GetPolicyOptions) Reset() { + *x = GetPolicyOptions{} + if protoimpl.UnsafeEnabled { + mi := &file_google_iam_v1_options_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *GetPolicyOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GetPolicyOptions.Unmarshal(m, b) -} -func (m *GetPolicyOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GetPolicyOptions.Marshal(b, m, deterministic) +func (x *GetPolicyOptions) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *GetPolicyOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_GetPolicyOptions.Merge(m, src) -} -func (m *GetPolicyOptions) XXX_Size() int { - return xxx_messageInfo_GetPolicyOptions.Size(m) -} -func (m *GetPolicyOptions) XXX_DiscardUnknown() { - xxx_messageInfo_GetPolicyOptions.DiscardUnknown(m) + +func (*GetPolicyOptions) ProtoMessage() {} + +func (x *GetPolicyOptions) ProtoReflect() protoreflect.Message { + mi := &file_google_iam_v1_options_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_GetPolicyOptions proto.InternalMessageInfo +// Deprecated: Use GetPolicyOptions.ProtoReflect.Descriptor instead. +func (*GetPolicyOptions) Descriptor() ([]byte, []int) { + return file_google_iam_v1_options_proto_rawDescGZIP(), []int{0} +} -func (m *GetPolicyOptions) GetRequestedPolicyVersion() int32 { - if m != nil { - return m.RequestedPolicyVersion +func (x *GetPolicyOptions) GetRequestedPolicyVersion() int32 { + if x != nil { + return x.RequestedPolicyVersion } return 0 } -func init() { - proto.RegisterType((*GetPolicyOptions)(nil), "google.iam.v1.GetPolicyOptions") +var File_google_iam_v1_options_proto protoreflect.FileDescriptor + +var file_google_iam_v1_options_proto_rawDesc = []byte{ + 0x0a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x76, 0x31, 0x2f, + 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x1a, 0x1c, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x4c, 0x0a, 0x10, 0x47, 0x65, + 0x74, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x38, + 0x0a, 0x18, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x5f, 0x70, 0x6f, 0x6c, 0x69, + 0x63, 0x79, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, + 0x52, 0x16, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x50, 0x6f, 0x6c, 0x69, 0x63, + 0x79, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x42, 0x84, 0x01, 0x0a, 0x11, 0x63, 0x6f, 0x6d, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x42, 0x0c, + 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x30, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, + 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x76, 0x31, 0x3b, 0x69, 0x61, 0x6d, + 0xf8, 0x01, 0x01, 0xaa, 0x02, 0x13, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, 0x6c, 0x6f, + 0x75, 0x64, 0x2e, 0x49, 0x61, 0x6d, 0x2e, 0x56, 0x31, 0xca, 0x02, 0x13, 0x47, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x5c, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x5c, 0x49, 0x61, 0x6d, 0x5c, 0x56, 0x31, 0x62, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_google_iam_v1_options_proto_rawDescOnce sync.Once + file_google_iam_v1_options_proto_rawDescData = file_google_iam_v1_options_proto_rawDesc +) + +func file_google_iam_v1_options_proto_rawDescGZIP() []byte { + file_google_iam_v1_options_proto_rawDescOnce.Do(func() { + file_google_iam_v1_options_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_iam_v1_options_proto_rawDescData) + }) + return file_google_iam_v1_options_proto_rawDescData } -func init() { - proto.RegisterFile("google/iam/v1/options.proto", fileDescriptor_19aa09e909092bd1) +var file_google_iam_v1_options_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_google_iam_v1_options_proto_goTypes = []interface{}{ + (*GetPolicyOptions)(nil), // 0: google.iam.v1.GetPolicyOptions +} +var file_google_iam_v1_options_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name } -var fileDescriptor_19aa09e909092bd1 = []byte{ - // 229 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0xcf, 0x4c, 0xcc, 0xd5, 0x2f, 0x33, 0xd4, 0xcf, 0x2f, 0x28, 0xc9, 0xcc, 0xcf, - 0x2b, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x85, 0x48, 0xea, 0x65, 0x26, 0xe6, 0xea, - 0x95, 0x19, 0x4a, 0xc9, 0x40, 0xd5, 0x26, 0x16, 0x64, 0xea, 0x27, 0xe6, 0xe5, 0xe5, 0x97, 0x24, - 0x22, 0x29, 0x56, 0xf2, 0xe1, 0x12, 0x70, 0x4f, 0x2d, 0x09, 0xc8, 0xcf, 0xc9, 0x4c, 0xae, 0xf4, - 0x87, 0x18, 0x23, 0x64, 0xc1, 0x25, 0x51, 0x94, 0x5a, 0x58, 0x9a, 0x5a, 0x5c, 0x92, 0x9a, 0x12, - 0x5f, 0x00, 0x96, 0x8a, 0x2f, 0x4b, 0x2d, 0x2a, 0xce, 0xcc, 0xcf, 0x93, 0x60, 0x54, 0x60, 0xd4, - 0x60, 0x0d, 0x12, 0x83, 0xcb, 0x43, 0x74, 0x86, 0x41, 0x64, 0x9d, 0x5a, 0x18, 0xb9, 0x04, 0x93, - 0xf3, 0x73, 0xf5, 0x50, 0x5c, 0xe0, 0xc4, 0x03, 0x35, 0x38, 0x00, 0x64, 0x63, 0x00, 0x63, 0x94, - 0x01, 0x54, 0x3a, 0x3d, 0x3f, 0x27, 0x31, 0x2f, 0x5d, 0x2f, 0xbf, 0x28, 0x5d, 0x3f, 0x3d, 0x35, - 0x0f, 0xec, 0x1e, 0x7d, 0x88, 0x54, 0x62, 0x41, 0x66, 0x31, 0xd4, 0x73, 0xd6, 0x99, 0x89, 0xb9, - 0x3f, 0x18, 0x19, 0x57, 0x31, 0x09, 0xbb, 0x43, 0x74, 0x39, 0xe7, 0xe4, 0x97, 0xa6, 0xe8, 0x79, - 0x26, 0xe6, 0xea, 0x85, 0x19, 0x9e, 0x82, 0x89, 0xc6, 0x80, 0x45, 0x63, 0x3c, 0x13, 0x73, 0x63, - 0xc2, 0x0c, 0x93, 0xd8, 0xc0, 0x66, 0x19, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xdf, 0x96, 0x0c, - 0x8b, 0x27, 0x01, 0x00, 0x00, +func init() { file_google_iam_v1_options_proto_init() } +func file_google_iam_v1_options_proto_init() { + if File_google_iam_v1_options_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_iam_v1_options_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetPolicyOptions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_iam_v1_options_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_iam_v1_options_proto_goTypes, + DependencyIndexes: file_google_iam_v1_options_proto_depIdxs, + MessageInfos: file_google_iam_v1_options_proto_msgTypes, + }.Build() + File_google_iam_v1_options_proto = out.File + file_google_iam_v1_options_proto_rawDesc = nil + file_google_iam_v1_options_proto_goTypes = nil + file_google_iam_v1_options_proto_depIdxs = nil } diff --git a/vendor/google.golang.org/genproto/googleapis/iam/v1/policy.pb.go b/vendor/google.golang.org/genproto/googleapis/iam/v1/policy.pb.go index 086732f120e..ba64dcc4690 100644 --- a/vendor/google.golang.org/genproto/googleapis/iam/v1/policy.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/iam/v1/policy.pb.go @@ -1,27 +1,47 @@ +// Copyright 2019 Google LLC. +// +// 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 protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.22.0 +// protoc v3.12.3 // source: google/iam/v1/policy.proto package iam import ( - fmt "fmt" - math "math" + reflect "reflect" + sync "sync" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" expr "google.golang.org/genproto/googleapis/type/expr" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 // The type of action performed on a Binding in a policy. type BindingDelta_Action int32 @@ -35,24 +55,45 @@ const ( BindingDelta_REMOVE BindingDelta_Action = 2 ) -var BindingDelta_Action_name = map[int32]string{ - 0: "ACTION_UNSPECIFIED", - 1: "ADD", - 2: "REMOVE", -} +// Enum value maps for BindingDelta_Action. +var ( + BindingDelta_Action_name = map[int32]string{ + 0: "ACTION_UNSPECIFIED", + 1: "ADD", + 2: "REMOVE", + } + BindingDelta_Action_value = map[string]int32{ + "ACTION_UNSPECIFIED": 0, + "ADD": 1, + "REMOVE": 2, + } +) -var BindingDelta_Action_value = map[string]int32{ - "ACTION_UNSPECIFIED": 0, - "ADD": 1, - "REMOVE": 2, +func (x BindingDelta_Action) Enum() *BindingDelta_Action { + p := new(BindingDelta_Action) + *p = x + return p } func (x BindingDelta_Action) String() string { - return proto.EnumName(BindingDelta_Action_name, int32(x)) + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } +func (BindingDelta_Action) Descriptor() protoreflect.EnumDescriptor { + return file_google_iam_v1_policy_proto_enumTypes[0].Descriptor() +} + +func (BindingDelta_Action) Type() protoreflect.EnumType { + return &file_google_iam_v1_policy_proto_enumTypes[0] +} + +func (x BindingDelta_Action) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use BindingDelta_Action.Descriptor instead. func (BindingDelta_Action) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_a3cd40b8a66b2a99, []int{3, 0} + return file_google_iam_v1_policy_proto_rawDescGZIP(), []int{3, 0} } // The type of action performed on an audit configuration in a policy. @@ -67,24 +108,45 @@ const ( AuditConfigDelta_REMOVE AuditConfigDelta_Action = 2 ) -var AuditConfigDelta_Action_name = map[int32]string{ - 0: "ACTION_UNSPECIFIED", - 1: "ADD", - 2: "REMOVE", -} +// Enum value maps for AuditConfigDelta_Action. +var ( + AuditConfigDelta_Action_name = map[int32]string{ + 0: "ACTION_UNSPECIFIED", + 1: "ADD", + 2: "REMOVE", + } + AuditConfigDelta_Action_value = map[string]int32{ + "ACTION_UNSPECIFIED": 0, + "ADD": 1, + "REMOVE": 2, + } +) -var AuditConfigDelta_Action_value = map[string]int32{ - "ACTION_UNSPECIFIED": 0, - "ADD": 1, - "REMOVE": 2, +func (x AuditConfigDelta_Action) Enum() *AuditConfigDelta_Action { + p := new(AuditConfigDelta_Action) + *p = x + return p } func (x AuditConfigDelta_Action) String() string { - return proto.EnumName(AuditConfigDelta_Action_name, int32(x)) + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } +func (AuditConfigDelta_Action) Descriptor() protoreflect.EnumDescriptor { + return file_google_iam_v1_policy_proto_enumTypes[1].Descriptor() +} + +func (AuditConfigDelta_Action) Type() protoreflect.EnumType { + return &file_google_iam_v1_policy_proto_enumTypes[1] +} + +func (x AuditConfigDelta_Action) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use AuditConfigDelta_Action.Descriptor instead. func (AuditConfigDelta_Action) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_a3cd40b8a66b2a99, []int{4, 0} + return file_google_iam_v1_policy_proto_rawDescGZIP(), []int{4, 0} } // Defines an Identity and Access Management (IAM) policy. It is used to @@ -145,6 +207,10 @@ func (AuditConfigDelta_Action) EnumDescriptor() ([]byte, []int) { // For a description of IAM and its features, see the // [IAM developer's guide](https://cloud.google.com/iam/docs). type Policy struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // Specifies the format of the policy. // // Valid values are 0, 1, and 3. Requests specifying an invalid value will be @@ -176,60 +242,68 @@ type Policy struct { // policy is overwritten. Due to blind-set semantics of an etag-less policy, // 'setIamPolicy' will not fail even if the incoming policy version does not // meet the requirements for modifying the stored policy. - Etag []byte `protobuf:"bytes,3,opt,name=etag,proto3" json:"etag,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Etag []byte `protobuf:"bytes,3,opt,name=etag,proto3" json:"etag,omitempty"` } -func (m *Policy) Reset() { *m = Policy{} } -func (m *Policy) String() string { return proto.CompactTextString(m) } -func (*Policy) ProtoMessage() {} -func (*Policy) Descriptor() ([]byte, []int) { - return fileDescriptor_a3cd40b8a66b2a99, []int{0} +func (x *Policy) Reset() { + *x = Policy{} + if protoimpl.UnsafeEnabled { + mi := &file_google_iam_v1_policy_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Policy) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Policy.Unmarshal(m, b) -} -func (m *Policy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Policy.Marshal(b, m, deterministic) -} -func (m *Policy) XXX_Merge(src proto.Message) { - xxx_messageInfo_Policy.Merge(m, src) -} -func (m *Policy) XXX_Size() int { - return xxx_messageInfo_Policy.Size(m) +func (x *Policy) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Policy) XXX_DiscardUnknown() { - xxx_messageInfo_Policy.DiscardUnknown(m) + +func (*Policy) ProtoMessage() {} + +func (x *Policy) ProtoReflect() protoreflect.Message { + mi := &file_google_iam_v1_policy_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Policy proto.InternalMessageInfo +// Deprecated: Use Policy.ProtoReflect.Descriptor instead. +func (*Policy) Descriptor() ([]byte, []int) { + return file_google_iam_v1_policy_proto_rawDescGZIP(), []int{0} +} -func (m *Policy) GetVersion() int32 { - if m != nil { - return m.Version +func (x *Policy) GetVersion() int32 { + if x != nil { + return x.Version } return 0 } -func (m *Policy) GetBindings() []*Binding { - if m != nil { - return m.Bindings +func (x *Policy) GetBindings() []*Binding { + if x != nil { + return x.Bindings } return nil } -func (m *Policy) GetEtag() []byte { - if m != nil { - return m.Etag +func (x *Policy) GetEtag() []byte { + if x != nil { + return x.Etag } return nil } // Associates `members` with a `role`. type Binding struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // Role that is assigned to `members`. // For example, `roles/viewer`, `roles/editor`, or `roles/owner`. Role string `protobuf:"bytes,1,opt,name=role,proto3" json:"role,omitempty"` @@ -262,104 +336,116 @@ type Binding struct { // NOTE: An unsatisfied condition will not allow user access via current // binding. Different bindings, including their conditions, are examined // independently. - Condition *expr.Expr `protobuf:"bytes,3,opt,name=condition,proto3" json:"condition,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Condition *expr.Expr `protobuf:"bytes,3,opt,name=condition,proto3" json:"condition,omitempty"` } -func (m *Binding) Reset() { *m = Binding{} } -func (m *Binding) String() string { return proto.CompactTextString(m) } -func (*Binding) ProtoMessage() {} -func (*Binding) Descriptor() ([]byte, []int) { - return fileDescriptor_a3cd40b8a66b2a99, []int{1} +func (x *Binding) Reset() { + *x = Binding{} + if protoimpl.UnsafeEnabled { + mi := &file_google_iam_v1_policy_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Binding) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Binding.Unmarshal(m, b) -} -func (m *Binding) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Binding.Marshal(b, m, deterministic) -} -func (m *Binding) XXX_Merge(src proto.Message) { - xxx_messageInfo_Binding.Merge(m, src) +func (x *Binding) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Binding) XXX_Size() int { - return xxx_messageInfo_Binding.Size(m) -} -func (m *Binding) XXX_DiscardUnknown() { - xxx_messageInfo_Binding.DiscardUnknown(m) + +func (*Binding) ProtoMessage() {} + +func (x *Binding) ProtoReflect() protoreflect.Message { + mi := &file_google_iam_v1_policy_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Binding proto.InternalMessageInfo +// Deprecated: Use Binding.ProtoReflect.Descriptor instead. +func (*Binding) Descriptor() ([]byte, []int) { + return file_google_iam_v1_policy_proto_rawDescGZIP(), []int{1} +} -func (m *Binding) GetRole() string { - if m != nil { - return m.Role +func (x *Binding) GetRole() string { + if x != nil { + return x.Role } return "" } -func (m *Binding) GetMembers() []string { - if m != nil { - return m.Members +func (x *Binding) GetMembers() []string { + if x != nil { + return x.Members } return nil } -func (m *Binding) GetCondition() *expr.Expr { - if m != nil { - return m.Condition +func (x *Binding) GetCondition() *expr.Expr { + if x != nil { + return x.Condition } return nil } // The difference delta between two policies. type PolicyDelta struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // The delta for Bindings between two policies. BindingDeltas []*BindingDelta `protobuf:"bytes,1,rep,name=binding_deltas,json=bindingDeltas,proto3" json:"binding_deltas,omitempty"` // The delta for AuditConfigs between two policies. - AuditConfigDeltas []*AuditConfigDelta `protobuf:"bytes,2,rep,name=audit_config_deltas,json=auditConfigDeltas,proto3" json:"audit_config_deltas,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + AuditConfigDeltas []*AuditConfigDelta `protobuf:"bytes,2,rep,name=audit_config_deltas,json=auditConfigDeltas,proto3" json:"audit_config_deltas,omitempty"` } -func (m *PolicyDelta) Reset() { *m = PolicyDelta{} } -func (m *PolicyDelta) String() string { return proto.CompactTextString(m) } -func (*PolicyDelta) ProtoMessage() {} -func (*PolicyDelta) Descriptor() ([]byte, []int) { - return fileDescriptor_a3cd40b8a66b2a99, []int{2} +func (x *PolicyDelta) Reset() { + *x = PolicyDelta{} + if protoimpl.UnsafeEnabled { + mi := &file_google_iam_v1_policy_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *PolicyDelta) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_PolicyDelta.Unmarshal(m, b) -} -func (m *PolicyDelta) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_PolicyDelta.Marshal(b, m, deterministic) -} -func (m *PolicyDelta) XXX_Merge(src proto.Message) { - xxx_messageInfo_PolicyDelta.Merge(m, src) +func (x *PolicyDelta) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *PolicyDelta) XXX_Size() int { - return xxx_messageInfo_PolicyDelta.Size(m) -} -func (m *PolicyDelta) XXX_DiscardUnknown() { - xxx_messageInfo_PolicyDelta.DiscardUnknown(m) + +func (*PolicyDelta) ProtoMessage() {} + +func (x *PolicyDelta) ProtoReflect() protoreflect.Message { + mi := &file_google_iam_v1_policy_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_PolicyDelta proto.InternalMessageInfo +// Deprecated: Use PolicyDelta.ProtoReflect.Descriptor instead. +func (*PolicyDelta) Descriptor() ([]byte, []int) { + return file_google_iam_v1_policy_proto_rawDescGZIP(), []int{2} +} -func (m *PolicyDelta) GetBindingDeltas() []*BindingDelta { - if m != nil { - return m.BindingDeltas +func (x *PolicyDelta) GetBindingDeltas() []*BindingDelta { + if x != nil { + return x.BindingDeltas } return nil } -func (m *PolicyDelta) GetAuditConfigDeltas() []*AuditConfigDelta { - if m != nil { - return m.AuditConfigDeltas +func (x *PolicyDelta) GetAuditConfigDeltas() []*AuditConfigDelta { + if x != nil { + return x.AuditConfigDeltas } return nil } @@ -367,6 +453,10 @@ func (m *PolicyDelta) GetAuditConfigDeltas() []*AuditConfigDelta { // One delta entry for Binding. Each individual change (only one member in each // entry) to a binding will be a separate entry. type BindingDelta struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // The action that was performed on a Binding. // Required Action BindingDelta_Action `protobuf:"varint,1,opt,name=action,proto3,enum=google.iam.v1.BindingDelta_Action" json:"action,omitempty"` @@ -379,61 +469,65 @@ type BindingDelta struct { // Required Member string `protobuf:"bytes,3,opt,name=member,proto3" json:"member,omitempty"` // The condition that is associated with this binding. - Condition *expr.Expr `protobuf:"bytes,4,opt,name=condition,proto3" json:"condition,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Condition *expr.Expr `protobuf:"bytes,4,opt,name=condition,proto3" json:"condition,omitempty"` } -func (m *BindingDelta) Reset() { *m = BindingDelta{} } -func (m *BindingDelta) String() string { return proto.CompactTextString(m) } -func (*BindingDelta) ProtoMessage() {} -func (*BindingDelta) Descriptor() ([]byte, []int) { - return fileDescriptor_a3cd40b8a66b2a99, []int{3} +func (x *BindingDelta) Reset() { + *x = BindingDelta{} + if protoimpl.UnsafeEnabled { + mi := &file_google_iam_v1_policy_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *BindingDelta) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BindingDelta.Unmarshal(m, b) -} -func (m *BindingDelta) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BindingDelta.Marshal(b, m, deterministic) -} -func (m *BindingDelta) XXX_Merge(src proto.Message) { - xxx_messageInfo_BindingDelta.Merge(m, src) +func (x *BindingDelta) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *BindingDelta) XXX_Size() int { - return xxx_messageInfo_BindingDelta.Size(m) -} -func (m *BindingDelta) XXX_DiscardUnknown() { - xxx_messageInfo_BindingDelta.DiscardUnknown(m) + +func (*BindingDelta) ProtoMessage() {} + +func (x *BindingDelta) ProtoReflect() protoreflect.Message { + mi := &file_google_iam_v1_policy_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_BindingDelta proto.InternalMessageInfo +// Deprecated: Use BindingDelta.ProtoReflect.Descriptor instead. +func (*BindingDelta) Descriptor() ([]byte, []int) { + return file_google_iam_v1_policy_proto_rawDescGZIP(), []int{3} +} -func (m *BindingDelta) GetAction() BindingDelta_Action { - if m != nil { - return m.Action +func (x *BindingDelta) GetAction() BindingDelta_Action { + if x != nil { + return x.Action } return BindingDelta_ACTION_UNSPECIFIED } -func (m *BindingDelta) GetRole() string { - if m != nil { - return m.Role +func (x *BindingDelta) GetRole() string { + if x != nil { + return x.Role } return "" } -func (m *BindingDelta) GetMember() string { - if m != nil { - return m.Member +func (x *BindingDelta) GetMember() string { + if x != nil { + return x.Member } return "" } -func (m *BindingDelta) GetCondition() *expr.Expr { - if m != nil { - return m.Condition +func (x *BindingDelta) GetCondition() *expr.Expr { + if x != nil { + return x.Condition } return nil } @@ -441,6 +535,10 @@ func (m *BindingDelta) GetCondition() *expr.Expr { // One delta entry for AuditConfig. Each individual change (only one // exempted_member in each entry) to a AuditConfig will be a separate entry. type AuditConfigDelta struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // The action that was performed on an audit configuration in a policy. // Required Action AuditConfigDelta_Action `protobuf:"varint,1,opt,name=action,proto3,enum=google.iam.v1.AuditConfigDelta_Action" json:"action,omitempty"` @@ -456,114 +554,265 @@ type AuditConfigDelta struct { // Specifies the log_type that was be enabled. ADMIN_ACTIVITY is always // enabled, and cannot be configured. // Required - LogType string `protobuf:"bytes,4,opt,name=log_type,json=logType,proto3" json:"log_type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + LogType string `protobuf:"bytes,4,opt,name=log_type,json=logType,proto3" json:"log_type,omitempty"` } -func (m *AuditConfigDelta) Reset() { *m = AuditConfigDelta{} } -func (m *AuditConfigDelta) String() string { return proto.CompactTextString(m) } -func (*AuditConfigDelta) ProtoMessage() {} -func (*AuditConfigDelta) Descriptor() ([]byte, []int) { - return fileDescriptor_a3cd40b8a66b2a99, []int{4} +func (x *AuditConfigDelta) Reset() { + *x = AuditConfigDelta{} + if protoimpl.UnsafeEnabled { + mi := &file_google_iam_v1_policy_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *AuditConfigDelta) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_AuditConfigDelta.Unmarshal(m, b) -} -func (m *AuditConfigDelta) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_AuditConfigDelta.Marshal(b, m, deterministic) -} -func (m *AuditConfigDelta) XXX_Merge(src proto.Message) { - xxx_messageInfo_AuditConfigDelta.Merge(m, src) +func (x *AuditConfigDelta) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *AuditConfigDelta) XXX_Size() int { - return xxx_messageInfo_AuditConfigDelta.Size(m) -} -func (m *AuditConfigDelta) XXX_DiscardUnknown() { - xxx_messageInfo_AuditConfigDelta.DiscardUnknown(m) + +func (*AuditConfigDelta) ProtoMessage() {} + +func (x *AuditConfigDelta) ProtoReflect() protoreflect.Message { + mi := &file_google_iam_v1_policy_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_AuditConfigDelta proto.InternalMessageInfo +// Deprecated: Use AuditConfigDelta.ProtoReflect.Descriptor instead. +func (*AuditConfigDelta) Descriptor() ([]byte, []int) { + return file_google_iam_v1_policy_proto_rawDescGZIP(), []int{4} +} -func (m *AuditConfigDelta) GetAction() AuditConfigDelta_Action { - if m != nil { - return m.Action +func (x *AuditConfigDelta) GetAction() AuditConfigDelta_Action { + if x != nil { + return x.Action } return AuditConfigDelta_ACTION_UNSPECIFIED } -func (m *AuditConfigDelta) GetService() string { - if m != nil { - return m.Service +func (x *AuditConfigDelta) GetService() string { + if x != nil { + return x.Service } return "" } -func (m *AuditConfigDelta) GetExemptedMember() string { - if m != nil { - return m.ExemptedMember +func (x *AuditConfigDelta) GetExemptedMember() string { + if x != nil { + return x.ExemptedMember } return "" } -func (m *AuditConfigDelta) GetLogType() string { - if m != nil { - return m.LogType +func (x *AuditConfigDelta) GetLogType() string { + if x != nil { + return x.LogType } return "" } -func init() { - proto.RegisterEnum("google.iam.v1.BindingDelta_Action", BindingDelta_Action_name, BindingDelta_Action_value) - proto.RegisterEnum("google.iam.v1.AuditConfigDelta_Action", AuditConfigDelta_Action_name, AuditConfigDelta_Action_value) - proto.RegisterType((*Policy)(nil), "google.iam.v1.Policy") - proto.RegisterType((*Binding)(nil), "google.iam.v1.Binding") - proto.RegisterType((*PolicyDelta)(nil), "google.iam.v1.PolicyDelta") - proto.RegisterType((*BindingDelta)(nil), "google.iam.v1.BindingDelta") - proto.RegisterType((*AuditConfigDelta)(nil), "google.iam.v1.AuditConfigDelta") -} - -func init() { - proto.RegisterFile("google/iam/v1/policy.proto", fileDescriptor_a3cd40b8a66b2a99) -} - -var fileDescriptor_a3cd40b8a66b2a99 = []byte{ - // 550 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x93, 0xcf, 0xae, 0xd2, 0x4e, - 0x14, 0xc7, 0x7f, 0x03, 0xfc, 0xca, 0xe5, 0x70, 0x2f, 0xc2, 0xdc, 0x84, 0x54, 0x34, 0x91, 0x74, - 0xa1, 0xac, 0x5a, 0xc1, 0xb8, 0xd1, 0xc4, 0x84, 0x7f, 0x1a, 0x16, 0xf7, 0x42, 0xc6, 0x2b, 0x0b, - 0x43, 0x42, 0x86, 0x76, 0xac, 0x63, 0xda, 0x4e, 0xd3, 0xf6, 0x12, 0x58, 0xfb, 0x26, 0x2e, 0x7d, - 0x14, 0x1f, 0xc2, 0xad, 0xaf, 0xe0, 0xd2, 0x74, 0xa6, 0x45, 0x68, 0x8c, 0x1a, 0x77, 0x73, 0xce, - 0xf9, 0xce, 0x39, 0xe7, 0xf3, 0x6d, 0x07, 0x3a, 0xae, 0x10, 0xae, 0xc7, 0x2c, 0x4e, 0x7d, 0x6b, - 0xdb, 0xb7, 0x42, 0xe1, 0x71, 0x7b, 0x6f, 0x86, 0x91, 0x48, 0x04, 0xbe, 0x50, 0x35, 0x93, 0x53, - 0xdf, 0xdc, 0xf6, 0x3b, 0xed, 0x4c, 0x9a, 0xec, 0x43, 0x66, 0xb1, 0x5d, 0x18, 0x29, 0x59, 0xe7, - 0x7e, 0x96, 0xa7, 0x21, 0xb7, 0x68, 0x10, 0x88, 0x84, 0x26, 0x5c, 0x04, 0xb1, 0xaa, 0x1a, 0x1f, - 0x40, 0x5b, 0xc8, 0xa6, 0x58, 0x87, 0xea, 0x96, 0x45, 0x31, 0x17, 0x81, 0x8e, 0xba, 0xa8, 0xf7, - 0x3f, 0xc9, 0x43, 0x3c, 0x80, 0xb3, 0x0d, 0x0f, 0x1c, 0x1e, 0xb8, 0xb1, 0x5e, 0xe9, 0x96, 0x7b, - 0xf5, 0x41, 0xdb, 0x3c, 0x99, 0x6d, 0x8e, 0x54, 0x99, 0x1c, 0x74, 0x18, 0x43, 0x85, 0x25, 0xd4, - 0xd5, 0xcb, 0x5d, 0xd4, 0x3b, 0x27, 0xf2, 0x6c, 0xbc, 0x87, 0x6a, 0x26, 0x4c, 0xcb, 0x91, 0xf0, - 0x98, 0x9c, 0x54, 0x23, 0xf2, 0x9c, 0x2e, 0xe0, 0x33, 0x7f, 0xc3, 0xa2, 0x58, 0x2f, 0x75, 0xcb, - 0xbd, 0x1a, 0xc9, 0x43, 0x6c, 0x41, 0xcd, 0x16, 0x81, 0xc3, 0xd3, 0xc5, 0x65, 0xc7, 0xfa, 0xa0, - 0x95, 0x6f, 0x90, 0xe2, 0x9a, 0xd3, 0x5d, 0x18, 0x91, 0x9f, 0x1a, 0xe3, 0x13, 0x82, 0xba, 0xc2, - 0x9a, 0x30, 0x2f, 0xa1, 0x78, 0x04, 0x8d, 0x6c, 0xb3, 0xb5, 0x93, 0x26, 0x62, 0x1d, 0x49, 0x8e, - 0x7b, 0xbf, 0xe6, 0x90, 0x97, 0xc8, 0xc5, 0xe6, 0x28, 0x8a, 0xf1, 0x1c, 0x2e, 0xe9, 0xad, 0xc3, - 0x93, 0xb5, 0x2d, 0x82, 0x77, 0xfc, 0xd0, 0xa8, 0x24, 0x1b, 0x3d, 0x28, 0x34, 0x1a, 0xa6, 0xca, - 0xb1, 0x14, 0xaa, 0x66, 0x2d, 0x5a, 0xc8, 0xc4, 0xc6, 0x57, 0x04, 0xe7, 0xc7, 0x03, 0xf1, 0x33, - 0xd0, 0xa8, 0x9d, 0xe4, 0x1f, 0xa0, 0x31, 0x30, 0x7e, 0xb3, 0x9d, 0x39, 0x94, 0x4a, 0x92, 0xdd, - 0x38, 0x18, 0x5a, 0x3a, 0x32, 0xb4, 0x0d, 0x9a, 0x72, 0x50, 0x7a, 0x56, 0x23, 0x59, 0x74, 0x6a, - 0x67, 0xe5, 0x2f, 0xec, 0x7c, 0x0a, 0x9a, 0x1a, 0x87, 0xdb, 0x80, 0x87, 0xe3, 0x9b, 0xd9, 0xfc, - 0x7a, 0xfd, 0xe6, 0xfa, 0xf5, 0x62, 0x3a, 0x9e, 0xbd, 0x9c, 0x4d, 0x27, 0xcd, 0xff, 0x70, 0x15, - 0xca, 0xc3, 0xc9, 0xa4, 0x89, 0x30, 0x80, 0x46, 0xa6, 0x57, 0xf3, 0xe5, 0xb4, 0x59, 0x32, 0xbe, - 0x21, 0x68, 0x16, 0x8d, 0xc0, 0x2f, 0x0a, 0x90, 0x0f, 0xff, 0xe0, 0x5c, 0x11, 0x54, 0x87, 0x6a, - 0xcc, 0xa2, 0x2d, 0xb7, 0x73, 0xd6, 0x3c, 0xc4, 0x8f, 0xe0, 0x0e, 0xdb, 0x31, 0x3f, 0x4c, 0x98, - 0xb3, 0x3e, 0xe1, 0x6e, 0xe4, 0xe9, 0x2b, 0xc5, 0x7f, 0x17, 0xce, 0x3c, 0xe1, 0xae, 0x53, 0x54, - 0x89, 0x5f, 0x23, 0x55, 0x4f, 0xb8, 0x37, 0xfb, 0x90, 0xfd, 0x23, 0xe9, 0xe8, 0x23, 0x82, 0x96, - 0x2d, 0xfc, 0x53, 0x94, 0x51, 0xf6, 0x0b, 0x2e, 0xd2, 0x87, 0xb6, 0x40, 0x6f, 0x1f, 0x67, 0x55, - 0x57, 0x78, 0x34, 0x70, 0x4d, 0x11, 0xb9, 0x96, 0xcb, 0x02, 0xf9, 0x0c, 0x2d, 0x55, 0xa2, 0x21, - 0x8f, 0xb3, 0xa7, 0xfe, 0x9c, 0x53, 0xff, 0x3b, 0x42, 0x9f, 0x4b, 0x97, 0xaf, 0xd4, 0xad, 0xb1, - 0x27, 0x6e, 0x1d, 0x73, 0x46, 0x7d, 0x73, 0xd9, 0xff, 0x92, 0x67, 0x57, 0x32, 0xbb, 0x9a, 0x51, - 0x7f, 0xb5, 0xec, 0x6f, 0x34, 0xd9, 0xeb, 0xc9, 0x8f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x29, 0x86, - 0x8f, 0x3e, 0x35, 0x04, 0x00, 0x00, +var File_google_iam_v1_policy_proto protoreflect.FileDescriptor + +var file_google_iam_v1_policy_proto_rawDesc = []byte{ + 0x0a, 0x1a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x76, 0x31, 0x2f, + 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x1a, 0x16, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x65, 0x78, 0x70, 0x72, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, + 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x22, 0x6a, 0x0a, 0x06, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x76, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x07, 0x76, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x32, 0x0a, 0x08, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, + 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x42, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x52, + 0x08, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x65, 0x74, 0x61, + 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x65, 0x74, 0x61, 0x67, 0x22, 0x68, 0x0a, + 0x07, 0x42, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x12, 0x12, 0x0a, 0x04, 0x72, 0x6f, 0x6c, 0x65, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x72, 0x6f, 0x6c, 0x65, 0x12, 0x18, 0x0a, 0x07, + 0x6d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x07, 0x6d, + 0x65, 0x6d, 0x62, 0x65, 0x72, 0x73, 0x12, 0x2f, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, + 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x45, 0x78, 0x70, 0x72, 0x52, 0x09, 0x63, 0x6f, + 0x6e, 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0xa2, 0x01, 0x0a, 0x0b, 0x50, 0x6f, 0x6c, 0x69, + 0x63, 0x79, 0x44, 0x65, 0x6c, 0x74, 0x61, 0x12, 0x42, 0x0a, 0x0e, 0x62, 0x69, 0x6e, 0x64, 0x69, + 0x6e, 0x67, 0x5f, 0x64, 0x65, 0x6c, 0x74, 0x61, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, + 0x1b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x2e, + 0x42, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x44, 0x65, 0x6c, 0x74, 0x61, 0x52, 0x0d, 0x62, 0x69, + 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x44, 0x65, 0x6c, 0x74, 0x61, 0x73, 0x12, 0x4f, 0x0a, 0x13, 0x61, + 0x75, 0x64, 0x69, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x5f, 0x64, 0x65, 0x6c, 0x74, + 0x61, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x75, 0x64, 0x69, 0x74, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x44, 0x65, 0x6c, 0x74, 0x61, 0x52, 0x11, 0x61, 0x75, 0x64, 0x69, 0x74, + 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x44, 0x65, 0x6c, 0x74, 0x61, 0x73, 0x22, 0xde, 0x01, 0x0a, + 0x0c, 0x42, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x44, 0x65, 0x6c, 0x74, 0x61, 0x12, 0x3a, 0x0a, + 0x06, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x22, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x42, 0x69, + 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x44, 0x65, 0x6c, 0x74, 0x61, 0x2e, 0x41, 0x63, 0x74, 0x69, 0x6f, + 0x6e, 0x52, 0x06, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x72, 0x6f, 0x6c, + 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x72, 0x6f, 0x6c, 0x65, 0x12, 0x16, 0x0a, + 0x06, 0x6d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6d, + 0x65, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x2f, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x64, 0x69, 0x74, 0x69, + 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x74, 0x79, 0x70, 0x65, 0x2e, 0x45, 0x78, 0x70, 0x72, 0x52, 0x09, 0x63, 0x6f, 0x6e, + 0x64, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x35, 0x0a, 0x06, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, + 0x12, 0x16, 0x0a, 0x12, 0x41, 0x43, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, + 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x41, 0x44, 0x44, 0x10, + 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x52, 0x45, 0x4d, 0x4f, 0x56, 0x45, 0x10, 0x02, 0x22, 0xe7, 0x01, + 0x0a, 0x10, 0x41, 0x75, 0x64, 0x69, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x44, 0x65, 0x6c, + 0x74, 0x61, 0x12, 0x3e, 0x0a, 0x06, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x0e, 0x32, 0x26, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, + 0x76, 0x31, 0x2e, 0x41, 0x75, 0x64, 0x69, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x44, 0x65, + 0x6c, 0x74, 0x61, 0x2e, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x06, 0x61, 0x63, 0x74, 0x69, + 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x07, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x27, 0x0a, 0x0f, + 0x65, 0x78, 0x65, 0x6d, 0x70, 0x74, 0x65, 0x64, 0x5f, 0x6d, 0x65, 0x6d, 0x62, 0x65, 0x72, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x65, 0x78, 0x65, 0x6d, 0x70, 0x74, 0x65, 0x64, 0x4d, + 0x65, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x6c, 0x6f, 0x67, 0x5f, 0x74, 0x79, 0x70, + 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6c, 0x6f, 0x67, 0x54, 0x79, 0x70, 0x65, + 0x22, 0x35, 0x0a, 0x06, 0x41, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x12, 0x41, 0x43, + 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, + 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x41, 0x44, 0x44, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x52, + 0x45, 0x4d, 0x4f, 0x56, 0x45, 0x10, 0x02, 0x42, 0x83, 0x01, 0x0a, 0x11, 0x63, 0x6f, 0x6d, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x31, 0x42, 0x0b, 0x50, + 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x30, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, + 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, + 0x70, 0x69, 0x73, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x76, 0x31, 0x3b, 0x69, 0x61, 0x6d, 0xf8, 0x01, + 0x01, 0xaa, 0x02, 0x13, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, 0x6c, 0x6f, 0x75, 0x64, + 0x2e, 0x49, 0x61, 0x6d, 0x2e, 0x56, 0x31, 0xca, 0x02, 0x13, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x5c, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x5c, 0x49, 0x61, 0x6d, 0x5c, 0x56, 0x31, 0x62, 0x06, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_google_iam_v1_policy_proto_rawDescOnce sync.Once + file_google_iam_v1_policy_proto_rawDescData = file_google_iam_v1_policy_proto_rawDesc +) + +func file_google_iam_v1_policy_proto_rawDescGZIP() []byte { + file_google_iam_v1_policy_proto_rawDescOnce.Do(func() { + file_google_iam_v1_policy_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_iam_v1_policy_proto_rawDescData) + }) + return file_google_iam_v1_policy_proto_rawDescData +} + +var file_google_iam_v1_policy_proto_enumTypes = make([]protoimpl.EnumInfo, 2) +var file_google_iam_v1_policy_proto_msgTypes = make([]protoimpl.MessageInfo, 5) +var file_google_iam_v1_policy_proto_goTypes = []interface{}{ + (BindingDelta_Action)(0), // 0: google.iam.v1.BindingDelta.Action + (AuditConfigDelta_Action)(0), // 1: google.iam.v1.AuditConfigDelta.Action + (*Policy)(nil), // 2: google.iam.v1.Policy + (*Binding)(nil), // 3: google.iam.v1.Binding + (*PolicyDelta)(nil), // 4: google.iam.v1.PolicyDelta + (*BindingDelta)(nil), // 5: google.iam.v1.BindingDelta + (*AuditConfigDelta)(nil), // 6: google.iam.v1.AuditConfigDelta + (*expr.Expr)(nil), // 7: google.type.Expr +} +var file_google_iam_v1_policy_proto_depIdxs = []int32{ + 3, // 0: google.iam.v1.Policy.bindings:type_name -> google.iam.v1.Binding + 7, // 1: google.iam.v1.Binding.condition:type_name -> google.type.Expr + 5, // 2: google.iam.v1.PolicyDelta.binding_deltas:type_name -> google.iam.v1.BindingDelta + 6, // 3: google.iam.v1.PolicyDelta.audit_config_deltas:type_name -> google.iam.v1.AuditConfigDelta + 0, // 4: google.iam.v1.BindingDelta.action:type_name -> google.iam.v1.BindingDelta.Action + 7, // 5: google.iam.v1.BindingDelta.condition:type_name -> google.type.Expr + 1, // 6: google.iam.v1.AuditConfigDelta.action:type_name -> google.iam.v1.AuditConfigDelta.Action + 7, // [7:7] is the sub-list for method output_type + 7, // [7:7] is the sub-list for method input_type + 7, // [7:7] is the sub-list for extension type_name + 7, // [7:7] is the sub-list for extension extendee + 0, // [0:7] is the sub-list for field type_name +} + +func init() { file_google_iam_v1_policy_proto_init() } +func file_google_iam_v1_policy_proto_init() { + if File_google_iam_v1_policy_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_iam_v1_policy_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Policy); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_iam_v1_policy_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Binding); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_iam_v1_policy_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*PolicyDelta); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_iam_v1_policy_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*BindingDelta); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_iam_v1_policy_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AuditConfigDelta); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_iam_v1_policy_proto_rawDesc, + NumEnums: 2, + NumMessages: 5, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_iam_v1_policy_proto_goTypes, + DependencyIndexes: file_google_iam_v1_policy_proto_depIdxs, + EnumInfos: file_google_iam_v1_policy_proto_enumTypes, + MessageInfos: file_google_iam_v1_policy_proto_msgTypes, + }.Build() + File_google_iam_v1_policy_proto = out.File + file_google_iam_v1_policy_proto_rawDesc = nil + file_google_iam_v1_policy_proto_goTypes = nil + file_google_iam_v1_policy_proto_depIdxs = nil } diff --git a/vendor/google.golang.org/genproto/googleapis/rpc/code/code.pb.go b/vendor/google.golang.org/genproto/googleapis/rpc/code/code.pb.go index a6e45696447..9034439ad9f 100644 --- a/vendor/google.golang.org/genproto/googleapis/rpc/code/code.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/rpc/code/code.pb.go @@ -1,25 +1,44 @@ +// Copyright 2020 Google LLC +// +// 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 protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.22.0 +// protoc v3.12.3 // source: google/rpc/code.proto package code import ( - fmt "fmt" - math "math" + reflect "reflect" + sync "sync" proto "github.com/golang/protobuf/proto" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 // The canonical error codes for gRPC APIs. // @@ -170,85 +189,153 @@ const ( Code_DATA_LOSS Code = 15 ) -var Code_name = map[int32]string{ - 0: "OK", - 1: "CANCELLED", - 2: "UNKNOWN", - 3: "INVALID_ARGUMENT", - 4: "DEADLINE_EXCEEDED", - 5: "NOT_FOUND", - 6: "ALREADY_EXISTS", - 7: "PERMISSION_DENIED", - 16: "UNAUTHENTICATED", - 8: "RESOURCE_EXHAUSTED", - 9: "FAILED_PRECONDITION", - 10: "ABORTED", - 11: "OUT_OF_RANGE", - 12: "UNIMPLEMENTED", - 13: "INTERNAL", - 14: "UNAVAILABLE", - 15: "DATA_LOSS", -} +// Enum value maps for Code. +var ( + Code_name = map[int32]string{ + 0: "OK", + 1: "CANCELLED", + 2: "UNKNOWN", + 3: "INVALID_ARGUMENT", + 4: "DEADLINE_EXCEEDED", + 5: "NOT_FOUND", + 6: "ALREADY_EXISTS", + 7: "PERMISSION_DENIED", + 16: "UNAUTHENTICATED", + 8: "RESOURCE_EXHAUSTED", + 9: "FAILED_PRECONDITION", + 10: "ABORTED", + 11: "OUT_OF_RANGE", + 12: "UNIMPLEMENTED", + 13: "INTERNAL", + 14: "UNAVAILABLE", + 15: "DATA_LOSS", + } + Code_value = map[string]int32{ + "OK": 0, + "CANCELLED": 1, + "UNKNOWN": 2, + "INVALID_ARGUMENT": 3, + "DEADLINE_EXCEEDED": 4, + "NOT_FOUND": 5, + "ALREADY_EXISTS": 6, + "PERMISSION_DENIED": 7, + "UNAUTHENTICATED": 16, + "RESOURCE_EXHAUSTED": 8, + "FAILED_PRECONDITION": 9, + "ABORTED": 10, + "OUT_OF_RANGE": 11, + "UNIMPLEMENTED": 12, + "INTERNAL": 13, + "UNAVAILABLE": 14, + "DATA_LOSS": 15, + } +) -var Code_value = map[string]int32{ - "OK": 0, - "CANCELLED": 1, - "UNKNOWN": 2, - "INVALID_ARGUMENT": 3, - "DEADLINE_EXCEEDED": 4, - "NOT_FOUND": 5, - "ALREADY_EXISTS": 6, - "PERMISSION_DENIED": 7, - "UNAUTHENTICATED": 16, - "RESOURCE_EXHAUSTED": 8, - "FAILED_PRECONDITION": 9, - "ABORTED": 10, - "OUT_OF_RANGE": 11, - "UNIMPLEMENTED": 12, - "INTERNAL": 13, - "UNAVAILABLE": 14, - "DATA_LOSS": 15, +func (x Code) Enum() *Code { + p := new(Code) + *p = x + return p } func (x Code) String() string { - return proto.EnumName(Code_name, int32(x)) + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (Code) Descriptor() protoreflect.EnumDescriptor { + return file_google_rpc_code_proto_enumTypes[0].Descriptor() } +func (Code) Type() protoreflect.EnumType { + return &file_google_rpc_code_proto_enumTypes[0] +} + +func (x Code) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use Code.Descriptor instead. func (Code) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_fe593a732623ccf0, []int{0} + return file_google_rpc_code_proto_rawDescGZIP(), []int{0} +} + +var File_google_rpc_code_proto protoreflect.FileDescriptor + +var file_google_rpc_code_proto_rawDesc = []byte{ + 0x0a, 0x15, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x63, 0x6f, 0x64, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x72, 0x70, 0x63, 0x2a, 0xb7, 0x02, 0x0a, 0x04, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x06, 0x0a, 0x02, + 0x4f, 0x4b, 0x10, 0x00, 0x12, 0x0d, 0x0a, 0x09, 0x43, 0x41, 0x4e, 0x43, 0x45, 0x4c, 0x4c, 0x45, + 0x44, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0x02, + 0x12, 0x14, 0x0a, 0x10, 0x49, 0x4e, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x5f, 0x41, 0x52, 0x47, 0x55, + 0x4d, 0x45, 0x4e, 0x54, 0x10, 0x03, 0x12, 0x15, 0x0a, 0x11, 0x44, 0x45, 0x41, 0x44, 0x4c, 0x49, + 0x4e, 0x45, 0x5f, 0x45, 0x58, 0x43, 0x45, 0x45, 0x44, 0x45, 0x44, 0x10, 0x04, 0x12, 0x0d, 0x0a, + 0x09, 0x4e, 0x4f, 0x54, 0x5f, 0x46, 0x4f, 0x55, 0x4e, 0x44, 0x10, 0x05, 0x12, 0x12, 0x0a, 0x0e, + 0x41, 0x4c, 0x52, 0x45, 0x41, 0x44, 0x59, 0x5f, 0x45, 0x58, 0x49, 0x53, 0x54, 0x53, 0x10, 0x06, + 0x12, 0x15, 0x0a, 0x11, 0x50, 0x45, 0x52, 0x4d, 0x49, 0x53, 0x53, 0x49, 0x4f, 0x4e, 0x5f, 0x44, + 0x45, 0x4e, 0x49, 0x45, 0x44, 0x10, 0x07, 0x12, 0x13, 0x0a, 0x0f, 0x55, 0x4e, 0x41, 0x55, 0x54, + 0x48, 0x45, 0x4e, 0x54, 0x49, 0x43, 0x41, 0x54, 0x45, 0x44, 0x10, 0x10, 0x12, 0x16, 0x0a, 0x12, + 0x52, 0x45, 0x53, 0x4f, 0x55, 0x52, 0x43, 0x45, 0x5f, 0x45, 0x58, 0x48, 0x41, 0x55, 0x53, 0x54, + 0x45, 0x44, 0x10, 0x08, 0x12, 0x17, 0x0a, 0x13, 0x46, 0x41, 0x49, 0x4c, 0x45, 0x44, 0x5f, 0x50, + 0x52, 0x45, 0x43, 0x4f, 0x4e, 0x44, 0x49, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x09, 0x12, 0x0b, 0x0a, + 0x07, 0x41, 0x42, 0x4f, 0x52, 0x54, 0x45, 0x44, 0x10, 0x0a, 0x12, 0x10, 0x0a, 0x0c, 0x4f, 0x55, + 0x54, 0x5f, 0x4f, 0x46, 0x5f, 0x52, 0x41, 0x4e, 0x47, 0x45, 0x10, 0x0b, 0x12, 0x11, 0x0a, 0x0d, + 0x55, 0x4e, 0x49, 0x4d, 0x50, 0x4c, 0x45, 0x4d, 0x45, 0x4e, 0x54, 0x45, 0x44, 0x10, 0x0c, 0x12, + 0x0c, 0x0a, 0x08, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x10, 0x0d, 0x12, 0x0f, 0x0a, + 0x0b, 0x55, 0x4e, 0x41, 0x56, 0x41, 0x49, 0x4c, 0x41, 0x42, 0x4c, 0x45, 0x10, 0x0e, 0x12, 0x0d, + 0x0a, 0x09, 0x44, 0x41, 0x54, 0x41, 0x5f, 0x4c, 0x4f, 0x53, 0x53, 0x10, 0x0f, 0x42, 0x58, 0x0a, + 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x42, + 0x09, 0x43, 0x6f, 0x64, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x33, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, + 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, + 0x70, 0x69, 0x73, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x63, 0x6f, 0x64, 0x65, 0x3b, 0x63, 0x6f, 0x64, + 0x65, 0xa2, 0x02, 0x03, 0x52, 0x50, 0x43, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } -func init() { - proto.RegisterEnum("google.rpc.Code", Code_name, Code_value) +var ( + file_google_rpc_code_proto_rawDescOnce sync.Once + file_google_rpc_code_proto_rawDescData = file_google_rpc_code_proto_rawDesc +) + +func file_google_rpc_code_proto_rawDescGZIP() []byte { + file_google_rpc_code_proto_rawDescOnce.Do(func() { + file_google_rpc_code_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_rpc_code_proto_rawDescData) + }) + return file_google_rpc_code_proto_rawDescData } -func init() { - proto.RegisterFile("google/rpc/code.proto", fileDescriptor_fe593a732623ccf0) +var file_google_rpc_code_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_google_rpc_code_proto_goTypes = []interface{}{ + (Code)(0), // 0: google.rpc.Code +} +var file_google_rpc_code_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name } -var fileDescriptor_fe593a732623ccf0 = []byte{ - // 362 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0x51, 0xcd, 0x6e, 0x93, 0x31, - 0x10, 0xa4, 0x69, 0x49, 0x9b, 0xcd, 0xdf, 0xd6, 0xa5, 0xf0, 0x0e, 0x1c, 0x92, 0x43, 0x8f, 0x9c, - 0x36, 0x9f, 0x37, 0xad, 0x55, 0x67, 0xfd, 0xc9, 0x3f, 0x25, 0x70, 0xb1, 0x4a, 0x1a, 0x7d, 0x42, - 0x2a, 0x75, 0xf4, 0xc1, 0x13, 0xf1, 0x12, 0xbc, 0x1e, 0x72, 0x8b, 0xe8, 0xc5, 0x87, 0x99, 0xf1, - 0xee, 0xce, 0x0c, 0x5c, 0x76, 0xa5, 0x74, 0x8f, 0xfb, 0x65, 0x7f, 0xd8, 0x2d, 0x77, 0xe5, 0x61, - 0xbf, 0x38, 0xf4, 0xe5, 0x57, 0x51, 0xf0, 0x02, 0x2f, 0xfa, 0xc3, 0xee, 0xe3, 0x9f, 0x01, 0x9c, - 0x34, 0xe5, 0x61, 0xaf, 0x86, 0x30, 0x70, 0xb7, 0xf8, 0x46, 0x4d, 0x61, 0xd4, 0x90, 0x34, 0x6c, - 0x2d, 0x6b, 0x3c, 0x52, 0x63, 0x38, 0x4d, 0x72, 0x2b, 0xee, 0xb3, 0xe0, 0x40, 0xbd, 0x03, 0x34, - 0x72, 0x47, 0xd6, 0xe8, 0x4c, 0xfe, 0x3a, 0x6d, 0x58, 0x22, 0x1e, 0xab, 0x4b, 0x38, 0xd7, 0x4c, - 0xda, 0x1a, 0xe1, 0xcc, 0xdb, 0x86, 0x59, 0xb3, 0xc6, 0x93, 0x3a, 0x48, 0x5c, 0xcc, 0x6b, 0x97, - 0x44, 0xe3, 0x5b, 0xa5, 0x60, 0x46, 0xd6, 0x33, 0xe9, 0x2f, 0x99, 0xb7, 0x26, 0xc4, 0x80, 0xc3, - 0xfa, 0xb3, 0x65, 0xbf, 0x31, 0x21, 0x18, 0x27, 0x59, 0xb3, 0x18, 0xd6, 0x78, 0xaa, 0x2e, 0x60, - 0x9e, 0x84, 0x52, 0xbc, 0x61, 0x89, 0xa6, 0xa1, 0xc8, 0x1a, 0x51, 0xbd, 0x07, 0xe5, 0x39, 0xb8, - 0xe4, 0x9b, 0xba, 0xe5, 0x86, 0x52, 0xa8, 0xf8, 0x99, 0xfa, 0x00, 0x17, 0x6b, 0x32, 0x96, 0x75, - 0x6e, 0x3d, 0x37, 0x4e, 0xb4, 0x89, 0xc6, 0x09, 0x8e, 0xea, 0xe5, 0xb4, 0x72, 0xbe, 0xaa, 0x40, - 0x21, 0x4c, 0x5c, 0x8a, 0xd9, 0xad, 0xb3, 0x27, 0xb9, 0x66, 0x1c, 0xab, 0x73, 0x98, 0x26, 0x31, - 0x9b, 0xd6, 0x72, 0xb5, 0xc1, 0x1a, 0x27, 0x6a, 0x02, 0x67, 0x46, 0x22, 0x7b, 0x21, 0x8b, 0x53, - 0x35, 0x87, 0x71, 0x12, 0xba, 0x23, 0x63, 0x69, 0x65, 0x19, 0x67, 0xd5, 0x90, 0xa6, 0x48, 0xd9, - 0xba, 0x10, 0x70, 0xbe, 0xda, 0xc2, 0x6c, 0x57, 0x7e, 0x2c, 0x5e, 0xb3, 0x5c, 0x8d, 0x6a, 0x90, - 0x6d, 0x8d, 0xb8, 0x3d, 0xfa, 0x7a, 0xf5, 0x8f, 0xe8, 0xca, 0xe3, 0xfd, 0x53, 0xb7, 0x28, 0x7d, - 0xb7, 0xec, 0xf6, 0x4f, 0xcf, 0x05, 0x2c, 0x5f, 0xa8, 0xfb, 0xc3, 0xf7, 0x9f, 0xff, 0xab, 0xf9, - 0x54, 0x9f, 0xdf, 0x83, 0x63, 0xdf, 0x36, 0xdf, 0x86, 0xcf, 0xaa, 0xab, 0xbf, 0x01, 0x00, 0x00, - 0xff, 0xff, 0x8e, 0x97, 0x77, 0xc2, 0xbf, 0x01, 0x00, 0x00, +func init() { file_google_rpc_code_proto_init() } +func file_google_rpc_code_proto_init() { + if File_google_rpc_code_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_rpc_code_proto_rawDesc, + NumEnums: 1, + NumMessages: 0, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_rpc_code_proto_goTypes, + DependencyIndexes: file_google_rpc_code_proto_depIdxs, + EnumInfos: file_google_rpc_code_proto_enumTypes, + }.Build() + File_google_rpc_code_proto = out.File + file_google_rpc_code_proto_rawDesc = nil + file_google_rpc_code_proto_goTypes = nil + file_google_rpc_code_proto_depIdxs = nil } diff --git a/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go b/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go index c988461b639..5dfabd640ba 100644 --- a/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go @@ -1,26 +1,45 @@ +// Copyright 2020 Google LLC +// +// 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 protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.22.0 +// protoc v3.12.3 // source: google/rpc/status.proto package status import ( - fmt "fmt" - math "math" + reflect "reflect" + sync "sync" proto "github.com/golang/protobuf/proto" any "github.com/golang/protobuf/ptypes/any" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 // The `Status` type defines a logical error model that is suitable for // different programming environments, including REST APIs and RPC APIs. It is @@ -30,6 +49,10 @@ const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // You can find out more about this error model and how to work with it in the // [API Design Guide](https://cloud.google.com/apis/design/errors). type Status struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code]. Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` // A developer-facing error message, which should be in English. Any @@ -38,80 +61,146 @@ type Status struct { Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` // A list of messages that carry the error details. There is a common set of // message types for APIs to use. - Details []*any.Any `protobuf:"bytes,3,rep,name=details,proto3" json:"details,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Details []*any.Any `protobuf:"bytes,3,rep,name=details,proto3" json:"details,omitempty"` } -func (m *Status) Reset() { *m = Status{} } -func (m *Status) String() string { return proto.CompactTextString(m) } -func (*Status) ProtoMessage() {} -func (*Status) Descriptor() ([]byte, []int) { - return fileDescriptor_24d244abaf643bfe, []int{0} +func (x *Status) Reset() { + *x = Status{} + if protoimpl.UnsafeEnabled { + mi := &file_google_rpc_status_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Status) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Status.Unmarshal(m, b) -} -func (m *Status) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Status.Marshal(b, m, deterministic) +func (x *Status) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Status) XXX_Merge(src proto.Message) { - xxx_messageInfo_Status.Merge(m, src) -} -func (m *Status) XXX_Size() int { - return xxx_messageInfo_Status.Size(m) -} -func (m *Status) XXX_DiscardUnknown() { - xxx_messageInfo_Status.DiscardUnknown(m) + +func (*Status) ProtoMessage() {} + +func (x *Status) ProtoReflect() protoreflect.Message { + mi := &file_google_rpc_status_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Status proto.InternalMessageInfo +// Deprecated: Use Status.ProtoReflect.Descriptor instead. +func (*Status) Descriptor() ([]byte, []int) { + return file_google_rpc_status_proto_rawDescGZIP(), []int{0} +} -func (m *Status) GetCode() int32 { - if m != nil { - return m.Code +func (x *Status) GetCode() int32 { + if x != nil { + return x.Code } return 0 } -func (m *Status) GetMessage() string { - if m != nil { - return m.Message +func (x *Status) GetMessage() string { + if x != nil { + return x.Message } return "" } -func (m *Status) GetDetails() []*any.Any { - if m != nil { - return m.Details +func (x *Status) GetDetails() []*any.Any { + if x != nil { + return x.Details } return nil } -func init() { - proto.RegisterType((*Status)(nil), "google.rpc.Status") +var File_google_rpc_status_proto protoreflect.FileDescriptor + +var file_google_rpc_status_proto_rawDesc = []byte{ + 0x0a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x73, 0x74, 0x61, + 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x72, 0x70, 0x63, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x22, 0x66, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, + 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x18, + 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x2e, 0x0a, 0x07, 0x64, 0x65, 0x74, 0x61, + 0x69, 0x6c, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, + 0x07, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x42, 0x61, 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x42, 0x0b, 0x53, 0x74, 0x61, 0x74, + 0x75, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x37, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, + 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x3b, 0x73, 0x74, 0x61, 0x74, + 0x75, 0x73, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x03, 0x52, 0x50, 0x43, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, +} + +var ( + file_google_rpc_status_proto_rawDescOnce sync.Once + file_google_rpc_status_proto_rawDescData = file_google_rpc_status_proto_rawDesc +) + +func file_google_rpc_status_proto_rawDescGZIP() []byte { + file_google_rpc_status_proto_rawDescOnce.Do(func() { + file_google_rpc_status_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_rpc_status_proto_rawDescData) + }) + return file_google_rpc_status_proto_rawDescData } -func init() { - proto.RegisterFile("google/rpc/status.proto", fileDescriptor_24d244abaf643bfe) +var file_google_rpc_status_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_google_rpc_status_proto_goTypes = []interface{}{ + (*Status)(nil), // 0: google.rpc.Status + (*any.Any)(nil), // 1: google.protobuf.Any +} +var file_google_rpc_status_proto_depIdxs = []int32{ + 1, // 0: google.rpc.Status.details:type_name -> google.protobuf.Any + 1, // [1:1] is the sub-list for method output_type + 1, // [1:1] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name } -var fileDescriptor_24d244abaf643bfe = []byte{ - // 212 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4f, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0x2a, 0x48, 0xd6, 0x2f, 0x2e, 0x49, 0x2c, 0x29, 0x2d, 0xd6, 0x2b, 0x28, - 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x82, 0x48, 0xe8, 0x15, 0x15, 0x24, 0x4b, 0x49, 0x42, 0x15, 0x81, - 0x65, 0x92, 0x4a, 0xd3, 0xf4, 0x13, 0xf3, 0x2a, 0x21, 0xca, 0x94, 0xd2, 0xb8, 0xd8, 0x82, 0xc1, - 0xda, 0x84, 0x84, 0xb8, 0x58, 0x92, 0xf3, 0x53, 0x52, 0x25, 0x18, 0x15, 0x18, 0x35, 0x58, 0x83, - 0xc0, 0x6c, 0x21, 0x09, 0x2e, 0xf6, 0xdc, 0xd4, 0xe2, 0xe2, 0xc4, 0xf4, 0x54, 0x09, 0x26, 0x05, - 0x46, 0x0d, 0xce, 0x20, 0x18, 0x57, 0x48, 0x8f, 0x8b, 0x3d, 0x25, 0xb5, 0x24, 0x31, 0x33, 0xa7, - 0x58, 0x82, 0x59, 0x81, 0x59, 0x83, 0xdb, 0x48, 0x44, 0x0f, 0x6a, 0x21, 0xcc, 0x12, 0x3d, 0xc7, - 0xbc, 0xca, 0x20, 0x98, 0x22, 0xa7, 0x44, 0x2e, 0xbe, 0xe4, 0xfc, 0x5c, 0x3d, 0x84, 0xa3, 0x9c, - 0xb8, 0x21, 0xf6, 0x06, 0x80, 0x94, 0x07, 0x30, 0x46, 0x99, 0x43, 0xa5, 0xd2, 0xf3, 0x73, 0x12, - 0xf3, 0xd2, 0xf5, 0xf2, 0x8b, 0xd2, 0xf5, 0xd3, 0x53, 0xf3, 0xc0, 0x86, 0xe9, 0x43, 0xa4, 0x12, - 0x0b, 0x32, 0x8b, 0x91, 0xfc, 0x69, 0x0d, 0xa1, 0x7e, 0x30, 0x32, 0x2e, 0x62, 0x62, 0x0e, 0x0a, - 0x70, 0x4e, 0x62, 0x03, 0x2b, 0x36, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xb9, 0x28, 0x45, 0xb1, - 0x13, 0x01, 0x00, 0x00, +func init() { file_google_rpc_status_proto_init() } +func file_google_rpc_status_proto_init() { + if File_google_rpc_status_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_rpc_status_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Status); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_rpc_status_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_rpc_status_proto_goTypes, + DependencyIndexes: file_google_rpc_status_proto_depIdxs, + MessageInfos: file_google_rpc_status_proto_msgTypes, + }.Build() + File_google_rpc_status_proto = out.File + file_google_rpc_status_proto_rawDesc = nil + file_google_rpc_status_proto_goTypes = nil + file_google_rpc_status_proto_depIdxs = nil } diff --git a/vendor/google.golang.org/genproto/googleapis/type/expr/expr.pb.go b/vendor/google.golang.org/genproto/googleapis/type/expr/expr.pb.go index 5f8f3d7c2e2..4d9a47dca94 100644 --- a/vendor/google.golang.org/genproto/googleapis/type/expr/expr.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/type/expr/expr.pb.go @@ -1,25 +1,45 @@ +// Copyright 2019 Google LLC. +// +// 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 protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.22.0 +// protoc v3.12.3 // source: google/type/expr.proto package expr import ( - fmt "fmt" - math "math" + reflect "reflect" + sync "sync" proto "github.com/golang/protobuf/proto" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 // Represents an expression text. Example: // @@ -27,6 +47,10 @@ const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // description: "Determines whether the request has a user account" // expression: "size(request.user) > 0" type Expr struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + // Textual representation of an expression in // Common Expression Language syntax. // @@ -42,86 +66,150 @@ type Expr struct { Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` // An optional string indicating the location of the expression for error // reporting, e.g. a file name and a position in the file. - Location string `protobuf:"bytes,4,opt,name=location,proto3" json:"location,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Location string `protobuf:"bytes,4,opt,name=location,proto3" json:"location,omitempty"` } -func (m *Expr) Reset() { *m = Expr{} } -func (m *Expr) String() string { return proto.CompactTextString(m) } -func (*Expr) ProtoMessage() {} -func (*Expr) Descriptor() ([]byte, []int) { - return fileDescriptor_d7920f1ae7a2722f, []int{0} +func (x *Expr) Reset() { + *x = Expr{} + if protoimpl.UnsafeEnabled { + mi := &file_google_type_expr_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Expr) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Expr.Unmarshal(m, b) -} -func (m *Expr) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Expr.Marshal(b, m, deterministic) -} -func (m *Expr) XXX_Merge(src proto.Message) { - xxx_messageInfo_Expr.Merge(m, src) -} -func (m *Expr) XXX_Size() int { - return xxx_messageInfo_Expr.Size(m) +func (x *Expr) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Expr) XXX_DiscardUnknown() { - xxx_messageInfo_Expr.DiscardUnknown(m) + +func (*Expr) ProtoMessage() {} + +func (x *Expr) ProtoReflect() protoreflect.Message { + mi := &file_google_type_expr_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Expr proto.InternalMessageInfo +// Deprecated: Use Expr.ProtoReflect.Descriptor instead. +func (*Expr) Descriptor() ([]byte, []int) { + return file_google_type_expr_proto_rawDescGZIP(), []int{0} +} -func (m *Expr) GetExpression() string { - if m != nil { - return m.Expression +func (x *Expr) GetExpression() string { + if x != nil { + return x.Expression } return "" } -func (m *Expr) GetTitle() string { - if m != nil { - return m.Title +func (x *Expr) GetTitle() string { + if x != nil { + return x.Title } return "" } -func (m *Expr) GetDescription() string { - if m != nil { - return m.Description +func (x *Expr) GetDescription() string { + if x != nil { + return x.Description } return "" } -func (m *Expr) GetLocation() string { - if m != nil { - return m.Location +func (x *Expr) GetLocation() string { + if x != nil { + return x.Location } return "" } -func init() { - proto.RegisterType((*Expr)(nil), "google.type.Expr") +var File_google_type_expr_proto protoreflect.FileDescriptor + +var file_google_type_expr_proto_rawDesc = []byte{ + 0x0a, 0x16, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x65, 0x78, + 0x70, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x74, 0x79, 0x70, 0x65, 0x22, 0x7a, 0x0a, 0x04, 0x45, 0x78, 0x70, 0x72, 0x12, 0x1e, 0x0a, + 0x0a, 0x65, 0x78, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x0a, 0x65, 0x78, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x14, 0x0a, + 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x69, + 0x74, 0x6c, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1a, 0x0a, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x42, 0x5a, 0x0a, 0x0f, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x74, 0x79, 0x70, 0x65, 0x42, 0x09, 0x45, 0x78, 0x70, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, + 0x01, 0x5a, 0x34, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, + 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x2f, 0x65, 0x78, + 0x70, 0x72, 0x3b, 0x65, 0x78, 0x70, 0x72, 0xa2, 0x02, 0x03, 0x47, 0x54, 0x50, 0x62, 0x06, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_google_type_expr_proto_rawDescOnce sync.Once + file_google_type_expr_proto_rawDescData = file_google_type_expr_proto_rawDesc +) + +func file_google_type_expr_proto_rawDescGZIP() []byte { + file_google_type_expr_proto_rawDescOnce.Do(func() { + file_google_type_expr_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_type_expr_proto_rawDescData) + }) + return file_google_type_expr_proto_rawDescData } -func init() { - proto.RegisterFile("google/type/expr.proto", fileDescriptor_d7920f1ae7a2722f) +var file_google_type_expr_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_google_type_expr_proto_goTypes = []interface{}{ + (*Expr)(nil), // 0: google.type.Expr +} +var file_google_type_expr_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name } -var fileDescriptor_d7920f1ae7a2722f = []byte{ - // 195 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4b, 0xcf, 0xcf, 0x4f, - 0xcf, 0x49, 0xd5, 0x2f, 0xa9, 0x2c, 0x48, 0xd5, 0x4f, 0xad, 0x28, 0x28, 0xd2, 0x2b, 0x28, 0xca, - 0x2f, 0xc9, 0x17, 0xe2, 0x86, 0x88, 0xeb, 0x81, 0xc4, 0x95, 0xaa, 0xb8, 0x58, 0x5c, 0x2b, 0x0a, - 0x8a, 0x84, 0xe4, 0xb8, 0xb8, 0x40, 0x4a, 0x52, 0x8b, 0x8b, 0x33, 0xf3, 0xf3, 0x24, 0x18, 0x15, - 0x18, 0x35, 0x38, 0x83, 0x90, 0x44, 0x84, 0x44, 0xb8, 0x58, 0x4b, 0x32, 0x4b, 0x72, 0x52, 0x25, - 0x98, 0xc0, 0x52, 0x10, 0x8e, 0x90, 0x02, 0x17, 0x77, 0x4a, 0x6a, 0x71, 0x72, 0x51, 0x66, 0x41, - 0x09, 0x48, 0x1b, 0x33, 0x58, 0x0e, 0x59, 0x48, 0x48, 0x8a, 0x8b, 0x23, 0x27, 0x3f, 0x39, 0x11, - 0x2c, 0xcd, 0x02, 0x96, 0x86, 0xf3, 0x9d, 0xa2, 0xb8, 0xf8, 0x93, 0xf3, 0x73, 0xf5, 0x90, 0x9c, - 0xe3, 0xc4, 0x09, 0x72, 0x4c, 0x00, 0xc8, 0x99, 0x01, 0x8c, 0x51, 0x26, 0x50, 0x99, 0xf4, 0xfc, - 0x9c, 0xc4, 0xbc, 0x74, 0xbd, 0xfc, 0xa2, 0x74, 0xfd, 0xf4, 0xd4, 0x3c, 0xb0, 0x27, 0xf4, 0x21, - 0x52, 0x89, 0x05, 0x99, 0xc5, 0x08, 0xff, 0x59, 0x83, 0x88, 0x45, 0x4c, 0xcc, 0xee, 0x21, 0x01, - 0x49, 0x6c, 0x60, 0x65, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xe7, 0x67, 0x9e, 0xf5, 0x05, - 0x01, 0x00, 0x00, +func init() { file_google_type_expr_proto_init() } +func file_google_type_expr_proto_init() { + if File_google_type_expr_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_type_expr_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Expr); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_type_expr_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_type_expr_proto_goTypes, + DependencyIndexes: file_google_type_expr_proto_depIdxs, + MessageInfos: file_google_type_expr_proto_msgTypes, + }.Build() + File_google_type_expr_proto = out.File + file_google_type_expr_proto_rawDesc = nil + file_google_type_expr_proto_goTypes = nil + file_google_type_expr_proto_depIdxs = nil } diff --git a/vendor/google.golang.org/grpc/.travis.yml b/vendor/google.golang.org/grpc/.travis.yml index a11e8cbca66..0e24e59f056 100644 --- a/vendor/google.golang.org/grpc/.travis.yml +++ b/vendor/google.golang.org/grpc/.travis.yml @@ -2,19 +2,19 @@ language: go matrix: include: - - go: 1.13.x + - go: 1.14.x env: VET=1 GO111MODULE=on - - go: 1.13.x + - go: 1.14.x env: RACE=1 GO111MODULE=on - - go: 1.13.x + - go: 1.14.x env: RUN386=1 - - go: 1.13.x + - go: 1.14.x env: GRPC_GO_RETRY=on - - go: 1.13.x + - go: 1.14.x env: TESTEXTRAS=1 - - go: 1.12.x + - go: 1.13.x env: GO111MODULE=on - - go: 1.11.x + - go: 1.12.x env: GO111MODULE=on - go: 1.9.x env: GAE=1 diff --git a/vendor/google.golang.org/grpc/README.md b/vendor/google.golang.org/grpc/README.md index afbc43db510..249cd206327 100644 --- a/vendor/google.golang.org/grpc/README.md +++ b/vendor/google.golang.org/grpc/README.md @@ -7,7 +7,7 @@ The Go implementation of [gRPC](https://grpc.io/): A high performance, open source, general RPC framework that puts mobile and HTTP/2 first. For more information see the [gRPC Quick Start: -Go](https://grpc.io/docs/quickstart/go.html) guide. +Go](https://grpc.io/docs/languages/go/quickstart/) guide. Installation ------------ @@ -29,7 +29,8 @@ If you are trying to access grpc-go from within China, please see the Prerequisites ------------- -gRPC-Go requires Go 1.9 or later. +gRPC-Go officially supports the +[three latest major releases of Go](https://golang.org/doc/devel/release.html). Documentation ------------- @@ -93,6 +94,22 @@ To build Go code, there are several options: #### Compiling error, undefined: grpc.SupportPackageIsVersion +##### If you are using Go modules: + +Please ensure your gRPC-Go version is `require`d at the appropriate version in +the same module containing the generated `.pb.go` files. For example, +`SupportPackageIsVersion6` needs `v1.27.0`, so in your `go.mod` file: + +``` +module + +require ( + google.golang.org/grpc v1.27.0 +) +``` + +##### If you are *not* using Go modules: + Please update proto package, gRPC package and rebuild the proto files: - `go get -u github.com/golang/protobuf/{proto,protoc-gen-go}` - `go get -u google.golang.org/grpc` @@ -114,6 +131,10 @@ possible reasons, including: 1. mis-configured transport credentials, connection failed on handshaking 1. bytes disrupted, possibly by a proxy in between 1. server shutdown + 1. Keepalive parameters caused connection shutdown, for example if you have configured + your server to terminate connections regularly to [trigger DNS lookups](https://github.com/grpc/grpc-go/issues/3170#issuecomment-552517779). + If this is the case, you may want to increase your [MaxConnectionAgeGrace](https://pkg.go.dev/google.golang.org/grpc/keepalive?tab=doc#ServerParameters), + to allow longer RPC calls to finish. It can be tricky to debug this because the error happens on the client side but the root cause of the connection being closed is on the server side. Turn on diff --git a/vendor/google.golang.org/grpc/attributes/attributes.go b/vendor/google.golang.org/grpc/attributes/attributes.go index 68ffc620137..ee5c51e6cdb 100644 --- a/vendor/google.golang.org/grpc/attributes/attributes.go +++ b/vendor/google.golang.org/grpc/attributes/attributes.go @@ -50,6 +50,9 @@ func New(kvs ...interface{}) *Attributes { // times, the last value overwrites all previous values for that key. To // remove an existing key, use a nil value. func (a *Attributes) WithValues(kvs ...interface{}) *Attributes { + if a == nil { + return New(kvs...) + } if len(kvs)%2 != 0 { panic(fmt.Sprintf("attributes.New called with unexpected input: len(kvs) = %v", len(kvs))) } @@ -66,5 +69,8 @@ func (a *Attributes) WithValues(kvs ...interface{}) *Attributes { // Value returns the value associated with these attributes for key, or nil if // no value is associated with key. func (a *Attributes) Value(key interface{}) interface{} { + if a == nil { + return nil + } return a.m[key] } diff --git a/vendor/google.golang.org/grpc/balancer.go b/vendor/google.golang.org/grpc/balancer.go deleted file mode 100644 index a8eb0f47609..00000000000 --- a/vendor/google.golang.org/grpc/balancer.go +++ /dev/null @@ -1,391 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * 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 grpc - -import ( - "context" - "net" - "sync" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/naming" - "google.golang.org/grpc/status" -) - -// Address represents a server the client connects to. -// -// Deprecated: please use package balancer. -type Address struct { - // Addr is the server address on which a connection will be established. - Addr string - // Metadata is the information associated with Addr, which may be used - // to make load balancing decision. - Metadata interface{} -} - -// BalancerConfig specifies the configurations for Balancer. -// -// Deprecated: please use package balancer. May be removed in a future 1.x release. -type BalancerConfig struct { - // DialCreds is the transport credential the Balancer implementation can - // use to dial to a remote load balancer server. The Balancer implementations - // can ignore this if it does not need to talk to another party securely. - DialCreds credentials.TransportCredentials - // Dialer is the custom dialer the Balancer implementation can use to dial - // to a remote load balancer server. The Balancer implementations - // can ignore this if it doesn't need to talk to remote balancer. - Dialer func(context.Context, string) (net.Conn, error) -} - -// BalancerGetOptions configures a Get call. -// -// Deprecated: please use package balancer. May be removed in a future 1.x release. -type BalancerGetOptions struct { - // BlockingWait specifies whether Get should block when there is no - // connected address. - BlockingWait bool -} - -// Balancer chooses network addresses for RPCs. -// -// Deprecated: please use package balancer. May be removed in a future 1.x release. -type Balancer interface { - // Start does the initialization work to bootstrap a Balancer. For example, - // this function may start the name resolution and watch the updates. It will - // be called when dialing. - Start(target string, config BalancerConfig) error - // Up informs the Balancer that gRPC has a connection to the server at - // addr. It returns down which is called once the connection to addr gets - // lost or closed. - // TODO: It is not clear how to construct and take advantage of the meaningful error - // parameter for down. Need realistic demands to guide. - Up(addr Address) (down func(error)) - // Get gets the address of a server for the RPC corresponding to ctx. - // i) If it returns a connected address, gRPC internals issues the RPC on the - // connection to this address; - // ii) If it returns an address on which the connection is under construction - // (initiated by Notify(...)) but not connected, gRPC internals - // * fails RPC if the RPC is fail-fast and connection is in the TransientFailure or - // Shutdown state; - // or - // * issues RPC on the connection otherwise. - // iii) If it returns an address on which the connection does not exist, gRPC - // internals treats it as an error and will fail the corresponding RPC. - // - // Therefore, the following is the recommended rule when writing a custom Balancer. - // If opts.BlockingWait is true, it should return a connected address or - // block if there is no connected address. It should respect the timeout or - // cancellation of ctx when blocking. If opts.BlockingWait is false (for fail-fast - // RPCs), it should return an address it has notified via Notify(...) immediately - // instead of blocking. - // - // The function returns put which is called once the rpc has completed or failed. - // put can collect and report RPC stats to a remote load balancer. - // - // This function should only return the errors Balancer cannot recover by itself. - // gRPC internals will fail the RPC if an error is returned. - Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) - // Notify returns a channel that is used by gRPC internals to watch the addresses - // gRPC needs to connect. The addresses might be from a name resolver or remote - // load balancer. gRPC internals will compare it with the existing connected - // addresses. If the address Balancer notified is not in the existing connected - // addresses, gRPC starts to connect the address. If an address in the existing - // connected addresses is not in the notification list, the corresponding connection - // is shutdown gracefully. Otherwise, there are no operations to take. Note that - // the Address slice must be the full list of the Addresses which should be connected. - // It is NOT delta. - Notify() <-chan []Address - // Close shuts down the balancer. - Close() error -} - -// RoundRobin returns a Balancer that selects addresses round-robin. It uses r to watch -// the name resolution updates and updates the addresses available correspondingly. -// -// Deprecated: please use package balancer/roundrobin. May be removed in a future 1.x release. -func RoundRobin(r naming.Resolver) Balancer { - return &roundRobin{r: r} -} - -type addrInfo struct { - addr Address - connected bool -} - -type roundRobin struct { - r naming.Resolver - w naming.Watcher - addrs []*addrInfo // all the addresses the client should potentially connect - mu sync.Mutex - addrCh chan []Address // the channel to notify gRPC internals the list of addresses the client should connect to. - next int // index of the next address to return for Get() - waitCh chan struct{} // the channel to block when there is no connected address available - done bool // The Balancer is closed. -} - -func (rr *roundRobin) watchAddrUpdates() error { - updates, err := rr.w.Next() - if err != nil { - grpclog.Warningf("grpc: the naming watcher stops working due to %v.", err) - return err - } - rr.mu.Lock() - defer rr.mu.Unlock() - for _, update := range updates { - addr := Address{ - Addr: update.Addr, - Metadata: update.Metadata, - } - switch update.Op { - case naming.Add: - var exist bool - for _, v := range rr.addrs { - if addr == v.addr { - exist = true - grpclog.Infoln("grpc: The name resolver wanted to add an existing address: ", addr) - break - } - } - if exist { - continue - } - rr.addrs = append(rr.addrs, &addrInfo{addr: addr}) - case naming.Delete: - for i, v := range rr.addrs { - if addr == v.addr { - copy(rr.addrs[i:], rr.addrs[i+1:]) - rr.addrs = rr.addrs[:len(rr.addrs)-1] - break - } - } - default: - grpclog.Errorln("Unknown update.Op ", update.Op) - } - } - // Make a copy of rr.addrs and write it onto rr.addrCh so that gRPC internals gets notified. - open := make([]Address, len(rr.addrs)) - for i, v := range rr.addrs { - open[i] = v.addr - } - if rr.done { - return ErrClientConnClosing - } - select { - case <-rr.addrCh: - default: - } - rr.addrCh <- open - return nil -} - -func (rr *roundRobin) Start(target string, config BalancerConfig) error { - rr.mu.Lock() - defer rr.mu.Unlock() - if rr.done { - return ErrClientConnClosing - } - if rr.r == nil { - // If there is no name resolver installed, it is not needed to - // do name resolution. In this case, target is added into rr.addrs - // as the only address available and rr.addrCh stays nil. - rr.addrs = append(rr.addrs, &addrInfo{addr: Address{Addr: target}}) - return nil - } - w, err := rr.r.Resolve(target) - if err != nil { - return err - } - rr.w = w - rr.addrCh = make(chan []Address, 1) - go func() { - for { - if err := rr.watchAddrUpdates(); err != nil { - return - } - } - }() - return nil -} - -// Up sets the connected state of addr and sends notification if there are pending -// Get() calls. -func (rr *roundRobin) Up(addr Address) func(error) { - rr.mu.Lock() - defer rr.mu.Unlock() - var cnt int - for _, a := range rr.addrs { - if a.addr == addr { - if a.connected { - return nil - } - a.connected = true - } - if a.connected { - cnt++ - } - } - // addr is only one which is connected. Notify the Get() callers who are blocking. - if cnt == 1 && rr.waitCh != nil { - close(rr.waitCh) - rr.waitCh = nil - } - return func(err error) { - rr.down(addr, err) - } -} - -// down unsets the connected state of addr. -func (rr *roundRobin) down(addr Address, err error) { - rr.mu.Lock() - defer rr.mu.Unlock() - for _, a := range rr.addrs { - if addr == a.addr { - a.connected = false - break - } - } -} - -// Get returns the next addr in the rotation. -func (rr *roundRobin) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) { - var ch chan struct{} - rr.mu.Lock() - if rr.done { - rr.mu.Unlock() - err = ErrClientConnClosing - return - } - - if len(rr.addrs) > 0 { - if rr.next >= len(rr.addrs) { - rr.next = 0 - } - next := rr.next - for { - a := rr.addrs[next] - next = (next + 1) % len(rr.addrs) - if a.connected { - addr = a.addr - rr.next = next - rr.mu.Unlock() - return - } - if next == rr.next { - // Has iterated all the possible address but none is connected. - break - } - } - } - if !opts.BlockingWait { - if len(rr.addrs) == 0 { - rr.mu.Unlock() - err = status.Errorf(codes.Unavailable, "there is no address available") - return - } - // Returns the next addr on rr.addrs for failfast RPCs. - addr = rr.addrs[rr.next].addr - rr.next++ - rr.mu.Unlock() - return - } - // Wait on rr.waitCh for non-failfast RPCs. - if rr.waitCh == nil { - ch = make(chan struct{}) - rr.waitCh = ch - } else { - ch = rr.waitCh - } - rr.mu.Unlock() - for { - select { - case <-ctx.Done(): - err = ctx.Err() - return - case <-ch: - rr.mu.Lock() - if rr.done { - rr.mu.Unlock() - err = ErrClientConnClosing - return - } - - if len(rr.addrs) > 0 { - if rr.next >= len(rr.addrs) { - rr.next = 0 - } - next := rr.next - for { - a := rr.addrs[next] - next = (next + 1) % len(rr.addrs) - if a.connected { - addr = a.addr - rr.next = next - rr.mu.Unlock() - return - } - if next == rr.next { - // Has iterated all the possible address but none is connected. - break - } - } - } - // The newly added addr got removed by Down() again. - if rr.waitCh == nil { - ch = make(chan struct{}) - rr.waitCh = ch - } else { - ch = rr.waitCh - } - rr.mu.Unlock() - } - } -} - -func (rr *roundRobin) Notify() <-chan []Address { - return rr.addrCh -} - -func (rr *roundRobin) Close() error { - rr.mu.Lock() - defer rr.mu.Unlock() - if rr.done { - return errBalancerClosed - } - rr.done = true - if rr.w != nil { - rr.w.Close() - } - if rr.waitCh != nil { - close(rr.waitCh) - rr.waitCh = nil - } - if rr.addrCh != nil { - close(rr.addrCh) - } - return nil -} - -// pickFirst is used to test multi-addresses in one addrConn in which all addresses share the same addrConn. -// It is a wrapper around roundRobin balancer. The logic of all methods works fine because balancer.Get() -// returns the only address Up by resetTransport(). -type pickFirst struct { - *roundRobin -} diff --git a/vendor/google.golang.org/grpc/balancer/balancer.go b/vendor/google.golang.org/grpc/balancer/balancer.go index 9258858ed75..e75b2843604 100644 --- a/vendor/google.golang.org/grpc/balancer/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/balancer.go @@ -111,6 +111,9 @@ type NewSubConnOptions struct { // CredsBundle is the credentials bundle that will be used in the created // SubConn. If it's nil, the original creds from grpc DialOptions will be // used. + // + // Deprecated: Use the Attributes field in resolver.Address to pass + // arbitrary data to the credential handshaker. CredsBundle credentials.Bundle // HealthCheckEnabled indicates whether health check service should be // enabled on this SubConn @@ -123,7 +126,7 @@ type State struct { // determine the state of the ClientConn. ConnectivityState connectivity.State // Picker is used to choose connections (SubConns) for RPCs. - Picker V2Picker + Picker Picker } // ClientConn represents a gRPC ClientConn. @@ -141,20 +144,11 @@ type ClientConn interface { // The SubConn will be shutdown. RemoveSubConn(SubConn) - // UpdateBalancerState is called by balancer to notify gRPC that some internal - // state in balancer has changed. - // - // gRPC will update the connectivity state of the ClientConn, and will call pick - // on the new picker to pick new SubConn. - // - // Deprecated: use UpdateState instead - UpdateBalancerState(s connectivity.State, p Picker) - // UpdateState notifies gRPC that the balancer's internal state has // changed. // - // gRPC will update the connectivity state of the ClientConn, and will call pick - // on the new picker to pick new SubConns. + // gRPC will update the connectivity state of the ClientConn, and will call + // Pick on the new Picker to pick new SubConns. UpdateState(State) // ResolveNow is called by balancer to notify gRPC to do a name resolving. @@ -232,55 +226,16 @@ type DoneInfo struct { var ( // ErrNoSubConnAvailable indicates no SubConn is available for pick(). - // gRPC will block the RPC until a new picker is available via UpdateBalancerState(). + // gRPC will block the RPC until a new picker is available via UpdateState(). ErrNoSubConnAvailable = errors.New("no SubConn is available") // ErrTransientFailure indicates all SubConns are in TransientFailure. // WaitForReady RPCs will block, non-WaitForReady RPCs will fail. - ErrTransientFailure = TransientFailureError(errors.New("all SubConns are in TransientFailure")) -) - -// Picker is used by gRPC to pick a SubConn to send an RPC. -// Balancer is expected to generate a new picker from its snapshot every time its -// internal state has changed. -// -// The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState(). -// -// Deprecated: use V2Picker instead -type Picker interface { - // Pick returns the SubConn to be used to send the RPC. - // The returned SubConn must be one returned by NewSubConn(). - // - // This functions is expected to return: - // - a SubConn that is known to be READY; - // - ErrNoSubConnAvailable if no SubConn is available, but progress is being - // made (for example, some SubConn is in CONNECTING mode); - // - other errors if no active connecting is happening (for example, all SubConn - // are in TRANSIENT_FAILURE mode). - // - // If a SubConn is returned: - // - If it is READY, gRPC will send the RPC on it; - // - If it is not ready, or becomes not ready after it's returned, gRPC will - // block until UpdateBalancerState() is called and will call pick on the - // new picker. The done function returned from Pick(), if not nil, will be - // called with nil error, no bytes sent and no bytes received. - // - // If the returned error is not nil: - // - If the error is ErrNoSubConnAvailable, gRPC will block until UpdateBalancerState() - // - If the error is ErrTransientFailure or implements IsTransientFailure() - // bool, returning true: - // - If the RPC is wait-for-ready, gRPC will block until UpdateBalancerState() - // is called to pick again; - // - Otherwise, RPC will fail with unavailable error. - // - Else (error is other non-nil error): - // - The RPC will fail with the error's status code, or Unknown if it is - // not a status error. // - // The returned done() function will be called once the rpc has finished, - // with the final status of that RPC. If the SubConn returned is not a - // valid SubConn type, done may not be called. done may be nil if balancer - // doesn't care about the RPC status. - Pick(ctx context.Context, info PickInfo) (conn SubConn, done func(DoneInfo), err error) -} + // Deprecated: return an appropriate error based on the last resolution or + // connection attempt instead. The behavior is the same for any non-gRPC + // status error. + ErrTransientFailure = errors.New("all SubConns are in TransientFailure") +) // PickResult contains information related to a connection chosen for an RPC. type PickResult struct { @@ -297,24 +252,19 @@ type PickResult struct { Done func(DoneInfo) } -type transientFailureError struct { - error -} - -func (e *transientFailureError) IsTransientFailure() bool { return true } - -// TransientFailureError wraps err in an error implementing -// IsTransientFailure() bool, returning true. -func TransientFailureError(err error) error { - return &transientFailureError{error: err} -} +// TransientFailureError returns e. It exists for backward compatibility and +// will be deleted soon. +// +// Deprecated: no longer necessary, picker errors are treated this way by +// default. +func TransientFailureError(e error) error { return e } -// V2Picker is used by gRPC to pick a SubConn to send an RPC. +// Picker is used by gRPC to pick a SubConn to send an RPC. // Balancer is expected to generate a new picker from its snapshot every time its // internal state has changed. // -// The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState(). -type V2Picker interface { +// The pickers used by gRPC can be updated by ClientConn.UpdateState(). +type Picker interface { // Pick returns the connection to use for this RPC and related information. // // Pick should not block. If the balancer needs to do I/O or any blocking @@ -327,14 +277,13 @@ type V2Picker interface { // - If the error is ErrNoSubConnAvailable, gRPC will block until a new // Picker is provided by the balancer (using ClientConn.UpdateState). // - // - If the error implements IsTransientFailure() bool, returning true, - // wait for ready RPCs will wait, but non-wait for ready RPCs will be - // terminated with this error's Error() string and status code - // Unavailable. + // - If the error is a status error (implemented by the grpc/status + // package), gRPC will terminate the RPC with the code and message + // provided. // - // - Any other errors terminate all RPCs with the code and message - // provided. If the error is not a status error, it will be converted by - // gRPC to a status error with code Unknown. + // - For all other errors, wait for ready RPCs will wait, but non-wait for + // ready RPCs will be terminated with this error's Error() string and + // status code Unavailable. Pick(info PickInfo) (PickResult, error) } @@ -343,34 +292,36 @@ type V2Picker interface { // // It also generates and updates the Picker used by gRPC to pick SubConns for RPCs. // -// HandleSubConnectionStateChange, HandleResolvedAddrs and Close are guaranteed -// to be called synchronously from the same goroutine. -// There's no guarantee on picker.Pick, it may be called anytime. +// UpdateClientConnState, ResolverError, UpdateSubConnState, and Close are +// guaranteed to be called synchronously from the same goroutine. There's no +// guarantee on picker.Pick, it may be called anytime. type Balancer interface { - // HandleSubConnStateChange is called by gRPC when the connectivity state - // of sc has changed. - // Balancer is expected to aggregate all the state of SubConn and report - // that back to gRPC. - // Balancer should also generate and update Pickers when its internal state has - // been changed by the new state. - // - // Deprecated: if V2Balancer is implemented by the Balancer, - // UpdateSubConnState will be called instead. - HandleSubConnStateChange(sc SubConn, state connectivity.State) - // HandleResolvedAddrs is called by gRPC to send updated resolved addresses to - // balancers. - // Balancer can create new SubConn or remove SubConn with the addresses. - // An empty address slice and a non-nil error will be passed if the resolver returns - // non-nil error to gRPC. - // - // Deprecated: if V2Balancer is implemented by the Balancer, - // UpdateClientConnState will be called instead. - HandleResolvedAddrs([]resolver.Address, error) + // UpdateClientConnState is called by gRPC when the state of the ClientConn + // changes. If the error returned is ErrBadResolverState, the ClientConn + // will begin calling ResolveNow on the active name resolver with + // exponential backoff until a subsequent call to UpdateClientConnState + // returns a nil error. Any other errors are currently ignored. + UpdateClientConnState(ClientConnState) error + // ResolverError is called by gRPC when the name resolver reports an error. + ResolverError(error) + // UpdateSubConnState is called by gRPC when the state of a SubConn + // changes. + UpdateSubConnState(SubConn, SubConnState) // Close closes the balancer. The balancer is not required to call // ClientConn.RemoveSubConn for its existing SubConns. Close() } +// V2Balancer is temporarily defined for backward compatibility reasons. +// +// Deprecated: use Balancer directly instead. +type V2Balancer = Balancer + +// V2Picker is temporarily defined for backward compatibility reasons. +// +// Deprecated: use Picker directly instead. +type V2Picker = Picker + // SubConnState describes the state of a SubConn. type SubConnState struct { // ConnectivityState is the connectivity state of the SubConn. @@ -393,27 +344,6 @@ type ClientConnState struct { // problem with the provided name resolver data. var ErrBadResolverState = errors.New("bad resolver state") -// V2Balancer is defined for documentation purposes. If a Balancer also -// implements V2Balancer, its UpdateClientConnState method will be called -// instead of HandleResolvedAddrs and its UpdateSubConnState will be called -// instead of HandleSubConnStateChange. -type V2Balancer interface { - // UpdateClientConnState is called by gRPC when the state of the ClientConn - // changes. If the error returned is ErrBadResolverState, the ClientConn - // will begin calling ResolveNow on the active name resolver with - // exponential backoff until a subsequent call to UpdateClientConnState - // returns a nil error. Any other errors are currently ignored. - UpdateClientConnState(ClientConnState) error - // ResolverError is called by gRPC when the name resolver reports an error. - ResolverError(error) - // UpdateSubConnState is called by gRPC when the state of a SubConn - // changes. - UpdateSubConnState(SubConn, SubConnState) - // Close closes the balancer. The balancer is not required to call - // ClientConn.RemoveSubConn for its existing SubConns. - Close() -} - // ConnectivityStateEvaluator takes the connectivity states of multiple SubConns // and returns one aggregated connectivity state. // diff --git a/vendor/google.golang.org/grpc/balancer/base/balancer.go b/vendor/google.golang.org/grpc/balancer/base/balancer.go index d7d72918ad6..d62b4b6069a 100644 --- a/vendor/google.golang.org/grpc/balancer/base/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/base/balancer.go @@ -19,7 +19,6 @@ package base import ( - "context" "errors" "fmt" @@ -30,17 +29,15 @@ import ( ) type baseBuilder struct { - name string - pickerBuilder PickerBuilder - v2PickerBuilder V2PickerBuilder - config Config + name string + pickerBuilder PickerBuilder + config Config } func (bb *baseBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer { bal := &baseBalancer{ - cc: cc, - pickerBuilder: bb.pickerBuilder, - v2PickerBuilder: bb.v2PickerBuilder, + cc: cc, + pickerBuilder: bb.pickerBuilder, subConns: make(map[resolver.Address]balancer.SubConn), scStates: make(map[balancer.SubConn]connectivity.State), @@ -50,11 +47,7 @@ func (bb *baseBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) // Initialize picker to a picker that always returns // ErrNoSubConnAvailable, because when state of a SubConn changes, we // may call UpdateState with this picker. - if bb.pickerBuilder != nil { - bal.picker = NewErrPicker(balancer.ErrNoSubConnAvailable) - } else { - bal.v2Picker = NewErrPickerV2(balancer.ErrNoSubConnAvailable) - } + bal.picker = NewErrPicker(balancer.ErrNoSubConnAvailable) return bal } @@ -62,12 +55,9 @@ func (bb *baseBuilder) Name() string { return bb.name } -var _ balancer.V2Balancer = (*baseBalancer)(nil) // Assert that we implement V2Balancer - type baseBalancer struct { - cc balancer.ClientConn - pickerBuilder PickerBuilder - v2PickerBuilder V2PickerBuilder + cc balancer.ClientConn + pickerBuilder PickerBuilder csEvltr *balancer.ConnectivityStateEvaluator state connectivity.State @@ -75,48 +65,35 @@ type baseBalancer struct { subConns map[resolver.Address]balancer.SubConn scStates map[balancer.SubConn]connectivity.State picker balancer.Picker - v2Picker balancer.V2Picker config Config resolverErr error // the last error reported by the resolver; cleared on successful resolution connErr error // the last connection error; cleared upon leaving TransientFailure } -func (b *baseBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { - panic("not implemented") -} - func (b *baseBalancer) ResolverError(err error) { b.resolverErr = err if len(b.subConns) == 0 { b.state = connectivity.TransientFailure } + if b.state != connectivity.TransientFailure { // The picker will not change since the balancer does not currently // report an error. return } b.regeneratePicker() - if b.picker != nil { - b.cc.UpdateBalancerState(b.state, b.picker) - } else { - b.cc.UpdateState(balancer.State{ - ConnectivityState: b.state, - Picker: b.v2Picker, - }) - } + b.cc.UpdateState(balancer.State{ + ConnectivityState: b.state, + Picker: b.picker, + }) } func (b *baseBalancer) UpdateClientConnState(s balancer.ClientConnState) error { - // TODO: handle s.ResolverState.Err (log if not nil) once implemented. // TODO: handle s.ResolverState.ServiceConfig? if grpclog.V(2) { grpclog.Infoln("base.baseBalancer: got new ClientConn state: ", s) } - if len(s.ResolverState.Addresses) == 0 { - b.ResolverError(errors.New("produced zero addresses")) - return balancer.ErrBadResolverState - } // Successful resolution; clear resolver error and ensure we return nil. b.resolverErr = nil // addrsSet is the set converted from addrs, it's used for quick lookup of an address. @@ -141,9 +118,17 @@ func (b *baseBalancer) UpdateClientConnState(s balancer.ClientConnState) error { b.cc.RemoveSubConn(sc) delete(b.subConns, a) // Keep the state of this sc in b.scStates until sc's state becomes Shutdown. - // The entry will be deleted in HandleSubConnStateChange. + // The entry will be deleted in UpdateSubConnState. } } + // If resolver state contains no addresses, return an error so ClientConn + // will trigger re-resolve. Also records this as an resolver error, so when + // the overall state turns transient failure, the error message will have + // the zero address information. + if len(s.ResolverState.Addresses) == 0 { + b.ResolverError(errors.New("produced zero addresses")) + return balancer.ErrBadResolverState + } return nil } @@ -167,38 +152,18 @@ func (b *baseBalancer) mergeErrors() error { // - built by the pickerBuilder with all READY SubConns otherwise. func (b *baseBalancer) regeneratePicker() { if b.state == connectivity.TransientFailure { - if b.pickerBuilder != nil { - b.picker = NewErrPicker(balancer.ErrTransientFailure) - } else { - b.v2Picker = NewErrPickerV2(balancer.TransientFailureError(b.mergeErrors())) - } + b.picker = NewErrPicker(b.mergeErrors()) return } - if b.pickerBuilder != nil { - readySCs := make(map[resolver.Address]balancer.SubConn) + readySCs := make(map[balancer.SubConn]SubConnInfo) - // Filter out all ready SCs from full subConn map. - for addr, sc := range b.subConns { - if st, ok := b.scStates[sc]; ok && st == connectivity.Ready { - readySCs[addr] = sc - } + // Filter out all ready SCs from full subConn map. + for addr, sc := range b.subConns { + if st, ok := b.scStates[sc]; ok && st == connectivity.Ready { + readySCs[sc] = SubConnInfo{Address: addr} } - b.picker = b.pickerBuilder.Build(readySCs) - } else { - readySCs := make(map[balancer.SubConn]SubConnInfo) - - // Filter out all ready SCs from full subConn map. - for addr, sc := range b.subConns { - if st, ok := b.scStates[sc]; ok && st == connectivity.Ready { - readySCs[sc] = SubConnInfo{Address: addr} - } - } - b.v2Picker = b.v2PickerBuilder.Build(PickerBuildInfo{ReadySCs: readySCs}) } -} - -func (b *baseBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - panic("not implemented") + b.picker = b.pickerBuilder.Build(PickerBuildInfo{ReadySCs: readySCs}) } func (b *baseBalancer) UpdateSubConnState(sc balancer.SubConn, state balancer.SubConnState) { @@ -213,6 +178,12 @@ func (b *baseBalancer) UpdateSubConnState(sc balancer.SubConn, state balancer.Su } return } + if oldS == connectivity.TransientFailure && s == connectivity.Connecting { + // Once a subconn enters TRANSIENT_FAILURE, ignore subsequent + // CONNECTING transitions to prevent the aggregated state from being + // always CONNECTING when many backends exist but are all down. + return + } b.scStates[sc] = s switch s { case connectivity.Idle: @@ -221,29 +192,23 @@ func (b *baseBalancer) UpdateSubConnState(sc balancer.SubConn, state balancer.Su // When an address was removed by resolver, b called RemoveSubConn but // kept the sc's state in scStates. Remove state for this sc here. delete(b.scStates, sc) + case connectivity.TransientFailure: + // Save error to be reported via picker. + b.connErr = state.ConnectionError } - oldAggrState := b.state b.state = b.csEvltr.RecordTransition(oldS, s) - // Set or clear the last connection error accordingly. - b.connErr = state.ConnectionError - // Regenerate picker when one of the following happens: - // - this sc became ready from not-ready - // - this sc became not-ready from ready - // - the aggregated state of balancer became TransientFailure from non-TransientFailure - // - the aggregated state of balancer became non-TransientFailure from TransientFailure + // - this sc entered or left ready + // - the aggregated state of balancer is TransientFailure + // (may need to update error message) if (s == connectivity.Ready) != (oldS == connectivity.Ready) || - (b.state == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) { + b.state == connectivity.TransientFailure { b.regeneratePicker() } - if b.picker != nil { - b.cc.UpdateBalancerState(b.state, b.picker) - } else { - b.cc.UpdateState(balancer.State{ConnectivityState: b.state, Picker: b.v2Picker}) - } + b.cc.UpdateState(balancer.State{ConnectivityState: b.state, Picker: b.picker}) } // Close is a nop because base balancer doesn't have internal state to clean up, @@ -251,28 +216,20 @@ func (b *baseBalancer) UpdateSubConnState(sc balancer.SubConn, state balancer.Su func (b *baseBalancer) Close() { } -// NewErrPicker returns a picker that always returns err on Pick(). +// NewErrPicker returns a Picker that always returns err on Pick(). func NewErrPicker(err error) balancer.Picker { return &errPicker{err: err} } -type errPicker struct { - err error // Pick() always returns this err. -} - -func (p *errPicker) Pick(context.Context, balancer.PickInfo) (balancer.SubConn, func(balancer.DoneInfo), error) { - return nil, nil, p.err -} - -// NewErrPickerV2 returns a V2Picker that always returns err on Pick(). -func NewErrPickerV2(err error) balancer.V2Picker { - return &errPickerV2{err: err} -} +// NewErrPickerV2 is temporarily defined for backward compatibility reasons. +// +// Deprecated: use NewErrPicker instead. +var NewErrPickerV2 = NewErrPicker -type errPickerV2 struct { +type errPicker struct { err error // Pick() always returns this err. } -func (p *errPickerV2) Pick(info balancer.PickInfo) (balancer.PickResult, error) { +func (p *errPicker) Pick(info balancer.PickInfo) (balancer.PickResult, error) { return balancer.PickResult{}, p.err } diff --git a/vendor/google.golang.org/grpc/balancer/base/base.go b/vendor/google.golang.org/grpc/balancer/base/base.go index 4192918b9e2..c4fc89111bf 100644 --- a/vendor/google.golang.org/grpc/balancer/base/base.go +++ b/vendor/google.golang.org/grpc/balancer/base/base.go @@ -37,15 +37,8 @@ import ( // PickerBuilder creates balancer.Picker. type PickerBuilder interface { - // Build takes a slice of ready SubConns, and returns a picker that will be - // used by gRPC to pick a SubConn. - Build(readySCs map[resolver.Address]balancer.SubConn) balancer.Picker -} - -// V2PickerBuilder creates balancer.V2Picker. -type V2PickerBuilder interface { // Build returns a picker that will be used by gRPC to pick a SubConn. - Build(info PickerBuildInfo) balancer.V2Picker + Build(info PickerBuildInfo) balancer.Picker } // PickerBuildInfo contains information needed by the picker builder to @@ -62,20 +55,14 @@ type SubConnInfo struct { Address resolver.Address // the address used to create this SubConn } -// NewBalancerBuilder returns a balancer builder. The balancers -// built by this builder will use the picker builder to build pickers. -func NewBalancerBuilder(name string, pb PickerBuilder) balancer.Builder { - return NewBalancerBuilderWithConfig(name, pb, Config{}) -} - // Config contains the config info about the base balancer builder. type Config struct { // HealthCheck indicates whether health checking should be enabled for this specific balancer. HealthCheck bool } -// NewBalancerBuilderWithConfig returns a base balancer builder configured by the provided config. -func NewBalancerBuilderWithConfig(name string, pb PickerBuilder, config Config) balancer.Builder { +// NewBalancerBuilder returns a base balancer builder configured by the provided config. +func NewBalancerBuilder(name string, pb PickerBuilder, config Config) balancer.Builder { return &baseBuilder{ name: name, pickerBuilder: pb, @@ -83,11 +70,13 @@ func NewBalancerBuilderWithConfig(name string, pb PickerBuilder, config Config) } } -// NewBalancerBuilderV2 returns a base balancer builder configured by the provided config. -func NewBalancerBuilderV2(name string, pb V2PickerBuilder, config Config) balancer.Builder { - return &baseBuilder{ - name: name, - v2PickerBuilder: pb, - config: config, - } -} +// NewBalancerBuilderV2 is temporarily defined for backward compatibility +// reasons. +// +// Deprecated: use NewBalancerBuilder instead. +var NewBalancerBuilderV2 = NewBalancerBuilder + +// V2PickerBuilder is temporarily defined for backward compatibility reasons. +// +// Deprecated: use PickerBuilder instead. +type V2PickerBuilder = PickerBuilder diff --git a/vendor/google.golang.org/grpc/balancer/grpclb/state/state.go b/vendor/google.golang.org/grpc/balancer/grpclb/state/state.go new file mode 100644 index 00000000000..a24264a34f5 --- /dev/null +++ b/vendor/google.golang.org/grpc/balancer/grpclb/state/state.go @@ -0,0 +1,51 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * 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 state declares grpclb types to be set by resolvers wishing to pass +// information to grpclb via resolver.State Attributes. +package state + +import ( + "google.golang.org/grpc/resolver" +) + +// keyType is the key to use for storing State in Attributes. +type keyType string + +const key = keyType("grpc.grpclb.state") + +// State contains gRPCLB-relevant data passed from the name resolver. +type State struct { + // BalancerAddresses contains the remote load balancer address(es). If + // set, overrides any resolver-provided addresses with Type of GRPCLB. + BalancerAddresses []resolver.Address +} + +// Set returns a copy of the provided state with attributes containing s. s's +// data should not be mutated after calling Set. +func Set(state resolver.State, s *State) resolver.State { + state.Attributes = state.Attributes.WithValues(key, s) + return state +} + +// Get returns the grpclb State in the resolver.State, or nil if not present. +// The returned data should not be mutated. +func Get(state resolver.State) *State { + s, _ := state.Attributes.Value(key).(*State) + return s +} diff --git a/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go b/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go index d4d645501c1..a02b372cf20 100644 --- a/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go +++ b/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go @@ -35,7 +35,7 @@ const Name = "round_robin" // newBuilder creates a new roundrobin balancer builder. func newBuilder() balancer.Builder { - return base.NewBalancerBuilderV2(Name, &rrPickerBuilder{}, base.Config{HealthCheck: true}) + return base.NewBalancerBuilder(Name, &rrPickerBuilder{}, base.Config{HealthCheck: true}) } func init() { @@ -44,10 +44,10 @@ func init() { type rrPickerBuilder struct{} -func (*rrPickerBuilder) Build(info base.PickerBuildInfo) balancer.V2Picker { +func (*rrPickerBuilder) Build(info base.PickerBuildInfo) balancer.Picker { grpclog.Infof("roundrobinPicker: newPicker called with info: %v", info) if len(info.ReadySCs) == 0 { - return base.NewErrPickerV2(balancer.ErrNoSubConnAvailable) + return base.NewErrPicker(balancer.ErrNoSubConnAvailable) } var scs []balancer.SubConn for sc := range info.ReadySCs { diff --git a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go b/vendor/google.golang.org/grpc/balancer_conn_wrappers.go index 824f28e740a..807d1919777 100644 --- a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go +++ b/vendor/google.golang.org/grpc/balancer_conn_wrappers.go @@ -24,8 +24,8 @@ import ( "google.golang.org/grpc/balancer" "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/buffer" + "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/resolver" ) @@ -74,11 +74,7 @@ func (ccb *ccBalancerWrapper) watcher() { } ccb.balancerMu.Lock() su := t.(*scStateUpdate) - if ub, ok := ccb.balancer.(balancer.V2Balancer); ok { - ub.UpdateSubConnState(su.sc, balancer.SubConnState{ConnectivityState: su.state, ConnectionError: su.err}) - } else { - ccb.balancer.HandleSubConnStateChange(su.sc, su.state) - } + ccb.balancer.UpdateSubConnState(su.sc, balancer.SubConnState{ConnectivityState: su.state, ConnectionError: su.err}) ccb.balancerMu.Unlock() case <-ccb.done.Done(): } @@ -123,19 +119,13 @@ func (ccb *ccBalancerWrapper) handleSubConnStateChange(sc balancer.SubConn, s co func (ccb *ccBalancerWrapper) updateClientConnState(ccs *balancer.ClientConnState) error { ccb.balancerMu.Lock() defer ccb.balancerMu.Unlock() - if ub, ok := ccb.balancer.(balancer.V2Balancer); ok { - return ub.UpdateClientConnState(*ccs) - } - ccb.balancer.HandleResolvedAddrs(ccs.ResolverState.Addresses, nil) - return nil + return ccb.balancer.UpdateClientConnState(*ccs) } func (ccb *ccBalancerWrapper) resolverError(err error) { - if ub, ok := ccb.balancer.(balancer.V2Balancer); ok { - ccb.balancerMu.Lock() - ub.ResolverError(err) - ccb.balancerMu.Unlock() - } + ccb.balancerMu.Lock() + ccb.balancer.ResolverError(err) + ccb.balancerMu.Unlock() } func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { @@ -173,21 +163,6 @@ func (ccb *ccBalancerWrapper) RemoveSubConn(sc balancer.SubConn) { ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) } -func (ccb *ccBalancerWrapper) UpdateBalancerState(s connectivity.State, p balancer.Picker) { - ccb.mu.Lock() - defer ccb.mu.Unlock() - if ccb.subConns == nil { - return - } - // Update picker before updating state. Even though the ordering here does - // not matter, it can lead to multiple calls of Pick in the common start-up - // case where we wait for ready and then perform an RPC. If the picker is - // updated later, we could call the "connecting" picker when the state is - // updated, and then call the "ready" picker after the picker gets updated. - ccb.cc.blockingpicker.updatePicker(p) - ccb.cc.csMgr.updateState(s) -} - func (ccb *ccBalancerWrapper) UpdateState(s balancer.State) { ccb.mu.Lock() defer ccb.mu.Unlock() @@ -199,7 +174,7 @@ func (ccb *ccBalancerWrapper) UpdateState(s balancer.State) { // case where we wait for ready and then perform an RPC. If the picker is // updated later, we could call the "connecting" picker when the state is // updated, and then call the "ready" picker after the picker gets updated. - ccb.cc.blockingpicker.updatePickerV2(s.Picker) + ccb.cc.blockingpicker.updatePicker(s.Picker) ccb.cc.csMgr.updateState(s.ConnectivityState) } @@ -245,7 +220,7 @@ func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { ac, err := cc.newAddrConn(addrs, opts) if err != nil { - grpclog.Warningf("acBalancerWrapper: UpdateAddresses: failed to newAddrConn: %v", err) + channelz.Warningf(acbw.ac.channelzID, "acBalancerWrapper: UpdateAddresses: failed to newAddrConn: %v", err) return } acbw.ac = ac diff --git a/vendor/google.golang.org/grpc/balancer_v1_wrapper.go b/vendor/google.golang.org/grpc/balancer_v1_wrapper.go deleted file mode 100644 index db04b08b842..00000000000 --- a/vendor/google.golang.org/grpc/balancer_v1_wrapper.go +++ /dev/null @@ -1,334 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * 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 grpc - -import ( - "sync" - - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" -) - -type balancerWrapperBuilder struct { - b Balancer // The v1 balancer. -} - -func (bwb *balancerWrapperBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer { - bwb.b.Start(opts.Target.Endpoint, BalancerConfig{ - DialCreds: opts.DialCreds, - Dialer: opts.Dialer, - }) - _, pickfirst := bwb.b.(*pickFirst) - bw := &balancerWrapper{ - balancer: bwb.b, - pickfirst: pickfirst, - cc: cc, - targetAddr: opts.Target.Endpoint, - startCh: make(chan struct{}), - conns: make(map[resolver.Address]balancer.SubConn), - connSt: make(map[balancer.SubConn]*scState), - csEvltr: &balancer.ConnectivityStateEvaluator{}, - state: connectivity.Idle, - } - cc.UpdateState(balancer.State{ConnectivityState: connectivity.Idle, Picker: bw}) - go bw.lbWatcher() - return bw -} - -func (bwb *balancerWrapperBuilder) Name() string { - return "wrapper" -} - -type scState struct { - addr Address // The v1 address type. - s connectivity.State - down func(error) -} - -type balancerWrapper struct { - balancer Balancer // The v1 balancer. - pickfirst bool - - cc balancer.ClientConn - targetAddr string // Target without the scheme. - - mu sync.Mutex - conns map[resolver.Address]balancer.SubConn - connSt map[balancer.SubConn]*scState - // This channel is closed when handling the first resolver result. - // lbWatcher blocks until this is closed, to avoid race between - // - NewSubConn is created, cc wants to notify balancer of state changes; - // - Build hasn't return, cc doesn't have access to balancer. - startCh chan struct{} - - // To aggregate the connectivity state. - csEvltr *balancer.ConnectivityStateEvaluator - state connectivity.State -} - -// lbWatcher watches the Notify channel of the balancer and manages -// connections accordingly. -func (bw *balancerWrapper) lbWatcher() { - <-bw.startCh - notifyCh := bw.balancer.Notify() - if notifyCh == nil { - // There's no resolver in the balancer. Connect directly. - a := resolver.Address{ - Addr: bw.targetAddr, - Type: resolver.Backend, - } - sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("Error creating connection to %v. Err: %v", a, err) - } else { - bw.mu.Lock() - bw.conns[a] = sc - bw.connSt[sc] = &scState{ - addr: Address{Addr: bw.targetAddr}, - s: connectivity.Idle, - } - bw.mu.Unlock() - sc.Connect() - } - return - } - - for addrs := range notifyCh { - grpclog.Infof("balancerWrapper: got update addr from Notify: %v", addrs) - if bw.pickfirst { - var ( - oldA resolver.Address - oldSC balancer.SubConn - ) - bw.mu.Lock() - for oldA, oldSC = range bw.conns { - break - } - bw.mu.Unlock() - if len(addrs) <= 0 { - if oldSC != nil { - // Teardown old sc. - bw.mu.Lock() - delete(bw.conns, oldA) - delete(bw.connSt, oldSC) - bw.mu.Unlock() - bw.cc.RemoveSubConn(oldSC) - } - continue - } - - var newAddrs []resolver.Address - for _, a := range addrs { - newAddr := resolver.Address{ - Addr: a.Addr, - Type: resolver.Backend, // All addresses from balancer are all backends. - ServerName: "", - Metadata: a.Metadata, - } - newAddrs = append(newAddrs, newAddr) - } - if oldSC == nil { - // Create new sc. - sc, err := bw.cc.NewSubConn(newAddrs, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("Error creating connection to %v. Err: %v", newAddrs, err) - } else { - bw.mu.Lock() - // For pickfirst, there should be only one SubConn, so the - // address doesn't matter. All states updating (up and down) - // and picking should all happen on that only SubConn. - bw.conns[resolver.Address{}] = sc - bw.connSt[sc] = &scState{ - addr: addrs[0], // Use the first address. - s: connectivity.Idle, - } - bw.mu.Unlock() - sc.Connect() - } - } else { - bw.mu.Lock() - bw.connSt[oldSC].addr = addrs[0] - bw.mu.Unlock() - oldSC.UpdateAddresses(newAddrs) - } - } else { - var ( - add []resolver.Address // Addresses need to setup connections. - del []balancer.SubConn // Connections need to tear down. - ) - resAddrs := make(map[resolver.Address]Address) - for _, a := range addrs { - resAddrs[resolver.Address{ - Addr: a.Addr, - Type: resolver.Backend, // All addresses from balancer are all backends. - ServerName: "", - Metadata: a.Metadata, - }] = a - } - bw.mu.Lock() - for a := range resAddrs { - if _, ok := bw.conns[a]; !ok { - add = append(add, a) - } - } - for a, c := range bw.conns { - if _, ok := resAddrs[a]; !ok { - del = append(del, c) - delete(bw.conns, a) - // Keep the state of this sc in bw.connSt until its state becomes Shutdown. - } - } - bw.mu.Unlock() - for _, a := range add { - sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) - if err != nil { - grpclog.Warningf("Error creating connection to %v. Err: %v", a, err) - } else { - bw.mu.Lock() - bw.conns[a] = sc - bw.connSt[sc] = &scState{ - addr: resAddrs[a], - s: connectivity.Idle, - } - bw.mu.Unlock() - sc.Connect() - } - } - for _, c := range del { - bw.cc.RemoveSubConn(c) - } - } - } -} - -func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - bw.mu.Lock() - defer bw.mu.Unlock() - scSt, ok := bw.connSt[sc] - if !ok { - return - } - if s == connectivity.Idle { - sc.Connect() - } - oldS := scSt.s - scSt.s = s - if oldS != connectivity.Ready && s == connectivity.Ready { - scSt.down = bw.balancer.Up(scSt.addr) - } else if oldS == connectivity.Ready && s != connectivity.Ready { - if scSt.down != nil { - scSt.down(errConnClosing) - } - } - sa := bw.csEvltr.RecordTransition(oldS, s) - if bw.state != sa { - bw.state = sa - } - bw.cc.UpdateState(balancer.State{ConnectivityState: bw.state, Picker: bw}) - if s == connectivity.Shutdown { - // Remove state for this sc. - delete(bw.connSt, sc) - } -} - -func (bw *balancerWrapper) HandleResolvedAddrs([]resolver.Address, error) { - bw.mu.Lock() - defer bw.mu.Unlock() - select { - case <-bw.startCh: - default: - close(bw.startCh) - } - // There should be a resolver inside the balancer. - // All updates here, if any, are ignored. -} - -func (bw *balancerWrapper) Close() { - bw.mu.Lock() - defer bw.mu.Unlock() - select { - case <-bw.startCh: - default: - close(bw.startCh) - } - bw.balancer.Close() -} - -// The picker is the balancerWrapper itself. -// It either blocks or returns error, consistent with v1 balancer Get(). -func (bw *balancerWrapper) Pick(info balancer.PickInfo) (result balancer.PickResult, err error) { - failfast := true // Default failfast is true. - if ss, ok := rpcInfoFromContext(info.Ctx); ok { - failfast = ss.failfast - } - a, p, err := bw.balancer.Get(info.Ctx, BalancerGetOptions{BlockingWait: !failfast}) - if err != nil { - return balancer.PickResult{}, toRPCErr(err) - } - if p != nil { - result.Done = func(balancer.DoneInfo) { p() } - defer func() { - if err != nil { - p() - } - }() - } - - bw.mu.Lock() - defer bw.mu.Unlock() - if bw.pickfirst { - // Get the first sc in conns. - for _, result.SubConn = range bw.conns { - return result, nil - } - return balancer.PickResult{}, balancer.ErrNoSubConnAvailable - } - var ok1 bool - result.SubConn, ok1 = bw.conns[resolver.Address{ - Addr: a.Addr, - Type: resolver.Backend, - ServerName: "", - Metadata: a.Metadata, - }] - s, ok2 := bw.connSt[result.SubConn] - if !ok1 || !ok2 { - // This can only happen due to a race where Get() returned an address - // that was subsequently removed by Notify. In this case we should - // retry always. - return balancer.PickResult{}, balancer.ErrNoSubConnAvailable - } - switch s.s { - case connectivity.Ready, connectivity.Idle: - return result, nil - case connectivity.Shutdown, connectivity.TransientFailure: - // If the returned sc has been shut down or is in transient failure, - // return error, and this RPC will fail or wait for another picker (if - // non-failfast). - return balancer.PickResult{}, balancer.ErrTransientFailure - default: - // For other states (connecting or unknown), the v1 balancer would - // traditionally wait until ready and then issue the RPC. Returning - // ErrNoSubConnAvailable will be a slight improvement in that it will - // allow the balancer to choose another address in case others are - // connected. - return balancer.PickResult{}, balancer.ErrNoSubConnAvailable - } -} diff --git a/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go b/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go index f393bb66187..f826ec76984 100644 --- a/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go +++ b/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go @@ -1,13 +1,15 @@ // Code generated by protoc-gen-go. DO NOT EDIT. -// source: grpc/binarylog/grpc_binarylog_v1/binarylog.proto +// source: grpc/binlog/v1/binarylog.proto -package grpc_binarylog_v1 // import "google.golang.org/grpc/binarylog/grpc_binarylog_v1" +package grpc_binarylog_v1 -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" -import duration "github.com/golang/protobuf/ptypes/duration" -import timestamp "github.com/golang/protobuf/ptypes/timestamp" +import ( + fmt "fmt" + proto "github.com/golang/protobuf/proto" + duration "github.com/golang/protobuf/ptypes/duration" + timestamp "github.com/golang/protobuf/ptypes/timestamp" + math "math" +) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal @@ -18,7 +20,7 @@ var _ = math.Inf // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package +const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // Enumerates the type of event // Note the terminology is different from the RPC semantics @@ -64,6 +66,7 @@ var GrpcLogEntry_EventType_name = map[int32]string{ 6: "EVENT_TYPE_SERVER_TRAILER", 7: "EVENT_TYPE_CANCEL", } + var GrpcLogEntry_EventType_value = map[string]int32{ "EVENT_TYPE_UNKNOWN": 0, "EVENT_TYPE_CLIENT_HEADER": 1, @@ -78,8 +81,9 @@ var GrpcLogEntry_EventType_value = map[string]int32{ func (x GrpcLogEntry_EventType) String() string { return proto.EnumName(GrpcLogEntry_EventType_name, int32(x)) } + func (GrpcLogEntry_EventType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_binarylog_264c8c9c551ce911, []int{0, 0} + return fileDescriptor_b7972e58de45083a, []int{0, 0} } // Enumerates the entity that generates the log entry @@ -96,6 +100,7 @@ var GrpcLogEntry_Logger_name = map[int32]string{ 1: "LOGGER_CLIENT", 2: "LOGGER_SERVER", } + var GrpcLogEntry_Logger_value = map[string]int32{ "LOGGER_UNKNOWN": 0, "LOGGER_CLIENT": 1, @@ -105,8 +110,9 @@ var GrpcLogEntry_Logger_value = map[string]int32{ func (x GrpcLogEntry_Logger) String() string { return proto.EnumName(GrpcLogEntry_Logger_name, int32(x)) } + func (GrpcLogEntry_Logger) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_binarylog_264c8c9c551ce911, []int{0, 1} + return fileDescriptor_b7972e58de45083a, []int{0, 1} } type Address_Type int32 @@ -128,6 +134,7 @@ var Address_Type_name = map[int32]string{ 2: "TYPE_IPV6", 3: "TYPE_UNIX", } + var Address_Type_value = map[string]int32{ "TYPE_UNKNOWN": 0, "TYPE_IPV4": 1, @@ -138,8 +145,9 @@ var Address_Type_value = map[string]int32{ func (x Address_Type) String() string { return proto.EnumName(Address_Type_name, int32(x)) } + func (Address_Type) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_binarylog_264c8c9c551ce911, []int{7, 0} + return fileDescriptor_b7972e58de45083a, []int{7, 0} } // Log entry we store in binary logs @@ -185,16 +193,17 @@ func (m *GrpcLogEntry) Reset() { *m = GrpcLogEntry{} } func (m *GrpcLogEntry) String() string { return proto.CompactTextString(m) } func (*GrpcLogEntry) ProtoMessage() {} func (*GrpcLogEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_binarylog_264c8c9c551ce911, []int{0} + return fileDescriptor_b7972e58de45083a, []int{0} } + func (m *GrpcLogEntry) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_GrpcLogEntry.Unmarshal(m, b) } func (m *GrpcLogEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_GrpcLogEntry.Marshal(b, m, deterministic) } -func (dst *GrpcLogEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_GrpcLogEntry.Merge(dst, src) +func (m *GrpcLogEntry) XXX_Merge(src proto.Message) { + xxx_messageInfo_GrpcLogEntry.Merge(m, src) } func (m *GrpcLogEntry) XXX_Size() int { return xxx_messageInfo_GrpcLogEntry.Size(m) @@ -317,9 +326,9 @@ func (m *GrpcLogEntry) GetPeer() *Address { return nil } -// XXX_OneofFuncs is for the internal use of the proto package. -func (*GrpcLogEntry) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { - return _GrpcLogEntry_OneofMarshaler, _GrpcLogEntry_OneofUnmarshaler, _GrpcLogEntry_OneofSizer, []interface{}{ +// XXX_OneofWrappers is for the internal use of the proto package. +func (*GrpcLogEntry) XXX_OneofWrappers() []interface{} { + return []interface{}{ (*GrpcLogEntry_ClientHeader)(nil), (*GrpcLogEntry_ServerHeader)(nil), (*GrpcLogEntry_Message)(nil), @@ -327,108 +336,6 @@ func (*GrpcLogEntry) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) } } -func _GrpcLogEntry_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { - m := msg.(*GrpcLogEntry) - // payload - switch x := m.Payload.(type) { - case *GrpcLogEntry_ClientHeader: - b.EncodeVarint(6<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ClientHeader); err != nil { - return err - } - case *GrpcLogEntry_ServerHeader: - b.EncodeVarint(7<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.ServerHeader); err != nil { - return err - } - case *GrpcLogEntry_Message: - b.EncodeVarint(8<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Message); err != nil { - return err - } - case *GrpcLogEntry_Trailer: - b.EncodeVarint(9<<3 | proto.WireBytes) - if err := b.EncodeMessage(x.Trailer); err != nil { - return err - } - case nil: - default: - return fmt.Errorf("GrpcLogEntry.Payload has unexpected type %T", x) - } - return nil -} - -func _GrpcLogEntry_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { - m := msg.(*GrpcLogEntry) - switch tag { - case 6: // payload.client_header - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ClientHeader) - err := b.DecodeMessage(msg) - m.Payload = &GrpcLogEntry_ClientHeader{msg} - return true, err - case 7: // payload.server_header - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(ServerHeader) - err := b.DecodeMessage(msg) - m.Payload = &GrpcLogEntry_ServerHeader{msg} - return true, err - case 8: // payload.message - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Message) - err := b.DecodeMessage(msg) - m.Payload = &GrpcLogEntry_Message{msg} - return true, err - case 9: // payload.trailer - if wire != proto.WireBytes { - return true, proto.ErrInternalBadWireType - } - msg := new(Trailer) - err := b.DecodeMessage(msg) - m.Payload = &GrpcLogEntry_Trailer{msg} - return true, err - default: - return false, nil - } -} - -func _GrpcLogEntry_OneofSizer(msg proto.Message) (n int) { - m := msg.(*GrpcLogEntry) - // payload - switch x := m.Payload.(type) { - case *GrpcLogEntry_ClientHeader: - s := proto.Size(x.ClientHeader) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *GrpcLogEntry_ServerHeader: - s := proto.Size(x.ServerHeader) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *GrpcLogEntry_Message: - s := proto.Size(x.Message) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case *GrpcLogEntry_Trailer: - s := proto.Size(x.Trailer) - n += 1 // tag and wire - n += proto.SizeVarint(uint64(s)) - n += s - case nil: - default: - panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) - } - return n -} - type ClientHeader struct { // This contains only the metadata from the application. Metadata *Metadata `protobuf:"bytes,1,opt,name=metadata,proto3" json:"metadata,omitempty"` @@ -453,16 +360,17 @@ func (m *ClientHeader) Reset() { *m = ClientHeader{} } func (m *ClientHeader) String() string { return proto.CompactTextString(m) } func (*ClientHeader) ProtoMessage() {} func (*ClientHeader) Descriptor() ([]byte, []int) { - return fileDescriptor_binarylog_264c8c9c551ce911, []int{1} + return fileDescriptor_b7972e58de45083a, []int{1} } + func (m *ClientHeader) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ClientHeader.Unmarshal(m, b) } func (m *ClientHeader) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ClientHeader.Marshal(b, m, deterministic) } -func (dst *ClientHeader) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClientHeader.Merge(dst, src) +func (m *ClientHeader) XXX_Merge(src proto.Message) { + xxx_messageInfo_ClientHeader.Merge(m, src) } func (m *ClientHeader) XXX_Size() int { return xxx_messageInfo_ClientHeader.Size(m) @@ -513,16 +421,17 @@ func (m *ServerHeader) Reset() { *m = ServerHeader{} } func (m *ServerHeader) String() string { return proto.CompactTextString(m) } func (*ServerHeader) ProtoMessage() {} func (*ServerHeader) Descriptor() ([]byte, []int) { - return fileDescriptor_binarylog_264c8c9c551ce911, []int{2} + return fileDescriptor_b7972e58de45083a, []int{2} } + func (m *ServerHeader) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ServerHeader.Unmarshal(m, b) } func (m *ServerHeader) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ServerHeader.Marshal(b, m, deterministic) } -func (dst *ServerHeader) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServerHeader.Merge(dst, src) +func (m *ServerHeader) XXX_Merge(src proto.Message) { + xxx_messageInfo_ServerHeader.Merge(m, src) } func (m *ServerHeader) XXX_Size() int { return xxx_messageInfo_ServerHeader.Size(m) @@ -560,16 +469,17 @@ func (m *Trailer) Reset() { *m = Trailer{} } func (m *Trailer) String() string { return proto.CompactTextString(m) } func (*Trailer) ProtoMessage() {} func (*Trailer) Descriptor() ([]byte, []int) { - return fileDescriptor_binarylog_264c8c9c551ce911, []int{3} + return fileDescriptor_b7972e58de45083a, []int{3} } + func (m *Trailer) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Trailer.Unmarshal(m, b) } func (m *Trailer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Trailer.Marshal(b, m, deterministic) } -func (dst *Trailer) XXX_Merge(src proto.Message) { - xxx_messageInfo_Trailer.Merge(dst, src) +func (m *Trailer) XXX_Merge(src proto.Message) { + xxx_messageInfo_Trailer.Merge(m, src) } func (m *Trailer) XXX_Size() int { return xxx_messageInfo_Trailer.Size(m) @@ -624,16 +534,17 @@ func (m *Message) Reset() { *m = Message{} } func (m *Message) String() string { return proto.CompactTextString(m) } func (*Message) ProtoMessage() {} func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_binarylog_264c8c9c551ce911, []int{4} + return fileDescriptor_b7972e58de45083a, []int{4} } + func (m *Message) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Message.Unmarshal(m, b) } func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Message.Marshal(b, m, deterministic) } -func (dst *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(dst, src) +func (m *Message) XXX_Merge(src proto.Message) { + xxx_messageInfo_Message.Merge(m, src) } func (m *Message) XXX_Size() int { return xxx_messageInfo_Message.Size(m) @@ -690,16 +601,17 @@ func (m *Metadata) Reset() { *m = Metadata{} } func (m *Metadata) String() string { return proto.CompactTextString(m) } func (*Metadata) ProtoMessage() {} func (*Metadata) Descriptor() ([]byte, []int) { - return fileDescriptor_binarylog_264c8c9c551ce911, []int{5} + return fileDescriptor_b7972e58de45083a, []int{5} } + func (m *Metadata) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Metadata.Unmarshal(m, b) } func (m *Metadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Metadata.Marshal(b, m, deterministic) } -func (dst *Metadata) XXX_Merge(src proto.Message) { - xxx_messageInfo_Metadata.Merge(dst, src) +func (m *Metadata) XXX_Merge(src proto.Message) { + xxx_messageInfo_Metadata.Merge(m, src) } func (m *Metadata) XXX_Size() int { return xxx_messageInfo_Metadata.Size(m) @@ -730,16 +642,17 @@ func (m *MetadataEntry) Reset() { *m = MetadataEntry{} } func (m *MetadataEntry) String() string { return proto.CompactTextString(m) } func (*MetadataEntry) ProtoMessage() {} func (*MetadataEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_binarylog_264c8c9c551ce911, []int{6} + return fileDescriptor_b7972e58de45083a, []int{6} } + func (m *MetadataEntry) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_MetadataEntry.Unmarshal(m, b) } func (m *MetadataEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_MetadataEntry.Marshal(b, m, deterministic) } -func (dst *MetadataEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_MetadataEntry.Merge(dst, src) +func (m *MetadataEntry) XXX_Merge(src proto.Message) { + xxx_messageInfo_MetadataEntry.Merge(m, src) } func (m *MetadataEntry) XXX_Size() int { return xxx_messageInfo_MetadataEntry.Size(m) @@ -779,16 +692,17 @@ func (m *Address) Reset() { *m = Address{} } func (m *Address) String() string { return proto.CompactTextString(m) } func (*Address) ProtoMessage() {} func (*Address) Descriptor() ([]byte, []int) { - return fileDescriptor_binarylog_264c8c9c551ce911, []int{7} + return fileDescriptor_b7972e58de45083a, []int{7} } + func (m *Address) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Address.Unmarshal(m, b) } func (m *Address) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Address.Marshal(b, m, deterministic) } -func (dst *Address) XXX_Merge(src proto.Message) { - xxx_messageInfo_Address.Merge(dst, src) +func (m *Address) XXX_Merge(src proto.Message) { + xxx_messageInfo_Address.Merge(m, src) } func (m *Address) XXX_Size() int { return xxx_messageInfo_Address.Size(m) @@ -821,6 +735,9 @@ func (m *Address) GetIpPort() uint32 { } func init() { + proto.RegisterEnum("grpc.binarylog.v1.GrpcLogEntry_EventType", GrpcLogEntry_EventType_name, GrpcLogEntry_EventType_value) + proto.RegisterEnum("grpc.binarylog.v1.GrpcLogEntry_Logger", GrpcLogEntry_Logger_name, GrpcLogEntry_Logger_value) + proto.RegisterEnum("grpc.binarylog.v1.Address_Type", Address_Type_name, Address_Type_value) proto.RegisterType((*GrpcLogEntry)(nil), "grpc.binarylog.v1.GrpcLogEntry") proto.RegisterType((*ClientHeader)(nil), "grpc.binarylog.v1.ClientHeader") proto.RegisterType((*ServerHeader)(nil), "grpc.binarylog.v1.ServerHeader") @@ -829,72 +746,67 @@ func init() { proto.RegisterType((*Metadata)(nil), "grpc.binarylog.v1.Metadata") proto.RegisterType((*MetadataEntry)(nil), "grpc.binarylog.v1.MetadataEntry") proto.RegisterType((*Address)(nil), "grpc.binarylog.v1.Address") - proto.RegisterEnum("grpc.binarylog.v1.GrpcLogEntry_EventType", GrpcLogEntry_EventType_name, GrpcLogEntry_EventType_value) - proto.RegisterEnum("grpc.binarylog.v1.GrpcLogEntry_Logger", GrpcLogEntry_Logger_name, GrpcLogEntry_Logger_value) - proto.RegisterEnum("grpc.binarylog.v1.Address_Type", Address_Type_name, Address_Type_value) } -func init() { - proto.RegisterFile("grpc/binarylog/grpc_binarylog_v1/binarylog.proto", fileDescriptor_binarylog_264c8c9c551ce911) -} +func init() { proto.RegisterFile("grpc/binlog/v1/binarylog.proto", fileDescriptor_b7972e58de45083a) } -var fileDescriptor_binarylog_264c8c9c551ce911 = []byte{ - // 900 bytes of a gzipped FileDescriptorProto +var fileDescriptor_b7972e58de45083a = []byte{ + // 904 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x55, 0x51, 0x6f, 0xe3, 0x44, - 0x10, 0x3e, 0x37, 0x69, 0xdc, 0x4c, 0x92, 0xca, 0x5d, 0x95, 0x3b, 0x5f, 0x29, 0x34, 0xb2, 0x04, - 0x0a, 0x42, 0x72, 0xb9, 0x94, 0xeb, 0xf1, 0x02, 0x52, 0x92, 0xfa, 0xd2, 0x88, 0x5c, 0x1a, 0x6d, - 0x72, 0x3d, 0x40, 0x48, 0xd6, 0x36, 0x5e, 0x1c, 0x0b, 0xc7, 0x6b, 0xd6, 0x9b, 0xa0, 0xfc, 0x2c, - 0xde, 0x90, 0xee, 0x77, 0xf1, 0x8e, 0xbc, 0x6b, 0x27, 0xa6, 0x69, 0x0f, 0x09, 0xde, 0x3c, 0xdf, - 0x7c, 0xf3, 0xcd, 0xee, 0x78, 0x66, 0x16, 0xbe, 0xf2, 0x79, 0x3c, 0x3b, 0xbf, 0x0b, 0x22, 0xc2, - 0xd7, 0x21, 0xf3, 0xcf, 0x53, 0xd3, 0xdd, 0x98, 0xee, 0xea, 0xc5, 0xd6, 0x67, 0xc7, 0x9c, 0x09, - 0x86, 0x8e, 0x52, 0x8a, 0xbd, 0x45, 0x57, 0x2f, 0x4e, 0x3e, 0xf5, 0x19, 0xf3, 0x43, 0x7a, 0x2e, - 0x09, 0x77, 0xcb, 0x5f, 0xce, 0xbd, 0x25, 0x27, 0x22, 0x60, 0x91, 0x0a, 0x39, 0x39, 0xbb, 0xef, - 0x17, 0xc1, 0x82, 0x26, 0x82, 0x2c, 0x62, 0x45, 0xb0, 0xde, 0xeb, 0x50, 0xef, 0xf3, 0x78, 0x36, - 0x64, 0xbe, 0x13, 0x09, 0xbe, 0x46, 0xdf, 0x40, 0x75, 0xc3, 0x31, 0xb5, 0xa6, 0xd6, 0xaa, 0xb5, - 0x4f, 0x6c, 0xa5, 0x62, 0xe7, 0x2a, 0xf6, 0x34, 0x67, 0xe0, 0x2d, 0x19, 0x3d, 0x03, 0x7d, 0x46, - 0xc2, 0xd0, 0x0d, 0x3c, 0x73, 0xaf, 0xa9, 0xb5, 0xca, 0xb8, 0x92, 0x9a, 0x03, 0x0f, 0xbd, 0x84, - 0x67, 0x09, 0xfd, 0x6d, 0x49, 0xa3, 0x19, 0x75, 0x03, 0xcf, 0xfd, 0x3d, 0x10, 0xf3, 0x20, 0x72, - 0x53, 0xa7, 0x59, 0x92, 0xc4, 0xe3, 0xdc, 0x3d, 0xf0, 0xde, 0x49, 0x67, 0x8f, 0x84, 0x21, 0xfa, - 0x16, 0xca, 0x62, 0x1d, 0x53, 0xb3, 0xdc, 0xd4, 0x5a, 0x87, 0xed, 0x2f, 0xec, 0x9d, 0xdb, 0xdb, - 0xc5, 0x83, 0xdb, 0xce, 0x8a, 0x46, 0x62, 0xba, 0x8e, 0x29, 0x96, 0x61, 0xe8, 0x3b, 0xa8, 0x84, - 0xcc, 0xf7, 0x29, 0x37, 0xf7, 0xa5, 0xc0, 0xe7, 0xff, 0x26, 0x30, 0x94, 0x6c, 0x9c, 0x45, 0xa1, - 0xd7, 0xd0, 0x98, 0x85, 0x01, 0x8d, 0x84, 0x3b, 0xa7, 0xc4, 0xa3, 0xdc, 0xac, 0xc8, 0x62, 0x9c, - 0x3d, 0x20, 0xd3, 0x93, 0xbc, 0x6b, 0x49, 0xbb, 0x7e, 0x82, 0xeb, 0xb3, 0x82, 0x9d, 0xea, 0x24, - 0x94, 0xaf, 0x28, 0xcf, 0x75, 0xf4, 0x47, 0x75, 0x26, 0x92, 0xb7, 0xd5, 0x49, 0x0a, 0x36, 0xba, - 0x04, 0x7d, 0x41, 0x93, 0x84, 0xf8, 0xd4, 0x3c, 0xc8, 0x7f, 0xcb, 0x8e, 0xc2, 0x1b, 0xc5, 0xb8, - 0x7e, 0x82, 0x73, 0x72, 0x1a, 0x27, 0x38, 0x09, 0x42, 0xca, 0xcd, 0xea, 0xa3, 0x71, 0x53, 0xc5, - 0x48, 0xe3, 0x32, 0x32, 0xfa, 0x12, 0x8e, 0x62, 0xb2, 0x0e, 0x19, 0xf1, 0x5c, 0xc1, 0x97, 0xd1, - 0x8c, 0x08, 0xea, 0x99, 0xd0, 0xd4, 0x5a, 0x07, 0xd8, 0xc8, 0x1c, 0xd3, 0x1c, 0x47, 0x36, 0x94, - 0x63, 0x4a, 0xb9, 0x59, 0x7b, 0x34, 0x43, 0xc7, 0xf3, 0x38, 0x4d, 0x12, 0x2c, 0x79, 0xd6, 0x5f, - 0x1a, 0x54, 0x37, 0x3f, 0x0c, 0x3d, 0x05, 0xe4, 0xdc, 0x3a, 0xa3, 0xa9, 0x3b, 0xfd, 0x71, 0xec, - 0xb8, 0x6f, 0x47, 0xdf, 0x8f, 0x6e, 0xde, 0x8d, 0x8c, 0x27, 0xe8, 0x14, 0xcc, 0x02, 0xde, 0x1b, - 0x0e, 0xd2, 0xef, 0x6b, 0xa7, 0x73, 0xe5, 0x60, 0x43, 0xbb, 0xe7, 0x9d, 0x38, 0xf8, 0xd6, 0xc1, - 0xb9, 0x77, 0x0f, 0x7d, 0x02, 0xcf, 0x77, 0x63, 0xdf, 0x38, 0x93, 0x49, 0xa7, 0xef, 0x18, 0xa5, - 0x7b, 0xee, 0x2c, 0x38, 0x77, 0x97, 0x51, 0x13, 0x4e, 0x1f, 0xc8, 0xdc, 0x19, 0xbe, 0x76, 0x7b, - 0xc3, 0x9b, 0x89, 0x63, 0xec, 0x3f, 0x2c, 0x30, 0xc5, 0x9d, 0xc1, 0xd0, 0xc1, 0x46, 0x05, 0x7d, - 0x04, 0x47, 0x45, 0x81, 0xce, 0xa8, 0xe7, 0x0c, 0x0d, 0xdd, 0xea, 0x42, 0x45, 0xb5, 0x19, 0x42, - 0x70, 0x38, 0xbc, 0xe9, 0xf7, 0x1d, 0x5c, 0xb8, 0xef, 0x11, 0x34, 0x32, 0x4c, 0x65, 0x34, 0xb4, - 0x02, 0xa4, 0x52, 0x18, 0x7b, 0xdd, 0x2a, 0xe8, 0x59, 0xfd, 0xad, 0xf7, 0x1a, 0xd4, 0x8b, 0xcd, - 0x87, 0x5e, 0xc1, 0xc1, 0x82, 0x0a, 0xe2, 0x11, 0x41, 0xb2, 0xe1, 0xfd, 0xf8, 0xc1, 0x2e, 0x51, - 0x14, 0xbc, 0x21, 0xa3, 0x33, 0xa8, 0x2d, 0xa8, 0x98, 0x33, 0xcf, 0x8d, 0xc8, 0x82, 0xca, 0x01, - 0xae, 0x62, 0x50, 0xd0, 0x88, 0x2c, 0x28, 0x3a, 0x85, 0x2a, 0x59, 0x8a, 0x39, 0xe3, 0x81, 0x58, - 0xcb, 0xb1, 0xad, 0xe2, 0x2d, 0x80, 0x2e, 0x40, 0x4f, 0x17, 0x01, 0x5b, 0x0a, 0x39, 0xae, 0xb5, - 0xf6, 0xf3, 0x9d, 0x9d, 0x71, 0x95, 0x6d, 0x26, 0x9c, 0x33, 0xad, 0x3e, 0xd4, 0x8b, 0x1d, 0xff, - 0x9f, 0x0f, 0x6f, 0xfd, 0xa1, 0x81, 0x9e, 0x75, 0xf0, 0xff, 0xaa, 0x40, 0x22, 0x88, 0x58, 0x26, - 0xee, 0x8c, 0x79, 0xaa, 0x02, 0x0d, 0x0c, 0x0a, 0xea, 0x31, 0x8f, 0xa2, 0xcf, 0xe0, 0x30, 0x23, - 0xe4, 0x73, 0xa8, 0xca, 0xd0, 0x50, 0x68, 0x36, 0x7a, 0x05, 0x9a, 0x47, 0x05, 0x09, 0xc2, 0x44, - 0x56, 0xa4, 0x9e, 0xd3, 0xae, 0x14, 0x68, 0xbd, 0x04, 0x3d, 0x8f, 0x78, 0x0a, 0x95, 0x90, 0x46, - 0xbe, 0x98, 0xcb, 0x03, 0x37, 0x70, 0x66, 0x21, 0x04, 0x65, 0x79, 0x8d, 0x3d, 0x19, 0x2f, 0xbf, - 0xad, 0x2e, 0x1c, 0xe4, 0x67, 0x47, 0x97, 0xb0, 0x4f, 0xd3, 0xcd, 0x65, 0x6a, 0xcd, 0x52, 0xab, - 0xd6, 0x6e, 0x7e, 0xe0, 0x9e, 0x72, 0xc3, 0x61, 0x45, 0xb7, 0x5e, 0x41, 0xe3, 0x1f, 0x38, 0x32, - 0xa0, 0xf4, 0x2b, 0x5d, 0xcb, 0xec, 0x55, 0x9c, 0x7e, 0xa2, 0x63, 0xd8, 0x5f, 0x91, 0x70, 0x49, - 0xb3, 0xdc, 0xca, 0xb0, 0xfe, 0xd4, 0x40, 0xcf, 0xe6, 0x18, 0x5d, 0x64, 0xdb, 0x59, 0x93, 0xcb, - 0xf5, 0xec, 0xf1, 0x89, 0xb7, 0x0b, 0x3b, 0xd9, 0x04, 0x9d, 0x28, 0x34, 0xeb, 0xb0, 0xdc, 0x4c, - 0x1f, 0x8f, 0x20, 0x76, 0x63, 0xc6, 0x85, 0xac, 0x6a, 0x03, 0x57, 0x82, 0x78, 0xcc, 0xb8, 0xb0, - 0x1c, 0x28, 0xcb, 0x1d, 0x61, 0x40, 0xfd, 0xde, 0x76, 0x68, 0x40, 0x55, 0x22, 0x83, 0xf1, 0xed, - 0xd7, 0x86, 0x56, 0x34, 0x2f, 0x8d, 0xbd, 0x8d, 0xf9, 0x76, 0x34, 0xf8, 0xc1, 0x28, 0x75, 0x7f, - 0x86, 0xe3, 0x80, 0xed, 0x1e, 0xb2, 0x7b, 0xd8, 0x95, 0xd6, 0x90, 0xf9, 0xe3, 0xb4, 0x51, 0xc7, - 0xda, 0x4f, 0xed, 0xac, 0x71, 0x7d, 0x16, 0x92, 0xc8, 0xb7, 0x19, 0x57, 0x4f, 0xf3, 0x87, 0x5e, - 0xea, 0xbb, 0x8a, 0xec, 0xf2, 0x8b, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0xe7, 0xf6, 0x4b, 0x50, - 0xd4, 0x07, 0x00, 0x00, + 0x10, 0xae, 0xdb, 0x34, 0x6e, 0x26, 0x49, 0xe5, 0xae, 0xca, 0x9d, 0xaf, 0x94, 0x6b, 0x64, 0x09, + 0x14, 0x84, 0xe4, 0xa8, 0x29, 0xd7, 0xe3, 0x05, 0xa4, 0x24, 0xf5, 0xa5, 0x11, 0xb9, 0x34, 0xda, + 0xe4, 0x7a, 0x80, 0x90, 0xac, 0x6d, 0xbc, 0x38, 0x16, 0x8e, 0xd7, 0xac, 0x37, 0x41, 0xf9, 0x59, + 0xbc, 0x21, 0xdd, 0xef, 0xe2, 0x1d, 0x79, 0xd7, 0x4e, 0x4d, 0xd3, 0x82, 0xc4, 0xbd, 0xed, 0x7c, + 0xf3, 0xcd, 0x37, 0xbb, 0xe3, 0x99, 0x31, 0xbc, 0xf4, 0x79, 0x3c, 0x6b, 0xdd, 0x05, 0x51, 0xc8, + 0xfc, 0xd6, 0xea, 0x3c, 0x3d, 0x11, 0xbe, 0x0e, 0x99, 0x6f, 0xc7, 0x9c, 0x09, 0x86, 0x8e, 0x52, + 0xbf, 0x7d, 0x8f, 0xae, 0xce, 0x4f, 0x5e, 0xfa, 0x8c, 0xf9, 0x21, 0x6d, 0x49, 0xc2, 0xdd, 0xf2, + 0x97, 0x96, 0xb7, 0xe4, 0x44, 0x04, 0x2c, 0x52, 0x21, 0x27, 0x67, 0x0f, 0xfd, 0x22, 0x58, 0xd0, + 0x44, 0x90, 0x45, 0xac, 0x08, 0xd6, 0x07, 0x1d, 0x6a, 0x7d, 0x1e, 0xcf, 0x86, 0xcc, 0x77, 0x22, + 0xc1, 0xd7, 0xe8, 0x1b, 0xa8, 0x6c, 0x38, 0xa6, 0xd6, 0xd0, 0x9a, 0xd5, 0xf6, 0x89, 0xad, 0x54, + 0xec, 0x5c, 0xc5, 0x9e, 0xe6, 0x0c, 0x7c, 0x4f, 0x46, 0xcf, 0x41, 0x9f, 0x91, 0x30, 0x74, 0x03, + 0xcf, 0xdc, 0x6d, 0x68, 0xcd, 0x12, 0x2e, 0xa7, 0xe6, 0xc0, 0x43, 0xaf, 0xe0, 0x79, 0x42, 0x7f, + 0x5b, 0xd2, 0x68, 0x46, 0xdd, 0xc0, 0x73, 0x7f, 0x0f, 0xc4, 0x3c, 0x88, 0xdc, 0xd4, 0x69, 0xee, + 0x49, 0xe2, 0x71, 0xee, 0x1e, 0x78, 0xef, 0xa5, 0xb3, 0x47, 0xc2, 0x10, 0x7d, 0x0b, 0x25, 0xb1, + 0x8e, 0xa9, 0x59, 0x6a, 0x68, 0xcd, 0xc3, 0xf6, 0x97, 0xf6, 0xd6, 0xeb, 0xed, 0xe2, 0xc5, 0x6d, + 0x67, 0x45, 0x23, 0x31, 0x5d, 0xc7, 0x14, 0xcb, 0x30, 0xf4, 0x1d, 0x94, 0x43, 0xe6, 0xfb, 0x94, + 0x9b, 0xfb, 0x52, 0xe0, 0x8b, 0xff, 0x12, 0x18, 0x4a, 0x36, 0xce, 0xa2, 0xd0, 0x1b, 0xa8, 0xcf, + 0xc2, 0x80, 0x46, 0xc2, 0x9d, 0x53, 0xe2, 0x51, 0x6e, 0x96, 0x65, 0x31, 0xce, 0x1e, 0x91, 0xe9, + 0x49, 0xde, 0xb5, 0xa4, 0x5d, 0xef, 0xe0, 0xda, 0xac, 0x60, 0xa7, 0x3a, 0x09, 0xe5, 0x2b, 0xca, + 0x73, 0x1d, 0xfd, 0x49, 0x9d, 0x89, 0xe4, 0xdd, 0xeb, 0x24, 0x05, 0x1b, 0x5d, 0x82, 0xbe, 0xa0, + 0x49, 0x42, 0x7c, 0x6a, 0x1e, 0xe4, 0x9f, 0x65, 0x4b, 0xe1, 0xad, 0x62, 0x5c, 0xef, 0xe0, 0x9c, + 0x9c, 0xc6, 0x09, 0x4e, 0x82, 0x90, 0x72, 0xb3, 0xf2, 0x64, 0xdc, 0x54, 0x31, 0xd2, 0xb8, 0x8c, + 0x8c, 0xbe, 0x82, 0xa3, 0x98, 0xac, 0x43, 0x46, 0x3c, 0x57, 0xf0, 0x65, 0x34, 0x23, 0x82, 0x7a, + 0x26, 0x34, 0xb4, 0xe6, 0x01, 0x36, 0x32, 0xc7, 0x34, 0xc7, 0x91, 0x0d, 0xa5, 0x98, 0x52, 0x6e, + 0x56, 0x9f, 0xcc, 0xd0, 0xf1, 0x3c, 0x4e, 0x93, 0x04, 0x4b, 0x9e, 0xf5, 0x97, 0x06, 0x95, 0xcd, + 0x07, 0x43, 0xcf, 0x00, 0x39, 0xb7, 0xce, 0x68, 0xea, 0x4e, 0x7f, 0x1c, 0x3b, 0xee, 0xbb, 0xd1, + 0xf7, 0xa3, 0x9b, 0xf7, 0x23, 0x63, 0x07, 0x9d, 0x82, 0x59, 0xc0, 0x7b, 0xc3, 0x41, 0x7a, 0xbe, + 0x76, 0x3a, 0x57, 0x0e, 0x36, 0xb4, 0x07, 0xde, 0x89, 0x83, 0x6f, 0x1d, 0x9c, 0x7b, 0x77, 0xd1, + 0x67, 0xf0, 0x62, 0x3b, 0xf6, 0xad, 0x33, 0x99, 0x74, 0xfa, 0x8e, 0xb1, 0xf7, 0xc0, 0x9d, 0x05, + 0xe7, 0xee, 0x12, 0x6a, 0xc0, 0xe9, 0x23, 0x99, 0x3b, 0xc3, 0x37, 0x6e, 0x6f, 0x78, 0x33, 0x71, + 0x8c, 0xfd, 0xc7, 0x05, 0xa6, 0xb8, 0x33, 0x18, 0x3a, 0xd8, 0x28, 0xa3, 0x4f, 0xe0, 0xa8, 0x28, + 0xd0, 0x19, 0xf5, 0x9c, 0xa1, 0xa1, 0x5b, 0x5d, 0x28, 0xab, 0x36, 0x43, 0x08, 0x0e, 0x87, 0x37, + 0xfd, 0xbe, 0x83, 0x0b, 0xef, 0x3d, 0x82, 0x7a, 0x86, 0xa9, 0x8c, 0x86, 0x56, 0x80, 0x54, 0x0a, + 0x63, 0xb7, 0x5b, 0x01, 0x3d, 0xab, 0xbf, 0xf5, 0x41, 0x83, 0x5a, 0xb1, 0xf9, 0xd0, 0x6b, 0x38, + 0x58, 0x50, 0x41, 0x3c, 0x22, 0x48, 0x36, 0xbc, 0x9f, 0x3e, 0xda, 0x25, 0x8a, 0x82, 0x37, 0x64, + 0x74, 0x06, 0xd5, 0x05, 0x15, 0x73, 0xe6, 0xb9, 0x11, 0x59, 0x50, 0x39, 0xc0, 0x15, 0x0c, 0x0a, + 0x1a, 0x91, 0x05, 0x45, 0xa7, 0x50, 0x21, 0x4b, 0x31, 0x67, 0x3c, 0x10, 0x6b, 0x39, 0xb6, 0x15, + 0x7c, 0x0f, 0xa0, 0x0b, 0xd0, 0xd3, 0x45, 0xc0, 0x96, 0x42, 0x8e, 0x6b, 0xb5, 0xfd, 0x62, 0x6b, + 0x67, 0x5c, 0x65, 0x9b, 0x09, 0xe7, 0x4c, 0xab, 0x0f, 0xb5, 0x62, 0xc7, 0xff, 0xef, 0xcb, 0x5b, + 0x7f, 0x68, 0xa0, 0x67, 0x1d, 0xfc, 0x51, 0x15, 0x48, 0x04, 0x11, 0xcb, 0xc4, 0x9d, 0x31, 0x4f, + 0x55, 0xa0, 0x8e, 0x41, 0x41, 0x3d, 0xe6, 0x51, 0xf4, 0x39, 0x1c, 0x66, 0x84, 0x7c, 0x0e, 0x55, + 0x19, 0xea, 0x0a, 0xcd, 0x46, 0xaf, 0x40, 0xf3, 0xa8, 0x20, 0x41, 0x98, 0xc8, 0x8a, 0xd4, 0x72, + 0xda, 0x95, 0x02, 0xad, 0x57, 0xa0, 0xe7, 0x11, 0xcf, 0xa0, 0x1c, 0xd2, 0xc8, 0x17, 0x73, 0x79, + 0xe1, 0x3a, 0xce, 0x2c, 0x84, 0xa0, 0x24, 0x9f, 0xb1, 0x2b, 0xe3, 0xe5, 0xd9, 0xea, 0xc2, 0x41, + 0x7e, 0x77, 0x74, 0x09, 0xfb, 0x34, 0xdd, 0x5c, 0xa6, 0xd6, 0xd8, 0x6b, 0x56, 0xdb, 0x8d, 0x7f, + 0x79, 0xa7, 0xdc, 0x70, 0x58, 0xd1, 0xad, 0xd7, 0x50, 0xff, 0x07, 0x8e, 0x0c, 0xd8, 0xfb, 0x95, + 0xae, 0x65, 0xf6, 0x0a, 0x4e, 0x8f, 0xe8, 0x18, 0xf6, 0x57, 0x24, 0x5c, 0xd2, 0x2c, 0xb7, 0x32, + 0xac, 0x3f, 0x35, 0xd0, 0xb3, 0x39, 0x46, 0x17, 0xd9, 0x76, 0xd6, 0xe4, 0x72, 0x3d, 0x7b, 0x7a, + 0xe2, 0xed, 0xc2, 0x4e, 0x36, 0x41, 0x27, 0x0a, 0xcd, 0x3a, 0x2c, 0x37, 0xd3, 0x9f, 0x47, 0x10, + 0xbb, 0x31, 0xe3, 0x42, 0x56, 0xb5, 0x8e, 0xcb, 0x41, 0x3c, 0x66, 0x5c, 0x58, 0x0e, 0x94, 0xe4, + 0x8e, 0x30, 0xa0, 0xf6, 0x60, 0x3b, 0xd4, 0xa1, 0x22, 0x91, 0xc1, 0xf8, 0xf6, 0x6b, 0x43, 0x2b, + 0x9a, 0x97, 0xc6, 0xee, 0xc6, 0x7c, 0x37, 0x1a, 0xfc, 0x60, 0xec, 0x75, 0x7f, 0x86, 0xe3, 0x80, + 0x6d, 0x5f, 0xb2, 0x7b, 0xd8, 0x95, 0xd6, 0x90, 0xf9, 0xe3, 0xb4, 0x51, 0xc7, 0xda, 0x4f, 0xed, + 0xac, 0x71, 0x7d, 0x16, 0x92, 0xc8, 0xb7, 0x19, 0xf7, 0x5b, 0xf9, 0x7f, 0x59, 0x85, 0x49, 0xd3, + 0xdd, 0x98, 0xee, 0xea, 0xfc, 0xae, 0x2c, 0xbb, 0xfc, 0xe2, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, + 0x10, 0x93, 0x68, 0x41, 0xc2, 0x07, 0x00, 0x00, } diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go index f58740b2507..ef327e8af4f 100644 --- a/vendor/google.golang.org/grpc/clientconn.go +++ b/vendor/google.golang.org/grpc/clientconn.go @@ -35,10 +35,10 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/backoff" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" + "google.golang.org/grpc/internal/grpcutil" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/resolver" @@ -68,8 +68,6 @@ var ( errConnDrain = errors.New("grpc: the connection is drained") // errConnClosing indicates that the connection is closing. errConnClosing = errors.New("grpc: the connection is closing") - // errBalancerClosed indicates that the balancer is closed. - errBalancerClosed = errors.New("grpc: balancer is closed") // invalidDefaultServiceConfigErrPrefix is used to prefix the json parsing error for the default // service config. invalidDefaultServiceConfigErrPrefix = "grpc: the provided default service config is invalid" @@ -151,7 +149,7 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * if channelz.IsOn() { if cc.dopts.channelzParentID != 0 { cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, cc.dopts.channelzParentID, target) - channelz.AddTraceEvent(cc.channelzID, &channelz.TraceEventDesc{ + channelz.AddTraceEvent(cc.channelzID, 0, &channelz.TraceEventDesc{ Desc: "Channel Created", Severity: channelz.CtINFO, Parent: &channelz.TraceEventDesc{ @@ -161,10 +159,7 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * }) } else { cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, 0, target) - channelz.AddTraceEvent(cc.channelzID, &channelz.TraceEventDesc{ - Desc: "Channel Created", - Severity: channelz.CtINFO, - }) + channelz.Info(cc.channelzID, "Channel Created") } cc.csMgr.channelzID = cc.channelzID } @@ -197,12 +192,13 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * cc.mkp = cc.dopts.copts.KeepaliveParams if cc.dopts.copts.Dialer == nil { - cc.dopts.copts.Dialer = newProxyDialer( - func(ctx context.Context, addr string) (net.Conn, error) { - network, addr := parseDialTarget(addr) - return (&net.Dialer{}).DialContext(ctx, network, addr) - }, - ) + cc.dopts.copts.Dialer = func(ctx context.Context, addr string) (net.Conn, error) { + network, addr := parseDialTarget(addr) + return (&net.Dialer{}).DialContext(ctx, network, addr) + } + if cc.dopts.withProxy { + cc.dopts.copts.Dialer = newProxyDialer(cc.dopts.copts.Dialer) + } } if cc.dopts.copts.UserAgent != "" { @@ -219,7 +215,14 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * defer func() { select { case <-ctx.Done(): - conn, err = nil, ctx.Err() + switch { + case ctx.Err() == err: + conn = nil + case err == nil || !cc.dopts.returnLastError: + conn, err = nil, ctx.Err() + default: + conn, err = nil, fmt.Errorf("%v: %v", ctx.Err(), err) + } default: } }() @@ -241,14 +244,14 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * } // Determine the resolver to use. - cc.parsedTarget = parseTarget(cc.target) - grpclog.Infof("parsed scheme: %q", cc.parsedTarget.Scheme) + cc.parsedTarget = grpcutil.ParseTarget(cc.target) + channelz.Infof(cc.channelzID, "parsed scheme: %q", cc.parsedTarget.Scheme) resolverBuilder := cc.getResolver(cc.parsedTarget.Scheme) if resolverBuilder == nil { // If resolver builder is still nil, the parsed target's scheme is // not registered. Fallback to default resolver and set Endpoint to // the original target. - grpclog.Infof("scheme %q not registered, fallback to default scheme", cc.parsedTarget.Scheme) + channelz.Infof(cc.channelzID, "scheme %q not registered, fallback to default scheme", cc.parsedTarget.Scheme) cc.parsedTarget = resolver.Target{ Scheme: resolver.GetDefaultScheme(), Endpoint: target, @@ -313,7 +316,7 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * if s == connectivity.Ready { break } else if cc.dopts.copts.FailOnNonTempDialError && s == connectivity.TransientFailure { - if err = cc.blockingpicker.connectionError(); err != nil { + if err = cc.connectionError(); err != nil { terr, ok := err.(interface { Temporary() bool }) @@ -324,6 +327,9 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * } if !cc.WaitForStateChange(ctx, s) { // ctx got timeout or canceled. + if err = cc.connectionError(); err != nil && cc.dopts.returnLastError { + return nil, err + } return nil, ctx.Err() } } @@ -416,12 +422,7 @@ func (csm *connectivityStateManager) updateState(state connectivity.State) { return } csm.state = state - if channelz.IsOn() { - channelz.AddTraceEvent(csm.channelzID, &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Channel Connectivity change to %v", state), - Severity: channelz.CtINFO, - }) - } + channelz.Infof(csm.channelzID, "Channel Connectivity change to %v", state) if csm.notifyChan != nil { // There are other goroutines waiting on this channel. close(csm.notifyChan) @@ -497,6 +498,9 @@ type ClientConn struct { channelzID int64 // channelz unique identification number czData *channelzData + + lceMu sync.Mutex // protects lastConnectionError + lastConnectionError error } // WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or @@ -671,9 +675,9 @@ func (cc *ClientConn) switchBalancer(name string) { return } - grpclog.Infof("ClientConn switching balancer to %q", name) + channelz.Infof(cc.channelzID, "ClientConn switching balancer to %q", name) if cc.dopts.balancerBuilder != nil { - grpclog.Infoln("ignoring balancer switching: Balancer DialOption used instead") + channelz.Info(cc.channelzID, "ignoring balancer switching: Balancer DialOption used instead") return } if cc.balancerWrapper != nil { @@ -681,22 +685,12 @@ func (cc *ClientConn) switchBalancer(name string) { } builder := balancer.Get(name) - if channelz.IsOn() { - if builder == nil { - channelz.AddTraceEvent(cc.channelzID, &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Channel switches to new LB policy %q due to fallback from invalid balancer name", PickFirstBalancerName), - Severity: channelz.CtWarning, - }) - } else { - channelz.AddTraceEvent(cc.channelzID, &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Channel switches to new LB policy %q", name), - Severity: channelz.CtINFO, - }) - } - } if builder == nil { - grpclog.Infof("failed to get balancer builder for: %v, using pick_first instead", name) + channelz.Warningf(cc.channelzID, "Channel switches to new LB policy %q due to fallback from invalid balancer name", PickFirstBalancerName) + channelz.Infof(cc.channelzID, "failed to get balancer builder for: %v, using pick_first instead", name) builder = newPickfirstBuilder() + } else { + channelz.Infof(cc.channelzID, "Channel switches to new LB policy %q", name) } cc.curBalancerName = builder.Name() @@ -720,6 +714,7 @@ func (cc *ClientConn) handleSubConnStateChange(sc balancer.SubConn, s connectivi // Caller needs to make sure len(addrs) > 0. func (cc *ClientConn) newAddrConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (*addrConn, error) { ac := &addrConn{ + state: connectivity.Idle, cc: cc, addrs: addrs, scopts: opts, @@ -736,7 +731,7 @@ func (cc *ClientConn) newAddrConn(addrs []resolver.Address, opts balancer.NewSub } if channelz.IsOn() { ac.channelzID = channelz.RegisterSubChannel(ac, cc.channelzID, "") - channelz.AddTraceEvent(ac.channelzID, &channelz.TraceEventDesc{ + channelz.AddTraceEvent(ac.channelzID, 0, &channelz.TraceEventDesc{ Desc: "Subchannel Created", Severity: channelz.CtINFO, Parent: &channelz.TraceEventDesc{ @@ -834,7 +829,7 @@ func (ac *addrConn) connect() error { func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool { ac.mu.Lock() defer ac.mu.Unlock() - grpclog.Infof("addrConn: tryUpdateAddrs curAddr: %v, addrs: %v", ac.curAddr, addrs) + channelz.Infof(ac.channelzID, "addrConn: tryUpdateAddrs curAddr: %v, addrs: %v", ac.curAddr, addrs) if ac.state == connectivity.Shutdown || ac.state == connectivity.TransientFailure || ac.state == connectivity.Idle { @@ -854,7 +849,7 @@ func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool { break } } - grpclog.Infof("addrConn: tryUpdateAddrs curAddrFound: %v", curAddrFound) + channelz.Infof(ac.channelzID, "addrConn: tryUpdateAddrs curAddrFound: %v", curAddrFound) if curAddrFound { ac.addrs = addrs } @@ -1025,7 +1020,7 @@ func (cc *ClientConn) Close() error { Severity: channelz.CtINFO, } } - channelz.AddTraceEvent(cc.channelzID, ted) + channelz.AddTraceEvent(cc.channelzID, 0, ted) // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add trace reference to // the entity being deleted, and thus prevent it from being deleted right away. channelz.RemoveEntry(cc.channelzID) @@ -1068,15 +1063,8 @@ func (ac *addrConn) updateConnectivityState(s connectivity.State, lastErr error) if ac.state == s { return } - - updateMsg := fmt.Sprintf("Subchannel Connectivity change to %v", s) ac.state = s - if channelz.IsOn() { - channelz.AddTraceEvent(ac.channelzID, &channelz.TraceEventDesc{ - Desc: updateMsg, - Severity: channelz.CtINFO, - }) - } + channelz.Infof(ac.channelzID, "Subchannel Connectivity change to %v", s) ac.cc.handleSubConnStateChange(ac.acbw, s, lastErr) } @@ -1213,12 +1201,7 @@ func (ac *addrConn) tryAllAddrs(addrs []resolver.Address, connectDeadline time.T } ac.mu.Unlock() - if channelz.IsOn() { - channelz.AddTraceEvent(ac.channelzID, &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Subchannel picks a new address %q to connect", addr.Addr), - Severity: channelz.CtINFO, - }) - } + channelz.Infof(ac.channelzID, "Subchannel picks a new address %q to connect", addr.Addr) newTr, reconnect, err := ac.createTransport(addr, copts, connectDeadline) if err == nil { @@ -1227,7 +1210,7 @@ func (ac *addrConn) tryAllAddrs(addrs []resolver.Address, connectDeadline time.T if firstConnErr == nil { firstConnErr = err } - ac.cc.blockingpicker.updateConnectionError(err) + ac.cc.updateConnectionError(err) } // Couldn't connect to any address. @@ -1242,16 +1225,9 @@ func (ac *addrConn) createTransport(addr resolver.Address, copts transport.Conne onCloseCalled := make(chan struct{}) reconnect := grpcsync.NewEvent() - authority := ac.cc.authority // addr.ServerName takes precedent over ClientConn authority, if present. - if addr.ServerName != "" { - authority = addr.ServerName - } - - target := transport.TargetInfo{ - Addr: addr.Addr, - Metadata: addr.Metadata, - Authority: authority, + if addr.ServerName == "" { + addr.ServerName = ac.cc.authority } once := sync.Once{} @@ -1297,10 +1273,10 @@ func (ac *addrConn) createTransport(addr resolver.Address, copts transport.Conne copts.ChannelzParentID = ac.channelzID } - newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, target, copts, onPrefaceReceipt, onGoAway, onClose) + newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, addr, copts, onPrefaceReceipt, onGoAway, onClose) if err != nil { // newTr is either nil, or closed. - grpclog.Warningf("grpc: addrConn.createTransport failed to connect to %v. Err :%v. Reconnecting...", addr, err) + channelz.Warningf(ac.channelzID, "grpc: addrConn.createTransport failed to connect to %v. Err: %v. Reconnecting...", addr, err) return nil, nil, err } @@ -1308,7 +1284,7 @@ func (ac *addrConn) createTransport(addr resolver.Address, copts transport.Conne case <-time.After(time.Until(connectDeadline)): // We didn't get the preface in time. newTr.Close() - grpclog.Warningf("grpc: addrConn.createTransport failed to connect to %v: didn't receive server preface in time. Reconnecting...", addr) + channelz.Warningf(ac.channelzID, "grpc: addrConn.createTransport failed to connect to %v: didn't receive server preface in time. Reconnecting...", addr) return nil, nil, errors.New("timed out waiting for server handshake") case <-prefaceReceived: // We got the preface - huzzah! things are good. @@ -1355,7 +1331,7 @@ func (ac *addrConn) startHealthCheck(ctx context.Context) { // The health package is not imported to set health check function. // // TODO: add a link to the health check doc in the error message. - grpclog.Error("Health check is requested but health check function is not set.") + channelz.Error(ac.channelzID, "Health check is requested but health check function is not set.") return } @@ -1385,15 +1361,9 @@ func (ac *addrConn) startHealthCheck(ctx context.Context) { err := ac.cc.dopts.healthCheckFunc(ctx, newStream, setConnectivityState, healthCheckConfig.ServiceName) if err != nil { if status.Code(err) == codes.Unimplemented { - if channelz.IsOn() { - channelz.AddTraceEvent(ac.channelzID, &channelz.TraceEventDesc{ - Desc: "Subchannel health check is unimplemented at server side, thus health check is disabled", - Severity: channelz.CtError, - }) - } - grpclog.Error("Subchannel health check is unimplemented at server side, thus health check is disabled") + channelz.Error(ac.channelzID, "Subchannel health check is unimplemented at server side, thus health check is disabled") } else { - grpclog.Errorf("HealthCheckFunc exits with unexpected error %v", err) + channelz.Errorf(ac.channelzID, "HealthCheckFunc exits with unexpected error %v", err) } } }() @@ -1458,7 +1428,7 @@ func (ac *addrConn) tearDown(err error) { ac.mu.Lock() } if channelz.IsOn() { - channelz.AddTraceEvent(ac.channelzID, &channelz.TraceEventDesc{ + channelz.AddTraceEvent(ac.channelzID, 0, &channelz.TraceEventDesc{ Desc: "Subchannel Deleted", Severity: channelz.CtINFO, Parent: &channelz.TraceEventDesc{ @@ -1560,9 +1530,21 @@ var ErrClientConnTimeout = errors.New("grpc: timed out when dialing") func (cc *ClientConn) getResolver(scheme string) resolver.Builder { for _, rb := range cc.dopts.resolvers { - if cc.parsedTarget.Scheme == rb.Scheme() { + if scheme == rb.Scheme() { return rb } } - return resolver.Get(cc.parsedTarget.Scheme) + return resolver.Get(scheme) +} + +func (cc *ClientConn) updateConnectionError(err error) { + cc.lceMu.Lock() + cc.lastConnectionError = err + cc.lceMu.Unlock() +} + +func (cc *ClientConn) connectionError() error { + cc.lceMu.Lock() + defer cc.lceMu.Unlock() + return cc.lastConnectionError } diff --git a/vendor/google.golang.org/grpc/credentials/credentials.go b/vendor/google.golang.org/grpc/credentials/credentials.go index 845ce5d2161..02766443ae7 100644 --- a/vendor/google.golang.org/grpc/credentials/credentials.go +++ b/vendor/google.golang.org/grpc/credentials/credentials.go @@ -29,6 +29,7 @@ import ( "net" "github.com/golang/protobuf/proto" + "google.golang.org/grpc/attributes" "google.golang.org/grpc/internal" ) @@ -57,9 +58,11 @@ type PerRPCCredentials interface { type SecurityLevel int const ( - // NoSecurity indicates a connection is insecure. + // Invalid indicates an invalid security level. // The zero SecurityLevel value is invalid for backward compatibility. - NoSecurity SecurityLevel = iota + 1 + Invalid SecurityLevel = iota + // NoSecurity indicates a connection is insecure. + NoSecurity // IntegrityOnly indicates a connection only provides integrity protection. IntegrityOnly // PrivacyAndIntegrity indicates a connection provides both privacy and integrity protection. @@ -100,7 +103,11 @@ type ProtocolInfo struct { ProtocolVersion string // SecurityProtocol is the security protocol in use. SecurityProtocol string - // SecurityVersion is the security protocol version. + // SecurityVersion is the security protocol version. It is a static version string from the + // credentials, not a value that reflects per-connection protocol negotiation. To retrieve + // details about the credentials used for a connection, use the Peer's AuthInfo field instead. + // + // Deprecated: please use Peer.AuthInfo. SecurityVersion string // ServerName is the user-configured server name. ServerName string @@ -120,15 +127,18 @@ var ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gR // TransportCredentials defines the common interface for all the live gRPC wire // protocols and supported transport security protocols (e.g., TLS, SSL). type TransportCredentials interface { - // ClientHandshake does the authentication handshake specified by the corresponding - // authentication protocol on rawConn for clients. It returns the authenticated - // connection and the corresponding auth information about the connection. - // The auth information should embed CommonAuthInfo to return additional information about - // the credentials. Implementations must use the provided context to implement timely cancellation. - // gRPC will try to reconnect if the error returned is a temporary error - // (io.EOF, context.DeadlineExceeded or err.Temporary() == true). - // If the returned error is a wrapper error, implementations should make sure that + // ClientHandshake does the authentication handshake specified by the + // corresponding authentication protocol on rawConn for clients. It returns + // the authenticated connection and the corresponding auth information + // about the connection. The auth information should embed CommonAuthInfo + // to return additional information about the credentials. Implementations + // must use the provided context to implement timely cancellation. gRPC + // will try to reconnect if the error returned is a temporary error + // (io.EOF, context.DeadlineExceeded or err.Temporary() == true). If the + // returned error is a wrapper error, implementations should make sure that // the error implements Temporary() to have the correct retry behaviors. + // Additionally, ClientHandshakeInfo data will be available via the context + // passed to this call. // // If the returned net.Conn is closed, it MUST close the net.Conn provided. ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error) @@ -189,6 +199,31 @@ func RequestInfoFromContext(ctx context.Context) (ri RequestInfo, ok bool) { return } +// ClientHandshakeInfo holds data to be passed to ClientHandshake. This makes +// it possible to pass arbitrary data to the handshaker from gRPC, resolver, +// balancer etc. Individual credential implementations control the actual +// format of the data that they are willing to receive. +// +// This API is experimental. +type ClientHandshakeInfo struct { + // Attributes contains the attributes for the address. It could be provided + // by the gRPC, resolver, balancer etc. + Attributes *attributes.Attributes +} + +// clientHandshakeInfoKey is a struct used as the key to store +// ClientHandshakeInfo in a context. +type clientHandshakeInfoKey struct{} + +// ClientHandshakeInfoFromContext returns the ClientHandshakeInfo struct stored +// in ctx. +// +// This API is experimental. +func ClientHandshakeInfoFromContext(ctx context.Context) ClientHandshakeInfo { + chi, _ := ctx.Value(clientHandshakeInfoKey{}).(ClientHandshakeInfo) + return chi +} + // CheckSecurityLevel checks if a connection's security level is greater than or equal to the specified one. // It returns success if 1) the condition is satisified or 2) AuthInfo struct does not implement GetCommonAuthInfo() method // or 3) CommonAuthInfo.SecurityLevel has an invalid zero value. For 2) and 3), it is for the purpose of backward-compatibility. @@ -204,7 +239,7 @@ func CheckSecurityLevel(ctx context.Context, level SecurityLevel) error { } if ci, ok := ri.AuthInfo.(internalInfo); ok { // CommonAuthInfo.SecurityLevel has an invalid value. - if ci.GetCommonAuthInfo().SecurityLevel == 0 { + if ci.GetCommonAuthInfo().SecurityLevel == Invalid { return nil } if ci.GetCommonAuthInfo().SecurityLevel < level { @@ -219,6 +254,9 @@ func init() { internal.NewRequestInfoContext = func(ctx context.Context, ri RequestInfo) context.Context { return context.WithValue(ctx, requestInfoKey{}, ri) } + internal.NewClientHandshakeInfoContext = func(ctx context.Context, chi ClientHandshakeInfo) context.Context { + return context.WithValue(ctx, clientHandshakeInfoKey{}, chi) + } } // ChannelzSecurityInfo defines the interface that security protocols should implement diff --git a/vendor/google.golang.org/grpc/credentials/tls.go b/vendor/google.golang.org/grpc/credentials/tls.go index 28b4f6232de..86e956bc8b7 100644 --- a/vendor/google.golang.org/grpc/credentials/tls.go +++ b/vendor/google.golang.org/grpc/credentials/tls.go @@ -135,16 +135,26 @@ func NewTLS(c *tls.Config) TransportCredentials { return tc } -// NewClientTLSFromCert constructs TLS credentials from the input certificate for client. +// NewClientTLSFromCert constructs TLS credentials from the provided root +// certificate authority certificate(s) to validate server connections. If +// certificates to establish the identity of the client need to be included in +// the credentials (eg: for mTLS), use NewTLS instead, where a complete +// tls.Config can be specified. // serverNameOverride is for testing only. If set to a non empty string, -// it will override the virtual host name of authority (e.g. :authority header field) in requests. +// it will override the virtual host name of authority (e.g. :authority header +// field) in requests. func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials { return NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}) } -// NewClientTLSFromFile constructs TLS credentials from the input certificate file for client. +// NewClientTLSFromFile constructs TLS credentials from the provided root +// certificate authority certificate file(s) to validate server connections. If +// certificates to establish the identity of the client need to be included in +// the credentials (eg: for mTLS), use NewTLS instead, where a complete +// tls.Config can be specified. // serverNameOverride is for testing only. If set to a non empty string, -// it will override the virtual host name of authority (e.g. :authority header field) in requests. +// it will override the virtual host name of authority (e.g. :authority header +// field) in requests. func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) { b, err := ioutil.ReadFile(certFile) if err != nil { diff --git a/vendor/google.golang.org/grpc/dialoptions.go b/vendor/google.golang.org/grpc/dialoptions.go index 63f5ae21df1..d5030c07617 100644 --- a/vendor/google.golang.org/grpc/dialoptions.go +++ b/vendor/google.golang.org/grpc/dialoptions.go @@ -46,18 +46,18 @@ type dialOptions struct { chainUnaryInts []UnaryClientInterceptor chainStreamInts []StreamClientInterceptor - cp Compressor - dc Decompressor - bs internalbackoff.Strategy - block bool - insecure bool - timeout time.Duration - scChan <-chan ServiceConfig - authority string - copts transport.ConnectOptions - callOptions []CallOption - // This is used by v1 balancer dial option WithBalancer to support v1 - // balancer, and also by WithBalancerName dial option. + cp Compressor + dc Decompressor + bs internalbackoff.Strategy + block bool + returnLastError bool + insecure bool + timeout time.Duration + scChan <-chan ServiceConfig + authority string + copts transport.ConnectOptions + callOptions []CallOption + // This is used by WithBalancerName dial option. balancerBuilder balancer.Builder channelzParentID int64 disableServiceConfig bool @@ -72,6 +72,7 @@ type dialOptions struct { // we need to be able to configure this in tests. resolveNowBackoff func(int) time.Duration resolvers []resolver.Builder + withProxy bool } // DialOption configures how we set up the connection. @@ -198,19 +199,6 @@ func WithDecompressor(dc Decompressor) DialOption { }) } -// WithBalancer returns a DialOption which sets a load balancer with the v1 API. -// Name resolver will be ignored if this DialOption is specified. -// -// Deprecated: use the new balancer APIs in balancer package and -// WithBalancerName. Will be removed in a future 1.x release. -func WithBalancer(b Balancer) DialOption { - return newFuncDialOption(func(o *dialOptions) { - o.balancerBuilder = &balancerWrapperBuilder{ - b: b, - } - }) -} - // WithBalancerName sets the balancer that the ClientConn will be initialized // with. Balancer registered with balancerName will be used. This function // panics if no balancer was registered by balancerName. @@ -298,6 +286,19 @@ func WithBlock() DialOption { }) } +// WithReturnConnectionError returns a DialOption which makes the client connection +// return a string containing both the last connection error that occurred and +// the context.DeadlineExceeded error. +// Implies WithBlock() +// +// This API is EXPERIMENTAL. +func WithReturnConnectionError() DialOption { + return newFuncDialOption(func(o *dialOptions) { + o.block = true + o.returnLastError = true + }) +} + // WithInsecure returns a DialOption which disables transport security for this // ClientConn. Note that transport security is required unless WithInsecure is // set. @@ -307,6 +308,16 @@ func WithInsecure() DialOption { }) } +// WithNoProxy returns a DialOption which disables the use of proxies for this +// ClientConn. This is ignored if WithDialer or WithContextDialer are used. +// +// This API is EXPERIMENTAL. +func WithNoProxy() DialOption { + return newFuncDialOption(func(o *dialOptions) { + o.withProxy = false + }) +} + // WithTransportCredentials returns a DialOption which configures a connection // level security credentials (e.g., TLS/SSL). This should not be used together // with WithCredentialsBundle. @@ -448,7 +459,7 @@ func WithStreamInterceptor(f StreamClientInterceptor) DialOption { } // WithChainStreamInterceptor returns a DialOption that specifies the chained -// interceptor for unary RPCs. The first interceptor will be the outer most, +// interceptor for streaming RPCs. The first interceptor will be the outer most, // while the last interceptor will be the inner most wrapper around the real call. // All interceptors added by this method will be chained, and the interceptor // defined by WithStreamInterceptor will always be prepended to the chain. @@ -557,6 +568,7 @@ func defaultDialOptions() dialOptions { ReadBufferSize: defaultReadBufSize, }, resolveNowBackoff: internalbackoff.DefaultExponential.Backoff, + withProxy: true, } } diff --git a/vendor/google.golang.org/grpc/doc.go b/vendor/google.golang.org/grpc/doc.go index 187adbb117f..0022859ad74 100644 --- a/vendor/google.golang.org/grpc/doc.go +++ b/vendor/google.golang.org/grpc/doc.go @@ -16,6 +16,8 @@ * */ +//go:generate ./regenerate.sh + /* Package grpc implements an RPC system called gRPC. diff --git a/vendor/google.golang.org/grpc/go.mod b/vendor/google.golang.org/grpc/go.mod index 2378361302f..31f2b01f64e 100644 --- a/vendor/google.golang.org/grpc/go.mod +++ b/vendor/google.golang.org/grpc/go.mod @@ -3,12 +3,11 @@ module google.golang.org/grpc go 1.11 require ( - github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473 - github.com/envoyproxy/protoc-gen-validate v0.1.0 + github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f + github.com/envoyproxy/go-control-plane v0.9.4 github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b - github.com/golang/mock v1.1.1 - github.com/golang/protobuf v1.3.2 - github.com/google/go-cmp v0.2.0 + github.com/golang/protobuf v1.3.3 + github.com/google/go-cmp v0.4.0 golang.org/x/net v0.0.0-20190311183353-d8887717615a golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a diff --git a/vendor/google.golang.org/grpc/go.sum b/vendor/google.golang.org/grpc/go.sum index dd5d0cee7ad..be8078eace2 100644 --- a/vendor/google.golang.org/grpc/go.sum +++ b/vendor/google.golang.org/grpc/go.sum @@ -1,10 +1,15 @@ cloud.google.com/go v0.26.0 h1:e0WKqKTd5BnrG8aKH3J3h+QvEIQtSUcf2n5UZ5ZgLtQ= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/client9/misspell v0.3.4 h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473 h1:4cmBvAEBNJaGARUEs3/suWRyfyBfhf7I60WBZq+bv2w= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f h1:WBZRG4aNOuI15bLRrCgN8fCq8E5Xuty6jGbmSNEvSsU= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4 h1:rEvIZUSZ3fx39WIi3JkQqQBitGwpELBIYWeBVh6wn+E= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0 h1:EQciDnbrYxy13PgWoY8AqoxGiPrpgBZ1R8UNe3ddc+A= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= @@ -14,13 +19,18 @@ github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfb github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 h1:XQyxROzUlZH+WIQwySDgnISgOivlhjIEwaQaJEJrrN0= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -40,7 +50,10 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135 h1:5Beo0mZN8dRzgrMMkDp0jc8YXQKx9DiJ2k1dkvGsn5A= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -49,5 +62,7 @@ google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2El google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/vendor/google.golang.org/grpc/grpclog/grpclog.go b/vendor/google.golang.org/grpc/grpclog/grpclog.go index 874ea6d98a6..c8bb2be34bf 100644 --- a/vendor/google.golang.org/grpc/grpclog/grpclog.go +++ b/vendor/google.golang.org/grpc/grpclog/grpclog.go @@ -26,64 +26,70 @@ // verbosity level can be set by GRPC_GO_LOG_VERBOSITY_LEVEL. package grpclog // import "google.golang.org/grpc/grpclog" -import "os" +import ( + "os" -var logger = newLoggerV2() + "google.golang.org/grpc/internal/grpclog" +) + +func init() { + SetLoggerV2(newLoggerV2()) +} // V reports whether verbosity level l is at least the requested verbose level. func V(l int) bool { - return logger.V(l) + return grpclog.Logger.V(l) } // Info logs to the INFO log. func Info(args ...interface{}) { - logger.Info(args...) + grpclog.Logger.Info(args...) } // Infof logs to the INFO log. Arguments are handled in the manner of fmt.Printf. func Infof(format string, args ...interface{}) { - logger.Infof(format, args...) + grpclog.Logger.Infof(format, args...) } // Infoln logs to the INFO log. Arguments are handled in the manner of fmt.Println. func Infoln(args ...interface{}) { - logger.Infoln(args...) + grpclog.Logger.Infoln(args...) } // Warning logs to the WARNING log. func Warning(args ...interface{}) { - logger.Warning(args...) + grpclog.Logger.Warning(args...) } // Warningf logs to the WARNING log. Arguments are handled in the manner of fmt.Printf. func Warningf(format string, args ...interface{}) { - logger.Warningf(format, args...) + grpclog.Logger.Warningf(format, args...) } // Warningln logs to the WARNING log. Arguments are handled in the manner of fmt.Println. func Warningln(args ...interface{}) { - logger.Warningln(args...) + grpclog.Logger.Warningln(args...) } // Error logs to the ERROR log. func Error(args ...interface{}) { - logger.Error(args...) + grpclog.Logger.Error(args...) } // Errorf logs to the ERROR log. Arguments are handled in the manner of fmt.Printf. func Errorf(format string, args ...interface{}) { - logger.Errorf(format, args...) + grpclog.Logger.Errorf(format, args...) } // Errorln logs to the ERROR log. Arguments are handled in the manner of fmt.Println. func Errorln(args ...interface{}) { - logger.Errorln(args...) + grpclog.Logger.Errorln(args...) } // Fatal logs to the FATAL log. Arguments are handled in the manner of fmt.Print. // It calls os.Exit() with exit code 1. func Fatal(args ...interface{}) { - logger.Fatal(args...) + grpclog.Logger.Fatal(args...) // Make sure fatal logs will exit. os.Exit(1) } @@ -91,7 +97,7 @@ func Fatal(args ...interface{}) { // Fatalf logs to the FATAL log. Arguments are handled in the manner of fmt.Printf. // It calls os.Exit() with exit code 1. func Fatalf(format string, args ...interface{}) { - logger.Fatalf(format, args...) + grpclog.Logger.Fatalf(format, args...) // Make sure fatal logs will exit. os.Exit(1) } @@ -99,7 +105,7 @@ func Fatalf(format string, args ...interface{}) { // Fatalln logs to the FATAL log. Arguments are handled in the manner of fmt.Println. // It calle os.Exit()) with exit code 1. func Fatalln(args ...interface{}) { - logger.Fatalln(args...) + grpclog.Logger.Fatalln(args...) // Make sure fatal logs will exit. os.Exit(1) } @@ -108,19 +114,19 @@ func Fatalln(args ...interface{}) { // // Deprecated: use Info. func Print(args ...interface{}) { - logger.Info(args...) + grpclog.Logger.Info(args...) } // Printf prints to the logger. Arguments are handled in the manner of fmt.Printf. // // Deprecated: use Infof. func Printf(format string, args ...interface{}) { - logger.Infof(format, args...) + grpclog.Logger.Infof(format, args...) } // Println prints to the logger. Arguments are handled in the manner of fmt.Println. // // Deprecated: use Infoln. func Println(args ...interface{}) { - logger.Infoln(args...) + grpclog.Logger.Infoln(args...) } diff --git a/vendor/google.golang.org/grpc/grpclog/logger.go b/vendor/google.golang.org/grpc/grpclog/logger.go index 097494f710f..ef06a4822b7 100644 --- a/vendor/google.golang.org/grpc/grpclog/logger.go +++ b/vendor/google.golang.org/grpc/grpclog/logger.go @@ -18,6 +18,8 @@ package grpclog +import "google.golang.org/grpc/internal/grpclog" + // Logger mimics golang's standard Logger as an interface. // // Deprecated: use LoggerV2. @@ -35,7 +37,7 @@ type Logger interface { // // Deprecated: use SetLoggerV2. func SetLogger(l Logger) { - logger = &loggerWrapper{Logger: l} + grpclog.Logger = &loggerWrapper{Logger: l} } // loggerWrapper wraps Logger into a LoggerV2. diff --git a/vendor/google.golang.org/grpc/grpclog/loggerv2.go b/vendor/google.golang.org/grpc/grpclog/loggerv2.go index d4932577695..23612b7c41b 100644 --- a/vendor/google.golang.org/grpc/grpclog/loggerv2.go +++ b/vendor/google.golang.org/grpc/grpclog/loggerv2.go @@ -24,6 +24,8 @@ import ( "log" "os" "strconv" + + "google.golang.org/grpc/internal/grpclog" ) // LoggerV2 does underlying logging work for grpclog. @@ -65,7 +67,8 @@ type LoggerV2 interface { // SetLoggerV2 sets logger that is used in grpc to a V2 logger. // Not mutex-protected, should be called before any gRPC functions. func SetLoggerV2(l LoggerV2) { - logger = l + grpclog.Logger = l + grpclog.DepthLogger, _ = l.(grpclog.DepthLoggerV2) } const ( @@ -193,3 +196,19 @@ func (g *loggerT) Fatalf(format string, args ...interface{}) { func (g *loggerT) V(l int) bool { return l <= g.v } + +// DepthLoggerV2 logs at a specified call frame. If a LoggerV2 also implements +// DepthLoggerV2, the below functions will be called with the appropriate stack +// depth set for trivial functions the logger may ignore. +// +// This API is EXPERIMENTAL. +type DepthLoggerV2 interface { + // InfoDepth logs to INFO log at the specified depth. Arguments are handled in the manner of fmt.Print. + InfoDepth(depth int, args ...interface{}) + // WarningDepth logs to WARNING log at the specified depth. Arguments are handled in the manner of fmt.Print. + WarningDepth(depth int, args ...interface{}) + // ErrorDetph logs to ERROR log at the specified depth. Arguments are handled in the manner of fmt.Print. + ErrorDepth(depth int, args ...interface{}) + // FatalDepth logs to FATAL log at the specified depth. Arguments are handled in the manner of fmt.Print. + FatalDepth(depth int, args ...interface{}) +} diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go index c99e27ae5b6..e9919c0073b 100644 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go +++ b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go @@ -4,12 +4,8 @@ package grpc_health_v1 import ( - context "context" fmt "fmt" proto "github.com/golang/protobuf/proto" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" math "math" ) @@ -163,181 +159,3 @@ var fileDescriptor_e265fd9d4e077217 = []byte{ 0xd3, 0x20, 0x46, 0xe8, 0x85, 0x19, 0x26, 0xb1, 0x81, 0x93, 0x83, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x12, 0x7d, 0x96, 0xcb, 0x2d, 0x02, 0x00, 0x00, } - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// HealthClient is the client API for Health service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type HealthClient interface { - // If the requested service is unknown, the call will fail with status - // NOT_FOUND. - Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) - // Performs a watch for the serving status of the requested service. - // The server will immediately send back a message indicating the current - // serving status. It will then subsequently send a new message whenever - // the service's serving status changes. - // - // If the requested service is unknown when the call is received, the - // server will send a message setting the serving status to - // SERVICE_UNKNOWN but will *not* terminate the call. If at some - // future point, the serving status of the service becomes known, the - // server will send a new message with the service's serving status. - // - // If the call terminates with status UNIMPLEMENTED, then clients - // should assume this method is not supported and should not retry the - // call. If the call terminates with any other status (including OK), - // clients should retry the call with appropriate exponential backoff. - Watch(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (Health_WatchClient, error) -} - -type healthClient struct { - cc *grpc.ClientConn -} - -func NewHealthClient(cc *grpc.ClientConn) HealthClient { - return &healthClient{cc} -} - -func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) { - out := new(HealthCheckResponse) - err := c.cc.Invoke(ctx, "/grpc.health.v1.Health/Check", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *healthClient) Watch(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (Health_WatchClient, error) { - stream, err := c.cc.NewStream(ctx, &_Health_serviceDesc.Streams[0], "/grpc.health.v1.Health/Watch", opts...) - if err != nil { - return nil, err - } - x := &healthWatchClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Health_WatchClient interface { - Recv() (*HealthCheckResponse, error) - grpc.ClientStream -} - -type healthWatchClient struct { - grpc.ClientStream -} - -func (x *healthWatchClient) Recv() (*HealthCheckResponse, error) { - m := new(HealthCheckResponse) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// HealthServer is the server API for Health service. -type HealthServer interface { - // If the requested service is unknown, the call will fail with status - // NOT_FOUND. - Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) - // Performs a watch for the serving status of the requested service. - // The server will immediately send back a message indicating the current - // serving status. It will then subsequently send a new message whenever - // the service's serving status changes. - // - // If the requested service is unknown when the call is received, the - // server will send a message setting the serving status to - // SERVICE_UNKNOWN but will *not* terminate the call. If at some - // future point, the serving status of the service becomes known, the - // server will send a new message with the service's serving status. - // - // If the call terminates with status UNIMPLEMENTED, then clients - // should assume this method is not supported and should not retry the - // call. If the call terminates with any other status (including OK), - // clients should retry the call with appropriate exponential backoff. - Watch(*HealthCheckRequest, Health_WatchServer) error -} - -// UnimplementedHealthServer can be embedded to have forward compatible implementations. -type UnimplementedHealthServer struct { -} - -func (*UnimplementedHealthServer) Check(ctx context.Context, req *HealthCheckRequest) (*HealthCheckResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Check not implemented") -} -func (*UnimplementedHealthServer) Watch(req *HealthCheckRequest, srv Health_WatchServer) error { - return status.Errorf(codes.Unimplemented, "method Watch not implemented") -} - -func RegisterHealthServer(s *grpc.Server, srv HealthServer) { - s.RegisterService(&_Health_serviceDesc, srv) -} - -func _Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(HealthCheckRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(HealthServer).Check(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/grpc.health.v1.Health/Check", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(HealthServer).Check(ctx, req.(*HealthCheckRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Health_Watch_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(HealthCheckRequest) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(HealthServer).Watch(m, &healthWatchServer{stream}) -} - -type Health_WatchServer interface { - Send(*HealthCheckResponse) error - grpc.ServerStream -} - -type healthWatchServer struct { - grpc.ServerStream -} - -func (x *healthWatchServer) Send(m *HealthCheckResponse) error { - return x.ServerStream.SendMsg(m) -} - -var _Health_serviceDesc = grpc.ServiceDesc{ - ServiceName: "grpc.health.v1.Health", - HandlerType: (*HealthServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Check", - Handler: _Health_Check_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Watch", - Handler: _Health_Watch_Handler, - ServerStreams: true, - }, - }, - Metadata: "grpc/health/v1/health.proto", -} diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go new file mode 100644 index 00000000000..f87e3c92adb --- /dev/null +++ b/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go @@ -0,0 +1,186 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. + +package grpc_health_v1 + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion6 + +// HealthClient is the client API for Health service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type HealthClient interface { + // If the requested service is unknown, the call will fail with status + // NOT_FOUND. + Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) + // Performs a watch for the serving status of the requested service. + // The server will immediately send back a message indicating the current + // serving status. It will then subsequently send a new message whenever + // the service's serving status changes. + // + // If the requested service is unknown when the call is received, the + // server will send a message setting the serving status to + // SERVICE_UNKNOWN but will *not* terminate the call. If at some + // future point, the serving status of the service becomes known, the + // server will send a new message with the service's serving status. + // + // If the call terminates with status UNIMPLEMENTED, then clients + // should assume this method is not supported and should not retry the + // call. If the call terminates with any other status (including OK), + // clients should retry the call with appropriate exponential backoff. + Watch(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (Health_WatchClient, error) +} + +type healthClient struct { + cc grpc.ClientConnInterface +} + +func NewHealthClient(cc grpc.ClientConnInterface) HealthClient { + return &healthClient{cc} +} + +func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) { + out := new(HealthCheckResponse) + err := c.cc.Invoke(ctx, "/grpc.health.v1.Health/Check", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *healthClient) Watch(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (Health_WatchClient, error) { + stream, err := c.cc.NewStream(ctx, &_Health_serviceDesc.Streams[0], "/grpc.health.v1.Health/Watch", opts...) + if err != nil { + return nil, err + } + x := &healthWatchClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type Health_WatchClient interface { + Recv() (*HealthCheckResponse, error) + grpc.ClientStream +} + +type healthWatchClient struct { + grpc.ClientStream +} + +func (x *healthWatchClient) Recv() (*HealthCheckResponse, error) { + m := new(HealthCheckResponse) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// HealthServer is the server API for Health service. +// All implementations should embed UnimplementedHealthServer +// for forward compatibility +type HealthServer interface { + // If the requested service is unknown, the call will fail with status + // NOT_FOUND. + Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) + // Performs a watch for the serving status of the requested service. + // The server will immediately send back a message indicating the current + // serving status. It will then subsequently send a new message whenever + // the service's serving status changes. + // + // If the requested service is unknown when the call is received, the + // server will send a message setting the serving status to + // SERVICE_UNKNOWN but will *not* terminate the call. If at some + // future point, the serving status of the service becomes known, the + // server will send a new message with the service's serving status. + // + // If the call terminates with status UNIMPLEMENTED, then clients + // should assume this method is not supported and should not retry the + // call. If the call terminates with any other status (including OK), + // clients should retry the call with appropriate exponential backoff. + Watch(*HealthCheckRequest, Health_WatchServer) error +} + +// UnimplementedHealthServer should be embedded to have forward compatible implementations. +type UnimplementedHealthServer struct { +} + +func (*UnimplementedHealthServer) Check(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Check not implemented") +} +func (*UnimplementedHealthServer) Watch(*HealthCheckRequest, Health_WatchServer) error { + return status.Errorf(codes.Unimplemented, "method Watch not implemented") +} + +func RegisterHealthServer(s *grpc.Server, srv HealthServer) { + s.RegisterService(&_Health_serviceDesc, srv) +} + +func _Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(HealthCheckRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(HealthServer).Check(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/grpc.health.v1.Health/Check", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(HealthServer).Check(ctx, req.(*HealthCheckRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Health_Watch_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(HealthCheckRequest) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(HealthServer).Watch(m, &healthWatchServer{stream}) +} + +type Health_WatchServer interface { + Send(*HealthCheckResponse) error + grpc.ServerStream +} + +type healthWatchServer struct { + grpc.ServerStream +} + +func (x *healthWatchServer) Send(m *HealthCheckResponse) error { + return x.ServerStream.SendMsg(m) +} + +var _Health_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.health.v1.Health", + HandlerType: (*HealthServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Check", + Handler: _Health_Check_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "Watch", + Handler: _Health_Watch_Handler, + ServerStreams: true, + }, + }, + Metadata: "grpc/health/v1/health.proto", +} diff --git a/vendor/google.golang.org/grpc/health/regenerate.sh b/vendor/google.golang.org/grpc/health/regenerate.sh deleted file mode 100644 index b11eccb295b..00000000000 --- a/vendor/google.golang.org/grpc/health/regenerate.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash -# Copyright 2018 gRPC authors. -# -# 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. - -set -eux -o pipefail - -TMP=$(mktemp -d) - -function finish { - rm -rf "$TMP" -} -trap finish EXIT - -pushd "$TMP" -mkdir -p grpc/health/v1 -curl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/health/v1/health.proto > grpc/health/v1/health.proto - -protoc --go_out=plugins=grpc,paths=source_relative:. -I. grpc/health/v1/*.proto -popd -rm -f grpc_health_v1/*.pb.go -cp "$TMP"/grpc/health/v1/*.pb.go grpc_health_v1/ - diff --git a/vendor/google.golang.org/grpc/health/server.go b/vendor/google.golang.org/grpc/health/server.go index 2262607f882..ed2b3df70f4 100644 --- a/vendor/google.golang.org/grpc/health/server.go +++ b/vendor/google.golang.org/grpc/health/server.go @@ -16,8 +16,6 @@ * */ -//go:generate ./regenerate.sh - // Package health provides a service that exposes server's health and it must be // imported to enable support for client-side health checks. package health @@ -35,6 +33,7 @@ import ( // Server implements `service Health`. type Server struct { + healthgrpc.UnimplementedHealthServer mu sync.RWMutex // If shutdown is true, it's expected all serving status is NOT_SERVING, and // will stay in NOT_SERVING. diff --git a/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go b/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go index 8b105167491..b7a3dd8f918 100644 --- a/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go +++ b/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go @@ -25,6 +25,7 @@ import ( "os" "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/internal/grpcutil" ) // Logger is the global binary logger. It can be used to get binary logger for @@ -146,7 +147,7 @@ func (l *logger) setBlacklist(method string) error { // Each methodLogger returned by this method is a new instance. This is to // generate sequence id within the call. func (l *logger) getMethodLogger(methodName string) *MethodLogger { - s, m, err := parseMethodName(methodName) + s, m, err := grpcutil.ParseMethod(methodName) if err != nil { grpclog.Infof("binarylogging: failed to parse %q: %v", methodName, err) return nil diff --git a/vendor/google.golang.org/grpc/internal/binarylog/regenerate.sh b/vendor/google.golang.org/grpc/internal/binarylog/regenerate.sh deleted file mode 100644 index 113d40cbe16..00000000000 --- a/vendor/google.golang.org/grpc/internal/binarylog/regenerate.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash -# Copyright 2018 gRPC authors. -# -# 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. - -set -eux -o pipefail - -TMP=$(mktemp -d) - -function finish { - rm -rf "$TMP" -} -trap finish EXIT - -pushd "$TMP" -mkdir -p grpc/binarylog/grpc_binarylog_v1 -curl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/binlog/v1/binarylog.proto > grpc/binarylog/grpc_binarylog_v1/binarylog.proto - -protoc --go_out=plugins=grpc,paths=source_relative:. -I. grpc/binarylog/grpc_binarylog_v1/*.proto -popd -rm -f ./grpc_binarylog_v1/*.pb.go -cp "$TMP"/grpc/binarylog/grpc_binarylog_v1/*.pb.go ../../binarylog/grpc_binarylog_v1/ - diff --git a/vendor/google.golang.org/grpc/internal/binarylog/util.go b/vendor/google.golang.org/grpc/internal/binarylog/util.go deleted file mode 100644 index 15dc7803d8b..00000000000 --- a/vendor/google.golang.org/grpc/internal/binarylog/util.go +++ /dev/null @@ -1,41 +0,0 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * 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 binarylog - -import ( - "errors" - "strings" -) - -// parseMethodName splits service and method from the input. It expects format -// "/service/method". -// -// TODO: move to internal/grpcutil. -func parseMethodName(methodName string) (service, method string, _ error) { - if !strings.HasPrefix(methodName, "/") { - return "", "", errors.New("invalid method name: should start with /") - } - methodName = methodName[1:] - - pos := strings.LastIndex(methodName, "/") - if pos < 0 { - return "", "", errors.New("invalid method name: suffix /method is missing") - } - return methodName[:pos], methodName[pos+1:], nil -} diff --git a/vendor/google.golang.org/grpc/internal/channelz/funcs.go b/vendor/google.golang.org/grpc/internal/channelz/funcs.go index f0744f9937e..e4252e5be9f 100644 --- a/vendor/google.golang.org/grpc/internal/channelz/funcs.go +++ b/vendor/google.golang.org/grpc/internal/channelz/funcs.go @@ -30,7 +30,7 @@ import ( "sync/atomic" "time" - "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/internal/grpclog" ) const ( @@ -216,7 +216,7 @@ func RegisterChannel(c Channel, pid int64, ref string) int64 { // by pid). It returns the unique channelz tracking id assigned to this subchannel. func RegisterSubChannel(c Channel, pid int64, ref string) int64 { if pid == 0 { - grpclog.Error("a SubChannel's parent id cannot be 0") + grpclog.ErrorDepth(0, "a SubChannel's parent id cannot be 0") return 0 } id := idGen.genID() @@ -253,7 +253,7 @@ func RegisterServer(s Server, ref string) int64 { // this listen socket. func RegisterListenSocket(s Socket, pid int64, ref string) int64 { if pid == 0 { - grpclog.Error("a ListenSocket's parent id cannot be 0") + grpclog.ErrorDepth(0, "a ListenSocket's parent id cannot be 0") return 0 } id := idGen.genID() @@ -268,7 +268,7 @@ func RegisterListenSocket(s Socket, pid int64, ref string) int64 { // this normal socket. func RegisterNormalSocket(s Socket, pid int64, ref string) int64 { if pid == 0 { - grpclog.Error("a NormalSocket's parent id cannot be 0") + grpclog.ErrorDepth(0, "a NormalSocket's parent id cannot be 0") return 0 } id := idGen.genID() @@ -294,7 +294,19 @@ type TraceEventDesc struct { } // AddTraceEvent adds trace related to the entity with specified id, using the provided TraceEventDesc. -func AddTraceEvent(id int64, desc *TraceEventDesc) { +func AddTraceEvent(id int64, depth int, desc *TraceEventDesc) { + for d := desc; d != nil; d = d.Parent { + switch d.Severity { + case CtUNKNOWN: + grpclog.InfoDepth(depth+1, d.Desc) + case CtINFO: + grpclog.InfoDepth(depth+1, d.Desc) + case CtWarning: + grpclog.WarningDepth(depth+1, d.Desc) + case CtError: + grpclog.ErrorDepth(depth+1, d.Desc) + } + } if getMaxTraceEntry() == 0 { return } diff --git a/vendor/google.golang.org/grpc/internal/channelz/logging.go b/vendor/google.golang.org/grpc/internal/channelz/logging.go new file mode 100644 index 00000000000..59c7bedecd9 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/channelz/logging.go @@ -0,0 +1,100 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * 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 channelz + +import ( + "fmt" + + "google.golang.org/grpc/internal/grpclog" +) + +// Info logs through grpclog.Info and adds a trace event if channelz is on. +func Info(id int64, args ...interface{}) { + if IsOn() { + AddTraceEvent(id, 1, &TraceEventDesc{ + Desc: fmt.Sprint(args...), + Severity: CtINFO, + }) + } else { + grpclog.InfoDepth(1, args...) + } +} + +// Infof logs through grpclog.Infof and adds a trace event if channelz is on. +func Infof(id int64, format string, args ...interface{}) { + msg := fmt.Sprintf(format, args...) + if IsOn() { + AddTraceEvent(id, 1, &TraceEventDesc{ + Desc: msg, + Severity: CtINFO, + }) + } else { + grpclog.InfoDepth(1, msg) + } +} + +// Warning logs through grpclog.Warning and adds a trace event if channelz is on. +func Warning(id int64, args ...interface{}) { + if IsOn() { + AddTraceEvent(id, 1, &TraceEventDesc{ + Desc: fmt.Sprint(args...), + Severity: CtWarning, + }) + } else { + grpclog.WarningDepth(1, args...) + } +} + +// Warningf logs through grpclog.Warningf and adds a trace event if channelz is on. +func Warningf(id int64, format string, args ...interface{}) { + msg := fmt.Sprintf(format, args...) + if IsOn() { + AddTraceEvent(id, 1, &TraceEventDesc{ + Desc: msg, + Severity: CtWarning, + }) + } else { + grpclog.WarningDepth(1, msg) + } +} + +// Error logs through grpclog.Error and adds a trace event if channelz is on. +func Error(id int64, args ...interface{}) { + if IsOn() { + AddTraceEvent(id, 1, &TraceEventDesc{ + Desc: fmt.Sprint(args...), + Severity: CtError, + }) + } else { + grpclog.ErrorDepth(1, args...) + } +} + +// Errorf logs through grpclog.Errorf and adds a trace event if channelz is on. +func Errorf(id int64, format string, args ...interface{}) { + msg := fmt.Sprintf(format, args...) + if IsOn() { + AddTraceEvent(id, 1, &TraceEventDesc{ + Desc: msg, + Severity: CtError, + }) + } else { + grpclog.ErrorDepth(1, msg) + } +} diff --git a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go index ae6c8972fd7..73931a94bca 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go @@ -34,5 +34,5 @@ var ( // Retry is set if retry is explicitly enabled via "GRPC_GO_RETRY=on". Retry = strings.EqualFold(os.Getenv(retryStr), "on") // TXTErrIgnore is set if TXT errors should be ignored ("GRPC_GO_IGNORE_TXT_ERRORS" is not "false"). - TXTErrIgnore = !strings.EqualFold(os.Getenv(retryStr), "false") + TXTErrIgnore = !strings.EqualFold(os.Getenv(txtErrIgnoreStr), "false") ) diff --git a/vendor/google.golang.org/grpc/internal/grpclog/grpclog.go b/vendor/google.golang.org/grpc/internal/grpclog/grpclog.go new file mode 100644 index 00000000000..8c8e19fce1d --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/grpclog/grpclog.go @@ -0,0 +1,118 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * 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 grpclog (internal) defines depth logging for grpc. +package grpclog + +// Logger is the logger used for the non-depth log functions. +var Logger LoggerV2 + +// DepthLogger is the logger used for the depth log functions. +var DepthLogger DepthLoggerV2 + +// InfoDepth logs to the INFO log at the specified depth. +func InfoDepth(depth int, args ...interface{}) { + if DepthLogger != nil { + DepthLogger.InfoDepth(depth, args...) + } else { + Logger.Info(args...) + } +} + +// WarningDepth logs to the WARNING log at the specified depth. +func WarningDepth(depth int, args ...interface{}) { + if DepthLogger != nil { + DepthLogger.WarningDepth(depth, args...) + } else { + Logger.Warning(args...) + } +} + +// ErrorDepth logs to the ERROR log at the specified depth. +func ErrorDepth(depth int, args ...interface{}) { + if DepthLogger != nil { + DepthLogger.ErrorDepth(depth, args...) + } else { + Logger.Error(args...) + } +} + +// FatalDepth logs to the FATAL log at the specified depth. +func FatalDepth(depth int, args ...interface{}) { + if DepthLogger != nil { + DepthLogger.FatalDepth(depth, args...) + } else { + Logger.Fatal(args...) + } +} + +// LoggerV2 does underlying logging work for grpclog. +// This is a copy of the LoggerV2 defined in the external grpclog package. It +// is defined here to avoid a circular dependency. +type LoggerV2 interface { + // Info logs to INFO log. Arguments are handled in the manner of fmt.Print. + Info(args ...interface{}) + // Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println. + Infoln(args ...interface{}) + // Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf. + Infof(format string, args ...interface{}) + // Warning logs to WARNING log. Arguments are handled in the manner of fmt.Print. + Warning(args ...interface{}) + // Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println. + Warningln(args ...interface{}) + // Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf. + Warningf(format string, args ...interface{}) + // Error logs to ERROR log. Arguments are handled in the manner of fmt.Print. + Error(args ...interface{}) + // Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println. + Errorln(args ...interface{}) + // Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. + Errorf(format string, args ...interface{}) + // Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Print. + // gRPC ensures that all Fatal logs will exit with os.Exit(1). + // Implementations may also call os.Exit() with a non-zero exit code. + Fatal(args ...interface{}) + // Fatalln logs to ERROR log. Arguments are handled in the manner of fmt.Println. + // gRPC ensures that all Fatal logs will exit with os.Exit(1). + // Implementations may also call os.Exit() with a non-zero exit code. + Fatalln(args ...interface{}) + // Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. + // gRPC ensures that all Fatal logs will exit with os.Exit(1). + // Implementations may also call os.Exit() with a non-zero exit code. + Fatalf(format string, args ...interface{}) + // V reports whether verbosity level l is at least the requested verbose level. + V(l int) bool +} + +// DepthLoggerV2 logs at a specified call frame. If a LoggerV2 also implements +// DepthLoggerV2, the below functions will be called with the appropriate stack +// depth set for trivial functions the logger may ignore. +// This is a copy of the DepthLoggerV2 defined in the external grpclog package. +// It is defined here to avoid a circular dependency. +// +// This API is EXPERIMENTAL. +type DepthLoggerV2 interface { + // InfoDepth logs to INFO log at the specified depth. Arguments are handled in the manner of fmt.Print. + InfoDepth(depth int, args ...interface{}) + // WarningDepth logs to WARNING log at the specified depth. Arguments are handled in the manner of fmt.Print. + WarningDepth(depth int, args ...interface{}) + // ErrorDetph logs to ERROR log at the specified depth. Arguments are handled in the manner of fmt.Print. + ErrorDepth(depth int, args ...interface{}) + // FatalDepth logs to FATAL log at the specified depth. Arguments are handled in the manner of fmt.Print. + FatalDepth(depth int, args ...interface{}) +} diff --git a/vendor/google.golang.org/grpc/internal/grpclog/prefixLogger.go b/vendor/google.golang.org/grpc/internal/grpclog/prefixLogger.go new file mode 100644 index 00000000000..f6e0dc1da8d --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/grpclog/prefixLogger.go @@ -0,0 +1,63 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * 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 grpclog + +// PrefixLogger does logging with a prefix. +// +// Logging method on a nil logs without any prefix. +type PrefixLogger struct { + prefix string +} + +// Infof does info logging. +func (pl *PrefixLogger) Infof(format string, args ...interface{}) { + if pl != nil { + // Handle nil, so the tests can pass in a nil logger. + format = pl.prefix + format + } + Logger.Infof(format, args...) +} + +// Warningf does warning logging. +func (pl *PrefixLogger) Warningf(format string, args ...interface{}) { + if pl != nil { + format = pl.prefix + format + } + Logger.Warningf(format, args...) +} + +// Errorf does error logging. +func (pl *PrefixLogger) Errorf(format string, args ...interface{}) { + if pl != nil { + format = pl.prefix + format + } + Logger.Errorf(format, args...) +} + +// Debugf does info logging at verbose level 2. +func (pl *PrefixLogger) Debugf(format string, args ...interface{}) { + if Logger.V(2) { + pl.Infof(format, args...) + } +} + +// NewPrefixLogger creates a prefix logger with the given prefix. +func NewPrefixLogger(prefix string) *PrefixLogger { + return &PrefixLogger{prefix: prefix} +} diff --git a/vendor/google.golang.org/grpc/internal/grpcutil/method.go b/vendor/google.golang.org/grpc/internal/grpcutil/method.go new file mode 100644 index 00000000000..2c2ff7732a8 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/grpcutil/method.go @@ -0,0 +1,40 @@ +/* + * + * Copyright 2018 gRPC authors. + * + * 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 grpcutil + +import ( + "errors" + "strings" +) + +// ParseMethod splits service and method from the input. It expects format +// "/service/method". +// +func ParseMethod(methodName string) (service, method string, _ error) { + if !strings.HasPrefix(methodName, "/") { + return "", "", errors.New("invalid method name: should start with /") + } + methodName = methodName[1:] + + pos := strings.LastIndex(methodName, "/") + if pos < 0 { + return "", "", errors.New("invalid method name: suffix /method is missing") + } + return methodName[:pos], methodName[pos+1:], nil +} diff --git a/vendor/google.golang.org/grpc/internal/grpcutil/target.go b/vendor/google.golang.org/grpc/internal/grpcutil/target.go new file mode 100644 index 00000000000..80b33cdaf90 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/grpcutil/target.go @@ -0,0 +1,55 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * 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 grpcutil provides a bunch of utility functions to be used across the +// gRPC codebase. +package grpcutil + +import ( + "strings" + + "google.golang.org/grpc/resolver" +) + +// split2 returns the values from strings.SplitN(s, sep, 2). +// If sep is not found, it returns ("", "", false) instead. +func split2(s, sep string) (string, string, bool) { + spl := strings.SplitN(s, sep, 2) + if len(spl) < 2 { + return "", "", false + } + return spl[0], spl[1], true +} + +// ParseTarget splits target into a resolver.Target struct containing scheme, +// authority and endpoint. +// +// If target is not a valid scheme://authority/endpoint, it returns {Endpoint: +// target}. +func ParseTarget(target string) (ret resolver.Target) { + var ok bool + ret.Scheme, ret.Endpoint, ok = split2(target, "://") + if !ok { + return resolver.Target{Endpoint: target} + } + ret.Authority, ret.Endpoint, ok = split2(ret.Endpoint, "/") + if !ok { + return resolver.Target{Endpoint: target} + } + return ret +} diff --git a/vendor/google.golang.org/grpc/internal/internal.go b/vendor/google.golang.org/grpc/internal/internal.go index 0912f0bf4c3..818ca857998 100644 --- a/vendor/google.golang.org/grpc/internal/internal.go +++ b/vendor/google.golang.org/grpc/internal/internal.go @@ -25,6 +25,7 @@ import ( "time" "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/serviceconfig" ) var ( @@ -37,17 +38,20 @@ var ( // KeepaliveMinPingTime is the minimum ping interval. This must be 10s by // default, but tests may wish to set it lower for convenience. KeepaliveMinPingTime = 10 * time.Second - // StatusRawProto is exported by status/status.go. This func returns a - // pointer to the wrapped Status proto for a given status.Status without a - // call to proto.Clone(). The returned Status proto should not be mutated by - // the caller. - StatusRawProto interface{} // func (*status.Status) *spb.Status // NewRequestInfoContext creates a new context based on the argument context attaching // the passed in RequestInfo to the new context. NewRequestInfoContext interface{} // func(context.Context, credentials.RequestInfo) context.Context + // NewClientHandshakeInfoContext returns a copy of the input context with + // the passed in ClientHandshakeInfo struct added to it. + NewClientHandshakeInfoContext interface{} // func(context.Context, credentials.ClientHandshakeInfo) context.Context // ParseServiceConfigForTesting is for creating a fake // ClientConn for resolver testing only ParseServiceConfigForTesting interface{} // func(string) *serviceconfig.ParseResult + // EqualServiceConfigForTesting is for testing service config generation and + // parsing. Both a and b should be returned by ParseServiceConfigForTesting. + // This function compares the config without rawJSON stripped, in case the + // there's difference in white space. + EqualServiceConfigForTesting func(a, b serviceconfig.Config) bool ) // HealthChecker defines the signature of the client-side LB channel health checking function. diff --git a/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go b/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go index c368db62ea1..9d08dd8ab09 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go +++ b/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go @@ -32,6 +32,7 @@ import ( "sync" "time" + grpclbstate "google.golang.org/grpc/balancer/grpclb/state" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/envconfig" "google.golang.org/grpc/internal/grpcrand" @@ -251,7 +252,7 @@ func (d *dnsResolver) lookupSRV() ([]resolver.Address, error) { return nil, fmt.Errorf("dns: error parsing A record IP address %v", a) } addr := ip + ":" + strconv.Itoa(int(s.Port)) - newAddrs = append(newAddrs, resolver.Address{Addr: addr, Type: resolver.GRPCLB, ServerName: s.Target}) + newAddrs = append(newAddrs, resolver.Address{Addr: addr, ServerName: s.Target}) } } return newAddrs, nil @@ -326,13 +327,15 @@ func (d *dnsResolver) lookup() (*resolver.State, error) { if hostErr != nil && (srvErr != nil || len(srv) == 0) { return nil, hostErr } - state := &resolver.State{ - Addresses: append(addrs, srv...), + + state := resolver.State{Addresses: addrs} + if len(srv) > 0 { + state = grpclbstate.Set(state, &grpclbstate.State{BalancerAddresses: srv}) } if !d.disableServiceConfig { state.ServiceConfig = d.lookupTXT() } - return state, nil + return &state, nil } // formatIP returns ok = false if addr is not a valid textual representation of an IP address. diff --git a/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go b/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go new file mode 100644 index 00000000000..9b26414d40e --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go @@ -0,0 +1,90 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * 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 serviceconfig contains utility functions to parse service config. +package serviceconfig + +import ( + "encoding/json" + "fmt" + + "google.golang.org/grpc/balancer" + "google.golang.org/grpc/grpclog" + externalserviceconfig "google.golang.org/grpc/serviceconfig" +) + +// BalancerConfig is the balancer config part that service config's +// loadBalancingConfig fields can be unmarshalled to. It's a json unmarshaller. +// +// https://github.com/grpc/grpc-proto/blob/54713b1e8bc6ed2d4f25fb4dff527842150b91b2/grpc/service_config/service_config.proto#L247 +type BalancerConfig struct { + Name string + Config externalserviceconfig.LoadBalancingConfig +} + +type intermediateBalancerConfig []map[string]json.RawMessage + +// UnmarshalJSON implements json unmarshaller. +func (bc *BalancerConfig) UnmarshalJSON(b []byte) error { + var ir intermediateBalancerConfig + err := json.Unmarshal(b, &ir) + if err != nil { + return err + } + + for i, lbcfg := range ir { + if len(lbcfg) != 1 { + return fmt.Errorf("invalid loadBalancingConfig: entry %v does not contain exactly 1 policy/config pair: %q", i, lbcfg) + } + var ( + name string + jsonCfg json.RawMessage + ) + // Get the key:value pair from the map. + for name, jsonCfg = range lbcfg { + } + builder := balancer.Get(name) + if builder == nil { + // If the balancer is not registered, move on to the next config. + // This is not an error. + continue + } + bc.Name = name + + parser, ok := builder.(balancer.ConfigParser) + if !ok { + if string(jsonCfg) != "{}" { + grpclog.Warningf("non-empty balancer configuration %q, but balancer does not implement ParseConfig", string(jsonCfg)) + } + // Stop at this, though the builder doesn't support parsing config. + return nil + } + + cfg, err := parser.ParseConfig(jsonCfg) + if err != nil { + return fmt.Errorf("error parsing loadBalancingConfig for policy %q: %v", name, err) + } + bc.Config = cfg + return nil + } + // This is reached when the for loop iterates over all entries, but didn't + // return. This means we had a loadBalancingConfig slice but did not + // encounter a registered policy. The config is considered invalid in this + // case. + return fmt.Errorf("invalid loadBalancingConfig: no supported policies found") +} diff --git a/vendor/google.golang.org/grpc/internal/status/status.go b/vendor/google.golang.org/grpc/internal/status/status.go new file mode 100644 index 00000000000..710223b8ded --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/status/status.go @@ -0,0 +1,162 @@ +/* + * + * Copyright 2020 gRPC authors. + * + * 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 status implements errors returned by gRPC. These errors are +// serialized and transmitted on the wire between server and client, and allow +// for additional data to be transmitted via the Details field in the status +// proto. gRPC service handlers should return an error created by this +// package, and gRPC clients should expect a corresponding error to be +// returned from the RPC call. +// +// This package upholds the invariants that a non-nil error may not +// contain an OK code, and an OK code must result in a nil error. +package status + +import ( + "errors" + "fmt" + + "github.com/golang/protobuf/proto" + "github.com/golang/protobuf/ptypes" + spb "google.golang.org/genproto/googleapis/rpc/status" + "google.golang.org/grpc/codes" +) + +// Status represents an RPC status code, message, and details. It is immutable +// and should be created with New, Newf, or FromProto. +type Status struct { + s *spb.Status +} + +// New returns a Status representing c and msg. +func New(c codes.Code, msg string) *Status { + return &Status{s: &spb.Status{Code: int32(c), Message: msg}} +} + +// Newf returns New(c, fmt.Sprintf(format, a...)). +func Newf(c codes.Code, format string, a ...interface{}) *Status { + return New(c, fmt.Sprintf(format, a...)) +} + +// FromProto returns a Status representing s. +func FromProto(s *spb.Status) *Status { + return &Status{s: proto.Clone(s).(*spb.Status)} +} + +// Err returns an error representing c and msg. If c is OK, returns nil. +func Err(c codes.Code, msg string) error { + return New(c, msg).Err() +} + +// Errorf returns Error(c, fmt.Sprintf(format, a...)). +func Errorf(c codes.Code, format string, a ...interface{}) error { + return Err(c, fmt.Sprintf(format, a...)) +} + +// Code returns the status code contained in s. +func (s *Status) Code() codes.Code { + if s == nil || s.s == nil { + return codes.OK + } + return codes.Code(s.s.Code) +} + +// Message returns the message contained in s. +func (s *Status) Message() string { + if s == nil || s.s == nil { + return "" + } + return s.s.Message +} + +// Proto returns s's status as an spb.Status proto message. +func (s *Status) Proto() *spb.Status { + if s == nil { + return nil + } + return proto.Clone(s.s).(*spb.Status) +} + +// Err returns an immutable error representing s; returns nil if s.Code() is OK. +func (s *Status) Err() error { + if s.Code() == codes.OK { + return nil + } + return &Error{e: s.Proto()} +} + +// WithDetails returns a new status with the provided details messages appended to the status. +// If any errors are encountered, it returns nil and the first error encountered. +func (s *Status) WithDetails(details ...proto.Message) (*Status, error) { + if s.Code() == codes.OK { + return nil, errors.New("no error details for status with code OK") + } + // s.Code() != OK implies that s.Proto() != nil. + p := s.Proto() + for _, detail := range details { + any, err := ptypes.MarshalAny(detail) + if err != nil { + return nil, err + } + p.Details = append(p.Details, any) + } + return &Status{s: p}, nil +} + +// Details returns a slice of details messages attached to the status. +// If a detail cannot be decoded, the error is returned in place of the detail. +func (s *Status) Details() []interface{} { + if s == nil || s.s == nil { + return nil + } + details := make([]interface{}, 0, len(s.s.Details)) + for _, any := range s.s.Details { + detail := &ptypes.DynamicAny{} + if err := ptypes.UnmarshalAny(any, detail); err != nil { + details = append(details, err) + continue + } + details = append(details, detail.Message) + } + return details +} + +// Error wraps a pointer of a status proto. It implements error and Status, +// and a nil *Error should never be returned by this package. +type Error struct { + e *spb.Status +} + +func (e *Error) Error() string { + return fmt.Sprintf("rpc error: code = %s desc = %s", codes.Code(e.e.GetCode()), e.e.GetMessage()) +} + +// GRPCStatus returns the Status represented by se. +func (e *Error) GRPCStatus() *Status { + return FromProto(e.e) +} + +// Is implements future error.Is functionality. +// A Error is equivalent if the code and message are identical. +func (e *Error) Is(target error) bool { + tse, ok := target.(*Error) + if !ok { + return false + } + return proto.Equal(e.e, tse.e) +} diff --git a/vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go b/vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go index d3fd9dab333..ae0a9117e7b 100644 --- a/vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go +++ b/vendor/google.golang.org/grpc/internal/syscall/syscall_nonlinux.go @@ -18,6 +18,8 @@ * */ +// Package syscall provides functionalities that grpc uses to get low-level +// operating system stats/info. package syscall import ( diff --git a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go index ddee20b6bef..d4bb19c3bb5 100644 --- a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go +++ b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go @@ -857,38 +857,45 @@ func (l *loopyWriter) processData() (bool, error) { return false, nil } var ( - idx int buf []byte ) - if len(dataItem.h) != 0 { // data header has not been written out yet. - buf = dataItem.h - } else { - idx = 1 - buf = dataItem.d - } - size := http2MaxFrameLen - if len(buf) < size { - size = len(buf) - } + // Figure out the maximum size we can send + maxSize := http2MaxFrameLen if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota <= 0 { // stream-level flow control. str.state = waitingOnStreamQuota return false, nil - } else if strQuota < size { - size = strQuota + } else if maxSize > strQuota { + maxSize = strQuota + } + if maxSize > int(l.sendQuota) { // connection-level flow control. + maxSize = int(l.sendQuota) + } + // Compute how much of the header and data we can send within quota and max frame length + hSize := min(maxSize, len(dataItem.h)) + dSize := min(maxSize-hSize, len(dataItem.d)) + if hSize != 0 { + if dSize == 0 { + buf = dataItem.h + } else { + // We can add some data to grpc message header to distribute bytes more equally across frames. + // Copy on the stack to avoid generating garbage + var localBuf [http2MaxFrameLen]byte + copy(localBuf[:hSize], dataItem.h) + copy(localBuf[hSize:], dataItem.d[:dSize]) + buf = localBuf[:hSize+dSize] + } + } else { + buf = dataItem.d } - if l.sendQuota < uint32(size) { // connection-level flow control. - size = int(l.sendQuota) - } + size := hSize + dSize + // Now that outgoing flow controls are checked we can replenish str's write quota str.wq.replenish(size) var endStream bool // If this is the last data message on this stream and all of it can be written in this iteration. - if dataItem.endStream && size == len(buf) { - // buf contains either data or it contains header but data is empty. - if idx == 1 || len(dataItem.d) == 0 { - endStream = true - } + if dataItem.endStream && len(dataItem.h)+len(dataItem.d) <= size { + endStream = true } if dataItem.onEachWrite != nil { dataItem.onEachWrite() @@ -896,14 +903,10 @@ func (l *loopyWriter) processData() (bool, error) { if err := l.framer.fr.WriteData(dataItem.streamID, endStream, buf[:size]); err != nil { return false, err } - buf = buf[size:] str.bytesOutStanding += size l.sendQuota -= uint32(size) - if idx == 0 { - dataItem.h = buf - } else { - dataItem.d = buf - } + dataItem.h = dataItem.h[hSize:] + dataItem.d = dataItem.d[dSize:] if len(dataItem.h) == 0 && len(dataItem.d) == 0 { // All the data from that message was written out. str.itl.dequeue() @@ -924,3 +927,10 @@ func (l *loopyWriter) processData() (bool, error) { } return false, nil } + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/vendor/google.golang.org/grpc/internal/transport/handler_server.go b/vendor/google.golang.org/grpc/internal/transport/handler_server.go index c3c32dafe9e..fc44e976195 100644 --- a/vendor/google.golang.org/grpc/internal/transport/handler_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/handler_server.go @@ -112,11 +112,10 @@ func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats sta // at this point to be speaking over HTTP/2, so it's able to speak valid // gRPC. type serverHandlerTransport struct { - rw http.ResponseWriter - req *http.Request - timeoutSet bool - timeout time.Duration - didCommonHeaders bool + rw http.ResponseWriter + req *http.Request + timeoutSet bool + timeout time.Duration headerMD metadata.MD @@ -186,8 +185,11 @@ func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) erro ht.writeStatusMu.Lock() defer ht.writeStatusMu.Unlock() + headersWritten := s.updateHeaderSent() err := ht.do(func() { - ht.writeCommonHeaders(s) + if !headersWritten { + ht.writePendingHeaders(s) + } // And flush, in case no header or body has been sent yet. // This forces a separation of headers and trailers if this is the @@ -227,6 +229,8 @@ func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) erro if err == nil { // transport has not been closed if ht.stats != nil { + // Note: The trailer fields are compressed with hpack after this call returns. + // No WireLength field is set here. ht.stats.HandleRPC(s.Context(), &stats.OutTrailer{ Trailer: s.trailer.Copy(), }) @@ -236,14 +240,16 @@ func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) erro return err } +// writePendingHeaders sets common and custom headers on the first +// write call (Write, WriteHeader, or WriteStatus) +func (ht *serverHandlerTransport) writePendingHeaders(s *Stream) { + ht.writeCommonHeaders(s) + ht.writeCustomHeaders(s) +} + // writeCommonHeaders sets common headers on the first write // call (Write, WriteHeader, or WriteStatus). func (ht *serverHandlerTransport) writeCommonHeaders(s *Stream) { - if ht.didCommonHeaders { - return - } - ht.didCommonHeaders = true - h := ht.rw.Header() h["Date"] = nil // suppress Date to make tests happy; TODO: restore h.Set("Content-Type", ht.contentType) @@ -262,9 +268,30 @@ func (ht *serverHandlerTransport) writeCommonHeaders(s *Stream) { } } +// writeCustomHeaders sets custom headers set on the stream via SetHeader +// on the first write call (Write, WriteHeader, or WriteStatus). +func (ht *serverHandlerTransport) writeCustomHeaders(s *Stream) { + h := ht.rw.Header() + + s.hdrMu.Lock() + for k, vv := range s.header { + if isReservedHeader(k) { + continue + } + for _, v := range vv { + h.Add(k, encodeMetadataHeader(k, v)) + } + } + + s.hdrMu.Unlock() +} + func (ht *serverHandlerTransport) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { + headersWritten := s.updateHeaderSent() return ht.do(func() { - ht.writeCommonHeaders(s) + if !headersWritten { + ht.writePendingHeaders(s) + } ht.rw.Write(hdr) ht.rw.Write(data) ht.rw.(http.Flusher).Flush() @@ -272,27 +299,27 @@ func (ht *serverHandlerTransport) Write(s *Stream, hdr []byte, data []byte, opts } func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error { + if err := s.SetHeader(md); err != nil { + return err + } + + headersWritten := s.updateHeaderSent() err := ht.do(func() { - ht.writeCommonHeaders(s) - h := ht.rw.Header() - for k, vv := range md { - // Clients don't tolerate reading restricted headers after some non restricted ones were sent. - if isReservedHeader(k) { - continue - } - for _, v := range vv { - v = encodeMetadataHeader(k, v) - h.Add(k, v) - } + if !headersWritten { + ht.writePendingHeaders(s) } + ht.rw.WriteHeader(200) ht.rw.(http.Flusher).Flush() }) if err == nil { if ht.stats != nil { + // Note: The header fields are compressed with hpack after this call returns. + // No WireLength field is set here. ht.stats.HandleRPC(s.Context(), &stats.OutHeader{ - Header: md.Copy(), + Header: md.Copy(), + Compression: s.sendCompress, }) } } @@ -338,7 +365,7 @@ func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), trace Addr: ht.RemoteAddr(), } if req.TLS != nil { - pr.AuthInfo = credentials.TLSInfo{State: *req.TLS, CommonAuthInfo: credentials.CommonAuthInfo{credentials.PrivacyAndIntegrity}} + pr.AuthInfo = credentials.TLSInfo{State: *req.TLS, CommonAuthInfo: credentials.CommonAuthInfo{SecurityLevel: credentials.PrivacyAndIntegrity}} } ctx = metadata.NewIncomingContext(ctx, ht.headerMD) s.ctx = peer.NewContext(ctx, pr) diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_client.go b/vendor/google.golang.org/grpc/internal/transport/http2_client.go index 2d6feeb1be9..b43e21ffaf7 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_client.go @@ -41,6 +41,7 @@ import ( "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" + "google.golang.org/grpc/resolver" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" ) @@ -161,7 +162,7 @@ func isTemporary(err error) bool { // newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2 // and starts to receive messages on it. Non-nil error returns if construction // fails. -func newHTTP2Client(connectCtx, ctx context.Context, addr TargetInfo, opts ConnectOptions, onPrefaceReceipt func(), onGoAway func(GoAwayReason), onClose func()) (_ *http2Client, err error) { +func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts ConnectOptions, onPrefaceReceipt func(), onGoAway func(GoAwayReason), onClose func()) (_ *http2Client, err error) { scheme := "http" ctx, cancel := context.WithCancel(ctx) defer func() { @@ -214,12 +215,20 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr TargetInfo, opts Conne } } if transportCreds != nil { - scheme = "https" - conn, authInfo, err = transportCreds.ClientHandshake(connectCtx, addr.Authority, conn) + // gRPC, resolver, balancer etc. can specify arbitrary data in the + // Attributes field of resolver.Address, which is shoved into connectCtx + // and passed to the credential handshaker. This makes it possible for + // address specific arbitrary data to reach the credential handshaker. + contextWithHandshakeInfo := internal.NewClientHandshakeInfoContext.(func(context.Context, credentials.ClientHandshakeInfo) context.Context) + connectCtx = contextWithHandshakeInfo(connectCtx, credentials.ClientHandshakeInfo{Attributes: addr.Attributes}) + conn, authInfo, err = transportCreds.ClientHandshake(connectCtx, addr.ServerName, conn) if err != nil { return nil, connectionErrorf(isTemporary(err), err, "transport: authentication handshake failed: %v", err) } isSecure = true + if transportCreds.Info().SecurityProtocol == "tls" { + scheme = "https" + } } dynamicWindow := true icwz := int32(initialWindowSize) @@ -554,13 +563,26 @@ func (t *http2Client) getCallAuthData(ctx context.Context, audience string, call return callAuthData, nil } +// PerformedIOError wraps an error to indicate IO may have been performed +// before the error occurred. +type PerformedIOError struct { + Err error +} + +// Error implements error. +func (p PerformedIOError) Error() string { + return p.Err.Error() +} + // NewStream creates a stream and registers it into the transport as "active" // streams. func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) { ctx = peer.NewContext(ctx, t.getPeer()) headerFields, err := t.createHeaderFields(ctx, callHdr) if err != nil { - return nil, err + // We may have performed I/O in the per-RPC creds callback, so do not + // allow transparent retry. + return nil, PerformedIOError{err} } s := t.newStream(ctx, callHdr) cleanup := func(err error) { @@ -680,14 +702,21 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Strea } } if t.statsHandler != nil { - header, _, _ := metadata.FromOutgoingContextRaw(ctx) + header, ok := metadata.FromOutgoingContext(ctx) + if ok { + header.Set("user-agent", t.userAgent) + } else { + header = metadata.Pairs("user-agent", t.userAgent) + } + // Note: The header fields are compressed with hpack after this call returns. + // No WireLength field is set here. outHeader := &stats.OutHeader{ Client: true, FullMethod: callHdr.Method, RemoteAddr: t.remoteAddr, LocalAddr: t.localAddr, Compression: callHdr.SendCompress, - Header: header.Copy(), + Header: header, } t.statsHandler.HandleRPC(s.ctx, outHeader) } @@ -847,18 +876,10 @@ func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) e df := &dataFrame{ streamID: s.id, endStream: opts.Last, + h: hdr, + d: data, } - if hdr != nil || data != nil { // If it's not an empty data frame. - // Add some data to grpc message header so that we can equally - // distribute bytes across frames. - emptyLen := http2MaxFrameLen - len(hdr) - if emptyLen > len(data) { - emptyLen = len(data) - } - hdr = append(hdr, data[:emptyLen]...) - data = data[emptyLen:] - df.h, df.d = hdr, data - // TODO(mmukhi): The above logic in this if can be moved to loopyWriter's data handler. + if hdr != nil || data != nil { // If it's not an empty data frame, check quota. if err := s.wq.get(int32(len(hdr) + len(data))); err != nil { return err } @@ -1188,9 +1209,10 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { if t.statsHandler != nil { if isHeader { inHeader := &stats.InHeader{ - Client: true, - WireLength: int(frame.Header().Length), - Header: s.header.Copy(), + Client: true, + WireLength: int(frame.Header().Length), + Header: s.header.Copy(), + Compression: s.recvCompress, } t.statsHandler.HandleRPC(s.ctx, inHeader) } else { diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_server.go b/vendor/google.golang.org/grpc/internal/transport/http2_server.go index 8b04b0392a0..e8c75732128 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_server.go @@ -35,11 +35,9 @@ import ( "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" - spb "google.golang.org/genproto/googleapis/rpc/status" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcrand" "google.golang.org/grpc/keepalive" @@ -57,9 +55,6 @@ var ( // ErrHeaderListSizeLimitViolation indicates that the header list size is larger // than the limit set by peer. ErrHeaderListSizeLimitViolation = errors.New("transport: trying to send header list size larger than the limit set by peer") - // statusRawProto is a function to get to the raw status proto wrapped in a - // status.Status without a proto.Clone(). - statusRawProto = internal.StatusRawProto.(func(*status.Status) *spb.Status) ) // serverConnectionCounter counts the number of connections a server has seen @@ -813,10 +808,11 @@ func (t *http2Server) writeHeaderLocked(s *Stream) error { return ErrHeaderListSizeLimitViolation } if t.stats != nil { - // Note: WireLength is not set in outHeader. - // TODO(mmukhi): Revisit this later, if needed. + // Note: Headers are compressed with hpack after this call returns. + // No WireLength field is set here. outHeader := &stats.OutHeader{ - Header: s.header.Copy(), + Header: s.header.Copy(), + Compression: s.sendCompress, } t.stats.HandleRPC(s.Context(), outHeader) } @@ -849,7 +845,7 @@ func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-status", Value: strconv.Itoa(int(st.Code()))}) headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-message", Value: encodeGrpcMessage(st.Message())}) - if p := statusRawProto(st); p != nil && len(p.Details) > 0 { + if p := st.Proto(); p != nil && len(p.Details) > 0 { stBytes, err := proto.Marshal(p) if err != nil { // TODO: return error instead, when callers are able to handle it. @@ -880,6 +876,8 @@ func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error { rst := s.getState() == streamActive t.finishStream(s, rst, http2.ErrCodeNo, trailingHeader, true) if t.stats != nil { + // Note: The trailer fields are compressed with hpack after this call returns. + // No WireLength field is set here. t.stats.HandleRPC(s.Context(), &stats.OutTrailer{ Trailer: s.trailer.Copy(), }) @@ -911,13 +909,6 @@ func (t *http2Server) Write(s *Stream, hdr []byte, data []byte, opts *Options) e return ContextErr(s.ctx.Err()) } } - // Add some data to header frame so that we can equally distribute bytes across frames. - emptyLen := http2MaxFrameLen - len(hdr) - if emptyLen > len(data) { - emptyLen = len(data) - } - hdr = append(hdr, data[:emptyLen]...) - data = data[emptyLen:] df := &dataFrame{ streamID: s.id, h: hdr, diff --git a/vendor/google.golang.org/grpc/internal/transport/transport.go b/vendor/google.golang.org/grpc/internal/transport/transport.go index a30da9eb324..1ffd96ff43d 100644 --- a/vendor/google.golang.org/grpc/internal/transport/transport.go +++ b/vendor/google.golang.org/grpc/internal/transport/transport.go @@ -35,6 +35,7 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" + "google.golang.org/grpc/resolver" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" "google.golang.org/grpc/tap" @@ -568,17 +569,10 @@ type ConnectOptions struct { MaxHeaderListSize *uint32 } -// TargetInfo contains the information of the target such as network address and metadata. -type TargetInfo struct { - Addr string - Metadata interface{} - Authority string -} - // NewClientTransport establishes the transport with the required ConnectOptions // and returns it to the caller. -func NewClientTransport(connectCtx, ctx context.Context, target TargetInfo, opts ConnectOptions, onPrefaceReceipt func(), onGoAway func(GoAwayReason), onClose func()) (ClientTransport, error) { - return newHTTP2Client(connectCtx, ctx, target, opts, onPrefaceReceipt, onGoAway, onClose) +func NewClientTransport(connectCtx, ctx context.Context, addr resolver.Address, opts ConnectOptions, onPrefaceReceipt func(), onGoAway func(GoAwayReason), onClose func()) (ClientTransport, error) { + return newHTTP2Client(connectCtx, ctx, addr, opts, onPrefaceReceipt, onGoAway, onClose) } // Options provides additional hints and information for message diff --git a/vendor/google.golang.org/grpc/naming/dns_resolver.go b/vendor/google.golang.org/grpc/naming/dns_resolver.go deleted file mode 100644 index c9f79dc5336..00000000000 --- a/vendor/google.golang.org/grpc/naming/dns_resolver.go +++ /dev/null @@ -1,293 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * 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 naming - -import ( - "context" - "errors" - "fmt" - "net" - "strconv" - "time" - - "google.golang.org/grpc/grpclog" -) - -const ( - defaultPort = "443" - defaultFreq = time.Minute * 30 -) - -var ( - errMissingAddr = errors.New("missing address") - errWatcherClose = errors.New("watcher has been closed") - - lookupHost = net.DefaultResolver.LookupHost - lookupSRV = net.DefaultResolver.LookupSRV -) - -// NewDNSResolverWithFreq creates a DNS Resolver that can resolve DNS names, and -// create watchers that poll the DNS server using the frequency set by freq. -func NewDNSResolverWithFreq(freq time.Duration) (Resolver, error) { - return &dnsResolver{freq: freq}, nil -} - -// NewDNSResolver creates a DNS Resolver that can resolve DNS names, and create -// watchers that poll the DNS server using the default frequency defined by defaultFreq. -func NewDNSResolver() (Resolver, error) { - return NewDNSResolverWithFreq(defaultFreq) -} - -// dnsResolver handles name resolution for names following the DNS scheme -type dnsResolver struct { - // frequency of polling the DNS server that the watchers created by this resolver will use. - freq time.Duration -} - -// formatIP returns ok = false if addr is not a valid textual representation of an IP address. -// If addr is an IPv4 address, return the addr and ok = true. -// If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true. -func formatIP(addr string) (addrIP string, ok bool) { - ip := net.ParseIP(addr) - if ip == nil { - return "", false - } - if ip.To4() != nil { - return addr, true - } - return "[" + addr + "]", true -} - -// parseTarget takes the user input target string, returns formatted host and port info. -// If target doesn't specify a port, set the port to be the defaultPort. -// If target is in IPv6 format and host-name is enclosed in square brackets, brackets -// are stripped when setting the host. -// examples: -// target: "www.google.com" returns host: "www.google.com", port: "443" -// target: "ipv4-host:80" returns host: "ipv4-host", port: "80" -// target: "[ipv6-host]" returns host: "ipv6-host", port: "443" -// target: ":80" returns host: "localhost", port: "80" -// target: ":" returns host: "localhost", port: "443" -func parseTarget(target string) (host, port string, err error) { - if target == "" { - return "", "", errMissingAddr - } - - if ip := net.ParseIP(target); ip != nil { - // target is an IPv4 or IPv6(without brackets) address - return target, defaultPort, nil - } - if host, port, err := net.SplitHostPort(target); err == nil { - // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port - if host == "" { - // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed. - host = "localhost" - } - if port == "" { - // If the port field is empty(target ends with colon), e.g. "[::1]:", defaultPort is used. - port = defaultPort - } - return host, port, nil - } - if host, port, err := net.SplitHostPort(target + ":" + defaultPort); err == nil { - // target doesn't have port - return host, port, nil - } - return "", "", fmt.Errorf("invalid target address %v", target) -} - -// Resolve creates a watcher that watches the name resolution of the target. -func (r *dnsResolver) Resolve(target string) (Watcher, error) { - host, port, err := parseTarget(target) - if err != nil { - return nil, err - } - - if net.ParseIP(host) != nil { - ipWatcher := &ipWatcher{ - updateChan: make(chan *Update, 1), - } - host, _ = formatIP(host) - ipWatcher.updateChan <- &Update{Op: Add, Addr: host + ":" + port} - return ipWatcher, nil - } - - ctx, cancel := context.WithCancel(context.Background()) - return &dnsWatcher{ - r: r, - host: host, - port: port, - ctx: ctx, - cancel: cancel, - t: time.NewTimer(0), - }, nil -} - -// dnsWatcher watches for the name resolution update for a specific target -type dnsWatcher struct { - r *dnsResolver - host string - port string - // The latest resolved address set - curAddrs map[string]*Update - ctx context.Context - cancel context.CancelFunc - t *time.Timer -} - -// ipWatcher watches for the name resolution update for an IP address. -type ipWatcher struct { - updateChan chan *Update -} - -// Next returns the address resolution Update for the target. For IP address, -// the resolution is itself, thus polling name server is unnecessary. Therefore, -// Next() will return an Update the first time it is called, and will be blocked -// for all following calls as no Update exists until watcher is closed. -func (i *ipWatcher) Next() ([]*Update, error) { - u, ok := <-i.updateChan - if !ok { - return nil, errWatcherClose - } - return []*Update{u}, nil -} - -// Close closes the ipWatcher. -func (i *ipWatcher) Close() { - close(i.updateChan) -} - -// AddressType indicates the address type returned by name resolution. -type AddressType uint8 - -const ( - // Backend indicates the server is a backend server. - Backend AddressType = iota - // GRPCLB indicates the server is a grpclb load balancer. - GRPCLB -) - -// AddrMetadataGRPCLB contains the information the name resolver for grpclb should provide. The -// name resolver used by the grpclb balancer is required to provide this type of metadata in -// its address updates. -type AddrMetadataGRPCLB struct { - // AddrType is the type of server (grpc load balancer or backend). - AddrType AddressType - // ServerName is the name of the grpc load balancer. Used for authentication. - ServerName string -} - -// compileUpdate compares the old resolved addresses and newly resolved addresses, -// and generates an update list -func (w *dnsWatcher) compileUpdate(newAddrs map[string]*Update) []*Update { - var res []*Update - for a, u := range w.curAddrs { - if _, ok := newAddrs[a]; !ok { - u.Op = Delete - res = append(res, u) - } - } - for a, u := range newAddrs { - if _, ok := w.curAddrs[a]; !ok { - res = append(res, u) - } - } - return res -} - -func (w *dnsWatcher) lookupSRV() map[string]*Update { - newAddrs := make(map[string]*Update) - _, srvs, err := lookupSRV(w.ctx, "grpclb", "tcp", w.host) - if err != nil { - grpclog.Infof("grpc: failed dns SRV record lookup due to %v.\n", err) - return nil - } - for _, s := range srvs { - lbAddrs, err := lookupHost(w.ctx, s.Target) - if err != nil { - grpclog.Warningf("grpc: failed load balancer address dns lookup due to %v.\n", err) - continue - } - for _, a := range lbAddrs { - a, ok := formatIP(a) - if !ok { - grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) - continue - } - addr := a + ":" + strconv.Itoa(int(s.Port)) - newAddrs[addr] = &Update{Addr: addr, - Metadata: AddrMetadataGRPCLB{AddrType: GRPCLB, ServerName: s.Target}} - } - } - return newAddrs -} - -func (w *dnsWatcher) lookupHost() map[string]*Update { - newAddrs := make(map[string]*Update) - addrs, err := lookupHost(w.ctx, w.host) - if err != nil { - grpclog.Warningf("grpc: failed dns A record lookup due to %v.\n", err) - return nil - } - for _, a := range addrs { - a, ok := formatIP(a) - if !ok { - grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) - continue - } - addr := a + ":" + w.port - newAddrs[addr] = &Update{Addr: addr} - } - return newAddrs -} - -func (w *dnsWatcher) lookup() []*Update { - newAddrs := w.lookupSRV() - if newAddrs == nil { - // If failed to get any balancer address (either no corresponding SRV for the - // target, or caused by failure during resolution/parsing of the balancer target), - // return any A record info available. - newAddrs = w.lookupHost() - } - result := w.compileUpdate(newAddrs) - w.curAddrs = newAddrs - return result -} - -// Next returns the resolved address update(delta) for the target. If there's no -// change, it will sleep for 30 mins and try to resolve again after that. -func (w *dnsWatcher) Next() ([]*Update, error) { - for { - select { - case <-w.ctx.Done(): - return nil, errWatcherClose - case <-w.t.C: - } - result := w.lookup() - // Next lookup should happen after an interval defined by w.r.freq. - w.t.Reset(w.r.freq) - if len(result) > 0 { - return result, nil - } - } -} - -func (w *dnsWatcher) Close() { - w.cancel() -} diff --git a/vendor/google.golang.org/grpc/naming/naming.go b/vendor/google.golang.org/grpc/naming/naming.go deleted file mode 100644 index f4c1c8b6894..00000000000 --- a/vendor/google.golang.org/grpc/naming/naming.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - * - * Copyright 2014 gRPC authors. - * - * 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 naming defines the naming API and related data structures for gRPC. -// -// This package is deprecated: please use package resolver instead. -package naming - -// Operation defines the corresponding operations for a name resolution change. -// -// Deprecated: please use package resolver. -type Operation uint8 - -const ( - // Add indicates a new address is added. - Add Operation = iota - // Delete indicates an existing address is deleted. - Delete -) - -// Update defines a name resolution update. Notice that it is not valid having both -// empty string Addr and nil Metadata in an Update. -// -// Deprecated: please use package resolver. -type Update struct { - // Op indicates the operation of the update. - Op Operation - // Addr is the updated address. It is empty string if there is no address update. - Addr string - // Metadata is the updated metadata. It is nil if there is no metadata update. - // Metadata is not required for a custom naming implementation. - Metadata interface{} -} - -// Resolver creates a Watcher for a target to track its resolution changes. -// -// Deprecated: please use package resolver. -type Resolver interface { - // Resolve creates a Watcher for target. - Resolve(target string) (Watcher, error) -} - -// Watcher watches for the updates on the specified target. -// -// Deprecated: please use package resolver. -type Watcher interface { - // Next blocks until an update or error happens. It may return one or more - // updates. The first call should get the full set of the results. It should - // return an error if and only if Watcher cannot recover. - Next() ([]*Update, error) - // Close closes the Watcher. - Close() -} diff --git a/vendor/google.golang.org/grpc/picker_wrapper.go b/vendor/google.golang.org/grpc/picker_wrapper.go index 00447894f07..7f3edaaedc6 100644 --- a/vendor/google.golang.org/grpc/picker_wrapper.go +++ b/vendor/google.golang.org/grpc/picker_wrapper.go @@ -20,7 +20,6 @@ package grpc import ( "context" - "fmt" "io" "sync" @@ -32,68 +31,21 @@ import ( "google.golang.org/grpc/status" ) -// v2PickerWrapper wraps a balancer.Picker while providing the -// balancer.V2Picker API. It requires a pickerWrapper to generate errors -// including the latest connectionError. To be deleted when balancer.Picker is -// updated to the balancer.V2Picker API. -type v2PickerWrapper struct { - picker balancer.Picker - connErr *connErr -} - -func (v *v2PickerWrapper) Pick(info balancer.PickInfo) (balancer.PickResult, error) { - sc, done, err := v.picker.Pick(info.Ctx, info) - if err != nil { - if err == balancer.ErrTransientFailure { - return balancer.PickResult{}, balancer.TransientFailureError(fmt.Errorf("%v, latest connection error: %v", err, v.connErr.connectionError())) - } - return balancer.PickResult{}, err - } - return balancer.PickResult{SubConn: sc, Done: done}, nil -} - // pickerWrapper is a wrapper of balancer.Picker. It blocks on certain pick // actions and unblock when there's a picker update. type pickerWrapper struct { mu sync.Mutex done bool blockingCh chan struct{} - picker balancer.V2Picker - - // The latest connection error. TODO: remove when V1 picker is deprecated; - // balancer should be responsible for providing the error. - *connErr -} - -type connErr struct { - mu sync.Mutex - err error -} - -func (c *connErr) updateConnectionError(err error) { - c.mu.Lock() - c.err = err - c.mu.Unlock() -} - -func (c *connErr) connectionError() error { - c.mu.Lock() - err := c.err - c.mu.Unlock() - return err + picker balancer.Picker } func newPickerWrapper() *pickerWrapper { - return &pickerWrapper{blockingCh: make(chan struct{}), connErr: &connErr{}} + return &pickerWrapper{blockingCh: make(chan struct{})} } // updatePicker is called by UpdateBalancerState. It unblocks all blocked pick. func (pw *pickerWrapper) updatePicker(p balancer.Picker) { - pw.updatePickerV2(&v2PickerWrapper{picker: p, connErr: pw.connErr}) -} - -// updatePicker is called by UpdateBalancerState. It unblocks all blocked pick. -func (pw *pickerWrapper) updatePickerV2(p balancer.V2Picker) { pw.mu.Lock() if pw.done { pw.mu.Unlock() @@ -154,8 +106,6 @@ func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer. var errStr string if lastPickErr != nil { errStr = "latest balancer error: " + lastPickErr.Error() - } else if connectionErr := pw.connectionError(); connectionErr != nil { - errStr = "latest connection error: " + connectionErr.Error() } else { errStr = ctx.Err().Error() } @@ -180,18 +130,17 @@ func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer. if err == balancer.ErrNoSubConnAvailable { continue } - if tfe, ok := err.(interface{ IsTransientFailure() bool }); ok && tfe.IsTransientFailure() { - if !failfast { - lastPickErr = err - continue - } - return nil, nil, status.Error(codes.Unavailable, err.Error()) - } if _, ok := status.FromError(err); ok { + // Status error: end the RPC unconditionally with this status. return nil, nil, err } - // err is some other error. - return nil, nil, status.Error(codes.Unknown, err.Error()) + // For all other errors, wait for ready RPCs should block and other + // RPCs should fail with unavailable. + if !failfast { + lastPickErr = err + continue + } + return nil, nil, status.Error(codes.Unavailable, err.Error()) } acw, ok := pickResult.SubConn.(*acBalancerWrapper) diff --git a/vendor/google.golang.org/grpc/pickfirst.go b/vendor/google.golang.org/grpc/pickfirst.go index c43dac9ad84..4b7340ad3ec 100644 --- a/vendor/google.golang.org/grpc/pickfirst.go +++ b/vendor/google.golang.org/grpc/pickfirst.go @@ -20,13 +20,11 @@ package grpc import ( "errors" + "fmt" "google.golang.org/grpc/balancer" - "google.golang.org/grpc/codes" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/status" ) // PickFirstBalancerName is the name of the pick_first balancer. @@ -52,27 +50,13 @@ type pickfirstBalancer struct { sc balancer.SubConn } -var _ balancer.V2Balancer = &pickfirstBalancer{} // Assert we implement v2 - -func (b *pickfirstBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { - if err != nil { - b.ResolverError(err) - return - } - b.UpdateClientConnState(balancer.ClientConnState{ResolverState: resolver.State{Addresses: addrs}}) // Ignore error -} - -func (b *pickfirstBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - b.UpdateSubConnState(sc, balancer.SubConnState{ConnectivityState: s}) -} - func (b *pickfirstBalancer) ResolverError(err error) { switch b.state { case connectivity.TransientFailure, connectivity.Idle, connectivity.Connecting: // Set a failing picker if we don't have a good picker. b.cc.UpdateState(balancer.State{ConnectivityState: connectivity.TransientFailure, - Picker: &picker{err: status.Errorf(codes.Unavailable, "name resolver error: %v", err)}}, - ) + Picker: &picker{err: fmt.Errorf("name resolver error: %v", err)}, + }) } if grpclog.V(2) { grpclog.Infof("pickfirstBalancer: ResolverError called with error %v", err) @@ -93,8 +77,8 @@ func (b *pickfirstBalancer) UpdateClientConnState(cs balancer.ClientConnState) e } b.state = connectivity.TransientFailure b.cc.UpdateState(balancer.State{ConnectivityState: connectivity.TransientFailure, - Picker: &picker{err: status.Errorf(codes.Unavailable, "error creating connection: %v", err)}}, - ) + Picker: &picker{err: fmt.Errorf("error creating connection: %v", err)}, + }) return balancer.ErrBadResolverState } b.state = connectivity.Idle @@ -109,7 +93,7 @@ func (b *pickfirstBalancer) UpdateClientConnState(cs balancer.ClientConnState) e func (b *pickfirstBalancer) UpdateSubConnState(sc balancer.SubConn, s balancer.SubConnState) { if grpclog.V(2) { - grpclog.Infof("pickfirstBalancer: HandleSubConnStateChange: %p, %v", sc, s) + grpclog.Infof("pickfirstBalancer: UpdateSubConnState: %p, %v", sc, s) } if b.sc != sc { if grpclog.V(2) { @@ -129,15 +113,9 @@ func (b *pickfirstBalancer) UpdateSubConnState(sc balancer.SubConn, s balancer.S case connectivity.Connecting: b.cc.UpdateState(balancer.State{ConnectivityState: s.ConnectivityState, Picker: &picker{err: balancer.ErrNoSubConnAvailable}}) case connectivity.TransientFailure: - err := balancer.ErrTransientFailure - // TODO: this can be unconditional after the V1 API is removed, as - // SubConnState will always contain a connection error. - if s.ConnectionError != nil { - err = balancer.TransientFailureError(s.ConnectionError) - } b.cc.UpdateState(balancer.State{ ConnectivityState: s.ConnectivityState, - Picker: &picker{err: err}, + Picker: &picker{err: s.ConnectionError}, }) } } diff --git a/vendor/google.golang.org/grpc/reflection/README.md b/vendor/google.golang.org/grpc/reflection/README.md new file mode 100644 index 00000000000..04b6371afcb --- /dev/null +++ b/vendor/google.golang.org/grpc/reflection/README.md @@ -0,0 +1,18 @@ +# Reflection + +Package reflection implements server reflection service. + +The service implemented is defined in: https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1alpha/reflection.proto. + +To register server reflection on a gRPC server: +```go +import "google.golang.org/grpc/reflection" + +s := grpc.NewServer() +pb.RegisterYourOwnServer(s, &server{}) + +// Register reflection service on gRPC server. +reflection.Register(s) + +s.Serve(lis) +``` diff --git a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go new file mode 100644 index 00000000000..382612d520d --- /dev/null +++ b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.pb.go @@ -0,0 +1,634 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: reflection/grpc_reflection_v1alpha/reflection.proto + +package grpc_reflection_v1alpha + +import ( + fmt "fmt" + proto "github.com/golang/protobuf/proto" + math "math" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package + +// The message sent by the client when calling ServerReflectionInfo method. +type ServerReflectionRequest struct { + Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"` + // To use reflection service, the client should set one of the following + // fields in message_request. The server distinguishes requests by their + // defined field and then handles them using corresponding methods. + // + // Types that are valid to be assigned to MessageRequest: + // *ServerReflectionRequest_FileByFilename + // *ServerReflectionRequest_FileContainingSymbol + // *ServerReflectionRequest_FileContainingExtension + // *ServerReflectionRequest_AllExtensionNumbersOfType + // *ServerReflectionRequest_ListServices + MessageRequest isServerReflectionRequest_MessageRequest `protobuf_oneof:"message_request"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ServerReflectionRequest) Reset() { *m = ServerReflectionRequest{} } +func (m *ServerReflectionRequest) String() string { return proto.CompactTextString(m) } +func (*ServerReflectionRequest) ProtoMessage() {} +func (*ServerReflectionRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_e8cf9f2921ad6c95, []int{0} +} + +func (m *ServerReflectionRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ServerReflectionRequest.Unmarshal(m, b) +} +func (m *ServerReflectionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ServerReflectionRequest.Marshal(b, m, deterministic) +} +func (m *ServerReflectionRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_ServerReflectionRequest.Merge(m, src) +} +func (m *ServerReflectionRequest) XXX_Size() int { + return xxx_messageInfo_ServerReflectionRequest.Size(m) +} +func (m *ServerReflectionRequest) XXX_DiscardUnknown() { + xxx_messageInfo_ServerReflectionRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_ServerReflectionRequest proto.InternalMessageInfo + +func (m *ServerReflectionRequest) GetHost() string { + if m != nil { + return m.Host + } + return "" +} + +type isServerReflectionRequest_MessageRequest interface { + isServerReflectionRequest_MessageRequest() +} + +type ServerReflectionRequest_FileByFilename struct { + FileByFilename string `protobuf:"bytes,3,opt,name=file_by_filename,json=fileByFilename,proto3,oneof"` +} + +type ServerReflectionRequest_FileContainingSymbol struct { + FileContainingSymbol string `protobuf:"bytes,4,opt,name=file_containing_symbol,json=fileContainingSymbol,proto3,oneof"` +} + +type ServerReflectionRequest_FileContainingExtension struct { + FileContainingExtension *ExtensionRequest `protobuf:"bytes,5,opt,name=file_containing_extension,json=fileContainingExtension,proto3,oneof"` +} + +type ServerReflectionRequest_AllExtensionNumbersOfType struct { + AllExtensionNumbersOfType string `protobuf:"bytes,6,opt,name=all_extension_numbers_of_type,json=allExtensionNumbersOfType,proto3,oneof"` +} + +type ServerReflectionRequest_ListServices struct { + ListServices string `protobuf:"bytes,7,opt,name=list_services,json=listServices,proto3,oneof"` +} + +func (*ServerReflectionRequest_FileByFilename) isServerReflectionRequest_MessageRequest() {} + +func (*ServerReflectionRequest_FileContainingSymbol) isServerReflectionRequest_MessageRequest() {} + +func (*ServerReflectionRequest_FileContainingExtension) isServerReflectionRequest_MessageRequest() {} + +func (*ServerReflectionRequest_AllExtensionNumbersOfType) isServerReflectionRequest_MessageRequest() { +} + +func (*ServerReflectionRequest_ListServices) isServerReflectionRequest_MessageRequest() {} + +func (m *ServerReflectionRequest) GetMessageRequest() isServerReflectionRequest_MessageRequest { + if m != nil { + return m.MessageRequest + } + return nil +} + +func (m *ServerReflectionRequest) GetFileByFilename() string { + if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileByFilename); ok { + return x.FileByFilename + } + return "" +} + +func (m *ServerReflectionRequest) GetFileContainingSymbol() string { + if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileContainingSymbol); ok { + return x.FileContainingSymbol + } + return "" +} + +func (m *ServerReflectionRequest) GetFileContainingExtension() *ExtensionRequest { + if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_FileContainingExtension); ok { + return x.FileContainingExtension + } + return nil +} + +func (m *ServerReflectionRequest) GetAllExtensionNumbersOfType() string { + if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_AllExtensionNumbersOfType); ok { + return x.AllExtensionNumbersOfType + } + return "" +} + +func (m *ServerReflectionRequest) GetListServices() string { + if x, ok := m.GetMessageRequest().(*ServerReflectionRequest_ListServices); ok { + return x.ListServices + } + return "" +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*ServerReflectionRequest) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*ServerReflectionRequest_FileByFilename)(nil), + (*ServerReflectionRequest_FileContainingSymbol)(nil), + (*ServerReflectionRequest_FileContainingExtension)(nil), + (*ServerReflectionRequest_AllExtensionNumbersOfType)(nil), + (*ServerReflectionRequest_ListServices)(nil), + } +} + +// The type name and extension number sent by the client when requesting +// file_containing_extension. +type ExtensionRequest struct { + // Fully-qualified type name. The format should be . + ContainingType string `protobuf:"bytes,1,opt,name=containing_type,json=containingType,proto3" json:"containing_type,omitempty"` + ExtensionNumber int32 `protobuf:"varint,2,opt,name=extension_number,json=extensionNumber,proto3" json:"extension_number,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ExtensionRequest) Reset() { *m = ExtensionRequest{} } +func (m *ExtensionRequest) String() string { return proto.CompactTextString(m) } +func (*ExtensionRequest) ProtoMessage() {} +func (*ExtensionRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_e8cf9f2921ad6c95, []int{1} +} + +func (m *ExtensionRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ExtensionRequest.Unmarshal(m, b) +} +func (m *ExtensionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ExtensionRequest.Marshal(b, m, deterministic) +} +func (m *ExtensionRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_ExtensionRequest.Merge(m, src) +} +func (m *ExtensionRequest) XXX_Size() int { + return xxx_messageInfo_ExtensionRequest.Size(m) +} +func (m *ExtensionRequest) XXX_DiscardUnknown() { + xxx_messageInfo_ExtensionRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_ExtensionRequest proto.InternalMessageInfo + +func (m *ExtensionRequest) GetContainingType() string { + if m != nil { + return m.ContainingType + } + return "" +} + +func (m *ExtensionRequest) GetExtensionNumber() int32 { + if m != nil { + return m.ExtensionNumber + } + return 0 +} + +// The message sent by the server to answer ServerReflectionInfo method. +type ServerReflectionResponse struct { + ValidHost string `protobuf:"bytes,1,opt,name=valid_host,json=validHost,proto3" json:"valid_host,omitempty"` + OriginalRequest *ServerReflectionRequest `protobuf:"bytes,2,opt,name=original_request,json=originalRequest,proto3" json:"original_request,omitempty"` + // The server sets one of the following fields according to the + // message_request in the request. + // + // Types that are valid to be assigned to MessageResponse: + // *ServerReflectionResponse_FileDescriptorResponse + // *ServerReflectionResponse_AllExtensionNumbersResponse + // *ServerReflectionResponse_ListServicesResponse + // *ServerReflectionResponse_ErrorResponse + MessageResponse isServerReflectionResponse_MessageResponse `protobuf_oneof:"message_response"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ServerReflectionResponse) Reset() { *m = ServerReflectionResponse{} } +func (m *ServerReflectionResponse) String() string { return proto.CompactTextString(m) } +func (*ServerReflectionResponse) ProtoMessage() {} +func (*ServerReflectionResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e8cf9f2921ad6c95, []int{2} +} + +func (m *ServerReflectionResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ServerReflectionResponse.Unmarshal(m, b) +} +func (m *ServerReflectionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ServerReflectionResponse.Marshal(b, m, deterministic) +} +func (m *ServerReflectionResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ServerReflectionResponse.Merge(m, src) +} +func (m *ServerReflectionResponse) XXX_Size() int { + return xxx_messageInfo_ServerReflectionResponse.Size(m) +} +func (m *ServerReflectionResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ServerReflectionResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_ServerReflectionResponse proto.InternalMessageInfo + +func (m *ServerReflectionResponse) GetValidHost() string { + if m != nil { + return m.ValidHost + } + return "" +} + +func (m *ServerReflectionResponse) GetOriginalRequest() *ServerReflectionRequest { + if m != nil { + return m.OriginalRequest + } + return nil +} + +type isServerReflectionResponse_MessageResponse interface { + isServerReflectionResponse_MessageResponse() +} + +type ServerReflectionResponse_FileDescriptorResponse struct { + FileDescriptorResponse *FileDescriptorResponse `protobuf:"bytes,4,opt,name=file_descriptor_response,json=fileDescriptorResponse,proto3,oneof"` +} + +type ServerReflectionResponse_AllExtensionNumbersResponse struct { + AllExtensionNumbersResponse *ExtensionNumberResponse `protobuf:"bytes,5,opt,name=all_extension_numbers_response,json=allExtensionNumbersResponse,proto3,oneof"` +} + +type ServerReflectionResponse_ListServicesResponse struct { + ListServicesResponse *ListServiceResponse `protobuf:"bytes,6,opt,name=list_services_response,json=listServicesResponse,proto3,oneof"` +} + +type ServerReflectionResponse_ErrorResponse struct { + ErrorResponse *ErrorResponse `protobuf:"bytes,7,opt,name=error_response,json=errorResponse,proto3,oneof"` +} + +func (*ServerReflectionResponse_FileDescriptorResponse) isServerReflectionResponse_MessageResponse() { +} + +func (*ServerReflectionResponse_AllExtensionNumbersResponse) isServerReflectionResponse_MessageResponse() { +} + +func (*ServerReflectionResponse_ListServicesResponse) isServerReflectionResponse_MessageResponse() {} + +func (*ServerReflectionResponse_ErrorResponse) isServerReflectionResponse_MessageResponse() {} + +func (m *ServerReflectionResponse) GetMessageResponse() isServerReflectionResponse_MessageResponse { + if m != nil { + return m.MessageResponse + } + return nil +} + +func (m *ServerReflectionResponse) GetFileDescriptorResponse() *FileDescriptorResponse { + if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_FileDescriptorResponse); ok { + return x.FileDescriptorResponse + } + return nil +} + +func (m *ServerReflectionResponse) GetAllExtensionNumbersResponse() *ExtensionNumberResponse { + if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_AllExtensionNumbersResponse); ok { + return x.AllExtensionNumbersResponse + } + return nil +} + +func (m *ServerReflectionResponse) GetListServicesResponse() *ListServiceResponse { + if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_ListServicesResponse); ok { + return x.ListServicesResponse + } + return nil +} + +func (m *ServerReflectionResponse) GetErrorResponse() *ErrorResponse { + if x, ok := m.GetMessageResponse().(*ServerReflectionResponse_ErrorResponse); ok { + return x.ErrorResponse + } + return nil +} + +// XXX_OneofWrappers is for the internal use of the proto package. +func (*ServerReflectionResponse) XXX_OneofWrappers() []interface{} { + return []interface{}{ + (*ServerReflectionResponse_FileDescriptorResponse)(nil), + (*ServerReflectionResponse_AllExtensionNumbersResponse)(nil), + (*ServerReflectionResponse_ListServicesResponse)(nil), + (*ServerReflectionResponse_ErrorResponse)(nil), + } +} + +// Serialized FileDescriptorProto messages sent by the server answering +// a file_by_filename, file_containing_symbol, or file_containing_extension +// request. +type FileDescriptorResponse struct { + // Serialized FileDescriptorProto messages. We avoid taking a dependency on + // descriptor.proto, which uses proto2 only features, by making them opaque + // bytes instead. + FileDescriptorProto [][]byte `protobuf:"bytes,1,rep,name=file_descriptor_proto,json=fileDescriptorProto,proto3" json:"file_descriptor_proto,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *FileDescriptorResponse) Reset() { *m = FileDescriptorResponse{} } +func (m *FileDescriptorResponse) String() string { return proto.CompactTextString(m) } +func (*FileDescriptorResponse) ProtoMessage() {} +func (*FileDescriptorResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e8cf9f2921ad6c95, []int{3} +} + +func (m *FileDescriptorResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_FileDescriptorResponse.Unmarshal(m, b) +} +func (m *FileDescriptorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_FileDescriptorResponse.Marshal(b, m, deterministic) +} +func (m *FileDescriptorResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_FileDescriptorResponse.Merge(m, src) +} +func (m *FileDescriptorResponse) XXX_Size() int { + return xxx_messageInfo_FileDescriptorResponse.Size(m) +} +func (m *FileDescriptorResponse) XXX_DiscardUnknown() { + xxx_messageInfo_FileDescriptorResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_FileDescriptorResponse proto.InternalMessageInfo + +func (m *FileDescriptorResponse) GetFileDescriptorProto() [][]byte { + if m != nil { + return m.FileDescriptorProto + } + return nil +} + +// A list of extension numbers sent by the server answering +// all_extension_numbers_of_type request. +type ExtensionNumberResponse struct { + // Full name of the base type, including the package name. The format + // is . + BaseTypeName string `protobuf:"bytes,1,opt,name=base_type_name,json=baseTypeName,proto3" json:"base_type_name,omitempty"` + ExtensionNumber []int32 `protobuf:"varint,2,rep,packed,name=extension_number,json=extensionNumber,proto3" json:"extension_number,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ExtensionNumberResponse) Reset() { *m = ExtensionNumberResponse{} } +func (m *ExtensionNumberResponse) String() string { return proto.CompactTextString(m) } +func (*ExtensionNumberResponse) ProtoMessage() {} +func (*ExtensionNumberResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e8cf9f2921ad6c95, []int{4} +} + +func (m *ExtensionNumberResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ExtensionNumberResponse.Unmarshal(m, b) +} +func (m *ExtensionNumberResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ExtensionNumberResponse.Marshal(b, m, deterministic) +} +func (m *ExtensionNumberResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ExtensionNumberResponse.Merge(m, src) +} +func (m *ExtensionNumberResponse) XXX_Size() int { + return xxx_messageInfo_ExtensionNumberResponse.Size(m) +} +func (m *ExtensionNumberResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ExtensionNumberResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_ExtensionNumberResponse proto.InternalMessageInfo + +func (m *ExtensionNumberResponse) GetBaseTypeName() string { + if m != nil { + return m.BaseTypeName + } + return "" +} + +func (m *ExtensionNumberResponse) GetExtensionNumber() []int32 { + if m != nil { + return m.ExtensionNumber + } + return nil +} + +// A list of ServiceResponse sent by the server answering list_services request. +type ListServiceResponse struct { + // The information of each service may be expanded in the future, so we use + // ServiceResponse message to encapsulate it. + Service []*ServiceResponse `protobuf:"bytes,1,rep,name=service,proto3" json:"service,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ListServiceResponse) Reset() { *m = ListServiceResponse{} } +func (m *ListServiceResponse) String() string { return proto.CompactTextString(m) } +func (*ListServiceResponse) ProtoMessage() {} +func (*ListServiceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e8cf9f2921ad6c95, []int{5} +} + +func (m *ListServiceResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ListServiceResponse.Unmarshal(m, b) +} +func (m *ListServiceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ListServiceResponse.Marshal(b, m, deterministic) +} +func (m *ListServiceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ListServiceResponse.Merge(m, src) +} +func (m *ListServiceResponse) XXX_Size() int { + return xxx_messageInfo_ListServiceResponse.Size(m) +} +func (m *ListServiceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ListServiceResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_ListServiceResponse proto.InternalMessageInfo + +func (m *ListServiceResponse) GetService() []*ServiceResponse { + if m != nil { + return m.Service + } + return nil +} + +// The information of a single service used by ListServiceResponse to answer +// list_services request. +type ServiceResponse struct { + // Full name of a registered service, including its package name. The format + // is . + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ServiceResponse) Reset() { *m = ServiceResponse{} } +func (m *ServiceResponse) String() string { return proto.CompactTextString(m) } +func (*ServiceResponse) ProtoMessage() {} +func (*ServiceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e8cf9f2921ad6c95, []int{6} +} + +func (m *ServiceResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ServiceResponse.Unmarshal(m, b) +} +func (m *ServiceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ServiceResponse.Marshal(b, m, deterministic) +} +func (m *ServiceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ServiceResponse.Merge(m, src) +} +func (m *ServiceResponse) XXX_Size() int { + return xxx_messageInfo_ServiceResponse.Size(m) +} +func (m *ServiceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ServiceResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_ServiceResponse proto.InternalMessageInfo + +func (m *ServiceResponse) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +// The error code and error message sent by the server when an error occurs. +type ErrorResponse struct { + // This field uses the error codes defined in grpc::StatusCode. + ErrorCode int32 `protobuf:"varint,1,opt,name=error_code,json=errorCode,proto3" json:"error_code,omitempty"` + ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ErrorResponse) Reset() { *m = ErrorResponse{} } +func (m *ErrorResponse) String() string { return proto.CompactTextString(m) } +func (*ErrorResponse) ProtoMessage() {} +func (*ErrorResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e8cf9f2921ad6c95, []int{7} +} + +func (m *ErrorResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ErrorResponse.Unmarshal(m, b) +} +func (m *ErrorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ErrorResponse.Marshal(b, m, deterministic) +} +func (m *ErrorResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ErrorResponse.Merge(m, src) +} +func (m *ErrorResponse) XXX_Size() int { + return xxx_messageInfo_ErrorResponse.Size(m) +} +func (m *ErrorResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ErrorResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_ErrorResponse proto.InternalMessageInfo + +func (m *ErrorResponse) GetErrorCode() int32 { + if m != nil { + return m.ErrorCode + } + return 0 +} + +func (m *ErrorResponse) GetErrorMessage() string { + if m != nil { + return m.ErrorMessage + } + return "" +} + +func init() { + proto.RegisterType((*ServerReflectionRequest)(nil), "grpc.reflection.v1alpha.ServerReflectionRequest") + proto.RegisterType((*ExtensionRequest)(nil), "grpc.reflection.v1alpha.ExtensionRequest") + proto.RegisterType((*ServerReflectionResponse)(nil), "grpc.reflection.v1alpha.ServerReflectionResponse") + proto.RegisterType((*FileDescriptorResponse)(nil), "grpc.reflection.v1alpha.FileDescriptorResponse") + proto.RegisterType((*ExtensionNumberResponse)(nil), "grpc.reflection.v1alpha.ExtensionNumberResponse") + proto.RegisterType((*ListServiceResponse)(nil), "grpc.reflection.v1alpha.ListServiceResponse") + proto.RegisterType((*ServiceResponse)(nil), "grpc.reflection.v1alpha.ServiceResponse") + proto.RegisterType((*ErrorResponse)(nil), "grpc.reflection.v1alpha.ErrorResponse") +} + +func init() { + proto.RegisterFile("reflection/grpc_reflection_v1alpha/reflection.proto", fileDescriptor_e8cf9f2921ad6c95) +} + +var fileDescriptor_e8cf9f2921ad6c95 = []byte{ + // 686 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x55, 0x41, 0x6f, 0xd3, 0x4c, + 0x10, 0xad, 0xdb, 0xa4, 0x55, 0x26, 0x69, 0x92, 0x6f, 0xdb, 0xaf, 0x71, 0x41, 0x45, 0x91, 0xa1, + 0x90, 0x22, 0x94, 0xb4, 0xa9, 0x84, 0x84, 0xb8, 0xa5, 0x80, 0x82, 0x54, 0x5a, 0xe4, 0x70, 0x01, + 0x0e, 0x2b, 0x27, 0x99, 0xb8, 0x06, 0xc7, 0x6b, 0x76, 0xdd, 0x40, 0x4e, 0xfc, 0x08, 0x7e, 0x14, + 0x7f, 0x89, 0x23, 0xda, 0xb5, 0x63, 0x3b, 0x6e, 0x4c, 0xd5, 0x53, 0x9c, 0x37, 0x33, 0xfb, 0x66, + 0xf6, 0xbd, 0xb1, 0xe1, 0x94, 0xe3, 0xc4, 0xc5, 0x51, 0xe0, 0x30, 0xaf, 0x63, 0x73, 0x7f, 0x44, + 0x93, 0xff, 0x74, 0x76, 0x62, 0xb9, 0xfe, 0x95, 0xd5, 0x49, 0xa0, 0xb6, 0xcf, 0x59, 0xc0, 0x48, + 0x43, 0x66, 0xb6, 0x53, 0x70, 0x94, 0x69, 0xfc, 0x59, 0x87, 0xc6, 0x00, 0xf9, 0x0c, 0xb9, 0x19, + 0x07, 0x4d, 0xfc, 0x76, 0x8d, 0x22, 0x20, 0x04, 0x0a, 0x57, 0x4c, 0x04, 0xba, 0xd6, 0xd4, 0x5a, + 0x25, 0x53, 0x3d, 0x93, 0xa7, 0x50, 0x9f, 0x38, 0x2e, 0xd2, 0xe1, 0x9c, 0xca, 0x5f, 0xcf, 0x9a, + 0xa2, 0xbe, 0x21, 0xe3, 0xfd, 0x35, 0xb3, 0x2a, 0x91, 0xde, 0xfc, 0x4d, 0x84, 0x93, 0xe7, 0xb0, + 0xa7, 0x72, 0x47, 0xcc, 0x0b, 0x2c, 0xc7, 0x73, 0x3c, 0x9b, 0x8a, 0xf9, 0x74, 0xc8, 0x5c, 0xbd, + 0x10, 0x55, 0xec, 0xca, 0xf8, 0x59, 0x1c, 0x1e, 0xa8, 0x28, 0xb1, 0x61, 0x3f, 0x5b, 0x87, 0x3f, + 0x02, 0xf4, 0x84, 0xc3, 0x3c, 0xbd, 0xd8, 0xd4, 0x5a, 0xe5, 0xee, 0x51, 0x3b, 0x67, 0xa0, 0xf6, + 0xeb, 0x45, 0x66, 0x34, 0x45, 0x7f, 0xcd, 0x6c, 0x2c, 0xb3, 0xc4, 0x19, 0xa4, 0x07, 0x07, 0x96, + 0xeb, 0x26, 0x87, 0x53, 0xef, 0x7a, 0x3a, 0x44, 0x2e, 0x28, 0x9b, 0xd0, 0x60, 0xee, 0xa3, 0xbe, + 0x19, 0xf5, 0xb9, 0x6f, 0xb9, 0x6e, 0x5c, 0x76, 0x11, 0x26, 0x5d, 0x4e, 0x3e, 0xcc, 0x7d, 0x24, + 0x87, 0xb0, 0xed, 0x3a, 0x22, 0xa0, 0x02, 0xf9, 0xcc, 0x19, 0xa1, 0xd0, 0xb7, 0xa2, 0x9a, 0x8a, + 0x84, 0x07, 0x11, 0xda, 0xfb, 0x0f, 0x6a, 0x53, 0x14, 0xc2, 0xb2, 0x91, 0xf2, 0xb0, 0x31, 0x63, + 0x02, 0xf5, 0x6c, 0xb3, 0xe4, 0x09, 0xd4, 0x52, 0x53, 0xab, 0x1e, 0xc2, 0xdb, 0xaf, 0x26, 0xb0, + 0xa2, 0x3d, 0x82, 0x7a, 0xb6, 0x6d, 0x7d, 0xbd, 0xa9, 0xb5, 0x8a, 0x66, 0x0d, 0x97, 0x1b, 0x35, + 0x7e, 0x17, 0x40, 0xbf, 0x29, 0xb1, 0xf0, 0x99, 0x27, 0x90, 0x1c, 0x00, 0xcc, 0x2c, 0xd7, 0x19, + 0xd3, 0x94, 0xd2, 0x25, 0x85, 0xf4, 0xa5, 0xdc, 0x9f, 0xa1, 0xce, 0xb8, 0x63, 0x3b, 0x9e, 0xe5, + 0x2e, 0xfa, 0x56, 0x34, 0xe5, 0xee, 0x71, 0xae, 0x02, 0x39, 0x76, 0x32, 0x6b, 0x8b, 0x93, 0x16, + 0xc3, 0x7e, 0x05, 0x5d, 0xe9, 0x3c, 0x46, 0x31, 0xe2, 0x8e, 0x1f, 0x30, 0x4e, 0x79, 0xd4, 0x97, + 0x72, 0x48, 0xb9, 0xdb, 0xc9, 0x25, 0x91, 0x26, 0x7b, 0x15, 0xd7, 0x2d, 0xc6, 0xe9, 0xaf, 0x99, + 0xca, 0x72, 0x37, 0x23, 0xe4, 0x3b, 0x3c, 0x58, 0xad, 0x75, 0x4c, 0x59, 0xbc, 0x65, 0xae, 0x8c, + 0x01, 0x52, 0x9c, 0xf7, 0x57, 0xd8, 0x23, 0x26, 0x1e, 0xc3, 0xde, 0x92, 0x41, 0x12, 0xc2, 0x4d, + 0x45, 0xf8, 0x2c, 0x97, 0xf0, 0x3c, 0x31, 0x50, 0x8a, 0x6c, 0x37, 0xed, 0xab, 0x98, 0xe5, 0x12, + 0xaa, 0xc8, 0x79, 0xfa, 0x06, 0xb7, 0xd4, 0xe9, 0x8f, 0xf3, 0xc7, 0x91, 0xe9, 0xa9, 0x73, 0xb7, + 0x31, 0x0d, 0xf4, 0x08, 0xd4, 0x13, 0xc3, 0x86, 0x98, 0x71, 0x0e, 0x7b, 0xab, 0xef, 0x9d, 0x74, + 0xe1, 0xff, 0xac, 0x94, 0xea, 0xc5, 0xa3, 0x6b, 0xcd, 0x8d, 0x56, 0xc5, 0xdc, 0x59, 0x16, 0xe5, + 0xbd, 0x0c, 0x19, 0x5f, 0xa0, 0x91, 0x73, 0xa5, 0xe4, 0x11, 0x54, 0x87, 0x96, 0x40, 0xb5, 0x00, + 0x54, 0xbd, 0x63, 0x42, 0x67, 0x56, 0x24, 0x2a, 0xfd, 0x7f, 0x21, 0xdf, 0x2f, 0xab, 0x77, 0x60, + 0x63, 0xd5, 0x0e, 0x7c, 0x84, 0x9d, 0x15, 0xb7, 0x49, 0x7a, 0xb0, 0x15, 0xc9, 0xa2, 0x1a, 0x2d, + 0x77, 0x5b, 0xff, 0x74, 0x75, 0xaa, 0xd4, 0x5c, 0x14, 0x1a, 0x87, 0x50, 0xcb, 0x1e, 0x4b, 0xa0, + 0x90, 0x6a, 0x5a, 0x3d, 0x1b, 0x03, 0xd8, 0x5e, 0xba, 0x71, 0xb9, 0x79, 0xa1, 0x62, 0x23, 0x36, + 0x0e, 0x53, 0x8b, 0x66, 0x49, 0x21, 0x67, 0x6c, 0x8c, 0xe4, 0x21, 0x84, 0x82, 0xd0, 0x48, 0x05, + 0xb5, 0x76, 0x25, 0xb3, 0xa2, 0xc0, 0x77, 0x21, 0xd6, 0xfd, 0xa5, 0x41, 0x3d, 0xbb, 0x6e, 0xe4, + 0x27, 0xec, 0x66, 0xb1, 0xb7, 0xde, 0x84, 0x91, 0x3b, 0x6f, 0xec, 0xbd, 0x93, 0x3b, 0x54, 0x84, + 0x53, 0xb5, 0xb4, 0x63, 0xad, 0xf7, 0xf2, 0xd3, 0x0b, 0x9b, 0x31, 0xdb, 0xc5, 0xb6, 0xcd, 0x5c, + 0xcb, 0xb3, 0xdb, 0x8c, 0xdb, 0xea, 0x53, 0xd5, 0xb9, 0xfd, 0xd3, 0x35, 0xdc, 0x54, 0xbe, 0x39, + 0xfd, 0x1b, 0x00, 0x00, 0xff, 0xff, 0x6c, 0x74, 0x3a, 0x67, 0xe7, 0x06, 0x00, 0x00, +} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.proto b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.proto new file mode 100644 index 00000000000..ee2b82c0a5b --- /dev/null +++ b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection.proto @@ -0,0 +1,138 @@ +// Copyright 2016 gRPC authors. +// +// 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. + +// Service exported by server reflection + +syntax = "proto3"; + +option go_package = "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"; + +package grpc.reflection.v1alpha; + +service ServerReflection { + // The reflection service is structured as a bidirectional stream, ensuring + // all related requests go to a single server. + rpc ServerReflectionInfo(stream ServerReflectionRequest) + returns (stream ServerReflectionResponse); +} + +// The message sent by the client when calling ServerReflectionInfo method. +message ServerReflectionRequest { + string host = 1; + // To use reflection service, the client should set one of the following + // fields in message_request. The server distinguishes requests by their + // defined field and then handles them using corresponding methods. + oneof message_request { + // Find a proto file by the file name. + string file_by_filename = 3; + + // Find the proto file that declares the given fully-qualified symbol name. + // This field should be a fully-qualified symbol name + // (e.g. .[.] or .). + string file_containing_symbol = 4; + + // Find the proto file which defines an extension extending the given + // message type with the given field number. + ExtensionRequest file_containing_extension = 5; + + // Finds the tag numbers used by all known extensions of extendee_type, and + // appends them to ExtensionNumberResponse in an undefined order. + // Its corresponding method is best-effort: it's not guaranteed that the + // reflection service will implement this method, and it's not guaranteed + // that this method will provide all extensions. Returns + // StatusCode::UNIMPLEMENTED if it's not implemented. + // This field should be a fully-qualified type name. The format is + // . + string all_extension_numbers_of_type = 6; + + // List the full names of registered services. The content will not be + // checked. + string list_services = 7; + } +} + +// The type name and extension number sent by the client when requesting +// file_containing_extension. +message ExtensionRequest { + // Fully-qualified type name. The format should be . + string containing_type = 1; + int32 extension_number = 2; +} + +// The message sent by the server to answer ServerReflectionInfo method. +message ServerReflectionResponse { + string valid_host = 1; + ServerReflectionRequest original_request = 2; + // The server sets one of the following fields according to the + // message_request in the request. + oneof message_response { + // This message is used to answer file_by_filename, file_containing_symbol, + // file_containing_extension requests with transitive dependencies. + // As the repeated label is not allowed in oneof fields, we use a + // FileDescriptorResponse message to encapsulate the repeated fields. + // The reflection service is allowed to avoid sending FileDescriptorProtos + // that were previously sent in response to earlier requests in the stream. + FileDescriptorResponse file_descriptor_response = 4; + + // This message is used to answer all_extension_numbers_of_type requests. + ExtensionNumberResponse all_extension_numbers_response = 5; + + // This message is used to answer list_services requests. + ListServiceResponse list_services_response = 6; + + // This message is used when an error occurs. + ErrorResponse error_response = 7; + } +} + +// Serialized FileDescriptorProto messages sent by the server answering +// a file_by_filename, file_containing_symbol, or file_containing_extension +// request. +message FileDescriptorResponse { + // Serialized FileDescriptorProto messages. We avoid taking a dependency on + // descriptor.proto, which uses proto2 only features, by making them opaque + // bytes instead. + repeated bytes file_descriptor_proto = 1; +} + +// A list of extension numbers sent by the server answering +// all_extension_numbers_of_type request. +message ExtensionNumberResponse { + // Full name of the base type, including the package name. The format + // is . + string base_type_name = 1; + repeated int32 extension_number = 2; +} + +// A list of ServiceResponse sent by the server answering list_services request. +message ListServiceResponse { + // The information of each service may be expanded in the future, so we use + // ServiceResponse message to encapsulate it. + repeated ServiceResponse service = 1; +} + +// The information of a single service used by ListServiceResponse to answer +// list_services request. +message ServiceResponse { + // Full name of a registered service, including its package name. The format + // is . + string name = 1; +} + +// The error code and error message sent by the server when an error occurs. +message ErrorResponse { + // This field uses the error codes defined in grpc::StatusCode. + int32 error_code = 1; + string error_message = 2; +} diff --git a/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go new file mode 100644 index 00000000000..2294b2c6c9e --- /dev/null +++ b/vendor/google.golang.org/grpc/reflection/grpc_reflection_v1alpha/reflection_grpc.pb.go @@ -0,0 +1,124 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. + +package grpc_reflection_v1alpha + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion6 + +// ServerReflectionClient is the client API for ServerReflection service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type ServerReflectionClient interface { + // The reflection service is structured as a bidirectional stream, ensuring + // all related requests go to a single server. + ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) +} + +type serverReflectionClient struct { + cc grpc.ClientConnInterface +} + +func NewServerReflectionClient(cc grpc.ClientConnInterface) ServerReflectionClient { + return &serverReflectionClient{cc} +} + +func (c *serverReflectionClient) ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (ServerReflection_ServerReflectionInfoClient, error) { + stream, err := c.cc.NewStream(ctx, &_ServerReflection_serviceDesc.Streams[0], "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", opts...) + if err != nil { + return nil, err + } + x := &serverReflectionServerReflectionInfoClient{stream} + return x, nil +} + +type ServerReflection_ServerReflectionInfoClient interface { + Send(*ServerReflectionRequest) error + Recv() (*ServerReflectionResponse, error) + grpc.ClientStream +} + +type serverReflectionServerReflectionInfoClient struct { + grpc.ClientStream +} + +func (x *serverReflectionServerReflectionInfoClient) Send(m *ServerReflectionRequest) error { + return x.ClientStream.SendMsg(m) +} + +func (x *serverReflectionServerReflectionInfoClient) Recv() (*ServerReflectionResponse, error) { + m := new(ServerReflectionResponse) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// ServerReflectionServer is the server API for ServerReflection service. +// All implementations should embed UnimplementedServerReflectionServer +// for forward compatibility +type ServerReflectionServer interface { + // The reflection service is structured as a bidirectional stream, ensuring + // all related requests go to a single server. + ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error +} + +// UnimplementedServerReflectionServer should be embedded to have forward compatible implementations. +type UnimplementedServerReflectionServer struct { +} + +func (*UnimplementedServerReflectionServer) ServerReflectionInfo(ServerReflection_ServerReflectionInfoServer) error { + return status.Errorf(codes.Unimplemented, "method ServerReflectionInfo not implemented") +} + +func RegisterServerReflectionServer(s *grpc.Server, srv ServerReflectionServer) { + s.RegisterService(&_ServerReflection_serviceDesc, srv) +} + +func _ServerReflection_ServerReflectionInfo_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(ServerReflectionServer).ServerReflectionInfo(&serverReflectionServerReflectionInfoServer{stream}) +} + +type ServerReflection_ServerReflectionInfoServer interface { + Send(*ServerReflectionResponse) error + Recv() (*ServerReflectionRequest, error) + grpc.ServerStream +} + +type serverReflectionServerReflectionInfoServer struct { + grpc.ServerStream +} + +func (x *serverReflectionServerReflectionInfoServer) Send(m *ServerReflectionResponse) error { + return x.ServerStream.SendMsg(m) +} + +func (x *serverReflectionServerReflectionInfoServer) Recv() (*ServerReflectionRequest, error) { + m := new(ServerReflectionRequest) + if err := x.ServerStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +var _ServerReflection_serviceDesc = grpc.ServiceDesc{ + ServiceName: "grpc.reflection.v1alpha.ServerReflection", + HandlerType: (*ServerReflectionServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{ + { + StreamName: "ServerReflectionInfo", + Handler: _ServerReflection_ServerReflectionInfo_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "reflection/grpc_reflection_v1alpha/reflection.proto", +} diff --git a/vendor/google.golang.org/grpc/reflection/serverreflection.go b/vendor/google.golang.org/grpc/reflection/serverreflection.go new file mode 100644 index 00000000000..7b6dd414a27 --- /dev/null +++ b/vendor/google.golang.org/grpc/reflection/serverreflection.go @@ -0,0 +1,453 @@ +/* + * + * Copyright 2016 gRPC authors. + * + * 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 reflection implements server reflection service. + +The service implemented is defined in: +https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1alpha/reflection.proto. + +To register server reflection on a gRPC server: + import "google.golang.org/grpc/reflection" + + s := grpc.NewServer() + pb.RegisterYourOwnServer(s, &server{}) + + // Register reflection service on gRPC server. + reflection.Register(s) + + s.Serve(lis) + +*/ +package reflection // import "google.golang.org/grpc/reflection" + +import ( + "bytes" + "compress/gzip" + "fmt" + "io" + "io/ioutil" + "reflect" + "sort" + "sync" + + "github.com/golang/protobuf/proto" + dpb "github.com/golang/protobuf/protoc-gen-go/descriptor" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + rpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha" + "google.golang.org/grpc/status" +) + +type serverReflectionServer struct { + rpb.UnimplementedServerReflectionServer + s *grpc.Server + + initSymbols sync.Once + serviceNames []string + symbols map[string]*dpb.FileDescriptorProto // map of fully-qualified names to files +} + +// Register registers the server reflection service on the given gRPC server. +func Register(s *grpc.Server) { + rpb.RegisterServerReflectionServer(s, &serverReflectionServer{ + s: s, + }) +} + +// protoMessage is used for type assertion on proto messages. +// Generated proto message implements function Descriptor(), but Descriptor() +// is not part of interface proto.Message. This interface is needed to +// call Descriptor(). +type protoMessage interface { + Descriptor() ([]byte, []int) +} + +func (s *serverReflectionServer) getSymbols() (svcNames []string, symbolIndex map[string]*dpb.FileDescriptorProto) { + s.initSymbols.Do(func() { + serviceInfo := s.s.GetServiceInfo() + + s.symbols = map[string]*dpb.FileDescriptorProto{} + s.serviceNames = make([]string, 0, len(serviceInfo)) + processed := map[string]struct{}{} + for svc, info := range serviceInfo { + s.serviceNames = append(s.serviceNames, svc) + fdenc, ok := parseMetadata(info.Metadata) + if !ok { + continue + } + fd, err := decodeFileDesc(fdenc) + if err != nil { + continue + } + s.processFile(fd, processed) + } + sort.Strings(s.serviceNames) + }) + + return s.serviceNames, s.symbols +} + +func (s *serverReflectionServer) processFile(fd *dpb.FileDescriptorProto, processed map[string]struct{}) { + filename := fd.GetName() + if _, ok := processed[filename]; ok { + return + } + processed[filename] = struct{}{} + + prefix := fd.GetPackage() + + for _, msg := range fd.MessageType { + s.processMessage(fd, prefix, msg) + } + for _, en := range fd.EnumType { + s.processEnum(fd, prefix, en) + } + for _, ext := range fd.Extension { + s.processField(fd, prefix, ext) + } + for _, svc := range fd.Service { + svcName := fqn(prefix, svc.GetName()) + s.symbols[svcName] = fd + for _, meth := range svc.Method { + name := fqn(svcName, meth.GetName()) + s.symbols[name] = fd + } + } + + for _, dep := range fd.Dependency { + fdenc := proto.FileDescriptor(dep) + fdDep, err := decodeFileDesc(fdenc) + if err != nil { + continue + } + s.processFile(fdDep, processed) + } +} + +func (s *serverReflectionServer) processMessage(fd *dpb.FileDescriptorProto, prefix string, msg *dpb.DescriptorProto) { + msgName := fqn(prefix, msg.GetName()) + s.symbols[msgName] = fd + + for _, nested := range msg.NestedType { + s.processMessage(fd, msgName, nested) + } + for _, en := range msg.EnumType { + s.processEnum(fd, msgName, en) + } + for _, ext := range msg.Extension { + s.processField(fd, msgName, ext) + } + for _, fld := range msg.Field { + s.processField(fd, msgName, fld) + } + for _, oneof := range msg.OneofDecl { + oneofName := fqn(msgName, oneof.GetName()) + s.symbols[oneofName] = fd + } +} + +func (s *serverReflectionServer) processEnum(fd *dpb.FileDescriptorProto, prefix string, en *dpb.EnumDescriptorProto) { + enName := fqn(prefix, en.GetName()) + s.symbols[enName] = fd + + for _, val := range en.Value { + valName := fqn(enName, val.GetName()) + s.symbols[valName] = fd + } +} + +func (s *serverReflectionServer) processField(fd *dpb.FileDescriptorProto, prefix string, fld *dpb.FieldDescriptorProto) { + fldName := fqn(prefix, fld.GetName()) + s.symbols[fldName] = fd +} + +func fqn(prefix, name string) string { + if prefix == "" { + return name + } + return prefix + "." + name +} + +// fileDescForType gets the file descriptor for the given type. +// The given type should be a proto message. +func (s *serverReflectionServer) fileDescForType(st reflect.Type) (*dpb.FileDescriptorProto, error) { + m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(protoMessage) + if !ok { + return nil, fmt.Errorf("failed to create message from type: %v", st) + } + enc, _ := m.Descriptor() + + return decodeFileDesc(enc) +} + +// decodeFileDesc does decompression and unmarshalling on the given +// file descriptor byte slice. +func decodeFileDesc(enc []byte) (*dpb.FileDescriptorProto, error) { + raw, err := decompress(enc) + if err != nil { + return nil, fmt.Errorf("failed to decompress enc: %v", err) + } + + fd := new(dpb.FileDescriptorProto) + if err := proto.Unmarshal(raw, fd); err != nil { + return nil, fmt.Errorf("bad descriptor: %v", err) + } + return fd, nil +} + +// decompress does gzip decompression. +func decompress(b []byte) ([]byte, error) { + r, err := gzip.NewReader(bytes.NewReader(b)) + if err != nil { + return nil, fmt.Errorf("bad gzipped descriptor: %v", err) + } + out, err := ioutil.ReadAll(r) + if err != nil { + return nil, fmt.Errorf("bad gzipped descriptor: %v", err) + } + return out, nil +} + +func typeForName(name string) (reflect.Type, error) { + pt := proto.MessageType(name) + if pt == nil { + return nil, fmt.Errorf("unknown type: %q", name) + } + st := pt.Elem() + + return st, nil +} + +func fileDescContainingExtension(st reflect.Type, ext int32) (*dpb.FileDescriptorProto, error) { + m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) + if !ok { + return nil, fmt.Errorf("failed to create message from type: %v", st) + } + + var extDesc *proto.ExtensionDesc + for id, desc := range proto.RegisteredExtensions(m) { + if id == ext { + extDesc = desc + break + } + } + + if extDesc == nil { + return nil, fmt.Errorf("failed to find registered extension for extension number %v", ext) + } + + return decodeFileDesc(proto.FileDescriptor(extDesc.Filename)) +} + +func (s *serverReflectionServer) allExtensionNumbersForType(st reflect.Type) ([]int32, error) { + m, ok := reflect.Zero(reflect.PtrTo(st)).Interface().(proto.Message) + if !ok { + return nil, fmt.Errorf("failed to create message from type: %v", st) + } + + exts := proto.RegisteredExtensions(m) + out := make([]int32, 0, len(exts)) + for id := range exts { + out = append(out, id) + } + return out, nil +} + +// fileDescEncodingByFilename finds the file descriptor for given filename, +// does marshalling on it and returns the marshalled result. +func (s *serverReflectionServer) fileDescEncodingByFilename(name string) ([]byte, error) { + enc := proto.FileDescriptor(name) + if enc == nil { + return nil, fmt.Errorf("unknown file: %v", name) + } + fd, err := decodeFileDesc(enc) + if err != nil { + return nil, err + } + return proto.Marshal(fd) +} + +// parseMetadata finds the file descriptor bytes specified meta. +// For SupportPackageIsVersion4, m is the name of the proto file, we +// call proto.FileDescriptor to get the byte slice. +// For SupportPackageIsVersion3, m is a byte slice itself. +func parseMetadata(meta interface{}) ([]byte, bool) { + // Check if meta is the file name. + if fileNameForMeta, ok := meta.(string); ok { + return proto.FileDescriptor(fileNameForMeta), true + } + + // Check if meta is the byte slice. + if enc, ok := meta.([]byte); ok { + return enc, true + } + + return nil, false +} + +// fileDescEncodingContainingSymbol finds the file descriptor containing the given symbol, +// does marshalling on it and returns the marshalled result. +// The given symbol can be a type, a service or a method. +func (s *serverReflectionServer) fileDescEncodingContainingSymbol(name string) ([]byte, error) { + _, symbols := s.getSymbols() + fd := symbols[name] + if fd == nil { + // Check if it's a type name that was not present in the + // transitive dependencies of the registered services. + if st, err := typeForName(name); err == nil { + fd, err = s.fileDescForType(st) + if err != nil { + return nil, err + } + } + } + + if fd == nil { + return nil, fmt.Errorf("unknown symbol: %v", name) + } + + return proto.Marshal(fd) +} + +// fileDescEncodingContainingExtension finds the file descriptor containing given extension, +// does marshalling on it and returns the marshalled result. +func (s *serverReflectionServer) fileDescEncodingContainingExtension(typeName string, extNum int32) ([]byte, error) { + st, err := typeForName(typeName) + if err != nil { + return nil, err + } + fd, err := fileDescContainingExtension(st, extNum) + if err != nil { + return nil, err + } + return proto.Marshal(fd) +} + +// allExtensionNumbersForTypeName returns all extension numbers for the given type. +func (s *serverReflectionServer) allExtensionNumbersForTypeName(name string) ([]int32, error) { + st, err := typeForName(name) + if err != nil { + return nil, err + } + extNums, err := s.allExtensionNumbersForType(st) + if err != nil { + return nil, err + } + return extNums, nil +} + +// ServerReflectionInfo is the reflection service handler. +func (s *serverReflectionServer) ServerReflectionInfo(stream rpb.ServerReflection_ServerReflectionInfoServer) error { + for { + in, err := stream.Recv() + if err == io.EOF { + return nil + } + if err != nil { + return err + } + + out := &rpb.ServerReflectionResponse{ + ValidHost: in.Host, + OriginalRequest: in, + } + switch req := in.MessageRequest.(type) { + case *rpb.ServerReflectionRequest_FileByFilename: + b, err := s.fileDescEncodingByFilename(req.FileByFilename) + if err != nil { + out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ + ErrorResponse: &rpb.ErrorResponse{ + ErrorCode: int32(codes.NotFound), + ErrorMessage: err.Error(), + }, + } + } else { + out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ + FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, + } + } + case *rpb.ServerReflectionRequest_FileContainingSymbol: + b, err := s.fileDescEncodingContainingSymbol(req.FileContainingSymbol) + if err != nil { + out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ + ErrorResponse: &rpb.ErrorResponse{ + ErrorCode: int32(codes.NotFound), + ErrorMessage: err.Error(), + }, + } + } else { + out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ + FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, + } + } + case *rpb.ServerReflectionRequest_FileContainingExtension: + typeName := req.FileContainingExtension.ContainingType + extNum := req.FileContainingExtension.ExtensionNumber + b, err := s.fileDescEncodingContainingExtension(typeName, extNum) + if err != nil { + out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ + ErrorResponse: &rpb.ErrorResponse{ + ErrorCode: int32(codes.NotFound), + ErrorMessage: err.Error(), + }, + } + } else { + out.MessageResponse = &rpb.ServerReflectionResponse_FileDescriptorResponse{ + FileDescriptorResponse: &rpb.FileDescriptorResponse{FileDescriptorProto: [][]byte{b}}, + } + } + case *rpb.ServerReflectionRequest_AllExtensionNumbersOfType: + extNums, err := s.allExtensionNumbersForTypeName(req.AllExtensionNumbersOfType) + if err != nil { + out.MessageResponse = &rpb.ServerReflectionResponse_ErrorResponse{ + ErrorResponse: &rpb.ErrorResponse{ + ErrorCode: int32(codes.NotFound), + ErrorMessage: err.Error(), + }, + } + } else { + out.MessageResponse = &rpb.ServerReflectionResponse_AllExtensionNumbersResponse{ + AllExtensionNumbersResponse: &rpb.ExtensionNumberResponse{ + BaseTypeName: req.AllExtensionNumbersOfType, + ExtensionNumber: extNums, + }, + } + } + case *rpb.ServerReflectionRequest_ListServices: + svcNames, _ := s.getSymbols() + serviceResponses := make([]*rpb.ServiceResponse, len(svcNames)) + for i, n := range svcNames { + serviceResponses[i] = &rpb.ServiceResponse{ + Name: n, + } + } + out.MessageResponse = &rpb.ServerReflectionResponse_ListServicesResponse{ + ListServicesResponse: &rpb.ListServiceResponse{ + Service: serviceResponses, + }, + } + default: + return status.Errorf(codes.InvalidArgument, "invalid MessageRequest: %v", in.MessageRequest) + } + + if err := stream.Send(out); err != nil { + return err + } + } +} diff --git a/vendor/google.golang.org/grpc/regenerate.sh b/vendor/google.golang.org/grpc/regenerate.sh new file mode 100644 index 00000000000..987bc20251d --- /dev/null +++ b/vendor/google.golang.org/grpc/regenerate.sh @@ -0,0 +1,79 @@ +#!/bin/bash +# Copyright 2020 gRPC authors. +# +# 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. + +set -eu -o pipefail + +WORKDIR=$(mktemp -d) + +function finish { + rm -rf "$WORKDIR" +} +trap finish EXIT + +export GOBIN=${WORKDIR}/bin +export PATH=${GOBIN}:${PATH} +mkdir -p ${GOBIN} + +echo "go install github.com/golang/protobuf/protoc-gen-go" +(cd test/tools && go install github.com/golang/protobuf/protoc-gen-go) + +echo "go install cmd/protoc-gen-go-grpc" +(cd cmd/protoc-gen-go-grpc && go install .) + +echo "git clone https://github.com/grpc/grpc-proto" +git clone --quiet https://github.com/grpc/grpc-proto ${WORKDIR}/grpc-proto + +mkdir -p ${WORKDIR}/googleapis/google/rpc +echo "curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto" +curl --silent https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto > ${WORKDIR}/googleapis/google/rpc/code.proto + +mkdir -p ${WORKDIR}/out + +SOURCES=( + ${WORKDIR}/googleapis/google/rpc/code.proto + ${WORKDIR}/grpc-proto/grpc/binlog/v1/binarylog.proto + ${WORKDIR}/grpc-proto/grpc/channelz/v1/channelz.proto + ${WORKDIR}/grpc-proto/grpc/gcp/altscontext.proto + ${WORKDIR}/grpc-proto/grpc/gcp/handshaker.proto + ${WORKDIR}/grpc-proto/grpc/gcp/transport_security_common.proto + ${WORKDIR}/grpc-proto/grpc/health/v1/health.proto + ${WORKDIR}/grpc-proto/grpc/lb/v1/load_balancer.proto + ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls.proto + ${WORKDIR}/grpc-proto/grpc/service_config/service_config.proto + $(git ls-files --exclude-standard --cached --others "*.proto") +) +OPTS=Mgrpc/service_config/service_config.proto=/internal/proto/grpc_service_config +for src in ${SOURCES[@]}; do + echo "protoc ${src}" + protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS},requireUnimplementedServers=false:${WORKDIR}/out \ + -I"." \ + -I${WORKDIR}/grpc-proto \ + -I${WORKDIR}/googleapis \ + ${src} +done + +# The go_package option in grpc/lookup/v1/rls.proto doesn't match the +# current location. Move it into the right place. +mkdir -p ${WORKDIR}/out/google.golang.org/grpc/balancer/rls/internal/proto/grpc_lookup_v1 +mv ${WORKDIR}/out/google.golang.org/grpc/lookup/grpc_lookup_v1/* ${WORKDIR}/out/google.golang.org/grpc/balancer/rls/internal/proto/grpc_lookup_v1 + +# grpc_testingv3/testv3.pb.go is not re-generated because it was +# intentionally generated by an older version of protoc-gen-go. +rm ${WORKDIR}/out/google.golang.org/grpc/reflection/grpc_testingv3/*.pb.go + +# grpc/service_config/service_config.proto does not have a go_package option. +cp ${WORKDIR}/out/grpc/service_config/service_config.pb.go internal/proto/grpc_service_config + +cp -R ${WORKDIR}/out/google.golang.org/grpc/* . diff --git a/vendor/google.golang.org/grpc/resolver/resolver.go b/vendor/google.golang.org/grpc/resolver/resolver.go index fe14b2fb982..379275a2d9b 100644 --- a/vendor/google.golang.org/grpc/resolver/resolver.go +++ b/vendor/google.golang.org/grpc/resolver/resolver.go @@ -85,7 +85,10 @@ const ( Backend AddressType = iota // GRPCLB indicates the address is for a grpclb load balancer. // - // Deprecated: use Attributes in Address instead. + // Deprecated: to select the GRPCLB load balancing policy, use a service + // config with a corresponding loadBalancingConfig. To supply balancer + // addresses to the GRPCLB load balancing policy, set State.Attributes + // using balancer/grpclb/state.Set. GRPCLB ) diff --git a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go b/vendor/google.golang.org/grpc/resolver_conn_wrapper.go index 3eaf724cd6d..edfda866c00 100644 --- a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go +++ b/vendor/google.golang.org/grpc/resolver_conn_wrapper.go @@ -26,7 +26,6 @@ import ( "google.golang.org/grpc/balancer" "google.golang.org/grpc/credentials" - "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/resolver" @@ -46,34 +45,6 @@ type ccResolverWrapper struct { polling chan struct{} } -// split2 returns the values from strings.SplitN(s, sep, 2). -// If sep is not found, it returns ("", "", false) instead. -func split2(s, sep string) (string, string, bool) { - spl := strings.SplitN(s, sep, 2) - if len(spl) < 2 { - return "", "", false - } - return spl[0], spl[1], true -} - -// parseTarget splits target into a struct containing scheme, authority and -// endpoint. -// -// If target is not a valid scheme://authority/endpoint, it returns {Endpoint: -// target}. -func parseTarget(target string) (ret resolver.Target) { - var ok bool - ret.Scheme, ret.Endpoint, ok = split2(target, "://") - if !ok { - return resolver.Target{Endpoint: target} - } - ret.Authority, ret.Endpoint, ok = split2(ret.Endpoint, "/") - if !ok { - return resolver.Target{Endpoint: target} - } - return ret -} - // newCCResolverWrapper uses the resolver.Builder to build a Resolver and // returns a ccResolverWrapper object which wraps the newly built resolver. func newCCResolverWrapper(cc *ClientConn, rb resolver.Builder) (*ccResolverWrapper, error) { @@ -169,7 +140,7 @@ func (ccr *ccResolverWrapper) UpdateState(s resolver.State) { if ccr.done.HasFired() { return } - grpclog.Infof("ccResolverWrapper: sending update to cc: %v", s) + channelz.Infof(ccr.cc.channelzID, "ccResolverWrapper: sending update to cc: %v", s) if channelz.IsOn() { ccr.addChannelzTraceEvent(s) } @@ -181,13 +152,7 @@ func (ccr *ccResolverWrapper) ReportError(err error) { if ccr.done.HasFired() { return } - grpclog.Warningf("ccResolverWrapper: reporting error to cc: %v", err) - if channelz.IsOn() { - channelz.AddTraceEvent(ccr.cc.channelzID, &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Resolver reported error: %v", err), - Severity: channelz.CtWarning, - }) - } + channelz.Warningf(ccr.cc.channelzID, "ccResolverWrapper: reporting error to cc: %v", err) ccr.poll(ccr.cc.updateResolverState(resolver.State{}, err)) } @@ -196,7 +161,7 @@ func (ccr *ccResolverWrapper) NewAddress(addrs []resolver.Address) { if ccr.done.HasFired() { return } - grpclog.Infof("ccResolverWrapper: sending new addresses to cc: %v", addrs) + channelz.Infof(ccr.cc.channelzID, "ccResolverWrapper: sending new addresses to cc: %v", addrs) if channelz.IsOn() { ccr.addChannelzTraceEvent(resolver.State{Addresses: addrs, ServiceConfig: ccr.curState.ServiceConfig}) } @@ -210,20 +175,14 @@ func (ccr *ccResolverWrapper) NewServiceConfig(sc string) { if ccr.done.HasFired() { return } - grpclog.Infof("ccResolverWrapper: got new service config: %v", sc) + channelz.Infof(ccr.cc.channelzID, "ccResolverWrapper: got new service config: %v", sc) if ccr.cc.dopts.disableServiceConfig { - grpclog.Infof("Service config lookups disabled; ignoring config") + channelz.Info(ccr.cc.channelzID, "Service config lookups disabled; ignoring config") return } scpr := parseServiceConfig(sc) if scpr.Err != nil { - grpclog.Warningf("ccResolverWrapper: error parsing service config: %v", scpr.Err) - if channelz.IsOn() { - channelz.AddTraceEvent(ccr.cc.channelzID, &channelz.TraceEventDesc{ - Desc: fmt.Sprintf("Error parsing service config: %v", scpr.Err), - Severity: channelz.CtWarning, - }) - } + channelz.Warningf(ccr.cc.channelzID, "ccResolverWrapper: error parsing service config: %v", scpr.Err) ccr.poll(balancer.ErrBadResolverState) return } @@ -256,7 +215,7 @@ func (ccr *ccResolverWrapper) addChannelzTraceEvent(s resolver.State) { } else if len(ccr.curState.Addresses) == 0 && len(s.Addresses) > 0 { updates = append(updates, "resolver returned new addresses") } - channelz.AddTraceEvent(ccr.cc.channelzID, &channelz.TraceEventDesc{ + channelz.AddTraceEvent(ccr.cc.channelzID, 0, &channelz.TraceEventDesc{ Desc: fmt.Sprintf("Resolver state updated: %+v (%v)", s, strings.Join(updates, "; ")), Severity: channelz.CtINFO, }) diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go index d3a4adc5ee6..8644b8a7d0d 100644 --- a/vendor/google.golang.org/grpc/rpc_util.go +++ b/vendor/google.golang.org/grpc/rpc_util.go @@ -155,7 +155,6 @@ func (d *gzipDecompressor) Type() string { type callInfo struct { compressorType string failFast bool - stream ClientStream maxReceiveMessageSize *int maxSendMessageSize *int creds credentials.PerRPCCredentials @@ -180,7 +179,7 @@ type CallOption interface { // after is called after the call has completed. after cannot return an // error, so any failures should be reported via output parameters. - after(*callInfo) + after(*callInfo, *csAttempt) } // EmptyCallOption does not alter the Call configuration. @@ -188,8 +187,8 @@ type CallOption interface { // by interceptors. type EmptyCallOption struct{} -func (EmptyCallOption) before(*callInfo) error { return nil } -func (EmptyCallOption) after(*callInfo) {} +func (EmptyCallOption) before(*callInfo) error { return nil } +func (EmptyCallOption) after(*callInfo, *csAttempt) {} // Header returns a CallOptions that retrieves the header metadata // for a unary RPC. @@ -205,10 +204,8 @@ type HeaderCallOption struct { } func (o HeaderCallOption) before(c *callInfo) error { return nil } -func (o HeaderCallOption) after(c *callInfo) { - if c.stream != nil { - *o.HeaderAddr, _ = c.stream.Header() - } +func (o HeaderCallOption) after(c *callInfo, attempt *csAttempt) { + *o.HeaderAddr, _ = attempt.s.Header() } // Trailer returns a CallOptions that retrieves the trailer metadata @@ -225,10 +222,8 @@ type TrailerCallOption struct { } func (o TrailerCallOption) before(c *callInfo) error { return nil } -func (o TrailerCallOption) after(c *callInfo) { - if c.stream != nil { - *o.TrailerAddr = c.stream.Trailer() - } +func (o TrailerCallOption) after(c *callInfo, attempt *csAttempt) { + *o.TrailerAddr = attempt.s.Trailer() } // Peer returns a CallOption that retrieves peer information for a unary RPC. @@ -245,11 +240,9 @@ type PeerCallOption struct { } func (o PeerCallOption) before(c *callInfo) error { return nil } -func (o PeerCallOption) after(c *callInfo) { - if c.stream != nil { - if x, ok := peer.FromContext(c.stream.Context()); ok { - *o.PeerAddr = *x - } +func (o PeerCallOption) after(c *callInfo, attempt *csAttempt) { + if x, ok := peer.FromContext(attempt.s.Context()); ok { + *o.PeerAddr = *x } } @@ -285,15 +278,16 @@ func (o FailFastCallOption) before(c *callInfo) error { c.failFast = o.FailFast return nil } -func (o FailFastCallOption) after(c *callInfo) {} +func (o FailFastCallOption) after(c *callInfo, attempt *csAttempt) {} -// MaxCallRecvMsgSize returns a CallOption which sets the maximum message size the client can receive. -func MaxCallRecvMsgSize(s int) CallOption { - return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: s} +// MaxCallRecvMsgSize returns a CallOption which sets the maximum message size +// in bytes the client can receive. +func MaxCallRecvMsgSize(bytes int) CallOption { + return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: bytes} } // MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message -// size the client can receive. +// size in bytes the client can receive. // This is an EXPERIMENTAL API. type MaxRecvMsgSizeCallOption struct { MaxRecvMsgSize int @@ -303,15 +297,16 @@ func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error { c.maxReceiveMessageSize = &o.MaxRecvMsgSize return nil } -func (o MaxRecvMsgSizeCallOption) after(c *callInfo) {} +func (o MaxRecvMsgSizeCallOption) after(c *callInfo, attempt *csAttempt) {} -// MaxCallSendMsgSize returns a CallOption which sets the maximum message size the client can send. -func MaxCallSendMsgSize(s int) CallOption { - return MaxSendMsgSizeCallOption{MaxSendMsgSize: s} +// MaxCallSendMsgSize returns a CallOption which sets the maximum message size +// in bytes the client can send. +func MaxCallSendMsgSize(bytes int) CallOption { + return MaxSendMsgSizeCallOption{MaxSendMsgSize: bytes} } // MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message -// size the client can send. +// size in bytes the client can send. // This is an EXPERIMENTAL API. type MaxSendMsgSizeCallOption struct { MaxSendMsgSize int @@ -321,7 +316,7 @@ func (o MaxSendMsgSizeCallOption) before(c *callInfo) error { c.maxSendMessageSize = &o.MaxSendMsgSize return nil } -func (o MaxSendMsgSizeCallOption) after(c *callInfo) {} +func (o MaxSendMsgSizeCallOption) after(c *callInfo, attempt *csAttempt) {} // PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials // for a call. @@ -340,7 +335,7 @@ func (o PerRPCCredsCallOption) before(c *callInfo) error { c.creds = o.Creds return nil } -func (o PerRPCCredsCallOption) after(c *callInfo) {} +func (o PerRPCCredsCallOption) after(c *callInfo, attempt *csAttempt) {} // UseCompressor returns a CallOption which sets the compressor used when // sending the request. If WithCompressor is also set, UseCompressor has @@ -361,7 +356,7 @@ func (o CompressorCallOption) before(c *callInfo) error { c.compressorType = o.CompressorType return nil } -func (o CompressorCallOption) after(c *callInfo) {} +func (o CompressorCallOption) after(c *callInfo, attempt *csAttempt) {} // CallContentSubtype returns a CallOption that will set the content-subtype // for a call. For example, if content-subtype is "json", the Content-Type over @@ -394,7 +389,7 @@ func (o ContentSubtypeCallOption) before(c *callInfo) error { c.contentSubtype = o.ContentSubtype return nil } -func (o ContentSubtypeCallOption) after(c *callInfo) {} +func (o ContentSubtypeCallOption) after(c *callInfo, attempt *csAttempt) {} // ForceCodec returns a CallOption that will set the given Codec to be // used for all request and response messages for a call. The result of calling @@ -426,7 +421,7 @@ func (o ForceCodecCallOption) before(c *callInfo) error { c.codec = o.Codec return nil } -func (o ForceCodecCallOption) after(c *callInfo) {} +func (o ForceCodecCallOption) after(c *callInfo, attempt *csAttempt) {} // CallCustomCodec behaves like ForceCodec, but accepts a grpc.Codec instead of // an encoding.Codec. @@ -448,7 +443,7 @@ func (o CustomCodecCallOption) before(c *callInfo) error { c.codec = o.Codec return nil } -func (o CustomCodecCallOption) after(c *callInfo) {} +func (o CustomCodecCallOption) after(c *callInfo, attempt *csAttempt) {} // MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory // used for buffering this RPC's requests for retry purposes. @@ -469,7 +464,7 @@ func (o MaxRetryRPCBufferSizeCallOption) before(c *callInfo) error { c.maxRetryRPCBufferSize = o.MaxRetryRPCBufferSize return nil } -func (o MaxRetryRPCBufferSizeCallOption) after(c *callInfo) {} +func (o MaxRetryRPCBufferSizeCallOption) after(c *callInfo, attempt *csAttempt) {} // The format of the payload: compressed or not? type payloadFormat uint8 diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go index 0d75cb109a0..c2c7cae6c5d 100644 --- a/vendor/google.golang.org/grpc/server.go +++ b/vendor/google.golang.org/grpc/server.go @@ -42,6 +42,7 @@ import ( "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/binarylog" "google.golang.org/grpc/internal/channelz" + "google.golang.org/grpc/internal/grpcrand" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/keepalive" @@ -87,6 +88,12 @@ type service struct { mdata interface{} } +type serverWorkerData struct { + st transport.ServerTransport + wg *sync.WaitGroup + stream *transport.Stream +} + // Server is a gRPC server to serve RPC requests. type Server struct { opts serverOptions @@ -107,6 +114,8 @@ type Server struct { channelzID int64 // channelz unique identification number czData *channelzData + + serverWorkerChannels []chan *serverWorkerData } type serverOptions struct { @@ -116,6 +125,8 @@ type serverOptions struct { dc Decompressor unaryInt UnaryServerInterceptor streamInt StreamServerInterceptor + chainUnaryInts []UnaryServerInterceptor + chainStreamInts []StreamServerInterceptor inTapHandle tap.ServerInHandle statsHandler stats.Handler maxConcurrentStreams uint32 @@ -131,6 +142,7 @@ type serverOptions struct { connectionTimeout time.Duration maxHeaderListSize *uint32 headerTableSize *uint32 + numServerWorkers uint32 } var defaultServerOptions = serverOptions{ @@ -311,6 +323,16 @@ func UnaryInterceptor(i UnaryServerInterceptor) ServerOption { }) } +// ChainUnaryInterceptor returns a ServerOption that specifies the chained interceptor +// for unary RPCs. The first interceptor will be the outer most, +// while the last interceptor will be the inner most wrapper around the real call. +// All unary interceptors added by this method will be chained. +func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption { + return newFuncServerOption(func(o *serverOptions) { + o.chainUnaryInts = append(o.chainUnaryInts, interceptors...) + }) +} + // StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the // server. Only one stream interceptor can be installed. func StreamInterceptor(i StreamServerInterceptor) ServerOption { @@ -322,6 +344,16 @@ func StreamInterceptor(i StreamServerInterceptor) ServerOption { }) } +// ChainStreamInterceptor returns a ServerOption that specifies the chained interceptor +// for streaming RPCs. The first interceptor will be the outer most, +// while the last interceptor will be the inner most wrapper around the real call. +// All stream interceptors added by this method will be chained. +func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption { + return newFuncServerOption(func(o *serverOptions) { + o.chainStreamInts = append(o.chainStreamInts, interceptors...) + }) +} + // InTapHandle returns a ServerOption that sets the tap handle for all the server // transport to be created. Only one can be installed. func InTapHandle(h tap.ServerInHandle) ServerOption { @@ -388,6 +420,66 @@ func HeaderTableSize(s uint32) ServerOption { }) } +// NumStreamWorkers returns a ServerOption that sets the number of worker +// goroutines that should be used to process incoming streams. Setting this to +// zero (default) will disable workers and spawn a new goroutine for each +// stream. +// +// This API is EXPERIMENTAL. +func NumStreamWorkers(numServerWorkers uint32) ServerOption { + // TODO: If/when this API gets stabilized (i.e. stream workers become the + // only way streams are processed), change the behavior of the zero value to + // a sane default. Preliminary experiments suggest that a value equal to the + // number of CPUs available is most performant; requires thorough testing. + return newFuncServerOption(func(o *serverOptions) { + o.numServerWorkers = numServerWorkers + }) +} + +// serverWorkerResetThreshold defines how often the stack must be reset. Every +// N requests, by spawning a new goroutine in its place, a worker can reset its +// stack so that large stacks don't live in memory forever. 2^16 should allow +// each goroutine stack to live for at least a few seconds in a typical +// workload (assuming a QPS of a few thousand requests/sec). +const serverWorkerResetThreshold = 1 << 16 + +// serverWorkers blocks on a *transport.Stream channel forever and waits for +// data to be fed by serveStreams. This allows different requests to be +// processed by the same goroutine, removing the need for expensive stack +// re-allocations (see the runtime.morestack problem [1]). +// +// [1] https://github.com/golang/go/issues/18138 +func (s *Server) serverWorker(ch chan *serverWorkerData) { + // To make sure all server workers don't reset at the same time, choose a + // random number of iterations before resetting. + threshold := serverWorkerResetThreshold + grpcrand.Intn(serverWorkerResetThreshold) + for completed := 0; completed < threshold; completed++ { + data, ok := <-ch + if !ok { + return + } + s.handleStream(data.st, data.stream, s.traceInfo(data.st, data.stream)) + data.wg.Done() + } + go s.serverWorker(ch) +} + +// initServerWorkers creates worker goroutines and channels to process incoming +// connections to reduce the time spent overall on runtime.morestack. +func (s *Server) initServerWorkers() { + s.serverWorkerChannels = make([]chan *serverWorkerData, s.opts.numServerWorkers) + for i := uint32(0); i < s.opts.numServerWorkers; i++ { + s.serverWorkerChannels[i] = make(chan *serverWorkerData) + go s.serverWorker(s.serverWorkerChannels[i]) + } +} + +func (s *Server) stopServerWorkers() { + for i := uint32(0); i < s.opts.numServerWorkers; i++ { + close(s.serverWorkerChannels[i]) + } +} + // NewServer creates a gRPC server which has no service registered and has not // started to accept requests yet. func NewServer(opt ...ServerOption) *Server { @@ -404,12 +496,18 @@ func NewServer(opt ...ServerOption) *Server { done: grpcsync.NewEvent(), czData: new(channelzData), } + chainUnaryServerInterceptors(s) + chainStreamServerInterceptors(s) s.cv = sync.NewCond(&s.mu) if EnableTracing { _, file, line, _ := runtime.Caller(1) s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line)) } + if s.opts.numServerWorkers > 0 { + s.initServerWorkers() + } + if channelz.IsOn() { s.channelzID = channelz.RegisterServer(&channelzServer{s}, "") } @@ -658,7 +756,7 @@ func (s *Server) handleRawConn(rawConn net.Conn) { s.mu.Lock() s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err) s.mu.Unlock() - grpclog.Warningf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err) + channelz.Warningf(s.channelzID, "grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err) rawConn.Close() } rawConn.SetDeadline(time.Time{}) @@ -705,7 +803,7 @@ func (s *Server) newHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) tr s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err) s.mu.Unlock() c.Close() - grpclog.Warningln("grpc: Server.Serve failed to create ServerTransport: ", err) + channelz.Warning(s.channelzID, "grpc: Server.Serve failed to create ServerTransport: ", err) return nil } @@ -715,12 +813,27 @@ func (s *Server) newHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) tr func (s *Server) serveStreams(st transport.ServerTransport) { defer st.Close() var wg sync.WaitGroup + + var roundRobinCounter uint32 st.HandleStreams(func(stream *transport.Stream) { wg.Add(1) - go func() { - defer wg.Done() - s.handleStream(st, stream, s.traceInfo(st, stream)) - }() + if s.opts.numServerWorkers > 0 { + data := &serverWorkerData{st: st, wg: &wg, stream: stream} + select { + case s.serverWorkerChannels[atomic.AddUint32(&roundRobinCounter, 1)%s.opts.numServerWorkers] <- data: + default: + // If all stream workers are busy, fallback to the default code path. + go func() { + s.handleStream(st, stream, s.traceInfo(st, stream)) + wg.Done() + }() + } + } else { + go func() { + defer wg.Done() + s.handleStream(st, stream, s.traceInfo(st, stream)) + }() + } }, func(ctx context.Context, method string) context.Context { if !EnableTracing { return ctx @@ -844,12 +957,12 @@ func (s *Server) incrCallsFailed() { func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options, comp encoding.Compressor) error { data, err := encode(s.getCodec(stream.ContentSubtype()), msg) if err != nil { - grpclog.Errorln("grpc: server failed to encode response: ", err) + channelz.Error(s.channelzID, "grpc: server failed to encode response: ", err) return err } compData, err := compress(data, cp, comp) if err != nil { - grpclog.Errorln("grpc: server failed to compress response: ", err) + channelz.Error(s.channelzID, "grpc: server failed to compress response: ", err) return err } hdr, payload := msgHeader(data, compData) @@ -864,6 +977,40 @@ func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Str return err } +// chainUnaryServerInterceptors chains all unary server interceptors into one. +func chainUnaryServerInterceptors(s *Server) { + // Prepend opts.unaryInt to the chaining interceptors if it exists, since unaryInt will + // be executed before any other chained interceptors. + interceptors := s.opts.chainUnaryInts + if s.opts.unaryInt != nil { + interceptors = append([]UnaryServerInterceptor{s.opts.unaryInt}, s.opts.chainUnaryInts...) + } + + var chainedInt UnaryServerInterceptor + if len(interceptors) == 0 { + chainedInt = nil + } else if len(interceptors) == 1 { + chainedInt = interceptors[0] + } else { + chainedInt = func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (interface{}, error) { + return interceptors[0](ctx, req, info, getChainUnaryHandler(interceptors, 0, info, handler)) + } + } + + s.opts.unaryInt = chainedInt +} + +// getChainUnaryHandler recursively generate the chained UnaryHandler +func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info *UnaryServerInfo, finalHandler UnaryHandler) UnaryHandler { + if curr == len(interceptors)-1 { + return finalHandler + } + + return func(ctx context.Context, req interface{}) (interface{}, error) { + return interceptors[curr+1](ctx, req, info, getChainUnaryHandler(interceptors, curr+1, info, finalHandler)) + } +} + func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, md *MethodDesc, trInfo *traceInfo) (err error) { sh := s.opts.statsHandler if sh != nil || trInfo != nil || channelz.IsOn() { @@ -989,7 +1136,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. if err != nil { if st, ok := status.FromError(err); ok { if e := t.WriteStatus(stream, st); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) + channelz.Warningf(s.channelzID, "grpc: Server.processUnaryRPC failed to write status %v", e) } } return err @@ -1034,7 +1181,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. trInfo.tr.SetError() } if e := t.WriteStatus(stream, appStatus); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status: %v", e) + channelz.Warningf(s.channelzID, "grpc: Server.processUnaryRPC failed to write status: %v", e) } if binlog != nil { if h, _ := stream.Header(); h.Len() > 0 { @@ -1061,9 +1208,9 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. // The entire stream is done (for unary RPC only). return err } - if s, ok := status.FromError(err); ok { - if e := t.WriteStatus(stream, s); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status: %v", e) + if sts, ok := status.FromError(err); ok { + if e := t.WriteStatus(stream, sts); e != nil { + channelz.Warningf(s.channelzID, "grpc: Server.processUnaryRPC failed to write status: %v", e) } } else { switch st := err.(type) { @@ -1113,6 +1260,40 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. return err } +// chainStreamServerInterceptors chains all stream server interceptors into one. +func chainStreamServerInterceptors(s *Server) { + // Prepend opts.streamInt to the chaining interceptors if it exists, since streamInt will + // be executed before any other chained interceptors. + interceptors := s.opts.chainStreamInts + if s.opts.streamInt != nil { + interceptors = append([]StreamServerInterceptor{s.opts.streamInt}, s.opts.chainStreamInts...) + } + + var chainedInt StreamServerInterceptor + if len(interceptors) == 0 { + chainedInt = nil + } else if len(interceptors) == 1 { + chainedInt = interceptors[0] + } else { + chainedInt = func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error { + return interceptors[0](srv, ss, info, getChainStreamHandler(interceptors, 0, info, handler)) + } + } + + s.opts.streamInt = chainedInt +} + +// getChainStreamHandler recursively generate the chained StreamHandler +func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, info *StreamServerInfo, finalHandler StreamHandler) StreamHandler { + if curr == len(interceptors)-1 { + return finalHandler + } + + return func(srv interface{}, ss ServerStream) error { + return interceptors[curr+1](srv, ss, info, getChainStreamHandler(interceptors, curr+1, info, finalHandler)) + } +} + func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, sd *StreamDesc, trInfo *traceInfo) (err error) { if channelz.IsOn() { s.incrCallsStarted() @@ -1297,7 +1478,7 @@ func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Str trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) trInfo.tr.SetError() } - grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err) + channelz.Warningf(s.channelzID, "grpc: Server.handleStream failed to write status: %v", err) } if trInfo != nil { trInfo.tr.Finish() @@ -1338,7 +1519,7 @@ func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Str trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) trInfo.tr.SetError() } - grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err) + channelz.Warningf(s.channelzID, "grpc: Server.handleStream failed to write status: %v", err) } if trInfo != nil { trInfo.tr.Finish() @@ -1415,6 +1596,9 @@ func (s *Server) Stop() { for c := range st { c.Close() } + if s.opts.numServerWorkers > 0 { + s.stopServerWorkers() + } s.mu.Lock() if s.events != nil { diff --git a/vendor/google.golang.org/grpc/service_config.go b/vendor/google.golang.org/grpc/service_config.go index 5a80a575a5e..3132a66cd68 100644 --- a/vendor/google.golang.org/grpc/service_config.go +++ b/vendor/google.golang.org/grpc/service_config.go @@ -21,14 +21,15 @@ package grpc import ( "encoding/json" "fmt" + "reflect" "strconv" "strings" "time" - "google.golang.org/grpc/balancer" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal" + internalserviceconfig "google.golang.org/grpc/internal/serviceconfig" "google.golang.org/grpc/serviceconfig" ) @@ -79,7 +80,7 @@ type ServiceConfig struct { serviceconfig.Config // LB is the load balancer the service providers recommends. The balancer - // specified via grpc.WithBalancer will override this. This is deprecated; + // specified via grpc.WithBalancerName will override this. This is deprecated; // lbConfigs is preferred. If lbConfig and LB are both present, lbConfig // will be used. LB *string @@ -249,12 +250,10 @@ type jsonMC struct { RetryPolicy *jsonRetryPolicy } -type loadBalancingConfig map[string]json.RawMessage - // TODO(lyuxuan): delete this struct after cleaning up old service config implementation. type jsonSC struct { LoadBalancingPolicy *string - LoadBalancingConfig *[]loadBalancingConfig + LoadBalancingConfig *internalserviceconfig.BalancerConfig MethodConfig *[]jsonMC RetryThrottling *retryThrottlingPolicy HealthCheckConfig *healthCheckConfig @@ -280,40 +279,10 @@ func parseServiceConfig(js string) *serviceconfig.ParseResult { healthCheckConfig: rsc.HealthCheckConfig, rawJSONString: js, } - if rsc.LoadBalancingConfig != nil { - for i, lbcfg := range *rsc.LoadBalancingConfig { - if len(lbcfg) != 1 { - err := fmt.Errorf("invalid loadBalancingConfig: entry %v does not contain exactly 1 policy/config pair: %q", i, lbcfg) - grpclog.Warningf(err.Error()) - return &serviceconfig.ParseResult{Err: err} - } - var name string - var jsonCfg json.RawMessage - for name, jsonCfg = range lbcfg { - } - builder := balancer.Get(name) - if builder == nil { - continue - } - sc.lbConfig = &lbConfig{name: name} - if parser, ok := builder.(balancer.ConfigParser); ok { - var err error - sc.lbConfig.cfg, err = parser.ParseConfig(jsonCfg) - if err != nil { - return &serviceconfig.ParseResult{Err: fmt.Errorf("error parsing loadBalancingConfig for policy %q: %v", name, err)} - } - } else if string(jsonCfg) != "{}" { - grpclog.Warningf("non-empty balancer configuration %q, but balancer does not implement ParseConfig", string(jsonCfg)) - } - break - } - if sc.lbConfig == nil { - // We had a loadBalancingConfig field but did not encounter a - // supported policy. The config is considered invalid in this - // case. - err := fmt.Errorf("invalid loadBalancingConfig: no supported policies found") - grpclog.Warningf(err.Error()) - return &serviceconfig.ParseResult{Err: err} + if c := rsc.LoadBalancingConfig; c != nil { + sc.lbConfig = &lbConfig{ + name: c.Name, + cfg: c.Config, } } @@ -432,3 +401,34 @@ func getMaxSize(mcMax, doptMax *int, defaultVal int) *int { func newInt(b int) *int { return &b } + +func init() { + internal.EqualServiceConfigForTesting = equalServiceConfig +} + +// equalServiceConfig compares two configs. The rawJSONString field is ignored, +// because they may diff in white spaces. +// +// If any of them is NOT *ServiceConfig, return false. +func equalServiceConfig(a, b serviceconfig.Config) bool { + aa, ok := a.(*ServiceConfig) + if !ok { + return false + } + bb, ok := b.(*ServiceConfig) + if !ok { + return false + } + aaRaw := aa.rawJSONString + aa.rawJSONString = "" + bbRaw := bb.rawJSONString + bb.rawJSONString = "" + defer func() { + aa.rawJSONString = aaRaw + bb.rawJSONString = bbRaw + }() + // Using reflect.DeepEqual instead of cmp.Equal because many balancer + // configs are unexported, and cmp.Equal cannot compare unexported fields + // from unexported structs. + return reflect.DeepEqual(aa, bb) +} diff --git a/vendor/google.golang.org/grpc/stats/stats.go b/vendor/google.golang.org/grpc/stats/stats.go index 9e22c393f16..63e476ee7ff 100644 --- a/vendor/google.golang.org/grpc/stats/stats.go +++ b/vendor/google.golang.org/grpc/stats/stats.go @@ -16,8 +16,6 @@ * */ -//go:generate protoc --go_out=plugins=grpc:. grpc_testing/test.proto - // Package stats is for collecting and reporting various network and RPC stats. // This package is for monitoring purpose only. All fields are read-only. // All APIs are experimental. @@ -81,6 +79,10 @@ type InHeader struct { Client bool // WireLength is the wire length of header. WireLength int + // Compression is the compression algorithm used for the RPC. + Compression string + // Header contains the header metadata received. + Header metadata.MD // The following fields are valid only if Client is false. // FullMethod is the full RPC method string, i.e., /package.service/method. @@ -89,10 +91,6 @@ type InHeader struct { RemoteAddr net.Addr // LocalAddr is the local address of the corresponding connection. LocalAddr net.Addr - // Compression is the compression algorithm used for the RPC. - Compression string - // Header contains the header metadata received. - Header metadata.MD } // IsClient indicates if the stats information is from client side. @@ -141,6 +139,10 @@ func (s *OutPayload) isRPCStats() {} type OutHeader struct { // Client is true if this OutHeader is from client side. Client bool + // Compression is the compression algorithm used for the RPC. + Compression string + // Header contains the header metadata sent. + Header metadata.MD // The following fields are valid only if Client is true. // FullMethod is the full RPC method string, i.e., /package.service/method. @@ -149,10 +151,6 @@ type OutHeader struct { RemoteAddr net.Addr // LocalAddr is the local address of the corresponding connection. LocalAddr net.Addr - // Compression is the compression algorithm used for the RPC. - Compression string - // Header contains the header metadata sent. - Header metadata.MD } // IsClient indicates if this stats information is from client side. @@ -165,6 +163,9 @@ type OutTrailer struct { // Client is true if this OutTrailer is from client side. Client bool // WireLength is the wire length of trailer. + // + // Deprecated: This field is never set. The length is not known when this message is + // emitted because the trailer fields are compressed with hpack after that. WireLength int // Trailer contains the trailer metadata sent to the client. This // field is only valid if this OutTrailer is from the server side. diff --git a/vendor/google.golang.org/grpc/status/status.go b/vendor/google.golang.org/grpc/status/status.go index a1348e9b16b..01e182c306c 100644 --- a/vendor/google.golang.org/grpc/status/status.go +++ b/vendor/google.golang.org/grpc/status/status.go @@ -29,88 +29,23 @@ package status import ( "context" - "errors" "fmt" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes" spb "google.golang.org/genproto/googleapis/rpc/status" + "google.golang.org/grpc/codes" - "google.golang.org/grpc/internal" + "google.golang.org/grpc/internal/status" ) -func init() { - internal.StatusRawProto = statusRawProto -} - -func statusRawProto(s *Status) *spb.Status { return s.s } - -// statusError is an alias of a status proto. It implements error and Status, -// and a nil statusError should never be returned by this package. -type statusError spb.Status - -func (se *statusError) Error() string { - p := (*spb.Status)(se) - return fmt.Sprintf("rpc error: code = %s desc = %s", codes.Code(p.GetCode()), p.GetMessage()) -} - -func (se *statusError) GRPCStatus() *Status { - return &Status{s: (*spb.Status)(se)} -} - -// Is implements future error.Is functionality. -// A statusError is equivalent if the code and message are identical. -func (se *statusError) Is(target error) bool { - tse, ok := target.(*statusError) - if !ok { - return false - } - - return proto.Equal((*spb.Status)(se), (*spb.Status)(tse)) -} - -// Status represents an RPC status code, message, and details. It is immutable -// and should be created with New, Newf, or FromProto. -type Status struct { - s *spb.Status -} - -// Code returns the status code contained in s. -func (s *Status) Code() codes.Code { - if s == nil || s.s == nil { - return codes.OK - } - return codes.Code(s.s.Code) -} - -// Message returns the message contained in s. -func (s *Status) Message() string { - if s == nil || s.s == nil { - return "" - } - return s.s.Message -} - -// Proto returns s's status as an spb.Status proto message. -func (s *Status) Proto() *spb.Status { - if s == nil { - return nil - } - return proto.Clone(s.s).(*spb.Status) -} - -// Err returns an immutable error representing s; returns nil if s.Code() is -// OK. -func (s *Status) Err() error { - if s.Code() == codes.OK { - return nil - } - return (*statusError)(s.s) -} +// Status references google.golang.org/grpc/internal/status. It represents an +// RPC status code, message, and details. It is immutable and should be +// created with New, Newf, or FromProto. +// https://godoc.org/google.golang.org/grpc/internal/status +type Status = status.Status // New returns a Status representing c and msg. func New(c codes.Code, msg string) *Status { - return &Status{s: &spb.Status{Code: int32(c), Message: msg}} + return status.New(c, msg) } // Newf returns New(c, fmt.Sprintf(format, a...)). @@ -135,7 +70,7 @@ func ErrorProto(s *spb.Status) error { // FromProto returns a Status representing s. func FromProto(s *spb.Status) *Status { - return &Status{s: proto.Clone(s).(*spb.Status)} + return status.FromProto(s) } // FromError returns a Status representing err if it was produced from this @@ -160,42 +95,6 @@ func Convert(err error) *Status { return s } -// WithDetails returns a new status with the provided details messages appended to the status. -// If any errors are encountered, it returns nil and the first error encountered. -func (s *Status) WithDetails(details ...proto.Message) (*Status, error) { - if s.Code() == codes.OK { - return nil, errors.New("no error details for status with code OK") - } - // s.Code() != OK implies that s.Proto() != nil. - p := s.Proto() - for _, detail := range details { - any, err := ptypes.MarshalAny(detail) - if err != nil { - return nil, err - } - p.Details = append(p.Details, any) - } - return &Status{s: p}, nil -} - -// Details returns a slice of details messages attached to the status. -// If a detail cannot be decoded, the error is returned in place of the detail. -func (s *Status) Details() []interface{} { - if s == nil || s.s == nil { - return nil - } - details := make([]interface{}, 0, len(s.s.Details)) - for _, any := range s.s.Details { - detail := &ptypes.DynamicAny{} - if err := ptypes.UnmarshalAny(any, detail); err != nil { - details = append(details, err) - continue - } - details = append(details, detail.Message) - } - return details -} - // Code returns the Code of the error if it is a Status error, codes.OK if err // is nil, or codes.Unknown otherwise. func Code(err error) codes.Code { diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go index bb99940e36f..629af76bdfa 100644 --- a/vendor/google.golang.org/grpc/stream.go +++ b/vendor/google.golang.org/grpc/stream.go @@ -31,7 +31,6 @@ import ( "google.golang.org/grpc/balancer" "google.golang.org/grpc/codes" "google.golang.org/grpc/encoding" - "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal/balancerload" "google.golang.org/grpc/internal/binarylog" "google.golang.org/grpc/internal/channelz" @@ -278,7 +277,6 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth } cs.binlog = binarylog.GetMethodLogger(method) - cs.callInfo.stream = cs // Only this initial attempt has stats/tracing. // TODO(dfawley): move to newAttempt when per-attempt stats are implemented. if err := cs.newAttemptLocked(sh, trInfo); err != nil { @@ -366,6 +364,11 @@ func (a *csAttempt) newStream() error { cs.callHdr.PreviousAttempts = cs.numRetries s, err := a.t.NewStream(cs.ctx, cs.callHdr) if err != nil { + if _, ok := err.(transport.PerformedIOError); ok { + // Return without converting to an RPC error so retry code can + // inspect. + return err + } return toRPCErr(err) } cs.attempt.s = s @@ -461,11 +464,21 @@ func (cs *clientStream) commitAttempt() { // shouldRetry returns nil if the RPC should be retried; otherwise it returns // the error that should be returned by the operation. func (cs *clientStream) shouldRetry(err error) error { - if cs.attempt.s == nil && !cs.callInfo.failFast { - // In the event of any error from NewStream (attempt.s == nil), we - // never attempted to write anything to the wire, so we can retry - // indefinitely for non-fail-fast RPCs. - return nil + unprocessed := false + if cs.attempt.s == nil { + pioErr, ok := err.(transport.PerformedIOError) + if ok { + // Unwrap error. + err = toRPCErr(pioErr.Err) + } else { + unprocessed = true + } + if !ok && !cs.callInfo.failFast { + // In the event of a non-IO operation error from NewStream, we + // never attempted to write anything to the wire, so we can retry + // indefinitely for non-fail-fast RPCs. + return nil + } } if cs.finished || cs.committed { // RPC is finished or committed; cannot retry. @@ -474,13 +487,12 @@ func (cs *clientStream) shouldRetry(err error) error { // Wait for the trailers. if cs.attempt.s != nil { <-cs.attempt.s.Done() + unprocessed = cs.attempt.s.Unprocessed() } - if cs.firstAttempt && (cs.attempt.s == nil || cs.attempt.s.Unprocessed()) { + if cs.firstAttempt && unprocessed { // First attempt, stream unprocessed: transparently retry. - cs.firstAttempt = false return nil } - cs.firstAttempt = false if cs.cc.dopts.disableRetry { return err } @@ -498,13 +510,13 @@ func (cs *clientStream) shouldRetry(err error) error { if len(sps) == 1 { var e error if pushback, e = strconv.Atoi(sps[0]); e != nil || pushback < 0 { - grpclog.Infof("Server retry pushback specified to abort (%q).", sps[0]) + channelz.Infof(cs.cc.channelzID, "Server retry pushback specified to abort (%q).", sps[0]) cs.retryThrottler.throttle() // This counts as a failure for throttling. return err } hasPushback = true } else if len(sps) > 1 { - grpclog.Warningf("Server retry pushback specified multiple values (%q); not retrying.", sps) + channelz.Warningf(cs.cc.channelzID, "Server retry pushback specified multiple values (%q); not retrying.", sps) cs.retryThrottler.throttle() // This counts as a failure for throttling. return err } @@ -566,6 +578,7 @@ func (cs *clientStream) retryLocked(lastErr error) error { cs.commitAttemptLocked() return err } + cs.firstAttempt = false if err := cs.newAttemptLocked(nil, nil); err != nil { return err } @@ -800,6 +813,15 @@ func (cs *clientStream) finish(err error) { } cs.finished = true cs.commitAttemptLocked() + if cs.attempt != nil { + cs.attempt.finish(err) + // after functions all rely upon having a stream. + if cs.attempt.s != nil { + for _, o := range cs.opts { + o.after(cs.callInfo, cs.attempt) + } + } + } cs.mu.Unlock() // For binary logging. only log cancel in finish (could be caused by RPC ctx // canceled or ClientConn closed). Trailer will be logged in RecvMsg. @@ -821,15 +843,6 @@ func (cs *clientStream) finish(err error) { cs.cc.incrCallsSucceeded() } } - if cs.attempt != nil { - cs.attempt.finish(err) - // after functions all rely upon having a stream. - if cs.attempt.s != nil { - for _, o := range cs.opts { - o.after(cs.callInfo) - } - } - } cs.cancel() } @@ -1067,7 +1080,6 @@ func newNonRetryClientStream(ctx context.Context, desc *StreamDesc, method strin t: t, } - as.callInfo.stream = as s, err := as.t.NewStream(as.ctx, as.callHdr) if err != nil { err = toRPCErr(err) diff --git a/vendor/google.golang.org/grpc/test/bufconn/bufconn.go b/vendor/google.golang.org/grpc/test/bufconn/bufconn.go deleted file mode 100644 index 168cdb8578d..00000000000 --- a/vendor/google.golang.org/grpc/test/bufconn/bufconn.go +++ /dev/null @@ -1,308 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * 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 bufconn provides a net.Conn implemented by a buffer and related -// dialing and listening functionality. -package bufconn - -import ( - "fmt" - "io" - "net" - "sync" - "time" -) - -// Listener implements a net.Listener that creates local, buffered net.Conns -// via its Accept and Dial method. -type Listener struct { - mu sync.Mutex - sz int - ch chan net.Conn - done chan struct{} -} - -// Implementation of net.Error providing timeout -type netErrorTimeout struct { - error -} - -func (e netErrorTimeout) Timeout() bool { return true } -func (e netErrorTimeout) Temporary() bool { return false } - -var errClosed = fmt.Errorf("closed") -var errTimeout net.Error = netErrorTimeout{error: fmt.Errorf("i/o timeout")} - -// Listen returns a Listener that can only be contacted by its own Dialers and -// creates buffered connections between the two. -func Listen(sz int) *Listener { - return &Listener{sz: sz, ch: make(chan net.Conn), done: make(chan struct{})} -} - -// Accept blocks until Dial is called, then returns a net.Conn for the server -// half of the connection. -func (l *Listener) Accept() (net.Conn, error) { - select { - case <-l.done: - return nil, errClosed - case c := <-l.ch: - return c, nil - } -} - -// Close stops the listener. -func (l *Listener) Close() error { - l.mu.Lock() - defer l.mu.Unlock() - select { - case <-l.done: - // Already closed. - break - default: - close(l.done) - } - return nil -} - -// Addr reports the address of the listener. -func (l *Listener) Addr() net.Addr { return addr{} } - -// Dial creates an in-memory full-duplex network connection, unblocks Accept by -// providing it the server half of the connection, and returns the client half -// of the connection. -func (l *Listener) Dial() (net.Conn, error) { - p1, p2 := newPipe(l.sz), newPipe(l.sz) - select { - case <-l.done: - return nil, errClosed - case l.ch <- &conn{p1, p2}: - return &conn{p2, p1}, nil - } -} - -type pipe struct { - mu sync.Mutex - - // buf contains the data in the pipe. It is a ring buffer of fixed capacity, - // with r and w pointing to the offset to read and write, respsectively. - // - // Data is read between [r, w) and written to [w, r), wrapping around the end - // of the slice if necessary. - // - // The buffer is empty if r == len(buf), otherwise if r == w, it is full. - // - // w and r are always in the range [0, cap(buf)) and [0, len(buf)]. - buf []byte - w, r int - - wwait sync.Cond - rwait sync.Cond - - // Indicate that a write/read timeout has occurred - wtimedout bool - rtimedout bool - - wtimer *time.Timer - rtimer *time.Timer - - closed bool - writeClosed bool -} - -func newPipe(sz int) *pipe { - p := &pipe{buf: make([]byte, 0, sz)} - p.wwait.L = &p.mu - p.rwait.L = &p.mu - - p.wtimer = time.AfterFunc(0, func() {}) - p.rtimer = time.AfterFunc(0, func() {}) - return p -} - -func (p *pipe) empty() bool { - return p.r == len(p.buf) -} - -func (p *pipe) full() bool { - return p.r < len(p.buf) && p.r == p.w -} - -func (p *pipe) Read(b []byte) (n int, err error) { - p.mu.Lock() - defer p.mu.Unlock() - // Block until p has data. - for { - if p.closed { - return 0, io.ErrClosedPipe - } - if !p.empty() { - break - } - if p.writeClosed { - return 0, io.EOF - } - if p.rtimedout { - return 0, errTimeout - } - - p.rwait.Wait() - } - wasFull := p.full() - - n = copy(b, p.buf[p.r:len(p.buf)]) - p.r += n - if p.r == cap(p.buf) { - p.r = 0 - p.buf = p.buf[:p.w] - } - - // Signal a blocked writer, if any - if wasFull { - p.wwait.Signal() - } - - return n, nil -} - -func (p *pipe) Write(b []byte) (n int, err error) { - p.mu.Lock() - defer p.mu.Unlock() - if p.closed { - return 0, io.ErrClosedPipe - } - for len(b) > 0 { - // Block until p is not full. - for { - if p.closed || p.writeClosed { - return 0, io.ErrClosedPipe - } - if !p.full() { - break - } - if p.wtimedout { - return 0, errTimeout - } - - p.wwait.Wait() - } - wasEmpty := p.empty() - - end := cap(p.buf) - if p.w < p.r { - end = p.r - } - x := copy(p.buf[p.w:end], b) - b = b[x:] - n += x - p.w += x - if p.w > len(p.buf) { - p.buf = p.buf[:p.w] - } - if p.w == cap(p.buf) { - p.w = 0 - } - - // Signal a blocked reader, if any. - if wasEmpty { - p.rwait.Signal() - } - } - return n, nil -} - -func (p *pipe) Close() error { - p.mu.Lock() - defer p.mu.Unlock() - p.closed = true - // Signal all blocked readers and writers to return an error. - p.rwait.Broadcast() - p.wwait.Broadcast() - return nil -} - -func (p *pipe) closeWrite() error { - p.mu.Lock() - defer p.mu.Unlock() - p.writeClosed = true - // Signal all blocked readers and writers to return an error. - p.rwait.Broadcast() - p.wwait.Broadcast() - return nil -} - -type conn struct { - io.Reader - io.Writer -} - -func (c *conn) Close() error { - err1 := c.Reader.(*pipe).Close() - err2 := c.Writer.(*pipe).closeWrite() - if err1 != nil { - return err1 - } - return err2 -} - -func (c *conn) SetDeadline(t time.Time) error { - c.SetReadDeadline(t) - c.SetWriteDeadline(t) - return nil -} - -func (c *conn) SetReadDeadline(t time.Time) error { - p := c.Reader.(*pipe) - p.mu.Lock() - defer p.mu.Unlock() - p.rtimer.Stop() - p.rtimedout = false - if !t.IsZero() { - p.rtimer = time.AfterFunc(time.Until(t), func() { - p.mu.Lock() - defer p.mu.Unlock() - p.rtimedout = true - p.rwait.Broadcast() - }) - } - return nil -} - -func (c *conn) SetWriteDeadline(t time.Time) error { - p := c.Writer.(*pipe) - p.mu.Lock() - defer p.mu.Unlock() - p.wtimer.Stop() - p.wtimedout = false - if !t.IsZero() { - p.wtimer = time.AfterFunc(time.Until(t), func() { - p.mu.Lock() - defer p.mu.Unlock() - p.wtimedout = true - p.wwait.Broadcast() - }) - } - return nil -} - -func (*conn) LocalAddr() net.Addr { return addr{} } -func (*conn) RemoteAddr() net.Addr { return addr{} } - -type addr struct{} - -func (addr) Network() string { return "bufconn" } -func (addr) String() string { return "bufconn" } diff --git a/vendor/google.golang.org/grpc/version.go b/vendor/google.golang.org/grpc/version.go index 1a831b159ab..c7e67b8476d 100644 --- a/vendor/google.golang.org/grpc/version.go +++ b/vendor/google.golang.org/grpc/version.go @@ -19,4 +19,4 @@ package grpc // Version is the current grpc version. -const Version = "1.27.1" +const Version = "1.30.0" diff --git a/vendor/google.golang.org/grpc/vet.sh b/vendor/google.golang.org/grpc/vet.sh index 0e737072781..f0a67298a5b 100644 --- a/vendor/google.golang.org/grpc/vet.sh +++ b/vendor/google.golang.org/grpc/vet.sh @@ -1,20 +1,22 @@ #!/bin/bash -if [[ `uname -a` = *"Darwin"* ]]; then - echo "It seems you are running on Mac. This script does not work on Mac. See https://github.com/grpc/grpc-go/issues/2047" - exit 1 -fi - set -ex # Exit on error; debugging enabled. set -o pipefail # Fail a pipe if any sub-command fails. +# not makes sure the command passed to it does not exit with a return code of 0. +not() { + # This is required instead of the earlier (! $COMMAND) because subshells and + # pipefail don't work the same on Darwin as in Linux. + ! "$@" +} + die() { echo "$@" >&2 exit 1 } fail_on_output() { - tee /dev/stderr | (! read) + tee /dev/stderr | not read } # Check to make sure it's safe to modify the user's git repo. @@ -37,8 +39,7 @@ if [[ "$1" = "-install" ]]; then golang.org/x/lint/golint \ golang.org/x/tools/cmd/goimports \ honnef.co/go/tools/cmd/staticcheck \ - github.com/client9/misspell/cmd/misspell \ - github.com/golang/protobuf/protoc-gen-go + github.com/client9/misspell/cmd/misspell popd else # Ye olde `go get` incantation. @@ -48,8 +49,7 @@ if [[ "$1" = "-install" ]]; then golang.org/x/lint/golint \ golang.org/x/tools/cmd/goimports \ honnef.co/go/tools/cmd/staticcheck \ - github.com/client9/misspell/cmd/misspell \ - github.com/golang/protobuf/protoc-gen-go + github.com/client9/misspell/cmd/misspell fi if [[ -z "${VET_SKIP_PROTO}" ]]; then if [[ "${TRAVIS}" = "true" ]]; then @@ -60,7 +60,7 @@ if [[ "$1" = "-install" ]]; then unzip ${PROTOC_FILENAME} bin/protoc --version popd - elif ! which protoc > /dev/null; then + elif not which protoc > /dev/null; then die "Please install protoc into your path" fi fi @@ -70,21 +70,24 @@ elif [[ "$#" -ne 0 ]]; then fi # - Ensure all source files contain a copyright message. -(! git grep -L "\(Copyright [0-9]\{4,\} gRPC authors\)\|DO NOT EDIT" -- '*.go') +not git grep -L "\(Copyright [0-9]\{4,\} gRPC authors\)\|DO NOT EDIT" -- '*.go' # - Make sure all tests in grpc and grpc/test use leakcheck via Teardown. -(! grep 'func Test[^(]' *_test.go) -(! grep 'func Test[^(]' test/*.go) +not grep 'func Test[^(]' *_test.go +not grep 'func Test[^(]' test/*.go # - Do not import x/net/context. -(! git grep -l 'x/net/context' -- "*.go") +not git grep -l 'x/net/context' -- "*.go" # - Do not import math/rand for real library code. Use internal/grpcrand for # thread safety. -git grep -l '"math/rand"' -- "*.go" 2>&1 | (! grep -v '^examples\|^stress\|grpcrand\|^benchmark\|wrr_test') +git grep -l '"math/rand"' -- "*.go" 2>&1 | not grep -v '^examples\|^stress\|grpcrand\|^benchmark\|wrr_test' # - Ensure all ptypes proto packages are renamed when importing. -(! git grep "\(import \|^\s*\)\"github.com/golang/protobuf/ptypes/" -- "*.go") +not git grep "\(import \|^\s*\)\"github.com/golang/protobuf/ptypes/" -- "*.go" + +# - Ensure all xds proto imports are renamed to *pb or *grpc. +git grep '"github.com/envoyproxy/go-control-plane/envoy' -- '*.go' | not grep -v 'pb "\|grpc "' # - Check imports that are illegal in appengine (until Go 1.11). # TODO: Remove when we drop Go 1.10 support @@ -92,9 +95,9 @@ go list -f {{.Dir}} ./... | xargs go run test/go_vet/vet.go # - gofmt, goimports, golint (with exceptions for generated code), go vet. gofmt -s -d -l . 2>&1 | fail_on_output -goimports -l . 2>&1 | (! grep -vE "(_mock|\.pb)\.go") -golint ./... 2>&1 | (! grep -vE "(_mock|\.pb)\.go:") -go vet -all . +goimports -l . 2>&1 | not grep -vE "(_mock|\.pb)\.go" +golint ./... 2>&1 | not grep -vE "(_mock|\.pb)\.go:" +go vet -all ./... misspell -error . @@ -119,16 +122,15 @@ fi SC_OUT="$(mktemp)" staticcheck -go 1.9 -checks 'inherit,-ST1015' ./... > "${SC_OUT}" || true # Error if anything other than deprecation warnings are printed. -(! grep -v "is deprecated:.*SA1019" "${SC_OUT}") +not grep -v "is deprecated:.*SA1019" "${SC_OUT}" # Only ignore the following deprecated types/fields/functions. -(! grep -Fv '.HandleResolvedAddrs -.HandleSubConnStateChange +not grep -Fv '.CredsBundle .HeaderMap +.Metadata is deprecated: use Attributes .NewAddress .NewServiceConfig -.Metadata is deprecated: use Attributes .Type is deprecated: use Attributes -.UpdateBalancerState +balancer.ErrTransientFailure balancer.Picker grpc.CallCustomCodec grpc.Code @@ -140,9 +142,7 @@ grpc.NewGZIPCompressor grpc.NewGZIPDecompressor grpc.RPCCompressor grpc.RPCDecompressor -grpc.RoundRobin grpc.ServiceConfig -grpc.WithBalancer grpc.WithBalancerName grpc.WithCompressor grpc.WithDecompressor @@ -151,9 +151,39 @@ grpc.WithMaxMsgSize grpc.WithServiceConfig grpc.WithTimeout http.CloseNotifier -naming.Resolver -naming.Update -naming.Watcher +info.SecurityVersion resolver.Backend resolver.GRPCLB' "${SC_OUT}" -) + +# - special golint on package comments. +lint_package_comment_per_package() { + # Number of files in this go package. + fileCount=$(go list -f '{{len .GoFiles}}' $1) + if [ ${fileCount} -eq 0 ]; then + return 0 + fi + # Number of package errors generated by golint. + lintPackageCommentErrorsCount=$(golint --min_confidence 0 $1 | grep -c "should have a package comment") + # golint complains about every file that's missing the package comment. If the + # number of files for this package is greater than the number of errors, there's + # at least one file with package comment, good. Otherwise, fail. + if [ ${fileCount} -le ${lintPackageCommentErrorsCount} ]; then + echo "Package $1 (with ${fileCount} files) is missing package comment" + return 1 + fi +} +lint_package_comment() { + set +ex + + count=0 + for i in $(go list ./...); do + lint_package_comment_per_package "$i" + ((count += $?)) + done + + set -ex + return $count +} +lint_package_comment + +echo SUCCESS diff --git a/vendor/google.golang.org/protobuf/AUTHORS b/vendor/google.golang.org/protobuf/AUTHORS new file mode 100644 index 00000000000..2b00ddba0df --- /dev/null +++ b/vendor/google.golang.org/protobuf/AUTHORS @@ -0,0 +1,3 @@ +# This source code refers to The Go Authors for copyright purposes. +# The master list of authors is in the main Go distribution, +# visible at https://tip.golang.org/AUTHORS. diff --git a/vendor/google.golang.org/protobuf/CONTRIBUTORS b/vendor/google.golang.org/protobuf/CONTRIBUTORS new file mode 100644 index 00000000000..1fbd3e976fa --- /dev/null +++ b/vendor/google.golang.org/protobuf/CONTRIBUTORS @@ -0,0 +1,3 @@ +# This source code was written by the Go contributors. +# The master list of contributors is in the main Go distribution, +# visible at https://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/google.golang.org/protobuf/LICENSE b/vendor/google.golang.org/protobuf/LICENSE new file mode 100644 index 00000000000..49ea0f92882 --- /dev/null +++ b/vendor/google.golang.org/protobuf/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2018 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/google.golang.org/protobuf/PATENTS b/vendor/google.golang.org/protobuf/PATENTS new file mode 100644 index 00000000000..733099041f8 --- /dev/null +++ b/vendor/google.golang.org/protobuf/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google 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, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/init.go b/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/init.go new file mode 100644 index 00000000000..369df13da27 --- /dev/null +++ b/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/init.go @@ -0,0 +1,168 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package internal_gengo + +import ( + "unicode" + "unicode/utf8" + + "google.golang.org/protobuf/compiler/protogen" + "google.golang.org/protobuf/encoding/protowire" + + "google.golang.org/protobuf/types/descriptorpb" +) + +type fileInfo struct { + *protogen.File + + allEnums []*enumInfo + allMessages []*messageInfo + allExtensions []*extensionInfo + + allEnumsByPtr map[*enumInfo]int // value is index into allEnums + allMessagesByPtr map[*messageInfo]int // value is index into allMessages + allMessageFieldsByPtr map[*messageInfo]*structFields + + // needRawDesc specifies whether the generator should emit logic to provide + // the legacy raw descriptor in GZIP'd form. + // This is updated by enum and message generation logic as necessary, + // and checked at the end of file generation. + needRawDesc bool +} + +type structFields struct { + count int + unexported map[int]string +} + +func (sf *structFields) append(name string) { + if r, _ := utf8.DecodeRuneInString(name); !unicode.IsUpper(r) { + if sf.unexported == nil { + sf.unexported = make(map[int]string) + } + sf.unexported[sf.count] = name + } + sf.count++ +} + +func newFileInfo(file *protogen.File) *fileInfo { + f := &fileInfo{File: file} + + // Collect all enums, messages, and extensions in "flattened ordering". + // See filetype.TypeBuilder. + var walkMessages func([]*protogen.Message, func(*protogen.Message)) + walkMessages = func(messages []*protogen.Message, f func(*protogen.Message)) { + for _, m := range messages { + f(m) + walkMessages(m.Messages, f) + } + } + initEnumInfos := func(enums []*protogen.Enum) { + for _, enum := range enums { + f.allEnums = append(f.allEnums, newEnumInfo(f, enum)) + } + } + initMessageInfos := func(messages []*protogen.Message) { + for _, message := range messages { + f.allMessages = append(f.allMessages, newMessageInfo(f, message)) + } + } + initExtensionInfos := func(extensions []*protogen.Extension) { + for _, extension := range extensions { + f.allExtensions = append(f.allExtensions, newExtensionInfo(f, extension)) + } + } + initEnumInfos(f.Enums) + initMessageInfos(f.Messages) + initExtensionInfos(f.Extensions) + walkMessages(f.Messages, func(m *protogen.Message) { + initEnumInfos(m.Enums) + initMessageInfos(m.Messages) + initExtensionInfos(m.Extensions) + }) + + // Derive a reverse mapping of enum and message pointers to their index + // in allEnums and allMessages. + if len(f.allEnums) > 0 { + f.allEnumsByPtr = make(map[*enumInfo]int) + for i, e := range f.allEnums { + f.allEnumsByPtr[e] = i + } + } + if len(f.allMessages) > 0 { + f.allMessagesByPtr = make(map[*messageInfo]int) + f.allMessageFieldsByPtr = make(map[*messageInfo]*structFields) + for i, m := range f.allMessages { + f.allMessagesByPtr[m] = i + f.allMessageFieldsByPtr[m] = new(structFields) + } + } + + return f +} + +type enumInfo struct { + *protogen.Enum + + genJSONMethod bool + genRawDescMethod bool +} + +func newEnumInfo(f *fileInfo, enum *protogen.Enum) *enumInfo { + e := &enumInfo{Enum: enum} + e.genJSONMethod = true + e.genRawDescMethod = true + return e +} + +type messageInfo struct { + *protogen.Message + + genRawDescMethod bool + genExtRangeMethod bool + + isTracked bool + hasWeak bool +} + +func newMessageInfo(f *fileInfo, message *protogen.Message) *messageInfo { + m := &messageInfo{Message: message} + m.genRawDescMethod = true + m.genExtRangeMethod = true + m.isTracked = isTrackedMessage(m) + for _, field := range m.Fields { + m.hasWeak = m.hasWeak || field.Desc.IsWeak() + } + return m +} + +// isTrackedMessage reports whether field tracking is enabled on the message. +func isTrackedMessage(m *messageInfo) (tracked bool) { + const trackFieldUse_fieldNumber = 37383685 + + // Decode the option from unknown fields to avoid a dependency on the + // annotation proto from protoc-gen-go. + b := m.Desc.Options().(*descriptorpb.MessageOptions).ProtoReflect().GetUnknown() + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + if num == trackFieldUse_fieldNumber && typ == protowire.VarintType { + v, _ := protowire.ConsumeVarint(b) + tracked = protowire.DecodeBool(v) + } + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + return tracked +} + +type extensionInfo struct { + *protogen.Extension +} + +func newExtensionInfo(f *fileInfo, extension *protogen.Extension) *extensionInfo { + x := &extensionInfo{Extension: extension} + return x +} diff --git a/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/main.go b/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/main.go new file mode 100644 index 00000000000..b2e3930fb0a --- /dev/null +++ b/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/main.go @@ -0,0 +1,901 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package internal_gengo is internal to the protobuf module. +package internal_gengo + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "math" + "strconv" + "strings" + "unicode" + "unicode/utf8" + + "google.golang.org/protobuf/compiler/protogen" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/encoding/tag" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/version" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoimpl" + + "google.golang.org/protobuf/types/descriptorpb" + "google.golang.org/protobuf/types/pluginpb" +) + +// SupportedFeatures reports the set of supported protobuf language features. +var SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL) + +// GenerateVersionMarkers specifies whether to generate version markers. +var GenerateVersionMarkers = true + +// Standard library dependencies. +const ( + base64Package = protogen.GoImportPath("encoding/base64") + mathPackage = protogen.GoImportPath("math") + reflectPackage = protogen.GoImportPath("reflect") + sortPackage = protogen.GoImportPath("sort") + stringsPackage = protogen.GoImportPath("strings") + syncPackage = protogen.GoImportPath("sync") + timePackage = protogen.GoImportPath("time") + utf8Package = protogen.GoImportPath("unicode/utf8") +) + +// Protobuf library dependencies. +// +// These are declared as an interface type so that they can be more easily +// patched to support unique build environments that impose restrictions +// on the dependencies of generated source code. +var ( + protoPackage goImportPath = protogen.GoImportPath("google.golang.org/protobuf/proto") + protoifacePackage goImportPath = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoiface") + protoimplPackage goImportPath = protogen.GoImportPath("google.golang.org/protobuf/runtime/protoimpl") + protojsonPackage goImportPath = protogen.GoImportPath("google.golang.org/protobuf/encoding/protojson") + protoreflectPackage goImportPath = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoreflect") + protoregistryPackage goImportPath = protogen.GoImportPath("google.golang.org/protobuf/reflect/protoregistry") + protoV1Package goImportPath = protogen.GoImportPath("github.com/golang/protobuf/proto") +) + +type goImportPath interface { + String() string + Ident(string) protogen.GoIdent +} + +// GenerateFile generates the contents of a .pb.go file. +func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile { + filename := file.GeneratedFilenamePrefix + ".pb.go" + g := gen.NewGeneratedFile(filename, file.GoImportPath) + f := newFileInfo(file) + + genStandaloneComments(g, f, int32(genid.FileDescriptorProto_Syntax_field_number)) + genGeneratedHeader(gen, g, f) + genStandaloneComments(g, f, int32(genid.FileDescriptorProto_Package_field_number)) + + packageDoc := genPackageKnownComment(f) + g.P(packageDoc, "package ", f.GoPackageName) + g.P() + + // Emit a static check that enforces a minimum version of the proto package. + if GenerateVersionMarkers { + g.P("const (") + g.P("// Verify that this generated code is sufficiently up-to-date.") + g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimpl.GenVersion, " - ", protoimplPackage.Ident("MinVersion"), ")") + g.P("// Verify that runtime/protoimpl is sufficiently up-to-date.") + g.P("_ = ", protoimplPackage.Ident("EnforceVersion"), "(", protoimplPackage.Ident("MaxVersion"), " - ", protoimpl.GenVersion, ")") + g.P(")") + g.P() + + // TODO: Remove this after some soak-in period after the v2 release. + g.P("// This is a compile-time assertion that a sufficiently up-to-date version") + g.P("// of the legacy proto package is being used.") + g.P("const _ = ", protoV1Package.Ident("ProtoPackageIsVersion4")) + g.P() + } + + for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ { + genImport(gen, g, f, imps.Get(i)) + } + for _, enum := range f.allEnums { + genEnum(g, f, enum) + } + for _, message := range f.allMessages { + genMessage(g, f, message) + } + genExtensions(g, f) + + genReflectFileDescriptor(gen, g, f) + + return g +} + +// genStandaloneComments prints all leading comments for a FileDescriptorProto +// location identified by the field number n. +func genStandaloneComments(g *protogen.GeneratedFile, f *fileInfo, n int32) { + for _, loc := range f.Proto.GetSourceCodeInfo().GetLocation() { + if len(loc.Path) == 1 && loc.Path[0] == n { + for _, s := range loc.GetLeadingDetachedComments() { + g.P(protogen.Comments(s)) + g.P() + } + if s := loc.GetLeadingComments(); s != "" { + g.P(protogen.Comments(s)) + g.P() + } + } + } +} + +func genGeneratedHeader(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) { + g.P("// Code generated by protoc-gen-go. DO NOT EDIT.") + + if GenerateVersionMarkers { + g.P("// versions:") + protocGenGoVersion := version.String() + protocVersion := "(unknown)" + if v := gen.Request.GetCompilerVersion(); v != nil { + protocVersion = fmt.Sprintf("v%v.%v.%v", v.GetMajor(), v.GetMinor(), v.GetPatch()) + } + g.P("// \tprotoc-gen-go ", protocGenGoVersion) + g.P("// \tprotoc ", protocVersion) + } + + if f.Proto.GetOptions().GetDeprecated() { + g.P("// ", f.Desc.Path(), " is a deprecated file.") + } else { + g.P("// source: ", f.Desc.Path()) + } + g.P() +} + +func genImport(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo, imp protoreflect.FileImport) { + impFile, ok := gen.FilesByPath[imp.Path()] + if !ok { + return + } + if impFile.GoImportPath == f.GoImportPath { + // Don't generate imports or aliases for types in the same Go package. + return + } + // Generate imports for all non-weak dependencies, even if they are not + // referenced, because other code and tools depend on having the + // full transitive closure of protocol buffer types in the binary. + if !imp.IsWeak { + g.Import(impFile.GoImportPath) + } + if !imp.IsPublic { + return + } + + // Generate public imports by generating the imported file, parsing it, + // and extracting every symbol that should receive a forwarding declaration. + impGen := GenerateFile(gen, impFile) + impGen.Skip() + b, err := impGen.Content() + if err != nil { + gen.Error(err) + return + } + fset := token.NewFileSet() + astFile, err := parser.ParseFile(fset, "", b, parser.ParseComments) + if err != nil { + gen.Error(err) + return + } + genForward := func(tok token.Token, name string, expr ast.Expr) { + // Don't import unexported symbols. + r, _ := utf8.DecodeRuneInString(name) + if !unicode.IsUpper(r) { + return + } + // Don't import the FileDescriptor. + if name == impFile.GoDescriptorIdent.GoName { + return + } + // Don't import decls referencing a symbol defined in another package. + // i.e., don't import decls which are themselves public imports: + // + // type T = somepackage.T + if _, ok := expr.(*ast.SelectorExpr); ok { + return + } + g.P(tok, " ", name, " = ", impFile.GoImportPath.Ident(name)) + } + g.P("// Symbols defined in public import of ", imp.Path(), ".") + g.P() + for _, decl := range astFile.Decls { + switch decl := decl.(type) { + case *ast.GenDecl: + for _, spec := range decl.Specs { + switch spec := spec.(type) { + case *ast.TypeSpec: + genForward(decl.Tok, spec.Name.Name, spec.Type) + case *ast.ValueSpec: + for i, name := range spec.Names { + var expr ast.Expr + if i < len(spec.Values) { + expr = spec.Values[i] + } + genForward(decl.Tok, name.Name, expr) + } + case *ast.ImportSpec: + default: + panic(fmt.Sprintf("can't generate forward for spec type %T", spec)) + } + } + } + } + g.P() +} + +func genEnum(g *protogen.GeneratedFile, f *fileInfo, e *enumInfo) { + // Enum type declaration. + g.Annotate(e.GoIdent.GoName, e.Location) + leadingComments := appendDeprecationSuffix(e.Comments.Leading, + e.Desc.Options().(*descriptorpb.EnumOptions).GetDeprecated()) + g.P(leadingComments, + "type ", e.GoIdent, " int32") + + // Enum value constants. + g.P("const (") + for _, value := range e.Values { + g.Annotate(value.GoIdent.GoName, value.Location) + leadingComments := appendDeprecationSuffix(value.Comments.Leading, + value.Desc.Options().(*descriptorpb.EnumValueOptions).GetDeprecated()) + g.P(leadingComments, + value.GoIdent, " ", e.GoIdent, " = ", value.Desc.Number(), + trailingComment(value.Comments.Trailing)) + } + g.P(")") + g.P() + + // Enum value maps. + g.P("// Enum value maps for ", e.GoIdent, ".") + g.P("var (") + g.P(e.GoIdent.GoName+"_name", " = map[int32]string{") + for _, value := range e.Values { + duplicate := "" + if value.Desc != e.Desc.Values().ByNumber(value.Desc.Number()) { + duplicate = "// Duplicate value: " + } + g.P(duplicate, value.Desc.Number(), ": ", strconv.Quote(string(value.Desc.Name())), ",") + } + g.P("}") + g.P(e.GoIdent.GoName+"_value", " = map[string]int32{") + for _, value := range e.Values { + g.P(strconv.Quote(string(value.Desc.Name())), ": ", value.Desc.Number(), ",") + } + g.P("}") + g.P(")") + g.P() + + // Enum method. + // + // NOTE: A pointer value is needed to represent presence in proto2. + // Since a proto2 message can reference a proto3 enum, it is useful to + // always generate this method (even on proto3 enums) to support that case. + g.P("func (x ", e.GoIdent, ") Enum() *", e.GoIdent, " {") + g.P("p := new(", e.GoIdent, ")") + g.P("*p = x") + g.P("return p") + g.P("}") + g.P() + + // String method. + g.P("func (x ", e.GoIdent, ") String() string {") + g.P("return ", protoimplPackage.Ident("X"), ".EnumStringOf(x.Descriptor(), ", protoreflectPackage.Ident("EnumNumber"), "(x))") + g.P("}") + g.P() + + genEnumReflectMethods(g, f, e) + + // UnmarshalJSON method. + if e.genJSONMethod && e.Desc.Syntax() == protoreflect.Proto2 { + g.P("// Deprecated: Do not use.") + g.P("func (x *", e.GoIdent, ") UnmarshalJSON(b []byte) error {") + g.P("num, err := ", protoimplPackage.Ident("X"), ".UnmarshalJSONEnum(x.Descriptor(), b)") + g.P("if err != nil {") + g.P("return err") + g.P("}") + g.P("*x = ", e.GoIdent, "(num)") + g.P("return nil") + g.P("}") + g.P() + } + + // EnumDescriptor method. + if e.genRawDescMethod { + var indexes []string + for i := 1; i < len(e.Location.Path); i += 2 { + indexes = append(indexes, strconv.Itoa(int(e.Location.Path[i]))) + } + g.P("// Deprecated: Use ", e.GoIdent, ".Descriptor instead.") + g.P("func (", e.GoIdent, ") EnumDescriptor() ([]byte, []int) {") + g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}") + g.P("}") + g.P() + f.needRawDesc = true + } +} + +func genMessage(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { + if m.Desc.IsMapEntry() { + return + } + + // Message type declaration. + g.Annotate(m.GoIdent.GoName, m.Location) + leadingComments := appendDeprecationSuffix(m.Comments.Leading, + m.Desc.Options().(*descriptorpb.MessageOptions).GetDeprecated()) + g.P(leadingComments, + "type ", m.GoIdent, " struct {") + genMessageFields(g, f, m) + g.P("}") + g.P() + + genMessageKnownFunctions(g, f, m) + genMessageDefaultDecls(g, f, m) + genMessageMethods(g, f, m) + genMessageOneofWrapperTypes(g, f, m) +} + +func genMessageFields(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { + sf := f.allMessageFieldsByPtr[m] + genMessageInternalFields(g, f, m, sf) + for _, field := range m.Fields { + genMessageField(g, f, m, field, sf) + } +} + +func genMessageInternalFields(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo, sf *structFields) { + g.P(genid.State_goname, " ", protoimplPackage.Ident("MessageState")) + sf.append(genid.State_goname) + g.P(genid.SizeCache_goname, " ", protoimplPackage.Ident("SizeCache")) + sf.append(genid.SizeCache_goname) + if m.hasWeak { + g.P(genid.WeakFields_goname, " ", protoimplPackage.Ident("WeakFields")) + sf.append(genid.WeakFields_goname) + } + g.P(genid.UnknownFields_goname, " ", protoimplPackage.Ident("UnknownFields")) + sf.append(genid.UnknownFields_goname) + if m.Desc.ExtensionRanges().Len() > 0 { + g.P(genid.ExtensionFields_goname, " ", protoimplPackage.Ident("ExtensionFields")) + sf.append(genid.ExtensionFields_goname) + } + if sf.count > 0 { + g.P() + } +} + +func genMessageField(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo, field *protogen.Field, sf *structFields) { + if oneof := field.Oneof; oneof != nil && !oneof.Desc.IsSynthetic() { + // It would be a bit simpler to iterate over the oneofs below, + // but generating the field here keeps the contents of the Go + // struct in the same order as the contents of the source + // .proto file. + if oneof.Fields[0] != field { + return // only generate for first appearance + } + + tags := structTags{ + {"protobuf_oneof", string(oneof.Desc.Name())}, + } + if m.isTracked { + tags = append(tags, gotrackTags...) + } + + g.Annotate(m.GoIdent.GoName+"."+oneof.GoName, oneof.Location) + leadingComments := oneof.Comments.Leading + if leadingComments != "" { + leadingComments += "\n" + } + ss := []string{fmt.Sprintf(" Types that are assignable to %s:\n", oneof.GoName)} + for _, field := range oneof.Fields { + ss = append(ss, "\t*"+field.GoIdent.GoName+"\n") + } + leadingComments += protogen.Comments(strings.Join(ss, "")) + g.P(leadingComments, + oneof.GoName, " ", oneofInterfaceName(oneof), tags) + sf.append(oneof.GoName) + return + } + goType, pointer := fieldGoType(g, f, field) + if pointer { + goType = "*" + goType + } + tags := structTags{ + {"protobuf", fieldProtobufTagValue(field)}, + {"json", fieldJSONTagValue(field)}, + } + if field.Desc.IsMap() { + key := field.Message.Fields[0] + val := field.Message.Fields[1] + tags = append(tags, structTags{ + {"protobuf_key", fieldProtobufTagValue(key)}, + {"protobuf_val", fieldProtobufTagValue(val)}, + }...) + } + if m.isTracked { + tags = append(tags, gotrackTags...) + } + + name := field.GoName + if field.Desc.IsWeak() { + name = genid.WeakFieldPrefix_goname + name + } + g.Annotate(m.GoIdent.GoName+"."+name, field.Location) + leadingComments := appendDeprecationSuffix(field.Comments.Leading, + field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()) + g.P(leadingComments, + name, " ", goType, tags, + trailingComment(field.Comments.Trailing)) + sf.append(field.GoName) +} + +// genMessageDefaultDecls generates consts and vars holding the default +// values of fields. +func genMessageDefaultDecls(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { + var consts, vars []string + for _, field := range m.Fields { + if !field.Desc.HasDefault() { + continue + } + name := "Default_" + m.GoIdent.GoName + "_" + field.GoName + goType, _ := fieldGoType(g, f, field) + defVal := field.Desc.Default() + switch field.Desc.Kind() { + case protoreflect.StringKind: + consts = append(consts, fmt.Sprintf("%s = %s(%q)", name, goType, defVal.String())) + case protoreflect.BytesKind: + vars = append(vars, fmt.Sprintf("%s = %s(%q)", name, goType, defVal.Bytes())) + case protoreflect.EnumKind: + idx := field.Desc.DefaultEnumValue().Index() + val := field.Enum.Values[idx] + consts = append(consts, fmt.Sprintf("%s = %s", name, g.QualifiedGoIdent(val.GoIdent))) + case protoreflect.FloatKind, protoreflect.DoubleKind: + if f := defVal.Float(); math.IsNaN(f) || math.IsInf(f, 0) { + var fn, arg string + switch f := defVal.Float(); { + case math.IsInf(f, -1): + fn, arg = g.QualifiedGoIdent(mathPackage.Ident("Inf")), "-1" + case math.IsInf(f, +1): + fn, arg = g.QualifiedGoIdent(mathPackage.Ident("Inf")), "+1" + case math.IsNaN(f): + fn, arg = g.QualifiedGoIdent(mathPackage.Ident("NaN")), "" + } + vars = append(vars, fmt.Sprintf("%s = %s(%s(%s))", name, goType, fn, arg)) + } else { + consts = append(consts, fmt.Sprintf("%s = %s(%v)", name, goType, f)) + } + default: + consts = append(consts, fmt.Sprintf("%s = %s(%v)", name, goType, defVal.Interface())) + } + } + if len(consts) > 0 { + g.P("// Default values for ", m.GoIdent, " fields.") + g.P("const (") + for _, s := range consts { + g.P(s) + } + g.P(")") + } + if len(vars) > 0 { + g.P("// Default values for ", m.GoIdent, " fields.") + g.P("var (") + for _, s := range vars { + g.P(s) + } + g.P(")") + } + g.P() +} + +func genMessageMethods(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { + genMessageBaseMethods(g, f, m) + genMessageGetterMethods(g, f, m) + genMessageSetterMethods(g, f, m) +} + +func genMessageBaseMethods(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { + // Reset method. + g.P("func (x *", m.GoIdent, ") Reset() {") + g.P("*x = ", m.GoIdent, "{}") + g.P("if ", protoimplPackage.Ident("UnsafeEnabled"), " {") + g.P("mi := &", messageTypesVarName(f), "[", f.allMessagesByPtr[m], "]") + g.P("ms := ", protoimplPackage.Ident("X"), ".MessageStateOf(", protoimplPackage.Ident("Pointer"), "(x))") + g.P("ms.StoreMessageInfo(mi)") + g.P("}") + g.P("}") + g.P() + + // String method. + g.P("func (x *", m.GoIdent, ") String() string {") + g.P("return ", protoimplPackage.Ident("X"), ".MessageStringOf(x)") + g.P("}") + g.P() + + // ProtoMessage method. + g.P("func (*", m.GoIdent, ") ProtoMessage() {}") + g.P() + + // ProtoReflect method. + genMessageReflectMethods(g, f, m) + + // Descriptor method. + if m.genRawDescMethod { + var indexes []string + for i := 1; i < len(m.Location.Path); i += 2 { + indexes = append(indexes, strconv.Itoa(int(m.Location.Path[i]))) + } + g.P("// Deprecated: Use ", m.GoIdent, ".ProtoReflect.Descriptor instead.") + g.P("func (*", m.GoIdent, ") Descriptor() ([]byte, []int) {") + g.P("return ", rawDescVarName(f), "GZIP(), []int{", strings.Join(indexes, ","), "}") + g.P("}") + g.P() + f.needRawDesc = true + } + + // ExtensionRangeArray method. + extRanges := m.Desc.ExtensionRanges() + if m.genExtRangeMethod && extRanges.Len() > 0 { + protoExtRange := protoifacePackage.Ident("ExtensionRangeV1") + extRangeVar := "extRange_" + m.GoIdent.GoName + g.P("var ", extRangeVar, " = []", protoExtRange, " {") + for i := 0; i < extRanges.Len(); i++ { + r := extRanges.Get(i) + g.P("{Start:", r[0], ", End:", r[1]-1 /* inclusive */, "},") + } + g.P("}") + g.P() + g.P("// Deprecated: Use ", m.GoIdent, ".ProtoReflect.Descriptor.ExtensionRanges instead.") + g.P("func (*", m.GoIdent, ") ExtensionRangeArray() []", protoExtRange, " {") + g.P("return ", extRangeVar) + g.P("}") + g.P() + } +} + +func genMessageGetterMethods(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { + for _, field := range m.Fields { + genNoInterfacePragma(g, m.isTracked) + + // Getter for parent oneof. + if oneof := field.Oneof; oneof != nil && oneof.Fields[0] == field && !oneof.Desc.IsSynthetic() { + g.Annotate(m.GoIdent.GoName+".Get"+oneof.GoName, oneof.Location) + g.P("func (m *", m.GoIdent.GoName, ") Get", oneof.GoName, "() ", oneofInterfaceName(oneof), " {") + g.P("if m != nil {") + g.P("return m.", oneof.GoName) + g.P("}") + g.P("return nil") + g.P("}") + g.P() + } + + // Getter for message field. + goType, pointer := fieldGoType(g, f, field) + defaultValue := fieldDefaultValue(g, m, field) + g.Annotate(m.GoIdent.GoName+".Get"+field.GoName, field.Location) + leadingComments := appendDeprecationSuffix("", + field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()) + switch { + case field.Desc.IsWeak(): + g.P(leadingComments, "func (x *", m.GoIdent, ") Get", field.GoName, "() ", protoPackage.Ident("Message"), "{") + g.P("var w ", protoimplPackage.Ident("WeakFields")) + g.P("if x != nil {") + g.P("w = x.", genid.WeakFields_goname) + if m.isTracked { + g.P("_ = x.", genid.WeakFieldPrefix_goname+field.GoName) + } + g.P("}") + g.P("return ", protoimplPackage.Ident("X"), ".GetWeak(w, ", field.Desc.Number(), ", ", strconv.Quote(string(field.Message.Desc.FullName())), ")") + g.P("}") + case field.Oneof != nil && !field.Oneof.Desc.IsSynthetic(): + g.P(leadingComments, "func (x *", m.GoIdent, ") Get", field.GoName, "() ", goType, " {") + g.P("if x, ok := x.Get", field.Oneof.GoName, "().(*", field.GoIdent, "); ok {") + g.P("return x.", field.GoName) + g.P("}") + g.P("return ", defaultValue) + g.P("}") + default: + g.P(leadingComments, "func (x *", m.GoIdent, ") Get", field.GoName, "() ", goType, " {") + if !field.Desc.HasPresence() || defaultValue == "nil" { + g.P("if x != nil {") + } else { + g.P("if x != nil && x.", field.GoName, " != nil {") + } + star := "" + if pointer { + star = "*" + } + g.P("return ", star, " x.", field.GoName) + g.P("}") + g.P("return ", defaultValue) + g.P("}") + } + g.P() + } +} + +func genMessageSetterMethods(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { + for _, field := range m.Fields { + if !field.Desc.IsWeak() { + continue + } + + genNoInterfacePragma(g, m.isTracked) + + g.Annotate(m.GoIdent.GoName+".Set"+field.GoName, field.Location) + leadingComments := appendDeprecationSuffix("", + field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()) + g.P(leadingComments, "func (x *", m.GoIdent, ") Set", field.GoName, "(v ", protoPackage.Ident("Message"), ") {") + g.P("var w *", protoimplPackage.Ident("WeakFields")) + g.P("if x != nil {") + g.P("w = &x.", genid.WeakFields_goname) + if m.isTracked { + g.P("_ = x.", genid.WeakFieldPrefix_goname+field.GoName) + } + g.P("}") + g.P(protoimplPackage.Ident("X"), ".SetWeak(w, ", field.Desc.Number(), ", ", strconv.Quote(string(field.Message.Desc.FullName())), ", v)") + g.P("}") + g.P() + } +} + +// fieldGoType returns the Go type used for a field. +// +// If it returns pointer=true, the struct field is a pointer to the type. +func fieldGoType(g *protogen.GeneratedFile, f *fileInfo, field *protogen.Field) (goType string, pointer bool) { + if field.Desc.IsWeak() { + return "struct{}", false + } + + pointer = field.Desc.HasPresence() + switch field.Desc.Kind() { + case protoreflect.BoolKind: + goType = "bool" + case protoreflect.EnumKind: + goType = g.QualifiedGoIdent(field.Enum.GoIdent) + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: + goType = "int32" + case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: + goType = "uint32" + case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: + goType = "int64" + case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: + goType = "uint64" + case protoreflect.FloatKind: + goType = "float32" + case protoreflect.DoubleKind: + goType = "float64" + case protoreflect.StringKind: + goType = "string" + case protoreflect.BytesKind: + goType = "[]byte" + pointer = false // rely on nullability of slices for presence + case protoreflect.MessageKind, protoreflect.GroupKind: + goType = "*" + g.QualifiedGoIdent(field.Message.GoIdent) + pointer = false // pointer captured as part of the type + } + switch { + case field.Desc.IsList(): + return "[]" + goType, false + case field.Desc.IsMap(): + keyType, _ := fieldGoType(g, f, field.Message.Fields[0]) + valType, _ := fieldGoType(g, f, field.Message.Fields[1]) + return fmt.Sprintf("map[%v]%v", keyType, valType), false + } + return goType, pointer +} + +func fieldProtobufTagValue(field *protogen.Field) string { + var enumName string + if field.Desc.Kind() == protoreflect.EnumKind { + enumName = protoimpl.X.LegacyEnumName(field.Enum.Desc) + } + return tag.Marshal(field.Desc, enumName) +} + +func fieldDefaultValue(g *protogen.GeneratedFile, m *messageInfo, field *protogen.Field) string { + if field.Desc.IsList() { + return "nil" + } + if field.Desc.HasDefault() { + defVarName := "Default_" + m.GoIdent.GoName + "_" + field.GoName + if field.Desc.Kind() == protoreflect.BytesKind { + return "append([]byte(nil), " + defVarName + "...)" + } + return defVarName + } + switch field.Desc.Kind() { + case protoreflect.BoolKind: + return "false" + case protoreflect.StringKind: + return `""` + case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.BytesKind: + return "nil" + case protoreflect.EnumKind: + return g.QualifiedGoIdent(field.Enum.Values[0].GoIdent) + default: + return "0" + } +} + +func fieldJSONTagValue(field *protogen.Field) string { + return string(field.Desc.Name()) + ",omitempty" +} + +func genExtensions(g *protogen.GeneratedFile, f *fileInfo) { + if len(f.allExtensions) == 0 { + return + } + + g.P("var ", extensionTypesVarName(f), " = []", protoimplPackage.Ident("ExtensionInfo"), "{") + for _, x := range f.allExtensions { + // For MessageSet extensions, the name used is the parent message. + name := x.Desc.FullName() + if messageset.IsMessageSetExtension(x.Desc) { + name = name.Parent() + } + + g.P("{") + g.P("ExtendedType: (*", x.Extendee.GoIdent, ")(nil),") + goType, pointer := fieldGoType(g, f, x.Extension) + if pointer { + goType = "*" + goType + } + g.P("ExtensionType: (", goType, ")(nil),") + g.P("Field: ", x.Desc.Number(), ",") + g.P("Name: ", strconv.Quote(string(name)), ",") + g.P("Tag: ", strconv.Quote(fieldProtobufTagValue(x.Extension)), ",") + g.P("Filename: ", strconv.Quote(f.Desc.Path()), ",") + g.P("},") + } + g.P("}") + g.P() + + // Group extensions by the target message. + var orderedTargets []protogen.GoIdent + allExtensionsByTarget := make(map[protogen.GoIdent][]*extensionInfo) + allExtensionsByPtr := make(map[*extensionInfo]int) + for i, x := range f.allExtensions { + target := x.Extendee.GoIdent + if len(allExtensionsByTarget[target]) == 0 { + orderedTargets = append(orderedTargets, target) + } + allExtensionsByTarget[target] = append(allExtensionsByTarget[target], x) + allExtensionsByPtr[x] = i + } + for _, target := range orderedTargets { + g.P("// Extension fields to ", target, ".") + g.P("var (") + for _, x := range allExtensionsByTarget[target] { + xd := x.Desc + typeName := xd.Kind().String() + switch xd.Kind() { + case protoreflect.EnumKind: + typeName = string(xd.Enum().FullName()) + case protoreflect.MessageKind, protoreflect.GroupKind: + typeName = string(xd.Message().FullName()) + } + fieldName := string(xd.Name()) + + leadingComments := x.Comments.Leading + if leadingComments != "" { + leadingComments += "\n" + } + leadingComments += protogen.Comments(fmt.Sprintf(" %v %v %v = %v;\n", + xd.Cardinality(), typeName, fieldName, xd.Number())) + leadingComments = appendDeprecationSuffix(leadingComments, + x.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()) + g.P(leadingComments, + "E_", x.GoIdent, " = &", extensionTypesVarName(f), "[", allExtensionsByPtr[x], "]", + trailingComment(x.Comments.Trailing)) + } + g.P(")") + g.P() + } +} + +// genMessageOneofWrapperTypes generates the oneof wrapper types and +// associates the types with the parent message type. +func genMessageOneofWrapperTypes(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { + for _, oneof := range m.Oneofs { + if oneof.Desc.IsSynthetic() { + continue + } + ifName := oneofInterfaceName(oneof) + g.P("type ", ifName, " interface {") + g.P(ifName, "()") + g.P("}") + g.P() + for _, field := range oneof.Fields { + g.Annotate(field.GoIdent.GoName, field.Location) + g.Annotate(field.GoIdent.GoName+"."+field.GoName, field.Location) + g.P("type ", field.GoIdent, " struct {") + goType, _ := fieldGoType(g, f, field) + tags := structTags{ + {"protobuf", fieldProtobufTagValue(field)}, + } + if m.isTracked { + tags = append(tags, gotrackTags...) + } + leadingComments := appendDeprecationSuffix(field.Comments.Leading, + field.Desc.Options().(*descriptorpb.FieldOptions).GetDeprecated()) + g.P(leadingComments, + field.GoName, " ", goType, tags, + trailingComment(field.Comments.Trailing)) + g.P("}") + g.P() + } + for _, field := range oneof.Fields { + g.P("func (*", field.GoIdent, ") ", ifName, "() {}") + g.P() + } + } +} + +// oneofInterfaceName returns the name of the interface type implemented by +// the oneof field value types. +func oneofInterfaceName(oneof *protogen.Oneof) string { + return "is" + oneof.GoIdent.GoName +} + +// genNoInterfacePragma generates a standalone "nointerface" pragma to +// decorate methods with field-tracking support. +func genNoInterfacePragma(g *protogen.GeneratedFile, tracked bool) { + if tracked { + g.P("//go:nointerface") + g.P() + } +} + +var gotrackTags = structTags{{"go", "track"}} + +// structTags is a data structure for build idiomatic Go struct tags. +// Each [2]string is a key-value pair, where value is the unescaped string. +// +// Example: structTags{{"key", "value"}}.String() -> `key:"value"` +type structTags [][2]string + +func (tags structTags) String() string { + if len(tags) == 0 { + return "" + } + var ss []string + for _, tag := range tags { + // NOTE: When quoting the value, we need to make sure the backtick + // character does not appear. Convert all cases to the escaped hex form. + key := tag[0] + val := strings.Replace(strconv.Quote(tag[1]), "`", `\x60`, -1) + ss = append(ss, fmt.Sprintf("%s:%s", key, val)) + } + return "`" + strings.Join(ss, " ") + "`" +} + +// appendDeprecationSuffix optionally appends a deprecation notice as a suffix. +func appendDeprecationSuffix(prefix protogen.Comments, deprecated bool) protogen.Comments { + if !deprecated { + return prefix + } + if prefix != "" { + prefix += "\n" + } + return prefix + " Deprecated: Do not use.\n" +} + +// trailingComment is like protogen.Comments, but lacks a trailing newline. +type trailingComment protogen.Comments + +func (c trailingComment) String() string { + s := strings.TrimSuffix(protogen.Comments(c).String(), "\n") + if strings.Contains(s, "\n") { + // We don't support multi-lined trailing comments as it is unclear + // how to best render them in the generated code. + return "" + } + return s +} diff --git a/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/reflect.go b/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/reflect.go new file mode 100644 index 00000000000..1319a126750 --- /dev/null +++ b/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/reflect.go @@ -0,0 +1,351 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package internal_gengo + +import ( + "fmt" + "math" + "strings" + "unicode/utf8" + + "google.golang.org/protobuf/compiler/protogen" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + + "google.golang.org/protobuf/types/descriptorpb" +) + +func genReflectFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) { + g.P("var ", f.GoDescriptorIdent, " ", protoreflectPackage.Ident("FileDescriptor")) + g.P() + + genFileDescriptor(gen, g, f) + if len(f.allEnums) > 0 { + g.P("var ", enumTypesVarName(f), " = make([]", protoimplPackage.Ident("EnumInfo"), ",", len(f.allEnums), ")") + } + if len(f.allMessages) > 0 { + g.P("var ", messageTypesVarName(f), " = make([]", protoimplPackage.Ident("MessageInfo"), ",", len(f.allMessages), ")") + } + + // Generate a unique list of Go types for all declarations and dependencies, + // and the associated index into the type list for all dependencies. + var goTypes []string + var depIdxs []string + seen := map[protoreflect.FullName]int{} + genDep := func(name protoreflect.FullName, depSource string) { + if depSource != "" { + line := fmt.Sprintf("%d, // %d: %s -> %s", seen[name], len(depIdxs), depSource, name) + depIdxs = append(depIdxs, line) + } + } + genEnum := func(e *protogen.Enum, depSource string) { + if e != nil { + name := e.Desc.FullName() + if _, ok := seen[name]; !ok { + line := fmt.Sprintf("(%s)(0), // %d: %s", g.QualifiedGoIdent(e.GoIdent), len(goTypes), name) + goTypes = append(goTypes, line) + seen[name] = len(seen) + } + if depSource != "" { + genDep(name, depSource) + } + } + } + genMessage := func(m *protogen.Message, depSource string) { + if m != nil { + name := m.Desc.FullName() + if _, ok := seen[name]; !ok { + line := fmt.Sprintf("(*%s)(nil), // %d: %s", g.QualifiedGoIdent(m.GoIdent), len(goTypes), name) + if m.Desc.IsMapEntry() { + // Map entry messages have no associated Go type. + line = fmt.Sprintf("nil, // %d: %s", len(goTypes), name) + } + goTypes = append(goTypes, line) + seen[name] = len(seen) + } + if depSource != "" { + genDep(name, depSource) + } + } + } + + // This ordering is significant. + // See filetype.TypeBuilder.DependencyIndexes. + type offsetEntry struct { + start int + name string + } + var depOffsets []offsetEntry + for _, enum := range f.allEnums { + genEnum(enum.Enum, "") + } + for _, message := range f.allMessages { + genMessage(message.Message, "") + } + depOffsets = append(depOffsets, offsetEntry{len(depIdxs), "field type_name"}) + for _, message := range f.allMessages { + for _, field := range message.Fields { + if field.Desc.IsWeak() { + continue + } + source := string(field.Desc.FullName()) + genEnum(field.Enum, source+":type_name") + genMessage(field.Message, source+":type_name") + } + } + depOffsets = append(depOffsets, offsetEntry{len(depIdxs), "extension extendee"}) + for _, extension := range f.allExtensions { + source := string(extension.Desc.FullName()) + genMessage(extension.Extendee, source+":extendee") + } + depOffsets = append(depOffsets, offsetEntry{len(depIdxs), "extension type_name"}) + for _, extension := range f.allExtensions { + source := string(extension.Desc.FullName()) + genEnum(extension.Enum, source+":type_name") + genMessage(extension.Message, source+":type_name") + } + depOffsets = append(depOffsets, offsetEntry{len(depIdxs), "method input_type"}) + for _, service := range f.Services { + for _, method := range service.Methods { + source := string(method.Desc.FullName()) + genMessage(method.Input, source+":input_type") + } + } + depOffsets = append(depOffsets, offsetEntry{len(depIdxs), "method output_type"}) + for _, service := range f.Services { + for _, method := range service.Methods { + source := string(method.Desc.FullName()) + genMessage(method.Output, source+":output_type") + } + } + depOffsets = append(depOffsets, offsetEntry{len(depIdxs), ""}) + for i := len(depOffsets) - 2; i >= 0; i-- { + curr, next := depOffsets[i], depOffsets[i+1] + depIdxs = append(depIdxs, fmt.Sprintf("%d, // [%d:%d] is the sub-list for %s", + curr.start, curr.start, next.start, curr.name)) + } + if len(depIdxs) > math.MaxInt32 { + panic("too many dependencies") // sanity check + } + + g.P("var ", goTypesVarName(f), " = []interface{}{") + for _, s := range goTypes { + g.P(s) + } + g.P("}") + + g.P("var ", depIdxsVarName(f), " = []int32{") + for _, s := range depIdxs { + g.P(s) + } + g.P("}") + + g.P("func init() { ", initFuncName(f.File), "() }") + + g.P("func ", initFuncName(f.File), "() {") + g.P("if ", f.GoDescriptorIdent, " != nil {") + g.P("return") + g.P("}") + + // Ensure that initialization functions for different files in the same Go + // package run in the correct order: Call the init funcs for every .proto file + // imported by this one that is in the same Go package. + for i, imps := 0, f.Desc.Imports(); i < imps.Len(); i++ { + impFile := gen.FilesByPath[imps.Get(i).Path()] + if impFile.GoImportPath != f.GoImportPath { + continue + } + g.P(initFuncName(impFile), "()") + } + + if len(f.allMessages) > 0 { + // Populate MessageInfo.Exporters. + g.P("if !", protoimplPackage.Ident("UnsafeEnabled"), " {") + for _, message := range f.allMessages { + if sf := f.allMessageFieldsByPtr[message]; len(sf.unexported) > 0 { + idx := f.allMessagesByPtr[message] + typesVar := messageTypesVarName(f) + + g.P(typesVar, "[", idx, "].Exporter = func(v interface{}, i int) interface{} {") + g.P("switch v := v.(*", message.GoIdent, "); i {") + for i := 0; i < sf.count; i++ { + if name := sf.unexported[i]; name != "" { + g.P("case ", i, ": return &v.", name) + } + } + g.P("default: return nil") + g.P("}") + g.P("}") + } + } + g.P("}") + + // Populate MessageInfo.OneofWrappers. + for _, message := range f.allMessages { + if len(message.Oneofs) > 0 { + idx := f.allMessagesByPtr[message] + typesVar := messageTypesVarName(f) + + // Associate the wrapper types by directly passing them to the MessageInfo. + g.P(typesVar, "[", idx, "].OneofWrappers = []interface{} {") + for _, oneof := range message.Oneofs { + if !oneof.Desc.IsSynthetic() { + for _, field := range oneof.Fields { + g.P("(*", field.GoIdent, ")(nil),") + } + } + } + g.P("}") + } + } + } + + g.P("type x struct{}") + g.P("out := ", protoimplPackage.Ident("TypeBuilder"), "{") + g.P("File: ", protoimplPackage.Ident("DescBuilder"), "{") + g.P("GoPackagePath: ", reflectPackage.Ident("TypeOf"), "(x{}).PkgPath(),") + g.P("RawDescriptor: ", rawDescVarName(f), ",") + g.P("NumEnums: ", len(f.allEnums), ",") + g.P("NumMessages: ", len(f.allMessages), ",") + g.P("NumExtensions: ", len(f.allExtensions), ",") + g.P("NumServices: ", len(f.Services), ",") + g.P("},") + g.P("GoTypes: ", goTypesVarName(f), ",") + g.P("DependencyIndexes: ", depIdxsVarName(f), ",") + if len(f.allEnums) > 0 { + g.P("EnumInfos: ", enumTypesVarName(f), ",") + } + if len(f.allMessages) > 0 { + g.P("MessageInfos: ", messageTypesVarName(f), ",") + } + if len(f.allExtensions) > 0 { + g.P("ExtensionInfos: ", extensionTypesVarName(f), ",") + } + g.P("}.Build()") + g.P(f.GoDescriptorIdent, " = out.File") + + // Set inputs to nil to allow GC to reclaim resources. + g.P(rawDescVarName(f), " = nil") + g.P(goTypesVarName(f), " = nil") + g.P(depIdxsVarName(f), " = nil") + g.P("}") +} + +func genFileDescriptor(gen *protogen.Plugin, g *protogen.GeneratedFile, f *fileInfo) { + descProto := proto.Clone(f.Proto).(*descriptorpb.FileDescriptorProto) + descProto.SourceCodeInfo = nil // drop source code information + + b, err := proto.MarshalOptions{AllowPartial: true, Deterministic: true}.Marshal(descProto) + if err != nil { + gen.Error(err) + return + } + + g.P("var ", rawDescVarName(f), " = []byte{") + for len(b) > 0 { + n := 16 + if n > len(b) { + n = len(b) + } + + s := "" + for _, c := range b[:n] { + s += fmt.Sprintf("0x%02x,", c) + } + g.P(s) + + b = b[n:] + } + g.P("}") + g.P() + + if f.needRawDesc { + onceVar := rawDescVarName(f) + "Once" + dataVar := rawDescVarName(f) + "Data" + g.P("var (") + g.P(onceVar, " ", syncPackage.Ident("Once")) + g.P(dataVar, " = ", rawDescVarName(f)) + g.P(")") + g.P() + + g.P("func ", rawDescVarName(f), "GZIP() []byte {") + g.P(onceVar, ".Do(func() {") + g.P(dataVar, " = ", protoimplPackage.Ident("X"), ".CompressGZIP(", dataVar, ")") + g.P("})") + g.P("return ", dataVar) + g.P("}") + g.P() + } +} + +func genEnumReflectMethods(g *protogen.GeneratedFile, f *fileInfo, e *enumInfo) { + idx := f.allEnumsByPtr[e] + typesVar := enumTypesVarName(f) + + // Descriptor method. + g.P("func (", e.GoIdent, ") Descriptor() ", protoreflectPackage.Ident("EnumDescriptor"), " {") + g.P("return ", typesVar, "[", idx, "].Descriptor()") + g.P("}") + g.P() + + // Type method. + g.P("func (", e.GoIdent, ") Type() ", protoreflectPackage.Ident("EnumType"), " {") + g.P("return &", typesVar, "[", idx, "]") + g.P("}") + g.P() + + // Number method. + g.P("func (x ", e.GoIdent, ") Number() ", protoreflectPackage.Ident("EnumNumber"), " {") + g.P("return ", protoreflectPackage.Ident("EnumNumber"), "(x)") + g.P("}") + g.P() +} + +func genMessageReflectMethods(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { + idx := f.allMessagesByPtr[m] + typesVar := messageTypesVarName(f) + + // ProtoReflect method. + g.P("func (x *", m.GoIdent, ") ProtoReflect() ", protoreflectPackage.Ident("Message"), " {") + g.P("mi := &", typesVar, "[", idx, "]") + g.P("if ", protoimplPackage.Ident("UnsafeEnabled"), " && x != nil {") + g.P("ms := ", protoimplPackage.Ident("X"), ".MessageStateOf(", protoimplPackage.Ident("Pointer"), "(x))") + g.P("if ms.LoadMessageInfo() == nil {") + g.P("ms.StoreMessageInfo(mi)") + g.P("}") + g.P("return ms") + g.P("}") + g.P("return mi.MessageOf(x)") + g.P("}") + g.P() +} + +func fileVarName(f *protogen.File, suffix string) string { + prefix := f.GoDescriptorIdent.GoName + _, n := utf8.DecodeRuneInString(prefix) + prefix = strings.ToLower(prefix[:n]) + prefix[n:] + return prefix + "_" + suffix +} +func rawDescVarName(f *fileInfo) string { + return fileVarName(f.File, "rawDesc") +} +func goTypesVarName(f *fileInfo) string { + return fileVarName(f.File, "goTypes") +} +func depIdxsVarName(f *fileInfo) string { + return fileVarName(f.File, "depIdxs") +} +func enumTypesVarName(f *fileInfo) string { + return fileVarName(f.File, "enumTypes") +} +func messageTypesVarName(f *fileInfo) string { + return fileVarName(f.File, "msgTypes") +} +func extensionTypesVarName(f *fileInfo) string { + return fileVarName(f.File, "extTypes") +} +func initFuncName(f *protogen.File) string { + return fileVarName(f, "init") +} diff --git a/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/well_known_types.go b/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/well_known_types.go new file mode 100644 index 00000000000..9a1b7bdfa3f --- /dev/null +++ b/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo/well_known_types.go @@ -0,0 +1,1077 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package internal_gengo + +import ( + "strings" + + "google.golang.org/protobuf/compiler/protogen" + "google.golang.org/protobuf/internal/genid" +) + +// Specialized support for well-known types are hard-coded into the generator +// as opposed to being injected in adjacent .go sources in the generated package +// in order to support specialized build systems like Bazel that always generate +// dynamically from the source .proto files. + +func genPackageKnownComment(f *fileInfo) protogen.Comments { + switch f.Desc.Path() { + case genid.File_google_protobuf_any_proto: + return ` Package anypb contains generated types for ` + genid.File_google_protobuf_any_proto + `. + + The Any message is a dynamic representation of any other message value. + It is functionally a tuple of the full name of the remote message type and + the serialized bytes of the remote message value. + + + Constructing an Any + + An Any message containing another message value is constructed using New: + + any, err := anypb.New(m) + if err != nil { + ... // handle error + } + ... // make use of any + + + Unmarshaling an Any + + With a populated Any message, the underlying message can be serialized into + a remote concrete message value in a few ways. + + If the exact concrete type is known, then a new (or pre-existing) instance + of that message can be passed to the UnmarshalTo method: + + m := new(foopb.MyMessage) + if err := any.UnmarshalTo(m); err != nil { + ... // handle error + } + ... // make use of m + + If the exact concrete type is not known, then the UnmarshalNew method can be + used to unmarshal the contents into a new instance of the remote message type: + + m, err := any.UnmarshalNew() + if err != nil { + ... // handle error + } + ... // make use of m + + UnmarshalNew uses the global type registry to resolve the message type and + construct a new instance of that message to unmarshal into. In order for a + message type to appear in the global registry, the Go type representing that + protobuf message type must be linked into the Go binary. For messages + generated by protoc-gen-go, this is achieved through an import of the + generated Go package representing a .proto file. + + A common pattern with UnmarshalNew is to use a type switch with the resulting + proto.Message value: + + switch m := m.(type) { + case *foopb.MyMessage: + ... // make use of m as a *foopb.MyMessage + case *barpb.OtherMessage: + ... // make use of m as a *barpb.OtherMessage + case *bazpb.SomeMessage: + ... // make use of m as a *bazpb.SomeMessage + } + + This pattern ensures that the generated packages containing the message types + listed in the case clauses are linked into the Go binary and therefore also + registered in the global registry. + + + Type checking an Any + + In order to type check whether an Any message represents some other message, + then use the MessageIs method: + + if any.MessageIs((*foopb.MyMessage)(nil)) { + ... // make use of any, knowing that it contains a foopb.MyMessage + } + + The MessageIs method can also be used with an allocated instance of the target + message type if the intention is to unmarshal into it if the type matches: + + m := new(foopb.MyMessage) + if any.MessageIs(m) { + if err := any.UnmarshalTo(m); err != nil { + ... // handle error + } + ... // make use of m + } + +` + case genid.File_google_protobuf_timestamp_proto: + return ` Package timestamppb contains generated types for ` + genid.File_google_protobuf_timestamp_proto + `. + + The Timestamp message represents a timestamp, + an instant in time since the Unix epoch (January 1st, 1970). + + + Conversion to a Go Time + + The AsTime method can be used to convert a Timestamp message to a + standard Go time.Time value in UTC: + + t := ts.AsTime() + ... // make use of t as a time.Time + + Converting to a time.Time is a common operation so that the extensive + set of time-based operations provided by the time package can be leveraged. + See https://golang.org/pkg/time for more information. + + The AsTime method performs the conversion on a best-effort basis. Timestamps + with denormal values (e.g., nanoseconds beyond 0 and 99999999, inclusive) + are normalized during the conversion to a time.Time. To manually check for + invalid Timestamps per the documented limitations in timestamp.proto, + additionally call the CheckValid method: + + if err := ts.CheckValid(); err != nil { + ... // handle error + } + + + Conversion from a Go Time + + The timestamppb.New function can be used to construct a Timestamp message + from a standard Go time.Time value: + + ts := timestamppb.New(t) + ... // make use of ts as a *timestamppb.Timestamp + + In order to construct a Timestamp representing the current time, use Now: + + ts := timestamppb.Now() + ... // make use of ts as a *timestamppb.Timestamp + +` + case genid.File_google_protobuf_duration_proto: + return ` Package durationpb contains generated types for ` + genid.File_google_protobuf_duration_proto + `. + + The Duration message represents a signed span of time. + + + Conversion to a Go Duration + + The AsDuration method can be used to convert a Duration message to a + standard Go time.Duration value: + + d := dur.AsDuration() + ... // make use of d as a time.Duration + + Converting to a time.Duration is a common operation so that the extensive + set of time-based operations provided by the time package can be leveraged. + See https://golang.org/pkg/time for more information. + + The AsDuration method performs the conversion on a best-effort basis. + Durations with denormal values (e.g., nanoseconds beyond -99999999 and + +99999999, inclusive; or seconds and nanoseconds with opposite signs) + are normalized during the conversion to a time.Duration. To manually check for + invalid Duration per the documented limitations in duration.proto, + additionally call the CheckValid method: + + if err := dur.CheckValid(); err != nil { + ... // handle error + } + + Note that the documented limitations in duration.proto does not protect a + Duration from overflowing the representable range of a time.Duration in Go. + The AsDuration method uses saturation arithmetic such that an overflow clamps + the resulting value to the closest representable value (e.g., math.MaxInt64 + for positive overflow and math.MinInt64 for negative overflow). + + + Conversion from a Go Duration + + The durationpb.New function can be used to construct a Duration message + from a standard Go time.Duration value: + + dur := durationpb.New(d) + ... // make use of d as a *durationpb.Duration + +` + case genid.File_google_protobuf_struct_proto: + return ` Package structpb contains generated types for ` + genid.File_google_protobuf_struct_proto + `. + + The messages (i.e., Value, Struct, and ListValue) defined in struct.proto are + used to represent arbitrary JSON. The Value message represents a JSON value, + the Struct message represents a JSON object, and the ListValue message + represents a JSON array. See https://json.org for more information. + + The Value, Struct, and ListValue types have generated MarshalJSON and + UnmarshalJSON methods such that they serialize JSON equivalent to what the + messages themselves represent. Use of these types with the + "google.golang.org/protobuf/encoding/protojson" package + ensures that they will be serialized as their JSON equivalent. + + + Conversion to and from a Go interface + + The standard Go "encoding/json" package has functionality to serialize + arbitrary types to a large degree. The Value.AsInterface, Struct.AsMap, and + ListValue.AsSlice methods can convert the protobuf message representation into + a form represented by interface{}, map[string]interface{}, and []interface{}. + This form can be used with other packages that operate on such data structures + and also directly with the standard json package. + + In order to convert the interface{}, map[string]interface{}, and []interface{} + forms back as Value, Struct, and ListValue messages, use the NewStruct, + NewList, and NewValue constructor functions. + + + Example usage + + Consider the following example JSON object: + + { + "firstName": "John", + "lastName": "Smith", + "isAlive": true, + "age": 27, + "address": { + "streetAddress": "21 2nd Street", + "city": "New York", + "state": "NY", + "postalCode": "10021-3100" + }, + "phoneNumbers": [ + { + "type": "home", + "number": "212 555-1234" + }, + { + "type": "office", + "number": "646 555-4567" + } + ], + "children": [], + "spouse": null + } + + To construct a Value message representing the above JSON object: + + m, err := structpb.NewValue(map[string]interface{}{ + "firstName": "John", + "lastName": "Smith", + "isAlive": true, + "age": 27, + "address": map[string]interface{}{ + "streetAddress": "21 2nd Street", + "city": "New York", + "state": "NY", + "postalCode": "10021-3100", + }, + "phoneNumbers": []interface{}{ + map[string]interface{}{ + "type": "home", + "number": "212 555-1234", + }, + map[string]interface{}{ + "type": "office", + "number": "646 555-4567", + }, + }, + "children": []interface{}{}, + "spouse": nil, + }) + if err != nil { + ... // handle error + } + ... // make use of m as a *structpb.Value + +` + case genid.File_google_protobuf_field_mask_proto: + return ` Package fieldmaskpb contains generated types for ` + genid.File_google_protobuf_field_mask_proto + `. + + The FieldMask message represents a set of symbolic field paths. + The paths are specific to some target message type, + which is not stored within the FieldMask message itself. + + + Constructing a FieldMask + + The New function is used construct a FieldMask: + + var messageType *descriptorpb.DescriptorProto + fm, err := fieldmaskpb.New(messageType, "field.name", "field.number") + if err != nil { + ... // handle error + } + ... // make use of fm + + The "field.name" and "field.number" paths are valid paths according to the + google.protobuf.DescriptorProto message. Use of a path that does not correlate + to valid fields reachable from DescriptorProto would result in an error. + + Once a FieldMask message has been constructed, + the Append method can be used to insert additional paths to the path set: + + var messageType *descriptorpb.DescriptorProto + if err := fm.Append(messageType, "options"); err != nil { + ... // handle error + } + + + Type checking a FieldMask + + In order to verify that a FieldMask represents a set of fields that are + reachable from some target message type, use the IsValid method: + + var messageType *descriptorpb.DescriptorProto + if fm.IsValid(messageType) { + ... // make use of fm + } + + IsValid needs to be passed the target message type as an input since the + FieldMask message itself does not store the message type that the set of paths + are for. +` + default: + return "" + } +} + +func genMessageKnownFunctions(g *protogen.GeneratedFile, f *fileInfo, m *messageInfo) { + switch m.Desc.FullName() { + case genid.Any_message_fullname: + g.P("// New marshals src into a new Any instance.") + g.P("func New(src ", protoPackage.Ident("Message"), ") (*Any, error) {") + g.P(" dst := new(Any)") + g.P(" if err := dst.MarshalFrom(src); err != nil {") + g.P(" return nil, err") + g.P(" }") + g.P(" return dst, nil") + g.P("}") + g.P() + + g.P("// MarshalFrom marshals src into dst as the underlying message") + g.P("// using the provided marshal options.") + g.P("//") + g.P("// If no options are specified, call dst.MarshalFrom instead.") + g.P("func MarshalFrom(dst *Any, src ", protoPackage.Ident("Message"), ", opts ", protoPackage.Ident("MarshalOptions"), ") error {") + g.P(" const urlPrefix = \"type.googleapis.com/\"") + g.P(" if src == nil {") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil source message\")") + g.P(" }") + g.P(" b, err := opts.Marshal(src)") + g.P(" if err != nil {") + g.P(" return err") + g.P(" }") + g.P(" dst.TypeUrl = urlPrefix + string(src.ProtoReflect().Descriptor().FullName())") + g.P(" dst.Value = b") + g.P(" return nil") + g.P("}") + g.P() + + g.P("// UnmarshalTo unmarshals the underlying message from src into dst") + g.P("// using the provided unmarshal options.") + g.P("// It reports an error if dst is not of the right message type.") + g.P("//") + g.P("// If no options are specified, call src.UnmarshalTo instead.") + g.P("func UnmarshalTo(src *Any, dst ", protoPackage.Ident("Message"), ", opts ", protoPackage.Ident("UnmarshalOptions"), ") error {") + g.P(" if src == nil {") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil source message\")") + g.P(" }") + g.P(" if !src.MessageIs(dst) {") + g.P(" got := dst.ProtoReflect().Descriptor().FullName()") + g.P(" want := src.MessageName()") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"mismatched message type: got %q, want %q\", got, want)") + g.P(" }") + g.P(" return opts.Unmarshal(src.GetValue(), dst)") + g.P("}") + g.P() + + g.P("// UnmarshalNew unmarshals the underlying message from src into dst,") + g.P("// which is newly created message using a type resolved from the type URL.") + g.P("// The message type is resolved according to opt.Resolver,") + g.P("// which should implement protoregistry.MessageTypeResolver.") + g.P("// It reports an error if the underlying message type could not be resolved.") + g.P("//") + g.P("// If no options are specified, call src.UnmarshalNew instead.") + g.P("func UnmarshalNew(src *Any, opts ", protoPackage.Ident("UnmarshalOptions"), ") (dst ", protoPackage.Ident("Message"), ", err error) {") + g.P(" if src.GetTypeUrl() == \"\" {") + g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid empty type URL\")") + g.P(" }") + g.P(" if opts.Resolver == nil {") + g.P(" opts.Resolver = ", protoregistryPackage.Ident("GlobalTypes")) + g.P(" }") + g.P(" r, ok := opts.Resolver.(", protoregistryPackage.Ident("MessageTypeResolver"), ")") + g.P(" if !ok {") + g.P(" return nil, ", protoregistryPackage.Ident("NotFound")) + g.P(" }") + g.P(" mt, err := r.FindMessageByURL(src.GetTypeUrl())") + g.P(" if err != nil {") + g.P(" if err == ", protoregistryPackage.Ident("NotFound"), " {") + g.P(" return nil, err") + g.P(" }") + g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"could not resolve %q: %v\", src.GetTypeUrl(), err)") + g.P(" }") + g.P(" dst = mt.New().Interface()") + g.P(" return dst, opts.Unmarshal(src.GetValue(), dst)") + g.P("}") + g.P() + + g.P("// MessageIs reports whether the underlying message is of the same type as m.") + g.P("func (x *Any) MessageIs(m ", protoPackage.Ident("Message"), ") bool {") + g.P(" if m == nil {") + g.P(" return false") + g.P(" }") + g.P(" url := x.GetTypeUrl()") + g.P(" name := string(m.ProtoReflect().Descriptor().FullName())") + g.P(" if !", stringsPackage.Ident("HasSuffix"), "(url, name) {") + g.P(" return false") + g.P(" }") + g.P(" return len(url) == len(name) || url[len(url)-len(name)-1] == '/'") + g.P("}") + g.P() + + g.P("// MessageName reports the full name of the underlying message,") + g.P("// returning an empty string if invalid.") + g.P("func (x *Any) MessageName() ", protoreflectPackage.Ident("FullName"), " {") + g.P(" url := x.GetTypeUrl()") + g.P(" name := ", protoreflectPackage.Ident("FullName"), "(url)") + g.P(" if i := ", stringsPackage.Ident("LastIndexByte"), "(url, '/'); i >= 0 {") + g.P(" name = name[i+len(\"/\"):]") + g.P(" }") + g.P(" if !name.IsValid() {") + g.P(" return \"\"") + g.P(" }") + g.P(" return name") + g.P("}") + g.P() + + g.P("// MarshalFrom marshals m into x as the underlying message.") + g.P("func (x *Any) MarshalFrom(m ", protoPackage.Ident("Message"), ") error {") + g.P(" return MarshalFrom(x, m, ", protoPackage.Ident("MarshalOptions"), "{})") + g.P("}") + g.P() + + g.P("// UnmarshalTo unmarshals the contents of the underlying message of x into m.") + g.P("// It resets m before performing the unmarshal operation.") + g.P("// It reports an error if m is not of the right message type.") + g.P("func (x *Any) UnmarshalTo(m ", protoPackage.Ident("Message"), ") error {") + g.P(" return UnmarshalTo(x, m, ", protoPackage.Ident("UnmarshalOptions"), "{})") + g.P("}") + g.P() + + g.P("// UnmarshalNew unmarshals the contents of the underlying message of x into") + g.P("// a newly allocated message of the specified type.") + g.P("// It reports an error if the underlying message type could not be resolved.") + g.P("func (x *Any) UnmarshalNew() (", protoPackage.Ident("Message"), ", error) {") + g.P(" return UnmarshalNew(x, ", protoPackage.Ident("UnmarshalOptions"), "{})") + g.P("}") + g.P() + + case genid.Timestamp_message_fullname: + g.P("// Now constructs a new Timestamp from the current time.") + g.P("func Now() *Timestamp {") + g.P(" return New(", timePackage.Ident("Now"), "())") + g.P("}") + g.P() + + g.P("// New constructs a new Timestamp from the provided time.Time.") + g.P("func New(t ", timePackage.Ident("Time"), ") *Timestamp {") + g.P(" return &Timestamp{Seconds: int64(t.Unix()), Nanos: int32(t.Nanosecond())}") + g.P("}") + g.P() + + g.P("// AsTime converts x to a time.Time.") + g.P("func (x *Timestamp) AsTime() ", timePackage.Ident("Time"), " {") + g.P(" return ", timePackage.Ident("Unix"), "(int64(x.GetSeconds()), int64(x.GetNanos())).UTC()") + g.P("}") + g.P() + + g.P("// IsValid reports whether the timestamp is valid.") + g.P("// It is equivalent to CheckValid == nil.") + g.P("func (x *Timestamp) IsValid() bool {") + g.P(" return x.check() == 0") + g.P("}") + g.P() + + g.P("// CheckValid returns an error if the timestamp is invalid.") + g.P("// In particular, it checks whether the value represents a date that is") + g.P("// in the range of 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.") + g.P("// An error is reported for a nil Timestamp.") + g.P("func (x *Timestamp) CheckValid() error {") + g.P(" switch x.check() {") + g.P(" case invalidNil:") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil Timestamp\")") + g.P(" case invalidUnderflow:") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"timestamp (%v) before 0001-01-01\", x)") + g.P(" case invalidOverflow:") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"timestamp (%v) after 9999-12-31\", x)") + g.P(" case invalidNanos:") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"timestamp (%v) has out-of-range nanos\", x)") + g.P(" default:") + g.P(" return nil") + g.P(" }") + g.P("}") + g.P() + + g.P("const (") + g.P(" _ = iota") + g.P(" invalidNil") + g.P(" invalidUnderflow") + g.P(" invalidOverflow") + g.P(" invalidNanos") + g.P(")") + g.P() + + g.P("func (x *Timestamp) check() uint {") + g.P(" const minTimestamp = -62135596800 // Seconds between 1970-01-01T00:00:00Z and 0001-01-01T00:00:00Z, inclusive") + g.P(" const maxTimestamp = +253402300799 // Seconds between 1970-01-01T00:00:00Z and 9999-12-31T23:59:59Z, inclusive") + g.P(" secs := x.GetSeconds()") + g.P(" nanos := x.GetNanos()") + g.P(" switch {") + g.P(" case x == nil:") + g.P(" return invalidNil") + g.P(" case secs < minTimestamp:") + g.P(" return invalidUnderflow") + g.P(" case secs > maxTimestamp:") + g.P(" return invalidOverflow") + g.P(" case nanos < 0 || nanos >= 1e9:") + g.P(" return invalidNanos") + g.P(" default:") + g.P(" return 0") + g.P(" }") + g.P("}") + g.P() + + case genid.Duration_message_fullname: + g.P("// New constructs a new Duration from the provided time.Duration.") + g.P("func New(d ", timePackage.Ident("Duration"), ") *Duration {") + g.P(" nanos := d.Nanoseconds()") + g.P(" secs := nanos / 1e9") + g.P(" nanos -= secs * 1e9") + g.P(" return &Duration{Seconds: int64(secs), Nanos: int32(nanos)}") + g.P("}") + g.P() + + g.P("// AsDuration converts x to a time.Duration,") + g.P("// returning the closest duration value in the event of overflow.") + g.P("func (x *Duration) AsDuration() ", timePackage.Ident("Duration"), " {") + g.P(" secs := x.GetSeconds()") + g.P(" nanos := x.GetNanos()") + g.P(" d := ", timePackage.Ident("Duration"), "(secs) * ", timePackage.Ident("Second")) + g.P(" overflow := d/", timePackage.Ident("Second"), " != ", timePackage.Ident("Duration"), "(secs)") + g.P(" d += ", timePackage.Ident("Duration"), "(nanos) * ", timePackage.Ident("Nanosecond")) + g.P(" overflow = overflow || (secs < 0 && nanos < 0 && d > 0)") + g.P(" overflow = overflow || (secs > 0 && nanos > 0 && d < 0)") + g.P(" if overflow {") + g.P(" switch {") + g.P(" case secs < 0:") + g.P(" return ", timePackage.Ident("Duration"), "(", mathPackage.Ident("MinInt64"), ")") + g.P(" case secs > 0:") + g.P(" return ", timePackage.Ident("Duration"), "(", mathPackage.Ident("MaxInt64"), ")") + g.P(" }") + g.P(" }") + g.P(" return d") + g.P("}") + g.P() + + g.P("// IsValid reports whether the duration is valid.") + g.P("// It is equivalent to CheckValid == nil.") + g.P("func (x *Duration) IsValid() bool {") + g.P(" return x.check() == 0") + g.P("}") + g.P() + + g.P("// CheckValid returns an error if the duration is invalid.") + g.P("// In particular, it checks whether the value is within the range of") + g.P("// -10000 years to +10000 years inclusive.") + g.P("// An error is reported for a nil Duration.") + g.P("func (x *Duration) CheckValid() error {") + g.P(" switch x.check() {") + g.P(" case invalidNil:") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil Duration\")") + g.P(" case invalidUnderflow:") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) exceeds -10000 years\", x)") + g.P(" case invalidOverflow:") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) exceeds +10000 years\", x)") + g.P(" case invalidNanosRange:") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) has out-of-range nanos\", x)") + g.P(" case invalidNanosSign:") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) has seconds and nanos with different signs\", x)") + g.P(" default:") + g.P(" return nil") + g.P(" }") + g.P("}") + g.P() + + g.P("const (") + g.P(" _ = iota") + g.P(" invalidNil") + g.P(" invalidUnderflow") + g.P(" invalidOverflow") + g.P(" invalidNanosRange") + g.P(" invalidNanosSign") + g.P(")") + g.P() + + g.P("func (x *Duration) check() uint {") + g.P(" const absDuration = 315576000000 // 10000yr * 365.25day/yr * 24hr/day * 60min/hr * 60sec/min") + g.P(" secs := x.GetSeconds()") + g.P(" nanos := x.GetNanos()") + g.P(" switch {") + g.P(" case x == nil:") + g.P(" return invalidNil") + g.P(" case secs < -absDuration:") + g.P(" return invalidUnderflow") + g.P(" case secs > +absDuration:") + g.P(" return invalidOverflow") + g.P(" case nanos <= -1e9 || nanos >= +1e9:") + g.P(" return invalidNanosRange") + g.P(" case (secs > 0 && nanos < 0) || (secs < 0 && nanos > 0):") + g.P(" return invalidNanosSign") + g.P(" default:") + g.P(" return 0") + g.P(" }") + g.P("}") + g.P() + + case genid.Struct_message_fullname: + g.P("// NewStruct constructs a Struct from a general-purpose Go map.") + g.P("// The map keys must be valid UTF-8.") + g.P("// The map values are converted using NewValue.") + g.P("func NewStruct(v map[string]interface{}) (*Struct, error) {") + g.P(" x := &Struct{Fields: make(map[string]*Value, len(v))}") + g.P(" for k, v := range v {") + g.P(" if !", utf8Package.Ident("ValidString"), "(k) {") + g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid UTF-8 in string: %q\", k)") + g.P(" }") + g.P(" var err error") + g.P(" x.Fields[k], err = NewValue(v)") + g.P(" if err != nil {") + g.P(" return nil, err") + g.P(" }") + g.P(" }") + g.P(" return x, nil") + g.P("}") + g.P() + + g.P("// AsMap converts x to a general-purpose Go map.") + g.P("// The map values are converted by calling Value.AsInterface.") + g.P("func (x *Struct) AsMap() map[string]interface{} {") + g.P(" vs := make(map[string]interface{})") + g.P(" for k, v := range x.GetFields() {") + g.P(" vs[k] = v.AsInterface()") + g.P(" }") + g.P(" return vs") + g.P("}") + g.P() + + g.P("func (x *Struct) MarshalJSON() ([]byte, error) {") + g.P(" return ", protojsonPackage.Ident("Marshal"), "(x)") + g.P("}") + g.P() + + g.P("func (x *Struct) UnmarshalJSON(b []byte) error {") + g.P(" return ", protojsonPackage.Ident("Unmarshal"), "(b, x)") + g.P("}") + g.P() + + case genid.ListValue_message_fullname: + g.P("// NewList constructs a ListValue from a general-purpose Go slice.") + g.P("// The slice elements are converted using NewValue.") + g.P("func NewList(v []interface{}) (*ListValue, error) {") + g.P(" x := &ListValue{Values: make([]*Value, len(v))}") + g.P(" for i, v := range v {") + g.P(" var err error") + g.P(" x.Values[i], err = NewValue(v)") + g.P(" if err != nil {") + g.P(" return nil, err") + g.P(" }") + g.P(" }") + g.P(" return x, nil") + g.P("}") + g.P() + + g.P("// AsSlice converts x to a general-purpose Go slice.") + g.P("// The slice elements are converted by calling Value.AsInterface.") + g.P("func (x *ListValue) AsSlice() []interface{} {") + g.P(" vs := make([]interface{}, len(x.GetValues()))") + g.P(" for i, v := range x.GetValues() {") + g.P(" vs[i] = v.AsInterface()") + g.P(" }") + g.P(" return vs") + g.P("}") + g.P() + + g.P("func (x *ListValue) MarshalJSON() ([]byte, error) {") + g.P(" return ", protojsonPackage.Ident("Marshal"), "(x)") + g.P("}") + g.P() + + g.P("func (x *ListValue) UnmarshalJSON(b []byte) error {") + g.P(" return ", protojsonPackage.Ident("Unmarshal"), "(b, x)") + g.P("}") + g.P() + + case genid.Value_message_fullname: + g.P("// NewValue constructs a Value from a general-purpose Go interface.") + g.P("//") + g.P("// ╔════════════════════════╤════════════════════════════════════════════╗") + g.P("// ║ Go type │ Conversion ║") + g.P("// ╠════════════════════════╪════════════════════════════════════════════╣") + g.P("// ║ nil │ stored as NullValue ║") + g.P("// ║ bool │ stored as BoolValue ║") + g.P("// ║ int, int32, int64 │ stored as NumberValue ║") + g.P("// ║ uint, uint32, uint64 │ stored as NumberValue ║") + g.P("// ║ float32, float64 │ stored as NumberValue ║") + g.P("// ║ string │ stored as StringValue; must be valid UTF-8 ║") + g.P("// ║ []byte │ stored as StringValue; base64-encoded ║") + g.P("// ║ map[string]interface{} │ stored as StructValue ║") + g.P("// ║ []interface{} │ stored as ListValue ║") + g.P("// ╚════════════════════════╧════════════════════════════════════════════╝") + g.P("//") + g.P("// When converting an int64 or uint64 to a NumberValue, numeric precision loss") + g.P("// is possible since they are stored as a float64.") + g.P("func NewValue(v interface{}) (*Value, error) {") + g.P(" switch v := v.(type) {") + g.P(" case nil:") + g.P(" return NewNullValue(), nil") + g.P(" case bool:") + g.P(" return NewBoolValue(v), nil") + g.P(" case int:") + g.P(" return NewNumberValue(float64(v)), nil") + g.P(" case int32:") + g.P(" return NewNumberValue(float64(v)), nil") + g.P(" case int64:") + g.P(" return NewNumberValue(float64(v)), nil") + g.P(" case uint:") + g.P(" return NewNumberValue(float64(v)), nil") + g.P(" case uint32:") + g.P(" return NewNumberValue(float64(v)), nil") + g.P(" case uint64:") + g.P(" return NewNumberValue(float64(v)), nil") + g.P(" case float32:") + g.P(" return NewNumberValue(float64(v)), nil") + g.P(" case float64:") + g.P(" return NewNumberValue(float64(v)), nil") + g.P(" case string:") + g.P(" if !", utf8Package.Ident("ValidString"), "(v) {") + g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid UTF-8 in string: %q\", v)") + g.P(" }") + g.P(" return NewStringValue(v), nil") + g.P(" case []byte:") + g.P(" s := ", base64Package.Ident("StdEncoding"), ".EncodeToString(v)") + g.P(" return NewStringValue(s), nil") + g.P(" case map[string]interface{}:") + g.P(" v2, err := NewStruct(v)") + g.P(" if err != nil {") + g.P(" return nil, err") + g.P(" }") + g.P(" return NewStructValue(v2), nil") + g.P(" case []interface{}:") + g.P(" v2, err := NewList(v)") + g.P(" if err != nil {") + g.P(" return nil, err") + g.P(" }") + g.P(" return NewListValue(v2), nil") + g.P(" default:") + g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid type: %T\", v)") + g.P(" }") + g.P("}") + g.P() + + g.P("// NewNullValue constructs a new null Value.") + g.P("func NewNullValue() *Value {") + g.P(" return &Value{Kind: &Value_NullValue{NullValue: NullValue_NULL_VALUE}}") + g.P("}") + g.P() + + g.P("// NewBoolValue constructs a new boolean Value.") + g.P("func NewBoolValue(v bool) *Value {") + g.P(" return &Value{Kind: &Value_BoolValue{BoolValue: v}}") + g.P("}") + g.P() + + g.P("// NewNumberValue constructs a new number Value.") + g.P("func NewNumberValue(v float64) *Value {") + g.P(" return &Value{Kind: &Value_NumberValue{NumberValue: v}}") + g.P("}") + g.P() + + g.P("// NewStringValue constructs a new string Value.") + g.P("func NewStringValue(v string) *Value {") + g.P(" return &Value{Kind: &Value_StringValue{StringValue: v}}") + g.P("}") + g.P() + + g.P("// NewStructValue constructs a new struct Value.") + g.P("func NewStructValue(v *Struct) *Value {") + g.P(" return &Value{Kind: &Value_StructValue{StructValue: v}}") + g.P("}") + g.P() + + g.P("// NewListValue constructs a new list Value.") + g.P("func NewListValue(v *ListValue) *Value {") + g.P(" return &Value{Kind: &Value_ListValue{ListValue: v}}") + g.P("}") + g.P() + + g.P("// AsInterface converts x to a general-purpose Go interface.") + g.P("//") + g.P("// Calling Value.MarshalJSON and \"encoding/json\".Marshal on this output produce") + g.P("// semantically equivalent JSON (assuming no errors occur).") + g.P("//") + g.P("// Floating-point values (i.e., \"NaN\", \"Infinity\", and \"-Infinity\") are") + g.P("// converted as strings to remain compatible with MarshalJSON.") + g.P("func (x *Value) AsInterface() interface{} {") + g.P(" switch v := x.GetKind().(type) {") + g.P(" case *Value_NumberValue:") + g.P(" if v != nil {") + g.P(" switch {") + g.P(" case ", mathPackage.Ident("IsNaN"), "(v.NumberValue):") + g.P(" return \"NaN\"") + g.P(" case ", mathPackage.Ident("IsInf"), "(v.NumberValue, +1):") + g.P(" return \"Infinity\"") + g.P(" case ", mathPackage.Ident("IsInf"), "(v.NumberValue, -1):") + g.P(" return \"-Infinity\"") + g.P(" default:") + g.P(" return v.NumberValue") + g.P(" }") + g.P(" }") + g.P(" case *Value_StringValue:") + g.P(" if v != nil {") + g.P(" return v.StringValue") + g.P(" }") + g.P(" case *Value_BoolValue:") + g.P(" if v != nil {") + g.P(" return v.BoolValue") + g.P(" }") + g.P(" case *Value_StructValue:") + g.P(" if v != nil {") + g.P(" return v.StructValue.AsMap()") + g.P(" }") + g.P(" case *Value_ListValue:") + g.P(" if v != nil {") + g.P(" return v.ListValue.AsSlice()") + g.P(" }") + g.P(" }") + g.P(" return nil") + g.P("}") + g.P() + + g.P("func (x *Value) MarshalJSON() ([]byte, error) {") + g.P(" return ", protojsonPackage.Ident("Marshal"), "(x)") + g.P("}") + g.P() + + g.P("func (x *Value) UnmarshalJSON(b []byte) error {") + g.P(" return ", protojsonPackage.Ident("Unmarshal"), "(b, x)") + g.P("}") + g.P() + + case genid.FieldMask_message_fullname: + g.P("// New constructs a field mask from a list of paths and verifies that") + g.P("// each one is valid according to the specified message type.") + g.P("func New(m ", protoPackage.Ident("Message"), ", paths ...string) (*FieldMask, error) {") + g.P(" x := new(FieldMask)") + g.P(" return x, x.Append(m, paths...)") + g.P("}") + g.P() + + g.P("// Union returns the union of all the paths in the input field masks.") + g.P("func Union(mx *FieldMask, my *FieldMask, ms ...*FieldMask) *FieldMask {") + g.P(" var out []string") + g.P(" out = append(out, mx.GetPaths()...)") + g.P(" out = append(out, my.GetPaths()...)") + g.P(" for _, m := range ms {") + g.P(" out = append(out, m.GetPaths()...)") + g.P(" }") + g.P(" return &FieldMask{Paths: normalizePaths(out)}") + g.P("}") + g.P() + + g.P("// Intersect returns the intersection of all the paths in the input field masks.") + g.P("func Intersect(mx *FieldMask, my *FieldMask, ms ...*FieldMask) *FieldMask {") + g.P(" var ss1, ss2 []string // reused buffers for performance") + g.P(" intersect := func(out, in []string) []string {") + g.P(" ss1 = normalizePaths(append(ss1[:0], in...))") + g.P(" ss2 = normalizePaths(append(ss2[:0], out...))") + g.P(" out = out[:0]") + g.P(" for i1, i2 := 0, 0; i1 < len(ss1) && i2 < len(ss2); {") + g.P(" switch s1, s2 := ss1[i1], ss2[i2]; {") + g.P(" case hasPathPrefix(s1, s2):") + g.P(" out = append(out, s1)") + g.P(" i1++") + g.P(" case hasPathPrefix(s2, s1):") + g.P(" out = append(out, s2)") + g.P(" i2++") + g.P(" case lessPath(s1, s2):") + g.P(" i1++") + g.P(" case lessPath(s2, s1):") + g.P(" i2++") + g.P(" }") + g.P(" }") + g.P(" return out") + g.P(" }") + g.P() + g.P(" out := Union(mx, my, ms...).GetPaths()") + g.P(" out = intersect(out, mx.GetPaths())") + g.P(" out = intersect(out, my.GetPaths())") + g.P(" for _, m := range ms {") + g.P(" out = intersect(out, m.GetPaths())") + g.P(" }") + g.P(" return &FieldMask{Paths: normalizePaths(out)}") + g.P("}") + g.P() + + g.P("// IsValid reports whether all the paths are syntactically valid and") + g.P("// refer to known fields in the specified message type.") + g.P("// It reports false for a nil FieldMask.") + g.P("func (x *FieldMask) IsValid(m ", protoPackage.Ident("Message"), ") bool {") + g.P(" paths := x.GetPaths()") + g.P(" return x != nil && numValidPaths(m, paths) == len(paths)") + g.P("}") + g.P() + + g.P("// Append appends a list of paths to the mask and verifies that each one") + g.P("// is valid according to the specified message type.") + g.P("// An invalid path is not appended and breaks insertion of subsequent paths.") + g.P("func (x *FieldMask) Append(m ", protoPackage.Ident("Message"), ", paths ...string) error {") + g.P(" numValid := numValidPaths(m, paths)") + g.P(" x.Paths = append(x.Paths, paths[:numValid]...)") + g.P(" paths = paths[numValid:]") + g.P(" if len(paths) > 0 {") + g.P(" name := m.ProtoReflect().Descriptor().FullName()") + g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid path %q for message %q\", paths[0], name)") + g.P(" }") + g.P(" return nil") + g.P("}") + g.P() + + g.P("func numValidPaths(m ", protoPackage.Ident("Message"), ", paths []string) int {") + g.P(" md0 := m.ProtoReflect().Descriptor()") + g.P(" for i, path := range paths {") + g.P(" md := md0") + g.P(" if !rangeFields(path, func(field string) bool {") + g.P(" // Search the field within the message.") + g.P(" if md == nil {") + g.P(" return false // not within a message") + g.P(" }") + g.P(" fd := md.Fields().ByName(", protoreflectPackage.Ident("Name"), "(field))") + g.P(" // The real field name of a group is the message name.") + g.P(" if fd == nil {") + g.P(" gd := md.Fields().ByName(", protoreflectPackage.Ident("Name"), "(", stringsPackage.Ident("ToLower"), "(field)))") + g.P(" if gd != nil && gd.Kind() == ", protoreflectPackage.Ident("GroupKind"), " && string(gd.Message().Name()) == field {") + g.P(" fd = gd") + g.P(" }") + g.P(" } else if fd.Kind() == ", protoreflectPackage.Ident("GroupKind"), " && string(fd.Message().Name()) != field {") + g.P(" fd = nil") + g.P(" }") + g.P(" if fd == nil {") + g.P(" return false // message has does not have this field") + g.P(" }") + g.P() + g.P(" // Identify the next message to search within.") + g.P(" md = fd.Message() // may be nil") + g.P(" if fd.IsMap() {") + g.P(" md = fd.MapValue().Message() // may be nil") + g.P(" }") + g.P(" return true") + g.P(" }) {") + g.P(" return i") + g.P(" }") + g.P(" }") + g.P(" return len(paths)") + g.P("}") + g.P() + + g.P("// Normalize converts the mask to its canonical form where all paths are sorted") + g.P("// and redundant paths are removed.") + g.P("func (x *FieldMask) Normalize() {") + g.P(" x.Paths = normalizePaths(x.Paths)") + g.P("}") + g.P() + g.P("func normalizePaths(paths []string) []string {") + g.P(" ", sortPackage.Ident("Slice"), "(paths, func(i, j int) bool {") + g.P(" return lessPath(paths[i], paths[j])") + g.P(" })") + g.P() + g.P(" // Elide any path that is a prefix match on the previous.") + g.P(" out := paths[:0]") + g.P(" for _, path := range paths {") + g.P(" if len(out) > 0 && hasPathPrefix(path, out[len(out)-1]) {") + g.P(" continue") + g.P(" }") + g.P(" out = append(out, path)") + g.P(" }") + g.P(" return out") + g.P("}") + g.P() + + g.P("// hasPathPrefix is like strings.HasPrefix, but further checks for either") + g.P("// an exact matche or that the prefix is delimited by a dot.") + g.P("func hasPathPrefix(path, prefix string) bool {") + g.P(" return ", stringsPackage.Ident("HasPrefix"), "(path, prefix) && (len(path) == len(prefix) || path[len(prefix)] == '.')") + g.P("}") + g.P() + + g.P("// lessPath is a lexicographical comparison where dot is specially treated") + g.P("// as the smallest symbol.") + g.P("func lessPath(x, y string) bool {") + g.P(" for i := 0; i < len(x) && i < len(y); i++ {") + g.P(" if x[i] != y[i] {") + g.P(" return (x[i] - '.') < (y[i] - '.')") + g.P(" }") + g.P(" }") + g.P(" return len(x) < len(y)") + g.P("}") + g.P() + + g.P("// rangeFields is like strings.Split(path, \".\"), but avoids allocations by") + g.P("// iterating over each field in place and calling a iterator function.") + g.P("func rangeFields(path string, f func(field string) bool) bool {") + g.P(" for {") + g.P(" var field string") + g.P(" if i := ", stringsPackage.Ident("IndexByte"), "(path, '.'); i >= 0 {") + g.P(" field, path = path[:i], path[i:]") + g.P(" } else {") + g.P(" field, path = path, \"\"") + g.P(" }") + g.P() + g.P(" if !f(field) {") + g.P(" return false") + g.P(" }") + g.P() + g.P(" if len(path) == 0 {") + g.P(" return true") + g.P(" }") + g.P(" path = ", stringsPackage.Ident("TrimPrefix"), "(path, \".\")") + g.P(" }") + g.P("}") + g.P() + + case genid.BoolValue_message_fullname, + genid.Int32Value_message_fullname, + genid.Int64Value_message_fullname, + genid.UInt32Value_message_fullname, + genid.UInt64Value_message_fullname, + genid.FloatValue_message_fullname, + genid.DoubleValue_message_fullname, + genid.StringValue_message_fullname, + genid.BytesValue_message_fullname: + funcName := strings.TrimSuffix(m.GoIdent.GoName, "Value") + typeName := strings.ToLower(funcName) + switch typeName { + case "float": + typeName = "float32" + case "double": + typeName = "float64" + case "bytes": + typeName = "[]byte" + } + + g.P("// ", funcName, " stores v in a new ", m.GoIdent, " and returns a pointer to it.") + g.P("func ", funcName, "(v ", typeName, ") *", m.GoIdent, " {") + g.P(" return &", m.GoIdent, "{Value: v}") + g.P("}") + g.P() + } +} diff --git a/vendor/google.golang.org/protobuf/compiler/protogen/protogen.go b/vendor/google.golang.org/protobuf/compiler/protogen/protogen.go new file mode 100644 index 00000000000..3892d0583eb --- /dev/null +++ b/vendor/google.golang.org/protobuf/compiler/protogen/protogen.go @@ -0,0 +1,1419 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package protogen provides support for writing protoc plugins. +// +// Plugins for protoc, the Protocol Buffer compiler, +// are programs which read a CodeGeneratorRequest message from standard input +// and write a CodeGeneratorResponse message to standard output. +// This package provides support for writing plugins which generate Go code. +package protogen + +import ( + "bufio" + "bytes" + "encoding/binary" + "fmt" + "go/ast" + "go/parser" + "go/printer" + "go/token" + "go/types" + "io/ioutil" + "log" + "os" + "path" + "path/filepath" + "sort" + "strconv" + "strings" + + "google.golang.org/protobuf/encoding/prototext" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + + "google.golang.org/protobuf/types/descriptorpb" + "google.golang.org/protobuf/types/pluginpb" +) + +const goPackageDocURL = "https://developers.google.com/protocol-buffers/docs/reference/go-generated#package" + +// Run executes a function as a protoc plugin. +// +// It reads a CodeGeneratorRequest message from os.Stdin, invokes the plugin +// function, and writes a CodeGeneratorResponse message to os.Stdout. +// +// If a failure occurs while reading or writing, Run prints an error to +// os.Stderr and calls os.Exit(1). +func (opts Options) Run(f func(*Plugin) error) { + if err := run(opts, f); err != nil { + fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Base(os.Args[0]), err) + os.Exit(1) + } +} + +func run(opts Options, f func(*Plugin) error) error { + if len(os.Args) > 1 { + return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1]) + } + in, err := ioutil.ReadAll(os.Stdin) + if err != nil { + return err + } + req := &pluginpb.CodeGeneratorRequest{} + if err := proto.Unmarshal(in, req); err != nil { + return err + } + gen, err := opts.New(req) + if err != nil { + return err + } + if err := f(gen); err != nil { + // Errors from the plugin function are reported by setting the + // error field in the CodeGeneratorResponse. + // + // In contrast, errors that indicate a problem in protoc + // itself (unparsable input, I/O errors, etc.) are reported + // to stderr. + gen.Error(err) + } + resp := gen.Response() + out, err := proto.Marshal(resp) + if err != nil { + return err + } + if _, err := os.Stdout.Write(out); err != nil { + return err + } + return nil +} + +// A Plugin is a protoc plugin invocation. +type Plugin struct { + // Request is the CodeGeneratorRequest provided by protoc. + Request *pluginpb.CodeGeneratorRequest + + // Files is the set of files to generate and everything they import. + // Files appear in topological order, so each file appears before any + // file that imports it. + Files []*File + FilesByPath map[string]*File + + // SupportedFeatures is the set of protobuf language features supported by + // this generator plugin. See the documentation for + // google.protobuf.CodeGeneratorResponse.supported_features for details. + SupportedFeatures uint64 + + fileReg *protoregistry.Files + enumsByName map[protoreflect.FullName]*Enum + messagesByName map[protoreflect.FullName]*Message + annotateCode bool + pathType pathType + module string + genFiles []*GeneratedFile + opts Options + err error +} + +type Options struct { + // If ParamFunc is non-nil, it will be called with each unknown + // generator parameter. + // + // Plugins for protoc can accept parameters from the command line, + // passed in the --_out protoc, separated from the output + // directory with a colon; e.g., + // + // --go_out==,=: + // + // Parameters passed in this fashion as a comma-separated list of + // key=value pairs will be passed to the ParamFunc. + // + // The (flag.FlagSet).Set method matches this function signature, + // so parameters can be converted into flags as in the following: + // + // var flags flag.FlagSet + // value := flags.Bool("param", false, "") + // opts := &protogen.Options{ + // ParamFunc: flags.Set, + // } + // protogen.Run(opts, func(p *protogen.Plugin) error { + // if *value { ... } + // }) + ParamFunc func(name, value string) error + + // ImportRewriteFunc is called with the import path of each package + // imported by a generated file. It returns the import path to use + // for this package. + ImportRewriteFunc func(GoImportPath) GoImportPath +} + +// New returns a new Plugin. +func (opts Options) New(req *pluginpb.CodeGeneratorRequest) (*Plugin, error) { + gen := &Plugin{ + Request: req, + FilesByPath: make(map[string]*File), + fileReg: new(protoregistry.Files), + enumsByName: make(map[protoreflect.FullName]*Enum), + messagesByName: make(map[protoreflect.FullName]*Message), + opts: opts, + } + + packageNames := make(map[string]GoPackageName) // filename -> package name + importPaths := make(map[string]GoImportPath) // filename -> import path + mfiles := make(map[string]bool) // filename set + var packageImportPath GoImportPath + for _, param := range strings.Split(req.GetParameter(), ",") { + var value string + if i := strings.Index(param, "="); i >= 0 { + value = param[i+1:] + param = param[0:i] + } + switch param { + case "": + // Ignore. + case "import_path": + packageImportPath = GoImportPath(value) + case "module": + gen.module = value + case "paths": + switch value { + case "import": + gen.pathType = pathTypeImport + case "source_relative": + gen.pathType = pathTypeSourceRelative + default: + return nil, fmt.Errorf(`unknown path type %q: want "import" or "source_relative"`, value) + } + case "annotate_code": + switch value { + case "true", "": + gen.annotateCode = true + case "false": + default: + return nil, fmt.Errorf(`bad value for parameter %q: want "true" or "false"`, param) + } + default: + if param[0] == 'M' { + if i := strings.Index(value, ";"); i >= 0 { + pkgName := GoPackageName(value[i+1:]) + if otherName, ok := packageNames[param[1:]]; ok && pkgName != otherName { + return nil, fmt.Errorf("inconsistent package names for %q: %q != %q", value[:i], pkgName, otherName) + } + packageNames[param[1:]] = pkgName + value = value[:i] + } + importPaths[param[1:]] = GoImportPath(value) + mfiles[param[1:]] = true + continue + } + if opts.ParamFunc != nil { + if err := opts.ParamFunc(param, value); err != nil { + return nil, err + } + } + } + } + if gen.module != "" { + // When the module= option is provided, we strip the module name + // prefix from generated files. This only makes sense if generated + // filenames are based on the import path, so default to paths=import + // and complain if source_relative was selected manually. + switch gen.pathType { + case pathTypeLegacy: + gen.pathType = pathTypeImport + case pathTypeSourceRelative: + return nil, fmt.Errorf("cannot use module= with paths=source_relative") + } + } + + // Figure out the import path and package name for each file. + // + // The rules here are complicated and have grown organically over time. + // Interactions between different ways of specifying package information + // may be surprising. + // + // The recommended approach is to include a go_package option in every + // .proto source file specifying the full import path of the Go package + // associated with this file. + // + // option go_package = "google.golang.org/protobuf/types/known/anypb"; + // + // Build systems which want to exert full control over import paths may + // specify M= flags. + // + // Other approaches are not recommend. + generatedFileNames := make(map[string]bool) + for _, name := range gen.Request.FileToGenerate { + generatedFileNames[name] = true + } + // We need to determine the import paths before the package names, + // because the Go package name for a file is sometimes derived from + // different file in the same package. + packageNameForImportPath := make(map[GoImportPath]GoPackageName) + for _, fdesc := range gen.Request.ProtoFile { + filename := fdesc.GetName() + packageName, importPath := goPackageOption(fdesc) + switch { + case importPaths[filename] != "": + // Command line: Mfoo.proto=quux/bar + // + // Explicit mapping of source file to import path. + case generatedFileNames[filename] && packageImportPath != "": + // Command line: import_path=quux/bar + // + // The import_path flag sets the import path for every file that + // we generate code for. + importPaths[filename] = packageImportPath + case importPath != "": + // Source file: option go_package = "quux/bar"; + // + // The go_package option sets the import path. Most users should use this. + importPaths[filename] = importPath + default: + // Source filename. + // + // Last resort when nothing else is available. + importPaths[filename] = GoImportPath(path.Dir(filename)) + } + if packageName != "" { + packageNameForImportPath[importPaths[filename]] = packageName + } + } + for _, fdesc := range gen.Request.ProtoFile { + filename := fdesc.GetName() + packageName, importPath := goPackageOption(fdesc) + defaultPackageName := packageNameForImportPath[importPaths[filename]] + switch { + case packageNames[filename] != "": + // A package name specified by the "M" command-line argument. + case packageName != "": + // TODO: For the "M" command-line argument, this means that the + // package name can be derived from the go_package option. + // Go package information should either consistently come from the + // command-line or the .proto source file, but not both. + // See how to make this consistent. + + // Source file: option go_package = "quux/bar"; + packageNames[filename] = packageName + case defaultPackageName != "": + // A go_package option in another file in the same package. + // + // This is a poor choice in general, since every source file should + // contain a go_package option. Supported mainly for historical + // compatibility. + packageNames[filename] = defaultPackageName + case generatedFileNames[filename] && packageImportPath != "": + // Command line: import_path=quux/bar + packageNames[filename] = cleanPackageName(path.Base(string(packageImportPath))) + case fdesc.GetPackage() != "": + // Source file: package quux.bar; + packageNames[filename] = cleanPackageName(fdesc.GetPackage()) + default: + // Source filename. + packageNames[filename] = cleanPackageName(baseName(filename)) + } + + goPkgOpt := string(importPaths[filename]) + if path.Base(string(goPkgOpt)) != string(packageNames[filename]) { + goPkgOpt += ";" + string(packageNames[filename]) + } + switch { + case packageImportPath != "": + // Command line: import_path=quux/bar + warn("Deprecated use of the 'import_path' command-line argument. In %q, please specify:\n"+ + "\toption go_package = %q;\n"+ + "A future release of protoc-gen-go will no longer support the 'import_path' argument.\n"+ + "See "+goPackageDocURL+" for more information.\n"+ + "\n", fdesc.GetName(), goPkgOpt) + case mfiles[filename]: + // Command line: M=foo.proto=quux/bar + case packageName != "" && importPath == "": + // Source file: option go_package = "quux"; + warn("Deprecated use of 'go_package' option without a full import path in %q, please specify:\n"+ + "\toption go_package = %q;\n"+ + "A future release of protoc-gen-go will require the import path be specified.\n"+ + "See "+goPackageDocURL+" for more information.\n"+ + "\n", fdesc.GetName(), goPkgOpt) + case packageName == "" && importPath == "": + // No Go package information provided. + dotIdx := strings.Index(goPkgOpt, ".") // heuristic for top-level domain + slashIdx := strings.Index(goPkgOpt, "/") // heuristic for multi-segment path + if isFull := 0 <= dotIdx && dotIdx <= slashIdx; isFull { + warn("Missing 'go_package' option in %q, please specify:\n"+ + "\toption go_package = %q;\n"+ + "A future release of protoc-gen-go will require this be specified.\n"+ + "See "+goPackageDocURL+" for more information.\n"+ + "\n", fdesc.GetName(), goPkgOpt) + } else { + warn("Missing 'go_package' option in %q,\n"+ + "please specify it with the full Go package path as\n"+ + "a future release of protoc-gen-go will require this be specified.\n"+ + "See "+goPackageDocURL+" for more information.\n"+ + "\n", fdesc.GetName()) + } + } + } + + // Consistency check: Every file with the same Go import path should have + // the same Go package name. + packageFiles := make(map[GoImportPath][]string) + for filename, importPath := range importPaths { + if _, ok := packageNames[filename]; !ok { + // Skip files mentioned in a M= parameter + // but which do not appear in the CodeGeneratorRequest. + continue + } + packageFiles[importPath] = append(packageFiles[importPath], filename) + } + for importPath, filenames := range packageFiles { + for i := 1; i < len(filenames); i++ { + if a, b := packageNames[filenames[0]], packageNames[filenames[i]]; a != b { + return nil, fmt.Errorf("Go package %v has inconsistent names %v (%v) and %v (%v)", + importPath, a, filenames[0], b, filenames[i]) + } + } + } + + for _, fdesc := range gen.Request.ProtoFile { + filename := fdesc.GetName() + if gen.FilesByPath[filename] != nil { + return nil, fmt.Errorf("duplicate file name: %q", filename) + } + f, err := newFile(gen, fdesc, packageNames[filename], importPaths[filename]) + if err != nil { + return nil, err + } + gen.Files = append(gen.Files, f) + gen.FilesByPath[filename] = f + } + for _, filename := range gen.Request.FileToGenerate { + f, ok := gen.FilesByPath[filename] + if !ok { + return nil, fmt.Errorf("no descriptor for generated file: %v", filename) + } + f.Generate = true + } + return gen, nil +} + +// Error records an error in code generation. The generator will report the +// error back to protoc and will not produce output. +func (gen *Plugin) Error(err error) { + if gen.err == nil { + gen.err = err + } +} + +// Response returns the generator output. +func (gen *Plugin) Response() *pluginpb.CodeGeneratorResponse { + resp := &pluginpb.CodeGeneratorResponse{} + if gen.err != nil { + resp.Error = proto.String(gen.err.Error()) + return resp + } + for _, g := range gen.genFiles { + if g.skip { + continue + } + content, err := g.Content() + if err != nil { + return &pluginpb.CodeGeneratorResponse{ + Error: proto.String(err.Error()), + } + } + filename := g.filename + if gen.module != "" { + trim := gen.module + "/" + if !strings.HasPrefix(filename, trim) { + return &pluginpb.CodeGeneratorResponse{ + Error: proto.String(fmt.Sprintf("%v: generated file does not match prefix %q", filename, gen.module)), + } + } + filename = strings.TrimPrefix(filename, trim) + } + resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{ + Name: proto.String(filename), + Content: proto.String(string(content)), + }) + if gen.annotateCode && strings.HasSuffix(g.filename, ".go") { + meta, err := g.metaFile(content) + if err != nil { + return &pluginpb.CodeGeneratorResponse{ + Error: proto.String(err.Error()), + } + } + resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{ + Name: proto.String(filename + ".meta"), + Content: proto.String(meta), + }) + } + } + if gen.SupportedFeatures > 0 { + resp.SupportedFeatures = proto.Uint64(gen.SupportedFeatures) + } + return resp +} + +// A File describes a .proto source file. +type File struct { + Desc protoreflect.FileDescriptor + Proto *descriptorpb.FileDescriptorProto + + GoDescriptorIdent GoIdent // name of Go variable for the file descriptor + GoPackageName GoPackageName // name of this file's Go package + GoImportPath GoImportPath // import path of this file's Go package + + Enums []*Enum // top-level enum declarations + Messages []*Message // top-level message declarations + Extensions []*Extension // top-level extension declarations + Services []*Service // top-level service declarations + + Generate bool // true if we should generate code for this file + + // GeneratedFilenamePrefix is used to construct filenames for generated + // files associated with this source file. + // + // For example, the source file "dir/foo.proto" might have a filename prefix + // of "dir/foo". Appending ".pb.go" produces an output file of "dir/foo.pb.go". + GeneratedFilenamePrefix string + + comments map[pathKey]CommentSet +} + +func newFile(gen *Plugin, p *descriptorpb.FileDescriptorProto, packageName GoPackageName, importPath GoImportPath) (*File, error) { + desc, err := protodesc.NewFile(p, gen.fileReg) + if err != nil { + return nil, fmt.Errorf("invalid FileDescriptorProto %q: %v", p.GetName(), err) + } + if err := gen.fileReg.RegisterFile(desc); err != nil { + return nil, fmt.Errorf("cannot register descriptor %q: %v", p.GetName(), err) + } + f := &File{ + Desc: desc, + Proto: p, + GoPackageName: packageName, + GoImportPath: importPath, + comments: make(map[pathKey]CommentSet), + } + + // Determine the prefix for generated Go files. + prefix := p.GetName() + if ext := path.Ext(prefix); ext == ".proto" || ext == ".protodevel" { + prefix = prefix[:len(prefix)-len(ext)] + } + switch gen.pathType { + case pathTypeLegacy: + // The default is to derive the output filename from the Go import path + // if the file contains a go_package option,or from the input filename instead. + if _, importPath := goPackageOption(p); importPath != "" { + prefix = path.Join(string(importPath), path.Base(prefix)) + } + case pathTypeImport: + // If paths=import, the output filename is derived from the Go import path. + prefix = path.Join(string(f.GoImportPath), path.Base(prefix)) + case pathTypeSourceRelative: + // If paths=source_relative, the output filename is derived from + // the input filename. + } + f.GoDescriptorIdent = GoIdent{ + GoName: "File_" + strs.GoSanitized(p.GetName()), + GoImportPath: f.GoImportPath, + } + f.GeneratedFilenamePrefix = prefix + + for _, loc := range p.GetSourceCodeInfo().GetLocation() { + // Descriptors declarations are guaranteed to have unique comment sets. + // Other locations may not be unique, but we don't use them. + var leadingDetached []Comments + for _, s := range loc.GetLeadingDetachedComments() { + leadingDetached = append(leadingDetached, Comments(s)) + } + f.comments[newPathKey(loc.Path)] = CommentSet{ + LeadingDetached: leadingDetached, + Leading: Comments(loc.GetLeadingComments()), + Trailing: Comments(loc.GetTrailingComments()), + } + } + for i, eds := 0, desc.Enums(); i < eds.Len(); i++ { + f.Enums = append(f.Enums, newEnum(gen, f, nil, eds.Get(i))) + } + for i, mds := 0, desc.Messages(); i < mds.Len(); i++ { + f.Messages = append(f.Messages, newMessage(gen, f, nil, mds.Get(i))) + } + for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ { + f.Extensions = append(f.Extensions, newField(gen, f, nil, xds.Get(i))) + } + for i, sds := 0, desc.Services(); i < sds.Len(); i++ { + f.Services = append(f.Services, newService(gen, f, sds.Get(i))) + } + for _, message := range f.Messages { + if err := message.resolveDependencies(gen); err != nil { + return nil, err + } + } + for _, extension := range f.Extensions { + if err := extension.resolveDependencies(gen); err != nil { + return nil, err + } + } + for _, service := range f.Services { + for _, method := range service.Methods { + if err := method.resolveDependencies(gen); err != nil { + return nil, err + } + } + } + return f, nil +} + +func (f *File) location(idxPath ...int32) Location { + return Location{ + SourceFile: f.Desc.Path(), + Path: idxPath, + } +} + +// goPackageOption interprets a file's go_package option. +// If there is no go_package, it returns ("", ""). +// If there's a simple name, it returns (pkg, ""). +// If the option implies an import path, it returns (pkg, impPath). +func goPackageOption(d *descriptorpb.FileDescriptorProto) (pkg GoPackageName, impPath GoImportPath) { + opt := d.GetOptions().GetGoPackage() + if opt == "" { + return "", "" + } + rawPkg, impPath := goPackageOptionRaw(opt) + pkg = cleanPackageName(rawPkg) + if string(pkg) != rawPkg && impPath != "" { + warn("Malformed 'go_package' option in %q, please specify:\n"+ + "\toption go_package = %q;\n"+ + "A future release of protoc-gen-go will reject this.\n"+ + "See "+goPackageDocURL+" for more information.\n"+ + "\n", d.GetName(), string(impPath)+";"+string(pkg)) + } + return pkg, impPath +} +func goPackageOptionRaw(opt string) (rawPkg string, impPath GoImportPath) { + // A semicolon-delimited suffix delimits the import path and package name. + if i := strings.Index(opt, ";"); i >= 0 { + return opt[i+1:], GoImportPath(opt[:i]) + } + // The presence of a slash implies there's an import path. + if i := strings.LastIndex(opt, "/"); i >= 0 { + return opt[i+1:], GoImportPath(opt) + } + return opt, "" +} + +// An Enum describes an enum. +type Enum struct { + Desc protoreflect.EnumDescriptor + + GoIdent GoIdent // name of the generated Go type + + Values []*EnumValue // enum value declarations + + Location Location // location of this enum + Comments CommentSet // comments associated with this enum +} + +func newEnum(gen *Plugin, f *File, parent *Message, desc protoreflect.EnumDescriptor) *Enum { + var loc Location + if parent != nil { + loc = parent.Location.appendPath(int32(genid.DescriptorProto_EnumType_field_number), int32(desc.Index())) + } else { + loc = f.location(int32(genid.FileDescriptorProto_EnumType_field_number), int32(desc.Index())) + } + enum := &Enum{ + Desc: desc, + GoIdent: newGoIdent(f, desc), + Location: loc, + Comments: f.comments[newPathKey(loc.Path)], + } + gen.enumsByName[desc.FullName()] = enum + for i, vds := 0, enum.Desc.Values(); i < vds.Len(); i++ { + enum.Values = append(enum.Values, newEnumValue(gen, f, parent, enum, vds.Get(i))) + } + return enum +} + +// An EnumValue describes an enum value. +type EnumValue struct { + Desc protoreflect.EnumValueDescriptor + + GoIdent GoIdent // name of the generated Go declaration + + Parent *Enum // enum in which this value is declared + + Location Location // location of this enum value + Comments CommentSet // comments associated with this enum value +} + +func newEnumValue(gen *Plugin, f *File, message *Message, enum *Enum, desc protoreflect.EnumValueDescriptor) *EnumValue { + // A top-level enum value's name is: EnumName_ValueName + // An enum value contained in a message is: MessageName_ValueName + // + // For historical reasons, enum value names are not camel-cased. + parentIdent := enum.GoIdent + if message != nil { + parentIdent = message.GoIdent + } + name := parentIdent.GoName + "_" + string(desc.Name()) + loc := enum.Location.appendPath(int32(genid.EnumDescriptorProto_Value_field_number), int32(desc.Index())) + return &EnumValue{ + Desc: desc, + GoIdent: f.GoImportPath.Ident(name), + Parent: enum, + Location: loc, + Comments: f.comments[newPathKey(loc.Path)], + } +} + +// A Message describes a message. +type Message struct { + Desc protoreflect.MessageDescriptor + + GoIdent GoIdent // name of the generated Go type + + Fields []*Field // message field declarations + Oneofs []*Oneof // message oneof declarations + + Enums []*Enum // nested enum declarations + Messages []*Message // nested message declarations + Extensions []*Extension // nested extension declarations + + Location Location // location of this message + Comments CommentSet // comments associated with this message +} + +func newMessage(gen *Plugin, f *File, parent *Message, desc protoreflect.MessageDescriptor) *Message { + var loc Location + if parent != nil { + loc = parent.Location.appendPath(int32(genid.DescriptorProto_NestedType_field_number), int32(desc.Index())) + } else { + loc = f.location(int32(genid.FileDescriptorProto_MessageType_field_number), int32(desc.Index())) + } + message := &Message{ + Desc: desc, + GoIdent: newGoIdent(f, desc), + Location: loc, + Comments: f.comments[newPathKey(loc.Path)], + } + gen.messagesByName[desc.FullName()] = message + for i, eds := 0, desc.Enums(); i < eds.Len(); i++ { + message.Enums = append(message.Enums, newEnum(gen, f, message, eds.Get(i))) + } + for i, mds := 0, desc.Messages(); i < mds.Len(); i++ { + message.Messages = append(message.Messages, newMessage(gen, f, message, mds.Get(i))) + } + for i, fds := 0, desc.Fields(); i < fds.Len(); i++ { + message.Fields = append(message.Fields, newField(gen, f, message, fds.Get(i))) + } + for i, ods := 0, desc.Oneofs(); i < ods.Len(); i++ { + message.Oneofs = append(message.Oneofs, newOneof(gen, f, message, ods.Get(i))) + } + for i, xds := 0, desc.Extensions(); i < xds.Len(); i++ { + message.Extensions = append(message.Extensions, newField(gen, f, message, xds.Get(i))) + } + + // Resolve local references between fields and oneofs. + for _, field := range message.Fields { + if od := field.Desc.ContainingOneof(); od != nil { + oneof := message.Oneofs[od.Index()] + field.Oneof = oneof + oneof.Fields = append(oneof.Fields, field) + } + } + + // Field name conflict resolution. + // + // We assume well-known method names that may be attached to a generated + // message type, as well as a 'Get*' method for each field. For each + // field in turn, we add _s to its name until there are no conflicts. + // + // Any change to the following set of method names is a potential + // incompatible API change because it may change generated field names. + // + // TODO: If we ever support a 'go_name' option to set the Go name of a + // field, we should consider dropping this entirely. The conflict + // resolution algorithm is subtle and surprising (changing the order + // in which fields appear in the .proto source file can change the + // names of fields in generated code), and does not adapt well to + // adding new per-field methods such as setters. + usedNames := map[string]bool{ + "Reset": true, + "String": true, + "ProtoMessage": true, + "Marshal": true, + "Unmarshal": true, + "ExtensionRangeArray": true, + "ExtensionMap": true, + "Descriptor": true, + } + makeNameUnique := func(name string, hasGetter bool) string { + for usedNames[name] || (hasGetter && usedNames["Get"+name]) { + name += "_" + } + usedNames[name] = true + usedNames["Get"+name] = hasGetter + return name + } + for _, field := range message.Fields { + field.GoName = makeNameUnique(field.GoName, true) + field.GoIdent.GoName = message.GoIdent.GoName + "_" + field.GoName + if field.Oneof != nil && field.Oneof.Fields[0] == field { + // Make the name for a oneof unique as well. For historical reasons, + // this assumes that a getter method is not generated for oneofs. + // This is incorrect, but fixing it breaks existing code. + field.Oneof.GoName = makeNameUnique(field.Oneof.GoName, false) + field.Oneof.GoIdent.GoName = message.GoIdent.GoName + "_" + field.Oneof.GoName + } + } + + // Oneof field name conflict resolution. + // + // This conflict resolution is incomplete as it does not consider collisions + // with other oneof field types, but fixing it breaks existing code. + for _, field := range message.Fields { + if field.Oneof != nil { + Loop: + for { + for _, nestedMessage := range message.Messages { + if nestedMessage.GoIdent == field.GoIdent { + field.GoIdent.GoName += "_" + continue Loop + } + } + for _, nestedEnum := range message.Enums { + if nestedEnum.GoIdent == field.GoIdent { + field.GoIdent.GoName += "_" + continue Loop + } + } + break Loop + } + } + } + + return message +} + +func (message *Message) resolveDependencies(gen *Plugin) error { + for _, field := range message.Fields { + if err := field.resolveDependencies(gen); err != nil { + return err + } + } + for _, message := range message.Messages { + if err := message.resolveDependencies(gen); err != nil { + return err + } + } + for _, extension := range message.Extensions { + if err := extension.resolveDependencies(gen); err != nil { + return err + } + } + return nil +} + +// A Field describes a message field. +type Field struct { + Desc protoreflect.FieldDescriptor + + // GoName is the base name of this field's Go field and methods. + // For code generated by protoc-gen-go, this means a field named + // '{{GoName}}' and a getter method named 'Get{{GoName}}'. + GoName string // e.g., "FieldName" + + // GoIdent is the base name of a top-level declaration for this field. + // For code generated by protoc-gen-go, this means a wrapper type named + // '{{GoIdent}}' for members fields of a oneof, and a variable named + // 'E_{{GoIdent}}' for extension fields. + GoIdent GoIdent // e.g., "MessageName_FieldName" + + Parent *Message // message in which this field is declared; nil if top-level extension + Oneof *Oneof // containing oneof; nil if not part of a oneof + Extendee *Message // extended message for extension fields; nil otherwise + + Enum *Enum // type for enum fields; nil otherwise + Message *Message // type for message or group fields; nil otherwise + + Location Location // location of this field + Comments CommentSet // comments associated with this field +} + +func newField(gen *Plugin, f *File, message *Message, desc protoreflect.FieldDescriptor) *Field { + var loc Location + switch { + case desc.IsExtension() && message == nil: + loc = f.location(int32(genid.FileDescriptorProto_Extension_field_number), int32(desc.Index())) + case desc.IsExtension() && message != nil: + loc = message.Location.appendPath(int32(genid.DescriptorProto_Extension_field_number), int32(desc.Index())) + default: + loc = message.Location.appendPath(int32(genid.DescriptorProto_Field_field_number), int32(desc.Index())) + } + camelCased := strs.GoCamelCase(string(desc.Name())) + var parentPrefix string + if message != nil { + parentPrefix = message.GoIdent.GoName + "_" + } + field := &Field{ + Desc: desc, + GoName: camelCased, + GoIdent: GoIdent{ + GoImportPath: f.GoImportPath, + GoName: parentPrefix + camelCased, + }, + Parent: message, + Location: loc, + Comments: f.comments[newPathKey(loc.Path)], + } + return field +} + +func (field *Field) resolveDependencies(gen *Plugin) error { + desc := field.Desc + switch desc.Kind() { + case protoreflect.EnumKind: + name := field.Desc.Enum().FullName() + enum, ok := gen.enumsByName[name] + if !ok { + return fmt.Errorf("field %v: no descriptor for enum %v", desc.FullName(), name) + } + field.Enum = enum + case protoreflect.MessageKind, protoreflect.GroupKind: + name := desc.Message().FullName() + message, ok := gen.messagesByName[name] + if !ok { + return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name) + } + field.Message = message + } + if desc.IsExtension() { + name := desc.ContainingMessage().FullName() + message, ok := gen.messagesByName[name] + if !ok { + return fmt.Errorf("field %v: no descriptor for type %v", desc.FullName(), name) + } + field.Extendee = message + } + return nil +} + +// A Oneof describes a message oneof. +type Oneof struct { + Desc protoreflect.OneofDescriptor + + // GoName is the base name of this oneof's Go field and methods. + // For code generated by protoc-gen-go, this means a field named + // '{{GoName}}' and a getter method named 'Get{{GoName}}'. + GoName string // e.g., "OneofName" + + // GoIdent is the base name of a top-level declaration for this oneof. + GoIdent GoIdent // e.g., "MessageName_OneofName" + + Parent *Message // message in which this oneof is declared + + Fields []*Field // fields that are part of this oneof + + Location Location // location of this oneof + Comments CommentSet // comments associated with this oneof +} + +func newOneof(gen *Plugin, f *File, message *Message, desc protoreflect.OneofDescriptor) *Oneof { + loc := message.Location.appendPath(int32(genid.DescriptorProto_OneofDecl_field_number), int32(desc.Index())) + camelCased := strs.GoCamelCase(string(desc.Name())) + parentPrefix := message.GoIdent.GoName + "_" + return &Oneof{ + Desc: desc, + Parent: message, + GoName: camelCased, + GoIdent: GoIdent{ + GoImportPath: f.GoImportPath, + GoName: parentPrefix + camelCased, + }, + Location: loc, + Comments: f.comments[newPathKey(loc.Path)], + } +} + +// Extension is an alias of Field for documentation. +type Extension = Field + +// A Service describes a service. +type Service struct { + Desc protoreflect.ServiceDescriptor + + GoName string + + Methods []*Method // service method declarations + + Location Location // location of this service + Comments CommentSet // comments associated with this service +} + +func newService(gen *Plugin, f *File, desc protoreflect.ServiceDescriptor) *Service { + loc := f.location(int32(genid.FileDescriptorProto_Service_field_number), int32(desc.Index())) + service := &Service{ + Desc: desc, + GoName: strs.GoCamelCase(string(desc.Name())), + Location: loc, + Comments: f.comments[newPathKey(loc.Path)], + } + for i, mds := 0, desc.Methods(); i < mds.Len(); i++ { + service.Methods = append(service.Methods, newMethod(gen, f, service, mds.Get(i))) + } + return service +} + +// A Method describes a method in a service. +type Method struct { + Desc protoreflect.MethodDescriptor + + GoName string + + Parent *Service // service in which this method is declared + + Input *Message + Output *Message + + Location Location // location of this method + Comments CommentSet // comments associated with this method +} + +func newMethod(gen *Plugin, f *File, service *Service, desc protoreflect.MethodDescriptor) *Method { + loc := service.Location.appendPath(int32(genid.ServiceDescriptorProto_Method_field_number), int32(desc.Index())) + method := &Method{ + Desc: desc, + GoName: strs.GoCamelCase(string(desc.Name())), + Parent: service, + Location: loc, + Comments: f.comments[newPathKey(loc.Path)], + } + return method +} + +func (method *Method) resolveDependencies(gen *Plugin) error { + desc := method.Desc + + inName := desc.Input().FullName() + in, ok := gen.messagesByName[inName] + if !ok { + return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), inName) + } + method.Input = in + + outName := desc.Output().FullName() + out, ok := gen.messagesByName[outName] + if !ok { + return fmt.Errorf("method %v: no descriptor for type %v", desc.FullName(), outName) + } + method.Output = out + + return nil +} + +// A GeneratedFile is a generated file. +type GeneratedFile struct { + gen *Plugin + skip bool + filename string + goImportPath GoImportPath + buf bytes.Buffer + packageNames map[GoImportPath]GoPackageName + usedPackageNames map[GoPackageName]bool + manualImports map[GoImportPath]bool + annotations map[string][]Location +} + +// NewGeneratedFile creates a new generated file with the given filename +// and import path. +func (gen *Plugin) NewGeneratedFile(filename string, goImportPath GoImportPath) *GeneratedFile { + g := &GeneratedFile{ + gen: gen, + filename: filename, + goImportPath: goImportPath, + packageNames: make(map[GoImportPath]GoPackageName), + usedPackageNames: make(map[GoPackageName]bool), + manualImports: make(map[GoImportPath]bool), + annotations: make(map[string][]Location), + } + + // All predeclared identifiers in Go are already used. + for _, s := range types.Universe.Names() { + g.usedPackageNames[GoPackageName(s)] = true + } + + gen.genFiles = append(gen.genFiles, g) + return g +} + +// P prints a line to the generated output. It converts each parameter to a +// string following the same rules as fmt.Print. It never inserts spaces +// between parameters. +func (g *GeneratedFile) P(v ...interface{}) { + for _, x := range v { + switch x := x.(type) { + case GoIdent: + fmt.Fprint(&g.buf, g.QualifiedGoIdent(x)) + default: + fmt.Fprint(&g.buf, x) + } + } + fmt.Fprintln(&g.buf) +} + +// QualifiedGoIdent returns the string to use for a Go identifier. +// +// If the identifier is from a different Go package than the generated file, +// the returned name will be qualified (package.name) and an import statement +// for the identifier's package will be included in the file. +func (g *GeneratedFile) QualifiedGoIdent(ident GoIdent) string { + if ident.GoImportPath == g.goImportPath { + return ident.GoName + } + if packageName, ok := g.packageNames[ident.GoImportPath]; ok { + return string(packageName) + "." + ident.GoName + } + packageName := cleanPackageName(baseName(string(ident.GoImportPath))) + for i, orig := 1, packageName; g.usedPackageNames[packageName]; i++ { + packageName = orig + GoPackageName(strconv.Itoa(i)) + } + g.packageNames[ident.GoImportPath] = packageName + g.usedPackageNames[packageName] = true + return string(packageName) + "." + ident.GoName +} + +// Import ensures a package is imported by the generated file. +// +// Packages referenced by QualifiedGoIdent are automatically imported. +// Explicitly importing a package with Import is generally only necessary +// when the import will be blank (import _ "package"). +func (g *GeneratedFile) Import(importPath GoImportPath) { + g.manualImports[importPath] = true +} + +// Write implements io.Writer. +func (g *GeneratedFile) Write(p []byte) (n int, err error) { + return g.buf.Write(p) +} + +// Skip removes the generated file from the plugin output. +func (g *GeneratedFile) Skip() { + g.skip = true +} + +// Unskip reverts a previous call to Skip, re-including the generated file in +// the plugin output. +func (g *GeneratedFile) Unskip() { + g.skip = false +} + +// Annotate associates a symbol in a generated Go file with a location in a +// source .proto file. +// +// The symbol may refer to a type, constant, variable, function, method, or +// struct field. The "T.sel" syntax is used to identify the method or field +// 'sel' on type 'T'. +func (g *GeneratedFile) Annotate(symbol string, loc Location) { + g.annotations[symbol] = append(g.annotations[symbol], loc) +} + +// Content returns the contents of the generated file. +func (g *GeneratedFile) Content() ([]byte, error) { + if !strings.HasSuffix(g.filename, ".go") { + return g.buf.Bytes(), nil + } + + // Reformat generated code. + original := g.buf.Bytes() + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, "", original, parser.ParseComments) + if err != nil { + // Print out the bad code with line numbers. + // This should never happen in practice, but it can while changing generated code + // so consider this a debugging aid. + var src bytes.Buffer + s := bufio.NewScanner(bytes.NewReader(original)) + for line := 1; s.Scan(); line++ { + fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes()) + } + return nil, fmt.Errorf("%v: unparsable Go source: %v\n%v", g.filename, err, src.String()) + } + + // Collect a sorted list of all imports. + var importPaths [][2]string + rewriteImport := func(importPath string) string { + if f := g.gen.opts.ImportRewriteFunc; f != nil { + return string(f(GoImportPath(importPath))) + } + return importPath + } + for importPath := range g.packageNames { + pkgName := string(g.packageNames[GoImportPath(importPath)]) + pkgPath := rewriteImport(string(importPath)) + importPaths = append(importPaths, [2]string{pkgName, pkgPath}) + } + for importPath := range g.manualImports { + if _, ok := g.packageNames[importPath]; !ok { + pkgPath := rewriteImport(string(importPath)) + importPaths = append(importPaths, [2]string{"_", pkgPath}) + } + } + sort.Slice(importPaths, func(i, j int) bool { + return importPaths[i][1] < importPaths[j][1] + }) + + // Modify the AST to include a new import block. + if len(importPaths) > 0 { + // Insert block after package statement or + // possible comment attached to the end of the package statement. + pos := file.Package + tokFile := fset.File(file.Package) + pkgLine := tokFile.Line(file.Package) + for _, c := range file.Comments { + if tokFile.Line(c.Pos()) > pkgLine { + break + } + pos = c.End() + } + + // Construct the import block. + impDecl := &ast.GenDecl{ + Tok: token.IMPORT, + TokPos: pos, + Lparen: pos, + Rparen: pos, + } + for _, importPath := range importPaths { + impDecl.Specs = append(impDecl.Specs, &ast.ImportSpec{ + Name: &ast.Ident{ + Name: importPath[0], + NamePos: pos, + }, + Path: &ast.BasicLit{ + Kind: token.STRING, + Value: strconv.Quote(importPath[1]), + ValuePos: pos, + }, + EndPos: pos, + }) + } + file.Decls = append([]ast.Decl{impDecl}, file.Decls...) + } + + var out bytes.Buffer + if err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(&out, fset, file); err != nil { + return nil, fmt.Errorf("%v: can not reformat Go source: %v", g.filename, err) + } + return out.Bytes(), nil +} + +// metaFile returns the contents of the file's metadata file, which is a +// text formatted string of the google.protobuf.GeneratedCodeInfo. +func (g *GeneratedFile) metaFile(content []byte) (string, error) { + fset := token.NewFileSet() + astFile, err := parser.ParseFile(fset, "", content, 0) + if err != nil { + return "", err + } + info := &descriptorpb.GeneratedCodeInfo{} + + seenAnnotations := make(map[string]bool) + annotate := func(s string, ident *ast.Ident) { + seenAnnotations[s] = true + for _, loc := range g.annotations[s] { + info.Annotation = append(info.Annotation, &descriptorpb.GeneratedCodeInfo_Annotation{ + SourceFile: proto.String(loc.SourceFile), + Path: loc.Path, + Begin: proto.Int32(int32(fset.Position(ident.Pos()).Offset)), + End: proto.Int32(int32(fset.Position(ident.End()).Offset)), + }) + } + } + for _, decl := range astFile.Decls { + switch decl := decl.(type) { + case *ast.GenDecl: + for _, spec := range decl.Specs { + switch spec := spec.(type) { + case *ast.TypeSpec: + annotate(spec.Name.Name, spec.Name) + switch st := spec.Type.(type) { + case *ast.StructType: + for _, field := range st.Fields.List { + for _, name := range field.Names { + annotate(spec.Name.Name+"."+name.Name, name) + } + } + case *ast.InterfaceType: + for _, field := range st.Methods.List { + for _, name := range field.Names { + annotate(spec.Name.Name+"."+name.Name, name) + } + } + } + case *ast.ValueSpec: + for _, name := range spec.Names { + annotate(name.Name, name) + } + } + } + case *ast.FuncDecl: + if decl.Recv == nil { + annotate(decl.Name.Name, decl.Name) + } else { + recv := decl.Recv.List[0].Type + if s, ok := recv.(*ast.StarExpr); ok { + recv = s.X + } + if id, ok := recv.(*ast.Ident); ok { + annotate(id.Name+"."+decl.Name.Name, decl.Name) + } + } + } + } + for a := range g.annotations { + if !seenAnnotations[a] { + return "", fmt.Errorf("%v: no symbol matching annotation %q", g.filename, a) + } + } + + b, err := prototext.Marshal(info) + if err != nil { + return "", err + } + return string(b), nil +} + +// A GoIdent is a Go identifier, consisting of a name and import path. +// The name is a single identifier and may not be a dot-qualified selector. +type GoIdent struct { + GoName string + GoImportPath GoImportPath +} + +func (id GoIdent) String() string { return fmt.Sprintf("%q.%v", id.GoImportPath, id.GoName) } + +// newGoIdent returns the Go identifier for a descriptor. +func newGoIdent(f *File, d protoreflect.Descriptor) GoIdent { + name := strings.TrimPrefix(string(d.FullName()), string(f.Desc.Package())+".") + return GoIdent{ + GoName: strs.GoCamelCase(name), + GoImportPath: f.GoImportPath, + } +} + +// A GoImportPath is the import path of a Go package. +// For example: "google.golang.org/protobuf/compiler/protogen" +type GoImportPath string + +func (p GoImportPath) String() string { return strconv.Quote(string(p)) } + +// Ident returns a GoIdent with s as the GoName and p as the GoImportPath. +func (p GoImportPath) Ident(s string) GoIdent { + return GoIdent{GoName: s, GoImportPath: p} +} + +// A GoPackageName is the name of a Go package. e.g., "protobuf". +type GoPackageName string + +// cleanPackageName converts a string to a valid Go package name. +func cleanPackageName(name string) GoPackageName { + return GoPackageName(strs.GoSanitized(name)) +} + +// baseName returns the last path element of the name, with the last dotted suffix removed. +func baseName(name string) string { + // First, find the last element + if i := strings.LastIndex(name, "/"); i >= 0 { + name = name[i+1:] + } + // Now drop the suffix + if i := strings.LastIndex(name, "."); i >= 0 { + name = name[:i] + } + return name +} + +type pathType int + +const ( + pathTypeLegacy pathType = iota + pathTypeImport + pathTypeSourceRelative +) + +// A Location is a location in a .proto source file. +// +// See the google.protobuf.SourceCodeInfo documentation in descriptor.proto +// for details. +type Location struct { + SourceFile string + Path protoreflect.SourcePath +} + +// appendPath add elements to a Location's path, returning a new Location. +func (loc Location) appendPath(a ...int32) Location { + var n protoreflect.SourcePath + n = append(n, loc.Path...) + n = append(n, a...) + return Location{ + SourceFile: loc.SourceFile, + Path: n, + } +} + +// A pathKey is a representation of a location path suitable for use as a map key. +type pathKey struct { + s string +} + +// newPathKey converts a location path to a pathKey. +func newPathKey(idxPath []int32) pathKey { + buf := make([]byte, 4*len(idxPath)) + for i, x := range idxPath { + binary.LittleEndian.PutUint32(buf[i*4:], uint32(x)) + } + return pathKey{string(buf)} +} + +// CommentSet is a set of leading and trailing comments associated +// with a .proto descriptor declaration. +type CommentSet struct { + LeadingDetached []Comments + Leading Comments + Trailing Comments +} + +// Comments is a comments string as provided by protoc. +type Comments string + +// String formats the comments by inserting // to the start of each line, +// ensuring that there is a trailing newline. +// An empty comment is formatted as an empty string. +func (c Comments) String() string { + if c == "" { + return "" + } + var b []byte + for _, line := range strings.Split(strings.TrimSuffix(string(c), "\n"), "\n") { + b = append(b, "//"...) + b = append(b, line...) + b = append(b, "\n"...) + } + return string(b) +} + +var warnings = true + +func warn(format string, a ...interface{}) { + if warnings { + log.Printf("WARNING: "+format, a...) + } +} diff --git a/vendor/google.golang.org/protobuf/encoding/prototext/decode.go b/vendor/google.golang.org/protobuf/encoding/prototext/decode.go new file mode 100644 index 00000000000..cab95a42735 --- /dev/null +++ b/vendor/google.golang.org/protobuf/encoding/prototext/decode.go @@ -0,0 +1,791 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package prototext + +import ( + "fmt" + "strings" + "unicode/utf8" + + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/encoding/text" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/internal/set" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/proto" + pref "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +// Unmarshal reads the given []byte into the given proto.Message. +func Unmarshal(b []byte, m proto.Message) error { + return UnmarshalOptions{}.Unmarshal(b, m) +} + +// UnmarshalOptions is a configurable textproto format unmarshaler. +type UnmarshalOptions struct { + pragma.NoUnkeyedLiterals + + // AllowPartial accepts input for messages that will result in missing + // required fields. If AllowPartial is false (the default), Unmarshal will + // return error if there are any missing required fields. + AllowPartial bool + + // DiscardUnknown specifies whether to ignore unknown fields when parsing. + // An unknown field is any field whose field name or field number does not + // resolve to any known or extension field in the message. + // By default, unmarshal rejects unknown fields as an error. + DiscardUnknown bool + + // Resolver is used for looking up types when unmarshaling + // google.protobuf.Any messages or extension fields. + // If nil, this defaults to using protoregistry.GlobalTypes. + Resolver interface { + protoregistry.MessageTypeResolver + protoregistry.ExtensionTypeResolver + } +} + +// Unmarshal reads the given []byte and populates the given proto.Message using options in +// UnmarshalOptions object. +func (o UnmarshalOptions) Unmarshal(b []byte, m proto.Message) error { + return o.unmarshal(b, m) +} + +// unmarshal is a centralized function that all unmarshal operations go through. +// For profiling purposes, avoid changing the name of this function or +// introducing other code paths for unmarshal that do not go through this. +func (o UnmarshalOptions) unmarshal(b []byte, m proto.Message) error { + proto.Reset(m) + + if o.Resolver == nil { + o.Resolver = protoregistry.GlobalTypes + } + + dec := decoder{text.NewDecoder(b), o} + if err := dec.unmarshalMessage(m.ProtoReflect(), false); err != nil { + return err + } + if o.AllowPartial { + return nil + } + return proto.CheckInitialized(m) +} + +type decoder struct { + *text.Decoder + opts UnmarshalOptions +} + +// newError returns an error object with position info. +func (d decoder) newError(pos int, f string, x ...interface{}) error { + line, column := d.Position(pos) + head := fmt.Sprintf("(line %d:%d): ", line, column) + return errors.New(head+f, x...) +} + +// unexpectedTokenError returns a syntax error for the given unexpected token. +func (d decoder) unexpectedTokenError(tok text.Token) error { + return d.syntaxError(tok.Pos(), "unexpected token: %s", tok.RawString()) +} + +// syntaxError returns a syntax error for given position. +func (d decoder) syntaxError(pos int, f string, x ...interface{}) error { + line, column := d.Position(pos) + head := fmt.Sprintf("syntax error (line %d:%d): ", line, column) + return errors.New(head+f, x...) +} + +// unmarshalMessage unmarshals into the given protoreflect.Message. +func (d decoder) unmarshalMessage(m pref.Message, checkDelims bool) error { + messageDesc := m.Descriptor() + if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) { + return errors.New("no support for proto1 MessageSets") + } + + if messageDesc.FullName() == genid.Any_message_fullname { + return d.unmarshalAny(m, checkDelims) + } + + if checkDelims { + tok, err := d.Read() + if err != nil { + return err + } + + if tok.Kind() != text.MessageOpen { + return d.unexpectedTokenError(tok) + } + } + + var seenNums set.Ints + var seenOneofs set.Ints + fieldDescs := messageDesc.Fields() + + for { + // Read field name. + tok, err := d.Read() + if err != nil { + return err + } + switch typ := tok.Kind(); typ { + case text.Name: + // Continue below. + case text.EOF: + if checkDelims { + return text.ErrUnexpectedEOF + } + return nil + default: + if checkDelims && typ == text.MessageClose { + return nil + } + return d.unexpectedTokenError(tok) + } + + // Resolve the field descriptor. + var name pref.Name + var fd pref.FieldDescriptor + var xt pref.ExtensionType + var xtErr error + var isFieldNumberName bool + + switch tok.NameKind() { + case text.IdentName: + name = pref.Name(tok.IdentName()) + fd = fieldDescs.ByName(name) + if fd == nil { + // The proto name of a group field is in all lowercase, + // while the textproto field name is the group message name. + gd := fieldDescs.ByName(pref.Name(strings.ToLower(string(name)))) + if gd != nil && gd.Kind() == pref.GroupKind && gd.Message().Name() == name { + fd = gd + } + } else if fd.Kind() == pref.GroupKind && fd.Message().Name() != name { + fd = nil // reset since field name is actually the message name + } + + case text.TypeName: + // Handle extensions only. This code path is not for Any. + xt, xtErr = d.findExtension(pref.FullName(tok.TypeName())) + + case text.FieldNumber: + isFieldNumberName = true + num := pref.FieldNumber(tok.FieldNumber()) + if !num.IsValid() { + return d.newError(tok.Pos(), "invalid field number: %d", num) + } + fd = fieldDescs.ByNumber(num) + if fd == nil { + xt, xtErr = d.opts.Resolver.FindExtensionByNumber(messageDesc.FullName(), num) + } + } + + if xt != nil { + fd = xt.TypeDescriptor() + if !messageDesc.ExtensionRanges().Has(fd.Number()) || fd.ContainingMessage().FullName() != messageDesc.FullName() { + return d.newError(tok.Pos(), "message %v cannot be extended by %v", messageDesc.FullName(), fd.FullName()) + } + } else if xtErr != nil && xtErr != protoregistry.NotFound { + return d.newError(tok.Pos(), "unable to resolve [%s]: %v", tok.RawString(), xtErr) + } + if flags.ProtoLegacy { + if fd != nil && fd.IsWeak() && fd.Message().IsPlaceholder() { + fd = nil // reset since the weak reference is not linked in + } + } + + // Handle unknown fields. + if fd == nil { + if d.opts.DiscardUnknown || messageDesc.ReservedNames().Has(name) { + d.skipValue() + continue + } + return d.newError(tok.Pos(), "unknown field: %v", tok.RawString()) + } + + // Handle fields identified by field number. + if isFieldNumberName { + // TODO: Add an option to permit parsing field numbers. + // + // This requires careful thought as the MarshalOptions.EmitUnknown + // option allows formatting unknown fields as the field number and the + // best-effort textual representation of the field value. In that case, + // it may not be possible to unmarshal the value from a parser that does + // have information about the unknown field. + return d.newError(tok.Pos(), "cannot specify field by number: %v", tok.RawString()) + } + + switch { + case fd.IsList(): + kind := fd.Kind() + if kind != pref.MessageKind && kind != pref.GroupKind && !tok.HasSeparator() { + return d.syntaxError(tok.Pos(), "missing field separator :") + } + + list := m.Mutable(fd).List() + if err := d.unmarshalList(fd, list); err != nil { + return err + } + + case fd.IsMap(): + mmap := m.Mutable(fd).Map() + if err := d.unmarshalMap(fd, mmap); err != nil { + return err + } + + default: + kind := fd.Kind() + if kind != pref.MessageKind && kind != pref.GroupKind && !tok.HasSeparator() { + return d.syntaxError(tok.Pos(), "missing field separator :") + } + + // If field is a oneof, check if it has already been set. + if od := fd.ContainingOneof(); od != nil { + idx := uint64(od.Index()) + if seenOneofs.Has(idx) { + return d.newError(tok.Pos(), "error parsing %q, oneof %v is already set", tok.RawString(), od.FullName()) + } + seenOneofs.Set(idx) + } + + num := uint64(fd.Number()) + if seenNums.Has(num) { + return d.newError(tok.Pos(), "non-repeated field %q is repeated", tok.RawString()) + } + + if err := d.unmarshalSingular(fd, m); err != nil { + return err + } + seenNums.Set(num) + } + } + + return nil +} + +// findExtension returns protoreflect.ExtensionType from the Resolver if found. +func (d decoder) findExtension(xtName pref.FullName) (pref.ExtensionType, error) { + xt, err := d.opts.Resolver.FindExtensionByName(xtName) + if err == nil { + return xt, nil + } + return messageset.FindMessageSetExtension(d.opts.Resolver, xtName) +} + +// unmarshalSingular unmarshals a non-repeated field value specified by the +// given FieldDescriptor. +func (d decoder) unmarshalSingular(fd pref.FieldDescriptor, m pref.Message) error { + var val pref.Value + var err error + switch fd.Kind() { + case pref.MessageKind, pref.GroupKind: + val = m.NewField(fd) + err = d.unmarshalMessage(val.Message(), true) + default: + val, err = d.unmarshalScalar(fd) + } + if err == nil { + m.Set(fd, val) + } + return err +} + +// unmarshalScalar unmarshals a scalar/enum protoreflect.Value specified by the +// given FieldDescriptor. +func (d decoder) unmarshalScalar(fd pref.FieldDescriptor) (pref.Value, error) { + tok, err := d.Read() + if err != nil { + return pref.Value{}, err + } + + if tok.Kind() != text.Scalar { + return pref.Value{}, d.unexpectedTokenError(tok) + } + + kind := fd.Kind() + switch kind { + case pref.BoolKind: + if b, ok := tok.Bool(); ok { + return pref.ValueOfBool(b), nil + } + + case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind: + if n, ok := tok.Int32(); ok { + return pref.ValueOfInt32(n), nil + } + + case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind: + if n, ok := tok.Int64(); ok { + return pref.ValueOfInt64(n), nil + } + + case pref.Uint32Kind, pref.Fixed32Kind: + if n, ok := tok.Uint32(); ok { + return pref.ValueOfUint32(n), nil + } + + case pref.Uint64Kind, pref.Fixed64Kind: + if n, ok := tok.Uint64(); ok { + return pref.ValueOfUint64(n), nil + } + + case pref.FloatKind: + if n, ok := tok.Float32(); ok { + return pref.ValueOfFloat32(n), nil + } + + case pref.DoubleKind: + if n, ok := tok.Float64(); ok { + return pref.ValueOfFloat64(n), nil + } + + case pref.StringKind: + if s, ok := tok.String(); ok { + if strs.EnforceUTF8(fd) && !utf8.ValidString(s) { + return pref.Value{}, d.newError(tok.Pos(), "contains invalid UTF-8") + } + return pref.ValueOfString(s), nil + } + + case pref.BytesKind: + if b, ok := tok.String(); ok { + return pref.ValueOfBytes([]byte(b)), nil + } + + case pref.EnumKind: + if lit, ok := tok.Enum(); ok { + // Lookup EnumNumber based on name. + if enumVal := fd.Enum().Values().ByName(pref.Name(lit)); enumVal != nil { + return pref.ValueOfEnum(enumVal.Number()), nil + } + } + if num, ok := tok.Int32(); ok { + return pref.ValueOfEnum(pref.EnumNumber(num)), nil + } + + default: + panic(fmt.Sprintf("invalid scalar kind %v", kind)) + } + + return pref.Value{}, d.newError(tok.Pos(), "invalid value for %v type: %v", kind, tok.RawString()) +} + +// unmarshalList unmarshals into given protoreflect.List. A list value can +// either be in [] syntax or simply just a single scalar/message value. +func (d decoder) unmarshalList(fd pref.FieldDescriptor, list pref.List) error { + tok, err := d.Peek() + if err != nil { + return err + } + + switch fd.Kind() { + case pref.MessageKind, pref.GroupKind: + switch tok.Kind() { + case text.ListOpen: + d.Read() + for { + tok, err := d.Peek() + if err != nil { + return err + } + + switch tok.Kind() { + case text.ListClose: + d.Read() + return nil + case text.MessageOpen: + pval := list.NewElement() + if err := d.unmarshalMessage(pval.Message(), true); err != nil { + return err + } + list.Append(pval) + default: + return d.unexpectedTokenError(tok) + } + } + + case text.MessageOpen: + pval := list.NewElement() + if err := d.unmarshalMessage(pval.Message(), true); err != nil { + return err + } + list.Append(pval) + return nil + } + + default: + switch tok.Kind() { + case text.ListOpen: + d.Read() + for { + tok, err := d.Peek() + if err != nil { + return err + } + + switch tok.Kind() { + case text.ListClose: + d.Read() + return nil + case text.Scalar: + pval, err := d.unmarshalScalar(fd) + if err != nil { + return err + } + list.Append(pval) + default: + return d.unexpectedTokenError(tok) + } + } + + case text.Scalar: + pval, err := d.unmarshalScalar(fd) + if err != nil { + return err + } + list.Append(pval) + return nil + } + } + + return d.unexpectedTokenError(tok) +} + +// unmarshalMap unmarshals into given protoreflect.Map. A map value is a +// textproto message containing {key: , value: }. +func (d decoder) unmarshalMap(fd pref.FieldDescriptor, mmap pref.Map) error { + // Determine ahead whether map entry is a scalar type or a message type in + // order to call the appropriate unmarshalMapValue func inside + // unmarshalMapEntry. + var unmarshalMapValue func() (pref.Value, error) + switch fd.MapValue().Kind() { + case pref.MessageKind, pref.GroupKind: + unmarshalMapValue = func() (pref.Value, error) { + pval := mmap.NewValue() + if err := d.unmarshalMessage(pval.Message(), true); err != nil { + return pref.Value{}, err + } + return pval, nil + } + default: + unmarshalMapValue = func() (pref.Value, error) { + return d.unmarshalScalar(fd.MapValue()) + } + } + + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + case text.MessageOpen: + return d.unmarshalMapEntry(fd, mmap, unmarshalMapValue) + + case text.ListOpen: + for { + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + case text.ListClose: + return nil + case text.MessageOpen: + if err := d.unmarshalMapEntry(fd, mmap, unmarshalMapValue); err != nil { + return err + } + default: + return d.unexpectedTokenError(tok) + } + } + + default: + return d.unexpectedTokenError(tok) + } +} + +// unmarshalMap unmarshals into given protoreflect.Map. A map value is a +// textproto message containing {key: , value: }. +func (d decoder) unmarshalMapEntry(fd pref.FieldDescriptor, mmap pref.Map, unmarshalMapValue func() (pref.Value, error)) error { + var key pref.MapKey + var pval pref.Value +Loop: + for { + // Read field name. + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + case text.Name: + if tok.NameKind() != text.IdentName { + if !d.opts.DiscardUnknown { + return d.newError(tok.Pos(), "unknown map entry field %q", tok.RawString()) + } + d.skipValue() + continue Loop + } + // Continue below. + case text.MessageClose: + break Loop + default: + return d.unexpectedTokenError(tok) + } + + switch name := pref.Name(tok.IdentName()); name { + case genid.MapEntry_Key_field_name: + if !tok.HasSeparator() { + return d.syntaxError(tok.Pos(), "missing field separator :") + } + if key.IsValid() { + return d.newError(tok.Pos(), "map entry %q cannot be repeated", name) + } + val, err := d.unmarshalScalar(fd.MapKey()) + if err != nil { + return err + } + key = val.MapKey() + + case genid.MapEntry_Value_field_name: + if kind := fd.MapValue().Kind(); (kind != pref.MessageKind) && (kind != pref.GroupKind) { + if !tok.HasSeparator() { + return d.syntaxError(tok.Pos(), "missing field separator :") + } + } + if pval.IsValid() { + return d.newError(tok.Pos(), "map entry %q cannot be repeated", name) + } + pval, err = unmarshalMapValue() + if err != nil { + return err + } + + default: + if !d.opts.DiscardUnknown { + return d.newError(tok.Pos(), "unknown map entry field %q", name) + } + d.skipValue() + } + } + + if !key.IsValid() { + key = fd.MapKey().Default().MapKey() + } + if !pval.IsValid() { + switch fd.MapValue().Kind() { + case pref.MessageKind, pref.GroupKind: + // If value field is not set for message/group types, construct an + // empty one as default. + pval = mmap.NewValue() + default: + pval = fd.MapValue().Default() + } + } + mmap.Set(key, pval) + return nil +} + +// unmarshalAny unmarshals an Any textproto. It can either be in expanded form +// or non-expanded form. +func (d decoder) unmarshalAny(m pref.Message, checkDelims bool) error { + var typeURL string + var bValue []byte + var seenTypeUrl bool + var seenValue bool + var isExpanded bool + + if checkDelims { + tok, err := d.Read() + if err != nil { + return err + } + + if tok.Kind() != text.MessageOpen { + return d.unexpectedTokenError(tok) + } + } + +Loop: + for { + // Read field name. Can only have 3 possible field names, i.e. type_url, + // value and type URL name inside []. + tok, err := d.Read() + if err != nil { + return err + } + if typ := tok.Kind(); typ != text.Name { + if checkDelims { + if typ == text.MessageClose { + break Loop + } + } else if typ == text.EOF { + break Loop + } + return d.unexpectedTokenError(tok) + } + + switch tok.NameKind() { + case text.IdentName: + // Both type_url and value fields require field separator :. + if !tok.HasSeparator() { + return d.syntaxError(tok.Pos(), "missing field separator :") + } + + switch name := pref.Name(tok.IdentName()); name { + case genid.Any_TypeUrl_field_name: + if seenTypeUrl { + return d.newError(tok.Pos(), "duplicate %v field", genid.Any_TypeUrl_field_fullname) + } + if isExpanded { + return d.newError(tok.Pos(), "conflict with [%s] field", typeURL) + } + tok, err := d.Read() + if err != nil { + return err + } + var ok bool + typeURL, ok = tok.String() + if !ok { + return d.newError(tok.Pos(), "invalid %v field value: %v", genid.Any_TypeUrl_field_fullname, tok.RawString()) + } + seenTypeUrl = true + + case genid.Any_Value_field_name: + if seenValue { + return d.newError(tok.Pos(), "duplicate %v field", genid.Any_Value_field_fullname) + } + if isExpanded { + return d.newError(tok.Pos(), "conflict with [%s] field", typeURL) + } + tok, err := d.Read() + if err != nil { + return err + } + s, ok := tok.String() + if !ok { + return d.newError(tok.Pos(), "invalid %v field value: %v", genid.Any_Value_field_fullname, tok.RawString()) + } + bValue = []byte(s) + seenValue = true + + default: + if !d.opts.DiscardUnknown { + return d.newError(tok.Pos(), "invalid field name %q in %v message", tok.RawString(), genid.Any_message_fullname) + } + } + + case text.TypeName: + if isExpanded { + return d.newError(tok.Pos(), "cannot have more than one type") + } + if seenTypeUrl { + return d.newError(tok.Pos(), "conflict with type_url field") + } + typeURL = tok.TypeName() + var err error + bValue, err = d.unmarshalExpandedAny(typeURL, tok.Pos()) + if err != nil { + return err + } + isExpanded = true + + default: + if !d.opts.DiscardUnknown { + return d.newError(tok.Pos(), "invalid field name %q in %v message", tok.RawString(), genid.Any_message_fullname) + } + } + } + + fds := m.Descriptor().Fields() + if len(typeURL) > 0 { + m.Set(fds.ByNumber(genid.Any_TypeUrl_field_number), pref.ValueOfString(typeURL)) + } + if len(bValue) > 0 { + m.Set(fds.ByNumber(genid.Any_Value_field_number), pref.ValueOfBytes(bValue)) + } + return nil +} + +func (d decoder) unmarshalExpandedAny(typeURL string, pos int) ([]byte, error) { + mt, err := d.opts.Resolver.FindMessageByURL(typeURL) + if err != nil { + return nil, d.newError(pos, "unable to resolve message [%v]: %v", typeURL, err) + } + // Create new message for the embedded message type and unmarshal the value + // field into it. + m := mt.New() + if err := d.unmarshalMessage(m, true); err != nil { + return nil, err + } + // Serialize the embedded message and return the resulting bytes. + b, err := proto.MarshalOptions{ + AllowPartial: true, // Never check required fields inside an Any. + Deterministic: true, + }.Marshal(m.Interface()) + if err != nil { + return nil, d.newError(pos, "error in marshaling message into Any.value: %v", err) + } + return b, nil +} + +// skipValue makes the decoder parse a field value in order to advance the read +// to the next field. It relies on Read returning an error if the types are not +// in valid sequence. +func (d decoder) skipValue() error { + tok, err := d.Read() + if err != nil { + return err + } + // Only need to continue reading for messages and lists. + switch tok.Kind() { + case text.MessageOpen: + return d.skipMessageValue() + + case text.ListOpen: + for { + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + case text.ListClose: + return nil + case text.MessageOpen: + return d.skipMessageValue() + default: + // Skip items. This will not validate whether skipped values are + // of the same type or not, same behavior as C++ + // TextFormat::Parser::AllowUnknownField(true) version 3.8.0. + if err := d.skipValue(); err != nil { + return err + } + } + } + } + return nil +} + +// skipMessageValue makes the decoder parse and skip over all fields in a +// message. It assumes that the previous read type is MessageOpen. +func (d decoder) skipMessageValue() error { + for { + tok, err := d.Read() + if err != nil { + return err + } + switch tok.Kind() { + case text.MessageClose: + return nil + case text.Name: + if err := d.skipValue(); err != nil { + return err + } + } + } +} diff --git a/vendor/google.golang.org/protobuf/encoding/prototext/doc.go b/vendor/google.golang.org/protobuf/encoding/prototext/doc.go new file mode 100644 index 00000000000..162b4f98a41 --- /dev/null +++ b/vendor/google.golang.org/protobuf/encoding/prototext/doc.go @@ -0,0 +1,7 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package prototext marshals and unmarshals protocol buffer messages as the +// textproto format. +package prototext diff --git a/vendor/google.golang.org/protobuf/encoding/prototext/encode.go b/vendor/google.golang.org/protobuf/encoding/prototext/encode.go new file mode 100644 index 00000000000..0877d71c519 --- /dev/null +++ b/vendor/google.golang.org/protobuf/encoding/prototext/encode.go @@ -0,0 +1,433 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package prototext + +import ( + "fmt" + "sort" + "strconv" + "unicode/utf8" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/encoding/text" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/mapsort" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/proto" + pref "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +const defaultIndent = " " + +// Format formats the message as a multiline string. +// This function is only intended for human consumption and ignores errors. +// Do not depend on the output being stable. It may change over time across +// different versions of the program. +func Format(m proto.Message) string { + return MarshalOptions{Multiline: true}.Format(m) +} + +// Marshal writes the given proto.Message in textproto format using default +// options. Do not depend on the output being stable. It may change over time +// across different versions of the program. +func Marshal(m proto.Message) ([]byte, error) { + return MarshalOptions{}.Marshal(m) +} + +// MarshalOptions is a configurable text format marshaler. +type MarshalOptions struct { + pragma.NoUnkeyedLiterals + + // Multiline specifies whether the marshaler should format the output in + // indented-form with every textual element on a new line. + // If Indent is an empty string, then an arbitrary indent is chosen. + Multiline bool + + // Indent specifies the set of indentation characters to use in a multiline + // formatted output such that every entry is preceded by Indent and + // terminated by a newline. If non-empty, then Multiline is treated as true. + // Indent can only be composed of space or tab characters. + Indent string + + // EmitASCII specifies whether to format strings and bytes as ASCII only + // as opposed to using UTF-8 encoding when possible. + EmitASCII bool + + // allowInvalidUTF8 specifies whether to permit the encoding of strings + // with invalid UTF-8. This is unexported as it is intended to only + // be specified by the Format method. + allowInvalidUTF8 bool + + // AllowPartial allows messages that have missing required fields to marshal + // without returning an error. If AllowPartial is false (the default), + // Marshal will return error if there are any missing required fields. + AllowPartial bool + + // EmitUnknown specifies whether to emit unknown fields in the output. + // If specified, the unmarshaler may be unable to parse the output. + // The default is to exclude unknown fields. + EmitUnknown bool + + // Resolver is used for looking up types when expanding google.protobuf.Any + // messages. If nil, this defaults to using protoregistry.GlobalTypes. + Resolver interface { + protoregistry.ExtensionTypeResolver + protoregistry.MessageTypeResolver + } +} + +// Format formats the message as a string. +// This method is only intended for human consumption and ignores errors. +// Do not depend on the output being stable. It may change over time across +// different versions of the program. +func (o MarshalOptions) Format(m proto.Message) string { + if m == nil || !m.ProtoReflect().IsValid() { + return "" // invalid syntax, but okay since this is for debugging + } + o.allowInvalidUTF8 = true + o.AllowPartial = true + o.EmitUnknown = true + b, _ := o.Marshal(m) + return string(b) +} + +// Marshal writes the given proto.Message in textproto format using options in +// MarshalOptions object. Do not depend on the output being stable. It may +// change over time across different versions of the program. +func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) { + return o.marshal(m) +} + +// marshal is a centralized function that all marshal operations go through. +// For profiling purposes, avoid changing the name of this function or +// introducing other code paths for marshal that do not go through this. +func (o MarshalOptions) marshal(m proto.Message) ([]byte, error) { + var delims = [2]byte{'{', '}'} + + if o.Multiline && o.Indent == "" { + o.Indent = defaultIndent + } + if o.Resolver == nil { + o.Resolver = protoregistry.GlobalTypes + } + + internalEnc, err := text.NewEncoder(o.Indent, delims, o.EmitASCII) + if err != nil { + return nil, err + } + + // Treat nil message interface as an empty message, + // in which case there is nothing to output. + if m == nil { + return []byte{}, nil + } + + enc := encoder{internalEnc, o} + err = enc.marshalMessage(m.ProtoReflect(), false) + if err != nil { + return nil, err + } + out := enc.Bytes() + if len(o.Indent) > 0 && len(out) > 0 { + out = append(out, '\n') + } + if o.AllowPartial { + return out, nil + } + return out, proto.CheckInitialized(m) +} + +type encoder struct { + *text.Encoder + opts MarshalOptions +} + +// marshalMessage marshals the given protoreflect.Message. +func (e encoder) marshalMessage(m pref.Message, inclDelims bool) error { + messageDesc := m.Descriptor() + if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) { + return errors.New("no support for proto1 MessageSets") + } + + if inclDelims { + e.StartMessage() + defer e.EndMessage() + } + + // Handle Any expansion. + if messageDesc.FullName() == genid.Any_message_fullname { + if e.marshalAny(m) { + return nil + } + // If unable to expand, continue on to marshal Any as a regular message. + } + + // Marshal known fields. + fieldDescs := messageDesc.Fields() + size := fieldDescs.Len() + for i := 0; i < size; { + fd := fieldDescs.Get(i) + if od := fd.ContainingOneof(); od != nil { + fd = m.WhichOneof(od) + i += od.Fields().Len() + } else { + i++ + } + + if fd == nil || !m.Has(fd) { + continue + } + + name := fd.Name() + // Use type name for group field name. + if fd.Kind() == pref.GroupKind { + name = fd.Message().Name() + } + val := m.Get(fd) + if err := e.marshalField(string(name), val, fd); err != nil { + return err + } + } + + // Marshal extensions. + if err := e.marshalExtensions(m); err != nil { + return err + } + + // Marshal unknown fields. + if e.opts.EmitUnknown { + e.marshalUnknown(m.GetUnknown()) + } + + return nil +} + +// marshalField marshals the given field with protoreflect.Value. +func (e encoder) marshalField(name string, val pref.Value, fd pref.FieldDescriptor) error { + switch { + case fd.IsList(): + return e.marshalList(name, val.List(), fd) + case fd.IsMap(): + return e.marshalMap(name, val.Map(), fd) + default: + e.WriteName(name) + return e.marshalSingular(val, fd) + } +} + +// marshalSingular marshals the given non-repeated field value. This includes +// all scalar types, enums, messages, and groups. +func (e encoder) marshalSingular(val pref.Value, fd pref.FieldDescriptor) error { + kind := fd.Kind() + switch kind { + case pref.BoolKind: + e.WriteBool(val.Bool()) + + case pref.StringKind: + s := val.String() + if !e.opts.allowInvalidUTF8 && strs.EnforceUTF8(fd) && !utf8.ValidString(s) { + return errors.InvalidUTF8(string(fd.FullName())) + } + e.WriteString(s) + + case pref.Int32Kind, pref.Int64Kind, + pref.Sint32Kind, pref.Sint64Kind, + pref.Sfixed32Kind, pref.Sfixed64Kind: + e.WriteInt(val.Int()) + + case pref.Uint32Kind, pref.Uint64Kind, + pref.Fixed32Kind, pref.Fixed64Kind: + e.WriteUint(val.Uint()) + + case pref.FloatKind: + // Encoder.WriteFloat handles the special numbers NaN and infinites. + e.WriteFloat(val.Float(), 32) + + case pref.DoubleKind: + // Encoder.WriteFloat handles the special numbers NaN and infinites. + e.WriteFloat(val.Float(), 64) + + case pref.BytesKind: + e.WriteString(string(val.Bytes())) + + case pref.EnumKind: + num := val.Enum() + if desc := fd.Enum().Values().ByNumber(num); desc != nil { + e.WriteLiteral(string(desc.Name())) + } else { + // Use numeric value if there is no enum description. + e.WriteInt(int64(num)) + } + + case pref.MessageKind, pref.GroupKind: + return e.marshalMessage(val.Message(), true) + + default: + panic(fmt.Sprintf("%v has unknown kind: %v", fd.FullName(), kind)) + } + return nil +} + +// marshalList marshals the given protoreflect.List as multiple name-value fields. +func (e encoder) marshalList(name string, list pref.List, fd pref.FieldDescriptor) error { + size := list.Len() + for i := 0; i < size; i++ { + e.WriteName(name) + if err := e.marshalSingular(list.Get(i), fd); err != nil { + return err + } + } + return nil +} + +// marshalMap marshals the given protoreflect.Map as multiple name-value fields. +func (e encoder) marshalMap(name string, mmap pref.Map, fd pref.FieldDescriptor) error { + var err error + mapsort.Range(mmap, fd.MapKey().Kind(), func(key pref.MapKey, val pref.Value) bool { + e.WriteName(name) + e.StartMessage() + defer e.EndMessage() + + e.WriteName(string(genid.MapEntry_Key_field_name)) + err = e.marshalSingular(key.Value(), fd.MapKey()) + if err != nil { + return false + } + + e.WriteName(string(genid.MapEntry_Value_field_name)) + err = e.marshalSingular(val, fd.MapValue()) + if err != nil { + return false + } + return true + }) + return err +} + +// marshalExtensions marshals extension fields. +func (e encoder) marshalExtensions(m pref.Message) error { + type entry struct { + key string + value pref.Value + desc pref.FieldDescriptor + } + + // Get a sorted list based on field key first. + var entries []entry + m.Range(func(fd pref.FieldDescriptor, v pref.Value) bool { + if !fd.IsExtension() { + return true + } + // For MessageSet extensions, the name used is the parent message. + name := fd.FullName() + if messageset.IsMessageSetExtension(fd) { + name = name.Parent() + } + entries = append(entries, entry{ + key: string(name), + value: v, + desc: fd, + }) + return true + }) + // Sort extensions lexicographically. + sort.Slice(entries, func(i, j int) bool { + return entries[i].key < entries[j].key + }) + + // Write out sorted list. + for _, entry := range entries { + // Extension field name is the proto field name enclosed in []. + name := "[" + entry.key + "]" + if err := e.marshalField(name, entry.value, entry.desc); err != nil { + return err + } + } + return nil +} + +// marshalUnknown parses the given []byte and marshals fields out. +// This function assumes proper encoding in the given []byte. +func (e encoder) marshalUnknown(b []byte) { + const dec = 10 + const hex = 16 + for len(b) > 0 { + num, wtype, n := protowire.ConsumeTag(b) + b = b[n:] + e.WriteName(strconv.FormatInt(int64(num), dec)) + + switch wtype { + case protowire.VarintType: + var v uint64 + v, n = protowire.ConsumeVarint(b) + e.WriteUint(v) + case protowire.Fixed32Type: + var v uint32 + v, n = protowire.ConsumeFixed32(b) + e.WriteLiteral("0x" + strconv.FormatUint(uint64(v), hex)) + case protowire.Fixed64Type: + var v uint64 + v, n = protowire.ConsumeFixed64(b) + e.WriteLiteral("0x" + strconv.FormatUint(v, hex)) + case protowire.BytesType: + var v []byte + v, n = protowire.ConsumeBytes(b) + e.WriteString(string(v)) + case protowire.StartGroupType: + e.StartMessage() + var v []byte + v, n = protowire.ConsumeGroup(num, b) + e.marshalUnknown(v) + e.EndMessage() + default: + panic(fmt.Sprintf("prototext: error parsing unknown field wire type: %v", wtype)) + } + + b = b[n:] + } +} + +// marshalAny marshals the given google.protobuf.Any message in expanded form. +// It returns true if it was able to marshal, else false. +func (e encoder) marshalAny(any pref.Message) bool { + // Construct the embedded message. + fds := any.Descriptor().Fields() + fdType := fds.ByNumber(genid.Any_TypeUrl_field_number) + typeURL := any.Get(fdType).String() + mt, err := e.opts.Resolver.FindMessageByURL(typeURL) + if err != nil { + return false + } + m := mt.New().Interface() + + // Unmarshal bytes into embedded message. + fdValue := fds.ByNumber(genid.Any_Value_field_number) + value := any.Get(fdValue) + err = proto.UnmarshalOptions{ + AllowPartial: true, + Resolver: e.opts.Resolver, + }.Unmarshal(value.Bytes(), m) + if err != nil { + return false + } + + // Get current encoder position. If marshaling fails, reset encoder output + // back to this position. + pos := e.Snapshot() + + // Field name is the proto field name enclosed in []. + e.WriteName("[" + typeURL + "]") + err = e.marshalMessage(m.ProtoReflect(), true) + if err != nil { + e.Reset(pos) + return false + } + return true +} diff --git a/vendor/google.golang.org/protobuf/encoding/protowire/wire.go b/vendor/google.golang.org/protobuf/encoding/protowire/wire.go new file mode 100644 index 00000000000..a427f8b7043 --- /dev/null +++ b/vendor/google.golang.org/protobuf/encoding/protowire/wire.go @@ -0,0 +1,538 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package protowire parses and formats the raw wire encoding. +// See https://developers.google.com/protocol-buffers/docs/encoding. +// +// For marshaling and unmarshaling entire protobuf messages, +// use the "google.golang.org/protobuf/proto" package instead. +package protowire + +import ( + "io" + "math" + "math/bits" + + "google.golang.org/protobuf/internal/errors" +) + +// Number represents the field number. +type Number int32 + +const ( + MinValidNumber Number = 1 + FirstReservedNumber Number = 19000 + LastReservedNumber Number = 19999 + MaxValidNumber Number = 1<<29 - 1 +) + +// IsValid reports whether the field number is semantically valid. +// +// Note that while numbers within the reserved range are semantically invalid, +// they are syntactically valid in the wire format. +// Implementations may treat records with reserved field numbers as unknown. +func (n Number) IsValid() bool { + return MinValidNumber <= n && n < FirstReservedNumber || LastReservedNumber < n && n <= MaxValidNumber +} + +// Type represents the wire type. +type Type int8 + +const ( + VarintType Type = 0 + Fixed32Type Type = 5 + Fixed64Type Type = 1 + BytesType Type = 2 + StartGroupType Type = 3 + EndGroupType Type = 4 +) + +const ( + _ = -iota + errCodeTruncated + errCodeFieldNumber + errCodeOverflow + errCodeReserved + errCodeEndGroup +) + +var ( + errFieldNumber = errors.New("invalid field number") + errOverflow = errors.New("variable length integer overflow") + errReserved = errors.New("cannot parse reserved wire type") + errEndGroup = errors.New("mismatching end group marker") + errParse = errors.New("parse error") +) + +// ParseError converts an error code into an error value. +// This returns nil if n is a non-negative number. +func ParseError(n int) error { + if n >= 0 { + return nil + } + switch n { + case errCodeTruncated: + return io.ErrUnexpectedEOF + case errCodeFieldNumber: + return errFieldNumber + case errCodeOverflow: + return errOverflow + case errCodeReserved: + return errReserved + case errCodeEndGroup: + return errEndGroup + default: + return errParse + } +} + +// ConsumeField parses an entire field record (both tag and value) and returns +// the field number, the wire type, and the total length. +// This returns a negative length upon an error (see ParseError). +// +// The total length includes the tag header and the end group marker (if the +// field is a group). +func ConsumeField(b []byte) (Number, Type, int) { + num, typ, n := ConsumeTag(b) + if n < 0 { + return 0, 0, n // forward error code + } + m := ConsumeFieldValue(num, typ, b[n:]) + if m < 0 { + return 0, 0, m // forward error code + } + return num, typ, n + m +} + +// ConsumeFieldValue parses a field value and returns its length. +// This assumes that the field Number and wire Type have already been parsed. +// This returns a negative length upon an error (see ParseError). +// +// When parsing a group, the length includes the end group marker and +// the end group is verified to match the starting field number. +func ConsumeFieldValue(num Number, typ Type, b []byte) (n int) { + switch typ { + case VarintType: + _, n = ConsumeVarint(b) + return n + case Fixed32Type: + _, n = ConsumeFixed32(b) + return n + case Fixed64Type: + _, n = ConsumeFixed64(b) + return n + case BytesType: + _, n = ConsumeBytes(b) + return n + case StartGroupType: + n0 := len(b) + for { + num2, typ2, n := ConsumeTag(b) + if n < 0 { + return n // forward error code + } + b = b[n:] + if typ2 == EndGroupType { + if num != num2 { + return errCodeEndGroup + } + return n0 - len(b) + } + + n = ConsumeFieldValue(num2, typ2, b) + if n < 0 { + return n // forward error code + } + b = b[n:] + } + case EndGroupType: + return errCodeEndGroup + default: + return errCodeReserved + } +} + +// AppendTag encodes num and typ as a varint-encoded tag and appends it to b. +func AppendTag(b []byte, num Number, typ Type) []byte { + return AppendVarint(b, EncodeTag(num, typ)) +} + +// ConsumeTag parses b as a varint-encoded tag, reporting its length. +// This returns a negative length upon an error (see ParseError). +func ConsumeTag(b []byte) (Number, Type, int) { + v, n := ConsumeVarint(b) + if n < 0 { + return 0, 0, n // forward error code + } + num, typ := DecodeTag(v) + if num < MinValidNumber { + return 0, 0, errCodeFieldNumber + } + return num, typ, n +} + +func SizeTag(num Number) int { + return SizeVarint(EncodeTag(num, 0)) // wire type has no effect on size +} + +// AppendVarint appends v to b as a varint-encoded uint64. +func AppendVarint(b []byte, v uint64) []byte { + switch { + case v < 1<<7: + b = append(b, byte(v)) + case v < 1<<14: + b = append(b, + byte((v>>0)&0x7f|0x80), + byte(v>>7)) + case v < 1<<21: + b = append(b, + byte((v>>0)&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte(v>>14)) + case v < 1<<28: + b = append(b, + byte((v>>0)&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte(v>>21)) + case v < 1<<35: + b = append(b, + byte((v>>0)&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte(v>>28)) + case v < 1<<42: + b = append(b, + byte((v>>0)&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte(v>>35)) + case v < 1<<49: + b = append(b, + byte((v>>0)&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte(v>>42)) + case v < 1<<56: + b = append(b, + byte((v>>0)&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte(v>>49)) + case v < 1<<63: + b = append(b, + byte((v>>0)&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte((v>>49)&0x7f|0x80), + byte(v>>56)) + default: + b = append(b, + byte((v>>0)&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte((v>>49)&0x7f|0x80), + byte((v>>56)&0x7f|0x80), + 1) + } + return b +} + +// ConsumeVarint parses b as a varint-encoded uint64, reporting its length. +// This returns a negative length upon an error (see ParseError). +func ConsumeVarint(b []byte) (v uint64, n int) { + var y uint64 + if len(b) <= 0 { + return 0, errCodeTruncated + } + v = uint64(b[0]) + if v < 0x80 { + return v, 1 + } + v -= 0x80 + + if len(b) <= 1 { + return 0, errCodeTruncated + } + y = uint64(b[1]) + v += y << 7 + if y < 0x80 { + return v, 2 + } + v -= 0x80 << 7 + + if len(b) <= 2 { + return 0, errCodeTruncated + } + y = uint64(b[2]) + v += y << 14 + if y < 0x80 { + return v, 3 + } + v -= 0x80 << 14 + + if len(b) <= 3 { + return 0, errCodeTruncated + } + y = uint64(b[3]) + v += y << 21 + if y < 0x80 { + return v, 4 + } + v -= 0x80 << 21 + + if len(b) <= 4 { + return 0, errCodeTruncated + } + y = uint64(b[4]) + v += y << 28 + if y < 0x80 { + return v, 5 + } + v -= 0x80 << 28 + + if len(b) <= 5 { + return 0, errCodeTruncated + } + y = uint64(b[5]) + v += y << 35 + if y < 0x80 { + return v, 6 + } + v -= 0x80 << 35 + + if len(b) <= 6 { + return 0, errCodeTruncated + } + y = uint64(b[6]) + v += y << 42 + if y < 0x80 { + return v, 7 + } + v -= 0x80 << 42 + + if len(b) <= 7 { + return 0, errCodeTruncated + } + y = uint64(b[7]) + v += y << 49 + if y < 0x80 { + return v, 8 + } + v -= 0x80 << 49 + + if len(b) <= 8 { + return 0, errCodeTruncated + } + y = uint64(b[8]) + v += y << 56 + if y < 0x80 { + return v, 9 + } + v -= 0x80 << 56 + + if len(b) <= 9 { + return 0, errCodeTruncated + } + y = uint64(b[9]) + v += y << 63 + if y < 2 { + return v, 10 + } + return 0, errCodeOverflow +} + +// SizeVarint returns the encoded size of a varint. +// The size is guaranteed to be within 1 and 10, inclusive. +func SizeVarint(v uint64) int { + // This computes 1 + (bits.Len64(v)-1)/7. + // 9/64 is a good enough approximation of 1/7 + return int(9*uint32(bits.Len64(v))+64) / 64 +} + +// AppendFixed32 appends v to b as a little-endian uint32. +func AppendFixed32(b []byte, v uint32) []byte { + return append(b, + byte(v>>0), + byte(v>>8), + byte(v>>16), + byte(v>>24)) +} + +// ConsumeFixed32 parses b as a little-endian uint32, reporting its length. +// This returns a negative length upon an error (see ParseError). +func ConsumeFixed32(b []byte) (v uint32, n int) { + if len(b) < 4 { + return 0, errCodeTruncated + } + v = uint32(b[0])<<0 | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + return v, 4 +} + +// SizeFixed32 returns the encoded size of a fixed32; which is always 4. +func SizeFixed32() int { + return 4 +} + +// AppendFixed64 appends v to b as a little-endian uint64. +func AppendFixed64(b []byte, v uint64) []byte { + return append(b, + byte(v>>0), + byte(v>>8), + byte(v>>16), + byte(v>>24), + byte(v>>32), + byte(v>>40), + byte(v>>48), + byte(v>>56)) +} + +// ConsumeFixed64 parses b as a little-endian uint64, reporting its length. +// This returns a negative length upon an error (see ParseError). +func ConsumeFixed64(b []byte) (v uint64, n int) { + if len(b) < 8 { + return 0, errCodeTruncated + } + v = uint64(b[0])<<0 | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 + return v, 8 +} + +// SizeFixed64 returns the encoded size of a fixed64; which is always 8. +func SizeFixed64() int { + return 8 +} + +// AppendBytes appends v to b as a length-prefixed bytes value. +func AppendBytes(b []byte, v []byte) []byte { + return append(AppendVarint(b, uint64(len(v))), v...) +} + +// ConsumeBytes parses b as a length-prefixed bytes value, reporting its length. +// This returns a negative length upon an error (see ParseError). +func ConsumeBytes(b []byte) (v []byte, n int) { + m, n := ConsumeVarint(b) + if n < 0 { + return nil, n // forward error code + } + if m > uint64(len(b[n:])) { + return nil, errCodeTruncated + } + return b[n:][:m], n + int(m) +} + +// SizeBytes returns the encoded size of a length-prefixed bytes value, +// given only the length. +func SizeBytes(n int) int { + return SizeVarint(uint64(n)) + n +} + +// AppendString appends v to b as a length-prefixed bytes value. +func AppendString(b []byte, v string) []byte { + return append(AppendVarint(b, uint64(len(v))), v...) +} + +// ConsumeString parses b as a length-prefixed bytes value, reporting its length. +// This returns a negative length upon an error (see ParseError). +func ConsumeString(b []byte) (v string, n int) { + bb, n := ConsumeBytes(b) + return string(bb), n +} + +// AppendGroup appends v to b as group value, with a trailing end group marker. +// The value v must not contain the end marker. +func AppendGroup(b []byte, num Number, v []byte) []byte { + return AppendVarint(append(b, v...), EncodeTag(num, EndGroupType)) +} + +// ConsumeGroup parses b as a group value until the trailing end group marker, +// and verifies that the end marker matches the provided num. The value v +// does not contain the end marker, while the length does contain the end marker. +// This returns a negative length upon an error (see ParseError). +func ConsumeGroup(num Number, b []byte) (v []byte, n int) { + n = ConsumeFieldValue(num, StartGroupType, b) + if n < 0 { + return nil, n // forward error code + } + b = b[:n] + + // Truncate off end group marker, but need to handle denormalized varints. + // Assuming end marker is never 0 (which is always the case since + // EndGroupType is non-zero), we can truncate all trailing bytes where the + // lower 7 bits are all zero (implying that the varint is denormalized). + for len(b) > 0 && b[len(b)-1]&0x7f == 0 { + b = b[:len(b)-1] + } + b = b[:len(b)-SizeTag(num)] + return b, n +} + +// SizeGroup returns the encoded size of a group, given only the length. +func SizeGroup(num Number, n int) int { + return n + SizeTag(num) +} + +// DecodeTag decodes the field Number and wire Type from its unified form. +// The Number is -1 if the decoded field number overflows int32. +// Other than overflow, this does not check for field number validity. +func DecodeTag(x uint64) (Number, Type) { + // NOTE: MessageSet allows for larger field numbers than normal. + if x>>3 > uint64(math.MaxInt32) { + return -1, 0 + } + return Number(x >> 3), Type(x & 7) +} + +// EncodeTag encodes the field Number and wire Type into its unified form. +func EncodeTag(num Number, typ Type) uint64 { + return uint64(num)<<3 | uint64(typ&7) +} + +// DecodeZigZag decodes a zig-zag-encoded uint64 as an int64. +// Input: {…, 5, 3, 1, 0, 2, 4, 6, …} +// Output: {…, -3, -2, -1, 0, +1, +2, +3, …} +func DecodeZigZag(x uint64) int64 { + return int64(x>>1) ^ int64(x)<<63>>63 +} + +// EncodeZigZag encodes an int64 as a zig-zag-encoded uint64. +// Input: {…, -3, -2, -1, 0, +1, +2, +3, …} +// Output: {…, 5, 3, 1, 0, 2, 4, 6, …} +func EncodeZigZag(x int64) uint64 { + return uint64(x<<1) ^ uint64(x>>63) +} + +// DecodeBool decodes a uint64 as a bool. +// Input: { 0, 1, 2, …} +// Output: {false, true, true, …} +func DecodeBool(x uint64) bool { + return x != 0 +} + +// EncodeBool encodes a bool as a uint64. +// Input: {false, true} +// Output: { 0, 1} +func EncodeBool(x bool) uint64 { + if x { + return 1 + } + return 0 +} diff --git a/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go b/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go new file mode 100644 index 00000000000..e7af0fe0de2 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go @@ -0,0 +1,316 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package descfmt provides functionality to format descriptors. +package descfmt + +import ( + "fmt" + "io" + "reflect" + "strconv" + "strings" + + "google.golang.org/protobuf/internal/detrand" + "google.golang.org/protobuf/internal/pragma" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +type list interface { + Len() int + pragma.DoNotImplement +} + +func FormatList(s fmt.State, r rune, vs list) { + io.WriteString(s, formatListOpt(vs, true, r == 'v' && (s.Flag('+') || s.Flag('#')))) +} +func formatListOpt(vs list, isRoot, allowMulti bool) string { + start, end := "[", "]" + if isRoot { + var name string + switch vs.(type) { + case pref.Names: + name = "Names" + case pref.FieldNumbers: + name = "FieldNumbers" + case pref.FieldRanges: + name = "FieldRanges" + case pref.EnumRanges: + name = "EnumRanges" + case pref.FileImports: + name = "FileImports" + case pref.Descriptor: + name = reflect.ValueOf(vs).MethodByName("Get").Type().Out(0).Name() + "s" + } + start, end = name+"{", "}" + } + + var ss []string + switch vs := vs.(type) { + case pref.Names: + for i := 0; i < vs.Len(); i++ { + ss = append(ss, fmt.Sprint(vs.Get(i))) + } + return start + joinStrings(ss, false) + end + case pref.FieldNumbers: + for i := 0; i < vs.Len(); i++ { + ss = append(ss, fmt.Sprint(vs.Get(i))) + } + return start + joinStrings(ss, false) + end + case pref.FieldRanges: + for i := 0; i < vs.Len(); i++ { + r := vs.Get(i) + if r[0]+1 == r[1] { + ss = append(ss, fmt.Sprintf("%d", r[0])) + } else { + ss = append(ss, fmt.Sprintf("%d:%d", r[0], r[1])) // enum ranges are end exclusive + } + } + return start + joinStrings(ss, false) + end + case pref.EnumRanges: + for i := 0; i < vs.Len(); i++ { + r := vs.Get(i) + if r[0] == r[1] { + ss = append(ss, fmt.Sprintf("%d", r[0])) + } else { + ss = append(ss, fmt.Sprintf("%d:%d", r[0], int64(r[1])+1)) // enum ranges are end inclusive + } + } + return start + joinStrings(ss, false) + end + case pref.FileImports: + for i := 0; i < vs.Len(); i++ { + var rs records + rs.Append(reflect.ValueOf(vs.Get(i)), "Path", "Package", "IsPublic", "IsWeak") + ss = append(ss, "{"+rs.Join()+"}") + } + return start + joinStrings(ss, allowMulti) + end + default: + _, isEnumValue := vs.(pref.EnumValueDescriptors) + for i := 0; i < vs.Len(); i++ { + m := reflect.ValueOf(vs).MethodByName("Get") + v := m.Call([]reflect.Value{reflect.ValueOf(i)})[0].Interface() + ss = append(ss, formatDescOpt(v.(pref.Descriptor), false, allowMulti && !isEnumValue)) + } + return start + joinStrings(ss, allowMulti && isEnumValue) + end + } +} + +// descriptorAccessors is a list of accessors to print for each descriptor. +// +// Do not print all accessors since some contain redundant information, +// while others are pointers that we do not want to follow since the descriptor +// is actually a cyclic graph. +// +// Using a list allows us to print the accessors in a sensible order. +var descriptorAccessors = map[reflect.Type][]string{ + reflect.TypeOf((*pref.FileDescriptor)(nil)).Elem(): {"Path", "Package", "Imports", "Messages", "Enums", "Extensions", "Services"}, + reflect.TypeOf((*pref.MessageDescriptor)(nil)).Elem(): {"IsMapEntry", "Fields", "Oneofs", "ReservedNames", "ReservedRanges", "RequiredNumbers", "ExtensionRanges", "Messages", "Enums", "Extensions"}, + reflect.TypeOf((*pref.FieldDescriptor)(nil)).Elem(): {"Number", "Cardinality", "Kind", "HasJSONName", "JSONName", "HasPresence", "IsExtension", "IsPacked", "IsWeak", "IsList", "IsMap", "MapKey", "MapValue", "HasDefault", "Default", "ContainingOneof", "ContainingMessage", "Message", "Enum"}, + reflect.TypeOf((*pref.OneofDescriptor)(nil)).Elem(): {"Fields"}, // not directly used; must keep in sync with formatDescOpt + reflect.TypeOf((*pref.EnumDescriptor)(nil)).Elem(): {"Values", "ReservedNames", "ReservedRanges"}, + reflect.TypeOf((*pref.EnumValueDescriptor)(nil)).Elem(): {"Number"}, + reflect.TypeOf((*pref.ServiceDescriptor)(nil)).Elem(): {"Methods"}, + reflect.TypeOf((*pref.MethodDescriptor)(nil)).Elem(): {"Input", "Output", "IsStreamingClient", "IsStreamingServer"}, +} + +func FormatDesc(s fmt.State, r rune, t pref.Descriptor) { + io.WriteString(s, formatDescOpt(t, true, r == 'v' && (s.Flag('+') || s.Flag('#')))) +} +func formatDescOpt(t pref.Descriptor, isRoot, allowMulti bool) string { + rv := reflect.ValueOf(t) + rt := rv.MethodByName("ProtoType").Type().In(0) + + start, end := "{", "}" + if isRoot { + start = rt.Name() + "{" + } + + _, isFile := t.(pref.FileDescriptor) + rs := records{allowMulti: allowMulti} + if t.IsPlaceholder() { + if isFile { + rs.Append(rv, "Path", "Package", "IsPlaceholder") + } else { + rs.Append(rv, "FullName", "IsPlaceholder") + } + } else { + switch { + case isFile: + rs.Append(rv, "Syntax") + case isRoot: + rs.Append(rv, "Syntax", "FullName") + default: + rs.Append(rv, "Name") + } + switch t := t.(type) { + case pref.FieldDescriptor: + for _, s := range descriptorAccessors[rt] { + switch s { + case "MapKey": + if k := t.MapKey(); k != nil { + rs.recs = append(rs.recs, [2]string{"MapKey", k.Kind().String()}) + } + case "MapValue": + if v := t.MapValue(); v != nil { + switch v.Kind() { + case pref.EnumKind: + rs.recs = append(rs.recs, [2]string{"MapValue", string(v.Enum().FullName())}) + case pref.MessageKind, pref.GroupKind: + rs.recs = append(rs.recs, [2]string{"MapValue", string(v.Message().FullName())}) + default: + rs.recs = append(rs.recs, [2]string{"MapValue", v.Kind().String()}) + } + } + case "ContainingOneof": + if od := t.ContainingOneof(); od != nil { + rs.recs = append(rs.recs, [2]string{"Oneof", string(od.Name())}) + } + case "ContainingMessage": + if t.IsExtension() { + rs.recs = append(rs.recs, [2]string{"Extendee", string(t.ContainingMessage().FullName())}) + } + case "Message": + if !t.IsMap() { + rs.Append(rv, s) + } + default: + rs.Append(rv, s) + } + } + case pref.OneofDescriptor: + var ss []string + fs := t.Fields() + for i := 0; i < fs.Len(); i++ { + ss = append(ss, string(fs.Get(i).Name())) + } + if len(ss) > 0 { + rs.recs = append(rs.recs, [2]string{"Fields", "[" + joinStrings(ss, false) + "]"}) + } + default: + rs.Append(rv, descriptorAccessors[rt]...) + } + if rv.MethodByName("GoType").IsValid() { + rs.Append(rv, "GoType") + } + } + return start + rs.Join() + end +} + +type records struct { + recs [][2]string + allowMulti bool +} + +func (rs *records) Append(v reflect.Value, accessors ...string) { + for _, a := range accessors { + var rv reflect.Value + if m := v.MethodByName(a); m.IsValid() { + rv = m.Call(nil)[0] + } + if v.Kind() == reflect.Struct && !rv.IsValid() { + rv = v.FieldByName(a) + } + if !rv.IsValid() { + panic(fmt.Sprintf("unknown accessor: %v.%s", v.Type(), a)) + } + if _, ok := rv.Interface().(pref.Value); ok { + rv = rv.MethodByName("Interface").Call(nil)[0] + if !rv.IsNil() { + rv = rv.Elem() + } + } + + // Ignore zero values. + var isZero bool + switch rv.Kind() { + case reflect.Interface, reflect.Slice: + isZero = rv.IsNil() + case reflect.Bool: + isZero = rv.Bool() == false + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + isZero = rv.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + isZero = rv.Uint() == 0 + case reflect.String: + isZero = rv.String() == "" + } + if n, ok := rv.Interface().(list); ok { + isZero = n.Len() == 0 + } + if isZero { + continue + } + + // Format the value. + var s string + v := rv.Interface() + switch v := v.(type) { + case list: + s = formatListOpt(v, false, rs.allowMulti) + case pref.FieldDescriptor, pref.OneofDescriptor, pref.EnumValueDescriptor, pref.MethodDescriptor: + s = string(v.(pref.Descriptor).Name()) + case pref.Descriptor: + s = string(v.FullName()) + case string: + s = strconv.Quote(v) + case []byte: + s = fmt.Sprintf("%q", v) + default: + s = fmt.Sprint(v) + } + rs.recs = append(rs.recs, [2]string{a, s}) + } +} + +func (rs *records) Join() string { + var ss []string + + // In single line mode, simply join all records with commas. + if !rs.allowMulti { + for _, r := range rs.recs { + ss = append(ss, r[0]+formatColon(0)+r[1]) + } + return joinStrings(ss, false) + } + + // In allowMulti line mode, align single line records for more readable output. + var maxLen int + flush := func(i int) { + for _, r := range rs.recs[len(ss):i] { + ss = append(ss, r[0]+formatColon(maxLen-len(r[0]))+r[1]) + } + maxLen = 0 + } + for i, r := range rs.recs { + if isMulti := strings.Contains(r[1], "\n"); isMulti { + flush(i) + ss = append(ss, r[0]+formatColon(0)+strings.Join(strings.Split(r[1], "\n"), "\n\t")) + } else if maxLen < len(r[0]) { + maxLen = len(r[0]) + } + } + flush(len(rs.recs)) + return joinStrings(ss, true) +} + +func formatColon(padding int) string { + // Deliberately introduce instability into the debug output to + // discourage users from performing string comparisons. + // This provides us flexibility to change the output in the future. + if detrand.Bool() { + return ":" + strings.Repeat(" ", 1+padding) // use non-breaking spaces (U+00a0) + } else { + return ":" + strings.Repeat(" ", 1+padding) // use regular spaces (U+0020) + } +} + +func joinStrings(ss []string, isMulti bool) string { + if len(ss) == 0 { + return "" + } + if isMulti { + return "\n\t" + strings.Join(ss, "\n\t") + "\n" + } + return strings.Join(ss, ", ") +} diff --git a/vendor/google.golang.org/protobuf/internal/descopts/options.go b/vendor/google.golang.org/protobuf/internal/descopts/options.go new file mode 100644 index 00000000000..8401be8c84f --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/descopts/options.go @@ -0,0 +1,29 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package descopts contains the nil pointers to concrete descriptor options. +// +// This package exists as a form of reverse dependency injection so that certain +// packages (e.g., internal/filedesc and internal/filetype can avoid a direct +// dependency on the descriptor proto package). +package descopts + +import pref "google.golang.org/protobuf/reflect/protoreflect" + +// These variables are set by the init function in descriptor.pb.go via logic +// in internal/filetype. In other words, so long as the descriptor proto package +// is linked in, these variables will be populated. +// +// Each variable is populated with a nil pointer to the options struct. +var ( + File pref.ProtoMessage + Enum pref.ProtoMessage + EnumValue pref.ProtoMessage + Message pref.ProtoMessage + Field pref.ProtoMessage + Oneof pref.ProtoMessage + ExtensionRange pref.ProtoMessage + Service pref.ProtoMessage + Method pref.ProtoMessage +) diff --git a/vendor/google.golang.org/protobuf/internal/detrand/rand.go b/vendor/google.golang.org/protobuf/internal/detrand/rand.go new file mode 100644 index 00000000000..a904dd1f91a --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/detrand/rand.go @@ -0,0 +1,61 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package detrand provides deterministically random functionality. +// +// The pseudo-randomness of these functions is seeded by the program binary +// itself and guarantees that the output does not change within a program, +// while ensuring that the output is unstable across different builds. +package detrand + +import ( + "encoding/binary" + "hash/fnv" + "os" +) + +// Disable disables detrand such that all functions returns the zero value. +// This function is not concurrent-safe and must be called during program init. +func Disable() { + randSeed = 0 +} + +// Bool returns a deterministically random boolean. +func Bool() bool { + return randSeed%2 == 1 +} + +// randSeed is a best-effort at an approximate hash of the Go binary. +var randSeed = binaryHash() + +func binaryHash() uint64 { + // Open the Go binary. + s, err := os.Executable() + if err != nil { + return 0 + } + f, err := os.Open(s) + if err != nil { + return 0 + } + defer f.Close() + + // Hash the size and several samples of the Go binary. + const numSamples = 8 + var buf [64]byte + h := fnv.New64() + fi, err := f.Stat() + if err != nil { + return 0 + } + binary.LittleEndian.PutUint64(buf[:8], uint64(fi.Size())) + h.Write(buf[:8]) + for i := int64(0); i < numSamples; i++ { + if _, err := f.ReadAt(buf[:], i*fi.Size()/numSamples); err != nil { + return 0 + } + h.Write(buf[:]) + } + return h.Sum64() +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/defval/default.go b/vendor/google.golang.org/protobuf/internal/encoding/defval/default.go new file mode 100644 index 00000000000..fdd9b13f2fc --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/defval/default.go @@ -0,0 +1,213 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package defval marshals and unmarshals textual forms of default values. +// +// This package handles both the form historically used in Go struct field tags +// and also the form used by google.protobuf.FieldDescriptorProto.default_value +// since they differ in superficial ways. +package defval + +import ( + "fmt" + "math" + "strconv" + + ptext "google.golang.org/protobuf/internal/encoding/text" + errors "google.golang.org/protobuf/internal/errors" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +// Format is the serialization format used to represent the default value. +type Format int + +const ( + _ Format = iota + + // Descriptor uses the serialization format that protoc uses with the + // google.protobuf.FieldDescriptorProto.default_value field. + Descriptor + + // GoTag uses the historical serialization format in Go struct field tags. + GoTag +) + +// Unmarshal deserializes the default string s according to the given kind k. +// When k is an enum, a list of enum value descriptors must be provided. +func Unmarshal(s string, k pref.Kind, evs pref.EnumValueDescriptors, f Format) (pref.Value, pref.EnumValueDescriptor, error) { + switch k { + case pref.BoolKind: + if f == GoTag { + switch s { + case "1": + return pref.ValueOfBool(true), nil, nil + case "0": + return pref.ValueOfBool(false), nil, nil + } + } else { + switch s { + case "true": + return pref.ValueOfBool(true), nil, nil + case "false": + return pref.ValueOfBool(false), nil, nil + } + } + case pref.EnumKind: + if f == GoTag { + // Go tags use the numeric form of the enum value. + if n, err := strconv.ParseInt(s, 10, 32); err == nil { + if ev := evs.ByNumber(pref.EnumNumber(n)); ev != nil { + return pref.ValueOfEnum(ev.Number()), ev, nil + } + } + } else { + // Descriptor default_value use the enum identifier. + ev := evs.ByName(pref.Name(s)) + if ev != nil { + return pref.ValueOfEnum(ev.Number()), ev, nil + } + } + case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind: + if v, err := strconv.ParseInt(s, 10, 32); err == nil { + return pref.ValueOfInt32(int32(v)), nil, nil + } + case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind: + if v, err := strconv.ParseInt(s, 10, 64); err == nil { + return pref.ValueOfInt64(int64(v)), nil, nil + } + case pref.Uint32Kind, pref.Fixed32Kind: + if v, err := strconv.ParseUint(s, 10, 32); err == nil { + return pref.ValueOfUint32(uint32(v)), nil, nil + } + case pref.Uint64Kind, pref.Fixed64Kind: + if v, err := strconv.ParseUint(s, 10, 64); err == nil { + return pref.ValueOfUint64(uint64(v)), nil, nil + } + case pref.FloatKind, pref.DoubleKind: + var v float64 + var err error + switch s { + case "-inf": + v = math.Inf(-1) + case "inf": + v = math.Inf(+1) + case "nan": + v = math.NaN() + default: + v, err = strconv.ParseFloat(s, 64) + } + if err == nil { + if k == pref.FloatKind { + return pref.ValueOfFloat32(float32(v)), nil, nil + } else { + return pref.ValueOfFloat64(float64(v)), nil, nil + } + } + case pref.StringKind: + // String values are already unescaped and can be used as is. + return pref.ValueOfString(s), nil, nil + case pref.BytesKind: + if b, ok := unmarshalBytes(s); ok { + return pref.ValueOfBytes(b), nil, nil + } + } + return pref.Value{}, nil, errors.New("could not parse value for %v: %q", k, s) +} + +// Marshal serializes v as the default string according to the given kind k. +// When specifying the Descriptor format for an enum kind, the associated +// enum value descriptor must be provided. +func Marshal(v pref.Value, ev pref.EnumValueDescriptor, k pref.Kind, f Format) (string, error) { + switch k { + case pref.BoolKind: + if f == GoTag { + if v.Bool() { + return "1", nil + } else { + return "0", nil + } + } else { + if v.Bool() { + return "true", nil + } else { + return "false", nil + } + } + case pref.EnumKind: + if f == GoTag { + return strconv.FormatInt(int64(v.Enum()), 10), nil + } else { + return string(ev.Name()), nil + } + case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind, pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind: + return strconv.FormatInt(v.Int(), 10), nil + case pref.Uint32Kind, pref.Fixed32Kind, pref.Uint64Kind, pref.Fixed64Kind: + return strconv.FormatUint(v.Uint(), 10), nil + case pref.FloatKind, pref.DoubleKind: + f := v.Float() + switch { + case math.IsInf(f, -1): + return "-inf", nil + case math.IsInf(f, +1): + return "inf", nil + case math.IsNaN(f): + return "nan", nil + default: + if k == pref.FloatKind { + return strconv.FormatFloat(f, 'g', -1, 32), nil + } else { + return strconv.FormatFloat(f, 'g', -1, 64), nil + } + } + case pref.StringKind: + // String values are serialized as is without any escaping. + return v.String(), nil + case pref.BytesKind: + if s, ok := marshalBytes(v.Bytes()); ok { + return s, nil + } + } + return "", errors.New("could not format value for %v: %v", k, v) +} + +// unmarshalBytes deserializes bytes by applying C unescaping. +func unmarshalBytes(s string) ([]byte, bool) { + // Bytes values use the same escaping as the text format, + // however they lack the surrounding double quotes. + v, err := ptext.UnmarshalString(`"` + s + `"`) + if err != nil { + return nil, false + } + return []byte(v), true +} + +// marshalBytes serializes bytes by using C escaping. +// To match the exact output of protoc, this is identical to the +// CEscape function in strutil.cc of the protoc source code. +func marshalBytes(b []byte) (string, bool) { + var s []byte + for _, c := range b { + switch c { + case '\n': + s = append(s, `\n`...) + case '\r': + s = append(s, `\r`...) + case '\t': + s = append(s, `\t`...) + case '"': + s = append(s, `\"`...) + case '\'': + s = append(s, `\'`...) + case '\\': + s = append(s, `\\`...) + default: + if printableASCII := c >= 0x20 && c <= 0x7e; printableASCII { + s = append(s, c) + } else { + s = append(s, fmt.Sprintf(`\%03o`, c)...) + } + } + } + return string(s), true +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/messageset/messageset.go b/vendor/google.golang.org/protobuf/internal/encoding/messageset/messageset.go new file mode 100644 index 00000000000..b1eeea50797 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/messageset/messageset.go @@ -0,0 +1,258 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package messageset encodes and decodes the obsolete MessageSet wire format. +package messageset + +import ( + "math" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/errors" + pref "google.golang.org/protobuf/reflect/protoreflect" + preg "google.golang.org/protobuf/reflect/protoregistry" +) + +// The MessageSet wire format is equivalent to a message defiend as follows, +// where each Item defines an extension field with a field number of 'type_id' +// and content of 'message'. MessageSet extensions must be non-repeated message +// fields. +// +// message MessageSet { +// repeated group Item = 1 { +// required int32 type_id = 2; +// required string message = 3; +// } +// } +const ( + FieldItem = protowire.Number(1) + FieldTypeID = protowire.Number(2) + FieldMessage = protowire.Number(3) +) + +// ExtensionName is the field name for extensions of MessageSet. +// +// A valid MessageSet extension must be of the form: +// message MyMessage { +// extend proto2.bridge.MessageSet { +// optional MyMessage message_set_extension = 1234; +// } +// ... +// } +const ExtensionName = "message_set_extension" + +// IsMessageSet returns whether the message uses the MessageSet wire format. +func IsMessageSet(md pref.MessageDescriptor) bool { + xmd, ok := md.(interface{ IsMessageSet() bool }) + return ok && xmd.IsMessageSet() +} + +// IsMessageSetExtension reports this field extends a MessageSet. +func IsMessageSetExtension(fd pref.FieldDescriptor) bool { + if fd.Name() != ExtensionName { + return false + } + if fd.FullName().Parent() != fd.Message().FullName() { + return false + } + return IsMessageSet(fd.ContainingMessage()) +} + +// FindMessageSetExtension locates a MessageSet extension field by name. +// In text and JSON formats, the extension name used is the message itself. +// The extension field name is derived by appending ExtensionName. +func FindMessageSetExtension(r preg.ExtensionTypeResolver, s pref.FullName) (pref.ExtensionType, error) { + name := s.Append(ExtensionName) + xt, err := r.FindExtensionByName(name) + if err != nil { + if err == preg.NotFound { + return nil, err + } + return nil, errors.Wrap(err, "%q", name) + } + if !IsMessageSetExtension(xt.TypeDescriptor()) { + return nil, preg.NotFound + } + return xt, nil +} + +// SizeField returns the size of a MessageSet item field containing an extension +// with the given field number, not counting the contents of the message subfield. +func SizeField(num protowire.Number) int { + return 2*protowire.SizeTag(FieldItem) + protowire.SizeTag(FieldTypeID) + protowire.SizeVarint(uint64(num)) +} + +// Unmarshal parses a MessageSet. +// +// It calls fn with the type ID and value of each item in the MessageSet. +// Unknown fields are discarded. +// +// If wantLen is true, the item values include the varint length prefix. +// This is ugly, but simplifies the fast-path decoder in internal/impl. +func Unmarshal(b []byte, wantLen bool, fn func(typeID protowire.Number, value []byte) error) error { + for len(b) > 0 { + num, wtyp, n := protowire.ConsumeTag(b) + if n < 0 { + return protowire.ParseError(n) + } + b = b[n:] + if num != FieldItem || wtyp != protowire.StartGroupType { + n := protowire.ConsumeFieldValue(num, wtyp, b) + if n < 0 { + return protowire.ParseError(n) + } + b = b[n:] + continue + } + typeID, value, n, err := ConsumeFieldValue(b, wantLen) + if err != nil { + return err + } + b = b[n:] + if typeID == 0 { + continue + } + if err := fn(typeID, value); err != nil { + return err + } + } + return nil +} + +// ConsumeFieldValue parses b as a MessageSet item field value until and including +// the trailing end group marker. It assumes the start group tag has already been parsed. +// It returns the contents of the type_id and message subfields and the total +// item length. +// +// If wantLen is true, the returned message value includes the length prefix. +func ConsumeFieldValue(b []byte, wantLen bool) (typeid protowire.Number, message []byte, n int, err error) { + ilen := len(b) + for { + num, wtyp, n := protowire.ConsumeTag(b) + if n < 0 { + return 0, nil, 0, protowire.ParseError(n) + } + b = b[n:] + switch { + case num == FieldItem && wtyp == protowire.EndGroupType: + if wantLen && len(message) == 0 { + // The message field was missing, which should never happen. + // Be prepared for this case anyway. + message = protowire.AppendVarint(message, 0) + } + return typeid, message, ilen - len(b), nil + case num == FieldTypeID && wtyp == protowire.VarintType: + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return 0, nil, 0, protowire.ParseError(n) + } + b = b[n:] + if v < 1 || v > math.MaxInt32 { + return 0, nil, 0, errors.New("invalid type_id in message set") + } + typeid = protowire.Number(v) + case num == FieldMessage && wtyp == protowire.BytesType: + m, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, nil, 0, protowire.ParseError(n) + } + if message == nil { + if wantLen { + message = b[:n:n] + } else { + message = m[:len(m):len(m)] + } + } else { + // This case should never happen in practice, but handle it for + // correctness: The MessageSet item contains multiple message + // fields, which need to be merged. + // + // In the case where we're returning the length, this becomes + // quite inefficient since we need to strip the length off + // the existing data and reconstruct it with the combined length. + if wantLen { + _, nn := protowire.ConsumeVarint(message) + m0 := message[nn:] + message = nil + message = protowire.AppendVarint(message, uint64(len(m0)+len(m))) + message = append(message, m0...) + message = append(message, m...) + } else { + message = append(message, m...) + } + } + b = b[n:] + default: + // We have no place to put it, so we just ignore unknown fields. + n := protowire.ConsumeFieldValue(num, wtyp, b) + if n < 0 { + return 0, nil, 0, protowire.ParseError(n) + } + b = b[n:] + } + } +} + +// AppendFieldStart appends the start of a MessageSet item field containing +// an extension with the given number. The caller must add the message +// subfield (including the tag). +func AppendFieldStart(b []byte, num protowire.Number) []byte { + b = protowire.AppendTag(b, FieldItem, protowire.StartGroupType) + b = protowire.AppendTag(b, FieldTypeID, protowire.VarintType) + b = protowire.AppendVarint(b, uint64(num)) + return b +} + +// AppendFieldEnd appends the trailing end group marker for a MessageSet item field. +func AppendFieldEnd(b []byte) []byte { + return protowire.AppendTag(b, FieldItem, protowire.EndGroupType) +} + +// SizeUnknown returns the size of an unknown fields section in MessageSet format. +// +// See AppendUnknown. +func SizeUnknown(unknown []byte) (size int) { + for len(unknown) > 0 { + num, typ, n := protowire.ConsumeTag(unknown) + if n < 0 || typ != protowire.BytesType { + return 0 + } + unknown = unknown[n:] + _, n = protowire.ConsumeBytes(unknown) + if n < 0 { + return 0 + } + unknown = unknown[n:] + size += SizeField(num) + protowire.SizeTag(FieldMessage) + n + } + return size +} + +// AppendUnknown appends unknown fields to b in MessageSet format. +// +// For historic reasons, unresolved items in a MessageSet are stored in a +// message's unknown fields section in non-MessageSet format. That is, an +// unknown item with typeID T and value V appears in the unknown fields as +// a field with number T and value V. +// +// This function converts the unknown fields back into MessageSet form. +func AppendUnknown(b, unknown []byte) ([]byte, error) { + for len(unknown) > 0 { + num, typ, n := protowire.ConsumeTag(unknown) + if n < 0 || typ != protowire.BytesType { + return nil, errors.New("invalid data in message set unknown fields") + } + unknown = unknown[n:] + _, n = protowire.ConsumeBytes(unknown) + if n < 0 { + return nil, errors.New("invalid data in message set unknown fields") + } + b = AppendFieldStart(b, num) + b = protowire.AppendTag(b, FieldMessage, protowire.BytesType) + b = append(b, unknown[:n]...) + b = AppendFieldEnd(b) + unknown = unknown[n:] + } + return b, nil +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/tag/tag.go b/vendor/google.golang.org/protobuf/internal/encoding/tag/tag.go new file mode 100644 index 00000000000..16c02d7b627 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/tag/tag.go @@ -0,0 +1,207 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package tag marshals and unmarshals the legacy struct tags as generated +// by historical versions of protoc-gen-go. +package tag + +import ( + "reflect" + "strconv" + "strings" + + defval "google.golang.org/protobuf/internal/encoding/defval" + fdesc "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/internal/strs" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +var byteType = reflect.TypeOf(byte(0)) + +// Unmarshal decodes the tag into a prototype.Field. +// +// The goType is needed to determine the original protoreflect.Kind since the +// tag does not record sufficient information to determine that. +// The type is the underlying field type (e.g., a repeated field may be +// represented by []T, but the Go type passed in is just T). +// A list of enum value descriptors must be provided for enum fields. +// This does not populate the Enum or Message (except for weak message). +// +// This function is a best effort attempt; parsing errors are ignored. +func Unmarshal(tag string, goType reflect.Type, evs pref.EnumValueDescriptors) pref.FieldDescriptor { + f := new(fdesc.Field) + f.L0.ParentFile = fdesc.SurrogateProto2 + for len(tag) > 0 { + i := strings.IndexByte(tag, ',') + if i < 0 { + i = len(tag) + } + switch s := tag[:i]; { + case strings.HasPrefix(s, "name="): + f.L0.FullName = pref.FullName(s[len("name="):]) + case strings.Trim(s, "0123456789") == "": + n, _ := strconv.ParseUint(s, 10, 32) + f.L1.Number = pref.FieldNumber(n) + case s == "opt": + f.L1.Cardinality = pref.Optional + case s == "req": + f.L1.Cardinality = pref.Required + case s == "rep": + f.L1.Cardinality = pref.Repeated + case s == "varint": + switch goType.Kind() { + case reflect.Bool: + f.L1.Kind = pref.BoolKind + case reflect.Int32: + f.L1.Kind = pref.Int32Kind + case reflect.Int64: + f.L1.Kind = pref.Int64Kind + case reflect.Uint32: + f.L1.Kind = pref.Uint32Kind + case reflect.Uint64: + f.L1.Kind = pref.Uint64Kind + } + case s == "zigzag32": + if goType.Kind() == reflect.Int32 { + f.L1.Kind = pref.Sint32Kind + } + case s == "zigzag64": + if goType.Kind() == reflect.Int64 { + f.L1.Kind = pref.Sint64Kind + } + case s == "fixed32": + switch goType.Kind() { + case reflect.Int32: + f.L1.Kind = pref.Sfixed32Kind + case reflect.Uint32: + f.L1.Kind = pref.Fixed32Kind + case reflect.Float32: + f.L1.Kind = pref.FloatKind + } + case s == "fixed64": + switch goType.Kind() { + case reflect.Int64: + f.L1.Kind = pref.Sfixed64Kind + case reflect.Uint64: + f.L1.Kind = pref.Fixed64Kind + case reflect.Float64: + f.L1.Kind = pref.DoubleKind + } + case s == "bytes": + switch { + case goType.Kind() == reflect.String: + f.L1.Kind = pref.StringKind + case goType.Kind() == reflect.Slice && goType.Elem() == byteType: + f.L1.Kind = pref.BytesKind + default: + f.L1.Kind = pref.MessageKind + } + case s == "group": + f.L1.Kind = pref.GroupKind + case strings.HasPrefix(s, "enum="): + f.L1.Kind = pref.EnumKind + case strings.HasPrefix(s, "json="): + jsonName := s[len("json="):] + if jsonName != strs.JSONCamelCase(string(f.L0.FullName.Name())) { + f.L1.JSONName.Init(jsonName) + } + case s == "packed": + f.L1.HasPacked = true + f.L1.IsPacked = true + case strings.HasPrefix(s, "weak="): + f.L1.IsWeak = true + f.L1.Message = fdesc.PlaceholderMessage(pref.FullName(s[len("weak="):])) + case strings.HasPrefix(s, "def="): + // The default tag is special in that everything afterwards is the + // default regardless of the presence of commas. + s, i = tag[len("def="):], len(tag) + v, ev, _ := defval.Unmarshal(s, f.L1.Kind, evs, defval.GoTag) + f.L1.Default = fdesc.DefaultValue(v, ev) + case s == "proto3": + f.L0.ParentFile = fdesc.SurrogateProto3 + } + tag = strings.TrimPrefix(tag[i:], ",") + } + + // The generator uses the group message name instead of the field name. + // We obtain the real field name by lowercasing the group name. + if f.L1.Kind == pref.GroupKind { + f.L0.FullName = pref.FullName(strings.ToLower(string(f.L0.FullName))) + } + return f +} + +// Marshal encodes the protoreflect.FieldDescriptor as a tag. +// +// The enumName must be provided if the kind is an enum. +// Historically, the formulation of the enum "name" was the proto package +// dot-concatenated with the generated Go identifier for the enum type. +// Depending on the context on how Marshal is called, there are different ways +// through which that information is determined. As such it is the caller's +// responsibility to provide a function to obtain that information. +func Marshal(fd pref.FieldDescriptor, enumName string) string { + var tag []string + switch fd.Kind() { + case pref.BoolKind, pref.EnumKind, pref.Int32Kind, pref.Uint32Kind, pref.Int64Kind, pref.Uint64Kind: + tag = append(tag, "varint") + case pref.Sint32Kind: + tag = append(tag, "zigzag32") + case pref.Sint64Kind: + tag = append(tag, "zigzag64") + case pref.Sfixed32Kind, pref.Fixed32Kind, pref.FloatKind: + tag = append(tag, "fixed32") + case pref.Sfixed64Kind, pref.Fixed64Kind, pref.DoubleKind: + tag = append(tag, "fixed64") + case pref.StringKind, pref.BytesKind, pref.MessageKind: + tag = append(tag, "bytes") + case pref.GroupKind: + tag = append(tag, "group") + } + tag = append(tag, strconv.Itoa(int(fd.Number()))) + switch fd.Cardinality() { + case pref.Optional: + tag = append(tag, "opt") + case pref.Required: + tag = append(tag, "req") + case pref.Repeated: + tag = append(tag, "rep") + } + if fd.IsPacked() { + tag = append(tag, "packed") + } + name := string(fd.Name()) + if fd.Kind() == pref.GroupKind { + // The name of the FieldDescriptor for a group field is + // lowercased. To find the original capitalization, we + // look in the field's MessageType. + name = string(fd.Message().Name()) + } + tag = append(tag, "name="+name) + if jsonName := fd.JSONName(); jsonName != "" && jsonName != name && !fd.IsExtension() { + // NOTE: The jsonName != name condition is suspect, but it preserve + // the exact same semantics from the previous generator. + tag = append(tag, "json="+jsonName) + } + if fd.IsWeak() { + tag = append(tag, "weak="+string(fd.Message().FullName())) + } + // The previous implementation does not tag extension fields as proto3, + // even when the field is defined in a proto3 file. Match that behavior + // for consistency. + if fd.Syntax() == pref.Proto3 && !fd.IsExtension() { + tag = append(tag, "proto3") + } + if fd.Kind() == pref.EnumKind && enumName != "" { + tag = append(tag, "enum="+enumName) + } + if fd.ContainingOneof() != nil { + tag = append(tag, "oneof") + } + // This must appear last in the tag, since commas in strings aren't escaped. + if fd.HasDefault() { + def, _ := defval.Marshal(fd.Default(), fd.DefaultEnumValue(), fd.Kind(), defval.GoTag) + tag = append(tag, "def="+def) + } + return strings.Join(tag, ",") +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/text/decode.go b/vendor/google.golang.org/protobuf/internal/encoding/text/decode.go new file mode 100644 index 00000000000..eb10ea10261 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/text/decode.go @@ -0,0 +1,665 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package text + +import ( + "bytes" + "fmt" + "io" + "regexp" + "strconv" + "unicode/utf8" + + "google.golang.org/protobuf/internal/errors" +) + +// Decoder is a token-based textproto decoder. +type Decoder struct { + // lastCall is last method called, either readCall or peekCall. + // Initial value is readCall. + lastCall call + + // lastToken contains the last read token. + lastToken Token + + // lastErr contains the last read error. + lastErr error + + // openStack is a stack containing the byte characters for MessageOpen and + // ListOpen kinds. The top of stack represents the message or the list that + // the current token is nested in. An empty stack means the current token is + // at the top level message. The characters '{' and '<' both represent the + // MessageOpen kind. + openStack []byte + + // orig is used in reporting line and column. + orig []byte + // in contains the unconsumed input. + in []byte +} + +// NewDecoder returns a Decoder to read the given []byte. +func NewDecoder(b []byte) *Decoder { + return &Decoder{orig: b, in: b} +} + +// ErrUnexpectedEOF means that EOF was encountered in the middle of the input. +var ErrUnexpectedEOF = errors.New("%v", io.ErrUnexpectedEOF) + +// call specifies which Decoder method was invoked. +type call uint8 + +const ( + readCall call = iota + peekCall +) + +// Peek looks ahead and returns the next token and error without advancing a read. +func (d *Decoder) Peek() (Token, error) { + defer func() { d.lastCall = peekCall }() + if d.lastCall == readCall { + d.lastToken, d.lastErr = d.Read() + } + return d.lastToken, d.lastErr +} + +// Read returns the next token. +// It will return an error if there is no valid token. +func (d *Decoder) Read() (Token, error) { + defer func() { d.lastCall = readCall }() + if d.lastCall == peekCall { + return d.lastToken, d.lastErr + } + + tok, err := d.parseNext(d.lastToken.kind) + if err != nil { + return Token{}, err + } + + switch tok.kind { + case comma, semicolon: + tok, err = d.parseNext(tok.kind) + if err != nil { + return Token{}, err + } + } + d.lastToken = tok + return tok, nil +} + +const ( + mismatchedFmt = "mismatched close character %q" + unexpectedFmt = "unexpected character %q" +) + +// parseNext parses the next Token based on given last kind. +func (d *Decoder) parseNext(lastKind Kind) (Token, error) { + // Trim leading spaces. + d.consume(0) + isEOF := false + if len(d.in) == 0 { + isEOF = true + } + + switch lastKind { + case EOF: + return d.consumeToken(EOF, 0, 0), nil + + case bof: + // Start of top level message. Next token can be EOF or Name. + if isEOF { + return d.consumeToken(EOF, 0, 0), nil + } + return d.parseFieldName() + + case Name: + // Next token can be MessageOpen, ListOpen or Scalar. + if isEOF { + return Token{}, ErrUnexpectedEOF + } + switch ch := d.in[0]; ch { + case '{', '<': + d.pushOpenStack(ch) + return d.consumeToken(MessageOpen, 1, 0), nil + case '[': + d.pushOpenStack(ch) + return d.consumeToken(ListOpen, 1, 0), nil + default: + return d.parseScalar() + } + + case Scalar: + openKind, closeCh := d.currentOpenKind() + switch openKind { + case bof: + // Top level message. + // Next token can be EOF, comma, semicolon or Name. + if isEOF { + return d.consumeToken(EOF, 0, 0), nil + } + switch d.in[0] { + case ',': + return d.consumeToken(comma, 1, 0), nil + case ';': + return d.consumeToken(semicolon, 1, 0), nil + default: + return d.parseFieldName() + } + + case MessageOpen: + // Next token can be MessageClose, comma, semicolon or Name. + if isEOF { + return Token{}, ErrUnexpectedEOF + } + switch ch := d.in[0]; ch { + case closeCh: + d.popOpenStack() + return d.consumeToken(MessageClose, 1, 0), nil + case otherCloseChar[closeCh]: + return Token{}, d.newSyntaxError(mismatchedFmt, ch) + case ',': + return d.consumeToken(comma, 1, 0), nil + case ';': + return d.consumeToken(semicolon, 1, 0), nil + default: + return d.parseFieldName() + } + + case ListOpen: + // Next token can be ListClose or comma. + if isEOF { + return Token{}, ErrUnexpectedEOF + } + switch ch := d.in[0]; ch { + case ']': + d.popOpenStack() + return d.consumeToken(ListClose, 1, 0), nil + case ',': + return d.consumeToken(comma, 1, 0), nil + default: + return Token{}, d.newSyntaxError(unexpectedFmt, ch) + } + } + + case MessageOpen: + // Next token can be MessageClose or Name. + if isEOF { + return Token{}, ErrUnexpectedEOF + } + _, closeCh := d.currentOpenKind() + switch ch := d.in[0]; ch { + case closeCh: + d.popOpenStack() + return d.consumeToken(MessageClose, 1, 0), nil + case otherCloseChar[closeCh]: + return Token{}, d.newSyntaxError(mismatchedFmt, ch) + default: + return d.parseFieldName() + } + + case MessageClose: + openKind, closeCh := d.currentOpenKind() + switch openKind { + case bof: + // Top level message. + // Next token can be EOF, comma, semicolon or Name. + if isEOF { + return d.consumeToken(EOF, 0, 0), nil + } + switch ch := d.in[0]; ch { + case ',': + return d.consumeToken(comma, 1, 0), nil + case ';': + return d.consumeToken(semicolon, 1, 0), nil + default: + return d.parseFieldName() + } + + case MessageOpen: + // Next token can be MessageClose, comma, semicolon or Name. + if isEOF { + return Token{}, ErrUnexpectedEOF + } + switch ch := d.in[0]; ch { + case closeCh: + d.popOpenStack() + return d.consumeToken(MessageClose, 1, 0), nil + case otherCloseChar[closeCh]: + return Token{}, d.newSyntaxError(mismatchedFmt, ch) + case ',': + return d.consumeToken(comma, 1, 0), nil + case ';': + return d.consumeToken(semicolon, 1, 0), nil + default: + return d.parseFieldName() + } + + case ListOpen: + // Next token can be ListClose or comma + if isEOF { + return Token{}, ErrUnexpectedEOF + } + switch ch := d.in[0]; ch { + case closeCh: + d.popOpenStack() + return d.consumeToken(ListClose, 1, 0), nil + case ',': + return d.consumeToken(comma, 1, 0), nil + default: + return Token{}, d.newSyntaxError(unexpectedFmt, ch) + } + } + + case ListOpen: + // Next token can be ListClose, MessageStart or Scalar. + if isEOF { + return Token{}, ErrUnexpectedEOF + } + switch ch := d.in[0]; ch { + case ']': + d.popOpenStack() + return d.consumeToken(ListClose, 1, 0), nil + case '{', '<': + d.pushOpenStack(ch) + return d.consumeToken(MessageOpen, 1, 0), nil + default: + return d.parseScalar() + } + + case ListClose: + openKind, closeCh := d.currentOpenKind() + switch openKind { + case bof: + // Top level message. + // Next token can be EOF, comma, semicolon or Name. + if isEOF { + return d.consumeToken(EOF, 0, 0), nil + } + switch ch := d.in[0]; ch { + case ',': + return d.consumeToken(comma, 1, 0), nil + case ';': + return d.consumeToken(semicolon, 1, 0), nil + default: + return d.parseFieldName() + } + + case MessageOpen: + // Next token can be MessageClose, comma, semicolon or Name. + if isEOF { + return Token{}, ErrUnexpectedEOF + } + switch ch := d.in[0]; ch { + case closeCh: + d.popOpenStack() + return d.consumeToken(MessageClose, 1, 0), nil + case otherCloseChar[closeCh]: + return Token{}, d.newSyntaxError(mismatchedFmt, ch) + case ',': + return d.consumeToken(comma, 1, 0), nil + case ';': + return d.consumeToken(semicolon, 1, 0), nil + default: + return d.parseFieldName() + } + + default: + // It is not possible to have this case. Let it panic below. + } + + case comma, semicolon: + openKind, closeCh := d.currentOpenKind() + switch openKind { + case bof: + // Top level message. Next token can be EOF or Name. + if isEOF { + return d.consumeToken(EOF, 0, 0), nil + } + return d.parseFieldName() + + case MessageOpen: + // Next token can be MessageClose or Name. + if isEOF { + return Token{}, ErrUnexpectedEOF + } + switch ch := d.in[0]; ch { + case closeCh: + d.popOpenStack() + return d.consumeToken(MessageClose, 1, 0), nil + case otherCloseChar[closeCh]: + return Token{}, d.newSyntaxError(mismatchedFmt, ch) + default: + return d.parseFieldName() + } + + case ListOpen: + if lastKind == semicolon { + // It is not be possible to have this case as logic here + // should not have produced a semicolon Token when inside a + // list. Let it panic below. + break + } + // Next token can be MessageOpen or Scalar. + if isEOF { + return Token{}, ErrUnexpectedEOF + } + switch ch := d.in[0]; ch { + case '{', '<': + d.pushOpenStack(ch) + return d.consumeToken(MessageOpen, 1, 0), nil + default: + return d.parseScalar() + } + } + } + + line, column := d.Position(len(d.orig) - len(d.in)) + panic(fmt.Sprintf("Decoder.parseNext: bug at handling line %d:%d with lastKind=%v", line, column, lastKind)) +} + +var otherCloseChar = map[byte]byte{ + '}': '>', + '>': '}', +} + +// currentOpenKind indicates whether current position is inside a message, list +// or top-level message by returning MessageOpen, ListOpen or bof respectively. +// If the returned kind is either a MessageOpen or ListOpen, it also returns the +// corresponding closing character. +func (d *Decoder) currentOpenKind() (Kind, byte) { + if len(d.openStack) == 0 { + return bof, 0 + } + openCh := d.openStack[len(d.openStack)-1] + switch openCh { + case '{': + return MessageOpen, '}' + case '<': + return MessageOpen, '>' + case '[': + return ListOpen, ']' + } + panic(fmt.Sprintf("Decoder: openStack contains invalid byte %s", string(openCh))) +} + +func (d *Decoder) pushOpenStack(ch byte) { + d.openStack = append(d.openStack, ch) +} + +func (d *Decoder) popOpenStack() { + d.openStack = d.openStack[:len(d.openStack)-1] +} + +// parseFieldName parses field name and separator. +func (d *Decoder) parseFieldName() (tok Token, err error) { + defer func() { + if err == nil && d.tryConsumeChar(':') { + tok.attrs |= hasSeparator + } + }() + + // Extension or Any type URL. + if d.in[0] == '[' { + return d.parseTypeName() + } + + // Identifier. + if size := parseIdent(d.in, false); size > 0 { + return d.consumeToken(Name, size, uint8(IdentName)), nil + } + + // Field number. Identify if input is a valid number that is not negative + // and is decimal integer within 32-bit range. + if num := parseNumber(d.in); num.size > 0 { + if !num.neg && num.kind == numDec { + if _, err := strconv.ParseInt(string(d.in[:num.size]), 10, 32); err == nil { + return d.consumeToken(Name, num.size, uint8(FieldNumber)), nil + } + } + return Token{}, d.newSyntaxError("invalid field number: %s", d.in[:num.size]) + } + + return Token{}, d.newSyntaxError("invalid field name: %s", errRegexp.Find(d.in)) +} + +// parseTypeName parses Any type URL or extension field name. The name is +// enclosed in [ and ] characters. The C++ parser does not handle many legal URL +// strings. This implementation is more liberal and allows for the pattern +// ^[-_a-zA-Z0-9]+([./][-_a-zA-Z0-9]+)*`). Whitespaces and comments are allowed +// in between [ ], '.', '/' and the sub names. +func (d *Decoder) parseTypeName() (Token, error) { + startPos := len(d.orig) - len(d.in) + // Use alias s to advance first in order to use d.in for error handling. + // Caller already checks for [ as first character. + s := consume(d.in[1:], 0) + if len(s) == 0 { + return Token{}, ErrUnexpectedEOF + } + + var name []byte + for len(s) > 0 && isTypeNameChar(s[0]) { + name = append(name, s[0]) + s = s[1:] + } + s = consume(s, 0) + + var closed bool + for len(s) > 0 && !closed { + switch { + case s[0] == ']': + s = s[1:] + closed = true + + case s[0] == '/', s[0] == '.': + if len(name) > 0 && (name[len(name)-1] == '/' || name[len(name)-1] == '.') { + return Token{}, d.newSyntaxError("invalid type URL/extension field name: %s", + d.orig[startPos:len(d.orig)-len(s)+1]) + } + name = append(name, s[0]) + s = s[1:] + s = consume(s, 0) + for len(s) > 0 && isTypeNameChar(s[0]) { + name = append(name, s[0]) + s = s[1:] + } + s = consume(s, 0) + + default: + return Token{}, d.newSyntaxError( + "invalid type URL/extension field name: %s", d.orig[startPos:len(d.orig)-len(s)+1]) + } + } + + if !closed { + return Token{}, ErrUnexpectedEOF + } + + // First character cannot be '.'. Last character cannot be '.' or '/'. + size := len(name) + if size == 0 || name[0] == '.' || name[size-1] == '.' || name[size-1] == '/' { + return Token{}, d.newSyntaxError("invalid type URL/extension field name: %s", + d.orig[startPos:len(d.orig)-len(s)]) + } + + d.in = s + endPos := len(d.orig) - len(d.in) + d.consume(0) + + return Token{ + kind: Name, + attrs: uint8(TypeName), + pos: startPos, + raw: d.orig[startPos:endPos], + str: string(name), + }, nil +} + +func isTypeNameChar(b byte) bool { + return (b == '-' || b == '_' || + ('0' <= b && b <= '9') || + ('a' <= b && b <= 'z') || + ('A' <= b && b <= 'Z')) +} + +func isWhiteSpace(b byte) bool { + switch b { + case ' ', '\n', '\r', '\t': + return true + default: + return false + } +} + +// parseIdent parses an unquoted proto identifier and returns size. +// If allowNeg is true, it allows '-' to be the first character in the +// identifier. This is used when parsing literal values like -infinity, etc. +// Regular expression matches an identifier: `^[_a-zA-Z][_a-zA-Z0-9]*` +func parseIdent(input []byte, allowNeg bool) int { + var size int + + s := input + if len(s) == 0 { + return 0 + } + + if allowNeg && s[0] == '-' { + s = s[1:] + size++ + if len(s) == 0 { + return 0 + } + } + + switch { + case s[0] == '_', + 'a' <= s[0] && s[0] <= 'z', + 'A' <= s[0] && s[0] <= 'Z': + s = s[1:] + size++ + default: + return 0 + } + + for len(s) > 0 && (s[0] == '_' || + 'a' <= s[0] && s[0] <= 'z' || + 'A' <= s[0] && s[0] <= 'Z' || + '0' <= s[0] && s[0] <= '9') { + s = s[1:] + size++ + } + + if len(s) > 0 && !isDelim(s[0]) { + return 0 + } + + return size +} + +// parseScalar parses for a string, literal or number value. +func (d *Decoder) parseScalar() (Token, error) { + if d.in[0] == '"' || d.in[0] == '\'' { + return d.parseStringValue() + } + + if tok, ok := d.parseLiteralValue(); ok { + return tok, nil + } + + if tok, ok := d.parseNumberValue(); ok { + return tok, nil + } + + return Token{}, d.newSyntaxError("invalid scalar value: %s", errRegexp.Find(d.in)) +} + +// parseLiteralValue parses a literal value. A literal value is used for +// bools, special floats and enums. This function simply identifies that the +// field value is a literal. +func (d *Decoder) parseLiteralValue() (Token, bool) { + size := parseIdent(d.in, true) + if size == 0 { + return Token{}, false + } + return d.consumeToken(Scalar, size, literalValue), true +} + +// consumeToken constructs a Token for given Kind from d.in and consumes given +// size-length from it. +func (d *Decoder) consumeToken(kind Kind, size int, attrs uint8) Token { + // Important to compute raw and pos before consuming. + tok := Token{ + kind: kind, + attrs: attrs, + pos: len(d.orig) - len(d.in), + raw: d.in[:size], + } + d.consume(size) + return tok +} + +// newSyntaxError returns a syntax error with line and column information for +// current position. +func (d *Decoder) newSyntaxError(f string, x ...interface{}) error { + e := errors.New(f, x...) + line, column := d.Position(len(d.orig) - len(d.in)) + return errors.New("syntax error (line %d:%d): %v", line, column, e) +} + +// Position returns line and column number of given index of the original input. +// It will panic if index is out of range. +func (d *Decoder) Position(idx int) (line int, column int) { + b := d.orig[:idx] + line = bytes.Count(b, []byte("\n")) + 1 + if i := bytes.LastIndexByte(b, '\n'); i >= 0 { + b = b[i+1:] + } + column = utf8.RuneCount(b) + 1 // ignore multi-rune characters + return line, column +} + +func (d *Decoder) tryConsumeChar(c byte) bool { + if len(d.in) > 0 && d.in[0] == c { + d.consume(1) + return true + } + return false +} + +// consume consumes n bytes of input and any subsequent whitespace or comments. +func (d *Decoder) consume(n int) { + d.in = consume(d.in, n) + return +} + +// consume consumes n bytes of input and any subsequent whitespace or comments. +func consume(b []byte, n int) []byte { + b = b[n:] + for len(b) > 0 { + switch b[0] { + case ' ', '\n', '\r', '\t': + b = b[1:] + case '#': + if i := bytes.IndexByte(b, '\n'); i >= 0 { + b = b[i+len("\n"):] + } else { + b = nil + } + default: + return b + } + } + return b +} + +// Any sequence that looks like a non-delimiter (for error reporting). +var errRegexp = regexp.MustCompile(`^([-+._a-zA-Z0-9\/]+|.)`) + +// isDelim returns true if given byte is a delimiter character. +func isDelim(c byte) bool { + return !(c == '-' || c == '+' || c == '.' || c == '_' || + ('a' <= c && c <= 'z') || + ('A' <= c && c <= 'Z') || + ('0' <= c && c <= '9')) +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/text/decode_number.go b/vendor/google.golang.org/protobuf/internal/encoding/text/decode_number.go new file mode 100644 index 00000000000..f2d90b78999 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/text/decode_number.go @@ -0,0 +1,190 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package text + +// parseNumberValue parses a number from the input and returns a Token object. +func (d *Decoder) parseNumberValue() (Token, bool) { + in := d.in + num := parseNumber(in) + if num.size == 0 { + return Token{}, false + } + numAttrs := num.kind + if num.neg { + numAttrs |= isNegative + } + strSize := num.size + last := num.size - 1 + if num.kind == numFloat && (d.in[last] == 'f' || d.in[last] == 'F') { + strSize = last + } + tok := Token{ + kind: Scalar, + attrs: numberValue, + pos: len(d.orig) - len(d.in), + raw: d.in[:num.size], + str: string(d.in[:strSize]), + numAttrs: numAttrs, + } + d.consume(num.size) + return tok, true +} + +const ( + numDec uint8 = (1 << iota) / 2 + numHex + numOct + numFloat +) + +// number is the result of parsing out a valid number from parseNumber. It +// contains data for doing float or integer conversion via the strconv package +// in conjunction with the input bytes. +type number struct { + kind uint8 + neg bool + size int +} + +// parseNumber constructs a number object from given input. It allows for the +// following patterns: +// integer: ^-?([1-9][0-9]*|0[xX][0-9a-fA-F]+|0[0-7]*) +// float: ^-?((0|[1-9][0-9]*)?([.][0-9]*)?([eE][+-]?[0-9]+)?[fF]?) +// It also returns the number of parsed bytes for the given number, 0 if it is +// not a number. +func parseNumber(input []byte) number { + kind := numDec + var size int + var neg bool + + s := input + if len(s) == 0 { + return number{} + } + + // Optional - + if s[0] == '-' { + neg = true + s = s[1:] + size++ + if len(s) == 0 { + return number{} + } + } + + // C++ allows for whitespace and comments in between the negative sign and + // the rest of the number. This logic currently does not but is consistent + // with v1. + + switch { + case s[0] == '0': + if len(s) > 1 { + switch { + case s[1] == 'x' || s[1] == 'X': + // Parse as hex number. + kind = numHex + n := 2 + s = s[2:] + for len(s) > 0 && (('0' <= s[0] && s[0] <= '9') || + ('a' <= s[0] && s[0] <= 'f') || + ('A' <= s[0] && s[0] <= 'F')) { + s = s[1:] + n++ + } + if n == 2 { + return number{} + } + size += n + + case '0' <= s[1] && s[1] <= '7': + // Parse as octal number. + kind = numOct + n := 2 + s = s[2:] + for len(s) > 0 && '0' <= s[0] && s[0] <= '7' { + s = s[1:] + n++ + } + size += n + } + + if kind&(numHex|numOct) > 0 { + if len(s) > 0 && !isDelim(s[0]) { + return number{} + } + return number{kind: kind, neg: neg, size: size} + } + } + s = s[1:] + size++ + + case '1' <= s[0] && s[0] <= '9': + n := 1 + s = s[1:] + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + size += n + + case s[0] == '.': + // Set kind to numFloat to signify the intent to parse as float. And + // that it needs to have other digits after '.'. + kind = numFloat + + default: + return number{} + } + + // . followed by 0 or more digits. + if len(s) > 0 && s[0] == '.' { + n := 1 + s = s[1:] + // If decimal point was before any digits, it should be followed by + // other digits. + if len(s) == 0 && kind == numFloat { + return number{} + } + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + size += n + kind = numFloat + } + + // e or E followed by an optional - or + and 1 or more digits. + if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { + kind = numFloat + s = s[1:] + n := 1 + if s[0] == '+' || s[0] == '-' { + s = s[1:] + n++ + if len(s) == 0 { + return number{} + } + } + for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { + s = s[1:] + n++ + } + size += n + } + + // Optional suffix f or F for floats. + if len(s) > 0 && (s[0] == 'f' || s[0] == 'F') { + kind = numFloat + s = s[1:] + size++ + } + + // Check that next byte is a delimiter or it is at the end. + if len(s) > 0 && !isDelim(s[0]) { + return number{} + } + + return number{kind: kind, neg: neg, size: size} +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/text/decode_string.go b/vendor/google.golang.org/protobuf/internal/encoding/text/decode_string.go new file mode 100644 index 00000000000..d4d34902360 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/text/decode_string.go @@ -0,0 +1,161 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package text + +import ( + "bytes" + "strconv" + "strings" + "unicode" + "unicode/utf16" + "unicode/utf8" + + "google.golang.org/protobuf/internal/strs" +) + +// parseStringValue parses string field token. +// This differs from parseString since the text format allows +// multiple back-to-back string literals where they are semantically treated +// as a single large string with all values concatenated. +// +// E.g., `"foo" "bar" "baz"` => "foobarbaz" +func (d *Decoder) parseStringValue() (Token, error) { + // Note that the ending quote is sufficient to unambiguously mark the end + // of a string. Thus, the text grammar does not require intervening + // whitespace or control characters in-between strings. + // Thus, the following is valid: + // `"foo"'bar'"baz"` => "foobarbaz" + in0 := d.in + var ss []string + for len(d.in) > 0 && (d.in[0] == '"' || d.in[0] == '\'') { + s, err := d.parseString() + if err != nil { + return Token{}, err + } + ss = append(ss, s) + } + // d.in already points to the end of the value at this point. + return Token{ + kind: Scalar, + attrs: stringValue, + pos: len(d.orig) - len(in0), + raw: in0[:len(in0)-len(d.in)], + str: strings.Join(ss, ""), + }, nil +} + +// parseString parses a string value enclosed in " or '. +func (d *Decoder) parseString() (string, error) { + in := d.in + if len(in) == 0 { + return "", ErrUnexpectedEOF + } + quote := in[0] + in = in[1:] + i := indexNeedEscapeInBytes(in) + in, out := in[i:], in[:i:i] // set cap to prevent mutations + for len(in) > 0 { + switch r, n := utf8.DecodeRune(in); { + case r == utf8.RuneError && n == 1: + return "", d.newSyntaxError("invalid UTF-8 detected") + case r == 0 || r == '\n': + return "", d.newSyntaxError("invalid character %q in string", r) + case r == rune(quote): + in = in[1:] + d.consume(len(d.in) - len(in)) + return string(out), nil + case r == '\\': + if len(in) < 2 { + return "", ErrUnexpectedEOF + } + switch r := in[1]; r { + case '"', '\'', '\\', '?': + in, out = in[2:], append(out, r) + case 'a': + in, out = in[2:], append(out, '\a') + case 'b': + in, out = in[2:], append(out, '\b') + case 'n': + in, out = in[2:], append(out, '\n') + case 'r': + in, out = in[2:], append(out, '\r') + case 't': + in, out = in[2:], append(out, '\t') + case 'v': + in, out = in[2:], append(out, '\v') + case 'f': + in, out = in[2:], append(out, '\f') + case '0', '1', '2', '3', '4', '5', '6', '7': + // One, two, or three octal characters. + n := len(in[1:]) - len(bytes.TrimLeft(in[1:], "01234567")) + if n > 3 { + n = 3 + } + v, err := strconv.ParseUint(string(in[1:1+n]), 8, 8) + if err != nil { + return "", d.newSyntaxError("invalid octal escape code %q in string", in[:1+n]) + } + in, out = in[1+n:], append(out, byte(v)) + case 'x': + // One or two hexadecimal characters. + n := len(in[2:]) - len(bytes.TrimLeft(in[2:], "0123456789abcdefABCDEF")) + if n > 2 { + n = 2 + } + v, err := strconv.ParseUint(string(in[2:2+n]), 16, 8) + if err != nil { + return "", d.newSyntaxError("invalid hex escape code %q in string", in[:2+n]) + } + in, out = in[2+n:], append(out, byte(v)) + case 'u', 'U': + // Four or eight hexadecimal characters + n := 6 + if r == 'U' { + n = 10 + } + if len(in) < n { + return "", ErrUnexpectedEOF + } + v, err := strconv.ParseUint(string(in[2:n]), 16, 32) + if utf8.MaxRune < v || err != nil { + return "", d.newSyntaxError("invalid Unicode escape code %q in string", in[:n]) + } + in = in[n:] + + r := rune(v) + if utf16.IsSurrogate(r) { + if len(in) < 6 { + return "", ErrUnexpectedEOF + } + v, err := strconv.ParseUint(string(in[2:6]), 16, 16) + r = utf16.DecodeRune(r, rune(v)) + if in[0] != '\\' || in[1] != 'u' || r == unicode.ReplacementChar || err != nil { + return "", d.newSyntaxError("invalid Unicode escape code %q in string", in[:6]) + } + in = in[6:] + } + out = append(out, string(r)...) + default: + return "", d.newSyntaxError("invalid escape code %q in string", in[:2]) + } + default: + i := indexNeedEscapeInBytes(in[n:]) + in, out = in[n+i:], append(out, in[:n+i]...) + } + } + return "", ErrUnexpectedEOF +} + +// indexNeedEscapeInString returns the index of the character that needs +// escaping. If no characters need escaping, this returns the input length. +func indexNeedEscapeInBytes(b []byte) int { return indexNeedEscapeInString(strs.UnsafeString(b)) } + +// UnmarshalString returns an unescaped string given a textproto string value. +// String value needs to contain single or double quotes. This is only used by +// internal/encoding/defval package for unmarshaling bytes. +func UnmarshalString(s string) (string, error) { + d := NewDecoder([]byte(s)) + return d.parseString() +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/text/decode_token.go b/vendor/google.golang.org/protobuf/internal/encoding/text/decode_token.go new file mode 100644 index 00000000000..83d2b0d5aec --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/text/decode_token.go @@ -0,0 +1,373 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package text + +import ( + "bytes" + "fmt" + "math" + "strconv" + "strings" + + "google.golang.org/protobuf/internal/flags" +) + +// Kind represents a token kind expressible in the textproto format. +type Kind uint8 + +// Kind values. +const ( + Invalid Kind = iota + EOF + Name // Name indicates the field name. + Scalar // Scalar are scalar values, e.g. "string", 47, ENUM_LITERAL, true. + MessageOpen + MessageClose + ListOpen + ListClose + + // comma and semi-colon are only for parsing in between values and should not be exposed. + comma + semicolon + + // bof indicates beginning of file, which is the default token + // kind at the beginning of parsing. + bof = Invalid +) + +func (t Kind) String() string { + switch t { + case Invalid: + return "" + case EOF: + return "eof" + case Scalar: + return "scalar" + case Name: + return "name" + case MessageOpen: + return "{" + case MessageClose: + return "}" + case ListOpen: + return "[" + case ListClose: + return "]" + case comma: + return "," + case semicolon: + return ";" + default: + return fmt.Sprintf("", uint8(t)) + } +} + +// NameKind represents different types of field names. +type NameKind uint8 + +// NameKind values. +const ( + IdentName NameKind = iota + 1 + TypeName + FieldNumber +) + +func (t NameKind) String() string { + switch t { + case IdentName: + return "IdentName" + case TypeName: + return "TypeName" + case FieldNumber: + return "FieldNumber" + default: + return fmt.Sprintf("", uint8(t)) + } +} + +// Bit mask in Token.attrs to indicate if a Name token is followed by the +// separator char ':'. The field name separator char is optional for message +// field or repeated message field, but required for all other types. Decoder +// simply indicates whether a Name token is followed by separator or not. It is +// up to the prototext package to validate. +const hasSeparator = 1 << 7 + +// Scalar value types. +const ( + numberValue = iota + 1 + stringValue + literalValue +) + +// Bit mask in Token.numAttrs to indicate that the number is a negative. +const isNegative = 1 << 7 + +// Token provides a parsed token kind and value. Values are provided by the +// different accessor methods. +type Token struct { + // Kind of the Token object. + kind Kind + // attrs contains metadata for the following Kinds: + // Name: hasSeparator bit and one of NameKind. + // Scalar: one of numberValue, stringValue, literalValue. + attrs uint8 + // numAttrs contains metadata for numberValue: + // - highest bit is whether negative or positive. + // - lower bits indicate one of numDec, numHex, numOct, numFloat. + numAttrs uint8 + // pos provides the position of the token in the original input. + pos int + // raw bytes of the serialized token. + // This is a subslice into the original input. + raw []byte + // str contains parsed string for the following: + // - stringValue of Scalar kind + // - numberValue of Scalar kind + // - TypeName of Name kind + str string +} + +// Kind returns the token kind. +func (t Token) Kind() Kind { + return t.kind +} + +// RawString returns the read value in string. +func (t Token) RawString() string { + return string(t.raw) +} + +// Pos returns the token position from the input. +func (t Token) Pos() int { + return t.pos +} + +// NameKind returns IdentName, TypeName or FieldNumber. +// It panics if type is not Name. +func (t Token) NameKind() NameKind { + if t.kind == Name { + return NameKind(t.attrs &^ hasSeparator) + } + panic(fmt.Sprintf("Token is not a Name type: %s", t.kind)) +} + +// HasSeparator returns true if the field name is followed by the separator char +// ':', else false. It panics if type is not Name. +func (t Token) HasSeparator() bool { + if t.kind == Name { + return t.attrs&hasSeparator != 0 + } + panic(fmt.Sprintf("Token is not a Name type: %s", t.kind)) +} + +// IdentName returns the value for IdentName type. +func (t Token) IdentName() string { + if t.kind == Name && t.attrs&uint8(IdentName) != 0 { + return string(t.raw) + } + panic(fmt.Sprintf("Token is not an IdentName: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator))) +} + +// TypeName returns the value for TypeName type. +func (t Token) TypeName() string { + if t.kind == Name && t.attrs&uint8(TypeName) != 0 { + return t.str + } + panic(fmt.Sprintf("Token is not a TypeName: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator))) +} + +// FieldNumber returns the value for FieldNumber type. It returns a +// non-negative int32 value. Caller will still need to validate for the correct +// field number range. +func (t Token) FieldNumber() int32 { + if t.kind != Name || t.attrs&uint8(FieldNumber) == 0 { + panic(fmt.Sprintf("Token is not a FieldNumber: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator))) + } + // Following should not return an error as it had already been called right + // before this Token was constructed. + num, _ := strconv.ParseInt(string(t.raw), 10, 32) + return int32(num) +} + +// String returns the string value for a Scalar type. +func (t Token) String() (string, bool) { + if t.kind != Scalar || t.attrs != stringValue { + return "", false + } + return t.str, true +} + +// Enum returns the literal value for a Scalar type for use as enum literals. +func (t Token) Enum() (string, bool) { + if t.kind != Scalar || t.attrs != literalValue || (len(t.raw) > 0 && t.raw[0] == '-') { + return "", false + } + return string(t.raw), true +} + +// Bool returns the bool value for a Scalar type. +func (t Token) Bool() (bool, bool) { + if t.kind != Scalar { + return false, false + } + switch t.attrs { + case literalValue: + if b, ok := boolLits[string(t.raw)]; ok { + return b, true + } + case numberValue: + // Unsigned integer representation of 0 or 1 is permitted: 00, 0x0, 01, + // 0x1, etc. + n, err := strconv.ParseUint(t.str, 0, 64) + if err == nil { + switch n { + case 0: + return false, true + case 1: + return true, true + } + } + } + return false, false +} + +// These exact boolean literals are the ones supported in C++. +var boolLits = map[string]bool{ + "t": true, + "true": true, + "True": true, + "f": false, + "false": false, + "False": false, +} + +// Uint64 returns the uint64 value for a Scalar type. +func (t Token) Uint64() (uint64, bool) { + if t.kind != Scalar || t.attrs != numberValue || + t.numAttrs&isNegative > 0 || t.numAttrs&numFloat > 0 { + return 0, false + } + n, err := strconv.ParseUint(t.str, 0, 64) + if err != nil { + return 0, false + } + return n, true +} + +// Uint32 returns the uint32 value for a Scalar type. +func (t Token) Uint32() (uint32, bool) { + if t.kind != Scalar || t.attrs != numberValue || + t.numAttrs&isNegative > 0 || t.numAttrs&numFloat > 0 { + return 0, false + } + n, err := strconv.ParseUint(t.str, 0, 32) + if err != nil { + return 0, false + } + return uint32(n), true +} + +// Int64 returns the int64 value for a Scalar type. +func (t Token) Int64() (int64, bool) { + if t.kind != Scalar || t.attrs != numberValue || t.numAttrs&numFloat > 0 { + return 0, false + } + if n, err := strconv.ParseInt(t.str, 0, 64); err == nil { + return n, true + } + // C++ accepts large positive hex numbers as negative values. + // This feature is here for proto1 backwards compatibility purposes. + if flags.ProtoLegacy && (t.numAttrs == numHex) { + if n, err := strconv.ParseUint(t.str, 0, 64); err == nil { + return int64(n), true + } + } + return 0, false +} + +// Int32 returns the int32 value for a Scalar type. +func (t Token) Int32() (int32, bool) { + if t.kind != Scalar || t.attrs != numberValue || t.numAttrs&numFloat > 0 { + return 0, false + } + if n, err := strconv.ParseInt(t.str, 0, 32); err == nil { + return int32(n), true + } + // C++ accepts large positive hex numbers as negative values. + // This feature is here for proto1 backwards compatibility purposes. + if flags.ProtoLegacy && (t.numAttrs == numHex) { + if n, err := strconv.ParseUint(t.str, 0, 32); err == nil { + return int32(n), true + } + } + return 0, false +} + +// Float64 returns the float64 value for a Scalar type. +func (t Token) Float64() (float64, bool) { + if t.kind != Scalar { + return 0, false + } + switch t.attrs { + case literalValue: + if f, ok := floatLits[strings.ToLower(string(t.raw))]; ok { + return f, true + } + case numberValue: + n, err := strconv.ParseFloat(t.str, 64) + if err == nil { + return n, true + } + nerr := err.(*strconv.NumError) + if nerr.Err == strconv.ErrRange { + return n, true + } + } + return 0, false +} + +// Float32 returns the float32 value for a Scalar type. +func (t Token) Float32() (float32, bool) { + if t.kind != Scalar { + return 0, false + } + switch t.attrs { + case literalValue: + if f, ok := floatLits[strings.ToLower(string(t.raw))]; ok { + return float32(f), true + } + case numberValue: + n, err := strconv.ParseFloat(t.str, 64) + if err == nil { + // Overflows are treated as (-)infinity. + return float32(n), true + } + nerr := err.(*strconv.NumError) + if nerr.Err == strconv.ErrRange { + return float32(n), true + } + } + return 0, false +} + +// These are the supported float literals which C++ permits case-insensitive +// variants of these. +var floatLits = map[string]float64{ + "nan": math.NaN(), + "inf": math.Inf(1), + "infinity": math.Inf(1), + "-inf": math.Inf(-1), + "-infinity": math.Inf(-1), +} + +// TokenEquals returns true if given Tokens are equal, else false. +func TokenEquals(x, y Token) bool { + return x.kind == y.kind && + x.attrs == y.attrs && + x.numAttrs == y.numAttrs && + x.pos == y.pos && + bytes.Equal(x.raw, y.raw) && + x.str == y.str +} diff --git a/vendor/google.golang.org/protobuf/internal/encoding/text/doc.go b/vendor/google.golang.org/protobuf/internal/encoding/text/doc.go new file mode 100644 index 00000000000..0ce8d6fb83d --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/text/doc.go @@ -0,0 +1,29 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package text implements the text format for protocol buffers. +// This package has no semantic understanding for protocol buffers and is only +// a parser and composer for the format. +// +// There is no formal specification for the protobuf text format, as such the +// C++ implementation (see google::protobuf::TextFormat) is the reference +// implementation of the text format. +// +// This package is neither a superset nor a subset of the C++ implementation. +// This implementation permits a more liberal grammar in some cases to be +// backwards compatible with the historical Go implementation. +// Future parsings unique to Go should not be added. +// Some grammars allowed by the C++ implementation are deliberately +// not implemented here because they are considered a bug by the protobuf team +// and should not be replicated. +// +// The Go implementation should implement a sufficient amount of the C++ +// grammar such that the default text serialization by C++ can be parsed by Go. +// However, just because the C++ parser accepts some input does not mean that +// the Go implementation should as well. +// +// The text format is almost a superset of JSON except: +// * message keys are not quoted strings, but identifiers +// * the top-level value must be a message without the delimiters +package text diff --git a/vendor/google.golang.org/protobuf/internal/encoding/text/encode.go b/vendor/google.golang.org/protobuf/internal/encoding/text/encode.go new file mode 100644 index 00000000000..c4ba1c598fb --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/encoding/text/encode.go @@ -0,0 +1,267 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package text + +import ( + "math" + "math/bits" + "strconv" + "strings" + "unicode/utf8" + + "google.golang.org/protobuf/internal/detrand" + "google.golang.org/protobuf/internal/errors" +) + +// encType represents an encoding type. +type encType uint8 + +const ( + _ encType = (1 << iota) / 2 + name + scalar + messageOpen + messageClose +) + +// Encoder provides methods to write out textproto constructs and values. The user is +// responsible for producing valid sequences of constructs and values. +type Encoder struct { + encoderState + + indent string + newline string // set to "\n" if len(indent) > 0 + delims [2]byte + outputASCII bool +} + +type encoderState struct { + lastType encType + indents []byte + out []byte +} + +// NewEncoder returns an Encoder. +// +// If indent is a non-empty string, it causes every entry in a List or Message +// to be preceded by the indent and trailed by a newline. +// +// If delims is not the zero value, it controls the delimiter characters used +// for messages (e.g., "{}" vs "<>"). +// +// If outputASCII is true, strings will be serialized in such a way that +// multi-byte UTF-8 sequences are escaped. This property ensures that the +// overall output is ASCII (as opposed to UTF-8). +func NewEncoder(indent string, delims [2]byte, outputASCII bool) (*Encoder, error) { + e := &Encoder{} + if len(indent) > 0 { + if strings.Trim(indent, " \t") != "" { + return nil, errors.New("indent may only be composed of space and tab characters") + } + e.indent = indent + e.newline = "\n" + } + switch delims { + case [2]byte{0, 0}: + e.delims = [2]byte{'{', '}'} + case [2]byte{'{', '}'}, [2]byte{'<', '>'}: + e.delims = delims + default: + return nil, errors.New("delimiters may only be \"{}\" or \"<>\"") + } + e.outputASCII = outputASCII + + return e, nil +} + +// Bytes returns the content of the written bytes. +func (e *Encoder) Bytes() []byte { + return e.out +} + +// StartMessage writes out the '{' or '<' symbol. +func (e *Encoder) StartMessage() { + e.prepareNext(messageOpen) + e.out = append(e.out, e.delims[0]) +} + +// EndMessage writes out the '}' or '>' symbol. +func (e *Encoder) EndMessage() { + e.prepareNext(messageClose) + e.out = append(e.out, e.delims[1]) +} + +// WriteName writes out the field name and the separator ':'. +func (e *Encoder) WriteName(s string) { + e.prepareNext(name) + e.out = append(e.out, s...) + e.out = append(e.out, ':') +} + +// WriteBool writes out the given boolean value. +func (e *Encoder) WriteBool(b bool) { + if b { + e.WriteLiteral("true") + } else { + e.WriteLiteral("false") + } +} + +// WriteString writes out the given string value. +func (e *Encoder) WriteString(s string) { + e.prepareNext(scalar) + e.out = appendString(e.out, s, e.outputASCII) +} + +func appendString(out []byte, in string, outputASCII bool) []byte { + out = append(out, '"') + i := indexNeedEscapeInString(in) + in, out = in[i:], append(out, in[:i]...) + for len(in) > 0 { + switch r, n := utf8.DecodeRuneInString(in); { + case r == utf8.RuneError && n == 1: + // We do not report invalid UTF-8 because strings in the text format + // are used to represent both the proto string and bytes type. + r = rune(in[0]) + fallthrough + case r < ' ' || r == '"' || r == '\\': + out = append(out, '\\') + switch r { + case '"', '\\': + out = append(out, byte(r)) + case '\n': + out = append(out, 'n') + case '\r': + out = append(out, 'r') + case '\t': + out = append(out, 't') + default: + out = append(out, 'x') + out = append(out, "00"[1+(bits.Len32(uint32(r))-1)/4:]...) + out = strconv.AppendUint(out, uint64(r), 16) + } + in = in[n:] + case outputASCII && r >= utf8.RuneSelf: + out = append(out, '\\') + if r <= math.MaxUint16 { + out = append(out, 'u') + out = append(out, "0000"[1+(bits.Len32(uint32(r))-1)/4:]...) + out = strconv.AppendUint(out, uint64(r), 16) + } else { + out = append(out, 'U') + out = append(out, "00000000"[1+(bits.Len32(uint32(r))-1)/4:]...) + out = strconv.AppendUint(out, uint64(r), 16) + } + in = in[n:] + default: + i := indexNeedEscapeInString(in[n:]) + in, out = in[n+i:], append(out, in[:n+i]...) + } + } + out = append(out, '"') + return out +} + +// indexNeedEscapeInString returns the index of the character that needs +// escaping. If no characters need escaping, this returns the input length. +func indexNeedEscapeInString(s string) int { + for i := 0; i < len(s); i++ { + if c := s[i]; c < ' ' || c == '"' || c == '\'' || c == '\\' || c >= utf8.RuneSelf { + return i + } + } + return len(s) +} + +// WriteFloat writes out the given float value for given bitSize. +func (e *Encoder) WriteFloat(n float64, bitSize int) { + e.prepareNext(scalar) + e.out = appendFloat(e.out, n, bitSize) +} + +func appendFloat(out []byte, n float64, bitSize int) []byte { + switch { + case math.IsNaN(n): + return append(out, "nan"...) + case math.IsInf(n, +1): + return append(out, "inf"...) + case math.IsInf(n, -1): + return append(out, "-inf"...) + default: + return strconv.AppendFloat(out, n, 'g', -1, bitSize) + } +} + +// WriteInt writes out the given signed integer value. +func (e *Encoder) WriteInt(n int64) { + e.prepareNext(scalar) + e.out = append(e.out, strconv.FormatInt(n, 10)...) +} + +// WriteUint writes out the given unsigned integer value. +func (e *Encoder) WriteUint(n uint64) { + e.prepareNext(scalar) + e.out = append(e.out, strconv.FormatUint(n, 10)...) +} + +// WriteLiteral writes out the given string as a literal value without quotes. +// This is used for writing enum literal strings. +func (e *Encoder) WriteLiteral(s string) { + e.prepareNext(scalar) + e.out = append(e.out, s...) +} + +// prepareNext adds possible space and indentation for the next value based +// on last encType and indent option. It also updates e.lastType to next. +func (e *Encoder) prepareNext(next encType) { + defer func() { + e.lastType = next + }() + + // Single line. + if len(e.indent) == 0 { + // Add space after each field before the next one. + if e.lastType&(scalar|messageClose) != 0 && next == name { + e.out = append(e.out, ' ') + // Add a random extra space to make output unstable. + if detrand.Bool() { + e.out = append(e.out, ' ') + } + } + return + } + + // Multi-line. + switch { + case e.lastType == name: + e.out = append(e.out, ' ') + // Add a random extra space after name: to make output unstable. + if detrand.Bool() { + e.out = append(e.out, ' ') + } + + case e.lastType == messageOpen && next != messageClose: + e.indents = append(e.indents, e.indent...) + e.out = append(e.out, '\n') + e.out = append(e.out, e.indents...) + + case e.lastType&(scalar|messageClose) != 0: + if next == messageClose { + e.indents = e.indents[:len(e.indents)-len(e.indent)] + } + e.out = append(e.out, '\n') + e.out = append(e.out, e.indents...) + } +} + +// Snapshot returns the current snapshot for use in Reset. +func (e *Encoder) Snapshot() encoderState { + return e.encoderState +} + +// Reset resets the Encoder to the given encoderState from a Snapshot. +func (e *Encoder) Reset(es encoderState) { + e.encoderState = es +} diff --git a/vendor/google.golang.org/protobuf/internal/errors/errors.go b/vendor/google.golang.org/protobuf/internal/errors/errors.go new file mode 100644 index 00000000000..20c17b35e3a --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/errors/errors.go @@ -0,0 +1,89 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package errors implements functions to manipulate errors. +package errors + +import ( + "errors" + "fmt" + + "google.golang.org/protobuf/internal/detrand" +) + +// Error is a sentinel matching all errors produced by this package. +var Error = errors.New("protobuf error") + +// New formats a string according to the format specifier and arguments and +// returns an error that has a "proto" prefix. +func New(f string, x ...interface{}) error { + return &prefixError{s: format(f, x...)} +} + +type prefixError struct{ s string } + +var prefix = func() string { + // Deliberately introduce instability into the error message string to + // discourage users from performing error string comparisons. + if detrand.Bool() { + return "proto: " // use non-breaking spaces (U+00a0) + } else { + return "proto: " // use regular spaces (U+0020) + } +}() + +func (e *prefixError) Error() string { + return prefix + e.s +} + +func (e *prefixError) Unwrap() error { + return Error +} + +// Wrap returns an error that has a "proto" prefix, the formatted string described +// by the format specifier and arguments, and a suffix of err. The error wraps err. +func Wrap(err error, f string, x ...interface{}) error { + return &wrapError{ + s: format(f, x...), + err: err, + } +} + +type wrapError struct { + s string + err error +} + +func (e *wrapError) Error() string { + return format("%v%v: %v", prefix, e.s, e.err) +} + +func (e *wrapError) Unwrap() error { + return e.err +} + +func (e *wrapError) Is(target error) bool { + return target == Error +} + +func format(f string, x ...interface{}) string { + // avoid "proto: " prefix when chaining + for i := 0; i < len(x); i++ { + switch e := x[i].(type) { + case *prefixError: + x[i] = e.s + case *wrapError: + x[i] = format("%v: %v", e.s, e.err) + } + } + return fmt.Sprintf(f, x...) +} + +func InvalidUTF8(name string) error { + return New("field %v contains invalid UTF-8", name) +} + +func RequiredNotSet(name string) error { + return New("required field %v not set", name) +} diff --git a/vendor/google.golang.org/protobuf/internal/errors/is_go112.go b/vendor/google.golang.org/protobuf/internal/errors/is_go112.go new file mode 100644 index 00000000000..f90e909b37a --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/errors/is_go112.go @@ -0,0 +1,39 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.13 + +package errors + +import "reflect" + +// Is is a copy of Go 1.13's errors.Is for use with older Go versions. +func Is(err, target error) bool { + if target == nil { + return err == target + } + + isComparable := reflect.TypeOf(target).Comparable() + for { + if isComparable && err == target { + return true + } + if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) { + return true + } + if err = unwrap(err); err == nil { + return false + } + } +} + +func unwrap(err error) error { + u, ok := err.(interface { + Unwrap() error + }) + if !ok { + return nil + } + return u.Unwrap() +} diff --git a/vendor/google.golang.org/protobuf/internal/errors/is_go113.go b/vendor/google.golang.org/protobuf/internal/errors/is_go113.go new file mode 100644 index 00000000000..dc05f4191c0 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/errors/is_go113.go @@ -0,0 +1,12 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.13 + +package errors + +import "errors" + +// Is is errors.Is. +func Is(err, target error) bool { return errors.Is(err, target) } diff --git a/vendor/google.golang.org/protobuf/internal/fieldsort/fieldsort.go b/vendor/google.golang.org/protobuf/internal/fieldsort/fieldsort.go new file mode 100644 index 00000000000..517c4e2a041 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/fieldsort/fieldsort.go @@ -0,0 +1,40 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package fieldsort defines an ordering of fields. +// +// The ordering defined by this package matches the historic behavior of the proto +// package, placing extensions first and oneofs last. +// +// There is no guarantee about stability of the wire encoding, and users should not +// depend on the order defined in this package as it is subject to change without +// notice. +package fieldsort + +import ( + "google.golang.org/protobuf/reflect/protoreflect" +) + +// Less returns true if field a comes before field j in ordered wire marshal output. +func Less(a, b protoreflect.FieldDescriptor) bool { + ea := a.IsExtension() + eb := b.IsExtension() + oa := a.ContainingOneof() + ob := b.ContainingOneof() + switch { + case ea != eb: + return ea + case oa != nil && ob != nil: + if oa == ob { + return a.Number() < b.Number() + } + return oa.Index() < ob.Index() + case oa != nil && !oa.IsSynthetic(): + return false + case ob != nil && !ob.IsSynthetic(): + return true + default: + return a.Number() < b.Number() + } +} diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/build.go b/vendor/google.golang.org/protobuf/internal/filedesc/build.go new file mode 100644 index 00000000000..d02d770c984 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/filedesc/build.go @@ -0,0 +1,155 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package filedesc provides functionality for constructing descriptors. +package filedesc + +import ( + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/reflect/protoreflect" + pref "google.golang.org/protobuf/reflect/protoreflect" + preg "google.golang.org/protobuf/reflect/protoregistry" +) + +// Builder construct a protoreflect.FileDescriptor from the raw descriptor. +type Builder struct { + // GoPackagePath is the Go package path that is invoking this builder. + GoPackagePath string + + // RawDescriptor is the wire-encoded bytes of FileDescriptorProto + // and must be populated. + RawDescriptor []byte + + // NumEnums is the total number of enums declared in the file. + NumEnums int32 + // NumMessages is the total number of messages declared in the file. + // It includes the implicit message declarations for map entries. + NumMessages int32 + // NumExtensions is the total number of extensions declared in the file. + NumExtensions int32 + // NumServices is the total number of services declared in the file. + NumServices int32 + + // TypeResolver resolves extension field types for descriptor options. + // If nil, it uses protoregistry.GlobalTypes. + TypeResolver interface { + preg.ExtensionTypeResolver + } + + // FileRegistry is use to lookup file, enum, and message dependencies. + // Once constructed, the file descriptor is registered here. + // If nil, it uses protoregistry.GlobalFiles. + FileRegistry interface { + FindFileByPath(string) (protoreflect.FileDescriptor, error) + FindDescriptorByName(pref.FullName) (pref.Descriptor, error) + RegisterFile(pref.FileDescriptor) error + } +} + +// resolverByIndex is an interface Builder.FileRegistry may implement. +// If so, it permits looking up an enum or message dependency based on the +// sub-list and element index into filetype.Builder.DependencyIndexes. +type resolverByIndex interface { + FindEnumByIndex(int32, int32, []Enum, []Message) pref.EnumDescriptor + FindMessageByIndex(int32, int32, []Enum, []Message) pref.MessageDescriptor +} + +// Indexes of each sub-list in filetype.Builder.DependencyIndexes. +const ( + listFieldDeps int32 = iota + listExtTargets + listExtDeps + listMethInDeps + listMethOutDeps +) + +// Out is the output of the Builder. +type Out struct { + File pref.FileDescriptor + + // Enums is all enum descriptors in "flattened ordering". + Enums []Enum + // Messages is all message descriptors in "flattened ordering". + // It includes the implicit message declarations for map entries. + Messages []Message + // Extensions is all extension descriptors in "flattened ordering". + Extensions []Extension + // Service is all service descriptors in "flattened ordering". + Services []Service +} + +// Build constructs a FileDescriptor given the parameters set in Builder. +// It assumes that the inputs are well-formed and panics if any inconsistencies +// are encountered. +// +// If NumEnums+NumMessages+NumExtensions+NumServices is zero, +// then Build automatically derives them from the raw descriptor. +func (db Builder) Build() (out Out) { + // Populate the counts if uninitialized. + if db.NumEnums+db.NumMessages+db.NumExtensions+db.NumServices == 0 { + db.unmarshalCounts(db.RawDescriptor, true) + } + + // Initialize resolvers and registries if unpopulated. + if db.TypeResolver == nil { + db.TypeResolver = preg.GlobalTypes + } + if db.FileRegistry == nil { + db.FileRegistry = preg.GlobalFiles + } + + fd := newRawFile(db) + out.File = fd + out.Enums = fd.allEnums + out.Messages = fd.allMessages + out.Extensions = fd.allExtensions + out.Services = fd.allServices + + if err := db.FileRegistry.RegisterFile(fd); err != nil { + panic(err) + } + return out +} + +// unmarshalCounts counts the number of enum, message, extension, and service +// declarations in the raw message, which is either a FileDescriptorProto +// or a MessageDescriptorProto depending on whether isFile is set. +func (db *Builder) unmarshalCounts(b []byte, isFile bool) { + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + if isFile { + switch num { + case genid.FileDescriptorProto_EnumType_field_number: + db.NumEnums++ + case genid.FileDescriptorProto_MessageType_field_number: + db.unmarshalCounts(v, false) + db.NumMessages++ + case genid.FileDescriptorProto_Extension_field_number: + db.NumExtensions++ + case genid.FileDescriptorProto_Service_field_number: + db.NumServices++ + } + } else { + switch num { + case genid.DescriptorProto_EnumType_field_number: + db.NumEnums++ + case genid.DescriptorProto_NestedType_field_number: + db.unmarshalCounts(v, false) + db.NumMessages++ + case genid.DescriptorProto_Extension_field_number: + db.NumExtensions++ + } + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } +} diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc.go new file mode 100644 index 00000000000..9385126fba6 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc.go @@ -0,0 +1,614 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package filedesc + +import ( + "bytes" + "fmt" + "sync" + "sync/atomic" + + "google.golang.org/protobuf/internal/descfmt" + "google.golang.org/protobuf/internal/descopts" + "google.golang.org/protobuf/internal/encoding/defval" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/internal/strs" + pref "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +// The types in this file may have a suffix: +// • L0: Contains fields common to all descriptors (except File) and +// must be initialized up front. +// • L1: Contains fields specific to a descriptor and +// must be initialized up front. +// • L2: Contains fields that are lazily initialized when constructing +// from the raw file descriptor. When constructing as a literal, the L2 +// fields must be initialized up front. +// +// The types are exported so that packages like reflect/protodesc can +// directly construct descriptors. + +type ( + File struct { + fileRaw + L1 FileL1 + + once uint32 // atomically set if L2 is valid + mu sync.Mutex // protects L2 + L2 *FileL2 + } + FileL1 struct { + Syntax pref.Syntax + Path string + Package pref.FullName + + Enums Enums + Messages Messages + Extensions Extensions + Services Services + } + FileL2 struct { + Options func() pref.ProtoMessage + Imports FileImports + Locations SourceLocations + } +) + +func (fd *File) ParentFile() pref.FileDescriptor { return fd } +func (fd *File) Parent() pref.Descriptor { return nil } +func (fd *File) Index() int { return 0 } +func (fd *File) Syntax() pref.Syntax { return fd.L1.Syntax } +func (fd *File) Name() pref.Name { return fd.L1.Package.Name() } +func (fd *File) FullName() pref.FullName { return fd.L1.Package } +func (fd *File) IsPlaceholder() bool { return false } +func (fd *File) Options() pref.ProtoMessage { + if f := fd.lazyInit().Options; f != nil { + return f() + } + return descopts.File +} +func (fd *File) Path() string { return fd.L1.Path } +func (fd *File) Package() pref.FullName { return fd.L1.Package } +func (fd *File) Imports() pref.FileImports { return &fd.lazyInit().Imports } +func (fd *File) Enums() pref.EnumDescriptors { return &fd.L1.Enums } +func (fd *File) Messages() pref.MessageDescriptors { return &fd.L1.Messages } +func (fd *File) Extensions() pref.ExtensionDescriptors { return &fd.L1.Extensions } +func (fd *File) Services() pref.ServiceDescriptors { return &fd.L1.Services } +func (fd *File) SourceLocations() pref.SourceLocations { return &fd.lazyInit().Locations } +func (fd *File) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, fd) } +func (fd *File) ProtoType(pref.FileDescriptor) {} +func (fd *File) ProtoInternal(pragma.DoNotImplement) {} + +func (fd *File) lazyInit() *FileL2 { + if atomic.LoadUint32(&fd.once) == 0 { + fd.lazyInitOnce() + } + return fd.L2 +} + +func (fd *File) lazyInitOnce() { + fd.mu.Lock() + if fd.L2 == nil { + fd.lazyRawInit() // recursively initializes all L2 structures + } + atomic.StoreUint32(&fd.once, 1) + fd.mu.Unlock() +} + +// ProtoLegacyRawDesc is a pseudo-internal API for allowing the v1 code +// to be able to retrieve the raw descriptor. +// +// WARNING: This method is exempt from the compatibility promise and may be +// removed in the future without warning. +func (fd *File) ProtoLegacyRawDesc() []byte { + return fd.builder.RawDescriptor +} + +// GoPackagePath is a pseudo-internal API for determining the Go package path +// that this file descriptor is declared in. +// +// WARNING: This method is exempt from the compatibility promise and may be +// removed in the future without warning. +func (fd *File) GoPackagePath() string { + return fd.builder.GoPackagePath +} + +type ( + Enum struct { + Base + L1 EnumL1 + L2 *EnumL2 // protected by fileDesc.once + } + EnumL1 struct { + eagerValues bool // controls whether EnumL2.Values is already populated + } + EnumL2 struct { + Options func() pref.ProtoMessage + Values EnumValues + ReservedNames Names + ReservedRanges EnumRanges + } + + EnumValue struct { + Base + L1 EnumValueL1 + } + EnumValueL1 struct { + Options func() pref.ProtoMessage + Number pref.EnumNumber + } +) + +func (ed *Enum) Options() pref.ProtoMessage { + if f := ed.lazyInit().Options; f != nil { + return f() + } + return descopts.Enum +} +func (ed *Enum) Values() pref.EnumValueDescriptors { + if ed.L1.eagerValues { + return &ed.L2.Values + } + return &ed.lazyInit().Values +} +func (ed *Enum) ReservedNames() pref.Names { return &ed.lazyInit().ReservedNames } +func (ed *Enum) ReservedRanges() pref.EnumRanges { return &ed.lazyInit().ReservedRanges } +func (ed *Enum) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, ed) } +func (ed *Enum) ProtoType(pref.EnumDescriptor) {} +func (ed *Enum) lazyInit() *EnumL2 { + ed.L0.ParentFile.lazyInit() // implicitly initializes L2 + return ed.L2 +} + +func (ed *EnumValue) Options() pref.ProtoMessage { + if f := ed.L1.Options; f != nil { + return f() + } + return descopts.EnumValue +} +func (ed *EnumValue) Number() pref.EnumNumber { return ed.L1.Number } +func (ed *EnumValue) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, ed) } +func (ed *EnumValue) ProtoType(pref.EnumValueDescriptor) {} + +type ( + Message struct { + Base + L1 MessageL1 + L2 *MessageL2 // protected by fileDesc.once + } + MessageL1 struct { + Enums Enums + Messages Messages + Extensions Extensions + IsMapEntry bool // promoted from google.protobuf.MessageOptions + IsMessageSet bool // promoted from google.protobuf.MessageOptions + } + MessageL2 struct { + Options func() pref.ProtoMessage + Fields Fields + Oneofs Oneofs + ReservedNames Names + ReservedRanges FieldRanges + RequiredNumbers FieldNumbers // must be consistent with Fields.Cardinality + ExtensionRanges FieldRanges + ExtensionRangeOptions []func() pref.ProtoMessage // must be same length as ExtensionRanges + } + + Field struct { + Base + L1 FieldL1 + } + FieldL1 struct { + Options func() pref.ProtoMessage + Number pref.FieldNumber + Cardinality pref.Cardinality // must be consistent with Message.RequiredNumbers + Kind pref.Kind + JSONName jsonName + IsProto3Optional bool // promoted from google.protobuf.FieldDescriptorProto + IsWeak bool // promoted from google.protobuf.FieldOptions + HasPacked bool // promoted from google.protobuf.FieldOptions + IsPacked bool // promoted from google.protobuf.FieldOptions + HasEnforceUTF8 bool // promoted from google.protobuf.FieldOptions + EnforceUTF8 bool // promoted from google.protobuf.FieldOptions + Default defaultValue + ContainingOneof pref.OneofDescriptor // must be consistent with Message.Oneofs.Fields + Enum pref.EnumDescriptor + Message pref.MessageDescriptor + } + + Oneof struct { + Base + L1 OneofL1 + } + OneofL1 struct { + Options func() pref.ProtoMessage + Fields OneofFields // must be consistent with Message.Fields.ContainingOneof + } +) + +func (md *Message) Options() pref.ProtoMessage { + if f := md.lazyInit().Options; f != nil { + return f() + } + return descopts.Message +} +func (md *Message) IsMapEntry() bool { return md.L1.IsMapEntry } +func (md *Message) Fields() pref.FieldDescriptors { return &md.lazyInit().Fields } +func (md *Message) Oneofs() pref.OneofDescriptors { return &md.lazyInit().Oneofs } +func (md *Message) ReservedNames() pref.Names { return &md.lazyInit().ReservedNames } +func (md *Message) ReservedRanges() pref.FieldRanges { return &md.lazyInit().ReservedRanges } +func (md *Message) RequiredNumbers() pref.FieldNumbers { return &md.lazyInit().RequiredNumbers } +func (md *Message) ExtensionRanges() pref.FieldRanges { return &md.lazyInit().ExtensionRanges } +func (md *Message) ExtensionRangeOptions(i int) pref.ProtoMessage { + if f := md.lazyInit().ExtensionRangeOptions[i]; f != nil { + return f() + } + return descopts.ExtensionRange +} +func (md *Message) Enums() pref.EnumDescriptors { return &md.L1.Enums } +func (md *Message) Messages() pref.MessageDescriptors { return &md.L1.Messages } +func (md *Message) Extensions() pref.ExtensionDescriptors { return &md.L1.Extensions } +func (md *Message) ProtoType(pref.MessageDescriptor) {} +func (md *Message) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, md) } +func (md *Message) lazyInit() *MessageL2 { + md.L0.ParentFile.lazyInit() // implicitly initializes L2 + return md.L2 +} + +// IsMessageSet is a pseudo-internal API for checking whether a message +// should serialize in the proto1 message format. +// +// WARNING: This method is exempt from the compatibility promise and may be +// removed in the future without warning. +func (md *Message) IsMessageSet() bool { + return md.L1.IsMessageSet +} + +func (fd *Field) Options() pref.ProtoMessage { + if f := fd.L1.Options; f != nil { + return f() + } + return descopts.Field +} +func (fd *Field) Number() pref.FieldNumber { return fd.L1.Number } +func (fd *Field) Cardinality() pref.Cardinality { return fd.L1.Cardinality } +func (fd *Field) Kind() pref.Kind { return fd.L1.Kind } +func (fd *Field) HasJSONName() bool { return fd.L1.JSONName.has } +func (fd *Field) JSONName() string { return fd.L1.JSONName.get(fd) } +func (fd *Field) HasPresence() bool { + return fd.L1.Cardinality != pref.Repeated && (fd.L0.ParentFile.L1.Syntax == pref.Proto2 || fd.L1.Message != nil || fd.L1.ContainingOneof != nil) +} +func (fd *Field) HasOptionalKeyword() bool { + return (fd.L0.ParentFile.L1.Syntax == pref.Proto2 && fd.L1.Cardinality == pref.Optional && fd.L1.ContainingOneof == nil) || fd.L1.IsProto3Optional +} +func (fd *Field) IsPacked() bool { + if !fd.L1.HasPacked && fd.L0.ParentFile.L1.Syntax != pref.Proto2 && fd.L1.Cardinality == pref.Repeated { + switch fd.L1.Kind { + case pref.StringKind, pref.BytesKind, pref.MessageKind, pref.GroupKind: + default: + return true + } + } + return fd.L1.IsPacked +} +func (fd *Field) IsExtension() bool { return false } +func (fd *Field) IsWeak() bool { return fd.L1.IsWeak } +func (fd *Field) IsList() bool { return fd.Cardinality() == pref.Repeated && !fd.IsMap() } +func (fd *Field) IsMap() bool { return fd.Message() != nil && fd.Message().IsMapEntry() } +func (fd *Field) MapKey() pref.FieldDescriptor { + if !fd.IsMap() { + return nil + } + return fd.Message().Fields().ByNumber(genid.MapEntry_Key_field_number) +} +func (fd *Field) MapValue() pref.FieldDescriptor { + if !fd.IsMap() { + return nil + } + return fd.Message().Fields().ByNumber(genid.MapEntry_Value_field_number) +} +func (fd *Field) HasDefault() bool { return fd.L1.Default.has } +func (fd *Field) Default() pref.Value { return fd.L1.Default.get(fd) } +func (fd *Field) DefaultEnumValue() pref.EnumValueDescriptor { return fd.L1.Default.enum } +func (fd *Field) ContainingOneof() pref.OneofDescriptor { return fd.L1.ContainingOneof } +func (fd *Field) ContainingMessage() pref.MessageDescriptor { + return fd.L0.Parent.(pref.MessageDescriptor) +} +func (fd *Field) Enum() pref.EnumDescriptor { + return fd.L1.Enum +} +func (fd *Field) Message() pref.MessageDescriptor { + if fd.L1.IsWeak { + if d, _ := protoregistry.GlobalFiles.FindDescriptorByName(fd.L1.Message.FullName()); d != nil { + return d.(pref.MessageDescriptor) + } + } + return fd.L1.Message +} +func (fd *Field) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, fd) } +func (fd *Field) ProtoType(pref.FieldDescriptor) {} + +// EnforceUTF8 is a pseudo-internal API to determine whether to enforce UTF-8 +// validation for the string field. This exists for Google-internal use only +// since proto3 did not enforce UTF-8 validity prior to the open-source release. +// If this method does not exist, the default is to enforce valid UTF-8. +// +// WARNING: This method is exempt from the compatibility promise and may be +// removed in the future without warning. +func (fd *Field) EnforceUTF8() bool { + if fd.L1.HasEnforceUTF8 { + return fd.L1.EnforceUTF8 + } + return fd.L0.ParentFile.L1.Syntax == pref.Proto3 +} + +func (od *Oneof) IsSynthetic() bool { + return od.L0.ParentFile.L1.Syntax == pref.Proto3 && len(od.L1.Fields.List) == 1 && od.L1.Fields.List[0].HasOptionalKeyword() +} +func (od *Oneof) Options() pref.ProtoMessage { + if f := od.L1.Options; f != nil { + return f() + } + return descopts.Oneof +} +func (od *Oneof) Fields() pref.FieldDescriptors { return &od.L1.Fields } +func (od *Oneof) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, od) } +func (od *Oneof) ProtoType(pref.OneofDescriptor) {} + +type ( + Extension struct { + Base + L1 ExtensionL1 + L2 *ExtensionL2 // protected by fileDesc.once + } + ExtensionL1 struct { + Number pref.FieldNumber + Extendee pref.MessageDescriptor + Cardinality pref.Cardinality + Kind pref.Kind + } + ExtensionL2 struct { + Options func() pref.ProtoMessage + JSONName jsonName + IsProto3Optional bool // promoted from google.protobuf.FieldDescriptorProto + IsPacked bool // promoted from google.protobuf.FieldOptions + Default defaultValue + Enum pref.EnumDescriptor + Message pref.MessageDescriptor + } +) + +func (xd *Extension) Options() pref.ProtoMessage { + if f := xd.lazyInit().Options; f != nil { + return f() + } + return descopts.Field +} +func (xd *Extension) Number() pref.FieldNumber { return xd.L1.Number } +func (xd *Extension) Cardinality() pref.Cardinality { return xd.L1.Cardinality } +func (xd *Extension) Kind() pref.Kind { return xd.L1.Kind } +func (xd *Extension) HasJSONName() bool { return xd.lazyInit().JSONName.has } +func (xd *Extension) JSONName() string { return xd.lazyInit().JSONName.get(xd) } +func (xd *Extension) HasPresence() bool { return xd.L1.Cardinality != pref.Repeated } +func (xd *Extension) HasOptionalKeyword() bool { + return (xd.L0.ParentFile.L1.Syntax == pref.Proto2 && xd.L1.Cardinality == pref.Optional) || xd.lazyInit().IsProto3Optional +} +func (xd *Extension) IsPacked() bool { return xd.lazyInit().IsPacked } +func (xd *Extension) IsExtension() bool { return true } +func (xd *Extension) IsWeak() bool { return false } +func (xd *Extension) IsList() bool { return xd.Cardinality() == pref.Repeated } +func (xd *Extension) IsMap() bool { return false } +func (xd *Extension) MapKey() pref.FieldDescriptor { return nil } +func (xd *Extension) MapValue() pref.FieldDescriptor { return nil } +func (xd *Extension) HasDefault() bool { return xd.lazyInit().Default.has } +func (xd *Extension) Default() pref.Value { return xd.lazyInit().Default.get(xd) } +func (xd *Extension) DefaultEnumValue() pref.EnumValueDescriptor { return xd.lazyInit().Default.enum } +func (xd *Extension) ContainingOneof() pref.OneofDescriptor { return nil } +func (xd *Extension) ContainingMessage() pref.MessageDescriptor { return xd.L1.Extendee } +func (xd *Extension) Enum() pref.EnumDescriptor { return xd.lazyInit().Enum } +func (xd *Extension) Message() pref.MessageDescriptor { return xd.lazyInit().Message } +func (xd *Extension) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, xd) } +func (xd *Extension) ProtoType(pref.FieldDescriptor) {} +func (xd *Extension) ProtoInternal(pragma.DoNotImplement) {} +func (xd *Extension) lazyInit() *ExtensionL2 { + xd.L0.ParentFile.lazyInit() // implicitly initializes L2 + return xd.L2 +} + +type ( + Service struct { + Base + L1 ServiceL1 + L2 *ServiceL2 // protected by fileDesc.once + } + ServiceL1 struct{} + ServiceL2 struct { + Options func() pref.ProtoMessage + Methods Methods + } + + Method struct { + Base + L1 MethodL1 + } + MethodL1 struct { + Options func() pref.ProtoMessage + Input pref.MessageDescriptor + Output pref.MessageDescriptor + IsStreamingClient bool + IsStreamingServer bool + } +) + +func (sd *Service) Options() pref.ProtoMessage { + if f := sd.lazyInit().Options; f != nil { + return f() + } + return descopts.Service +} +func (sd *Service) Methods() pref.MethodDescriptors { return &sd.lazyInit().Methods } +func (sd *Service) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, sd) } +func (sd *Service) ProtoType(pref.ServiceDescriptor) {} +func (sd *Service) ProtoInternal(pragma.DoNotImplement) {} +func (sd *Service) lazyInit() *ServiceL2 { + sd.L0.ParentFile.lazyInit() // implicitly initializes L2 + return sd.L2 +} + +func (md *Method) Options() pref.ProtoMessage { + if f := md.L1.Options; f != nil { + return f() + } + return descopts.Method +} +func (md *Method) Input() pref.MessageDescriptor { return md.L1.Input } +func (md *Method) Output() pref.MessageDescriptor { return md.L1.Output } +func (md *Method) IsStreamingClient() bool { return md.L1.IsStreamingClient } +func (md *Method) IsStreamingServer() bool { return md.L1.IsStreamingServer } +func (md *Method) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, md) } +func (md *Method) ProtoType(pref.MethodDescriptor) {} +func (md *Method) ProtoInternal(pragma.DoNotImplement) {} + +// Surrogate files are can be used to create standalone descriptors +// where the syntax is only information derived from the parent file. +var ( + SurrogateProto2 = &File{L1: FileL1{Syntax: pref.Proto2}, L2: &FileL2{}} + SurrogateProto3 = &File{L1: FileL1{Syntax: pref.Proto3}, L2: &FileL2{}} +) + +type ( + Base struct { + L0 BaseL0 + } + BaseL0 struct { + FullName pref.FullName // must be populated + ParentFile *File // must be populated + Parent pref.Descriptor + Index int + } +) + +func (d *Base) Name() pref.Name { return d.L0.FullName.Name() } +func (d *Base) FullName() pref.FullName { return d.L0.FullName } +func (d *Base) ParentFile() pref.FileDescriptor { + if d.L0.ParentFile == SurrogateProto2 || d.L0.ParentFile == SurrogateProto3 { + return nil // surrogate files are not real parents + } + return d.L0.ParentFile +} +func (d *Base) Parent() pref.Descriptor { return d.L0.Parent } +func (d *Base) Index() int { return d.L0.Index } +func (d *Base) Syntax() pref.Syntax { return d.L0.ParentFile.Syntax() } +func (d *Base) IsPlaceholder() bool { return false } +func (d *Base) ProtoInternal(pragma.DoNotImplement) {} + +type jsonName struct { + has bool + once sync.Once + name string +} + +// Init initializes the name. It is exported for use by other internal packages. +func (js *jsonName) Init(s string) { + js.has = true + js.name = s +} + +func (js *jsonName) get(fd pref.FieldDescriptor) string { + if !js.has { + js.once.Do(func() { + js.name = strs.JSONCamelCase(string(fd.Name())) + }) + } + return js.name +} + +func DefaultValue(v pref.Value, ev pref.EnumValueDescriptor) defaultValue { + dv := defaultValue{has: v.IsValid(), val: v, enum: ev} + if b, ok := v.Interface().([]byte); ok { + // Store a copy of the default bytes, so that we can detect + // accidental mutations of the original value. + dv.bytes = append([]byte(nil), b...) + } + return dv +} + +func unmarshalDefault(b []byte, k pref.Kind, pf *File, ed pref.EnumDescriptor) defaultValue { + var evs pref.EnumValueDescriptors + if k == pref.EnumKind { + // If the enum is declared within the same file, be careful not to + // blindly call the Values method, lest we bind ourselves in a deadlock. + if e, ok := ed.(*Enum); ok && e.L0.ParentFile == pf { + evs = &e.L2.Values + } else { + evs = ed.Values() + } + + // If we are unable to resolve the enum dependency, use a placeholder + // enum value since we will not be able to parse the default value. + if ed.IsPlaceholder() && pref.Name(b).IsValid() { + v := pref.ValueOfEnum(0) + ev := PlaceholderEnumValue(ed.FullName().Parent().Append(pref.Name(b))) + return DefaultValue(v, ev) + } + } + + v, ev, err := defval.Unmarshal(string(b), k, evs, defval.Descriptor) + if err != nil { + panic(err) + } + return DefaultValue(v, ev) +} + +type defaultValue struct { + has bool + val pref.Value + enum pref.EnumValueDescriptor + bytes []byte +} + +func (dv *defaultValue) get(fd pref.FieldDescriptor) pref.Value { + // Return the zero value as the default if unpopulated. + if !dv.has { + if fd.Cardinality() == pref.Repeated { + return pref.Value{} + } + switch fd.Kind() { + case pref.BoolKind: + return pref.ValueOfBool(false) + case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind: + return pref.ValueOfInt32(0) + case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind: + return pref.ValueOfInt64(0) + case pref.Uint32Kind, pref.Fixed32Kind: + return pref.ValueOfUint32(0) + case pref.Uint64Kind, pref.Fixed64Kind: + return pref.ValueOfUint64(0) + case pref.FloatKind: + return pref.ValueOfFloat32(0) + case pref.DoubleKind: + return pref.ValueOfFloat64(0) + case pref.StringKind: + return pref.ValueOfString("") + case pref.BytesKind: + return pref.ValueOfBytes(nil) + case pref.EnumKind: + if evs := fd.Enum().Values(); evs.Len() > 0 { + return pref.ValueOfEnum(evs.Get(0).Number()) + } + return pref.ValueOfEnum(0) + } + } + + if len(dv.bytes) > 0 && !bytes.Equal(dv.bytes, dv.val.Bytes()) { + // TODO: Avoid panic if we're running with the race detector + // and instead spawn a goroutine that periodically resets + // this value back to the original to induce a race. + panic(fmt.Sprintf("detected mutation on the default bytes for %v", fd.FullName())) + } + return dv.val +} diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go new file mode 100644 index 00000000000..66e1fee5224 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.go @@ -0,0 +1,471 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package filedesc + +import ( + "sync" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/strs" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +// fileRaw is a data struct used when initializing a file descriptor from +// a raw FileDescriptorProto. +type fileRaw struct { + builder Builder + allEnums []Enum + allMessages []Message + allExtensions []Extension + allServices []Service +} + +func newRawFile(db Builder) *File { + fd := &File{fileRaw: fileRaw{builder: db}} + fd.initDecls(db.NumEnums, db.NumMessages, db.NumExtensions, db.NumServices) + fd.unmarshalSeed(db.RawDescriptor) + + // Extended message targets are eagerly resolved since registration + // needs this information at program init time. + for i := range fd.allExtensions { + xd := &fd.allExtensions[i] + xd.L1.Extendee = fd.resolveMessageDependency(xd.L1.Extendee, listExtTargets, int32(i)) + } + + fd.checkDecls() + return fd +} + +// initDecls pre-allocates slices for the exact number of enums, messages +// (including map entries), extensions, and services declared in the proto file. +// This is done to avoid regrowing the slice, which would change the address +// for any previously seen declaration. +// +// The alloc methods "allocates" slices by pulling from the capacity. +func (fd *File) initDecls(numEnums, numMessages, numExtensions, numServices int32) { + fd.allEnums = make([]Enum, 0, numEnums) + fd.allMessages = make([]Message, 0, numMessages) + fd.allExtensions = make([]Extension, 0, numExtensions) + fd.allServices = make([]Service, 0, numServices) +} + +func (fd *File) allocEnums(n int) []Enum { + total := len(fd.allEnums) + es := fd.allEnums[total : total+n] + fd.allEnums = fd.allEnums[:total+n] + return es +} +func (fd *File) allocMessages(n int) []Message { + total := len(fd.allMessages) + ms := fd.allMessages[total : total+n] + fd.allMessages = fd.allMessages[:total+n] + return ms +} +func (fd *File) allocExtensions(n int) []Extension { + total := len(fd.allExtensions) + xs := fd.allExtensions[total : total+n] + fd.allExtensions = fd.allExtensions[:total+n] + return xs +} +func (fd *File) allocServices(n int) []Service { + total := len(fd.allServices) + xs := fd.allServices[total : total+n] + fd.allServices = fd.allServices[:total+n] + return xs +} + +// checkDecls performs a sanity check that the expected number of expected +// declarations matches the number that were found in the descriptor proto. +func (fd *File) checkDecls() { + switch { + case len(fd.allEnums) != cap(fd.allEnums): + case len(fd.allMessages) != cap(fd.allMessages): + case len(fd.allExtensions) != cap(fd.allExtensions): + case len(fd.allServices) != cap(fd.allServices): + default: + return + } + panic("mismatching cardinality") +} + +func (fd *File) unmarshalSeed(b []byte) { + sb := getBuilder() + defer putBuilder(sb) + + var prevField pref.FieldNumber + var numEnums, numMessages, numExtensions, numServices int + var posEnums, posMessages, posExtensions, posServices int + b0 := b + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.FileDescriptorProto_Syntax_field_number: + switch string(v) { + case "proto2": + fd.L1.Syntax = pref.Proto2 + case "proto3": + fd.L1.Syntax = pref.Proto3 + default: + panic("invalid syntax") + } + case genid.FileDescriptorProto_Name_field_number: + fd.L1.Path = sb.MakeString(v) + case genid.FileDescriptorProto_Package_field_number: + fd.L1.Package = pref.FullName(sb.MakeString(v)) + case genid.FileDescriptorProto_EnumType_field_number: + if prevField != genid.FileDescriptorProto_EnumType_field_number { + if numEnums > 0 { + panic("non-contiguous repeated field") + } + posEnums = len(b0) - len(b) - n - m + } + numEnums++ + case genid.FileDescriptorProto_MessageType_field_number: + if prevField != genid.FileDescriptorProto_MessageType_field_number { + if numMessages > 0 { + panic("non-contiguous repeated field") + } + posMessages = len(b0) - len(b) - n - m + } + numMessages++ + case genid.FileDescriptorProto_Extension_field_number: + if prevField != genid.FileDescriptorProto_Extension_field_number { + if numExtensions > 0 { + panic("non-contiguous repeated field") + } + posExtensions = len(b0) - len(b) - n - m + } + numExtensions++ + case genid.FileDescriptorProto_Service_field_number: + if prevField != genid.FileDescriptorProto_Service_field_number { + if numServices > 0 { + panic("non-contiguous repeated field") + } + posServices = len(b0) - len(b) - n - m + } + numServices++ + } + prevField = num + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + prevField = -1 // ignore known field numbers of unknown wire type + } + } + + // If syntax is missing, it is assumed to be proto2. + if fd.L1.Syntax == 0 { + fd.L1.Syntax = pref.Proto2 + } + + // Must allocate all declarations before parsing each descriptor type + // to ensure we handled all descriptors in "flattened ordering". + if numEnums > 0 { + fd.L1.Enums.List = fd.allocEnums(numEnums) + } + if numMessages > 0 { + fd.L1.Messages.List = fd.allocMessages(numMessages) + } + if numExtensions > 0 { + fd.L1.Extensions.List = fd.allocExtensions(numExtensions) + } + if numServices > 0 { + fd.L1.Services.List = fd.allocServices(numServices) + } + + if numEnums > 0 { + b := b0[posEnums:] + for i := range fd.L1.Enums.List { + _, n := protowire.ConsumeVarint(b) + v, m := protowire.ConsumeBytes(b[n:]) + fd.L1.Enums.List[i].unmarshalSeed(v, sb, fd, fd, i) + b = b[n+m:] + } + } + if numMessages > 0 { + b := b0[posMessages:] + for i := range fd.L1.Messages.List { + _, n := protowire.ConsumeVarint(b) + v, m := protowire.ConsumeBytes(b[n:]) + fd.L1.Messages.List[i].unmarshalSeed(v, sb, fd, fd, i) + b = b[n+m:] + } + } + if numExtensions > 0 { + b := b0[posExtensions:] + for i := range fd.L1.Extensions.List { + _, n := protowire.ConsumeVarint(b) + v, m := protowire.ConsumeBytes(b[n:]) + fd.L1.Extensions.List[i].unmarshalSeed(v, sb, fd, fd, i) + b = b[n+m:] + } + } + if numServices > 0 { + b := b0[posServices:] + for i := range fd.L1.Services.List { + _, n := protowire.ConsumeVarint(b) + v, m := protowire.ConsumeBytes(b[n:]) + fd.L1.Services.List[i].unmarshalSeed(v, sb, fd, fd, i) + b = b[n+m:] + } + } +} + +func (ed *Enum) unmarshalSeed(b []byte, sb *strs.Builder, pf *File, pd pref.Descriptor, i int) { + ed.L0.ParentFile = pf + ed.L0.Parent = pd + ed.L0.Index = i + + var numValues int + for b := b; len(b) > 0; { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.EnumDescriptorProto_Name_field_number: + ed.L0.FullName = appendFullName(sb, pd.FullName(), v) + case genid.EnumDescriptorProto_Value_field_number: + numValues++ + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + + // Only construct enum value descriptors for top-level enums since + // they are needed for registration. + if pd != pf { + return + } + ed.L1.eagerValues = true + ed.L2 = new(EnumL2) + ed.L2.Values.List = make([]EnumValue, numValues) + for i := 0; len(b) > 0; { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.EnumDescriptorProto_Value_field_number: + ed.L2.Values.List[i].unmarshalFull(v, sb, pf, ed, i) + i++ + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } +} + +func (md *Message) unmarshalSeed(b []byte, sb *strs.Builder, pf *File, pd pref.Descriptor, i int) { + md.L0.ParentFile = pf + md.L0.Parent = pd + md.L0.Index = i + + var prevField pref.FieldNumber + var numEnums, numMessages, numExtensions int + var posEnums, posMessages, posExtensions int + b0 := b + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.DescriptorProto_Name_field_number: + md.L0.FullName = appendFullName(sb, pd.FullName(), v) + case genid.DescriptorProto_EnumType_field_number: + if prevField != genid.DescriptorProto_EnumType_field_number { + if numEnums > 0 { + panic("non-contiguous repeated field") + } + posEnums = len(b0) - len(b) - n - m + } + numEnums++ + case genid.DescriptorProto_NestedType_field_number: + if prevField != genid.DescriptorProto_NestedType_field_number { + if numMessages > 0 { + panic("non-contiguous repeated field") + } + posMessages = len(b0) - len(b) - n - m + } + numMessages++ + case genid.DescriptorProto_Extension_field_number: + if prevField != genid.DescriptorProto_Extension_field_number { + if numExtensions > 0 { + panic("non-contiguous repeated field") + } + posExtensions = len(b0) - len(b) - n - m + } + numExtensions++ + case genid.DescriptorProto_Options_field_number: + md.unmarshalSeedOptions(v) + } + prevField = num + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + prevField = -1 // ignore known field numbers of unknown wire type + } + } + + // Must allocate all declarations before parsing each descriptor type + // to ensure we handled all descriptors in "flattened ordering". + if numEnums > 0 { + md.L1.Enums.List = pf.allocEnums(numEnums) + } + if numMessages > 0 { + md.L1.Messages.List = pf.allocMessages(numMessages) + } + if numExtensions > 0 { + md.L1.Extensions.List = pf.allocExtensions(numExtensions) + } + + if numEnums > 0 { + b := b0[posEnums:] + for i := range md.L1.Enums.List { + _, n := protowire.ConsumeVarint(b) + v, m := protowire.ConsumeBytes(b[n:]) + md.L1.Enums.List[i].unmarshalSeed(v, sb, pf, md, i) + b = b[n+m:] + } + } + if numMessages > 0 { + b := b0[posMessages:] + for i := range md.L1.Messages.List { + _, n := protowire.ConsumeVarint(b) + v, m := protowire.ConsumeBytes(b[n:]) + md.L1.Messages.List[i].unmarshalSeed(v, sb, pf, md, i) + b = b[n+m:] + } + } + if numExtensions > 0 { + b := b0[posExtensions:] + for i := range md.L1.Extensions.List { + _, n := protowire.ConsumeVarint(b) + v, m := protowire.ConsumeBytes(b[n:]) + md.L1.Extensions.List[i].unmarshalSeed(v, sb, pf, md, i) + b = b[n+m:] + } + } +} + +func (md *Message) unmarshalSeedOptions(b []byte) { + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.MessageOptions_MapEntry_field_number: + md.L1.IsMapEntry = protowire.DecodeBool(v) + case genid.MessageOptions_MessageSetWireFormat_field_number: + md.L1.IsMessageSet = protowire.DecodeBool(v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } +} + +func (xd *Extension) unmarshalSeed(b []byte, sb *strs.Builder, pf *File, pd pref.Descriptor, i int) { + xd.L0.ParentFile = pf + xd.L0.Parent = pd + xd.L0.Index = i + + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.FieldDescriptorProto_Number_field_number: + xd.L1.Number = pref.FieldNumber(v) + case genid.FieldDescriptorProto_Label_field_number: + xd.L1.Cardinality = pref.Cardinality(v) + case genid.FieldDescriptorProto_Type_field_number: + xd.L1.Kind = pref.Kind(v) + } + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.FieldDescriptorProto_Name_field_number: + xd.L0.FullName = appendFullName(sb, pd.FullName(), v) + case genid.FieldDescriptorProto_Extendee_field_number: + xd.L1.Extendee = PlaceholderMessage(makeFullName(sb, v)) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } +} + +func (sd *Service) unmarshalSeed(b []byte, sb *strs.Builder, pf *File, pd pref.Descriptor, i int) { + sd.L0.ParentFile = pf + sd.L0.Parent = pd + sd.L0.Index = i + + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.ServiceDescriptorProto_Name_field_number: + sd.L0.FullName = appendFullName(sb, pd.FullName(), v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } +} + +var nameBuilderPool = sync.Pool{ + New: func() interface{} { return new(strs.Builder) }, +} + +func getBuilder() *strs.Builder { + return nameBuilderPool.Get().(*strs.Builder) +} +func putBuilder(b *strs.Builder) { + nameBuilderPool.Put(b) +} + +// makeFullName converts b to a protoreflect.FullName, +// where b must start with a leading dot. +func makeFullName(sb *strs.Builder, b []byte) pref.FullName { + if len(b) == 0 || b[0] != '.' { + panic("name reference must be fully qualified") + } + return pref.FullName(sb.MakeString(b[1:])) +} + +func appendFullName(sb *strs.Builder, prefix pref.FullName, suffix []byte) pref.FullName { + return sb.AppendFullName(prefix, pref.Name(strs.UnsafeString(suffix))) +} diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go new file mode 100644 index 00000000000..e672233e77e --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go @@ -0,0 +1,704 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package filedesc + +import ( + "reflect" + "sync" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/descopts" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/proto" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +func (fd *File) lazyRawInit() { + fd.unmarshalFull(fd.builder.RawDescriptor) + fd.resolveMessages() + fd.resolveExtensions() + fd.resolveServices() +} + +func (file *File) resolveMessages() { + var depIdx int32 + for i := range file.allMessages { + md := &file.allMessages[i] + + // Resolve message field dependencies. + for j := range md.L2.Fields.List { + fd := &md.L2.Fields.List[j] + + // Weak fields are resolved upon actual use. + if fd.L1.IsWeak { + continue + } + + // Resolve message field dependency. + switch fd.L1.Kind { + case pref.EnumKind: + fd.L1.Enum = file.resolveEnumDependency(fd.L1.Enum, listFieldDeps, depIdx) + depIdx++ + case pref.MessageKind, pref.GroupKind: + fd.L1.Message = file.resolveMessageDependency(fd.L1.Message, listFieldDeps, depIdx) + depIdx++ + } + + // Default is resolved here since it depends on Enum being resolved. + if v := fd.L1.Default.val; v.IsValid() { + fd.L1.Default = unmarshalDefault(v.Bytes(), fd.L1.Kind, file, fd.L1.Enum) + } + } + } +} + +func (file *File) resolveExtensions() { + var depIdx int32 + for i := range file.allExtensions { + xd := &file.allExtensions[i] + + // Resolve extension field dependency. + switch xd.L1.Kind { + case pref.EnumKind: + xd.L2.Enum = file.resolveEnumDependency(xd.L2.Enum, listExtDeps, depIdx) + depIdx++ + case pref.MessageKind, pref.GroupKind: + xd.L2.Message = file.resolveMessageDependency(xd.L2.Message, listExtDeps, depIdx) + depIdx++ + } + + // Default is resolved here since it depends on Enum being resolved. + if v := xd.L2.Default.val; v.IsValid() { + xd.L2.Default = unmarshalDefault(v.Bytes(), xd.L1.Kind, file, xd.L2.Enum) + } + } +} + +func (file *File) resolveServices() { + var depIdx int32 + for i := range file.allServices { + sd := &file.allServices[i] + + // Resolve method dependencies. + for j := range sd.L2.Methods.List { + md := &sd.L2.Methods.List[j] + md.L1.Input = file.resolveMessageDependency(md.L1.Input, listMethInDeps, depIdx) + md.L1.Output = file.resolveMessageDependency(md.L1.Output, listMethOutDeps, depIdx) + depIdx++ + } + } +} + +func (file *File) resolveEnumDependency(ed pref.EnumDescriptor, i, j int32) pref.EnumDescriptor { + r := file.builder.FileRegistry + if r, ok := r.(resolverByIndex); ok { + if ed2 := r.FindEnumByIndex(i, j, file.allEnums, file.allMessages); ed2 != nil { + return ed2 + } + } + for i := range file.allEnums { + if ed2 := &file.allEnums[i]; ed2.L0.FullName == ed.FullName() { + return ed2 + } + } + if d, _ := r.FindDescriptorByName(ed.FullName()); d != nil { + return d.(pref.EnumDescriptor) + } + return ed +} + +func (file *File) resolveMessageDependency(md pref.MessageDescriptor, i, j int32) pref.MessageDescriptor { + r := file.builder.FileRegistry + if r, ok := r.(resolverByIndex); ok { + if md2 := r.FindMessageByIndex(i, j, file.allEnums, file.allMessages); md2 != nil { + return md2 + } + } + for i := range file.allMessages { + if md2 := &file.allMessages[i]; md2.L0.FullName == md.FullName() { + return md2 + } + } + if d, _ := r.FindDescriptorByName(md.FullName()); d != nil { + return d.(pref.MessageDescriptor) + } + return md +} + +func (fd *File) unmarshalFull(b []byte) { + sb := getBuilder() + defer putBuilder(sb) + + var enumIdx, messageIdx, extensionIdx, serviceIdx int + var rawOptions []byte + fd.L2 = new(FileL2) + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.FileDescriptorProto_PublicDependency_field_number: + fd.L2.Imports[v].IsPublic = true + case genid.FileDescriptorProto_WeakDependency_field_number: + fd.L2.Imports[v].IsWeak = true + } + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.FileDescriptorProto_Dependency_field_number: + path := sb.MakeString(v) + imp, _ := fd.builder.FileRegistry.FindFileByPath(path) + if imp == nil { + imp = PlaceholderFile(path) + } + fd.L2.Imports = append(fd.L2.Imports, pref.FileImport{FileDescriptor: imp}) + case genid.FileDescriptorProto_EnumType_field_number: + fd.L1.Enums.List[enumIdx].unmarshalFull(v, sb) + enumIdx++ + case genid.FileDescriptorProto_MessageType_field_number: + fd.L1.Messages.List[messageIdx].unmarshalFull(v, sb) + messageIdx++ + case genid.FileDescriptorProto_Extension_field_number: + fd.L1.Extensions.List[extensionIdx].unmarshalFull(v, sb) + extensionIdx++ + case genid.FileDescriptorProto_Service_field_number: + fd.L1.Services.List[serviceIdx].unmarshalFull(v, sb) + serviceIdx++ + case genid.FileDescriptorProto_Options_field_number: + rawOptions = appendOptions(rawOptions, v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + fd.L2.Options = fd.builder.optionsUnmarshaler(&descopts.File, rawOptions) +} + +func (ed *Enum) unmarshalFull(b []byte, sb *strs.Builder) { + var rawValues [][]byte + var rawOptions []byte + if !ed.L1.eagerValues { + ed.L2 = new(EnumL2) + } + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.EnumDescriptorProto_Value_field_number: + rawValues = append(rawValues, v) + case genid.EnumDescriptorProto_ReservedName_field_number: + ed.L2.ReservedNames.List = append(ed.L2.ReservedNames.List, pref.Name(sb.MakeString(v))) + case genid.EnumDescriptorProto_ReservedRange_field_number: + ed.L2.ReservedRanges.List = append(ed.L2.ReservedRanges.List, unmarshalEnumReservedRange(v)) + case genid.EnumDescriptorProto_Options_field_number: + rawOptions = appendOptions(rawOptions, v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + if !ed.L1.eagerValues && len(rawValues) > 0 { + ed.L2.Values.List = make([]EnumValue, len(rawValues)) + for i, b := range rawValues { + ed.L2.Values.List[i].unmarshalFull(b, sb, ed.L0.ParentFile, ed, i) + } + } + ed.L2.Options = ed.L0.ParentFile.builder.optionsUnmarshaler(&descopts.Enum, rawOptions) +} + +func unmarshalEnumReservedRange(b []byte) (r [2]pref.EnumNumber) { + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.EnumDescriptorProto_EnumReservedRange_Start_field_number: + r[0] = pref.EnumNumber(v) + case genid.EnumDescriptorProto_EnumReservedRange_End_field_number: + r[1] = pref.EnumNumber(v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + return r +} + +func (vd *EnumValue) unmarshalFull(b []byte, sb *strs.Builder, pf *File, pd pref.Descriptor, i int) { + vd.L0.ParentFile = pf + vd.L0.Parent = pd + vd.L0.Index = i + + var rawOptions []byte + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.EnumValueDescriptorProto_Number_field_number: + vd.L1.Number = pref.EnumNumber(v) + } + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.EnumValueDescriptorProto_Name_field_number: + // NOTE: Enum values are in the same scope as the enum parent. + vd.L0.FullName = appendFullName(sb, pd.Parent().FullName(), v) + case genid.EnumValueDescriptorProto_Options_field_number: + rawOptions = appendOptions(rawOptions, v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + vd.L1.Options = pf.builder.optionsUnmarshaler(&descopts.EnumValue, rawOptions) +} + +func (md *Message) unmarshalFull(b []byte, sb *strs.Builder) { + var rawFields, rawOneofs [][]byte + var enumIdx, messageIdx, extensionIdx int + var rawOptions []byte + md.L2 = new(MessageL2) + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.DescriptorProto_Field_field_number: + rawFields = append(rawFields, v) + case genid.DescriptorProto_OneofDecl_field_number: + rawOneofs = append(rawOneofs, v) + case genid.DescriptorProto_ReservedName_field_number: + md.L2.ReservedNames.List = append(md.L2.ReservedNames.List, pref.Name(sb.MakeString(v))) + case genid.DescriptorProto_ReservedRange_field_number: + md.L2.ReservedRanges.List = append(md.L2.ReservedRanges.List, unmarshalMessageReservedRange(v)) + case genid.DescriptorProto_ExtensionRange_field_number: + r, rawOptions := unmarshalMessageExtensionRange(v) + opts := md.L0.ParentFile.builder.optionsUnmarshaler(&descopts.ExtensionRange, rawOptions) + md.L2.ExtensionRanges.List = append(md.L2.ExtensionRanges.List, r) + md.L2.ExtensionRangeOptions = append(md.L2.ExtensionRangeOptions, opts) + case genid.DescriptorProto_EnumType_field_number: + md.L1.Enums.List[enumIdx].unmarshalFull(v, sb) + enumIdx++ + case genid.DescriptorProto_NestedType_field_number: + md.L1.Messages.List[messageIdx].unmarshalFull(v, sb) + messageIdx++ + case genid.DescriptorProto_Extension_field_number: + md.L1.Extensions.List[extensionIdx].unmarshalFull(v, sb) + extensionIdx++ + case genid.DescriptorProto_Options_field_number: + md.unmarshalOptions(v) + rawOptions = appendOptions(rawOptions, v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + if len(rawFields) > 0 || len(rawOneofs) > 0 { + md.L2.Fields.List = make([]Field, len(rawFields)) + md.L2.Oneofs.List = make([]Oneof, len(rawOneofs)) + for i, b := range rawFields { + fd := &md.L2.Fields.List[i] + fd.unmarshalFull(b, sb, md.L0.ParentFile, md, i) + if fd.L1.Cardinality == pref.Required { + md.L2.RequiredNumbers.List = append(md.L2.RequiredNumbers.List, fd.L1.Number) + } + } + for i, b := range rawOneofs { + od := &md.L2.Oneofs.List[i] + od.unmarshalFull(b, sb, md.L0.ParentFile, md, i) + } + } + md.L2.Options = md.L0.ParentFile.builder.optionsUnmarshaler(&descopts.Message, rawOptions) +} + +func (md *Message) unmarshalOptions(b []byte) { + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.MessageOptions_MapEntry_field_number: + md.L1.IsMapEntry = protowire.DecodeBool(v) + case genid.MessageOptions_MessageSetWireFormat_field_number: + md.L1.IsMessageSet = protowire.DecodeBool(v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } +} + +func unmarshalMessageReservedRange(b []byte) (r [2]pref.FieldNumber) { + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.DescriptorProto_ReservedRange_Start_field_number: + r[0] = pref.FieldNumber(v) + case genid.DescriptorProto_ReservedRange_End_field_number: + r[1] = pref.FieldNumber(v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + return r +} + +func unmarshalMessageExtensionRange(b []byte) (r [2]pref.FieldNumber, rawOptions []byte) { + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.DescriptorProto_ExtensionRange_Start_field_number: + r[0] = pref.FieldNumber(v) + case genid.DescriptorProto_ExtensionRange_End_field_number: + r[1] = pref.FieldNumber(v) + } + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.DescriptorProto_ExtensionRange_Options_field_number: + rawOptions = appendOptions(rawOptions, v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + return r, rawOptions +} + +func (fd *Field) unmarshalFull(b []byte, sb *strs.Builder, pf *File, pd pref.Descriptor, i int) { + fd.L0.ParentFile = pf + fd.L0.Parent = pd + fd.L0.Index = i + + var rawTypeName []byte + var rawOptions []byte + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.FieldDescriptorProto_Number_field_number: + fd.L1.Number = pref.FieldNumber(v) + case genid.FieldDescriptorProto_Label_field_number: + fd.L1.Cardinality = pref.Cardinality(v) + case genid.FieldDescriptorProto_Type_field_number: + fd.L1.Kind = pref.Kind(v) + case genid.FieldDescriptorProto_OneofIndex_field_number: + // In Message.unmarshalFull, we allocate slices for both + // the field and oneof descriptors before unmarshaling either + // of them. This ensures pointers to slice elements are stable. + od := &pd.(*Message).L2.Oneofs.List[v] + od.L1.Fields.List = append(od.L1.Fields.List, fd) + if fd.L1.ContainingOneof != nil { + panic("oneof type already set") + } + fd.L1.ContainingOneof = od + case genid.FieldDescriptorProto_Proto3Optional_field_number: + fd.L1.IsProto3Optional = protowire.DecodeBool(v) + } + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.FieldDescriptorProto_Name_field_number: + fd.L0.FullName = appendFullName(sb, pd.FullName(), v) + case genid.FieldDescriptorProto_JsonName_field_number: + fd.L1.JSONName.Init(sb.MakeString(v)) + case genid.FieldDescriptorProto_DefaultValue_field_number: + fd.L1.Default.val = pref.ValueOfBytes(v) // temporarily store as bytes; later resolved in resolveMessages + case genid.FieldDescriptorProto_TypeName_field_number: + rawTypeName = v + case genid.FieldDescriptorProto_Options_field_number: + fd.unmarshalOptions(v) + rawOptions = appendOptions(rawOptions, v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + if rawTypeName != nil { + name := makeFullName(sb, rawTypeName) + switch fd.L1.Kind { + case pref.EnumKind: + fd.L1.Enum = PlaceholderEnum(name) + case pref.MessageKind, pref.GroupKind: + fd.L1.Message = PlaceholderMessage(name) + } + } + fd.L1.Options = pf.builder.optionsUnmarshaler(&descopts.Field, rawOptions) +} + +func (fd *Field) unmarshalOptions(b []byte) { + const FieldOptions_EnforceUTF8 = 13 + + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.FieldOptions_Packed_field_number: + fd.L1.HasPacked = true + fd.L1.IsPacked = protowire.DecodeBool(v) + case genid.FieldOptions_Weak_field_number: + fd.L1.IsWeak = protowire.DecodeBool(v) + case FieldOptions_EnforceUTF8: + fd.L1.HasEnforceUTF8 = true + fd.L1.EnforceUTF8 = protowire.DecodeBool(v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } +} + +func (od *Oneof) unmarshalFull(b []byte, sb *strs.Builder, pf *File, pd pref.Descriptor, i int) { + od.L0.ParentFile = pf + od.L0.Parent = pd + od.L0.Index = i + + var rawOptions []byte + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.OneofDescriptorProto_Name_field_number: + od.L0.FullName = appendFullName(sb, pd.FullName(), v) + case genid.OneofDescriptorProto_Options_field_number: + rawOptions = appendOptions(rawOptions, v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + od.L1.Options = pf.builder.optionsUnmarshaler(&descopts.Oneof, rawOptions) +} + +func (xd *Extension) unmarshalFull(b []byte, sb *strs.Builder) { + var rawTypeName []byte + var rawOptions []byte + xd.L2 = new(ExtensionL2) + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.FieldDescriptorProto_Proto3Optional_field_number: + xd.L2.IsProto3Optional = protowire.DecodeBool(v) + } + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.FieldDescriptorProto_JsonName_field_number: + xd.L2.JSONName.Init(sb.MakeString(v)) + case genid.FieldDescriptorProto_DefaultValue_field_number: + xd.L2.Default.val = pref.ValueOfBytes(v) // temporarily store as bytes; later resolved in resolveExtensions + case genid.FieldDescriptorProto_TypeName_field_number: + rawTypeName = v + case genid.FieldDescriptorProto_Options_field_number: + xd.unmarshalOptions(v) + rawOptions = appendOptions(rawOptions, v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + if rawTypeName != nil { + name := makeFullName(sb, rawTypeName) + switch xd.L1.Kind { + case pref.EnumKind: + xd.L2.Enum = PlaceholderEnum(name) + case pref.MessageKind, pref.GroupKind: + xd.L2.Message = PlaceholderMessage(name) + } + } + xd.L2.Options = xd.L0.ParentFile.builder.optionsUnmarshaler(&descopts.Field, rawOptions) +} + +func (xd *Extension) unmarshalOptions(b []byte) { + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.FieldOptions_Packed_field_number: + xd.L2.IsPacked = protowire.DecodeBool(v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } +} + +func (sd *Service) unmarshalFull(b []byte, sb *strs.Builder) { + var rawMethods [][]byte + var rawOptions []byte + sd.L2 = new(ServiceL2) + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.ServiceDescriptorProto_Method_field_number: + rawMethods = append(rawMethods, v) + case genid.ServiceDescriptorProto_Options_field_number: + rawOptions = appendOptions(rawOptions, v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + if len(rawMethods) > 0 { + sd.L2.Methods.List = make([]Method, len(rawMethods)) + for i, b := range rawMethods { + sd.L2.Methods.List[i].unmarshalFull(b, sb, sd.L0.ParentFile, sd, i) + } + } + sd.L2.Options = sd.L0.ParentFile.builder.optionsUnmarshaler(&descopts.Service, rawOptions) +} + +func (md *Method) unmarshalFull(b []byte, sb *strs.Builder, pf *File, pd pref.Descriptor, i int) { + md.L0.ParentFile = pf + md.L0.Parent = pd + md.L0.Index = i + + var rawOptions []byte + for len(b) > 0 { + num, typ, n := protowire.ConsumeTag(b) + b = b[n:] + switch typ { + case protowire.VarintType: + v, m := protowire.ConsumeVarint(b) + b = b[m:] + switch num { + case genid.MethodDescriptorProto_ClientStreaming_field_number: + md.L1.IsStreamingClient = protowire.DecodeBool(v) + case genid.MethodDescriptorProto_ServerStreaming_field_number: + md.L1.IsStreamingServer = protowire.DecodeBool(v) + } + case protowire.BytesType: + v, m := protowire.ConsumeBytes(b) + b = b[m:] + switch num { + case genid.MethodDescriptorProto_Name_field_number: + md.L0.FullName = appendFullName(sb, pd.FullName(), v) + case genid.MethodDescriptorProto_InputType_field_number: + md.L1.Input = PlaceholderMessage(makeFullName(sb, v)) + case genid.MethodDescriptorProto_OutputType_field_number: + md.L1.Output = PlaceholderMessage(makeFullName(sb, v)) + case genid.MethodDescriptorProto_Options_field_number: + rawOptions = appendOptions(rawOptions, v) + } + default: + m := protowire.ConsumeFieldValue(num, typ, b) + b = b[m:] + } + } + md.L1.Options = pf.builder.optionsUnmarshaler(&descopts.Method, rawOptions) +} + +// appendOptions appends src to dst, where the returned slice is never nil. +// This is necessary to distinguish between empty and unpopulated options. +func appendOptions(dst, src []byte) []byte { + if dst == nil { + dst = []byte{} + } + return append(dst, src...) +} + +// optionsUnmarshaler constructs a lazy unmarshal function for an options message. +// +// The type of message to unmarshal to is passed as a pointer since the +// vars in descopts may not yet be populated at the time this function is called. +func (db *Builder) optionsUnmarshaler(p *pref.ProtoMessage, b []byte) func() pref.ProtoMessage { + if b == nil { + return nil + } + var opts pref.ProtoMessage + var once sync.Once + return func() pref.ProtoMessage { + once.Do(func() { + if *p == nil { + panic("Descriptor.Options called without importing the descriptor package") + } + opts = reflect.New(reflect.TypeOf(*p).Elem()).Interface().(pref.ProtoMessage) + if err := (proto.UnmarshalOptions{ + AllowPartial: true, + Resolver: db.TypeResolver, + }).Unmarshal(b, opts); err != nil { + panic(err) + } + }) + return opts + } +} diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc_list.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc_list.go new file mode 100644 index 00000000000..c876cd34d70 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc_list.go @@ -0,0 +1,282 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package filedesc + +import ( + "fmt" + "sort" + "sync" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/descfmt" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/reflect/protoreflect" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +type FileImports []pref.FileImport + +func (p *FileImports) Len() int { return len(*p) } +func (p *FileImports) Get(i int) pref.FileImport { return (*p)[i] } +func (p *FileImports) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } +func (p *FileImports) ProtoInternal(pragma.DoNotImplement) {} + +type Names struct { + List []pref.Name + once sync.Once + has map[pref.Name]int // protected by once +} + +func (p *Names) Len() int { return len(p.List) } +func (p *Names) Get(i int) pref.Name { return p.List[i] } +func (p *Names) Has(s pref.Name) bool { return p.lazyInit().has[s] > 0 } +func (p *Names) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } +func (p *Names) ProtoInternal(pragma.DoNotImplement) {} +func (p *Names) lazyInit() *Names { + p.once.Do(func() { + if len(p.List) > 0 { + p.has = make(map[pref.Name]int, len(p.List)) + for _, s := range p.List { + p.has[s] = p.has[s] + 1 + } + } + }) + return p +} + +// CheckValid reports any errors with the set of names with an error message +// that completes the sentence: "ranges is invalid because it has ..." +func (p *Names) CheckValid() error { + for s, n := range p.lazyInit().has { + switch { + case n > 1: + return errors.New("duplicate name: %q", s) + case false && !s.IsValid(): + // NOTE: The C++ implementation does not validate the identifier. + // See https://github.com/protocolbuffers/protobuf/issues/6335. + return errors.New("invalid name: %q", s) + } + } + return nil +} + +type EnumRanges struct { + List [][2]pref.EnumNumber // start inclusive; end inclusive + once sync.Once + sorted [][2]pref.EnumNumber // protected by once +} + +func (p *EnumRanges) Len() int { return len(p.List) } +func (p *EnumRanges) Get(i int) [2]pref.EnumNumber { return p.List[i] } +func (p *EnumRanges) Has(n pref.EnumNumber) bool { + for ls := p.lazyInit().sorted; len(ls) > 0; { + i := len(ls) / 2 + switch r := enumRange(ls[i]); { + case n < r.Start(): + ls = ls[:i] // search lower + case n > r.End(): + ls = ls[i+1:] // search upper + default: + return true + } + } + return false +} +func (p *EnumRanges) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } +func (p *EnumRanges) ProtoInternal(pragma.DoNotImplement) {} +func (p *EnumRanges) lazyInit() *EnumRanges { + p.once.Do(func() { + p.sorted = append(p.sorted, p.List...) + sort.Slice(p.sorted, func(i, j int) bool { + return p.sorted[i][0] < p.sorted[j][0] + }) + }) + return p +} + +// CheckValid reports any errors with the set of names with an error message +// that completes the sentence: "ranges is invalid because it has ..." +func (p *EnumRanges) CheckValid() error { + var rp enumRange + for i, r := range p.lazyInit().sorted { + r := enumRange(r) + switch { + case !(r.Start() <= r.End()): + return errors.New("invalid range: %v", r) + case !(rp.End() < r.Start()) && i > 0: + return errors.New("overlapping ranges: %v with %v", rp, r) + } + rp = r + } + return nil +} + +type enumRange [2]protoreflect.EnumNumber + +func (r enumRange) Start() protoreflect.EnumNumber { return r[0] } // inclusive +func (r enumRange) End() protoreflect.EnumNumber { return r[1] } // inclusive +func (r enumRange) String() string { + if r.Start() == r.End() { + return fmt.Sprintf("%d", r.Start()) + } + return fmt.Sprintf("%d to %d", r.Start(), r.End()) +} + +type FieldRanges struct { + List [][2]pref.FieldNumber // start inclusive; end exclusive + once sync.Once + sorted [][2]pref.FieldNumber // protected by once +} + +func (p *FieldRanges) Len() int { return len(p.List) } +func (p *FieldRanges) Get(i int) [2]pref.FieldNumber { return p.List[i] } +func (p *FieldRanges) Has(n pref.FieldNumber) bool { + for ls := p.lazyInit().sorted; len(ls) > 0; { + i := len(ls) / 2 + switch r := fieldRange(ls[i]); { + case n < r.Start(): + ls = ls[:i] // search lower + case n > r.End(): + ls = ls[i+1:] // search upper + default: + return true + } + } + return false +} +func (p *FieldRanges) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } +func (p *FieldRanges) ProtoInternal(pragma.DoNotImplement) {} +func (p *FieldRanges) lazyInit() *FieldRanges { + p.once.Do(func() { + p.sorted = append(p.sorted, p.List...) + sort.Slice(p.sorted, func(i, j int) bool { + return p.sorted[i][0] < p.sorted[j][0] + }) + }) + return p +} + +// CheckValid reports any errors with the set of ranges with an error message +// that completes the sentence: "ranges is invalid because it has ..." +func (p *FieldRanges) CheckValid(isMessageSet bool) error { + var rp fieldRange + for i, r := range p.lazyInit().sorted { + r := fieldRange(r) + switch { + case !isValidFieldNumber(r.Start(), isMessageSet): + return errors.New("invalid field number: %d", r.Start()) + case !isValidFieldNumber(r.End(), isMessageSet): + return errors.New("invalid field number: %d", r.End()) + case !(r.Start() <= r.End()): + return errors.New("invalid range: %v", r) + case !(rp.End() < r.Start()) && i > 0: + return errors.New("overlapping ranges: %v with %v", rp, r) + } + rp = r + } + return nil +} + +// isValidFieldNumber reports whether the field number is valid. +// Unlike the FieldNumber.IsValid method, it allows ranges that cover the +// reserved number range. +func isValidFieldNumber(n protoreflect.FieldNumber, isMessageSet bool) bool { + return protowire.MinValidNumber <= n && (n <= protowire.MaxValidNumber || isMessageSet) +} + +// CheckOverlap reports an error if p and q overlap. +func (p *FieldRanges) CheckOverlap(q *FieldRanges) error { + rps := p.lazyInit().sorted + rqs := q.lazyInit().sorted + for pi, qi := 0, 0; pi < len(rps) && qi < len(rqs); { + rp := fieldRange(rps[pi]) + rq := fieldRange(rqs[qi]) + if !(rp.End() < rq.Start() || rq.End() < rp.Start()) { + return errors.New("overlapping ranges: %v with %v", rp, rq) + } + if rp.Start() < rq.Start() { + pi++ + } else { + qi++ + } + } + return nil +} + +type fieldRange [2]protoreflect.FieldNumber + +func (r fieldRange) Start() protoreflect.FieldNumber { return r[0] } // inclusive +func (r fieldRange) End() protoreflect.FieldNumber { return r[1] - 1 } // inclusive +func (r fieldRange) String() string { + if r.Start() == r.End() { + return fmt.Sprintf("%d", r.Start()) + } + return fmt.Sprintf("%d to %d", r.Start(), r.End()) +} + +type FieldNumbers struct { + List []pref.FieldNumber + once sync.Once + has map[pref.FieldNumber]struct{} // protected by once +} + +func (p *FieldNumbers) Len() int { return len(p.List) } +func (p *FieldNumbers) Get(i int) pref.FieldNumber { return p.List[i] } +func (p *FieldNumbers) Has(n pref.FieldNumber) bool { + p.once.Do(func() { + if len(p.List) > 0 { + p.has = make(map[pref.FieldNumber]struct{}, len(p.List)) + for _, n := range p.List { + p.has[n] = struct{}{} + } + } + }) + _, ok := p.has[n] + return ok +} +func (p *FieldNumbers) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } +func (p *FieldNumbers) ProtoInternal(pragma.DoNotImplement) {} + +type OneofFields struct { + List []pref.FieldDescriptor + once sync.Once + byName map[pref.Name]pref.FieldDescriptor // protected by once + byJSON map[string]pref.FieldDescriptor // protected by once + byNum map[pref.FieldNumber]pref.FieldDescriptor // protected by once +} + +func (p *OneofFields) Len() int { return len(p.List) } +func (p *OneofFields) Get(i int) pref.FieldDescriptor { return p.List[i] } +func (p *OneofFields) ByName(s pref.Name) pref.FieldDescriptor { return p.lazyInit().byName[s] } +func (p *OneofFields) ByJSONName(s string) pref.FieldDescriptor { return p.lazyInit().byJSON[s] } +func (p *OneofFields) ByNumber(n pref.FieldNumber) pref.FieldDescriptor { return p.lazyInit().byNum[n] } +func (p *OneofFields) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } +func (p *OneofFields) ProtoInternal(pragma.DoNotImplement) {} + +func (p *OneofFields) lazyInit() *OneofFields { + p.once.Do(func() { + if len(p.List) > 0 { + p.byName = make(map[pref.Name]pref.FieldDescriptor, len(p.List)) + p.byJSON = make(map[string]pref.FieldDescriptor, len(p.List)) + p.byNum = make(map[pref.FieldNumber]pref.FieldDescriptor, len(p.List)) + for _, f := range p.List { + // Field names and numbers are guaranteed to be unique. + p.byName[f.Name()] = f + p.byJSON[f.JSONName()] = f + p.byNum[f.Number()] = f + } + } + }) + return p +} + +type SourceLocations struct { + List []pref.SourceLocation +} + +func (p *SourceLocations) Len() int { return len(p.List) } +func (p *SourceLocations) Get(i int) pref.SourceLocation { return p.List[i] } +func (p *SourceLocations) ProtoInternal(pragma.DoNotImplement) {} diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc_list_gen.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc_list_gen.go new file mode 100644 index 00000000000..6a8825e8027 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc_list_gen.go @@ -0,0 +1,345 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-types. DO NOT EDIT. + +package filedesc + +import ( + "fmt" + "sync" + + "google.golang.org/protobuf/internal/descfmt" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/reflect/protoreflect" +) + +type Enums struct { + List []Enum + once sync.Once + byName map[protoreflect.Name]*Enum // protected by once +} + +func (p *Enums) Len() int { + return len(p.List) +} +func (p *Enums) Get(i int) protoreflect.EnumDescriptor { + return &p.List[i] +} +func (p *Enums) ByName(s protoreflect.Name) protoreflect.EnumDescriptor { + if d := p.lazyInit().byName[s]; d != nil { + return d + } + return nil +} +func (p *Enums) Format(s fmt.State, r rune) { + descfmt.FormatList(s, r, p) +} +func (p *Enums) ProtoInternal(pragma.DoNotImplement) {} +func (p *Enums) lazyInit() *Enums { + p.once.Do(func() { + if len(p.List) > 0 { + p.byName = make(map[protoreflect.Name]*Enum, len(p.List)) + for i := range p.List { + d := &p.List[i] + if _, ok := p.byName[d.Name()]; !ok { + p.byName[d.Name()] = d + } + } + } + }) + return p +} + +type EnumValues struct { + List []EnumValue + once sync.Once + byName map[protoreflect.Name]*EnumValue // protected by once + byNum map[protoreflect.EnumNumber]*EnumValue // protected by once +} + +func (p *EnumValues) Len() int { + return len(p.List) +} +func (p *EnumValues) Get(i int) protoreflect.EnumValueDescriptor { + return &p.List[i] +} +func (p *EnumValues) ByName(s protoreflect.Name) protoreflect.EnumValueDescriptor { + if d := p.lazyInit().byName[s]; d != nil { + return d + } + return nil +} +func (p *EnumValues) ByNumber(n protoreflect.EnumNumber) protoreflect.EnumValueDescriptor { + if d := p.lazyInit().byNum[n]; d != nil { + return d + } + return nil +} +func (p *EnumValues) Format(s fmt.State, r rune) { + descfmt.FormatList(s, r, p) +} +func (p *EnumValues) ProtoInternal(pragma.DoNotImplement) {} +func (p *EnumValues) lazyInit() *EnumValues { + p.once.Do(func() { + if len(p.List) > 0 { + p.byName = make(map[protoreflect.Name]*EnumValue, len(p.List)) + p.byNum = make(map[protoreflect.EnumNumber]*EnumValue, len(p.List)) + for i := range p.List { + d := &p.List[i] + if _, ok := p.byName[d.Name()]; !ok { + p.byName[d.Name()] = d + } + if _, ok := p.byNum[d.Number()]; !ok { + p.byNum[d.Number()] = d + } + } + } + }) + return p +} + +type Messages struct { + List []Message + once sync.Once + byName map[protoreflect.Name]*Message // protected by once +} + +func (p *Messages) Len() int { + return len(p.List) +} +func (p *Messages) Get(i int) protoreflect.MessageDescriptor { + return &p.List[i] +} +func (p *Messages) ByName(s protoreflect.Name) protoreflect.MessageDescriptor { + if d := p.lazyInit().byName[s]; d != nil { + return d + } + return nil +} +func (p *Messages) Format(s fmt.State, r rune) { + descfmt.FormatList(s, r, p) +} +func (p *Messages) ProtoInternal(pragma.DoNotImplement) {} +func (p *Messages) lazyInit() *Messages { + p.once.Do(func() { + if len(p.List) > 0 { + p.byName = make(map[protoreflect.Name]*Message, len(p.List)) + for i := range p.List { + d := &p.List[i] + if _, ok := p.byName[d.Name()]; !ok { + p.byName[d.Name()] = d + } + } + } + }) + return p +} + +type Fields struct { + List []Field + once sync.Once + byName map[protoreflect.Name]*Field // protected by once + byJSON map[string]*Field // protected by once + byNum map[protoreflect.FieldNumber]*Field // protected by once +} + +func (p *Fields) Len() int { + return len(p.List) +} +func (p *Fields) Get(i int) protoreflect.FieldDescriptor { + return &p.List[i] +} +func (p *Fields) ByName(s protoreflect.Name) protoreflect.FieldDescriptor { + if d := p.lazyInit().byName[s]; d != nil { + return d + } + return nil +} +func (p *Fields) ByJSONName(s string) protoreflect.FieldDescriptor { + if d := p.lazyInit().byJSON[s]; d != nil { + return d + } + return nil +} +func (p *Fields) ByNumber(n protoreflect.FieldNumber) protoreflect.FieldDescriptor { + if d := p.lazyInit().byNum[n]; d != nil { + return d + } + return nil +} +func (p *Fields) Format(s fmt.State, r rune) { + descfmt.FormatList(s, r, p) +} +func (p *Fields) ProtoInternal(pragma.DoNotImplement) {} +func (p *Fields) lazyInit() *Fields { + p.once.Do(func() { + if len(p.List) > 0 { + p.byName = make(map[protoreflect.Name]*Field, len(p.List)) + p.byJSON = make(map[string]*Field, len(p.List)) + p.byNum = make(map[protoreflect.FieldNumber]*Field, len(p.List)) + for i := range p.List { + d := &p.List[i] + if _, ok := p.byName[d.Name()]; !ok { + p.byName[d.Name()] = d + } + if _, ok := p.byJSON[d.JSONName()]; !ok { + p.byJSON[d.JSONName()] = d + } + if _, ok := p.byNum[d.Number()]; !ok { + p.byNum[d.Number()] = d + } + } + } + }) + return p +} + +type Oneofs struct { + List []Oneof + once sync.Once + byName map[protoreflect.Name]*Oneof // protected by once +} + +func (p *Oneofs) Len() int { + return len(p.List) +} +func (p *Oneofs) Get(i int) protoreflect.OneofDescriptor { + return &p.List[i] +} +func (p *Oneofs) ByName(s protoreflect.Name) protoreflect.OneofDescriptor { + if d := p.lazyInit().byName[s]; d != nil { + return d + } + return nil +} +func (p *Oneofs) Format(s fmt.State, r rune) { + descfmt.FormatList(s, r, p) +} +func (p *Oneofs) ProtoInternal(pragma.DoNotImplement) {} +func (p *Oneofs) lazyInit() *Oneofs { + p.once.Do(func() { + if len(p.List) > 0 { + p.byName = make(map[protoreflect.Name]*Oneof, len(p.List)) + for i := range p.List { + d := &p.List[i] + if _, ok := p.byName[d.Name()]; !ok { + p.byName[d.Name()] = d + } + } + } + }) + return p +} + +type Extensions struct { + List []Extension + once sync.Once + byName map[protoreflect.Name]*Extension // protected by once +} + +func (p *Extensions) Len() int { + return len(p.List) +} +func (p *Extensions) Get(i int) protoreflect.ExtensionDescriptor { + return &p.List[i] +} +func (p *Extensions) ByName(s protoreflect.Name) protoreflect.ExtensionDescriptor { + if d := p.lazyInit().byName[s]; d != nil { + return d + } + return nil +} +func (p *Extensions) Format(s fmt.State, r rune) { + descfmt.FormatList(s, r, p) +} +func (p *Extensions) ProtoInternal(pragma.DoNotImplement) {} +func (p *Extensions) lazyInit() *Extensions { + p.once.Do(func() { + if len(p.List) > 0 { + p.byName = make(map[protoreflect.Name]*Extension, len(p.List)) + for i := range p.List { + d := &p.List[i] + if _, ok := p.byName[d.Name()]; !ok { + p.byName[d.Name()] = d + } + } + } + }) + return p +} + +type Services struct { + List []Service + once sync.Once + byName map[protoreflect.Name]*Service // protected by once +} + +func (p *Services) Len() int { + return len(p.List) +} +func (p *Services) Get(i int) protoreflect.ServiceDescriptor { + return &p.List[i] +} +func (p *Services) ByName(s protoreflect.Name) protoreflect.ServiceDescriptor { + if d := p.lazyInit().byName[s]; d != nil { + return d + } + return nil +} +func (p *Services) Format(s fmt.State, r rune) { + descfmt.FormatList(s, r, p) +} +func (p *Services) ProtoInternal(pragma.DoNotImplement) {} +func (p *Services) lazyInit() *Services { + p.once.Do(func() { + if len(p.List) > 0 { + p.byName = make(map[protoreflect.Name]*Service, len(p.List)) + for i := range p.List { + d := &p.List[i] + if _, ok := p.byName[d.Name()]; !ok { + p.byName[d.Name()] = d + } + } + } + }) + return p +} + +type Methods struct { + List []Method + once sync.Once + byName map[protoreflect.Name]*Method // protected by once +} + +func (p *Methods) Len() int { + return len(p.List) +} +func (p *Methods) Get(i int) protoreflect.MethodDescriptor { + return &p.List[i] +} +func (p *Methods) ByName(s protoreflect.Name) protoreflect.MethodDescriptor { + if d := p.lazyInit().byName[s]; d != nil { + return d + } + return nil +} +func (p *Methods) Format(s fmt.State, r rune) { + descfmt.FormatList(s, r, p) +} +func (p *Methods) ProtoInternal(pragma.DoNotImplement) {} +func (p *Methods) lazyInit() *Methods { + p.once.Do(func() { + if len(p.List) > 0 { + p.byName = make(map[protoreflect.Name]*Method, len(p.List)) + for i := range p.List { + d := &p.List[i] + if _, ok := p.byName[d.Name()]; !ok { + p.byName[d.Name()] = d + } + } + } + }) + return p +} diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/placeholder.go b/vendor/google.golang.org/protobuf/internal/filedesc/placeholder.go new file mode 100644 index 00000000000..dbf2c605bfe --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/filedesc/placeholder.go @@ -0,0 +1,107 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package filedesc + +import ( + "google.golang.org/protobuf/internal/descopts" + "google.golang.org/protobuf/internal/pragma" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +var ( + emptyNames = new(Names) + emptyEnumRanges = new(EnumRanges) + emptyFieldRanges = new(FieldRanges) + emptyFieldNumbers = new(FieldNumbers) + emptySourceLocations = new(SourceLocations) + + emptyFiles = new(FileImports) + emptyMessages = new(Messages) + emptyFields = new(Fields) + emptyOneofs = new(Oneofs) + emptyEnums = new(Enums) + emptyEnumValues = new(EnumValues) + emptyExtensions = new(Extensions) + emptyServices = new(Services) +) + +// PlaceholderFile is a placeholder, representing only the file path. +type PlaceholderFile string + +func (f PlaceholderFile) ParentFile() pref.FileDescriptor { return f } +func (f PlaceholderFile) Parent() pref.Descriptor { return nil } +func (f PlaceholderFile) Index() int { return 0 } +func (f PlaceholderFile) Syntax() pref.Syntax { return 0 } +func (f PlaceholderFile) Name() pref.Name { return "" } +func (f PlaceholderFile) FullName() pref.FullName { return "" } +func (f PlaceholderFile) IsPlaceholder() bool { return true } +func (f PlaceholderFile) Options() pref.ProtoMessage { return descopts.File } +func (f PlaceholderFile) Path() string { return string(f) } +func (f PlaceholderFile) Package() pref.FullName { return "" } +func (f PlaceholderFile) Imports() pref.FileImports { return emptyFiles } +func (f PlaceholderFile) Messages() pref.MessageDescriptors { return emptyMessages } +func (f PlaceholderFile) Enums() pref.EnumDescriptors { return emptyEnums } +func (f PlaceholderFile) Extensions() pref.ExtensionDescriptors { return emptyExtensions } +func (f PlaceholderFile) Services() pref.ServiceDescriptors { return emptyServices } +func (f PlaceholderFile) SourceLocations() pref.SourceLocations { return emptySourceLocations } +func (f PlaceholderFile) ProtoType(pref.FileDescriptor) { return } +func (f PlaceholderFile) ProtoInternal(pragma.DoNotImplement) { return } + +// PlaceholderEnum is a placeholder, representing only the full name. +type PlaceholderEnum pref.FullName + +func (e PlaceholderEnum) ParentFile() pref.FileDescriptor { return nil } +func (e PlaceholderEnum) Parent() pref.Descriptor { return nil } +func (e PlaceholderEnum) Index() int { return 0 } +func (e PlaceholderEnum) Syntax() pref.Syntax { return 0 } +func (e PlaceholderEnum) Name() pref.Name { return pref.FullName(e).Name() } +func (e PlaceholderEnum) FullName() pref.FullName { return pref.FullName(e) } +func (e PlaceholderEnum) IsPlaceholder() bool { return true } +func (e PlaceholderEnum) Options() pref.ProtoMessage { return descopts.Enum } +func (e PlaceholderEnum) Values() pref.EnumValueDescriptors { return emptyEnumValues } +func (e PlaceholderEnum) ReservedNames() pref.Names { return emptyNames } +func (e PlaceholderEnum) ReservedRanges() pref.EnumRanges { return emptyEnumRanges } +func (e PlaceholderEnum) ProtoType(pref.EnumDescriptor) { return } +func (e PlaceholderEnum) ProtoInternal(pragma.DoNotImplement) { return } + +// PlaceholderEnumValue is a placeholder, representing only the full name. +type PlaceholderEnumValue pref.FullName + +func (e PlaceholderEnumValue) ParentFile() pref.FileDescriptor { return nil } +func (e PlaceholderEnumValue) Parent() pref.Descriptor { return nil } +func (e PlaceholderEnumValue) Index() int { return 0 } +func (e PlaceholderEnumValue) Syntax() pref.Syntax { return 0 } +func (e PlaceholderEnumValue) Name() pref.Name { return pref.FullName(e).Name() } +func (e PlaceholderEnumValue) FullName() pref.FullName { return pref.FullName(e) } +func (e PlaceholderEnumValue) IsPlaceholder() bool { return true } +func (e PlaceholderEnumValue) Options() pref.ProtoMessage { return descopts.EnumValue } +func (e PlaceholderEnumValue) Number() pref.EnumNumber { return 0 } +func (e PlaceholderEnumValue) ProtoType(pref.EnumValueDescriptor) { return } +func (e PlaceholderEnumValue) ProtoInternal(pragma.DoNotImplement) { return } + +// PlaceholderMessage is a placeholder, representing only the full name. +type PlaceholderMessage pref.FullName + +func (m PlaceholderMessage) ParentFile() pref.FileDescriptor { return nil } +func (m PlaceholderMessage) Parent() pref.Descriptor { return nil } +func (m PlaceholderMessage) Index() int { return 0 } +func (m PlaceholderMessage) Syntax() pref.Syntax { return 0 } +func (m PlaceholderMessage) Name() pref.Name { return pref.FullName(m).Name() } +func (m PlaceholderMessage) FullName() pref.FullName { return pref.FullName(m) } +func (m PlaceholderMessage) IsPlaceholder() bool { return true } +func (m PlaceholderMessage) Options() pref.ProtoMessage { return descopts.Message } +func (m PlaceholderMessage) IsMapEntry() bool { return false } +func (m PlaceholderMessage) Fields() pref.FieldDescriptors { return emptyFields } +func (m PlaceholderMessage) Oneofs() pref.OneofDescriptors { return emptyOneofs } +func (m PlaceholderMessage) ReservedNames() pref.Names { return emptyNames } +func (m PlaceholderMessage) ReservedRanges() pref.FieldRanges { return emptyFieldRanges } +func (m PlaceholderMessage) RequiredNumbers() pref.FieldNumbers { return emptyFieldNumbers } +func (m PlaceholderMessage) ExtensionRanges() pref.FieldRanges { return emptyFieldRanges } +func (m PlaceholderMessage) ExtensionRangeOptions(int) pref.ProtoMessage { panic("index out of range") } +func (m PlaceholderMessage) Messages() pref.MessageDescriptors { return emptyMessages } +func (m PlaceholderMessage) Enums() pref.EnumDescriptors { return emptyEnums } +func (m PlaceholderMessage) Extensions() pref.ExtensionDescriptors { return emptyExtensions } +func (m PlaceholderMessage) ProtoType(pref.MessageDescriptor) { return } +func (m PlaceholderMessage) ProtoInternal(pragma.DoNotImplement) { return } diff --git a/vendor/google.golang.org/protobuf/internal/filetype/build.go b/vendor/google.golang.org/protobuf/internal/filetype/build.go new file mode 100644 index 00000000000..0a0dd35de5a --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/filetype/build.go @@ -0,0 +1,297 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package filetype provides functionality for wrapping descriptors +// with Go type information. +package filetype + +import ( + "reflect" + + "google.golang.org/protobuf/internal/descopts" + fdesc "google.golang.org/protobuf/internal/filedesc" + pimpl "google.golang.org/protobuf/internal/impl" + pref "google.golang.org/protobuf/reflect/protoreflect" + preg "google.golang.org/protobuf/reflect/protoregistry" +) + +// Builder constructs type descriptors from a raw file descriptor +// and associated Go types for each enum and message declaration. +// +// +// Flattened Ordering +// +// The protobuf type system represents declarations as a tree. Certain nodes in +// the tree require us to either associate it with a concrete Go type or to +// resolve a dependency, which is information that must be provided separately +// since it cannot be derived from the file descriptor alone. +// +// However, representing a tree as Go literals is difficult to simply do in a +// space and time efficient way. Thus, we store them as a flattened list of +// objects where the serialization order from the tree-based form is important. +// +// The "flattened ordering" is defined as a tree traversal of all enum, message, +// extension, and service declarations using the following algorithm: +// +// def VisitFileDecls(fd): +// for e in fd.Enums: yield e +// for m in fd.Messages: yield m +// for x in fd.Extensions: yield x +// for s in fd.Services: yield s +// for m in fd.Messages: yield from VisitMessageDecls(m) +// +// def VisitMessageDecls(md): +// for e in md.Enums: yield e +// for m in md.Messages: yield m +// for x in md.Extensions: yield x +// for m in md.Messages: yield from VisitMessageDecls(m) +// +// The traversal starts at the root file descriptor and yields each direct +// declaration within each node before traversing into sub-declarations +// that children themselves may have. +type Builder struct { + // File is the underlying file descriptor builder. + File fdesc.Builder + + // GoTypes is a unique set of the Go types for all declarations and + // dependencies. Each type is represented as a zero value of the Go type. + // + // Declarations are Go types generated for enums and messages directly + // declared (not publicly imported) in the proto source file. + // Messages for map entries are accounted for, but represented by nil. + // Enum declarations in "flattened ordering" come first, followed by + // message declarations in "flattened ordering". + // + // Dependencies are Go types for enums or messages referenced by + // message fields (excluding weak fields), for parent extended messages of + // extension fields, for enums or messages referenced by extension fields, + // and for input and output messages referenced by service methods. + // Dependencies must come after declarations, but the ordering of + // dependencies themselves is unspecified. + GoTypes []interface{} + + // DependencyIndexes is an ordered list of indexes into GoTypes for the + // dependencies of messages, extensions, or services. + // + // There are 5 sub-lists in "flattened ordering" concatenated back-to-back: + // 0. Message field dependencies: list of the enum or message type + // referred to by every message field. + // 1. Extension field targets: list of the extended parent message of + // every extension. + // 2. Extension field dependencies: list of the enum or message type + // referred to by every extension field. + // 3. Service method inputs: list of the input message type + // referred to by every service method. + // 4. Service method outputs: list of the output message type + // referred to by every service method. + // + // The offset into DependencyIndexes for the start of each sub-list + // is appended to the end in reverse order. + DependencyIndexes []int32 + + // EnumInfos is a list of enum infos in "flattened ordering". + EnumInfos []pimpl.EnumInfo + + // MessageInfos is a list of message infos in "flattened ordering". + // If provided, the GoType and PBType for each element is populated. + // + // Requirement: len(MessageInfos) == len(Build.Messages) + MessageInfos []pimpl.MessageInfo + + // ExtensionInfos is a list of extension infos in "flattened ordering". + // Each element is initialized and registered with the protoregistry package. + // + // Requirement: len(LegacyExtensions) == len(Build.Extensions) + ExtensionInfos []pimpl.ExtensionInfo + + // TypeRegistry is the registry to register each type descriptor. + // If nil, it uses protoregistry.GlobalTypes. + TypeRegistry interface { + RegisterMessage(pref.MessageType) error + RegisterEnum(pref.EnumType) error + RegisterExtension(pref.ExtensionType) error + } +} + +// Out is the output of the builder. +type Out struct { + File pref.FileDescriptor +} + +func (tb Builder) Build() (out Out) { + // Replace the resolver with one that resolves dependencies by index, + // which is faster and more reliable than relying on the global registry. + if tb.File.FileRegistry == nil { + tb.File.FileRegistry = preg.GlobalFiles + } + tb.File.FileRegistry = &resolverByIndex{ + goTypes: tb.GoTypes, + depIdxs: tb.DependencyIndexes, + fileRegistry: tb.File.FileRegistry, + } + + // Initialize registry if unpopulated. + if tb.TypeRegistry == nil { + tb.TypeRegistry = preg.GlobalTypes + } + + fbOut := tb.File.Build() + out.File = fbOut.File + + // Process enums. + enumGoTypes := tb.GoTypes[:len(fbOut.Enums)] + if len(tb.EnumInfos) != len(fbOut.Enums) { + panic("mismatching enum lengths") + } + if len(fbOut.Enums) > 0 { + for i := range fbOut.Enums { + tb.EnumInfos[i] = pimpl.EnumInfo{ + GoReflectType: reflect.TypeOf(enumGoTypes[i]), + Desc: &fbOut.Enums[i], + } + // Register enum types. + if err := tb.TypeRegistry.RegisterEnum(&tb.EnumInfos[i]); err != nil { + panic(err) + } + } + } + + // Process messages. + messageGoTypes := tb.GoTypes[len(fbOut.Enums):][:len(fbOut.Messages)] + if len(tb.MessageInfos) != len(fbOut.Messages) { + panic("mismatching message lengths") + } + if len(fbOut.Messages) > 0 { + for i := range fbOut.Messages { + if messageGoTypes[i] == nil { + continue // skip map entry + } + + tb.MessageInfos[i].GoReflectType = reflect.TypeOf(messageGoTypes[i]) + tb.MessageInfos[i].Desc = &fbOut.Messages[i] + + // Register message types. + if err := tb.TypeRegistry.RegisterMessage(&tb.MessageInfos[i]); err != nil { + panic(err) + } + } + + // As a special-case for descriptor.proto, + // locally register concrete message type for the options. + if out.File.Path() == "google/protobuf/descriptor.proto" && out.File.Package() == "google.protobuf" { + for i := range fbOut.Messages { + switch fbOut.Messages[i].Name() { + case "FileOptions": + descopts.File = messageGoTypes[i].(pref.ProtoMessage) + case "EnumOptions": + descopts.Enum = messageGoTypes[i].(pref.ProtoMessage) + case "EnumValueOptions": + descopts.EnumValue = messageGoTypes[i].(pref.ProtoMessage) + case "MessageOptions": + descopts.Message = messageGoTypes[i].(pref.ProtoMessage) + case "FieldOptions": + descopts.Field = messageGoTypes[i].(pref.ProtoMessage) + case "OneofOptions": + descopts.Oneof = messageGoTypes[i].(pref.ProtoMessage) + case "ExtensionRangeOptions": + descopts.ExtensionRange = messageGoTypes[i].(pref.ProtoMessage) + case "ServiceOptions": + descopts.Service = messageGoTypes[i].(pref.ProtoMessage) + case "MethodOptions": + descopts.Method = messageGoTypes[i].(pref.ProtoMessage) + } + } + } + } + + // Process extensions. + if len(tb.ExtensionInfos) != len(fbOut.Extensions) { + panic("mismatching extension lengths") + } + var depIdx int32 + for i := range fbOut.Extensions { + // For enum and message kinds, determine the referent Go type so + // that we can construct their constructors. + const listExtDeps = 2 + var goType reflect.Type + switch fbOut.Extensions[i].L1.Kind { + case pref.EnumKind: + j := depIdxs.Get(tb.DependencyIndexes, listExtDeps, depIdx) + goType = reflect.TypeOf(tb.GoTypes[j]) + depIdx++ + case pref.MessageKind, pref.GroupKind: + j := depIdxs.Get(tb.DependencyIndexes, listExtDeps, depIdx) + goType = reflect.TypeOf(tb.GoTypes[j]) + depIdx++ + default: + goType = goTypeForPBKind[fbOut.Extensions[i].L1.Kind] + } + if fbOut.Extensions[i].IsList() { + goType = reflect.SliceOf(goType) + } + + pimpl.InitExtensionInfo(&tb.ExtensionInfos[i], &fbOut.Extensions[i], goType) + + // Register extension types. + if err := tb.TypeRegistry.RegisterExtension(&tb.ExtensionInfos[i]); err != nil { + panic(err) + } + } + + return out +} + +var goTypeForPBKind = map[pref.Kind]reflect.Type{ + pref.BoolKind: reflect.TypeOf(bool(false)), + pref.Int32Kind: reflect.TypeOf(int32(0)), + pref.Sint32Kind: reflect.TypeOf(int32(0)), + pref.Sfixed32Kind: reflect.TypeOf(int32(0)), + pref.Int64Kind: reflect.TypeOf(int64(0)), + pref.Sint64Kind: reflect.TypeOf(int64(0)), + pref.Sfixed64Kind: reflect.TypeOf(int64(0)), + pref.Uint32Kind: reflect.TypeOf(uint32(0)), + pref.Fixed32Kind: reflect.TypeOf(uint32(0)), + pref.Uint64Kind: reflect.TypeOf(uint64(0)), + pref.Fixed64Kind: reflect.TypeOf(uint64(0)), + pref.FloatKind: reflect.TypeOf(float32(0)), + pref.DoubleKind: reflect.TypeOf(float64(0)), + pref.StringKind: reflect.TypeOf(string("")), + pref.BytesKind: reflect.TypeOf([]byte(nil)), +} + +type depIdxs []int32 + +// Get retrieves the jth element of the ith sub-list. +func (x depIdxs) Get(i, j int32) int32 { + return x[x[int32(len(x))-i-1]+j] +} + +type ( + resolverByIndex struct { + goTypes []interface{} + depIdxs depIdxs + fileRegistry + } + fileRegistry interface { + FindFileByPath(string) (pref.FileDescriptor, error) + FindDescriptorByName(pref.FullName) (pref.Descriptor, error) + RegisterFile(pref.FileDescriptor) error + } +) + +func (r *resolverByIndex) FindEnumByIndex(i, j int32, es []fdesc.Enum, ms []fdesc.Message) pref.EnumDescriptor { + if depIdx := int(r.depIdxs.Get(i, j)); int(depIdx) < len(es)+len(ms) { + return &es[depIdx] + } else { + return pimpl.Export{}.EnumDescriptorOf(r.goTypes[depIdx]) + } +} + +func (r *resolverByIndex) FindMessageByIndex(i, j int32, es []fdesc.Enum, ms []fdesc.Message) pref.MessageDescriptor { + if depIdx := int(r.depIdxs.Get(i, j)); depIdx < len(es)+len(ms) { + return &ms[depIdx-len(es)] + } else { + return pimpl.Export{}.MessageDescriptorOf(r.goTypes[depIdx]) + } +} diff --git a/vendor/google.golang.org/protobuf/internal/flags/flags.go b/vendor/google.golang.org/protobuf/internal/flags/flags.go new file mode 100644 index 00000000000..58372dd3485 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/flags/flags.go @@ -0,0 +1,24 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package flags provides a set of flags controlled by build tags. +package flags + +// ProtoLegacy specifies whether to enable support for legacy functionality +// such as MessageSets, weak fields, and various other obscure behavior +// that is necessary to maintain backwards compatibility with proto1 or +// the pre-release variants of proto2 and proto3. +// +// This is disabled by default unless built with the "protolegacy" tag. +// +// WARNING: The compatibility agreement covers nothing provided by this flag. +// As such, functionality may suddenly be removed or changed at our discretion. +const ProtoLegacy = protoLegacy + +// LazyUnmarshalExtensions specifies whether to lazily unmarshal extensions. +// +// Lazy extension unmarshaling validates the contents of message-valued +// extension fields at unmarshal time, but defers creating the message +// structure until the extension is first accessed. +const LazyUnmarshalExtensions = ProtoLegacy diff --git a/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go b/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go new file mode 100644 index 00000000000..a72995f02d9 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go @@ -0,0 +1,9 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !protolegacy + +package flags + +const protoLegacy = false diff --git a/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go b/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go new file mode 100644 index 00000000000..772e2f0e4d6 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go @@ -0,0 +1,9 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build protolegacy + +package flags + +const protoLegacy = true diff --git a/vendor/google.golang.org/protobuf/internal/genid/any_gen.go b/vendor/google.golang.org/protobuf/internal/genid/any_gen.go new file mode 100644 index 00000000000..e6f7d47ab6d --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/any_gen.go @@ -0,0 +1,34 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-protos. DO NOT EDIT. + +package genid + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" +) + +const File_google_protobuf_any_proto = "google/protobuf/any.proto" + +// Names for google.protobuf.Any. +const ( + Any_message_name protoreflect.Name = "Any" + Any_message_fullname protoreflect.FullName = "google.protobuf.Any" +) + +// Field names for google.protobuf.Any. +const ( + Any_TypeUrl_field_name protoreflect.Name = "type_url" + Any_Value_field_name protoreflect.Name = "value" + + Any_TypeUrl_field_fullname protoreflect.FullName = "google.protobuf.Any.type_url" + Any_Value_field_fullname protoreflect.FullName = "google.protobuf.Any.value" +) + +// Field numbers for google.protobuf.Any. +const ( + Any_TypeUrl_field_number protoreflect.FieldNumber = 1 + Any_Value_field_number protoreflect.FieldNumber = 2 +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/api_gen.go b/vendor/google.golang.org/protobuf/internal/genid/api_gen.go new file mode 100644 index 00000000000..df8f9185013 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/api_gen.go @@ -0,0 +1,106 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-protos. DO NOT EDIT. + +package genid + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" +) + +const File_google_protobuf_api_proto = "google/protobuf/api.proto" + +// Names for google.protobuf.Api. +const ( + Api_message_name protoreflect.Name = "Api" + Api_message_fullname protoreflect.FullName = "google.protobuf.Api" +) + +// Field names for google.protobuf.Api. +const ( + Api_Name_field_name protoreflect.Name = "name" + Api_Methods_field_name protoreflect.Name = "methods" + Api_Options_field_name protoreflect.Name = "options" + Api_Version_field_name protoreflect.Name = "version" + Api_SourceContext_field_name protoreflect.Name = "source_context" + Api_Mixins_field_name protoreflect.Name = "mixins" + Api_Syntax_field_name protoreflect.Name = "syntax" + + Api_Name_field_fullname protoreflect.FullName = "google.protobuf.Api.name" + Api_Methods_field_fullname protoreflect.FullName = "google.protobuf.Api.methods" + Api_Options_field_fullname protoreflect.FullName = "google.protobuf.Api.options" + Api_Version_field_fullname protoreflect.FullName = "google.protobuf.Api.version" + Api_SourceContext_field_fullname protoreflect.FullName = "google.protobuf.Api.source_context" + Api_Mixins_field_fullname protoreflect.FullName = "google.protobuf.Api.mixins" + Api_Syntax_field_fullname protoreflect.FullName = "google.protobuf.Api.syntax" +) + +// Field numbers for google.protobuf.Api. +const ( + Api_Name_field_number protoreflect.FieldNumber = 1 + Api_Methods_field_number protoreflect.FieldNumber = 2 + Api_Options_field_number protoreflect.FieldNumber = 3 + Api_Version_field_number protoreflect.FieldNumber = 4 + Api_SourceContext_field_number protoreflect.FieldNumber = 5 + Api_Mixins_field_number protoreflect.FieldNumber = 6 + Api_Syntax_field_number protoreflect.FieldNumber = 7 +) + +// Names for google.protobuf.Method. +const ( + Method_message_name protoreflect.Name = "Method" + Method_message_fullname protoreflect.FullName = "google.protobuf.Method" +) + +// Field names for google.protobuf.Method. +const ( + Method_Name_field_name protoreflect.Name = "name" + Method_RequestTypeUrl_field_name protoreflect.Name = "request_type_url" + Method_RequestStreaming_field_name protoreflect.Name = "request_streaming" + Method_ResponseTypeUrl_field_name protoreflect.Name = "response_type_url" + Method_ResponseStreaming_field_name protoreflect.Name = "response_streaming" + Method_Options_field_name protoreflect.Name = "options" + Method_Syntax_field_name protoreflect.Name = "syntax" + + Method_Name_field_fullname protoreflect.FullName = "google.protobuf.Method.name" + Method_RequestTypeUrl_field_fullname protoreflect.FullName = "google.protobuf.Method.request_type_url" + Method_RequestStreaming_field_fullname protoreflect.FullName = "google.protobuf.Method.request_streaming" + Method_ResponseTypeUrl_field_fullname protoreflect.FullName = "google.protobuf.Method.response_type_url" + Method_ResponseStreaming_field_fullname protoreflect.FullName = "google.protobuf.Method.response_streaming" + Method_Options_field_fullname protoreflect.FullName = "google.protobuf.Method.options" + Method_Syntax_field_fullname protoreflect.FullName = "google.protobuf.Method.syntax" +) + +// Field numbers for google.protobuf.Method. +const ( + Method_Name_field_number protoreflect.FieldNumber = 1 + Method_RequestTypeUrl_field_number protoreflect.FieldNumber = 2 + Method_RequestStreaming_field_number protoreflect.FieldNumber = 3 + Method_ResponseTypeUrl_field_number protoreflect.FieldNumber = 4 + Method_ResponseStreaming_field_number protoreflect.FieldNumber = 5 + Method_Options_field_number protoreflect.FieldNumber = 6 + Method_Syntax_field_number protoreflect.FieldNumber = 7 +) + +// Names for google.protobuf.Mixin. +const ( + Mixin_message_name protoreflect.Name = "Mixin" + Mixin_message_fullname protoreflect.FullName = "google.protobuf.Mixin" +) + +// Field names for google.protobuf.Mixin. +const ( + Mixin_Name_field_name protoreflect.Name = "name" + Mixin_Root_field_name protoreflect.Name = "root" + + Mixin_Name_field_fullname protoreflect.FullName = "google.protobuf.Mixin.name" + Mixin_Root_field_fullname protoreflect.FullName = "google.protobuf.Mixin.root" +) + +// Field numbers for google.protobuf.Mixin. +const ( + Mixin_Name_field_number protoreflect.FieldNumber = 1 + Mixin_Root_field_number protoreflect.FieldNumber = 2 +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go b/vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go new file mode 100644 index 00000000000..e3cdf1c2059 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go @@ -0,0 +1,829 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-protos. DO NOT EDIT. + +package genid + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" +) + +const File_google_protobuf_descriptor_proto = "google/protobuf/descriptor.proto" + +// Names for google.protobuf.FileDescriptorSet. +const ( + FileDescriptorSet_message_name protoreflect.Name = "FileDescriptorSet" + FileDescriptorSet_message_fullname protoreflect.FullName = "google.protobuf.FileDescriptorSet" +) + +// Field names for google.protobuf.FileDescriptorSet. +const ( + FileDescriptorSet_File_field_name protoreflect.Name = "file" + + FileDescriptorSet_File_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorSet.file" +) + +// Field numbers for google.protobuf.FileDescriptorSet. +const ( + FileDescriptorSet_File_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.FileDescriptorProto. +const ( + FileDescriptorProto_message_name protoreflect.Name = "FileDescriptorProto" + FileDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto" +) + +// Field names for google.protobuf.FileDescriptorProto. +const ( + FileDescriptorProto_Name_field_name protoreflect.Name = "name" + FileDescriptorProto_Package_field_name protoreflect.Name = "package" + FileDescriptorProto_Dependency_field_name protoreflect.Name = "dependency" + FileDescriptorProto_PublicDependency_field_name protoreflect.Name = "public_dependency" + FileDescriptorProto_WeakDependency_field_name protoreflect.Name = "weak_dependency" + FileDescriptorProto_MessageType_field_name protoreflect.Name = "message_type" + FileDescriptorProto_EnumType_field_name protoreflect.Name = "enum_type" + FileDescriptorProto_Service_field_name protoreflect.Name = "service" + FileDescriptorProto_Extension_field_name protoreflect.Name = "extension" + FileDescriptorProto_Options_field_name protoreflect.Name = "options" + FileDescriptorProto_SourceCodeInfo_field_name protoreflect.Name = "source_code_info" + FileDescriptorProto_Syntax_field_name protoreflect.Name = "syntax" + + FileDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.name" + FileDescriptorProto_Package_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.package" + FileDescriptorProto_Dependency_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.dependency" + FileDescriptorProto_PublicDependency_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.public_dependency" + FileDescriptorProto_WeakDependency_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.weak_dependency" + FileDescriptorProto_MessageType_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.message_type" + FileDescriptorProto_EnumType_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.enum_type" + FileDescriptorProto_Service_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.service" + FileDescriptorProto_Extension_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.extension" + FileDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.options" + FileDescriptorProto_SourceCodeInfo_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.source_code_info" + FileDescriptorProto_Syntax_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.syntax" +) + +// Field numbers for google.protobuf.FileDescriptorProto. +const ( + FileDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 + FileDescriptorProto_Package_field_number protoreflect.FieldNumber = 2 + FileDescriptorProto_Dependency_field_number protoreflect.FieldNumber = 3 + FileDescriptorProto_PublicDependency_field_number protoreflect.FieldNumber = 10 + FileDescriptorProto_WeakDependency_field_number protoreflect.FieldNumber = 11 + FileDescriptorProto_MessageType_field_number protoreflect.FieldNumber = 4 + FileDescriptorProto_EnumType_field_number protoreflect.FieldNumber = 5 + FileDescriptorProto_Service_field_number protoreflect.FieldNumber = 6 + FileDescriptorProto_Extension_field_number protoreflect.FieldNumber = 7 + FileDescriptorProto_Options_field_number protoreflect.FieldNumber = 8 + FileDescriptorProto_SourceCodeInfo_field_number protoreflect.FieldNumber = 9 + FileDescriptorProto_Syntax_field_number protoreflect.FieldNumber = 12 +) + +// Names for google.protobuf.DescriptorProto. +const ( + DescriptorProto_message_name protoreflect.Name = "DescriptorProto" + DescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.DescriptorProto" +) + +// Field names for google.protobuf.DescriptorProto. +const ( + DescriptorProto_Name_field_name protoreflect.Name = "name" + DescriptorProto_Field_field_name protoreflect.Name = "field" + DescriptorProto_Extension_field_name protoreflect.Name = "extension" + DescriptorProto_NestedType_field_name protoreflect.Name = "nested_type" + DescriptorProto_EnumType_field_name protoreflect.Name = "enum_type" + DescriptorProto_ExtensionRange_field_name protoreflect.Name = "extension_range" + DescriptorProto_OneofDecl_field_name protoreflect.Name = "oneof_decl" + DescriptorProto_Options_field_name protoreflect.Name = "options" + DescriptorProto_ReservedRange_field_name protoreflect.Name = "reserved_range" + DescriptorProto_ReservedName_field_name protoreflect.Name = "reserved_name" + + DescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.name" + DescriptorProto_Field_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.field" + DescriptorProto_Extension_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.extension" + DescriptorProto_NestedType_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.nested_type" + DescriptorProto_EnumType_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.enum_type" + DescriptorProto_ExtensionRange_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.extension_range" + DescriptorProto_OneofDecl_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.oneof_decl" + DescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.options" + DescriptorProto_ReservedRange_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.reserved_range" + DescriptorProto_ReservedName_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.reserved_name" +) + +// Field numbers for google.protobuf.DescriptorProto. +const ( + DescriptorProto_Name_field_number protoreflect.FieldNumber = 1 + DescriptorProto_Field_field_number protoreflect.FieldNumber = 2 + DescriptorProto_Extension_field_number protoreflect.FieldNumber = 6 + DescriptorProto_NestedType_field_number protoreflect.FieldNumber = 3 + DescriptorProto_EnumType_field_number protoreflect.FieldNumber = 4 + DescriptorProto_ExtensionRange_field_number protoreflect.FieldNumber = 5 + DescriptorProto_OneofDecl_field_number protoreflect.FieldNumber = 8 + DescriptorProto_Options_field_number protoreflect.FieldNumber = 7 + DescriptorProto_ReservedRange_field_number protoreflect.FieldNumber = 9 + DescriptorProto_ReservedName_field_number protoreflect.FieldNumber = 10 +) + +// Names for google.protobuf.DescriptorProto.ExtensionRange. +const ( + DescriptorProto_ExtensionRange_message_name protoreflect.Name = "ExtensionRange" + DescriptorProto_ExtensionRange_message_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ExtensionRange" +) + +// Field names for google.protobuf.DescriptorProto.ExtensionRange. +const ( + DescriptorProto_ExtensionRange_Start_field_name protoreflect.Name = "start" + DescriptorProto_ExtensionRange_End_field_name protoreflect.Name = "end" + DescriptorProto_ExtensionRange_Options_field_name protoreflect.Name = "options" + + DescriptorProto_ExtensionRange_Start_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ExtensionRange.start" + DescriptorProto_ExtensionRange_End_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ExtensionRange.end" + DescriptorProto_ExtensionRange_Options_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ExtensionRange.options" +) + +// Field numbers for google.protobuf.DescriptorProto.ExtensionRange. +const ( + DescriptorProto_ExtensionRange_Start_field_number protoreflect.FieldNumber = 1 + DescriptorProto_ExtensionRange_End_field_number protoreflect.FieldNumber = 2 + DescriptorProto_ExtensionRange_Options_field_number protoreflect.FieldNumber = 3 +) + +// Names for google.protobuf.DescriptorProto.ReservedRange. +const ( + DescriptorProto_ReservedRange_message_name protoreflect.Name = "ReservedRange" + DescriptorProto_ReservedRange_message_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ReservedRange" +) + +// Field names for google.protobuf.DescriptorProto.ReservedRange. +const ( + DescriptorProto_ReservedRange_Start_field_name protoreflect.Name = "start" + DescriptorProto_ReservedRange_End_field_name protoreflect.Name = "end" + + DescriptorProto_ReservedRange_Start_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ReservedRange.start" + DescriptorProto_ReservedRange_End_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ReservedRange.end" +) + +// Field numbers for google.protobuf.DescriptorProto.ReservedRange. +const ( + DescriptorProto_ReservedRange_Start_field_number protoreflect.FieldNumber = 1 + DescriptorProto_ReservedRange_End_field_number protoreflect.FieldNumber = 2 +) + +// Names for google.protobuf.ExtensionRangeOptions. +const ( + ExtensionRangeOptions_message_name protoreflect.Name = "ExtensionRangeOptions" + ExtensionRangeOptions_message_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions" +) + +// Field names for google.protobuf.ExtensionRangeOptions. +const ( + ExtensionRangeOptions_UninterpretedOption_field_name protoreflect.Name = "uninterpreted_option" + + ExtensionRangeOptions_UninterpretedOption_field_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions.uninterpreted_option" +) + +// Field numbers for google.protobuf.ExtensionRangeOptions. +const ( + ExtensionRangeOptions_UninterpretedOption_field_number protoreflect.FieldNumber = 999 +) + +// Names for google.protobuf.FieldDescriptorProto. +const ( + FieldDescriptorProto_message_name protoreflect.Name = "FieldDescriptorProto" + FieldDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto" +) + +// Field names for google.protobuf.FieldDescriptorProto. +const ( + FieldDescriptorProto_Name_field_name protoreflect.Name = "name" + FieldDescriptorProto_Number_field_name protoreflect.Name = "number" + FieldDescriptorProto_Label_field_name protoreflect.Name = "label" + FieldDescriptorProto_Type_field_name protoreflect.Name = "type" + FieldDescriptorProto_TypeName_field_name protoreflect.Name = "type_name" + FieldDescriptorProto_Extendee_field_name protoreflect.Name = "extendee" + FieldDescriptorProto_DefaultValue_field_name protoreflect.Name = "default_value" + FieldDescriptorProto_OneofIndex_field_name protoreflect.Name = "oneof_index" + FieldDescriptorProto_JsonName_field_name protoreflect.Name = "json_name" + FieldDescriptorProto_Options_field_name protoreflect.Name = "options" + FieldDescriptorProto_Proto3Optional_field_name protoreflect.Name = "proto3_optional" + + FieldDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.name" + FieldDescriptorProto_Number_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.number" + FieldDescriptorProto_Label_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.label" + FieldDescriptorProto_Type_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.type" + FieldDescriptorProto_TypeName_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.type_name" + FieldDescriptorProto_Extendee_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.extendee" + FieldDescriptorProto_DefaultValue_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.default_value" + FieldDescriptorProto_OneofIndex_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.oneof_index" + FieldDescriptorProto_JsonName_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.json_name" + FieldDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.options" + FieldDescriptorProto_Proto3Optional_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.proto3_optional" +) + +// Field numbers for google.protobuf.FieldDescriptorProto. +const ( + FieldDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 + FieldDescriptorProto_Number_field_number protoreflect.FieldNumber = 3 + FieldDescriptorProto_Label_field_number protoreflect.FieldNumber = 4 + FieldDescriptorProto_Type_field_number protoreflect.FieldNumber = 5 + FieldDescriptorProto_TypeName_field_number protoreflect.FieldNumber = 6 + FieldDescriptorProto_Extendee_field_number protoreflect.FieldNumber = 2 + FieldDescriptorProto_DefaultValue_field_number protoreflect.FieldNumber = 7 + FieldDescriptorProto_OneofIndex_field_number protoreflect.FieldNumber = 9 + FieldDescriptorProto_JsonName_field_number protoreflect.FieldNumber = 10 + FieldDescriptorProto_Options_field_number protoreflect.FieldNumber = 8 + FieldDescriptorProto_Proto3Optional_field_number protoreflect.FieldNumber = 17 +) + +// Full and short names for google.protobuf.FieldDescriptorProto.Type. +const ( + FieldDescriptorProto_Type_enum_fullname = "google.protobuf.FieldDescriptorProto.Type" + FieldDescriptorProto_Type_enum_name = "Type" +) + +// Full and short names for google.protobuf.FieldDescriptorProto.Label. +const ( + FieldDescriptorProto_Label_enum_fullname = "google.protobuf.FieldDescriptorProto.Label" + FieldDescriptorProto_Label_enum_name = "Label" +) + +// Names for google.protobuf.OneofDescriptorProto. +const ( + OneofDescriptorProto_message_name protoreflect.Name = "OneofDescriptorProto" + OneofDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.OneofDescriptorProto" +) + +// Field names for google.protobuf.OneofDescriptorProto. +const ( + OneofDescriptorProto_Name_field_name protoreflect.Name = "name" + OneofDescriptorProto_Options_field_name protoreflect.Name = "options" + + OneofDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.OneofDescriptorProto.name" + OneofDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.OneofDescriptorProto.options" +) + +// Field numbers for google.protobuf.OneofDescriptorProto. +const ( + OneofDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 + OneofDescriptorProto_Options_field_number protoreflect.FieldNumber = 2 +) + +// Names for google.protobuf.EnumDescriptorProto. +const ( + EnumDescriptorProto_message_name protoreflect.Name = "EnumDescriptorProto" + EnumDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto" +) + +// Field names for google.protobuf.EnumDescriptorProto. +const ( + EnumDescriptorProto_Name_field_name protoreflect.Name = "name" + EnumDescriptorProto_Value_field_name protoreflect.Name = "value" + EnumDescriptorProto_Options_field_name protoreflect.Name = "options" + EnumDescriptorProto_ReservedRange_field_name protoreflect.Name = "reserved_range" + EnumDescriptorProto_ReservedName_field_name protoreflect.Name = "reserved_name" + + EnumDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.name" + EnumDescriptorProto_Value_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.value" + EnumDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.options" + EnumDescriptorProto_ReservedRange_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.reserved_range" + EnumDescriptorProto_ReservedName_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.reserved_name" +) + +// Field numbers for google.protobuf.EnumDescriptorProto. +const ( + EnumDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 + EnumDescriptorProto_Value_field_number protoreflect.FieldNumber = 2 + EnumDescriptorProto_Options_field_number protoreflect.FieldNumber = 3 + EnumDescriptorProto_ReservedRange_field_number protoreflect.FieldNumber = 4 + EnumDescriptorProto_ReservedName_field_number protoreflect.FieldNumber = 5 +) + +// Names for google.protobuf.EnumDescriptorProto.EnumReservedRange. +const ( + EnumDescriptorProto_EnumReservedRange_message_name protoreflect.Name = "EnumReservedRange" + EnumDescriptorProto_EnumReservedRange_message_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.EnumReservedRange" +) + +// Field names for google.protobuf.EnumDescriptorProto.EnumReservedRange. +const ( + EnumDescriptorProto_EnumReservedRange_Start_field_name protoreflect.Name = "start" + EnumDescriptorProto_EnumReservedRange_End_field_name protoreflect.Name = "end" + + EnumDescriptorProto_EnumReservedRange_Start_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.EnumReservedRange.start" + EnumDescriptorProto_EnumReservedRange_End_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.EnumReservedRange.end" +) + +// Field numbers for google.protobuf.EnumDescriptorProto.EnumReservedRange. +const ( + EnumDescriptorProto_EnumReservedRange_Start_field_number protoreflect.FieldNumber = 1 + EnumDescriptorProto_EnumReservedRange_End_field_number protoreflect.FieldNumber = 2 +) + +// Names for google.protobuf.EnumValueDescriptorProto. +const ( + EnumValueDescriptorProto_message_name protoreflect.Name = "EnumValueDescriptorProto" + EnumValueDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.EnumValueDescriptorProto" +) + +// Field names for google.protobuf.EnumValueDescriptorProto. +const ( + EnumValueDescriptorProto_Name_field_name protoreflect.Name = "name" + EnumValueDescriptorProto_Number_field_name protoreflect.Name = "number" + EnumValueDescriptorProto_Options_field_name protoreflect.Name = "options" + + EnumValueDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.EnumValueDescriptorProto.name" + EnumValueDescriptorProto_Number_field_fullname protoreflect.FullName = "google.protobuf.EnumValueDescriptorProto.number" + EnumValueDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.EnumValueDescriptorProto.options" +) + +// Field numbers for google.protobuf.EnumValueDescriptorProto. +const ( + EnumValueDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 + EnumValueDescriptorProto_Number_field_number protoreflect.FieldNumber = 2 + EnumValueDescriptorProto_Options_field_number protoreflect.FieldNumber = 3 +) + +// Names for google.protobuf.ServiceDescriptorProto. +const ( + ServiceDescriptorProto_message_name protoreflect.Name = "ServiceDescriptorProto" + ServiceDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.ServiceDescriptorProto" +) + +// Field names for google.protobuf.ServiceDescriptorProto. +const ( + ServiceDescriptorProto_Name_field_name protoreflect.Name = "name" + ServiceDescriptorProto_Method_field_name protoreflect.Name = "method" + ServiceDescriptorProto_Options_field_name protoreflect.Name = "options" + + ServiceDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.ServiceDescriptorProto.name" + ServiceDescriptorProto_Method_field_fullname protoreflect.FullName = "google.protobuf.ServiceDescriptorProto.method" + ServiceDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.ServiceDescriptorProto.options" +) + +// Field numbers for google.protobuf.ServiceDescriptorProto. +const ( + ServiceDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 + ServiceDescriptorProto_Method_field_number protoreflect.FieldNumber = 2 + ServiceDescriptorProto_Options_field_number protoreflect.FieldNumber = 3 +) + +// Names for google.protobuf.MethodDescriptorProto. +const ( + MethodDescriptorProto_message_name protoreflect.Name = "MethodDescriptorProto" + MethodDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto" +) + +// Field names for google.protobuf.MethodDescriptorProto. +const ( + MethodDescriptorProto_Name_field_name protoreflect.Name = "name" + MethodDescriptorProto_InputType_field_name protoreflect.Name = "input_type" + MethodDescriptorProto_OutputType_field_name protoreflect.Name = "output_type" + MethodDescriptorProto_Options_field_name protoreflect.Name = "options" + MethodDescriptorProto_ClientStreaming_field_name protoreflect.Name = "client_streaming" + MethodDescriptorProto_ServerStreaming_field_name protoreflect.Name = "server_streaming" + + MethodDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.name" + MethodDescriptorProto_InputType_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.input_type" + MethodDescriptorProto_OutputType_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.output_type" + MethodDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.options" + MethodDescriptorProto_ClientStreaming_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.client_streaming" + MethodDescriptorProto_ServerStreaming_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.server_streaming" +) + +// Field numbers for google.protobuf.MethodDescriptorProto. +const ( + MethodDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 + MethodDescriptorProto_InputType_field_number protoreflect.FieldNumber = 2 + MethodDescriptorProto_OutputType_field_number protoreflect.FieldNumber = 3 + MethodDescriptorProto_Options_field_number protoreflect.FieldNumber = 4 + MethodDescriptorProto_ClientStreaming_field_number protoreflect.FieldNumber = 5 + MethodDescriptorProto_ServerStreaming_field_number protoreflect.FieldNumber = 6 +) + +// Names for google.protobuf.FileOptions. +const ( + FileOptions_message_name protoreflect.Name = "FileOptions" + FileOptions_message_fullname protoreflect.FullName = "google.protobuf.FileOptions" +) + +// Field names for google.protobuf.FileOptions. +const ( + FileOptions_JavaPackage_field_name protoreflect.Name = "java_package" + FileOptions_JavaOuterClassname_field_name protoreflect.Name = "java_outer_classname" + FileOptions_JavaMultipleFiles_field_name protoreflect.Name = "java_multiple_files" + FileOptions_JavaGenerateEqualsAndHash_field_name protoreflect.Name = "java_generate_equals_and_hash" + FileOptions_JavaStringCheckUtf8_field_name protoreflect.Name = "java_string_check_utf8" + FileOptions_OptimizeFor_field_name protoreflect.Name = "optimize_for" + FileOptions_GoPackage_field_name protoreflect.Name = "go_package" + FileOptions_CcGenericServices_field_name protoreflect.Name = "cc_generic_services" + FileOptions_JavaGenericServices_field_name protoreflect.Name = "java_generic_services" + FileOptions_PyGenericServices_field_name protoreflect.Name = "py_generic_services" + FileOptions_PhpGenericServices_field_name protoreflect.Name = "php_generic_services" + FileOptions_Deprecated_field_name protoreflect.Name = "deprecated" + FileOptions_CcEnableArenas_field_name protoreflect.Name = "cc_enable_arenas" + FileOptions_ObjcClassPrefix_field_name protoreflect.Name = "objc_class_prefix" + FileOptions_CsharpNamespace_field_name protoreflect.Name = "csharp_namespace" + FileOptions_SwiftPrefix_field_name protoreflect.Name = "swift_prefix" + FileOptions_PhpClassPrefix_field_name protoreflect.Name = "php_class_prefix" + FileOptions_PhpNamespace_field_name protoreflect.Name = "php_namespace" + FileOptions_PhpMetadataNamespace_field_name protoreflect.Name = "php_metadata_namespace" + FileOptions_RubyPackage_field_name protoreflect.Name = "ruby_package" + FileOptions_UninterpretedOption_field_name protoreflect.Name = "uninterpreted_option" + + FileOptions_JavaPackage_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.java_package" + FileOptions_JavaOuterClassname_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.java_outer_classname" + FileOptions_JavaMultipleFiles_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.java_multiple_files" + FileOptions_JavaGenerateEqualsAndHash_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.java_generate_equals_and_hash" + FileOptions_JavaStringCheckUtf8_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.java_string_check_utf8" + FileOptions_OptimizeFor_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.optimize_for" + FileOptions_GoPackage_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.go_package" + FileOptions_CcGenericServices_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.cc_generic_services" + FileOptions_JavaGenericServices_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.java_generic_services" + FileOptions_PyGenericServices_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.py_generic_services" + FileOptions_PhpGenericServices_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.php_generic_services" + FileOptions_Deprecated_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.deprecated" + FileOptions_CcEnableArenas_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.cc_enable_arenas" + FileOptions_ObjcClassPrefix_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.objc_class_prefix" + FileOptions_CsharpNamespace_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.csharp_namespace" + FileOptions_SwiftPrefix_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.swift_prefix" + FileOptions_PhpClassPrefix_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.php_class_prefix" + FileOptions_PhpNamespace_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.php_namespace" + FileOptions_PhpMetadataNamespace_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.php_metadata_namespace" + FileOptions_RubyPackage_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.ruby_package" + FileOptions_UninterpretedOption_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.uninterpreted_option" +) + +// Field numbers for google.protobuf.FileOptions. +const ( + FileOptions_JavaPackage_field_number protoreflect.FieldNumber = 1 + FileOptions_JavaOuterClassname_field_number protoreflect.FieldNumber = 8 + FileOptions_JavaMultipleFiles_field_number protoreflect.FieldNumber = 10 + FileOptions_JavaGenerateEqualsAndHash_field_number protoreflect.FieldNumber = 20 + FileOptions_JavaStringCheckUtf8_field_number protoreflect.FieldNumber = 27 + FileOptions_OptimizeFor_field_number protoreflect.FieldNumber = 9 + FileOptions_GoPackage_field_number protoreflect.FieldNumber = 11 + FileOptions_CcGenericServices_field_number protoreflect.FieldNumber = 16 + FileOptions_JavaGenericServices_field_number protoreflect.FieldNumber = 17 + FileOptions_PyGenericServices_field_number protoreflect.FieldNumber = 18 + FileOptions_PhpGenericServices_field_number protoreflect.FieldNumber = 42 + FileOptions_Deprecated_field_number protoreflect.FieldNumber = 23 + FileOptions_CcEnableArenas_field_number protoreflect.FieldNumber = 31 + FileOptions_ObjcClassPrefix_field_number protoreflect.FieldNumber = 36 + FileOptions_CsharpNamespace_field_number protoreflect.FieldNumber = 37 + FileOptions_SwiftPrefix_field_number protoreflect.FieldNumber = 39 + FileOptions_PhpClassPrefix_field_number protoreflect.FieldNumber = 40 + FileOptions_PhpNamespace_field_number protoreflect.FieldNumber = 41 + FileOptions_PhpMetadataNamespace_field_number protoreflect.FieldNumber = 44 + FileOptions_RubyPackage_field_number protoreflect.FieldNumber = 45 + FileOptions_UninterpretedOption_field_number protoreflect.FieldNumber = 999 +) + +// Full and short names for google.protobuf.FileOptions.OptimizeMode. +const ( + FileOptions_OptimizeMode_enum_fullname = "google.protobuf.FileOptions.OptimizeMode" + FileOptions_OptimizeMode_enum_name = "OptimizeMode" +) + +// Names for google.protobuf.MessageOptions. +const ( + MessageOptions_message_name protoreflect.Name = "MessageOptions" + MessageOptions_message_fullname protoreflect.FullName = "google.protobuf.MessageOptions" +) + +// Field names for google.protobuf.MessageOptions. +const ( + MessageOptions_MessageSetWireFormat_field_name protoreflect.Name = "message_set_wire_format" + MessageOptions_NoStandardDescriptorAccessor_field_name protoreflect.Name = "no_standard_descriptor_accessor" + MessageOptions_Deprecated_field_name protoreflect.Name = "deprecated" + MessageOptions_MapEntry_field_name protoreflect.Name = "map_entry" + MessageOptions_UninterpretedOption_field_name protoreflect.Name = "uninterpreted_option" + + MessageOptions_MessageSetWireFormat_field_fullname protoreflect.FullName = "google.protobuf.MessageOptions.message_set_wire_format" + MessageOptions_NoStandardDescriptorAccessor_field_fullname protoreflect.FullName = "google.protobuf.MessageOptions.no_standard_descriptor_accessor" + MessageOptions_Deprecated_field_fullname protoreflect.FullName = "google.protobuf.MessageOptions.deprecated" + MessageOptions_MapEntry_field_fullname protoreflect.FullName = "google.protobuf.MessageOptions.map_entry" + MessageOptions_UninterpretedOption_field_fullname protoreflect.FullName = "google.protobuf.MessageOptions.uninterpreted_option" +) + +// Field numbers for google.protobuf.MessageOptions. +const ( + MessageOptions_MessageSetWireFormat_field_number protoreflect.FieldNumber = 1 + MessageOptions_NoStandardDescriptorAccessor_field_number protoreflect.FieldNumber = 2 + MessageOptions_Deprecated_field_number protoreflect.FieldNumber = 3 + MessageOptions_MapEntry_field_number protoreflect.FieldNumber = 7 + MessageOptions_UninterpretedOption_field_number protoreflect.FieldNumber = 999 +) + +// Names for google.protobuf.FieldOptions. +const ( + FieldOptions_message_name protoreflect.Name = "FieldOptions" + FieldOptions_message_fullname protoreflect.FullName = "google.protobuf.FieldOptions" +) + +// Field names for google.protobuf.FieldOptions. +const ( + FieldOptions_Ctype_field_name protoreflect.Name = "ctype" + FieldOptions_Packed_field_name protoreflect.Name = "packed" + FieldOptions_Jstype_field_name protoreflect.Name = "jstype" + FieldOptions_Lazy_field_name protoreflect.Name = "lazy" + FieldOptions_Deprecated_field_name protoreflect.Name = "deprecated" + FieldOptions_Weak_field_name protoreflect.Name = "weak" + FieldOptions_UninterpretedOption_field_name protoreflect.Name = "uninterpreted_option" + + FieldOptions_Ctype_field_fullname protoreflect.FullName = "google.protobuf.FieldOptions.ctype" + FieldOptions_Packed_field_fullname protoreflect.FullName = "google.protobuf.FieldOptions.packed" + FieldOptions_Jstype_field_fullname protoreflect.FullName = "google.protobuf.FieldOptions.jstype" + FieldOptions_Lazy_field_fullname protoreflect.FullName = "google.protobuf.FieldOptions.lazy" + FieldOptions_Deprecated_field_fullname protoreflect.FullName = "google.protobuf.FieldOptions.deprecated" + FieldOptions_Weak_field_fullname protoreflect.FullName = "google.protobuf.FieldOptions.weak" + FieldOptions_UninterpretedOption_field_fullname protoreflect.FullName = "google.protobuf.FieldOptions.uninterpreted_option" +) + +// Field numbers for google.protobuf.FieldOptions. +const ( + FieldOptions_Ctype_field_number protoreflect.FieldNumber = 1 + FieldOptions_Packed_field_number protoreflect.FieldNumber = 2 + FieldOptions_Jstype_field_number protoreflect.FieldNumber = 6 + FieldOptions_Lazy_field_number protoreflect.FieldNumber = 5 + FieldOptions_Deprecated_field_number protoreflect.FieldNumber = 3 + FieldOptions_Weak_field_number protoreflect.FieldNumber = 10 + FieldOptions_UninterpretedOption_field_number protoreflect.FieldNumber = 999 +) + +// Full and short names for google.protobuf.FieldOptions.CType. +const ( + FieldOptions_CType_enum_fullname = "google.protobuf.FieldOptions.CType" + FieldOptions_CType_enum_name = "CType" +) + +// Full and short names for google.protobuf.FieldOptions.JSType. +const ( + FieldOptions_JSType_enum_fullname = "google.protobuf.FieldOptions.JSType" + FieldOptions_JSType_enum_name = "JSType" +) + +// Names for google.protobuf.OneofOptions. +const ( + OneofOptions_message_name protoreflect.Name = "OneofOptions" + OneofOptions_message_fullname protoreflect.FullName = "google.protobuf.OneofOptions" +) + +// Field names for google.protobuf.OneofOptions. +const ( + OneofOptions_UninterpretedOption_field_name protoreflect.Name = "uninterpreted_option" + + OneofOptions_UninterpretedOption_field_fullname protoreflect.FullName = "google.protobuf.OneofOptions.uninterpreted_option" +) + +// Field numbers for google.protobuf.OneofOptions. +const ( + OneofOptions_UninterpretedOption_field_number protoreflect.FieldNumber = 999 +) + +// Names for google.protobuf.EnumOptions. +const ( + EnumOptions_message_name protoreflect.Name = "EnumOptions" + EnumOptions_message_fullname protoreflect.FullName = "google.protobuf.EnumOptions" +) + +// Field names for google.protobuf.EnumOptions. +const ( + EnumOptions_AllowAlias_field_name protoreflect.Name = "allow_alias" + EnumOptions_Deprecated_field_name protoreflect.Name = "deprecated" + EnumOptions_UninterpretedOption_field_name protoreflect.Name = "uninterpreted_option" + + EnumOptions_AllowAlias_field_fullname protoreflect.FullName = "google.protobuf.EnumOptions.allow_alias" + EnumOptions_Deprecated_field_fullname protoreflect.FullName = "google.protobuf.EnumOptions.deprecated" + EnumOptions_UninterpretedOption_field_fullname protoreflect.FullName = "google.protobuf.EnumOptions.uninterpreted_option" +) + +// Field numbers for google.protobuf.EnumOptions. +const ( + EnumOptions_AllowAlias_field_number protoreflect.FieldNumber = 2 + EnumOptions_Deprecated_field_number protoreflect.FieldNumber = 3 + EnumOptions_UninterpretedOption_field_number protoreflect.FieldNumber = 999 +) + +// Names for google.protobuf.EnumValueOptions. +const ( + EnumValueOptions_message_name protoreflect.Name = "EnumValueOptions" + EnumValueOptions_message_fullname protoreflect.FullName = "google.protobuf.EnumValueOptions" +) + +// Field names for google.protobuf.EnumValueOptions. +const ( + EnumValueOptions_Deprecated_field_name protoreflect.Name = "deprecated" + EnumValueOptions_UninterpretedOption_field_name protoreflect.Name = "uninterpreted_option" + + EnumValueOptions_Deprecated_field_fullname protoreflect.FullName = "google.protobuf.EnumValueOptions.deprecated" + EnumValueOptions_UninterpretedOption_field_fullname protoreflect.FullName = "google.protobuf.EnumValueOptions.uninterpreted_option" +) + +// Field numbers for google.protobuf.EnumValueOptions. +const ( + EnumValueOptions_Deprecated_field_number protoreflect.FieldNumber = 1 + EnumValueOptions_UninterpretedOption_field_number protoreflect.FieldNumber = 999 +) + +// Names for google.protobuf.ServiceOptions. +const ( + ServiceOptions_message_name protoreflect.Name = "ServiceOptions" + ServiceOptions_message_fullname protoreflect.FullName = "google.protobuf.ServiceOptions" +) + +// Field names for google.protobuf.ServiceOptions. +const ( + ServiceOptions_Deprecated_field_name protoreflect.Name = "deprecated" + ServiceOptions_UninterpretedOption_field_name protoreflect.Name = "uninterpreted_option" + + ServiceOptions_Deprecated_field_fullname protoreflect.FullName = "google.protobuf.ServiceOptions.deprecated" + ServiceOptions_UninterpretedOption_field_fullname protoreflect.FullName = "google.protobuf.ServiceOptions.uninterpreted_option" +) + +// Field numbers for google.protobuf.ServiceOptions. +const ( + ServiceOptions_Deprecated_field_number protoreflect.FieldNumber = 33 + ServiceOptions_UninterpretedOption_field_number protoreflect.FieldNumber = 999 +) + +// Names for google.protobuf.MethodOptions. +const ( + MethodOptions_message_name protoreflect.Name = "MethodOptions" + MethodOptions_message_fullname protoreflect.FullName = "google.protobuf.MethodOptions" +) + +// Field names for google.protobuf.MethodOptions. +const ( + MethodOptions_Deprecated_field_name protoreflect.Name = "deprecated" + MethodOptions_IdempotencyLevel_field_name protoreflect.Name = "idempotency_level" + MethodOptions_UninterpretedOption_field_name protoreflect.Name = "uninterpreted_option" + + MethodOptions_Deprecated_field_fullname protoreflect.FullName = "google.protobuf.MethodOptions.deprecated" + MethodOptions_IdempotencyLevel_field_fullname protoreflect.FullName = "google.protobuf.MethodOptions.idempotency_level" + MethodOptions_UninterpretedOption_field_fullname protoreflect.FullName = "google.protobuf.MethodOptions.uninterpreted_option" +) + +// Field numbers for google.protobuf.MethodOptions. +const ( + MethodOptions_Deprecated_field_number protoreflect.FieldNumber = 33 + MethodOptions_IdempotencyLevel_field_number protoreflect.FieldNumber = 34 + MethodOptions_UninterpretedOption_field_number protoreflect.FieldNumber = 999 +) + +// Full and short names for google.protobuf.MethodOptions.IdempotencyLevel. +const ( + MethodOptions_IdempotencyLevel_enum_fullname = "google.protobuf.MethodOptions.IdempotencyLevel" + MethodOptions_IdempotencyLevel_enum_name = "IdempotencyLevel" +) + +// Names for google.protobuf.UninterpretedOption. +const ( + UninterpretedOption_message_name protoreflect.Name = "UninterpretedOption" + UninterpretedOption_message_fullname protoreflect.FullName = "google.protobuf.UninterpretedOption" +) + +// Field names for google.protobuf.UninterpretedOption. +const ( + UninterpretedOption_Name_field_name protoreflect.Name = "name" + UninterpretedOption_IdentifierValue_field_name protoreflect.Name = "identifier_value" + UninterpretedOption_PositiveIntValue_field_name protoreflect.Name = "positive_int_value" + UninterpretedOption_NegativeIntValue_field_name protoreflect.Name = "negative_int_value" + UninterpretedOption_DoubleValue_field_name protoreflect.Name = "double_value" + UninterpretedOption_StringValue_field_name protoreflect.Name = "string_value" + UninterpretedOption_AggregateValue_field_name protoreflect.Name = "aggregate_value" + + UninterpretedOption_Name_field_fullname protoreflect.FullName = "google.protobuf.UninterpretedOption.name" + UninterpretedOption_IdentifierValue_field_fullname protoreflect.FullName = "google.protobuf.UninterpretedOption.identifier_value" + UninterpretedOption_PositiveIntValue_field_fullname protoreflect.FullName = "google.protobuf.UninterpretedOption.positive_int_value" + UninterpretedOption_NegativeIntValue_field_fullname protoreflect.FullName = "google.protobuf.UninterpretedOption.negative_int_value" + UninterpretedOption_DoubleValue_field_fullname protoreflect.FullName = "google.protobuf.UninterpretedOption.double_value" + UninterpretedOption_StringValue_field_fullname protoreflect.FullName = "google.protobuf.UninterpretedOption.string_value" + UninterpretedOption_AggregateValue_field_fullname protoreflect.FullName = "google.protobuf.UninterpretedOption.aggregate_value" +) + +// Field numbers for google.protobuf.UninterpretedOption. +const ( + UninterpretedOption_Name_field_number protoreflect.FieldNumber = 2 + UninterpretedOption_IdentifierValue_field_number protoreflect.FieldNumber = 3 + UninterpretedOption_PositiveIntValue_field_number protoreflect.FieldNumber = 4 + UninterpretedOption_NegativeIntValue_field_number protoreflect.FieldNumber = 5 + UninterpretedOption_DoubleValue_field_number protoreflect.FieldNumber = 6 + UninterpretedOption_StringValue_field_number protoreflect.FieldNumber = 7 + UninterpretedOption_AggregateValue_field_number protoreflect.FieldNumber = 8 +) + +// Names for google.protobuf.UninterpretedOption.NamePart. +const ( + UninterpretedOption_NamePart_message_name protoreflect.Name = "NamePart" + UninterpretedOption_NamePart_message_fullname protoreflect.FullName = "google.protobuf.UninterpretedOption.NamePart" +) + +// Field names for google.protobuf.UninterpretedOption.NamePart. +const ( + UninterpretedOption_NamePart_NamePart_field_name protoreflect.Name = "name_part" + UninterpretedOption_NamePart_IsExtension_field_name protoreflect.Name = "is_extension" + + UninterpretedOption_NamePart_NamePart_field_fullname protoreflect.FullName = "google.protobuf.UninterpretedOption.NamePart.name_part" + UninterpretedOption_NamePart_IsExtension_field_fullname protoreflect.FullName = "google.protobuf.UninterpretedOption.NamePart.is_extension" +) + +// Field numbers for google.protobuf.UninterpretedOption.NamePart. +const ( + UninterpretedOption_NamePart_NamePart_field_number protoreflect.FieldNumber = 1 + UninterpretedOption_NamePart_IsExtension_field_number protoreflect.FieldNumber = 2 +) + +// Names for google.protobuf.SourceCodeInfo. +const ( + SourceCodeInfo_message_name protoreflect.Name = "SourceCodeInfo" + SourceCodeInfo_message_fullname protoreflect.FullName = "google.protobuf.SourceCodeInfo" +) + +// Field names for google.protobuf.SourceCodeInfo. +const ( + SourceCodeInfo_Location_field_name protoreflect.Name = "location" + + SourceCodeInfo_Location_field_fullname protoreflect.FullName = "google.protobuf.SourceCodeInfo.location" +) + +// Field numbers for google.protobuf.SourceCodeInfo. +const ( + SourceCodeInfo_Location_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.SourceCodeInfo.Location. +const ( + SourceCodeInfo_Location_message_name protoreflect.Name = "Location" + SourceCodeInfo_Location_message_fullname protoreflect.FullName = "google.protobuf.SourceCodeInfo.Location" +) + +// Field names for google.protobuf.SourceCodeInfo.Location. +const ( + SourceCodeInfo_Location_Path_field_name protoreflect.Name = "path" + SourceCodeInfo_Location_Span_field_name protoreflect.Name = "span" + SourceCodeInfo_Location_LeadingComments_field_name protoreflect.Name = "leading_comments" + SourceCodeInfo_Location_TrailingComments_field_name protoreflect.Name = "trailing_comments" + SourceCodeInfo_Location_LeadingDetachedComments_field_name protoreflect.Name = "leading_detached_comments" + + SourceCodeInfo_Location_Path_field_fullname protoreflect.FullName = "google.protobuf.SourceCodeInfo.Location.path" + SourceCodeInfo_Location_Span_field_fullname protoreflect.FullName = "google.protobuf.SourceCodeInfo.Location.span" + SourceCodeInfo_Location_LeadingComments_field_fullname protoreflect.FullName = "google.protobuf.SourceCodeInfo.Location.leading_comments" + SourceCodeInfo_Location_TrailingComments_field_fullname protoreflect.FullName = "google.protobuf.SourceCodeInfo.Location.trailing_comments" + SourceCodeInfo_Location_LeadingDetachedComments_field_fullname protoreflect.FullName = "google.protobuf.SourceCodeInfo.Location.leading_detached_comments" +) + +// Field numbers for google.protobuf.SourceCodeInfo.Location. +const ( + SourceCodeInfo_Location_Path_field_number protoreflect.FieldNumber = 1 + SourceCodeInfo_Location_Span_field_number protoreflect.FieldNumber = 2 + SourceCodeInfo_Location_LeadingComments_field_number protoreflect.FieldNumber = 3 + SourceCodeInfo_Location_TrailingComments_field_number protoreflect.FieldNumber = 4 + SourceCodeInfo_Location_LeadingDetachedComments_field_number protoreflect.FieldNumber = 6 +) + +// Names for google.protobuf.GeneratedCodeInfo. +const ( + GeneratedCodeInfo_message_name protoreflect.Name = "GeneratedCodeInfo" + GeneratedCodeInfo_message_fullname protoreflect.FullName = "google.protobuf.GeneratedCodeInfo" +) + +// Field names for google.protobuf.GeneratedCodeInfo. +const ( + GeneratedCodeInfo_Annotation_field_name protoreflect.Name = "annotation" + + GeneratedCodeInfo_Annotation_field_fullname protoreflect.FullName = "google.protobuf.GeneratedCodeInfo.annotation" +) + +// Field numbers for google.protobuf.GeneratedCodeInfo. +const ( + GeneratedCodeInfo_Annotation_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.GeneratedCodeInfo.Annotation. +const ( + GeneratedCodeInfo_Annotation_message_name protoreflect.Name = "Annotation" + GeneratedCodeInfo_Annotation_message_fullname protoreflect.FullName = "google.protobuf.GeneratedCodeInfo.Annotation" +) + +// Field names for google.protobuf.GeneratedCodeInfo.Annotation. +const ( + GeneratedCodeInfo_Annotation_Path_field_name protoreflect.Name = "path" + GeneratedCodeInfo_Annotation_SourceFile_field_name protoreflect.Name = "source_file" + GeneratedCodeInfo_Annotation_Begin_field_name protoreflect.Name = "begin" + GeneratedCodeInfo_Annotation_End_field_name protoreflect.Name = "end" + + GeneratedCodeInfo_Annotation_Path_field_fullname protoreflect.FullName = "google.protobuf.GeneratedCodeInfo.Annotation.path" + GeneratedCodeInfo_Annotation_SourceFile_field_fullname protoreflect.FullName = "google.protobuf.GeneratedCodeInfo.Annotation.source_file" + GeneratedCodeInfo_Annotation_Begin_field_fullname protoreflect.FullName = "google.protobuf.GeneratedCodeInfo.Annotation.begin" + GeneratedCodeInfo_Annotation_End_field_fullname protoreflect.FullName = "google.protobuf.GeneratedCodeInfo.Annotation.end" +) + +// Field numbers for google.protobuf.GeneratedCodeInfo.Annotation. +const ( + GeneratedCodeInfo_Annotation_Path_field_number protoreflect.FieldNumber = 1 + GeneratedCodeInfo_Annotation_SourceFile_field_number protoreflect.FieldNumber = 2 + GeneratedCodeInfo_Annotation_Begin_field_number protoreflect.FieldNumber = 3 + GeneratedCodeInfo_Annotation_End_field_number protoreflect.FieldNumber = 4 +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/doc.go b/vendor/google.golang.org/protobuf/internal/genid/doc.go new file mode 100644 index 00000000000..45ccd01211c --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/doc.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package genid contains constants for declarations in descriptor.proto +// and the well-known types. +package genid + +import protoreflect "google.golang.org/protobuf/reflect/protoreflect" + +const GoogleProtobuf_package protoreflect.FullName = "google.protobuf" diff --git a/vendor/google.golang.org/protobuf/internal/genid/duration_gen.go b/vendor/google.golang.org/protobuf/internal/genid/duration_gen.go new file mode 100644 index 00000000000..b070ef4fd69 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/duration_gen.go @@ -0,0 +1,34 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-protos. DO NOT EDIT. + +package genid + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" +) + +const File_google_protobuf_duration_proto = "google/protobuf/duration.proto" + +// Names for google.protobuf.Duration. +const ( + Duration_message_name protoreflect.Name = "Duration" + Duration_message_fullname protoreflect.FullName = "google.protobuf.Duration" +) + +// Field names for google.protobuf.Duration. +const ( + Duration_Seconds_field_name protoreflect.Name = "seconds" + Duration_Nanos_field_name protoreflect.Name = "nanos" + + Duration_Seconds_field_fullname protoreflect.FullName = "google.protobuf.Duration.seconds" + Duration_Nanos_field_fullname protoreflect.FullName = "google.protobuf.Duration.nanos" +) + +// Field numbers for google.protobuf.Duration. +const ( + Duration_Seconds_field_number protoreflect.FieldNumber = 1 + Duration_Nanos_field_number protoreflect.FieldNumber = 2 +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/empty_gen.go b/vendor/google.golang.org/protobuf/internal/genid/empty_gen.go new file mode 100644 index 00000000000..762abb34a4e --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/empty_gen.go @@ -0,0 +1,19 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-protos. DO NOT EDIT. + +package genid + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" +) + +const File_google_protobuf_empty_proto = "google/protobuf/empty.proto" + +// Names for google.protobuf.Empty. +const ( + Empty_message_name protoreflect.Name = "Empty" + Empty_message_fullname protoreflect.FullName = "google.protobuf.Empty" +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/field_mask_gen.go b/vendor/google.golang.org/protobuf/internal/genid/field_mask_gen.go new file mode 100644 index 00000000000..70bed453fee --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/field_mask_gen.go @@ -0,0 +1,31 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-protos. DO NOT EDIT. + +package genid + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" +) + +const File_google_protobuf_field_mask_proto = "google/protobuf/field_mask.proto" + +// Names for google.protobuf.FieldMask. +const ( + FieldMask_message_name protoreflect.Name = "FieldMask" + FieldMask_message_fullname protoreflect.FullName = "google.protobuf.FieldMask" +) + +// Field names for google.protobuf.FieldMask. +const ( + FieldMask_Paths_field_name protoreflect.Name = "paths" + + FieldMask_Paths_field_fullname protoreflect.FullName = "google.protobuf.FieldMask.paths" +) + +// Field numbers for google.protobuf.FieldMask. +const ( + FieldMask_Paths_field_number protoreflect.FieldNumber = 1 +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/goname.go b/vendor/google.golang.org/protobuf/internal/genid/goname.go new file mode 100644 index 00000000000..693d2e9e1fe --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/goname.go @@ -0,0 +1,25 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package genid + +// Go names of implementation-specific struct fields in generated messages. +const ( + State_goname = "state" + + SizeCache_goname = "sizeCache" + SizeCacheA_goname = "XXX_sizecache" + + WeakFields_goname = "weakFields" + WeakFieldsA_goname = "XXX_weak" + + UnknownFields_goname = "unknownFields" + UnknownFieldsA_goname = "XXX_unrecognized" + + ExtensionFields_goname = "extensionFields" + ExtensionFieldsA_goname = "XXX_InternalExtensions" + ExtensionFieldsB_goname = "XXX_extensions" + + WeakFieldPrefix_goname = "XXX_weak_" +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/map_entry.go b/vendor/google.golang.org/protobuf/internal/genid/map_entry.go new file mode 100644 index 00000000000..8f9ea02ff2a --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/map_entry.go @@ -0,0 +1,16 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package genid + +import protoreflect "google.golang.org/protobuf/reflect/protoreflect" + +// Generic field names and numbers for synthetic map entry messages. +const ( + MapEntry_Key_field_name protoreflect.Name = "key" + MapEntry_Value_field_name protoreflect.Name = "value" + + MapEntry_Key_field_number protoreflect.FieldNumber = 1 + MapEntry_Value_field_number protoreflect.FieldNumber = 2 +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/source_context_gen.go b/vendor/google.golang.org/protobuf/internal/genid/source_context_gen.go new file mode 100644 index 00000000000..3e99ae16c84 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/source_context_gen.go @@ -0,0 +1,31 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-protos. DO NOT EDIT. + +package genid + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" +) + +const File_google_protobuf_source_context_proto = "google/protobuf/source_context.proto" + +// Names for google.protobuf.SourceContext. +const ( + SourceContext_message_name protoreflect.Name = "SourceContext" + SourceContext_message_fullname protoreflect.FullName = "google.protobuf.SourceContext" +) + +// Field names for google.protobuf.SourceContext. +const ( + SourceContext_FileName_field_name protoreflect.Name = "file_name" + + SourceContext_FileName_field_fullname protoreflect.FullName = "google.protobuf.SourceContext.file_name" +) + +// Field numbers for google.protobuf.SourceContext. +const ( + SourceContext_FileName_field_number protoreflect.FieldNumber = 1 +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/struct_gen.go b/vendor/google.golang.org/protobuf/internal/genid/struct_gen.go new file mode 100644 index 00000000000..1a38944b26e --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/struct_gen.go @@ -0,0 +1,116 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-protos. DO NOT EDIT. + +package genid + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" +) + +const File_google_protobuf_struct_proto = "google/protobuf/struct.proto" + +// Full and short names for google.protobuf.NullValue. +const ( + NullValue_enum_fullname = "google.protobuf.NullValue" + NullValue_enum_name = "NullValue" +) + +// Names for google.protobuf.Struct. +const ( + Struct_message_name protoreflect.Name = "Struct" + Struct_message_fullname protoreflect.FullName = "google.protobuf.Struct" +) + +// Field names for google.protobuf.Struct. +const ( + Struct_Fields_field_name protoreflect.Name = "fields" + + Struct_Fields_field_fullname protoreflect.FullName = "google.protobuf.Struct.fields" +) + +// Field numbers for google.protobuf.Struct. +const ( + Struct_Fields_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.Struct.FieldsEntry. +const ( + Struct_FieldsEntry_message_name protoreflect.Name = "FieldsEntry" + Struct_FieldsEntry_message_fullname protoreflect.FullName = "google.protobuf.Struct.FieldsEntry" +) + +// Field names for google.protobuf.Struct.FieldsEntry. +const ( + Struct_FieldsEntry_Key_field_name protoreflect.Name = "key" + Struct_FieldsEntry_Value_field_name protoreflect.Name = "value" + + Struct_FieldsEntry_Key_field_fullname protoreflect.FullName = "google.protobuf.Struct.FieldsEntry.key" + Struct_FieldsEntry_Value_field_fullname protoreflect.FullName = "google.protobuf.Struct.FieldsEntry.value" +) + +// Field numbers for google.protobuf.Struct.FieldsEntry. +const ( + Struct_FieldsEntry_Key_field_number protoreflect.FieldNumber = 1 + Struct_FieldsEntry_Value_field_number protoreflect.FieldNumber = 2 +) + +// Names for google.protobuf.Value. +const ( + Value_message_name protoreflect.Name = "Value" + Value_message_fullname protoreflect.FullName = "google.protobuf.Value" +) + +// Field names for google.protobuf.Value. +const ( + Value_NullValue_field_name protoreflect.Name = "null_value" + Value_NumberValue_field_name protoreflect.Name = "number_value" + Value_StringValue_field_name protoreflect.Name = "string_value" + Value_BoolValue_field_name protoreflect.Name = "bool_value" + Value_StructValue_field_name protoreflect.Name = "struct_value" + Value_ListValue_field_name protoreflect.Name = "list_value" + + Value_NullValue_field_fullname protoreflect.FullName = "google.protobuf.Value.null_value" + Value_NumberValue_field_fullname protoreflect.FullName = "google.protobuf.Value.number_value" + Value_StringValue_field_fullname protoreflect.FullName = "google.protobuf.Value.string_value" + Value_BoolValue_field_fullname protoreflect.FullName = "google.protobuf.Value.bool_value" + Value_StructValue_field_fullname protoreflect.FullName = "google.protobuf.Value.struct_value" + Value_ListValue_field_fullname protoreflect.FullName = "google.protobuf.Value.list_value" +) + +// Field numbers for google.protobuf.Value. +const ( + Value_NullValue_field_number protoreflect.FieldNumber = 1 + Value_NumberValue_field_number protoreflect.FieldNumber = 2 + Value_StringValue_field_number protoreflect.FieldNumber = 3 + Value_BoolValue_field_number protoreflect.FieldNumber = 4 + Value_StructValue_field_number protoreflect.FieldNumber = 5 + Value_ListValue_field_number protoreflect.FieldNumber = 6 +) + +// Oneof names for google.protobuf.Value. +const ( + Value_Kind_oneof_name protoreflect.Name = "kind" + + Value_Kind_oneof_fullname protoreflect.FullName = "google.protobuf.Value.kind" +) + +// Names for google.protobuf.ListValue. +const ( + ListValue_message_name protoreflect.Name = "ListValue" + ListValue_message_fullname protoreflect.FullName = "google.protobuf.ListValue" +) + +// Field names for google.protobuf.ListValue. +const ( + ListValue_Values_field_name protoreflect.Name = "values" + + ListValue_Values_field_fullname protoreflect.FullName = "google.protobuf.ListValue.values" +) + +// Field numbers for google.protobuf.ListValue. +const ( + ListValue_Values_field_number protoreflect.FieldNumber = 1 +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/timestamp_gen.go b/vendor/google.golang.org/protobuf/internal/genid/timestamp_gen.go new file mode 100644 index 00000000000..f5cd5634c2e --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/timestamp_gen.go @@ -0,0 +1,34 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-protos. DO NOT EDIT. + +package genid + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" +) + +const File_google_protobuf_timestamp_proto = "google/protobuf/timestamp.proto" + +// Names for google.protobuf.Timestamp. +const ( + Timestamp_message_name protoreflect.Name = "Timestamp" + Timestamp_message_fullname protoreflect.FullName = "google.protobuf.Timestamp" +) + +// Field names for google.protobuf.Timestamp. +const ( + Timestamp_Seconds_field_name protoreflect.Name = "seconds" + Timestamp_Nanos_field_name protoreflect.Name = "nanos" + + Timestamp_Seconds_field_fullname protoreflect.FullName = "google.protobuf.Timestamp.seconds" + Timestamp_Nanos_field_fullname protoreflect.FullName = "google.protobuf.Timestamp.nanos" +) + +// Field numbers for google.protobuf.Timestamp. +const ( + Timestamp_Seconds_field_number protoreflect.FieldNumber = 1 + Timestamp_Nanos_field_number protoreflect.FieldNumber = 2 +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/type_gen.go b/vendor/google.golang.org/protobuf/internal/genid/type_gen.go new file mode 100644 index 00000000000..3bc710138ad --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/type_gen.go @@ -0,0 +1,184 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-protos. DO NOT EDIT. + +package genid + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" +) + +const File_google_protobuf_type_proto = "google/protobuf/type.proto" + +// Full and short names for google.protobuf.Syntax. +const ( + Syntax_enum_fullname = "google.protobuf.Syntax" + Syntax_enum_name = "Syntax" +) + +// Names for google.protobuf.Type. +const ( + Type_message_name protoreflect.Name = "Type" + Type_message_fullname protoreflect.FullName = "google.protobuf.Type" +) + +// Field names for google.protobuf.Type. +const ( + Type_Name_field_name protoreflect.Name = "name" + Type_Fields_field_name protoreflect.Name = "fields" + Type_Oneofs_field_name protoreflect.Name = "oneofs" + Type_Options_field_name protoreflect.Name = "options" + Type_SourceContext_field_name protoreflect.Name = "source_context" + Type_Syntax_field_name protoreflect.Name = "syntax" + + Type_Name_field_fullname protoreflect.FullName = "google.protobuf.Type.name" + Type_Fields_field_fullname protoreflect.FullName = "google.protobuf.Type.fields" + Type_Oneofs_field_fullname protoreflect.FullName = "google.protobuf.Type.oneofs" + Type_Options_field_fullname protoreflect.FullName = "google.protobuf.Type.options" + Type_SourceContext_field_fullname protoreflect.FullName = "google.protobuf.Type.source_context" + Type_Syntax_field_fullname protoreflect.FullName = "google.protobuf.Type.syntax" +) + +// Field numbers for google.protobuf.Type. +const ( + Type_Name_field_number protoreflect.FieldNumber = 1 + Type_Fields_field_number protoreflect.FieldNumber = 2 + Type_Oneofs_field_number protoreflect.FieldNumber = 3 + Type_Options_field_number protoreflect.FieldNumber = 4 + Type_SourceContext_field_number protoreflect.FieldNumber = 5 + Type_Syntax_field_number protoreflect.FieldNumber = 6 +) + +// Names for google.protobuf.Field. +const ( + Field_message_name protoreflect.Name = "Field" + Field_message_fullname protoreflect.FullName = "google.protobuf.Field" +) + +// Field names for google.protobuf.Field. +const ( + Field_Kind_field_name protoreflect.Name = "kind" + Field_Cardinality_field_name protoreflect.Name = "cardinality" + Field_Number_field_name protoreflect.Name = "number" + Field_Name_field_name protoreflect.Name = "name" + Field_TypeUrl_field_name protoreflect.Name = "type_url" + Field_OneofIndex_field_name protoreflect.Name = "oneof_index" + Field_Packed_field_name protoreflect.Name = "packed" + Field_Options_field_name protoreflect.Name = "options" + Field_JsonName_field_name protoreflect.Name = "json_name" + Field_DefaultValue_field_name protoreflect.Name = "default_value" + + Field_Kind_field_fullname protoreflect.FullName = "google.protobuf.Field.kind" + Field_Cardinality_field_fullname protoreflect.FullName = "google.protobuf.Field.cardinality" + Field_Number_field_fullname protoreflect.FullName = "google.protobuf.Field.number" + Field_Name_field_fullname protoreflect.FullName = "google.protobuf.Field.name" + Field_TypeUrl_field_fullname protoreflect.FullName = "google.protobuf.Field.type_url" + Field_OneofIndex_field_fullname protoreflect.FullName = "google.protobuf.Field.oneof_index" + Field_Packed_field_fullname protoreflect.FullName = "google.protobuf.Field.packed" + Field_Options_field_fullname protoreflect.FullName = "google.protobuf.Field.options" + Field_JsonName_field_fullname protoreflect.FullName = "google.protobuf.Field.json_name" + Field_DefaultValue_field_fullname protoreflect.FullName = "google.protobuf.Field.default_value" +) + +// Field numbers for google.protobuf.Field. +const ( + Field_Kind_field_number protoreflect.FieldNumber = 1 + Field_Cardinality_field_number protoreflect.FieldNumber = 2 + Field_Number_field_number protoreflect.FieldNumber = 3 + Field_Name_field_number protoreflect.FieldNumber = 4 + Field_TypeUrl_field_number protoreflect.FieldNumber = 6 + Field_OneofIndex_field_number protoreflect.FieldNumber = 7 + Field_Packed_field_number protoreflect.FieldNumber = 8 + Field_Options_field_number protoreflect.FieldNumber = 9 + Field_JsonName_field_number protoreflect.FieldNumber = 10 + Field_DefaultValue_field_number protoreflect.FieldNumber = 11 +) + +// Full and short names for google.protobuf.Field.Kind. +const ( + Field_Kind_enum_fullname = "google.protobuf.Field.Kind" + Field_Kind_enum_name = "Kind" +) + +// Full and short names for google.protobuf.Field.Cardinality. +const ( + Field_Cardinality_enum_fullname = "google.protobuf.Field.Cardinality" + Field_Cardinality_enum_name = "Cardinality" +) + +// Names for google.protobuf.Enum. +const ( + Enum_message_name protoreflect.Name = "Enum" + Enum_message_fullname protoreflect.FullName = "google.protobuf.Enum" +) + +// Field names for google.protobuf.Enum. +const ( + Enum_Name_field_name protoreflect.Name = "name" + Enum_Enumvalue_field_name protoreflect.Name = "enumvalue" + Enum_Options_field_name protoreflect.Name = "options" + Enum_SourceContext_field_name protoreflect.Name = "source_context" + Enum_Syntax_field_name protoreflect.Name = "syntax" + + Enum_Name_field_fullname protoreflect.FullName = "google.protobuf.Enum.name" + Enum_Enumvalue_field_fullname protoreflect.FullName = "google.protobuf.Enum.enumvalue" + Enum_Options_field_fullname protoreflect.FullName = "google.protobuf.Enum.options" + Enum_SourceContext_field_fullname protoreflect.FullName = "google.protobuf.Enum.source_context" + Enum_Syntax_field_fullname protoreflect.FullName = "google.protobuf.Enum.syntax" +) + +// Field numbers for google.protobuf.Enum. +const ( + Enum_Name_field_number protoreflect.FieldNumber = 1 + Enum_Enumvalue_field_number protoreflect.FieldNumber = 2 + Enum_Options_field_number protoreflect.FieldNumber = 3 + Enum_SourceContext_field_number protoreflect.FieldNumber = 4 + Enum_Syntax_field_number protoreflect.FieldNumber = 5 +) + +// Names for google.protobuf.EnumValue. +const ( + EnumValue_message_name protoreflect.Name = "EnumValue" + EnumValue_message_fullname protoreflect.FullName = "google.protobuf.EnumValue" +) + +// Field names for google.protobuf.EnumValue. +const ( + EnumValue_Name_field_name protoreflect.Name = "name" + EnumValue_Number_field_name protoreflect.Name = "number" + EnumValue_Options_field_name protoreflect.Name = "options" + + EnumValue_Name_field_fullname protoreflect.FullName = "google.protobuf.EnumValue.name" + EnumValue_Number_field_fullname protoreflect.FullName = "google.protobuf.EnumValue.number" + EnumValue_Options_field_fullname protoreflect.FullName = "google.protobuf.EnumValue.options" +) + +// Field numbers for google.protobuf.EnumValue. +const ( + EnumValue_Name_field_number protoreflect.FieldNumber = 1 + EnumValue_Number_field_number protoreflect.FieldNumber = 2 + EnumValue_Options_field_number protoreflect.FieldNumber = 3 +) + +// Names for google.protobuf.Option. +const ( + Option_message_name protoreflect.Name = "Option" + Option_message_fullname protoreflect.FullName = "google.protobuf.Option" +) + +// Field names for google.protobuf.Option. +const ( + Option_Name_field_name protoreflect.Name = "name" + Option_Value_field_name protoreflect.Name = "value" + + Option_Name_field_fullname protoreflect.FullName = "google.protobuf.Option.name" + Option_Value_field_fullname protoreflect.FullName = "google.protobuf.Option.value" +) + +// Field numbers for google.protobuf.Option. +const ( + Option_Name_field_number protoreflect.FieldNumber = 1 + Option_Value_field_number protoreflect.FieldNumber = 2 +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/wrappers.go b/vendor/google.golang.org/protobuf/internal/genid/wrappers.go new file mode 100644 index 00000000000..429384b85b0 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/wrappers.go @@ -0,0 +1,13 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package genid + +import protoreflect "google.golang.org/protobuf/reflect/protoreflect" + +// Generic field name and number for messages in wrappers.proto. +const ( + WrapperValue_Value_field_name protoreflect.Name = "value" + WrapperValue_Value_field_number protoreflect.FieldNumber = 1 +) diff --git a/vendor/google.golang.org/protobuf/internal/genid/wrappers_gen.go b/vendor/google.golang.org/protobuf/internal/genid/wrappers_gen.go new file mode 100644 index 00000000000..72527d2ab03 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/genid/wrappers_gen.go @@ -0,0 +1,175 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-protos. DO NOT EDIT. + +package genid + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" +) + +const File_google_protobuf_wrappers_proto = "google/protobuf/wrappers.proto" + +// Names for google.protobuf.DoubleValue. +const ( + DoubleValue_message_name protoreflect.Name = "DoubleValue" + DoubleValue_message_fullname protoreflect.FullName = "google.protobuf.DoubleValue" +) + +// Field names for google.protobuf.DoubleValue. +const ( + DoubleValue_Value_field_name protoreflect.Name = "value" + + DoubleValue_Value_field_fullname protoreflect.FullName = "google.protobuf.DoubleValue.value" +) + +// Field numbers for google.protobuf.DoubleValue. +const ( + DoubleValue_Value_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.FloatValue. +const ( + FloatValue_message_name protoreflect.Name = "FloatValue" + FloatValue_message_fullname protoreflect.FullName = "google.protobuf.FloatValue" +) + +// Field names for google.protobuf.FloatValue. +const ( + FloatValue_Value_field_name protoreflect.Name = "value" + + FloatValue_Value_field_fullname protoreflect.FullName = "google.protobuf.FloatValue.value" +) + +// Field numbers for google.protobuf.FloatValue. +const ( + FloatValue_Value_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.Int64Value. +const ( + Int64Value_message_name protoreflect.Name = "Int64Value" + Int64Value_message_fullname protoreflect.FullName = "google.protobuf.Int64Value" +) + +// Field names for google.protobuf.Int64Value. +const ( + Int64Value_Value_field_name protoreflect.Name = "value" + + Int64Value_Value_field_fullname protoreflect.FullName = "google.protobuf.Int64Value.value" +) + +// Field numbers for google.protobuf.Int64Value. +const ( + Int64Value_Value_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.UInt64Value. +const ( + UInt64Value_message_name protoreflect.Name = "UInt64Value" + UInt64Value_message_fullname protoreflect.FullName = "google.protobuf.UInt64Value" +) + +// Field names for google.protobuf.UInt64Value. +const ( + UInt64Value_Value_field_name protoreflect.Name = "value" + + UInt64Value_Value_field_fullname protoreflect.FullName = "google.protobuf.UInt64Value.value" +) + +// Field numbers for google.protobuf.UInt64Value. +const ( + UInt64Value_Value_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.Int32Value. +const ( + Int32Value_message_name protoreflect.Name = "Int32Value" + Int32Value_message_fullname protoreflect.FullName = "google.protobuf.Int32Value" +) + +// Field names for google.protobuf.Int32Value. +const ( + Int32Value_Value_field_name protoreflect.Name = "value" + + Int32Value_Value_field_fullname protoreflect.FullName = "google.protobuf.Int32Value.value" +) + +// Field numbers for google.protobuf.Int32Value. +const ( + Int32Value_Value_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.UInt32Value. +const ( + UInt32Value_message_name protoreflect.Name = "UInt32Value" + UInt32Value_message_fullname protoreflect.FullName = "google.protobuf.UInt32Value" +) + +// Field names for google.protobuf.UInt32Value. +const ( + UInt32Value_Value_field_name protoreflect.Name = "value" + + UInt32Value_Value_field_fullname protoreflect.FullName = "google.protobuf.UInt32Value.value" +) + +// Field numbers for google.protobuf.UInt32Value. +const ( + UInt32Value_Value_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.BoolValue. +const ( + BoolValue_message_name protoreflect.Name = "BoolValue" + BoolValue_message_fullname protoreflect.FullName = "google.protobuf.BoolValue" +) + +// Field names for google.protobuf.BoolValue. +const ( + BoolValue_Value_field_name protoreflect.Name = "value" + + BoolValue_Value_field_fullname protoreflect.FullName = "google.protobuf.BoolValue.value" +) + +// Field numbers for google.protobuf.BoolValue. +const ( + BoolValue_Value_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.StringValue. +const ( + StringValue_message_name protoreflect.Name = "StringValue" + StringValue_message_fullname protoreflect.FullName = "google.protobuf.StringValue" +) + +// Field names for google.protobuf.StringValue. +const ( + StringValue_Value_field_name protoreflect.Name = "value" + + StringValue_Value_field_fullname protoreflect.FullName = "google.protobuf.StringValue.value" +) + +// Field numbers for google.protobuf.StringValue. +const ( + StringValue_Value_field_number protoreflect.FieldNumber = 1 +) + +// Names for google.protobuf.BytesValue. +const ( + BytesValue_message_name protoreflect.Name = "BytesValue" + BytesValue_message_fullname protoreflect.FullName = "google.protobuf.BytesValue" +) + +// Field names for google.protobuf.BytesValue. +const ( + BytesValue_Value_field_name protoreflect.Name = "value" + + BytesValue_Value_field_fullname protoreflect.FullName = "google.protobuf.BytesValue.value" +) + +// Field numbers for google.protobuf.BytesValue. +const ( + BytesValue_Value_field_number protoreflect.FieldNumber = 1 +) diff --git a/vendor/google.golang.org/protobuf/internal/impl/api_export.go b/vendor/google.golang.org/protobuf/internal/impl/api_export.go new file mode 100644 index 00000000000..b5974528db6 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/api_export.go @@ -0,0 +1,177 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + "strconv" + + "google.golang.org/protobuf/encoding/prototext" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/proto" + pref "google.golang.org/protobuf/reflect/protoreflect" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +// Export is a zero-length named type that exists only to export a set of +// functions that we do not want to appear in godoc. +type Export struct{} + +// NewError formats a string according to the format specifier and arguments and +// returns an error that has a "proto" prefix. +func (Export) NewError(f string, x ...interface{}) error { + return errors.New(f, x...) +} + +// enum is any enum type generated by protoc-gen-go +// and must be a named int32 type. +type enum = interface{} + +// EnumOf returns the protoreflect.Enum interface over e. +// It returns nil if e is nil. +func (Export) EnumOf(e enum) pref.Enum { + switch e := e.(type) { + case nil: + return nil + case pref.Enum: + return e + default: + return legacyWrapEnum(reflect.ValueOf(e)) + } +} + +// EnumDescriptorOf returns the protoreflect.EnumDescriptor for e. +// It returns nil if e is nil. +func (Export) EnumDescriptorOf(e enum) pref.EnumDescriptor { + switch e := e.(type) { + case nil: + return nil + case pref.Enum: + return e.Descriptor() + default: + return LegacyLoadEnumDesc(reflect.TypeOf(e)) + } +} + +// EnumTypeOf returns the protoreflect.EnumType for e. +// It returns nil if e is nil. +func (Export) EnumTypeOf(e enum) pref.EnumType { + switch e := e.(type) { + case nil: + return nil + case pref.Enum: + return e.Type() + default: + return legacyLoadEnumType(reflect.TypeOf(e)) + } +} + +// EnumStringOf returns the enum value as a string, either as the name if +// the number is resolvable, or the number formatted as a string. +func (Export) EnumStringOf(ed pref.EnumDescriptor, n pref.EnumNumber) string { + ev := ed.Values().ByNumber(n) + if ev != nil { + return string(ev.Name()) + } + return strconv.Itoa(int(n)) +} + +// message is any message type generated by protoc-gen-go +// and must be a pointer to a named struct type. +type message = interface{} + +// legacyMessageWrapper wraps a v2 message as a v1 message. +type legacyMessageWrapper struct{ m pref.ProtoMessage } + +func (m legacyMessageWrapper) Reset() { proto.Reset(m.m) } +func (m legacyMessageWrapper) String() string { return Export{}.MessageStringOf(m.m) } +func (m legacyMessageWrapper) ProtoMessage() {} + +// ProtoMessageV1Of converts either a v1 or v2 message to a v1 message. +// It returns nil if m is nil. +func (Export) ProtoMessageV1Of(m message) piface.MessageV1 { + switch mv := m.(type) { + case nil: + return nil + case piface.MessageV1: + return mv + case unwrapper: + return Export{}.ProtoMessageV1Of(mv.protoUnwrap()) + case pref.ProtoMessage: + return legacyMessageWrapper{mv} + default: + panic(fmt.Sprintf("message %T is neither a v1 or v2 Message", m)) + } +} + +func (Export) protoMessageV2Of(m message) pref.ProtoMessage { + switch mv := m.(type) { + case nil: + return nil + case pref.ProtoMessage: + return mv + case legacyMessageWrapper: + return mv.m + case piface.MessageV1: + return nil + default: + panic(fmt.Sprintf("message %T is neither a v1 or v2 Message", m)) + } +} + +// ProtoMessageV2Of converts either a v1 or v2 message to a v2 message. +// It returns nil if m is nil. +func (Export) ProtoMessageV2Of(m message) pref.ProtoMessage { + if m == nil { + return nil + } + if mv := (Export{}).protoMessageV2Of(m); mv != nil { + return mv + } + return legacyWrapMessage(reflect.ValueOf(m)).Interface() +} + +// MessageOf returns the protoreflect.Message interface over m. +// It returns nil if m is nil. +func (Export) MessageOf(m message) pref.Message { + if m == nil { + return nil + } + if mv := (Export{}).protoMessageV2Of(m); mv != nil { + return mv.ProtoReflect() + } + return legacyWrapMessage(reflect.ValueOf(m)) +} + +// MessageDescriptorOf returns the protoreflect.MessageDescriptor for m. +// It returns nil if m is nil. +func (Export) MessageDescriptorOf(m message) pref.MessageDescriptor { + if m == nil { + return nil + } + if mv := (Export{}).protoMessageV2Of(m); mv != nil { + return mv.ProtoReflect().Descriptor() + } + return LegacyLoadMessageDesc(reflect.TypeOf(m)) +} + +// MessageTypeOf returns the protoreflect.MessageType for m. +// It returns nil if m is nil. +func (Export) MessageTypeOf(m message) pref.MessageType { + if m == nil { + return nil + } + if mv := (Export{}).protoMessageV2Of(m); mv != nil { + return mv.ProtoReflect().Type() + } + return legacyLoadMessageInfo(reflect.TypeOf(m), "") +} + +// MessageStringOf returns the message value as a string, +// which is the message serialized in the protobuf text format. +func (Export) MessageStringOf(m pref.ProtoMessage) string { + return prototext.MarshalOptions{Multiline: false}.Format(m) +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/checkinit.go b/vendor/google.golang.org/protobuf/internal/impl/checkinit.go new file mode 100644 index 00000000000..b82341e575c --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/checkinit.go @@ -0,0 +1,141 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "sync" + + "google.golang.org/protobuf/internal/errors" + pref "google.golang.org/protobuf/reflect/protoreflect" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +func (mi *MessageInfo) checkInitialized(in piface.CheckInitializedInput) (piface.CheckInitializedOutput, error) { + var p pointer + if ms, ok := in.Message.(*messageState); ok { + p = ms.pointer() + } else { + p = in.Message.(*messageReflectWrapper).pointer() + } + return piface.CheckInitializedOutput{}, mi.checkInitializedPointer(p) +} + +func (mi *MessageInfo) checkInitializedPointer(p pointer) error { + mi.init() + if !mi.needsInitCheck { + return nil + } + if p.IsNil() { + for _, f := range mi.orderedCoderFields { + if f.isRequired { + return errors.RequiredNotSet(string(mi.Desc.Fields().ByNumber(f.num).FullName())) + } + } + return nil + } + if mi.extensionOffset.IsValid() { + e := p.Apply(mi.extensionOffset).Extensions() + if err := mi.isInitExtensions(e); err != nil { + return err + } + } + for _, f := range mi.orderedCoderFields { + if !f.isRequired && f.funcs.isInit == nil { + continue + } + fptr := p.Apply(f.offset) + if f.isPointer && fptr.Elem().IsNil() { + if f.isRequired { + return errors.RequiredNotSet(string(mi.Desc.Fields().ByNumber(f.num).FullName())) + } + continue + } + if f.funcs.isInit == nil { + continue + } + if err := f.funcs.isInit(fptr, f); err != nil { + return err + } + } + return nil +} + +func (mi *MessageInfo) isInitExtensions(ext *map[int32]ExtensionField) error { + if ext == nil { + return nil + } + for _, x := range *ext { + ei := getExtensionFieldInfo(x.Type()) + if ei.funcs.isInit == nil { + continue + } + v := x.Value() + if !v.IsValid() { + continue + } + if err := ei.funcs.isInit(v); err != nil { + return err + } + } + return nil +} + +var ( + needsInitCheckMu sync.Mutex + needsInitCheckMap sync.Map +) + +// needsInitCheck reports whether a message needs to be checked for partial initialization. +// +// It returns true if the message transitively includes any required or extension fields. +func needsInitCheck(md pref.MessageDescriptor) bool { + if v, ok := needsInitCheckMap.Load(md); ok { + if has, ok := v.(bool); ok { + return has + } + } + needsInitCheckMu.Lock() + defer needsInitCheckMu.Unlock() + return needsInitCheckLocked(md) +} + +func needsInitCheckLocked(md pref.MessageDescriptor) (has bool) { + if v, ok := needsInitCheckMap.Load(md); ok { + // If has is true, we've previously determined that this message + // needs init checks. + // + // If has is false, we've previously determined that it can never + // be uninitialized. + // + // If has is not a bool, we've just encountered a cycle in the + // message graph. In this case, it is safe to return false: If + // the message does have required fields, we'll detect them later + // in the graph traversal. + has, ok := v.(bool) + return ok && has + } + needsInitCheckMap.Store(md, struct{}{}) // avoid cycles while descending into this message + defer func() { + needsInitCheckMap.Store(md, has) + }() + if md.RequiredNumbers().Len() > 0 { + return true + } + if md.ExtensionRanges().Len() > 0 { + return true + } + for i := 0; i < md.Fields().Len(); i++ { + fd := md.Fields().Get(i) + // Map keys are never messages, so just consider the map value. + if fd.IsMap() { + fd = fd.MapValue() + } + fmd := fd.Message() + if fmd != nil && needsInitCheckLocked(fmd) { + return true + } + } + return false +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_extension.go b/vendor/google.golang.org/protobuf/internal/impl/codec_extension.go new file mode 100644 index 00000000000..08d35170b66 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_extension.go @@ -0,0 +1,223 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "sync" + "sync/atomic" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/errors" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +type extensionFieldInfo struct { + wiretag uint64 + tagsize int + unmarshalNeedsValue bool + funcs valueCoderFuncs + validation validationInfo +} + +var legacyExtensionFieldInfoCache sync.Map // map[protoreflect.ExtensionType]*extensionFieldInfo + +func getExtensionFieldInfo(xt pref.ExtensionType) *extensionFieldInfo { + if xi, ok := xt.(*ExtensionInfo); ok { + xi.lazyInit() + return xi.info + } + return legacyLoadExtensionFieldInfo(xt) +} + +// legacyLoadExtensionFieldInfo dynamically loads a *ExtensionInfo for xt. +func legacyLoadExtensionFieldInfo(xt pref.ExtensionType) *extensionFieldInfo { + if xi, ok := legacyExtensionFieldInfoCache.Load(xt); ok { + return xi.(*extensionFieldInfo) + } + e := makeExtensionFieldInfo(xt.TypeDescriptor()) + if e, ok := legacyMessageTypeCache.LoadOrStore(xt, e); ok { + return e.(*extensionFieldInfo) + } + return e +} + +func makeExtensionFieldInfo(xd pref.ExtensionDescriptor) *extensionFieldInfo { + var wiretag uint64 + if !xd.IsPacked() { + wiretag = protowire.EncodeTag(xd.Number(), wireTypes[xd.Kind()]) + } else { + wiretag = protowire.EncodeTag(xd.Number(), protowire.BytesType) + } + e := &extensionFieldInfo{ + wiretag: wiretag, + tagsize: protowire.SizeVarint(wiretag), + funcs: encoderFuncsForValue(xd), + } + // Does the unmarshal function need a value passed to it? + // This is true for composite types, where we pass in a message, list, or map to fill in, + // and for enums, where we pass in a prototype value to specify the concrete enum type. + switch xd.Kind() { + case pref.MessageKind, pref.GroupKind, pref.EnumKind: + e.unmarshalNeedsValue = true + default: + if xd.Cardinality() == pref.Repeated { + e.unmarshalNeedsValue = true + } + } + return e +} + +type lazyExtensionValue struct { + atomicOnce uint32 // atomically set if value is valid + mu sync.Mutex + xi *extensionFieldInfo + value pref.Value + b []byte + fn func() pref.Value +} + +type ExtensionField struct { + typ pref.ExtensionType + + // value is either the value of GetValue, + // or a *lazyExtensionValue that then returns the value of GetValue. + value pref.Value + lazy *lazyExtensionValue +} + +func (f *ExtensionField) appendLazyBytes(xt pref.ExtensionType, xi *extensionFieldInfo, num protowire.Number, wtyp protowire.Type, b []byte) { + if f.lazy == nil { + f.lazy = &lazyExtensionValue{xi: xi} + } + f.typ = xt + f.lazy.xi = xi + f.lazy.b = protowire.AppendTag(f.lazy.b, num, wtyp) + f.lazy.b = append(f.lazy.b, b...) +} + +func (f *ExtensionField) canLazy(xt pref.ExtensionType) bool { + if f.typ == nil { + return true + } + if f.typ == xt && f.lazy != nil && atomic.LoadUint32(&f.lazy.atomicOnce) == 0 { + return true + } + return false +} + +func (f *ExtensionField) lazyInit() { + f.lazy.mu.Lock() + defer f.lazy.mu.Unlock() + if atomic.LoadUint32(&f.lazy.atomicOnce) == 1 { + return + } + if f.lazy.xi != nil { + b := f.lazy.b + val := f.typ.New() + for len(b) > 0 { + var tag uint64 + if b[0] < 0x80 { + tag = uint64(b[0]) + b = b[1:] + } else if len(b) >= 2 && b[1] < 128 { + tag = uint64(b[0]&0x7f) + uint64(b[1])<<7 + b = b[2:] + } else { + var n int + tag, n = protowire.ConsumeVarint(b) + if n < 0 { + panic(errors.New("bad tag in lazy extension decoding")) + } + b = b[n:] + } + num := protowire.Number(tag >> 3) + wtyp := protowire.Type(tag & 7) + var out unmarshalOutput + var err error + val, out, err = f.lazy.xi.funcs.unmarshal(b, val, num, wtyp, lazyUnmarshalOptions) + if err != nil { + panic(errors.New("decode failure in lazy extension decoding: %v", err)) + } + b = b[out.n:] + } + f.lazy.value = val + } else { + f.lazy.value = f.lazy.fn() + } + f.lazy.xi = nil + f.lazy.fn = nil + f.lazy.b = nil + atomic.StoreUint32(&f.lazy.atomicOnce, 1) +} + +// Set sets the type and value of the extension field. +// This must not be called concurrently. +func (f *ExtensionField) Set(t pref.ExtensionType, v pref.Value) { + f.typ = t + f.value = v + f.lazy = nil +} + +// SetLazy sets the type and a value that is to be lazily evaluated upon first use. +// This must not be called concurrently. +func (f *ExtensionField) SetLazy(t pref.ExtensionType, fn func() pref.Value) { + f.typ = t + f.lazy = &lazyExtensionValue{fn: fn} +} + +// Value returns the value of the extension field. +// This may be called concurrently. +func (f *ExtensionField) Value() pref.Value { + if f.lazy != nil { + if atomic.LoadUint32(&f.lazy.atomicOnce) == 0 { + f.lazyInit() + } + return f.lazy.value + } + return f.value +} + +// Type returns the type of the extension field. +// This may be called concurrently. +func (f ExtensionField) Type() pref.ExtensionType { + return f.typ +} + +// IsSet returns whether the extension field is set. +// This may be called concurrently. +func (f ExtensionField) IsSet() bool { + return f.typ != nil +} + +// IsLazy reports whether a field is lazily encoded. +// It is exported for testing. +func IsLazy(m pref.Message, fd pref.FieldDescriptor) bool { + var mi *MessageInfo + var p pointer + switch m := m.(type) { + case *messageState: + mi = m.messageInfo() + p = m.pointer() + case *messageReflectWrapper: + mi = m.messageInfo() + p = m.pointer() + default: + return false + } + xd, ok := fd.(pref.ExtensionTypeDescriptor) + if !ok { + return false + } + xt := xd.Type() + ext := mi.extensionMap(p) + if ext == nil { + return false + } + f, ok := (*ext)[int32(fd.Number())] + if !ok { + return false + } + return f.typ == xt && f.lazy != nil && atomic.LoadUint32(&f.lazy.atomicOnce) == 0 +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_field.go b/vendor/google.golang.org/protobuf/internal/impl/codec_field.go new file mode 100644 index 00000000000..c00744d385c --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_field.go @@ -0,0 +1,828 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + "sync" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/proto" + pref "google.golang.org/protobuf/reflect/protoreflect" + preg "google.golang.org/protobuf/reflect/protoregistry" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +type errInvalidUTF8 struct{} + +func (errInvalidUTF8) Error() string { return "string field contains invalid UTF-8" } +func (errInvalidUTF8) InvalidUTF8() bool { return true } + +// initOneofFieldCoders initializes the fast-path functions for the fields in a oneof. +// +// For size, marshal, and isInit operations, functions are set only on the first field +// in the oneof. The functions are called when the oneof is non-nil, and will dispatch +// to the appropriate field-specific function as necessary. +// +// The unmarshal function is set on each field individually as usual. +func (mi *MessageInfo) initOneofFieldCoders(od pref.OneofDescriptor, si structInfo) { + fs := si.oneofsByName[od.Name()] + ft := fs.Type + oneofFields := make(map[reflect.Type]*coderFieldInfo) + needIsInit := false + fields := od.Fields() + for i, lim := 0, fields.Len(); i < lim; i++ { + fd := od.Fields().Get(i) + num := fd.Number() + // Make a copy of the original coderFieldInfo for use in unmarshaling. + // + // oneofFields[oneofType].funcs.marshal is the field-specific marshal function. + // + // mi.coderFields[num].marshal is set on only the first field in the oneof, + // and dispatches to the field-specific marshaler in oneofFields. + cf := *mi.coderFields[num] + ot := si.oneofWrappersByNumber[num] + cf.ft = ot.Field(0).Type + cf.mi, cf.funcs = fieldCoder(fd, cf.ft) + oneofFields[ot] = &cf + if cf.funcs.isInit != nil { + needIsInit = true + } + mi.coderFields[num].funcs.unmarshal = func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { + var vw reflect.Value // pointer to wrapper type + vi := p.AsValueOf(ft).Elem() // oneof field value of interface kind + if !vi.IsNil() && !vi.Elem().IsNil() && vi.Elem().Elem().Type() == ot { + vw = vi.Elem() + } else { + vw = reflect.New(ot) + } + out, err := cf.funcs.unmarshal(b, pointerOfValue(vw).Apply(zeroOffset), wtyp, &cf, opts) + if err != nil { + return out, err + } + vi.Set(vw) + return out, nil + } + } + getInfo := func(p pointer) (pointer, *coderFieldInfo) { + v := p.AsValueOf(ft).Elem() + if v.IsNil() { + return pointer{}, nil + } + v = v.Elem() // interface -> *struct + if v.IsNil() { + return pointer{}, nil + } + return pointerOfValue(v).Apply(zeroOffset), oneofFields[v.Elem().Type()] + } + first := mi.coderFields[od.Fields().Get(0).Number()] + first.funcs.size = func(p pointer, _ *coderFieldInfo, opts marshalOptions) int { + p, info := getInfo(p) + if info == nil || info.funcs.size == nil { + return 0 + } + return info.funcs.size(p, info, opts) + } + first.funcs.marshal = func(b []byte, p pointer, _ *coderFieldInfo, opts marshalOptions) ([]byte, error) { + p, info := getInfo(p) + if info == nil || info.funcs.marshal == nil { + return b, nil + } + return info.funcs.marshal(b, p, info, opts) + } + first.funcs.merge = func(dst, src pointer, _ *coderFieldInfo, opts mergeOptions) { + srcp, srcinfo := getInfo(src) + if srcinfo == nil || srcinfo.funcs.merge == nil { + return + } + dstp, dstinfo := getInfo(dst) + if dstinfo != srcinfo { + dst.AsValueOf(ft).Elem().Set(reflect.New(src.AsValueOf(ft).Elem().Elem().Elem().Type())) + dstp = pointerOfValue(dst.AsValueOf(ft).Elem().Elem()).Apply(zeroOffset) + } + srcinfo.funcs.merge(dstp, srcp, srcinfo, opts) + } + if needIsInit { + first.funcs.isInit = func(p pointer, _ *coderFieldInfo) error { + p, info := getInfo(p) + if info == nil || info.funcs.isInit == nil { + return nil + } + return info.funcs.isInit(p, info) + } + } +} + +func makeWeakMessageFieldCoder(fd pref.FieldDescriptor) pointerCoderFuncs { + var once sync.Once + var messageType pref.MessageType + lazyInit := func() { + once.Do(func() { + messageName := fd.Message().FullName() + messageType, _ = preg.GlobalTypes.FindMessageByName(messageName) + }) + } + + return pointerCoderFuncs{ + size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { + m, ok := p.WeakFields().get(f.num) + if !ok { + return 0 + } + lazyInit() + if messageType == nil { + panic(fmt.Sprintf("weak message %v is not linked in", fd.Message().FullName())) + } + return sizeMessage(m, f.tagsize, opts) + }, + marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + m, ok := p.WeakFields().get(f.num) + if !ok { + return b, nil + } + lazyInit() + if messageType == nil { + panic(fmt.Sprintf("weak message %v is not linked in", fd.Message().FullName())) + } + return appendMessage(b, m, f.wiretag, opts) + }, + unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { + fs := p.WeakFields() + m, ok := fs.get(f.num) + if !ok { + lazyInit() + if messageType == nil { + return unmarshalOutput{}, errUnknown + } + m = messageType.New().Interface() + fs.set(f.num, m) + } + return consumeMessage(b, m, wtyp, opts) + }, + isInit: func(p pointer, f *coderFieldInfo) error { + m, ok := p.WeakFields().get(f.num) + if !ok { + return nil + } + return proto.CheckInitialized(m) + }, + merge: func(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { + sm, ok := src.WeakFields().get(f.num) + if !ok { + return + } + dm, ok := dst.WeakFields().get(f.num) + if !ok { + lazyInit() + if messageType == nil { + panic(fmt.Sprintf("weak message %v is not linked in", fd.Message().FullName())) + } + dm = messageType.New().Interface() + dst.WeakFields().set(f.num, dm) + } + opts.Merge(dm, sm) + }, + } +} + +func makeMessageFieldCoder(fd pref.FieldDescriptor, ft reflect.Type) pointerCoderFuncs { + if mi := getMessageInfo(ft); mi != nil { + funcs := pointerCoderFuncs{ + size: sizeMessageInfo, + marshal: appendMessageInfo, + unmarshal: consumeMessageInfo, + merge: mergeMessage, + } + if needsInitCheck(mi.Desc) { + funcs.isInit = isInitMessageInfo + } + return funcs + } else { + return pointerCoderFuncs{ + size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { + m := asMessage(p.AsValueOf(ft).Elem()) + return sizeMessage(m, f.tagsize, opts) + }, + marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + m := asMessage(p.AsValueOf(ft).Elem()) + return appendMessage(b, m, f.wiretag, opts) + }, + unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { + mp := p.AsValueOf(ft).Elem() + if mp.IsNil() { + mp.Set(reflect.New(ft.Elem())) + } + return consumeMessage(b, asMessage(mp), wtyp, opts) + }, + isInit: func(p pointer, f *coderFieldInfo) error { + m := asMessage(p.AsValueOf(ft).Elem()) + return proto.CheckInitialized(m) + }, + merge: mergeMessage, + } + } +} + +func sizeMessageInfo(p pointer, f *coderFieldInfo, opts marshalOptions) int { + return protowire.SizeBytes(f.mi.sizePointer(p.Elem(), opts)) + f.tagsize +} + +func appendMessageInfo(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(f.mi.sizePointer(p.Elem(), opts))) + return f.mi.marshalAppendPointer(b, p.Elem(), opts) +} + +func consumeMessageInfo(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + if p.Elem().IsNil() { + p.SetPointer(pointerOfValue(reflect.New(f.mi.GoReflectType.Elem()))) + } + o, err := f.mi.unmarshalPointer(v, p.Elem(), 0, opts) + if err != nil { + return out, err + } + out.n = n + out.initialized = o.initialized + return out, nil +} + +func isInitMessageInfo(p pointer, f *coderFieldInfo) error { + return f.mi.checkInitializedPointer(p.Elem()) +} + +func sizeMessage(m proto.Message, tagsize int, _ marshalOptions) int { + return protowire.SizeBytes(proto.Size(m)) + tagsize +} + +func appendMessage(b []byte, m proto.Message, wiretag uint64, opts marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, uint64(proto.Size(m))) + return opts.Options().MarshalAppend(b, m) +} + +func consumeMessage(b []byte, m proto.Message, wtyp protowire.Type, opts unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + o, err := opts.Options().UnmarshalState(piface.UnmarshalInput{ + Buf: v, + Message: m.ProtoReflect(), + }) + if err != nil { + return out, err + } + out.n = n + out.initialized = o.Flags&piface.UnmarshalInitialized != 0 + return out, nil +} + +func sizeMessageValue(v pref.Value, tagsize int, opts marshalOptions) int { + m := v.Message().Interface() + return sizeMessage(m, tagsize, opts) +} + +func appendMessageValue(b []byte, v pref.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { + m := v.Message().Interface() + return appendMessage(b, m, wiretag, opts) +} + +func consumeMessageValue(b []byte, v pref.Value, _ protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (pref.Value, unmarshalOutput, error) { + m := v.Message().Interface() + out, err := consumeMessage(b, m, wtyp, opts) + return v, out, err +} + +func isInitMessageValue(v pref.Value) error { + m := v.Message().Interface() + return proto.CheckInitialized(m) +} + +var coderMessageValue = valueCoderFuncs{ + size: sizeMessageValue, + marshal: appendMessageValue, + unmarshal: consumeMessageValue, + isInit: isInitMessageValue, + merge: mergeMessageValue, +} + +func sizeGroupValue(v pref.Value, tagsize int, opts marshalOptions) int { + m := v.Message().Interface() + return sizeGroup(m, tagsize, opts) +} + +func appendGroupValue(b []byte, v pref.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { + m := v.Message().Interface() + return appendGroup(b, m, wiretag, opts) +} + +func consumeGroupValue(b []byte, v pref.Value, num protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (pref.Value, unmarshalOutput, error) { + m := v.Message().Interface() + out, err := consumeGroup(b, m, num, wtyp, opts) + return v, out, err +} + +var coderGroupValue = valueCoderFuncs{ + size: sizeGroupValue, + marshal: appendGroupValue, + unmarshal: consumeGroupValue, + isInit: isInitMessageValue, + merge: mergeMessageValue, +} + +func makeGroupFieldCoder(fd pref.FieldDescriptor, ft reflect.Type) pointerCoderFuncs { + num := fd.Number() + if mi := getMessageInfo(ft); mi != nil { + funcs := pointerCoderFuncs{ + size: sizeGroupType, + marshal: appendGroupType, + unmarshal: consumeGroupType, + merge: mergeMessage, + } + if needsInitCheck(mi.Desc) { + funcs.isInit = isInitMessageInfo + } + return funcs + } else { + return pointerCoderFuncs{ + size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { + m := asMessage(p.AsValueOf(ft).Elem()) + return sizeGroup(m, f.tagsize, opts) + }, + marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + m := asMessage(p.AsValueOf(ft).Elem()) + return appendGroup(b, m, f.wiretag, opts) + }, + unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { + mp := p.AsValueOf(ft).Elem() + if mp.IsNil() { + mp.Set(reflect.New(ft.Elem())) + } + return consumeGroup(b, asMessage(mp), num, wtyp, opts) + }, + isInit: func(p pointer, f *coderFieldInfo) error { + m := asMessage(p.AsValueOf(ft).Elem()) + return proto.CheckInitialized(m) + }, + merge: mergeMessage, + } + } +} + +func sizeGroupType(p pointer, f *coderFieldInfo, opts marshalOptions) int { + return 2*f.tagsize + f.mi.sizePointer(p.Elem(), opts) +} + +func appendGroupType(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, f.wiretag) // start group + b, err := f.mi.marshalAppendPointer(b, p.Elem(), opts) + b = protowire.AppendVarint(b, f.wiretag+1) // end group + return b, err +} + +func consumeGroupType(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.StartGroupType { + return out, errUnknown + } + if p.Elem().IsNil() { + p.SetPointer(pointerOfValue(reflect.New(f.mi.GoReflectType.Elem()))) + } + return f.mi.unmarshalPointer(b, p.Elem(), f.num, opts) +} + +func sizeGroup(m proto.Message, tagsize int, _ marshalOptions) int { + return 2*tagsize + proto.Size(m) +} + +func appendGroup(b []byte, m proto.Message, wiretag uint64, opts marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) // start group + b, err := opts.Options().MarshalAppend(b, m) + b = protowire.AppendVarint(b, wiretag+1) // end group + return b, err +} + +func consumeGroup(b []byte, m proto.Message, num protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.StartGroupType { + return out, errUnknown + } + b, n := protowire.ConsumeGroup(num, b) + if n < 0 { + return out, protowire.ParseError(n) + } + o, err := opts.Options().UnmarshalState(piface.UnmarshalInput{ + Buf: b, + Message: m.ProtoReflect(), + }) + if err != nil { + return out, err + } + out.n = n + out.initialized = o.Flags&piface.UnmarshalInitialized != 0 + return out, nil +} + +func makeMessageSliceFieldCoder(fd pref.FieldDescriptor, ft reflect.Type) pointerCoderFuncs { + if mi := getMessageInfo(ft); mi != nil { + funcs := pointerCoderFuncs{ + size: sizeMessageSliceInfo, + marshal: appendMessageSliceInfo, + unmarshal: consumeMessageSliceInfo, + merge: mergeMessageSlice, + } + if needsInitCheck(mi.Desc) { + funcs.isInit = isInitMessageSliceInfo + } + return funcs + } + return pointerCoderFuncs{ + size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { + return sizeMessageSlice(p, ft, f.tagsize, opts) + }, + marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + return appendMessageSlice(b, p, f.wiretag, ft, opts) + }, + unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { + return consumeMessageSlice(b, p, ft, wtyp, opts) + }, + isInit: func(p pointer, f *coderFieldInfo) error { + return isInitMessageSlice(p, ft) + }, + merge: mergeMessageSlice, + } +} + +func sizeMessageSliceInfo(p pointer, f *coderFieldInfo, opts marshalOptions) int { + s := p.PointerSlice() + n := 0 + for _, v := range s { + n += protowire.SizeBytes(f.mi.sizePointer(v, opts)) + f.tagsize + } + return n +} + +func appendMessageSliceInfo(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + s := p.PointerSlice() + var err error + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + siz := f.mi.sizePointer(v, opts) + b = protowire.AppendVarint(b, uint64(siz)) + b, err = f.mi.marshalAppendPointer(b, v, opts) + if err != nil { + return b, err + } + } + return b, nil +} + +func consumeMessageSliceInfo(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + m := reflect.New(f.mi.GoReflectType.Elem()).Interface() + mp := pointerOfIface(m) + o, err := f.mi.unmarshalPointer(v, mp, 0, opts) + if err != nil { + return out, err + } + p.AppendPointerSlice(mp) + out.n = n + out.initialized = o.initialized + return out, nil +} + +func isInitMessageSliceInfo(p pointer, f *coderFieldInfo) error { + s := p.PointerSlice() + for _, v := range s { + if err := f.mi.checkInitializedPointer(v); err != nil { + return err + } + } + return nil +} + +func sizeMessageSlice(p pointer, goType reflect.Type, tagsize int, _ marshalOptions) int { + s := p.PointerSlice() + n := 0 + for _, v := range s { + m := asMessage(v.AsValueOf(goType.Elem())) + n += protowire.SizeBytes(proto.Size(m)) + tagsize + } + return n +} + +func appendMessageSlice(b []byte, p pointer, wiretag uint64, goType reflect.Type, opts marshalOptions) ([]byte, error) { + s := p.PointerSlice() + var err error + for _, v := range s { + m := asMessage(v.AsValueOf(goType.Elem())) + b = protowire.AppendVarint(b, wiretag) + siz := proto.Size(m) + b = protowire.AppendVarint(b, uint64(siz)) + b, err = opts.Options().MarshalAppend(b, m) + if err != nil { + return b, err + } + } + return b, nil +} + +func consumeMessageSlice(b []byte, p pointer, goType reflect.Type, wtyp protowire.Type, opts unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + mp := reflect.New(goType.Elem()) + o, err := opts.Options().UnmarshalState(piface.UnmarshalInput{ + Buf: v, + Message: asMessage(mp).ProtoReflect(), + }) + if err != nil { + return out, err + } + p.AppendPointerSlice(pointerOfValue(mp)) + out.n = n + out.initialized = o.Flags&piface.UnmarshalInitialized != 0 + return out, nil +} + +func isInitMessageSlice(p pointer, goType reflect.Type) error { + s := p.PointerSlice() + for _, v := range s { + m := asMessage(v.AsValueOf(goType.Elem())) + if err := proto.CheckInitialized(m); err != nil { + return err + } + } + return nil +} + +// Slices of messages + +func sizeMessageSliceValue(listv pref.Value, tagsize int, opts marshalOptions) int { + list := listv.List() + n := 0 + for i, llen := 0, list.Len(); i < llen; i++ { + m := list.Get(i).Message().Interface() + n += protowire.SizeBytes(proto.Size(m)) + tagsize + } + return n +} + +func appendMessageSliceValue(b []byte, listv pref.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { + list := listv.List() + mopts := opts.Options() + for i, llen := 0, list.Len(); i < llen; i++ { + m := list.Get(i).Message().Interface() + b = protowire.AppendVarint(b, wiretag) + siz := proto.Size(m) + b = protowire.AppendVarint(b, uint64(siz)) + var err error + b, err = mopts.MarshalAppend(b, m) + if err != nil { + return b, err + } + } + return b, nil +} + +func consumeMessageSliceValue(b []byte, listv pref.Value, _ protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (_ pref.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp != protowire.BytesType { + return pref.Value{}, out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return pref.Value{}, out, protowire.ParseError(n) + } + m := list.NewElement() + o, err := opts.Options().UnmarshalState(piface.UnmarshalInput{ + Buf: v, + Message: m.Message(), + }) + if err != nil { + return pref.Value{}, out, err + } + list.Append(m) + out.n = n + out.initialized = o.Flags&piface.UnmarshalInitialized != 0 + return listv, out, nil +} + +func isInitMessageSliceValue(listv pref.Value) error { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + m := list.Get(i).Message().Interface() + if err := proto.CheckInitialized(m); err != nil { + return err + } + } + return nil +} + +var coderMessageSliceValue = valueCoderFuncs{ + size: sizeMessageSliceValue, + marshal: appendMessageSliceValue, + unmarshal: consumeMessageSliceValue, + isInit: isInitMessageSliceValue, + merge: mergeMessageListValue, +} + +func sizeGroupSliceValue(listv pref.Value, tagsize int, opts marshalOptions) int { + list := listv.List() + n := 0 + for i, llen := 0, list.Len(); i < llen; i++ { + m := list.Get(i).Message().Interface() + n += 2*tagsize + proto.Size(m) + } + return n +} + +func appendGroupSliceValue(b []byte, listv pref.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { + list := listv.List() + mopts := opts.Options() + for i, llen := 0, list.Len(); i < llen; i++ { + m := list.Get(i).Message().Interface() + b = protowire.AppendVarint(b, wiretag) // start group + var err error + b, err = mopts.MarshalAppend(b, m) + if err != nil { + return b, err + } + b = protowire.AppendVarint(b, wiretag+1) // end group + } + return b, nil +} + +func consumeGroupSliceValue(b []byte, listv pref.Value, num protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (_ pref.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp != protowire.StartGroupType { + return pref.Value{}, out, errUnknown + } + b, n := protowire.ConsumeGroup(num, b) + if n < 0 { + return pref.Value{}, out, protowire.ParseError(n) + } + m := list.NewElement() + o, err := opts.Options().UnmarshalState(piface.UnmarshalInput{ + Buf: b, + Message: m.Message(), + }) + if err != nil { + return pref.Value{}, out, err + } + list.Append(m) + out.n = n + out.initialized = o.Flags&piface.UnmarshalInitialized != 0 + return listv, out, nil +} + +var coderGroupSliceValue = valueCoderFuncs{ + size: sizeGroupSliceValue, + marshal: appendGroupSliceValue, + unmarshal: consumeGroupSliceValue, + isInit: isInitMessageSliceValue, + merge: mergeMessageListValue, +} + +func makeGroupSliceFieldCoder(fd pref.FieldDescriptor, ft reflect.Type) pointerCoderFuncs { + num := fd.Number() + if mi := getMessageInfo(ft); mi != nil { + funcs := pointerCoderFuncs{ + size: sizeGroupSliceInfo, + marshal: appendGroupSliceInfo, + unmarshal: consumeGroupSliceInfo, + merge: mergeMessageSlice, + } + if needsInitCheck(mi.Desc) { + funcs.isInit = isInitMessageSliceInfo + } + return funcs + } + return pointerCoderFuncs{ + size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { + return sizeGroupSlice(p, ft, f.tagsize, opts) + }, + marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + return appendGroupSlice(b, p, f.wiretag, ft, opts) + }, + unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { + return consumeGroupSlice(b, p, num, wtyp, ft, opts) + }, + isInit: func(p pointer, f *coderFieldInfo) error { + return isInitMessageSlice(p, ft) + }, + merge: mergeMessageSlice, + } +} + +func sizeGroupSlice(p pointer, messageType reflect.Type, tagsize int, _ marshalOptions) int { + s := p.PointerSlice() + n := 0 + for _, v := range s { + m := asMessage(v.AsValueOf(messageType.Elem())) + n += 2*tagsize + proto.Size(m) + } + return n +} + +func appendGroupSlice(b []byte, p pointer, wiretag uint64, messageType reflect.Type, opts marshalOptions) ([]byte, error) { + s := p.PointerSlice() + var err error + for _, v := range s { + m := asMessage(v.AsValueOf(messageType.Elem())) + b = protowire.AppendVarint(b, wiretag) // start group + b, err = opts.Options().MarshalAppend(b, m) + if err != nil { + return b, err + } + b = protowire.AppendVarint(b, wiretag+1) // end group + } + return b, nil +} + +func consumeGroupSlice(b []byte, p pointer, num protowire.Number, wtyp protowire.Type, goType reflect.Type, opts unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.StartGroupType { + return out, errUnknown + } + b, n := protowire.ConsumeGroup(num, b) + if n < 0 { + return out, protowire.ParseError(n) + } + mp := reflect.New(goType.Elem()) + o, err := opts.Options().UnmarshalState(piface.UnmarshalInput{ + Buf: b, + Message: asMessage(mp).ProtoReflect(), + }) + if err != nil { + return out, err + } + p.AppendPointerSlice(pointerOfValue(mp)) + out.n = n + out.initialized = o.Flags&piface.UnmarshalInitialized != 0 + return out, nil +} + +func sizeGroupSliceInfo(p pointer, f *coderFieldInfo, opts marshalOptions) int { + s := p.PointerSlice() + n := 0 + for _, v := range s { + n += 2*f.tagsize + f.mi.sizePointer(v, opts) + } + return n +} + +func appendGroupSliceInfo(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + s := p.PointerSlice() + var err error + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) // start group + b, err = f.mi.marshalAppendPointer(b, v, opts) + if err != nil { + return b, err + } + b = protowire.AppendVarint(b, f.wiretag+1) // end group + } + return b, nil +} + +func consumeGroupSliceInfo(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { + if wtyp != protowire.StartGroupType { + return unmarshalOutput{}, errUnknown + } + m := reflect.New(f.mi.GoReflectType.Elem()).Interface() + mp := pointerOfIface(m) + out, err := f.mi.unmarshalPointer(b, mp, f.num, opts) + if err != nil { + return out, err + } + p.AppendPointerSlice(mp) + return out, nil +} + +func asMessage(v reflect.Value) pref.ProtoMessage { + if m, ok := v.Interface().(pref.ProtoMessage); ok { + return m + } + return legacyWrapMessage(v).Interface() +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_gen.go b/vendor/google.golang.org/protobuf/internal/impl/codec_gen.go new file mode 100644 index 00000000000..ff198d0a153 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_gen.go @@ -0,0 +1,5637 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-types. DO NOT EDIT. + +package impl + +import ( + "math" + "unicode/utf8" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/reflect/protoreflect" +) + +// sizeBool returns the size of wire encoding a bool pointer as a Bool. +func sizeBool(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Bool() + return f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) +} + +// appendBool wire encodes a bool pointer as a Bool. +func appendBool(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Bool() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeBool(v)) + return b, nil +} + +// consumeBool wire decodes a bool pointer as a Bool. +func consumeBool(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Bool() = protowire.DecodeBool(v) + out.n = n + return out, nil +} + +var coderBool = pointerCoderFuncs{ + size: sizeBool, + marshal: appendBool, + unmarshal: consumeBool, + merge: mergeBool, +} + +// sizeBoolNoZero returns the size of wire encoding a bool pointer as a Bool. +// The zero value is not encoded. +func sizeBoolNoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Bool() + if v == false { + return 0 + } + return f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) +} + +// appendBoolNoZero wire encodes a bool pointer as a Bool. +// The zero value is not encoded. +func appendBoolNoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Bool() + if v == false { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeBool(v)) + return b, nil +} + +var coderBoolNoZero = pointerCoderFuncs{ + size: sizeBoolNoZero, + marshal: appendBoolNoZero, + unmarshal: consumeBool, + merge: mergeBoolNoZero, +} + +// sizeBoolPtr returns the size of wire encoding a *bool pointer as a Bool. +// It panics if the pointer is nil. +func sizeBoolPtr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := **p.BoolPtr() + return f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) +} + +// appendBoolPtr wire encodes a *bool pointer as a Bool. +// It panics if the pointer is nil. +func appendBoolPtr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.BoolPtr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeBool(v)) + return b, nil +} + +// consumeBoolPtr wire decodes a *bool pointer as a Bool. +func consumeBoolPtr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.BoolPtr() + if *vp == nil { + *vp = new(bool) + } + **vp = protowire.DecodeBool(v) + out.n = n + return out, nil +} + +var coderBoolPtr = pointerCoderFuncs{ + size: sizeBoolPtr, + marshal: appendBoolPtr, + unmarshal: consumeBoolPtr, + merge: mergeBoolPtr, +} + +// sizeBoolSlice returns the size of wire encoding a []bool pointer as a repeated Bool. +func sizeBoolSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.BoolSlice() + for _, v := range s { + size += f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) + } + return size +} + +// appendBoolSlice encodes a []bool pointer as a repeated Bool. +func appendBoolSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.BoolSlice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeBool(v)) + } + return b, nil +} + +// consumeBoolSlice wire decodes a []bool pointer as a repeated Bool. +func consumeBoolSlice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.BoolSlice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, protowire.DecodeBool(v)) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, protowire.DecodeBool(v)) + out.n = n + return out, nil +} + +var coderBoolSlice = pointerCoderFuncs{ + size: sizeBoolSlice, + marshal: appendBoolSlice, + unmarshal: consumeBoolSlice, + merge: mergeBoolSlice, +} + +// sizeBoolPackedSlice returns the size of wire encoding a []bool pointer as a packed repeated Bool. +func sizeBoolPackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.BoolSlice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += protowire.SizeVarint(protowire.EncodeBool(v)) + } + return f.tagsize + protowire.SizeBytes(n) +} + +// appendBoolPackedSlice encodes a []bool pointer as a packed repeated Bool. +func appendBoolPackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.BoolSlice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := 0 + for _, v := range s { + n += protowire.SizeVarint(protowire.EncodeBool(v)) + } + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendVarint(b, protowire.EncodeBool(v)) + } + return b, nil +} + +var coderBoolPackedSlice = pointerCoderFuncs{ + size: sizeBoolPackedSlice, + marshal: appendBoolPackedSlice, + unmarshal: consumeBoolSlice, + merge: mergeBoolSlice, +} + +// sizeBoolValue returns the size of wire encoding a bool value as a Bool. +func sizeBoolValue(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeVarint(protowire.EncodeBool(v.Bool())) +} + +// appendBoolValue encodes a bool value as a Bool. +func appendBoolValue(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) + return b, nil +} + +// consumeBoolValue decodes a bool value as a Bool. +func consumeBoolValue(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfBool(protowire.DecodeBool(v)), out, nil +} + +var coderBoolValue = valueCoderFuncs{ + size: sizeBoolValue, + marshal: appendBoolValue, + unmarshal: consumeBoolValue, + merge: mergeScalarValue, +} + +// sizeBoolSliceValue returns the size of wire encoding a []bool value as a repeated Bool. +func sizeBoolSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + size += tagsize + protowire.SizeVarint(protowire.EncodeBool(v.Bool())) + } + return size +} + +// appendBoolSliceValue encodes a []bool value as a repeated Bool. +func appendBoolSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) + } + return b, nil +} + +// consumeBoolSliceValue wire decodes a []bool value as a repeated Bool. +func consumeBoolSliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) + out.n = n + return listv, out, nil +} + +var coderBoolSliceValue = valueCoderFuncs{ + size: sizeBoolSliceValue, + marshal: appendBoolSliceValue, + unmarshal: consumeBoolSliceValue, + merge: mergeListValue, +} + +// sizeBoolPackedSliceValue returns the size of wire encoding a []bool value as a packed repeated Bool. +func sizeBoolPackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := 0 + for i, llen := 0, llen; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(protowire.EncodeBool(v.Bool())) + } + return tagsize + protowire.SizeBytes(n) +} + +// appendBoolPackedSliceValue encodes a []bool value as a packed repeated Bool. +func appendBoolPackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := 0 + for i := 0; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(protowire.EncodeBool(v.Bool())) + } + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) + } + return b, nil +} + +var coderBoolPackedSliceValue = valueCoderFuncs{ + size: sizeBoolPackedSliceValue, + marshal: appendBoolPackedSliceValue, + unmarshal: consumeBoolSliceValue, + merge: mergeListValue, +} + +// sizeEnumValue returns the size of wire encoding a value as a Enum. +func sizeEnumValue(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeVarint(uint64(v.Enum())) +} + +// appendEnumValue encodes a value as a Enum. +func appendEnumValue(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, uint64(v.Enum())) + return b, nil +} + +// consumeEnumValue decodes a value as a Enum. +func consumeEnumValue(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfEnum(protoreflect.EnumNumber(v)), out, nil +} + +var coderEnumValue = valueCoderFuncs{ + size: sizeEnumValue, + marshal: appendEnumValue, + unmarshal: consumeEnumValue, + merge: mergeScalarValue, +} + +// sizeEnumSliceValue returns the size of wire encoding a [] value as a repeated Enum. +func sizeEnumSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + size += tagsize + protowire.SizeVarint(uint64(v.Enum())) + } + return size +} + +// appendEnumSliceValue encodes a [] value as a repeated Enum. +func appendEnumSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, uint64(v.Enum())) + } + return b, nil +} + +// consumeEnumSliceValue wire decodes a [] value as a repeated Enum. +func consumeEnumSliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) + out.n = n + return listv, out, nil +} + +var coderEnumSliceValue = valueCoderFuncs{ + size: sizeEnumSliceValue, + marshal: appendEnumSliceValue, + unmarshal: consumeEnumSliceValue, + merge: mergeListValue, +} + +// sizeEnumPackedSliceValue returns the size of wire encoding a [] value as a packed repeated Enum. +func sizeEnumPackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := 0 + for i, llen := 0, llen; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(uint64(v.Enum())) + } + return tagsize + protowire.SizeBytes(n) +} + +// appendEnumPackedSliceValue encodes a [] value as a packed repeated Enum. +func appendEnumPackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := 0 + for i := 0; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(uint64(v.Enum())) + } + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, uint64(v.Enum())) + } + return b, nil +} + +var coderEnumPackedSliceValue = valueCoderFuncs{ + size: sizeEnumPackedSliceValue, + marshal: appendEnumPackedSliceValue, + unmarshal: consumeEnumSliceValue, + merge: mergeListValue, +} + +// sizeInt32 returns the size of wire encoding a int32 pointer as a Int32. +func sizeInt32(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Int32() + return f.tagsize + protowire.SizeVarint(uint64(v)) +} + +// appendInt32 wire encodes a int32 pointer as a Int32. +func appendInt32(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int32() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + return b, nil +} + +// consumeInt32 wire decodes a int32 pointer as a Int32. +func consumeInt32(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Int32() = int32(v) + out.n = n + return out, nil +} + +var coderInt32 = pointerCoderFuncs{ + size: sizeInt32, + marshal: appendInt32, + unmarshal: consumeInt32, + merge: mergeInt32, +} + +// sizeInt32NoZero returns the size of wire encoding a int32 pointer as a Int32. +// The zero value is not encoded. +func sizeInt32NoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Int32() + if v == 0 { + return 0 + } + return f.tagsize + protowire.SizeVarint(uint64(v)) +} + +// appendInt32NoZero wire encodes a int32 pointer as a Int32. +// The zero value is not encoded. +func appendInt32NoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int32() + if v == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + return b, nil +} + +var coderInt32NoZero = pointerCoderFuncs{ + size: sizeInt32NoZero, + marshal: appendInt32NoZero, + unmarshal: consumeInt32, + merge: mergeInt32NoZero, +} + +// sizeInt32Ptr returns the size of wire encoding a *int32 pointer as a Int32. +// It panics if the pointer is nil. +func sizeInt32Ptr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := **p.Int32Ptr() + return f.tagsize + protowire.SizeVarint(uint64(v)) +} + +// appendInt32Ptr wire encodes a *int32 pointer as a Int32. +// It panics if the pointer is nil. +func appendInt32Ptr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Int32Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + return b, nil +} + +// consumeInt32Ptr wire decodes a *int32 pointer as a Int32. +func consumeInt32Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Int32Ptr() + if *vp == nil { + *vp = new(int32) + } + **vp = int32(v) + out.n = n + return out, nil +} + +var coderInt32Ptr = pointerCoderFuncs{ + size: sizeInt32Ptr, + marshal: appendInt32Ptr, + unmarshal: consumeInt32Ptr, + merge: mergeInt32Ptr, +} + +// sizeInt32Slice returns the size of wire encoding a []int32 pointer as a repeated Int32. +func sizeInt32Slice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int32Slice() + for _, v := range s { + size += f.tagsize + protowire.SizeVarint(uint64(v)) + } + return size +} + +// appendInt32Slice encodes a []int32 pointer as a repeated Int32. +func appendInt32Slice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int32Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + } + return b, nil +} + +// consumeInt32Slice wire decodes a []int32 pointer as a repeated Int32. +func consumeInt32Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Int32Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, int32(v)) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, int32(v)) + out.n = n + return out, nil +} + +var coderInt32Slice = pointerCoderFuncs{ + size: sizeInt32Slice, + marshal: appendInt32Slice, + unmarshal: consumeInt32Slice, + merge: mergeInt32Slice, +} + +// sizeInt32PackedSlice returns the size of wire encoding a []int32 pointer as a packed repeated Int32. +func sizeInt32PackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += protowire.SizeVarint(uint64(v)) + } + return f.tagsize + protowire.SizeBytes(n) +} + +// appendInt32PackedSlice encodes a []int32 pointer as a packed repeated Int32. +func appendInt32PackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int32Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := 0 + for _, v := range s { + n += protowire.SizeVarint(uint64(v)) + } + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendVarint(b, uint64(v)) + } + return b, nil +} + +var coderInt32PackedSlice = pointerCoderFuncs{ + size: sizeInt32PackedSlice, + marshal: appendInt32PackedSlice, + unmarshal: consumeInt32Slice, + merge: mergeInt32Slice, +} + +// sizeInt32Value returns the size of wire encoding a int32 value as a Int32. +func sizeInt32Value(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeVarint(uint64(int32(v.Int()))) +} + +// appendInt32Value encodes a int32 value as a Int32. +func appendInt32Value(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, uint64(int32(v.Int()))) + return b, nil +} + +// consumeInt32Value decodes a int32 value as a Int32. +func consumeInt32Value(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfInt32(int32(v)), out, nil +} + +var coderInt32Value = valueCoderFuncs{ + size: sizeInt32Value, + marshal: appendInt32Value, + unmarshal: consumeInt32Value, + merge: mergeScalarValue, +} + +// sizeInt32SliceValue returns the size of wire encoding a []int32 value as a repeated Int32. +func sizeInt32SliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + size += tagsize + protowire.SizeVarint(uint64(int32(v.Int()))) + } + return size +} + +// appendInt32SliceValue encodes a []int32 value as a repeated Int32. +func appendInt32SliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, uint64(int32(v.Int()))) + } + return b, nil +} + +// consumeInt32SliceValue wire decodes a []int32 value as a repeated Int32. +func consumeInt32SliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt32(int32(v))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt32(int32(v))) + out.n = n + return listv, out, nil +} + +var coderInt32SliceValue = valueCoderFuncs{ + size: sizeInt32SliceValue, + marshal: appendInt32SliceValue, + unmarshal: consumeInt32SliceValue, + merge: mergeListValue, +} + +// sizeInt32PackedSliceValue returns the size of wire encoding a []int32 value as a packed repeated Int32. +func sizeInt32PackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := 0 + for i, llen := 0, llen; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(uint64(int32(v.Int()))) + } + return tagsize + protowire.SizeBytes(n) +} + +// appendInt32PackedSliceValue encodes a []int32 value as a packed repeated Int32. +func appendInt32PackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := 0 + for i := 0; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(uint64(int32(v.Int()))) + } + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, uint64(int32(v.Int()))) + } + return b, nil +} + +var coderInt32PackedSliceValue = valueCoderFuncs{ + size: sizeInt32PackedSliceValue, + marshal: appendInt32PackedSliceValue, + unmarshal: consumeInt32SliceValue, + merge: mergeListValue, +} + +// sizeSint32 returns the size of wire encoding a int32 pointer as a Sint32. +func sizeSint32(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Int32() + return f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(int64(v))) +} + +// appendSint32 wire encodes a int32 pointer as a Sint32. +func appendSint32(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int32() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(v))) + return b, nil +} + +// consumeSint32 wire decodes a int32 pointer as a Sint32. +func consumeSint32(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Int32() = int32(protowire.DecodeZigZag(v & math.MaxUint32)) + out.n = n + return out, nil +} + +var coderSint32 = pointerCoderFuncs{ + size: sizeSint32, + marshal: appendSint32, + unmarshal: consumeSint32, + merge: mergeInt32, +} + +// sizeSint32NoZero returns the size of wire encoding a int32 pointer as a Sint32. +// The zero value is not encoded. +func sizeSint32NoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Int32() + if v == 0 { + return 0 + } + return f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(int64(v))) +} + +// appendSint32NoZero wire encodes a int32 pointer as a Sint32. +// The zero value is not encoded. +func appendSint32NoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int32() + if v == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(v))) + return b, nil +} + +var coderSint32NoZero = pointerCoderFuncs{ + size: sizeSint32NoZero, + marshal: appendSint32NoZero, + unmarshal: consumeSint32, + merge: mergeInt32NoZero, +} + +// sizeSint32Ptr returns the size of wire encoding a *int32 pointer as a Sint32. +// It panics if the pointer is nil. +func sizeSint32Ptr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := **p.Int32Ptr() + return f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(int64(v))) +} + +// appendSint32Ptr wire encodes a *int32 pointer as a Sint32. +// It panics if the pointer is nil. +func appendSint32Ptr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Int32Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(v))) + return b, nil +} + +// consumeSint32Ptr wire decodes a *int32 pointer as a Sint32. +func consumeSint32Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Int32Ptr() + if *vp == nil { + *vp = new(int32) + } + **vp = int32(protowire.DecodeZigZag(v & math.MaxUint32)) + out.n = n + return out, nil +} + +var coderSint32Ptr = pointerCoderFuncs{ + size: sizeSint32Ptr, + marshal: appendSint32Ptr, + unmarshal: consumeSint32Ptr, + merge: mergeInt32Ptr, +} + +// sizeSint32Slice returns the size of wire encoding a []int32 pointer as a repeated Sint32. +func sizeSint32Slice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int32Slice() + for _, v := range s { + size += f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(int64(v))) + } + return size +} + +// appendSint32Slice encodes a []int32 pointer as a repeated Sint32. +func appendSint32Slice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int32Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(v))) + } + return b, nil +} + +// consumeSint32Slice wire decodes a []int32 pointer as a repeated Sint32. +func consumeSint32Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Int32Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, int32(protowire.DecodeZigZag(v&math.MaxUint32))) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, int32(protowire.DecodeZigZag(v&math.MaxUint32))) + out.n = n + return out, nil +} + +var coderSint32Slice = pointerCoderFuncs{ + size: sizeSint32Slice, + marshal: appendSint32Slice, + unmarshal: consumeSint32Slice, + merge: mergeInt32Slice, +} + +// sizeSint32PackedSlice returns the size of wire encoding a []int32 pointer as a packed repeated Sint32. +func sizeSint32PackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += protowire.SizeVarint(protowire.EncodeZigZag(int64(v))) + } + return f.tagsize + protowire.SizeBytes(n) +} + +// appendSint32PackedSlice encodes a []int32 pointer as a packed repeated Sint32. +func appendSint32PackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int32Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := 0 + for _, v := range s { + n += protowire.SizeVarint(protowire.EncodeZigZag(int64(v))) + } + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(v))) + } + return b, nil +} + +var coderSint32PackedSlice = pointerCoderFuncs{ + size: sizeSint32PackedSlice, + marshal: appendSint32PackedSlice, + unmarshal: consumeSint32Slice, + merge: mergeInt32Slice, +} + +// sizeSint32Value returns the size of wire encoding a int32 value as a Sint32. +func sizeSint32Value(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeVarint(protowire.EncodeZigZag(int64(int32(v.Int())))) +} + +// appendSint32Value encodes a int32 value as a Sint32. +func appendSint32Value(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(int32(v.Int())))) + return b, nil +} + +// consumeSint32Value decodes a int32 value as a Sint32. +func consumeSint32Value(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32))), out, nil +} + +var coderSint32Value = valueCoderFuncs{ + size: sizeSint32Value, + marshal: appendSint32Value, + unmarshal: consumeSint32Value, + merge: mergeScalarValue, +} + +// sizeSint32SliceValue returns the size of wire encoding a []int32 value as a repeated Sint32. +func sizeSint32SliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + size += tagsize + protowire.SizeVarint(protowire.EncodeZigZag(int64(int32(v.Int())))) + } + return size +} + +// appendSint32SliceValue encodes a []int32 value as a repeated Sint32. +func appendSint32SliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(int32(v.Int())))) + } + return b, nil +} + +// consumeSint32SliceValue wire decodes a []int32 value as a repeated Sint32. +func consumeSint32SliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32)))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32)))) + out.n = n + return listv, out, nil +} + +var coderSint32SliceValue = valueCoderFuncs{ + size: sizeSint32SliceValue, + marshal: appendSint32SliceValue, + unmarshal: consumeSint32SliceValue, + merge: mergeListValue, +} + +// sizeSint32PackedSliceValue returns the size of wire encoding a []int32 value as a packed repeated Sint32. +func sizeSint32PackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := 0 + for i, llen := 0, llen; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(protowire.EncodeZigZag(int64(int32(v.Int())))) + } + return tagsize + protowire.SizeBytes(n) +} + +// appendSint32PackedSliceValue encodes a []int32 value as a packed repeated Sint32. +func appendSint32PackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := 0 + for i := 0; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(protowire.EncodeZigZag(int64(int32(v.Int())))) + } + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(int32(v.Int())))) + } + return b, nil +} + +var coderSint32PackedSliceValue = valueCoderFuncs{ + size: sizeSint32PackedSliceValue, + marshal: appendSint32PackedSliceValue, + unmarshal: consumeSint32SliceValue, + merge: mergeListValue, +} + +// sizeUint32 returns the size of wire encoding a uint32 pointer as a Uint32. +func sizeUint32(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Uint32() + return f.tagsize + protowire.SizeVarint(uint64(v)) +} + +// appendUint32 wire encodes a uint32 pointer as a Uint32. +func appendUint32(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Uint32() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + return b, nil +} + +// consumeUint32 wire decodes a uint32 pointer as a Uint32. +func consumeUint32(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Uint32() = uint32(v) + out.n = n + return out, nil +} + +var coderUint32 = pointerCoderFuncs{ + size: sizeUint32, + marshal: appendUint32, + unmarshal: consumeUint32, + merge: mergeUint32, +} + +// sizeUint32NoZero returns the size of wire encoding a uint32 pointer as a Uint32. +// The zero value is not encoded. +func sizeUint32NoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Uint32() + if v == 0 { + return 0 + } + return f.tagsize + protowire.SizeVarint(uint64(v)) +} + +// appendUint32NoZero wire encodes a uint32 pointer as a Uint32. +// The zero value is not encoded. +func appendUint32NoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Uint32() + if v == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + return b, nil +} + +var coderUint32NoZero = pointerCoderFuncs{ + size: sizeUint32NoZero, + marshal: appendUint32NoZero, + unmarshal: consumeUint32, + merge: mergeUint32NoZero, +} + +// sizeUint32Ptr returns the size of wire encoding a *uint32 pointer as a Uint32. +// It panics if the pointer is nil. +func sizeUint32Ptr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := **p.Uint32Ptr() + return f.tagsize + protowire.SizeVarint(uint64(v)) +} + +// appendUint32Ptr wire encodes a *uint32 pointer as a Uint32. +// It panics if the pointer is nil. +func appendUint32Ptr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Uint32Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + return b, nil +} + +// consumeUint32Ptr wire decodes a *uint32 pointer as a Uint32. +func consumeUint32Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Uint32Ptr() + if *vp == nil { + *vp = new(uint32) + } + **vp = uint32(v) + out.n = n + return out, nil +} + +var coderUint32Ptr = pointerCoderFuncs{ + size: sizeUint32Ptr, + marshal: appendUint32Ptr, + unmarshal: consumeUint32Ptr, + merge: mergeUint32Ptr, +} + +// sizeUint32Slice returns the size of wire encoding a []uint32 pointer as a repeated Uint32. +func sizeUint32Slice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Uint32Slice() + for _, v := range s { + size += f.tagsize + protowire.SizeVarint(uint64(v)) + } + return size +} + +// appendUint32Slice encodes a []uint32 pointer as a repeated Uint32. +func appendUint32Slice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Uint32Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + } + return b, nil +} + +// consumeUint32Slice wire decodes a []uint32 pointer as a repeated Uint32. +func consumeUint32Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Uint32Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, uint32(v)) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, uint32(v)) + out.n = n + return out, nil +} + +var coderUint32Slice = pointerCoderFuncs{ + size: sizeUint32Slice, + marshal: appendUint32Slice, + unmarshal: consumeUint32Slice, + merge: mergeUint32Slice, +} + +// sizeUint32PackedSlice returns the size of wire encoding a []uint32 pointer as a packed repeated Uint32. +func sizeUint32PackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Uint32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += protowire.SizeVarint(uint64(v)) + } + return f.tagsize + protowire.SizeBytes(n) +} + +// appendUint32PackedSlice encodes a []uint32 pointer as a packed repeated Uint32. +func appendUint32PackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Uint32Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := 0 + for _, v := range s { + n += protowire.SizeVarint(uint64(v)) + } + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendVarint(b, uint64(v)) + } + return b, nil +} + +var coderUint32PackedSlice = pointerCoderFuncs{ + size: sizeUint32PackedSlice, + marshal: appendUint32PackedSlice, + unmarshal: consumeUint32Slice, + merge: mergeUint32Slice, +} + +// sizeUint32Value returns the size of wire encoding a uint32 value as a Uint32. +func sizeUint32Value(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeVarint(uint64(uint32(v.Uint()))) +} + +// appendUint32Value encodes a uint32 value as a Uint32. +func appendUint32Value(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, uint64(uint32(v.Uint()))) + return b, nil +} + +// consumeUint32Value decodes a uint32 value as a Uint32. +func consumeUint32Value(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfUint32(uint32(v)), out, nil +} + +var coderUint32Value = valueCoderFuncs{ + size: sizeUint32Value, + marshal: appendUint32Value, + unmarshal: consumeUint32Value, + merge: mergeScalarValue, +} + +// sizeUint32SliceValue returns the size of wire encoding a []uint32 value as a repeated Uint32. +func sizeUint32SliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + size += tagsize + protowire.SizeVarint(uint64(uint32(v.Uint()))) + } + return size +} + +// appendUint32SliceValue encodes a []uint32 value as a repeated Uint32. +func appendUint32SliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, uint64(uint32(v.Uint()))) + } + return b, nil +} + +// consumeUint32SliceValue wire decodes a []uint32 value as a repeated Uint32. +func consumeUint32SliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint32(uint32(v))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint32(uint32(v))) + out.n = n + return listv, out, nil +} + +var coderUint32SliceValue = valueCoderFuncs{ + size: sizeUint32SliceValue, + marshal: appendUint32SliceValue, + unmarshal: consumeUint32SliceValue, + merge: mergeListValue, +} + +// sizeUint32PackedSliceValue returns the size of wire encoding a []uint32 value as a packed repeated Uint32. +func sizeUint32PackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := 0 + for i, llen := 0, llen; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(uint64(uint32(v.Uint()))) + } + return tagsize + protowire.SizeBytes(n) +} + +// appendUint32PackedSliceValue encodes a []uint32 value as a packed repeated Uint32. +func appendUint32PackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := 0 + for i := 0; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(uint64(uint32(v.Uint()))) + } + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, uint64(uint32(v.Uint()))) + } + return b, nil +} + +var coderUint32PackedSliceValue = valueCoderFuncs{ + size: sizeUint32PackedSliceValue, + marshal: appendUint32PackedSliceValue, + unmarshal: consumeUint32SliceValue, + merge: mergeListValue, +} + +// sizeInt64 returns the size of wire encoding a int64 pointer as a Int64. +func sizeInt64(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Int64() + return f.tagsize + protowire.SizeVarint(uint64(v)) +} + +// appendInt64 wire encodes a int64 pointer as a Int64. +func appendInt64(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int64() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + return b, nil +} + +// consumeInt64 wire decodes a int64 pointer as a Int64. +func consumeInt64(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Int64() = int64(v) + out.n = n + return out, nil +} + +var coderInt64 = pointerCoderFuncs{ + size: sizeInt64, + marshal: appendInt64, + unmarshal: consumeInt64, + merge: mergeInt64, +} + +// sizeInt64NoZero returns the size of wire encoding a int64 pointer as a Int64. +// The zero value is not encoded. +func sizeInt64NoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Int64() + if v == 0 { + return 0 + } + return f.tagsize + protowire.SizeVarint(uint64(v)) +} + +// appendInt64NoZero wire encodes a int64 pointer as a Int64. +// The zero value is not encoded. +func appendInt64NoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int64() + if v == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + return b, nil +} + +var coderInt64NoZero = pointerCoderFuncs{ + size: sizeInt64NoZero, + marshal: appendInt64NoZero, + unmarshal: consumeInt64, + merge: mergeInt64NoZero, +} + +// sizeInt64Ptr returns the size of wire encoding a *int64 pointer as a Int64. +// It panics if the pointer is nil. +func sizeInt64Ptr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := **p.Int64Ptr() + return f.tagsize + protowire.SizeVarint(uint64(v)) +} + +// appendInt64Ptr wire encodes a *int64 pointer as a Int64. +// It panics if the pointer is nil. +func appendInt64Ptr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Int64Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + return b, nil +} + +// consumeInt64Ptr wire decodes a *int64 pointer as a Int64. +func consumeInt64Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Int64Ptr() + if *vp == nil { + *vp = new(int64) + } + **vp = int64(v) + out.n = n + return out, nil +} + +var coderInt64Ptr = pointerCoderFuncs{ + size: sizeInt64Ptr, + marshal: appendInt64Ptr, + unmarshal: consumeInt64Ptr, + merge: mergeInt64Ptr, +} + +// sizeInt64Slice returns the size of wire encoding a []int64 pointer as a repeated Int64. +func sizeInt64Slice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int64Slice() + for _, v := range s { + size += f.tagsize + protowire.SizeVarint(uint64(v)) + } + return size +} + +// appendInt64Slice encodes a []int64 pointer as a repeated Int64. +func appendInt64Slice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int64Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + } + return b, nil +} + +// consumeInt64Slice wire decodes a []int64 pointer as a repeated Int64. +func consumeInt64Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Int64Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, int64(v)) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, int64(v)) + out.n = n + return out, nil +} + +var coderInt64Slice = pointerCoderFuncs{ + size: sizeInt64Slice, + marshal: appendInt64Slice, + unmarshal: consumeInt64Slice, + merge: mergeInt64Slice, +} + +// sizeInt64PackedSlice returns the size of wire encoding a []int64 pointer as a packed repeated Int64. +func sizeInt64PackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += protowire.SizeVarint(uint64(v)) + } + return f.tagsize + protowire.SizeBytes(n) +} + +// appendInt64PackedSlice encodes a []int64 pointer as a packed repeated Int64. +func appendInt64PackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int64Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := 0 + for _, v := range s { + n += protowire.SizeVarint(uint64(v)) + } + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendVarint(b, uint64(v)) + } + return b, nil +} + +var coderInt64PackedSlice = pointerCoderFuncs{ + size: sizeInt64PackedSlice, + marshal: appendInt64PackedSlice, + unmarshal: consumeInt64Slice, + merge: mergeInt64Slice, +} + +// sizeInt64Value returns the size of wire encoding a int64 value as a Int64. +func sizeInt64Value(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeVarint(uint64(v.Int())) +} + +// appendInt64Value encodes a int64 value as a Int64. +func appendInt64Value(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, uint64(v.Int())) + return b, nil +} + +// consumeInt64Value decodes a int64 value as a Int64. +func consumeInt64Value(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfInt64(int64(v)), out, nil +} + +var coderInt64Value = valueCoderFuncs{ + size: sizeInt64Value, + marshal: appendInt64Value, + unmarshal: consumeInt64Value, + merge: mergeScalarValue, +} + +// sizeInt64SliceValue returns the size of wire encoding a []int64 value as a repeated Int64. +func sizeInt64SliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + size += tagsize + protowire.SizeVarint(uint64(v.Int())) + } + return size +} + +// appendInt64SliceValue encodes a []int64 value as a repeated Int64. +func appendInt64SliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, uint64(v.Int())) + } + return b, nil +} + +// consumeInt64SliceValue wire decodes a []int64 value as a repeated Int64. +func consumeInt64SliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt64(int64(v))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt64(int64(v))) + out.n = n + return listv, out, nil +} + +var coderInt64SliceValue = valueCoderFuncs{ + size: sizeInt64SliceValue, + marshal: appendInt64SliceValue, + unmarshal: consumeInt64SliceValue, + merge: mergeListValue, +} + +// sizeInt64PackedSliceValue returns the size of wire encoding a []int64 value as a packed repeated Int64. +func sizeInt64PackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := 0 + for i, llen := 0, llen; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(uint64(v.Int())) + } + return tagsize + protowire.SizeBytes(n) +} + +// appendInt64PackedSliceValue encodes a []int64 value as a packed repeated Int64. +func appendInt64PackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := 0 + for i := 0; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(uint64(v.Int())) + } + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, uint64(v.Int())) + } + return b, nil +} + +var coderInt64PackedSliceValue = valueCoderFuncs{ + size: sizeInt64PackedSliceValue, + marshal: appendInt64PackedSliceValue, + unmarshal: consumeInt64SliceValue, + merge: mergeListValue, +} + +// sizeSint64 returns the size of wire encoding a int64 pointer as a Sint64. +func sizeSint64(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Int64() + return f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(v)) +} + +// appendSint64 wire encodes a int64 pointer as a Sint64. +func appendSint64(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int64() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(v)) + return b, nil +} + +// consumeSint64 wire decodes a int64 pointer as a Sint64. +func consumeSint64(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Int64() = protowire.DecodeZigZag(v) + out.n = n + return out, nil +} + +var coderSint64 = pointerCoderFuncs{ + size: sizeSint64, + marshal: appendSint64, + unmarshal: consumeSint64, + merge: mergeInt64, +} + +// sizeSint64NoZero returns the size of wire encoding a int64 pointer as a Sint64. +// The zero value is not encoded. +func sizeSint64NoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Int64() + if v == 0 { + return 0 + } + return f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(v)) +} + +// appendSint64NoZero wire encodes a int64 pointer as a Sint64. +// The zero value is not encoded. +func appendSint64NoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int64() + if v == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(v)) + return b, nil +} + +var coderSint64NoZero = pointerCoderFuncs{ + size: sizeSint64NoZero, + marshal: appendSint64NoZero, + unmarshal: consumeSint64, + merge: mergeInt64NoZero, +} + +// sizeSint64Ptr returns the size of wire encoding a *int64 pointer as a Sint64. +// It panics if the pointer is nil. +func sizeSint64Ptr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := **p.Int64Ptr() + return f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(v)) +} + +// appendSint64Ptr wire encodes a *int64 pointer as a Sint64. +// It panics if the pointer is nil. +func appendSint64Ptr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Int64Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(v)) + return b, nil +} + +// consumeSint64Ptr wire decodes a *int64 pointer as a Sint64. +func consumeSint64Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Int64Ptr() + if *vp == nil { + *vp = new(int64) + } + **vp = protowire.DecodeZigZag(v) + out.n = n + return out, nil +} + +var coderSint64Ptr = pointerCoderFuncs{ + size: sizeSint64Ptr, + marshal: appendSint64Ptr, + unmarshal: consumeSint64Ptr, + merge: mergeInt64Ptr, +} + +// sizeSint64Slice returns the size of wire encoding a []int64 pointer as a repeated Sint64. +func sizeSint64Slice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int64Slice() + for _, v := range s { + size += f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(v)) + } + return size +} + +// appendSint64Slice encodes a []int64 pointer as a repeated Sint64. +func appendSint64Slice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int64Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(v)) + } + return b, nil +} + +// consumeSint64Slice wire decodes a []int64 pointer as a repeated Sint64. +func consumeSint64Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Int64Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, protowire.DecodeZigZag(v)) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, protowire.DecodeZigZag(v)) + out.n = n + return out, nil +} + +var coderSint64Slice = pointerCoderFuncs{ + size: sizeSint64Slice, + marshal: appendSint64Slice, + unmarshal: consumeSint64Slice, + merge: mergeInt64Slice, +} + +// sizeSint64PackedSlice returns the size of wire encoding a []int64 pointer as a packed repeated Sint64. +func sizeSint64PackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += protowire.SizeVarint(protowire.EncodeZigZag(v)) + } + return f.tagsize + protowire.SizeBytes(n) +} + +// appendSint64PackedSlice encodes a []int64 pointer as a packed repeated Sint64. +func appendSint64PackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int64Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := 0 + for _, v := range s { + n += protowire.SizeVarint(protowire.EncodeZigZag(v)) + } + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendVarint(b, protowire.EncodeZigZag(v)) + } + return b, nil +} + +var coderSint64PackedSlice = pointerCoderFuncs{ + size: sizeSint64PackedSlice, + marshal: appendSint64PackedSlice, + unmarshal: consumeSint64Slice, + merge: mergeInt64Slice, +} + +// sizeSint64Value returns the size of wire encoding a int64 value as a Sint64. +func sizeSint64Value(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeVarint(protowire.EncodeZigZag(v.Int())) +} + +// appendSint64Value encodes a int64 value as a Sint64. +func appendSint64Value(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(v.Int())) + return b, nil +} + +// consumeSint64Value decodes a int64 value as a Sint64. +func consumeSint64Value(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfInt64(protowire.DecodeZigZag(v)), out, nil +} + +var coderSint64Value = valueCoderFuncs{ + size: sizeSint64Value, + marshal: appendSint64Value, + unmarshal: consumeSint64Value, + merge: mergeScalarValue, +} + +// sizeSint64SliceValue returns the size of wire encoding a []int64 value as a repeated Sint64. +func sizeSint64SliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + size += tagsize + protowire.SizeVarint(protowire.EncodeZigZag(v.Int())) + } + return size +} + +// appendSint64SliceValue encodes a []int64 value as a repeated Sint64. +func appendSint64SliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(v.Int())) + } + return b, nil +} + +// consumeSint64SliceValue wire decodes a []int64 value as a repeated Sint64. +func consumeSint64SliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt64(protowire.DecodeZigZag(v))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt64(protowire.DecodeZigZag(v))) + out.n = n + return listv, out, nil +} + +var coderSint64SliceValue = valueCoderFuncs{ + size: sizeSint64SliceValue, + marshal: appendSint64SliceValue, + unmarshal: consumeSint64SliceValue, + merge: mergeListValue, +} + +// sizeSint64PackedSliceValue returns the size of wire encoding a []int64 value as a packed repeated Sint64. +func sizeSint64PackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := 0 + for i, llen := 0, llen; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(protowire.EncodeZigZag(v.Int())) + } + return tagsize + protowire.SizeBytes(n) +} + +// appendSint64PackedSliceValue encodes a []int64 value as a packed repeated Sint64. +func appendSint64PackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := 0 + for i := 0; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(protowire.EncodeZigZag(v.Int())) + } + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, protowire.EncodeZigZag(v.Int())) + } + return b, nil +} + +var coderSint64PackedSliceValue = valueCoderFuncs{ + size: sizeSint64PackedSliceValue, + marshal: appendSint64PackedSliceValue, + unmarshal: consumeSint64SliceValue, + merge: mergeListValue, +} + +// sizeUint64 returns the size of wire encoding a uint64 pointer as a Uint64. +func sizeUint64(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Uint64() + return f.tagsize + protowire.SizeVarint(v) +} + +// appendUint64 wire encodes a uint64 pointer as a Uint64. +func appendUint64(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Uint64() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, v) + return b, nil +} + +// consumeUint64 wire decodes a uint64 pointer as a Uint64. +func consumeUint64(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Uint64() = v + out.n = n + return out, nil +} + +var coderUint64 = pointerCoderFuncs{ + size: sizeUint64, + marshal: appendUint64, + unmarshal: consumeUint64, + merge: mergeUint64, +} + +// sizeUint64NoZero returns the size of wire encoding a uint64 pointer as a Uint64. +// The zero value is not encoded. +func sizeUint64NoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Uint64() + if v == 0 { + return 0 + } + return f.tagsize + protowire.SizeVarint(v) +} + +// appendUint64NoZero wire encodes a uint64 pointer as a Uint64. +// The zero value is not encoded. +func appendUint64NoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Uint64() + if v == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, v) + return b, nil +} + +var coderUint64NoZero = pointerCoderFuncs{ + size: sizeUint64NoZero, + marshal: appendUint64NoZero, + unmarshal: consumeUint64, + merge: mergeUint64NoZero, +} + +// sizeUint64Ptr returns the size of wire encoding a *uint64 pointer as a Uint64. +// It panics if the pointer is nil. +func sizeUint64Ptr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := **p.Uint64Ptr() + return f.tagsize + protowire.SizeVarint(v) +} + +// appendUint64Ptr wire encodes a *uint64 pointer as a Uint64. +// It panics if the pointer is nil. +func appendUint64Ptr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Uint64Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, v) + return b, nil +} + +// consumeUint64Ptr wire decodes a *uint64 pointer as a Uint64. +func consumeUint64Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Uint64Ptr() + if *vp == nil { + *vp = new(uint64) + } + **vp = v + out.n = n + return out, nil +} + +var coderUint64Ptr = pointerCoderFuncs{ + size: sizeUint64Ptr, + marshal: appendUint64Ptr, + unmarshal: consumeUint64Ptr, + merge: mergeUint64Ptr, +} + +// sizeUint64Slice returns the size of wire encoding a []uint64 pointer as a repeated Uint64. +func sizeUint64Slice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Uint64Slice() + for _, v := range s { + size += f.tagsize + protowire.SizeVarint(v) + } + return size +} + +// appendUint64Slice encodes a []uint64 pointer as a repeated Uint64. +func appendUint64Slice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Uint64Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, v) + } + return b, nil +} + +// consumeUint64Slice wire decodes a []uint64 pointer as a repeated Uint64. +func consumeUint64Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Uint64Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, v) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.VarintType { + return out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, v) + out.n = n + return out, nil +} + +var coderUint64Slice = pointerCoderFuncs{ + size: sizeUint64Slice, + marshal: appendUint64Slice, + unmarshal: consumeUint64Slice, + merge: mergeUint64Slice, +} + +// sizeUint64PackedSlice returns the size of wire encoding a []uint64 pointer as a packed repeated Uint64. +func sizeUint64PackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Uint64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += protowire.SizeVarint(v) + } + return f.tagsize + protowire.SizeBytes(n) +} + +// appendUint64PackedSlice encodes a []uint64 pointer as a packed repeated Uint64. +func appendUint64PackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Uint64Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := 0 + for _, v := range s { + n += protowire.SizeVarint(v) + } + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendVarint(b, v) + } + return b, nil +} + +var coderUint64PackedSlice = pointerCoderFuncs{ + size: sizeUint64PackedSlice, + marshal: appendUint64PackedSlice, + unmarshal: consumeUint64Slice, + merge: mergeUint64Slice, +} + +// sizeUint64Value returns the size of wire encoding a uint64 value as a Uint64. +func sizeUint64Value(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeVarint(v.Uint()) +} + +// appendUint64Value encodes a uint64 value as a Uint64. +func appendUint64Value(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, v.Uint()) + return b, nil +} + +// consumeUint64Value decodes a uint64 value as a Uint64. +func consumeUint64Value(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfUint64(v), out, nil +} + +var coderUint64Value = valueCoderFuncs{ + size: sizeUint64Value, + marshal: appendUint64Value, + unmarshal: consumeUint64Value, + merge: mergeScalarValue, +} + +// sizeUint64SliceValue returns the size of wire encoding a []uint64 value as a repeated Uint64. +func sizeUint64SliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + size += tagsize + protowire.SizeVarint(v.Uint()) + } + return size +} + +// appendUint64SliceValue encodes a []uint64 value as a repeated Uint64. +func appendUint64SliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendVarint(b, v.Uint()) + } + return b, nil +} + +// consumeUint64SliceValue wire decodes a []uint64 value as a repeated Uint64. +func consumeUint64SliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint64(v)) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.VarintType { + return protoreflect.Value{}, out, errUnknown + } + var v uint64 + var n int + if len(b) >= 1 && b[0] < 0x80 { + v = uint64(b[0]) + n = 1 + } else if len(b) >= 2 && b[1] < 128 { + v = uint64(b[0]&0x7f) + uint64(b[1])<<7 + n = 2 + } else { + v, n = protowire.ConsumeVarint(b) + } + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint64(v)) + out.n = n + return listv, out, nil +} + +var coderUint64SliceValue = valueCoderFuncs{ + size: sizeUint64SliceValue, + marshal: appendUint64SliceValue, + unmarshal: consumeUint64SliceValue, + merge: mergeListValue, +} + +// sizeUint64PackedSliceValue returns the size of wire encoding a []uint64 value as a packed repeated Uint64. +func sizeUint64PackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := 0 + for i, llen := 0, llen; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(v.Uint()) + } + return tagsize + protowire.SizeBytes(n) +} + +// appendUint64PackedSliceValue encodes a []uint64 value as a packed repeated Uint64. +func appendUint64PackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := 0 + for i := 0; i < llen; i++ { + v := list.Get(i) + n += protowire.SizeVarint(v.Uint()) + } + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, v.Uint()) + } + return b, nil +} + +var coderUint64PackedSliceValue = valueCoderFuncs{ + size: sizeUint64PackedSliceValue, + marshal: appendUint64PackedSliceValue, + unmarshal: consumeUint64SliceValue, + merge: mergeListValue, +} + +// sizeSfixed32 returns the size of wire encoding a int32 pointer as a Sfixed32. +func sizeSfixed32(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + + return f.tagsize + protowire.SizeFixed32() +} + +// appendSfixed32 wire encodes a int32 pointer as a Sfixed32. +func appendSfixed32(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int32() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, uint32(v)) + return b, nil +} + +// consumeSfixed32 wire decodes a int32 pointer as a Sfixed32. +func consumeSfixed32(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed32Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Int32() = int32(v) + out.n = n + return out, nil +} + +var coderSfixed32 = pointerCoderFuncs{ + size: sizeSfixed32, + marshal: appendSfixed32, + unmarshal: consumeSfixed32, + merge: mergeInt32, +} + +// sizeSfixed32NoZero returns the size of wire encoding a int32 pointer as a Sfixed32. +// The zero value is not encoded. +func sizeSfixed32NoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Int32() + if v == 0 { + return 0 + } + return f.tagsize + protowire.SizeFixed32() +} + +// appendSfixed32NoZero wire encodes a int32 pointer as a Sfixed32. +// The zero value is not encoded. +func appendSfixed32NoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int32() + if v == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, uint32(v)) + return b, nil +} + +var coderSfixed32NoZero = pointerCoderFuncs{ + size: sizeSfixed32NoZero, + marshal: appendSfixed32NoZero, + unmarshal: consumeSfixed32, + merge: mergeInt32NoZero, +} + +// sizeSfixed32Ptr returns the size of wire encoding a *int32 pointer as a Sfixed32. +// It panics if the pointer is nil. +func sizeSfixed32Ptr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + return f.tagsize + protowire.SizeFixed32() +} + +// appendSfixed32Ptr wire encodes a *int32 pointer as a Sfixed32. +// It panics if the pointer is nil. +func appendSfixed32Ptr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Int32Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, uint32(v)) + return b, nil +} + +// consumeSfixed32Ptr wire decodes a *int32 pointer as a Sfixed32. +func consumeSfixed32Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed32Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Int32Ptr() + if *vp == nil { + *vp = new(int32) + } + **vp = int32(v) + out.n = n + return out, nil +} + +var coderSfixed32Ptr = pointerCoderFuncs{ + size: sizeSfixed32Ptr, + marshal: appendSfixed32Ptr, + unmarshal: consumeSfixed32Ptr, + merge: mergeInt32Ptr, +} + +// sizeSfixed32Slice returns the size of wire encoding a []int32 pointer as a repeated Sfixed32. +func sizeSfixed32Slice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int32Slice() + size = len(s) * (f.tagsize + protowire.SizeFixed32()) + return size +} + +// appendSfixed32Slice encodes a []int32 pointer as a repeated Sfixed32. +func appendSfixed32Slice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int32Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, uint32(v)) + } + return b, nil +} + +// consumeSfixed32Slice wire decodes a []int32 pointer as a repeated Sfixed32. +func consumeSfixed32Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Int32Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, int32(v)) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.Fixed32Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, int32(v)) + out.n = n + return out, nil +} + +var coderSfixed32Slice = pointerCoderFuncs{ + size: sizeSfixed32Slice, + marshal: appendSfixed32Slice, + unmarshal: consumeSfixed32Slice, + merge: mergeInt32Slice, +} + +// sizeSfixed32PackedSlice returns the size of wire encoding a []int32 pointer as a packed repeated Sfixed32. +func sizeSfixed32PackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int32Slice() + if len(s) == 0 { + return 0 + } + n := len(s) * protowire.SizeFixed32() + return f.tagsize + protowire.SizeBytes(n) +} + +// appendSfixed32PackedSlice encodes a []int32 pointer as a packed repeated Sfixed32. +func appendSfixed32PackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int32Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := len(s) * protowire.SizeFixed32() + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendFixed32(b, uint32(v)) + } + return b, nil +} + +var coderSfixed32PackedSlice = pointerCoderFuncs{ + size: sizeSfixed32PackedSlice, + marshal: appendSfixed32PackedSlice, + unmarshal: consumeSfixed32Slice, + merge: mergeInt32Slice, +} + +// sizeSfixed32Value returns the size of wire encoding a int32 value as a Sfixed32. +func sizeSfixed32Value(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeFixed32() +} + +// appendSfixed32Value encodes a int32 value as a Sfixed32. +func appendSfixed32Value(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed32(b, uint32(v.Int())) + return b, nil +} + +// consumeSfixed32Value decodes a int32 value as a Sfixed32. +func consumeSfixed32Value(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.Fixed32Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfInt32(int32(v)), out, nil +} + +var coderSfixed32Value = valueCoderFuncs{ + size: sizeSfixed32Value, + marshal: appendSfixed32Value, + unmarshal: consumeSfixed32Value, + merge: mergeScalarValue, +} + +// sizeSfixed32SliceValue returns the size of wire encoding a []int32 value as a repeated Sfixed32. +func sizeSfixed32SliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + size = list.Len() * (tagsize + protowire.SizeFixed32()) + return size +} + +// appendSfixed32SliceValue encodes a []int32 value as a repeated Sfixed32. +func appendSfixed32SliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed32(b, uint32(v.Int())) + } + return b, nil +} + +// consumeSfixed32SliceValue wire decodes a []int32 value as a repeated Sfixed32. +func consumeSfixed32SliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt32(int32(v))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.Fixed32Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt32(int32(v))) + out.n = n + return listv, out, nil +} + +var coderSfixed32SliceValue = valueCoderFuncs{ + size: sizeSfixed32SliceValue, + marshal: appendSfixed32SliceValue, + unmarshal: consumeSfixed32SliceValue, + merge: mergeListValue, +} + +// sizeSfixed32PackedSliceValue returns the size of wire encoding a []int32 value as a packed repeated Sfixed32. +func sizeSfixed32PackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := llen * protowire.SizeFixed32() + return tagsize + protowire.SizeBytes(n) +} + +// appendSfixed32PackedSliceValue encodes a []int32 value as a packed repeated Sfixed32. +func appendSfixed32PackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := llen * protowire.SizeFixed32() + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendFixed32(b, uint32(v.Int())) + } + return b, nil +} + +var coderSfixed32PackedSliceValue = valueCoderFuncs{ + size: sizeSfixed32PackedSliceValue, + marshal: appendSfixed32PackedSliceValue, + unmarshal: consumeSfixed32SliceValue, + merge: mergeListValue, +} + +// sizeFixed32 returns the size of wire encoding a uint32 pointer as a Fixed32. +func sizeFixed32(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + + return f.tagsize + protowire.SizeFixed32() +} + +// appendFixed32 wire encodes a uint32 pointer as a Fixed32. +func appendFixed32(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Uint32() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, v) + return b, nil +} + +// consumeFixed32 wire decodes a uint32 pointer as a Fixed32. +func consumeFixed32(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed32Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Uint32() = v + out.n = n + return out, nil +} + +var coderFixed32 = pointerCoderFuncs{ + size: sizeFixed32, + marshal: appendFixed32, + unmarshal: consumeFixed32, + merge: mergeUint32, +} + +// sizeFixed32NoZero returns the size of wire encoding a uint32 pointer as a Fixed32. +// The zero value is not encoded. +func sizeFixed32NoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Uint32() + if v == 0 { + return 0 + } + return f.tagsize + protowire.SizeFixed32() +} + +// appendFixed32NoZero wire encodes a uint32 pointer as a Fixed32. +// The zero value is not encoded. +func appendFixed32NoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Uint32() + if v == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, v) + return b, nil +} + +var coderFixed32NoZero = pointerCoderFuncs{ + size: sizeFixed32NoZero, + marshal: appendFixed32NoZero, + unmarshal: consumeFixed32, + merge: mergeUint32NoZero, +} + +// sizeFixed32Ptr returns the size of wire encoding a *uint32 pointer as a Fixed32. +// It panics if the pointer is nil. +func sizeFixed32Ptr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + return f.tagsize + protowire.SizeFixed32() +} + +// appendFixed32Ptr wire encodes a *uint32 pointer as a Fixed32. +// It panics if the pointer is nil. +func appendFixed32Ptr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Uint32Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, v) + return b, nil +} + +// consumeFixed32Ptr wire decodes a *uint32 pointer as a Fixed32. +func consumeFixed32Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed32Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Uint32Ptr() + if *vp == nil { + *vp = new(uint32) + } + **vp = v + out.n = n + return out, nil +} + +var coderFixed32Ptr = pointerCoderFuncs{ + size: sizeFixed32Ptr, + marshal: appendFixed32Ptr, + unmarshal: consumeFixed32Ptr, + merge: mergeUint32Ptr, +} + +// sizeFixed32Slice returns the size of wire encoding a []uint32 pointer as a repeated Fixed32. +func sizeFixed32Slice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Uint32Slice() + size = len(s) * (f.tagsize + protowire.SizeFixed32()) + return size +} + +// appendFixed32Slice encodes a []uint32 pointer as a repeated Fixed32. +func appendFixed32Slice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Uint32Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, v) + } + return b, nil +} + +// consumeFixed32Slice wire decodes a []uint32 pointer as a repeated Fixed32. +func consumeFixed32Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Uint32Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, v) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.Fixed32Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, v) + out.n = n + return out, nil +} + +var coderFixed32Slice = pointerCoderFuncs{ + size: sizeFixed32Slice, + marshal: appendFixed32Slice, + unmarshal: consumeFixed32Slice, + merge: mergeUint32Slice, +} + +// sizeFixed32PackedSlice returns the size of wire encoding a []uint32 pointer as a packed repeated Fixed32. +func sizeFixed32PackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Uint32Slice() + if len(s) == 0 { + return 0 + } + n := len(s) * protowire.SizeFixed32() + return f.tagsize + protowire.SizeBytes(n) +} + +// appendFixed32PackedSlice encodes a []uint32 pointer as a packed repeated Fixed32. +func appendFixed32PackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Uint32Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := len(s) * protowire.SizeFixed32() + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendFixed32(b, v) + } + return b, nil +} + +var coderFixed32PackedSlice = pointerCoderFuncs{ + size: sizeFixed32PackedSlice, + marshal: appendFixed32PackedSlice, + unmarshal: consumeFixed32Slice, + merge: mergeUint32Slice, +} + +// sizeFixed32Value returns the size of wire encoding a uint32 value as a Fixed32. +func sizeFixed32Value(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeFixed32() +} + +// appendFixed32Value encodes a uint32 value as a Fixed32. +func appendFixed32Value(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed32(b, uint32(v.Uint())) + return b, nil +} + +// consumeFixed32Value decodes a uint32 value as a Fixed32. +func consumeFixed32Value(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.Fixed32Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfUint32(uint32(v)), out, nil +} + +var coderFixed32Value = valueCoderFuncs{ + size: sizeFixed32Value, + marshal: appendFixed32Value, + unmarshal: consumeFixed32Value, + merge: mergeScalarValue, +} + +// sizeFixed32SliceValue returns the size of wire encoding a []uint32 value as a repeated Fixed32. +func sizeFixed32SliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + size = list.Len() * (tagsize + protowire.SizeFixed32()) + return size +} + +// appendFixed32SliceValue encodes a []uint32 value as a repeated Fixed32. +func appendFixed32SliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed32(b, uint32(v.Uint())) + } + return b, nil +} + +// consumeFixed32SliceValue wire decodes a []uint32 value as a repeated Fixed32. +func consumeFixed32SliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint32(uint32(v))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.Fixed32Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint32(uint32(v))) + out.n = n + return listv, out, nil +} + +var coderFixed32SliceValue = valueCoderFuncs{ + size: sizeFixed32SliceValue, + marshal: appendFixed32SliceValue, + unmarshal: consumeFixed32SliceValue, + merge: mergeListValue, +} + +// sizeFixed32PackedSliceValue returns the size of wire encoding a []uint32 value as a packed repeated Fixed32. +func sizeFixed32PackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := llen * protowire.SizeFixed32() + return tagsize + protowire.SizeBytes(n) +} + +// appendFixed32PackedSliceValue encodes a []uint32 value as a packed repeated Fixed32. +func appendFixed32PackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := llen * protowire.SizeFixed32() + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendFixed32(b, uint32(v.Uint())) + } + return b, nil +} + +var coderFixed32PackedSliceValue = valueCoderFuncs{ + size: sizeFixed32PackedSliceValue, + marshal: appendFixed32PackedSliceValue, + unmarshal: consumeFixed32SliceValue, + merge: mergeListValue, +} + +// sizeFloat returns the size of wire encoding a float32 pointer as a Float. +func sizeFloat(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + + return f.tagsize + protowire.SizeFixed32() +} + +// appendFloat wire encodes a float32 pointer as a Float. +func appendFloat(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Float32() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, math.Float32bits(v)) + return b, nil +} + +// consumeFloat wire decodes a float32 pointer as a Float. +func consumeFloat(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed32Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Float32() = math.Float32frombits(v) + out.n = n + return out, nil +} + +var coderFloat = pointerCoderFuncs{ + size: sizeFloat, + marshal: appendFloat, + unmarshal: consumeFloat, + merge: mergeFloat32, +} + +// sizeFloatNoZero returns the size of wire encoding a float32 pointer as a Float. +// The zero value is not encoded. +func sizeFloatNoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Float32() + if v == 0 && !math.Signbit(float64(v)) { + return 0 + } + return f.tagsize + protowire.SizeFixed32() +} + +// appendFloatNoZero wire encodes a float32 pointer as a Float. +// The zero value is not encoded. +func appendFloatNoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Float32() + if v == 0 && !math.Signbit(float64(v)) { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, math.Float32bits(v)) + return b, nil +} + +var coderFloatNoZero = pointerCoderFuncs{ + size: sizeFloatNoZero, + marshal: appendFloatNoZero, + unmarshal: consumeFloat, + merge: mergeFloat32NoZero, +} + +// sizeFloatPtr returns the size of wire encoding a *float32 pointer as a Float. +// It panics if the pointer is nil. +func sizeFloatPtr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + return f.tagsize + protowire.SizeFixed32() +} + +// appendFloatPtr wire encodes a *float32 pointer as a Float. +// It panics if the pointer is nil. +func appendFloatPtr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Float32Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, math.Float32bits(v)) + return b, nil +} + +// consumeFloatPtr wire decodes a *float32 pointer as a Float. +func consumeFloatPtr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed32Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Float32Ptr() + if *vp == nil { + *vp = new(float32) + } + **vp = math.Float32frombits(v) + out.n = n + return out, nil +} + +var coderFloatPtr = pointerCoderFuncs{ + size: sizeFloatPtr, + marshal: appendFloatPtr, + unmarshal: consumeFloatPtr, + merge: mergeFloat32Ptr, +} + +// sizeFloatSlice returns the size of wire encoding a []float32 pointer as a repeated Float. +func sizeFloatSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Float32Slice() + size = len(s) * (f.tagsize + protowire.SizeFixed32()) + return size +} + +// appendFloatSlice encodes a []float32 pointer as a repeated Float. +func appendFloatSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Float32Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed32(b, math.Float32bits(v)) + } + return b, nil +} + +// consumeFloatSlice wire decodes a []float32 pointer as a repeated Float. +func consumeFloatSlice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Float32Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, math.Float32frombits(v)) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.Fixed32Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, math.Float32frombits(v)) + out.n = n + return out, nil +} + +var coderFloatSlice = pointerCoderFuncs{ + size: sizeFloatSlice, + marshal: appendFloatSlice, + unmarshal: consumeFloatSlice, + merge: mergeFloat32Slice, +} + +// sizeFloatPackedSlice returns the size of wire encoding a []float32 pointer as a packed repeated Float. +func sizeFloatPackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Float32Slice() + if len(s) == 0 { + return 0 + } + n := len(s) * protowire.SizeFixed32() + return f.tagsize + protowire.SizeBytes(n) +} + +// appendFloatPackedSlice encodes a []float32 pointer as a packed repeated Float. +func appendFloatPackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Float32Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := len(s) * protowire.SizeFixed32() + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendFixed32(b, math.Float32bits(v)) + } + return b, nil +} + +var coderFloatPackedSlice = pointerCoderFuncs{ + size: sizeFloatPackedSlice, + marshal: appendFloatPackedSlice, + unmarshal: consumeFloatSlice, + merge: mergeFloat32Slice, +} + +// sizeFloatValue returns the size of wire encoding a float32 value as a Float. +func sizeFloatValue(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeFixed32() +} + +// appendFloatValue encodes a float32 value as a Float. +func appendFloatValue(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed32(b, math.Float32bits(float32(v.Float()))) + return b, nil +} + +// consumeFloatValue decodes a float32 value as a Float. +func consumeFloatValue(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.Fixed32Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v))), out, nil +} + +var coderFloatValue = valueCoderFuncs{ + size: sizeFloatValue, + marshal: appendFloatValue, + unmarshal: consumeFloatValue, + merge: mergeScalarValue, +} + +// sizeFloatSliceValue returns the size of wire encoding a []float32 value as a repeated Float. +func sizeFloatSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + size = list.Len() * (tagsize + protowire.SizeFixed32()) + return size +} + +// appendFloatSliceValue encodes a []float32 value as a repeated Float. +func appendFloatSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed32(b, math.Float32bits(float32(v.Float()))) + } + return b, nil +} + +// consumeFloatSliceValue wire decodes a []float32 value as a repeated Float. +func consumeFloatSliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v)))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.Fixed32Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v)))) + out.n = n + return listv, out, nil +} + +var coderFloatSliceValue = valueCoderFuncs{ + size: sizeFloatSliceValue, + marshal: appendFloatSliceValue, + unmarshal: consumeFloatSliceValue, + merge: mergeListValue, +} + +// sizeFloatPackedSliceValue returns the size of wire encoding a []float32 value as a packed repeated Float. +func sizeFloatPackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := llen * protowire.SizeFixed32() + return tagsize + protowire.SizeBytes(n) +} + +// appendFloatPackedSliceValue encodes a []float32 value as a packed repeated Float. +func appendFloatPackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := llen * protowire.SizeFixed32() + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendFixed32(b, math.Float32bits(float32(v.Float()))) + } + return b, nil +} + +var coderFloatPackedSliceValue = valueCoderFuncs{ + size: sizeFloatPackedSliceValue, + marshal: appendFloatPackedSliceValue, + unmarshal: consumeFloatSliceValue, + merge: mergeListValue, +} + +// sizeSfixed64 returns the size of wire encoding a int64 pointer as a Sfixed64. +func sizeSfixed64(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + + return f.tagsize + protowire.SizeFixed64() +} + +// appendSfixed64 wire encodes a int64 pointer as a Sfixed64. +func appendSfixed64(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int64() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, uint64(v)) + return b, nil +} + +// consumeSfixed64 wire decodes a int64 pointer as a Sfixed64. +func consumeSfixed64(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed64Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Int64() = int64(v) + out.n = n + return out, nil +} + +var coderSfixed64 = pointerCoderFuncs{ + size: sizeSfixed64, + marshal: appendSfixed64, + unmarshal: consumeSfixed64, + merge: mergeInt64, +} + +// sizeSfixed64NoZero returns the size of wire encoding a int64 pointer as a Sfixed64. +// The zero value is not encoded. +func sizeSfixed64NoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Int64() + if v == 0 { + return 0 + } + return f.tagsize + protowire.SizeFixed64() +} + +// appendSfixed64NoZero wire encodes a int64 pointer as a Sfixed64. +// The zero value is not encoded. +func appendSfixed64NoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Int64() + if v == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, uint64(v)) + return b, nil +} + +var coderSfixed64NoZero = pointerCoderFuncs{ + size: sizeSfixed64NoZero, + marshal: appendSfixed64NoZero, + unmarshal: consumeSfixed64, + merge: mergeInt64NoZero, +} + +// sizeSfixed64Ptr returns the size of wire encoding a *int64 pointer as a Sfixed64. +// It panics if the pointer is nil. +func sizeSfixed64Ptr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + return f.tagsize + protowire.SizeFixed64() +} + +// appendSfixed64Ptr wire encodes a *int64 pointer as a Sfixed64. +// It panics if the pointer is nil. +func appendSfixed64Ptr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Int64Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, uint64(v)) + return b, nil +} + +// consumeSfixed64Ptr wire decodes a *int64 pointer as a Sfixed64. +func consumeSfixed64Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed64Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Int64Ptr() + if *vp == nil { + *vp = new(int64) + } + **vp = int64(v) + out.n = n + return out, nil +} + +var coderSfixed64Ptr = pointerCoderFuncs{ + size: sizeSfixed64Ptr, + marshal: appendSfixed64Ptr, + unmarshal: consumeSfixed64Ptr, + merge: mergeInt64Ptr, +} + +// sizeSfixed64Slice returns the size of wire encoding a []int64 pointer as a repeated Sfixed64. +func sizeSfixed64Slice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int64Slice() + size = len(s) * (f.tagsize + protowire.SizeFixed64()) + return size +} + +// appendSfixed64Slice encodes a []int64 pointer as a repeated Sfixed64. +func appendSfixed64Slice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int64Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, uint64(v)) + } + return b, nil +} + +// consumeSfixed64Slice wire decodes a []int64 pointer as a repeated Sfixed64. +func consumeSfixed64Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Int64Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, int64(v)) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.Fixed64Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, int64(v)) + out.n = n + return out, nil +} + +var coderSfixed64Slice = pointerCoderFuncs{ + size: sizeSfixed64Slice, + marshal: appendSfixed64Slice, + unmarshal: consumeSfixed64Slice, + merge: mergeInt64Slice, +} + +// sizeSfixed64PackedSlice returns the size of wire encoding a []int64 pointer as a packed repeated Sfixed64. +func sizeSfixed64PackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Int64Slice() + if len(s) == 0 { + return 0 + } + n := len(s) * protowire.SizeFixed64() + return f.tagsize + protowire.SizeBytes(n) +} + +// appendSfixed64PackedSlice encodes a []int64 pointer as a packed repeated Sfixed64. +func appendSfixed64PackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Int64Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := len(s) * protowire.SizeFixed64() + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendFixed64(b, uint64(v)) + } + return b, nil +} + +var coderSfixed64PackedSlice = pointerCoderFuncs{ + size: sizeSfixed64PackedSlice, + marshal: appendSfixed64PackedSlice, + unmarshal: consumeSfixed64Slice, + merge: mergeInt64Slice, +} + +// sizeSfixed64Value returns the size of wire encoding a int64 value as a Sfixed64. +func sizeSfixed64Value(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeFixed64() +} + +// appendSfixed64Value encodes a int64 value as a Sfixed64. +func appendSfixed64Value(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed64(b, uint64(v.Int())) + return b, nil +} + +// consumeSfixed64Value decodes a int64 value as a Sfixed64. +func consumeSfixed64Value(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.Fixed64Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfInt64(int64(v)), out, nil +} + +var coderSfixed64Value = valueCoderFuncs{ + size: sizeSfixed64Value, + marshal: appendSfixed64Value, + unmarshal: consumeSfixed64Value, + merge: mergeScalarValue, +} + +// sizeSfixed64SliceValue returns the size of wire encoding a []int64 value as a repeated Sfixed64. +func sizeSfixed64SliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + size = list.Len() * (tagsize + protowire.SizeFixed64()) + return size +} + +// appendSfixed64SliceValue encodes a []int64 value as a repeated Sfixed64. +func appendSfixed64SliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed64(b, uint64(v.Int())) + } + return b, nil +} + +// consumeSfixed64SliceValue wire decodes a []int64 value as a repeated Sfixed64. +func consumeSfixed64SliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt64(int64(v))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.Fixed64Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt64(int64(v))) + out.n = n + return listv, out, nil +} + +var coderSfixed64SliceValue = valueCoderFuncs{ + size: sizeSfixed64SliceValue, + marshal: appendSfixed64SliceValue, + unmarshal: consumeSfixed64SliceValue, + merge: mergeListValue, +} + +// sizeSfixed64PackedSliceValue returns the size of wire encoding a []int64 value as a packed repeated Sfixed64. +func sizeSfixed64PackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := llen * protowire.SizeFixed64() + return tagsize + protowire.SizeBytes(n) +} + +// appendSfixed64PackedSliceValue encodes a []int64 value as a packed repeated Sfixed64. +func appendSfixed64PackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := llen * protowire.SizeFixed64() + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendFixed64(b, uint64(v.Int())) + } + return b, nil +} + +var coderSfixed64PackedSliceValue = valueCoderFuncs{ + size: sizeSfixed64PackedSliceValue, + marshal: appendSfixed64PackedSliceValue, + unmarshal: consumeSfixed64SliceValue, + merge: mergeListValue, +} + +// sizeFixed64 returns the size of wire encoding a uint64 pointer as a Fixed64. +func sizeFixed64(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + + return f.tagsize + protowire.SizeFixed64() +} + +// appendFixed64 wire encodes a uint64 pointer as a Fixed64. +func appendFixed64(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Uint64() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, v) + return b, nil +} + +// consumeFixed64 wire decodes a uint64 pointer as a Fixed64. +func consumeFixed64(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed64Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Uint64() = v + out.n = n + return out, nil +} + +var coderFixed64 = pointerCoderFuncs{ + size: sizeFixed64, + marshal: appendFixed64, + unmarshal: consumeFixed64, + merge: mergeUint64, +} + +// sizeFixed64NoZero returns the size of wire encoding a uint64 pointer as a Fixed64. +// The zero value is not encoded. +func sizeFixed64NoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Uint64() + if v == 0 { + return 0 + } + return f.tagsize + protowire.SizeFixed64() +} + +// appendFixed64NoZero wire encodes a uint64 pointer as a Fixed64. +// The zero value is not encoded. +func appendFixed64NoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Uint64() + if v == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, v) + return b, nil +} + +var coderFixed64NoZero = pointerCoderFuncs{ + size: sizeFixed64NoZero, + marshal: appendFixed64NoZero, + unmarshal: consumeFixed64, + merge: mergeUint64NoZero, +} + +// sizeFixed64Ptr returns the size of wire encoding a *uint64 pointer as a Fixed64. +// It panics if the pointer is nil. +func sizeFixed64Ptr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + return f.tagsize + protowire.SizeFixed64() +} + +// appendFixed64Ptr wire encodes a *uint64 pointer as a Fixed64. +// It panics if the pointer is nil. +func appendFixed64Ptr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Uint64Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, v) + return b, nil +} + +// consumeFixed64Ptr wire decodes a *uint64 pointer as a Fixed64. +func consumeFixed64Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed64Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Uint64Ptr() + if *vp == nil { + *vp = new(uint64) + } + **vp = v + out.n = n + return out, nil +} + +var coderFixed64Ptr = pointerCoderFuncs{ + size: sizeFixed64Ptr, + marshal: appendFixed64Ptr, + unmarshal: consumeFixed64Ptr, + merge: mergeUint64Ptr, +} + +// sizeFixed64Slice returns the size of wire encoding a []uint64 pointer as a repeated Fixed64. +func sizeFixed64Slice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Uint64Slice() + size = len(s) * (f.tagsize + protowire.SizeFixed64()) + return size +} + +// appendFixed64Slice encodes a []uint64 pointer as a repeated Fixed64. +func appendFixed64Slice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Uint64Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, v) + } + return b, nil +} + +// consumeFixed64Slice wire decodes a []uint64 pointer as a repeated Fixed64. +func consumeFixed64Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Uint64Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, v) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.Fixed64Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, v) + out.n = n + return out, nil +} + +var coderFixed64Slice = pointerCoderFuncs{ + size: sizeFixed64Slice, + marshal: appendFixed64Slice, + unmarshal: consumeFixed64Slice, + merge: mergeUint64Slice, +} + +// sizeFixed64PackedSlice returns the size of wire encoding a []uint64 pointer as a packed repeated Fixed64. +func sizeFixed64PackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Uint64Slice() + if len(s) == 0 { + return 0 + } + n := len(s) * protowire.SizeFixed64() + return f.tagsize + protowire.SizeBytes(n) +} + +// appendFixed64PackedSlice encodes a []uint64 pointer as a packed repeated Fixed64. +func appendFixed64PackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Uint64Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := len(s) * protowire.SizeFixed64() + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendFixed64(b, v) + } + return b, nil +} + +var coderFixed64PackedSlice = pointerCoderFuncs{ + size: sizeFixed64PackedSlice, + marshal: appendFixed64PackedSlice, + unmarshal: consumeFixed64Slice, + merge: mergeUint64Slice, +} + +// sizeFixed64Value returns the size of wire encoding a uint64 value as a Fixed64. +func sizeFixed64Value(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeFixed64() +} + +// appendFixed64Value encodes a uint64 value as a Fixed64. +func appendFixed64Value(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed64(b, v.Uint()) + return b, nil +} + +// consumeFixed64Value decodes a uint64 value as a Fixed64. +func consumeFixed64Value(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.Fixed64Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfUint64(v), out, nil +} + +var coderFixed64Value = valueCoderFuncs{ + size: sizeFixed64Value, + marshal: appendFixed64Value, + unmarshal: consumeFixed64Value, + merge: mergeScalarValue, +} + +// sizeFixed64SliceValue returns the size of wire encoding a []uint64 value as a repeated Fixed64. +func sizeFixed64SliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + size = list.Len() * (tagsize + protowire.SizeFixed64()) + return size +} + +// appendFixed64SliceValue encodes a []uint64 value as a repeated Fixed64. +func appendFixed64SliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed64(b, v.Uint()) + } + return b, nil +} + +// consumeFixed64SliceValue wire decodes a []uint64 value as a repeated Fixed64. +func consumeFixed64SliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint64(v)) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.Fixed64Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint64(v)) + out.n = n + return listv, out, nil +} + +var coderFixed64SliceValue = valueCoderFuncs{ + size: sizeFixed64SliceValue, + marshal: appendFixed64SliceValue, + unmarshal: consumeFixed64SliceValue, + merge: mergeListValue, +} + +// sizeFixed64PackedSliceValue returns the size of wire encoding a []uint64 value as a packed repeated Fixed64. +func sizeFixed64PackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := llen * protowire.SizeFixed64() + return tagsize + protowire.SizeBytes(n) +} + +// appendFixed64PackedSliceValue encodes a []uint64 value as a packed repeated Fixed64. +func appendFixed64PackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := llen * protowire.SizeFixed64() + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendFixed64(b, v.Uint()) + } + return b, nil +} + +var coderFixed64PackedSliceValue = valueCoderFuncs{ + size: sizeFixed64PackedSliceValue, + marshal: appendFixed64PackedSliceValue, + unmarshal: consumeFixed64SliceValue, + merge: mergeListValue, +} + +// sizeDouble returns the size of wire encoding a float64 pointer as a Double. +func sizeDouble(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + + return f.tagsize + protowire.SizeFixed64() +} + +// appendDouble wire encodes a float64 pointer as a Double. +func appendDouble(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Float64() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, math.Float64bits(v)) + return b, nil +} + +// consumeDouble wire decodes a float64 pointer as a Double. +func consumeDouble(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed64Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Float64() = math.Float64frombits(v) + out.n = n + return out, nil +} + +var coderDouble = pointerCoderFuncs{ + size: sizeDouble, + marshal: appendDouble, + unmarshal: consumeDouble, + merge: mergeFloat64, +} + +// sizeDoubleNoZero returns the size of wire encoding a float64 pointer as a Double. +// The zero value is not encoded. +func sizeDoubleNoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Float64() + if v == 0 && !math.Signbit(float64(v)) { + return 0 + } + return f.tagsize + protowire.SizeFixed64() +} + +// appendDoubleNoZero wire encodes a float64 pointer as a Double. +// The zero value is not encoded. +func appendDoubleNoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Float64() + if v == 0 && !math.Signbit(float64(v)) { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, math.Float64bits(v)) + return b, nil +} + +var coderDoubleNoZero = pointerCoderFuncs{ + size: sizeDoubleNoZero, + marshal: appendDoubleNoZero, + unmarshal: consumeDouble, + merge: mergeFloat64NoZero, +} + +// sizeDoublePtr returns the size of wire encoding a *float64 pointer as a Double. +// It panics if the pointer is nil. +func sizeDoublePtr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + return f.tagsize + protowire.SizeFixed64() +} + +// appendDoublePtr wire encodes a *float64 pointer as a Double. +// It panics if the pointer is nil. +func appendDoublePtr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.Float64Ptr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, math.Float64bits(v)) + return b, nil +} + +// consumeDoublePtr wire decodes a *float64 pointer as a Double. +func consumeDoublePtr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.Fixed64Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.Float64Ptr() + if *vp == nil { + *vp = new(float64) + } + **vp = math.Float64frombits(v) + out.n = n + return out, nil +} + +var coderDoublePtr = pointerCoderFuncs{ + size: sizeDoublePtr, + marshal: appendDoublePtr, + unmarshal: consumeDoublePtr, + merge: mergeFloat64Ptr, +} + +// sizeDoubleSlice returns the size of wire encoding a []float64 pointer as a repeated Double. +func sizeDoubleSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Float64Slice() + size = len(s) * (f.tagsize + protowire.SizeFixed64()) + return size +} + +// appendDoubleSlice encodes a []float64 pointer as a repeated Double. +func appendDoubleSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Float64Slice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendFixed64(b, math.Float64bits(v)) + } + return b, nil +} + +// consumeDoubleSlice wire decodes a []float64 pointer as a repeated Double. +func consumeDoubleSlice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.Float64Slice() + if wtyp == protowire.BytesType { + s := *sp + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + s = append(s, math.Float64frombits(v)) + b = b[n:] + } + *sp = s + out.n = n + return out, nil + } + if wtyp != protowire.Fixed64Type { + return out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, math.Float64frombits(v)) + out.n = n + return out, nil +} + +var coderDoubleSlice = pointerCoderFuncs{ + size: sizeDoubleSlice, + marshal: appendDoubleSlice, + unmarshal: consumeDoubleSlice, + merge: mergeFloat64Slice, +} + +// sizeDoublePackedSlice returns the size of wire encoding a []float64 pointer as a packed repeated Double. +func sizeDoublePackedSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.Float64Slice() + if len(s) == 0 { + return 0 + } + n := len(s) * protowire.SizeFixed64() + return f.tagsize + protowire.SizeBytes(n) +} + +// appendDoublePackedSlice encodes a []float64 pointer as a packed repeated Double. +func appendDoublePackedSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.Float64Slice() + if len(s) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := len(s) * protowire.SizeFixed64() + b = protowire.AppendVarint(b, uint64(n)) + for _, v := range s { + b = protowire.AppendFixed64(b, math.Float64bits(v)) + } + return b, nil +} + +var coderDoublePackedSlice = pointerCoderFuncs{ + size: sizeDoublePackedSlice, + marshal: appendDoublePackedSlice, + unmarshal: consumeDoubleSlice, + merge: mergeFloat64Slice, +} + +// sizeDoubleValue returns the size of wire encoding a float64 value as a Double. +func sizeDoubleValue(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeFixed64() +} + +// appendDoubleValue encodes a float64 value as a Double. +func appendDoubleValue(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed64(b, math.Float64bits(v.Float())) + return b, nil +} + +// consumeDoubleValue decodes a float64 value as a Double. +func consumeDoubleValue(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.Fixed64Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfFloat64(math.Float64frombits(v)), out, nil +} + +var coderDoubleValue = valueCoderFuncs{ + size: sizeDoubleValue, + marshal: appendDoubleValue, + unmarshal: consumeDoubleValue, + merge: mergeScalarValue, +} + +// sizeDoubleSliceValue returns the size of wire encoding a []float64 value as a repeated Double. +func sizeDoubleSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + size = list.Len() * (tagsize + protowire.SizeFixed64()) + return size +} + +// appendDoubleSliceValue encodes a []float64 value as a repeated Double. +func appendDoubleSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendFixed64(b, math.Float64bits(v.Float())) + } + return b, nil +} + +// consumeDoubleSliceValue wire decodes a []float64 value as a repeated Double. +func consumeDoubleSliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfFloat64(math.Float64frombits(v))) + b = b[n:] + } + out.n = n + return listv, out, nil + } + if wtyp != protowire.Fixed64Type { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfFloat64(math.Float64frombits(v))) + out.n = n + return listv, out, nil +} + +var coderDoubleSliceValue = valueCoderFuncs{ + size: sizeDoubleSliceValue, + marshal: appendDoubleSliceValue, + unmarshal: consumeDoubleSliceValue, + merge: mergeListValue, +} + +// sizeDoublePackedSliceValue returns the size of wire encoding a []float64 value as a packed repeated Double. +func sizeDoublePackedSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return 0 + } + n := llen * protowire.SizeFixed64() + return tagsize + protowire.SizeBytes(n) +} + +// appendDoublePackedSliceValue encodes a []float64 value as a packed repeated Double. +func appendDoublePackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + llen := list.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, wiretag) + n := llen * protowire.SizeFixed64() + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + v := list.Get(i) + b = protowire.AppendFixed64(b, math.Float64bits(v.Float())) + } + return b, nil +} + +var coderDoublePackedSliceValue = valueCoderFuncs{ + size: sizeDoublePackedSliceValue, + marshal: appendDoublePackedSliceValue, + unmarshal: consumeDoubleSliceValue, + merge: mergeListValue, +} + +// sizeString returns the size of wire encoding a string pointer as a String. +func sizeString(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.String() + return f.tagsize + protowire.SizeBytes(len(v)) +} + +// appendString wire encodes a string pointer as a String. +func appendString(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.String() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendString(b, v) + return b, nil +} + +// consumeString wire decodes a string pointer as a String. +func consumeString(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeString(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *p.String() = v + out.n = n + return out, nil +} + +var coderString = pointerCoderFuncs{ + size: sizeString, + marshal: appendString, + unmarshal: consumeString, + merge: mergeString, +} + +// appendStringValidateUTF8 wire encodes a string pointer as a String. +func appendStringValidateUTF8(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.String() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendString(b, v) + if !utf8.ValidString(v) { + return b, errInvalidUTF8{} + } + return b, nil +} + +// consumeStringValidateUTF8 wire decodes a string pointer as a String. +func consumeStringValidateUTF8(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeString(b) + if n < 0 { + return out, protowire.ParseError(n) + } + if !utf8.ValidString(v) { + return out, errInvalidUTF8{} + } + *p.String() = v + out.n = n + return out, nil +} + +var coderStringValidateUTF8 = pointerCoderFuncs{ + size: sizeString, + marshal: appendStringValidateUTF8, + unmarshal: consumeStringValidateUTF8, + merge: mergeString, +} + +// sizeStringNoZero returns the size of wire encoding a string pointer as a String. +// The zero value is not encoded. +func sizeStringNoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.String() + if len(v) == 0 { + return 0 + } + return f.tagsize + protowire.SizeBytes(len(v)) +} + +// appendStringNoZero wire encodes a string pointer as a String. +// The zero value is not encoded. +func appendStringNoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.String() + if len(v) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendString(b, v) + return b, nil +} + +var coderStringNoZero = pointerCoderFuncs{ + size: sizeStringNoZero, + marshal: appendStringNoZero, + unmarshal: consumeString, + merge: mergeStringNoZero, +} + +// appendStringNoZeroValidateUTF8 wire encodes a string pointer as a String. +// The zero value is not encoded. +func appendStringNoZeroValidateUTF8(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.String() + if len(v) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendString(b, v) + if !utf8.ValidString(v) { + return b, errInvalidUTF8{} + } + return b, nil +} + +var coderStringNoZeroValidateUTF8 = pointerCoderFuncs{ + size: sizeStringNoZero, + marshal: appendStringNoZeroValidateUTF8, + unmarshal: consumeStringValidateUTF8, + merge: mergeStringNoZero, +} + +// sizeStringPtr returns the size of wire encoding a *string pointer as a String. +// It panics if the pointer is nil. +func sizeStringPtr(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := **p.StringPtr() + return f.tagsize + protowire.SizeBytes(len(v)) +} + +// appendStringPtr wire encodes a *string pointer as a String. +// It panics if the pointer is nil. +func appendStringPtr(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.StringPtr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendString(b, v) + return b, nil +} + +// consumeStringPtr wire decodes a *string pointer as a String. +func consumeStringPtr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeString(b) + if n < 0 { + return out, protowire.ParseError(n) + } + vp := p.StringPtr() + if *vp == nil { + *vp = new(string) + } + **vp = v + out.n = n + return out, nil +} + +var coderStringPtr = pointerCoderFuncs{ + size: sizeStringPtr, + marshal: appendStringPtr, + unmarshal: consumeStringPtr, + merge: mergeStringPtr, +} + +// appendStringPtrValidateUTF8 wire encodes a *string pointer as a String. +// It panics if the pointer is nil. +func appendStringPtrValidateUTF8(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := **p.StringPtr() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendString(b, v) + if !utf8.ValidString(v) { + return b, errInvalidUTF8{} + } + return b, nil +} + +// consumeStringPtrValidateUTF8 wire decodes a *string pointer as a String. +func consumeStringPtrValidateUTF8(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeString(b) + if n < 0 { + return out, protowire.ParseError(n) + } + if !utf8.ValidString(v) { + return out, errInvalidUTF8{} + } + vp := p.StringPtr() + if *vp == nil { + *vp = new(string) + } + **vp = v + out.n = n + return out, nil +} + +var coderStringPtrValidateUTF8 = pointerCoderFuncs{ + size: sizeStringPtr, + marshal: appendStringPtrValidateUTF8, + unmarshal: consumeStringPtrValidateUTF8, + merge: mergeStringPtr, +} + +// sizeStringSlice returns the size of wire encoding a []string pointer as a repeated String. +func sizeStringSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.StringSlice() + for _, v := range s { + size += f.tagsize + protowire.SizeBytes(len(v)) + } + return size +} + +// appendStringSlice encodes a []string pointer as a repeated String. +func appendStringSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.StringSlice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendString(b, v) + } + return b, nil +} + +// consumeStringSlice wire decodes a []string pointer as a repeated String. +func consumeStringSlice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.StringSlice() + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeString(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, v) + out.n = n + return out, nil +} + +var coderStringSlice = pointerCoderFuncs{ + size: sizeStringSlice, + marshal: appendStringSlice, + unmarshal: consumeStringSlice, + merge: mergeStringSlice, +} + +// appendStringSliceValidateUTF8 encodes a []string pointer as a repeated String. +func appendStringSliceValidateUTF8(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.StringSlice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendString(b, v) + if !utf8.ValidString(v) { + return b, errInvalidUTF8{} + } + } + return b, nil +} + +// consumeStringSliceValidateUTF8 wire decodes a []string pointer as a repeated String. +func consumeStringSliceValidateUTF8(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.StringSlice() + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeString(b) + if n < 0 { + return out, protowire.ParseError(n) + } + if !utf8.ValidString(v) { + return out, errInvalidUTF8{} + } + *sp = append(*sp, v) + out.n = n + return out, nil +} + +var coderStringSliceValidateUTF8 = pointerCoderFuncs{ + size: sizeStringSlice, + marshal: appendStringSliceValidateUTF8, + unmarshal: consumeStringSliceValidateUTF8, + merge: mergeStringSlice, +} + +// sizeStringValue returns the size of wire encoding a string value as a String. +func sizeStringValue(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeBytes(len(v.String())) +} + +// appendStringValue encodes a string value as a String. +func appendStringValue(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendString(b, v.String()) + return b, nil +} + +// consumeStringValue decodes a string value as a String. +func consumeStringValue(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeString(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfString(string(v)), out, nil +} + +var coderStringValue = valueCoderFuncs{ + size: sizeStringValue, + marshal: appendStringValue, + unmarshal: consumeStringValue, + merge: mergeScalarValue, +} + +// appendStringValueValidateUTF8 encodes a string value as a String. +func appendStringValueValidateUTF8(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendString(b, v.String()) + if !utf8.ValidString(v.String()) { + return b, errInvalidUTF8{} + } + return b, nil +} + +// consumeStringValueValidateUTF8 decodes a string value as a String. +func consumeStringValueValidateUTF8(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeString(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + if !utf8.ValidString(v) { + return protoreflect.Value{}, out, errInvalidUTF8{} + } + out.n = n + return protoreflect.ValueOfString(string(v)), out, nil +} + +var coderStringValueValidateUTF8 = valueCoderFuncs{ + size: sizeStringValue, + marshal: appendStringValueValidateUTF8, + unmarshal: consumeStringValueValidateUTF8, + merge: mergeScalarValue, +} + +// sizeStringSliceValue returns the size of wire encoding a []string value as a repeated String. +func sizeStringSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + size += tagsize + protowire.SizeBytes(len(v.String())) + } + return size +} + +// appendStringSliceValue encodes a []string value as a repeated String. +func appendStringSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendString(b, v.String()) + } + return b, nil +} + +// consumeStringSliceValue wire decodes a []string value as a repeated String. +func consumeStringSliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp != protowire.BytesType { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeString(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfString(string(v))) + out.n = n + return listv, out, nil +} + +var coderStringSliceValue = valueCoderFuncs{ + size: sizeStringSliceValue, + marshal: appendStringSliceValue, + unmarshal: consumeStringSliceValue, + merge: mergeListValue, +} + +// sizeBytes returns the size of wire encoding a []byte pointer as a Bytes. +func sizeBytes(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Bytes() + return f.tagsize + protowire.SizeBytes(len(v)) +} + +// appendBytes wire encodes a []byte pointer as a Bytes. +func appendBytes(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Bytes() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendBytes(b, v) + return b, nil +} + +// consumeBytes wire decodes a []byte pointer as a Bytes. +func consumeBytes(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Bytes() = append(emptyBuf[:], v...) + out.n = n + return out, nil +} + +var coderBytes = pointerCoderFuncs{ + size: sizeBytes, + marshal: appendBytes, + unmarshal: consumeBytes, + merge: mergeBytes, +} + +// appendBytesValidateUTF8 wire encodes a []byte pointer as a Bytes. +func appendBytesValidateUTF8(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Bytes() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendBytes(b, v) + if !utf8.Valid(v) { + return b, errInvalidUTF8{} + } + return b, nil +} + +// consumeBytesValidateUTF8 wire decodes a []byte pointer as a Bytes. +func consumeBytesValidateUTF8(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + if !utf8.Valid(v) { + return out, errInvalidUTF8{} + } + *p.Bytes() = append(emptyBuf[:], v...) + out.n = n + return out, nil +} + +var coderBytesValidateUTF8 = pointerCoderFuncs{ + size: sizeBytes, + marshal: appendBytesValidateUTF8, + unmarshal: consumeBytesValidateUTF8, + merge: mergeBytes, +} + +// sizeBytesNoZero returns the size of wire encoding a []byte pointer as a Bytes. +// The zero value is not encoded. +func sizeBytesNoZero(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := *p.Bytes() + if len(v) == 0 { + return 0 + } + return f.tagsize + protowire.SizeBytes(len(v)) +} + +// appendBytesNoZero wire encodes a []byte pointer as a Bytes. +// The zero value is not encoded. +func appendBytesNoZero(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Bytes() + if len(v) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendBytes(b, v) + return b, nil +} + +// consumeBytesNoZero wire decodes a []byte pointer as a Bytes. +// The zero value is not decoded. +func consumeBytesNoZero(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *p.Bytes() = append(([]byte)(nil), v...) + out.n = n + return out, nil +} + +var coderBytesNoZero = pointerCoderFuncs{ + size: sizeBytesNoZero, + marshal: appendBytesNoZero, + unmarshal: consumeBytesNoZero, + merge: mergeBytesNoZero, +} + +// appendBytesNoZeroValidateUTF8 wire encodes a []byte pointer as a Bytes. +// The zero value is not encoded. +func appendBytesNoZeroValidateUTF8(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + v := *p.Bytes() + if len(v) == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendBytes(b, v) + if !utf8.Valid(v) { + return b, errInvalidUTF8{} + } + return b, nil +} + +// consumeBytesNoZeroValidateUTF8 wire decodes a []byte pointer as a Bytes. +func consumeBytesNoZeroValidateUTF8(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + if !utf8.Valid(v) { + return out, errInvalidUTF8{} + } + *p.Bytes() = append(([]byte)(nil), v...) + out.n = n + return out, nil +} + +var coderBytesNoZeroValidateUTF8 = pointerCoderFuncs{ + size: sizeBytesNoZero, + marshal: appendBytesNoZeroValidateUTF8, + unmarshal: consumeBytesNoZeroValidateUTF8, + merge: mergeBytesNoZero, +} + +// sizeBytesSlice returns the size of wire encoding a [][]byte pointer as a repeated Bytes. +func sizeBytesSlice(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + s := *p.BytesSlice() + for _, v := range s { + size += f.tagsize + protowire.SizeBytes(len(v)) + } + return size +} + +// appendBytesSlice encodes a [][]byte pointer as a repeated Bytes. +func appendBytesSlice(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.BytesSlice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendBytes(b, v) + } + return b, nil +} + +// consumeBytesSlice wire decodes a [][]byte pointer as a repeated Bytes. +func consumeBytesSlice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.BytesSlice() + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + *sp = append(*sp, append(emptyBuf[:], v...)) + out.n = n + return out, nil +} + +var coderBytesSlice = pointerCoderFuncs{ + size: sizeBytesSlice, + marshal: appendBytesSlice, + unmarshal: consumeBytesSlice, + merge: mergeBytesSlice, +} + +// appendBytesSliceValidateUTF8 encodes a [][]byte pointer as a repeated Bytes. +func appendBytesSliceValidateUTF8(b []byte, p pointer, f *coderFieldInfo, _ marshalOptions) ([]byte, error) { + s := *p.BytesSlice() + for _, v := range s { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendBytes(b, v) + if !utf8.Valid(v) { + return b, errInvalidUTF8{} + } + } + return b, nil +} + +// consumeBytesSliceValidateUTF8 wire decodes a [][]byte pointer as a repeated Bytes. +func consumeBytesSliceValidateUTF8(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + sp := p.BytesSlice() + if wtyp != protowire.BytesType { + return out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + if !utf8.Valid(v) { + return out, errInvalidUTF8{} + } + *sp = append(*sp, append(emptyBuf[:], v...)) + out.n = n + return out, nil +} + +var coderBytesSliceValidateUTF8 = pointerCoderFuncs{ + size: sizeBytesSlice, + marshal: appendBytesSliceValidateUTF8, + unmarshal: consumeBytesSliceValidateUTF8, + merge: mergeBytesSlice, +} + +// sizeBytesValue returns the size of wire encoding a []byte value as a Bytes. +func sizeBytesValue(v protoreflect.Value, tagsize int, _ marshalOptions) int { + return tagsize + protowire.SizeBytes(len(v.Bytes())) +} + +// appendBytesValue encodes a []byte value as a Bytes. +func appendBytesValue(b []byte, v protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendBytes(b, v.Bytes()) + return b, nil +} + +// consumeBytesValue decodes a []byte value as a Bytes. +func consumeBytesValue(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + out.n = n + return protoreflect.ValueOfBytes(append(emptyBuf[:], v...)), out, nil +} + +var coderBytesValue = valueCoderFuncs{ + size: sizeBytesValue, + marshal: appendBytesValue, + unmarshal: consumeBytesValue, + merge: mergeBytesValue, +} + +// sizeBytesSliceValue returns the size of wire encoding a [][]byte value as a repeated Bytes. +func sizeBytesSliceValue(listv protoreflect.Value, tagsize int, _ marshalOptions) (size int) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + size += tagsize + protowire.SizeBytes(len(v.Bytes())) + } + return size +} + +// appendBytesSliceValue encodes a [][]byte value as a repeated Bytes. +func appendBytesSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, _ marshalOptions) ([]byte, error) { + list := listv.List() + for i, llen := 0, list.Len(); i < llen; i++ { + v := list.Get(i) + b = protowire.AppendVarint(b, wiretag) + b = protowire.AppendBytes(b, v.Bytes()) + } + return b, nil +} + +// consumeBytesSliceValue wire decodes a [][]byte value as a repeated Bytes. +func consumeBytesSliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, _ unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { + list := listv.List() + if wtyp != protowire.BytesType { + return protoreflect.Value{}, out, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return protoreflect.Value{}, out, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfBytes(append(emptyBuf[:], v...))) + out.n = n + return listv, out, nil +} + +var coderBytesSliceValue = valueCoderFuncs{ + size: sizeBytesSliceValue, + marshal: appendBytesSliceValue, + unmarshal: consumeBytesSliceValue, + merge: mergeBytesListValue, +} + +// We append to an empty array rather than a nil []byte to get non-nil zero-length byte slices. +var emptyBuf [0]byte + +var wireTypes = map[protoreflect.Kind]protowire.Type{ + protoreflect.BoolKind: protowire.VarintType, + protoreflect.EnumKind: protowire.VarintType, + protoreflect.Int32Kind: protowire.VarintType, + protoreflect.Sint32Kind: protowire.VarintType, + protoreflect.Uint32Kind: protowire.VarintType, + protoreflect.Int64Kind: protowire.VarintType, + protoreflect.Sint64Kind: protowire.VarintType, + protoreflect.Uint64Kind: protowire.VarintType, + protoreflect.Sfixed32Kind: protowire.Fixed32Type, + protoreflect.Fixed32Kind: protowire.Fixed32Type, + protoreflect.FloatKind: protowire.Fixed32Type, + protoreflect.Sfixed64Kind: protowire.Fixed64Type, + protoreflect.Fixed64Kind: protowire.Fixed64Type, + protoreflect.DoubleKind: protowire.Fixed64Type, + protoreflect.StringKind: protowire.BytesType, + protoreflect.BytesKind: protowire.BytesType, + protoreflect.MessageKind: protowire.BytesType, + protoreflect.GroupKind: protowire.StartGroupType, +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_map.go b/vendor/google.golang.org/protobuf/internal/impl/codec_map.go new file mode 100644 index 00000000000..44885a761f6 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_map.go @@ -0,0 +1,389 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "errors" + "reflect" + "sort" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/genid" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +type mapInfo struct { + goType reflect.Type + keyWiretag uint64 + valWiretag uint64 + keyFuncs valueCoderFuncs + valFuncs valueCoderFuncs + keyZero pref.Value + keyKind pref.Kind + conv *mapConverter +} + +func encoderFuncsForMap(fd pref.FieldDescriptor, ft reflect.Type) (valueMessage *MessageInfo, funcs pointerCoderFuncs) { + // TODO: Consider generating specialized map coders. + keyField := fd.MapKey() + valField := fd.MapValue() + keyWiretag := protowire.EncodeTag(1, wireTypes[keyField.Kind()]) + valWiretag := protowire.EncodeTag(2, wireTypes[valField.Kind()]) + keyFuncs := encoderFuncsForValue(keyField) + valFuncs := encoderFuncsForValue(valField) + conv := newMapConverter(ft, fd) + + mapi := &mapInfo{ + goType: ft, + keyWiretag: keyWiretag, + valWiretag: valWiretag, + keyFuncs: keyFuncs, + valFuncs: valFuncs, + keyZero: keyField.Default(), + keyKind: keyField.Kind(), + conv: conv, + } + if valField.Kind() == pref.MessageKind { + valueMessage = getMessageInfo(ft.Elem()) + } + + funcs = pointerCoderFuncs{ + size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { + return sizeMap(p.AsValueOf(ft).Elem(), mapi, f, opts) + }, + marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + return appendMap(b, p.AsValueOf(ft).Elem(), mapi, f, opts) + }, + unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { + mp := p.AsValueOf(ft) + if mp.Elem().IsNil() { + mp.Elem().Set(reflect.MakeMap(mapi.goType)) + } + if f.mi == nil { + return consumeMap(b, mp.Elem(), wtyp, mapi, f, opts) + } else { + return consumeMapOfMessage(b, mp.Elem(), wtyp, mapi, f, opts) + } + }, + } + switch valField.Kind() { + case pref.MessageKind: + funcs.merge = mergeMapOfMessage + case pref.BytesKind: + funcs.merge = mergeMapOfBytes + default: + funcs.merge = mergeMap + } + if valFuncs.isInit != nil { + funcs.isInit = func(p pointer, f *coderFieldInfo) error { + return isInitMap(p.AsValueOf(ft).Elem(), mapi, f) + } + } + return valueMessage, funcs +} + +const ( + mapKeyTagSize = 1 // field 1, tag size 1. + mapValTagSize = 1 // field 2, tag size 2. +) + +func sizeMap(mapv reflect.Value, mapi *mapInfo, f *coderFieldInfo, opts marshalOptions) int { + if mapv.Len() == 0 { + return 0 + } + n := 0 + iter := mapRange(mapv) + for iter.Next() { + key := mapi.conv.keyConv.PBValueOf(iter.Key()).MapKey() + keySize := mapi.keyFuncs.size(key.Value(), mapKeyTagSize, opts) + var valSize int + value := mapi.conv.valConv.PBValueOf(iter.Value()) + if f.mi == nil { + valSize = mapi.valFuncs.size(value, mapValTagSize, opts) + } else { + p := pointerOfValue(iter.Value()) + valSize += mapValTagSize + valSize += protowire.SizeBytes(f.mi.sizePointer(p, opts)) + } + n += f.tagsize + protowire.SizeBytes(keySize+valSize) + } + return n +} + +func consumeMap(b []byte, mapv reflect.Value, wtyp protowire.Type, mapi *mapInfo, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + var ( + key = mapi.keyZero + val = mapi.conv.valConv.New() + ) + for len(b) > 0 { + num, wtyp, n := protowire.ConsumeTag(b) + if n < 0 { + return out, protowire.ParseError(n) + } + if num > protowire.MaxValidNumber { + return out, errors.New("invalid field number") + } + b = b[n:] + err := errUnknown + switch num { + case genid.MapEntry_Key_field_number: + var v pref.Value + var o unmarshalOutput + v, o, err = mapi.keyFuncs.unmarshal(b, key, num, wtyp, opts) + if err != nil { + break + } + key = v + n = o.n + case genid.MapEntry_Value_field_number: + var v pref.Value + var o unmarshalOutput + v, o, err = mapi.valFuncs.unmarshal(b, val, num, wtyp, opts) + if err != nil { + break + } + val = v + n = o.n + } + if err == errUnknown { + n = protowire.ConsumeFieldValue(num, wtyp, b) + if n < 0 { + return out, protowire.ParseError(n) + } + } else if err != nil { + return out, err + } + b = b[n:] + } + mapv.SetMapIndex(mapi.conv.keyConv.GoValueOf(key), mapi.conv.valConv.GoValueOf(val)) + out.n = n + return out, nil +} + +func consumeMapOfMessage(b []byte, mapv reflect.Value, wtyp protowire.Type, mapi *mapInfo, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.BytesType { + return out, errUnknown + } + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + var ( + key = mapi.keyZero + val = reflect.New(f.mi.GoReflectType.Elem()) + ) + for len(b) > 0 { + num, wtyp, n := protowire.ConsumeTag(b) + if n < 0 { + return out, protowire.ParseError(n) + } + if num > protowire.MaxValidNumber { + return out, errors.New("invalid field number") + } + b = b[n:] + err := errUnknown + switch num { + case 1: + var v pref.Value + var o unmarshalOutput + v, o, err = mapi.keyFuncs.unmarshal(b, key, num, wtyp, opts) + if err != nil { + break + } + key = v + n = o.n + case 2: + if wtyp != protowire.BytesType { + break + } + var v []byte + v, n = protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + var o unmarshalOutput + o, err = f.mi.unmarshalPointer(v, pointerOfValue(val), 0, opts) + if o.initialized { + // Consider this map item initialized so long as we see + // an initialized value. + out.initialized = true + } + } + if err == errUnknown { + n = protowire.ConsumeFieldValue(num, wtyp, b) + if n < 0 { + return out, protowire.ParseError(n) + } + } else if err != nil { + return out, err + } + b = b[n:] + } + mapv.SetMapIndex(mapi.conv.keyConv.GoValueOf(key), val) + out.n = n + return out, nil +} + +func appendMapItem(b []byte, keyrv, valrv reflect.Value, mapi *mapInfo, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + if f.mi == nil { + key := mapi.conv.keyConv.PBValueOf(keyrv).MapKey() + val := mapi.conv.valConv.PBValueOf(valrv) + size := 0 + size += mapi.keyFuncs.size(key.Value(), mapKeyTagSize, opts) + size += mapi.valFuncs.size(val, mapValTagSize, opts) + b = protowire.AppendVarint(b, uint64(size)) + b, err := mapi.keyFuncs.marshal(b, key.Value(), mapi.keyWiretag, opts) + if err != nil { + return nil, err + } + return mapi.valFuncs.marshal(b, val, mapi.valWiretag, opts) + } else { + key := mapi.conv.keyConv.PBValueOf(keyrv).MapKey() + val := pointerOfValue(valrv) + valSize := f.mi.sizePointer(val, opts) + size := 0 + size += mapi.keyFuncs.size(key.Value(), mapKeyTagSize, opts) + size += mapValTagSize + protowire.SizeBytes(valSize) + b = protowire.AppendVarint(b, uint64(size)) + b, err := mapi.keyFuncs.marshal(b, key.Value(), mapi.keyWiretag, opts) + if err != nil { + return nil, err + } + b = protowire.AppendVarint(b, mapi.valWiretag) + b = protowire.AppendVarint(b, uint64(valSize)) + return f.mi.marshalAppendPointer(b, val, opts) + } +} + +func appendMap(b []byte, mapv reflect.Value, mapi *mapInfo, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + if mapv.Len() == 0 { + return b, nil + } + if opts.Deterministic() { + return appendMapDeterministic(b, mapv, mapi, f, opts) + } + iter := mapRange(mapv) + for iter.Next() { + var err error + b = protowire.AppendVarint(b, f.wiretag) + b, err = appendMapItem(b, iter.Key(), iter.Value(), mapi, f, opts) + if err != nil { + return b, err + } + } + return b, nil +} + +func appendMapDeterministic(b []byte, mapv reflect.Value, mapi *mapInfo, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + keys := mapv.MapKeys() + sort.Slice(keys, func(i, j int) bool { + switch keys[i].Kind() { + case reflect.Bool: + return !keys[i].Bool() && keys[j].Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return keys[i].Int() < keys[j].Int() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return keys[i].Uint() < keys[j].Uint() + case reflect.Float32, reflect.Float64: + return keys[i].Float() < keys[j].Float() + case reflect.String: + return keys[i].String() < keys[j].String() + default: + panic("invalid kind: " + keys[i].Kind().String()) + } + }) + for _, key := range keys { + var err error + b = protowire.AppendVarint(b, f.wiretag) + b, err = appendMapItem(b, key, mapv.MapIndex(key), mapi, f, opts) + if err != nil { + return b, err + } + } + return b, nil +} + +func isInitMap(mapv reflect.Value, mapi *mapInfo, f *coderFieldInfo) error { + if mi := f.mi; mi != nil { + mi.init() + if !mi.needsInitCheck { + return nil + } + iter := mapRange(mapv) + for iter.Next() { + val := pointerOfValue(iter.Value()) + if err := mi.checkInitializedPointer(val); err != nil { + return err + } + } + } else { + iter := mapRange(mapv) + for iter.Next() { + val := mapi.conv.valConv.PBValueOf(iter.Value()) + if err := mapi.valFuncs.isInit(val); err != nil { + return err + } + } + } + return nil +} + +func mergeMap(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { + dstm := dst.AsValueOf(f.ft).Elem() + srcm := src.AsValueOf(f.ft).Elem() + if srcm.Len() == 0 { + return + } + if dstm.IsNil() { + dstm.Set(reflect.MakeMap(f.ft)) + } + iter := mapRange(srcm) + for iter.Next() { + dstm.SetMapIndex(iter.Key(), iter.Value()) + } +} + +func mergeMapOfBytes(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { + dstm := dst.AsValueOf(f.ft).Elem() + srcm := src.AsValueOf(f.ft).Elem() + if srcm.Len() == 0 { + return + } + if dstm.IsNil() { + dstm.Set(reflect.MakeMap(f.ft)) + } + iter := mapRange(srcm) + for iter.Next() { + dstm.SetMapIndex(iter.Key(), reflect.ValueOf(append(emptyBuf[:], iter.Value().Bytes()...))) + } +} + +func mergeMapOfMessage(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { + dstm := dst.AsValueOf(f.ft).Elem() + srcm := src.AsValueOf(f.ft).Elem() + if srcm.Len() == 0 { + return + } + if dstm.IsNil() { + dstm.Set(reflect.MakeMap(f.ft)) + } + iter := mapRange(srcm) + for iter.Next() { + val := reflect.New(f.ft.Elem().Elem()) + if f.mi != nil { + f.mi.mergePointer(pointerOfValue(val), pointerOfValue(iter.Value()), opts) + } else { + opts.Merge(asMessage(val), asMessage(iter.Value())) + } + dstm.SetMapIndex(iter.Key(), val) + } +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_map_go111.go b/vendor/google.golang.org/protobuf/internal/impl/codec_map_go111.go new file mode 100644 index 00000000000..2706bb67f5d --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_map_go111.go @@ -0,0 +1,37 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.12 + +package impl + +import "reflect" + +type mapIter struct { + v reflect.Value + keys []reflect.Value +} + +// mapRange provides a less-efficient equivalent to +// the Go 1.12 reflect.Value.MapRange method. +func mapRange(v reflect.Value) *mapIter { + return &mapIter{v: v} +} + +func (i *mapIter) Next() bool { + if i.keys == nil { + i.keys = i.v.MapKeys() + } else { + i.keys = i.keys[1:] + } + return len(i.keys) > 0 +} + +func (i *mapIter) Key() reflect.Value { + return i.keys[0] +} + +func (i *mapIter) Value() reflect.Value { + return i.v.MapIndex(i.keys[0]) +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_map_go112.go b/vendor/google.golang.org/protobuf/internal/impl/codec_map_go112.go new file mode 100644 index 00000000000..1533ef600cd --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_map_go112.go @@ -0,0 +1,11 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.12 + +package impl + +import "reflect" + +func mapRange(v reflect.Value) *reflect.MapIter { return v.MapRange() } diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_message.go b/vendor/google.golang.org/protobuf/internal/impl/codec_message.go new file mode 100644 index 00000000000..0e176d565d4 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_message.go @@ -0,0 +1,159 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + "sort" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/fieldsort" + pref "google.golang.org/protobuf/reflect/protoreflect" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +// coderMessageInfo contains per-message information used by the fast-path functions. +// This is a different type from MessageInfo to keep MessageInfo as general-purpose as +// possible. +type coderMessageInfo struct { + methods piface.Methods + + orderedCoderFields []*coderFieldInfo + denseCoderFields []*coderFieldInfo + coderFields map[protowire.Number]*coderFieldInfo + sizecacheOffset offset + unknownOffset offset + extensionOffset offset + needsInitCheck bool + isMessageSet bool + numRequiredFields uint8 +} + +type coderFieldInfo struct { + funcs pointerCoderFuncs // fast-path per-field functions + mi *MessageInfo // field's message + ft reflect.Type + validation validationInfo // information used by message validation + num pref.FieldNumber // field number + offset offset // struct field offset + wiretag uint64 // field tag (number + wire type) + tagsize int // size of the varint-encoded tag + isPointer bool // true if IsNil may be called on the struct field + isRequired bool // true if field is required +} + +func (mi *MessageInfo) makeCoderMethods(t reflect.Type, si structInfo) { + mi.sizecacheOffset = si.sizecacheOffset + mi.unknownOffset = si.unknownOffset + mi.extensionOffset = si.extensionOffset + + mi.coderFields = make(map[protowire.Number]*coderFieldInfo) + fields := mi.Desc.Fields() + preallocFields := make([]coderFieldInfo, fields.Len()) + for i := 0; i < fields.Len(); i++ { + fd := fields.Get(i) + + fs := si.fieldsByNumber[fd.Number()] + isOneof := fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic() + if isOneof { + fs = si.oneofsByName[fd.ContainingOneof().Name()] + } + ft := fs.Type + var wiretag uint64 + if !fd.IsPacked() { + wiretag = protowire.EncodeTag(fd.Number(), wireTypes[fd.Kind()]) + } else { + wiretag = protowire.EncodeTag(fd.Number(), protowire.BytesType) + } + var fieldOffset offset + var funcs pointerCoderFuncs + var childMessage *MessageInfo + switch { + case isOneof: + fieldOffset = offsetOf(fs, mi.Exporter) + case fd.IsWeak(): + fieldOffset = si.weakOffset + funcs = makeWeakMessageFieldCoder(fd) + default: + fieldOffset = offsetOf(fs, mi.Exporter) + childMessage, funcs = fieldCoder(fd, ft) + } + cf := &preallocFields[i] + *cf = coderFieldInfo{ + num: fd.Number(), + offset: fieldOffset, + wiretag: wiretag, + ft: ft, + tagsize: protowire.SizeVarint(wiretag), + funcs: funcs, + mi: childMessage, + validation: newFieldValidationInfo(mi, si, fd, ft), + isPointer: fd.Cardinality() == pref.Repeated || fd.HasPresence(), + isRequired: fd.Cardinality() == pref.Required, + } + mi.orderedCoderFields = append(mi.orderedCoderFields, cf) + mi.coderFields[cf.num] = cf + } + for i, oneofs := 0, mi.Desc.Oneofs(); i < oneofs.Len(); i++ { + if od := oneofs.Get(i); !od.IsSynthetic() { + mi.initOneofFieldCoders(od, si) + } + } + if messageset.IsMessageSet(mi.Desc) { + if !mi.extensionOffset.IsValid() { + panic(fmt.Sprintf("%v: MessageSet with no extensions field", mi.Desc.FullName())) + } + if !mi.unknownOffset.IsValid() { + panic(fmt.Sprintf("%v: MessageSet with no unknown field", mi.Desc.FullName())) + } + mi.isMessageSet = true + } + sort.Slice(mi.orderedCoderFields, func(i, j int) bool { + return mi.orderedCoderFields[i].num < mi.orderedCoderFields[j].num + }) + + var maxDense pref.FieldNumber + for _, cf := range mi.orderedCoderFields { + if cf.num >= 16 && cf.num >= 2*maxDense { + break + } + maxDense = cf.num + } + mi.denseCoderFields = make([]*coderFieldInfo, maxDense+1) + for _, cf := range mi.orderedCoderFields { + if int(cf.num) >= len(mi.denseCoderFields) { + break + } + mi.denseCoderFields[cf.num] = cf + } + + // To preserve compatibility with historic wire output, marshal oneofs last. + if mi.Desc.Oneofs().Len() > 0 { + sort.Slice(mi.orderedCoderFields, func(i, j int) bool { + fi := fields.ByNumber(mi.orderedCoderFields[i].num) + fj := fields.ByNumber(mi.orderedCoderFields[j].num) + return fieldsort.Less(fi, fj) + }) + } + + mi.needsInitCheck = needsInitCheck(mi.Desc) + if mi.methods.Marshal == nil && mi.methods.Size == nil { + mi.methods.Flags |= piface.SupportMarshalDeterministic + mi.methods.Marshal = mi.marshal + mi.methods.Size = mi.size + } + if mi.methods.Unmarshal == nil { + mi.methods.Flags |= piface.SupportUnmarshalDiscardUnknown + mi.methods.Unmarshal = mi.unmarshal + } + if mi.methods.CheckInitialized == nil { + mi.methods.CheckInitialized = mi.checkInitialized + } + if mi.methods.Merge == nil { + mi.methods.Merge = mi.merge + } +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_messageset.go b/vendor/google.golang.org/protobuf/internal/impl/codec_messageset.go new file mode 100644 index 00000000000..cfb68e12fbf --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_messageset.go @@ -0,0 +1,120 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "sort" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/flags" +) + +func sizeMessageSet(mi *MessageInfo, p pointer, opts marshalOptions) (size int) { + if !flags.ProtoLegacy { + return 0 + } + + ext := *p.Apply(mi.extensionOffset).Extensions() + for _, x := range ext { + xi := getExtensionFieldInfo(x.Type()) + if xi.funcs.size == nil { + continue + } + num, _ := protowire.DecodeTag(xi.wiretag) + size += messageset.SizeField(num) + size += xi.funcs.size(x.Value(), protowire.SizeTag(messageset.FieldMessage), opts) + } + + unknown := *p.Apply(mi.unknownOffset).Bytes() + size += messageset.SizeUnknown(unknown) + + return size +} + +func marshalMessageSet(mi *MessageInfo, b []byte, p pointer, opts marshalOptions) ([]byte, error) { + if !flags.ProtoLegacy { + return b, errors.New("no support for message_set_wire_format") + } + + ext := *p.Apply(mi.extensionOffset).Extensions() + switch len(ext) { + case 0: + case 1: + // Fast-path for one extension: Don't bother sorting the keys. + for _, x := range ext { + var err error + b, err = marshalMessageSetField(mi, b, x, opts) + if err != nil { + return b, err + } + } + default: + // Sort the keys to provide a deterministic encoding. + // Not sure this is required, but the old code does it. + keys := make([]int, 0, len(ext)) + for k := range ext { + keys = append(keys, int(k)) + } + sort.Ints(keys) + for _, k := range keys { + var err error + b, err = marshalMessageSetField(mi, b, ext[int32(k)], opts) + if err != nil { + return b, err + } + } + } + + unknown := *p.Apply(mi.unknownOffset).Bytes() + b, err := messageset.AppendUnknown(b, unknown) + if err != nil { + return b, err + } + + return b, nil +} + +func marshalMessageSetField(mi *MessageInfo, b []byte, x ExtensionField, opts marshalOptions) ([]byte, error) { + xi := getExtensionFieldInfo(x.Type()) + num, _ := protowire.DecodeTag(xi.wiretag) + b = messageset.AppendFieldStart(b, num) + b, err := xi.funcs.marshal(b, x.Value(), protowire.EncodeTag(messageset.FieldMessage, protowire.BytesType), opts) + if err != nil { + return b, err + } + b = messageset.AppendFieldEnd(b) + return b, nil +} + +func unmarshalMessageSet(mi *MessageInfo, b []byte, p pointer, opts unmarshalOptions) (out unmarshalOutput, err error) { + if !flags.ProtoLegacy { + return out, errors.New("no support for message_set_wire_format") + } + + ep := p.Apply(mi.extensionOffset).Extensions() + if *ep == nil { + *ep = make(map[int32]ExtensionField) + } + ext := *ep + unknown := p.Apply(mi.unknownOffset).Bytes() + initialized := true + err = messageset.Unmarshal(b, true, func(num protowire.Number, v []byte) error { + o, err := mi.unmarshalExtension(v, num, protowire.BytesType, ext, opts) + if err == errUnknown { + *unknown = protowire.AppendTag(*unknown, num, protowire.BytesType) + *unknown = append(*unknown, v...) + return nil + } + if !o.initialized { + initialized = false + } + return err + }) + out.n = len(b) + out.initialized = initialized + return out, err +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_reflect.go b/vendor/google.golang.org/protobuf/internal/impl/codec_reflect.go new file mode 100644 index 00000000000..86f7dc3c9d7 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_reflect.go @@ -0,0 +1,209 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build purego appengine + +package impl + +import ( + "reflect" + + "google.golang.org/protobuf/encoding/protowire" +) + +func sizeEnum(p pointer, f *coderFieldInfo, _ marshalOptions) (size int) { + v := p.v.Elem().Int() + return f.tagsize + protowire.SizeVarint(uint64(v)) +} + +func appendEnum(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + v := p.v.Elem().Int() + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(v)) + return b, nil +} + +func consumeEnum(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, _ unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return out, protowire.ParseError(n) + } + p.v.Elem().SetInt(int64(v)) + out.n = n + return out, nil +} + +func mergeEnum(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + dst.v.Elem().Set(src.v.Elem()) +} + +var coderEnum = pointerCoderFuncs{ + size: sizeEnum, + marshal: appendEnum, + unmarshal: consumeEnum, + merge: mergeEnum, +} + +func sizeEnumNoZero(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { + if p.v.Elem().Int() == 0 { + return 0 + } + return sizeEnum(p, f, opts) +} + +func appendEnumNoZero(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + if p.v.Elem().Int() == 0 { + return b, nil + } + return appendEnum(b, p, f, opts) +} + +func mergeEnumNoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + if src.v.Elem().Int() != 0 { + dst.v.Elem().Set(src.v.Elem()) + } +} + +var coderEnumNoZero = pointerCoderFuncs{ + size: sizeEnumNoZero, + marshal: appendEnumNoZero, + unmarshal: consumeEnum, + merge: mergeEnumNoZero, +} + +func sizeEnumPtr(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { + return sizeEnum(pointer{p.v.Elem()}, f, opts) +} + +func appendEnumPtr(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + return appendEnum(b, pointer{p.v.Elem()}, f, opts) +} + +func consumeEnumPtr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { + if wtyp != protowire.VarintType { + return out, errUnknown + } + if p.v.Elem().IsNil() { + p.v.Elem().Set(reflect.New(p.v.Elem().Type().Elem())) + } + return consumeEnum(b, pointer{p.v.Elem()}, wtyp, f, opts) +} + +func mergeEnumPtr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + if !src.v.Elem().IsNil() { + v := reflect.New(dst.v.Type().Elem().Elem()) + v.Elem().Set(src.v.Elem().Elem()) + dst.v.Elem().Set(v) + } +} + +var coderEnumPtr = pointerCoderFuncs{ + size: sizeEnumPtr, + marshal: appendEnumPtr, + unmarshal: consumeEnumPtr, + merge: mergeEnumPtr, +} + +func sizeEnumSlice(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { + s := p.v.Elem() + for i, llen := 0, s.Len(); i < llen; i++ { + size += protowire.SizeVarint(uint64(s.Index(i).Int())) + f.tagsize + } + return size +} + +func appendEnumSlice(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + s := p.v.Elem() + for i, llen := 0, s.Len(); i < llen; i++ { + b = protowire.AppendVarint(b, f.wiretag) + b = protowire.AppendVarint(b, uint64(s.Index(i).Int())) + } + return b, nil +} + +func consumeEnumSlice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { + s := p.v.Elem() + if wtyp == protowire.BytesType { + b, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, protowire.ParseError(n) + } + for len(b) > 0 { + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return out, protowire.ParseError(n) + } + rv := reflect.New(s.Type().Elem()).Elem() + rv.SetInt(int64(v)) + s.Set(reflect.Append(s, rv)) + b = b[n:] + } + out.n = n + return out, nil + } + if wtyp != protowire.VarintType { + return out, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return out, protowire.ParseError(n) + } + rv := reflect.New(s.Type().Elem()).Elem() + rv.SetInt(int64(v)) + s.Set(reflect.Append(s, rv)) + out.n = n + return out, nil +} + +func mergeEnumSlice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + dst.v.Elem().Set(reflect.AppendSlice(dst.v.Elem(), src.v.Elem())) +} + +var coderEnumSlice = pointerCoderFuncs{ + size: sizeEnumSlice, + marshal: appendEnumSlice, + unmarshal: consumeEnumSlice, + merge: mergeEnumSlice, +} + +func sizeEnumPackedSlice(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { + s := p.v.Elem() + llen := s.Len() + if llen == 0 { + return 0 + } + n := 0 + for i := 0; i < llen; i++ { + n += protowire.SizeVarint(uint64(s.Index(i).Int())) + } + return f.tagsize + protowire.SizeBytes(n) +} + +func appendEnumPackedSlice(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { + s := p.v.Elem() + llen := s.Len() + if llen == 0 { + return b, nil + } + b = protowire.AppendVarint(b, f.wiretag) + n := 0 + for i := 0; i < llen; i++ { + n += protowire.SizeVarint(uint64(s.Index(i).Int())) + } + b = protowire.AppendVarint(b, uint64(n)) + for i := 0; i < llen; i++ { + b = protowire.AppendVarint(b, uint64(s.Index(i).Int())) + } + return b, nil +} + +var coderEnumPackedSlice = pointerCoderFuncs{ + size: sizeEnumPackedSlice, + marshal: appendEnumPackedSlice, + unmarshal: consumeEnumSlice, + merge: mergeEnumSlice, +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_tables.go b/vendor/google.golang.org/protobuf/internal/impl/codec_tables.go new file mode 100644 index 00000000000..e8997123887 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_tables.go @@ -0,0 +1,557 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/strs" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +// pointerCoderFuncs is a set of pointer encoding functions. +type pointerCoderFuncs struct { + mi *MessageInfo + size func(p pointer, f *coderFieldInfo, opts marshalOptions) int + marshal func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) + unmarshal func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) + isInit func(p pointer, f *coderFieldInfo) error + merge func(dst, src pointer, f *coderFieldInfo, opts mergeOptions) +} + +// valueCoderFuncs is a set of protoreflect.Value encoding functions. +type valueCoderFuncs struct { + size func(v pref.Value, tagsize int, opts marshalOptions) int + marshal func(b []byte, v pref.Value, wiretag uint64, opts marshalOptions) ([]byte, error) + unmarshal func(b []byte, v pref.Value, num protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (pref.Value, unmarshalOutput, error) + isInit func(v pref.Value) error + merge func(dst, src pref.Value, opts mergeOptions) pref.Value +} + +// fieldCoder returns pointer functions for a field, used for operating on +// struct fields. +func fieldCoder(fd pref.FieldDescriptor, ft reflect.Type) (*MessageInfo, pointerCoderFuncs) { + switch { + case fd.IsMap(): + return encoderFuncsForMap(fd, ft) + case fd.Cardinality() == pref.Repeated && !fd.IsPacked(): + // Repeated fields (not packed). + if ft.Kind() != reflect.Slice { + break + } + ft := ft.Elem() + switch fd.Kind() { + case pref.BoolKind: + if ft.Kind() == reflect.Bool { + return nil, coderBoolSlice + } + case pref.EnumKind: + if ft.Kind() == reflect.Int32 { + return nil, coderEnumSlice + } + case pref.Int32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderInt32Slice + } + case pref.Sint32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderSint32Slice + } + case pref.Uint32Kind: + if ft.Kind() == reflect.Uint32 { + return nil, coderUint32Slice + } + case pref.Int64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderInt64Slice + } + case pref.Sint64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderSint64Slice + } + case pref.Uint64Kind: + if ft.Kind() == reflect.Uint64 { + return nil, coderUint64Slice + } + case pref.Sfixed32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderSfixed32Slice + } + case pref.Fixed32Kind: + if ft.Kind() == reflect.Uint32 { + return nil, coderFixed32Slice + } + case pref.FloatKind: + if ft.Kind() == reflect.Float32 { + return nil, coderFloatSlice + } + case pref.Sfixed64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderSfixed64Slice + } + case pref.Fixed64Kind: + if ft.Kind() == reflect.Uint64 { + return nil, coderFixed64Slice + } + case pref.DoubleKind: + if ft.Kind() == reflect.Float64 { + return nil, coderDoubleSlice + } + case pref.StringKind: + if ft.Kind() == reflect.String && strs.EnforceUTF8(fd) { + return nil, coderStringSliceValidateUTF8 + } + if ft.Kind() == reflect.String { + return nil, coderStringSlice + } + if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 && strs.EnforceUTF8(fd) { + return nil, coderBytesSliceValidateUTF8 + } + if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { + return nil, coderBytesSlice + } + case pref.BytesKind: + if ft.Kind() == reflect.String { + return nil, coderStringSlice + } + if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { + return nil, coderBytesSlice + } + case pref.MessageKind: + return getMessageInfo(ft), makeMessageSliceFieldCoder(fd, ft) + case pref.GroupKind: + return getMessageInfo(ft), makeGroupSliceFieldCoder(fd, ft) + } + case fd.Cardinality() == pref.Repeated && fd.IsPacked(): + // Packed repeated fields. + // + // Only repeated fields of primitive numeric types + // (Varint, Fixed32, or Fixed64 wire type) can be packed. + if ft.Kind() != reflect.Slice { + break + } + ft := ft.Elem() + switch fd.Kind() { + case pref.BoolKind: + if ft.Kind() == reflect.Bool { + return nil, coderBoolPackedSlice + } + case pref.EnumKind: + if ft.Kind() == reflect.Int32 { + return nil, coderEnumPackedSlice + } + case pref.Int32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderInt32PackedSlice + } + case pref.Sint32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderSint32PackedSlice + } + case pref.Uint32Kind: + if ft.Kind() == reflect.Uint32 { + return nil, coderUint32PackedSlice + } + case pref.Int64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderInt64PackedSlice + } + case pref.Sint64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderSint64PackedSlice + } + case pref.Uint64Kind: + if ft.Kind() == reflect.Uint64 { + return nil, coderUint64PackedSlice + } + case pref.Sfixed32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderSfixed32PackedSlice + } + case pref.Fixed32Kind: + if ft.Kind() == reflect.Uint32 { + return nil, coderFixed32PackedSlice + } + case pref.FloatKind: + if ft.Kind() == reflect.Float32 { + return nil, coderFloatPackedSlice + } + case pref.Sfixed64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderSfixed64PackedSlice + } + case pref.Fixed64Kind: + if ft.Kind() == reflect.Uint64 { + return nil, coderFixed64PackedSlice + } + case pref.DoubleKind: + if ft.Kind() == reflect.Float64 { + return nil, coderDoublePackedSlice + } + } + case fd.Kind() == pref.MessageKind: + return getMessageInfo(ft), makeMessageFieldCoder(fd, ft) + case fd.Kind() == pref.GroupKind: + return getMessageInfo(ft), makeGroupFieldCoder(fd, ft) + case fd.Syntax() == pref.Proto3 && fd.ContainingOneof() == nil: + // Populated oneof fields always encode even if set to the zero value, + // which normally are not encoded in proto3. + switch fd.Kind() { + case pref.BoolKind: + if ft.Kind() == reflect.Bool { + return nil, coderBoolNoZero + } + case pref.EnumKind: + if ft.Kind() == reflect.Int32 { + return nil, coderEnumNoZero + } + case pref.Int32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderInt32NoZero + } + case pref.Sint32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderSint32NoZero + } + case pref.Uint32Kind: + if ft.Kind() == reflect.Uint32 { + return nil, coderUint32NoZero + } + case pref.Int64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderInt64NoZero + } + case pref.Sint64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderSint64NoZero + } + case pref.Uint64Kind: + if ft.Kind() == reflect.Uint64 { + return nil, coderUint64NoZero + } + case pref.Sfixed32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderSfixed32NoZero + } + case pref.Fixed32Kind: + if ft.Kind() == reflect.Uint32 { + return nil, coderFixed32NoZero + } + case pref.FloatKind: + if ft.Kind() == reflect.Float32 { + return nil, coderFloatNoZero + } + case pref.Sfixed64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderSfixed64NoZero + } + case pref.Fixed64Kind: + if ft.Kind() == reflect.Uint64 { + return nil, coderFixed64NoZero + } + case pref.DoubleKind: + if ft.Kind() == reflect.Float64 { + return nil, coderDoubleNoZero + } + case pref.StringKind: + if ft.Kind() == reflect.String && strs.EnforceUTF8(fd) { + return nil, coderStringNoZeroValidateUTF8 + } + if ft.Kind() == reflect.String { + return nil, coderStringNoZero + } + if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 && strs.EnforceUTF8(fd) { + return nil, coderBytesNoZeroValidateUTF8 + } + if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { + return nil, coderBytesNoZero + } + case pref.BytesKind: + if ft.Kind() == reflect.String { + return nil, coderStringNoZero + } + if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { + return nil, coderBytesNoZero + } + } + case ft.Kind() == reflect.Ptr: + ft := ft.Elem() + switch fd.Kind() { + case pref.BoolKind: + if ft.Kind() == reflect.Bool { + return nil, coderBoolPtr + } + case pref.EnumKind: + if ft.Kind() == reflect.Int32 { + return nil, coderEnumPtr + } + case pref.Int32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderInt32Ptr + } + case pref.Sint32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderSint32Ptr + } + case pref.Uint32Kind: + if ft.Kind() == reflect.Uint32 { + return nil, coderUint32Ptr + } + case pref.Int64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderInt64Ptr + } + case pref.Sint64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderSint64Ptr + } + case pref.Uint64Kind: + if ft.Kind() == reflect.Uint64 { + return nil, coderUint64Ptr + } + case pref.Sfixed32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderSfixed32Ptr + } + case pref.Fixed32Kind: + if ft.Kind() == reflect.Uint32 { + return nil, coderFixed32Ptr + } + case pref.FloatKind: + if ft.Kind() == reflect.Float32 { + return nil, coderFloatPtr + } + case pref.Sfixed64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderSfixed64Ptr + } + case pref.Fixed64Kind: + if ft.Kind() == reflect.Uint64 { + return nil, coderFixed64Ptr + } + case pref.DoubleKind: + if ft.Kind() == reflect.Float64 { + return nil, coderDoublePtr + } + case pref.StringKind: + if ft.Kind() == reflect.String && strs.EnforceUTF8(fd) { + return nil, coderStringPtrValidateUTF8 + } + if ft.Kind() == reflect.String { + return nil, coderStringPtr + } + case pref.BytesKind: + if ft.Kind() == reflect.String { + return nil, coderStringPtr + } + } + default: + switch fd.Kind() { + case pref.BoolKind: + if ft.Kind() == reflect.Bool { + return nil, coderBool + } + case pref.EnumKind: + if ft.Kind() == reflect.Int32 { + return nil, coderEnum + } + case pref.Int32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderInt32 + } + case pref.Sint32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderSint32 + } + case pref.Uint32Kind: + if ft.Kind() == reflect.Uint32 { + return nil, coderUint32 + } + case pref.Int64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderInt64 + } + case pref.Sint64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderSint64 + } + case pref.Uint64Kind: + if ft.Kind() == reflect.Uint64 { + return nil, coderUint64 + } + case pref.Sfixed32Kind: + if ft.Kind() == reflect.Int32 { + return nil, coderSfixed32 + } + case pref.Fixed32Kind: + if ft.Kind() == reflect.Uint32 { + return nil, coderFixed32 + } + case pref.FloatKind: + if ft.Kind() == reflect.Float32 { + return nil, coderFloat + } + case pref.Sfixed64Kind: + if ft.Kind() == reflect.Int64 { + return nil, coderSfixed64 + } + case pref.Fixed64Kind: + if ft.Kind() == reflect.Uint64 { + return nil, coderFixed64 + } + case pref.DoubleKind: + if ft.Kind() == reflect.Float64 { + return nil, coderDouble + } + case pref.StringKind: + if ft.Kind() == reflect.String && strs.EnforceUTF8(fd) { + return nil, coderStringValidateUTF8 + } + if ft.Kind() == reflect.String { + return nil, coderString + } + if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 && strs.EnforceUTF8(fd) { + return nil, coderBytesValidateUTF8 + } + if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { + return nil, coderBytes + } + case pref.BytesKind: + if ft.Kind() == reflect.String { + return nil, coderString + } + if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { + return nil, coderBytes + } + } + } + panic(fmt.Sprintf("invalid type: no encoder for %v %v %v/%v", fd.FullName(), fd.Cardinality(), fd.Kind(), ft)) +} + +// encoderFuncsForValue returns value functions for a field, used for +// extension values and map encoding. +func encoderFuncsForValue(fd pref.FieldDescriptor) valueCoderFuncs { + switch { + case fd.Cardinality() == pref.Repeated && !fd.IsPacked(): + switch fd.Kind() { + case pref.BoolKind: + return coderBoolSliceValue + case pref.EnumKind: + return coderEnumSliceValue + case pref.Int32Kind: + return coderInt32SliceValue + case pref.Sint32Kind: + return coderSint32SliceValue + case pref.Uint32Kind: + return coderUint32SliceValue + case pref.Int64Kind: + return coderInt64SliceValue + case pref.Sint64Kind: + return coderSint64SliceValue + case pref.Uint64Kind: + return coderUint64SliceValue + case pref.Sfixed32Kind: + return coderSfixed32SliceValue + case pref.Fixed32Kind: + return coderFixed32SliceValue + case pref.FloatKind: + return coderFloatSliceValue + case pref.Sfixed64Kind: + return coderSfixed64SliceValue + case pref.Fixed64Kind: + return coderFixed64SliceValue + case pref.DoubleKind: + return coderDoubleSliceValue + case pref.StringKind: + // We don't have a UTF-8 validating coder for repeated string fields. + // Value coders are used for extensions and maps. + // Extensions are never proto3, and maps never contain lists. + return coderStringSliceValue + case pref.BytesKind: + return coderBytesSliceValue + case pref.MessageKind: + return coderMessageSliceValue + case pref.GroupKind: + return coderGroupSliceValue + } + case fd.Cardinality() == pref.Repeated && fd.IsPacked(): + switch fd.Kind() { + case pref.BoolKind: + return coderBoolPackedSliceValue + case pref.EnumKind: + return coderEnumPackedSliceValue + case pref.Int32Kind: + return coderInt32PackedSliceValue + case pref.Sint32Kind: + return coderSint32PackedSliceValue + case pref.Uint32Kind: + return coderUint32PackedSliceValue + case pref.Int64Kind: + return coderInt64PackedSliceValue + case pref.Sint64Kind: + return coderSint64PackedSliceValue + case pref.Uint64Kind: + return coderUint64PackedSliceValue + case pref.Sfixed32Kind: + return coderSfixed32PackedSliceValue + case pref.Fixed32Kind: + return coderFixed32PackedSliceValue + case pref.FloatKind: + return coderFloatPackedSliceValue + case pref.Sfixed64Kind: + return coderSfixed64PackedSliceValue + case pref.Fixed64Kind: + return coderFixed64PackedSliceValue + case pref.DoubleKind: + return coderDoublePackedSliceValue + } + default: + switch fd.Kind() { + default: + case pref.BoolKind: + return coderBoolValue + case pref.EnumKind: + return coderEnumValue + case pref.Int32Kind: + return coderInt32Value + case pref.Sint32Kind: + return coderSint32Value + case pref.Uint32Kind: + return coderUint32Value + case pref.Int64Kind: + return coderInt64Value + case pref.Sint64Kind: + return coderSint64Value + case pref.Uint64Kind: + return coderUint64Value + case pref.Sfixed32Kind: + return coderSfixed32Value + case pref.Fixed32Kind: + return coderFixed32Value + case pref.FloatKind: + return coderFloatValue + case pref.Sfixed64Kind: + return coderSfixed64Value + case pref.Fixed64Kind: + return coderFixed64Value + case pref.DoubleKind: + return coderDoubleValue + case pref.StringKind: + if strs.EnforceUTF8(fd) { + return coderStringValueValidateUTF8 + } + return coderStringValue + case pref.BytesKind: + return coderBytesValue + case pref.MessageKind: + return coderMessageValue + case pref.GroupKind: + return coderGroupValue + } + } + panic(fmt.Sprintf("invalid field: no encoder for %v %v %v", fd.FullName(), fd.Cardinality(), fd.Kind())) +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go b/vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go new file mode 100644 index 00000000000..e118af1e20c --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go @@ -0,0 +1,17 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !purego,!appengine + +package impl + +// When using unsafe pointers, we can just treat enum values as int32s. + +var ( + coderEnumNoZero = coderInt32NoZero + coderEnum = coderInt32 + coderEnumPtr = coderInt32Ptr + coderEnumSlice = coderInt32Slice + coderEnumPackedSlice = coderInt32PackedSlice +) diff --git a/vendor/google.golang.org/protobuf/internal/impl/convert.go b/vendor/google.golang.org/protobuf/internal/impl/convert.go new file mode 100644 index 00000000000..36a90dff381 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/convert.go @@ -0,0 +1,467 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +// unwrapper unwraps the value to the underlying value. +// This is implemented by List and Map. +type unwrapper interface { + protoUnwrap() interface{} +} + +// A Converter coverts to/from Go reflect.Value types and protobuf protoreflect.Value types. +type Converter interface { + // PBValueOf converts a reflect.Value to a protoreflect.Value. + PBValueOf(reflect.Value) pref.Value + + // GoValueOf converts a protoreflect.Value to a reflect.Value. + GoValueOf(pref.Value) reflect.Value + + // IsValidPB returns whether a protoreflect.Value is compatible with this type. + IsValidPB(pref.Value) bool + + // IsValidGo returns whether a reflect.Value is compatible with this type. + IsValidGo(reflect.Value) bool + + // New returns a new field value. + // For scalars, it returns the default value of the field. + // For composite types, it returns a new mutable value. + New() pref.Value + + // Zero returns a new field value. + // For scalars, it returns the default value of the field. + // For composite types, it returns an immutable, empty value. + Zero() pref.Value +} + +// NewConverter matches a Go type with a protobuf field and returns a Converter +// that converts between the two. Enums must be a named int32 kind that +// implements protoreflect.Enum, and messages must be pointer to a named +// struct type that implements protoreflect.ProtoMessage. +// +// This matcher deliberately supports a wider range of Go types than what +// protoc-gen-go historically generated to be able to automatically wrap some +// v1 messages generated by other forks of protoc-gen-go. +func NewConverter(t reflect.Type, fd pref.FieldDescriptor) Converter { + switch { + case fd.IsList(): + return newListConverter(t, fd) + case fd.IsMap(): + return newMapConverter(t, fd) + default: + return newSingularConverter(t, fd) + } + panic(fmt.Sprintf("invalid Go type %v for field %v", t, fd.FullName())) +} + +var ( + boolType = reflect.TypeOf(bool(false)) + int32Type = reflect.TypeOf(int32(0)) + int64Type = reflect.TypeOf(int64(0)) + uint32Type = reflect.TypeOf(uint32(0)) + uint64Type = reflect.TypeOf(uint64(0)) + float32Type = reflect.TypeOf(float32(0)) + float64Type = reflect.TypeOf(float64(0)) + stringType = reflect.TypeOf(string("")) + bytesType = reflect.TypeOf([]byte(nil)) + byteType = reflect.TypeOf(byte(0)) +) + +var ( + boolZero = pref.ValueOfBool(false) + int32Zero = pref.ValueOfInt32(0) + int64Zero = pref.ValueOfInt64(0) + uint32Zero = pref.ValueOfUint32(0) + uint64Zero = pref.ValueOfUint64(0) + float32Zero = pref.ValueOfFloat32(0) + float64Zero = pref.ValueOfFloat64(0) + stringZero = pref.ValueOfString("") + bytesZero = pref.ValueOfBytes(nil) +) + +func newSingularConverter(t reflect.Type, fd pref.FieldDescriptor) Converter { + defVal := func(fd pref.FieldDescriptor, zero pref.Value) pref.Value { + if fd.Cardinality() == pref.Repeated { + // Default isn't defined for repeated fields. + return zero + } + return fd.Default() + } + switch fd.Kind() { + case pref.BoolKind: + if t.Kind() == reflect.Bool { + return &boolConverter{t, defVal(fd, boolZero)} + } + case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind: + if t.Kind() == reflect.Int32 { + return &int32Converter{t, defVal(fd, int32Zero)} + } + case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind: + if t.Kind() == reflect.Int64 { + return &int64Converter{t, defVal(fd, int64Zero)} + } + case pref.Uint32Kind, pref.Fixed32Kind: + if t.Kind() == reflect.Uint32 { + return &uint32Converter{t, defVal(fd, uint32Zero)} + } + case pref.Uint64Kind, pref.Fixed64Kind: + if t.Kind() == reflect.Uint64 { + return &uint64Converter{t, defVal(fd, uint64Zero)} + } + case pref.FloatKind: + if t.Kind() == reflect.Float32 { + return &float32Converter{t, defVal(fd, float32Zero)} + } + case pref.DoubleKind: + if t.Kind() == reflect.Float64 { + return &float64Converter{t, defVal(fd, float64Zero)} + } + case pref.StringKind: + if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) { + return &stringConverter{t, defVal(fd, stringZero)} + } + case pref.BytesKind: + if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) { + return &bytesConverter{t, defVal(fd, bytesZero)} + } + case pref.EnumKind: + // Handle enums, which must be a named int32 type. + if t.Kind() == reflect.Int32 { + return newEnumConverter(t, fd) + } + case pref.MessageKind, pref.GroupKind: + return newMessageConverter(t) + } + panic(fmt.Sprintf("invalid Go type %v for field %v", t, fd.FullName())) +} + +type boolConverter struct { + goType reflect.Type + def pref.Value +} + +func (c *boolConverter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + return pref.ValueOfBool(v.Bool()) +} +func (c *boolConverter) GoValueOf(v pref.Value) reflect.Value { + return reflect.ValueOf(v.Bool()).Convert(c.goType) +} +func (c *boolConverter) IsValidPB(v pref.Value) bool { + _, ok := v.Interface().(bool) + return ok +} +func (c *boolConverter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} +func (c *boolConverter) New() pref.Value { return c.def } +func (c *boolConverter) Zero() pref.Value { return c.def } + +type int32Converter struct { + goType reflect.Type + def pref.Value +} + +func (c *int32Converter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + return pref.ValueOfInt32(int32(v.Int())) +} +func (c *int32Converter) GoValueOf(v pref.Value) reflect.Value { + return reflect.ValueOf(int32(v.Int())).Convert(c.goType) +} +func (c *int32Converter) IsValidPB(v pref.Value) bool { + _, ok := v.Interface().(int32) + return ok +} +func (c *int32Converter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} +func (c *int32Converter) New() pref.Value { return c.def } +func (c *int32Converter) Zero() pref.Value { return c.def } + +type int64Converter struct { + goType reflect.Type + def pref.Value +} + +func (c *int64Converter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + return pref.ValueOfInt64(int64(v.Int())) +} +func (c *int64Converter) GoValueOf(v pref.Value) reflect.Value { + return reflect.ValueOf(int64(v.Int())).Convert(c.goType) +} +func (c *int64Converter) IsValidPB(v pref.Value) bool { + _, ok := v.Interface().(int64) + return ok +} +func (c *int64Converter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} +func (c *int64Converter) New() pref.Value { return c.def } +func (c *int64Converter) Zero() pref.Value { return c.def } + +type uint32Converter struct { + goType reflect.Type + def pref.Value +} + +func (c *uint32Converter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + return pref.ValueOfUint32(uint32(v.Uint())) +} +func (c *uint32Converter) GoValueOf(v pref.Value) reflect.Value { + return reflect.ValueOf(uint32(v.Uint())).Convert(c.goType) +} +func (c *uint32Converter) IsValidPB(v pref.Value) bool { + _, ok := v.Interface().(uint32) + return ok +} +func (c *uint32Converter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} +func (c *uint32Converter) New() pref.Value { return c.def } +func (c *uint32Converter) Zero() pref.Value { return c.def } + +type uint64Converter struct { + goType reflect.Type + def pref.Value +} + +func (c *uint64Converter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + return pref.ValueOfUint64(uint64(v.Uint())) +} +func (c *uint64Converter) GoValueOf(v pref.Value) reflect.Value { + return reflect.ValueOf(uint64(v.Uint())).Convert(c.goType) +} +func (c *uint64Converter) IsValidPB(v pref.Value) bool { + _, ok := v.Interface().(uint64) + return ok +} +func (c *uint64Converter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} +func (c *uint64Converter) New() pref.Value { return c.def } +func (c *uint64Converter) Zero() pref.Value { return c.def } + +type float32Converter struct { + goType reflect.Type + def pref.Value +} + +func (c *float32Converter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + return pref.ValueOfFloat32(float32(v.Float())) +} +func (c *float32Converter) GoValueOf(v pref.Value) reflect.Value { + return reflect.ValueOf(float32(v.Float())).Convert(c.goType) +} +func (c *float32Converter) IsValidPB(v pref.Value) bool { + _, ok := v.Interface().(float32) + return ok +} +func (c *float32Converter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} +func (c *float32Converter) New() pref.Value { return c.def } +func (c *float32Converter) Zero() pref.Value { return c.def } + +type float64Converter struct { + goType reflect.Type + def pref.Value +} + +func (c *float64Converter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + return pref.ValueOfFloat64(float64(v.Float())) +} +func (c *float64Converter) GoValueOf(v pref.Value) reflect.Value { + return reflect.ValueOf(float64(v.Float())).Convert(c.goType) +} +func (c *float64Converter) IsValidPB(v pref.Value) bool { + _, ok := v.Interface().(float64) + return ok +} +func (c *float64Converter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} +func (c *float64Converter) New() pref.Value { return c.def } +func (c *float64Converter) Zero() pref.Value { return c.def } + +type stringConverter struct { + goType reflect.Type + def pref.Value +} + +func (c *stringConverter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + return pref.ValueOfString(v.Convert(stringType).String()) +} +func (c *stringConverter) GoValueOf(v pref.Value) reflect.Value { + // pref.Value.String never panics, so we go through an interface + // conversion here to check the type. + s := v.Interface().(string) + if c.goType.Kind() == reflect.Slice && s == "" { + return reflect.Zero(c.goType) // ensure empty string is []byte(nil) + } + return reflect.ValueOf(s).Convert(c.goType) +} +func (c *stringConverter) IsValidPB(v pref.Value) bool { + _, ok := v.Interface().(string) + return ok +} +func (c *stringConverter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} +func (c *stringConverter) New() pref.Value { return c.def } +func (c *stringConverter) Zero() pref.Value { return c.def } + +type bytesConverter struct { + goType reflect.Type + def pref.Value +} + +func (c *bytesConverter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + if c.goType.Kind() == reflect.String && v.Len() == 0 { + return pref.ValueOfBytes(nil) // ensure empty string is []byte(nil) + } + return pref.ValueOfBytes(v.Convert(bytesType).Bytes()) +} +func (c *bytesConverter) GoValueOf(v pref.Value) reflect.Value { + return reflect.ValueOf(v.Bytes()).Convert(c.goType) +} +func (c *bytesConverter) IsValidPB(v pref.Value) bool { + _, ok := v.Interface().([]byte) + return ok +} +func (c *bytesConverter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} +func (c *bytesConverter) New() pref.Value { return c.def } +func (c *bytesConverter) Zero() pref.Value { return c.def } + +type enumConverter struct { + goType reflect.Type + def pref.Value +} + +func newEnumConverter(goType reflect.Type, fd pref.FieldDescriptor) Converter { + var def pref.Value + if fd.Cardinality() == pref.Repeated { + def = pref.ValueOfEnum(fd.Enum().Values().Get(0).Number()) + } else { + def = fd.Default() + } + return &enumConverter{goType, def} +} + +func (c *enumConverter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + return pref.ValueOfEnum(pref.EnumNumber(v.Int())) +} + +func (c *enumConverter) GoValueOf(v pref.Value) reflect.Value { + return reflect.ValueOf(v.Enum()).Convert(c.goType) +} + +func (c *enumConverter) IsValidPB(v pref.Value) bool { + _, ok := v.Interface().(pref.EnumNumber) + return ok +} + +func (c *enumConverter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} + +func (c *enumConverter) New() pref.Value { + return c.def +} + +func (c *enumConverter) Zero() pref.Value { + return c.def +} + +type messageConverter struct { + goType reflect.Type +} + +func newMessageConverter(goType reflect.Type) Converter { + return &messageConverter{goType} +} + +func (c *messageConverter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + if m, ok := v.Interface().(pref.ProtoMessage); ok { + return pref.ValueOfMessage(m.ProtoReflect()) + } + return pref.ValueOfMessage(legacyWrapMessage(v)) +} + +func (c *messageConverter) GoValueOf(v pref.Value) reflect.Value { + m := v.Message() + var rv reflect.Value + if u, ok := m.(unwrapper); ok { + rv = reflect.ValueOf(u.protoUnwrap()) + } else { + rv = reflect.ValueOf(m.Interface()) + } + if rv.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), c.goType)) + } + return rv +} + +func (c *messageConverter) IsValidPB(v pref.Value) bool { + m := v.Message() + var rv reflect.Value + if u, ok := m.(unwrapper); ok { + rv = reflect.ValueOf(u.protoUnwrap()) + } else { + rv = reflect.ValueOf(m.Interface()) + } + return rv.Type() == c.goType +} + +func (c *messageConverter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} + +func (c *messageConverter) New() pref.Value { + return c.PBValueOf(reflect.New(c.goType.Elem())) +} + +func (c *messageConverter) Zero() pref.Value { + return c.PBValueOf(reflect.Zero(c.goType)) +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/convert_list.go b/vendor/google.golang.org/protobuf/internal/impl/convert_list.go new file mode 100644 index 00000000000..6fccab520e5 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/convert_list.go @@ -0,0 +1,141 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +func newListConverter(t reflect.Type, fd pref.FieldDescriptor) Converter { + switch { + case t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Slice: + return &listPtrConverter{t, newSingularConverter(t.Elem().Elem(), fd)} + case t.Kind() == reflect.Slice: + return &listConverter{t, newSingularConverter(t.Elem(), fd)} + } + panic(fmt.Sprintf("invalid Go type %v for field %v", t, fd.FullName())) +} + +type listConverter struct { + goType reflect.Type // []T + c Converter +} + +func (c *listConverter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + pv := reflect.New(c.goType) + pv.Elem().Set(v) + return pref.ValueOfList(&listReflect{pv, c.c}) +} + +func (c *listConverter) GoValueOf(v pref.Value) reflect.Value { + rv := v.List().(*listReflect).v + if rv.IsNil() { + return reflect.Zero(c.goType) + } + return rv.Elem() +} + +func (c *listConverter) IsValidPB(v pref.Value) bool { + list, ok := v.Interface().(*listReflect) + if !ok { + return false + } + return list.v.Type().Elem() == c.goType +} + +func (c *listConverter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} + +func (c *listConverter) New() pref.Value { + return pref.ValueOfList(&listReflect{reflect.New(c.goType), c.c}) +} + +func (c *listConverter) Zero() pref.Value { + return pref.ValueOfList(&listReflect{reflect.Zero(reflect.PtrTo(c.goType)), c.c}) +} + +type listPtrConverter struct { + goType reflect.Type // *[]T + c Converter +} + +func (c *listPtrConverter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + return pref.ValueOfList(&listReflect{v, c.c}) +} + +func (c *listPtrConverter) GoValueOf(v pref.Value) reflect.Value { + return v.List().(*listReflect).v +} + +func (c *listPtrConverter) IsValidPB(v pref.Value) bool { + list, ok := v.Interface().(*listReflect) + if !ok { + return false + } + return list.v.Type() == c.goType +} + +func (c *listPtrConverter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} + +func (c *listPtrConverter) New() pref.Value { + return c.PBValueOf(reflect.New(c.goType.Elem())) +} + +func (c *listPtrConverter) Zero() pref.Value { + return c.PBValueOf(reflect.Zero(c.goType)) +} + +type listReflect struct { + v reflect.Value // *[]T + conv Converter +} + +func (ls *listReflect) Len() int { + if ls.v.IsNil() { + return 0 + } + return ls.v.Elem().Len() +} +func (ls *listReflect) Get(i int) pref.Value { + return ls.conv.PBValueOf(ls.v.Elem().Index(i)) +} +func (ls *listReflect) Set(i int, v pref.Value) { + ls.v.Elem().Index(i).Set(ls.conv.GoValueOf(v)) +} +func (ls *listReflect) Append(v pref.Value) { + ls.v.Elem().Set(reflect.Append(ls.v.Elem(), ls.conv.GoValueOf(v))) +} +func (ls *listReflect) AppendMutable() pref.Value { + if _, ok := ls.conv.(*messageConverter); !ok { + panic("invalid AppendMutable on list with non-message type") + } + v := ls.NewElement() + ls.Append(v) + return v +} +func (ls *listReflect) Truncate(i int) { + ls.v.Elem().Set(ls.v.Elem().Slice(0, i)) +} +func (ls *listReflect) NewElement() pref.Value { + return ls.conv.New() +} +func (ls *listReflect) IsValid() bool { + return !ls.v.IsNil() +} +func (ls *listReflect) protoUnwrap() interface{} { + return ls.v.Interface() +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/convert_map.go b/vendor/google.golang.org/protobuf/internal/impl/convert_map.go new file mode 100644 index 00000000000..de06b2593f8 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/convert_map.go @@ -0,0 +1,121 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +type mapConverter struct { + goType reflect.Type // map[K]V + keyConv, valConv Converter +} + +func newMapConverter(t reflect.Type, fd pref.FieldDescriptor) *mapConverter { + if t.Kind() != reflect.Map { + panic(fmt.Sprintf("invalid Go type %v for field %v", t, fd.FullName())) + } + return &mapConverter{ + goType: t, + keyConv: newSingularConverter(t.Key(), fd.MapKey()), + valConv: newSingularConverter(t.Elem(), fd.MapValue()), + } +} + +func (c *mapConverter) PBValueOf(v reflect.Value) pref.Value { + if v.Type() != c.goType { + panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) + } + return pref.ValueOfMap(&mapReflect{v, c.keyConv, c.valConv}) +} + +func (c *mapConverter) GoValueOf(v pref.Value) reflect.Value { + return v.Map().(*mapReflect).v +} + +func (c *mapConverter) IsValidPB(v pref.Value) bool { + mapv, ok := v.Interface().(*mapReflect) + if !ok { + return false + } + return mapv.v.Type() == c.goType +} + +func (c *mapConverter) IsValidGo(v reflect.Value) bool { + return v.IsValid() && v.Type() == c.goType +} + +func (c *mapConverter) New() pref.Value { + return c.PBValueOf(reflect.MakeMap(c.goType)) +} + +func (c *mapConverter) Zero() pref.Value { + return c.PBValueOf(reflect.Zero(c.goType)) +} + +type mapReflect struct { + v reflect.Value // map[K]V + keyConv Converter + valConv Converter +} + +func (ms *mapReflect) Len() int { + return ms.v.Len() +} +func (ms *mapReflect) Has(k pref.MapKey) bool { + rk := ms.keyConv.GoValueOf(k.Value()) + rv := ms.v.MapIndex(rk) + return rv.IsValid() +} +func (ms *mapReflect) Get(k pref.MapKey) pref.Value { + rk := ms.keyConv.GoValueOf(k.Value()) + rv := ms.v.MapIndex(rk) + if !rv.IsValid() { + return pref.Value{} + } + return ms.valConv.PBValueOf(rv) +} +func (ms *mapReflect) Set(k pref.MapKey, v pref.Value) { + rk := ms.keyConv.GoValueOf(k.Value()) + rv := ms.valConv.GoValueOf(v) + ms.v.SetMapIndex(rk, rv) +} +func (ms *mapReflect) Clear(k pref.MapKey) { + rk := ms.keyConv.GoValueOf(k.Value()) + ms.v.SetMapIndex(rk, reflect.Value{}) +} +func (ms *mapReflect) Mutable(k pref.MapKey) pref.Value { + if _, ok := ms.valConv.(*messageConverter); !ok { + panic("invalid Mutable on map with non-message value type") + } + v := ms.Get(k) + if !v.IsValid() { + v = ms.NewValue() + ms.Set(k, v) + } + return v +} +func (ms *mapReflect) Range(f func(pref.MapKey, pref.Value) bool) { + iter := mapRange(ms.v) + for iter.Next() { + k := ms.keyConv.PBValueOf(iter.Key()).MapKey() + v := ms.valConv.PBValueOf(iter.Value()) + if !f(k, v) { + return + } + } +} +func (ms *mapReflect) NewValue() pref.Value { + return ms.valConv.New() +} +func (ms *mapReflect) IsValid() bool { + return !ms.v.IsNil() +} +func (ms *mapReflect) protoUnwrap() interface{} { + return ms.v.Interface() +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/decode.go b/vendor/google.golang.org/protobuf/internal/impl/decode.go new file mode 100644 index 00000000000..85ba1d3b334 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/decode.go @@ -0,0 +1,274 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "math/bits" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + preg "google.golang.org/protobuf/reflect/protoregistry" + "google.golang.org/protobuf/runtime/protoiface" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +type unmarshalOptions struct { + flags protoiface.UnmarshalInputFlags + resolver interface { + FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) + FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) + } +} + +func (o unmarshalOptions) Options() proto.UnmarshalOptions { + return proto.UnmarshalOptions{ + Merge: true, + AllowPartial: true, + DiscardUnknown: o.DiscardUnknown(), + Resolver: o.resolver, + } +} + +func (o unmarshalOptions) DiscardUnknown() bool { return o.flags&piface.UnmarshalDiscardUnknown != 0 } + +func (o unmarshalOptions) IsDefault() bool { + return o.flags == 0 && o.resolver == preg.GlobalTypes +} + +var lazyUnmarshalOptions = unmarshalOptions{ + resolver: preg.GlobalTypes, +} + +type unmarshalOutput struct { + n int // number of bytes consumed + initialized bool +} + +// unmarshal is protoreflect.Methods.Unmarshal. +func (mi *MessageInfo) unmarshal(in piface.UnmarshalInput) (piface.UnmarshalOutput, error) { + var p pointer + if ms, ok := in.Message.(*messageState); ok { + p = ms.pointer() + } else { + p = in.Message.(*messageReflectWrapper).pointer() + } + out, err := mi.unmarshalPointer(in.Buf, p, 0, unmarshalOptions{ + flags: in.Flags, + resolver: in.Resolver, + }) + var flags piface.UnmarshalOutputFlags + if out.initialized { + flags |= piface.UnmarshalInitialized + } + return piface.UnmarshalOutput{ + Flags: flags, + }, err +} + +// errUnknown is returned during unmarshaling to indicate a parse error that +// should result in a field being placed in the unknown fields section (for example, +// when the wire type doesn't match) as opposed to the entire unmarshal operation +// failing (for example, when a field extends past the available input). +// +// This is a sentinel error which should never be visible to the user. +var errUnknown = errors.New("unknown") + +func (mi *MessageInfo) unmarshalPointer(b []byte, p pointer, groupTag protowire.Number, opts unmarshalOptions) (out unmarshalOutput, err error) { + mi.init() + if flags.ProtoLegacy && mi.isMessageSet { + return unmarshalMessageSet(mi, b, p, opts) + } + initialized := true + var requiredMask uint64 + var exts *map[int32]ExtensionField + start := len(b) + for len(b) > 0 { + // Parse the tag (field number and wire type). + var tag uint64 + if b[0] < 0x80 { + tag = uint64(b[0]) + b = b[1:] + } else if len(b) >= 2 && b[1] < 128 { + tag = uint64(b[0]&0x7f) + uint64(b[1])<<7 + b = b[2:] + } else { + var n int + tag, n = protowire.ConsumeVarint(b) + if n < 0 { + return out, protowire.ParseError(n) + } + b = b[n:] + } + var num protowire.Number + if n := tag >> 3; n < uint64(protowire.MinValidNumber) || n > uint64(protowire.MaxValidNumber) { + return out, errors.New("invalid field number") + } else { + num = protowire.Number(n) + } + wtyp := protowire.Type(tag & 7) + + if wtyp == protowire.EndGroupType { + if num != groupTag { + return out, errors.New("mismatching end group marker") + } + groupTag = 0 + break + } + + var f *coderFieldInfo + if int(num) < len(mi.denseCoderFields) { + f = mi.denseCoderFields[num] + } else { + f = mi.coderFields[num] + } + var n int + err := errUnknown + switch { + case f != nil: + if f.funcs.unmarshal == nil { + break + } + var o unmarshalOutput + o, err = f.funcs.unmarshal(b, p.Apply(f.offset), wtyp, f, opts) + n = o.n + if err != nil { + break + } + requiredMask |= f.validation.requiredBit + if f.funcs.isInit != nil && !o.initialized { + initialized = false + } + default: + // Possible extension. + if exts == nil && mi.extensionOffset.IsValid() { + exts = p.Apply(mi.extensionOffset).Extensions() + if *exts == nil { + *exts = make(map[int32]ExtensionField) + } + } + if exts == nil { + break + } + var o unmarshalOutput + o, err = mi.unmarshalExtension(b, num, wtyp, *exts, opts) + if err != nil { + break + } + n = o.n + if !o.initialized { + initialized = false + } + } + if err != nil { + if err != errUnknown { + return out, err + } + n = protowire.ConsumeFieldValue(num, wtyp, b) + if n < 0 { + return out, protowire.ParseError(n) + } + if !opts.DiscardUnknown() && mi.unknownOffset.IsValid() { + u := p.Apply(mi.unknownOffset).Bytes() + *u = protowire.AppendTag(*u, num, wtyp) + *u = append(*u, b[:n]...) + } + } + b = b[n:] + } + if groupTag != 0 { + return out, errors.New("missing end group marker") + } + if mi.numRequiredFields > 0 && bits.OnesCount64(requiredMask) != int(mi.numRequiredFields) { + initialized = false + } + if initialized { + out.initialized = true + } + out.n = start - len(b) + return out, nil +} + +func (mi *MessageInfo) unmarshalExtension(b []byte, num protowire.Number, wtyp protowire.Type, exts map[int32]ExtensionField, opts unmarshalOptions) (out unmarshalOutput, err error) { + x := exts[int32(num)] + xt := x.Type() + if xt == nil { + var err error + xt, err = opts.resolver.FindExtensionByNumber(mi.Desc.FullName(), num) + if err != nil { + if err == preg.NotFound { + return out, errUnknown + } + return out, errors.New("%v: unable to resolve extension %v: %v", mi.Desc.FullName(), num, err) + } + } + xi := getExtensionFieldInfo(xt) + if xi.funcs.unmarshal == nil { + return out, errUnknown + } + if flags.LazyUnmarshalExtensions { + if opts.IsDefault() && x.canLazy(xt) { + out, valid := skipExtension(b, xi, num, wtyp, opts) + switch valid { + case ValidationValid: + if out.initialized { + x.appendLazyBytes(xt, xi, num, wtyp, b[:out.n]) + exts[int32(num)] = x + return out, nil + } + case ValidationInvalid: + return out, errors.New("invalid wire format") + case ValidationUnknown: + } + } + } + ival := x.Value() + if !ival.IsValid() && xi.unmarshalNeedsValue { + // Create a new message, list, or map value to fill in. + // For enums, create a prototype value to let the unmarshal func know the + // concrete type. + ival = xt.New() + } + v, out, err := xi.funcs.unmarshal(b, ival, num, wtyp, opts) + if err != nil { + return out, err + } + if xi.funcs.isInit == nil { + out.initialized = true + } + x.Set(xt, v) + exts[int32(num)] = x + return out, nil +} + +func skipExtension(b []byte, xi *extensionFieldInfo, num protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (out unmarshalOutput, _ ValidationStatus) { + if xi.validation.mi == nil { + return out, ValidationUnknown + } + xi.validation.mi.init() + switch xi.validation.typ { + case validationTypeMessage: + if wtyp != protowire.BytesType { + return out, ValidationUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return out, ValidationUnknown + } + out, st := xi.validation.mi.validate(v, 0, opts) + out.n = n + return out, st + case validationTypeGroup: + if wtyp != protowire.StartGroupType { + return out, ValidationUnknown + } + out, st := xi.validation.mi.validate(b, num, opts) + return out, st + default: + return out, ValidationUnknown + } +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/encode.go b/vendor/google.golang.org/protobuf/internal/impl/encode.go new file mode 100644 index 00000000000..8c8a794c631 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/encode.go @@ -0,0 +1,199 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "math" + "sort" + "sync/atomic" + + "google.golang.org/protobuf/internal/flags" + proto "google.golang.org/protobuf/proto" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +type marshalOptions struct { + flags piface.MarshalInputFlags +} + +func (o marshalOptions) Options() proto.MarshalOptions { + return proto.MarshalOptions{ + AllowPartial: true, + Deterministic: o.Deterministic(), + UseCachedSize: o.UseCachedSize(), + } +} + +func (o marshalOptions) Deterministic() bool { return o.flags&piface.MarshalDeterministic != 0 } +func (o marshalOptions) UseCachedSize() bool { return o.flags&piface.MarshalUseCachedSize != 0 } + +// size is protoreflect.Methods.Size. +func (mi *MessageInfo) size(in piface.SizeInput) piface.SizeOutput { + var p pointer + if ms, ok := in.Message.(*messageState); ok { + p = ms.pointer() + } else { + p = in.Message.(*messageReflectWrapper).pointer() + } + size := mi.sizePointer(p, marshalOptions{ + flags: in.Flags, + }) + return piface.SizeOutput{Size: size} +} + +func (mi *MessageInfo) sizePointer(p pointer, opts marshalOptions) (size int) { + mi.init() + if p.IsNil() { + return 0 + } + if opts.UseCachedSize() && mi.sizecacheOffset.IsValid() { + if size := atomic.LoadInt32(p.Apply(mi.sizecacheOffset).Int32()); size >= 0 { + return int(size) + } + } + return mi.sizePointerSlow(p, opts) +} + +func (mi *MessageInfo) sizePointerSlow(p pointer, opts marshalOptions) (size int) { + if flags.ProtoLegacy && mi.isMessageSet { + size = sizeMessageSet(mi, p, opts) + if mi.sizecacheOffset.IsValid() { + atomic.StoreInt32(p.Apply(mi.sizecacheOffset).Int32(), int32(size)) + } + return size + } + if mi.extensionOffset.IsValid() { + e := p.Apply(mi.extensionOffset).Extensions() + size += mi.sizeExtensions(e, opts) + } + for _, f := range mi.orderedCoderFields { + if f.funcs.size == nil { + continue + } + fptr := p.Apply(f.offset) + if f.isPointer && fptr.Elem().IsNil() { + continue + } + size += f.funcs.size(fptr, f, opts) + } + if mi.unknownOffset.IsValid() { + u := *p.Apply(mi.unknownOffset).Bytes() + size += len(u) + } + if mi.sizecacheOffset.IsValid() { + if size > math.MaxInt32 { + // The size is too large for the int32 sizecache field. + // We will need to recompute the size when encoding; + // unfortunately expensive, but better than invalid output. + atomic.StoreInt32(p.Apply(mi.sizecacheOffset).Int32(), -1) + } else { + atomic.StoreInt32(p.Apply(mi.sizecacheOffset).Int32(), int32(size)) + } + } + return size +} + +// marshal is protoreflect.Methods.Marshal. +func (mi *MessageInfo) marshal(in piface.MarshalInput) (out piface.MarshalOutput, err error) { + var p pointer + if ms, ok := in.Message.(*messageState); ok { + p = ms.pointer() + } else { + p = in.Message.(*messageReflectWrapper).pointer() + } + b, err := mi.marshalAppendPointer(in.Buf, p, marshalOptions{ + flags: in.Flags, + }) + return piface.MarshalOutput{Buf: b}, err +} + +func (mi *MessageInfo) marshalAppendPointer(b []byte, p pointer, opts marshalOptions) ([]byte, error) { + mi.init() + if p.IsNil() { + return b, nil + } + if flags.ProtoLegacy && mi.isMessageSet { + return marshalMessageSet(mi, b, p, opts) + } + var err error + // The old marshaler encodes extensions at beginning. + if mi.extensionOffset.IsValid() { + e := p.Apply(mi.extensionOffset).Extensions() + // TODO: Special handling for MessageSet? + b, err = mi.appendExtensions(b, e, opts) + if err != nil { + return b, err + } + } + for _, f := range mi.orderedCoderFields { + if f.funcs.marshal == nil { + continue + } + fptr := p.Apply(f.offset) + if f.isPointer && fptr.Elem().IsNil() { + continue + } + b, err = f.funcs.marshal(b, fptr, f, opts) + if err != nil { + return b, err + } + } + if mi.unknownOffset.IsValid() && !mi.isMessageSet { + u := *p.Apply(mi.unknownOffset).Bytes() + b = append(b, u...) + } + return b, nil +} + +func (mi *MessageInfo) sizeExtensions(ext *map[int32]ExtensionField, opts marshalOptions) (n int) { + if ext == nil { + return 0 + } + for _, x := range *ext { + xi := getExtensionFieldInfo(x.Type()) + if xi.funcs.size == nil { + continue + } + n += xi.funcs.size(x.Value(), xi.tagsize, opts) + } + return n +} + +func (mi *MessageInfo) appendExtensions(b []byte, ext *map[int32]ExtensionField, opts marshalOptions) ([]byte, error) { + if ext == nil { + return b, nil + } + + switch len(*ext) { + case 0: + return b, nil + case 1: + // Fast-path for one extension: Don't bother sorting the keys. + var err error + for _, x := range *ext { + xi := getExtensionFieldInfo(x.Type()) + b, err = xi.funcs.marshal(b, x.Value(), xi.wiretag, opts) + } + return b, err + default: + // Sort the keys to provide a deterministic encoding. + // Not sure this is required, but the old code does it. + keys := make([]int, 0, len(*ext)) + for k := range *ext { + keys = append(keys, int(k)) + } + sort.Ints(keys) + var err error + for _, k := range keys { + x := (*ext)[int32(k)] + xi := getExtensionFieldInfo(x.Type()) + b, err = xi.funcs.marshal(b, x.Value(), xi.wiretag, opts) + if err != nil { + return b, err + } + } + return b, nil + } +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/enum.go b/vendor/google.golang.org/protobuf/internal/impl/enum.go new file mode 100644 index 00000000000..8c1eab4bfd8 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/enum.go @@ -0,0 +1,21 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "reflect" + + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +type EnumInfo struct { + GoReflectType reflect.Type // int32 kind + Desc pref.EnumDescriptor +} + +func (t *EnumInfo) New(n pref.EnumNumber) pref.Enum { + return reflect.ValueOf(n).Convert(t.GoReflectType).Interface().(pref.Enum) +} +func (t *EnumInfo) Descriptor() pref.EnumDescriptor { return t.Desc } diff --git a/vendor/google.golang.org/protobuf/internal/impl/extension.go b/vendor/google.golang.org/protobuf/internal/impl/extension.go new file mode 100644 index 00000000000..e904fd99365 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/extension.go @@ -0,0 +1,156 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "reflect" + "sync" + "sync/atomic" + + pref "google.golang.org/protobuf/reflect/protoreflect" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +// ExtensionInfo implements ExtensionType. +// +// This type contains a number of exported fields for legacy compatibility. +// The only non-deprecated use of this type is through the methods of the +// ExtensionType interface. +type ExtensionInfo struct { + // An ExtensionInfo may exist in several stages of initialization. + // + // extensionInfoUninitialized: Some or all of the legacy exported + // fields may be set, but none of the unexported fields have been + // initialized. This is the starting state for an ExtensionInfo + // in legacy generated code. + // + // extensionInfoDescInit: The desc field is set, but other unexported fields + // may not be initialized. Legacy exported fields may or may not be set. + // This is the starting state for an ExtensionInfo in newly generated code. + // + // extensionInfoFullInit: The ExtensionInfo is fully initialized. + // This state is only entered after lazy initialization is complete. + init uint32 + mu sync.Mutex + + goType reflect.Type + desc extensionTypeDescriptor + conv Converter + info *extensionFieldInfo // for fast-path method implementations + + // ExtendedType is a typed nil-pointer to the parent message type that + // is being extended. It is possible for this to be unpopulated in v2 + // since the message may no longer implement the MessageV1 interface. + // + // Deprecated: Use the ExtendedType method instead. + ExtendedType piface.MessageV1 + + // ExtensionType is the zero value of the extension type. + // + // For historical reasons, reflect.TypeOf(ExtensionType) and the + // type returned by InterfaceOf may not be identical. + // + // Deprecated: Use InterfaceOf(xt.Zero()) instead. + ExtensionType interface{} + + // Field is the field number of the extension. + // + // Deprecated: Use the Descriptor().Number method instead. + Field int32 + + // Name is the fully qualified name of extension. + // + // Deprecated: Use the Descriptor().FullName method instead. + Name string + + // Tag is the protobuf struct tag used in the v1 API. + // + // Deprecated: Do not use. + Tag string + + // Filename is the proto filename in which the extension is defined. + // + // Deprecated: Use Descriptor().ParentFile().Path() instead. + Filename string +} + +// Stages of initialization: See the ExtensionInfo.init field. +const ( + extensionInfoUninitialized = 0 + extensionInfoDescInit = 1 + extensionInfoFullInit = 2 +) + +func InitExtensionInfo(xi *ExtensionInfo, xd pref.ExtensionDescriptor, goType reflect.Type) { + xi.goType = goType + xi.desc = extensionTypeDescriptor{xd, xi} + xi.init = extensionInfoDescInit +} + +func (xi *ExtensionInfo) New() pref.Value { + return xi.lazyInit().New() +} +func (xi *ExtensionInfo) Zero() pref.Value { + return xi.lazyInit().Zero() +} +func (xi *ExtensionInfo) ValueOf(v interface{}) pref.Value { + return xi.lazyInit().PBValueOf(reflect.ValueOf(v)) +} +func (xi *ExtensionInfo) InterfaceOf(v pref.Value) interface{} { + return xi.lazyInit().GoValueOf(v).Interface() +} +func (xi *ExtensionInfo) IsValidValue(v pref.Value) bool { + return xi.lazyInit().IsValidPB(v) +} +func (xi *ExtensionInfo) IsValidInterface(v interface{}) bool { + return xi.lazyInit().IsValidGo(reflect.ValueOf(v)) +} +func (xi *ExtensionInfo) TypeDescriptor() pref.ExtensionTypeDescriptor { + if atomic.LoadUint32(&xi.init) < extensionInfoDescInit { + xi.lazyInitSlow() + } + return &xi.desc +} + +func (xi *ExtensionInfo) lazyInit() Converter { + if atomic.LoadUint32(&xi.init) < extensionInfoFullInit { + xi.lazyInitSlow() + } + return xi.conv +} + +func (xi *ExtensionInfo) lazyInitSlow() { + xi.mu.Lock() + defer xi.mu.Unlock() + + if xi.init == extensionInfoFullInit { + return + } + defer atomic.StoreUint32(&xi.init, extensionInfoFullInit) + + if xi.desc.ExtensionDescriptor == nil { + xi.initFromLegacy() + } + if !xi.desc.ExtensionDescriptor.IsPlaceholder() { + if xi.ExtensionType == nil { + xi.initToLegacy() + } + xi.conv = NewConverter(xi.goType, xi.desc.ExtensionDescriptor) + xi.info = makeExtensionFieldInfo(xi.desc.ExtensionDescriptor) + xi.info.validation = newValidationInfo(xi.desc.ExtensionDescriptor, xi.goType) + } +} + +type extensionTypeDescriptor struct { + pref.ExtensionDescriptor + xi *ExtensionInfo +} + +func (xtd *extensionTypeDescriptor) Type() pref.ExtensionType { + return xtd.xi +} +func (xtd *extensionTypeDescriptor) Descriptor() pref.ExtensionDescriptor { + return xtd.ExtensionDescriptor +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go b/vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go new file mode 100644 index 00000000000..f7d7ffb5103 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go @@ -0,0 +1,219 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + "strings" + "sync" + + "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/reflect/protoreflect" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +// legacyEnumName returns the name of enums used in legacy code. +// It is neither the protobuf full name nor the qualified Go name, +// but rather an odd hybrid of both. +func legacyEnumName(ed pref.EnumDescriptor) string { + var protoPkg string + enumName := string(ed.FullName()) + if fd := ed.ParentFile(); fd != nil { + protoPkg = string(fd.Package()) + enumName = strings.TrimPrefix(enumName, protoPkg+".") + } + if protoPkg == "" { + return strs.GoCamelCase(enumName) + } + return protoPkg + "." + strs.GoCamelCase(enumName) +} + +// legacyWrapEnum wraps v as a protoreflect.Enum, +// where v must be a int32 kind and not implement the v2 API already. +func legacyWrapEnum(v reflect.Value) pref.Enum { + et := legacyLoadEnumType(v.Type()) + return et.New(pref.EnumNumber(v.Int())) +} + +var legacyEnumTypeCache sync.Map // map[reflect.Type]protoreflect.EnumType + +// legacyLoadEnumType dynamically loads a protoreflect.EnumType for t, +// where t must be an int32 kind and not implement the v2 API already. +func legacyLoadEnumType(t reflect.Type) pref.EnumType { + // Fast-path: check if a EnumType is cached for this concrete type. + if et, ok := legacyEnumTypeCache.Load(t); ok { + return et.(pref.EnumType) + } + + // Slow-path: derive enum descriptor and initialize EnumType. + var et pref.EnumType + ed := LegacyLoadEnumDesc(t) + et = &legacyEnumType{ + desc: ed, + goType: t, + } + if et, ok := legacyEnumTypeCache.LoadOrStore(t, et); ok { + return et.(pref.EnumType) + } + return et +} + +type legacyEnumType struct { + desc pref.EnumDescriptor + goType reflect.Type + m sync.Map // map[protoreflect.EnumNumber]proto.Enum +} + +func (t *legacyEnumType) New(n pref.EnumNumber) pref.Enum { + if e, ok := t.m.Load(n); ok { + return e.(pref.Enum) + } + e := &legacyEnumWrapper{num: n, pbTyp: t, goTyp: t.goType} + t.m.Store(n, e) + return e +} +func (t *legacyEnumType) Descriptor() pref.EnumDescriptor { + return t.desc +} + +type legacyEnumWrapper struct { + num pref.EnumNumber + pbTyp pref.EnumType + goTyp reflect.Type +} + +func (e *legacyEnumWrapper) Descriptor() pref.EnumDescriptor { + return e.pbTyp.Descriptor() +} +func (e *legacyEnumWrapper) Type() pref.EnumType { + return e.pbTyp +} +func (e *legacyEnumWrapper) Number() pref.EnumNumber { + return e.num +} +func (e *legacyEnumWrapper) ProtoReflect() pref.Enum { + return e +} +func (e *legacyEnumWrapper) protoUnwrap() interface{} { + v := reflect.New(e.goTyp).Elem() + v.SetInt(int64(e.num)) + return v.Interface() +} + +var ( + _ pref.Enum = (*legacyEnumWrapper)(nil) + _ unwrapper = (*legacyEnumWrapper)(nil) +) + +var legacyEnumDescCache sync.Map // map[reflect.Type]protoreflect.EnumDescriptor + +// LegacyLoadEnumDesc returns an EnumDescriptor derived from the Go type, +// which must be an int32 kind and not implement the v2 API already. +// +// This is exported for testing purposes. +func LegacyLoadEnumDesc(t reflect.Type) pref.EnumDescriptor { + // Fast-path: check if an EnumDescriptor is cached for this concrete type. + if ed, ok := legacyEnumDescCache.Load(t); ok { + return ed.(pref.EnumDescriptor) + } + + // Slow-path: initialize EnumDescriptor from the raw descriptor. + ev := reflect.Zero(t).Interface() + if _, ok := ev.(pref.Enum); ok { + panic(fmt.Sprintf("%v already implements proto.Enum", t)) + } + edV1, ok := ev.(enumV1) + if !ok { + return aberrantLoadEnumDesc(t) + } + b, idxs := edV1.EnumDescriptor() + + var ed pref.EnumDescriptor + if len(idxs) == 1 { + ed = legacyLoadFileDesc(b).Enums().Get(idxs[0]) + } else { + md := legacyLoadFileDesc(b).Messages().Get(idxs[0]) + for _, i := range idxs[1 : len(idxs)-1] { + md = md.Messages().Get(i) + } + ed = md.Enums().Get(idxs[len(idxs)-1]) + } + if ed, ok := legacyEnumDescCache.LoadOrStore(t, ed); ok { + return ed.(protoreflect.EnumDescriptor) + } + return ed +} + +var aberrantEnumDescCache sync.Map // map[reflect.Type]protoreflect.EnumDescriptor + +// aberrantLoadEnumDesc returns an EnumDescriptor derived from the Go type, +// which must not implement protoreflect.Enum or enumV1. +// +// If the type does not implement enumV1, then there is no reliable +// way to derive the original protobuf type information. +// We are unable to use the global enum registry since it is +// unfortunately keyed by the protobuf full name, which we also do not know. +// Thus, this produces some bogus enum descriptor based on the Go type name. +func aberrantLoadEnumDesc(t reflect.Type) pref.EnumDescriptor { + // Fast-path: check if an EnumDescriptor is cached for this concrete type. + if ed, ok := aberrantEnumDescCache.Load(t); ok { + return ed.(pref.EnumDescriptor) + } + + // Slow-path: construct a bogus, but unique EnumDescriptor. + ed := &filedesc.Enum{L2: new(filedesc.EnumL2)} + ed.L0.FullName = AberrantDeriveFullName(t) // e.g., github_com.user.repo.MyEnum + ed.L0.ParentFile = filedesc.SurrogateProto3 + ed.L2.Values.List = append(ed.L2.Values.List, filedesc.EnumValue{}) + + // TODO: Use the presence of a UnmarshalJSON method to determine proto2? + + vd := &ed.L2.Values.List[0] + vd.L0.FullName = ed.L0.FullName + "_UNKNOWN" // e.g., github_com.user.repo.MyEnum_UNKNOWN + vd.L0.ParentFile = ed.L0.ParentFile + vd.L0.Parent = ed + + // TODO: We could use the String method to obtain some enum value names by + // starting at 0 and print the enum until it produces invalid identifiers. + // An exhaustive query is clearly impractical, but can be best-effort. + + if ed, ok := aberrantEnumDescCache.LoadOrStore(t, ed); ok { + return ed.(pref.EnumDescriptor) + } + return ed +} + +// AberrantDeriveFullName derives a fully qualified protobuf name for the given Go type +// The provided name is not guaranteed to be stable nor universally unique. +// It should be sufficiently unique within a program. +// +// This is exported for testing purposes. +func AberrantDeriveFullName(t reflect.Type) pref.FullName { + sanitize := func(r rune) rune { + switch { + case r == '/': + return '.' + case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z', '0' <= r && r <= '9': + return r + default: + return '_' + } + } + prefix := strings.Map(sanitize, t.PkgPath()) + suffix := strings.Map(sanitize, t.Name()) + if suffix == "" { + suffix = fmt.Sprintf("UnknownX%X", reflect.ValueOf(t).Pointer()) + } + + ss := append(strings.Split(prefix, "."), suffix) + for i, s := range ss { + if s == "" || ('0' <= s[0] && s[0] <= '9') { + ss[i] = "x" + s + } + } + return pref.FullName(strings.Join(ss, ".")) +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/legacy_export.go b/vendor/google.golang.org/protobuf/internal/impl/legacy_export.go new file mode 100644 index 00000000000..c3d741c2f0c --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/legacy_export.go @@ -0,0 +1,92 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "encoding/binary" + "encoding/json" + "hash/crc32" + "math" + "reflect" + + "google.golang.org/protobuf/internal/errors" + pref "google.golang.org/protobuf/reflect/protoreflect" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +// These functions exist to support exported APIs in generated protobufs. +// While these are deprecated, they cannot be removed for compatibility reasons. + +// LegacyEnumName returns the name of enums used in legacy code. +func (Export) LegacyEnumName(ed pref.EnumDescriptor) string { + return legacyEnumName(ed) +} + +// LegacyMessageTypeOf returns the protoreflect.MessageType for m, +// with name used as the message name if necessary. +func (Export) LegacyMessageTypeOf(m piface.MessageV1, name pref.FullName) pref.MessageType { + if mv := (Export{}).protoMessageV2Of(m); mv != nil { + return mv.ProtoReflect().Type() + } + return legacyLoadMessageInfo(reflect.TypeOf(m), name) +} + +// UnmarshalJSONEnum unmarshals an enum from a JSON-encoded input. +// The input can either be a string representing the enum value by name, +// or a number representing the enum number itself. +func (Export) UnmarshalJSONEnum(ed pref.EnumDescriptor, b []byte) (pref.EnumNumber, error) { + if b[0] == '"' { + var name pref.Name + if err := json.Unmarshal(b, &name); err != nil { + return 0, errors.New("invalid input for enum %v: %s", ed.FullName(), b) + } + ev := ed.Values().ByName(name) + if ev == nil { + return 0, errors.New("invalid value for enum %v: %s", ed.FullName(), name) + } + return ev.Number(), nil + } else { + var num pref.EnumNumber + if err := json.Unmarshal(b, &num); err != nil { + return 0, errors.New("invalid input for enum %v: %s", ed.FullName(), b) + } + return num, nil + } +} + +// CompressGZIP compresses the input as a GZIP-encoded file. +// The current implementation does no compression. +func (Export) CompressGZIP(in []byte) (out []byte) { + // RFC 1952, section 2.3.1. + var gzipHeader = [10]byte{0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff} + + // RFC 1951, section 3.2.4. + var blockHeader [5]byte + const maxBlockSize = math.MaxUint16 + numBlocks := 1 + len(in)/maxBlockSize + + // RFC 1952, section 2.3.1. + var gzipFooter [8]byte + binary.LittleEndian.PutUint32(gzipFooter[0:4], crc32.ChecksumIEEE(in)) + binary.LittleEndian.PutUint32(gzipFooter[4:8], uint32(len(in))) + + // Encode the input without compression using raw DEFLATE blocks. + out = make([]byte, 0, len(gzipHeader)+len(blockHeader)*numBlocks+len(in)+len(gzipFooter)) + out = append(out, gzipHeader[:]...) + for blockHeader[0] == 0 { + blockSize := maxBlockSize + if blockSize > len(in) { + blockHeader[0] = 0x01 // final bit per RFC 1951, section 3.2.3. + blockSize = len(in) + } + binary.LittleEndian.PutUint16(blockHeader[1:3], uint16(blockSize)^0x0000) + binary.LittleEndian.PutUint16(blockHeader[3:5], uint16(blockSize)^0xffff) + out = append(out, blockHeader[:]...) + out = append(out, in[:blockSize]...) + in = in[blockSize:] + } + out = append(out, gzipFooter[:]...) + return out +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/legacy_extension.go b/vendor/google.golang.org/protobuf/internal/impl/legacy_extension.go new file mode 100644 index 00000000000..61757ce50a7 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/legacy_extension.go @@ -0,0 +1,175 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "reflect" + + "google.golang.org/protobuf/internal/descopts" + "google.golang.org/protobuf/internal/encoding/messageset" + ptag "google.golang.org/protobuf/internal/encoding/tag" + "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/internal/pragma" + pref "google.golang.org/protobuf/reflect/protoreflect" + preg "google.golang.org/protobuf/reflect/protoregistry" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +func (xi *ExtensionInfo) initToLegacy() { + xd := xi.desc + var parent piface.MessageV1 + messageName := xd.ContainingMessage().FullName() + if mt, _ := preg.GlobalTypes.FindMessageByName(messageName); mt != nil { + // Create a new parent message and unwrap it if possible. + mv := mt.New().Interface() + t := reflect.TypeOf(mv) + if mv, ok := mv.(unwrapper); ok { + t = reflect.TypeOf(mv.protoUnwrap()) + } + + // Check whether the message implements the legacy v1 Message interface. + mz := reflect.Zero(t).Interface() + if mz, ok := mz.(piface.MessageV1); ok { + parent = mz + } + } + + // Determine the v1 extension type, which is unfortunately not the same as + // the v2 ExtensionType.GoType. + extType := xi.goType + switch extType.Kind() { + case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: + extType = reflect.PtrTo(extType) // T -> *T for singular scalar fields + } + + // Reconstruct the legacy enum full name. + var enumName string + if xd.Kind() == pref.EnumKind { + enumName = legacyEnumName(xd.Enum()) + } + + // Derive the proto file that the extension was declared within. + var filename string + if fd := xd.ParentFile(); fd != nil { + filename = fd.Path() + } + + // For MessageSet extensions, the name used is the parent message. + name := xd.FullName() + if messageset.IsMessageSetExtension(xd) { + name = name.Parent() + } + + xi.ExtendedType = parent + xi.ExtensionType = reflect.Zero(extType).Interface() + xi.Field = int32(xd.Number()) + xi.Name = string(name) + xi.Tag = ptag.Marshal(xd, enumName) + xi.Filename = filename +} + +// initFromLegacy initializes an ExtensionInfo from +// the contents of the deprecated exported fields of the type. +func (xi *ExtensionInfo) initFromLegacy() { + // The v1 API returns "type incomplete" descriptors where only the + // field number is specified. In such a case, use a placeholder. + if xi.ExtendedType == nil || xi.ExtensionType == nil { + xd := placeholderExtension{ + name: pref.FullName(xi.Name), + number: pref.FieldNumber(xi.Field), + } + xi.desc = extensionTypeDescriptor{xd, xi} + return + } + + // Resolve enum or message dependencies. + var ed pref.EnumDescriptor + var md pref.MessageDescriptor + t := reflect.TypeOf(xi.ExtensionType) + isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct + isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 + if isOptional || isRepeated { + t = t.Elem() + } + switch v := reflect.Zero(t).Interface().(type) { + case pref.Enum: + ed = v.Descriptor() + case enumV1: + ed = LegacyLoadEnumDesc(t) + case pref.ProtoMessage: + md = v.ProtoReflect().Descriptor() + case messageV1: + md = LegacyLoadMessageDesc(t) + } + + // Derive basic field information from the struct tag. + var evs pref.EnumValueDescriptors + if ed != nil { + evs = ed.Values() + } + fd := ptag.Unmarshal(xi.Tag, t, evs).(*filedesc.Field) + + // Construct a v2 ExtensionType. + xd := &filedesc.Extension{L2: new(filedesc.ExtensionL2)} + xd.L0.ParentFile = filedesc.SurrogateProto2 + xd.L0.FullName = pref.FullName(xi.Name) + xd.L1.Number = pref.FieldNumber(xi.Field) + xd.L1.Cardinality = fd.L1.Cardinality + xd.L1.Kind = fd.L1.Kind + xd.L2.IsPacked = fd.L1.IsPacked + xd.L2.Default = fd.L1.Default + xd.L1.Extendee = Export{}.MessageDescriptorOf(xi.ExtendedType) + xd.L2.Enum = ed + xd.L2.Message = md + + // Derive real extension field name for MessageSets. + if messageset.IsMessageSet(xd.L1.Extendee) && md.FullName() == xd.L0.FullName { + xd.L0.FullName = xd.L0.FullName.Append(messageset.ExtensionName) + } + + tt := reflect.TypeOf(xi.ExtensionType) + if isOptional { + tt = tt.Elem() + } + xi.goType = tt + xi.desc = extensionTypeDescriptor{xd, xi} +} + +type placeholderExtension struct { + name pref.FullName + number pref.FieldNumber +} + +func (x placeholderExtension) ParentFile() pref.FileDescriptor { return nil } +func (x placeholderExtension) Parent() pref.Descriptor { return nil } +func (x placeholderExtension) Index() int { return 0 } +func (x placeholderExtension) Syntax() pref.Syntax { return 0 } +func (x placeholderExtension) Name() pref.Name { return x.name.Name() } +func (x placeholderExtension) FullName() pref.FullName { return x.name } +func (x placeholderExtension) IsPlaceholder() bool { return true } +func (x placeholderExtension) Options() pref.ProtoMessage { return descopts.Field } +func (x placeholderExtension) Number() pref.FieldNumber { return x.number } +func (x placeholderExtension) Cardinality() pref.Cardinality { return 0 } +func (x placeholderExtension) Kind() pref.Kind { return 0 } +func (x placeholderExtension) HasJSONName() bool { return false } +func (x placeholderExtension) JSONName() string { return "" } +func (x placeholderExtension) HasPresence() bool { return false } +func (x placeholderExtension) HasOptionalKeyword() bool { return false } +func (x placeholderExtension) IsExtension() bool { return true } +func (x placeholderExtension) IsWeak() bool { return false } +func (x placeholderExtension) IsPacked() bool { return false } +func (x placeholderExtension) IsList() bool { return false } +func (x placeholderExtension) IsMap() bool { return false } +func (x placeholderExtension) MapKey() pref.FieldDescriptor { return nil } +func (x placeholderExtension) MapValue() pref.FieldDescriptor { return nil } +func (x placeholderExtension) HasDefault() bool { return false } +func (x placeholderExtension) Default() pref.Value { return pref.Value{} } +func (x placeholderExtension) DefaultEnumValue() pref.EnumValueDescriptor { return nil } +func (x placeholderExtension) ContainingOneof() pref.OneofDescriptor { return nil } +func (x placeholderExtension) ContainingMessage() pref.MessageDescriptor { return nil } +func (x placeholderExtension) Enum() pref.EnumDescriptor { return nil } +func (x placeholderExtension) Message() pref.MessageDescriptor { return nil } +func (x placeholderExtension) ProtoType(pref.FieldDescriptor) { return } +func (x placeholderExtension) ProtoInternal(pragma.DoNotImplement) { return } diff --git a/vendor/google.golang.org/protobuf/internal/impl/legacy_file.go b/vendor/google.golang.org/protobuf/internal/impl/legacy_file.go new file mode 100644 index 00000000000..9ab091086c9 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/legacy_file.go @@ -0,0 +1,81 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "bytes" + "compress/gzip" + "io/ioutil" + "sync" + + "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +// Every enum and message type generated by protoc-gen-go since commit 2fc053c5 +// on February 25th, 2016 has had a method to get the raw descriptor. +// Types that were not generated by protoc-gen-go or were generated prior +// to that version are not supported. +// +// The []byte returned is the encoded form of a FileDescriptorProto message +// compressed using GZIP. The []int is the path from the top-level file +// to the specific message or enum declaration. +type ( + enumV1 interface { + EnumDescriptor() ([]byte, []int) + } + messageV1 interface { + Descriptor() ([]byte, []int) + } +) + +var legacyFileDescCache sync.Map // map[*byte]protoreflect.FileDescriptor + +// legacyLoadFileDesc unmarshals b as a compressed FileDescriptorProto message. +// +// This assumes that b is immutable and that b does not refer to part of a +// concatenated series of GZIP files (which would require shenanigans that +// rely on the concatenation properties of both protobufs and GZIP). +// File descriptors generated by protoc-gen-go do not rely on that property. +func legacyLoadFileDesc(b []byte) protoreflect.FileDescriptor { + // Fast-path: check whether we already have a cached file descriptor. + if fd, ok := legacyFileDescCache.Load(&b[0]); ok { + return fd.(protoreflect.FileDescriptor) + } + + // Slow-path: decompress and unmarshal the file descriptor proto. + zr, err := gzip.NewReader(bytes.NewReader(b)) + if err != nil { + panic(err) + } + b2, err := ioutil.ReadAll(zr) + if err != nil { + panic(err) + } + + fd := filedesc.Builder{ + RawDescriptor: b2, + FileRegistry: resolverOnly{protoregistry.GlobalFiles}, // do not register back to global registry + }.Build().File + if fd, ok := legacyFileDescCache.LoadOrStore(&b[0], fd); ok { + return fd.(protoreflect.FileDescriptor) + } + return fd +} + +type resolverOnly struct { + reg *protoregistry.Files +} + +func (r resolverOnly) FindFileByPath(path string) (protoreflect.FileDescriptor, error) { + return r.reg.FindFileByPath(path) +} +func (r resolverOnly) FindDescriptorByName(name protoreflect.FullName) (protoreflect.Descriptor, error) { + return r.reg.FindDescriptorByName(name) +} +func (resolverOnly) RegisterFile(protoreflect.FileDescriptor) error { + return nil +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/legacy_message.go b/vendor/google.golang.org/protobuf/internal/impl/legacy_message.go new file mode 100644 index 00000000000..06c68e11702 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/legacy_message.go @@ -0,0 +1,502 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + "strings" + "sync" + + "google.golang.org/protobuf/internal/descopts" + ptag "google.golang.org/protobuf/internal/encoding/tag" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/reflect/protoreflect" + pref "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoiface" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +// legacyWrapMessage wraps v as a protoreflect.Message, +// where v must be a *struct kind and not implement the v2 API already. +func legacyWrapMessage(v reflect.Value) pref.Message { + typ := v.Type() + if typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct { + return aberrantMessage{v: v} + } + mt := legacyLoadMessageInfo(typ, "") + return mt.MessageOf(v.Interface()) +} + +var legacyMessageTypeCache sync.Map // map[reflect.Type]*MessageInfo + +// legacyLoadMessageInfo dynamically loads a *MessageInfo for t, +// where t must be a *struct kind and not implement the v2 API already. +// The provided name is used if it cannot be determined from the message. +func legacyLoadMessageInfo(t reflect.Type, name pref.FullName) *MessageInfo { + // Fast-path: check if a MessageInfo is cached for this concrete type. + if mt, ok := legacyMessageTypeCache.Load(t); ok { + return mt.(*MessageInfo) + } + + // Slow-path: derive message descriptor and initialize MessageInfo. + mi := &MessageInfo{ + Desc: legacyLoadMessageDesc(t, name), + GoReflectType: t, + } + + v := reflect.Zero(t).Interface() + if _, ok := v.(legacyMarshaler); ok { + mi.methods.Marshal = legacyMarshal + + // We have no way to tell whether the type's Marshal method + // supports deterministic serialization or not, but this + // preserves the v1 implementation's behavior of always + // calling Marshal methods when present. + mi.methods.Flags |= piface.SupportMarshalDeterministic + } + if _, ok := v.(legacyUnmarshaler); ok { + mi.methods.Unmarshal = legacyUnmarshal + } + if _, ok := v.(legacyMerger); ok { + mi.methods.Merge = legacyMerge + } + + if mi, ok := legacyMessageTypeCache.LoadOrStore(t, mi); ok { + return mi.(*MessageInfo) + } + return mi +} + +var legacyMessageDescCache sync.Map // map[reflect.Type]protoreflect.MessageDescriptor + +// LegacyLoadMessageDesc returns an MessageDescriptor derived from the Go type, +// which must be a *struct kind and not implement the v2 API already. +// +// This is exported for testing purposes. +func LegacyLoadMessageDesc(t reflect.Type) pref.MessageDescriptor { + return legacyLoadMessageDesc(t, "") +} +func legacyLoadMessageDesc(t reflect.Type, name pref.FullName) pref.MessageDescriptor { + // Fast-path: check if a MessageDescriptor is cached for this concrete type. + if mi, ok := legacyMessageDescCache.Load(t); ok { + return mi.(pref.MessageDescriptor) + } + + // Slow-path: initialize MessageDescriptor from the raw descriptor. + mv := reflect.Zero(t).Interface() + if _, ok := mv.(pref.ProtoMessage); ok { + panic(fmt.Sprintf("%v already implements proto.Message", t)) + } + mdV1, ok := mv.(messageV1) + if !ok { + return aberrantLoadMessageDesc(t, name) + } + + // If this is a dynamic message type where there isn't a 1-1 mapping between + // Go and protobuf types, calling the Descriptor method on the zero value of + // the message type isn't likely to work. If it panics, swallow the panic and + // continue as if the Descriptor method wasn't present. + b, idxs := func() ([]byte, []int) { + defer func() { + recover() + }() + return mdV1.Descriptor() + }() + if b == nil { + return aberrantLoadMessageDesc(t, name) + } + + // If the Go type has no fields, then this might be a proto3 empty message + // from before the size cache was added. If there are any fields, check to + // see that at least one of them looks like something we generated. + if nfield := t.Elem().NumField(); nfield > 0 { + hasProtoField := false + for i := 0; i < nfield; i++ { + f := t.Elem().Field(i) + if f.Tag.Get("protobuf") != "" || f.Tag.Get("protobuf_oneof") != "" || strings.HasPrefix(f.Name, "XXX_") { + hasProtoField = true + break + } + } + if !hasProtoField { + return aberrantLoadMessageDesc(t, name) + } + } + + md := legacyLoadFileDesc(b).Messages().Get(idxs[0]) + for _, i := range idxs[1:] { + md = md.Messages().Get(i) + } + if name != "" && md.FullName() != name { + panic(fmt.Sprintf("mismatching message name: got %v, want %v", md.FullName(), name)) + } + if md, ok := legacyMessageDescCache.LoadOrStore(t, md); ok { + return md.(protoreflect.MessageDescriptor) + } + return md +} + +var ( + aberrantMessageDescLock sync.Mutex + aberrantMessageDescCache map[reflect.Type]protoreflect.MessageDescriptor +) + +// aberrantLoadMessageDesc returns an MessageDescriptor derived from the Go type, +// which must not implement protoreflect.ProtoMessage or messageV1. +// +// This is a best-effort derivation of the message descriptor using the protobuf +// tags on the struct fields. +func aberrantLoadMessageDesc(t reflect.Type, name pref.FullName) pref.MessageDescriptor { + aberrantMessageDescLock.Lock() + defer aberrantMessageDescLock.Unlock() + if aberrantMessageDescCache == nil { + aberrantMessageDescCache = make(map[reflect.Type]protoreflect.MessageDescriptor) + } + return aberrantLoadMessageDescReentrant(t, name) +} +func aberrantLoadMessageDescReentrant(t reflect.Type, name pref.FullName) pref.MessageDescriptor { + // Fast-path: check if an MessageDescriptor is cached for this concrete type. + if md, ok := aberrantMessageDescCache[t]; ok { + return md + } + + // Slow-path: construct a descriptor from the Go struct type (best-effort). + // Cache the MessageDescriptor early on so that we can resolve internal + // cyclic references. + md := &filedesc.Message{L2: new(filedesc.MessageL2)} + md.L0.FullName = aberrantDeriveMessageName(t, name) + md.L0.ParentFile = filedesc.SurrogateProto2 + aberrantMessageDescCache[t] = md + + if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct { + return md + } + + // Try to determine if the message is using proto3 by checking scalars. + for i := 0; i < t.Elem().NumField(); i++ { + f := t.Elem().Field(i) + if tag := f.Tag.Get("protobuf"); tag != "" { + switch f.Type.Kind() { + case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: + md.L0.ParentFile = filedesc.SurrogateProto3 + } + for _, s := range strings.Split(tag, ",") { + if s == "proto3" { + md.L0.ParentFile = filedesc.SurrogateProto3 + } + } + } + } + + // Obtain a list of oneof wrapper types. + var oneofWrappers []reflect.Type + for _, method := range []string{"XXX_OneofFuncs", "XXX_OneofWrappers"} { + if fn, ok := t.MethodByName(method); ok { + for _, v := range fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))}) { + if vs, ok := v.Interface().([]interface{}); ok { + for _, v := range vs { + oneofWrappers = append(oneofWrappers, reflect.TypeOf(v)) + } + } + } + } + } + + // Obtain a list of the extension ranges. + if fn, ok := t.MethodByName("ExtensionRangeArray"); ok { + vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0] + for i := 0; i < vs.Len(); i++ { + v := vs.Index(i) + md.L2.ExtensionRanges.List = append(md.L2.ExtensionRanges.List, [2]pref.FieldNumber{ + pref.FieldNumber(v.FieldByName("Start").Int()), + pref.FieldNumber(v.FieldByName("End").Int() + 1), + }) + md.L2.ExtensionRangeOptions = append(md.L2.ExtensionRangeOptions, nil) + } + } + + // Derive the message fields by inspecting the struct fields. + for i := 0; i < t.Elem().NumField(); i++ { + f := t.Elem().Field(i) + if tag := f.Tag.Get("protobuf"); tag != "" { + tagKey := f.Tag.Get("protobuf_key") + tagVal := f.Tag.Get("protobuf_val") + aberrantAppendField(md, f.Type, tag, tagKey, tagVal) + } + if tag := f.Tag.Get("protobuf_oneof"); tag != "" { + n := len(md.L2.Oneofs.List) + md.L2.Oneofs.List = append(md.L2.Oneofs.List, filedesc.Oneof{}) + od := &md.L2.Oneofs.List[n] + od.L0.FullName = md.FullName().Append(pref.Name(tag)) + od.L0.ParentFile = md.L0.ParentFile + od.L0.Parent = md + od.L0.Index = n + + for _, t := range oneofWrappers { + if t.Implements(f.Type) { + f := t.Elem().Field(0) + if tag := f.Tag.Get("protobuf"); tag != "" { + aberrantAppendField(md, f.Type, tag, "", "") + fd := &md.L2.Fields.List[len(md.L2.Fields.List)-1] + fd.L1.ContainingOneof = od + od.L1.Fields.List = append(od.L1.Fields.List, fd) + } + } + } + } + } + + return md +} + +func aberrantDeriveMessageName(t reflect.Type, name pref.FullName) pref.FullName { + if name.IsValid() { + return name + } + func() { + defer func() { recover() }() // swallow possible nil panics + if m, ok := reflect.Zero(t).Interface().(interface{ XXX_MessageName() string }); ok { + name = pref.FullName(m.XXX_MessageName()) + } + }() + if name.IsValid() { + return name + } + if t.Kind() == reflect.Ptr { + t = t.Elem() + } + return AberrantDeriveFullName(t) +} + +func aberrantAppendField(md *filedesc.Message, goType reflect.Type, tag, tagKey, tagVal string) { + t := goType + isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct + isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 + if isOptional || isRepeated { + t = t.Elem() + } + fd := ptag.Unmarshal(tag, t, placeholderEnumValues{}).(*filedesc.Field) + + // Append field descriptor to the message. + n := len(md.L2.Fields.List) + md.L2.Fields.List = append(md.L2.Fields.List, *fd) + fd = &md.L2.Fields.List[n] + fd.L0.FullName = md.FullName().Append(fd.Name()) + fd.L0.ParentFile = md.L0.ParentFile + fd.L0.Parent = md + fd.L0.Index = n + + if fd.L1.IsWeak || fd.L1.HasPacked { + fd.L1.Options = func() pref.ProtoMessage { + opts := descopts.Field.ProtoReflect().New() + if fd.L1.IsWeak { + opts.Set(opts.Descriptor().Fields().ByName("weak"), protoreflect.ValueOfBool(true)) + } + if fd.L1.HasPacked { + opts.Set(opts.Descriptor().Fields().ByName("packed"), protoreflect.ValueOfBool(fd.L1.IsPacked)) + } + return opts.Interface() + } + } + + // Populate Enum and Message. + if fd.Enum() == nil && fd.Kind() == pref.EnumKind { + switch v := reflect.Zero(t).Interface().(type) { + case pref.Enum: + fd.L1.Enum = v.Descriptor() + default: + fd.L1.Enum = LegacyLoadEnumDesc(t) + } + } + if fd.Message() == nil && (fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind) { + switch v := reflect.Zero(t).Interface().(type) { + case pref.ProtoMessage: + fd.L1.Message = v.ProtoReflect().Descriptor() + case messageV1: + fd.L1.Message = LegacyLoadMessageDesc(t) + default: + if t.Kind() == reflect.Map { + n := len(md.L1.Messages.List) + md.L1.Messages.List = append(md.L1.Messages.List, filedesc.Message{L2: new(filedesc.MessageL2)}) + md2 := &md.L1.Messages.List[n] + md2.L0.FullName = md.FullName().Append(pref.Name(strs.MapEntryName(string(fd.Name())))) + md2.L0.ParentFile = md.L0.ParentFile + md2.L0.Parent = md + md2.L0.Index = n + + md2.L1.IsMapEntry = true + md2.L2.Options = func() pref.ProtoMessage { + opts := descopts.Message.ProtoReflect().New() + opts.Set(opts.Descriptor().Fields().ByName("map_entry"), protoreflect.ValueOfBool(true)) + return opts.Interface() + } + + aberrantAppendField(md2, t.Key(), tagKey, "", "") + aberrantAppendField(md2, t.Elem(), tagVal, "", "") + + fd.L1.Message = md2 + break + } + fd.L1.Message = aberrantLoadMessageDescReentrant(t, "") + } + } +} + +type placeholderEnumValues struct { + protoreflect.EnumValueDescriptors +} + +func (placeholderEnumValues) ByNumber(n pref.EnumNumber) pref.EnumValueDescriptor { + return filedesc.PlaceholderEnumValue(pref.FullName(fmt.Sprintf("UNKNOWN_%d", n))) +} + +// legacyMarshaler is the proto.Marshaler interface superseded by protoiface.Methoder. +type legacyMarshaler interface { + Marshal() ([]byte, error) +} + +// legacyUnmarshaler is the proto.Unmarshaler interface superseded by protoiface.Methoder. +type legacyUnmarshaler interface { + Unmarshal([]byte) error +} + +// legacyMerger is the proto.Merger interface superseded by protoiface.Methoder. +type legacyMerger interface { + Merge(protoiface.MessageV1) +} + +var legacyProtoMethods = &piface.Methods{ + Marshal: legacyMarshal, + Unmarshal: legacyUnmarshal, + Merge: legacyMerge, + + // We have no way to tell whether the type's Marshal method + // supports deterministic serialization or not, but this + // preserves the v1 implementation's behavior of always + // calling Marshal methods when present. + Flags: piface.SupportMarshalDeterministic, +} + +func legacyMarshal(in piface.MarshalInput) (piface.MarshalOutput, error) { + v := in.Message.(unwrapper).protoUnwrap() + marshaler, ok := v.(legacyMarshaler) + if !ok { + return piface.MarshalOutput{}, errors.New("%T does not implement Marshal", v) + } + out, err := marshaler.Marshal() + if in.Buf != nil { + out = append(in.Buf, out...) + } + return piface.MarshalOutput{ + Buf: out, + }, err +} + +func legacyUnmarshal(in piface.UnmarshalInput) (piface.UnmarshalOutput, error) { + v := in.Message.(unwrapper).protoUnwrap() + unmarshaler, ok := v.(legacyUnmarshaler) + if !ok { + return piface.UnmarshalOutput{}, errors.New("%T does not implement Marshal", v) + } + return piface.UnmarshalOutput{}, unmarshaler.Unmarshal(in.Buf) +} + +func legacyMerge(in piface.MergeInput) piface.MergeOutput { + dstv := in.Destination.(unwrapper).protoUnwrap() + merger, ok := dstv.(legacyMerger) + if !ok { + return piface.MergeOutput{} + } + merger.Merge(Export{}.ProtoMessageV1Of(in.Source)) + return piface.MergeOutput{Flags: piface.MergeComplete} +} + +// aberrantMessageType implements MessageType for all types other than pointer-to-struct. +type aberrantMessageType struct { + t reflect.Type +} + +func (mt aberrantMessageType) New() pref.Message { + return aberrantMessage{reflect.Zero(mt.t)} +} +func (mt aberrantMessageType) Zero() pref.Message { + return aberrantMessage{reflect.Zero(mt.t)} +} +func (mt aberrantMessageType) GoType() reflect.Type { + return mt.t +} +func (mt aberrantMessageType) Descriptor() pref.MessageDescriptor { + return LegacyLoadMessageDesc(mt.t) +} + +// aberrantMessage implements Message for all types other than pointer-to-struct. +// +// When the underlying type implements legacyMarshaler or legacyUnmarshaler, +// the aberrant Message can be marshaled or unmarshaled. Otherwise, there is +// not much that can be done with values of this type. +type aberrantMessage struct { + v reflect.Value +} + +func (m aberrantMessage) ProtoReflect() pref.Message { + return m +} + +func (m aberrantMessage) Descriptor() pref.MessageDescriptor { + return LegacyLoadMessageDesc(m.v.Type()) +} +func (m aberrantMessage) Type() pref.MessageType { + return aberrantMessageType{m.v.Type()} +} +func (m aberrantMessage) New() pref.Message { + return aberrantMessage{reflect.Zero(m.v.Type())} +} +func (m aberrantMessage) Interface() pref.ProtoMessage { + return m +} +func (m aberrantMessage) Range(f func(pref.FieldDescriptor, pref.Value) bool) { +} +func (m aberrantMessage) Has(pref.FieldDescriptor) bool { + panic("invalid field descriptor") +} +func (m aberrantMessage) Clear(pref.FieldDescriptor) { + panic("invalid field descriptor") +} +func (m aberrantMessage) Get(pref.FieldDescriptor) pref.Value { + panic("invalid field descriptor") +} +func (m aberrantMessage) Set(pref.FieldDescriptor, pref.Value) { + panic("invalid field descriptor") +} +func (m aberrantMessage) Mutable(pref.FieldDescriptor) pref.Value { + panic("invalid field descriptor") +} +func (m aberrantMessage) NewField(pref.FieldDescriptor) pref.Value { + panic("invalid field descriptor") +} +func (m aberrantMessage) WhichOneof(pref.OneofDescriptor) pref.FieldDescriptor { + panic("invalid oneof descriptor") +} +func (m aberrantMessage) GetUnknown() pref.RawFields { + return nil +} +func (m aberrantMessage) SetUnknown(pref.RawFields) { + // SetUnknown discards its input on messages which don't support unknown field storage. +} +func (m aberrantMessage) IsValid() bool { + // An invalid message is a read-only, empty message. Since we don't know anything + // about the alleged contents of this message, we can't say with confidence that + // it is invalid in this sense. Therefore, report it as valid. + return true +} +func (m aberrantMessage) ProtoMethods() *piface.Methods { + return legacyProtoMethods +} +func (m aberrantMessage) protoUnwrap() interface{} { + return m.v.Interface() +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/merge.go b/vendor/google.golang.org/protobuf/internal/impl/merge.go new file mode 100644 index 00000000000..cdc4267dfad --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/merge.go @@ -0,0 +1,176 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + + "google.golang.org/protobuf/proto" + pref "google.golang.org/protobuf/reflect/protoreflect" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +type mergeOptions struct{} + +func (o mergeOptions) Merge(dst, src proto.Message) { + proto.Merge(dst, src) +} + +// merge is protoreflect.Methods.Merge. +func (mi *MessageInfo) merge(in piface.MergeInput) piface.MergeOutput { + dp, ok := mi.getPointer(in.Destination) + if !ok { + return piface.MergeOutput{} + } + sp, ok := mi.getPointer(in.Source) + if !ok { + return piface.MergeOutput{} + } + mi.mergePointer(dp, sp, mergeOptions{}) + return piface.MergeOutput{Flags: piface.MergeComplete} +} + +func (mi *MessageInfo) mergePointer(dst, src pointer, opts mergeOptions) { + mi.init() + if dst.IsNil() { + panic(fmt.Sprintf("invalid value: merging into nil message")) + } + if src.IsNil() { + return + } + for _, f := range mi.orderedCoderFields { + if f.funcs.merge == nil { + continue + } + sfptr := src.Apply(f.offset) + if f.isPointer && sfptr.Elem().IsNil() { + continue + } + f.funcs.merge(dst.Apply(f.offset), sfptr, f, opts) + } + if mi.extensionOffset.IsValid() { + sext := src.Apply(mi.extensionOffset).Extensions() + dext := dst.Apply(mi.extensionOffset).Extensions() + if *dext == nil { + *dext = make(map[int32]ExtensionField) + } + for num, sx := range *sext { + xt := sx.Type() + xi := getExtensionFieldInfo(xt) + if xi.funcs.merge == nil { + continue + } + dx := (*dext)[num] + var dv pref.Value + if dx.Type() == sx.Type() { + dv = dx.Value() + } + if !dv.IsValid() && xi.unmarshalNeedsValue { + dv = xt.New() + } + dv = xi.funcs.merge(dv, sx.Value(), opts) + dx.Set(sx.Type(), dv) + (*dext)[num] = dx + } + } + if mi.unknownOffset.IsValid() { + du := dst.Apply(mi.unknownOffset).Bytes() + su := src.Apply(mi.unknownOffset).Bytes() + if len(*su) > 0 { + *du = append(*du, *su...) + } + } +} + +func mergeScalarValue(dst, src pref.Value, opts mergeOptions) pref.Value { + return src +} + +func mergeBytesValue(dst, src pref.Value, opts mergeOptions) pref.Value { + return pref.ValueOfBytes(append(emptyBuf[:], src.Bytes()...)) +} + +func mergeListValue(dst, src pref.Value, opts mergeOptions) pref.Value { + dstl := dst.List() + srcl := src.List() + for i, llen := 0, srcl.Len(); i < llen; i++ { + dstl.Append(srcl.Get(i)) + } + return dst +} + +func mergeBytesListValue(dst, src pref.Value, opts mergeOptions) pref.Value { + dstl := dst.List() + srcl := src.List() + for i, llen := 0, srcl.Len(); i < llen; i++ { + sb := srcl.Get(i).Bytes() + db := append(emptyBuf[:], sb...) + dstl.Append(pref.ValueOfBytes(db)) + } + return dst +} + +func mergeMessageListValue(dst, src pref.Value, opts mergeOptions) pref.Value { + dstl := dst.List() + srcl := src.List() + for i, llen := 0, srcl.Len(); i < llen; i++ { + sm := srcl.Get(i).Message() + dm := proto.Clone(sm.Interface()).ProtoReflect() + dstl.Append(pref.ValueOfMessage(dm)) + } + return dst +} + +func mergeMessageValue(dst, src pref.Value, opts mergeOptions) pref.Value { + opts.Merge(dst.Message().Interface(), src.Message().Interface()) + return dst +} + +func mergeMessage(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { + if f.mi != nil { + if dst.Elem().IsNil() { + dst.SetPointer(pointerOfValue(reflect.New(f.mi.GoReflectType.Elem()))) + } + f.mi.mergePointer(dst.Elem(), src.Elem(), opts) + } else { + dm := dst.AsValueOf(f.ft).Elem() + sm := src.AsValueOf(f.ft).Elem() + if dm.IsNil() { + dm.Set(reflect.New(f.ft.Elem())) + } + opts.Merge(asMessage(dm), asMessage(sm)) + } +} + +func mergeMessageSlice(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { + for _, sp := range src.PointerSlice() { + dm := reflect.New(f.ft.Elem().Elem()) + if f.mi != nil { + f.mi.mergePointer(pointerOfValue(dm), sp, opts) + } else { + opts.Merge(asMessage(dm), asMessage(sp.AsValueOf(f.ft.Elem().Elem()))) + } + dst.AppendPointerSlice(pointerOfValue(dm)) + } +} + +func mergeBytes(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + *dst.Bytes() = append(emptyBuf[:], *src.Bytes()...) +} + +func mergeBytesNoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + v := *src.Bytes() + if len(v) > 0 { + *dst.Bytes() = append(emptyBuf[:], v...) + } +} + +func mergeBytesSlice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + ds := dst.BytesSlice() + for _, v := range *src.BytesSlice() { + *ds = append(*ds, append(emptyBuf[:], v...)) + } +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go b/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go new file mode 100644 index 00000000000..8816c274d28 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go @@ -0,0 +1,209 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-types. DO NOT EDIT. + +package impl + +import () + +func mergeBool(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + *dst.Bool() = *src.Bool() +} + +func mergeBoolNoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + v := *src.Bool() + if v != false { + *dst.Bool() = v + } +} + +func mergeBoolPtr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + p := *src.BoolPtr() + if p != nil { + v := *p + *dst.BoolPtr() = &v + } +} + +func mergeBoolSlice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + ds := dst.BoolSlice() + ss := src.BoolSlice() + *ds = append(*ds, *ss...) +} + +func mergeInt32(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + *dst.Int32() = *src.Int32() +} + +func mergeInt32NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + v := *src.Int32() + if v != 0 { + *dst.Int32() = v + } +} + +func mergeInt32Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + p := *src.Int32Ptr() + if p != nil { + v := *p + *dst.Int32Ptr() = &v + } +} + +func mergeInt32Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + ds := dst.Int32Slice() + ss := src.Int32Slice() + *ds = append(*ds, *ss...) +} + +func mergeUint32(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + *dst.Uint32() = *src.Uint32() +} + +func mergeUint32NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + v := *src.Uint32() + if v != 0 { + *dst.Uint32() = v + } +} + +func mergeUint32Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + p := *src.Uint32Ptr() + if p != nil { + v := *p + *dst.Uint32Ptr() = &v + } +} + +func mergeUint32Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + ds := dst.Uint32Slice() + ss := src.Uint32Slice() + *ds = append(*ds, *ss...) +} + +func mergeInt64(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + *dst.Int64() = *src.Int64() +} + +func mergeInt64NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + v := *src.Int64() + if v != 0 { + *dst.Int64() = v + } +} + +func mergeInt64Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + p := *src.Int64Ptr() + if p != nil { + v := *p + *dst.Int64Ptr() = &v + } +} + +func mergeInt64Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + ds := dst.Int64Slice() + ss := src.Int64Slice() + *ds = append(*ds, *ss...) +} + +func mergeUint64(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + *dst.Uint64() = *src.Uint64() +} + +func mergeUint64NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + v := *src.Uint64() + if v != 0 { + *dst.Uint64() = v + } +} + +func mergeUint64Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + p := *src.Uint64Ptr() + if p != nil { + v := *p + *dst.Uint64Ptr() = &v + } +} + +func mergeUint64Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + ds := dst.Uint64Slice() + ss := src.Uint64Slice() + *ds = append(*ds, *ss...) +} + +func mergeFloat32(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + *dst.Float32() = *src.Float32() +} + +func mergeFloat32NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + v := *src.Float32() + if v != 0 { + *dst.Float32() = v + } +} + +func mergeFloat32Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + p := *src.Float32Ptr() + if p != nil { + v := *p + *dst.Float32Ptr() = &v + } +} + +func mergeFloat32Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + ds := dst.Float32Slice() + ss := src.Float32Slice() + *ds = append(*ds, *ss...) +} + +func mergeFloat64(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + *dst.Float64() = *src.Float64() +} + +func mergeFloat64NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + v := *src.Float64() + if v != 0 { + *dst.Float64() = v + } +} + +func mergeFloat64Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + p := *src.Float64Ptr() + if p != nil { + v := *p + *dst.Float64Ptr() = &v + } +} + +func mergeFloat64Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + ds := dst.Float64Slice() + ss := src.Float64Slice() + *ds = append(*ds, *ss...) +} + +func mergeString(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + *dst.String() = *src.String() +} + +func mergeStringNoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + v := *src.String() + if v != "" { + *dst.String() = v + } +} + +func mergeStringPtr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + p := *src.StringPtr() + if p != nil { + v := *p + *dst.StringPtr() = &v + } +} + +func mergeStringSlice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { + ds := dst.StringSlice() + ss := src.StringSlice() + *ds = append(*ds, *ss...) +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/message.go b/vendor/google.golang.org/protobuf/internal/impl/message.go new file mode 100644 index 00000000000..c026a98180d --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/message.go @@ -0,0 +1,215 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + "strconv" + "strings" + "sync" + "sync/atomic" + + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/reflect/protoreflect" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +// MessageInfo provides protobuf related functionality for a given Go type +// that represents a message. A given instance of MessageInfo is tied to +// exactly one Go type, which must be a pointer to a struct type. +// +// The exported fields must be populated before any methods are called +// and cannot be mutated after set. +type MessageInfo struct { + // GoReflectType is the underlying message Go type and must be populated. + GoReflectType reflect.Type // pointer to struct + + // Desc is the underlying message descriptor type and must be populated. + Desc pref.MessageDescriptor + + // Exporter must be provided in a purego environment in order to provide + // access to unexported fields. + Exporter exporter + + // OneofWrappers is list of pointers to oneof wrapper struct types. + OneofWrappers []interface{} + + initMu sync.Mutex // protects all unexported fields + initDone uint32 + + reflectMessageInfo // for reflection implementation + coderMessageInfo // for fast-path method implementations +} + +// exporter is a function that returns a reference to the ith field of v, +// where v is a pointer to a struct. It returns nil if it does not support +// exporting the requested field (e.g., already exported). +type exporter func(v interface{}, i int) interface{} + +// getMessageInfo returns the MessageInfo for any message type that +// is generated by our implementation of protoc-gen-go (for v2 and on). +// If it is unable to obtain a MessageInfo, it returns nil. +func getMessageInfo(mt reflect.Type) *MessageInfo { + m, ok := reflect.Zero(mt).Interface().(pref.ProtoMessage) + if !ok { + return nil + } + mr, ok := m.ProtoReflect().(interface{ ProtoMessageInfo() *MessageInfo }) + if !ok { + return nil + } + return mr.ProtoMessageInfo() +} + +func (mi *MessageInfo) init() { + // This function is called in the hot path. Inline the sync.Once logic, + // since allocating a closure for Once.Do is expensive. + // Keep init small to ensure that it can be inlined. + if atomic.LoadUint32(&mi.initDone) == 0 { + mi.initOnce() + } +} + +func (mi *MessageInfo) initOnce() { + mi.initMu.Lock() + defer mi.initMu.Unlock() + if mi.initDone == 1 { + return + } + + t := mi.GoReflectType + if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct { + panic(fmt.Sprintf("got %v, want *struct kind", t)) + } + t = t.Elem() + + si := mi.makeStructInfo(t) + mi.makeReflectFuncs(t, si) + mi.makeCoderMethods(t, si) + + atomic.StoreUint32(&mi.initDone, 1) +} + +// getPointer returns the pointer for a message, which should be of +// the type of the MessageInfo. If the message is of a different type, +// it returns ok==false. +func (mi *MessageInfo) getPointer(m pref.Message) (p pointer, ok bool) { + switch m := m.(type) { + case *messageState: + return m.pointer(), m.messageInfo() == mi + case *messageReflectWrapper: + return m.pointer(), m.messageInfo() == mi + } + return pointer{}, false +} + +type ( + SizeCache = int32 + WeakFields = map[int32]protoreflect.ProtoMessage + UnknownFields = []byte + ExtensionFields = map[int32]ExtensionField +) + +var ( + sizecacheType = reflect.TypeOf(SizeCache(0)) + weakFieldsType = reflect.TypeOf(WeakFields(nil)) + unknownFieldsType = reflect.TypeOf(UnknownFields(nil)) + extensionFieldsType = reflect.TypeOf(ExtensionFields(nil)) +) + +type structInfo struct { + sizecacheOffset offset + weakOffset offset + unknownOffset offset + extensionOffset offset + + fieldsByNumber map[pref.FieldNumber]reflect.StructField + oneofsByName map[pref.Name]reflect.StructField + oneofWrappersByType map[reflect.Type]pref.FieldNumber + oneofWrappersByNumber map[pref.FieldNumber]reflect.Type +} + +func (mi *MessageInfo) makeStructInfo(t reflect.Type) structInfo { + si := structInfo{ + sizecacheOffset: invalidOffset, + weakOffset: invalidOffset, + unknownOffset: invalidOffset, + extensionOffset: invalidOffset, + + fieldsByNumber: map[pref.FieldNumber]reflect.StructField{}, + oneofsByName: map[pref.Name]reflect.StructField{}, + oneofWrappersByType: map[reflect.Type]pref.FieldNumber{}, + oneofWrappersByNumber: map[pref.FieldNumber]reflect.Type{}, + } + +fieldLoop: + for i := 0; i < t.NumField(); i++ { + switch f := t.Field(i); f.Name { + case genid.SizeCache_goname, genid.SizeCacheA_goname: + if f.Type == sizecacheType { + si.sizecacheOffset = offsetOf(f, mi.Exporter) + } + case genid.WeakFields_goname, genid.WeakFieldsA_goname: + if f.Type == weakFieldsType { + si.weakOffset = offsetOf(f, mi.Exporter) + } + case genid.UnknownFields_goname, genid.UnknownFieldsA_goname: + if f.Type == unknownFieldsType { + si.unknownOffset = offsetOf(f, mi.Exporter) + } + case genid.ExtensionFields_goname, genid.ExtensionFieldsA_goname, genid.ExtensionFieldsB_goname: + if f.Type == extensionFieldsType { + si.extensionOffset = offsetOf(f, mi.Exporter) + } + default: + for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") { + if len(s) > 0 && strings.Trim(s, "0123456789") == "" { + n, _ := strconv.ParseUint(s, 10, 64) + si.fieldsByNumber[pref.FieldNumber(n)] = f + continue fieldLoop + } + } + if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 { + si.oneofsByName[pref.Name(s)] = f + continue fieldLoop + } + } + } + + // Derive a mapping of oneof wrappers to fields. + oneofWrappers := mi.OneofWrappers + for _, method := range []string{"XXX_OneofFuncs", "XXX_OneofWrappers"} { + if fn, ok := reflect.PtrTo(t).MethodByName(method); ok { + for _, v := range fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))}) { + if vs, ok := v.Interface().([]interface{}); ok { + oneofWrappers = vs + } + } + } + } + for _, v := range oneofWrappers { + tf := reflect.TypeOf(v).Elem() + f := tf.Field(0) + for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") { + if len(s) > 0 && strings.Trim(s, "0123456789") == "" { + n, _ := strconv.ParseUint(s, 10, 64) + si.oneofWrappersByType[tf] = pref.FieldNumber(n) + si.oneofWrappersByNumber[pref.FieldNumber(n)] = tf + break + } + } + } + + return si +} + +func (mi *MessageInfo) New() protoreflect.Message { + return mi.MessageOf(reflect.New(mi.GoReflectType.Elem()).Interface()) +} +func (mi *MessageInfo) Zero() protoreflect.Message { + return mi.MessageOf(reflect.Zero(mi.GoReflectType).Interface()) +} +func (mi *MessageInfo) Descriptor() protoreflect.MessageDescriptor { return mi.Desc } diff --git a/vendor/google.golang.org/protobuf/internal/impl/message_reflect.go b/vendor/google.golang.org/protobuf/internal/impl/message_reflect.go new file mode 100644 index 00000000000..0f4b8db760a --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/message_reflect.go @@ -0,0 +1,364 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "reflect" + + "google.golang.org/protobuf/internal/pragma" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +type reflectMessageInfo struct { + fields map[pref.FieldNumber]*fieldInfo + oneofs map[pref.Name]*oneofInfo + + // denseFields is a subset of fields where: + // 0 < fieldDesc.Number() < len(denseFields) + // It provides faster access to the fieldInfo, but may be incomplete. + denseFields []*fieldInfo + + // rangeInfos is a list of all fields (not belonging to a oneof) and oneofs. + rangeInfos []interface{} // either *fieldInfo or *oneofInfo + + getUnknown func(pointer) pref.RawFields + setUnknown func(pointer, pref.RawFields) + extensionMap func(pointer) *extensionMap + + nilMessage atomicNilMessage +} + +// makeReflectFuncs generates the set of functions to support reflection. +func (mi *MessageInfo) makeReflectFuncs(t reflect.Type, si structInfo) { + mi.makeKnownFieldsFunc(si) + mi.makeUnknownFieldsFunc(t, si) + mi.makeExtensionFieldsFunc(t, si) +} + +// makeKnownFieldsFunc generates functions for operations that can be performed +// on each protobuf message field. It takes in a reflect.Type representing the +// Go struct and matches message fields with struct fields. +// +// This code assumes that the struct is well-formed and panics if there are +// any discrepancies. +func (mi *MessageInfo) makeKnownFieldsFunc(si structInfo) { + mi.fields = map[pref.FieldNumber]*fieldInfo{} + md := mi.Desc + fds := md.Fields() + for i := 0; i < fds.Len(); i++ { + fd := fds.Get(i) + fs := si.fieldsByNumber[fd.Number()] + var fi fieldInfo + switch { + case fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic(): + fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], mi.Exporter, si.oneofWrappersByNumber[fd.Number()]) + case fd.IsMap(): + fi = fieldInfoForMap(fd, fs, mi.Exporter) + case fd.IsList(): + fi = fieldInfoForList(fd, fs, mi.Exporter) + case fd.IsWeak(): + fi = fieldInfoForWeakMessage(fd, si.weakOffset) + case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind: + fi = fieldInfoForMessage(fd, fs, mi.Exporter) + default: + fi = fieldInfoForScalar(fd, fs, mi.Exporter) + } + mi.fields[fd.Number()] = &fi + } + + mi.oneofs = map[pref.Name]*oneofInfo{} + for i := 0; i < md.Oneofs().Len(); i++ { + od := md.Oneofs().Get(i) + mi.oneofs[od.Name()] = makeOneofInfo(od, si, mi.Exporter) + } + + mi.denseFields = make([]*fieldInfo, fds.Len()*2) + for i := 0; i < fds.Len(); i++ { + if fd := fds.Get(i); int(fd.Number()) < len(mi.denseFields) { + mi.denseFields[fd.Number()] = mi.fields[fd.Number()] + } + } + + for i := 0; i < fds.Len(); { + fd := fds.Get(i) + if od := fd.ContainingOneof(); od != nil && !od.IsSynthetic() { + mi.rangeInfos = append(mi.rangeInfos, mi.oneofs[od.Name()]) + i += od.Fields().Len() + } else { + mi.rangeInfos = append(mi.rangeInfos, mi.fields[fd.Number()]) + i++ + } + } +} + +func (mi *MessageInfo) makeUnknownFieldsFunc(t reflect.Type, si structInfo) { + mi.getUnknown = func(pointer) pref.RawFields { return nil } + mi.setUnknown = func(pointer, pref.RawFields) { return } + if si.unknownOffset.IsValid() { + mi.getUnknown = func(p pointer) pref.RawFields { + if p.IsNil() { + return nil + } + rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType) + return pref.RawFields(*rv.Interface().(*[]byte)) + } + mi.setUnknown = func(p pointer, b pref.RawFields) { + if p.IsNil() { + panic("invalid SetUnknown on nil Message") + } + rv := p.Apply(si.unknownOffset).AsValueOf(unknownFieldsType) + *rv.Interface().(*[]byte) = []byte(b) + } + } else { + mi.getUnknown = func(pointer) pref.RawFields { + return nil + } + mi.setUnknown = func(p pointer, _ pref.RawFields) { + if p.IsNil() { + panic("invalid SetUnknown on nil Message") + } + } + } +} + +func (mi *MessageInfo) makeExtensionFieldsFunc(t reflect.Type, si structInfo) { + if si.extensionOffset.IsValid() { + mi.extensionMap = func(p pointer) *extensionMap { + if p.IsNil() { + return (*extensionMap)(nil) + } + v := p.Apply(si.extensionOffset).AsValueOf(extensionFieldsType) + return (*extensionMap)(v.Interface().(*map[int32]ExtensionField)) + } + } else { + mi.extensionMap = func(pointer) *extensionMap { + return (*extensionMap)(nil) + } + } +} + +type extensionMap map[int32]ExtensionField + +func (m *extensionMap) Range(f func(pref.FieldDescriptor, pref.Value) bool) { + if m != nil { + for _, x := range *m { + xd := x.Type().TypeDescriptor() + v := x.Value() + if xd.IsList() && v.List().Len() == 0 { + continue + } + if !f(xd, v) { + return + } + } + } +} +func (m *extensionMap) Has(xt pref.ExtensionType) (ok bool) { + if m == nil { + return false + } + xd := xt.TypeDescriptor() + x, ok := (*m)[int32(xd.Number())] + if !ok { + return false + } + switch { + case xd.IsList(): + return x.Value().List().Len() > 0 + case xd.IsMap(): + return x.Value().Map().Len() > 0 + case xd.Message() != nil: + return x.Value().Message().IsValid() + } + return true +} +func (m *extensionMap) Clear(xt pref.ExtensionType) { + delete(*m, int32(xt.TypeDescriptor().Number())) +} +func (m *extensionMap) Get(xt pref.ExtensionType) pref.Value { + xd := xt.TypeDescriptor() + if m != nil { + if x, ok := (*m)[int32(xd.Number())]; ok { + return x.Value() + } + } + return xt.Zero() +} +func (m *extensionMap) Set(xt pref.ExtensionType, v pref.Value) { + xd := xt.TypeDescriptor() + isValid := true + switch { + case !xt.IsValidValue(v): + isValid = false + case xd.IsList(): + isValid = v.List().IsValid() + case xd.IsMap(): + isValid = v.Map().IsValid() + case xd.Message() != nil: + isValid = v.Message().IsValid() + } + if !isValid { + panic(fmt.Sprintf("%v: assigning invalid value", xt.TypeDescriptor().FullName())) + } + + if *m == nil { + *m = make(map[int32]ExtensionField) + } + var x ExtensionField + x.Set(xt, v) + (*m)[int32(xd.Number())] = x +} +func (m *extensionMap) Mutable(xt pref.ExtensionType) pref.Value { + xd := xt.TypeDescriptor() + if xd.Kind() != pref.MessageKind && xd.Kind() != pref.GroupKind && !xd.IsList() && !xd.IsMap() { + panic("invalid Mutable on field with non-composite type") + } + if x, ok := (*m)[int32(xd.Number())]; ok { + return x.Value() + } + v := xt.New() + m.Set(xt, v) + return v +} + +// MessageState is a data structure that is nested as the first field in a +// concrete message. It provides a way to implement the ProtoReflect method +// in an allocation-free way without needing to have a shadow Go type generated +// for every message type. This technique only works using unsafe. +// +// +// Example generated code: +// +// type M struct { +// state protoimpl.MessageState +// +// Field1 int32 +// Field2 string +// Field3 *BarMessage +// ... +// } +// +// func (m *M) ProtoReflect() protoreflect.Message { +// mi := &file_fizz_buzz_proto_msgInfos[5] +// if protoimpl.UnsafeEnabled && m != nil { +// ms := protoimpl.X.MessageStateOf(Pointer(m)) +// if ms.LoadMessageInfo() == nil { +// ms.StoreMessageInfo(mi) +// } +// return ms +// } +// return mi.MessageOf(m) +// } +// +// The MessageState type holds a *MessageInfo, which must be atomically set to +// the message info associated with a given message instance. +// By unsafely converting a *M into a *MessageState, the MessageState object +// has access to all the information needed to implement protobuf reflection. +// It has access to the message info as its first field, and a pointer to the +// MessageState is identical to a pointer to the concrete message value. +// +// +// Requirements: +// • The type M must implement protoreflect.ProtoMessage. +// • The address of m must not be nil. +// • The address of m and the address of m.state must be equal, +// even though they are different Go types. +type MessageState struct { + pragma.NoUnkeyedLiterals + pragma.DoNotCompare + pragma.DoNotCopy + + atomicMessageInfo *MessageInfo +} + +type messageState MessageState + +var ( + _ pref.Message = (*messageState)(nil) + _ unwrapper = (*messageState)(nil) +) + +// messageDataType is a tuple of a pointer to the message data and +// a pointer to the message type. It is a generalized way of providing a +// reflective view over a message instance. The disadvantage of this approach +// is the need to allocate this tuple of 16B. +type messageDataType struct { + p pointer + mi *MessageInfo +} + +type ( + messageReflectWrapper messageDataType + messageIfaceWrapper messageDataType +) + +var ( + _ pref.Message = (*messageReflectWrapper)(nil) + _ unwrapper = (*messageReflectWrapper)(nil) + _ pref.ProtoMessage = (*messageIfaceWrapper)(nil) + _ unwrapper = (*messageIfaceWrapper)(nil) +) + +// MessageOf returns a reflective view over a message. The input must be a +// pointer to a named Go struct. If the provided type has a ProtoReflect method, +// it must be implemented by calling this method. +func (mi *MessageInfo) MessageOf(m interface{}) pref.Message { + // TODO: Switch the input to be an opaque Pointer. + if reflect.TypeOf(m) != mi.GoReflectType { + panic(fmt.Sprintf("type mismatch: got %T, want %v", m, mi.GoReflectType)) + } + p := pointerOfIface(m) + if p.IsNil() { + return mi.nilMessage.Init(mi) + } + return &messageReflectWrapper{p, mi} +} + +func (m *messageReflectWrapper) pointer() pointer { return m.p } +func (m *messageReflectWrapper) messageInfo() *MessageInfo { return m.mi } + +func (m *messageIfaceWrapper) ProtoReflect() pref.Message { + return (*messageReflectWrapper)(m) +} +func (m *messageIfaceWrapper) protoUnwrap() interface{} { + return m.p.AsIfaceOf(m.mi.GoReflectType.Elem()) +} + +// checkField verifies that the provided field descriptor is valid. +// Exactly one of the returned values is populated. +func (mi *MessageInfo) checkField(fd pref.FieldDescriptor) (*fieldInfo, pref.ExtensionType) { + var fi *fieldInfo + if n := fd.Number(); 0 < n && int(n) < len(mi.denseFields) { + fi = mi.denseFields[n] + } else { + fi = mi.fields[n] + } + if fi != nil { + if fi.fieldDesc != fd { + if got, want := fd.FullName(), fi.fieldDesc.FullName(); got != want { + panic(fmt.Sprintf("mismatching field: got %v, want %v", got, want)) + } + panic(fmt.Sprintf("mismatching field: %v", fd.FullName())) + } + return fi, nil + } + + if fd.IsExtension() { + if got, want := fd.ContainingMessage().FullName(), mi.Desc.FullName(); got != want { + // TODO: Should this be exact containing message descriptor match? + panic(fmt.Sprintf("extension %v has mismatching containing message: got %v, want %v", fd.FullName(), got, want)) + } + if !mi.Desc.ExtensionRanges().Has(fd.Number()) { + panic(fmt.Sprintf("extension %v extends %v outside the extension range", fd.FullName(), mi.Desc.FullName())) + } + xtd, ok := fd.(pref.ExtensionTypeDescriptor) + if !ok { + panic(fmt.Sprintf("extension %v does not implement protoreflect.ExtensionTypeDescriptor", fd.FullName())) + } + return nil, xtd.Type() + } + panic(fmt.Sprintf("field %v is invalid", fd.FullName())) +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/message_reflect_field.go b/vendor/google.golang.org/protobuf/internal/impl/message_reflect_field.go new file mode 100644 index 00000000000..23124a86e40 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/message_reflect_field.go @@ -0,0 +1,466 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "math" + "reflect" + "sync" + + "google.golang.org/protobuf/internal/flags" + pref "google.golang.org/protobuf/reflect/protoreflect" + preg "google.golang.org/protobuf/reflect/protoregistry" +) + +type fieldInfo struct { + fieldDesc pref.FieldDescriptor + + // These fields are used for protobuf reflection support. + has func(pointer) bool + clear func(pointer) + get func(pointer) pref.Value + set func(pointer, pref.Value) + mutable func(pointer) pref.Value + newMessage func() pref.Message + newField func() pref.Value +} + +func fieldInfoForOneof(fd pref.FieldDescriptor, fs reflect.StructField, x exporter, ot reflect.Type) fieldInfo { + ft := fs.Type + if ft.Kind() != reflect.Interface { + panic(fmt.Sprintf("field %v has invalid type: got %v, want interface kind", fd.FullName(), ft)) + } + if ot.Kind() != reflect.Struct { + panic(fmt.Sprintf("field %v has invalid type: got %v, want struct kind", fd.FullName(), ot)) + } + if !reflect.PtrTo(ot).Implements(ft) { + panic(fmt.Sprintf("field %v has invalid type: %v does not implement %v", fd.FullName(), ot, ft)) + } + conv := NewConverter(ot.Field(0).Type, fd) + isMessage := fd.Message() != nil + + // TODO: Implement unsafe fast path? + fieldOffset := offsetOf(fs, x) + return fieldInfo{ + // NOTE: The logic below intentionally assumes that oneof fields are + // well-formatted. That is, the oneof interface never contains a + // typed nil pointer to one of the wrapper structs. + + fieldDesc: fd, + has: func(p pointer) bool { + if p.IsNil() { + return false + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if rv.IsNil() || rv.Elem().Type().Elem() != ot || rv.Elem().IsNil() { + return false + } + return true + }, + clear: func(p pointer) { + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if rv.IsNil() || rv.Elem().Type().Elem() != ot { + // NOTE: We intentionally don't check for rv.Elem().IsNil() + // so that (*OneofWrapperType)(nil) gets cleared to nil. + return + } + rv.Set(reflect.Zero(rv.Type())) + }, + get: func(p pointer) pref.Value { + if p.IsNil() { + return conv.Zero() + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if rv.IsNil() || rv.Elem().Type().Elem() != ot || rv.Elem().IsNil() { + return conv.Zero() + } + rv = rv.Elem().Elem().Field(0) + return conv.PBValueOf(rv) + }, + set: func(p pointer, v pref.Value) { + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if rv.IsNil() || rv.Elem().Type().Elem() != ot || rv.Elem().IsNil() { + rv.Set(reflect.New(ot)) + } + rv = rv.Elem().Elem().Field(0) + rv.Set(conv.GoValueOf(v)) + }, + mutable: func(p pointer) pref.Value { + if !isMessage { + panic(fmt.Sprintf("field %v with invalid Mutable call on field with non-composite type", fd.FullName())) + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if rv.IsNil() || rv.Elem().Type().Elem() != ot || rv.Elem().IsNil() { + rv.Set(reflect.New(ot)) + } + rv = rv.Elem().Elem().Field(0) + if rv.IsNil() { + rv.Set(conv.GoValueOf(pref.ValueOfMessage(conv.New().Message()))) + } + return conv.PBValueOf(rv) + }, + newMessage: func() pref.Message { + return conv.New().Message() + }, + newField: func() pref.Value { + return conv.New() + }, + } +} + +func fieldInfoForMap(fd pref.FieldDescriptor, fs reflect.StructField, x exporter) fieldInfo { + ft := fs.Type + if ft.Kind() != reflect.Map { + panic(fmt.Sprintf("field %v has invalid type: got %v, want map kind", fd.FullName(), ft)) + } + conv := NewConverter(ft, fd) + + // TODO: Implement unsafe fast path? + fieldOffset := offsetOf(fs, x) + return fieldInfo{ + fieldDesc: fd, + has: func(p pointer) bool { + if p.IsNil() { + return false + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + return rv.Len() > 0 + }, + clear: func(p pointer) { + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + rv.Set(reflect.Zero(rv.Type())) + }, + get: func(p pointer) pref.Value { + if p.IsNil() { + return conv.Zero() + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if rv.Len() == 0 { + return conv.Zero() + } + return conv.PBValueOf(rv) + }, + set: func(p pointer, v pref.Value) { + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + pv := conv.GoValueOf(v) + if pv.IsNil() { + panic(fmt.Sprintf("map field %v cannot be set with read-only value", fd.FullName())) + } + rv.Set(pv) + }, + mutable: func(p pointer) pref.Value { + v := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if v.IsNil() { + v.Set(reflect.MakeMap(fs.Type)) + } + return conv.PBValueOf(v) + }, + newField: func() pref.Value { + return conv.New() + }, + } +} + +func fieldInfoForList(fd pref.FieldDescriptor, fs reflect.StructField, x exporter) fieldInfo { + ft := fs.Type + if ft.Kind() != reflect.Slice { + panic(fmt.Sprintf("field %v has invalid type: got %v, want slice kind", fd.FullName(), ft)) + } + conv := NewConverter(reflect.PtrTo(ft), fd) + + // TODO: Implement unsafe fast path? + fieldOffset := offsetOf(fs, x) + return fieldInfo{ + fieldDesc: fd, + has: func(p pointer) bool { + if p.IsNil() { + return false + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + return rv.Len() > 0 + }, + clear: func(p pointer) { + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + rv.Set(reflect.Zero(rv.Type())) + }, + get: func(p pointer) pref.Value { + if p.IsNil() { + return conv.Zero() + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type) + if rv.Elem().Len() == 0 { + return conv.Zero() + } + return conv.PBValueOf(rv) + }, + set: func(p pointer, v pref.Value) { + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + pv := conv.GoValueOf(v) + if pv.IsNil() { + panic(fmt.Sprintf("list field %v cannot be set with read-only value", fd.FullName())) + } + rv.Set(pv.Elem()) + }, + mutable: func(p pointer) pref.Value { + v := p.Apply(fieldOffset).AsValueOf(fs.Type) + return conv.PBValueOf(v) + }, + newField: func() pref.Value { + return conv.New() + }, + } +} + +var ( + nilBytes = reflect.ValueOf([]byte(nil)) + emptyBytes = reflect.ValueOf([]byte{}) +) + +func fieldInfoForScalar(fd pref.FieldDescriptor, fs reflect.StructField, x exporter) fieldInfo { + ft := fs.Type + nullable := fd.HasPresence() + isBytes := ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 + if nullable { + if ft.Kind() != reflect.Ptr && ft.Kind() != reflect.Slice { + panic(fmt.Sprintf("field %v has invalid type: got %v, want pointer", fd.FullName(), ft)) + } + if ft.Kind() == reflect.Ptr { + ft = ft.Elem() + } + } + conv := NewConverter(ft, fd) + + // TODO: Implement unsafe fast path? + fieldOffset := offsetOf(fs, x) + return fieldInfo{ + fieldDesc: fd, + has: func(p pointer) bool { + if p.IsNil() { + return false + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if nullable { + return !rv.IsNil() + } + switch rv.Kind() { + case reflect.Bool: + return rv.Bool() + case reflect.Int32, reflect.Int64: + return rv.Int() != 0 + case reflect.Uint32, reflect.Uint64: + return rv.Uint() != 0 + case reflect.Float32, reflect.Float64: + return rv.Float() != 0 || math.Signbit(rv.Float()) + case reflect.String, reflect.Slice: + return rv.Len() > 0 + default: + panic(fmt.Sprintf("field %v has invalid type: %v", fd.FullName(), rv.Type())) // should never happen + } + }, + clear: func(p pointer) { + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + rv.Set(reflect.Zero(rv.Type())) + }, + get: func(p pointer) pref.Value { + if p.IsNil() { + return conv.Zero() + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if nullable { + if rv.IsNil() { + return conv.Zero() + } + if rv.Kind() == reflect.Ptr { + rv = rv.Elem() + } + } + return conv.PBValueOf(rv) + }, + set: func(p pointer, v pref.Value) { + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if nullable && rv.Kind() == reflect.Ptr { + if rv.IsNil() { + rv.Set(reflect.New(ft)) + } + rv = rv.Elem() + } + rv.Set(conv.GoValueOf(v)) + if isBytes && rv.Len() == 0 { + if nullable { + rv.Set(emptyBytes) // preserve presence + } else { + rv.Set(nilBytes) // do not preserve presence + } + } + }, + newField: func() pref.Value { + return conv.New() + }, + } +} + +func fieldInfoForWeakMessage(fd pref.FieldDescriptor, weakOffset offset) fieldInfo { + if !flags.ProtoLegacy { + panic("no support for proto1 weak fields") + } + + var once sync.Once + var messageType pref.MessageType + lazyInit := func() { + once.Do(func() { + messageName := fd.Message().FullName() + messageType, _ = preg.GlobalTypes.FindMessageByName(messageName) + if messageType == nil { + panic(fmt.Sprintf("weak message %v for field %v is not linked in", messageName, fd.FullName())) + } + }) + } + + num := fd.Number() + return fieldInfo{ + fieldDesc: fd, + has: func(p pointer) bool { + if p.IsNil() { + return false + } + _, ok := p.Apply(weakOffset).WeakFields().get(num) + return ok + }, + clear: func(p pointer) { + p.Apply(weakOffset).WeakFields().clear(num) + }, + get: func(p pointer) pref.Value { + lazyInit() + if p.IsNil() { + return pref.ValueOfMessage(messageType.Zero()) + } + m, ok := p.Apply(weakOffset).WeakFields().get(num) + if !ok { + return pref.ValueOfMessage(messageType.Zero()) + } + return pref.ValueOfMessage(m.ProtoReflect()) + }, + set: func(p pointer, v pref.Value) { + lazyInit() + m := v.Message() + if m.Descriptor() != messageType.Descriptor() { + if got, want := m.Descriptor().FullName(), messageType.Descriptor().FullName(); got != want { + panic(fmt.Sprintf("field %v has mismatching message descriptor: got %v, want %v", fd.FullName(), got, want)) + } + panic(fmt.Sprintf("field %v has mismatching message descriptor: %v", fd.FullName(), m.Descriptor().FullName())) + } + p.Apply(weakOffset).WeakFields().set(num, m.Interface()) + }, + mutable: func(p pointer) pref.Value { + lazyInit() + fs := p.Apply(weakOffset).WeakFields() + m, ok := fs.get(num) + if !ok { + m = messageType.New().Interface() + fs.set(num, m) + } + return pref.ValueOfMessage(m.ProtoReflect()) + }, + newMessage: func() pref.Message { + lazyInit() + return messageType.New() + }, + newField: func() pref.Value { + lazyInit() + return pref.ValueOfMessage(messageType.New()) + }, + } +} + +func fieldInfoForMessage(fd pref.FieldDescriptor, fs reflect.StructField, x exporter) fieldInfo { + ft := fs.Type + conv := NewConverter(ft, fd) + + // TODO: Implement unsafe fast path? + fieldOffset := offsetOf(fs, x) + return fieldInfo{ + fieldDesc: fd, + has: func(p pointer) bool { + if p.IsNil() { + return false + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + return !rv.IsNil() + }, + clear: func(p pointer) { + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + rv.Set(reflect.Zero(rv.Type())) + }, + get: func(p pointer) pref.Value { + if p.IsNil() { + return conv.Zero() + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + return conv.PBValueOf(rv) + }, + set: func(p pointer, v pref.Value) { + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + rv.Set(conv.GoValueOf(v)) + if rv.IsNil() { + panic(fmt.Sprintf("field %v has invalid nil pointer", fd.FullName())) + } + }, + mutable: func(p pointer) pref.Value { + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if rv.IsNil() { + rv.Set(conv.GoValueOf(conv.New())) + } + return conv.PBValueOf(rv) + }, + newMessage: func() pref.Message { + return conv.New().Message() + }, + newField: func() pref.Value { + return conv.New() + }, + } +} + +type oneofInfo struct { + oneofDesc pref.OneofDescriptor + which func(pointer) pref.FieldNumber +} + +func makeOneofInfo(od pref.OneofDescriptor, si structInfo, x exporter) *oneofInfo { + oi := &oneofInfo{oneofDesc: od} + if od.IsSynthetic() { + fs := si.fieldsByNumber[od.Fields().Get(0).Number()] + fieldOffset := offsetOf(fs, x) + oi.which = func(p pointer) pref.FieldNumber { + if p.IsNil() { + return 0 + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if rv.IsNil() { // valid on either *T or []byte + return 0 + } + return od.Fields().Get(0).Number() + } + } else { + fs := si.oneofsByName[od.Name()] + fieldOffset := offsetOf(fs, x) + oi.which = func(p pointer) pref.FieldNumber { + if p.IsNil() { + return 0 + } + rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() + if rv.IsNil() { + return 0 + } + rv = rv.Elem() + if rv.IsNil() { + return 0 + } + return si.oneofWrappersByType[rv.Type().Elem()] + } + } + return oi +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go b/vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go new file mode 100644 index 00000000000..741d6e5b6bd --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go @@ -0,0 +1,249 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-types. DO NOT EDIT. + +package impl + +import ( + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoiface" +) + +func (m *messageState) Descriptor() protoreflect.MessageDescriptor { + return m.messageInfo().Desc +} +func (m *messageState) Type() protoreflect.MessageType { + return m.messageInfo() +} +func (m *messageState) New() protoreflect.Message { + return m.messageInfo().New() +} +func (m *messageState) Interface() protoreflect.ProtoMessage { + return m.protoUnwrap().(protoreflect.ProtoMessage) +} +func (m *messageState) protoUnwrap() interface{} { + return m.pointer().AsIfaceOf(m.messageInfo().GoReflectType.Elem()) +} +func (m *messageState) ProtoMethods() *protoiface.Methods { + m.messageInfo().init() + return &m.messageInfo().methods +} + +// ProtoMessageInfo is a pseudo-internal API for allowing the v1 code +// to be able to retrieve a v2 MessageInfo struct. +// +// WARNING: This method is exempt from the compatibility promise and +// may be removed in the future without warning. +func (m *messageState) ProtoMessageInfo() *MessageInfo { + return m.messageInfo() +} + +func (m *messageState) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + m.messageInfo().init() + for _, ri := range m.messageInfo().rangeInfos { + switch ri := ri.(type) { + case *fieldInfo: + if ri.has(m.pointer()) { + if !f(ri.fieldDesc, ri.get(m.pointer())) { + return + } + } + case *oneofInfo: + if n := ri.which(m.pointer()); n > 0 { + fi := m.messageInfo().fields[n] + if !f(fi.fieldDesc, fi.get(m.pointer())) { + return + } + } + } + } + m.messageInfo().extensionMap(m.pointer()).Range(f) +} +func (m *messageState) Has(fd protoreflect.FieldDescriptor) bool { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + return fi.has(m.pointer()) + } else { + return m.messageInfo().extensionMap(m.pointer()).Has(xt) + } +} +func (m *messageState) Clear(fd protoreflect.FieldDescriptor) { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + fi.clear(m.pointer()) + } else { + m.messageInfo().extensionMap(m.pointer()).Clear(xt) + } +} +func (m *messageState) Get(fd protoreflect.FieldDescriptor) protoreflect.Value { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + return fi.get(m.pointer()) + } else { + return m.messageInfo().extensionMap(m.pointer()).Get(xt) + } +} +func (m *messageState) Set(fd protoreflect.FieldDescriptor, v protoreflect.Value) { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + fi.set(m.pointer(), v) + } else { + m.messageInfo().extensionMap(m.pointer()).Set(xt, v) + } +} +func (m *messageState) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + return fi.mutable(m.pointer()) + } else { + return m.messageInfo().extensionMap(m.pointer()).Mutable(xt) + } +} +func (m *messageState) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + return fi.newField() + } else { + return xt.New() + } +} +func (m *messageState) WhichOneof(od protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + m.messageInfo().init() + if oi := m.messageInfo().oneofs[od.Name()]; oi != nil && oi.oneofDesc == od { + return od.Fields().ByNumber(oi.which(m.pointer())) + } + panic("invalid oneof descriptor " + string(od.FullName()) + " for message " + string(m.Descriptor().FullName())) +} +func (m *messageState) GetUnknown() protoreflect.RawFields { + m.messageInfo().init() + return m.messageInfo().getUnknown(m.pointer()) +} +func (m *messageState) SetUnknown(b protoreflect.RawFields) { + m.messageInfo().init() + m.messageInfo().setUnknown(m.pointer(), b) +} +func (m *messageState) IsValid() bool { + return !m.pointer().IsNil() +} + +func (m *messageReflectWrapper) Descriptor() protoreflect.MessageDescriptor { + return m.messageInfo().Desc +} +func (m *messageReflectWrapper) Type() protoreflect.MessageType { + return m.messageInfo() +} +func (m *messageReflectWrapper) New() protoreflect.Message { + return m.messageInfo().New() +} +func (m *messageReflectWrapper) Interface() protoreflect.ProtoMessage { + if m, ok := m.protoUnwrap().(protoreflect.ProtoMessage); ok { + return m + } + return (*messageIfaceWrapper)(m) +} +func (m *messageReflectWrapper) protoUnwrap() interface{} { + return m.pointer().AsIfaceOf(m.messageInfo().GoReflectType.Elem()) +} +func (m *messageReflectWrapper) ProtoMethods() *protoiface.Methods { + m.messageInfo().init() + return &m.messageInfo().methods +} + +// ProtoMessageInfo is a pseudo-internal API for allowing the v1 code +// to be able to retrieve a v2 MessageInfo struct. +// +// WARNING: This method is exempt from the compatibility promise and +// may be removed in the future without warning. +func (m *messageReflectWrapper) ProtoMessageInfo() *MessageInfo { + return m.messageInfo() +} + +func (m *messageReflectWrapper) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + m.messageInfo().init() + for _, ri := range m.messageInfo().rangeInfos { + switch ri := ri.(type) { + case *fieldInfo: + if ri.has(m.pointer()) { + if !f(ri.fieldDesc, ri.get(m.pointer())) { + return + } + } + case *oneofInfo: + if n := ri.which(m.pointer()); n > 0 { + fi := m.messageInfo().fields[n] + if !f(fi.fieldDesc, fi.get(m.pointer())) { + return + } + } + } + } + m.messageInfo().extensionMap(m.pointer()).Range(f) +} +func (m *messageReflectWrapper) Has(fd protoreflect.FieldDescriptor) bool { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + return fi.has(m.pointer()) + } else { + return m.messageInfo().extensionMap(m.pointer()).Has(xt) + } +} +func (m *messageReflectWrapper) Clear(fd protoreflect.FieldDescriptor) { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + fi.clear(m.pointer()) + } else { + m.messageInfo().extensionMap(m.pointer()).Clear(xt) + } +} +func (m *messageReflectWrapper) Get(fd protoreflect.FieldDescriptor) protoreflect.Value { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + return fi.get(m.pointer()) + } else { + return m.messageInfo().extensionMap(m.pointer()).Get(xt) + } +} +func (m *messageReflectWrapper) Set(fd protoreflect.FieldDescriptor, v protoreflect.Value) { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + fi.set(m.pointer(), v) + } else { + m.messageInfo().extensionMap(m.pointer()).Set(xt, v) + } +} +func (m *messageReflectWrapper) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + return fi.mutable(m.pointer()) + } else { + return m.messageInfo().extensionMap(m.pointer()).Mutable(xt) + } +} +func (m *messageReflectWrapper) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { + m.messageInfo().init() + if fi, xt := m.messageInfo().checkField(fd); fi != nil { + return fi.newField() + } else { + return xt.New() + } +} +func (m *messageReflectWrapper) WhichOneof(od protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { + m.messageInfo().init() + if oi := m.messageInfo().oneofs[od.Name()]; oi != nil && oi.oneofDesc == od { + return od.Fields().ByNumber(oi.which(m.pointer())) + } + panic("invalid oneof descriptor " + string(od.FullName()) + " for message " + string(m.Descriptor().FullName())) +} +func (m *messageReflectWrapper) GetUnknown() protoreflect.RawFields { + m.messageInfo().init() + return m.messageInfo().getUnknown(m.pointer()) +} +func (m *messageReflectWrapper) SetUnknown(b protoreflect.RawFields) { + m.messageInfo().init() + m.messageInfo().setUnknown(m.pointer(), b) +} +func (m *messageReflectWrapper) IsValid() bool { + return !m.pointer().IsNil() +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/pointer_reflect.go b/vendor/google.golang.org/protobuf/internal/impl/pointer_reflect.go new file mode 100644 index 00000000000..67b4ede6705 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/pointer_reflect.go @@ -0,0 +1,177 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build purego appengine + +package impl + +import ( + "fmt" + "reflect" + "sync" +) + +const UnsafeEnabled = false + +// Pointer is an opaque pointer type. +type Pointer interface{} + +// offset represents the offset to a struct field, accessible from a pointer. +// The offset is the field index into a struct. +type offset struct { + index int + export exporter +} + +// offsetOf returns a field offset for the struct field. +func offsetOf(f reflect.StructField, x exporter) offset { + if len(f.Index) != 1 { + panic("embedded structs are not supported") + } + if f.PkgPath == "" { + return offset{index: f.Index[0]} // field is already exported + } + if x == nil { + panic("exporter must be provided for unexported field") + } + return offset{index: f.Index[0], export: x} +} + +// IsValid reports whether the offset is valid. +func (f offset) IsValid() bool { return f.index >= 0 } + +// invalidOffset is an invalid field offset. +var invalidOffset = offset{index: -1} + +// zeroOffset is a noop when calling pointer.Apply. +var zeroOffset = offset{index: 0} + +// pointer is an abstract representation of a pointer to a struct or field. +type pointer struct{ v reflect.Value } + +// pointerOf returns p as a pointer. +func pointerOf(p Pointer) pointer { + return pointerOfIface(p) +} + +// pointerOfValue returns v as a pointer. +func pointerOfValue(v reflect.Value) pointer { + return pointer{v: v} +} + +// pointerOfIface returns the pointer portion of an interface. +func pointerOfIface(v interface{}) pointer { + return pointer{v: reflect.ValueOf(v)} +} + +// IsNil reports whether the pointer is nil. +func (p pointer) IsNil() bool { + return p.v.IsNil() +} + +// Apply adds an offset to the pointer to derive a new pointer +// to a specified field. The current pointer must be pointing at a struct. +func (p pointer) Apply(f offset) pointer { + if f.export != nil { + if v := reflect.ValueOf(f.export(p.v.Interface(), f.index)); v.IsValid() { + return pointer{v: v} + } + } + return pointer{v: p.v.Elem().Field(f.index).Addr()} +} + +// AsValueOf treats p as a pointer to an object of type t and returns the value. +// It is equivalent to reflect.ValueOf(p.AsIfaceOf(t)) +func (p pointer) AsValueOf(t reflect.Type) reflect.Value { + if got := p.v.Type().Elem(); got != t { + panic(fmt.Sprintf("invalid type: got %v, want %v", got, t)) + } + return p.v +} + +// AsIfaceOf treats p as a pointer to an object of type t and returns the value. +// It is equivalent to p.AsValueOf(t).Interface() +func (p pointer) AsIfaceOf(t reflect.Type) interface{} { + return p.AsValueOf(t).Interface() +} + +func (p pointer) Bool() *bool { return p.v.Interface().(*bool) } +func (p pointer) BoolPtr() **bool { return p.v.Interface().(**bool) } +func (p pointer) BoolSlice() *[]bool { return p.v.Interface().(*[]bool) } +func (p pointer) Int32() *int32 { return p.v.Interface().(*int32) } +func (p pointer) Int32Ptr() **int32 { return p.v.Interface().(**int32) } +func (p pointer) Int32Slice() *[]int32 { return p.v.Interface().(*[]int32) } +func (p pointer) Int64() *int64 { return p.v.Interface().(*int64) } +func (p pointer) Int64Ptr() **int64 { return p.v.Interface().(**int64) } +func (p pointer) Int64Slice() *[]int64 { return p.v.Interface().(*[]int64) } +func (p pointer) Uint32() *uint32 { return p.v.Interface().(*uint32) } +func (p pointer) Uint32Ptr() **uint32 { return p.v.Interface().(**uint32) } +func (p pointer) Uint32Slice() *[]uint32 { return p.v.Interface().(*[]uint32) } +func (p pointer) Uint64() *uint64 { return p.v.Interface().(*uint64) } +func (p pointer) Uint64Ptr() **uint64 { return p.v.Interface().(**uint64) } +func (p pointer) Uint64Slice() *[]uint64 { return p.v.Interface().(*[]uint64) } +func (p pointer) Float32() *float32 { return p.v.Interface().(*float32) } +func (p pointer) Float32Ptr() **float32 { return p.v.Interface().(**float32) } +func (p pointer) Float32Slice() *[]float32 { return p.v.Interface().(*[]float32) } +func (p pointer) Float64() *float64 { return p.v.Interface().(*float64) } +func (p pointer) Float64Ptr() **float64 { return p.v.Interface().(**float64) } +func (p pointer) Float64Slice() *[]float64 { return p.v.Interface().(*[]float64) } +func (p pointer) String() *string { return p.v.Interface().(*string) } +func (p pointer) StringPtr() **string { return p.v.Interface().(**string) } +func (p pointer) StringSlice() *[]string { return p.v.Interface().(*[]string) } +func (p pointer) Bytes() *[]byte { return p.v.Interface().(*[]byte) } +func (p pointer) BytesSlice() *[][]byte { return p.v.Interface().(*[][]byte) } +func (p pointer) WeakFields() *weakFields { return (*weakFields)(p.v.Interface().(*WeakFields)) } +func (p pointer) Extensions() *map[int32]ExtensionField { + return p.v.Interface().(*map[int32]ExtensionField) +} + +func (p pointer) Elem() pointer { + return pointer{v: p.v.Elem()} +} + +// PointerSlice copies []*T from p as a new []pointer. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) PointerSlice() []pointer { + // TODO: reconsider this + if p.v.IsNil() { + return nil + } + n := p.v.Elem().Len() + s := make([]pointer, n) + for i := 0; i < n; i++ { + s[i] = pointer{v: p.v.Elem().Index(i)} + } + return s +} + +// AppendPointerSlice appends v to p, which must be a []*T. +func (p pointer) AppendPointerSlice(v pointer) { + sp := p.v.Elem() + sp.Set(reflect.Append(sp, v.v)) +} + +// SetPointer sets *p to v. +func (p pointer) SetPointer(v pointer) { + p.v.Elem().Set(v.v) +} + +func (Export) MessageStateOf(p Pointer) *messageState { panic("not supported") } +func (ms *messageState) pointer() pointer { panic("not supported") } +func (ms *messageState) messageInfo() *MessageInfo { panic("not supported") } +func (ms *messageState) LoadMessageInfo() *MessageInfo { panic("not supported") } +func (ms *messageState) StoreMessageInfo(mi *MessageInfo) { panic("not supported") } + +type atomicNilMessage struct { + once sync.Once + m messageReflectWrapper +} + +func (m *atomicNilMessage) Init(mi *MessageInfo) *messageReflectWrapper { + m.once.Do(func() { + m.m.p = pointerOfIface(reflect.Zero(mi.GoReflectType).Interface()) + m.m.mi = mi + }) + return &m.m +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go b/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go new file mode 100644 index 00000000000..088aa85d483 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go @@ -0,0 +1,173 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !purego,!appengine + +package impl + +import ( + "reflect" + "sync/atomic" + "unsafe" +) + +const UnsafeEnabled = true + +// Pointer is an opaque pointer type. +type Pointer unsafe.Pointer + +// offset represents the offset to a struct field, accessible from a pointer. +// The offset is the byte offset to the field from the start of the struct. +type offset uintptr + +// offsetOf returns a field offset for the struct field. +func offsetOf(f reflect.StructField, x exporter) offset { + return offset(f.Offset) +} + +// IsValid reports whether the offset is valid. +func (f offset) IsValid() bool { return f != invalidOffset } + +// invalidOffset is an invalid field offset. +var invalidOffset = ^offset(0) + +// zeroOffset is a noop when calling pointer.Apply. +var zeroOffset = offset(0) + +// pointer is a pointer to a message struct or field. +type pointer struct{ p unsafe.Pointer } + +// pointerOf returns p as a pointer. +func pointerOf(p Pointer) pointer { + return pointer{p: unsafe.Pointer(p)} +} + +// pointerOfValue returns v as a pointer. +func pointerOfValue(v reflect.Value) pointer { + return pointer{p: unsafe.Pointer(v.Pointer())} +} + +// pointerOfIface returns the pointer portion of an interface. +func pointerOfIface(v interface{}) pointer { + type ifaceHeader struct { + Type unsafe.Pointer + Data unsafe.Pointer + } + return pointer{p: (*ifaceHeader)(unsafe.Pointer(&v)).Data} +} + +// IsNil reports whether the pointer is nil. +func (p pointer) IsNil() bool { + return p.p == nil +} + +// Apply adds an offset to the pointer to derive a new pointer +// to a specified field. The pointer must be valid and pointing at a struct. +func (p pointer) Apply(f offset) pointer { + if p.IsNil() { + panic("invalid nil pointer") + } + return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} +} + +// AsValueOf treats p as a pointer to an object of type t and returns the value. +// It is equivalent to reflect.ValueOf(p.AsIfaceOf(t)) +func (p pointer) AsValueOf(t reflect.Type) reflect.Value { + return reflect.NewAt(t, p.p) +} + +// AsIfaceOf treats p as a pointer to an object of type t and returns the value. +// It is equivalent to p.AsValueOf(t).Interface() +func (p pointer) AsIfaceOf(t reflect.Type) interface{} { + // TODO: Use tricky unsafe magic to directly create ifaceHeader. + return p.AsValueOf(t).Interface() +} + +func (p pointer) Bool() *bool { return (*bool)(p.p) } +func (p pointer) BoolPtr() **bool { return (**bool)(p.p) } +func (p pointer) BoolSlice() *[]bool { return (*[]bool)(p.p) } +func (p pointer) Int32() *int32 { return (*int32)(p.p) } +func (p pointer) Int32Ptr() **int32 { return (**int32)(p.p) } +func (p pointer) Int32Slice() *[]int32 { return (*[]int32)(p.p) } +func (p pointer) Int64() *int64 { return (*int64)(p.p) } +func (p pointer) Int64Ptr() **int64 { return (**int64)(p.p) } +func (p pointer) Int64Slice() *[]int64 { return (*[]int64)(p.p) } +func (p pointer) Uint32() *uint32 { return (*uint32)(p.p) } +func (p pointer) Uint32Ptr() **uint32 { return (**uint32)(p.p) } +func (p pointer) Uint32Slice() *[]uint32 { return (*[]uint32)(p.p) } +func (p pointer) Uint64() *uint64 { return (*uint64)(p.p) } +func (p pointer) Uint64Ptr() **uint64 { return (**uint64)(p.p) } +func (p pointer) Uint64Slice() *[]uint64 { return (*[]uint64)(p.p) } +func (p pointer) Float32() *float32 { return (*float32)(p.p) } +func (p pointer) Float32Ptr() **float32 { return (**float32)(p.p) } +func (p pointer) Float32Slice() *[]float32 { return (*[]float32)(p.p) } +func (p pointer) Float64() *float64 { return (*float64)(p.p) } +func (p pointer) Float64Ptr() **float64 { return (**float64)(p.p) } +func (p pointer) Float64Slice() *[]float64 { return (*[]float64)(p.p) } +func (p pointer) String() *string { return (*string)(p.p) } +func (p pointer) StringPtr() **string { return (**string)(p.p) } +func (p pointer) StringSlice() *[]string { return (*[]string)(p.p) } +func (p pointer) Bytes() *[]byte { return (*[]byte)(p.p) } +func (p pointer) BytesSlice() *[][]byte { return (*[][]byte)(p.p) } +func (p pointer) WeakFields() *weakFields { return (*weakFields)(p.p) } +func (p pointer) Extensions() *map[int32]ExtensionField { return (*map[int32]ExtensionField)(p.p) } + +func (p pointer) Elem() pointer { + return pointer{p: *(*unsafe.Pointer)(p.p)} +} + +// PointerSlice loads []*T from p as a []pointer. +// The value returned is aliased with the original slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) PointerSlice() []pointer { + // Super-tricky - p should point to a []*T where T is a + // message type. We load it as []pointer. + return *(*[]pointer)(p.p) +} + +// AppendPointerSlice appends v to p, which must be a []*T. +func (p pointer) AppendPointerSlice(v pointer) { + *(*[]pointer)(p.p) = append(*(*[]pointer)(p.p), v) +} + +// SetPointer sets *p to v. +func (p pointer) SetPointer(v pointer) { + *(*unsafe.Pointer)(p.p) = (unsafe.Pointer)(v.p) +} + +// Static check that MessageState does not exceed the size of a pointer. +const _ = uint(unsafe.Sizeof(unsafe.Pointer(nil)) - unsafe.Sizeof(MessageState{})) + +func (Export) MessageStateOf(p Pointer) *messageState { + // Super-tricky - see documentation on MessageState. + return (*messageState)(unsafe.Pointer(p)) +} +func (ms *messageState) pointer() pointer { + // Super-tricky - see documentation on MessageState. + return pointer{p: unsafe.Pointer(ms)} +} +func (ms *messageState) messageInfo() *MessageInfo { + mi := ms.LoadMessageInfo() + if mi == nil { + panic("invalid nil message info; this suggests memory corruption due to a race or shallow copy on the message struct") + } + return mi +} +func (ms *messageState) LoadMessageInfo() *MessageInfo { + return (*MessageInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&ms.atomicMessageInfo)))) +} +func (ms *messageState) StoreMessageInfo(mi *MessageInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&ms.atomicMessageInfo)), unsafe.Pointer(mi)) +} + +type atomicNilMessage struct{ p unsafe.Pointer } // p is a *messageReflectWrapper + +func (m *atomicNilMessage) Init(mi *MessageInfo) *messageReflectWrapper { + if p := atomic.LoadPointer(&m.p); p != nil { + return (*messageReflectWrapper)(p) + } + w := &messageReflectWrapper{mi: mi} + atomic.CompareAndSwapPointer(&m.p, nil, (unsafe.Pointer)(w)) + return (*messageReflectWrapper)(atomic.LoadPointer(&m.p)) +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/validate.go b/vendor/google.golang.org/protobuf/internal/impl/validate.go new file mode 100644 index 00000000000..08cfb6054b4 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/validate.go @@ -0,0 +1,576 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + "math" + "math/bits" + "reflect" + "unicode/utf8" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/strs" + pref "google.golang.org/protobuf/reflect/protoreflect" + preg "google.golang.org/protobuf/reflect/protoregistry" + piface "google.golang.org/protobuf/runtime/protoiface" +) + +// ValidationStatus is the result of validating the wire-format encoding of a message. +type ValidationStatus int + +const ( + // ValidationUnknown indicates that unmarshaling the message might succeed or fail. + // The validator was unable to render a judgement. + // + // The only causes of this status are an aberrant message type appearing somewhere + // in the message or a failure in the extension resolver. + ValidationUnknown ValidationStatus = iota + 1 + + // ValidationInvalid indicates that unmarshaling the message will fail. + ValidationInvalid + + // ValidationValid indicates that unmarshaling the message will succeed. + ValidationValid +) + +func (v ValidationStatus) String() string { + switch v { + case ValidationUnknown: + return "ValidationUnknown" + case ValidationInvalid: + return "ValidationInvalid" + case ValidationValid: + return "ValidationValid" + default: + return fmt.Sprintf("ValidationStatus(%d)", int(v)) + } +} + +// Validate determines whether the contents of the buffer are a valid wire encoding +// of the message type. +// +// This function is exposed for testing. +func Validate(mt pref.MessageType, in piface.UnmarshalInput) (out piface.UnmarshalOutput, _ ValidationStatus) { + mi, ok := mt.(*MessageInfo) + if !ok { + return out, ValidationUnknown + } + if in.Resolver == nil { + in.Resolver = preg.GlobalTypes + } + o, st := mi.validate(in.Buf, 0, unmarshalOptions{ + flags: in.Flags, + resolver: in.Resolver, + }) + if o.initialized { + out.Flags |= piface.UnmarshalInitialized + } + return out, st +} + +type validationInfo struct { + mi *MessageInfo + typ validationType + keyType, valType validationType + + // For non-required fields, requiredBit is 0. + // + // For required fields, requiredBit's nth bit is set, where n is a + // unique index in the range [0, MessageInfo.numRequiredFields). + // + // If there are more than 64 required fields, requiredBit is 0. + requiredBit uint64 +} + +type validationType uint8 + +const ( + validationTypeOther validationType = iota + validationTypeMessage + validationTypeGroup + validationTypeMap + validationTypeRepeatedVarint + validationTypeRepeatedFixed32 + validationTypeRepeatedFixed64 + validationTypeVarint + validationTypeFixed32 + validationTypeFixed64 + validationTypeBytes + validationTypeUTF8String + validationTypeMessageSetItem +) + +func newFieldValidationInfo(mi *MessageInfo, si structInfo, fd pref.FieldDescriptor, ft reflect.Type) validationInfo { + var vi validationInfo + switch { + case fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic(): + switch fd.Kind() { + case pref.MessageKind: + vi.typ = validationTypeMessage + if ot, ok := si.oneofWrappersByNumber[fd.Number()]; ok { + vi.mi = getMessageInfo(ot.Field(0).Type) + } + case pref.GroupKind: + vi.typ = validationTypeGroup + if ot, ok := si.oneofWrappersByNumber[fd.Number()]; ok { + vi.mi = getMessageInfo(ot.Field(0).Type) + } + case pref.StringKind: + if strs.EnforceUTF8(fd) { + vi.typ = validationTypeUTF8String + } + } + default: + vi = newValidationInfo(fd, ft) + } + if fd.Cardinality() == pref.Required { + // Avoid overflow. The required field check is done with a 64-bit mask, with + // any message containing more than 64 required fields always reported as + // potentially uninitialized, so it is not important to get a precise count + // of the required fields past 64. + if mi.numRequiredFields < math.MaxUint8 { + mi.numRequiredFields++ + vi.requiredBit = 1 << (mi.numRequiredFields - 1) + } + } + return vi +} + +func newValidationInfo(fd pref.FieldDescriptor, ft reflect.Type) validationInfo { + var vi validationInfo + switch { + case fd.IsList(): + switch fd.Kind() { + case pref.MessageKind: + vi.typ = validationTypeMessage + if ft.Kind() == reflect.Slice { + vi.mi = getMessageInfo(ft.Elem()) + } + case pref.GroupKind: + vi.typ = validationTypeGroup + if ft.Kind() == reflect.Slice { + vi.mi = getMessageInfo(ft.Elem()) + } + case pref.StringKind: + vi.typ = validationTypeBytes + if strs.EnforceUTF8(fd) { + vi.typ = validationTypeUTF8String + } + default: + switch wireTypes[fd.Kind()] { + case protowire.VarintType: + vi.typ = validationTypeRepeatedVarint + case protowire.Fixed32Type: + vi.typ = validationTypeRepeatedFixed32 + case protowire.Fixed64Type: + vi.typ = validationTypeRepeatedFixed64 + } + } + case fd.IsMap(): + vi.typ = validationTypeMap + switch fd.MapKey().Kind() { + case pref.StringKind: + if strs.EnforceUTF8(fd) { + vi.keyType = validationTypeUTF8String + } + } + switch fd.MapValue().Kind() { + case pref.MessageKind: + vi.valType = validationTypeMessage + if ft.Kind() == reflect.Map { + vi.mi = getMessageInfo(ft.Elem()) + } + case pref.StringKind: + if strs.EnforceUTF8(fd) { + vi.valType = validationTypeUTF8String + } + } + default: + switch fd.Kind() { + case pref.MessageKind: + vi.typ = validationTypeMessage + if !fd.IsWeak() { + vi.mi = getMessageInfo(ft) + } + case pref.GroupKind: + vi.typ = validationTypeGroup + vi.mi = getMessageInfo(ft) + case pref.StringKind: + vi.typ = validationTypeBytes + if strs.EnforceUTF8(fd) { + vi.typ = validationTypeUTF8String + } + default: + switch wireTypes[fd.Kind()] { + case protowire.VarintType: + vi.typ = validationTypeVarint + case protowire.Fixed32Type: + vi.typ = validationTypeFixed32 + case protowire.Fixed64Type: + vi.typ = validationTypeFixed64 + case protowire.BytesType: + vi.typ = validationTypeBytes + } + } + } + return vi +} + +func (mi *MessageInfo) validate(b []byte, groupTag protowire.Number, opts unmarshalOptions) (out unmarshalOutput, result ValidationStatus) { + mi.init() + type validationState struct { + typ validationType + keyType, valType validationType + endGroup protowire.Number + mi *MessageInfo + tail []byte + requiredMask uint64 + } + + // Pre-allocate some slots to avoid repeated slice reallocation. + states := make([]validationState, 0, 16) + states = append(states, validationState{ + typ: validationTypeMessage, + mi: mi, + }) + if groupTag > 0 { + states[0].typ = validationTypeGroup + states[0].endGroup = groupTag + } + initialized := true + start := len(b) +State: + for len(states) > 0 { + st := &states[len(states)-1] + for len(b) > 0 { + // Parse the tag (field number and wire type). + var tag uint64 + if b[0] < 0x80 { + tag = uint64(b[0]) + b = b[1:] + } else if len(b) >= 2 && b[1] < 128 { + tag = uint64(b[0]&0x7f) + uint64(b[1])<<7 + b = b[2:] + } else { + var n int + tag, n = protowire.ConsumeVarint(b) + if n < 0 { + return out, ValidationInvalid + } + b = b[n:] + } + var num protowire.Number + if n := tag >> 3; n < uint64(protowire.MinValidNumber) || n > uint64(protowire.MaxValidNumber) { + return out, ValidationInvalid + } else { + num = protowire.Number(n) + } + wtyp := protowire.Type(tag & 7) + + if wtyp == protowire.EndGroupType { + if st.endGroup == num { + goto PopState + } + return out, ValidationInvalid + } + var vi validationInfo + switch { + case st.typ == validationTypeMap: + switch num { + case genid.MapEntry_Key_field_number: + vi.typ = st.keyType + case genid.MapEntry_Value_field_number: + vi.typ = st.valType + vi.mi = st.mi + vi.requiredBit = 1 + } + case flags.ProtoLegacy && st.mi.isMessageSet: + switch num { + case messageset.FieldItem: + vi.typ = validationTypeMessageSetItem + } + default: + var f *coderFieldInfo + if int(num) < len(st.mi.denseCoderFields) { + f = st.mi.denseCoderFields[num] + } else { + f = st.mi.coderFields[num] + } + if f != nil { + vi = f.validation + if vi.typ == validationTypeMessage && vi.mi == nil { + // Probable weak field. + // + // TODO: Consider storing the results of this lookup somewhere + // rather than recomputing it on every validation. + fd := st.mi.Desc.Fields().ByNumber(num) + if fd == nil || !fd.IsWeak() { + break + } + messageName := fd.Message().FullName() + messageType, err := preg.GlobalTypes.FindMessageByName(messageName) + switch err { + case nil: + vi.mi, _ = messageType.(*MessageInfo) + case preg.NotFound: + vi.typ = validationTypeBytes + default: + return out, ValidationUnknown + } + } + break + } + // Possible extension field. + // + // TODO: We should return ValidationUnknown when: + // 1. The resolver is not frozen. (More extensions may be added to it.) + // 2. The resolver returns preg.NotFound. + // In this case, a type added to the resolver in the future could cause + // unmarshaling to begin failing. Supporting this requires some way to + // determine if the resolver is frozen. + xt, err := opts.resolver.FindExtensionByNumber(st.mi.Desc.FullName(), num) + if err != nil && err != preg.NotFound { + return out, ValidationUnknown + } + if err == nil { + vi = getExtensionFieldInfo(xt).validation + } + } + if vi.requiredBit != 0 { + // Check that the field has a compatible wire type. + // We only need to consider non-repeated field types, + // since repeated fields (and maps) can never be required. + ok := false + switch vi.typ { + case validationTypeVarint: + ok = wtyp == protowire.VarintType + case validationTypeFixed32: + ok = wtyp == protowire.Fixed32Type + case validationTypeFixed64: + ok = wtyp == protowire.Fixed64Type + case validationTypeBytes, validationTypeUTF8String, validationTypeMessage: + ok = wtyp == protowire.BytesType + case validationTypeGroup: + ok = wtyp == protowire.StartGroupType + } + if ok { + st.requiredMask |= vi.requiredBit + } + } + + switch wtyp { + case protowire.VarintType: + if len(b) >= 10 { + switch { + case b[0] < 0x80: + b = b[1:] + case b[1] < 0x80: + b = b[2:] + case b[2] < 0x80: + b = b[3:] + case b[3] < 0x80: + b = b[4:] + case b[4] < 0x80: + b = b[5:] + case b[5] < 0x80: + b = b[6:] + case b[6] < 0x80: + b = b[7:] + case b[7] < 0x80: + b = b[8:] + case b[8] < 0x80: + b = b[9:] + case b[9] < 0x80 && b[9] < 2: + b = b[10:] + default: + return out, ValidationInvalid + } + } else { + switch { + case len(b) > 0 && b[0] < 0x80: + b = b[1:] + case len(b) > 1 && b[1] < 0x80: + b = b[2:] + case len(b) > 2 && b[2] < 0x80: + b = b[3:] + case len(b) > 3 && b[3] < 0x80: + b = b[4:] + case len(b) > 4 && b[4] < 0x80: + b = b[5:] + case len(b) > 5 && b[5] < 0x80: + b = b[6:] + case len(b) > 6 && b[6] < 0x80: + b = b[7:] + case len(b) > 7 && b[7] < 0x80: + b = b[8:] + case len(b) > 8 && b[8] < 0x80: + b = b[9:] + case len(b) > 9 && b[9] < 2: + b = b[10:] + default: + return out, ValidationInvalid + } + } + continue State + case protowire.BytesType: + var size uint64 + if len(b) >= 1 && b[0] < 0x80 { + size = uint64(b[0]) + b = b[1:] + } else if len(b) >= 2 && b[1] < 128 { + size = uint64(b[0]&0x7f) + uint64(b[1])<<7 + b = b[2:] + } else { + var n int + size, n = protowire.ConsumeVarint(b) + if n < 0 { + return out, ValidationInvalid + } + b = b[n:] + } + if size > uint64(len(b)) { + return out, ValidationInvalid + } + v := b[:size] + b = b[size:] + switch vi.typ { + case validationTypeMessage: + if vi.mi == nil { + return out, ValidationUnknown + } + vi.mi.init() + fallthrough + case validationTypeMap: + if vi.mi != nil { + vi.mi.init() + } + states = append(states, validationState{ + typ: vi.typ, + keyType: vi.keyType, + valType: vi.valType, + mi: vi.mi, + tail: b, + }) + b = v + continue State + case validationTypeRepeatedVarint: + // Packed field. + for len(v) > 0 { + _, n := protowire.ConsumeVarint(v) + if n < 0 { + return out, ValidationInvalid + } + v = v[n:] + } + case validationTypeRepeatedFixed32: + // Packed field. + if len(v)%4 != 0 { + return out, ValidationInvalid + } + case validationTypeRepeatedFixed64: + // Packed field. + if len(v)%8 != 0 { + return out, ValidationInvalid + } + case validationTypeUTF8String: + if !utf8.Valid(v) { + return out, ValidationInvalid + } + } + case protowire.Fixed32Type: + if len(b) < 4 { + return out, ValidationInvalid + } + b = b[4:] + case protowire.Fixed64Type: + if len(b) < 8 { + return out, ValidationInvalid + } + b = b[8:] + case protowire.StartGroupType: + switch { + case vi.typ == validationTypeGroup: + if vi.mi == nil { + return out, ValidationUnknown + } + vi.mi.init() + states = append(states, validationState{ + typ: validationTypeGroup, + mi: vi.mi, + endGroup: num, + }) + continue State + case flags.ProtoLegacy && vi.typ == validationTypeMessageSetItem: + typeid, v, n, err := messageset.ConsumeFieldValue(b, false) + if err != nil { + return out, ValidationInvalid + } + xt, err := opts.resolver.FindExtensionByNumber(st.mi.Desc.FullName(), typeid) + switch { + case err == preg.NotFound: + b = b[n:] + case err != nil: + return out, ValidationUnknown + default: + xvi := getExtensionFieldInfo(xt).validation + if xvi.mi != nil { + xvi.mi.init() + } + states = append(states, validationState{ + typ: xvi.typ, + mi: xvi.mi, + tail: b[n:], + }) + b = v + continue State + } + default: + n := protowire.ConsumeFieldValue(num, wtyp, b) + if n < 0 { + return out, ValidationInvalid + } + b = b[n:] + } + default: + return out, ValidationInvalid + } + } + if st.endGroup != 0 { + return out, ValidationInvalid + } + if len(b) != 0 { + return out, ValidationInvalid + } + b = st.tail + PopState: + numRequiredFields := 0 + switch st.typ { + case validationTypeMessage, validationTypeGroup: + numRequiredFields = int(st.mi.numRequiredFields) + case validationTypeMap: + // If this is a map field with a message value that contains + // required fields, require that the value be present. + if st.mi != nil && st.mi.numRequiredFields > 0 { + numRequiredFields = 1 + } + } + // If there are more than 64 required fields, this check will + // always fail and we will report that the message is potentially + // uninitialized. + if numRequiredFields > 0 && bits.OnesCount64(st.requiredMask) != numRequiredFields { + initialized = false + } + states = states[:len(states)-1] + } + out.n = start - len(b) + if initialized { + out.initialized = true + } + return out, ValidationValid +} diff --git a/vendor/google.golang.org/protobuf/internal/impl/weak.go b/vendor/google.golang.org/protobuf/internal/impl/weak.go new file mode 100644 index 00000000000..009cbefd1ed --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/impl/weak.go @@ -0,0 +1,74 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package impl + +import ( + "fmt" + + pref "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +// weakFields adds methods to the exported WeakFields type for internal use. +// +// The exported type is an alias to an unnamed type, so methods can't be +// defined directly on it. +type weakFields WeakFields + +func (w weakFields) get(num pref.FieldNumber) (pref.ProtoMessage, bool) { + m, ok := w[int32(num)] + return m, ok +} + +func (w *weakFields) set(num pref.FieldNumber, m pref.ProtoMessage) { + if *w == nil { + *w = make(weakFields) + } + (*w)[int32(num)] = m +} + +func (w *weakFields) clear(num pref.FieldNumber) { + delete(*w, int32(num)) +} + +func (Export) HasWeak(w WeakFields, num pref.FieldNumber) bool { + _, ok := w[int32(num)] + return ok +} + +func (Export) ClearWeak(w *WeakFields, num pref.FieldNumber) { + delete(*w, int32(num)) +} + +func (Export) GetWeak(w WeakFields, num pref.FieldNumber, name pref.FullName) pref.ProtoMessage { + if m, ok := w[int32(num)]; ok { + return m + } + mt, _ := protoregistry.GlobalTypes.FindMessageByName(name) + if mt == nil { + panic(fmt.Sprintf("message %v for weak field is not linked in", name)) + } + return mt.Zero().Interface() +} + +func (Export) SetWeak(w *WeakFields, num pref.FieldNumber, name pref.FullName, m pref.ProtoMessage) { + if m != nil { + mt, _ := protoregistry.GlobalTypes.FindMessageByName(name) + if mt == nil { + panic(fmt.Sprintf("message %v for weak field is not linked in", name)) + } + if mt != m.ProtoReflect().Type() { + panic(fmt.Sprintf("invalid message type for weak field: got %T, want %T", m, mt.Zero().Interface())) + } + } + if m == nil || !m.ProtoReflect().IsValid() { + delete(*w, int32(num)) + return + } + if *w == nil { + *w = make(weakFields) + } + (*w)[int32(num)] = m +} diff --git a/vendor/google.golang.org/protobuf/internal/mapsort/mapsort.go b/vendor/google.golang.org/protobuf/internal/mapsort/mapsort.go new file mode 100644 index 00000000000..a3de1cf3241 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/mapsort/mapsort.go @@ -0,0 +1,43 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package mapsort provides sorted access to maps. +package mapsort + +import ( + "sort" + + "google.golang.org/protobuf/reflect/protoreflect" +) + +// Range iterates over every map entry in sorted key order, +// calling f for each key and value encountered. +func Range(mapv protoreflect.Map, keyKind protoreflect.Kind, f func(protoreflect.MapKey, protoreflect.Value) bool) { + var keys []protoreflect.MapKey + mapv.Range(func(key protoreflect.MapKey, _ protoreflect.Value) bool { + keys = append(keys, key) + return true + }) + sort.Slice(keys, func(i, j int) bool { + switch keyKind { + case protoreflect.BoolKind: + return !keys[i].Bool() && keys[j].Bool() + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, + protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: + return keys[i].Int() < keys[j].Int() + case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, + protoreflect.Uint64Kind, protoreflect.Fixed64Kind: + return keys[i].Uint() < keys[j].Uint() + case protoreflect.StringKind: + return keys[i].String() < keys[j].String() + default: + panic("invalid kind: " + keyKind.String()) + } + }) + for _, key := range keys { + if !f(key, mapv.Get(key)) { + break + } + } +} diff --git a/vendor/google.golang.org/protobuf/internal/pragma/pragma.go b/vendor/google.golang.org/protobuf/internal/pragma/pragma.go new file mode 100644 index 00000000000..49dc4fcd98e --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/pragma/pragma.go @@ -0,0 +1,29 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package pragma provides types that can be embedded into a struct to +// statically enforce or prevent certain language properties. +package pragma + +import "sync" + +// NoUnkeyedLiterals can be embedded in a struct to prevent unkeyed literals. +type NoUnkeyedLiterals struct{} + +// DoNotImplement can be embedded in an interface to prevent trivial +// implementations of the interface. +// +// This is useful to prevent unauthorized implementations of an interface +// so that it can be extended in the future for any protobuf language changes. +type DoNotImplement interface{ ProtoInternal(DoNotImplement) } + +// DoNotCompare can be embedded in a struct to prevent comparability. +type DoNotCompare [0]func() + +// DoNotCopy can be embedded in a struct to help prevent shallow copies. +// This does not rely on a Go language feature, but rather a special case +// within the vet checker. +// +// See https://golang.org/issues/8005. +type DoNotCopy [0]sync.Mutex diff --git a/vendor/google.golang.org/protobuf/internal/set/ints.go b/vendor/google.golang.org/protobuf/internal/set/ints.go new file mode 100644 index 00000000000..d3d7f89ab55 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/set/ints.go @@ -0,0 +1,58 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package set provides simple set data structures for uint64s. +package set + +import "math/bits" + +// int64s represents a set of integers within the range of 0..63. +type int64s uint64 + +func (bs *int64s) Len() int { + return bits.OnesCount64(uint64(*bs)) +} +func (bs *int64s) Has(n uint64) bool { + return uint64(*bs)&(uint64(1)< 0 +} +func (bs *int64s) Set(n uint64) { + *(*uint64)(bs) |= uint64(1) << n +} +func (bs *int64s) Clear(n uint64) { + *(*uint64)(bs) &^= uint64(1) << n +} + +// Ints represents a set of integers within the range of 0..math.MaxUint64. +type Ints struct { + lo int64s + hi map[uint64]struct{} +} + +func (bs *Ints) Len() int { + return bs.lo.Len() + len(bs.hi) +} +func (bs *Ints) Has(n uint64) bool { + if n < 64 { + return bs.lo.Has(n) + } + _, ok := bs.hi[n] + return ok +} +func (bs *Ints) Set(n uint64) { + if n < 64 { + bs.lo.Set(n) + return + } + if bs.hi == nil { + bs.hi = make(map[uint64]struct{}) + } + bs.hi[n] = struct{}{} +} +func (bs *Ints) Clear(n uint64) { + if n < 64 { + bs.lo.Clear(n) + return + } + delete(bs.hi, n) +} diff --git a/vendor/google.golang.org/protobuf/internal/strs/strings.go b/vendor/google.golang.org/protobuf/internal/strs/strings.go new file mode 100644 index 00000000000..0b74e76586b --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/strs/strings.go @@ -0,0 +1,196 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package strs provides string manipulation functionality specific to protobuf. +package strs + +import ( + "go/token" + "strings" + "unicode" + "unicode/utf8" + + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/reflect/protoreflect" +) + +// EnforceUTF8 reports whether to enforce strict UTF-8 validation. +func EnforceUTF8(fd protoreflect.FieldDescriptor) bool { + if flags.ProtoLegacy { + if fd, ok := fd.(interface{ EnforceUTF8() bool }); ok { + return fd.EnforceUTF8() + } + } + return fd.Syntax() == protoreflect.Proto3 +} + +// GoCamelCase camel-cases a protobuf name for use as a Go identifier. +// +// If there is an interior underscore followed by a lower case letter, +// drop the underscore and convert the letter to upper case. +func GoCamelCase(s string) string { + // Invariant: if the next letter is lower case, it must be converted + // to upper case. + // That is, we process a word at a time, where words are marked by _ or + // upper case letter. Digits are treated as words. + var b []byte + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case c == '.' && i+1 < len(s) && isASCIILower(s[i+1]): + // Skip over '.' in ".{{lowercase}}". + case c == '.': + b = append(b, '_') // convert '.' to '_' + case c == '_' && (i == 0 || s[i-1] == '.'): + // Convert initial '_' to ensure we start with a capital letter. + // Do the same for '_' after '.' to match historic behavior. + b = append(b, 'X') // convert '_' to 'X' + case c == '_' && i+1 < len(s) && isASCIILower(s[i+1]): + // Skip over '_' in "_{{lowercase}}". + case isASCIIDigit(c): + b = append(b, c) + default: + // Assume we have a letter now - if not, it's a bogus identifier. + // The next word is a sequence of characters that must start upper case. + if isASCIILower(c) { + c -= 'a' - 'A' // convert lowercase to uppercase + } + b = append(b, c) + + // Accept lower case sequence that follows. + for ; i+1 < len(s) && isASCIILower(s[i+1]); i++ { + b = append(b, s[i+1]) + } + } + } + return string(b) +} + +// GoSanitized converts a string to a valid Go identifier. +func GoSanitized(s string) string { + // Sanitize the input to the set of valid characters, + // which must be '_' or be in the Unicode L or N categories. + s = strings.Map(func(r rune) rune { + if unicode.IsLetter(r) || unicode.IsDigit(r) { + return r + } + return '_' + }, s) + + // Prepend '_' in the event of a Go keyword conflict or if + // the identifier is invalid (does not start in the Unicode L category). + r, _ := utf8.DecodeRuneInString(s) + if token.Lookup(s).IsKeyword() || !unicode.IsLetter(r) { + return "_" + s + } + return s +} + +// JSONCamelCase converts a snake_case identifier to a camelCase identifier, +// according to the protobuf JSON specification. +func JSONCamelCase(s string) string { + var b []byte + var wasUnderscore bool + for i := 0; i < len(s); i++ { // proto identifiers are always ASCII + c := s[i] + if c != '_' { + if wasUnderscore && isASCIILower(c) { + c -= 'a' - 'A' // convert to uppercase + } + b = append(b, c) + } + wasUnderscore = c == '_' + } + return string(b) +} + +// JSONSnakeCase converts a camelCase identifier to a snake_case identifier, +// according to the protobuf JSON specification. +func JSONSnakeCase(s string) string { + var b []byte + for i := 0; i < len(s); i++ { // proto identifiers are always ASCII + c := s[i] + if isASCIIUpper(c) { + b = append(b, '_') + c += 'a' - 'A' // convert to lowercase + } + b = append(b, c) + } + return string(b) +} + +// MapEntryName derives the name of the map entry message given the field name. +// See protoc v3.8.0: src/google/protobuf/descriptor.cc:254-276,6057 +func MapEntryName(s string) string { + var b []byte + upperNext := true + for _, c := range s { + switch { + case c == '_': + upperNext = true + case upperNext: + b = append(b, byte(unicode.ToUpper(c))) + upperNext = false + default: + b = append(b, byte(c)) + } + } + b = append(b, "Entry"...) + return string(b) +} + +// EnumValueName derives the camel-cased enum value name. +// See protoc v3.8.0: src/google/protobuf/descriptor.cc:297-313 +func EnumValueName(s string) string { + var b []byte + upperNext := true + for _, c := range s { + switch { + case c == '_': + upperNext = true + case upperNext: + b = append(b, byte(unicode.ToUpper(c))) + upperNext = false + default: + b = append(b, byte(unicode.ToLower(c))) + upperNext = false + } + } + return string(b) +} + +// TrimEnumPrefix trims the enum name prefix from an enum value name, +// where the prefix is all lowercase without underscores. +// See protoc v3.8.0: src/google/protobuf/descriptor.cc:330-375 +func TrimEnumPrefix(s, prefix string) string { + s0 := s // original input + for len(s) > 0 && len(prefix) > 0 { + if s[0] == '_' { + s = s[1:] + continue + } + if unicode.ToLower(rune(s[0])) != rune(prefix[0]) { + return s0 // no prefix match + } + s, prefix = s[1:], prefix[1:] + } + if len(prefix) > 0 { + return s0 // no prefix match + } + s = strings.TrimLeft(s, "_") + if len(s) == 0 { + return s0 // avoid returning empty string + } + return s +} + +func isASCIILower(c byte) bool { + return 'a' <= c && c <= 'z' +} +func isASCIIUpper(c byte) bool { + return 'A' <= c && c <= 'Z' +} +func isASCIIDigit(c byte) bool { + return '0' <= c && c <= '9' +} diff --git a/vendor/google.golang.org/protobuf/internal/strs/strings_pure.go b/vendor/google.golang.org/protobuf/internal/strs/strings_pure.go new file mode 100644 index 00000000000..85e074c977d --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/strs/strings_pure.go @@ -0,0 +1,27 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build purego appengine + +package strs + +import pref "google.golang.org/protobuf/reflect/protoreflect" + +func UnsafeString(b []byte) string { + return string(b) +} + +func UnsafeBytes(s string) []byte { + return []byte(s) +} + +type Builder struct{} + +func (*Builder) AppendFullName(prefix pref.FullName, name pref.Name) pref.FullName { + return prefix.Append(name) +} + +func (*Builder) MakeString(b []byte) string { + return string(b) +} diff --git a/vendor/google.golang.org/protobuf/internal/strs/strings_unsafe.go b/vendor/google.golang.org/protobuf/internal/strs/strings_unsafe.go new file mode 100644 index 00000000000..2160c701914 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/strs/strings_unsafe.go @@ -0,0 +1,94 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !purego,!appengine + +package strs + +import ( + "unsafe" + + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +type ( + stringHeader struct { + Data unsafe.Pointer + Len int + } + sliceHeader struct { + Data unsafe.Pointer + Len int + Cap int + } +) + +// UnsafeString returns an unsafe string reference of b. +// The caller must treat the input slice as immutable. +// +// WARNING: Use carefully. The returned result must not leak to the end user +// unless the input slice is provably immutable. +func UnsafeString(b []byte) (s string) { + src := (*sliceHeader)(unsafe.Pointer(&b)) + dst := (*stringHeader)(unsafe.Pointer(&s)) + dst.Data = src.Data + dst.Len = src.Len + return s +} + +// UnsafeBytes returns an unsafe bytes slice reference of s. +// The caller must treat returned slice as immutable. +// +// WARNING: Use carefully. The returned result must not leak to the end user. +func UnsafeBytes(s string) (b []byte) { + src := (*stringHeader)(unsafe.Pointer(&s)) + dst := (*sliceHeader)(unsafe.Pointer(&b)) + dst.Data = src.Data + dst.Len = src.Len + dst.Cap = src.Len + return b +} + +// Builder builds a set of strings with shared lifetime. +// This differs from strings.Builder, which is for building a single string. +type Builder struct { + buf []byte +} + +// AppendFullName is equivalent to protoreflect.FullName.Append, +// but optimized for large batches where each name has a shared lifetime. +func (sb *Builder) AppendFullName(prefix pref.FullName, name pref.Name) pref.FullName { + n := len(prefix) + len(".") + len(name) + if len(prefix) == 0 { + n -= len(".") + } + sb.grow(n) + sb.buf = append(sb.buf, prefix...) + sb.buf = append(sb.buf, '.') + sb.buf = append(sb.buf, name...) + return pref.FullName(sb.last(n)) +} + +// MakeString is equivalent to string(b), but optimized for large batches +// with a shared lifetime. +func (sb *Builder) MakeString(b []byte) string { + sb.grow(len(b)) + sb.buf = append(sb.buf, b...) + return sb.last(len(b)) +} + +func (sb *Builder) grow(n int) { + if cap(sb.buf)-len(sb.buf) >= n { + return + } + + // Unlike strings.Builder, we do not need to copy over the contents + // of the old buffer since our builder provides no API for + // retrieving previously created strings. + sb.buf = make([]byte, 2*(cap(sb.buf)+n)) +} + +func (sb *Builder) last(n int) string { + return UnsafeString(sb.buf[len(sb.buf)-n:]) +} diff --git a/vendor/google.golang.org/protobuf/internal/version/version.go b/vendor/google.golang.org/protobuf/internal/version/version.go new file mode 100644 index 00000000000..72cf770b427 --- /dev/null +++ b/vendor/google.golang.org/protobuf/internal/version/version.go @@ -0,0 +1,79 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package version records versioning information about this module. +package version + +import ( + "fmt" + "strings" +) + +// These constants determine the current version of this module. +// +// +// For our release process, we enforce the following rules: +// * Tagged releases use a tag that is identical to String. +// * Tagged releases never reference a commit where the String +// contains "devel". +// * The set of all commits in this repository where String +// does not contain "devel" must have a unique String. +// +// +// Steps for tagging a new release: +// 1. Create a new CL. +// +// 2. Update Minor, Patch, and/or PreRelease as necessary. +// PreRelease must not contain the string "devel". +// +// 3. Since the last released minor version, have there been any changes to +// generator that relies on new functionality in the runtime? +// If yes, then increment RequiredGenerated. +// +// 4. Since the last released minor version, have there been any changes to +// the runtime that removes support for old .pb.go source code? +// If yes, then increment SupportMinimum. +// +// 5. Send out the CL for review and submit it. +// Note that the next CL in step 8 must be submitted after this CL +// without any other CLs in-between. +// +// 6. Tag a new version, where the tag is is the current String. +// +// 7. Write release notes for all notable changes +// between this release and the last release. +// +// 8. Create a new CL. +// +// 9. Update PreRelease to include the string "devel". +// For example: "" -> "devel" or "rc.1" -> "rc.1.devel" +// +// 10. Send out the CL for review and submit it. +const ( + Major = 1 + Minor = 25 + Patch = 0 + PreRelease = "" +) + +// String formats the version string for this module in semver format. +// +// Examples: +// v1.20.1 +// v1.21.0-rc.1 +func String() string { + v := fmt.Sprintf("v%d.%d.%d", Major, Minor, Patch) + if PreRelease != "" { + v += "-" + PreRelease + + // TODO: Add metadata about the commit or build hash. + // See https://golang.org/issue/29814 + // See https://golang.org/issue/33533 + var metadata string + if strings.Contains(PreRelease, "devel") && metadata != "" { + v += "+" + metadata + } + } + return v +} diff --git a/vendor/google.golang.org/protobuf/proto/checkinit.go b/vendor/google.golang.org/protobuf/proto/checkinit.go new file mode 100644 index 00000000000..3e9a6a2f66c --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/checkinit.go @@ -0,0 +1,71 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoiface" +) + +// CheckInitialized returns an error if any required fields in m are not set. +func CheckInitialized(m Message) error { + // Treat a nil message interface as an "untyped" empty message, + // which we assume to have no required fields. + if m == nil { + return nil + } + + return checkInitialized(m.ProtoReflect()) +} + +// CheckInitialized returns an error if any required fields in m are not set. +func checkInitialized(m protoreflect.Message) error { + if methods := protoMethods(m); methods != nil && methods.CheckInitialized != nil { + _, err := methods.CheckInitialized(protoiface.CheckInitializedInput{ + Message: m, + }) + return err + } + return checkInitializedSlow(m) +} + +func checkInitializedSlow(m protoreflect.Message) error { + md := m.Descriptor() + fds := md.Fields() + for i, nums := 0, md.RequiredNumbers(); i < nums.Len(); i++ { + fd := fds.ByNumber(nums.Get(i)) + if !m.Has(fd) { + return errors.RequiredNotSet(string(fd.FullName())) + } + } + var err error + m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + switch { + case fd.IsList(): + if fd.Message() == nil { + return true + } + for i, list := 0, v.List(); i < list.Len() && err == nil; i++ { + err = checkInitialized(list.Get(i).Message()) + } + case fd.IsMap(): + if fd.MapValue().Message() == nil { + return true + } + v.Map().Range(func(key protoreflect.MapKey, v protoreflect.Value) bool { + err = checkInitialized(v.Message()) + return err == nil + }) + default: + if fd.Message() == nil { + return true + } + err = checkInitialized(v.Message()) + } + return err == nil + }) + return err +} diff --git a/vendor/google.golang.org/protobuf/proto/decode.go b/vendor/google.golang.org/protobuf/proto/decode.go new file mode 100644 index 00000000000..42fc5195e87 --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/decode.go @@ -0,0 +1,274 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + "google.golang.org/protobuf/runtime/protoiface" +) + +// UnmarshalOptions configures the unmarshaler. +// +// Example usage: +// err := UnmarshalOptions{DiscardUnknown: true}.Unmarshal(b, m) +type UnmarshalOptions struct { + pragma.NoUnkeyedLiterals + + // Merge merges the input into the destination message. + // The default behavior is to always reset the message before unmarshaling, + // unless Merge is specified. + Merge bool + + // AllowPartial accepts input for messages that will result in missing + // required fields. If AllowPartial is false (the default), Unmarshal will + // return an error if there are any missing required fields. + AllowPartial bool + + // If DiscardUnknown is set, unknown fields are ignored. + DiscardUnknown bool + + // Resolver is used for looking up types when unmarshaling extension fields. + // If nil, this defaults to using protoregistry.GlobalTypes. + Resolver interface { + FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) + FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) + } +} + +// Unmarshal parses the wire-format message in b and places the result in m. +func Unmarshal(b []byte, m Message) error { + _, err := UnmarshalOptions{}.unmarshal(b, m.ProtoReflect()) + return err +} + +// Unmarshal parses the wire-format message in b and places the result in m. +func (o UnmarshalOptions) Unmarshal(b []byte, m Message) error { + _, err := o.unmarshal(b, m.ProtoReflect()) + return err +} + +// UnmarshalState parses a wire-format message and places the result in m. +// +// This method permits fine-grained control over the unmarshaler. +// Most users should use Unmarshal instead. +func (o UnmarshalOptions) UnmarshalState(in protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { + return o.unmarshal(in.Buf, in.Message) +} + +// unmarshal is a centralized function that all unmarshal operations go through. +// For profiling purposes, avoid changing the name of this function or +// introducing other code paths for unmarshal that do not go through this. +func (o UnmarshalOptions) unmarshal(b []byte, m protoreflect.Message) (out protoiface.UnmarshalOutput, err error) { + if o.Resolver == nil { + o.Resolver = protoregistry.GlobalTypes + } + if !o.Merge { + Reset(m.Interface()) + } + allowPartial := o.AllowPartial + o.Merge = true + o.AllowPartial = true + methods := protoMethods(m) + if methods != nil && methods.Unmarshal != nil && + !(o.DiscardUnknown && methods.Flags&protoiface.SupportUnmarshalDiscardUnknown == 0) { + in := protoiface.UnmarshalInput{ + Message: m, + Buf: b, + Resolver: o.Resolver, + } + if o.DiscardUnknown { + in.Flags |= protoiface.UnmarshalDiscardUnknown + } + out, err = methods.Unmarshal(in) + } else { + err = o.unmarshalMessageSlow(b, m) + } + if err != nil { + return out, err + } + if allowPartial || (out.Flags&protoiface.UnmarshalInitialized != 0) { + return out, nil + } + return out, checkInitialized(m) +} + +func (o UnmarshalOptions) unmarshalMessage(b []byte, m protoreflect.Message) error { + _, err := o.unmarshal(b, m) + return err +} + +func (o UnmarshalOptions) unmarshalMessageSlow(b []byte, m protoreflect.Message) error { + md := m.Descriptor() + if messageset.IsMessageSet(md) { + return o.unmarshalMessageSet(b, m) + } + fields := md.Fields() + for len(b) > 0 { + // Parse the tag (field number and wire type). + num, wtyp, tagLen := protowire.ConsumeTag(b) + if tagLen < 0 { + return protowire.ParseError(tagLen) + } + if num > protowire.MaxValidNumber { + return errors.New("invalid field number") + } + + // Find the field descriptor for this field number. + fd := fields.ByNumber(num) + if fd == nil && md.ExtensionRanges().Has(num) { + extType, err := o.Resolver.FindExtensionByNumber(md.FullName(), num) + if err != nil && err != protoregistry.NotFound { + return errors.New("%v: unable to resolve extension %v: %v", md.FullName(), num, err) + } + if extType != nil { + fd = extType.TypeDescriptor() + } + } + var err error + if fd == nil { + err = errUnknown + } else if flags.ProtoLegacy { + if fd.IsWeak() && fd.Message().IsPlaceholder() { + err = errUnknown // weak referent is not linked in + } + } + + // Parse the field value. + var valLen int + switch { + case err != nil: + case fd.IsList(): + valLen, err = o.unmarshalList(b[tagLen:], wtyp, m.Mutable(fd).List(), fd) + case fd.IsMap(): + valLen, err = o.unmarshalMap(b[tagLen:], wtyp, m.Mutable(fd).Map(), fd) + default: + valLen, err = o.unmarshalSingular(b[tagLen:], wtyp, m, fd) + } + if err != nil { + if err != errUnknown { + return err + } + valLen = protowire.ConsumeFieldValue(num, wtyp, b[tagLen:]) + if valLen < 0 { + return protowire.ParseError(valLen) + } + if !o.DiscardUnknown { + m.SetUnknown(append(m.GetUnknown(), b[:tagLen+valLen]...)) + } + } + b = b[tagLen+valLen:] + } + return nil +} + +func (o UnmarshalOptions) unmarshalSingular(b []byte, wtyp protowire.Type, m protoreflect.Message, fd protoreflect.FieldDescriptor) (n int, err error) { + v, n, err := o.unmarshalScalar(b, wtyp, fd) + if err != nil { + return 0, err + } + switch fd.Kind() { + case protoreflect.GroupKind, protoreflect.MessageKind: + m2 := m.Mutable(fd).Message() + if err := o.unmarshalMessage(v.Bytes(), m2); err != nil { + return n, err + } + default: + // Non-message scalars replace the previous value. + m.Set(fd, v) + } + return n, nil +} + +func (o UnmarshalOptions) unmarshalMap(b []byte, wtyp protowire.Type, mapv protoreflect.Map, fd protoreflect.FieldDescriptor) (n int, err error) { + if wtyp != protowire.BytesType { + return 0, errUnknown + } + b, n = protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + var ( + keyField = fd.MapKey() + valField = fd.MapValue() + key protoreflect.Value + val protoreflect.Value + haveKey bool + haveVal bool + ) + switch valField.Kind() { + case protoreflect.GroupKind, protoreflect.MessageKind: + val = mapv.NewValue() + } + // Map entries are represented as a two-element message with fields + // containing the key and value. + for len(b) > 0 { + num, wtyp, n := protowire.ConsumeTag(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + if num > protowire.MaxValidNumber { + return 0, errors.New("invalid field number") + } + b = b[n:] + err = errUnknown + switch num { + case genid.MapEntry_Key_field_number: + key, n, err = o.unmarshalScalar(b, wtyp, keyField) + if err != nil { + break + } + haveKey = true + case genid.MapEntry_Value_field_number: + var v protoreflect.Value + v, n, err = o.unmarshalScalar(b, wtyp, valField) + if err != nil { + break + } + switch valField.Kind() { + case protoreflect.GroupKind, protoreflect.MessageKind: + if err := o.unmarshalMessage(v.Bytes(), val.Message()); err != nil { + return 0, err + } + default: + val = v + } + haveVal = true + } + if err == errUnknown { + n = protowire.ConsumeFieldValue(num, wtyp, b) + if n < 0 { + return 0, protowire.ParseError(n) + } + } else if err != nil { + return 0, err + } + b = b[n:] + } + // Every map entry should have entries for key and value, but this is not strictly required. + if !haveKey { + key = keyField.Default() + } + if !haveVal { + switch valField.Kind() { + case protoreflect.GroupKind, protoreflect.MessageKind: + default: + val = valField.Default() + } + } + mapv.Set(key.MapKey(), val) + return n, nil +} + +// errUnknown is used internally to indicate fields which should be added +// to the unknown field set of a message. It is never returned from an exported +// function. +var errUnknown = errors.New("BUG: internal error (unknown)") diff --git a/vendor/google.golang.org/protobuf/proto/decode_gen.go b/vendor/google.golang.org/protobuf/proto/decode_gen.go new file mode 100644 index 00000000000..d6dc904dccf --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/decode_gen.go @@ -0,0 +1,603 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-types. DO NOT EDIT. + +package proto + +import ( + "math" + "unicode/utf8" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/reflect/protoreflect" +) + +// unmarshalScalar decodes a value of the given kind. +// +// Message values are decoded into a []byte which aliases the input data. +func (o UnmarshalOptions) unmarshalScalar(b []byte, wtyp protowire.Type, fd protoreflect.FieldDescriptor) (val protoreflect.Value, n int, err error) { + switch fd.Kind() { + case protoreflect.BoolKind: + if wtyp != protowire.VarintType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfBool(protowire.DecodeBool(v)), n, nil + case protoreflect.EnumKind: + if wtyp != protowire.VarintType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfEnum(protoreflect.EnumNumber(v)), n, nil + case protoreflect.Int32Kind: + if wtyp != protowire.VarintType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfInt32(int32(v)), n, nil + case protoreflect.Sint32Kind: + if wtyp != protowire.VarintType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32))), n, nil + case protoreflect.Uint32Kind: + if wtyp != protowire.VarintType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfUint32(uint32(v)), n, nil + case protoreflect.Int64Kind: + if wtyp != protowire.VarintType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfInt64(int64(v)), n, nil + case protoreflect.Sint64Kind: + if wtyp != protowire.VarintType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfInt64(protowire.DecodeZigZag(v)), n, nil + case protoreflect.Uint64Kind: + if wtyp != protowire.VarintType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfUint64(v), n, nil + case protoreflect.Sfixed32Kind: + if wtyp != protowire.Fixed32Type { + return val, 0, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfInt32(int32(v)), n, nil + case protoreflect.Fixed32Kind: + if wtyp != protowire.Fixed32Type { + return val, 0, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfUint32(uint32(v)), n, nil + case protoreflect.FloatKind: + if wtyp != protowire.Fixed32Type { + return val, 0, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v))), n, nil + case protoreflect.Sfixed64Kind: + if wtyp != protowire.Fixed64Type { + return val, 0, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfInt64(int64(v)), n, nil + case protoreflect.Fixed64Kind: + if wtyp != protowire.Fixed64Type { + return val, 0, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfUint64(v), n, nil + case protoreflect.DoubleKind: + if wtyp != protowire.Fixed64Type { + return val, 0, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfFloat64(math.Float64frombits(v)), n, nil + case protoreflect.StringKind: + if wtyp != protowire.BytesType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + if strs.EnforceUTF8(fd) && !utf8.Valid(v) { + return protoreflect.Value{}, 0, errors.InvalidUTF8(string(fd.FullName())) + } + return protoreflect.ValueOfString(string(v)), n, nil + case protoreflect.BytesKind: + if wtyp != protowire.BytesType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfBytes(append(emptyBuf[:], v...)), n, nil + case protoreflect.MessageKind: + if wtyp != protowire.BytesType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfBytes(v), n, nil + case protoreflect.GroupKind: + if wtyp != protowire.StartGroupType { + return val, 0, errUnknown + } + v, n := protowire.ConsumeGroup(fd.Number(), b) + if n < 0 { + return val, 0, protowire.ParseError(n) + } + return protoreflect.ValueOfBytes(v), n, nil + default: + return val, 0, errUnknown + } +} + +func (o UnmarshalOptions) unmarshalList(b []byte, wtyp protowire.Type, list protoreflect.List, fd protoreflect.FieldDescriptor) (n int, err error) { + switch fd.Kind() { + case protoreflect.BoolKind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeVarint(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) + } + return n, nil + } + if wtyp != protowire.VarintType { + return 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) + return n, nil + case protoreflect.EnumKind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeVarint(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) + } + return n, nil + } + if wtyp != protowire.VarintType { + return 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) + return n, nil + case protoreflect.Int32Kind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeVarint(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfInt32(int32(v))) + } + return n, nil + } + if wtyp != protowire.VarintType { + return 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt32(int32(v))) + return n, nil + case protoreflect.Sint32Kind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeVarint(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32)))) + } + return n, nil + } + if wtyp != protowire.VarintType { + return 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32)))) + return n, nil + case protoreflect.Uint32Kind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeVarint(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfUint32(uint32(v))) + } + return n, nil + } + if wtyp != protowire.VarintType { + return 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint32(uint32(v))) + return n, nil + case protoreflect.Int64Kind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeVarint(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfInt64(int64(v))) + } + return n, nil + } + if wtyp != protowire.VarintType { + return 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt64(int64(v))) + return n, nil + case protoreflect.Sint64Kind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeVarint(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfInt64(protowire.DecodeZigZag(v))) + } + return n, nil + } + if wtyp != protowire.VarintType { + return 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt64(protowire.DecodeZigZag(v))) + return n, nil + case protoreflect.Uint64Kind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeVarint(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfUint64(v)) + } + return n, nil + } + if wtyp != protowire.VarintType { + return 0, errUnknown + } + v, n := protowire.ConsumeVarint(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint64(v)) + return n, nil + case protoreflect.Sfixed32Kind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeFixed32(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfInt32(int32(v))) + } + return n, nil + } + if wtyp != protowire.Fixed32Type { + return 0, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt32(int32(v))) + return n, nil + case protoreflect.Fixed32Kind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeFixed32(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfUint32(uint32(v))) + } + return n, nil + } + if wtyp != protowire.Fixed32Type { + return 0, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint32(uint32(v))) + return n, nil + case protoreflect.FloatKind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeFixed32(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v)))) + } + return n, nil + } + if wtyp != protowire.Fixed32Type { + return 0, errUnknown + } + v, n := protowire.ConsumeFixed32(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v)))) + return n, nil + case protoreflect.Sfixed64Kind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeFixed64(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfInt64(int64(v))) + } + return n, nil + } + if wtyp != protowire.Fixed64Type { + return 0, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfInt64(int64(v))) + return n, nil + case protoreflect.Fixed64Kind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeFixed64(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfUint64(v)) + } + return n, nil + } + if wtyp != protowire.Fixed64Type { + return 0, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfUint64(v)) + return n, nil + case protoreflect.DoubleKind: + if wtyp == protowire.BytesType { + buf, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + for len(buf) > 0 { + v, n := protowire.ConsumeFixed64(buf) + if n < 0 { + return 0, protowire.ParseError(n) + } + buf = buf[n:] + list.Append(protoreflect.ValueOfFloat64(math.Float64frombits(v))) + } + return n, nil + } + if wtyp != protowire.Fixed64Type { + return 0, errUnknown + } + v, n := protowire.ConsumeFixed64(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfFloat64(math.Float64frombits(v))) + return n, nil + case protoreflect.StringKind: + if wtyp != protowire.BytesType { + return 0, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + if strs.EnforceUTF8(fd) && !utf8.Valid(v) { + return 0, errors.InvalidUTF8(string(fd.FullName())) + } + list.Append(protoreflect.ValueOfString(string(v))) + return n, nil + case protoreflect.BytesKind: + if wtyp != protowire.BytesType { + return 0, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + list.Append(protoreflect.ValueOfBytes(append(emptyBuf[:], v...))) + return n, nil + case protoreflect.MessageKind: + if wtyp != protowire.BytesType { + return 0, errUnknown + } + v, n := protowire.ConsumeBytes(b) + if n < 0 { + return 0, protowire.ParseError(n) + } + m := list.NewElement() + if err := o.unmarshalMessage(v, m.Message()); err != nil { + return 0, err + } + list.Append(m) + return n, nil + case protoreflect.GroupKind: + if wtyp != protowire.StartGroupType { + return 0, errUnknown + } + v, n := protowire.ConsumeGroup(fd.Number(), b) + if n < 0 { + return 0, protowire.ParseError(n) + } + m := list.NewElement() + if err := o.unmarshalMessage(v, m.Message()); err != nil { + return 0, err + } + list.Append(m) + return n, nil + default: + return 0, errUnknown + } +} + +// We append to an empty array rather than a nil []byte to get non-nil zero-length byte slices. +var emptyBuf [0]byte diff --git a/vendor/google.golang.org/protobuf/proto/doc.go b/vendor/google.golang.org/protobuf/proto/doc.go new file mode 100644 index 00000000000..c52d8c4ab79 --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/doc.go @@ -0,0 +1,94 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package proto provides functions operating on protocol buffer messages. +// +// For documentation on protocol buffers in general, see: +// +// https://developers.google.com/protocol-buffers +// +// For a tutorial on using protocol buffers with Go, see: +// +// https://developers.google.com/protocol-buffers/docs/gotutorial +// +// For a guide to generated Go protocol buffer code, see: +// +// https://developers.google.com/protocol-buffers/docs/reference/go-generated +// +// +// Binary serialization +// +// This package contains functions to convert to and from the wire format, +// an efficient binary serialization of protocol buffers. +// +// • Size reports the size of a message in the wire format. +// +// • Marshal converts a message to the wire format. +// The MarshalOptions type provides more control over wire marshaling. +// +// • Unmarshal converts a message from the wire format. +// The UnmarshalOptions type provides more control over wire unmarshaling. +// +// +// Basic message operations +// +// • Clone makes a deep copy of a message. +// +// • Merge merges the content of a message into another. +// +// • Equal compares two messages. For more control over comparisons +// and detailed reporting of differences, see package +// "google.golang.org/protobuf/testing/protocmp". +// +// • Reset clears the content of a message. +// +// • CheckInitialized reports whether all required fields in a message are set. +// +// +// Optional scalar constructors +// +// The API for some generated messages represents optional scalar fields +// as pointers to a value. For example, an optional string field has the +// Go type *string. +// +// • Bool, Int32, Int64, Uint32, Uint64, Float32, Float64, and String +// take a value and return a pointer to a new instance of it, +// to simplify construction of optional field values. +// +// Generated enum types usually have an Enum method which performs the +// same operation. +// +// Optional scalar fields are only supported in proto2. +// +// +// Extension accessors +// +// • HasExtension, GetExtension, SetExtension, and ClearExtension +// access extension field values in a protocol buffer message. +// +// Extension fields are only supported in proto2. +// +// +// Related packages +// +// • Package "google.golang.org/protobuf/encoding/protojson" converts messages to +// and from JSON. +// +// • Package "google.golang.org/protobuf/encoding/prototext" converts messages to +// and from the text format. +// +// • Package "google.golang.org/protobuf/reflect/protoreflect" provides a +// reflection interface for protocol buffer data types. +// +// • Package "google.golang.org/protobuf/testing/protocmp" provides features +// to compare protocol buffer messages with the "github.com/google/go-cmp/cmp" +// package. +// +// • Package "google.golang.org/protobuf/types/dynamicpb" provides a dynamic +// message type, suitable for working with messages where the protocol buffer +// type is only known at runtime. +// +// This module contains additional packages for more specialized use cases. +// Consult the individual package documentation for details. +package proto diff --git a/vendor/google.golang.org/protobuf/proto/encode.go b/vendor/google.golang.org/protobuf/proto/encode.go new file mode 100644 index 00000000000..7b47a1180e4 --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/encode.go @@ -0,0 +1,346 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "sort" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/fieldsort" + "google.golang.org/protobuf/internal/mapsort" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoiface" +) + +// MarshalOptions configures the marshaler. +// +// Example usage: +// b, err := MarshalOptions{Deterministic: true}.Marshal(m) +type MarshalOptions struct { + pragma.NoUnkeyedLiterals + + // AllowPartial allows messages that have missing required fields to marshal + // without returning an error. If AllowPartial is false (the default), + // Marshal will return an error if there are any missing required fields. + AllowPartial bool + + // Deterministic controls whether the same message will always be + // serialized to the same bytes within the same binary. + // + // Setting this option guarantees that repeated serialization of + // the same message will return the same bytes, and that different + // processes of the same binary (which may be executing on different + // machines) will serialize equal messages to the same bytes. + // It has no effect on the resulting size of the encoded message compared + // to a non-deterministic marshal. + // + // Note that the deterministic serialization is NOT canonical across + // languages. It is not guaranteed to remain stable over time. It is + // unstable across different builds with schema changes due to unknown + // fields. Users who need canonical serialization (e.g., persistent + // storage in a canonical form, fingerprinting, etc.) must define + // their own canonicalization specification and implement their own + // serializer rather than relying on this API. + // + // If deterministic serialization is requested, map entries will be + // sorted by keys in lexographical order. This is an implementation + // detail and subject to change. + Deterministic bool + + // UseCachedSize indicates that the result of a previous Size call + // may be reused. + // + // Setting this option asserts that: + // + // 1. Size has previously been called on this message with identical + // options (except for UseCachedSize itself). + // + // 2. The message and all its submessages have not changed in any + // way since the Size call. + // + // If either of these invariants is violated, + // the results are undefined and may include panics or corrupted output. + // + // Implementations MAY take this option into account to provide + // better performance, but there is no guarantee that they will do so. + // There is absolutely no guarantee that Size followed by Marshal with + // UseCachedSize set will perform equivalently to Marshal alone. + UseCachedSize bool +} + +// Marshal returns the wire-format encoding of m. +func Marshal(m Message) ([]byte, error) { + // Treat nil message interface as an empty message; nothing to output. + if m == nil { + return nil, nil + } + + out, err := MarshalOptions{}.marshal(nil, m.ProtoReflect()) + if len(out.Buf) == 0 && err == nil { + out.Buf = emptyBytesForMessage(m) + } + return out.Buf, err +} + +// Marshal returns the wire-format encoding of m. +func (o MarshalOptions) Marshal(m Message) ([]byte, error) { + // Treat nil message interface as an empty message; nothing to output. + if m == nil { + return nil, nil + } + + out, err := o.marshal(nil, m.ProtoReflect()) + if len(out.Buf) == 0 && err == nil { + out.Buf = emptyBytesForMessage(m) + } + return out.Buf, err +} + +// emptyBytesForMessage returns a nil buffer if and only if m is invalid, +// otherwise it returns a non-nil empty buffer. +// +// This is to assist the edge-case where user-code does the following: +// m1.OptionalBytes, _ = proto.Marshal(m2) +// where they expect the proto2 "optional_bytes" field to be populated +// if any only if m2 is a valid message. +func emptyBytesForMessage(m Message) []byte { + if m == nil || !m.ProtoReflect().IsValid() { + return nil + } + return emptyBuf[:] +} + +// MarshalAppend appends the wire-format encoding of m to b, +// returning the result. +func (o MarshalOptions) MarshalAppend(b []byte, m Message) ([]byte, error) { + // Treat nil message interface as an empty message; nothing to append. + if m == nil { + return b, nil + } + + out, err := o.marshal(b, m.ProtoReflect()) + return out.Buf, err +} + +// MarshalState returns the wire-format encoding of a message. +// +// This method permits fine-grained control over the marshaler. +// Most users should use Marshal instead. +func (o MarshalOptions) MarshalState(in protoiface.MarshalInput) (protoiface.MarshalOutput, error) { + return o.marshal(in.Buf, in.Message) +} + +// marshal is a centralized function that all marshal operations go through. +// For profiling purposes, avoid changing the name of this function or +// introducing other code paths for marshal that do not go through this. +func (o MarshalOptions) marshal(b []byte, m protoreflect.Message) (out protoiface.MarshalOutput, err error) { + allowPartial := o.AllowPartial + o.AllowPartial = true + if methods := protoMethods(m); methods != nil && methods.Marshal != nil && + !(o.Deterministic && methods.Flags&protoiface.SupportMarshalDeterministic == 0) { + in := protoiface.MarshalInput{ + Message: m, + Buf: b, + } + if o.Deterministic { + in.Flags |= protoiface.MarshalDeterministic + } + if o.UseCachedSize { + in.Flags |= protoiface.MarshalUseCachedSize + } + if methods.Size != nil { + sout := methods.Size(protoiface.SizeInput{ + Message: m, + Flags: in.Flags, + }) + if cap(b) < len(b)+sout.Size { + in.Buf = make([]byte, len(b), growcap(cap(b), len(b)+sout.Size)) + copy(in.Buf, b) + } + in.Flags |= protoiface.MarshalUseCachedSize + } + out, err = methods.Marshal(in) + } else { + out.Buf, err = o.marshalMessageSlow(b, m) + } + if err != nil { + return out, err + } + if allowPartial { + return out, nil + } + return out, checkInitialized(m) +} + +func (o MarshalOptions) marshalMessage(b []byte, m protoreflect.Message) ([]byte, error) { + out, err := o.marshal(b, m) + return out.Buf, err +} + +// growcap scales up the capacity of a slice. +// +// Given a slice with a current capacity of oldcap and a desired +// capacity of wantcap, growcap returns a new capacity >= wantcap. +// +// The algorithm is mostly identical to the one used by append as of Go 1.14. +func growcap(oldcap, wantcap int) (newcap int) { + if wantcap > oldcap*2 { + newcap = wantcap + } else if oldcap < 1024 { + // The Go 1.14 runtime takes this case when len(s) < 1024, + // not when cap(s) < 1024. The difference doesn't seem + // significant here. + newcap = oldcap * 2 + } else { + newcap = oldcap + for 0 < newcap && newcap < wantcap { + newcap += newcap / 4 + } + if newcap <= 0 { + newcap = wantcap + } + } + return newcap +} + +func (o MarshalOptions) marshalMessageSlow(b []byte, m protoreflect.Message) ([]byte, error) { + if messageset.IsMessageSet(m.Descriptor()) { + return o.marshalMessageSet(b, m) + } + // There are many choices for what order we visit fields in. The default one here + // is chosen for reasonable efficiency and simplicity given the protoreflect API. + // It is not deterministic, since Message.Range does not return fields in any + // defined order. + // + // When using deterministic serialization, we sort the known fields. + var err error + o.rangeFields(m, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + b, err = o.marshalField(b, fd, v) + return err == nil + }) + if err != nil { + return b, err + } + b = append(b, m.GetUnknown()...) + return b, nil +} + +// rangeFields visits fields in a defined order when deterministic serialization is enabled. +func (o MarshalOptions) rangeFields(m protoreflect.Message, f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { + if !o.Deterministic { + m.Range(f) + return + } + var fds []protoreflect.FieldDescriptor + m.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { + fds = append(fds, fd) + return true + }) + sort.Slice(fds, func(a, b int) bool { + return fieldsort.Less(fds[a], fds[b]) + }) + for _, fd := range fds { + if !f(fd, m.Get(fd)) { + break + } + } +} + +func (o MarshalOptions) marshalField(b []byte, fd protoreflect.FieldDescriptor, value protoreflect.Value) ([]byte, error) { + switch { + case fd.IsList(): + return o.marshalList(b, fd, value.List()) + case fd.IsMap(): + return o.marshalMap(b, fd, value.Map()) + default: + b = protowire.AppendTag(b, fd.Number(), wireTypes[fd.Kind()]) + return o.marshalSingular(b, fd, value) + } +} + +func (o MarshalOptions) marshalList(b []byte, fd protoreflect.FieldDescriptor, list protoreflect.List) ([]byte, error) { + if fd.IsPacked() && list.Len() > 0 { + b = protowire.AppendTag(b, fd.Number(), protowire.BytesType) + b, pos := appendSpeculativeLength(b) + for i, llen := 0, list.Len(); i < llen; i++ { + var err error + b, err = o.marshalSingular(b, fd, list.Get(i)) + if err != nil { + return b, err + } + } + b = finishSpeculativeLength(b, pos) + return b, nil + } + + kind := fd.Kind() + for i, llen := 0, list.Len(); i < llen; i++ { + var err error + b = protowire.AppendTag(b, fd.Number(), wireTypes[kind]) + b, err = o.marshalSingular(b, fd, list.Get(i)) + if err != nil { + return b, err + } + } + return b, nil +} + +func (o MarshalOptions) marshalMap(b []byte, fd protoreflect.FieldDescriptor, mapv protoreflect.Map) ([]byte, error) { + keyf := fd.MapKey() + valf := fd.MapValue() + var err error + o.rangeMap(mapv, keyf.Kind(), func(key protoreflect.MapKey, value protoreflect.Value) bool { + b = protowire.AppendTag(b, fd.Number(), protowire.BytesType) + var pos int + b, pos = appendSpeculativeLength(b) + + b, err = o.marshalField(b, keyf, key.Value()) + if err != nil { + return false + } + b, err = o.marshalField(b, valf, value) + if err != nil { + return false + } + b = finishSpeculativeLength(b, pos) + return true + }) + return b, err +} + +func (o MarshalOptions) rangeMap(mapv protoreflect.Map, kind protoreflect.Kind, f func(protoreflect.MapKey, protoreflect.Value) bool) { + if !o.Deterministic { + mapv.Range(f) + return + } + mapsort.Range(mapv, kind, f) +} + +// When encoding length-prefixed fields, we speculatively set aside some number of bytes +// for the length, encode the data, and then encode the length (shifting the data if necessary +// to make room). +const speculativeLength = 1 + +func appendSpeculativeLength(b []byte) ([]byte, int) { + pos := len(b) + b = append(b, "\x00\x00\x00\x00"[:speculativeLength]...) + return b, pos +} + +func finishSpeculativeLength(b []byte, pos int) []byte { + mlen := len(b) - pos - speculativeLength + msiz := protowire.SizeVarint(uint64(mlen)) + if msiz != speculativeLength { + for i := 0; i < msiz-speculativeLength; i++ { + b = append(b, 0) + } + copy(b[pos+msiz:], b[pos+speculativeLength:]) + b = b[:pos+msiz+mlen] + } + protowire.AppendVarint(b[:pos], uint64(mlen)) + return b +} diff --git a/vendor/google.golang.org/protobuf/proto/encode_gen.go b/vendor/google.golang.org/protobuf/proto/encode_gen.go new file mode 100644 index 00000000000..185dacfb49b --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/encode_gen.go @@ -0,0 +1,97 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-types. DO NOT EDIT. + +package proto + +import ( + "math" + "unicode/utf8" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/reflect/protoreflect" +) + +var wireTypes = map[protoreflect.Kind]protowire.Type{ + protoreflect.BoolKind: protowire.VarintType, + protoreflect.EnumKind: protowire.VarintType, + protoreflect.Int32Kind: protowire.VarintType, + protoreflect.Sint32Kind: protowire.VarintType, + protoreflect.Uint32Kind: protowire.VarintType, + protoreflect.Int64Kind: protowire.VarintType, + protoreflect.Sint64Kind: protowire.VarintType, + protoreflect.Uint64Kind: protowire.VarintType, + protoreflect.Sfixed32Kind: protowire.Fixed32Type, + protoreflect.Fixed32Kind: protowire.Fixed32Type, + protoreflect.FloatKind: protowire.Fixed32Type, + protoreflect.Sfixed64Kind: protowire.Fixed64Type, + protoreflect.Fixed64Kind: protowire.Fixed64Type, + protoreflect.DoubleKind: protowire.Fixed64Type, + protoreflect.StringKind: protowire.BytesType, + protoreflect.BytesKind: protowire.BytesType, + protoreflect.MessageKind: protowire.BytesType, + protoreflect.GroupKind: protowire.StartGroupType, +} + +func (o MarshalOptions) marshalSingular(b []byte, fd protoreflect.FieldDescriptor, v protoreflect.Value) ([]byte, error) { + switch fd.Kind() { + case protoreflect.BoolKind: + b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) + case protoreflect.EnumKind: + b = protowire.AppendVarint(b, uint64(v.Enum())) + case protoreflect.Int32Kind: + b = protowire.AppendVarint(b, uint64(int32(v.Int()))) + case protoreflect.Sint32Kind: + b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(int32(v.Int())))) + case protoreflect.Uint32Kind: + b = protowire.AppendVarint(b, uint64(uint32(v.Uint()))) + case protoreflect.Int64Kind: + b = protowire.AppendVarint(b, uint64(v.Int())) + case protoreflect.Sint64Kind: + b = protowire.AppendVarint(b, protowire.EncodeZigZag(v.Int())) + case protoreflect.Uint64Kind: + b = protowire.AppendVarint(b, v.Uint()) + case protoreflect.Sfixed32Kind: + b = protowire.AppendFixed32(b, uint32(v.Int())) + case protoreflect.Fixed32Kind: + b = protowire.AppendFixed32(b, uint32(v.Uint())) + case protoreflect.FloatKind: + b = protowire.AppendFixed32(b, math.Float32bits(float32(v.Float()))) + case protoreflect.Sfixed64Kind: + b = protowire.AppendFixed64(b, uint64(v.Int())) + case protoreflect.Fixed64Kind: + b = protowire.AppendFixed64(b, v.Uint()) + case protoreflect.DoubleKind: + b = protowire.AppendFixed64(b, math.Float64bits(v.Float())) + case protoreflect.StringKind: + if strs.EnforceUTF8(fd) && !utf8.ValidString(v.String()) { + return b, errors.InvalidUTF8(string(fd.FullName())) + } + b = protowire.AppendString(b, v.String()) + case protoreflect.BytesKind: + b = protowire.AppendBytes(b, v.Bytes()) + case protoreflect.MessageKind: + var pos int + var err error + b, pos = appendSpeculativeLength(b) + b, err = o.marshalMessage(b, v.Message()) + if err != nil { + return b, err + } + b = finishSpeculativeLength(b, pos) + case protoreflect.GroupKind: + var err error + b, err = o.marshalMessage(b, v.Message()) + if err != nil { + return b, err + } + b = protowire.AppendVarint(b, protowire.EncodeTag(fd.Number(), protowire.EndGroupType)) + default: + return b, errors.New("invalid kind %v", fd.Kind()) + } + return b, nil +} diff --git a/vendor/google.golang.org/protobuf/proto/equal.go b/vendor/google.golang.org/protobuf/proto/equal.go new file mode 100644 index 00000000000..10902bd851e --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/equal.go @@ -0,0 +1,154 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "bytes" + "math" + "reflect" + + "google.golang.org/protobuf/encoding/protowire" + pref "google.golang.org/protobuf/reflect/protoreflect" +) + +// Equal reports whether two messages are equal. +// If two messages marshal to the same bytes under deterministic serialization, +// then Equal is guaranteed to report true. +// +// Two messages are equal if they belong to the same message descriptor, +// have the same set of populated known and extension field values, +// and the same set of unknown fields values. If either of the top-level +// messages are invalid, then Equal reports true only if both are invalid. +// +// Scalar values are compared with the equivalent of the == operator in Go, +// except bytes values which are compared using bytes.Equal and +// floating point values which specially treat NaNs as equal. +// Message values are compared by recursively calling Equal. +// Lists are equal if each element value is also equal. +// Maps are equal if they have the same set of keys, where the pair of values +// for each key is also equal. +func Equal(x, y Message) bool { + if x == nil || y == nil { + return x == nil && y == nil + } + mx := x.ProtoReflect() + my := y.ProtoReflect() + if mx.IsValid() != my.IsValid() { + return false + } + return equalMessage(mx, my) +} + +// equalMessage compares two messages. +func equalMessage(mx, my pref.Message) bool { + if mx.Descriptor() != my.Descriptor() { + return false + } + + nx := 0 + equal := true + mx.Range(func(fd pref.FieldDescriptor, vx pref.Value) bool { + nx++ + vy := my.Get(fd) + equal = my.Has(fd) && equalField(fd, vx, vy) + return equal + }) + if !equal { + return false + } + ny := 0 + my.Range(func(fd pref.FieldDescriptor, vx pref.Value) bool { + ny++ + return true + }) + if nx != ny { + return false + } + + return equalUnknown(mx.GetUnknown(), my.GetUnknown()) +} + +// equalField compares two fields. +func equalField(fd pref.FieldDescriptor, x, y pref.Value) bool { + switch { + case fd.IsList(): + return equalList(fd, x.List(), y.List()) + case fd.IsMap(): + return equalMap(fd, x.Map(), y.Map()) + default: + return equalValue(fd, x, y) + } +} + +// equalMap compares two maps. +func equalMap(fd pref.FieldDescriptor, x, y pref.Map) bool { + if x.Len() != y.Len() { + return false + } + equal := true + x.Range(func(k pref.MapKey, vx pref.Value) bool { + vy := y.Get(k) + equal = y.Has(k) && equalValue(fd.MapValue(), vx, vy) + return equal + }) + return equal +} + +// equalList compares two lists. +func equalList(fd pref.FieldDescriptor, x, y pref.List) bool { + if x.Len() != y.Len() { + return false + } + for i := x.Len() - 1; i >= 0; i-- { + if !equalValue(fd, x.Get(i), y.Get(i)) { + return false + } + } + return true +} + +// equalValue compares two singular values. +func equalValue(fd pref.FieldDescriptor, x, y pref.Value) bool { + switch { + case fd.Message() != nil: + return equalMessage(x.Message(), y.Message()) + case fd.Kind() == pref.BytesKind: + return bytes.Equal(x.Bytes(), y.Bytes()) + case fd.Kind() == pref.FloatKind, fd.Kind() == pref.DoubleKind: + fx := x.Float() + fy := y.Float() + if math.IsNaN(fx) || math.IsNaN(fy) { + return math.IsNaN(fx) && math.IsNaN(fy) + } + return fx == fy + default: + return x.Interface() == y.Interface() + } +} + +// equalUnknown compares unknown fields by direct comparison on the raw bytes +// of each individual field number. +func equalUnknown(x, y pref.RawFields) bool { + if len(x) != len(y) { + return false + } + if bytes.Equal([]byte(x), []byte(y)) { + return true + } + + mx := make(map[pref.FieldNumber]pref.RawFields) + my := make(map[pref.FieldNumber]pref.RawFields) + for len(x) > 0 { + fnum, _, n := protowire.ConsumeField(x) + mx[fnum] = append(mx[fnum], x[:n]...) + x = x[n:] + } + for len(y) > 0 { + fnum, _, n := protowire.ConsumeField(y) + my[fnum] = append(my[fnum], y[:n]...) + y = y[n:] + } + return reflect.DeepEqual(mx, my) +} diff --git a/vendor/google.golang.org/protobuf/proto/extension.go b/vendor/google.golang.org/protobuf/proto/extension.go new file mode 100644 index 00000000000..5f293cda869 --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/extension.go @@ -0,0 +1,92 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "google.golang.org/protobuf/reflect/protoreflect" +) + +// HasExtension reports whether an extension field is populated. +// It returns false if m is invalid or if xt does not extend m. +func HasExtension(m Message, xt protoreflect.ExtensionType) bool { + // Treat nil message interface as an empty message; no populated fields. + if m == nil { + return false + } + + // As a special-case, we reports invalid or mismatching descriptors + // as always not being populated (since they aren't). + if xt == nil || m.ProtoReflect().Descriptor() != xt.TypeDescriptor().ContainingMessage() { + return false + } + + return m.ProtoReflect().Has(xt.TypeDescriptor()) +} + +// ClearExtension clears an extension field such that subsequent +// HasExtension calls return false. +// It panics if m is invalid or if xt does not extend m. +func ClearExtension(m Message, xt protoreflect.ExtensionType) { + m.ProtoReflect().Clear(xt.TypeDescriptor()) +} + +// GetExtension retrieves the value for an extension field. +// If the field is unpopulated, it returns the default value for +// scalars and an immutable, empty value for lists or messages. +// It panics if xt does not extend m. +func GetExtension(m Message, xt protoreflect.ExtensionType) interface{} { + // Treat nil message interface as an empty message; return the default. + if m == nil { + return xt.InterfaceOf(xt.Zero()) + } + + return xt.InterfaceOf(m.ProtoReflect().Get(xt.TypeDescriptor())) +} + +// SetExtension stores the value of an extension field. +// It panics if m is invalid, xt does not extend m, or if type of v +// is invalid for the specified extension field. +func SetExtension(m Message, xt protoreflect.ExtensionType, v interface{}) { + xd := xt.TypeDescriptor() + pv := xt.ValueOf(v) + + // Specially treat an invalid list, map, or message as clear. + isValid := true + switch { + case xd.IsList(): + isValid = pv.List().IsValid() + case xd.IsMap(): + isValid = pv.Map().IsValid() + case xd.Message() != nil: + isValid = pv.Message().IsValid() + } + if !isValid { + m.ProtoReflect().Clear(xd) + return + } + + m.ProtoReflect().Set(xd, pv) +} + +// RangeExtensions iterates over every populated extension field in m in an +// undefined order, calling f for each extension type and value encountered. +// It returns immediately if f returns false. +// While iterating, mutating operations may only be performed +// on the current extension field. +func RangeExtensions(m Message, f func(protoreflect.ExtensionType, interface{}) bool) { + // Treat nil message interface as an empty message; nothing to range over. + if m == nil { + return + } + + m.ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + if fd.IsExtension() { + xt := fd.(protoreflect.ExtensionTypeDescriptor).Type() + vi := xt.InterfaceOf(v) + return f(xt, vi) + } + return true + }) +} diff --git a/vendor/google.golang.org/protobuf/proto/merge.go b/vendor/google.golang.org/protobuf/proto/merge.go new file mode 100644 index 00000000000..d761ab331d1 --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/merge.go @@ -0,0 +1,139 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "fmt" + + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoiface" +) + +// Merge merges src into dst, which must be a message with the same descriptor. +// +// Populated scalar fields in src are copied to dst, while populated +// singular messages in src are merged into dst by recursively calling Merge. +// The elements of every list field in src is appended to the corresponded +// list fields in dst. The entries of every map field in src is copied into +// the corresponding map field in dst, possibly replacing existing entries. +// The unknown fields of src are appended to the unknown fields of dst. +// +// It is semantically equivalent to unmarshaling the encoded form of src +// into dst with the UnmarshalOptions.Merge option specified. +func Merge(dst, src Message) { + // TODO: Should nil src be treated as semantically equivalent to a + // untyped, read-only, empty message? What about a nil dst? + + dstMsg, srcMsg := dst.ProtoReflect(), src.ProtoReflect() + if dstMsg.Descriptor() != srcMsg.Descriptor() { + if got, want := dstMsg.Descriptor().FullName(), srcMsg.Descriptor().FullName(); got != want { + panic(fmt.Sprintf("descriptor mismatch: %v != %v", got, want)) + } + panic("descriptor mismatch") + } + mergeOptions{}.mergeMessage(dstMsg, srcMsg) +} + +// Clone returns a deep copy of m. +// If the top-level message is invalid, it returns an invalid message as well. +func Clone(m Message) Message { + // NOTE: Most usages of Clone assume the following properties: + // t := reflect.TypeOf(m) + // t == reflect.TypeOf(m.ProtoReflect().New().Interface()) + // t == reflect.TypeOf(m.ProtoReflect().Type().Zero().Interface()) + // + // Embedding protobuf messages breaks this since the parent type will have + // a forwarded ProtoReflect method, but the Interface method will return + // the underlying embedded message type. + if m == nil { + return nil + } + src := m.ProtoReflect() + if !src.IsValid() { + return src.Type().Zero().Interface() + } + dst := src.New() + mergeOptions{}.mergeMessage(dst, src) + return dst.Interface() +} + +// mergeOptions provides a namespace for merge functions, and can be +// exported in the future if we add user-visible merge options. +type mergeOptions struct{} + +func (o mergeOptions) mergeMessage(dst, src protoreflect.Message) { + methods := protoMethods(dst) + if methods != nil && methods.Merge != nil { + in := protoiface.MergeInput{ + Destination: dst, + Source: src, + } + out := methods.Merge(in) + if out.Flags&protoiface.MergeComplete != 0 { + return + } + } + + if !dst.IsValid() { + panic(fmt.Sprintf("cannot merge into invalid %v message", dst.Descriptor().FullName())) + } + + src.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + switch { + case fd.IsList(): + o.mergeList(dst.Mutable(fd).List(), v.List(), fd) + case fd.IsMap(): + o.mergeMap(dst.Mutable(fd).Map(), v.Map(), fd.MapValue()) + case fd.Message() != nil: + o.mergeMessage(dst.Mutable(fd).Message(), v.Message()) + case fd.Kind() == protoreflect.BytesKind: + dst.Set(fd, o.cloneBytes(v)) + default: + dst.Set(fd, v) + } + return true + }) + + if len(src.GetUnknown()) > 0 { + dst.SetUnknown(append(dst.GetUnknown(), src.GetUnknown()...)) + } +} + +func (o mergeOptions) mergeList(dst, src protoreflect.List, fd protoreflect.FieldDescriptor) { + // Merge semantics appends to the end of the existing list. + for i, n := 0, src.Len(); i < n; i++ { + switch v := src.Get(i); { + case fd.Message() != nil: + dstv := dst.NewElement() + o.mergeMessage(dstv.Message(), v.Message()) + dst.Append(dstv) + case fd.Kind() == protoreflect.BytesKind: + dst.Append(o.cloneBytes(v)) + default: + dst.Append(v) + } + } +} + +func (o mergeOptions) mergeMap(dst, src protoreflect.Map, fd protoreflect.FieldDescriptor) { + // Merge semantics replaces, rather than merges into existing entries. + src.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { + switch { + case fd.Message() != nil: + dstv := dst.NewValue() + o.mergeMessage(dstv.Message(), v.Message()) + dst.Set(k, dstv) + case fd.Kind() == protoreflect.BytesKind: + dst.Set(k, o.cloneBytes(v)) + default: + dst.Set(k, v) + } + return true + }) +} + +func (o mergeOptions) cloneBytes(v protoreflect.Value) protoreflect.Value { + return protoreflect.ValueOfBytes(append([]byte{}, v.Bytes()...)) +} diff --git a/vendor/google.golang.org/protobuf/proto/messageset.go b/vendor/google.golang.org/protobuf/proto/messageset.go new file mode 100644 index 00000000000..1d692c3a8b3 --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/messageset.go @@ -0,0 +1,88 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" +) + +func (o MarshalOptions) sizeMessageSet(m protoreflect.Message) (size int) { + m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + size += messageset.SizeField(fd.Number()) + size += protowire.SizeTag(messageset.FieldMessage) + size += protowire.SizeBytes(o.size(v.Message())) + return true + }) + size += messageset.SizeUnknown(m.GetUnknown()) + return size +} + +func (o MarshalOptions) marshalMessageSet(b []byte, m protoreflect.Message) ([]byte, error) { + if !flags.ProtoLegacy { + return b, errors.New("no support for message_set_wire_format") + } + var err error + o.rangeFields(m, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + b, err = o.marshalMessageSetField(b, fd, v) + return err == nil + }) + if err != nil { + return b, err + } + return messageset.AppendUnknown(b, m.GetUnknown()) +} + +func (o MarshalOptions) marshalMessageSetField(b []byte, fd protoreflect.FieldDescriptor, value protoreflect.Value) ([]byte, error) { + b = messageset.AppendFieldStart(b, fd.Number()) + b = protowire.AppendTag(b, messageset.FieldMessage, protowire.BytesType) + b = protowire.AppendVarint(b, uint64(o.Size(value.Message().Interface()))) + b, err := o.marshalMessage(b, value.Message()) + if err != nil { + return b, err + } + b = messageset.AppendFieldEnd(b) + return b, nil +} + +func (o UnmarshalOptions) unmarshalMessageSet(b []byte, m protoreflect.Message) error { + if !flags.ProtoLegacy { + return errors.New("no support for message_set_wire_format") + } + return messageset.Unmarshal(b, false, func(num protowire.Number, v []byte) error { + err := o.unmarshalMessageSetField(m, num, v) + if err == errUnknown { + unknown := m.GetUnknown() + unknown = protowire.AppendTag(unknown, num, protowire.BytesType) + unknown = protowire.AppendBytes(unknown, v) + m.SetUnknown(unknown) + return nil + } + return err + }) +} + +func (o UnmarshalOptions) unmarshalMessageSetField(m protoreflect.Message, num protowire.Number, v []byte) error { + md := m.Descriptor() + if !md.ExtensionRanges().Has(num) { + return errUnknown + } + xt, err := o.Resolver.FindExtensionByNumber(md.FullName(), num) + if err == protoregistry.NotFound { + return errUnknown + } + if err != nil { + return errors.New("%v: unable to resolve extension %v: %v", md.FullName(), num, err) + } + xd := xt.TypeDescriptor() + if err := o.unmarshalMessage(v, m.Mutable(xd).Message()); err != nil { + return err + } + return nil +} diff --git a/vendor/google.golang.org/protobuf/proto/proto.go b/vendor/google.golang.org/protobuf/proto/proto.go new file mode 100644 index 00000000000..ca14b09c341 --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/proto.go @@ -0,0 +1,34 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/reflect/protoreflect" +) + +// Message is the top-level interface that all messages must implement. +// It provides access to a reflective view of a message. +// Any implementation of this interface may be used with all functions in the +// protobuf module that accept a Message, except where otherwise specified. +// +// This is the v2 interface definition for protobuf messages. +// The v1 interface definition is "github.com/golang/protobuf/proto".Message. +// +// To convert a v1 message to a v2 message, +// use "github.com/golang/protobuf/proto".MessageV2. +// To convert a v2 message to a v1 message, +// use "github.com/golang/protobuf/proto".MessageV1. +type Message = protoreflect.ProtoMessage + +// Error matches all errors produced by packages in the protobuf module. +// +// That is, errors.Is(err, Error) reports whether an error is produced +// by this module. +var Error error + +func init() { + Error = errors.Error +} diff --git a/vendor/google.golang.org/protobuf/proto/proto_methods.go b/vendor/google.golang.org/protobuf/proto/proto_methods.go new file mode 100644 index 00000000000..d8dd604f6b6 --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/proto_methods.go @@ -0,0 +1,19 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// The protoreflect build tag disables use of fast-path methods. +// +build !protoreflect + +package proto + +import ( + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoiface" +) + +const hasProtoMethods = true + +func protoMethods(m protoreflect.Message) *protoiface.Methods { + return m.ProtoMethods() +} diff --git a/vendor/google.golang.org/protobuf/proto/proto_reflect.go b/vendor/google.golang.org/protobuf/proto/proto_reflect.go new file mode 100644 index 00000000000..b103d43205c --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/proto_reflect.go @@ -0,0 +1,19 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// The protoreflect build tag disables use of fast-path methods. +// +build protoreflect + +package proto + +import ( + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoiface" +) + +const hasProtoMethods = false + +func protoMethods(m protoreflect.Message) *protoiface.Methods { + return nil +} diff --git a/vendor/google.golang.org/protobuf/proto/reset.go b/vendor/google.golang.org/protobuf/proto/reset.go new file mode 100644 index 00000000000..3d7f894362f --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/reset.go @@ -0,0 +1,43 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "fmt" + + "google.golang.org/protobuf/reflect/protoreflect" +) + +// Reset clears every field in the message. +// The resulting message shares no observable memory with its previous state +// other than the memory for the message itself. +func Reset(m Message) { + if mr, ok := m.(interface{ Reset() }); ok && hasProtoMethods { + mr.Reset() + return + } + resetMessage(m.ProtoReflect()) +} + +func resetMessage(m protoreflect.Message) { + if !m.IsValid() { + panic(fmt.Sprintf("cannot reset invalid %v message", m.Descriptor().FullName())) + } + + // Clear all known fields. + fds := m.Descriptor().Fields() + for i := 0; i < fds.Len(); i++ { + m.Clear(fds.Get(i)) + } + + // Clear extension fields. + m.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { + m.Clear(fd) + return true + }) + + // Clear unknown fields. + m.SetUnknown(nil) +} diff --git a/vendor/google.golang.org/protobuf/proto/size.go b/vendor/google.golang.org/protobuf/proto/size.go new file mode 100644 index 00000000000..554b9c6c09a --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/size.go @@ -0,0 +1,97 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +import ( + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/encoding/messageset" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoiface" +) + +// Size returns the size in bytes of the wire-format encoding of m. +func Size(m Message) int { + return MarshalOptions{}.Size(m) +} + +// Size returns the size in bytes of the wire-format encoding of m. +func (o MarshalOptions) Size(m Message) int { + // Treat a nil message interface as an empty message; nothing to output. + if m == nil { + return 0 + } + + return o.size(m.ProtoReflect()) +} + +// size is a centralized function that all size operations go through. +// For profiling purposes, avoid changing the name of this function or +// introducing other code paths for size that do not go through this. +func (o MarshalOptions) size(m protoreflect.Message) (size int) { + methods := protoMethods(m) + if methods != nil && methods.Size != nil { + out := methods.Size(protoiface.SizeInput{ + Message: m, + }) + return out.Size + } + if methods != nil && methods.Marshal != nil { + // This is not efficient, but we don't have any choice. + // This case is mainly used for legacy types with a Marshal method. + out, _ := methods.Marshal(protoiface.MarshalInput{ + Message: m, + }) + return len(out.Buf) + } + return o.sizeMessageSlow(m) +} + +func (o MarshalOptions) sizeMessageSlow(m protoreflect.Message) (size int) { + if messageset.IsMessageSet(m.Descriptor()) { + return o.sizeMessageSet(m) + } + m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { + size += o.sizeField(fd, v) + return true + }) + size += len(m.GetUnknown()) + return size +} + +func (o MarshalOptions) sizeField(fd protoreflect.FieldDescriptor, value protoreflect.Value) (size int) { + num := fd.Number() + switch { + case fd.IsList(): + return o.sizeList(num, fd, value.List()) + case fd.IsMap(): + return o.sizeMap(num, fd, value.Map()) + default: + return protowire.SizeTag(num) + o.sizeSingular(num, fd.Kind(), value) + } +} + +func (o MarshalOptions) sizeList(num protowire.Number, fd protoreflect.FieldDescriptor, list protoreflect.List) (size int) { + if fd.IsPacked() && list.Len() > 0 { + content := 0 + for i, llen := 0, list.Len(); i < llen; i++ { + content += o.sizeSingular(num, fd.Kind(), list.Get(i)) + } + return protowire.SizeTag(num) + protowire.SizeBytes(content) + } + + for i, llen := 0, list.Len(); i < llen; i++ { + size += protowire.SizeTag(num) + o.sizeSingular(num, fd.Kind(), list.Get(i)) + } + return size +} + +func (o MarshalOptions) sizeMap(num protowire.Number, fd protoreflect.FieldDescriptor, mapv protoreflect.Map) (size int) { + mapv.Range(func(key protoreflect.MapKey, value protoreflect.Value) bool { + size += protowire.SizeTag(num) + size += protowire.SizeBytes(o.sizeField(fd.MapKey(), key.Value()) + o.sizeField(fd.MapValue(), value)) + return true + }) + return size +} diff --git a/vendor/google.golang.org/protobuf/proto/size_gen.go b/vendor/google.golang.org/protobuf/proto/size_gen.go new file mode 100644 index 00000000000..3cf61a824a7 --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/size_gen.go @@ -0,0 +1,55 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Code generated by generate-types. DO NOT EDIT. + +package proto + +import ( + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/reflect/protoreflect" +) + +func (o MarshalOptions) sizeSingular(num protowire.Number, kind protoreflect.Kind, v protoreflect.Value) int { + switch kind { + case protoreflect.BoolKind: + return protowire.SizeVarint(protowire.EncodeBool(v.Bool())) + case protoreflect.EnumKind: + return protowire.SizeVarint(uint64(v.Enum())) + case protoreflect.Int32Kind: + return protowire.SizeVarint(uint64(int32(v.Int()))) + case protoreflect.Sint32Kind: + return protowire.SizeVarint(protowire.EncodeZigZag(int64(int32(v.Int())))) + case protoreflect.Uint32Kind: + return protowire.SizeVarint(uint64(uint32(v.Uint()))) + case protoreflect.Int64Kind: + return protowire.SizeVarint(uint64(v.Int())) + case protoreflect.Sint64Kind: + return protowire.SizeVarint(protowire.EncodeZigZag(v.Int())) + case protoreflect.Uint64Kind: + return protowire.SizeVarint(v.Uint()) + case protoreflect.Sfixed32Kind: + return protowire.SizeFixed32() + case protoreflect.Fixed32Kind: + return protowire.SizeFixed32() + case protoreflect.FloatKind: + return protowire.SizeFixed32() + case protoreflect.Sfixed64Kind: + return protowire.SizeFixed64() + case protoreflect.Fixed64Kind: + return protowire.SizeFixed64() + case protoreflect.DoubleKind: + return protowire.SizeFixed64() + case protoreflect.StringKind: + return protowire.SizeBytes(len(v.String())) + case protoreflect.BytesKind: + return protowire.SizeBytes(len(v.Bytes())) + case protoreflect.MessageKind: + return protowire.SizeBytes(o.size(v.Message())) + case protoreflect.GroupKind: + return protowire.SizeGroup(num, o.size(v.Message())) + default: + return 0 + } +} diff --git a/vendor/google.golang.org/protobuf/proto/wrappers.go b/vendor/google.golang.org/protobuf/proto/wrappers.go new file mode 100644 index 00000000000..653b12c3af5 --- /dev/null +++ b/vendor/google.golang.org/protobuf/proto/wrappers.go @@ -0,0 +1,29 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package proto + +// Bool stores v in a new bool value and returns a pointer to it. +func Bool(v bool) *bool { return &v } + +// Int32 stores v in a new int32 value and returns a pointer to it. +func Int32(v int32) *int32 { return &v } + +// Int64 stores v in a new int64 value and returns a pointer to it. +func Int64(v int64) *int64 { return &v } + +// Float32 stores v in a new float32 value and returns a pointer to it. +func Float32(v float32) *float32 { return &v } + +// Float64 stores v in a new float64 value and returns a pointer to it. +func Float64(v float64) *float64 { return &v } + +// Uint32 stores v in a new uint32 value and returns a pointer to it. +func Uint32(v uint32) *uint32 { return &v } + +// Uint64 stores v in a new uint64 value and returns a pointer to it. +func Uint64(v uint64) *uint64 { return &v } + +// String stores v in a new string value and returns a pointer to it. +func String(v string) *string { return &v } diff --git a/vendor/google.golang.org/protobuf/reflect/protodesc/desc.go b/vendor/google.golang.org/protobuf/reflect/protodesc/desc.go new file mode 100644 index 00000000000..37f254d4c05 --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protodesc/desc.go @@ -0,0 +1,275 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package protodesc provides functionality for converting +// FileDescriptorProto messages to/from protoreflect.FileDescriptor values. +// +// The google.protobuf.FileDescriptorProto is a protobuf message that describes +// the type information for a .proto file in a form that is easily serializable. +// The protoreflect.FileDescriptor is a more structured representation of +// the FileDescriptorProto message where references and remote dependencies +// can be directly followed. +package protodesc + +import ( + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + + "google.golang.org/protobuf/types/descriptorpb" +) + +// Resolver is the resolver used by NewFile to resolve dependencies. +// The enums and messages provided must belong to some parent file, +// which is also registered. +// +// It is implemented by protoregistry.Files. +type Resolver interface { + FindFileByPath(string) (protoreflect.FileDescriptor, error) + FindDescriptorByName(protoreflect.FullName) (protoreflect.Descriptor, error) +} + +// FileOptions configures the construction of file descriptors. +type FileOptions struct { + pragma.NoUnkeyedLiterals + + // AllowUnresolvable configures New to permissively allow unresolvable + // file, enum, or message dependencies. Unresolved dependencies are replaced + // by placeholder equivalents. + // + // The following dependencies may be left unresolved: + // • Resolving an imported file. + // • Resolving the type for a message field or extension field. + // If the kind of the field is unknown, then a placeholder is used for both + // the Enum and Message accessors on the protoreflect.FieldDescriptor. + // • Resolving an enum value set as the default for an optional enum field. + // If unresolvable, the protoreflect.FieldDescriptor.Default is set to the + // first value in the associated enum (or zero if the also enum dependency + // is also unresolvable). The protoreflect.FieldDescriptor.DefaultEnumValue + // is populated with a placeholder. + // • Resolving the extended message type for an extension field. + // • Resolving the input or output message type for a service method. + // + // If the unresolved dependency uses a relative name, + // then the placeholder will contain an invalid FullName with a "*." prefix, + // indicating that the starting prefix of the full name is unknown. + AllowUnresolvable bool +} + +// NewFile creates a new protoreflect.FileDescriptor from the provided +// file descriptor message. See FileOptions.New for more information. +func NewFile(fd *descriptorpb.FileDescriptorProto, r Resolver) (protoreflect.FileDescriptor, error) { + return FileOptions{}.New(fd, r) +} + +// NewFiles creates a new protoregistry.Files from the provided +// FileDescriptorSet message. See FileOptions.NewFiles for more information. +func NewFiles(fd *descriptorpb.FileDescriptorSet) (*protoregistry.Files, error) { + return FileOptions{}.NewFiles(fd) +} + +// New creates a new protoreflect.FileDescriptor from the provided +// file descriptor message. The file must represent a valid proto file according +// to protobuf semantics. The returned descriptor is a deep copy of the input. +// +// Any imported files, enum types, or message types referenced in the file are +// resolved using the provided registry. When looking up an import file path, +// the path must be unique. The newly created file descriptor is not registered +// back into the provided file registry. +func (o FileOptions) New(fd *descriptorpb.FileDescriptorProto, r Resolver) (protoreflect.FileDescriptor, error) { + if r == nil { + r = (*protoregistry.Files)(nil) // empty resolver + } + + // Handle the file descriptor content. + f := &filedesc.File{L2: &filedesc.FileL2{}} + switch fd.GetSyntax() { + case "proto2", "": + f.L1.Syntax = protoreflect.Proto2 + case "proto3": + f.L1.Syntax = protoreflect.Proto3 + default: + return nil, errors.New("invalid syntax: %q", fd.GetSyntax()) + } + f.L1.Path = fd.GetName() + if f.L1.Path == "" { + return nil, errors.New("file path must be populated") + } + f.L1.Package = protoreflect.FullName(fd.GetPackage()) + if !f.L1.Package.IsValid() && f.L1.Package != "" { + return nil, errors.New("invalid package: %q", f.L1.Package) + } + if opts := fd.GetOptions(); opts != nil { + opts = proto.Clone(opts).(*descriptorpb.FileOptions) + f.L2.Options = func() protoreflect.ProtoMessage { return opts } + } + + f.L2.Imports = make(filedesc.FileImports, len(fd.GetDependency())) + for _, i := range fd.GetPublicDependency() { + if !(0 <= i && int(i) < len(f.L2.Imports)) || f.L2.Imports[i].IsPublic { + return nil, errors.New("invalid or duplicate public import index: %d", i) + } + f.L2.Imports[i].IsPublic = true + } + for _, i := range fd.GetWeakDependency() { + if !(0 <= i && int(i) < len(f.L2.Imports)) || f.L2.Imports[i].IsWeak { + return nil, errors.New("invalid or duplicate weak import index: %d", i) + } + f.L2.Imports[i].IsWeak = true + } + imps := importSet{f.Path(): true} + for i, path := range fd.GetDependency() { + imp := &f.L2.Imports[i] + f, err := r.FindFileByPath(path) + if err == protoregistry.NotFound && (o.AllowUnresolvable || imp.IsWeak) { + f = filedesc.PlaceholderFile(path) + } else if err != nil { + return nil, errors.New("could not resolve import %q: %v", path, err) + } + imp.FileDescriptor = f + + if imps[imp.Path()] { + return nil, errors.New("already imported %q", path) + } + imps[imp.Path()] = true + } + for i := range fd.GetDependency() { + imp := &f.L2.Imports[i] + imps.importPublic(imp.Imports()) + } + + // Handle source locations. + for _, loc := range fd.GetSourceCodeInfo().GetLocation() { + var l protoreflect.SourceLocation + // TODO: Validate that the path points to an actual declaration? + l.Path = protoreflect.SourcePath(loc.GetPath()) + s := loc.GetSpan() + switch len(s) { + case 3: + l.StartLine, l.StartColumn, l.EndLine, l.EndColumn = int(s[0]), int(s[1]), int(s[0]), int(s[2]) + case 4: + l.StartLine, l.StartColumn, l.EndLine, l.EndColumn = int(s[0]), int(s[1]), int(s[2]), int(s[3]) + default: + return nil, errors.New("invalid span: %v", s) + } + // TODO: Validate that the span information is sensible? + // See https://github.com/protocolbuffers/protobuf/issues/6378. + if false && (l.EndLine < l.StartLine || l.StartLine < 0 || l.StartColumn < 0 || l.EndColumn < 0 || + (l.StartLine == l.EndLine && l.EndColumn <= l.StartColumn)) { + return nil, errors.New("invalid span: %v", s) + } + l.LeadingDetachedComments = loc.GetLeadingDetachedComments() + l.LeadingComments = loc.GetLeadingComments() + l.TrailingComments = loc.GetTrailingComments() + f.L2.Locations.List = append(f.L2.Locations.List, l) + } + + // Step 1: Allocate and derive the names for all declarations. + // This copies all fields from the descriptor proto except: + // google.protobuf.FieldDescriptorProto.type_name + // google.protobuf.FieldDescriptorProto.default_value + // google.protobuf.FieldDescriptorProto.oneof_index + // google.protobuf.FieldDescriptorProto.extendee + // google.protobuf.MethodDescriptorProto.input + // google.protobuf.MethodDescriptorProto.output + var err error + sb := new(strs.Builder) + r1 := make(descsByName) + if f.L1.Enums.List, err = r1.initEnumDeclarations(fd.GetEnumType(), f, sb); err != nil { + return nil, err + } + if f.L1.Messages.List, err = r1.initMessagesDeclarations(fd.GetMessageType(), f, sb); err != nil { + return nil, err + } + if f.L1.Extensions.List, err = r1.initExtensionDeclarations(fd.GetExtension(), f, sb); err != nil { + return nil, err + } + if f.L1.Services.List, err = r1.initServiceDeclarations(fd.GetService(), f, sb); err != nil { + return nil, err + } + + // Step 2: Resolve every dependency reference not handled by step 1. + r2 := &resolver{local: r1, remote: r, imports: imps, allowUnresolvable: o.AllowUnresolvable} + if err := r2.resolveMessageDependencies(f.L1.Messages.List, fd.GetMessageType()); err != nil { + return nil, err + } + if err := r2.resolveExtensionDependencies(f.L1.Extensions.List, fd.GetExtension()); err != nil { + return nil, err + } + if err := r2.resolveServiceDependencies(f.L1.Services.List, fd.GetService()); err != nil { + return nil, err + } + + // Step 3: Validate every enum, message, and extension declaration. + if err := validateEnumDeclarations(f.L1.Enums.List, fd.GetEnumType()); err != nil { + return nil, err + } + if err := validateMessageDeclarations(f.L1.Messages.List, fd.GetMessageType()); err != nil { + return nil, err + } + if err := validateExtensionDeclarations(f.L1.Extensions.List, fd.GetExtension()); err != nil { + return nil, err + } + + return f, nil +} + +type importSet map[string]bool + +func (is importSet) importPublic(imps protoreflect.FileImports) { + for i := 0; i < imps.Len(); i++ { + if imp := imps.Get(i); imp.IsPublic { + is[imp.Path()] = true + is.importPublic(imp.Imports()) + } + } +} + +// NewFiles creates a new protoregistry.Files from the provided +// FileDescriptorSet message. The descriptor set must include only +// valid files according to protobuf semantics. The returned descriptors +// are a deep copy of the input. +func (o FileOptions) NewFiles(fds *descriptorpb.FileDescriptorSet) (*protoregistry.Files, error) { + files := make(map[string]*descriptorpb.FileDescriptorProto) + for _, fd := range fds.File { + if _, ok := files[fd.GetName()]; ok { + return nil, errors.New("file appears multiple times: %q", fd.GetName()) + } + files[fd.GetName()] = fd + } + r := &protoregistry.Files{} + for _, fd := range files { + if err := o.addFileDeps(r, fd, files); err != nil { + return nil, err + } + } + return r, nil +} +func (o FileOptions) addFileDeps(r *protoregistry.Files, fd *descriptorpb.FileDescriptorProto, files map[string]*descriptorpb.FileDescriptorProto) error { + // Set the entry to nil while descending into a file's dependencies to detect cycles. + files[fd.GetName()] = nil + for _, dep := range fd.Dependency { + depfd, ok := files[dep] + if depfd == nil { + if ok { + return errors.New("import cycle in file: %q", dep) + } + continue + } + if err := o.addFileDeps(r, depfd, files); err != nil { + return err + } + } + // Delete the entry once dependencies are processed. + delete(files, fd.GetName()) + f, err := o.New(fd, r) + if err != nil { + return err + } + return r.RegisterFile(f) +} diff --git a/vendor/google.golang.org/protobuf/reflect/protodesc/desc_init.go b/vendor/google.golang.org/protobuf/reflect/protodesc/desc_init.go new file mode 100644 index 00000000000..673a230e7a0 --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protodesc/desc_init.go @@ -0,0 +1,248 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protodesc + +import ( + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + + "google.golang.org/protobuf/types/descriptorpb" +) + +type descsByName map[protoreflect.FullName]protoreflect.Descriptor + +func (r descsByName) initEnumDeclarations(eds []*descriptorpb.EnumDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (es []filedesc.Enum, err error) { + es = make([]filedesc.Enum, len(eds)) // allocate up-front to ensure stable pointers + for i, ed := range eds { + e := &es[i] + e.L2 = new(filedesc.EnumL2) + if e.L0, err = r.makeBase(e, parent, ed.GetName(), i, sb); err != nil { + return nil, err + } + if opts := ed.GetOptions(); opts != nil { + opts = proto.Clone(opts).(*descriptorpb.EnumOptions) + e.L2.Options = func() protoreflect.ProtoMessage { return opts } + } + for _, s := range ed.GetReservedName() { + e.L2.ReservedNames.List = append(e.L2.ReservedNames.List, protoreflect.Name(s)) + } + for _, rr := range ed.GetReservedRange() { + e.L2.ReservedRanges.List = append(e.L2.ReservedRanges.List, [2]protoreflect.EnumNumber{ + protoreflect.EnumNumber(rr.GetStart()), + protoreflect.EnumNumber(rr.GetEnd()), + }) + } + if e.L2.Values.List, err = r.initEnumValuesFromDescriptorProto(ed.GetValue(), e, sb); err != nil { + return nil, err + } + } + return es, nil +} + +func (r descsByName) initEnumValuesFromDescriptorProto(vds []*descriptorpb.EnumValueDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (vs []filedesc.EnumValue, err error) { + vs = make([]filedesc.EnumValue, len(vds)) // allocate up-front to ensure stable pointers + for i, vd := range vds { + v := &vs[i] + if v.L0, err = r.makeBase(v, parent, vd.GetName(), i, sb); err != nil { + return nil, err + } + if opts := vd.GetOptions(); opts != nil { + opts = proto.Clone(opts).(*descriptorpb.EnumValueOptions) + v.L1.Options = func() protoreflect.ProtoMessage { return opts } + } + v.L1.Number = protoreflect.EnumNumber(vd.GetNumber()) + } + return vs, nil +} + +func (r descsByName) initMessagesDeclarations(mds []*descriptorpb.DescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (ms []filedesc.Message, err error) { + ms = make([]filedesc.Message, len(mds)) // allocate up-front to ensure stable pointers + for i, md := range mds { + m := &ms[i] + m.L2 = new(filedesc.MessageL2) + if m.L0, err = r.makeBase(m, parent, md.GetName(), i, sb); err != nil { + return nil, err + } + if opts := md.GetOptions(); opts != nil { + opts = proto.Clone(opts).(*descriptorpb.MessageOptions) + m.L2.Options = func() protoreflect.ProtoMessage { return opts } + m.L1.IsMapEntry = opts.GetMapEntry() + m.L1.IsMessageSet = opts.GetMessageSetWireFormat() + } + for _, s := range md.GetReservedName() { + m.L2.ReservedNames.List = append(m.L2.ReservedNames.List, protoreflect.Name(s)) + } + for _, rr := range md.GetReservedRange() { + m.L2.ReservedRanges.List = append(m.L2.ReservedRanges.List, [2]protoreflect.FieldNumber{ + protoreflect.FieldNumber(rr.GetStart()), + protoreflect.FieldNumber(rr.GetEnd()), + }) + } + for _, xr := range md.GetExtensionRange() { + m.L2.ExtensionRanges.List = append(m.L2.ExtensionRanges.List, [2]protoreflect.FieldNumber{ + protoreflect.FieldNumber(xr.GetStart()), + protoreflect.FieldNumber(xr.GetEnd()), + }) + var optsFunc func() protoreflect.ProtoMessage + if opts := xr.GetOptions(); opts != nil { + opts = proto.Clone(opts).(*descriptorpb.ExtensionRangeOptions) + optsFunc = func() protoreflect.ProtoMessage { return opts } + } + m.L2.ExtensionRangeOptions = append(m.L2.ExtensionRangeOptions, optsFunc) + } + if m.L2.Fields.List, err = r.initFieldsFromDescriptorProto(md.GetField(), m, sb); err != nil { + return nil, err + } + if m.L2.Oneofs.List, err = r.initOneofsFromDescriptorProto(md.GetOneofDecl(), m, sb); err != nil { + return nil, err + } + if m.L1.Enums.List, err = r.initEnumDeclarations(md.GetEnumType(), m, sb); err != nil { + return nil, err + } + if m.L1.Messages.List, err = r.initMessagesDeclarations(md.GetNestedType(), m, sb); err != nil { + return nil, err + } + if m.L1.Extensions.List, err = r.initExtensionDeclarations(md.GetExtension(), m, sb); err != nil { + return nil, err + } + } + return ms, nil +} + +func (r descsByName) initFieldsFromDescriptorProto(fds []*descriptorpb.FieldDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (fs []filedesc.Field, err error) { + fs = make([]filedesc.Field, len(fds)) // allocate up-front to ensure stable pointers + for i, fd := range fds { + f := &fs[i] + if f.L0, err = r.makeBase(f, parent, fd.GetName(), i, sb); err != nil { + return nil, err + } + f.L1.IsProto3Optional = fd.GetProto3Optional() + if opts := fd.GetOptions(); opts != nil { + opts = proto.Clone(opts).(*descriptorpb.FieldOptions) + f.L1.Options = func() protoreflect.ProtoMessage { return opts } + f.L1.IsWeak = opts.GetWeak() + f.L1.HasPacked = opts.Packed != nil + f.L1.IsPacked = opts.GetPacked() + } + f.L1.Number = protoreflect.FieldNumber(fd.GetNumber()) + f.L1.Cardinality = protoreflect.Cardinality(fd.GetLabel()) + if fd.Type != nil { + f.L1.Kind = protoreflect.Kind(fd.GetType()) + } + if fd.JsonName != nil { + f.L1.JSONName.Init(fd.GetJsonName()) + } + } + return fs, nil +} + +func (r descsByName) initOneofsFromDescriptorProto(ods []*descriptorpb.OneofDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (os []filedesc.Oneof, err error) { + os = make([]filedesc.Oneof, len(ods)) // allocate up-front to ensure stable pointers + for i, od := range ods { + o := &os[i] + if o.L0, err = r.makeBase(o, parent, od.GetName(), i, sb); err != nil { + return nil, err + } + if opts := od.GetOptions(); opts != nil { + opts = proto.Clone(opts).(*descriptorpb.OneofOptions) + o.L1.Options = func() protoreflect.ProtoMessage { return opts } + } + } + return os, nil +} + +func (r descsByName) initExtensionDeclarations(xds []*descriptorpb.FieldDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (xs []filedesc.Extension, err error) { + xs = make([]filedesc.Extension, len(xds)) // allocate up-front to ensure stable pointers + for i, xd := range xds { + x := &xs[i] + x.L2 = new(filedesc.ExtensionL2) + if x.L0, err = r.makeBase(x, parent, xd.GetName(), i, sb); err != nil { + return nil, err + } + if opts := xd.GetOptions(); opts != nil { + opts = proto.Clone(opts).(*descriptorpb.FieldOptions) + x.L2.Options = func() protoreflect.ProtoMessage { return opts } + x.L2.IsPacked = opts.GetPacked() + } + x.L1.Number = protoreflect.FieldNumber(xd.GetNumber()) + x.L1.Cardinality = protoreflect.Cardinality(xd.GetLabel()) + if xd.Type != nil { + x.L1.Kind = protoreflect.Kind(xd.GetType()) + } + if xd.JsonName != nil { + x.L2.JSONName.Init(xd.GetJsonName()) + } + } + return xs, nil +} + +func (r descsByName) initServiceDeclarations(sds []*descriptorpb.ServiceDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (ss []filedesc.Service, err error) { + ss = make([]filedesc.Service, len(sds)) // allocate up-front to ensure stable pointers + for i, sd := range sds { + s := &ss[i] + s.L2 = new(filedesc.ServiceL2) + if s.L0, err = r.makeBase(s, parent, sd.GetName(), i, sb); err != nil { + return nil, err + } + if opts := sd.GetOptions(); opts != nil { + opts = proto.Clone(opts).(*descriptorpb.ServiceOptions) + s.L2.Options = func() protoreflect.ProtoMessage { return opts } + } + if s.L2.Methods.List, err = r.initMethodsFromDescriptorProto(sd.GetMethod(), s, sb); err != nil { + return nil, err + } + } + return ss, nil +} + +func (r descsByName) initMethodsFromDescriptorProto(mds []*descriptorpb.MethodDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (ms []filedesc.Method, err error) { + ms = make([]filedesc.Method, len(mds)) // allocate up-front to ensure stable pointers + for i, md := range mds { + m := &ms[i] + if m.L0, err = r.makeBase(m, parent, md.GetName(), i, sb); err != nil { + return nil, err + } + if opts := md.GetOptions(); opts != nil { + opts = proto.Clone(opts).(*descriptorpb.MethodOptions) + m.L1.Options = func() protoreflect.ProtoMessage { return opts } + } + m.L1.IsStreamingClient = md.GetClientStreaming() + m.L1.IsStreamingServer = md.GetServerStreaming() + } + return ms, nil +} + +func (r descsByName) makeBase(child, parent protoreflect.Descriptor, name string, idx int, sb *strs.Builder) (filedesc.BaseL0, error) { + if !protoreflect.Name(name).IsValid() { + return filedesc.BaseL0{}, errors.New("descriptor %q has an invalid nested name: %q", parent.FullName(), name) + } + + // Derive the full name of the child. + // Note that enum values are a sibling to the enum parent in the namespace. + var fullName protoreflect.FullName + if _, ok := parent.(protoreflect.EnumDescriptor); ok { + fullName = sb.AppendFullName(parent.FullName().Parent(), protoreflect.Name(name)) + } else { + fullName = sb.AppendFullName(parent.FullName(), protoreflect.Name(name)) + } + if _, ok := r[fullName]; ok { + return filedesc.BaseL0{}, errors.New("descriptor %q already declared", fullName) + } + r[fullName] = child + + // TODO: Verify that the full name does not already exist in the resolver? + // This is not as critical since most usages of NewFile will register + // the created file back into the registry, which will perform this check. + + return filedesc.BaseL0{ + FullName: fullName, + ParentFile: parent.ParentFile().(*filedesc.File), + Parent: parent, + Index: idx, + }, nil +} diff --git a/vendor/google.golang.org/protobuf/reflect/protodesc/desc_resolve.go b/vendor/google.golang.org/protobuf/reflect/protodesc/desc_resolve.go new file mode 100644 index 00000000000..cebb36cdade --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protodesc/desc_resolve.go @@ -0,0 +1,286 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protodesc + +import ( + "google.golang.org/protobuf/internal/encoding/defval" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + + "google.golang.org/protobuf/types/descriptorpb" +) + +// resolver is a wrapper around a local registry of declarations within the file +// and the remote resolver. The remote resolver is restricted to only return +// descriptors that have been imported. +type resolver struct { + local descsByName + remote Resolver + imports importSet + + allowUnresolvable bool +} + +func (r *resolver) resolveMessageDependencies(ms []filedesc.Message, mds []*descriptorpb.DescriptorProto) (err error) { + for i, md := range mds { + m := &ms[i] + for j, fd := range md.GetField() { + f := &m.L2.Fields.List[j] + if f.L1.Cardinality == protoreflect.Required { + m.L2.RequiredNumbers.List = append(m.L2.RequiredNumbers.List, f.L1.Number) + } + if fd.OneofIndex != nil { + k := int(fd.GetOneofIndex()) + if !(0 <= k && k < len(md.GetOneofDecl())) { + return errors.New("message field %q has an invalid oneof index: %d", f.FullName(), k) + } + o := &m.L2.Oneofs.List[k] + f.L1.ContainingOneof = o + o.L1.Fields.List = append(o.L1.Fields.List, f) + } + + if f.L1.Kind, f.L1.Enum, f.L1.Message, err = r.findTarget(f.Kind(), f.Parent().FullName(), partialName(fd.GetTypeName()), f.IsWeak()); err != nil { + return errors.New("message field %q cannot resolve type: %v", f.FullName(), err) + } + if fd.DefaultValue != nil { + v, ev, err := unmarshalDefault(fd.GetDefaultValue(), f, r.allowUnresolvable) + if err != nil { + return errors.New("message field %q has invalid default: %v", f.FullName(), err) + } + f.L1.Default = filedesc.DefaultValue(v, ev) + } + } + + if err := r.resolveMessageDependencies(m.L1.Messages.List, md.GetNestedType()); err != nil { + return err + } + if err := r.resolveExtensionDependencies(m.L1.Extensions.List, md.GetExtension()); err != nil { + return err + } + } + return nil +} + +func (r *resolver) resolveExtensionDependencies(xs []filedesc.Extension, xds []*descriptorpb.FieldDescriptorProto) (err error) { + for i, xd := range xds { + x := &xs[i] + if x.L1.Extendee, err = r.findMessageDescriptor(x.Parent().FullName(), partialName(xd.GetExtendee()), false); err != nil { + return errors.New("extension field %q cannot resolve extendee: %v", x.FullName(), err) + } + if x.L1.Kind, x.L2.Enum, x.L2.Message, err = r.findTarget(x.Kind(), x.Parent().FullName(), partialName(xd.GetTypeName()), false); err != nil { + return errors.New("extension field %q cannot resolve type: %v", x.FullName(), err) + } + if xd.DefaultValue != nil { + v, ev, err := unmarshalDefault(xd.GetDefaultValue(), x, r.allowUnresolvable) + if err != nil { + return errors.New("extension field %q has invalid default: %v", x.FullName(), err) + } + x.L2.Default = filedesc.DefaultValue(v, ev) + } + } + return nil +} + +func (r *resolver) resolveServiceDependencies(ss []filedesc.Service, sds []*descriptorpb.ServiceDescriptorProto) (err error) { + for i, sd := range sds { + s := &ss[i] + for j, md := range sd.GetMethod() { + m := &s.L2.Methods.List[j] + m.L1.Input, err = r.findMessageDescriptor(m.Parent().FullName(), partialName(md.GetInputType()), false) + if err != nil { + return errors.New("service method %q cannot resolve input: %v", m.FullName(), err) + } + m.L1.Output, err = r.findMessageDescriptor(s.FullName(), partialName(md.GetOutputType()), false) + if err != nil { + return errors.New("service method %q cannot resolve output: %v", m.FullName(), err) + } + } + } + return nil +} + +// findTarget finds an enum or message descriptor if k is an enum, message, +// group, or unknown. If unknown, and the name could be resolved, the kind +// returned kind is set based on the type of the resolved descriptor. +func (r *resolver) findTarget(k protoreflect.Kind, scope protoreflect.FullName, ref partialName, isWeak bool) (protoreflect.Kind, protoreflect.EnumDescriptor, protoreflect.MessageDescriptor, error) { + switch k { + case protoreflect.EnumKind: + ed, err := r.findEnumDescriptor(scope, ref, isWeak) + if err != nil { + return 0, nil, nil, err + } + return k, ed, nil, nil + case protoreflect.MessageKind, protoreflect.GroupKind: + md, err := r.findMessageDescriptor(scope, ref, isWeak) + if err != nil { + return 0, nil, nil, err + } + return k, nil, md, nil + case 0: + // Handle unspecified kinds (possible with parsers that operate + // on a per-file basis without knowledge of dependencies). + d, err := r.findDescriptor(scope, ref) + if err == protoregistry.NotFound && (r.allowUnresolvable || isWeak) { + return k, filedesc.PlaceholderEnum(ref.FullName()), filedesc.PlaceholderMessage(ref.FullName()), nil + } else if err == protoregistry.NotFound { + return 0, nil, nil, errors.New("%q not found", ref.FullName()) + } else if err != nil { + return 0, nil, nil, err + } + switch d := d.(type) { + case protoreflect.EnumDescriptor: + return protoreflect.EnumKind, d, nil, nil + case protoreflect.MessageDescriptor: + return protoreflect.MessageKind, nil, d, nil + default: + return 0, nil, nil, errors.New("unknown kind") + } + default: + if ref != "" { + return 0, nil, nil, errors.New("target name cannot be specified for %v", k) + } + if !k.IsValid() { + return 0, nil, nil, errors.New("invalid kind: %d", k) + } + return k, nil, nil, nil + } +} + +// findDescriptor finds the descriptor by name, +// which may be a relative name within some scope. +// +// Suppose the scope was "fizz.buzz" and the reference was "Foo.Bar", +// then the following full names are searched: +// * fizz.buzz.Foo.Bar +// * fizz.Foo.Bar +// * Foo.Bar +func (r *resolver) findDescriptor(scope protoreflect.FullName, ref partialName) (protoreflect.Descriptor, error) { + if !ref.IsValid() { + return nil, errors.New("invalid name reference: %q", ref) + } + if ref.IsFull() { + scope, ref = "", ref[1:] + } + var foundButNotImported protoreflect.Descriptor + for { + // Derive the full name to search. + s := protoreflect.FullName(ref) + if scope != "" { + s = scope + "." + s + } + + // Check the current file for the descriptor. + if d, ok := r.local[s]; ok { + return d, nil + } + + // Check the remote registry for the descriptor. + d, err := r.remote.FindDescriptorByName(s) + if err == nil { + // Only allow descriptors covered by one of the imports. + if r.imports[d.ParentFile().Path()] { + return d, nil + } + foundButNotImported = d + } else if err != protoregistry.NotFound { + return nil, errors.Wrap(err, "%q", s) + } + + // Continue on at a higher level of scoping. + if scope == "" { + if d := foundButNotImported; d != nil { + return nil, errors.New("resolved %q, but %q is not imported", d.FullName(), d.ParentFile().Path()) + } + return nil, protoregistry.NotFound + } + scope = scope.Parent() + } +} + +func (r *resolver) findEnumDescriptor(scope protoreflect.FullName, ref partialName, isWeak bool) (protoreflect.EnumDescriptor, error) { + d, err := r.findDescriptor(scope, ref) + if err == protoregistry.NotFound && (r.allowUnresolvable || isWeak) { + return filedesc.PlaceholderEnum(ref.FullName()), nil + } else if err == protoregistry.NotFound { + return nil, errors.New("%q not found", ref.FullName()) + } else if err != nil { + return nil, err + } + ed, ok := d.(protoreflect.EnumDescriptor) + if !ok { + return nil, errors.New("resolved %q, but it is not an enum", d.FullName()) + } + return ed, nil +} + +func (r *resolver) findMessageDescriptor(scope protoreflect.FullName, ref partialName, isWeak bool) (protoreflect.MessageDescriptor, error) { + d, err := r.findDescriptor(scope, ref) + if err == protoregistry.NotFound && (r.allowUnresolvable || isWeak) { + return filedesc.PlaceholderMessage(ref.FullName()), nil + } else if err == protoregistry.NotFound { + return nil, errors.New("%q not found", ref.FullName()) + } else if err != nil { + return nil, err + } + md, ok := d.(protoreflect.MessageDescriptor) + if !ok { + return nil, errors.New("resolved %q, but it is not an message", d.FullName()) + } + return md, nil +} + +// partialName is the partial name. A leading dot means that the name is full, +// otherwise the name is relative to some current scope. +// See google.protobuf.FieldDescriptorProto.type_name. +type partialName string + +func (s partialName) IsFull() bool { + return len(s) > 0 && s[0] == '.' +} + +func (s partialName) IsValid() bool { + if s.IsFull() { + return protoreflect.FullName(s[1:]).IsValid() + } + return protoreflect.FullName(s).IsValid() +} + +const unknownPrefix = "*." + +// FullName converts the partial name to a full name on a best-effort basis. +// If relative, it creates an invalid full name, using a "*." prefix +// to indicate that the start of the full name is unknown. +func (s partialName) FullName() protoreflect.FullName { + if s.IsFull() { + return protoreflect.FullName(s[1:]) + } + return protoreflect.FullName(unknownPrefix + s) +} + +func unmarshalDefault(s string, fd protoreflect.FieldDescriptor, allowUnresolvable bool) (protoreflect.Value, protoreflect.EnumValueDescriptor, error) { + var evs protoreflect.EnumValueDescriptors + if fd.Enum() != nil { + evs = fd.Enum().Values() + } + v, ev, err := defval.Unmarshal(s, fd.Kind(), evs, defval.Descriptor) + if err != nil && allowUnresolvable && evs != nil && protoreflect.Name(s).IsValid() { + v = protoreflect.ValueOfEnum(0) + if evs.Len() > 0 { + v = protoreflect.ValueOfEnum(evs.Get(0).Number()) + } + ev = filedesc.PlaceholderEnumValue(fd.Enum().FullName().Parent().Append(protoreflect.Name(s))) + } else if err != nil { + return v, ev, err + } + if fd.Syntax() == protoreflect.Proto3 { + return v, ev, errors.New("cannot be specified under proto3 semantics") + } + if fd.Kind() == protoreflect.MessageKind || fd.Kind() == protoreflect.GroupKind || fd.Cardinality() == protoreflect.Repeated { + return v, ev, errors.New("cannot be specified on composite types") + } + return v, ev, nil +} diff --git a/vendor/google.golang.org/protobuf/reflect/protodesc/desc_validate.go b/vendor/google.golang.org/protobuf/reflect/protodesc/desc_validate.go new file mode 100644 index 00000000000..2d5fa9936ba --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protodesc/desc_validate.go @@ -0,0 +1,371 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protodesc + +import ( + "strings" + "unicode" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/internal/flags" + "google.golang.org/protobuf/internal/genid" + "google.golang.org/protobuf/internal/strs" + "google.golang.org/protobuf/reflect/protoreflect" + + "google.golang.org/protobuf/types/descriptorpb" +) + +func validateEnumDeclarations(es []filedesc.Enum, eds []*descriptorpb.EnumDescriptorProto) error { + for i, ed := range eds { + e := &es[i] + if err := e.L2.ReservedNames.CheckValid(); err != nil { + return errors.New("enum %q reserved names has %v", e.FullName(), err) + } + if err := e.L2.ReservedRanges.CheckValid(); err != nil { + return errors.New("enum %q reserved ranges has %v", e.FullName(), err) + } + if len(ed.GetValue()) == 0 { + return errors.New("enum %q must contain at least one value declaration", e.FullName()) + } + allowAlias := ed.GetOptions().GetAllowAlias() + foundAlias := false + for i := 0; i < e.Values().Len(); i++ { + v1 := e.Values().Get(i) + if v2 := e.Values().ByNumber(v1.Number()); v1 != v2 { + foundAlias = true + if !allowAlias { + return errors.New("enum %q has conflicting non-aliased values on number %d: %q with %q", e.FullName(), v1.Number(), v1.Name(), v2.Name()) + } + } + } + if allowAlias && !foundAlias { + return errors.New("enum %q allows aliases, but none were found", e.FullName()) + } + if e.Syntax() == protoreflect.Proto3 { + if v := e.Values().Get(0); v.Number() != 0 { + return errors.New("enum %q using proto3 semantics must have zero number for the first value", v.FullName()) + } + // Verify that value names in proto3 do not conflict if the + // case-insensitive prefix is removed. + // See protoc v3.8.0: src/google/protobuf/descriptor.cc:4991-5055 + names := map[string]protoreflect.EnumValueDescriptor{} + prefix := strings.Replace(strings.ToLower(string(e.Name())), "_", "", -1) + for i := 0; i < e.Values().Len(); i++ { + v1 := e.Values().Get(i) + s := strs.EnumValueName(strs.TrimEnumPrefix(string(v1.Name()), prefix)) + if v2, ok := names[s]; ok && v1.Number() != v2.Number() { + return errors.New("enum %q using proto3 semantics has conflict: %q with %q", e.FullName(), v1.Name(), v2.Name()) + } + names[s] = v1 + } + } + + for j, vd := range ed.GetValue() { + v := &e.L2.Values.List[j] + if vd.Number == nil { + return errors.New("enum value %q must have a specified number", v.FullName()) + } + if e.L2.ReservedNames.Has(v.Name()) { + return errors.New("enum value %q must not use reserved name", v.FullName()) + } + if e.L2.ReservedRanges.Has(v.Number()) { + return errors.New("enum value %q must not use reserved number %d", v.FullName(), v.Number()) + } + } + } + return nil +} + +func validateMessageDeclarations(ms []filedesc.Message, mds []*descriptorpb.DescriptorProto) error { + for i, md := range mds { + m := &ms[i] + + // Handle the message descriptor itself. + isMessageSet := md.GetOptions().GetMessageSetWireFormat() + if err := m.L2.ReservedNames.CheckValid(); err != nil { + return errors.New("message %q reserved names has %v", m.FullName(), err) + } + if err := m.L2.ReservedRanges.CheckValid(isMessageSet); err != nil { + return errors.New("message %q reserved ranges has %v", m.FullName(), err) + } + if err := m.L2.ExtensionRanges.CheckValid(isMessageSet); err != nil { + return errors.New("message %q extension ranges has %v", m.FullName(), err) + } + if err := (*filedesc.FieldRanges).CheckOverlap(&m.L2.ReservedRanges, &m.L2.ExtensionRanges); err != nil { + return errors.New("message %q reserved and extension ranges has %v", m.FullName(), err) + } + for i := 0; i < m.Fields().Len(); i++ { + f1 := m.Fields().Get(i) + if f2 := m.Fields().ByNumber(f1.Number()); f1 != f2 { + return errors.New("message %q has conflicting fields: %q with %q", m.FullName(), f1.Name(), f2.Name()) + } + } + if isMessageSet && !flags.ProtoLegacy { + return errors.New("message %q is a MessageSet, which is a legacy proto1 feature that is no longer supported", m.FullName()) + } + if isMessageSet && (m.Syntax() != protoreflect.Proto2 || m.Fields().Len() > 0 || m.ExtensionRanges().Len() == 0) { + return errors.New("message %q is an invalid proto1 MessageSet", m.FullName()) + } + if m.Syntax() == protoreflect.Proto3 { + if m.ExtensionRanges().Len() > 0 { + return errors.New("message %q using proto3 semantics cannot have extension ranges", m.FullName()) + } + // Verify that field names in proto3 do not conflict if lowercased + // with all underscores removed. + // See protoc v3.8.0: src/google/protobuf/descriptor.cc:5830-5847 + names := map[string]protoreflect.FieldDescriptor{} + for i := 0; i < m.Fields().Len(); i++ { + f1 := m.Fields().Get(i) + s := strings.Replace(strings.ToLower(string(f1.Name())), "_", "", -1) + if f2, ok := names[s]; ok { + return errors.New("message %q using proto3 semantics has conflict: %q with %q", m.FullName(), f1.Name(), f2.Name()) + } + names[s] = f1 + } + } + + for j, fd := range md.GetField() { + f := &m.L2.Fields.List[j] + if m.L2.ReservedNames.Has(f.Name()) { + return errors.New("message field %q must not use reserved name", f.FullName()) + } + if !f.Number().IsValid() { + return errors.New("message field %q has an invalid number: %d", f.FullName(), f.Number()) + } + if !f.Cardinality().IsValid() { + return errors.New("message field %q has an invalid cardinality: %d", f.FullName(), f.Cardinality()) + } + if m.L2.ReservedRanges.Has(f.Number()) { + return errors.New("message field %q must not use reserved number %d", f.FullName(), f.Number()) + } + if m.L2.ExtensionRanges.Has(f.Number()) { + return errors.New("message field %q with number %d in extension range", f.FullName(), f.Number()) + } + if fd.Extendee != nil { + return errors.New("message field %q may not have extendee: %q", f.FullName(), fd.GetExtendee()) + } + if f.L1.IsProto3Optional { + if f.Syntax() != protoreflect.Proto3 { + return errors.New("message field %q under proto3 optional semantics must be specified in the proto3 syntax", f.FullName()) + } + if f.Cardinality() != protoreflect.Optional { + return errors.New("message field %q under proto3 optional semantics must have optional cardinality", f.FullName()) + } + if f.ContainingOneof() != nil && f.ContainingOneof().Fields().Len() != 1 { + return errors.New("message field %q under proto3 optional semantics must be within a single element oneof", f.FullName()) + } + } + if f.IsWeak() && !flags.ProtoLegacy { + return errors.New("message field %q is a weak field, which is a legacy proto1 feature that is no longer supported", f.FullName()) + } + if f.IsWeak() && (f.Syntax() != protoreflect.Proto2 || !isOptionalMessage(f) || f.ContainingOneof() != nil) { + return errors.New("message field %q may only be weak for an optional message", f.FullName()) + } + if f.IsPacked() && !isPackable(f) { + return errors.New("message field %q is not packable", f.FullName()) + } + if err := checkValidGroup(f); err != nil { + return errors.New("message field %q is an invalid group: %v", f.FullName(), err) + } + if err := checkValidMap(f); err != nil { + return errors.New("message field %q is an invalid map: %v", f.FullName(), err) + } + if f.Syntax() == protoreflect.Proto3 { + if f.Cardinality() == protoreflect.Required { + return errors.New("message field %q using proto3 semantics cannot be required", f.FullName()) + } + if f.Enum() != nil && !f.Enum().IsPlaceholder() && f.Enum().Syntax() != protoreflect.Proto3 { + return errors.New("message field %q using proto3 semantics may only depend on a proto3 enum", f.FullName()) + } + } + } + seenSynthetic := false // synthetic oneofs for proto3 optional must come after real oneofs + for j := range md.GetOneofDecl() { + o := &m.L2.Oneofs.List[j] + if o.Fields().Len() == 0 { + return errors.New("message oneof %q must contain at least one field declaration", o.FullName()) + } + if n := o.Fields().Len(); n-1 != (o.Fields().Get(n-1).Index() - o.Fields().Get(0).Index()) { + return errors.New("message oneof %q must have consecutively declared fields", o.FullName()) + } + + if o.IsSynthetic() { + seenSynthetic = true + continue + } + if !o.IsSynthetic() && seenSynthetic { + return errors.New("message oneof %q must be declared before synthetic oneofs", o.FullName()) + } + + for i := 0; i < o.Fields().Len(); i++ { + f := o.Fields().Get(i) + if f.Cardinality() != protoreflect.Optional { + return errors.New("message field %q belongs in a oneof and must be optional", f.FullName()) + } + if f.IsWeak() { + return errors.New("message field %q belongs in a oneof and must not be a weak reference", f.FullName()) + } + } + } + + if err := validateEnumDeclarations(m.L1.Enums.List, md.GetEnumType()); err != nil { + return err + } + if err := validateMessageDeclarations(m.L1.Messages.List, md.GetNestedType()); err != nil { + return err + } + if err := validateExtensionDeclarations(m.L1.Extensions.List, md.GetExtension()); err != nil { + return err + } + } + return nil +} + +func validateExtensionDeclarations(xs []filedesc.Extension, xds []*descriptorpb.FieldDescriptorProto) error { + for i, xd := range xds { + x := &xs[i] + // NOTE: Avoid using the IsValid method since extensions to MessageSet + // may have a field number higher than normal. This check only verifies + // that the number is not negative or reserved. We check again later + // if we know that the extendee is definitely not a MessageSet. + if n := x.Number(); n < 0 || (protowire.FirstReservedNumber <= n && n <= protowire.LastReservedNumber) { + return errors.New("extension field %q has an invalid number: %d", x.FullName(), x.Number()) + } + if !x.Cardinality().IsValid() || x.Cardinality() == protoreflect.Required { + return errors.New("extension field %q has an invalid cardinality: %d", x.FullName(), x.Cardinality()) + } + if xd.JsonName != nil { + if xd.GetJsonName() != strs.JSONCamelCase(string(x.Name())) { + return errors.New("extension field %q may not have an explicitly set JSON name: %q", x.FullName(), xd.GetJsonName()) + } + } + if xd.OneofIndex != nil { + return errors.New("extension field %q may not be part of a oneof", x.FullName()) + } + if md := x.ContainingMessage(); !md.IsPlaceholder() { + if !md.ExtensionRanges().Has(x.Number()) { + return errors.New("extension field %q extends %q with non-extension field number: %d", x.FullName(), md.FullName(), x.Number()) + } + isMessageSet := md.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() + if isMessageSet && !isOptionalMessage(x) { + return errors.New("extension field %q extends MessageSet and must be an optional message", x.FullName()) + } + if !isMessageSet && !x.Number().IsValid() { + return errors.New("extension field %q has an invalid number: %d", x.FullName(), x.Number()) + } + } + if xd.GetOptions().GetWeak() { + return errors.New("extension field %q cannot be a weak reference", x.FullName()) + } + if x.IsPacked() && !isPackable(x) { + return errors.New("extension field %q is not packable", x.FullName()) + } + if err := checkValidGroup(x); err != nil { + return errors.New("extension field %q is an invalid group: %v", x.FullName(), err) + } + if md := x.Message(); md != nil && md.IsMapEntry() { + return errors.New("extension field %q cannot be a map entry", x.FullName()) + } + if x.Syntax() == protoreflect.Proto3 { + switch x.ContainingMessage().FullName() { + case (*descriptorpb.FileOptions)(nil).ProtoReflect().Descriptor().FullName(): + case (*descriptorpb.EnumOptions)(nil).ProtoReflect().Descriptor().FullName(): + case (*descriptorpb.EnumValueOptions)(nil).ProtoReflect().Descriptor().FullName(): + case (*descriptorpb.MessageOptions)(nil).ProtoReflect().Descriptor().FullName(): + case (*descriptorpb.FieldOptions)(nil).ProtoReflect().Descriptor().FullName(): + case (*descriptorpb.OneofOptions)(nil).ProtoReflect().Descriptor().FullName(): + case (*descriptorpb.ExtensionRangeOptions)(nil).ProtoReflect().Descriptor().FullName(): + case (*descriptorpb.ServiceOptions)(nil).ProtoReflect().Descriptor().FullName(): + case (*descriptorpb.MethodOptions)(nil).ProtoReflect().Descriptor().FullName(): + default: + return errors.New("extension field %q cannot be declared in proto3 unless extended descriptor options", x.FullName()) + } + } + } + return nil +} + +// isOptionalMessage reports whether this is an optional message. +// If the kind is unknown, it is assumed to be a message. +func isOptionalMessage(fd protoreflect.FieldDescriptor) bool { + return (fd.Kind() == 0 || fd.Kind() == protoreflect.MessageKind) && fd.Cardinality() == protoreflect.Optional +} + +// isPackable checks whether the pack option can be specified. +func isPackable(fd protoreflect.FieldDescriptor) bool { + switch fd.Kind() { + case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind, protoreflect.GroupKind: + return false + } + return fd.IsList() +} + +// checkValidGroup reports whether fd is a valid group according to the same +// rules that protoc imposes. +func checkValidGroup(fd protoreflect.FieldDescriptor) error { + md := fd.Message() + switch { + case fd.Kind() != protoreflect.GroupKind: + return nil + case fd.Syntax() != protoreflect.Proto2: + return errors.New("invalid under proto2 semantics") + case md == nil || md.IsPlaceholder(): + return errors.New("message must be resolvable") + case fd.FullName().Parent() != md.FullName().Parent(): + return errors.New("message and field must be declared in the same scope") + case !unicode.IsUpper(rune(md.Name()[0])): + return errors.New("message name must start with an uppercase") + case fd.Name() != protoreflect.Name(strings.ToLower(string(md.Name()))): + return errors.New("field name must be lowercased form of the message name") + } + return nil +} + +// checkValidMap checks whether the field is a valid map according to the same +// rules that protoc imposes. +// See protoc v3.8.0: src/google/protobuf/descriptor.cc:6045-6115 +func checkValidMap(fd protoreflect.FieldDescriptor) error { + md := fd.Message() + switch { + case md == nil || !md.IsMapEntry(): + return nil + case fd.FullName().Parent() != md.FullName().Parent(): + return errors.New("message and field must be declared in the same scope") + case md.Name() != protoreflect.Name(strs.MapEntryName(string(fd.Name()))): + return errors.New("incorrect implicit map entry name") + case fd.Cardinality() != protoreflect.Repeated: + return errors.New("field must be repeated") + case md.Fields().Len() != 2: + return errors.New("message must have exactly two fields") + case md.ExtensionRanges().Len() > 0: + return errors.New("message must not have any extension ranges") + case md.Enums().Len()+md.Messages().Len()+md.Extensions().Len() > 0: + return errors.New("message must not have any nested declarations") + } + kf := md.Fields().Get(0) + vf := md.Fields().Get(1) + switch { + case kf.Name() != genid.MapEntry_Key_field_name || kf.Number() != genid.MapEntry_Key_field_number || kf.Cardinality() != protoreflect.Optional || kf.ContainingOneof() != nil || kf.HasDefault(): + return errors.New("invalid key field") + case vf.Name() != genid.MapEntry_Value_field_name || vf.Number() != genid.MapEntry_Value_field_number || vf.Cardinality() != protoreflect.Optional || vf.ContainingOneof() != nil || vf.HasDefault(): + return errors.New("invalid value field") + } + switch kf.Kind() { + case protoreflect.BoolKind: // bool + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: // int32 + case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: // int64 + case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: // uint32 + case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: // uint64 + case protoreflect.StringKind: // string + default: + return errors.New("invalid key kind: %v", kf.Kind()) + } + if e := vf.Enum(); e != nil && e.Values().Len() > 0 && e.Values().Get(0).Number() != 0 { + return errors.New("map enum value must have zero number for the first value") + } + return nil +} diff --git a/vendor/google.golang.org/protobuf/reflect/protodesc/proto.go b/vendor/google.golang.org/protobuf/reflect/protodesc/proto.go new file mode 100644 index 00000000000..00d35e02eee --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protodesc/proto.go @@ -0,0 +1,242 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protodesc + +import ( + "fmt" + "strings" + + "google.golang.org/protobuf/internal/encoding/defval" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + + "google.golang.org/protobuf/types/descriptorpb" +) + +// ToFileDescriptorProto copies a protoreflect.FileDescriptor into a +// google.protobuf.FileDescriptorProto message. +func ToFileDescriptorProto(file protoreflect.FileDescriptor) *descriptorpb.FileDescriptorProto { + p := &descriptorpb.FileDescriptorProto{ + Name: proto.String(file.Path()), + Package: proto.String(string(file.Package())), + Options: proto.Clone(file.Options()).(*descriptorpb.FileOptions), + } + for i, imports := 0, file.Imports(); i < imports.Len(); i++ { + imp := imports.Get(i) + p.Dependency = append(p.Dependency, imp.Path()) + if imp.IsPublic { + p.PublicDependency = append(p.PublicDependency, int32(i)) + } + if imp.IsWeak { + p.WeakDependency = append(p.WeakDependency, int32(i)) + } + } + for i, locs := 0, file.SourceLocations(); i < locs.Len(); i++ { + loc := locs.Get(i) + l := &descriptorpb.SourceCodeInfo_Location{} + l.Path = append(l.Path, loc.Path...) + if loc.StartLine == loc.EndLine { + l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndColumn)} + } else { + l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndLine), int32(loc.EndColumn)} + } + l.LeadingDetachedComments = append([]string(nil), loc.LeadingDetachedComments...) + if loc.LeadingComments != "" { + l.LeadingComments = proto.String(loc.LeadingComments) + } + if loc.TrailingComments != "" { + l.TrailingComments = proto.String(loc.TrailingComments) + } + if p.SourceCodeInfo == nil { + p.SourceCodeInfo = &descriptorpb.SourceCodeInfo{} + } + p.SourceCodeInfo.Location = append(p.SourceCodeInfo.Location, l) + + } + for i, messages := 0, file.Messages(); i < messages.Len(); i++ { + p.MessageType = append(p.MessageType, ToDescriptorProto(messages.Get(i))) + } + for i, enums := 0, file.Enums(); i < enums.Len(); i++ { + p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i))) + } + for i, services := 0, file.Services(); i < services.Len(); i++ { + p.Service = append(p.Service, ToServiceDescriptorProto(services.Get(i))) + } + for i, exts := 0, file.Extensions(); i < exts.Len(); i++ { + p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i))) + } + if syntax := file.Syntax(); syntax != protoreflect.Proto2 { + p.Syntax = proto.String(file.Syntax().String()) + } + return p +} + +// ToDescriptorProto copies a protoreflect.MessageDescriptor into a +// google.protobuf.DescriptorProto message. +func ToDescriptorProto(message protoreflect.MessageDescriptor) *descriptorpb.DescriptorProto { + p := &descriptorpb.DescriptorProto{ + Name: proto.String(string(message.Name())), + Options: proto.Clone(message.Options()).(*descriptorpb.MessageOptions), + } + for i, fields := 0, message.Fields(); i < fields.Len(); i++ { + p.Field = append(p.Field, ToFieldDescriptorProto(fields.Get(i))) + } + for i, exts := 0, message.Extensions(); i < exts.Len(); i++ { + p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i))) + } + for i, messages := 0, message.Messages(); i < messages.Len(); i++ { + p.NestedType = append(p.NestedType, ToDescriptorProto(messages.Get(i))) + } + for i, enums := 0, message.Enums(); i < enums.Len(); i++ { + p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i))) + } + for i, xranges := 0, message.ExtensionRanges(); i < xranges.Len(); i++ { + xrange := xranges.Get(i) + p.ExtensionRange = append(p.ExtensionRange, &descriptorpb.DescriptorProto_ExtensionRange{ + Start: proto.Int32(int32(xrange[0])), + End: proto.Int32(int32(xrange[1])), + Options: proto.Clone(message.ExtensionRangeOptions(i)).(*descriptorpb.ExtensionRangeOptions), + }) + } + for i, oneofs := 0, message.Oneofs(); i < oneofs.Len(); i++ { + p.OneofDecl = append(p.OneofDecl, ToOneofDescriptorProto(oneofs.Get(i))) + } + for i, ranges := 0, message.ReservedRanges(); i < ranges.Len(); i++ { + rrange := ranges.Get(i) + p.ReservedRange = append(p.ReservedRange, &descriptorpb.DescriptorProto_ReservedRange{ + Start: proto.Int32(int32(rrange[0])), + End: proto.Int32(int32(rrange[1])), + }) + } + for i, names := 0, message.ReservedNames(); i < names.Len(); i++ { + p.ReservedName = append(p.ReservedName, string(names.Get(i))) + } + return p +} + +// ToFieldDescriptorProto copies a protoreflect.FieldDescriptor into a +// google.protobuf.FieldDescriptorProto message. +func ToFieldDescriptorProto(field protoreflect.FieldDescriptor) *descriptorpb.FieldDescriptorProto { + p := &descriptorpb.FieldDescriptorProto{ + Name: proto.String(string(field.Name())), + Number: proto.Int32(int32(field.Number())), + Label: descriptorpb.FieldDescriptorProto_Label(field.Cardinality()).Enum(), + Options: proto.Clone(field.Options()).(*descriptorpb.FieldOptions), + } + if field.IsExtension() { + p.Extendee = fullNameOf(field.ContainingMessage()) + } + if field.Kind().IsValid() { + p.Type = descriptorpb.FieldDescriptorProto_Type(field.Kind()).Enum() + } + if field.Enum() != nil { + p.TypeName = fullNameOf(field.Enum()) + } + if field.Message() != nil { + p.TypeName = fullNameOf(field.Message()) + } + if field.HasJSONName() { + p.JsonName = proto.String(field.JSONName()) + } + if field.Syntax() == protoreflect.Proto3 && field.HasOptionalKeyword() { + p.Proto3Optional = proto.Bool(true) + } + if field.HasDefault() { + def, err := defval.Marshal(field.Default(), field.DefaultEnumValue(), field.Kind(), defval.Descriptor) + if err != nil && field.DefaultEnumValue() != nil { + def = string(field.DefaultEnumValue().Name()) // occurs for unresolved enum values + } else if err != nil { + panic(fmt.Sprintf("%v: %v", field.FullName(), err)) + } + p.DefaultValue = proto.String(def) + } + if oneof := field.ContainingOneof(); oneof != nil { + p.OneofIndex = proto.Int32(int32(oneof.Index())) + } + return p +} + +// ToOneofDescriptorProto copies a protoreflect.OneofDescriptor into a +// google.protobuf.OneofDescriptorProto message. +func ToOneofDescriptorProto(oneof protoreflect.OneofDescriptor) *descriptorpb.OneofDescriptorProto { + return &descriptorpb.OneofDescriptorProto{ + Name: proto.String(string(oneof.Name())), + Options: proto.Clone(oneof.Options()).(*descriptorpb.OneofOptions), + } +} + +// ToEnumDescriptorProto copies a protoreflect.EnumDescriptor into a +// google.protobuf.EnumDescriptorProto message. +func ToEnumDescriptorProto(enum protoreflect.EnumDescriptor) *descriptorpb.EnumDescriptorProto { + p := &descriptorpb.EnumDescriptorProto{ + Name: proto.String(string(enum.Name())), + Options: proto.Clone(enum.Options()).(*descriptorpb.EnumOptions), + } + for i, values := 0, enum.Values(); i < values.Len(); i++ { + p.Value = append(p.Value, ToEnumValueDescriptorProto(values.Get(i))) + } + for i, ranges := 0, enum.ReservedRanges(); i < ranges.Len(); i++ { + rrange := ranges.Get(i) + p.ReservedRange = append(p.ReservedRange, &descriptorpb.EnumDescriptorProto_EnumReservedRange{ + Start: proto.Int32(int32(rrange[0])), + End: proto.Int32(int32(rrange[1])), + }) + } + for i, names := 0, enum.ReservedNames(); i < names.Len(); i++ { + p.ReservedName = append(p.ReservedName, string(names.Get(i))) + } + return p +} + +// ToEnumValueDescriptorProto copies a protoreflect.EnumValueDescriptor into a +// google.protobuf.EnumValueDescriptorProto message. +func ToEnumValueDescriptorProto(value protoreflect.EnumValueDescriptor) *descriptorpb.EnumValueDescriptorProto { + return &descriptorpb.EnumValueDescriptorProto{ + Name: proto.String(string(value.Name())), + Number: proto.Int32(int32(value.Number())), + Options: proto.Clone(value.Options()).(*descriptorpb.EnumValueOptions), + } +} + +// ToServiceDescriptorProto copies a protoreflect.ServiceDescriptor into a +// google.protobuf.ServiceDescriptorProto message. +func ToServiceDescriptorProto(service protoreflect.ServiceDescriptor) *descriptorpb.ServiceDescriptorProto { + p := &descriptorpb.ServiceDescriptorProto{ + Name: proto.String(string(service.Name())), + Options: proto.Clone(service.Options()).(*descriptorpb.ServiceOptions), + } + for i, methods := 0, service.Methods(); i < methods.Len(); i++ { + p.Method = append(p.Method, ToMethodDescriptorProto(methods.Get(i))) + } + return p +} + +// ToMethodDescriptorProto copies a protoreflect.MethodDescriptor into a +// google.protobuf.MethodDescriptorProto message. +func ToMethodDescriptorProto(method protoreflect.MethodDescriptor) *descriptorpb.MethodDescriptorProto { + p := &descriptorpb.MethodDescriptorProto{ + Name: proto.String(string(method.Name())), + InputType: fullNameOf(method.Input()), + OutputType: fullNameOf(method.Output()), + Options: proto.Clone(method.Options()).(*descriptorpb.MethodOptions), + } + if method.IsStreamingClient() { + p.ClientStreaming = proto.Bool(true) + } + if method.IsStreamingServer() { + p.ServerStreaming = proto.Bool(true) + } + return p +} + +func fullNameOf(d protoreflect.Descriptor) *string { + if d == nil { + return nil + } + if strings.HasPrefix(string(d.FullName()), unknownPrefix) { + return proto.String(string(d.FullName()[len(unknownPrefix):])) + } + return proto.String("." + string(d.FullName())) +} diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/methods.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/methods.go new file mode 100644 index 00000000000..6be5d16e9f3 --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/methods.go @@ -0,0 +1,77 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protoreflect + +import ( + "google.golang.org/protobuf/internal/pragma" +) + +// The following types are used by the fast-path Message.ProtoMethods method. +// +// To avoid polluting the public protoreflect API with types used only by +// low-level implementations, the canonical definitions of these types are +// in the runtime/protoiface package. The definitions here and in protoiface +// must be kept in sync. +type ( + methods = struct { + pragma.NoUnkeyedLiterals + Flags supportFlags + Size func(sizeInput) sizeOutput + Marshal func(marshalInput) (marshalOutput, error) + Unmarshal func(unmarshalInput) (unmarshalOutput, error) + Merge func(mergeInput) mergeOutput + CheckInitialized func(checkInitializedInput) (checkInitializedOutput, error) + } + supportFlags = uint64 + sizeInput = struct { + pragma.NoUnkeyedLiterals + Message Message + Flags uint8 + } + sizeOutput = struct { + pragma.NoUnkeyedLiterals + Size int + } + marshalInput = struct { + pragma.NoUnkeyedLiterals + Message Message + Buf []byte + Flags uint8 + } + marshalOutput = struct { + pragma.NoUnkeyedLiterals + Buf []byte + } + unmarshalInput = struct { + pragma.NoUnkeyedLiterals + Message Message + Buf []byte + Flags uint8 + Resolver interface { + FindExtensionByName(field FullName) (ExtensionType, error) + FindExtensionByNumber(message FullName, field FieldNumber) (ExtensionType, error) + } + } + unmarshalOutput = struct { + pragma.NoUnkeyedLiterals + Flags uint8 + } + mergeInput = struct { + pragma.NoUnkeyedLiterals + Source Message + Destination Message + } + mergeOutput = struct { + pragma.NoUnkeyedLiterals + Flags uint8 + } + checkInitializedInput = struct { + pragma.NoUnkeyedLiterals + Message Message + } + checkInitializedOutput = struct { + pragma.NoUnkeyedLiterals + } +) diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/proto.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/proto.go new file mode 100644 index 00000000000..dd85915bd4b --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/proto.go @@ -0,0 +1,504 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package protoreflect provides interfaces to dynamically manipulate messages. +// +// This package includes type descriptors which describe the structure of types +// defined in proto source files and value interfaces which provide the +// ability to examine and manipulate the contents of messages. +// +// +// Protocol Buffer Descriptors +// +// Protobuf descriptors (e.g., EnumDescriptor or MessageDescriptor) +// are immutable objects that represent protobuf type information. +// They are wrappers around the messages declared in descriptor.proto. +// Protobuf descriptors alone lack any information regarding Go types. +// +// Enums and messages generated by this module implement Enum and ProtoMessage, +// where the Descriptor and ProtoReflect.Descriptor accessors respectively +// return the protobuf descriptor for the values. +// +// The protobuf descriptor interfaces are not meant to be implemented by +// user code since they might need to be extended in the future to support +// additions to the protobuf language. +// The "google.golang.org/protobuf/reflect/protodesc" package converts between +// google.protobuf.DescriptorProto messages and protobuf descriptors. +// +// +// Go Type Descriptors +// +// A type descriptor (e.g., EnumType or MessageType) is a constructor for +// a concrete Go type that represents the associated protobuf descriptor. +// There is commonly a one-to-one relationship between protobuf descriptors and +// Go type descriptors, but it can potentially be a one-to-many relationship. +// +// Enums and messages generated by this module implement Enum and ProtoMessage, +// where the Type and ProtoReflect.Type accessors respectively +// return the protobuf descriptor for the values. +// +// The "google.golang.org/protobuf/types/dynamicpb" package can be used to +// create Go type descriptors from protobuf descriptors. +// +// +// Value Interfaces +// +// The Enum and Message interfaces provide a reflective view over an +// enum or message instance. For enums, it provides the ability to retrieve +// the enum value number for any concrete enum type. For messages, it provides +// the ability to access or manipulate fields of the message. +// +// To convert a proto.Message to a protoreflect.Message, use the +// former's ProtoReflect method. Since the ProtoReflect method is new to the +// v2 message interface, it may not be present on older message implementations. +// The "github.com/golang/protobuf/proto".MessageReflect function can be used +// to obtain a reflective view on older messages. +// +// +// Relationships +// +// The following diagrams demonstrate the relationships between +// various types declared in this package. +// +// +// ┌───────────────────────────────────┐ +// V │ +// ┌────────────── New(n) ─────────────┐ │ +// │ │ │ +// │ ┌──── Descriptor() ──┐ │ ┌── Number() ──┐ │ +// │ │ V V │ V │ +// ╔════════════╗ ╔════════════════╗ ╔════════╗ ╔════════════╗ +// ║ EnumType ║ ║ EnumDescriptor ║ ║ Enum ║ ║ EnumNumber ║ +// ╚════════════╝ ╚════════════════╝ ╚════════╝ ╚════════════╝ +// Λ Λ │ │ +// │ └─── Descriptor() ──┘ │ +// │ │ +// └────────────────── Type() ───────┘ +// +// • An EnumType describes a concrete Go enum type. +// It has an EnumDescriptor and can construct an Enum instance. +// +// • An EnumDescriptor describes an abstract protobuf enum type. +// +// • An Enum is a concrete enum instance. Generated enums implement Enum. +// +// +// ┌──────────────── New() ─────────────────┐ +// │ │ +// │ ┌─── Descriptor() ─────┐ │ ┌── Interface() ───┐ +// │ │ V V │ V +// ╔═════════════╗ ╔═══════════════════╗ ╔═════════╗ ╔══════════════╗ +// ║ MessageType ║ ║ MessageDescriptor ║ ║ Message ║ ║ ProtoMessage ║ +// ╚═════════════╝ ╚═══════════════════╝ ╚═════════╝ ╚══════════════╝ +// Λ Λ │ │ Λ │ +// │ └──── Descriptor() ────┘ │ └─ ProtoReflect() ─┘ +// │ │ +// └─────────────────── Type() ─────────┘ +// +// • A MessageType describes a concrete Go message type. +// It has a MessageDescriptor and can construct a Message instance. +// +// • A MessageDescriptor describes an abstract protobuf message type. +// +// • A Message is a concrete message instance. Generated messages implement +// ProtoMessage, which can convert to/from a Message. +// +// +// ┌── TypeDescriptor() ──┐ ┌───── Descriptor() ─────┐ +// │ V │ V +// ╔═══════════════╗ ╔═════════════════════════╗ ╔═════════════════════╗ +// ║ ExtensionType ║ ║ ExtensionTypeDescriptor ║ ║ ExtensionDescriptor ║ +// ╚═══════════════╝ ╚═════════════════════════╝ ╚═════════════════════╝ +// Λ │ │ Λ │ Λ +// └─────── Type() ───────┘ │ └─── may implement ────┘ │ +// │ │ +// └────── implements ────────┘ +// +// • An ExtensionType describes a concrete Go implementation of an extension. +// It has an ExtensionTypeDescriptor and can convert to/from +// abstract Values and Go values. +// +// • An ExtensionTypeDescriptor is an ExtensionDescriptor +// which also has an ExtensionType. +// +// • An ExtensionDescriptor describes an abstract protobuf extension field and +// may not always be an ExtensionTypeDescriptor. +package protoreflect + +import ( + "fmt" + "strings" + + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/internal/pragma" +) + +type doNotImplement pragma.DoNotImplement + +// ProtoMessage is the top-level interface that all proto messages implement. +// This is declared in the protoreflect package to avoid a cyclic dependency; +// use the proto.Message type instead, which aliases this type. +type ProtoMessage interface{ ProtoReflect() Message } + +// Syntax is the language version of the proto file. +type Syntax syntax + +type syntax int8 // keep exact type opaque as the int type may change + +const ( + Proto2 Syntax = 2 + Proto3 Syntax = 3 +) + +// IsValid reports whether the syntax is valid. +func (s Syntax) IsValid() bool { + switch s { + case Proto2, Proto3: + return true + default: + return false + } +} + +// String returns s as a proto source identifier (e.g., "proto2"). +func (s Syntax) String() string { + switch s { + case Proto2: + return "proto2" + case Proto3: + return "proto3" + default: + return fmt.Sprintf("", s) + } +} + +// GoString returns s as a Go source identifier (e.g., "Proto2"). +func (s Syntax) GoString() string { + switch s { + case Proto2: + return "Proto2" + case Proto3: + return "Proto3" + default: + return fmt.Sprintf("Syntax(%d)", s) + } +} + +// Cardinality determines whether a field is optional, required, or repeated. +type Cardinality cardinality + +type cardinality int8 // keep exact type opaque as the int type may change + +// Constants as defined by the google.protobuf.Cardinality enumeration. +const ( + Optional Cardinality = 1 // appears zero or one times + Required Cardinality = 2 // appears exactly one time; invalid with Proto3 + Repeated Cardinality = 3 // appears zero or more times +) + +// IsValid reports whether the cardinality is valid. +func (c Cardinality) IsValid() bool { + switch c { + case Optional, Required, Repeated: + return true + default: + return false + } +} + +// String returns c as a proto source identifier (e.g., "optional"). +func (c Cardinality) String() string { + switch c { + case Optional: + return "optional" + case Required: + return "required" + case Repeated: + return "repeated" + default: + return fmt.Sprintf("", c) + } +} + +// GoString returns c as a Go source identifier (e.g., "Optional"). +func (c Cardinality) GoString() string { + switch c { + case Optional: + return "Optional" + case Required: + return "Required" + case Repeated: + return "Repeated" + default: + return fmt.Sprintf("Cardinality(%d)", c) + } +} + +// Kind indicates the basic proto kind of a field. +type Kind kind + +type kind int8 // keep exact type opaque as the int type may change + +// Constants as defined by the google.protobuf.Field.Kind enumeration. +const ( + BoolKind Kind = 8 + EnumKind Kind = 14 + Int32Kind Kind = 5 + Sint32Kind Kind = 17 + Uint32Kind Kind = 13 + Int64Kind Kind = 3 + Sint64Kind Kind = 18 + Uint64Kind Kind = 4 + Sfixed32Kind Kind = 15 + Fixed32Kind Kind = 7 + FloatKind Kind = 2 + Sfixed64Kind Kind = 16 + Fixed64Kind Kind = 6 + DoubleKind Kind = 1 + StringKind Kind = 9 + BytesKind Kind = 12 + MessageKind Kind = 11 + GroupKind Kind = 10 +) + +// IsValid reports whether the kind is valid. +func (k Kind) IsValid() bool { + switch k { + case BoolKind, EnumKind, + Int32Kind, Sint32Kind, Uint32Kind, + Int64Kind, Sint64Kind, Uint64Kind, + Sfixed32Kind, Fixed32Kind, FloatKind, + Sfixed64Kind, Fixed64Kind, DoubleKind, + StringKind, BytesKind, MessageKind, GroupKind: + return true + default: + return false + } +} + +// String returns k as a proto source identifier (e.g., "bool"). +func (k Kind) String() string { + switch k { + case BoolKind: + return "bool" + case EnumKind: + return "enum" + case Int32Kind: + return "int32" + case Sint32Kind: + return "sint32" + case Uint32Kind: + return "uint32" + case Int64Kind: + return "int64" + case Sint64Kind: + return "sint64" + case Uint64Kind: + return "uint64" + case Sfixed32Kind: + return "sfixed32" + case Fixed32Kind: + return "fixed32" + case FloatKind: + return "float" + case Sfixed64Kind: + return "sfixed64" + case Fixed64Kind: + return "fixed64" + case DoubleKind: + return "double" + case StringKind: + return "string" + case BytesKind: + return "bytes" + case MessageKind: + return "message" + case GroupKind: + return "group" + default: + return fmt.Sprintf("", k) + } +} + +// GoString returns k as a Go source identifier (e.g., "BoolKind"). +func (k Kind) GoString() string { + switch k { + case BoolKind: + return "BoolKind" + case EnumKind: + return "EnumKind" + case Int32Kind: + return "Int32Kind" + case Sint32Kind: + return "Sint32Kind" + case Uint32Kind: + return "Uint32Kind" + case Int64Kind: + return "Int64Kind" + case Sint64Kind: + return "Sint64Kind" + case Uint64Kind: + return "Uint64Kind" + case Sfixed32Kind: + return "Sfixed32Kind" + case Fixed32Kind: + return "Fixed32Kind" + case FloatKind: + return "FloatKind" + case Sfixed64Kind: + return "Sfixed64Kind" + case Fixed64Kind: + return "Fixed64Kind" + case DoubleKind: + return "DoubleKind" + case StringKind: + return "StringKind" + case BytesKind: + return "BytesKind" + case MessageKind: + return "MessageKind" + case GroupKind: + return "GroupKind" + default: + return fmt.Sprintf("Kind(%d)", k) + } +} + +// FieldNumber is the field number in a message. +type FieldNumber = protowire.Number + +// FieldNumbers represent a list of field numbers. +type FieldNumbers interface { + // Len reports the number of fields in the list. + Len() int + // Get returns the ith field number. It panics if out of bounds. + Get(i int) FieldNumber + // Has reports whether n is within the list of fields. + Has(n FieldNumber) bool + + doNotImplement +} + +// FieldRanges represent a list of field number ranges. +type FieldRanges interface { + // Len reports the number of ranges in the list. + Len() int + // Get returns the ith range. It panics if out of bounds. + Get(i int) [2]FieldNumber // start inclusive; end exclusive + // Has reports whether n is within any of the ranges. + Has(n FieldNumber) bool + + doNotImplement +} + +// EnumNumber is the numeric value for an enum. +type EnumNumber int32 + +// EnumRanges represent a list of enum number ranges. +type EnumRanges interface { + // Len reports the number of ranges in the list. + Len() int + // Get returns the ith range. It panics if out of bounds. + Get(i int) [2]EnumNumber // start inclusive; end inclusive + // Has reports whether n is within any of the ranges. + Has(n EnumNumber) bool + + doNotImplement +} + +// Name is the short name for a proto declaration. This is not the name +// as used in Go source code, which might not be identical to the proto name. +type Name string // e.g., "Kind" + +// IsValid reports whether s is a syntactically valid name. +// An empty name is invalid. +func (s Name) IsValid() bool { + return consumeIdent(string(s)) == len(s) +} + +// Names represent a list of names. +type Names interface { + // Len reports the number of names in the list. + Len() int + // Get returns the ith name. It panics if out of bounds. + Get(i int) Name + // Has reports whether s matches any names in the list. + Has(s Name) bool + + doNotImplement +} + +// FullName is a qualified name that uniquely identifies a proto declaration. +// A qualified name is the concatenation of the proto package along with the +// fully-declared name (i.e., name of parent preceding the name of the child), +// with a '.' delimiter placed between each Name. +// +// This should not have any leading or trailing dots. +type FullName string // e.g., "google.protobuf.Field.Kind" + +// IsValid reports whether s is a syntactically valid full name. +// An empty full name is invalid. +func (s FullName) IsValid() bool { + i := consumeIdent(string(s)) + if i < 0 { + return false + } + for len(s) > i { + if s[i] != '.' { + return false + } + i++ + n := consumeIdent(string(s[i:])) + if n < 0 { + return false + } + i += n + } + return true +} + +func consumeIdent(s string) (i int) { + if len(s) == 0 || !isLetter(s[i]) { + return -1 + } + i++ + for len(s) > i && isLetterDigit(s[i]) { + i++ + } + return i +} +func isLetter(c byte) bool { + return c == '_' || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') +} +func isLetterDigit(c byte) bool { + return isLetter(c) || ('0' <= c && c <= '9') +} + +// Name returns the short name, which is the last identifier segment. +// A single segment FullName is the Name itself. +func (n FullName) Name() Name { + if i := strings.LastIndexByte(string(n), '.'); i >= 0 { + return Name(n[i+1:]) + } + return Name(n) +} + +// Parent returns the full name with the trailing identifier removed. +// A single segment FullName has no parent. +func (n FullName) Parent() FullName { + if i := strings.LastIndexByte(string(n), '.'); i >= 0 { + return n[:i] + } + return "" +} + +// Append returns the qualified name appended with the provided short name. +// +// Invariant: n == n.Parent().Append(n.Name()) // assuming n is valid +func (n FullName) Append(s Name) FullName { + if n == "" { + return FullName(s) + } + return n + "." + FullName(s) +} diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/source.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/source.go new file mode 100644 index 00000000000..32ea3d98cd2 --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/source.go @@ -0,0 +1,52 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protoreflect + +// SourceLocations is a list of source locations. +type SourceLocations interface { + // Len reports the number of source locations in the proto file. + Len() int + // Get returns the ith SourceLocation. It panics if out of bounds. + Get(int) SourceLocation + + doNotImplement + + // TODO: Add ByPath and ByDescriptor helper methods. +} + +// SourceLocation describes a source location and +// corresponds with the google.protobuf.SourceCodeInfo.Location message. +type SourceLocation struct { + // Path is the path to the declaration from the root file descriptor. + // The contents of this slice must not be mutated. + Path SourcePath + + // StartLine and StartColumn are the zero-indexed starting location + // in the source file for the declaration. + StartLine, StartColumn int + // EndLine and EndColumn are the zero-indexed ending location + // in the source file for the declaration. + // In the descriptor.proto, the end line may be omitted if it is identical + // to the start line. Here, it is always populated. + EndLine, EndColumn int + + // LeadingDetachedComments are the leading detached comments + // for the declaration. The contents of this slice must not be mutated. + LeadingDetachedComments []string + // LeadingComments is the leading attached comment for the declaration. + LeadingComments string + // TrailingComments is the trailing attached comment for the declaration. + TrailingComments string +} + +// SourcePath identifies part of a file descriptor for a source location. +// The SourcePath is a sequence of either field numbers or indexes into +// a repeated field that form a path starting from the root file descriptor. +// +// See google.protobuf.SourceCodeInfo.Location.path. +type SourcePath []int32 + +// TODO: Add SourcePath.String method to pretty-print the path. For example: +// ".message_type[6].nested_type[15].field[3]" diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/type.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/type.go new file mode 100644 index 00000000000..5be14a72584 --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/type.go @@ -0,0 +1,631 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protoreflect + +// Descriptor provides a set of accessors that are common to every descriptor. +// Each descriptor type wraps the equivalent google.protobuf.XXXDescriptorProto, +// but provides efficient lookup and immutability. +// +// Each descriptor is comparable. Equality implies that the two types are +// exactly identical. However, it is possible for the same semantically +// identical proto type to be represented by multiple type descriptors. +// +// For example, suppose we have t1 and t2 which are both MessageDescriptors. +// If t1 == t2, then the types are definitely equal and all accessors return +// the same information. However, if t1 != t2, then it is still possible that +// they still represent the same proto type (e.g., t1.FullName == t2.FullName). +// This can occur if a descriptor type is created dynamically, or multiple +// versions of the same proto type are accidentally linked into the Go binary. +type Descriptor interface { + // ParentFile returns the parent file descriptor that this descriptor + // is declared within. The parent file for the file descriptor is itself. + // + // Support for this functionality is optional and may return nil. + ParentFile() FileDescriptor + + // Parent returns the parent containing this descriptor declaration. + // The following shows the mapping from child type to possible parent types: + // + // ╔═════════════════════╤═══════════════════════════════════╗ + // ║ Child type │ Possible parent types ║ + // ╠═════════════════════╪═══════════════════════════════════╣ + // ║ FileDescriptor │ nil ║ + // ║ MessageDescriptor │ FileDescriptor, MessageDescriptor ║ + // ║ FieldDescriptor │ FileDescriptor, MessageDescriptor ║ + // ║ OneofDescriptor │ MessageDescriptor ║ + // ║ EnumDescriptor │ FileDescriptor, MessageDescriptor ║ + // ║ EnumValueDescriptor │ EnumDescriptor ║ + // ║ ServiceDescriptor │ FileDescriptor ║ + // ║ MethodDescriptor │ ServiceDescriptor ║ + // ╚═════════════════════╧═══════════════════════════════════╝ + // + // Support for this functionality is optional and may return nil. + Parent() Descriptor + + // Index returns the index of this descriptor within its parent. + // It returns 0 if the descriptor does not have a parent or if the parent + // is unknown. + Index() int + + // Syntax is the protobuf syntax. + Syntax() Syntax // e.g., Proto2 or Proto3 + + // Name is the short name of the declaration (i.e., FullName.Name). + Name() Name // e.g., "Any" + + // FullName is the fully-qualified name of the declaration. + // + // The FullName is a concatenation of the full name of the type that this + // type is declared within and the declaration name. For example, + // field "foo_field" in message "proto.package.MyMessage" is + // uniquely identified as "proto.package.MyMessage.foo_field". + // Enum values are an exception to the rule (see EnumValueDescriptor). + FullName() FullName // e.g., "google.protobuf.Any" + + // IsPlaceholder reports whether type information is missing since a + // dependency is not resolved, in which case only name information is known. + // + // Placeholder types may only be returned by the following accessors + // as a result of unresolved dependencies or weak imports: + // + // ╔═══════════════════════════════════╤═════════════════════╗ + // ║ Accessor │ Descriptor ║ + // ╠═══════════════════════════════════╪═════════════════════╣ + // ║ FileImports.FileDescriptor │ FileDescriptor ║ + // ║ FieldDescriptor.Enum │ EnumDescriptor ║ + // ║ FieldDescriptor.Message │ MessageDescriptor ║ + // ║ FieldDescriptor.DefaultEnumValue │ EnumValueDescriptor ║ + // ║ FieldDescriptor.ContainingMessage │ MessageDescriptor ║ + // ║ MethodDescriptor.Input │ MessageDescriptor ║ + // ║ MethodDescriptor.Output │ MessageDescriptor ║ + // ╚═══════════════════════════════════╧═════════════════════╝ + // + // If true, only Name and FullName are valid. + // For FileDescriptor, the Path is also valid. + IsPlaceholder() bool + + // Options returns the descriptor options. The caller must not modify + // the returned value. + // + // To avoid a dependency cycle, this function returns a proto.Message value. + // The proto message type returned for each descriptor type is as follows: + // ╔═════════════════════╤══════════════════════════════════════════╗ + // ║ Go type │ Protobuf message type ║ + // ╠═════════════════════╪══════════════════════════════════════════╣ + // ║ FileDescriptor │ google.protobuf.FileOptions ║ + // ║ EnumDescriptor │ google.protobuf.EnumOptions ║ + // ║ EnumValueDescriptor │ google.protobuf.EnumValueOptions ║ + // ║ MessageDescriptor │ google.protobuf.MessageOptions ║ + // ║ FieldDescriptor │ google.protobuf.FieldOptions ║ + // ║ OneofDescriptor │ google.protobuf.OneofOptions ║ + // ║ ServiceDescriptor │ google.protobuf.ServiceOptions ║ + // ║ MethodDescriptor │ google.protobuf.MethodOptions ║ + // ╚═════════════════════╧══════════════════════════════════════════╝ + // + // This method returns a typed nil-pointer if no options are present. + // The caller must import the descriptorpb package to use this. + Options() ProtoMessage + + doNotImplement +} + +// FileDescriptor describes the types in a complete proto file and +// corresponds with the google.protobuf.FileDescriptorProto message. +// +// Top-level declarations: +// EnumDescriptor, MessageDescriptor, FieldDescriptor, and/or ServiceDescriptor. +type FileDescriptor interface { + Descriptor // Descriptor.FullName is identical to Package + + // Path returns the file name, relative to the source tree root. + Path() string // e.g., "path/to/file.proto" + // Package returns the protobuf package namespace. + Package() FullName // e.g., "google.protobuf" + + // Imports is a list of imported proto files. + Imports() FileImports + + // Enums is a list of the top-level enum declarations. + Enums() EnumDescriptors + // Messages is a list of the top-level message declarations. + Messages() MessageDescriptors + // Extensions is a list of the top-level extension declarations. + Extensions() ExtensionDescriptors + // Services is a list of the top-level service declarations. + Services() ServiceDescriptors + + // SourceLocations is a list of source locations. + SourceLocations() SourceLocations + + isFileDescriptor +} +type isFileDescriptor interface{ ProtoType(FileDescriptor) } + +// FileImports is a list of file imports. +type FileImports interface { + // Len reports the number of files imported by this proto file. + Len() int + // Get returns the ith FileImport. It panics if out of bounds. + Get(i int) FileImport + + doNotImplement +} + +// FileImport is the declaration for a proto file import. +type FileImport struct { + // FileDescriptor is the file type for the given import. + // It is a placeholder descriptor if IsWeak is set or if a dependency has + // not been regenerated to implement the new reflection APIs. + FileDescriptor + + // IsPublic reports whether this is a public import, which causes this file + // to alias declarations within the imported file. The intended use cases + // for this feature is the ability to move proto files without breaking + // existing dependencies. + // + // The current file and the imported file must be within proto package. + IsPublic bool + + // IsWeak reports whether this is a weak import, which does not impose + // a direct dependency on the target file. + // + // Weak imports are a legacy proto1 feature. Equivalent behavior is + // achieved using proto2 extension fields or proto3 Any messages. + IsWeak bool +} + +// MessageDescriptor describes a message and +// corresponds with the google.protobuf.DescriptorProto message. +// +// Nested declarations: +// FieldDescriptor, OneofDescriptor, FieldDescriptor, EnumDescriptor, +// and/or MessageDescriptor. +type MessageDescriptor interface { + Descriptor + + // IsMapEntry indicates that this is an auto-generated message type to + // represent the entry type for a map field. + // + // Map entry messages have only two fields: + // • a "key" field with a field number of 1 + // • a "value" field with a field number of 2 + // The key and value types are determined by these two fields. + // + // If IsMapEntry is true, it implies that FieldDescriptor.IsMap is true + // for some field with this message type. + IsMapEntry() bool + + // Fields is a list of nested field declarations. + Fields() FieldDescriptors + // Oneofs is a list of nested oneof declarations. + Oneofs() OneofDescriptors + + // ReservedNames is a list of reserved field names. + ReservedNames() Names + // ReservedRanges is a list of reserved ranges of field numbers. + ReservedRanges() FieldRanges + // RequiredNumbers is a list of required field numbers. + // In Proto3, it is always an empty list. + RequiredNumbers() FieldNumbers + // ExtensionRanges is the field ranges used for extension fields. + // In Proto3, it is always an empty ranges. + ExtensionRanges() FieldRanges + // ExtensionRangeOptions returns the ith extension range options. + // + // To avoid a dependency cycle, this method returns a proto.Message value, + // which always contains a google.protobuf.ExtensionRangeOptions message. + // This method returns a typed nil-pointer if no options are present. + // The caller must import the descriptorpb package to use this. + ExtensionRangeOptions(i int) ProtoMessage + + // Enums is a list of nested enum declarations. + Enums() EnumDescriptors + // Messages is a list of nested message declarations. + Messages() MessageDescriptors + // Extensions is a list of nested extension declarations. + Extensions() ExtensionDescriptors + + isMessageDescriptor +} +type isMessageDescriptor interface{ ProtoType(MessageDescriptor) } + +// MessageType encapsulates a MessageDescriptor with a concrete Go implementation. +type MessageType interface { + // New returns a newly allocated empty message. + New() Message + + // Zero returns an empty, read-only message. + Zero() Message + + // Descriptor returns the message descriptor. + // + // Invariant: t.Descriptor() == t.New().Descriptor() + Descriptor() MessageDescriptor +} + +// MessageDescriptors is a list of message declarations. +type MessageDescriptors interface { + // Len reports the number of messages. + Len() int + // Get returns the ith MessageDescriptor. It panics if out of bounds. + Get(i int) MessageDescriptor + // ByName returns the MessageDescriptor for a message named s. + // It returns nil if not found. + ByName(s Name) MessageDescriptor + + doNotImplement +} + +// FieldDescriptor describes a field within a message and +// corresponds with the google.protobuf.FieldDescriptorProto message. +// +// It is used for both normal fields defined within the parent message +// (e.g., MessageDescriptor.Fields) and fields that extend some remote message +// (e.g., FileDescriptor.Extensions or MessageDescriptor.Extensions). +type FieldDescriptor interface { + Descriptor + + // Number reports the unique number for this field. + Number() FieldNumber + // Cardinality reports the cardinality for this field. + Cardinality() Cardinality + // Kind reports the basic kind for this field. + Kind() Kind + + // HasJSONName reports whether this field has an explicitly set JSON name. + HasJSONName() bool + + // JSONName reports the name used for JSON serialization. + // It is usually the camel-cased form of the field name. + JSONName() string + + // HasPresence reports whether the field distinguishes between unpopulated + // and default values. + HasPresence() bool + + // IsExtension reports whether this is an extension field. If false, + // then Parent and ContainingMessage refer to the same message. + // Otherwise, ContainingMessage and Parent likely differ. + IsExtension() bool + + // HasOptionalKeyword reports whether the "optional" keyword was explicitly + // specified in the source .proto file. + HasOptionalKeyword() bool + + // IsWeak reports whether this is a weak field, which does not impose a + // direct dependency on the target type. + // If true, then Message returns a placeholder type. + IsWeak() bool + + // IsPacked reports whether repeated primitive numeric kinds should be + // serialized using a packed encoding. + // If true, then it implies Cardinality is Repeated. + IsPacked() bool + + // IsList reports whether this field represents a list, + // where the value type for the associated field is a List. + // It is equivalent to checking whether Cardinality is Repeated and + // that IsMap reports false. + IsList() bool + + // IsMap reports whether this field represents a map, + // where the value type for the associated field is a Map. + // It is equivalent to checking whether Cardinality is Repeated, + // that the Kind is MessageKind, and that Message.IsMapEntry reports true. + IsMap() bool + + // MapKey returns the field descriptor for the key in the map entry. + // It returns nil if IsMap reports false. + MapKey() FieldDescriptor + + // MapValue returns the field descriptor for the value in the map entry. + // It returns nil if IsMap reports false. + MapValue() FieldDescriptor + + // HasDefault reports whether this field has a default value. + HasDefault() bool + + // Default returns the default value for scalar fields. + // For proto2, it is the default value as specified in the proto file, + // or the zero value if unspecified. + // For proto3, it is always the zero value of the scalar. + // The Value type is determined by the Kind. + Default() Value + + // DefaultEnumValue returns the enum value descriptor for the default value + // of an enum field, and is nil for any other kind of field. + DefaultEnumValue() EnumValueDescriptor + + // ContainingOneof is the containing oneof that this field belongs to, + // and is nil if this field is not part of a oneof. + ContainingOneof() OneofDescriptor + + // ContainingMessage is the containing message that this field belongs to. + // For extension fields, this may not necessarily be the parent message + // that the field is declared within. + ContainingMessage() MessageDescriptor + + // Enum is the enum descriptor if Kind is EnumKind. + // It returns nil for any other Kind. + Enum() EnumDescriptor + + // Message is the message descriptor if Kind is + // MessageKind or GroupKind. It returns nil for any other Kind. + Message() MessageDescriptor + + isFieldDescriptor +} +type isFieldDescriptor interface{ ProtoType(FieldDescriptor) } + +// FieldDescriptors is a list of field declarations. +type FieldDescriptors interface { + // Len reports the number of fields. + Len() int + // Get returns the ith FieldDescriptor. It panics if out of bounds. + Get(i int) FieldDescriptor + // ByName returns the FieldDescriptor for a field named s. + // It returns nil if not found. + ByName(s Name) FieldDescriptor + // ByJSONName returns the FieldDescriptor for a field with s as the JSON name. + // It returns nil if not found. + ByJSONName(s string) FieldDescriptor + // ByNumber returns the FieldDescriptor for a field numbered n. + // It returns nil if not found. + ByNumber(n FieldNumber) FieldDescriptor + + doNotImplement +} + +// OneofDescriptor describes a oneof field set within a given message and +// corresponds with the google.protobuf.OneofDescriptorProto message. +type OneofDescriptor interface { + Descriptor + + // IsSynthetic reports whether this is a synthetic oneof created to support + // proto3 optional semantics. If true, Fields contains exactly one field + // with HasOptionalKeyword specified. + IsSynthetic() bool + + // Fields is a list of fields belonging to this oneof. + Fields() FieldDescriptors + + isOneofDescriptor +} +type isOneofDescriptor interface{ ProtoType(OneofDescriptor) } + +// OneofDescriptors is a list of oneof declarations. +type OneofDescriptors interface { + // Len reports the number of oneof fields. + Len() int + // Get returns the ith OneofDescriptor. It panics if out of bounds. + Get(i int) OneofDescriptor + // ByName returns the OneofDescriptor for a oneof named s. + // It returns nil if not found. + ByName(s Name) OneofDescriptor + + doNotImplement +} + +// ExtensionDescriptor is an alias of FieldDescriptor for documentation. +type ExtensionDescriptor = FieldDescriptor + +// ExtensionTypeDescriptor is an ExtensionDescriptor with an associated ExtensionType. +type ExtensionTypeDescriptor interface { + ExtensionDescriptor + + // Type returns the associated ExtensionType. + Type() ExtensionType + + // Descriptor returns the plain ExtensionDescriptor without the + // associated ExtensionType. + Descriptor() ExtensionDescriptor +} + +// ExtensionDescriptors is a list of field declarations. +type ExtensionDescriptors interface { + // Len reports the number of fields. + Len() int + // Get returns the ith ExtensionDescriptor. It panics if out of bounds. + Get(i int) ExtensionDescriptor + // ByName returns the ExtensionDescriptor for a field named s. + // It returns nil if not found. + ByName(s Name) ExtensionDescriptor + + doNotImplement +} + +// ExtensionType encapsulates an ExtensionDescriptor with a concrete +// Go implementation. The nested field descriptor must be for a extension field. +// +// While a normal field is a member of the parent message that it is declared +// within (see Descriptor.Parent), an extension field is a member of some other +// target message (see ExtensionDescriptor.Extendee) and may have no +// relationship with the parent. However, the full name of an extension field is +// relative to the parent that it is declared within. +// +// For example: +// syntax = "proto2"; +// package example; +// message FooMessage { +// extensions 100 to max; +// } +// message BarMessage { +// extends FooMessage { optional BarMessage bar_field = 100; } +// } +// +// Field "bar_field" is an extension of FooMessage, but its full name is +// "example.BarMessage.bar_field" instead of "example.FooMessage.bar_field". +type ExtensionType interface { + // New returns a new value for the field. + // For scalars, this returns the default value in native Go form. + New() Value + + // Zero returns a new value for the field. + // For scalars, this returns the default value in native Go form. + // For composite types, this returns an empty, read-only message, list, or map. + Zero() Value + + // TypeDescriptor returns the extension type descriptor. + TypeDescriptor() ExtensionTypeDescriptor + + // ValueOf wraps the input and returns it as a Value. + // ValueOf panics if the input value is invalid or not the appropriate type. + // + // ValueOf is more extensive than protoreflect.ValueOf for a given field's + // value as it has more type information available. + ValueOf(interface{}) Value + + // InterfaceOf completely unwraps the Value to the underlying Go type. + // InterfaceOf panics if the input is nil or does not represent the + // appropriate underlying Go type. For composite types, it panics if the + // value is not mutable. + // + // InterfaceOf is able to unwrap the Value further than Value.Interface + // as it has more type information available. + InterfaceOf(Value) interface{} + + // IsValidValue reports whether the Value is valid to assign to the field. + IsValidValue(Value) bool + + // IsValidInterface reports whether the input is valid to assign to the field. + IsValidInterface(interface{}) bool +} + +// EnumDescriptor describes an enum and +// corresponds with the google.protobuf.EnumDescriptorProto message. +// +// Nested declarations: +// EnumValueDescriptor. +type EnumDescriptor interface { + Descriptor + + // Values is a list of nested enum value declarations. + Values() EnumValueDescriptors + + // ReservedNames is a list of reserved enum names. + ReservedNames() Names + // ReservedRanges is a list of reserved ranges of enum numbers. + ReservedRanges() EnumRanges + + isEnumDescriptor +} +type isEnumDescriptor interface{ ProtoType(EnumDescriptor) } + +// EnumType encapsulates an EnumDescriptor with a concrete Go implementation. +type EnumType interface { + // New returns an instance of this enum type with its value set to n. + New(n EnumNumber) Enum + + // Descriptor returns the enum descriptor. + // + // Invariant: t.Descriptor() == t.New(0).Descriptor() + Descriptor() EnumDescriptor +} + +// EnumDescriptors is a list of enum declarations. +type EnumDescriptors interface { + // Len reports the number of enum types. + Len() int + // Get returns the ith EnumDescriptor. It panics if out of bounds. + Get(i int) EnumDescriptor + // ByName returns the EnumDescriptor for an enum named s. + // It returns nil if not found. + ByName(s Name) EnumDescriptor + + doNotImplement +} + +// EnumValueDescriptor describes an enum value and +// corresponds with the google.protobuf.EnumValueDescriptorProto message. +// +// All other proto declarations are in the namespace of the parent. +// However, enum values do not follow this rule and are within the namespace +// of the parent's parent (i.e., they are a sibling of the containing enum). +// Thus, a value named "FOO_VALUE" declared within an enum uniquely identified +// as "proto.package.MyEnum" has a full name of "proto.package.FOO_VALUE". +type EnumValueDescriptor interface { + Descriptor + + // Number returns the enum value as an integer. + Number() EnumNumber + + isEnumValueDescriptor +} +type isEnumValueDescriptor interface{ ProtoType(EnumValueDescriptor) } + +// EnumValueDescriptors is a list of enum value declarations. +type EnumValueDescriptors interface { + // Len reports the number of enum values. + Len() int + // Get returns the ith EnumValueDescriptor. It panics if out of bounds. + Get(i int) EnumValueDescriptor + // ByName returns the EnumValueDescriptor for the enum value named s. + // It returns nil if not found. + ByName(s Name) EnumValueDescriptor + // ByNumber returns the EnumValueDescriptor for the enum value numbered n. + // If multiple have the same number, the first one defined is returned + // It returns nil if not found. + ByNumber(n EnumNumber) EnumValueDescriptor + + doNotImplement +} + +// ServiceDescriptor describes a service and +// corresponds with the google.protobuf.ServiceDescriptorProto message. +// +// Nested declarations: MethodDescriptor. +type ServiceDescriptor interface { + Descriptor + + // Methods is a list of nested message declarations. + Methods() MethodDescriptors + + isServiceDescriptor +} +type isServiceDescriptor interface{ ProtoType(ServiceDescriptor) } + +// ServiceDescriptors is a list of service declarations. +type ServiceDescriptors interface { + // Len reports the number of services. + Len() int + // Get returns the ith ServiceDescriptor. It panics if out of bounds. + Get(i int) ServiceDescriptor + // ByName returns the ServiceDescriptor for a service named s. + // It returns nil if not found. + ByName(s Name) ServiceDescriptor + + doNotImplement +} + +// MethodDescriptor describes a method and +// corresponds with the google.protobuf.MethodDescriptorProto message. +type MethodDescriptor interface { + Descriptor + + // Input is the input message descriptor. + Input() MessageDescriptor + // Output is the output message descriptor. + Output() MessageDescriptor + // IsStreamingClient reports whether the client streams multiple messages. + IsStreamingClient() bool + // IsStreamingServer reports whether the server streams multiple messages. + IsStreamingServer() bool + + isMethodDescriptor +} +type isMethodDescriptor interface{ ProtoType(MethodDescriptor) } + +// MethodDescriptors is a list of method declarations. +type MethodDescriptors interface { + // Len reports the number of methods. + Len() int + // Get returns the ith MethodDescriptor. It panics if out of bounds. + Get(i int) MethodDescriptor + // ByName returns the MethodDescriptor for a service method named s. + // It returns nil if not found. + ByName(s Name) MethodDescriptor + + doNotImplement +} diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/value.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/value.go new file mode 100644 index 00000000000..f3198107782 --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/value.go @@ -0,0 +1,285 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protoreflect + +import "google.golang.org/protobuf/encoding/protowire" + +// Enum is a reflection interface for a concrete enum value, +// which provides type information and a getter for the enum number. +// Enum does not provide a mutable API since enums are commonly backed by +// Go constants, which are not addressable. +type Enum interface { + // Descriptor returns enum descriptor, which contains only the protobuf + // type information for the enum. + Descriptor() EnumDescriptor + + // Type returns the enum type, which encapsulates both Go and protobuf + // type information. If the Go type information is not needed, + // it is recommended that the enum descriptor be used instead. + Type() EnumType + + // Number returns the enum value as an integer. + Number() EnumNumber +} + +// Message is a reflective interface for a concrete message value, +// encapsulating both type and value information for the message. +// +// Accessor/mutators for individual fields are keyed by FieldDescriptor. +// For non-extension fields, the descriptor must exactly match the +// field known by the parent message. +// For extension fields, the descriptor must implement ExtensionTypeDescriptor, +// extend the parent message (i.e., have the same message FullName), and +// be within the parent's extension range. +// +// Each field Value can be a scalar or a composite type (Message, List, or Map). +// See Value for the Go types associated with a FieldDescriptor. +// Providing a Value that is invalid or of an incorrect type panics. +type Message interface { + // Descriptor returns message descriptor, which contains only the protobuf + // type information for the message. + Descriptor() MessageDescriptor + + // Type returns the message type, which encapsulates both Go and protobuf + // type information. If the Go type information is not needed, + // it is recommended that the message descriptor be used instead. + Type() MessageType + + // New returns a newly allocated and mutable empty message. + New() Message + + // Interface unwraps the message reflection interface and + // returns the underlying ProtoMessage interface. + Interface() ProtoMessage + + // Range iterates over every populated field in an undefined order, + // calling f for each field descriptor and value encountered. + // Range returns immediately if f returns false. + // While iterating, mutating operations may only be performed + // on the current field descriptor. + Range(f func(FieldDescriptor, Value) bool) + + // Has reports whether a field is populated. + // + // Some fields have the property of nullability where it is possible to + // distinguish between the default value of a field and whether the field + // was explicitly populated with the default value. Singular message fields, + // member fields of a oneof, and proto2 scalar fields are nullable. Such + // fields are populated only if explicitly set. + // + // In other cases (aside from the nullable cases above), + // a proto3 scalar field is populated if it contains a non-zero value, and + // a repeated field is populated if it is non-empty. + Has(FieldDescriptor) bool + + // Clear clears the field such that a subsequent Has call reports false. + // + // Clearing an extension field clears both the extension type and value + // associated with the given field number. + // + // Clear is a mutating operation and unsafe for concurrent use. + Clear(FieldDescriptor) + + // Get retrieves the value for a field. + // + // For unpopulated scalars, it returns the default value, where + // the default value of a bytes scalar is guaranteed to be a copy. + // For unpopulated composite types, it returns an empty, read-only view + // of the value; to obtain a mutable reference, use Mutable. + Get(FieldDescriptor) Value + + // Set stores the value for a field. + // + // For a field belonging to a oneof, it implicitly clears any other field + // that may be currently set within the same oneof. + // For extension fields, it implicitly stores the provided ExtensionType. + // When setting a composite type, it is unspecified whether the stored value + // aliases the source's memory in any way. If the composite value is an + // empty, read-only value, then it panics. + // + // Set is a mutating operation and unsafe for concurrent use. + Set(FieldDescriptor, Value) + + // Mutable returns a mutable reference to a composite type. + // + // If the field is unpopulated, it may allocate a composite value. + // For a field belonging to a oneof, it implicitly clears any other field + // that may be currently set within the same oneof. + // For extension fields, it implicitly stores the provided ExtensionType + // if not already stored. + // It panics if the field does not contain a composite type. + // + // Mutable is a mutating operation and unsafe for concurrent use. + Mutable(FieldDescriptor) Value + + // NewField returns a new value that is assignable to the field + // for the given descriptor. For scalars, this returns the default value. + // For lists, maps, and messages, this returns a new, empty, mutable value. + NewField(FieldDescriptor) Value + + // WhichOneof reports which field within the oneof is populated, + // returning nil if none are populated. + // It panics if the oneof descriptor does not belong to this message. + WhichOneof(OneofDescriptor) FieldDescriptor + + // GetUnknown retrieves the entire list of unknown fields. + // The caller may only mutate the contents of the RawFields + // if the mutated bytes are stored back into the message with SetUnknown. + GetUnknown() RawFields + + // SetUnknown stores an entire list of unknown fields. + // The raw fields must be syntactically valid according to the wire format. + // An implementation may panic if this is not the case. + // Once stored, the caller must not mutate the content of the RawFields. + // An empty RawFields may be passed to clear the fields. + // + // SetUnknown is a mutating operation and unsafe for concurrent use. + SetUnknown(RawFields) + + // IsValid reports whether the message is valid. + // + // An invalid message is an empty, read-only value. + // + // An invalid message often corresponds to a nil pointer of the concrete + // message type, but the details are implementation dependent. + // Validity is not part of the protobuf data model, and may not + // be preserved in marshaling or other operations. + IsValid() bool + + // ProtoMethods returns optional fast-path implementions of various operations. + // This method may return nil. + // + // The returned methods type is identical to + // "google.golang.org/protobuf/runtime/protoiface".Methods. + // Consult the protoiface package documentation for details. + ProtoMethods() *methods +} + +// RawFields is the raw bytes for an ordered sequence of fields. +// Each field contains both the tag (representing field number and wire type), +// and also the wire data itself. +type RawFields []byte + +// IsValid reports whether b is syntactically correct wire format. +func (b RawFields) IsValid() bool { + for len(b) > 0 { + _, _, n := protowire.ConsumeField(b) + if n < 0 { + return false + } + b = b[n:] + } + return true +} + +// List is a zero-indexed, ordered list. +// The element Value type is determined by FieldDescriptor.Kind. +// Providing a Value that is invalid or of an incorrect type panics. +type List interface { + // Len reports the number of entries in the List. + // Get, Set, and Truncate panic with out of bound indexes. + Len() int + + // Get retrieves the value at the given index. + // It never returns an invalid value. + Get(int) Value + + // Set stores a value for the given index. + // When setting a composite type, it is unspecified whether the set + // value aliases the source's memory in any way. + // + // Set is a mutating operation and unsafe for concurrent use. + Set(int, Value) + + // Append appends the provided value to the end of the list. + // When appending a composite type, it is unspecified whether the appended + // value aliases the source's memory in any way. + // + // Append is a mutating operation and unsafe for concurrent use. + Append(Value) + + // AppendMutable appends a new, empty, mutable message value to the end + // of the list and returns it. + // It panics if the list does not contain a message type. + AppendMutable() Value + + // Truncate truncates the list to a smaller length. + // + // Truncate is a mutating operation and unsafe for concurrent use. + Truncate(int) + + // NewElement returns a new value for a list element. + // For enums, this returns the first enum value. + // For other scalars, this returns the zero value. + // For messages, this returns a new, empty, mutable value. + NewElement() Value + + // IsValid reports whether the list is valid. + // + // An invalid list is an empty, read-only value. + // + // Validity is not part of the protobuf data model, and may not + // be preserved in marshaling or other operations. + IsValid() bool +} + +// Map is an unordered, associative map. +// The entry MapKey type is determined by FieldDescriptor.MapKey.Kind. +// The entry Value type is determined by FieldDescriptor.MapValue.Kind. +// Providing a MapKey or Value that is invalid or of an incorrect type panics. +type Map interface { + // Len reports the number of elements in the map. + Len() int + + // Range iterates over every map entry in an undefined order, + // calling f for each key and value encountered. + // Range calls f Len times unless f returns false, which stops iteration. + // While iterating, mutating operations may only be performed + // on the current map key. + Range(f func(MapKey, Value) bool) + + // Has reports whether an entry with the given key is in the map. + Has(MapKey) bool + + // Clear clears the entry associated with they given key. + // The operation does nothing if there is no entry associated with the key. + // + // Clear is a mutating operation and unsafe for concurrent use. + Clear(MapKey) + + // Get retrieves the value for an entry with the given key. + // It returns an invalid value for non-existent entries. + Get(MapKey) Value + + // Set stores the value for an entry with the given key. + // It panics when given a key or value that is invalid or the wrong type. + // When setting a composite type, it is unspecified whether the set + // value aliases the source's memory in any way. + // + // Set is a mutating operation and unsafe for concurrent use. + Set(MapKey, Value) + + // Mutable retrieves a mutable reference to the entry for the given key. + // If no entry exists for the key, it creates a new, empty, mutable value + // and stores it as the entry for the key. + // It panics if the map value is not a message. + Mutable(MapKey) Value + + // NewValue returns a new value assignable as a map value. + // For enums, this returns the first enum value. + // For other scalars, this returns the zero value. + // For messages, this returns a new, empty, mutable value. + NewValue() Value + + // IsValid reports whether the map is valid. + // + // An invalid map is an empty, read-only value. + // + // An invalid message often corresponds to a nil Go map value, + // but the details are implementation dependent. + // Validity is not part of the protobuf data model, and may not + // be preserved in marshaling or other operations. + IsValid() bool +} diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go new file mode 100644 index 00000000000..918e685e1d5 --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_pure.go @@ -0,0 +1,59 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build purego appengine + +package protoreflect + +import "google.golang.org/protobuf/internal/pragma" + +type valueType int + +const ( + nilType valueType = iota + boolType + int32Type + int64Type + uint32Type + uint64Type + float32Type + float64Type + stringType + bytesType + enumType + ifaceType +) + +// value is a union where only one type can be represented at a time. +// This uses a distinct field for each type. This is type safe in Go, but +// occupies more memory than necessary (72B). +type value struct { + pragma.DoNotCompare // 0B + + typ valueType // 8B + num uint64 // 8B + str string // 16B + bin []byte // 24B + iface interface{} // 16B +} + +func valueOfString(v string) Value { + return Value{typ: stringType, str: v} +} +func valueOfBytes(v []byte) Value { + return Value{typ: bytesType, bin: v} +} +func valueOfIface(v interface{}) Value { + return Value{typ: ifaceType, iface: v} +} + +func (v Value) getString() string { + return v.str +} +func (v Value) getBytes() []byte { + return v.bin +} +func (v Value) getIface() interface{} { + return v.iface +} diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_union.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_union.go new file mode 100644 index 00000000000..5a341472419 --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_union.go @@ -0,0 +1,411 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protoreflect + +import ( + "fmt" + "math" +) + +// Value is a union where only one Go type may be set at a time. +// The Value is used to represent all possible values a field may take. +// The following shows which Go type is used to represent each proto Kind: +// +// ╔════════════╤═════════════════════════════════════╗ +// ║ Go type │ Protobuf kind ║ +// ╠════════════╪═════════════════════════════════════╣ +// ║ bool │ BoolKind ║ +// ║ int32 │ Int32Kind, Sint32Kind, Sfixed32Kind ║ +// ║ int64 │ Int64Kind, Sint64Kind, Sfixed64Kind ║ +// ║ uint32 │ Uint32Kind, Fixed32Kind ║ +// ║ uint64 │ Uint64Kind, Fixed64Kind ║ +// ║ float32 │ FloatKind ║ +// ║ float64 │ DoubleKind ║ +// ║ string │ StringKind ║ +// ║ []byte │ BytesKind ║ +// ║ EnumNumber │ EnumKind ║ +// ║ Message │ MessageKind, GroupKind ║ +// ╚════════════╧═════════════════════════════════════╝ +// +// Multiple protobuf Kinds may be represented by a single Go type if the type +// can losslessly represent the information for the proto kind. For example, +// Int64Kind, Sint64Kind, and Sfixed64Kind are all represented by int64, +// but use different integer encoding methods. +// +// The List or Map types are used if the field cardinality is repeated. +// A field is a List if FieldDescriptor.IsList reports true. +// A field is a Map if FieldDescriptor.IsMap reports true. +// +// Converting to/from a Value and a concrete Go value panics on type mismatch. +// For example, ValueOf("hello").Int() panics because this attempts to +// retrieve an int64 from a string. +type Value value + +// The protoreflect API uses a custom Value union type instead of interface{} +// to keep the future open for performance optimizations. Using an interface{} +// always incurs an allocation for primitives (e.g., int64) since it needs to +// be boxed on the heap (as interfaces can only contain pointers natively). +// Instead, we represent the Value union as a flat struct that internally keeps +// track of which type is set. Using unsafe, the Value union can be reduced +// down to 24B, which is identical in size to a slice. +// +// The latest compiler (Go1.11) currently suffers from some limitations: +// • With inlining, the compiler should be able to statically prove that +// only one of these switch cases are taken and inline one specific case. +// See https://golang.org/issue/22310. + +// ValueOf returns a Value initialized with the concrete value stored in v. +// This panics if the type does not match one of the allowed types in the +// Value union. +func ValueOf(v interface{}) Value { + switch v := v.(type) { + case nil: + return Value{} + case bool: + return ValueOfBool(v) + case int32: + return ValueOfInt32(v) + case int64: + return ValueOfInt64(v) + case uint32: + return ValueOfUint32(v) + case uint64: + return ValueOfUint64(v) + case float32: + return ValueOfFloat32(v) + case float64: + return ValueOfFloat64(v) + case string: + return ValueOfString(v) + case []byte: + return ValueOfBytes(v) + case EnumNumber: + return ValueOfEnum(v) + case Message, List, Map: + return valueOfIface(v) + case ProtoMessage: + panic(fmt.Sprintf("invalid proto.Message(%T) type, expected a protoreflect.Message type", v)) + default: + panic(fmt.Sprintf("invalid type: %T", v)) + } +} + +// ValueOfBool returns a new boolean value. +func ValueOfBool(v bool) Value { + if v { + return Value{typ: boolType, num: 1} + } else { + return Value{typ: boolType, num: 0} + } +} + +// ValueOfInt32 returns a new int32 value. +func ValueOfInt32(v int32) Value { + return Value{typ: int32Type, num: uint64(v)} +} + +// ValueOfInt64 returns a new int64 value. +func ValueOfInt64(v int64) Value { + return Value{typ: int64Type, num: uint64(v)} +} + +// ValueOfUint32 returns a new uint32 value. +func ValueOfUint32(v uint32) Value { + return Value{typ: uint32Type, num: uint64(v)} +} + +// ValueOfUint64 returns a new uint64 value. +func ValueOfUint64(v uint64) Value { + return Value{typ: uint64Type, num: v} +} + +// ValueOfFloat32 returns a new float32 value. +func ValueOfFloat32(v float32) Value { + return Value{typ: float32Type, num: uint64(math.Float64bits(float64(v)))} +} + +// ValueOfFloat64 returns a new float64 value. +func ValueOfFloat64(v float64) Value { + return Value{typ: float64Type, num: uint64(math.Float64bits(float64(v)))} +} + +// ValueOfString returns a new string value. +func ValueOfString(v string) Value { + return valueOfString(v) +} + +// ValueOfBytes returns a new bytes value. +func ValueOfBytes(v []byte) Value { + return valueOfBytes(v[:len(v):len(v)]) +} + +// ValueOfEnum returns a new enum value. +func ValueOfEnum(v EnumNumber) Value { + return Value{typ: enumType, num: uint64(v)} +} + +// ValueOfMessage returns a new Message value. +func ValueOfMessage(v Message) Value { + return valueOfIface(v) +} + +// ValueOfList returns a new List value. +func ValueOfList(v List) Value { + return valueOfIface(v) +} + +// ValueOfMap returns a new Map value. +func ValueOfMap(v Map) Value { + return valueOfIface(v) +} + +// IsValid reports whether v is populated with a value. +func (v Value) IsValid() bool { + return v.typ != nilType +} + +// Interface returns v as an interface{}. +// +// Invariant: v == ValueOf(v).Interface() +func (v Value) Interface() interface{} { + switch v.typ { + case nilType: + return nil + case boolType: + return v.Bool() + case int32Type: + return int32(v.Int()) + case int64Type: + return int64(v.Int()) + case uint32Type: + return uint32(v.Uint()) + case uint64Type: + return uint64(v.Uint()) + case float32Type: + return float32(v.Float()) + case float64Type: + return float64(v.Float()) + case stringType: + return v.String() + case bytesType: + return v.Bytes() + case enumType: + return v.Enum() + default: + return v.getIface() + } +} + +func (v Value) typeName() string { + switch v.typ { + case nilType: + return "nil" + case boolType: + return "bool" + case int32Type: + return "int32" + case int64Type: + return "int64" + case uint32Type: + return "uint32" + case uint64Type: + return "uint64" + case float32Type: + return "float32" + case float64Type: + return "float64" + case stringType: + return "string" + case bytesType: + return "bytes" + case enumType: + return "enum" + default: + switch v := v.getIface().(type) { + case Message: + return "message" + case List: + return "list" + case Map: + return "map" + default: + return fmt.Sprintf("", v) + } + } +} + +func (v Value) panicMessage(what string) string { + return fmt.Sprintf("type mismatch: cannot convert %v to %s", v.typeName(), what) +} + +// Bool returns v as a bool and panics if the type is not a bool. +func (v Value) Bool() bool { + switch v.typ { + case boolType: + return v.num > 0 + default: + panic(v.panicMessage("bool")) + } +} + +// Int returns v as a int64 and panics if the type is not a int32 or int64. +func (v Value) Int() int64 { + switch v.typ { + case int32Type, int64Type: + return int64(v.num) + default: + panic(v.panicMessage("int")) + } +} + +// Uint returns v as a uint64 and panics if the type is not a uint32 or uint64. +func (v Value) Uint() uint64 { + switch v.typ { + case uint32Type, uint64Type: + return uint64(v.num) + default: + panic(v.panicMessage("uint")) + } +} + +// Float returns v as a float64 and panics if the type is not a float32 or float64. +func (v Value) Float() float64 { + switch v.typ { + case float32Type, float64Type: + return math.Float64frombits(uint64(v.num)) + default: + panic(v.panicMessage("float")) + } +} + +// String returns v as a string. Since this method implements fmt.Stringer, +// this returns the formatted string value for any non-string type. +func (v Value) String() string { + switch v.typ { + case stringType: + return v.getString() + default: + return fmt.Sprint(v.Interface()) + } +} + +// Bytes returns v as a []byte and panics if the type is not a []byte. +func (v Value) Bytes() []byte { + switch v.typ { + case bytesType: + return v.getBytes() + default: + panic(v.panicMessage("bytes")) + } +} + +// Enum returns v as a EnumNumber and panics if the type is not a EnumNumber. +func (v Value) Enum() EnumNumber { + switch v.typ { + case enumType: + return EnumNumber(v.num) + default: + panic(v.panicMessage("enum")) + } +} + +// Message returns v as a Message and panics if the type is not a Message. +func (v Value) Message() Message { + switch vi := v.getIface().(type) { + case Message: + return vi + default: + panic(v.panicMessage("message")) + } +} + +// List returns v as a List and panics if the type is not a List. +func (v Value) List() List { + switch vi := v.getIface().(type) { + case List: + return vi + default: + panic(v.panicMessage("list")) + } +} + +// Map returns v as a Map and panics if the type is not a Map. +func (v Value) Map() Map { + switch vi := v.getIface().(type) { + case Map: + return vi + default: + panic(v.panicMessage("map")) + } +} + +// MapKey returns v as a MapKey and panics for invalid MapKey types. +func (v Value) MapKey() MapKey { + switch v.typ { + case boolType, int32Type, int64Type, uint32Type, uint64Type, stringType: + return MapKey(v) + default: + panic(v.panicMessage("map key")) + } +} + +// MapKey is used to index maps, where the Go type of the MapKey must match +// the specified key Kind (see MessageDescriptor.IsMapEntry). +// The following shows what Go type is used to represent each proto Kind: +// +// ╔═════════╤═════════════════════════════════════╗ +// ║ Go type │ Protobuf kind ║ +// ╠═════════╪═════════════════════════════════════╣ +// ║ bool │ BoolKind ║ +// ║ int32 │ Int32Kind, Sint32Kind, Sfixed32Kind ║ +// ║ int64 │ Int64Kind, Sint64Kind, Sfixed64Kind ║ +// ║ uint32 │ Uint32Kind, Fixed32Kind ║ +// ║ uint64 │ Uint64Kind, Fixed64Kind ║ +// ║ string │ StringKind ║ +// ╚═════════╧═════════════════════════════════════╝ +// +// A MapKey is constructed and accessed through a Value: +// k := ValueOf("hash").MapKey() // convert string to MapKey +// s := k.String() // convert MapKey to string +// +// The MapKey is a strict subset of valid types used in Value; +// converting a Value to a MapKey with an invalid type panics. +type MapKey value + +// IsValid reports whether k is populated with a value. +func (k MapKey) IsValid() bool { + return Value(k).IsValid() +} + +// Interface returns k as an interface{}. +func (k MapKey) Interface() interface{} { + return Value(k).Interface() +} + +// Bool returns k as a bool and panics if the type is not a bool. +func (k MapKey) Bool() bool { + return Value(k).Bool() +} + +// Int returns k as a int64 and panics if the type is not a int32 or int64. +func (k MapKey) Int() int64 { + return Value(k).Int() +} + +// Uint returns k as a uint64 and panics if the type is not a uint32 or uint64. +func (k MapKey) Uint() uint64 { + return Value(k).Uint() +} + +// String returns k as a string. Since this method implements fmt.Stringer, +// this returns the formatted string value for any non-string type. +func (k MapKey) String() string { + return Value(k).String() +} + +// Value returns k as a Value. +func (k MapKey) Value() Value { + return Value(k) +} diff --git a/vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go new file mode 100644 index 00000000000..c45debdcac6 --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protoreflect/value_unsafe.go @@ -0,0 +1,98 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !purego,!appengine + +package protoreflect + +import ( + "unsafe" + + "google.golang.org/protobuf/internal/pragma" +) + +type ( + stringHeader struct { + Data unsafe.Pointer + Len int + } + sliceHeader struct { + Data unsafe.Pointer + Len int + Cap int + } + ifaceHeader struct { + Type unsafe.Pointer + Data unsafe.Pointer + } +) + +var ( + nilType = typeOf(nil) + boolType = typeOf(*new(bool)) + int32Type = typeOf(*new(int32)) + int64Type = typeOf(*new(int64)) + uint32Type = typeOf(*new(uint32)) + uint64Type = typeOf(*new(uint64)) + float32Type = typeOf(*new(float32)) + float64Type = typeOf(*new(float64)) + stringType = typeOf(*new(string)) + bytesType = typeOf(*new([]byte)) + enumType = typeOf(*new(EnumNumber)) +) + +// typeOf returns a pointer to the Go type information. +// The pointer is comparable and equal if and only if the types are identical. +func typeOf(t interface{}) unsafe.Pointer { + return (*ifaceHeader)(unsafe.Pointer(&t)).Type +} + +// value is a union where only one type can be represented at a time. +// The struct is 24B large on 64-bit systems and requires the minimum storage +// necessary to represent each possible type. +// +// The Go GC needs to be able to scan variables containing pointers. +// As such, pointers and non-pointers cannot be intermixed. +type value struct { + pragma.DoNotCompare // 0B + + // typ stores the type of the value as a pointer to the Go type. + typ unsafe.Pointer // 8B + + // ptr stores the data pointer for a String, Bytes, or interface value. + ptr unsafe.Pointer // 8B + + // num stores a Bool, Int32, Int64, Uint32, Uint64, Float32, Float64, or + // Enum value as a raw uint64. + // + // It is also used to store the length of a String or Bytes value; + // the capacity is ignored. + num uint64 // 8B +} + +func valueOfString(v string) Value { + p := (*stringHeader)(unsafe.Pointer(&v)) + return Value{typ: stringType, ptr: p.Data, num: uint64(len(v))} +} +func valueOfBytes(v []byte) Value { + p := (*sliceHeader)(unsafe.Pointer(&v)) + return Value{typ: bytesType, ptr: p.Data, num: uint64(len(v))} +} +func valueOfIface(v interface{}) Value { + p := (*ifaceHeader)(unsafe.Pointer(&v)) + return Value{typ: p.Type, ptr: p.Data} +} + +func (v Value) getString() (x string) { + *(*stringHeader)(unsafe.Pointer(&x)) = stringHeader{Data: v.ptr, Len: int(v.num)} + return x +} +func (v Value) getBytes() (x []byte) { + *(*sliceHeader)(unsafe.Pointer(&x)) = sliceHeader{Data: v.ptr, Len: int(v.num), Cap: int(v.num)} + return x +} +func (v Value) getIface() (x interface{}) { + *(*ifaceHeader)(unsafe.Pointer(&x)) = ifaceHeader{Type: v.typ, Data: v.ptr} + return x +} diff --git a/vendor/google.golang.org/protobuf/reflect/protoregistry/registry.go b/vendor/google.golang.org/protobuf/reflect/protoregistry/registry.go new file mode 100644 index 00000000000..5e5f9671646 --- /dev/null +++ b/vendor/google.golang.org/protobuf/reflect/protoregistry/registry.go @@ -0,0 +1,800 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package protoregistry provides data structures to register and lookup +// protobuf descriptor types. +// +// The Files registry contains file descriptors and provides the ability +// to iterate over the files or lookup a specific descriptor within the files. +// Files only contains protobuf descriptors and has no understanding of Go +// type information that may be associated with each descriptor. +// +// The Types registry contains descriptor types for which there is a known +// Go type associated with that descriptor. It provides the ability to iterate +// over the registered types or lookup a type by name. +package protoregistry + +import ( + "fmt" + "log" + "strings" + "sync" + + "google.golang.org/protobuf/internal/errors" + "google.golang.org/protobuf/reflect/protoreflect" +) + +// ignoreConflict reports whether to ignore a registration conflict +// given the descriptor being registered and the error. +// It is a variable so that the behavior is easily overridden in another file. +var ignoreConflict = func(d protoreflect.Descriptor, err error) bool { + log.Printf(""+ + "WARNING: %v\n"+ + "A future release will panic on registration conflicts. See:\n"+ + "https://developers.google.com/protocol-buffers/docs/reference/go/faq#namespace-conflict\n"+ + "\n", err) + return true +} + +var globalMutex sync.RWMutex + +// GlobalFiles is a global registry of file descriptors. +var GlobalFiles *Files = new(Files) + +// GlobalTypes is the registry used by default for type lookups +// unless a local registry is provided by the user. +var GlobalTypes *Types = new(Types) + +// NotFound is a sentinel error value to indicate that the type was not found. +// +// Since registry lookup can happen in the critical performance path, resolvers +// must return this exact error value, not an error wrapping it. +var NotFound = errors.New("not found") + +// Files is a registry for looking up or iterating over files and the +// descriptors contained within them. +// The Find and Range methods are safe for concurrent use. +type Files struct { + // The map of descsByName contains: + // EnumDescriptor + // EnumValueDescriptor + // MessageDescriptor + // ExtensionDescriptor + // ServiceDescriptor + // *packageDescriptor + // + // Note that files are stored as a slice, since a package may contain + // multiple files. Only top-level declarations are registered. + // Note that enum values are in the top-level since that are in the same + // scope as the parent enum. + descsByName map[protoreflect.FullName]interface{} + filesByPath map[string]protoreflect.FileDescriptor +} + +type packageDescriptor struct { + files []protoreflect.FileDescriptor +} + +// RegisterFile registers the provided file descriptor. +// +// If any descriptor within the file conflicts with the descriptor of any +// previously registered file (e.g., two enums with the same full name), +// then the file is not registered and an error is returned. +// +// It is permitted for multiple files to have the same file path. +func (r *Files) RegisterFile(file protoreflect.FileDescriptor) error { + if r == GlobalFiles { + globalMutex.Lock() + defer globalMutex.Unlock() + } + if r.descsByName == nil { + r.descsByName = map[protoreflect.FullName]interface{}{ + "": &packageDescriptor{}, + } + r.filesByPath = make(map[string]protoreflect.FileDescriptor) + } + path := file.Path() + if prev := r.filesByPath[path]; prev != nil { + // TODO: Remove this after some soak-in period after moving these types. + var prevPath string + const prevModule = "google.golang.org/genproto" + const prevVersion = "cb27e3aa (May 26th, 2020)" + switch path { + case "google/protobuf/field_mask.proto": + prevPath = prevModule + "/protobuf/field_mask" + case "google/protobuf/api.proto": + prevPath = prevModule + "/protobuf/api" + case "google/protobuf/type.proto": + prevPath = prevModule + "/protobuf/ptype" + case "google/protobuf/source_context.proto": + prevPath = prevModule + "/protobuf/source_context" + } + if r == GlobalFiles && prevPath != "" { + pkgName := strings.TrimSuffix(strings.TrimPrefix(path, "google/protobuf/"), ".proto") + pkgName = strings.Replace(pkgName, "_", "", -1) + "pb" + currPath := "google.golang.org/protobuf/types/known/" + pkgName + panic(fmt.Sprintf(""+ + "duplicate registration of %q\n"+ + "\n"+ + "The generated definition for this file has moved:\n"+ + "\tfrom: %q\n"+ + "\tto: %q\n"+ + "A dependency on the %q module must\n"+ + "be at version %v or higher.\n"+ + "\n"+ + "Upgrade the dependency by running:\n"+ + "\tgo get -u %v\n", + path, prevPath, currPath, prevModule, prevVersion, prevPath)) + } + + err := errors.New("file %q is already registered", file.Path()) + err = amendErrorWithCaller(err, prev, file) + if r == GlobalFiles && ignoreConflict(file, err) { + err = nil + } + return err + } + + for name := file.Package(); name != ""; name = name.Parent() { + switch prev := r.descsByName[name]; prev.(type) { + case nil, *packageDescriptor: + default: + err := errors.New("file %q has a package name conflict over %v", file.Path(), name) + err = amendErrorWithCaller(err, prev, file) + if r == GlobalFiles && ignoreConflict(file, err) { + err = nil + } + return err + } + } + var err error + var hasConflict bool + rangeTopLevelDescriptors(file, func(d protoreflect.Descriptor) { + if prev := r.descsByName[d.FullName()]; prev != nil { + hasConflict = true + err = errors.New("file %q has a name conflict over %v", file.Path(), d.FullName()) + err = amendErrorWithCaller(err, prev, file) + if r == GlobalFiles && ignoreConflict(d, err) { + err = nil + } + } + }) + if hasConflict { + return err + } + + for name := file.Package(); name != ""; name = name.Parent() { + if r.descsByName[name] == nil { + r.descsByName[name] = &packageDescriptor{} + } + } + p := r.descsByName[file.Package()].(*packageDescriptor) + p.files = append(p.files, file) + rangeTopLevelDescriptors(file, func(d protoreflect.Descriptor) { + r.descsByName[d.FullName()] = d + }) + r.filesByPath[path] = file + return nil +} + +// FindDescriptorByName looks up a descriptor by the full name. +// +// This returns (nil, NotFound) if not found. +func (r *Files) FindDescriptorByName(name protoreflect.FullName) (protoreflect.Descriptor, error) { + if r == nil { + return nil, NotFound + } + if r == GlobalFiles { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + prefix := name + suffix := nameSuffix("") + for prefix != "" { + if d, ok := r.descsByName[prefix]; ok { + switch d := d.(type) { + case protoreflect.EnumDescriptor: + if d.FullName() == name { + return d, nil + } + case protoreflect.EnumValueDescriptor: + if d.FullName() == name { + return d, nil + } + case protoreflect.MessageDescriptor: + if d.FullName() == name { + return d, nil + } + if d := findDescriptorInMessage(d, suffix); d != nil && d.FullName() == name { + return d, nil + } + case protoreflect.ExtensionDescriptor: + if d.FullName() == name { + return d, nil + } + case protoreflect.ServiceDescriptor: + if d.FullName() == name { + return d, nil + } + if d := d.Methods().ByName(suffix.Pop()); d != nil && d.FullName() == name { + return d, nil + } + } + return nil, NotFound + } + prefix = prefix.Parent() + suffix = nameSuffix(name[len(prefix)+len("."):]) + } + return nil, NotFound +} + +func findDescriptorInMessage(md protoreflect.MessageDescriptor, suffix nameSuffix) protoreflect.Descriptor { + name := suffix.Pop() + if suffix == "" { + if ed := md.Enums().ByName(name); ed != nil { + return ed + } + for i := md.Enums().Len() - 1; i >= 0; i-- { + if vd := md.Enums().Get(i).Values().ByName(name); vd != nil { + return vd + } + } + if xd := md.Extensions().ByName(name); xd != nil { + return xd + } + if fd := md.Fields().ByName(name); fd != nil { + return fd + } + if od := md.Oneofs().ByName(name); od != nil { + return od + } + } + if md := md.Messages().ByName(name); md != nil { + if suffix == "" { + return md + } + return findDescriptorInMessage(md, suffix) + } + return nil +} + +type nameSuffix string + +func (s *nameSuffix) Pop() (name protoreflect.Name) { + if i := strings.IndexByte(string(*s), '.'); i >= 0 { + name, *s = protoreflect.Name((*s)[:i]), (*s)[i+1:] + } else { + name, *s = protoreflect.Name((*s)), "" + } + return name +} + +// FindFileByPath looks up a file by the path. +// +// This returns (nil, NotFound) if not found. +func (r *Files) FindFileByPath(path string) (protoreflect.FileDescriptor, error) { + if r == nil { + return nil, NotFound + } + if r == GlobalFiles { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + if fd, ok := r.filesByPath[path]; ok { + return fd, nil + } + return nil, NotFound +} + +// NumFiles reports the number of registered files. +func (r *Files) NumFiles() int { + if r == nil { + return 0 + } + if r == GlobalFiles { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + return len(r.filesByPath) +} + +// RangeFiles iterates over all registered files while f returns true. +// The iteration order is undefined. +func (r *Files) RangeFiles(f func(protoreflect.FileDescriptor) bool) { + if r == nil { + return + } + if r == GlobalFiles { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + for _, file := range r.filesByPath { + if !f(file) { + return + } + } +} + +// NumFilesByPackage reports the number of registered files in a proto package. +func (r *Files) NumFilesByPackage(name protoreflect.FullName) int { + if r == nil { + return 0 + } + if r == GlobalFiles { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + p, ok := r.descsByName[name].(*packageDescriptor) + if !ok { + return 0 + } + return len(p.files) +} + +// RangeFilesByPackage iterates over all registered files in a given proto package +// while f returns true. The iteration order is undefined. +func (r *Files) RangeFilesByPackage(name protoreflect.FullName, f func(protoreflect.FileDescriptor) bool) { + if r == nil { + return + } + if r == GlobalFiles { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + p, ok := r.descsByName[name].(*packageDescriptor) + if !ok { + return + } + for _, file := range p.files { + if !f(file) { + return + } + } +} + +// rangeTopLevelDescriptors iterates over all top-level descriptors in a file +// which will be directly entered into the registry. +func rangeTopLevelDescriptors(fd protoreflect.FileDescriptor, f func(protoreflect.Descriptor)) { + eds := fd.Enums() + for i := eds.Len() - 1; i >= 0; i-- { + f(eds.Get(i)) + vds := eds.Get(i).Values() + for i := vds.Len() - 1; i >= 0; i-- { + f(vds.Get(i)) + } + } + mds := fd.Messages() + for i := mds.Len() - 1; i >= 0; i-- { + f(mds.Get(i)) + } + xds := fd.Extensions() + for i := xds.Len() - 1; i >= 0; i-- { + f(xds.Get(i)) + } + sds := fd.Services() + for i := sds.Len() - 1; i >= 0; i-- { + f(sds.Get(i)) + } +} + +// MessageTypeResolver is an interface for looking up messages. +// +// A compliant implementation must deterministically return the same type +// if no error is encountered. +// +// The Types type implements this interface. +type MessageTypeResolver interface { + // FindMessageByName looks up a message by its full name. + // E.g., "google.protobuf.Any" + // + // This return (nil, NotFound) if not found. + FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) + + // FindMessageByURL looks up a message by a URL identifier. + // See documentation on google.protobuf.Any.type_url for the URL format. + // + // This returns (nil, NotFound) if not found. + FindMessageByURL(url string) (protoreflect.MessageType, error) +} + +// ExtensionTypeResolver is an interface for looking up extensions. +// +// A compliant implementation must deterministically return the same type +// if no error is encountered. +// +// The Types type implements this interface. +type ExtensionTypeResolver interface { + // FindExtensionByName looks up a extension field by the field's full name. + // Note that this is the full name of the field as determined by + // where the extension is declared and is unrelated to the full name of the + // message being extended. + // + // This returns (nil, NotFound) if not found. + FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) + + // FindExtensionByNumber looks up a extension field by the field number + // within some parent message, identified by full name. + // + // This returns (nil, NotFound) if not found. + FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) +} + +var ( + _ MessageTypeResolver = (*Types)(nil) + _ ExtensionTypeResolver = (*Types)(nil) +) + +// Types is a registry for looking up or iterating over descriptor types. +// The Find and Range methods are safe for concurrent use. +type Types struct { + typesByName typesByName + extensionsByMessage extensionsByMessage + + numEnums int + numMessages int + numExtensions int +} + +type ( + typesByName map[protoreflect.FullName]interface{} + extensionsByMessage map[protoreflect.FullName]extensionsByNumber + extensionsByNumber map[protoreflect.FieldNumber]protoreflect.ExtensionType +) + +// RegisterMessage registers the provided message type. +// +// If a naming conflict occurs, the type is not registered and an error is returned. +func (r *Types) RegisterMessage(mt protoreflect.MessageType) error { + // Under rare circumstances getting the descriptor might recursively + // examine the registry, so fetch it before locking. + md := mt.Descriptor() + + if r == GlobalTypes { + globalMutex.Lock() + defer globalMutex.Unlock() + } + + if err := r.register("message", md, mt); err != nil { + return err + } + r.numMessages++ + return nil +} + +// RegisterEnum registers the provided enum type. +// +// If a naming conflict occurs, the type is not registered and an error is returned. +func (r *Types) RegisterEnum(et protoreflect.EnumType) error { + // Under rare circumstances getting the descriptor might recursively + // examine the registry, so fetch it before locking. + ed := et.Descriptor() + + if r == GlobalTypes { + globalMutex.Lock() + defer globalMutex.Unlock() + } + + if err := r.register("enum", ed, et); err != nil { + return err + } + r.numEnums++ + return nil +} + +// RegisterExtension registers the provided extension type. +// +// If a naming conflict occurs, the type is not registered and an error is returned. +func (r *Types) RegisterExtension(xt protoreflect.ExtensionType) error { + // Under rare circumstances getting the descriptor might recursively + // examine the registry, so fetch it before locking. + // + // A known case where this can happen: Fetching the TypeDescriptor for a + // legacy ExtensionDesc can consult the global registry. + xd := xt.TypeDescriptor() + + if r == GlobalTypes { + globalMutex.Lock() + defer globalMutex.Unlock() + } + + field := xd.Number() + message := xd.ContainingMessage().FullName() + if prev := r.extensionsByMessage[message][field]; prev != nil { + err := errors.New("extension number %d is already registered on message %v", field, message) + err = amendErrorWithCaller(err, prev, xt) + if !(r == GlobalTypes && ignoreConflict(xd, err)) { + return err + } + } + + if err := r.register("extension", xd, xt); err != nil { + return err + } + if r.extensionsByMessage == nil { + r.extensionsByMessage = make(extensionsByMessage) + } + if r.extensionsByMessage[message] == nil { + r.extensionsByMessage[message] = make(extensionsByNumber) + } + r.extensionsByMessage[message][field] = xt + r.numExtensions++ + return nil +} + +func (r *Types) register(kind string, desc protoreflect.Descriptor, typ interface{}) error { + name := desc.FullName() + prev := r.typesByName[name] + if prev != nil { + err := errors.New("%v %v is already registered", kind, name) + err = amendErrorWithCaller(err, prev, typ) + if !(r == GlobalTypes && ignoreConflict(desc, err)) { + return err + } + } + if r.typesByName == nil { + r.typesByName = make(typesByName) + } + r.typesByName[name] = typ + return nil +} + +// FindEnumByName looks up an enum by its full name. +// E.g., "google.protobuf.Field.Kind". +// +// This returns (nil, NotFound) if not found. +func (r *Types) FindEnumByName(enum protoreflect.FullName) (protoreflect.EnumType, error) { + if r == nil { + return nil, NotFound + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + if v := r.typesByName[enum]; v != nil { + if et, _ := v.(protoreflect.EnumType); et != nil { + return et, nil + } + return nil, errors.New("found wrong type: got %v, want enum", typeName(v)) + } + return nil, NotFound +} + +// FindMessageByName looks up a message by its full name. +// E.g., "google.protobuf.Any" +// +// This return (nil, NotFound) if not found. +func (r *Types) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) { + // The full name by itself is a valid URL. + return r.FindMessageByURL(string(message)) +} + +// FindMessageByURL looks up a message by a URL identifier. +// See documentation on google.protobuf.Any.type_url for the URL format. +// +// This returns (nil, NotFound) if not found. +func (r *Types) FindMessageByURL(url string) (protoreflect.MessageType, error) { + if r == nil { + return nil, NotFound + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + message := protoreflect.FullName(url) + if i := strings.LastIndexByte(url, '/'); i >= 0 { + message = message[i+len("/"):] + } + + if v := r.typesByName[message]; v != nil { + if mt, _ := v.(protoreflect.MessageType); mt != nil { + return mt, nil + } + return nil, errors.New("found wrong type: got %v, want message", typeName(v)) + } + return nil, NotFound +} + +// FindExtensionByName looks up a extension field by the field's full name. +// Note that this is the full name of the field as determined by +// where the extension is declared and is unrelated to the full name of the +// message being extended. +// +// This returns (nil, NotFound) if not found. +func (r *Types) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) { + if r == nil { + return nil, NotFound + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + if v := r.typesByName[field]; v != nil { + if xt, _ := v.(protoreflect.ExtensionType); xt != nil { + return xt, nil + } + return nil, errors.New("found wrong type: got %v, want extension", typeName(v)) + } + return nil, NotFound +} + +// FindExtensionByNumber looks up a extension field by the field number +// within some parent message, identified by full name. +// +// This returns (nil, NotFound) if not found. +func (r *Types) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) { + if r == nil { + return nil, NotFound + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + if xt, ok := r.extensionsByMessage[message][field]; ok { + return xt, nil + } + return nil, NotFound +} + +// NumEnums reports the number of registered enums. +func (r *Types) NumEnums() int { + if r == nil { + return 0 + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + return r.numEnums +} + +// RangeEnums iterates over all registered enums while f returns true. +// Iteration order is undefined. +func (r *Types) RangeEnums(f func(protoreflect.EnumType) bool) { + if r == nil { + return + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + for _, typ := range r.typesByName { + if et, ok := typ.(protoreflect.EnumType); ok { + if !f(et) { + return + } + } + } +} + +// NumMessages reports the number of registered messages. +func (r *Types) NumMessages() int { + if r == nil { + return 0 + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + return r.numMessages +} + +// RangeMessages iterates over all registered messages while f returns true. +// Iteration order is undefined. +func (r *Types) RangeMessages(f func(protoreflect.MessageType) bool) { + if r == nil { + return + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + for _, typ := range r.typesByName { + if mt, ok := typ.(protoreflect.MessageType); ok { + if !f(mt) { + return + } + } + } +} + +// NumExtensions reports the number of registered extensions. +func (r *Types) NumExtensions() int { + if r == nil { + return 0 + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + return r.numExtensions +} + +// RangeExtensions iterates over all registered extensions while f returns true. +// Iteration order is undefined. +func (r *Types) RangeExtensions(f func(protoreflect.ExtensionType) bool) { + if r == nil { + return + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + for _, typ := range r.typesByName { + if xt, ok := typ.(protoreflect.ExtensionType); ok { + if !f(xt) { + return + } + } + } +} + +// NumExtensionsByMessage reports the number of registered extensions for +// a given message type. +func (r *Types) NumExtensionsByMessage(message protoreflect.FullName) int { + if r == nil { + return 0 + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + return len(r.extensionsByMessage[message]) +} + +// RangeExtensionsByMessage iterates over all registered extensions filtered +// by a given message type while f returns true. Iteration order is undefined. +func (r *Types) RangeExtensionsByMessage(message protoreflect.FullName, f func(protoreflect.ExtensionType) bool) { + if r == nil { + return + } + if r == GlobalTypes { + globalMutex.RLock() + defer globalMutex.RUnlock() + } + for _, xt := range r.extensionsByMessage[message] { + if !f(xt) { + return + } + } +} + +func typeName(t interface{}) string { + switch t.(type) { + case protoreflect.EnumType: + return "enum" + case protoreflect.MessageType: + return "message" + case protoreflect.ExtensionType: + return "extension" + default: + return fmt.Sprintf("%T", t) + } +} + +func amendErrorWithCaller(err error, prev, curr interface{}) error { + prevPkg := goPackage(prev) + currPkg := goPackage(curr) + if prevPkg == "" || currPkg == "" || prevPkg == currPkg { + return err + } + return errors.New("%s\n\tpreviously from: %q\n\tcurrently from: %q", err, prevPkg, currPkg) +} + +func goPackage(v interface{}) string { + switch d := v.(type) { + case protoreflect.EnumType: + v = d.Descriptor() + case protoreflect.MessageType: + v = d.Descriptor() + case protoreflect.ExtensionType: + v = d.TypeDescriptor() + } + if d, ok := v.(protoreflect.Descriptor); ok { + v = d.ParentFile() + } + if d, ok := v.(interface{ GoPackagePath() string }); ok { + return d.GoPackagePath() + } + return "" +} diff --git a/vendor/google.golang.org/protobuf/runtime/protoiface/legacy.go b/vendor/google.golang.org/protobuf/runtime/protoiface/legacy.go new file mode 100644 index 00000000000..c587276752a --- /dev/null +++ b/vendor/google.golang.org/protobuf/runtime/protoiface/legacy.go @@ -0,0 +1,15 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protoiface + +type MessageV1 interface { + Reset() + String() string + ProtoMessage() +} + +type ExtensionRangeV1 struct { + Start, End int32 // both inclusive +} diff --git a/vendor/google.golang.org/protobuf/runtime/protoiface/methods.go b/vendor/google.golang.org/protobuf/runtime/protoiface/methods.go new file mode 100644 index 00000000000..32c04f67eb7 --- /dev/null +++ b/vendor/google.golang.org/protobuf/runtime/protoiface/methods.go @@ -0,0 +1,167 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package protoiface contains types referenced or implemented by messages. +// +// WARNING: This package should only be imported by message implementations. +// The functionality found in this package should be accessed through +// higher-level abstractions provided by the proto package. +package protoiface + +import ( + "google.golang.org/protobuf/internal/pragma" + "google.golang.org/protobuf/reflect/protoreflect" +) + +// Methods is a set of optional fast-path implementations of various operations. +type Methods = struct { + pragma.NoUnkeyedLiterals + + // Flags indicate support for optional features. + Flags SupportFlags + + // Size returns the size in bytes of the wire-format encoding of a message. + // Marshal must be provided if a custom Size is provided. + Size func(SizeInput) SizeOutput + + // Marshal formats a message in the wire-format encoding to the provided buffer. + // Size should be provided if a custom Marshal is provided. + // It must not return an error for a partial message. + Marshal func(MarshalInput) (MarshalOutput, error) + + // Unmarshal parses the wire-format encoding and merges the result into a message. + // It must not reset the target message or return an error for a partial message. + Unmarshal func(UnmarshalInput) (UnmarshalOutput, error) + + // Merge merges the contents of a source message into a destination message. + Merge func(MergeInput) MergeOutput + + // CheckInitialized returns an error if any required fields in the message are not set. + CheckInitialized func(CheckInitializedInput) (CheckInitializedOutput, error) +} + +// SupportFlags indicate support for optional features. +type SupportFlags = uint64 + +const ( + // SupportMarshalDeterministic reports whether MarshalOptions.Deterministic is supported. + SupportMarshalDeterministic SupportFlags = 1 << iota + + // SupportUnmarshalDiscardUnknown reports whether UnmarshalOptions.DiscardUnknown is supported. + SupportUnmarshalDiscardUnknown +) + +// SizeInput is input to the Size method. +type SizeInput = struct { + pragma.NoUnkeyedLiterals + + Message protoreflect.Message + Flags MarshalInputFlags +} + +// SizeOutput is output from the Size method. +type SizeOutput = struct { + pragma.NoUnkeyedLiterals + + Size int +} + +// MarshalInput is input to the Marshal method. +type MarshalInput = struct { + pragma.NoUnkeyedLiterals + + Message protoreflect.Message + Buf []byte // output is appended to this buffer + Flags MarshalInputFlags +} + +// MarshalOutput is output from the Marshal method. +type MarshalOutput = struct { + pragma.NoUnkeyedLiterals + + Buf []byte // contains marshaled message +} + +// MarshalInputFlags configure the marshaler. +// Most flags correspond to fields in proto.MarshalOptions. +type MarshalInputFlags = uint8 + +const ( + MarshalDeterministic MarshalInputFlags = 1 << iota + MarshalUseCachedSize +) + +// UnmarshalInput is input to the Unmarshal method. +type UnmarshalInput = struct { + pragma.NoUnkeyedLiterals + + Message protoreflect.Message + Buf []byte // input buffer + Flags UnmarshalInputFlags + Resolver interface { + FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) + FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) + } +} + +// UnmarshalOutput is output from the Unmarshal method. +type UnmarshalOutput = struct { + pragma.NoUnkeyedLiterals + + Flags UnmarshalOutputFlags +} + +// UnmarshalInputFlags configure the unmarshaler. +// Most flags correspond to fields in proto.UnmarshalOptions. +type UnmarshalInputFlags = uint8 + +const ( + UnmarshalDiscardUnknown UnmarshalInputFlags = 1 << iota +) + +// UnmarshalOutputFlags are output from the Unmarshal method. +type UnmarshalOutputFlags = uint8 + +const ( + // UnmarshalInitialized may be set on return if all required fields are known to be set. + // If unset, then it does not necessarily indicate that the message is uninitialized, + // only that its status could not be confirmed. + UnmarshalInitialized UnmarshalOutputFlags = 1 << iota +) + +// MergeInput is input to the Merge method. +type MergeInput = struct { + pragma.NoUnkeyedLiterals + + Source protoreflect.Message + Destination protoreflect.Message +} + +// MergeOutput is output from the Merge method. +type MergeOutput = struct { + pragma.NoUnkeyedLiterals + + Flags MergeOutputFlags +} + +// MergeOutputFlags are output from the Merge method. +type MergeOutputFlags = uint8 + +const ( + // MergeComplete reports whether the merge was performed. + // If unset, the merger must have made no changes to the destination. + MergeComplete MergeOutputFlags = 1 << iota +) + +// CheckInitializedInput is input to the CheckInitialized method. +type CheckInitializedInput = struct { + pragma.NoUnkeyedLiterals + + Message protoreflect.Message +} + +// CheckInitializedOutput is output from the CheckInitialized method. +type CheckInitializedOutput = struct { + pragma.NoUnkeyedLiterals +} diff --git a/vendor/google.golang.org/protobuf/runtime/protoimpl/impl.go b/vendor/google.golang.org/protobuf/runtime/protoimpl/impl.go new file mode 100644 index 00000000000..4a1ab7fb3de --- /dev/null +++ b/vendor/google.golang.org/protobuf/runtime/protoimpl/impl.go @@ -0,0 +1,44 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package protoimpl contains the default implementation for messages +// generated by protoc-gen-go. +// +// WARNING: This package should only ever be imported by generated messages. +// The compatibility agreement covers nothing except for functionality needed +// to keep existing generated messages operational. Breakages that occur due +// to unauthorized usages of this package are not the author's responsibility. +package protoimpl + +import ( + "google.golang.org/protobuf/internal/filedesc" + "google.golang.org/protobuf/internal/filetype" + "google.golang.org/protobuf/internal/impl" +) + +// UnsafeEnabled specifies whether package unsafe can be used. +const UnsafeEnabled = impl.UnsafeEnabled + +type ( + // Types used by generated code in init functions. + DescBuilder = filedesc.Builder + TypeBuilder = filetype.Builder + + // Types used by generated code to implement EnumType, MessageType, and ExtensionType. + EnumInfo = impl.EnumInfo + MessageInfo = impl.MessageInfo + ExtensionInfo = impl.ExtensionInfo + + // Types embedded in generated messages. + MessageState = impl.MessageState + SizeCache = impl.SizeCache + WeakFields = impl.WeakFields + UnknownFields = impl.UnknownFields + ExtensionFields = impl.ExtensionFields + ExtensionFieldV1 = impl.ExtensionField + + Pointer = impl.Pointer +) + +var X impl.Export diff --git a/vendor/google.golang.org/protobuf/runtime/protoimpl/version.go b/vendor/google.golang.org/protobuf/runtime/protoimpl/version.go new file mode 100644 index 00000000000..ff094e1ba44 --- /dev/null +++ b/vendor/google.golang.org/protobuf/runtime/protoimpl/version.go @@ -0,0 +1,56 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package protoimpl + +import ( + "google.golang.org/protobuf/internal/version" +) + +const ( + // MaxVersion is the maximum supported version for generated .pb.go files. + // It is always the current version of the module. + MaxVersion = version.Minor + + // GenVersion is the runtime version required by generated .pb.go files. + // This is incremented when generated code relies on new functionality + // in the runtime. + GenVersion = 20 + + // MinVersion is the minimum supported version for generated .pb.go files. + // This is incremented when the runtime drops support for old code. + MinVersion = 0 +) + +// EnforceVersion is used by code generated by protoc-gen-go +// to statically enforce minimum and maximum versions of this package. +// A compilation failure implies either that: +// * the runtime package is too old and needs to be updated OR +// * the generated code is too old and needs to be regenerated. +// +// The runtime package can be upgraded by running: +// go get google.golang.org/protobuf +// +// The generated code can be regenerated by running: +// protoc --go_out=${PROTOC_GEN_GO_ARGS} ${PROTO_FILES} +// +// Example usage by generated code: +// const ( +// // Verify that this generated code is sufficiently up-to-date. +// _ = protoimpl.EnforceVersion(genVersion - protoimpl.MinVersion) +// // Verify that runtime/protoimpl is sufficiently up-to-date. +// _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - genVersion) +// ) +// +// The genVersion is the current minor version used to generated the code. +// This compile-time check relies on negative integer overflow of a uint +// being a compilation failure (guaranteed by the Go specification). +type EnforceVersion uint + +// This enforces the following invariant: +// MinVersion ≤ GenVersion ≤ MaxVersion +const ( + _ = EnforceVersion(GenVersion - MinVersion) + _ = EnforceVersion(MaxVersion - GenVersion) +) diff --git a/vendor/google.golang.org/protobuf/types/descriptorpb/descriptor.pb.go b/vendor/google.golang.org/protobuf/types/descriptorpb/descriptor.pb.go new file mode 100644 index 00000000000..8242378569b --- /dev/null +++ b/vendor/google.golang.org/protobuf/types/descriptorpb/descriptor.pb.go @@ -0,0 +1,4040 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// The messages in this file describe the definitions found in .proto files. +// A valid .proto file can be translated directly to a FileDescriptorProto +// without any other information (e.g. without reading its imports). + +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: google/protobuf/descriptor.proto + +package descriptorpb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoiface "google.golang.org/protobuf/runtime/protoiface" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +type FieldDescriptorProto_Type int32 + +const ( + // 0 is reserved for errors. + // Order is weird for historical reasons. + FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 + FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 + FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 + FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 + FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 + FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 + FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 + // Tag-delimited aggregate. + // Group type is deprecated and not supported in proto3. However, Proto3 + // implementations should still be able to parse the group wire format and + // treat group fields as unknown fields. + FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 + FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 // Length-delimited aggregate. + // New in version 2. + FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 + FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 + FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 + FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 + FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 + FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 // Uses ZigZag encoding. + FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 // Uses ZigZag encoding. +) + +// Enum value maps for FieldDescriptorProto_Type. +var ( + FieldDescriptorProto_Type_name = map[int32]string{ + 1: "TYPE_DOUBLE", + 2: "TYPE_FLOAT", + 3: "TYPE_INT64", + 4: "TYPE_UINT64", + 5: "TYPE_INT32", + 6: "TYPE_FIXED64", + 7: "TYPE_FIXED32", + 8: "TYPE_BOOL", + 9: "TYPE_STRING", + 10: "TYPE_GROUP", + 11: "TYPE_MESSAGE", + 12: "TYPE_BYTES", + 13: "TYPE_UINT32", + 14: "TYPE_ENUM", + 15: "TYPE_SFIXED32", + 16: "TYPE_SFIXED64", + 17: "TYPE_SINT32", + 18: "TYPE_SINT64", + } + FieldDescriptorProto_Type_value = map[string]int32{ + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18, + } +) + +func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { + p := new(FieldDescriptorProto_Type) + *p = x + return p +} + +func (x FieldDescriptorProto_Type) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (FieldDescriptorProto_Type) Descriptor() protoreflect.EnumDescriptor { + return file_google_protobuf_descriptor_proto_enumTypes[0].Descriptor() +} + +func (FieldDescriptorProto_Type) Type() protoreflect.EnumType { + return &file_google_protobuf_descriptor_proto_enumTypes[0] +} + +func (x FieldDescriptorProto_Type) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Do not use. +func (x *FieldDescriptorProto_Type) UnmarshalJSON(b []byte) error { + num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) + if err != nil { + return err + } + *x = FieldDescriptorProto_Type(num) + return nil +} + +// Deprecated: Use FieldDescriptorProto_Type.Descriptor instead. +func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{4, 0} +} + +type FieldDescriptorProto_Label int32 + +const ( + // 0 is reserved for errors + FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 + FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 + FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 +) + +// Enum value maps for FieldDescriptorProto_Label. +var ( + FieldDescriptorProto_Label_name = map[int32]string{ + 1: "LABEL_OPTIONAL", + 2: "LABEL_REQUIRED", + 3: "LABEL_REPEATED", + } + FieldDescriptorProto_Label_value = map[string]int32{ + "LABEL_OPTIONAL": 1, + "LABEL_REQUIRED": 2, + "LABEL_REPEATED": 3, + } +) + +func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { + p := new(FieldDescriptorProto_Label) + *p = x + return p +} + +func (x FieldDescriptorProto_Label) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (FieldDescriptorProto_Label) Descriptor() protoreflect.EnumDescriptor { + return file_google_protobuf_descriptor_proto_enumTypes[1].Descriptor() +} + +func (FieldDescriptorProto_Label) Type() protoreflect.EnumType { + return &file_google_protobuf_descriptor_proto_enumTypes[1] +} + +func (x FieldDescriptorProto_Label) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Do not use. +func (x *FieldDescriptorProto_Label) UnmarshalJSON(b []byte) error { + num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) + if err != nil { + return err + } + *x = FieldDescriptorProto_Label(num) + return nil +} + +// Deprecated: Use FieldDescriptorProto_Label.Descriptor instead. +func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{4, 1} +} + +// Generated classes can be optimized for speed or code size. +type FileOptions_OptimizeMode int32 + +const ( + FileOptions_SPEED FileOptions_OptimizeMode = 1 // Generate complete code for parsing, serialization, + // etc. + FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 // Use ReflectionOps to implement these methods. + FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 // Generate code using MessageLite and the lite runtime. +) + +// Enum value maps for FileOptions_OptimizeMode. +var ( + FileOptions_OptimizeMode_name = map[int32]string{ + 1: "SPEED", + 2: "CODE_SIZE", + 3: "LITE_RUNTIME", + } + FileOptions_OptimizeMode_value = map[string]int32{ + "SPEED": 1, + "CODE_SIZE": 2, + "LITE_RUNTIME": 3, + } +) + +func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { + p := new(FileOptions_OptimizeMode) + *p = x + return p +} + +func (x FileOptions_OptimizeMode) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (FileOptions_OptimizeMode) Descriptor() protoreflect.EnumDescriptor { + return file_google_protobuf_descriptor_proto_enumTypes[2].Descriptor() +} + +func (FileOptions_OptimizeMode) Type() protoreflect.EnumType { + return &file_google_protobuf_descriptor_proto_enumTypes[2] +} + +func (x FileOptions_OptimizeMode) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Do not use. +func (x *FileOptions_OptimizeMode) UnmarshalJSON(b []byte) error { + num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) + if err != nil { + return err + } + *x = FileOptions_OptimizeMode(num) + return nil +} + +// Deprecated: Use FileOptions_OptimizeMode.Descriptor instead. +func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{10, 0} +} + +type FieldOptions_CType int32 + +const ( + // Default mode. + FieldOptions_STRING FieldOptions_CType = 0 + FieldOptions_CORD FieldOptions_CType = 1 + FieldOptions_STRING_PIECE FieldOptions_CType = 2 +) + +// Enum value maps for FieldOptions_CType. +var ( + FieldOptions_CType_name = map[int32]string{ + 0: "STRING", + 1: "CORD", + 2: "STRING_PIECE", + } + FieldOptions_CType_value = map[string]int32{ + "STRING": 0, + "CORD": 1, + "STRING_PIECE": 2, + } +) + +func (x FieldOptions_CType) Enum() *FieldOptions_CType { + p := new(FieldOptions_CType) + *p = x + return p +} + +func (x FieldOptions_CType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (FieldOptions_CType) Descriptor() protoreflect.EnumDescriptor { + return file_google_protobuf_descriptor_proto_enumTypes[3].Descriptor() +} + +func (FieldOptions_CType) Type() protoreflect.EnumType { + return &file_google_protobuf_descriptor_proto_enumTypes[3] +} + +func (x FieldOptions_CType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Do not use. +func (x *FieldOptions_CType) UnmarshalJSON(b []byte) error { + num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) + if err != nil { + return err + } + *x = FieldOptions_CType(num) + return nil +} + +// Deprecated: Use FieldOptions_CType.Descriptor instead. +func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{12, 0} +} + +type FieldOptions_JSType int32 + +const ( + // Use the default type. + FieldOptions_JS_NORMAL FieldOptions_JSType = 0 + // Use JavaScript strings. + FieldOptions_JS_STRING FieldOptions_JSType = 1 + // Use JavaScript numbers. + FieldOptions_JS_NUMBER FieldOptions_JSType = 2 +) + +// Enum value maps for FieldOptions_JSType. +var ( + FieldOptions_JSType_name = map[int32]string{ + 0: "JS_NORMAL", + 1: "JS_STRING", + 2: "JS_NUMBER", + } + FieldOptions_JSType_value = map[string]int32{ + "JS_NORMAL": 0, + "JS_STRING": 1, + "JS_NUMBER": 2, + } +) + +func (x FieldOptions_JSType) Enum() *FieldOptions_JSType { + p := new(FieldOptions_JSType) + *p = x + return p +} + +func (x FieldOptions_JSType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (FieldOptions_JSType) Descriptor() protoreflect.EnumDescriptor { + return file_google_protobuf_descriptor_proto_enumTypes[4].Descriptor() +} + +func (FieldOptions_JSType) Type() protoreflect.EnumType { + return &file_google_protobuf_descriptor_proto_enumTypes[4] +} + +func (x FieldOptions_JSType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Do not use. +func (x *FieldOptions_JSType) UnmarshalJSON(b []byte) error { + num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) + if err != nil { + return err + } + *x = FieldOptions_JSType(num) + return nil +} + +// Deprecated: Use FieldOptions_JSType.Descriptor instead. +func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{12, 1} +} + +// Is this method side-effect-free (or safe in HTTP parlance), or idempotent, +// or neither? HTTP based RPC implementation may choose GET verb for safe +// methods, and PUT verb for idempotent methods instead of the default POST. +type MethodOptions_IdempotencyLevel int32 + +const ( + MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0 + MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1 // implies idempotent + MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2 // idempotent, but may have side effects +) + +// Enum value maps for MethodOptions_IdempotencyLevel. +var ( + MethodOptions_IdempotencyLevel_name = map[int32]string{ + 0: "IDEMPOTENCY_UNKNOWN", + 1: "NO_SIDE_EFFECTS", + 2: "IDEMPOTENT", + } + MethodOptions_IdempotencyLevel_value = map[string]int32{ + "IDEMPOTENCY_UNKNOWN": 0, + "NO_SIDE_EFFECTS": 1, + "IDEMPOTENT": 2, + } +) + +func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel { + p := new(MethodOptions_IdempotencyLevel) + *p = x + return p +} + +func (x MethodOptions_IdempotencyLevel) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (MethodOptions_IdempotencyLevel) Descriptor() protoreflect.EnumDescriptor { + return file_google_protobuf_descriptor_proto_enumTypes[5].Descriptor() +} + +func (MethodOptions_IdempotencyLevel) Type() protoreflect.EnumType { + return &file_google_protobuf_descriptor_proto_enumTypes[5] +} + +func (x MethodOptions_IdempotencyLevel) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Do not use. +func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(b []byte) error { + num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) + if err != nil { + return err + } + *x = MethodOptions_IdempotencyLevel(num) + return nil +} + +// Deprecated: Use MethodOptions_IdempotencyLevel.Descriptor instead. +func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{17, 0} +} + +// The protocol compiler can output a FileDescriptorSet containing the .proto +// files it parses. +type FileDescriptorSet struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` +} + +func (x *FileDescriptorSet) Reset() { + *x = FileDescriptorSet{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *FileDescriptorSet) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FileDescriptorSet) ProtoMessage() {} + +func (x *FileDescriptorSet) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FileDescriptorSet.ProtoReflect.Descriptor instead. +func (*FileDescriptorSet) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{0} +} + +func (x *FileDescriptorSet) GetFile() []*FileDescriptorProto { + if x != nil { + return x.File + } + return nil +} + +// Describes a complete .proto file. +type FileDescriptorProto struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` // file name, relative to root of source tree + Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"` // e.g. "foo", "foo.bar", etc. + // Names of files imported by this file. + Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"` + // Indexes of the public imported files in the dependency list above. + PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"` + // Indexes of the weak imported files in the dependency list. + // For Google-internal migration only. Do not use. + WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"` + // All top-level definitions in this file. + MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"` + EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` + Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"` + Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"` + Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` + // This field contains optional information about the original source code. + // You may safely remove this entire field without harming runtime + // functionality of the descriptors -- the information is needed only by + // development tools. + SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"` + // The syntax of the proto file. + // The supported values are "proto2" and "proto3". + Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"` +} + +func (x *FileDescriptorProto) Reset() { + *x = FileDescriptorProto{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *FileDescriptorProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FileDescriptorProto) ProtoMessage() {} + +func (x *FileDescriptorProto) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FileDescriptorProto.ProtoReflect.Descriptor instead. +func (*FileDescriptorProto) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{1} +} + +func (x *FileDescriptorProto) GetName() string { + if x != nil && x.Name != nil { + return *x.Name + } + return "" +} + +func (x *FileDescriptorProto) GetPackage() string { + if x != nil && x.Package != nil { + return *x.Package + } + return "" +} + +func (x *FileDescriptorProto) GetDependency() []string { + if x != nil { + return x.Dependency + } + return nil +} + +func (x *FileDescriptorProto) GetPublicDependency() []int32 { + if x != nil { + return x.PublicDependency + } + return nil +} + +func (x *FileDescriptorProto) GetWeakDependency() []int32 { + if x != nil { + return x.WeakDependency + } + return nil +} + +func (x *FileDescriptorProto) GetMessageType() []*DescriptorProto { + if x != nil { + return x.MessageType + } + return nil +} + +func (x *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto { + if x != nil { + return x.EnumType + } + return nil +} + +func (x *FileDescriptorProto) GetService() []*ServiceDescriptorProto { + if x != nil { + return x.Service + } + return nil +} + +func (x *FileDescriptorProto) GetExtension() []*FieldDescriptorProto { + if x != nil { + return x.Extension + } + return nil +} + +func (x *FileDescriptorProto) GetOptions() *FileOptions { + if x != nil { + return x.Options + } + return nil +} + +func (x *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo { + if x != nil { + return x.SourceCodeInfo + } + return nil +} + +func (x *FileDescriptorProto) GetSyntax() string { + if x != nil && x.Syntax != nil { + return *x.Syntax + } + return "" +} + +// Describes a message type. +type DescriptorProto struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"` + Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"` + NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"` + EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` + ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"` + OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"` + Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"` + ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` + // Reserved field names, which may not be used by fields in the same message. + // A given name may only be reserved once. + ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` +} + +func (x *DescriptorProto) Reset() { + *x = DescriptorProto{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DescriptorProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DescriptorProto) ProtoMessage() {} + +func (x *DescriptorProto) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DescriptorProto.ProtoReflect.Descriptor instead. +func (*DescriptorProto) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{2} +} + +func (x *DescriptorProto) GetName() string { + if x != nil && x.Name != nil { + return *x.Name + } + return "" +} + +func (x *DescriptorProto) GetField() []*FieldDescriptorProto { + if x != nil { + return x.Field + } + return nil +} + +func (x *DescriptorProto) GetExtension() []*FieldDescriptorProto { + if x != nil { + return x.Extension + } + return nil +} + +func (x *DescriptorProto) GetNestedType() []*DescriptorProto { + if x != nil { + return x.NestedType + } + return nil +} + +func (x *DescriptorProto) GetEnumType() []*EnumDescriptorProto { + if x != nil { + return x.EnumType + } + return nil +} + +func (x *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange { + if x != nil { + return x.ExtensionRange + } + return nil +} + +func (x *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto { + if x != nil { + return x.OneofDecl + } + return nil +} + +func (x *DescriptorProto) GetOptions() *MessageOptions { + if x != nil { + return x.Options + } + return nil +} + +func (x *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange { + if x != nil { + return x.ReservedRange + } + return nil +} + +func (x *DescriptorProto) GetReservedName() []string { + if x != nil { + return x.ReservedName + } + return nil +} + +type ExtensionRangeOptions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + extensionFields protoimpl.ExtensionFields + + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` +} + +func (x *ExtensionRangeOptions) Reset() { + *x = ExtensionRangeOptions{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ExtensionRangeOptions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExtensionRangeOptions) ProtoMessage() {} + +func (x *ExtensionRangeOptions) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ExtensionRangeOptions.ProtoReflect.Descriptor instead. +func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{3} +} + +var extRange_ExtensionRangeOptions = []protoiface.ExtensionRangeV1{ + {Start: 1000, End: 536870911}, +} + +// Deprecated: Use ExtensionRangeOptions.ProtoReflect.Descriptor.ExtensionRanges instead. +func (*ExtensionRangeOptions) ExtensionRangeArray() []protoiface.ExtensionRangeV1 { + return extRange_ExtensionRangeOptions +} + +func (x *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption { + if x != nil { + return x.UninterpretedOption + } + return nil +} + +// Describes a field within a message. +type FieldDescriptorProto struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"` + Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"` + // If type_name is set, this need not be set. If both this and type_name + // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"` + // For message and enum types, this is the name of the type. If the name + // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + // rules are used to find the type (i.e. first the nested types within this + // message are searched, then within the parent, on up to the root + // namespace). + TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"` + // For extensions, this is the name of the type being extended. It is + // resolved in the same manner as type_name. + Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"` + // For numeric types, contains the original text representation of the value. + // For booleans, "true" or "false". + // For strings, contains the default text contents (not escaped in any way). + // For bytes, contains the C escaped value. All bytes >= 128 are escaped. + // TODO(kenton): Base-64 encode? + DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"` + // If set, gives the index of a oneof in the containing type's oneof_decl + // list. This field is a member of that oneof. + OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"` + // JSON name of this field. The value is set by protocol compiler. If the + // user has set a "json_name" option on this field, that option's value + // will be used. Otherwise, it's deduced from the field's name by converting + // it to camelCase. + JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"` + Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` + // If true, this is a proto3 "optional". When a proto3 field is optional, it + // tracks presence regardless of field type. + // + // When proto3_optional is true, this field must be belong to a oneof to + // signal to old proto3 clients that presence is tracked for this field. This + // oneof is known as a "synthetic" oneof, and this field must be its sole + // member (each proto3 optional field gets its own synthetic oneof). Synthetic + // oneofs exist in the descriptor only, and do not generate any API. Synthetic + // oneofs must be ordered after all "real" oneofs. + // + // For message fields, proto3_optional doesn't create any semantic change, + // since non-repeated message fields always track presence. However it still + // indicates the semantic detail of whether the user wrote "optional" or not. + // This can be useful for round-tripping the .proto file. For consistency we + // give message fields a synthetic oneof also, even though it is not required + // to track presence. This is especially important because the parser can't + // tell if a field is a message or an enum, so it must always create a + // synthetic oneof. + // + // Proto2 optional fields do not set this flag, because they already indicate + // optional with `LABEL_OPTIONAL`. + Proto3Optional *bool `protobuf:"varint,17,opt,name=proto3_optional,json=proto3Optional" json:"proto3_optional,omitempty"` +} + +func (x *FieldDescriptorProto) Reset() { + *x = FieldDescriptorProto{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *FieldDescriptorProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FieldDescriptorProto) ProtoMessage() {} + +func (x *FieldDescriptorProto) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FieldDescriptorProto.ProtoReflect.Descriptor instead. +func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{4} +} + +func (x *FieldDescriptorProto) GetName() string { + if x != nil && x.Name != nil { + return *x.Name + } + return "" +} + +func (x *FieldDescriptorProto) GetNumber() int32 { + if x != nil && x.Number != nil { + return *x.Number + } + return 0 +} + +func (x *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label { + if x != nil && x.Label != nil { + return *x.Label + } + return FieldDescriptorProto_LABEL_OPTIONAL +} + +func (x *FieldDescriptorProto) GetType() FieldDescriptorProto_Type { + if x != nil && x.Type != nil { + return *x.Type + } + return FieldDescriptorProto_TYPE_DOUBLE +} + +func (x *FieldDescriptorProto) GetTypeName() string { + if x != nil && x.TypeName != nil { + return *x.TypeName + } + return "" +} + +func (x *FieldDescriptorProto) GetExtendee() string { + if x != nil && x.Extendee != nil { + return *x.Extendee + } + return "" +} + +func (x *FieldDescriptorProto) GetDefaultValue() string { + if x != nil && x.DefaultValue != nil { + return *x.DefaultValue + } + return "" +} + +func (x *FieldDescriptorProto) GetOneofIndex() int32 { + if x != nil && x.OneofIndex != nil { + return *x.OneofIndex + } + return 0 +} + +func (x *FieldDescriptorProto) GetJsonName() string { + if x != nil && x.JsonName != nil { + return *x.JsonName + } + return "" +} + +func (x *FieldDescriptorProto) GetOptions() *FieldOptions { + if x != nil { + return x.Options + } + return nil +} + +func (x *FieldDescriptorProto) GetProto3Optional() bool { + if x != nil && x.Proto3Optional != nil { + return *x.Proto3Optional + } + return false +} + +// Describes a oneof. +type OneofDescriptorProto struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` +} + +func (x *OneofDescriptorProto) Reset() { + *x = OneofDescriptorProto{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *OneofDescriptorProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OneofDescriptorProto) ProtoMessage() {} + +func (x *OneofDescriptorProto) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OneofDescriptorProto.ProtoReflect.Descriptor instead. +func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{5} +} + +func (x *OneofDescriptorProto) GetName() string { + if x != nil && x.Name != nil { + return *x.Name + } + return "" +} + +func (x *OneofDescriptorProto) GetOptions() *OneofOptions { + if x != nil { + return x.Options + } + return nil +} + +// Describes an enum type. +type EnumDescriptorProto struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` + Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` + // Range of reserved numeric values. Reserved numeric values may not be used + // by enum values in the same enum declaration. Reserved ranges may not + // overlap. + ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` + // Reserved enum value names, which may not be reused. A given name may only + // be reserved once. + ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` +} + +func (x *EnumDescriptorProto) Reset() { + *x = EnumDescriptorProto{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *EnumDescriptorProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EnumDescriptorProto) ProtoMessage() {} + +func (x *EnumDescriptorProto) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EnumDescriptorProto.ProtoReflect.Descriptor instead. +func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{6} +} + +func (x *EnumDescriptorProto) GetName() string { + if x != nil && x.Name != nil { + return *x.Name + } + return "" +} + +func (x *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto { + if x != nil { + return x.Value + } + return nil +} + +func (x *EnumDescriptorProto) GetOptions() *EnumOptions { + if x != nil { + return x.Options + } + return nil +} + +func (x *EnumDescriptorProto) GetReservedRange() []*EnumDescriptorProto_EnumReservedRange { + if x != nil { + return x.ReservedRange + } + return nil +} + +func (x *EnumDescriptorProto) GetReservedName() []string { + if x != nil { + return x.ReservedName + } + return nil +} + +// Describes a value within an enum. +type EnumValueDescriptorProto struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` + Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` +} + +func (x *EnumValueDescriptorProto) Reset() { + *x = EnumValueDescriptorProto{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *EnumValueDescriptorProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EnumValueDescriptorProto) ProtoMessage() {} + +func (x *EnumValueDescriptorProto) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[7] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EnumValueDescriptorProto.ProtoReflect.Descriptor instead. +func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{7} +} + +func (x *EnumValueDescriptorProto) GetName() string { + if x != nil && x.Name != nil { + return *x.Name + } + return "" +} + +func (x *EnumValueDescriptorProto) GetNumber() int32 { + if x != nil && x.Number != nil { + return *x.Number + } + return 0 +} + +func (x *EnumValueDescriptorProto) GetOptions() *EnumValueOptions { + if x != nil { + return x.Options + } + return nil +} + +// Describes a service. +type ServiceDescriptorProto struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` + Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` +} + +func (x *ServiceDescriptorProto) Reset() { + *x = ServiceDescriptorProto{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ServiceDescriptorProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ServiceDescriptorProto) ProtoMessage() {} + +func (x *ServiceDescriptorProto) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ServiceDescriptorProto.ProtoReflect.Descriptor instead. +func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{8} +} + +func (x *ServiceDescriptorProto) GetName() string { + if x != nil && x.Name != nil { + return *x.Name + } + return "" +} + +func (x *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto { + if x != nil { + return x.Method + } + return nil +} + +func (x *ServiceDescriptorProto) GetOptions() *ServiceOptions { + if x != nil { + return x.Options + } + return nil +} + +// Describes a method of a service. +type MethodDescriptorProto struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + // Input and output type names. These are resolved in the same way as + // FieldDescriptorProto.type_name, but must refer to a message type. + InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"` + OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"` + Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"` + // Identifies if client streams multiple client messages + ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"` + // Identifies if server streams multiple server messages + ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"` +} + +// Default values for MethodDescriptorProto fields. +const ( + Default_MethodDescriptorProto_ClientStreaming = bool(false) + Default_MethodDescriptorProto_ServerStreaming = bool(false) +) + +func (x *MethodDescriptorProto) Reset() { + *x = MethodDescriptorProto{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MethodDescriptorProto) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MethodDescriptorProto) ProtoMessage() {} + +func (x *MethodDescriptorProto) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[9] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MethodDescriptorProto.ProtoReflect.Descriptor instead. +func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{9} +} + +func (x *MethodDescriptorProto) GetName() string { + if x != nil && x.Name != nil { + return *x.Name + } + return "" +} + +func (x *MethodDescriptorProto) GetInputType() string { + if x != nil && x.InputType != nil { + return *x.InputType + } + return "" +} + +func (x *MethodDescriptorProto) GetOutputType() string { + if x != nil && x.OutputType != nil { + return *x.OutputType + } + return "" +} + +func (x *MethodDescriptorProto) GetOptions() *MethodOptions { + if x != nil { + return x.Options + } + return nil +} + +func (x *MethodDescriptorProto) GetClientStreaming() bool { + if x != nil && x.ClientStreaming != nil { + return *x.ClientStreaming + } + return Default_MethodDescriptorProto_ClientStreaming +} + +func (x *MethodDescriptorProto) GetServerStreaming() bool { + if x != nil && x.ServerStreaming != nil { + return *x.ServerStreaming + } + return Default_MethodDescriptorProto_ServerStreaming +} + +type FileOptions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + extensionFields protoimpl.ExtensionFields + + // Sets the Java package where classes generated from this .proto will be + // placed. By default, the proto package is used, but this is often + // inappropriate because proto packages do not normally start with backwards + // domain names. + JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"` + // If set, all the classes from the .proto file are wrapped in a single + // outer class with the given name. This applies to both Proto1 + // (equivalent to the old "--one_java_file" option) and Proto2 (where + // a .proto always translates to a single class, but you may want to + // explicitly choose the class name). + JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"` + // If set true, then the Java code generator will generate a separate .java + // file for each top-level message, enum, and service defined in the .proto + // file. Thus, these types will *not* be nested inside the outer class + // named by java_outer_classname. However, the outer class will still be + // generated to contain the file's getDescriptor() method as well as any + // top-level extensions defined in the file. + JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"` + // This option does nothing. + // + // Deprecated: Do not use. + JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` + // If set true, then the Java2 code generator will generate code that + // throws an exception whenever an attempt is made to assign a non-UTF-8 + // byte sequence to a string field. + // Message reflection will do the same. + // However, an extension field still accepts non-UTF-8 byte sequences. + // This option has no effect on when used with the lite runtime. + JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"` + OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"` + // Sets the Go package where structs generated from this .proto will be + // placed. If omitted, the Go package will be derived from the following: + // - The basename of the package import path, if provided. + // - Otherwise, the package statement in the .proto file, if present. + // - Otherwise, the basename of the .proto file, without extension. + GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"` + // Should generic services be generated in each language? "Generic" services + // are not specific to any particular RPC system. They are generated by the + // main code generators in each language (without additional plugins). + // Generic services were the only kind of service generation supported by + // early versions of google.protobuf. + // + // Generic services are now considered deprecated in favor of using plugins + // that generate code specific to your particular RPC system. Therefore, + // these default to false. Old code which depends on generic services should + // explicitly set them to true. + CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"` + JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"` + PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"` + PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"` + // Is this file deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for everything in the file, or it will be completely ignored; in the very + // least, this is a formalization for deprecating files. + Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"` + // Enables the use of arenas for the proto messages in this file. This applies + // only to generated classes for C++. + CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=1" json:"cc_enable_arenas,omitempty"` + // Sets the objective c class prefix which is prepended to all objective c + // generated classes from this .proto. There is no default. + ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"` + // Namespace for generated classes; defaults to the package. + CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"` + // By default Swift generators will take the proto package and CamelCase it + // replacing '.' with underscore and use that to prefix the types/symbols + // defined. When this options is provided, they will use this value instead + // to prefix the types/symbols defined. + SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"` + // Sets the php class prefix which is prepended to all php generated classes + // from this .proto. Default is empty. + PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"` + // Use this option to change the namespace of php generated classes. Default + // is empty. When this option is empty, the package name will be used for + // determining the namespace. + PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"` + // Use this option to change the namespace of php generated metadata classes. + // Default is empty. When this option is empty, the proto file name will be + // used for determining the namespace. + PhpMetadataNamespace *string `protobuf:"bytes,44,opt,name=php_metadata_namespace,json=phpMetadataNamespace" json:"php_metadata_namespace,omitempty"` + // Use this option to change the package of ruby generated classes. Default + // is empty. When this option is not set, the package name will be used for + // determining the ruby package. + RubyPackage *string `protobuf:"bytes,45,opt,name=ruby_package,json=rubyPackage" json:"ruby_package,omitempty"` + // The parser stores options it doesn't recognize here. + // See the documentation for the "Options" section above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` +} + +// Default values for FileOptions fields. +const ( + Default_FileOptions_JavaMultipleFiles = bool(false) + Default_FileOptions_JavaStringCheckUtf8 = bool(false) + Default_FileOptions_OptimizeFor = FileOptions_SPEED + Default_FileOptions_CcGenericServices = bool(false) + Default_FileOptions_JavaGenericServices = bool(false) + Default_FileOptions_PyGenericServices = bool(false) + Default_FileOptions_PhpGenericServices = bool(false) + Default_FileOptions_Deprecated = bool(false) + Default_FileOptions_CcEnableArenas = bool(true) +) + +func (x *FileOptions) Reset() { + *x = FileOptions{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *FileOptions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FileOptions) ProtoMessage() {} + +func (x *FileOptions) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[10] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FileOptions.ProtoReflect.Descriptor instead. +func (*FileOptions) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{10} +} + +var extRange_FileOptions = []protoiface.ExtensionRangeV1{ + {Start: 1000, End: 536870911}, +} + +// Deprecated: Use FileOptions.ProtoReflect.Descriptor.ExtensionRanges instead. +func (*FileOptions) ExtensionRangeArray() []protoiface.ExtensionRangeV1 { + return extRange_FileOptions +} + +func (x *FileOptions) GetJavaPackage() string { + if x != nil && x.JavaPackage != nil { + return *x.JavaPackage + } + return "" +} + +func (x *FileOptions) GetJavaOuterClassname() string { + if x != nil && x.JavaOuterClassname != nil { + return *x.JavaOuterClassname + } + return "" +} + +func (x *FileOptions) GetJavaMultipleFiles() bool { + if x != nil && x.JavaMultipleFiles != nil { + return *x.JavaMultipleFiles + } + return Default_FileOptions_JavaMultipleFiles +} + +// Deprecated: Do not use. +func (x *FileOptions) GetJavaGenerateEqualsAndHash() bool { + if x != nil && x.JavaGenerateEqualsAndHash != nil { + return *x.JavaGenerateEqualsAndHash + } + return false +} + +func (x *FileOptions) GetJavaStringCheckUtf8() bool { + if x != nil && x.JavaStringCheckUtf8 != nil { + return *x.JavaStringCheckUtf8 + } + return Default_FileOptions_JavaStringCheckUtf8 +} + +func (x *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode { + if x != nil && x.OptimizeFor != nil { + return *x.OptimizeFor + } + return Default_FileOptions_OptimizeFor +} + +func (x *FileOptions) GetGoPackage() string { + if x != nil && x.GoPackage != nil { + return *x.GoPackage + } + return "" +} + +func (x *FileOptions) GetCcGenericServices() bool { + if x != nil && x.CcGenericServices != nil { + return *x.CcGenericServices + } + return Default_FileOptions_CcGenericServices +} + +func (x *FileOptions) GetJavaGenericServices() bool { + if x != nil && x.JavaGenericServices != nil { + return *x.JavaGenericServices + } + return Default_FileOptions_JavaGenericServices +} + +func (x *FileOptions) GetPyGenericServices() bool { + if x != nil && x.PyGenericServices != nil { + return *x.PyGenericServices + } + return Default_FileOptions_PyGenericServices +} + +func (x *FileOptions) GetPhpGenericServices() bool { + if x != nil && x.PhpGenericServices != nil { + return *x.PhpGenericServices + } + return Default_FileOptions_PhpGenericServices +} + +func (x *FileOptions) GetDeprecated() bool { + if x != nil && x.Deprecated != nil { + return *x.Deprecated + } + return Default_FileOptions_Deprecated +} + +func (x *FileOptions) GetCcEnableArenas() bool { + if x != nil && x.CcEnableArenas != nil { + return *x.CcEnableArenas + } + return Default_FileOptions_CcEnableArenas +} + +func (x *FileOptions) GetObjcClassPrefix() string { + if x != nil && x.ObjcClassPrefix != nil { + return *x.ObjcClassPrefix + } + return "" +} + +func (x *FileOptions) GetCsharpNamespace() string { + if x != nil && x.CsharpNamespace != nil { + return *x.CsharpNamespace + } + return "" +} + +func (x *FileOptions) GetSwiftPrefix() string { + if x != nil && x.SwiftPrefix != nil { + return *x.SwiftPrefix + } + return "" +} + +func (x *FileOptions) GetPhpClassPrefix() string { + if x != nil && x.PhpClassPrefix != nil { + return *x.PhpClassPrefix + } + return "" +} + +func (x *FileOptions) GetPhpNamespace() string { + if x != nil && x.PhpNamespace != nil { + return *x.PhpNamespace + } + return "" +} + +func (x *FileOptions) GetPhpMetadataNamespace() string { + if x != nil && x.PhpMetadataNamespace != nil { + return *x.PhpMetadataNamespace + } + return "" +} + +func (x *FileOptions) GetRubyPackage() string { + if x != nil && x.RubyPackage != nil { + return *x.RubyPackage + } + return "" +} + +func (x *FileOptions) GetUninterpretedOption() []*UninterpretedOption { + if x != nil { + return x.UninterpretedOption + } + return nil +} + +type MessageOptions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + extensionFields protoimpl.ExtensionFields + + // Set true to use the old proto1 MessageSet wire format for extensions. + // This is provided for backwards-compatibility with the MessageSet wire + // format. You should not use this for any other reason: It's less + // efficient, has fewer features, and is more complicated. + // + // The message must be defined exactly as follows: + // message Foo { + // option message_set_wire_format = true; + // extensions 4 to max; + // } + // Note that the message cannot have any defined fields; MessageSets only + // have extensions. + // + // All extensions of your type must be singular messages; e.g. they cannot + // be int32s, enums, or repeated messages. + // + // Because this is an option, the above two restrictions are not enforced by + // the protocol compiler. + MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"` + // Disables the generation of the standard "descriptor()" accessor, which can + // conflict with a field of the same name. This is meant to make migration + // from proto1 easier; new code should avoid fields named "descriptor". + NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"` + // Is this message deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the message, or it will be completely ignored; in the very least, + // this is a formalization for deprecating messages. + Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` + // Whether the message is an automatically generated map entry type for the + // maps field. + // + // For maps fields: + // map map_field = 1; + // The parsed descriptor looks like: + // message MapFieldEntry { + // option map_entry = true; + // optional KeyType key = 1; + // optional ValueType value = 2; + // } + // repeated MapFieldEntry map_field = 1; + // + // Implementations may choose not to generate the map_entry=true message, but + // use a native map in the target language to hold the keys and values. + // The reflection APIs in such implementations still need to work as + // if the field is a repeated message field. + // + // NOTE: Do not set the option in .proto files. Always use the maps syntax + // instead. The option should only be implicitly set by the proto compiler + // parser. + MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"` + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` +} + +// Default values for MessageOptions fields. +const ( + Default_MessageOptions_MessageSetWireFormat = bool(false) + Default_MessageOptions_NoStandardDescriptorAccessor = bool(false) + Default_MessageOptions_Deprecated = bool(false) +) + +func (x *MessageOptions) Reset() { + *x = MessageOptions{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MessageOptions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MessageOptions) ProtoMessage() {} + +func (x *MessageOptions) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[11] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MessageOptions.ProtoReflect.Descriptor instead. +func (*MessageOptions) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{11} +} + +var extRange_MessageOptions = []protoiface.ExtensionRangeV1{ + {Start: 1000, End: 536870911}, +} + +// Deprecated: Use MessageOptions.ProtoReflect.Descriptor.ExtensionRanges instead. +func (*MessageOptions) ExtensionRangeArray() []protoiface.ExtensionRangeV1 { + return extRange_MessageOptions +} + +func (x *MessageOptions) GetMessageSetWireFormat() bool { + if x != nil && x.MessageSetWireFormat != nil { + return *x.MessageSetWireFormat + } + return Default_MessageOptions_MessageSetWireFormat +} + +func (x *MessageOptions) GetNoStandardDescriptorAccessor() bool { + if x != nil && x.NoStandardDescriptorAccessor != nil { + return *x.NoStandardDescriptorAccessor + } + return Default_MessageOptions_NoStandardDescriptorAccessor +} + +func (x *MessageOptions) GetDeprecated() bool { + if x != nil && x.Deprecated != nil { + return *x.Deprecated + } + return Default_MessageOptions_Deprecated +} + +func (x *MessageOptions) GetMapEntry() bool { + if x != nil && x.MapEntry != nil { + return *x.MapEntry + } + return false +} + +func (x *MessageOptions) GetUninterpretedOption() []*UninterpretedOption { + if x != nil { + return x.UninterpretedOption + } + return nil +} + +type FieldOptions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + extensionFields protoimpl.ExtensionFields + + // The ctype option instructs the C++ code generator to use a different + // representation of the field than it normally would. See the specific + // options below. This option is not yet implemented in the open source + // release -- sorry, we'll try to include it in a future version! + Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"` + // The packed option can be enabled for repeated primitive fields to enable + // a more efficient representation on the wire. Rather than repeatedly + // writing the tag and type for each element, the entire array is encoded as + // a single length-delimited blob. In proto3, only explicit setting it to + // false will avoid using packed encoding. + Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"` + // The jstype option determines the JavaScript type used for values of the + // field. The option is permitted only for 64 bit integral and fixed types + // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + // is represented as JavaScript string, which avoids loss of precision that + // can happen when a large value is converted to a floating point JavaScript. + // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + // use the JavaScript "number" type. The behavior of the default option + // JS_NORMAL is implementation dependent. + // + // This option is an enum to permit additional types to be added, e.g. + // goog.math.Integer. + Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"` + // Should this field be parsed lazily? Lazy applies only to message-type + // fields. It means that when the outer message is initially parsed, the + // inner message's contents will not be parsed but instead stored in encoded + // form. The inner message will actually be parsed when it is first accessed. + // + // This is only a hint. Implementations are free to choose whether to use + // eager or lazy parsing regardless of the value of this option. However, + // setting this option true suggests that the protocol author believes that + // using lazy parsing on this field is worth the additional bookkeeping + // overhead typically needed to implement it. + // + // This option does not affect the public interface of any generated code; + // all method signatures remain the same. Furthermore, thread-safety of the + // interface is not affected by this option; const methods remain safe to + // call from multiple threads concurrently, while non-const methods continue + // to require exclusive access. + // + // + // Note that implementations may choose not to check required fields within + // a lazy sub-message. That is, calling IsInitialized() on the outer message + // may return true even if the inner message has missing required fields. + // This is necessary because otherwise the inner message would have to be + // parsed in order to perform the check, defeating the purpose of lazy + // parsing. An implementation which chooses not to check required fields + // must be consistent about it. That is, for any particular sub-message, the + // implementation must either *always* check its required fields, or *never* + // check its required fields, regardless of whether or not the message has + // been parsed. + Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"` + // Is this field deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for accessors, or it will be completely ignored; in the very least, this + // is a formalization for deprecating fields. + Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` + // For Google-internal migration only. Do not use. + Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"` + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` +} + +// Default values for FieldOptions fields. +const ( + Default_FieldOptions_Ctype = FieldOptions_STRING + Default_FieldOptions_Jstype = FieldOptions_JS_NORMAL + Default_FieldOptions_Lazy = bool(false) + Default_FieldOptions_Deprecated = bool(false) + Default_FieldOptions_Weak = bool(false) +) + +func (x *FieldOptions) Reset() { + *x = FieldOptions{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *FieldOptions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FieldOptions) ProtoMessage() {} + +func (x *FieldOptions) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[12] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FieldOptions.ProtoReflect.Descriptor instead. +func (*FieldOptions) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{12} +} + +var extRange_FieldOptions = []protoiface.ExtensionRangeV1{ + {Start: 1000, End: 536870911}, +} + +// Deprecated: Use FieldOptions.ProtoReflect.Descriptor.ExtensionRanges instead. +func (*FieldOptions) ExtensionRangeArray() []protoiface.ExtensionRangeV1 { + return extRange_FieldOptions +} + +func (x *FieldOptions) GetCtype() FieldOptions_CType { + if x != nil && x.Ctype != nil { + return *x.Ctype + } + return Default_FieldOptions_Ctype +} + +func (x *FieldOptions) GetPacked() bool { + if x != nil && x.Packed != nil { + return *x.Packed + } + return false +} + +func (x *FieldOptions) GetJstype() FieldOptions_JSType { + if x != nil && x.Jstype != nil { + return *x.Jstype + } + return Default_FieldOptions_Jstype +} + +func (x *FieldOptions) GetLazy() bool { + if x != nil && x.Lazy != nil { + return *x.Lazy + } + return Default_FieldOptions_Lazy +} + +func (x *FieldOptions) GetDeprecated() bool { + if x != nil && x.Deprecated != nil { + return *x.Deprecated + } + return Default_FieldOptions_Deprecated +} + +func (x *FieldOptions) GetWeak() bool { + if x != nil && x.Weak != nil { + return *x.Weak + } + return Default_FieldOptions_Weak +} + +func (x *FieldOptions) GetUninterpretedOption() []*UninterpretedOption { + if x != nil { + return x.UninterpretedOption + } + return nil +} + +type OneofOptions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + extensionFields protoimpl.ExtensionFields + + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` +} + +func (x *OneofOptions) Reset() { + *x = OneofOptions{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *OneofOptions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OneofOptions) ProtoMessage() {} + +func (x *OneofOptions) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[13] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OneofOptions.ProtoReflect.Descriptor instead. +func (*OneofOptions) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{13} +} + +var extRange_OneofOptions = []protoiface.ExtensionRangeV1{ + {Start: 1000, End: 536870911}, +} + +// Deprecated: Use OneofOptions.ProtoReflect.Descriptor.ExtensionRanges instead. +func (*OneofOptions) ExtensionRangeArray() []protoiface.ExtensionRangeV1 { + return extRange_OneofOptions +} + +func (x *OneofOptions) GetUninterpretedOption() []*UninterpretedOption { + if x != nil { + return x.UninterpretedOption + } + return nil +} + +type EnumOptions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + extensionFields protoimpl.ExtensionFields + + // Set this option to true to allow mapping different tag names to the same + // value. + AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"` + // Is this enum deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum, or it will be completely ignored; in the very least, this + // is a formalization for deprecating enums. + Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` +} + +// Default values for EnumOptions fields. +const ( + Default_EnumOptions_Deprecated = bool(false) +) + +func (x *EnumOptions) Reset() { + *x = EnumOptions{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *EnumOptions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EnumOptions) ProtoMessage() {} + +func (x *EnumOptions) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[14] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EnumOptions.ProtoReflect.Descriptor instead. +func (*EnumOptions) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{14} +} + +var extRange_EnumOptions = []protoiface.ExtensionRangeV1{ + {Start: 1000, End: 536870911}, +} + +// Deprecated: Use EnumOptions.ProtoReflect.Descriptor.ExtensionRanges instead. +func (*EnumOptions) ExtensionRangeArray() []protoiface.ExtensionRangeV1 { + return extRange_EnumOptions +} + +func (x *EnumOptions) GetAllowAlias() bool { + if x != nil && x.AllowAlias != nil { + return *x.AllowAlias + } + return false +} + +func (x *EnumOptions) GetDeprecated() bool { + if x != nil && x.Deprecated != nil { + return *x.Deprecated + } + return Default_EnumOptions_Deprecated +} + +func (x *EnumOptions) GetUninterpretedOption() []*UninterpretedOption { + if x != nil { + return x.UninterpretedOption + } + return nil +} + +type EnumValueOptions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + extensionFields protoimpl.ExtensionFields + + // Is this enum value deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum value, or it will be completely ignored; in the very least, + // this is a formalization for deprecating enum values. + Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"` + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` +} + +// Default values for EnumValueOptions fields. +const ( + Default_EnumValueOptions_Deprecated = bool(false) +) + +func (x *EnumValueOptions) Reset() { + *x = EnumValueOptions{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *EnumValueOptions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EnumValueOptions) ProtoMessage() {} + +func (x *EnumValueOptions) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[15] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EnumValueOptions.ProtoReflect.Descriptor instead. +func (*EnumValueOptions) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{15} +} + +var extRange_EnumValueOptions = []protoiface.ExtensionRangeV1{ + {Start: 1000, End: 536870911}, +} + +// Deprecated: Use EnumValueOptions.ProtoReflect.Descriptor.ExtensionRanges instead. +func (*EnumValueOptions) ExtensionRangeArray() []protoiface.ExtensionRangeV1 { + return extRange_EnumValueOptions +} + +func (x *EnumValueOptions) GetDeprecated() bool { + if x != nil && x.Deprecated != nil { + return *x.Deprecated + } + return Default_EnumValueOptions_Deprecated +} + +func (x *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption { + if x != nil { + return x.UninterpretedOption + } + return nil +} + +type ServiceOptions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + extensionFields protoimpl.ExtensionFields + + // Is this service deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the service, or it will be completely ignored; in the very least, + // this is a formalization for deprecating services. + Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` +} + +// Default values for ServiceOptions fields. +const ( + Default_ServiceOptions_Deprecated = bool(false) +) + +func (x *ServiceOptions) Reset() { + *x = ServiceOptions{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ServiceOptions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ServiceOptions) ProtoMessage() {} + +func (x *ServiceOptions) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[16] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ServiceOptions.ProtoReflect.Descriptor instead. +func (*ServiceOptions) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{16} +} + +var extRange_ServiceOptions = []protoiface.ExtensionRangeV1{ + {Start: 1000, End: 536870911}, +} + +// Deprecated: Use ServiceOptions.ProtoReflect.Descriptor.ExtensionRanges instead. +func (*ServiceOptions) ExtensionRangeArray() []protoiface.ExtensionRangeV1 { + return extRange_ServiceOptions +} + +func (x *ServiceOptions) GetDeprecated() bool { + if x != nil && x.Deprecated != nil { + return *x.Deprecated + } + return Default_ServiceOptions_Deprecated +} + +func (x *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption { + if x != nil { + return x.UninterpretedOption + } + return nil +} + +type MethodOptions struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + extensionFields protoimpl.ExtensionFields + + // Is this method deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the method, or it will be completely ignored; in the very least, + // this is a formalization for deprecating methods. + Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` + IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"` + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` +} + +// Default values for MethodOptions fields. +const ( + Default_MethodOptions_Deprecated = bool(false) + Default_MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN +) + +func (x *MethodOptions) Reset() { + *x = MethodOptions{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MethodOptions) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MethodOptions) ProtoMessage() {} + +func (x *MethodOptions) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[17] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MethodOptions.ProtoReflect.Descriptor instead. +func (*MethodOptions) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{17} +} + +var extRange_MethodOptions = []protoiface.ExtensionRangeV1{ + {Start: 1000, End: 536870911}, +} + +// Deprecated: Use MethodOptions.ProtoReflect.Descriptor.ExtensionRanges instead. +func (*MethodOptions) ExtensionRangeArray() []protoiface.ExtensionRangeV1 { + return extRange_MethodOptions +} + +func (x *MethodOptions) GetDeprecated() bool { + if x != nil && x.Deprecated != nil { + return *x.Deprecated + } + return Default_MethodOptions_Deprecated +} + +func (x *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel { + if x != nil && x.IdempotencyLevel != nil { + return *x.IdempotencyLevel + } + return Default_MethodOptions_IdempotencyLevel +} + +func (x *MethodOptions) GetUninterpretedOption() []*UninterpretedOption { + if x != nil { + return x.UninterpretedOption + } + return nil +} + +// A message representing a option the parser does not recognize. This only +// appears in options protos created by the compiler::Parser class. +// DescriptorPool resolves these when building Descriptor objects. Therefore, +// options protos in descriptor objects (e.g. returned by Descriptor::options(), +// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions +// in them. +type UninterpretedOption struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"` + // The value of the uninterpreted option, in whatever type the tokenizer + // identified it as during parsing. Exactly one of these should be set. + IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"` + PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"` + NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"` + DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` + StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` + AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"` +} + +func (x *UninterpretedOption) Reset() { + *x = UninterpretedOption{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UninterpretedOption) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UninterpretedOption) ProtoMessage() {} + +func (x *UninterpretedOption) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[18] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UninterpretedOption.ProtoReflect.Descriptor instead. +func (*UninterpretedOption) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{18} +} + +func (x *UninterpretedOption) GetName() []*UninterpretedOption_NamePart { + if x != nil { + return x.Name + } + return nil +} + +func (x *UninterpretedOption) GetIdentifierValue() string { + if x != nil && x.IdentifierValue != nil { + return *x.IdentifierValue + } + return "" +} + +func (x *UninterpretedOption) GetPositiveIntValue() uint64 { + if x != nil && x.PositiveIntValue != nil { + return *x.PositiveIntValue + } + return 0 +} + +func (x *UninterpretedOption) GetNegativeIntValue() int64 { + if x != nil && x.NegativeIntValue != nil { + return *x.NegativeIntValue + } + return 0 +} + +func (x *UninterpretedOption) GetDoubleValue() float64 { + if x != nil && x.DoubleValue != nil { + return *x.DoubleValue + } + return 0 +} + +func (x *UninterpretedOption) GetStringValue() []byte { + if x != nil { + return x.StringValue + } + return nil +} + +func (x *UninterpretedOption) GetAggregateValue() string { + if x != nil && x.AggregateValue != nil { + return *x.AggregateValue + } + return "" +} + +// Encapsulates information about the original source file from which a +// FileDescriptorProto was generated. +type SourceCodeInfo struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // A Location identifies a piece of source code in a .proto file which + // corresponds to a particular definition. This information is intended + // to be useful to IDEs, code indexers, documentation generators, and similar + // tools. + // + // For example, say we have a file like: + // message Foo { + // optional string foo = 1; + // } + // Let's look at just the field definition: + // optional string foo = 1; + // ^ ^^ ^^ ^ ^^^ + // a bc de f ghi + // We have the following locations: + // span path represents + // [a,i) [ 4, 0, 2, 0 ] The whole field definition. + // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + // + // Notes: + // - A location may refer to a repeated field itself (i.e. not to any + // particular index within it). This is used whenever a set of elements are + // logically enclosed in a single code segment. For example, an entire + // extend block (possibly containing multiple extension definitions) will + // have an outer location whose path refers to the "extensions" repeated + // field without an index. + // - Multiple locations may have the same path. This happens when a single + // logical declaration is spread out across multiple places. The most + // obvious example is the "extend" block again -- there may be multiple + // extend blocks in the same scope, each of which will have the same path. + // - A location's span is not always a subset of its parent's span. For + // example, the "extendee" of an extension declaration appears at the + // beginning of the "extend" block and is shared by all extensions within + // the block. + // - Just because a location's span is a subset of some other location's span + // does not mean that it is a descendant. For example, a "group" defines + // both a type and a field in a single declaration. Thus, the locations + // corresponding to the type and field and their components will overlap. + // - Code which tries to interpret locations should probably be designed to + // ignore those that it doesn't understand, as more types of locations could + // be recorded in the future. + Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` +} + +func (x *SourceCodeInfo) Reset() { + *x = SourceCodeInfo{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SourceCodeInfo) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SourceCodeInfo) ProtoMessage() {} + +func (x *SourceCodeInfo) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[19] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SourceCodeInfo.ProtoReflect.Descriptor instead. +func (*SourceCodeInfo) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{19} +} + +func (x *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location { + if x != nil { + return x.Location + } + return nil +} + +// Describes the relationship between generated code and its original source +// file. A GeneratedCodeInfo message is associated with only one generated +// source file, but may contain references to different source .proto files. +type GeneratedCodeInfo struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // An Annotation connects some span of text in generated code to an element + // of its generating .proto file. + Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"` +} + +func (x *GeneratedCodeInfo) Reset() { + *x = GeneratedCodeInfo{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GeneratedCodeInfo) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GeneratedCodeInfo) ProtoMessage() {} + +func (x *GeneratedCodeInfo) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[20] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GeneratedCodeInfo.ProtoReflect.Descriptor instead. +func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{20} +} + +func (x *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation { + if x != nil { + return x.Annotation + } + return nil +} + +type DescriptorProto_ExtensionRange struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` // Inclusive. + End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` // Exclusive. + Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` +} + +func (x *DescriptorProto_ExtensionRange) Reset() { + *x = DescriptorProto_ExtensionRange{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DescriptorProto_ExtensionRange) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DescriptorProto_ExtensionRange) ProtoMessage() {} + +func (x *DescriptorProto_ExtensionRange) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[21] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DescriptorProto_ExtensionRange.ProtoReflect.Descriptor instead. +func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{2, 0} +} + +func (x *DescriptorProto_ExtensionRange) GetStart() int32 { + if x != nil && x.Start != nil { + return *x.Start + } + return 0 +} + +func (x *DescriptorProto_ExtensionRange) GetEnd() int32 { + if x != nil && x.End != nil { + return *x.End + } + return 0 +} + +func (x *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions { + if x != nil { + return x.Options + } + return nil +} + +// Range of reserved tag numbers. Reserved tag numbers may not be used by +// fields or extension ranges in the same message. Reserved ranges may +// not overlap. +type DescriptorProto_ReservedRange struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` // Inclusive. + End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` // Exclusive. +} + +func (x *DescriptorProto_ReservedRange) Reset() { + *x = DescriptorProto_ReservedRange{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[22] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DescriptorProto_ReservedRange) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DescriptorProto_ReservedRange) ProtoMessage() {} + +func (x *DescriptorProto_ReservedRange) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[22] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DescriptorProto_ReservedRange.ProtoReflect.Descriptor instead. +func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{2, 1} +} + +func (x *DescriptorProto_ReservedRange) GetStart() int32 { + if x != nil && x.Start != nil { + return *x.Start + } + return 0 +} + +func (x *DescriptorProto_ReservedRange) GetEnd() int32 { + if x != nil && x.End != nil { + return *x.End + } + return 0 +} + +// Range of reserved numeric values. Reserved values may not be used by +// entries in the same enum. Reserved ranges may not overlap. +// +// Note that this is distinct from DescriptorProto.ReservedRange in that it +// is inclusive such that it can appropriately represent the entire int32 +// domain. +type EnumDescriptorProto_EnumReservedRange struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` // Inclusive. + End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` // Inclusive. +} + +func (x *EnumDescriptorProto_EnumReservedRange) Reset() { + *x = EnumDescriptorProto_EnumReservedRange{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *EnumDescriptorProto_EnumReservedRange) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {} + +func (x *EnumDescriptorProto_EnumReservedRange) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[23] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EnumDescriptorProto_EnumReservedRange.ProtoReflect.Descriptor instead. +func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{6, 0} +} + +func (x *EnumDescriptorProto_EnumReservedRange) GetStart() int32 { + if x != nil && x.Start != nil { + return *x.Start + } + return 0 +} + +func (x *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 { + if x != nil && x.End != nil { + return *x.End + } + return 0 +} + +// The name of the uninterpreted option. Each string represents a segment in +// a dot-separated name. is_extension is true iff a segment represents an +// extension (denoted with parentheses in options specs in .proto files). +// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents +// "foo.(bar.baz).qux". +type UninterpretedOption_NamePart struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"` + IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"` +} + +func (x *UninterpretedOption_NamePart) Reset() { + *x = UninterpretedOption_NamePart{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[24] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UninterpretedOption_NamePart) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UninterpretedOption_NamePart) ProtoMessage() {} + +func (x *UninterpretedOption_NamePart) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[24] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UninterpretedOption_NamePart.ProtoReflect.Descriptor instead. +func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{18, 0} +} + +func (x *UninterpretedOption_NamePart) GetNamePart() string { + if x != nil && x.NamePart != nil { + return *x.NamePart + } + return "" +} + +func (x *UninterpretedOption_NamePart) GetIsExtension() bool { + if x != nil && x.IsExtension != nil { + return *x.IsExtension + } + return false +} + +type SourceCodeInfo_Location struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Identifies which part of the FileDescriptorProto was defined at this + // location. + // + // Each element is a field number or an index. They form a path from + // the root FileDescriptorProto to the place where the definition. For + // example, this path: + // [ 4, 3, 2, 7, 1 ] + // refers to: + // file.message_type(3) // 4, 3 + // .field(7) // 2, 7 + // .name() // 1 + // This is because FileDescriptorProto.message_type has field number 4: + // repeated DescriptorProto message_type = 4; + // and DescriptorProto.field has field number 2: + // repeated FieldDescriptorProto field = 2; + // and FieldDescriptorProto.name has field number 1: + // optional string name = 1; + // + // Thus, the above path gives the location of a field name. If we removed + // the last element: + // [ 4, 3, 2, 7 ] + // this path refers to the whole field declaration (from the beginning + // of the label to the terminating semicolon). + Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` + // Always has exactly three or four elements: start line, start column, + // end line (optional, otherwise assumed same as start line), end column. + // These are packed into a single field for efficiency. Note that line + // and column numbers are zero-based -- typically you will want to add + // 1 to each before displaying to a user. + Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"` + // If this SourceCodeInfo represents a complete declaration, these are any + // comments appearing before and after the declaration which appear to be + // attached to the declaration. + // + // A series of line comments appearing on consecutive lines, with no other + // tokens appearing on those lines, will be treated as a single comment. + // + // leading_detached_comments will keep paragraphs of comments that appear + // before (but not connected to) the current element. Each paragraph, + // separated by empty lines, will be one comment element in the repeated + // field. + // + // Only the comment content is provided; comment markers (e.g. //) are + // stripped out. For block comments, leading whitespace and an asterisk + // will be stripped from the beginning of each line other than the first. + // Newlines are included in the output. + // + // Examples: + // + // optional int32 foo = 1; // Comment attached to foo. + // // Comment attached to bar. + // optional int32 bar = 2; + // + // optional string baz = 3; + // // Comment attached to baz. + // // Another line attached to baz. + // + // // Comment attached to qux. + // // + // // Another line attached to qux. + // optional double qux = 4; + // + // // Detached comment for corge. This is not leading or trailing comments + // // to qux or corge because there are blank lines separating it from + // // both. + // + // // Detached comment for corge paragraph 2. + // + // optional string corge = 5; + // /* Block comment attached + // * to corge. Leading asterisks + // * will be removed. */ + // /* Block comment attached to + // * grault. */ + // optional int32 grault = 6; + // + // // ignored detached comments. + LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"` + TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"` + LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"` +} + +func (x *SourceCodeInfo_Location) Reset() { + *x = SourceCodeInfo_Location{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[25] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SourceCodeInfo_Location) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SourceCodeInfo_Location) ProtoMessage() {} + +func (x *SourceCodeInfo_Location) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[25] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SourceCodeInfo_Location.ProtoReflect.Descriptor instead. +func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{19, 0} +} + +func (x *SourceCodeInfo_Location) GetPath() []int32 { + if x != nil { + return x.Path + } + return nil +} + +func (x *SourceCodeInfo_Location) GetSpan() []int32 { + if x != nil { + return x.Span + } + return nil +} + +func (x *SourceCodeInfo_Location) GetLeadingComments() string { + if x != nil && x.LeadingComments != nil { + return *x.LeadingComments + } + return "" +} + +func (x *SourceCodeInfo_Location) GetTrailingComments() string { + if x != nil && x.TrailingComments != nil { + return *x.TrailingComments + } + return "" +} + +func (x *SourceCodeInfo_Location) GetLeadingDetachedComments() []string { + if x != nil { + return x.LeadingDetachedComments + } + return nil +} + +type GeneratedCodeInfo_Annotation struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Identifies the element in the original source .proto file. This field + // is formatted the same as SourceCodeInfo.Location.path. + Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` + // Identifies the filesystem path to the original source .proto. + SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"` + // Identifies the starting offset in bytes in the generated code + // that relates to the identified object. + Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"` + // Identifies the ending offset in bytes in the generated code that + // relates to the identified offset. The end offset should be one past + // the last relevant byte (so the length of the text = end - begin). + End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"` +} + +func (x *GeneratedCodeInfo_Annotation) Reset() { + *x = GeneratedCodeInfo_Annotation{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_descriptor_proto_msgTypes[26] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GeneratedCodeInfo_Annotation) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GeneratedCodeInfo_Annotation) ProtoMessage() {} + +func (x *GeneratedCodeInfo_Annotation) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_descriptor_proto_msgTypes[26] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GeneratedCodeInfo_Annotation.ProtoReflect.Descriptor instead. +func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) { + return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{20, 0} +} + +func (x *GeneratedCodeInfo_Annotation) GetPath() []int32 { + if x != nil { + return x.Path + } + return nil +} + +func (x *GeneratedCodeInfo_Annotation) GetSourceFile() string { + if x != nil && x.SourceFile != nil { + return *x.SourceFile + } + return "" +} + +func (x *GeneratedCodeInfo_Annotation) GetBegin() int32 { + if x != nil && x.Begin != nil { + return *x.Begin + } + return 0 +} + +func (x *GeneratedCodeInfo_Annotation) GetEnd() int32 { + if x != nil && x.End != nil { + return *x.End + } + return 0 +} + +var File_google_protobuf_descriptor_proto protoreflect.FileDescriptor + +var file_google_protobuf_descriptor_proto_rawDesc = []byte{ + 0x0a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x12, 0x0f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x22, 0x4d, 0x0a, 0x11, 0x46, 0x69, 0x6c, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, + 0x69, 0x70, 0x74, 0x6f, 0x72, 0x53, 0x65, 0x74, 0x12, 0x38, 0x0a, 0x04, 0x66, 0x69, 0x6c, 0x65, + 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x44, 0x65, 0x73, + 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x52, 0x04, 0x66, 0x69, + 0x6c, 0x65, 0x22, 0xe4, 0x04, 0x0a, 0x13, 0x46, 0x69, 0x6c, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, + 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, + 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x18, + 0x0a, 0x07, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x07, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x64, 0x65, 0x70, 0x65, + 0x6e, 0x64, 0x65, 0x6e, 0x63, 0x79, 0x18, 0x03, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0a, 0x64, 0x65, + 0x70, 0x65, 0x6e, 0x64, 0x65, 0x6e, 0x63, 0x79, 0x12, 0x2b, 0x0a, 0x11, 0x70, 0x75, 0x62, 0x6c, + 0x69, 0x63, 0x5f, 0x64, 0x65, 0x70, 0x65, 0x6e, 0x64, 0x65, 0x6e, 0x63, 0x79, 0x18, 0x0a, 0x20, + 0x03, 0x28, 0x05, 0x52, 0x10, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x44, 0x65, 0x70, 0x65, 0x6e, + 0x64, 0x65, 0x6e, 0x63, 0x79, 0x12, 0x27, 0x0a, 0x0f, 0x77, 0x65, 0x61, 0x6b, 0x5f, 0x64, 0x65, + 0x70, 0x65, 0x6e, 0x64, 0x65, 0x6e, 0x63, 0x79, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x05, 0x52, 0x0e, + 0x77, 0x65, 0x61, 0x6b, 0x44, 0x65, 0x70, 0x65, 0x6e, 0x64, 0x65, 0x6e, 0x63, 0x79, 0x12, 0x43, + 0x0a, 0x0c, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x04, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, + 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x52, 0x0b, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, + 0x79, 0x70, 0x65, 0x12, 0x41, 0x0a, 0x09, 0x65, 0x6e, 0x75, 0x6d, 0x5f, 0x74, 0x79, 0x70, 0x65, + 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6e, 0x75, 0x6d, 0x44, 0x65, 0x73, + 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x52, 0x08, 0x65, 0x6e, + 0x75, 0x6d, 0x54, 0x79, 0x70, 0x65, 0x12, 0x41, 0x0a, 0x07, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x18, 0x06, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, + 0x52, 0x07, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x43, 0x0a, 0x09, 0x65, 0x78, 0x74, + 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, + 0x69, 0x65, 0x6c, 0x64, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, + 0x6f, 0x74, 0x6f, 0x52, 0x09, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x36, + 0x0a, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x07, 0x6f, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x49, 0x0a, 0x10, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2e, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, + 0x6f, 0x52, 0x0e, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, + 0x6f, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x18, 0x0c, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x06, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x22, 0xb9, 0x06, 0x0a, 0x0f, 0x44, 0x65, + 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x12, 0x0a, + 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, + 0x65, 0x12, 0x3b, 0x0a, 0x05, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x25, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, + 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x52, 0x05, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x12, 0x43, + 0x0a, 0x09, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x25, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, + 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x52, 0x09, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, + 0x69, 0x6f, 0x6e, 0x12, 0x41, 0x0a, 0x0b, 0x6e, 0x65, 0x73, 0x74, 0x65, 0x64, 0x5f, 0x74, 0x79, + 0x70, 0x65, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x65, 0x73, 0x63, 0x72, + 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x52, 0x0a, 0x6e, 0x65, 0x73, 0x74, + 0x65, 0x64, 0x54, 0x79, 0x70, 0x65, 0x12, 0x41, 0x0a, 0x09, 0x65, 0x6e, 0x75, 0x6d, 0x5f, 0x74, + 0x79, 0x70, 0x65, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6e, 0x75, 0x6d, + 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x52, + 0x08, 0x65, 0x6e, 0x75, 0x6d, 0x54, 0x79, 0x70, 0x65, 0x12, 0x58, 0x0a, 0x0f, 0x65, 0x78, 0x74, + 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x18, 0x05, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, + 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x61, + 0x6e, 0x67, 0x65, 0x52, 0x0e, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x61, + 0x6e, 0x67, 0x65, 0x12, 0x44, 0x0a, 0x0a, 0x6f, 0x6e, 0x65, 0x6f, 0x66, 0x5f, 0x64, 0x65, 0x63, + 0x6c, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x25, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4f, 0x6e, 0x65, 0x6f, 0x66, 0x44, + 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x52, 0x09, + 0x6f, 0x6e, 0x65, 0x6f, 0x66, 0x44, 0x65, 0x63, 0x6c, 0x12, 0x39, 0x0a, 0x07, 0x6f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4d, 0x65, 0x73, + 0x73, 0x61, 0x67, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x07, 0x6f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x55, 0x0a, 0x0e, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, + 0x5f, 0x72, 0x61, 0x6e, 0x67, 0x65, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, + 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x52, + 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x0d, 0x72, 0x65, + 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x72, + 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x0a, 0x20, 0x03, + 0x28, 0x09, 0x52, 0x0c, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x4e, 0x61, 0x6d, 0x65, + 0x1a, 0x7a, 0x0a, 0x0e, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x61, 0x6e, + 0x67, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x05, 0x52, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x65, 0x6e, 0x64, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x65, 0x6e, 0x64, 0x12, 0x40, 0x0a, 0x07, 0x6f, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x78, + 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x4f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x52, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x1a, 0x37, 0x0a, 0x0d, + 0x52, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x14, 0x0a, + 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x73, 0x74, + 0x61, 0x72, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x65, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, + 0x52, 0x03, 0x65, 0x6e, 0x64, 0x22, 0x7c, 0x0a, 0x15, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, + 0x6f, 0x6e, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x58, + 0x0a, 0x14, 0x75, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x5f, + 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0xe7, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x55, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x52, 0x13, 0x75, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, + 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x2a, 0x09, 0x08, 0xe8, 0x07, 0x10, 0x80, 0x80, + 0x80, 0x80, 0x02, 0x22, 0xc1, 0x06, 0x0a, 0x14, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x44, 0x65, 0x73, + 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x12, 0x0a, 0x04, + 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, + 0x12, 0x16, 0x0a, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, + 0x52, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x41, 0x0a, 0x05, 0x6c, 0x61, 0x62, 0x65, + 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x44, + 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x4c, + 0x61, 0x62, 0x65, 0x6c, 0x52, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x12, 0x3e, 0x0a, 0x04, 0x74, + 0x79, 0x70, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, + 0x64, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, + 0x2e, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x74, + 0x79, 0x70, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, + 0x74, 0x79, 0x70, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x65, 0x78, 0x74, 0x65, + 0x6e, 0x64, 0x65, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x65, 0x78, 0x74, 0x65, + 0x6e, 0x64, 0x65, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x5f, + 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x64, 0x65, 0x66, + 0x61, 0x75, 0x6c, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x6f, 0x6e, 0x65, + 0x6f, 0x66, 0x5f, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x18, 0x09, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, + 0x6f, 0x6e, 0x65, 0x6f, 0x66, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x12, 0x1b, 0x0a, 0x09, 0x6a, 0x73, + 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x6a, + 0x73, 0x6f, 0x6e, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x37, 0x0a, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, + 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x12, 0x27, 0x0a, 0x0f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, + 0x6e, 0x61, 0x6c, 0x18, 0x11, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x33, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x22, 0xb6, 0x02, 0x0a, 0x04, 0x54, 0x79, + 0x70, 0x65, 0x12, 0x0f, 0x0a, 0x0b, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x44, 0x4f, 0x55, 0x42, 0x4c, + 0x45, 0x10, 0x01, 0x12, 0x0e, 0x0a, 0x0a, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x46, 0x4c, 0x4f, 0x41, + 0x54, 0x10, 0x02, 0x12, 0x0e, 0x0a, 0x0a, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x49, 0x4e, 0x54, 0x36, + 0x34, 0x10, 0x03, 0x12, 0x0f, 0x0a, 0x0b, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x49, 0x4e, 0x54, + 0x36, 0x34, 0x10, 0x04, 0x12, 0x0e, 0x0a, 0x0a, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x49, 0x4e, 0x54, + 0x33, 0x32, 0x10, 0x05, 0x12, 0x10, 0x0a, 0x0c, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x46, 0x49, 0x58, + 0x45, 0x44, 0x36, 0x34, 0x10, 0x06, 0x12, 0x10, 0x0a, 0x0c, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x46, + 0x49, 0x58, 0x45, 0x44, 0x33, 0x32, 0x10, 0x07, 0x12, 0x0d, 0x0a, 0x09, 0x54, 0x59, 0x50, 0x45, + 0x5f, 0x42, 0x4f, 0x4f, 0x4c, 0x10, 0x08, 0x12, 0x0f, 0x0a, 0x0b, 0x54, 0x59, 0x50, 0x45, 0x5f, + 0x53, 0x54, 0x52, 0x49, 0x4e, 0x47, 0x10, 0x09, 0x12, 0x0e, 0x0a, 0x0a, 0x54, 0x59, 0x50, 0x45, + 0x5f, 0x47, 0x52, 0x4f, 0x55, 0x50, 0x10, 0x0a, 0x12, 0x10, 0x0a, 0x0c, 0x54, 0x59, 0x50, 0x45, + 0x5f, 0x4d, 0x45, 0x53, 0x53, 0x41, 0x47, 0x45, 0x10, 0x0b, 0x12, 0x0e, 0x0a, 0x0a, 0x54, 0x59, + 0x50, 0x45, 0x5f, 0x42, 0x59, 0x54, 0x45, 0x53, 0x10, 0x0c, 0x12, 0x0f, 0x0a, 0x0b, 0x54, 0x59, + 0x50, 0x45, 0x5f, 0x55, 0x49, 0x4e, 0x54, 0x33, 0x32, 0x10, 0x0d, 0x12, 0x0d, 0x0a, 0x09, 0x54, + 0x59, 0x50, 0x45, 0x5f, 0x45, 0x4e, 0x55, 0x4d, 0x10, 0x0e, 0x12, 0x11, 0x0a, 0x0d, 0x54, 0x59, + 0x50, 0x45, 0x5f, 0x53, 0x46, 0x49, 0x58, 0x45, 0x44, 0x33, 0x32, 0x10, 0x0f, 0x12, 0x11, 0x0a, + 0x0d, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x53, 0x46, 0x49, 0x58, 0x45, 0x44, 0x36, 0x34, 0x10, 0x10, + 0x12, 0x0f, 0x0a, 0x0b, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x53, 0x49, 0x4e, 0x54, 0x33, 0x32, 0x10, + 0x11, 0x12, 0x0f, 0x0a, 0x0b, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x53, 0x49, 0x4e, 0x54, 0x36, 0x34, + 0x10, 0x12, 0x22, 0x43, 0x0a, 0x05, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x12, 0x12, 0x0a, 0x0e, 0x4c, + 0x41, 0x42, 0x45, 0x4c, 0x5f, 0x4f, 0x50, 0x54, 0x49, 0x4f, 0x4e, 0x41, 0x4c, 0x10, 0x01, 0x12, + 0x12, 0x0a, 0x0e, 0x4c, 0x41, 0x42, 0x45, 0x4c, 0x5f, 0x52, 0x45, 0x51, 0x55, 0x49, 0x52, 0x45, + 0x44, 0x10, 0x02, 0x12, 0x12, 0x0a, 0x0e, 0x4c, 0x41, 0x42, 0x45, 0x4c, 0x5f, 0x52, 0x45, 0x50, + 0x45, 0x41, 0x54, 0x45, 0x44, 0x10, 0x03, 0x22, 0x63, 0x0a, 0x14, 0x4f, 0x6e, 0x65, 0x6f, 0x66, + 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x12, + 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x12, 0x37, 0x0a, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4f, 0x6e, 0x65, 0x6f, 0x66, 0x4f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x52, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0xe3, 0x02, 0x0a, + 0x13, 0x45, 0x6e, 0x75, 0x6d, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, + 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x3f, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, + 0x65, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6e, 0x75, 0x6d, 0x56, 0x61, + 0x6c, 0x75, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, + 0x74, 0x6f, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x36, 0x0a, 0x07, 0x6f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6e, 0x75, + 0x6d, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x12, 0x5d, 0x0a, 0x0e, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x5f, 0x72, 0x61, + 0x6e, 0x67, 0x65, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x36, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6e, 0x75, 0x6d, + 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, + 0x45, 0x6e, 0x75, 0x6d, 0x52, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x52, 0x61, 0x6e, 0x67, + 0x65, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, + 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x5f, 0x6e, 0x61, 0x6d, + 0x65, 0x18, 0x05, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, + 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x1a, 0x3b, 0x0a, 0x11, 0x45, 0x6e, 0x75, 0x6d, 0x52, 0x65, 0x73, + 0x65, 0x72, 0x76, 0x65, 0x64, 0x52, 0x61, 0x6e, 0x67, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x74, + 0x61, 0x72, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, + 0x12, 0x10, 0x0a, 0x03, 0x65, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x65, + 0x6e, 0x64, 0x22, 0x83, 0x01, 0x0a, 0x18, 0x45, 0x6e, 0x75, 0x6d, 0x56, 0x61, 0x6c, 0x75, 0x65, + 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x12, + 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x05, 0x52, 0x06, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x3b, 0x0a, 0x07, 0x6f, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, + 0x6e, 0x75, 0x6d, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, + 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0xa7, 0x01, 0x0a, 0x16, 0x53, 0x65, 0x72, + 0x76, 0x69, 0x63, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, + 0x6f, 0x74, 0x6f, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x3e, 0x0a, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, + 0x64, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, + 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x52, + 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x12, 0x39, 0x0a, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, + 0x63, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x22, 0x89, 0x02, 0x0a, 0x15, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x44, 0x65, 0x73, + 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x12, 0x0a, 0x04, + 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, + 0x12, 0x1d, 0x0a, 0x0a, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, + 0x1f, 0x0a, 0x0b, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x54, 0x79, 0x70, 0x65, + 0x12, 0x38, 0x0a, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x52, 0x07, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x30, 0x0a, 0x10, 0x63, 0x6c, + 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x18, 0x05, + 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x52, 0x0f, 0x63, 0x6c, 0x69, + 0x65, 0x6e, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x12, 0x30, 0x0a, 0x10, + 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, + 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x52, 0x0f, 0x73, + 0x65, 0x72, 0x76, 0x65, 0x72, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x22, 0x91, + 0x09, 0x0a, 0x0b, 0x46, 0x69, 0x6c, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x21, + 0x0a, 0x0c, 0x6a, 0x61, 0x76, 0x61, 0x5f, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6a, 0x61, 0x76, 0x61, 0x50, 0x61, 0x63, 0x6b, 0x61, 0x67, + 0x65, 0x12, 0x30, 0x0a, 0x14, 0x6a, 0x61, 0x76, 0x61, 0x5f, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x5f, + 0x63, 0x6c, 0x61, 0x73, 0x73, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x12, 0x6a, 0x61, 0x76, 0x61, 0x4f, 0x75, 0x74, 0x65, 0x72, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x6e, + 0x61, 0x6d, 0x65, 0x12, 0x35, 0x0a, 0x13, 0x6a, 0x61, 0x76, 0x61, 0x5f, 0x6d, 0x75, 0x6c, 0x74, + 0x69, 0x70, 0x6c, 0x65, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x08, + 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x52, 0x11, 0x6a, 0x61, 0x76, 0x61, 0x4d, 0x75, 0x6c, + 0x74, 0x69, 0x70, 0x6c, 0x65, 0x46, 0x69, 0x6c, 0x65, 0x73, 0x12, 0x44, 0x0a, 0x1d, 0x6a, 0x61, + 0x76, 0x61, 0x5f, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x5f, 0x65, 0x71, 0x75, 0x61, + 0x6c, 0x73, 0x5f, 0x61, 0x6e, 0x64, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x14, 0x20, 0x01, 0x28, + 0x08, 0x42, 0x02, 0x18, 0x01, 0x52, 0x19, 0x6a, 0x61, 0x76, 0x61, 0x47, 0x65, 0x6e, 0x65, 0x72, + 0x61, 0x74, 0x65, 0x45, 0x71, 0x75, 0x61, 0x6c, 0x73, 0x41, 0x6e, 0x64, 0x48, 0x61, 0x73, 0x68, + 0x12, 0x3a, 0x0a, 0x16, 0x6a, 0x61, 0x76, 0x61, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x5f, + 0x63, 0x68, 0x65, 0x63, 0x6b, 0x5f, 0x75, 0x74, 0x66, 0x38, 0x18, 0x1b, 0x20, 0x01, 0x28, 0x08, + 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x52, 0x13, 0x6a, 0x61, 0x76, 0x61, 0x53, 0x74, 0x72, + 0x69, 0x6e, 0x67, 0x43, 0x68, 0x65, 0x63, 0x6b, 0x55, 0x74, 0x66, 0x38, 0x12, 0x53, 0x0a, 0x0c, + 0x6f, 0x70, 0x74, 0x69, 0x6d, 0x69, 0x7a, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x18, 0x09, 0x20, 0x01, + 0x28, 0x0e, 0x32, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x2e, 0x4f, 0x70, 0x74, 0x69, 0x6d, 0x69, 0x7a, 0x65, 0x4d, 0x6f, 0x64, 0x65, 0x3a, 0x05, 0x53, + 0x50, 0x45, 0x45, 0x44, 0x52, 0x0b, 0x6f, 0x70, 0x74, 0x69, 0x6d, 0x69, 0x7a, 0x65, 0x46, 0x6f, + 0x72, 0x12, 0x1d, 0x0a, 0x0a, 0x67, 0x6f, 0x5f, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x18, + 0x0b, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x67, 0x6f, 0x50, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, + 0x12, 0x35, 0x0a, 0x13, 0x63, 0x63, 0x5f, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x5f, 0x73, + 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x18, 0x10, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, + 0x61, 0x6c, 0x73, 0x65, 0x52, 0x11, 0x63, 0x63, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x53, + 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x12, 0x39, 0x0a, 0x15, 0x6a, 0x61, 0x76, 0x61, 0x5f, + 0x67, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, + 0x18, 0x11, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x52, 0x13, 0x6a, + 0x61, 0x76, 0x61, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x73, 0x12, 0x35, 0x0a, 0x13, 0x70, 0x79, 0x5f, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, + 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x18, 0x12, 0x20, 0x01, 0x28, 0x08, 0x3a, + 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x52, 0x11, 0x70, 0x79, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x69, + 0x63, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x12, 0x37, 0x0a, 0x14, 0x70, 0x68, 0x70, + 0x5f, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, + 0x73, 0x18, 0x2a, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x52, 0x12, + 0x70, 0x68, 0x70, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x69, 0x63, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x73, 0x12, 0x25, 0x0a, 0x0a, 0x64, 0x65, 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, 0x65, 0x64, + 0x18, 0x17, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x52, 0x0a, 0x64, + 0x65, 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, 0x65, 0x64, 0x12, 0x2e, 0x0a, 0x10, 0x63, 0x63, 0x5f, + 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x61, 0x72, 0x65, 0x6e, 0x61, 0x73, 0x18, 0x1f, 0x20, + 0x01, 0x28, 0x08, 0x3a, 0x04, 0x74, 0x72, 0x75, 0x65, 0x52, 0x0e, 0x63, 0x63, 0x45, 0x6e, 0x61, + 0x62, 0x6c, 0x65, 0x41, 0x72, 0x65, 0x6e, 0x61, 0x73, 0x12, 0x2a, 0x0a, 0x11, 0x6f, 0x62, 0x6a, + 0x63, 0x5f, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x5f, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x18, 0x24, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x6f, 0x62, 0x6a, 0x63, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x50, + 0x72, 0x65, 0x66, 0x69, 0x78, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x73, 0x68, 0x61, 0x72, 0x70, 0x5f, + 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x25, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x0f, 0x63, 0x73, 0x68, 0x61, 0x72, 0x70, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, + 0x12, 0x21, 0x0a, 0x0c, 0x73, 0x77, 0x69, 0x66, 0x74, 0x5f, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, + 0x18, 0x27, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x73, 0x77, 0x69, 0x66, 0x74, 0x50, 0x72, 0x65, + 0x66, 0x69, 0x78, 0x12, 0x28, 0x0a, 0x10, 0x70, 0x68, 0x70, 0x5f, 0x63, 0x6c, 0x61, 0x73, 0x73, + 0x5f, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x18, 0x28, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x70, + 0x68, 0x70, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x50, 0x72, 0x65, 0x66, 0x69, 0x78, 0x12, 0x23, 0x0a, + 0x0d, 0x70, 0x68, 0x70, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x29, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x70, 0x68, 0x70, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, + 0x63, 0x65, 0x12, 0x34, 0x0a, 0x16, 0x70, 0x68, 0x70, 0x5f, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, + 0x74, 0x61, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x2c, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x14, 0x70, 0x68, 0x70, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x4e, + 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x72, 0x75, 0x62, 0x79, + 0x5f, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x18, 0x2d, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, + 0x72, 0x75, 0x62, 0x79, 0x50, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x12, 0x58, 0x0a, 0x14, 0x75, + 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x5f, 0x6f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x18, 0xe7, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x6e, 0x69, + 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x52, 0x13, 0x75, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x3a, 0x0a, 0x0c, 0x4f, 0x70, 0x74, 0x69, 0x6d, 0x69, 0x7a, + 0x65, 0x4d, 0x6f, 0x64, 0x65, 0x12, 0x09, 0x0a, 0x05, 0x53, 0x50, 0x45, 0x45, 0x44, 0x10, 0x01, + 0x12, 0x0d, 0x0a, 0x09, 0x43, 0x4f, 0x44, 0x45, 0x5f, 0x53, 0x49, 0x5a, 0x45, 0x10, 0x02, 0x12, + 0x10, 0x0a, 0x0c, 0x4c, 0x49, 0x54, 0x45, 0x5f, 0x52, 0x55, 0x4e, 0x54, 0x49, 0x4d, 0x45, 0x10, + 0x03, 0x2a, 0x09, 0x08, 0xe8, 0x07, 0x10, 0x80, 0x80, 0x80, 0x80, 0x02, 0x4a, 0x04, 0x08, 0x26, + 0x10, 0x27, 0x22, 0xd1, 0x02, 0x0a, 0x0e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x4f, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x3c, 0x0a, 0x17, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, + 0x5f, 0x73, 0x65, 0x74, 0x5f, 0x77, 0x69, 0x72, 0x65, 0x5f, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x52, 0x14, 0x6d, + 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x57, 0x69, 0x72, 0x65, 0x46, 0x6f, 0x72, + 0x6d, 0x61, 0x74, 0x12, 0x4c, 0x0a, 0x1f, 0x6e, 0x6f, 0x5f, 0x73, 0x74, 0x61, 0x6e, 0x64, 0x61, + 0x72, 0x64, 0x5f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x5f, 0x61, 0x63, + 0x63, 0x65, 0x73, 0x73, 0x6f, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, + 0x6c, 0x73, 0x65, 0x52, 0x1c, 0x6e, 0x6f, 0x53, 0x74, 0x61, 0x6e, 0x64, 0x61, 0x72, 0x64, 0x44, + 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x41, 0x63, 0x63, 0x65, 0x73, 0x73, 0x6f, + 0x72, 0x12, 0x25, 0x0a, 0x0a, 0x64, 0x65, 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, 0x65, 0x64, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x52, 0x0a, 0x64, 0x65, + 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, 0x65, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x6d, 0x61, 0x70, 0x5f, + 0x65, 0x6e, 0x74, 0x72, 0x79, 0x18, 0x07, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x6d, 0x61, 0x70, + 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x58, 0x0a, 0x14, 0x75, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, + 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0xe7, 0x07, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, + 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x13, 0x75, 0x6e, 0x69, 0x6e, + 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x2a, + 0x09, 0x08, 0xe8, 0x07, 0x10, 0x80, 0x80, 0x80, 0x80, 0x02, 0x4a, 0x04, 0x08, 0x08, 0x10, 0x09, + 0x4a, 0x04, 0x08, 0x09, 0x10, 0x0a, 0x22, 0xe2, 0x03, 0x0a, 0x0c, 0x46, 0x69, 0x65, 0x6c, 0x64, + 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x41, 0x0a, 0x05, 0x63, 0x74, 0x79, 0x70, 0x65, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x23, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4f, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x43, 0x54, 0x79, 0x70, 0x65, 0x3a, 0x06, 0x53, 0x54, 0x52, + 0x49, 0x4e, 0x47, 0x52, 0x05, 0x63, 0x74, 0x79, 0x70, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x61, + 0x63, 0x6b, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x06, 0x70, 0x61, 0x63, 0x6b, + 0x65, 0x64, 0x12, 0x47, 0x0a, 0x06, 0x6a, 0x73, 0x74, 0x79, 0x70, 0x65, 0x18, 0x06, 0x20, 0x01, + 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x2e, 0x4a, 0x53, 0x54, 0x79, 0x70, 0x65, 0x3a, 0x09, 0x4a, 0x53, 0x5f, 0x4e, 0x4f, 0x52, + 0x4d, 0x41, 0x4c, 0x52, 0x06, 0x6a, 0x73, 0x74, 0x79, 0x70, 0x65, 0x12, 0x19, 0x0a, 0x04, 0x6c, + 0x61, 0x7a, 0x79, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, + 0x52, 0x04, 0x6c, 0x61, 0x7a, 0x79, 0x12, 0x25, 0x0a, 0x0a, 0x64, 0x65, 0x70, 0x72, 0x65, 0x63, + 0x61, 0x74, 0x65, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, + 0x65, 0x52, 0x0a, 0x64, 0x65, 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, 0x65, 0x64, 0x12, 0x19, 0x0a, + 0x04, 0x77, 0x65, 0x61, 0x6b, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, + 0x73, 0x65, 0x52, 0x04, 0x77, 0x65, 0x61, 0x6b, 0x12, 0x58, 0x0a, 0x14, 0x75, 0x6e, 0x69, 0x6e, + 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x18, 0xe7, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x6e, 0x69, 0x6e, 0x74, 0x65, + 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x13, 0x75, + 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x22, 0x2f, 0x0a, 0x05, 0x43, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0a, 0x0a, 0x06, 0x53, + 0x54, 0x52, 0x49, 0x4e, 0x47, 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04, 0x43, 0x4f, 0x52, 0x44, 0x10, + 0x01, 0x12, 0x10, 0x0a, 0x0c, 0x53, 0x54, 0x52, 0x49, 0x4e, 0x47, 0x5f, 0x50, 0x49, 0x45, 0x43, + 0x45, 0x10, 0x02, 0x22, 0x35, 0x0a, 0x06, 0x4a, 0x53, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0d, 0x0a, + 0x09, 0x4a, 0x53, 0x5f, 0x4e, 0x4f, 0x52, 0x4d, 0x41, 0x4c, 0x10, 0x00, 0x12, 0x0d, 0x0a, 0x09, + 0x4a, 0x53, 0x5f, 0x53, 0x54, 0x52, 0x49, 0x4e, 0x47, 0x10, 0x01, 0x12, 0x0d, 0x0a, 0x09, 0x4a, + 0x53, 0x5f, 0x4e, 0x55, 0x4d, 0x42, 0x45, 0x52, 0x10, 0x02, 0x2a, 0x09, 0x08, 0xe8, 0x07, 0x10, + 0x80, 0x80, 0x80, 0x80, 0x02, 0x4a, 0x04, 0x08, 0x04, 0x10, 0x05, 0x22, 0x73, 0x0a, 0x0c, 0x4f, + 0x6e, 0x65, 0x6f, 0x66, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x58, 0x0a, 0x14, 0x75, + 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x5f, 0x6f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x18, 0xe7, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x6e, 0x69, + 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x52, 0x13, 0x75, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x2a, 0x09, 0x08, 0xe8, 0x07, 0x10, 0x80, 0x80, 0x80, 0x80, 0x02, + 0x22, 0xc0, 0x01, 0x0a, 0x0b, 0x45, 0x6e, 0x75, 0x6d, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x12, 0x1f, 0x0a, 0x0b, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x5f, 0x61, 0x6c, 0x69, 0x61, 0x73, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0a, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x41, 0x6c, 0x69, 0x61, + 0x73, 0x12, 0x25, 0x0a, 0x0a, 0x64, 0x65, 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, 0x65, 0x64, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x52, 0x0a, 0x64, 0x65, + 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, 0x65, 0x64, 0x12, 0x58, 0x0a, 0x14, 0x75, 0x6e, 0x69, 0x6e, + 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x18, 0xe7, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x6e, 0x69, 0x6e, 0x74, 0x65, + 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x13, 0x75, + 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x2a, 0x09, 0x08, 0xe8, 0x07, 0x10, 0x80, 0x80, 0x80, 0x80, 0x02, 0x4a, 0x04, 0x08, + 0x05, 0x10, 0x06, 0x22, 0x9e, 0x01, 0x0a, 0x10, 0x45, 0x6e, 0x75, 0x6d, 0x56, 0x61, 0x6c, 0x75, + 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x25, 0x0a, 0x0a, 0x64, 0x65, 0x70, 0x72, + 0x65, 0x63, 0x61, 0x74, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, + 0x6c, 0x73, 0x65, 0x52, 0x0a, 0x64, 0x65, 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, 0x65, 0x64, 0x12, + 0x58, 0x0a, 0x14, 0x75, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, + 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0xe7, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x55, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x13, 0x75, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, + 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x2a, 0x09, 0x08, 0xe8, 0x07, 0x10, 0x80, + 0x80, 0x80, 0x80, 0x02, 0x22, 0x9c, 0x01, 0x0a, 0x0e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, + 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x25, 0x0a, 0x0a, 0x64, 0x65, 0x70, 0x72, 0x65, + 0x63, 0x61, 0x74, 0x65, 0x64, 0x18, 0x21, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, + 0x73, 0x65, 0x52, 0x0a, 0x64, 0x65, 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, 0x65, 0x64, 0x12, 0x58, + 0x0a, 0x14, 0x75, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x5f, + 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0xe7, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x55, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x52, 0x13, 0x75, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, + 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x2a, 0x09, 0x08, 0xe8, 0x07, 0x10, 0x80, 0x80, + 0x80, 0x80, 0x02, 0x22, 0xe0, 0x02, 0x0a, 0x0d, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x4f, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x25, 0x0a, 0x0a, 0x64, 0x65, 0x70, 0x72, 0x65, 0x63, 0x61, + 0x74, 0x65, 0x64, 0x18, 0x21, 0x20, 0x01, 0x28, 0x08, 0x3a, 0x05, 0x66, 0x61, 0x6c, 0x73, 0x65, + 0x52, 0x0a, 0x64, 0x65, 0x70, 0x72, 0x65, 0x63, 0x61, 0x74, 0x65, 0x64, 0x12, 0x71, 0x0a, 0x11, + 0x69, 0x64, 0x65, 0x6d, 0x70, 0x6f, 0x74, 0x65, 0x6e, 0x63, 0x79, 0x5f, 0x6c, 0x65, 0x76, 0x65, + 0x6c, 0x18, 0x22, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, + 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x49, 0x64, 0x65, 0x6d, 0x70, 0x6f, 0x74, 0x65, + 0x6e, 0x63, 0x79, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x3a, 0x13, 0x49, 0x44, 0x45, 0x4d, 0x50, 0x4f, + 0x54, 0x45, 0x4e, 0x43, 0x59, 0x5f, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x52, 0x10, 0x69, + 0x64, 0x65, 0x6d, 0x70, 0x6f, 0x74, 0x65, 0x6e, 0x63, 0x79, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x12, + 0x58, 0x0a, 0x14, 0x75, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, + 0x5f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0xe7, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x55, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x13, 0x75, 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, + 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x50, 0x0a, 0x10, 0x49, 0x64, 0x65, + 0x6d, 0x70, 0x6f, 0x74, 0x65, 0x6e, 0x63, 0x79, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x17, 0x0a, + 0x13, 0x49, 0x44, 0x45, 0x4d, 0x50, 0x4f, 0x54, 0x45, 0x4e, 0x43, 0x59, 0x5f, 0x55, 0x4e, 0x4b, + 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0x00, 0x12, 0x13, 0x0a, 0x0f, 0x4e, 0x4f, 0x5f, 0x53, 0x49, 0x44, + 0x45, 0x5f, 0x45, 0x46, 0x46, 0x45, 0x43, 0x54, 0x53, 0x10, 0x01, 0x12, 0x0e, 0x0a, 0x0a, 0x49, + 0x44, 0x45, 0x4d, 0x50, 0x4f, 0x54, 0x45, 0x4e, 0x54, 0x10, 0x02, 0x2a, 0x09, 0x08, 0xe8, 0x07, + 0x10, 0x80, 0x80, 0x80, 0x80, 0x02, 0x22, 0x9a, 0x03, 0x0a, 0x13, 0x55, 0x6e, 0x69, 0x6e, 0x74, + 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x41, + 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, + 0x6e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x72, 0x65, 0x74, 0x65, 0x64, 0x4f, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x2e, 0x4e, 0x61, 0x6d, 0x65, 0x50, 0x61, 0x72, 0x74, 0x52, 0x04, 0x6e, 0x61, 0x6d, + 0x65, 0x12, 0x29, 0x0a, 0x10, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x5f, + 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x69, 0x64, 0x65, + 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x2c, 0x0a, 0x12, + 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x69, 0x6e, 0x74, 0x5f, 0x76, 0x61, 0x6c, + 0x75, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x10, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, + 0x76, 0x65, 0x49, 0x6e, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x2c, 0x0a, 0x12, 0x6e, 0x65, + 0x67, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x69, 0x6e, 0x74, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x10, 0x6e, 0x65, 0x67, 0x61, 0x74, 0x69, 0x76, 0x65, + 0x49, 0x6e, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x64, 0x6f, 0x75, 0x62, + 0x6c, 0x65, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x01, 0x52, 0x0b, + 0x64, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x73, + 0x74, 0x72, 0x69, 0x6e, 0x67, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, + 0x0c, 0x52, 0x0b, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x27, + 0x0a, 0x0f, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, 0x74, 0x65, 0x5f, 0x76, 0x61, 0x6c, 0x75, + 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x61, 0x67, 0x67, 0x72, 0x65, 0x67, 0x61, + 0x74, 0x65, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x1a, 0x4a, 0x0a, 0x08, 0x4e, 0x61, 0x6d, 0x65, 0x50, + 0x61, 0x72, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x5f, 0x70, 0x61, 0x72, 0x74, + 0x18, 0x01, 0x20, 0x02, 0x28, 0x09, 0x52, 0x08, 0x6e, 0x61, 0x6d, 0x65, 0x50, 0x61, 0x72, 0x74, + 0x12, 0x21, 0x0a, 0x0c, 0x69, 0x73, 0x5f, 0x65, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x6f, 0x6e, + 0x18, 0x02, 0x20, 0x02, 0x28, 0x08, 0x52, 0x0b, 0x69, 0x73, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, + 0x69, 0x6f, 0x6e, 0x22, 0xa7, 0x02, 0x0a, 0x0e, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x43, 0x6f, + 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x44, 0x0a, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x6f, 0x75, 0x72, 0x63, + 0x65, 0x43, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x4c, 0x6f, 0x63, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x52, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x1a, 0xce, 0x01, 0x0a, + 0x08, 0x4c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x04, 0x70, 0x61, 0x74, + 0x68, 0x18, 0x01, 0x20, 0x03, 0x28, 0x05, 0x42, 0x02, 0x10, 0x01, 0x52, 0x04, 0x70, 0x61, 0x74, + 0x68, 0x12, 0x16, 0x0a, 0x04, 0x73, 0x70, 0x61, 0x6e, 0x18, 0x02, 0x20, 0x03, 0x28, 0x05, 0x42, + 0x02, 0x10, 0x01, 0x52, 0x04, 0x73, 0x70, 0x61, 0x6e, 0x12, 0x29, 0x0a, 0x10, 0x6c, 0x65, 0x61, + 0x64, 0x69, 0x6e, 0x67, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x0f, 0x6c, 0x65, 0x61, 0x64, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6d, 0x6d, + 0x65, 0x6e, 0x74, 0x73, 0x12, 0x2b, 0x0a, 0x11, 0x74, 0x72, 0x61, 0x69, 0x6c, 0x69, 0x6e, 0x67, + 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x10, 0x74, 0x72, 0x61, 0x69, 0x6c, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, + 0x73, 0x12, 0x3a, 0x0a, 0x19, 0x6c, 0x65, 0x61, 0x64, 0x69, 0x6e, 0x67, 0x5f, 0x64, 0x65, 0x74, + 0x61, 0x63, 0x68, 0x65, 0x64, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x06, + 0x20, 0x03, 0x28, 0x09, 0x52, 0x17, 0x6c, 0x65, 0x61, 0x64, 0x69, 0x6e, 0x67, 0x44, 0x65, 0x74, + 0x61, 0x63, 0x68, 0x65, 0x64, 0x43, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x22, 0xd1, 0x01, + 0x0a, 0x11, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x64, 0x43, 0x6f, 0x64, 0x65, 0x49, + 0x6e, 0x66, 0x6f, 0x12, 0x4d, 0x0a, 0x0a, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, + 0x74, 0x65, 0x64, 0x43, 0x6f, 0x64, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x2e, 0x41, 0x6e, 0x6e, 0x6f, + 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0a, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x1a, 0x6d, 0x0a, 0x0a, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x12, 0x16, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x03, 0x28, 0x05, 0x42, 0x02, + 0x10, 0x01, 0x52, 0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x1f, 0x0a, 0x0b, 0x73, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x73, + 0x6f, 0x75, 0x72, 0x63, 0x65, 0x46, 0x69, 0x6c, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x65, 0x67, + 0x69, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x62, 0x65, 0x67, 0x69, 0x6e, 0x12, + 0x10, 0x0a, 0x03, 0x65, 0x6e, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x65, 0x6e, + 0x64, 0x42, 0x8f, 0x01, 0x0a, 0x13, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x42, 0x10, 0x44, 0x65, 0x73, 0x63, 0x72, + 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x48, 0x01, 0x5a, 0x3e, 0x67, + 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, + 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, + 0x2d, 0x67, 0x65, 0x6e, 0x2d, 0x67, 0x6f, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, + 0x6f, 0x72, 0x3b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0xf8, 0x01, 0x01, + 0xa2, 0x02, 0x03, 0x47, 0x50, 0x42, 0xaa, 0x02, 0x1a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x52, 0x65, 0x66, 0x6c, 0x65, 0x63, 0x74, + 0x69, 0x6f, 0x6e, +} + +var ( + file_google_protobuf_descriptor_proto_rawDescOnce sync.Once + file_google_protobuf_descriptor_proto_rawDescData = file_google_protobuf_descriptor_proto_rawDesc +) + +func file_google_protobuf_descriptor_proto_rawDescGZIP() []byte { + file_google_protobuf_descriptor_proto_rawDescOnce.Do(func() { + file_google_protobuf_descriptor_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_protobuf_descriptor_proto_rawDescData) + }) + return file_google_protobuf_descriptor_proto_rawDescData +} + +var file_google_protobuf_descriptor_proto_enumTypes = make([]protoimpl.EnumInfo, 6) +var file_google_protobuf_descriptor_proto_msgTypes = make([]protoimpl.MessageInfo, 27) +var file_google_protobuf_descriptor_proto_goTypes = []interface{}{ + (FieldDescriptorProto_Type)(0), // 0: google.protobuf.FieldDescriptorProto.Type + (FieldDescriptorProto_Label)(0), // 1: google.protobuf.FieldDescriptorProto.Label + (FileOptions_OptimizeMode)(0), // 2: google.protobuf.FileOptions.OptimizeMode + (FieldOptions_CType)(0), // 3: google.protobuf.FieldOptions.CType + (FieldOptions_JSType)(0), // 4: google.protobuf.FieldOptions.JSType + (MethodOptions_IdempotencyLevel)(0), // 5: google.protobuf.MethodOptions.IdempotencyLevel + (*FileDescriptorSet)(nil), // 6: google.protobuf.FileDescriptorSet + (*FileDescriptorProto)(nil), // 7: google.protobuf.FileDescriptorProto + (*DescriptorProto)(nil), // 8: google.protobuf.DescriptorProto + (*ExtensionRangeOptions)(nil), // 9: google.protobuf.ExtensionRangeOptions + (*FieldDescriptorProto)(nil), // 10: google.protobuf.FieldDescriptorProto + (*OneofDescriptorProto)(nil), // 11: google.protobuf.OneofDescriptorProto + (*EnumDescriptorProto)(nil), // 12: google.protobuf.EnumDescriptorProto + (*EnumValueDescriptorProto)(nil), // 13: google.protobuf.EnumValueDescriptorProto + (*ServiceDescriptorProto)(nil), // 14: google.protobuf.ServiceDescriptorProto + (*MethodDescriptorProto)(nil), // 15: google.protobuf.MethodDescriptorProto + (*FileOptions)(nil), // 16: google.protobuf.FileOptions + (*MessageOptions)(nil), // 17: google.protobuf.MessageOptions + (*FieldOptions)(nil), // 18: google.protobuf.FieldOptions + (*OneofOptions)(nil), // 19: google.protobuf.OneofOptions + (*EnumOptions)(nil), // 20: google.protobuf.EnumOptions + (*EnumValueOptions)(nil), // 21: google.protobuf.EnumValueOptions + (*ServiceOptions)(nil), // 22: google.protobuf.ServiceOptions + (*MethodOptions)(nil), // 23: google.protobuf.MethodOptions + (*UninterpretedOption)(nil), // 24: google.protobuf.UninterpretedOption + (*SourceCodeInfo)(nil), // 25: google.protobuf.SourceCodeInfo + (*GeneratedCodeInfo)(nil), // 26: google.protobuf.GeneratedCodeInfo + (*DescriptorProto_ExtensionRange)(nil), // 27: google.protobuf.DescriptorProto.ExtensionRange + (*DescriptorProto_ReservedRange)(nil), // 28: google.protobuf.DescriptorProto.ReservedRange + (*EnumDescriptorProto_EnumReservedRange)(nil), // 29: google.protobuf.EnumDescriptorProto.EnumReservedRange + (*UninterpretedOption_NamePart)(nil), // 30: google.protobuf.UninterpretedOption.NamePart + (*SourceCodeInfo_Location)(nil), // 31: google.protobuf.SourceCodeInfo.Location + (*GeneratedCodeInfo_Annotation)(nil), // 32: google.protobuf.GeneratedCodeInfo.Annotation +} +var file_google_protobuf_descriptor_proto_depIdxs = []int32{ + 7, // 0: google.protobuf.FileDescriptorSet.file:type_name -> google.protobuf.FileDescriptorProto + 8, // 1: google.protobuf.FileDescriptorProto.message_type:type_name -> google.protobuf.DescriptorProto + 12, // 2: google.protobuf.FileDescriptorProto.enum_type:type_name -> google.protobuf.EnumDescriptorProto + 14, // 3: google.protobuf.FileDescriptorProto.service:type_name -> google.protobuf.ServiceDescriptorProto + 10, // 4: google.protobuf.FileDescriptorProto.extension:type_name -> google.protobuf.FieldDescriptorProto + 16, // 5: google.protobuf.FileDescriptorProto.options:type_name -> google.protobuf.FileOptions + 25, // 6: google.protobuf.FileDescriptorProto.source_code_info:type_name -> google.protobuf.SourceCodeInfo + 10, // 7: google.protobuf.DescriptorProto.field:type_name -> google.protobuf.FieldDescriptorProto + 10, // 8: google.protobuf.DescriptorProto.extension:type_name -> google.protobuf.FieldDescriptorProto + 8, // 9: google.protobuf.DescriptorProto.nested_type:type_name -> google.protobuf.DescriptorProto + 12, // 10: google.protobuf.DescriptorProto.enum_type:type_name -> google.protobuf.EnumDescriptorProto + 27, // 11: google.protobuf.DescriptorProto.extension_range:type_name -> google.protobuf.DescriptorProto.ExtensionRange + 11, // 12: google.protobuf.DescriptorProto.oneof_decl:type_name -> google.protobuf.OneofDescriptorProto + 17, // 13: google.protobuf.DescriptorProto.options:type_name -> google.protobuf.MessageOptions + 28, // 14: google.protobuf.DescriptorProto.reserved_range:type_name -> google.protobuf.DescriptorProto.ReservedRange + 24, // 15: google.protobuf.ExtensionRangeOptions.uninterpreted_option:type_name -> google.protobuf.UninterpretedOption + 1, // 16: google.protobuf.FieldDescriptorProto.label:type_name -> google.protobuf.FieldDescriptorProto.Label + 0, // 17: google.protobuf.FieldDescriptorProto.type:type_name -> google.protobuf.FieldDescriptorProto.Type + 18, // 18: google.protobuf.FieldDescriptorProto.options:type_name -> google.protobuf.FieldOptions + 19, // 19: google.protobuf.OneofDescriptorProto.options:type_name -> google.protobuf.OneofOptions + 13, // 20: google.protobuf.EnumDescriptorProto.value:type_name -> google.protobuf.EnumValueDescriptorProto + 20, // 21: google.protobuf.EnumDescriptorProto.options:type_name -> google.protobuf.EnumOptions + 29, // 22: google.protobuf.EnumDescriptorProto.reserved_range:type_name -> google.protobuf.EnumDescriptorProto.EnumReservedRange + 21, // 23: google.protobuf.EnumValueDescriptorProto.options:type_name -> google.protobuf.EnumValueOptions + 15, // 24: google.protobuf.ServiceDescriptorProto.method:type_name -> google.protobuf.MethodDescriptorProto + 22, // 25: google.protobuf.ServiceDescriptorProto.options:type_name -> google.protobuf.ServiceOptions + 23, // 26: google.protobuf.MethodDescriptorProto.options:type_name -> google.protobuf.MethodOptions + 2, // 27: google.protobuf.FileOptions.optimize_for:type_name -> google.protobuf.FileOptions.OptimizeMode + 24, // 28: google.protobuf.FileOptions.uninterpreted_option:type_name -> google.protobuf.UninterpretedOption + 24, // 29: google.protobuf.MessageOptions.uninterpreted_option:type_name -> google.protobuf.UninterpretedOption + 3, // 30: google.protobuf.FieldOptions.ctype:type_name -> google.protobuf.FieldOptions.CType + 4, // 31: google.protobuf.FieldOptions.jstype:type_name -> google.protobuf.FieldOptions.JSType + 24, // 32: google.protobuf.FieldOptions.uninterpreted_option:type_name -> google.protobuf.UninterpretedOption + 24, // 33: google.protobuf.OneofOptions.uninterpreted_option:type_name -> google.protobuf.UninterpretedOption + 24, // 34: google.protobuf.EnumOptions.uninterpreted_option:type_name -> google.protobuf.UninterpretedOption + 24, // 35: google.protobuf.EnumValueOptions.uninterpreted_option:type_name -> google.protobuf.UninterpretedOption + 24, // 36: google.protobuf.ServiceOptions.uninterpreted_option:type_name -> google.protobuf.UninterpretedOption + 5, // 37: google.protobuf.MethodOptions.idempotency_level:type_name -> google.protobuf.MethodOptions.IdempotencyLevel + 24, // 38: google.protobuf.MethodOptions.uninterpreted_option:type_name -> google.protobuf.UninterpretedOption + 30, // 39: google.protobuf.UninterpretedOption.name:type_name -> google.protobuf.UninterpretedOption.NamePart + 31, // 40: google.protobuf.SourceCodeInfo.location:type_name -> google.protobuf.SourceCodeInfo.Location + 32, // 41: google.protobuf.GeneratedCodeInfo.annotation:type_name -> google.protobuf.GeneratedCodeInfo.Annotation + 9, // 42: google.protobuf.DescriptorProto.ExtensionRange.options:type_name -> google.protobuf.ExtensionRangeOptions + 43, // [43:43] is the sub-list for method output_type + 43, // [43:43] is the sub-list for method input_type + 43, // [43:43] is the sub-list for extension type_name + 43, // [43:43] is the sub-list for extension extendee + 0, // [0:43] is the sub-list for field type_name +} + +func init() { file_google_protobuf_descriptor_proto_init() } +func file_google_protobuf_descriptor_proto_init() { + if File_google_protobuf_descriptor_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_protobuf_descriptor_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*FileDescriptorSet); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*FileDescriptorProto); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DescriptorProto); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ExtensionRangeOptions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + case 3: + return &v.extensionFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*FieldDescriptorProto); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*OneofDescriptorProto); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*EnumDescriptorProto); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*EnumValueDescriptorProto); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ServiceDescriptorProto); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MethodDescriptorProto); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*FileOptions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + case 3: + return &v.extensionFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MessageOptions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + case 3: + return &v.extensionFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*FieldOptions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + case 3: + return &v.extensionFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*OneofOptions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + case 3: + return &v.extensionFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*EnumOptions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + case 3: + return &v.extensionFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*EnumValueOptions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + case 3: + return &v.extensionFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ServiceOptions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + case 3: + return &v.extensionFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MethodOptions); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + case 3: + return &v.extensionFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*UninterpretedOption); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SourceCodeInfo); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GeneratedCodeInfo); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[21].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DescriptorProto_ExtensionRange); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DescriptorProto_ReservedRange); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*EnumDescriptorProto_EnumReservedRange); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[24].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*UninterpretedOption_NamePart); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SourceCodeInfo_Location); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_descriptor_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GeneratedCodeInfo_Annotation); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_protobuf_descriptor_proto_rawDesc, + NumEnums: 6, + NumMessages: 27, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_protobuf_descriptor_proto_goTypes, + DependencyIndexes: file_google_protobuf_descriptor_proto_depIdxs, + EnumInfos: file_google_protobuf_descriptor_proto_enumTypes, + MessageInfos: file_google_protobuf_descriptor_proto_msgTypes, + }.Build() + File_google_protobuf_descriptor_proto = out.File + file_google_protobuf_descriptor_proto_rawDesc = nil + file_google_protobuf_descriptor_proto_goTypes = nil + file_google_protobuf_descriptor_proto_depIdxs = nil +} diff --git a/vendor/google.golang.org/protobuf/types/known/anypb/any.pb.go b/vendor/google.golang.org/protobuf/types/known/anypb/any.pb.go new file mode 100644 index 00000000000..82a473e2652 --- /dev/null +++ b/vendor/google.golang.org/protobuf/types/known/anypb/any.pb.go @@ -0,0 +1,494 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: google/protobuf/any.proto + +// Package anypb contains generated types for google/protobuf/any.proto. +// +// The Any message is a dynamic representation of any other message value. +// It is functionally a tuple of the full name of the remote message type and +// the serialized bytes of the remote message value. +// +// +// Constructing an Any +// +// An Any message containing another message value is constructed using New: +// +// any, err := anypb.New(m) +// if err != nil { +// ... // handle error +// } +// ... // make use of any +// +// +// Unmarshaling an Any +// +// With a populated Any message, the underlying message can be serialized into +// a remote concrete message value in a few ways. +// +// If the exact concrete type is known, then a new (or pre-existing) instance +// of that message can be passed to the UnmarshalTo method: +// +// m := new(foopb.MyMessage) +// if err := any.UnmarshalTo(m); err != nil { +// ... // handle error +// } +// ... // make use of m +// +// If the exact concrete type is not known, then the UnmarshalNew method can be +// used to unmarshal the contents into a new instance of the remote message type: +// +// m, err := any.UnmarshalNew() +// if err != nil { +// ... // handle error +// } +// ... // make use of m +// +// UnmarshalNew uses the global type registry to resolve the message type and +// construct a new instance of that message to unmarshal into. In order for a +// message type to appear in the global registry, the Go type representing that +// protobuf message type must be linked into the Go binary. For messages +// generated by protoc-gen-go, this is achieved through an import of the +// generated Go package representing a .proto file. +// +// A common pattern with UnmarshalNew is to use a type switch with the resulting +// proto.Message value: +// +// switch m := m.(type) { +// case *foopb.MyMessage: +// ... // make use of m as a *foopb.MyMessage +// case *barpb.OtherMessage: +// ... // make use of m as a *barpb.OtherMessage +// case *bazpb.SomeMessage: +// ... // make use of m as a *bazpb.SomeMessage +// } +// +// This pattern ensures that the generated packages containing the message types +// listed in the case clauses are linked into the Go binary and therefore also +// registered in the global registry. +// +// +// Type checking an Any +// +// In order to type check whether an Any message represents some other message, +// then use the MessageIs method: +// +// if any.MessageIs((*foopb.MyMessage)(nil)) { +// ... // make use of any, knowing that it contains a foopb.MyMessage +// } +// +// The MessageIs method can also be used with an allocated instance of the target +// message type if the intention is to unmarshal into it if the type matches: +// +// m := new(foopb.MyMessage) +// if any.MessageIs(m) { +// if err := any.UnmarshalTo(m); err != nil { +// ... // handle error +// } +// ... // make use of m +// } +// +package anypb + +import ( + proto "google.golang.org/protobuf/proto" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoregistry "google.golang.org/protobuf/reflect/protoregistry" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + strings "strings" + sync "sync" +) + +// `Any` contains an arbitrary serialized protocol buffer message along with a +// URL that describes the type of the serialized message. +// +// Protobuf library provides support to pack/unpack Any values in the form +// of utility functions or additional generated methods of the Any type. +// +// Example 1: Pack and unpack a message in C++. +// +// Foo foo = ...; +// Any any; +// any.PackFrom(foo); +// ... +// if (any.UnpackTo(&foo)) { +// ... +// } +// +// Example 2: Pack and unpack a message in Java. +// +// Foo foo = ...; +// Any any = Any.pack(foo); +// ... +// if (any.is(Foo.class)) { +// foo = any.unpack(Foo.class); +// } +// +// Example 3: Pack and unpack a message in Python. +// +// foo = Foo(...) +// any = Any() +// any.Pack(foo) +// ... +// if any.Is(Foo.DESCRIPTOR): +// any.Unpack(foo) +// ... +// +// Example 4: Pack and unpack a message in Go +// +// foo := &pb.Foo{...} +// any, err := ptypes.MarshalAny(foo) +// ... +// foo := &pb.Foo{} +// if err := ptypes.UnmarshalAny(any, foo); err != nil { +// ... +// } +// +// The pack methods provided by protobuf library will by default use +// 'type.googleapis.com/full.type.name' as the type URL and the unpack +// methods only use the fully qualified type name after the last '/' +// in the type URL, for example "foo.bar.com/x/y.z" will yield type +// name "y.z". +// +// +// JSON +// ==== +// The JSON representation of an `Any` value uses the regular +// representation of the deserialized, embedded message, with an +// additional field `@type` which contains the type URL. Example: +// +// package google.profile; +// message Person { +// string first_name = 1; +// string last_name = 2; +// } +// +// { +// "@type": "type.googleapis.com/google.profile.Person", +// "firstName": , +// "lastName": +// } +// +// If the embedded message type is well-known and has a custom JSON +// representation, that representation will be embedded adding a field +// `value` which holds the custom JSON in addition to the `@type` +// field. Example (for message [google.protobuf.Duration][]): +// +// { +// "@type": "type.googleapis.com/google.protobuf.Duration", +// "value": "1.212s" +// } +// +type Any struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // A URL/resource name that uniquely identifies the type of the serialized + // protocol buffer message. This string must contain at least + // one "/" character. The last segment of the URL's path must represent + // the fully qualified name of the type (as in + // `path/google.protobuf.Duration`). The name should be in a canonical form + // (e.g., leading "." is not accepted). + // + // In practice, teams usually precompile into the binary all types that they + // expect it to use in the context of Any. However, for URLs which use the + // scheme `http`, `https`, or no scheme, one can optionally set up a type + // server that maps type URLs to message definitions as follows: + // + // * If no scheme is provided, `https` is assumed. + // * An HTTP GET on the URL must yield a [google.protobuf.Type][] + // value in binary format, or produce an error. + // * Applications are allowed to cache lookup results based on the + // URL, or have them precompiled into a binary to avoid any + // lookup. Therefore, binary compatibility needs to be preserved + // on changes to types. (Use versioned type names to manage + // breaking changes.) + // + // Note: this functionality is not currently available in the official + // protobuf release, and it is not used for type URLs beginning with + // type.googleapis.com. + // + // Schemes other than `http`, `https` (or the empty scheme) might be + // used with implementation specific semantics. + // + TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"` + // Must be a valid serialized protocol buffer of the above specified type. + Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` +} + +// New marshals src into a new Any instance. +func New(src proto.Message) (*Any, error) { + dst := new(Any) + if err := dst.MarshalFrom(src); err != nil { + return nil, err + } + return dst, nil +} + +// MarshalFrom marshals src into dst as the underlying message +// using the provided marshal options. +// +// If no options are specified, call dst.MarshalFrom instead. +func MarshalFrom(dst *Any, src proto.Message, opts proto.MarshalOptions) error { + const urlPrefix = "type.googleapis.com/" + if src == nil { + return protoimpl.X.NewError("invalid nil source message") + } + b, err := opts.Marshal(src) + if err != nil { + return err + } + dst.TypeUrl = urlPrefix + string(src.ProtoReflect().Descriptor().FullName()) + dst.Value = b + return nil +} + +// UnmarshalTo unmarshals the underlying message from src into dst +// using the provided unmarshal options. +// It reports an error if dst is not of the right message type. +// +// If no options are specified, call src.UnmarshalTo instead. +func UnmarshalTo(src *Any, dst proto.Message, opts proto.UnmarshalOptions) error { + if src == nil { + return protoimpl.X.NewError("invalid nil source message") + } + if !src.MessageIs(dst) { + got := dst.ProtoReflect().Descriptor().FullName() + want := src.MessageName() + return protoimpl.X.NewError("mismatched message type: got %q, want %q", got, want) + } + return opts.Unmarshal(src.GetValue(), dst) +} + +// UnmarshalNew unmarshals the underlying message from src into dst, +// which is newly created message using a type resolved from the type URL. +// The message type is resolved according to opt.Resolver, +// which should implement protoregistry.MessageTypeResolver. +// It reports an error if the underlying message type could not be resolved. +// +// If no options are specified, call src.UnmarshalNew instead. +func UnmarshalNew(src *Any, opts proto.UnmarshalOptions) (dst proto.Message, err error) { + if src.GetTypeUrl() == "" { + return nil, protoimpl.X.NewError("invalid empty type URL") + } + if opts.Resolver == nil { + opts.Resolver = protoregistry.GlobalTypes + } + r, ok := opts.Resolver.(protoregistry.MessageTypeResolver) + if !ok { + return nil, protoregistry.NotFound + } + mt, err := r.FindMessageByURL(src.GetTypeUrl()) + if err != nil { + if err == protoregistry.NotFound { + return nil, err + } + return nil, protoimpl.X.NewError("could not resolve %q: %v", src.GetTypeUrl(), err) + } + dst = mt.New().Interface() + return dst, opts.Unmarshal(src.GetValue(), dst) +} + +// MessageIs reports whether the underlying message is of the same type as m. +func (x *Any) MessageIs(m proto.Message) bool { + if m == nil { + return false + } + url := x.GetTypeUrl() + name := string(m.ProtoReflect().Descriptor().FullName()) + if !strings.HasSuffix(url, name) { + return false + } + return len(url) == len(name) || url[len(url)-len(name)-1] == '/' +} + +// MessageName reports the full name of the underlying message, +// returning an empty string if invalid. +func (x *Any) MessageName() protoreflect.FullName { + url := x.GetTypeUrl() + name := protoreflect.FullName(url) + if i := strings.LastIndexByte(url, '/'); i >= 0 { + name = name[i+len("/"):] + } + if !name.IsValid() { + return "" + } + return name +} + +// MarshalFrom marshals m into x as the underlying message. +func (x *Any) MarshalFrom(m proto.Message) error { + return MarshalFrom(x, m, proto.MarshalOptions{}) +} + +// UnmarshalTo unmarshals the contents of the underlying message of x into m. +// It resets m before performing the unmarshal operation. +// It reports an error if m is not of the right message type. +func (x *Any) UnmarshalTo(m proto.Message) error { + return UnmarshalTo(x, m, proto.UnmarshalOptions{}) +} + +// UnmarshalNew unmarshals the contents of the underlying message of x into +// a newly allocated message of the specified type. +// It reports an error if the underlying message type could not be resolved. +func (x *Any) UnmarshalNew() (proto.Message, error) { + return UnmarshalNew(x, proto.UnmarshalOptions{}) +} + +func (x *Any) Reset() { + *x = Any{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_any_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Any) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Any) ProtoMessage() {} + +func (x *Any) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_any_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Any.ProtoReflect.Descriptor instead. +func (*Any) Descriptor() ([]byte, []int) { + return file_google_protobuf_any_proto_rawDescGZIP(), []int{0} +} + +func (x *Any) GetTypeUrl() string { + if x != nil { + return x.TypeUrl + } + return "" +} + +func (x *Any) GetValue() []byte { + if x != nil { + return x.Value + } + return nil +} + +var File_google_protobuf_any_proto protoreflect.FileDescriptor + +var file_google_protobuf_any_proto_rawDesc = []byte{ + 0x0a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0f, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x22, 0x36, 0x0a, 0x03, + 0x41, 0x6e, 0x79, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x79, 0x70, 0x65, 0x5f, 0x75, 0x72, 0x6c, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x74, 0x79, 0x70, 0x65, 0x55, 0x72, 0x6c, 0x12, 0x14, + 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x76, + 0x61, 0x6c, 0x75, 0x65, 0x42, 0x6f, 0x0a, 0x13, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x42, 0x08, 0x41, 0x6e, 0x79, + 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x25, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, + 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x61, 0x6e, 0x79, 0xa2, 0x02, + 0x03, 0x47, 0x50, 0x42, 0xaa, 0x02, 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x50, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x57, 0x65, 0x6c, 0x6c, 0x4b, 0x6e, 0x6f, 0x77, 0x6e, + 0x54, 0x79, 0x70, 0x65, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_google_protobuf_any_proto_rawDescOnce sync.Once + file_google_protobuf_any_proto_rawDescData = file_google_protobuf_any_proto_rawDesc +) + +func file_google_protobuf_any_proto_rawDescGZIP() []byte { + file_google_protobuf_any_proto_rawDescOnce.Do(func() { + file_google_protobuf_any_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_protobuf_any_proto_rawDescData) + }) + return file_google_protobuf_any_proto_rawDescData +} + +var file_google_protobuf_any_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_google_protobuf_any_proto_goTypes = []interface{}{ + (*Any)(nil), // 0: google.protobuf.Any +} +var file_google_protobuf_any_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_google_protobuf_any_proto_init() } +func file_google_protobuf_any_proto_init() { + if File_google_protobuf_any_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_protobuf_any_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Any); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_protobuf_any_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_protobuf_any_proto_goTypes, + DependencyIndexes: file_google_protobuf_any_proto_depIdxs, + MessageInfos: file_google_protobuf_any_proto_msgTypes, + }.Build() + File_google_protobuf_any_proto = out.File + file_google_protobuf_any_proto_rawDesc = nil + file_google_protobuf_any_proto_goTypes = nil + file_google_protobuf_any_proto_depIdxs = nil +} diff --git a/vendor/google.golang.org/protobuf/types/known/durationpb/duration.pb.go b/vendor/google.golang.org/protobuf/types/known/durationpb/duration.pb.go new file mode 100644 index 00000000000..f7a11099404 --- /dev/null +++ b/vendor/google.golang.org/protobuf/types/known/durationpb/duration.pb.go @@ -0,0 +1,379 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: google/protobuf/duration.proto + +// Package durationpb contains generated types for google/protobuf/duration.proto. +// +// The Duration message represents a signed span of time. +// +// +// Conversion to a Go Duration +// +// The AsDuration method can be used to convert a Duration message to a +// standard Go time.Duration value: +// +// d := dur.AsDuration() +// ... // make use of d as a time.Duration +// +// Converting to a time.Duration is a common operation so that the extensive +// set of time-based operations provided by the time package can be leveraged. +// See https://golang.org/pkg/time for more information. +// +// The AsDuration method performs the conversion on a best-effort basis. +// Durations with denormal values (e.g., nanoseconds beyond -99999999 and +// +99999999, inclusive; or seconds and nanoseconds with opposite signs) +// are normalized during the conversion to a time.Duration. To manually check for +// invalid Duration per the documented limitations in duration.proto, +// additionally call the CheckValid method: +// +// if err := dur.CheckValid(); err != nil { +// ... // handle error +// } +// +// Note that the documented limitations in duration.proto does not protect a +// Duration from overflowing the representable range of a time.Duration in Go. +// The AsDuration method uses saturation arithmetic such that an overflow clamps +// the resulting value to the closest representable value (e.g., math.MaxInt64 +// for positive overflow and math.MinInt64 for negative overflow). +// +// +// Conversion from a Go Duration +// +// The durationpb.New function can be used to construct a Duration message +// from a standard Go time.Duration value: +// +// dur := durationpb.New(d) +// ... // make use of d as a *durationpb.Duration +// +package durationpb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + math "math" + reflect "reflect" + sync "sync" + time "time" +) + +// A Duration represents a signed, fixed-length span of time represented +// as a count of seconds and fractions of seconds at nanosecond +// resolution. It is independent of any calendar and concepts like "day" +// or "month". It is related to Timestamp in that the difference between +// two Timestamp values is a Duration and it can be added or subtracted +// from a Timestamp. Range is approximately +-10,000 years. +// +// # Examples +// +// Example 1: Compute Duration from two Timestamps in pseudo code. +// +// Timestamp start = ...; +// Timestamp end = ...; +// Duration duration = ...; +// +// duration.seconds = end.seconds - start.seconds; +// duration.nanos = end.nanos - start.nanos; +// +// if (duration.seconds < 0 && duration.nanos > 0) { +// duration.seconds += 1; +// duration.nanos -= 1000000000; +// } else if (duration.seconds > 0 && duration.nanos < 0) { +// duration.seconds -= 1; +// duration.nanos += 1000000000; +// } +// +// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. +// +// Timestamp start = ...; +// Duration duration = ...; +// Timestamp end = ...; +// +// end.seconds = start.seconds + duration.seconds; +// end.nanos = start.nanos + duration.nanos; +// +// if (end.nanos < 0) { +// end.seconds -= 1; +// end.nanos += 1000000000; +// } else if (end.nanos >= 1000000000) { +// end.seconds += 1; +// end.nanos -= 1000000000; +// } +// +// Example 3: Compute Duration from datetime.timedelta in Python. +// +// td = datetime.timedelta(days=3, minutes=10) +// duration = Duration() +// duration.FromTimedelta(td) +// +// # JSON Mapping +// +// In JSON format, the Duration type is encoded as a string rather than an +// object, where the string ends in the suffix "s" (indicating seconds) and +// is preceded by the number of seconds, with nanoseconds expressed as +// fractional seconds. For example, 3 seconds with 0 nanoseconds should be +// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should +// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 +// microsecond should be expressed in JSON format as "3.000001s". +// +// +type Duration struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Signed seconds of the span of time. Must be from -315,576,000,000 + // to +315,576,000,000 inclusive. Note: these bounds are computed from: + // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years + Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` + // Signed fractions of a second at nanosecond resolution of the span + // of time. Durations less than one second are represented with a 0 + // `seconds` field and a positive or negative `nanos` field. For durations + // of one second or more, a non-zero value for the `nanos` field must be + // of the same sign as the `seconds` field. Must be from -999,999,999 + // to +999,999,999 inclusive. + Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` +} + +// New constructs a new Duration from the provided time.Duration. +func New(d time.Duration) *Duration { + nanos := d.Nanoseconds() + secs := nanos / 1e9 + nanos -= secs * 1e9 + return &Duration{Seconds: int64(secs), Nanos: int32(nanos)} +} + +// AsDuration converts x to a time.Duration, +// returning the closest duration value in the event of overflow. +func (x *Duration) AsDuration() time.Duration { + secs := x.GetSeconds() + nanos := x.GetNanos() + d := time.Duration(secs) * time.Second + overflow := d/time.Second != time.Duration(secs) + d += time.Duration(nanos) * time.Nanosecond + overflow = overflow || (secs < 0 && nanos < 0 && d > 0) + overflow = overflow || (secs > 0 && nanos > 0 && d < 0) + if overflow { + switch { + case secs < 0: + return time.Duration(math.MinInt64) + case secs > 0: + return time.Duration(math.MaxInt64) + } + } + return d +} + +// IsValid reports whether the duration is valid. +// It is equivalent to CheckValid == nil. +func (x *Duration) IsValid() bool { + return x.check() == 0 +} + +// CheckValid returns an error if the duration is invalid. +// In particular, it checks whether the value is within the range of +// -10000 years to +10000 years inclusive. +// An error is reported for a nil Duration. +func (x *Duration) CheckValid() error { + switch x.check() { + case invalidNil: + return protoimpl.X.NewError("invalid nil Duration") + case invalidUnderflow: + return protoimpl.X.NewError("duration (%v) exceeds -10000 years", x) + case invalidOverflow: + return protoimpl.X.NewError("duration (%v) exceeds +10000 years", x) + case invalidNanosRange: + return protoimpl.X.NewError("duration (%v) has out-of-range nanos", x) + case invalidNanosSign: + return protoimpl.X.NewError("duration (%v) has seconds and nanos with different signs", x) + default: + return nil + } +} + +const ( + _ = iota + invalidNil + invalidUnderflow + invalidOverflow + invalidNanosRange + invalidNanosSign +) + +func (x *Duration) check() uint { + const absDuration = 315576000000 // 10000yr * 365.25day/yr * 24hr/day * 60min/hr * 60sec/min + secs := x.GetSeconds() + nanos := x.GetNanos() + switch { + case x == nil: + return invalidNil + case secs < -absDuration: + return invalidUnderflow + case secs > +absDuration: + return invalidOverflow + case nanos <= -1e9 || nanos >= +1e9: + return invalidNanosRange + case (secs > 0 && nanos < 0) || (secs < 0 && nanos > 0): + return invalidNanosSign + default: + return 0 + } +} + +func (x *Duration) Reset() { + *x = Duration{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_duration_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Duration) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Duration) ProtoMessage() {} + +func (x *Duration) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_duration_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Duration.ProtoReflect.Descriptor instead. +func (*Duration) Descriptor() ([]byte, []int) { + return file_google_protobuf_duration_proto_rawDescGZIP(), []int{0} +} + +func (x *Duration) GetSeconds() int64 { + if x != nil { + return x.Seconds + } + return 0 +} + +func (x *Duration) GetNanos() int32 { + if x != nil { + return x.Nanos + } + return 0 +} + +var File_google_protobuf_duration_proto protoreflect.FileDescriptor + +var file_google_protobuf_duration_proto_rawDesc = []byte{ + 0x0a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x12, 0x0f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x22, 0x3a, 0x0a, 0x08, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, + 0x07, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, + 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x6e, 0x61, 0x6e, 0x6f, 0x73, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x6e, 0x61, 0x6e, 0x6f, 0x73, 0x42, 0x7c, 0x0a, + 0x13, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x42, 0x0d, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x72, + 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2a, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, + 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x03, 0x47, 0x50, 0x42, 0xaa, 0x02, 0x1e, 0x47, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x57, 0x65, 0x6c, + 0x6c, 0x4b, 0x6e, 0x6f, 0x77, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, +} + +var ( + file_google_protobuf_duration_proto_rawDescOnce sync.Once + file_google_protobuf_duration_proto_rawDescData = file_google_protobuf_duration_proto_rawDesc +) + +func file_google_protobuf_duration_proto_rawDescGZIP() []byte { + file_google_protobuf_duration_proto_rawDescOnce.Do(func() { + file_google_protobuf_duration_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_protobuf_duration_proto_rawDescData) + }) + return file_google_protobuf_duration_proto_rawDescData +} + +var file_google_protobuf_duration_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_google_protobuf_duration_proto_goTypes = []interface{}{ + (*Duration)(nil), // 0: google.protobuf.Duration +} +var file_google_protobuf_duration_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_google_protobuf_duration_proto_init() } +func file_google_protobuf_duration_proto_init() { + if File_google_protobuf_duration_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_protobuf_duration_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Duration); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_protobuf_duration_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_protobuf_duration_proto_goTypes, + DependencyIndexes: file_google_protobuf_duration_proto_depIdxs, + MessageInfos: file_google_protobuf_duration_proto_msgTypes, + }.Build() + File_google_protobuf_duration_proto = out.File + file_google_protobuf_duration_proto_rawDesc = nil + file_google_protobuf_duration_proto_goTypes = nil + file_google_protobuf_duration_proto_depIdxs = nil +} diff --git a/vendor/google.golang.org/protobuf/types/known/emptypb/empty.pb.go b/vendor/google.golang.org/protobuf/types/known/emptypb/empty.pb.go new file mode 100644 index 00000000000..32a583df544 --- /dev/null +++ b/vendor/google.golang.org/protobuf/types/known/emptypb/empty.pb.go @@ -0,0 +1,168 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: google/protobuf/empty.proto + +package emptypb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +// A generic empty message that you can re-use to avoid defining duplicated +// empty messages in your APIs. A typical example is to use it as the request +// or the response type of an API method. For instance: +// +// service Foo { +// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); +// } +// +// The JSON representation for `Empty` is empty JSON object `{}`. +type Empty struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *Empty) Reset() { + *x = Empty{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_empty_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Empty) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Empty) ProtoMessage() {} + +func (x *Empty) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_empty_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Empty.ProtoReflect.Descriptor instead. +func (*Empty) Descriptor() ([]byte, []int) { + return file_google_protobuf_empty_proto_rawDescGZIP(), []int{0} +} + +var File_google_protobuf_empty_proto protoreflect.FileDescriptor + +var file_google_protobuf_empty_proto_rawDesc = []byte{ + 0x0a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0f, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x22, 0x07, + 0x0a, 0x05, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x42, 0x76, 0x0a, 0x13, 0x63, 0x6f, 0x6d, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x42, 0x0a, + 0x45, 0x6d, 0x70, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x27, 0x67, 0x69, + 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, + 0x65, 0x6d, 0x70, 0x74, 0x79, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x03, 0x47, 0x50, 0x42, 0xaa, 0x02, + 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x57, 0x65, 0x6c, 0x6c, 0x4b, 0x6e, 0x6f, 0x77, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x73, 0x62, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_google_protobuf_empty_proto_rawDescOnce sync.Once + file_google_protobuf_empty_proto_rawDescData = file_google_protobuf_empty_proto_rawDesc +) + +func file_google_protobuf_empty_proto_rawDescGZIP() []byte { + file_google_protobuf_empty_proto_rawDescOnce.Do(func() { + file_google_protobuf_empty_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_protobuf_empty_proto_rawDescData) + }) + return file_google_protobuf_empty_proto_rawDescData +} + +var file_google_protobuf_empty_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_google_protobuf_empty_proto_goTypes = []interface{}{ + (*Empty)(nil), // 0: google.protobuf.Empty +} +var file_google_protobuf_empty_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_google_protobuf_empty_proto_init() } +func file_google_protobuf_empty_proto_init() { + if File_google_protobuf_empty_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_protobuf_empty_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Empty); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_protobuf_empty_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_protobuf_empty_proto_goTypes, + DependencyIndexes: file_google_protobuf_empty_proto_depIdxs, + MessageInfos: file_google_protobuf_empty_proto_msgTypes, + }.Build() + File_google_protobuf_empty_proto = out.File + file_google_protobuf_empty_proto_rawDesc = nil + file_google_protobuf_empty_proto_goTypes = nil + file_google_protobuf_empty_proto_depIdxs = nil +} diff --git a/vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go b/vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go new file mode 100644 index 00000000000..c25e4bd7d0d --- /dev/null +++ b/vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go @@ -0,0 +1,381 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: google/protobuf/timestamp.proto + +// Package timestamppb contains generated types for google/protobuf/timestamp.proto. +// +// The Timestamp message represents a timestamp, +// an instant in time since the Unix epoch (January 1st, 1970). +// +// +// Conversion to a Go Time +// +// The AsTime method can be used to convert a Timestamp message to a +// standard Go time.Time value in UTC: +// +// t := ts.AsTime() +// ... // make use of t as a time.Time +// +// Converting to a time.Time is a common operation so that the extensive +// set of time-based operations provided by the time package can be leveraged. +// See https://golang.org/pkg/time for more information. +// +// The AsTime method performs the conversion on a best-effort basis. Timestamps +// with denormal values (e.g., nanoseconds beyond 0 and 99999999, inclusive) +// are normalized during the conversion to a time.Time. To manually check for +// invalid Timestamps per the documented limitations in timestamp.proto, +// additionally call the CheckValid method: +// +// if err := ts.CheckValid(); err != nil { +// ... // handle error +// } +// +// +// Conversion from a Go Time +// +// The timestamppb.New function can be used to construct a Timestamp message +// from a standard Go time.Time value: +// +// ts := timestamppb.New(t) +// ... // make use of ts as a *timestamppb.Timestamp +// +// In order to construct a Timestamp representing the current time, use Now: +// +// ts := timestamppb.Now() +// ... // make use of ts as a *timestamppb.Timestamp +// +package timestamppb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + time "time" +) + +// A Timestamp represents a point in time independent of any time zone or local +// calendar, encoded as a count of seconds and fractions of seconds at +// nanosecond resolution. The count is relative to an epoch at UTC midnight on +// January 1, 1970, in the proleptic Gregorian calendar which extends the +// Gregorian calendar backwards to year one. +// +// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap +// second table is needed for interpretation, using a [24-hour linear +// smear](https://developers.google.com/time/smear). +// +// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By +// restricting to that range, we ensure that we can convert to and from [RFC +// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. +// +// # Examples +// +// Example 1: Compute Timestamp from POSIX `time()`. +// +// Timestamp timestamp; +// timestamp.set_seconds(time(NULL)); +// timestamp.set_nanos(0); +// +// Example 2: Compute Timestamp from POSIX `gettimeofday()`. +// +// struct timeval tv; +// gettimeofday(&tv, NULL); +// +// Timestamp timestamp; +// timestamp.set_seconds(tv.tv_sec); +// timestamp.set_nanos(tv.tv_usec * 1000); +// +// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. +// +// FILETIME ft; +// GetSystemTimeAsFileTime(&ft); +// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; +// +// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z +// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. +// Timestamp timestamp; +// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); +// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); +// +// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. +// +// long millis = System.currentTimeMillis(); +// +// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) +// .setNanos((int) ((millis % 1000) * 1000000)).build(); +// +// +// Example 5: Compute Timestamp from current time in Python. +// +// timestamp = Timestamp() +// timestamp.GetCurrentTime() +// +// # JSON Mapping +// +// In JSON format, the Timestamp type is encoded as a string in the +// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the +// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" +// where {year} is always expressed using four digits while {month}, {day}, +// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional +// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), +// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone +// is required. A proto3 JSON serializer should always use UTC (as indicated by +// "Z") when printing the Timestamp type and a proto3 JSON parser should be +// able to accept both UTC and other timezones (as indicated by an offset). +// +// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past +// 01:30 UTC on January 15, 2017. +// +// In JavaScript, one can convert a Date object to this format using the +// standard +// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) +// method. In Python, a standard `datetime.datetime` object can be converted +// to this format using +// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with +// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use +// the Joda Time's [`ISODateTimeFormat.dateTime()`]( +// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D +// ) to obtain a formatter capable of generating timestamps in this format. +// +// +type Timestamp struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Represents seconds of UTC time since Unix epoch + // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + // 9999-12-31T23:59:59Z inclusive. + Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` + // Non-negative fractions of a second at nanosecond resolution. Negative + // second values with fractions must still have non-negative nanos values + // that count forward in time. Must be from 0 to 999,999,999 + // inclusive. + Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` +} + +// Now constructs a new Timestamp from the current time. +func Now() *Timestamp { + return New(time.Now()) +} + +// New constructs a new Timestamp from the provided time.Time. +func New(t time.Time) *Timestamp { + return &Timestamp{Seconds: int64(t.Unix()), Nanos: int32(t.Nanosecond())} +} + +// AsTime converts x to a time.Time. +func (x *Timestamp) AsTime() time.Time { + return time.Unix(int64(x.GetSeconds()), int64(x.GetNanos())).UTC() +} + +// IsValid reports whether the timestamp is valid. +// It is equivalent to CheckValid == nil. +func (x *Timestamp) IsValid() bool { + return x.check() == 0 +} + +// CheckValid returns an error if the timestamp is invalid. +// In particular, it checks whether the value represents a date that is +// in the range of 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive. +// An error is reported for a nil Timestamp. +func (x *Timestamp) CheckValid() error { + switch x.check() { + case invalidNil: + return protoimpl.X.NewError("invalid nil Timestamp") + case invalidUnderflow: + return protoimpl.X.NewError("timestamp (%v) before 0001-01-01", x) + case invalidOverflow: + return protoimpl.X.NewError("timestamp (%v) after 9999-12-31", x) + case invalidNanos: + return protoimpl.X.NewError("timestamp (%v) has out-of-range nanos", x) + default: + return nil + } +} + +const ( + _ = iota + invalidNil + invalidUnderflow + invalidOverflow + invalidNanos +) + +func (x *Timestamp) check() uint { + const minTimestamp = -62135596800 // Seconds between 1970-01-01T00:00:00Z and 0001-01-01T00:00:00Z, inclusive + const maxTimestamp = +253402300799 // Seconds between 1970-01-01T00:00:00Z and 9999-12-31T23:59:59Z, inclusive + secs := x.GetSeconds() + nanos := x.GetNanos() + switch { + case x == nil: + return invalidNil + case secs < minTimestamp: + return invalidUnderflow + case secs > maxTimestamp: + return invalidOverflow + case nanos < 0 || nanos >= 1e9: + return invalidNanos + default: + return 0 + } +} + +func (x *Timestamp) Reset() { + *x = Timestamp{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_timestamp_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Timestamp) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Timestamp) ProtoMessage() {} + +func (x *Timestamp) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_timestamp_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Timestamp.ProtoReflect.Descriptor instead. +func (*Timestamp) Descriptor() ([]byte, []int) { + return file_google_protobuf_timestamp_proto_rawDescGZIP(), []int{0} +} + +func (x *Timestamp) GetSeconds() int64 { + if x != nil { + return x.Seconds + } + return 0 +} + +func (x *Timestamp) GetNanos() int32 { + if x != nil { + return x.Nanos + } + return 0 +} + +var File_google_protobuf_timestamp_proto protoreflect.FileDescriptor + +var file_google_protobuf_timestamp_proto_rawDesc = []byte{ + 0x0a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x12, 0x0f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x22, 0x3b, 0x0a, 0x09, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, + 0x18, 0x0a, 0x07, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, + 0x52, 0x07, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x6e, 0x61, 0x6e, + 0x6f, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x6e, 0x61, 0x6e, 0x6f, 0x73, 0x42, + 0x7e, 0x0a, 0x13, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x42, 0x0e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, + 0x70, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, + 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x74, 0x69, 0x6d, 0x65, + 0x73, 0x74, 0x61, 0x6d, 0x70, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x03, 0x47, 0x50, 0x42, 0xaa, 0x02, + 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x57, 0x65, 0x6c, 0x6c, 0x4b, 0x6e, 0x6f, 0x77, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x73, 0x62, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_google_protobuf_timestamp_proto_rawDescOnce sync.Once + file_google_protobuf_timestamp_proto_rawDescData = file_google_protobuf_timestamp_proto_rawDesc +) + +func file_google_protobuf_timestamp_proto_rawDescGZIP() []byte { + file_google_protobuf_timestamp_proto_rawDescOnce.Do(func() { + file_google_protobuf_timestamp_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_protobuf_timestamp_proto_rawDescData) + }) + return file_google_protobuf_timestamp_proto_rawDescData +} + +var file_google_protobuf_timestamp_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_google_protobuf_timestamp_proto_goTypes = []interface{}{ + (*Timestamp)(nil), // 0: google.protobuf.Timestamp +} +var file_google_protobuf_timestamp_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_google_protobuf_timestamp_proto_init() } +func file_google_protobuf_timestamp_proto_init() { + if File_google_protobuf_timestamp_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_protobuf_timestamp_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Timestamp); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_protobuf_timestamp_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_protobuf_timestamp_proto_goTypes, + DependencyIndexes: file_google_protobuf_timestamp_proto_depIdxs, + MessageInfos: file_google_protobuf_timestamp_proto_msgTypes, + }.Build() + File_google_protobuf_timestamp_proto = out.File + file_google_protobuf_timestamp_proto_rawDesc = nil + file_google_protobuf_timestamp_proto_goTypes = nil + file_google_protobuf_timestamp_proto_depIdxs = nil +} diff --git a/vendor/google.golang.org/protobuf/types/pluginpb/plugin.pb.go b/vendor/google.golang.org/protobuf/types/pluginpb/plugin.pb.go new file mode 100644 index 00000000000..43ef7cb1456 --- /dev/null +++ b/vendor/google.golang.org/protobuf/types/pluginpb/plugin.pb.go @@ -0,0 +1,636 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// +// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to +// change. +// +// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is +// just a program that reads a CodeGeneratorRequest from stdin and writes a +// CodeGeneratorResponse to stdout. +// +// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead +// of dealing with the raw protocol defined here. +// +// A plugin executable needs only to be placed somewhere in the path. The +// plugin should be named "protoc-gen-$NAME", and will then be used when the +// flag "--${NAME}_out" is passed to protoc. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: google/protobuf/compiler/plugin.proto + +package pluginpb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + descriptorpb "google.golang.org/protobuf/types/descriptorpb" + reflect "reflect" + sync "sync" +) + +// Sync with code_generator.h. +type CodeGeneratorResponse_Feature int32 + +const ( + CodeGeneratorResponse_FEATURE_NONE CodeGeneratorResponse_Feature = 0 + CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL CodeGeneratorResponse_Feature = 1 +) + +// Enum value maps for CodeGeneratorResponse_Feature. +var ( + CodeGeneratorResponse_Feature_name = map[int32]string{ + 0: "FEATURE_NONE", + 1: "FEATURE_PROTO3_OPTIONAL", + } + CodeGeneratorResponse_Feature_value = map[string]int32{ + "FEATURE_NONE": 0, + "FEATURE_PROTO3_OPTIONAL": 1, + } +) + +func (x CodeGeneratorResponse_Feature) Enum() *CodeGeneratorResponse_Feature { + p := new(CodeGeneratorResponse_Feature) + *p = x + return p +} + +func (x CodeGeneratorResponse_Feature) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (CodeGeneratorResponse_Feature) Descriptor() protoreflect.EnumDescriptor { + return file_google_protobuf_compiler_plugin_proto_enumTypes[0].Descriptor() +} + +func (CodeGeneratorResponse_Feature) Type() protoreflect.EnumType { + return &file_google_protobuf_compiler_plugin_proto_enumTypes[0] +} + +func (x CodeGeneratorResponse_Feature) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Do not use. +func (x *CodeGeneratorResponse_Feature) UnmarshalJSON(b []byte) error { + num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) + if err != nil { + return err + } + *x = CodeGeneratorResponse_Feature(num) + return nil +} + +// Deprecated: Use CodeGeneratorResponse_Feature.Descriptor instead. +func (CodeGeneratorResponse_Feature) EnumDescriptor() ([]byte, []int) { + return file_google_protobuf_compiler_plugin_proto_rawDescGZIP(), []int{2, 0} +} + +// The version number of protocol compiler. +type Version struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Major *int32 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"` + Minor *int32 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"` + Patch *int32 `protobuf:"varint,3,opt,name=patch" json:"patch,omitempty"` + // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should + // be empty for mainline stable releases. + Suffix *string `protobuf:"bytes,4,opt,name=suffix" json:"suffix,omitempty"` +} + +func (x *Version) Reset() { + *x = Version{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_compiler_plugin_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Version) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Version) ProtoMessage() {} + +func (x *Version) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_compiler_plugin_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Version.ProtoReflect.Descriptor instead. +func (*Version) Descriptor() ([]byte, []int) { + return file_google_protobuf_compiler_plugin_proto_rawDescGZIP(), []int{0} +} + +func (x *Version) GetMajor() int32 { + if x != nil && x.Major != nil { + return *x.Major + } + return 0 +} + +func (x *Version) GetMinor() int32 { + if x != nil && x.Minor != nil { + return *x.Minor + } + return 0 +} + +func (x *Version) GetPatch() int32 { + if x != nil && x.Patch != nil { + return *x.Patch + } + return 0 +} + +func (x *Version) GetSuffix() string { + if x != nil && x.Suffix != nil { + return *x.Suffix + } + return "" +} + +// An encoded CodeGeneratorRequest is written to the plugin's stdin. +type CodeGeneratorRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The .proto files that were explicitly listed on the command-line. The + // code generator should generate code only for these files. Each file's + // descriptor will be included in proto_file, below. + FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate,json=fileToGenerate" json:"file_to_generate,omitempty"` + // The generator parameter passed on the command-line. + Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"` + // FileDescriptorProtos for all files in files_to_generate and everything + // they import. The files will appear in topological order, so each file + // appears before any file that imports it. + // + // protoc guarantees that all proto_files will be written after + // the fields above, even though this is not technically guaranteed by the + // protobuf wire format. This theoretically could allow a plugin to stream + // in the FileDescriptorProtos and handle them one by one rather than read + // the entire set into memory at once. However, as of this writing, this + // is not similarly optimized on protoc's end -- it will store all fields in + // memory at once before sending them to the plugin. + // + // Type names of fields and extensions in the FileDescriptorProto are always + // fully qualified. + ProtoFile []*descriptorpb.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file,json=protoFile" json:"proto_file,omitempty"` + // The version number of protocol compiler. + CompilerVersion *Version `protobuf:"bytes,3,opt,name=compiler_version,json=compilerVersion" json:"compiler_version,omitempty"` +} + +func (x *CodeGeneratorRequest) Reset() { + *x = CodeGeneratorRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_compiler_plugin_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CodeGeneratorRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CodeGeneratorRequest) ProtoMessage() {} + +func (x *CodeGeneratorRequest) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_compiler_plugin_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CodeGeneratorRequest.ProtoReflect.Descriptor instead. +func (*CodeGeneratorRequest) Descriptor() ([]byte, []int) { + return file_google_protobuf_compiler_plugin_proto_rawDescGZIP(), []int{1} +} + +func (x *CodeGeneratorRequest) GetFileToGenerate() []string { + if x != nil { + return x.FileToGenerate + } + return nil +} + +func (x *CodeGeneratorRequest) GetParameter() string { + if x != nil && x.Parameter != nil { + return *x.Parameter + } + return "" +} + +func (x *CodeGeneratorRequest) GetProtoFile() []*descriptorpb.FileDescriptorProto { + if x != nil { + return x.ProtoFile + } + return nil +} + +func (x *CodeGeneratorRequest) GetCompilerVersion() *Version { + if x != nil { + return x.CompilerVersion + } + return nil +} + +// The plugin writes an encoded CodeGeneratorResponse to stdout. +type CodeGeneratorResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Error message. If non-empty, code generation failed. The plugin process + // should exit with status code zero even if it reports an error in this way. + // + // This should be used to indicate errors in .proto files which prevent the + // code generator from generating correct code. Errors which indicate a + // problem in protoc itself -- such as the input CodeGeneratorRequest being + // unparseable -- should be reported by writing a message to stderr and + // exiting with a non-zero status code. + Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"` + // A bitmask of supported features that the code generator supports. + // This is a bitwise "or" of values from the Feature enum. + SupportedFeatures *uint64 `protobuf:"varint,2,opt,name=supported_features,json=supportedFeatures" json:"supported_features,omitempty"` + File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"` +} + +func (x *CodeGeneratorResponse) Reset() { + *x = CodeGeneratorResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_compiler_plugin_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CodeGeneratorResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CodeGeneratorResponse) ProtoMessage() {} + +func (x *CodeGeneratorResponse) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_compiler_plugin_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CodeGeneratorResponse.ProtoReflect.Descriptor instead. +func (*CodeGeneratorResponse) Descriptor() ([]byte, []int) { + return file_google_protobuf_compiler_plugin_proto_rawDescGZIP(), []int{2} +} + +func (x *CodeGeneratorResponse) GetError() string { + if x != nil && x.Error != nil { + return *x.Error + } + return "" +} + +func (x *CodeGeneratorResponse) GetSupportedFeatures() uint64 { + if x != nil && x.SupportedFeatures != nil { + return *x.SupportedFeatures + } + return 0 +} + +func (x *CodeGeneratorResponse) GetFile() []*CodeGeneratorResponse_File { + if x != nil { + return x.File + } + return nil +} + +// Represents a single generated file. +type CodeGeneratorResponse_File struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The file name, relative to the output directory. The name must not + // contain "." or ".." components and must be relative, not be absolute (so, + // the file cannot lie outside the output directory). "/" must be used as + // the path separator, not "\". + // + // If the name is omitted, the content will be appended to the previous + // file. This allows the generator to break large files into small chunks, + // and allows the generated text to be streamed back to protoc so that large + // files need not reside completely in memory at one time. Note that as of + // this writing protoc does not optimize for this -- it will read the entire + // CodeGeneratorResponse before writing files to disk. + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + // If non-empty, indicates that the named file should already exist, and the + // content here is to be inserted into that file at a defined insertion + // point. This feature allows a code generator to extend the output + // produced by another code generator. The original generator may provide + // insertion points by placing special annotations in the file that look + // like: + // @@protoc_insertion_point(NAME) + // The annotation can have arbitrary text before and after it on the line, + // which allows it to be placed in a comment. NAME should be replaced with + // an identifier naming the point -- this is what other generators will use + // as the insertion_point. Code inserted at this point will be placed + // immediately above the line containing the insertion point (thus multiple + // insertions to the same point will come out in the order they were added). + // The double-@ is intended to make it unlikely that the generated code + // could contain things that look like insertion points by accident. + // + // For example, the C++ code generator places the following line in the + // .pb.h files that it generates: + // // @@protoc_insertion_point(namespace_scope) + // This line appears within the scope of the file's package namespace, but + // outside of any particular class. Another plugin can then specify the + // insertion_point "namespace_scope" to generate additional classes or + // other declarations that should be placed in this scope. + // + // Note that if the line containing the insertion point begins with + // whitespace, the same whitespace will be added to every line of the + // inserted text. This is useful for languages like Python, where + // indentation matters. In these languages, the insertion point comment + // should be indented the same amount as any inserted code will need to be + // in order to work correctly in that context. + // + // The code generator that generates the initial file and the one which + // inserts into it must both run as part of a single invocation of protoc. + // Code generators are executed in the order in which they appear on the + // command line. + // + // If |insertion_point| is present, |name| must also be present. + InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point,json=insertionPoint" json:"insertion_point,omitempty"` + // The file contents. + Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"` +} + +func (x *CodeGeneratorResponse_File) Reset() { + *x = CodeGeneratorResponse_File{} + if protoimpl.UnsafeEnabled { + mi := &file_google_protobuf_compiler_plugin_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CodeGeneratorResponse_File) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CodeGeneratorResponse_File) ProtoMessage() {} + +func (x *CodeGeneratorResponse_File) ProtoReflect() protoreflect.Message { + mi := &file_google_protobuf_compiler_plugin_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CodeGeneratorResponse_File.ProtoReflect.Descriptor instead. +func (*CodeGeneratorResponse_File) Descriptor() ([]byte, []int) { + return file_google_protobuf_compiler_plugin_proto_rawDescGZIP(), []int{2, 0} +} + +func (x *CodeGeneratorResponse_File) GetName() string { + if x != nil && x.Name != nil { + return *x.Name + } + return "" +} + +func (x *CodeGeneratorResponse_File) GetInsertionPoint() string { + if x != nil && x.InsertionPoint != nil { + return *x.InsertionPoint + } + return "" +} + +func (x *CodeGeneratorResponse_File) GetContent() string { + if x != nil && x.Content != nil { + return *x.Content + } + return "" +} + +var File_google_protobuf_compiler_plugin_proto protoreflect.FileDescriptor + +var file_google_protobuf_compiler_plugin_proto_rawDesc = []byte{ + 0x0a, 0x25, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2f, 0x63, 0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x65, 0x72, 0x2f, 0x70, 0x6c, 0x75, 0x67, 0x69, + 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x18, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x63, 0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x65, + 0x72, 0x1a, 0x20, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x22, 0x63, 0x0a, 0x07, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x14, + 0x0a, 0x05, 0x6d, 0x61, 0x6a, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x6d, + 0x61, 0x6a, 0x6f, 0x72, 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x69, 0x6e, 0x6f, 0x72, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x05, 0x52, 0x05, 0x6d, 0x69, 0x6e, 0x6f, 0x72, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x61, + 0x74, 0x63, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, + 0x12, 0x16, 0x0a, 0x06, 0x73, 0x75, 0x66, 0x66, 0x69, 0x78, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x06, 0x73, 0x75, 0x66, 0x66, 0x69, 0x78, 0x22, 0xf1, 0x01, 0x0a, 0x14, 0x43, 0x6f, 0x64, + 0x65, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x12, 0x28, 0x0a, 0x10, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x74, 0x6f, 0x5f, 0x67, 0x65, 0x6e, + 0x65, 0x72, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0e, 0x66, 0x69, 0x6c, + 0x65, 0x54, 0x6f, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x70, + 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, + 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x12, 0x43, 0x0a, 0x0a, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x18, 0x0f, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x46, 0x69, 0x6c, 0x65, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x50, 0x72, + 0x6f, 0x74, 0x6f, 0x52, 0x09, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x46, 0x69, 0x6c, 0x65, 0x12, 0x4c, + 0x0a, 0x10, 0x63, 0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x65, 0x72, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x63, 0x6f, 0x6d, 0x70, 0x69, + 0x6c, 0x65, 0x72, 0x2e, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x63, 0x6f, 0x6d, + 0x70, 0x69, 0x6c, 0x65, 0x72, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0xbf, 0x02, 0x0a, + 0x15, 0x43, 0x6f, 0x64, 0x65, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x2d, 0x0a, 0x12, + 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x5f, 0x66, 0x65, 0x61, 0x74, 0x75, 0x72, + 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x11, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, + 0x74, 0x65, 0x64, 0x46, 0x65, 0x61, 0x74, 0x75, 0x72, 0x65, 0x73, 0x12, 0x48, 0x0a, 0x04, 0x66, + 0x69, 0x6c, 0x65, 0x18, 0x0f, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x34, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x63, 0x6f, 0x6d, 0x70, + 0x69, 0x6c, 0x65, 0x72, 0x2e, 0x43, 0x6f, 0x64, 0x65, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, + 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x52, + 0x04, 0x66, 0x69, 0x6c, 0x65, 0x1a, 0x5d, 0x0a, 0x04, 0x46, 0x69, 0x6c, 0x65, 0x12, 0x12, 0x0a, + 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, + 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x69, 0x6e, 0x73, 0x65, 0x72, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x70, + 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x69, 0x6e, 0x73, 0x65, + 0x72, 0x74, 0x69, 0x6f, 0x6e, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, + 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6e, + 0x74, 0x65, 0x6e, 0x74, 0x22, 0x38, 0x0a, 0x07, 0x46, 0x65, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, + 0x10, 0x0a, 0x0c, 0x46, 0x45, 0x41, 0x54, 0x55, 0x52, 0x45, 0x5f, 0x4e, 0x4f, 0x4e, 0x45, 0x10, + 0x00, 0x12, 0x1b, 0x0a, 0x17, 0x46, 0x45, 0x41, 0x54, 0x55, 0x52, 0x45, 0x5f, 0x50, 0x52, 0x4f, + 0x54, 0x4f, 0x33, 0x5f, 0x4f, 0x50, 0x54, 0x49, 0x4f, 0x4e, 0x41, 0x4c, 0x10, 0x01, 0x42, 0x67, + 0x0a, 0x1c, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x63, 0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x65, 0x72, 0x42, 0x0c, + 0x50, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x5a, 0x39, 0x67, 0x69, + 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x2d, + 0x67, 0x65, 0x6e, 0x2d, 0x67, 0x6f, 0x2f, 0x70, 0x6c, 0x75, 0x67, 0x69, 0x6e, 0x3b, 0x70, 0x6c, + 0x75, 0x67, 0x69, 0x6e, 0x5f, 0x67, 0x6f, +} + +var ( + file_google_protobuf_compiler_plugin_proto_rawDescOnce sync.Once + file_google_protobuf_compiler_plugin_proto_rawDescData = file_google_protobuf_compiler_plugin_proto_rawDesc +) + +func file_google_protobuf_compiler_plugin_proto_rawDescGZIP() []byte { + file_google_protobuf_compiler_plugin_proto_rawDescOnce.Do(func() { + file_google_protobuf_compiler_plugin_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_protobuf_compiler_plugin_proto_rawDescData) + }) + return file_google_protobuf_compiler_plugin_proto_rawDescData +} + +var file_google_protobuf_compiler_plugin_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_google_protobuf_compiler_plugin_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_google_protobuf_compiler_plugin_proto_goTypes = []interface{}{ + (CodeGeneratorResponse_Feature)(0), // 0: google.protobuf.compiler.CodeGeneratorResponse.Feature + (*Version)(nil), // 1: google.protobuf.compiler.Version + (*CodeGeneratorRequest)(nil), // 2: google.protobuf.compiler.CodeGeneratorRequest + (*CodeGeneratorResponse)(nil), // 3: google.protobuf.compiler.CodeGeneratorResponse + (*CodeGeneratorResponse_File)(nil), // 4: google.protobuf.compiler.CodeGeneratorResponse.File + (*descriptorpb.FileDescriptorProto)(nil), // 5: google.protobuf.FileDescriptorProto +} +var file_google_protobuf_compiler_plugin_proto_depIdxs = []int32{ + 5, // 0: google.protobuf.compiler.CodeGeneratorRequest.proto_file:type_name -> google.protobuf.FileDescriptorProto + 1, // 1: google.protobuf.compiler.CodeGeneratorRequest.compiler_version:type_name -> google.protobuf.compiler.Version + 4, // 2: google.protobuf.compiler.CodeGeneratorResponse.file:type_name -> google.protobuf.compiler.CodeGeneratorResponse.File + 3, // [3:3] is the sub-list for method output_type + 3, // [3:3] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_google_protobuf_compiler_plugin_proto_init() } +func file_google_protobuf_compiler_plugin_proto_init() { + if File_google_protobuf_compiler_plugin_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_protobuf_compiler_plugin_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Version); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_compiler_plugin_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CodeGeneratorRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_compiler_plugin_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CodeGeneratorResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_protobuf_compiler_plugin_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CodeGeneratorResponse_File); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_protobuf_compiler_plugin_proto_rawDesc, + NumEnums: 1, + NumMessages: 4, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_protobuf_compiler_plugin_proto_goTypes, + DependencyIndexes: file_google_protobuf_compiler_plugin_proto_depIdxs, + EnumInfos: file_google_protobuf_compiler_plugin_proto_enumTypes, + MessageInfos: file_google_protobuf_compiler_plugin_proto_msgTypes, + }.Build() + File_google_protobuf_compiler_plugin_proto = out.File + file_google_protobuf_compiler_plugin_proto_rawDesc = nil + file_google_protobuf_compiler_plugin_proto_goTypes = nil + file_google_protobuf_compiler_plugin_proto_depIdxs = nil +} diff --git a/vendor/gopkg.in/yaml.v2/apic.go b/vendor/gopkg.in/yaml.v2/apic.go index 1f7e87e6727..d2c2308f1f4 100644 --- a/vendor/gopkg.in/yaml.v2/apic.go +++ b/vendor/gopkg.in/yaml.v2/apic.go @@ -86,6 +86,7 @@ func yaml_emitter_initialize(emitter *yaml_emitter_t) { raw_buffer: make([]byte, 0, output_raw_buffer_size), states: make([]yaml_emitter_state_t, 0, initial_stack_size), events: make([]yaml_event_t, 0, initial_queue_size), + best_width: -1, } } diff --git a/vendor/gopkg.in/yaml.v3/.travis.yml b/vendor/gopkg.in/yaml.v3/.travis.yml new file mode 100644 index 00000000000..04d4dae09c7 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/.travis.yml @@ -0,0 +1,16 @@ +language: go + +go: + - "1.4.x" + - "1.5.x" + - "1.6.x" + - "1.7.x" + - "1.8.x" + - "1.9.x" + - "1.10.x" + - "1.11.x" + - "1.12.x" + - "1.13.x" + - "tip" + +go_import_path: gopkg.in/yaml.v3 diff --git a/vendor/gopkg.in/yaml.v3/LICENSE b/vendor/gopkg.in/yaml.v3/LICENSE new file mode 100644 index 00000000000..2683e4bb1f2 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/LICENSE @@ -0,0 +1,50 @@ + +This project is covered by two different licenses: MIT and Apache. + +#### MIT License #### + +The following files were ported to Go from C files of libyaml, and thus +are still covered by their original MIT license, with the additional +copyright staring in 2011 when the project was ported over: + + apic.go emitterc.go parserc.go readerc.go scannerc.go + writerc.go yamlh.go yamlprivateh.go + +Copyright (c) 2006-2010 Kirill Simonov +Copyright (c) 2006-2011 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +### Apache License ### + +All the remaining project files are covered by the Apache license: + +Copyright (c) 2011-2019 Canonical Ltd + +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/gopkg.in/yaml.v3/NOTICE b/vendor/gopkg.in/yaml.v3/NOTICE new file mode 100644 index 00000000000..866d74a7ad7 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/NOTICE @@ -0,0 +1,13 @@ +Copyright 2011-2016 Canonical Ltd. + +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/gopkg.in/yaml.v3/README.md b/vendor/gopkg.in/yaml.v3/README.md new file mode 100644 index 00000000000..08eb1babddf --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/README.md @@ -0,0 +1,150 @@ +# YAML support for the Go language + +Introduction +------------ + +The yaml package enables Go programs to comfortably encode and decode YAML +values. It was developed within [Canonical](https://www.canonical.com) as +part of the [juju](https://juju.ubuntu.com) project, and is based on a +pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) +C library to parse and generate YAML data quickly and reliably. + +Compatibility +------------- + +The yaml package supports most of YAML 1.2, but preserves some behavior +from 1.1 for backwards compatibility. + +Specifically, as of v3 of the yaml package: + + - YAML 1.1 bools (_yes/no, on/off_) are supported as long as they are being + decoded into a typed bool value. Otherwise they behave as a string. Booleans + in YAML 1.2 are _true/false_ only. + - Octals encode and decode as _0777_ per YAML 1.1, rather than _0o777_ + as specified in YAML 1.2, because most parsers still use the old format. + Octals in the _0o777_ format are supported though, so new files work. + - Does not support base-60 floats. These are gone from YAML 1.2, and were + actually never supported by this package as it's clearly a poor choice. + +and offers backwards +compatibility with YAML 1.1 in some cases. +1.2, including support for +anchors, tags, map merging, etc. Multi-document unmarshalling is not yet +implemented, and base-60 floats from YAML 1.1 are purposefully not +supported since they're a poor design and are gone in YAML 1.2. + +Installation and usage +---------------------- + +The import path for the package is *gopkg.in/yaml.v3*. + +To install it, run: + + go get gopkg.in/yaml.v3 + +API documentation +----------------- + +If opened in a browser, the import path itself leads to the API documentation: + + - [https://gopkg.in/yaml.v3](https://gopkg.in/yaml.v3) + +API stability +------------- + +The package API for yaml v3 will remain stable as described in [gopkg.in](https://gopkg.in). + + +License +------- + +The yaml package is licensed under the MIT and Apache License 2.0 licenses. +Please see the LICENSE file for details. + + +Example +------- + +```Go +package main + +import ( + "fmt" + "log" + + "gopkg.in/yaml.v3" +) + +var data = ` +a: Easy! +b: + c: 2 + d: [3, 4] +` + +// Note: struct fields must be public in order for unmarshal to +// correctly populate the data. +type T struct { + A string + B struct { + RenamedC int `yaml:"c"` + D []int `yaml:",flow"` + } +} + +func main() { + t := T{} + + err := yaml.Unmarshal([]byte(data), &t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t:\n%v\n\n", t) + + d, err := yaml.Marshal(&t) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- t dump:\n%s\n\n", string(d)) + + m := make(map[interface{}]interface{}) + + err = yaml.Unmarshal([]byte(data), &m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m:\n%v\n\n", m) + + d, err = yaml.Marshal(&m) + if err != nil { + log.Fatalf("error: %v", err) + } + fmt.Printf("--- m dump:\n%s\n\n", string(d)) +} +``` + +This example will generate the following output: + +``` +--- t: +{Easy! {2 [3 4]}} + +--- t dump: +a: Easy! +b: + c: 2 + d: [3, 4] + + +--- m: +map[a:Easy! b:map[c:2 d:[3 4]]] + +--- m dump: +a: Easy! +b: + c: 2 + d: + - 3 + - 4 +``` + diff --git a/vendor/github.com/zclconf/go-cty-yaml/apic.go b/vendor/gopkg.in/yaml.v3/apic.go similarity index 93% rename from vendor/github.com/zclconf/go-cty-yaml/apic.go rename to vendor/gopkg.in/yaml.v3/apic.go index 1f7e87e6727..65846e67497 100644 --- a/vendor/github.com/zclconf/go-cty-yaml/apic.go +++ b/vendor/gopkg.in/yaml.v3/apic.go @@ -1,3 +1,25 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + package yaml import ( @@ -138,7 +160,7 @@ func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { emitter.canonical = canonical } -//// Set the indentation increment. +// Set the indentation increment. func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { if indent < 2 || indent > 9 { indent = 2 @@ -288,29 +310,14 @@ func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { } } -///* -// * Create ALIAS. -// */ -// -//YAML_DECLARE(int) -//yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t) -//{ -// mark yaml_mark_t = { 0, 0, 0 } -// anchor_copy *yaml_char_t = NULL -// -// assert(event) // Non-NULL event object is expected. -// assert(anchor) // Non-NULL anchor is expected. -// -// if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0 -// -// anchor_copy = yaml_strdup(anchor) -// if (!anchor_copy) -// return 0 -// -// ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark) -// -// return 1 -//} +// Create ALIAS. +func yaml_alias_event_initialize(event *yaml_event_t, anchor []byte) bool { + *event = yaml_event_t{ + typ: yaml_ALIAS_EVENT, + anchor: anchor, + } + return true +} // Create SCALAR. func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { diff --git a/vendor/gopkg.in/yaml.v3/decode.go b/vendor/gopkg.in/yaml.v3/decode.go new file mode 100644 index 00000000000..be63169b719 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/decode.go @@ -0,0 +1,931 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// 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 yaml + +import ( + "encoding" + "encoding/base64" + "fmt" + "io" + "math" + "reflect" + "strconv" + "time" +) + +// ---------------------------------------------------------------------------- +// Parser, produces a node tree out of a libyaml event stream. + +type parser struct { + parser yaml_parser_t + event yaml_event_t + doc *Node + anchors map[string]*Node + doneInit bool +} + +func newParser(b []byte) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + if len(b) == 0 { + b = []byte{'\n'} + } + yaml_parser_set_input_string(&p.parser, b) + return &p +} + +func newParserFromReader(r io.Reader) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") + } + yaml_parser_set_input_reader(&p.parser, r) + return &p +} + +func (p *parser) init() { + if p.doneInit { + return + } + p.anchors = make(map[string]*Node) + p.expect(yaml_STREAM_START_EVENT) + p.doneInit = true +} + +func (p *parser) destroy() { + if p.event.typ != yaml_NO_EVENT { + yaml_event_delete(&p.event) + } + yaml_parser_delete(&p.parser) +} + +// expect consumes an event from the event stream and +// checks that it's of the expected type. +func (p *parser) expect(e yaml_event_type_t) { + if p.event.typ == yaml_NO_EVENT { + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + } + if p.event.typ == yaml_STREAM_END_EVENT { + failf("attempted to go past the end of stream; corrupted value?") + } + if p.event.typ != e { + p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) + p.fail() + } + yaml_event_delete(&p.event) + p.event.typ = yaml_NO_EVENT +} + +// peek peeks at the next event in the event stream, +// puts the results into p.event and returns the event type. +func (p *parser) peek() yaml_event_type_t { + if p.event.typ != yaml_NO_EVENT { + return p.event.typ + } + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() + } + return p.event.typ +} + +func (p *parser) fail() { + var where string + var line int + if p.parser.problem_mark.line != 0 { + line = p.parser.problem_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } + } else if p.parser.context_mark.line != 0 { + line = p.parser.context_mark.line + } + if line != 0 { + where = "line " + strconv.Itoa(line) + ": " + } + var msg string + if len(p.parser.problem) > 0 { + msg = p.parser.problem + } else { + msg = "unknown problem parsing YAML content" + } + failf("%s%s", where, msg) +} + +func (p *parser) anchor(n *Node, anchor []byte) { + if anchor != nil { + n.Anchor = string(anchor) + p.anchors[n.Anchor] = n + } +} + +func (p *parser) parse() *Node { + p.init() + switch p.peek() { + case yaml_SCALAR_EVENT: + return p.scalar() + case yaml_ALIAS_EVENT: + return p.alias() + case yaml_MAPPING_START_EVENT: + return p.mapping() + case yaml_SEQUENCE_START_EVENT: + return p.sequence() + case yaml_DOCUMENT_START_EVENT: + return p.document() + case yaml_STREAM_END_EVENT: + // Happens when attempting to decode an empty buffer. + return nil + case yaml_TAIL_COMMENT_EVENT: + panic("internal error: unexpected tail comment event (please report)") + default: + panic("internal error: attempted to parse unknown event (please report): " + p.event.typ.String()) + } +} + +func (p *parser) node(kind Kind, defaultTag, tag, value string) *Node { + var style Style + if tag != "" && tag != "!" { + tag = shortTag(tag) + style = TaggedStyle + } else if defaultTag != "" { + tag = defaultTag + } else if kind == ScalarNode { + tag, _ = resolve("", value) + } + return &Node{ + Kind: kind, + Tag: tag, + Value: value, + Style: style, + Line: p.event.start_mark.line + 1, + Column: p.event.start_mark.column + 1, + HeadComment: string(p.event.head_comment), + LineComment: string(p.event.line_comment), + FootComment: string(p.event.foot_comment), + } +} + +func (p *parser) parseChild(parent *Node) *Node { + child := p.parse() + parent.Content = append(parent.Content, child) + return child +} + +func (p *parser) document() *Node { + n := p.node(DocumentNode, "", "", "") + p.doc = n + p.expect(yaml_DOCUMENT_START_EVENT) + p.parseChild(n) + if p.peek() == yaml_DOCUMENT_END_EVENT { + n.FootComment = string(p.event.foot_comment) + } + p.expect(yaml_DOCUMENT_END_EVENT) + return n +} + +func (p *parser) alias() *Node { + n := p.node(AliasNode, "", "", string(p.event.anchor)) + n.Alias = p.anchors[n.Value] + if n.Alias == nil { + failf("unknown anchor '%s' referenced", n.Value) + } + p.expect(yaml_ALIAS_EVENT) + return n +} + +func (p *parser) scalar() *Node { + var parsedStyle = p.event.scalar_style() + var nodeStyle Style + switch { + case parsedStyle&yaml_DOUBLE_QUOTED_SCALAR_STYLE != 0: + nodeStyle = DoubleQuotedStyle + case parsedStyle&yaml_SINGLE_QUOTED_SCALAR_STYLE != 0: + nodeStyle = SingleQuotedStyle + case parsedStyle&yaml_LITERAL_SCALAR_STYLE != 0: + nodeStyle = LiteralStyle + case parsedStyle&yaml_FOLDED_SCALAR_STYLE != 0: + nodeStyle = FoldedStyle + } + var nodeValue = string(p.event.value) + var nodeTag = string(p.event.tag) + var defaultTag string + if nodeStyle == 0 { + if nodeValue == "<<" { + defaultTag = mergeTag + } + } else { + defaultTag = strTag + } + n := p.node(ScalarNode, defaultTag, nodeTag, nodeValue) + n.Style |= nodeStyle + p.anchor(n, p.event.anchor) + p.expect(yaml_SCALAR_EVENT) + return n +} + +func (p *parser) sequence() *Node { + n := p.node(SequenceNode, seqTag, string(p.event.tag), "") + if p.event.sequence_style()&yaml_FLOW_SEQUENCE_STYLE != 0 { + n.Style |= FlowStyle + } + p.anchor(n, p.event.anchor) + p.expect(yaml_SEQUENCE_START_EVENT) + for p.peek() != yaml_SEQUENCE_END_EVENT { + p.parseChild(n) + } + n.LineComment = string(p.event.line_comment) + n.FootComment = string(p.event.foot_comment) + p.expect(yaml_SEQUENCE_END_EVENT) + return n +} + +func (p *parser) mapping() *Node { + n := p.node(MappingNode, mapTag, string(p.event.tag), "") + block := true + if p.event.mapping_style()&yaml_FLOW_MAPPING_STYLE != 0 { + block = false + n.Style |= FlowStyle + } + p.anchor(n, p.event.anchor) + p.expect(yaml_MAPPING_START_EVENT) + for p.peek() != yaml_MAPPING_END_EVENT { + k := p.parseChild(n) + if block && k.FootComment != "" { + // Must be a foot comment for the prior value when being dedented. + if len(n.Content) > 2 { + n.Content[len(n.Content)-3].FootComment = k.FootComment + k.FootComment = "" + } + } + v := p.parseChild(n) + if k.FootComment == "" && v.FootComment != "" { + k.FootComment = v.FootComment + v.FootComment = "" + } + if p.peek() == yaml_TAIL_COMMENT_EVENT { + if k.FootComment == "" { + k.FootComment = string(p.event.foot_comment) + } + p.expect(yaml_TAIL_COMMENT_EVENT) + } + } + n.LineComment = string(p.event.line_comment) + n.FootComment = string(p.event.foot_comment) + if n.Style&FlowStyle == 0 && n.FootComment != "" && len(n.Content) > 1 { + n.Content[len(n.Content)-2].FootComment = n.FootComment + n.FootComment = "" + } + p.expect(yaml_MAPPING_END_EVENT) + return n +} + +// ---------------------------------------------------------------------------- +// Decoder, unmarshals a node into a provided value. + +type decoder struct { + doc *Node + aliases map[*Node]bool + terrors []string + + stringMapType reflect.Type + generalMapType reflect.Type + + knownFields bool + uniqueKeys bool + decodeCount int + aliasCount int + aliasDepth int +} + +var ( + nodeType = reflect.TypeOf(Node{}) + durationType = reflect.TypeOf(time.Duration(0)) + stringMapType = reflect.TypeOf(map[string]interface{}{}) + generalMapType = reflect.TypeOf(map[interface{}]interface{}{}) + ifaceType = generalMapType.Elem() + timeType = reflect.TypeOf(time.Time{}) + ptrTimeType = reflect.TypeOf(&time.Time{}) +) + +func newDecoder() *decoder { + d := &decoder{ + stringMapType: stringMapType, + generalMapType: generalMapType, + uniqueKeys: true, + } + d.aliases = make(map[*Node]bool) + return d +} + +func (d *decoder) terror(n *Node, tag string, out reflect.Value) { + if n.Tag != "" { + tag = n.Tag + } + value := n.Value + if tag != seqTag && tag != mapTag { + if len(value) > 10 { + value = " `" + value[:7] + "...`" + } else { + value = " `" + value + "`" + } + } + d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.Line, shortTag(tag), value, out.Type())) +} + +func (d *decoder) callUnmarshaler(n *Node, u Unmarshaler) (good bool) { + err := u.UnmarshalYAML(n) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true +} + +func (d *decoder) callObsoleteUnmarshaler(n *Node, u obsoleteUnmarshaler) (good bool) { + terrlen := len(d.terrors) + err := u.UnmarshalYAML(func(v interface{}) (err error) { + defer handleErr(&err) + d.unmarshal(n, reflect.ValueOf(v)) + if len(d.terrors) > terrlen { + issues := d.terrors[terrlen:] + d.terrors = d.terrors[:terrlen] + return &TypeError{issues} + } + return nil + }) + if e, ok := err.(*TypeError); ok { + d.terrors = append(d.terrors, e.Errors...) + return false + } + if err != nil { + fail(err) + } + return true +} + +// d.prepare initializes and dereferences pointers and calls UnmarshalYAML +// if a value is found to implement it. +// It returns the initialized and dereferenced out value, whether +// unmarshalling was already done by UnmarshalYAML, and if so whether +// its types unmarshalled appropriately. +// +// If n holds a null value, prepare returns before doing anything. +func (d *decoder) prepare(n *Node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { + if n.ShortTag() == nullTag { + return out, false, false + } + again := true + for again { + again = false + if out.Kind() == reflect.Ptr { + if out.IsNil() { + out.Set(reflect.New(out.Type().Elem())) + } + out = out.Elem() + again = true + } + if out.CanAddr() { + outi := out.Addr().Interface() + if u, ok := outi.(Unmarshaler); ok { + good = d.callUnmarshaler(n, u) + return out, true, good + } + if u, ok := outi.(obsoleteUnmarshaler); ok { + good = d.callObsoleteUnmarshaler(n, u) + return out, true, good + } + } + } + return out, false, false +} + +func (d *decoder) fieldByIndex(n *Node, v reflect.Value, index []int) (field reflect.Value) { + if n.ShortTag() == nullTag { + return reflect.Value{} + } + for _, num := range index { + for { + if v.Kind() == reflect.Ptr { + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } + v = v.Elem() + continue + } + break + } + v = v.Field(num) + } + return v +} + +const ( + // 400,000 decode operations is ~500kb of dense object declarations, or + // ~5kb of dense object declarations with 10000% alias expansion + alias_ratio_range_low = 400000 + + // 4,000,000 decode operations is ~5MB of dense object declarations, or + // ~4.5MB of dense object declarations with 10% alias expansion + alias_ratio_range_high = 4000000 + + // alias_ratio_range is the range over which we scale allowed alias ratios + alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low) +) + +func allowedAliasRatio(decodeCount int) float64 { + switch { + case decodeCount <= alias_ratio_range_low: + // allow 99% to come from alias expansion for small-to-medium documents + return 0.99 + case decodeCount >= alias_ratio_range_high: + // allow 10% to come from alias expansion for very large documents + return 0.10 + default: + // scale smoothly from 99% down to 10% over the range. + // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range. + // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps). + return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range) + } +} + +func (d *decoder) unmarshal(n *Node, out reflect.Value) (good bool) { + d.decodeCount++ + if d.aliasDepth > 0 { + d.aliasCount++ + } + if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) { + failf("document contains excessive aliasing") + } + if out.Type() == nodeType { + out.Set(reflect.ValueOf(n).Elem()) + return true + } + switch n.Kind { + case DocumentNode: + return d.document(n, out) + case AliasNode: + return d.alias(n, out) + } + out, unmarshaled, good := d.prepare(n, out) + if unmarshaled { + return good + } + switch n.Kind { + case ScalarNode: + good = d.scalar(n, out) + case MappingNode: + good = d.mapping(n, out) + case SequenceNode: + good = d.sequence(n, out) + default: + panic("internal error: unknown node kind: " + strconv.Itoa(int(n.Kind))) + } + return good +} + +func (d *decoder) document(n *Node, out reflect.Value) (good bool) { + if len(n.Content) == 1 { + d.doc = n + d.unmarshal(n.Content[0], out) + return true + } + return false +} + +func (d *decoder) alias(n *Node, out reflect.Value) (good bool) { + if d.aliases[n] { + // TODO this could actually be allowed in some circumstances. + failf("anchor '%s' value contains itself", n.Value) + } + d.aliases[n] = true + d.aliasDepth++ + good = d.unmarshal(n.Alias, out) + d.aliasDepth-- + delete(d.aliases, n) + return good +} + +var zeroValue reflect.Value + +func resetMap(out reflect.Value) { + for _, k := range out.MapKeys() { + out.SetMapIndex(k, zeroValue) + } +} + +func (d *decoder) scalar(n *Node, out reflect.Value) bool { + var tag string + var resolved interface{} + if n.indicatedString() { + tag = strTag + resolved = n.Value + } else { + tag, resolved = resolve(n.Tag, n.Value) + if tag == binaryTag { + data, err := base64.StdEncoding.DecodeString(resolved.(string)) + if err != nil { + failf("!!binary value contains invalid base64 data") + } + resolved = string(data) + } + } + if resolved == nil { + if out.CanAddr() { + switch out.Kind() { + case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: + out.Set(reflect.Zero(out.Type())) + return true + } + } + return false + } + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + // We've resolved to exactly the type we want, so use that. + out.Set(resolvedv) + return true + } + // Perhaps we can use the value as a TextUnmarshaler to + // set its value. + if out.CanAddr() { + u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) + if ok { + var text []byte + if tag == binaryTag { + text = []byte(resolved.(string)) + } else { + // We let any value be unmarshaled into TextUnmarshaler. + // That might be more lax than we'd like, but the + // TextUnmarshaler itself should bowl out any dubious values. + text = []byte(n.Value) + } + err := u.UnmarshalText(text) + if err != nil { + fail(err) + } + return true + } + } + switch out.Kind() { + case reflect.String: + if tag == binaryTag { + out.SetString(resolved.(string)) + return true + } + out.SetString(n.Value) + return true + case reflect.Interface: + out.Set(reflect.ValueOf(resolved)) + return true + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + // This used to work in v2, but it's very unfriendly. + isDuration := out.Type() == durationType + + switch resolved := resolved.(type) { + case int: + if !isDuration && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case int64: + if !isDuration && !out.OverflowInt(resolved) { + out.SetInt(resolved) + return true + } + case uint64: + if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case float64: + if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { + out.SetInt(int64(resolved)) + return true + } + case string: + if out.Type() == durationType { + d, err := time.ParseDuration(resolved) + if err == nil { + out.SetInt(int64(d)) + return true + } + } + } + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + switch resolved := resolved.(type) { + case int: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case int64: + if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case uint64: + if !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + case float64: + if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { + out.SetUint(uint64(resolved)) + return true + } + } + case reflect.Bool: + switch resolved := resolved.(type) { + case bool: + out.SetBool(resolved) + return true + case string: + // This offers some compatibility with the 1.1 spec (https://yaml.org/type/bool.html). + // It only works if explicitly attempting to unmarshal into a typed bool value. + switch resolved { + case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON": + out.SetBool(true) + return true + case "n", "N", "no", "No", "NO", "off", "Off", "OFF": + out.SetBool(false) + return true + } + } + case reflect.Float32, reflect.Float64: + switch resolved := resolved.(type) { + case int: + out.SetFloat(float64(resolved)) + return true + case int64: + out.SetFloat(float64(resolved)) + return true + case uint64: + out.SetFloat(float64(resolved)) + return true + case float64: + out.SetFloat(resolved) + return true + } + case reflect.Struct: + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + out.Set(resolvedv) + return true + } + case reflect.Ptr: + panic("yaml internal error: please report the issue") + } + d.terror(n, tag, out) + return false +} + +func settableValueOf(i interface{}) reflect.Value { + v := reflect.ValueOf(i) + sv := reflect.New(v.Type()).Elem() + sv.Set(v) + return sv +} + +func (d *decoder) sequence(n *Node, out reflect.Value) (good bool) { + l := len(n.Content) + + var iface reflect.Value + switch out.Kind() { + case reflect.Slice: + out.Set(reflect.MakeSlice(out.Type(), l, l)) + case reflect.Array: + if l != out.Len() { + failf("invalid array: want %d elements but got %d", out.Len(), l) + } + case reflect.Interface: + // No type hints. Will have to use a generic sequence. + iface = out + out = settableValueOf(make([]interface{}, l)) + default: + d.terror(n, seqTag, out) + return false + } + et := out.Type().Elem() + + j := 0 + for i := 0; i < l; i++ { + e := reflect.New(et).Elem() + if ok := d.unmarshal(n.Content[i], e); ok { + out.Index(j).Set(e) + j++ + } + } + if out.Kind() != reflect.Array { + out.Set(out.Slice(0, j)) + } + if iface.IsValid() { + iface.Set(out) + } + return true +} + +func (d *decoder) mapping(n *Node, out reflect.Value) (good bool) { + l := len(n.Content) + if d.uniqueKeys { + nerrs := len(d.terrors) + for i := 0; i < l; i += 2 { + ni := n.Content[i] + for j := i + 2; j < l; j += 2 { + nj := n.Content[j] + if ni.Kind == nj.Kind && ni.Value == nj.Value { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: mapping key %#v already defined at line %d", nj.Line, nj.Value, ni.Line)) + } + } + } + if len(d.terrors) > nerrs { + return false + } + } + switch out.Kind() { + case reflect.Struct: + return d.mappingStruct(n, out) + case reflect.Map: + // okay + case reflect.Interface: + iface := out + if isStringMap(n) { + out = reflect.MakeMap(d.stringMapType) + } else { + out = reflect.MakeMap(d.generalMapType) + } + iface.Set(out) + default: + d.terror(n, mapTag, out) + return false + } + + outt := out.Type() + kt := outt.Key() + et := outt.Elem() + + stringMapType := d.stringMapType + generalMapType := d.generalMapType + if outt.Elem() == ifaceType { + if outt.Key().Kind() == reflect.String { + d.stringMapType = outt + } else if outt.Key() == ifaceType { + d.generalMapType = outt + } + } + + if out.IsNil() { + out.Set(reflect.MakeMap(outt)) + } + for i := 0; i < l; i += 2 { + if isMerge(n.Content[i]) { + d.merge(n.Content[i+1], out) + continue + } + k := reflect.New(kt).Elem() + if d.unmarshal(n.Content[i], k) { + kkind := k.Kind() + if kkind == reflect.Interface { + kkind = k.Elem().Kind() + } + if kkind == reflect.Map || kkind == reflect.Slice { + failf("invalid map key: %#v", k.Interface()) + } + e := reflect.New(et).Elem() + if d.unmarshal(n.Content[i+1], e) { + out.SetMapIndex(k, e) + } + } + } + d.stringMapType = stringMapType + d.generalMapType = generalMapType + return true +} + +func isStringMap(n *Node) bool { + if n.Kind != MappingNode { + return false + } + l := len(n.Content) + for i := 0; i < l; i += 2 { + if n.Content[i].ShortTag() != strTag { + return false + } + } + return true +} + +func (d *decoder) mappingStruct(n *Node, out reflect.Value) (good bool) { + sinfo, err := getStructInfo(out.Type()) + if err != nil { + panic(err) + } + + var inlineMap reflect.Value + var elemType reflect.Type + if sinfo.InlineMap != -1 { + inlineMap = out.Field(sinfo.InlineMap) + inlineMap.Set(reflect.New(inlineMap.Type()).Elem()) + elemType = inlineMap.Type().Elem() + } + + for _, index := range sinfo.InlineUnmarshalers { + field := d.fieldByIndex(n, out, index) + d.prepare(n, field) + } + + var doneFields []bool + if d.uniqueKeys { + doneFields = make([]bool, len(sinfo.FieldsList)) + } + name := settableValueOf("") + l := len(n.Content) + for i := 0; i < l; i += 2 { + ni := n.Content[i] + if isMerge(ni) { + d.merge(n.Content[i+1], out) + continue + } + if !d.unmarshal(ni, name) { + continue + } + if info, ok := sinfo.FieldsMap[name.String()]; ok { + if d.uniqueKeys { + if doneFields[info.Id] { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.Line, name.String(), out.Type())) + continue + } + doneFields[info.Id] = true + } + var field reflect.Value + if info.Inline == nil { + field = out.Field(info.Num) + } else { + field = d.fieldByIndex(n, out, info.Inline) + } + d.unmarshal(n.Content[i+1], field) + } else if sinfo.InlineMap != -1 { + if inlineMap.IsNil() { + inlineMap.Set(reflect.MakeMap(inlineMap.Type())) + } + value := reflect.New(elemType).Elem() + d.unmarshal(n.Content[i+1], value) + inlineMap.SetMapIndex(name, value) + } else if d.knownFields { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.Line, name.String(), out.Type())) + } + } + return true +} + +func failWantMap() { + failf("map merge requires map or sequence of maps as the value") +} + +func (d *decoder) merge(n *Node, out reflect.Value) { + switch n.Kind { + case MappingNode: + d.unmarshal(n, out) + case AliasNode: + if n.Alias != nil && n.Alias.Kind != MappingNode { + failWantMap() + } + d.unmarshal(n, out) + case SequenceNode: + // Step backwards as earlier nodes take precedence. + for i := len(n.Content) - 1; i >= 0; i-- { + ni := n.Content[i] + if ni.Kind == AliasNode { + if ni.Alias != nil && ni.Alias.Kind != MappingNode { + failWantMap() + } + } else if ni.Kind != MappingNode { + failWantMap() + } + d.unmarshal(ni, out) + } + default: + failWantMap() + } +} + +func isMerge(n *Node) bool { + return n.Kind == ScalarNode && n.Value == "<<" && (n.Tag == "" || n.Tag == "!" || shortTag(n.Tag) == mergeTag) +} diff --git a/vendor/github.com/zclconf/go-cty-yaml/emitterc.go b/vendor/gopkg.in/yaml.v3/emitterc.go similarity index 82% rename from vendor/github.com/zclconf/go-cty-yaml/emitterc.go rename to vendor/gopkg.in/yaml.v3/emitterc.go index a1c2cc52627..ab2a066194c 100644 --- a/vendor/github.com/zclconf/go-cty-yaml/emitterc.go +++ b/vendor/gopkg.in/yaml.v3/emitterc.go @@ -1,3 +1,25 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + package yaml import ( @@ -43,8 +65,13 @@ func put_break(emitter *yaml_emitter_t) bool { default: panic("unknown line break setting") } + if emitter.column == 0 { + emitter.space_above = true + } emitter.column = 0 emitter.line++ + // [Go] Do this here and below and drop from everywhere else (see commented lines). + emitter.indention = true return true } @@ -97,8 +124,13 @@ func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { if !write(emitter, s, i) { return false } + if emitter.column == 0 { + emitter.space_above = true + } emitter.column = 0 emitter.line++ + // [Go] Do this here and above and drop from everywhere else (see commented lines). + emitter.indention = true } return true } @@ -204,6 +236,10 @@ func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool } } else if !indentless { emitter.indent += emitter.best_indent + // [Go] If inside a block sequence item, discount the space taken by the indicator. + if emitter.best_indent > 2 && emitter.states[len(emitter.states)-1] == yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE { + emitter.indent -= 2 + } } return true } @@ -228,16 +264,22 @@ func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bo return yaml_emitter_emit_document_end(emitter, event) case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, true) + return yaml_emitter_emit_flow_sequence_item(emitter, event, true, false) + + case yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE: + return yaml_emitter_emit_flow_sequence_item(emitter, event, false, true) case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, false) + return yaml_emitter_emit_flow_sequence_item(emitter, event, false, false) case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, true) + return yaml_emitter_emit_flow_mapping_key(emitter, event, true, false) + + case yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE: + return yaml_emitter_emit_flow_mapping_key(emitter, event, false, true) case yaml_EMIT_FLOW_MAPPING_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, false) + return yaml_emitter_emit_flow_mapping_key(emitter, event, false, false) case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: return yaml_emitter_emit_flow_mapping_value(emitter, event, true) @@ -298,6 +340,8 @@ func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t emitter.column = 0 emitter.whitespace = true emitter.indention = true + emitter.space_above = true + emitter.foot_indent = -1 if emitter.encoding != yaml_UTF8_ENCODING { if !yaml_emitter_write_bom(emitter) { @@ -392,13 +436,22 @@ func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { return false } - if emitter.canonical { + if emitter.canonical || true { if !yaml_emitter_write_indent(emitter) { return false } } } + if len(emitter.head_comment) > 0 { + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if !put_break(emitter) { + return false + } + } + emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE return true } @@ -425,7 +478,20 @@ func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event // Expect the root node. func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) - return yaml_emitter_emit_node(emitter, event, true, false, false, false) + + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if !yaml_emitter_emit_node(emitter, event, true, false, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true } // Expect DOCUMENT-END. @@ -433,6 +499,12 @@ func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t if event.typ != yaml_DOCUMENT_END_EVENT { return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") } + // [Go] Force document foot separation. + emitter.foot_indent = 0 + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + emitter.foot_indent = -1 if !yaml_emitter_write_indent(emitter) { return false } @@ -454,7 +526,7 @@ func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t } // Expect a flow item node. -func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { +func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { if first { if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { return false @@ -466,13 +538,15 @@ func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_e } if event.typ == yaml_SEQUENCE_END_EVENT { - emitter.flow_level-- - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - if emitter.canonical && !first { + if emitter.canonical && !first && !trail { if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { return false } + } + emitter.flow_level-- + emitter.indent = emitter.indents[len(emitter.indents)-1] + emitter.indents = emitter.indents[:len(emitter.indents)-1] + if emitter.column == 0 || emitter.canonical && !first { if !yaml_emitter_write_indent(emitter) { return false } @@ -480,29 +554,62 @@ func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_e if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { return false } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } emitter.state = emitter.states[len(emitter.states)-1] emitter.states = emitter.states[:len(emitter.states)-1] return true } - if !first { + if !first && !trail { if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { return false } } + if !yaml_emitter_process_head_comment(emitter) { + return false + } + if emitter.column == 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if emitter.canonical || emitter.column > emitter.best_width { if !yaml_emitter_write_indent(emitter) { return false } } - emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) - return yaml_emitter_emit_node(emitter, event, false, true, false, false) + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE) + } else { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) + } + if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { + return false + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true } // Expect a flow key node. -func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { +func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { if first { if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { return false @@ -514,13 +621,18 @@ func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_eve } if event.typ == yaml_MAPPING_END_EVENT { + if (emitter.canonical || len(emitter.head_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0) && !first && !trail { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_head_comment(emitter) { + return false + } emitter.flow_level-- emitter.indent = emitter.indents[len(emitter.indents)-1] emitter.indents = emitter.indents[:len(emitter.indents)-1] if emitter.canonical && !first { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } if !yaml_emitter_write_indent(emitter) { return false } @@ -528,16 +640,33 @@ func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_eve if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { return false } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } emitter.state = emitter.states[len(emitter.states)-1] emitter.states = emitter.states[:len(emitter.states)-1] return true } - if !first { + if !first && !trail { if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { return false } } + + if !yaml_emitter_process_head_comment(emitter) { + return false + } + + if emitter.column == 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + } + if emitter.canonical || emitter.column > emitter.best_width { if !yaml_emitter_write_indent(emitter) { return false @@ -571,16 +700,41 @@ func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_e return false } } - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE) + } else { + emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) + } + if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { + return false + } + if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { + return false + } + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true } // Expect a block item node. func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { if first { - if !yaml_emitter_increase_indent(emitter, false, emitter.mapping_context && !emitter.indention) { + // [Go] The original logic here would not indent the sequence when inside a mapping. + // In Go we always indent it, but take the sequence indicator out of the indentation. + indentless := emitter.best_indent == 2 && emitter.mapping_context && (emitter.column == 0 || !emitter.indention) + original := emitter.indent + if !yaml_emitter_increase_indent(emitter, false, indentless) { return false } + if emitter.indent > original+2 { + emitter.indent -= 2 + } } if event.typ == yaml_SEQUENCE_END_EVENT { emitter.indent = emitter.indents[len(emitter.indents)-1] @@ -589,6 +743,9 @@ func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_ emitter.states = emitter.states[:len(emitter.states)-1] return true } + if !yaml_emitter_process_head_comment(emitter) { + return false + } if !yaml_emitter_write_indent(emitter) { return false } @@ -596,7 +753,16 @@ func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_ return false } emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) - return yaml_emitter_emit_node(emitter, event, false, true, false, false) + if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true } // Expect a block key node. @@ -606,6 +772,9 @@ func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_ev return false } } + if !yaml_emitter_process_head_comment(emitter) { + return false + } if event.typ == yaml_MAPPING_END_EVENT { emitter.indent = emitter.indents[len(emitter.indents)-1] emitter.indents = emitter.indents[:len(emitter.indents)-1] @@ -642,7 +811,16 @@ func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_ } } emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) + if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { + return false + } + if !yaml_emitter_process_line_comment(emitter) { + return false + } + if !yaml_emitter_process_foot_comment(emitter) { + return false + } + return true } // Expect a node. @@ -908,6 +1086,71 @@ func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { panic("unknown scalar style") } +// Write a head comment. +func yaml_emitter_process_head_comment(emitter *yaml_emitter_t) bool { + if len(emitter.tail_comment) > 0 { + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.tail_comment) { + return false + } + emitter.tail_comment = emitter.tail_comment[:0] + emitter.foot_indent = emitter.indent + if emitter.foot_indent < 0 { + emitter.foot_indent = 0 + } + } + + if len(emitter.head_comment) == 0 { + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.head_comment) { + return false + } + emitter.head_comment = emitter.head_comment[:0] + return true +} + +// Write an line comment. +func yaml_emitter_process_line_comment(emitter *yaml_emitter_t) bool { + if len(emitter.line_comment) == 0 { + return true + } + if !emitter.whitespace { + if !put(emitter, ' ') { + return false + } + } + if !yaml_emitter_write_comment(emitter, emitter.line_comment) { + return false + } + emitter.line_comment = emitter.line_comment[:0] + return true +} + +// Write a foot comment. +func yaml_emitter_process_foot_comment(emitter *yaml_emitter_t) bool { + if len(emitter.foot_comment) == 0 { + return true + } + if !yaml_emitter_write_indent(emitter) { + return false + } + if !yaml_emitter_write_comment(emitter, emitter.foot_comment) { + return false + } + emitter.foot_comment = emitter.foot_comment[:0] + emitter.foot_indent = emitter.indent + if emitter.foot_indent < 0 { + emitter.foot_indent = 0 + } + return true +} + // Check if a %YAML directive is valid. func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { if version_directive.major != 1 || version_directive.minor != 1 { @@ -987,6 +1230,7 @@ func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { flow_indicators = false line_breaks = false special_characters = false + tab_characters = false leading_space = false leading_break = false @@ -1055,7 +1299,9 @@ func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { } } - if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { + if value[i] == '\t' { + tab_characters = true + } else if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { special_characters = true } if is_space(value, i) { @@ -1110,10 +1356,12 @@ func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { emitter.scalar_data.block_plain_allowed = false emitter.scalar_data.single_quoted_allowed = false } - if space_break || special_characters { + if space_break || tab_characters || special_characters { emitter.scalar_data.flow_plain_allowed = false emitter.scalar_data.block_plain_allowed = false emitter.scalar_data.single_quoted_allowed = false + } + if space_break || special_characters { emitter.scalar_data.block_allowed = false } if line_breaks { @@ -1137,6 +1385,19 @@ func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bo emitter.tag_data.suffix = nil emitter.scalar_data.value = nil + if len(event.head_comment) > 0 { + emitter.head_comment = event.head_comment + } + if len(event.line_comment) > 0 { + emitter.line_comment = event.line_comment + } + if len(event.foot_comment) > 0 { + emitter.foot_comment = event.foot_comment + } + if len(event.tail_comment) > 0 { + emitter.tail_comment = event.tail_comment + } + switch event.typ { case yaml_ALIAS_EVENT: if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { @@ -1208,13 +1469,20 @@ func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { return false } } + if emitter.foot_indent == indent { + if !put_break(emitter) { + return false + } + } for emitter.column < indent { if !put(emitter, ' ') { return false } } emitter.whitespace = true - emitter.indention = true + //emitter.indention = true + emitter.space_above = false + emitter.foot_indent = -1 return true } @@ -1311,7 +1579,7 @@ func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_ } func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - if !emitter.whitespace { + if len(value) > 0 && !emitter.whitespace { if !put(emitter, ' ') { return false } @@ -1341,7 +1609,7 @@ func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allo if !write_break(emitter, value, &i) { return false } - emitter.indention = true + //emitter.indention = true breaks = true } else { if breaks { @@ -1358,7 +1626,9 @@ func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allo } } - emitter.whitespace = false + if len(value) > 0 { + emitter.whitespace = false + } emitter.indention = false if emitter.root_context { emitter.open_ended = true @@ -1397,7 +1667,7 @@ func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []by if !write_break(emitter, value, &i) { return false } - emitter.indention = true + //emitter.indention = true breaks = true } else { if breaks { @@ -1599,7 +1869,7 @@ func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bo if !put_break(emitter) { return false } - emitter.indention = true + //emitter.indention = true emitter.whitespace = true breaks := true for i := 0; i < len(value); { @@ -1607,7 +1877,7 @@ func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bo if !write_break(emitter, value, &i) { return false } - emitter.indention = true + //emitter.indention = true breaks = true } else { if breaks { @@ -1637,7 +1907,7 @@ func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) boo if !put_break(emitter) { return false } - emitter.indention = true + //emitter.indention = true emitter.whitespace = true breaks := true @@ -1658,7 +1928,7 @@ func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) boo if !write_break(emitter, value, &i) { return false } - emitter.indention = true + //emitter.indention = true breaks = true } else { if breaks { @@ -1683,3 +1953,40 @@ func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) boo } return true } + +func yaml_emitter_write_comment(emitter *yaml_emitter_t, comment []byte) bool { + breaks := false + pound := false + for i := 0; i < len(comment); { + if is_break(comment, i) { + if !write_break(emitter, comment, &i) { + return false + } + //emitter.indention = true + breaks = true + pound = false + } else { + if breaks && !yaml_emitter_write_indent(emitter) { + return false + } + if !pound { + if comment[i] != '#' && (!put(emitter, '#') || !put(emitter, ' ')) { + return false + } + pound = true + } + if !write(emitter, comment, &i) { + return false + } + emitter.indention = false + breaks = false + } + } + if !breaks && !put_break(emitter) { + return false + } + + emitter.whitespace = true + //emitter.indention = true + return true +} diff --git a/vendor/gopkg.in/yaml.v3/encode.go b/vendor/gopkg.in/yaml.v3/encode.go new file mode 100644 index 00000000000..1f37271ce45 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/encode.go @@ -0,0 +1,561 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// 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 yaml + +import ( + "encoding" + "fmt" + "io" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +type encoder struct { + emitter yaml_emitter_t + event yaml_event_t + out []byte + flow bool + indent int + doneInit bool +} + +func newEncoder() *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_string(&e.emitter, &e.out) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func newEncoderWithWriter(w io.Writer) *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_writer(&e.emitter, w) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func (e *encoder) init() { + if e.doneInit { + return + } + if e.indent == 0 { + e.indent = 4 + } + e.emitter.best_indent = e.indent + yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) + e.emit() + e.doneInit = true +} + +func (e *encoder) finish() { + e.emitter.open_ended = false + yaml_stream_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) destroy() { + yaml_emitter_delete(&e.emitter) +} + +func (e *encoder) emit() { + // This will internally delete the e.event value. + e.must(yaml_emitter_emit(&e.emitter, &e.event)) +} + +func (e *encoder) must(ok bool) { + if !ok { + msg := e.emitter.problem + if msg == "" { + msg = "unknown problem generating YAML content" + } + failf("%s", msg) + } +} + +func (e *encoder) marshalDoc(tag string, in reflect.Value) { + e.init() + var node *Node + if in.IsValid() { + node, _ = in.Interface().(*Node) + } + if node != nil && node.Kind == DocumentNode { + e.nodev(in) + } else { + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.emit() + e.marshal(tag, in) + yaml_document_end_event_initialize(&e.event, true) + e.emit() + } +} + +func (e *encoder) marshal(tag string, in reflect.Value) { + tag = shortTag(tag) + if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { + e.nilv() + return + } + iface := in.Interface() + switch value := iface.(type) { + case *Node: + e.nodev(in) + return + case time.Time: + e.timev(tag, in) + return + case *time.Time: + e.timev(tag, in.Elem()) + return + case time.Duration: + e.stringv(tag, reflect.ValueOf(value.String())) + return + case Marshaler: + v, err := value.MarshalYAML() + if err != nil { + fail(err) + } + if v == nil { + e.nilv() + return + } + e.marshal(tag, reflect.ValueOf(v)) + return + case encoding.TextMarshaler: + text, err := value.MarshalText() + if err != nil { + fail(err) + } + in = reflect.ValueOf(string(text)) + case nil: + e.nilv() + return + } + switch in.Kind() { + case reflect.Interface: + e.marshal(tag, in.Elem()) + case reflect.Map: + e.mapv(tag, in) + case reflect.Ptr: + e.marshal(tag, in.Elem()) + case reflect.Struct: + e.structv(tag, in) + case reflect.Slice, reflect.Array: + e.slicev(tag, in) + case reflect.String: + e.stringv(tag, in) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + e.intv(tag, in) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + e.uintv(tag, in) + case reflect.Float32, reflect.Float64: + e.floatv(tag, in) + case reflect.Bool: + e.boolv(tag, in) + default: + panic("cannot marshal type: " + in.Type().String()) + } +} + +func (e *encoder) mapv(tag string, in reflect.Value) { + e.mappingv(tag, func() { + keys := keyList(in.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + e.marshal("", k) + e.marshal("", in.MapIndex(k)) + } + }) +} + +func (e *encoder) fieldByIndex(v reflect.Value, index []int) (field reflect.Value) { + for _, num := range index { + for { + if v.Kind() == reflect.Ptr { + if v.IsNil() { + return reflect.Value{} + } + v = v.Elem() + continue + } + break + } + v = v.Field(num) + } + return v +} + +func (e *encoder) structv(tag string, in reflect.Value) { + sinfo, err := getStructInfo(in.Type()) + if err != nil { + panic(err) + } + e.mappingv(tag, func() { + for _, info := range sinfo.FieldsList { + var value reflect.Value + if info.Inline == nil { + value = in.Field(info.Num) + } else { + value = e.fieldByIndex(in, info.Inline) + if !value.IsValid() { + continue + } + } + if info.OmitEmpty && isZero(value) { + continue + } + e.marshal("", reflect.ValueOf(info.Key)) + e.flow = info.Flow + e.marshal("", value) + } + if sinfo.InlineMap >= 0 { + m := in.Field(sinfo.InlineMap) + if m.Len() > 0 { + e.flow = false + keys := keyList(m.MapKeys()) + sort.Sort(keys) + for _, k := range keys { + if _, found := sinfo.FieldsMap[k.String()]; found { + panic(fmt.Sprintf("cannot have key %q in inlined map: conflicts with struct field", k.String())) + } + e.marshal("", k) + e.flow = false + e.marshal("", m.MapIndex(k)) + } + } + } + }) +} + +func (e *encoder) mappingv(tag string, f func()) { + implicit := tag == "" + style := yaml_BLOCK_MAPPING_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) + e.emit() + f() + yaml_mapping_end_event_initialize(&e.event) + e.emit() +} + +func (e *encoder) slicev(tag string, in reflect.Value) { + implicit := tag == "" + style := yaml_BLOCK_SEQUENCE_STYLE + if e.flow { + e.flow = false + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) + e.emit() + n := in.Len() + for i := 0; i < n; i++ { + e.marshal("", in.Index(i)) + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.emit() +} + +// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. +// +// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported +// in YAML 1.2 and by this package, but these should be marshalled quoted for +// the time being for compatibility with other parsers. +func isBase60Float(s string) (result bool) { + // Fast path. + if s == "" { + return false + } + c := s[0] + if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { + return false + } + // Do the full match. + return base60float.MatchString(s) +} + +// From http://yaml.org/type/float.html, except the regular expression there +// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. +var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) + +// isOldBool returns whether s is bool notation as defined in YAML 1.1. +// +// We continue to force strings that YAML 1.1 would interpret as booleans to be +// rendered as quotes strings so that the marshalled output valid for YAML 1.1 +// parsing. +func isOldBool(s string) (result bool) { + switch s { + case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON", + "n", "N", "no", "No", "NO", "off", "Off", "OFF": + return true + default: + return false + } +} + +func (e *encoder) stringv(tag string, in reflect.Value) { + var style yaml_scalar_style_t + s := in.String() + canUsePlain := true + switch { + case !utf8.ValidString(s): + if tag == binaryTag { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if tag != "" { + failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = binaryTag + s = encodeBase64(s) + case tag == "": + // Check to see if it would resolve to a specific + // tag when encoded unquoted. If it doesn't, + // there's no need to quote it. + rtag, _ := resolve("", s) + canUsePlain = rtag == strTag && !(isBase60Float(s) || isOldBool(s)) + } + // Note: it's possible for user code to emit invalid YAML + // if they explicitly specify a tag and a string containing + // text that's incompatible with that tag. + switch { + case strings.Contains(s, "\n"): + if e.flow { + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } else { + style = yaml_LITERAL_SCALAR_STYLE + } + case canUsePlain: + style = yaml_PLAIN_SCALAR_STYLE + default: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + e.emitScalar(s, "", tag, style, nil, nil, nil, nil) +} + +func (e *encoder) boolv(tag string, in reflect.Value) { + var s string + if in.Bool() { + s = "true" + } else { + s = "false" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) intv(tag string, in reflect.Value) { + s := strconv.FormatInt(in.Int(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) uintv(tag string, in reflect.Value) { + s := strconv.FormatUint(in.Uint(), 10) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) timev(tag string, in reflect.Value) { + t := in.Interface().(time.Time) + s := t.Format(time.RFC3339Nano) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) floatv(tag string, in reflect.Value) { + // Issue #352: When formatting, use the precision of the underlying value + precision := 64 + if in.Kind() == reflect.Float32 { + precision = 32 + } + + s := strconv.FormatFloat(in.Float(), 'g', -1, precision) + switch s { + case "+Inf": + s = ".inf" + case "-Inf": + s = "-.inf" + case "NaN": + s = ".nan" + } + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) nilv() { + e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) +} + +func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t, head, line, foot, tail []byte) { + // TODO Kill this function. Replace all initialize calls by their underlining Go literals. + implicit := tag == "" + if !implicit { + tag = longTag(tag) + } + e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) + e.event.head_comment = head + e.event.line_comment = line + e.event.foot_comment = foot + e.event.tail_comment = tail + e.emit() +} + +func (e *encoder) nodev(in reflect.Value) { + e.node(in.Interface().(*Node), "") +} + +func (e *encoder) node(node *Node, tail string) { + // If the tag was not explicitly requested, and dropping it won't change the + // implicit tag of the value, don't include it in the presentation. + var tag = node.Tag + var stag = shortTag(tag) + var rtag string + var forceQuoting bool + if tag != "" && node.Style&TaggedStyle == 0 { + if node.Kind == ScalarNode { + if stag == strTag && node.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0 { + tag = "" + } else { + rtag, _ = resolve("", node.Value) + if rtag == stag { + tag = "" + } else if stag == strTag { + tag = "" + forceQuoting = true + } + } + } else { + switch node.Kind { + case MappingNode: + rtag = mapTag + case SequenceNode: + rtag = seqTag + } + if rtag == stag { + tag = "" + } + } + } + + switch node.Kind { + case DocumentNode: + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.event.head_comment = []byte(node.HeadComment) + e.emit() + for _, node := range node.Content { + e.node(node, "") + } + yaml_document_end_event_initialize(&e.event, true) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case SequenceNode: + style := yaml_BLOCK_SEQUENCE_STYLE + if node.Style&FlowStyle != 0 { + style = yaml_FLOW_SEQUENCE_STYLE + } + e.must(yaml_sequence_start_event_initialize(&e.event, []byte(node.Anchor), []byte(tag), tag == "", style)) + e.event.head_comment = []byte(node.HeadComment) + e.emit() + for _, node := range node.Content { + e.node(node, "") + } + e.must(yaml_sequence_end_event_initialize(&e.event)) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case MappingNode: + style := yaml_BLOCK_MAPPING_STYLE + if node.Style&FlowStyle != 0 { + style = yaml_FLOW_MAPPING_STYLE + } + yaml_mapping_start_event_initialize(&e.event, []byte(node.Anchor), []byte(tag), tag == "", style) + e.event.tail_comment = []byte(tail) + e.event.head_comment = []byte(node.HeadComment) + e.emit() + + // The tail logic below moves the foot comment of prior keys to the following key, + // since the value for each key may be a nested structure and the foot needs to be + // processed only the entirety of the value is streamed. The last tail is processed + // with the mapping end event. + var tail string + for i := 0; i+1 < len(node.Content); i += 2 { + k := node.Content[i] + foot := k.FootComment + if foot != "" { + kopy := *k + kopy.FootComment = "" + k = &kopy + } + e.node(k, tail) + tail = foot + + v := node.Content[i+1] + e.node(v, "") + } + + yaml_mapping_end_event_initialize(&e.event) + e.event.tail_comment = []byte(tail) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case AliasNode: + yaml_alias_event_initialize(&e.event, []byte(node.Value)) + e.event.head_comment = []byte(node.HeadComment) + e.event.line_comment = []byte(node.LineComment) + e.event.foot_comment = []byte(node.FootComment) + e.emit() + + case ScalarNode: + value := node.Value + if !utf8.ValidString(value) { + if tag == binaryTag { + failf("explicitly tagged !!binary data must be base64-encoded") + } + if tag != "" { + failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) + } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = binaryTag + value = encodeBase64(value) + } + + style := yaml_PLAIN_SCALAR_STYLE + switch { + case node.Style&DoubleQuotedStyle != 0: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + case node.Style&SingleQuotedStyle != 0: + style = yaml_SINGLE_QUOTED_SCALAR_STYLE + case node.Style&LiteralStyle != 0: + style = yaml_LITERAL_SCALAR_STYLE + case node.Style&FoldedStyle != 0: + style = yaml_FOLDED_SCALAR_STYLE + case strings.Contains(value, "\n"): + style = yaml_LITERAL_SCALAR_STYLE + case forceQuoting: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE + } + + e.emitScalar(value, node.Anchor, tag, style, []byte(node.HeadComment), []byte(node.LineComment), []byte(node.FootComment), []byte(tail)) + } +} diff --git a/vendor/gopkg.in/yaml.v3/go.mod b/vendor/gopkg.in/yaml.v3/go.mod new file mode 100644 index 00000000000..f407ea3213e --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/go.mod @@ -0,0 +1,5 @@ +module "gopkg.in/yaml.v3" + +require ( + "gopkg.in/check.v1" v0.0.0-20161208181325-20d25e280405 +) diff --git a/vendor/github.com/zclconf/go-cty-yaml/parserc.go b/vendor/gopkg.in/yaml.v3/parserc.go similarity index 86% rename from vendor/github.com/zclconf/go-cty-yaml/parserc.go rename to vendor/gopkg.in/yaml.v3/parserc.go index 81d05dfe573..aea9050b833 100644 --- a/vendor/github.com/zclconf/go-cty-yaml/parserc.go +++ b/vendor/gopkg.in/yaml.v3/parserc.go @@ -1,3 +1,25 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + package yaml import ( @@ -45,11 +67,46 @@ import ( // Peek the next token in the token queue. func peek_token(parser *yaml_parser_t) *yaml_token_t { if parser.token_available || yaml_parser_fetch_more_tokens(parser) { - return &parser.tokens[parser.tokens_head] + token := &parser.tokens[parser.tokens_head] + yaml_parser_unfold_comments(parser, token) + return token } return nil } +// yaml_parser_unfold_comments walks through the comments queue and joins all +// comments behind the position of the provided token into the respective +// top-level comment slices in the parser. +func yaml_parser_unfold_comments(parser *yaml_parser_t, token *yaml_token_t) { + for parser.comments_head < len(parser.comments) && token.start_mark.index >= parser.comments[parser.comments_head].token_mark.index { + comment := &parser.comments[parser.comments_head] + if len(comment.head) > 0 { + if token.typ == yaml_BLOCK_END_TOKEN { + // No heads on ends, so keep comment.head for a follow up token. + break + } + if len(parser.head_comment) > 0 { + parser.head_comment = append(parser.head_comment, '\n') + } + parser.head_comment = append(parser.head_comment, comment.head...) + } + if len(comment.foot) > 0 { + if len(parser.foot_comment) > 0 { + parser.foot_comment = append(parser.foot_comment, '\n') + } + parser.foot_comment = append(parser.foot_comment, comment.foot...) + } + if len(comment.line) > 0 { + if len(parser.line_comment) > 0 { + parser.line_comment = append(parser.line_comment, '\n') + } + parser.line_comment = append(parser.line_comment, comment.line...) + } + *comment = yaml_comment_t{} + parser.comments_head++ + } +} + // Remove the next token from the queue (must be called after peek_token). func skip_token(parser *yaml_parser_t) { parser.token_available = false @@ -224,10 +281,32 @@ func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) parser.state = yaml_PARSE_BLOCK_NODE_STATE + var head_comment []byte + if len(parser.head_comment) > 0 { + // [Go] Scan the header comment backwards, and if an empty line is found, break + // the header so the part before the last empty line goes into the + // document header, while the bottom of it goes into a follow up event. + for i := len(parser.head_comment) - 1; i > 0; i-- { + if parser.head_comment[i] == '\n' { + if i == len(parser.head_comment)-1 { + head_comment = parser.head_comment[:i] + parser.head_comment = parser.head_comment[i+1:] + break + } else if parser.head_comment[i-1] == '\n' { + head_comment = parser.head_comment[:i-1] + parser.head_comment = parser.head_comment[i+1:] + break + } + } + } + } + *event = yaml_event_t{ typ: yaml_DOCUMENT_START_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, + + head_comment: head_comment, } } else if token.typ != yaml_STREAM_END_TOKEN { @@ -284,6 +363,7 @@ func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event if token == nil { return false } + if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN || token.typ == yaml_DOCUMENT_START_TOKEN || @@ -327,9 +407,25 @@ func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) end_mark: end_mark, implicit: implicit, } + yaml_parser_set_event_comments(parser, event) + if len(event.head_comment) > 0 && len(event.foot_comment) == 0 { + event.foot_comment = event.head_comment + event.head_comment = nil + } return true } +func yaml_parser_set_event_comments(parser *yaml_parser_t, event *yaml_event_t) { + event.head_comment = parser.head_comment + event.line_comment = parser.line_comment + event.foot_comment = parser.foot_comment + parser.head_comment = nil + parser.line_comment = nil + parser.foot_comment = nil + parser.tail_comment = nil + parser.stem_comment = nil +} + // Parse the productions: // block_node_or_indentless_sequence ::= // ALIAS @@ -373,6 +469,7 @@ func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, i end_mark: token.end_mark, anchor: token.value, } + yaml_parser_set_event_comments(parser, event) skip_token(parser) return true } @@ -486,6 +583,7 @@ func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, i quoted_implicit: quoted_implicit, style: yaml_style_t(token.style), } + yaml_parser_set_event_comments(parser, event) skip_token(parser) return true } @@ -502,6 +600,7 @@ func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, i implicit: implicit, style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), } + yaml_parser_set_event_comments(parser, event) return true } if token.typ == yaml_FLOW_MAPPING_START_TOKEN { @@ -516,6 +615,7 @@ func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, i implicit: implicit, style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), } + yaml_parser_set_event_comments(parser, event) return true } if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { @@ -530,6 +630,10 @@ func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, i implicit: implicit, style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), } + if parser.stem_comment != nil { + event.head_comment = parser.stem_comment + parser.stem_comment = nil + } return true } if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { @@ -590,11 +694,25 @@ func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_e if token.typ == yaml_BLOCK_ENTRY_TOKEN { mark := token.end_mark + prior_head := len(parser.head_comment) skip_token(parser) token = peek_token(parser) if token == nil { return false } + if prior_head > 0 && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { + // [Go] It's a sequence under a sequence entry, so the former head comment + // is for the list itself, not the first list item under it. + parser.stem_comment = parser.head_comment[:prior_head] + if len(parser.head_comment) == prior_head { + parser.head_comment = nil + } else { + // Copy suffix to prevent very strange bugs if someone ever appends + // further bytes to the prefix in the stem_comment slice above. + parser.head_comment = append([]byte(nil), parser.head_comment[prior_head+1:]...) + } + + } if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) return yaml_parser_parse_node(parser, event, true, false) @@ -684,6 +802,19 @@ func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_even return false } + // [Go] A tail comment was left from the prior mapping value processed. Emit an event + // as it needs to be processed with that value and not the following key. + if len(parser.tail_comment) > 0 { + *event = yaml_event_t{ + typ: yaml_TAIL_COMMENT_EVENT, + start_mark: token.start_mark, + end_mark: token.end_mark, + foot_comment: parser.tail_comment, + } + parser.tail_comment = nil + return true + } + if token.typ == yaml_KEY_TOKEN { mark := token.end_mark skip_token(parser) @@ -709,6 +840,7 @@ func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_even start_mark: token.start_mark, end_mark: token.end_mark, } + yaml_parser_set_event_comments(parser, event) skip_token(parser) return true } @@ -820,6 +952,7 @@ func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_ev start_mark: token.start_mark, end_mark: token.end_mark, } + yaml_parser_set_event_comments(parser, event) skip_token(parser) return true @@ -959,6 +1092,7 @@ func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event start_mark: token.start_mark, end_mark: token.end_mark, } + yaml_parser_set_event_comments(parser, event) skip_token(parser) return true } diff --git a/vendor/github.com/zclconf/go-cty-yaml/readerc.go b/vendor/gopkg.in/yaml.v3/readerc.go similarity index 91% rename from vendor/github.com/zclconf/go-cty-yaml/readerc.go rename to vendor/gopkg.in/yaml.v3/readerc.go index 7c1f5fac3db..b7de0a89c46 100644 --- a/vendor/github.com/zclconf/go-cty-yaml/readerc.go +++ b/vendor/gopkg.in/yaml.v3/readerc.go @@ -1,3 +1,25 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + package yaml import ( @@ -95,7 +117,7 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { // [Go] This function was changed to guarantee the requested length size at EOF. // The fact we need to do this is pretty awful, but the description above implies - // for that to be the case, and there are tests + // for that to be the case, and there are tests // If the EOF flag is set and the raw buffer is empty, do nothing. if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { diff --git a/vendor/gopkg.in/yaml.v3/resolve.go b/vendor/gopkg.in/yaml.v3/resolve.go new file mode 100644 index 00000000000..64ae888057a --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/resolve.go @@ -0,0 +1,326 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// 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 yaml + +import ( + "encoding/base64" + "math" + "regexp" + "strconv" + "strings" + "time" +) + +type resolveMapItem struct { + value interface{} + tag string +} + +var resolveTable = make([]byte, 256) +var resolveMap = make(map[string]resolveMapItem) + +func init() { + t := resolveTable + t[int('+')] = 'S' // Sign + t[int('-')] = 'S' + for _, c := range "0123456789" { + t[int(c)] = 'D' // Digit + } + for _, c := range "yYnNtTfFoO~" { + t[int(c)] = 'M' // In map + } + t[int('.')] = '.' // Float (potentially in map) + + var resolveMapList = []struct { + v interface{} + tag string + l []string + }{ + {true, boolTag, []string{"true", "True", "TRUE"}}, + {false, boolTag, []string{"false", "False", "FALSE"}}, + {nil, nullTag, []string{"", "~", "null", "Null", "NULL"}}, + {math.NaN(), floatTag, []string{".nan", ".NaN", ".NAN"}}, + {math.Inf(+1), floatTag, []string{".inf", ".Inf", ".INF"}}, + {math.Inf(+1), floatTag, []string{"+.inf", "+.Inf", "+.INF"}}, + {math.Inf(-1), floatTag, []string{"-.inf", "-.Inf", "-.INF"}}, + {"<<", mergeTag, []string{"<<"}}, + } + + m := resolveMap + for _, item := range resolveMapList { + for _, s := range item.l { + m[s] = resolveMapItem{item.v, item.tag} + } + } +} + +const ( + nullTag = "!!null" + boolTag = "!!bool" + strTag = "!!str" + intTag = "!!int" + floatTag = "!!float" + timestampTag = "!!timestamp" + seqTag = "!!seq" + mapTag = "!!map" + binaryTag = "!!binary" + mergeTag = "!!merge" +) + +var longTags = make(map[string]string) +var shortTags = make(map[string]string) + +func init() { + for _, stag := range []string{nullTag, boolTag, strTag, intTag, floatTag, timestampTag, seqTag, mapTag, binaryTag, mergeTag} { + ltag := longTag(stag) + longTags[stag] = ltag + shortTags[ltag] = stag + } +} + +const longTagPrefix = "tag:yaml.org,2002:" + +func shortTag(tag string) string { + if strings.HasPrefix(tag, longTagPrefix) { + if stag, ok := shortTags[tag]; ok { + return stag + } + return "!!" + tag[len(longTagPrefix):] + } + return tag +} + +func longTag(tag string) string { + if strings.HasPrefix(tag, "!!") { + if ltag, ok := longTags[tag]; ok { + return ltag + } + return longTagPrefix + tag[2:] + } + return tag +} + +func resolvableTag(tag string) bool { + switch tag { + case "", strTag, boolTag, intTag, floatTag, nullTag, timestampTag: + return true + } + return false +} + +var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) + +func resolve(tag string, in string) (rtag string, out interface{}) { + tag = shortTag(tag) + if !resolvableTag(tag) { + return tag, in + } + + defer func() { + switch tag { + case "", rtag, strTag, binaryTag: + return + case floatTag: + if rtag == intTag { + switch v := out.(type) { + case int64: + rtag = floatTag + out = float64(v) + return + case int: + rtag = floatTag + out = float64(v) + return + } + } + } + failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) + }() + + // Any data is accepted as a !!str or !!binary. + // Otherwise, the prefix is enough of a hint about what it might be. + hint := byte('N') + if in != "" { + hint = resolveTable[in[0]] + } + if hint != 0 && tag != strTag && tag != binaryTag { + // Handle things we can lookup in a map. + if item, ok := resolveMap[in]; ok { + return item.tag, item.value + } + + // Base 60 floats are a bad idea, were dropped in YAML 1.2, and + // are purposefully unsupported here. They're still quoted on + // the way out for compatibility with other parser, though. + + switch hint { + case 'M': + // We've already checked the map above. + + case '.': + // Not in the map, so maybe a normal float. + floatv, err := strconv.ParseFloat(in, 64) + if err == nil { + return floatTag, floatv + } + + case 'D', 'S': + // Int, float, or timestamp. + // Only try values as a timestamp if the value is unquoted or there's an explicit + // !!timestamp tag. + if tag == "" || tag == timestampTag { + t, ok := parseTimestamp(in) + if ok { + return timestampTag, t + } + } + + plain := strings.Replace(in, "_", "", -1) + intv, err := strconv.ParseInt(plain, 0, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain, 0, 64) + if err == nil { + return intTag, uintv + } + if yamlStyleFloat.MatchString(plain) { + floatv, err := strconv.ParseFloat(plain, 64) + if err == nil { + return floatTag, floatv + } + } + if strings.HasPrefix(plain, "0b") { + intv, err := strconv.ParseInt(plain[2:], 2, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 2, 64) + if err == nil { + return intTag, uintv + } + } else if strings.HasPrefix(plain, "-0b") { + intv, err := strconv.ParseInt("-"+plain[3:], 2, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + } + // Octals as introduced in version 1.2 of the spec. + // Octals from the 1.1 spec, spelled as 0777, are still + // decoded by default in v3 as well for compatibility. + // May be dropped in v4 depending on how usage evolves. + if strings.HasPrefix(plain, "0o") { + intv, err := strconv.ParseInt(plain[2:], 8, 64) + if err == nil { + if intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + uintv, err := strconv.ParseUint(plain[2:], 8, 64) + if err == nil { + return intTag, uintv + } + } else if strings.HasPrefix(plain, "-0o") { + intv, err := strconv.ParseInt("-"+plain[3:], 8, 64) + if err == nil { + if true || intv == int64(int(intv)) { + return intTag, int(intv) + } else { + return intTag, intv + } + } + } + default: + panic("internal error: missing handler for resolver table: " + string(rune(hint)) + " (with " + in + ")") + } + } + return strTag, in +} + +// encodeBase64 encodes s as base64 that is broken up into multiple lines +// as appropriate for the resulting length. +func encodeBase64(s string) string { + const lineLen = 70 + encLen := base64.StdEncoding.EncodedLen(len(s)) + lines := encLen/lineLen + 1 + buf := make([]byte, encLen*2+lines) + in := buf[0:encLen] + out := buf[encLen:] + base64.StdEncoding.Encode(in, []byte(s)) + k := 0 + for i := 0; i < len(in); i += lineLen { + j := i + lineLen + if j > len(in) { + j = len(in) + } + k += copy(out[k:], in[i:j]) + if lines > 1 { + out[k] = '\n' + k++ + } + } + return string(out[:k]) +} + +// This is a subset of the formats allowed by the regular expression +// defined at http://yaml.org/type/timestamp.html. +var allowedTimestampFormats = []string{ + "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. + "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". + "2006-1-2 15:4:5.999999999", // space separated with no time zone + "2006-1-2", // date only + // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" + // from the set of examples. +} + +// parseTimestamp parses s as a timestamp string and +// returns the timestamp and reports whether it succeeded. +// Timestamp formats are defined at http://yaml.org/type/timestamp.html +func parseTimestamp(s string) (time.Time, bool) { + // TODO write code to check all the formats supported by + // http://yaml.org/type/timestamp.html instead of using time.Parse. + + // Quick check: all date formats start with YYYY-. + i := 0 + for ; i < len(s); i++ { + if c := s[i]; c < '0' || c > '9' { + break + } + } + if i != 4 || i == len(s) || s[i] != '-' { + return time.Time{}, false + } + for _, format := range allowedTimestampFormats { + if t, err := time.Parse(format, s); err == nil { + return t, true + } + } + return time.Time{}, false +} diff --git a/vendor/github.com/zclconf/go-cty-yaml/scannerc.go b/vendor/gopkg.in/yaml.v3/scannerc.go similarity index 85% rename from vendor/github.com/zclconf/go-cty-yaml/scannerc.go rename to vendor/gopkg.in/yaml.v3/scannerc.go index 077fd1dd2d4..57e954ca53d 100644 --- a/vendor/github.com/zclconf/go-cty-yaml/scannerc.go +++ b/vendor/gopkg.in/yaml.v3/scannerc.go @@ -1,3 +1,25 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + package yaml import ( @@ -489,6 +511,9 @@ func cache(parser *yaml_parser_t, length int) bool { // Advance the buffer pointer. func skip(parser *yaml_parser_t) { + if !is_blank(parser.buffer, parser.buffer_pos) { + parser.newlines = 0 + } parser.mark.index++ parser.mark.column++ parser.unread-- @@ -502,17 +527,22 @@ func skip_line(parser *yaml_parser_t) { parser.mark.line++ parser.unread -= 2 parser.buffer_pos += 2 + parser.newlines++ } else if is_break(parser.buffer, parser.buffer_pos) { parser.mark.index++ parser.mark.column = 0 parser.mark.line++ parser.unread-- parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) + parser.newlines++ } } // Copy a character to a string buffer and advance pointers. func read(parser *yaml_parser_t, s []byte) []byte { + if !is_blank(parser.buffer, parser.buffer_pos) { + parser.newlines = 0 + } w := width(parser.buffer[parser.buffer_pos]) if w == 0 { panic("invalid character sequence") @@ -564,6 +594,7 @@ func read_line(parser *yaml_parser_t, s []byte) []byte { parser.mark.column = 0 parser.mark.line++ parser.unread-- + parser.newlines++ return s } @@ -626,30 +657,21 @@ func trace(args ...interface{}) func() { func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { // While we need more tokens to fetch, do it. for { - // Check if we really need to fetch more tokens. - need_more_tokens := false - - if parser.tokens_head == len(parser.tokens) { - // Queue is empty. - need_more_tokens = true - } else { - // Check if any potential simple key may occupy the head position. - if !yaml_parser_stale_simple_keys(parser) { + // [Go] The comment parsing logic requires a lookahead of two tokens + // so that foot comments may be parsed in time of associating them + // with the tokens that are parsed before them, and also for line + // comments to be transformed into head comments in some edge cases. + if parser.tokens_head < len(parser.tokens)-2 { + // If a potential simple key is at the head position, we need to fetch + // the next token to disambiguate it. + head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed] + if !ok { + break + } else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok { return false + } else if !valid { + break } - - for i := range parser.simple_keys { - simple_key := &parser.simple_keys[i] - if simple_key.possible && simple_key.token_number == parser.tokens_parsed { - need_more_tokens = true - break - } - } - } - - // We are finished. - if !need_more_tokens { - break } // Fetch the next token. if !yaml_parser_fetch_next_token(parser) { @@ -662,7 +684,7 @@ func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { } // The dispatcher for token fetchers. -func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { +func yaml_parser_fetch_next_token(parser *yaml_parser_t) (ok bool) { // Ensure that the buffer is initialized. if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { return false @@ -673,18 +695,19 @@ func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { return yaml_parser_fetch_stream_start(parser) } + scan_mark := parser.mark + // Eat whitespaces and comments until we reach the next token. if !yaml_parser_scan_to_next_token(parser) { return false } - // Remove obsolete potential simple keys. - if !yaml_parser_stale_simple_keys(parser) { - return false - } + // [Go] While unrolling indents, transform the head comments of prior + // indentation levels observed after scan_start into foot comments at + // the respective indexes. // Check the indentation level against the current column. - if !yaml_parser_unroll_indent(parser, parser.mark.column) { + if !yaml_parser_unroll_indent(parser, parser.mark.column, scan_mark) { return false } @@ -717,6 +740,21 @@ func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) } + comment_mark := parser.mark + if len(parser.tokens) > 0 && (parser.flow_level == 0 && buf[pos] == ':' || parser.flow_level > 0 && buf[pos] == ',') { + // Associate any following comments with the prior token. + comment_mark = parser.tokens[len(parser.tokens)-1].start_mark + } + defer func() { + if !ok { + return + } + if !yaml_parser_scan_line_comment(parser, comment_mark) { + ok = false + return + } + }() + // Is it the flow sequence start indicator? if buf[pos] == '[' { return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) @@ -810,7 +848,7 @@ func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { // if it is followed by a non-space character. // // The last rule is more restrictive than the specification requires. - // [Go] Make this logic more reasonable. + // [Go] TODO Make this logic more reasonable. //switch parser.buffer[parser.buffer_pos] { //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': //} @@ -837,29 +875,30 @@ func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { "found character that cannot start any token") } -// Check the list of potential simple keys and remove the positions that -// cannot contain simple keys anymore. -func yaml_parser_stale_simple_keys(parser *yaml_parser_t) bool { - // Check for a potential simple key for each flow level. - for i := range parser.simple_keys { - simple_key := &parser.simple_keys[i] +func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) { + if !simple_key.possible { + return false, true + } - // The specification requires that a simple key - // - // - is limited to a single line, - // - is shorter than 1024 characters. - if simple_key.possible && (simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index) { - - // Check if the potential simple key to be removed is required. - if simple_key.required { - return yaml_parser_set_scanner_error(parser, - "while scanning a simple key", simple_key.mark, - "could not find expected ':'") - } - simple_key.possible = false + // The 1.2 specification says: + // + // "If the ? indicator is omitted, parsing needs to see past the + // implicit key to recognize it as such. To limit the amount of + // lookahead required, the “:” indicator must appear at most 1024 + // Unicode characters beyond the start of the key. In addition, the key + // is restricted to a single line." + // + if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index { + // Check if the potential simple key to be removed is required. + if simple_key.required { + return false, yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key.mark, + "could not find expected ':'") } + simple_key.possible = false + return false, true } - return true + return true, true } // Check if a simple key may start at the current position and add it if @@ -879,13 +918,14 @@ func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { possible: true, required: required, token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, } - simple_key.mark = parser.mark if !yaml_parser_remove_simple_key(parser) { return false } parser.simple_keys[len(parser.simple_keys)-1] = simple_key + parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1 } return true } @@ -900,19 +940,33 @@ func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { "while scanning a simple key", parser.simple_keys[i].mark, "could not find expected ':'") } + // Remove the key from the stack. + parser.simple_keys[i].possible = false + delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number) } - // Remove the key from the stack. - parser.simple_keys[i].possible = false return true } +// max_flow_level limits the flow_level +const max_flow_level = 10000 + // Increase the flow level and resize the simple key list if needed. func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { // Reset the simple key on the next level. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{ + possible: false, + required: false, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + }) // Increase the flow level. parser.flow_level++ + if parser.flow_level > max_flow_level { + return yaml_parser_set_scanner_error(parser, + "while increasing flow level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_flow_level)) + } return true } @@ -920,11 +974,16 @@ func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { if parser.flow_level > 0 { parser.flow_level-- - parser.simple_keys = parser.simple_keys[:len(parser.simple_keys)-1] + last := len(parser.simple_keys) - 1 + delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number) + parser.simple_keys = parser.simple_keys[:last] } return true } +// max_indents limits the indents stack size +const max_indents = 10000 + // Push the current indentation level to the stack and set the new level // the current column is greater than the indentation level. In this case, // append or insert the specified token into the token queue. @@ -939,6 +998,11 @@ func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml // indentation level. parser.indents = append(parser.indents, parser.indent) parser.indent = column + if len(parser.indents) > max_indents { + return yaml_parser_set_scanner_error(parser, + "while increasing indent level", parser.simple_keys[len(parser.simple_keys)-1].mark, + fmt.Sprintf("exceeded max depth of %d", max_indents)) + } // Create a token and insert it into the queue. token := yaml_token_t{ @@ -957,19 +1021,49 @@ func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml // Pop indentation levels from the indents stack until the current level // becomes less or equal to the column. For each indentation level, append // the BLOCK-END token. -func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool { +func yaml_parser_unroll_indent(parser *yaml_parser_t, column int, scan_mark yaml_mark_t) bool { // In the flow context, do nothing. if parser.flow_level > 0 { return true } + block_mark := scan_mark + block_mark.index-- + // Loop through the indentation levels in the stack. for parser.indent > column { + + // [Go] Reposition the end token before potential following + // foot comments of parent blocks. For that, search + // backwards for recent comments that were at the same + // indent as the block that is ending now. + stop_index := block_mark.index + for i := len(parser.comments) - 1; i >= 0; i-- { + comment := &parser.comments[i] + + if comment.end_mark.index < stop_index { + // Don't go back beyond the start of the comment/whitespace scan, unless column < 0. + // If requested indent column is < 0, then the document is over and everything else + // is a foot anyway. + break + } + if comment.start_mark.column == parser.indent+1 { + // This is a good match. But maybe there's a former comment + // at that same indent level, so keep searching. + block_mark = comment.start_mark + } + + // While the end of the former comment matches with + // the start of the following one, we know there's + // nothing in between and scanning is still safe. + stop_index = comment.scan_mark.index + } + // Create a token and append it to the queue. token := yaml_token_t{ typ: yaml_BLOCK_END_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, + start_mark: block_mark, + end_mark: block_mark, } yaml_insert_token(parser, -1, &token) @@ -989,6 +1083,8 @@ func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { // Initialize the simple key stack. parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) + parser.simple_keys_by_tok = make(map[int]int) + // A simple key is allowed at the beginning of the stream. parser.simple_key_allowed = true @@ -1016,7 +1112,7 @@ func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { } // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { return false } @@ -1040,7 +1136,7 @@ func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { // Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { return false } @@ -1064,7 +1160,7 @@ func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { // Produce the DOCUMENT-START or DOCUMENT-END token. func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { + if !yaml_parser_unroll_indent(parser, -1, parser.mark) { return false } @@ -1097,6 +1193,7 @@ func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_ // Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { + // The indicators '[' and '{' may start a simple key. if !yaml_parser_save_simple_key(parser) { return false @@ -1270,7 +1367,11 @@ func yaml_parser_fetch_value(parser *yaml_parser_t) bool { simple_key := &parser.simple_keys[len(parser.simple_keys)-1] // Have we found a simple key? - if simple_key.possible { + if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { + return false + + } else if valid { + // Create the KEY token and insert it into the queue. token := yaml_token_t{ typ: yaml_KEY_TOKEN, @@ -1288,6 +1389,7 @@ func yaml_parser_fetch_value(parser *yaml_parser_t) bool { // Remove the simple key. simple_key.possible = false + delete(parser.simple_keys_by_tok, simple_key.token_number) // A simple key cannot follow another simple key. parser.simple_key_allowed = false @@ -1427,6 +1529,8 @@ func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { // Eat whitespaces and comments until the next token is found. func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { + scan_mark := parser.mark + // Until the next token is not found. for { // Allow the BOM mark to start a line. @@ -1453,13 +1557,33 @@ func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { } } + // Check if we just had a line comment under a sequence entry that + // looks more like a header to the following content. Similar to this: + // + // - # The comment + // - Some data + // + // If so, transform the line comment to a head comment and reposition. + if len(parser.comments) > 0 && len(parser.tokens) > 1 { + tokenA := parser.tokens[len(parser.tokens)-2] + tokenB := parser.tokens[len(parser.tokens)-1] + comment := &parser.comments[len(parser.comments)-1] + if tokenA.typ == yaml_BLOCK_SEQUENCE_START_TOKEN && tokenB.typ == yaml_BLOCK_ENTRY_TOKEN && len(comment.line) > 0 && !is_break(parser.buffer, parser.buffer_pos) { + // If it was in the prior line, reposition so it becomes a + // header of the follow up token. Otherwise, keep it in place + // so it becomes a header of the former. + comment.head = comment.line + comment.line = nil + if comment.start_mark.line == parser.mark.line-1 { + comment.token_mark = parser.mark + } + } + } + // Eat a comment until a line break. if parser.buffer[parser.buffer_pos] == '#' { - for !is_breakz(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } + if !yaml_parser_scan_comments(parser, scan_mark) { + return false } } @@ -1557,6 +1681,10 @@ func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool } if parser.buffer[parser.buffer_pos] == '#' { + // [Go] Discard this inline comment for the time being. + //if !yaml_parser_scan_line_comment(parser, start_mark) { + // return false + //} for !is_breakz(parser.buffer, parser.buffer_pos) { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { @@ -1972,7 +2100,7 @@ func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', // '%'. - // [Go] Convert this into more reasonable logic. + // [Go] TODO Convert this into more reasonable logic. for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || @@ -2127,6 +2255,10 @@ func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, l } } if parser.buffer[parser.buffer_pos] == '#' { + // TODO Test this and then re-enable it. + //if !yaml_parser_scan_line_comment(parser, start_mark) { + // return false + //} for !is_breakz(parser.buffer, parser.buffer_pos) { skip(parser) if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { @@ -2694,3 +2826,200 @@ func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) b } return true } + +func yaml_parser_scan_line_comment(parser *yaml_parser_t, token_mark yaml_mark_t) bool { + if parser.newlines > 0 { + return true + } + + var start_mark yaml_mark_t + var text []byte + + for peek := 0; peek < 512; peek++ { + if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { + break + } + if is_blank(parser.buffer, parser.buffer_pos+peek) { + continue + } + if parser.buffer[parser.buffer_pos+peek] == '#' { + seen := parser.mark.index+peek + for { + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_breakz(parser.buffer, parser.buffer_pos) { + if parser.mark.index >= seen { + break + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } else { + if parser.mark.index >= seen { + if len(text) == 0 { + start_mark = parser.mark + } + text = append(text, parser.buffer[parser.buffer_pos]) + } + skip(parser) + } + } + } + break + } + if len(text) > 0 { + parser.comments = append(parser.comments, yaml_comment_t{ + token_mark: token_mark, + start_mark: start_mark, + line: text, + }) + } + return true +} + +func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) bool { + token := parser.tokens[len(parser.tokens)-1] + + if token.typ == yaml_FLOW_ENTRY_TOKEN && len(parser.tokens) > 1 { + token = parser.tokens[len(parser.tokens)-2] + } + + var token_mark = token.start_mark + var start_mark yaml_mark_t + + var recent_empty = false + var first_empty = parser.newlines <= 1 + + var line = parser.mark.line + var column = parser.mark.column + + var text []byte + + // The foot line is the place where a comment must start to + // still be considered as a foot of the prior content. + // If there's some content in the currently parsed line, then + // the foot is the line below it. + var foot_line = -1 + if scan_mark.line > 0 { + foot_line = parser.mark.line-parser.newlines+1 + if parser.newlines == 0 && parser.mark.column > 1 { + foot_line++ + } + } + + var peek = 0 + for ; peek < 512; peek++ { + if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { + break + } + column++ + if is_blank(parser.buffer, parser.buffer_pos+peek) { + continue + } + c := parser.buffer[parser.buffer_pos+peek] + if is_breakz(parser.buffer, parser.buffer_pos+peek) || parser.flow_level > 0 && (c == ']' || c == '}') { + // Got line break or terminator. + if !recent_empty { + if first_empty && (start_mark.line == foot_line || start_mark.column-1 < parser.indent) { + // This is the first empty line and there were no empty lines before, + // so this initial part of the comment is a foot of the prior token + // instead of being a head for the following one. Split it up. + if len(text) > 0 { + if start_mark.column-1 < parser.indent { + // If dedented it's unrelated to the prior token. + token_mark = start_mark + } + parser.comments = append(parser.comments, yaml_comment_t{ + scan_mark: scan_mark, + token_mark: token_mark, + start_mark: start_mark, + end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, + foot: text, + }) + scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} + token_mark = scan_mark + text = nil + } + } else { + if len(text) > 0 && parser.buffer[parser.buffer_pos+peek] != 0 { + text = append(text, '\n') + } + } + } + if !is_break(parser.buffer, parser.buffer_pos+peek) { + break + } + first_empty = false + recent_empty = true + column = 0 + line++ + continue + } + + if len(text) > 0 && column < parser.indent+1 && column != start_mark.column { + // The comment at the different indentation is a foot of the + // preceding data rather than a head of the upcoming one. + parser.comments = append(parser.comments, yaml_comment_t{ + scan_mark: scan_mark, + token_mark: token_mark, + start_mark: start_mark, + end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, + foot: text, + }) + scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} + token_mark = scan_mark + text = nil + } + + if parser.buffer[parser.buffer_pos+peek] != '#' { + break + } + + if len(text) == 0 { + start_mark = yaml_mark_t{parser.mark.index + peek, line, column} + } else { + text = append(text, '\n') + } + + recent_empty = false + + // Consume until after the consumed comment line. + seen := parser.mark.index+peek + for { + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + if is_breakz(parser.buffer, parser.buffer_pos) { + if parser.mark.index >= seen { + break + } + if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { + return false + } + skip_line(parser) + } else { + if parser.mark.index >= seen { + text = append(text, parser.buffer[parser.buffer_pos]) + } + skip(parser) + } + } + + peek = 0 + column = 0 + line = parser.mark.line + } + + if len(text) > 0 { + parser.comments = append(parser.comments, yaml_comment_t{ + scan_mark: scan_mark, + token_mark: start_mark, + start_mark: start_mark, + end_mark: yaml_mark_t{parser.mark.index + peek - 1, line, column}, + head: text, + }) + } + return true +} diff --git a/vendor/gopkg.in/yaml.v3/sorter.go b/vendor/gopkg.in/yaml.v3/sorter.go new file mode 100644 index 00000000000..9210ece7e97 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/sorter.go @@ -0,0 +1,134 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// 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 yaml + +import ( + "reflect" + "unicode" +) + +type keyList []reflect.Value + +func (l keyList) Len() int { return len(l) } +func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } +func (l keyList) Less(i, j int) bool { + a := l[i] + b := l[j] + ak := a.Kind() + bk := b.Kind() + for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { + a = a.Elem() + ak = a.Kind() + } + for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { + b = b.Elem() + bk = b.Kind() + } + af, aok := keyFloat(a) + bf, bok := keyFloat(b) + if aok && bok { + if af != bf { + return af < bf + } + if ak != bk { + return ak < bk + } + return numLess(a, b) + } + if ak != reflect.String || bk != reflect.String { + return ak < bk + } + ar, br := []rune(a.String()), []rune(b.String()) + digits := false + for i := 0; i < len(ar) && i < len(br); i++ { + if ar[i] == br[i] { + digits = unicode.IsDigit(ar[i]) + continue + } + al := unicode.IsLetter(ar[i]) + bl := unicode.IsLetter(br[i]) + if al && bl { + return ar[i] < br[i] + } + if al || bl { + if digits { + return al + } else { + return bl + } + } + var ai, bi int + var an, bn int64 + if ar[i] == '0' || br[i] == '0' { + for j := i - 1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + if ar[j] != '0' { + an = 1 + bn = 1 + break + } + } + } + for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { + an = an*10 + int64(ar[ai]-'0') + } + for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { + bn = bn*10 + int64(br[bi]-'0') + } + if an != bn { + return an < bn + } + if ai != bi { + return ai < bi + } + return ar[i] < br[i] + } + return len(ar) < len(br) +} + +// keyFloat returns a float value for v if it is a number/bool +// and whether it is a number/bool or not. +func keyFloat(v reflect.Value) (f float64, ok bool) { + switch v.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return float64(v.Int()), true + case reflect.Float32, reflect.Float64: + return v.Float(), true + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return float64(v.Uint()), true + case reflect.Bool: + if v.Bool() { + return 1, true + } + return 0, true + } + return 0, false +} + +// numLess returns whether a < b. +// a and b must necessarily have the same kind. +func numLess(a, b reflect.Value) bool { + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return a.Int() < b.Int() + case reflect.Float32, reflect.Float64: + return a.Float() < b.Float() + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return a.Uint() < b.Uint() + case reflect.Bool: + return !a.Bool() && b.Bool() + } + panic("not a number") +} diff --git a/vendor/gopkg.in/yaml.v3/writerc.go b/vendor/gopkg.in/yaml.v3/writerc.go new file mode 100644 index 00000000000..b8a116bf9a2 --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/writerc.go @@ -0,0 +1,48 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package yaml + +// Set the writer error and return false. +func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { + emitter.error = yaml_WRITER_ERROR + emitter.problem = problem + return false +} + +// Flush the output buffer. +func yaml_emitter_flush(emitter *yaml_emitter_t) bool { + if emitter.write_handler == nil { + panic("write handler not set") + } + + // Check if the buffer is empty. + if emitter.buffer_pos == 0 { + return true + } + + if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { + return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) + } + emitter.buffer_pos = 0 + return true +} diff --git a/vendor/gopkg.in/yaml.v3/yaml.go b/vendor/gopkg.in/yaml.v3/yaml.go new file mode 100644 index 00000000000..b5d35a50ded --- /dev/null +++ b/vendor/gopkg.in/yaml.v3/yaml.go @@ -0,0 +1,662 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// +// 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 yaml implements YAML support for the Go language. +// +// Source code and other details for the project are available at GitHub: +// +// https://github.com/go-yaml/yaml +// +package yaml + +import ( + "errors" + "fmt" + "io" + "reflect" + "strings" + "sync" + "unicode/utf8" +) + +// The Unmarshaler interface may be implemented by types to customize their +// behavior when being unmarshaled from a YAML document. +type Unmarshaler interface { + UnmarshalYAML(value *Node) error +} + +type obsoleteUnmarshaler interface { + UnmarshalYAML(unmarshal func(interface{}) error) error +} + +// The Marshaler interface may be implemented by types to customize their +// behavior when being marshaled into a YAML document. The returned value +// is marshaled in place of the original value implementing Marshaler. +// +// If an error is returned by MarshalYAML, the marshaling procedure stops +// and returns with the provided error. +type Marshaler interface { + MarshalYAML() (interface{}, error) +} + +// Unmarshal decodes the first document found within the in byte slice +// and assigns decoded values into the out value. +// +// Maps and pointers (to a struct, string, int, etc) are accepted as out +// values. If an internal pointer within a struct is not initialized, +// the yaml package will initialize it if necessary for unmarshalling +// the provided data. The out parameter must not be nil. +// +// The type of the decoded values should be compatible with the respective +// values in out. If one or more values cannot be decoded due to a type +// mismatches, decoding continues partially until the end of the YAML +// content, and a *yaml.TypeError is returned with details for all +// missed values. +// +// Struct fields are only unmarshalled if they are exported (have an +// upper case first letter), and are unmarshalled using the field name +// lowercased as the default key. Custom keys may be defined via the +// "yaml" name in the field tag: the content preceding the first comma +// is used as the key, and the following comma-separated options are +// used to tweak the marshalling process (see Marshal). +// Conflicting names result in a runtime error. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// var t T +// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) +// +// See the documentation of Marshal for the format of tags and a list of +// supported tag options. +// +func Unmarshal(in []byte, out interface{}) (err error) { + return unmarshal(in, out, false) +} + +// A Decorder reads and decodes YAML values from an input stream. +type Decoder struct { + parser *parser + knownFields bool +} + +// NewDecoder returns a new decoder that reads from r. +// +// The decoder introduces its own buffering and may read +// data from r beyond the YAML values requested. +func NewDecoder(r io.Reader) *Decoder { + return &Decoder{ + parser: newParserFromReader(r), + } +} + +// KnownFields ensures that the keys in decoded mappings to +// exist as fields in the struct being decoded into. +func (dec *Decoder) KnownFields(enable bool) { + dec.knownFields = enable +} + +// Decode reads the next YAML-encoded value from its input +// and stores it in the value pointed to by v. +// +// See the documentation for Unmarshal for details about the +// conversion of YAML into a Go value. +func (dec *Decoder) Decode(v interface{}) (err error) { + d := newDecoder() + d.knownFields = dec.knownFields + defer handleErr(&err) + node := dec.parser.parse() + if node == nil { + return io.EOF + } + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(node, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +// Decode decodes the node and stores its data into the value pointed to by v. +// +// See the documentation for Unmarshal for details about the +// conversion of YAML into a Go value. +func (n *Node) Decode(v interface{}) (err error) { + d := newDecoder() + defer handleErr(&err) + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(n, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +func unmarshal(in []byte, out interface{}, strict bool) (err error) { + defer handleErr(&err) + d := newDecoder() + p := newParser(in) + defer p.destroy() + node := p.parse() + if node != nil { + v := reflect.ValueOf(out) + if v.Kind() == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } + d.unmarshal(node, v) + } + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + +// Marshal serializes the value provided into a YAML document. The structure +// of the generated document will reflect the structure of the value itself. +// Maps and pointers (to struct, string, int, etc) are accepted as the in value. +// +// Struct fields are only marshalled if they are exported (have an upper case +// first letter), and are marshalled using the field name lowercased as the +// default key. Custom keys may be defined via the "yaml" name in the field +// tag: the content preceding the first comma is used as the key, and the +// following comma-separated options are used to tweak the marshalling process. +// Conflicting names result in a runtime error. +// +// The field tag format accepted is: +// +// `(...) yaml:"[][,[,]]" (...)` +// +// The following flags are currently supported: +// +// omitempty Only include the field if it's not set to the zero +// value for the type or to empty slices or maps. +// Zero valued structs will be omitted if all their public +// fields are zero, unless they implement an IsZero +// method (see the IsZeroer interface type), in which +// case the field will be included if that method returns true. +// +// flow Marshal using a flow style (useful for structs, +// sequences and maps). +// +// inline Inline the field, which must be a struct or a map, +// causing all of its fields or keys to be processed as if +// they were part of the outer struct. For maps, keys must +// not conflict with the yaml keys of other struct fields. +// +// In addition, if the key is "-", the field is ignored. +// +// For example: +// +// type T struct { +// F int `yaml:"a,omitempty"` +// B int +// } +// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" +// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" +// +func Marshal(in interface{}) (out []byte, err error) { + defer handleErr(&err) + e := newEncoder() + defer e.destroy() + e.marshalDoc("", reflect.ValueOf(in)) + e.finish() + out = e.out + return +} + +// An Encoder writes YAML values to an output stream. +type Encoder struct { + encoder *encoder +} + +// NewEncoder returns a new encoder that writes to w. +// The Encoder should be closed after use to flush all data +// to w. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{ + encoder: newEncoderWithWriter(w), + } +} + +// Encode writes the YAML encoding of v to the stream. +// If multiple items are encoded to the stream, the +// second and subsequent document will be preceded +// with a "---" document separator, but the first will not. +// +// See the documentation for Marshal for details about the conversion of Go +// values to YAML. +func (e *Encoder) Encode(v interface{}) (err error) { + defer handleErr(&err) + e.encoder.marshalDoc("", reflect.ValueOf(v)) + return nil +} + +// SetIndent changes the used indentation used when encoding. +func (e *Encoder) SetIndent(spaces int) { + if spaces < 0 { + panic("yaml: cannot indent to a negative number of spaces") + } + e.encoder.indent = spaces +} + +// Close closes the encoder by writing any remaining data. +// It does not write a stream terminating string "...". +func (e *Encoder) Close() (err error) { + defer handleErr(&err) + e.encoder.finish() + return nil +} + +func handleErr(err *error) { + if v := recover(); v != nil { + if e, ok := v.(yamlError); ok { + *err = e.err + } else { + panic(v) + } + } +} + +type yamlError struct { + err error +} + +func fail(err error) { + panic(yamlError{err}) +} + +func failf(format string, args ...interface{}) { + panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) +} + +// A TypeError is returned by Unmarshal when one or more fields in +// the YAML document cannot be properly decoded into the requested +// types. When this error is returned, the value is still +// unmarshaled partially. +type TypeError struct { + Errors []string +} + +func (e *TypeError) Error() string { + return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) +} + +type Kind uint32 + +const ( + DocumentNode Kind = 1 << iota + SequenceNode + MappingNode + ScalarNode + AliasNode +) + +type Style uint32 + +const ( + TaggedStyle Style = 1 << iota + DoubleQuotedStyle + SingleQuotedStyle + LiteralStyle + FoldedStyle + FlowStyle +) + +// Node represents an element in the YAML document hierarchy. While documents +// are typically encoded and decoded into higher level types, such as structs +// and maps, Node is an intermediate representation that allows detailed +// control over the content being decoded or encoded. +// +// Values that make use of the Node type interact with the yaml package in the +// same way any other type would do, by encoding and decoding yaml data +// directly or indirectly into them. +// +// For example: +// +// var person struct { +// Name string +// Address yaml.Node +// } +// err := yaml.Unmarshal(data, &person) +// +// Or by itself: +// +// var person Node +// err := yaml.Unmarshal(data, &person) +// +type Node struct { + // Kind defines whether the node is a document, a mapping, a sequence, + // a scalar value, or an alias to another node. The specific data type of + // scalar nodes may be obtained via the ShortTag and LongTag methods. + Kind Kind + + // Style allows customizing the apperance of the node in the tree. + Style Style + + // Tag holds the YAML tag defining the data type for the value. + // When decoding, this field will always be set to the resolved tag, + // even when it wasn't explicitly provided in the YAML content. + // When encoding, if this field is unset the value type will be + // implied from the node properties, and if it is set, it will only + // be serialized into the representation if TaggedStyle is used or + // the implicit tag diverges from the provided one. + Tag string + + // Value holds the unescaped and unquoted represenation of the value. + Value string + + // Anchor holds the anchor name for this node, which allows aliases to point to it. + Anchor string + + // Alias holds the node that this alias points to. Only valid when Kind is AliasNode. + Alias *Node + + // Content holds contained nodes for documents, mappings, and sequences. + Content []*Node + + // HeadComment holds any comments in the lines preceding the node and + // not separated by an empty line. + HeadComment string + + // LineComment holds any comments at the end of the line where the node is in. + LineComment string + + // FootComment holds any comments following the node and before empty lines. + FootComment string + + // Line and Column hold the node position in the decoded YAML text. + // These fields are not respected when encoding the node. + Line int + Column int +} + +// LongTag returns the long form of the tag that indicates the data type for +// the node. If the Tag field isn't explicitly defined, one will be computed +// based on the node properties. +func (n *Node) LongTag() string { + return longTag(n.ShortTag()) +} + +// ShortTag returns the short form of the YAML tag that indicates data type for +// the node. If the Tag field isn't explicitly defined, one will be computed +// based on the node properties. +func (n *Node) ShortTag() string { + if n.indicatedString() { + return strTag + } + if n.Tag == "" || n.Tag == "!" { + switch n.Kind { + case MappingNode: + return mapTag + case SequenceNode: + return seqTag + case AliasNode: + if n.Alias != nil { + return n.Alias.ShortTag() + } + case ScalarNode: + tag, _ := resolve("", n.Value) + return tag + } + return "" + } + return shortTag(n.Tag) +} + +func (n *Node) indicatedString() bool { + return n.Kind == ScalarNode && + (shortTag(n.Tag) == strTag || + (n.Tag == "" || n.Tag == "!") && n.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0) +} + +// SetString is a convenience function that sets the node to a string value +// and defines its style in a pleasant way depending on its content. +func (n *Node) SetString(s string) { + n.Kind = ScalarNode + if utf8.ValidString(s) { + n.Value = s + n.Tag = strTag + } else { + n.Value = encodeBase64(s) + n.Tag = binaryTag + } + if strings.Contains(n.Value, "\n") { + n.Style = LiteralStyle + } +} + +// -------------------------------------------------------------------------- +// Maintain a mapping of keys to structure field indexes + +// The code in this section was copied from mgo/bson. + +// structInfo holds details for the serialization of fields of +// a given struct. +type structInfo struct { + FieldsMap map[string]fieldInfo + FieldsList []fieldInfo + + // InlineMap is the number of the field in the struct that + // contains an ,inline map, or -1 if there's none. + InlineMap int + + // InlineUnmarshalers holds indexes to inlined fields that + // contain unmarshaler values. + InlineUnmarshalers [][]int +} + +type fieldInfo struct { + Key string + Num int + OmitEmpty bool + Flow bool + // Id holds the unique field identifier, so we can cheaply + // check for field duplicates without maintaining an extra map. + Id int + + // Inline holds the field index if the field is part of an inlined struct. + Inline []int +} + +var structMap = make(map[reflect.Type]*structInfo) +var fieldMapMutex sync.RWMutex +var unmarshalerType reflect.Type + +func init() { + var v Unmarshaler + unmarshalerType = reflect.ValueOf(&v).Elem().Type() +} + +func getStructInfo(st reflect.Type) (*structInfo, error) { + fieldMapMutex.RLock() + sinfo, found := structMap[st] + fieldMapMutex.RUnlock() + if found { + return sinfo, nil + } + + n := st.NumField() + fieldsMap := make(map[string]fieldInfo) + fieldsList := make([]fieldInfo, 0, n) + inlineMap := -1 + inlineUnmarshalers := [][]int(nil) + for i := 0; i != n; i++ { + field := st.Field(i) + if field.PkgPath != "" && !field.Anonymous { + continue // Private field + } + + info := fieldInfo{Num: i} + + tag := field.Tag.Get("yaml") + if tag == "" && strings.Index(string(field.Tag), ":") < 0 { + tag = string(field.Tag) + } + if tag == "-" { + continue + } + + inline := false + fields := strings.Split(tag, ",") + if len(fields) > 1 { + for _, flag := range fields[1:] { + switch flag { + case "omitempty": + info.OmitEmpty = true + case "flow": + info.Flow = true + case "inline": + inline = true + default: + return nil, errors.New(fmt.Sprintf("unsupported flag %q in tag %q of type %s", flag, tag, st)) + } + } + tag = fields[0] + } + + if inline { + switch field.Type.Kind() { + case reflect.Map: + if inlineMap >= 0 { + return nil, errors.New("multiple ,inline maps in struct " + st.String()) + } + if field.Type.Key() != reflect.TypeOf("") { + return nil, errors.New("option ,inline needs a map with string keys in struct " + st.String()) + } + inlineMap = info.Num + case reflect.Struct, reflect.Ptr: + ftype := field.Type + for ftype.Kind() == reflect.Ptr { + ftype = ftype.Elem() + } + if ftype.Kind() != reflect.Struct { + return nil, errors.New("option ,inline may only be used on a struct or map field") + } + if reflect.PtrTo(ftype).Implements(unmarshalerType) { + inlineUnmarshalers = append(inlineUnmarshalers, []int{i}) + } else { + sinfo, err := getStructInfo(ftype) + if err != nil { + return nil, err + } + for _, index := range sinfo.InlineUnmarshalers { + inlineUnmarshalers = append(inlineUnmarshalers, append([]int{i}, index...)) + } + for _, finfo := range sinfo.FieldsList { + if _, found := fieldsMap[finfo.Key]; found { + msg := "duplicated key '" + finfo.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + if finfo.Inline == nil { + finfo.Inline = []int{i, finfo.Num} + } else { + finfo.Inline = append([]int{i}, finfo.Inline...) + } + finfo.Id = len(fieldsList) + fieldsMap[finfo.Key] = finfo + fieldsList = append(fieldsList, finfo) + } + } + default: + return nil, errors.New("option ,inline may only be used on a struct or map field") + } + continue + } + + if tag != "" { + info.Key = tag + } else { + info.Key = strings.ToLower(field.Name) + } + + if _, found = fieldsMap[info.Key]; found { + msg := "duplicated key '" + info.Key + "' in struct " + st.String() + return nil, errors.New(msg) + } + + info.Id = len(fieldsList) + fieldsList = append(fieldsList, info) + fieldsMap[info.Key] = info + } + + sinfo = &structInfo{ + FieldsMap: fieldsMap, + FieldsList: fieldsList, + InlineMap: inlineMap, + InlineUnmarshalers: inlineUnmarshalers, + } + + fieldMapMutex.Lock() + structMap[st] = sinfo + fieldMapMutex.Unlock() + return sinfo, nil +} + +// IsZeroer is used to check whether an object is zero to +// determine whether it should be omitted when marshaling +// with the omitempty flag. One notable implementation +// is time.Time. +type IsZeroer interface { + IsZero() bool +} + +func isZero(v reflect.Value) bool { + kind := v.Kind() + if z, ok := v.Interface().(IsZeroer); ok { + if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { + return true + } + return z.IsZero() + } + switch kind { + case reflect.String: + return len(v.String()) == 0 + case reflect.Interface, reflect.Ptr: + return v.IsNil() + case reflect.Slice: + return v.Len() == 0 + case reflect.Map: + return v.Len() == 0 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Struct: + vt := v.Type() + for i := v.NumField() - 1; i >= 0; i-- { + if vt.Field(i).PkgPath != "" { + continue // Private field + } + if !isZero(v.Field(i)) { + return false + } + } + return true + } + return false +} diff --git a/vendor/github.com/zclconf/go-cty-yaml/yamlh.go b/vendor/gopkg.in/yaml.v3/yamlh.go similarity index 88% rename from vendor/github.com/zclconf/go-cty-yaml/yamlh.go rename to vendor/gopkg.in/yaml.v3/yamlh.go index e25cee563be..2719cfbb0b7 100644 --- a/vendor/github.com/zclconf/go-cty-yaml/yamlh.go +++ b/vendor/gopkg.in/yaml.v3/yamlh.go @@ -1,3 +1,25 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + package yaml import ( @@ -73,13 +95,13 @@ type yaml_scalar_style_t yaml_style_t // Scalar styles. const ( // Let the emitter choose the style. - yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota + yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = 0 - yaml_PLAIN_SCALAR_STYLE // The plain scalar style. - yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. - yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. - yaml_LITERAL_SCALAR_STYLE // The literal scalar style. - yaml_FOLDED_SCALAR_STYLE // The folded scalar style. + yaml_PLAIN_SCALAR_STYLE yaml_scalar_style_t = 1 << iota // The plain scalar style. + yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. + yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. + yaml_LITERAL_SCALAR_STYLE // The literal scalar style. + yaml_FOLDED_SCALAR_STYLE // The folded scalar style. ) type yaml_sequence_style_t yaml_style_t @@ -238,6 +260,7 @@ const ( yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. yaml_MAPPING_START_EVENT // A MAPPING-START event. yaml_MAPPING_END_EVENT // A MAPPING-END event. + yaml_TAIL_COMMENT_EVENT ) var eventStrings = []string{ @@ -252,6 +275,7 @@ var eventStrings = []string{ yaml_SEQUENCE_END_EVENT: "sequence end", yaml_MAPPING_START_EVENT: "mapping start", yaml_MAPPING_END_EVENT: "mapping end", + yaml_TAIL_COMMENT_EVENT: "tail comment", } func (e yaml_event_type_t) String() string { @@ -279,6 +303,12 @@ type yaml_event_t struct { // The list of tag directives (for yaml_DOCUMENT_START_EVENT). tag_directives []yaml_tag_directive_t + // The comments + head_comment []byte + line_comment []byte + foot_comment []byte + tail_comment []byte + // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). anchor []byte @@ -554,6 +584,8 @@ type yaml_parser_t struct { unread int // The number of unread characters in the buffer. + newlines int // The number of line breaks since last non-break/non-blank character + raw_buffer []byte // The raw buffer. raw_buffer_pos int // The current position of the buffer. @@ -562,6 +594,17 @@ type yaml_parser_t struct { offset int // The offset of the current position (in bytes). mark yaml_mark_t // The mark of the current position. + // Comments + + head_comment []byte // The current head comments + line_comment []byte // The current line comments + foot_comment []byte // The current foot comments + tail_comment []byte // Foot comment that happens at the end of a block. + stem_comment []byte // Comment in item preceding a nested structure (list inside list item, etc) + + comments []yaml_comment_t // The folded comments for all parsed tokens + comments_head int + // Scanner stuff stream_start_produced bool // Have we started to scan the input stream? @@ -579,6 +622,7 @@ type yaml_parser_t struct { simple_key_allowed bool // May a simple key occur at the current position? simple_keys []yaml_simple_key_t // The stack of simple keys. + simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number // Parser stuff @@ -594,6 +638,18 @@ type yaml_parser_t struct { document *yaml_document_t // The currently parsed document. } +type yaml_comment_t struct { + + scan_mark yaml_mark_t // Position where scanning for comments started + token_mark yaml_mark_t // Position after which tokens will be associated with this comment + start_mark yaml_mark_t // Position of '#' comment mark + end_mark yaml_mark_t // Position where comment terminated + + head []byte + line []byte + foot []byte +} + // Emitter Definitions // The prototype of a write handler. @@ -624,8 +680,10 @@ const ( yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. + yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE // Expect the next item of a flow sequence, with the comma already written out yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. + yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE // Expect the next key of a flow mapping, with the comma already written out yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. @@ -697,6 +755,9 @@ type yaml_emitter_t struct { indention bool // If the last character was an indentation character (' ', '-', '?', ':')? open_ended bool // If an explicit document end is required? + space_above bool // Is there's an empty line above? + foot_indent int // The indent used to write the foot comment above, or -1 if none. + // Anchor analysis. anchor_data struct { anchor []byte // The anchor value. @@ -720,6 +781,12 @@ type yaml_emitter_t struct { style yaml_scalar_style_t // The output style. } + // Comments + head_comment []byte + line_comment []byte + foot_comment []byte + tail_comment []byte + // Dumper stuff opened bool // If the stream was already opened? diff --git a/vendor/github.com/zclconf/go-cty-yaml/yamlprivateh.go b/vendor/gopkg.in/yaml.v3/yamlprivateh.go similarity index 78% rename from vendor/github.com/zclconf/go-cty-yaml/yamlprivateh.go rename to vendor/gopkg.in/yaml.v3/yamlprivateh.go index 8110ce3c37a..e88f9c54aec 100644 --- a/vendor/github.com/zclconf/go-cty-yaml/yamlprivateh.go +++ b/vendor/gopkg.in/yaml.v3/yamlprivateh.go @@ -1,3 +1,25 @@ +// +// Copyright (c) 2011-2019 Canonical Ltd +// Copyright (c) 2006-2010 Kirill Simonov +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +// of the Software, and to permit persons to whom the Software is furnished to do +// so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + package yaml const ( @@ -114,8 +136,9 @@ func is_crlf(b []byte, i int) bool { // Check if the character is a line break or NUL. func is_breakz(b []byte, i int) bool { //return is_break(b, i) || is_z(b, i) - return ( // is_break: - b[i] == '\r' || // CR (#xD) + return ( + // is_break: + b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) @@ -127,8 +150,9 @@ func is_breakz(b []byte, i int) bool { // Check if the character is a line break, space, or NUL. func is_spacez(b []byte, i int) bool { //return is_space(b, i) || is_breakz(b, i) - return ( // is_space: - b[i] == ' ' || + return ( + // is_space: + b[i] == ' ' || // is_breakz: b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) @@ -141,8 +165,9 @@ func is_spacez(b []byte, i int) bool { // Check if the character is a line break, space, tab, or NUL. func is_blankz(b []byte, i int) bool { //return is_blank(b, i) || is_breakz(b, i) - return ( // is_blank: - b[i] == ' ' || b[i] == '\t' || + return ( + // is_blank: + b[i] == ' ' || b[i] == '\t' || // is_breakz: b[i] == '\r' || // CR (#xD) b[i] == '\n' || // LF (#xA) diff --git a/vendor/honnef.co/go/tools/LICENSE-THIRD-PARTY b/vendor/honnef.co/go/tools/LICENSE-THIRD-PARTY index 7c241b71aef..623d85e85b7 100644 --- a/vendor/honnef.co/go/tools/LICENSE-THIRD-PARTY +++ b/vendor/honnef.co/go/tools/LICENSE-THIRD-PARTY @@ -75,7 +75,7 @@ resulting binaries. These projects are: limitations under the License. -* github.com/kisielk/gotool – https://github.com/kisielk/gotool +* github.com/kisielk/gotool - https://github.com/kisielk/gotool Copyright (c) 2013 Kamil Kisiel @@ -224,3 +224,61 @@ resulting binaries. These projects are: (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* gogrep - https://github.com/mvdan/gogrep + + Copyright (c) 2017, Daniel Martí. 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 the copyright holder 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +* gosmith - https://github.com/dvyukov/gosmith + + Copyright (c) 2014 Dmitry Vyukov. 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. + * The name of Dmitry Vyukov may be used to endorse or promote + products derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/honnef.co/go/tools/code/code.go b/vendor/honnef.co/go/tools/code/code.go new file mode 100644 index 00000000000..6f4df8b9aa6 --- /dev/null +++ b/vendor/honnef.co/go/tools/code/code.go @@ -0,0 +1,481 @@ +// Package code answers structural and type questions about Go code. +package code + +import ( + "flag" + "fmt" + "go/ast" + "go/constant" + "go/token" + "go/types" + "strings" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/passes/inspect" + "golang.org/x/tools/go/ast/astutil" + "golang.org/x/tools/go/ast/inspector" + "honnef.co/go/tools/facts" + "honnef.co/go/tools/go/types/typeutil" + "honnef.co/go/tools/ir" + "honnef.co/go/tools/lint" +) + +type Positioner interface { + Pos() token.Pos +} + +func CallName(call *ir.CallCommon) string { + if call.IsInvoke() { + return "" + } + switch v := call.Value.(type) { + case *ir.Function: + fn, ok := v.Object().(*types.Func) + if !ok { + return "" + } + return lint.FuncName(fn) + case *ir.Builtin: + return v.Name() + } + return "" +} + +func IsCallTo(call *ir.CallCommon, name string) bool { return CallName(call) == name } + +func IsCallToAny(call *ir.CallCommon, names ...string) bool { + q := CallName(call) + for _, name := range names { + if q == name { + return true + } + } + return false +} + +func IsType(T types.Type, name string) bool { return types.TypeString(T, nil) == name } + +func FilterDebug(instr []ir.Instruction) []ir.Instruction { + var out []ir.Instruction + for _, ins := range instr { + if _, ok := ins.(*ir.DebugRef); !ok { + out = append(out, ins) + } + } + return out +} + +func IsExample(fn *ir.Function) bool { + if !strings.HasPrefix(fn.Name(), "Example") { + return false + } + f := fn.Prog.Fset.File(fn.Pos()) + if f == nil { + return false + } + return strings.HasSuffix(f.Name(), "_test.go") +} + +func IsPointerLike(T types.Type) bool { + switch T := T.Underlying().(type) { + case *types.Interface, *types.Chan, *types.Map, *types.Signature, *types.Pointer: + return true + case *types.Basic: + return T.Kind() == types.UnsafePointer + } + return false +} + +func IsIdent(expr ast.Expr, ident string) bool { + id, ok := expr.(*ast.Ident) + return ok && id.Name == ident +} + +// isBlank returns whether id is the blank identifier "_". +// If id == nil, the answer is false. +func IsBlank(id ast.Expr) bool { + ident, _ := id.(*ast.Ident) + return ident != nil && ident.Name == "_" +} + +func IsIntLiteral(expr ast.Expr, literal string) bool { + lit, ok := expr.(*ast.BasicLit) + return ok && lit.Kind == token.INT && lit.Value == literal +} + +// Deprecated: use IsIntLiteral instead +func IsZero(expr ast.Expr) bool { + return IsIntLiteral(expr, "0") +} + +func IsOfType(pass *analysis.Pass, expr ast.Expr, name string) bool { + return IsType(pass.TypesInfo.TypeOf(expr), name) +} + +func IsInTest(pass *analysis.Pass, node Positioner) bool { + // FIXME(dh): this doesn't work for global variables with + // initializers + f := pass.Fset.File(node.Pos()) + return f != nil && strings.HasSuffix(f.Name(), "_test.go") +} + +// IsMain reports whether the package being processed is a package +// main. +func IsMain(pass *analysis.Pass) bool { + return pass.Pkg.Name() == "main" +} + +// IsMainLike reports whether the package being processed is a +// main-like package. A main-like package is a package that is +// package main, or that is intended to be used by a tool framework +// such as cobra to implement a command. +// +// Note that this function errs on the side of false positives; it may +// return true for packages that aren't main-like. IsMainLike is +// intended for analyses that wish to suppress diagnostics for +// main-like packages to avoid false positives. +func IsMainLike(pass *analysis.Pass) bool { + if pass.Pkg.Name() == "main" { + return true + } + for _, imp := range pass.Pkg.Imports() { + if imp.Path() == "github.com/spf13/cobra" { + return true + } + } + return false +} + +func SelectorName(pass *analysis.Pass, expr *ast.SelectorExpr) string { + info := pass.TypesInfo + sel := info.Selections[expr] + if sel == nil { + if x, ok := expr.X.(*ast.Ident); ok { + pkg, ok := info.ObjectOf(x).(*types.PkgName) + if !ok { + // This shouldn't happen + return fmt.Sprintf("%s.%s", x.Name, expr.Sel.Name) + } + return fmt.Sprintf("%s.%s", pkg.Imported().Path(), expr.Sel.Name) + } + panic(fmt.Sprintf("unsupported selector: %v", expr)) + } + return fmt.Sprintf("(%s).%s", sel.Recv(), sel.Obj().Name()) +} + +func IsNil(pass *analysis.Pass, expr ast.Expr) bool { + return pass.TypesInfo.Types[expr].IsNil() +} + +func BoolConst(pass *analysis.Pass, expr ast.Expr) bool { + val := pass.TypesInfo.ObjectOf(expr.(*ast.Ident)).(*types.Const).Val() + return constant.BoolVal(val) +} + +func IsBoolConst(pass *analysis.Pass, expr ast.Expr) bool { + // We explicitly don't support typed bools because more often than + // not, custom bool types are used as binary enums and the + // explicit comparison is desired. + + ident, ok := expr.(*ast.Ident) + if !ok { + return false + } + obj := pass.TypesInfo.ObjectOf(ident) + c, ok := obj.(*types.Const) + if !ok { + return false + } + basic, ok := c.Type().(*types.Basic) + if !ok { + return false + } + if basic.Kind() != types.UntypedBool && basic.Kind() != types.Bool { + return false + } + return true +} + +func ExprToInt(pass *analysis.Pass, expr ast.Expr) (int64, bool) { + tv := pass.TypesInfo.Types[expr] + if tv.Value == nil { + return 0, false + } + if tv.Value.Kind() != constant.Int { + return 0, false + } + return constant.Int64Val(tv.Value) +} + +func ExprToString(pass *analysis.Pass, expr ast.Expr) (string, bool) { + val := pass.TypesInfo.Types[expr].Value + if val == nil { + return "", false + } + if val.Kind() != constant.String { + return "", false + } + return constant.StringVal(val), true +} + +// Dereference returns a pointer's element type; otherwise it returns +// T. +func Dereference(T types.Type) types.Type { + if p, ok := T.Underlying().(*types.Pointer); ok { + return p.Elem() + } + return T +} + +// DereferenceR returns a pointer's element type; otherwise it returns +// T. If the element type is itself a pointer, DereferenceR will be +// applied recursively. +func DereferenceR(T types.Type) types.Type { + if p, ok := T.Underlying().(*types.Pointer); ok { + return DereferenceR(p.Elem()) + } + return T +} + +func CallNameAST(pass *analysis.Pass, call *ast.CallExpr) string { + switch fun := astutil.Unparen(call.Fun).(type) { + case *ast.SelectorExpr: + fn, ok := pass.TypesInfo.ObjectOf(fun.Sel).(*types.Func) + if !ok { + return "" + } + return lint.FuncName(fn) + case *ast.Ident: + obj := pass.TypesInfo.ObjectOf(fun) + switch obj := obj.(type) { + case *types.Func: + return lint.FuncName(obj) + case *types.Builtin: + return obj.Name() + default: + return "" + } + default: + return "" + } +} + +func IsCallToAST(pass *analysis.Pass, node ast.Node, name string) bool { + call, ok := node.(*ast.CallExpr) + if !ok { + return false + } + return CallNameAST(pass, call) == name +} + +func IsCallToAnyAST(pass *analysis.Pass, node ast.Node, names ...string) bool { + call, ok := node.(*ast.CallExpr) + if !ok { + return false + } + q := CallNameAST(pass, call) + for _, name := range names { + if q == name { + return true + } + } + return false +} + +func Preamble(f *ast.File) string { + cutoff := f.Package + if f.Doc != nil { + cutoff = f.Doc.Pos() + } + var out []string + for _, cmt := range f.Comments { + if cmt.Pos() >= cutoff { + break + } + out = append(out, cmt.Text()) + } + return strings.Join(out, "\n") +} + +func GroupSpecs(fset *token.FileSet, specs []ast.Spec) [][]ast.Spec { + if len(specs) == 0 { + return nil + } + groups := make([][]ast.Spec, 1) + groups[0] = append(groups[0], specs[0]) + + for _, spec := range specs[1:] { + g := groups[len(groups)-1] + if fset.PositionFor(spec.Pos(), false).Line-1 != + fset.PositionFor(g[len(g)-1].End(), false).Line { + + groups = append(groups, nil) + } + + groups[len(groups)-1] = append(groups[len(groups)-1], spec) + } + + return groups +} + +func IsObject(obj types.Object, name string) bool { + var path string + if pkg := obj.Pkg(); pkg != nil { + path = pkg.Path() + "." + } + return path+obj.Name() == name +} + +type Field struct { + Var *types.Var + Tag string + Path []int +} + +// FlattenFields recursively flattens T and embedded structs, +// returning a list of fields. If multiple fields with the same name +// exist, all will be returned. +func FlattenFields(T *types.Struct) []Field { + return flattenFields(T, nil, nil) +} + +func flattenFields(T *types.Struct, path []int, seen map[types.Type]bool) []Field { + if seen == nil { + seen = map[types.Type]bool{} + } + if seen[T] { + return nil + } + seen[T] = true + var out []Field + for i := 0; i < T.NumFields(); i++ { + field := T.Field(i) + tag := T.Tag(i) + np := append(path[:len(path):len(path)], i) + if field.Anonymous() { + if s, ok := Dereference(field.Type()).Underlying().(*types.Struct); ok { + out = append(out, flattenFields(s, np, seen)...) + } + } else { + out = append(out, Field{field, tag, np}) + } + } + return out +} + +func File(pass *analysis.Pass, node Positioner) *ast.File { + m := pass.ResultOf[facts.TokenFile].(map[*token.File]*ast.File) + return m[pass.Fset.File(node.Pos())] +} + +// IsGenerated reports whether pos is in a generated file, It ignores +// //line directives. +func IsGenerated(pass *analysis.Pass, pos token.Pos) bool { + _, ok := Generator(pass, pos) + return ok +} + +// Generator returns the generator that generated the file containing +// pos. It ignores //line directives. +func Generator(pass *analysis.Pass, pos token.Pos) (facts.Generator, bool) { + file := pass.Fset.PositionFor(pos, false).Filename + m := pass.ResultOf[facts.Generated].(map[string]facts.Generator) + g, ok := m[file] + return g, ok +} + +// MayHaveSideEffects reports whether expr may have side effects. If +// the purity argument is nil, this function implements a purely +// syntactic check, meaning that any function call may have side +// effects, regardless of the called function's body. Otherwise, +// purity will be consulted to determine the purity of function calls. +func MayHaveSideEffects(pass *analysis.Pass, expr ast.Expr, purity facts.PurityResult) bool { + switch expr := expr.(type) { + case *ast.BadExpr: + return true + case *ast.Ellipsis: + return MayHaveSideEffects(pass, expr.Elt, purity) + case *ast.FuncLit: + // the literal itself cannot have side ffects, only calling it + // might, which is handled by CallExpr. + return false + case *ast.ArrayType, *ast.StructType, *ast.FuncType, *ast.InterfaceType, *ast.MapType, *ast.ChanType: + // types cannot have side effects + return false + case *ast.BasicLit: + return false + case *ast.BinaryExpr: + return MayHaveSideEffects(pass, expr.X, purity) || MayHaveSideEffects(pass, expr.Y, purity) + case *ast.CallExpr: + if purity == nil { + return true + } + switch obj := typeutil.Callee(pass.TypesInfo, expr).(type) { + case *types.Func: + if _, ok := purity[obj]; !ok { + return true + } + case *types.Builtin: + switch obj.Name() { + case "len", "cap": + default: + return true + } + default: + return true + } + for _, arg := range expr.Args { + if MayHaveSideEffects(pass, arg, purity) { + return true + } + } + return false + case *ast.CompositeLit: + if MayHaveSideEffects(pass, expr.Type, purity) { + return true + } + for _, elt := range expr.Elts { + if MayHaveSideEffects(pass, elt, purity) { + return true + } + } + return false + case *ast.Ident: + return false + case *ast.IndexExpr: + return MayHaveSideEffects(pass, expr.X, purity) || MayHaveSideEffects(pass, expr.Index, purity) + case *ast.KeyValueExpr: + return MayHaveSideEffects(pass, expr.Key, purity) || MayHaveSideEffects(pass, expr.Value, purity) + case *ast.SelectorExpr: + return MayHaveSideEffects(pass, expr.X, purity) + case *ast.SliceExpr: + return MayHaveSideEffects(pass, expr.X, purity) || + MayHaveSideEffects(pass, expr.Low, purity) || + MayHaveSideEffects(pass, expr.High, purity) || + MayHaveSideEffects(pass, expr.Max, purity) + case *ast.StarExpr: + return MayHaveSideEffects(pass, expr.X, purity) + case *ast.TypeAssertExpr: + return MayHaveSideEffects(pass, expr.X, purity) + case *ast.UnaryExpr: + if MayHaveSideEffects(pass, expr.X, purity) { + return true + } + return expr.Op == token.ARROW + case *ast.ParenExpr: + return MayHaveSideEffects(pass, expr.X, purity) + case nil: + return false + default: + panic(fmt.Sprintf("internal error: unhandled type %T", expr)) + } +} + +func IsGoVersion(pass *analysis.Pass, minor int) bool { + version := pass.Analyzer.Flags.Lookup("go").Value.(flag.Getter).Get().(int) + return version >= minor +} + +func Preorder(pass *analysis.Pass, fn func(ast.Node), types ...ast.Node) { + pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder(types, fn) +} diff --git a/vendor/honnef.co/go/tools/config/config.go b/vendor/honnef.co/go/tools/config/config.go index c22093a6d98..55115371b9f 100644 --- a/vendor/honnef.co/go/tools/config/config.go +++ b/vendor/honnef.co/go/tools/config/config.go @@ -3,6 +3,8 @@ package config import ( "bytes" "fmt" + "go/ast" + "go/token" "os" "path/filepath" "reflect" @@ -12,38 +14,57 @@ import ( "golang.org/x/tools/go/analysis" ) +// Dir looks at a list of absolute file names, which should make up a +// single package, and returns the path of the directory that may +// contain a staticcheck.conf file. It returns the empty string if no +// such directory could be determined, for example because all files +// were located in Go's build cache. +func Dir(files []string) string { + if len(files) == 0 { + return "" + } + cache, err := os.UserCacheDir() + if err != nil { + cache = "" + } + var path string + for _, p := range files { + // FIXME(dh): using strings.HasPrefix isn't technically + // correct, but it should be good enough for now. + if cache != "" && strings.HasPrefix(p, cache) { + // File in the build cache of the standard Go build system + continue + } + path = p + break + } + + if path == "" { + // The package only consists of generated files. + return "" + } + + dir := filepath.Dir(path) + return dir +} + +func dirAST(files []*ast.File, fset *token.FileSet) string { + names := make([]string, len(files)) + for i, f := range files { + names[i] = fset.PositionFor(f.Pos(), true).Filename + } + return Dir(names) +} + var Analyzer = &analysis.Analyzer{ Name: "config", Doc: "loads configuration for the current package tree", Run: func(pass *analysis.Pass) (interface{}, error) { - if len(pass.Files) == 0 { - cfg := DefaultConfig - return &cfg, nil - } - cache, err := os.UserCacheDir() - if err != nil { - cache = "" - } - var path string - for _, f := range pass.Files { - p := pass.Fset.PositionFor(f.Pos(), true).Filename - // FIXME(dh): using strings.HasPrefix isn't technically - // correct, but it should be good enough for now. - if cache != "" && strings.HasPrefix(p, cache) { - // File in the build cache of the standard Go build system - continue - } - path = p - break - } - - if path == "" { - // The package only consists of generated files. + dir := dirAST(pass.Files, pass.Fset) + if dir == "" { cfg := DefaultConfig return &cfg, nil } - - dir := filepath.Dir(path) cfg, err := Load(dir) if err != nil { return nil, fmt.Errorf("error loading staticcheck.conf: %s", err) @@ -136,7 +157,7 @@ func (c Config) String() string { } var DefaultConfig = Config{ - Checks: []string{"all", "-ST1000", "-ST1003", "-ST1016"}, + Checks: []string{"all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022"}, Initialisms: []string{ "ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", @@ -144,20 +165,20 @@ var DefaultConfig = Config{ "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "GID", "UID", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", - "XSS", "SIP", "RTP", + "XSS", "SIP", "RTP", "AMQP", "DB", "TS", }, DotImportWhitelist: []string{}, HTTPStatusCodeWhitelist: []string{"200", "400", "404", "500"}, } -const configName = "staticcheck.conf" +const ConfigName = "staticcheck.conf" func parseConfigs(dir string) ([]Config, error) { var out []Config // TODO(dh): consider stopping at the GOPATH/module boundary for dir != "" { - f, err := os.Open(filepath.Join(dir, configName)) + f, err := os.Open(filepath.Join(dir, ConfigName)) if os.IsNotExist(err) { ndir := filepath.Dir(dir) if ndir == dir { diff --git a/vendor/honnef.co/go/tools/deprecated/stdlib.go b/vendor/honnef.co/go/tools/deprecated/stdlib.go index 5d8ce186b16..cabb8500a25 100644 --- a/vendor/honnef.co/go/tools/deprecated/stdlib.go +++ b/vendor/honnef.co/go/tools/deprecated/stdlib.go @@ -6,7 +6,6 @@ type Deprecation struct { } var Stdlib = map[string]Deprecation{ - "image/jpeg.Reader": {4, 0}, // FIXME(dh): AllowBinary isn't being detected as deprecated // because the comment has a newline right after "Deprecated:" "go/build.AllowBinary": {7, 7}, @@ -73,40 +72,48 @@ var Stdlib = map[string]Deprecation{ // This function has no alternative, but also no purpose. "(*crypto/rc4.Cipher).Reset": {12, 0}, "(net/http/httptest.ResponseRecorder).HeaderMap": {11, 7}, + "image.ZP": {13, 0}, + "image.ZR": {13, 0}, + "(*debug/gosym.LineTable).LineToPC": {2, 2}, + "(*debug/gosym.LineTable).PCToLine": {2, 2}, + "crypto/tls.VersionSSL30": {13, 0}, + "(crypto/tls.Config).NameToCertificate": {14, 14}, + "(*crypto/tls.Config).BuildNameToCertificate": {14, 14}, + "image/jpeg.Reader": {4, 0}, // All of these have been deprecated in favour of external libraries - "syscall.AttachLsf": {7, 0}, - "syscall.DetachLsf": {7, 0}, - "syscall.LsfSocket": {7, 0}, - "syscall.SetLsfPromisc": {7, 0}, - "syscall.LsfJump": {7, 0}, - "syscall.LsfStmt": {7, 0}, - "syscall.BpfStmt": {7, 0}, - "syscall.BpfJump": {7, 0}, - "syscall.BpfBuflen": {7, 0}, - "syscall.SetBpfBuflen": {7, 0}, - "syscall.BpfDatalink": {7, 0}, - "syscall.SetBpfDatalink": {7, 0}, - "syscall.SetBpfPromisc": {7, 0}, - "syscall.FlushBpf": {7, 0}, - "syscall.BpfInterface": {7, 0}, - "syscall.SetBpfInterface": {7, 0}, - "syscall.BpfTimeout": {7, 0}, - "syscall.SetBpfTimeout": {7, 0}, - "syscall.BpfStats": {7, 0}, - "syscall.SetBpfImmediate": {7, 0}, - "syscall.SetBpf": {7, 0}, - "syscall.CheckBpfVersion": {7, 0}, - "syscall.BpfHeadercmpl": {7, 0}, - "syscall.SetBpfHeadercmpl": {7, 0}, - "syscall.RouteRIB": {8, 0}, - "syscall.RoutingMessage": {8, 0}, - "syscall.RouteMessage": {8, 0}, - "syscall.InterfaceMessage": {8, 0}, - "syscall.InterfaceAddrMessage": {8, 0}, - "syscall.ParseRoutingMessage": {8, 0}, - "syscall.ParseRoutingSockaddr": {8, 0}, - "InterfaceAnnounceMessage": {7, 0}, - "InterfaceMulticastAddrMessage": {7, 0}, - "syscall.FormatMessage": {5, 0}, + "syscall.AttachLsf": {7, 0}, + "syscall.DetachLsf": {7, 0}, + "syscall.LsfSocket": {7, 0}, + "syscall.SetLsfPromisc": {7, 0}, + "syscall.LsfJump": {7, 0}, + "syscall.LsfStmt": {7, 0}, + "syscall.BpfStmt": {7, 0}, + "syscall.BpfJump": {7, 0}, + "syscall.BpfBuflen": {7, 0}, + "syscall.SetBpfBuflen": {7, 0}, + "syscall.BpfDatalink": {7, 0}, + "syscall.SetBpfDatalink": {7, 0}, + "syscall.SetBpfPromisc": {7, 0}, + "syscall.FlushBpf": {7, 0}, + "syscall.BpfInterface": {7, 0}, + "syscall.SetBpfInterface": {7, 0}, + "syscall.BpfTimeout": {7, 0}, + "syscall.SetBpfTimeout": {7, 0}, + "syscall.BpfStats": {7, 0}, + "syscall.SetBpfImmediate": {7, 0}, + "syscall.SetBpf": {7, 0}, + "syscall.CheckBpfVersion": {7, 0}, + "syscall.BpfHeadercmpl": {7, 0}, + "syscall.SetBpfHeadercmpl": {7, 0}, + "syscall.RouteRIB": {8, 0}, + "syscall.RoutingMessage": {8, 0}, + "syscall.RouteMessage": {8, 0}, + "syscall.InterfaceMessage": {8, 0}, + "syscall.InterfaceAddrMessage": {8, 0}, + "syscall.ParseRoutingMessage": {8, 0}, + "syscall.ParseRoutingSockaddr": {8, 0}, + "syscall.InterfaceAnnounceMessage": {7, 0}, + "syscall.InterfaceMulticastAddrMessage": {7, 0}, + "syscall.FormatMessage": {5, 0}, } diff --git a/vendor/honnef.co/go/tools/edit/edit.go b/vendor/honnef.co/go/tools/edit/edit.go new file mode 100644 index 00000000000..f4cfba2347c --- /dev/null +++ b/vendor/honnef.co/go/tools/edit/edit.go @@ -0,0 +1,67 @@ +package edit + +import ( + "bytes" + "go/ast" + "go/format" + "go/token" + + "golang.org/x/tools/go/analysis" + "honnef.co/go/tools/pattern" +) + +type Ranger interface { + Pos() token.Pos + End() token.Pos +} + +type Range [2]token.Pos + +func (r Range) Pos() token.Pos { return r[0] } +func (r Range) End() token.Pos { return r[1] } + +func ReplaceWithString(fset *token.FileSet, old Ranger, new string) analysis.TextEdit { + return analysis.TextEdit{ + Pos: old.Pos(), + End: old.End(), + NewText: []byte(new), + } +} + +func ReplaceWithNode(fset *token.FileSet, old Ranger, new ast.Node) analysis.TextEdit { + buf := &bytes.Buffer{} + if err := format.Node(buf, fset, new); err != nil { + panic("internal error: " + err.Error()) + } + return analysis.TextEdit{ + Pos: old.Pos(), + End: old.End(), + NewText: buf.Bytes(), + } +} + +func ReplaceWithPattern(pass *analysis.Pass, after pattern.Pattern, state pattern.State, node Ranger) analysis.TextEdit { + r := pattern.NodeToAST(after.Root, state) + buf := &bytes.Buffer{} + format.Node(buf, pass.Fset, r) + return analysis.TextEdit{ + Pos: node.Pos(), + End: node.End(), + NewText: buf.Bytes(), + } +} + +func Delete(old Ranger) analysis.TextEdit { + return analysis.TextEdit{ + Pos: old.Pos(), + End: old.End(), + NewText: nil, + } +} + +func Fix(msg string, edits ...analysis.TextEdit) analysis.SuggestedFix { + return analysis.SuggestedFix{ + Message: msg, + TextEdits: edits, + } +} diff --git a/vendor/honnef.co/go/tools/facts/generated.go b/vendor/honnef.co/go/tools/facts/generated.go index 1ed9563a30b..18cbb49bd9a 100644 --- a/vendor/honnef.co/go/tools/facts/generated.go +++ b/vendor/honnef.co/go/tools/facts/generated.go @@ -19,6 +19,7 @@ const ( Goyacc Cgo Stringer + ProtocGenGo ) var ( @@ -51,10 +52,16 @@ func isGenerated(path string) (Generator, bool) { return Goyacc, true case "by cmd/cgo;": return Cgo, true + case "by protoc-gen-go.": + return ProtocGenGo, true } if strings.HasPrefix(text, `by "stringer `) { return Stringer, true } + if strings.HasPrefix(text, `by goyacc `) { + return Goyacc, true + } + return Unknown, true } if bytes.Equal(s, oldCgo) { diff --git a/vendor/honnef.co/go/tools/facts/purity.go b/vendor/honnef.co/go/tools/facts/purity.go index 861ca41104a..099ee23e3b8 100644 --- a/vendor/honnef.co/go/tools/facts/purity.go +++ b/vendor/honnef.co/go/tools/facts/purity.go @@ -1,14 +1,13 @@ package facts import ( - "go/token" "go/types" "reflect" "golang.org/x/tools/go/analysis" "honnef.co/go/tools/functions" - "honnef.co/go/tools/internal/passes/buildssa" - "honnef.co/go/tools/ssa" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/ir" ) type IsPure struct{} @@ -22,7 +21,7 @@ var Purity = &analysis.Analyzer{ Name: "fact_purity", Doc: "Mark pure functions", Run: purity, - Requires: []*analysis.Analyzer{buildssa.Analyzer}, + Requires: []*analysis.Analyzer{buildir.Analyzer}, FactTypes: []analysis.Fact{(*IsPure)(nil)}, ResultType: reflect.TypeOf(PurityResult{}), } @@ -56,65 +55,68 @@ var pureStdlib = map[string]struct{}{ } func purity(pass *analysis.Pass) (interface{}, error) { - seen := map[*ssa.Function]struct{}{} - ssapkg := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).Pkg - var check func(ssafn *ssa.Function) (ret bool) - check = func(ssafn *ssa.Function) (ret bool) { - if ssafn.Object() == nil { + seen := map[*ir.Function]struct{}{} + irpkg := pass.ResultOf[buildir.Analyzer].(*buildir.IR).Pkg + var check func(fn *ir.Function) (ret bool) + check = func(fn *ir.Function) (ret bool) { + if fn.Object() == nil { // TODO(dh): support closures return false } - if pass.ImportObjectFact(ssafn.Object(), new(IsPure)) { + if pass.ImportObjectFact(fn.Object(), new(IsPure)) { return true } - if ssafn.Pkg != ssapkg { + if fn.Pkg != irpkg { // Function is in another package but wasn't marked as // pure, ergo it isn't pure return false } // Break recursion - if _, ok := seen[ssafn]; ok { + if _, ok := seen[fn]; ok { return false } - seen[ssafn] = struct{}{} + seen[fn] = struct{}{} defer func() { if ret { - pass.ExportObjectFact(ssafn.Object(), &IsPure{}) + pass.ExportObjectFact(fn.Object(), &IsPure{}) } }() - if functions.IsStub(ssafn) { + if functions.IsStub(fn) { return false } - if _, ok := pureStdlib[ssafn.Object().(*types.Func).FullName()]; ok { + if _, ok := pureStdlib[fn.Object().(*types.Func).FullName()]; ok { return true } - if ssafn.Signature.Results().Len() == 0 { + if fn.Signature.Results().Len() == 0 { // A function with no return values is empty or is doing some // work we cannot see (for example because of build tags); // don't consider it pure. return false } - for _, param := range ssafn.Params { + for _, param := range fn.Params { + // TODO(dh): this may not be strictly correct. pure code + // can, to an extent, operate on non-basic types. if _, ok := param.Type().Underlying().(*types.Basic); !ok { return false } } - if ssafn.Blocks == nil { + // Don't consider external functions pure. + if fn.Blocks == nil { return false } - checkCall := func(common *ssa.CallCommon) bool { + checkCall := func(common *ir.CallCommon) bool { if common.IsInvoke() { return false } - builtin, ok := common.Value.(*ssa.Builtin) + builtin, ok := common.Value.(*ir.Builtin) if !ok { - if common.StaticCallee() != ssafn { + if common.StaticCallee() != fn { if common.StaticCallee() == nil { return false } @@ -124,47 +126,47 @@ func purity(pass *analysis.Pass) (interface{}, error) { } } else { switch builtin.Name() { - case "len", "cap", "make", "new": + case "len", "cap": default: return false } } return true } - for _, b := range ssafn.Blocks { + for _, b := range fn.Blocks { for _, ins := range b.Instrs { switch ins := ins.(type) { - case *ssa.Call: + case *ir.Call: if !checkCall(ins.Common()) { return false } - case *ssa.Defer: + case *ir.Defer: if !checkCall(&ins.Call) { return false } - case *ssa.Select: + case *ir.Select: return false - case *ssa.Send: + case *ir.Send: return false - case *ssa.Go: + case *ir.Go: return false - case *ssa.Panic: + case *ir.Panic: return false - case *ssa.Store: + case *ir.Store: return false - case *ssa.FieldAddr: + case *ir.FieldAddr: + return false + case *ir.Alloc: + return false + case *ir.Load: return false - case *ssa.UnOp: - if ins.Op == token.MUL || ins.Op == token.AND { - return false - } } } } return true } - for _, ssafn := range pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs { - check(ssafn) + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + check(fn) } out := PurityResult{} diff --git a/vendor/honnef.co/go/tools/functions/loops.go b/vendor/honnef.co/go/tools/functions/loops.go index 15877a2f96b..a8af7010084 100644 --- a/vendor/honnef.co/go/tools/functions/loops.go +++ b/vendor/honnef.co/go/tools/functions/loops.go @@ -1,10 +1,10 @@ package functions -import "honnef.co/go/tools/ssa" +import "honnef.co/go/tools/ir" -type Loop struct{ ssa.BlockSet } +type Loop struct{ *ir.BlockSet } -func FindLoops(fn *ssa.Function) []Loop { +func FindLoops(fn *ir.Function) []Loop { if fn.Blocks == nil { return nil } @@ -18,12 +18,12 @@ func FindLoops(fn *ssa.Function) []Loop { // n is a back-edge to h // h is the loop header if n == h { - set := Loop{} + set := Loop{ir.NewBlockSet(len(fn.Blocks))} set.Add(n) sets = append(sets, set) continue } - set := Loop{} + set := Loop{ir.NewBlockSet(len(fn.Blocks))} set.Add(h) set.Add(n) for _, b := range allPredsBut(n, h, nil) { @@ -35,7 +35,7 @@ func FindLoops(fn *ssa.Function) []Loop { return sets } -func allPredsBut(b, but *ssa.BasicBlock, list []*ssa.BasicBlock) []*ssa.BasicBlock { +func allPredsBut(b, but *ir.BasicBlock, list []*ir.BasicBlock) []*ir.BasicBlock { outer: for _, pred := range b.Preds { if pred == but { diff --git a/vendor/honnef.co/go/tools/functions/pure.go b/vendor/honnef.co/go/tools/functions/pure.go deleted file mode 100644 index 8bc5587713a..00000000000 --- a/vendor/honnef.co/go/tools/functions/pure.go +++ /dev/null @@ -1,46 +0,0 @@ -package functions - -import ( - "honnef.co/go/tools/ssa" -) - -func filterDebug(instr []ssa.Instruction) []ssa.Instruction { - var out []ssa.Instruction - for _, ins := range instr { - if _, ok := ins.(*ssa.DebugRef); !ok { - out = append(out, ins) - } - } - return out -} - -// IsStub reports whether a function is a stub. A function is -// considered a stub if it has no instructions or exactly one -// instruction, which must be either returning only constant values or -// a panic. -func IsStub(fn *ssa.Function) bool { - if len(fn.Blocks) == 0 { - return true - } - if len(fn.Blocks) > 1 { - return false - } - instrs := filterDebug(fn.Blocks[0].Instrs) - if len(instrs) != 1 { - return false - } - - switch instrs[0].(type) { - case *ssa.Return: - // Since this is the only instruction, the return value must - // be a constant. We consider all constants as stubs, not just - // the zero value. This does not, unfortunately, cover zero - // initialised structs, as these cause additional - // instructions. - return true - case *ssa.Panic: - return true - default: - return false - } -} diff --git a/vendor/honnef.co/go/tools/functions/stub.go b/vendor/honnef.co/go/tools/functions/stub.go new file mode 100644 index 00000000000..4d5de10b85c --- /dev/null +++ b/vendor/honnef.co/go/tools/functions/stub.go @@ -0,0 +1,32 @@ +package functions + +import ( + "honnef.co/go/tools/ir" +) + +// IsStub reports whether a function is a stub. A function is +// considered a stub if it has no instructions or if all it does is +// return a constant value. +func IsStub(fn *ir.Function) bool { + for _, b := range fn.Blocks { + for _, instr := range b.Instrs { + switch instr.(type) { + case *ir.Const: + // const naturally has no side-effects + case *ir.Panic: + // panic is a stub if it only uses constants + case *ir.Return: + // return is a stub if it only uses constants + case *ir.DebugRef: + case *ir.Jump: + // if there are no disallowed instructions, then we're + // only jumping to the exit block (or possibly + // somewhere else that's stubby?) + default: + // all other instructions are assumed to do actual work + return false + } + } + } + return true +} diff --git a/vendor/honnef.co/go/tools/functions/terminates.go b/vendor/honnef.co/go/tools/functions/terminates.go index 3e9c3a23f37..c4984673f64 100644 --- a/vendor/honnef.co/go/tools/functions/terminates.go +++ b/vendor/honnef.co/go/tools/functions/terminates.go @@ -1,11 +1,15 @@ package functions -import "honnef.co/go/tools/ssa" +import ( + "go/types" + + "honnef.co/go/tools/ir" +) // Terminates reports whether fn is supposed to return, that is if it // has at least one theoretic path that returns from the function. // Explicit panics do not count as terminating. -func Terminates(fn *ssa.Function) bool { +func Terminates(fn *ir.Function) bool { if fn.Blocks == nil { // assuming that a function terminates is the conservative // choice @@ -13,11 +17,53 @@ func Terminates(fn *ssa.Function) bool { } for _, block := range fn.Blocks { - if len(block.Instrs) == 0 { - continue - } - if _, ok := block.Instrs[len(block.Instrs)-1].(*ssa.Return); ok { - return true + if _, ok := block.Control().(*ir.Return); ok { + if len(block.Preds) == 0 { + return true + } + for _, pred := range block.Preds { + switch ctrl := pred.Control().(type) { + case *ir.Panic: + // explicit panics do not count as terminating + case *ir.If: + // Check if we got here by receiving from a closed + // time.Tick channel – this cannot happen at + // runtime and thus doesn't constitute termination + iff := ctrl + if !ok { + return true + } + ex, ok := iff.Cond.(*ir.Extract) + if !ok { + return true + } + if ex.Index != 1 { + return true + } + recv, ok := ex.Tuple.(*ir.Recv) + if !ok { + return true + } + call, ok := recv.Chan.(*ir.Call) + if !ok { + return true + } + fn, ok := call.Common().Value.(*ir.Function) + if !ok { + return true + } + fn2, ok := fn.Object().(*types.Func) + if !ok { + return true + } + if fn2.FullName() != "time.Tick" { + return true + } + default: + // we've reached the exit block + return true + } + } } } return false diff --git a/vendor/honnef.co/go/tools/internal/cache/cache.go b/vendor/honnef.co/go/tools/internal/cache/cache.go index 2b33ca10671..6b41811cf25 100644 --- a/vendor/honnef.co/go/tools/internal/cache/cache.go +++ b/vendor/honnef.co/go/tools/internal/cache/cache.go @@ -177,7 +177,7 @@ func (c *Cache) get(id ActionID) (Entry, error) { i++ } tm, err := strconv.ParseInt(string(etime[i:]), 10, 64) - if err != nil || size < 0 { + if err != nil || tm < 0 { return missing() } @@ -265,7 +265,7 @@ func (c *Cache) Trim() { // We maintain in dir/trim.txt the time of the last completed cache trim. // If the cache has been trimmed recently enough, do nothing. // This is the common case. - data, _ := ioutil.ReadFile(filepath.Join(c.dir, "trim.txt")) + data, _ := renameio.ReadFile(filepath.Join(c.dir, "trim.txt")) t, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64) if err == nil && now.Sub(time.Unix(t, 0)) < trimInterval { return @@ -282,7 +282,7 @@ func (c *Cache) Trim() { // Ignore errors from here: if we don't write the complete timestamp, the // cache will appear older than it is, and we'll trim it again next time. - renameio.WriteFile(filepath.Join(c.dir, "trim.txt"), []byte(fmt.Sprintf("%d", now.Unix()))) + renameio.WriteFile(filepath.Join(c.dir, "trim.txt"), []byte(fmt.Sprintf("%d", now.Unix())), 0666) } // trimSubdir trims a single cache subdirectory. @@ -326,7 +326,8 @@ func (c *Cache) putIndexEntry(id ActionID, out OutputID, size int64, allowVerify // in verify mode we are double-checking that the cache entries // are entirely reproducible. As just noted, this may be unrealistic // in some cases but the check is also useful for shaking out real bugs. - entry := []byte(fmt.Sprintf("v1 %x %x %20d %20d\n", id, out, size, time.Now().UnixNano())) + entry := fmt.Sprintf("v1 %x %x %20d %20d\n", id, out, size, time.Now().UnixNano()) + if verify && allowVerify { old, err := c.get(id) if err == nil && (old.OutputID != out || old.Size != size) { @@ -336,7 +337,28 @@ func (c *Cache) putIndexEntry(id ActionID, out OutputID, size int64, allowVerify } } file := c.fileName(id, "a") - if err := ioutil.WriteFile(file, entry, 0666); err != nil { + + // Copy file to cache directory. + mode := os.O_WRONLY | os.O_CREATE + f, err := os.OpenFile(file, mode, 0666) + if err != nil { + return err + } + _, err = f.WriteString(entry) + if err == nil { + // Truncate the file only *after* writing it. + // (This should be a no-op, but truncate just in case of previous corruption.) + // + // This differs from ioutil.WriteFile, which truncates to 0 *before* writing + // via os.O_TRUNC. Truncating only after writing ensures that a second write + // of the same content to the same file is idempotent, and does not — even + // temporarily! — undo the effect of the first write. + err = f.Truncate(int64(len(entry))) + } + if closeErr := f.Close(); err == nil { + err = closeErr + } + if err != nil { // TODO(bcmills): This Remove potentially races with another go command writing to file. // Can we eliminate it? os.Remove(file) diff --git a/vendor/honnef.co/go/tools/internal/passes/buildir/buildir.go b/vendor/honnef.co/go/tools/internal/passes/buildir/buildir.go new file mode 100644 index 00000000000..39469770248 --- /dev/null +++ b/vendor/honnef.co/go/tools/internal/passes/buildir/buildir.go @@ -0,0 +1,113 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package buildir defines an Analyzer that constructs the IR +// of an error-free package and returns the set of all +// functions within it. It does not report any diagnostics itself but +// may be used as an input to other analyzers. +// +// THIS INTERFACE IS EXPERIMENTAL AND MAY BE SUBJECT TO INCOMPATIBLE CHANGE. +package buildir + +import ( + "go/ast" + "go/types" + "reflect" + + "golang.org/x/tools/go/analysis" + "honnef.co/go/tools/ir" +) + +type willExit struct{} +type willUnwind struct{} + +func (*willExit) AFact() {} +func (*willUnwind) AFact() {} + +var Analyzer = &analysis.Analyzer{ + Name: "buildir", + Doc: "build IR for later passes", + Run: run, + ResultType: reflect.TypeOf(new(IR)), + FactTypes: []analysis.Fact{new(willExit), new(willUnwind)}, +} + +// IR provides intermediate representation for all the +// non-blank source functions in the current package. +type IR struct { + Pkg *ir.Package + SrcFuncs []*ir.Function +} + +func run(pass *analysis.Pass) (interface{}, error) { + // Plundered from ssautil.BuildPackage. + + // We must create a new Program for each Package because the + // analysis API provides no place to hang a Program shared by + // all Packages. Consequently, IR Packages and Functions do not + // have a canonical representation across an analysis session of + // multiple packages. This is unlikely to be a problem in + // practice because the analysis API essentially forces all + // packages to be analysed independently, so any given call to + // Analysis.Run on a package will see only IR objects belonging + // to a single Program. + + mode := ir.GlobalDebug + + prog := ir.NewProgram(pass.Fset, mode) + + // Create IR packages for all imports. + // Order is not significant. + created := make(map[*types.Package]bool) + var createAll func(pkgs []*types.Package) + createAll = func(pkgs []*types.Package) { + for _, p := range pkgs { + if !created[p] { + created[p] = true + irpkg := prog.CreatePackage(p, nil, nil, true) + for _, fn := range irpkg.Functions { + if ast.IsExported(fn.Name()) { + var exit willExit + var unwind willUnwind + if pass.ImportObjectFact(fn.Object(), &exit) { + fn.WillExit = true + } + if pass.ImportObjectFact(fn.Object(), &unwind) { + fn.WillUnwind = true + } + } + } + createAll(p.Imports()) + } + } + } + createAll(pass.Pkg.Imports()) + + // Create and build the primary package. + irpkg := prog.CreatePackage(pass.Pkg, pass.Files, pass.TypesInfo, false) + irpkg.Build() + + // Compute list of source functions, including literals, + // in source order. + var addAnons func(f *ir.Function) + funcs := make([]*ir.Function, len(irpkg.Functions)) + copy(funcs, irpkg.Functions) + addAnons = func(f *ir.Function) { + for _, anon := range f.AnonFuncs { + funcs = append(funcs, anon) + addAnons(anon) + } + } + for _, fn := range irpkg.Functions { + addAnons(fn) + if fn.WillExit { + pass.ExportObjectFact(fn.Object(), new(willExit)) + } + if fn.WillUnwind { + pass.ExportObjectFact(fn.Object(), new(willUnwind)) + } + } + + return &IR{Pkg: irpkg, SrcFuncs: funcs}, nil +} diff --git a/vendor/honnef.co/go/tools/internal/passes/buildssa/buildssa.go b/vendor/honnef.co/go/tools/internal/passes/buildssa/buildssa.go deleted file mode 100644 index fde918d1213..00000000000 --- a/vendor/honnef.co/go/tools/internal/passes/buildssa/buildssa.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package buildssa defines an Analyzer that constructs the SSA -// representation of an error-free package and returns the set of all -// functions within it. It does not report any diagnostics itself but -// may be used as an input to other analyzers. -// -// THIS INTERFACE IS EXPERIMENTAL AND MAY BE SUBJECT TO INCOMPATIBLE CHANGE. -package buildssa - -import ( - "go/ast" - "go/types" - "reflect" - - "golang.org/x/tools/go/analysis" - "honnef.co/go/tools/ssa" -) - -var Analyzer = &analysis.Analyzer{ - Name: "buildssa", - Doc: "build SSA-form IR for later passes", - Run: run, - ResultType: reflect.TypeOf(new(SSA)), -} - -// SSA provides SSA-form intermediate representation for all the -// non-blank source functions in the current package. -type SSA struct { - Pkg *ssa.Package - SrcFuncs []*ssa.Function -} - -func run(pass *analysis.Pass) (interface{}, error) { - // Plundered from ssautil.BuildPackage. - - // We must create a new Program for each Package because the - // analysis API provides no place to hang a Program shared by - // all Packages. Consequently, SSA Packages and Functions do not - // have a canonical representation across an analysis session of - // multiple packages. This is unlikely to be a problem in - // practice because the analysis API essentially forces all - // packages to be analysed independently, so any given call to - // Analysis.Run on a package will see only SSA objects belonging - // to a single Program. - - mode := ssa.GlobalDebug - - prog := ssa.NewProgram(pass.Fset, mode) - - // Create SSA packages for all imports. - // Order is not significant. - created := make(map[*types.Package]bool) - var createAll func(pkgs []*types.Package) - createAll = func(pkgs []*types.Package) { - for _, p := range pkgs { - if !created[p] { - created[p] = true - prog.CreatePackage(p, nil, nil, true) - createAll(p.Imports()) - } - } - } - createAll(pass.Pkg.Imports()) - - // Create and build the primary package. - ssapkg := prog.CreatePackage(pass.Pkg, pass.Files, pass.TypesInfo, false) - ssapkg.Build() - - // Compute list of source functions, including literals, - // in source order. - var funcs []*ssa.Function - var addAnons func(f *ssa.Function) - addAnons = func(f *ssa.Function) { - funcs = append(funcs, f) - for _, anon := range f.AnonFuncs { - addAnons(anon) - } - } - addAnons(ssapkg.Members["init"].(*ssa.Function)) - for _, f := range pass.Files { - for _, decl := range f.Decls { - if fdecl, ok := decl.(*ast.FuncDecl); ok { - - // SSA will not build a Function - // for a FuncDecl named blank. - // That's arguably too strict but - // relaxing it would break uniqueness of - // names of package members. - if fdecl.Name.Name == "_" { - continue - } - - // (init functions have distinct Func - // objects named "init" and distinct - // ssa.Functions named "init#1", ...) - - fn := pass.TypesInfo.Defs[fdecl.Name].(*types.Func) - if fn == nil { - panic(fn) - } - - f := ssapkg.Prog.FuncValue(fn) - if f == nil { - panic(fn) - } - - addAnons(f) - } - } - } - - return &SSA{Pkg: ssapkg, SrcFuncs: funcs}, nil -} diff --git a/vendor/honnef.co/go/tools/internal/renameio/renameio.go b/vendor/honnef.co/go/tools/internal/renameio/renameio.go index 3f3f1708fa4..a279d1a1eba 100644 --- a/vendor/honnef.co/go/tools/internal/renameio/renameio.go +++ b/vendor/honnef.co/go/tools/internal/renameio/renameio.go @@ -8,15 +8,15 @@ package renameio import ( "bytes" "io" - "io/ioutil" + "math/rand" "os" "path/filepath" - "runtime" - "strings" - "time" + "strconv" + + "honnef.co/go/tools/internal/robustio" ) -const patternSuffix = "*.tmp" +const patternSuffix = ".tmp" // Pattern returns a glob pattern that matches the unrenamed temporary files // created when writing to filename. @@ -29,14 +29,14 @@ func Pattern(filename string) string { // final name. // // That ensures that the final location, if it exists, is always a complete file. -func WriteFile(filename string, data []byte) (err error) { - return WriteToFile(filename, bytes.NewReader(data)) +func WriteFile(filename string, data []byte, perm os.FileMode) (err error) { + return WriteToFile(filename, bytes.NewReader(data), perm) } // WriteToFile is a variant of WriteFile that accepts the data as an io.Reader // instead of a slice. -func WriteToFile(filename string, data io.Reader) (err error) { - f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename)+patternSuffix) +func WriteToFile(filename string, data io.Reader, perm os.FileMode) (err error) { + f, err := tempFile(filepath.Dir(filename), filepath.Base(filename), perm) if err != nil { return err } @@ -63,21 +63,31 @@ func WriteToFile(filename string, data io.Reader) (err error) { return err } - var start time.Time - for { - err := os.Rename(f.Name(), filename) - if err == nil || runtime.GOOS != "windows" || !strings.HasSuffix(err.Error(), "Access is denied.") { - return err - } + return robustio.Rename(f.Name(), filename) +} - // Windows seems to occasionally trigger spurious "Access is denied" errors - // here (see golang.org/issue/31247). We're not sure why. It's probably - // worth a little extra latency to avoid propagating the spurious errors. - if start.IsZero() { - start = time.Now() - } else if time.Since(start) >= 500*time.Millisecond { - return err +// tempFile creates a new temporary file with given permission bits. +func tempFile(dir, prefix string, perm os.FileMode) (f *os.File, err error) { + for i := 0; i < 10000; i++ { + name := filepath.Join(dir, prefix+strconv.Itoa(rand.Intn(1000000000))+patternSuffix) + f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, perm) + if os.IsExist(err) { + continue } - time.Sleep(5 * time.Millisecond) + break } + return +} + +// ReadFile is like ioutil.ReadFile, but on Windows retries spurious errors that +// may occur if the file is concurrently replaced. +// +// Errors are classified heuristically and retries are bounded, so even this +// function may occasionally return a spurious error on Windows. +// If so, the error will likely wrap one of: +// - syscall.ERROR_ACCESS_DENIED +// - syscall.ERROR_FILE_NOT_FOUND +// - internal/syscall/windows.ERROR_SHARING_VIOLATION +func ReadFile(filename string) ([]byte, error) { + return robustio.ReadFile(filename) } diff --git a/vendor/honnef.co/go/tools/internal/robustio/robustio.go b/vendor/honnef.co/go/tools/internal/robustio/robustio.go new file mode 100644 index 00000000000..76e47ad1ffa --- /dev/null +++ b/vendor/honnef.co/go/tools/internal/robustio/robustio.go @@ -0,0 +1,53 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package robustio wraps I/O functions that are prone to failure on Windows, +// transparently retrying errors up to an arbitrary timeout. +// +// Errors are classified heuristically and retries are bounded, so the functions +// in this package do not completely eliminate spurious errors. However, they do +// significantly reduce the rate of failure in practice. +// +// If so, the error will likely wrap one of: +// The functions in this package do not completely eliminate spurious errors, +// but substantially reduce their rate of occurrence in practice. +package robustio + +// Rename is like os.Rename, but on Windows retries errors that may occur if the +// file is concurrently read or overwritten. +// +// (See golang.org/issue/31247 and golang.org/issue/32188.) +func Rename(oldpath, newpath string) error { + return rename(oldpath, newpath) +} + +// ReadFile is like ioutil.ReadFile, but on Windows retries errors that may +// occur if the file is concurrently replaced. +// +// (See golang.org/issue/31247 and golang.org/issue/32188.) +func ReadFile(filename string) ([]byte, error) { + return readFile(filename) +} + +// RemoveAll is like os.RemoveAll, but on Windows retries errors that may occur +// if an executable file in the directory has recently been executed. +// +// (See golang.org/issue/19491.) +func RemoveAll(path string) error { + return removeAll(path) +} + +// IsEphemeralError reports whether err is one of the errors that the functions +// in this package attempt to mitigate. +// +// Errors considered ephemeral include: +// - syscall.ERROR_ACCESS_DENIED +// - syscall.ERROR_FILE_NOT_FOUND +// - internal/syscall/windows.ERROR_SHARING_VIOLATION +// +// This set may be expanded in the future; programs must not rely on the +// non-ephemerality of any given error. +func IsEphemeralError(err error) bool { + return isEphemeralError(err) +} diff --git a/vendor/honnef.co/go/tools/internal/robustio/robustio_darwin.go b/vendor/honnef.co/go/tools/internal/robustio/robustio_darwin.go new file mode 100644 index 00000000000..1ac0d10d7f1 --- /dev/null +++ b/vendor/honnef.co/go/tools/internal/robustio/robustio_darwin.go @@ -0,0 +1,29 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package robustio + +import ( + "os" + "syscall" +) + +const errFileNotFound = syscall.ENOENT + +// isEphemeralError returns true if err may be resolved by waiting. +func isEphemeralError(err error) bool { + switch werr := err.(type) { + case *os.PathError: + err = werr.Err + case *os.LinkError: + err = werr.Err + case *os.SyscallError: + err = werr.Err + + } + if errno, ok := err.(syscall.Errno); ok { + return errno == errFileNotFound + } + return false +} diff --git a/vendor/honnef.co/go/tools/internal/robustio/robustio_flaky.go b/vendor/honnef.co/go/tools/internal/robustio/robustio_flaky.go new file mode 100644 index 00000000000..e0bf5b9b3b9 --- /dev/null +++ b/vendor/honnef.co/go/tools/internal/robustio/robustio_flaky.go @@ -0,0 +1,93 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build windows darwin + +package robustio + +import ( + "io/ioutil" + "math/rand" + "os" + "syscall" + "time" +) + +const arbitraryTimeout = 500 * time.Millisecond + +const ERROR_SHARING_VIOLATION = 32 + +// retry retries ephemeral errors from f up to an arbitrary timeout +// to work around filesystem flakiness on Windows and Darwin. +func retry(f func() (err error, mayRetry bool)) error { + var ( + bestErr error + lowestErrno syscall.Errno + start time.Time + nextSleep time.Duration = 1 * time.Millisecond + ) + for { + err, mayRetry := f() + if err == nil || !mayRetry { + return err + } + + if errno, ok := err.(syscall.Errno); ok && (lowestErrno == 0 || errno < lowestErrno) { + bestErr = err + lowestErrno = errno + } else if bestErr == nil { + bestErr = err + } + + if start.IsZero() { + start = time.Now() + } else if d := time.Since(start) + nextSleep; d >= arbitraryTimeout { + break + } + time.Sleep(nextSleep) + nextSleep += time.Duration(rand.Int63n(int64(nextSleep))) + } + + return bestErr +} + +// rename is like os.Rename, but retries ephemeral errors. +// +// On windows it wraps os.Rename, which (as of 2019-06-04) uses MoveFileEx with +// MOVEFILE_REPLACE_EXISTING. +// +// Windows also provides a different system call, ReplaceFile, +// that provides similar semantics, but perhaps preserves more metadata. (The +// documentation on the differences between the two is very sparse.) +// +// Empirical error rates with MoveFileEx are lower under modest concurrency, so +// for now we're sticking with what the os package already provides. +func rename(oldpath, newpath string) (err error) { + return retry(func() (err error, mayRetry bool) { + err = os.Rename(oldpath, newpath) + return err, isEphemeralError(err) + }) +} + +// readFile is like ioutil.ReadFile, but retries ephemeral errors. +func readFile(filename string) ([]byte, error) { + var b []byte + err := retry(func() (err error, mayRetry bool) { + b, err = ioutil.ReadFile(filename) + + // Unlike in rename, we do not retry errFileNotFound here: it can occur + // as a spurious error, but the file may also genuinely not exist, so the + // increase in robustness is probably not worth the extra latency. + + return err, isEphemeralError(err) && err != errFileNotFound + }) + return b, err +} + +func removeAll(path string) error { + return retry(func() (err error, mayRetry bool) { + err = os.RemoveAll(path) + return err, isEphemeralError(err) + }) +} diff --git a/vendor/honnef.co/go/tools/internal/robustio/robustio_other.go b/vendor/honnef.co/go/tools/internal/robustio/robustio_other.go new file mode 100644 index 00000000000..a2428856f2e --- /dev/null +++ b/vendor/honnef.co/go/tools/internal/robustio/robustio_other.go @@ -0,0 +1,28 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//+build !windows,!darwin + +package robustio + +import ( + "io/ioutil" + "os" +) + +func rename(oldpath, newpath string) error { + return os.Rename(oldpath, newpath) +} + +func readFile(filename string) ([]byte, error) { + return ioutil.ReadFile(filename) +} + +func removeAll(path string) error { + return os.RemoveAll(path) +} + +func isEphemeralError(err error) bool { + return false +} diff --git a/vendor/honnef.co/go/tools/internal/robustio/robustio_windows.go b/vendor/honnef.co/go/tools/internal/robustio/robustio_windows.go new file mode 100644 index 00000000000..a35237d44ae --- /dev/null +++ b/vendor/honnef.co/go/tools/internal/robustio/robustio_windows.go @@ -0,0 +1,33 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package robustio + +import ( + "os" + "syscall" +) + +const errFileNotFound = syscall.ERROR_FILE_NOT_FOUND + +// isEphemeralError returns true if err may be resolved by waiting. +func isEphemeralError(err error) bool { + switch werr := err.(type) { + case *os.PathError: + err = werr.Err + case *os.LinkError: + err = werr.Err + case *os.SyscallError: + err = werr.Err + } + if errno, ok := err.(syscall.Errno); ok { + switch errno { + case syscall.ERROR_ACCESS_DENIED, + syscall.ERROR_FILE_NOT_FOUND, + ERROR_SHARING_VIOLATION: + return true + } + } + return false +} diff --git a/vendor/honnef.co/go/tools/internal/sharedcheck/lint.go b/vendor/honnef.co/go/tools/internal/sharedcheck/lint.go index affee660726..e9abf0d893e 100644 --- a/vendor/honnef.co/go/tools/internal/sharedcheck/lint.go +++ b/vendor/honnef.co/go/tools/internal/sharedcheck/lint.go @@ -5,23 +5,24 @@ import ( "go/types" "golang.org/x/tools/go/analysis" - "honnef.co/go/tools/internal/passes/buildssa" + "honnef.co/go/tools/code" + "honnef.co/go/tools/internal/passes/buildir" + "honnef.co/go/tools/ir" . "honnef.co/go/tools/lint/lintdsl" - "honnef.co/go/tools/ssa" ) func CheckRangeStringRunes(pass *analysis.Pass) (interface{}, error) { - for _, ssafn := range pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs { - fn := func(node ast.Node) bool { + for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs { + cb := func(node ast.Node) bool { rng, ok := node.(*ast.RangeStmt) - if !ok || !IsBlank(rng.Key) { + if !ok || !code.IsBlank(rng.Key) { return true } - v, _ := ssafn.ValueForExpr(rng.X) + v, _ := fn.ValueForExpr(rng.X) // Check that we're converting from string to []rune - val, _ := v.(*ssa.Convert) + val, _ := v.(*ir.Convert) if val == nil { return true } @@ -47,13 +48,13 @@ func CheckRangeStringRunes(pass *analysis.Pass) (interface{}, error) { // Expect two refs: one for obtaining the length of the slice, // one for accessing the elements - if len(FilterDebug(*refs)) != 2 { + if len(code.FilterDebug(*refs)) != 2 { // TODO(dh): right now, we check that only one place // refers to our slice. This will miss cases such as // ranging over the slice twice. Ideally, we'd ensure that // the slice is only used for ranging over (without // accessing the key), but that is harder to do because in - // SSA form, ranging over a slice looks like an ordinary + // IR form, ranging over a slice looks like an ordinary // loop with index increments and slice accesses. We'd // have to look at the associated AST node to check that // it's a range statement. @@ -64,7 +65,7 @@ func CheckRangeStringRunes(pass *analysis.Pass) (interface{}, error) { return true } - Inspect(ssafn.Syntax(), fn) + Inspect(fn.Source(), cb) } return nil, nil } diff --git a/vendor/honnef.co/go/tools/ssa/LICENSE b/vendor/honnef.co/go/tools/ir/LICENSE similarity index 100% rename from vendor/honnef.co/go/tools/ssa/LICENSE rename to vendor/honnef.co/go/tools/ir/LICENSE diff --git a/vendor/honnef.co/go/tools/ssa/blockopt.go b/vendor/honnef.co/go/tools/ir/blockopt.go similarity index 83% rename from vendor/honnef.co/go/tools/ssa/blockopt.go rename to vendor/honnef.co/go/tools/ir/blockopt.go index 22c9a4c0d42..d7a0e35676a 100644 --- a/vendor/honnef.co/go/tools/ssa/blockopt.go +++ b/vendor/honnef.co/go/tools/ir/blockopt.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package ssa +package ir // Simple block optimizations to simplify the control flow graph. @@ -21,35 +21,34 @@ const debugBlockOpt = false // markReachable sets Index=-1 for all blocks reachable from b. func markReachable(b *BasicBlock) { - b.Index = -1 + b.gaps = -1 for _, succ := range b.Succs { - if succ.Index == 0 { + if succ.gaps == 0 { markReachable(succ) } } } -func DeleteUnreachableBlocks(f *Function) { - deleteUnreachableBlocks(f) -} - // deleteUnreachableBlocks marks all reachable blocks of f and // eliminates (nils) all others, including possibly cyclic subgraphs. // func deleteUnreachableBlocks(f *Function) { const white, black = 0, -1 - // We borrow b.Index temporarily as the mark bit. + // We borrow b.gaps temporarily as the mark bit. for _, b := range f.Blocks { - b.Index = white + b.gaps = white } markReachable(f.Blocks[0]) - if f.Recover != nil { - markReachable(f.Recover) - } + // In SSI form, we need the exit to be reachable for correct + // post-dominance information. In original form, however, we + // cannot unconditionally mark it reachable because we won't + // be adding fake edges, and this breaks the calculation of + // dominance information. + markReachable(f.Exit) for i, b := range f.Blocks { - if b.Index == white { + if b.gaps == white { for _, c := range b.Succs { - if c.Index == black { + if c.gaps == black { c.removePred(b) // delete white->black edge } } @@ -73,6 +72,13 @@ func jumpThreading(f *Function, b *BasicBlock) bool { if b.Instrs == nil { return false } + for _, pred := range b.Preds { + switch pred.Control().(type) { + case *ConstantSwitch: + // don't optimize away the head blocks of switch statements + return false + } + } if _, ok := b.Instrs[0].(*Jump); !ok { return false // not just a jump } @@ -117,10 +123,17 @@ func fuseBlocks(f *Function, a *BasicBlock) bool { if len(a.Succs) != 1 { return false } + if a.Succs[0] == f.Exit { + return false + } b := a.Succs[0] if len(b.Preds) != 1 { return false } + if _, ok := a.Instrs[len(a.Instrs)-1].(*Panic); ok { + // panics aren't simple jumps, they have side effects. + return false + } // Degenerate &&/|| ops may result in a straight-line CFG // containing φ-nodes. (Ideally we'd replace such them with @@ -151,15 +164,16 @@ func fuseBlocks(f *Function, a *BasicBlock) bool { return true } -func OptimizeBlocks(f *Function) { - optimizeBlocks(f) -} - // optimizeBlocks() performs some simple block optimizations on a // completed function: dead block elimination, block fusion, jump // threading. // func optimizeBlocks(f *Function) { + if debugBlockOpt { + f.WriteTo(os.Stderr) + mustSanityCheck(f, nil) + } + deleteUnreachableBlocks(f) // Loop until no further progress. diff --git a/vendor/honnef.co/go/tools/ir/builder.go b/vendor/honnef.co/go/tools/ir/builder.go new file mode 100644 index 00000000000..fdf4cb1a91a --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/builder.go @@ -0,0 +1,2474 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// This file implements the BUILD phase of IR construction. +// +// IR construction has two phases, CREATE and BUILD. In the CREATE phase +// (create.go), all packages are constructed and type-checked and +// definitions of all package members are created, method-sets are +// computed, and wrapper methods are synthesized. +// ir.Packages are created in arbitrary order. +// +// In the BUILD phase (builder.go), the builder traverses the AST of +// each Go source function and generates IR instructions for the +// function body. Initializer expressions for package-level variables +// are emitted to the package's init() function in the order specified +// by go/types.Info.InitOrder, then code for each function in the +// package is generated in lexical order. +// +// The builder's and Program's indices (maps) are populated and +// mutated during the CREATE phase, but during the BUILD phase they +// remain constant. The sole exception is Prog.methodSets and its +// related maps, which are protected by a dedicated mutex. + +import ( + "fmt" + "go/ast" + "go/constant" + "go/token" + "go/types" + "os" +) + +type opaqueType struct { + types.Type + name string +} + +func (t *opaqueType) String() string { return t.name } + +var ( + varOk = newVar("ok", tBool) + varIndex = newVar("index", tInt) + + // Type constants. + tBool = types.Typ[types.Bool] + tByte = types.Typ[types.Byte] + tInt = types.Typ[types.Int] + tInvalid = types.Typ[types.Invalid] + tString = types.Typ[types.String] + tUntypedNil = types.Typ[types.UntypedNil] + tRangeIter = &opaqueType{nil, "iter"} // the type of all "range" iterators + tEface = types.NewInterfaceType(nil, nil).Complete() +) + +// builder holds state associated with the package currently being built. +// Its methods contain all the logic for AST-to-IR conversion. +type builder struct { + printFunc string + + blocksets [5]BlockSet +} + +// cond emits to fn code to evaluate boolean condition e and jump +// to t or f depending on its value, performing various simplifications. +// +// Postcondition: fn.currentBlock is nil. +// +func (b *builder) cond(fn *Function, e ast.Expr, t, f *BasicBlock) *If { + switch e := e.(type) { + case *ast.ParenExpr: + return b.cond(fn, e.X, t, f) + + case *ast.BinaryExpr: + switch e.Op { + case token.LAND: + ltrue := fn.newBasicBlock("cond.true") + b.cond(fn, e.X, ltrue, f) + fn.currentBlock = ltrue + return b.cond(fn, e.Y, t, f) + + case token.LOR: + lfalse := fn.newBasicBlock("cond.false") + b.cond(fn, e.X, t, lfalse) + fn.currentBlock = lfalse + return b.cond(fn, e.Y, t, f) + } + + case *ast.UnaryExpr: + if e.Op == token.NOT { + return b.cond(fn, e.X, f, t) + } + } + + // A traditional compiler would simplify "if false" (etc) here + // but we do not, for better fidelity to the source code. + // + // The value of a constant condition may be platform-specific, + // and may cause blocks that are reachable in some configuration + // to be hidden from subsequent analyses such as bug-finding tools. + return emitIf(fn, b.expr(fn, e), t, f, e) +} + +// logicalBinop emits code to fn to evaluate e, a &&- or +// ||-expression whose reified boolean value is wanted. +// The value is returned. +// +func (b *builder) logicalBinop(fn *Function, e *ast.BinaryExpr) Value { + rhs := fn.newBasicBlock("binop.rhs") + done := fn.newBasicBlock("binop.done") + + // T(e) = T(e.X) = T(e.Y) after untyped constants have been + // eliminated. + // TODO(adonovan): not true; MyBool==MyBool yields UntypedBool. + t := fn.Pkg.typeOf(e) + + var short Value // value of the short-circuit path + switch e.Op { + case token.LAND: + b.cond(fn, e.X, rhs, done) + short = emitConst(fn, NewConst(constant.MakeBool(false), t)) + + case token.LOR: + b.cond(fn, e.X, done, rhs) + short = emitConst(fn, NewConst(constant.MakeBool(true), t)) + } + + // Is rhs unreachable? + if rhs.Preds == nil { + // Simplify false&&y to false, true||y to true. + fn.currentBlock = done + return short + } + + // Is done unreachable? + if done.Preds == nil { + // Simplify true&&y (or false||y) to y. + fn.currentBlock = rhs + return b.expr(fn, e.Y) + } + + // All edges from e.X to done carry the short-circuit value. + var edges []Value + for range done.Preds { + edges = append(edges, short) + } + + // The edge from e.Y to done carries the value of e.Y. + fn.currentBlock = rhs + edges = append(edges, b.expr(fn, e.Y)) + emitJump(fn, done, e) + fn.currentBlock = done + + phi := &Phi{Edges: edges} + phi.typ = t + return done.emit(phi, e) +} + +// exprN lowers a multi-result expression e to IR form, emitting code +// to fn and returning a single Value whose type is a *types.Tuple. +// The caller must access the components via Extract. +// +// Multi-result expressions include CallExprs in a multi-value +// assignment or return statement, and "value,ok" uses of +// TypeAssertExpr, IndexExpr (when X is a map), and Recv. +// +func (b *builder) exprN(fn *Function, e ast.Expr) Value { + typ := fn.Pkg.typeOf(e).(*types.Tuple) + switch e := e.(type) { + case *ast.ParenExpr: + return b.exprN(fn, e.X) + + case *ast.CallExpr: + // Currently, no built-in function nor type conversion + // has multiple results, so we can avoid some of the + // cases for single-valued CallExpr. + var c Call + b.setCall(fn, e, &c.Call) + c.typ = typ + return fn.emit(&c, e) + + case *ast.IndexExpr: + mapt := fn.Pkg.typeOf(e.X).Underlying().(*types.Map) + lookup := &MapLookup{ + X: b.expr(fn, e.X), + Index: emitConv(fn, b.expr(fn, e.Index), mapt.Key(), e), + CommaOk: true, + } + lookup.setType(typ) + return fn.emit(lookup, e) + + case *ast.TypeAssertExpr: + return emitTypeTest(fn, b.expr(fn, e.X), typ.At(0).Type(), e) + + case *ast.UnaryExpr: // must be receive <- + return emitRecv(fn, b.expr(fn, e.X), true, typ, e) + } + panic(fmt.Sprintf("exprN(%T) in %s", e, fn)) +} + +// builtin emits to fn IR instructions to implement a call to the +// built-in function obj with the specified arguments +// and return type. It returns the value defined by the result. +// +// The result is nil if no special handling was required; in this case +// the caller should treat this like an ordinary library function +// call. +// +func (b *builder) builtin(fn *Function, obj *types.Builtin, args []ast.Expr, typ types.Type, source ast.Node) Value { + switch obj.Name() { + case "make": + switch typ.Underlying().(type) { + case *types.Slice: + n := b.expr(fn, args[1]) + m := n + if len(args) == 3 { + m = b.expr(fn, args[2]) + } + if m, ok := m.(*Const); ok { + // treat make([]T, n, m) as new([m]T)[:n] + cap := m.Int64() + at := types.NewArray(typ.Underlying().(*types.Slice).Elem(), cap) + alloc := emitNew(fn, at, source) + v := &Slice{ + X: alloc, + High: n, + } + v.setType(typ) + return fn.emit(v, source) + } + v := &MakeSlice{ + Len: n, + Cap: m, + } + v.setType(typ) + return fn.emit(v, source) + + case *types.Map: + var res Value + if len(args) == 2 { + res = b.expr(fn, args[1]) + } + v := &MakeMap{Reserve: res} + v.setType(typ) + return fn.emit(v, source) + + case *types.Chan: + var sz Value = emitConst(fn, intConst(0)) + if len(args) == 2 { + sz = b.expr(fn, args[1]) + } + v := &MakeChan{Size: sz} + v.setType(typ) + return fn.emit(v, source) + } + + case "new": + alloc := emitNew(fn, deref(typ), source) + return alloc + + case "len", "cap": + // Special case: len or cap of an array or *array is + // based on the type, not the value which may be nil. + // We must still evaluate the value, though. (If it + // was side-effect free, the whole call would have + // been constant-folded.) + t := deref(fn.Pkg.typeOf(args[0])).Underlying() + if at, ok := t.(*types.Array); ok { + b.expr(fn, args[0]) // for effects only + return emitConst(fn, intConst(at.Len())) + } + // Otherwise treat as normal. + + case "panic": + fn.emit(&Panic{ + X: emitConv(fn, b.expr(fn, args[0]), tEface, source), + }, source) + addEdge(fn.currentBlock, fn.Exit) + fn.currentBlock = fn.newBasicBlock("unreachable") + return emitConst(fn, NewConst(constant.MakeBool(true), tBool)) // any non-nil Value will do + } + return nil // treat all others as a regular function call +} + +// addr lowers a single-result addressable expression e to IR form, +// emitting code to fn and returning the location (an lvalue) defined +// by the expression. +// +// If escaping is true, addr marks the base variable of the +// addressable expression e as being a potentially escaping pointer +// value. For example, in this code: +// +// a := A{ +// b: [1]B{B{c: 1}} +// } +// return &a.b[0].c +// +// the application of & causes a.b[0].c to have its address taken, +// which means that ultimately the local variable a must be +// heap-allocated. This is a simple but very conservative escape +// analysis. +// +// Operations forming potentially escaping pointers include: +// - &x, including when implicit in method call or composite literals. +// - a[:] iff a is an array (not *array) +// - references to variables in lexically enclosing functions. +// +func (b *builder) addr(fn *Function, e ast.Expr, escaping bool) lvalue { + switch e := e.(type) { + case *ast.Ident: + if isBlankIdent(e) { + return blank{} + } + obj := fn.Pkg.objectOf(e) + v := fn.Prog.packageLevelValue(obj) // var (address) + if v == nil { + v = fn.lookup(obj, escaping) + } + return &address{addr: v, expr: e} + + case *ast.CompositeLit: + t := deref(fn.Pkg.typeOf(e)) + var v *Alloc + if escaping { + v = emitNew(fn, t, e) + } else { + v = fn.addLocal(t, e) + } + var sb storebuf + b.compLit(fn, v, e, true, &sb) + sb.emit(fn) + return &address{addr: v, expr: e} + + case *ast.ParenExpr: + return b.addr(fn, e.X, escaping) + + case *ast.SelectorExpr: + sel, ok := fn.Pkg.info.Selections[e] + if !ok { + // qualified identifier + return b.addr(fn, e.Sel, escaping) + } + if sel.Kind() != types.FieldVal { + panic(sel) + } + wantAddr := true + v := b.receiver(fn, e.X, wantAddr, escaping, sel, e) + last := len(sel.Index()) - 1 + return &address{ + addr: emitFieldSelection(fn, v, sel.Index()[last], true, e.Sel), + expr: e.Sel, + } + + case *ast.IndexExpr: + var x Value + var et types.Type + switch t := fn.Pkg.typeOf(e.X).Underlying().(type) { + case *types.Array: + x = b.addr(fn, e.X, escaping).address(fn) + et = types.NewPointer(t.Elem()) + case *types.Pointer: // *array + x = b.expr(fn, e.X) + et = types.NewPointer(t.Elem().Underlying().(*types.Array).Elem()) + case *types.Slice: + x = b.expr(fn, e.X) + et = types.NewPointer(t.Elem()) + case *types.Map: + return &element{ + m: b.expr(fn, e.X), + k: emitConv(fn, b.expr(fn, e.Index), t.Key(), e.Index), + t: t.Elem(), + } + default: + panic("unexpected container type in IndexExpr: " + t.String()) + } + v := &IndexAddr{ + X: x, + Index: emitConv(fn, b.expr(fn, e.Index), tInt, e.Index), + } + v.setType(et) + return &address{addr: fn.emit(v, e), expr: e} + + case *ast.StarExpr: + return &address{addr: b.expr(fn, e.X), expr: e} + } + + panic(fmt.Sprintf("unexpected address expression: %T", e)) +} + +type store struct { + lhs lvalue + rhs Value + source ast.Node +} + +type storebuf struct{ stores []store } + +func (sb *storebuf) store(lhs lvalue, rhs Value, source ast.Node) { + sb.stores = append(sb.stores, store{lhs, rhs, source}) +} + +func (sb *storebuf) emit(fn *Function) { + for _, s := range sb.stores { + s.lhs.store(fn, s.rhs, s.source) + } +} + +// assign emits to fn code to initialize the lvalue loc with the value +// of expression e. If isZero is true, assign assumes that loc holds +// the zero value for its type. +// +// This is equivalent to loc.store(fn, b.expr(fn, e)), but may generate +// better code in some cases, e.g., for composite literals in an +// addressable location. +// +// If sb is not nil, assign generates code to evaluate expression e, but +// not to update loc. Instead, the necessary stores are appended to the +// storebuf sb so that they can be executed later. This allows correct +// in-place update of existing variables when the RHS is a composite +// literal that may reference parts of the LHS. +// +func (b *builder) assign(fn *Function, loc lvalue, e ast.Expr, isZero bool, sb *storebuf, source ast.Node) { + // Can we initialize it in place? + if e, ok := unparen(e).(*ast.CompositeLit); ok { + // A CompositeLit never evaluates to a pointer, + // so if the type of the location is a pointer, + // an &-operation is implied. + if _, ok := loc.(blank); !ok { // avoid calling blank.typ() + if isPointer(loc.typ()) { + ptr := b.addr(fn, e, true).address(fn) + // copy address + if sb != nil { + sb.store(loc, ptr, source) + } else { + loc.store(fn, ptr, source) + } + return + } + } + + if _, ok := loc.(*address); ok { + if isInterface(loc.typ()) { + // e.g. var x interface{} = T{...} + // Can't in-place initialize an interface value. + // Fall back to copying. + } else { + // x = T{...} or x := T{...} + addr := loc.address(fn) + if sb != nil { + b.compLit(fn, addr, e, isZero, sb) + } else { + var sb storebuf + b.compLit(fn, addr, e, isZero, &sb) + sb.emit(fn) + } + + // Subtle: emit debug ref for aggregate types only; + // slice and map are handled by store ops in compLit. + switch loc.typ().Underlying().(type) { + case *types.Struct, *types.Array: + emitDebugRef(fn, e, addr, true) + } + + return + } + } + } + + // simple case: just copy + rhs := b.expr(fn, e) + if sb != nil { + sb.store(loc, rhs, source) + } else { + loc.store(fn, rhs, source) + } +} + +// expr lowers a single-result expression e to IR form, emitting code +// to fn and returning the Value defined by the expression. +// +func (b *builder) expr(fn *Function, e ast.Expr) Value { + e = unparen(e) + + tv := fn.Pkg.info.Types[e] + + // Is expression a constant? + if tv.Value != nil { + return emitConst(fn, NewConst(tv.Value, tv.Type)) + } + + var v Value + if tv.Addressable() { + // Prefer pointer arithmetic ({Index,Field}Addr) followed + // by Load over subelement extraction (e.g. Index, Field), + // to avoid large copies. + v = b.addr(fn, e, false).load(fn, e) + } else { + v = b.expr0(fn, e, tv) + } + if fn.debugInfo() { + emitDebugRef(fn, e, v, false) + } + return v +} + +func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value { + switch e := e.(type) { + case *ast.BasicLit: + panic("non-constant BasicLit") // unreachable + + case *ast.FuncLit: + fn2 := &Function{ + name: fmt.Sprintf("%s$%d", fn.Name(), 1+len(fn.AnonFuncs)), + Signature: fn.Pkg.typeOf(e.Type).Underlying().(*types.Signature), + parent: fn, + Pkg: fn.Pkg, + Prog: fn.Prog, + functionBody: new(functionBody), + } + fn2.source = e + fn.AnonFuncs = append(fn.AnonFuncs, fn2) + fn2.initHTML(b.printFunc) + b.buildFunction(fn2) + if fn2.FreeVars == nil { + return fn2 + } + v := &MakeClosure{Fn: fn2} + v.setType(tv.Type) + for _, fv := range fn2.FreeVars { + v.Bindings = append(v.Bindings, fv.outer) + fv.outer = nil + } + return fn.emit(v, e) + + case *ast.TypeAssertExpr: // single-result form only + return emitTypeAssert(fn, b.expr(fn, e.X), tv.Type, e) + + case *ast.CallExpr: + if fn.Pkg.info.Types[e.Fun].IsType() { + // Explicit type conversion, e.g. string(x) or big.Int(x) + x := b.expr(fn, e.Args[0]) + y := emitConv(fn, x, tv.Type, e) + return y + } + // Call to "intrinsic" built-ins, e.g. new, make, panic. + if id, ok := unparen(e.Fun).(*ast.Ident); ok { + if obj, ok := fn.Pkg.info.Uses[id].(*types.Builtin); ok { + if v := b.builtin(fn, obj, e.Args, tv.Type, e); v != nil { + return v + } + } + } + // Regular function call. + var v Call + b.setCall(fn, e, &v.Call) + v.setType(tv.Type) + return fn.emit(&v, e) + + case *ast.UnaryExpr: + switch e.Op { + case token.AND: // &X --- potentially escaping. + addr := b.addr(fn, e.X, true) + if _, ok := unparen(e.X).(*ast.StarExpr); ok { + // &*p must panic if p is nil (http://golang.org/s/go12nil). + // For simplicity, we'll just (suboptimally) rely + // on the side effects of a load. + // TODO(adonovan): emit dedicated nilcheck. + addr.load(fn, e) + } + return addr.address(fn) + case token.ADD: + return b.expr(fn, e.X) + case token.NOT, token.SUB, token.XOR: // ! <- - ^ + v := &UnOp{ + Op: e.Op, + X: b.expr(fn, e.X), + } + v.setType(tv.Type) + return fn.emit(v, e) + case token.ARROW: + return emitRecv(fn, b.expr(fn, e.X), false, tv.Type, e) + default: + panic(e.Op) + } + + case *ast.BinaryExpr: + switch e.Op { + case token.LAND, token.LOR: + return b.logicalBinop(fn, e) + case token.SHL, token.SHR: + fallthrough + case token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.AND, token.OR, token.XOR, token.AND_NOT: + return emitArith(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), tv.Type, e) + + case token.EQL, token.NEQ, token.GTR, token.LSS, token.LEQ, token.GEQ: + cmp := emitCompare(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), e) + // The type of x==y may be UntypedBool. + return emitConv(fn, cmp, types.Default(tv.Type), e) + default: + panic("illegal op in BinaryExpr: " + e.Op.String()) + } + + case *ast.SliceExpr: + var low, high, max Value + var x Value + switch fn.Pkg.typeOf(e.X).Underlying().(type) { + case *types.Array: + // Potentially escaping. + x = b.addr(fn, e.X, true).address(fn) + case *types.Basic, *types.Slice, *types.Pointer: // *array + x = b.expr(fn, e.X) + default: + panic("unreachable") + } + if e.High != nil { + high = b.expr(fn, e.High) + } + if e.Low != nil { + low = b.expr(fn, e.Low) + } + if e.Slice3 { + max = b.expr(fn, e.Max) + } + v := &Slice{ + X: x, + Low: low, + High: high, + Max: max, + } + v.setType(tv.Type) + return fn.emit(v, e) + + case *ast.Ident: + obj := fn.Pkg.info.Uses[e] + // Universal built-in or nil? + switch obj := obj.(type) { + case *types.Builtin: + return &Builtin{name: obj.Name(), sig: tv.Type.(*types.Signature)} + case *types.Nil: + return emitConst(fn, nilConst(tv.Type)) + } + // Package-level func or var? + if v := fn.Prog.packageLevelValue(obj); v != nil { + if _, ok := obj.(*types.Var); ok { + return emitLoad(fn, v, e) // var (address) + } + return v // (func) + } + // Local var. + return emitLoad(fn, fn.lookup(obj, false), e) // var (address) + + case *ast.SelectorExpr: + sel, ok := fn.Pkg.info.Selections[e] + if !ok { + // qualified identifier + return b.expr(fn, e.Sel) + } + switch sel.Kind() { + case types.MethodExpr: + // (*T).f or T.f, the method f from the method-set of type T. + // The result is a "thunk". + return emitConv(fn, makeThunk(fn.Prog, sel), tv.Type, e) + + case types.MethodVal: + // e.f where e is an expression and f is a method. + // The result is a "bound". + obj := sel.Obj().(*types.Func) + rt := recvType(obj) + wantAddr := isPointer(rt) + escaping := true + v := b.receiver(fn, e.X, wantAddr, escaping, sel, e) + if isInterface(rt) { + // If v has interface type I, + // we must emit a check that v is non-nil. + // We use: typeassert v.(I). + emitTypeAssert(fn, v, rt, e) + } + c := &MakeClosure{ + Fn: makeBound(fn.Prog, obj), + Bindings: []Value{v}, + } + c.source = e.Sel + c.setType(tv.Type) + return fn.emit(c, e) + + case types.FieldVal: + indices := sel.Index() + last := len(indices) - 1 + v := b.expr(fn, e.X) + v = emitImplicitSelections(fn, v, indices[:last], e) + v = emitFieldSelection(fn, v, indices[last], false, e.Sel) + return v + } + + panic("unexpected expression-relative selector") + + case *ast.IndexExpr: + switch t := fn.Pkg.typeOf(e.X).Underlying().(type) { + case *types.Array: + // Non-addressable array (in a register). + v := &Index{ + X: b.expr(fn, e.X), + Index: emitConv(fn, b.expr(fn, e.Index), tInt, e.Index), + } + v.setType(t.Elem()) + return fn.emit(v, e) + + case *types.Map: + // Maps are not addressable. + mapt := fn.Pkg.typeOf(e.X).Underlying().(*types.Map) + v := &MapLookup{ + X: b.expr(fn, e.X), + Index: emitConv(fn, b.expr(fn, e.Index), mapt.Key(), e.Index), + } + v.setType(mapt.Elem()) + return fn.emit(v, e) + + case *types.Basic: // => string + // Strings are not addressable. + v := &StringLookup{ + X: b.expr(fn, e.X), + Index: b.expr(fn, e.Index), + } + v.setType(tByte) + return fn.emit(v, e) + + case *types.Slice, *types.Pointer: // *array + // Addressable slice/array; use IndexAddr and Load. + return b.addr(fn, e, false).load(fn, e) + + default: + panic("unexpected container type in IndexExpr: " + t.String()) + } + + case *ast.CompositeLit, *ast.StarExpr: + // Addressable types (lvalues) + return b.addr(fn, e, false).load(fn, e) + } + + panic(fmt.Sprintf("unexpected expr: %T", e)) +} + +// stmtList emits to fn code for all statements in list. +func (b *builder) stmtList(fn *Function, list []ast.Stmt) { + for _, s := range list { + b.stmt(fn, s) + } +} + +// receiver emits to fn code for expression e in the "receiver" +// position of selection e.f (where f may be a field or a method) and +// returns the effective receiver after applying the implicit field +// selections of sel. +// +// wantAddr requests that the result is an an address. If +// !sel.Indirect(), this may require that e be built in addr() mode; it +// must thus be addressable. +// +// escaping is defined as per builder.addr(). +// +func (b *builder) receiver(fn *Function, e ast.Expr, wantAddr, escaping bool, sel *types.Selection, source ast.Node) Value { + var v Value + if wantAddr && !sel.Indirect() && !isPointer(fn.Pkg.typeOf(e)) { + v = b.addr(fn, e, escaping).address(fn) + } else { + v = b.expr(fn, e) + } + + last := len(sel.Index()) - 1 + v = emitImplicitSelections(fn, v, sel.Index()[:last], source) + if !wantAddr && isPointer(v.Type()) { + v = emitLoad(fn, v, e) + } + return v +} + +// setCallFunc populates the function parts of a CallCommon structure +// (Func, Method, Recv, Args[0]) based on the kind of invocation +// occurring in e. +// +func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) { + // Is this a method call? + if selector, ok := unparen(e.Fun).(*ast.SelectorExpr); ok { + sel, ok := fn.Pkg.info.Selections[selector] + if ok && sel.Kind() == types.MethodVal { + obj := sel.Obj().(*types.Func) + recv := recvType(obj) + wantAddr := isPointer(recv) + escaping := true + v := b.receiver(fn, selector.X, wantAddr, escaping, sel, selector) + if isInterface(recv) { + // Invoke-mode call. + c.Value = v + c.Method = obj + } else { + // "Call"-mode call. + c.Value = fn.Prog.declaredFunc(obj) + c.Args = append(c.Args, v) + } + return + } + + // sel.Kind()==MethodExpr indicates T.f() or (*T).f(): + // a statically dispatched call to the method f in the + // method-set of T or *T. T may be an interface. + // + // e.Fun would evaluate to a concrete method, interface + // wrapper function, or promotion wrapper. + // + // For now, we evaluate it in the usual way. + // + // TODO(adonovan): opt: inline expr() here, to make the + // call static and to avoid generation of wrappers. + // It's somewhat tricky as it may consume the first + // actual parameter if the call is "invoke" mode. + // + // Examples: + // type T struct{}; func (T) f() {} // "call" mode + // type T interface { f() } // "invoke" mode + // + // type S struct{ T } + // + // var s S + // S.f(s) + // (*S).f(&s) + // + // Suggested approach: + // - consume the first actual parameter expression + // and build it with b.expr(). + // - apply implicit field selections. + // - use MethodVal logic to populate fields of c. + } + + // Evaluate the function operand in the usual way. + c.Value = b.expr(fn, e.Fun) +} + +// emitCallArgs emits to f code for the actual parameters of call e to +// a (possibly built-in) function of effective type sig. +// The argument values are appended to args, which is then returned. +// +func (b *builder) emitCallArgs(fn *Function, sig *types.Signature, e *ast.CallExpr, args []Value) []Value { + // f(x, y, z...): pass slice z straight through. + if e.Ellipsis != 0 { + for i, arg := range e.Args { + v := emitConv(fn, b.expr(fn, arg), sig.Params().At(i).Type(), arg) + args = append(args, v) + } + return args + } + + offset := len(args) // 1 if call has receiver, 0 otherwise + + // Evaluate actual parameter expressions. + // + // If this is a chained call of the form f(g()) where g has + // multiple return values (MRV), they are flattened out into + // args; a suffix of them may end up in a varargs slice. + for _, arg := range e.Args { + v := b.expr(fn, arg) + if ttuple, ok := v.Type().(*types.Tuple); ok { // MRV chain + for i, n := 0, ttuple.Len(); i < n; i++ { + args = append(args, emitExtract(fn, v, i, arg)) + } + } else { + args = append(args, v) + } + } + + // Actual->formal assignability conversions for normal parameters. + np := sig.Params().Len() // number of normal parameters + if sig.Variadic() { + np-- + } + for i := 0; i < np; i++ { + args[offset+i] = emitConv(fn, args[offset+i], sig.Params().At(i).Type(), args[offset+i].Source()) + } + + // Actual->formal assignability conversions for variadic parameter, + // and construction of slice. + if sig.Variadic() { + varargs := args[offset+np:] + st := sig.Params().At(np).Type().(*types.Slice) + vt := st.Elem() + if len(varargs) == 0 { + args = append(args, emitConst(fn, nilConst(st))) + } else { + // Replace a suffix of args with a slice containing it. + at := types.NewArray(vt, int64(len(varargs))) + a := emitNew(fn, at, e) + a.source = e + for i, arg := range varargs { + iaddr := &IndexAddr{ + X: a, + Index: emitConst(fn, intConst(int64(i))), + } + iaddr.setType(types.NewPointer(vt)) + fn.emit(iaddr, e) + emitStore(fn, iaddr, arg, arg.Source()) + } + s := &Slice{X: a} + s.setType(st) + args[offset+np] = fn.emit(s, args[offset+np].Source()) + args = args[:offset+np+1] + } + } + return args +} + +// setCall emits to fn code to evaluate all the parameters of a function +// call e, and populates *c with those values. +// +func (b *builder) setCall(fn *Function, e *ast.CallExpr, c *CallCommon) { + // First deal with the f(...) part and optional receiver. + b.setCallFunc(fn, e, c) + + // Then append the other actual parameters. + sig, _ := fn.Pkg.typeOf(e.Fun).Underlying().(*types.Signature) + if sig == nil { + panic(fmt.Sprintf("no signature for call of %s", e.Fun)) + } + c.Args = b.emitCallArgs(fn, sig, e, c.Args) +} + +// assignOp emits to fn code to perform loc = val. +func (b *builder) assignOp(fn *Function, loc lvalue, val Value, op token.Token, source ast.Node) { + oldv := loc.load(fn, source) + loc.store(fn, emitArith(fn, op, oldv, emitConv(fn, val, oldv.Type(), source), loc.typ(), source), source) +} + +// localValueSpec emits to fn code to define all of the vars in the +// function-local ValueSpec, spec. +// +func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) { + switch { + case len(spec.Values) == len(spec.Names): + // e.g. var x, y = 0, 1 + // 1:1 assignment + for i, id := range spec.Names { + if !isBlankIdent(id) { + fn.addLocalForIdent(id) + } + lval := b.addr(fn, id, false) // non-escaping + b.assign(fn, lval, spec.Values[i], true, nil, spec) + } + + case len(spec.Values) == 0: + // e.g. var x, y int + // Locals are implicitly zero-initialized. + for _, id := range spec.Names { + if !isBlankIdent(id) { + lhs := fn.addLocalForIdent(id) + if fn.debugInfo() { + emitDebugRef(fn, id, lhs, true) + } + } + } + + default: + // e.g. var x, y = pos() + tuple := b.exprN(fn, spec.Values[0]) + for i, id := range spec.Names { + if !isBlankIdent(id) { + fn.addLocalForIdent(id) + lhs := b.addr(fn, id, false) // non-escaping + lhs.store(fn, emitExtract(fn, tuple, i, id), id) + } + } + } +} + +// assignStmt emits code to fn for a parallel assignment of rhss to lhss. +// isDef is true if this is a short variable declaration (:=). +// +// Note the similarity with localValueSpec. +// +func (b *builder) assignStmt(fn *Function, lhss, rhss []ast.Expr, isDef bool, source ast.Node) { + // Side effects of all LHSs and RHSs must occur in left-to-right order. + lvals := make([]lvalue, len(lhss)) + isZero := make([]bool, len(lhss)) + for i, lhs := range lhss { + var lval lvalue = blank{} + if !isBlankIdent(lhs) { + if isDef { + if obj := fn.Pkg.info.Defs[lhs.(*ast.Ident)]; obj != nil { + fn.addNamedLocal(obj, lhs) + isZero[i] = true + } + } + lval = b.addr(fn, lhs, false) // non-escaping + } + lvals[i] = lval + } + if len(lhss) == len(rhss) { + // Simple assignment: x = f() (!isDef) + // Parallel assignment: x, y = f(), g() (!isDef) + // or short var decl: x, y := f(), g() (isDef) + // + // In all cases, the RHSs may refer to the LHSs, + // so we need a storebuf. + var sb storebuf + for i := range rhss { + b.assign(fn, lvals[i], rhss[i], isZero[i], &sb, source) + } + sb.emit(fn) + } else { + // e.g. x, y = pos() + tuple := b.exprN(fn, rhss[0]) + emitDebugRef(fn, rhss[0], tuple, false) + for i, lval := range lvals { + lval.store(fn, emitExtract(fn, tuple, i, source), source) + } + } +} + +// arrayLen returns the length of the array whose composite literal elements are elts. +func (b *builder) arrayLen(fn *Function, elts []ast.Expr) int64 { + var max int64 = -1 + var i int64 = -1 + for _, e := range elts { + if kv, ok := e.(*ast.KeyValueExpr); ok { + i = b.expr(fn, kv.Key).(*Const).Int64() + } else { + i++ + } + if i > max { + max = i + } + } + return max + 1 +} + +// compLit emits to fn code to initialize a composite literal e at +// address addr with type typ. +// +// Nested composite literals are recursively initialized in place +// where possible. If isZero is true, compLit assumes that addr +// holds the zero value for typ. +// +// Because the elements of a composite literal may refer to the +// variables being updated, as in the second line below, +// x := T{a: 1} +// x = T{a: x.a} +// all the reads must occur before all the writes. Thus all stores to +// loc are emitted to the storebuf sb for later execution. +// +// A CompositeLit may have pointer type only in the recursive (nested) +// case when the type name is implicit. e.g. in []*T{{}}, the inner +// literal has type *T behaves like &T{}. +// In that case, addr must hold a T, not a *T. +// +func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero bool, sb *storebuf) { + typ := deref(fn.Pkg.typeOf(e)) + switch t := typ.Underlying().(type) { + case *types.Struct: + if !isZero && len(e.Elts) != t.NumFields() { + // memclear + sb.store(&address{addr, nil}, zeroValue(fn, deref(addr.Type()), e), e) + isZero = true + } + for i, e := range e.Elts { + fieldIndex := i + if kv, ok := e.(*ast.KeyValueExpr); ok { + fname := kv.Key.(*ast.Ident).Name + for i, n := 0, t.NumFields(); i < n; i++ { + sf := t.Field(i) + if sf.Name() == fname { + fieldIndex = i + e = kv.Value + break + } + } + } + sf := t.Field(fieldIndex) + faddr := &FieldAddr{ + X: addr, + Field: fieldIndex, + } + faddr.setType(types.NewPointer(sf.Type())) + fn.emit(faddr, e) + b.assign(fn, &address{addr: faddr, expr: e}, e, isZero, sb, e) + } + + case *types.Array, *types.Slice: + var at *types.Array + var array Value + switch t := t.(type) { + case *types.Slice: + at = types.NewArray(t.Elem(), b.arrayLen(fn, e.Elts)) + alloc := emitNew(fn, at, e) + array = alloc + case *types.Array: + at = t + array = addr + + if !isZero && int64(len(e.Elts)) != at.Len() { + // memclear + sb.store(&address{array, nil}, zeroValue(fn, deref(array.Type()), e), e) + } + } + + var idx *Const + for _, e := range e.Elts { + if kv, ok := e.(*ast.KeyValueExpr); ok { + idx = b.expr(fn, kv.Key).(*Const) + e = kv.Value + } else { + var idxval int64 + if idx != nil { + idxval = idx.Int64() + 1 + } + idx = emitConst(fn, intConst(idxval)) + } + iaddr := &IndexAddr{ + X: array, + Index: idx, + } + iaddr.setType(types.NewPointer(at.Elem())) + fn.emit(iaddr, e) + if t != at { // slice + // backing array is unaliased => storebuf not needed. + b.assign(fn, &address{addr: iaddr, expr: e}, e, true, nil, e) + } else { + b.assign(fn, &address{addr: iaddr, expr: e}, e, true, sb, e) + } + } + + if t != at { // slice + s := &Slice{X: array} + s.setType(typ) + sb.store(&address{addr: addr, expr: e}, fn.emit(s, e), e) + } + + case *types.Map: + m := &MakeMap{Reserve: emitConst(fn, intConst(int64(len(e.Elts))))} + m.setType(typ) + fn.emit(m, e) + for _, e := range e.Elts { + e := e.(*ast.KeyValueExpr) + + // If a key expression in a map literal is itself a + // composite literal, the type may be omitted. + // For example: + // map[*struct{}]bool{{}: true} + // An &-operation may be implied: + // map[*struct{}]bool{&struct{}{}: true} + var key Value + if _, ok := unparen(e.Key).(*ast.CompositeLit); ok && isPointer(t.Key()) { + // A CompositeLit never evaluates to a pointer, + // so if the type of the location is a pointer, + // an &-operation is implied. + key = b.addr(fn, e.Key, true).address(fn) + } else { + key = b.expr(fn, e.Key) + } + + loc := element{ + m: m, + k: emitConv(fn, key, t.Key(), e), + t: t.Elem(), + } + + // We call assign() only because it takes care + // of any &-operation required in the recursive + // case, e.g., + // map[int]*struct{}{0: {}} implies &struct{}{}. + // In-place update is of course impossible, + // and no storebuf is needed. + b.assign(fn, &loc, e.Value, true, nil, e) + } + sb.store(&address{addr: addr, expr: e}, m, e) + + default: + panic("unexpected CompositeLit type: " + t.String()) + } +} + +func (b *builder) switchStmt(fn *Function, s *ast.SwitchStmt, label *lblock) { + if s.Tag == nil { + b.switchStmtDynamic(fn, s, label) + return + } + dynamic := false + for _, iclause := range s.Body.List { + clause := iclause.(*ast.CaseClause) + for _, cond := range clause.List { + if fn.Pkg.info.Types[unparen(cond)].Value == nil { + dynamic = true + break + } + } + } + + if dynamic { + b.switchStmtDynamic(fn, s, label) + return + } + + if s.Init != nil { + b.stmt(fn, s.Init) + } + + entry := fn.currentBlock + tag := b.expr(fn, s.Tag) + + heads := make([]*BasicBlock, 0, len(s.Body.List)) + bodies := make([]*BasicBlock, len(s.Body.List)) + conds := make([]Value, 0, len(s.Body.List)) + + hasDefault := false + done := fn.newBasicBlock(fmt.Sprintf("switch.done")) + if label != nil { + label._break = done + } + for i, stmt := range s.Body.List { + body := fn.newBasicBlock(fmt.Sprintf("switch.body.%d", i)) + bodies[i] = body + cas := stmt.(*ast.CaseClause) + if cas.List == nil { + // default branch + hasDefault = true + head := fn.newBasicBlock(fmt.Sprintf("switch.head.%d", i)) + conds = append(conds, nil) + heads = append(heads, head) + fn.currentBlock = head + emitJump(fn, body, cas) + } + for j, cond := range stmt.(*ast.CaseClause).List { + fn.currentBlock = entry + head := fn.newBasicBlock(fmt.Sprintf("switch.head.%d.%d", i, j)) + conds = append(conds, b.expr(fn, cond)) + heads = append(heads, head) + fn.currentBlock = head + emitJump(fn, body, cond) + } + } + + for i, stmt := range s.Body.List { + clause := stmt.(*ast.CaseClause) + body := bodies[i] + fn.currentBlock = body + fallthru := done + if i+1 < len(bodies) { + fallthru = bodies[i+1] + } + fn.targets = &targets{ + tail: fn.targets, + _break: done, + _fallthrough: fallthru, + } + b.stmtList(fn, clause.Body) + fn.targets = fn.targets.tail + emitJump(fn, done, stmt) + } + + if !hasDefault { + head := fn.newBasicBlock(fmt.Sprintf("switch.head.implicit-default")) + body := fn.newBasicBlock("switch.body.implicit-default") + fn.currentBlock = head + emitJump(fn, body, s) + fn.currentBlock = body + emitJump(fn, done, s) + heads = append(heads, head) + conds = append(conds, nil) + } + + if len(heads) != len(conds) { + panic(fmt.Sprintf("internal error: %d heads for %d conds", len(heads), len(conds))) + } + for _, head := range heads { + addEdge(entry, head) + } + fn.currentBlock = entry + entry.emit(&ConstantSwitch{ + Tag: tag, + Conds: conds, + }, s) + fn.currentBlock = done +} + +// switchStmt emits to fn code for the switch statement s, optionally +// labelled by label. +// +func (b *builder) switchStmtDynamic(fn *Function, s *ast.SwitchStmt, label *lblock) { + // We treat SwitchStmt like a sequential if-else chain. + // Multiway dispatch can be recovered later by irutil.Switches() + // to those cases that are free of side effects. + if s.Init != nil { + b.stmt(fn, s.Init) + } + kTrue := emitConst(fn, NewConst(constant.MakeBool(true), tBool)) + + var tagv Value = kTrue + var tagSource ast.Node = s + if s.Tag != nil { + tagv = b.expr(fn, s.Tag) + tagSource = s.Tag + } + // lifting only considers loads and stores, but we want different + // sigma nodes for the different comparisons. use a temporary and + // load it in every branch. + tag := fn.addLocal(tagv.Type(), tagSource) + emitStore(fn, tag, tagv, tagSource) + + done := fn.newBasicBlock("switch.done") + if label != nil { + label._break = done + } + // We pull the default case (if present) down to the end. + // But each fallthrough label must point to the next + // body block in source order, so we preallocate a + // body block (fallthru) for the next case. + // Unfortunately this makes for a confusing block order. + var dfltBody *[]ast.Stmt + var dfltFallthrough *BasicBlock + var fallthru, dfltBlock *BasicBlock + ncases := len(s.Body.List) + for i, clause := range s.Body.List { + body := fallthru + if body == nil { + body = fn.newBasicBlock("switch.body") // first case only + } + + // Preallocate body block for the next case. + fallthru = done + if i+1 < ncases { + fallthru = fn.newBasicBlock("switch.body") + } + + cc := clause.(*ast.CaseClause) + if cc.List == nil { + // Default case. + dfltBody = &cc.Body + dfltFallthrough = fallthru + dfltBlock = body + continue + } + + var nextCond *BasicBlock + for _, cond := range cc.List { + nextCond = fn.newBasicBlock("switch.next") + if tagv == kTrue { + // emit a proper if/else chain instead of a comparison + // of a value against true. + // + // NOTE(dh): adonovan had a todo saying "don't forget + // conversions though". As far as I can tell, there + // aren't any conversions that we need to take care of + // here. `case bool(a) && bool(b)` as well as `case + // bool(a && b)` are being taken care of by b.cond, + // and `case a` where a is not of type bool is + // invalid. + b.cond(fn, cond, body, nextCond) + } else { + cond := emitCompare(fn, token.EQL, emitLoad(fn, tag, cond), b.expr(fn, cond), cond) + emitIf(fn, cond, body, nextCond, cond.Source()) + } + + fn.currentBlock = nextCond + } + fn.currentBlock = body + fn.targets = &targets{ + tail: fn.targets, + _break: done, + _fallthrough: fallthru, + } + b.stmtList(fn, cc.Body) + fn.targets = fn.targets.tail + emitJump(fn, done, s) + fn.currentBlock = nextCond + } + if dfltBlock != nil { + // The lack of a Source for the jump doesn't matter, block + // fusing will get rid of the jump later. + + emitJump(fn, dfltBlock, s) + fn.currentBlock = dfltBlock + fn.targets = &targets{ + tail: fn.targets, + _break: done, + _fallthrough: dfltFallthrough, + } + b.stmtList(fn, *dfltBody) + fn.targets = fn.targets.tail + } + emitJump(fn, done, s) + fn.currentBlock = done +} + +func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lblock) { + if s.Init != nil { + b.stmt(fn, s.Init) + } + + var tag Value + switch e := s.Assign.(type) { + case *ast.ExprStmt: // x.(type) + tag = b.expr(fn, unparen(e.X).(*ast.TypeAssertExpr).X) + case *ast.AssignStmt: // y := x.(type) + tag = b.expr(fn, unparen(e.Rhs[0]).(*ast.TypeAssertExpr).X) + default: + panic("unreachable") + } + tagPtr := fn.addLocal(tag.Type(), tag.Source()) + emitStore(fn, tagPtr, tag, tag.Source()) + + // +1 in case there's no explicit default case + heads := make([]*BasicBlock, 0, len(s.Body.List)+1) + + entry := fn.currentBlock + done := fn.newBasicBlock("done") + if label != nil { + label._break = done + } + + // set up type switch and constant switch, populate their conditions + tswtch := &TypeSwitch{ + Tag: emitLoad(fn, tagPtr, tag.Source()), + Conds: make([]types.Type, 0, len(s.Body.List)+1), + } + cswtch := &ConstantSwitch{ + Conds: make([]Value, 0, len(s.Body.List)+1), + } + + rets := make([]types.Type, 0, len(s.Body.List)+1) + index := 0 + var default_ *ast.CaseClause + for _, clause := range s.Body.List { + cc := clause.(*ast.CaseClause) + if obj := fn.Pkg.info.Implicits[cc]; obj != nil { + fn.addNamedLocal(obj, cc) + } + if cc.List == nil { + // default case + default_ = cc + } else { + for _, expr := range cc.List { + tswtch.Conds = append(tswtch.Conds, fn.Pkg.typeOf(expr)) + cswtch.Conds = append(cswtch.Conds, emitConst(fn, intConst(int64(index)))) + index++ + } + if len(cc.List) == 1 { + rets = append(rets, fn.Pkg.typeOf(cc.List[0])) + } else { + for range cc.List { + rets = append(rets, tag.Type()) + } + } + } + } + + // default branch + rets = append(rets, tag.Type()) + + var vars []*types.Var + vars = append(vars, varIndex) + for _, typ := range rets { + vars = append(vars, anonVar(typ)) + } + tswtch.setType(types.NewTuple(vars...)) + // default branch + fn.currentBlock = entry + fn.emit(tswtch, s) + cswtch.Conds = append(cswtch.Conds, emitConst(fn, intConst(int64(-1)))) + // in theory we should add a local and stores/loads for tswtch, to + // generate sigma nodes in the branches. however, there isn't any + // useful information we could possibly attach to it. + cswtch.Tag = emitExtract(fn, tswtch, 0, s) + fn.emit(cswtch, s) + + // build heads and bodies + index = 0 + for _, clause := range s.Body.List { + cc := clause.(*ast.CaseClause) + if cc.List == nil { + continue + } + + body := fn.newBasicBlock("typeswitch.body") + for _, expr := range cc.List { + head := fn.newBasicBlock("typeswitch.head") + heads = append(heads, head) + fn.currentBlock = head + + if obj := fn.Pkg.info.Implicits[cc]; obj != nil { + // In a switch y := x.(type), each case clause + // implicitly declares a distinct object y. + // In a single-type case, y has that type. + // In multi-type cases, 'case nil' and default, + // y has the same type as the interface operand. + + l := fn.objects[obj] + if rets[index] == tUntypedNil { + emitStore(fn, l, emitConst(fn, nilConst(tswtch.Tag.Type())), s.Assign) + } else { + x := emitExtract(fn, tswtch, index+1, s.Assign) + emitStore(fn, l, x, nil) + } + } + + emitJump(fn, body, expr) + index++ + } + fn.currentBlock = body + fn.targets = &targets{ + tail: fn.targets, + _break: done, + } + b.stmtList(fn, cc.Body) + fn.targets = fn.targets.tail + emitJump(fn, done, clause) + } + + if default_ == nil { + // implicit default + heads = append(heads, done) + } else { + body := fn.newBasicBlock("typeswitch.default") + heads = append(heads, body) + fn.currentBlock = body + fn.targets = &targets{ + tail: fn.targets, + _break: done, + } + if obj := fn.Pkg.info.Implicits[default_]; obj != nil { + l := fn.objects[obj] + x := emitExtract(fn, tswtch, index+1, s.Assign) + emitStore(fn, l, x, s) + } + b.stmtList(fn, default_.Body) + fn.targets = fn.targets.tail + emitJump(fn, done, s) + } + + fn.currentBlock = entry + for _, head := range heads { + addEdge(entry, head) + } + fn.currentBlock = done +} + +// selectStmt emits to fn code for the select statement s, optionally +// labelled by label. +// +func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) (noreturn bool) { + if len(s.Body.List) == 0 { + instr := &Select{Blocking: true} + instr.setType(types.NewTuple(varIndex, varOk)) + fn.emit(instr, s) + fn.emit(new(Unreachable), s) + addEdge(fn.currentBlock, fn.Exit) + return true + } + + // A blocking select of a single case degenerates to a + // simple send or receive. + // TODO(adonovan): opt: is this optimization worth its weight? + if len(s.Body.List) == 1 { + clause := s.Body.List[0].(*ast.CommClause) + if clause.Comm != nil { + b.stmt(fn, clause.Comm) + done := fn.newBasicBlock("select.done") + if label != nil { + label._break = done + } + fn.targets = &targets{ + tail: fn.targets, + _break: done, + } + b.stmtList(fn, clause.Body) + fn.targets = fn.targets.tail + emitJump(fn, done, clause) + fn.currentBlock = done + return false + } + } + + // First evaluate all channels in all cases, and find + // the directions of each state. + var states []*SelectState + blocking := true + debugInfo := fn.debugInfo() + for _, clause := range s.Body.List { + var st *SelectState + switch comm := clause.(*ast.CommClause).Comm.(type) { + case nil: // default case + blocking = false + continue + + case *ast.SendStmt: // ch<- i + ch := b.expr(fn, comm.Chan) + st = &SelectState{ + Dir: types.SendOnly, + Chan: ch, + Send: emitConv(fn, b.expr(fn, comm.Value), + ch.Type().Underlying().(*types.Chan).Elem(), comm), + Pos: comm.Arrow, + } + if debugInfo { + st.DebugNode = comm + } + + case *ast.AssignStmt: // x := <-ch + recv := unparen(comm.Rhs[0]).(*ast.UnaryExpr) + st = &SelectState{ + Dir: types.RecvOnly, + Chan: b.expr(fn, recv.X), + Pos: recv.OpPos, + } + if debugInfo { + st.DebugNode = recv + } + + case *ast.ExprStmt: // <-ch + recv := unparen(comm.X).(*ast.UnaryExpr) + st = &SelectState{ + Dir: types.RecvOnly, + Chan: b.expr(fn, recv.X), + Pos: recv.OpPos, + } + if debugInfo { + st.DebugNode = recv + } + } + states = append(states, st) + } + + // We dispatch on the (fair) result of Select using a + // switch on the returned index. + sel := &Select{ + States: states, + Blocking: blocking, + } + sel.source = s + var vars []*types.Var + vars = append(vars, varIndex, varOk) + for _, st := range states { + if st.Dir == types.RecvOnly { + tElem := st.Chan.Type().Underlying().(*types.Chan).Elem() + vars = append(vars, anonVar(tElem)) + } + } + sel.setType(types.NewTuple(vars...)) + fn.emit(sel, s) + idx := emitExtract(fn, sel, 0, s) + + done := fn.newBasicBlock("select.done") + if label != nil { + label._break = done + } + + entry := fn.currentBlock + swtch := &ConstantSwitch{ + Tag: idx, + // one condition per case + Conds: make([]Value, 0, len(s.Body.List)+1), + } + // note that we don't need heads; a select case can only have a single condition + var bodies []*BasicBlock + + state := 0 + r := 2 // index in 'sel' tuple of value; increments if st.Dir==RECV + for _, cc := range s.Body.List { + clause := cc.(*ast.CommClause) + if clause.Comm == nil { + body := fn.newBasicBlock("select.default") + fn.currentBlock = body + bodies = append(bodies, body) + fn.targets = &targets{ + tail: fn.targets, + _break: done, + } + b.stmtList(fn, clause.Body) + emitJump(fn, done, s) + fn.targets = fn.targets.tail + swtch.Conds = append(swtch.Conds, emitConst(fn, intConst(-1))) + continue + } + swtch.Conds = append(swtch.Conds, emitConst(fn, intConst(int64(state)))) + body := fn.newBasicBlock("select.body") + fn.currentBlock = body + bodies = append(bodies, body) + fn.targets = &targets{ + tail: fn.targets, + _break: done, + } + switch comm := clause.Comm.(type) { + case *ast.ExprStmt: // <-ch + if debugInfo { + v := emitExtract(fn, sel, r, comm) + emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false) + } + r++ + + case *ast.AssignStmt: // x := <-states[state].Chan + if comm.Tok == token.DEFINE { + fn.addLocalForIdent(comm.Lhs[0].(*ast.Ident)) + } + x := b.addr(fn, comm.Lhs[0], false) // non-escaping + v := emitExtract(fn, sel, r, comm) + if debugInfo { + emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false) + } + x.store(fn, v, comm) + + if len(comm.Lhs) == 2 { // x, ok := ... + if comm.Tok == token.DEFINE { + fn.addLocalForIdent(comm.Lhs[1].(*ast.Ident)) + } + ok := b.addr(fn, comm.Lhs[1], false) // non-escaping + ok.store(fn, emitExtract(fn, sel, 1, comm), comm) + } + r++ + } + b.stmtList(fn, clause.Body) + fn.targets = fn.targets.tail + emitJump(fn, done, s) + state++ + } + fn.currentBlock = entry + fn.emit(swtch, s) + for _, body := range bodies { + addEdge(entry, body) + } + fn.currentBlock = done + return false +} + +// forStmt emits to fn code for the for statement s, optionally +// labelled by label. +// +func (b *builder) forStmt(fn *Function, s *ast.ForStmt, label *lblock) { + // ...init... + // jump loop + // loop: + // if cond goto body else done + // body: + // ...body... + // jump post + // post: (target of continue) + // ...post... + // jump loop + // done: (target of break) + if s.Init != nil { + b.stmt(fn, s.Init) + } + body := fn.newBasicBlock("for.body") + done := fn.newBasicBlock("for.done") // target of 'break' + loop := body // target of back-edge + if s.Cond != nil { + loop = fn.newBasicBlock("for.loop") + } + cont := loop // target of 'continue' + if s.Post != nil { + cont = fn.newBasicBlock("for.post") + } + if label != nil { + label._break = done + label._continue = cont + } + emitJump(fn, loop, s) + fn.currentBlock = loop + if loop != body { + b.cond(fn, s.Cond, body, done) + fn.currentBlock = body + } + fn.targets = &targets{ + tail: fn.targets, + _break: done, + _continue: cont, + } + b.stmt(fn, s.Body) + fn.targets = fn.targets.tail + emitJump(fn, cont, s) + + if s.Post != nil { + fn.currentBlock = cont + b.stmt(fn, s.Post) + emitJump(fn, loop, s) // back-edge + } + fn.currentBlock = done +} + +// rangeIndexed emits to fn the header for an integer-indexed loop +// over array, *array or slice value x. +// The v result is defined only if tv is non-nil. +// forPos is the position of the "for" token. +// +func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, source ast.Node) (k, v Value, loop, done *BasicBlock) { + // + // length = len(x) + // index = -1 + // loop: (target of continue) + // index++ + // if index < length goto body else done + // body: + // k = index + // v = x[index] + // ...body... + // jump loop + // done: (target of break) + + // Determine number of iterations. + var length Value + if arr, ok := deref(x.Type()).Underlying().(*types.Array); ok { + // For array or *array, the number of iterations is + // known statically thanks to the type. We avoid a + // data dependence upon x, permitting later dead-code + // elimination if x is pure, static unrolling, etc. + // Ranging over a nil *array may have >0 iterations. + // We still generate code for x, in case it has effects. + length = emitConst(fn, intConst(arr.Len())) + } else { + // length = len(x). + var c Call + c.Call.Value = makeLen(x.Type()) + c.Call.Args = []Value{x} + c.setType(tInt) + length = fn.emit(&c, source) + } + + index := fn.addLocal(tInt, source) + emitStore(fn, index, emitConst(fn, intConst(-1)), source) + + loop = fn.newBasicBlock("rangeindex.loop") + emitJump(fn, loop, source) + fn.currentBlock = loop + + incr := &BinOp{ + Op: token.ADD, + X: emitLoad(fn, index, source), + Y: emitConst(fn, intConst(1)), + } + incr.setType(tInt) + emitStore(fn, index, fn.emit(incr, source), source) + + body := fn.newBasicBlock("rangeindex.body") + done = fn.newBasicBlock("rangeindex.done") + emitIf(fn, emitCompare(fn, token.LSS, incr, length, source), body, done, source) + fn.currentBlock = body + + k = emitLoad(fn, index, source) + if tv != nil { + switch t := x.Type().Underlying().(type) { + case *types.Array: + instr := &Index{ + X: x, + Index: k, + } + instr.setType(t.Elem()) + v = fn.emit(instr, source) + + case *types.Pointer: // *array + instr := &IndexAddr{ + X: x, + Index: k, + } + instr.setType(types.NewPointer(t.Elem().Underlying().(*types.Array).Elem())) + v = emitLoad(fn, fn.emit(instr, source), source) + + case *types.Slice: + instr := &IndexAddr{ + X: x, + Index: k, + } + instr.setType(types.NewPointer(t.Elem())) + v = emitLoad(fn, fn.emit(instr, source), source) + + default: + panic("rangeIndexed x:" + t.String()) + } + } + return +} + +// rangeIter emits to fn the header for a loop using +// Range/Next/Extract to iterate over map or string value x. +// tk and tv are the types of the key/value results k and v, or nil +// if the respective component is not wanted. +// +func (b *builder) rangeIter(fn *Function, x Value, tk, tv types.Type, source ast.Node) (k, v Value, loop, done *BasicBlock) { + // + // it = range x + // loop: (target of continue) + // okv = next it (ok, key, value) + // ok = extract okv #0 + // if ok goto body else done + // body: + // k = extract okv #1 + // v = extract okv #2 + // ...body... + // jump loop + // done: (target of break) + // + + if tk == nil { + tk = tInvalid + } + if tv == nil { + tv = tInvalid + } + + rng := &Range{X: x} + rng.setType(tRangeIter) + it := fn.emit(rng, source) + + loop = fn.newBasicBlock("rangeiter.loop") + emitJump(fn, loop, source) + fn.currentBlock = loop + + _, isString := x.Type().Underlying().(*types.Basic) + + okv := &Next{ + Iter: it, + IsString: isString, + } + okv.setType(types.NewTuple( + varOk, + newVar("k", tk), + newVar("v", tv), + )) + fn.emit(okv, source) + + body := fn.newBasicBlock("rangeiter.body") + done = fn.newBasicBlock("rangeiter.done") + emitIf(fn, emitExtract(fn, okv, 0, source), body, done, source) + fn.currentBlock = body + + if tk != tInvalid { + k = emitExtract(fn, okv, 1, source) + } + if tv != tInvalid { + v = emitExtract(fn, okv, 2, source) + } + return +} + +// rangeChan emits to fn the header for a loop that receives from +// channel x until it fails. +// tk is the channel's element type, or nil if the k result is +// not wanted +// pos is the position of the '=' or ':=' token. +// +func (b *builder) rangeChan(fn *Function, x Value, tk types.Type, source ast.Node) (k Value, loop, done *BasicBlock) { + // + // loop: (target of continue) + // ko = <-x (key, ok) + // ok = extract ko #1 + // if ok goto body else done + // body: + // k = extract ko #0 + // ... + // goto loop + // done: (target of break) + + loop = fn.newBasicBlock("rangechan.loop") + emitJump(fn, loop, source) + fn.currentBlock = loop + retv := emitRecv(fn, x, true, types.NewTuple(newVar("k", x.Type().Underlying().(*types.Chan).Elem()), varOk), source) + body := fn.newBasicBlock("rangechan.body") + done = fn.newBasicBlock("rangechan.done") + emitIf(fn, emitExtract(fn, retv, 1, source), body, done, source) + fn.currentBlock = body + if tk != nil { + k = emitExtract(fn, retv, 0, source) + } + return +} + +// rangeStmt emits to fn code for the range statement s, optionally +// labelled by label. +// +func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock, source ast.Node) { + var tk, tv types.Type + if s.Key != nil && !isBlankIdent(s.Key) { + tk = fn.Pkg.typeOf(s.Key) + } + if s.Value != nil && !isBlankIdent(s.Value) { + tv = fn.Pkg.typeOf(s.Value) + } + + // If iteration variables are defined (:=), this + // occurs once outside the loop. + // + // Unlike a short variable declaration, a RangeStmt + // using := never redeclares an existing variable; it + // always creates a new one. + if s.Tok == token.DEFINE { + if tk != nil { + fn.addLocalForIdent(s.Key.(*ast.Ident)) + } + if tv != nil { + fn.addLocalForIdent(s.Value.(*ast.Ident)) + } + } + + x := b.expr(fn, s.X) + + var k, v Value + var loop, done *BasicBlock + switch rt := x.Type().Underlying().(type) { + case *types.Slice, *types.Array, *types.Pointer: // *array + k, v, loop, done = b.rangeIndexed(fn, x, tv, source) + + case *types.Chan: + k, loop, done = b.rangeChan(fn, x, tk, source) + + case *types.Map, *types.Basic: // string + k, v, loop, done = b.rangeIter(fn, x, tk, tv, source) + + default: + panic("Cannot range over: " + rt.String()) + } + + // Evaluate both LHS expressions before we update either. + var kl, vl lvalue + if tk != nil { + kl = b.addr(fn, s.Key, false) // non-escaping + } + if tv != nil { + vl = b.addr(fn, s.Value, false) // non-escaping + } + if tk != nil { + kl.store(fn, k, s) + } + if tv != nil { + vl.store(fn, v, s) + } + + if label != nil { + label._break = done + label._continue = loop + } + + fn.targets = &targets{ + tail: fn.targets, + _break: done, + _continue: loop, + } + b.stmt(fn, s.Body) + fn.targets = fn.targets.tail + emitJump(fn, loop, source) // back-edge + fn.currentBlock = done +} + +// stmt lowers statement s to IR form, emitting code to fn. +func (b *builder) stmt(fn *Function, _s ast.Stmt) { + // The label of the current statement. If non-nil, its _goto + // target is always set; its _break and _continue are set only + // within the body of switch/typeswitch/select/for/range. + // It is effectively an additional default-nil parameter of stmt(). + var label *lblock +start: + switch s := _s.(type) { + case *ast.EmptyStmt: + // ignore. (Usually removed by gofmt.) + + case *ast.DeclStmt: // Con, Var or Typ + d := s.Decl.(*ast.GenDecl) + if d.Tok == token.VAR { + for _, spec := range d.Specs { + if vs, ok := spec.(*ast.ValueSpec); ok { + b.localValueSpec(fn, vs) + } + } + } + + case *ast.LabeledStmt: + label = fn.labelledBlock(s.Label) + emitJump(fn, label._goto, s) + fn.currentBlock = label._goto + _s = s.Stmt + goto start // effectively: tailcall stmt(fn, s.Stmt, label) + + case *ast.ExprStmt: + b.expr(fn, s.X) + + case *ast.SendStmt: + instr := &Send{ + Chan: b.expr(fn, s.Chan), + X: emitConv(fn, b.expr(fn, s.Value), + fn.Pkg.typeOf(s.Chan).Underlying().(*types.Chan).Elem(), s), + } + fn.emit(instr, s) + + case *ast.IncDecStmt: + op := token.ADD + if s.Tok == token.DEC { + op = token.SUB + } + loc := b.addr(fn, s.X, false) + b.assignOp(fn, loc, emitConst(fn, NewConst(constant.MakeInt64(1), loc.typ())), op, s) + + case *ast.AssignStmt: + switch s.Tok { + case token.ASSIGN, token.DEFINE: + b.assignStmt(fn, s.Lhs, s.Rhs, s.Tok == token.DEFINE, _s) + + default: // +=, etc. + op := s.Tok + token.ADD - token.ADD_ASSIGN + b.assignOp(fn, b.addr(fn, s.Lhs[0], false), b.expr(fn, s.Rhs[0]), op, s) + } + + case *ast.GoStmt: + // The "intrinsics" new/make/len/cap are forbidden here. + // panic is treated like an ordinary function call. + v := Go{} + b.setCall(fn, s.Call, &v.Call) + fn.emit(&v, s) + + case *ast.DeferStmt: + // The "intrinsics" new/make/len/cap are forbidden here. + // panic is treated like an ordinary function call. + v := Defer{} + b.setCall(fn, s.Call, &v.Call) + fn.hasDefer = true + fn.emit(&v, s) + + case *ast.ReturnStmt: + // TODO(dh): we could emit tigher position information by + // using the ith returned expression + + var results []Value + if len(s.Results) == 1 && fn.Signature.Results().Len() > 1 { + // Return of one expression in a multi-valued function. + tuple := b.exprN(fn, s.Results[0]) + ttuple := tuple.Type().(*types.Tuple) + for i, n := 0, ttuple.Len(); i < n; i++ { + results = append(results, + emitConv(fn, emitExtract(fn, tuple, i, s), + fn.Signature.Results().At(i).Type(), s)) + } + } else { + // 1:1 return, or no-arg return in non-void function. + for i, r := range s.Results { + v := emitConv(fn, b.expr(fn, r), fn.Signature.Results().At(i).Type(), s) + results = append(results, v) + } + } + + ret := fn.results() + for i, r := range results { + emitStore(fn, ret[i], r, s) + } + + emitJump(fn, fn.Exit, s) + fn.currentBlock = fn.newBasicBlock("unreachable") + + case *ast.BranchStmt: + var block *BasicBlock + switch s.Tok { + case token.BREAK: + if s.Label != nil { + block = fn.labelledBlock(s.Label)._break + } else { + for t := fn.targets; t != nil && block == nil; t = t.tail { + block = t._break + } + } + + case token.CONTINUE: + if s.Label != nil { + block = fn.labelledBlock(s.Label)._continue + } else { + for t := fn.targets; t != nil && block == nil; t = t.tail { + block = t._continue + } + } + + case token.FALLTHROUGH: + for t := fn.targets; t != nil && block == nil; t = t.tail { + block = t._fallthrough + } + + case token.GOTO: + block = fn.labelledBlock(s.Label)._goto + } + j := emitJump(fn, block, s) + j.Comment = s.Tok.String() + fn.currentBlock = fn.newBasicBlock("unreachable") + + case *ast.BlockStmt: + b.stmtList(fn, s.List) + + case *ast.IfStmt: + if s.Init != nil { + b.stmt(fn, s.Init) + } + then := fn.newBasicBlock("if.then") + done := fn.newBasicBlock("if.done") + els := done + if s.Else != nil { + els = fn.newBasicBlock("if.else") + } + instr := b.cond(fn, s.Cond, then, els) + instr.source = s + fn.currentBlock = then + b.stmt(fn, s.Body) + emitJump(fn, done, s) + + if s.Else != nil { + fn.currentBlock = els + b.stmt(fn, s.Else) + emitJump(fn, done, s) + } + + fn.currentBlock = done + + case *ast.SwitchStmt: + b.switchStmt(fn, s, label) + + case *ast.TypeSwitchStmt: + b.typeSwitchStmt(fn, s, label) + + case *ast.SelectStmt: + if b.selectStmt(fn, s, label) { + // the select has no cases, it blocks forever + fn.currentBlock = fn.newBasicBlock("unreachable") + } + + case *ast.ForStmt: + b.forStmt(fn, s, label) + + case *ast.RangeStmt: + b.rangeStmt(fn, s, label, s) + + default: + panic(fmt.Sprintf("unexpected statement kind: %T", s)) + } +} + +// buildFunction builds IR code for the body of function fn. Idempotent. +func (b *builder) buildFunction(fn *Function) { + if fn.Blocks != nil { + return // building already started + } + + var recvField *ast.FieldList + var body *ast.BlockStmt + var functype *ast.FuncType + switch n := fn.source.(type) { + case nil: + return // not a Go source function. (Synthetic, or from object file.) + case *ast.FuncDecl: + functype = n.Type + recvField = n.Recv + body = n.Body + case *ast.FuncLit: + functype = n.Type + body = n.Body + default: + panic(n) + } + + if fn.Package().Pkg.Path() == "syscall" && fn.Name() == "Exit" { + // syscall.Exit is a stub and the way os.Exit terminates the + // process. Note that there are other functions in the runtime + // that also terminate or unwind that we cannot analyze. + // However, they aren't stubs, so buildExits ends up getting + // called on them, so that's where we handle those special + // cases. + fn.WillExit = true + } + + if body == nil { + // External function. + if fn.Params == nil { + // This condition ensures we add a non-empty + // params list once only, but we may attempt + // the degenerate empty case repeatedly. + // TODO(adonovan): opt: don't do that. + + // We set Function.Params even though there is no body + // code to reference them. This simplifies clients. + if recv := fn.Signature.Recv(); recv != nil { + // XXX synthesize an ast.Node + fn.addParamObj(recv, nil) + } + params := fn.Signature.Params() + for i, n := 0, params.Len(); i < n; i++ { + // XXX synthesize an ast.Node + fn.addParamObj(params.At(i), nil) + } + } + return + } + if fn.Prog.mode&LogSource != 0 { + defer logStack("build function %s @ %s", fn, fn.Prog.Fset.Position(fn.Pos()))() + } + fn.blocksets = b.blocksets + fn.startBody() + fn.createSyntacticParams(recvField, functype) + fn.exitBlock() + b.stmt(fn, body) + if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb.Preds != nil) { + // Control fell off the end of the function's body block. + // + // Block optimizations eliminate the current block, if + // unreachable. It is a builder invariant that + // if this no-arg return is ill-typed for + // fn.Signature.Results, this block must be + // unreachable. The sanity checker checks this. + // fn.emit(new(RunDefers)) + // fn.emit(new(Return)) + emitJump(fn, fn.Exit, nil) + } + optimizeBlocks(fn) + buildFakeExits(fn) + b.buildExits(fn) + b.addUnreachables(fn) + fn.finishBody() + b.blocksets = fn.blocksets + fn.functionBody = nil +} + +// buildFuncDecl builds IR code for the function or method declared +// by decl in package pkg. +// +func (b *builder) buildFuncDecl(pkg *Package, decl *ast.FuncDecl) { + id := decl.Name + if isBlankIdent(id) { + return // discard + } + fn := pkg.values[pkg.info.Defs[id]].(*Function) + if decl.Recv == nil && id.Name == "init" { + var v Call + v.Call.Value = fn + v.setType(types.NewTuple()) + pkg.init.emit(&v, decl) + } + fn.source = decl + b.buildFunction(fn) +} + +// Build calls Package.Build for each package in prog. +// +// Build is intended for whole-program analysis; a typical compiler +// need only build a single package. +// +// Build is idempotent and thread-safe. +// +func (prog *Program) Build() { + for _, p := range prog.packages { + p.Build() + } +} + +// Build builds IR code for all functions and vars in package p. +// +// Precondition: CreatePackage must have been called for all of p's +// direct imports (and hence its direct imports must have been +// error-free). +// +// Build is idempotent and thread-safe. +// +func (p *Package) Build() { p.buildOnce.Do(p.build) } + +func (p *Package) build() { + if p.info == nil { + return // synthetic package, e.g. "testmain" + } + + // Ensure we have runtime type info for all exported members. + // TODO(adonovan): ideally belongs in memberFromObject, but + // that would require package creation in topological order. + for name, mem := range p.Members { + if ast.IsExported(name) { + p.Prog.needMethodsOf(mem.Type()) + } + } + if p.Prog.mode&LogSource != 0 { + defer logStack("build %s", p)() + } + init := p.init + init.startBody() + init.exitBlock() + + var done *BasicBlock + + // Make init() skip if package is already initialized. + initguard := p.Var("init$guard") + doinit := init.newBasicBlock("init.start") + done = init.Exit + emitIf(init, emitLoad(init, initguard, nil), done, doinit, nil) + init.currentBlock = doinit + emitStore(init, initguard, emitConst(init, NewConst(constant.MakeBool(true), tBool)), nil) + + // Call the init() function of each package we import. + for _, pkg := range p.Pkg.Imports() { + prereq := p.Prog.packages[pkg] + if prereq == nil { + panic(fmt.Sprintf("Package(%q).Build(): unsatisfied import: Program.CreatePackage(%q) was not called", p.Pkg.Path(), pkg.Path())) + } + var v Call + v.Call.Value = prereq.init + v.setType(types.NewTuple()) + init.emit(&v, nil) + } + + b := builder{ + printFunc: p.printFunc, + } + + // Initialize package-level vars in correct order. + for _, varinit := range p.info.InitOrder { + if init.Prog.mode&LogSource != 0 { + fmt.Fprintf(os.Stderr, "build global initializer %v @ %s\n", + varinit.Lhs, p.Prog.Fset.Position(varinit.Rhs.Pos())) + } + if len(varinit.Lhs) == 1 { + // 1:1 initialization: var x, y = a(), b() + var lval lvalue + if v := varinit.Lhs[0]; v.Name() != "_" { + lval = &address{addr: p.values[v].(*Global)} + } else { + lval = blank{} + } + // TODO(dh): do emit position information + b.assign(init, lval, varinit.Rhs, true, nil, nil) + } else { + // n:1 initialization: var x, y := f() + tuple := b.exprN(init, varinit.Rhs) + for i, v := range varinit.Lhs { + if v.Name() == "_" { + continue + } + emitStore(init, p.values[v].(*Global), emitExtract(init, tuple, i, nil), nil) + } + } + } + + // Build all package-level functions, init functions + // and methods, including unreachable/blank ones. + // We build them in source order, but it's not significant. + for _, file := range p.files { + for _, decl := range file.Decls { + if decl, ok := decl.(*ast.FuncDecl); ok { + b.buildFuncDecl(p, decl) + } + } + } + + // Finish up init(). + emitJump(init, done, nil) + init.finishBody() + + p.info = nil // We no longer need ASTs or go/types deductions. + + if p.Prog.mode&SanityCheckFunctions != 0 { + sanityCheckPackage(p) + } +} + +// Like ObjectOf, but panics instead of returning nil. +// Only valid during p's create and build phases. +func (p *Package) objectOf(id *ast.Ident) types.Object { + if o := p.info.ObjectOf(id); o != nil { + return o + } + panic(fmt.Sprintf("no types.Object for ast.Ident %s @ %s", + id.Name, p.Prog.Fset.Position(id.Pos()))) +} + +// Like TypeOf, but panics instead of returning nil. +// Only valid during p's create and build phases. +func (p *Package) typeOf(e ast.Expr) types.Type { + if T := p.info.TypeOf(e); T != nil { + return T + } + panic(fmt.Sprintf("no type for %T @ %s", + e, p.Prog.Fset.Position(e.Pos()))) +} diff --git a/vendor/honnef.co/go/tools/ssa/const.go b/vendor/honnef.co/go/tools/ir/const.go similarity index 85% rename from vendor/honnef.co/go/tools/ssa/const.go rename to vendor/honnef.co/go/tools/ir/const.go index f95d9e11400..7cdf006e83a 100644 --- a/vendor/honnef.co/go/tools/ssa/const.go +++ b/vendor/honnef.co/go/tools/ir/const.go @@ -2,14 +2,13 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package ssa +package ir // This file defines the Const SSA value type. import ( "fmt" "go/constant" - "go/token" "go/types" "strconv" ) @@ -18,7 +17,12 @@ import ( // val must be valid according to the specification of Const.Value. // func NewConst(val constant.Value, typ types.Type) *Const { - return &Const{typ, val} + return &Const{ + register: register{ + typ: typ, + }, + Value: val, + } } // intConst returns an 'int' constant that evaluates to i. @@ -71,43 +75,25 @@ func zeroConst(t types.Type) *Const { } func (c *Const) RelString(from *types.Package) string { - var s string + var p string if c.Value == nil { - s = "nil" + p = "nil" } else if c.Value.Kind() == constant.String { - s = constant.StringVal(c.Value) + v := constant.StringVal(c.Value) const max = 20 // TODO(adonovan): don't cut a rune in half. - if len(s) > max { - s = s[:max-3] + "..." // abbreviate + if len(v) > max { + v = v[:max-3] + "..." // abbreviate } - s = strconv.Quote(s) + p = strconv.Quote(v) } else { - s = c.Value.String() + p = c.Value.String() } - return s + ":" + relType(c.Type(), from) -} - -func (c *Const) Name() string { - return c.RelString(nil) + return fmt.Sprintf("Const <%s> {%s}", relType(c.Type(), from), p) } func (c *Const) String() string { - return c.Name() -} - -func (c *Const) Type() types.Type { - return c.typ -} - -func (c *Const) Referrers() *[]Instruction { - return nil -} - -func (c *Const) Parent() *Function { return nil } - -func (c *Const) Pos() token.Pos { - return token.NoPos + return c.RelString(c.Parent().pkg()) } // IsNil returns true if this constant represents a typed or untyped nil value. @@ -115,8 +101,6 @@ func (c *Const) IsNil() bool { return c.Value == nil } -// TODO(adonovan): move everything below into honnef.co/go/tools/ssa/interp. - // Int64 returns the numeric value of this constant truncated to fit // a signed 64-bit integer. // diff --git a/vendor/honnef.co/go/tools/ssa/create.go b/vendor/honnef.co/go/tools/ir/create.go similarity index 82% rename from vendor/honnef.co/go/tools/ssa/create.go rename to vendor/honnef.co/go/tools/ir/create.go index 85163a0c5a7..ff81a244bdc 100644 --- a/vendor/honnef.co/go/tools/ssa/create.go +++ b/vendor/honnef.co/go/tools/ir/create.go @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package ssa +package ir -// This file implements the CREATE phase of SSA construction. +// This file implements the CREATE phase of IR construction. // See builder.go for explanation. import ( @@ -18,9 +18,9 @@ import ( "golang.org/x/tools/go/types/typeutil" ) -// NewProgram returns a new SSA Program. +// NewProgram returns a new IR Program. // -// mode controls diagnostics and checking during SSA construction. +// mode controls diagnostics and checking during IR construction. // func NewProgram(fset *token.FileSet, mode BuilderMode) *Program { prog := &Program{ @@ -75,7 +75,6 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { name: name, object: obj, typ: types.NewPointer(obj.Type()), // address - pos: obj.Pos(), } pkg.values[obj] = g pkg.Members[name] = g @@ -90,16 +89,20 @@ func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node) { name: name, object: obj, Signature: sig, - syntax: syntax, - pos: obj.Pos(), Pkg: pkg, Prog: pkg.Prog, } + + fn.source = syntax + fn.initHTML(pkg.printFunc) if syntax == nil { fn.Synthetic = "loaded from gc object file" + } else { + fn.functionBody = new(functionBody) } pkg.values[obj] = fn + pkg.Functions = append(pkg.Functions, fn) if sig.Recv() == nil { pkg.Members[name] = fn // package-level function } @@ -152,35 +155,39 @@ func membersFromDecl(pkg *Package, decl ast.Decl) { } } -// CreatePackage constructs and returns an SSA Package from the +// CreatePackage constructs and returns an IR Package from the // specified type-checked, error-free file ASTs, and populates its // Members mapping. // // importable determines whether this package should be returned by a // subsequent call to ImportedPackage(pkg.Path()). // -// The real work of building SSA form for each function is not done +// The real work of building IR form for each function is not done // until a subsequent call to Package.Build(). // func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info *types.Info, importable bool) *Package { p := &Package{ - Prog: prog, - Members: make(map[string]Member), - values: make(map[types.Object]Value), - Pkg: pkg, - info: info, // transient (CREATE and BUILD phases) - files: files, // transient (CREATE and BUILD phases) + Prog: prog, + Members: make(map[string]Member), + values: make(map[types.Object]Value), + Pkg: pkg, + info: info, // transient (CREATE and BUILD phases) + files: files, // transient (CREATE and BUILD phases) + printFunc: prog.PrintFunc, } // Add init() function. p.init = &Function{ - name: "init", - Signature: new(types.Signature), - Synthetic: "package initializer", - Pkg: p, - Prog: prog, + name: "init", + Signature: new(types.Signature), + Synthetic: "package initializer", + Pkg: p, + Prog: prog, + functionBody: new(functionBody), } + p.init.initHTML(prog.PrintFunc) p.Members[p.init.name] = p.init + p.Functions = append(p.Functions, p.init) // CREATE phase. // Allocate all package members: vars, funcs, consts and types. @@ -209,15 +216,13 @@ func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info * } } - if prog.mode&BareInits == 0 { - // Add initializer guard variable. - initguard := &Global{ - Pkg: p, - name: "init$guard", - typ: types.NewPointer(tBool), - } - p.Members[initguard.Name()] = initguard + // Add initializer guard variable. + initguard := &Global{ + Pkg: p, + name: "init$guard", + typ: types.NewPointer(tBool), } + p.Members[initguard.Name()] = initguard if prog.mode&GlobalDebug != 0 { p.SetDebugMode(true) @@ -260,10 +265,10 @@ func (prog *Program) AllPackages() []*Package { // // TODO(adonovan): rethink this function and the "importable" concept; // most packages are importable. This function assumes that all -// types.Package.Path values are unique within the ssa.Program, which is +// types.Package.Path values are unique within the ir.Program, which is // false---yet this function remains very convenient. // Clients should use (*Program).Package instead where possible. -// SSA doesn't really need a string-keyed map of packages. +// IR doesn't really need a string-keyed map of packages. // func (prog *Program) ImportedPackage(path string) *Package { return prog.imported[path] diff --git a/vendor/honnef.co/go/tools/ir/doc.go b/vendor/honnef.co/go/tools/ir/doc.go new file mode 100644 index 00000000000..a5f42e4f47d --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/doc.go @@ -0,0 +1,129 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package ir defines a representation of the elements of Go programs +// (packages, types, functions, variables and constants) using a +// static single-information (SSI) form intermediate representation +// (IR) for the bodies of functions. +// +// THIS INTERFACE IS EXPERIMENTAL AND IS LIKELY TO CHANGE. +// +// For an introduction to SSA form, upon which SSI builds, see +// http://en.wikipedia.org/wiki/Static_single_assignment_form. +// This page provides a broader reading list: +// http://www.dcs.gla.ac.uk/~jsinger/ssa.html. +// +// For an introduction to SSI form, see The static single information +// form by C. Scott Ananian. +// +// The level of abstraction of the IR form is intentionally close to +// the source language to facilitate construction of source analysis +// tools. It is not intended for machine code generation. +// +// The simplest way to create the IR of a package is +// to load typed syntax trees using golang.org/x/tools/go/packages, then +// invoke the irutil.Packages helper function. See ExampleLoadPackages +// and ExampleWholeProgram for examples. +// The resulting ir.Program contains all the packages and their +// members, but IR code is not created for function bodies until a +// subsequent call to (*Package).Build or (*Program).Build. +// +// The builder initially builds a naive IR form in which all local +// variables are addresses of stack locations with explicit loads and +// stores. Registerisation of eligible locals and φ-node insertion +// using dominance and dataflow are then performed as a second pass +// called "lifting" to improve the accuracy and performance of +// subsequent analyses; this pass can be skipped by setting the +// NaiveForm builder flag. +// +// The primary interfaces of this package are: +// +// - Member: a named member of a Go package. +// - Value: an expression that yields a value. +// - Instruction: a statement that consumes values and performs computation. +// - Node: a Value or Instruction (emphasizing its membership in the IR value graph) +// +// A computation that yields a result implements both the Value and +// Instruction interfaces. The following table shows for each +// concrete type which of these interfaces it implements. +// +// Value? Instruction? Member? +// *Alloc ✔ ✔ +// *BinOp ✔ ✔ +// *BlankStore ✔ +// *Builtin ✔ +// *Call ✔ ✔ +// *ChangeInterface ✔ ✔ +// *ChangeType ✔ ✔ +// *Const ✔ ✔ +// *Convert ✔ ✔ +// *DebugRef ✔ +// *Defer ✔ ✔ +// *Extract ✔ ✔ +// *Field ✔ ✔ +// *FieldAddr ✔ ✔ +// *FreeVar ✔ +// *Function ✔ ✔ (func) +// *Global ✔ ✔ (var) +// *Go ✔ ✔ +// *If ✔ +// *Index ✔ ✔ +// *IndexAddr ✔ ✔ +// *Jump ✔ +// *Load ✔ ✔ +// *MakeChan ✔ ✔ +// *MakeClosure ✔ ✔ +// *MakeInterface ✔ ✔ +// *MakeMap ✔ ✔ +// *MakeSlice ✔ ✔ +// *MapLookup ✔ ✔ +// *MapUpdate ✔ ✔ +// *NamedConst ✔ (const) +// *Next ✔ ✔ +// *Panic ✔ +// *Parameter ✔ ✔ +// *Phi ✔ ✔ +// *Range ✔ ✔ +// *Recv ✔ ✔ +// *Return ✔ +// *RunDefers ✔ +// *Select ✔ ✔ +// *Send ✔ ✔ +// *Sigma ✔ ✔ +// *Slice ✔ ✔ +// *Store ✔ ✔ +// *StringLookup ✔ ✔ +// *Type ✔ (type) +// *TypeAssert ✔ ✔ +// *UnOp ✔ ✔ +// *Unreachable ✔ +// +// Other key types in this package include: Program, Package, Function +// and BasicBlock. +// +// The program representation constructed by this package is fully +// resolved internally, i.e. it does not rely on the names of Values, +// Packages, Functions, Types or BasicBlocks for the correct +// interpretation of the program. Only the identities of objects and +// the topology of the IR and type graphs are semantically +// significant. (There is one exception: Ids, used to identify field +// and method names, contain strings.) Avoidance of name-based +// operations simplifies the implementation of subsequent passes and +// can make them very efficient. Many objects are nonetheless named +// to aid in debugging, but it is not essential that the names be +// either accurate or unambiguous. The public API exposes a number of +// name-based maps for client convenience. +// +// The ir/irutil package provides various utilities that depend only +// on the public API of this package. +// +// TODO(adonovan): Consider the exceptional control-flow implications +// of defer and recover(). +// +// TODO(adonovan): write a how-to document for all the various cases +// of trying to determine corresponding elements across the four +// domains of source locations, ast.Nodes, types.Objects, +// ir.Values/Instructions. +// +package ir // import "honnef.co/go/tools/ir" diff --git a/vendor/honnef.co/go/tools/ir/dom.go b/vendor/honnef.co/go/tools/ir/dom.go new file mode 100644 index 00000000000..08c147df9b9 --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/dom.go @@ -0,0 +1,461 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// This file defines algorithms related to dominance. + +// Dominator tree construction ---------------------------------------- +// +// We use the algorithm described in Lengauer & Tarjan. 1979. A fast +// algorithm for finding dominators in a flowgraph. +// http://doi.acm.org/10.1145/357062.357071 +// +// We also apply the optimizations to SLT described in Georgiadis et +// al, Finding Dominators in Practice, JGAA 2006, +// http://jgaa.info/accepted/2006/GeorgiadisTarjanWerneck2006.10.1.pdf +// to avoid the need for buckets of size > 1. + +import ( + "bytes" + "fmt" + "io" + "math/big" + "os" + "sort" +) + +// Idom returns the block that immediately dominates b: +// its parent in the dominator tree, if any. +// The entry node (b.Index==0) does not have a parent. +// +func (b *BasicBlock) Idom() *BasicBlock { return b.dom.idom } + +// Dominees returns the list of blocks that b immediately dominates: +// its children in the dominator tree. +// +func (b *BasicBlock) Dominees() []*BasicBlock { return b.dom.children } + +// Dominates reports whether b dominates c. +func (b *BasicBlock) Dominates(c *BasicBlock) bool { + return b.dom.pre <= c.dom.pre && c.dom.post <= b.dom.post +} + +type byDomPreorder []*BasicBlock + +func (a byDomPreorder) Len() int { return len(a) } +func (a byDomPreorder) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a byDomPreorder) Less(i, j int) bool { return a[i].dom.pre < a[j].dom.pre } + +// DomPreorder returns a new slice containing the blocks of f in +// dominator tree preorder. +// +func (f *Function) DomPreorder() []*BasicBlock { + n := len(f.Blocks) + order := make(byDomPreorder, n) + copy(order, f.Blocks) + sort.Sort(order) + return order +} + +// domInfo contains a BasicBlock's dominance information. +type domInfo struct { + idom *BasicBlock // immediate dominator (parent in domtree) + children []*BasicBlock // nodes immediately dominated by this one + pre, post int32 // pre- and post-order numbering within domtree +} + +// buildDomTree computes the dominator tree of f using the LT algorithm. +// Precondition: all blocks are reachable (e.g. optimizeBlocks has been run). +// +func buildDomTree(fn *Function) { + // The step numbers refer to the original LT paper; the + // reordering is due to Georgiadis. + + // Clear any previous domInfo. + for _, b := range fn.Blocks { + b.dom = domInfo{} + } + + idoms := make([]*BasicBlock, len(fn.Blocks)) + + order := make([]*BasicBlock, 0, len(fn.Blocks)) + seen := fn.blockset(0) + var dfs func(b *BasicBlock) + dfs = func(b *BasicBlock) { + if !seen.Add(b) { + return + } + for _, succ := range b.Succs { + dfs(succ) + } + if fn.fakeExits.Has(b) { + dfs(fn.Exit) + } + order = append(order, b) + b.post = len(order) - 1 + } + dfs(fn.Blocks[0]) + + for i := 0; i < len(order)/2; i++ { + o := len(order) - i - 1 + order[i], order[o] = order[o], order[i] + } + + idoms[fn.Blocks[0].Index] = fn.Blocks[0] + changed := true + for changed { + changed = false + // iterate over all nodes in reverse postorder, except for the + // entry node + for _, b := range order[1:] { + var newIdom *BasicBlock + do := func(p *BasicBlock) { + if idoms[p.Index] == nil { + return + } + if newIdom == nil { + newIdom = p + } else { + finger1 := p + finger2 := newIdom + for finger1 != finger2 { + for finger1.post < finger2.post { + finger1 = idoms[finger1.Index] + } + for finger2.post < finger1.post { + finger2 = idoms[finger2.Index] + } + } + newIdom = finger1 + } + } + for _, p := range b.Preds { + do(p) + } + if b == fn.Exit { + for _, p := range fn.Blocks { + if fn.fakeExits.Has(p) { + do(p) + } + } + } + + if idoms[b.Index] != newIdom { + idoms[b.Index] = newIdom + changed = true + } + } + } + + for i, b := range idoms { + fn.Blocks[i].dom.idom = b + if b == nil { + // malformed CFG + continue + } + if i == b.Index { + continue + } + b.dom.children = append(b.dom.children, fn.Blocks[i]) + } + + numberDomTree(fn.Blocks[0], 0, 0) + + // printDomTreeDot(os.Stderr, fn) // debugging + // printDomTreeText(os.Stderr, root, 0) // debugging + + if fn.Prog.mode&SanityCheckFunctions != 0 { + sanityCheckDomTree(fn) + } +} + +// buildPostDomTree is like buildDomTree, but builds the post-dominator tree instead. +func buildPostDomTree(fn *Function) { + // The step numbers refer to the original LT paper; the + // reordering is due to Georgiadis. + + // Clear any previous domInfo. + for _, b := range fn.Blocks { + b.pdom = domInfo{} + } + + idoms := make([]*BasicBlock, len(fn.Blocks)) + + order := make([]*BasicBlock, 0, len(fn.Blocks)) + seen := fn.blockset(0) + var dfs func(b *BasicBlock) + dfs = func(b *BasicBlock) { + if !seen.Add(b) { + return + } + for _, pred := range b.Preds { + dfs(pred) + } + if b == fn.Exit { + for _, p := range fn.Blocks { + if fn.fakeExits.Has(p) { + dfs(p) + } + } + } + order = append(order, b) + b.post = len(order) - 1 + } + dfs(fn.Exit) + + for i := 0; i < len(order)/2; i++ { + o := len(order) - i - 1 + order[i], order[o] = order[o], order[i] + } + + idoms[fn.Exit.Index] = fn.Exit + changed := true + for changed { + changed = false + // iterate over all nodes in reverse postorder, except for the + // exit node + for _, b := range order[1:] { + var newIdom *BasicBlock + do := func(p *BasicBlock) { + if idoms[p.Index] == nil { + return + } + if newIdom == nil { + newIdom = p + } else { + finger1 := p + finger2 := newIdom + for finger1 != finger2 { + for finger1.post < finger2.post { + finger1 = idoms[finger1.Index] + } + for finger2.post < finger1.post { + finger2 = idoms[finger2.Index] + } + } + newIdom = finger1 + } + } + for _, p := range b.Succs { + do(p) + } + if fn.fakeExits.Has(b) { + do(fn.Exit) + } + + if idoms[b.Index] != newIdom { + idoms[b.Index] = newIdom + changed = true + } + } + } + + for i, b := range idoms { + fn.Blocks[i].pdom.idom = b + if b == nil { + // malformed CFG + continue + } + if i == b.Index { + continue + } + b.pdom.children = append(b.pdom.children, fn.Blocks[i]) + } + + numberPostDomTree(fn.Exit, 0, 0) + + // printPostDomTreeDot(os.Stderr, fn) // debugging + // printPostDomTreeText(os.Stderr, fn.Exit, 0) // debugging + + if fn.Prog.mode&SanityCheckFunctions != 0 { // XXX + sanityCheckDomTree(fn) // XXX + } +} + +// numberDomTree sets the pre- and post-order numbers of a depth-first +// traversal of the dominator tree rooted at v. These are used to +// answer dominance queries in constant time. +// +func numberDomTree(v *BasicBlock, pre, post int32) (int32, int32) { + v.dom.pre = pre + pre++ + for _, child := range v.dom.children { + pre, post = numberDomTree(child, pre, post) + } + v.dom.post = post + post++ + return pre, post +} + +// numberPostDomTree sets the pre- and post-order numbers of a depth-first +// traversal of the post-dominator tree rooted at v. These are used to +// answer post-dominance queries in constant time. +// +func numberPostDomTree(v *BasicBlock, pre, post int32) (int32, int32) { + v.pdom.pre = pre + pre++ + for _, child := range v.pdom.children { + pre, post = numberPostDomTree(child, pre, post) + } + v.pdom.post = post + post++ + return pre, post +} + +// Testing utilities ---------------------------------------- + +// sanityCheckDomTree checks the correctness of the dominator tree +// computed by the LT algorithm by comparing against the dominance +// relation computed by a naive Kildall-style forward dataflow +// analysis (Algorithm 10.16 from the "Dragon" book). +// +func sanityCheckDomTree(f *Function) { + n := len(f.Blocks) + + // D[i] is the set of blocks that dominate f.Blocks[i], + // represented as a bit-set of block indices. + D := make([]big.Int, n) + + one := big.NewInt(1) + + // all is the set of all blocks; constant. + var all big.Int + all.Set(one).Lsh(&all, uint(n)).Sub(&all, one) + + // Initialization. + for i := range f.Blocks { + if i == 0 { + // A root is dominated only by itself. + D[i].SetBit(&D[0], 0, 1) + } else { + // All other blocks are (initially) dominated + // by every block. + D[i].Set(&all) + } + } + + // Iteration until fixed point. + for changed := true; changed; { + changed = false + for i, b := range f.Blocks { + if i == 0 { + continue + } + // Compute intersection across predecessors. + var x big.Int + x.Set(&all) + for _, pred := range b.Preds { + x.And(&x, &D[pred.Index]) + } + if b == f.Exit { + for _, p := range f.Blocks { + if f.fakeExits.Has(p) { + x.And(&x, &D[p.Index]) + } + } + } + x.SetBit(&x, i, 1) // a block always dominates itself. + if D[i].Cmp(&x) != 0 { + D[i].Set(&x) + changed = true + } + } + } + + // Check the entire relation. O(n^2). + ok := true + for i := 0; i < n; i++ { + for j := 0; j < n; j++ { + b, c := f.Blocks[i], f.Blocks[j] + actual := b.Dominates(c) + expected := D[j].Bit(i) == 1 + if actual != expected { + fmt.Fprintf(os.Stderr, "dominates(%s, %s)==%t, want %t\n", b, c, actual, expected) + ok = false + } + } + } + + preorder := f.DomPreorder() + for _, b := range f.Blocks { + if got := preorder[b.dom.pre]; got != b { + fmt.Fprintf(os.Stderr, "preorder[%d]==%s, want %s\n", b.dom.pre, got, b) + ok = false + } + } + + if !ok { + panic("sanityCheckDomTree failed for " + f.String()) + } + +} + +// Printing functions ---------------------------------------- + +// printDomTree prints the dominator tree as text, using indentation. +//lint:ignore U1000 used during debugging +func printDomTreeText(buf *bytes.Buffer, v *BasicBlock, indent int) { + fmt.Fprintf(buf, "%*s%s\n", 4*indent, "", v) + for _, child := range v.dom.children { + printDomTreeText(buf, child, indent+1) + } +} + +// printDomTreeDot prints the dominator tree of f in AT&T GraphViz +// (.dot) format. +//lint:ignore U1000 used during debugging +func printDomTreeDot(buf io.Writer, f *Function) { + fmt.Fprintln(buf, "//", f) + fmt.Fprintln(buf, "digraph domtree {") + for i, b := range f.Blocks { + v := b.dom + fmt.Fprintf(buf, "\tn%d [label=\"%s (%d, %d)\",shape=\"rectangle\"];\n", v.pre, b, v.pre, v.post) + // TODO(adonovan): improve appearance of edges + // belonging to both dominator tree and CFG. + + // Dominator tree edge. + if i != 0 { + fmt.Fprintf(buf, "\tn%d -> n%d [style=\"solid\",weight=100];\n", v.idom.dom.pre, v.pre) + } + // CFG edges. + for _, pred := range b.Preds { + fmt.Fprintf(buf, "\tn%d -> n%d [style=\"dotted\",weight=0];\n", pred.dom.pre, v.pre) + } + } + fmt.Fprintln(buf, "}") +} + +// printDomTree prints the dominator tree as text, using indentation. +//lint:ignore U1000 used during debugging +func printPostDomTreeText(buf io.Writer, v *BasicBlock, indent int) { + fmt.Fprintf(buf, "%*s%s\n", 4*indent, "", v) + for _, child := range v.pdom.children { + printPostDomTreeText(buf, child, indent+1) + } +} + +// printDomTreeDot prints the dominator tree of f in AT&T GraphViz +// (.dot) format. +//lint:ignore U1000 used during debugging +func printPostDomTreeDot(buf io.Writer, f *Function) { + fmt.Fprintln(buf, "//", f) + fmt.Fprintln(buf, "digraph pdomtree {") + for _, b := range f.Blocks { + v := b.pdom + fmt.Fprintf(buf, "\tn%d [label=\"%s (%d, %d)\",shape=\"rectangle\"];\n", v.pre, b, v.pre, v.post) + // TODO(adonovan): improve appearance of edges + // belonging to both dominator tree and CFG. + + // Dominator tree edge. + if b != f.Exit { + fmt.Fprintf(buf, "\tn%d -> n%d [style=\"solid\",weight=100];\n", v.idom.pdom.pre, v.pre) + } + // CFG edges. + for _, pred := range b.Preds { + fmt.Fprintf(buf, "\tn%d -> n%d [style=\"dotted\",weight=0];\n", pred.pdom.pre, v.pre) + } + } + fmt.Fprintln(buf, "}") +} diff --git a/vendor/honnef.co/go/tools/ssa/emit.go b/vendor/honnef.co/go/tools/ir/emit.go similarity index 75% rename from vendor/honnef.co/go/tools/ssa/emit.go rename to vendor/honnef.co/go/tools/ir/emit.go index 6bf9ec32dae..5fa137af9ec 100644 --- a/vendor/honnef.co/go/tools/ssa/emit.go +++ b/vendor/honnef.co/go/tools/ir/emit.go @@ -2,13 +2,14 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package ssa +package ir -// Helpers for emitting SSA instructions. +// Helpers for emitting IR instructions. import ( "fmt" "go/ast" + "go/constant" "go/token" "go/types" ) @@ -16,24 +17,32 @@ import ( // emitNew emits to f a new (heap Alloc) instruction allocating an // object of type typ. pos is the optional source location. // -func emitNew(f *Function, typ types.Type, pos token.Pos) *Alloc { +func emitNew(f *Function, typ types.Type, source ast.Node) *Alloc { v := &Alloc{Heap: true} v.setType(types.NewPointer(typ)) - v.setPos(pos) - f.emit(v) + f.emit(v, source) return v } // emitLoad emits to f an instruction to load the address addr into a // new temporary, and returns the value so defined. // -func emitLoad(f *Function, addr Value) *UnOp { - v := &UnOp{Op: token.MUL, X: addr} +func emitLoad(f *Function, addr Value, source ast.Node) *Load { + v := &Load{X: addr} v.setType(deref(addr.Type())) - f.emit(v) + f.emit(v, source) return v } +func emitRecv(f *Function, ch Value, commaOk bool, typ types.Type, source ast.Node) Value { + recv := &Recv{ + Chan: ch, + CommaOk: commaOk, + } + recv.setType(typ) + return f.emit(recv, source) +} + // emitDebugRef emits to f a DebugRef pseudo-instruction associating // expression e with value v. // @@ -61,7 +70,7 @@ func emitDebugRef(f *Function, e ast.Expr, v Value, isAddr bool) { Expr: e, IsAddr: isAddr, object: obj, - }) + }, nil) } // emitArith emits to f code to compute the binary operation op(x, y) @@ -69,19 +78,19 @@ func emitDebugRef(f *Function, e ast.Expr, v Value, isAddr bool) { // (Use emitCompare() for comparisons and Builder.logicalBinop() for // non-eager operations.) // -func emitArith(f *Function, op token.Token, x, y Value, t types.Type, pos token.Pos) Value { +func emitArith(f *Function, op token.Token, x, y Value, t types.Type, source ast.Node) Value { switch op { case token.SHL, token.SHR: - x = emitConv(f, x, t) + x = emitConv(f, x, t, source) // y may be signed or an 'untyped' constant. // TODO(adonovan): whence signed values? if b, ok := y.Type().Underlying().(*types.Basic); ok && b.Info()&types.IsUnsigned == 0 { - y = emitConv(f, y, types.Typ[types.Uint64]) + y = emitConv(f, y, types.Typ[types.Uint64], source) } case token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.AND, token.OR, token.XOR, token.AND_NOT: - x = emitConv(f, x, t) - y = emitConv(f, y, t) + x = emitConv(f, x, t, source) + y = emitConv(f, y, t, source) default: panic("illegal op in emitArith: " + op.String()) @@ -92,15 +101,14 @@ func emitArith(f *Function, op token.Token, x, y Value, t types.Type, pos token. X: x, Y: y, } - v.setPos(pos) v.setType(t) - return f.emit(v) + return f.emit(v, source) } // emitCompare emits to f code compute the boolean result of // comparison comparison 'x op y'. // -func emitCompare(f *Function, op token.Token, x, y Value, pos token.Pos) Value { +func emitCompare(f *Function, op token.Token, x, y Value, source ast.Node) Value { xt := x.Type().Underlying() yt := y.Type().Underlying() @@ -111,7 +119,7 @@ func emitCompare(f *Function, op token.Token, x, y Value, pos token.Pos) Value { // if e==true { ... } // even in the case when e's type is an interface. // TODO(adonovan): opt: generalise to x==true, false!=y, etc. - if x == vTrue && op == token.EQL { + if x, ok := x.(*Const); ok && op == token.EQL && x.Value != nil && x.Value.Kind() == constant.Bool && constant.BoolVal(x.Value) { if yt, ok := yt.(*types.Basic); ok && yt.Info()&types.IsBoolean != 0 { return y } @@ -120,13 +128,13 @@ func emitCompare(f *Function, op token.Token, x, y Value, pos token.Pos) Value { if types.Identical(xt, yt) { // no conversion necessary } else if _, ok := xt.(*types.Interface); ok { - y = emitConv(f, y, x.Type()) + y = emitConv(f, y, x.Type(), source) } else if _, ok := yt.(*types.Interface); ok { - x = emitConv(f, x, y.Type()) + x = emitConv(f, x, y.Type(), source) } else if _, ok := x.(*Const); ok { - x = emitConv(f, x, y.Type()) + x = emitConv(f, x, y.Type(), source) } else if _, ok := y.(*Const); ok { - y = emitConv(f, y, x.Type()) + y = emitConv(f, y, x.Type(), source) //lint:ignore SA9003 no-op } else { // other cases, e.g. channels. No-op. @@ -137,9 +145,8 @@ func emitCompare(f *Function, op token.Token, x, y Value, pos token.Pos) Value { X: x, Y: y, } - v.setPos(pos) v.setType(tBool) - return f.emit(v) + return f.emit(v, source) } // isValuePreserving returns true if a conversion from ut_src to @@ -171,7 +178,7 @@ func isValuePreserving(ut_src, ut_dst types.Type) bool { // by language assignability rules in assignments, parameter passing, // etc. Conversions cannot fail dynamically. // -func emitConv(f *Function, val Value, typ types.Type) Value { +func emitConv(f *Function, val Value, typ types.Type, source ast.Node) Value { t_src := val.Type() // Identical types? Conversion is a no-op. @@ -186,7 +193,7 @@ func emitConv(f *Function, val Value, typ types.Type) Value { if isValuePreserving(ut_src, ut_dst) { c := &ChangeType{X: val} c.setType(typ) - return f.emit(c) + return f.emit(c, source) } // Conversion to, or construction of a value of, an interface type? @@ -195,23 +202,23 @@ func emitConv(f *Function, val Value, typ types.Type) Value { if _, ok := ut_src.(*types.Interface); ok { c := &ChangeInterface{X: val} c.setType(typ) - return f.emit(c) + return f.emit(c, source) } // Untyped nil constant? Return interface-typed nil constant. if ut_src == tUntypedNil { - return nilConst(typ) + return emitConst(f, nilConst(typ)) } // Convert (non-nil) "untyped" literals to their default type. if t, ok := ut_src.(*types.Basic); ok && t.Info()&types.IsUntyped != 0 { - val = emitConv(f, val, DefaultType(ut_src)) + val = emitConv(f, val, types.Default(ut_src), source) } f.Pkg.Prog.needMethodsOf(val.Type()) mi := &MakeInterface{X: val} mi.setType(typ) - return f.emit(mi) + return f.emit(mi, source) } // Conversion of a compile-time constant value? @@ -222,7 +229,7 @@ func emitConv(f *Function, val Value, typ types.Type) Value { // constant of the destination type and // (initially) the same abstract value. // We don't truncate the value yet. - return NewConst(c.Value, typ) + return emitConst(f, NewConst(c.Value, typ)) } // We're converting from constant to non-constant type, @@ -237,7 +244,7 @@ func emitConv(f *Function, val Value, typ types.Type) Value { if ok1 || ok2 { c := &Convert{X: val} c.setType(typ) - return f.emit(c) + return f.emit(c, source) } panic(fmt.Sprintf("in %s: cannot convert %s (%s) to %s", f, val, val.Type(), typ)) @@ -246,72 +253,75 @@ func emitConv(f *Function, val Value, typ types.Type) Value { // emitStore emits to f an instruction to store value val at location // addr, applying implicit conversions as required by assignability rules. // -func emitStore(f *Function, addr, val Value, pos token.Pos) *Store { +func emitStore(f *Function, addr, val Value, source ast.Node) *Store { s := &Store{ Addr: addr, - Val: emitConv(f, val, deref(addr.Type())), - pos: pos, + Val: emitConv(f, val, deref(addr.Type()), source), } - f.emit(s) + // make sure we call getMem after the call to emitConv, which may + // itself update the memory state + f.emit(s, source) return s } // emitJump emits to f a jump to target, and updates the control-flow graph. // Postcondition: f.currentBlock is nil. // -func emitJump(f *Function, target *BasicBlock) { +func emitJump(f *Function, target *BasicBlock, source ast.Node) *Jump { b := f.currentBlock - b.emit(new(Jump)) + j := new(Jump) + b.emit(j, source) addEdge(b, target) f.currentBlock = nil + return j } // emitIf emits to f a conditional jump to tblock or fblock based on // cond, and updates the control-flow graph. // Postcondition: f.currentBlock is nil. // -func emitIf(f *Function, cond Value, tblock, fblock *BasicBlock) { +func emitIf(f *Function, cond Value, tblock, fblock *BasicBlock, source ast.Node) *If { b := f.currentBlock - b.emit(&If{Cond: cond}) + stmt := &If{Cond: cond} + b.emit(stmt, source) addEdge(b, tblock) addEdge(b, fblock) f.currentBlock = nil + return stmt } // emitExtract emits to f an instruction to extract the index'th // component of tuple. It returns the extracted value. // -func emitExtract(f *Function, tuple Value, index int) Value { +func emitExtract(f *Function, tuple Value, index int, source ast.Node) Value { e := &Extract{Tuple: tuple, Index: index} e.setType(tuple.Type().(*types.Tuple).At(index).Type()) - return f.emit(e) + return f.emit(e, source) } // emitTypeAssert emits to f a type assertion value := x.(t) and // returns the value. x.Type() must be an interface. // -func emitTypeAssert(f *Function, x Value, t types.Type, pos token.Pos) Value { +func emitTypeAssert(f *Function, x Value, t types.Type, source ast.Node) Value { a := &TypeAssert{X: x, AssertedType: t} - a.setPos(pos) a.setType(t) - return f.emit(a) + return f.emit(a, source) } // emitTypeTest emits to f a type test value,ok := x.(t) and returns // a (value, ok) tuple. x.Type() must be an interface. // -func emitTypeTest(f *Function, x Value, t types.Type, pos token.Pos) Value { +func emitTypeTest(f *Function, x Value, t types.Type, source ast.Node) Value { a := &TypeAssert{ X: x, AssertedType: t, CommaOk: true, } - a.setPos(pos) a.setType(types.NewTuple( newVar("value", t), varOk, )) - return f.emit(a) + return f.emit(a, source) } // emitTailCall emits to f a function call in tail position. The @@ -320,7 +330,7 @@ func emitTypeTest(f *Function, x Value, t types.Type, pos token.Pos) Value { // Precondition: f does/will not use deferred procedure calls. // Postcondition: f.currentBlock is nil. // -func emitTailCall(f *Function, call *Call) { +func emitTailCall(f *Function, call *Call, source ast.Node) { tresults := f.Signature.Results() nr := tresults.Len() if nr == 1 { @@ -328,7 +338,7 @@ func emitTailCall(f *Function, call *Call) { } else { call.typ = tresults } - tuple := f.emit(call) + tuple := f.emit(call, source) var ret Return switch nr { case 0: @@ -337,7 +347,7 @@ func emitTailCall(f *Function, call *Call) { ret.Results = []Value{tuple} default: for i := 0; i < nr; i++ { - v := emitExtract(f, tuple, i) + v := emitExtract(f, tuple, i, source) // TODO(adonovan): in principle, this is required: // v = emitConv(f, o.Type, f.Signature.Results[i].Type) // but in practice emitTailCall is only used when @@ -345,7 +355,11 @@ func emitTailCall(f *Function, call *Call) { ret.Results = append(ret.Results, v) } } - f.emit(&ret) + + f.Exit = f.newBasicBlock("exit") + emitJump(f, f.Exit, source) + f.currentBlock = f.Exit + f.emit(&ret, source) f.currentBlock = nil } @@ -357,7 +371,7 @@ func emitTailCall(f *Function, call *Call) { // a field; if it is the value of a struct, the result will be the // value of a field. // -func emitImplicitSelections(f *Function, v Value, indices []int) Value { +func emitImplicitSelections(f *Function, v Value, indices []int, source ast.Node) Value { for _, index := range indices { fld := deref(v.Type()).Underlying().(*types.Struct).Field(index) @@ -367,10 +381,10 @@ func emitImplicitSelections(f *Function, v Value, indices []int) Value { Field: index, } instr.setType(types.NewPointer(fld.Type())) - v = f.emit(instr) + v = f.emit(instr, source) // Load the field's value iff indirectly embedded. if isPointer(fld.Type()) { - v = emitLoad(f, v) + v = emitLoad(f, v, source) } } else { instr := &Field{ @@ -378,7 +392,7 @@ func emitImplicitSelections(f *Function, v Value, indices []int) Value { Field: index, } instr.setType(fld.Type()) - v = f.emit(instr) + v = f.emit(instr, source) } } return v @@ -398,21 +412,21 @@ func emitFieldSelection(f *Function, v Value, index int, wantAddr bool, id *ast. X: v, Field: index, } - instr.setPos(id.Pos()) + instr.setSource(id) instr.setType(types.NewPointer(fld.Type())) - v = f.emit(instr) + v = f.emit(instr, id) // Load the field's value iff we don't want its address. if !wantAddr { - v = emitLoad(f, v) + v = emitLoad(f, v, id) } } else { instr := &Field{ X: v, Field: index, } - instr.setPos(id.Pos()) + instr.setSource(id) instr.setType(fld.Type()) - v = f.emit(instr) + v = f.emit(instr, id) } emitDebugRef(f, id, v, wantAddr) return v @@ -421,49 +435,16 @@ func emitFieldSelection(f *Function, v Value, index int, wantAddr bool, id *ast. // zeroValue emits to f code to produce a zero value of type t, // and returns it. // -func zeroValue(f *Function, t types.Type) Value { +func zeroValue(f *Function, t types.Type, source ast.Node) Value { switch t.Underlying().(type) { case *types.Struct, *types.Array: - return emitLoad(f, f.addLocal(t, token.NoPos)) + return emitLoad(f, f.addLocal(t, source), source) default: - return zeroConst(t) + return emitConst(f, zeroConst(t)) } } -// createRecoverBlock emits to f a block of code to return after a -// recovered panic, and sets f.Recover to it. -// -// If f's result parameters are named, the code loads and returns -// their current values, otherwise it returns the zero values of their -// type. -// -// Idempotent. -// -func createRecoverBlock(f *Function) { - if f.Recover != nil { - return // already created - } - saved := f.currentBlock - - f.Recover = f.newBasicBlock("recover") - f.currentBlock = f.Recover - - var results []Value - if f.namedResults != nil { - // Reload NRPs to form value tuple. - for _, r := range f.namedResults { - results = append(results, emitLoad(f, r)) - } - } else { - R := f.Signature.Results() - for i, n := 0, R.Len(); i < n; i++ { - T := R.At(i).Type() - - // Return zero value of each result type. - results = append(results, zeroValue(f, T)) - } - } - f.emit(&Return{Results: results}) - - f.currentBlock = saved +func emitConst(f *Function, c *Const) *Const { + f.consts = append(f.consts, c) + return c } diff --git a/vendor/honnef.co/go/tools/ir/exits.go b/vendor/honnef.co/go/tools/ir/exits.go new file mode 100644 index 00000000000..10cda7bb66e --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/exits.go @@ -0,0 +1,271 @@ +package ir + +import ( + "go/types" +) + +func (b *builder) buildExits(fn *Function) { + if obj := fn.Object(); obj != nil { + switch obj.Pkg().Path() { + case "runtime": + switch obj.Name() { + case "exit": + fn.WillExit = true + return + case "throw": + fn.WillExit = true + return + case "Goexit": + fn.WillUnwind = true + return + } + case "github.com/sirupsen/logrus": + switch obj.(*types.Func).FullName() { + case "(*github.com/sirupsen/logrus.Logger).Exit": + // Technically, this method does not unconditionally exit + // the process. It dynamically calls a function stored in + // the logger. If the function is nil, it defaults to + // os.Exit. + // + // The main intent of this method is to terminate the + // process, and that's what the vast majority of people + // will use it for. We'll happily accept some false + // negatives to avoid a lot of false positives. + fn.WillExit = true + return + case "(*github.com/sirupsen/logrus.Logger).Panic", + "(*github.com/sirupsen/logrus.Logger).Panicf", + "(*github.com/sirupsen/logrus.Logger).Panicln": + + // These methods will always panic, but that's not + // statically known from the code alone, because they + // take a detour through the generic Log methods. + fn.WillUnwind = true + return + case "(*github.com/sirupsen/logrus.Entry).Panicf", + "(*github.com/sirupsen/logrus.Entry).Panicln": + + // Entry.Panic has an explicit panic, but Panicf and + // Panicln do not, relying fully on the generic Log + // method. + fn.WillUnwind = true + return + case "(*github.com/sirupsen/logrus.Logger).Log", + "(*github.com/sirupsen/logrus.Logger).Logf", + "(*github.com/sirupsen/logrus.Logger).Logln": + // TODO(dh): we cannot handle these case. Whether they + // exit or unwind depends on the level, which is set + // via the first argument. We don't currently support + // call-site-specific exit information. + } + } + } + + buildDomTree(fn) + + isRecoverCall := func(instr Instruction) bool { + if instr, ok := instr.(*Call); ok { + if builtin, ok := instr.Call.Value.(*Builtin); ok { + if builtin.Name() == "recover" { + return true + } + } + } + return false + } + + // All panics branch to the exit block, which means that if every + // possible path through the function panics, then all + // predecessors of the exit block must panic. + willPanic := true + for _, pred := range fn.Exit.Preds { + if _, ok := pred.Control().(*Panic); !ok { + willPanic = false + } + } + if willPanic { + recovers := false + recoverLoop: + for _, u := range fn.Blocks { + for _, instr := range u.Instrs { + if instr, ok := instr.(*Defer); ok { + call := instr.Call.StaticCallee() + if call == nil { + // not a static call, so we can't be sure the + // deferred call isn't calling recover + recovers = true + break recoverLoop + } + if len(call.Blocks) == 0 { + // external function, we don't know what's + // happening inside it + // + // TODO(dh): this includes functions from + // imported packages, due to how go/analysis + // works. We could introduce another fact, + // like we've done for exiting and unwinding, + // but it doesn't seem worth it. Virtually all + // uses of recover will be in closures. + recovers = true + break recoverLoop + } + for _, y := range call.Blocks { + for _, instr2 := range y.Instrs { + if isRecoverCall(instr2) { + recovers = true + break recoverLoop + } + } + } + } + } + } + if !recovers { + fn.WillUnwind = true + return + } + } + + // TODO(dh): don't check that any specific call dominates the exit + // block. instead, check that all calls combined cover every + // possible path through the function. + exits := NewBlockSet(len(fn.Blocks)) + unwinds := NewBlockSet(len(fn.Blocks)) + for _, u := range fn.Blocks { + for _, instr := range u.Instrs { + if instr, ok := instr.(CallInstruction); ok { + switch instr.(type) { + case *Defer, *Call: + default: + continue + } + if instr.Common().IsInvoke() { + // give up + return + } + var call *Function + switch instr.Common().Value.(type) { + case *Function, *MakeClosure: + call = instr.Common().StaticCallee() + case *Builtin: + // the only builtins that affect control flow are + // panic and recover, and we've already handled + // those + continue + default: + // dynamic dispatch + return + } + // buildFunction is idempotent. if we're part of a + // (mutually) recursive call chain, then buildFunction + // will immediately return, and fn.WillExit will be false. + if call.Package() == fn.Package() { + b.buildFunction(call) + } + dom := u.Dominates(fn.Exit) + if call.WillExit { + if dom { + fn.WillExit = true + return + } + exits.Add(u) + } else if call.WillUnwind { + if dom { + fn.WillUnwind = true + return + } + unwinds.Add(u) + } + } + } + } + + // depth-first search trying to find a path to the exit block that + // doesn't cross any of the blacklisted blocks + seen := NewBlockSet(len(fn.Blocks)) + var findPath func(root *BasicBlock, bl *BlockSet) bool + findPath = func(root *BasicBlock, bl *BlockSet) bool { + if root == fn.Exit { + return true + } + if seen.Has(root) { + return false + } + if bl.Has(root) { + return false + } + seen.Add(root) + for _, succ := range root.Succs { + if findPath(succ, bl) { + return true + } + } + return false + } + + if exits.Num() > 0 { + if !findPath(fn.Blocks[0], exits) { + fn.WillExit = true + return + } + } + if unwinds.Num() > 0 { + seen.Clear() + if !findPath(fn.Blocks[0], unwinds) { + fn.WillUnwind = true + return + } + } +} + +func (b *builder) addUnreachables(fn *Function) { + for _, bb := range fn.Blocks { + for i, instr := range bb.Instrs { + if instr, ok := instr.(*Call); ok { + var call *Function + switch v := instr.Common().Value.(type) { + case *Function: + call = v + case *MakeClosure: + call = v.Fn.(*Function) + } + if call == nil { + continue + } + if call.Package() == fn.Package() { + // make sure we have information on all functions in this package + b.buildFunction(call) + } + if call.WillExit { + // This call will cause the process to terminate. + // Remove remaining instructions in the block and + // replace any control flow with Unreachable. + for _, succ := range bb.Succs { + succ.removePred(bb) + } + bb.Succs = bb.Succs[:0] + + bb.Instrs = bb.Instrs[:i+1] + bb.emit(new(Unreachable), instr.Source()) + addEdge(bb, fn.Exit) + break + } else if call.WillUnwind { + // This call will cause the goroutine to terminate + // and defers to run (i.e. a panic or + // runtime.Goexit). Remove remaining instructions + // in the block and replace any control flow with + // an unconditional jump to the exit block. + for _, succ := range bb.Succs { + succ.removePred(bb) + } + bb.Succs = bb.Succs[:0] + + bb.Instrs = bb.Instrs[:i+1] + bb.emit(new(Jump), instr.Source()) + addEdge(bb, fn.Exit) + break + } + } + } + } +} diff --git a/vendor/honnef.co/go/tools/ir/func.go b/vendor/honnef.co/go/tools/ir/func.go new file mode 100644 index 00000000000..386d82b6708 --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/func.go @@ -0,0 +1,961 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// This file implements the Function and BasicBlock types. + +import ( + "bytes" + "fmt" + "go/ast" + "go/constant" + "go/format" + "go/token" + "go/types" + "io" + "os" + "strings" +) + +// addEdge adds a control-flow graph edge from from to to. +func addEdge(from, to *BasicBlock) { + from.Succs = append(from.Succs, to) + to.Preds = append(to.Preds, from) +} + +// Control returns the last instruction in the block. +func (b *BasicBlock) Control() Instruction { + if len(b.Instrs) == 0 { + return nil + } + return b.Instrs[len(b.Instrs)-1] +} + +// SIgmaFor returns the sigma node for v coming from pred. +func (b *BasicBlock) SigmaFor(v Value, pred *BasicBlock) *Sigma { + for _, instr := range b.Instrs { + sigma, ok := instr.(*Sigma) + if !ok { + // no more sigmas + return nil + } + if sigma.From == pred && sigma.X == v { + return sigma + } + } + return nil +} + +// Parent returns the function that contains block b. +func (b *BasicBlock) Parent() *Function { return b.parent } + +// String returns a human-readable label of this block. +// It is not guaranteed unique within the function. +// +func (b *BasicBlock) String() string { + return fmt.Sprintf("%d", b.Index) +} + +// emit appends an instruction to the current basic block. +// If the instruction defines a Value, it is returned. +// +func (b *BasicBlock) emit(i Instruction, source ast.Node) Value { + i.setSource(source) + i.setBlock(b) + b.Instrs = append(b.Instrs, i) + v, _ := i.(Value) + return v +} + +// predIndex returns the i such that b.Preds[i] == c or panics if +// there is none. +func (b *BasicBlock) predIndex(c *BasicBlock) int { + for i, pred := range b.Preds { + if pred == c { + return i + } + } + panic(fmt.Sprintf("no edge %s -> %s", c, b)) +} + +// succIndex returns the i such that b.Succs[i] == c or -1 if there is none. +func (b *BasicBlock) succIndex(c *BasicBlock) int { + for i, succ := range b.Succs { + if succ == c { + return i + } + } + return -1 +} + +// hasPhi returns true if b.Instrs contains φ-nodes. +func (b *BasicBlock) hasPhi() bool { + _, ok := b.Instrs[0].(*Phi) + return ok +} + +func (b *BasicBlock) Phis() []Instruction { + return b.phis() +} + +// phis returns the prefix of b.Instrs containing all the block's φ-nodes. +func (b *BasicBlock) phis() []Instruction { + for i, instr := range b.Instrs { + if _, ok := instr.(*Phi); !ok { + return b.Instrs[:i] + } + } + return nil // unreachable in well-formed blocks +} + +// replacePred replaces all occurrences of p in b's predecessor list with q. +// Ordinarily there should be at most one. +// +func (b *BasicBlock) replacePred(p, q *BasicBlock) { + for i, pred := range b.Preds { + if pred == p { + b.Preds[i] = q + } + } +} + +// replaceSucc replaces all occurrences of p in b's successor list with q. +// Ordinarily there should be at most one. +// +func (b *BasicBlock) replaceSucc(p, q *BasicBlock) { + for i, succ := range b.Succs { + if succ == p { + b.Succs[i] = q + } + } +} + +// removePred removes all occurrences of p in b's +// predecessor list and φ-nodes. +// Ordinarily there should be at most one. +// +func (b *BasicBlock) removePred(p *BasicBlock) { + phis := b.phis() + + // We must preserve edge order for φ-nodes. + j := 0 + for i, pred := range b.Preds { + if pred != p { + b.Preds[j] = b.Preds[i] + // Strike out φ-edge too. + for _, instr := range phis { + phi := instr.(*Phi) + phi.Edges[j] = phi.Edges[i] + } + j++ + } + } + // Nil out b.Preds[j:] and φ-edges[j:] to aid GC. + for i := j; i < len(b.Preds); i++ { + b.Preds[i] = nil + for _, instr := range phis { + instr.(*Phi).Edges[i] = nil + } + } + b.Preds = b.Preds[:j] + for _, instr := range phis { + phi := instr.(*Phi) + phi.Edges = phi.Edges[:j] + } +} + +// Destinations associated with unlabelled for/switch/select stmts. +// We push/pop one of these as we enter/leave each construct and for +// each BranchStmt we scan for the innermost target of the right type. +// +type targets struct { + tail *targets // rest of stack + _break *BasicBlock + _continue *BasicBlock + _fallthrough *BasicBlock +} + +// Destinations associated with a labelled block. +// We populate these as labels are encountered in forward gotos or +// labelled statements. +// +type lblock struct { + _goto *BasicBlock + _break *BasicBlock + _continue *BasicBlock +} + +// labelledBlock returns the branch target associated with the +// specified label, creating it if needed. +// +func (f *Function) labelledBlock(label *ast.Ident) *lblock { + lb := f.lblocks[label.Obj] + if lb == nil { + lb = &lblock{_goto: f.newBasicBlock(label.Name)} + if f.lblocks == nil { + f.lblocks = make(map[*ast.Object]*lblock) + } + f.lblocks[label.Obj] = lb + } + return lb +} + +// addParam adds a (non-escaping) parameter to f.Params of the +// specified name, type and source position. +// +func (f *Function) addParam(name string, typ types.Type, source ast.Node) *Parameter { + var b *BasicBlock + if len(f.Blocks) > 0 { + b = f.Blocks[0] + } + v := &Parameter{ + name: name, + } + v.setBlock(b) + v.setType(typ) + v.setSource(source) + f.Params = append(f.Params, v) + if b != nil { + // There may be no blocks if this function has no body. We + // still create params, but aren't interested in the + // instruction. + f.Blocks[0].Instrs = append(f.Blocks[0].Instrs, v) + } + return v +} + +func (f *Function) addParamObj(obj types.Object, source ast.Node) *Parameter { + name := obj.Name() + if name == "" { + name = fmt.Sprintf("arg%d", len(f.Params)) + } + param := f.addParam(name, obj.Type(), source) + param.object = obj + return param +} + +// addSpilledParam declares a parameter that is pre-spilled to the +// stack; the function body will load/store the spilled location. +// Subsequent lifting will eliminate spills where possible. +// +func (f *Function) addSpilledParam(obj types.Object, source ast.Node) { + param := f.addParamObj(obj, source) + spill := &Alloc{} + spill.setType(types.NewPointer(obj.Type())) + spill.source = source + f.objects[obj] = spill + f.Locals = append(f.Locals, spill) + f.emit(spill, source) + emitStore(f, spill, param, source) + // f.emit(&Store{Addr: spill, Val: param}) +} + +// startBody initializes the function prior to generating IR code for its body. +// Precondition: f.Type() already set. +// +func (f *Function) startBody() { + entry := f.newBasicBlock("entry") + f.currentBlock = entry + f.objects = make(map[types.Object]Value) // needed for some synthetics, e.g. init +} + +func (f *Function) blockset(i int) *BlockSet { + bs := &f.blocksets[i] + if len(bs.values) != len(f.Blocks) { + if cap(bs.values) >= len(f.Blocks) { + bs.values = bs.values[:len(f.Blocks)] + bs.Clear() + } else { + bs.values = make([]bool, len(f.Blocks)) + } + } else { + bs.Clear() + } + return bs +} + +func (f *Function) exitBlock() { + old := f.currentBlock + + f.Exit = f.newBasicBlock("exit") + f.currentBlock = f.Exit + + ret := f.results() + results := make([]Value, len(ret)) + // Run function calls deferred in this + // function when explicitly returning from it. + f.emit(new(RunDefers), nil) + for i, r := range ret { + results[i] = emitLoad(f, r, nil) + } + + f.emit(&Return{Results: results}, nil) + f.currentBlock = old +} + +// createSyntacticParams populates f.Params and generates code (spills +// and named result locals) for all the parameters declared in the +// syntax. In addition it populates the f.objects mapping. +// +// Preconditions: +// f.startBody() was called. +// Postcondition: +// len(f.Params) == len(f.Signature.Params) + (f.Signature.Recv() ? 1 : 0) +// +func (f *Function) createSyntacticParams(recv *ast.FieldList, functype *ast.FuncType) { + // Receiver (at most one inner iteration). + if recv != nil { + for _, field := range recv.List { + for _, n := range field.Names { + f.addSpilledParam(f.Pkg.info.Defs[n], n) + } + // Anonymous receiver? No need to spill. + if field.Names == nil { + f.addParamObj(f.Signature.Recv(), field) + } + } + } + + // Parameters. + if functype.Params != nil { + n := len(f.Params) // 1 if has recv, 0 otherwise + for _, field := range functype.Params.List { + for _, n := range field.Names { + f.addSpilledParam(f.Pkg.info.Defs[n], n) + } + // Anonymous parameter? No need to spill. + if field.Names == nil { + f.addParamObj(f.Signature.Params().At(len(f.Params)-n), field) + } + } + } + + // Named results. + if functype.Results != nil { + for _, field := range functype.Results.List { + // Implicit "var" decl of locals for named results. + for _, n := range field.Names { + f.namedResults = append(f.namedResults, f.addLocalForIdent(n)) + } + } + + if len(f.namedResults) == 0 { + sig := f.Signature.Results() + for i := 0; i < sig.Len(); i++ { + // XXX position information + v := f.addLocal(sig.At(i).Type(), nil) + f.implicitResults = append(f.implicitResults, v) + } + } + } +} + +func numberNodes(f *Function) { + var base ID + for _, b := range f.Blocks { + for _, instr := range b.Instrs { + if instr == nil { + continue + } + base++ + instr.setID(base) + } + } +} + +// buildReferrers populates the def/use information in all non-nil +// Value.Referrers slice. +// Precondition: all such slices are initially empty. +func buildReferrers(f *Function) { + var rands []*Value + for _, b := range f.Blocks { + for _, instr := range b.Instrs { + rands = instr.Operands(rands[:0]) // recycle storage + for _, rand := range rands { + if r := *rand; r != nil { + if ref := r.Referrers(); ref != nil { + *ref = append(*ref, instr) + } + } + } + } + } +} + +func (f *Function) emitConsts() { + if len(f.Blocks) == 0 { + f.consts = nil + return + } + + // TODO(dh): our deduplication only works on booleans and + // integers. other constants are represented as pointers to + // things. + if len(f.consts) == 0 { + return + } else if len(f.consts) <= 32 { + f.emitConstsFew() + } else { + f.emitConstsMany() + } +} + +func (f *Function) emitConstsFew() { + dedup := make([]*Const, 0, 32) + for _, c := range f.consts { + if len(*c.Referrers()) == 0 { + continue + } + found := false + for _, d := range dedup { + if c.typ == d.typ && c.Value == d.Value { + replaceAll(c, d) + found = true + break + } + } + if !found { + dedup = append(dedup, c) + } + } + + instrs := make([]Instruction, len(f.Blocks[0].Instrs)+len(dedup)) + for i, c := range dedup { + instrs[i] = c + c.setBlock(f.Blocks[0]) + } + copy(instrs[len(dedup):], f.Blocks[0].Instrs) + f.Blocks[0].Instrs = instrs + f.consts = nil +} + +func (f *Function) emitConstsMany() { + type constKey struct { + typ types.Type + value constant.Value + } + + m := make(map[constKey]Value, len(f.consts)) + areNil := 0 + for i, c := range f.consts { + if len(*c.Referrers()) == 0 { + f.consts[i] = nil + areNil++ + continue + } + + k := constKey{ + typ: c.typ, + value: c.Value, + } + if dup, ok := m[k]; !ok { + m[k] = c + } else { + f.consts[i] = nil + areNil++ + replaceAll(c, dup) + } + } + + instrs := make([]Instruction, len(f.Blocks[0].Instrs)+len(f.consts)-areNil) + i := 0 + for _, c := range f.consts { + if c != nil { + instrs[i] = c + c.setBlock(f.Blocks[0]) + i++ + } + } + copy(instrs[i:], f.Blocks[0].Instrs) + f.Blocks[0].Instrs = instrs + f.consts = nil +} + +// buildFakeExits ensures that every block in the function is +// reachable in reverse from the Exit block. This is required to build +// a full post-dominator tree, and to ensure the exit block's +// inclusion in the dominator tree. +func buildFakeExits(fn *Function) { + // Find back-edges via forward DFS + fn.fakeExits = BlockSet{values: make([]bool, len(fn.Blocks))} + seen := fn.blockset(0) + backEdges := fn.blockset(1) + + var dfs func(b *BasicBlock) + dfs = func(b *BasicBlock) { + if !seen.Add(b) { + backEdges.Add(b) + return + } + for _, pred := range b.Succs { + dfs(pred) + } + } + dfs(fn.Blocks[0]) +buildLoop: + for { + seen := fn.blockset(2) + var dfs func(b *BasicBlock) + dfs = func(b *BasicBlock) { + if !seen.Add(b) { + return + } + for _, pred := range b.Preds { + dfs(pred) + } + if b == fn.Exit { + for _, b := range fn.Blocks { + if fn.fakeExits.Has(b) { + dfs(b) + } + } + } + } + dfs(fn.Exit) + + for _, b := range fn.Blocks { + if !seen.Has(b) && backEdges.Has(b) { + // Block b is not reachable from the exit block. Add a + // fake jump from b to exit, then try again. Note that we + // only add one fake edge at a time, as it may make + // multiple blocks reachable. + // + // We only consider those blocks that have back edges. + // Any unreachable block that doesn't have a back edge + // must flow into a loop, which by definition has a + // back edge. Thus, by looking for loops, we should + // need fewer fake edges overall. + fn.fakeExits.Add(b) + continue buildLoop + } + } + + break + } +} + +// finishBody() finalizes the function after IR code generation of its body. +func (f *Function) finishBody() { + f.objects = nil + f.currentBlock = nil + f.lblocks = nil + + // Remove from f.Locals any Allocs that escape to the heap. + j := 0 + for _, l := range f.Locals { + if !l.Heap { + f.Locals[j] = l + j++ + } + } + // Nil out f.Locals[j:] to aid GC. + for i := j; i < len(f.Locals); i++ { + f.Locals[i] = nil + } + f.Locals = f.Locals[:j] + + optimizeBlocks(f) + buildReferrers(f) + buildDomTree(f) + buildPostDomTree(f) + + if f.Prog.mode&NaiveForm == 0 { + lift(f) + } + + // emit constants after lifting, because lifting may produce new constants. + f.emitConsts() + + f.namedResults = nil // (used by lifting) + f.implicitResults = nil + + numberNodes(f) + + defer f.wr.Close() + f.wr.WriteFunc("start", "start", f) + + if f.Prog.mode&PrintFunctions != 0 { + printMu.Lock() + f.WriteTo(os.Stdout) + printMu.Unlock() + } + + if f.Prog.mode&SanityCheckFunctions != 0 { + mustSanityCheck(f, nil) + } +} + +func isUselessPhi(phi *Phi) (Value, bool) { + var v0 Value + for _, e := range phi.Edges { + if e == phi { + continue + } + if v0 == nil { + v0 = e + } + if v0 != e { + if v0, ok := v0.(*Const); ok { + if e, ok := e.(*Const); ok { + if v0.typ == e.typ && v0.Value == e.Value { + continue + } + } + } + return nil, false + } + } + return v0, true +} + +func (f *Function) RemoveNilBlocks() { + f.removeNilBlocks() +} + +// removeNilBlocks eliminates nils from f.Blocks and updates each +// BasicBlock.Index. Use this after any pass that may delete blocks. +// +func (f *Function) removeNilBlocks() { + j := 0 + for _, b := range f.Blocks { + if b != nil { + b.Index = j + f.Blocks[j] = b + j++ + } + } + // Nil out f.Blocks[j:] to aid GC. + for i := j; i < len(f.Blocks); i++ { + f.Blocks[i] = nil + } + f.Blocks = f.Blocks[:j] +} + +// SetDebugMode sets the debug mode for package pkg. If true, all its +// functions will include full debug info. This greatly increases the +// size of the instruction stream, and causes Functions to depend upon +// the ASTs, potentially keeping them live in memory for longer. +// +func (pkg *Package) SetDebugMode(debug bool) { + // TODO(adonovan): do we want ast.File granularity? + pkg.debug = debug +} + +// debugInfo reports whether debug info is wanted for this function. +func (f *Function) debugInfo() bool { + return f.Pkg != nil && f.Pkg.debug +} + +// addNamedLocal creates a local variable, adds it to function f and +// returns it. Its name and type are taken from obj. Subsequent +// calls to f.lookup(obj) will return the same local. +// +func (f *Function) addNamedLocal(obj types.Object, source ast.Node) *Alloc { + l := f.addLocal(obj.Type(), source) + f.objects[obj] = l + return l +} + +func (f *Function) addLocalForIdent(id *ast.Ident) *Alloc { + return f.addNamedLocal(f.Pkg.info.Defs[id], id) +} + +// addLocal creates an anonymous local variable of type typ, adds it +// to function f and returns it. pos is the optional source location. +// +func (f *Function) addLocal(typ types.Type, source ast.Node) *Alloc { + v := &Alloc{} + v.setType(types.NewPointer(typ)) + f.Locals = append(f.Locals, v) + f.emit(v, source) + return v +} + +// lookup returns the address of the named variable identified by obj +// that is local to function f or one of its enclosing functions. +// If escaping, the reference comes from a potentially escaping pointer +// expression and the referent must be heap-allocated. +// +func (f *Function) lookup(obj types.Object, escaping bool) Value { + if v, ok := f.objects[obj]; ok { + if alloc, ok := v.(*Alloc); ok && escaping { + alloc.Heap = true + } + return v // function-local var (address) + } + + // Definition must be in an enclosing function; + // plumb it through intervening closures. + if f.parent == nil { + panic("no ir.Value for " + obj.String()) + } + outer := f.parent.lookup(obj, true) // escaping + v := &FreeVar{ + name: obj.Name(), + typ: outer.Type(), + outer: outer, + parent: f, + } + f.objects[obj] = v + f.FreeVars = append(f.FreeVars, v) + return v +} + +// emit emits the specified instruction to function f. +func (f *Function) emit(instr Instruction, source ast.Node) Value { + return f.currentBlock.emit(instr, source) +} + +// RelString returns the full name of this function, qualified by +// package name, receiver type, etc. +// +// The specific formatting rules are not guaranteed and may change. +// +// Examples: +// "math.IsNaN" // a package-level function +// "(*bytes.Buffer).Bytes" // a declared method or a wrapper +// "(*bytes.Buffer).Bytes$thunk" // thunk (func wrapping method; receiver is param 0) +// "(*bytes.Buffer).Bytes$bound" // bound (func wrapping method; receiver supplied by closure) +// "main.main$1" // an anonymous function in main +// "main.init#1" // a declared init function +// "main.init" // the synthesized package initializer +// +// When these functions are referred to from within the same package +// (i.e. from == f.Pkg.Object), they are rendered without the package path. +// For example: "IsNaN", "(*Buffer).Bytes", etc. +// +// All non-synthetic functions have distinct package-qualified names. +// (But two methods may have the same name "(T).f" if one is a synthetic +// wrapper promoting a non-exported method "f" from another package; in +// that case, the strings are equal but the identifiers "f" are distinct.) +// +func (f *Function) RelString(from *types.Package) string { + // Anonymous? + if f.parent != nil { + // An anonymous function's Name() looks like "parentName$1", + // but its String() should include the type/package/etc. + parent := f.parent.RelString(from) + for i, anon := range f.parent.AnonFuncs { + if anon == f { + return fmt.Sprintf("%s$%d", parent, 1+i) + } + } + + return f.name // should never happen + } + + // Method (declared or wrapper)? + if recv := f.Signature.Recv(); recv != nil { + return f.relMethod(from, recv.Type()) + } + + // Thunk? + if f.method != nil { + return f.relMethod(from, f.method.Recv()) + } + + // Bound? + if len(f.FreeVars) == 1 && strings.HasSuffix(f.name, "$bound") { + return f.relMethod(from, f.FreeVars[0].Type()) + } + + // Package-level function? + // Prefix with package name for cross-package references only. + if p := f.pkg(); p != nil && p != from { + return fmt.Sprintf("%s.%s", p.Path(), f.name) + } + + // Unknown. + return f.name +} + +func (f *Function) relMethod(from *types.Package, recv types.Type) string { + return fmt.Sprintf("(%s).%s", relType(recv, from), f.name) +} + +// writeSignature writes to buf the signature sig in declaration syntax. +func writeSignature(buf *bytes.Buffer, from *types.Package, name string, sig *types.Signature, params []*Parameter) { + buf.WriteString("func ") + if recv := sig.Recv(); recv != nil { + buf.WriteString("(") + if n := params[0].Name(); n != "" { + buf.WriteString(n) + buf.WriteString(" ") + } + types.WriteType(buf, params[0].Type(), types.RelativeTo(from)) + buf.WriteString(") ") + } + buf.WriteString(name) + types.WriteSignature(buf, sig, types.RelativeTo(from)) +} + +func (f *Function) pkg() *types.Package { + if f.Pkg != nil { + return f.Pkg.Pkg + } + return nil +} + +var _ io.WriterTo = (*Function)(nil) // *Function implements io.Writer + +func (f *Function) WriteTo(w io.Writer) (int64, error) { + var buf bytes.Buffer + WriteFunction(&buf, f) + n, err := w.Write(buf.Bytes()) + return int64(n), err +} + +// WriteFunction writes to buf a human-readable "disassembly" of f. +func WriteFunction(buf *bytes.Buffer, f *Function) { + fmt.Fprintf(buf, "# Name: %s\n", f.String()) + if f.Pkg != nil { + fmt.Fprintf(buf, "# Package: %s\n", f.Pkg.Pkg.Path()) + } + if syn := f.Synthetic; syn != "" { + fmt.Fprintln(buf, "# Synthetic:", syn) + } + if pos := f.Pos(); pos.IsValid() { + fmt.Fprintf(buf, "# Location: %s\n", f.Prog.Fset.Position(pos)) + } + + if f.parent != nil { + fmt.Fprintf(buf, "# Parent: %s\n", f.parent.Name()) + } + + from := f.pkg() + + if f.FreeVars != nil { + buf.WriteString("# Free variables:\n") + for i, fv := range f.FreeVars { + fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, fv.Name(), relType(fv.Type(), from)) + } + } + + if len(f.Locals) > 0 { + buf.WriteString("# Locals:\n") + for i, l := range f.Locals { + fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, l.Name(), relType(deref(l.Type()), from)) + } + } + writeSignature(buf, from, f.Name(), f.Signature, f.Params) + buf.WriteString(":\n") + + if f.Blocks == nil { + buf.WriteString("\t(external)\n") + } + + for _, b := range f.Blocks { + if b == nil { + // Corrupt CFG. + fmt.Fprintf(buf, ".nil:\n") + continue + } + fmt.Fprintf(buf, "b%d:", b.Index) + if len(b.Preds) > 0 { + fmt.Fprint(buf, " ←") + for _, pred := range b.Preds { + fmt.Fprintf(buf, " b%d", pred.Index) + } + } + if b.Comment != "" { + fmt.Fprintf(buf, " # %s", b.Comment) + } + buf.WriteByte('\n') + + if false { // CFG debugging + fmt.Fprintf(buf, "\t# CFG: %s --> %s --> %s\n", b.Preds, b, b.Succs) + } + + buf2 := &bytes.Buffer{} + for _, instr := range b.Instrs { + buf.WriteString("\t") + switch v := instr.(type) { + case Value: + // Left-align the instruction. + if name := v.Name(); name != "" { + fmt.Fprintf(buf, "%s = ", name) + } + buf.WriteString(instr.String()) + case nil: + // Be robust against bad transforms. + buf.WriteString("") + default: + buf.WriteString(instr.String()) + } + buf.WriteString("\n") + + if f.Prog.mode&PrintSource != 0 { + if s := instr.Source(); s != nil { + buf2.Reset() + format.Node(buf2, f.Prog.Fset, s) + for { + line, err := buf2.ReadString('\n') + if len(line) == 0 { + break + } + buf.WriteString("\t\t> ") + buf.WriteString(line) + if line[len(line)-1] != '\n' { + buf.WriteString("\n") + } + if err != nil { + break + } + } + } + } + } + buf.WriteString("\n") + } +} + +// newBasicBlock adds to f a new basic block and returns it. It does +// not automatically become the current block for subsequent calls to emit. +// comment is an optional string for more readable debugging output. +// +func (f *Function) newBasicBlock(comment string) *BasicBlock { + b := &BasicBlock{ + Index: len(f.Blocks), + Comment: comment, + parent: f, + } + b.Succs = b.succs2[:0] + f.Blocks = append(f.Blocks, b) + return b +} + +// NewFunction returns a new synthetic Function instance belonging to +// prog, with its name and signature fields set as specified. +// +// The caller is responsible for initializing the remaining fields of +// the function object, e.g. Pkg, Params, Blocks. +// +// It is practically impossible for clients to construct well-formed +// IR functions/packages/programs directly, so we assume this is the +// job of the Builder alone. NewFunction exists to provide clients a +// little flexibility. For example, analysis tools may wish to +// construct fake Functions for the root of the callgraph, a fake +// "reflect" package, etc. +// +// TODO(adonovan): think harder about the API here. +// +func (prog *Program) NewFunction(name string, sig *types.Signature, provenance string) *Function { + return &Function{Prog: prog, name: name, Signature: sig, Synthetic: provenance} +} + +//lint:ignore U1000 we may make use of this for functions loaded from export data +type extentNode [2]token.Pos + +func (n extentNode) Pos() token.Pos { return n[0] } +func (n extentNode) End() token.Pos { return n[1] } + +func (f *Function) initHTML(name string) { + if name == "" { + return + } + if rel := f.RelString(nil); rel == name { + f.wr = NewHTMLWriter("ir.html", rel, "") + } +} diff --git a/vendor/honnef.co/go/tools/ir/html.go b/vendor/honnef.co/go/tools/ir/html.go new file mode 100644 index 00000000000..c18375333a9 --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/html.go @@ -0,0 +1,1124 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Copyright 2019 Dominik Honnef. All rights reserved. + +package ir + +import ( + "bytes" + "fmt" + "go/types" + "html" + "io" + "log" + "os" + "os/exec" + "path/filepath" + "reflect" + "sort" + "strings" +) + +func live(f *Function) []bool { + max := 0 + var ops []*Value + + for _, b := range f.Blocks { + for _, instr := range b.Instrs { + if int(instr.ID()) > max { + max = int(instr.ID()) + } + } + } + + out := make([]bool, max+1) + var q []Node + for _, b := range f.Blocks { + for _, instr := range b.Instrs { + switch instr.(type) { + case *BlankStore, *Call, *ConstantSwitch, *Defer, *Go, *If, *Jump, *MapUpdate, *Next, *Panic, *Recv, *Return, *RunDefers, *Send, *Store, *Unreachable: + out[instr.ID()] = true + q = append(q, instr) + } + } + } + + for len(q) > 0 { + v := q[len(q)-1] + q = q[:len(q)-1] + for _, op := range v.Operands(ops) { + if *op == nil { + continue + } + if !out[(*op).ID()] { + out[(*op).ID()] = true + q = append(q, *op) + } + } + } + + return out +} + +type funcPrinter interface { + startBlock(b *BasicBlock, reachable bool) + endBlock(b *BasicBlock) + value(v Node, live bool) + startDepCycle() + endDepCycle() + named(n string, vals []Value) +} + +func namedValues(f *Function) map[types.Object][]Value { + names := map[types.Object][]Value{} + for _, b := range f.Blocks { + for _, instr := range b.Instrs { + if instr, ok := instr.(*DebugRef); ok { + if obj := instr.object; obj != nil { + names[obj] = append(names[obj], instr.X) + } + } + } + } + // XXX deduplicate values + return names +} + +func fprintFunc(p funcPrinter, f *Function) { + // XXX does our IR form preserve unreachable blocks? + // reachable, live := findlive(f) + + l := live(f) + for _, b := range f.Blocks { + // XXX + // p.startBlock(b, reachable[b.Index]) + p.startBlock(b, true) + + end := len(b.Instrs) - 1 + if end < 0 { + end = 0 + } + for _, v := range b.Instrs[:end] { + if _, ok := v.(*DebugRef); !ok { + p.value(v, l[v.ID()]) + } + } + p.endBlock(b) + } + + names := namedValues(f) + keys := make([]types.Object, 0, len(names)) + for key := range names { + keys = append(keys, key) + } + sort.Slice(keys, func(i, j int) bool { + return keys[i].Pos() < keys[j].Pos() + }) + for _, key := range keys { + p.named(key.Name(), names[key]) + } +} + +func opName(v Node) string { + switch v := v.(type) { + case *Call: + if v.Common().IsInvoke() { + return "Invoke" + } + return "Call" + case *Alloc: + if v.Heap { + return "HeapAlloc" + } + return "StackAlloc" + case *Select: + if v.Blocking { + return "SelectBlocking" + } + return "SelectNonBlocking" + default: + return reflect.ValueOf(v).Type().Elem().Name() + } +} + +type HTMLWriter struct { + w io.WriteCloser + path string + dot *dotWriter +} + +func NewHTMLWriter(path string, funcname, cfgMask string) *HTMLWriter { + out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) + if err != nil { + log.Fatalf("%v", err) + } + pwd, err := os.Getwd() + if err != nil { + log.Fatalf("%v", err) + } + html := HTMLWriter{w: out, path: filepath.Join(pwd, path)} + html.dot = newDotWriter() + html.start(funcname) + return &html +} + +func (w *HTMLWriter) start(name string) { + if w == nil { + return + } + w.WriteString("") + w.WriteString(` + + + + + +`) + w.WriteString("") + w.WriteString("

") + w.WriteString(html.EscapeString(name)) + w.WriteString("

") + w.WriteString(` +help +
+ +

+Click on a value or block to toggle highlighting of that value/block +and its uses. (Values and blocks are highlighted by ID, and IDs of +dead items may be reused, so not all highlights necessarily correspond +to the clicked item.) +

+ +

+Faded out values and blocks are dead code that has not been eliminated. +

+ +

+Values printed in italics have a dependency cycle. +

+ +

+CFG: Dashed edge is for unlikely branches. Blue color is for backward edges. +Edge with a dot means that this edge follows the order in which blocks were laidout. +

+ +
+`) + w.WriteString("") + w.WriteString("") +} + +func (w *HTMLWriter) Close() { + if w == nil { + return + } + io.WriteString(w.w, "") + io.WriteString(w.w, "
") + io.WriteString(w.w, "") + io.WriteString(w.w, "") + w.w.Close() + fmt.Printf("dumped IR to %v\n", w.path) +} + +// WriteFunc writes f in a column headed by title. +// phase is used for collapsing columns and should be unique across the table. +func (w *HTMLWriter) WriteFunc(phase, title string, f *Function) { + if w == nil { + return + } + w.WriteColumn(phase, title, "", funcHTML(f, phase, w.dot)) +} + +// WriteColumn writes raw HTML in a column headed by title. +// It is intended for pre- and post-compilation log output. +func (w *HTMLWriter) WriteColumn(phase, title, class, html string) { + if w == nil { + return + } + id := strings.Replace(phase, " ", "-", -1) + // collapsed column + w.Printf("
%v
", id, phase) + + if class == "" { + w.Printf("", id) + } else { + w.Printf("", id, class) + } + w.WriteString("

" + title + "

") + w.WriteString(html) + w.WriteString("") +} + +func (w *HTMLWriter) Printf(msg string, v ...interface{}) { + if _, err := fmt.Fprintf(w.w, msg, v...); err != nil { + log.Fatalf("%v", err) + } +} + +func (w *HTMLWriter) WriteString(s string) { + if _, err := io.WriteString(w.w, s); err != nil { + log.Fatalf("%v", err) + } +} + +func valueHTML(v Node) string { + if v == nil { + return "<nil>" + } + // TODO: Using the value ID as the class ignores the fact + // that value IDs get recycled and that some values + // are transmuted into other values. + class := fmt.Sprintf("t%d", v.ID()) + var label string + switch v := v.(type) { + case *Function: + label = v.RelString(nil) + case *Builtin: + label = v.Name() + default: + label = class + } + return fmt.Sprintf("%s", class, label) +} + +func valueLongHTML(v Node) string { + // TODO: Any intra-value formatting? + // I'm wary of adding too much visual noise, + // but a little bit might be valuable. + // We already have visual noise in the form of punctuation + // maybe we could replace some of that with formatting. + s := fmt.Sprintf("", v.ID()) + + linenumber := "(?)" + if v.Pos().IsValid() { + line := v.Parent().Prog.Fset.Position(v.Pos()).Line + linenumber = fmt.Sprintf("(%d)", line, line) + } + + s += fmt.Sprintf("%s %s = %s", valueHTML(v), linenumber, opName(v)) + + if v, ok := v.(Value); ok { + s += " <" + html.EscapeString(v.Type().String()) + ">" + } + + switch v := v.(type) { + case *Parameter: + s += fmt.Sprintf(" {%s}", html.EscapeString(v.name)) + case *BinOp: + s += fmt.Sprintf(" {%s}", html.EscapeString(v.Op.String())) + case *UnOp: + s += fmt.Sprintf(" {%s}", html.EscapeString(v.Op.String())) + case *Extract: + name := v.Tuple.Type().(*types.Tuple).At(v.Index).Name() + s += fmt.Sprintf(" [%d] (%s)", v.Index, name) + case *Field: + st := v.X.Type().Underlying().(*types.Struct) + // Be robust against a bad index. + name := "?" + if 0 <= v.Field && v.Field < st.NumFields() { + name = st.Field(v.Field).Name() + } + s += fmt.Sprintf(" [%d] (%s)", v.Field, name) + case *FieldAddr: + st := deref(v.X.Type()).Underlying().(*types.Struct) + // Be robust against a bad index. + name := "?" + if 0 <= v.Field && v.Field < st.NumFields() { + name = st.Field(v.Field).Name() + } + + s += fmt.Sprintf(" [%d] (%s)", v.Field, name) + case *Recv: + s += fmt.Sprintf(" {%t}", v.CommaOk) + case *Call: + if v.Common().IsInvoke() { + s += fmt.Sprintf(" {%s}", html.EscapeString(v.Common().Method.FullName())) + } + case *Const: + if v.Value == nil { + s += " {<nil>}" + } else { + s += fmt.Sprintf(" {%s}", html.EscapeString(v.Value.String())) + } + case *Sigma: + s += fmt.Sprintf(" [#%s]", v.From) + } + for _, a := range v.Operands(nil) { + s += fmt.Sprintf(" %s", valueHTML(*a)) + } + + // OPT(dh): we're calling namedValues many times on the same function. + allNames := namedValues(v.Parent()) + var names []string + for name, values := range allNames { + for _, value := range values { + if v == value { + names = append(names, name.Name()) + break + } + } + } + if len(names) != 0 { + s += " (" + strings.Join(names, ", ") + ")" + } + + s += "" + return s +} + +func blockHTML(b *BasicBlock) string { + // TODO: Using the value ID as the class ignores the fact + // that value IDs get recycled and that some values + // are transmuted into other values. + s := html.EscapeString(b.String()) + return fmt.Sprintf("%s", s, s) +} + +func blockLongHTML(b *BasicBlock) string { + var kind string + var term Instruction + if len(b.Instrs) > 0 { + term = b.Control() + kind = opName(term) + } + // TODO: improve this for HTML? + s := fmt.Sprintf("%s", b.Index, kind) + + if term != nil { + ops := term.Operands(nil) + if len(ops) > 0 { + var ss []string + for _, op := range ops { + ss = append(ss, valueHTML(*op)) + } + s += " " + strings.Join(ss, ", ") + } + } + if len(b.Succs) > 0 { + s += " →" // right arrow + for _, c := range b.Succs { + s += " " + blockHTML(c) + } + } + return s +} + +func funcHTML(f *Function, phase string, dot *dotWriter) string { + buf := new(bytes.Buffer) + if dot != nil { + dot.writeFuncSVG(buf, phase, f) + } + fmt.Fprint(buf, "") + p := htmlFuncPrinter{w: buf} + fprintFunc(p, f) + + // fprintFunc(&buf, f) // TODO: HTML, not text,
for line breaks, etc. + fmt.Fprint(buf, "
") + return buf.String() +} + +type htmlFuncPrinter struct { + w io.Writer +} + +func (p htmlFuncPrinter) startBlock(b *BasicBlock, reachable bool) { + var dead string + if !reachable { + dead = "dead-block" + } + fmt.Fprintf(p.w, "
    ", b, dead) + fmt.Fprintf(p.w, "
  • %s:", blockHTML(b)) + if len(b.Preds) > 0 { + io.WriteString(p.w, " ←") // left arrow + for _, pred := range b.Preds { + fmt.Fprintf(p.w, " %s", blockHTML(pred)) + } + } + if len(b.Instrs) > 0 { + io.WriteString(p.w, ``) + } + io.WriteString(p.w, "
  • ") + if len(b.Instrs) > 0 { // start list of values + io.WriteString(p.w, "
  • ") + io.WriteString(p.w, "
      ") + } +} + +func (p htmlFuncPrinter) endBlock(b *BasicBlock) { + if len(b.Instrs) > 0 { // end list of values + io.WriteString(p.w, "
    ") + io.WriteString(p.w, "
  • ") + } + io.WriteString(p.w, "
  • ") + fmt.Fprint(p.w, blockLongHTML(b)) + io.WriteString(p.w, "
  • ") + io.WriteString(p.w, "
") +} + +func (p htmlFuncPrinter) value(v Node, live bool) { + var dead string + if !live { + dead = "dead-value" + } + fmt.Fprintf(p.w, "
  • ", dead) + fmt.Fprint(p.w, valueLongHTML(v)) + io.WriteString(p.w, "
  • ") +} + +func (p htmlFuncPrinter) startDepCycle() { + fmt.Fprintln(p.w, "") +} + +func (p htmlFuncPrinter) endDepCycle() { + fmt.Fprintln(p.w, "") +} + +func (p htmlFuncPrinter) named(n string, vals []Value) { + fmt.Fprintf(p.w, "
  • name %s: ", n) + for _, val := range vals { + fmt.Fprintf(p.w, "%s ", valueHTML(val)) + } + fmt.Fprintf(p.w, "
  • ") +} + +type dotWriter struct { + path string + broken bool +} + +// newDotWriter returns non-nil value when mask is valid. +// dotWriter will generate SVGs only for the phases specified in the mask. +// mask can contain following patterns and combinations of them: +// * - all of them; +// x-y - x through y, inclusive; +// x,y - x and y, but not the passes between. +func newDotWriter() *dotWriter { + path, err := exec.LookPath("dot") + if err != nil { + fmt.Println(err) + return nil + } + return &dotWriter{path: path} +} + +func (d *dotWriter) writeFuncSVG(w io.Writer, phase string, f *Function) { + if d.broken { + return + } + cmd := exec.Command(d.path, "-Tsvg") + pipe, err := cmd.StdinPipe() + if err != nil { + d.broken = true + fmt.Println(err) + return + } + buf := new(bytes.Buffer) + cmd.Stdout = buf + bufErr := new(bytes.Buffer) + cmd.Stderr = bufErr + err = cmd.Start() + if err != nil { + d.broken = true + fmt.Println(err) + return + } + fmt.Fprint(pipe, `digraph "" { margin=0; size="4,40"; ranksep=.2; `) + id := strings.Replace(phase, " ", "-", -1) + fmt.Fprintf(pipe, `id="g_graph_%s";`, id) + fmt.Fprintf(pipe, `node [style=filled,fillcolor=white,fontsize=16,fontname="Menlo,Times,serif",margin="0.01,0.03"];`) + fmt.Fprintf(pipe, `edge [fontsize=16,fontname="Menlo,Times,serif"];`) + for _, b := range f.Blocks { + layout := "" + fmt.Fprintf(pipe, `%v [label="%v%s\n%v",id="graph_node_%v_%v"];`, b, b, layout, b.Control().String(), id, b) + } + indexOf := make([]int, len(f.Blocks)) + for i, b := range f.Blocks { + indexOf[b.Index] = i + } + + // XXX + /* + ponums := make([]int32, len(f.Blocks)) + _ = postorderWithNumbering(f, ponums) + isBackEdge := func(from, to int) bool { + return ponums[from] <= ponums[to] + } + */ + isBackEdge := func(from, to int) bool { return false } + + for _, b := range f.Blocks { + for i, s := range b.Succs { + style := "solid" + color := "black" + arrow := "vee" + if isBackEdge(b.Index, s.Index) { + color = "blue" + } + fmt.Fprintf(pipe, `%v -> %v [label=" %d ",style="%s",color="%s",arrowhead="%s"];`, b, s, i, style, color, arrow) + } + } + fmt.Fprint(pipe, "}") + pipe.Close() + err = cmd.Wait() + if err != nil { + d.broken = true + fmt.Printf("dot: %v\n%v\n", err, bufErr.String()) + return + } + + svgID := "svg_graph_" + id + fmt.Fprintf(w, `
    `, svgID, svgID) + // For now, an awful hack: edit the html as it passes through + // our fingers, finding ' 0 { + fset = initial[0].Fset + } + + prog := ir.NewProgram(fset, mode) + if opts != nil { + prog.PrintFunc = opts.PrintFunc + } + + isInitial := make(map[*packages.Package]bool, len(initial)) + for _, p := range initial { + isInitial[p] = true + } + + irmap := make(map[*packages.Package]*ir.Package) + packages.Visit(initial, nil, func(p *packages.Package) { + if p.Types != nil && !p.IllTyped { + var files []*ast.File + if deps || isInitial[p] { + files = p.Syntax + } + irmap[p] = prog.CreatePackage(p.Types, files, p.TypesInfo, true) + } + }) + + var irpkgs []*ir.Package + for _, p := range initial { + irpkgs = append(irpkgs, irmap[p]) // may be nil + } + return prog, irpkgs +} + +// CreateProgram returns a new program in IR form, given a program +// loaded from source. An IR package is created for each transitively +// error-free package of lprog. +// +// Code for bodies of functions is not built until Build is called +// on the result. +// +// The mode parameter controls diagnostics and checking during IR construction. +// +// Deprecated: use golang.org/x/tools/go/packages and the Packages +// function instead; see ir.ExampleLoadPackages. +// +func CreateProgram(lprog *loader.Program, mode ir.BuilderMode) *ir.Program { + prog := ir.NewProgram(lprog.Fset, mode) + + for _, info := range lprog.AllPackages { + if info.TransitivelyErrorFree { + prog.CreatePackage(info.Pkg, info.Files, &info.Info, info.Importable) + } + } + + return prog +} + +// BuildPackage builds an IR program with IR for a single package. +// +// It populates pkg by type-checking the specified file ASTs. All +// dependencies are loaded using the importer specified by tc, which +// typically loads compiler export data; IR code cannot be built for +// those packages. BuildPackage then constructs an ir.Program with all +// dependency packages created, and builds and returns the IR package +// corresponding to pkg. +// +// The caller must have set pkg.Path() to the import path. +// +// The operation fails if there were any type-checking or import errors. +// +// See ../ir/example_test.go for an example. +// +func BuildPackage(tc *types.Config, fset *token.FileSet, pkg *types.Package, files []*ast.File, mode ir.BuilderMode) (*ir.Package, *types.Info, error) { + if fset == nil { + panic("no token.FileSet") + } + if pkg.Path() == "" { + panic("package has no import path") + } + + info := &types.Info{ + Types: make(map[ast.Expr]types.TypeAndValue), + Defs: make(map[*ast.Ident]types.Object), + Uses: make(map[*ast.Ident]types.Object), + Implicits: make(map[ast.Node]types.Object), + Scopes: make(map[ast.Node]*types.Scope), + Selections: make(map[*ast.SelectorExpr]*types.Selection), + } + if err := types.NewChecker(tc, fset, pkg, info).Files(files); err != nil { + return nil, nil, err + } + + prog := ir.NewProgram(fset, mode) + + // Create IR packages for all imports. + // Order is not significant. + created := make(map[*types.Package]bool) + var createAll func(pkgs []*types.Package) + createAll = func(pkgs []*types.Package) { + for _, p := range pkgs { + if !created[p] { + created[p] = true + prog.CreatePackage(p, nil, nil, true) + createAll(p.Imports()) + } + } + } + createAll(pkg.Imports()) + + // Create and build the primary package. + irpkg := prog.CreatePackage(pkg, files, info, false) + irpkg.Build() + return irpkg, info, nil +} diff --git a/vendor/honnef.co/go/tools/ir/irutil/switch.go b/vendor/honnef.co/go/tools/ir/irutil/switch.go new file mode 100644 index 00000000000..f44cbca9e9e --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/irutil/switch.go @@ -0,0 +1,264 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package irutil + +// This file implements discovery of switch and type-switch constructs +// from low-level control flow. +// +// Many techniques exist for compiling a high-level switch with +// constant cases to efficient machine code. The optimal choice will +// depend on the data type, the specific case values, the code in the +// body of each case, and the hardware. +// Some examples: +// - a lookup table (for a switch that maps constants to constants) +// - a computed goto +// - a binary tree +// - a perfect hash +// - a two-level switch (to partition constant strings by their first byte). + +import ( + "bytes" + "fmt" + "go/token" + "go/types" + + "honnef.co/go/tools/ir" +) + +// A ConstCase represents a single constant comparison. +// It is part of a Switch. +type ConstCase struct { + Block *ir.BasicBlock // block performing the comparison + Body *ir.BasicBlock // body of the case + Value *ir.Const // case comparand +} + +// A TypeCase represents a single type assertion. +// It is part of a Switch. +type TypeCase struct { + Block *ir.BasicBlock // block performing the type assert + Body *ir.BasicBlock // body of the case + Type types.Type // case type + Binding ir.Value // value bound by this case +} + +// A Switch is a logical high-level control flow operation +// (a multiway branch) discovered by analysis of a CFG containing +// only if/else chains. It is not part of the ir.Instruction set. +// +// One of ConstCases and TypeCases has length >= 2; +// the other is nil. +// +// In a value switch, the list of cases may contain duplicate constants. +// A type switch may contain duplicate types, or types assignable +// to an interface type also in the list. +// TODO(adonovan): eliminate such duplicates. +// +type Switch struct { + Start *ir.BasicBlock // block containing start of if/else chain + X ir.Value // the switch operand + ConstCases []ConstCase // ordered list of constant comparisons + TypeCases []TypeCase // ordered list of type assertions + Default *ir.BasicBlock // successor if all comparisons fail +} + +func (sw *Switch) String() string { + // We represent each block by the String() of its + // first Instruction, e.g. "print(42:int)". + var buf bytes.Buffer + if sw.ConstCases != nil { + fmt.Fprintf(&buf, "switch %s {\n", sw.X.Name()) + for _, c := range sw.ConstCases { + fmt.Fprintf(&buf, "case %s: %s\n", c.Value.Name(), c.Body.Instrs[0]) + } + } else { + fmt.Fprintf(&buf, "switch %s.(type) {\n", sw.X.Name()) + for _, c := range sw.TypeCases { + fmt.Fprintf(&buf, "case %s %s: %s\n", + c.Binding.Name(), c.Type, c.Body.Instrs[0]) + } + } + if sw.Default != nil { + fmt.Fprintf(&buf, "default: %s\n", sw.Default.Instrs[0]) + } + fmt.Fprintf(&buf, "}") + return buf.String() +} + +// Switches examines the control-flow graph of fn and returns the +// set of inferred value and type switches. A value switch tests an +// ir.Value for equality against two or more compile-time constant +// values. Switches involving link-time constants (addresses) are +// ignored. A type switch type-asserts an ir.Value against two or +// more types. +// +// The switches are returned in dominance order. +// +// The resulting switches do not necessarily correspond to uses of the +// 'switch' keyword in the source: for example, a single source-level +// switch statement with non-constant cases may result in zero, one or +// many Switches, one per plural sequence of constant cases. +// Switches may even be inferred from if/else- or goto-based control flow. +// (In general, the control flow constructs of the source program +// cannot be faithfully reproduced from the IR.) +// +func Switches(fn *ir.Function) []Switch { + // Traverse the CFG in dominance order, so we don't + // enter an if/else-chain in the middle. + var switches []Switch + seen := make(map[*ir.BasicBlock]bool) // TODO(adonovan): opt: use ir.blockSet + for _, b := range fn.DomPreorder() { + if x, k := isComparisonBlock(b); x != nil { + // Block b starts a switch. + sw := Switch{Start: b, X: x} + valueSwitch(&sw, k, seen) + if len(sw.ConstCases) > 1 { + switches = append(switches, sw) + } + } + + if y, x, T := isTypeAssertBlock(b); y != nil { + // Block b starts a type switch. + sw := Switch{Start: b, X: x} + typeSwitch(&sw, y, T, seen) + if len(sw.TypeCases) > 1 { + switches = append(switches, sw) + } + } + } + return switches +} + +func isSameX(x1 ir.Value, x2 ir.Value) bool { + if x1 == x2 { + return true + } + if x2, ok := x2.(*ir.Sigma); ok { + return isSameX(x1, x2.X) + } + return false +} + +func valueSwitch(sw *Switch, k *ir.Const, seen map[*ir.BasicBlock]bool) { + b := sw.Start + x := sw.X + for isSameX(sw.X, x) { + if seen[b] { + break + } + seen[b] = true + + sw.ConstCases = append(sw.ConstCases, ConstCase{ + Block: b, + Body: b.Succs[0], + Value: k, + }) + b = b.Succs[1] + n := 0 + for _, instr := range b.Instrs { + switch instr.(type) { + case *ir.If, *ir.BinOp: + n++ + case *ir.Sigma, *ir.Phi, *ir.DebugRef: + default: + n += 1000 + } + } + if n != 2 { + // Block b contains not just 'if x == k' and σ/ϕ nodes, + // so it may have side effects that + // make it unsafe to elide. + break + } + if len(b.Preds) != 1 { + // Block b has multiple predecessors, + // so it cannot be treated as a case. + break + } + x, k = isComparisonBlock(b) + } + sw.Default = b +} + +func typeSwitch(sw *Switch, y ir.Value, T types.Type, seen map[*ir.BasicBlock]bool) { + b := sw.Start + x := sw.X + for isSameX(sw.X, x) { + if seen[b] { + break + } + seen[b] = true + + sw.TypeCases = append(sw.TypeCases, TypeCase{ + Block: b, + Body: b.Succs[0], + Type: T, + Binding: y, + }) + b = b.Succs[1] + n := 0 + for _, instr := range b.Instrs { + switch instr.(type) { + case *ir.TypeAssert, *ir.Extract, *ir.If: + n++ + case *ir.Sigma, *ir.Phi: + default: + n += 1000 + } + } + if n != 4 { + // Block b contains not just + // {TypeAssert; Extract #0; Extract #1; If} + // so it may have side effects that + // make it unsafe to elide. + break + } + if len(b.Preds) != 1 { + // Block b has multiple predecessors, + // so it cannot be treated as a case. + break + } + y, x, T = isTypeAssertBlock(b) + } + sw.Default = b +} + +// isComparisonBlock returns the operands (v, k) if a block ends with +// a comparison v==k, where k is a compile-time constant. +// +func isComparisonBlock(b *ir.BasicBlock) (v ir.Value, k *ir.Const) { + if n := len(b.Instrs); n >= 2 { + if i, ok := b.Instrs[n-1].(*ir.If); ok { + if binop, ok := i.Cond.(*ir.BinOp); ok && binop.Block() == b && binop.Op == token.EQL { + if k, ok := binop.Y.(*ir.Const); ok { + return binop.X, k + } + if k, ok := binop.X.(*ir.Const); ok { + return binop.Y, k + } + } + } + } + return +} + +// isTypeAssertBlock returns the operands (y, x, T) if a block ends with +// a type assertion "if y, ok := x.(T); ok {". +// +func isTypeAssertBlock(b *ir.BasicBlock) (y, x ir.Value, T types.Type) { + if n := len(b.Instrs); n >= 4 { + if i, ok := b.Instrs[n-1].(*ir.If); ok { + if ext1, ok := i.Cond.(*ir.Extract); ok && ext1.Block() == b && ext1.Index == 1 { + if ta, ok := ext1.Tuple.(*ir.TypeAssert); ok && ta.Block() == b { + // hack: relies upon instruction ordering. + if ext0, ok := b.Instrs[n-3].(*ir.Extract); ok { + return ext0, ta.X, ta.AssertedType + } + } + } + } + } + return +} diff --git a/vendor/honnef.co/go/tools/ir/irutil/util.go b/vendor/honnef.co/go/tools/ir/irutil/util.go new file mode 100644 index 00000000000..04b25f5f9be --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/irutil/util.go @@ -0,0 +1,70 @@ +package irutil + +import ( + "honnef.co/go/tools/ir" +) + +func Reachable(from, to *ir.BasicBlock) bool { + if from == to { + return true + } + if from.Dominates(to) { + return true + } + + found := false + Walk(from, func(b *ir.BasicBlock) bool { + if b == to { + found = true + return false + } + return true + }) + return found +} + +func Walk(b *ir.BasicBlock, fn func(*ir.BasicBlock) bool) { + seen := map[*ir.BasicBlock]bool{} + wl := []*ir.BasicBlock{b} + for len(wl) > 0 { + b := wl[len(wl)-1] + wl = wl[:len(wl)-1] + if seen[b] { + continue + } + seen[b] = true + if !fn(b) { + continue + } + wl = append(wl, b.Succs...) + } +} + +func Vararg(x *ir.Slice) ([]ir.Value, bool) { + var out []ir.Value + slice, ok := x.X.(*ir.Alloc) + if !ok { + return nil, false + } + for _, ref := range *slice.Referrers() { + if ref == x { + continue + } + if ref.Block() != x.Block() { + return nil, false + } + idx, ok := ref.(*ir.IndexAddr) + if !ok { + return nil, false + } + if len(*idx.Referrers()) != 1 { + return nil, false + } + store, ok := (*idx.Referrers())[0].(*ir.Store) + if !ok { + return nil, false + } + out = append(out, store.Val) + } + return out, true +} diff --git a/vendor/honnef.co/go/tools/ir/irutil/visit.go b/vendor/honnef.co/go/tools/ir/irutil/visit.go new file mode 100644 index 00000000000..657c9cde747 --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/irutil/visit.go @@ -0,0 +1,79 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package irutil // import "honnef.co/go/tools/ir/irutil" + +import "honnef.co/go/tools/ir" + +// This file defines utilities for visiting the IR of +// a Program. +// +// TODO(adonovan): test coverage. + +// AllFunctions finds and returns the set of functions potentially +// needed by program prog, as determined by a simple linker-style +// reachability algorithm starting from the members and method-sets of +// each package. The result may include anonymous functions and +// synthetic wrappers. +// +// Precondition: all packages are built. +// +func AllFunctions(prog *ir.Program) map[*ir.Function]bool { + visit := visitor{ + prog: prog, + seen: make(map[*ir.Function]bool), + } + visit.program() + return visit.seen +} + +type visitor struct { + prog *ir.Program + seen map[*ir.Function]bool +} + +func (visit *visitor) program() { + for _, pkg := range visit.prog.AllPackages() { + for _, mem := range pkg.Members { + if fn, ok := mem.(*ir.Function); ok { + visit.function(fn) + } + } + } + for _, T := range visit.prog.RuntimeTypes() { + mset := visit.prog.MethodSets.MethodSet(T) + for i, n := 0, mset.Len(); i < n; i++ { + visit.function(visit.prog.MethodValue(mset.At(i))) + } + } +} + +func (visit *visitor) function(fn *ir.Function) { + if !visit.seen[fn] { + visit.seen[fn] = true + var buf [10]*ir.Value // avoid alloc in common case + for _, b := range fn.Blocks { + for _, instr := range b.Instrs { + for _, op := range instr.Operands(buf[:0]) { + if fn, ok := (*op).(*ir.Function); ok { + visit.function(fn) + } + } + } + } + } +} + +// MainPackages returns the subset of the specified packages +// named "main" that define a main function. +// The result may include synthetic "testmain" packages. +func MainPackages(pkgs []*ir.Package) []*ir.Package { + var mains []*ir.Package + for _, pkg := range pkgs { + if pkg.Pkg.Name() == "main" && pkg.Func("main") != nil { + mains = append(mains, pkg) + } + } + return mains +} diff --git a/vendor/honnef.co/go/tools/ir/lift.go b/vendor/honnef.co/go/tools/ir/lift.go new file mode 100644 index 00000000000..71d5c8cb060 --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/lift.go @@ -0,0 +1,1063 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// This file defines the lifting pass which tries to "lift" Alloc +// cells (new/local variables) into SSA registers, replacing loads +// with the dominating stored value, eliminating loads and stores, and +// inserting φ- and σ-nodes as needed. + +// Cited papers and resources: +// +// Ron Cytron et al. 1991. Efficiently computing SSA form... +// http://doi.acm.org/10.1145/115372.115320 +// +// Cooper, Harvey, Kennedy. 2001. A Simple, Fast Dominance Algorithm. +// Software Practice and Experience 2001, 4:1-10. +// http://www.hipersoft.rice.edu/grads/publications/dom14.pdf +// +// Daniel Berlin, llvmdev mailing list, 2012. +// http://lists.cs.uiuc.edu/pipermail/llvmdev/2012-January/046638.html +// (Be sure to expand the whole thread.) +// +// C. Scott Ananian. 1997. The static single information form. +// +// Jeremy Singer. 2006. Static program analysis based on virtual register renaming. + +// TODO(adonovan): opt: there are many optimizations worth evaluating, and +// the conventional wisdom for SSA construction is that a simple +// algorithm well engineered often beats those of better asymptotic +// complexity on all but the most egregious inputs. +// +// Danny Berlin suggests that the Cooper et al. algorithm for +// computing the dominance frontier is superior to Cytron et al. +// Furthermore he recommends that rather than computing the DF for the +// whole function then renaming all alloc cells, it may be cheaper to +// compute the DF for each alloc cell separately and throw it away. +// +// Consider exploiting liveness information to avoid creating dead +// φ-nodes which we then immediately remove. +// +// Also see many other "TODO: opt" suggestions in the code. + +import ( + "fmt" + "go/types" + "os" +) + +// If true, show diagnostic information at each step of lifting. +// Very verbose. +const debugLifting = false + +// domFrontier maps each block to the set of blocks in its dominance +// frontier. The outer slice is conceptually a map keyed by +// Block.Index. The inner slice is conceptually a set, possibly +// containing duplicates. +// +// TODO(adonovan): opt: measure impact of dups; consider a packed bit +// representation, e.g. big.Int, and bitwise parallel operations for +// the union step in the Children loop. +// +// domFrontier's methods mutate the slice's elements but not its +// length, so their receivers needn't be pointers. +// +type domFrontier [][]*BasicBlock + +func (df domFrontier) add(u, v *BasicBlock) { + df[u.Index] = append(df[u.Index], v) +} + +// build builds the dominance frontier df for the dominator tree of +// fn, using the algorithm found in A Simple, Fast Dominance +// Algorithm, Figure 5. +// +// TODO(adonovan): opt: consider Berlin approach, computing pruned SSA +// by pruning the entire IDF computation, rather than merely pruning +// the DF -> IDF step. +func (df domFrontier) build(fn *Function) { + for _, b := range fn.Blocks { + if len(b.Preds) >= 2 { + for _, p := range b.Preds { + runner := p + for runner != b.dom.idom { + df.add(runner, b) + runner = runner.dom.idom + } + } + } + } +} + +func buildDomFrontier(fn *Function) domFrontier { + df := make(domFrontier, len(fn.Blocks)) + df.build(fn) + return df +} + +type postDomFrontier [][]*BasicBlock + +func (rdf postDomFrontier) add(u, v *BasicBlock) { + rdf[u.Index] = append(rdf[u.Index], v) +} + +func (rdf postDomFrontier) build(fn *Function) { + for _, b := range fn.Blocks { + if len(b.Succs) >= 2 { + for _, s := range b.Succs { + runner := s + for runner != b.pdom.idom { + rdf.add(runner, b) + runner = runner.pdom.idom + } + } + } + } +} + +func buildPostDomFrontier(fn *Function) postDomFrontier { + rdf := make(postDomFrontier, len(fn.Blocks)) + rdf.build(fn) + return rdf +} + +func removeInstr(refs []Instruction, instr Instruction) []Instruction { + i := 0 + for _, ref := range refs { + if ref == instr { + continue + } + refs[i] = ref + i++ + } + for j := i; j != len(refs); j++ { + refs[j] = nil // aid GC + } + return refs[:i] +} + +func clearInstrs(instrs []Instruction) { + for i := range instrs { + instrs[i] = nil + } +} + +// lift replaces local and new Allocs accessed only with +// load/store by IR registers, inserting φ- and σ-nodes where necessary. +// The result is a program in pruned SSI form. +// +// Preconditions: +// - fn has no dead blocks (blockopt has run). +// - Def/use info (Operands and Referrers) is up-to-date. +// - The dominator tree is up-to-date. +// +func lift(fn *Function) { + // TODO(adonovan): opt: lots of little optimizations may be + // worthwhile here, especially if they cause us to avoid + // buildDomFrontier. For example: + // + // - Alloc never loaded? Eliminate. + // - Alloc never stored? Replace all loads with a zero constant. + // - Alloc stored once? Replace loads with dominating store; + // don't forget that an Alloc is itself an effective store + // of zero. + // - Alloc used only within a single block? + // Use degenerate algorithm avoiding φ-nodes. + // - Consider synergy with scalar replacement of aggregates (SRA). + // e.g. *(&x.f) where x is an Alloc. + // Perhaps we'd get better results if we generated this as x.f + // i.e. Field(x, .f) instead of Load(FieldIndex(x, .f)). + // Unclear. + // + // But we will start with the simplest correct code. + var df domFrontier + var rdf postDomFrontier + var closure *closure + var newPhis newPhiMap + var newSigmas newSigmaMap + + // During this pass we will replace some BasicBlock.Instrs + // (allocs, loads and stores) with nil, keeping a count in + // BasicBlock.gaps. At the end we will reset Instrs to the + // concatenation of all non-dead newPhis and non-nil Instrs + // for the block, reusing the original array if space permits. + + // While we're here, we also eliminate 'rundefers' + // instructions in functions that contain no 'defer' + // instructions. + usesDefer := false + + // Determine which allocs we can lift and number them densely. + // The renaming phase uses this numbering for compact maps. + numAllocs := 0 + for _, b := range fn.Blocks { + b.gaps = 0 + b.rundefers = 0 + for _, instr := range b.Instrs { + switch instr := instr.(type) { + case *Alloc: + if !liftable(instr) { + instr.index = -1 + continue + } + index := -1 + if numAllocs == 0 { + df = buildDomFrontier(fn) + rdf = buildPostDomFrontier(fn) + if len(fn.Blocks) > 2 { + closure = transitiveClosure(fn) + } + newPhis = make(newPhiMap, len(fn.Blocks)) + newSigmas = make(newSigmaMap, len(fn.Blocks)) + + if debugLifting { + title := false + for i, blocks := range df { + if blocks != nil { + if !title { + fmt.Fprintf(os.Stderr, "Dominance frontier of %s:\n", fn) + title = true + } + fmt.Fprintf(os.Stderr, "\t%s: %s\n", fn.Blocks[i], blocks) + } + } + } + } + liftAlloc(closure, df, rdf, instr, newPhis, newSigmas) + index = numAllocs + numAllocs++ + instr.index = index + case *Defer: + usesDefer = true + case *RunDefers: + b.rundefers++ + } + } + } + + if numAllocs > 0 { + // renaming maps an alloc (keyed by index) to its replacement + // value. Initially the renaming contains nil, signifying the + // zero constant of the appropriate type; we construct the + // Const lazily at most once on each path through the domtree. + // TODO(adonovan): opt: cache per-function not per subtree. + renaming := make([]Value, numAllocs) + + // Renaming. + rename(fn.Blocks[0], renaming, newPhis, newSigmas) + + simplifyPhis(newPhis) + + // Eliminate dead φ- and σ-nodes. + markLiveNodes(fn.Blocks, newPhis, newSigmas) + } + + // Prepend remaining live φ-nodes to each block and possibly kill rundefers. + for _, b := range fn.Blocks { + var head []Instruction + if numAllocs > 0 { + nps := newPhis[b.Index] + head = make([]Instruction, 0, len(nps)) + for _, pred := range b.Preds { + nss := newSigmas[pred.Index] + idx := pred.succIndex(b) + for _, newSigma := range nss { + if sigma := newSigma.sigmas[idx]; sigma != nil && sigma.live { + head = append(head, sigma) + + // we didn't populate referrers before, as most + // sigma nodes will be killed + if refs := sigma.X.Referrers(); refs != nil { + *refs = append(*refs, sigma) + } + } else if sigma != nil { + sigma.block = nil + } + } + } + for _, np := range nps { + if np.phi.live { + head = append(head, np.phi) + } else { + for _, edge := range np.phi.Edges { + if refs := edge.Referrers(); refs != nil { + *refs = removeInstr(*refs, np.phi) + } + } + np.phi.block = nil + } + } + } + + rundefersToKill := b.rundefers + if usesDefer { + rundefersToKill = 0 + } + + j := len(head) + if j+b.gaps+rundefersToKill == 0 { + continue // fast path: no new phis or gaps + } + + // We could do straight copies instead of element-wise copies + // when both b.gaps and rundefersToKill are zero. However, + // that seems to only be the case ~1% of the time, which + // doesn't seem worth the extra branch. + + // Remove dead instructions, add phis and sigmas + ns := len(b.Instrs) + j - b.gaps - rundefersToKill + if ns <= cap(b.Instrs) { + // b.Instrs has enough capacity to store all instructions + + // OPT(dh): check cap vs the actually required space; if + // there is a big enough difference, it may be worth + // allocating a new slice, to avoid pinning memory. + dst := b.Instrs[:cap(b.Instrs)] + i := len(dst) - 1 + for n := len(b.Instrs) - 1; n >= 0; n-- { + instr := dst[n] + if instr == nil { + continue + } + if !usesDefer { + if _, ok := instr.(*RunDefers); ok { + continue + } + } + dst[i] = instr + i-- + } + off := i + 1 - len(head) + // aid GC + clearInstrs(dst[:off]) + dst = dst[off:] + copy(dst, head) + b.Instrs = dst + } else { + // not enough space, so allocate a new slice and copy + // over. + dst := make([]Instruction, ns) + copy(dst, head) + + for _, instr := range b.Instrs { + if instr == nil { + continue + } + if !usesDefer { + if _, ok := instr.(*RunDefers); ok { + continue + } + } + dst[j] = instr + j++ + } + b.Instrs = dst + } + } + + // Remove any fn.Locals that were lifted. + j := 0 + for _, l := range fn.Locals { + if l.index < 0 { + fn.Locals[j] = l + j++ + } + } + // Nil out fn.Locals[j:] to aid GC. + for i := j; i < len(fn.Locals); i++ { + fn.Locals[i] = nil + } + fn.Locals = fn.Locals[:j] +} + +func hasDirectReferrer(instr Instruction) bool { + for _, instr := range *instr.Referrers() { + switch instr.(type) { + case *Phi, *Sigma: + // ignore + default: + return true + } + } + return false +} + +func markLiveNodes(blocks []*BasicBlock, newPhis newPhiMap, newSigmas newSigmaMap) { + // Phi and sigma nodes are considered live if a non-phi, non-sigma + // node uses them. Once we find a node that is live, we mark all + // of its operands as used, too. + for _, npList := range newPhis { + for _, np := range npList { + phi := np.phi + if !phi.live && hasDirectReferrer(phi) { + markLivePhi(phi) + } + } + } + for _, npList := range newSigmas { + for _, np := range npList { + for _, sigma := range np.sigmas { + if sigma != nil && !sigma.live && hasDirectReferrer(sigma) { + markLiveSigma(sigma) + } + } + } + } + // Existing φ-nodes due to && and || operators + // are all considered live (see Go issue 19622). + for _, b := range blocks { + for _, phi := range b.phis() { + markLivePhi(phi.(*Phi)) + } + } +} + +func markLivePhi(phi *Phi) { + phi.live = true + for _, rand := range phi.Edges { + switch rand := rand.(type) { + case *Phi: + if !rand.live { + markLivePhi(rand) + } + case *Sigma: + if !rand.live { + markLiveSigma(rand) + } + } + } +} + +func markLiveSigma(sigma *Sigma) { + sigma.live = true + switch rand := sigma.X.(type) { + case *Phi: + if !rand.live { + markLivePhi(rand) + } + case *Sigma: + if !rand.live { + markLiveSigma(rand) + } + } +} + +// simplifyPhis replaces trivial phis with non-phi alternatives. Phi +// nodes where all edges are identical, or consist of only the phi +// itself and one other value, may be replaced with the value. +func simplifyPhis(newPhis newPhiMap) { + // find all phis that are trivial and can be replaced with a + // non-phi value. run until we reach a fixpoint, because replacing + // a phi may make other phis trivial. + for changed := true; changed; { + changed = false + for _, npList := range newPhis { + for _, np := range npList { + if np.phi.live { + // we're reusing 'live' to mean 'dead' in the context of simplifyPhis + continue + } + if r, ok := isUselessPhi(np.phi); ok { + // useless phi, replace its uses with the + // replacement value. the dead phi pass will clean + // up the phi afterwards. + replaceAll(np.phi, r) + np.phi.live = true + changed = true + } + } + } + } + + for _, npList := range newPhis { + for _, np := range npList { + np.phi.live = false + } + } +} + +type BlockSet struct { + idx int + values []bool + count int +} + +func NewBlockSet(size int) *BlockSet { + return &BlockSet{values: make([]bool, size)} +} + +func (s *BlockSet) Set(s2 *BlockSet) { + copy(s.values, s2.values) + s.count = 0 + for _, v := range s.values { + if v { + s.count++ + } + } +} + +func (s *BlockSet) Num() int { + return s.count +} + +func (s *BlockSet) Has(b *BasicBlock) bool { + if b.Index >= len(s.values) { + return false + } + return s.values[b.Index] +} + +// add adds b to the set and returns true if the set changed. +func (s *BlockSet) Add(b *BasicBlock) bool { + if s.values[b.Index] { + return false + } + s.count++ + s.values[b.Index] = true + s.idx = b.Index + + return true +} + +func (s *BlockSet) Clear() { + for j := range s.values { + s.values[j] = false + } + s.count = 0 +} + +// take removes an arbitrary element from a set s and +// returns its index, or returns -1 if empty. +func (s *BlockSet) Take() int { + // [i, end] + for i := s.idx; i < len(s.values); i++ { + if s.values[i] { + s.values[i] = false + s.idx = i + s.count-- + return i + } + } + + // [start, i) + for i := 0; i < s.idx; i++ { + if s.values[i] { + s.values[i] = false + s.idx = i + s.count-- + return i + } + } + + return -1 +} + +type closure struct { + span []uint32 + reachables []interval +} + +type interval uint32 + +const ( + flagMask = 1 << 31 + numBits = 20 + lengthBits = 32 - numBits - 1 + lengthMask = (1<>numBits + } else { + // large interval + i++ + start = uint32(inv & numMask) + end = uint32(r[i]) + } + if idx >= start && idx <= end { + return true + } + } + return false +} + +func (c closure) reachable(id int) []interval { + return c.reachables[c.span[id]:c.span[id+1]] +} + +func (c closure) walk(current *BasicBlock, b *BasicBlock, visited []bool) { + visited[b.Index] = true + for _, succ := range b.Succs { + if visited[succ.Index] { + continue + } + visited[succ.Index] = true + c.walk(current, succ, visited) + } +} + +func transitiveClosure(fn *Function) *closure { + reachable := make([]bool, len(fn.Blocks)) + c := &closure{} + c.span = make([]uint32, len(fn.Blocks)+1) + + addInterval := func(start, end uint32) { + if l := end - start; l <= 1<= 0 { // store of zero to Alloc cell + // Replace dominated loads by the zero value. + renaming[instr.index] = nil + if debugLifting { + fmt.Fprintf(os.Stderr, "\tkill alloc %s\n", instr) + } + // Delete the Alloc. + u.Instrs[i] = nil + u.gaps++ + } + + case *Store: + if alloc, ok := instr.Addr.(*Alloc); ok && alloc.index >= 0 { // store to Alloc cell + // Replace dominated loads by the stored value. + renaming[alloc.index] = instr.Val + if debugLifting { + fmt.Fprintf(os.Stderr, "\tkill store %s; new value: %s\n", + instr, instr.Val.Name()) + } + if refs := instr.Addr.Referrers(); refs != nil { + *refs = removeInstr(*refs, instr) + } + if refs := instr.Val.Referrers(); refs != nil { + *refs = removeInstr(*refs, instr) + } + // Delete the Store. + u.Instrs[i] = nil + u.gaps++ + } + + case *Load: + if alloc, ok := instr.X.(*Alloc); ok && alloc.index >= 0 { // load of Alloc cell + // In theory, we wouldn't be able to replace loads + // directly, because a loaded value could be used in + // different branches, in which case it should be + // replaced with different sigma nodes. But we can't + // simply defer replacement, either, because then + // later stores might incorrectly affect this load. + // + // To avoid doing renaming on _all_ values (instead of + // just loads and stores like we're doing), we make + // sure during code generation that each load is only + // used in one block. For example, in constant switch + // statements, where the tag is only evaluated once, + // we store it in a temporary and load it for each + // comparison, so that we have individual loads to + // replace. + newval := renamed(u.Parent(), renaming, alloc) + if debugLifting { + fmt.Fprintf(os.Stderr, "\tupdate load %s = %s with %s\n", + instr.Name(), instr, newval) + } + replaceAll(instr, newval) + u.Instrs[i] = nil + u.gaps++ + } + + case *DebugRef: + if x, ok := instr.X.(*Alloc); ok && x.index >= 0 { + if instr.IsAddr { + instr.X = renamed(u.Parent(), renaming, x) + instr.IsAddr = false + + // Add DebugRef to instr.X's referrers. + if refs := instr.X.Referrers(); refs != nil { + *refs = append(*refs, instr) + } + } else { + // A source expression denotes the address + // of an Alloc that was optimized away. + instr.X = nil + + // Delete the DebugRef. + u.Instrs[i] = nil + u.gaps++ + } + } + } + } + + // update all outgoing sigma nodes with the dominating store + for _, sigmas := range newSigmas[u.Index] { + for _, sigma := range sigmas.sigmas { + if sigma == nil { + continue + } + sigma.X = renamed(u.Parent(), renaming, sigmas.alloc) + } + } + + // For each φ-node in a CFG successor, rename the edge. + for succi, v := range u.Succs { + phis := newPhis[v.Index] + if len(phis) == 0 { + continue + } + i := v.predIndex(u) + for _, np := range phis { + phi := np.phi + alloc := np.alloc + // if there's a sigma node, use it, else use the dominating value + var newval Value + for _, sigmas := range newSigmas[u.Index] { + if sigmas.alloc == alloc && sigmas.sigmas[succi] != nil { + newval = sigmas.sigmas[succi] + break + } + } + if newval == nil { + newval = renamed(u.Parent(), renaming, alloc) + } + if debugLifting { + fmt.Fprintf(os.Stderr, "\tsetphi %s edge %s -> %s (#%d) (alloc=%s) := %s\n", + phi.Name(), u, v, i, alloc.Name(), newval.Name()) + } + phi.Edges[i] = newval + if prefs := newval.Referrers(); prefs != nil { + *prefs = append(*prefs, phi) + } + } + } + + // Continue depth-first recursion over domtree, pushing a + // fresh copy of the renaming map for each subtree. + r := make([]Value, len(renaming)) + for _, v := range u.dom.children { + // XXX add debugging + copy(r, renaming) + + // on entry to a block, the incoming sigma nodes become the new values for their alloc + if idx := u.succIndex(v); idx != -1 { + for _, sigma := range newSigmas[u.Index] { + if sigma.sigmas[idx] != nil { + r[sigma.alloc.index] = sigma.sigmas[idx] + } + } + } + rename(v, r, newPhis, newSigmas) + } + +} diff --git a/vendor/honnef.co/go/tools/ir/lvalue.go b/vendor/honnef.co/go/tools/ir/lvalue.go new file mode 100644 index 00000000000..f676a1f7abe --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/lvalue.go @@ -0,0 +1,116 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// lvalues are the union of addressable expressions and map-index +// expressions. + +import ( + "go/ast" + "go/types" +) + +// An lvalue represents an assignable location that may appear on the +// left-hand side of an assignment. This is a generalization of a +// pointer to permit updates to elements of maps. +// +type lvalue interface { + store(fn *Function, v Value, source ast.Node) // stores v into the location + load(fn *Function, source ast.Node) Value // loads the contents of the location + address(fn *Function) Value // address of the location + typ() types.Type // returns the type of the location +} + +// An address is an lvalue represented by a true pointer. +type address struct { + addr Value + expr ast.Expr // source syntax of the value (not address) [debug mode] +} + +func (a *address) load(fn *Function, source ast.Node) Value { + return emitLoad(fn, a.addr, source) +} + +func (a *address) store(fn *Function, v Value, source ast.Node) { + store := emitStore(fn, a.addr, v, source) + if a.expr != nil { + // store.Val is v, converted for assignability. + emitDebugRef(fn, a.expr, store.Val, false) + } +} + +func (a *address) address(fn *Function) Value { + if a.expr != nil { + emitDebugRef(fn, a.expr, a.addr, true) + } + return a.addr +} + +func (a *address) typ() types.Type { + return deref(a.addr.Type()) +} + +// An element is an lvalue represented by m[k], the location of an +// element of a map. These locations are not addressable +// since pointers cannot be formed from them, but they do support +// load() and store(). +// +type element struct { + m, k Value // map + t types.Type // map element type +} + +func (e *element) load(fn *Function, source ast.Node) Value { + l := &MapLookup{ + X: e.m, + Index: e.k, + } + l.setType(e.t) + return fn.emit(l, source) +} + +func (e *element) store(fn *Function, v Value, source ast.Node) { + up := &MapUpdate{ + Map: e.m, + Key: e.k, + Value: emitConv(fn, v, e.t, source), + } + fn.emit(up, source) +} + +func (e *element) address(fn *Function) Value { + panic("map elements are not addressable") +} + +func (e *element) typ() types.Type { + return e.t +} + +// A blank is a dummy variable whose name is "_". +// It is not reified: loads are illegal and stores are ignored. +// +type blank struct{} + +func (bl blank) load(fn *Function, source ast.Node) Value { + panic("blank.load is illegal") +} + +func (bl blank) store(fn *Function, v Value, source ast.Node) { + s := &BlankStore{ + Val: v, + } + fn.emit(s, source) +} + +func (bl blank) address(fn *Function) Value { + panic("blank var is not addressable") +} + +func (bl blank) typ() types.Type { + // This should be the type of the blank Ident; the typechecker + // doesn't provide this yet, but fortunately, we don't need it + // yet either. + panic("blank.typ is unimplemented") +} diff --git a/vendor/honnef.co/go/tools/ir/methods.go b/vendor/honnef.co/go/tools/ir/methods.go new file mode 100644 index 00000000000..517f448b8c3 --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/methods.go @@ -0,0 +1,239 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// This file defines utilities for population of method sets. + +import ( + "fmt" + "go/types" +) + +// MethodValue returns the Function implementing method sel, building +// wrapper methods on demand. It returns nil if sel denotes an +// abstract (interface) method. +// +// Precondition: sel.Kind() == MethodVal. +// +// Thread-safe. +// +// EXCLUSIVE_LOCKS_ACQUIRED(prog.methodsMu) +// +func (prog *Program) MethodValue(sel *types.Selection) *Function { + if sel.Kind() != types.MethodVal { + panic(fmt.Sprintf("MethodValue(%s) kind != MethodVal", sel)) + } + T := sel.Recv() + if isInterface(T) { + return nil // abstract method + } + if prog.mode&LogSource != 0 { + defer logStack("MethodValue %s %v", T, sel)() + } + + prog.methodsMu.Lock() + defer prog.methodsMu.Unlock() + + return prog.addMethod(prog.createMethodSet(T), sel) +} + +// LookupMethod returns the implementation of the method of type T +// identified by (pkg, name). It returns nil if the method exists but +// is abstract, and panics if T has no such method. +// +func (prog *Program) LookupMethod(T types.Type, pkg *types.Package, name string) *Function { + sel := prog.MethodSets.MethodSet(T).Lookup(pkg, name) + if sel == nil { + panic(fmt.Sprintf("%s has no method %s", T, types.Id(pkg, name))) + } + return prog.MethodValue(sel) +} + +// methodSet contains the (concrete) methods of a non-interface type. +type methodSet struct { + mapping map[string]*Function // populated lazily + complete bool // mapping contains all methods +} + +// Precondition: !isInterface(T). +// EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu) +func (prog *Program) createMethodSet(T types.Type) *methodSet { + mset, ok := prog.methodSets.At(T).(*methodSet) + if !ok { + mset = &methodSet{mapping: make(map[string]*Function)} + prog.methodSets.Set(T, mset) + } + return mset +} + +// EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu) +func (prog *Program) addMethod(mset *methodSet, sel *types.Selection) *Function { + if sel.Kind() == types.MethodExpr { + panic(sel) + } + id := sel.Obj().Id() + fn := mset.mapping[id] + if fn == nil { + obj := sel.Obj().(*types.Func) + + needsPromotion := len(sel.Index()) > 1 + needsIndirection := !isPointer(recvType(obj)) && isPointer(sel.Recv()) + if needsPromotion || needsIndirection { + fn = makeWrapper(prog, sel) + } else { + fn = prog.declaredFunc(obj) + } + if fn.Signature.Recv() == nil { + panic(fn) // missing receiver + } + mset.mapping[id] = fn + } + return fn +} + +// RuntimeTypes returns a new unordered slice containing all +// concrete types in the program for which a complete (non-empty) +// method set is required at run-time. +// +// Thread-safe. +// +// EXCLUSIVE_LOCKS_ACQUIRED(prog.methodsMu) +// +func (prog *Program) RuntimeTypes() []types.Type { + prog.methodsMu.Lock() + defer prog.methodsMu.Unlock() + + var res []types.Type + prog.methodSets.Iterate(func(T types.Type, v interface{}) { + if v.(*methodSet).complete { + res = append(res, T) + } + }) + return res +} + +// declaredFunc returns the concrete function/method denoted by obj. +// Panic ensues if there is none. +// +func (prog *Program) declaredFunc(obj *types.Func) *Function { + if v := prog.packageLevelValue(obj); v != nil { + return v.(*Function) + } + panic("no concrete method: " + obj.String()) +} + +// needMethodsOf ensures that runtime type information (including the +// complete method set) is available for the specified type T and all +// its subcomponents. +// +// needMethodsOf must be called for at least every type that is an +// operand of some MakeInterface instruction, and for the type of +// every exported package member. +// +// Precondition: T is not a method signature (*Signature with Recv()!=nil). +// +// Thread-safe. (Called via emitConv from multiple builder goroutines.) +// +// TODO(adonovan): make this faster. It accounts for 20% of SSA build time. +// +// EXCLUSIVE_LOCKS_ACQUIRED(prog.methodsMu) +// +func (prog *Program) needMethodsOf(T types.Type) { + prog.methodsMu.Lock() + prog.needMethods(T, false) + prog.methodsMu.Unlock() +} + +// Precondition: T is not a method signature (*Signature with Recv()!=nil). +// Recursive case: skip => don't create methods for T. +// +// EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu) +// +func (prog *Program) needMethods(T types.Type, skip bool) { + // Each package maintains its own set of types it has visited. + if prevSkip, ok := prog.runtimeTypes.At(T).(bool); ok { + // needMethods(T) was previously called + if !prevSkip || skip { + return // already seen, with same or false 'skip' value + } + } + prog.runtimeTypes.Set(T, skip) + + tmset := prog.MethodSets.MethodSet(T) + + if !skip && !isInterface(T) && tmset.Len() > 0 { + // Create methods of T. + mset := prog.createMethodSet(T) + if !mset.complete { + mset.complete = true + n := tmset.Len() + for i := 0; i < n; i++ { + prog.addMethod(mset, tmset.At(i)) + } + } + } + + // Recursion over signatures of each method. + for i := 0; i < tmset.Len(); i++ { + sig := tmset.At(i).Type().(*types.Signature) + prog.needMethods(sig.Params(), false) + prog.needMethods(sig.Results(), false) + } + + switch t := T.(type) { + case *types.Basic: + // nop + + case *types.Interface: + // nop---handled by recursion over method set. + + case *types.Pointer: + prog.needMethods(t.Elem(), false) + + case *types.Slice: + prog.needMethods(t.Elem(), false) + + case *types.Chan: + prog.needMethods(t.Elem(), false) + + case *types.Map: + prog.needMethods(t.Key(), false) + prog.needMethods(t.Elem(), false) + + case *types.Signature: + if t.Recv() != nil { + panic(fmt.Sprintf("Signature %s has Recv %s", t, t.Recv())) + } + prog.needMethods(t.Params(), false) + prog.needMethods(t.Results(), false) + + case *types.Named: + // A pointer-to-named type can be derived from a named + // type via reflection. It may have methods too. + prog.needMethods(types.NewPointer(T), false) + + // Consider 'type T struct{S}' where S has methods. + // Reflection provides no way to get from T to struct{S}, + // only to S, so the method set of struct{S} is unwanted, + // so set 'skip' flag during recursion. + prog.needMethods(t.Underlying(), true) + + case *types.Array: + prog.needMethods(t.Elem(), false) + + case *types.Struct: + for i, n := 0, t.NumFields(); i < n; i++ { + prog.needMethods(t.Field(i).Type(), false) + } + + case *types.Tuple: + for i, n := 0, t.Len(); i < n; i++ { + prog.needMethods(t.At(i).Type(), false) + } + + default: + panic(T) + } +} diff --git a/vendor/honnef.co/go/tools/ir/mode.go b/vendor/honnef.co/go/tools/ir/mode.go new file mode 100644 index 00000000000..da548fdbb29 --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/mode.go @@ -0,0 +1,98 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// This file defines the BuilderMode type and its command-line flag. + +import ( + "bytes" + "fmt" +) + +// BuilderMode is a bitmask of options for diagnostics and checking. +// +// *BuilderMode satisfies the flag.Value interface. Example: +// +// var mode = ir.BuilderMode(0) +// func init() { flag.Var(&mode, "build", ir.BuilderModeDoc) } +// +type BuilderMode uint + +const ( + PrintPackages BuilderMode = 1 << iota // Print package inventory to stdout + PrintFunctions // Print function IR code to stdout + PrintSource // Print source code when printing function IR + LogSource // Log source locations as IR builder progresses + SanityCheckFunctions // Perform sanity checking of function bodies + NaiveForm // Build naïve IR form: don't replace local loads/stores with registers + GlobalDebug // Enable debug info for all packages +) + +const BuilderModeDoc = `Options controlling the IR builder. +The value is a sequence of zero or more of these letters: +C perform sanity [C]hecking of the IR form. +D include [D]ebug info for every function. +P print [P]ackage inventory. +F print [F]unction IR code. +A print [A]ST nodes responsible for IR instructions +S log [S]ource locations as IR builder progresses. +N build [N]aive IR form: don't replace local loads/stores with registers. +` + +func (m BuilderMode) String() string { + var buf bytes.Buffer + if m&GlobalDebug != 0 { + buf.WriteByte('D') + } + if m&PrintPackages != 0 { + buf.WriteByte('P') + } + if m&PrintFunctions != 0 { + buf.WriteByte('F') + } + if m&PrintSource != 0 { + buf.WriteByte('A') + } + if m&LogSource != 0 { + buf.WriteByte('S') + } + if m&SanityCheckFunctions != 0 { + buf.WriteByte('C') + } + if m&NaiveForm != 0 { + buf.WriteByte('N') + } + return buf.String() +} + +// Set parses the flag characters in s and updates *m. +func (m *BuilderMode) Set(s string) error { + var mode BuilderMode + for _, c := range s { + switch c { + case 'D': + mode |= GlobalDebug + case 'P': + mode |= PrintPackages + case 'F': + mode |= PrintFunctions + case 'A': + mode |= PrintSource + case 'S': + mode |= LogSource + case 'C': + mode |= SanityCheckFunctions + case 'N': + mode |= NaiveForm + default: + return fmt.Errorf("unknown BuilderMode option: %q", c) + } + } + *m = mode + return nil +} + +// Get returns m. +func (m BuilderMode) Get() interface{} { return m } diff --git a/vendor/honnef.co/go/tools/ir/print.go b/vendor/honnef.co/go/tools/ir/print.go new file mode 100644 index 00000000000..c16c08efa65 --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/print.go @@ -0,0 +1,472 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// This file implements the String() methods for all Value and +// Instruction types. + +import ( + "bytes" + "fmt" + "go/types" + "io" + "reflect" + "sort" + + "golang.org/x/tools/go/types/typeutil" +) + +// relName returns the name of v relative to i. +// In most cases, this is identical to v.Name(), but references to +// Functions (including methods) and Globals use RelString and +// all types are displayed with relType, so that only cross-package +// references are package-qualified. +// +func relName(v Value, i Instruction) string { + if v == nil { + return "" + } + var from *types.Package + if i != nil { + from = i.Parent().pkg() + } + switch v := v.(type) { + case Member: // *Function or *Global + return v.RelString(from) + } + return v.Name() +} + +func relType(t types.Type, from *types.Package) string { + return types.TypeString(t, types.RelativeTo(from)) +} + +func relString(m Member, from *types.Package) string { + // NB: not all globals have an Object (e.g. init$guard), + // so use Package().Object not Object.Package(). + if pkg := m.Package().Pkg; pkg != nil && pkg != from { + return fmt.Sprintf("%s.%s", pkg.Path(), m.Name()) + } + return m.Name() +} + +// Value.String() +// +// This method is provided only for debugging. +// It never appears in disassembly, which uses Value.Name(). + +func (v *Parameter) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("Parameter <%s> {%s}", relType(v.Type(), from), v.name) +} + +func (v *FreeVar) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("FreeVar <%s> %s", relType(v.Type(), from), v.Name()) +} + +func (v *Builtin) String() string { + return fmt.Sprintf("Builtin %s", v.Name()) +} + +// Instruction.String() + +func (v *Alloc) String() string { + from := v.Parent().pkg() + storage := "Stack" + if v.Heap { + storage = "Heap" + } + return fmt.Sprintf("%sAlloc <%s>", storage, relType(v.Type(), from)) +} + +func (v *Sigma) String() string { + from := v.Parent().pkg() + s := fmt.Sprintf("Sigma <%s> [b%d] %s", relType(v.Type(), from), v.From.Index, v.X.Name()) + return s +} + +func (v *Phi) String() string { + var b bytes.Buffer + fmt.Fprintf(&b, "Phi <%s>", v.Type()) + for i, edge := range v.Edges { + b.WriteString(" ") + // Be robust against malformed CFG. + if v.block == nil { + b.WriteString("??") + continue + } + block := -1 + if i < len(v.block.Preds) { + block = v.block.Preds[i].Index + } + fmt.Fprintf(&b, "%d:", block) + edgeVal := "" // be robust + if edge != nil { + edgeVal = relName(edge, v) + } + b.WriteString(edgeVal) + } + return b.String() +} + +func printCall(v *CallCommon, prefix string, instr Instruction) string { + var b bytes.Buffer + if !v.IsInvoke() { + if value, ok := instr.(Value); ok { + fmt.Fprintf(&b, "%s <%s> %s", prefix, relType(value.Type(), instr.Parent().pkg()), relName(v.Value, instr)) + } else { + fmt.Fprintf(&b, "%s %s", prefix, relName(v.Value, instr)) + } + } else { + if value, ok := instr.(Value); ok { + fmt.Fprintf(&b, "%sInvoke <%s> %s.%s", prefix, relType(value.Type(), instr.Parent().pkg()), relName(v.Value, instr), v.Method.Name()) + } else { + fmt.Fprintf(&b, "%sInvoke %s.%s", prefix, relName(v.Value, instr), v.Method.Name()) + } + } + for _, arg := range v.Args { + b.WriteString(" ") + b.WriteString(relName(arg, instr)) + } + return b.String() +} + +func (c *CallCommon) String() string { + return printCall(c, "", nil) +} + +func (v *Call) String() string { + return printCall(&v.Call, "Call", v) +} + +func (v *BinOp) String() string { + return fmt.Sprintf("BinOp <%s> {%s} %s %s", relType(v.Type(), v.Parent().pkg()), v.Op.String(), relName(v.X, v), relName(v.Y, v)) +} + +func (v *UnOp) String() string { + return fmt.Sprintf("UnOp <%s> {%s} %s", relType(v.Type(), v.Parent().pkg()), v.Op.String(), relName(v.X, v)) +} + +func (v *Load) String() string { + return fmt.Sprintf("Load <%s> %s", relType(v.Type(), v.Parent().pkg()), relName(v.X, v)) +} + +func printConv(prefix string, v, x Value) string { + from := v.Parent().pkg() + return fmt.Sprintf("%s <%s> %s", + prefix, + relType(v.Type(), from), + relName(x, v.(Instruction))) +} + +func (v *ChangeType) String() string { return printConv("ChangeType", v, v.X) } +func (v *Convert) String() string { return printConv("Convert", v, v.X) } +func (v *ChangeInterface) String() string { return printConv("ChangeInterface", v, v.X) } +func (v *MakeInterface) String() string { return printConv("MakeInterface", v, v.X) } + +func (v *MakeClosure) String() string { + from := v.Parent().pkg() + var b bytes.Buffer + fmt.Fprintf(&b, "MakeClosure <%s> %s", relType(v.Type(), from), relName(v.Fn, v)) + if v.Bindings != nil { + for _, c := range v.Bindings { + b.WriteString(" ") + b.WriteString(relName(c, v)) + } + } + return b.String() +} + +func (v *MakeSlice) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("MakeSlice <%s> %s %s", + relType(v.Type(), from), + relName(v.Len, v), + relName(v.Cap, v)) +} + +func (v *Slice) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("Slice <%s> %s %s %s %s", + relType(v.Type(), from), relName(v.X, v), relName(v.Low, v), relName(v.High, v), relName(v.Max, v)) +} + +func (v *MakeMap) String() string { + res := "" + if v.Reserve != nil { + res = relName(v.Reserve, v) + } + from := v.Parent().pkg() + return fmt.Sprintf("MakeMap <%s> %s", relType(v.Type(), from), res) +} + +func (v *MakeChan) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("MakeChan <%s> %s", relType(v.Type(), from), relName(v.Size, v)) +} + +func (v *FieldAddr) String() string { + from := v.Parent().pkg() + st := deref(v.X.Type()).Underlying().(*types.Struct) + // Be robust against a bad index. + name := "?" + if 0 <= v.Field && v.Field < st.NumFields() { + name = st.Field(v.Field).Name() + } + return fmt.Sprintf("FieldAddr <%s> [%d] (%s) %s", relType(v.Type(), from), v.Field, name, relName(v.X, v)) +} + +func (v *Field) String() string { + st := v.X.Type().Underlying().(*types.Struct) + // Be robust against a bad index. + name := "?" + if 0 <= v.Field && v.Field < st.NumFields() { + name = st.Field(v.Field).Name() + } + from := v.Parent().pkg() + return fmt.Sprintf("Field <%s> [%d] (%s) %s", relType(v.Type(), from), v.Field, name, relName(v.X, v)) +} + +func (v *IndexAddr) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("IndexAddr <%s> %s %s", relType(v.Type(), from), relName(v.X, v), relName(v.Index, v)) +} + +func (v *Index) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("Index <%s> %s %s", relType(v.Type(), from), relName(v.X, v), relName(v.Index, v)) +} + +func (v *MapLookup) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("MapLookup <%s> %s %s", relType(v.Type(), from), relName(v.X, v), relName(v.Index, v)) +} + +func (v *StringLookup) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("StringLookup <%s> %s %s", relType(v.Type(), from), relName(v.X, v), relName(v.Index, v)) +} + +func (v *Range) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("Range <%s> %s", relType(v.Type(), from), relName(v.X, v)) +} + +func (v *Next) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("Next <%s> %s", relType(v.Type(), from), relName(v.Iter, v)) +} + +func (v *TypeAssert) String() string { + from := v.Parent().pkg() + return fmt.Sprintf("TypeAssert <%s> %s", relType(v.Type(), from), relName(v.X, v)) +} + +func (v *Extract) String() string { + from := v.Parent().pkg() + name := v.Tuple.Type().(*types.Tuple).At(v.Index).Name() + return fmt.Sprintf("Extract <%s> [%d] (%s) %s", relType(v.Type(), from), v.Index, name, relName(v.Tuple, v)) +} + +func (s *Jump) String() string { + // Be robust against malformed CFG. + block := -1 + if s.block != nil && len(s.block.Succs) == 1 { + block = s.block.Succs[0].Index + } + str := fmt.Sprintf("Jump → b%d", block) + if s.Comment != "" { + str = fmt.Sprintf("%s # %s", str, s.Comment) + } + return str +} + +func (s *Unreachable) String() string { + // Be robust against malformed CFG. + block := -1 + if s.block != nil && len(s.block.Succs) == 1 { + block = s.block.Succs[0].Index + } + return fmt.Sprintf("Unreachable → b%d", block) +} + +func (s *If) String() string { + // Be robust against malformed CFG. + tblock, fblock := -1, -1 + if s.block != nil && len(s.block.Succs) == 2 { + tblock = s.block.Succs[0].Index + fblock = s.block.Succs[1].Index + } + return fmt.Sprintf("If %s → b%d b%d", relName(s.Cond, s), tblock, fblock) +} + +func (s *ConstantSwitch) String() string { + var b bytes.Buffer + fmt.Fprintf(&b, "ConstantSwitch %s", relName(s.Tag, s)) + for _, cond := range s.Conds { + fmt.Fprintf(&b, " %s", relName(cond, s)) + } + fmt.Fprint(&b, " →") + for _, succ := range s.block.Succs { + fmt.Fprintf(&b, " b%d", succ.Index) + } + return b.String() +} + +func (s *TypeSwitch) String() string { + from := s.Parent().pkg() + var b bytes.Buffer + fmt.Fprintf(&b, "TypeSwitch <%s> %s", relType(s.typ, from), relName(s.Tag, s)) + for _, cond := range s.Conds { + fmt.Fprintf(&b, " %q", relType(cond, s.block.parent.pkg())) + } + return b.String() +} + +func (s *Go) String() string { + return printCall(&s.Call, "Go", s) +} + +func (s *Panic) String() string { + // Be robust against malformed CFG. + block := -1 + if s.block != nil && len(s.block.Succs) == 1 { + block = s.block.Succs[0].Index + } + return fmt.Sprintf("Panic %s → b%d", relName(s.X, s), block) +} + +func (s *Return) String() string { + var b bytes.Buffer + b.WriteString("Return") + for _, r := range s.Results { + b.WriteString(" ") + b.WriteString(relName(r, s)) + } + return b.String() +} + +func (*RunDefers) String() string { + return "RunDefers" +} + +func (s *Send) String() string { + return fmt.Sprintf("Send %s %s", relName(s.Chan, s), relName(s.X, s)) +} + +func (recv *Recv) String() string { + from := recv.Parent().pkg() + return fmt.Sprintf("Recv <%s> %s", relType(recv.Type(), from), relName(recv.Chan, recv)) +} + +func (s *Defer) String() string { + return printCall(&s.Call, "Defer", s) +} + +func (s *Select) String() string { + var b bytes.Buffer + for i, st := range s.States { + if i > 0 { + b.WriteString(", ") + } + if st.Dir == types.RecvOnly { + b.WriteString("<-") + b.WriteString(relName(st.Chan, s)) + } else { + b.WriteString(relName(st.Chan, s)) + b.WriteString("<-") + b.WriteString(relName(st.Send, s)) + } + } + non := "" + if !s.Blocking { + non = "Non" + } + from := s.Parent().pkg() + return fmt.Sprintf("Select%sBlocking <%s> [%s]", non, relType(s.Type(), from), b.String()) +} + +func (s *Store) String() string { + return fmt.Sprintf("Store {%s} %s %s", + s.Val.Type(), relName(s.Addr, s), relName(s.Val, s)) +} + +func (s *BlankStore) String() string { + return fmt.Sprintf("BlankStore %s", relName(s.Val, s)) +} + +func (s *MapUpdate) String() string { + return fmt.Sprintf("MapUpdate %s %s %s", relName(s.Map, s), relName(s.Key, s), relName(s.Value, s)) +} + +func (s *DebugRef) String() string { + p := s.Parent().Prog.Fset.Position(s.Pos()) + var descr interface{} + if s.object != nil { + descr = s.object // e.g. "var x int" + } else { + descr = reflect.TypeOf(s.Expr) // e.g. "*ast.CallExpr" + } + var addr string + if s.IsAddr { + addr = "address of " + } + return fmt.Sprintf("; %s%s @ %d:%d is %s", addr, descr, p.Line, p.Column, s.X.Name()) +} + +func (p *Package) String() string { + return "package " + p.Pkg.Path() +} + +var _ io.WriterTo = (*Package)(nil) // *Package implements io.Writer + +func (p *Package) WriteTo(w io.Writer) (int64, error) { + var buf bytes.Buffer + WritePackage(&buf, p) + n, err := w.Write(buf.Bytes()) + return int64(n), err +} + +// WritePackage writes to buf a human-readable summary of p. +func WritePackage(buf *bytes.Buffer, p *Package) { + fmt.Fprintf(buf, "%s:\n", p) + + var names []string + maxname := 0 + for name := range p.Members { + if l := len(name); l > maxname { + maxname = l + } + names = append(names, name) + } + + from := p.Pkg + sort.Strings(names) + for _, name := range names { + switch mem := p.Members[name].(type) { + case *NamedConst: + fmt.Fprintf(buf, " const %-*s %s = %s\n", + maxname, name, mem.Name(), mem.Value.RelString(from)) + + case *Function: + fmt.Fprintf(buf, " func %-*s %s\n", + maxname, name, relType(mem.Type(), from)) + + case *Type: + fmt.Fprintf(buf, " type %-*s %s\n", + maxname, name, relType(mem.Type().Underlying(), from)) + for _, meth := range typeutil.IntuitiveMethodSet(mem.Type(), &p.Prog.MethodSets) { + fmt.Fprintf(buf, " %s\n", types.SelectionString(meth, types.RelativeTo(from))) + } + + case *Global: + fmt.Fprintf(buf, " var %-*s %s\n", + maxname, name, relType(mem.Type().(*types.Pointer).Elem(), from)) + } + } + + fmt.Fprintf(buf, "\n") +} diff --git a/vendor/honnef.co/go/tools/ssa/sanity.go b/vendor/honnef.co/go/tools/ir/sanity.go similarity index 89% rename from vendor/honnef.co/go/tools/ssa/sanity.go rename to vendor/honnef.co/go/tools/ir/sanity.go index 1d29b66b02c..ff9edbc6463 100644 --- a/vendor/honnef.co/go/tools/ssa/sanity.go +++ b/vendor/honnef.co/go/tools/ir/sanity.go @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package ssa +package ir -// An optional pass for sanity-checking invariants of the SSA representation. +// An optional pass for sanity-checking invariants of the IR representation. // Currently it checks CFG invariants but little at the instruction level. import ( @@ -23,7 +23,7 @@ type sanity struct { insane bool } -// sanityCheck performs integrity checking of the SSA representation +// sanityCheck performs integrity checking of the IR representation // of the function fn and returns true if it was valid. Diagnostics // are written to reporter if non-nil, os.Stderr otherwise. Some // diagnostics are only warnings and do not imply a negative result. @@ -89,8 +89,15 @@ func findDuplicate(blocks []*BasicBlock) *BasicBlock { func (s *sanity) checkInstr(idx int, instr Instruction) { switch instr := instr.(type) { - case *If, *Jump, *Return, *Panic: + case *If, *Jump, *Return, *Panic, *Unreachable, *ConstantSwitch: s.errorf("control flow instruction not at end of block") + case *Sigma: + if idx > 0 { + prev := s.block.Instrs[idx-1] + if _, ok := prev.(*Sigma); !ok { + s.errorf("Sigma instruction follows a non-Sigma: %T", prev) + } + } case *Phi: if idx == 0 { // It suffices to apply this check to just the first phi node. @@ -99,8 +106,10 @@ func (s *sanity) checkInstr(idx int, instr Instruction) { } } else { prev := s.block.Instrs[idx-1] - if _, ok := prev.(*Phi); !ok { - s.errorf("Phi instruction follows a non-Phi: %T", prev) + switch prev.(type) { + case *Phi, *Sigma: + default: + s.errorf("Phi instruction follows a non-Phi, non-Sigma: %T", prev) } } if ne, np := len(instr.Edges), len(s.block.Preds); ne != np { @@ -109,7 +118,7 @@ func (s *sanity) checkInstr(idx int, instr Instruction) { } else { for i, e := range instr.Edges { if e == nil { - s.errorf("phi node '%s' has no value for edge #%d from %s", instr.Comment, i, s.block.Preds[i]) + s.errorf("phi node '%v' has no value for edge #%d from %s", instr, i, s.block.Preds[i]) } } } @@ -146,7 +155,8 @@ func (s *sanity) checkInstr(idx int, instr Instruction) { case *Go: case *Index: case *IndexAddr: - case *Lookup: + case *MapLookup: + case *StringLookup: case *MakeChan: case *MakeClosure: numFree := len(instr.Fn.(*Function).FreeVars) @@ -175,8 +185,11 @@ func (s *sanity) checkInstr(idx int, instr Instruction) { case *UnOp: case *DebugRef: case *BlankStore: - case *Sigma: - // TODO(adonovan): implement checks. + case *Load: + case *Parameter: + case *Const: + case *Recv: + case *TypeSwitch: default: panic(fmt.Sprintf("Unknown instruction type: %T", instr)) } @@ -196,7 +209,9 @@ func (s *sanity) checkInstr(idx int, instr Instruction) { } else if t == tRangeIter { // not a proper type; ignore. } else if b, ok := t.Underlying().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 { - s.errorf("instruction has 'untyped' result: %s = %s : %s", v.Name(), v, t) + if _, ok := v.(*Const); !ok { + s.errorf("instruction has 'untyped' result: %s = %s : %s", v.Name(), v, t) + } } s.checkReferrerList(v) } @@ -239,11 +254,19 @@ func (s *sanity) checkFinalInstr(instr Instruction) { } case *Panic: - if nsuccs := len(s.block.Succs); nsuccs != 0 { - s.errorf("Panic-terminated block has %d successors; expected none", nsuccs) + if nsuccs := len(s.block.Succs); nsuccs != 1 { + s.errorf("Panic-terminated block has %d successors; expected one", nsuccs) return } + case *Unreachable: + if nsuccs := len(s.block.Succs); nsuccs != 1 { + s.errorf("Unreachable-terminated block has %d successors; expected one", nsuccs) + return + } + + case *ConstantSwitch: + default: s.errorf("non-control flow instruction at end of block") } @@ -260,9 +283,8 @@ func (s *sanity) checkBlock(b *BasicBlock, index int) { } // Check all blocks are reachable. - // (The entry block is always implicitly reachable, - // as is the Recover block, if any.) - if (index > 0 && b != b.parent.Recover) && len(b.Preds) == 0 { + // (The entry block is always implicitly reachable, the exit block may be unreachable.) + if index > 1 && len(b.Preds) == 0 { s.warnf("unreachable block") if b.Instrs == nil { // Since this block is about to be pruned, @@ -395,7 +417,11 @@ func (s *sanity) checkReferrerList(v Value) { } for i, ref := range *refs { if _, ok := s.instrs[ref]; !ok { - s.errorf("%s.Referrers()[%d] = %s is not an instruction belonging to this function", v.Name(), i, ref) + if val, ok := ref.(Value); ok { + s.errorf("%s.Referrers()[%d] = %s = %s is not an instruction belonging to this function", v.Name(), i, val.Name(), val) + } else { + s.errorf("%s.Referrers()[%d] = %s is not an instruction belonging to this function", v.Name(), i, ref) + } } } } @@ -426,7 +452,7 @@ func (s *sanity) checkFunction(fn *Function) bool { s.errorf("nil Pkg") } } - if src, syn := fn.Synthetic == "", fn.Syntax() != nil; src != syn { + if src, syn := fn.Synthetic == "", fn.source != nil; src != syn { s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn) } for i, l := range fn.Locals { @@ -481,9 +507,6 @@ func (s *sanity) checkFunction(fn *Function) bool { } s.checkBlock(b, i) } - if fn.Recover != nil && fn.Blocks[fn.Recover.Index] != fn.Recover { - s.errorf("Recover block is not in Blocks slice") - } s.block = nil for i, anon := range fn.AnonFuncs { @@ -522,14 +545,11 @@ func sanityCheckPackage(pkg *Package) { if obj.Name() != name { if obj.Name() == "init" && strings.HasPrefix(mem.Name(), "init#") { // Ok. The name of a declared init function varies between - // its types.Func ("init") and its ssa.Function ("init#%d"). + // its types.Func ("init") and its ir.Function ("init#%d"). } else { panic(fmt.Sprintf("%s: %T.Object().Name() = %s, want %s", pkg.Pkg.Path(), mem, obj.Name(), name)) } } - if obj.Pos() != mem.Pos() { - panic(fmt.Sprintf("%s Pos=%d obj.Pos=%d", mem, mem.Pos(), obj.Pos())) - } } } diff --git a/vendor/honnef.co/go/tools/ir/source.go b/vendor/honnef.co/go/tools/ir/source.go new file mode 100644 index 00000000000..93d1ccbd290 --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/source.go @@ -0,0 +1,270 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// This file defines utilities for working with source positions +// or source-level named entities ("objects"). + +// TODO(adonovan): test that {Value,Instruction}.Pos() positions match +// the originating syntax, as specified. + +import ( + "go/ast" + "go/token" + "go/types" +) + +// EnclosingFunction returns the function that contains the syntax +// node denoted by path. +// +// Syntax associated with package-level variable specifications is +// enclosed by the package's init() function. +// +// Returns nil if not found; reasons might include: +// - the node is not enclosed by any function. +// - the node is within an anonymous function (FuncLit) and +// its IR function has not been created yet +// (pkg.Build() has not yet been called). +// +func EnclosingFunction(pkg *Package, path []ast.Node) *Function { + // Start with package-level function... + fn := findEnclosingPackageLevelFunction(pkg, path) + if fn == nil { + return nil // not in any function + } + + // ...then walk down the nested anonymous functions. + n := len(path) +outer: + for i := range path { + if lit, ok := path[n-1-i].(*ast.FuncLit); ok { + for _, anon := range fn.AnonFuncs { + if anon.Pos() == lit.Type.Func { + fn = anon + continue outer + } + } + // IR function not found: + // - package not yet built, or maybe + // - builder skipped FuncLit in dead block + // (in principle; but currently the Builder + // generates even dead FuncLits). + return nil + } + } + return fn +} + +// HasEnclosingFunction returns true if the AST node denoted by path +// is contained within the declaration of some function or +// package-level variable. +// +// Unlike EnclosingFunction, the behaviour of this function does not +// depend on whether IR code for pkg has been built, so it can be +// used to quickly reject check inputs that will cause +// EnclosingFunction to fail, prior to IR building. +// +func HasEnclosingFunction(pkg *Package, path []ast.Node) bool { + return findEnclosingPackageLevelFunction(pkg, path) != nil +} + +// findEnclosingPackageLevelFunction returns the Function +// corresponding to the package-level function enclosing path. +// +func findEnclosingPackageLevelFunction(pkg *Package, path []ast.Node) *Function { + if n := len(path); n >= 2 { // [... {Gen,Func}Decl File] + switch decl := path[n-2].(type) { + case *ast.GenDecl: + if decl.Tok == token.VAR && n >= 3 { + // Package-level 'var' initializer. + return pkg.init + } + + case *ast.FuncDecl: + // Declared function/method. + fn := findNamedFunc(pkg, decl.Pos()) + if fn == nil && decl.Recv == nil && decl.Name.Name == "init" { + // Hack: return non-nil when IR is not yet + // built so that HasEnclosingFunction works. + return pkg.init + } + return fn + } + } + return nil // not in any function +} + +// findNamedFunc returns the named function whose FuncDecl.Ident is at +// position pos. +// +func findNamedFunc(pkg *Package, pos token.Pos) *Function { + for _, fn := range pkg.Functions { + if fn.Pos() == pos { + return fn + } + } + return nil +} + +// ValueForExpr returns the IR Value that corresponds to non-constant +// expression e. +// +// It returns nil if no value was found, e.g. +// - the expression is not lexically contained within f; +// - f was not built with debug information; or +// - e is a constant expression. (For efficiency, no debug +// information is stored for constants. Use +// go/types.Info.Types[e].Value instead.) +// - e is a reference to nil or a built-in function. +// - the value was optimised away. +// +// If e is an addressable expression used in an lvalue context, +// value is the address denoted by e, and isAddr is true. +// +// The types of e (or &e, if isAddr) and the result are equal +// (modulo "untyped" bools resulting from comparisons). +// +// (Tip: to find the ir.Value given a source position, use +// astutil.PathEnclosingInterval to locate the ast.Node, then +// EnclosingFunction to locate the Function, then ValueForExpr to find +// the ir.Value.) +// +func (f *Function) ValueForExpr(e ast.Expr) (value Value, isAddr bool) { + if f.debugInfo() { // (opt) + e = unparen(e) + for _, b := range f.Blocks { + for _, instr := range b.Instrs { + if ref, ok := instr.(*DebugRef); ok { + if ref.Expr == e { + return ref.X, ref.IsAddr + } + } + } + } + } + return +} + +// --- Lookup functions for source-level named entities (types.Objects) --- + +// Package returns the IR Package corresponding to the specified +// type-checker package object. +// It returns nil if no such IR package has been created. +// +func (prog *Program) Package(obj *types.Package) *Package { + return prog.packages[obj] +} + +// packageLevelValue returns the package-level value corresponding to +// the specified named object, which may be a package-level const +// (*Const), var (*Global) or func (*Function) of some package in +// prog. It returns nil if the object is not found. +// +func (prog *Program) packageLevelValue(obj types.Object) Value { + if pkg, ok := prog.packages[obj.Pkg()]; ok { + return pkg.values[obj] + } + return nil +} + +// FuncValue returns the concrete Function denoted by the source-level +// named function obj, or nil if obj denotes an interface method. +// +// TODO(adonovan): check the invariant that obj.Type() matches the +// result's Signature, both in the params/results and in the receiver. +// +func (prog *Program) FuncValue(obj *types.Func) *Function { + fn, _ := prog.packageLevelValue(obj).(*Function) + return fn +} + +// ConstValue returns the IR Value denoted by the source-level named +// constant obj. +// +func (prog *Program) ConstValue(obj *types.Const) *Const { + // TODO(adonovan): opt: share (don't reallocate) + // Consts for const objects and constant ast.Exprs. + + // Universal constant? {true,false,nil} + if obj.Parent() == types.Universe { + return NewConst(obj.Val(), obj.Type()) + } + // Package-level named constant? + if v := prog.packageLevelValue(obj); v != nil { + return v.(*Const) + } + return NewConst(obj.Val(), obj.Type()) +} + +// VarValue returns the IR Value that corresponds to a specific +// identifier denoting the source-level named variable obj. +// +// VarValue returns nil if a local variable was not found, perhaps +// because its package was not built, the debug information was not +// requested during IR construction, or the value was optimized away. +// +// ref is the path to an ast.Ident (e.g. from PathEnclosingInterval), +// and that ident must resolve to obj. +// +// pkg is the package enclosing the reference. (A reference to a var +// always occurs within a function, so we need to know where to find it.) +// +// If the identifier is a field selector and its base expression is +// non-addressable, then VarValue returns the value of that field. +// For example: +// func f() struct {x int} +// f().x // VarValue(x) returns a *Field instruction of type int +// +// All other identifiers denote addressable locations (variables). +// For them, VarValue may return either the variable's address or its +// value, even when the expression is evaluated only for its value; the +// situation is reported by isAddr, the second component of the result. +// +// If !isAddr, the returned value is the one associated with the +// specific identifier. For example, +// var x int // VarValue(x) returns Const 0 here +// x = 1 // VarValue(x) returns Const 1 here +// +// It is not specified whether the value or the address is returned in +// any particular case, as it may depend upon optimizations performed +// during IR code generation, such as registerization, constant +// folding, avoidance of materialization of subexpressions, etc. +// +func (prog *Program) VarValue(obj *types.Var, pkg *Package, ref []ast.Node) (value Value, isAddr bool) { + // All references to a var are local to some function, possibly init. + fn := EnclosingFunction(pkg, ref) + if fn == nil { + return // e.g. def of struct field; IR not built? + } + + id := ref[0].(*ast.Ident) + + // Defining ident of a parameter? + if id.Pos() == obj.Pos() { + for _, param := range fn.Params { + if param.Object() == obj { + return param, false + } + } + } + + // Other ident? + for _, b := range fn.Blocks { + for _, instr := range b.Instrs { + if dr, ok := instr.(*DebugRef); ok { + if dr.Pos() == id.Pos() { + return dr.X, dr.IsAddr + } + } + } + } + + // Defining ident of package-level var? + if v := prog.packageLevelValue(obj); v != nil { + return v.(*Global), true + } + + return // e.g. debug info not requested, or var optimized away +} diff --git a/vendor/honnef.co/go/tools/ir/ssa.go b/vendor/honnef.co/go/tools/ir/ssa.go new file mode 100644 index 00000000000..49693045f0b --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/ssa.go @@ -0,0 +1,1856 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// This package defines a high-level intermediate representation for +// Go programs using static single-information (SSI) form. + +import ( + "fmt" + "go/ast" + "go/constant" + "go/token" + "go/types" + "sync" + + "golang.org/x/tools/go/types/typeutil" +) + +type ID int + +// A Program is a partial or complete Go program converted to IR form. +type Program struct { + Fset *token.FileSet // position information for the files of this Program + PrintFunc string // create ir.html for function specified in PrintFunc + imported map[string]*Package // all importable Packages, keyed by import path + packages map[*types.Package]*Package // all loaded Packages, keyed by object + mode BuilderMode // set of mode bits for IR construction + MethodSets typeutil.MethodSetCache // cache of type-checker's method-sets + + methodsMu sync.Mutex // guards the following maps: + methodSets typeutil.Map // maps type to its concrete methodSet + runtimeTypes typeutil.Map // types for which rtypes are needed + canon typeutil.Map // type canonicalization map + bounds map[*types.Func]*Function // bounds for curried x.Method closures + thunks map[selectionKey]*Function // thunks for T.Method expressions +} + +// A Package is a single analyzed Go package containing Members for +// all package-level functions, variables, constants and types it +// declares. These may be accessed directly via Members, or via the +// type-specific accessor methods Func, Type, Var and Const. +// +// Members also contains entries for "init" (the synthetic package +// initializer) and "init#%d", the nth declared init function, +// and unspecified other things too. +// +type Package struct { + Prog *Program // the owning program + Pkg *types.Package // the corresponding go/types.Package + Members map[string]Member // all package members keyed by name (incl. init and init#%d) + Functions []*Function // all functions, excluding anonymous ones + values map[types.Object]Value // package members (incl. types and methods), keyed by object + init *Function // Func("init"); the package's init function + debug bool // include full debug info in this package + printFunc string // which function to print in HTML form + + // The following fields are set transiently, then cleared + // after building. + buildOnce sync.Once // ensures package building occurs once + ninit int32 // number of init functions + info *types.Info // package type information + files []*ast.File // package ASTs +} + +// A Member is a member of a Go package, implemented by *NamedConst, +// *Global, *Function, or *Type; they are created by package-level +// const, var, func and type declarations respectively. +// +type Member interface { + Name() string // declared name of the package member + String() string // package-qualified name of the package member + RelString(*types.Package) string // like String, but relative refs are unqualified + Object() types.Object // typechecker's object for this member, if any + Type() types.Type // type of the package member + Token() token.Token // token.{VAR,FUNC,CONST,TYPE} + Package() *Package // the containing package +} + +// A Type is a Member of a Package representing a package-level named type. +type Type struct { + object *types.TypeName + pkg *Package +} + +// A NamedConst is a Member of a Package representing a package-level +// named constant. +// +// Pos() returns the position of the declaring ast.ValueSpec.Names[*] +// identifier. +// +// NB: a NamedConst is not a Value; it contains a constant Value, which +// it augments with the name and position of its 'const' declaration. +// +type NamedConst struct { + object *types.Const + Value *Const + pkg *Package +} + +// A Value is an IR value that can be referenced by an instruction. +type Value interface { + setID(ID) + + // Name returns the name of this value, and determines how + // this Value appears when used as an operand of an + // Instruction. + // + // This is the same as the source name for Parameters, + // Builtins, Functions, FreeVars, Globals. + // For constants, it is a representation of the constant's value + // and type. For all other Values this is the name of the + // virtual register defined by the instruction. + // + // The name of an IR Value is not semantically significant, + // and may not even be unique within a function. + Name() string + + // ID returns the ID of this value. IDs are unique within a single + // function and are densely numbered, but may contain gaps. + // Values and other Instructions share the same ID space. + // Globally, values are identified by their addresses. However, + // IDs exist to facilitate efficient storage of mappings between + // values and data when analysing functions. + // + // NB: IDs are allocated late in the IR construction process and + // are not available to early stages of said process. + ID() ID + + // If this value is an Instruction, String returns its + // disassembled form; otherwise it returns unspecified + // human-readable information about the Value, such as its + // kind, name and type. + String() string + + // Type returns the type of this value. Many instructions + // (e.g. IndexAddr) change their behaviour depending on the + // types of their operands. + Type() types.Type + + // Parent returns the function to which this Value belongs. + // It returns nil for named Functions, Builtin and Global. + Parent() *Function + + // Referrers returns the list of instructions that have this + // value as one of their operands; it may contain duplicates + // if an instruction has a repeated operand. + // + // Referrers actually returns a pointer through which the + // caller may perform mutations to the object's state. + // + // Referrers is currently only defined if Parent()!=nil, + // i.e. for the function-local values FreeVar, Parameter, + // Functions (iff anonymous) and all value-defining instructions. + // It returns nil for named Functions, Builtin and Global. + // + // Instruction.Operands contains the inverse of this relation. + Referrers() *[]Instruction + + Operands(rands []*Value) []*Value // nil for non-Instructions + + // Source returns the AST node responsible for creating this + // value. A single AST node may be responsible for more than one + // value, and not all values have an associated AST node. + // + // Do not use this method to find a Value given an ast.Expr; use + // ValueForExpr instead. + Source() ast.Node + + // Pos returns Source().Pos() if Source is not nil, else it + // returns token.NoPos. + Pos() token.Pos +} + +// An Instruction is an IR instruction that computes a new Value or +// has some effect. +// +// An Instruction that defines a value (e.g. BinOp) also implements +// the Value interface; an Instruction that only has an effect (e.g. Store) +// does not. +// +type Instruction interface { + setSource(ast.Node) + setID(ID) + + // String returns the disassembled form of this value. + // + // Examples of Instructions that are Values: + // "BinOp {+} t1 t2" (BinOp) + // "Call len t1" (Call) + // Note that the name of the Value is not printed. + // + // Examples of Instructions that are not Values: + // "Return t1" (Return) + // "Store {int} t2 t1" (Store) + // + // (The separation of Value.Name() from Value.String() is useful + // for some analyses which distinguish the operation from the + // value it defines, e.g., 'y = local int' is both an allocation + // of memory 'local int' and a definition of a pointer y.) + String() string + + // ID returns the ID of this instruction. IDs are unique within a single + // function and are densely numbered, but may contain gaps. + // Globally, instructions are identified by their addresses. However, + // IDs exist to facilitate efficient storage of mappings between + // instructions and data when analysing functions. + // + // NB: IDs are allocated late in the IR construction process and + // are not available to early stages of said process. + ID() ID + + // Parent returns the function to which this instruction + // belongs. + Parent() *Function + + // Block returns the basic block to which this instruction + // belongs. + Block() *BasicBlock + + // setBlock sets the basic block to which this instruction belongs. + setBlock(*BasicBlock) + + // Operands returns the operands of this instruction: the + // set of Values it references. + // + // Specifically, it appends their addresses to rands, a + // user-provided slice, and returns the resulting slice, + // permitting avoidance of memory allocation. + // + // The operands are appended in undefined order, but the order + // is consistent for a given Instruction; the addresses are + // always non-nil but may point to a nil Value. Clients may + // store through the pointers, e.g. to effect a value + // renaming. + // + // Value.Referrers is a subset of the inverse of this + // relation. (Referrers are not tracked for all types of + // Values.) + Operands(rands []*Value) []*Value + + Referrers() *[]Instruction // nil for non-Values + + // Source returns the AST node responsible for creating this + // instruction. A single AST node may be responsible for more than + // one instruction, and not all instructions have an associated + // AST node. + Source() ast.Node + + // Pos returns Source().Pos() if Source is not nil, else it + // returns token.NoPos. + Pos() token.Pos +} + +// A Node is a node in the IR value graph. Every concrete type that +// implements Node is also either a Value, an Instruction, or both. +// +// Node contains the methods common to Value and Instruction, plus the +// Operands and Referrers methods generalized to return nil for +// non-Instructions and non-Values, respectively. +// +// Node is provided to simplify IR graph algorithms. Clients should +// use the more specific and informative Value or Instruction +// interfaces where appropriate. +// +type Node interface { + setID(ID) + + // Common methods: + ID() ID + String() string + Source() ast.Node + Pos() token.Pos + Parent() *Function + + // Partial methods: + Operands(rands []*Value) []*Value // nil for non-Instructions + Referrers() *[]Instruction // nil for non-Values +} + +// Function represents the parameters, results, and code of a function +// or method. +// +// If Blocks is nil, this indicates an external function for which no +// Go source code is available. In this case, FreeVars and Locals +// are nil too. Clients performing whole-program analysis must +// handle external functions specially. +// +// Blocks contains the function's control-flow graph (CFG). +// Blocks[0] is the function entry point; block order is not otherwise +// semantically significant, though it may affect the readability of +// the disassembly. +// To iterate over the blocks in dominance order, use DomPreorder(). +// +// A nested function (Parent()!=nil) that refers to one or more +// lexically enclosing local variables ("free variables") has FreeVars. +// Such functions cannot be called directly but require a +// value created by MakeClosure which, via its Bindings, supplies +// values for these parameters. +// +// If the function is a method (Signature.Recv() != nil) then the first +// element of Params is the receiver parameter. +// +// A Go package may declare many functions called "init". +// For each one, Object().Name() returns "init" but Name() returns +// "init#1", etc, in declaration order. +// +// Pos() returns the declaring ast.FuncLit.Type.Func or the position +// of the ast.FuncDecl.Name, if the function was explicit in the +// source. Synthetic wrappers, for which Synthetic != "", may share +// the same position as the function they wrap. +// Syntax.Pos() always returns the position of the declaring "func" token. +// +// Type() returns the function's Signature. +// +type Function struct { + node + + name string + object types.Object // a declared *types.Func or one of its wrappers + method *types.Selection // info about provenance of synthetic methods + Signature *types.Signature + + Synthetic string // provenance of synthetic function; "" for true source functions + parent *Function // enclosing function if anon; nil if global + Pkg *Package // enclosing package; nil for shared funcs (wrappers and error.Error) + Prog *Program // enclosing program + Params []*Parameter // function parameters; for methods, includes receiver + FreeVars []*FreeVar // free variables whose values must be supplied by closure + Locals []*Alloc // local variables of this function + Blocks []*BasicBlock // basic blocks of the function; nil => external + Exit *BasicBlock // The function's exit block + AnonFuncs []*Function // anonymous functions directly beneath this one + referrers []Instruction // referring instructions (iff Parent() != nil) + WillExit bool // Calling this function will always terminate the process + WillUnwind bool // Calling this function will always unwind (it will call runtime.Goexit or panic) + + *functionBody +} + +type functionBody struct { + // The following fields are set transiently during building, + // then cleared. + currentBlock *BasicBlock // where to emit code + objects map[types.Object]Value // addresses of local variables + namedResults []*Alloc // tuple of named results + implicitResults []*Alloc // tuple of results + targets *targets // linked stack of branch targets + lblocks map[*ast.Object]*lblock // labelled blocks + consts []*Const + wr *HTMLWriter + fakeExits BlockSet + blocksets [5]BlockSet + hasDefer bool +} + +func (fn *Function) results() []*Alloc { + if len(fn.namedResults) > 0 { + return fn.namedResults + } + return fn.implicitResults +} + +// BasicBlock represents an IR basic block. +// +// The final element of Instrs is always an explicit transfer of +// control (If, Jump, Return, Panic, or Unreachable). +// +// A block may contain no Instructions only if it is unreachable, +// i.e., Preds is nil. Empty blocks are typically pruned. +// +// BasicBlocks and their Preds/Succs relation form a (possibly cyclic) +// graph independent of the IR Value graph: the control-flow graph or +// CFG. It is illegal for multiple edges to exist between the same +// pair of blocks. +// +// Each BasicBlock is also a node in the dominator tree of the CFG. +// The tree may be navigated using Idom()/Dominees() and queried using +// Dominates(). +// +// The order of Preds and Succs is significant (to Phi and If +// instructions, respectively). +// +type BasicBlock struct { + Index int // index of this block within Parent().Blocks + Comment string // optional label; no semantic significance + parent *Function // parent function + Instrs []Instruction // instructions in order + Preds, Succs []*BasicBlock // predecessors and successors + succs2 [2]*BasicBlock // initial space for Succs + dom domInfo // dominator tree info + pdom domInfo // post-dominator tree info + post int + gaps int // number of nil Instrs (transient) + rundefers int // number of rundefers (transient) +} + +// Pure values ---------------------------------------- + +// A FreeVar represents a free variable of the function to which it +// belongs. +// +// FreeVars are used to implement anonymous functions, whose free +// variables are lexically captured in a closure formed by +// MakeClosure. The value of such a free var is an Alloc or another +// FreeVar and is considered a potentially escaping heap address, with +// pointer type. +// +// FreeVars are also used to implement bound method closures. Such a +// free var represents the receiver value and may be of any type that +// has concrete methods. +// +// Pos() returns the position of the value that was captured, which +// belongs to an enclosing function. +// +type FreeVar struct { + node + + name string + typ types.Type + parent *Function + referrers []Instruction + + // Transiently needed during building. + outer Value // the Value captured from the enclosing context. +} + +// A Parameter represents an input parameter of a function. +// +type Parameter struct { + register + + name string + object types.Object // a *types.Var; nil for non-source locals +} + +// A Const represents the value of a constant expression. +// +// The underlying type of a constant may be any boolean, numeric, or +// string type. In addition, a Const may represent the nil value of +// any reference type---interface, map, channel, pointer, slice, or +// function---but not "untyped nil". +// +// All source-level constant expressions are represented by a Const +// of the same type and value. +// +// Value holds the exact value of the constant, independent of its +// Type(), using the same representation as package go/constant uses for +// constants, or nil for a typed nil value. +// +// Pos() returns token.NoPos. +// +// Example printed form: +// Const {42} +// Const {"test"} +// Const {(3 + 4i)} +// +type Const struct { + register + + Value constant.Value +} + +// A Global is a named Value holding the address of a package-level +// variable. +// +// Pos() returns the position of the ast.ValueSpec.Names[*] +// identifier. +// +type Global struct { + node + + name string + object types.Object // a *types.Var; may be nil for synthetics e.g. init$guard + typ types.Type + + Pkg *Package +} + +// A Builtin represents a specific use of a built-in function, e.g. len. +// +// Builtins are immutable values. Builtins do not have addresses. +// Builtins can only appear in CallCommon.Func. +// +// Name() indicates the function: one of the built-in functions from the +// Go spec (excluding "make" and "new") or one of these ir-defined +// intrinsics: +// +// // wrapnilchk returns ptr if non-nil, panics otherwise. +// // (For use in indirection wrappers.) +// func ir:wrapnilchk(ptr *T, recvType, methodName string) *T +// +// Object() returns a *types.Builtin for built-ins defined by the spec, +// nil for others. +// +// Type() returns a *types.Signature representing the effective +// signature of the built-in for this call. +// +type Builtin struct { + node + + name string + sig *types.Signature +} + +// Value-defining instructions ---------------------------------------- + +// The Alloc instruction reserves space for a variable of the given type, +// zero-initializes it, and yields its address. +// +// Alloc values are always addresses, and have pointer types, so the +// type of the allocated variable is actually +// Type().Underlying().(*types.Pointer).Elem(). +// +// If Heap is false, Alloc allocates space in the function's +// activation record (frame); we refer to an Alloc(Heap=false) as a +// "stack" alloc. Each stack Alloc returns the same address each time +// it is executed within the same activation; the space is +// re-initialized to zero. +// +// If Heap is true, Alloc allocates space in the heap; we +// refer to an Alloc(Heap=true) as a "heap" alloc. Each heap Alloc +// returns a different address each time it is executed. +// +// When Alloc is applied to a channel, map or slice type, it returns +// the address of an uninitialized (nil) reference of that kind; store +// the result of MakeSlice, MakeMap or MakeChan in that location to +// instantiate these types. +// +// Pos() returns the ast.CompositeLit.Lbrace for a composite literal, +// or the ast.CallExpr.Rparen for a call to new() or for a call that +// allocates a varargs slice. +// +// Example printed form: +// t1 = StackAlloc <*int> +// t2 = HeapAlloc <*int> (new) +// +type Alloc struct { + register + Heap bool + index int // dense numbering; for lifting +} + +var _ Instruction = (*Sigma)(nil) +var _ Value = (*Sigma)(nil) + +// The Sigma instruction represents an SSI σ-node, which splits values +// at branches in the control flow. +// +// Conceptually, σ-nodes exist at the end of blocks that branch and +// constitute parallel assignments to one value per destination block. +// However, such a representation would be awkward to work with, so +// instead we place σ-nodes at the beginning of branch targets. The +// From field denotes to which incoming edge the node applies. +// +// Within a block, all σ-nodes must appear before all non-σ nodes. +// +// Example printed form: +// t2 = Sigma [#0] t1 (x) +// +type Sigma struct { + register + From *BasicBlock + X Value + + live bool // used during lifting +} + +// The Phi instruction represents an SSA φ-node, which combines values +// that differ across incoming control-flow edges and yields a new +// value. Within a block, all φ-nodes must appear before all non-φ, non-σ +// nodes. +// +// Pos() returns the position of the && or || for short-circuit +// control-flow joins, or that of the *Alloc for φ-nodes inserted +// during SSA renaming. +// +// Example printed form: +// t3 = Phi 2:t1 4:t2 (x) +// +type Phi struct { + register + Edges []Value // Edges[i] is value for Block().Preds[i] + + live bool // used during lifting +} + +// The Call instruction represents a function or method call. +// +// The Call instruction yields the function result if there is exactly +// one. Otherwise it returns a tuple, the components of which are +// accessed via Extract. +// +// See CallCommon for generic function call documentation. +// +// Pos() returns the ast.CallExpr.Lparen, if explicit in the source. +// +// Example printed form: +// t3 = Call <()> println t1 t2 +// t4 = Call <()> foo$1 +// t6 = Invoke t5.String +// +type Call struct { + register + Call CallCommon +} + +// The BinOp instruction yields the result of binary operation X Op Y. +// +// Pos() returns the ast.BinaryExpr.OpPos, if explicit in the source. +// +// Example printed form: +// t3 = BinOp {+} t2 t1 +// +type BinOp struct { + register + // One of: + // ADD SUB MUL QUO REM + - * / % + // AND OR XOR SHL SHR AND_NOT & | ^ << >> &^ + // EQL NEQ LSS LEQ GTR GEQ == != < <= < >= + Op token.Token + X, Y Value +} + +// The UnOp instruction yields the result of Op X. +// XOR is bitwise complement. +// SUB is negation. +// NOT is logical negation. +// +// +// Example printed form: +// t2 = UnOp {^} t1 +// +type UnOp struct { + register + Op token.Token // One of: NOT SUB XOR ! - ^ + X Value +} + +// The Load instruction loads a value from a memory address. +// +// For implicit memory loads, Pos() returns the position of the +// most closely associated source-level construct; the details are not +// specified. +// +// Example printed form: +// t2 = Load t1 +// +type Load struct { + register + X Value +} + +// The ChangeType instruction applies to X a value-preserving type +// change to Type(). +// +// Type changes are permitted: +// - between a named type and its underlying type. +// - between two named types of the same underlying type. +// - between (possibly named) pointers to identical base types. +// - from a bidirectional channel to a read- or write-channel, +// optionally adding/removing a name. +// +// This operation cannot fail dynamically. +// +// Pos() returns the ast.CallExpr.Lparen, if the instruction arose +// from an explicit conversion in the source. +// +// Example printed form: +// t2 = ChangeType <*T> t1 +// +type ChangeType struct { + register + X Value +} + +// The Convert instruction yields the conversion of value X to type +// Type(). One or both of those types is basic (but possibly named). +// +// A conversion may change the value and representation of its operand. +// Conversions are permitted: +// - between real numeric types. +// - between complex numeric types. +// - between string and []byte or []rune. +// - between pointers and unsafe.Pointer. +// - between unsafe.Pointer and uintptr. +// - from (Unicode) integer to (UTF-8) string. +// A conversion may imply a type name change also. +// +// This operation cannot fail dynamically. +// +// Conversions of untyped string/number/bool constants to a specific +// representation are eliminated during IR construction. +// +// Pos() returns the ast.CallExpr.Lparen, if the instruction arose +// from an explicit conversion in the source. +// +// Example printed form: +// t2 = Convert <[]byte> t1 +// +type Convert struct { + register + X Value +} + +// ChangeInterface constructs a value of one interface type from a +// value of another interface type known to be assignable to it. +// This operation cannot fail. +// +// Pos() returns the ast.CallExpr.Lparen if the instruction arose from +// an explicit T(e) conversion; the ast.TypeAssertExpr.Lparen if the +// instruction arose from an explicit e.(T) operation; or token.NoPos +// otherwise. +// +// Example printed form: +// t2 = ChangeInterface t1 +// +type ChangeInterface struct { + register + X Value +} + +// MakeInterface constructs an instance of an interface type from a +// value of a concrete type. +// +// Use Program.MethodSets.MethodSet(X.Type()) to find the method-set +// of X, and Program.MethodValue(m) to find the implementation of a method. +// +// To construct the zero value of an interface type T, use: +// NewConst(constant.MakeNil(), T, pos) +// +// Pos() returns the ast.CallExpr.Lparen, if the instruction arose +// from an explicit conversion in the source. +// +// Example printed form: +// t2 = MakeInterface t1 +// +type MakeInterface struct { + register + X Value +} + +// The MakeClosure instruction yields a closure value whose code is +// Fn and whose free variables' values are supplied by Bindings. +// +// Type() returns a (possibly named) *types.Signature. +// +// Pos() returns the ast.FuncLit.Type.Func for a function literal +// closure or the ast.SelectorExpr.Sel for a bound method closure. +// +// Example printed form: +// t1 = MakeClosure foo$1 t1 t2 +// t5 = MakeClosure (T).foo$bound t4 +// +type MakeClosure struct { + register + Fn Value // always a *Function + Bindings []Value // values for each free variable in Fn.FreeVars +} + +// The MakeMap instruction creates a new hash-table-based map object +// and yields a value of kind map. +// +// Type() returns a (possibly named) *types.Map. +// +// Pos() returns the ast.CallExpr.Lparen, if created by make(map), or +// the ast.CompositeLit.Lbrack if created by a literal. +// +// Example printed form: +// t1 = MakeMap +// t2 = MakeMap t1 +// +type MakeMap struct { + register + Reserve Value // initial space reservation; nil => default +} + +// The MakeChan instruction creates a new channel object and yields a +// value of kind chan. +// +// Type() returns a (possibly named) *types.Chan. +// +// Pos() returns the ast.CallExpr.Lparen for the make(chan) that +// created it. +// +// Example printed form: +// t3 = MakeChan t1 +// t4 = MakeChan t2 +// +type MakeChan struct { + register + Size Value // int; size of buffer; zero => synchronous. +} + +// The MakeSlice instruction yields a slice of length Len backed by a +// newly allocated array of length Cap. +// +// Both Len and Cap must be non-nil Values of integer type. +// +// (Alloc(types.Array) followed by Slice will not suffice because +// Alloc can only create arrays of constant length.) +// +// Type() returns a (possibly named) *types.Slice. +// +// Pos() returns the ast.CallExpr.Lparen for the make([]T) that +// created it. +// +// Example printed form: +// t3 = MakeSlice <[]string> t1 t2 +// t4 = MakeSlice t1 t2 +// +type MakeSlice struct { + register + Len Value + Cap Value +} + +// The Slice instruction yields a slice of an existing string, slice +// or *array X between optional integer bounds Low and High. +// +// Dynamically, this instruction panics if X evaluates to a nil *array +// pointer. +// +// Type() returns string if the type of X was string, otherwise a +// *types.Slice with the same element type as X. +// +// Pos() returns the ast.SliceExpr.Lbrack if created by a x[:] slice +// operation, the ast.CompositeLit.Lbrace if created by a literal, or +// NoPos if not explicit in the source (e.g. a variadic argument slice). +// +// Example printed form: +// t4 = Slice <[]int> t3 t2 t1 +// +type Slice struct { + register + X Value // slice, string, or *array + Low, High, Max Value // each may be nil +} + +// The FieldAddr instruction yields the address of Field of *struct X. +// +// The field is identified by its index within the field list of the +// struct type of X. +// +// Dynamically, this instruction panics if X evaluates to a nil +// pointer. +// +// Type() returns a (possibly named) *types.Pointer. +// +// Pos() returns the position of the ast.SelectorExpr.Sel for the +// field, if explicit in the source. +// +// Example printed form: +// t2 = FieldAddr <*int> [0] (X) t1 +// +type FieldAddr struct { + register + X Value // *struct + Field int // field is X.Type().Underlying().(*types.Pointer).Elem().Underlying().(*types.Struct).Field(Field) +} + +// The Field instruction yields the Field of struct X. +// +// The field is identified by its index within the field list of the +// struct type of X; by using numeric indices we avoid ambiguity of +// package-local identifiers and permit compact representations. +// +// Pos() returns the position of the ast.SelectorExpr.Sel for the +// field, if explicit in the source. +// +// Example printed form: +// t2 = FieldAddr [0] (X) t1 +// +type Field struct { + register + X Value // struct + Field int // index into X.Type().(*types.Struct).Fields +} + +// The IndexAddr instruction yields the address of the element at +// index Index of collection X. Index is an integer expression. +// +// The elements of maps and strings are not addressable; use StringLookup, MapLookup or +// MapUpdate instead. +// +// Dynamically, this instruction panics if X evaluates to a nil *array +// pointer. +// +// Type() returns a (possibly named) *types.Pointer. +// +// Pos() returns the ast.IndexExpr.Lbrack for the index operation, if +// explicit in the source. +// +// Example printed form: +// t3 = IndexAddr <*int> t2 t1 +// +type IndexAddr struct { + register + X Value // slice or *array, + Index Value // numeric index +} + +// The Index instruction yields element Index of array X. +// +// Pos() returns the ast.IndexExpr.Lbrack for the index operation, if +// explicit in the source. +// +// Example printed form: +// t3 = Index t2 t1 +// +type Index struct { + register + X Value // array + Index Value // integer index +} + +// The MapLookup instruction yields element Index of collection X, a map. +// +// If CommaOk, the result is a 2-tuple of the value above and a +// boolean indicating the result of a map membership test for the key. +// The components of the tuple are accessed using Extract. +// +// Pos() returns the ast.IndexExpr.Lbrack, if explicit in the source. +// +// Example printed form: +// t4 = MapLookup t3 t1 +// t6 = MapLookup <(string, bool)> t3 t2 +// +type MapLookup struct { + register + X Value // map + Index Value // key-typed index + CommaOk bool // return a value,ok pair +} + +// The StringLookup instruction yields element Index of collection X, a string. +// Index is an integer expression. +// +// Pos() returns the ast.IndexExpr.Lbrack, if explicit in the source. +// +// Example printed form: +// t3 = StringLookup t2 t1 +// +type StringLookup struct { + register + X Value // string + Index Value // numeric index +} + +// SelectState is a helper for Select. +// It represents one goal state and its corresponding communication. +// +type SelectState struct { + Dir types.ChanDir // direction of case (SendOnly or RecvOnly) + Chan Value // channel to use (for send or receive) + Send Value // value to send (for send) + Pos token.Pos // position of token.ARROW + DebugNode ast.Node // ast.SendStmt or ast.UnaryExpr(<-) [debug mode] +} + +// The Select instruction tests whether (or blocks until) one +// of the specified sent or received states is entered. +// +// Let n be the number of States for which Dir==RECV and Tᵢ (0 ≤ i < n) +// be the element type of each such state's Chan. +// Select returns an n+2-tuple +// (index int, recvOk bool, r₀ T₀, ... rₙ-1 Tₙ-1) +// The tuple's components, described below, must be accessed via the +// Extract instruction. +// +// If Blocking, select waits until exactly one state holds, i.e. a +// channel becomes ready for the designated operation of sending or +// receiving; select chooses one among the ready states +// pseudorandomly, performs the send or receive operation, and sets +// 'index' to the index of the chosen channel. +// +// If !Blocking, select doesn't block if no states hold; instead it +// returns immediately with index equal to -1. +// +// If the chosen channel was used for a receive, the rᵢ component is +// set to the received value, where i is the index of that state among +// all n receive states; otherwise rᵢ has the zero value of type Tᵢ. +// Note that the receive index i is not the same as the state +// index index. +// +// The second component of the triple, recvOk, is a boolean whose value +// is true iff the selected operation was a receive and the receive +// successfully yielded a value. +// +// Pos() returns the ast.SelectStmt.Select. +// +// Example printed form: +// t6 = SelectNonBlocking <(index int, ok bool, int)> [<-t4, t5<-t1] +// t11 = SelectBlocking <(index int, ok bool)> [] +// +type Select struct { + register + States []*SelectState + Blocking bool +} + +// The Range instruction yields an iterator over the domain and range +// of X, which must be a string or map. +// +// Elements are accessed via Next. +// +// Type() returns an opaque and degenerate "rangeIter" type. +// +// Pos() returns the ast.RangeStmt.For. +// +// Example printed form: +// t2 = Range t1 +// +type Range struct { + register + X Value // string or map +} + +// The Next instruction reads and advances the (map or string) +// iterator Iter and returns a 3-tuple value (ok, k, v). If the +// iterator is not exhausted, ok is true and k and v are the next +// elements of the domain and range, respectively. Otherwise ok is +// false and k and v are undefined. +// +// Components of the tuple are accessed using Extract. +// +// The IsString field distinguishes iterators over strings from those +// over maps, as the Type() alone is insufficient: consider +// map[int]rune. +// +// Type() returns a *types.Tuple for the triple (ok, k, v). +// The types of k and/or v may be types.Invalid. +// +// Example printed form: +// t5 = Next <(ok bool, k int, v rune)> t2 +// t5 = Next <(ok bool, k invalid type, v invalid type)> t2 +// +type Next struct { + register + Iter Value + IsString bool // true => string iterator; false => map iterator. +} + +// The TypeAssert instruction tests whether interface value X has type +// AssertedType. +// +// If !CommaOk, on success it returns v, the result of the conversion +// (defined below); on failure it panics. +// +// If CommaOk: on success it returns a pair (v, true) where v is the +// result of the conversion; on failure it returns (z, false) where z +// is AssertedType's zero value. The components of the pair must be +// accessed using the Extract instruction. +// +// If AssertedType is a concrete type, TypeAssert checks whether the +// dynamic type in interface X is equal to it, and if so, the result +// of the conversion is a copy of the value in the interface. +// +// If AssertedType is an interface, TypeAssert checks whether the +// dynamic type of the interface is assignable to it, and if so, the +// result of the conversion is a copy of the interface value X. +// If AssertedType is a superinterface of X.Type(), the operation will +// fail iff the operand is nil. (Contrast with ChangeInterface, which +// performs no nil-check.) +// +// Type() reflects the actual type of the result, possibly a +// 2-types.Tuple; AssertedType is the asserted type. +// +// Pos() returns the ast.CallExpr.Lparen if the instruction arose from +// an explicit T(e) conversion; the ast.TypeAssertExpr.Lparen if the +// instruction arose from an explicit e.(T) operation; or the +// ast.CaseClause.Case if the instruction arose from a case of a +// type-switch statement. +// +// Example printed form: +// t2 = TypeAssert t1 +// t4 = TypeAssert <(value fmt.Stringer, ok bool)> t1 +// +type TypeAssert struct { + register + X Value + AssertedType types.Type + CommaOk bool +} + +// The Extract instruction yields component Index of Tuple. +// +// This is used to access the results of instructions with multiple +// return values, such as Call, TypeAssert, Next, Recv, +// MapLookup and others. +// +// Example printed form: +// t7 = Extract [1] (ok) t4 +// +type Extract struct { + register + Tuple Value + Index int +} + +// Instructions executed for effect. They do not yield a value. -------------------- + +// The Jump instruction transfers control to the sole successor of its +// owning block. +// +// A Jump must be the last instruction of its containing BasicBlock. +// +// Pos() returns NoPos. +// +// Example printed form: +// Jump → b1 +// +type Jump struct { + anInstruction + Comment string +} + +// The Unreachable pseudo-instruction signals that execution cannot +// continue after the preceding function call because it terminates +// the process. +// +// The instruction acts as a control instruction, jumping to the exit +// block. However, this jump will never execute. +// +// An Unreachable instruction must be the last instruction of its +// containing BasicBlock. +// +// Example printed form: +// Unreachable → b1 +// +type Unreachable struct { + anInstruction +} + +// The If instruction transfers control to one of the two successors +// of its owning block, depending on the boolean Cond: the first if +// true, the second if false. +// +// An If instruction must be the last instruction of its containing +// BasicBlock. +// +// Pos() returns the *ast.IfStmt, if explicit in the source. +// +// Example printed form: +// If t2 → b1 b2 +// +type If struct { + anInstruction + Cond Value +} + +type ConstantSwitch struct { + anInstruction + Tag Value + // Constant branch conditions. A nil Value denotes the (implicit + // or explicit) default branch. + Conds []Value +} + +type TypeSwitch struct { + register + Tag Value + Conds []types.Type +} + +// The Return instruction returns values and control back to the calling +// function. +// +// len(Results) is always equal to the number of results in the +// function's signature. +// +// If len(Results) > 1, Return returns a tuple value with the specified +// components which the caller must access using Extract instructions. +// +// There is no instruction to return a ready-made tuple like those +// returned by a "value,ok"-mode TypeAssert, MapLookup or Recv or +// a tail-call to a function with multiple result parameters. +// +// Return must be the last instruction of its containing BasicBlock. +// Such a block has no successors. +// +// Pos() returns the ast.ReturnStmt.Return, if explicit in the source. +// +// Example printed form: +// Return +// Return t1 t2 +// +type Return struct { + anInstruction + Results []Value +} + +// The RunDefers instruction pops and invokes the entire stack of +// procedure calls pushed by Defer instructions in this function. +// +// It is legal to encounter multiple 'rundefers' instructions in a +// single control-flow path through a function; this is useful in +// the combined init() function, for example. +// +// Pos() returns NoPos. +// +// Example printed form: +// RunDefers +// +type RunDefers struct { + anInstruction +} + +// The Panic instruction initiates a panic with value X. +// +// A Panic instruction must be the last instruction of its containing +// BasicBlock, which must have one successor, the exit block. +// +// NB: 'go panic(x)' and 'defer panic(x)' do not use this instruction; +// they are treated as calls to a built-in function. +// +// Pos() returns the ast.CallExpr.Lparen if this panic was explicit +// in the source. +// +// Example printed form: +// Panic t1 +// +type Panic struct { + anInstruction + X Value // an interface{} +} + +// The Go instruction creates a new goroutine and calls the specified +// function within it. +// +// See CallCommon for generic function call documentation. +// +// Pos() returns the ast.GoStmt.Go. +// +// Example printed form: +// Go println t1 +// Go t3 +// GoInvoke t4.Bar t2 +// +type Go struct { + anInstruction + Call CallCommon +} + +// The Defer instruction pushes the specified call onto a stack of +// functions to be called by a RunDefers instruction or by a panic. +// +// See CallCommon for generic function call documentation. +// +// Pos() returns the ast.DeferStmt.Defer. +// +// Example printed form: +// Defer println t1 +// Defer t3 +// DeferInvoke t4.Bar t2 +// +type Defer struct { + anInstruction + Call CallCommon +} + +// The Send instruction sends X on channel Chan. +// +// Pos() returns the ast.SendStmt.Arrow, if explicit in the source. +// +// Example printed form: +// Send t2 t1 +// +type Send struct { + anInstruction + Chan, X Value +} + +// The Recv instruction receives from channel Chan. +// +// If CommaOk, the result is a 2-tuple of the value above +// and a boolean indicating the success of the receive. The +// components of the tuple are accessed using Extract. +// +// Pos() returns the ast.UnaryExpr.OpPos, if explicit in the source. +// For receive operations implicit in ranging over a channel, +// Pos() returns the ast.RangeStmt.For. +// +// Example printed form: +// t2 = Recv t1 +// t3 = Recv <(int, bool)> t1 +type Recv struct { + register + Chan Value + CommaOk bool +} + +// The Store instruction stores Val at address Addr. +// Stores can be of arbitrary types. +// +// Pos() returns the position of the source-level construct most closely +// associated with the memory store operation. +// Since implicit memory stores are numerous and varied and depend upon +// implementation choices, the details are not specified. +// +// Example printed form: +// Store {int} t2 t1 +// +type Store struct { + anInstruction + Addr Value + Val Value +} + +// The BlankStore instruction is emitted for assignments to the blank +// identifier. +// +// BlankStore is a pseudo-instruction: it has no dynamic effect. +// +// Pos() returns NoPos. +// +// Example printed form: +// BlankStore t1 +// +type BlankStore struct { + anInstruction + Val Value +} + +// The MapUpdate instruction updates the association of Map[Key] to +// Value. +// +// Pos() returns the ast.KeyValueExpr.Colon or ast.IndexExpr.Lbrack, +// if explicit in the source. +// +// Example printed form: +// MapUpdate t3 t1 t2 +// +type MapUpdate struct { + anInstruction + Map Value + Key Value + Value Value +} + +// A DebugRef instruction maps a source-level expression Expr to the +// IR value X that represents the value (!IsAddr) or address (IsAddr) +// of that expression. +// +// DebugRef is a pseudo-instruction: it has no dynamic effect. +// +// Pos() returns Expr.Pos(), the start position of the source-level +// expression. This is not the same as the "designated" token as +// documented at Value.Pos(). e.g. CallExpr.Pos() does not return the +// position of the ("designated") Lparen token. +// +// DebugRefs are generated only for functions built with debugging +// enabled; see Package.SetDebugMode() and the GlobalDebug builder +// mode flag. +// +// DebugRefs are not emitted for ast.Idents referring to constants or +// predeclared identifiers, since they are trivial and numerous. +// Nor are they emitted for ast.ParenExprs. +// +// (By representing these as instructions, rather than out-of-band, +// consistency is maintained during transformation passes by the +// ordinary SSA renaming machinery.) +// +// Example printed form: +// ; *ast.CallExpr @ 102:9 is t5 +// ; var x float64 @ 109:72 is x +// ; address of *ast.CompositeLit @ 216:10 is t0 +// +type DebugRef struct { + anInstruction + Expr ast.Expr // the referring expression (never *ast.ParenExpr) + object types.Object // the identity of the source var/func + IsAddr bool // Expr is addressable and X is the address it denotes + X Value // the value or address of Expr +} + +// Embeddable mix-ins and helpers for common parts of other structs. ----------- + +// register is a mix-in embedded by all IR values that are also +// instructions, i.e. virtual registers, and provides a uniform +// implementation of most of the Value interface: Value.Name() is a +// numbered register (e.g. "t0"); the other methods are field accessors. +// +// Temporary names are automatically assigned to each register on +// completion of building a function in IR form. +// +type register struct { + anInstruction + typ types.Type // type of virtual register + referrers []Instruction +} + +type node struct { + source ast.Node + id ID +} + +func (n *node) setID(id ID) { n.id = id } +func (n node) ID() ID { return n.id } + +func (n *node) setSource(source ast.Node) { n.source = source } +func (n *node) Source() ast.Node { return n.source } + +func (n *node) Pos() token.Pos { + if n.source != nil { + return n.source.Pos() + } + return token.NoPos +} + +// anInstruction is a mix-in embedded by all Instructions. +// It provides the implementations of the Block and setBlock methods. +type anInstruction struct { + node + block *BasicBlock // the basic block of this instruction +} + +// CallCommon is contained by Go, Defer and Call to hold the +// common parts of a function or method call. +// +// Each CallCommon exists in one of two modes, function call and +// interface method invocation, or "call" and "invoke" for short. +// +// 1. "call" mode: when Method is nil (!IsInvoke), a CallCommon +// represents an ordinary function call of the value in Value, +// which may be a *Builtin, a *Function or any other value of kind +// 'func'. +// +// Value may be one of: +// (a) a *Function, indicating a statically dispatched call +// to a package-level function, an anonymous function, or +// a method of a named type. +// (b) a *MakeClosure, indicating an immediately applied +// function literal with free variables. +// (c) a *Builtin, indicating a statically dispatched call +// to a built-in function. +// (d) any other value, indicating a dynamically dispatched +// function call. +// StaticCallee returns the identity of the callee in cases +// (a) and (b), nil otherwise. +// +// Args contains the arguments to the call. If Value is a method, +// Args[0] contains the receiver parameter. +// +// Example printed form: +// t3 = Call <()> println t1 t2 +// Go t3 +// Defer t3 +// +// 2. "invoke" mode: when Method is non-nil (IsInvoke), a CallCommon +// represents a dynamically dispatched call to an interface method. +// In this mode, Value is the interface value and Method is the +// interface's abstract method. Note: an abstract method may be +// shared by multiple interfaces due to embedding; Value.Type() +// provides the specific interface used for this call. +// +// Value is implicitly supplied to the concrete method implementation +// as the receiver parameter; in other words, Args[0] holds not the +// receiver but the first true argument. +// +// Example printed form: +// t6 = Invoke t5.String +// GoInvoke t4.Bar t2 +// DeferInvoke t4.Bar t2 +// +// For all calls to variadic functions (Signature().Variadic()), +// the last element of Args is a slice. +// +type CallCommon struct { + Value Value // receiver (invoke mode) or func value (call mode) + Method *types.Func // abstract method (invoke mode) + Args []Value // actual parameters (in static method call, includes receiver) + Results Value +} + +// IsInvoke returns true if this call has "invoke" (not "call") mode. +func (c *CallCommon) IsInvoke() bool { + return c.Method != nil +} + +// Signature returns the signature of the called function. +// +// For an "invoke"-mode call, the signature of the interface method is +// returned. +// +// In either "call" or "invoke" mode, if the callee is a method, its +// receiver is represented by sig.Recv, not sig.Params().At(0). +// +func (c *CallCommon) Signature() *types.Signature { + if c.Method != nil { + return c.Method.Type().(*types.Signature) + } + return c.Value.Type().Underlying().(*types.Signature) +} + +// StaticCallee returns the callee if this is a trivially static +// "call"-mode call to a function. +func (c *CallCommon) StaticCallee() *Function { + switch fn := c.Value.(type) { + case *Function: + return fn + case *MakeClosure: + return fn.Fn.(*Function) + } + return nil +} + +// Description returns a description of the mode of this call suitable +// for a user interface, e.g., "static method call". +func (c *CallCommon) Description() string { + switch fn := c.Value.(type) { + case *Builtin: + return "built-in function call" + case *MakeClosure: + return "static function closure call" + case *Function: + if fn.Signature.Recv() != nil { + return "static method call" + } + return "static function call" + } + if c.IsInvoke() { + return "dynamic method call" // ("invoke" mode) + } + return "dynamic function call" +} + +// The CallInstruction interface, implemented by *Go, *Defer and *Call, +// exposes the common parts of function-calling instructions, +// yet provides a way back to the Value defined by *Call alone. +// +type CallInstruction interface { + Instruction + Common() *CallCommon // returns the common parts of the call + Value() *Call +} + +func (s *Call) Common() *CallCommon { return &s.Call } +func (s *Defer) Common() *CallCommon { return &s.Call } +func (s *Go) Common() *CallCommon { return &s.Call } + +func (s *Call) Value() *Call { return s } +func (s *Defer) Value() *Call { return nil } +func (s *Go) Value() *Call { return nil } + +func (v *Builtin) Type() types.Type { return v.sig } +func (v *Builtin) Name() string { return v.name } +func (*Builtin) Referrers() *[]Instruction { return nil } +func (v *Builtin) Pos() token.Pos { return token.NoPos } +func (v *Builtin) Object() types.Object { return types.Universe.Lookup(v.name) } +func (v *Builtin) Parent() *Function { return nil } + +func (v *FreeVar) Type() types.Type { return v.typ } +func (v *FreeVar) Name() string { return v.name } +func (v *FreeVar) Referrers() *[]Instruction { return &v.referrers } +func (v *FreeVar) Parent() *Function { return v.parent } + +func (v *Global) Type() types.Type { return v.typ } +func (v *Global) Name() string { return v.name } +func (v *Global) Parent() *Function { return nil } +func (v *Global) Referrers() *[]Instruction { return nil } +func (v *Global) Token() token.Token { return token.VAR } +func (v *Global) Object() types.Object { return v.object } +func (v *Global) String() string { return v.RelString(nil) } +func (v *Global) Package() *Package { return v.Pkg } +func (v *Global) RelString(from *types.Package) string { return relString(v, from) } + +func (v *Function) Name() string { return v.name } +func (v *Function) Type() types.Type { return v.Signature } +func (v *Function) Token() token.Token { return token.FUNC } +func (v *Function) Object() types.Object { return v.object } +func (v *Function) String() string { return v.RelString(nil) } +func (v *Function) Package() *Package { return v.Pkg } +func (v *Function) Parent() *Function { return v.parent } +func (v *Function) Referrers() *[]Instruction { + if v.parent != nil { + return &v.referrers + } + return nil +} + +func (v *Parameter) Object() types.Object { return v.object } + +func (v *Alloc) Type() types.Type { return v.typ } +func (v *Alloc) Referrers() *[]Instruction { return &v.referrers } + +func (v *register) Type() types.Type { return v.typ } +func (v *register) setType(typ types.Type) { v.typ = typ } +func (v *register) Name() string { return fmt.Sprintf("t%d", v.id) } +func (v *register) Referrers() *[]Instruction { return &v.referrers } + +func (v *anInstruction) Parent() *Function { return v.block.parent } +func (v *anInstruction) Block() *BasicBlock { return v.block } +func (v *anInstruction) setBlock(block *BasicBlock) { v.block = block } +func (v *anInstruction) Referrers() *[]Instruction { return nil } + +func (t *Type) Name() string { return t.object.Name() } +func (t *Type) Pos() token.Pos { return t.object.Pos() } +func (t *Type) Type() types.Type { return t.object.Type() } +func (t *Type) Token() token.Token { return token.TYPE } +func (t *Type) Object() types.Object { return t.object } +func (t *Type) String() string { return t.RelString(nil) } +func (t *Type) Package() *Package { return t.pkg } +func (t *Type) RelString(from *types.Package) string { return relString(t, from) } + +func (c *NamedConst) Name() string { return c.object.Name() } +func (c *NamedConst) Pos() token.Pos { return c.object.Pos() } +func (c *NamedConst) String() string { return c.RelString(nil) } +func (c *NamedConst) Type() types.Type { return c.object.Type() } +func (c *NamedConst) Token() token.Token { return token.CONST } +func (c *NamedConst) Object() types.Object { return c.object } +func (c *NamedConst) Package() *Package { return c.pkg } +func (c *NamedConst) RelString(from *types.Package) string { return relString(c, from) } + +// Func returns the package-level function of the specified name, +// or nil if not found. +// +func (p *Package) Func(name string) (f *Function) { + f, _ = p.Members[name].(*Function) + return +} + +// Var returns the package-level variable of the specified name, +// or nil if not found. +// +func (p *Package) Var(name string) (g *Global) { + g, _ = p.Members[name].(*Global) + return +} + +// Const returns the package-level constant of the specified name, +// or nil if not found. +// +func (p *Package) Const(name string) (c *NamedConst) { + c, _ = p.Members[name].(*NamedConst) + return +} + +// Type returns the package-level type of the specified name, +// or nil if not found. +// +func (p *Package) Type(name string) (t *Type) { + t, _ = p.Members[name].(*Type) + return +} + +func (s *DebugRef) Pos() token.Pos { return s.Expr.Pos() } + +// Operands. + +func (v *Alloc) Operands(rands []*Value) []*Value { + return rands +} + +func (v *BinOp) Operands(rands []*Value) []*Value { + return append(rands, &v.X, &v.Y) +} + +func (c *CallCommon) Operands(rands []*Value) []*Value { + rands = append(rands, &c.Value) + for i := range c.Args { + rands = append(rands, &c.Args[i]) + } + return rands +} + +func (s *Go) Operands(rands []*Value) []*Value { + return s.Call.Operands(rands) +} + +func (s *Call) Operands(rands []*Value) []*Value { + return s.Call.Operands(rands) +} + +func (s *Defer) Operands(rands []*Value) []*Value { + return s.Call.Operands(rands) +} + +func (v *ChangeInterface) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + +func (v *ChangeType) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + +func (v *Convert) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + +func (s *DebugRef) Operands(rands []*Value) []*Value { + return append(rands, &s.X) +} + +func (v *Extract) Operands(rands []*Value) []*Value { + return append(rands, &v.Tuple) +} + +func (v *Field) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + +func (v *FieldAddr) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + +func (s *If) Operands(rands []*Value) []*Value { + return append(rands, &s.Cond) +} + +func (s *ConstantSwitch) Operands(rands []*Value) []*Value { + rands = append(rands, &s.Tag) + for i := range s.Conds { + rands = append(rands, &s.Conds[i]) + } + return rands +} + +func (s *TypeSwitch) Operands(rands []*Value) []*Value { + rands = append(rands, &s.Tag) + return rands +} + +func (v *Index) Operands(rands []*Value) []*Value { + return append(rands, &v.X, &v.Index) +} + +func (v *IndexAddr) Operands(rands []*Value) []*Value { + return append(rands, &v.X, &v.Index) +} + +func (*Jump) Operands(rands []*Value) []*Value { + return rands +} + +func (*Unreachable) Operands(rands []*Value) []*Value { + return rands +} + +func (v *MapLookup) Operands(rands []*Value) []*Value { + return append(rands, &v.X, &v.Index) +} + +func (v *StringLookup) Operands(rands []*Value) []*Value { + return append(rands, &v.X, &v.Index) +} + +func (v *MakeChan) Operands(rands []*Value) []*Value { + return append(rands, &v.Size) +} + +func (v *MakeClosure) Operands(rands []*Value) []*Value { + rands = append(rands, &v.Fn) + for i := range v.Bindings { + rands = append(rands, &v.Bindings[i]) + } + return rands +} + +func (v *MakeInterface) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + +func (v *MakeMap) Operands(rands []*Value) []*Value { + return append(rands, &v.Reserve) +} + +func (v *MakeSlice) Operands(rands []*Value) []*Value { + return append(rands, &v.Len, &v.Cap) +} + +func (v *MapUpdate) Operands(rands []*Value) []*Value { + return append(rands, &v.Map, &v.Key, &v.Value) +} + +func (v *Next) Operands(rands []*Value) []*Value { + return append(rands, &v.Iter) +} + +func (s *Panic) Operands(rands []*Value) []*Value { + return append(rands, &s.X) +} + +func (v *Sigma) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + +func (v *Phi) Operands(rands []*Value) []*Value { + for i := range v.Edges { + rands = append(rands, &v.Edges[i]) + } + return rands +} + +func (v *Range) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + +func (s *Return) Operands(rands []*Value) []*Value { + for i := range s.Results { + rands = append(rands, &s.Results[i]) + } + return rands +} + +func (*RunDefers) Operands(rands []*Value) []*Value { + return rands +} + +func (v *Select) Operands(rands []*Value) []*Value { + for i := range v.States { + rands = append(rands, &v.States[i].Chan, &v.States[i].Send) + } + return rands +} + +func (s *Send) Operands(rands []*Value) []*Value { + return append(rands, &s.Chan, &s.X) +} + +func (recv *Recv) Operands(rands []*Value) []*Value { + return append(rands, &recv.Chan) +} + +func (v *Slice) Operands(rands []*Value) []*Value { + return append(rands, &v.X, &v.Low, &v.High, &v.Max) +} + +func (s *Store) Operands(rands []*Value) []*Value { + return append(rands, &s.Addr, &s.Val) +} + +func (s *BlankStore) Operands(rands []*Value) []*Value { + return append(rands, &s.Val) +} + +func (v *TypeAssert) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + +func (v *UnOp) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + +func (v *Load) Operands(rands []*Value) []*Value { + return append(rands, &v.X) +} + +// Non-Instruction Values: +func (v *Builtin) Operands(rands []*Value) []*Value { return rands } +func (v *FreeVar) Operands(rands []*Value) []*Value { return rands } +func (v *Const) Operands(rands []*Value) []*Value { return rands } +func (v *Function) Operands(rands []*Value) []*Value { return rands } +func (v *Global) Operands(rands []*Value) []*Value { return rands } +func (v *Parameter) Operands(rands []*Value) []*Value { return rands } diff --git a/vendor/honnef.co/go/tools/ssa/staticcheck.conf b/vendor/honnef.co/go/tools/ir/staticcheck.conf similarity index 100% rename from vendor/honnef.co/go/tools/ssa/staticcheck.conf rename to vendor/honnef.co/go/tools/ir/staticcheck.conf diff --git a/vendor/honnef.co/go/tools/ir/util.go b/vendor/honnef.co/go/tools/ir/util.go new file mode 100644 index 00000000000..df0f8bf971d --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/util.go @@ -0,0 +1,89 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// This file defines a number of miscellaneous utility functions. + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + "io" + "os" + + "golang.org/x/tools/go/ast/astutil" +) + +//// AST utilities + +func unparen(e ast.Expr) ast.Expr { return astutil.Unparen(e) } + +// isBlankIdent returns true iff e is an Ident with name "_". +// They have no associated types.Object, and thus no type. +// +func isBlankIdent(e ast.Expr) bool { + id, ok := e.(*ast.Ident) + return ok && id.Name == "_" +} + +//// Type utilities. Some of these belong in go/types. + +// isPointer returns true for types whose underlying type is a pointer. +func isPointer(typ types.Type) bool { + _, ok := typ.Underlying().(*types.Pointer) + return ok +} + +func isInterface(T types.Type) bool { return types.IsInterface(T) } + +// deref returns a pointer's element type; otherwise it returns typ. +func deref(typ types.Type) types.Type { + if p, ok := typ.Underlying().(*types.Pointer); ok { + return p.Elem() + } + return typ +} + +// recvType returns the receiver type of method obj. +func recvType(obj *types.Func) types.Type { + return obj.Type().(*types.Signature).Recv().Type() +} + +// logStack prints the formatted "start" message to stderr and +// returns a closure that prints the corresponding "end" message. +// Call using 'defer logStack(...)()' to show builder stack on panic. +// Don't forget trailing parens! +// +func logStack(format string, args ...interface{}) func() { + msg := fmt.Sprintf(format, args...) + io.WriteString(os.Stderr, msg) + io.WriteString(os.Stderr, "\n") + return func() { + io.WriteString(os.Stderr, msg) + io.WriteString(os.Stderr, " end\n") + } +} + +// newVar creates a 'var' for use in a types.Tuple. +func newVar(name string, typ types.Type) *types.Var { + return types.NewParam(token.NoPos, nil, name, typ) +} + +// anonVar creates an anonymous 'var' for use in a types.Tuple. +func anonVar(typ types.Type) *types.Var { + return newVar("", typ) +} + +var lenResults = types.NewTuple(anonVar(tInt)) + +// makeLen returns the len builtin specialized to type func(T)int. +func makeLen(T types.Type) *Builtin { + lenParams := types.NewTuple(anonVar(T)) + return &Builtin{ + name: "len", + sig: types.NewSignature(nil, lenParams, lenResults, false), + } +} diff --git a/vendor/honnef.co/go/tools/ir/wrappers.go b/vendor/honnef.co/go/tools/ir/wrappers.go new file mode 100644 index 00000000000..7dd33474806 --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/wrappers.go @@ -0,0 +1,292 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package ir + +// This file defines synthesis of Functions that delegate to declared +// methods; they come in three kinds: +// +// (1) wrappers: methods that wrap declared methods, performing +// implicit pointer indirections and embedded field selections. +// +// (2) thunks: funcs that wrap declared methods. Like wrappers, +// thunks perform indirections and field selections. The thunk's +// first parameter is used as the receiver for the method call. +// +// (3) bounds: funcs that wrap declared methods. The bound's sole +// free variable, supplied by a closure, is used as the receiver +// for the method call. No indirections or field selections are +// performed since they can be done before the call. + +import ( + "fmt" + + "go/types" +) + +// -- wrappers ----------------------------------------------------------- + +// makeWrapper returns a synthetic method that delegates to the +// declared method denoted by meth.Obj(), first performing any +// necessary pointer indirections or field selections implied by meth. +// +// The resulting method's receiver type is meth.Recv(). +// +// This function is versatile but quite subtle! Consider the +// following axes of variation when making changes: +// - optional receiver indirection +// - optional implicit field selections +// - meth.Obj() may denote a concrete or an interface method +// - the result may be a thunk or a wrapper. +// +// EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu) +// +func makeWrapper(prog *Program, sel *types.Selection) *Function { + obj := sel.Obj().(*types.Func) // the declared function + sig := sel.Type().(*types.Signature) // type of this wrapper + + var recv *types.Var // wrapper's receiver or thunk's params[0] + name := obj.Name() + var description string + var start int // first regular param + if sel.Kind() == types.MethodExpr { + name += "$thunk" + description = "thunk" + recv = sig.Params().At(0) + start = 1 + } else { + description = "wrapper" + recv = sig.Recv() + } + + description = fmt.Sprintf("%s for %s", description, sel.Obj()) + if prog.mode&LogSource != 0 { + defer logStack("make %s to (%s)", description, recv.Type())() + } + fn := &Function{ + name: name, + method: sel, + object: obj, + Signature: sig, + Synthetic: description, + Prog: prog, + functionBody: new(functionBody), + } + fn.initHTML(prog.PrintFunc) + fn.startBody() + fn.addSpilledParam(recv, nil) + createParams(fn, start) + + indices := sel.Index() + + var v Value = fn.Locals[0] // spilled receiver + if isPointer(sel.Recv()) { + v = emitLoad(fn, v, nil) + + // For simple indirection wrappers, perform an informative nil-check: + // "value method (T).f called using nil *T pointer" + if len(indices) == 1 && !isPointer(recvType(obj)) { + var c Call + c.Call.Value = &Builtin{ + name: "ir:wrapnilchk", + sig: types.NewSignature(nil, + types.NewTuple(anonVar(sel.Recv()), anonVar(tString), anonVar(tString)), + types.NewTuple(anonVar(sel.Recv())), false), + } + c.Call.Args = []Value{ + v, + emitConst(fn, stringConst(deref(sel.Recv()).String())), + emitConst(fn, stringConst(sel.Obj().Name())), + } + c.setType(v.Type()) + v = fn.emit(&c, nil) + } + } + + // Invariant: v is a pointer, either + // value of *A receiver param, or + // address of A spilled receiver. + + // We use pointer arithmetic (FieldAddr possibly followed by + // Load) in preference to value extraction (Field possibly + // preceded by Load). + + v = emitImplicitSelections(fn, v, indices[:len(indices)-1], nil) + + // Invariant: v is a pointer, either + // value of implicit *C field, or + // address of implicit C field. + + var c Call + if r := recvType(obj); !isInterface(r) { // concrete method + if !isPointer(r) { + v = emitLoad(fn, v, nil) + } + c.Call.Value = prog.declaredFunc(obj) + c.Call.Args = append(c.Call.Args, v) + } else { + c.Call.Method = obj + c.Call.Value = emitLoad(fn, v, nil) + } + for _, arg := range fn.Params[1:] { + c.Call.Args = append(c.Call.Args, arg) + } + emitTailCall(fn, &c, nil) + fn.finishBody() + return fn +} + +// createParams creates parameters for wrapper method fn based on its +// Signature.Params, which do not include the receiver. +// start is the index of the first regular parameter to use. +// +func createParams(fn *Function, start int) { + tparams := fn.Signature.Params() + for i, n := start, tparams.Len(); i < n; i++ { + fn.addParamObj(tparams.At(i), nil) + } +} + +// -- bounds ----------------------------------------------------------- + +// makeBound returns a bound method wrapper (or "bound"), a synthetic +// function that delegates to a concrete or interface method denoted +// by obj. The resulting function has no receiver, but has one free +// variable which will be used as the method's receiver in the +// tail-call. +// +// Use MakeClosure with such a wrapper to construct a bound method +// closure. e.g.: +// +// type T int or: type T interface { meth() } +// func (t T) meth() +// var t T +// f := t.meth +// f() // calls t.meth() +// +// f is a closure of a synthetic wrapper defined as if by: +// +// f := func() { return t.meth() } +// +// Unlike makeWrapper, makeBound need perform no indirection or field +// selections because that can be done before the closure is +// constructed. +// +// EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu) +// +func makeBound(prog *Program, obj *types.Func) *Function { + prog.methodsMu.Lock() + defer prog.methodsMu.Unlock() + fn, ok := prog.bounds[obj] + if !ok { + description := fmt.Sprintf("bound method wrapper for %s", obj) + if prog.mode&LogSource != 0 { + defer logStack("%s", description)() + } + fn = &Function{ + name: obj.Name() + "$bound", + object: obj, + Signature: changeRecv(obj.Type().(*types.Signature), nil), // drop receiver + Synthetic: description, + Prog: prog, + functionBody: new(functionBody), + } + fn.initHTML(prog.PrintFunc) + + fv := &FreeVar{name: "recv", typ: recvType(obj), parent: fn} + fn.FreeVars = []*FreeVar{fv} + fn.startBody() + createParams(fn, 0) + var c Call + + if !isInterface(recvType(obj)) { // concrete + c.Call.Value = prog.declaredFunc(obj) + c.Call.Args = []Value{fv} + } else { + c.Call.Value = fv + c.Call.Method = obj + } + for _, arg := range fn.Params { + c.Call.Args = append(c.Call.Args, arg) + } + emitTailCall(fn, &c, nil) + fn.finishBody() + + prog.bounds[obj] = fn + } + return fn +} + +// -- thunks ----------------------------------------------------------- + +// makeThunk returns a thunk, a synthetic function that delegates to a +// concrete or interface method denoted by sel.Obj(). The resulting +// function has no receiver, but has an additional (first) regular +// parameter. +// +// Precondition: sel.Kind() == types.MethodExpr. +// +// type T int or: type T interface { meth() } +// func (t T) meth() +// f := T.meth +// var t T +// f(t) // calls t.meth() +// +// f is a synthetic wrapper defined as if by: +// +// f := func(t T) { return t.meth() } +// +// TODO(adonovan): opt: currently the stub is created even when used +// directly in a function call: C.f(i, 0). This is less efficient +// than inlining the stub. +// +// EXCLUSIVE_LOCKS_ACQUIRED(meth.Prog.methodsMu) +// +func makeThunk(prog *Program, sel *types.Selection) *Function { + if sel.Kind() != types.MethodExpr { + panic(sel) + } + + key := selectionKey{ + kind: sel.Kind(), + recv: sel.Recv(), + obj: sel.Obj(), + index: fmt.Sprint(sel.Index()), + indirect: sel.Indirect(), + } + + prog.methodsMu.Lock() + defer prog.methodsMu.Unlock() + + // Canonicalize key.recv to avoid constructing duplicate thunks. + canonRecv, ok := prog.canon.At(key.recv).(types.Type) + if !ok { + canonRecv = key.recv + prog.canon.Set(key.recv, canonRecv) + } + key.recv = canonRecv + + fn, ok := prog.thunks[key] + if !ok { + fn = makeWrapper(prog, sel) + if fn.Signature.Recv() != nil { + panic(fn) // unexpected receiver + } + prog.thunks[key] = fn + } + return fn +} + +func changeRecv(s *types.Signature, recv *types.Var) *types.Signature { + return types.NewSignature(recv, s.Params(), s.Results(), s.Variadic()) +} + +// selectionKey is like types.Selection but a usable map key. +type selectionKey struct { + kind types.SelectionKind + recv types.Type // canonicalized via Program.canon + obj types.Object + index string + indirect bool +} diff --git a/vendor/honnef.co/go/tools/ir/write.go b/vendor/honnef.co/go/tools/ir/write.go new file mode 100644 index 00000000000..b936bc98528 --- /dev/null +++ b/vendor/honnef.co/go/tools/ir/write.go @@ -0,0 +1,5 @@ +package ir + +func NewJump(parent *BasicBlock) *Jump { + return &Jump{anInstruction{block: parent}, ""} +} diff --git a/vendor/honnef.co/go/tools/lint/lint.go b/vendor/honnef.co/go/tools/lint/lint.go index de5a8f1288d..1a70e0c298e 100644 --- a/vendor/honnef.co/go/tools/lint/lint.go +++ b/vendor/honnef.co/go/tools/lint/lint.go @@ -3,6 +3,7 @@ package lint // import "honnef.co/go/tools/lint" import ( "bytes" + "encoding/gob" "fmt" "go/scanner" "go/token" @@ -17,6 +18,7 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/packages" "honnef.co/go/tools/config" + "honnef.co/go/tools/internal/cache" ) type Documentation struct { @@ -62,7 +64,7 @@ type LineIgnore struct { Line int Checks []string Matched bool - Pos token.Pos + Pos token.Position } func (li *LineIgnore) Match(p Problem) bool { @@ -119,6 +121,21 @@ type Problem struct { Message string Check string Severity Severity + Related []Related +} + +type Related struct { + Pos token.Position + End token.Position + Message string +} + +func (p Problem) Equal(o Problem) bool { + return p.Pos == o.Pos && + p.End == o.End && + p.Message == o.Message && + p.Check == o.Check && + p.Severity == o.Severity } func (p *Problem) String() string { @@ -132,6 +149,7 @@ type Linter struct { GoVersion int Config config.Config Stats Stats + RepeatAnalyzers uint } type CumulativeChecker interface { @@ -184,6 +202,7 @@ func (l *Linter) Lint(cfg *packages.Config, patterns []string) ([]Problem, error return nil, err } r.goVersion = l.GoVersion + r.repeatAnalyzers = l.RepeatAnalyzers pkgs, err := r.Run(cfg, patterns, allowedAnalyzers, hasCumulative) if err != nil { @@ -264,10 +283,12 @@ func (l *Linter) Lint(cfg *packages.Config, patterns []string) ([]Problem, error } atomic.StoreUint32(&r.stats.State, StateCumulative) - var problems []Problem for _, cum := range l.CumulativeCheckers { for _, res := range cum.Result() { pkg := tpkgToPkg[res.Pkg()] + if pkg == nil { + panic(fmt.Sprintf("analyzer %s flagged object %s in package %s, a package that we aren't tracking", cum.Analyzer(), res, res.Pkg())) + } allowedChecks := FilterChecks(allowedAnalyzers, pkg.cfg.Merge(l.Config).Checks) if allowedChecks[cum.Analyzer().Name] { pos := DisplayPosition(pkg.Fset, res.Pos()) @@ -278,21 +299,51 @@ func (l *Linter) Lint(cfg *packages.Config, patterns []string) ([]Problem, error continue } p := cum.ProblemObject(pkg.Fset, res) - problems = append(problems, p) + pkg.problems = append(pkg.problems, p) } } } + for _, pkg := range pkgs { + if !pkg.fromSource { + // Don't cache packages that we loaded from the cache + continue + } + cpkg := cachedPackage{ + Problems: pkg.problems, + Ignores: pkg.ignores, + Config: pkg.cfg, + } + buf := &bytes.Buffer{} + if err := gob.NewEncoder(buf).Encode(cpkg); err != nil { + return nil, err + } + id := cache.Subkey(pkg.actionID, "data "+r.problemsCacheKey) + if err := r.cache.PutBytes(id, buf.Bytes()); err != nil { + return nil, err + } + } + + var problems []Problem + // Deduplicate line ignores. When U1000 processes a package and + // its test variant, it will only emit a single problem for an + // unused object, not two problems. We will, however, have two + // line ignores, one per package. Without deduplication, one line + // ignore will be marked as matched, while the other one won't, + // subsequently reporting a "this linter directive didn't match + // anything" error. + ignores := map[token.Position]Ignore{} for _, pkg := range pkgs { for _, ig := range pkg.ignores { - for i := range pkg.problems { - p := &pkg.problems[i] - if ig.Match(*p) { - p.Severity = Ignored + if lig, ok := ig.(*LineIgnore); ok { + ig = ignores[lig.Pos] + if ig == nil { + ignores[lig.Pos] = lig + ig = lig } } - for i := range problems { - p := &problems[i] + for i := range pkg.problems { + p := &pkg.problems[i] if ig.Match(*p) { p.Severity = Ignored } @@ -318,6 +369,7 @@ func (l *Linter) Lint(cfg *packages.Config, patterns []string) ([]Problem, error if !ok { continue } + ig = ignores[ig.Pos].(*LineIgnore) if ig.Matched { continue } @@ -338,7 +390,7 @@ func (l *Linter) Lint(cfg *packages.Config, patterns []string) ([]Problem, error continue } p := Problem{ - Pos: DisplayPosition(pkg.Fset, ig.Pos), + Pos: ig.Pos, Message: "this linter directive didn't match anything; should it be removed?", Check: "", } @@ -372,7 +424,7 @@ func (l *Linter) Lint(cfg *packages.Config, patterns []string) ([]Problem, error for i, p := range problems[1:] { // We may encounter duplicate problems because one file // can be part of many packages. - if problems[i] != p { + if !problems[i].Equal(p) { out = append(out, p) } } @@ -422,10 +474,6 @@ func FilterChecks(allChecks []*analysis.Analyzer, checks []string) map[string]bo return allowedChecks } -type Positioner interface { - Pos() token.Pos -} - func DisplayPosition(fset *token.FileSet, p token.Pos) token.Position { if p == token.NoPos { return token.Position{} diff --git a/vendor/honnef.co/go/tools/lint/lintdsl/lintdsl.go b/vendor/honnef.co/go/tools/lint/lintdsl/lintdsl.go index 3b939e95f2f..4408aff25e4 100644 --- a/vendor/honnef.co/go/tools/lint/lintdsl/lintdsl.go +++ b/vendor/honnef.co/go/tools/lint/lintdsl/lintdsl.go @@ -4,283 +4,14 @@ package lintdsl import ( "bytes" - "flag" "fmt" "go/ast" - "go/constant" - "go/printer" - "go/token" - "go/types" - "strings" + "go/format" "golang.org/x/tools/go/analysis" - "honnef.co/go/tools/facts" - "honnef.co/go/tools/lint" - "honnef.co/go/tools/ssa" + "honnef.co/go/tools/pattern" ) -type packager interface { - Package() *ssa.Package -} - -func CallName(call *ssa.CallCommon) string { - if call.IsInvoke() { - return "" - } - switch v := call.Value.(type) { - case *ssa.Function: - fn, ok := v.Object().(*types.Func) - if !ok { - return "" - } - return lint.FuncName(fn) - case *ssa.Builtin: - return v.Name() - } - return "" -} - -func IsCallTo(call *ssa.CallCommon, name string) bool { return CallName(call) == name } -func IsType(T types.Type, name string) bool { return types.TypeString(T, nil) == name } - -func FilterDebug(instr []ssa.Instruction) []ssa.Instruction { - var out []ssa.Instruction - for _, ins := range instr { - if _, ok := ins.(*ssa.DebugRef); !ok { - out = append(out, ins) - } - } - return out -} - -func IsExample(fn *ssa.Function) bool { - if !strings.HasPrefix(fn.Name(), "Example") { - return false - } - f := fn.Prog.Fset.File(fn.Pos()) - if f == nil { - return false - } - return strings.HasSuffix(f.Name(), "_test.go") -} - -func IsPointerLike(T types.Type) bool { - switch T := T.Underlying().(type) { - case *types.Interface, *types.Chan, *types.Map, *types.Signature, *types.Pointer: - return true - case *types.Basic: - return T.Kind() == types.UnsafePointer - } - return false -} - -func IsIdent(expr ast.Expr, ident string) bool { - id, ok := expr.(*ast.Ident) - return ok && id.Name == ident -} - -// isBlank returns whether id is the blank identifier "_". -// If id == nil, the answer is false. -func IsBlank(id ast.Expr) bool { - ident, _ := id.(*ast.Ident) - return ident != nil && ident.Name == "_" -} - -func IsIntLiteral(expr ast.Expr, literal string) bool { - lit, ok := expr.(*ast.BasicLit) - return ok && lit.Kind == token.INT && lit.Value == literal -} - -// Deprecated: use IsIntLiteral instead -func IsZero(expr ast.Expr) bool { - return IsIntLiteral(expr, "0") -} - -func IsOfType(pass *analysis.Pass, expr ast.Expr, name string) bool { - return IsType(pass.TypesInfo.TypeOf(expr), name) -} - -func IsInTest(pass *analysis.Pass, node lint.Positioner) bool { - // FIXME(dh): this doesn't work for global variables with - // initializers - f := pass.Fset.File(node.Pos()) - return f != nil && strings.HasSuffix(f.Name(), "_test.go") -} - -func IsInMain(pass *analysis.Pass, node lint.Positioner) bool { - if node, ok := node.(packager); ok { - return node.Package().Pkg.Name() == "main" - } - return pass.Pkg.Name() == "main" -} - -func SelectorName(pass *analysis.Pass, expr *ast.SelectorExpr) string { - info := pass.TypesInfo - sel := info.Selections[expr] - if sel == nil { - if x, ok := expr.X.(*ast.Ident); ok { - pkg, ok := info.ObjectOf(x).(*types.PkgName) - if !ok { - // This shouldn't happen - return fmt.Sprintf("%s.%s", x.Name, expr.Sel.Name) - } - return fmt.Sprintf("%s.%s", pkg.Imported().Path(), expr.Sel.Name) - } - panic(fmt.Sprintf("unsupported selector: %v", expr)) - } - return fmt.Sprintf("(%s).%s", sel.Recv(), sel.Obj().Name()) -} - -func IsNil(pass *analysis.Pass, expr ast.Expr) bool { - return pass.TypesInfo.Types[expr].IsNil() -} - -func BoolConst(pass *analysis.Pass, expr ast.Expr) bool { - val := pass.TypesInfo.ObjectOf(expr.(*ast.Ident)).(*types.Const).Val() - return constant.BoolVal(val) -} - -func IsBoolConst(pass *analysis.Pass, expr ast.Expr) bool { - // We explicitly don't support typed bools because more often than - // not, custom bool types are used as binary enums and the - // explicit comparison is desired. - - ident, ok := expr.(*ast.Ident) - if !ok { - return false - } - obj := pass.TypesInfo.ObjectOf(ident) - c, ok := obj.(*types.Const) - if !ok { - return false - } - basic, ok := c.Type().(*types.Basic) - if !ok { - return false - } - if basic.Kind() != types.UntypedBool && basic.Kind() != types.Bool { - return false - } - return true -} - -func ExprToInt(pass *analysis.Pass, expr ast.Expr) (int64, bool) { - tv := pass.TypesInfo.Types[expr] - if tv.Value == nil { - return 0, false - } - if tv.Value.Kind() != constant.Int { - return 0, false - } - return constant.Int64Val(tv.Value) -} - -func ExprToString(pass *analysis.Pass, expr ast.Expr) (string, bool) { - val := pass.TypesInfo.Types[expr].Value - if val == nil { - return "", false - } - if val.Kind() != constant.String { - return "", false - } - return constant.StringVal(val), true -} - -// Dereference returns a pointer's element type; otherwise it returns -// T. -func Dereference(T types.Type) types.Type { - if p, ok := T.Underlying().(*types.Pointer); ok { - return p.Elem() - } - return T -} - -// DereferenceR returns a pointer's element type; otherwise it returns -// T. If the element type is itself a pointer, DereferenceR will be -// applied recursively. -func DereferenceR(T types.Type) types.Type { - if p, ok := T.Underlying().(*types.Pointer); ok { - return DereferenceR(p.Elem()) - } - return T -} - -func IsGoVersion(pass *analysis.Pass, minor int) bool { - version := pass.Analyzer.Flags.Lookup("go").Value.(flag.Getter).Get().(int) - return version >= minor -} - -func CallNameAST(pass *analysis.Pass, call *ast.CallExpr) string { - switch fun := call.Fun.(type) { - case *ast.SelectorExpr: - fn, ok := pass.TypesInfo.ObjectOf(fun.Sel).(*types.Func) - if !ok { - return "" - } - return lint.FuncName(fn) - case *ast.Ident: - obj := pass.TypesInfo.ObjectOf(fun) - switch obj := obj.(type) { - case *types.Func: - return lint.FuncName(obj) - case *types.Builtin: - return obj.Name() - default: - return "" - } - default: - return "" - } -} - -func IsCallToAST(pass *analysis.Pass, node ast.Node, name string) bool { - call, ok := node.(*ast.CallExpr) - if !ok { - return false - } - return CallNameAST(pass, call) == name -} - -func IsCallToAnyAST(pass *analysis.Pass, node ast.Node, names ...string) bool { - for _, name := range names { - if IsCallToAST(pass, node, name) { - return true - } - } - return false -} - -func Render(pass *analysis.Pass, x interface{}) string { - var buf bytes.Buffer - if err := printer.Fprint(&buf, pass.Fset, x); err != nil { - panic(err) - } - return buf.String() -} - -func RenderArgs(pass *analysis.Pass, args []ast.Expr) string { - var ss []string - for _, arg := range args { - ss = append(ss, Render(pass, arg)) - } - return strings.Join(ss, ", ") -} - -func Preamble(f *ast.File) string { - cutoff := f.Package - if f.Doc != nil { - cutoff = f.Doc.Pos() - } - var out []string - for _, cmt := range f.Comments { - if cmt.Pos() >= cutoff { - break - } - out = append(out, cmt.Text()) - } - return strings.Join(out, "\n") -} - func Inspect(node ast.Node, fn func(node ast.Node) bool) { if node == nil { return @@ -288,113 +19,40 @@ func Inspect(node ast.Node, fn func(node ast.Node) bool) { ast.Inspect(node, fn) } -func GroupSpecs(fset *token.FileSet, specs []ast.Spec) [][]ast.Spec { - if len(specs) == 0 { - return nil - } - groups := make([][]ast.Spec, 1) - groups[0] = append(groups[0], specs[0]) - - for _, spec := range specs[1:] { - g := groups[len(groups)-1] - if fset.PositionFor(spec.Pos(), false).Line-1 != - fset.PositionFor(g[len(g)-1].End(), false).Line { - - groups = append(groups, nil) - } - - groups[len(groups)-1] = append(groups[len(groups)-1], spec) - } - - return groups -} - -func IsObject(obj types.Object, name string) bool { - var path string - if pkg := obj.Pkg(); pkg != nil { - path = pkg.Path() + "." - } - return path+obj.Name() == name -} - -type Field struct { - Var *types.Var - Tag string - Path []int -} - -// FlattenFields recursively flattens T and embedded structs, -// returning a list of fields. If multiple fields with the same name -// exist, all will be returned. -func FlattenFields(T *types.Struct) []Field { - return flattenFields(T, nil, nil) +func Match(pass *analysis.Pass, q pattern.Pattern, node ast.Node) (*pattern.Matcher, bool) { + // Note that we ignore q.Relevant – callers of Match usually use + // AST inspectors that already filter on nodes we're interested + // in. + m := &pattern.Matcher{TypesInfo: pass.TypesInfo} + ok := m.Match(q.Root, node) + return m, ok } -func flattenFields(T *types.Struct, path []int, seen map[types.Type]bool) []Field { - if seen == nil { - seen = map[types.Type]bool{} - } - if seen[T] { - return nil - } - seen[T] = true - var out []Field - for i := 0; i < T.NumFields(); i++ { - field := T.Field(i) - tag := T.Tag(i) - np := append(path[:len(path):len(path)], i) - if field.Anonymous() { - if s, ok := Dereference(field.Type()).Underlying().(*types.Struct); ok { - out = append(out, flattenFields(s, np, seen)...) - } - } else { - out = append(out, Field{field, tag, np}) - } +func MatchAndEdit(pass *analysis.Pass, before, after pattern.Pattern, node ast.Node) (*pattern.Matcher, []analysis.TextEdit, bool) { + m, ok := Match(pass, before, node) + if !ok { + return m, nil, false } - return out -} - -func File(pass *analysis.Pass, node lint.Positioner) *ast.File { - pass.Fset.PositionFor(node.Pos(), true) - m := pass.ResultOf[facts.TokenFile].(map[*token.File]*ast.File) - return m[pass.Fset.File(node.Pos())] -} - -// IsGenerated reports whether pos is in a generated file, It ignores -// //line directives. -func IsGenerated(pass *analysis.Pass, pos token.Pos) bool { - _, ok := Generator(pass, pos) - return ok + r := pattern.NodeToAST(after.Root, m.State) + buf := &bytes.Buffer{} + format.Node(buf, pass.Fset, r) + edit := []analysis.TextEdit{{ + Pos: node.Pos(), + End: node.End(), + NewText: buf.Bytes(), + }} + return m, edit, true } -// Generator returns the generator that generated the file containing -// pos. It ignores //line directives. -func Generator(pass *analysis.Pass, pos token.Pos) (facts.Generator, bool) { - file := pass.Fset.PositionFor(pos, false).Filename - m := pass.ResultOf[facts.Generated].(map[string]facts.Generator) - g, ok := m[file] - return g, ok -} - -func ReportfFG(pass *analysis.Pass, pos token.Pos, f string, args ...interface{}) { - file := lint.DisplayPosition(pass.Fset, pos).Filename - m := pass.ResultOf[facts.Generated].(map[string]facts.Generator) - if _, ok := m[file]; ok { - return +func Selector(x, sel string) *ast.SelectorExpr { + return &ast.SelectorExpr{ + X: &ast.Ident{Name: x}, + Sel: &ast.Ident{Name: sel}, } - pass.Reportf(pos, f, args...) } -func ReportNodef(pass *analysis.Pass, node ast.Node, format string, args ...interface{}) { - msg := fmt.Sprintf(format, args...) - pass.Report(analysis.Diagnostic{Pos: node.Pos(), End: node.End(), Message: msg}) -} - -func ReportNodefFG(pass *analysis.Pass, node ast.Node, format string, args ...interface{}) { - file := lint.DisplayPosition(pass.Fset, node.Pos()).Filename - m := pass.ResultOf[facts.Generated].(map[string]facts.Generator) - if _, ok := m[file]; ok { - return - } - ReportNodef(pass, node, format, args...) +// ExhaustiveTypeSwitch panics when called. It can be used to ensure +// that type switches are exhaustive. +func ExhaustiveTypeSwitch(v interface{}) { + panic(fmt.Sprintf("internal error: unhandled case %T", v)) } diff --git a/vendor/honnef.co/go/tools/lint/lintutil/format/format.go b/vendor/honnef.co/go/tools/lint/lintutil/format/format.go index 9385431f88b..b28f8885b87 100644 --- a/vendor/honnef.co/go/tools/lint/lintutil/format/format.go +++ b/vendor/honnef.co/go/tools/lint/lintutil/format/format.go @@ -39,7 +39,7 @@ func relativePositionString(pos token.Position) string { } type Statter interface { - Stats(total, errors, warnings int) + Stats(total, errors, warnings, ignored int) } type Formatter interface { @@ -51,7 +51,10 @@ type Text struct { } func (o Text) Format(p lint.Problem) { - fmt.Fprintf(o.W, "%v: %s\n", relativePositionString(p.Pos), p.String()) + fmt.Fprintf(o.W, "%s: %s\n", relativePositionString(p.Pos), p.String()) + for _, r := range p.Related { + fmt.Fprintf(o.W, "\t%s: %s\n", relativePositionString(r.Pos), r.Message) + } } type JSON struct { @@ -76,12 +79,18 @@ func (o JSON) Format(p lint.Problem) { Line int `json:"line"` Column int `json:"column"` } - jp := struct { - Code string `json:"code"` - Severity string `json:"severity,omitempty"` + type related struct { Location location `json:"location"` End location `json:"end"` Message string `json:"message"` + } + jp := struct { + Code string `json:"code"` + Severity string `json:"severity,omitempty"` + Location location `json:"location"` + End location `json:"end"` + Message string `json:"message"` + Related []related `json:"related,omitempty"` }{ Code: p.Check, Severity: severity(p.Severity), @@ -97,6 +106,21 @@ func (o JSON) Format(p lint.Problem) { }, Message: p.Message, } + for _, r := range p.Related { + jp.Related = append(jp.Related, related{ + Location: location{ + File: r.Pos.Filename, + Line: r.Pos.Line, + Column: r.Pos.Column, + }, + End: location{ + File: r.End.Filename, + Line: r.End.Line, + Column: r.End.Column, + }, + Message: r.Message, + }) + } _ = json.NewEncoder(o.W).Encode(jp) } @@ -123,13 +147,16 @@ func (o *Stylish) Format(p lint.Problem) { o.tw = tabwriter.NewWriter(o.W, 0, 4, 2, ' ', 0) } fmt.Fprintf(o.tw, " (%d, %d)\t%s\t%s\n", pos.Line, pos.Column, p.Check, p.Message) + for _, r := range p.Related { + fmt.Fprintf(o.tw, " (%d, %d)\t\t %s\n", r.Pos.Line, r.Pos.Column, r.Message) + } } -func (o *Stylish) Stats(total, errors, warnings int) { +func (o *Stylish) Stats(total, errors, warnings, ignored int) { if o.tw != nil { o.tw.Flush() fmt.Fprintln(o.W) } - fmt.Fprintf(o.W, " ✖ %d problems (%d errors, %d warnings)\n", - total, errors, warnings) + fmt.Fprintf(o.W, " ✖ %d problems (%d errors, %d warnings, %d ignored)\n", + total, errors, warnings, ignored) } diff --git a/vendor/honnef.co/go/tools/lint/lintutil/util.go b/vendor/honnef.co/go/tools/lint/lintutil/util.go index fe0279f921c..7c3dbdec193 100644 --- a/vendor/honnef.co/go/tools/lint/lintutil/util.go +++ b/vendor/honnef.co/go/tools/lint/lintutil/util.go @@ -23,7 +23,9 @@ import ( "runtime/pprof" "strconv" "strings" + "sync" "sync/atomic" + "time" "honnef.co/go/tools/config" "honnef.co/go/tools/internal/cache" @@ -114,6 +116,8 @@ func FlagSet(name string) *flag.FlagSet { flags.String("debug.memprofile", "", "Write memory profile to `file`") flags.Bool("debug.version", false, "Print detailed version information about this program") flags.Bool("debug.no-compile-errors", false, "Don't print compile errors") + flags.String("debug.measure-analyzers", "", "Write analysis measurements to `file`. `file` will be opened for appending if it already exists.") + flags.Uint("debug.repeat-analyzers", 0, "Run analyzers `num` times") checks := list{"inherit"} fail := list{"all"} @@ -153,6 +157,24 @@ func ProcessFlagSet(cs []*analysis.Analyzer, cums []lint.CumulativeChecker, fs * memProfile := fs.Lookup("debug.memprofile").Value.(flag.Getter).Get().(string) debugVersion := fs.Lookup("debug.version").Value.(flag.Getter).Get().(bool) debugNoCompile := fs.Lookup("debug.no-compile-errors").Value.(flag.Getter).Get().(bool) + debugRepeat := fs.Lookup("debug.repeat-analyzers").Value.(flag.Getter).Get().(uint) + + var measureAnalyzers func(analysis *analysis.Analyzer, pkg *lint.Package, d time.Duration) + if path := fs.Lookup("debug.measure-analyzers").Value.(flag.Getter).Get().(string); path != "" { + f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + log.Fatal(err) + } + + mu := &sync.Mutex{} + measureAnalyzers = func(analysis *analysis.Analyzer, pkg *lint.Package, d time.Duration) { + mu.Lock() + defer mu.Unlock() + if _, err := fmt.Fprintf(f, "%s\t%s\t%d\n", analysis.Name, pkg.ID, d.Nanoseconds()); err != nil { + log.Println("error writing analysis measurements:", err) + } + } + } cfg := config.Config{} cfg.Checks = *fs.Lookup("checks").Value.(*list) @@ -218,10 +240,12 @@ func ProcessFlagSet(cs []*analysis.Analyzer, cums []lint.CumulativeChecker, fs * } ps, err := Lint(cs, cums, fs.Args(), &Options{ - Tags: tags, - LintTests: tests, - GoVersion: goVersion, - Config: cfg, + Tags: tags, + LintTests: tests, + GoVersion: goVersion, + Config: cfg, + PrintAnalyzerMeasurement: measureAnalyzers, + RepeatAnalyzers: debugRepeat, }) if err != nil { fmt.Fprintln(os.Stderr, err) @@ -245,6 +269,7 @@ func ProcessFlagSet(cs []*analysis.Analyzer, cums []lint.CumulativeChecker, fs * total int errors int warnings int + ignored int ) fail := *fs.Lookup("fail").Value.(*list) @@ -262,6 +287,7 @@ func ProcessFlagSet(cs []*analysis.Analyzer, cums []lint.CumulativeChecker, fs * continue } if p.Severity == lint.Ignored && !showIgnored { + ignored++ continue } if shouldExit[p.Check] { @@ -273,7 +299,7 @@ func ProcessFlagSet(cs []*analysis.Analyzer, cums []lint.CumulativeChecker, fs * f.Format(p) } if f, ok := f.(format.Statter); ok { - f.Stats(total, errors, warnings) + f.Stats(total, errors, warnings, ignored) } if errors > 0 { exit(1) @@ -284,9 +310,11 @@ func ProcessFlagSet(cs []*analysis.Analyzer, cums []lint.CumulativeChecker, fs * type Options struct { Config config.Config - Tags string - LintTests bool - GoVersion int + Tags string + LintTests bool + GoVersion int + PrintAnalyzerMeasurement func(analysis *analysis.Analyzer, pkg *lint.Package, d time.Duration) + RepeatAnalyzers uint } func computeSalt() ([]byte, error) { @@ -325,7 +353,9 @@ func Lint(cs []*analysis.Analyzer, cums []lint.CumulativeChecker, paths []string CumulativeCheckers: cums, GoVersion: opt.GoVersion, Config: opt.Config, + RepeatAnalyzers: opt.RepeatAnalyzers, } + l.Stats.PrintAnalyzerMeasurement = opt.PrintAnalyzerMeasurement cfg := &packages.Config{} if opt.LintTests { cfg.Tests = true @@ -368,7 +398,8 @@ func Lint(cs []*analysis.Analyzer, cums []lint.CumulativeChecker, paths []string }() } - return l.Lint(cfg, paths) + ps, err := l.Lint(cfg, paths) + return ps, err } var posRe = regexp.MustCompile(`^(.+?):(\d+)(?::(\d+)?)?$`) @@ -390,3 +421,24 @@ func parsePos(pos string) token.Position { Column: col, } } + +func InitializeAnalyzers(docs map[string]*lint.Documentation, analyzers map[string]*analysis.Analyzer) map[string]*analysis.Analyzer { + out := make(map[string]*analysis.Analyzer, len(analyzers)) + for k, v := range analyzers { + vc := *v + out[k] = &vc + + vc.Name = k + doc, ok := docs[k] + if !ok { + panic(fmt.Sprintf("missing documentation for check %s", k)) + } + vc.Doc = doc.String() + if vc.Flags.Usage == nil { + fs := flag.NewFlagSet("", flag.PanicOnError) + fs.Var(NewVersionFlag(), "go", "Target Go version") + vc.Flags = *fs + } + } + return out +} diff --git a/vendor/honnef.co/go/tools/lint/runner.go b/vendor/honnef.co/go/tools/lint/runner.go index 3b22a63fa21..74106ced826 100644 --- a/vendor/honnef.co/go/tools/lint/runner.go +++ b/vendor/honnef.co/go/tools/lint/runner.go @@ -1,6 +1,30 @@ package lint /* +Package loading + +Conceptually, package loading in the runner can be imagined as a +graph-shaped work list. We iteratively pop off leaf nodes (packages +that have no unloaded dependencies) and load data from export data, +our cache, or source. + +Specifically, non-initial packages are loaded from export data and the +fact cache if possible, otherwise from source. Initial packages are +loaded from export data, the fact cache and the (problems, ignores, +config) cache if possible, otherwise from source. + +The appeal of this approach is that it is both simple to implement and +easily parallelizable. Each leaf node can be processed independently, +and new leaf nodes appear as their dependencies are being processed. + +The downside of this approach, however, is that we're doing more work +than necessary. Imagine an initial package A, which has the following +dependency chain: A->B->C->D – in the current implementation, we will +load all 4 packages. However, if package A can be loaded fully from +cached information, then none of its dependencies are necessary, and +we could avoid loading them. + + Parallelism Runner implements parallel processing of packages by spawning one @@ -19,6 +43,34 @@ all execute in parallel, while not wasting resources for long linear chains or trying to process more subgraphs in parallel than the system can handle. + +Caching + +We make use of several caches. These caches are Go's export data, our +facts cache, and our (problems, ignores, config) cache. + +Initial packages will either be loaded from a combination of all three +caches, or from source. Non-initial packages will either be loaded +from a combination of export data and facts cache, or from source. + +The facts cache is separate from the (problems, ignores, config) cache +because when we process non-initial packages, we generate facts, but +we discard problems and ignores. + +The facts cache is keyed by (package, analyzer), whereas the +(problems, ignores, config) cache is keyed by (package, list of +analyzes). The difference between the two exists because there are +only a handful of analyses that produce facts, but hundreds of +analyses that don't. Creating one cache entry per fact-generating +analysis is feasible, creating one cache entry per normal analysis has +significant performance and storage overheads. + +The downside of keying by the list of analyzes is, naturally, that a +change in list of analyzes changes the cache key. `staticcheck -checks +A` and `staticcheck -checks A,B` will therefore need their own cache +entries and not reuse each other's work. This problem does not affect +the facts cache. + */ import ( @@ -37,6 +89,7 @@ import ( "strings" "sync" "sync/atomic" + "time" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/packages" @@ -47,6 +100,11 @@ import ( "honnef.co/go/tools/loader" ) +func init() { + gob.Register(&FileIgnore{}) + gob.Register(&LineIgnore{}) +} + // If enabled, abuse of the go/analysis API will lead to panics const sanityCheck = true @@ -58,21 +116,43 @@ const sanityCheck = true // This may change unused's behavior, however, as it may observe fewer // interfaces from transitive dependencies. +// OPT(dh): every single package will have the same value for +// canClearTypes. We could move the Package.decUse method to runner to +// eliminate this field. This is probably not worth it, though. There +// are only thousands of packages, so the field only takes up +// kilobytes of memory. + +// OPT(dh): do we really need the Package.gen field? it's based +// trivially on pkg.results and merely caches the result of a type +// assertion. How often do we actually use the field? + type Package struct { + // dependents is initially set to 1 plus the number of packages + // that directly import this package. It is atomically decreased + // by 1 every time a dependent has been processed or when the + // package itself has been processed. Once the value reaches zero, + // the package is no longer needed. dependents uint64 *packages.Package - Imports []*Package - initial bool + Imports []*Package + initial bool + // fromSource is set to true for packages that have been loaded + // from source. This is the case for initial packages, packages + // with missing export data, and packages with no cached facts. fromSource bool - hash string - done chan struct{} + // hash stores the package hash, as computed by packageHash + hash string + actionID cache.ActionID + done chan struct{} resultsMu sync.Mutex - // results maps analyzer IDs to analyzer results + // results maps analyzer IDs to analyzer results. it is + // implemented as a deduplicating concurrent cache. results []*result - cfg *config.Config + cfg *config.Config + // gen maps file names to the code generator that created them gen map[string]facts.Generator problems []Problem ignores []Ignore @@ -82,12 +162,22 @@ type Package struct { facts []map[types.Object][]analysis.Fact pkgFacts [][]analysis.Fact + // canClearTypes is set to true if we can discard type + // information after the package and its dependents have been + // processed. This is the case when no cumulative checkers are + // being run. canClearTypes bool } +type cachedPackage struct { + Problems []Problem + Ignores []Ignore + Config *config.Config +} + func (pkg *Package) decUse() { - atomic.AddUint64(&pkg.dependents, ^uint64(0)) - if atomic.LoadUint64(&pkg.dependents) == 0 { + ret := atomic.AddUint64(&pkg.dependents, ^uint64(0)) + if ret == 0 { // nobody depends on this package anymore if pkg.canClearTypes { pkg.Types = nil @@ -108,16 +198,16 @@ type result struct { } type Runner struct { - ld loader.Loader - cache *cache.Cache + cache *cache.Cache + goVersion int + stats *Stats + repeatAnalyzers uint - analyzerIDs analyzerIDs + analyzerIDs analyzerIDs + problemsCacheKey string // limits parallelism of loading packages loadSem chan struct{} - - goVersion int - stats *Stats } type analyzerIDs struct { @@ -225,6 +315,13 @@ func (ac *analysisAction) report(pass *analysis.Pass, d analysis.Diagnostic) { Message: d.Message, Check: pass.Analyzer.Name, } + for _, r := range d.Related { + p.Related = append(p.Related, Related{ + Pos: DisplayPosition(pass.Fset, r.Pos), + End: DisplayPosition(pass.Fset, r.End), + Message: r.Message, + }) + } ac.problems = append(ac.problems, p) } @@ -278,6 +375,21 @@ func (r *Runner) runAnalysis(ac *analysisAction) (ret interface{}, err error) { } } +func (r *Runner) loadCachedPackage(pkg *Package, analyzers []*analysis.Analyzer) (cachedPackage, bool) { + // OPT(dh): we can cache this computation, it'll be the same for all packages + id := cache.Subkey(pkg.actionID, "data "+r.problemsCacheKey) + + b, _, err := r.cache.GetBytes(id) + if err != nil { + return cachedPackage{}, false + } + var cpkg cachedPackage + if err := gob.NewDecoder(bytes.NewReader(b)).Decode(&cpkg); err != nil { + return cachedPackage{}, false + } + return cpkg, true +} + func (r *Runner) loadCachedFacts(a *analysis.Analyzer, pkg *Package) ([]Fact, bool) { if len(a.FactTypes) == 0 { return nil, true @@ -285,10 +397,7 @@ func (r *Runner) loadCachedFacts(a *analysis.Analyzer, pkg *Package) ([]Fact, bo var facts []Fact // Look in the cache for facts - aID, err := passActionID(pkg, a) - if err != nil { - return nil, false - } + aID := passActionID(pkg, a) aID = cache.Subkey(aID, "facts") b, _, err := r.cache.GetBytes(aID) if err != nil { @@ -378,9 +487,15 @@ func (r *Runner) runAnalysisUser(pass *analysis.Pass, ac *analysisAction) (inter } // Then with this analyzer - ret, err := ac.analyzer.Run(pass) - if err != nil { - return nil, err + var ret interface{} + for i := uint(0); i < r.repeatAnalyzers+1; i++ { + var err error + t := time.Now() + ret, err = ac.analyzer.Run(pass) + r.stats.MeasureAnalyzer(ac.analyzer, ac.pkg, time.Since(t)) + if err != nil { + return nil, err + } } if len(ac.analyzer.FactTypes) > 0 { @@ -404,16 +519,7 @@ func (r *Runner) runAnalysisUser(pass *analysis.Pass, ac *analysisAction) (inter } } - buf := &bytes.Buffer{} - if err := gob.NewEncoder(buf).Encode(facts); err != nil { - return nil, err - } - aID, err := passActionID(ac.pkg, ac.analyzer) - if err != nil { - return nil, err - } - aID = cache.Subkey(aID, "facts") - if err := r.cache.PutBytes(aID, buf.Bytes()); err != nil { + if err := r.cacheData(facts, ac.pkg, ac.analyzer, "facts"); err != nil { return nil, err } } @@ -421,6 +527,19 @@ func (r *Runner) runAnalysisUser(pass *analysis.Pass, ac *analysisAction) (inter return ret, nil } +func (r *Runner) cacheData(v interface{}, pkg *Package, a *analysis.Analyzer, subkey string) error { + buf := &bytes.Buffer{} + if err := gob.NewEncoder(buf).Encode(v); err != nil { + return err + } + aID := passActionID(pkg, a) + aID = cache.Subkey(aID, subkey) + if err := r.cache.PutBytes(aID, buf.Bytes()); err != nil { + return err + } + return nil +} + func NewRunner(stats *Stats) (*Runner, error) { cache, err := cache.Default() if err != nil { @@ -438,9 +557,17 @@ func NewRunner(stats *Stats) (*Runner, error) { // diagnostics as well as extracted ignore directives. // // Note that diagnostics have not been filtered at this point yet, to -// accomodate cumulative analyzes that require additional steps to +// accommodate cumulative analyzes that require additional steps to // produce diagnostics. func (r *Runner) Run(cfg *packages.Config, patterns []string, analyzers []*analysis.Analyzer, hasCumulative bool) ([]*Package, error) { + checkerNames := make([]string, len(analyzers)) + for i, a := range analyzers { + checkerNames[i] = a.Name + } + sort.Strings(checkerNames) + r.problemsCacheKey = strings.Join(checkerNames, " ") + + var allAnalyzers []*analysis.Analyzer r.analyzerIDs = analyzerIDs{m: map[*analysis.Analyzer]int{}} id := 0 seen := map[*analysis.Analyzer]struct{}{} @@ -450,6 +577,7 @@ func (r *Runner) Run(cfg *packages.Config, patterns []string, analyzers []*analy return } seen[a] = struct{}{} + allAnalyzers = append(allAnalyzers, a) r.analyzerIDs.m[a] = id id++ for _, f := range a.FactTypes { @@ -468,6 +596,11 @@ func (r *Runner) Run(cfg *packages.Config, patterns []string, analyzers []*analy for _, a := range injectedAnalyses { dfs(a) } + // Run all analyzers on all packages (subject to further + // restrictions enforced later). This guarantees that if analyzer + // A1 depends on A2, and A2 has facts, that A2 will run on the + // dependencies of user-provided packages, even though A1 won't. + analyzers = allAnalyzers var dcfg packages.Config if cfg != nil { @@ -475,11 +608,10 @@ func (r *Runner) Run(cfg *packages.Config, patterns []string, analyzers []*analy } atomic.StoreUint32(&r.stats.State, StateGraph) - initialPkgs, err := r.ld.Graph(dcfg, patterns...) + initialPkgs, err := loader.Graph(dcfg, patterns...) if err != nil { return nil, err } - defer r.cache.Trim() var allPkgs []*Package @@ -507,7 +639,8 @@ func (r *Runner) Run(cfg *packages.Config, patterns []string, analyzers []*analy m[l].Imports = append(m[l].Imports, m[v]) } - m[l].hash, err = packageHash(m[l]) + m[l].hash, err = r.packageHash(m[l]) + m[l].actionID = packageActionID(m[l]) if err != nil { m[l].errs = append(m[l].errs, err) } @@ -564,27 +697,36 @@ func parsePos(pos string) (token.Position, int, error) { }, len(parts[0]), nil } -// loadPkg loads a Go package. If the package is in the set of initial -// packages, it will be loaded from source, otherwise it will be -// loaded from export data. In the case that the package was loaded -// from export data, cached facts will also be loaded. -// -// Currently, only cached facts for this package will be loaded, not -// for any of its dependencies. +// loadPkg loads a Go package. It may be loaded from a combination of +// caches, or from source. func (r *Runner) loadPkg(pkg *Package, analyzers []*analysis.Analyzer) error { if pkg.Types != nil { panic(fmt.Sprintf("internal error: %s has already been loaded", pkg.Package)) } - // Load type information if pkg.initial { - // Load package from source - pkg.fromSource = true - return r.ld.LoadFromSource(pkg.Package) + // Try to load cached package + cpkg, ok := r.loadCachedPackage(pkg, analyzers) + if ok { + pkg.problems = cpkg.Problems + pkg.ignores = cpkg.Ignores + pkg.cfg = cpkg.Config + } else { + pkg.fromSource = true + return loader.LoadFromSource(pkg.Package) + } } + // At this point we're either working with a non-initial package, + // or we managed to load cached problems for the package. We still + // need export data and facts. + + // OPT(dh): we don't need type information for this package if no + // other package depends on it. this may be the case for initial + // packages. + // Load package from export data - if err := r.ld.LoadFromExport(pkg.Package); err != nil { + if err := loader.LoadFromExport(pkg.Package); err != nil { // We asked Go to give us up to date export data, yet // we can't load it. There must be something wrong. // @@ -597,7 +739,7 @@ func (r *Runner) loadPkg(pkg *Package, analyzers []*analysis.Analyzer) error { // FIXME(dh): we no longer reload from export data, so // theoretically we should be able to continue pkg.fromSource = true - if err := r.ld.LoadFromSource(pkg.Package); err != nil { + if err := loader.LoadFromSource(pkg.Package); err != nil { return err } // Make sure this package can't be imported successfully @@ -658,13 +800,14 @@ func (r *Runner) loadPkg(pkg *Package, analyzers []*analysis.Analyzer) error { dfs(a) } - if failed { - pkg.fromSource = true - // XXX we added facts to the maps, we need to get rid of those - return r.ld.LoadFromSource(pkg.Package) + if !failed { + return nil } - return nil + // We failed to load some cached facts + pkg.fromSource = true + // XXX we added facts to the maps, we need to get rid of those + return loader.LoadFromSource(pkg.Package) } type analysisError struct { @@ -695,7 +838,7 @@ func (r *Runner) processPkg(pkg *Package, analyzers []*analysis.Analyzer) { }() // Ensure all packages have the generated map and config. This is - // required by interna of the runner. Analyses that themselves + // required by internals of the runner. Analyses that themselves // make use of either have an explicit dependency so that other // runners work correctly, too. analyzers = append(analyzers[0:len(analyzers):len(analyzers)], injectedAnalyses...) @@ -766,7 +909,7 @@ func (r *Runner) processPkg(pkg *Package, analyzers []*analysis.Analyzer) { defer wg.Done() // Only initial packages and packages with missing // facts will have been loaded from source. - if pkg.initial || r.hasFacts(a) { + if pkg.initial || len(a.FactTypes) > 0 { if _, err := r.runAnalysis(ac); err != nil { errs[i] = analysisError{a, pkg, err} return @@ -800,6 +943,8 @@ func (r *Runner) processPkg(pkg *Package, analyzers []*analysis.Analyzer) { // We can't process ignores at this point because `unused` needs // to see more than one package to make its decision. + // + // OPT(dh): can't we guard this block of code by pkg.initial? ignores, problems := parseDirectives(pkg.Package) pkg.ignores = append(pkg.ignores, ignores...) pkg.problems = append(pkg.problems, problems...) @@ -824,32 +969,6 @@ func (r *Runner) processPkg(pkg *Package, analyzers []*analysis.Analyzer) { // from processPkg. } -// hasFacts reports whether an analysis exports any facts. An analysis -// that has a transitive dependency that exports facts is considered -// to be exporting facts. -func (r *Runner) hasFacts(a *analysis.Analyzer) bool { - ret := false - seen := make([]bool, len(r.analyzerIDs.m)) - var dfs func(*analysis.Analyzer) - dfs = func(a *analysis.Analyzer) { - if seen[r.analyzerIDs.get(a)] { - return - } - seen[r.analyzerIDs.get(a)] = true - if len(a.FactTypes) > 0 { - ret = true - } - for _, req := range a.Requires { - if ret { - break - } - dfs(req) - } - } - dfs(a) - return ret -} - func parseDirective(s string) (cmd string, args []string) { if !strings.HasPrefix(s, "//lint:") { return "", nil @@ -912,7 +1031,7 @@ func parseDirectives(pkg *packages.Package) ([]Ignore, []Problem) { File: pos.Filename, Line: pos.Line, Checks: checks, - Pos: c.Pos(), + Pos: DisplayPosition(pkg.Fset, c.Pos()), } case "file-ignore": ig = &FileIgnore{ @@ -932,9 +1051,10 @@ func parseDirectives(pkg *packages.Package) ([]Ignore, []Problem) { // packageHash computes a package's hash. The hash is based on all Go // files that make up the package, as well as the hashes of imported // packages. -func packageHash(pkg *Package) (string, error) { +func (r *Runner) packageHash(pkg *Package) (string, error) { key := cache.NewHash("package hash") fmt.Fprintf(key, "pkgpath %s\n", pkg.PkgPath) + fmt.Fprintf(key, "go %d\n", r.goVersion) for _, f := range pkg.CompiledGoFiles { h, err := cache.FileHash(f) if err != nil { @@ -943,6 +1063,28 @@ func packageHash(pkg *Package) (string, error) { fmt.Fprintf(key, "file %s %x\n", f, h) } + // Actually load the configuration to calculate its hash. This + // will take into consideration inheritance of configuration + // files, as well as the default configuration. + // + // OPT(dh): doing this means we'll load the config twice: once for + // computing the hash, and once when analyzing the package from + // source. + cdir := config.Dir(pkg.GoFiles) + if cdir == "" { + fmt.Fprintf(key, "file %s %x\n", config.ConfigName, [cache.HashSize]byte{}) + } else { + cfg, err := config.Load(cdir) + if err != nil { + return "", err + } + h := cache.NewHash(config.ConfigName) + if _, err := h.Write([]byte(cfg.String())); err != nil { + return "", err + } + fmt.Fprintf(key, "file %s %x\n", config.ConfigName, h.Sum()) + } + imps := make([]*Package, len(pkg.Imports)) copy(imps, pkg.Imports) sort.Slice(imps, func(i, j int) bool { @@ -959,12 +1101,14 @@ func packageHash(pkg *Package) (string, error) { return hex.EncodeToString(h[:]), nil } -// passActionID computes an ActionID for an analysis pass. -func passActionID(pkg *Package, analyzer *analysis.Analyzer) (cache.ActionID, error) { - key := cache.NewHash("action ID") +func packageActionID(pkg *Package) cache.ActionID { + key := cache.NewHash("package ID") fmt.Fprintf(key, "pkgpath %s\n", pkg.PkgPath) fmt.Fprintf(key, "pkghash %s\n", pkg.hash) - fmt.Fprintf(key, "analyzer %s\n", analyzer.Name) + return key.Sum() +} - return key.Sum(), nil +// passActionID computes an ActionID for an analysis pass. +func passActionID(pkg *Package, analyzer *analysis.Analyzer) cache.ActionID { + return cache.Subkey(pkg.actionID, fmt.Sprintf("analyzer %s", analyzer.Name)) } diff --git a/vendor/honnef.co/go/tools/lint/stats.go b/vendor/honnef.co/go/tools/lint/stats.go index 2f650855937..85eb9784489 100644 --- a/vendor/honnef.co/go/tools/lint/stats.go +++ b/vendor/honnef.co/go/tools/lint/stats.go @@ -1,5 +1,11 @@ package lint +import ( + "time" + + "golang.org/x/tools/go/analysis" +) + const ( StateInitializing = 0 StateGraph = 1 @@ -17,4 +23,16 @@ type Stats struct { Problems uint32 ActiveWorkers uint32 TotalWorkers uint32 + PrintAnalyzerMeasurement func(*analysis.Analyzer, *Package, time.Duration) +} + +type AnalysisMeasurementKey struct { + Analysis string + Pkg string +} + +func (s *Stats) MeasureAnalyzer(analysis *analysis.Analyzer, pkg *Package, d time.Duration) { + if s.PrintAnalyzerMeasurement != nil { + s.PrintAnalyzerMeasurement(analysis, pkg, d) + } } diff --git a/vendor/honnef.co/go/tools/loader/loader.go b/vendor/honnef.co/go/tools/loader/loader.go index 9c6885d485f..a14f274d293 100644 --- a/vendor/honnef.co/go/tools/loader/loader.go +++ b/vendor/honnef.co/go/tools/loader/loader.go @@ -1,6 +1,7 @@ package loader import ( + "errors" "fmt" "go/ast" "go/parser" @@ -9,22 +10,17 @@ import ( "go/types" "log" "os" - "sync" "golang.org/x/tools/go/gcexportdata" "golang.org/x/tools/go/packages" ) -type Loader struct { - exportMu sync.RWMutex -} - // Graph resolves patterns and returns packages with all the // information required to later load type information, and optionally // syntax trees. // // The provided config can set any setting with the exception of Mode. -func (ld *Loader) Graph(cfg packages.Config, patterns ...string) ([]*packages.Package, error) { +func Graph(cfg packages.Config, patterns ...string) ([]*packages.Package, error) { cfg.Mode = packages.NeedName | packages.NeedImports | packages.NeedDeps | packages.NeedExportsFile | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedTypesSizes pkgs, err := packages.Load(&cfg, patterns...) if err != nil { @@ -34,15 +30,29 @@ func (ld *Loader) Graph(cfg packages.Config, patterns ...string) ([]*packages.Pa packages.Visit(pkgs, nil, func(pkg *packages.Package) { pkg.Fset = fset }) - return pkgs, nil + + n := 0 + for _, pkg := range pkgs { + if len(pkg.CompiledGoFiles) == 0 && len(pkg.Errors) == 0 && pkg.PkgPath != "unsafe" { + // If a package consists only of test files, then + // go/packages incorrectly(?) returns an empty package for + // the non-test variant. Get rid of those packages. See + // #646. + // + // Do not, however, skip packages that have errors. Those, + // too, may have no files, but we want to print the + // errors. + continue + } + pkgs[n] = pkg + n++ + } + return pkgs[:n], nil } // LoadFromExport loads a package from export data. All of its // dependencies must have been loaded already. -func (ld *Loader) LoadFromExport(pkg *packages.Package) error { - ld.exportMu.Lock() - defer ld.exportMu.Unlock() - +func LoadFromExport(pkg *packages.Package) error { pkg.IllTyped = true for path, pkg := range pkg.Imports { if pkg.Types == nil { @@ -87,10 +97,7 @@ func (ld *Loader) LoadFromExport(pkg *packages.Package) error { // LoadFromSource loads a package from source. All of its dependencies // must have been loaded already. -func (ld *Loader) LoadFromSource(pkg *packages.Package) error { - ld.exportMu.RLock() - defer ld.exportMu.RUnlock() - +func LoadFromSource(pkg *packages.Package) error { pkg.IllTyped = true pkg.Types = types.NewPackage(pkg.PkgPath, pkg.Name) @@ -121,6 +128,12 @@ func (ld *Loader) LoadFromSource(pkg *packages.Package) error { if path == "unsafe" { return types.Unsafe, nil } + if path == "C" { + // go/packages doesn't tell us that cgo preprocessing + // failed. When we subsequently try to parse the package, + // we'll encounter the raw C import. + return nil, errors.New("cgo preprocessing failed") + } imp := pkg.Imports[path] if imp == nil { return nil, nil diff --git a/vendor/honnef.co/go/tools/pattern/convert.go b/vendor/honnef.co/go/tools/pattern/convert.go new file mode 100644 index 00000000000..dfcd1560d74 --- /dev/null +++ b/vendor/honnef.co/go/tools/pattern/convert.go @@ -0,0 +1,242 @@ +package pattern + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + "reflect" +) + +var astTypes = map[string]reflect.Type{ + "Ellipsis": reflect.TypeOf(ast.Ellipsis{}), + "RangeStmt": reflect.TypeOf(ast.RangeStmt{}), + "AssignStmt": reflect.TypeOf(ast.AssignStmt{}), + "IndexExpr": reflect.TypeOf(ast.IndexExpr{}), + "Ident": reflect.TypeOf(ast.Ident{}), + "ValueSpec": reflect.TypeOf(ast.ValueSpec{}), + "GenDecl": reflect.TypeOf(ast.GenDecl{}), + "BinaryExpr": reflect.TypeOf(ast.BinaryExpr{}), + "ForStmt": reflect.TypeOf(ast.ForStmt{}), + "ArrayType": reflect.TypeOf(ast.ArrayType{}), + "DeferStmt": reflect.TypeOf(ast.DeferStmt{}), + "MapType": reflect.TypeOf(ast.MapType{}), + "ReturnStmt": reflect.TypeOf(ast.ReturnStmt{}), + "SliceExpr": reflect.TypeOf(ast.SliceExpr{}), + "StarExpr": reflect.TypeOf(ast.StarExpr{}), + "UnaryExpr": reflect.TypeOf(ast.UnaryExpr{}), + "SendStmt": reflect.TypeOf(ast.SendStmt{}), + "SelectStmt": reflect.TypeOf(ast.SelectStmt{}), + "ImportSpec": reflect.TypeOf(ast.ImportSpec{}), + "IfStmt": reflect.TypeOf(ast.IfStmt{}), + "GoStmt": reflect.TypeOf(ast.GoStmt{}), + "Field": reflect.TypeOf(ast.Field{}), + "SelectorExpr": reflect.TypeOf(ast.SelectorExpr{}), + "StructType": reflect.TypeOf(ast.StructType{}), + "KeyValueExpr": reflect.TypeOf(ast.KeyValueExpr{}), + "FuncType": reflect.TypeOf(ast.FuncType{}), + "FuncLit": reflect.TypeOf(ast.FuncLit{}), + "FuncDecl": reflect.TypeOf(ast.FuncDecl{}), + "ChanType": reflect.TypeOf(ast.ChanType{}), + "CallExpr": reflect.TypeOf(ast.CallExpr{}), + "CaseClause": reflect.TypeOf(ast.CaseClause{}), + "CommClause": reflect.TypeOf(ast.CommClause{}), + "CompositeLit": reflect.TypeOf(ast.CompositeLit{}), + "EmptyStmt": reflect.TypeOf(ast.EmptyStmt{}), + "SwitchStmt": reflect.TypeOf(ast.SwitchStmt{}), + "TypeSwitchStmt": reflect.TypeOf(ast.TypeSwitchStmt{}), + "TypeAssertExpr": reflect.TypeOf(ast.TypeAssertExpr{}), + "TypeSpec": reflect.TypeOf(ast.TypeSpec{}), + "InterfaceType": reflect.TypeOf(ast.InterfaceType{}), + "BranchStmt": reflect.TypeOf(ast.BranchStmt{}), + "IncDecStmt": reflect.TypeOf(ast.IncDecStmt{}), + "BasicLit": reflect.TypeOf(ast.BasicLit{}), +} + +func ASTToNode(node interface{}) Node { + switch node := node.(type) { + case *ast.File: + panic("cannot convert *ast.File to Node") + case nil: + return Nil{} + case string: + return String(node) + case token.Token: + return Token(node) + case *ast.ExprStmt: + return ASTToNode(node.X) + case *ast.BlockStmt: + if node == nil { + return Nil{} + } + return ASTToNode(node.List) + case *ast.FieldList: + if node == nil { + return Nil{} + } + return ASTToNode(node.List) + case *ast.BasicLit: + if node == nil { + return Nil{} + } + case *ast.ParenExpr: + return ASTToNode(node.X) + } + + if node, ok := node.(ast.Node); ok { + name := reflect.TypeOf(node).Elem().Name() + T, ok := structNodes[name] + if !ok { + panic(fmt.Sprintf("internal error: unhandled type %T", node)) + } + + if reflect.ValueOf(node).IsNil() { + return Nil{} + } + v := reflect.ValueOf(node).Elem() + objs := make([]Node, T.NumField()) + for i := 0; i < T.NumField(); i++ { + f := v.FieldByName(T.Field(i).Name) + objs[i] = ASTToNode(f.Interface()) + } + + n, err := populateNode(name, objs, false) + if err != nil { + panic(fmt.Sprintf("internal error: %s", err)) + } + return n + } + + s := reflect.ValueOf(node) + if s.Kind() == reflect.Slice { + if s.Len() == 0 { + return List{} + } + if s.Len() == 1 { + return ASTToNode(s.Index(0).Interface()) + } + + tail := List{} + for i := s.Len() - 1; i >= 0; i-- { + head := ASTToNode(s.Index(i).Interface()) + l := List{ + Head: head, + Tail: tail, + } + tail = l + } + return tail + } + + panic(fmt.Sprintf("internal error: unhandled type %T", node)) +} + +func NodeToAST(node Node, state State) interface{} { + switch node := node.(type) { + case Binding: + v, ok := state[node.Name] + if !ok { + // really we want to return an error here + panic("XXX") + } + switch v := v.(type) { + case types.Object: + return &ast.Ident{Name: v.Name()} + default: + return v + } + case Builtin, Any, Object, Function, Not, Or: + panic("XXX") + case List: + if (node == List{}) { + return []ast.Node{} + } + x := []ast.Node{NodeToAST(node.Head, state).(ast.Node)} + x = append(x, NodeToAST(node.Tail, state).([]ast.Node)...) + return x + case Token: + return token.Token(node) + case String: + return string(node) + case Nil: + return nil + } + + name := reflect.TypeOf(node).Name() + T, ok := astTypes[name] + if !ok { + panic(fmt.Sprintf("internal error: unhandled type %T", node)) + } + v := reflect.ValueOf(node) + out := reflect.New(T) + for i := 0; i < T.NumField(); i++ { + fNode := v.FieldByName(T.Field(i).Name) + if (fNode == reflect.Value{}) { + continue + } + fAST := out.Elem().FieldByName(T.Field(i).Name) + switch fAST.Type().Kind() { + case reflect.Slice: + c := reflect.ValueOf(NodeToAST(fNode.Interface().(Node), state)) + if c.Kind() != reflect.Slice { + // it's a single node in the pattern, we have to wrap + // it in a slice + slice := reflect.MakeSlice(fAST.Type(), 1, 1) + slice.Index(0).Set(c) + c = slice + } + switch fAST.Interface().(type) { + case []ast.Node: + switch cc := c.Interface().(type) { + case []ast.Node: + fAST.Set(c) + case []ast.Expr: + var slice []ast.Node + for _, el := range cc { + slice = append(slice, el) + } + fAST.Set(reflect.ValueOf(slice)) + default: + panic("XXX") + } + case []ast.Expr: + switch cc := c.Interface().(type) { + case []ast.Node: + var slice []ast.Expr + for _, el := range cc { + slice = append(slice, el.(ast.Expr)) + } + fAST.Set(reflect.ValueOf(slice)) + case []ast.Expr: + fAST.Set(c) + default: + panic("XXX") + } + default: + panic("XXX") + } + case reflect.Int: + c := reflect.ValueOf(NodeToAST(fNode.Interface().(Node), state)) + switch c.Kind() { + case reflect.String: + tok, ok := tokensByString[c.Interface().(string)] + if !ok { + // really we want to return an error here + panic("XXX") + } + fAST.SetInt(int64(tok)) + case reflect.Int: + fAST.Set(c) + default: + panic(fmt.Sprintf("internal error: unexpected kind %s", c.Kind())) + } + default: + r := NodeToAST(fNode.Interface().(Node), state) + if r != nil { + fAST.Set(reflect.ValueOf(r)) + } + } + } + + return out.Interface().(ast.Node) +} diff --git a/vendor/honnef.co/go/tools/pattern/doc.go b/vendor/honnef.co/go/tools/pattern/doc.go new file mode 100644 index 00000000000..05d86c25144 --- /dev/null +++ b/vendor/honnef.co/go/tools/pattern/doc.go @@ -0,0 +1,273 @@ +/* +Package pattern implements a simple language for pattern matching Go ASTs. + +Design decisions and trade-offs + +The language is designed specifically for the task of filtering ASTs +to simplify the implementation of analyses in staticcheck. +It is also intended to be trivial to parse and execute. + +To that end, we make certain decisions that make the language more +suited to its task, while making certain queries infeasible. + +Furthermore, it is fully expected that the majority of analyses will still require ordinary Go code +to further process the filtered AST, to make use of type information and to enforce complex invariants. +It is not our goal to design a scripting language for writing entire checks in. + +The language + +At its core, patterns are a representation of Go ASTs, allowing for the use of placeholders to enable pattern matching. +Their syntax is inspired by LISP and Haskell, but unlike LISP, the core unit of patterns isn't the list, but the node. +There is a fixed set of nodes, identified by name, and with the exception of the Or node, all nodes have a fixed number of arguments. +In addition to nodes, there are atoms, which represent basic units such as strings or the nil value. + +Pattern matching is implemented via bindings, represented by the Binding node. +A Binding can match nodes and associate them with names, to later recall the nodes. +This allows for expressing "this node must be equal to that node" constraints. + +To simplify writing and reading patterns, a small amount of additional syntax exists on top of nodes and atoms. +This additional syntax doesn't add any new features of its own, it simply provides shortcuts to creating nodes and atoms. + +To show an example of a pattern, first consider this snippet of Go code: + + if x := fn(); x != nil { + for _, v := range x { + println(v, x) + } + } + +The corresponding AST expressed as an idiomatic pattern would look as follows: + + (IfStmt + (AssignStmt (Ident "x") ":=" (CallExpr (Ident "fn") [])) + (BinaryExpr (Ident "x") "!=" (Ident "nil")) + (RangeStmt + (Ident "_") (Ident "v") ":=" (Ident "x") + (CallExpr (Ident "println") [(Ident "v") (Ident "x")])) + nil) + +Two things are worth noting about this representation. +First, the [el1 el2 ...] syntax is a short-hand for creating lists. +It is a short-hand for el1:el2:[], which itself is a short-hand for (List el1 (List el2 (List nil nil)). +Second, note the absence of a lot of lists in places that normally accept lists. +For example, assignment assigns a number of right-hands to a number of left-hands, yet our AssignStmt is lacking any form of list. +This is due to the fact that a single node can match a list of exactly one element. +Thus, the two following forms have identical matching behavior: + + (AssignStmt (Ident "x") ":=" (CallExpr (Ident "fn") [])) + (AssignStmt [(Ident "x")] ":=" [(CallExpr (Ident "fn") [])]) + +This section serves as an overview of the language's syntax. +More in-depth explanations of the matching behavior as well as an exhaustive list of node types follows in the coming sections. + +Pattern matching + +TODO write about pattern matching + +- inspired by haskell syntax, but much, much simpler and naive + +Node types + +The language contains two kinds of nodes: those that map to nodes in the AST, and those that implement additional logic. + +Nodes that map directly to AST nodes are named identically to the types in the go/ast package. +What follows is an exhaustive list of these nodes: + + (ArrayType len elt) + (AssignStmt lhs tok rhs) + (BasicLit kind value) + (BinaryExpr x op y) + (BranchStmt tok label) + (CallExpr fun args) + (CaseClause list body) + (ChanType dir value) + (CommClause comm body) + (CompositeLit type elts) + (DeferStmt call) + (Ellipsis elt) + (EmptyStmt) + (Field names type tag) + (ForStmt init cond post body) + (FuncDecl recv name type body) + (FuncLit type body) + (FuncType params results) + (GenDecl specs) + (GoStmt call) + (Ident name) + (IfStmt init cond body else) + (ImportSpec name path) + (IncDecStmt x tok) + (IndexExpr x index) + (InterfaceType methods) + (KeyValueExpr key value) + (MapType key value) + (RangeStmt key value tok x body) + (ReturnStmt results) + (SelectStmt body) + (SelectorExpr x sel) + (SendStmt chan value) + (SliceExpr x low high max) + (StarExpr x) + (StructType fields) + (SwitchStmt init tag body) + (TypeAssertExpr) + (TypeSpec name type) + (TypeSwitchStmt init assign body) + (UnaryExpr op x) + (ValueSpec names type values) + +Additionally, there are the String, Token and nil atoms. +Strings are double-quoted string literals, as in (Ident "someName"). +Tokens are also represented as double-quoted string literals, but are converted to token.Token values in contexts that require tokens, +such as in (BinaryExpr x "<" y), where "<" is transparently converted to token.LSS during matching. +The keyword 'nil' denotes the nil value, which represents the absence of any value. + +We also defines the (List head tail) node, which is used to represent sequences of elements as a singly linked list. +The head is a single element, and the tail is the remainder of the list. +For example, + + (List "foo" (List "bar" (List "baz" (List nil nil)))) + +represents a list of three elements, "foo", "bar" and "baz". There is dedicated syntax for writing lists, which looks as follows: + + ["foo" "bar" "baz"] + +This syntax is itself syntactic sugar for the following form: + + "foo":"bar":"baz":[] + +This form is of particular interest for pattern matching, as it allows matching on the head and tail. For example, + + "foo":"bar":_ + +would match any list with at least two elements, where the first two elements are "foo" and "bar". This is equivalent to writing + + (List "foo" (List "bar" _)) + +Note that it is not possible to match from the end of the list. +That is, there is no way to express a query such as "a list of any length where the last element is foo". + +Note that unlike in LISP, nil and empty lists are distinct from one another. +In patterns, with respect to lists, nil is akin to Go's untyped nil. +It will match a nil ast.Node, but it will not match a nil []ast.Expr. Nil will, however, match pointers to named types such as *ast.Ident. +Similarly, lists are akin to Go's +slices. An empty list will match both a nil and an empty []ast.Expr, but it will not match a nil ast.Node. + +Due to the difference between nil and empty lists, an empty list is represented as (List nil nil), i.e. a list with no head or tail. +Similarly, a list of one element is represented as (List el (List nil nil)). Unlike in LISP, it cannot be represented by (List el nil). + +Finally, there are nodes that implement special logic or matching behavior. + +(Any) matches any value. The underscore (_) maps to this node, making the following two forms equivalent: + + (Ident _) + (Ident (Any)) + +(Builtin name) matches a built-in identifier or function by name. +This is a type-aware variant of (Ident name). +Instead of only comparing the name, it resolves the object behind the name and makes sure it's a pre-declared identifier. + +For example, in the following piece of code + + func fn() { + println(true) + true := false + println(true) + } + +the pattern + + (Builtin "true") + +will match exactly once, on the first use of 'true' in the function. +Subsequent occurrences of 'true' no longer refer to the pre-declared identifier. + +(Object name) matches an identifier by name, but yields the +types.Object it refers to. + +(Function name) matches ast.Idents and ast.SelectorExprs that refer to a function with a given fully qualified name. +For example, "net/url.PathEscape" matches the PathEscape function in the net/url package, +and "(net/url.EscapeError).Error" refers to the Error method on the net/url.EscapeError type, +either on an instance of the type, or on the type itself. + +For example, the following patterns match the following lines of code: + + (CallExpr (Function "fmt.Println") _) // pattern 1 + (CallExpr (Function "(net/url.EscapeError).Error") _) // pattern 2 + + fmt.Println("hello, world") // matches pattern 1 + var x url.EscapeError + x.Error() // matches pattern 2 + (url.EscapeError).Error(x) // also matches pattern 2 + +(Binding name node) creates or uses a binding. +Bindings work like variable assignments, allowing referring to already matched nodes. +As an example, bindings are necessary to match self-assignment of the form "x = x", +since we need to express that the right-hand side is identical to the left-hand side. + +If a binding's node is not nil, the matcher will attempt to match a node according to the pattern. +If a binding's node is nil, the binding will either recall an existing value, or match the Any node. +It is an error to provide a non-nil node to a binding that has already been bound. + +Referring back to the earlier example, the following pattern will match self-assignment of idents: + + (AssignStmt (Binding "lhs" (Ident _)) "=" (Binding "lhs" nil)) + +Because bindings are a crucial component of pattern matching, there is special syntax for creating and recalling bindings. +Lower-case names refer to bindings. If standing on its own, the name "foo" will be equivalent to (Binding "foo" nil). +If a name is followed by an at-sign (@) then it will create a binding for the node that follows. +Together, this allows us to rewrite the earlier example as follows: + + (AssignStmt lhs@(Ident _) "=" lhs) + +(Or nodes...) is a variadic node that tries matching each node until one succeeds. For example, the following pattern matches all idents of name "foo" or "bar": + + (Ident (Or "foo" "bar")) + +We could also have written + + (Or (Ident "foo") (Ident "bar")) + +and achieved the same result. We can also mix different kinds of nodes: + + (Or (Ident "foo") (CallExpr (Ident "bar") _)) + +When using bindings inside of nodes used inside Or, all or none of the bindings will be bound. +That is, partially matched nodes that ultimately failed to match will not produce any bindings observable outside of the matching attempt. +We can thus write + + (Or (Ident name) (CallExpr name)) + +and 'name' will either be a String if the first option matched, or an Ident or SelectorExpr if the second option matched. + +(Not node) + +The Not node negates a match. For example, (Not (Ident _)) will match all nodes that aren't identifiers. + +ChanDir(0) + +Automatic unnesting of AST nodes + +The Go AST has several types of nodes that wrap other nodes. +To simplify matching, we automatically unwrap some of these nodes. + +These nodes are ExprStmt (for using expressions in a statement context), +ParenExpr (for parenthesized expressions), +DeclStmt (for declarations in a statement context), +and LabeledStmt (for labeled statements). + +Thus, the query + + (FuncLit _ [(CallExpr _ _)] + +will match a function literal containing a single function call, +even though in the actual Go AST, the CallExpr is nested inside an ExprStmt, +as function bodies are made up of sequences of statements. + +On the flip-side, there is no way to specifically match these wrapper nodes. +For example, there is no way of searching for unnecessary parentheses, like in the following piece of Go code: + + ((x)) += 2 + +*/ +package pattern diff --git a/vendor/honnef.co/go/tools/pattern/fuzz.go b/vendor/honnef.co/go/tools/pattern/fuzz.go new file mode 100644 index 00000000000..52e7df9742b --- /dev/null +++ b/vendor/honnef.co/go/tools/pattern/fuzz.go @@ -0,0 +1,50 @@ +// +build gofuzz + +package pattern + +import ( + "go/ast" + goparser "go/parser" + "go/token" + "os" + "path/filepath" + "strings" +) + +var files []*ast.File + +func init() { + fset := token.NewFileSet() + filepath.Walk("/usr/lib/go/src", func(path string, info os.FileInfo, err error) error { + if err != nil { + // XXX error handling + panic(err) + } + if !strings.HasSuffix(path, ".go") { + return nil + } + f, err := goparser.ParseFile(fset, path, nil, 0) + if err != nil { + return nil + } + files = append(files, f) + return nil + }) +} + +func Fuzz(data []byte) int { + p := &Parser{} + pat, err := p.Parse(string(data)) + if err != nil { + if strings.Contains(err.Error(), "internal error") { + panic(err) + } + return 0 + } + _ = pat.Root.String() + + for _, f := range files { + Match(pat.Root, f) + } + return 1 +} diff --git a/vendor/honnef.co/go/tools/pattern/lexer.go b/vendor/honnef.co/go/tools/pattern/lexer.go new file mode 100644 index 00000000000..fb72e392bde --- /dev/null +++ b/vendor/honnef.co/go/tools/pattern/lexer.go @@ -0,0 +1,221 @@ +package pattern + +import ( + "fmt" + "go/token" + "unicode" + "unicode/utf8" +) + +type lexer struct { + f *token.File + + input string + start int + pos int + width int + items chan item +} + +type itemType int + +const eof = -1 + +const ( + itemError itemType = iota + itemLeftParen + itemRightParen + itemLeftBracket + itemRightBracket + itemTypeName + itemVariable + itemAt + itemColon + itemBlank + itemString + itemEOF +) + +func (typ itemType) String() string { + switch typ { + case itemError: + return "ERROR" + case itemLeftParen: + return "(" + case itemRightParen: + return ")" + case itemLeftBracket: + return "[" + case itemRightBracket: + return "]" + case itemTypeName: + return "TYPE" + case itemVariable: + return "VAR" + case itemAt: + return "@" + case itemColon: + return ":" + case itemBlank: + return "_" + case itemString: + return "STRING" + case itemEOF: + return "EOF" + default: + return fmt.Sprintf("itemType(%d)", typ) + } +} + +type item struct { + typ itemType + val string + pos int +} + +type stateFn func(*lexer) stateFn + +func (l *lexer) run() { + for state := lexStart; state != nil; { + state = state(l) + } + close(l.items) +} + +func (l *lexer) emitValue(t itemType, value string) { + l.items <- item{t, value, l.start} + l.start = l.pos +} + +func (l *lexer) emit(t itemType) { + l.items <- item{t, l.input[l.start:l.pos], l.start} + l.start = l.pos +} + +func lexStart(l *lexer) stateFn { + switch r := l.next(); { + case r == eof: + l.emit(itemEOF) + return nil + case unicode.IsSpace(r): + l.ignore() + case r == '(': + l.emit(itemLeftParen) + case r == ')': + l.emit(itemRightParen) + case r == '[': + l.emit(itemLeftBracket) + case r == ']': + l.emit(itemRightBracket) + case r == '@': + l.emit(itemAt) + case r == ':': + l.emit(itemColon) + case r == '_': + l.emit(itemBlank) + case r == '"': + l.backup() + return lexString + case unicode.IsUpper(r): + l.backup() + return lexType + case unicode.IsLower(r): + l.backup() + return lexVariable + default: + return l.errorf("unexpected character %c", r) + } + return lexStart +} + +func (l *lexer) next() (r rune) { + if l.pos >= len(l.input) { + l.width = 0 + return eof + } + r, l.width = utf8.DecodeRuneInString(l.input[l.pos:]) + + if r == '\n' { + l.f.AddLine(l.pos) + } + + l.pos += l.width + + return r +} + +func (l *lexer) ignore() { + l.start = l.pos +} + +func (l *lexer) backup() { + l.pos -= l.width +} + +func (l *lexer) errorf(format string, args ...interface{}) stateFn { + // TODO(dh): emit position information in errors + l.items <- item{ + itemError, + fmt.Sprintf(format, args...), + l.start, + } + return nil +} + +func isAlphaNumeric(r rune) bool { + return r >= '0' && r <= '9' || + r >= 'a' && r <= 'z' || + r >= 'A' && r <= 'Z' +} + +func lexString(l *lexer) stateFn { + l.next() // skip quote + escape := false + + var runes []rune + for { + switch r := l.next(); r { + case eof: + return l.errorf("unterminated string") + case '"': + if !escape { + l.emitValue(itemString, string(runes)) + return lexStart + } else { + runes = append(runes, '"') + escape = false + } + case '\\': + if escape { + runes = append(runes, '\\') + escape = false + } else { + escape = true + } + default: + runes = append(runes, r) + } + } +} + +func lexType(l *lexer) stateFn { + l.next() + for { + if !isAlphaNumeric(l.next()) { + l.backup() + l.emit(itemTypeName) + return lexStart + } + } +} + +func lexVariable(l *lexer) stateFn { + l.next() + for { + if !isAlphaNumeric(l.next()) { + l.backup() + l.emit(itemVariable) + return lexStart + } + } +} diff --git a/vendor/honnef.co/go/tools/pattern/match.go b/vendor/honnef.co/go/tools/pattern/match.go new file mode 100644 index 00000000000..ff039baa75d --- /dev/null +++ b/vendor/honnef.co/go/tools/pattern/match.go @@ -0,0 +1,513 @@ +package pattern + +import ( + "fmt" + "go/ast" + "go/token" + "go/types" + "reflect" + + "honnef.co/go/tools/lint" +) + +var tokensByString = map[string]Token{ + "INT": Token(token.INT), + "FLOAT": Token(token.FLOAT), + "IMAG": Token(token.IMAG), + "CHAR": Token(token.CHAR), + "STRING": Token(token.STRING), + "+": Token(token.ADD), + "-": Token(token.SUB), + "*": Token(token.MUL), + "/": Token(token.QUO), + "%": Token(token.REM), + "&": Token(token.AND), + "|": Token(token.OR), + "^": Token(token.XOR), + "<<": Token(token.SHL), + ">>": Token(token.SHR), + "&^": Token(token.AND_NOT), + "+=": Token(token.ADD_ASSIGN), + "-=": Token(token.SUB_ASSIGN), + "*=": Token(token.MUL_ASSIGN), + "/=": Token(token.QUO_ASSIGN), + "%=": Token(token.REM_ASSIGN), + "&=": Token(token.AND_ASSIGN), + "|=": Token(token.OR_ASSIGN), + "^=": Token(token.XOR_ASSIGN), + "<<=": Token(token.SHL_ASSIGN), + ">>=": Token(token.SHR_ASSIGN), + "&^=": Token(token.AND_NOT_ASSIGN), + "&&": Token(token.LAND), + "||": Token(token.LOR), + "<-": Token(token.ARROW), + "++": Token(token.INC), + "--": Token(token.DEC), + "==": Token(token.EQL), + "<": Token(token.LSS), + ">": Token(token.GTR), + "=": Token(token.ASSIGN), + "!": Token(token.NOT), + "!=": Token(token.NEQ), + "<=": Token(token.LEQ), + ">=": Token(token.GEQ), + ":=": Token(token.DEFINE), + "...": Token(token.ELLIPSIS), + "IMPORT": Token(token.IMPORT), + "VAR": Token(token.VAR), + "TYPE": Token(token.TYPE), + "CONST": Token(token.CONST), +} + +func maybeToken(node Node) (Node, bool) { + if node, ok := node.(String); ok { + if tok, ok := tokensByString[string(node)]; ok { + return tok, true + } + return node, false + } + return node, false +} + +func isNil(v interface{}) bool { + if v == nil { + return true + } + if _, ok := v.(Nil); ok { + return true + } + return false +} + +type matcher interface { + Match(*Matcher, interface{}) (interface{}, bool) +} + +type State = map[string]interface{} + +type Matcher struct { + TypesInfo *types.Info + State State +} + +func (m *Matcher) fork() *Matcher { + state := make(State, len(m.State)) + for k, v := range m.State { + state[k] = v + } + return &Matcher{ + TypesInfo: m.TypesInfo, + State: state, + } +} + +func (m *Matcher) merge(mc *Matcher) { + m.State = mc.State +} + +func (m *Matcher) Match(a Node, b ast.Node) bool { + m.State = State{} + _, ok := match(m, a, b) + return ok +} + +func Match(a Node, b ast.Node) (*Matcher, bool) { + m := &Matcher{} + ret := m.Match(a, b) + return m, ret +} + +// Match two items, which may be (Node, AST) or (AST, AST) +func match(m *Matcher, l, r interface{}) (interface{}, bool) { + if _, ok := r.(Node); ok { + panic("Node mustn't be on right side of match") + } + + switch l := l.(type) { + case *ast.ParenExpr: + return match(m, l.X, r) + case *ast.ExprStmt: + return match(m, l.X, r) + case *ast.DeclStmt: + return match(m, l.Decl, r) + case *ast.LabeledStmt: + return match(m, l.Stmt, r) + case *ast.BlockStmt: + return match(m, l.List, r) + case *ast.FieldList: + return match(m, l.List, r) + } + + switch r := r.(type) { + case *ast.ParenExpr: + return match(m, l, r.X) + case *ast.ExprStmt: + return match(m, l, r.X) + case *ast.DeclStmt: + return match(m, l, r.Decl) + case *ast.LabeledStmt: + return match(m, l, r.Stmt) + case *ast.BlockStmt: + if r == nil { + return match(m, l, nil) + } + return match(m, l, r.List) + case *ast.FieldList: + if r == nil { + return match(m, l, nil) + } + return match(m, l, r.List) + case *ast.BasicLit: + if r == nil { + return match(m, l, nil) + } + } + + if l, ok := l.(matcher); ok { + return l.Match(m, r) + } + + if l, ok := l.(Node); ok { + // Matching of pattern with concrete value + return matchNodeAST(m, l, r) + } + + if l == nil || r == nil { + return nil, l == r + } + + { + ln, ok1 := l.(ast.Node) + rn, ok2 := r.(ast.Node) + if ok1 && ok2 { + return matchAST(m, ln, rn) + } + } + + { + obj, ok := l.(types.Object) + if ok { + switch r := r.(type) { + case *ast.Ident: + return obj, obj == m.TypesInfo.ObjectOf(r) + case *ast.SelectorExpr: + return obj, obj == m.TypesInfo.ObjectOf(r.Sel) + default: + return obj, false + } + } + } + + { + ln, ok1 := l.([]ast.Expr) + rn, ok2 := r.([]ast.Expr) + if ok1 || ok2 { + if ok1 && !ok2 { + rn = []ast.Expr{r.(ast.Expr)} + } else if !ok1 && ok2 { + ln = []ast.Expr{l.(ast.Expr)} + } + + if len(ln) != len(rn) { + return nil, false + } + for i, ll := range ln { + if _, ok := match(m, ll, rn[i]); !ok { + return nil, false + } + } + return r, true + } + } + + { + ln, ok1 := l.([]ast.Stmt) + rn, ok2 := r.([]ast.Stmt) + if ok1 || ok2 { + if ok1 && !ok2 { + rn = []ast.Stmt{r.(ast.Stmt)} + } else if !ok1 && ok2 { + ln = []ast.Stmt{l.(ast.Stmt)} + } + + if len(ln) != len(rn) { + return nil, false + } + for i, ll := range ln { + if _, ok := match(m, ll, rn[i]); !ok { + return nil, false + } + } + return r, true + } + } + + panic(fmt.Sprintf("unsupported comparison: %T and %T", l, r)) +} + +// Match a Node with an AST node +func matchNodeAST(m *Matcher, a Node, b interface{}) (interface{}, bool) { + switch b := b.(type) { + case []ast.Stmt: + // 'a' is not a List or we'd be using its Match + // implementation. + + if len(b) != 1 { + return nil, false + } + return match(m, a, b[0]) + case []ast.Expr: + // 'a' is not a List or we'd be using its Match + // implementation. + + if len(b) != 1 { + return nil, false + } + return match(m, a, b[0]) + case ast.Node: + ra := reflect.ValueOf(a) + rb := reflect.ValueOf(b).Elem() + + if ra.Type().Name() != rb.Type().Name() { + return nil, false + } + + for i := 0; i < ra.NumField(); i++ { + af := ra.Field(i) + fieldName := ra.Type().Field(i).Name + bf := rb.FieldByName(fieldName) + if (bf == reflect.Value{}) { + panic(fmt.Sprintf("internal error: could not find field %s in type %t when comparing with %T", fieldName, b, a)) + } + ai := af.Interface() + bi := bf.Interface() + if ai == nil { + return b, bi == nil + } + if _, ok := match(m, ai.(Node), bi); !ok { + return b, false + } + } + return b, true + case nil: + return nil, a == Nil{} + default: + panic(fmt.Sprintf("unhandled type %T", b)) + } +} + +// Match two AST nodes +func matchAST(m *Matcher, a, b ast.Node) (interface{}, bool) { + ra := reflect.ValueOf(a) + rb := reflect.ValueOf(b) + + if ra.Type() != rb.Type() { + return nil, false + } + if ra.IsNil() || rb.IsNil() { + return rb, ra.IsNil() == rb.IsNil() + } + + ra = ra.Elem() + rb = rb.Elem() + for i := 0; i < ra.NumField(); i++ { + af := ra.Field(i) + bf := rb.Field(i) + if af.Type() == rtTokPos || af.Type() == rtObject || af.Type() == rtCommentGroup { + continue + } + + switch af.Kind() { + case reflect.Slice: + if af.Len() != bf.Len() { + return nil, false + } + for j := 0; j < af.Len(); j++ { + if _, ok := match(m, af.Index(j).Interface().(ast.Node), bf.Index(j).Interface().(ast.Node)); !ok { + return nil, false + } + } + case reflect.String: + if af.String() != bf.String() { + return nil, false + } + case reflect.Int: + if af.Int() != bf.Int() { + return nil, false + } + case reflect.Bool: + if af.Bool() != bf.Bool() { + return nil, false + } + case reflect.Ptr, reflect.Interface: + if _, ok := match(m, af.Interface(), bf.Interface()); !ok { + return nil, false + } + default: + panic(fmt.Sprintf("internal error: unhandled kind %s (%T)", af.Kind(), af.Interface())) + } + } + return b, true +} + +func (b Binding) Match(m *Matcher, node interface{}) (interface{}, bool) { + if isNil(b.Node) { + v, ok := m.State[b.Name] + if ok { + // Recall value + return match(m, v, node) + } + // Matching anything + b.Node = Any{} + } + + // Store value + if _, ok := m.State[b.Name]; ok { + panic(fmt.Sprintf("binding already created: %s", b.Name)) + } + new, ret := match(m, b.Node, node) + if ret { + m.State[b.Name] = new + } + return new, ret +} + +func (Any) Match(m *Matcher, node interface{}) (interface{}, bool) { + return node, true +} + +func (l List) Match(m *Matcher, node interface{}) (interface{}, bool) { + v := reflect.ValueOf(node) + if v.Kind() == reflect.Slice { + if isNil(l.Head) { + return node, v.Len() == 0 + } + if v.Len() == 0 { + return nil, false + } + // OPT(dh): don't check the entire tail if head didn't match + _, ok1 := match(m, l.Head, v.Index(0).Interface()) + _, ok2 := match(m, l.Tail, v.Slice(1, v.Len()).Interface()) + return node, ok1 && ok2 + } + // Our empty list does not equal an untyped Go nil. This way, we can + // tell apart an if with no else and an if with an empty else. + return nil, false +} + +func (s String) Match(m *Matcher, node interface{}) (interface{}, bool) { + switch o := node.(type) { + case token.Token: + if tok, ok := maybeToken(s); ok { + return match(m, tok, node) + } + return nil, false + case string: + return o, string(s) == o + default: + return nil, false + } +} + +func (tok Token) Match(m *Matcher, node interface{}) (interface{}, bool) { + o, ok := node.(token.Token) + if !ok { + return nil, false + } + return o, token.Token(tok) == o +} + +func (Nil) Match(m *Matcher, node interface{}) (interface{}, bool) { + return nil, isNil(node) +} + +func (builtin Builtin) Match(m *Matcher, node interface{}) (interface{}, bool) { + ident, ok := node.(*ast.Ident) + if !ok { + return nil, false + } + obj := m.TypesInfo.ObjectOf(ident) + if obj != types.Universe.Lookup(ident.Name) { + return nil, false + } + return match(m, builtin.Name, ident.Name) +} + +func (obj Object) Match(m *Matcher, node interface{}) (interface{}, bool) { + ident, ok := node.(*ast.Ident) + if !ok { + return nil, false + } + + id := m.TypesInfo.ObjectOf(ident) + _, ok = match(m, obj.Name, ident.Name) + return id, ok +} + +func (fn Function) Match(m *Matcher, node interface{}) (interface{}, bool) { + var name string + var obj types.Object + switch node := node.(type) { + case *ast.Ident: + obj = m.TypesInfo.ObjectOf(node) + switch obj := obj.(type) { + case *types.Func: + name = lint.FuncName(obj) + case *types.Builtin: + name = obj.Name() + default: + return nil, false + } + case *ast.SelectorExpr: + var ok bool + obj, ok = m.TypesInfo.ObjectOf(node.Sel).(*types.Func) + if !ok { + return nil, false + } + name = lint.FuncName(obj.(*types.Func)) + default: + return nil, false + } + _, ok := match(m, fn.Name, name) + return obj, ok +} + +func (or Or) Match(m *Matcher, node interface{}) (interface{}, bool) { + for _, opt := range or.Nodes { + mc := m.fork() + if ret, ok := match(mc, opt, node); ok { + m.merge(mc) + return ret, true + } + } + return nil, false +} + +func (not Not) Match(m *Matcher, node interface{}) (interface{}, bool) { + _, ok := match(m, not.Node, node) + if ok { + return nil, false + } + return node, true +} + +var ( + // Types of fields in go/ast structs that we want to skip + rtTokPos = reflect.TypeOf(token.Pos(0)) + rtObject = reflect.TypeOf((*ast.Object)(nil)) + rtCommentGroup = reflect.TypeOf((*ast.CommentGroup)(nil)) +) + +var ( + _ matcher = Binding{} + _ matcher = Any{} + _ matcher = List{} + _ matcher = String("") + _ matcher = Token(0) + _ matcher = Nil{} + _ matcher = Builtin{} + _ matcher = Object{} + _ matcher = Function{} + _ matcher = Or{} + _ matcher = Not{} +) diff --git a/vendor/honnef.co/go/tools/pattern/parser.go b/vendor/honnef.co/go/tools/pattern/parser.go new file mode 100644 index 00000000000..009238b8608 --- /dev/null +++ b/vendor/honnef.co/go/tools/pattern/parser.go @@ -0,0 +1,455 @@ +package pattern + +import ( + "fmt" + "go/ast" + "go/token" + "reflect" +) + +type Pattern struct { + Root Node + // Relevant contains instances of ast.Node that could potentially + // initiate a successful match of the pattern. + Relevant []reflect.Type +} + +func MustParse(s string) Pattern { + p := &Parser{AllowTypeInfo: true} + pat, err := p.Parse(s) + if err != nil { + panic(err) + } + return pat +} + +func roots(node Node) []reflect.Type { + switch node := node.(type) { + case Or: + var out []reflect.Type + for _, el := range node.Nodes { + out = append(out, roots(el)...) + } + return out + case Not: + return roots(node.Node) + case Binding: + return roots(node.Node) + case Nil, nil: + // this branch is reached via bindings + return allTypes + default: + Ts, ok := nodeToASTTypes[reflect.TypeOf(node)] + if !ok { + panic(fmt.Sprintf("internal error: unhandled type %T", node)) + } + return Ts + } +} + +var allTypes = []reflect.Type{ + reflect.TypeOf((*ast.RangeStmt)(nil)), + reflect.TypeOf((*ast.AssignStmt)(nil)), + reflect.TypeOf((*ast.IndexExpr)(nil)), + reflect.TypeOf((*ast.Ident)(nil)), + reflect.TypeOf((*ast.ValueSpec)(nil)), + reflect.TypeOf((*ast.GenDecl)(nil)), + reflect.TypeOf((*ast.BinaryExpr)(nil)), + reflect.TypeOf((*ast.ForStmt)(nil)), + reflect.TypeOf((*ast.ArrayType)(nil)), + reflect.TypeOf((*ast.DeferStmt)(nil)), + reflect.TypeOf((*ast.MapType)(nil)), + reflect.TypeOf((*ast.ReturnStmt)(nil)), + reflect.TypeOf((*ast.SliceExpr)(nil)), + reflect.TypeOf((*ast.StarExpr)(nil)), + reflect.TypeOf((*ast.UnaryExpr)(nil)), + reflect.TypeOf((*ast.SendStmt)(nil)), + reflect.TypeOf((*ast.SelectStmt)(nil)), + reflect.TypeOf((*ast.ImportSpec)(nil)), + reflect.TypeOf((*ast.IfStmt)(nil)), + reflect.TypeOf((*ast.GoStmt)(nil)), + reflect.TypeOf((*ast.Field)(nil)), + reflect.TypeOf((*ast.SelectorExpr)(nil)), + reflect.TypeOf((*ast.StructType)(nil)), + reflect.TypeOf((*ast.KeyValueExpr)(nil)), + reflect.TypeOf((*ast.FuncType)(nil)), + reflect.TypeOf((*ast.FuncLit)(nil)), + reflect.TypeOf((*ast.FuncDecl)(nil)), + reflect.TypeOf((*ast.ChanType)(nil)), + reflect.TypeOf((*ast.CallExpr)(nil)), + reflect.TypeOf((*ast.CaseClause)(nil)), + reflect.TypeOf((*ast.CommClause)(nil)), + reflect.TypeOf((*ast.CompositeLit)(nil)), + reflect.TypeOf((*ast.EmptyStmt)(nil)), + reflect.TypeOf((*ast.SwitchStmt)(nil)), + reflect.TypeOf((*ast.TypeSwitchStmt)(nil)), + reflect.TypeOf((*ast.TypeAssertExpr)(nil)), + reflect.TypeOf((*ast.TypeSpec)(nil)), + reflect.TypeOf((*ast.InterfaceType)(nil)), + reflect.TypeOf((*ast.BranchStmt)(nil)), + reflect.TypeOf((*ast.IncDecStmt)(nil)), + reflect.TypeOf((*ast.BasicLit)(nil)), +} + +var nodeToASTTypes = map[reflect.Type][]reflect.Type{ + reflect.TypeOf(String("")): nil, + reflect.TypeOf(Token(0)): nil, + reflect.TypeOf(List{}): {reflect.TypeOf((*ast.BlockStmt)(nil)), reflect.TypeOf((*ast.FieldList)(nil))}, + reflect.TypeOf(Builtin{}): {reflect.TypeOf((*ast.Ident)(nil))}, + reflect.TypeOf(Object{}): {reflect.TypeOf((*ast.Ident)(nil))}, + reflect.TypeOf(Function{}): {reflect.TypeOf((*ast.Ident)(nil)), reflect.TypeOf((*ast.SelectorExpr)(nil))}, + reflect.TypeOf(Any{}): allTypes, + reflect.TypeOf(RangeStmt{}): {reflect.TypeOf((*ast.RangeStmt)(nil))}, + reflect.TypeOf(AssignStmt{}): {reflect.TypeOf((*ast.AssignStmt)(nil))}, + reflect.TypeOf(IndexExpr{}): {reflect.TypeOf((*ast.IndexExpr)(nil))}, + reflect.TypeOf(Ident{}): {reflect.TypeOf((*ast.Ident)(nil))}, + reflect.TypeOf(ValueSpec{}): {reflect.TypeOf((*ast.ValueSpec)(nil))}, + reflect.TypeOf(GenDecl{}): {reflect.TypeOf((*ast.GenDecl)(nil))}, + reflect.TypeOf(BinaryExpr{}): {reflect.TypeOf((*ast.BinaryExpr)(nil))}, + reflect.TypeOf(ForStmt{}): {reflect.TypeOf((*ast.ForStmt)(nil))}, + reflect.TypeOf(ArrayType{}): {reflect.TypeOf((*ast.ArrayType)(nil))}, + reflect.TypeOf(DeferStmt{}): {reflect.TypeOf((*ast.DeferStmt)(nil))}, + reflect.TypeOf(MapType{}): {reflect.TypeOf((*ast.MapType)(nil))}, + reflect.TypeOf(ReturnStmt{}): {reflect.TypeOf((*ast.ReturnStmt)(nil))}, + reflect.TypeOf(SliceExpr{}): {reflect.TypeOf((*ast.SliceExpr)(nil))}, + reflect.TypeOf(StarExpr{}): {reflect.TypeOf((*ast.StarExpr)(nil))}, + reflect.TypeOf(UnaryExpr{}): {reflect.TypeOf((*ast.UnaryExpr)(nil))}, + reflect.TypeOf(SendStmt{}): {reflect.TypeOf((*ast.SendStmt)(nil))}, + reflect.TypeOf(SelectStmt{}): {reflect.TypeOf((*ast.SelectStmt)(nil))}, + reflect.TypeOf(ImportSpec{}): {reflect.TypeOf((*ast.ImportSpec)(nil))}, + reflect.TypeOf(IfStmt{}): {reflect.TypeOf((*ast.IfStmt)(nil))}, + reflect.TypeOf(GoStmt{}): {reflect.TypeOf((*ast.GoStmt)(nil))}, + reflect.TypeOf(Field{}): {reflect.TypeOf((*ast.Field)(nil))}, + reflect.TypeOf(SelectorExpr{}): {reflect.TypeOf((*ast.SelectorExpr)(nil))}, + reflect.TypeOf(StructType{}): {reflect.TypeOf((*ast.StructType)(nil))}, + reflect.TypeOf(KeyValueExpr{}): {reflect.TypeOf((*ast.KeyValueExpr)(nil))}, + reflect.TypeOf(FuncType{}): {reflect.TypeOf((*ast.FuncType)(nil))}, + reflect.TypeOf(FuncLit{}): {reflect.TypeOf((*ast.FuncLit)(nil))}, + reflect.TypeOf(FuncDecl{}): {reflect.TypeOf((*ast.FuncDecl)(nil))}, + reflect.TypeOf(ChanType{}): {reflect.TypeOf((*ast.ChanType)(nil))}, + reflect.TypeOf(CallExpr{}): {reflect.TypeOf((*ast.CallExpr)(nil))}, + reflect.TypeOf(CaseClause{}): {reflect.TypeOf((*ast.CaseClause)(nil))}, + reflect.TypeOf(CommClause{}): {reflect.TypeOf((*ast.CommClause)(nil))}, + reflect.TypeOf(CompositeLit{}): {reflect.TypeOf((*ast.CompositeLit)(nil))}, + reflect.TypeOf(EmptyStmt{}): {reflect.TypeOf((*ast.EmptyStmt)(nil))}, + reflect.TypeOf(SwitchStmt{}): {reflect.TypeOf((*ast.SwitchStmt)(nil))}, + reflect.TypeOf(TypeSwitchStmt{}): {reflect.TypeOf((*ast.TypeSwitchStmt)(nil))}, + reflect.TypeOf(TypeAssertExpr{}): {reflect.TypeOf((*ast.TypeAssertExpr)(nil))}, + reflect.TypeOf(TypeSpec{}): {reflect.TypeOf((*ast.TypeSpec)(nil))}, + reflect.TypeOf(InterfaceType{}): {reflect.TypeOf((*ast.InterfaceType)(nil))}, + reflect.TypeOf(BranchStmt{}): {reflect.TypeOf((*ast.BranchStmt)(nil))}, + reflect.TypeOf(IncDecStmt{}): {reflect.TypeOf((*ast.IncDecStmt)(nil))}, + reflect.TypeOf(BasicLit{}): {reflect.TypeOf((*ast.BasicLit)(nil))}, +} + +var requiresTypeInfo = map[string]bool{ + "Function": true, + "Builtin": true, + "Object": true, +} + +type Parser struct { + // Allow nodes that rely on type information + AllowTypeInfo bool + + lex *lexer + cur item + last *item + items chan item +} + +func (p *Parser) Parse(s string) (Pattern, error) { + p.cur = item{} + p.last = nil + p.items = nil + + fset := token.NewFileSet() + p.lex = &lexer{ + f: fset.AddFile("
  • Custom Service Endpoints
  • +
  • + Resource Tagging +
  • AWS Provider Track on HashiCorp Learn
  • @@ -1109,6 +1112,9 @@
  • aws_ebs_volume
  • +
  • + aws_ebs_volumes +
  • aws_ec2_coip_pool
  • @@ -1133,6 +1139,18 @@
  • aws_ec2_local_gateway_route_tables
  • +
  • + aws_ec2_local_gateway_virtual_interface +
  • +
  • + aws_ec2_local_gateway_virtual_interface_group +
  • +
  • + aws_ec2_local_gateway_virtual_interface_groups +
  • +
  • + aws_ec2_spot_price +
  • aws_ec2_transit_gateway
  • @@ -1201,15 +1219,30 @@
  • aws_ec2_capacity_reservation
  • +
  • + aws_ec2_client_vpn_authorization_rule +
  • aws_ec2_client_vpn_endpoint
  • aws_ec2_client_vpn_network_association
  • +
  • + aws_ec2_client_vpn_route +
  • +
  • + aws_ec2_local_gateway_route +
  • +
  • + aws_ec2_local_gateway_route_table_vpc_association +
  • aws_ec2_fleet
  • +
  • + aws_ec2_tag +
  • aws_ec2_traffic_mirror_filter
  • @@ -1295,6 +1328,9 @@
  • Data Sources
  • diff --git a/website/docs/d/acm_certificate.html.markdown b/website/docs/d/acm_certificate.html.markdown index 53a3867efdb..c753ae432cb 100644 --- a/website/docs/d/acm_certificate.html.markdown +++ b/website/docs/d/acm_certificate.html.markdown @@ -16,20 +16,20 @@ it by domain without having to hard code the ARNs as input. ```hcl # Find a certificate that is issued -data "aws_acm_certificate" "example" { +data "aws_acm_certificate" "issued" { domain = "tf.example.com" statuses = ["ISSUED"] } # Find a certificate issued by (not imported into) ACM -data "aws_acm_certificate" "example" { +data "aws_acm_certificate" "amazon_issued" { domain = "tf.example.com" types = ["AMAZON_ISSUED"] most_recent = true } # Find a RSA 4096 bit certificate -data "aws_acm_certificate" "example" { +data "aws_acm_certificate" "rsa_4096" { domain = "tf.example.com" key_types = ["RSA_4096"] } @@ -37,16 +37,16 @@ data "aws_acm_certificate" "example" { ## Argument Reference - * `domain` - (Required) The domain of the certificate to look up. If no certificate is found with this name, an error will be returned. - * `key_types` - (Optional) A list of key algorithms to filter certificates. By default, ACM does not return all certificate types when searching. Valid values are `RSA_1024`, `RSA_2048`, `RSA_4096`, `EC_prime256v1`, `EC_secp384r1`, and `EC_secp521r1`. - * `statuses` - (Optional) A list of statuses on which to filter the returned list. Valid values are `PENDING_VALIDATION`, `ISSUED`, +* `domain` - (Required) The domain of the certificate to look up. If no certificate is found with this name, an error will be returned. +* `key_types` - (Optional) A list of key algorithms to filter certificates. By default, ACM does not return all certificate types when searching. Valid values are `RSA_1024`, `RSA_2048`, `RSA_4096`, `EC_prime256v1`, `EC_secp384r1`, and `EC_secp521r1`. +* `statuses` - (Optional) A list of statuses on which to filter the returned list. Valid values are `PENDING_VALIDATION`, `ISSUED`, `INACTIVE`, `EXPIRED`, `VALIDATION_TIMED_OUT`, `REVOKED` and `FAILED`. If no value is specified, only certificates in the `ISSUED` state are returned. - * `types` - (Optional) A list of types on which to filter the returned list. Valid values are `AMAZON_ISSUED` and `IMPORTED`. - * `most_recent` - (Optional) If set to true, it sorts the certificates matched by previous criteria by the NotBefore field, returning only the most recent one. If set to false, it returns an error if more than one certificate is found. Defaults to false. +* `types` - (Optional) A list of types on which to filter the returned list. Valid values are `AMAZON_ISSUED` and `IMPORTED`. +* `most_recent` - (Optional) If set to true, it sorts the certificates matched by previous criteria by the NotBefore field, returning only the most recent one. If set to false, it returns an error if more than one certificate is found. Defaults to false. ## Attributes Reference - * `arn` - Set to the ARN of the found certificate, suitable for referencing in other resources that support ACM certificates. - * `tags` - A mapping of tags for the resource. +* `arn` - Set to the ARN of the found certificate, suitable for referencing in other resources that support ACM certificates. +* `tags` - A mapping of tags for the resource. diff --git a/website/docs/d/acmpca_certificate_authority.html.markdown b/website/docs/d/acmpca_certificate_authority.html.markdown index f5e44bc8bc6..b721c3dabd5 100644 --- a/website/docs/d/acmpca_certificate_authority.html.markdown +++ b/website/docs/d/acmpca_certificate_authority.html.markdown @@ -35,11 +35,11 @@ In addition to all arguments above, the following attributes are exported: * `not_after` - Date and time after which the certificate authority is not valid. Only available after the certificate authority certificate has been imported. * `not_before` - Date and time before which the certificate authority is not valid. Only available after the certificate authority certificate has been imported. * `revocation_configuration` - Nested attribute containing revocation configuration. - * `revocation_configuration.0.crl_configuration` - Nested attribute containing configuration of the certificate revocation list (CRL), if any, maintained by the certificate authority. - * `revocation_configuration.0.crl_configuration.0.custom_cname` - Name inserted into the certificate CRL Distribution Points extension that enables the use of an alias for the CRL distribution point. - * `revocation_configuration.0.crl_configuration.0.enabled` - Boolean value that specifies whether certificate revocation lists (CRLs) are enabled. - * `revocation_configuration.0.crl_configuration.0.expiration_in_days` - Number of days until a certificate expires. - * `revocation_configuration.0.crl_configuration.0.s3_bucket_name` - Name of the S3 bucket that contains the CRL. + * `revocation_configuration.0.crl_configuration` - Nested attribute containing configuration of the certificate revocation list (CRL), if any, maintained by the certificate authority. + * `revocation_configuration.0.crl_configuration.0.custom_cname` - Name inserted into the certificate CRL Distribution Points extension that enables the use of an alias for the CRL distribution point. + * `revocation_configuration.0.crl_configuration.0.enabled` - Boolean value that specifies whether certificate revocation lists (CRLs) are enabled. + * `revocation_configuration.0.crl_configuration.0.expiration_in_days` - Number of days until a certificate expires. + * `revocation_configuration.0.crl_configuration.0.s3_bucket_name` - Name of the S3 bucket that contains the CRL. * `serial` - Serial number of the certificate authority. Only available after the certificate authority certificate has been imported. * `status` - Status of the certificate authority. * `tags` - Specifies a key-value map of user-defined tags that are attached to the certificate authority. diff --git a/website/docs/d/ami.html.markdown b/website/docs/d/ami.html.markdown index 989cfafcea5..e8e99a13444 100644 --- a/website/docs/d/ami.html.markdown +++ b/website/docs/d/ami.html.markdown @@ -3,7 +3,7 @@ subcategory: "EC2" layout: "aws" page_title: "AWS: aws_ami" description: |- - Get information on a Amazon Machine Image (AMI). + Get information on an Amazon Machine Image (AMI). --- # Data Source: aws_ami @@ -70,21 +70,22 @@ are exported: ~> **NOTE:** Some values are not always set and may not be available for interpolation. +* `arn` - The ARN of the AMI. * `architecture` - The OS architecture of the AMI (ie: `i386` or `x86_64`). * `block_device_mappings` - The block device mappings of the AMI. - * `block_device_mappings.#.device_name` - The physical name of the device. - * `block_device_mappings.#.ebs.delete_on_termination` - `true` if the EBS volume + * `block_device_mappings.#.device_name` - The physical name of the device. + * `block_device_mappings.#.ebs.delete_on_termination` - `true` if the EBS volume will be deleted on termination. - * `block_device_mappings.#.ebs.encrypted` - `true` if the EBS volume + * `block_device_mappings.#.ebs.encrypted` - `true` if the EBS volume is encrypted. - * `block_device_mappings.#.ebs.iops` - `0` if the EBS volume is + * `block_device_mappings.#.ebs.iops` - `0` if the EBS volume is not a provisioned IOPS image, otherwise the supported IOPS count. - * `block_device_mappings.#.ebs.snapshot_id` - The ID of the snapshot. - * `block_device_mappings.#.ebs.volume_size` - The size of the volume, in GiB. - * `block_device_mappings.#.ebs.volume_type` - The volume type. - * `block_device_mappings.#.no_device` - Suppresses the specified device + * `block_device_mappings.#.ebs.snapshot_id` - The ID of the snapshot. + * `block_device_mappings.#.ebs.volume_size` - The size of the volume, in GiB. + * `block_device_mappings.#.ebs.volume_type` - The volume type. + * `block_device_mappings.#.no_device` - Suppresses the specified device included in the block device mapping of the AMI. - * `block_device_mappings.#.virtual_name` - The virtual device name (for + * `block_device_mappings.#.virtual_name` - The virtual device name (for instance stores). * `creation_date` - The date and time the image was created. * `description` - The description of the AMI that was provided during image @@ -101,8 +102,8 @@ interpolation. * `owner_id` - The AWS account ID of the image owner. * `platform` - The value is Windows for `Windows` AMIs; otherwise blank. * `product_codes` - Any product codes associated with the AMI. - * `product_codes.#.product_code_id` - The product code. - * `product_codes.#.product_code_type` - The type of product code. + * `product_codes.#.product_code_id` - The product code. + * `product_codes.#.product_code_type` - The type of product code. * `public` - `true` if the image has public launch permissions. * `ramdisk_id` - The RAM disk associated with the image, if any. Only applicable for machine images. @@ -114,11 +115,11 @@ interpolation. * `state` - The current state of the AMI. If the state is `available`, the image is successfully registered and can be used to launch an instance. * `state_reason` - Describes a state change. Fields are `UNSET` if not available. - * `state_reason.code` - The reason code for the state change. - * `state_reason.message` - The message for the state change. + * `state_reason.code` - The reason code for the state change. + * `state_reason.message` - The message for the state change. * `tags` - Any tags assigned to the image. - * `tags.#.key` - The key name of the tag. - * `tags.#.value` - The value of the tag. + * `tags.#.key` - The key name of the tag. + * `tags.#.value` - The value of the tag. * `virtualization_type` - The type of virtualization of the AMI (ie: `hvm` or `paravirtual`). diff --git a/website/docs/d/api_gateway_api_key.html.markdown b/website/docs/d/api_gateway_api_key.html.markdown index f2f6ea6f89f..b4a737ca23a 100644 --- a/website/docs/d/api_gateway_api_key.html.markdown +++ b/website/docs/d/api_gateway_api_key.html.markdown @@ -21,15 +21,15 @@ data "aws_api_gateway_api_key" "my_api_key" { ## Argument Reference - * `id` - (Required) The ID of the API Key to look up. +* `id` - (Required) The ID of the API Key to look up. ## Attributes Reference - * `id` - Set to the ID of the API Key. - * `name` - Set to the name of the API Key. - * `value` - Set to the value of the API Key. - * `created_date` - The date and time when the API Key was created. - * `last_updated_date` - The date and time when the API Key was last updated. - * `description` - The description of the API Key. - * `enabled` - Specifies whether the API Key is enabled. - * `tags` - A map of tags for the resource. +* `id` - Set to the ID of the API Key. +* `name` - Set to the name of the API Key. +* `value` - Set to the value of the API Key. +* `created_date` - The date and time when the API Key was created. +* `last_updated_date` - The date and time when the API Key was last updated. +* `description` - The description of the API Key. +* `enabled` - Specifies whether the API Key is enabled. +* `tags` - A map of tags for the resource. diff --git a/website/docs/d/api_gateway_resource.html.markdown b/website/docs/d/api_gateway_resource.html.markdown index e4df007c2ef..46e4d476f87 100644 --- a/website/docs/d/api_gateway_resource.html.markdown +++ b/website/docs/d/api_gateway_resource.html.markdown @@ -19,18 +19,18 @@ data "aws_api_gateway_rest_api" "my_rest_api" { } data "aws_api_gateway_resource" "my_resource" { - rest_api_id = "${data.aws_api_gateway_rest_api.my_rest_api.id}" + rest_api_id = data.aws_api_gateway_rest_api.my_rest_api.id path = "/endpoint/path" } ``` ## Argument Reference - * `rest_api_id` - (Required) The REST API id that owns the resource. If no REST API is found, an error will be returned. - * `path` - (Required) The full path of the resource. If no path is found, an error will be returned. +* `rest_api_id` - (Required) The REST API id that owns the resource. If no REST API is found, an error will be returned. +* `path` - (Required) The full path of the resource. If no path is found, an error will be returned. ## Attributes Reference - * `id` - Set to the ID of the found Resource. - * `parent_id` - Set to the ID of the parent Resource. - * `path_part` - Set to the path relative to the parent Resource. +* `id` - Set to the ID of the found Resource. +* `parent_id` - Set to the ID of the parent Resource. +* `path_part` - Set to the path relative to the parent Resource. diff --git a/website/docs/d/api_gateway_vpc_link.html.markdown b/website/docs/d/api_gateway_vpc_link.html.markdown index 472f8fd1b65..c53eda4396b 100644 --- a/website/docs/d/api_gateway_vpc_link.html.markdown +++ b/website/docs/d/api_gateway_vpc_link.html.markdown @@ -23,14 +23,14 @@ data "aws_api_gateway_vpc_link" "my_api_gateway_vpc_link" { ## Argument Reference - * `name` - (Required) The name of the API Gateway VPC Link to look up. If no API Gateway VPC Link is found with this name, an error will be returned. +* `name` - (Required) The name of the API Gateway VPC Link to look up. If no API Gateway VPC Link is found with this name, an error will be returned. If multiple API Gateway VPC Links are found with this name, an error will be returned. ## Attributes Reference - * `id` - Set to the ID of the found API Gateway VPC Link. - * `description` - The description of the VPC link. - * `status` - The status of the VPC link. - * `status_message` - The status message of the VPC link. - * `target_arns` - The list of network load balancer arns in the VPC targeted by the VPC link. Currently AWS only supports 1 target. - * `tags` - Key-value map of resource tags +* `id` - Set to the ID of the found API Gateway VPC Link. +* `description` - The description of the VPC link. +* `status` - The status of the VPC link. +* `status_message` - The status message of the VPC link. +* `target_arns` - The list of network load balancer arns in the VPC targeted by the VPC link. Currently AWS only supports 1 target. +* `tags` - Key-value map of resource tags diff --git a/website/docs/d/autoscaling_groups.html.markdown b/website/docs/d/autoscaling_groups.html.markdown index 4a5011f5c9d..a19dd412c3e 100644 --- a/website/docs/d/autoscaling_groups.html.markdown +++ b/website/docs/d/autoscaling_groups.html.markdown @@ -27,7 +27,7 @@ data "aws_autoscaling_groups" "groups" { } resource "aws_autoscaling_notification" "slack_notifications" { - group_names = ["${data.aws_autoscaling_groups.groups.names}"] + group_names = data.aws_autoscaling_groups.groups.names notifications = [ "autoscaling:EC2_INSTANCE_LAUNCH", @@ -43,8 +43,8 @@ resource "aws_autoscaling_notification" "slack_notifications" { ## Argument Reference * `filter` - (Optional) A filter used to scope the list e.g. by tags. See [related docs](http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_Filter.html). - * `name` - (Required) The name of the filter. The valid values are: `auto-scaling-group`, `key`, `value`, and `propagate-at-launch`. - * `values` - (Required) The value of the filter. + * `name` - (Required) The name of the filter. The valid values are: `auto-scaling-group`, `key`, `value`, and `propagate-at-launch`. + * `values` - (Required) The value of the filter. ## Attributes Reference diff --git a/website/docs/d/availability_zone.html.markdown b/website/docs/d/availability_zone.html.markdown index b4be1d4fe6a..4252243f644 100644 --- a/website/docs/d/availability_zone.html.markdown +++ b/website/docs/d/availability_zone.html.markdown @@ -58,13 +58,13 @@ data "aws_availability_zone" "example" { # Create a VPC for the region associated with the AZ resource "aws_vpc" "example" { - cidr_block = "${cidrsubnet("10.0.0.0/8", 4, var.region_number[data.aws_availability_zone.example.region])}" + cidr_block = cidrsubnet("10.0.0.0/8", 4, var.region_number[data.aws_availability_zone.example.region]) } # Create a subnet for the AZ within the regional VPC resource "aws_subnet" "example" { - vpc_id = "${aws_vpc.example.id}" - cidr_block = "${cidrsubnet(aws_vpc.example.cidr_block, 4, var.az_number[data.aws_availability_zone.example.name_suffix])}" + vpc_id = aws_vpc.example.id + cidr_block = cidrsubnet(aws_vpc.example.cidr_block, 4, var.az_number[data.aws_availability_zone.example.name_suffix]) } ``` diff --git a/website/docs/d/availability_zones.html.markdown b/website/docs/d/availability_zones.html.markdown index 5939110abe4..0d8552f277c 100644 --- a/website/docs/d/availability_zones.html.markdown +++ b/website/docs/d/availability_zones.html.markdown @@ -73,9 +73,9 @@ data "aws_availability_zones" "example" { The following arguments are supported: * `all_availability_zones` - (Optional) Set to `true` to include all Availability Zones and Local Zones regardless of your opt in status. -* `blacklisted_names` - (Optional) List of blacklisted Availability Zone names. -* `blacklisted_zone_ids` - (Optional) List of blacklisted Availability Zone IDs. * `filter` - (Optional) Configuration block(s) for filtering. Detailed below. +* `exclude_names` - (Optional) List of Availability Zone names to exclude. +* `exclude_zone_ids` - (Optional) List of Availability Zone IDs to exclude. * `state` - (Optional) Allows to filter list of Availability Zones based on their current state. Can be either `"available"`, `"information"`, `"impaired"` or `"unavailable"`. By default the list includes a complete set of Availability Zones diff --git a/website/docs/d/backup_selection.html.markdown b/website/docs/d/backup_selection.html.markdown index 416f384c00d..cf5e36397d9 100644 --- a/website/docs/d/backup_selection.html.markdown +++ b/website/docs/d/backup_selection.html.markdown @@ -14,7 +14,7 @@ Use this data source to get information on an existing backup selection. ```hcl data "aws_backup_selection" "example" { - plan_id = "${data.aws_backup_plan.example.id}" + plan_id = data.aws_backup_plan.example.id selection_id = "selection-id-example" } ``` diff --git a/website/docs/d/batch_job_queue.html.markdown b/website/docs/d/batch_job_queue.html.markdown index 4e2f0ee291e..efe2a78063f 100644 --- a/website/docs/d/batch_job_queue.html.markdown +++ b/website/docs/d/batch_job_queue.html.markdown @@ -38,5 +38,5 @@ In addition to all arguments above, the following attributes are exported: associated with the same compute environment. * `compute_environment_order` - The compute environments that are attached to the job queue and the order in which job placement is preferred. Compute environments are selected for job placement in ascending order. - * `compute_environment_order.#.order` - The order of the compute environment. - * `compute_environment_order.#.compute_environment` - The ARN of the compute environment. + * `compute_environment_order.#.order` - The order of the compute environment. + * `compute_environment_order.#.compute_environment` - The ARN of the compute environment. diff --git a/website/docs/d/billing_service_account.html.markdown b/website/docs/d/billing_service_account.html.markdown index 69982b1f763..5680f0c9ace 100644 --- a/website/docs/d/billing_service_account.html.markdown +++ b/website/docs/d/billing_service_account.html.markdown @@ -8,7 +8,7 @@ description: |- # Data Source: aws_billing_service_account -Use this data source to get the Account ID of the [AWS Billing and Cost Management Service Account](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-getting-started.html#step-2) for the purpose of whitelisting in S3 bucket policy. +Use this data source to get the Account ID of the [AWS Billing and Cost Management Service Account](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-getting-started.html#step-2) for the purpose of permitting in S3 bucket policy. ## Example Usage diff --git a/website/docs/d/caller_identity.html.markdown b/website/docs/d/caller_identity.html.markdown index ef072972409..e32d1ea2d38 100644 --- a/website/docs/d/caller_identity.html.markdown +++ b/website/docs/d/caller_identity.html.markdown @@ -18,15 +18,15 @@ which Terraform is authorized. data "aws_caller_identity" "current" {} output "account_id" { - value = "${data.aws_caller_identity.current.account_id}" + value = data.aws_caller_identity.current.account_id } output "caller_arn" { - value = "${data.aws_caller_identity.current.arn}" + value = data.aws_caller_identity.current.arn } output "caller_user" { - value = "${data.aws_caller_identity.current.user_id}" + value = data.aws_caller_identity.current.user_id } ``` diff --git a/website/docs/d/canonical_user_id.html.markdown b/website/docs/d/canonical_user_id.html.markdown index 11c17f31cbc..6bb82140cb2 100644 --- a/website/docs/d/canonical_user_id.html.markdown +++ b/website/docs/d/canonical_user_id.html.markdown @@ -18,7 +18,7 @@ for the effective account in which Terraform is working. data "aws_canonical_user_id" "current" {} output "canonical_user_id" { - value = "${data.aws_canonical_user_id.current.id}" + value = data.aws_canonical_user_id.current.id } ``` diff --git a/website/docs/d/cloudformation_export.html.markdown b/website/docs/d/cloudformation_export.html.markdown index d62c12b54ec..f39404bc0e3 100644 --- a/website/docs/d/cloudformation_export.html.markdown +++ b/website/docs/d/cloudformation_export.html.markdown @@ -22,8 +22,8 @@ data "aws_cloudformation_export" "subnet_id" { resource "aws_instance" "web" { ami = "ami-abb07bcb" - instance_type = "t1.micro" - subnet_id = "${data.aws_cloudformation_export.subnet_id.value}" + instance_type = "t2.micro" + subnet_id = data.aws_cloudformation_export.subnet_id.value } ``` diff --git a/website/docs/d/cloudformation_stack.html.markdown b/website/docs/d/cloudformation_stack.html.markdown index 34e5a03d0f8..5e429001548 100644 --- a/website/docs/d/cloudformation_stack.html.markdown +++ b/website/docs/d/cloudformation_stack.html.markdown @@ -20,8 +20,8 @@ data "aws_cloudformation_stack" "network" { resource "aws_instance" "web" { ami = "ami-abb07bcb" - instance_type = "t1.micro" - subnet_id = "${data.aws_cloudformation_stack.network.outputs["SubnetId"]}" + instance_type = "t2.micro" + subnet_id = data.aws_cloudformation_stack.network.outputs["SubnetId"] tags = { Name = "HelloWorld" diff --git a/website/docs/d/cloudfront_distribution.html.markdown b/website/docs/d/cloudfront_distribution.html.markdown index 68b0044458a..d7cde052318 100644 --- a/website/docs/d/cloudfront_distribution.html.markdown +++ b/website/docs/d/cloudfront_distribution.html.markdown @@ -16,36 +16,35 @@ Use this data source to retrieve information about a CloudFront distribution. data "aws_cloudfront_distribution" "test" { id = "EDFDVBD632BHDS5" } - ``` ## Argument Reference - * `id` - The identifier for the distribution. For example: `EDFDVBD632BHDS5`. +* `id` - The identifier for the distribution. For example: `EDFDVBD632BHDS5`. ## Attributes Reference The following attributes are exported: - * `id` - The identifier for the distribution. For example: `EDFDVBD632BHDS5`. +* `id` - The identifier for the distribution. For example: `EDFDVBD632BHDS5`. - * `arn` - The ARN (Amazon Resource Name) for the distribution. For example: arn:aws:cloudfront::123456789012:distribution/EDFDVBD632BHDS5, where 123456789012 is your AWS account ID. +* `arn` - The ARN (Amazon Resource Name) for the distribution. For example: arn:aws:cloudfront::123456789012:distribution/EDFDVBD632BHDS5, where 123456789012 is your AWS account ID. - * `status` - The current status of the distribution. `Deployed` if the +* `status` - The current status of the distribution. `Deployed` if the distribution's information is fully propagated throughout the Amazon CloudFront system. - * `domain_name` - The domain name corresponding to the distribution. For +* `domain_name` - The domain name corresponding to the distribution. For example: `d604721fxaaqy9.cloudfront.net`. - * `last_modified_time` - The date and time the distribution was last modified. +* `last_modified_time` - The date and time the distribution was last modified. - * `in_progress_validation_batches` - The number of invalidation batches +* `in_progress_validation_batches` - The number of invalidation batches currently in progress. - * `etag` - The current version of the distribution's information. For example: +* `etag` - The current version of the distribution's information. For example: `E2QWRUHAPOMQZL`. - * `hosted_zone_id` - The CloudFront Route 53 zone ID that can be used to +* `hosted_zone_id` - The CloudFront Route 53 zone ID that can be used to route an [Alias Resource Record Set][7] to. This attribute is simply an alias for the zone ID `Z2FDTNDATAQYW2`. diff --git a/website/docs/d/cloudhsm_v2_cluster.html.markdown b/website/docs/d/cloudhsm_v2_cluster.html.markdown index 8211f040df0..dd5ea96b69f 100644 --- a/website/docs/d/cloudhsm_v2_cluster.html.markdown +++ b/website/docs/d/cloudhsm_v2_cluster.html.markdown @@ -33,9 +33,9 @@ The following attributes are exported: * `security_group_id` - The ID of the security group associated with the CloudHSM cluster. * `subnet_ids` - The IDs of subnets in which cluster operates. * `cluster_certificates` - The list of cluster certificates. - * `cluster_certificates.0.cluster_certificate` - The cluster certificate issued (signed) by the issuing certificate authority (CA) of the cluster's owner. - * `cluster_certificates.0.cluster_csr` - The certificate signing request (CSR). Available only in UNINITIALIZED state. - * `cluster_certificates.0.aws_hardware_certificate` - The HSM hardware certificate issued (signed) by AWS CloudHSM. - * `cluster_certificates.0.hsm_certificate` - The HSM certificate issued (signed) by the HSM hardware. - * `cluster_certificates.0.manufacturer_hardware_certificate` - The HSM hardware certificate issued (signed) by the hardware manufacturer. + * `cluster_certificates.0.cluster_certificate` - The cluster certificate issued (signed) by the issuing certificate authority (CA) of the cluster's owner. + * `cluster_certificates.0.cluster_csr` - The certificate signing request (CSR). Available only in UNINITIALIZED state. + * `cluster_certificates.0.aws_hardware_certificate` - The HSM hardware certificate issued (signed) by AWS CloudHSM. + * `cluster_certificates.0.hsm_certificate` - The HSM certificate issued (signed) by the HSM hardware. + * `cluster_certificates.0.manufacturer_hardware_certificate` - The HSM hardware certificate issued (signed) by the hardware manufacturer. The number of available cluster certificates may vary depending on state of the cluster. diff --git a/website/docs/d/cognito_user_pools.markdown b/website/docs/d/cognito_user_pools.markdown index f0c2ac116a2..ee325efbabb 100644 --- a/website/docs/d/cognito_user_pools.markdown +++ b/website/docs/d/cognito_user_pools.markdown @@ -14,18 +14,18 @@ Use this data source to get a list of cognito user pools. ```hcl data "aws_api_gateway_rest_api" "selected" { - name = "${var.api_gateway_name}" + name = var.api_gateway_name } data "aws_cognito_user_pools" "selected" { - name = "${var.cognito_user_pool_name}" + name = var.cognito_user_pool_name } resource "aws_api_gateway_authorizer" "cognito" { name = "cognito" type = "COGNITO_USER_POOLS" - rest_api_id = "${data.aws_api_gateway_rest_api.selected.id}" - provider_arns = ["${data.aws_cognito_user_pools.selected.arns}"] + rest_api_id = data.aws_api_gateway_rest_api.selected.id + provider_arns = data.aws_cognito_user_pools.selected.arns } ``` diff --git a/website/docs/d/customer_gateway.html.markdown b/website/docs/d/customer_gateway.html.markdown index 959129e2a81..9678384a812 100644 --- a/website/docs/d/customer_gateway.html.markdown +++ b/website/docs/d/customer_gateway.html.markdown @@ -21,14 +21,14 @@ data "aws_customer_gateway" "foo" { } resource "aws_vpn_gateway" "main" { - vpc_id = "${aws_vpc.main.id}" + vpc_id = aws_vpc.main.id amazon_side_asn = 7224 } resource "aws_vpn_connection" "transit" { - vpn_gateway_id = "${aws_vpn_gateway.main.id}" - customer_gateway_id = "${data.aws_customer_gateway.foo.id}" - type = "${data.aws_customer_gateway.foo.type}" + vpn_gateway_id = aws_vpn_gateway.main.id + customer_gateway_id = data.aws_customer_gateway.foo.id + type = data.aws_customer_gateway.foo.type static_routes_only = false } ``` @@ -46,6 +46,7 @@ The following arguments are supported: In addition to the arguments above, the following attributes are exported: +* `arn` - The ARN of the customer gateway. * `bgp_asn` - (Optional) The gateway's Border Gateway Protocol (BGP) Autonomous System Number (ASN). * `ip_address` - (Optional) The IP address of the gateway's Internet-routable external interface. * `tags` - Map of key-value pairs assigned to the gateway. diff --git a/website/docs/d/db_cluster_snapshot.html.markdown b/website/docs/d/db_cluster_snapshot.html.markdown index de1975979c8..acc178bddd6 100644 --- a/website/docs/d/db_cluster_snapshot.html.markdown +++ b/website/docs/d/db_cluster_snapshot.html.markdown @@ -25,16 +25,16 @@ data "aws_db_cluster_snapshot" "development_final_snapshot" { # a new dev database. resource "aws_rds_cluster" "aurora" { cluster_identifier = "development_cluster" - snapshot_identifier = "${data.aws_db_cluster_snapshot.development_final_snapshot.id}" + snapshot_identifier = data.aws_db_cluster_snapshot.development_final_snapshot.id db_subnet_group_name = "my_db_subnet_group" lifecycle { - ignore_changes = ["snapshot_identifier"] + ignore_changes = [snapshot_identifier] } } resource "aws_rds_cluster_instance" "aurora" { - cluster_identifier = "${aws_rds_cluster.aurora.id}" + cluster_identifier = aws_rds_cluster.aurora.id instance_class = "db.t2.small" db_subnet_group_name = "my_db_subnet_group" } diff --git a/website/docs/d/db_event_categories.html.markdown b/website/docs/d/db_event_categories.html.markdown index b9f6d2778b9..2652095fbd2 100644 --- a/website/docs/d/db_event_categories.html.markdown +++ b/website/docs/d/db_event_categories.html.markdown @@ -16,7 +16,7 @@ List the event categories of all the RDS resources. data "aws_db_event_categories" "example" {} output "example" { - value = "${data.aws_db_event_categories.example.event_categories}" + value = data.aws_db_event_categories.example.event_categories } ``` @@ -28,7 +28,7 @@ data "aws_db_event_categories" "example" { } output "example" { - value = "${data.aws_db_event_categories.example.event_categories}" + value = data.aws_db_event_categories.example.event_categories } ``` diff --git a/website/docs/d/db_snapshot.html.markdown b/website/docs/d/db_snapshot.html.markdown index 68bca155d91..cecda33f7ac 100644 --- a/website/docs/d/db_snapshot.html.markdown +++ b/website/docs/d/db_snapshot.html.markdown @@ -29,7 +29,7 @@ resource "aws_db_instance" "prod" { } data "aws_db_snapshot" "latest_prod_snapshot" { - db_instance_identifier = "${aws_db_instance.prod.id}" + db_instance_identifier = aws_db_instance.prod.id most_recent = true } @@ -37,10 +37,10 @@ data "aws_db_snapshot" "latest_prod_snapshot" { resource "aws_db_instance" "dev" { instance_class = "db.t2.micro" name = "mydbdev" - snapshot_identifier = "${data.aws_db_snapshot.latest_prod_snapshot.id}" + snapshot_identifier = data.aws_db_snapshot.latest_prod_snapshot.id lifecycle { - ignore_changes = ["snapshot_identifier"] + ignore_changes = [snapshot_identifier] } } ``` diff --git a/website/docs/d/directory_service_directory.html.markdown b/website/docs/d/directory_service_directory.html.markdown index d9f0173205c..a07162e68a6 100644 --- a/website/docs/d/directory_service_directory.html.markdown +++ b/website/docs/d/directory_service_directory.html.markdown @@ -14,38 +14,39 @@ Get attributes of AWS Directory Service directory (SimpleAD, Managed AD, AD Conn ```hcl data "aws_directory_service_directory" "example" { - directory_id = "${aws_directory_service_directory.main.id}" + directory_id = aws_directory_service_directory.main.id } ``` ## Argument Reference - * `directory_id` - (Required) The ID of the directory. +* `directory_id` - (Required) The ID of the directory. ## Attributes Reference - * `type` - The directory type (`SimpleAD`, `ADConnector` or `MicrosoftAD`). - * `edition` - (for `MicrosoftAD`) The Microsoft AD edition (`Standard` or `Enterprise`). - * `name` - The fully qualified name for the directory/connector. - * `password` - The password for the directory administrator or connector user. - * `size` - (for `SimpleAD` and `ADConnector`) The size of the directory/connector (`Small` or `Large`). - * `alias` - The alias for the directory/connector, such as `d-991708b282.awsapps.com`. - * `description` - A textual description for the directory/connector. - * `short_name` - The short name of the directory/connector, such as `CORP`. - * `enable_sso` - The directory/connector single-sign on status. - * `access_url` - The access URL for the directory/connector, such as http://alias.awsapps.com. - * `dns_ip_addresses` - A list of IP addresses of the DNS servers for the directory/connector. - * `security_group_id` - The ID of the security group created by the directory/connector. - * `tags` – A map of tags assigned to the directory/connector. +* `type` - The directory type (`SimpleAD`, `ADConnector` or `MicrosoftAD`). +* `edition` - (for `MicrosoftAD`) The Microsoft AD edition (`Standard` or `Enterprise`). +* `name` - The fully qualified name for the directory/connector. +* `password` - The password for the directory administrator or connector user. +* `size` - (for `SimpleAD` and `ADConnector`) The size of the directory/connector (`Small` or `Large`). +* `alias` - The alias for the directory/connector, such as `d-991708b282.awsapps.com`. +* `description` - A textual description for the directory/connector. +* `short_name` - The short name of the directory/connector, such as `CORP`. +* `enable_sso` - The directory/connector single-sign on status. +* `access_url` - The access URL for the directory/connector, such as http://alias.awsapps.com. +* `dns_ip_addresses` - A list of IP addresses of the DNS servers for the directory/connector. +* `security_group_id` - The ID of the security group created by the directory/connector. +* `tags` – A map of tags assigned to the directory/connector. `vpc_settings` (for `SimpleAD` and `MicrosoftAD`) is also exported with the following attributes: - * `subnet_ids` - The identifiers of the subnets for the directory servers (2 subnets in 2 different AZs). - * `vpc_id` - The ID of the VPC that the directory is in. +* `subnet_ids` - The identifiers of the subnets for the directory servers (2 subnets in 2 different AZs). +* `vpc_id` - The ID of the VPC that the directory is in. `connect_settings` (for `ADConnector`) is also exported with the following attributes: - * `customer_username` - The username corresponding to the password provided. - * `customer_dns_ips` - The DNS IP addresses of the domain to connect to. - * `subnet_ids` - The identifiers of the subnets for the connector servers (2 subnets in 2 different AZs). - * `vpc_id` - The ID of the VPC that the connector is in. +* `connect_ips` - The IP addresses of the AD Connector servers. +* `customer_username` - The username corresponding to the password provided. +* `customer_dns_ips` - The DNS IP addresses of the domain to connect to. +* `subnet_ids` - The identifiers of the subnets for the connector servers (2 subnets in 2 different AZs). +* `vpc_id` - The ID of the VPC that the connector is in. diff --git a/website/docs/d/ebs_default_kms_key.html.markdown b/website/docs/d/ebs_default_kms_key.html.markdown index 0dc3608dbeb..c36d96ca076 100644 --- a/website/docs/d/ebs_default_kms_key.html.markdown +++ b/website/docs/d/ebs_default_kms_key.html.markdown @@ -19,8 +19,7 @@ resource "aws_ebs_volume" "example" { availability_zone = "us-west-2a" encrypted = true - kms_key_id = "${data.aws_ebs_default_kms_key.current.key_arn}" - + kms_key_id = data.aws_ebs_default_kms_key.current.key_arn } ``` diff --git a/website/docs/d/ebs_snapshot.html.markdown b/website/docs/d/ebs_snapshot.html.markdown index 428297c1381..f0a7ea1c110 100644 --- a/website/docs/d/ebs_snapshot.html.markdown +++ b/website/docs/d/ebs_snapshot.html.markdown @@ -50,6 +50,7 @@ several valid keys, for a full reference, check out In addition to all arguments above, the following attributes are exported: +* `arn` - Amazon Resource Name (ARN) of the EBS Snapshot. * `id` - The snapshot ID (e.g. snap-59fcb34e). * `snapshot_id` - The snapshot ID (e.g. snap-59fcb34e). * `description` - A description for the snapshot diff --git a/website/docs/d/ebs_volumes.html.markdown b/website/docs/d/ebs_volumes.html.markdown new file mode 100644 index 00000000000..46d8ae4fe89 --- /dev/null +++ b/website/docs/d/ebs_volumes.html.markdown @@ -0,0 +1,68 @@ +--- +subcategory: "VPC" +layout: "aws" +page_title: "AWS: aws_ebs_volumes" +description: |- + Provides identifying information for EBS volumes matching given criteria +--- + +# Data Source: aws_ebs_volumes + +`aws_ebs_volumes` provides identifying information for EBS volumes matching given criteria. + +This data source can be useful for getting a list of volume IDs with (for example) matching tags. + +## Example Usage + +The following demonstrates obtaining a map of availability zone to EBS volume ID for volumes with a given tag value. + +```hcl +data "aws_ebs_volumes" "example" { + tags = { + VolumeSet = "TestVolumeSet" + } +} + +data "aws_ebs_volume" "example" { + for_each = data.aws_ebs_volumes.example.ids + filter { + name = "volume-id" + values = [each.value] + } +} + +output "availability_zone_to_volume_id" { + value = { for s in data.aws_ebs_volume.example : s.id => s.availability_zone } +} +``` + +## Argument Reference + +* `filter` - (Optional) Custom filter block as described below. + +* `tags` - (Optional) A map of tags, each pair of which must exactly match + a pair on the desired volumes. + +More complex filters can be expressed using one or more `filter` sub-blocks, +which take the following arguments: + +* `name` - (Required) The name of the field to filter by, as defined by + [the underlying AWS API](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVolumes.html). + For example, if matching against the `size` filter, use: + +```hcl +data "aws_ebs_volumes" "ten_or_twenty_gb_volumes" { + filter { + name = "size" + values = ["10", "20"] + } +} +``` + +* `values` - (Required) Set of values that are accepted for the given field. + EBS Volume IDs will be selected if any one of the given values match. + +## Attributes Reference + +* `ids` - A set of all the EBS Volume IDs found. This data source will fail if + no volumes match the provided criteria. diff --git a/website/docs/d/ec2_coip_pool.html.markdown b/website/docs/d/ec2_coip_pool.html.markdown index 1ba9986fbf5..0114b780009 100644 --- a/website/docs/d/ec2_coip_pool.html.markdown +++ b/website/docs/d/ec2_coip_pool.html.markdown @@ -22,7 +22,7 @@ The following example returns a specific coip pool ID variable "coip_pool_id" {} data "aws_ec2_coip_pool" "selected" { - id = "${var.coip_pool_id}" + id = var.coip_pool_id } ``` diff --git a/website/docs/d/ec2_coip_pools.html.markdown b/website/docs/d/ec2_coip_pools.html.markdown index 1289e5f5da6..952d2ae0cf1 100644 --- a/website/docs/d/ec2_coip_pools.html.markdown +++ b/website/docs/d/ec2_coip_pools.html.markdown @@ -18,7 +18,7 @@ The following shows outputing all COIP Pool Ids. data "aws_ec2_coip_pools" "foo" {} output "foo" { - value = "${data.aws_ec2_coip_pools.foo.ids}" + value = data.aws_ec2_coip_pools.foo.ids } ``` diff --git a/website/docs/d/ec2_instance_type_offering.html.markdown b/website/docs/d/ec2_instance_type_offering.html.markdown index 46cf5ba9d83..6d3e14b70f2 100644 --- a/website/docs/d/ec2_instance_type_offering.html.markdown +++ b/website/docs/d/ec2_instance_type_offering.html.markdown @@ -16,10 +16,10 @@ Information about single EC2 Instance Type Offering. data "aws_ec2_instance_type_offering" "example" { filter { name = "instance-type" - values = ["t1.micro", "t2.micro", "t3.micro"] + values = ["t2.micro", "t3.micro"] } - preferred_instance_types = ["t3.micro", "t2.micro", "t1.micro"] + preferred_instance_types = ["t3.micro", "t2.micro"] } ``` diff --git a/website/docs/d/ec2_local_gateway.html.markdown b/website/docs/d/ec2_local_gateway.html.markdown index f4df1116abf..ba1347cb3bd 100644 --- a/website/docs/d/ec2_local_gateway.html.markdown +++ b/website/docs/d/ec2_local_gateway.html.markdown @@ -18,7 +18,7 @@ The following example shows how one might accept a local gateway id as a variabl variable "local_gateway_id" {} data "aws_ec2_local_gateway" "selected" { - id = "${var.local_gateway_id}" + id = var.local_gateway_id } ``` diff --git a/website/docs/d/ec2_local_gateway_route_table.html.markdown b/website/docs/d/ec2_local_gateway_route_table.html.markdown index 5b274e78977..a884015773e 100644 --- a/website/docs/d/ec2_local_gateway_route_table.html.markdown +++ b/website/docs/d/ec2_local_gateway_route_table.html.markdown @@ -19,8 +19,9 @@ The following example returns a specific local gateway route table ID ```hcl variable "aws_ec2_local_gateway_route_table" {} + data "aws_ec2_local_gateway_route_table" "selected" { - local_gateway_route_table_id = "${var.aws_ec2_local_gateway_route_table}" + local_gateway_route_table_id = var.aws_ec2_local_gateway_route_table } ``` diff --git a/website/docs/d/ec2_local_gateway_route_tables.html.markdown b/website/docs/d/ec2_local_gateway_route_tables.html.markdown index 324f7c178da..c84d9d89f50 100644 --- a/website/docs/d/ec2_local_gateway_route_tables.html.markdown +++ b/website/docs/d/ec2_local_gateway_route_tables.html.markdown @@ -16,8 +16,9 @@ The following shows outputing all Local Gateway Route Table Ids. ```hcl data "aws_ec2_local_gateway_route_table" "foo" {} + output "foo" { - value = "${data.aws_ec2_local_gateway_route_table.foo.ids}" + value = data.aws_ec2_local_gateway_route_table.foo.ids } ``` diff --git a/website/docs/d/ec2_local_gateway_virtual_interface.html.markdown b/website/docs/d/ec2_local_gateway_virtual_interface.html.markdown new file mode 100644 index 00000000000..2a9edab0739 --- /dev/null +++ b/website/docs/d/ec2_local_gateway_virtual_interface.html.markdown @@ -0,0 +1,47 @@ +--- +subcategory: "EC2" +layout: "aws" +page_title: "AWS: aws_ec2_local_gateway_virtual_interface" +description: |- + Provides details about an EC2 Local Gateway Virtual Interface +--- + +# Data Source: aws_ec2_local_gateway_virtual_interface + +Provides details about an EC2 Local Gateway Virtual Interface. More information can be found in the [Outposts User Guide](https://docs.aws.amazon.com/outposts/latest/userguide/outposts-networking-components.html#routing). + +## Example Usage + +```hcl +data "aws_ec2_local_gateway_virtual_interface" "example" { + for_each = data.aws_ec2_local_gateway_virtual_interface_group.example.local_gateway_virtual_interface_ids + + id = each.value +} +``` + +## Argument Reference + +The following arguments are optional: + +* `filter` - (Optional) One or more configuration blocks containing name-values filters. See the [EC2 API Reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeLocalGatewayVirtualInterfaces.html) for supported filters. Detailed below. +* `id` - (Optional) Identifier of EC2 Local Gateway Virtual Interface. +* `tags` - (Optional) Key-value map of resource tags, each pair of which must exactly match a pair on the desired local gateway route table. + +### filter Argument Reference + +The `filter` configuration block supports the following arguments: + +* `name` - (Required) Name of the filter. +* `values` - (Required) List of one or more values for the filter. + +## Attribute Reference + +In addition to all arguments above, the following attributes are exported: + +* `local_address` - Local address. +* `local_bgp_asn` - Border Gateway Protocol (BGP) Autonomous System Number (ASN) of the EC2 Local Gateway. +* `local_gateway_id` - Identifier of the EC2 Local Gateway. +* `peer_address` - Peer address. +* `peer_bgp_asn` - Border Gateway Protocol (BGP) Autonomous System Number (ASN) of the peer. +* `vlan` - Virtual Local Area Network. diff --git a/website/docs/d/ec2_local_gateway_virtual_interface_group.html.markdown b/website/docs/d/ec2_local_gateway_virtual_interface_group.html.markdown new file mode 100644 index 00000000000..4616ea320de --- /dev/null +++ b/website/docs/d/ec2_local_gateway_virtual_interface_group.html.markdown @@ -0,0 +1,41 @@ +--- +subcategory: "EC2" +layout: "aws" +page_title: "AWS: aws_ec2_local_gateway_virtual_interface_group" +description: |- + Provides details about an EC2 Local Gateway Virtual Interface Group +--- + +# Data Source: aws_ec2_local_gateway_virtual_interface_group + +Provides details about an EC2 Local Gateway Virtual Interface Group. More information can be found in the [Outposts User Guide](https://docs.aws.amazon.com/outposts/latest/userguide/outposts-networking-components.html#routing). + +## Example Usage + +```hcl +data "aws_ec2_local_gateway_virtual_interface_group" "example" { + local_gateway_id = data.aws_ec2_local_gateway.example.id +} +``` + +## Argument Reference + +The following arguments are optional: + +* `filter` - (Optional) One or more configuration blocks containing name-values filters. See the [EC2 API Reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeLocalGatewayVirtualInterfaceGroups.html) for supported filters. Detailed below. +* `id` - (Optional) Identifier of EC2 Local Gateway Virtual Interface Group. +* `local_gateway_id` - (Optional) Identifier of EC2 Local Gateway. +* `tags` - (Optional) Key-value map of resource tags, each pair of which must exactly match a pair on the desired local gateway route table. + +### filter Argument Reference + +The `filter` configuration block supports the following arguments: + +* `name` - (Required) Name of the filter. +* `values` - (Required) List of one or more values for the filter. + +## Attribute Reference + +In addition to all arguments above, the following attributes are exported: + +* `local_gateway_virtual_interface_ids` - Set of EC2 Local Gateway Virtual Interface identifiers. diff --git a/website/docs/d/ec2_local_gateway_virtual_interface_groups.html.markdown b/website/docs/d/ec2_local_gateway_virtual_interface_groups.html.markdown new file mode 100644 index 00000000000..8560bb4f6db --- /dev/null +++ b/website/docs/d/ec2_local_gateway_virtual_interface_groups.html.markdown @@ -0,0 +1,38 @@ +--- +subcategory: "EC2" +layout: "aws" +page_title: "AWS: aws_ec2_local_gateway_virtual_interface_groups" +description: |- + Provides details about multiple EC2 Local Gateway Virtual Interface Groups +--- + +# Data Source: aws_ec2_local_gateway_virtual_interface_groups + +Provides details about multiple EC2 Local Gateway Virtual Interface Groups, such as identifiers. More information can be found in the [Outposts User Guide](https://docs.aws.amazon.com/outposts/latest/userguide/outposts-networking-components.html#routing). + +## Example Usage + +```hcl +data "aws_ec2_local_gateway_virtual_interface_groups" "all" {} +``` + +## Argument Reference + +The following arguments are optional: + +* `filter` - (Optional) One or more configuration blocks containing name-values filters. See the [EC2 API Reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeLocalGatewayVirtualInterfaceGroups.html) for supported filters. Detailed below. +* `tags` - (Optional) Key-value map of resource tags, each pair of which must exactly match a pair on the desired local gateway route table. + +### filter Argument Reference + +The `filter` configuration block supports the following arguments: + +* `name` - (Required) Name of the filter. +* `values` - (Required) List of one or more values for the filter. + +## Attribute Reference + +In addition to all arguments above, the following attributes are exported: + +* `ids` - Set of EC2 Local Gateway Virtual Interface Group identifiers. +* `local_gateway_virtual_interface_ids` - Set of EC2 Local Gateway Virtual Interface identifiers. diff --git a/website/docs/d/ec2_local_gateways.html.markdown b/website/docs/d/ec2_local_gateways.html.markdown index fc739b33681..614691ee00b 100644 --- a/website/docs/d/ec2_local_gateways.html.markdown +++ b/website/docs/d/ec2_local_gateways.html.markdown @@ -22,7 +22,7 @@ data "aws_ec2_local_gateways" "foo" { } output "foo" { - value = "${data.aws_ec2_local_gateways.foo.ids}" + value = data.aws_ec2_local_gateways.foo.ids } ``` diff --git a/website/docs/d/ec2_spot_price.html.markdown b/website/docs/d/ec2_spot_price.html.markdown new file mode 100644 index 00000000000..6958ea0afde --- /dev/null +++ b/website/docs/d/ec2_spot_price.html.markdown @@ -0,0 +1,45 @@ +--- +subcategory: "EC2" +layout: "aws" +page_title: "AWS: aws_ec2_instance_spot_price" +description: |- + Information about most recent Spot Price for a given EC2 instance. +--- + +# Data Source: aws_ec2_instance_spot_price + +Information about most recent Spot Price for a given EC2 instance. + +## Example Usage + +```hcl +data "aws_ec2_instance_spot_price" "example" { + instance_type = "t3.medium" + availability_zone = "us-west-2a" + + filter { + name = "product-description" + values = ["Linux/UNIX"] + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `instance_type` - (Optional) The type of instance for which to query Spot Price information. +* `availability_zone` - (Optional) The availability zone in which to query Spot price information. +* `filter` - (Optional) One or more configuration blocks containing name-values filters. See the [EC2 API Reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSpotPriceHistory.html) for supported filters. Detailed below. + +### filter Argument Reference + +* `name` - (Required) Name of the filter. +* `values` - (Required) List of one or more values for the filter. + +## Attribute Reference + +In addition to all arguments above, the following attributes are exported: + +* `spot_price` - The most recent Spot Price value for the given instance type and AZ. +* `spot_price_timestamp` - The timestamp at which the Spot Price value was published. diff --git a/website/docs/d/ec2_transit_gateway_dx_gateway_attachment.html.markdown b/website/docs/d/ec2_transit_gateway_dx_gateway_attachment.html.markdown index a9838187643..ffa6c6d18b8 100644 --- a/website/docs/d/ec2_transit_gateway_dx_gateway_attachment.html.markdown +++ b/website/docs/d/ec2_transit_gateway_dx_gateway_attachment.html.markdown @@ -16,8 +16,8 @@ Get information on an EC2 Transit Gateway's attachment to a Direct Connect Gatew ```hcl data "aws_ec2_transit_gateway_dx_gateway_attachment" "example" { - transit_gateway_id = "${aws_ec2_transit_gateway.example.id}" - dx_gateway_id = "${aws_dx_gateway.example.id}" + transit_gateway_id = aws_ec2_transit_gateway.example.id + dx_gateway_id = aws_dx_gateway.example.id } ``` diff --git a/website/docs/d/ec2_transit_gateway_vpn_attachment.html.markdown b/website/docs/d/ec2_transit_gateway_vpn_attachment.html.markdown index bcbab94e16c..c545581223b 100644 --- a/website/docs/d/ec2_transit_gateway_vpn_attachment.html.markdown +++ b/website/docs/d/ec2_transit_gateway_vpn_attachment.html.markdown @@ -16,8 +16,8 @@ Get information on an EC2 Transit Gateway VPN Attachment. ```hcl data "aws_ec2_transit_gateway_vpn_attachment" "example" { - transit_gateway_id = "${aws_ec2_transit_gateway.example.id}" - vpn_connection_id = "${aws_vpn_connection.example.id}" + transit_gateway_id = aws_ec2_transit_gateway.example.id + vpn_connection_id = aws_vpn_connection.example.id } ``` diff --git a/website/docs/d/ecr_authorization_token.html.markdown b/website/docs/d/ecr_authorization_token.html.markdown new file mode 100644 index 00000000000..ac919522a9e --- /dev/null +++ b/website/docs/d/ecr_authorization_token.html.markdown @@ -0,0 +1,34 @@ +--- +subcategory: "ECR" +layout: "aws" +page_title: "AWS: aws_ecr_authorization_token" +description: |- + Provides details about an ECR Authorization Token +--- + +# Data Source: aws_ecr_authorization_token + +The ECR Authorization Token data source allows the authorization token, proxy endpoint, token expiration date, user name and password to be retrieved for an ECR repository. + +## Example Usage + +```hcl +data "aws_ecr_authorization_token" "token" { +} +``` + +## Argument Reference + +The following arguments are supported: + +* `registry_id` - (Optional) AWS account ID of the ECR Repository. If not specified the default account is assumed. + +## Attributes Reference + +In addition to the argument above, the following attributes are exported: + +* `authorization_token` - Temporary IAM authentication credentials to access the ECR repository encoded in base64 in the form of `user_name:password`. +* `proxy_endpoint` - The registry URL to use in the docker login command. +* `expires_at` - The time in UTC RFC3339 format when the authorization token expires. +* `user_name` - User name decoded from the authorization token. +* `password` - Password decoded from the authorization token. diff --git a/website/docs/d/ecr_repository.html.markdown b/website/docs/d/ecr_repository.html.markdown index 8f7f97f8b7b..f58000af725 100644 --- a/website/docs/d/ecr_repository.html.markdown +++ b/website/docs/d/ecr_repository.html.markdown @@ -23,12 +23,25 @@ data "aws_ecr_repository" "service" { The following arguments are supported: * `name` - (Required) The name of the ECR Repository. +* `registry_id` - (Optional) The registry ID where the repository was created. ## Attributes Reference In addition to all arguments above, the following attributes are exported: * `arn` - Full ARN of the repository. -* `registry_id` - The registry ID where the repository was created. +* `encryption_configuration` - Encryption configuration for the repository. See [Encryption Configuration](#encryption-configuration) below. +* `image_scanning_configuration` - Configuration block that defines image scanning configuration for the repository. See [Image Scanning Configuration](#image-scanning-configuration) below. +* `image_tag_mutability` - The tag mutability setting for the repository. * `repository_url` - The URL of the repository (in the form `aws_account_id.dkr.ecr.region.amazonaws.com/repositoryName`). * `tags` - A map of tags assigned to the resource. + +### Encryption Configuration + +* `encryption_type` - The encryption type to use for the repository, either `AES256` or `KMS`. +* `kms_key` - If `encryption_type` is `KMS`, the ARN of the KMS key used. + +### Image Scanning Configuration + +* `scan_on_push` - Indicates whether images are scanned after being pushed to the repository. + diff --git a/website/docs/d/ecs_container_definition.html.markdown b/website/docs/d/ecs_container_definition.html.markdown index 6354eda7780..d67ed4cf728 100644 --- a/website/docs/d/ecs_container_definition.html.markdown +++ b/website/docs/d/ecs_container_definition.html.markdown @@ -15,7 +15,7 @@ a specific container within an AWS ECS service. ```hcl data "aws_ecs_container_definition" "ecs-mongo" { - task_definition = "${aws_ecs_task_definition.mongo.id}" + task_definition = aws_ecs_task_definition.mongo.id container_name = "mongodb" } ``` diff --git a/website/docs/d/ecs_service.html.markdown b/website/docs/d/ecs_service.html.markdown index 11e49936de8..65c95a84913 100644 --- a/website/docs/d/ecs_service.html.markdown +++ b/website/docs/d/ecs_service.html.markdown @@ -16,7 +16,7 @@ Service within a AWS ECS Cluster. ```hcl data "aws_ecs_service" "example" { service_name = "example" - cluster_arn = "${data.aws_ecs_cluster.example.arn}" + cluster_arn = data.aws_ecs_cluster.example.arn } ``` diff --git a/website/docs/d/ecs_task_definition.html.markdown b/website/docs/d/ecs_task_definition.html.markdown index 31d1b010be1..8e7a93a48cb 100644 --- a/website/docs/d/ecs_task_definition.html.markdown +++ b/website/docs/d/ecs_task_definition.html.markdown @@ -17,7 +17,7 @@ a specific AWS ECS task definition. ```hcl # Simply specify the family to find the latest ACTIVE revision in that family. data "aws_ecs_task_definition" "mongo" { - task_definition = "${aws_ecs_task_definition.mongo.family}" + task_definition = aws_ecs_task_definition.mongo.family } resource "aws_ecs_cluster" "foo" { @@ -47,11 +47,11 @@ DEFINITION resource "aws_ecs_service" "mongo" { name = "mongo" - cluster = "${aws_ecs_cluster.foo.id}" + cluster = aws_ecs_cluster.foo.id desired_count = 2 # Track the latest ACTIVE revision - task_definition = "${aws_ecs_task_definition.mongo.family}:${max("${aws_ecs_task_definition.mongo.revision}", "${data.aws_ecs_task_definition.mongo.revision}")}" + task_definition = "${aws_ecs_task_definition.mongo.family}:${max(aws_ecs_task_definition.mongo.revision, data.aws_ecs_task_definition.mongo.revision)}" } ``` diff --git a/website/docs/d/efs_access_point.html.markdown b/website/docs/d/efs_access_point.html.markdown new file mode 100644 index 00000000000..ad83ad94d4e --- /dev/null +++ b/website/docs/d/efs_access_point.html.markdown @@ -0,0 +1,45 @@ +--- +subcategory: "EFS" +layout: "aws" +page_title: "AWS: aws_efs_access_point" +description: |- + Provides an Elastic File System (EFS) Access Point data source. +--- + +# Data Source: aws_efs_access_point + +Provides information about an Elastic File System (EFS) Access Point. + +## Example Usage + +```hcl +data "aws_efs_access_point" "test" { + access_point_id = "fsap-12345678" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `access_point_id` - (Required) The ID that identifies the file system. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The ID of the access point. +* `arn` - Amazon Resource Name of the file system. +* `file_system_arn` - Amazon Resource Name of the file system. +* `file_system_id` - The ID of the file system for which the access point is intended. +* `posix_user` - Single element list containing operating system user and group applied to all file system requests made using the access point. + * `gid` - Group ID + * `secondary_gids` - Secondary group IDs + * `uid` - User Id +* `root_directory`- Single element list containing information on the directory on the Amazon EFS file system that the access point provides access to. + * `creation_info` - Single element list containing information on the creation permissions of the directory + * `owner_gid` - POSIX owner group ID + * `owner_uid` - POSIX owner user ID + * `permissions` - POSIX permissions mode + * `path` - Path exposed as the root directory +* `tags` - Key-value mapping of resource tags. diff --git a/website/docs/d/efs_access_points.html.markdown b/website/docs/d/efs_access_points.html.markdown new file mode 100644 index 00000000000..d71e8c1d429 --- /dev/null +++ b/website/docs/d/efs_access_points.html.markdown @@ -0,0 +1,33 @@ +--- +subcategory: "EFS" +layout: "aws" +page_title: "AWS: aws_efs_access_points" +description: |- + Provides information about multiple Elastic File System (EFS) Access Points. +--- + +# Data Source: aws_efs_access_points + +Provides information about multiple Elastic File System (EFS) Access Points. + +## Example Usage + +```hcl +data "aws_efs_access_points" "test" { + file_system_id = "fs-12345678" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `file_system_id` - (Required) EFS File System identifier. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arns` - Set of Amazon Resource Names (ARNs). +* `id` - RFC3339 timestamp when the data source was invoked. +* `ids` - Set of identifiers. diff --git a/website/docs/d/efs_file_system.html.markdown b/website/docs/d/efs_file_system.html.markdown index 75da4112e39..9e8b0c12c57 100644 --- a/website/docs/d/efs_file_system.html.markdown +++ b/website/docs/d/efs_file_system.html.markdown @@ -3,23 +3,23 @@ subcategory: "EFS" layout: "aws" page_title: "AWS: aws_efs_file_system" description: |- - Provides an Elastic File System (EFS) data source. + Provides an Elastic File System (EFS) File System data source. --- # Data Source: aws_efs_file_system -Provides information about an Elastic File System (EFS). +Provides information about an Elastic File System (EFS) File System. ## Example Usage ```hcl variable "file_system_id" { - type = "string" + type = string default = "" } data "aws_efs_file_system" "by_id" { - file_system_id = "${var.file_system_id}" + file_system_id = var.file_system_id } ``` diff --git a/website/docs/d/efs_mount_target.html.markdown b/website/docs/d/efs_mount_target.html.markdown index e3a3e6f28f1..ca42eb248b8 100644 --- a/website/docs/d/efs_mount_target.html.markdown +++ b/website/docs/d/efs_mount_target.html.markdown @@ -14,12 +14,12 @@ Provides information about an Elastic File System Mount Target (EFS). ```hcl variable "mount_target_id" { - type = "string" + type = string default = "" } data "aws_efs_mount_target" "by_id" { - mount_target_id = "${var.mount_target_id}" + mount_target_id = var.mount_target_id } ``` @@ -38,6 +38,9 @@ In addition to all arguments above, the following attributes are exported: * `subnet_id` - ID of the mount target's subnet. * `ip_address` - Address at which the file system may be mounted via the mount target. * `security_groups` - List of VPC security group IDs attached to the mount target. -* `dns_name` - The DNS name for the given subnet/AZ per [documented convention](http://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html). +* `dns_name` - The DNS name for the EFS file system. +* `mount_target_dns_name` - The DNS name for the given subnet/AZ per [documented convention](http://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html). * `network_interface_id` - The ID of the network interface that Amazon EFS created when it created the mount target. - +* `availability_zone_name` - The name of the Availability Zone (AZ) that the mount target resides in. +* `availability_zone_id` - The unique and consistent identifier of the Availability Zone (AZ) that the mount target resides in. +* `owner_id` - AWS account ID that owns the resource. diff --git a/website/docs/d/eks_cluster.html.markdown b/website/docs/d/eks_cluster.html.markdown index 6488f591169..e1fa9ef331b 100644 --- a/website/docs/d/eks_cluster.html.markdown +++ b/website/docs/d/eks_cluster.html.markdown @@ -18,16 +18,16 @@ data "aws_eks_cluster" "example" { } output "endpoint" { - value = "${data.aws_eks_cluster.example.endpoint}" + value = data.aws_eks_cluster.example.endpoint } output "kubeconfig-certificate-authority-data" { - value = "${data.aws_eks_cluster.example.certificate_authority.0.data}" + value = data.aws_eks_cluster.example.certificate_authority[0].data } # Only available on Kubernetes version 1.13 and 1.14 clusters created or upgraded on or after September 3, 2019. output "identity-oidc-issuer" { - value = "${data.aws_eks_cluster.example.identity.0.oidc.0.issuer}" + value = data.aws_eks_cluster.example.identity[0].oidc[0].issuer } ``` @@ -40,23 +40,23 @@ output "identity-oidc-issuer" { * `id` - The name of the cluster * `arn` - The Amazon Resource Name (ARN) of the cluster. * `certificate_authority` - Nested attribute containing `certificate-authority-data` for your cluster. - * `data` - The base64 encoded certificate data required to communicate with your cluster. Add this to the `certificate-authority-data` section of the `kubeconfig` file for your cluster. + * `data` - The base64 encoded certificate data required to communicate with your cluster. Add this to the `certificate-authority-data` section of the `kubeconfig` file for your cluster. * `created_at` - The Unix epoch time stamp in seconds for when the cluster was created. * `enabled_cluster_log_types` - The enabled control plane logs. * `endpoint` - The endpoint for your Kubernetes API server. * `identity` - Nested attribute containing identity provider information for your cluster. Only available on Kubernetes version 1.13 and 1.14 clusters created or upgraded on or after September 3, 2019. For an example using this information to enable IAM Roles for Service Accounts, see the [`aws_eks_cluster` resource documentation](/docs/providers/aws/r/eks_cluster.html). - * `oidc` - Nested attribute containing [OpenID Connect](https://openid.net/connect/) identity provider information for the cluster. - * `issuer` - Issuer URL for the OpenID Connect identity provider. + * `oidc` - Nested attribute containing [OpenID Connect](https://openid.net/connect/) identity provider information for the cluster. + * `issuer` - Issuer URL for the OpenID Connect identity provider. * `platform_version` - The platform version for the cluster. * `role_arn` - The Amazon Resource Name (ARN) of the IAM role that provides permissions for the Kubernetes control plane to make calls to AWS API operations on your behalf. * `status` - The status of the EKS cluster. One of `CREATING`, `ACTIVE`, `DELETING`, `FAILED`. * `tags` - Key-value map of resource tags. * `version` - The Kubernetes server version for the cluster. * `vpc_config` - Nested list containing VPC configuration for the cluster. - * `cluster_security_group_id` - The cluster security group that was created by Amazon EKS for the cluster. - * `endpoint_private_access` - Indicates whether or not the Amazon EKS private API server endpoint is enabled. - * `endpoint_public_access` - Indicates whether or not the Amazon EKS public API server endpoint is enabled. - * `public_access_cidrs` - List of CIDR blocks. Indicates which CIDR blocks can access the Amazon EKS public API server endpoint. - * `security_group_ids` – List of security group IDs - * `subnet_ids` – List of subnet IDs - * `vpc_id` – The VPC associated with your cluster. + * `cluster_security_group_id` - The cluster security group that was created by Amazon EKS for the cluster. + * `endpoint_private_access` - Indicates whether or not the Amazon EKS private API server endpoint is enabled. + * `endpoint_public_access` - Indicates whether or not the Amazon EKS public API server endpoint is enabled. + * `public_access_cidrs` - List of CIDR blocks. Indicates which CIDR blocks can access the Amazon EKS public API server endpoint. + * `security_group_ids` – List of security group IDs + * `subnet_ids` – List of subnet IDs + * `vpc_id` – The VPC associated with your cluster. diff --git a/website/docs/d/eks_cluster_auth.html.markdown b/website/docs/d/eks_cluster_auth.html.markdown index b06dcb95896..4ebce97755f 100644 --- a/website/docs/d/eks_cluster_auth.html.markdown +++ b/website/docs/d/eks_cluster_auth.html.markdown @@ -27,9 +27,9 @@ data "aws_eks_cluster_auth" "example" { } provider "kubernetes" { - host = "${data.aws_eks_cluster.example.endpoint}" - cluster_ca_certificate = "${base64decode(data.aws_eks_cluster.example.certificate_authority.0.data)}" - token = "${data.aws_eks_cluster_auth.example.token}" + host = data.aws_eks_cluster.example.endpoint + cluster_ca_certificate = base64decode(data.aws_eks_cluster.example.certificate_authority[0].data) + token = data.aws_eks_cluster_auth.example.token load_config_file = false } ``` diff --git a/website/docs/d/elastic_beanstalk_application.html.markdown b/website/docs/d/elastic_beanstalk_application.html.markdown index 70025a8dcbf..5006099f8e0 100644 --- a/website/docs/d/elastic_beanstalk_application.html.markdown +++ b/website/docs/d/elastic_beanstalk_application.html.markdown @@ -18,11 +18,11 @@ data "aws_elastic_beanstalk_application" "example" { } output "arn" { - value = "${data.aws_elastic_beanstalk_application.example.arn}" + value = data.aws_elastic_beanstalk_application.example.arn } output "description" { - value = "${data.aws_elastic_beanstalk_application.example.description}" + value = data.aws_elastic_beanstalk_application.example.description } ``` diff --git a/website/docs/d/elasticsearch_domain.html.markdown b/website/docs/d/elasticsearch_domain.html.markdown index cc7145160f3..ee4bc7f46cb 100644 --- a/website/docs/d/elasticsearch_domain.html.markdown +++ b/website/docs/d/elasticsearch_domain.html.markdown @@ -31,49 +31,55 @@ The following attributes are exported: * `access_policies` – The policy document attached to the domain. * `advanced_options` - Key-value string pairs to specify advanced configuration options. +* `advanced_security_options` - Status of the Elasticsearch domain's advanced security options. The block consists of the following attributes: + * `enabled` - Whether advanced security is enabled. + * `internal_user_database_enabled` - Whether the internal user database is enabled. * `arn` – The Amazon Resource Name (ARN) of the domain. * `cluster_config` - Cluster configuration of the domain. - * `instance_type` - Instance type of data nodes in the cluster. - * `instance_count` - Number of instances in the cluster. - * `dedicated_master_enabled` - Indicates whether dedicated master nodes are enabled for the cluster. - * `dedicated_master_type` - Instance type of the dedicated master nodes in the cluster. - * `dedicated_master_count` - Number of dedicated master nodes in the cluster. - * `zone_awareness_enabled` - Indicates whether zone awareness is enabled. - * `zone_awareness_config` - Configuration block containing zone awareness settings. - * `availability_zone_count` - Number of availability zones used. + * `instance_type` - Instance type of data nodes in the cluster. + * `instance_count` - Number of instances in the cluster. + * `dedicated_master_enabled` - Indicates whether dedicated master nodes are enabled for the cluster. + * `dedicated_master_type` - Instance type of the dedicated master nodes in the cluster. + * `dedicated_master_count` - Number of dedicated master nodes in the cluster. + * `zone_awareness_enabled` - Indicates whether zone awareness is enabled. + * `zone_awareness_config` - Configuration block containing zone awareness settings. + * `availability_zone_count` - Number of availability zones used. + * `warm_enabled` - Indicates warm storage is enabled. + * `warm_count` - The number of warm nodes in the cluster. + * `warm_type` - The instance type for the Elasticsearch cluster's warm nodes. * `cognito_options` - Domain Amazon Cognito Authentication options for Kibana. - * `enabled` - Whether Amazon Cognito Authentication is enabled. - * `user_pool_id` - The Cognito User pool used by the domain. - * `identity_pool_id` - The Cognito Identity pool used by the domain. - * `role_arn` - The IAM Role with the AmazonESCognitoAccess policy attached. + * `enabled` - Whether Amazon Cognito Authentication is enabled. + * `user_pool_id` - The Cognito User pool used by the domain. + * `identity_pool_id` - The Cognito Identity pool used by the domain. + * `role_arn` - The IAM Role with the AmazonESCognitoAccess policy attached. * `created` – Status of the creation of the domain. * `deleted` – Status of the deletion of the domain. * `domain_id` – Unique identifier for the domain. * `ebs_options` - EBS Options for the instances in the domain. - * `ebs_enabled` - Whether EBS volumes are attached to data nodes in the domain. - * `volume_type` - The type of EBS volumes attached to data nodes. - * `volume_size` - The size of EBS volumes attached to data nodes (in GB). - * `iops` - The baseline input/output (I/O) performance of EBS volumes + * `ebs_enabled` - Whether EBS volumes are attached to data nodes in the domain. + * `volume_type` - The type of EBS volumes attached to data nodes. + * `volume_size` - The size of EBS volumes attached to data nodes (in GB). + * `iops` - The baseline input/output (I/O) performance of EBS volumes attached to data nodes. * `elasticsearch_version` – ElasticSearch version for the domain. * `encryption_at_rest` - Domain encryption at rest related options. - * `enabled` - Whether encryption at rest is enabled in the domain. - * `kms_key_id` - The KMS key id used to encrypt data at rest. + * `enabled` - Whether encryption at rest is enabled in the domain. + * `kms_key_id` - The KMS key id used to encrypt data at rest. * `endpoint` – Domain-specific endpoint used to submit index, search, and data upload requests. * `kibana_endpoint` - Domain-specific endpoint used to access the Kibana application. * `log_publishing_options` - Domain log publishing related options. - * `log_type` - The type of Elasticsearch log being published. - * `cloudwatch_log_group_arn` - The CloudWatch Log Group where the logs are published. - * `enabled` - Whether log publishing is enabled. + * `log_type` - The type of Elasticsearch log being published. + * `cloudwatch_log_group_arn` - The CloudWatch Log Group where the logs are published. + * `enabled` - Whether log publishing is enabled. * `node_to_node_encryption` - Domain in transit encryption related options. - * `enabled` - Whether node to node encryption is enabled. + * `enabled` - Whether node to node encryption is enabled. * `processing` – Status of a configuration change in the domain. * `snapshot_options` – Domain snapshot related options. - * `automated_snapshot_start_hour` - Hour during which the service takes an automated daily + * `automated_snapshot_start_hour` - Hour during which the service takes an automated daily snapshot of the indices in the domain. * `tags` - The tags assigned to the domain. * `vpc_options` - VPC Options for private Elasticsearch domains. - * `availability_zones` - The availability zones used by the domain. - * `security_group_ids` - The security groups used by the domain. - * `subnet_ids` - The subnets used by the domain. - * `vpc_id` - The VPC used by the domain. + * `availability_zones` - The availability zones used by the domain. + * `security_group_ids` - The security groups used by the domain. + * `subnet_ids` - The subnets used by the domain. + * `vpc_id` - The VPC used by the domain. diff --git a/website/docs/d/elb.html.markdown b/website/docs/d/elb.html.markdown index 8106ca796cf..e68e1db0204 100644 --- a/website/docs/d/elb.html.markdown +++ b/website/docs/d/elb.html.markdown @@ -20,12 +20,12 @@ with it, etc. ```hcl variable "lb_name" { - type = "string" + type = string default = "" } data "aws_elb" "test" { - name = "${var.lb_name}" + name = var.lb_name } ``` diff --git a/website/docs/d/elb_hosted_zone_id.html.markdown b/website/docs/d/elb_hosted_zone_id.html.markdown index c011318789b..51207333a75 100644 --- a/website/docs/d/elb_hosted_zone_id.html.markdown +++ b/website/docs/d/elb_hosted_zone_id.html.markdown @@ -17,13 +17,13 @@ in a given region for the purpose of using in an AWS Route53 Alias. data "aws_elb_hosted_zone_id" "main" {} resource "aws_route53_record" "www" { - zone_id = "${aws_route53_zone.primary.zone_id}" + zone_id = aws_route53_zone.primary.zone_id name = "example.com" type = "A" alias { - name = "${aws_elb.main.dns_name}" - zone_id = "${data.aws_elb_hosted_zone_id.main.id}" + name = aws_elb.main.dns_name + zone_id = data.aws_elb_hosted_zone_id.main.id evaluate_target_health = true } } diff --git a/website/docs/d/elb_service_account.html.markdown b/website/docs/d/elb_service_account.html.markdown index b4c0c2d2f3d..b1c1f87443f 100644 --- a/website/docs/d/elb_service_account.html.markdown +++ b/website/docs/d/elb_service_account.html.markdown @@ -9,7 +9,7 @@ description: |- # Data Source: aws_elb_service_account Use this data source to get the Account ID of the [AWS Elastic Load Balancing Service Account](http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-access-logs.html#attach-bucket-policy) -in a given region for the purpose of whitelisting in S3 bucket policy. +in a given region for the purpose of permitting in S3 bucket policy. ## Example Usage @@ -47,7 +47,7 @@ resource "aws_elb" "bar" { availability_zones = ["us-west-2a"] access_logs { - bucket = "${aws_s3_bucket.elb_logs.bucket}" + bucket = aws_s3_bucket.elb_logs.bucket interval = 5 } diff --git a/website/docs/d/glue_script.html.markdown b/website/docs/d/glue_script.html.markdown index 8b9928d2582..90514f25153 100644 --- a/website/docs/d/glue_script.html.markdown +++ b/website/docs/d/glue_script.html.markdown @@ -110,7 +110,7 @@ data "aws_glue_script" "example" { } output "python_script" { - value = "${data.aws_glue_script.example.python_script}" + value = data.aws_glue_script.example.python_script } ``` @@ -212,7 +212,7 @@ data "aws_glue_script" "example" { } output "scala_code" { - value = "${data.aws_glue_script.example.scala_code}" + value = data.aws_glue_script.example.scala_code } ``` diff --git a/website/docs/d/iam_account_alias.html.markdown b/website/docs/d/iam_account_alias.html.markdown index 7136a145168..9cf6e983431 100644 --- a/website/docs/d/iam_account_alias.html.markdown +++ b/website/docs/d/iam_account_alias.html.markdown @@ -18,7 +18,7 @@ for the effective account in which Terraform is working. data "aws_iam_account_alias" "current" {} output "account_id" { - value = "${data.aws_iam_account_alias.current.account_alias}" + value = data.aws_iam_account_alias.current.account_alias } ``` diff --git a/website/docs/d/iam_policy_document.html.markdown b/website/docs/d/iam_policy_document.html.markdown index d8be0d66c6c..c8f69e62a6a 100644 --- a/website/docs/d/iam_policy_document.html.markdown +++ b/website/docs/d/iam_policy_document.html.markdown @@ -67,7 +67,7 @@ data "aws_iam_policy_document" "example" { resource "aws_iam_policy" "example" { name = "example_policy" path = "/" - policy = "${data.aws_iam_policy_document.example.json}" + policy = data.aws_iam_policy_document.example.json } ``` @@ -109,8 +109,8 @@ each accept the following arguments: does *not* apply to. Used to apply a policy statement to all resources *except* those listed. * `principals` (Optional) - A nested configuration block (described below) - specifying a resource (or resource pattern) to which this statement applies. -* `not_principals` (Optional) - Like `principals` except gives resources that + specifying a principal (or principal pattern) to which this statement applies. +* `not_principals` (Optional) - Like `principals` except gives principals that the statement does *not* apply to. * `condition` (Optional) - A nested configuration block (described below) that defines a further, possibly-service-specific condition that constrains @@ -119,9 +119,11 @@ each accept the following arguments: Each policy may have either zero or more `principals` blocks or zero or more `not_principals` blocks, both of which each accept the following arguments: -* `type` (Required) The type of principal. For AWS ARNs this is "AWS". For AWS services (e.g. Lambda), this is "Service". +* `type` (Required) The type of principal. For AWS ARNs this is "AWS". For AWS services (e.g. Lambda), this is "Service". For Federated access the type is "Federated". * `identifiers` (Required) List of identifiers for principals. When `type` - is "AWS", these are IAM user or role ARNs. When `type` is "Service", these are AWS Service roles e.g. `lambda.amazonaws.com`. + is "AWS", these are IAM user or role ARNs. When `type` is "Service", these are AWS Service roles e.g. `lambda.amazonaws.com`. When `type` is "Federated", these are web identity users or SAML provider ARNs. + +For further examples or information about AWS principals then please refer to the [documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html). Each policy statement may have zero or more `condition` blocks, which each accept the following arguments: @@ -182,7 +184,12 @@ data "aws_iam_policy_document" "event_stream_bucket_role_assume_role_policy" { principals { type = "AWS" - identifiers = ["${var.trusted_role_arn}"] + identifiers = [var.trusted_role_arn] + } + + principals { + type = "Federated" + identifiers = ["arn:aws:iam::${var.account_id}:saml-provider/${var.provider_name}", "cognito-identity.amazonaws.com"] } } } @@ -208,7 +215,7 @@ data "aws_iam_policy_document" "source" { } data "aws_iam_policy_document" "source_json_example" { - source_json = "${data.aws_iam_policy_document.source.json}" + source_json = data.aws_iam_policy_document.source.json statement { sid = "SidToOverwrite" @@ -232,7 +239,7 @@ data "aws_iam_policy_document" "override" { } data "aws_iam_policy_document" "override_json_example" { - override_json = "${data.aws_iam_policy_document.override.json}" + override_json = data.aws_iam_policy_document.override.json statement { actions = ["ec2:*"] @@ -323,8 +330,8 @@ data "aws_iam_policy_document" "override" { } data "aws_iam_policy_document" "politik" { - source_json = "${data.aws_iam_policy_document.source.json}" - override_json = "${data.aws_iam_policy_document.override.json}" + source_json = data.aws_iam_policy_document.source.json + override_json = data.aws_iam_policy_document.override.json } ``` diff --git a/website/docs/d/iam_server_certificate.html.markdown b/website/docs/d/iam_server_certificate.html.markdown index 7489394f9c4..a72132ba18f 100644 --- a/website/docs/d/iam_server_certificate.html.markdown +++ b/website/docs/d/iam_server_certificate.html.markdown @@ -26,7 +26,7 @@ resource "aws_elb" "elb" { instance_protocol = "https" lb_port = 443 lb_protocol = "https" - ssl_certificate_id = "${data.aws_iam_server_certificate.my-domain.arn}" + ssl_certificate_id = data.aws_iam_server_certificate.my-domain.arn } } ``` diff --git a/website/docs/d/inspector_rules_packages.html.markdown b/website/docs/d/inspector_rules_packages.html.markdown index b785148b64d..ca257d61710 100644 --- a/website/docs/d/inspector_rules_packages.html.markdown +++ b/website/docs/d/inspector_rules_packages.html.markdown @@ -27,15 +27,15 @@ resource "aws_inspector_resource_group" "group" { resource "aws_inspector_assessment_target" "assessment" { name = "test" - resource_group_arn = "${aws_inspector_resource_group.group.arn}" + resource_group_arn = aws_inspector_resource_group.group.arn } resource "aws_inspector_assessment_template" "assessment" { name = "Test" - target_arn = "${aws_inspector_assessment_target.assessment.arn}" + target_arn = aws_inspector_assessment_target.assessment.arn duration = "60" - rules_package_arns = ["${data.aws_inspector_rules_packages.rules.arns}"] + rules_package_arns = data.aws_inspector_rules_packages.rules.arns } ``` diff --git a/website/docs/d/instance.html.markdown b/website/docs/d/instance.html.markdown index 567d6feef3c..83dcb7f3880 100644 --- a/website/docs/d/instance.html.markdown +++ b/website/docs/d/instance.html.markdown @@ -63,19 +63,19 @@ interpolation. * `associate_public_ip_address` - Whether or not the Instance is associated with a public IP address or not (Boolean). * `availability_zone` - The availability zone of the Instance. * `ebs_block_device` - The EBS block device mappings of the Instance. - * `delete_on_termination` - If the EBS volume will be deleted on termination. - * `device_name` - The physical name of the device. - * `encrypted` - If the EBS volume is encrypted. - * `iops` - `0` If the EBS volume is not a provisioned IOPS image, otherwise the supported IOPS count. - * `kms_key_arn` - Amazon Resource Name (ARN) of KMS Key, if EBS volume is encrypted. - * `snapshot_id` - The ID of the snapshot. - * `volume_size` - The size of the volume, in GiB. - * `volume_type` - The volume type. + * `delete_on_termination` - If the EBS volume will be deleted on termination. + * `device_name` - The physical name of the device. + * `encrypted` - If the EBS volume is encrypted. + * `iops` - `0` If the EBS volume is not a provisioned IOPS image, otherwise the supported IOPS count. + * `kms_key_arn` - Amazon Resource Name (ARN) of KMS Key, if EBS volume is encrypted. + * `snapshot_id` - The ID of the snapshot. + * `volume_size` - The size of the volume, in GiB. + * `volume_type` - The volume type. * `ebs_optimized` - Whether the Instance is EBS optimized or not (Boolean). * `ephemeral_block_device` - The ephemeral block device mappings of the Instance. - * `device_name` - The physical name of the device. - * `no_device` - Whether the specified device included in the device mapping was suppressed or not (Boolean). - * `virtual_name` - The virtual device name. + * `device_name` - The physical name of the device. + * `no_device` - Whether the specified device included in the device mapping was suppressed or not (Boolean). + * `virtual_name` - The virtual device name. * `iam_instance_profile` - The name of the instance profile associated with the Instance. * `ipv6_addresses` - The IPv6 addresses associated to the Instance, if applicable. **NOTE**: Unlike the IPv4 address, this doesn't change if you attach an EIP to the instance. * `instance_state` - The state of the instance. One of: `pending`, `running`, `shutting-down`, `terminated`, `stopping`, `stopped`. See [Instance Lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) for more information. @@ -92,17 +92,18 @@ interpolation. used inside the Amazon EC2, and only available if you've enabled DNS hostnames for your VPC. * `private_ip` - The private IP address assigned to the Instance. +* `secondary_private_ips` - The secondary private IPv4 addresses assigned to the instance's primary network interface (eth0) in a VPC. * `public_dns` - The public DNS name assigned to the Instance. For EC2-VPC, this is only available if you've enabled DNS hostnames for your VPC. * `public_ip` - The public IP address assigned to the Instance, if applicable. **NOTE**: If you are using an [`aws_eip`](/docs/providers/aws/r/eip.html) with your instance, you should refer to the EIP's address directly and not use `public_ip`, as this field will change after the EIP is attached. * `root_block_device` - The root block device mappings of the Instance - * `device_name` - The physical name of the device. - * `delete_on_termination` - If the root block device will be deleted on termination. - * `encrypted` - If the EBS volume is encrypted. - * `iops` - `0` If the volume is not a provisioned IOPS image, otherwise the supported IOPS count. - * `kms_key_arn` - Amazon Resource Name (ARN) of KMS Key, if EBS volume is encrypted. - * `volume_size` - The size of the volume, in GiB. - * `volume_type` - The type of the volume. + * `device_name` - The physical name of the device. + * `delete_on_termination` - If the root block device will be deleted on termination. + * `encrypted` - If the EBS volume is encrypted. + * `iops` - `0` If the volume is not a provisioned IOPS image, otherwise the supported IOPS count. + * `kms_key_arn` - Amazon Resource Name (ARN) of KMS Key, if EBS volume is encrypted. + * `volume_size` - The size of the volume, in GiB. + * `volume_type` - The type of the volume. * `security_groups` - The associated security groups. * `source_dest_check` - Whether the network interface performs source/destination checking (Boolean). * `subnet_id` - The VPC subnet ID. @@ -115,8 +116,8 @@ interpolation. * `vpc_security_group_ids` - The associated security groups in a non-default VPC. * `credit_specification` - The credit specification of the Instance. * `metadata_options` - The metadata options of the Instance. - * `http_endpoint` - The state of the metadata service: `enabled`, `disabled`. - * `http_tokens` - If session tokens are required: `optional`, `required`. - * `http_put_response_hop_limit` - The desired HTTP PUT response hop limit for instance metadata requests. + * `http_endpoint` - The state of the metadata service: `enabled`, `disabled`. + * `http_tokens` - If session tokens are required: `optional`, `required`. + * `http_put_response_hop_limit` - The desired HTTP PUT response hop limit for instance metadata requests. [1]: http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html diff --git a/website/docs/d/instances.html.markdown b/website/docs/d/instances.html.markdown index d32b3d4848c..773550f37f3 100644 --- a/website/docs/d/instances.html.markdown +++ b/website/docs/d/instances.html.markdown @@ -38,8 +38,8 @@ data "aws_instances" "test" { } resource "aws_eip" "test" { - count = "${length(data.aws_instances.test.ids)}" - instance = "${data.aws_instances.test.ids[count.index]}" + count = length(data.aws_instances.test.ids) + instance = data.aws_instances.test.ids[count.index] } ``` diff --git a/website/docs/d/internet_gateway.html.markdown b/website/docs/d/internet_gateway.html.markdown index d98f39f0099..002bef064b2 100644 --- a/website/docs/d/internet_gateway.html.markdown +++ b/website/docs/d/internet_gateway.html.markdown @@ -18,7 +18,7 @@ variable "vpc_id" {} data "aws_internet_gateway" "default" { filter { name = "attachment.vpc-id" - values = ["${var.vpc_id}"] + values = [var.vpc_id] } } ``` @@ -47,6 +47,8 @@ which take the following arguments: ## Attributes Reference +* `arn` - The ARN of the Internet Gateway. + All of the argument attributes except `filter` block are also exported as result attributes. This data source will complete the data by populating any fields that are not included in the configuration with the data for diff --git a/website/docs/d/iot_endpoint.html.markdown b/website/docs/d/iot_endpoint.html.markdown index cd9d1974378..ac93ae1d09a 100644 --- a/website/docs/d/iot_endpoint.html.markdown +++ b/website/docs/d/iot_endpoint.html.markdown @@ -25,12 +25,10 @@ resource "kubernetes_pod" "agent" { image = "gcr.io/my-project/image-name" name = "image-name" - env = [ - { - name = "IOT_ENDPOINT" - value = "${data.aws_iot_endpoint.example.endpoint_address}" - }, - ] + env { + name = "IOT_ENDPOINT" + value = data.aws_iot_endpoint.example.endpoint_address + } } } } @@ -43,8 +41,8 @@ resource "kubernetes_pod" "agent" { ## Attributes Reference * `endpoint_address` - The endpoint based on `endpoint_type`: - * No `endpoint_type`: Either `iot:Data` or `iot:Data-ATS` [depending on region](https://aws.amazon.com/blogs/iot/aws-iot-core-ats-endpoints/) - * `iot:CredentialsProvider`: `IDENTIFIER.credentials.iot.REGION.amazonaws.com` - * `iot:Data`: `IDENTIFIER.iot.REGION.amazonaws.com` - * `iot:Data-ATS`: `IDENTIFIER-ats.iot.REGION.amazonaws.com` - * `iot:Job`: `IDENTIFIER.jobs.iot.REGION.amazonaws.com` + * No `endpoint_type`: Either `iot:Data` or `iot:Data-ATS` [depending on region](https://aws.amazon.com/blogs/iot/aws-iot-core-ats-endpoints/) + * `iot:CredentialsProvider`: `IDENTIFIER.credentials.iot.REGION.amazonaws.com` + * `iot:Data`: `IDENTIFIER.iot.REGION.amazonaws.com` + * `iot:Data-ATS`: `IDENTIFIER-ats.iot.REGION.amazonaws.com` + * `iot:Job`: `IDENTIFIER.jobs.iot.REGION.amazonaws.com` diff --git a/website/docs/d/ip_ranges.html.markdown b/website/docs/d/ip_ranges.html.markdown index afce18c7a8b..3b119e08aa7 100644 --- a/website/docs/d/ip_ranges.html.markdown +++ b/website/docs/d/ip_ranges.html.markdown @@ -30,8 +30,8 @@ resource "aws_security_group" "from_europe" { } tags = { - CreateDate = "${data.aws_ip_ranges.european_ec2.create_date}" - SyncToken = "${data.aws_ip_ranges.european_ec2.sync_token}" + CreateDate = data.aws_ip_ranges.european_ec2.create_date + SyncToken = data.aws_ip_ranges.european_ec2.sync_token } } ``` diff --git a/website/docs/d/kms_ciphertext.html.markdown b/website/docs/d/kms_ciphertext.html.markdown index 1ead939e641..be9de4a2641 100644 --- a/website/docs/d/kms_ciphertext.html.markdown +++ b/website/docs/d/kms_ciphertext.html.markdown @@ -25,7 +25,7 @@ resource "aws_kms_key" "oauth_config" { } data "aws_kms_ciphertext" "oauth" { - key_id = "${aws_kms_key.oauth_config.key_id}" + key_id = aws_kms_key.oauth_config.key_id plaintext = < If you have a newline character at the end of your file, it will be decrypted with this newline character intact. For most use cases this is undesirable and leads to incorrect passwords or invalid values, as well as possible changes in the plan. Be sure to use `echo -n` if necessary. @@ -47,8 +47,8 @@ data "aws_kms_secrets" "example" { resource "aws_rds_cluster" "example" { # ... other configuration ... - master_password = "${data.aws_kms_secrets.example.plaintext["master_password"]}" - master_username = "${data.aws_kms_secrets.example.plaintext["master_username"]}" + master_password = data.aws_kms_secrets.example.plaintext["master_password"] + master_username = data.aws_kms_secrets.example.plaintext["master_username"] } ``` diff --git a/website/docs/d/lambda_function.html.markdown b/website/docs/d/lambda_function.html.markdown index 8042c36c612..12cea056e4f 100644 --- a/website/docs/d/lambda_function.html.markdown +++ b/website/docs/d/lambda_function.html.markdown @@ -14,11 +14,11 @@ Provides information about a Lambda Function. ```hcl variable "function_name" { - type = "string" + type = string } data "aws_lambda_function" "existing" { - function_name = "${var.function_name}" + function_name = var.function_name } ``` @@ -37,6 +37,7 @@ In addition to all arguments above, the following attributes are exported: * `dead_letter_config` - Configure the function's *dead letter queue*. * `description` - Description of what your Lambda Function does. * `environment` - The Lambda environment's configuration settings. +* `file_system_config` - The connection settings for an Amazon EFS file system. * `handler` - The function entrypoint in your code. * `invoke_arn` - The ARN to be used for invoking Lambda Function from API Gateway. * `kms_key_arn` - The ARN for the KMS encryption key. diff --git a/website/docs/d/lambda_invocation.html.markdown b/website/docs/d/lambda_invocation.html.markdown index 7e6eccdd656..5d1c713a64a 100644 --- a/website/docs/d/lambda_invocation.html.markdown +++ b/website/docs/d/lambda_invocation.html.markdown @@ -16,7 +16,7 @@ invocation type. ```hcl data "aws_lambda_invocation" "example" { - function_name = "${aws_lambda_function.lambda_function_test.function_name}" + function_name = aws_lambda_function.lambda_function_test.function_name input = <cloudwatch
  • cloudwatchevents
  • cloudwatchlogs
  • +
  • codeartifact
  • codebuild
  • codecommit
  • codedeploy
  • @@ -127,7 +128,6 @@ The Terraform AWS Provider allows the following endpoints to be customized:
  • iotanalytics
  • iotevents
  • kafka
  • -
  • kinesis_analytics (DEPRECATED Use kinesisanalytics instead)
  • kinesis
  • kinesisanalytics
  • kinesisanalyticsv2
  • @@ -149,18 +149,20 @@ The Terraform AWS Provider allows the following endpoints to be customized:
  • mediastoredata
  • mq
  • neptune
  • +
  • networkmanager
  • opsworks
  • organizations
  • +
  • outposts
  • personalize
  • pinpoint
  • pricing
  • qldb
  • quicksight
  • -
  • r53
  • (DEPRECATED Use route53 instead)
  • ram
  • rds
  • redshift
  • resourcegroups
  • +
  • resourcegroupstaggingapi
  • route53
  • route53domains
  • route53resolver
  • @@ -183,6 +185,7 @@ The Terraform AWS Provider allows the following endpoints to be customized:
  • storagegateway
  • sts
  • swf
  • +
  • synthetics
  • transfer
  • waf
  • wafregional
  • diff --git a/website/docs/guides/resource-tagging.html.md b/website/docs/guides/resource-tagging.html.md new file mode 100644 index 00000000000..06b14d5e82e --- /dev/null +++ b/website/docs/guides/resource-tagging.html.md @@ -0,0 +1,173 @@ +--- +subcategory: "" +layout: "aws" +page_title: "Terraform AWS Provider Resource Tagging" +description: |- + Managing resource tags with the Terraform AWS Provider. +--- + +# Resource Tagging + +Many AWS services implement [resource tags](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) as an essential part of managing components. These arbitrary key-value pairs can be utilized for billing, ownership, automation, [access control](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html), and many other use cases. Given that these tags are an important aspect of successfully managing an AWS environment, the Terraform AWS Provider implements additional functionality beyond the typical one-to-one resource lifecycle management for easier and more customized implementations. + +-> Not all AWS resources support tagging, which can differ across AWS services and even across resources within the same service. Browse the individual Terraform AWS Provider resource documentation pages for the `tags` argument, to see which support resource tagging. If the AWS API implements tagging support for a resource and it is missing from the Terraform AWS Provider resource, a [feature request](https://github.com/terraform-providers/terraform-provider-aws/issues/new?labels=enhancement&template=Feature_Request.md) can be submitted. + + + +- [Getting Started with Resource Tags](#getting-started-with-resource-tags) +- [Ignoring Changes to Specific Tags](#ignoring-changes-to-specific-tags) + - [Ignoring Changes in Individual Resources](#ignoring-changes-in-individual-resources) + - [Ignoring Changes in All Resources](#ignoring-changes-in-all-resources) +- [Managing Individual Resource Tags](#managing-individual-resource-tags) + + + +## Getting Started with Resource Tags + +Terraform AWS Provider resources that support resource tags implement a consistent argument named `tags` which accepts a key-value map, e.g. + +```hcl +resource "aws_vpc" "example" { + # ... other configuration ... + + tags = { + Name = "MyVPC" + } +} +``` + +The tags for the resource are wholly managed by Terraform except tag keys beginning with `aws:` as these are managed by AWS services and cannot typically be edited or deleted. Any non-AWS tags added to the VPC outside of Terraform will be proposed for removal on the next Terraform execution. Missing tags or those with incorrect values from the Terraform configuration will be proposed for addition or update on the next Terraform execution. Advanced patterns that can adjust these behaviors for special use cases, such as Terraform AWS Provider configurations that affect all resources and the ability to manage resource tags for resources not managed by Terraform, can be found later in this guide. + +For most environments and use cases, this is the typical implementation pattern, whether it be in a standalone Terraform configuration or within a [Terraform Module](/docs/modules/). The Terraform configuration language also enables less repetitive configurations via [variables](/docs/configuration/variables.html), [locals](/docs/configuration/locals.html), or potentially a combination of these, e.g. + +```hcl +# Terraform 0.12 and later syntax +variable "additional_tags" { + default = {} + description = "Additional resource tags" + type = map(string) +} + +resource "aws_vpc" "example" { + # ... other configuration ... + + # This configuration combines some "default" tags with optionally provided additional tags + tags = merge( + var.additional_tags, + { + Name = "MyVPC" + }, + ) +} +``` + +## Ignoring Changes to Specific Tags + +Systems outside of Terraform may automatically interact with the tagging associated with AWS resources. These external systems may be for administrative purposes, such as a Configuration Management Database, or the tagging may be required functionality for those systems, such as Kubernetes. This section shows methods to prevent Terraform from showing differences for specific tags. + +### Ignoring Changes in Individual Resources + +All Terraform resources support the [`lifecycle` configuration block `ignore_changes` argument](/docs/configuration/resources.html#ignore_changes), which can be used to explicitly ignore all tags changes on a resource beyond an initial configuration or individual tag values. + +In this example, the `Name` tag will be added to the VPC on resource creation, however any external changes to the `Name` tag value or the addition/removal of any tag (including the `Name` tag) will be ignored: + +```hcl +# Terraform 0.12 and later syntax +resource "aws_vpc" "example" { + # ... other configuration ... + + tags = { + Name = "MyVPC" + } + + lifecycle { + ignore_changes = [tags] + } +} +``` + +In this example, the `Name` and `Owner` tags will be added to the VPC on resource creation, however any external changes to the value of the `Name` tag will be ignored while any changes to other tags (including the `Owner` tag and any additions) will still be proposed: + +```hcl +# Terraform 0.12 and later syntax +resource "aws_vpc" "example" { + # ... other configuration ... + + tags = { + Name = "MyVPC" + Owner = "Operations" + } + + lifecycle { + ignore_changes = [tags.Name] + } +} +``` + +### Ignoring Changes in All Resources + +As of version 2.60.0 of the Terraform AWS Provider, there is support for ignoring tag changes across all resources under a provider. This simplifies situations where certain tags may be externally applied more globally and enhances functionality beyond `ignore_changes` to support cases such as tag key prefixes. + +In this example, all resources will ignore any addition of the `LastScanned` tag: + +```hcl +provider "aws" { + # ... potentially other configuration ... + + ignore_tags { + keys = ["LastScanned"] + } +} +``` + +In this example, all resources will ignore any addition of tags with the `kubernetes.io/` prefix, such as `kubernetes.io/cluster/name` or `kubernetes.io/role/elb`: + +```hcl +provider "aws" { + # ... potentially other configuration ... + + ignore_tags { + key_prefixes = ["kubernetes.io/"] + } +} +``` + +Any of the `ignore_tags` configurations can be combined as needed. + +The provider ignore tags configuration applies to all Terraform AWS Provider resources under that particular instance (the `default` provider instance in the above cases). If multiple, different Terraform AWS Provider configurations are being used (e.g. [multiple provider instances](https://www.terraform.io/docs/configuration/providers.html#alias-multiple-provider-instances)), the ignore tags configuration must be added to all applicable provider configurations. + +## Managing Individual Resource Tags + +Certain Terraform AWS Provider services support a special resource for managing an individual tag on a resource without managing the resource itself. One example is the [`aws_ec2_tag` resource](/docs/providers/aws/r/ec2_tag.html). These resources enable tagging where resources are created outside Terraform such as EC2 Images (AMIs), shared across accounts via Resource Access Manager (RAM), or implicitly created by other means such as EC2 VPN Connections implicitly creating a taggable EC2 Transit Gateway VPN Attachment. + +~> **NOTE:** This is an advanced use case and can cause conflicting management issues when improperly implemented. These individual tag resources should not be combined with the Terraform resource for managing the parent resource. For example, using `aws_vpc` and `aws_ec2_tag` to manage tags of the same VPC will cause a perpetual difference where the `aws_vpc` resource will try to remove the tag being added by the `aws_ec2_tag` resource. + +-> Not all services supported by the Terraform AWS Provider implement these resources. Browse the Terraform AWS Provider resource documentation pages for a resource with a type ending in `_tag`. If there is a use case where this type of resource is missing, a [feature request](https://github.com/terraform-providers/terraform-provider-aws/issues/new?labels=enhancement&template=Feature_Request.md) can be submitted. + +```hcl +# Terraform 0.12 and later syntax +# ... other configuration ... + +resource "aws_ec2_tag" "example" { + resource_id = aws_vpn_connection.example.transit_gateway_attachment_id + key = "Owner" + value = "Operations" +} +``` + +To manage multiple tags for a resource in this scenario, [`for_each`](/docs/configuration/resources.html#for_each-multiple-resource-instances-defined-by-a-map-or-set-of-strings) can be used: + +```hcl +# Terraform 0.12 and later syntax +# ... other configuration ... + +resource "aws_ec2_tag" "example" { + for_each = { "Name" : "MyAttachment", "Owner" : "Operations" } + + resource_id = aws_vpn_connection.example.transit_gateway_attachment_id + key = each.key + value = each.value +} +``` + +The inline map provided to `for_each` in the example above is used for brevity, but other Terraform configuration language features similar to those noted at the beginning of this guide can be used to make the example more extensible. diff --git a/website/docs/guides/version-2-upgrade.html.md b/website/docs/guides/version-2-upgrade.html.md index 79a3d8f5d4c..b6be65d224d 100644 --- a/website/docs/guides/version-2-upgrade.html.md +++ b/website/docs/guides/version-2-upgrade.html.md @@ -244,7 +244,7 @@ resource "aws_api_gateway_api_key" "example" { } resource "aws_api_gateway_usage_plan" "example" { - name = "example" + name = "example" api_stages { api_id = "${aws_api_gateway_rest_api.example.id}" @@ -352,7 +352,7 @@ resource "aws_api_gateway_method" "example" { request_parameters = { "method.request.header.Content-Type" = false - "method.request.querystring.page" = true + "method.request.querystring.page" = true } } ``` @@ -735,9 +735,9 @@ resource "aws_redshift_cluster" "example" { # ... other configuration ... logging { - bucket_name = "example" - enable = true - s3_key_prefix = "example" + bucket_name = "example" + enable = true + s3_key_prefix = "example" } } ``` diff --git a/website/docs/guides/version-3-upgrade.html.md b/website/docs/guides/version-3-upgrade.html.md index bb91f659028..10952be22b6 100644 --- a/website/docs/guides/version-3-upgrade.html.md +++ b/website/docs/guides/version-3-upgrade.html.md @@ -8,49 +8,886 @@ description: |- # Terraform AWS Provider Version 3 Upgrade Guide -~> **NOTE:** This upgrade guide is a work in progress and will not be completed until the release of version 3.0.0 of the provider in the coming months. Many of the topics discussed, except for the actual provider upgrade, can be performed using the most recent 2.X version of the provider. +Version 3.0.0 of the AWS provider for Terraform is a major release and includes some changes that you will need to consider when upgrading. This guide is intended to help with that process and focuses only on changes from version 2.X to version 3.0.0. See the [Version 2 Upgrade Guide](/docs/providers/aws/guides/version-2-upgrade.html) for information about upgrading from 1.X to version 2.0.0. -Version 3.0.0 of the AWS provider for Terraform is a major release and includes some changes that you will need to consider when upgrading. This guide is intended to help with that process and focuses only on changes from version 1.X to version 3.0.0. +Most of the changes outlined in this guide have been previously marked as deprecated in the Terraform plan/apply output throughout previous provider releases. These changes, such as deprecation notices, can always be found in the [Terraform AWS Provider CHANGELOG](https://github.com/terraform-providers/terraform-provider-aws/blob/master/CHANGELOG.md). + +~> **NOTE:** Version 3.0.0 and later of the AWS Provider can only be automatically installed on Terraform 0.12 and later. + +Upgrade topics: + + + +- [Provider Version Configuration](#provider-version-configuration) +- [Provider Authentication Updates](#provider-authentication-updates) +- [Provider Custom Service Endpoint Updates](#provider-custom-service-endpoint-updates) +- [Data Source: aws_availability_zones](#data-source-aws_availability_zones) +- [Data Source: aws_lambda_invocation](#data-source-aws_lambda_invocation) +- [Data Source: aws_route53_resolver_rule](#data-source-aws_route53_resolver_rule) +- [Data Source: aws_route53_zone](#data-source-aws_route53_zone) +- [Resource: aws_acm_certificate](#resource-aws_acm_certificate) +- [Resource: aws_api_gateway_method_settings](#resource-aws_api_gateway_method_settings) +- [Resource: aws_autoscaling_group](#resource-aws_autoscaling_group) +- [Resource: aws_cloudfront_distribution](#resource-aws_cloudfront_distribution) +- [Resource: aws_cloudwatch_log_group](#resource-aws_cloudwatch_log_group) +- [Resource: aws_codepipeline](#resource-aws_codepipeline) +- [Resource: aws_cognito_user_pool](#resource-aws_cognito_user_pool) +- [Resource: aws_dx_gateway](#resource-aws_dx_gateway) +- [Resource: aws_dx_gateway_association](#resource-aws_dx_gateway_association) +- [Resource: aws_dx_gateway_association_proposal](#resource-aws_dx_gateway_association_proposal) +- [Resource: aws_ebs_volume](#resource-aws_ebs_volume) +- [Resource: aws_elastic_transcoder_preset](#resource-aws_elastic_transcoder_preset) +- [Resource: aws_emr_cluster](#resource-aws_emr_cluster) +- [Resource: aws_glue_job](#resource-aws_glue_job) +- [Resource: aws_iam_access_key](#resource-aws_iam_access_key) +- [Resource: aws_iam_instance_profile](#resource-aws_iam_instance_profile) +- [Resource: aws_iam_server_certificate](#resource-aws_iam_server_certificate) +- [Resource: aws_instance](#resource-aws_instance) +- [Resource: aws_lambda_alias](#resource-aws_lambda_alias) +- [Resource: aws_launch_template](#resource-aws_launch_template) +- [Resource: aws_lb_listener_rule](#resource-aws_lb_listener_rule) +- [Resource: aws_msk_cluster](#resource-aws_msk_cluster) +- [Resource: aws_rds_cluster](#resource-aws_rds_cluster) +- [Resource: aws_route53_resolver_rule](#resource-aws_route53_resolver_rule) +- [Resource: aws_route53_zone](#resource-aws_route53_zone) +- [Resource: aws_s3_bucket](#resource-aws_s3_bucket) +- [Resource: aws_s3_bucket_metric](#resource-aws_s3_bucket_metric) +- [Resource: aws_security_group](#resource-aws_security_group) +- [Resource: aws_sns_platform_application](#resource-aws_sns_platform_application) +- [Resource: aws_spot_fleet_request](#resource-aws_spot_fleet_request) + + + +## Provider Version Configuration + +-> Before upgrading to version 3.0.0, it is recommended to upgrade to the most recent 2.X version of the provider and ensure that your environment successfully runs [`terraform plan`](https://www.terraform.io/docs/commands/plan.html) without unexpected changes or deprecation notices. + +It is recommended to use [version constraints when configuring Terraform providers](https://www.terraform.io/docs/configuration/providers.html#provider-versions). If you are following that recommendation, update the version constraints in your Terraform configuration and run [`terraform init`](https://www.terraform.io/docs/commands/init.html) to download the new version. + +For example, given this previous configuration: + +```hcl +provider "aws" { + # ... other configuration ... + + version = "~> 2.70" +} +``` + +Update to latest 3.X version: + +```hcl +provider "aws" { + # ... other configuration ... + + version = "~> 3.0" +} +``` + +## Provider Authentication Updates + +### Authentication Ordering + +Previously, the provider preferred credentials in the following order: + +- Static credentials (those defined in the Terraform configuration) +- Environment variables (e.g. `AWS_ACCESS_KEY_ID` or `AWS_PROFILE`) +- Shared credentials file (e.g. `~/.aws/credentials`) +- EC2 Instance Metadata Service +- Default AWS Go SDK handling (shared configuration, CodeBuild/ECS/EKS) + +The provider now prefers the following credential ordering: + +- Static credentials (those defined in the Terraform configuration) +- Environment variables (e.g. `AWS_ACCESS_KEY_ID` or `AWS_PROFILE`) +- Shared credentials and/or configuration file (e.g. `~/.aws/credentials` and `~/.aws/config`) +- Default AWS Go SDK handling (shared configuration, CodeBuild/ECS/EKS, EC2 Instance Metadata Service) + +This means workarounds of disabling the EC2 Instance Metadata Service handling to enable CodeBuild/ECS/EKS credentials or to enable other credential methods such as `credential_process` in the AWS shared configuration are no longer necessary. + +### Shared Configuration File Automatically Enabled + +The `AWS_SDK_LOAD_CONFIG` environment variable is no longer necessary for the provider to automatically load the AWS shared configuration file (e.g. `~/.aws/config`). + +### Removal of AWS_METADATA_TIMEOUT Environment Variable Usage + +The provider now relies on the default AWS Go SDK timeouts for interacting with the EC2 Instance Metadata Service. + +## Provider Custom Service Endpoint Updates + +### Removal of kinesis_analytics and r53 Arguments + +The [custom service endpoints](custom-service-endpoints.html) for Kinesis Analytics and Route 53 now use the `kinesisanalytics` and `route53` argument names in the provider configuration. + +For example, given this previous configuration: + +```hcl +provider "aws" { + # ... potentially other configuration ... + + endpoints { + # ... potentially other configuration ... + + kinesis_analytics = "https://example.com" + r53 = "https://example.com" + } +} +``` + +An updated configuration: + +```hcl +provider "aws" { + # ... potentially other configuration ... + + endpoints { + # ... potentially other configuration ... + + kinesisanalytics = "https://example.com" + route53 = "https://example.com" + } +} +``` + +## Data Source: aws_availability_zones + +### blacklisted_names Attribute Removal + +Switch your Terraform configuration to the `exclude_names` attribute instead. + +For example, given this previous configuration: + +```hcl +data "aws_availability_zones" "example" { + blacklisted_names = ["us-west-2d"] +} +``` + +An updated configuration: + +```hcl +data "aws_availability_zones" "example" { + exclude_names = ["us-west-2d"] +} +``` + +### blacklisted_zone_ids Attribute Removal + +Switch your Terraform configuration to the `exclude_zone_ids` attribute instead. + +For example, given this previous configuration: + +```hcl +data "aws_availability_zones" "example" { + blacklisted_zone_ids = ["usw2-az4"] +} +``` + +An updated configuration: + +```hcl +data "aws_availability_zones" "example" { + exclude_zone_ids = ["usw2-az4"] +} +``` + +## Data Source: aws_lambda_invocation + +### result_map Attribute Removal + +Switch your Terraform configuration to the `result` attribute with the [`jsondecode()` function](https://www.terraform.io/docs/configuration/functions/jsondecode.html) instead. + +For example, given this previous configuration: + +```hcl +# In Terraform 0.11 and earlier, the result_map attribute can be used +# to convert a result JSON string to a map of string keys to string values. +output "lambda_result" { + value = "${data.aws_lambda_invocation.example.result_map["key1"]}" +} +``` + +An updated configuration: + +```hcl +# In Terraform 0.12 and later, the jsondecode() function can be used +# to convert a result JSON string to native Terraform types. +output "lambda_result" { + value = jsondecode(data.aws_lambda_invocation.example.result)["key1"] +} +``` + +## Data Source: aws_route53_resolver_rule + +### Removal of trailing period in domain_name argument + +Previously the data-source returned the Resolver Rule Domain Name directly from the API, which included a `.` suffix. This proves difficult when many other AWS services do not accept this trailing period (e.g. ACM Certificate). This period is now automatically removed. For example, when the attribute would previously return a Resolver Rule Domain Name such as `example.com.`, the attribute now will be returned as `example.com`. +While the returned value will omit the trailing period, use of configurations with trailing periods will not be interrupted. + +## Data Source: aws_route53_zone + +### Removal of trailing period in name argument + +Previously the data-source returned the Hosted Zone Domain Name directly from the API, which included a `.` suffix. This proves difficult when many other AWS services do not accept this trailing period (e.g. ACM Certificate). This period is now automatically removed. For example, when the attribute would previously return a Hosted Zone Domain Name such as `example.com.`, the attribute now will be returned as `example.com`. +While the returned value will omit the trailing period, use of configurations with trailing periods will not be interrupted. + +## Resource: aws_acm_certificate + +### domain_validation_options Changed from List to Set + +Previously, the `domain_validation_options` attribute was a list type and completely unknown until after an initial `terraform apply`. This generally required complicated configuration workarounds to properly create DNS validation records since referencing this attribute directly could produce errors similar to the below: + +``` +Error: Invalid for_each argument + + on main.tf line 16, in resource "aws_route53_record" "existing": + 16: for_each = aws_acm_certificate.existing.domain_validation_options + +The "for_each" value depends on resource attributes that cannot be determined +until apply, so Terraform cannot predict how many instances will be created. +To work around this, use the -target argument to first apply only the +resources that the for_each depends on. +``` + +The `domain_validation_options` attribute is now a set type and the resource will attempt to populate the information necessary during the planning phase to handle the above situation in most environments without workarounds. This change also prevents Terraform from showing unexpected differences if the API returns the results in varying order. + +Configuration references to this attribute will likely require updates since sets cannot be indexed (e.g. `domain_validation_options[0]` or the older `domain_validation_options.0.` syntax will return errors). If the `domain_validation_options` list previously contained only a single element like the two examples just shown, it may be possible to wrap these references using the [`tolist()` function](/docs/configuration/functions/tolist.html) (e.g. `tolist(aws_acm_certificate.example.domain_validation_options)[0]`) as a quick configuration update, however given the complexity and workarounds required with the previous `domain_validation_options` attribute implementation, different environments will require different configuration updates and migration steps. Below is a more advanced example. Further questions on potential update steps can be submitted to the [community forums](https://discuss.hashicorp.com/c/terraform-providers/tf-aws/33). + +For example, given this previous configuration using a `count` based resource approach that may have been used in certain environments: + +```hcl +data "aws_route53_zone" "public_root_domain" { + name = var.public_root_domain +} + +resource "aws_acm_certificate" "existing" { + domain_name = "existing.${var.public_root_domain}" + subject_alternative_names = [ + "existing1.${var.public_root_domain}", + "existing2.${var.public_root_domain}", + "existing3.${var.public_root_domain}", + ] + validation_method = "DNS" +} + +resource "aws_route53_record" "existing" { + count = length(aws_acm_certificate.existing.subject_alternative_names) + 1 + + allow_overwrite = true + name = aws_acm_certificate.existing.domain_validation_options[count.index].resource_record_name + records = [aws_acm_certificate.existing.domain_validation_options[count.index].resource_record_value] + ttl = 60 + type = aws_acm_certificate.existing.domain_validation_options[count.index].resource_record_type + zone_id = data.aws_route53_zone.public_root_domain.zone_id +} + +resource "aws_acm_certificate_validation" "existing" { + certificate_arn = aws_acm_certificate.existing.arn + validation_record_fqdns = aws_route53_record.existing[*].fqdn +} + +``` + +It will receive errors like the below after upgrading: + +``` +Error: Invalid index + + on main.tf line 14, in resource "aws_route53_record" "existing": + 14: name = aws_acm_certificate.existing.domain_validation_options[count.index].resource_record_name + |---------------- + | aws_acm_certificate.existing.domain_validation_options is set of object with 4 elements + | count.index is 1 + +This value does not have any indices. +``` + +Since the `domain_validation_options` attribute changed from a list to a set and sets cannot be indexed in Terraform, the recommendation is to update the configuration to use the more stable [resource `for_each` support](/docs/configuration/resources.html#for_each-multiple-resource-instances-defined-by-a-map-or-set-of-strings) instead of [`count`](/docs/configuration/resources.html#count-multiple-resource-instances-by-count). Note the slight change in the `validation_record_fqdns` syntax as well. + +```hcl +resource "aws_route53_record" "existing" { + for_each = { + for dvo in aws_acm_certificate.existing.domain_validation_options : dvo.domain_name => { + name = dvo.resource_record_name + record = dvo.resource_record_value + type = dvo.resource_record_type + } + } + + allow_overwrite = true + name = each.value.name + records = [each.value.record] + ttl = 60 + type = each.value.type + zone_id = data.aws_route53_zone.public_root_domain.zone_id +} + +resource "aws_acm_certificate_validation" "existing" { + certificate_arn = aws_acm_certificate.existing.arn + validation_record_fqdns = [for record in aws_route53_record.existing : record.fqdn] +} +``` + +After the configuration has been updated, a plan should no longer error and may look like the following: + +``` +------------------------------------------------------------------------ + +An execution plan has been generated and is shown below. +Resource actions are indicated with the following symbols: + + create + - destroy +-/+ destroy and then create replacement + +Terraform will perform the following actions: + + # aws_acm_certificate_validation.existing must be replaced +-/+ resource "aws_acm_certificate_validation" "existing" { + certificate_arn = "arn:aws:acm:us-east-2:123456789012:certificate/ccbc58e8-061d-4443-9035-d3af0512e863" + ~ id = "2020-07-16 00:01:19 +0000 UTC" -> (known after apply) + ~ validation_record_fqdns = [ + - "_40b71647a8d88eb82d53fe988e8a3cc1.existing2.example.com", + - "_812ddf11b781af1eec1643ec58f102d2.existing.example.com", + - "_8dc56b6e35f699b8754afcdd79e9748d.existing3.example.com", + - "_d7112da809a40e848207c04399babcec.existing1.example.com", + ] -> (known after apply) # forces replacement + } + + # aws_route53_record.existing will be destroyed + - resource "aws_route53_record" "existing" { + - fqdn = "_812ddf11b781af1eec1643ec58f102d2.existing.example.com" -> null + - id = "Z123456789012__812ddf11b781af1eec1643ec58f102d2.existing.example.com._CNAME" -> null + - name = "_812ddf11b781af1eec1643ec58f102d2.existing.example.com" -> null + - records = [ + - "_bdeba72164eec216c55a32374bcceafd.jfrzftwwjs.acm-validations.aws.", + ] -> null + - ttl = 60 -> null + - type = "CNAME" -> null + - zone_id = "Z123456789012" -> null + } + + # aws_route53_record.existing[1] will be destroyed + - resource "aws_route53_record" "existing" { + - fqdn = "_40b71647a8d88eb82d53fe988e8a3cc1.existing2.example.com" -> null + - id = "Z123456789012__40b71647a8d88eb82d53fe988e8a3cc1.existing2.example.com._CNAME" -> null + - name = "_40b71647a8d88eb82d53fe988e8a3cc1.existing2.example.com" -> null + - records = [ + - "_638532db1fa6a1b71aaf063c8ea29d52.jfrzftwwjs.acm-validations.aws.", + ] -> null + - ttl = 60 -> null + - type = "CNAME" -> null + - zone_id = "Z123456789012" -> null + } + + # aws_route53_record.existing[2] will be destroyed + - resource "aws_route53_record" "existing" { + - fqdn = "_d7112da809a40e848207c04399babcec.existing1.example.com" -> null + - id = "Z123456789012__d7112da809a40e848207c04399babcec.existing1.example.com._CNAME" -> null + - name = "_d7112da809a40e848207c04399babcec.existing1.example.com" -> null + - records = [ + - "_6e1da5574ab46a6c782ed73438274181.jfrzftwwjs.acm-validations.aws.", + ] -> null + - ttl = 60 -> null + - type = "CNAME" -> null + - zone_id = "Z123456789012" -> null + } + + # aws_route53_record.existing[3] will be destroyed + - resource "aws_route53_record" "existing" { + - fqdn = "_8dc56b6e35f699b8754afcdd79e9748d.existing3.example.com" -> null + - id = "Z123456789012__8dc56b6e35f699b8754afcdd79e9748d.existing3.example.com._CNAME" -> null + - name = "_8dc56b6e35f699b8754afcdd79e9748d.existing3.example.com" -> null + - records = [ + - "_a419f8410d2e0720528a96c3506f3841.jfrzftwwjs.acm-validations.aws.", + ] -> null + - ttl = 60 -> null + - type = "CNAME" -> null + - zone_id = "Z123456789012" -> null + } + + # aws_route53_record.existing["existing.example.com"] will be created + + resource "aws_route53_record" "existing" { + + allow_overwrite = true + + fqdn = (known after apply) + + id = (known after apply) + + name = "_812ddf11b781af1eec1643ec58f102d2.existing.example.com" + + records = [ + + "_bdeba72164eec216c55a32374bcceafd.jfrzftwwjs.acm-validations.aws.", + ] + + ttl = 60 + + type = "CNAME" + + zone_id = "Z123456789012" + } + + # aws_route53_record.existing["existing1.example.com"] will be created + + resource "aws_route53_record" "existing" { + + allow_overwrite = true + + fqdn = (known after apply) + + id = (known after apply) + + name = "_d7112da809a40e848207c04399babcec.existing1.example.com" + + records = [ + + "_6e1da5574ab46a6c782ed73438274181.jfrzftwwjs.acm-validations.aws.", + ] + + ttl = 60 + + type = "CNAME" + + zone_id = "Z123456789012" + } + + # aws_route53_record.existing["existing2.example.com"] will be created + + resource "aws_route53_record" "existing" { + + allow_overwrite = true + + fqdn = (known after apply) + + id = (known after apply) + + name = "_40b71647a8d88eb82d53fe988e8a3cc1.existing2.example.com" + + records = [ + + "_638532db1fa6a1b71aaf063c8ea29d52.jfrzftwwjs.acm-validations.aws.", + ] + + ttl = 60 + + type = "CNAME" + + zone_id = "Z123456789012" + } + + # aws_route53_record.existing["existing3.example.com"] will be created + + resource "aws_route53_record" "existing" { + + allow_overwrite = true + + fqdn = (known after apply) + + id = (known after apply) + + name = "_8dc56b6e35f699b8754afcdd79e9748d.existing3.example.com" + + records = [ + + "_a419f8410d2e0720528a96c3506f3841.jfrzftwwjs.acm-validations.aws.", + ] + + ttl = 60 + + type = "CNAME" + + zone_id = "Z123456789012" + } + +Plan: 5 to add, 0 to change, 5 to destroy. +``` + +Due to the type of configuration change, Terraform does not know that the previous `aws_route53_record` resources (indexed by number in the existing state) and the new resources (indexed by domain names in the updated configuration) are equivalent. Typically in this situation, the [`terraform state mv` command](/docs/commands/state/mv.html) can be used to reduce the plan to show no changes. This is done by associating the count index (e.g. `[1]`) with the equivalent domain name index (e.g. `["existing2.example.com"]`), making one of the four commands to fix the above example: `terraform state mv 'aws_route53_record.existing[1]' 'aws_route53_record.existing["existing2.example.com"]'`. It is recommended to use this `terraform state mv` update process where possible to reduce chances of unexpected behaviors or changes in an environment. + +If using `terraform state mv` to reduce the plan to show no changes, no additional steps are required. + +In larger or more complex environments though, this process can be tedius to match the old resource address to the new resource address and run all the necessary `terraform state mv` commands. Instead, since the `aws_route53_record` resource implements the `allow_overwrite = true` argument, it is possible to just remove the old `aws_route53_record` resources from the Terraform state using the [`terraform state rm` command](/docs/commands/state/rm.html). In this case, Terraform will leave the existing records in Route 53 and plan to just overwrite the existing validation records with the same exact (previous) values. + +-> This guide is showing the simpler `terraform state rm` option below as a potential shortcut in this specific situation, however in most other cases `terraform state mv` is required to change from `count` based resources to `for_each` based resources and properly match the existing Terraform state to the updated Terraform configuration. + +```console +$ terraform state rm aws_route53_record.existing +Removed aws_route53_record.existing[0] +Removed aws_route53_record.existing[1] +Removed aws_route53_record.existing[2] +Removed aws_route53_record.existing[3] +Successfully removed 4 resource instance(s). +``` + +Now the Terraform plan will show only the additions of new Route 53 records (which are exactly the same as before the upgrade) and the proposed recreation of the `aws_acm_certificate_validation` resource. The `aws_acm_certificate_validation` resource recreation will have no effect as the certificate is already validated and issued. + +``` +An execution plan has been generated and is shown below. +Resource actions are indicated with the following symbols: + + create +-/+ destroy and then create replacement + +Terraform will perform the following actions: + + # aws_acm_certificate_validation.existing must be replaced +-/+ resource "aws_acm_certificate_validation" "existing" { + certificate_arn = "arn:aws:acm:us-east-2:123456789012:certificate/ccbc58e8-061d-4443-9035-d3af0512e863" + ~ id = "2020-07-16 00:01:19 +0000 UTC" -> (known after apply) + ~ validation_record_fqdns = [ + - "_40b71647a8d88eb82d53fe988e8a3cc1.existing2.example.com", + - "_812ddf11b781af1eec1643ec58f102d2.existing.example.com", + - "_8dc56b6e35f699b8754afcdd79e9748d.existing3.example.com", + - "_d7112da809a40e848207c04399babcec.existing1.example.com", + ] -> (known after apply) # forces replacement + } + + # aws_route53_record.existing["existing.example.com"] will be created + + resource "aws_route53_record" "existing" { + + allow_overwrite = true + + fqdn = (known after apply) + + id = (known after apply) + + name = "_812ddf11b781af1eec1643ec58f102d2.existing.example.com" + + records = [ + + "_bdeba72164eec216c55a32374bcceafd.jfrzftwwjs.acm-validations.aws.", + ] + + ttl = 60 + + type = "CNAME" + + zone_id = "Z123456789012" + } + + # aws_route53_record.existing["existing1.example.com"] will be created + + resource "aws_route53_record" "existing" { + + allow_overwrite = true + + fqdn = (known after apply) + + id = (known after apply) + + name = "_d7112da809a40e848207c04399babcec.existing1.example.com" + + records = [ + + "_6e1da5574ab46a6c782ed73438274181.jfrzftwwjs.acm-validations.aws.", + ] + + ttl = 60 + + type = "CNAME" + + zone_id = "Z123456789012" + } + + # aws_route53_record.existing["existing2.example.com"] will be created + + resource "aws_route53_record" "existing" { + + allow_overwrite = true + + fqdn = (known after apply) + + id = (known after apply) + + name = "_40b71647a8d88eb82d53fe988e8a3cc1.existing2.example.com" + + records = [ + + "_638532db1fa6a1b71aaf063c8ea29d52.jfrzftwwjs.acm-validations.aws.", + ] + + ttl = 60 + + type = "CNAME" + + zone_id = "Z123456789012" + } + + # aws_route53_record.existing["existing3.example.com"] will be created + + resource "aws_route53_record" "existing" { + + allow_overwrite = true + + fqdn = (known after apply) + + id = (known after apply) + + name = "_8dc56b6e35f699b8754afcdd79e9748d.existing3.example.com" + + records = [ + + "_a419f8410d2e0720528a96c3506f3841.jfrzftwwjs.acm-validations.aws.", + ] + + ttl = 60 + + type = "CNAME" + + zone_id = "Z123456789012" + } + +Plan: 5 to add, 0 to change, 1 to destroy. +``` + +Once applied, no differences should be shown and no additional steps should be necessary. + +### subject_alternative_names Changed from List to Set + +Previously the `subject_alternative_names` argument was stored in the Terraform state as an ordered list while the API returned information in an unordered manner. The attribute is now configured as a set instead of a list. Certain Terraform configuration language features distinguish between these two attribute types such as not being able to index a set (e.g. `aws_acm_certificate.example.subject_alternative_names[0]` is no longer a valid reference). Depending on the implementation details of a particular configuration using `subject_alternative_names` as a reference, possible solutions include changing references to using `for`/`for_each` or using the `tolist()` function as a temporary workaround to keep the previous behavior until an appropriate configuration (properly using the unordered set) can be determined. Usage questions can be submitted to the [community forums](https://discuss.hashicorp.com/c/terraform-providers/tf-aws/33). + +### certificate_body, certificate_chain, and private_key Arguments No Longer Stored as Hash + +Previously when the `certificate_body`, `certificate_chain`, and `private_key` arguments were stored in state, they were stored as a hash of the actual value. This prevented Terraform from properly updating the resource when necessary and the hashing has been removed. The Terraform AWS Provider will show an update to these arguments on the first apply after upgrading to version 3.0.0, which is fixing the Terraform state to remove the hash. Since the `private_key` attribute is marked as sensitive, the values in the update will not be visible in the Terraform output. If the non-hashed values have not changed, then no update is occurring other than the Terraform state update. If these arguments are the only updates and they all match the hash removal, the apply will occur without submitting API calls. + +## Resource: aws_api_gateway_method_settings + +### throttling_burst_limit and throttling_rate_limit Arguments Now Default to -1 + +Previously when the `throttling_burst_limit` or `throttling_rate_limit` argument was not configured, the resource would enable throttling and set the limit value to the AWS API Gateway default. In addition, as these arguments were marked as `Computed`, Terraform ignored any subsequent changes made to these arguments in the resource. These behaviors have been removed and, by default, the `throttling_burst_limit` and `throttling_rate_limit` arguments will be disabled in the resource with a value of `-1`. + +## Resource: aws_autoscaling_group + +### availability_zones and vpc_zone_identifier Arguments Now Report Plan-Time Conflict + +Specifying both the `availability_zones` and `vpc_zone_identifier` arguments previously led to confusing behavior and errors. Now this issue is reported at plan-time. Use the `null` value instead of `[]` (empty list) in conditionals to ensure this validation does not unexpectedly trigger. + +### Drift detection enabled for `load_balancers` and `target_group_arns` arguments + +If you previously set one of these arguments to an empty list to enable drift detection (e.g. when migrating an ASG from ELB to ALB), this can be updated as follows. + +For example, given this previous configuration: + +```hcl +resource "aws_autoscaling_group" "example" { + # ... other configuration ... + load_balancers = [] + target_group_arns = [aws_lb_target_group.example.arn] +} +``` + +An updated configuration: + +```hcl +resource "aws_autoscaling_group" "example" { + # ... other configuration ... + target_group_arns = [aws_lb_target_group.example.arn] +} +``` + +If `aws_autoscaling_attachment` resources reference your ASG configurations, you will need to add the [`lifecycle` configuration block](/docs/configuration/resources.html#lifecycle-lifecycle-customizations) with an `ignore_changes` argument to prevent Terraform non-empty plans (i.e. forcing resource update) during the next state refresh. + +For example, given this previous configuration: + +```hcl +resource "aws_autoscaling_attachment" "example" { + autoscaling_group_name = aws_autoscaling_group.example.id + elb = aws_elb.example.id +} + +resource "aws_autoscaling_group" "example" { + # ... other configuration ... +} +``` + +An updated configuration: + +```hcl +resource "aws_autoscaling_attachment" "example" { + autoscaling_group_name = aws_autoscaling_group.example.id + elb = aws_elb.example.id +} + +resource "aws_autoscaling_group" "example" { + # ... other configuration ... + + lifecycle { + ignore_changes = [load_balancers, target_group_arns] + } +} +``` + +## Resource: aws_cloudfront_distribution + +### active_trusted_signers Attribute Name and Type Change + +Previously, the `active_trusted_signers` computed attribute was implemented with a Map that did not support accessing its computed `items` attribute in Terraform 0.12 correctly. +To address this, the `active_trusted_signers` attribute has been renamed to `trusted_signers` and is now implemented as a List with a computed `items` List attribute and computed `enabled` boolean attribute. +The nested `items` attribute includes computed `aws_account_number` and `key_pair_ids` sub-fields, with the latter implemented as a List. +Thus, user configurations referencing the `active_trusted_signers` attribute and its sub-fields will need to be changed as follows. + +Given these previous references: + +``` +aws_cloudfront_distribution.example.active_trusted_signers.enabled +aws_cloudfront_distribution.example.active_trusted_signers.items +``` + +Updated references: + +``` +aws_cloudfront_distribution.example.trusted_signers[0].enabled +aws_cloudfront_distribution.example.trusted_signers[0].items +``` + +## Resource: aws_cloudwatch_log_group + +### Removal of arn Wildcard Suffix + +Previously, the resource returned the Amazon Resource Name (ARN) directly from the API, which included a `:*` suffix to denote all CloudWatch Log Streams under the CloudWatch Log Group. Most other AWS resources that return ARNs and many other AWS services do not use the `:*` suffix. The suffix is now automatically removed. For example, the resource previously returned an ARN such as `arn:aws:logs:us-east-1:123456789012:log-group:/example:*` but will now return `arn:aws:logs:us-east-1:123456789012:log-group:/example`. + +Workarounds, such as using `replace()` as shown below, should be removed: + +```hcl +resource "aws_cloudwatch_log_group" "example" { + name = "example" +} +resource "aws_datasync_task" "example" { + # ... other configuration ... + cloudwatch_log_group_arn = replace(aws_cloudwatch_log_group.example.arn, ":*", "") +} +``` + +Removing the `:*` suffix is a breaking change for some configurations. Fix these configurations using string interpolations as demonstrated below. For example, this configuration is now broken: + +```hcl +data "aws_iam_policy_document" "ad-log-policy" { + statement { + actions = [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + principals { + identifiers = ["ds.amazonaws.com"] + type = "Service" + } + resources = [aws_cloudwatch_log_group.example.arn] + effect = "Allow" + } +} +``` + +An updated configuration: + +```hcl +data "aws_iam_policy_document" "ad-log-policy" { + statement { + actions = [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + principals { + identifiers = ["ds.amazonaws.com"] + type = "Service" + } + resources = ["${aws_cloudwatch_log_group.example.arn}:*"] + effect = "Allow" + } +} +``` + +## Resource: aws_codepipeline + +### GITHUB_TOKEN environment variable removal + +Switch your Terraform configuration to the `OAuthToken` element in the `action` `configuration` map instead. + +For example, given this previous configuration: + +```bash +$ GITHUB_TOKEN= terraform apply +``` + +```hcl +resource "aws_codepipeline" "example" { + # ... other configuration ... + + stage { + name = "Source" + + action { + name = "Source" + category = "Source" + owner = "ThirdParty" + provider = "GitHub" + version = "1" + output_artifacts = ["example"] + + configuration = { + Owner = "lifesum-terraform" + Repo = "example" + Branch = "main" + } + } + } +} +``` + +```bash +$ TF_VAR_github_token= terraform apply +``` + +```hcl +variable "github_token" {} -Most of the changes outlined in this guide have been previously marked as deprecated in the Terraform plan/apply output throughout previous provider releases. These changes, such as deprecation notices, can always be found in the [Terraform AWS Provider CHANGELOG](https://github.com/terraform-providers/terraform-provider-aws/blob/master/CHANGELOG.md). +resource "aws_codepipeline" "example" { + # ... other configuration ... -Upgrade topics: + stage { + name = "Source" + + action { + name = "Source" + category = "Source" + owner = "ThirdParty" + provider = "GitHub" + version = "1" + output_artifacts = ["example"] + + configuration = { + Owner = "lifesum-terraform" + Repo = "example" + Branch = "main" + OAuthToken = var.github_token + } + } + } +} +``` - +## Resource: aws_cognito_user_pool -- [Provider Version Configuration](#provider-version-configuration) -- [Resource: aws_emr_cluster](#resource-aws_emr_cluster) +### Removal of admin_create_user_config.unused_account_validity_days Argument - +The Cognito API previously deprecated the `admin_create_user_config` configuration block `unused_account_validity_days` argument in preference of the `password_policy` configuration block `temporary_password_validity_days` argument. Configurations will need to be updated to use the API supported configuration. -## Provider Version Configuration +For example, given this previous configuration: + +```hcl +resource "aws_cognito_user_pool" "example" { + # ... other configuration ... -!> **WARNING:** This topic is placeholder documentation until version 3.0.0 is released in the coming months. + admin_create_user_config { + # ... potentially other configuration ... --> Before upgrading to version 3.0.0, it is recommended to upgrade to the most recent 2.X version of the provider and ensure that your environment successfully runs [`terraform plan`](https://www.terraform.io/docs/commands/plan.html) without unexpected changes or deprecation notices. + unused_account_validity_days = 7 + } +} +``` -It is recommended to use [version constraints when configuring Terraform providers](https://www.terraform.io/docs/configuration/providers.html#provider-versions). If you are following that recommendation, update the version constraints in your Terraform configuration and run [`terraform init`](https://www.terraform.io/docs/commands/init.html) to download the new version. +An updated configuration: + +```hcl +resource "aws_cognito_user_pool" "example" { + # ... other configuration ... + + password_policy { + # ... potentially other configuration ... + + temporary_password_validity_days = 7 + } +} +``` + +## Resource: aws_dx_gateway + +### Removal of Automatic aws_dx_gateway_association Import + +Previously when importing the `aws_dx_gateway` resource with the [`terraform import` command](/docs/commands/import.html), the Terraform AWS Provider would automatically attempt to import an associated `aws_dx_gateway_association` resource(s) as well. This automatic resource import has been removed. Use the [`aws_dx_gateway_association` resource import](/docs/providers/aws/r/dx_gateway_association.html#import) to import those resources separately. + +## Resource: aws_dx_gateway_association + +### vpn_gateway_id Argument Removal + +Switch your Terraform configuration to the `associated_gateway_id` argument instead. For example, given this previous configuration: ```hcl -provider "aws" { +resource "aws_dx_gateway_association" "example" { # ... other configuration ... + vpn_gateway_id = aws_vpn_gateway.example.id +} +``` - version = "~> 2.8" +An updated configuration: + +```hcl +resource "aws_dx_gateway_association" "example" { + # ... other configuration ... + associated_gateway_id = aws_vpn_gateway.example.id } ``` -Update to latest 3.X version: +## Resource: aws_dx_gateway_association_proposal + +### vpn_gateway_id Argument Removal + +Switch your Terraform configuration to the `associated_gateway_id` argument instead. + +For example, given this previous configuration: ```hcl -provider "aws" { +resource "aws_dx_gateway_association_proposal" "example" { # ... other configuration ... + vpn_gateway_id = aws_vpn_gateway.example.id +} +``` - version = "~> 3.0" +An updated configuration: + +```hcl +resource "aws_dx_gateway_association_proposal" "example" { + # ... other configuration ... + associated_gateway_id = aws_vpn_gateway.example.id } ``` +## Resource: aws_ebs_volume + +### iops Argument Apply-Time Validation + +Previously when the `iops` argument was configured with a `type` other than `io1` (either explicitly or omitted, indicating the default type `gp2`), the Terraform AWS Provider would automatically disregard the value provided to `iops` as it is only configurable for the `io1` volume type per the AWS EC2 API. This behavior has changed such that the Terraform AWS Provider will instead return an error at apply time indicating an `iops` value is invalid for types other than `io1`. +Exceptions to this are in cases where `iops` is set to `null` or `0` such that the Terraform AWS Provider will continue to accept the value regardless of `type`. + +## Resource: aws_elastic_transcoder_preset + +### video Configuration Block max_frame_rate Argument No Longer Uses 30 Default + +Previously when the `max_frame_rate` argument was not configured, the resource would default to 30. This behavior has been removed and allows for auto frame rate presets to automatically set the appropriate value. + ## Resource: aws_emr_cluster ### core_instance_count Argument Removal @@ -118,8 +955,8 @@ resource "aws_emr_cluster" "example" { # ... other configuration ... instance_group { - instance_role = "MASTER" - instance_type = "m4.large" + instance_role = "MASTER" + instance_type = "m4.large" } instance_group { @@ -153,7 +990,7 @@ resource "aws_emr_cluster" "example" { } resource "aws_emr_instance_group" "example" { - cluster_id = "${aws_emr_cluster.example.id}" + cluster_id = aws_emr_cluster.example.id instance_count = 2 instance_type = "c4.xlarge" } @@ -185,6 +1022,117 @@ resource "aws_emr_cluster" "example" { } ``` +## Resource: aws_glue_job + +### allocated_capacity Argument Removal + +The Glue API has deprecated the `allocated_capacity` argument. Switch your Terraform configuration to the `max_capacity` argument instead. + +For example, given this previous configuration: + +```hcl +resource "aws_glue_job" "example" { + # ... other configuration ... + + allocated_capacity = 2 +} +``` + +An updated configuration: + +```hcl +resource "aws_glue_job" "example" { + # ... other configuration ... + + max_capacity = 2 +} +``` + +## Resource: aws_iam_access_key + +### ses_smtp_password Attribute Removal + +In many regions today and in all regions after October 1, 2020, the [SES API will only accept version 4 signatures](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/using-ses-api-authentication.html). If referencing the `ses_smtp_password` attribute, switch your Terraform configuration to the `ses_smtp_password_v4` attribute instead. Please note that this signature is based on the region of the Terraform AWS Provider. If you need the SES v4 password in multiple regions, it may require using [multiple provider instances](/docs/configuration/providers.html#alias-multiple-provider-instances). + +## Resource: aws_iam_instance_profile + +### roles Argument Removal + +Switch your Terraform configuration to the `role` argument instead. + +For example, given this previous configuration: + +```hcl +resource "aws_iam_instance_profile" "example" { + # ... other configuration ... + + roles = [aws_iam_role.example.id] +} +``` + +An updated configuration: + +```hcl +resource "aws_iam_instance_profile" "example" { + # ... other configuration ... + + role = aws_iam_role.example.id +} +``` + +## Resource: aws_iam_server_certificate + +### certificate_body, certificate_chain, and private_key Arguments No Longer Stored as Hash + +Previously when the `certificate_body`, `certificate_chain`, and `private_key` arguments were stored in state, they were stored as a hash of the actual value. This hashing has been removed for new or recreated resources to prevent lifecycle issues. + +## Resource: aws_instance + +### ebs_block_device.iops and root_block_device.iops Argument Apply-Time Validations + +Previously when the `iops` argument was configured in either the `ebs_block_device` or `root_block_device` configuration block, the Terraform AWS Provider would automatically disregard the value provided to `iops` if the `type` argument was also configured with a value other than `io1` (either explicitly or omitted, indicating the default type `gp2`) as `iops` are only configurable for the `io1` volume type per the AWS EC2 API. This behavior has changed such that the Terraform AWS Provider will instead return an error at apply time indicating an `iops` value is invalid for volume types other than `io1`. +Exceptions to this are in cases where `iops` is set to `null` or `0` such that the Terraform AWS Provider will continue to accept the value regardless of `type`. + +## Resource: aws_lambda_alias + +### Import No Longer Converts Function Name to ARN + +Previously the resource import would always convert the `function_name` portion of the import identifier into the ARN format. Configurations using the Lambda Function name would show this as an unexpected difference after import. Now this will passthrough the given value on import whether its a Lambda Function name or ARN. + +## Resource: aws_launch_template + +### network_interfaces.delete_on_termination Argument type change + +The `network_interfaces.delete_on_termination` argument is now of type `string`, allowing an unspecified value for the argument since the previous `bool` type only allowed for `true/false` and defaulted to `false` when no value was set. Now to enforce `delete_on_termination` to `false`, the string `"false"` or bare `false` value must be used. + +For example, given this previous configuration: + +```hcl +resource "aws_launch_template" "example" { + # ... other configuration ... + + network_interfaces { + # ... other configuration ... + + delete_on_termination = null + } +} +``` + +An updated configuration: + +```hcl +resource "aws_launch_template" "example" { + # ... other configuration ... + + network_interfaces { + # ... other configuration ... + + delete_on_termination = false + } +} +``` + ## Resource: aws_lb_listener_rule ### condition.field and condition.values Arguments Removal @@ -217,3 +1165,193 @@ resource "aws_lb_listener_rule" "example" { } } ``` + +## Resource: aws_msk_cluster + +### encryption_info.encryption_in_transit.client_broker Default Updated to Match API + +A few weeks after general availability launch and initial release of the `aws_msk_cluster` resource, the MSK API default for client broker encryption switched from `TLS_PLAINTEXT` to `TLS`. The attribute default has now been updated to match the more secure API default, however existing Terraform configurations may show a difference if this setting is not configured. + +To continue using the old default when it was previously not configured, add or modify this configuration: + +```hcl +resource "aws_msk_cluster" "example" { + # ... other configuration ... + + encryption_info { + # ... potentially other configuration ... + + encryption_in_transit { + # ... potentially other configuration ... + + client_broker = "TLS_PLAINTEXT" + } + } +} +``` + +## Resource: aws_rds_cluster + +### scaling_configuration.min_capacity Now Defaults to 1 + +Previously when the `min_capacity` argument in a `scaling_configuration` block was not configured, the resource would default to 2. This behavior has been updated to align with the AWS RDS Cluster API default of 1. + +## Resource: aws_route53_resolver_rule + +### Removal of trailing period in domain_name argument + +Previously the resource returned the Resolver Rule Domain Name directly from the API, which included a `.` suffix. This proves difficult when many other AWS services do not accept this trailing period (e.g. ACM Certificate). This period is now automatically removed. For example, when the attribute would previously return a Resolver Rule Domain Name such as `example.com.`, the attribute now will be returned as `example.com`. +While the returned value will omit the trailing period, use of configurations with trailing periods will not be interrupted. + +## Resource: aws_route53_zone + +### Removal of trailing period in name argument + +Previously the resource returned the Hosted Zone Domain Name directly from the API, which included a `.` suffix. This proves difficult when many other AWS services do not accept this trailing period (e.g. ACM Certificate). This period is now automatically removed. For example, when the attribute would previously return a Hosted Zone Domain Name such as `example.com.`, the attribute now will be returned as `example.com`. +While the returned value will omit the trailing period, use of configurations with trailing periods will not be interrupted. + +## Resource: aws_s3_bucket + +### Removal of Automatic aws_s3_bucket_policy Import + +Previously when importing the `aws_s3_bucket` resource with the [`terraform import` command](/docs/commands/import.html), the Terraform AWS Provider would automatically attempt to import an associated `aws_s3_bucket_policy` resource as well. This automatic resource import has been removed. Use the [`aws_s3_bucket_policy` resource import](/docs/providers/aws/r/s3_bucket_policy.html#import) to import that resource separately. + +### region Attribute Is Now Read-Only + +The `region` attribute is no longer configurable, but it remains as a read-only attribute. The region of the `aws_s3_bucket` resource is determined by the region of the Terraform AWS Provider, similar to all other resources. + +For example, given this previous configuration: + +```hcl +resource "aws_s3_bucket" "example" { + # ... other configuration ... + + region = "us-west-2" +} +``` + +An updated configuration: + +```hcl +resource "aws_s3_bucket" "example" { + # ... other configuration ... +} +``` + +## Resource: aws_s3_bucket_metric + +### filter configuration block Plan-Time Validation Change + +The `filter` configuration block no longer supports the empty block `{}` and requires at least one of the `prefix` or `tags` attributes to be specified. + +For example, given this previous configuration: + +```hcl +resource "aws_s3_bucket_metric" "example" { + # ... other configuration ... + + filter {} +} +``` + +An updated configuration: + +```hcl +resource "aws_s3_bucket_metric" "example" { + # ... other configuration ... +} +``` + +## Resource: aws_security_group + +### Removal of Automatic aws_security_group_rule Import + +Previously when importing the `aws_security_group` resource with the [`terraform import` command](/docs/commands/import.html), the Terraform AWS Provider would automatically attempt to import an associated `aws_security_group_rule` resource(s) as well. This automatic resource import has been removed. Use the [`aws_security_group_rule` resource import](/docs/providers/aws/r/security_group_rule.html#import) to import those resources separately. + +## Resource: aws_sns_platform_application + +### platform_credential and platform_principal Arguments No Longer Stored as SHA256 Hash + +Previously when the `platform_credential` and `platform_principal` arguments were stored in state, they were stored as a SHA256 hash of the actual value. This prevented Terraform from properly updating the resource when necessary and the hashing has been removed. The Terraform AWS Provider will show an update to these arguments on the first apply after upgrading to version 3.0.0, which is fixing the Terraform state to remove the hash. Since the attributes are marked as sensitive, the values in the update will not be visible in the Terraform output. If the non-hashed values have not changed, then no update is occurring other than the Terraform state update. If these arguments are the only two updates and they both match the SHA256 removal, the apply will occur without submitting an actual `SetPlatformApplicationAttributes` API call. + +## Resource: aws_spot_fleet_request + +### valid_until Argument No Longer Uses 24 Hour Default + +Previously when the `valid_until` argument was not configured, the resource would default to a 24 hour request. This behavior has been removed and allows for non-expiring requests. To recreate the old behavior, the [`time_offset` resource](/docs/providers/time/r/offset.html) can potentially be used. + +## Resource: aws_ssm_maintenance_window_task + +### logging_info Configuration Block Removal + +Switch your Terraform configuration to the `task_invocation_parameters` configuration block `run_command_parameters` configuration block `output_s3_bucket` and `output_s3_key_prefix` arguments instead. + +For example, given this previous configuration: + +```hcl +resource "aws_ssm_maintenance_window_task" "example" { + # ... other configuration ... + + logging_info { + s3_bucket_name = aws_s3_bucket.example.id + s3_bucket_key_prefix = "example" + } +} +``` + +An updated configuration: + +```hcl +resource "aws_ssm_maintenance_window_task" "example" { + # ... other configuration ... + + task_invocation_parameters { + # ... potentially other configuration ... + + run_command_parameters { + # ... potentially other configuration ... + + output_s3_bucket = aws_s3_bucket.example.id + output_s3_key_prefix = "example" + } + } +} +``` + +### task_parameters Configuration Block Removal + +Switch your Terraform configuration to the `task_invocation_parameters` configuration block `run_command_parameters` configuration block `parameter` configuration blocks instead. + +For example, given this previous configuration: + +```hcl +resource "aws_ssm_maintenance_window_task" "example" { + # ... other configuration ... + + task_parameters { + name = "commands" + values = ["date"] + } +} +``` + +An updated configuration: + +```hcl +resource "aws_ssm_maintenance_window_task" "example" { + # ... other configuration ... + + task_invocation_parameters { + # ... potentially other configuration ... + + run_command_parameters { + # ... potentially other configuration ... + + parameter { + name = "commands" + values = ["date"] + } + } + } +} +``` diff --git a/website/docs/index.html.markdown b/website/docs/index.html.markdown index 1cc5df3721d..61856f987f8 100644 --- a/website/docs/index.html.markdown +++ b/website/docs/index.html.markdown @@ -18,7 +18,7 @@ Use the navigation to the left to read about the available resources. ```hcl # Configure the AWS Provider provider "aws" { - version = "~> 2.0" + version = "~> 3.0" region = "us-east-1" } @@ -36,10 +36,11 @@ explained below: - Static credentials - Environment variables -- Shared credentials file -- EC2 Role +- Shared credentials/configuration file +- CodeBuild, ECS, and EKS Roles +- EC2 Instance Metadata Service (IMDS and IMDSv2) -### Static credentials +### Static Credentials !> **Warning:** Hard-coding credentials into any Terraform configuration is not recommended, and risks secret leakage should this file ever be committed to a @@ -58,7 +59,7 @@ provider "aws" { } ``` -### Environment variables +### Environment Variables You can provide your credentials via the `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, environment variables, representing your AWS @@ -81,17 +82,9 @@ $ export AWS_DEFAULT_REGION="us-west-2" $ terraform plan ``` -### Shared Credentials file +### Shared Credentials File -You can use an AWS credentials file to specify your credentials. The -default location is `$HOME/.aws/credentials` on Linux and OS X, or -`"%USERPROFILE%\.aws\credentials"` for Windows users. If we fail to -detect credentials inline, or in the environment, Terraform will check -this location. You can optionally specify a different location in the -configuration by providing the `shared_credentials_file` attribute, or -in the environment with the `AWS_SHARED_CREDENTIALS_FILE` variable. This -method also supports a `profile` configuration and matching -`AWS_PROFILE` environment variable: +You can use an [AWS credentials or configuration file](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html) to specify your credentials. The default location is `$HOME/.aws/credentials` on Linux and macOS, or `"%USERPROFILE%\.aws\credentials"` on Windows. You can optionally specify a different location in the Terraform configuration by providing the `shared_credentials_file` argument or using the `AWS_SHARED_CREDENTIALS_FILE` environment variable. This method also supports a `profile` configuration and matching `AWS_PROFILE` environment variable: Usage: @@ -103,17 +96,15 @@ provider "aws" { } ``` -If specifying the profile through the `AWS_PROFILE` environment variable, you -may also need to set `AWS_SDK_LOAD_CONFIG` to a truthy value (e.g. `AWS_SDK_LOAD_CONFIG=1`) for advanced AWS client configurations, such as profiles that use the `source_profile` or `role_arn` configurations. +Please note that the [AWS Go SDK](https://aws.amazon.com/sdk-for-go/), the underlying authentication handler used by the Terraform AWS Provider, does not support all AWS CLI features, such as Single Sign On (SSO) configuration or credentials. -### ECS and CodeBuild Task Roles +### CodeBuild, ECS, and EKS Roles -If you're running Terraform on ECS or CodeBuild and you have configured an [IAM Task Role](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html), -Terraform will use the container's Task Role. Terraform looks for the presence of the `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` -environment variable that AWS injects when a Task Role is configured. If you have not defined a Task Role for your container -or CodeBuild job, Terraform will continue to use the [EC2 Role](#ec2-role). +If you're running Terraform on CodeBuild or ECS and have configured an [IAM Task Role](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html), Terraform will use the container's Task Role. This support is based on the underlying `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` and `AWS_CONTAINER_CREDENTIALS_FULL_URI` environment variables being automatically set by those services or manually for advanced usage. -### EC2 Role +If you're running Terraform on EKS and have configured [IAM Roles for Service Accounts (IRSA)](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html), Terraform will use the pod's role. This support is based on the underlying `AWS_ROLE_ARN` and `AWS_WEB_IDENTITY_TOKEN_FILE` environment variables being automatically set by Kubernetes or manually for advanced usage. + +### EC2 Instance Metadata Service If you're running Terraform from an EC2 instance with IAM Instance Profile using IAM Role, Terraform will just ask @@ -127,15 +118,7 @@ which reduces the chance of leakage. You can provide the custom metadata API endpoint via the `AWS_METADATA_URL` variable which expects the endpoint URL, including the version, and defaults to `http://169.254.169.254:80/latest`. -The default deadline for the EC2 metadata API endpoint is 100 milliseconds, -which can be overidden by setting the `AWS_METADATA_TIMEOUT` environment -variable. The variable expects a positive golang Time.Duration string, which is -a sequence of decimal numbers and a unit suffix; valid suffixes are `ns` -(nanoseconds), `us` (microseconds), `ms` (milliseconds), `s` (seconds), `m` -(minutes), and `h` (hours). Examples of valid inputs: `100ms`, `250ms`, `1s`, -`2.5s`, `2.5m`, `1m30s`. - -### Assume role +### Assume Role If provided with a role ARN, Terraform will attempt to assume this role using the supplied credentials. @@ -188,19 +171,19 @@ for more information about connecting to alternate AWS endpoints or AWS compatib * `max_retries` - (Optional) This is the maximum number of times an API call is retried, in the case where requests are being throttled or experiencing transient failures. The delay between the subsequent API - calls increases exponentially. + calls increases exponentially. If omitted, default value is `25`. -* `allowed_account_ids` - (Optional) List of allowed, white listed, AWS +* `allowed_account_ids` - (Optional) List of allowed AWS account IDs to prevent you from mistakenly using an incorrect one (and potentially end up destroying a live environment). Conflicts with `forbidden_account_ids`. -* `forbidden_account_ids` - (Optional) List of forbidden, blacklisted, +* `forbidden_account_ids` - (Optional) List of forbidden AWS account IDs to prevent you mistakenly using a wrong one (and potentially end up destroying a live environment). Conflicts with `allowed_account_ids`. -* `ignore_tags` - (Optional) Configuration block with resource tag settings to ignore across all resources handled by this provider (except `aws_autoscaling_group`) for situations where external systems are managing certain resource tags. Arguments to the configuration block are described below in the `ignore_tags` Configuration Block section. See the [Terraform multiple provider instances documentation](/docs/configuration/providers.html#alias-multiple-provider-instances) for more information about additional provider configurations. +* `ignore_tags` - (Optional) Configuration block with resource tag settings to ignore across all resources handled by this provider (except `aws_autoscaling_group` and any individual service tag resources such as `aws_ec2_tag`) for situations where external systems are managing certain resource tags. Arguments to the configuration block are described below in the `ignore_tags` Configuration Block section. See the [Terraform multiple provider instances documentation](/docs/configuration/providers.html#alias-multiple-provider-instances) for more information about additional provider configurations. * `insecure` - (Optional) Explicitly allow the provider to perform "insecure" SSL requests. If omitted, default value is `false`. @@ -222,47 +205,111 @@ for more information about connecting to alternate AWS endpoints or AWS compatib API, or metadata API. When set to `true` and not determined previously, returns an empty account ID when manually constructing ARN attributes with the following: - - [`aws_api_gateway_deployment` resource](/docs/providers/aws/r/api_gateway_deployment.html) - - [`aws_api_gateway_rest_api` resource](/docs/providers/aws/r/api_gateway_rest_api.html) - - [`aws_api_gateway_stage` resource](/docs/providers/aws/r/api_gateway_stage.html) - - [`aws_budgets_budget` resource](/docs/providers/aws/r/budgets_budget.html) - - [`aws_cognito_identity_pool` resource](/docs/providers/aws/r/cognito_identity_pool.html) - - [`aws_cognito_user_pool` resource](/docs/providers/aws/r/cognito_user_pool.html) - - [`aws_cognito_user_pools` data source](/docs/providers/aws/d/cognito_user_pools.html) - - [`aws_dms_replication_subnet_group` resource](/docs/providers/aws/r/dms_replication_subnet_group.html) - - [`aws_dx_connection` resource](/docs/providers/aws/r/dx_connection.html) - - [`aws_dx_hosted_private_virtual_interface_accepter` resource](/docs/providers/aws/r/dx_hosted_private_virtual_interface_accepter.html) - - [`aws_dx_hosted_private_virtual_interface` resource](/docs/providers/aws/r/dx_hosted_private_virtual_interface.html) - - [`aws_dx_hosted_public_virtual_interface_accepter` resource](/docs/providers/aws/r/dx_hosted_public_virtual_interface_accepter.html) - - [`aws_dx_hosted_public_virtual_interface` resource](/docs/providers/aws/r/dx_hosted_public_virtual_interface.html) - - [`aws_dx_lag` resource](/docs/providers/aws/r/dx_lag.html) - - [`aws_dx_private_virtual_interface` resource](/docs/providers/aws/r/dx_private_virtual_interface.html) - - [`aws_dx_public_virtual_interface` resource](/docs/providers/aws/r/dx_public_virtual_interface.html) - - [`aws_ebs_volume` data source](/docs/providers/aws/d/ebs_volume.html) - - [`aws_ecs_cluster` resource (import)](/docs/providers/aws/r/ecs_cluster.html) - - [`aws_ecs_service` resource (import)](/docs/providers/aws/r/ecs_service.html) - - [`aws_efs_file_system` data source](/docs/providers/aws/d/efs_file_system.html) - - [`aws_efs_file_system` resource](/docs/providers/aws/r/efs_file_system.html) - - [`aws_efs_mount_target` data source](/docs/providers/aws/d/efs_mount_target.html) - - [`aws_efs_mount_target` resource](/docs/providers/aws/r/efs_mount_target.html) - - [`aws_elasticache_cluster` data source](/docs/providers/aws/d/elasticache_cluster.html) - - [`aws_elasticache_cluster` resource](/docs/providers/aws/r/elasticache_cluster.html) - - [`aws_elb` resource](/docs/providers/aws/r/elb.html) - - [`aws_glue_crawler` resource](/docs/providers/aws/r/glue_crawler.html) - - [`aws_instance` data source](/docs/providers/aws/d/instance.html) - - [`aws_instance` resource](/docs/providers/aws/r/instance.html) - - [`aws_launch_template` resource](/docs/providers/aws/r/launch_template.html) - - [`aws_redshift_cluster` resource](/docs/providers/aws/r/redshift_cluster.html) - - [`aws_redshift_subnet_group` resource](/docs/providers/aws/r/redshift_subnet_group.html) - - [`aws_s3_account_public_access_block` resource](/docs/providers/aws/r/s3_account_public_access_block.html) - - [`aws_ses_domain_identity_verification` resource](/docs/providers/aws/r/ses_domain_identity_verification.html) - - [`aws_ses_domain_identity` resource](/docs/providers/aws/r/ses_domain_identity.html) - - [`aws_ssm_document` resource](/docs/providers/aws/r/ssm_document.html) - - [`aws_ssm_parameter` resource](/docs/providers/aws/r/ssm_parameter.html) - - [`aws_vpc` data source](/docs/providers/aws/d/vpc.html) - - [`aws_vpc` resource](/docs/providers/aws/r/vpc.html) - - [`aws_waf_ipset` resource](/docs/providers/aws/r/waf_ipset.html) - - [`aws_wafregional_ipset` resource](/docs/providers/aws/r/wafregional_ipset.html) + - [`aws_api_gateway_deployment` resource](/docs/providers/aws/r/api_gateway_deployment.html) + - [`aws_api_gateway_rest_api` resource](/docs/providers/aws/r/api_gateway_rest_api.html) + - [`aws_api_gateway_stage` resource](/docs/providers/aws/r/api_gateway_stage.html) + - [`aws_apigatewayv2_api` resource](/docs/providers/aws/r/apigatewayv2_api.html) + - [`aws_apigatewayv2_stage` resource](/docs/providers/aws/r/apigatewayv2_stage.html) + - [`aws_athena_workgroup` resource](/docs/providers/aws/r/athena_workgroup.html) + - [`aws_budgets_budget` resource](/docs/providers/aws/r/budgets_budget.html) + - [`aws_cognito_identity_pool` resource](/docs/providers/aws/r/cognito_identity_pool.html) + - [`aws_cognito_user_pool` resource](/docs/providers/aws/r/cognito_user_pool.html) + - [`aws_cognito_user_pools` data source](/docs/providers/aws/d/cognito_user_pools.html) + - [`aws_default_network_acl` resource](/docs/providers/aws/r/default_network_acl.html) + - [`aws_default_vpc_dhcp_options`](/docs/providers/aws/r/default_vpc_dhcp_options.html) + - [`aws_dms_event_subscription` resource](/docs/providers/aws/r/dms_event_subscription.html) + - [`aws_dms_replication_subnet_group` resource](/docs/providers/aws/r/dms_replication_subnet_group.html) + - [`aws_dx_connection` resource](/docs/providers/aws/r/dx_connection.html) + - [`aws_dx_hosted_private_virtual_interface_accepter` resource](/docs/providers/aws/r/dx_hosted_private_virtual_interface_accepter.html) + - [`aws_dx_hosted_private_virtual_interface` resource](/docs/providers/aws/r/dx_hosted_private_virtual_interface.html) + - [`aws_dx_hosted_public_virtual_interface_accepter` resource](/docs/providers/aws/r/dx_hosted_public_virtual_interface_accepter.html) + - [`aws_dx_hosted_public_virtual_interface` resource](/docs/providers/aws/r/dx_hosted_public_virtual_interface.html) + - [`aws_dx_hosted_transit_virtual_interface_accepter` resource](/docs/providers/aws/r/dx_hosted_transit_virtual_interface_accepter.html) + - [`aws_dx_hosted_transit_virtual_interface` resource](/docs/providers/aws/r/dx_hosted_transit_virtual_interface.html) + - [`aws_dx_lag` resource](/docs/providers/aws/r/dx_lag.html) + - [`aws_dx_private_virtual_interface` resource](/docs/providers/aws/r/dx_private_virtual_interface.html) + - [`aws_dx_public_virtual_interface` resource](/docs/providers/aws/r/dx_public_virtual_interface.html) + - [`aws_dx_transit_virtual_interface` resource](/docs/providers/aws/r/dx_transit_virtual_interface.html) + - [`aws_ebs_volume` data source](/docs/providers/aws/d/ebs_volume.html) + - [`aws_ec2_capacity_reservation` resource](/docs/providers/aws/r/ec2_capacity_reservation.html) + - [`aws_ec2_client_vpn_endpoint` resource](/docs/providers/aws/r/ec2_client_vpn_endpoint.html) + - [`aws_ec2_traffic_mirror_session` resource](/docs/providers/aws/r/ec2_traffic_mirror_session.html) + - [`aws_ec2_traffic_mirror_target` resource](/docs/providers/aws/r/ec2_traffic_mirror_target.html) + - [`aws_ecs_capacity_provider` resource (import)](/docs/providers/aws/r/ecs_capacity_provider.html) + - [`aws_ecs_cluster` resource (import)](/docs/providers/aws/r/ecs_cluster.html) + - [`aws_ecs_service` resource (import)](/docs/providers/aws/r/ecs_service.html) + - [`aws_customer_gateway` data source](/docs/providers/aws/d/customer_gateway.html) + - [`aws_customer_gateway` resource](/docs/providers/aws/r/customer_gateway.html) + - [`aws_efs_access_point` data source](/docs/providers/aws/d/efs_access_point.html) + - [`aws_efs_access_point` resource](/docs/providers/aws/r/efs_access_point.html) + - [`aws_efs_file_system` data source](/docs/providers/aws/d/efs_file_system.html) + - [`aws_efs_file_system` resource](/docs/providers/aws/r/efs_file_system.html) + - [`aws_efs_mount_target` data source](/docs/providers/aws/d/efs_mount_target.html) + - [`aws_efs_mount_target` resource](/docs/providers/aws/r/efs_mount_target.html) + - [`aws_elasticache_cluster` data source](/docs/providers/aws/d/elasticache_cluster.html) + - [`aws_elasticache_cluster` resource](/docs/providers/aws/r/elasticache_cluster.html) + - [`aws_elb` data source](/docs/providers/aws/d/elb.html) + - [`aws_elb` resource](/docs/providers/aws/r/elb.html) + - [`aws_flow_log` resource](/docs/providers/aws/r/flow_log.html) + - [`aws_glue_catalog_database` resource](/docs/providers/aws/r/glue_catalog_database.html) + - [`aws_glue_catalog_table` resource](/docs/providers/aws/r/glue_catalog_table.html) + - [`aws_glue_connection` resource](/docs/providers/aws/r/glue_connection.html) + - [`aws_glue_crawler` resource](/docs/providers/aws/r/glue_crawler.html) + - [`aws_glue_job` resource](/docs/providers/aws/r/glue_job.html) + - [`aws_glue_trigger` resource](/docs/providers/aws/r/glue_trigger.html) + - [`aws_guardduty_detector` resource](/docs/providers/aws/r/guardduty_detector.html) + - [`aws_guardduty_ipset` resource](/docs/providers/aws/r/guardduty_ipset.html) + - [`aws_guardduty_threatintelset` resource](/docs/providers/aws/r/guardduty_threatintelset.html) + - [`aws_instance` data source](/docs/providers/aws/d/instance.html) + - [`aws_instance` resource](/docs/providers/aws/r/instance.html) + - [`aws_internet_gateway` data source](/docs/providers/aws/d/internet_gateway.html) + - [`aws_internet_gateway` resource](/docs/providers/aws/r/internet_gateway.html) + - [`aws_key_pair` resource](/docs/providers/aws/r/key_pair.html) + - [`aws_launch_template` data source](/docs/providers/aws/d/launch_template.html) + - [`aws_launch_template` resource](/docs/providers/aws/r/launch_template.html) + - [`aws_network_acl` resource](/docs/providers/aws/r/network_acl.html) + - [`aws_placement_group` resource](/docs/providers/aws/r/placement_group.html) + - [`aws_redshift_cluster` resource](/docs/providers/aws/r/redshift_cluster.html) + - [`aws_redshift_event_subscription` resource](/docs/providers/aws/r/redshift_event_subscription.html) + - [`aws_redshift_parameter_group` resource](/docs/providers/aws/r/redshift_parameter_group.html) + - [`aws_redshift_snapshot_copy_grant` resource](/docs/providers/aws/r/redshift_snapshot_copy_grant.html) + - [`aws_redshift_snapshot_schedule` resource](/docs/providers/aws/r/redshift_snapshot_schedule.html) + - [`aws_redshift_subnet_group` resource](/docs/providers/aws/r/redshift_subnet_group.html) + - [`aws_s3_account_public_access_block` resource](/docs/providers/aws/r/s3_account_public_access_block.html) + - [`aws_ses_domain_identity` resource](/docs/providers/aws/r/ses_domain_identity.html) + - [`aws_ses_domain_identity_verification` resource](/docs/providers/aws/r/ses_domain_identity_verification.html) + - [`aws_ses_email_identity` resource](/docs/providers/aws/r/ses_email_identity.html) + - [`aws_ses_receipt_filter` resource](/docs/providers/aws/r/ses_receipt_filter.html) + - [`aws_ssm_document` data source](/docs/providers/aws/d/ssm_document.html) + - [`aws_ssm_document` resource](/docs/providers/aws/r/ssm_document.html) + - [`aws_ssm_parameter` data source](/docs/providers/aws/d/ssm_parameter.html) + - [`aws_ssm_parameter` resource](/docs/providers/aws/r/ssm_parameter.html) + - [`aws_vpc` data source](/docs/providers/aws/d/vpc.html) + - [`aws_vpc` resource](/docs/providers/aws/r/vpc.html) + - [`aws_vpc_dhcp_options` data source](/docs/providers/aws/d/vpc_dhcp_options.html) + - [`aws_vpc_dhcp_options` resource](/docs/providers/aws/r/vpc_dhcp_options.html) + - [`aws_vpc_endpoint` data source](/docs/providers/aws/d/vpc_endpoint.html) + - [`aws_vpc_endpoint` resource](/docs/providers/aws/r/vpc_endpoint.html) + - [`aws_vpc_endpoint_service` data source](/docs/providers/aws/d/vpc_endpoint_service.html) + - [`aws_vpc_endpoint_service` resource](/docs/providers/aws/r/vpc_endpoint_service.html) + - [`aws_vpn_connection` resource](/docs/providers/aws/r/vpn_connection.html) + - [`aws_vpn_gateway` data source](/docs/providers/aws/d/vpn_gateway.html) + - [`aws_vpn_gateway` resource](/docs/providers/aws/r/vpn_gateway.html) + - [`aws_waf_geo_match_set` resource](/docs/providers/aws/r/waf_geo_match_set.html) + - [`aws_waf_ipset` resource](/docs/providers/aws/r/waf_ipset.html) + - [`aws_waf_rate_based_rule` resource](/docs/providers/aws/r/waf_rate_based_rule.html) + - [`aws_waf_regex_match_set` resource](/docs/providers/aws/r/waf_regex_match_set.html) + - [`aws_waf_regex_pattern_set` resource](/docs/providers/aws/r/waf_regex_pattern_set.html) + - [`aws_wafregional_ipset` resource](/docs/providers/aws/r/wafregional_ipset.html) + - [`aws_wafregional_rate_based_rule` resource](/docs/providers/aws/r/wafregional_rate_based_rule.html) + - [`aws_wafregional_rule` resource](/docs/providers/aws/r/wafregional_rule.html) + - [`aws_wafregional_rule_group` resource](/docs/providers/aws/r/wafregional_rule_group.html) + - [`aws_wafregional_web_acl` resource](/docs/providers/aws/r/wafregional_web_acl.html) + - [`aws_waf_rule` resource](/docs/providers/aws/r/waf_rule.html) + - [`aws_waf_rule_group` resource](/docs/providers/aws/r/waf_rule_group.html) + - [`aws_waf_size_constraint_set` resource](/docs/providers/aws/r/waf_size_constraint_set.html) + - [`aws_waf_web_acl` resource](/docs/providers/aws/r/waf_web_acl.html) + - [`aws_waf_xss_match_set` resource](/docs/providers/aws/r/waf_xss_match_set.html) * `skip_metadata_api_check` - (Optional) Skip the AWS Metadata API check. Useful for AWS API implementations that do not have a metadata @@ -279,20 +326,16 @@ for more information about connecting to alternate AWS endpoints or AWS compatib ### assume_role Configuration Block -The `assume_role` configuration block supports the following arguments: - -* `role_arn` - (Required) The ARN of the role to assume. - -* `session_name` - (Optional) The session name to use when making the - AssumeRole call. - -* `external_id` - (Optional) The external ID to use when making the - AssumeRole call. +The `assume_role` configuration block supports the following optional arguments: -* `policy` - (Optional) A more restrictive policy to apply to the temporary credentials. -This gives you a way to further restrict the permissions for the resulting temporary -security credentials. You cannot use the passed policy to grant permissions that are -in excess of those allowed by the access policy of the role that is being assumed. +* `duration_seconds` - (Optional) Number of seconds to restrict the assume role session duration. +* `external_id` - (Optional) External identifier to use when assuming the role. +* `policy` - (Optional) IAM Policy JSON describing further restricting permissions for the IAM Role being assumed. +* `policy_arns` - (Optional) Set of Amazon Resource Names (ARNs) of IAM Policies describing further restricting permissions for the IAM Role being assumed. +* `role_arn` - (Optional) Amazon Resource Name (ARN) of the IAM Role to assume. +* `session_name` - (Optional) Session name to use when assuming the role. +* `tags` - (Optional) Map of assume role session tags. +* `transitive_tag_keys` - (Optional) Set of assume role session tag keys to pass to any subsequent sessions. ### ignore_tags Configuration Block @@ -319,15 +362,15 @@ in order to compare it with allowed or forbidden IDs. Approaches differ per authentication providers: - * EC2 instance w/ IAM Instance Profile - [Metadata API](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) +* EC2 instance w/ IAM Instance Profile - [Metadata API](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) is always used. Introduced in Terraform `0.6.16`. - * All other providers (environment variable, shared credentials file, ...) +* All other providers (environment variable, shared credentials file, ...) will try three approaches in the following order - * `iam:GetUser` - Typically useful for IAM Users. It also means + * `iam:GetUser` - Typically useful for IAM Users. It also means that each user needs to be privileged to call `iam:GetUser` for themselves. - * `sts:GetCallerIdentity` - _Should_ work for both IAM Users and federated IAM Roles, + * `sts:GetCallerIdentity` - _Should_ work for both IAM Users and federated IAM Roles, introduced in Terraform `0.6.16`. - * `iam:ListRoles` - This is specifically useful for IdP-federated profiles + * `iam:ListRoles` - This is specifically useful for IdP-federated profiles which cannot use `iam:GetUser`. It also means that each federated user need to be _assuming_ an IAM role which allows `iam:ListRoles`. Used in Terraform `0.6.16+`. diff --git a/website/docs/r/accessanalyzer_analyzer.html.markdown b/website/docs/r/accessanalyzer_analyzer.html.markdown index 935ef405760..82cef7d93f5 100644 --- a/website/docs/r/accessanalyzer_analyzer.html.markdown +++ b/website/docs/r/accessanalyzer_analyzer.html.markdown @@ -12,12 +12,29 @@ Manages an Access Analyzer Analyzer. More information can be found in the [Acces ## Example Usage +### Account Analyzer + ```hcl resource "aws_accessanalyzer_analyzer" "example" { analyzer_name = "example" } ``` +### Organization Analyzer + +```hcl +resource "aws_organizations_organization" "example" { + aws_service_access_principals = ["access-analyzer.amazonaws.com"] +} + +resource "aws_accessanalyzer_analyzer" "example" { + depends_on = [aws_organizations_organization.example] + + analyzer_name = "example" + type = "ORGANIZATION" +} +``` + ## Argument Reference The following arguments are required: @@ -27,7 +44,7 @@ The following arguments are required: The following arguments are optional: * `tags` - (Optional) Key-value map of resource tags. -* `type` - (Optional) Type of Analyzer. Valid value is currently only `ACCOUNT`. Defaults to `ACCOUNT`. +* `type` - (Optional) Type of Analyzer. Valid values are `ACCOUNT` or `ORGANIZATION`. Defaults to `ACCOUNT`. ## Attributes Reference diff --git a/website/docs/r/acm_certificate.html.markdown b/website/docs/r/acm_certificate.html.markdown index 70a13a08ea9..8d1346eabc9 100644 --- a/website/docs/r/acm_certificate.html.markdown +++ b/website/docs/r/acm_certificate.html.markdown @@ -16,7 +16,7 @@ This resource does not deal with validation of a certificate but can provide inp for other resources implementing the validation. It does not wait for a certificate to be issued. Use a [`aws_acm_certificate_validation`](acm_certificate_validation.html) resource for this. -Most commonly, this resource is used to together with [`aws_route53_record`](route53_record.html) and +Most commonly, this resource is used together with [`aws_route53_record`](route53_record.html) and [`aws_acm_certificate_validation`](acm_certificate_validation.html) to request a DNS validated certificate, deploy the required validation records and wait for validation to complete. @@ -54,7 +54,7 @@ resource "tls_private_key" "example" { resource "tls_self_signed_cert" "example" { key_algorithm = "RSA" - private_key_pem = "${tls_private_key.example.private_key_pem}" + private_key_pem = tls_private_key.example.private_key_pem subject { common_name = "example.com" @@ -71,8 +71,31 @@ resource "tls_self_signed_cert" "example" { } resource "aws_acm_certificate" "cert" { - private_key = "${tls_private_key.example.private_key_pem}" - certificate_body = "${tls_self_signed_cert.example.cert_pem}" + private_key = tls_private_key.example.private_key_pem + certificate_body = tls_self_signed_cert.example.cert_pem +} +``` + +### Referencing domain_validation_options With for_each Based Resources + +See the [`aws_acm_certificate_validation` resource](acm_certificate_validation.html) for a full example of performing DNS validation. + +```hcl +resource "aws_route53_record" "example" { + for_each = { + for dvo in aws_acm_certificate.example.domain_validation_options : dvo.domain_name => { + name = dvo.resource_record_name + record = dvo.resource_record_value + type = dvo.resource_record_type + } + } + + allow_overwrite = true + name = each.value.name + records = [each.value.record] + ttl = 60 + type = each.value.type + zone_id = aws_route53_zone.example.zone_id } ``` @@ -81,18 +104,18 @@ resource "aws_acm_certificate" "cert" { The following arguments are supported: * Creating an amazon issued certificate - * `domain_name` - (Required) A domain name for which the certificate should be issued - * `subject_alternative_names` - (Optional) A list of domains that should be SANs in the issued certificate - * `validation_method` - (Required) Which method to use for validation. `DNS` or `EMAIL` are valid, `NONE` can be used for certificates that were imported into ACM and then into Terraform. - * `options` - (Optional) Configuration block used to set certificate options. Detailed below. + * `domain_name` - (Required) A domain name for which the certificate should be issued + * `subject_alternative_names` - (Optional) Set of domains that should be SANs in the issued certificate. To remove all elements of a previously configured list, set this value equal to an empty list (`[]`) or use the [`terraform taint` command](https://www.terraform.io/docs/commands/taint.html) to trigger recreation. + * `validation_method` - (Required) Which method to use for validation. `DNS` or `EMAIL` are valid, `NONE` can be used for certificates that were imported into ACM and then into Terraform. + * `options` - (Optional) Configuration block used to set certificate options. Detailed below. * Importing an existing certificate - * `private_key` - (Required) The certificate's PEM-formatted private key - * `certificate_body` - (Required) The certificate's PEM-formatted public key - * `certificate_chain` - (Optional) The certificate's PEM-formatted chain + * `private_key` - (Required) The certificate's PEM-formatted private key + * `certificate_body` - (Required) The certificate's PEM-formatted public key + * `certificate_chain` - (Optional) The certificate's PEM-formatted chain * Creating a private CA issued certificate - * `domain_name` - (Required) A domain name for which the certificate should be issued - * `certificate_authority_arn` - (Required) ARN of an ACMPCA - * `subject_alternative_names` - (Optional) A list of domains that should be SANs in the issued certificate + * `domain_name` - (Required) A domain name for which the certificate should be issued + * `certificate_authority_arn` - (Required) ARN of an ACMPCA + * `subject_alternative_names` - (Optional) Set of domains that should be SANs in the issued certificate. To remove all elements of a previously configured list, set this value equal to an empty list (`[]`) or use the [`terraform taint` command](https://www.terraform.io/docs/commands/taint.html) to trigger recreation. * `tags` - (Optional) A map of tags to assign to the resource. ## options Configuration Block @@ -108,7 +131,8 @@ In addition to all arguments above, the following attributes are exported: * `id` - The ARN of the certificate * `arn` - The ARN of the certificate * `domain_name` - The domain name for which the certificate is issued -* `domain_validation_options` - A list of attributes to feed into other resources to complete certificate validation. Can have more than one element, e.g. if SANs are defined. Only set if `DNS`-validation was used. +* `domain_validation_options` - Set of domain validation objects which can be used to complete certificate validation. Can have more than one element, e.g. if SANs are defined. Only set if `DNS`-validation was used. +* `status` - Status of the certificate. * `validation_emails` - A list of addresses that received a validation E-Mail. Only set if `EMAIL`-validation was used. Domain validation objects export the following attributes: diff --git a/website/docs/r/acm_certificate_validation.html.markdown b/website/docs/r/acm_certificate_validation.html.markdown index 8cefaa487c5..1cd5fdb019b 100644 --- a/website/docs/r/acm_certificate_validation.html.markdown +++ b/website/docs/r/acm_certificate_validation.html.markdown @@ -23,91 +23,91 @@ deploy the required validation records and wait for validation to complete. ### DNS Validation with Route 53 ```hcl -resource "aws_acm_certificate" "cert" { +resource "aws_acm_certificate" "example" { domain_name = "example.com" validation_method = "DNS" } -data "aws_route53_zone" "zone" { - name = "example.com." +data "aws_route53_zone" "example" { + name = "example.com" private_zone = false } -resource "aws_route53_record" "cert_validation" { - name = "${aws_acm_certificate.cert.domain_validation_options.0.resource_record_name}" - type = "${aws_acm_certificate.cert.domain_validation_options.0.resource_record_type}" - zone_id = "${data.aws_route53_zone.zone.zone_id}" - records = ["${aws_acm_certificate.cert.domain_validation_options.0.resource_record_value}"] - ttl = 60 +resource "aws_route53_record" "example" { + for_each = { + for dvo in aws_acm_certificate.example.domain_validation_options : dvo.domain_name => { + name = dvo.resource_record_name + record = dvo.resource_record_value + type = dvo.resource_record_type + } + } + + allow_overwrite = true + name = each.value.name + records = [each.value.record] + ttl = 60 + type = each.value.type + zone_id = data.aws_route53_zone.example.zone_id } -resource "aws_acm_certificate_validation" "cert" { - certificate_arn = "${aws_acm_certificate.cert.arn}" - validation_record_fqdns = ["${aws_route53_record.cert_validation.fqdn}"] +resource "aws_acm_certificate_validation" "example" { + certificate_arn = aws_acm_certificate.example.arn + validation_record_fqdns = [for record in aws_route53_record.example : record.fqdn] } -resource "aws_lb_listener" "front_end" { - # [...] - certificate_arn = "${aws_acm_certificate_validation.cert.certificate_arn}" +resource "aws_lb_listener" "example" { + # ... other configuration ... + + certificate_arn = aws_acm_certificate_validation.example.certificate_arn } ``` ### Alternative Domains DNS Validation with Route 53 ```hcl -resource "aws_acm_certificate" "cert" { +resource "aws_acm_certificate" "example" { domain_name = "example.com" subject_alternative_names = ["www.example.com", "example.org"] validation_method = "DNS" } -data "aws_route53_zone" "zone" { - name = "example.com." +data "aws_route53_zone" "example_com" { + name = "example.com" private_zone = false } -data "aws_route53_zone" "zone_alt" { - name = "example.org." +data "aws_route53_zone" "example_org" { + name = "example.org" private_zone = false } -resource "aws_route53_record" "cert_validation" { - name = "${aws_acm_certificate.cert.domain_validation_options.0.resource_record_name}" - type = "${aws_acm_certificate.cert.domain_validation_options.0.resource_record_type}" - zone_id = "${data.aws_route53_zone.zone.zone_id}" - records = ["${aws_acm_certificate.cert.domain_validation_options.0.resource_record_value}"] - ttl = 60 -} - -resource "aws_route53_record" "cert_validation_alt1" { - name = "${aws_acm_certificate.cert.domain_validation_options.1.resource_record_name}" - type = "${aws_acm_certificate.cert.domain_validation_options.1.resource_record_type}" - zone_id = "${data.aws_route53_zone.zone.zone_id}" - records = ["${aws_acm_certificate.cert.domain_validation_options.1.resource_record_value}"] - ttl = 60 +resource "aws_route53_record" "example" { + for_each = { + for dvo in aws_acm_certificate.example.domain_validation_options : dvo.domain_name => { + name = dvo.resource_record_name + record = dvo.resource_record_value + type = dvo.resource_record_type + zone_id = dvo.domain_name == "example.org" ? data.aws_route53_zone.example_org.zone_id : data.aws_route53_zone.example_com.zone_id + } + } + + allow_overwrite = true + name = each.value.name + records = [each.value.record] + ttl = 60 + type = each.value.type + zone_id = each.value.zone_id } -resource "aws_route53_record" "cert_validation_alt2" { - name = "${aws_acm_certificate.cert.domain_validation_options.2.resource_record_name}" - type = "${aws_acm_certificate.cert.domain_validation_options.2.resource_record_type}" - zone_id = "${data.aws_route53_zone.zone_alt.zone_id}" - records = ["${aws_acm_certificate.cert.domain_validation_options.2.resource_record_value}"] - ttl = 60 +resource "aws_acm_certificate_validation" "example" { + certificate_arn = aws_acm_certificate.example.arn + validation_record_fqdns = [for record in aws_route53_record.example : record.fqdn] } -resource "aws_acm_certificate_validation" "cert" { - certificate_arn = "${aws_acm_certificate.cert.arn}" - - validation_record_fqdns = [ - "${aws_route53_record.cert_validation.fqdn}", - "${aws_route53_record.cert_validation_alt1.fqdn}", - "${aws_route53_record.cert_validation_alt2.fqdn}", - ] -} +resource "aws_lb_listener" "example" { + # ... other configuration ... -resource "aws_lb_listener" "front_end" { - # [...] - certificate_arn = "${aws_acm_certificate_validation.cert.certificate_arn}" + certificate_arn = aws_acm_certificate_validation.example.certificate_arn } ``` @@ -116,13 +116,13 @@ resource "aws_lb_listener" "front_end" { In this situation, the resource is simply a waiter for manual email approval of ACM certificates. ```hcl -resource "aws_acm_certificate" "cert" { +resource "aws_acm_certificate" "example" { domain_name = "example.com" validation_method = "EMAIL" } -resource "aws_acm_certificate_validation" "cert" { - certificate_arn = "${aws_acm_certificate.cert.arn}" +resource "aws_acm_certificate_validation" "example" { + certificate_arn = aws_acm_certificate.example.arn } ``` diff --git a/website/docs/r/acmpca_certificate_authority.html.markdown b/website/docs/r/acmpca_certificate_authority.html.markdown index 14c95de2121..1f4674738c9 100644 --- a/website/docs/r/acmpca_certificate_authority.html.markdown +++ b/website/docs/r/acmpca_certificate_authority.html.markdown @@ -48,7 +48,7 @@ data "aws_iam_policy_document" "acmpca_bucket_access" { ] resources = [ - "${aws_s3_bucket.example.arn}", + aws_s3_bucket.example.arn, "${aws_s3_bucket.example.arn}/*", ] @@ -60,8 +60,8 @@ data "aws_iam_policy_document" "acmpca_bucket_access" { } resource "aws_s3_bucket_policy" "example" { - bucket = "${aws_s3_bucket.example.id}" - policy = "${data.aws_iam_policy_document.acmpca_bucket_access.json}" + bucket = aws_s3_bucket.example.id + policy = data.aws_iam_policy_document.acmpca_bucket_access.json } resource "aws_acmpca_certificate_authority" "example" { @@ -79,11 +79,11 @@ resource "aws_acmpca_certificate_authority" "example" { custom_cname = "crl.example.com" enabled = true expiration_in_days = 7 - s3_bucket_name = "${aws_s3_bucket.example.id}" + s3_bucket_name = aws_s3_bucket.example.id } } - depends_on = ["aws_s3_bucket_policy.example"] + depends_on = [aws_s3_bucket_policy.example] } ``` diff --git a/website/docs/r/ami.html.markdown b/website/docs/r/ami.html.markdown index ca264bd9578..3eacdd30a62 100644 --- a/website/docs/r/ami.html.markdown +++ b/website/docs/r/ami.html.markdown @@ -108,6 +108,7 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d In addition to all arguments above, the following attributes are exported: +* `arn` - The ARN of the AMI. * `id` - The ID of the created AMI. * `root_snapshot_id` - The Snapshot ID for the root volume (for EBS-backed AMIs) diff --git a/website/docs/r/ami_copy.html.markdown b/website/docs/r/ami_copy.html.markdown index 2eeeee68518..a8b167c44bb 100644 --- a/website/docs/r/ami_copy.html.markdown +++ b/website/docs/r/ami_copy.html.markdown @@ -62,6 +62,7 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d In addition to all arguments above, the following attributes are exported: +* `arn` - The ARN of the AMI. * `id` - The ID of the created AMI. This resource also exports a full set of attributes corresponding to the arguments of the diff --git a/website/docs/r/ami_from_instance.html.markdown b/website/docs/r/ami_from_instance.html.markdown index 0a67c04475e..e85be3adc75 100644 --- a/website/docs/r/ami_from_instance.html.markdown +++ b/website/docs/r/ami_from_instance.html.markdown @@ -59,6 +59,7 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d In addition to all arguments above, the following attributes are exported: +* `arn` - The ARN of the AMI. * `id` - The ID of the created AMI. This resource also exports a full set of attributes corresponding to the arguments of the diff --git a/website/docs/r/ami_launch_permission.html.markdown b/website/docs/r/ami_launch_permission.html.markdown index 3af6fef0214..a55d9a87e0c 100644 --- a/website/docs/r/ami_launch_permission.html.markdown +++ b/website/docs/r/ami_launch_permission.html.markdown @@ -23,14 +23,14 @@ resource "aws_ami_launch_permission" "example" { The following arguments are supported: - * `image_id` - (required) A region-unique name for the AMI. - * `account_id` - (required) An AWS Account ID to add launch permissions. +* `image_id` - (required) A region-unique name for the AMI. +* `account_id` - (required) An AWS Account ID to add launch permissions. ## Attributes Reference In addition to all arguments above, the following attributes are exported: - * `id` - A combination of "`image_id`-`account_id`". +* `id` - A combination of "`image_id`-`account_id`". ## Import diff --git a/website/docs/r/api_gateway_account.html.markdown b/website/docs/r/api_gateway_account.html.markdown index c23075c5c0f..263591171a8 100644 --- a/website/docs/r/api_gateway_account.html.markdown +++ b/website/docs/r/api_gateway_account.html.markdown @@ -16,7 +16,7 @@ Provides a settings of an API Gateway Account. Settings is applied region-wide p ```hcl resource "aws_api_gateway_account" "demo" { - cloudwatch_role_arn = "${aws_iam_role.cloudwatch.arn}" + cloudwatch_role_arn = aws_iam_role.cloudwatch.arn } resource "aws_iam_role" "cloudwatch" { @@ -41,7 +41,7 @@ EOF resource "aws_iam_role_policy" "cloudwatch" { name = "default" - role = "${aws_iam_role.cloudwatch.id}" + role = aws_iam_role.cloudwatch.id policy = < **NOTE on AutoScaling Groups and ASG Attachments:** Terraform currently provides both a standalone ASG Attachment resource (describing an ASG attached to -an ELB), and an [AutoScaling Group resource](autoscaling_group.html) with -`load_balancers` defined in-line. At this time you cannot use an ASG with in-line -load balancers in conjunction with an ASG Attachment resource. Doing so will cause a -conflict and will overwrite attachments. +an ELB or ALB), and an [AutoScaling Group resource](autoscaling_group.html) with +`load_balancers` and `target_group_arns` defined in-line. At this time you can use an ASG with in-line +`load balancers` or `target_group_arns` in conjunction with an ASG Attachment resource, however, to prevent +unintended resource updates, the `aws_autoscaling_group` resource must be configured +to ignore changes to the `load_balancers` and `target_group_arns` arguments within a [`lifecycle` configuration block](/docs/configuration/resources.html#lifecycle-lifecycle-customizations). ## Example Usage ```hcl # Create a new load balancer attachment resource "aws_autoscaling_attachment" "asg_attachment_bar" { - autoscaling_group_name = "${aws_autoscaling_group.asg.id}" - elb = "${aws_elb.bar.id}" + autoscaling_group_name = aws_autoscaling_group.asg.id + elb = aws_elb.bar.id } ``` ```hcl # Create a new ALB Target Group attachment resource "aws_autoscaling_attachment" "asg_attachment_bar" { - autoscaling_group_name = "${aws_autoscaling_group.asg.id}" - alb_target_group_arn = "${aws_alb_target_group.test.arn}" + autoscaling_group_name = aws_autoscaling_group.asg.id + alb_target_group_arn = aws_alb_target_group.test.arn +} +``` + +## With An AutoScaling Group Resource + +```hcl +resource "aws_autoscaling_group" "asg" { + # ... other configuration ... + + lifecycle { + ignore_changes = [load_balancers, target_group_arns] + } +} + +resource "aws_autoscaling_attachment" "asg_attachment_bar" { + autoscaling_group_name = aws_autoscaling_group.asg.id + elb = aws_elb.test.id } ``` diff --git a/website/docs/r/autoscaling_group.html.markdown b/website/docs/r/autoscaling_group.html.markdown index 2d4360c9ee2..68c8332738a 100644 --- a/website/docs/r/autoscaling_group.html.markdown +++ b/website/docs/r/autoscaling_group.html.markdown @@ -28,9 +28,9 @@ resource "aws_autoscaling_group" "bar" { health_check_type = "ELB" desired_capacity = 4 force_delete = true - placement_group = "${aws_placement_group.test.id}" - launch_configuration = "${aws_launch_configuration.foobar.name}" - vpc_zone_identifier = ["${aws_subnet.example1.id}", "${aws_subnet.example2.id}"] + placement_group = aws_placement_group.test.id + launch_configuration = aws_launch_configuration.foobar.name + vpc_zone_identifier = [aws_subnet.example1.id, aws_subnet.example2.id] initial_lifecycle_hook { name = "foobar" @@ -82,7 +82,7 @@ resource "aws_autoscaling_group" "bar" { min_size = 1 launch_template { - id = "${aws_launch_template.foobar.id}" + id = aws_launch_template.foobar.id version = "$Latest" } } @@ -93,7 +93,7 @@ resource "aws_autoscaling_group" "bar" { ```hcl resource "aws_launch_template" "example" { name_prefix = "example" - image_id = "${data.aws_ami.example.id}" + image_id = data.aws_ami.example.id instance_type = "c5.large" } @@ -106,7 +106,7 @@ resource "aws_autoscaling_group" "example" { mixed_instances_policy { launch_template { launch_template_specification { - launch_template_id = "${aws_launch_template.example.id}" + launch_template_id = aws_launch_template.example.id } override { @@ -145,16 +145,24 @@ resource "aws_autoscaling_group" "bar" { name = "foobar3-terraform-test" max_size = 5 min_size = 2 - launch_configuration = "${aws_launch_configuration.foobar.name}" - vpc_zone_identifier = ["${aws_subnet.example1.id}", "${aws_subnet.example2.id}"] - - tags = ["${concat( - list( - map("key", "interpolation1", "value", "value3", "propagate_at_launch", true), - map("key", "interpolation2", "value", "value4", "propagate_at_launch", true) - ), - var.extra_tags) - }"] + launch_configuration = aws_launch_configuration.foobar.name + vpc_zone_identifier = [aws_subnet.example1.id, aws_subnet.example2.id] + + tags = concat( + [ + { + "key" = "interpolation1" + "value" = "value3" + "propagate_at_launch" = true + }, + { + "key" = "interpolation2" + "value" = "value4" + "propagate_at_launch" = true + }, + ], + var.extra_tags, + ) } ``` @@ -168,7 +176,7 @@ The following arguments are supported: * `max_size` - (Required) The maximum size of the auto scale group. * `min_size` - (Required) The minimum size of the auto scale group. (See also [Waiting for Capacity](#waiting-for-capacity) below.) -* `availability_zones` - (Required only for EC2-Classic) A list of one or more availability zones for the group. This parameter should not be specified when using `vpc_zone_identifier`. +* `availability_zones` - (Optional) A list of one or more availability zones for the group. Used for EC2-Classic and default subnets when not specified with `vpc_zone_identifier` argument. Conflicts with `vpc_zone_identifier`. * `default_cooldown` - (Optional) The amount of time, in seconds, after a scaling activity completes before another scaling activity can start. * `launch_configuration` - (Optional) The name of the launch configuration to use. * `launch_template` - (Optional) Nested argument with Launch template specification to use to launch instances. Defined below. @@ -192,13 +200,13 @@ The following arguments are supported: behavior and potentially leaves resources dangling. * `load_balancers` (Optional) A list of elastic load balancer names to add to the autoscaling group names. Only valid for classic load balancers. For ALBs, use `target_group_arns` instead. -* `vpc_zone_identifier` (Optional) A list of subnet IDs to launch resources in. -* `target_group_arns` (Optional) A list of `aws_alb_target_group` ARNs, for use with Application or Network Load Balancing. +* `vpc_zone_identifier` (Optional) A list of subnet IDs to launch resources in. Subnets automatically determine which availability zones the group will reside. Conflicts with `availability_zones`. +* `target_group_arns` (Optional) A set of `aws_alb_target_group` ARNs, for use with Application or Network Load Balancing. * `termination_policies` (Optional) A list of policies to decide how the instances in the auto scale group should be terminated. The allowed values are `OldestInstance`, `NewestInstance`, `OldestLaunchConfiguration`, `ClosestToNextInstanceHour`, `OldestLaunchTemplate`, `AllocationStrategy`, `Default`. * `suspended_processes` - (Optional) A list of processes to suspend for the AutoScaling Group. The allowed values are `Launch`, `Terminate`, `HealthCheck`, `ReplaceUnhealthy`, `AZRebalance`, `AlarmNotification`, `ScheduledActions`, `AddToLoadBalancer`. Note that if you suspend either the `Launch` or `Terminate` process types, it can prevent your autoscaling group from functioning properly. -* `tag` (Optional) A list of tag blocks. Tags documented below. -* `tags` (Optional) A list of tag blocks (maps). Tags documented below. +* `tag` (Optional) Configuration block(s) containing resource tags. Conflicts with `tags`. Documented below. +* `tags` (Optional) Set of maps containing resource tags. Conflicts with `tag`. Documented below. * `placement_group` (Optional) The name of the placement group into which you'll launch your instances, if any. * `metrics_granularity` - (Optional) The granularity to associate with the metrics to collect. The only valid value is `1Minute`. Default is `1Minute`. * `enabled_metrics` - (Optional) A list of metrics to collect. The allowed values are `GroupDesiredCapacity`, `GroupInServiceCapacity`, `GroupPendingCapacity`, `GroupMinSize`, `GroupMaxSize`, `GroupInServiceInstances`, `GroupPendingInstances`, `GroupStandbyInstances`, `GroupStandbyCapacity`, `GroupTerminatingCapacity`, `GroupTerminatingInstances`, `GroupTotalCapacity`, `GroupTotalInstances`. @@ -217,7 +225,7 @@ Note that if you suspend either the `Launch` or `Terminate` process types, it ca precedence over `min_elb_capacity` behavior.) (See also [Waiting for Capacity](#waiting-for-capacity) below.) * `protect_from_scale_in` (Optional) Allows setting instance protection. The - autoscaling group will not select instances with this setting for terminination + autoscaling group will not select instances with this setting for termination during scale in events. * `service_linked_role_arn` (Optional) The ARN of the service-linked role that the ASG will use to call other AWS services * `max_instance_lifetime` (Optional) The maximum amount of time, in seconds, that an instance can be in service, values must be either equal to 0 or between 604800 and 31536000 seconds. @@ -286,7 +294,7 @@ Alternatively the `tags` attributes can be used, which accepts a list of maps co This allows the construction of dynamic lists of tags which is not possible using the single `tag` attribute. `tag` and `tags` are mutually exclusive, only one of them can be specified. -~> **NOTE:** Other AWS APIs may automatically add special tags to their associated Auto Scaling Group for management purposes, such as ECS Capacity Providers adding the `AmazonECSManaged` tag. To ignore the removal of these automatic tags, see the [`ignore_tags` provider configuration](https://www.terraform.io/docs/providers/aws/index.html#ignore_tags) or the [`ignore_changes` lifecycle argument for Terraform resources](https://www.terraform.io/docs/configuration/resources.html#ignore_changes). +~> **NOTE:** Other AWS APIs may automatically add special tags to their associated Auto Scaling Group for management purposes, such as ECS Capacity Providers adding the `AmazonECSManaged` tag. These generally should be included in the configuration so Terraform does not attempt to remove them and so if the `min_size` was greater than zero on creation, that these tag(s) are applied to any initial EC2 Instances in the Auto Scaling Group. If these tag(s) were missing in the Auto Scaling Group configuration on creation, affected EC2 Instances missing the tags may require manual intervention of adding the tags to ensure they work properly with the other AWS service. ## Attributes Reference @@ -304,10 +312,6 @@ In addition to all arguments above, the following attributes are exported: * `desired_capacity` -The number of Amazon EC2 instances that should be running in the group. * `launch_configuration` - The launch configuration of the autoscale group * `vpc_zone_identifier` (Optional) - The VPC zone identifier -* `load_balancers` (Optional) The load balancer names associated with the - autoscaling group. -* `target_group_arns` (Optional) list of Target Group ARNs that apply to this -AutoScaling Group ~> **NOTE:** When using `ELB` as the `health_check_type`, `health_check_grace_period` is required. diff --git a/website/docs/r/autoscaling_lifecycle_hook.html.markdown b/website/docs/r/autoscaling_lifecycle_hook.html.markdown index 885388f1159..c981b134bff 100644 --- a/website/docs/r/autoscaling_lifecycle_hook.html.markdown +++ b/website/docs/r/autoscaling_lifecycle_hook.html.markdown @@ -40,7 +40,7 @@ resource "aws_autoscaling_group" "foobar" { resource "aws_autoscaling_lifecycle_hook" "foobar" { name = "foobar" - autoscaling_group_name = "${aws_autoscaling_group.foobar.name}" + autoscaling_group_name = aws_autoscaling_group.foobar.name default_result = "CONTINUE" heartbeat_timeout = 2000 lifecycle_transition = "autoscaling:EC2_INSTANCE_LAUNCHING" @@ -74,5 +74,5 @@ The following arguments are supported: AutoScaling Lifecycle Hooks can be imported using the role autoscaling_group_name and name separated by `/`. ``` -$ terraform import aws_aws_autoscaling_lifecycle_hook.test-lifecycle-hook asg-name/lifecycle-hook-name +$ terraform import aws_autoscaling_lifecycle_hook.test-lifecycle-hook asg-name/lifecycle-hook-name ``` diff --git a/website/docs/r/autoscaling_notification.html.markdown b/website/docs/r/autoscaling_notification.html.markdown index 860d4bcaf56..f142a051bb5 100644 --- a/website/docs/r/autoscaling_notification.html.markdown +++ b/website/docs/r/autoscaling_notification.html.markdown @@ -19,8 +19,8 @@ Basic usage: ```hcl resource "aws_autoscaling_notification" "example_notifications" { group_names = [ - "${aws_autoscaling_group.bar.name}", - "${aws_autoscaling_group.foo.name}", + aws_autoscaling_group.bar.name, + aws_autoscaling_group.foo.name, ] notifications = [ @@ -30,7 +30,7 @@ resource "aws_autoscaling_notification" "example_notifications" { "autoscaling:EC2_INSTANCE_TERMINATE_ERROR", ] - topic_arn = "${aws_sns_topic.example.arn}" + topic_arn = aws_sns_topic.example.arn } resource "aws_sns_topic" "example" { diff --git a/website/docs/r/autoscaling_policy.html.markdown b/website/docs/r/autoscaling_policy.html.markdown index c2557e9fbaa..aa913b2d608 100644 --- a/website/docs/r/autoscaling_policy.html.markdown +++ b/website/docs/r/autoscaling_policy.html.markdown @@ -24,7 +24,7 @@ resource "aws_autoscaling_policy" "bat" { scaling_adjustment = 4 adjustment_type = "ChangeInCapacity" cooldown = 300 - autoscaling_group_name = "${aws_autoscaling_group.bar.name}" + autoscaling_group_name = aws_autoscaling_group.bar.name } resource "aws_autoscaling_group" "bar" { @@ -35,7 +35,7 @@ resource "aws_autoscaling_group" "bar" { health_check_grace_period = 300 health_check_type = "ELB" force_delete = true - launch_configuration = "${aws_launch_configuration.foo.name}" + launch_configuration = aws_launch_configuration.foo.name } ``` @@ -61,16 +61,20 @@ The following arguments are only available to "StepScaling" type policies: group scaling. These have the following structure: ```hcl -step_adjustment { - scaling_adjustment = -1 - metric_interval_lower_bound = 1.0 - metric_interval_upper_bound = 2.0 -} +resource "aws_autoscaling_policy" "example" { + # ... other configuration ... + + step_adjustment { + scaling_adjustment = -1 + metric_interval_lower_bound = 1.0 + metric_interval_upper_bound = 2.0 + } -step_adjustment { - scaling_adjustment = 1 - metric_interval_lower_bound = 2.0 - metric_interval_upper_bound = 3.0 + step_adjustment { + scaling_adjustment = 1 + metric_interval_lower_bound = 2.0 + metric_interval_upper_bound = 3.0 + } } ``` @@ -92,27 +96,31 @@ The following arguments are only available to "TargetTrackingScaling" type polic * `target_tracking_configuration` - (Optional) A target tracking policy. These have the following structure: ```hcl -target_tracking_configuration { - predefined_metric_specification { - predefined_metric_type = "ASGAverageCPUUtilization" +resource "aws_autoscaling_policy" "example" { + # ... other configuration ... + + target_tracking_configuration { + predefined_metric_specification { + predefined_metric_type = "ASGAverageCPUUtilization" + } + + target_value = 40.0 } - target_value = 40.0 -} + target_tracking_configuration { + customized_metric_specification { + metric_dimension { + name = "fuga" + value = "fuga" + } -target_tracking_configuration { - customized_metric_specification { - metric_dimension { - name = "fuga" - value = "fuga" + metric_name = "hoge" + namespace = "hoge" + statistic = "Average" } - metric_name = "hoge" - namespace = "hoge" - statistic = "Average" + target_value = 40.0 } - - target_value = 40.0 } ``` diff --git a/website/docs/r/autoscaling_schedule.html.markdown b/website/docs/r/autoscaling_schedule.html.markdown index 01b94d192ed..639c9073611 100644 --- a/website/docs/r/autoscaling_schedule.html.markdown +++ b/website/docs/r/autoscaling_schedule.html.markdown @@ -31,7 +31,7 @@ resource "aws_autoscaling_schedule" "foobar" { desired_capacity = 0 start_time = "2016-12-11T18:00:00Z" end_time = "2016-12-12T06:00:00Z" - autoscaling_group_name = "${aws_autoscaling_group.foobar.name}" + autoscaling_group_name = aws_autoscaling_group.foobar.name } ``` diff --git a/website/docs/r/backup_plan.html.markdown b/website/docs/r/backup_plan.html.markdown index da429e24624..420240f9a84 100644 --- a/website/docs/r/backup_plan.html.markdown +++ b/website/docs/r/backup_plan.html.markdown @@ -18,7 +18,7 @@ resource "aws_backup_plan" "example" { rule { rule_name = "tf_example_backup_rule" - target_vault_name = "${aws_backup_vault.test.name}" + target_vault_name = aws_backup_vault.test.name schedule = "cron(0 12 * * ? *)" } } diff --git a/website/docs/r/backup_selection.html.markdown b/website/docs/r/backup_selection.html.markdown index 5fda87e85f1..c45e47dc165 100644 --- a/website/docs/r/backup_selection.html.markdown +++ b/website/docs/r/backup_selection.html.markdown @@ -39,13 +39,13 @@ POLICY resource "aws_iam_role_policy_attachment" "example" { policy_arn = "arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup" - role = "${aws_iam_role.example.name}" + role = aws_iam_role.example.name } resource "aws_backup_selection" "example" { # ... other configuration ... - iam_role_arn = "${aws_iam_role.example.arn}" + iam_role_arn = aws_iam_role.example.arn } ``` @@ -53,9 +53,9 @@ resource "aws_backup_selection" "example" { ```hcl resource "aws_backup_selection" "example" { - iam_role_arn = "${aws_iam_role.example.arn}" + iam_role_arn = aws_iam_role.example.arn name = "tf_example_backup_selection" - plan_id = "${aws_backup_plan.example.id}" + plan_id = aws_backup_plan.example.id selection_tag { type = "STRINGEQUALS" @@ -69,14 +69,14 @@ resource "aws_backup_selection" "example" { ```hcl resource "aws_backup_selection" "example" { - iam_role_arn = "${aws_iam_role.example.arn}" + iam_role_arn = aws_iam_role.example.arn name = "tf_example_backup_selection" - plan_id = "${aws_backup_plan.example.id}" + plan_id = aws_backup_plan.example.id resources = [ - "${aws_db_instance.example.arn}", - "${aws_ebs_volume.example.arn}", - "${aws_efs_file_system.example.arn}", + aws_db_instance.example.arn, + aws_ebs_volume.example.arn, + aws_efs_file_system.example.arn, ] } ``` diff --git a/website/docs/r/backup_vault.html.markdown b/website/docs/r/backup_vault.html.markdown index 0473854ba0a..a278991de51 100644 --- a/website/docs/r/backup_vault.html.markdown +++ b/website/docs/r/backup_vault.html.markdown @@ -15,7 +15,7 @@ Provides an AWS Backup vault resource. ```hcl resource "aws_backup_vault" "example" { name = "example_backup_vault" - kms_key_arn = "${aws_kms_key.example.arn}" + kms_key_arn = aws_kms_key.example.arn } ``` diff --git a/website/docs/r/batch_compute_environment.html.markdown b/website/docs/r/batch_compute_environment.html.markdown index 447c2706436..22e18d22478 100644 --- a/website/docs/r/batch_compute_environment.html.markdown +++ b/website/docs/r/batch_compute_environment.html.markdown @@ -39,13 +39,13 @@ EOF } resource "aws_iam_role_policy_attachment" "ecs_instance_role" { - role = "${aws_iam_role.ecs_instance_role.name}" + role = aws_iam_role.ecs_instance_role.name policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role" } resource "aws_iam_instance_profile" "ecs_instance_role" { name = "ecs_instance_role" - role = "${aws_iam_role.ecs_instance_role.name}" + role = aws_iam_role.ecs_instance_role.name } resource "aws_iam_role" "aws_batch_service_role" { @@ -68,7 +68,7 @@ EOF } resource "aws_iam_role_policy_attachment" "aws_batch_service_role" { - role = "${aws_iam_role.aws_batch_service_role.name}" + role = aws_iam_role.aws_batch_service_role.name policy_arn = "arn:aws:iam::aws:policy/service-role/AWSBatchServiceRole" } @@ -88,7 +88,7 @@ resource "aws_vpc" "sample" { } resource "aws_subnet" "sample" { - vpc_id = "${aws_vpc.sample.id}" + vpc_id = aws_vpc.sample.id cidr_block = "10.1.1.0/24" } @@ -96,7 +96,7 @@ resource "aws_batch_compute_environment" "sample" { compute_environment_name = "sample" compute_resources { - instance_role = "${aws_iam_instance_profile.ecs_instance_role.arn}" + instance_role = aws_iam_instance_profile.ecs_instance_role.arn instance_type = [ "c4.large", @@ -106,19 +106,19 @@ resource "aws_batch_compute_environment" "sample" { min_vcpus = 0 security_group_ids = [ - "${aws_security_group.sample.id}", + aws_security_group.sample.id, ] subnets = [ - "${aws_subnet.sample.id}", + aws_subnet.sample.id, ] type = "EC2" } - service_role = "${aws_iam_role.aws_batch_service_role.arn}" + service_role = aws_iam_role.aws_batch_service_role.arn type = "MANAGED" - depends_on = ["aws_iam_role_policy_attachment.aws_batch_service_role"] + depends_on = [aws_iam_role_policy_attachment.aws_batch_service_role] } ``` diff --git a/website/docs/r/batch_job_queue.html.markdown b/website/docs/r/batch_job_queue.html.markdown index 2cf3bb0a1ac..ee15b76af8b 100644 --- a/website/docs/r/batch_job_queue.html.markdown +++ b/website/docs/r/batch_job_queue.html.markdown @@ -14,10 +14,13 @@ Provides a Batch Job Queue resource. ```hcl resource "aws_batch_job_queue" "test_queue" { - name = "tf-test-batch-job-queue" - state = "ENABLED" - priority = 1 - compute_environments = ["${aws_batch_compute_environment.test_environment_1.arn}", "${aws_batch_compute_environment.test_environment_2.arn}"] + name = "tf-test-batch-job-queue" + state = "ENABLED" + priority = 1 + compute_environments = [ + aws_batch_compute_environment.test_environment_1.arn, + aws_batch_compute_environment.test_environment_2.arn, + ] } ``` diff --git a/website/docs/r/budgets_budget.html.markdown b/website/docs/r/budgets_budget.html.markdown index 4ca33cb536c..75ffbcb0f0d 100644 --- a/website/docs/r/budgets_budget.html.markdown +++ b/website/docs/r/budgets_budget.html.markdown @@ -161,19 +161,19 @@ Refer to [AWS CostTypes documentation](https://docs.aws.amazon.com/aws-cost-mana Valid keys for `cost_filters` parameter vary depending on the `budget_type` value. * `cost` - * `AZ` - * `LinkedAccount` - * `Operation` - * `PurchaseType` - * `Service` - * `TagKeyValue` + * `AZ` + * `LinkedAccount` + * `Operation` + * `PurchaseType` + * `Service` + * `TagKeyValue` * `usage` - * `AZ` - * `LinkedAccount` - * `Operation` - * `PurchaseType` - * `UsageType:` - * `TagKeyValue` + * `AZ` + * `LinkedAccount` + * `Operation` + * `PurchaseType` + * `UsageType:` + * `TagKeyValue` Refer to [AWS CostFilter documentation](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/data-type-filter.html) for further detail. diff --git a/website/docs/r/cloudformation_stack_set.html.markdown b/website/docs/r/cloudformation_stack_set.html.markdown index 872e50763a4..b8dfa6c8dd8 100644 --- a/website/docs/r/cloudformation_stack_set.html.markdown +++ b/website/docs/r/cloudformation_stack_set.html.markdown @@ -30,12 +30,12 @@ data "aws_iam_policy_document" "AWSCloudFormationStackSetAdministrationRole_assu } resource "aws_iam_role" "AWSCloudFormationStackSetAdministrationRole" { - assume_role_policy = "${data.aws_iam_policy_document.AWSCloudFormationStackSetAdministrationRole_assume_role_policy.json}" + assume_role_policy = data.aws_iam_policy_document.AWSCloudFormationStackSetAdministrationRole_assume_role_policy.json name = "AWSCloudFormationStackSetAdministrationRole" } resource "aws_cloudformation_stack_set" "example" { - administration_role_arn = "${aws_iam_role.AWSCloudFormationStackSetAdministrationRole.arn}" + administration_role_arn = aws_iam_role.AWSCloudFormationStackSetAdministrationRole.arn name = "example" parameters = { @@ -76,8 +76,8 @@ data "aws_iam_policy_document" "AWSCloudFormationStackSetAdministrationRole_Exec resource "aws_iam_role_policy" "AWSCloudFormationStackSetAdministrationRole_ExecutionPolicy" { name = "ExecutionPolicy" - policy = "${data.aws_iam_policy_document.AWSCloudFormationStackSetAdministrationRole_ExecutionPolicy.json}" - role = "${aws_iam_role.AWSCloudFormationStackSetAdministrationRole.name}" + policy = data.aws_iam_policy_document.AWSCloudFormationStackSetAdministrationRole_ExecutionPolicy.json + role = aws_iam_role.AWSCloudFormationStackSetAdministrationRole.name } ``` diff --git a/website/docs/r/cloudformation_stack_set_instance.html.markdown b/website/docs/r/cloudformation_stack_set_instance.html.markdown index e48291d956c..4de9c15095f 100644 --- a/website/docs/r/cloudformation_stack_set_instance.html.markdown +++ b/website/docs/r/cloudformation_stack_set_instance.html.markdown @@ -20,7 +20,7 @@ Manages a CloudFormation StackSet Instance. Instances are managed in the account resource "aws_cloudformation_stack_set_instance" "example" { account_id = "123456789012" region = "us-east-1" - stack_set_name = "${aws_cloudformation_stack_set.example.name}" + stack_set_name = aws_cloudformation_stack_set.example.name } ``` @@ -33,14 +33,14 @@ data "aws_iam_policy_document" "AWSCloudFormationStackSetExecutionRole_assume_ro effect = "Allow" principals { - identifiers = ["${aws_iam_role.AWSCloudFormationStackSetAdministrationRole.arn}"] + identifiers = [aws_iam_role.AWSCloudFormationStackSetAdministrationRole.arn] type = "AWS" } } } resource "aws_iam_role" "AWSCloudFormationStackSetExecutionRole" { - assume_role_policy = "${data.aws_iam_policy_document.AWSCloudFormationStackSetExecutionRole_assume_role_policy.json}" + assume_role_policy = data.aws_iam_policy_document.AWSCloudFormationStackSetExecutionRole_assume_role_policy.json name = "AWSCloudFormationStackSetExecutionRole" } @@ -61,8 +61,8 @@ data "aws_iam_policy_document" "AWSCloudFormationStackSetExecutionRole_MinimumEx resource "aws_iam_role_policy" "AWSCloudFormationStackSetExecutionRole_MinimumExecutionPolicy" { name = "MinimumExecutionPolicy" - policy = "${data.aws_iam_policy_document.AWSCloudFormationStackSetExecutionRole_MinimumExecutionPolicy.json}" - role = "${aws_iam_role.AWSCloudFormationStackSetExecutionRole.name}" + policy = data.aws_iam_policy_document.AWSCloudFormationStackSetExecutionRole_MinimumExecutionPolicy.json + role = aws_iam_role.AWSCloudFormationStackSetExecutionRole.name } ``` diff --git a/website/docs/r/cloudfront_distribution.html.markdown b/website/docs/r/cloudfront_distribution.html.markdown index 1e85553e2e3..b6d5c62b9de 100644 --- a/website/docs/r/cloudfront_distribution.html.markdown +++ b/website/docs/r/cloudfront_distribution.html.markdown @@ -40,8 +40,8 @@ locals { resource "aws_cloudfront_distribution" "s3_distribution" { origin { - domain_name = "${aws_s3_bucket.b.bucket_regional_domain_name}" - origin_id = "${local.s3_origin_id}" + domain_name = aws_s3_bucket.b.bucket_regional_domain_name + origin_id = local.s3_origin_id s3_origin_config { origin_access_identity = "origin-access-identity/cloudfront/ABCDEFG1234567" @@ -64,7 +64,7 @@ resource "aws_cloudfront_distribution" "s3_distribution" { default_cache_behavior { allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"] cached_methods = ["GET", "HEAD"] - target_origin_id = "${local.s3_origin_id}" + target_origin_id = local.s3_origin_id forwarded_values { query_string = false @@ -85,7 +85,7 @@ resource "aws_cloudfront_distribution" "s3_distribution" { path_pattern = "/content/immutable/*" allowed_methods = ["GET", "HEAD", "OPTIONS"] cached_methods = ["GET", "HEAD", "OPTIONS"] - target_origin_id = "${local.s3_origin_id}" + target_origin_id = local.s3_origin_id forwarded_values { query_string = false @@ -108,7 +108,7 @@ resource "aws_cloudfront_distribution" "s3_distribution" { path_pattern = "/content/*" allowed_methods = ["GET", "HEAD", "OPTIONS"] cached_methods = ["GET", "HEAD"] - target_origin_id = "${local.s3_origin_id}" + target_origin_id = local.s3_origin_id forwarded_values { query_string = false @@ -165,20 +165,20 @@ resource "aws_cloudfront_distribution" "s3_distribution" { } origin { - domain_name = "${aws_s3_bucket.primary.bucket_regional_domain_name}" + domain_name = aws_s3_bucket.primary.bucket_regional_domain_name origin_id = "primaryS3" s3_origin_config { - origin_access_identity = "${aws_cloudfront_origin_access_identity.default.cloudfront_access_identity_path}" + origin_access_identity = aws_cloudfront_origin_access_identity.default.cloudfront_access_identity_path } } origin { - domain_name = "${aws_s3_bucket.failover.bucket_regional_domain_name}" + domain_name = aws_s3_bucket.failover.bucket_regional_domain_name origin_id = "failoverS3" s3_origin_config { - origin_access_identity = "${aws_cloudfront_origin_access_identity.default.cloudfront_access_identity_path}" + origin_access_identity = aws_cloudfront_origin_access_identity.default.cloudfront_access_identity_path } } @@ -198,136 +198,136 @@ of several sub-resources - these resources are laid out below. ### Top-Level Arguments - * `aliases` (Optional) - Extra CNAMEs (alternate domain names), if any, for +* `aliases` (Optional) - Extra CNAMEs (alternate domain names), if any, for this distribution. - * `comment` (Optional) - Any comments you want to include about the +* `comment` (Optional) - Any comments you want to include about the distribution. - * `custom_error_response` (Optional) - One or more [custom error response](#custom-error-response-arguments) elements (multiples allowed). +* `custom_error_response` (Optional) - One or more [custom error response](#custom-error-response-arguments) elements (multiples allowed). - * `default_cache_behavior` (Required) - The [default cache behavior](#default-cache-behavior-arguments) for this distribution (maximum +* `default_cache_behavior` (Required) - The [default cache behavior](#default-cache-behavior-arguments) for this distribution (maximum one). - * `default_root_object` (Optional) - The object that you want CloudFront to +* `default_root_object` (Optional) - The object that you want CloudFront to return (for example, index.html) when an end user requests the root URL. - * `enabled` (Required) - Whether the distribution is enabled to accept end +* `enabled` (Required) - Whether the distribution is enabled to accept end user requests for content. - * `is_ipv6_enabled` (Optional) - Whether the IPv6 is enabled for the distribution. +* `is_ipv6_enabled` (Optional) - Whether the IPv6 is enabled for the distribution. - * `http_version` (Optional) - The maximum HTTP version to support on the +* `http_version` (Optional) - The maximum HTTP version to support on the distribution. Allowed values are `http1.1` and `http2`. The default is `http2`. - * `logging_config` (Optional) - The [logging +* `logging_config` (Optional) - The [logging configuration](#logging-config-arguments) that controls how logs are written to your distribution (maximum one). - * `ordered_cache_behavior` (Optional) - An ordered list of [cache behaviors](#cache-behavior-arguments) +* `ordered_cache_behavior` (Optional) - An ordered list of [cache behaviors](#cache-behavior-arguments) resource for this distribution. List from top to bottom in order of precedence. The topmost cache behavior will have precedence 0. - * `origin` (Required) - One or more [origins](#origin-arguments) for this +* `origin` (Required) - One or more [origins](#origin-arguments) for this distribution (multiples allowed). - * `origin_group` (Optional) - One or more [origin_group](#origin-group-arguments) for this +* `origin_group` (Optional) - One or more [origin_group](#origin-group-arguments) for this distribution (multiples allowed). - * `price_class` (Optional) - The price class for this distribution. One of +* `price_class` (Optional) - The price class for this distribution. One of `PriceClass_All`, `PriceClass_200`, `PriceClass_100` - * `restrictions` (Required) - The [restriction +* `restrictions` (Required) - The [restriction configuration](#restrictions-arguments) for this distribution (maximum one). - * `tags` - (Optional) A map of tags to assign to the resource. +* `tags` - (Optional) A map of tags to assign to the resource. - * `viewer_certificate` (Required) - The [SSL +* `viewer_certificate` (Required) - The [SSL configuration](#viewer-certificate-arguments) for this distribution (maximum one). - * `web_acl_id` (Optional) - If you're using AWS WAF to filter CloudFront +* `web_acl_id` (Optional) - If you're using AWS WAF to filter CloudFront requests, the Id of the AWS WAF web ACL that is associated with the distribution. The WAF Web ACL must exist in the WAF Global (CloudFront) region and the credentials configuring this argument must have - `waf:GetWebACL` permissions assigned. + `waf:GetWebACL` permissions assigned. If using WAFv2, provide the ARN of the web ACL. - * `retain_on_delete` (Optional) - Disables the distribution instead of +* `retain_on_delete` (Optional) - Disables the distribution instead of deleting it when destroying the resource through Terraform. If this is set, the distribution needs to be deleted manually afterwards. Default: `false`. - * `wait_for_deployment` (Optional) - If enabled, the resource will wait for +* `wait_for_deployment` (Optional) - If enabled, the resource will wait for the distribution status to change from `InProgress` to `Deployed`. Setting this to`false` will skip the process. Default: `true`. #### Cache Behavior Arguments - * `allowed_methods` (Required) - Controls which HTTP methods CloudFront +* `allowed_methods` (Required) - Controls which HTTP methods CloudFront processes and forwards to your Amazon S3 bucket or your custom origin. - * `cached_methods` (Required) - Controls whether CloudFront caches the +* `cached_methods` (Required) - Controls whether CloudFront caches the response to requests using the specified HTTP methods. - * `compress` (Optional) - Whether you want CloudFront to automatically +* `compress` (Optional) - Whether you want CloudFront to automatically compress content for web requests that include `Accept-Encoding: gzip` in the request header (default: `false`). - * `default_ttl` (Optional) - The default amount of time (in seconds) that an +* `default_ttl` (Optional) - The default amount of time (in seconds) that an object is in a CloudFront cache before CloudFront forwards another request in the absence of an `Cache-Control max-age` or `Expires` header. Defaults to 1 day. - * `field_level_encryption_id` (Optional) - Field level encryption configuration ID +* `field_level_encryption_id` (Optional) - Field level encryption configuration ID - * `forwarded_values` (Required) - The [forwarded values configuration](#forwarded-values-arguments) that specifies how CloudFront +* `forwarded_values` (Required) - The [forwarded values configuration](#forwarded-values-arguments) that specifies how CloudFront handles query strings, cookies and headers (maximum one). - * `lambda_function_association` (Optional) - A config block that triggers a lambda function with +* `lambda_function_association` (Optional) - A config block that triggers a lambda function with specific actions. Defined below, maximum 4. - * `max_ttl` (Optional) - The maximum amount of time (in seconds) that an +* `max_ttl` (Optional) - The maximum amount of time (in seconds) that an object is in a CloudFront cache before CloudFront forwards another request to your origin to determine whether the object has been updated. Only effective in the presence of `Cache-Control max-age`, `Cache-Control s-maxage`, and `Expires` headers. Defaults to 365 days. - * `min_ttl` (Optional) - The minimum amount of time that you want objects to +* `min_ttl` (Optional) - The minimum amount of time that you want objects to stay in CloudFront caches before CloudFront queries your origin to see whether the object has been updated. Defaults to 0 seconds. - * `path_pattern` (Required) - The pattern (for example, `images/*.jpg)` that +* `path_pattern` (Required) - The pattern (for example, `images/*.jpg)` that specifies which requests you want this cache behavior to apply to. - * `smooth_streaming` (Optional) - Indicates whether you want to distribute +* `smooth_streaming` (Optional) - Indicates whether you want to distribute media files in Microsoft Smooth Streaming format using the origin that is associated with this cache behavior. - * `target_origin_id` (Required) - The value of ID for the origin that you want +* `target_origin_id` (Required) - The value of ID for the origin that you want CloudFront to route requests to when a request matches the path pattern either for a cache behavior or for the default cache behavior. - * `trusted_signers` (Optional) - The AWS accounts, if any, that you want to - allow to create signed URLs for private content. +* `trusted_signers` (Optional) - List of AWS account IDs (or `self`) that you want to allow to create signed URLs for private content. +See the [CloudFront User Guide](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html) for more information about this feature. - * `viewer_protocol_policy` (Required) - Use this element to specify the +* `viewer_protocol_policy` (Required) - Use this element to specify the protocol that users can use to access the files in the origin specified by TargetOriginId when a request matches the path pattern in PathPattern. One of `allow-all`, `https-only`, or `redirect-to-https`. ##### Forwarded Values Arguments - * `cookies` (Required) - The [forwarded values cookies](#cookies-arguments) +* `cookies` (Required) - The [forwarded values cookies](#cookies-arguments) that specifies how CloudFront handles cookies (maximum one). - * `headers` (Optional) - Specifies the Headers, if any, that you want +* `headers` (Optional) - Specifies the Headers, if any, that you want CloudFront to vary upon for this cache behavior. Specify `*` to include all headers. - * `query_string` (Required) - Indicates whether you want CloudFront to forward +* `query_string` (Required) - Indicates whether you want CloudFront to forward query strings to the origin that is associated with this cache behavior. - * `query_string_cache_keys` (Optional) - When specified, along with a value of +* `query_string_cache_keys` (Optional) - When specified, along with a value of `true` for `query_string`, all query strings are forwarded, however only the query string keys listed in this argument are cached. When omitted with a value of `true` for `query_string`, all query string keys are cached. @@ -351,7 +351,7 @@ resource "aws_cloudfront_distribution" "example" { lambda_function_association { event_type = "viewer-request" - lambda_arn = "${aws_lambda_function.example.qualified_arn}" + lambda_arn = aws_lambda_function.example.qualified_arn include_body = false } } @@ -366,28 +366,28 @@ resource "aws_cloudfront_distribution" "example" { ##### Cookies Arguments - * `forward` (Required) - Specifies whether you want CloudFront to forward +* `forward` (Required) - Specifies whether you want CloudFront to forward cookies to the origin that is associated with this cache behavior. You can specify `all`, `none` or `whitelist`. If `whitelist`, you must include the subsequent `whitelisted_names` - * `whitelisted_names` (Optional) - If you have specified `whitelist` to +* `whitelisted_names` (Optional) - If you have specified `whitelist` to `forward`, the whitelisted cookies that you want CloudFront to forward to your origin. #### Custom Error Response Arguments - * `error_caching_min_ttl` (Optional) - The minimum amount of time you want +* `error_caching_min_ttl` (Optional) - The minimum amount of time you want HTTP error codes to stay in CloudFront caches before CloudFront queries your origin to see whether the object has been updated. - * `error_code` (Required) - The 4xx or 5xx HTTP status code that you want to +* `error_code` (Required) - The 4xx or 5xx HTTP status code that you want to customize. - * `response_code` (Optional) - The HTTP status code that you want CloudFront +* `response_code` (Optional) - The HTTP status code that you want CloudFront to return with the custom error page to the viewer. - * `response_page_path` (Optional) - The path of the custom error page (for +* `response_page_path` (Optional) - The path of the custom error page (for example, `/custom_404.html`). #### Default Cache Behavior Arguments @@ -398,54 +398,54 @@ argument is not required. #### Logging Config Arguments - * `bucket` (Required) - The Amazon S3 bucket to store the access logs in, for +* `bucket` (Required) - The Amazon S3 bucket to store the access logs in, for example, `myawslogbucket.s3.amazonaws.com`. - * `include_cookies` (Optional) - Specifies whether you want CloudFront to +* `include_cookies` (Optional) - Specifies whether you want CloudFront to include cookies in access logs (default: `false`). - * `prefix` (Optional) - An optional string that you want CloudFront to prefix +* `prefix` (Optional) - An optional string that you want CloudFront to prefix to the access log filenames for this distribution, for example, `myprefix/`. #### Origin Arguments - * `custom_origin_config` - The [CloudFront custom +* `custom_origin_config` - The [CloudFront custom origin](#custom-origin-config-arguments) configuration information. If an S3 origin is required, use `s3_origin_config` instead. - * `domain_name` (Required) - The DNS domain name of either the S3 bucket, or +* `domain_name` (Required) - The DNS domain name of either the S3 bucket, or web site of your custom origin. - * `custom_header` (Optional) - One or more sub-resources with `name` and +* `custom_header` (Optional) - One or more sub-resources with `name` and `value` parameters that specify header data that will be sent to the origin (multiples allowed). - * `origin_id` (Required) - A unique identifier for the origin. +* `origin_id` (Required) - A unique identifier for the origin. - * `origin_path` (Optional) - An optional element that causes CloudFront to +* `origin_path` (Optional) - An optional element that causes CloudFront to request your content from a directory in your Amazon S3 bucket or your custom origin. - * `s3_origin_config` - The [CloudFront S3 origin](#s3-origin-config-arguments) +* `s3_origin_config` - The [CloudFront S3 origin](#s3-origin-config-arguments) configuration information. If a custom origin is required, use `custom_origin_config` instead. ##### Custom Origin Config Arguments - * `http_port` (Required) - The HTTP port the custom origin listens on. +* `http_port` (Required) - The HTTP port the custom origin listens on. - * `https_port` (Required) - The HTTPS port the custom origin listens on. +* `https_port` (Required) - The HTTPS port the custom origin listens on. - * `origin_protocol_policy` (Required) - The origin protocol policy to apply to +* `origin_protocol_policy` (Required) - The origin protocol policy to apply to your origin. One of `http-only`, `https-only`, or `match-viewer`. - * `origin_ssl_protocols` (Required) - The SSL/TLS protocols that you want +* `origin_ssl_protocols` (Required) - The SSL/TLS protocols that you want CloudFront to use when communicating with your origin over HTTPS. A list of one or more of `SSLv3`, `TLSv1`, `TLSv1.1`, and `TLSv1.2`. - * `origin_keepalive_timeout` - (Optional) The Custom KeepAlive timeout, in seconds. By default, AWS enforces a limit of `60`. But you can request an [increase](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#request-custom-request-timeout). +* `origin_keepalive_timeout` - (Optional) The Custom KeepAlive timeout, in seconds. By default, AWS enforces a limit of `60`. But you can request an [increase](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#request-custom-request-timeout). - * `origin_read_timeout` - (Optional) The Custom Read timeout, in seconds. By default, AWS enforces a limit of `60`. But you can request an [increase](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#request-custom-request-timeout). +* `origin_read_timeout` - (Optional) The Custom Read timeout, in seconds. By default, AWS enforces a limit of `60`. But you can request an [increase](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#request-custom-request-timeout). ##### S3 Origin Config Arguments @@ -454,11 +454,11 @@ argument is not required. #### Origin Group Arguments - * `origin_id` (Required) - A unique identifier for the origin group. +* `origin_id` (Required) - A unique identifier for the origin group. - * `failover_criteria` (Required) - The [failover criteria](#failover-criteria-arguments) for when to failover to the secondary origin +* `failover_criteria` (Required) - The [failover criteria](#failover-criteria-arguments) for when to failover to the secondary origin - * `member` (Required) - Ordered [member](#member-arguments) configuration blocks assigned to the origin group, where the first member is the primary origin. You must specify two members. +* `member` (Required) - Ordered [member](#member-arguments) configuration blocks assigned to the origin group, where the first member is the primary origin. You must specify two members. ##### Failover Criteria Arguments @@ -475,33 +475,33 @@ The `restrictions` sub-resource takes another single sub-resource named The arguments of `geo_restriction` are: - * `locations` (Optional) - The [ISO 3166-1-alpha-2 codes][4] for which you +* `locations` (Optional) - The [ISO 3166-1-alpha-2 codes][4] for which you want CloudFront either to distribute your content (`whitelist`) or not distribute your content (`blacklist`). - * `restriction_type` (Required) - The method that you want to use to restrict +* `restriction_type` (Required) - The method that you want to use to restrict distribution of your content by country: `none`, `whitelist`, or `blacklist`. #### Viewer Certificate Arguments - * `acm_certificate_arn` - The ARN of the [AWS Certificate Manager][6] +* `acm_certificate_arn` - The ARN of the [AWS Certificate Manager][6] certificate that you wish to use with this distribution. Specify this, `cloudfront_default_certificate`, or `iam_certificate_id`. The ACM certificate must be in US-EAST-1. - * `cloudfront_default_certificate` - `true` if you want viewers to use HTTPS +* `cloudfront_default_certificate` - `true` if you want viewers to use HTTPS to request your objects and you're using the CloudFront domain name for your distribution. Specify this, `acm_certificate_arn`, or `iam_certificate_id`. - * `iam_certificate_id` - The IAM certificate identifier of the custom viewer +* `iam_certificate_id` - The IAM certificate identifier of the custom viewer certificate for this distribution if you are using a custom domain. Specify this, `acm_certificate_arn`, or `cloudfront_default_certificate`. - * `minimum_protocol_version` - The minimum version of the SSL protocol that +* `minimum_protocol_version` - The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections. Can only be set if `cloudfront_default_certificate = false`. One of `SSLv3`, `TLSv1`, - `TLSv1_2016`, `TLSv1.1_2016` or `TLSv1.2_2018`. Default: `TLSv1`. **NOTE**: + `TLSv1_2016`, `TLSv1.1_2016`, `TLSv1.2_2018` or `TLSv1.2_2019`. Default: `TLSv1`. **NOTE**: If you are using a custom certificate (specified with `acm_certificate_arn` or `iam_certificate_id`), and have specified `sni-only` in `ssl_support_method`, `TLSv1` or later must be specified. If you have @@ -509,7 +509,7 @@ The arguments of `geo_restriction` are: specified. If you have specified `cloudfront_default_certificate`, `TLSv1` must be specified. - * `ssl_support_method`: Specifies how you want CloudFront to serve HTTPS +* `ssl_support_method`: Specifies how you want CloudFront to serve HTTPS requests. One of `vip` or `sni-only`. Required if you specify `acm_certificate_arn` or `iam_certificate_id`. **NOTE:** `vip` causes CloudFront to use a dedicated IP address and may incur extra charges. @@ -518,33 +518,35 @@ The arguments of `geo_restriction` are: In addition to all arguments above, the following attributes are exported: - * `id` - The identifier for the distribution. For example: `EDFDVBD632BHDS5`. +* `id` - The identifier for the distribution. For example: `EDFDVBD632BHDS5`. - * `arn` - The ARN (Amazon Resource Name) for the distribution. For example: arn:aws:cloudfront::123456789012:distribution/EDFDVBD632BHDS5, where 123456789012 is your AWS account ID. +* `arn` - The ARN (Amazon Resource Name) for the distribution. For example: `arn:aws:cloudfront::123456789012:distribution/EDFDVBD632BHDS5`, where `123456789012` is your AWS account ID. - * `caller_reference` - Internal value used by CloudFront to allow future +* `caller_reference` - Internal value used by CloudFront to allow future updates to the distribution configuration. - * `status` - The current status of the distribution. `Deployed` if the +* `status` - The current status of the distribution. `Deployed` if the distribution's information is fully propagated throughout the Amazon CloudFront system. - * `active_trusted_signers` - The key pair IDs that CloudFront is aware of for - each trusted signer, if the distribution is set up to serve private content - with signed URLs. +* `trusted_signers` - List of nested attributes for active trusted signers, if the distribution is set up to serve private content with signed URLs + * `enabled` - `true` if any of the AWS accounts listed as trusted signers have active CloudFront key pairs + * `items` - List of nested attributes for each trusted signer + * `aws_account_number` - AWS account ID or `self` + * `key_pair_ids` - Set of active CloudFront key pairs associated with the signer account - * `domain_name` - The domain name corresponding to the distribution. For +* `domain_name` - The domain name corresponding to the distribution. For example: `d604721fxaaqy9.cloudfront.net`. - * `last_modified_time` - The date and time the distribution was last modified. +* `last_modified_time` - The date and time the distribution was last modified. - * `in_progress_validation_batches` - The number of invalidation batches +* `in_progress_validation_batches` - The number of invalidation batches currently in progress. - * `etag` - The current version of the distribution's information. For example: +* `etag` - The current version of the distribution's information. For example: `E2QWRUHAPOMQZL`. - * `hosted_zone_id` - The CloudFront Route 53 zone ID that can be used to +* `hosted_zone_id` - The CloudFront Route 53 zone ID that can be used to route an [Alias Resource Record Set][7] to. This attribute is simply an alias for the zone ID `Z2FDTNDATAQYW2`. diff --git a/website/docs/r/cloudfront_origin_access_identity.html.markdown b/website/docs/r/cloudfront_origin_access_identity.html.markdown index 67eb280a5b1..24be5f5c897 100644 --- a/website/docs/r/cloudfront_origin_access_identity.html.markdown +++ b/website/docs/r/cloudfront_origin_access_identity.html.markdown @@ -56,8 +56,14 @@ The below snippet demonstrates use with the `s3_origin_config` structure for the [`aws_cloudfront_distribution`][3] resource: ```hcl -s3_origin_config { - origin_access_identity = "${aws_cloudfront_origin_access_identity.origin_access_identity.cloudfront_access_identity_path}" +resource "aws_cloudfront_distribution" "example" { + # ... other configuration ... + + origin { + s3_origin_config { + origin_access_identity = aws_cloudfront_origin_access_identity.example.cloudfront_access_identity_path + } + } } ``` @@ -76,24 +82,14 @@ data "aws_iam_policy_document" "s3_policy" { principals { type = "AWS" - identifiers = ["${aws_cloudfront_origin_access_identity.origin_access_identity.iam_arn}"] - } - } - - statement { - actions = ["s3:ListBucket"] - resources = ["${aws_s3_bucket.example.arn}"] - - principals { - type = "AWS" - identifiers = ["${aws_cloudfront_origin_access_identity.origin_access_identity.iam_arn}"] + identifiers = [aws_cloudfront_origin_access_identity.origin_access_identity.iam_arn] } } } resource "aws_s3_bucket_policy" "example" { - bucket = "${aws_s3_bucket.example.id}" - policy = "${data.aws_iam_policy_document.s3_policy.json}" + bucket = aws_s3_bucket.example.id + policy = data.aws_iam_policy_document.s3_policy.json } ``` diff --git a/website/docs/r/cloudfront_public_key.html.markdown b/website/docs/r/cloudfront_public_key.html.markdown index 687cb20c3b9..bedf8901211 100644 --- a/website/docs/r/cloudfront_public_key.html.markdown +++ b/website/docs/r/cloudfront_public_key.html.markdown @@ -15,7 +15,7 @@ The following example below creates a CloudFront public key. ```hcl resource "aws_cloudfront_public_key" "example" { comment = "test public key" - encoded_key = "${file("public_key.pem")}" + encoded_key = file("public_key.pem") name = "test_key" } ``` diff --git a/website/docs/r/cloudhsm_v2_cluster.html.markdown b/website/docs/r/cloudhsm_v2_cluster.html.markdown index 3385fd9d143..49dac57a131 100644 --- a/website/docs/r/cloudhsm_v2_cluster.html.markdown +++ b/website/docs/r/cloudhsm_v2_cluster.html.markdown @@ -14,10 +14,10 @@ For information about CloudHSM v2, see the [AWS CloudHSM User Guide][1] and the [Amazon CloudHSM API Reference][2]. -~> **NOTE:** CloudHSM can take up to several minutes to be set up. -Practically no single attribute can be updated except TAGS. +~> **NOTE:** A CloudHSM Cluster can take several minutes to set up. +Practically no single attribute can be updated, except for `tags`. If you need to delete a cluster, you have to remove its HSM modules first. -To initialize cluster, you have to add an hsm instance to the cluster then sign CSR and upload it. +To initialize cluster, you have to add an HSM instance to the cluster, then sign CSR and upload it. ## Example Usage @@ -25,7 +25,7 @@ The following example below creates a CloudHSM cluster. ```hcl provider "aws" { - region = "${var.aws_region}" + region = var.aws_region } data "aws_availability_zones" "available" {} @@ -40,10 +40,10 @@ resource "aws_vpc" "cloudhsm_v2_vpc" { resource "aws_subnet" "cloudhsm_v2_subnets" { count = 2 - vpc_id = "${aws_vpc.cloudhsm_v2_vpc.id}" - cidr_block = "${element(var.subnets, count.index)}" + vpc_id = aws_vpc.cloudhsm_v2_vpc.id + cidr_block = element(var.subnets, count.index) map_public_ip_on_launch = false - availability_zone = "${element(data.aws_availability_zones.available.names, count.index)}" + availability_zone = element(data.aws_availability_zones.available.names, count.index) tags = { Name = "example-aws_cloudhsm_v2_cluster" @@ -52,7 +52,7 @@ resource "aws_subnet" "cloudhsm_v2_subnets" { resource "aws_cloudhsm_v2_cluster" "cloudhsm_v2_cluster" { hsm_type = "hsm1.medium" - subnet_ids = ["${aws_subnet.cloudhsm_v2_subnets.*.id}"] + subnet_ids = aws_subnet.cloudhsm_v2_subnets.*.id tags = { Name = "example-aws_cloudhsm_v2_cluster" @@ -65,7 +65,7 @@ resource "aws_cloudhsm_v2_cluster" "cloudhsm_v2_cluster" { The following arguments are supported: * `source_backup_identifier` - (Optional) The id of Cloud HSM v2 cluster backup to be restored. -* `hsm_type` - (Required) The type of HSM module in the cluster. Currently, only hsm1.medium is supported. +* `hsm_type` - (Required) The type of HSM module in the cluster. Currently, only `hsm1.medium` is supported. * `subnet_ids` - (Required) The IDs of subnets in which cluster will operate. * `tags` - (Optional) A map of tags to assign to the resource. @@ -74,15 +74,15 @@ The following arguments are supported: The following attributes are exported: * `cluster_id` - The id of the CloudHSM cluster. -* `cluster_state` - The state of the cluster. +* `cluster_state` - The state of the CloudHSM cluster. * `vpc_id` - The id of the VPC that the CloudHSM cluster resides in. * `security_group_id` - The ID of the security group associated with the CloudHSM cluster. * `cluster_certificates` - The list of cluster certificates. - * `cluster_certificates.0.cluster_certificate` - The cluster certificate issued (signed) by the issuing certificate authority (CA) of the cluster's owner. - * `cluster_certificates.0.cluster_csr` - The certificate signing request (CSR). Available only in UNINITIALIZED state after an hsm instance is added to the cluster. - * `cluster_certificates.0.aws_hardware_certificate` - The HSM hardware certificate issued (signed) by AWS CloudHSM. - * `cluster_certificates.0.hsm_certificate` - The HSM certificate issued (signed) by the HSM hardware. - * `cluster_certificates.0.manufacturer_hardware_certificate` - The HSM hardware certificate issued (signed) by the hardware manufacturer. + * `cluster_certificates.0.cluster_certificate` - The cluster certificate issued (signed) by the issuing certificate authority (CA) of the cluster's owner. + * `cluster_certificates.0.cluster_csr` - The certificate signing request (CSR). Available only in `UNINITIALIZED` state after an HSM instance is added to the cluster. + * `cluster_certificates.0.aws_hardware_certificate` - The HSM hardware certificate issued (signed) by AWS CloudHSM. + * `cluster_certificates.0.hsm_certificate` - The HSM certificate issued (signed) by the HSM hardware. + * `cluster_certificates.0.manufacturer_hardware_certificate` - The HSM hardware certificate issued (signed) by the hardware manufacturer. [1]: https://docs.aws.amazon.com/cloudhsm/latest/userguide/introduction.html [2]: https://docs.aws.amazon.com/cloudhsm/latest/APIReference/Welcome.html diff --git a/website/docs/r/cloudhsm_v2_hsm.html.markdown b/website/docs/r/cloudhsm_v2_hsm.html.markdown index 7bac9e32654..e709caa4bb3 100644 --- a/website/docs/r/cloudhsm_v2_hsm.html.markdown +++ b/website/docs/r/cloudhsm_v2_hsm.html.markdown @@ -16,12 +16,12 @@ The following example below creates an HSM module in CloudHSM cluster. ```hcl data "aws_cloudhsm_v2_cluster" "cluster" { - cluster_id = "${var.cloudhsm_cluster_id}" + cluster_id = var.cloudhsm_cluster_id } resource "aws_cloudhsm_v2_hsm" "cloudhsm_v2_hsm" { - subnet_id = "${data.aws_cloudhsm_v2_cluster.cluster.subnet_ids[0]}" - cluster_id = "${data.aws_cloudhsm_v2_cluster.cluster.cluster_id}" + subnet_id = data.aws_cloudhsm_v2_cluster.cluster.subnet_ids[0] + cluster_id = data.aws_cloudhsm_v2_cluster.cluster.cluster_id } ``` diff --git a/website/docs/r/cloudtrail.html.markdown b/website/docs/r/cloudtrail.html.markdown index 18593f6b584..79fd755685e 100644 --- a/website/docs/r/cloudtrail.html.markdown +++ b/website/docs/r/cloudtrail.html.markdown @@ -26,7 +26,7 @@ data "aws_caller_identity" "current" {} resource "aws_cloudtrail" "foobar" { name = "tf-trail-foobar" - s3_bucket_name = "${aws_s3_bucket.foo.id}" + s3_bucket_name = aws_s3_bucket.foo.id s3_key_prefix = "prefix" include_global_service_events = false } diff --git a/website/docs/r/cloudwatch_dashboard.html.markdown b/website/docs/r/cloudwatch_dashboard.html.markdown index 8c13d825b26..95e72230c6b 100644 --- a/website/docs/r/cloudwatch_dashboard.html.markdown +++ b/website/docs/r/cloudwatch_dashboard.html.markdown @@ -17,42 +17,42 @@ resource "aws_cloudwatch_dashboard" "main" { dashboard_name = "my-dashboard" dashboard_body = < **NOTE on CodeCommit Availability**: The CodeCommit is not yet rolled out -in all regions - available regions are listed -[the AWS Docs](https://docs.aws.amazon.com/general/latest/gr/rande.html#codecommit_region). - ## Example Usage ```hcl diff --git a/website/docs/r/codecommit_trigger.html.markdown b/website/docs/r/codecommit_trigger.html.markdown index bdb2c373f50..43e58723c01 100644 --- a/website/docs/r/codecommit_trigger.html.markdown +++ b/website/docs/r/codecommit_trigger.html.markdown @@ -10,10 +10,6 @@ description: |- Provides a CodeCommit Trigger Resource. -~> **NOTE on CodeCommit**: The CodeCommit is not yet rolled out -in all regions - available regions are listed -[the AWS Docs](https://docs.aws.amazon.com/general/latest/gr/rande.html#codecommit_region). - ## Example Usage ```hcl @@ -22,12 +18,12 @@ resource "aws_codecommit_repository" "test" { } resource "aws_codecommit_trigger" "test" { - repository_name = "${aws_codecommit_repository.test.repository_name}" + repository_name = aws_codecommit_repository.test.repository_name trigger { name = "all" events = ["all"] - destination_arn = "${aws_sns_topic.test.arn}" + destination_arn = aws_sns_topic.test.arn } } ``` diff --git a/website/docs/r/codedeploy_deployment_config.html.markdown b/website/docs/r/codedeploy_deployment_config.html.markdown index aa76723ecd7..05e33048007 100644 --- a/website/docs/r/codedeploy_deployment_config.html.markdown +++ b/website/docs/r/codedeploy_deployment_config.html.markdown @@ -25,10 +25,10 @@ resource "aws_codedeploy_deployment_config" "foo" { } resource "aws_codedeploy_deployment_group" "foo" { - app_name = "${aws_codedeploy_app.foo_app.name}" + app_name = aws_codedeploy_app.foo_app.name deployment_group_name = "bar" - service_role_arn = "${aws_iam_role.foo_role.arn}" - deployment_config_name = "${aws_codedeploy_deployment_config.foo.id}" + service_role_arn = aws_iam_role.foo_role.arn + deployment_config_name = aws_codedeploy_deployment_config.foo.id ec2_tag_filter { key = "filterkey" @@ -72,10 +72,10 @@ resource "aws_codedeploy_deployment_config" "foo" { } resource "aws_codedeploy_deployment_group" "foo" { - app_name = "${aws_codedeploy_app.foo_app.name}" + app_name = aws_codedeploy_app.foo_app.name deployment_group_name = "bar" - service_role_arn = "${aws_iam_role.foo_role.arn}" - deployment_config_name = "${aws_codedeploy_deployment_config.foo.id}" + service_role_arn = aws_iam_role.foo_role.arn + deployment_config_name = aws_codedeploy_deployment_config.foo.id auto_rollback_configuration { enabled = true diff --git a/website/docs/r/codedeploy_deployment_group.html.markdown b/website/docs/r/codedeploy_deployment_group.html.markdown index 1882ff1e8bd..9f69bd4b7f6 100644 --- a/website/docs/r/codedeploy_deployment_group.html.markdown +++ b/website/docs/r/codedeploy_deployment_group.html.markdown @@ -37,7 +37,7 @@ EOF resource "aws_iam_role_policy_attachment" "AWSCodeDeployRole" { policy_arn = "arn:aws:iam::aws:policy/service-role/AWSCodeDeployRole" - role = "${aws_iam_role.example.name}" + role = aws_iam_role.example.name } resource "aws_codedeploy_app" "example" { @@ -49,9 +49,9 @@ resource "aws_sns_topic" "example" { } resource "aws_codedeploy_deployment_group" "example" { - app_name = "${aws_codedeploy_app.example.name}" + app_name = aws_codedeploy_app.example.name deployment_group_name = "example-group" - service_role_arn = "${aws_iam_role.example.arn}" + service_role_arn = aws_iam_role.example.arn ec2_tag_set { ec2_tag_filter { @@ -70,7 +70,7 @@ resource "aws_codedeploy_deployment_group" "example" { trigger_configuration { trigger_events = ["DeploymentFailure"] trigger_name = "example-trigger" - trigger_target_arn = "${aws_sns_topic.example.arn}" + trigger_target_arn = aws_sns_topic.example.arn } auto_rollback_configuration { @@ -94,10 +94,10 @@ resource "aws_codedeploy_app" "example" { } resource "aws_codedeploy_deployment_group" "example" { - app_name = "${aws_codedeploy_app.example.name}" + app_name = aws_codedeploy_app.example.name deployment_config_name = "CodeDeployDefault.ECSAllAtOnce" deployment_group_name = "example" - service_role_arn = "${aws_iam_role.example.arn}" + service_role_arn = aws_iam_role.example.arn auto_rollback_configuration { enabled = true @@ -121,22 +121,22 @@ resource "aws_codedeploy_deployment_group" "example" { } ecs_service { - cluster_name = "${aws_ecs_cluster.example.name}" - service_name = "${aws_ecs_service.example.name}" + cluster_name = aws_ecs_cluster.example.name + service_name = aws_ecs_service.example.name } load_balancer_info { target_group_pair_info { prod_traffic_route { - listener_arns = ["${aws_lb_listener.example.arn}"] + listener_arns = [aws_lb_listener.example.arn] } target_group { - name = "${aws_lb_target_group.blue.name}" + name = aws_lb_target_group.blue.name } target_group { - name = "${aws_lb_target_group.green.name}" + name = aws_lb_target_group.green.name } } } @@ -151,9 +151,9 @@ resource "aws_codedeploy_app" "example" { } resource "aws_codedeploy_deployment_group" "example" { - app_name = "${aws_codedeploy_app.example.name}" + app_name = aws_codedeploy_app.example.name deployment_group_name = "example-group" - service_role_arn = "${aws_iam_role.example.arn}" + service_role_arn = aws_iam_role.example.arn deployment_style { deployment_option = "WITH_TRAFFIC_CONTROL" @@ -162,7 +162,7 @@ resource "aws_codedeploy_deployment_group" "example" { load_balancer_info { elb_info { - name = "${aws_elb.example.name}" + name = aws_elb.example.name } } @@ -210,8 +210,8 @@ You can configure a deployment to stop when a **CloudWatch** alarm detects that * `alarms` - (Optional) A list of alarms configured for the deployment group. _A maximum of 10 alarms can be added to a deployment group_. * `enabled` - (Optional) Indicates whether the alarm configuration is enabled. This option is useful when you want to temporarily deactivate alarm monitoring for a deployment group without having to add the same alarms again later. * `ignore_poll_alarm_failure` - (Optional) Indicates whether a deployment should continue if information about the current state of alarms cannot be retrieved from CloudWatch. The default value is `false`. - * `true`: The deployment will proceed even if alarm status information can't be retrieved. - * `false`: The deployment will stop if alarm status information can't be retrieved. + * `true`: The deployment will proceed even if alarm status information can't be retrieved. + * `false`: The deployment will stop if alarm status information can't be retrieved. _Only one `alarm_configuration` is allowed_. @@ -237,21 +237,21 @@ _Only one `blue_green_deployment_config` is allowed_. You can configure how traffic is rerouted to instances in a replacement environment in a blue/green deployment. `deployment_ready_option` supports the following: * `action_on_timeout` - (Optional) When to reroute traffic from an original environment to a replacement environment in a blue/green deployment. - * `CONTINUE_DEPLOYMENT`: Register new instances with the load balancer immediately after the new application revision is installed on the instances in the replacement environment. - * `STOP_DEPLOYMENT`: Do not register new instances with load balancer unless traffic is rerouted manually. If traffic is not rerouted manually before the end of the specified wait period, the deployment status is changed to Stopped. + * `CONTINUE_DEPLOYMENT`: Register new instances with the load balancer immediately after the new application revision is installed on the instances in the replacement environment. + * `STOP_DEPLOYMENT`: Do not register new instances with load balancer unless traffic is rerouted manually. If traffic is not rerouted manually before the end of the specified wait period, the deployment status is changed to Stopped. * `wait_time_in_minutes` - (Optional) The number of minutes to wait before the status of a blue/green deployment changed to Stopped if rerouting is not started manually. Applies only to the `STOP_DEPLOYMENT` option for `action_on_timeout`. You can configure how instances will be added to the replacement environment in a blue/green deployment. `green_fleet_provisioning_option` supports the following: * `action` - (Optional) The method used to add instances to a replacement environment. - * `DISCOVER_EXISTING`: Use instances that already exist or will be created manually. - * `COPY_AUTO_SCALING_GROUP`: Use settings from a specified **Auto Scaling** group to define and create instances in a new Auto Scaling group. _Exactly one Auto Scaling group must be specified_ when selecting `COPY_AUTO_SCALING_GROUP`. Use `autoscaling_groups` to specify the Auto Scaling group. + * `DISCOVER_EXISTING`: Use instances that already exist or will be created manually. + * `COPY_AUTO_SCALING_GROUP`: Use settings from a specified **Auto Scaling** group to define and create instances in a new Auto Scaling group. _Exactly one Auto Scaling group must be specified_ when selecting `COPY_AUTO_SCALING_GROUP`. Use `autoscaling_groups` to specify the Auto Scaling group. You can configure how instances in the original environment are terminated when a blue/green deployment is successful. `terminate_blue_instances_on_deployment_success` supports the following: * `action` - (Optional) The action to take on instances in the original environment after a successful blue/green deployment. - * `TERMINATE`: Instances are terminated after a specified wait time. - * `KEEP_ALIVE`: Instances are left running after they are deregistered from the load balancer and removed from the deployment group. + * `TERMINATE`: Instances are terminated after a specified wait time. + * `KEEP_ALIVE`: Instances are left running after they are deregistered from the load balancer and removed from the deployment group. * `termination_wait_time_in_minutes` - (Optional) The number of minutes to wait after a successful blue/green deployment before terminating instances from the original environment. ### deployment_style Argument Reference diff --git a/website/docs/r/codepipeline.markdown b/website/docs/r/codepipeline.markdown index 6dea75f12d7..377580c1567 100644 --- a/website/docs/r/codepipeline.markdown +++ b/website/docs/r/codepipeline.markdown @@ -10,83 +10,19 @@ description: |- Provides a CodePipeline. -~> **NOTE on `aws_codepipeline`:** - the `GITHUB_TOKEN` environment variable must be set if the GitHub provider is specified. - ## Example Usage ```hcl -resource "aws_s3_bucket" "codepipeline_bucket" { - bucket = "test-bucket" - acl = "private" -} - -resource "aws_iam_role" "codepipeline_role" { - name = "test-role" - - assume_role_policy = < +``` diff --git a/website/docs/r/cognito_identity_provider.html.markdown b/website/docs/r/cognito_identity_provider.html.markdown index c41de80520a..3729b95a616 100644 --- a/website/docs/r/cognito_identity_provider.html.markdown +++ b/website/docs/r/cognito_identity_provider.html.markdown @@ -20,7 +20,7 @@ resource "aws_cognito_user_pool" "example" { } resource "aws_cognito_identity_provider" "example_provider" { - user_pool_id = "${aws_cognito_user_pool.example.id}" + user_pool_id = aws_cognito_user_pool.example.id provider_name = "Google" provider_type = "Google" diff --git a/website/docs/r/cognito_resource_server.markdown b/website/docs/r/cognito_resource_server.markdown index 9494e45eee6..b730f389100 100644 --- a/website/docs/r/cognito_resource_server.markdown +++ b/website/docs/r/cognito_resource_server.markdown @@ -24,7 +24,7 @@ resource "aws_cognito_resource_server" "resource" { identifier = "https://example.com" name = "example" - user_pool_id = "${aws_cognito_user_pool.pool.id}" + user_pool_id = aws_cognito_user_pool.pool.id } ``` @@ -44,7 +44,7 @@ resource "aws_cognito_resource_server" "resource" { scope_description = "a Sample Scope Description" } - user_pool_id = "${aws_cognito_user_pool.pool.id}" + user_pool_id = aws_cognito_user_pool.pool.id } ``` diff --git a/website/docs/r/cognito_user_group.html.markdown b/website/docs/r/cognito_user_group.html.markdown index 89bcadc3886..3dd4bd65068 100644 --- a/website/docs/r/cognito_user_group.html.markdown +++ b/website/docs/r/cognito_user_group.html.markdown @@ -47,10 +47,10 @@ EOF resource "aws_cognito_user_group" "main" { name = "user-group" - user_pool_id = "${aws_cognito_user_pool.main.id}" + user_pool_id = aws_cognito_user_pool.main.id description = "Managed by Terraform" precedence = 42 - role_arn = "${aws_iam_role.group_role.arn}" + role_arn = aws_iam_role.group_role.arn } ``` diff --git a/website/docs/r/cognito_user_pool.markdown b/website/docs/r/cognito_user_pool.markdown index 33786218db9..4710f924492 100644 --- a/website/docs/r/cognito_user_pool.markdown +++ b/website/docs/r/cognito_user_pool.markdown @@ -71,61 +71,60 @@ The following arguments are supported: #### Admin Create User Config - * `allow_admin_create_user_only` (Optional) - Set to True if only the administrator is allowed to create user profiles. Set to False if users can sign themselves up via an app. - * `invite_message_template` (Optional) - The [invite message template structure](#invite-message-template). - * `unused_account_validity_days` (Optional) - **DEPRECATED** Use password_policy.temporary_password_validity_days instead - The user account expiration limit, in days, after which the account is no longer usable. +* `allow_admin_create_user_only` (Optional) - Set to True if only the administrator is allowed to create user profiles. Set to False if users can sign themselves up via an app. +* `invite_message_template` (Optional) - The [invite message template structure](#invite-message-template). ##### Invite Message template - * `email_message` (Optional) - The message template for email messages. Must contain `{username}` and `{####}` placeholders, for username and temporary password, respectively. - * `email_subject` (Optional) - The subject line for email messages. - * `sms_message` (Optional) - The message template for SMS messages. Must contain `{username}` and `{####}` placeholders, for username and temporary password, respectively. +* `email_message` (Optional) - The message template for email messages. Must contain `{username}` and `{####}` placeholders, for username and temporary password, respectively. +* `email_subject` (Optional) - The subject line for email messages. +* `sms_message` (Optional) - The message template for SMS messages. Must contain `{username}` and `{####}` placeholders, for username and temporary password, respectively. #### Device Configuration - * `challenge_required_on_new_device` (Optional) - Indicates whether a challenge is required on a new device. Only applicable to a new device. - * `device_only_remembered_on_user_prompt` (Optional) - If true, a device is only remembered on user prompt. +* `challenge_required_on_new_device` (Optional) - Indicates whether a challenge is required on a new device. Only applicable to a new device. +* `device_only_remembered_on_user_prompt` (Optional) - If true, a device is only remembered on user prompt. #### Email Configuration - * `reply_to_email_address` (Optional) - The REPLY-TO email address. - * `source_arn` (Optional) - The ARN of the email source. - * `from_email_address` (Optional) - Sender’s email address or sender’s name with their email address (e.g. `john@smith.com` or `John Smith `) - * `email_sending_account` (Optional) - Instruct Cognito to either use its built-in functional or Amazon SES to send out emails. +* `reply_to_email_address` (Optional) - The REPLY-TO email address. +* `source_arn` (Optional) - The ARN of the SES verified email identity to to use. Required if `email_sending_account` is set to `DEVELOPER`. +* `from_email_address` (Optional) - Sender’s email address or sender’s display name with their email address (e.g. `john@example.com`, `John Smith ` or `\"John Smith Ph.D.\" `). Escaped double quotes are required around display names that contain certain characters as specified in [RFC 5322](https://tools.ietf.org/html/rfc5322). +* `email_sending_account` (Optional) - The email delivery method to use. `COGNITO_DEFAULT` for the default email functionality built into Cognito or `DEVELOPER` to use your Amazon SES configuration. #### Lambda Configuration - * `create_auth_challenge` (Optional) - The ARN of the lambda creating an authentication challenge. - * `custom_message` (Optional) - A custom Message AWS Lambda trigger. - * `define_auth_challenge` (Optional) - Defines the authentication challenge. - * `post_authentication` (Optional) - A post-authentication AWS Lambda trigger. - * `post_confirmation` (Optional) - A post-confirmation AWS Lambda trigger. - * `pre_authentication` (Optional) - A pre-authentication AWS Lambda trigger. - * `pre_sign_up` (Optional) - A pre-registration AWS Lambda trigger. - * `pre_token_generation` (Optional) - Allow to customize identity token claims before token generation. - * `user_migration` (Optional) - The user migration Lambda config type. - * `verify_auth_challenge_response` (Optional) - Verifies the authentication challenge response. +* `create_auth_challenge` (Optional) - The ARN of the lambda creating an authentication challenge. +* `custom_message` (Optional) - A custom Message AWS Lambda trigger. +* `define_auth_challenge` (Optional) - Defines the authentication challenge. +* `post_authentication` (Optional) - A post-authentication AWS Lambda trigger. +* `post_confirmation` (Optional) - A post-confirmation AWS Lambda trigger. +* `pre_authentication` (Optional) - A pre-authentication AWS Lambda trigger. +* `pre_sign_up` (Optional) - A pre-registration AWS Lambda trigger. +* `pre_token_generation` (Optional) - Allow to customize identity token claims before token generation. +* `user_migration` (Optional) - The user migration Lambda config type. +* `verify_auth_challenge_response` (Optional) - Verifies the authentication challenge response. #### Password Policy - * `minimum_length` (Optional) - The minimum length of the password policy that you have set. - * `require_lowercase` (Optional) - Whether you have required users to use at least one lowercase letter in their password. - * `require_numbers` (Optional) - Whether you have required users to use at least one number in their password. - * `require_symbols` (Optional) - Whether you have required users to use at least one symbol in their password. - * `require_uppercase` (Optional) - Whether you have required users to use at least one uppercase letter in their password. - * `temporary_password_validity_days` (Optional) - In the password policy you have set, refers to the number of days a temporary password is valid. If the user does not sign-in during this time, their password will need to be reset by an administrator. +* `minimum_length` (Optional) - The minimum length of the password policy that you have set. +* `require_lowercase` (Optional) - Whether you have required users to use at least one lowercase letter in their password. +* `require_numbers` (Optional) - Whether you have required users to use at least one number in their password. +* `require_symbols` (Optional) - Whether you have required users to use at least one symbol in their password. +* `require_uppercase` (Optional) - Whether you have required users to use at least one uppercase letter in their password. +* `temporary_password_validity_days` (Optional) - In the password policy you have set, refers to the number of days a temporary password is valid. If the user does not sign-in during this time, their password will need to be reset by an administrator. #### Schema Attributes ~> **NOTE:** When defining an `attribute_data_type` of `String` or `Number`, the respective attribute constraints configuration block (e.g `string_attribute_constraints` or `number_attribute_contraints`) is required to prevent recreation of the Terraform resource. This requirement is true for both standard (e.g. name, email) and custom schema attributes. - * `attribute_data_type` (Required) - The attribute data type. Must be one of `Boolean`, `Number`, `String`, `DateTime`. - * `developer_only_attribute` (Optional) - Specifies whether the attribute type is developer only. - * `mutable` (Optional) - Specifies whether the attribute can be changed once it has been created. - * `name` (Required) - The name of the attribute. - * `number_attribute_constraints` (Optional) - Specifies the [constraints for an attribute of the number type](#number-attribute-constraints). - * `required` (Optional) - Specifies whether a user pool attribute is required. If the attribute is required and the user does not provide a value, registration or sign-in will fail. - * `string_attribute_constraints` (Optional) -Specifies the [constraints for an attribute of the string type](#string-attribute-constraints). +* `attribute_data_type` (Required) - The attribute data type. Must be one of `Boolean`, `Number`, `String`, `DateTime`. +* `developer_only_attribute` (Optional) - Specifies whether the attribute type is developer only. +* `mutable` (Optional) - Specifies whether the attribute can be changed once it has been created. +* `name` (Required) - The name of the attribute. +* `number_attribute_constraints` (Optional) - Specifies the [constraints for an attribute of the number type](#number-attribute-constraints). +* `required` (Optional) - Specifies whether a user pool attribute is required. If the attribute is required and the user does not provide a value, registration or sign-in will fail. +* `string_attribute_constraints` (Optional) -Specifies the [constraints for an attribute of the string type](#string-attribute-constraints). ##### Defaults for Standard Attributes @@ -139,11 +138,11 @@ resource "aws_cognito_user_pool" "example" { name = "" attribute_data_type = "" developer_only_attribute = false - mutable = true // false for "sub" - required = false // true for "sub" - string_attribute_constraints { // if it's a string - min_length = 0 // 10 for "birthdate" - max_length = 2048 // 10 for "birthdate" + mutable = true # false for "sub" + required = false # true for "sub" + string_attribute_constraints { # if it is a string + min_length = 0 # 10 for "birthdate" + max_length = 2048 # 10 for "birthdate" } } } @@ -151,18 +150,18 @@ resource "aws_cognito_user_pool" "example" { ##### Number Attribute Constraints - * `max_value` (Optional) - The maximum value of an attribute that is of the number data type. - * `min_value` (Optional) - The minimum value of an attribute that is of the number data type. +* `max_value` (Optional) - The maximum value of an attribute that is of the number data type. +* `min_value` (Optional) - The minimum value of an attribute that is of the number data type. ##### String Attribute Constraints - * `max_length` (Optional) - The maximum length of an attribute value of the string type. - * `min_length` (Optional) - The minimum length of an attribute value of the string type. +* `max_length` (Optional) - The maximum length of an attribute value of the string type. +* `min_length` (Optional) - The minimum length of an attribute value of the string type. #### SMS Configuration - * `external_id` (Required) - The external ID used in IAM role trust relationships. For more information about using external IDs, see [How to Use an External ID When Granting Access to Your AWS Resources to a Third Party](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html). - * `sns_caller_arn` (Required) - The ARN of the Amazon SNS caller. This is usually the IAM role that you've given Cognito permission to assume. +* `external_id` (Required) - The external ID used in IAM role trust relationships. For more information about using external IDs, see [How to Use an External ID When Granting Access to Your AWS Resources to a Third Party](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html). +* `sns_caller_arn` (Required) - The ARN of the Amazon SNS caller. This is usually the IAM role that you've given Cognito permission to assume. ### Software Token MFA Configuration @@ -172,20 +171,20 @@ The following arguments are required in the `software_token_mfa_configuration` c #### Username Configuration - * `case_sensitive` (Required) - Specifies whether username case sensitivity will be applied for all users in the user pool through Cognito APIs. +* `case_sensitive` (Required) - Specifies whether username case sensitivity will be applied for all users in the user pool through Cognito APIs. #### User Pool Add-ons - * `advanced_security_mode` (Required) - The mode for advanced security, must be one of `OFF`, `AUDIT` or `ENFORCED`. +* `advanced_security_mode` (Required) - The mode for advanced security, must be one of `OFF`, `AUDIT` or `ENFORCED`. #### Verification Message Template - * `default_email_option` (Optional) - The default email option. Must be either `CONFIRM_WITH_CODE` or `CONFIRM_WITH_LINK`. Defaults to `CONFIRM_WITH_CODE`. - * `email_message` (Optional) - The email message template. Must contain the `{####}` placeholder. Conflicts with `email_verification_message` argument. - * `email_message_by_link` (Optional) - The email message template for sending a confirmation link to the user, it must contain the `{##Click Here##}` placeholder. - * `email_subject` (Optional) - The subject line for the email message template. Conflicts with `email_verification_subject` argument. - * `email_subject_by_link` (Optional) - The subject line for the email message template for sending a confirmation link to the user. - * `sms_message` (Optional) - The SMS message template. Must contain the `{####}` placeholder. Conflicts with `sms_verification_message` argument. +* `default_email_option` (Optional) - The default email option. Must be either `CONFIRM_WITH_CODE` or `CONFIRM_WITH_LINK`. Defaults to `CONFIRM_WITH_CODE`. +* `email_message` (Optional) - The email message template. Must contain the `{####}` placeholder. Conflicts with `email_verification_message` argument. +* `email_message_by_link` (Optional) - The email message template for sending a confirmation link to the user, it must contain the `{##Click Here##}` placeholder. +* `email_subject` (Optional) - The subject line for the email message template. Conflicts with `email_verification_subject` argument. +* `email_subject_by_link` (Optional) - The subject line for the email message template for sending a confirmation link to the user. +* `sms_message` (Optional) - The SMS message template. Must contain the `{####}` placeholder. Conflicts with `sms_verification_message` argument. ## Attribute Reference diff --git a/website/docs/r/cognito_user_pool_client.markdown b/website/docs/r/cognito_user_pool_client.markdown index 25a6687a6e0..b28fc9a18e9 100644 --- a/website/docs/r/cognito_user_pool_client.markdown +++ b/website/docs/r/cognito_user_pool_client.markdown @@ -22,7 +22,7 @@ resource "aws_cognito_user_pool" "pool" { resource "aws_cognito_user_pool_client" "client" { name = "client" - user_pool_id = "${aws_cognito_user_pool.pool.id}" + user_pool_id = aws_cognito_user_pool.pool.id } ``` @@ -36,7 +36,7 @@ resource "aws_cognito_user_pool" "pool" { resource "aws_cognito_user_pool_client" "client" { name = "client" - user_pool_id = "${aws_cognito_user_pool.pool.id}" + user_pool_id = aws_cognito_user_pool.pool.id generate_secret = true explicit_auth_flows = ["ADMIN_NO_SRP_AUTH"] @@ -78,33 +78,33 @@ EOF resource "aws_iam_role_policy" "test" { name = "role_policy" - role = "${aws_iam_role.test.id}" + role = aws_iam_role.test.id policy = <<-EOF - { - "Version": "2012-10-17", - "Statement": [ - { - "Action": [ - "mobiletargeting:UpdateEndpoint", - "mobiletargeting:PutItems" - ], - "Effect": "Allow", - "Resource": "arn:aws:mobiletargeting:*:${data.aws_caller_identity.current.account_id}:apps/${aws_pinpoint_app.test.application_id}*" - } - ] - } - EOF +{ + "Version": "2012-10-17", + "Statement": [ + { + "Action": [ + "mobiletargeting:UpdateEndpoint", + "mobiletargeting:PutItems" + ], + "Effect": "Allow", + "Resource": "arn:aws:mobiletargeting:*:${data.aws_caller_identity.current.account_id}:apps/${aws_pinpoint_app.test.application_id}*" + } + ] +} +EOF } resource "aws_cognito_user_pool_client" "test" { name = "pool_client" - user_pool_id = "${aws_cognito_user_pool.test.id}" + user_pool_id = aws_cognito_user_pool.test.id analytics_configuration { - application_id = "${aws_pinpoint_app.test.application_id}" + application_id = aws_pinpoint_app.test.application_id external_id = "some_id" - role_arn = "${aws_iam_role.test.arn}" + role_arn = aws_iam_role.test.arn user_data_shared = true } } diff --git a/website/docs/r/cognito_user_pool_domain.markdown b/website/docs/r/cognito_user_pool_domain.markdown index 3cbe0f54f1f..595ec23d3d6 100644 --- a/website/docs/r/cognito_user_pool_domain.markdown +++ b/website/docs/r/cognito_user_pool_domain.markdown @@ -17,7 +17,7 @@ Provides a Cognito User Pool Domain resource. ```hcl resource "aws_cognito_user_pool_domain" "main" { domain = "example-domain" - user_pool_id = "${aws_cognito_user_pool.example.id}" + user_pool_id = aws_cognito_user_pool.example.id } resource "aws_cognito_user_pool" "example" { @@ -30,16 +30,30 @@ resource "aws_cognito_user_pool" "example" { ```hcl resource "aws_cognito_user_pool_domain" "main" { domain = "example-domain.example.com" - certificate_arn = "${aws_acm_certificate.cert.arn}" - user_pool_id = "${aws_cognito_user_pool.example.id}" + certificate_arn = aws_acm_certificate.cert.arn + user_pool_id = aws_cognito_user_pool.example.id } resource "aws_cognito_user_pool" "example" { name = "example-pool" } -``` +data "aws_route53_zone" "example" { + name = "example.com" +} +resource "aws_route53_record" "auth-cognito-A" { + name = aws_cognito_user_pool_domain.main.domain + type = "A" + zone_id = data.aws_route53_zone.example.zone_id + alias { + evaluate_target_health = false + name = aws_cognito_user_pool_domain.main.cloudfront_distribution_arn + # This zone_id is fixed + zone_id = "Z2FDTNDATAQYW2" + } +} +``` ## Argument Reference @@ -54,7 +68,7 @@ The following arguments are supported: In addition to all arguments above, the following attributes are exported: * `aws_account_id` - The AWS account ID for the user pool owner. -* `cloudfront_distribution_arn` - The ARN of the CloudFront distribution. +* `cloudfront_distribution_arn` - The URL of the CloudFront distribution. This is required to generate the ALIAS `aws_route53_record` * `s3_bucket` - The S3 bucket where the static files for this domain are stored. * `version` - The app version. diff --git a/website/docs/r/config_config_rule.html.markdown b/website/docs/r/config_config_rule.html.markdown index 30a4df5f1f6..4b42d3a7d5a 100644 --- a/website/docs/r/config_config_rule.html.markdown +++ b/website/docs/r/config_config_rule.html.markdown @@ -27,12 +27,12 @@ resource "aws_config_config_rule" "r" { source_identifier = "S3_BUCKET_VERSIONING_ENABLED" } - depends_on = ["aws_config_configuration_recorder.foo"] + depends_on = [aws_config_configuration_recorder.foo] } resource "aws_config_configuration_recorder" "foo" { name = "example" - role_arn = "${aws_iam_role.r.arn}" + role_arn = aws_iam_role.r.arn } resource "aws_iam_role" "r" { @@ -57,7 +57,7 @@ POLICY resource "aws_iam_role_policy" "p" { name = "my-awsconfig-policy" - role = "${aws_iam_role.r.id}" + role = aws_iam_role.r.id policy = < **NOTE:** `dx_gateway_id` plus one of `associated_gateway_id`, or `vpn_gateway_id` must be specified for single account Direct Connect gateway associations. +~> **NOTE:** `dx_gateway_id` and `associated_gateway_id` must be specified for single account Direct Connect gateway associations. The following arguments are supported: * `dx_gateway_id` - (Required) The ID of the Direct Connect gateway. * `associated_gateway_id` - (Optional) The ID of the VGW or transit gateway with which to associate the Direct Connect gateway. Used for single account Direct Connect gateway associations. -* `vpn_gateway_id` - (Optional) *Deprecated:* Use `associated_gateway_id` instead. The ID of the VGW with which to associate the gateway. -Used for single account Direct Connect gateway associations. * `associated_gateway_owner_account_id` - (Optional) The ID of the AWS account that owns the VGW or transit gateway with which to associate the Direct Connect gateway. Used for cross-account Direct Connect gateway associations. * `proposal_id` - (Optional) The ID of the Direct Connect gateway association proposal. @@ -119,9 +118,9 @@ In addition to all arguments above, the following attributes are exported: `aws_dx_gateway_association` provides the following [Timeouts](/docs/configuration/resources.html#timeouts) configuration options: -- `create` - (Default `15 minutes`) Used for creating the association -- `update` - (Default `10 minutes`) Used for updating the association -- `delete` - (Default `15 minutes`) Used for destroying the association +- `create` - (Default `30 minutes`) Used for creating the association +- `update` - (Default `30 minutes`) Used for updating the association +- `delete` - (Default `30 minutes`) Used for destroying the association ## Import diff --git a/website/docs/r/dx_gateway_association_proposal.html.markdown b/website/docs/r/dx_gateway_association_proposal.html.markdown index 630ab642302..9ca61eb174d 100644 --- a/website/docs/r/dx_gateway_association_proposal.html.markdown +++ b/website/docs/r/dx_gateway_association_proposal.html.markdown @@ -14,9 +14,9 @@ Manages a Direct Connect Gateway Association Proposal, typically for enabling cr ```hcl resource "aws_dx_gateway_association_proposal" "example" { - dx_gateway_id = "${aws_dx_gateway.example.id}" - dx_gateway_owner_account_id = "${aws_dx_gateway.example.owner_account_id}" - associated_gateway_id = "${aws_vpn_gateway.example.id}" + dx_gateway_id = aws_dx_gateway.example.id + dx_gateway_owner_account_id = aws_dx_gateway.example.owner_account_id + associated_gateway_id = aws_vpn_gateway.example.id } ``` @@ -24,14 +24,11 @@ A full example of how to create a VPN Gateway in one AWS account, create a Direc ## Argument Reference -~> **NOTE:** One of `associated_gateway_id`, or `vpn_gateway_id` must be specified. - The following arguments are supported: +* `associated_gateway_id` - (Required) The ID of the VGW or transit gateway with which to associate the Direct Connect gateway. * `dx_gateway_id` - (Required) Direct Connect Gateway identifier. * `dx_gateway_owner_account_id` - (Required) AWS Account identifier of the Direct Connect Gateway's owner. -* `associated_gateway_id` - (Optional) The ID of the VGW or transit gateway with which to associate the Direct Connect gateway. -* `vpn_gateway_id` - (Optional) *Deprecated:* Use `associated_gateway_id` instead. Virtual Gateway identifier to associate with the Direct Connect Gateway. * `allowed_prefixes` - (Optional) VPC prefixes (CIDRs) to advertise to the Direct Connect gateway. Defaults to the CIDR block of the VPC associated with the Virtual Gateway. To enable drift detection, must be configured. ## Attributes Reference diff --git a/website/docs/r/dx_hosted_private_virtual_interface_accepter.html.markdown b/website/docs/r/dx_hosted_private_virtual_interface_accepter.html.markdown index 441cbc00741..cd10037105a 100644 --- a/website/docs/r/dx_hosted_private_virtual_interface_accepter.html.markdown +++ b/website/docs/r/dx_hosted_private_virtual_interface_accepter.html.markdown @@ -25,13 +25,13 @@ provider "aws" { } data "aws_caller_identity" "accepter" { - provider = "aws.accepter" + provider = aws.accepter } # Creator's side of the VIF resource "aws_dx_hosted_private_virtual_interface" "creator" { connection_id = "dxcon-zzzzzzzz" - owner_account_id = "${data.aws_caller_identity.accepter.account_id}" + owner_account_id = data.aws_caller_identity.accepter.account_id name = "vif-foo" vlan = 4094 @@ -40,18 +40,18 @@ resource "aws_dx_hosted_private_virtual_interface" "creator" { # The aws_dx_hosted_private_virtual_interface # must be destroyed before the aws_vpn_gateway. - depends_on = ["aws_vpn_gateway.vpn_gw"] + depends_on = [aws_vpn_gateway.vpn_gw] } # Accepter's side of the VIF. resource "aws_vpn_gateway" "vpn_gw" { - provider = "aws.accepter" + provider = aws.accepter } resource "aws_dx_hosted_private_virtual_interface_accepter" "accepter" { - provider = "aws.accepter" - virtual_interface_id = "${aws_dx_hosted_private_virtual_interface.creator.id}" - vpn_gateway_id = "${aws_vpn_gateway.vpn_gw.id}" + provider = aws.accepter + virtual_interface_id = aws_dx_hosted_private_virtual_interface.creator.id + vpn_gateway_id = aws_vpn_gateway.vpn_gw.id tags = { Side = "Accepter" diff --git a/website/docs/r/dx_hosted_public_virtual_interface_accepter.html.markdown b/website/docs/r/dx_hosted_public_virtual_interface_accepter.html.markdown index 41c6ceaf6be..dc07803b6c5 100644 --- a/website/docs/r/dx_hosted_public_virtual_interface_accepter.html.markdown +++ b/website/docs/r/dx_hosted_public_virtual_interface_accepter.html.markdown @@ -25,13 +25,13 @@ provider "aws" { } data "aws_caller_identity" "accepter" { - provider = "aws.accepter" + provider = aws.accepter } # Creator's side of the VIF resource "aws_dx_hosted_public_virtual_interface" "creator" { connection_id = "dxcon-zzzzzzzz" - owner_account_id = "${data.aws_caller_identity.accepter.account_id}" + owner_account_id = data.aws_caller_identity.accepter.account_id name = "vif-foo" vlan = 4094 @@ -49,8 +49,8 @@ resource "aws_dx_hosted_public_virtual_interface" "creator" { # Accepter's side of the VIF. resource "aws_dx_hosted_public_virtual_interface_accepter" "accepter" { - provider = "aws.accepter" - virtual_interface_id = "${aws_dx_hosted_public_virtual_interface.creator.id}" + provider = aws.accepter + virtual_interface_id = aws_dx_hosted_public_virtual_interface.creator.id tags = { Side = "Accepter" diff --git a/website/docs/r/dx_hosted_transit_virtual_interface.html.markdown b/website/docs/r/dx_hosted_transit_virtual_interface.html.markdown index 4827b1ed07b..75718b5caf5 100644 --- a/website/docs/r/dx_hosted_transit_virtual_interface.html.markdown +++ b/website/docs/r/dx_hosted_transit_virtual_interface.html.markdown @@ -16,7 +16,7 @@ A hosted virtual interface is a virtual interface that is owned by another AWS a ```hcl resource "aws_dx_hosted_transit_virtual_interface" "example" { - connection_id = "${aws_dx_connection.example.id}" + connection_id = aws_dx_connection.example.id name = "tf-transit-vif-example" vlan = 4094 diff --git a/website/docs/r/dx_hosted_transit_virtual_interface_accepter.html.markdown b/website/docs/r/dx_hosted_transit_virtual_interface_accepter.html.markdown index 675b74f006d..d3cf96e8047 100644 --- a/website/docs/r/dx_hosted_transit_virtual_interface_accepter.html.markdown +++ b/website/docs/r/dx_hosted_transit_virtual_interface_accepter.html.markdown @@ -27,13 +27,13 @@ provider "aws" { } data "aws_caller_identity" "accepter" { - provider = "aws.accepter" + provider = aws.accepter } # Creator's side of the VIF resource "aws_dx_hosted_transit_virtual_interface" "creator" { connection_id = "dxcon-zzzzzzzz" - owner_account_id = "${data.aws_caller_identity.accepter.account_id}" + owner_account_id = data.aws_caller_identity.accepter.account_id name = "tf-transit-vif-example" vlan = 4094 @@ -42,21 +42,21 @@ resource "aws_dx_hosted_transit_virtual_interface" "creator" { # The aws_dx_hosted_transit_virtual_interface # must be destroyed before the aws_dx_gateway. - depends_on = ["aws_dx_gateway.example"] + depends_on = [aws_dx_gateway.example] } # Accepter's side of the VIF. resource "aws_dx_gateway" "example" { - provider = "aws.accepter" + provider = aws.accepter name = "tf-dxg-example" amazon_side_asn = 64512 } resource "aws_dx_hosted_transit_virtual_interface_accepter" "accepter" { - provider = "aws.accepter" - virtual_interface_id = "${aws_dx_hosted_transit_virtual_interface.creator.id}" - dx_gateway_id = "${aws_dx_gateway.example.id}" + provider = aws.accepter + virtual_interface_id = aws_dx_hosted_transit_virtual_interface.creator.id + dx_gateway_id = aws_dx_gateway.example.id tags = { Side = "Accepter" diff --git a/website/docs/r/dx_transit_virtual_interface.html.markdown b/website/docs/r/dx_transit_virtual_interface.html.markdown index f6de8c94e2b..c45b35462d9 100644 --- a/website/docs/r/dx_transit_virtual_interface.html.markdown +++ b/website/docs/r/dx_transit_virtual_interface.html.markdown @@ -20,9 +20,9 @@ resource "aws_dx_gateway" "example" { } resource "aws_dx_transit_virtual_interface" "example" { - connection_id = "${aws_dx_connection.example.id}" + connection_id = aws_dx_connection.example.id - dx_gateway_id = "${aws_dx_gateway.example.id}" + dx_gateway_id = aws_dx_gateway.example.id name = "tf-transit-vif-example" vlan = 4094 address_family = "ipv4" diff --git a/website/docs/r/dynamodb_global_table.html.markdown b/website/docs/r/dynamodb_global_table.html.markdown index e873f9a1251..4e7b93ec503 100644 --- a/website/docs/r/dynamodb_global_table.html.markdown +++ b/website/docs/r/dynamodb_global_table.html.markdown @@ -28,7 +28,7 @@ provider "aws" { } resource "aws_dynamodb_table" "us-east-1" { - provider = "aws.us-east-1" + provider = aws.us-east-1 hash_key = "myAttribute" name = "myTable" @@ -44,7 +44,7 @@ resource "aws_dynamodb_table" "us-east-1" { } resource "aws_dynamodb_table" "us-west-2" { - provider = "aws.us-west-2" + provider = aws.us-west-2 hash_key = "myAttribute" name = "myTable" @@ -60,8 +60,11 @@ resource "aws_dynamodb_table" "us-west-2" { } resource "aws_dynamodb_global_table" "myTable" { - depends_on = ["aws_dynamodb_table.us-east-1", "aws_dynamodb_table.us-west-2"] - provider = "aws.us-east-1" + depends_on = [ + aws_dynamodb_table.us-east-1, + aws_dynamodb_table.us-west-2, + ] + provider = aws.us-east-1 name = "myTable" diff --git a/website/docs/r/dynamodb_table.html.markdown b/website/docs/r/dynamodb_table.html.markdown index 8b096f9ff0e..7ad39137702 100644 --- a/website/docs/r/dynamodb_table.html.markdown +++ b/website/docs/r/dynamodb_table.html.markdown @@ -102,11 +102,11 @@ The following arguments are supported: * `write_capacity` - (Optional) The number of write units for this table. If the `billing_mode` is `PROVISIONED`, this field is required. * `read_capacity` - (Optional) The number of read units for this table. If the `billing_mode` is `PROVISIONED`, this field is required. * `attribute` - (Required) List of nested attribute definitions. Only required for `hash_key` and `range_key` attributes. Each attribute has two properties: - * `name` - (Required) The name of the attribute - * `type` - (Required) Attribute type, which must be a scalar type: `S`, `N`, or `B` for (S)tring, (N)umber or (B)inary data + * `name` - (Required) The name of the attribute + * `type` - (Required) Attribute type, which must be a scalar type: `S`, `N`, or `B` for (S)tring, (N)umber or (B)inary data * `ttl` - (Optional) Defines ttl, has two properties, and can only be specified once: - * `enabled` - (Required) Indicates whether ttl is enabled (true) or disabled (false). - * `attribute_name` - (Required) The name of the table attribute to store the TTL timestamp in. + * `enabled` - (Required) Indicates whether ttl is enabled (true) or disabled (false). + * `attribute_name` - (Required) The name of the table attribute to store the TTL timestamp in. * `local_secondary_index` - (Optional, Forces new resource) Describe an LSI on the table; these can only be allocated *at creation* so you cannot change this definition after you have created the resource. diff --git a/website/docs/r/dynamodb_table_item.html.markdown b/website/docs/r/dynamodb_table_item.html.markdown index e2945c8760c..5b7e71a1701 100644 --- a/website/docs/r/dynamodb_table_item.html.markdown +++ b/website/docs/r/dynamodb_table_item.html.markdown @@ -17,8 +17,8 @@ Provides a DynamoDB table item resource ```hcl resource "aws_dynamodb_table_item" "example" { - table_name = "${aws_dynamodb_table.example.name}" - hash_key = "${aws_dynamodb_table.example.hash_key}" + table_name = aws_dynamodb_table.example.name + hash_key = aws_dynamodb_table.example.hash_key item = < **NOTE:** This tagging resource should not be combined with the Terraform resource for managing the parent resource. For example, using `aws_vpc` and `aws_ec2_tag` to manage tags of the same VPC will cause a perpetual difference where the `aws_vpc` resource will try to remove the tag being added by the `aws_ec2_tag` resource. + +~> **NOTE:** This tagging resource does not use the [provider `ignore_tags` configuration](/docs/providers/aws/index.html#ignore_tags). + +## Example Usage + +```hcl +resource "aws_ec2_transit_gateway" "example" {} + +resource "aws_customer_gateway" "example" { + bgp_asn = 65000 + ip_address = "172.0.0.1" + type = "ipsec.1" +} + +resource "aws_vpn_connection" "example" { + customer_gateway_id = aws_customer_gateway.example.id + transit_gateway_id = aws_ec2_transit_gateway.example.id + type = aws_customer_gateway.example.type +} + +resource "aws_ec2_tag" "example" { + resource_id = aws_vpn_connection.example.transit_gateway_attachment_id + key = "Name" + value = "Hello World" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `resource_id` - (Required) The ID of the EC2 resource to manage the tag for. +* `key` - (Required) The tag name. +* `value` - (Required) The value of the tag. + +## Attribute Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - EC2 resource identifier and key, separated by a comma (`,`) + +## Import + +`aws_ec2_tag` can be imported by using the EC2 resource identifier and key, separated by a comma (`,`), e.g. + +``` +$ terraform import aws_ec2_tag.example tgw-attach-1234567890abcdef,Name +``` diff --git a/website/docs/r/ec2_traffic_mirror_filter_rule.html.markdown b/website/docs/r/ec2_traffic_mirror_filter_rule.html.markdown index 759fdf8888e..2c2d5230055 100644 --- a/website/docs/r/ec2_traffic_mirror_filter_rule.html.markdown +++ b/website/docs/r/ec2_traffic_mirror_filter_rule.html.markdown @@ -23,7 +23,7 @@ resource "aws_ec2_traffic_mirror_filter" "filter" { resource "aws_ec2_traffic_mirror_filter_rule" "ruleout" { description = "test rule" - traffic_mirror_filter_id = "${aws_ec2_traffic_mirror_filter.filter.id}" + traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id destination_cidr_block = "10.0.0.0/8" source_cidr_block = "10.0.0.0/8" rule_number = 1 @@ -33,7 +33,7 @@ resource "aws_ec2_traffic_mirror_filter_rule" "ruleout" { resource "aws_ec2_traffic_mirror_filter_rule" "rulein" { description = "test rule" - traffic_mirror_filter_id = "${aws_ec2_traffic_mirror_filter.filter.id}" + traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id destination_cidr_block = "10.0.0.0/8" source_cidr_block = "10.0.0.0/8" rule_number = 1 diff --git a/website/docs/r/ec2_traffic_mirror_session.html.markdown b/website/docs/r/ec2_traffic_mirror_session.html.markdown index 82e48f87ba5..eea93334e2a 100644 --- a/website/docs/r/ec2_traffic_mirror_session.html.markdown +++ b/website/docs/r/ec2_traffic_mirror_session.html.markdown @@ -22,14 +22,14 @@ resource "aws_ec2_traffic_mirror_filter" "filter" { } resource "aws_ec2_traffic_mirror_target" "target" { - network_load_balancer_arn = "${aws_lb.lb.arn}" + network_load_balancer_arn = aws_lb.lb.arn } resource "aws_ec2_traffic_mirror_session" "session" { description = "traffic mirror session - terraform example" - network_interface_id = "${aws_instance.test.primary_network_interface_id}" - traffic_mirror_filter_id = "${aws_ec2_traffic_mirror_filter.filter.id}" - traffic_mirror_target_id = "${aws_ec2_traffic_mirror_target.target.id}" + network_interface_id = aws_instance.test.primary_network_interface_id + traffic_mirror_filter_id = aws_ec2_traffic_mirror_filter.filter.id + traffic_mirror_target_id = aws_ec2_traffic_mirror_target.target.id } ``` @@ -50,6 +50,7 @@ The following arguments are supported: In addition to all arguments above, the following attributes are exported: +* `arn` - The ARN of the traffic mirror session. * `id` - The name of the session. ## Import diff --git a/website/docs/r/ec2_traffic_mirror_target.html.markdown b/website/docs/r/ec2_traffic_mirror_target.html.markdown index 67390c2c2a5..cc185772723 100644 --- a/website/docs/r/ec2_traffic_mirror_target.html.markdown +++ b/website/docs/r/ec2_traffic_mirror_target.html.markdown @@ -18,14 +18,13 @@ To create a basic traffic mirror session ```hcl resource "aws_ec2_traffic_mirror_target" "nlb" { description = "NLB target" - network_load_balancer_arn = "${aws_lb.lb.arn}" + network_load_balancer_arn = aws_lb.lb.arn } resource "aws_ec2_traffic_mirror_target" "eni" { description = "ENI target" - network_interface_id = "${aws_instance.test.primary_network_interface_id}" + network_interface_id = aws_instance.test.primary_network_interface_id } - ``` ## Argument Reference @@ -43,7 +42,8 @@ The following arguments are supported: In addition to all arguments above, the following attributes are exported: -* `id` - The name of the traffic mirror target. +* `id` - The ID of the Traffic Mirror target. +* `arn` - The ARN of the traffic mirror target. ## Import diff --git a/website/docs/r/ec2_transit_gateway_peering_attachment_accepter.markdown b/website/docs/r/ec2_transit_gateway_peering_attachment_accepter.markdown index e9ea181158e..cc8138fcfb5 100644 --- a/website/docs/r/ec2_transit_gateway_peering_attachment_accepter.markdown +++ b/website/docs/r/ec2_transit_gateway_peering_attachment_accepter.markdown @@ -14,7 +14,7 @@ Manages the accepter's side of an EC2 Transit Gateway Peering Attachment. ```hcl resource "aws_ec2_transit_gateway_peering_attachment_accepter" "example" { - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_peering_attachment.example.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_peering_attachment.example.id tags = { Name = "Example cross-account attachment" diff --git a/website/docs/r/ec2_transit_gateway_route.html.markdown b/website/docs/r/ec2_transit_gateway_route.html.markdown index 49309eb8c6f..5f2178e7a9c 100644 --- a/website/docs/r/ec2_transit_gateway_route.html.markdown +++ b/website/docs/r/ec2_transit_gateway_route.html.markdown @@ -17,8 +17,8 @@ Manages an EC2 Transit Gateway Route. ```hcl resource "aws_ec2_transit_gateway_route" "example" { destination_cidr_block = "0.0.0.0/0" - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.example.id}" - transit_gateway_route_table_id = "${aws_ec2_transit_gateway.example.association_default_route_table_id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.example.id + transit_gateway_route_table_id = aws_ec2_transit_gateway.example.association_default_route_table_id } ``` @@ -28,7 +28,7 @@ resource "aws_ec2_transit_gateway_route" "example" { resource "aws_ec2_transit_gateway_route" "example" { destination_cidr_block = "0.0.0.0/0" blackhole = true - transit_gateway_route_table_id = "${aws_ec2_transit_gateway.example.association_default_route_table_id}" + transit_gateway_route_table_id = aws_ec2_transit_gateway.example.association_default_route_table_id } ``` diff --git a/website/docs/r/ec2_transit_gateway_route_table.html.markdown b/website/docs/r/ec2_transit_gateway_route_table.html.markdown index b6930be5ad7..11ece824804 100644 --- a/website/docs/r/ec2_transit_gateway_route_table.html.markdown +++ b/website/docs/r/ec2_transit_gateway_route_table.html.markdown @@ -14,7 +14,7 @@ Manages an EC2 Transit Gateway Route Table. ```hcl resource "aws_ec2_transit_gateway_route_table" "example" { - transit_gateway_id = "${aws_ec2_transit_gateway.example.id}" + transit_gateway_id = aws_ec2_transit_gateway.example.id } ``` diff --git a/website/docs/r/ec2_transit_gateway_route_table_association.html.markdown b/website/docs/r/ec2_transit_gateway_route_table_association.html.markdown index df43bbea233..a5ca3c69bdd 100644 --- a/website/docs/r/ec2_transit_gateway_route_table_association.html.markdown +++ b/website/docs/r/ec2_transit_gateway_route_table_association.html.markdown @@ -14,8 +14,8 @@ Manages an EC2 Transit Gateway Route Table association. ```hcl resource "aws_ec2_transit_gateway_route_table_association" "example" { - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.example.id}" - transit_gateway_route_table_id = "${aws_ec2_transit_gateway_route_table.example.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.example.id + transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.example.id } ``` diff --git a/website/docs/r/ec2_transit_gateway_route_table_propagation.html.markdown b/website/docs/r/ec2_transit_gateway_route_table_propagation.html.markdown index 761b9be5533..f5e60ee46ca 100644 --- a/website/docs/r/ec2_transit_gateway_route_table_propagation.html.markdown +++ b/website/docs/r/ec2_transit_gateway_route_table_propagation.html.markdown @@ -14,8 +14,8 @@ Manages an EC2 Transit Gateway Route Table propagation. ```hcl resource "aws_ec2_transit_gateway_route_table_propagation" "example" { - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.example.id}" - transit_gateway_route_table_id = "${aws_ec2_transit_gateway_route_table.example.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.example.id + transit_gateway_route_table_id = aws_ec2_transit_gateway_route_table.example.id } ``` diff --git a/website/docs/r/ec2_transit_gateway_vpc_attachment.html.markdown b/website/docs/r/ec2_transit_gateway_vpc_attachment.html.markdown index 4b4ac866aaa..1fa5c09bca5 100644 --- a/website/docs/r/ec2_transit_gateway_vpc_attachment.html.markdown +++ b/website/docs/r/ec2_transit_gateway_vpc_attachment.html.markdown @@ -14,9 +14,9 @@ Manages an EC2 Transit Gateway VPC Attachment. For examples of custom route tabl ```hcl resource "aws_ec2_transit_gateway_vpc_attachment" "example" { - subnet_ids = ["${aws_subnet.example.id}"] - transit_gateway_id = "${aws_ec2_transit_gateway.example.id}" - vpc_id = "${aws_vpc.example.id}" + subnet_ids = [aws_subnet.example.id] + transit_gateway_id = aws_ec2_transit_gateway.example.id + vpc_id = aws_vpc.example.id } ``` diff --git a/website/docs/r/ec2_transit_gateway_vpc_attachment_accepter.html.markdown b/website/docs/r/ec2_transit_gateway_vpc_attachment_accepter.html.markdown index a601395e1ac..ac4925055e0 100644 --- a/website/docs/r/ec2_transit_gateway_vpc_attachment_accepter.html.markdown +++ b/website/docs/r/ec2_transit_gateway_vpc_attachment_accepter.html.markdown @@ -20,7 +20,7 @@ connection into management. ```hcl resource "aws_ec2_transit_gateway_vpc_attachment_accepter" "example" { - transit_gateway_attachment_id = "${aws_ec2_transit_gateway_vpc_attachment.example.id}" + transit_gateway_attachment_id = aws_ec2_transit_gateway_vpc_attachment.example.id tags = { Name = "Example cross-account attachment" diff --git a/website/docs/r/ecr_lifecycle_policy.html.markdown b/website/docs/r/ecr_lifecycle_policy.html.markdown index 8d378c9e7aa..4db3efe103c 100644 --- a/website/docs/r/ecr_lifecycle_policy.html.markdown +++ b/website/docs/r/ecr_lifecycle_policy.html.markdown @@ -24,7 +24,7 @@ resource "aws_ecr_repository" "foo" { } resource "aws_ecr_lifecycle_policy" "foopolicy" { - repository = "${aws_ecr_repository.foo.name}" + repository = aws_ecr_repository.foo.name policy = < **NOTE:** The AWS API does not currently support deleting ECS cluster capacity providers. Removing this Terraform resource will only remove the Terraform state for it. +~> **NOTE:** Associating an ECS Capacity Provider to an Auto Scaling Group will automatically add the `AmazonECSManaged` tag to the Auto Scaling Group. This tag should be included in the `aws_autoscaling_group` resource configuration to prevent Terraform from removing it in subsequent executions as well as ensuring the `AmazonECSManaged` tag is propagated to all EC2 Instances in the Auto Scaling Group if `min_size` is above 0 on creation. Any EC2 Instances in the Auto Scaling Group without this tag must be manually be updated, otherwise they may cause unexpected scaling behavior and metrics. ## Example Usage ```hcl +resource "aws_autoscaling_group" "test" { + # ... other configuration, including potentially other tags ... + + tag { + key = "AmazonECSManaged" + propagate_at_launch = true + } +} + resource "aws_ecs_capacity_provider" "test" { name = "test" diff --git a/website/docs/r/ecs_service.html.markdown b/website/docs/r/ecs_service.html.markdown index 9603e2ac7b0..b5c8feaa33b 100644 --- a/website/docs/r/ecs_service.html.markdown +++ b/website/docs/r/ecs_service.html.markdown @@ -19,11 +19,11 @@ See [ECS Services section in AWS developer guide](https://docs.aws.amazon.com/Am ```hcl resource "aws_ecs_service" "mongo" { name = "mongodb" - cluster = "${aws_ecs_cluster.foo.id}" - task_definition = "${aws_ecs_task_definition.mongo.arn}" + cluster = aws_ecs_cluster.foo.id + task_definition = aws_ecs_task_definition.mongo.arn desired_count = 3 - iam_role = "${aws_iam_role.foo.arn}" - depends_on = ["aws_iam_role_policy.foo"] + iam_role = aws_iam_role.foo.arn + depends_on = [aws_iam_role_policy.foo] ordered_placement_strategy { type = "binpack" @@ -31,7 +31,7 @@ resource "aws_ecs_service" "mongo" { } load_balancer { - target_group_arn = "${aws_lb_target_group.foo.arn}" + target_group_arn = aws_lb_target_group.foo.arn container_name = "mongo" container_port = 8080 } @@ -56,7 +56,7 @@ resource "aws_ecs_service" "example" { # Optional: Allow external changes without Terraform plan difference lifecycle { - ignore_changes = ["desired_count"] + ignore_changes = [desired_count] } } ``` @@ -66,12 +66,25 @@ resource "aws_ecs_service" "example" { ```hcl resource "aws_ecs_service" "bar" { name = "bar" - cluster = "${aws_ecs_cluster.foo.id}" - task_definition = "${aws_ecs_task_definition.bar.arn}" + cluster = aws_ecs_cluster.foo.id + task_definition = aws_ecs_task_definition.bar.arn scheduling_strategy = "DAEMON" } ``` +### External Deployment Controller + +```hcl +resource "aws_ecs_service" "example" { + name = "example" + cluster = aws_ecs_cluster.example.id + + deployment_controller { + type = "EXTERNAL" + } +} +``` + ## Argument Reference The following arguments are supported: @@ -84,26 +97,26 @@ The following arguments are supported: * `deployment_minimum_healthy_percent` - (Optional) The lower limit (as a percentage of the service's desiredCount) of the number of running tasks that must remain running and healthy in a service during a deployment. * `desired_count` - (Optional) The number of instances of the task definition to place and keep running. Defaults to 0. Do not specify if using the `DAEMON` scheduling strategy. * `enable_ecs_managed_tags` - (Optional) Specifies whether to enable Amazon ECS managed tags for the tasks within the service. +* `force_new_deployment` - (Optional) Enable to force a new task deployment of the service. This can be used to update tasks to use a newer Docker image with same image/tag combination (e.g. `myimage:latest`), roll Fargate tasks onto a newer platform version, or immediately deploy `ordered_placement_strategy` and `placement_constraints` updates. * `health_check_grace_period_seconds` - (Optional) Seconds to ignore failing load balancer health checks on newly instantiated tasks to prevent premature shutdown, up to 2147483647. Only valid for services configured to use load balancers. * `iam_role` - (Optional) ARN of the IAM role that allows Amazon ECS to make calls to your load balancer on your behalf. This parameter is required if you are using a load balancer with your service, but only if your task definition does not use the `awsvpc` network mode. If using `awsvpc` network mode, do not specify this role. If your account has already created the Amazon ECS service-linked role, that role is used by default for your service unless you specify a role here. * `launch_type` - (Optional) The launch type on which to run your service. The valid values are `EC2` and `FARGATE`. Defaults to `EC2`. * `load_balancer` - (Optional) A load balancer block. Load balancers documented below. * `network_configuration` - (Optional) The network configuration for the service. This parameter is required for task definitions that use the `awsvpc` network mode to receive their own Elastic Network Interface, and it is not supported for other network modes. -* `ordered_placement_strategy` - (Optional) Service level strategy rules that are taken into consideration during task placement. List from top to bottom in order of precedence. The maximum number of `ordered_placement_strategy` blocks is `5`. Defined below. -* `placement_constraints` - (Optional) rules that are taken into consideration during task placement. Maximum number of -`placement_constraints` is `10`. Defined below. +* `ordered_placement_strategy` - (Optional) Service level strategy rules that are taken into consideration during task placement. List from top to bottom in order of precedence. Updates to this configuration will take effect next task deployment unless `force_new_deployment` is enabled. The maximum number of `ordered_placement_strategy` blocks is `5`. Defined below. +* `placement_constraints` - (Optional) rules that are taken into consideration during task placement. Updates to this configuration will take effect next task deployment unless `force_new_deployment` is enabled. Maximum number of `placement_constraints` is `10`. Defined below. * `platform_version` - (Optional) The platform version on which to run your service. Only applicable for `launch_type` set to `FARGATE`. Defaults to `LATEST`. More information about Fargate platform versions can be found in the [AWS ECS User Guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html). * `propagate_tags` - (Optional) Specifies whether to propagate the tags from the task definition or the service to the tasks. The valid values are `SERVICE` and `TASK_DEFINITION`. -* `scheduling_strategy` - (Optional) The scheduling strategy to use for the service. The valid values are `REPLICA` and `DAEMON`. Defaults to `REPLICA`. Note that [*Fargate tasks do not support the `DAEMON` scheduling strategy*](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/scheduling_tasks.html). +* `scheduling_strategy` - (Optional) The scheduling strategy to use for the service. The valid values are `REPLICA` and `DAEMON`. Defaults to `REPLICA`. Note that [*Tasks using the Fargate launch type or the `CODE_DEPLOY` or `EXTERNAL` deployment controller types don't support the `DAEMON` scheduling strategy*](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html). * `service_registries` - (Optional) The service discovery registries for the service. The maximum number of `service_registries` blocks is `1`. * `tags` - (Optional) Key-value map of resource tags -* `task_definition` - (Required) The family and revision (`family:revision`) or full ARN of the task definition that you want to run in your service. +* `task_definition` - (Optional) The family and revision (`family:revision`) or full ARN of the task definition that you want to run in your service. Required unless using the `EXTERNAL` deployment controller. If a revision is not specified, the latest `ACTIVE` revision is used. ## capacity_provider_strategy The `capacity_provider_strategy` configuration block supports the following: -* `capacity_provider` - (Required) The short name or full Amazon Resource Name (ARN) of the capacity provider. +* `capacity_provider` - (Required) The short name of the capacity provider. * `weight` - (Required) The relative percentage of the total number of launched tasks that should use the specified capacity provider. * `base` - (Optional) The number of tasks, at a minimum, to run on the specified capacity provider. Only one capacity provider in a capacity provider strategy can have a base defined. @@ -111,7 +124,7 @@ The `capacity_provider_strategy` configuration block supports the following: The `deployment_controller` configuration block supports the following: -* `type` - (Optional) Type of deployment controller. Valid values: `CODE_DEPLOY`, `ECS`. Default: `ECS`. +* `type` - (Optional) Type of deployment controller. Valid values: `CODE_DEPLOY`, `ECS`, `EXTERNAL`. Default: `ECS`. ## load_balancer @@ -176,6 +189,13 @@ In addition to all arguments above, the following attributes are exported: * `iam_role` - The ARN of IAM role used for ELB * `desired_count` - The number of instances of the task definition +## Timeouts + +`aws_ecs_service` provides the following +[Timeouts](/docs/configuration/resources.html#operation-timeouts) configuration options: + +- `delete` - (Default `20 minutes`) + ## Import ECS services can be imported using the `name` together with ecs cluster `name`, e.g. diff --git a/website/docs/r/ecs_task_definition.html.markdown b/website/docs/r/ecs_task_definition.html.markdown index e67517716d4..661d1c3784a 100644 --- a/website/docs/r/ecs_task_definition.html.markdown +++ b/website/docs/r/ecs_task_definition.html.markdown @@ -120,7 +120,7 @@ official [Developer Guide](https://docs.aws.amazon.com/AmazonECS/latest/develope parameter of container definition in the `mountPoints` section. * `host_path` - (Optional) The path on the host container instance that is presented to the container. If not set, ECS will create a nonpersistent data volume that starts empty and is deleted after the task has finished. * `docker_volume_configuration` - (Optional) Used to configure a [docker volume](#docker-volume-configuration-arguments) -* `efs_volume_configuration` - (Optional) Used to configure a [EFS volume](#efs-volume-configuration-arguments). Can be used only with an EC2 type task. +* `efs_volume_configuration` - (Optional) Used to configure a [EFS volume](#efs-volume-configuration-arguments). #### Docker Volume Configuration Arguments @@ -159,29 +159,41 @@ resource "aws_ecs_task_definition" "service" { #### EFS Volume Configuration Arguments -For more information, see [Specifying an EFS volume in your Task Definition Developer Guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_efs.html) +For more information, see [Specifying an EFS volume in your Task Definition Developer Guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/efs-volumes.html#specify-efs-config) * `file_system_id` - (Required) The ID of the EFS File System. -* `root_directory` - (Optional) The path to mount on the host +* `root_directory` - (Optional) The directory within the Amazon EFS file system to mount as the root directory inside the host. If this parameter is omitted, the root of the Amazon EFS volume will be used. Specifying / will have the same effect as omitting this parameter. This argument is ignored when using `authorization_config`. +* `transit_encryption` - (Optional) Whether or not to enable encryption for Amazon EFS data in transit between the Amazon ECS host and the Amazon EFS server. Transit encryption must be enabled if Amazon EFS IAM authorization is used. Valid values: `ENABLED`, `DISABLED`. If this parameter is omitted, the default value of `DISABLED` is used. +* `transit_encryption_port` - (Optional) The port to use for transit encryption. If you do not specify a transit encryption port, it will use the port selection strategy that the Amazon EFS mount helper uses. +* `authorization_config` - (Optional) The authorization configuration details for the Amazon EFS file system. + * `access_point_id` - The access point ID to use. If an access point is specified, the root directory value will be relative to the directory set for the access point. If specified, transit encryption must be enabled in the EFSVolumeConfiguration. + * `iam` - Whether or not to use the Amazon ECS task IAM role defined in a task definition when mounting the Amazon EFS file system. If enabled, transit encryption must be enabled in the EFSVolumeConfiguration. Valid values: `ENABLED`, `DISABLED`. If this parameter is omitted, the default value of `DISABLED` is used. ##### Example Usage ```hcl resource "aws_ecs_task_definition" "service" { family = "service" - container_definitions = "${file("task-definitions/service.json")}" + container_definitions = file("task-definitions/service.json") volume { name = "service-storage" efs_volume_configuration { - file_system_id = aws_efs_file_system.fs.id - root_directory = "/opt/data" + file_system_id = aws_efs_file_system.fs.id + root_directory = "/opt/data" + transit_encryption = "ENABLED" + transit_encryption_port = 2999 + authorization_config { + access_point_id = aws_efs_access_point.test.id + iam = "ENABLED" + } } } } ``` + #### Placement Constraints Arguments * `type` - (Required) The type of constraint. Use `memberOf` to restrict selection to a group of valid candidates. @@ -208,33 +220,33 @@ Guide](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-query- resource "aws_ecs_task_definition" "test" { family = "test" container_definitions = < **Note:** The `dns_name` attribute is only useful if the mount target is in a VPC that has +~> **Note:** The `dns_name` and `mount_target_dns_name` attributes are only useful if the mount target is in a VPC that has support for DNS hostnames enabled. See [Using DNS with Your VPC](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-dns.html) and [VPC resource](https://www.terraform.io/docs/providers/aws/r/vpc.html#enable_dns_hostnames) in Terraform for more information. In addition to all arguments above, the following attributes are exported: * `id` - The ID of the mount target. -* `dns_name` - The DNS name for the given subnet/AZ per [documented convention](http://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html). +* `dns_name` - The DNS name for the EFS file system. +* `mount_target_dns_name` - The DNS name for the given subnet/AZ per [documented convention](http://docs.aws.amazon.com/efs/latest/ug/mounting-fs-mount-cmd-dns-name.html). * `file_system_arn` - Amazon Resource Name of the file system. * `network_interface_id` - The ID of the network interface that Amazon EFS created when it created the mount target. +* `availability_zone_name` - The name of the Availability Zone (AZ) that the mount target resides in. +* `availability_zone_id` - The unique and consistent identifier of the Availability Zone (AZ) that the mount target resides in. +* `owner_id` - AWS account ID that owns the resource. ## Import diff --git a/website/docs/r/egress_only_internet_gateway.html.markdown b/website/docs/r/egress_only_internet_gateway.html.markdown index f541c198cba..9aeb77ca4f4 100644 --- a/website/docs/r/egress_only_internet_gateway.html.markdown +++ b/website/docs/r/egress_only_internet_gateway.html.markdown @@ -22,7 +22,7 @@ resource "aws_vpc" "example" { } resource "aws_egress_only_internet_gateway" "example" { - vpc_id = "${aws_vpc.example.id}" + vpc_id = aws_vpc.example.id tags = { Name = "main" diff --git a/website/docs/r/eip.html.markdown b/website/docs/r/eip.html.markdown index 2a5eb0d3dea..a3ec7785df1 100644 --- a/website/docs/r/eip.html.markdown +++ b/website/docs/r/eip.html.markdown @@ -20,7 +20,7 @@ Single EIP associated with an instance: ```hcl resource "aws_eip" "lb" { - instance = "${aws_instance.web.id}" + instance = aws_instance.web.id vpc = true } ``` @@ -29,19 +29,19 @@ Multiple EIPs associated with a single network interface: ```hcl resource "aws_network_interface" "multi-ip" { - subnet_id = "${aws_subnet.main.id}" + subnet_id = aws_subnet.main.id private_ips = ["10.0.0.10", "10.0.0.11"] } resource "aws_eip" "one" { vpc = true - network_interface = "${aws_network_interface.multi-ip.id}" + network_interface = aws_network_interface.multi-ip.id associate_with_private_ip = "10.0.0.10" } resource "aws_eip" "two" { vpc = true - network_interface = "${aws_network_interface.multi-ip.id}" + network_interface = aws_network_interface.multi-ip.id associate_with_private_ip = "10.0.0.11" } ``` @@ -55,15 +55,15 @@ resource "aws_vpc" "default" { } resource "aws_internet_gateway" "gw" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id } resource "aws_subnet" "tf_test_subnet" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id cidr_block = "10.0.0.0/24" map_public_ip_on_launch = true - depends_on = ["aws_internet_gateway.gw"] + depends_on = [aws_internet_gateway.gw] } resource "aws_instance" "foo" { @@ -72,15 +72,15 @@ resource "aws_instance" "foo" { instance_type = "t2.micro" private_ip = "10.0.0.12" - subnet_id = "${aws_subnet.tf_test_subnet.id}" + subnet_id = aws_subnet.tf_test_subnet.id } resource "aws_eip" "bar" { vpc = true - instance = "${aws_instance.foo.id}" + instance = aws_instance.foo.id associate_with_private_ip = "10.0.0.12" - depends_on = ["aws_internet_gateway.gw"] + depends_on = [aws_internet_gateway.gw] } ``` diff --git a/website/docs/r/eip_association.html.markdown b/website/docs/r/eip_association.html.markdown index 7288d91c733..34dc28a5fc6 100644 --- a/website/docs/r/eip_association.html.markdown +++ b/website/docs/r/eip_association.html.markdown @@ -20,14 +20,14 @@ pre-existing or distributed to customers or users and therefore cannot be change ```hcl resource "aws_eip_association" "eip_assoc" { - instance_id = "${aws_instance.web.id}" - allocation_id = "${aws_eip.example.id}" + instance_id = aws_instance.web.id + allocation_id = aws_eip.example.id } resource "aws_instance" "web" { ami = "ami-21f78e11" availability_zone = "us-west-2a" - instance_type = "t1.micro" + instance_type = "t2.micro" tags = { Name = "HelloWorld" diff --git a/website/docs/r/eks_cluster.html.markdown b/website/docs/r/eks_cluster.html.markdown index 4968fc135f7..5616ccdb80c 100644 --- a/website/docs/r/eks_cluster.html.markdown +++ b/website/docs/r/eks_cluster.html.markdown @@ -17,26 +17,25 @@ Manages an EKS Cluster. ```hcl resource "aws_eks_cluster" "example" { name = "example" - role_arn = "${aws_iam_role.example.arn}" + role_arn = aws_iam_role.example.arn vpc_config { - subnet_ids = ["${aws_subnet.example1.id}", "${aws_subnet.example2.id}"] + subnet_ids = [aws_subnet.example1.id, aws_subnet.example2.id] } # Ensure that IAM Role permissions are created before and deleted after EKS Cluster handling. # Otherwise, EKS will not be able to properly delete EKS managed EC2 infrastructure such as Security Groups. depends_on = [ - "aws_iam_role_policy_attachment.example-AmazonEKSClusterPolicy", - "aws_iam_role_policy_attachment.example-AmazonEKSServicePolicy", + aws_iam_role_policy_attachment.example-AmazonEKSClusterPolicy, ] } output "endpoint" { - value = "${aws_eks_cluster.example.endpoint}" + value = aws_eks_cluster.example.endpoint } output "kubeconfig-certificate-authority-data" { - value = "${aws_eks_cluster.example.certificate_authority.0.data}" + value = aws_eks_cluster.example.certificate_authority[0].data } ``` @@ -64,12 +63,7 @@ POLICY resource "aws_iam_role_policy_attachment" "example-AmazonEKSClusterPolicy" { policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy" - role = "${aws_iam_role.example.name}" -} - -resource "aws_iam_role_policy_attachment" "example-AmazonEKSServicePolicy" { - policy_arn = "arn:aws:iam::aws:policy/AmazonEKSServicePolicy" - role = "${aws_iam_role.example.name}" + role = aws_iam_role.example.name } ``` @@ -82,14 +76,14 @@ resource "aws_iam_role_policy_attachment" "example-AmazonEKSServicePolicy" { ```hcl variable "cluster_name" { default = "example" - type = "string" + type = string } resource "aws_eks_cluster" "example" { - depends_on = ["aws_cloudwatch_log_group.example"] + depends_on = [aws_cloudwatch_log_group.example] enabled_cluster_log_types = ["api", "audit"] - name = "${var.cluster_name}" + name = var.cluster_name # ... other configuration ... } @@ -114,7 +108,7 @@ resource "aws_eks_cluster" "example" { resource "aws_iam_openid_connect_provider" "example" { client_id_list = ["sts.amazonaws.com"] thumbprint_list = [] - url = "${aws_eks_cluster.example.identity.0.oidc.0.issuer}" + url = aws_eks_cluster.example.identity[0].oidc[0].issuer } data "aws_caller_identity" "current" {} @@ -131,14 +125,14 @@ data "aws_iam_policy_document" "example_assume_role_policy" { } principals { - identifiers = ["${aws_iam_openid_connect_provider.example.arn}"] + identifiers = [aws_iam_openid_connect_provider.example.arn] type = "Federated" } } } resource "aws_iam_role" "example" { - assume_role_policy = "${data.aws_iam_policy_document.example_assume_role_policy.json}" + assume_role_policy = data.aws_iam_policy_document.example_assume_role_policy.json name = "example" } ``` @@ -185,17 +179,17 @@ In addition to all arguments above, the following attributes are exported: * `id` - The name of the cluster. * `arn` - The Amazon Resource Name (ARN) of the cluster. * `certificate_authority` - Nested attribute containing `certificate-authority-data` for your cluster. - * `data` - The base64 encoded certificate data required to communicate with your cluster. Add this to the `certificate-authority-data` section of the `kubeconfig` file for your cluster. + * `data` - The base64 encoded certificate data required to communicate with your cluster. Add this to the `certificate-authority-data` section of the `kubeconfig` file for your cluster. * `endpoint` - The endpoint for your Kubernetes API server. * `identity` - Nested attribute containing identity provider information for your cluster. Only available on Kubernetes version 1.13 and 1.14 clusters created or upgraded on or after September 3, 2019. - * `oidc` - Nested attribute containing [OpenID Connect](https://openid.net/connect/) identity provider information for the cluster. - * `issuer` - Issuer URL for the OpenID Connect identity provider. + * `oidc` - Nested attribute containing [OpenID Connect](https://openid.net/connect/) identity provider information for the cluster. + * `issuer` - Issuer URL for the OpenID Connect identity provider. * `platform_version` - The platform version for the cluster. * `status` - The status of the EKS cluster. One of `CREATING`, `ACTIVE`, `DELETING`, `FAILED`. * `version` - The Kubernetes server version for the cluster. * `vpc_config` - Additional nested attributes: - * `cluster_security_group_id` - The cluster security group that was created by Amazon EKS for the cluster. - * `vpc_id` - The VPC associated with your cluster. + * `cluster_security_group_id` - The cluster security group that was created by Amazon EKS for the cluster. + * `vpc_id` - The VPC associated with your cluster. ## Timeouts diff --git a/website/docs/r/eks_node_group.html.markdown b/website/docs/r/eks_node_group.html.markdown index 772584769d9..5a55cab7b52 100644 --- a/website/docs/r/eks_node_group.html.markdown +++ b/website/docs/r/eks_node_group.html.markdown @@ -35,6 +35,28 @@ resource "aws_eks_node_group" "example" { } ``` +### Ignoring Changes to Desired Size + +You can utilize the generic Terraform resource [lifecycle configuration block](/docs/configuration/resources.html#lifecycle-lifecycle-customizations) with `ignore_changes` to create an EKS Node Group with an initial size of running instances, then ignore any changes to that count caused externally (e.g. Application Autoscaling). + +```hcl +resource "aws_eks_node_group" "example" { + # ... other configurations ... + + scaling_config { + # Example: Create EKS Node Group with 2 instances to start + desired_size = 2 + + # ... other configurations ... + } + + # Optional: Allow external changes without Terraform plan difference + lifecycle { + ignore_changes = [scaling_config[0].desired_size] + } +} +``` + ### Example IAM Role for EKS Node Group ```hcl @@ -103,6 +125,7 @@ The following arguments are optional: * `ami_type` - (Optional) Type of Amazon Machine Image (AMI) associated with the EKS Node Group. Defaults to `AL2_x86_64`. Valid values: `AL2_x86_64`, `AL2_x86_64_GPU`. Terraform will only perform drift detection if a configuration value is provided. * `disk_size` - (Optional) Disk size in GiB for worker nodes. Defaults to `20`. Terraform will only perform drift detection if a configuration value is provided. +* `force_update_version` - (Optional) Force version update if existing pods are unable to be drained due to a pod disruption budget issue. * `instance_types` - (Optional) Set of instance types associated with the EKS Node Group. Defaults to `["t3.medium"]`. Terraform will only perform drift detection if a configuration value is provided. Currently, the EKS API only accepts a single value in the set. * `labels` - (Optional) Key-value map of Kubernetes labels. Only labels that are applied with the EKS API are managed by this argument. Other Kubernetes labels applied to the EKS Node Group will not be managed. * `release_version` – (Optional) AMI version of the EKS Node Group. Defaults to latest version for Kubernetes version. @@ -128,9 +151,9 @@ In addition to all arguments above, the following attributes are exported: * `arn` - Amazon Resource Name (ARN) of the EKS Node Group. * `id` - EKS Cluster name and EKS Node Group name separated by a colon (`:`). * `resources` - List of objects containing information about underlying resources. - * `autoscaling_groups` - List of objects containing information about AutoScaling Groups. - * `name` - Name of the AutoScaling Group. - * `remote_access_security_group_id` - Identifier of the remote access EC2 Security Group. + * `autoscaling_groups` - List of objects containing information about AutoScaling Groups. + * `name` - Name of the AutoScaling Group. + * `remote_access_security_group_id` - Identifier of the remote access EC2 Security Group. * `status` - Status of the EKS Node Group. ## Timeouts diff --git a/website/docs/r/elastic_beanstalk_application.html.markdown b/website/docs/r/elastic_beanstalk_application.html.markdown index 25878f4193a..21aafbc78b3 100644 --- a/website/docs/r/elastic_beanstalk_application.html.markdown +++ b/website/docs/r/elastic_beanstalk_application.html.markdown @@ -23,7 +23,7 @@ resource "aws_elastic_beanstalk_application" "tftest" { description = "tf-test-desc" appversion_lifecycle { - service_role = "${aws_iam_role.beanstalk_service.arn}" + service_role = aws_iam_role.beanstalk_service.arn max_count = 128 delete_source_from_s3 = true } diff --git a/website/docs/r/elastic_beanstalk_application_version.html.markdown b/website/docs/r/elastic_beanstalk_application_version.html.markdown index a8593891338..90455b9f81a 100644 --- a/website/docs/r/elastic_beanstalk_application_version.html.markdown +++ b/website/docs/r/elastic_beanstalk_application_version.html.markdown @@ -28,7 +28,7 @@ resource "aws_s3_bucket" "default" { } resource "aws_s3_bucket_object" "default" { - bucket = "${aws_s3_bucket.default.id}" + bucket = aws_s3_bucket.default.id key = "beanstalk/go-v1.zip" source = "go-v1.zip" } @@ -42,8 +42,8 @@ resource "aws_elastic_beanstalk_application_version" "default" { name = "tf-test-version-label" application = "tf-test-name" description = "application version created by terraform" - bucket = "${aws_s3_bucket.default.id}" - key = "${aws_s3_bucket_object.default.id}" + bucket = aws_s3_bucket.default.id + key = aws_s3_bucket_object.default.id } ``` diff --git a/website/docs/r/elastic_beanstalk_configuration_template.html.markdown b/website/docs/r/elastic_beanstalk_configuration_template.html.markdown index adb28f99a1a..da4482d2fad 100644 --- a/website/docs/r/elastic_beanstalk_configuration_template.html.markdown +++ b/website/docs/r/elastic_beanstalk_configuration_template.html.markdown @@ -22,7 +22,7 @@ resource "aws_elastic_beanstalk_application" "tftest" { resource "aws_elastic_beanstalk_configuration_template" "tf_template" { name = "tf-test-template-config" - application = "${aws_elastic_beanstalk_application.tftest.name}" + application = aws_elastic_beanstalk_application.tftest.name solution_stack_name = "64bit Amazon Linux 2015.09 v2.0.8 running Go 1.4" } ``` diff --git a/website/docs/r/elastic_beanstalk_environment.html.markdown b/website/docs/r/elastic_beanstalk_environment.html.markdown index 319b8c00b60..3e96a5c3cd4 100644 --- a/website/docs/r/elastic_beanstalk_environment.html.markdown +++ b/website/docs/r/elastic_beanstalk_environment.html.markdown @@ -25,7 +25,7 @@ resource "aws_elastic_beanstalk_application" "tftest" { resource "aws_elastic_beanstalk_environment" "tfenvtest" { name = "tf-test-name" - application = "${aws_elastic_beanstalk_application.tftest.name}" + application = aws_elastic_beanstalk_application.tftest.name solution_stack_name = "64bit Amazon Linux 2015.03 v2.0.3 running Go 1.4" } ``` @@ -87,7 +87,7 @@ resource "aws_elastic_beanstalk_application" "tftest" { resource "aws_elastic_beanstalk_environment" "tfenvtest" { name = "tf-test-name" - application = "${aws_elastic_beanstalk_application.tftest.name}" + application = aws_elastic_beanstalk_application.tftest.name solution_stack_name = "64bit Amazon Linux 2015.03 v2.0.3 running Go 1.4" setting { diff --git a/website/docs/r/elasticache_cluster.html.markdown b/website/docs/r/elasticache_cluster.html.markdown index efa1741cebc..f68a2d5c79b 100644 --- a/website/docs/r/elasticache_cluster.html.markdown +++ b/website/docs/r/elasticache_cluster.html.markdown @@ -55,7 +55,7 @@ These inherit their settings from the replication group. ```hcl resource "aws_elasticache_cluster" "replica" { cluster_id = "cluster-example" - replication_group_id = "${aws_elasticache_replication_group.example.id}" + replication_group_id = aws_elasticache_replication_group.example.id } ``` diff --git a/website/docs/r/elasticache_replication_group.html.markdown b/website/docs/r/elasticache_replication_group.html.markdown index b6c9c5aa0d8..5f6d0a34577 100644 --- a/website/docs/r/elasticache_replication_group.html.markdown +++ b/website/docs/r/elasticache_replication_group.html.markdown @@ -56,7 +56,7 @@ resource "aws_elasticache_replication_group" "example" { port = 6379 lifecycle { - ignore_changes = ["number_cache_clusters"] + ignore_changes = [number_cache_clusters] } } @@ -64,7 +64,7 @@ resource "aws_elasticache_cluster" "replica" { count = 1 cluster_id = "tf-rep-group-1-${count.index}" - replication_group_id = "${aws_elasticache_replication_group.example.id}" + replication_group_id = aws_elasticache_replication_group.example.id } ``` diff --git a/website/docs/r/elasticache_security_group.html.markdown b/website/docs/r/elasticache_security_group.html.markdown index 8090a489e8e..906d0b80cbf 100644 --- a/website/docs/r/elasticache_security_group.html.markdown +++ b/website/docs/r/elasticache_security_group.html.markdown @@ -24,7 +24,7 @@ resource "aws_security_group" "bar" { resource "aws_elasticache_security_group" "bar" { name = "elasticache-security-group" - security_group_names = ["${aws_security_group.bar.name}"] + security_group_names = [aws_security_group.bar.name] } ``` diff --git a/website/docs/r/elasticache_subnet_group.html.markdown b/website/docs/r/elasticache_subnet_group.html.markdown index 3400976c718..6d405dc0bf3 100644 --- a/website/docs/r/elasticache_subnet_group.html.markdown +++ b/website/docs/r/elasticache_subnet_group.html.markdown @@ -26,7 +26,7 @@ resource "aws_vpc" "foo" { } resource "aws_subnet" "foo" { - vpc_id = "${aws_vpc.foo.id}" + vpc_id = aws_vpc.foo.id cidr_block = "10.0.0.0/24" availability_zone = "us-west-2a" @@ -37,7 +37,7 @@ resource "aws_subnet" "foo" { resource "aws_elasticache_subnet_group" "bar" { name = "tf-test-cache-subnet" - subnet_ids = ["${aws_subnet.foo.id}"] + subnet_ids = [aws_subnet.foo.id] } ``` diff --git a/website/docs/r/elasticsearch_domain.html.markdown b/website/docs/r/elasticsearch_domain.html.markdown index b205e0b7f88..455e5fd5244 100644 --- a/website/docs/r/elasticsearch_domain.html.markdown +++ b/website/docs/r/elasticsearch_domain.html.markdown @@ -47,7 +47,7 @@ data "aws_region" "current" {} data "aws_caller_identity" "current" {} resource "aws_elasticsearch_domain" "example" { - domain_name = "${var.domain}" + domain_name = var.domain # ... other configuration ... @@ -105,7 +105,7 @@ resource "aws_elasticsearch_domain" "example" { # .. other configuration ... log_publishing_options { - cloudwatch_log_group_arn = "${aws_cloudwatch_log_group.example.arn}" + cloudwatch_log_group_arn = aws_cloudwatch_log_group.example.arn log_type = "INDEX_SLOW_LOGS" } } @@ -122,12 +122,12 @@ variable "domain" { data "aws_vpc" "selected" { tags = { - Name = "${var.vpc}" + Name = var.vpc } } data "aws_subnet_ids" "selected" { - vpc_id = "${data.aws_vpc.selected.id}" + vpc_id = data.aws_vpc.selected.id tags = { Tier = "private" @@ -141,7 +141,7 @@ data "aws_caller_identity" "current" {} resource "aws_security_group" "es" { name = "${var.vpc}-elasticsearch-${var.domain}" description = "Managed by Terraform" - vpc_id = "${data.aws_vpc.selected.id}" + vpc_id = data.aws_vpc.selected.id ingress { from_port = 443 @@ -149,7 +149,7 @@ resource "aws_security_group" "es" { protocol = "tcp" cidr_blocks = [ - "${data.aws_vpc.selected.cidr_block}", + data.aws_vpc.selected.cidr_block, ] } } @@ -159,7 +159,7 @@ resource "aws_iam_service_linked_role" "es" { } resource "aws_elasticsearch_domain" "es" { - domain_name = "${var.domain}" + domain_name = var.domain elasticsearch_version = "6.3" cluster_config { @@ -168,11 +168,11 @@ resource "aws_elasticsearch_domain" "es" { vpc_options { subnet_ids = [ - "${data.aws_subnet_ids.selected.ids[0]}", - "${data.aws_subnet_ids.selected.ids[1]}", + data.aws_subnet_ids.selected.ids[0], + data.aws_subnet_ids.selected.ids[1], ] - security_group_ids = ["${aws_security_group.elasticsearch.id}"] + security_group_ids = [aws_security_group.es.id] } advanced_options = { @@ -201,9 +201,7 @@ CONFIG Domain = "TestDomain" } - depends_on = [ - "aws_iam_service_linked_role.es", - ] + depends_on = [aws_iam_service_linked_role.es] } ``` @@ -217,17 +215,27 @@ The following arguments are supported: Note that the values for these configuration options must be strings (wrapped in quotes) or they may be wrong and cause a perpetual diff, causing Terraform to want to recreate your Elasticsearch domain on every apply. +* `advanced_security_options` - (Optional) Options for [fine-grained access control](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/fgac.html). See below for more details. * `ebs_options` - (Optional) EBS related options, may be required based on chosen [instance size](https://aws.amazon.com/elasticsearch-service/pricing/). See below. * `encrypt_at_rest` - (Optional) Encrypt at rest options. Only available for [certain instance types](http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/aes-supported-instance-types.html). See below. * `node_to_node_encryption` - (Optional) Node-to-node encryption options. See below. * `cluster_config` - (Optional) Cluster configuration of the domain, see below. * `snapshot_options` - (Optional) Snapshot related options, see below. * `vpc_options` - (Optional) VPC related options, see below. Adding or removing this configuration forces a new resource ([documentation](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-vpc.html#es-vpc-limitations)). -* `log_publishing_options` - (Optional) Options for publishing slow logs to CloudWatch Logs. +* `log_publishing_options` - (Optional) Options for publishing slow and application logs to CloudWatch Logs. This block can be declared multiple times, for each log_type, within the same resource. * `elasticsearch_version` - (Optional) The version of Elasticsearch to deploy. Defaults to `1.5` * `domain_endpoint_options` - (Optional) Domain endpoint HTTP(S) related options. See below. * `tags` - (Optional) A map of tags to assign to the resource +The **advanced_security_options** block supports the following attributes: + +* `enabled` - (Required, Forces new resource) Whether advanced security is enabled +* `internal_user_database_enabled` - (Optional, Default: false) Whether the internal user database is enabled. If not set, defaults to `false` by the AWS API. +* `master_user_options` - (Optional) Credentials for the master user: username and password, or ARN + * `master_user_arn` - (Optional) ARN for the master user. Only specify if `internal_user_database_enabled` is not set or set to `false`) + * `master_user_name` - (Optional) The master user's username, which is stored in the Amazon Elasticsearch Service domain's internal database. Only specify if `internal_user_database_enabled` is set to `true`. + * `master_user_password` - (Optional) The master user's password, which is stored in the Amazon Elasticsearch Service domain's internal database. Only specify if `internal_user_database_enabled` is set to `true`. + **ebs_options** supports the following attributes: * `ebs_enabled` - (Required) Whether EBS volumes are attached to data nodes in the domain. @@ -256,6 +264,9 @@ The following arguments are supported: * `dedicated_master_count` - (Optional) Number of dedicated master nodes in the cluster * `zone_awareness_config` - (Optional) Configuration block containing zone awareness settings. Documented below. * `zone_awareness_enabled` - (Optional) Indicates whether zone awareness is enabled, set to `true` for multi-az deployment. To enable awareness with three Availability Zones, the `availability_zone_count` within the `zone_awareness_config` must be set to `3`. +* `warm_enabled` - (Optional) Indicates whether to enable warm storage. +* `warm_count` - (Optional) The number of warm nodes in the cluster. Valid values are between `2` and `150`. `warm_count` can be only and must be set when `warm_enabled` is set to `true`. +* `warm_type` - (Optional) The instance type for the Elasticsearch cluster's warm nodes. Valid values are `ultrawarm1.medium.elasticsearch`, `ultrawarm1.large.elasticsearch` and `ultrawarm1.xlarge.elasticsearch`. `warm_type` can be only and must be set when `warm_enabled` is set to `true`. **zone_awareness_config** supports the following attributes: diff --git a/website/docs/r/elasticsearch_domain_policy.html.markdown b/website/docs/r/elasticsearch_domain_policy.html.markdown index 6036908b7c8..94872e959d2 100644 --- a/website/docs/r/elasticsearch_domain_policy.html.markdown +++ b/website/docs/r/elasticsearch_domain_policy.html.markdown @@ -19,7 +19,7 @@ resource "aws_elasticsearch_domain" "example" { } resource "aws_elasticsearch_domain_policy" "main" { - domain_name = "${aws_elasticsearch_domain.example.domain_name}" + domain_name = aws_elasticsearch_domain.example.domain_name access_policies = < **NOTE:** The `allocated_capacity` attribute has been deprecated and might -be removed in future releases, please use `max_capacity` instead. - -* `allocated_capacity` – **DEPRECATED** (Optional) The number of AWS Glue data processing units (DPUs) to allocate to this Job. At least 2 DPUs need to be allocated; the default is 10. A DPU is a relative measure of processing power that consists of 4 vCPUs of compute capacity and 16 GB of memory. * `command` – (Required) The command of the job. Defined below. * `connections` – (Optional) The list of connections used for this job. * `default_arguments` – (Optional) The map of default arguments for this job. You can specify arguments here that your own job-execution script consumes, as well as arguments that AWS Glue itself consumes. For information about how to specify and consume your own Job arguments, see the [Calling AWS Glue APIs in Python](http://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python-calling.html) topic in the developer guide. For information about the key-value pairs that AWS Glue consumes to set up your job, see the [Special Parameters Used by AWS Glue](http://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python-glue-arguments.html) topic in the developer guide. diff --git a/website/docs/r/glue_security_configuration.html.markdown b/website/docs/r/glue_security_configuration.html.markdown index 2a45a3af741..25b900eb7a0 100644 --- a/website/docs/r/glue_security_configuration.html.markdown +++ b/website/docs/r/glue_security_configuration.html.markdown @@ -26,7 +26,7 @@ resource "aws_glue_security_configuration" "example" { } s3_encryption { - kms_key_arn = "${data.aws_kms_key.example.arn}" + kms_key_arn = data.aws_kms_key.example.arn s3_encryption_mode = "SSE-KMS" } } diff --git a/website/docs/r/glue_trigger.html.markdown b/website/docs/r/glue_trigger.html.markdown index 74e7a908ae1..8f3fb5e8461 100644 --- a/website/docs/r/glue_trigger.html.markdown +++ b/website/docs/r/glue_trigger.html.markdown @@ -20,12 +20,12 @@ resource "aws_glue_trigger" "example" { type = "CONDITIONAL" actions { - job_name = "${aws_glue_job.example1.name}" + job_name = aws_glue_job.example1.name } predicate { conditions { - job_name = "${aws_glue_job.example2.name}" + job_name = aws_glue_job.example2.name state = "SUCCEEDED" } } @@ -40,7 +40,7 @@ resource "aws_glue_trigger" "example" { type = "ON_DEMAND" actions { - job_name = "${aws_glue_job.example.name}" + job_name = aws_glue_job.example.name } } ``` @@ -54,7 +54,7 @@ resource "aws_glue_trigger" "example" { type = "SCHEDULED" actions { - job_name = "${aws_glue_job.example.name}" + job_name = aws_glue_job.example.name } } ``` @@ -69,12 +69,12 @@ resource "aws_glue_trigger" "example" { type = "CONDITIONAL" actions { - crawler_name = "${aws_glue_crawler.example1.name}" + crawler_name = aws_glue_crawler.example1.name } predicate { conditions { - job_name = "${aws_glue_job.example2.name}" + job_name = aws_glue_job.example2.name state = "SUCCEEDED" } } @@ -91,12 +91,12 @@ resource "aws_glue_trigger" "example" { type = "CONDITIONAL" actions { - job_name = "${aws_glue_job.example1.name}" + job_name = aws_glue_job.example1.name } predicate { conditions { - crawler_name = "${aws_glue_crawler.example2.name}" + crawler_name = aws_glue_crawler.example2.name crawl_state = "SUCCEEDED" } } diff --git a/website/docs/r/glue_workflow.html.markdown b/website/docs/r/glue_workflow.html.markdown index c776c27b5ec..949432c4f67 100644 --- a/website/docs/r/glue_workflow.html.markdown +++ b/website/docs/r/glue_workflow.html.markdown @@ -22,7 +22,7 @@ resource "aws_glue_workflow" "example" { resource "aws_glue_trigger" "example-start" { name = "trigger-start" type = "ON_DEMAND" - workflow_name = "${aws_glue_workflow.example.name}" + workflow_name = aws_glue_workflow.example.name actions { job_name = "example-job" @@ -32,7 +32,7 @@ resource "aws_glue_trigger" "example-start" { resource "aws_glue_trigger" "example-inner" { name = "trigger-inner" type = "CONDITIONAL" - workflow_name = "${aws_glue_workflow.example.name}" + workflow_name = aws_glue_workflow.example.name predicate { conditions { diff --git a/website/docs/r/guardduty_detector.html.markdown b/website/docs/r/guardduty_detector.html.markdown index 695a8d9f75e..1719ebc0fe5 100644 --- a/website/docs/r/guardduty_detector.html.markdown +++ b/website/docs/r/guardduty_detector.html.markdown @@ -25,14 +25,16 @@ resource "aws_guardduty_detector" "MyDetector" { The following arguments are supported: * `enable` - (Optional) Enable monitoring and feedback reporting. Setting to `false` is equivalent to "suspending" GuardDuty. Defaults to `true`. -* `finding_publishing_frequency` - (Optional) Specifies the frequency of notifications sent for subsequent finding occurrences. If the detector is a GuardDuty member account, the value is determined by the GuardDuty master account and cannot be modified, otherwise defaults to `SIX_HOURS`. For standalone and GuardDuty master accounts, it must be configured in Terraform to enable drift detection. Valid values for standalone and master accounts: `FIFTEEN_MINUTES`, `ONE_HOUR`, `SIX_HOURS`. See [AWS Documentation](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_findings_cloudwatch.html#guardduty_findings_cloudwatch_notification_frequency) for more information. +* `finding_publishing_frequency` - (Optional) Specifies the frequency of notifications sent for subsequent finding occurrences. If the detector is a GuardDuty member account, the value is determined by the GuardDuty primary account and cannot be modified, otherwise defaults to `SIX_HOURS`. For standalone and GuardDuty primary accounts, it must be configured in Terraform to enable drift detection. Valid values for standalone and primary accounts: `FIFTEEN_MINUTES`, `ONE_HOUR`, `SIX_HOURS`. See [AWS Documentation](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_findings_cloudwatch.html#guardduty_findings_cloudwatch_notification_frequency) for more information. +* `tags` - (Optional) Key-value map of resource tags. ## Attributes Reference In addition to all arguments above, the following attributes are exported: -* `id` - The ID of the GuardDuty detector * `account_id` - The AWS account ID of the GuardDuty detector +* `arn` - Amazon Resource Name (ARN) of the GuardDuty detector +* `id` - The ID of the GuardDuty detector ## Import diff --git a/website/docs/r/guardduty_invite_accepter.html.markdown b/website/docs/r/guardduty_invite_accepter.html.markdown index 9feb66cd039..8d511a2ecff 100644 --- a/website/docs/r/guardduty_invite_accepter.html.markdown +++ b/website/docs/r/guardduty_invite_accepter.html.markdown @@ -3,35 +3,46 @@ subcategory: "GuardDuty" layout: "aws" page_title: "AWS: aws_guardduty_invite_accepter" description: |- - Provides a resource to accept a pending GuardDuty invite on creation, ensure the detector has the correct master account on read, and disassociate with the master account upon removal. + Provides a resource to accept a pending GuardDuty invite on creation, ensure the detector has the correct primary account on read, and disassociate with the primary account upon removal. --- # Resource: aws_guardduty_invite_accepter -Provides a resource to accept a pending GuardDuty invite on creation, ensure the detector has the correct master account on read, and disassociate with the master account upon removal. +Provides a resource to accept a pending GuardDuty invite on creation, ensure the detector has the correct primary account on read, and disassociate with the primary account upon removal. ## Example Usage ```hcl -resource "aws_guardduty_detector" "master" {} +provider "aws" { + alias = "primary" +} -resource "aws_guardduty_detector" "member" { - provider = "aws.dev" +provider "aws" { + alias = "member" } -resource "aws_guardduty_member" "dev" { - account_id = "${aws_guardduty_detector.member.account_id}" - detector_id = "${aws_guardduty_detector.master.id}" +resource "aws_guardduty_invite_accepter" "member" { + depends_on = [aws_guardduty_member.member] + provider = aws.member + + detector_id = aws_guardduty_detector.member.id + master_account_id = aws_guardduty_detector.primary.account_id +} + +resource "aws_guardduty_member" "member" { + provider = aws.primary + account_id = aws_guardduty_detector.member.account_id + detector_id = aws_guardduty_detector.primary.id email = "required@example.com" invite = true } -resource "aws_guardduty_invite_accepter" "member" { - depends_on = ["aws_guardduty_member.dev"] - provider = "aws.dev" +resource "aws_guardduty_detector" "primary" { + provider = aws.primary +} - detector_id = "${aws_guardduty_detector.member.id}" - master_account_id = "${aws_guardduty_detector.master.account_id}" +resource "aws_guardduty_detector" "member" { + provider = aws.member } ``` @@ -40,7 +51,7 @@ resource "aws_guardduty_invite_accepter" "member" { The following arguments are supported: * `detector_id` - (Required) The detector ID of the member GuardDuty account. -* `master_account_id` - (Required) AWS account ID for master account. +* `master_account_id` - (Required) AWS account ID for primary account. ## Attributes Reference diff --git a/website/docs/r/guardduty_ipset.html.markdown b/website/docs/r/guardduty_ipset.html.markdown index e86d68b3dd4..5a780152cd2 100644 --- a/website/docs/r/guardduty_ipset.html.markdown +++ b/website/docs/r/guardduty_ipset.html.markdown @@ -9,12 +9,20 @@ description: Provides a resource to manage a GuardDuty IPSet Provides a resource to manage a GuardDuty IPSet. -~> **Note:** Currently in GuardDuty, users from member accounts cannot upload and further manage IPSets. IPSets that are uploaded by the master account are imposed on GuardDuty functionality in its member accounts. See the [GuardDuty API Documentation](https://docs.aws.amazon.com/guardduty/latest/ug/create-ip-set.html) +~> **Note:** Currently in GuardDuty, users from member accounts cannot upload and further manage IPSets. IPSets that are uploaded by the primary account are imposed on GuardDuty functionality in its member accounts. See the [GuardDuty API Documentation](https://docs.aws.amazon.com/guardduty/latest/ug/create-ip-set.html) ## Example Usage ```hcl -resource "aws_guardduty_detector" "master" { +resource "aws_guardduty_ipset" "example" { + activate = true + detector_id = aws_guardduty_detector.primary.id + format = "TXT" + location = "https://s3.amazonaws.com/${aws_s3_bucket_object.MyIPSet.bucket}/${aws_s3_bucket_object.MyIPSet.key}" + name = "MyIPSet" +} + +resource "aws_guardduty_detector" "primary" { enable = true } @@ -25,17 +33,9 @@ resource "aws_s3_bucket" "bucket" { resource "aws_s3_bucket_object" "MyIPSet" { acl = "public-read" content = "10.0.0.0/8\n" - bucket = "${aws_s3_bucket.bucket.id}" + bucket = aws_s3_bucket.bucket.id key = "MyIPSet" } - -resource "aws_guardduty_ipset" "MyIPSet" { - activate = true - detector_id = "${aws_guardduty_detector.master.id}" - format = "TXT" - location = "https://s3.amazonaws.com/${aws_s3_bucket_object.MyIPSet.bucket}/${aws_s3_bucket_object.MyIPSet.key}" - name = "MyIPSet" -} ``` ## Argument Reference @@ -47,16 +47,18 @@ The following arguments are supported: * `format` - (Required) The format of the file that contains the IPSet. Valid values: `TXT` | `STIX` | `OTX_CSV` | `ALIEN_VAULT` | `PROOF_POINT` | `FIRE_EYE` * `location` - (Required) The URI of the file that contains the IPSet. * `name` - (Required) The friendly name to identify the IPSet. +* `tags` - (Optional) Key-value map of resource tags. ## Attributes Reference In addition to all arguments above, the following attributes are exported: +* `arn` - Amazon Resource Name (ARN) of the GuardDuty IPSet. * `id` - The ID of the GuardDuty IPSet. ## Import -GuardDuty IPSet can be imported using the the master GuardDuty detector ID and IPSet ID, e.g. +GuardDuty IPSet can be imported using the the primary GuardDuty detector ID and IPSet ID, e.g. ``` $ terraform import aws_guardduty_ipset.MyIPSet 00b00fd5aecc0ab60a708659477e9617:123456789012 diff --git a/website/docs/r/guardduty_member.html.markdown b/website/docs/r/guardduty_member.html.markdown index ec025603744..aa0f8d87fd3 100644 --- a/website/docs/r/guardduty_member.html.markdown +++ b/website/docs/r/guardduty_member.html.markdown @@ -13,19 +13,19 @@ Provides a resource to manage a GuardDuty member. To accept invitations in membe ## Example Usage ```hcl -resource "aws_guardduty_detector" "master" { +resource "aws_guardduty_detector" "primary" { enable = true } resource "aws_guardduty_detector" "member" { - provider = "aws.dev" + provider = aws.dev enable = true } resource "aws_guardduty_member" "member" { - account_id = "${aws_guardduty_detector.member.account_id}" - detector_id = "${aws_guardduty_detector.master.id}" + account_id = aws_guardduty_detector.member.account_id + detector_id = aws_guardduty_detector.primary.id email = "required@example.com" invite = true invitation_message = "please accept guardduty invitation" @@ -57,11 +57,11 @@ configuration options: In addition to all arguments above, the following attributes are exported: * `id` - The ID of the GuardDuty member -* `relationship_status` - The status of the relationship between the member account and its master account. More information can be found in [Amazon GuardDuty API Reference](https://docs.aws.amazon.com/guardduty/latest/ug/get-members.html). +* `relationship_status` - The status of the relationship between the member account and its primary account. More information can be found in [Amazon GuardDuty API Reference](https://docs.aws.amazon.com/guardduty/latest/ug/get-members.html). ## Import -GuardDuty members can be imported using the the master GuardDuty detector ID and member AWS account ID, e.g. +GuardDuty members can be imported using the the primary GuardDuty detector ID and member AWS account ID, e.g. ``` $ terraform import aws_guardduty_member.MyMember 00b00fd5aecc0ab60a708659477e9617:123456789012 diff --git a/website/docs/r/guardduty_organization_admin_account.html.markdown b/website/docs/r/guardduty_organization_admin_account.html.markdown index 4a281241b82..0868654fd0f 100644 --- a/website/docs/r/guardduty_organization_admin_account.html.markdown +++ b/website/docs/r/guardduty_organization_admin_account.html.markdown @@ -8,7 +8,7 @@ description: |- # Resource: aws_guardduty_organization_admin_account -Manages a GuardDuty Organization Admin Account. The AWS account utilizing this resource must be an Organizations master account. More information about Organizations support in GuardDuty can be found in the [GuardDuty User Guide](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_organizations.html). +Manages a GuardDuty Organization Admin Account. The AWS account utilizing this resource must be an Organizations primary account. More information about Organizations support in GuardDuty can be found in the [GuardDuty User Guide](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_organizations.html). ## Example Usage diff --git a/website/docs/r/guardduty_threatintelset.html.markdown b/website/docs/r/guardduty_threatintelset.html.markdown index 398c0419213..e9d0a13607b 100644 --- a/website/docs/r/guardduty_threatintelset.html.markdown +++ b/website/docs/r/guardduty_threatintelset.html.markdown @@ -9,12 +9,12 @@ description: Provides a resource to manage a GuardDuty ThreatIntelSet Provides a resource to manage a GuardDuty ThreatIntelSet. -~> **Note:** Currently in GuardDuty, users from member accounts cannot upload and further manage ThreatIntelSets. ThreatIntelSets that are uploaded by the master account are imposed on GuardDuty functionality in its member accounts. See the [GuardDuty API Documentation](https://docs.aws.amazon.com/guardduty/latest/ug/create-threat-intel-set.html) +~> **Note:** Currently in GuardDuty, users from member accounts cannot upload and further manage ThreatIntelSets. ThreatIntelSets that are uploaded by the primary account are imposed on GuardDuty functionality in its member accounts. See the [GuardDuty API Documentation](https://docs.aws.amazon.com/guardduty/latest/ug/create-threat-intel-set.html) ## Example Usage ```hcl -resource "aws_guardduty_detector" "master" { +resource "aws_guardduty_detector" "primary" { enable = true } @@ -25,13 +25,13 @@ resource "aws_s3_bucket" "bucket" { resource "aws_s3_bucket_object" "MyThreatIntelSet" { acl = "public-read" content = "10.0.0.0/8\n" - bucket = "${aws_s3_bucket.bucket.id}" + bucket = aws_s3_bucket.bucket.id key = "MyThreatIntelSet" } resource "aws_guardduty_threatintelset" "MyThreatIntelSet" { activate = true - detector_id = "${aws_guardduty_detector.master.id}" + detector_id = aws_guardduty_detector.primary.id format = "TXT" location = "https://s3.amazonaws.com/${aws_s3_bucket_object.MyThreatIntelSet.bucket}/${aws_s3_bucket_object.MyThreatIntelSet.key}" name = "MyThreatIntelSet" @@ -47,16 +47,18 @@ The following arguments are supported: * `format` - (Required) The format of the file that contains the ThreatIntelSet. Valid values: `TXT` | `STIX` | `OTX_CSV` | `ALIEN_VAULT` | `PROOF_POINT` | `FIRE_EYE` * `location` - (Required) The URI of the file that contains the ThreatIntelSet. * `name` - (Required) The friendly name to identify the ThreatIntelSet. +* `tags` - (Optional) Key-value map of resource tags. ## Attributes Reference In addition to all arguments above, the following attributes are exported: +* `arn` - Amazon Resource Name (ARN) of the GuardDuty ThreatIntelSet. * `id` - The ID of the GuardDuty ThreatIntelSet and the detector ID. Format: `:` ## Import -GuardDuty ThreatIntelSet can be imported using the the master GuardDuty detector ID and ThreatIntelSetID, e.g. +GuardDuty ThreatIntelSet can be imported using the the primary GuardDuty detector ID and ThreatIntelSetID, e.g. ``` $ terraform import aws_guardduty_threatintelset.MyThreatIntelSet 00b00fd5aecc0ab60a708659477e9617:123456789012 diff --git a/website/docs/r/iam_access_key.html.markdown b/website/docs/r/iam_access_key.html.markdown index 1a2d039d06e..117b59135c2 100644 --- a/website/docs/r/iam_access_key.html.markdown +++ b/website/docs/r/iam_access_key.html.markdown @@ -14,7 +14,7 @@ Provides an IAM access key. This is a set of credentials that allow API requests ```hcl resource "aws_iam_access_key" "lb" { - user = "${aws_iam_user.lb.name}" + user = aws_iam_user.lb.name pgp_key = "keybase:some_person_that_exists" } @@ -25,7 +25,7 @@ resource "aws_iam_user" "lb" { resource "aws_iam_user_policy" "lb_ro" { name = "test" - user = "${aws_iam_user.lb.name}" + user = aws_iam_user.lb.name policy = < **NOTE:** The encrypted secret may be decrypted using the command line, for example: `terraform output encrypted_secret | base64 --decode | keybase pgp decrypt`. -* `ses_smtp_password` - **DEPRECATED** The secret access key converted into an SES SMTP - password by applying AWS's SigV2 conversion algorithm * `ses_smtp_password_v4` - The secret access key converted into an SES SMTP password by applying [AWS's documented Sigv4 conversion algorithm](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html#smtp-credentials-convert). diff --git a/website/docs/r/iam_group_membership.html.markdown b/website/docs/r/iam_group_membership.html.markdown index f5fb0a9779a..d0189ff197b 100644 --- a/website/docs/r/iam_group_membership.html.markdown +++ b/website/docs/r/iam_group_membership.html.markdown @@ -24,11 +24,11 @@ resource "aws_iam_group_membership" "team" { name = "tf-testing-group-membership" users = [ - "${aws_iam_user.user_one.name}", - "${aws_iam_user.user_two.name}", + aws_iam_user.user_one.name, + aws_iam_user.user_two.name, ] - group = "${aws_iam_group.group.name}" + group = aws_iam_group.group.name } resource "aws_iam_group" "group" { diff --git a/website/docs/r/iam_group_policy.html.markdown b/website/docs/r/iam_group_policy.html.markdown index 9843b37d3b8..283b0dba787 100644 --- a/website/docs/r/iam_group_policy.html.markdown +++ b/website/docs/r/iam_group_policy.html.markdown @@ -15,7 +15,7 @@ Provides an IAM policy attached to a group. ```hcl resource "aws_iam_group_policy" "my_developer_policy" { name = "my_developer_policy" - group = "${aws_iam_group.my_developers.id}" + group = aws_iam_group.my_developers.id policy = <= 2 roles are not possible. See [issue #11575](https://github.com/hashicorp/terraform/issues/11575). * `role` - (Optional) The role name to include in the profile. ## Attribute Reference @@ -60,7 +57,6 @@ A list of role names to include in the profile. The current default is 1. If y * `name` - The instance profile's name. * `path` - The path of the instance profile in IAM. * `role` - The role assigned to the instance profile. -* `roles` - The list of roles assigned to the instance profile. (**Deprecated**) * `unique_id` - The [unique ID][1] assigned by AWS. [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html#GUIDs diff --git a/website/docs/r/iam_policy_attachment.html.markdown b/website/docs/r/iam_policy_attachment.html.markdown index be52518f7e7..c31124edd21 100644 --- a/website/docs/r/iam_policy_attachment.html.markdown +++ b/website/docs/r/iam_policy_attachment.html.markdown @@ -67,10 +67,10 @@ EOF resource "aws_iam_policy_attachment" "test-attach" { name = "test-attachment" - users = ["${aws_iam_user.user.name}"] - roles = ["${aws_iam_role.role.name}"] - groups = ["${aws_iam_group.group.name}"] - policy_arn = "${aws_iam_policy.policy.arn}" + users = [aws_iam_user.user.name] + roles = [aws_iam_role.role.name] + groups = [aws_iam_group.group.name] + policy_arn = aws_iam_policy.policy.arn } ``` diff --git a/website/docs/r/iam_role.html.markdown b/website/docs/r/iam_role.html.markdown index 6e39ffc3c7a..8fd1c17e6f7 100644 --- a/website/docs/r/iam_role.html.markdown +++ b/website/docs/r/iam_role.html.markdown @@ -87,7 +87,7 @@ data "aws_iam_policy_document" "instance-assume-role-policy" { resource "aws_iam_role" "instance" { name = "instance_role" path = "/system/" - assume_role_policy = "${data.aws_iam_policy_document.instance-assume-role-policy.json}" + assume_role_policy = data.aws_iam_policy_document.instance-assume-role-policy.json } ``` diff --git a/website/docs/r/iam_role_policy_attachment.markdown b/website/docs/r/iam_role_policy_attachment.markdown index fe8173a221d..1804f509419 100644 --- a/website/docs/r/iam_role_policy_attachment.markdown +++ b/website/docs/r/iam_role_policy_attachment.markdown @@ -56,8 +56,8 @@ EOF } resource "aws_iam_role_policy_attachment" "test-attach" { - role = "${aws_iam_role.role.name}" - policy_arn = "${aws_iam_policy.policy.arn}" + role = aws_iam_role.role.name + policy_arn = aws_iam_policy.policy.arn } ``` diff --git a/website/docs/r/iam_saml_provider.html.markdown b/website/docs/r/iam_saml_provider.html.markdown index 472759e6819..373bc0e4ccb 100644 --- a/website/docs/r/iam_saml_provider.html.markdown +++ b/website/docs/r/iam_saml_provider.html.markdown @@ -15,7 +15,7 @@ Provides an IAM SAML provider. ```hcl resource "aws_iam_saml_provider" "default" { name = "myprovider" - saml_metadata_document = "${file("saml-metadata.xml")}" + saml_metadata_document = file("saml-metadata.xml") } ``` diff --git a/website/docs/r/iam_server_certificate.html.markdown b/website/docs/r/iam_server_certificate.html.markdown index c8a6df41a8e..3b00998ff86 100644 --- a/website/docs/r/iam_server_certificate.html.markdown +++ b/website/docs/r/iam_server_certificate.html.markdown @@ -29,8 +29,8 @@ Certificates][2] in AWS Documentation. ```hcl resource "aws_iam_server_certificate" "test_cert" { name = "some_test_cert" - certificate_body = "${file("self-ca-cert.pem")}" - private_key = "${file("test-key.pem")}" + certificate_body = file("self-ca-cert.pem") + private_key = file("test-key.pem") } ``` @@ -66,8 +66,8 @@ dependant resources before attempting to destroy the old version. ```hcl resource "aws_iam_server_certificate" "test_cert" { name_prefix = "example-cert" - certificate_body = "${file("self-ca-cert.pem")}" - private_key = "${file("test-key.pem")}" + certificate_body = file("self-ca-cert.pem") + private_key = file("test-key.pem") lifecycle { create_before_destroy = true @@ -84,7 +84,7 @@ resource "aws_elb" "ourapp" { instance_protocol = "http" lb_port = 443 lb_protocol = "https" - ssl_certificate_id = "${aws_iam_server_certificate.test_cert.arn}" + ssl_certificate_id = aws_iam_server_certificate.test_cert.arn } } ``` diff --git a/website/docs/r/iam_user.html.markdown b/website/docs/r/iam_user.html.markdown index 36ec509fabc..a650f17bba0 100644 --- a/website/docs/r/iam_user.html.markdown +++ b/website/docs/r/iam_user.html.markdown @@ -25,12 +25,12 @@ resource "aws_iam_user" "lb" { } resource "aws_iam_access_key" "lb" { - user = "${aws_iam_user.lb.name}" + user = aws_iam_user.lb.name } resource "aws_iam_user_policy" "lb_ro" { name = "test" - user = "${aws_iam_user.lb.name}" + user = aws_iam_user.lb.name policy = < **NOTE::** You can reuse URI components using the following reserved keywords: `#{protocol}`, `#{host}`, `#{port}`, `#{path}` (the leading "/" is removed) and `#{query}`. diff --git a/website/docs/r/lb_listener_certificate.html.markdown b/website/docs/r/lb_listener_certificate.html.markdown index 7c4df9379be..f0d5225414e 100644 --- a/website/docs/r/lb_listener_certificate.html.markdown +++ b/website/docs/r/lb_listener_certificate.html.markdown @@ -30,8 +30,8 @@ resource "aws_lb_listener" "front_end" { } resource "aws_lb_listener_certificate" "example" { - listener_arn = "${aws_lb_listener.front_end.arn}" - certificate_arn = "${aws_acm_certificate.example.arn}" + listener_arn = aws_lb_listener.front_end.arn + certificate_arn = aws_acm_certificate.example.arn } ``` diff --git a/website/docs/r/lb_listener_rule.html.markdown b/website/docs/r/lb_listener_rule.html.markdown index c3939e4db73..b237a2e2869 100644 --- a/website/docs/r/lb_listener_rule.html.markdown +++ b/website/docs/r/lb_listener_rule.html.markdown @@ -24,12 +24,12 @@ resource "aws_lb_listener" "front_end" { } resource "aws_lb_listener_rule" "static" { - listener_arn = "${aws_lb_listener.front_end.arn}" + listener_arn = aws_lb_listener.front_end.arn priority = 100 action { type = "forward" - target_group_arn = "${aws_lb_target_group.static.arn}" + target_group_arn = aws_lb_target_group.static.arn } condition { @@ -47,13 +47,46 @@ resource "aws_lb_listener_rule" "static" { # Forward action -resource "aws_lb_listener_rule" "host_based_routing" { - listener_arn = "${aws_lb_listener.front_end.arn}" +resource "aws_lb_listener_rule" "host_based_weighted_routing" { + listener_arn = aws_lb_listener.front_end.arn priority = 99 action { type = "forward" - target_group_arn = "${aws_lb_target_group.static.arn}" + target_group_arn = aws_lb_target_group.static.arn + } + + condition { + host_header { + values = ["my-service.*.terraform.io"] + } + } +} + +# Weighted Forward action + +resource "aws_lb_listener_rule" "host_based_routing" { + listener_arn = aws_lb_listener.front_end.arn + priority = 99 + + action { + type = "forward" + forward { + target_group { + arn = aws_lb_target_group.main.arn + weight = 80 + } + + target_group { + arn = aws_lb_target_group.canary.arn + weight = 20 + } + + stickiness { + enabled = true + duration = 600 + } + } } condition { @@ -66,7 +99,7 @@ resource "aws_lb_listener_rule" "host_based_routing" { # Redirect action resource "aws_lb_listener_rule" "redirect_http_to_https" { - listener_arn = "${aws_lb_listener.front_end.arn}" + listener_arn = aws_lb_listener.front_end.arn action { type = "redirect" @@ -89,7 +122,7 @@ resource "aws_lb_listener_rule" "redirect_http_to_https" { # Fixed-response action resource "aws_lb_listener_rule" "health_check" { - listener_arn = "${aws_lb_listener.front_end.arn}" + listener_arn = aws_lb_listener.front_end.arn action { type = "fixed-response" @@ -128,28 +161,28 @@ resource "aws_cognito_user_pool_domain" "domain" { } resource "aws_lb_listener_rule" "admin" { - listener_arn = "${aws_lb_listener.front_end.arn}" + listener_arn = aws_lb_listener.front_end.arn action { type = "authenticate-cognito" authenticate_cognito { - user_pool_arn = "${aws_cognito_user_pool.pool.arn}" - user_pool_client_id = "${aws_cognito_user_pool_client.client.id}" - user_pool_domain = "${aws_cognito_user_pool_domain.domain.domain}" + user_pool_arn = aws_cognito_user_pool.pool.arn + user_pool_client_id = aws_cognito_user_pool_client.client.id + user_pool_domain = aws_cognito_user_pool_domain.domain.domain } } action { type = "forward" - target_group_arn = "${aws_lb_target_group.static.arn}" + target_group_arn = aws_lb_target_group.static.arn } } # Authenticate-oidc Action -resource "aws_lb_listener_rule" "admin" { - listener_arn = "${aws_lb_listener.front_end.arn}" +resource "aws_lb_listener_rule" "oidc" { + listener_arn = aws_lb_listener.front_end.arn action { type = "authenticate-oidc" @@ -166,7 +199,7 @@ resource "aws_lb_listener_rule" "admin" { action { type = "forward" - target_group_arn = "${aws_lb_target_group.static.arn}" + target_group_arn = aws_lb_target_group.static.arn } } ``` @@ -185,12 +218,28 @@ The following arguments are supported: Action Blocks (for `action`) support the following: * `type` - (Required) The type of routing action. Valid values are `forward`, `redirect`, `fixed-response`, `authenticate-cognito` and `authenticate-oidc`. -* `target_group_arn` - (Optional) The ARN of the Target Group to which to route traffic. Required if `type` is `forward`. +* `target_group_arn` - (Optional) The ARN of the Target Group to which to route traffic. Specify only if `type` is `forward` and you want to route to a single target group. To route to one or more target groups, use a `forward` block instead. +* `forward` - (Optional) Information for creating an action that distributes requests among one or more target groups. Specify only if `type` is `forward`. If you specify both `forward` block and `target_group_arn` attribute, you can specify only one target group using `forward` and it must be the same target group specified in `target_group_arn`. * `redirect` - (Optional) Information for creating a redirect action. Required if `type` is `redirect`. * `fixed_response` - (Optional) Information for creating an action that returns a custom HTTP response. Required if `type` is `fixed-response`. * `authenticate_cognito` - (Optional) Information for creating an authenticate action using Cognito. Required if `type` is `authenticate-cognito`. * `authenticate_oidc` - (Optional) Information for creating an authenticate action using OIDC. Required if `type` is `authenticate-oidc`. +Forward Blocks (for `forward`) support the following: + +* `target_group` - (Required) One or more target groups block. +* `stickiness` - (Optional) The target group stickiness for the rule. + +Target Group Blocks (for `target_group`) supports the following: + +* `arn` - (Required) The Amazon Resource Name (ARN) of the target group. +* `weight` - (Optional) The weight. The range is 0 to 999. + +Target Group Stickiness Config Blocks (for `stickiness`) supports the following: + +* `enabled` - (Required) Indicates whether target group stickiness is enabled. +* `duration` - (Optional) The time period, in seconds, during which requests from a client should be routed to the same target group. The range is 1-604800 seconds (7 days). + Redirect Blocks (for `redirect`) support the following: ~> **NOTE::** You can reuse URI components using the following reserved keywords: `#{protocol}`, `#{host}`, `#{port}`, `#{path}` (the leading "/" is removed) and `#{query}`. @@ -244,16 +293,14 @@ One or more condition blocks can be set per rule. Most condition types can only Condition Blocks (for `condition`) support the following: -* `field` - (Optional, **DEPRECATED**) The type of condition. Valid values are `host-header` or `path-pattern`. Must also set `values`. -* `values` - (Optional, **DEPRECATED**) List of exactly one pattern to match. Required when `field` is set. * `host_header` - (Optional) Contains a single `values` item which is a list of host header patterns to match. The maximum size of each pattern is 128 characters. Comparison is case insensitive. Wildcard characters supported: * (matches 0 or more characters) and ? (matches exactly 1 character). Only one pattern needs to match for the condition to be satisfied. * `http_header` - (Optional) HTTP headers to match. [HTTP Header block](#http-header-blocks) fields documented below. * `http_request_method` - (Optional) Contains a single `values` item which is a list of HTTP request methods or verbs to match. Maximum size is 40 characters. Only allowed characters are A-Z, hyphen (-) and underscore (\_). Comparison is case sensitive. Wildcards are not supported. Only one needs to match for the condition to be satisfied. AWS recommends that GET and HEAD requests are routed in the same way because the response to a HEAD request may be cached. -* `path_pattern` - (Optional) Contains a single `values` item which is a list of path patterns to match against the request URL. Maximum size of each pattern is 128 characters. Comparison is case sensitive. Wildcard characters supported: * (matches 0 or more characters) and ? (matches exactly 1 character). Only one pattern needs to match for the condition to be satisfied. Path pattern is compared only to the path of the URL, not to its query string. To compare against the query string, use a `query-string` condition. +* `path_pattern` - (Optional) Contains a single `values` item which is a list of path patterns to match against the request URL. Maximum size of each pattern is 128 characters. Comparison is case sensitive. Wildcard characters supported: * (matches 0 or more characters) and ? (matches exactly 1 character). Only one pattern needs to match for the condition to be satisfied. Path pattern is compared only to the path of the URL, not to its query string. To compare against the query string, use a `query_string` condition. * `query_string` - (Optional) Query strings to match. [Query String block](#query-string-blocks) fields documented below. -* `source_ip` - (Optional) Contains a single `values` item which is a list of source IP CIDR notations to match. You can use both IPv4 and IPv6 addresses. Wildcards are not supported. Condition is satisfied if the source IP address of the request matches one of the CIDR blocks. Condition is not satisfied by the addresses in the `X-Forwarded-For` header, use `http-header` condition instead. +* `source_ip` - (Optional) Contains a single `values` item which is a list of source IP CIDR notations to match. You can use both IPv4 and IPv6 addresses. Wildcards are not supported. Condition is satisfied if the source IP address of the request matches one of the CIDR blocks. Condition is not satisfied by the addresses in the `X-Forwarded-For` header, use `http_header` condition instead. -~> **NOTE::** Exactly one of `field`, `host_header`, `http_header`, `http_request_method`, `path_pattern`, `query_string` or `source_ip` must be set per condition. +~> **NOTE::** Exactly one of `host_header`, `http_header`, `http_request_method`, `path_pattern`, `query_string` or `source_ip` must be set per condition. #### HTTP Header Blocks diff --git a/website/docs/r/lb_ssl_negotiation_policy.html.markdown b/website/docs/r/lb_ssl_negotiation_policy.html.markdown index d94521feb73..57a71859bfb 100644 --- a/website/docs/r/lb_ssl_negotiation_policy.html.markdown +++ b/website/docs/r/lb_ssl_negotiation_policy.html.markdown @@ -28,7 +28,7 @@ resource "aws_elb" "lb" { resource "aws_lb_ssl_negotiation_policy" "foo" { name = "foo-policy" - load_balancer = "${aws_elb.lb.id}" + load_balancer = aws_elb.lb.id lb_port = 443 attribute { @@ -79,8 +79,8 @@ The following arguments are supported: should be applied. This must be an active listener on the load balancer. * `attribute` - (Optional) An SSL Negotiation policy attribute. Each has two properties: - * `name` - The name of the attribute - * `value` - The value of the attribute + * `name` - The name of the attribute + * `value` - The value of the attribute To set your attributes, please see the [AWS Elastic Load Balancing Developer Guide](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-security-policy-table.html) for a listing of the supported SSL protocols, SSL options, and SSL ciphers. diff --git a/website/docs/r/lb_target_group.html.markdown b/website/docs/r/lb_target_group.html.markdown index ab5ab92755a..c1be583cdf4 100644 --- a/website/docs/r/lb_target_group.html.markdown +++ b/website/docs/r/lb_target_group.html.markdown @@ -21,7 +21,7 @@ resource "aws_lb_target_group" "test" { name = "tf-example-lb-tg" port = 80 protocol = "HTTP" - vpc_id = "${aws_vpc.main.id}" + vpc_id = aws_vpc.main.id } resource "aws_vpc" "main" { @@ -37,7 +37,7 @@ resource "aws_lb_target_group" "ip-example" { port = 80 protocol = "HTTP" target_type = "ip" - vpc_id = "${aws_vpc.main.id}" + vpc_id = aws_vpc.main.id } resource "aws_vpc" "main" { diff --git a/website/docs/r/lb_target_group_attachment.html.markdown b/website/docs/r/lb_target_group_attachment.html.markdown index 0cc231d9e14..bad22f98311 100644 --- a/website/docs/r/lb_target_group_attachment.html.markdown +++ b/website/docs/r/lb_target_group_attachment.html.markdown @@ -17,17 +17,17 @@ Provides the ability to register instances and containers with an Application Lo ```hcl resource "aws_lb_target_group_attachment" "test" { - target_group_arn = "${aws_lb_target_group.test.arn}" - target_id = "${aws_instance.test.id}" + target_group_arn = aws_lb_target_group.test.arn + target_id = aws_instance.test.id port = 80 } resource "aws_lb_target_group" "test" { - // Other arguments + # ... other configuration ... } resource "aws_instance" "test" { - // Other arguments + # ... other configuration ... } ``` @@ -37,9 +37,9 @@ resource "aws_instance" "test" { resource "aws_lambda_permission" "with_lb" { statement_id = "AllowExecutionFromlb" action = "lambda:InvokeFunction" - function_name = "${aws_lambda_function.test.arn}" + function_name = aws_lambda_function.test.arn principal = "elasticloadbalancing.amazonaws.com" - source_arn = "${aws_lb_target_group.test.arn}" + source_arn = aws_lb_target_group.test.arn } resource "aws_lb_target_group" "test" { @@ -48,13 +48,13 @@ resource "aws_lb_target_group" "test" { } resource "aws_lambda_function" "test" { - // Other arguments + # ... other configuration ... } resource "aws_lb_target_group_attachment" "test" { - target_group_arn = "${aws_lb_target_group.test.arn}" - target_id = "${aws_lambda_function.test.arn}" - depends_on = ["aws_lambda_permission.with_lb"] + target_group_arn = aws_lb_target_group.test.arn + target_id = aws_lambda_function.test.arn + depends_on = [aws_lambda_permission.with_lb] } ``` @@ -65,7 +65,7 @@ The following arguments are supported: * `target_group_arn` - (Required) The ARN of the target group with which to register targets * `target_id` (Required) The ID of the target. This is the Instance ID for an instance, or the container ID for an ECS container. If the target type is ip, specify an IP address. If the target type is lambda, specify the arn of lambda. * `port` - (Optional) The port on which targets receive traffic. -* `availability_zone` - (Optional) The Availability Zone where the IP address of the target is to be registered. +* `availability_zone` - (Optional) The Availability Zone where the IP address of the target is to be registered. If the private ip address is outside of the VPC scope, this value must be set to 'all'. ## Attributes Reference diff --git a/website/docs/r/licensemanager_association.markdown b/website/docs/r/licensemanager_association.markdown index fdae597d893..720df0a343e 100644 --- a/website/docs/r/licensemanager_association.markdown +++ b/website/docs/r/licensemanager_association.markdown @@ -26,7 +26,7 @@ data "aws_ami" "example" { } resource "aws_instance" "example" { - ami = "${data.aws_ami.example.id}" + ami = data.aws_ami.example.id instance_type = "t2.micro" } @@ -36,8 +36,8 @@ resource "aws_licensemanager_license_configuration" "example" { } resource "aws_licensemanager_association" "example" { - license_configuration_arn = "${aws_licensemanager_license_configuration.example.arn}" - resource_arn = "${aws_instance.example.arn}" + license_configuration_arn = aws_licensemanager_license_configuration.example.arn + resource_arn = aws_instance.example.arn } ``` diff --git a/website/docs/r/lightsail_key_pair.html.markdown b/website/docs/r/lightsail_key_pair.html.markdown index 021a74c3e57..acaff9b45b0 100644 --- a/website/docs/r/lightsail_key_pair.html.markdown +++ b/website/docs/r/lightsail_key_pair.html.markdown @@ -37,7 +37,7 @@ resource "aws_lightsail_key_pair" "lg_key_pair" { ```hcl resource "aws_lightsail_key_pair" "lg_key_pair" { name = "importing" - public_key = "${file("~/.ssh/id_rsa.pub")}" + public_key = file("~/.ssh/id_rsa.pub") } ``` diff --git a/website/docs/r/lightsail_static_ip_attachment.html.markdown b/website/docs/r/lightsail_static_ip_attachment.html.markdown index fbab38c3a69..0a132dbe5f5 100644 --- a/website/docs/r/lightsail_static_ip_attachment.html.markdown +++ b/website/docs/r/lightsail_static_ip_attachment.html.markdown @@ -16,8 +16,8 @@ Provides a static IP address attachment - relationship between a Lightsail stati ```hcl resource "aws_lightsail_static_ip_attachment" "test" { - static_ip_name = "${aws_lightsail_static_ip.test.id}" - instance_name = "${aws_lightsail_instance.test.id}" + static_ip_name = aws_lightsail_static_ip.test.id + instance_name = aws_lightsail_instance.test.id } resource "aws_lightsail_static_ip" "test" { diff --git a/website/docs/r/load_balancer_backend_server_policy.html.markdown b/website/docs/r/load_balancer_backend_server_policy.html.markdown index 06c7f510e30..63961e2fd37 100644 --- a/website/docs/r/load_balancer_backend_server_policy.html.markdown +++ b/website/docs/r/load_balancer_backend_server_policy.html.markdown @@ -32,33 +32,33 @@ resource "aws_elb" "wu-tang" { } resource "aws_load_balancer_policy" "wu-tang-ca-pubkey-policy" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name policy_name = "wu-tang-ca-pubkey-policy" policy_type_name = "PublicKeyPolicyType" policy_attribute { name = "PublicKey" - value = "${file("wu-tang-pubkey")}" + value = file("wu-tang-pubkey") } } resource "aws_load_balancer_policy" "wu-tang-root-ca-backend-auth-policy" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name policy_name = "wu-tang-root-ca-backend-auth-policy" policy_type_name = "BackendServerAuthenticationPolicyType" policy_attribute { name = "PublicKeyPolicyName" - value = "${aws_load_balancer_policy.wu-tang-root-ca-pubkey-policy.policy_name}" + value = aws_load_balancer_policy.wu-tang-root-ca-pubkey-policy.policy_name } } resource "aws_load_balancer_backend_server_policy" "wu-tang-backend-auth-policies-443" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name instance_port = 443 policy_names = [ - "${aws_load_balancer_policy.wu-tang-root-ca-backend-auth-policy.policy_name}", + aws_load_balancer_policy.wu-tang-root-ca-backend-auth-policy.policy_name, ] } ``` diff --git a/website/docs/r/load_balancer_listener_policy.html.markdown b/website/docs/r/load_balancer_listener_policy.html.markdown index 0e9d7879868..05ebc11ad05 100644 --- a/website/docs/r/load_balancer_listener_policy.html.markdown +++ b/website/docs/r/load_balancer_listener_policy.html.markdown @@ -32,7 +32,7 @@ resource "aws_elb" "wu-tang" { } resource "aws_load_balancer_policy" "wu-tang-ssl" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name policy_name = "wu-tang-ssl" policy_type_name = "SSLNegotiationPolicyType" @@ -48,11 +48,11 @@ resource "aws_load_balancer_policy" "wu-tang-ssl" { } resource "aws_load_balancer_listener_policy" "wu-tang-listener-policies-443" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name load_balancer_port = 443 policy_names = [ - "${aws_load_balancer_policy.wu-tang-ssl.policy_name}", + aws_load_balancer_policy.wu-tang-ssl.policy_name, ] } ``` @@ -80,7 +80,7 @@ resource "aws_elb" "wu-tang" { } resource "aws_load_balancer_policy" "wu-tang-ssl-tls-1-1" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name policy_name = "wu-tang-ssl" policy_type_name = "SSLNegotiationPolicyType" @@ -91,11 +91,11 @@ resource "aws_load_balancer_policy" "wu-tang-ssl-tls-1-1" { } resource "aws_load_balancer_listener_policy" "wu-tang-listener-policies-443" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name load_balancer_port = 443 policy_names = [ - "${aws_load_balancer_policy.wu-tang-ssl-tls-1-1.policy_name}", + aws_load_balancer_policy.wu-tang-ssl-tls-1-1.policy_name, ] } ``` diff --git a/website/docs/r/load_balancer_policy.html.markdown b/website/docs/r/load_balancer_policy.html.markdown index 9ed1d7ecd42..8bf1b8fb766 100644 --- a/website/docs/r/load_balancer_policy.html.markdown +++ b/website/docs/r/load_balancer_policy.html.markdown @@ -31,29 +31,29 @@ resource "aws_elb" "wu-tang" { } resource "aws_load_balancer_policy" "wu-tang-ca-pubkey-policy" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name policy_name = "wu-tang-ca-pubkey-policy" policy_type_name = "PublicKeyPolicyType" policy_attribute { name = "PublicKey" - value = "${file("wu-tang-pubkey")}" + value = file("wu-tang-pubkey") } } resource "aws_load_balancer_policy" "wu-tang-root-ca-backend-auth-policy" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name policy_name = "wu-tang-root-ca-backend-auth-policy" policy_type_name = "BackendServerAuthenticationPolicyType" policy_attribute { name = "PublicKeyPolicyName" - value = "${aws_load_balancer_policy.wu-tang-root-ca-pubkey-policy.policy_name}" + value = aws_load_balancer_policy.wu-tang-root-ca-pubkey-policy.policy_name } } resource "aws_load_balancer_policy" "wu-tang-ssl" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name policy_name = "wu-tang-ssl" policy_type_name = "SSLNegotiationPolicyType" @@ -69,7 +69,7 @@ resource "aws_load_balancer_policy" "wu-tang-ssl" { } resource "aws_load_balancer_policy" "wu-tang-ssl-tls-1-1" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name policy_name = "wu-tang-ssl" policy_type_name = "SSLNegotiationPolicyType" @@ -80,20 +80,20 @@ resource "aws_load_balancer_policy" "wu-tang-ssl-tls-1-1" { } resource "aws_load_balancer_backend_server_policy" "wu-tang-backend-auth-policies-443" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name instance_port = 443 policy_names = [ - "${aws_load_balancer_policy.wu-tang-root-ca-backend-auth-policy.policy_name}", + aws_load_balancer_policy.wu-tang-root-ca-backend-auth-policy.policy_name, ] } resource "aws_load_balancer_listener_policy" "wu-tang-listener-policies-443" { - load_balancer_name = "${aws_elb.wu-tang.name}" + load_balancer_name = aws_elb.wu-tang.name load_balancer_port = 443 policy_names = [ - "${aws_load_balancer_policy.wu-tang-ssl.policy_name}", + aws_load_balancer_policy.wu-tang-ssl.policy_name, ] } ``` diff --git a/website/docs/r/macie_member_account_association.html.markdown b/website/docs/r/macie_member_account_association.html.markdown index 44e81edd8da..237c727fbe5 100644 --- a/website/docs/r/macie_member_account_association.html.markdown +++ b/website/docs/r/macie_member_account_association.html.markdown @@ -1,5 +1,5 @@ --- -subcategory: "Macie" +subcategory: "Macie Classic" layout: "aws" page_title: "AWS: aws_macie_member_account_association" description: |- @@ -8,6 +8,8 @@ description: |- # Resource: aws_macie_member_account_association +~> **NOTE:** This resource interacts with [Amazon Macie Classic](https://docs.aws.amazon.com/macie/latest/userguide/what-is-macie.html). Macie Classic cannot be activated in new accounts. See the [FAQ](https://aws.amazon.com/macie/classic-faqs/) for more details. + Associates an AWS account with Amazon Macie as a member account. ~> **NOTE:** Before using Amazon Macie for the first time it must be enabled manually. Instructions are [here](https://docs.aws.amazon.com/macie/latest/userguide/macie-setting-up.html#macie-setting-up-enable). diff --git a/website/docs/r/macie_s3_bucket_association.html.markdown b/website/docs/r/macie_s3_bucket_association.html.markdown index 6fe7d84522b..ed0bb6f2e44 100644 --- a/website/docs/r/macie_s3_bucket_association.html.markdown +++ b/website/docs/r/macie_s3_bucket_association.html.markdown @@ -1,5 +1,5 @@ --- -subcategory: "Macie" +subcategory: "Macie Classic" layout: "aws" page_title: "AWS: aws_macie_s3_bucket_association" description: |- @@ -8,6 +8,8 @@ description: |- # Resource: aws_macie_s3_bucket_association +~> **NOTE:** This resource interacts with [Amazon Macie Classic](https://docs.aws.amazon.com/macie/latest/userguide/what-is-macie.html). Macie Classic cannot be activated in new accounts. See the [FAQ](https://aws.amazon.com/macie/classic-faqs/) for more details. + Associates an S3 resource with Amazon Macie for monitoring and data classification. ~> **NOTE:** Before using Amazon Macie for the first time it must be enabled manually. Instructions are [here](https://docs.aws.amazon.com/macie/latest/userguide/macie-setting-up.html#macie-setting-up-enable). diff --git a/website/docs/r/main_route_table_association.html.markdown b/website/docs/r/main_route_table_association.html.markdown index f0dbd3a22c9..9e011728705 100644 --- a/website/docs/r/main_route_table_association.html.markdown +++ b/website/docs/r/main_route_table_association.html.markdown @@ -14,8 +14,8 @@ Provides a resource for managing the main routing table of a VPC. ```hcl resource "aws_main_route_table_association" "a" { - vpc_id = "${aws_vpc.foo.id}" - route_table_id = "${aws_route_table.bar.id}" + vpc_id = aws_vpc.foo.id + route_table_id = aws_route_table.bar.id } ``` diff --git a/website/docs/r/media_package_channel.html.markdown b/website/docs/r/media_package_channel.html.markdown index d1d40b42c7d..4910ea7ed6a 100644 --- a/website/docs/r/media_package_channel.html.markdown +++ b/website/docs/r/media_package_channel.html.markdown @@ -34,10 +34,10 @@ In addition to all arguments above, the following attributes are exported: * `id` - The same as `channel_id` * `arn` - The ARN of the channel * `hls_ingest` - A single item list of HLS ingest information - * `ingest_endpoints` - A list of the ingest endpoints - * `password` - The password - * `url` - The URL - * `username` - The username + * `ingest_endpoints` - A list of the ingest endpoints + * `password` - The password + * `url` - The URL + * `username` - The username ## Import diff --git a/website/docs/r/media_store_container_policy.html.markdown b/website/docs/r/media_store_container_policy.html.markdown index b1c5edc9321..1476c77b5a0 100644 --- a/website/docs/r/media_store_container_policy.html.markdown +++ b/website/docs/r/media_store_container_policy.html.markdown @@ -22,7 +22,7 @@ resource "aws_media_store_container" "example" { } resource "aws_media_store_container_policy" "example" { - container_name = "${aws_media_store_container.example.name}" + container_name = aws_media_store_container.example.name policy = < **Note:** At least one of either `fqdn` or `ip_address` must be specified. + * `reference_name` - (Optional) This is a reference name used in Caller Reference (helpful for identifying single health_check set amongst others) * `fqdn` - (Optional) The fully qualified domain name of the endpoint to be checked. @@ -95,6 +97,12 @@ The following arguments are supported: * `search_string` - (Optional) String searched in the first 5120 bytes of the response body for check to be considered healthy. Only valid with `HTTP_STR_MATCH` and `HTTPS_STR_MATCH`. * `measure_latency` - (Optional) A Boolean value that indicates whether you want Route 53 to measure the latency between health checkers in multiple AWS regions and your endpoint and to display CloudWatch latency graphs in the Route 53 console. * `invert_healthcheck` - (Optional) A boolean value that indicates whether the status of health check should be inverted. For example, if a health check is healthy but Inverted is True , then Route 53 considers the health check to be unhealthy. +* `disabled` - (Optional) A boolean value that stops Route 53 from performing health checks. When set to true, Route 53 will do the following depending on the type of health check: + * For health checks that check the health of endpoints, Route5 53 stops submitting requests to your application, server, or other resource. + * For calculated health checks, Route 53 stops aggregating the status of the referenced health checks. + * For health checks that monitor CloudWatch alarms, Route 53 stops monitoring the corresponding CloudWatch metrics. + + ~> **Note:** After you disable a health check, Route 53 considers the status of the health check to always be healthy. If you configured DNS failover, Route 53 continues to route traffic to the corresponding resources. If you want to stop routing traffic to a resource, change the value of `invert_healthcheck`. * `enable_sni` - (Optional) A boolean value that indicates whether Route53 should send the `fqdn` to the endpoint when performing the health check. This defaults to AWS' defaults: when the `type` is "HTTPS" `enable_sni` defaults to `true`, when `type` is anything else `enable_sni` defaults to `false`. * `child_healthchecks` - (Optional) For a specified parent health check, a list of HealthCheckId values for the associated child health checks. * `child_health_threshold` - (Optional) The minimum number of child health checks that must be healthy for Route 53 to consider the parent health check to be healthy. Valid values are integers between 0 and 256, inclusive @@ -105,8 +113,6 @@ The following arguments are supported: * `tags` - (Optional) A map of tags to assign to the health check. -At least one of either `fqdn` or `ip_address` must be specified. - ## Attributes Reference The following attributes are exported in addition to the arguments listed above: diff --git a/website/docs/r/route53_query_log.html.markdown b/website/docs/r/route53_query_log.html.markdown index b0dc2ede0d4..9e20e531b84 100644 --- a/website/docs/r/route53_query_log.html.markdown +++ b/website/docs/r/route53_query_log.html.markdown @@ -27,7 +27,7 @@ provider "aws" { } resource "aws_cloudwatch_log_group" "aws_route53_example_com" { - provider = "aws.us-east-1" + provider = aws.us-east-1 name = "/aws/route53/${aws_route53_zone.example_com.name}" retention_in_days = 30 @@ -53,9 +53,9 @@ data "aws_iam_policy_document" "route53-query-logging-policy" { } resource "aws_cloudwatch_log_resource_policy" "route53-query-logging-policy" { - provider = "aws.us-east-1" + provider = aws.us-east-1 - policy_document = "${data.aws_iam_policy_document.route53-query-logging-policy.json}" + policy_document = data.aws_iam_policy_document.route53-query-logging-policy.json policy_name = "route53-query-logging-policy" } @@ -66,10 +66,10 @@ resource "aws_route53_zone" "example_com" { } resource "aws_route53_query_log" "example_com" { - depends_on = ["aws_cloudwatch_log_resource_policy.route53-query-logging-policy"] + depends_on = [aws_cloudwatch_log_resource_policy.route53-query-logging-policy] - cloudwatch_log_group_arn = "${aws_cloudwatch_log_group.aws_route53_example_com.arn}" - zone_id = "${aws_route53_zone.example_com.zone_id}" + cloudwatch_log_group_arn = aws_cloudwatch_log_group.aws_route53_example_com.arn + zone_id = aws_route53_zone.example_com.zone_id } ``` diff --git a/website/docs/r/route53_record.html.markdown b/website/docs/r/route53_record.html.markdown index 7a51f8827c4..a0a78ec945d 100644 --- a/website/docs/r/route53_record.html.markdown +++ b/website/docs/r/route53_record.html.markdown @@ -16,11 +16,11 @@ Provides a Route53 record resource. ```hcl resource "aws_route53_record" "www" { - zone_id = "${aws_route53_zone.primary.zone_id}" + zone_id = aws_route53_zone.primary.zone_id name = "www.example.com" type = "A" ttl = "300" - records = ["${aws_eip.lb.public_ip}"] + records = [aws_eip.lb.public_ip] } ``` @@ -29,7 +29,7 @@ Other routing policies are configured similarly. See [AWS Route53 Developer Guid ```hcl resource "aws_route53_record" "www-dev" { - zone_id = "${aws_route53_zone.primary.zone_id}" + zone_id = aws_route53_zone.primary.zone_id name = "www" type = "CNAME" ttl = "5" @@ -43,7 +43,7 @@ resource "aws_route53_record" "www-dev" { } resource "aws_route53_record" "www-live" { - zone_id = "${aws_route53_zone.primary.zone_id}" + zone_id = aws_route53_zone.primary.zone_id name = "www" type = "CNAME" ttl = "5" @@ -78,13 +78,13 @@ resource "aws_elb" "main" { } resource "aws_route53_record" "www" { - zone_id = "${aws_route53_zone.primary.zone_id}" + zone_id = aws_route53_zone.primary.zone_id name = "example.com" type = "A" alias { - name = "${aws_elb.main.dns_name}" - zone_id = "${aws_elb.main.zone_id}" + name = aws_elb.main.dns_name + zone_id = aws_elb.main.zone_id evaluate_target_health = true } } @@ -104,13 +104,13 @@ resource "aws_route53_record" "example" { name = "test.example.com" ttl = 30 type = "NS" - zone_id = "${aws_route53_zone.example.zone_id}" + zone_id = aws_route53_zone.example.zone_id records = [ - "${aws_route53_zone.example.name_servers.0}", - "${aws_route53_zone.example.name_servers.1}", - "${aws_route53_zone.example.name_servers.2}", - "${aws_route53_zone.example.name_servers.3}", + aws_route53_zone.example.name_servers[0], + aws_route53_zone.example.name_servers[1], + aws_route53_zone.example.name_servers[2], + aws_route53_zone.example.name_servers[3], ] } ``` diff --git a/website/docs/r/route53_resolver_endpoint.html.markdown b/website/docs/r/route53_resolver_endpoint.html.markdown index 3968bd8cd68..215d1d5104a 100644 --- a/website/docs/r/route53_resolver_endpoint.html.markdown +++ b/website/docs/r/route53_resolver_endpoint.html.markdown @@ -18,20 +18,20 @@ resource "aws_route53_resolver_endpoint" "foo" { direction = "INBOUND" security_group_ids = [ - "${aws_security_group.sg1.id}", - "${aws_security_group.sg2.id}", + aws_security_group.sg1.id, + aws_security_group.sg2.id, ] ip_address { - subnet_id = "${aws_subnet.sn1.id}" + subnet_id = aws_subnet.sn1.id } ip_address { - subnet_id = "${aws_subnet.sn2.id}" + subnet_id = aws_subnet.sn2.id ip = "10.0.64.4" } - tags { + tags = { Environment = "Prod" } } diff --git a/website/docs/r/route53_resolver_rule.html.markdown b/website/docs/r/route53_resolver_rule.html.markdown index 34bd33101a9..d5594f5db0d 100644 --- a/website/docs/r/route53_resolver_rule.html.markdown +++ b/website/docs/r/route53_resolver_rule.html.markdown @@ -28,13 +28,13 @@ resource "aws_route53_resolver_rule" "fwd" { domain_name = "example.com" name = "example" rule_type = "FORWARD" - resolver_endpoint_id = "${aws_route53_resolver_endpoint.foo.id}" + resolver_endpoint_id = aws_route53_resolver_endpoint.foo.id target_ip { ip = "123.45.67.89" } - tags { + tags = { Environment = "Prod" } } diff --git a/website/docs/r/route53_resolver_rule_association.html.markdown b/website/docs/r/route53_resolver_rule_association.html.markdown index f433de524d5..3435b89e018 100644 --- a/website/docs/r/route53_resolver_rule_association.html.markdown +++ b/website/docs/r/route53_resolver_rule_association.html.markdown @@ -14,8 +14,8 @@ Provides a Route53 Resolver rule association. ```hcl resource "aws_route53_resolver_rule_association" "example" { - resolver_rule_id = "${aws_route53_resolver_rule.sys.id}" - vpc_id = "${aws_vpc.foo.id}" + resolver_rule_id = aws_route53_resolver_rule.sys.id + vpc_id = aws_vpc.foo.id } ``` diff --git a/website/docs/r/route53_vpc_association_authorization.html.markdown b/website/docs/r/route53_vpc_association_authorization.html.markdown new file mode 100644 index 00000000000..85dcdcbba03 --- /dev/null +++ b/website/docs/r/route53_vpc_association_authorization.html.markdown @@ -0,0 +1,78 @@ +--- +subcategory: "Route53" +layout: "aws" +page_title: "AWS: aws_route53_vpc_association_authorization" +description: |- + Authorizes a VPC in a peer account to be associated with a local Route53 Hosted Zone +--- + +# Resource: aws_route53_vpc_association_authorization + +Authorizes a VPC in a peer account to be associated with a local Route53 Hosted Zone. + +## Example Usage + +```hcl +provider "aws" { +} + +provider "aws" { + alias = "alternate" +} + +resource "aws_vpc" "example" { + cidr_block = "10.6.0.0/16" + enable_dns_hostnames = true + enable_dns_support = true +} + +resource "aws_route53_zone" "example" { + name = "example.com" + + vpc { + vpc_id = aws_vpc.example.id + } +} + +resource "aws_vpc" "alternate" { + provider = "aws.alternate" + + cidr_block = "10.7.0.0/16" + enable_dns_hostnames = true + enable_dns_support = true +} + +resource "aws_route53_vpc_association_authorization" "example" { + vpc_id = aws_vpc.alternate.id + zone_id = aws_route53_zone.example.id +} + +resource "aws_route53_zone_association" "example" { + provider = "aws.alternate" + + vpc_id = aws_route53_vpc_association_authorization.example.vpc_id + zone_id = aws_route53_vpc_association_authorization.example.zone_id +} +``` + +## Argument Reference + +The following arguments are supported: + +* `zone_id` - (Required) The ID of the private hosted zone that you want to authorize associating a VPC with. +* `vpc_id` - (Required) The VPC to authorize for association with the private hosted zone. +* `vpc_region` - (Optional) The VPC's region. Defaults to the region of the AWS provider. + +## Attributes Reference + +The following attributes are exported: + +* `id` - The calculated unique identifier for the association. + +## Import + +Route 53 VPC Association Authorizations can be imported via the Hosted Zone ID and VPC ID, separated by a colon (`:`), e.g. + +``` +$ terraform import aws_route53_vpc_association_authorization.example Z123456ABCDEFG:vpc-12345678 +``` diff --git a/website/docs/r/route53_zone.html.markdown b/website/docs/r/route53_zone.html.markdown index 87da2694d15..b50dbeec2a1 100644 --- a/website/docs/r/route53_zone.html.markdown +++ b/website/docs/r/route53_zone.html.markdown @@ -40,17 +40,11 @@ resource "aws_route53_zone" "dev" { } resource "aws_route53_record" "dev-ns" { - zone_id = "${aws_route53_zone.main.zone_id}" + zone_id = aws_route53_zone.main.zone_id name = "dev.example.com" type = "NS" ttl = "30" - - records = [ - "${aws_route53_zone.dev.name_servers.0}", - "${aws_route53_zone.dev.name_servers.1}", - "${aws_route53_zone.dev.name_servers.2}", - "${aws_route53_zone.dev.name_servers.3}", - ] + records = aws_route53_zone.dev.name_servers } ``` @@ -65,7 +59,7 @@ resource "aws_route53_zone" "private" { name = "example.com" vpc { - vpc_id = "${aws_vpc.example.id}" + vpc_id = aws_vpc.example.id } } ``` diff --git a/website/docs/r/route53_zone_association.html.markdown b/website/docs/r/route53_zone_association.html.markdown index 51e47f421e8..dde709ee8e6 100644 --- a/website/docs/r/route53_zone_association.html.markdown +++ b/website/docs/r/route53_zone_association.html.markdown @@ -8,7 +8,7 @@ description: |- # Resource: aws_route53_zone_association -Manages a Route53 Hosted Zone VPC association. VPC associations can only be made on private zones. +Manages a Route53 Hosted Zone VPC association. VPC associations can only be made on private zones. See the [`aws_route53_vpc_association_authorization` resource](route53_vpc_association_authorization.html) for setting up cross-account associations. ~> **NOTE:** Unless explicit association ordering is required (e.g. a separate cross-account association authorization), usage of this resource is not recommended. Use the `vpc` configuration blocks available within the [`aws_route53_zone` resource](/docs/providers/aws/r/route53_zone.html) instead. @@ -38,17 +38,17 @@ resource "aws_route53_zone" "example" { # resource is for illustrative purposes (e.g. for a separate # cross-account authorization process, which is not shown here). vpc { - vpc_id = "${aws_vpc.primary.id}" + vpc_id = aws_vpc.primary.id } lifecycle { - ignore_changes = ["vpc"] + ignore_changes = [vpc] } } resource "aws_route53_zone_association" "secondary" { - zone_id = "${aws_route53_zone.example.zone_id}" - vpc_id = "${aws_vpc.secondary.id}" + zone_id = aws_route53_zone.example.zone_id + vpc_id = aws_vpc.secondary.id } ``` @@ -65,9 +65,7 @@ The following arguments are supported: In addition to all arguments above, the following attributes are exported: * `id` - The calculated unique identifier for the association. -* `zone_id` - The ID of the hosted zone for the association. -* `vpc_id` - The ID of the VPC for the association. -* `vpc_region` - The region in which the VPC identified by `vpc_id` was created. +* `owning_account` - The account ID of the account that created the hosted zone. ## Import @@ -76,3 +74,9 @@ Route 53 Hosted Zone Associations can be imported via the Hosted Zone ID and VPC ``` $ terraform import aws_route53_zone_association.example Z123456ABCDEFG:vpc-12345678 ``` + +If the VPC is in a different region than the Terraform AWS Provider region configuration, the VPC Region can be added to the end. e.g. + +``` +$ terraform import aws_route53_zone_association.example Z123456ABCDEFG:vpc-12345678:us-east-2 +``` diff --git a/website/docs/r/route_table.html.markdown b/website/docs/r/route_table.html.markdown index da6df8680c9..b26b1d3ee8c 100644 --- a/website/docs/r/route_table.html.markdown +++ b/website/docs/r/route_table.html.markdown @@ -33,16 +33,16 @@ the separate resource. ```hcl resource "aws_route_table" "r" { - vpc_id = "${aws_vpc.default.id}" + vpc_id = aws_vpc.default.id route { cidr_block = "10.0.1.0/24" - gateway_id = "${aws_internet_gateway.main.id}" + gateway_id = aws_internet_gateway.main.id } route { ipv6_cidr_block = "::/0" - egress_only_gateway_id = "${aws_egress_only_internet_gateway.foo.id}" + egress_only_gateway_id = aws_egress_only_internet_gateway.foo.id } tags = { diff --git a/website/docs/r/s3_access_point.html.markdown b/website/docs/r/s3_access_point.html.markdown index 237a99590a2..a2245f3ea9b 100644 --- a/website/docs/r/s3_access_point.html.markdown +++ b/website/docs/r/s3_access_point.html.markdown @@ -67,15 +67,15 @@ The following arguments are optional: The following arguments are optional: * `block_public_acls` - (Optional) Whether Amazon S3 should block public ACLs for buckets in this account. Defaults to `true`. Enabling this setting does not affect existing policies or ACLs. When set to `true` causes the following behavior: - * PUT Bucket acl and PUT Object acl calls fail if the specified ACL is public. - * PUT Object calls fail if the request includes a public ACL. - * PUT Bucket calls fail if the request includes a public ACL. + * PUT Bucket acl and PUT Object acl calls fail if the specified ACL is public. + * PUT Object calls fail if the request includes a public ACL. + * PUT Bucket calls fail if the request includes a public ACL. * `block_public_policy` - (Optional) Whether Amazon S3 should block public bucket policies for buckets in this account. Defaults to `true`. Enabling this setting does not affect existing bucket policies. When set to `true` causes Amazon S3 to: - * Reject calls to PUT Bucket policy if the specified bucket policy allows public access. + * Reject calls to PUT Bucket policy if the specified bucket policy allows public access. * `ignore_public_acls` - (Optional) Whether Amazon S3 should ignore public ACLs for buckets in this account. Defaults to `true`. Enabling this setting does not affect the persistence of any existing ACLs and doesn't prevent new public ACLs from being set. When set to `true` causes Amazon S3 to: - * Ignore all public ACLs on buckets in this account and any objects that they contain. + * Ignore all public ACLs on buckets in this account and any objects that they contain. * `restrict_public_buckets` - (Optional) Whether Amazon S3 should restrict public bucket policies for buckets in this account. Defaults to `true`. Enabling this setting does not affect previously stored bucket policies, except that public and cross-account access within any public bucket policy, including non-public delegation to specific accounts, is blocked. When set to `true`: - * Only the bucket owner and AWS Services can access buckets with public policies. + * Only the bucket owner and AWS Services can access buckets with public policies. ### vpc_configuration Configuration Block diff --git a/website/docs/r/s3_account_public_access_block.html.markdown b/website/docs/r/s3_account_public_access_block.html.markdown index 0ecb1b4fda9..52fd11000df 100644 --- a/website/docs/r/s3_account_public_access_block.html.markdown +++ b/website/docs/r/s3_account_public_access_block.html.markdown @@ -29,14 +29,14 @@ The following arguments are supported: * `account_id` - (Optional) AWS account ID to configure. Defaults to automatically determined account ID of the Terraform AWS provider. * `block_public_acls` - (Optional) Whether Amazon S3 should block public ACLs for buckets in this account. Defaults to `false`. Enabling this setting does not affect existing policies or ACLs. When set to `true` causes the following behavior: - * PUT Bucket acl and PUT Object acl calls will fail if the specified ACL allows public access. - * PUT Object calls will fail if the request includes an object ACL. + * PUT Bucket acl and PUT Object acl calls will fail if the specified ACL allows public access. + * PUT Object calls will fail if the request includes an object ACL. * `block_public_policy` - (Optional) Whether Amazon S3 should block public bucket policies for buckets in this account. Defaults to `false`. Enabling this setting does not affect existing bucket policies. When set to `true` causes Amazon S3 to: - * Reject calls to PUT Bucket policy if the specified bucket policy allows public access. + * Reject calls to PUT Bucket policy if the specified bucket policy allows public access. * `ignore_public_acls` - (Optional) Whether Amazon S3 should ignore public ACLs for buckets in this account. Defaults to `false`. Enabling this setting does not affect the persistence of any existing ACLs and doesn't prevent new public ACLs from being set. When set to `true` causes Amazon S3 to: - * Ignore all public ACLs on buckets in this account and any objects that they contain. + * Ignore all public ACLs on buckets in this account and any objects that they contain. * `restrict_public_buckets` - (Optional) Whether Amazon S3 should restrict public bucket policies for buckets in this account. Defaults to `false`. Enabling this setting does not affect previously stored bucket policies, except that public and cross-account access within any public bucket policy, including non-public delegation to specific accounts, is blocked. When set to `true`: - * Only the bucket owner and AWS Services can access buckets with public policies. + * Only the bucket owner and AWS Services can access buckets with public policies. ## Attribute Reference diff --git a/website/docs/r/s3_bucket.html.markdown b/website/docs/r/s3_bucket.html.markdown index 6eb96a9d192..fd0d3e5450a 100644 --- a/website/docs/r/s3_bucket.html.markdown +++ b/website/docs/r/s3_bucket.html.markdown @@ -32,7 +32,7 @@ resource "aws_s3_bucket" "b" { resource "aws_s3_bucket" "b" { bucket = "s3-website-test.hashicorp.com" acl = "public-read" - policy = "${file("policy.json")}" + policy = file("policy.json") website { index_document = "index.html" @@ -95,7 +95,7 @@ resource "aws_s3_bucket" "b" { acl = "private" logging { - target_bucket = "${aws_s3_bucket.log_bucket.id}" + target_bucket = aws_s3_bucket.log_bucket.id target_prefix = "log/" } } @@ -247,13 +247,12 @@ POLICY } resource "aws_iam_role_policy_attachment" "replication" { - role = "${aws_iam_role.replication.name}" - policy_arn = "${aws_iam_policy.replication.arn}" + role = aws_iam_role.replication.name + policy_arn = aws_iam_policy.replication.arn } resource "aws_s3_bucket" "destination" { bucket = "tf-test-bucket-destination-12345" - region = "eu-west-1" versioning { enabled = true @@ -261,17 +260,16 @@ resource "aws_s3_bucket" "destination" { } resource "aws_s3_bucket" "bucket" { - provider = "aws.central" + provider = aws.central bucket = "tf-test-bucket-12345" acl = "private" - region = "eu-central-1" versioning { enabled = true } replication_configuration { - role = "${aws_iam_role.replication.arn}" + role = aws_iam_role.replication.arn rules { id = "foobar" @@ -279,7 +277,7 @@ resource "aws_s3_bucket" "bucket" { status = "Enabled" destination { - bucket = "${aws_s3_bucket.destination.arn}" + bucket = aws_s3_bucket.destination.arn storage_class = "STANDARD" } } @@ -301,7 +299,7 @@ resource "aws_s3_bucket" "mybucket" { server_side_encryption_configuration { rule { apply_server_side_encryption_by_default { - kms_master_key_id = "${aws_kms_key.mykey.arn}" + kms_master_key_id = aws_kms_key.mykey.arn sse_algorithm = "aws:kms" } } @@ -318,7 +316,7 @@ resource "aws_s3_bucket" "bucket" { bucket = "mybucket" grant { - id = "${data.aws_canonical_user_id.current_user.id}" + id = data.aws_canonical_user_id.current_user.id type = "CanonicalUser" permissions = ["FULL_CONTROL"] } @@ -349,7 +347,6 @@ The following arguments are supported: * `logging` - (Optional) A settings of [bucket logging](https://docs.aws.amazon.com/AmazonS3/latest/UG/ManagingBucketLogging.html) (documented below). * `lifecycle_rule` - (Optional) A configuration of [object lifecycle management](http://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html) (documented below). * `acceleration_status` - (Optional) Sets the accelerate configuration of an existing bucket. Can be `Enabled` or `Suspended`. -* `region` - (Optional) If specified, the AWS region this bucket should reside in. Otherwise, the region used by the callee. * `request_payer` - (Optional) Specifies who should bear the cost of Amazon S3 data transfer. Can be either `BucketOwner` or `Requester`. By default, the owner of the S3 bucket would incur the costs of any data transfer. See [Requester Pays Buckets](http://docs.aws.amazon.com/AmazonS3/latest/dev/RequesterPaysBuckets.html) @@ -379,7 +376,7 @@ The `CORS` object supports the following: The `versioning` object supports the following: * `enabled` - (Optional) Enable versioning. Once you version-enable a bucket, it can never return to an unversioned state. You can, however, suspend versioning on that bucket. -* `mfa_delete` - (Optional) Enable MFA delete for either `Change the versioning state of your bucket` or `Permanently delete an object version`. Default is `false`. +* `mfa_delete` - (Optional) Enable MFA delete for either `Change the versioning state of your bucket` or `Permanently delete an object version`. Default is `false`. This cannot be used to toggle this setting but is available to allow managed buckets to reflect the state in AWS The `logging` object supports the following: @@ -414,12 +411,12 @@ The `transition` object supports the following The `noncurrent_version_expiration` object supports the following -* `days` (Required) Specifies the number of days an object is noncurrent object versions expire. +* `days` (Required) Specifies the number of days noncurrent object versions expire. The `noncurrent_version_transition` object supports the following -* `days` (Required) Specifies the number of days an object is noncurrent object versions expire. -* `storage_class` (Required) Specifies the Amazon S3 storage class to which you want the noncurrent versions object to transition. Can be `ONEZONE_IA`, `STANDARD_IA`, `INTELLIGENT_TIERING`, `GLACIER`, or `DEEP_ARCHIVE`. +* `days` (Required) Specifies the number of days noncurrent object versions transition. +* `storage_class` (Required) Specifies the Amazon S3 storage class to which you want the noncurrent object versions to transition. Can be `ONEZONE_IA`, `STANDARD_IA`, `INTELLIGENT_TIERING`, `GLACIER`, or `DEEP_ARCHIVE`. The `replication_configuration` object supports the following: @@ -533,3 +530,5 @@ S3 bucket can be imported using the `bucket`, e.g. ``` $ terraform import aws_s3_bucket.bucket bucket-name ``` + +The `policy` argument is not imported and will be deprecated in a future version 3.x of the Terraform AWS Provider for removal in version 4.0. Use the [`aws_s3_bucket_policy` resource](/docs/providers/aws/r/s3_bucket_policy.html) to manage the S3 Bucket Policy instead. diff --git a/website/docs/r/s3_bucket_analysis_configuration.html.markdown b/website/docs/r/s3_bucket_analytics_configuration.html.markdown similarity index 100% rename from website/docs/r/s3_bucket_analysis_configuration.html.markdown rename to website/docs/r/s3_bucket_analytics_configuration.html.markdown diff --git a/website/docs/r/s3_bucket_inventory.html.markdown b/website/docs/r/s3_bucket_inventory.html.markdown index 024ed15e434..89811e29c79 100644 --- a/website/docs/r/s3_bucket_inventory.html.markdown +++ b/website/docs/r/s3_bucket_inventory.html.markdown @@ -24,7 +24,7 @@ resource "aws_s3_bucket" "inventory" { } resource "aws_s3_bucket_inventory" "test" { - bucket = "${aws_s3_bucket.test.id}" + bucket = aws_s3_bucket.test.id name = "EntireBucketDaily" included_object_versions = "All" @@ -36,7 +36,7 @@ resource "aws_s3_bucket_inventory" "test" { destination { bucket { format = "ORC" - bucket_arn = "${aws_s3_bucket.inventory.arn}" + bucket_arn = aws_s3_bucket.inventory.arn } } } @@ -54,7 +54,7 @@ resource "aws_s3_bucket" "inventory" { } resource "aws_s3_bucket_inventory" "test-prefix" { - bucket = "${aws_s3_bucket.test.id}" + bucket = aws_s3_bucket.test.id name = "DocumentsWeekly" included_object_versions = "All" @@ -70,7 +70,7 @@ resource "aws_s3_bucket_inventory" "test-prefix" { destination { bucket { format = "ORC" - bucket_arn = "${aws_s3_bucket.inventory.arn}" + bucket_arn = aws_s3_bucket.inventory.arn prefix = "inventory" } } diff --git a/website/docs/r/s3_bucket_metric.html.markdown b/website/docs/r/s3_bucket_metric.html.markdown index 7eb0aae5284..ca638137ae0 100644 --- a/website/docs/r/s3_bucket_metric.html.markdown +++ b/website/docs/r/s3_bucket_metric.html.markdown @@ -20,7 +20,7 @@ resource "aws_s3_bucket" "example" { } resource "aws_s3_bucket_metric" "example-entire-bucket" { - bucket = "${aws_s3_bucket.example.bucket}" + bucket = aws_s3_bucket.example.bucket name = "EntireBucket" } ``` @@ -33,7 +33,7 @@ resource "aws_s3_bucket" "example" { } resource "aws_s3_bucket_metric" "example-filtered" { - bucket = "${aws_s3_bucket.example.bucket}" + bucket = aws_s3_bucket.example.bucket name = "ImportantBlueDocuments" filter { @@ -57,6 +57,8 @@ The following arguments are supported: The `filter` metric configuration supports the following: +~> **NOTE**: At least one of `prefix` or `tags` is required when specifying a `filter` + * `prefix` - (Optional) Object prefix for filtering (singular). * `tags` - (Optional) Object tags for filtering (up to 10). diff --git a/website/docs/r/s3_bucket_notification.html.markdown b/website/docs/r/s3_bucket_notification.html.markdown index 467622e1773..290406d621b 100644 --- a/website/docs/r/s3_bucket_notification.html.markdown +++ b/website/docs/r/s3_bucket_notification.html.markdown @@ -41,10 +41,10 @@ resource "aws_s3_bucket" "bucket" { } resource "aws_s3_bucket_notification" "bucket_notification" { - bucket = "${aws_s3_bucket.bucket.id}" + bucket = aws_s3_bucket.bucket.id topic { - topic_arn = "${aws_sns_topic.topic.arn}" + topic_arn = aws_sns_topic.topic.arn events = ["s3:ObjectCreated:*"] filter_suffix = ".log" } @@ -80,10 +80,10 @@ resource "aws_s3_bucket" "bucket" { } resource "aws_s3_bucket_notification" "bucket_notification" { - bucket = "${aws_s3_bucket.bucket.id}" + bucket = aws_s3_bucket.bucket.id queue { - queue_arn = "${aws_sqs_queue.queue.arn}" + queue_arn = aws_sqs_queue.queue.arn events = ["s3:ObjectCreated:*"] filter_suffix = ".log" } @@ -115,15 +115,15 @@ EOF resource "aws_lambda_permission" "allow_bucket" { statement_id = "AllowExecutionFromS3Bucket" action = "lambda:InvokeFunction" - function_name = "${aws_lambda_function.func.arn}" + function_name = aws_lambda_function.func.arn principal = "s3.amazonaws.com" - source_arn = "${aws_s3_bucket.bucket.arn}" + source_arn = aws_s3_bucket.bucket.arn } resource "aws_lambda_function" "func" { filename = "your-function.zip" function_name = "example_lambda_name" - role = "${aws_iam_role.iam_for_lambda.arn}" + role = aws_iam_role.iam_for_lambda.arn handler = "exports.example" runtime = "go1.x" } @@ -133,10 +133,10 @@ resource "aws_s3_bucket" "bucket" { } resource "aws_s3_bucket_notification" "bucket_notification" { - bucket = "${aws_s3_bucket.bucket.id}" + bucket = aws_s3_bucket.bucket.id lambda_function { - lambda_function_arn = "${aws_lambda_function.func.arn}" + lambda_function_arn = aws_lambda_function.func.arn events = ["s3:ObjectCreated:*"] filter_prefix = "AWSLogs/" filter_suffix = ".log" @@ -171,15 +171,15 @@ EOF resource "aws_lambda_permission" "allow_bucket1" { statement_id = "AllowExecutionFromS3Bucket1" action = "lambda:InvokeFunction" - function_name = "${aws_lambda_function.func1.arn}" + function_name = aws_lambda_function.func1.arn principal = "s3.amazonaws.com" - source_arn = "${aws_s3_bucket.bucket.arn}" + source_arn = aws_s3_bucket.bucket.arn } resource "aws_lambda_function" "func1" { filename = "your-function1.zip" function_name = "example_lambda_name1" - role = "${aws_iam_role.iam_for_lambda.arn}" + role = aws_iam_role.iam_for_lambda.arn handler = "exports.example" runtime = "go1.x" } @@ -187,15 +187,15 @@ resource "aws_lambda_function" "func1" { resource "aws_lambda_permission" "allow_bucket2" { statement_id = "AllowExecutionFromS3Bucket2" action = "lambda:InvokeFunction" - function_name = "${aws_lambda_function.func2.arn}" + function_name = aws_lambda_function.func2.arn principal = "s3.amazonaws.com" - source_arn = "${aws_s3_bucket.bucket.arn}" + source_arn = aws_s3_bucket.bucket.arn } resource "aws_lambda_function" "func2" { filename = "your-function2.zip" function_name = "example_lambda_name2" - role = "${aws_iam_role.iam_for_lambda.arn}" + role = aws_iam_role.iam_for_lambda.arn handler = "exports.example" } @@ -204,17 +204,17 @@ resource "aws_s3_bucket" "bucket" { } resource "aws_s3_bucket_notification" "bucket_notification" { - bucket = "${aws_s3_bucket.bucket.id}" + bucket = aws_s3_bucket.bucket.id lambda_function { - lambda_function_arn = "${aws_lambda_function.func1.arn}" + lambda_function_arn = aws_lambda_function.func1.arn events = ["s3:ObjectCreated:*"] filter_prefix = "AWSLogs/" filter_suffix = ".log" } lambda_function { - lambda_function_arn = "${aws_lambda_function.func2.arn}" + lambda_function_arn = aws_lambda_function.func2.arn events = ["s3:ObjectCreated:*"] filter_prefix = "OtherLogs/" filter_suffix = ".log" @@ -222,7 +222,7 @@ resource "aws_s3_bucket_notification" "bucket_notification" { depends_on = [ aws_lambda_permission.allow_bucket1, - aws_lambda_permission.allow_bucket2 + aws_lambda_permission.allow_bucket2, ] } ``` @@ -256,18 +256,18 @@ resource "aws_s3_bucket" "bucket" { } resource "aws_s3_bucket_notification" "bucket_notification" { - bucket = "${aws_s3_bucket.bucket.id}" + bucket = aws_s3_bucket.bucket.id queue { id = "image-upload-event" - queue_arn = "${aws_sqs_queue.queue.arn}" + queue_arn = aws_sqs_queue.queue.arn events = ["s3:ObjectCreated:*"] filter_prefix = "images/" } queue { id = "video-upload-event" - queue_arn = "${aws_sqs_queue.queue.arn}" + queue_arn = aws_sqs_queue.queue.arn events = ["s3:ObjectCreated:*"] filter_prefix = "videos/" } diff --git a/website/docs/r/s3_bucket_object.html.markdown b/website/docs/r/s3_bucket_object.html.markdown index 54c4f6c0439..a883e310203 100644 --- a/website/docs/r/s3_bucket_object.html.markdown +++ b/website/docs/r/s3_bucket_object.html.markdown @@ -23,7 +23,7 @@ resource "aws_s3_bucket_object" "object" { # The filemd5() function is available in Terraform 0.11.12 and later # For Terraform 0.11.11 and earlier, use the md5() function and the file() function: # etag = "${md5(file("path/to/file"))}" - etag = "${filemd5("path/to/file")}" + etag = filemd5("path/to/file") } ``` @@ -42,9 +42,9 @@ resource "aws_s3_bucket" "examplebucket" { resource "aws_s3_bucket_object" "examplebucket_object" { key = "someobject" - bucket = "${aws_s3_bucket.examplebucket.id}" + bucket = aws_s3_bucket.examplebucket.id source = "index.html" - kms_key_id = "${aws_kms_key.examplekms.arn}" + kms_key_id = aws_kms_key.examplekms.arn } ``` @@ -58,7 +58,7 @@ resource "aws_s3_bucket" "examplebucket" { resource "aws_s3_bucket_object" "examplebucket_object" { key = "someobject" - bucket = "${aws_s3_bucket.examplebucket.id}" + bucket = aws_s3_bucket.examplebucket.id source = "index.html" server_side_encryption = "aws:kms" } @@ -74,7 +74,7 @@ resource "aws_s3_bucket" "examplebucket" { resource "aws_s3_bucket_object" "examplebucket_object" { key = "someobject" - bucket = "${aws_s3_bucket.examplebucket.id}" + bucket = aws_s3_bucket.examplebucket.id source = "index.html" server_side_encryption = "AES256" } @@ -98,7 +98,7 @@ resource "aws_s3_bucket" "examplebucket" { resource "aws_s3_bucket_object" "examplebucket_object" { key = "someobject" - bucket = "${aws_s3_bucket.examplebucket.id}" + bucket = aws_s3_bucket.examplebucket.id source = "important.txt" object_lock_legal_hold_status = "ON" diff --git a/website/docs/r/s3_bucket_policy.html.markdown b/website/docs/r/s3_bucket_policy.html.markdown index 57d8ebb99b7..b094b006514 100644 --- a/website/docs/r/s3_bucket_policy.html.markdown +++ b/website/docs/r/s3_bucket_policy.html.markdown @@ -20,7 +20,7 @@ resource "aws_s3_bucket" "b" { } resource "aws_s3_bucket_policy" "b" { - bucket = "${aws_s3_bucket.b.id}" + bucket = aws_s3_bucket.b.id policy = < **NOTE:** Configuring rotation causes the secret to rotate once as soon as you enable rotation. Before you do this, you must ensure that all of your applications that use the credentials stored in the secret are updated to retrieve the secret from AWS Secrets Manager. The old credentials might no longer be usable after the initial rotation and any applications that you fail to update will break as soon as the old credentials are no longer valid. + +~> **NOTE:** If you cancel a rotation that is in progress (by removing the `rotation` configuration), it can leave the VersionStage labels in an unexpected state. Depending on what step of the rotation was in progress, you might need to remove the staging label AWSPENDING from the partially created version, specified by the SecretVersionId response value. You should also evaluate the partially rotated new version to see if it should be deleted, which you can do by removing all staging labels from the new version's VersionStage field. + +## Argument Reference + +The following arguments are supported: + +* `secret_id` - (Required) Specifies the secret to which you want to add a new version. You can specify either the Amazon Resource Name (ARN) or the friendly name of the secret. The secret must already exist. +* `rotation_lambda_arn` - (Required) Specifies the ARN of the Lambda function that can rotate the secret. +* `rotation_rules` - (Required) A structure that defines the rotation configuration for this secret. Defined below. + +### rotation_rules + +* `automatically_after_days` - (Required) Specifies the number of days between automatic scheduled rotations of the secret. + +## Attribute Reference + +* `id` - Amazon Resource Name (ARN) of the secret. +* `arn` - Amazon Resource Name (ARN) of the secret. +* `rotation_enabled` - Specifies whether automatic rotation is enabled for this secret. + +## Import + +`aws_secretsmanager_secret_rotation` can be imported by using the secret Amazon Resource Name (ARN), e.g. + +``` +$ terraform import aws_secretsmanager_secret_rotation.example arn:aws:secretsmanager:us-east-1:123456789012:secret:example-123456 +``` diff --git a/website/docs/r/secretsmanager_secret_version.html.markdown b/website/docs/r/secretsmanager_secret_version.html.markdown index f60d4234bbc..35a74baf568 100644 --- a/website/docs/r/secretsmanager_secret_version.html.markdown +++ b/website/docs/r/secretsmanager_secret_version.html.markdown @@ -18,7 +18,7 @@ Provides a resource to manage AWS Secrets Manager secret version including its s ```hcl resource "aws_secretsmanager_secret_version" "example" { - secret_id = "${aws_secretsmanager_secret.example.id}" + secret_id = aws_secretsmanager_secret.example.id secret_string = "example-string-to-protect" } ``` @@ -36,12 +36,12 @@ variable "example" { key2 = "value2" } - type = "map" + type = map(string) } resource "aws_secretsmanager_secret_version" "example" { - secret_id = "${aws_secretsmanager_secret.example.id}" - secret_string = "${jsonencode(var.example)}" + secret_id = aws_secretsmanager_secret.example.id + secret_string = jsonencode(var.example) } ``` diff --git a/website/docs/r/security_group.html.markdown b/website/docs/r/security_group.html.markdown index d0f6051e5fb..23f7046062b 100644 --- a/website/docs/r/security_group.html.markdown +++ b/website/docs/r/security_group.html.markdown @@ -29,14 +29,14 @@ Basic usage resource "aws_security_group" "allow_tls" { name = "allow_tls" description = "Allow TLS inbound traffic" - vpc_id = "${aws_vpc.main.id}" + vpc_id = aws_vpc.main.id ingress { description = "TLS from VPC" from_port = 443 to_port = 443 protocol = "tcp" - cidr_blocks = aws_vpc.main.cidr_block + cidr_blocks = [aws_vpc.main.cidr_block] } egress { @@ -118,11 +118,15 @@ surprises in terms of controlling your egress rules. If you desire this rule to be in place, you can use this `egress` block: ```hcl -egress { - from_port = 0 - to_port = 0 - protocol = "-1" - cidr_blocks = ["0.0.0.0/0"] +resource "aws_security_group" "example" { + # ... other configuration ... + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } } ``` @@ -133,17 +137,19 @@ are associated with a prefix list name, or service name, that is linked to a spe Prefix list IDs are exported on VPC Endpoints, so you can use this format: ```hcl -# ... -egress { - from_port = 0 - to_port = 0 - protocol = "-1" - prefix_list_ids = ["${aws_vpc_endpoint.my_endpoint.prefix_list_id}"] +resource "aws_security_group" "example" { + # ... other configuration ... + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + prefix_list_ids = [aws_vpc_endpoint.my_endpoint.prefix_list_id] + } } -# ... resource "aws_vpc_endpoint" "my_endpoint" { - # ... + # ... other configuration ... } ``` diff --git a/website/docs/r/security_group_rule.html.markdown b/website/docs/r/security_group_rule.html.markdown index 2439da4deff..e3f101ce1b2 100644 --- a/website/docs/r/security_group_rule.html.markdown +++ b/website/docs/r/security_group_rule.html.markdown @@ -32,7 +32,7 @@ resource "aws_security_group_rule" "example" { from_port = 0 to_port = 65535 protocol = "tcp" - cidr_blocks = aws_vpc.example.cidr_block + cidr_blocks = [aws_vpc.example.cidr_block] security_group_id = "sg-123456" } ``` @@ -68,7 +68,7 @@ resource "aws_security_group_rule" "allow_all" { type = "egress" to_port = 0 protocol = "-1" - prefix_list_ids = ["${aws_vpc_endpoint.my_endpoint.prefix_list_id}"] + prefix_list_ids = [aws_vpc_endpoint.my_endpoint.prefix_list_id] from_port = 0 security_group_id = "sg-123456" } diff --git a/website/docs/r/securityhub_member.markdown b/website/docs/r/securityhub_member.markdown index c156563a217..c36f7a5e023 100644 --- a/website/docs/r/securityhub_member.markdown +++ b/website/docs/r/securityhub_member.markdown @@ -16,7 +16,7 @@ Provides a Security Hub member resource. resource "aws_securityhub_account" "example" {} resource "aws_securityhub_member" "example" { - depends_on = ["aws_securityhub_account.example"] + depends_on = [aws_securityhub_account.example] account_id = "123456789012" email = "example@example.com" invite = true @@ -37,7 +37,7 @@ The following attributes are exported in addition to the arguments listed above: * `id` - The ID of the member AWS account (matches `account_id`). * `master_id` - The ID of the master Security Hub AWS account. -* `member_status` - The status of the relationship between the member account and its master account. +* `member_status` - The status of the member account relationship. ## Import diff --git a/website/docs/r/securityhub_product_subscription.markdown b/website/docs/r/securityhub_product_subscription.markdown index 167d1d226ee..868da5fa943 100644 --- a/website/docs/r/securityhub_product_subscription.markdown +++ b/website/docs/r/securityhub_product_subscription.markdown @@ -18,7 +18,7 @@ resource "aws_securityhub_account" "example" {} data "aws_region" "current" {} resource "aws_securityhub_product_subscription" "example" { - depends_on = ["aws_securityhub_account.example"] + depends_on = [aws_securityhub_account.example] product_arn = "arn:aws:securityhub:${data.aws_region.current.name}:733251395267:product/alertlogic/althreatmanagement" } ``` diff --git a/website/docs/r/securityhub_standards_subscription.markdown b/website/docs/r/securityhub_standards_subscription.markdown index 72155ea8ca5..e24a90ad3e1 100644 --- a/website/docs/r/securityhub_standards_subscription.markdown +++ b/website/docs/r/securityhub_standards_subscription.markdown @@ -16,12 +16,12 @@ Subscribes to a Security Hub standard. resource "aws_securityhub_account" "example" {} resource "aws_securityhub_standards_subscription" "cis" { - depends_on = ["aws_securityhub_account.example"] + depends_on = [aws_securityhub_account.example] standards_arn = "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0" } resource "aws_securityhub_standards_subscription" "pci_321" { - depends_on = ["aws_securityhub_account.example"] + depends_on = [aws_securityhub_account.example] standards_arn = "arn:aws:securityhub:us-east-1::standards/pci-dss/v/3.2.1" } ``` @@ -34,10 +34,11 @@ The following arguments are supported: Currently available standards: -| Name | ARN | -|---------------------|-----------------------------------------------------------------------| -| CIS AWS Foundations | `arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0` | -| PCI DSS | `arn:aws:securityhub:us-east-1::standards/pci-dss/v/3.2.1` | +| Name | ARN | +|------------------------------------------|---------------------------------------------------------------------------------------------| +| AWS Foundational Security Best Practices | `arn:aws:securityhub:us-east-1::standards/aws-foundational-security-best-practices/v/1.0.0` | +| CIS AWS Foundations | `arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0` | +| PCI DSS | `arn:aws:securityhub:us-east-1::standards/pci-dss/v/3.2.1` | ## Attributes Reference diff --git a/website/docs/r/service_discovery_http_namespace.html.markdown b/website/docs/r/service_discovery_http_namespace.html.markdown index cb6d8338d37..4c2969d46fd 100644 --- a/website/docs/r/service_discovery_http_namespace.html.markdown +++ b/website/docs/r/service_discovery_http_namespace.html.markdown @@ -24,6 +24,7 @@ The following arguments are supported: * `name` - (Required) The name of the http namespace. * `description` - (Optional) The description that you specify for the namespace when you create it. +* `tags` - (Optional) A map of tags to assign to the namespace. ## Attributes Reference diff --git a/website/docs/r/service_discovery_private_dns_namespace.html.markdown b/website/docs/r/service_discovery_private_dns_namespace.html.markdown index 1305e0d09f3..0a5cfa5d672 100644 --- a/website/docs/r/service_discovery_private_dns_namespace.html.markdown +++ b/website/docs/r/service_discovery_private_dns_namespace.html.markdown @@ -20,7 +20,7 @@ resource "aws_vpc" "example" { resource "aws_service_discovery_private_dns_namespace" "example" { name = "hoge.example.local" description = "example" - vpc = "${aws_vpc.example.id}" + vpc = aws_vpc.example.id } ``` @@ -31,6 +31,7 @@ The following arguments are supported: * `name` - (Required) The name of the namespace. * `vpc` - (Required) The ID of VPC that you want to associate the namespace with. * `description` - (Optional) The description that you specify for the namespace when you create it. +* `tags` - (Optional) A map of tags to assign to the namespace. ## Attributes Reference diff --git a/website/docs/r/service_discovery_public_dns_namespace.html.markdown b/website/docs/r/service_discovery_public_dns_namespace.html.markdown index df570e1e171..ad8f78a83ee 100644 --- a/website/docs/r/service_discovery_public_dns_namespace.html.markdown +++ b/website/docs/r/service_discovery_public_dns_namespace.html.markdown @@ -25,6 +25,7 @@ The following arguments are supported: * `name` - (Required) The name of the namespace. * `description` - (Optional) The description that you specify for the namespace when you create it. +* `tags` - (Optional) A map of tags to assign to the namespace. ## Attributes Reference diff --git a/website/docs/r/service_discovery_service.html.markdown b/website/docs/r/service_discovery_service.html.markdown index 80abdd34b41..6b691cde263 100644 --- a/website/docs/r/service_discovery_service.html.markdown +++ b/website/docs/r/service_discovery_service.html.markdown @@ -22,14 +22,14 @@ resource "aws_vpc" "example" { resource "aws_service_discovery_private_dns_namespace" "example" { name = "example.terraform.local" description = "example" - vpc = "${aws_vpc.example.id}" + vpc = aws_vpc.example.id } resource "aws_service_discovery_service" "example" { name = "example" dns_config { - namespace_id = "${aws_service_discovery_private_dns_namespace.example.id}" + namespace_id = aws_service_discovery_private_dns_namespace.example.id dns_records { ttl = 10 @@ -55,7 +55,7 @@ resource "aws_service_discovery_service" "example" { name = "example" dns_config { - namespace_id = "${aws_service_discovery_public_dns_namespace.example.id}" + namespace_id = aws_service_discovery_public_dns_namespace.example.id dns_records { ttl = 10 @@ -81,6 +81,7 @@ The following arguments are supported: * `health_check_config` - (Optional) A complex type that contains settings for an optional health check. Only for Public DNS namespaces. * `health_check_custom_config` - (Optional, ForceNew) A complex type that contains settings for ECS managed health checks. * `namespace_id` - (Optional) The ID of the namespace that you want to use to create the service. +* `tags` - (Optional) A map of tags to assign to the service. ### dns_config diff --git a/website/docs/r/ses_domain_dkim.html.markdown b/website/docs/r/ses_domain_dkim.html.markdown index aca1f562e73..66566b8f8a6 100644 --- a/website/docs/r/ses_domain_dkim.html.markdown +++ b/website/docs/r/ses_domain_dkim.html.markdown @@ -37,7 +37,7 @@ resource "aws_ses_domain_identity" "example" { } resource "aws_ses_domain_dkim" "example" { - domain = "${aws_ses_domain_identity.example.domain}" + domain = aws_ses_domain_identity.example.domain } resource "aws_route53_record" "example_amazonses_dkim_record" { diff --git a/website/docs/r/ses_domain_identity.html.markdown b/website/docs/r/ses_domain_identity.html.markdown index b3ac82d068b..23c7d6af204 100644 --- a/website/docs/r/ses_domain_identity.html.markdown +++ b/website/docs/r/ses_domain_identity.html.markdown @@ -42,7 +42,7 @@ resource "aws_route53_record" "example_amazonses_verification_record" { name = "_amazonses.example.com" type = "TXT" ttl = "600" - records = ["${aws_ses_domain_identity.example.verification_token}"] + records = [aws_ses_domain_identity.example.verification_token] } ``` diff --git a/website/docs/r/ses_domain_identity_verification.html.markdown b/website/docs/r/ses_domain_identity_verification.html.markdown index fd6449857d5..56069476a99 100644 --- a/website/docs/r/ses_domain_identity_verification.html.markdown +++ b/website/docs/r/ses_domain_identity_verification.html.markdown @@ -24,17 +24,17 @@ resource "aws_ses_domain_identity" "example" { } resource "aws_route53_record" "example_amazonses_verification_record" { - zone_id = "${aws_route53_zone.example.zone_id}" + zone_id = aws_route53_zone.example.zone_id name = "_amazonses.${aws_ses_domain_identity.example.id}" type = "TXT" ttl = "600" - records = ["${aws_ses_domain_identity.example.verification_token}"] + records = [aws_ses_domain_identity.example.verification_token] } resource "aws_ses_domain_identity_verification" "example_verification" { - domain = "${aws_ses_domain_identity.example.id}" + domain = aws_ses_domain_identity.example.id - depends_on = ["aws_route53_record.example_amazonses_verification_record"] + depends_on = [aws_route53_record.example_amazonses_verification_record] } ``` diff --git a/website/docs/r/ses_domain_mail_from.html.markdown b/website/docs/r/ses_domain_mail_from.html.markdown index 274ba4556f7..944fa236863 100644 --- a/website/docs/r/ses_domain_mail_from.html.markdown +++ b/website/docs/r/ses_domain_mail_from.html.markdown @@ -16,7 +16,7 @@ Provides an SES domain MAIL FROM resource. ```hcl resource "aws_ses_domain_mail_from" "example" { - domain = "${aws_ses_domain_identity.example.domain}" + domain = aws_ses_domain_identity.example.domain mail_from_domain = "bounce.${aws_ses_domain_identity.example.domain}" } @@ -27,8 +27,8 @@ resource "aws_ses_domain_identity" "example" { # Example Route53 MX record resource "aws_route53_record" "example_ses_domain_mail_from_mx" { - zone_id = "${aws_route53_zone.example.id}" - name = "${aws_ses_domain_mail_from.example.mail_from_domain}" + zone_id = aws_route53_zone.example.id + name = aws_ses_domain_mail_from.example.mail_from_domain type = "MX" ttl = "600" records = ["10 feedback-smtp.us-east-1.amazonses.com"] # Change to the region in which `aws_ses_domain_identity.example` is created @@ -36,8 +36,8 @@ resource "aws_route53_record" "example_ses_domain_mail_from_mx" { # Example Route53 TXT record for SPF resource "aws_route53_record" "example_ses_domain_mail_from_txt" { - zone_id = "${aws_route53_zone.example.id}" - name = "${aws_ses_domain_mail_from.example.mail_from_domain}" + zone_id = aws_route53_zone.example.id + name = aws_ses_domain_mail_from.example.mail_from_domain type = "TXT" ttl = "600" records = ["v=spf1 include:amazonses.com -all"] diff --git a/website/docs/r/ses_event_destination.markdown b/website/docs/r/ses_event_destination.markdown index 23208ddd1c4..48f4638bb33 100644 --- a/website/docs/r/ses_event_destination.markdown +++ b/website/docs/r/ses_event_destination.markdown @@ -17,7 +17,7 @@ Provides an SES event destination ```hcl resource "aws_ses_event_destination" "cloudwatch" { name = "event-destination-cloudwatch" - configuration_set_name = "${aws_ses_configuration_set.example.name}" + configuration_set_name = aws_ses_configuration_set.example.name enabled = true matching_types = ["bounce", "send"] @@ -34,13 +34,13 @@ resource "aws_ses_event_destination" "cloudwatch" { ```hcl resource "aws_ses_event_destination" "kinesis" { name = "event-destination-kinesis" - configuration_set_name = "${aws_ses_configuration_set.example.name}" + configuration_set_name = aws_ses_configuration_set.example.name enabled = true matching_types = ["bounce", "send"] kinesis_destination { - stream_arn = "${aws_kinesis_firehose_delivery_stream.example.arn}" - role_arn = "${aws_iam_role.example.arn}" + stream_arn = aws_kinesis_firehose_delivery_stream.example.arn + role_arn = aws_iam_role.example.arn } } ``` @@ -50,12 +50,12 @@ resource "aws_ses_event_destination" "kinesis" { ```hcl resource "aws_ses_event_destination" "sns" { name = "event-destination-sns" - configuration_set_name = "${aws_ses_configuration_set.example.name}" + configuration_set_name = aws_ses_configuration_set.example.name enabled = true matching_types = ["bounce", "send"] sns_destination { - topic_arn = "${aws_sns_topic.example.arn}" + topic_arn = aws_sns_topic.example.arn } } ``` @@ -88,3 +88,12 @@ The following arguments are supported: ### sns_destination Argument Reference * `topic_arn` - (Required) The ARN of the SNS topic + +## Import + +SES event destinations can be imported using `configuration_set_name` together with the event destination's `name`, +e.g. + +``` +$ terraform import aws_ses_event_destination.sns some-configuration-set-test/event-destination-sns +``` diff --git a/website/docs/r/ses_identity_notification_topic.markdown b/website/docs/r/ses_identity_notification_topic.markdown index 32610d68b28..42209428ed4 100644 --- a/website/docs/r/ses_identity_notification_topic.markdown +++ b/website/docs/r/ses_identity_notification_topic.markdown @@ -14,9 +14,9 @@ Resource for managing SES Identity Notification Topics ```hcl resource "aws_ses_identity_notification_topic" "test" { - topic_arn = "${aws_sns_topic.example.arn}" + topic_arn = aws_sns_topic.example.arn notification_type = "Bounce" - identity = "${aws_ses_domain_identity.example.domain}" + identity = aws_ses_domain_identity.example.domain include_original_headers = true } ``` diff --git a/website/docs/r/ses_identity_policy.html.markdown b/website/docs/r/ses_identity_policy.html.markdown index 6a1a8970d6c..0318eef21a6 100644 --- a/website/docs/r/ses_identity_policy.html.markdown +++ b/website/docs/r/ses_identity_policy.html.markdown @@ -20,7 +20,7 @@ resource "aws_ses_domain_identity" "example" { data "aws_iam_policy_document" "example" { statement { actions = ["SES:SendEmail", "SES:SendRawEmail"] - resources = ["${aws_ses_domain_identity.example.arn}"] + resources = [aws_ses_domain_identity.example.arn] principals { identifiers = ["*"] @@ -30,9 +30,9 @@ data "aws_iam_policy_document" "example" { } resource "aws_ses_identity_policy" "example" { - identity = "${aws_ses_domain_identity.example.arn}" + identity = aws_ses_domain_identity.example.arn name = "example" - policy = "${data.aws_iam_policy_document.example.json}" + policy = data.aws_iam_policy_document.example.json } ``` diff --git a/website/docs/r/ses_receipt_filter.html.markdown b/website/docs/r/ses_receipt_filter.html.markdown index bd6b5f8393d..b3f227cab81 100644 --- a/website/docs/r/ses_receipt_filter.html.markdown +++ b/website/docs/r/ses_receipt_filter.html.markdown @@ -27,3 +27,18 @@ The following arguments are supported: * `name` - (Required) The name of the filter * `cidr` - (Required) The IP address or address range to filter, in CIDR notation * `policy` - (Required) Block or Allow + +## Attributes Reference + +In addition to the arguments, which are exported, the following attributes are exported: + +* `id` - The SES receipt filter name. +* `arn` - The SES receipt filter ARN. + +## Import + +SES Receipt Filter can be imported using their `name`, e.g. + +``` +$ terraform import aws_ses_receipt_filter.test some-filter +``` diff --git a/website/docs/r/sfn_state_machine.html.markdown b/website/docs/r/sfn_state_machine.html.markdown index 14ef5cbcdae..d1277c2d43d 100644 --- a/website/docs/r/sfn_state_machine.html.markdown +++ b/website/docs/r/sfn_state_machine.html.markdown @@ -17,7 +17,7 @@ Provides a Step Function State Machine resource resource "aws_sfn_state_machine" "sfn_state_machine" { name = "my-state-machine" - role_arn = "${aws_iam_role.iam_for_sfn.arn}" + role_arn = aws_iam_role.iam_for_sfn.arn definition = < **NOTE:** These examples are referencing the [`aws_storagegateway_cache`](/docs/providers/aws/r/storagegateway_cache.html) resource `gateway_arn` attribute to ensure Terraform properly adds cache before creating the volume. If you are not using this method, you may need to declare an expicit dependency (e.g. via `depends_on = ["aws_storagegateway_cache.example"]`) to ensure proper ordering. +~> **NOTE:** These examples are referencing the [`aws_storagegateway_cache`](/docs/providers/aws/r/storagegateway_cache.html) resource `gateway_arn` attribute to ensure Terraform properly adds cache before creating the volume. If you are not using this method, you may need to declare an expicit dependency (e.g. via `depends_on = [aws_storagegateway_cache.example]`) to ensure proper ordering. ### Create Empty Cached iSCSI Volume ```hcl resource "aws_storagegateway_cached_iscsi_volume" "example" { - gateway_arn = "${aws_storagegateway_cache.example.gateway_arn}" - network_interface_id = "${aws_instance.example.private_ip}" + gateway_arn = aws_storagegateway_cache.example.gateway_arn + network_interface_id = aws_instance.example.private_ip target_name = "example" volume_size_in_bytes = 5368709120 # 5 GB } @@ -33,11 +33,11 @@ resource "aws_storagegateway_cached_iscsi_volume" "example" { ```hcl resource "aws_storagegateway_cached_iscsi_volume" "example" { - gateway_arn = "${aws_storagegateway_cache.example.gateway_arn}" - network_interface_id = "${aws_instance.example.private_ip}" - snapshot_id = "${aws_ebs_snapshot.example.id}" + gateway_arn = aws_storagegateway_cache.example.gateway_arn + network_interface_id = aws_instance.example.private_ip + snapshot_id = aws_ebs_snapshot.example.id target_name = "example" - volume_size_in_bytes = "${aws_ebs_snapshot.example.volume_size * 1024 * 1024 * 1024}" + volume_size_in_bytes = aws_ebs_snapshot.example.volume_size * 1024 * 1024 * 1024 } ``` @@ -45,11 +45,11 @@ resource "aws_storagegateway_cached_iscsi_volume" "example" { ```hcl resource "aws_storagegateway_cached_iscsi_volume" "example" { - gateway_arn = "${aws_storagegateway_cache.example.gateway_arn}" - network_interface_id = "${aws_instance.example.private_ip}" - source_volume_arn = "${aws_storagegateway_cached_iscsi_volume.existing.arn}" + gateway_arn = aws_storagegateway_cache.example.gateway_arn + network_interface_id = aws_instance.example.private_ip + source_volume_arn = aws_storagegateway_cached_iscsi_volume.existing.arn target_name = "example" - volume_size_in_bytes = "${aws_storagegateway_cached_iscsi_volume.existing.volume_size_in_bytes}" + volume_size_in_bytes = aws_storagegateway_cached_iscsi_volume.existing.volume_size_in_bytes } ``` diff --git a/website/docs/r/storagegateway_gateway.html.markdown b/website/docs/r/storagegateway_gateway.html.markdown index 7ff746bb19c..765868bb434 100644 --- a/website/docs/r/storagegateway_gateway.html.markdown +++ b/website/docs/r/storagegateway_gateway.html.markdown @@ -29,12 +29,12 @@ resource "aws_storagegateway_gateway" "example" { ```hcl resource "aws_storagegateway_gateway" "example" { - gateway_ip_address = "1.2.3.4" - gateway_name = "example" - gateway_timezone = "GMT" - gateway_type = "VTL" - media_changer_type = "AWS-Gateway-VTL" - tape_drive_type = "IBM-ULT3580-TD5" + gateway_ip_address = "1.2.3.4" + gateway_name = "example" + gateway_timezone = "GMT" + gateway_type = "VTL" + medium_changer_type = "AWS-Gateway-VTL" + tape_drive_type = "IBM-ULT3580-TD5" } ``` @@ -73,7 +73,7 @@ The following arguments are supported: * `gateway_type` - (Optional) Type of the gateway. The default value is `STORED`. Valid values: `CACHED`, `FILE_S3`, `STORED`, `VTL`. * `gateway_vpc_endpoint` - (Optional) VPC endpoint address to be used when activating your gateway. This should be used when your instance is in a private subnet. Requires HTTP access from client computer running terraform. More info on what ports are required by your VPC Endpoint Security group in [Activating a Gateway in a Virtual Private Cloud](https://docs.aws.amazon.com/storagegateway/latest/userguide/gateway-private-link.html). * `cloudwatch_log_group_arn` - (Optional) The Amazon Resource Name (ARN) of the Amazon CloudWatch log group to use to monitor and log events in the gateway. -* `media_changer_type` - (Optional) Type of medium changer to use for tape gateway. Terraform cannot detect drift of this argument. Valid values: `STK-L700`, `AWS-Gateway-VTL`. +* `medium_changer_type` - (Optional) Type of medium changer to use for tape gateway. Terraform cannot detect drift of this argument. Valid values: `STK-L700`, `AWS-Gateway-VTL`. * `smb_active_directory_settings` - (Optional) Nested argument with Active Directory domain join information for Server Message Block (SMB) file shares. Only valid for `FILE_S3` gateway type. Must be set before creating `ActiveDirectory` authentication SMB file shares. More details below. * `smb_guest_password` - (Optional) Guest password for Server Message Block (SMB) file shares. Only valid for `FILE_S3` gateway type. Must be set before creating `GuestAccess` authentication SMB file shares. Terraform can only detect drift of the existence of a guest password, not its actual value from the gateway. Terraform can however update the password with changing the argument. * `tape_drive_type` - (Optional) Type of tape drive to use for tape gateway. Terraform cannot detect drift of this argument. Valid values: `IBM-ULT3580-TD5`. diff --git a/website/docs/r/storagegateway_nfs_file_share.html.markdown b/website/docs/r/storagegateway_nfs_file_share.html.markdown index 89c7bb482c2..a553de6a896 100644 --- a/website/docs/r/storagegateway_nfs_file_share.html.markdown +++ b/website/docs/r/storagegateway_nfs_file_share.html.markdown @@ -15,9 +15,9 @@ Manages an AWS Storage Gateway NFS File Share. ```hcl resource "aws_storagegateway_nfs_file_share" "example" { client_list = ["0.0.0.0/0"] - gateway_arn = "${aws_storagegateway_gateway.example.arn}" - location_arn = "${aws_s3_bucket.example.arn}" - role_arn = "${aws_iam_role.example.arn}" + gateway_arn = aws_storagegateway_gateway.example.arn + location_arn = aws_s3_bucket.example.arn + role_arn = aws_iam_role.example.arn } ``` diff --git a/website/docs/r/storagegateway_smb_file_share.html.markdown b/website/docs/r/storagegateway_smb_file_share.html.markdown index 3106cf1f750..60dd01fef55 100644 --- a/website/docs/r/storagegateway_smb_file_share.html.markdown +++ b/website/docs/r/storagegateway_smb_file_share.html.markdown @@ -19,9 +19,9 @@ Manages an AWS Storage Gateway SMB File Share. ```hcl resource "aws_storagegateway_smb_file_share" "example" { authentication = "ActiveDirectory" - gateway_arn = "${aws_storagegateway_gateway.example.arn}" - location_arn = "${aws_s3_bucket.example.arn}" - role_arn = "${aws_iam_role.example.arn}" + gateway_arn = aws_storagegateway_gateway.example.arn + location_arn = aws_s3_bucket.example.arn + role_arn = aws_iam_role.example.arn } ``` @@ -32,9 +32,9 @@ resource "aws_storagegateway_smb_file_share" "example" { ```hcl resource "aws_storagegateway_smb_file_share" "example" { authentication = "GuestAccess" - gateway_arn = "${aws_storagegateway_gateway.example.arn}" - location_arn = "${aws_s3_bucket.example.arn}" - role_arn = "${aws_iam_role.example.arn}" + gateway_arn = aws_storagegateway_gateway.example.arn + location_arn = aws_s3_bucket.example.arn + role_arn = aws_iam_role.example.arn } ``` diff --git a/website/docs/r/storagegateway_upload_buffer.html.markdown b/website/docs/r/storagegateway_upload_buffer.html.markdown index de6bbed5783..ad71cb03822 100644 --- a/website/docs/r/storagegateway_upload_buffer.html.markdown +++ b/website/docs/r/storagegateway_upload_buffer.html.markdown @@ -16,8 +16,8 @@ Manages an AWS Storage Gateway upload buffer. ```hcl resource "aws_storagegateway_upload_buffer" "example" { - disk_id = "${data.aws_storagegateway_local_disk.example.id}" - gateway_arn = "${aws_storagegateway_gateway.example.arn}" + disk_id = data.aws_storagegateway_local_disk.example.id + gateway_arn = aws_storagegateway_gateway.example.arn } ``` diff --git a/website/docs/r/storagegateway_working_storage.html.markdown b/website/docs/r/storagegateway_working_storage.html.markdown index ff7b9858850..b2879e9f050 100644 --- a/website/docs/r/storagegateway_working_storage.html.markdown +++ b/website/docs/r/storagegateway_working_storage.html.markdown @@ -16,8 +16,8 @@ Manages an AWS Storage Gateway working storage. ```hcl resource "aws_storagegateway_working_storage" "example" { - disk_id = "${data.aws_storagegateway_local_disk.example.id}" - gateway_arn = "${aws_storagegateway_gateway.example.arn}" + disk_id = data.aws_storagegateway_local_disk.example.id + gateway_arn = aws_storagegateway_gateway.example.arn } ``` diff --git a/website/docs/r/subnet.html.markdown b/website/docs/r/subnet.html.markdown index 3f98c1f1093..e7f6410581c 100644 --- a/website/docs/r/subnet.html.markdown +++ b/website/docs/r/subnet.html.markdown @@ -18,7 +18,7 @@ Provides an VPC subnet resource. ```hcl resource "aws_subnet" "main" { - vpc_id = "${aws_vpc.main.id}" + vpc_id = aws_vpc.main.id cidr_block = "10.0.1.0/24" tags = { @@ -34,12 +34,12 @@ resource, it is recommended to reference that resource's `vpc_id` attribute to e ```hcl resource "aws_vpc_ipv4_cidr_block_association" "secondary_cidr" { - vpc_id = "${aws_vpc.main.id}" + vpc_id = aws_vpc.main.id cidr_block = "172.2.0.0/16" } resource "aws_subnet" "in_secondary_cidr" { - vpc_id = "${aws_vpc_ipv4_cidr_block_association.secondary_cidr.vpc_id}" + vpc_id = aws_vpc_ipv4_cidr_block_association.secondary_cidr.vpc_id cidr_block = "172.2.0.0/24" } ``` diff --git a/website/docs/r/transfer_server.html.markdown b/website/docs/r/transfer_server.html.markdown index 1333db78604..581228931ca 100644 --- a/website/docs/r/transfer_server.html.markdown +++ b/website/docs/r/transfer_server.html.markdown @@ -12,7 +12,17 @@ Provides a AWS Transfer Server resource. ```hcl -resource "aws_iam_role" "foo" { +resource "aws_transfer_server" "example" { + identity_provider_type = "SERVICE_MANAGED" + logging_role = aws_iam_role.example.arn + + tags = { + NAME = "tf-acc-test-transfer-server" + ENV = "test" + } +} + +resource "aws_iam_role" "example" { name = "tf-test-transfer-server-iam-role" assume_role_policy = < **NOTE**: One of `allow`, `block`, or `count`, expressed as an empty configuration block `{}`, is required when specifying an `action` + +* `allow` - (Optional) Instructs AWS WAF to allow the web request. +* `block` - (Optional) Instructs AWS WAF to block the web request. +* `count` - (Optional) Instructs AWS WAF to count the web request and allow it. + +### Statement + +The processing guidance for a Rule, used by AWS WAF to determine whether a web request matches the rule. See the [documentation](https://docs.aws.amazon.com/waf/latest/developerguide/waf-rule-statements-list.html) for more information. + +-> **NOTE:** Although the `statement` block is recursive, currently only 3 levels are supported. + +The `statement` block supports the following arguments: + +* `and_statement` - (Optional) A logical rule statement used to combine other rule statements with AND logic. See [AND Statement](#and-statement) below for details. +* `byte_match_statement` - (Optional) A rule statement that defines a string match search for AWS WAF to apply to web requests. See [Byte Match Statement](#byte-match-statement) below for details. +* `geo_match_statement` - (Optional) A rule statement used to identify web requests based on country of origin. See [GEO Match Statement](#geo-match-statement) below for details. +* `ip_set_reference_statement` - (Optional) A rule statement used to detect web requests coming from particular IP addresses or address ranges. See [IP Set Reference Statement](#ip-set-reference-statement) below for details. +* `not_statement` - (Optional) A logical rule statement used to negate the results of another rule statement. See [NOT Statement](#not-statement) below for details. +* `or_statement` - (Optional) A logical rule statement used to combine other rule statements with OR logic. See [OR Statement](#or-statement) below for details. +* `regex_pattern_set_reference_statement` - (Optional) A rule statement used to search web request components for matches with regular expressions. See [Regex Pattern Set Reference Statement](#regex-pattern-set-reference-statement) below for details. +* `size_constraint_statement` - (Optional) A rule statement that compares a number of bytes against the size of a request component, using a comparison operator, such as greater than (>) or less than (<). See [Size Constraint Statement](#size-constraint-statement) below for more details. +* `sqli_match_statement` - (Optional) An SQL injection match condition identifies the part of web requests, such as the URI or the query string, that you want AWS WAF to inspect. See [SQL Injection Match Statement](#sql-injection-match-statement) below for details. +* `xss_match_statement` - (Optional) A rule statement that defines a cross-site scripting (XSS) match search for AWS WAF to apply to web requests. See [XSS Match Statement](#xss-match-statement) below for details. + +### AND Statement + +A logical rule statement used to combine other rule statements with `AND` logic. You provide more than one `statement` within the `and_statement`. + +The `and_statement` block supports the following arguments: + +* `statement` - (Required) The statements to combine with `AND` logic. You can use any statements that can be nested. See [Statement](#statement) above for details. + +### Byte Match Statement + +The byte match statement provides the bytes to search for, the location in requests that you want AWS WAF to search, and other settings. The bytes to search for are typically a string that corresponds with ASCII characters. + +The `byte_match_statement` block supports the following arguments: + +* `field_to_match` - (Required) The part of a web request that you want AWS WAF to inspect. See [Field to Match](#field-to-match) below for details. +* `positional_constraint` - (Required) The area within the portion of a web request that you want AWS WAF to search for `search_string`. Valid values include the following: `EXACTLY`, `STARTS_WITH`, `ENDS_WITH`, `CONTAINS`, `CONTAINS_WORD`. See the AWS [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_ByteMatchStatement.html) for more information. +* `search_string` - (Required) A string value that you want AWS WAF to search for. AWS WAF searches only in the part of web requests that you designate for inspection in `field_to_match`. The maximum length of the value is 50 bytes. +* `text_transformation` - (Required) Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See [Text Transformation](#text-transformation) below for details. + +### GEO Match Statement + +The `geo_match_statement` block supports the following arguments: + +* `country_codes` - (Required) An array of two-character country codes, for example, [ "US", "CN" ], from the alpha-2 country ISO codes of the `ISO 3166` international standard. See the [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_GeoMatchStatement.html) for valid values. + +### IP Set Reference Statement + +A rule statement used to detect web requests coming from particular IP addresses or address ranges. To use this, create an `aws_wafv2_ip_set` that specifies the addresses you want to detect, then use the `ARN` of that set in this statement. + +The `ip_set_reference_statement` block supports the following arguments: + +* `arn` - (Required) The Amazon Resource Name (ARN) of the IP Set that this statement references. + +### NOT Statement + +A logical rule statement used to negate the results of another rule statement. You provide one `statement` within the `not_statement`. + +The `not_statement` block supports the following arguments: + +* `statement` - (Required) The statement to negate. You can use any statement that can be nested. See [Statement](#statement) above for details. + +### OR Statement + +A logical rule statement used to combine other rule statements with `OR` logic. You provide more than one `statement` within the `or_statement`. + +The `or_statement` block supports the following arguments: + +* `statement` - (Required) The statements to combine with `OR` logic. You can use any statements that can be nested. See [Statement](#statement) above for details. + +### Regex Pattern Set Reference Statement + +A rule statement used to search web request components for matches with regular expressions. To use this, create a `aws_wafv2_regex_pattern_set` that specifies the expressions that you want to detect, then use the `ARN` of that set in this statement. A web request matches the pattern set rule statement if the request component matches any of the patterns in the set. + +The `regex_pattern_set_reference_statement` block supports the following arguments: + +* `arn` - (Required) The Amazon Resource Name (ARN) of the Regex Pattern Set that this statement references. +* `field_to_match` - (Required) The part of a web request that you want AWS WAF to inspect. See [Field to Match](#field-to-match) below for details. +* `text_transformation` - (Required) Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See [Text Transformation](#text-transformation) below for details. + +### Size Constraint Statement + +A rule statement that uses a comparison operator to compare a number of bytes against the size of a request component. AWS WAFv2 inspects up to the first 8192 bytes (8 KB) of a request body, and when inspecting the request URI Path, the slash `/` in +the URI counts as one character. + +The `size_constraint_statement` block supports the following arguments: + +* `comparison_operator` - (Required) The operator to use to compare the request part to the size setting. Valid values include: `EQ`, `NE`, `LE`, `LT`, `GE`, or `GT`. +* `field_to_match` - (Optional) The part of a web request that you want AWS WAF to inspect. See [Field to Match](#field-to-match) below for details. +* `size` - (Required) The size, in bytes, to compare to the request part, after any transformations. Valid values are integers between 0 and 21474836480, inclusive. +* `text_transformation` - (Required) Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See [Text Transformation](#text-transformation) below for details. + +### SQL Injection Match Statement + +An SQL injection match condition identifies the part of web requests, such as the URI or the query string, that you want AWS WAF to inspect. Later in the process, when you create a web ACL, you specify whether to allow or block requests that appear to contain malicious SQL code. + +The `sqli_match_statement` block supports the following arguments: + +* `field_to_match` - (Required) The part of a web request that you want AWS WAF to inspect. See [Field to Match](#field-to-match) below for details. +* `text_transformation` - (Required) Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See [Text Transformation](#text-transformation) below for details. + +### XSS Match Statement + +The XSS match statement provides the location in requests that you want AWS WAF to search and text transformations to use on the search area before AWS WAF searches for character sequences that are likely to be malicious strings. + +The `xss_match_statement` block supports the following arguments: + +* `field_to_match` - (Required) The part of a web request that you want AWS WAF to inspect. See [Field to Match](#field-to-match) below for details. +* `text_transformation` - (Required) Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See [Text Transformation](#text-transformation) below for details. + +### Field to Match + +The part of a web request that you want AWS WAF to inspect. Include the single `field_to_match` type that you want to inspect, with additional specifications as needed, according to the type. You specify a single request component in `field_to_match` for each rule statement that requires it. To inspect more than one component of a web request, create a separate rule statement for each component. See the [documentation](https://docs.aws.amazon.com/waf/latest/developerguide/waf-rule-statement-fields.html#waf-rule-statement-request-component) for more details. + +The `field_to_match` block supports the following arguments: + +~> **NOTE**: An empty configuration block `{}` should be used when specifying `all_query_arguments`, `body`, `method`, or `query_string` attributes + +* `all_query_arguments` - (Optional) Inspect all query arguments. +* `body` - (Optional) Inspect the request body, which immediately follows the request headers. +* `method` - (Optional) Inspect the HTTP method. The method indicates the type of operation that the request is asking the origin to perform. +* `query_string` - (Optional) Inspect the query string. This is the part of a URL that appears after a `?` character, if any. +* `single_header` - (Optional) Inspect a single header. See [Single Header](#single-header) below for details. +* `single_query_argument` - (Optional) Inspect a single query argument. See [Single Query Argument](#single-query-argument) below for details. +* `uri_path` - (Optional) Inspect the request URI path. This is the part of a web request that identifies a resource, for example, `/images/daily-ad.jpg`. + +### Single Header + +Inspect a single header. Provide the name of the header to inspect, for example, `User-Agent` or `Referer` (provided as lowercase strings). + +The `single_header` block supports the following arguments: + +* `name` - (Optional) The name of the query header to inspect. This setting must be provided as lower case characters. + +### Single Query Argument + +Inspect a single query argument. Provide the name of the query argument to inspect, such as `UserName` or `SalesRegion` (provided as lowercase strings). + +The `single_query_argument` block supports the following arguments: + +* `name` - (Optional) The name of the query header to inspect. This setting must be provided as lower case characters. + +### Text Transformation + +The `text_transformation` block supports the following arguments: + +* `priority` - (Required) The relative processing order for multiple transformations that are defined for a rule statement. AWS WAF processes all transformations, from lowest priority to highest, before inspecting the transformed content. +* `type` - (Required) The transformation to apply, you can specify the following types: `NONE`, `COMPRESS_WHITE_SPACE`, `HTML_ENTITY_DECODE`, `LOWERCASE`, `CMD_LINE`, `URL_DECODE`. See the [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_TextTransformation.html) for more details. + +### Visibility Configuration + +The `visibility_config` block supports the following arguments: + +* `cloudwatch_metrics_enabled` - (Required) A boolean indicating whether the associated resource sends metrics to CloudWatch. For the list of available metrics, see [AWS WAF Metrics](https://docs.aws.amazon.com/waf/latest/developerguide/monitoring-cloudwatch.html#waf-metrics). +* `metric_name` - (Required, Forces new resource) A friendly name of the CloudWatch metric. The name can contain only alphanumeric characters (A-Z, a-z, 0-9) hyphen(-) and underscore (_), with length from one to 128 characters. It can't contain whitespace or metric names reserved for AWS WAF, for example `All` and `Default_Action`. +* `sampled_requests_enabled` - (Required) A boolean indicating whether AWS WAF should store a sampling of the web requests that match the rules. You can view the sampled requests through the AWS WAF console. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The ID of the WAF rule group. +* `arn` - The ARN of the WAF rule group. + +## Import + +WAFv2 Rule Group can be imported using `ID/name/scope` e.g. + +``` +$ terraform import aws_wafv2_rule_group.example a1b2c3d4-d5f6-7777-8888-9999aaaabbbbcccc/example/REGIONAL +``` diff --git a/website/docs/r/wafv2_web_acl.html.markdown b/website/docs/r/wafv2_web_acl.html.markdown new file mode 100644 index 00000000000..9a34bea9438 --- /dev/null +++ b/website/docs/r/wafv2_web_acl.html.markdown @@ -0,0 +1,519 @@ +--- +subcategory: "WAFv2" +layout: "aws" +page_title: "AWS: aws_wafv2_web_acl" +description: |- + Creates a WAFv2 Web ACL resource. +--- + +# Resource: aws_wafv2_web_acl + +Creates a WAFv2 Web ACL resource. + +## Example Usage + +This resource is based on `aws_wafv2_rule_group`, check the documentation of the `aws_wafv2_rule_group` resource to see examples of the various available statements. + + +### Managed Rule + +```hcl +resource "aws_wafv2_web_acl" "example" { + name = "managed-rule-example" + description = "Example of a managed rule." + scope = "REGIONAL" + + default_action { + allow {} + } + + rule { + name = "rule-1" + priority = 1 + + override_action { + count {} + } + + statement { + managed_rule_group_statement { + name = "AWSManagedRulesCommonRuleSet" + vendor_name = "AWS" + + excluded_rule { + name = "SizeRestrictions_QUERYSTRING" + } + + excluded_rule { + name = "NoUserAgent_HEADER" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + tags = { + Tag1 = "Value1" + Tag2 = "Value2" + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +``` + +### Rate Based + +```hcl +resource "aws_wafv2_web_acl" "example" { + name = "rate-based-example" + description = "Example of a rate based statement." + scope = "REGIONAL" + + default_action { + block {} + } + + rule { + name = "rule-1" + priority = 1 + + action { + count {} + } + + statement { + rate_based_statement { + limit = 10000 + aggregate_key_type = "IP" + + scope_down_statement { + geo_match_statement { + country_codes = ["US", "NL"] + } + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + tags = { + Tag1 = "Value1" + Tag2 = "Value2" + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +``` + +### Rule Group Reference + +```hcl +resource "aws_wafv2_rule_group" "example" { + capacity = 10 + name = "example-rule-group" + scope = "REGIONAL" + + rule { + name = "rule-1" + priority = 1 + + action { + count {} + } + + statement { + geo_match_statement { + country_codes = ["NL"] + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + rule { + name = "rule-to-exclude-a" + priority = 10 + + action { + allow {} + } + + statement { + geo_match_statement { + country_codes = ["US"] + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + rule { + name = "rule-to-exclude-b" + priority = 15 + + action { + allow {} + } + + statement { + geo_match_statement { + country_codes = ["GB"] + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} + +resource "aws_wafv2_web_acl" "test" { + name = "rule-group-example" + scope = "REGIONAL" + + default_action { + block {} + } + + rule { + name = "rule-1" + priority = 1 + + override_action { + count {} + } + + statement { + rule_group_reference_statement { + arn = aws_wafv2_rule_group.example.arn + + excluded_rule { + name = "rule-to-exclude-b" + } + + excluded_rule { + name = "rule-to-exclude-a" + } + } + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-rule-metric-name" + sampled_requests_enabled = false + } + } + + tags = { + Tag1 = "Value1" + Tag2 = "Value2" + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `default_action` - (Required) The action to perform if none of the `rules` contained in the WebACL match. See [Default Action](#default-action) below for details. +* `description` - (Optional) A friendly description of the WebACL. +* `name` - (Required) A friendly name of the WebACL. +* `rule` - (Optional) The rule blocks used to identify the web requests that you want to `allow`, `block`, or `count`. See [Rules](#rules) below for details. +* `scope` - (Required) Specifies whether this is for an AWS CloudFront distribution or for a regional application. Valid values are `CLOUDFRONT` or `REGIONAL`. To work with CloudFront, you must also specify the region `us-east-1` (N. Virginia) on the AWS provider. +* `tags` - (Optional) An array of key:value pairs to associate with the resource. +* `visibility_config` - (Required) Defines and enables Amazon CloudWatch metrics and web request sample collection. See [Visibility Configuration](#visibility-configuration) below for details. + +### Default Action + +The `default_action` block supports the following arguments: + +~> **NOTE**: One of `allow` or `block`, expressed as an empty configuration block `{}`, is required when specifying a `default_action` + +* `allow` - (Optional) Specifies that AWS WAF should allow requests by default. +* `block` - (Optional) Specifies that AWS WAF should block requests by default. + +### Rules + +~> **NOTE**: One of `action` or `override_action` is required when specifying a rule + +Each `rule` supports the following arguments: + +* `action` - (Optional) The action that AWS WAF should take on a web request when it matches the rule's statement. This is used only for rules whose **statements do not reference a rule group**. See [Action](#action) below for details. +* `name` - (Required) A friendly name of the rule. +* `override_action` - (Optional) The override action to apply to the rules in a rule group. Used only for rule **statements that reference a rule group**, like `rule_group_reference_statement` and `managed_rule_group_statement`. See [Override Action](#override-action) below for details. +* `priority` - (Required) If you define more than one Rule in a WebACL, AWS WAF evaluates each request against the `rules` in order based on the value of `priority`. AWS WAF processes rules with lower priority first. +* `statement` - (Required) The AWS WAF processing statement for the rule, for example `byte_match_statement` or `geo_match_statement`. See [Statement](#statement) below for details. +* `visibility_config` - (Required) Defines and enables Amazon CloudWatch metrics and web request sample collection. See [Visibility Configuration](#visibility-configuration) below for details. + +### Action + +The `action` block supports the following arguments: + +~> **NOTE**: One of `allow`, `block`, or `count`, expressed as an empty configuration block `{}`, is required when specifying an `action` + +* `allow` - (Optional) Instructs AWS WAF to allow the web request. Configure as an empty block `{}`. +* `block` - (Optional) Instructs AWS WAF to block the web request. Configure as an empty block `{}`. +* `count` - (Optional) Instructs AWS WAF to count the web request and allow it. Configure as an empty block `{}`. + +### Override Action + +The `override_action` block supports the following arguments: + +~> **NOTE**: One of `count` or `none`, expressed as an empty configuration block `{}`, is required when specifying an `override_action` + +* `count` - (Optional) Override the rule action setting to count (i.e. only count matches). Configured as an empty block `{}`. +* `none` - (Optional) Don't override the rule action setting. Configured as an empty block `{}`. + +### Statement + +The processing guidance for a Rule, used by AWS WAF to determine whether a web request matches the rule. See the [documentation](https://docs.aws.amazon.com/waf/latest/developerguide/waf-rule-statements-list.html) for more information. + +-> **NOTE:** Although the `statement` block is recursive, currently only 3 levels are supported. + +The `statement` block supports the following arguments: + +* `and_statement` - (Optional) A logical rule statement used to combine other rule statements with AND logic. See [AND Statement](#and-statement) below for details. +* `byte_match_statement` - (Optional) A rule statement that defines a string match search for AWS WAF to apply to web requests. See [Byte Match Statement](#byte-match-statement) below for details. +* `geo_match_statement` - (Optional) A rule statement used to identify web requests based on country of origin. See [GEO Match Statement](#geo-match-statement) below for details. +* `ip_set_reference_statement` - (Optional) A rule statement used to detect web requests coming from particular IP addresses or address ranges. See [IP Set Reference Statement](#ip-set-reference-statement) below for details. +* `managed_rule_group_statement` - (Optional) A rule statement used to run the rules that are defined in a managed rule group. This statement can not be nested. See [Managed Rule Group Statement](#managed-rule-group-statement) below for details. +* `not_statement` - (Optional) A logical rule statement used to negate the results of another rule statement. See [NOT Statement](#not-statement) below for details. +* `or_statement` - (Optional) A logical rule statement used to combine other rule statements with OR logic. See [OR Statement](#or-statement) below for details. +* `rate_based_statement` - (Optional) A rate-based rule tracks the rate of requests for each originating `IP address`, and triggers the rule action when the rate exceeds a limit that you specify on the number of requests in any `5-minute` time span. This statement can not be nested. See [Rate Based Statement](#rate-based-statement) below for details. +* `regex_pattern_set_reference_statement` - (Optional) A rule statement used to search web request components for matches with regular expressions. See [Regex Pattern Set Reference Statement](#regex-pattern-set-reference-statement) below for details. +* `rule_group_reference_statement` - (Optional) A rule statement used to run the rules that are defined in an WAFv2 Rule Group. See [Rule Group Reference Statement](#rule-group-reference-statement) below for details. +* `size_constraint_statement` - (Optional) A rule statement that compares a number of bytes against the size of a request component, using a comparison operator, such as greater than (>) or less than (<). See [Size Constraint Statement](#size-constraint-statement) below for more details. +* `sqli_match_statement` - (Optional) An SQL injection match condition identifies the part of web requests, such as the URI or the query string, that you want AWS WAF to inspect. See [SQL Injection Match Statement](#sql-injection-match-statement) below for details. +* `xss_match_statement` - (Optional) A rule statement that defines a cross-site scripting (XSS) match search for AWS WAF to apply to web requests. See [XSS Match Statement](#xss-match-statement) below for details. + +### AND Statement + +A logical rule statement used to combine other rule statements with `AND` logic. You provide more than one `statement` within the `and_statement`. + +The `and_statement` block supports the following arguments: + +* `statement` - (Required) The statements to combine with `AND` logic. You can use any statements that can be nested. See [Statement](#statement) above for details. + +### Byte Match Statement + +The byte match statement provides the bytes to search for, the location in requests that you want AWS WAF to search, and other settings. The bytes to search for are typically a string that corresponds with ASCII characters. + +The `byte_match_statement` block supports the following arguments: + +* `field_to_match` - (Optional) The part of a web request that you want AWS WAF to inspect. See [Field to Match](#field-to-match) below for details. +* `positional_constraint` - (Required) The area within the portion of a web request that you want AWS WAF to search for `search_string`. Valid values include the following: `EXACTLY`, `STARTS_WITH`, `ENDS_WITH`, `CONTAINS`, `CONTAINS_WORD`. See the AWS [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_ByteMatchStatement.html) for more information. +* `search_string` - (Required) A string value that you want AWS WAF to search for. AWS WAF searches only in the part of web requests that you designate for inspection in `field_to_match`. The maximum length of the value is 50 bytes. +* `text_transformation` - (Required) Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See [Text Transformation](#text-transformation) below for details. + + +### GEO Match Statement + +The `geo_match_statement` block supports the following arguments: + +* `country_codes` - (Required) An array of two-character country codes, for example, [ "US", "CN" ], from the alpha-2 country ISO codes of the `ISO 3166` international standard. See the [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_GeoMatchStatement.html) for valid values. + +### IP Set Reference Statement + +A rule statement used to detect web requests coming from particular IP addresses or address ranges. To use this, create an `aws_wafv2_ip_set` that specifies the addresses you want to detect, then use the `ARN` of that set in this statement. + +The `ip_set_reference_statement` block supports the following arguments: + +* `arn` - (Required) The Amazon Resource Name (ARN) of the IP Set that this statement references. + +### Managed Rule Group Statement + +A rule statement used to run the rules that are defined in a managed rule group. + +You can't nest a `managed_rule_group_statement`, for example for use inside a `not_statement` or `or_statement`. It can only be referenced as a `top-level` statement within a `rule`. + +The `managed_rule_group_statement` block supports the following arguments: + +* `excluded_rule` - (Optional) The `rules` whose actions are set to `COUNT` by the web ACL, regardless of the action that is set on the rule. See [Excluded Rule](#excluded-rule) below for details. +* `name` - (Required) The name of the managed rule group. +* `vendor_name` - (Required) The name of the managed rule group vendor. + +### NOT Statement + +A logical rule statement used to negate the results of another rule statement. You provide one `statement` within the `not_statement`. + +The `not_statement` block supports the following arguments: + +* `statement` - (Required) The statement to negate. You can use any statement that can be nested. See [Statement](#statement) above for details. + +### OR Statement + +A logical rule statement used to combine other rule statements with `OR` logic. You provide more than one `statement` within the `or_statement`. + +The `or_statement` block supports the following arguments: + +* `statement` - (Required) The statements to combine with `OR` logic. You can use any statements that can be nested. See [Statement](#statement) above for details. + +### Rate Based Statement + +A rate-based rule tracks the rate of requests for each originating IP address, and triggers the rule action when the rate exceeds a limit that you specify on the number of requests in any 5-minute time span. You can use this to put a temporary block on requests from an IP address that is sending excessive requests. See the [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_RateBasedStatement.html) for more information. + +You can't nest a `rate_based_statement`, for example for use inside a `not_statement` or `or_statement`. It can only be referenced as a `top-level` statement within a `rule`. + +The `rate_based_statement` block supports the following arguments: + +* `aggregate_key_type` - (Optional) Setting that indicates how to aggregate the request counts. Currently the only supported value is `IP` which is set as the default. +* `limit` - (Required) The limit on requests per 5-minute period for a single originating IP address. +* `scope_down_statement` - (Optional) An optional nested statement that narrows the scope of the rate-based statement to matching web requests. This can be any nestable statement, and you can nest statements at any level below this scope-down statement. See [Statement](#statement) above for details. + +### Regex Pattern Set Reference Statement + +A rule statement used to search web request components for matches with regular expressions. To use this, create a `aws_wafv2_regex_pattern_set` that specifies the expressions that you want to detect, then use the `ARN` of that set in this statement. A web request matches the pattern set rule statement if the request component matches any of the patterns in the set. + +The `regex_pattern_set_reference_statement` block supports the following arguments: + +* `arn` - (Required) The Amazon Resource Name (ARN) of the Regex Pattern Set that this statement references. + +### Rule Group Reference Statement + +A rule statement used to run the rules that are defined in an WAFv2 Rule Group or `aws_wafv2_rule_group` resource. + +You can't nest a `rule_group_reference_statement`, for example for use inside a `not_statement` or `or_statement`. It can only be referenced as a `top-level` statement within a `rule`. + +The `rule_group_reference_statement` block supports the following arguments: + +* `arn` - (Required) The Amazon Resource Name (ARN) of the `aws_wafv2_rule_group` resource. +* `excluded_rule` - (Optional) The `rules` whose actions are set to `COUNT` by the web ACL, regardless of the action that is set on the rule. See [Excluded Rule](#excluded-rule) below for details. + +### Size Constraint Statement + +A rule statement that uses a comparison operator to compare a number of bytes against the size of a request component. AWS WAFv2 inspects up to the first 8192 bytes (8 KB) of a request body, and when inspecting the request URI Path, the slash `/` in +the URI counts as one character. + +The `size_constraint_statement` block supports the following arguments: + +* `comparison_operator` - (Required) The operator to use to compare the request part to the size setting. Valid values include: `EQ`, `NE`, `LE`, `LT`, `GE`, or `GT`. +* `field_to_match` - (Optional) The part of a web request that you want AWS WAF to inspect. See [Field to Match](#field-to-match) below for details. +* `size` - (Required) The size, in bytes, to compare to the request part, after any transformations. Valid values are integers between 0 and 21474836480, inclusive. +* `text_transformation` - (Required) Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See [Text Transformation](#text-transformation) below for details. + +### SQL Injection Match Statement + +An SQL injection match condition identifies the part of web requests, such as the URI or the query string, that you want AWS WAF to inspect. Later in the process, when you create a web ACL, you specify whether to allow or block requests that appear to contain malicious SQL code. + +The `sqli_match_statement` block supports the following arguments: + +* `field_to_match` - (Optional) The part of a web request that you want AWS WAF to inspect. See [Field to Match](#field-to-match) below for details. +* `text_transformation` - (Required) Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See [Text Transformation](#text-transformation) below for details. + +### XSS Match Statement + +The XSS match statement provides the location in requests that you want AWS WAF to search and text transformations to use on the search area before AWS WAF searches for character sequences that are likely to be malicious strings. + +The `xss_match_statement` block supports the following arguments: + +* `field_to_match` - (Optional) The part of a web request that you want AWS WAF to inspect. See [Field to Match](#field-to-match) below for details. +* `text_transformation` - (Required) Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See [Text Transformation](#text-transformation) below for details. + +### Excluded Rule + +The `excluded_rule` block supports the following arguments: + +* `name` - (Required) The name of the rule to exclude. + +### Field to Match + +The part of a web request that you want AWS WAF to inspect. Include the single `field_to_match` type that you want to inspect, with additional specifications as needed, according to the type. You specify a single request component in `field_to_match` for each rule statement that requires it. To inspect more than one component of a web request, create a separate rule statement for each component. See the [documentation](https://docs.aws.amazon.com/waf/latest/developerguide/waf-rule-statement-fields.html#waf-rule-statement-request-component) for more details. + +The `field_to_match` block supports the following arguments: + +~> **NOTE**: An empty configuration block `{}` should be used when specifying `all_query_arguments`, `body`, `method`, or `query_string` attributes + +* `all_query_arguments` - (Optional) Inspect all query arguments. +* `body` - (Optional) Inspect the request body, which immediately follows the request headers. +* `method` - (Optional) Inspect the HTTP method. The method indicates the type of operation that the request is asking the origin to perform. +* `query_string` - (Optional) Inspect the query string. This is the part of a URL that appears after a `?` character, if any. +* `single_header` - (Optional) Inspect a single header. See [Single Header](#single-header) below for details. +* `single_query_argument` - (Optional) Inspect a single query argument. See [Single Query Argument](#single-query-argument) below for details. +* `uri_path` - (Optional) Inspect the request URI path. This is the part of a web request that identifies a resource, for example, `/images/daily-ad.jpg`. + +### Single Header + +Inspect a single header. Provide the name of the header to inspect, for example, `User-Agent` or `Referer` (provided as lowercase strings). + +The `single_header` block supports the following arguments: + +* `name` - (Optional) The name of the query header to inspect. This setting must be provided as lower case characters. + +### Single Query Argument + +Inspect a single query argument. Provide the name of the query argument to inspect, such as `UserName` or `SalesRegion` (provided as lowercase strings). + +The `single_query_argument` block supports the following arguments: + +* `name` - (Optional) The name of the query header to inspect. This setting must be provided as lower case characters. + +### Text Transformation + +The `text_transformation` block supports the following arguments: + +* `priority` - (Required) The relative processing order for multiple transformations that are defined for a rule statement. AWS WAF processes all transformations, from lowest priority to highest, before inspecting the transformed content. +* `type` - (Required) The transformation to apply, you can specify the following types: `NONE`, `COMPRESS_WHITE_SPACE`, `HTML_ENTITY_DECODE`, `LOWERCASE`, `CMD_LINE`, `URL_DECODE`. See the [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_TextTransformation.html) for more details. + +### Visibility Configuration + +The `visibility_config` block supports the following arguments: + +* `cloudwatch_metrics_enabled` - (Required) A boolean indicating whether the associated resource sends metrics to CloudWatch. For the list of available metrics, see [AWS WAF Metrics](https://docs.aws.amazon.com/waf/latest/developerguide/monitoring-cloudwatch.html#waf-metrics). +* `metric_name` - (Required) A friendly name of the CloudWatch metric. The name can contain only alphanumeric characters (A-Z, a-z, 0-9) hyphen(-) and underscore (\_), with length from one to 128 characters. It can't contain whitespace or metric names reserved for AWS WAF, for example `All` and `Default_Action`. +* `sampled_requests_enabled` - (Required) A boolean indicating whether AWS WAF should store a sampling of the web requests that match the rules. You can view the sampled requests through the AWS WAF console. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `arn` - The ARN of the WAF WebACL. +* `capacity` - The web ACL capacity units (WCUs) currently being used by this web ACL. +* `id` - The ID of the WAF WebACL. + +## Import + +WAFv2 Web ACLs can be imported using `ID/Name/Scope` e.g. + +``` +$ terraform import aws_wafv2_web_acl.example a1b2c3d4-d5f6-7777-8888-9999aaaabbbbcccc/example/REGIONAL +``` diff --git a/website/docs/r/wafv2_web_acl_association.html.markdown b/website/docs/r/wafv2_web_acl_association.html.markdown new file mode 100644 index 00000000000..b589d9ea2ac --- /dev/null +++ b/website/docs/r/wafv2_web_acl_association.html.markdown @@ -0,0 +1,86 @@ +--- +subcategory: "WAFv2" +layout: "aws" +page_title: "AWS: aws_wafv2_web_acl_association" +description: |- + Creates a WAFv2 Web ACL Association. +--- + +# Resource: aws_wafv2_web_acl_association + +Creates a WAFv2 Web ACL Association. + +## Example Usage + +```hcl +resource "aws_api_gateway_stage" "example" { + stage_name = "test" + rest_api_id = aws_api_gateway_rest_api.example.id + deployment_id = aws_api_gateway_deployment.example.id +} + +resource "aws_api_gateway_rest_api" "example" { + name = "web-acl-association-example" +} + +resource "aws_api_gateway_deployment" "example" { + rest_api_id = aws_api_gateway_rest_api.example.id + depends_on = [aws_api_gateway_integration.example] +} + +resource "aws_api_gateway_integration" "example" { + rest_api_id = aws_api_gateway_rest_api.example.id + resource_id = aws_api_gateway_resource.example.id + http_method = aws_api_gateway_method.example.http_method + type = "MOCK" +} + +resource "aws_api_gateway_resource" "example" { + rest_api_id = aws_api_gateway_rest_api.example.id + parent_id = aws_api_gateway_rest_api.example.root_resource_id + path_part = "mytestresource" +} + +resource "aws_api_gateway_method" "example" { + rest_api_id = aws_api_gateway_rest_api.example.id + resource_id = aws_api_gateway_resource.example.id + http_method = "GET" + authorization = "NONE" +} + +resource "aws_wafv2_web_acl" "example" { + name = "web-acl-association-example" + scope = "REGIONAL" + + default_action { + allow {} + } + + visibility_config { + cloudwatch_metrics_enabled = false + metric_name = "friendly-metric-name" + sampled_requests_enabled = false + } +} + +resource "aws_wafv2_web_acl_association" "example" { + resource_arn = aws_api_gateway_stage.example.arn + web_acl_arn = aws_wafv2_web_acl.example.arn +} +``` + + +## Argument Reference + +The following arguments are supported: + +* `resource_arn` - (Required) The Amazon Resource Name (ARN) of the resource to associate with the web ACL. This must be an ARN of an Application Load Balancer or an Amazon API Gateway stage. +* `web_acl_arn` - (Required) The Amazon Resource Name (ARN) of the Web ACL that you want to associate with the resource. + +## Import + +WAFv2 Web ACL Association can be imported using `WEB_ACL_ARN,RESOURCE_ARN` e.g. + +``` +$ terraform import aws_wafv2_web_acl_association.example arn:aws:wafv2:...7ce849ea,arn:aws:apigateway:...ages/name +``` diff --git a/website/docs/r/wafv2_web_acl_logging_configuration.html.markdown b/website/docs/r/wafv2_web_acl_logging_configuration.html.markdown new file mode 100644 index 00000000000..46dd3c089e9 --- /dev/null +++ b/website/docs/r/wafv2_web_acl_logging_configuration.html.markdown @@ -0,0 +1,76 @@ +--- +subcategory: "WAFv2" +layout: "aws" +page_title: "AWS: aws_wafv2_web_acl_logging_configuration" +description: |- + Creates a WAFv2 Web ACL Logging Configuration resource. +--- + +# Resource: aws_wafv2_web_acl_logging_configuration + +Creates a WAFv2 Web ACL Logging Configuration resource. + +-> **Note:** To start logging from a WAFv2 Web ACL, an Amazon Kinesis Data Firehose (e.g. [`aws_kinesis_firehose_delivery_stream` resource](/docs/providers/aws/r/kinesis_firehose_delivery_stream.html) must also be created with a PUT source (not a stream) and in the region that you are operating. +If you are capturing logs for Amazon CloudFront, always create the firehose in US East (N. Virginia). +Be sure to give the data firehose a name that starts with the prefix `aws-waf-logs-`. + +## Example Usage + +```hcl +resource "aws_wafv2_web_acl_logging_configuration" "example" { + log_destination_configs = [aws_kinesis_firehose_delivery_stream.example.arn] + resource_arn = aws_wafv2_web_acl.example.arn + redacted_fields { + single_header { + name = "user-agent" + } + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `log_destination_configs` - (Required) The Amazon Kinesis Data Firehose Amazon Resource Name (ARNs) that you want to associate with the web ACL. Currently, only 1 ARN is supported. +* `resource_arn` - (Required) The Amazon Resource Name (ARN) of the web ACL that you want to associate with `log_destination_configs`. +* `redacted_fields` - (Optional) The parts of the request that you want to keep out of the logs. Up to 100 `redacted_fields` blocks are supported. + +The `redacted_fields` block supports the following arguments: + +* `all_query_arguments` - (Optional) Inspect all query arguments. +* `body` - (Optional) Inspect the request body, which immediately follows the request headers. +* `method` - (Optional) Inspect the HTTP method. The method indicates the type of operation that the request is asking the origin to perform. +* `query_string` - (Optional) Inspect the query string. This is the part of a URL that appears after a `?` character, if any. +* `single_header` - (Optional) Inspect a single header. See [Single Header](#single-header) below for details. +* `single_query_argument` - (Optional) Inspect a single query argument. See [Single Query Argument](#single-query-argument) below for details. +* `uri_path` - (Optional) Inspect the request URI path. This is the part of a web request that identifies a resource, for example, `/images/daily-ad.jpg`. + +### Single Header + +Inspect a single header. Provide the name of the header to inspect, for example, `User-Agent` or `Referer` (provided as lowercase strings). + +The `single_header` block supports the following arguments: + +* `name` - (Optional) The name of the query header to inspect. This setting must be provided as lower case characters. + +### Single Query Argument + +Inspect a single query argument. Provide the name of the query argument to inspect, such as `UserName` or `SalesRegion` (provided as lowercase strings). + +The `single_query_argument` block supports the following arguments: + +* `name` - (Optional) The name of the query header to inspect. This setting must be provided as lower case characters. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The Amazon Resource Name (ARN) of the WAFv2 Web ACL. + +## Import + +WAFv2 Web ACL Logging Configurations can be imported using the WAFv2 Web ACL ARN e.g. + +``` +$ terraform import aws_wafv2_web_acl_logging_configuration.example arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test-logs/a1b2c3d4-5678-90ab-cdef diff --git a/website/docs/r/worklink_fleet.html.markdown b/website/docs/r/worklink_fleet.html.markdown index 1ccf365e404..fbe1e718e79 100644 --- a/website/docs/r/worklink_fleet.html.markdown +++ b/website/docs/r/worklink_fleet.html.markdown @@ -25,9 +25,9 @@ resource "aws_worklink_fleet" "example" { name = "terraform-example" network { - vpc_id = "${aws_vpc.test.id}" - subnet_ids = ["${aws_subnet.test.*.id}"] - security_group_ids = ["${aws_security_group.test.id}"] + vpc_id = aws_vpc.test.id + subnet_ids = [aws_subnet.test.*.id] + security_group_ids = [aws_security_group.test.id] } } ``` @@ -36,11 +36,11 @@ Identity Provider Configuration Usage: ```hcl resource "aws_worklink_fleet" "test" { - name = "tf-worklink-fleet-%s" + name = "tf-worklink-fleet" identity_provider { type = "SAML" - saml_metadata = "${file("saml-metadata.xml")}" + saml_metadata = file("saml-metadata.xml") } } ``` diff --git a/website/docs/r/worklink_website_certificate_authority_association.html.markdown b/website/docs/r/worklink_website_certificate_authority_association.html.markdown index 70d88748116..faf157b5a7d 100644 --- a/website/docs/r/worklink_website_certificate_authority_association.html.markdown +++ b/website/docs/r/worklink_website_certificate_authority_association.html.markdown @@ -16,8 +16,8 @@ resource "aws_worklink_fleet" "example" { } resource "aws_worklink_website_certificate_authority_association" "test" { - fleet_arn = "${aws_worklink_fleet.test.arn}" - certificate = "${file("certificate.pem")}" + fleet_arn = aws_worklink_fleet.test.arn + certificate = file("certificate.pem") } ``` diff --git a/website/docs/r/workspaces_directory.html.markdown b/website/docs/r/workspaces_directory.html.markdown index b84efde9de6..be7c956af9d 100644 --- a/website/docs/r/workspaces_directory.html.markdown +++ b/website/docs/r/workspaces_directory.html.markdown @@ -18,13 +18,13 @@ resource "aws_vpc" "main" { } resource "aws_subnet" "private-a" { - vpc_id = "${aws_vpc.main.id}" + vpc_id = aws_vpc.main.id availability_zone = "us-east-1a" cidr_block = "10.0.0.0/24" } resource "aws_subnet" "private-b" { - vpc_id = "${aws_vpc.main.id}" + vpc_id = aws_vpc.main.id availability_zone = "us-east-1b" cidr_block = "10.0.1.0/24" } @@ -34,15 +34,15 @@ resource "aws_directory_service_directory" "main" { password = "#S1ncerely" size = "Small" vpc_settings { - vpc_id = "${aws_vpc.main.id}" - subnet_ids = ["${aws_subnet.private-a.id}", "${aws_subnet.private-b.id}"] + vpc_id = aws_vpc.main.id + subnet_ids = [aws_subnet.private-a.id, aws_subnet.private-b.id] } } resource "aws_workspaces_directory" "main" { - directory_id = "${aws_directory_service_directory.main.id}" + directory_id = aws_directory_service_directory.main.id - self_service_permissions = { + self_service_permissions { increase_volume_size = true rebuild_workspace = true } diff --git a/website/docs/r/workspaces_workspace.html.markdown b/website/docs/r/workspaces_workspace.html.markdown new file mode 100644 index 00000000000..c5081b73abd --- /dev/null +++ b/website/docs/r/workspaces_workspace.html.markdown @@ -0,0 +1,83 @@ +--- +subcategory: "WorkSpaces" +layout: "aws" +page_title: "AWS: aws_workspaces_workspace" +description: |- + Provides a workspaces in AWS Workspaces Service. +--- + +# Resource: aws_workspace + +Provides a workspace in [AWS Workspaces](https://docs.aws.amazon.com/workspaces/latest/adminguide/amazon-workspaces.html) Service + +~> **NOTE:** During deletion of an `aws_workspaces_workspace` resource, the service role `workspaces_DefaultRole` must be attached to the +policy `arn:aws:iam::aws:policy/AmazonWorkSpacesServiceAccess`, or it will leak the ENI that the Workspaces service creates for the Workspace. + +## Example Usage + +```hcl +data "aws_workspaces_bundle" "value_windows_10" { + bundle_id = "wsb-bh8rsxt14" # Value with Windows 10 (English) +} + +resource "aws_workspaces_workspace" "example" { + directory_id = aws_workspaces_directory.example.id + bundle_id = data.aws_workspaces_bundle.value_windows_10.id + user_name = "john.doe" + + root_volume_encryption_enabled = true + user_volume_encryption_enabled = true + volume_encryption_key = "alias/aws/workspaces" + + workspace_properties { + compute_type_name = "VALUE" + user_volume_size_gib = 10 + root_volume_size_gib = 80 + running_mode = "AUTO_STOP" + running_mode_auto_stop_timeout_in_minutes = 60 + } + + tags = { + Department = "IT" + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `directory_id` - (Required) The ID of the directory for the WorkSpace. +* `bundle_id` - (Required) The ID of the bundle for the WorkSpace. +* `user_name` – (Required) The user name of the user for the WorkSpace. This user name must exist in the directory for the WorkSpace. +* `root_volume_encryption_enabled` - (Optional) Indicates whether the data stored on the root volume is encrypted. +* `user_volume_encryption_enabled` – (Optional) Indicates whether the data stored on the user volume is encrypted. +* `volume_encryption_key` – (Optional) The symmetric AWS KMS customer master key (CMK) used to encrypt data stored on your WorkSpace. Amazon WorkSpaces does not support asymmetric CMKs. +* `tags` - (Optional) The tags for the WorkSpace. +* `workspace_properties` – (Optional) The WorkSpace properties. + +`workspace_properties` supports the following: + +* `compute_type_name` – (Optional) The compute type. For more information, see [Amazon WorkSpaces Bundles](http://aws.amazon.com/workspaces/details/#Amazon_WorkSpaces_Bundles). Valid values are `VALUE`, `STANDARD`, `PERFORMANCE`, `POWER`, `GRAPHICS`, `POWERPRO` and `GRAPHICSPRO`. +* `root_volume_size_gib` – (Optional) The size of the root volume. +* `running_mode` – (Optional) The running mode. For more information, see [Manage the WorkSpace Running Mode](https://docs.aws.amazon.com/workspaces/latest/adminguide/running-mode.html). Valid values are `AUTO_STOP` and `ALWAYS_ON`. +* `running_mode_auto_stop_timeout_in_minutes` – (Optional) The time after a user logs off when WorkSpaces are automatically stopped. Configured in 60-minute intervals. +* `user_volume_size_gib` – (Optional) The size of the user storage. + +## Attributes Reference + +In addition to all arguments above, the following attributes are exported: + +* `id` - The workspaces ID. +* `ip_address` - The IP address of the WorkSpace. +* `computer_name` - The name of the WorkSpace, as seen by the operating system. +* `state` - The operational state of the WorkSpace. + +## Import + +Workspaces can be imported using their ID, e.g. + +``` +$ terraform import aws_workspaces_workspace.example ws-9z9zmbkhv +``` +